diff --git a/.codedocs b/.codedocs deleted file mode 100644 index 8b902d7c3b5..00000000000 --- a/.codedocs +++ /dev/null @@ -1,1536 +0,0 @@ -# Doxyfile 1.8.3 - -# This file describes the settings to be used by the documentation system -# doxygen (www.doxygen.org) for a project. -# -# All text after a hash (#) is considered a comment and will be ignored. -# The format is: -# TAG = value [value, ...] -# For lists items can also be appended using: -# TAG += value [value, ...] -# Values that contain spaces should be placed between quotes (" "). - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- - -# This tag specifies the encoding used for all characters in the config file -# that follow. The default is UTF-8 which is also the encoding used for all -# text before the first occurrence of this tag. Doxygen uses libiconv (or the -# iconv built into libc) for the transcoding. See -# http://www.gnu.org/software/libiconv for the list of possible encodings. - -DOXYFILE_ENCODING = UTF-8 - -# The PROJECT_NAME tag is a single word (or sequence of words) that should -# identify the project. Note that if you do not use Doxywizard you need -# to put quotes around the project name if it contains spaces. - -PROJECT_NAME = OGRE - -# The PROJECT_NUMBER tag can be used to enter a project or revision number. -# This could be handy for archiving the generated documentation or -# if some version control system is used. - -PROJECT_NUMBER = master - -# Using the PROJECT_BRIEF tag one can provide an optional one line description -# for a project that appears at the top of each page and should give viewer -# a quick idea about the purpose of the project. Keep the description short. - -PROJECT_BRIEF = "Object-Oriented Graphics Rendering Engine" - -# With the PROJECT_LOGO tag one can specify an logo or icon that is -# included in the documentation. The maximum height of the logo should not -# exceed 55 pixels and the maximum width should not exceed 200 pixels. -# Doxygen will copy the logo to the output directory. - -PROJECT_LOGO = "Docs/ogre-logo.png" - -# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) -# base path where the generated documentation will be put. -# If a relative path is entered, it will be relative to the location -# where doxygen was started. If left blank the current directory will be used. - -OUTPUT_DIRECTORY = "build/api/" - -# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create -# 4096 sub-directories (in 2 levels) under the output directory of each output -# format and will distribute the generated files over these directories. -# Enabling this option can be useful when feeding doxygen a huge amount of -# source files, where putting all generated files in the same directory would -# otherwise cause performance problems for the file system. - -CREATE_SUBDIRS = NO - -# The OUTPUT_LANGUAGE tag is used to specify the language in which all -# documentation generated by doxygen is written. Doxygen will use this -# information to generate all constant output in the proper language. -# The default language is English, other supported languages are: -# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, -# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, -# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English -# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, -# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, -# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. - -OUTPUT_LANGUAGE = English - -# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will -# include brief member descriptions after the members that are listed in -# the file and class documentation (similar to JavaDoc). -# Set to NO to disable this. - -BRIEF_MEMBER_DESC = YES - -# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend -# the brief description of a member or function before the detailed description. -# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the -# brief descriptions will be completely suppressed. - -REPEAT_BRIEF = YES - -# This tag implements a quasi-intelligent brief description abbreviator -# that is used to form the text in various listings. Each string -# in this list, if found as the leading text of the brief description, will be -# stripped from the text and the result after processing the whole list, is -# used as the annotated text. Otherwise, the brief description is used as-is. -# If left blank, the following values are used ("$name" is automatically -# replaced with the name of the entity): "The $name class" "The $name widget" -# "The $name file" "is" "provides" "specifies" "contains" -# "represents" "a" "an" "the" - -ABBREVIATE_BRIEF = "The $name class " \ - "The $name widget " \ - "The $name file " \ - is \ - provides \ - specifies \ - contains \ - represents \ - a \ - an \ - the - -# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then -# Doxygen will generate a detailed section even if there is only a brief -# description. - -ALWAYS_DETAILED_SEC = YES - -# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all -# inherited members of a class in the documentation of that class as if those -# members were ordinary class members. Constructors, destructors and assignment -# operators of the base classes will not be shown. - -INLINE_INHERITED_MEMB = NO - -# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full -# path before files name in the file list and in the header files. If set -# to NO the shortest path that makes the file name unique will be used. - -FULL_PATH_NAMES = NO - -# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag -# can be used to strip a user-defined part of the path. Stripping is -# only done if one of the specified strings matches the left-hand part of -# the path. The tag can be used to show relative paths in the file list. -# If left blank the directory from which doxygen is run is used as the -# path to strip. Note that you specify absolute paths here, but also -# relative paths, which will be relative from the directory where doxygen is -# started. - -STRIP_FROM_PATH = - -# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of -# the path mentioned in the documentation of a class, which tells -# the reader which header file to include in order to use a class. -# If left blank only the name of the header file containing the class -# definition is used. Otherwise one should specify the include paths that -# are normally passed to the compiler using the -I flag. - -STRIP_FROM_INC_PATH = - -# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter -# (but less readable) file names. This can be useful if your file system -# doesn't support long names like on DOS, Mac, or CD-ROM. - -SHORT_NAMES = NO - -# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen -# will interpret the first line (until the first dot) of a JavaDoc-style -# comment as the brief description. If set to NO, the JavaDoc -# comments will behave just like regular Qt-style comments -# (thus requiring an explicit @brief command for a brief description.) - -JAVADOC_AUTOBRIEF = YES - -# If the QT_AUTOBRIEF tag is set to YES then Doxygen will -# interpret the first line (until the first dot) of a Qt-style -# comment as the brief description. If set to NO, the comments -# will behave just like regular Qt-style comments (thus requiring -# an explicit \brief command for a brief description.) - -QT_AUTOBRIEF = NO - -# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen -# treat a multi-line C++ special comment block (i.e. a block of //! or /// -# comments) as a brief description. This used to be the default behaviour. -# The new default is to treat a multi-line C++ comment block as a detailed -# description. Set this tag to YES if you prefer the old behaviour instead. - -MULTILINE_CPP_IS_BRIEF = NO - -# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented -# member inherits the documentation from any documented member that it -# re-implements. - -INHERIT_DOCS = YES - -# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce -# a new page for each member. If set to NO, the documentation of a member will -# be part of the file/class/namespace that contains it. - -SEPARATE_MEMBER_PAGES = NO - -# The TAB_SIZE tag can be used to set the number of spaces in a tab. -# Doxygen uses this value to replace tabs by spaces in code fragments. - -TAB_SIZE = 4 - -# This tag can be used to specify a number of aliases that acts -# as commands in the documentation. An alias has the form "name=value". -# For example adding "sideeffect=\par Side Effects:\n" will allow you to -# put the command \sideeffect (or @sideeffect) in the documentation, which -# will result in a user-defined paragraph with heading "Side Effects:". -# You can put \n's in the value part of an alias to insert newlines. - -ALIASES = ffp_rtss_only="@note Only has an effect with the fixed-function pipeline or the @ref rtss" -ALIASES += shaderparam="@note When using shader programs, you have to explicitely forward this property in the @ref Program-Parameter-Specification" - -# This tag can be used to specify a number of word-keyword mappings (TCL only). -# A mapping has the form "name=value". For example adding -# "class=itcl::class" will allow you to use the command class in the -# itcl::class meaning. - -TCL_SUBST = - -# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C -# sources only. Doxygen will then generate output that is more tailored for C. -# For instance, some of the names that are used will be different. The list -# of all members will be omitted, etc. - -OPTIMIZE_OUTPUT_FOR_C = NO - -# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java -# sources only. Doxygen will then generate output that is more tailored for -# Java. For instance, namespaces will be presented as packages, qualified -# scopes will look different, etc. - -OPTIMIZE_OUTPUT_JAVA = NO - -# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran -# sources only. Doxygen will then generate output that is more tailored for -# Fortran. - -OPTIMIZE_FOR_FORTRAN = NO - -# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL -# sources. Doxygen will then generate output that is tailored for -# VHDL. - -OPTIMIZE_OUTPUT_VHDL = NO - -# Doxygen selects the parser to use depending on the extension of the files it -# parses. With this tag you can assign which parser to use for a given -# extension. Doxygen has a built-in mapping, but you can override or extend it -# using this tag. The format is ext=language, where ext is a file extension, -# and language is one of the parsers supported by doxygen: IDL, Java, -# Javascript, CSharp, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, -# C++. For instance to make doxygen treat .inc files as Fortran files (default -# is PHP), and .f files as C (default is Fortran), use: inc=Fortran f=C. Note -# that for custom extensions you also need to set FILE_PATTERNS otherwise the -# files are not read by doxygen. - -EXTENSION_MAPPING = material=C++ compositor=C++ particle=C++ txt=Python glsl=C++ - -# If MARKDOWN_SUPPORT is enabled (the default) then doxygen pre-processes all -# comments according to the Markdown format, which allows for more readable -# documentation. See http://daringfireball.net/projects/markdown/ for details. -# The output of markdown processing is further processed by doxygen, so you -# can mix doxygen, HTML, and XML commands with Markdown formatting. -# Disable only in case of backward compatibilities issues. - -MARKDOWN_SUPPORT = YES - -# When enabled doxygen tries to link words that correspond to documented classes, -# or namespaces to their corresponding documentation. Such a link can be -# prevented in individual cases by by putting a % sign in front of the word or -# globally by setting AUTOLINK_SUPPORT to NO. - -AUTOLINK_SUPPORT = YES - -# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want -# to include (a tag file for) the STL sources as input, then you should -# set this tag to YES in order to let doxygen match functions declarations and -# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. -# func(std::string) {}). This also makes the inheritance and collaboration -# diagrams that involve STL classes more complete and accurate. - -BUILTIN_STL_SUPPORT = NO - -# If you use Microsoft's C++/CLI language, you should set this option to YES to -# enable parsing support. - -CPP_CLI_SUPPORT = NO - -# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. -# Doxygen will parse them like normal C++ but will assume all classes use public -# instead of private inheritance when no explicit protection keyword is present. - -SIP_SUPPORT = NO - -# For Microsoft's IDL there are propget and propput attributes to indicate -# getter and setter methods for a property. Setting this option to YES (the -# default) will make doxygen replace the get and set methods by a property in -# the documentation. This will only work if the methods are indeed getting or -# setting a simple type. If this is not the case, or you want to show the -# methods anyway, you should set this option to NO. - -IDL_PROPERTY_SUPPORT = YES - -# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC -# tag is set to YES, then doxygen will reuse the documentation of the first -# member in the group (if any) for the other members of the group. By default -# all members of a group must be documented explicitly. - -DISTRIBUTE_GROUP_DOC = NO - -# Set the SUBGROUPING tag to YES (the default) to allow class member groups of -# the same type (for instance a group of public functions) to be put as a -# subgroup of that type (e.g. under the Public Functions section). Set it to -# NO to prevent subgrouping. Alternatively, this can be done per class using -# the \nosubgrouping command. - -SUBGROUPING = YES - -# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and -# unions are shown inside the group in which they are included (e.g. using -# @ingroup) instead of on a separate page (for HTML and Man pages) or -# section (for LaTeX and RTF). - -INLINE_GROUPED_CLASSES = NO - -# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and -# unions with only public data fields will be shown inline in the documentation -# of the scope in which they are defined (i.e. file, namespace, or group -# documentation), provided this scope is documented. If set to NO (the default), -# structs, classes, and unions are shown on a separate page (for HTML and Man -# pages) or section (for LaTeX and RTF). - -INLINE_SIMPLE_STRUCTS = NO - -# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum -# is documented as struct, union, or enum with the name of the typedef. So -# typedef struct TypeS {} TypeT, will appear in the documentation as a struct -# with name TypeT. When disabled the typedef will appear as a member of a file, -# namespace, or class. And the struct will be named TypeS. This can typically -# be useful for C code in case the coding convention dictates that all compound -# types are typedef'ed and only the typedef is referenced, never the tag name. - -TYPEDEF_HIDES_STRUCT = NO - -# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This -# cache is used to resolve symbols given their name and scope. Since this can be -# an expensive process and often the same symbol appears multiple times in the -# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small -# doxygen will become slower. If the cache is too large, memory is wasted. The -# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range -# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 -# symbols. At the end of a run doxygen will report the cache usage and suggest -# the optimal cache size from a speed point of view. -# Minimum value: 0, maximum value: 9, default value: 0. - -LOOKUP_CACHE_SIZE = 1 - -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- - -# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in -# documentation are documented, even if no documentation was available. -# Private class members and static file members will be hidden unless -# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES - -EXTRACT_ALL = YES - -# If the EXTRACT_PRIVATE tag is set to YES all private members of a class -# will be included in the documentation. - -EXTRACT_PRIVATE = NO - -# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal -# scope will be included in the documentation. - -EXTRACT_PACKAGE = NO - -# If the EXTRACT_STATIC tag is set to YES all static members of a file -# will be included in the documentation. - -EXTRACT_STATIC = YES - -# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) -# defined locally in source files will be included in the documentation. -# If set to NO only classes defined in header files are included. - -EXTRACT_LOCAL_CLASSES = YES - -# This flag is only useful for Objective-C code. When set to YES local -# methods, which are defined in the implementation section but not in -# the interface are included in the documentation. -# If set to NO (the default) only methods in the interface are included. - -EXTRACT_LOCAL_METHODS = NO - -# If this flag is set to YES, the members of anonymous namespaces will be -# extracted and appear in the documentation as a namespace called -# 'anonymous_namespace{file}', where file will be replaced with the base -# name of the file that contains the anonymous namespace. By default -# anonymous namespaces are hidden. - -EXTRACT_ANON_NSPACES = NO - -# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all -# undocumented members of documented classes, files or namespaces. -# If set to NO (the default) these members will be included in the -# various overviews, but no documentation section is generated. -# This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_MEMBERS = NO - -# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all -# undocumented classes that are normally visible in the class hierarchy. -# If set to NO (the default) these classes will be included in the various -# overviews. This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_CLASSES = NO - -# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all -# friend (class|struct|union) declarations. -# If set to NO (the default) these declarations will be included in the -# documentation. - -HIDE_FRIEND_COMPOUNDS = YES - -# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any -# documentation blocks found inside the body of a function. -# If set to NO (the default) these blocks will be appended to the -# function's detailed documentation block. - -HIDE_IN_BODY_DOCS = NO - -# The INTERNAL_DOCS tag determines if documentation -# that is typed after a \internal command is included. If the tag is set -# to NO (the default) then the documentation will be excluded. -# Set it to YES to include the internal documentation. - -INTERNAL_DOCS = NO - -# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate -# file names in lower-case letters. If set to YES upper-case letters are also -# allowed. This is useful if you have classes or files whose names only differ -# in case and if your file system supports case sensitive file names. Windows -# and Mac users are advised to set this option to NO. - -CASE_SENSE_NAMES = NO - -# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen -# will show members with their full class and namespace scopes in the -# documentation. If set to YES the scope will be hidden. - -HIDE_SCOPE_NAMES = NO - -# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen -# will put a list of the files that are included by a file in the documentation -# of that file. - -SHOW_INCLUDE_FILES = YES - -# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen -# will list include files with double quotes in the documentation -# rather than with sharp brackets. - -FORCE_LOCAL_INCLUDES = NO - -# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] -# is inserted in the documentation for inline members. - -INLINE_INFO = YES - -# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen -# will sort the (detailed) documentation of file and class members -# alphabetically by member name. If set to NO the members will appear in -# declaration order. - -SORT_MEMBER_DOCS = NO - -# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the -# brief documentation of file, namespace and class members alphabetically -# by member name. If set to NO (the default) the members will appear in -# declaration order. - -SORT_BRIEF_DOCS = YES - -# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen -# will sort the (brief and detailed) documentation of class members so that -# constructors and destructors are listed first. If set to NO (the default) -# the constructors will appear in the respective orders defined by -# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. -# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO -# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. - -SORT_MEMBERS_CTORS_1ST = YES - -# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the -# hierarchy of group names into alphabetical order. If set to NO (the default) -# the group names will appear in their defined order. - -SORT_GROUP_NAMES = YES - -# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be -# sorted by fully-qualified names, including namespaces. If set to -# NO (the default), the class list will be sorted only by class name, -# not including the namespace part. -# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. -# Note: This option applies only to the class list, not to the -# alphabetical list. - -SORT_BY_SCOPE_NAME = YES - -# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to -# do proper type resolution of all parameters of a function it will reject a -# match between the prototype and the implementation of a member function even -# if there is only one candidate or it is obvious which candidate to choose -# by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen -# will still accept a match between prototype and implementation in such cases. - -STRICT_PROTO_MATCHING = NO - -# The GENERATE_TODOLIST tag can be used to enable (YES) or -# disable (NO) the todo list. This list is created by putting \todo -# commands in the documentation. - -GENERATE_TODOLIST = NO - -# The GENERATE_TESTLIST tag can be used to enable (YES) or -# disable (NO) the test list. This list is created by putting \test -# commands in the documentation. - -GENERATE_TESTLIST = YES - -# The GENERATE_BUGLIST tag can be used to enable (YES) or -# disable (NO) the bug list. This list is created by putting \bug -# commands in the documentation. - -GENERATE_BUGLIST = YES - -# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or -# disable (NO) the deprecated list. This list is created by putting -# \deprecated commands in the documentation. - -GENERATE_DEPRECATEDLIST= YES - -# The ENABLED_SECTIONS tag can be used to enable conditional -# documentation sections, marked by \if section-label ... \endif -# and \cond section-label ... \endcond blocks. - -ENABLED_SECTIONS = - -# The MAX_INITIALIZER_LINES tag determines the maximum number of lines -# the initial value of a variable or macro consists of for it to appear in -# the documentation. If the initializer consists of more lines than specified -# here it will be hidden. Use a value of 0 to hide initializers completely. -# The appearance of the initializer of individual variables and macros in the -# documentation can be controlled using \showinitializer or \hideinitializer -# command in the documentation regardless of this setting. - -MAX_INITIALIZER_LINES = 30 - -# Set the SHOW_USED_FILES tag to NO to disable the list of files generated -# at the bottom of the documentation of classes and structs. If set to YES the -# list will mention the files that were used to generate the documentation. - -SHOW_USED_FILES = YES - -# Set the SHOW_FILES tag to NO to disable the generation of the Files page. -# This will remove the Files entry from the Quick Index and from the -# Folder Tree View (if specified). The default is YES. - -SHOW_FILES = YES - -# Set the SHOW_NAMESPACES tag to NO to disable the generation of the -# Namespaces page. -# This will remove the Namespaces entry from the Quick Index -# and from the Folder Tree View (if specified). The default is YES. - -SHOW_NAMESPACES = YES - -# The FILE_VERSION_FILTER tag can be used to specify a program or script that -# doxygen should invoke to get the current version for each file (typically from -# the version control system). Doxygen will invoke the program by executing (via -# popen()) the command , where is the value of -# the FILE_VERSION_FILTER tag, and is the name of an input file -# provided by doxygen. Whatever the program writes to standard output -# is used as the file version. See the manual for examples. - -FILE_VERSION_FILTER = - -# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed -# by doxygen. The layout file controls the global structure of the generated -# output files in an output format independent way. To create the layout file -# that represents doxygen's defaults, run doxygen with the -l option. -# You can optionally specify a file name after the option, if omitted -# DoxygenLayout.xml will be used as the name of the layout file. - -LAYOUT_FILE = - -# The CITE_BIB_FILES tag can be used to specify one or more bib files -# containing the references data. This must be a list of .bib files. The -# .bib extension is automatically appended if omitted. Using this command -# requires the bibtex tool to be installed. See also -# http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style -# of the bibliography can be controlled using LATEX_BIB_STYLE. To use this -# feature you need bibtex and perl available in the search path. Do not use -# file names with spaces, bibtex cannot handle them. - -CITE_BIB_FILES = "Docs/src/bibliography.bib" - -# The LATEX_BIB_STYLE tag can be used to specify the style to use for the -# bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See -# http://en.wikipedia.org/wiki/BibTeX for more info. - -LATEX_BIB_STYLE = plain - -#--------------------------------------------------------------------------- -# configuration options related to warning and progress messages -#--------------------------------------------------------------------------- - -# The QUIET tag can be used to turn on/off the messages that are generated -# by doxygen. Possible values are YES and NO. If left blank NO is used. - -QUIET = NO - -# The WARNINGS tag can be used to turn on/off the warning messages that are -# generated by doxygen. Possible values are YES and NO. If left blank -# NO is used. - -WARNINGS = YES - -# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings -# for undocumented members. If EXTRACT_ALL is set to YES then this flag will -# automatically be disabled. - -WARN_IF_UNDOCUMENTED = YES - -# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for -# potential errors in the documentation, such as not documenting some -# parameters in a documented function, or documenting parameters that -# don't exist or using markup commands wrongly. - -WARN_IF_DOC_ERROR = YES - -# The WARN_NO_PARAMDOC option can be enabled to get warnings for -# functions that are documented, but have no documentation for their parameters -# or return value. If set to NO (the default) doxygen will only warn about -# wrong or incomplete parameter documentation, but not about the absence of -# documentation. - -WARN_NO_PARAMDOC = NO - -# The WARN_FORMAT tag determines the format of the warning messages that -# doxygen can produce. The string should contain the $file, $line, and $text -# tags, which will be replaced by the file and line number from which the -# warning originated and the warning text. Optionally the format may contain -# $version, which will be replaced by the version of the file (if it could -# be obtained via FILE_VERSION_FILTER) - -WARN_FORMAT = "$file:$line: $text" - -# The WARN_LOGFILE tag can be used to specify a file to which warning -# and error messages should be written. If left blank the output is written -# to stderr. - -WARN_LOGFILE = "build/doxygen_warnings.log" - -#--------------------------------------------------------------------------- -# configuration options related to the input files -#--------------------------------------------------------------------------- - -# The INPUT tag can be used to specify the files and/or directories that contain -# documented source files. You may enter file names like "myfile.cpp" or -# directories like "/usr/src/myproject". Separate the files or directories -# with spaces. - -INPUT = OgreMain/include \ - Components/Bites/include \ - Components/MeshLodGenerator/include \ - Components/Overlay/include \ - Components/Paging/include \ - Components/Property/include \ - Components/RTShaderSystem/include \ - Components/Terrain/include \ - Components/Volume/include \ - PlugIns \ - PlugIns/PCZSceneManager/docs/readme.md \ - PlugIns/DotScene/README.md \ - RenderSystems \ - Docs/src/apimainpage.md \ - Docs/src/manual.md \ - Docs/src/ogre-shadows.md \ - Docs/src/scripts.md \ - Docs/src/material-scripts.md \ - Docs/src/high-level-programs.md \ - Docs/src/particle-scripts.md \ - Docs/src/hardware-buffers.md \ - Docs/src/rtss.md \ - Docs/src/resourcemanagement.md \ - BuildingOgre.md \ - Docs/src/tutorials/deferred.md \ - Docs/src/tutorials/external_texture.md \ - Docs/src/tutorials/manualmesh.md \ - Docs/src/tutorials/meshlod.md \ - Docs/src/tutorials/numpy.md \ - Docs/src/tutorials/profiler.md \ - Docs/src/tutorials/background-resource.md \ - Docs/src/tutorials/reversed-depth.md \ - Docs/src/tutorials/static-geometry.md \ - Docs/src/tutorials/setup.md \ - Docs/src/tutorials/trays.md \ - Docs/src/tutorials/tutorials.md \ - Docs/src/tutorials/volume.md \ - Docs/src/tutorials/basictutorials/basictutorial1.md \ - Docs/src/tutorials/basictutorials/basictutorial2.md \ - Docs/src/tutorials/basictutorials/basictutorial3.md - -# This tag can be used to specify the character encoding of the source files -# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is -# also the default input encoding. Doxygen uses libiconv (or the iconv built -# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for -# the list of possible encodings. - -INPUT_ENCODING = UTF-8 - -# If the value of the INPUT tag contains directories, you can use the -# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp -# and *.h) to filter out the source-files in the directories. If left -# blank the following patterns are tested: -# *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh -# *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py -# *.f90 *.f *.for *.vhd *.vhdl - -FILE_PATTERNS = Ogre*.h - -# The RECURSIVE tag can be used to turn specify whether or not subdirectories -# should be searched for input files as well. Possible values are YES and NO. -# If left blank NO is used. - -RECURSIVE = YES - -# The EXCLUDE tag can be used to specify files and/or directories that should be -# excluded from the INPUT source files. This way you can easily exclude a -# subdirectory from a directory tree whose root is specified with the INPUT tag. -# Note that relative paths are relative to the directory from which doxygen is -# run. - -EXCLUDE = - -# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or -# directories that are symbolic links (a Unix file system feature) are excluded -# from the input. - -EXCLUDE_SYMLINKS = NO - -# If the value of the INPUT tag contains directories, you can use the -# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude -# certain files from those directories. Note that the wildcards are matched -# against the file with absolute path, so to exclude all test directories -# for example use the pattern */test/* - -EXCLUDE_PATTERNS = *UTF* \ - */GLSupport/include/EGL/* \ - */GLSupport/include/GLX/* \ - */GLSupport/include/OSX/* \ - */GLSupport/include/win32/* \ - */include/Threading/* \ - */OgreMemoryAllocatorConfig.h \ - *EAGL* \ - */RenderSystems/GLES/* - -# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names -# (namespaces, classes, functions, etc.) that should be excluded from the -# output. The symbol name can be a fully qualified name, a word, or if the -# wildcard * is used, a substring. Examples: ANamespace, AClass, -# AClass::ANamespace, ANamespace::*Test - -EXCLUDE_SYMBOLS = Ogre::AllocatedObject Ogre::ParamCommand - -# The EXAMPLE_PATH tag can be used to specify one or more files or -# directories that contain example code fragments that are included (see -# the \include command). - -EXAMPLE_PATH = "." - -# If the value of the EXAMPLE_PATH tag contains directories, you can use the -# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp -# and *.h) to filter out the source-files in the directories. If left -# blank all files are included. - -EXAMPLE_PATTERNS = - -# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be -# searched for input files to be used with the \include or \dontinclude -# commands irrespective of the value of the RECURSIVE tag. -# Possible values are YES and NO. If left blank NO is used. - -EXAMPLE_RECURSIVE = NO - -# The IMAGE_PATH tag can be used to specify one or more files or -# directories that contain image that are included in the documentation (see -# the \image command). - -IMAGE_PATH = "Docs/src/tutorials/" \ - "Docs/src/images/" - -# The INPUT_FILTER tag can be used to specify a program that doxygen should -# invoke to filter for each input file. Doxygen will invoke the filter program -# by executing (via popen()) the command , where -# is the value of the INPUT_FILTER tag, and is the name of an -# input file. Doxygen will then use the output that the filter program writes -# to standard output. -# If FILTER_PATTERNS is specified, this tag will be -# ignored. - -INPUT_FILTER = - -# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern -# basis. -# Doxygen will compare the file name with each pattern and apply the -# filter if there is a match. -# The filters are a list of the form: -# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further -# info on how filters are used. If FILTER_PATTERNS is empty or if -# non of the patterns match the file name, INPUT_FILTER is applied. - -FILTER_PATTERNS = - -# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using -# INPUT_FILTER) will be used to filter the input files when producing source -# files to browse (i.e. when SOURCE_BROWSER is set to YES). - -FILTER_SOURCE_FILES = NO - -# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file -# pattern. A pattern will override the setting for FILTER_PATTERN (if any) -# and it is also possible to disable source filtering for a specific pattern -# using *.ext= (so without naming a filter). This option only has effect when -# FILTER_SOURCE_FILES is enabled. - -FILTER_SOURCE_PATTERNS = - -# If the USE_MD_FILE_AS_MAINPAGE tag refers to the name of a markdown file that -# is part of the input, its contents will be placed on the main page (index.html). -# This can be useful if you have a project on for instance GitHub and want reuse -# the introduction page also for the doxygen output. - -USE_MDFILE_AS_MAINPAGE = - -#--------------------------------------------------------------------------- -# configuration options related to source browsing -#--------------------------------------------------------------------------- - -# If the SOURCE_BROWSER tag is set to YES then a list of source files will -# be generated. Documented entities will be cross-referenced with these sources. -# Note: To get rid of all source code in the generated output, make sure also -# VERBATIM_HEADERS is set to NO. - -SOURCE_BROWSER = NO - -# Setting the INLINE_SOURCES tag to YES will include the body -# of functions and classes directly in the documentation. - -INLINE_SOURCES = NO - -# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct -# doxygen to hide any special comment blocks from generated source code -# fragments. Normal C, C++ and Fortran comments will always remain visible. - -STRIP_CODE_COMMENTS = YES - -# If the REFERENCED_BY_RELATION tag is set to YES -# then for each documented function all documented -# functions referencing it will be listed. - -REFERENCED_BY_RELATION = YES - -# If the REFERENCES_RELATION tag is set to YES -# then for each documented function all documented entities -# called/used by that function will be listed. - -REFERENCES_RELATION = YES - -# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) -# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from -# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will -# link to the source code. -# Otherwise they will link to the documentation. - -REFERENCES_LINK_SOURCE = YES - -# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the -# source code will show a tooltip with additional information such as prototype, -# brief description and links to the definition and documentation. Since this -# will make the HTML file larger and loading of large files a bit slower, you -# can opt to disable this feature. -# The default value is: YES. -# This tag requires that the tag SOURCE_BROWSER is set to YES. - -SOURCE_TOOLTIPS = YES -# If the USE_HTAGS tag is set to YES then the references to source code -# will point to the HTML generated by the htags(1) tool instead of doxygen -# built-in source browser. The htags tool is part of GNU's global source -# tagging system (see http://www.gnu.org/software/global/global.html). You -# will need version 4.8.6 or higher. - -USE_HTAGS = NO - -# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen -# will generate a verbatim copy of the header file for each class for -# which an include is specified. Set to NO to disable this. - -VERBATIM_HEADERS = NO - -#--------------------------------------------------------------------------- -# configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- - -# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index -# of all compounds will be generated. Enable this if the project -# contains a lot of classes, structs, unions or interfaces. - -ALPHABETICAL_INDEX = YES - -# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then -# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns -# in which this list will be split (can be a number in the range [1..20]) - -COLS_IN_ALPHA_INDEX = 3 - -# In case all classes in a project start with a common prefix, all -# classes will be put under the same header in the alphabetical index. -# The IGNORE_PREFIX tag can be used to specify one or more prefixes that -# should be ignored while generating the index headers. - -IGNORE_PREFIX = - -#--------------------------------------------------------------------------- -# configuration options related to the HTML output -#--------------------------------------------------------------------------- - -# If the GENERATE_HTML tag is set to YES (the default) Doxygen will -# generate HTML output. - -GENERATE_HTML = YES - -# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `html' will be used as the default path. - -HTML_OUTPUT = html - -# The HTML_FILE_EXTENSION tag can be used to specify the file extension for -# each generated HTML page (for example: .htm,.php,.asp). If it is left blank -# doxygen will generate files with .html extension. - -HTML_FILE_EXTENSION = .html - -# The HTML_HEADER tag can be used to specify a personal HTML header for -# each generated HTML page. If it is left blank doxygen will generate a -# standard header. Note that when using a custom header you are responsible -# for the proper inclusion of any scripts and style sheets that doxygen -# needs, which is dependent on the configuration options used. -# It is advised to generate a default header using "doxygen -w html -# header.html footer.html stylesheet.css YourConfigFile" and then modify -# that header. Note that the header is subject to change so you typically -# have to redo this when upgrading to a newer version of doxygen or when -# changing the value of configuration settings such as GENERATE_TREEVIEW! - -HTML_HEADER = - -# The HTML_FOOTER tag can be used to specify a personal HTML footer for -# each generated HTML page. If it is left blank doxygen will generate a -# standard footer. - -HTML_FOOTER = - -# The HTML_STYLESHEET tag can be used to specify a user-defined cascading -# style sheet that is used by each HTML page. It can be used to -# fine-tune the look of the HTML output. If left blank doxygen will -# generate a default style sheet. Note that it is recommended to use -# HTML_EXTRA_STYLESHEET instead of this one, as it is more robust and this -# tag will in the future become obsolete. - -HTML_STYLESHEET = - -# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional -# user-defined cascading style sheet that is included after the standard -# style sheets created by doxygen. Using this option one can overrule -# certain style aspects. This is preferred over using HTML_STYLESHEET -# since it does not replace the standard style sheet and is therefor more -# robust against future updates. Doxygen will copy the style sheet file to -# the output directory. - -HTML_EXTRA_STYLESHEET = "Docs/doxygen-awesome.css" "Docs/ogre_style.css" - -# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or -# other source files which should be copied to the HTML output directory. Note -# that these files will be copied to the base HTML output directory. Use the -# $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these -# files. In the HTML_STYLESHEET file, use the file name only. Also note that -# the files will be copied as-is; there are no commands or markers available. - -HTML_EXTRA_FILES = - -# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. -# Doxygen will adjust the colors in the style sheet and background images -# according to this color. Hue is specified as an angle on a colorwheel, -# see http://en.wikipedia.org/wiki/Hue for more information. -# For instance the value 0 represents red, 60 is yellow, 120 is green, -# 180 is cyan, 240 is blue, 300 purple, and 360 is red again. -# The allowed range is 0 to 359. - -HTML_COLORSTYLE_HUE = 130 - -# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of -# the colors in the HTML output. For a value of 0 the output will use -# grayscales only. A value of 255 will produce the most vivid colors. - -HTML_COLORSTYLE_SAT = 40 - -# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to -# the luminance component of the colors in the HTML output. Values below -# 100 gradually make the output lighter, whereas values above 100 make -# the output darker. The value divided by 100 is the actual gamma applied, -# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, -# and 100 does not change the gamma. - -HTML_COLORSTYLE_GAMMA = 80 - -# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML -# page will contain the date and time when the page was generated. Setting -# this to NO can help when comparing the output of multiple runs. - -HTML_TIMESTAMP = NO - -# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML -# documentation will contain sections that can be hidden and shown after the -# page has loaded. - -HTML_DYNAMIC_SECTIONS = YES - -# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of -# entries shown in the various tree structured indices initially; the user -# can expand and collapse entries dynamically later on. Doxygen will expand -# the tree to such a level that at most the specified number of entries are -# visible (unless a fully collapsed tree already exceeds this amount). -# So setting the number of entries 1 will produce a full collapsed tree by -# default. 0 is a special value representing an infinite number of entries -# and will result in a full expanded tree by default. - -HTML_INDEX_NUM_ENTRIES = 100 - -# The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) -# at top of each HTML page. The value NO (the default) enables the index and -# the value YES disables it. Since the tabs have the same information as the -# navigation tree you can set this option to NO if you already set -# GENERATE_TREEVIEW to YES. - -DISABLE_INDEX = NO - -# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index -# structure should be generated to display hierarchical information. -# If the tag value is set to YES, a side panel will be generated -# containing a tree-like index structure (just like the one that -# is generated for HTML Help). For this to work a browser that supports -# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). -# Windows users are probably better off using the HTML help feature. -# Since the tree basically has the same information as the tab index you -# could consider to set DISABLE_INDEX to NO when enabling this option. - -GENERATE_TREEVIEW = YES - -# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values -# (range [0,1..20]) that doxygen will group on one line in the generated HTML -# documentation. Note that a value of 0 will completely suppress the enum -# values from appearing in the overview section. - -ENUM_VALUES_PER_LINE = 4 - -# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be -# used to set the initial width (in pixels) of the frame in which the tree -# is shown. - -TREEVIEW_WIDTH = 250 - -# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open -# links to external symbols imported via tag files in a separate window. - -EXT_LINKS_IN_WINDOW = NO - -# Use this tag to change the font size of Latex formulas included -# as images in the HTML documentation. The default is 10. Note that -# when you change the font size after a successful doxygen run you need -# to manually remove any form_*.png images from the HTML output directory -# to force them to be regenerated. - -FORMULA_FONTSIZE = 10 - -# Use the FORMULA_TRANPARENT tag to determine whether or not the images -# generated for formulas are transparent PNGs. Transparent PNGs are -# not supported properly for IE 6.0, but are supported on all modern browsers. -# Note that when changing this option you need to delete any form_*.png files -# in the HTML output before the changes have effect. - -FORMULA_TRANSPARENT = YES - -# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax -# (see http://www.mathjax.org) which uses client side Javascript for the -# rendering instead of using prerendered bitmaps. Use this if you do not -# have LaTeX installed or if you want to formulas look prettier in the HTML -# output. When enabled you may also need to install MathJax separately and -# configure the path to it using the MATHJAX_RELPATH option. - -USE_MATHJAX = YES - -# When MathJax is enabled you can set the default output format to be used for -# thA MathJax output. Supported types are HTML-CSS, NativeMML (i.e. MathML) and -# SVG. The default value is HTML-CSS, which is slower, but has the best -# compatibility. - -MATHJAX_FORMAT = HTML-CSS - -# When MathJax is enabled you need to specify the location relative to the -# HTML output directory using the MATHJAX_RELPATH option. The destination -# directory should contain the MathJax.js script. For instance, if the mathjax -# directory is located at the same level as the HTML output directory, then -# MATHJAX_RELPATH should be ../mathjax. The default value points to -# the MathJax Content Delivery Network so you can quickly see the result without -# installing MathJax. -# However, it is strongly recommended to install a local -# copy of MathJax from http://www.mathjax.org before deployment. - -MATHJAX_RELPATH = https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0 - -# The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension -# names that should be enabled during MathJax rendering. - -MATHJAX_EXTENSIONS = - -# When the SEARCHENGINE tag is enabled doxygen will generate a search box -# for the HTML output. The underlying search engine uses javascript -# and DHTML and should work on any modern browser. Note that when using -# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets -# (GENERATE_DOCSET) there is already a search function so this one should -# typically be disabled. For large projects the javascript based search engine -# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. - -SEARCHENGINE = YES - -# When the SERVER_BASED_SEARCH tag is enabled the search engine will be -# implemented using a web server instead of a web client using Javascript. -# There are two flavours of web server based search depending on the -# EXTERNAL_SEARCH setting. When disabled, doxygen will generate a PHP script for -# searching and an index file used by the script. When EXTERNAL_SEARCH is -# enabled the indexing and searching needs to be provided by external tools. -# See the manual for details. - -SERVER_BASED_SEARCH = NO - -# When EXTERNAL_SEARCH is enabled doxygen will no longer generate the PHP -# script for searching. Instead the search results are written to an XML file -# which needs to be processed by an external indexer. Doxygen will invoke an -# external search engine pointed to by the SEARCHENGINE_URL option to obtain -# the search results. Doxygen ships with an example indexer (doxyindexer) and -# search engine (doxysearch.cgi) which are based on the open source search engine -# library Xapian. See the manual for configuration details. - -EXTERNAL_SEARCH = NO - -# The SEARCHENGINE_URL should point to a search engine hosted by a web server -# which will returned the search results when EXTERNAL_SEARCH is enabled. -# Doxygen ships with an example search engine (doxysearch) which is based on -# the open source search engine library Xapian. See the manual for configuration -# details. - -SEARCHENGINE_URL = - -# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed -# search data is written to a file for indexing by an external tool. With the -# SEARCHDATA_FILE tag the name of this file can be specified. - -SEARCHDATA_FILE = searchdata.xml - -# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through other -# doxygen projects that are not otherwise connected via tags files, but are -# all added to the same search index. Each project needs to have a tag file set -# via GENERATE_TAGFILE. The search mapping then maps the name of the tag file -# to a relative location where the documentation can be found, -# similar to the -# TAGFILES option but without actually processing the tag file. -# The format is: EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ... - -EXTRA_SEARCH_MAPPINGS = - -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- - -# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will -# evaluate all C-preprocessor directives found in the sources and include -# files. - -ENABLE_PREPROCESSING = YES - -# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro -# names in the source code. If set to NO (the default) only conditional -# compilation will be performed. Macro expansion can be done in a controlled -# way by setting EXPAND_ONLY_PREDEF to YES. - -MACRO_EXPANSION = YES - -# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES -# then the macro expansion is limited to the macros specified with the -# PREDEFINED and EXPAND_AS_DEFINED tags. - -EXPAND_ONLY_PREDEF = YES - -# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files -# pointed to by INCLUDE_PATH will be searched when a #include is found. - -SEARCH_INCLUDES = YES - -# The INCLUDE_PATH tag can be used to specify one or more directories that -# contain include files that are not input files but should be processed by -# the preprocessor. - -INCLUDE_PATH = - -# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard -# patterns (like *.h and *.hpp) to filter out the header-files in the -# directories. If left blank, the patterns specified with FILE_PATTERNS will -# be used. - -INCLUDE_FILE_PATTERNS = - -# The PREDEFINED tag can be used to specify one or more macro names that -# are defined before the preprocessor is started (similar to the -D option of -# gcc). The argument of the tag is a list of macros of the form: name -# or name=definition (no spaces). If the definition and the = are -# omitted =1 is assumed. To prevent a macro definition from being -# undefined via #undef or recursively expanded use the := operator -# instead of the = operator. - -PREDEFINED = OGRE_MEMORY_ALLOCATOR=1 \ - RTSHADER_SYSTEM_BUILD_CORE_SHADERS \ - RTSHADER_SYSTEM_BUILD_EXT_SHADERS \ - OGRE_PLATFORM=10 \ - OGRE_DEPRECATED= \ - OGRE_NODISCARD= \ - OGRE_NORETURN= \ - DECL_MALLOC= \ - OGRE_FORCE_INLINE=inline \ - OGRE_NODELESS_POSITIONING= \ - MANAGED_RESOURCE= \ - OGRE_AUTO_MUTEX= \ - OGRE_FORMAT_PRINTF=;// \ - OGRE_RESOURCE_GROUP_INIT==RGN_DEFAULT \ - protected=private - -# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then -# this tag can be used to specify a list of macro names that should be expanded. -# The macro definition that is found in the sources will be used. -# Use the PREDEFINED tag if you want to use a different macro definition that -# overrules the definition found in the source code. - -EXPAND_AS_DEFINED = - -# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then -# doxygen's preprocessor will remove all references to function-like macros -# that are alone on a line, have an all uppercase name, and do not end with a -# semicolon, because these will confuse the parser if not removed. - -SKIP_FUNCTION_MACROS = YES - -#--------------------------------------------------------------------------- -# Configuration::additions related to external references -#--------------------------------------------------------------------------- - -# The TAGFILES option can be used to specify one or more tagfiles. For each -# tag file the location of the external documentation should be added. The -# format of a tag file without this location is as follows: -# -# TAGFILES = file1 file2 ... -# Adding location for the tag files is done as follows: -# -# TAGFILES = file1=loc1 "file2 = loc2" ... -# where "loc1" and "loc2" can be relative or absolute paths -# or URLs. Note that each tag file must have a unique name (where the name does -# NOT include the path). If a tag file is not located in the directory in which -# doxygen is run, you must also specify the path to the tagfile here. - -TAGFILES = - -# When a file name is specified after GENERATE_TAGFILE, doxygen will create -# a tag file that is based on the input files it reads. - -GENERATE_TAGFILE = "build/api/Ogre.tag" - -# If the ALLEXTERNALS tag is set to YES all external classes will be listed -# in the class index. If set to NO only the inherited external classes -# will be listed. - -ALLEXTERNALS = NO - -# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed -# in the modules index. If set to NO, only the current project's groups will -# be listed. - -EXTERNAL_GROUPS = YES - -# The PERL_PATH should be the absolute path and name of the perl script -# interpreter (i.e. the result of `which perl'). - -PERL_PATH = /usr/bin/perl - -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- - -# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will -# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base -# or super classes. Setting the tag to NO turns the diagrams off. Note that -# this option also works with HAVE_DOT disabled, but it is recommended to -# install and use dot, since it yields more powerful graphs. - -CLASS_DIAGRAMS = YES - -# You can define message sequence charts within doxygen comments using the \msc -# command. Doxygen will then run the mscgen tool (see -# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the -# documentation. The MSCGEN_PATH tag allows you to specify the directory where -# the mscgen tool resides. If left empty the tool is assumed to be found in the -# default search path. - -MSCGEN_PATH = - -# If set to YES, the inheritance and collaboration graphs will hide -# inheritance and usage relations if the target is undocumented -# or is not a class. - -HIDE_UNDOC_RELATIONS = YES - -# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is -# available from the path. This tool is part of Graphviz, a graph visualization -# toolkit from AT&T and Lucent Bell Labs. The other options in this section -# have no effect if this option is set to NO (the default) - -HAVE_DOT = YES - -# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is -# allowed to run in parallel. When set to 0 (the default) doxygen will -# base this on the number of processors available in the system. You can set it -# explicitly to a value larger than 0 to get control over the balance -# between CPU load and processing speed. - -DOT_NUM_THREADS = 0 - -# By default doxygen will use the Helvetica font for all dot files that -# doxygen generates. When you want a differently looking font you can specify -# the font name using DOT_FONTNAME. You need to make sure dot is able to find -# the font, which can be done by putting it in a standard location or by setting -# the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the -# directory containing the font. - -DOT_FONTNAME = Helvetica - -# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. -# The default size is 10pt. - -DOT_FONTSIZE = 10 - -# By default doxygen will tell dot to use the Helvetica font. -# If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to -# set the path where dot can find it. - -DOT_FONTPATH = - -# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for each documented class showing the direct and -# indirect inheritance relations. Setting this tag to YES will force the -# CLASS_DIAGRAMS tag to NO. - -CLASS_GRAPH = YES - -# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for each documented class showing the direct and -# indirect implementation dependencies (inheritance, containment, and -# class references variables) of the class with other documented classes. - -COLLABORATION_GRAPH = NO - -# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for groups, showing the direct groups dependencies - -GROUP_GRAPHS = NO - -# If the UML_LOOK tag is set to YES doxygen will generate inheritance and -# collaboration diagrams in a style similar to the OMG's Unified Modeling -# Language. - -UML_LOOK = NO - -# If the UML_LOOK tag is enabled, the fields and methods are shown inside -# the class node. If there are many fields or methods and many nodes the -# graph may become too big to be useful. The UML_LIMIT_NUM_FIELDS -# threshold limits the number of items for each type to make the size more -# managable. Set this to 0 for no limit. Note that the threshold may be -# exceeded by 50% before the limit is enforced. - -UML_LIMIT_NUM_FIELDS = 10 - -# If set to YES, the inheritance and collaboration graphs will show the -# relations between templates and their instances. - -TEMPLATE_RELATIONS = NO - -# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT -# tags are set to YES then doxygen will generate a graph for each documented -# file showing the direct and indirect include dependencies of the file with -# other documented files. - -INCLUDE_GRAPH = NO - -# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and -# HAVE_DOT tags are set to YES then doxygen will generate a graph for each -# documented header file showing the documented files that directly or -# indirectly include this file. - -INCLUDED_BY_GRAPH = NO - -# If the CALL_GRAPH and HAVE_DOT options are set to YES then -# doxygen will generate a call dependency graph for every global function -# or class method. Note that enabling this option will significantly increase -# the time of a run. So in most cases it will be better to enable call graphs -# for selected functions only using the \callgraph command. - -CALL_GRAPH = NO - -# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then -# doxygen will generate a caller dependency graph for every global function -# or class method. Note that enabling this option will significantly increase -# the time of a run. So in most cases it will be better to enable caller -# graphs for selected functions only using the \callergraph command. - -CALLER_GRAPH = NO - -# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen -# will generate a graphical hierarchy of all classes instead of a textual one. - -GRAPHICAL_HIERARCHY = YES - -# If the DIRECTORY_GRAPH and HAVE_DOT tags are set to YES -# then doxygen will show the dependencies a directory has on other directories -# in a graphical way. The dependency relations are determined by the #include -# relations between the files in the directories. - -DIRECTORY_GRAPH = NO - -# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images -# generated by dot. Possible values are svg, png, jpg, or gif. -# If left blank png will be used. If you choose svg you need to set -# HTML_FILE_EXTENSION to xhtml in order to make the SVG files -# visible in IE 9+ (other browsers do not have this requirement). - -DOT_IMAGE_FORMAT = svg - -# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to -# enable generation of interactive SVG images that allow zooming and panning. -# Note that this requires a modern browser other than Internet Explorer. -# Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you -# need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files -# visible. Older versions of IE do not have SVG support. - -INTERACTIVE_SVG = NO - -# The tag DOT_PATH can be used to specify the path where the dot tool can be -# found. If left blank, it is assumed the dot tool can be found in the path. - -DOT_PATH = /usr/bin - -# The DOTFILE_DIRS tag can be used to specify one or more directories that -# contain dot files that are included in the documentation (see the -# \dotfile command). - -DOTFILE_DIRS = - -# The MSCFILE_DIRS tag can be used to specify one or more directories that -# contain msc files that are included in the documentation (see the -# \mscfile command). - -MSCFILE_DIRS = - -# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of -# nodes that will be shown in the graph. If the number of nodes in a graph -# becomes larger than this value, doxygen will truncate the graph, which is -# visualized by representing a node as a red box. Note that doxygen if the -# number of direct children of the root node in a graph is already larger than -# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note -# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. - -DOT_GRAPH_MAX_NODES = 50 - -# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the -# graphs generated by dot. A depth value of 3 means that only nodes reachable -# from the root by following a path via at most 3 edges will be shown. Nodes -# that lay further from the root node will be omitted. Note that setting this -# option to 1 or 2 may greatly reduce the computation time needed for large -# code bases. Also note that the size of a graph can be further restricted by -# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. - -MAX_DOT_GRAPH_DEPTH = 4 - -# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent -# background. This is disabled by default, because dot on Windows does not -# seem to support this out of the box. Warning: Depending on the platform used, -# enabling this option may lead to badly anti-aliased labels on the edges of -# a graph (i.e. they become hard to read). - -DOT_TRANSPARENT = YES - -# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output -# files in one run (i.e. multiple -o and -T options on the command line). This -# makes dot run faster, but since only newer versions of dot (>1.8.10) -# support this, this feature is disabled by default. - -DOT_MULTI_TARGETS = YES - -# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will -# generate a legend page explaining the meaning of the various boxes and -# arrows in the dot generated graphs. - -GENERATE_LEGEND = YES - -# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will -# remove the intermediate dot files that are used to generate -# the various graphs. - -DOT_CLEANUP = YES diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000000..cfde5e7fc33 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +*.file filter=lfs diff=lfs merge=lfs -text +*.ipch filter=lfs diff=lfs merge=lfs -text +*.pdb filter=lfs diff=lfs merge=lfs -text +*.tar.gz filter=lfs diff=lfs merge=lfs -text +*.obj filter=lfs diff=lfs merge=lfs -text +*.pch filter=lfs diff=lfs merge=lfs -text diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml deleted file mode 100644 index 6fb453d50fc..00000000000 --- a/.github/FUNDING.yml +++ /dev/null @@ -1,2 +0,0 @@ -patreon: ogre1 -github: paroj diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index 52fbc558e22..00000000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve -title: '' -labels: '' -assignees: '' - ---- - - -#### System Information -- Ogre Version: :grey_question: -- Operating System / Platform: :grey_question: -- RenderSystem: :grey_question: - -#### Detailled description - - -#### Ogre.log - diff --git a/.github/workflows/ci-build.yml b/.github/workflows/ci-build.yml deleted file mode 100644 index 863e04cd875..00000000000 --- a/.github/workflows/ci-build.yml +++ /dev/null @@ -1,107 +0,0 @@ -name: CI Build -on: - push: - branches: [master] - tags: ["v*"] - pull_request: - branches: [master] -jobs: - linux: - runs-on: ubuntu-20.04 - steps: - - name: Install Dependencies - run: | - sudo apt update - sudo apt install -y libxrandr-dev \ - libgles2-mesa-dev mesa-common-dev libgl1-mesa-dev mesa-vulkan-drivers \ - libfreetype6-dev libpugixml-dev libassimp-dev libbullet-dev qtbase5-dev cargo \ - nvidia-cg-dev glslang-dev spirv-tools spirv-headers \ - swig4.0 mono-mcs python3-dev \ - python3-lxml texlive-binaries texlive-base graphviz doxygen g++-7 - - uses: actions/checkout@v3 - with: - fetch-depth: 2 - - name: Build - run: | - cmake -P ci-build.cmake - cmake --build build -- -j 2 - cmake --build build --target OgreDoc > /dev/null - env: # need to fix warnings on newer compilers first - CC: gcc-7 - CXX: g++-7 - - name: Test - run: | - # doxygen warnings check - cat build/doxygen_warnings.log - test ! -s build/doxygen_warnings.log - # run unit tests - build/bin/Test_Ogre - # run visual tests - cd build/bin && ./TestContext -rs "OpenGL 3+ Rendering Subsystem" - ./TestContext -rs "OpenGL ES 2.x Rendering Subsystem" - # verify that the python modules are loadable - cd ../lib && python -c "import _Ogre; import _RTShader" - cd ../../ - # validate XMLConverter output - build/bin/OgreXMLConverter Samples/Media/models/jaiqua.mesh && build/bin/OgreXMLConverter Samples/Media/models/jaiqua.skeleton - python3 Tools/XMLConverter/docs/validate.py Samples/Media/models/jaiqua.mesh.xml - # MeshUpgrader does not crash - build/bin/OgreMeshUpgrader Samples/Media/models/jaiqua.mesh - # validate DotScene DTD - python3 PlugIns/DotScene/misc/validate.py PlugIns/DotScene/misc/example.scene - # check whitespace - git diff --check HEAD^ - android: - runs-on: ubuntu-20.04 - steps: - - uses: actions/checkout@v3 - - uses: actions/cache@v3 - with: - path: android-ndk-r21e - key: ${{ runner.os }}-android-ndk - - name: Install Dependencies - run: sudo apt-get install -y swig4.0 - - name: Build - run: | - cmake -P ci-build.cmake - cmake --build build -- -j 2 - env: - ANDROID: true - - name: zip SDK - id: package - run: | - [[ $GITHUB_REF = refs/tags/* ]] && VERNAME=${GITHUB_REF##*/} || VERNAME="master" - echo "ver=${VERNAME}" >> $GITHUB_OUTPUT - cd build/OgreJNI && zip -qr ogre-sdk-android-${VERNAME}-arm64-v8a.zip * - - name: upload artifact - run: | - test ! -n "$CLOUDSMITH_API_KEY" && exit 0 - pip3 install --upgrade cloudsmith-cli==1.0.0 - ~/.local/bin/cloudsmith push raw ogrecave/ogre build/OgreJNI/ogre-sdk-android-*-arm64-v8a.zip --republish --version ${{ steps.package.outputs.ver }} -k $CLOUDSMITH_API_KEY - env: - CLOUDSMITH_API_KEY: ${{ secrets.CLOUDSMITH_API_KEY }} - macos: - runs-on: macos-11 - steps: - - name: Install Dependencies - run: brew update && brew install sdl2 pugixml - - uses: actions/checkout@v3 - - name: Build - run: | - cmake -P ci-build.cmake - set -o pipefail && cmake --build build | xcpretty - env: - TRAVIS_OS_NAME: osx - - name: Test - run: build/bin/Debug/Test_Ogre.app/Contents/MacOS/Test_Ogre --gtest_filter=-UseCustomCapabilitiesTests* - ios: - runs-on: macos-11 - steps: - - uses: actions/checkout@v3 - - name: Build - run: | - cmake -P ci-build.cmake - set -o pipefail && cmake --build build | xcpretty - env: - IOS: true - \ No newline at end of file diff --git a/.github/workflows/pip-build.yml b/.github/workflows/pip-build.yml deleted file mode 100644 index e88f7ff0ffb..00000000000 --- a/.github/workflows/pip-build.yml +++ /dev/null @@ -1,62 +0,0 @@ -name: PIP packages -on: - push: - tags: ["v*"] -env: - TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} - TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} -jobs: - linux: - runs-on: ubuntu-20.04 - steps: - - uses: actions/checkout@v3 - - name: Docker Image - run: docker build SDK -t pypi - - name: Build - run: | - docker run -e PYVER=cp310-cp310 -e SKBUILD_BUILD_OPTIONS=-j2 --rm -v `pwd`:/workspace pypi - f=`ls *.whl` - mv $f ${f/linux/manylinux2014} - pip3 install twine - python -m twine upload --repository pypi *.whl - windows: - runs-on: windows-2019 - steps: - - uses: actions/checkout@v3 - - uses: ilammy/msvc-dev-cmd@v1 - with: - toolset: 14.1 - - uses: actions/setup-python@v4 - with: - python-version: '3.10' - # see https://github.com/actions/runner-images/issues/6627#issuecomment-1328214957 - - name: Remove Perl Strawberry (Workaround) - run: rm -rf C:/Strawberry/ - shell: bash - - name: Install Dependencies - run: | - curl -LO https://sdk.lunarg.com/sdk/download/1.3.224.1/windows/VulkanSDK-1.3.224.1-Installer.exe - .\VulkanSDK-1.3.224.1-Installer.exe --accept-licenses --default-answer --confirm-command install - - name: Build - run: | - python -m pip install --upgrade pip==22.0.4 - pip install setuptools wheel twine - pip wheel . --verbose - python -m twine upload --repository pypi *.whl - env: - VULKAN_SDK: C:\VulkanSDK\1.3.224.1 - SKBUILD_BUILD_OPTIONS: -j2 - macos: - runs-on: macos-11 - steps: - - uses: actions/checkout@v3 - - uses: actions/setup-python@v4 - with: - python-version: '3.10' - - name: Build - run: | - pip install setuptools wheel twine - pip wheel . --verbose - python -m twine upload --repository pypi *.whl - env: - SKBUILD_BUILD_OPTIONS: -j2 \ No newline at end of file diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 1b12ed9e357..00000000000 --- a/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -# Ignore CLion project directory and iml files -.idea/ -*.iml - -# Ignore build directories -cmake-build-*/ -/build/ -/installed/ -/android-build/ -/embuild/ -/eminstall/ -/mingw/ -/.cache/ -/_skbuild/ - -# Meta data of macOS's Finder.app -.DS_Store - -/Samples/Media/RTShaderLib/cache/ - -# Ignore vim files -*.swp diff --git a/AUTHORS b/AUTHORS deleted file mode 100644 index 31010f63a6d..00000000000 --- a/AUTHORS +++ /dev/null @@ -1,312 +0,0 @@ -AUTHORS -======= -OGRE was originally created by Steve Streeting (sinbad), but many other developers have contributed to the project over the years. - -If you feel your name was forgotten in this list, please submit a pull request. - -The full list of contributors is: - -James O'Sullivan ( _mental_ ) -Harald Achitz ( a4z ) -Chris Kohnert ( aeyr ) -Ahmed Ismaiel Zakaria ( ahmedismaiel ) -Allan Jaenicke -Laboureur Frederic ( alphasnd ) -Amit Mathew ( amitmathew ) -Andrew Patzwald ( amp44x ) -Andrew Fenn ( Zeaus ) -Andy Miller ( andy_miller ) -Andrew Zabolotny ( andyz ) -Ferdinand Joseph Fernandez ( anomalous underdog ) -Antony Suter ( Bontakun / sutera7606 ) -Artem Baguinski ( artm ) -Zdeno Miklas ( ashid ) -Assaf Raman -Jason Assalita ( avengre ) -Manuel Alvarez ( bananiafr ) -William V. Baxter III ( baxissimo ) -Bruno Crivelari Sanches ( bcsanchez ) -Argiris Kirtzidis ( Bekas ) -Brian Johnstone ( bjj1478 / Praetor ) -Avery Fay ( btmorex ) -Ivica Aracic ( bytelord ) -Tim Kelsey ( c4llidus ) -Holger Frydrych ( cabalistic ) -Adrian Cearnau ( cearny ) -Andres Mejia ( ceros ) -Chetan Deshpande ( ChetanDeshpande ) -Christian Southgate ( chrid ) -Christian Boutin ( christianboutin ) -Christian Lindequist Larsen ( dword ) -Luc Claustres ( claustre ) -Heikki Törmälä ( cmayhem ) -Mark Thomas ( Codetick / TMT ) -Greg Junker ( Xavier / cos_xavier ) -François Bruneau ( cottonbelly ) -Jean-Baptiste Griffo ( crashy ) -Paul Turner ( Crayzed / crazyeddie ) -Paolo Gavocanov ( cthno1 ) -Philippe Culet ( cuinl ) -Daniel Andersson ( d_mon ) -Damien Gerhardy ( gerds ) -Daniel Horn ( danielrh ) -David Batzle (davidcb) -David Durant ( ddurant ) -Dennis Verbeek ( dennisverbeek ) -Doraisamy Ganeshkumar ( dganesh ) -David Guy ( dguy ) -Dmitry Yunchik ( DimA ) -Doug Wolanick -Fred Guignot ( dropfred ) -Etienne Mallard ( earthquakeproof ) -Ethan Tira-Thompson ( ejtttje ) -Erik Karulf ( ekarulf ) -Eric Tulla ( Emtulla / ChocoboInbreeder ) -Eric Cha ( Xenopi / Chaster ) -Erik Hjortsberg ( erikhjortsberg ) -Erik Schack Andersen ( eschack ) -Evgeni Popov ( evpopov ) -Evgeny A. Marchenko ( mentor / evgeni_m ) -Alexander Folomeyv ( falek_sf ) -Wael El Oraiby ( farakon ) -Chris Robinson ( fatpwnage ) -Felix Bellaby ( felix_bellaby ) -Francesco Giordana ( fgiordana ) -Matthew Reid ( foxbat ) -Jiang Anxiong Jeffrey ( gamedboy ) -JianHua Xie ( genva ) -Gaylord Foureau ( gforeau ) -Gabriel Gambetta ( ggambett ) -Robert Noll ( ghoulsblade ) -Andrzej Giniewicz ( giniu ) -Guillaume Laforte ( glaforte ) -Gonen Beneish ( gonenb ) -John Van Vliet ( granite ) -Graham Scott Rhodes ( grhodes ) -Matthias Fink ( gs2x ) -Guillaume Buisson ( gustav ) -Andrzej Haczewski ( guyver6 ) -Daniel Wickert ( haffax ) -Daniel Horn ( hellcatv ) -David Longacre ( hexidave ) -Hidehiro Kuroda ( jagoon ) -Brian Hudson ( hudson_b ) -Qu shiwei ( iloseall ) -Sean Lindskog ( Jabberwocky ) -James D. Trotter ( jamesdt ) -Jose Antonio Milan Perez ( jamilan / spoke ) -Jonathan Anderson ( janders ) -Jason K. O'Brien -James Covington ( jaymzjc ) -Jay Sprenkle -Jesse Rusak ( jder ) -James Le Cuirot ( jerseychewi / Chewi ) -John Bartholomew ( johnb213 ) -Jorrit de Vries ( jorrit5477 ) -Josh Flowers -Jules Robichaud Gagnon ( jules_robichaud ) -Juozas Gaigalas ( juozasg ) -Justin Walsh ( JustinWalsh ) -Jon Watte ( jwatte ) -Kai-Peter Bäckman ( kai-peter ) -Kai Blin -Andreas Olov Stenius ( kaos_explosive ) -Matt Williams ( kardoon ) -Kevin J Bluck ( kbluck ) -Jesús Alonso Abad ( kencho ) -Urs Hanselmann ( kickin_bear / noisydev ) -Joël Lamotte ( Klaim ) -Koen Kooi -Paul Cheyrou-lagrèze ( tuan kuranes ) -Lakin Wecker -Chris McGuirk ( leedgitar ) -Lee Sandberg ( leesandberg ) -Pang Lih-Hern ( Lf3T-Hn4D ) -Leon Glass ( lglass ) -Andres Carrera ( lioric ) -Stefan Josua Walter ( Llarlen ) -Lois Desplat ( Lodes ) -Christopher Bowen ( lostera ) -Mathieu Le Ber ( m_leber ) -Martin Correll ( mac99 ) -Konrad Koch ( mad366 ) -Manuel García Rodríguez ( manuel_gr ) -Mattan Furst ( mattan_f ) -Alex Man ( mcspy0312 ) -Mika Halttunen ( mh ) -Michaël Broutin ( mikachu59 ) -Michael Dilger ( mikedilger ) -Nikita Buida ( mj / mj_sf ) -Jacobus Izak Van Aarde Krynauw ( nanocell ) -Nathan M. Hanish -Nathan Walker -Derek Nedelman ( nedelman ) -Jeff Doyle ( nfz ) -Jason Wagner ( nialscorva ) -Nicholas Molton ( nick_molton ) -Nils Schneider -Nir Hasson -Noam Gat ( Noman ) -Vincent Vivanloc ( nop / nopnopzero ) -Pau Novau Lebrato ( novaumas ) -Amit Bleiweiss ( omekinteractive ) -Michael Williamson ( ozwally ) -Paul Fenwick ( paulwf ) -Pavel Vorobealov ( pavor ) -Hamilton Chong ( peridexion ) -Peter Newman ( PeterNewman / wizarth ) -Pierre Morcello ( pierre_m / madmarx ) -Phillip J. Castaneda ( pjcast ) -Phil McLachlan -Peter Miller ( pmiller ) -Ciaran Gultnieks ( poisoned ) -Sascha Bosecker ( poldi-49152 ) -Poojan Prabhu ( poojan_prabhu / jimmemalone / psquare) -Quentin Froemke ( qfroemke / qtf ) -Henry Goffin ( qsilver ) -Stéphane Bessette ( rackle ) -Matt Rice ( ratmice ) -Bora Utku ( Red5_StandingBy ) -Michael Reimpell ( reimpell ) -Renato Araujo Oliveira Filho ( renatofilho ) -Rune Myrland ( rmy ) -Robin Bourianes ( robin_onesia / bamboo2 ) -Royce Eugene Mitchell III ( royce3 ) -John K. Grant ( rufeo / cryfer ) -Samuel Toulouse ( samlepirate ) -Sylvain Cunzi ( scunzi ) -Sebastien Frippiat ( sebarnolds ) -Sean Kennedy ( serrux ) -Antoine Diamant-Berger ( shadow007 ) -Ingo Heßling ( shadowcode1980 ) -Jon L. Griffeth ( silent3 ) -Steve Streeting ( sinbad ) -Shane Parker ( sirshane ) -Martin Schmitz ( skiri-ki ) -Steven S. Klug ( sklug ) -Ronald Hall ( Sobek47 ) -Daniel Svensson ( soldans ) -Martin Sherburn ( spacedude ) -Chris Hunt ( spacejim / Captain_Deathbeard ) -Dave Cunningham ( sparksparkspark ) -Henry van Merode ( spookyboo ) -Madhu Srinivasan ( srinivma ) -Satyajit Sarangi ( ssarangi ) -Stefan Geiger -Stewart Heckenberg ( youdaman ) -Wolfgang Steiner ( stoneCold ) -Benjamin Kinsey ( stormsong_lead ) -Andreas Podgurski ( SunSailor / SunSailor75 ) -Peter 'piet' Loest ( superpiet ) -Mats Leksell ( sxw ) -Thomas Muldowney ( temas ) -Timothy A. Graupmann ( tgraupmann ) -Beau Hardy ( theotherguy ) -Thorsten Lange ( Injector ) -Tibor Tihon -Thomas Hill ( tomlikestorock ) -Filip Volejnik ( volca ) -Van Stokes, Jr. ( Van ) -Ville Heiskanen ( vzheiska ) -Aneurin Price ( waywocket ) -Wesley Howe ( weshowe ) -Lucas Westine ( westine ) -Will Thimbleby -Leon Williams / EFI -Balázs Hajdics ( wolverine___ ) -Wladimir J. van der Laan ( wumpus ) -Daniel Jungmann ( xaphier ) -Eric Shorkey ( zeroskill ) -Zaid Abdulla ( zkam83 ) -Mark Ivey ( zovirl ) -Fabrizio Nunnari (fnunnari) -Jonathon Bijl (jonim8tor) -Zi Ye (omniter) -Thomas Fischer (tdev / rorthomas) -Till Eisele (till) -Crestez Dan Leonard (cdleonard) -David Rogers (davidrogers4 / sweetjimmy / masterfalcon) -Tommaso Checchi (tommo89 / _tommo_) -Yevgen Golushkov (eugene_gff) -Shanti Gaudreault (sgaudreault) -Zebedee Mason (zmason) -Remo Hertig (nairboon) -Roman Senuta (tony-bit) -Oliver Iking (oiking) -Stephan Starke (knox31085) -Enrico Zschemisch (enricozz) -Mike Jurka (mikejurka) -Joost van Dongen (Oogst) -Benjamin Rauscher (realmforge) -Murat Sari (wolfmanfx) -K.L. X (k_l_) (contributor has no latin character name) -Goran Sterjov (gozza/gozza11) -Matias N. Goldberg (dark_sylinc) -David Mitchell (moohasha) -Thomas Maniero (tmaniero/gersen) -Tang Yu (ershu) -Dirk Arnholt (darnholt / Jabarsa) -Pawel Stopinski (stoper) -Paul Tanganeli (tango3237) -Jean-Dominique Gascuel (gascuel) -Robrecht Noens (derobbe) -Felix Kerger (mirlix) -Morris Samuel (booleanlogic) -Mateusz Kotiuk (kotek) -Moamen El-Tahwagi (moagames) -Ivan Efimov (betauser) -Yashin Evgeny (johny5) -Christophe Nenning (kex/kex347) -Feiyun Wang (feiyunw) -David Cunningham (sparkprime) -Tam Bellini (skaiware) -James R. Evans (jrevans/fugalumpto) -Michael Kapelko (kornerr) -Ashley McConnell (ashmcconnell) -Jonathan Liu (net147) -Sam Hocevar (sammy/samhocevar) -Fabian Landau (x3n/xen-fl) -Wei Xu Kai (yesbaba) -Eddie D Bartley (bellyfish/fish) -Anssi Kullervo Kivinen (reptor/tone-gun) -Josh Faust (jfaust/jfaust-wg) -Zhang Heng (ZHing) -Glenn Ramsey (glennr) -Dario Ahdoot (diarrhio) -Stephane Kyles (cose) -Jim Buck (jbuck, jimbuck) -Ettore Pancini (ekt) -Micheal Larkin (micheallarkin) -Aaron J Gardner (nmodprime) -Florian George (floriangeorge) -Arnaud Moura (AMoura) -Philip Allgaier (spacegaier) -Jean-Franois Verdon (Nodrev) -Bastian Kšcher (zerokompex/zero) -Riley Adams (Praetorian, RileyA) -John Soklaski (mysterycoder) -Evandro Millian Paulino -Nick Anderson (Arkiruthis/CaptainFlaps) -Fathi Boudra (fboudra) -Daniel Brunton (dbrunton) -Simon Wallner (simonw) -Vadim Sergeev (m2codegen) -Andrew Mann (Rhad) -Antti Salonen (ajsalonen) -Edoardo Molinatti (edomoli/edoardo) -Jeremy Altavilla (fedyakin) -Peter Krattze (vouti / douvitoui) -Martin DubŽ (arcanemartz) -Jan Drabner (TheSHEEEP) -Pavel Rojtberg (paroj) -Jannik Heller (scrawl) -Peter Szücs (sajty) -Owen Shepherd (oshepherd) -Philip Lehmann-Böhm (philiplb) -Nikolay Kasyanov (corristo) -Jesse Johnson (holocronweaver) -Timothee Besset (ttimo) -Harald Reingruber (harald_reingruber_) - -Microsoft Open Technologies, Inc. - diff --git a/BuildingOgre.md b/BuildingOgre.md deleted file mode 100644 index a421f470db0..00000000000 --- a/BuildingOgre.md +++ /dev/null @@ -1,259 +0,0 @@ -# Guide to building OGRE {#building-ogre} - -@tableofcontents - -Ogre uses [CMake](https://cmake.org/) as its build system on all supported platforms. -This guide will explain to you how to use CMake to build Ogre from source. You need a CMake version >= 3.10. - -What is CMake? -------------------- - -CMake is a cross-platform build system - or perhaps more accurately a -build configurator. It is a program which, from a set of CMake scripts, -creates a native build system for your platform that allows you to -build Ogre. -The build process is configurable via CMake. Ogre provides several -options which you can use to customise your build. - -Preparing the build environment ------------------------------------- - -You should now create a build directory for Ogre somewhere outside -Ogre's sources. This is the directory where CMake will create the -build system for your chosen platform and compiler, and this is also -where the Ogre libraries will be compiled. This way, the Ogre source -dir stays clean, and you can have multiple build directories (e.g. for Android and for Linux) all -working from the same Ogre source. - -Getting dependencies --------------------- - -By default ogre will build the recommended dependencies automatically when you run cmake configure the first time. -Ogre will install the dependencies into the subfolder `Dependencies` in the build dir by default. You can configure it by setting `OGRE_DEPENDENCIES_DIR` in cmake. - -@note As the dependencies are built during the *configure* stage of CMake, you must specify the desired `CMAKE_BUILD_TYPE` via command-line. Changing the value in the CMake GUI will have no effect. - -If you would rather use system wide libraries set `OGRE_BUILD_DEPENDENCIES=OFF`. -On windows, you would then point `OGRE_DEPENDENCIES_DIR` to a common dependencies folder for all of your middleware projects. Inside this directory you must have the subdirectories bin, lib and include -where you place .dll, .lib and header files of the dependencies, respectively. - -For manually building the dependencies, please refer to the list below and get a source package from the website, then build it according to its documentation. - -### Linux - -On linux you additionally need the following system headers to build the GL, GL3+, GLES2 & Vulkan RenderSystems: -* Ubuntu - - sudo apt-get install libgles2-mesa-dev libvulkan-dev glslang-dev libxrandr-dev - -* Fedora - - sudo dnf install mesa-libGL-devel mesa-vulkan-devel glslang-devel - -furthermore we recommend installing the following optional packages - -* Ubuntu - - sudo apt-get install libsdl2-dev libxt-dev libxaw7-dev doxygen - -* Fedora - - sudo dnf install SDL2-devel libXt-devel libXaw-devel doxygen pugixml-devel - -these will enable input handling in the SampleBrowser, the X11 ConfigDialog and allow building the documentation. - -### Recommended dependencies - -* pugixml: https://github.com/zeux/pugixml -* SDL: https://www.libsdl.org/ -* zlib: http://www.zlib.net -* freetype: http://www.freetype.org - -### Optional dependencies - -* DirectX SDK: http://msdn.microsoft.com/en-us/directx/ -* Vulkan SDK: https://vulkan.lunarg.com/ -* FreeImage: http://freeimage.sourceforge.net -* Doxygen: http://doxygen.org -* Cg: http://developer.nvidia.com/object/cg_toolkit.html -* Remotery: https://github.com/Celtoys/Remotery -* SWIG: http://www.swig.org/ -* %Assimp: https://www.assimp.org/ - -Running CMake -------------- - -Now start the program cmake-gui by either typing the name in a console -or selecting it from the start menu. In the field *Where is the source -code* enter the path to the Ogre source directory (the directory which -contains this file). In the field *Where to build the binaries* enter -the path to the build directory you created. -Hit *Configure*. A dialogue will appear asking you to select a generator. - -Check the [CMake documentation](https://cmake.org/cmake/help/latest/manual/cmake-generators.7.html) for details on which one is appropriate for your platform and compiler. -@note on OSX, you must to use the Xcode generator to get a proper SampleBrowser .app bundle. - -Click *Finish*. CMake will now gather some information about your -build environment and try to locate the dependencies. It will then show -a list of build options. You can adjust the settings to your liking; -- unchecking any of the `OGRE_BUILD_XXX` options will disable that -particular component/ plugin from being built -- `OGRE_CONFIG_XXX` on the other hand allows you to configure Core features e.g. threading or zip file support. -- `OGRE_CONFIG_NODE_INHERIT_TRANSFORM` enables shearing and non-uniform scaling for Ogre::SceneNode. This requires slightly more storage and computation time. -- `OGRE_CONFIG_ENABLE_MESHLOD` If enabled, LOD levels from *.mesh files are used to reduce triangle count. If disabled, they are skipped at loading. Reducing submesh size and entity size. -- `OGRE_PROFILING` add profiling instrumentation the ogre library. -- `OGRE_PROFILING_REMOTERY_PATH` if set, Remotery is used for profiling instead of the Ogre internal profiler. -- `OGRE_ASSERT_MODE` allows you to to disable all runtime assertion exceptions or turn them into calls to `std::abort`. -- `OGRE_RESOURCEMANGER_STRICT` allows you to turn on resource lookup related quirks for pre ogre 1.10 compatibility. -- `OGRE_NODELESS_POSITIONING` allows to use Lights and Cameras without attaching them to nodes (only for legacy code). - -Once you are satisfied, hit -*Configure* again and then click on *Generate*. CMake will then create -the build system for you. - -Building --------- - -Go to your chosen build directory. CMake has generated a build system for -you which you will now use to build Ogre. If you are using Visual Studio, -you should find the file OGRE.sln. Open it and compile the target -*BUILD_ALL*. Similarly you will find an Xcode project to build Ogre -on MacOS. - -If you rather want to trigger the build form a console, then cd to your build directory and call the appropriate make program as - - cmake --build . --config Release - -to start the build process. - -@note on multi-config generators, notably Xcode and MSVC, `--config` must match the `CMAKE_BUILD_TYPE` specified when building the dependencies. This does not apply if you manually provide the dependencies as release *and* debug. - -If you have doxygen installed and CMake picked it up, then there will -be an additional build target called *OgreDoc* which you can optionally build. -This will freshly generate the API documentation for Ogre's classes from the header files. In Visual Studio, just select and build the target *OgreDoc*, on Linux type: - - make OgreDoc - - -Installing ----------- - -Once the build is complete, the libraries and headers must be copied to a clean location. -This is required if you want to reference %Ogre in your own projects with CMake. -In Visual Studio, just select and build the target *INSTALL*. When using the command line, type: - - cmake --build . --config Release --target install - -For Makefile based generators, type: - - make install # (or sudo make install, if root privileges are required) - -On Linux Ogre will be installed to `/usr/local` by default. On Windows this will create the folder `sdk` inside your build directory and copy all the -required libraries there. You can change the install location by changing the variable `CMAKE_INSTALL_PREFIX` in CMake. - -Installing and building via vcpkg ---------------------------------- -You can download and install ogre using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager: -``` -git clone https://github.com/Microsoft/vcpkg.git -cd vcpkg -./bootstrap-vcpkg.sh -./vcpkg integrate install -vcpkg install ogre -``` -The ogre port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. - -# Cross-Compiling - -Building on Ubuntu for Android --------------------------------------------- - -To build Ogre for Android, you need to specify the android cross toolchain to cmake as - - cmake -DCMAKE_TOOLCHAIN_FILE=path/to/android-ndk/build/cmake/android.toolchain.cmake -DANDROID_NDK=path/to/android-ndk . - -this will build the core Ogre libraries. Additionally it will create gradle projects `OgreJNI` for using Java bindings and `SampleBrowserNDK` for the C++ only Sample Browser. - -You can now import these projects in Android Studio or manually trigger the APK creation by changing into the project folders and running - - gradle assembleRelease - -Building for WebAssembly (using Emscripten) ------------------------------------------ -Install the Emscripten SDK (see full documentation on [www.emscripten.org](https://emscripten.org/docs/getting_started/downloads.html)), and make sure -that the environment variables are correctly set (eg. run `source /emsdk_env.sh` before attempting to build) - -Run cmake in cross compile mode using emscripten as following: - - mkdir build-wasm - emcmake cmake .. -DCMAKE_BUILD_TYPE=Release - emmake make - -NB: to simplify the process, 'emcmake' and 'emmake' wrappers are used. These tools are provided by Emscripten to correctly setup the cross compilation environment - -This will not build the full SampleBrowser, but just a minimal Sample. The resulting `EmscriptenSample.html` will be placed in `${CMAKE_BINARY_DIR}/bin/`. - -To prevent any cross-origin issues, start a local webserver as `python3 -m http.server 8000` and visit http://localhost:8000. - -Building on Mac OS X for iOS OS -------------------------------- - -To build Ogre for iOS, you need to specify the ios cross toolchain to cmake as - - cmake -DCMAKE_TOOLCHAIN_FILE=CMake/toolchain/ios.toolchain.xcode.cmake -DIOS_PLATFORM=SIMULATOR -G Xcode . - - -Unfortunately, you will now have to do a few manual steps to -make the generated build system work properly. - -A Xcode project has now been generated in the build directory, so -to start the Ogre build, open OGRE.xcodeproj and build as usual. -To run samples on your device you will need to have a valid iOS Developer -certificate installed. For each sample, double click on target in the Groups & -Files list. Ensure that a valid identity is selected in the Code Signing Identity -drop menu. -Also, because we can't tell CMake what Xcode project format you want, you will -have to change it yourself. Open the Project Menu, choose Edit Project Settings. -Click on the General tab in the settings window. Change Project Format to -Xcode 3.1-compatible. -And another thing. You will need to manually set the Bundle Identifier property of -the Info.plist file to match the App ID of the chosen code signing identity. -This can be done from the Target Properties panel. It must match the bundle -identifier of a valid developer certificate if you are building for devices. - -Building as Windows Store or Windows Phone application -------------------------------------------------------------------- - -You need Windows 8.0 or later, Windows 10 is recommended. - -Visual Studio 2015 is recommended as it is bundled with Universal 10.0.240.0, WinStore 8.0/8.1 and WinPhone 8.0/8.1 SDKs. - -Dependencies for Win32 and for WinRT must be located in -separate folders. Cg is not supported. - - cmake.exe -G "Visual Studio 15 2017" -DCMAKE_SYSTEM_NAME=WindowsStore -DCMAKE_SYSTEM_VERSION=10.0 .. - -Select SampleBrowser as the start up project and run. - -@par Notes - -1. The code and generated CMake solution should be on local NTFS drive, -and can't be on a network drive, including VMWare shared folders - or -you will get a errors when you will try to compile/link/run resulting exe. - -2. Ogre uses d3dcompiler_xx.dll to compile shaders, and WinStore and -WinPhone 8.1 projects can use it without restriction as it is part of OS. -But WinStore and WinPhone 8.0 applications should load already compiled -shaders from cache, as d3dcompiler_xx.dll is available to them only during -development. Therefore to avoid necessity to deploy d3dcompiler_xx.dll -during development (additional configurations with d3dcompiler_xx.dll) -and generation of such cache - use version 8.1 of these platforms. - -3. Running WinPhone emulator in OS running under VMware: -We were able to run the emulation and debug without an issue by using two -steps: (a) Under the settings of the VM > CPU, make sure you have the -option to pass-through the Intel VT-x/EPT feature, (b) Edit the config -file .vmx and add the parameter: hypervisor.cpuid.v0 = "FALSE" -All versions of Visual Studio 2012 have a window refresh issue when running -in VMware and the window is maximized, the solution is just to change the -size of the Visual Studio window to be less the the screen width and height. diff --git a/CMake/ConfigureBuild.cmake b/CMake/ConfigureBuild.cmake deleted file mode 100644 index a632e4d8184..00000000000 --- a/CMake/ConfigureBuild.cmake +++ /dev/null @@ -1,251 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -####################################################################### -# This file takes care of configuring Ogre to build with the settings -# given in CMake. It creates the necessary config.h file and will -# also prepare package files for pkg-config and CMake. -####################################################################### - -string(TOLOWER "${CMAKE_BUILD_TYPE}" BUILD_TYPE_LOWER) -if(${BUILD_TYPE_LOWER} STREQUAL "debug") - set(OGRE_DEBUG_MODE 1) -endif() - -if (APPLE_IOS) - set(OGRE_SET_BUILD_PLATFORM_APPLE_IOS 1) - set(OGRE_STATIC TRUE) - set(OGRE_STATIC_LIB TRUE) -endif() - -# should we build static libs? -if (OGRE_STATIC) - set(OGRE_LIB_TYPE STATIC) -else () - set(OGRE_LIB_TYPE SHARED) -endif () - -# configure threading options -set(OGRE_THREAD_PROVIDER 0) -if (OGRE_CONFIG_THREADS) - if (OGRE_CONFIG_THREAD_PROVIDER STREQUAL "boost") - set(OGRE_THREAD_PROVIDER 1) - include_directories(${Boost_INCLUDE_DIRS}) - # On MSVC Boost usually tries to autolink boost libraries. However since - # this behaviour is not available on all compilers, we need to find the libraries - # ourselves, anyway. Disable auto-linking to avoid mess-ups. - add_definitions(-DBOOST_ALL_NO_LIB) - if (MINGW AND Boost_USE_STATIC_LIBS) - # mingw needs this to link against static thread libraries - add_definitions(-DBOOST_THREAD_USE_LIB) - endif () - set(OGRE_THREAD_LIBRARIES ${Boost_LIBRARIES}) - endif () - - if (OGRE_CONFIG_THREAD_PROVIDER STREQUAL "poco") - set(OGRE_THREAD_PROVIDER 2) - include_directories(${POCO_INCLUDE_DIRS}) - set(OGRE_THREAD_LIBRARIES ${POCO_LIBRARIES}) - endif () - - if (OGRE_CONFIG_THREAD_PROVIDER STREQUAL "std") - set(OGRE_THREAD_PROVIDER 4) - endif () - -endif() - -set(OGRE_ASSERT_MODE 2 CACHE STRING - "Enable Ogre asserts. Possible values: - 0 - Standard asserts in debug builds, nothing in release builds. - 1 - Standard asserts in debug builds, exceptions in release builds. - 2 - Exceptions in debug & release builds." -) -set_property(CACHE OGRE_ASSERT_MODE PROPERTY STRINGS 0 1 2) - -# determine config values depending on build options -set(OGRE_STATIC_LIB ${OGRE_STATIC}) -set(OGRE_DOUBLE_PRECISION ${OGRE_CONFIG_DOUBLE}) -set(OGRE_NODE_INHERIT_TRANSFORM ${OGRE_CONFIG_NODE_INHERIT_TRANSFORM}) -set(OGRE_SET_ASSERT_MODE ${OGRE_ASSERT_MODE}) -set(OGRE_SET_THREADS ${OGRE_CONFIG_THREADS}) -set(OGRE_SET_THREAD_PROVIDER ${OGRE_THREAD_PROVIDER}) -if (NOT OGRE_CONFIG_ENABLE_MESHLOD) - set(OGRE_NO_MESHLOD 1) -endif() -if (NOT OGRE_CONFIG_ENABLE_DDS) - set(OGRE_NO_DDS_CODEC 1) -endif() -if (NOT OGRE_CONFIG_ENABLE_PVRTC) - set(OGRE_NO_PVRTC_CODEC 1) -endif() -if (NOT OGRE_CONFIG_ENABLE_ETC) - set(OGRE_NO_ETC_CODEC 1) -endif() -if (NOT OGRE_CONFIG_ENABLE_ASTC) - set(OGRE_NO_ASTC_CODEC 1) -endif() -if (NOT OGRE_CONFIG_ENABLE_ZIP) - set(OGRE_NO_ZIP_ARCHIVE 1) -endif() -if (NOT OGRE_CONFIG_ENABLE_GLES2_CG_SUPPORT) - set(OGRE_NO_GLES2_CG_SUPPORT 1) -endif() -if (NOT OGRE_CONFIG_ENABLE_GLES2_GLSL_OPTIMISER) - set(OGRE_NO_GLES2_GLSL_OPTIMISER 1) -endif() -if (NOT OGRE_CONFIG_ENABLE_GL_STATE_CACHE_SUPPORT) - set(OGRE_NO_GL_STATE_CACHE_SUPPORT 1) -endif() -if (NOT OGRE_CONFIG_ENABLE_GLES3_SUPPORT) - set(OGRE_NO_GLES3_SUPPORT 1) -endif() -if (NOT OGRE_CONFIG_ENABLE_TBB_SCHEDULER) - set(OGRE_NO_TBB_SCHEDULER 1) -endif() -if (OGRE_TEST_BIG_ENDIAN) - set(OGRE_CONFIG_BIG_ENDIAN 1) -else () - set(OGRE_CONFIG_LITTLE_ENDIAN 1) -endif () -set(RTSHADER_SYSTEM_BUILD_CORE_SHADERS ${OGRE_BUILD_RTSHADERSYSTEM_SHADERS}) -set(RTSHADER_SYSTEM_BUILD_EXT_SHADERS ${OGRE_BUILD_RTSHADERSYSTEM_SHADERS}) -if (NOT OGRE_CONFIG_ENABLE_QUAD_BUFFER_STEREO) - set(OGRE_NO_QUAD_BUFFER_STEREO 1) -endif() -if(SDL2_FOUND OR EMSCRIPTEN) - set(OGRE_BITES_HAVE_SDL 1) -endif() - -# determine if strtol_l is supported -include(CheckFunctionExists) -CHECK_FUNCTION_EXISTS(strtol_l HAVE_STRTOL_L) -if (NOT HAVE_STRTOL_L) - set(OGRE_NO_LOCALE_STRCONVERT 1) -endif () - -# generate OgreBuildSettings.h -configure_file(${OGRE_TEMPLATES_DIR}/OgreComponents.h.in ${PROJECT_BINARY_DIR}/include/OgreComponents.h @ONLY) -configure_file(${OGRE_TEMPLATES_DIR}/OgreBuildSettings.h.in ${PROJECT_BINARY_DIR}/include/OgreBuildSettings.h @ONLY) -configure_file(${OGRE_TEMPLATES_DIR}/OgreRTShaderConfig.h.in ${PROJECT_BINARY_DIR}/include/OgreRTShaderConfig.h @ONLY) -configure_file(${OGRE_TEMPLATES_DIR}/OgreGLES2Config.h.in ${PROJECT_BINARY_DIR}/include/OgreGLES2Config.h @ONLY) - -set(OGRE_LIB_SUFFIX "") - -if (OGRE_STATIC) - set(OGRE_LIB_SUFFIX "${OGRE_LIB_SUFFIX}Static") -endif () -if (BUILD_TYPE_LOWER STREQUAL "debug" AND WIN32) - set(OGRE_LIB_SUFFIX "${OGRE_LIB_SUFFIX}_d") -endif () - -# Create the pkg-config package files on Unix systems -if (UNIX OR MINGW) - if (MINGW) - set(OGRE_PLUGIN_EXT ".dll") - else() - set(OGRE_PLUGIN_EXT ".so") - endif() - set(OGRE_PAGING_ADDITIONAL_PACKAGES "") - if (OGRE_STATIC) - set(OGRE_PLUGIN_EXT ".a") - endif () - - set(OGRE_ADDITIONAL_LIBS "") - - set(OGRE_CFLAGS "") - set(OGRE_PREFIX_PATH ${CMAKE_INSTALL_PREFIX}) - if (OGRE_CONFIG_THREADS GREATER 0) - set(OGRE_CFLAGS "-pthread") - set(OGRE_ADDITIONAL_LIBS "${OGRE_ADDITIONAL_LIBS} -lpthread") - endif () - if (OGRE_STATIC) - if (OGRE_CONFIG_THREADS AND OGRE_CONFIG_THREAD_PROVIDER STREQUAL "boost") - if (CMAKE_BUILD_TYPE STREQUAL "Debug") - set(OGRE_ADDITIONAL_LIBS "${OGRE_ADDITIONAL_LIBS} ${Boost_THREAD_LIBRARY_DEBUG}") - else() - set(OGRE_ADDITIONAL_LIBS "${OGRE_ADDITIONAL_LIBS} ${Boost_THREAD_LIBRARY_RELEASE}") - endif() - endif () - # there is no pkgconfig file for freeimage, so we need to add that lib manually - if (CMAKE_BUILD_TYPE STREQUAL "Debug") - set(OGRE_ADDITIONAL_LIBS "${OGRE_ADDITIONAL_LIBS} ${FreeImage_LIBRARY_DBG}") - else() - set(OGRE_ADDITIONAL_LIBS "${OGRE_ADDITIONAL_LIBS} ${FreeImage_LIBRARY_REL}") - endif() - configure_file(${OGRE_TEMPLATES_DIR}/OGREStatic.pc.in ${PROJECT_BINARY_DIR}/pkgconfig/OGRE.pc @ONLY) - else () - configure_file(${OGRE_TEMPLATES_DIR}/OGRE.pc.in ${PROJECT_BINARY_DIR}/pkgconfig/OGRE.pc @ONLY) - endif () - install(FILES ${PROJECT_BINARY_DIR}/pkgconfig/OGRE.pc DESTINATION ${OGRE_LIB_DIRECTORY}/pkgconfig) - - # configure additional packages - - if (OGRE_BUILD_PLUGIN_PCZ) - configure_file(${OGRE_TEMPLATES_DIR}/OGRE-PCZ.pc.in ${PROJECT_BINARY_DIR}/pkgconfig/OGRE-PCZ.pc @ONLY) - install(FILES ${PROJECT_BINARY_DIR}/pkgconfig/OGRE-PCZ.pc DESTINATION ${OGRE_LIB_DIRECTORY}/pkgconfig) - endif () - - if (OGRE_BUILD_COMPONENT_PAGING) - configure_file(${OGRE_TEMPLATES_DIR}/OGRE-Paging.pc.in ${PROJECT_BINARY_DIR}/pkgconfig/OGRE-Paging.pc @ONLY) - install(FILES ${PROJECT_BINARY_DIR}/pkgconfig/OGRE-Paging.pc DESTINATION ${OGRE_LIB_DIRECTORY}/pkgconfig) - endif () - - if (OGRE_BUILD_COMPONENT_MESHLODGENERATOR) - configure_file(${OGRE_TEMPLATES_DIR}/OGRE-MeshLodGenerator.pc.in ${PROJECT_BINARY_DIR}/pkgconfig/OGRE-MeshLodGenerator.pc @ONLY) - install(FILES ${PROJECT_BINARY_DIR}/pkgconfig/OGRE-MeshLodGenerator.pc DESTINATION ${OGRE_LIB_DIRECTORY}/pkgconfig) - endif () - - if (OGRE_BUILD_COMPONENT_TERRAIN) - if (OGRE_BUILD_COMPONENT_PAGING) - set(OGRE_PAGING_ADDITIONAL_PACKAGES ", OGRE-Paging = ${OGRE_VERSION}") - endif () - configure_file(${OGRE_TEMPLATES_DIR}/OGRE-Terrain.pc.in ${PROJECT_BINARY_DIR}/pkgconfig/OGRE-Terrain.pc @ONLY) - install(FILES ${PROJECT_BINARY_DIR}/pkgconfig/OGRE-Terrain.pc DESTINATION ${OGRE_LIB_DIRECTORY}/pkgconfig) - endif () - - if (OGRE_BUILD_COMPONENT_RTSHADERSYSTEM) - configure_file(${OGRE_TEMPLATES_DIR}/OGRE-RTShaderSystem.pc.in ${PROJECT_BINARY_DIR}/pkgconfig/OGRE-RTShaderSystem.pc @ONLY) - install(FILES ${PROJECT_BINARY_DIR}/pkgconfig/OGRE-RTShaderSystem.pc DESTINATION ${OGRE_LIB_DIRECTORY}/pkgconfig) - endif () - - if (OGRE_BUILD_COMPONENT_PROPERTY) - configure_file(${OGRE_TEMPLATES_DIR}/OGRE-Property.pc.in ${PROJECT_BINARY_DIR}/pkgconfig/OGRE-Property.pc @ONLY) - install(FILES ${PROJECT_BINARY_DIR}/pkgconfig/OGRE-Property.pc DESTINATION ${OGRE_LIB_DIRECTORY}/pkgconfig) - endif () - - if (OGRE_BUILD_COMPONENT_OVERLAY) - configure_file(${OGRE_TEMPLATES_DIR}/OGRE-Overlay.pc.in ${PROJECT_BINARY_DIR}/pkgconfig/OGRE-Overlay.pc @ONLY) - install(FILES ${PROJECT_BINARY_DIR}/pkgconfig/OGRE-Overlay.pc DESTINATION ${OGRE_LIB_DIRECTORY}/pkgconfig) - endif () - - if (OGRE_BUILD_COMPONENT_VOLUME) - configure_file(${OGRE_TEMPLATES_DIR}/OGRE-Volume.pc.in ${PROJECT_BINARY_DIR}/pkgconfig/OGRE-Volume.pc @ONLY) - install(FILES ${PROJECT_BINARY_DIR}/pkgconfig/OGRE-Volume.pc DESTINATION ${OGRE_LIB_DIRECTORY}/pkgconfig) - endif () - - if (OGRE_BUILD_COMPONENT_BITES) - if (SDL2_FOUND) - set(OGRE_BITES_ADDITIONAL_PACKAGES ", sdl2") - endif () - configure_file(${OGRE_TEMPLATES_DIR}/OGRE-Bites.pc.in ${PROJECT_BINARY_DIR}/pkgconfig/OGRE-Bites.pc @ONLY) - install(FILES ${PROJECT_BINARY_DIR}/pkgconfig/OGRE-Bites.pc DESTINATION ${OGRE_LIB_DIRECTORY}/pkgconfig) - endif () -endif () - -if(OGRE_CONFIG_STATIC_LINK_CRT) -#We statically link to reduce dependencies -foreach(flag_var CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO) - if(${flag_var} MATCHES "/MD") - string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}") - endif(${flag_var} MATCHES "/MD") - if(${flag_var} MATCHES "/MDd") - string(REGEX REPLACE "/MDd" "/MTd" ${flag_var} "${${flag_var}}") - endif(${flag_var} MATCHES "/MDd") -endforeach(flag_var) -endif(OGRE_CONFIG_STATIC_LINK_CRT) diff --git a/CMake/Dependencies.cmake b/CMake/Dependencies.cmake deleted file mode 100644 index df563a3c9ce..00000000000 --- a/CMake/Dependencies.cmake +++ /dev/null @@ -1,346 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -####################################################################### -# Find all necessary and optional OGRE dependencies -####################################################################### - -# OGRE_DEPENDENCIES_DIR can be used to specify a single base -# folder where the required dependencies may be found. -set(OGRE_DEPENDENCIES_DIR "${PROJECT_BINARY_DIR}/Dependencies" CACHE PATH "Path to prebuilt OGRE dependencies") -option(OGRE_BUILD_DEPENDENCIES "automatically build Ogre Dependencies (SDL2, pugixml)" TRUE) - -message(STATUS "DEPENDENCIES_DIR: ${OGRE_DEPENDENCIES_DIR}") - -set(OGREDEPS_PATH "${OGRE_DEPENDENCIES_DIR}") -set(OGRE_DEP_SEARCH_PATH "${OGRE_DEPENDENCIES_DIR}") - -if(CMAKE_CROSSCOMPILING) - set(CMAKE_FIND_ROOT_PATH ${OGREDEPS_PATH} "${CMAKE_FIND_ROOT_PATH}") - - set(CROSS -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE}) - - if(ANDROID) - set(CROSS ${CROSS} - -DANDROID_NATIVE_API_LEVEL=${ANDROID_NATIVE_API_LEVEL} - -DANDROID_ABI=${ANDROID_ABI} - -DANDROID_NDK=${ANDROID_NDK}) - endif() - - if(APPLE_IOS) - set(CROSS ${CROSS} - -DIOS_PLATFORM=${IOS_PLATFORM}) - else() - # this should help discovering zlib, but on ios it breaks it - set(CROSS ${CROSS} - -DCMAKE_FIND_ROOT_PATH=${CMAKE_FIND_ROOT_PATH}) - endif() - -endif() - -if(APPLE) - set(CROSS ${CROSS} - -DCMAKE_OSX_ARCHITECTURES=${CMAKE_OSX_ARCHITECTURES}) -endif() - -# if we build our own deps, do it static as it generally eases distribution -set(OGREDEPS_SHARED FALSE) - -# get available processor cores -include(ProcessorCount) -ProcessorCount(NPROC) - -# can not get processor cores, fallback to default value -if(NPROC EQUAL 0) - set(NPROC 2) -endif() - -set(BUILD_COMMAND_OPTS --target install -j ${NPROC} --config ${CMAKE_BUILD_TYPE}) - -set(BUILD_COMMAND_COMMON ${CMAKE_COMMAND} - -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} - -DCMAKE_INSTALL_PREFIX=${OGREDEPS_PATH} - -G ${CMAKE_GENERATOR} - -DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM} - -DCMAKE_GENERATOR_TOOLSET=${CMAKE_GENERATOR_TOOLSET} - -DCMAKE_MAKE_PROGRAM=${CMAKE_MAKE_PROGRAM} - -DCMAKE_POSITION_INDEPENDENT_CODE=TRUE # allow linking into a shared lib - ${CROSS}) - -# Set hardcoded path guesses for various platforms -if (UNIX AND NOT EMSCRIPTEN) - set(OGRE_DEP_SEARCH_PATH ${OGRE_DEP_SEARCH_PATH} /usr/local) - # Ubuntu 11.10 has an inconvenient path to OpenGL libraries - set(OGRE_DEP_SEARCH_PATH ${OGRE_DEP_SEARCH_PATH} /usr/lib/${CMAKE_SYSTEM_PROCESSOR}-linux-gnu) -endif () - -# give guesses as hints to the find_package calls -set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} ${OGRE_DEP_SEARCH_PATH}) -set(CMAKE_FRAMEWORK_PATH ${CMAKE_FRAMEWORK_PATH} ${OGRE_DEP_SEARCH_PATH}) - -if(OGRE_BUILD_DEPENDENCIES AND NOT EXISTS ${OGREDEPS_PATH}) - message(STATUS "Building pugixml") - file(DOWNLOAD - https://github.com/zeux/pugixml/releases/download/v1.14/pugixml-1.14.tar.gz - ${PROJECT_BINARY_DIR}/pugixml-1.14.tar.gz) - execute_process(COMMAND ${CMAKE_COMMAND} - -E tar xf pugixml-1.14.tar.gz WORKING_DIRECTORY ${PROJECT_BINARY_DIR}) - execute_process(COMMAND ${BUILD_COMMAND_COMMON} - -DCMAKE_POSITION_INDEPENDENT_CODE=TRUE # this will be linked into a shared lib - ${PROJECT_BINARY_DIR}/pugixml-1.14 - WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/pugixml-1.14) - execute_process(COMMAND ${CMAKE_COMMAND} - --build ${PROJECT_BINARY_DIR}/pugixml-1.14 ${BUILD_COMMAND_OPTS}) - - #find_package(Freetype) - if (NOT FREETYPE_FOUND) - message(STATUS "Building freetype") - file(DOWNLOAD - https://download.savannah.gnu.org/releases/freetype/freetype-2.13.2.tar.gz - ${PROJECT_BINARY_DIR}/freetype-2.13.2.tar.gz) - execute_process(COMMAND ${CMAKE_COMMAND} - -E tar xf freetype-2.13.2.tar.gz WORKING_DIRECTORY ${PROJECT_BINARY_DIR}) - # patch toolchain for iOS - execute_process(COMMAND ${CMAKE_COMMAND} -E copy - ${PROJECT_SOURCE_DIR}/CMake/toolchain/ios.toolchain.xcode.cmake - freetype-2.13.2/builds/cmake/iOS.cmake - WORKING_DIRECTORY ${PROJECT_BINARY_DIR}) - execute_process(COMMAND ${BUILD_COMMAND_COMMON} - -DBUILD_SHARED_LIBS=${OGREDEPS_SHARED} - -DCMAKE_DISABLE_FIND_PACKAGE_PNG=TRUE # disable third-party deps - -DCMAKE_DISABLE_FIND_PACKAGE_HarfBuzz=TRUE - -DCMAKE_DISABLE_FIND_PACKAGE_BZip2=TRUE - -DCMAKE_DISABLE_FIND_PACKAGE_BrotliDec=TRUE - # workaround for broken iOS toolchain in freetype - -DPROJECT_SOURCE_DIR=${PROJECT_BINARY_DIR}/freetype-2.13.2 - ${PROJECT_BINARY_DIR}/freetype-2.13.2 - WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/freetype-2.13.2/objs) - execute_process(COMMAND ${CMAKE_COMMAND} - --build ${PROJECT_BINARY_DIR}/freetype-2.13.2/objs ${BUILD_COMMAND_OPTS}) - endif() - - if(MSVC OR MINGW OR SKBUILD) # other platforms dont need this - message(STATUS "Building SDL2") - file(DOWNLOAD - https://libsdl.org/release/SDL2-2.28.5.tar.gz - ${PROJECT_BINARY_DIR}/SDL2-2.28.5.tar.gz) - execute_process(COMMAND ${CMAKE_COMMAND} - -E tar xf SDL2-2.28.5.tar.gz WORKING_DIRECTORY ${PROJECT_BINARY_DIR}) - execute_process(COMMAND ${CMAKE_COMMAND} - -E make_directory ${PROJECT_BINARY_DIR}/SDL2-build) - execute_process(COMMAND ${BUILD_COMMAND_COMMON} - -DSDL_STATIC=FALSE - -DCMAKE_INSTALL_LIBDIR=lib - ${PROJECT_BINARY_DIR}/SDL2-2.28.5 - WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/SDL2-build) - execute_process(COMMAND ${CMAKE_COMMAND} - --build ${PROJECT_BINARY_DIR}/SDL2-build ${BUILD_COMMAND_OPTS}) - endif() - - if(MSVC OR MINGW OR SKBUILD) # other platforms dont need this - message(STATUS "Building zlib") # only needed for Assimp - file(DOWNLOAD - https://www.zlib.net/zlib-1.3.tar.gz - ${PROJECT_BINARY_DIR}/zlib-1.3.tar.gz - EXPECTED_HASH SHA256=ff0ba4c292013dbc27530b3a81e1f9a813cd39de01ca5e0f8bf355702efa593e) - execute_process(COMMAND ${CMAKE_COMMAND} - -E tar xf zlib-1.3.tar.gz WORKING_DIRECTORY ${PROJECT_BINARY_DIR}) - execute_process(COMMAND ${BUILD_COMMAND_COMMON} - -DBUILD_SHARED_LIBS=${OGREDEPS_SHARED} - ${PROJECT_BINARY_DIR}/zlib-1.3 - WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/zlib-1.3) - execute_process(COMMAND ${CMAKE_COMMAND} - --build ${PROJECT_BINARY_DIR}/zlib-1.3 ${BUILD_COMMAND_OPTS}) - - message(STATUS "Building Assimp") - file(DOWNLOAD - https://github.com/assimp/assimp/archive/refs/tags/v5.3.1.zip - ${PROJECT_BINARY_DIR}/v5.3.1.tar.gz) - execute_process(COMMAND ${CMAKE_COMMAND} - -E tar xf v5.3.1.tar.gz WORKING_DIRECTORY ${PROJECT_BINARY_DIR}) - execute_process(COMMAND ${BUILD_COMMAND_COMMON} - -DZLIB_ROOT=${OGREDEPS_PATH} - -DBUILD_SHARED_LIBS=OFF - -DASSIMP_BUILD_TESTS=OFF - -DASSIMP_NO_EXPORT=TRUE - -DASSIMP_BUILD_OGRE_IMPORTER=OFF - -DASSIMP_BUILD_ASSIMP_TOOLS=OFF - ${PROJECT_BINARY_DIR}/assimp-5.3.1 - WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/assimp-5.3.1) - execute_process(COMMAND ${CMAKE_COMMAND} - --build ${PROJECT_BINARY_DIR}/assimp-5.3.1 ${BUILD_COMMAND_OPTS}) - endif() - - message(STATUS "Building Bullet") - file(DOWNLOAD - https://github.com/bulletphysics/bullet3/archive/refs/tags/3.25.tar.gz - ${PROJECT_BINARY_DIR}/3.25.tar.gz) - execute_process(COMMAND ${CMAKE_COMMAND} - -E tar xf 3.25.tar.gz WORKING_DIRECTORY ${PROJECT_BINARY_DIR}) - execute_process(COMMAND ${BUILD_COMMAND_COMMON} - -DBUILD_SHARED_LIBS=OFF - -DINSTALL_LIBS=ON - -DCMAKE_POSITION_INDEPENDENT_CODE=ON - -DUSE_MSVC_RUNTIME_LIBRARY_DLL=ON - -DBUILD_PYBULLET=OFF - -DUSE_DOUBLE_PRECISION=OFF - -DBUILD_CPU_DEMOS=OFF - -DBUILD_BULLET2_DEMOS=OFF - -DBUILD_EXTRAS=OFF - -DBUILD_EGL=OFF - -DBUILD_ENET=OFF - -DBUILD_UNIT_TESTS=OFF - -DCMAKE_RELWITHDEBINFO_POSTFIX= # fixes FindBullet on MSVC - -DBUILD_CLSOCKET=OFF - ${PROJECT_BINARY_DIR}/bullet3-3.25 - WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/bullet3-3.25) - execute_process(COMMAND ${CMAKE_COMMAND} - --build ${PROJECT_BINARY_DIR}/bullet3-3.25 ${BUILD_COMMAND_OPTS}) - set(BULLET_ROOT ${OGREDEPS_PATH}) -endif() - -####################################################################### -# Core dependencies -####################################################################### - -# Find FreeImage -find_package(FreeImage) -macro_log_feature(FreeImage_FOUND "freeimage" "Support for commonly used graphics image formats" "http://freeimage.sourceforge.net") - -# Find FreeType -find_package(Freetype) -macro_log_feature(FREETYPE_FOUND "freetype" "Portable font engine" "http://www.freetype.org") - -# Find X11 -if (UNIX AND NOT APPLE AND NOT ANDROID AND NOT EMSCRIPTEN) - find_package(X11 REQUIRED) - macro_log_feature(X11_FOUND "X11" "X Window system" "http://www.x.org") -endif () - - -####################################################################### -# RenderSystem dependencies -####################################################################### - -# Find OpenGL -if(NOT ANDROID AND NOT EMSCRIPTEN) - find_package(OpenGL) - macro_log_feature(OPENGL_FOUND "OpenGL" "Support for the OpenGL and OpenGL 3+ render systems" "http://www.opengl.org/") -endif() - -# Find OpenGL ES 2.x -find_package(OpenGLES2) -macro_log_feature(OPENGLES2_FOUND "OpenGL ES 2.x" "Support for the OpenGL ES 2.x render system" "http://www.khronos.org/opengles/") - -# Find DirectX -if(WIN32) - find_package(DirectX) - macro_log_feature(DirectX9_FOUND "DirectX9" "Support for the DirectX render system" "http://msdn.microsoft.com/en-us/directx/") - - find_package(DirectX11) - macro_log_feature(DirectX11_FOUND "DirectX11" "Support for the DirectX11 render system" "http://msdn.microsoft.com/en-us/directx/") - - if(OGRE_CONFIG_ENABLE_QUAD_BUFFER_STEREO) - # Find DirectX Stereo Driver Libraries - find_package(NVAPI) - macro_log_feature(NVAPI_FOUND "NVAPI" "Support NVIDIA stereo with the DirectX render system" "https://developer.nvidia.com/nvapi") - - find_package(AMDQBS) - macro_log_feature(AMDQBS_FOUND "AMDQBS" "Support AMD stereo with the DirectX render system" "http://developer.amd.com/tools-and-sdks/graphics-development/amd-quad-buffer-sdk/") - endif() -endif() - -####################################################################### -# Additional features -####################################################################### - -# Find Cg -if (NOT (APPLE_IOS OR WINDOWS_STORE OR WINDOWS_PHONE OR ANDROID OR EMSCRIPTEN)) - find_package(Cg) - macro_log_feature(Cg_FOUND "cg" "C for graphics shader language" "http://developer.nvidia.com/object/cg_toolkit.html") -endif () - -# Find Vulkan SDK -macro_log_feature(ENV{VULKAN_SDK} "Vulkan SDK" "Vulkan RenderSystem, glslang Plugin. Alternatively use system packages" "https://vulkan.lunarg.com/") - -# OpenEXR -find_package(OpenEXR) -macro_log_feature(OPENEXR_FOUND "OpenEXR" "Load High dynamic range images" "http://www.openexr.com/") - -# Python -set(Python_ADDITIONAL_VERSIONS 3.4) # allows using python3 on Ubuntu 14.04 -find_package(PythonInterp) -find_package(PythonLibs) -macro_log_feature(PYTHONLIBS_FOUND "Python" "Language bindings to use OGRE from Python" "http://www.python.org/") - -# SWIG -find_package(SWIG 3.0.8 QUIET) -macro_log_feature(SWIG_FOUND "SWIG" "Language bindings (Python, Java, C#) for OGRE" "http://www.swig.org/") - -# pugixml -find_package(pugixml QUIET) -macro_log_feature(pugixml_FOUND "pugixml" "Needed for XMLConverter and DotScene Plugin" "https://pugixml.org/") - -# Find zlib -find_package(ZLIB) -macro_log_feature(ZLIB_FOUND "zlib" "Simple data compression library" "http://www.zlib.net") - -# Assimp -find_package(assimp QUIET) -macro_log_feature(assimp_FOUND "Assimp" "Needed for the AssimpLoader Plugin" "https://www.assimp.org/") - -# Bullet -find_package(Bullet QUIET) -macro_log_feature(BULLET_FOUND "Bullet" "Bullet physics" "https://pybullet.org") - -if(assimp_FOUND) - # workaround horribly broken assimp cmake, fixed with assimp 5.1 - add_library(fix::assimp INTERFACE IMPORTED) - set_target_properties(fix::assimp PROPERTIES - INTERFACE_LINK_LIBRARIES "${ASSIMP_LIBRARIES};pugixml" - INTERFACE_LINK_DIRECTORIES "${ASSIMP_LIBRARY_DIRS}" - ) - if(EXISTS "${ASSIMP_INCLUDE_DIRS}") - set_target_properties(fix::assimp PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${ASSIMP_INCLUDE_DIRS}") - endif() -endif() - -####################################################################### -# Samples dependencies -####################################################################### - -# Find sdl2 -if(NOT ANDROID AND NOT EMSCRIPTEN) - # find script does not work in cross compilation environment - find_package(SDL2 QUIET) - macro_log_feature(SDL2_FOUND "SDL2" "Simple DirectMedia Library needed for input handling in samples" "https://www.libsdl.org/") - if(SDL2_FOUND AND NOT TARGET SDL2::SDL2) - add_library(SDL2::SDL2 INTERFACE IMPORTED) - set_target_properties(SDL2::SDL2 PROPERTIES - INTERFACE_INCLUDE_DIRECTORIES "${SDL2_INCLUDE_DIRS}" - INTERFACE_LINK_LIBRARIES "${SDL2_LIBRARIES}" - ) - endif() - - find_package(QT NAMES Qt6 Qt5 COMPONENTS Core Gui QUIET CONFIG) - find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core Gui QUIET CONFIG) - - macro_log_feature(QT_FOUND "Qt" "optional integration with the Qt Library for window creation and input" "http://www.qt.io/") -endif() - -####################################################################### -# Tools -####################################################################### - -find_package(Doxygen QUIET) -macro_log_feature(DOXYGEN_FOUND "Doxygen" "Tool for building API documentation" "http://doxygen.org") - -# Find Softimage SDK -find_package(Softimage) -macro_log_feature(Softimage_FOUND "Softimage" "Softimage SDK needed for building XSIExporter" "") diff --git a/CMake/InstallDependencies.cmake b/CMake/InstallDependencies.cmake deleted file mode 100644 index 83f8f3a1496..00000000000 --- a/CMake/InstallDependencies.cmake +++ /dev/null @@ -1,173 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -##################################################### -# Install dependencies -##################################################### - -set(OGRE_DEP_DIR ${OGREDEPS_PATH}) - -set(INITVAL FALSE) -if(WIN32 OR APPLE OR EMSCRIPTEN) - set(INITVAL TRUE) -endif() -option(OGRE_INSTALL_DEPENDENCIES "Install dependency libs needed for samples" ${INITVAL}) -cmake_dependent_option(OGRE_COPY_DEPENDENCIES "Copy dependency libs to the build directory" TRUE "WIN32" FALSE) - -macro(install_debug INPUT) - if (EXISTS ${OGRE_DEP_DIR}/bin/debug/${INPUT}) - if (IS_DIRECTORY ${OGRE_DEP_DIR}/bin/debug/${INPUT}) - install(DIRECTORY ${OGRE_DEP_DIR}/bin/debug/${INPUT} DESTINATION bin/debug CONFIGURATIONS Debug) - else () - install(FILES ${OGRE_DEP_DIR}/bin/debug/${INPUT} DESTINATION bin/debug CONFIGURATIONS Debug) - endif () - else() - message(send_error "${OGRE_DEP_DIR}/bin/debug/${INPUT} did not exist, can't install!") - endif () -endmacro() - -macro(install_release INPUT) - if (EXISTS ${OGRE_DEP_DIR}/bin/release/${INPUT}) - if (IS_DIRECTORY ${OGRE_DEP_DIR}/bin/release/${INPUT}) - install(DIRECTORY ${OGRE_DEP_DIR}/bin/release/${INPUT} DESTINATION bin/release CONFIGURATIONS Release None "") - install(DIRECTORY ${OGRE_DEP_DIR}/bin/release/${INPUT} DESTINATION bin/relwithdebinfo CONFIGURATIONS RelWithDebInfo) - install(DIRECTORY ${OGRE_DEP_DIR}/bin/release/${INPUT} DESTINATION bin/minsizerel CONFIGURATIONS MinSizeRel) - else () - install(FILES ${OGRE_DEP_DIR}/bin/release/${INPUT} DESTINATION bin/release CONFIGURATIONS Release None "") - install(FILES ${OGRE_DEP_DIR}/bin/release/${INPUT} DESTINATION bin/relwithdebinfo CONFIGURATIONS RelWithDebInfo) - install(FILES ${OGRE_DEP_DIR}/bin/release/${INPUT} DESTINATION bin/minsizerel CONFIGURATIONS MinSizeRel) - endif () - else() - message(send_error "${OGRE_DEP_DIR}/bin/release/${INPUT} did not exist, can't install!") - endif () -endmacro() - -macro(copy_debug INPUT) - if (EXISTS ${OGRE_DEP_DIR}/lib/debug/${INPUT}) - if (MINGW OR NMAKE) - configure_file(${OGRE_DEP_DIR}/lib/debug/${INPUT} ${PROJECT_BINARY_DIR}/lib/${INPUT} COPYONLY) - else () - if (IS_DIRECTORY ${OGRE_DEP_DIR}/lib/debug/${INPUT}) - install(DIRECTORY ${OGRE_DEP_DIR}/lib/debug/${INPUT} DESTINATION lib/debug) - else () - configure_file(${OGRE_DEP_DIR}/lib/debug/${INPUT} ${PROJECT_BINARY_DIR}/lib/debug/${INPUT} COPYONLY) - endif () - endif () - endif () -endmacro() - -macro(copy_release INPUT) - if (EXISTS ${OGRE_DEP_DIR}/lib/release/${INPUT}) - if (MINGW OR NMAKE) - configure_file(${OGRE_DEP_DIR}/lib/release/${INPUT} ${PROJECT_BINARY_DIR}/lib/${INPUT} COPYONLY) - else () - if (IS_DIRECTORY ${OGRE_DEP_DIR}/lib/release/${INPUT}) - install(DIRECTORY ${OGRE_DEP_DIR}/lib/release/${INPUT} DESTINATION lib/release CONFIGURATIONS Release None "") - install(DIRECTORY ${OGRE_DEP_DIR}/lib/release/${INPUT} DESTINATION lib/relwithdebinfo CONFIGURATIONS RelWithDebInfo) - install(DIRECTORY ${OGRE_DEP_DIR}/lib/release/${INPUT} DESTINATION lib/minsizerel CONFIGURATIONS MinSizeRel) - else () - configure_file(${OGRE_DEP_DIR}/lib/release/${INPUT} ${PROJECT_BINARY_DIR}/lib/release/${INPUT} COPYONLY) - configure_file(${OGRE_DEP_DIR}/lib/release/${INPUT} ${PROJECT_BINARY_DIR}/lib/relwithdebinfo/${INPUT} COPYONLY) - configure_file(${OGRE_DEP_DIR}/lib/release/${INPUT} ${PROJECT_BINARY_DIR}/lib/minsizerel/${INPUT} COPYONLY) - endif () - endif () - endif () -endmacro () - -if (OGRE_INSTALL_DEPENDENCIES) - if (OGRE_STATIC) - # for static builds, projects must link against all Ogre dependencies themselves, so copy full include and lib dir - if (EXISTS ${OGRE_DEP_DIR}/include/) - install(DIRECTORY ${OGRE_DEP_DIR}/include/ DESTINATION include) - endif () - - if (EXISTS ${OGRE_DEP_DIR}/lib/) - install(DIRECTORY ${OGRE_DEP_DIR}/lib/ DESTINATION ${OGRE_LIB_DIRECTORY}) - endif () - else () - if(WIN32 AND MINGW) - install(FILES DESTINATION lib/debug CONFIGURATIONS Debug) - install(FILES DESTINATION lib/relwithdebinfo CONFIGURATIONS RelWithDebInfo) - install(FILES DESTINATION lib/release CONFIGURATIONS Release) - install(FILES DESTINATION lib/minsizerel CONFIGURATIONS MinSizeRel) - elseif(UNIX) - if (EXISTS ${OGRE_DEP_DIR}/lib/) - install(DIRECTORY ${OGRE_DEP_DIR}/lib/ DESTINATION ${OGRE_LIB_DIRECTORY}) - endif() - endif() - - if (EXISTS ${OGRE_DEP_DIR}/bin/) - install(DIRECTORY ${OGRE_DEP_DIR}/bin/ DESTINATION ${OGRE_BIN_DIRECTORY}) - endif () - endif () - - if(OGRE_BUILD_DEPENDENCIES AND OGRE_BUILD_COMPONENT_BULLET) - install(DIRECTORY ${OGRE_DEP_DIR}/include/bullet DESTINATION include) - endif() - - if(WIN32) - if(OGRE_BUILD_SAMPLES OR OGRE_BUILD_TESTS) - if(EXISTS "${SDL2_BINARY}") - file(COPY ${SDL2_BINARY} DESTINATION ${PROJECT_BINARY_DIR}/bin/debug) - file(COPY ${SDL2_BINARY} DESTINATION ${PROJECT_BINARY_DIR}/bin/release) - file(COPY ${SDL2_BINARY} DESTINATION ${PROJECT_BINARY_DIR}/bin/relwithdebinfo) - file(COPY ${SDL2_BINARY} DESTINATION ${PROJECT_BINARY_DIR}/bin/minsizerel) - endif() - endif() - - if (OGRE_BUILD_PLUGIN_CG) - # if MinGW or NMake, the release/debug cg.dll's would conflict, so just pick one - if (MINGW OR (CMAKE_GENERATOR STREQUAL "NMake Makefiles")) - if (CMAKE_BUILD_TYPE STREQUAL "Debug") - install_debug(cg.dll) - else () - install_release(cg.dll) - endif () - else () - install_debug(cg.dll) - install_release(cg.dll) - endif () - endif () # OGRE_BUILD_PLUGIN_CG - - # install GLES2 dlls - if (OGRE_BUILD_RENDERSYSTEM_GLES2) - install_debug(libGLESv2.dll) - install_release(libEGL.dll) - endif () - endif () # WIN32 -endif () - -if (OGRE_COPY_DEPENDENCIES) - # copy the required DLLs to the build directory - file(GLOB DLLS ${OGRE_DEP_DIR}/bin/*.dll) - file(COPY ${DLLS} DESTINATION ${PROJECT_BINARY_DIR}/bin/debug) - file(COPY ${DLLS} DESTINATION ${PROJECT_BINARY_DIR}/bin/release) - file(COPY ${DLLS} DESTINATION ${PROJECT_BINARY_DIR}/bin/relwithdebinfo) - file(COPY ${DLLS} DESTINATION ${PROJECT_BINARY_DIR}/bin/minsizerel) - - if (OGRE_BUILD_PLUGIN_CG) - if (EXISTS ${Cg_BINARY_DBG} AND EXISTS ${Cg_BINARY_REL}) - # if MinGW or NMake, the release/debug cg.dll's would conflict, so just pick one - if (MINGW OR (CMAKE_GENERATOR STREQUAL "NMake Makefiles")) - if (CMAKE_BUILD_TYPE STREQUAL "Debug") - file(COPY ${Cg_BINARY_DBG} DESTINATION ${PROJECT_BINARY_DIR}/bin/debug) - else () - file(COPY ${Cg_BINARY_REL} DESTINATION ${PROJECT_BINARY_DIR}/bin/release) - file(COPY ${Cg_BINARY_REL} DESTINATION ${PROJECT_BINARY_DIR}/bin/relwithdebinfo) - file(COPY ${Cg_BINARY_REL} DESTINATION ${PROJECT_BINARY_DIR}/bin/minsizerel) - endif () - else () - file(COPY ${Cg_BINARY_DBG} DESTINATION ${PROJECT_BINARY_DIR}/bin/debug) - file(COPY ${Cg_BINARY_REL} DESTINATION ${PROJECT_BINARY_DIR}/bin/release) - file(COPY ${Cg_BINARY_REL} DESTINATION ${PROJECT_BINARY_DIR}/bin/relwithdebinfo) - file(COPY ${Cg_BINARY_REL} DESTINATION ${PROJECT_BINARY_DIR}/bin/minsizerel) - endif () - endif() - endif() -endif () diff --git a/CMake/InstallResources.cmake b/CMake/InstallResources.cmake deleted file mode 100644 index ad531b3cfe5..00000000000 --- a/CMake/InstallResources.cmake +++ /dev/null @@ -1,261 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -################################################################## -# Generate and install the config files needed for the samples -################################################################## - -if (NOT OGRE_MEDIA_PATH) - if (WIN32) - set(OGRE_MEDIA_PATH "Media") - set(OGRE_MEDIA_DIR_REL "${CMAKE_INSTALL_PREFIX}/${OGRE_MEDIA_PATH}") - elseif (APPLE) - set(OGRE_MEDIA_PATH "Media") - if(APPLE_IOS) - set(OGRE_MEDIA_DIR_REL "${OGRE_MEDIA_PATH}") - else() - set(OGRE_MEDIA_DIR_REL "../${OGRE_MEDIA_PATH}") - endif() - elseif (UNIX) - set(OGRE_MEDIA_PATH "share/OGRE-${OGRE_SOVERSION}/Media") - set(OGRE_MEDIA_DIR_REL "./Media") - endif() -else () - set(OGRE_MEDIA_DIR_REL "${CMAKE_INSTALL_PREFIX}/${OGRE_MEDIA_PATH}") -endif() - -if (NOT OGRE_PLUGINS_PATH) - if (WIN32) - set(OGRE_PLUGINS_PATH "${OGRE_BIN_DIRECTORY}") - set(OGRE_PLUGIN_DIR_REL "${CMAKE_INSTALL_PREFIX}/${OGRE_BIN_DIRECTORY}") - else () - set(OGRE_PLUGINS_PATH "${OGRE_LIB_DIRECTORY}/OGRE") - set(OGRE_PLUGIN_DIR_REL "${CMAKE_INSTALL_PREFIX}/${OGRE_LIB_DIRECTORY}/OGRE") - endif() -else () - set(OGRE_PLUGIN_DIR_REL "${CMAKE_INSTALL_PREFIX}/${OGRE_PLUGINS_PATH}") -endif() - -if (NOT OGRE_CFG_INSTALL_PATH) - if (WIN32 OR APPLE) - set(OGRE_CFG_INSTALL_PATH "${OGRE_BIN_DIRECTORY}") - elseif (UNIX) - set(OGRE_CFG_INSTALL_PATH "share/OGRE-${OGRE_SOVERSION}") - endif() -endif() - -if (WIN32) - set(OGRE_TEST_MEDIA_DIR_REL "../Tests/${OGRE_MEDIA_PATH}") - set(OGRE_SAMPLES_DIR_REL ".") -elseif (APPLE) - if(APPLE_IOS) - set(OGRE_TEST_MEDIA_DIR_REL "../../Tests/${OGRE_MEDIA_PATH}") - else() - set(OGRE_TEST_MEDIA_DIR_REL "${CMAKE_INSTALL_PREFIX}/Tests/Media") - endif() - # these are resolved relative to the app bundle - set(OGRE_SAMPLES_DIR_REL "Contents/Plugins/") - set(OGRE_CFG_INSTALL_PATH "bin") -elseif (UNIX) - set(OGRE_TEST_MEDIA_DIR_REL "${CMAKE_INSTALL_PREFIX}/Tests/Media") - set(OGRE_SAMPLES_DIR_REL "${CMAKE_INSTALL_PREFIX}/${OGRE_LIB_DIRECTORY}/OGRE/Samples") -endif () - -# generate OgreConfigPaths.h -configure_file(${OGRE_TEMPLATES_DIR}/OgreConfigPaths.h.in ${PROJECT_BINARY_DIR}/include/OgreConfigPaths.h @ONLY) - -if(WIN32) - # we want relative paths inside the SDK - set(OGRE_PLUGIN_DIR_REL ".") - if (WINDOWS_STORE OR WINDOWS_PHONE) - set(OGRE_MEDIA_DIR_REL "${OGRE_MEDIA_PATH}") - set(OGRE_TEST_MEDIA_DIR_REL "${OGRE_MEDIA_PATH}") - else() - set(OGRE_MEDIA_DIR_REL "../${OGRE_MEDIA_PATH}") - set(OGRE_TEST_MEDIA_DIR_REL "../Tests/${OGRE_MEDIA_PATH}") - endif() -endif() - -# configure plugins.cfg -if (NOT OGRE_BUILD_RENDERSYSTEM_D3D9) - set(OGRE_COMMENT_RENDERSYSTEM_D3D9 "#") -endif () -if (NOT OGRE_BUILD_RENDERSYSTEM_D3D11) - set(OGRE_COMMENT_RENDERSYSTEM_D3D11 "#") -endif () -if (NOT MINGW AND CMAKE_SYSTEM_VERSION VERSION_LESS "6.0") - set(OGRE_COMMENT_RENDERSYSTEM_D3D11 "#") -endif () -if (NOT OGRE_BUILD_RENDERSYSTEM_GL) - set(OGRE_COMMENT_RENDERSYSTEM_GL "#") -endif () -if (NOT OGRE_BUILD_RENDERSYSTEM_GL3PLUS) - set(OGRE_COMMENT_RENDERSYSTEM_GL3PLUS "#") -endif () -if (NOT OGRE_BUILD_RENDERSYSTEM_GLES2) - set(OGRE_COMMENT_RENDERSYSTEM_GLES2 "#") -endif () -if (NOT OGRE_BUILD_RENDERSYSTEM_METAL) - set(OGRE_COMMENT_RENDERSYSTEM_METAL "#") -endif () -if (NOT OGRE_BUILD_RENDERSYSTEM_TINY) - set(OGRE_COMMENT_RENDERSYSTEM_TINY "#") -endif () -if (NOT OGRE_BUILD_RENDERSYSTEM_VULKAN) - set(OGRE_COMMENT_RENDERSYSTEM_VULKAN "#") -endif () -if (NOT OGRE_BUILD_PLUGIN_BSP) - set(OGRE_COMMENT_PLUGIN_BSP "#") -endif () -if (NOT OGRE_BUILD_PLUGIN_OCTREE) - set(OGRE_COMMENT_PLUGIN_OCTREE "#") -endif () -if (NOT OGRE_BUILD_PLUGIN_PCZ) - set(OGRE_COMMENT_PLUGIN_PCZ "#") -endif () -if (NOT OGRE_BUILD_PLUGIN_PFX) - set(OGRE_COMMENT_PLUGIN_PARTICLEFX "#") -endif () -if (NOT OGRE_BUILD_PLUGIN_CG) - set(OGRE_COMMENT_PLUGIN_CG "#") -endif () -if (NOT OGRE_BUILD_PLUGIN_GLSLANG) - set(OGRE_COMMENT_PLUGIN_GLSLANG "#") -endif () -if (NOT OGRE_BUILD_PLUGIN_STBI) - set(OGRE_COMMENT_PLUGIN_STBI "#") -endif () -if (NOT OGRE_BUILD_PLUGIN_RSIMAGE OR OGRE_BUILD_PLUGIN_STBI) - # has to be explicitely requested by disabeling STBI - set(OGRE_COMMENT_PLUGIN_RSIMAGE "#") -endif () -if (NOT OGRE_BUILD_PLUGIN_DOT_SCENE) - set(OGRE_COMMENT_PLUGIN_DOT_SCENE "#") -endif () -if (NOT OGRE_BUILD_PLUGIN_ASSIMP) - set(OGRE_COMMENT_PLUGIN_ASSIMP "#") -endif () -if (NOT OGRE_BUILD_PLUGIN_FREEIMAGE OR OGRE_BUILD_PLUGIN_STBI OR OGRE_BUILD_PLUGIN_RSIMAGE) - # has to be explicitely requested by disabeling STBI - set(OGRE_COMMENT_PLUGIN_FREEIMAGE "#") -endif () -if (NOT OGRE_BUILD_PLUGIN_EXRCODEC OR OGRE_COMMENT_PLUGIN_FREEIMAGE OR OGRE_BUILD_PLUGIN_RSIMAGE) - # overlaps with freeimage - set(OGRE_COMMENT_PLUGIN_EXRCODEC "#") -endif () -if(NOT OGRE_BUILD_TESTS) - set(OGRE_COMMENT_PLAYPENTESTS "#") -endif() - -set(OGRE_SAMPLE_RESOURCES "") - -set(OGRE_CORE_MEDIA_DIR "${OGRE_MEDIA_DIR_REL}") - -# CREATE CONFIG FILES - INSTALL VERSIONS - -if(OGRE_INSTALL_SAMPLES) - # deal with sample resources - configure_file(${OGRE_TEMPLATES_DIR}/sample_resources.cfg.in ${PROJECT_BINARY_DIR}/sample_resources.cfg) - file(READ ${PROJECT_BINARY_DIR}/sample_resources.cfg OGRE_SAMPLE_RESOURCES) -endif() - -configure_file(${OGRE_TEMPLATES_DIR}/resources.cfg.in ${PROJECT_BINARY_DIR}/inst/bin/resources.cfg) -configure_file(${OGRE_TEMPLATES_DIR}/plugins.cfg.in ${PROJECT_BINARY_DIR}/inst/bin/plugins.cfg) -configure_file(${OGRE_TEMPLATES_DIR}/samples.cfg.in ${PROJECT_BINARY_DIR}/inst/bin/samples.cfg) - -# install resource files -install(FILES - ${PROJECT_BINARY_DIR}/inst/bin/resources.cfg - ${PROJECT_BINARY_DIR}/inst/bin/plugins.cfg - DESTINATION "${OGRE_CFG_INSTALL_PATH}" -) - -# CREATE CONFIG FILES - BUILD DIR VERSIONS -if (NOT (APPLE_IOS OR WINDOWS_STORE OR WINDOWS_PHONE)) - set(OGRE_MEDIA_DIR_REL "${PROJECT_SOURCE_DIR}/Samples/Media") - set(OGRE_CORE_MEDIA_DIR "${PROJECT_SOURCE_DIR}/Media") - set(OGRE_TEST_MEDIA_DIR_REL "${PROJECT_SOURCE_DIR}/Tests/Media") -else () - # iOS needs to use relative paths in the config files - set(OGRE_MEDIA_DIR_REL "${OGRE_MEDIA_PATH}") - set(OGRE_CORE_MEDIA_DIR "${OGRE_MEDIA_PATH}") - set(OGRE_TEST_MEDIA_DIR_REL "${OGRE_MEDIA_PATH}") -endif () - -if (WIN32) - set(OGRE_PLUGIN_DIR_REL ".") - set(OGRE_SAMPLES_DIR_REL ".") -elseif (APPLE) - set(OGRE_PLUGIN_DIR_REL "Contents/Frameworks/") - set(OGRE_SAMPLES_DIR_REL "Contents/Plugins/") -elseif (UNIX) - set(OGRE_PLUGIN_DIR_REL "${PROJECT_BINARY_DIR}/lib") - set(OGRE_SAMPLES_DIR_REL "${PROJECT_BINARY_DIR}/lib") -endif () - -if(OGRE_BUILD_SAMPLES) - # deal with sample resources - configure_file(${OGRE_TEMPLATES_DIR}/sample_resources.cfg.in ${PROJECT_BINARY_DIR}/sample_resources.cfg) - file(READ ${PROJECT_BINARY_DIR}/sample_resources.cfg OGRE_SAMPLE_RESOURCES) -endif() - -if (WINDOWS_STORE OR WINDOWS_PHONE OR EMSCRIPTEN) - # These platfroms requires all resources to be packaged inside the application bundle, - # therefore install versions of configs would be copied and added as content file to each project. -elseif (MSVC AND NOT NMAKE) - configure_file(${OGRE_TEMPLATES_DIR}/resources.cfg.in ${PROJECT_BINARY_DIR}/bin/release/resources.cfg) - configure_file(${OGRE_TEMPLATES_DIR}/resources.cfg.in ${PROJECT_BINARY_DIR}/bin/relwithdebinfo/resources.cfg) - configure_file(${OGRE_TEMPLATES_DIR}/resources.cfg.in ${PROJECT_BINARY_DIR}/bin/minsizerel/resources.cfg) - configure_file(${OGRE_TEMPLATES_DIR}/resources.cfg.in ${PROJECT_BINARY_DIR}/bin/debug/resources.cfg) - - configure_file(${OGRE_TEMPLATES_DIR}/plugins.cfg.in ${PROJECT_BINARY_DIR}/bin/release/plugins.cfg) - configure_file(${OGRE_TEMPLATES_DIR}/plugins.cfg.in ${PROJECT_BINARY_DIR}/bin/relwithdebinfo/plugins.cfg) - configure_file(${OGRE_TEMPLATES_DIR}/plugins.cfg.in ${PROJECT_BINARY_DIR}/bin/minsizerel/plugins.cfg) - configure_file(${OGRE_TEMPLATES_DIR}/plugins.cfg.in ${PROJECT_BINARY_DIR}/bin/debug/plugins.cfg) - - configure_file(${OGRE_TEMPLATES_DIR}/samples.cfg.in ${PROJECT_BINARY_DIR}/bin/release/samples.cfg) - configure_file(${OGRE_TEMPLATES_DIR}/samples.cfg.in ${PROJECT_BINARY_DIR}/bin/relwithdebinfo/samples.cfg) - configure_file(${OGRE_TEMPLATES_DIR}/samples.cfg.in ${PROJECT_BINARY_DIR}/bin/minsizerel/samples.cfg) - configure_file(${OGRE_TEMPLATES_DIR}/samples.cfg.in ${PROJECT_BINARY_DIR}/bin/debug/samples.cfg) -else() # other OS only need one cfg file - # create resources.cfg - configure_file(${OGRE_TEMPLATES_DIR}/resources.cfg.in ${PROJECT_BINARY_DIR}/bin/resources.cfg) - # create plugins.cfg - configure_file(${OGRE_TEMPLATES_DIR}/plugins.cfg.in ${PROJECT_BINARY_DIR}/bin/plugins.cfg) - # create samples.cfg - configure_file(${OGRE_TEMPLATES_DIR}/samples.cfg.in ${PROJECT_BINARY_DIR}/bin/samples.cfg) -endif () - - -# Create the CMake package files -include(CMakePackageConfigHelpers) - -if (NOT OGRE_CMAKE_DIR) - if(WIN32 OR APPLE) - set(OGRE_CMAKE_DIR "CMake") - else() - set(OGRE_CMAKE_DIR "${OGRE_LIB_DIRECTORY}/OGRE/cmake") - endif() -endif() - -configure_package_config_file(${OGRE_TEMPLATES_DIR}/OGREConfig.cmake.in ${PROJECT_BINARY_DIR}/cmake/OGREConfig.cmake - INSTALL_DESTINATION ${OGRE_CMAKE_DIR} - PATH_VARS OGRE_MEDIA_PATH OGRE_PLUGINS_PATH OGRE_CFG_INSTALL_PATH CMAKE_INSTALL_PREFIX) -write_basic_package_version_file( - ${PROJECT_BINARY_DIR}/cmake/OGREConfigVersion.cmake - VERSION ${OGRE_VERSION} - COMPATIBILITY SameMajorVersion) -install(FILES - ${PROJECT_BINARY_DIR}/cmake/OGREConfig.cmake - ${PROJECT_BINARY_DIR}/cmake/OGREConfigVersion.cmake - DESTINATION ${OGRE_CMAKE_DIR} -) -install(EXPORT OgreTargetsRelease CONFIGURATIONS Release MinSizeRel None "" DESTINATION ${OGRE_CMAKE_DIR} FILE OgreTargets.cmake) -install(EXPORT OgreTargetsRelWithDebInfo CONFIGURATIONS RelWithDebInfo DESTINATION ${OGRE_CMAKE_DIR} FILE OgreTargets.cmake) -install(EXPORT OgreTargetsDebug CONFIGURATIONS Debug DESTINATION ${OGRE_CMAKE_DIR} FILE OgreTargets.cmake) diff --git a/CMake/OgreFeatureSummary.cmake b/CMake/OgreFeatureSummary.cmake deleted file mode 100644 index a344c7ade77..00000000000 --- a/CMake/OgreFeatureSummary.cmake +++ /dev/null @@ -1,251 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# This file prints a summary of the selected build features. - -set(_features "\n") -set(_features "${_features}----------------------------------------------------------------------------\n") -set(_features "${_features} FEATURE SUMMARY\n") -set(_features "${_features}----------------------------------------------------------------------------\n\n") - -#summarise components -if (OGRE_BUILD_COMPONENT_BITES) - set(_components "${_components} + Bites\n") - if(Qt5_FOUND) - set(_components "${_components} + Bites Qt Support\n") - endif() -endif () -if (OGRE_BUILD_COMPONENT_BULLET) - set(_components "${_components} + Bullet\n") -endif() -if (OGRE_BUILD_COMPONENT_MESHLODGENERATOR) - set(_components "${_components} + MeshLodGenerator\n") -endif () -if (OGRE_BUILD_COMPONENT_OVERLAY) - set(_components "${_components} + Overlay\n") - - if (OGRE_BUILD_COMPONENT_OVERLAY_IMGUI) - set(_components "${_components} + Overlay Dear Imgui\n") - endif () -endif () -if (OGRE_BUILD_COMPONENT_PAGING) - set(_components "${_components} + Paging\n") -endif () -if (OGRE_BUILD_COMPONENT_PROPERTY) - set(_components "${_components} + Property\n") -endif () -if (OGRE_BUILD_COMPONENT_PYTHON) - set(_components "${_components} + Python [BETA]\n") -endif () -if (OGRE_BUILD_COMPONENT_JAVA) - set(_components "${_components} + Java/ JNI [BETA]\n") -endif () -if (OGRE_BUILD_COMPONENT_CSHARP) - set(_components "${_components} + C#/ .NET [BETA]\n") -endif () -if (OGRE_BUILD_COMPONENT_RTSHADERSYSTEM) - set(_components "${_components} + RTShader System\n") - - if (OGRE_BUILD_RTSHADERSYSTEM_SHADERS) - set(_components "${_components} + RTShader System Shaders\n") - endif () -endif () -if (OGRE_BUILD_COMPONENT_TERRAIN) - set(_components "${_components} + Terrain\n") -endif () -if (OGRE_BUILD_COMPONENT_VOLUME) - set(_components "${_components} + Volume\n") -endif () - -if (DEFINED _components) - set(_features "${_features}Building components:\n${_components}") -endif () - -# summarise plugins -if (OGRE_BUILD_PLUGIN_BSP) - set(_plugins "${_plugins} + BSP scene manager\n") -endif () -if (OGRE_BUILD_PLUGIN_CG) - set(_plugins "${_plugins} + Cg program manager\n") -endif () -if (OGRE_BUILD_PLUGIN_GLSLANG) - set(_plugins "${_plugins} + Glslang (SPIRV) program manager\n") -endif () -if (OGRE_BUILD_PLUGIN_OCTREE) - set(_plugins "${_plugins} + Octree scene manager\n") -endif () -if(OGRE_BUILD_PLUGIN_EXRCODEC) - set(_plugins "${_plugins} + OpenEXR image codec\n") -endif() -if (OGRE_BUILD_PLUGIN_STBI) - set(_plugins "${_plugins} + STBI codec (generic)\n") -endif () -if (OGRE_BUILD_PLUGIN_FREEIMAGE) - set(_plugins "${_plugins} + FreeImage codec (generic)\n") -endif () -if (OGRE_BUILD_PLUGIN_PCZ) - set(_plugins "${_plugins} + Portal connected zone scene manager\n") -endif () -if (OGRE_BUILD_PLUGIN_PFX) - set(_plugins "${_plugins} + Particle FX\n") -endif () -if (OGRE_BUILD_PLUGIN_DOT_SCENE) - set(_plugins "${_plugins} + DotScene loader\n") -endif () -if (OGRE_BUILD_PLUGIN_ASSIMP) - set(_plugins "${_plugins} + Assimp loader (.obj, .ply, .fbx and more)\n") -endif () - -if (DEFINED _plugins) - set(_features "${_features}Building plugins:\n${_plugins}") -endif () - -# summarise rendersystems -if (OGRE_BUILD_RENDERSYSTEM_D3D9) - set(_rendersystems "${_rendersystems} + Direct3D 9\n") -endif () -if (OGRE_BUILD_RENDERSYSTEM_D3D11) - set(_rendersystems "${_rendersystems} + Direct3D 11\n") -endif () -if (OGRE_BUILD_RENDERSYSTEM_GL) - set(_rendersystems "${_rendersystems} + OpenGL\n") -endif () -if (OGRE_BUILD_RENDERSYSTEM_GL3PLUS) - set(_rendersystems "${_rendersystems} + OpenGL 3+\n") -endif () -if (OGRE_BUILD_RENDERSYSTEM_GLES2) - set(_rendersystems "${_rendersystems} + OpenGL ES2/ ES3\n") -endif () -if (OGRE_CONFIG_ENABLE_GLES2_GLSL_OPTIMISER) - set(_rendersystems "${_rendersystems} + OpenGL ES2 GLSL Optimiser\n") -endif () -if (OGRE_CONFIG_ENABLE_GLES2_CG_SUPPORT) - set(_rendersystems "${_rendersystems} + OpenGL ES2 Cg Support\n") -endif () -if (OGRE_CONFIG_ENABLE_GL_STATE_CACHE_SUPPORT) - set(_rendersystems "${_rendersystems} + OpenGL (all) StateCacheManager\n") -endif () -if (OGRE_BUILD_RENDERSYSTEM_METAL) - set(_rendersystems "${_rendersystems} + Metal [EXPERIMENTAL]\n") -endif () -if (OGRE_BUILD_RENDERSYSTEM_TINY) - set(_rendersystems "${_rendersystems} + Tiny (Software) [EXPERIMENTAL]\n") -endif () -if (OGRE_BUILD_RENDERSYSTEM_VULKAN) - set(_rendersystems "${_rendersystems} + Vulkan [BETA]\n") -endif () - -if (DEFINED _rendersystems) - set(_features "${_features}Building rendersystems:\n${_rendersystems}") -endif () - -# summarise programs -if (OGRE_BUILD_SAMPLES) - set(_programs "${_programs} + Samples\n") -endif () -if (OGRE_BUILD_TESTS) - set(_programs "${_programs} + Tests\n") -endif () -if (OGRE_BUILD_TOOLS) - set(_programs "${_programs} + Tools\n") -endif () - -if (DEFINED _programs) - set(_features "${_features}Building executables:\n${_programs}") -endif () - -# summarise core features -if (OGRE_CONFIG_ENABLE_MESHLOD) - set(_core "${_core} + Mesh Lod\n") -endif () -if (OGRE_CONFIG_ENABLE_DDS) - set(_core "${_core} + DDS image codec (.dds)\n") -endif () -if (OGRE_CONFIG_ENABLE_PVRTC) - set(_core "${_core} + PVRTC image codec (.pvr)\n") -endif () -if (OGRE_CONFIG_ENABLE_ETC) - set(_core "${_core} + ETC image codec (.pkm, .ktx) \n") -endif () -if (OGRE_CONFIG_ENABLE_ASTC) - set(_core "${_core} + ASTC image codec (.astc)\n") -endif () -if (OGRE_CONFIG_ENABLE_ZIP) - set(_core "${_core} + ZIP archives\n") -endif () -if (OGRE_CONFIG_ENABLE_QUAD_BUFFER_STEREO) - set(_core "${_core} + Quad Buffer Stereo Technology (EXPERIMENTAL)\n") -endif () -if (OGRE_RESOURCEMANAGER_STRICT EQUAL 1) - set(_core "${_core} + Pedantic resource lookup\n") -endif() -if (OGRE_CONFIG_THREADS GREATER 0) - set(_core "${_core} + Multi-threaded WorkQueue\n") -endif() -if (OGRE_CONFIG_NODE_INHERIT_TRANSFORM) - set(_core "${_core} + Non-uniform scaling & shearing of Nodes\n") -endif() -if (DEFINED _core) - set(_features "${_features}Building core features:\n${_core}") -endif () - - -if (OGRE_NODELESS_POSITIONING) - set(_legacy "${_legacy} + Nodeless positioning of Lights and Cameras\n") -endif () -if (OGRE_RESOURCEMANAGER_STRICT EQUAL 0) - set(_legacy "${_legacy} + Sloppy resource lookup\n") -endif() -if (OGRE_CONFIG_THREADS EQUAL 1 OR OGRE_CONFIG_THREADS EQUAL 2) - set(_legacy "${_legacy} + Internal Resource locking\n") -endif() -if (DEFINED _legacy) - set(_features "${_features}Deprecated 1.7 API-level features:\n${_legacy}") -endif () - -set(_features "${_features}\n") - - -# miscellaneous -macro(var_to_string VAR STR) - if (${VAR}) - set(${STR} "enabled") - else () - set(${STR} "disabled") - endif () -endmacro () - -# assert settings -if (OGRE_ASSERT_MODE EQUAL 0) - set(_assert "standard") -elseif (OGRE_ASSERT_MODE EQUAL 1) - set(_assert "release exceptions") -else () - set(_assert "exceptions") -endif() -# various true/false settings -var_to_string(OGRE_CONFIG_DOUBLE _double) - -# build type -if (OGRE_STATIC) - set(_buildtype "static") -else () - set(_buildtype "shared") -endif () - -set(_features "${_features}Build type: ${_buildtype}\n") -set(_features "${_features}Use double precision: ${_double}\n") -set(_features "${_features}Assert mode: ${_assert}\n") - - -set(_features "${_features}\n----------------------------------------------------------------------------\n") - -# Display results, terminate if anything required is missing -MACRO_DISPLAY_FEATURE_LOG() -message(STATUS ${_features}) diff --git a/CMake/Packages/FindAMDQBS.cmake b/CMake/Packages/FindAMDQBS.cmake deleted file mode 100644 index b2646342715..00000000000 --- a/CMake/Packages/FindAMDQBS.cmake +++ /dev/null @@ -1,38 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# - Try to find AMDQBS -# Once done, this will define -# -# AMDQBS_FOUND - system has AMDQBS -# AMDQBS_INCLUDE_DIRS - the AMDQBS include directories - -include(FindPkgMacros) -findpkg_begin(AMDQBS) - -# Get path, convert backslashes as ${ENV_${var}} -getenv_path(AMDQBS_HOME) -getenv_path(OGRE_SOURCE) -getenv_path(OGRE_HOME) - -# construct search paths -set(AMDQBS_PREFIX_PATH ${OGRE_SOURCE}/Dependencies ${ENV_OGRE_SOURCE}/Dependencies ${OGRE_HOME} ${ENV_OGRE_HOME}) -create_search_paths(AMDQBS) - -# redo search if prefix path changed -clear_if_changed(AMDQBS_PREFIX_PATH NVAPI_INCLUDE_DIR) - -use_pkgconfig(AMDQBS_PKGC AMDQBS) - -findpkg_framework(AMDQBS) - -find_path(AMDQBS_INCLUDE_DIR NAMES AmdDxExt.h HINTS ${AMDQBS_FRAMEWORK_INCLUDES} ${AMDQBS_INC_SEARCH_PATH} ${AMDQBS_PKGC_INCLUDE_DIRS} PATH_SUFFIXES AMDQBS) - -findpkg_finish(AMDQBS) -add_parent_dir(AMDQBS_INCLUDE_DIRS AMDQBS_INCLUDE_DIR) \ No newline at end of file diff --git a/CMake/Packages/FindCg.cmake b/CMake/Packages/FindCg.cmake deleted file mode 100644 index dbed6a329b5..00000000000 --- a/CMake/Packages/FindCg.cmake +++ /dev/null @@ -1,83 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# - Try to find Cg -# Once done, this will define -# -# Cg_FOUND - system has Cg -# Cg_INCLUDE_DIRS - the Cg include directories -# Cg_LIBRARIES - link these to use Cg - -include(FindPkgMacros) -findpkg_begin(Cg) - -# Get path, convert backslashes as ${ENV_${var}} -getenv_path(Cg_HOME) -getenv_path(OGRE_SOURCE) -getenv_path(OGRE_HOME) - -# construct search paths -set(Cg_PREFIX_PATH ${Cg_HOME} ${ENV_Cg_HOME} - ${OGRE_SOURCE}/Dependencies - ${ENV_OGRE_SOURCE}/Dependencies - ${OGRE_HOME} ${ENV_OGRE_HOME} - /opt/nvidia-cg-toolkit) -create_search_paths(Cg) -# redo search if prefix path changed -clear_if_changed(Cg_PREFIX_PATH - Cg_LIBRARY_FWK - Cg_LIBRARY_REL - Cg_LIBRARY_DBG - Cg_INCLUDE_DIR -) - -set(Cg_LIBRARY_NAMES Cg cg) -get_debug_names(Cg_LIBRARY_NAMES) - -use_pkgconfig(Cg_PKGC Cg) - -findpkg_framework(Cg) - -find_path(Cg_INCLUDE_DIR NAMES cg.h HINTS ${Cg_FRAMEWORK_INCLUDES} ${Cg_INC_SEARCH_PATH} ${Cg_PKGC_INCLUDE_DIRS} PATH_SUFFIXES Cg) - -if (CMAKE_SIZEOF_VOID_P EQUAL 8) - set (Cg_LIB_SEARCH_PATH ${Cg_HOME}/lib.x64 ${ENV_Cg_LIB64_PATH} - ${ENV_Cg_HOME}/lib.x64 ${Cg_LIB_SEARCH_PATH}) -else() - set (Cg_LIB_SEARCH_PATH ${Cg_HOME}/lib ${ENV_Cg_LIB_PATH} - ${ENV_Cg_HOME}/lib ${Cg_LIB_SEARCH_PATH}) -endif() - -find_library(Cg_LIBRARY_REL NAMES ${Cg_LIBRARY_NAMES} HINTS ${Cg_LIB_SEARCH_PATH} ${Cg_PKGC_LIBRARY_DIRS} PATH_SUFFIXES "" Release RelWithDebInfo MinSizeRel) -find_library(Cg_LIBRARY_DBG NAMES ${Cg_LIBRARY_NAMES_DBG} HINTS ${Cg_LIB_SEARCH_PATH} ${Cg_PKGC_LIBRARY_DIRS} PATH_SUFFIXES "" Debug) -make_library_set(Cg_LIBRARY) - -if (WIN32) - if (CMAKE_SIZEOF_VOID_P EQUAL 8) - set(Cg_BIN_SEARCH_PATH ${OGRE_DEPENDENCIES_DIR}/bin ${CMAKE_SOURCE_DIR}/Dependencies/bin ${Cg_HOME}/bin.x64 - ${ENV_Cg_BIN64_PATH} ${ENV_Cg_HOME}/bin.x64 ${ENV_OGRE_DEPENDENCIES_DIR}/bin - ${OGRE_SOURCE}/Dependencies/bin ${ENV_OGRE_SOURCE}/Dependencies/bin - ${OGRE_SDK}/bin ${ENV_OGRE_SDK}/bin - ${OGRE_HOME}/bin ${ENV_OGRE_HOME}/bin) - else() - set(Cg_BIN_SEARCH_PATH ${OGRE_DEPENDENCIES_DIR}/bin ${CMAKE_SOURCE_DIR}/Dependencies/bin ${Cg_HOME}/bin - ${ENV_Cg_BIN_PATH} ${ENV_Cg_HOME}/bin ${ENV_OGRE_DEPENDENCIES_DIR}/bin - ${OGRE_SOURCE}/Dependencies/bin ${ENV_OGRE_SOURCE}/Dependencies/bin - ${OGRE_SDK}/bin ${ENV_OGRE_SDK}/bin - ${OGRE_HOME}/bin ${ENV_OGRE_HOME}/bin) - endif() - find_file(Cg_BINARY_REL NAMES "cg.dll" HINTS ${Cg_BIN_SEARCH_PATH} - PATH_SUFFIXES "" release relwithdebinfo minsizerel) - find_file(Cg_BINARY_DBG NAMES "cg.dll" HINTS ${Cg_BIN_SEARCH_PATH} - PATH_SUFFIXES "" debug ) -endif() -mark_as_advanced(Cg_BINARY_REL Cg_BINARY_DBG) - -findpkg_finish(Cg) -add_parent_dir(Cg_INCLUDE_DIRS Cg_INCLUDE_DIR) diff --git a/CMake/Packages/FindDirectX.cmake b/CMake/Packages/FindDirectX.cmake deleted file mode 100644 index 0482c3da931..00000000000 --- a/CMake/Packages/FindDirectX.cmake +++ /dev/null @@ -1,70 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# ----------------------------------------------------------------------------- -# Find DirectX9 SDK -# Define: -# DirectX9_FOUND -# DirectX9_INCLUDE_DIR -# DirectX9_LIBRARY -# DirectX9_ROOT_DIR - -if(WIN32) # The only platform it makes sense to check for DirectX9 SDK - include(FindPkgMacros) - findpkg_begin(DirectX9) - - # Get path, convert backslashes as ${ENV_DXSDK_DIR} - getenv_path(DXSDK_DIR) - getenv_path(DirectX_HOME) - getenv_path(DirectX_ROOT) - getenv_path(DirectX_BASE) - - # construct search paths - set(DirectX9_PREFIX_PATH - "${DXSDK_DIR}" "${ENV_DXSDK_DIR}" - "${DIRECTX_HOME}" "${ENV_DIRECTX_HOME}" - "${DIRECTX_ROOT}" "${ENV_DIRECTX_ROOT}" - "${DIRECTX_BASE}" "${ENV_DIRECTX_BASE}" - "C:/apps_x86/Microsoft DirectX SDK*" - "C:/Program Files (x86)/Microsoft DirectX SDK*" - "C:/apps/Microsoft DirectX SDK*" - "C:/Program Files/Microsoft DirectX SDK*" - "$ENV{ProgramFiles}/Microsoft DirectX SDK*" - ) - - create_search_paths(DirectX9) - - # redo search if prefix path changed - clear_if_changed(DirectX9_PREFIX_PATH - DirectX9_LIBRARY - DirectX9_INCLUDE_DIR - ) - - find_path(DirectX9_INCLUDE_DIR NAMES d3d9.h D3DCommon.h HINTS ${DirectX9_INC_SEARCH_PATH}) - - # dlls are in DirectX9_ROOT_DIR/Developer Runtime/x64|x86 - # lib files are in DirectX9_ROOT_DIR/Lib/x64|x86 - if(CMAKE_SIZEOF_VOID_P EQUAL 8) - set(DirectX9_LIBPATH_SUFFIX "x64") - else(CMAKE_SIZEOF_VOID_P EQUAL 8) - set(DirectX9_LIBPATH_SUFFIX "x86") - endif(CMAKE_SIZEOF_VOID_P EQUAL 8) - find_library(DirectX9_LIBRARY NAMES d3d9 HINTS ${DirectX9_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX9_LIBPATH_SUFFIX}) - find_library(DirectX9_D3DX9_LIBRARY NAMES d3dx9 HINTS ${DirectX9_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX9_LIBPATH_SUFFIX}) - find_library(DirectX9_DXGUID_LIBRARY NAMES dxguid HINTS ${DirectX9_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX9_LIBPATH_SUFFIX}) - - findpkg_finish(DirectX9) - set(DirectX9_LIBRARIES ${DirectX9_LIBRARIES} - ${DirectX9_D3DX9_LIBRARY} - ${DirectX9_DXGUID_LIBRARY} - ) - - mark_as_advanced(DirectX9_D3DX9_LIBRARY DirectX9_DXGUID_LIBRARY - DirectX9_DXGI_LIBRARY DirectX9_D3DCOMPILER_LIBRARY) -endif(WIN32) diff --git a/CMake/Packages/FindDirectX11.cmake b/CMake/Packages/FindDirectX11.cmake deleted file mode 100644 index 1caae3bde4c..00000000000 --- a/CMake/Packages/FindDirectX11.cmake +++ /dev/null @@ -1,131 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# ----------------------------------------------------------------------------- -# Find DirectX11 SDK -# Define: -# DirectX11_FOUND -# DirectX11_INCLUDE_DIRS -# DirectX11_LIBRARIES - -if(WIN32) # The only platform it makes sense to check for DirectX11 SDK - include(FindPkgMacros) - findpkg_begin(DirectX11) - - if( MSVC AND NOT MSVC90 ) - # Windows 10.x SDK - get_filename_component(kit10_dir "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows Kits\\Installed Roots;KitsRoot10]" REALPATH) - file(GLOB W10SDK_VERSIONS RELATIVE ${kit10_dir}/Include ${kit10_dir}/Include/10.*) # enumerate pre-release and not yet known release versions - list(APPEND W10SDK_VERSIONS "10.0.10240.0" "10.0.14393.0" "10.0.15063.0" "10.0.16299.0") # enumerate well known release versions - list(REMOVE_DUPLICATES W10SDK_VERSIONS) - list(SORT W10SDK_VERSIONS) - list(REVERSE W10SDK_VERSIONS) # sort from high to low - if(CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION) - list(INSERT W10SDK_VERSIONS 0 ${CMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION}) # prefer version passed by CMake, if any - endif() - foreach(W10SDK_VER ${W10SDK_VERSIONS}) - find_path(DirectX11_INCLUDE_DIR NAMES d3d11.h HINTS "${kit10_dir}/Include/${W10SDK_VER}/um" "C:/Program Files (x86)/Windows Kits/10/Include/${W10SDK_VER}/um" "C:/Program Files/Windows Kits/10/Include/${W10SDK_VER}/um") - endforeach() - # Windows 8.1 SDK - if(NOT DirectX11_INCLUDE_DIR) - find_path(DirectX11_INCLUDE_DIR NAMES d3d11.h HINTS "C:/Program Files (x86)/Windows Kits/8.1/include/um" "C:/Program Files/Windows Kits/8.1/include/um") - endif() - # Windows 8.0 SDK - if(NOT DirectX11_INCLUDE_DIR) - find_path(DirectX11_INCLUDE_DIR NAMES d3d11.h HINTS "C:/Program Files (x86)/Windows Kits/8.0/include/um" "C:/Program Files/Windows Kits/8.0/include/um") - endif() - endif() - - if(DirectX11_INCLUDE_DIR) - # No need to specify full path to libraries, proper version would be found as part of SDK, in one of the following places - # "C:/Program Files (x86)/Windows Kits/10/lib/${W10SDK_VER}/um/${MSVC_CXX_ARCHITECTURE_ID}/" - # "C:/Program Files (x86)/Windows Kits/8.1/lib/winv6.3/um/${MSVC_CXX_ARCHITECTURE_ID}/" - # "C:/Program Files (x86)/Windows Kits/8.0/lib/win8/um/${MSVC_CXX_ARCHITECTURE_ID}/" - # "C:/Program Files (x86)/Windows Phone Kits/8.1/lib/${MSVC_CXX_ARCHITECTURE_ID}/" - # "C:/Program Files (x86)/Windows Phone Kits/8.0/lib/${MSVC_CXX_ARCHITECTURE_ID}/" - set(DirectX11_LIBRARY d3d11.lib dxgi.lib dxguid.lib) - # but it is usefull to output selected version to the log - message(STATUS "Found DirectX11 headers: ${DirectX11_INCLUDE_DIR}") - endif() - - # Legacy Direct X SDK - if( NOT DirectX11_INCLUDE_DIR OR NOT DirectX11_LIBRARY ) - # Get path, convert backslashes as ${ENV_DXSDK_DIR} - getenv_path(DXSDK_DIR) - getenv_path(DIRECTX_HOME) - getenv_path(DIRECTX_ROOT) - getenv_path(DIRECTX_BASE) - - # construct search paths - set(DirectX11_PREFIX_PATH - "${DXSDK_DIR}" "${ENV_DXSDK_DIR}" - "${DIRECTX_HOME}" "${ENV_DIRECTX_HOME}" - "${DIRECTX_ROOT}" "${ENV_DIRECTX_ROOT}" - "${DIRECTX_BASE}" "${ENV_DIRECTX_BASE}" - "C:/apps_x86/Microsoft DirectX SDK*" - "C:/Program Files (x86)/Microsoft DirectX SDK*" - "C:/apps/Microsoft DirectX SDK*" - "C:/Program Files/Microsoft DirectX SDK*" - "$ENV{ProgramFiles}/Microsoft DirectX SDK*" - ) - - create_search_paths(DirectX11) - # redo search if prefix path changed - clear_if_changed(DirectX11_PREFIX_PATH - DirectX11_LIBRARY - DirectX11_INCLUDE_DIR - ) - - # dlls are in DirectX11_ROOT_DIR/Developer Runtime/x64|x86 - # lib files are in DirectX11_ROOT_DIR/Lib/x64|x86 - if(CMAKE_SIZEOF_VOID_P EQUAL 8) - set(DirectX11_LIBPATH_SUFFIX "x64") - else(CMAKE_SIZEOF_VOID_P EQUAL 8) - set(DirectX11_LIBPATH_SUFFIX "x86") - endif(CMAKE_SIZEOF_VOID_P EQUAL 8) - - # look for D3D11 components - find_path(DirectX11_INCLUDE_DIR NAMES d3d11.h HINTS ${DirectX11_INC_SEARCH_PATH}) - find_library(DirectX11_DXERR_LIBRARY NAMES DxErr HINTS ${DirectX11_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX11_LIBPATH_SUFFIX}) - find_library(DirectX11_DXGUID_LIBRARY NAMES dxguid HINTS ${DirectX11_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX11_LIBPATH_SUFFIX}) - find_library(DirectX11_DXGI_LIBRARY NAMES dxgi HINTS ${DirectX11_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX11_LIBPATH_SUFFIX}) - find_library(DirectX11_D3DCOMPILER_LIBRARY NAMES d3dcompiler HINTS ${DirectX11_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX11_LIBPATH_SUFFIX}) - find_library(DirectX11_D3D11_LIBRARY NAMES d3d11 HINTS ${DirectX11_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX11_LIBPATH_SUFFIX}) - find_library(DirectX11_D3DX11_LIBRARY NAMES d3dx11 HINTS ${DirectX11_LIB_SEARCH_PATH} PATH_SUFFIXES ${DirectX11_LIBPATH_SUFFIX}) - - if (DirectX11_INCLUDE_DIR AND DirectX11_D3D11_LIBRARY) - set(DirectX11_D3D11_LIBRARIES ${DirectX11_D3D11_LIBRARIES} - ${DirectX11_D3D11_LIBRARY} - ${DirectX11_DXGI_LIBRARY} - ${DirectX11_DXGUID_LIBRARY} - ${DirectX11_D3DCOMPILER_LIBRARY} - ) - endif () - if (DirectX11_D3DX11_LIBRARY) - set(DirectX11_D3D11_LIBRARIES ${DirectX11_D3D11_LIBRARIES} ${DirectX11_D3DX11_LIBRARY}) - endif () - if (DirectX11_DXERR_LIBRARY) - set(DirectX11_D3D11_LIBRARIES ${DirectX11_D3D11_LIBRARIES} ${DirectX11_DXERR_LIBRARY}) - endif () - - set(DirectX11_LIBRARY - ${DirectX11_D3D11_LIBRARIES} - ) - - mark_as_advanced(DirectX11_D3D11_LIBRARY - DirectX11_D3DX11_LIBRARY - DirectX11_DXERR_LIBRARY - DirectX11_DXGUID_LIBRARY - DirectX11_DXGI_LIBRARY - DirectX11_D3DCOMPILER_LIBRARY) - endif () # Legacy Direct X SDK - - findpkg_finish(DirectX11) - -endif(WIN32) diff --git a/CMake/Packages/FindFreeImage.cmake b/CMake/Packages/FindFreeImage.cmake deleted file mode 100644 index 7c89ec53b85..00000000000 --- a/CMake/Packages/FindFreeImage.cmake +++ /dev/null @@ -1,49 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# - Try to find FreeImage -# Once done, this will define -# -# FreeImage_FOUND - system has FreeImage -# FreeImage_INCLUDE_DIRS - the FreeImage include directories -# FreeImage_LIBRARIES - link these to use FreeImage - -include(FindPkgMacros) -findpkg_begin(FreeImage) - -# Get path, convert backslashes as ${ENV_${var}} -getenv_path(FREEIMAGE_HOME) - -# construct search paths -set(FreeImage_PREFIX_PATH ${FREEIMAGE_HOME} ${ENV_FREEIMAGE_HOME}) -create_search_paths(FreeImage) -# redo search if prefix path changed -clear_if_changed(FreeImage_PREFIX_PATH - FreeImage_LIBRARY_FWK - FreeImage_LIBRARY_REL - FreeImage_LIBRARY_DBG - FreeImage_INCLUDE_DIR -) - -set(FreeImage_LIBRARY_NAMES freeimage freeimageLib FreeImage FreeImageLib) -get_debug_names(FreeImage_LIBRARY_NAMES) - -use_pkgconfig(FreeImage_PKGC freeimage) - -findpkg_framework(FreeImage) - -find_path(FreeImage_INCLUDE_DIR NAMES FreeImage.h HINTS ${FreeImage_INC_SEARCH_PATH} ${FreeImage_PKGC_INCLUDE_DIRS}) - -find_library(FreeImage_LIBRARY_REL NAMES ${FreeImage_LIBRARY_NAMES} HINTS ${FreeImage_LIB_SEARCH_PATH} ${FreeImage_PKGC_LIBRARY_DIRS} PATH_SUFFIXES "" Release RelWithDebInfo MinSizeRel) -find_library(FreeImage_LIBRARY_DBG NAMES ${FreeImage_LIBRARY_NAMES_DBG} HINTS ${FreeImage_LIB_SEARCH_PATH} ${FreeImage_PKGC_LIBRARY_DIRS} PATH_SUFFIXES "" Debug) - -make_library_set(FreeImage_LIBRARY) - -findpkg_finish(FreeImage) - diff --git a/CMake/Packages/FindGLSLOptimizer.cmake b/CMake/Packages/FindGLSLOptimizer.cmake deleted file mode 100644 index dd4b179ceb4..00000000000 --- a/CMake/Packages/FindGLSLOptimizer.cmake +++ /dev/null @@ -1,45 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# - Try to find GLSL Optimizer -# Once done, this will define -# -# GLSL_Optimizer_FOUND - system has GLSL_Optimizer -# GLSL_Optimizer_INCLUDE_DIRS - the GLSL_Optimizer include directories -# GLSL_Optimizer_LIBRARIES - link these to use GLSL_Optimizer - -include(FindPkgMacros) -findpkg_begin(GLSL_Optimizer) - -# construct search paths -set(GLSL_Optimizer_PREFIX_PATH ${GLSL_Optimizer_HOME} $ENV{GLSL_Optimizer_HOME} - ${OGRE_HOME} $ENV{OGRE_HOME} ${OGRE_DEP_SEARCH_PATH}) -create_search_paths(GLSL_Optimizer) -# redo search if prefix path changed -clear_if_changed(GLSL_Optimizer_PREFIX_PATH - GLSL_Optimizer_LIBRARY_FWK - GLSL_Optimizer_LIBRARY_REL - GLSL_Optimizer_LIBRARY_DBG - GLSL_Optimizer_INCLUDE_DIR -) - -set(GLSL_Optimizer_LIBRARY_NAMES mesaglsl2 glsl_optimizer) -get_debug_names(GLSL_Optimizer_LIBRARY_NAMES) - -use_pkgconfig(GLSL_Optimizer_PKGC GLSL_Optimizer) - -findpkg_framework(GLSL_Optimizer) -find_path(GLSL_Optimizer_INCLUDE_DIR NAMES glsl_optimizer.h HINTS ${GLSL_Optimizer_INC_SEARCH_PATH} ${GLSL_Optimizer_PKGC_INCLUDE_DIRS} PATH_SUFFIXES GLSL_Optimizer) -find_library(GLSL_Optimizer_LIBRARY_REL NAMES ${GLSL_Optimizer_LIBRARY_NAMES} HINTS ${GLSL_Optimizer_LIB_SEARCH_PATH} ${GLSL_Optimizer_PKGC_LIBRARY_DIRS} PATH_SUFFIXES "" Release RelWithDebInfo MinSizeRel) -find_library(GLSL_Optimizer_LIBRARY_DBG NAMES ${GLSL_Optimizer_LIBRARY_NAMES_DBG} HINTS ${GLSL_Optimizer_LIB_SEARCH_PATH} ${GLSL_Optimizer_PKGC_LIBRARY_DIRS} PATH_SUFFIXES "" Debug) -make_library_set(GLSL_Optimizer_LIBRARY) - -findpkg_finish(GLSL_Optimizer) -add_parent_dir(GLSL_Optimizer_INCLUDE_DIRS GLSL_Optimizer_INCLUDE_DIR) - diff --git a/CMake/Packages/FindHLSL2GLSL.cmake b/CMake/Packages/FindHLSL2GLSL.cmake deleted file mode 100644 index 71258956779..00000000000 --- a/CMake/Packages/FindHLSL2GLSL.cmake +++ /dev/null @@ -1,45 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# - Try to find HLSL2GLSL -# Once done, this will define -# -# HLSL2GLSL_FOUND - system has HLSL2GLSL -# HLSL2GLSL_INCLUDE_DIRS - the HLSL2GLSL include directories -# HLSL2GLSL_LIBRARIES - link these to use HLSL2GLSL - -include(FindPkgMacros) -findpkg_begin(HLSL2GLSL) - -# construct search paths -set(HLSL2GLSL_PREFIX_PATH ${HLSL2GLSL_HOME} $ENV{HLSL2GLSL_HOME} - ${OGRE_HOME} $ENV{OGRE_HOME} ${OGRE_DEP_SEARCH_PATH}) -create_search_paths(HLSL2GLSL) -# redo search if prefix path changed -clear_if_changed(HLSL2GLSL_PREFIX_PATH - HLSL2GLSL_LIBRARY_FWK - HLSL2GLSL_LIBRARY_REL - HLSL2GLSL_LIBRARY_DBG - HLSL2GLSL_INCLUDE_DIR -) - -set(HLSL2GLSL_LIBRARY_NAMES hlsl2glsl) -get_debug_names(HLSL2GLSL_LIBRARY_NAMES) - -use_pkgconfig(HLSL2GLSL_PKGC HLSL2GLSL) - -findpkg_framework(HLSL2GLSL) -find_path(HLSL2GLSL_INCLUDE_DIR NAMES hlsl2glsl.h HINTS ${HLSL2GLSL_INC_SEARCH_PATH} ${HLSL2GLSL_PKGC_INCLUDE_DIRS} PATH_SUFFIXES HLSL2GLSL) -find_library(HLSL2GLSL_LIBRARY_REL NAMES ${HLSL2GLSL_LIBRARY_NAMES} HINTS ${HLSL2GLSL_LIB_SEARCH_PATH} ${HLSL2GLSL_PKGC_LIBRARY_DIRS} PATH_SUFFIXES "" Release RelWithDebInfo MinSizeRel) -find_library(HLSL2GLSL_LIBRARY_DBG NAMES ${HLSL2GLSL_LIBRARY_NAMES_DBG} HINTS ${HLSL2GLSL_LIB_SEARCH_PATH} ${HLSL2GLSL_PKGC_LIBRARY_DIRS} PATH_SUFFIXES "" Debug) -make_library_set(HLSL2GLSL_LIBRARY) - -findpkg_finish(HLSL2GLSL) -add_parent_dir(HLSL2GLSL_INCLUDE_DIRS HLSL2GLSL_INCLUDE_DIR) - diff --git a/CMake/Packages/FindNVAPI.cmake b/CMake/Packages/FindNVAPI.cmake deleted file mode 100644 index 2b9deba99b3..00000000000 --- a/CMake/Packages/FindNVAPI.cmake +++ /dev/null @@ -1,50 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# - Try to find NVAPI -# Once done, this will define -# -# NVAPI_FOUND - system has NVAPI -# NVAPI_INCLUDE_DIRS - the NVAPI include directories -# NVAPI_LIBRARIES - link these to use NVAPI - -include(FindPkgMacros) -findpkg_begin(NVAPI) - -# Get path, convert backslashes as ${ENV_${var}} -getenv_path(OGRE_SOURCE) -getenv_path(OGRE_HOME) - -# construct search paths -set(NVAPI_PREFIX_PATH ${OGRE_SOURCE}/Dependencies ${ENV_OGRE_SOURCE}/Dependencies ${OGRE_HOME} ${ENV_OGRE_HOME}) - -create_search_paths(NVAPI) - -# redo search if prefix path changed -clear_if_changed(NVAPI_PREFIX_PATH - NVAPI_LIBRARY_FWK - NVAPI_LIBRARY_REL - NVAPI_LIBRARY_DBG - NVAPI_INCLUDE_DIR -) - -set(NVAPI_LIBRARY_NAMES NVAPI) -get_debug_names(NVAPI_LIBRARY_NAMES) - -use_pkgconfig(NVAPI_PKGC NVAPI) - -findpkg_framework(NVAPI) - -find_path(NVAPI_INCLUDE_DIR NAMES nvapi.h HINTS ${NVAPI_FRAMEWORK_INCLUDES} ${NVAPI_INC_SEARCH_PATH} ${NVAPI_PKGC_INCLUDE_DIRS} PATH_SUFFIXES NVAPI) -find_library(NVAPI_LIBRARY_REL NAMES ${NVAPI_LIBRARY_NAMES} HINTS ${NVAPI_LIB_SEARCH_PATH} ${NVAPI_PKGC_LIBRARY_DIRS} PATH_SUFFIXES "" release relwithdebinfo minsizerel) -find_library(NVAPI_LIBRARY_DBG NAMES ${NVAPI_LIBRARY_NAMES_DBG} HINTS ${NVAPI_LIB_SEARCH_PATH} ${NVAPI_PKGC_LIBRARY_DIRS} PATH_SUFFIXES "" debug) -make_library_set(NVAPI_LIBRARY) - -findpkg_finish(NVAPI) -add_parent_dir(NVAPI_INCLUDE_DIRS NVAPI_INCLUDE_DIR) \ No newline at end of file diff --git a/CMake/Packages/FindOpenEXR.cmake b/CMake/Packages/FindOpenEXR.cmake deleted file mode 100644 index 4ef5a108d31..00000000000 --- a/CMake/Packages/FindOpenEXR.cmake +++ /dev/null @@ -1,64 +0,0 @@ -# Locate OpenEXR -# This module defines -# OPENEXR_LIBRARY -# OPENEXR_FOUND, if false, do not try to link to OpenEXR -# OPENEXR_INCLUDE_DIR, where to find the headers -# -# $OPENEXR_DIR is an environment variable that would -# correspond to the ./configure --prefix=$OPENEXR_DIR -# -# Created by Robert Osfield. - - -FIND_PATH(OPENEXR_INCLUDE_DIR OpenEXR/ImfIO.h - $ENV{OPENEXR_DIR}/include - $ENV{OPENEXR_DIR} - ~/Library/Frameworks - /Library/Frameworks - /usr/local/include - /usr/include - /sw/include # Fink - /opt/local/include # DarwinPorts - /opt/csw/include # Blastwave - /opt/include - /usr/freeware/include -) - -# Macro to find exr libraries (deduplicating search paths) -# example: OPENEXR_FIND_VAR(OPENEXR_IlmImf_LIBRARY IlmImf) -MACRO(OPENEXR_FIND_VAR varname libname) - FIND_LIBRARY( ${varname} - NAMES ${libname} - PATHS - $ENV{OPENEXR_DIR}/lib - $ENV{OPENEXR_DIR} - ~/Library/Frameworks - /Library/Frameworks - /usr/local/lib - /usr/lib - /sw/lib - /opt/local/lib - /opt/csw/lib - /opt/lib - /usr/freeware/lib64 - ) -ENDMACRO(OPENEXR_FIND_VAR) - -# Macro to find exr libraries (and debug versions) -# example: OPENEXR_FIND(IlmImf) -MACRO(OPENEXR_FIND libname) - OPENEXR_FIND_VAR(OPENEXR_${libname}_LIBRARY ${libname}) - OPENEXR_FIND_VAR(OPENEXR_${libname}_LIBRARY_DEBUG ${libname}d) -ENDMACRO(OPENEXR_FIND) - -OPENEXR_FIND(IlmImf) -OPENEXR_FIND(IlmThread) -OPENEXR_FIND(Iex) -OPENEXR_FIND(Half) - -SET(OPENEXR_FOUND NO) -IF(OPENEXR_INCLUDE_DIR AND OPENEXR_IlmImf_LIBRARY AND OPENEXR_IlmThread_LIBRARY AND OPENEXR_Iex_LIBRARY AND OPENEXR_Half_LIBRARY) - SET(OPENEXR_LIBRARIES ${OPENEXR_IlmImf_LIBRARY} ${OPENEXR_IlmThread_LIBRARY} ${OPENEXR_Half_LIBRARY} ${OPENEXR_Iex_LIBRARY} ) - SET(OPENEXR_LIBRARIES_VARS OPENEXR_IlmImf_LIBRARY OPENEXR_IlmThread_LIBRARY OPENEXR_Half_LIBRARY OPENEXR_Iex_LIBRARY ) - SET(OPENEXR_FOUND YES) -ENDIF(OPENEXR_INCLUDE_DIR AND OPENEXR_IlmImf_LIBRARY AND OPENEXR_IlmThread_LIBRARY AND OPENEXR_Iex_LIBRARY AND OPENEXR_Half_LIBRARY) diff --git a/CMake/Packages/FindOpenGLES2.cmake b/CMake/Packages/FindOpenGLES2.cmake deleted file mode 100644 index 1ad144d4146..00000000000 --- a/CMake/Packages/FindOpenGLES2.cmake +++ /dev/null @@ -1,104 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# - Try to find OpenGLES and EGL -# If using ARM Mali emulation you can specify the parent directory that contains the bin and include directories by -# setting the MALI_SDK_ROOT variable in the environment. -# -# For AMD emulation use the AMD_SDK_ROOT variable -# -# Once done this will define -# -# OPENGLES2_FOUND - system has OpenGLES -# OPENGLES2_INCLUDE_DIR - the GL include directory -# OPENGLES2_LIBRARIES - Link these to use OpenGLES -# -# EGL_FOUND - system has EGL -# EGL_INCLUDE_DIR - the EGL include directory -# EGL_LIBRARIES - Link these to use EGL - -include(FindPkgMacros) - -IF(APPLE) - create_search_paths(/Developer/Platforms) - findpkg_framework(OpenGLES2) - set(OPENGLES2_gl_LIBRARY "-framework OpenGLES") -ELSEIF (WIN32) - # use WGL - find_package(OpenGL) - set(OPENGLES2_gl_LIBRARY ${OPENGL_gl_LIBRARY}) -ELSE () - getenv_path(AMD_SDK_ROOT) - getenv_path(MALI_SDK_ROOT) - - FIND_PATH(OPENGLES2_INCLUDE_DIR GLES2/gl2.h - ${ENV_AMD_SDK_ROOT}/include - ${ENV_MALI_SDK_ROOT}/include - /opt/Imagination/PowerVR/GraphicsSDK/SDK_3.1/Builds/Include - /usr/openwin/share/include - /opt/graphics/OpenGL/include /usr/X11R6/include - /usr/include - ) - - FIND_LIBRARY(OPENGLES2_gl_LIBRARY - NAMES GLESv2 - PATHS ${ENV_AMD_SDK_ROOT}/x86 - ${ENV_MALI_SDK_ROOT}/bin - /opt/Imagination/PowerVR/GraphicsSDK/SDK_3.1/Builds/Linux/x86_32/Lib - /opt/graphics/OpenGL/lib - /usr/openwin/lib - /usr/shlib /usr/X11R6/lib - /usr/lib - ) - - FIND_PATH(EGL_INCLUDE_DIR EGL/egl.h - ${ENV_AMD_SDK_ROOT}/include - ${ENV_MALI_SDK_ROOT}/include - /opt/Imagination/PowerVR/GraphicsSDK/SDK_3.1/Builds/Include - /usr/openwin/share/include - /opt/graphics/OpenGL/include /usr/X11R6/include - /usr/include - ) - - FIND_LIBRARY(EGL_egl_LIBRARY - NAMES EGL - PATHS ${ENV_AMD_SDK_ROOT}/x86 - ${ENV_MALI_SDK_ROOT}/bin - /opt/Imagination/PowerVR/GraphicsSDK/SDK_3.1/Builds/Linux/x86_32/Lib - /opt/graphics/OpenGL/lib - /usr/openwin/lib - /usr/shlib /usr/X11R6/lib - /usr/lib - ) -ENDIF () - -IF(OPENGLES2_gl_LIBRARY) - SET( OPENGLES2_LIBRARIES ${OPENGLES2_gl_LIBRARY} ${OPENGLES2_LIBRARIES}) - SET( OPENGLES2_FOUND TRUE ) -ENDIF(OPENGLES2_gl_LIBRARY) - -IF(OPENGL_egl_LIBRARY) - SET( EGL_LIBRARIES ${OPENGL_egl_LIBRARY}) - SET( EGL_FOUND TRUE ) -ELSEIF(EGL_egl_LIBRARY) - SET( EGL_LIBRARIES ${EGL_egl_LIBRARY}) - SET( EGL_FOUND TRUE) -ENDIF() - -if(EMSCRIPTEN) - SET( OPENGLES2_FOUND TRUE ) - SET( EGL_FOUND TRUE) -endif() - -MARK_AS_ADVANCED( - OPENGLES2_INCLUDE_DIR - OPENGLES2_gl_LIBRARY - EGL_INCLUDE_DIR - EGL_egl_LIBRARY -) diff --git a/CMake/Packages/FindPOCO.cmake b/CMake/Packages/FindPOCO.cmake deleted file mode 100644 index 6b6d7fa3406..00000000000 --- a/CMake/Packages/FindPOCO.cmake +++ /dev/null @@ -1,101 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# - Try to find POCO libraries -# Once done, this will define -# -# POCO_FOUND - system has POCO -# POCO_INCLUDE_DIRS - the POCO include directories -# POCO_LIBRARIES - link these to use POCO - -include(FindPkgMacros) -findpkg_begin(POCO) - -# Get path, convert backslashes as ${ENV_${var}} -getenv_path(POCO_HOME) -getenv_path(POCO_ROOT) -getenv_path(POCO_BASE) - -# construct search paths -set(POCO_PREFIX_PATH - ${POCO_HOME} ${ENV_POCO_HOME} - ${POCO_ROOT} ${ENV_POCO_ROOT} - ${POCO_BASE} ${ENV_POCO_BASE} -) -# redo search if prefix path changed -clear_if_changed(POCO_PREFIX_PATH - POCO_LIBRARY_FWK - POCO_LIBRARY_REL - POCO_LIBRARY_DBG - POCO_INCLUDE_DIR -) - -create_search_paths(POCO) -set(POCO_INC_SEARCH_PATH ${POCO_INC_SEARCH_PATH} ${POCO_PREFIX_PATH}) - - -set(POCO_LIBRARY_NAMES PocoFoundation PocoFoundationmt) -get_debug_names(POCO_LIBRARY_NAMES) - -use_pkgconfig(POCO_PKGC POCO) - -findpkg_framework(POCO) - -find_path(POCO_INCLUDE_DIR NAMES Poco/Foundation.h HINTS ${POCO_INC_SEARCH_PATH} ${POCO_PKGC_INCLUDE_DIRS} PATH_SUFFIXES Foundation/include) -find_library(POCO_LIBRARY_REL NAMES ${POCO_LIBRARY_NAMES} HINTS ${POCO_LIB_SEARCH_PATH} ${POCO_PKGC_LIBRARY_DIRS} PATH_SUFFIXES Linux/i686) -find_library(POCO_LIBRARY_DBG NAMES ${POCO_LIBRARY_NAMES_DBG} HINTS ${POCO_LIB_SEARCH_PATH} ${POCO_PKGC_LIBRARY_DIRS} PATH_SUFFIXES Linux/i686) -make_library_set(POCO_LIBRARY) - -findpkg_finish(POCO) - -if (NOT POCO_FOUND) - return() -endif () - - -# Look for Poco's Util package -findpkg_begin(POCO_Util) -set(POCO_Util_LIBRARY_NAMES PocoUtil PocoUtilmt) -get_debug_names(POCO_Util_LIBRARY_NAMES) -find_path(POCO_Util_INCLUDE_DIR NAMES Poco/Util/Util.h HINTS ${POCO_INCLUDE_DIR} ${POCO_INC_SEARCH_PATH} ${POCO_PKGC_INCLUDE_DIRS} PATH_SUFFIXES Util/include) -find_library(POCO_Util_LIBRARY_REL NAMES ${POCO_Util_LIBRARY_NAMES} HINTS ${POCO_LIB_SEARCH_PATH} ${POCO_PKGC_LIBRARY_DIRS} PATH_SUFFIXES Linux/i686) -find_library(POCO_Util_LIBRARY_DBG NAMES ${POCO_Util_LIBRARY_NAMES_DBG} HINTS ${POCO_LIB_SEARCH_PATH} ${POCO_PKGC_LIBRARY_DIRS} PATH_SUFFIXES Linux/i686) -make_library_set(POCO_Util_LIBRARY) -findpkg_finish(POCO_Util) - -# Look for Poco's Net package -findpkg_begin(POCO_Net) -set(POCO_Net_LIBRARY_NAMES PocoNet PocoNetmt) -get_debug_names(POCO_Net_LIBRARY_NAMES) -find_path(POCO_Net_INCLUDE_DIR NAMES Poco/Net/Net.h HINTS ${POCO_INCLUDE_DIR} ${POCO_INC_SEARCH_PATH} ${POCO_PKGC_INCLUDE_DIRS} PATH_SUFFIXES Net/include) -find_library(POCO_Net_LIBRARY_REL NAMES ${POCO_Net_LIBRARY_NAMES} HINTS ${POCO_LIB_SEARCH_PATH} ${POCO_PKGC_LIBRARY_DIRS} PATH_SUFFIXES Linux/i686) -find_library(POCO_Net_LIBRARY_DBG NAMES ${POCO_Net_LIBRARY_NAMES_DBG} HINTS ${POCO_LIB_SEARCH_PATH} ${POCO_PKGC_LIBRARY_DIRS} PATH_SUFFIXES Linux/i686) -make_library_set(POCO_Net_LIBRARY) -findpkg_finish(POCO_Net) - -# Look for Poco's NetSSL package -findpkg_begin(POCO_NetSSL) -set(POCO_NetSSL_LIBRARY_NAMES PocoNetSSL PocoNetSSLmt) -get_debug_names(POCO_NetSSL_LIBRARY_NAMES) -find_path(POCO_NetSSL_INCLUDE_DIR NAMES Poco/Net/NetSSL.h HINTS ${POCO_INCLUDE_DIR} ${POCO_INC_SEARCH_PATH} ${POCO_PKGC_INCLUDE_DIRS} PATH_SUFFIXES NetSSL/include) -find_library(POCO_NetSSL_LIBRARY_REL NAMES ${POCO_NetSSL_LIBRARY_NAMES} HINTS ${POCO_LIB_SEARCH_PATH} ${POCO_PKGC_LIBRARY_DIRS} PATH_SUFFIXES Linux/i686) -find_library(POCO_NetSSL_LIBRARY_DBG NAMES ${POCO_NetSSL_LIBRARY_NAMES_DBG} HINTS ${POCO_LIB_SEARCH_PATH} ${POCO_PKGC_LIBRARY_DIRS} PATH_SUFFIXES Linux/i686) -make_library_set(POCO_NetSSL_LIBRARY) -findpkg_finish(POCO_NetSSL) - -# Look for Poco's XML package -findpkg_begin(POCO_XML) -set(POCO_XML_LIBRARY_NAMES PocoXML PocoXMLmt) -get_debug_names(POCO_XML_LIBRARY_NAMES) -find_path(POCO_XML_INCLUDE_DIR NAMES Poco/XML/XML.h HINTS ${POCO_INCLUDE_DIR} ${POCO_INC_SEARCH_PATH} ${POCO_PKGC_INCLUDE_DIRS} PATH_SUFFIXES XML/include) -find_library(POCO_XML_LIBRARY_REL NAMES ${POCO_XML_LIBRARY_NAMES} HINTS ${POCO_LIB_SEARCH_PATH} ${POCO_PKGC_LIBRARY_DIRS} PATH_SUFFIXES Linux/i686) -find_library(POCO_XML_LIBRARY_DBG NAMES ${POCO_XML_LIBRARY_NAMES_DBG} HINTS ${POCO_LIB_SEARCH_PATH} ${POCO_PKGC_LIBRARY_DIRS} PATH_SUFFIXES Linux/i686) -make_library_set(POCO_XML_LIBRARY) -findpkg_finish(POCO_XML) - diff --git a/CMake/Packages/FindSoftimage.cmake b/CMake/Packages/FindSoftimage.cmake deleted file mode 100755 index db047f8a58c..00000000000 --- a/CMake/Packages/FindSoftimage.cmake +++ /dev/null @@ -1,80 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# - Try to find Softimage SDK -# Once done, this will define -# -# Softimage_FOUND - system has Softimage SDK -# Softimage_INCLUDE_DIRS - the Softimage include directories -# Softimage_LIBRARIES - link these to use OIS - -include(FindPkgMacros) -findpkg_begin(Softimage) - -# construct search paths -set(Softimage_PREFIX_PATH - "C:/Softimage/XSI_6.0/XSISDK" - "C:/Softimage/XSI_6.01/XSISDK" - "C:/Softimage/XSI_6.02/XSISDK" - "C:/Softimage/XSI_6.5/XSISDK" - "C:/Softimage/XSI_7.0/XSISDK" - "C:/Softimage/XSI_7.01/XSISDK" - "C:/Softimage/XSI_7.5/XSISDK" - "C:/Softimage/Softimage_2010/XSISDK" - "C:/Softimage/Softimage_2010_SP1/XSISDK" - "$ENV{ProgramFiles}/Autodesk/Softimage 2011/XSISDK" - "$ENV{ProgramFiles}/Autodesk/Softimage 2011 SP1/XSISDK" - "$ENV{ProgramFiles}/Autodesk/Softimage 2012/XSISDK" - "$ENV{ProgramFiles}/Autodesk/Softimage 2012 SP1/XSISDK" - "$ENV{ProgramFiles}/Autodesk/Softimage 2013/XSISDK" - "C:/Softimage/XSI_6.0_x64/XSISDK" - "C:/Softimage/XSI_6.01_x64/XSISDK" - "C:/Softimage/XSI_6.02_x64/XSISDK" - "C:/Softimage/XSI_6.5_x64/XSISDK" - "C:/Softimage/XSI_7.0_x64/XSISDK" - "C:/Softimage/XSI_7.01_x64/XSISDK" - "C:/Softimage/XSI_7.5_x64/XSISDK" - "C:/Softimage/Softimage_2010_x64/XSISDK" - "C:/Softimage/Softimage_2010_SP1_x64/XSISDK" - "$ENV{ProgramW6432}/Autodesk/Softimage 2011/XSISDK" - "$ENV{ProgramW6432}/Autodesk/Softimage 2011 SP1/XSISDK" - "$ENV{ProgramW6432}/Autodesk/Softimage 2012/XSISDK" - "$ENV{ProgramW6432}/Autodesk/Softimage 2012 SP1/XSISDK" - "$ENV{ProgramW6432}/Autodesk/Softimage 2013/XSISDK" -) - -if (CMAKE_SIZEOF_VOID_P EQUAL 8) - set(Softimage_LIBPATH_SUFFIX "nt-x86-64") -else(CMAKE_SIZEOF_VOID_P EQUAL 8) - set(Softimage_LIBPATH_SUFFIX "nt-x86") -endif(CMAKE_SIZEOF_VOID_P EQUAL 8) - -create_search_paths(Softimage) -# redo search if prefix path changed -clear_if_changed(Softimage_PREFIX_PATH - Softimage_LIBRARY - Softimage_SICPPSDK_LIBRARY - Softimage_INCLUDE_DIR -) - -set(Softimage_LIBRARY_NAMES sicoresdk) -set(Softimage_SICPPSDK_LIBRARY_NAMES sicppsdk) - -find_path(Softimage_INCLUDE_DIR NAMES xsisdk.h HINTS ${Softimage_INC_SEARCH_PATH}) - -find_library(Softimage_LIBRARY NAMES ${Softimage_LIBRARY_NAMES} HINTS ${Softimage_LIB_SEARCH_PATH} PATH_SUFFIXES ${Softimage_LIBPATH_SUFFIX}) -find_library(Softimage_SICPPSDK_LIBRARY NAMES ${Softimage_SICPPSDK_LIBRARY_NAMES} HINTS ${Softimage_LIB_SEARCH_PATH} PATH_SUFFIXES ${Softimage_LIBPATH_SUFFIX}) - -findpkg_finish(Softimage) - -set(Softimage_LIBRARIES ${Softimage_LIBRARIES} - ${Softimage_SICPPSDK_LIBRARY} -) - -mark_as_advanced(Softimage_SICPPSDK_LIBRARY) diff --git a/CMake/Packages/FindWix.cmake b/CMake/Packages/FindWix.cmake deleted file mode 100644 index 1167d3a2d05..00000000000 --- a/CMake/Packages/FindWix.cmake +++ /dev/null @@ -1,32 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# - Try to find Wix -# You can help this by defining WIX_HOME in the environment / CMake -# Once done, this will define -# -# Wix_FOUND - system has Wix -# Wix_BINARY_DIR - location of the Wix binaries - -include(FindPkgMacros) - -# Get path, convert backslashes as ${ENV_${var}} -getenv_path(WIX_HOME) - -# construct search paths -set(WIX_PREFIX_PATH ${WIX_HOME} ${ENV_WIX_HOME} - "C:/Program Files/Windows Installer XML Toolset 3.0" -) -find_path(Wix_BINARY_DIR NAMES candle.exe HINTS ${WIX_PREFIX_PATH} PATH_SUFFIXES bin) - -if(Wix_BINARY_DIR) - set (Wix_FOUND TRUE) -endif() - -mark_as_advanced(Wix_BINARY_DIR Wix_FOUND) \ No newline at end of file diff --git a/CMake/Packaging.cmake b/CMake/Packaging.cmake deleted file mode 100644 index 3f56373dc88..00000000000 --- a/CMake/Packaging.cmake +++ /dev/null @@ -1,32 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -set(CPACK_PACKAGE_VERSION ${OGRE_VERSION}) -set(CPACK_PACKAGE_VERSION_MAJOR ${OGRE_VERSION_MAJOR}) -set(CPACK_PACKAGE_VERSION_MINOR ${OGRE_VERSION_MINOR}) -set(CPACK_PACKAGE_VERSION_PATCH ${OGRE_VERSION_PATCH}) - -set(CPACK_INSTALL_CMAKE_PROJECTS "${PROJECT_BINARY_DIR}" "OGRE" "ALL" "/") -set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Open Source 3D Graphics Engine") -set(CPACK_PACKAGE_INSTALL_DIRECTORY "OGRE") -set(CPACK_PACKAGE_NAME "OGRE") -set(CPACK_PACKAGE_VENDOR "Torus Knot Software") - -# CPack won't allow file without recognized extension to be used as -# license file. -configure_file("${PROJECT_SOURCE_DIR}/LICENSE" "${PROJECT_BINARY_DIR}/LICENSE.txt" COPYONLY) -set(CPACK_RESOURCE_FILE_LICENSE "${PROJECT_BINARY_DIR}/LICENSE.txt") - -#set(CPACK_PACKAGE_ICON "${PROJECT_SOURCE_DIR}\\\\ogrelogo.gif") - -set(CPACK_PACKAGE_CONTACT "OGRE Team ") - -set(CPACK_NSIS_EXTRA_INSTALL_COMMANDS "WriteRegStr \\\${WriteEnvStr_RegKey} \\\"OGRE_HOME\\\" $INSTDIR") - -include(CPack) diff --git a/CMake/PrepareThreadingOptions.cmake b/CMake/PrepareThreadingOptions.cmake deleted file mode 100644 index 629d452c471..00000000000 --- a/CMake/PrepareThreadingOptions.cmake +++ /dev/null @@ -1,51 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -####################################################################### -# This file determines which threading options are available for the -# build, depending on the dependencies found. -####################################################################### - -# sanitise threading choices -if (NOT OGRE_CONFIG_THREADS) - set(OGRE_CONFIG_THREAD_PROVIDER "none") -else () - if (OGRE_CONFIG_THREAD_PROVIDER STREQUAL "boost") - if (WIN32 OR APPLE) - # Prefer static linking in all cases - set(Boost_USE_STATIC_LIBS TRUE) - else () - # Statically linking boost to a dynamic Ogre build doesn't work on Linux 64bit - set(Boost_USE_STATIC_LIBS ${OGRE_STATIC}) - endif () - if (APPLE AND APPLE_IOS) - set(Boost_USE_MULTITHREADED OFF) - endif() - - if(ANDROID) - # FindBoost needs extra hint on android - set(Boost_COMPILER -gcc) - endif() - - find_package(Boost COMPONENTS thread QUIET) - if (NOT Boost_THREAD_FOUND) - message(WARNING "boost-thread is not available. Using ${OGRE_THREAD_DEFAULT_PROVIDER} as thread provider.") - set(OGRE_CONFIG_THREAD_PROVIDER ${OGRE_THREAD_DEFAULT_PROVIDER}) - endif () - elseif (OGRE_CONFIG_THREAD_PROVIDER STREQUAL "poco") - find_package(POCO) - if (NOT POCO_FOUND) - message(WARNING "poco is not available. Using ${OGRE_THREAD_DEFAULT_PROVIDER} as thread provider.") - set(OGRE_CONFIG_THREAD_PROVIDER ${OGRE_THREAD_DEFAULT_PROVIDER}) - endif () - elseif (OGRE_CONFIG_THREAD_PROVIDER STREQUAL "std") - else () - message(WARNING "Unknown thread provider chosen. Defaulting to std.") - endif () -endif () diff --git a/CMake/Templates/AndroidManifest.xml.in b/CMake/Templates/AndroidManifest.xml.in deleted file mode 100644 index 358ec8c1d50..00000000000 --- a/CMake/Templates/AndroidManifest.xml.in +++ /dev/null @@ -1,14 +0,0 @@ - - - - @ANDROID_ADDITIONAL_PERMISSION@ - - - @ANDROID_ACTIVITIES@ - - - \ No newline at end of file diff --git a/CMake/Templates/Android_resources.cfg.in b/CMake/Templates/Android_resources.cfg.in deleted file mode 100644 index c76b1f4ac23..00000000000 --- a/CMake/Templates/Android_resources.cfg.in +++ /dev/null @@ -1,41 +0,0 @@ -# Ogre Core Resources -[OgreInternal] -APKFileSystem=/Main -APKFileSystem=/RTShaderLib -APKFileSystem=/Terrain - -# Resources required by the sample browser and most samples. -[Essential] -APKZip=/packs/SdkTrays.zip -APKFileSystem=/thumbnails - -# Common sample resources needed by many of the samples. -# Rarely used resources should be separately loaded by the -# samples which require them. -[General] -APKFileSystem=/materials/programs/GLSL -APKFileSystem=/materials/programs/GLSLES -APKFileSystem=/materials/scripts -APKFileSystem=/materials/textures -APKFileSystem=/materials/textures/glTF2_IBL -APKFileSystem=/materials/textures/terrain -APKFileSystem=/models -APKFileSystem=/particle -APKFileSystem=/materials/scripts/SSAO -APKFileSystem=/materials/textures/SSAO -APKZip=/packs/cubemap.zip -APKZip=/packs/cubemapsJS.zip -APKZip=/packs/dragon.zip -APKZip=/packs/fresneldemo.zip -APKZip=/packs/ogretestmap.zip -APKZip=/packs/ogredance.zip -APKZip=/packs/Sinbad.zip -APKZip=/packs/skybox.zip -APKZip=/packs/DamagedHelmet.zip - -APKFileSystem=/PBR -APKFileSystem=/DeferredShadingMedia -APKFileSystem=/DeferredShadingMedia/DeferredShading/post - -[BSPWorld] -APKZip=/packs/oa_rpg3dm2.pk3 \ No newline at end of file diff --git a/CMake/Templates/DemoLicense.rtf b/CMake/Templates/DemoLicense.rtf deleted file mode 100644 index cfb5e5dcaaf..00000000000 --- a/CMake/Templates/DemoLicense.rtf +++ /dev/null @@ -1,17 +0,0 @@ -{\rtf1\ansi\ansicpg1252\cocoartf1265\cocoasubrtf120 -\cocoascreenfonts1{\fonttbl\f0\fmodern\fcharset0 CourierNewPSMT;} -{\colortbl;\red255\green255\blue255;} -\vieww12000\viewh15060\viewkind0 -\deftab720 -\pard\pardeftab720 - -\f0\fs20 \cf0 OGRE (www.ogre3d.org) is made available under the MIT License.\ -\ -Copyright (c) 2000-2014 Torus Knot Software Ltd\ -\ -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\ -\ -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\ -\ -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\ -} \ No newline at end of file diff --git a/CMake/Templates/OGRE-Bites.pc.in b/CMake/Templates/OGRE-Bites.pc.in deleted file mode 100644 index aded9b18228..00000000000 --- a/CMake/Templates/OGRE-Bites.pc.in +++ /dev/null @@ -1,11 +0,0 @@ -prefix=@OGRE_PREFIX_PATH@ -exec_prefix=${prefix} -libdir=${prefix}/@OGRE_LIB_DIRECTORY@ -includedir=${prefix}/include - -Name: OGRE-Bites -Description: Bites component for OGRE -Version: @OGRE_VERSION@ -Requires: OGRE = @OGRE_VERSION@ @OGRE_BITES_ADDITIONAL_PACKAGES@ -Libs: -L${libdir} -lOgreBites@OGRE_LIB_SUFFIX@ -Cflags: -I${includedir}/OGRE/Bites @OGRE_CFLAGS@ \ No newline at end of file diff --git a/CMake/Templates/OGRE-MeshLodGenerator.pc.in b/CMake/Templates/OGRE-MeshLodGenerator.pc.in deleted file mode 100644 index 22e01ba7a75..00000000000 --- a/CMake/Templates/OGRE-MeshLodGenerator.pc.in +++ /dev/null @@ -1,11 +0,0 @@ -prefix=@OGRE_PREFIX_PATH@ -exec_prefix=${prefix} -libdir=${prefix}/@OGRE_LIB_DIRECTORY@ -includedir=${prefix}/include - -Name: OGRE-MeshLodGenerator -Description: Mesh Lod Generator for OGRE -Version: @OGRE_VERSION@ -Requires: OGRE = @OGRE_VERSION@ -Libs: -L${libdir} -lOgreMeshLodGenerator@OGRE_LIB_SUFFIX@ -Cflags: -I${includedir}/OGRE/MeshLodGenerator @OGRE_CFLAGS@ diff --git a/CMake/Templates/OGRE-Overlay.pc.in b/CMake/Templates/OGRE-Overlay.pc.in deleted file mode 100644 index da2e9dde130..00000000000 --- a/CMake/Templates/OGRE-Overlay.pc.in +++ /dev/null @@ -1,11 +0,0 @@ -prefix=@OGRE_PREFIX_PATH@ -exec_prefix=${prefix} -libdir=${prefix}/@OGRE_LIB_DIRECTORY@ -includedir=${prefix}/include - -Name: OGRE-Overlay -Description: Overlay component for OGRE -Version: @OGRE_VERSION@ -Requires: OGRE = @OGRE_VERSION@ -Libs: -L${libdir} -lOgreOverlay@OGRE_LIB_SUFFIX@ -Cflags: -I${includedir}/OGRE/Overlay @OGRE_CFLAGS@ \ No newline at end of file diff --git a/CMake/Templates/OGRE-PCZ.pc.in b/CMake/Templates/OGRE-PCZ.pc.in deleted file mode 100644 index 4f77a0ea5f2..00000000000 --- a/CMake/Templates/OGRE-PCZ.pc.in +++ /dev/null @@ -1,11 +0,0 @@ -prefix=@OGRE_PREFIX_PATH@ -exec_prefix=${prefix} -plugindir=${prefix}/@OGRE_PLUGINS_PATH@ -includedir=${prefix}/include - -Name: OGRE-PCZ -Description: Portal-Connected Zone Scene Manager for OGRE -Version: @OGRE_VERSION@ -Requires: OGRE = @OGRE_VERSION@ -Libs: -L${plugindir} -lPlugin_PCZSceneManager@OGRE_LIB_SUFFIX@ -lPlugin_OctreeZone@OGRE_LIB_SUFFIX@ -Cflags: -I${includedir}/OGRE/Plugins/PCZSceneManager -I${includedir}/OGRE/Plugins/OctreeZone @OGRE_CFLAGS@ diff --git a/CMake/Templates/OGRE-Paging.pc.in b/CMake/Templates/OGRE-Paging.pc.in deleted file mode 100644 index 356199b0251..00000000000 --- a/CMake/Templates/OGRE-Paging.pc.in +++ /dev/null @@ -1,11 +0,0 @@ -prefix=@OGRE_PREFIX_PATH@ -exec_prefix=${prefix} -libdir=${prefix}/@OGRE_LIB_DIRECTORY@ -includedir=${prefix}/include - -Name: OGRE-Paging -Description: General purpose paging component for OGRE -Version: @OGRE_VERSION@ -Requires: OGRE = @OGRE_VERSION@ -Libs: -L${libdir} -lOgrePaging@OGRE_LIB_SUFFIX@ -Cflags: -I${includedir}/OGRE/Paging @OGRE_CFLAGS@ diff --git a/CMake/Templates/OGRE-Property.pc.in b/CMake/Templates/OGRE-Property.pc.in deleted file mode 100644 index a177699a193..00000000000 --- a/CMake/Templates/OGRE-Property.pc.in +++ /dev/null @@ -1,11 +0,0 @@ -prefix=@OGRE_PREFIX_PATH@ -exec_prefix=${prefix} -libdir=${prefix}/@OGRE_LIB_DIRECTORY@ -includedir=${prefix}/include - -Name: OGRE-Property -Description: General purpose property component for OGRE -Version: @OGRE_VERSION@ -Requires: OGRE = @OGRE_VERSION@ -Libs: -L${libdir} -lOgreProperty@OGRE_LIB_SUFFIX@ -Cflags: -I${includedir}/OGRE/Property @OGRE_CFLAGS@ diff --git a/CMake/Templates/OGRE-RTShaderSystem.pc.in b/CMake/Templates/OGRE-RTShaderSystem.pc.in deleted file mode 100644 index e50a5740a7a..00000000000 --- a/CMake/Templates/OGRE-RTShaderSystem.pc.in +++ /dev/null @@ -1,11 +0,0 @@ -prefix=@OGRE_PREFIX_PATH@ -exec_prefix=${prefix} -libdir=${prefix}/@OGRE_LIB_DIRECTORY@ -includedir=${prefix}/include - -Name: OGRE-RTShaderSystem -Description: Real time shader generation component for OGRE -Version: @OGRE_VERSION@ -Requires: OGRE = @OGRE_VERSION@ -Libs: -L${libdir} -lOgreRTShaderSystem@OGRE_LIB_SUFFIX@ -Cflags: -I${includedir}/OGRE/RTShaderSystem @OGRE_CFLAGS@ diff --git a/CMake/Templates/OGRE-Terrain.pc.in b/CMake/Templates/OGRE-Terrain.pc.in deleted file mode 100644 index 356cd11f0d2..00000000000 --- a/CMake/Templates/OGRE-Terrain.pc.in +++ /dev/null @@ -1,11 +0,0 @@ -prefix=@OGRE_PREFIX_PATH@ -exec_prefix=${prefix} -libdir=${prefix}/@OGRE_LIB_DIRECTORY@ -includedir=${prefix}/include - -Name: OGRE-Terrain -Description: Outdoor terrain component for OGRE -Version: @OGRE_VERSION@ -Requires: OGRE = @OGRE_VERSION@ @OGRE_PAGING_ADDITIONAL_PACKAGES@ -Libs: -L${libdir} -lOgreTerrain@OGRE_LIB_SUFFIX@ -Cflags: -I${includedir}/OGRE/Terrain @OGRE_CFLAGS@ diff --git a/CMake/Templates/OGRE-Volume.pc.in b/CMake/Templates/OGRE-Volume.pc.in deleted file mode 100644 index 792dc7d6710..00000000000 --- a/CMake/Templates/OGRE-Volume.pc.in +++ /dev/null @@ -1,11 +0,0 @@ -prefix=@OGRE_PREFIX_PATH@ -exec_prefix=${prefix} -libdir=${prefix}/@OGRE_LIB_DIRECTORY@ -includedir=${prefix}/include - -Name: OGRE-Volume -Description: Voxel based terrain component for OGRE -Version: @OGRE_VERSION@ -Requires: OGRE = @OGRE_VERSION@ -Libs: -L${libdir} -lOgreVolume@OGRE_LIB_SUFFIX@ -Cflags: -I${includedir}/OGRE/Volume @OGRE_CFLAGS@ diff --git a/CMake/Templates/OGRE.pc.in b/CMake/Templates/OGRE.pc.in deleted file mode 100644 index 2e036c2b69d..00000000000 --- a/CMake/Templates/OGRE.pc.in +++ /dev/null @@ -1,12 +0,0 @@ -prefix=@OGRE_PREFIX_PATH@ -exec_prefix=${prefix} -libdir=${prefix}/@OGRE_LIB_DIRECTORY@ -includedir=${prefix}/include -plugindir=${prefix}/@OGRE_PLUGINS_PATH@ - -Name: OGRE -Description: Object-Oriented Graphics Rendering Engine -Version: @OGRE_VERSION@ -URL: http://www.ogre3d.org -Libs: -L${libdir} -lOgreMain@OGRE_LIB_SUFFIX@ @OGRE_ADDITIONAL_LIBS@ -Cflags: -I${includedir}/OGRE @OGRE_CFLAGS@ diff --git a/CMake/Templates/OGRE.props.in b/CMake/Templates/OGRE.props.in deleted file mode 100644 index e86c0181a42..00000000000 --- a/CMake/Templates/OGRE.props.in +++ /dev/null @@ -1,42 +0,0 @@ - - - - - @CMAKE_INSTALL_PREFIX@ - $(OGRE_HOME)/include - $(OGRE_HOME)/lib - $(OGRE_HOME)/bin - $(OGRE_HOME)/@OGRE_MEDIA_PATH@ - - - - - $(OGRE_INCLUDE);$(OGRE_INCLUDE)/OGRE;$(OGRE_INCLUDE)/OGRE/Overlay;$(OGRE_INCLUDE)/OIS;%(AdditionalIncludeDirectories) - - - $(OGRE_LIB);$(OGRE_LIB)/$(Configuration);%(AdditionalLibraryDirectories) - - - - - $(OGRE_HOME) - true - - - $(OGRE_INCLUDE) - true - - - $(OGRE_LIB) - true - - - $(OGRE_BIN) - true - - - $(OGRE_MEDIA) - true - - - \ No newline at end of file diff --git a/CMake/Templates/OGREConfig.cmake.in b/CMake/Templates/OGREConfig.cmake.in deleted file mode 100644 index 2047f6648e1..00000000000 --- a/CMake/Templates/OGREConfig.cmake.in +++ /dev/null @@ -1,173 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Find OGRE includes and library -# -# This module defines -# OGRE_INCLUDE_DIRS - the OGRE include directories -# OGRE_LIBRARIES - link these to use the OGRE -# OGRE_LIBRARY_DIRS, the location of the libraries -# OGRE_STATIC - whther ogre was build as static lib -# OGRE_${COMPONENT}_FOUND - ${COMPONENT} is available -# OGRE_${COMPONENT}_LIBRARIES - link these to only use ${COMPONENT} -# OGRE_PLUGIN_DIR - The directory where the OGRE plugins are located -# OGRE_MEDIA_DIR - The directory where the OGRE sample media is located -# OGRE_CONFIG_DIR - The directory where the OGRE config files are located - -@PACKAGE_INIT@ - -set(OGRE_STATIC @OGRE_STATIC@) -set_and_check(OGRE_MEDIA_DIR "@PACKAGE_OGRE_MEDIA_PATH@") -set_and_check(OGRE_PLUGIN_DIR "@PACKAGE_OGRE_PLUGINS_PATH@") -set_and_check(OGRE_CONFIG_DIR "@PACKAGE_OGRE_CFG_INSTALL_PATH@") - -set(OGRE_PREFIX_DIR "@PACKAGE_CMAKE_INSTALL_PREFIX@") -get_filename_component(OGRE_LIBRARY_DIRS "${OGRE_PREFIX_DIR}/lib" ABSOLUTE) -get_filename_component(OGRE_INCLUDE_DIRS "${OGRE_PREFIX_DIR}/include/OGRE" ABSOLUTE) -set(OGRE_LIBRARIES) - -cmake_policy(PUSH) -cmake_policy(SET CMP0012 NEW) - -if(@OGRE_THREAD_PROVIDER@ EQUAL 1) - list(APPEND OGRE_INCLUDE_DIRS @Boost_INCLUDE_DIRS@) -endif() - -list(APPEND OGRE_LIBRARIES @OGRE_THREAD_LIBRARIES@) - -set(OGRE_COMPONENTS) -set(OGRE_PLUGINS) - -macro(ogre_declare_component COMPONENT) - set(OGRE_${COMPONENT}_FOUND TRUE) - set(OGRE_${COMPONENT}_LIBRARIES Ogre${COMPONENT}) # backwards compatibility - - list(APPEND OGRE_COMPONENTS ${COMPONENT}) - list(APPEND OGRE_LIBRARIES Ogre${COMPONENT}) -endmacro() - -macro(ogre_declare_plugin TYPE COMPONENT) - set(OGRE_${TYPE}_${COMPONENT}_FOUND TRUE) - set(OGRE_${TYPE}_${COMPONENT}_LIBRARIES ${TYPE}_${COMPONENT}) - - if(@OGRE_STATIC@) - list(APPEND OGRE_LIBRARIES ${TYPE}_${COMPONENT}) - endif() - - list(APPEND OGRE_PLUGINS ${TYPE}_${COMPONENT}) -endmacro() - -## COMPONENTS -include("${CMAKE_CURRENT_LIST_DIR}/OgreTargets.cmake") - -if(@OGRE_BUILD_COMPONENT_BITES@) - ogre_declare_component(Bites) -endif() -if(@OGRE_BUILD_COMPONENT_BULLET@) - ogre_declare_component(Bullet) -endif() -if(@OGRE_BUILD_COMPONENT_MESHLODGENERATOR@) - ogre_declare_component(MeshLodGenerator) -endif() -if(@OGRE_BUILD_COMPONENT_OVERLAY@) - ogre_declare_component(Overlay) -endif() -if(@OGRE_BUILD_COMPONENT_PAGING@) - ogre_declare_component(Paging) -endif() -if(@OGRE_BUILD_COMPONENT_PROPERTY@) - ogre_declare_component(Property) -endif() -if(@OGRE_BUILD_COMPONENT_RTSHADERSYSTEM@) - ogre_declare_component(RTShaderSystem) -endif() -if(@OGRE_BUILD_COMPONENT_TERRAIN@) - ogre_declare_component(Terrain) -endif() -if(@OGRE_BUILD_COMPONENT_VOLUME@) - ogre_declare_component(Volume) -endif() - -## PLUGINS -if(@OGRE_BUILD_PLUGIN_BSP@) - ogre_declare_plugin(Plugin BSPSceneManager) -endif() - -if(@OGRE_BUILD_PLUGIN_CG@) - ogre_declare_plugin(Plugin CgProgramManager) -endif() - -if(@OGRE_BUILD_PLUGIN_OCTREE@) - ogre_declare_plugin(Plugin OctreeSceneManager) -endif() - -if(@OGRE_BUILD_PLUGIN_PCZ@) - ogre_declare_plugin(Plugin PCZSceneManager) -endif() - -if(@OGRE_BUILD_PLUGIN_PFX@) - ogre_declare_plugin(Plugin ParticleFX) -endif() - -if(@OGRE_BUILD_RENDERSYSTEM_GL@) - ogre_declare_plugin(RenderSystem GL) -endif() - -if(@OGRE_BUILD_RENDERSYSTEM_GLES2@) - ogre_declare_plugin(RenderSystem GLES2) -endif() - -if(@OGRE_BUILD_RENDERSYSTEM_GL3PLUS@) - ogre_declare_plugin(RenderSystem GL3Plus) -endif() - -if(@OGRE_BUILD_RENDERSYSTEM_D3D9@) - ogre_declare_plugin(RenderSystem Direct3D9) -endif() - -if(@OGRE_BUILD_RENDERSYSTEM_D3D11@) - ogre_declare_plugin(RenderSystem Direct3D11) -endif() - -if(@OGRE_BUILD_PLUGIN_STBI@) - ogre_declare_plugin(Codec STBI) -endif() - -if(@OGRE_BUILD_PLUGIN_FREEIMAGE@) - ogre_declare_plugin(Codec FreeImage) -endif() - -if(@OGRE_BUILD_PLUGIN_EXRCODEC@) - ogre_declare_plugin(Codec EXR) -endif() -cmake_policy(POP) - -if(@OGRE_STATIC@) - list(APPEND OGRE_LIBRARIES OgreGLSupport@OGRE_LIB_SUFFIX@ @CMAKE_DL_LIBS@) # glXXw uses dlopen - list(APPEND OGRE_LIBRARY_DIRS "${OGRE_LIBRARY_DIRS}/OGRE") # plugins folder -endif() - -# must come last in case of static build -list(APPEND OGRE_LIBRARIES OgreMain) - -foreach(_comp ${OGRE_FIND_COMPONENTS}) - list (FIND OGRE_COMPONENTS ${_comp} _index) - if (_index EQUAL -1 AND OGRE_FIND_REQUIRED_${_comp}) - set(OGRE_FOUND False) - set(OGRE_NOT_FOUND_MESSAGE "Component '${_comp}' is required but was not found") - endif() -endforeach() - -if(NOT OGRE_FIND_QUIETLY) - message(STATUS "Found OGRE") - message(STATUS " static : ${OGRE_STATIC}") - message(STATUS " components : ${OGRE_COMPONENTS}") - message(STATUS " plugins : ${OGRE_PLUGINS}") - message(STATUS " media : ${OGRE_MEDIA_DIR}") -endif() diff --git a/CMake/Templates/OGREStatic.pc.in b/CMake/Templates/OGREStatic.pc.in deleted file mode 100644 index 4e4202bb8b5..00000000000 --- a/CMake/Templates/OGREStatic.pc.in +++ /dev/null @@ -1,13 +0,0 @@ -prefix=@OGRE_PREFIX_PATH@ -exec_prefix=${prefix} -libdir=${prefix}/@OGRE_LIB_DIRECTORY@ -includedir=${prefix}/include -plugindir=${prefix}/@OGRE_PLUGINS_PATH@ - -Name: OGRE (static lib) -Description: Object-Oriented Graphics Rendering Engine -Version: @OGRE_VERSION@ -URL: http://www.ogre3d.org -Requires: freetype2, zziplib, x11, xt, xaw7, gl -Libs: -L${libdir} -L${plugindir} -lOgreMain@OGRE_LIB_SUFFIX@ @OGRE_ADDITIONAL_LIBS@ -Cflags: -I${includedir} -I${includedir}/OGRE @OGRE_CFLAGS@ diff --git a/CMake/Templates/OgreBuildSettings.h.in b/CMake/Templates/OgreBuildSettings.h.in deleted file mode 100644 index 19c3c0d36ca..00000000000 --- a/CMake/Templates/OgreBuildSettings.h.in +++ /dev/null @@ -1,108 +0,0 @@ -#ifndef __Custom_Config_H_ -#define __Custom_Config_H_ - -// CMake auto-generated configuration options - -// Define ogre version -#define OGRE_VERSION_MAJOR @OGRE_VERSION_MAJOR@ -#define OGRE_VERSION_MINOR @OGRE_VERSION_MINOR@ -#define OGRE_VERSION_PATCH @OGRE_VERSION_PATCH@ -#define OGRE_VERSION_SUFFIX "@OGRE_VERSION_SUFFIX@" -#define OGRE_VERSION_NAME "@OGRE_VERSION_NAME@" - -#cmakedefine OGRE_STATIC_LIB -#cmakedefine01 OGRE_DEBUG_MODE - -/** There are three modes for resource lookup -0 - LEGACY - search in all groups twice - for case sensitive and insensitive lookup -1 - PEDANTIC - require an explicit resource group. Case sensitive lookup. -2 - STRICT - search in default group if not specified otherwise. Case sensitive lookup. -*/ -#define OGRE_RESOURCEMANAGER_STRICT @OGRE_RESOURCEMANAGER_STRICT@ - -#cmakedefine OGRE_NODELESS_POSITIONING - -#cmakedefine OGRE_CONFIG_LITTLE_ENDIAN -#cmakedefine OGRE_CONFIG_BIG_ENDIAN - -/** If set to 1, Real is typedef'ed to double. Otherwise, Real is typedef'ed - to float. Setting this allows you to perform mathematical operations in the - CPU (Quaternion, Vector3 etc) with more precision, but bear in mind that the - GPU still operates in single-precision mode. -*/ -#cmakedefine01 OGRE_DOUBLE_PRECISION - -#cmakedefine01 OGRE_NODE_INHERIT_TRANSFORM - -/** There are three modes for handling asserts in OGRE: -0 - STANDARD - Standard asserts in debug builds, nothing in release builds -1 - RELEASE_EXCEPTIONS - Standard asserts in debug builds, exceptions in release builds -2 - EXCEPTIONS - Exceptions in debug builds, exceptions in release builds -*/ -#define OGRE_ASSERT_MODE @OGRE_SET_ASSERT_MODE@ - -/** Support for multithreading, there are 3 options - -OGRE_THREAD_SUPPORT = 0 - No support for threading. -OGRE_THREAD_SUPPORT = 1 - Thread support for background loading, by both loading and constructing resources - in a background thread. Resource management and SharedPtr handling becomes - thread-safe, and resources may be completely loaded in the background. - The places where threading is available are clearly - marked, you should assume state is NOT thread safe unless otherwise - stated in relation to this flag. -OGRE_THREAD_SUPPORT = 2 - Thread support for background resource preparation. This means that resource - data can streamed into memory in the background, but the final resource - construction (including RenderSystem dependencies) is still done in the primary - thread. Has a lower synchronisation primitive overhead than full threading - while still allowing the major blocking aspects of resource management (I/O) - to be done in the background. -OGRE_THREAD_SUPPORT = 3 - No synchronisation primitive overhead. WorkQueue is threaded. -*/ -#define OGRE_THREAD_SUPPORT @OGRE_SET_THREADS@ - -/** Provider for threading functionality, there are 4 options. - -OGRE_THREAD_PROVIDER = 0 - No support for threading. -OGRE_THREAD_PROVIDER = 1 - Boost libraries provide threading functionality. -OGRE_THREAD_PROVIDER = 2 - Poco libraries provide threading functionality. -OGRE_THREAD_PROVIDER = 4 - Standard library provides threading functionality. (requires compiler support) -*/ -#define OGRE_THREAD_PROVIDER @OGRE_SET_THREAD_PROVIDER@ - -#cmakedefine01 OGRE_NO_MESHLOD - -/** Disables use of the internal image codec for loading DDS files. */ -#cmakedefine01 OGRE_NO_DDS_CODEC - -/** Disables use of the internal image codec for loading PVRTC files. */ -#cmakedefine01 OGRE_NO_PVRTC_CODEC - -/** Disables use of the internal image codec for loading ETC files. */ -#cmakedefine01 OGRE_NO_ETC_CODEC - -#cmakedefine01 OGRE_NO_ASTC_CODEC - -/** Disables use of the ZIP archive support. -WARNING: Disabling this will make the samples unusable. -*/ -#cmakedefine01 OGRE_NO_ZIP_ARCHIVE - -#cmakedefine01 OGRE_NO_TBB_SCHEDULER - -/** If set to 1, profiling code will be included in the application. When you - are deploying your application you will probably want to set this to 0 */ -#cmakedefine01 OGRE_PROFILING - -#cmakedefine01 OGRE_NO_QUAD_BUFFER_STEREO - -#cmakedefine01 OGRE_NO_LOCALE_STRCONVERT - -#endif diff --git a/CMake/Templates/OgreComponents.h.in b/CMake/Templates/OgreComponents.h.in deleted file mode 100644 index 0fb5c3fe78b..00000000000 --- a/CMake/Templates/OgreComponents.h.in +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef __OGRE_COMPONENTS_Config_H_ -#define __OGRE_COMPONENTS_Config_H_ - -#cmakedefine OGRE_BUILD_RENDERSYSTEM_D3D9 -#cmakedefine OGRE_BUILD_RENDERSYSTEM_D3D11 -#cmakedefine OGRE_BUILD_RENDERSYSTEM_GL -#cmakedefine OGRE_BUILD_RENDERSYSTEM_GL3PLUS -#cmakedefine OGRE_BUILD_RENDERSYSTEM_GLES2 -#cmakedefine OGRE_BUILD_RENDERSYSTEM_TINY -#cmakedefine OGRE_BUILD_RENDERSYSTEM_VULKAN -#cmakedefine OGRE_BUILD_PLUGIN_ASSIMP -#cmakedefine OGRE_BUILD_PLUGIN_BSP -#cmakedefine OGRE_BUILD_PLUGIN_OCTREE -#cmakedefine OGRE_BUILD_PLUGIN_PCZ -#cmakedefine OGRE_BUILD_PLUGIN_PFX -#cmakedefine OGRE_BUILD_PLUGIN_CG -#cmakedefine OGRE_BUILD_PLUGIN_GLSLANG -#cmakedefine OGRE_BUILD_PLUGIN_STBI -#cmakedefine OGRE_BUILD_PLUGIN_RSIMAGE -#cmakedefine OGRE_BUILD_PLUGIN_FREEIMAGE -#cmakedefine OGRE_BUILD_PLUGIN_DOT_SCENE -#cmakedefine OGRE_BUILD_COMPONENT_PAGING -#cmakedefine OGRE_BUILD_COMPONENT_MESHLODGENERATOR -#cmakedefine OGRE_BUILD_COMPONENT_TERRAIN -#cmakedefine OGRE_BUILD_COMPONENT_VOLUME -#cmakedefine OGRE_BUILD_COMPONENT_PROPERTY -#cmakedefine OGRE_BUILD_COMPONENT_OVERLAY -#cmakedefine OGRE_BUILD_COMPONENT_RTSHADERSYSTEM -#cmakedefine OGRE_BUILD_COMPONENT_BULLET - -#cmakedefine01 OGRE_BITES_HAVE_SDL - -#endif diff --git a/CMake/Templates/OgreConfigPaths.h.in b/CMake/Templates/OgreConfigPaths.h.in deleted file mode 100644 index d51aab5475c..00000000000 --- a/CMake/Templates/OgreConfigPaths.h.in +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef OGRECONFIGPATHS_H_ -#define OGRECONFIGPATHS_H_ - -#define OGRE_CONFIG_DIR "@CMAKE_INSTALL_PREFIX@/@OGRE_CFG_INSTALL_PATH@" -#define OGRE_MEDIA_DIR "@CMAKE_INSTALL_PREFIX@/@OGRE_MEDIA_PATH@" -#define OGRE_PLUGIN_DIR "@OGRE_PLUGIN_DIR_REL@" - -#endif /* OGRECONFIGPATHS_H_ */ diff --git a/CMake/Templates/OgreGLES2Config.h.in b/CMake/Templates/OgreGLES2Config.h.in deleted file mode 100644 index c5817f2313c..00000000000 --- a/CMake/Templates/OgreGLES2Config.h.in +++ /dev/null @@ -1,10 +0,0 @@ -#ifndef RENDERSYSTEMS_GLES2_INCLUDE_OGREGLES2CONFIG_H_ -#define RENDERSYSTEMS_GLES2_INCLUDE_OGREGLES2CONFIG_H_ - -#cmakedefine01 OGRE_NO_GLES2_CG_SUPPORT - -#cmakedefine01 OGRE_NO_GLES2_GLSL_OPTIMISER - -#cmakedefine01 OGRE_NO_GLES3_SUPPORT - -#endif diff --git a/CMake/Templates/OgreRTShaderConfig.h.in b/CMake/Templates/OgreRTShaderConfig.h.in deleted file mode 100644 index edf1215da65..00000000000 --- a/CMake/Templates/OgreRTShaderConfig.h.in +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef COMPONENTS_RTSHADERSYSTEM_INCLUDE_OGRERTSHADERCONFIG_H_ -#define COMPONENTS_RTSHADERSYSTEM_INCLUDE_OGRERTSHADERCONFIG_H_ - -#cmakedefine RTSHADER_SYSTEM_BUILD_CORE_SHADERS - -#cmakedefine RTSHADER_SYSTEM_BUILD_EXT_SHADERS - -#endif diff --git a/CMake/Templates/Package_vc1900.WindowsStore.appxmanifest.in b/CMake/Templates/Package_vc1900.WindowsStore.appxmanifest.in deleted file mode 100644 index 6fb99ed1422..00000000000 --- a/CMake/Templates/Package_vc1900.WindowsStore.appxmanifest.in +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - @SHORT_NAME@ - Torus Knot Software - StoreLogo.png - - - - - - - - - - - - - - - - - - - - diff --git a/CMake/Templates/app.gradle.in b/CMake/Templates/app.gradle.in deleted file mode 100644 index 08c2d558ff2..00000000000 --- a/CMake/Templates/app.gradle.in +++ /dev/null @@ -1,22 +0,0 @@ -apply plugin: 'com.android.application' - -android { - compileSdkVersion 30 - - defaultConfig { - applicationId "@PKG_NAME@" - minSdkVersion 16 - targetSdkVersion 30 - } - - buildTypes { - release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' - } - } -} - -dependencies { - implementation 'androidx.core:core:1.0.2' -} \ No newline at end of file diff --git a/CMake/Templates/demomedia.wxi.in b/CMake/Templates/demomedia.wxi.in deleted file mode 100644 index 8535c751ecb..00000000000 --- a/CMake/Templates/demomedia.wxi.in +++ /dev/null @@ -1,1797 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/CMake/Templates/demos.wxs.in b/CMake/Templates/demos.wxs.in deleted file mode 100644 index a9eb6e37be7..00000000000 --- a/CMake/Templates/demos.wxs.in +++ /dev/null @@ -1,123 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/CMake/Templates/gradle.properties b/CMake/Templates/gradle.properties deleted file mode 100644 index 2d8d1e4dd15..00000000000 --- a/CMake/Templates/gradle.properties +++ /dev/null @@ -1 +0,0 @@ -android.useAndroidX=true \ No newline at end of file diff --git a/CMake/Templates/html.cfg.in b/CMake/Templates/html.cfg.in deleted file mode 100644 index 8ad62531d1e..00000000000 --- a/CMake/Templates/html.cfg.in +++ /dev/null @@ -1,1495 +0,0 @@ -# Doxyfile 1.8.3 - -# This file describes the settings to be used by the documentation system -# doxygen (www.doxygen.org) for a project. -# -# All text after a hash (#) is considered a comment and will be ignored. -# The format is: -# TAG = value [value, ...] -# For lists items can also be appended using: -# TAG += value [value, ...] -# Values that contain spaces should be placed between quotes (" "). - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- - -# This tag specifies the encoding used for all characters in the config file -# that follow. The default is UTF-8 which is also the encoding used for all -# text before the first occurrence of this tag. Doxygen uses libiconv (or the -# iconv built into libc) for the transcoding. See -# http://www.gnu.org/software/libiconv for the list of possible encodings. - -DOXYFILE_ENCODING = UTF-8 - -# The PROJECT_NAME tag is a single word (or sequence of words) that should -# identify the project. Note that if you do not use Doxywizard you need -# to put quotes around the project name if it contains spaces. - -PROJECT_NAME = OGRE - -# The PROJECT_NUMBER tag can be used to enter a project or revision number. -# This could be handy for archiving the generated documentation or -# if some version control system is used. - -PROJECT_NUMBER = ${OGRE_SOVERSION} - -# Using the PROJECT_BRIEF tag one can provide an optional one line description -# for a project that appears at the top of each page and should give viewer -# a quick idea about the purpose of the project. Keep the description short. - -PROJECT_BRIEF = "Object-Oriented Graphics Rendering Engine" - -# With the PROJECT_LOGO tag one can specify an logo or icon that is -# included in the documentation. The maximum height of the logo should not -# exceed 55 pixels and the maximum width should not exceed 200 pixels. -# Doxygen will copy the logo to the output directory. - -PROJECT_LOGO = "${PROJECT_SOURCE_DIR}/Docs/ogre-logo.png" - -# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) -# base path where the generated documentation will be put. -# If a relative path is entered, it will be relative to the location -# where doxygen was started. If left blank the current directory will be used. - -OUTPUT_DIRECTORY = "${PROJECT_BINARY_DIR}/api/" - -# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create -# 4096 sub-directories (in 2 levels) under the output directory of each output -# format and will distribute the generated files over these directories. -# Enabling this option can be useful when feeding doxygen a huge amount of -# source files, where putting all generated files in the same directory would -# otherwise cause performance problems for the file system. - -CREATE_SUBDIRS = NO - -# The OUTPUT_LANGUAGE tag is used to specify the language in which all -# documentation generated by doxygen is written. Doxygen will use this -# information to generate all constant output in the proper language. -# The default language is English, other supported languages are: -# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, -# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, -# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English -# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, -# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, -# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. - -OUTPUT_LANGUAGE = English - -# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will -# include brief member descriptions after the members that are listed in -# the file and class documentation (similar to JavaDoc). -# Set to NO to disable this. - -BRIEF_MEMBER_DESC = YES - -# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend -# the brief description of a member or function before the detailed description. -# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the -# brief descriptions will be completely suppressed. - -REPEAT_BRIEF = YES - -# This tag implements a quasi-intelligent brief description abbreviator -# that is used to form the text in various listings. Each string -# in this list, if found as the leading text of the brief description, will be -# stripped from the text and the result after processing the whole list, is -# used as the annotated text. Otherwise, the brief description is used as-is. -# If left blank, the following values are used ("$name" is automatically -# replaced with the name of the entity): "The $name class" "The $name widget" -# "The $name file" "is" "provides" "specifies" "contains" -# "represents" "a" "an" "the" - -ABBREVIATE_BRIEF = "The $name class " \ - "The $name widget " \ - "The $name file " \ - is \ - provides \ - specifies \ - contains \ - represents \ - a \ - an \ - the - -# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then -# Doxygen will generate a detailed section even if there is only a brief -# description. - -ALWAYS_DETAILED_SEC = YES - -# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all -# inherited members of a class in the documentation of that class as if those -# members were ordinary class members. Constructors, destructors and assignment -# operators of the base classes will not be shown. - -INLINE_INHERITED_MEMB = NO - -# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full -# path before files name in the file list and in the header files. If set -# to NO the shortest path that makes the file name unique will be used. - -FULL_PATH_NAMES = NO - -# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag -# can be used to strip a user-defined part of the path. Stripping is -# only done if one of the specified strings matches the left-hand part of -# the path. The tag can be used to show relative paths in the file list. -# If left blank the directory from which doxygen is run is used as the -# path to strip. Note that you specify absolute paths here, but also -# relative paths, which will be relative from the directory where doxygen is -# started. - -STRIP_FROM_PATH = - -# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of -# the path mentioned in the documentation of a class, which tells -# the reader which header file to include in order to use a class. -# If left blank only the name of the header file containing the class -# definition is used. Otherwise one should specify the include paths that -# are normally passed to the compiler using the -I flag. - -STRIP_FROM_INC_PATH = - -# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter -# (but less readable) file names. This can be useful if your file system -# doesn't support long names like on DOS, Mac, or CD-ROM. - -SHORT_NAMES = NO - -# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen -# will interpret the first line (until the first dot) of a JavaDoc-style -# comment as the brief description. If set to NO, the JavaDoc -# comments will behave just like regular Qt-style comments -# (thus requiring an explicit @brief command for a brief description.) - -JAVADOC_AUTOBRIEF = YES - -# If the QT_AUTOBRIEF tag is set to YES then Doxygen will -# interpret the first line (until the first dot) of a Qt-style -# comment as the brief description. If set to NO, the comments -# will behave just like regular Qt-style comments (thus requiring -# an explicit \brief command for a brief description.) - -QT_AUTOBRIEF = NO - -# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen -# treat a multi-line C++ special comment block (i.e. a block of //! or /// -# comments) as a brief description. This used to be the default behaviour. -# The new default is to treat a multi-line C++ comment block as a detailed -# description. Set this tag to YES if you prefer the old behaviour instead. - -MULTILINE_CPP_IS_BRIEF = NO - -# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented -# member inherits the documentation from any documented member that it -# re-implements. - -INHERIT_DOCS = YES - -# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce -# a new page for each member. If set to NO, the documentation of a member will -# be part of the file/class/namespace that contains it. - -SEPARATE_MEMBER_PAGES = NO - -# The TAB_SIZE tag can be used to set the number of spaces in a tab. -# Doxygen uses this value to replace tabs by spaces in code fragments. - -TAB_SIZE = 4 - -# This tag can be used to specify a number of aliases that acts -# as commands in the documentation. An alias has the form "name=value". -# For example adding "sideeffect=\par Side Effects:\n" will allow you to -# put the command \sideeffect (or @sideeffect) in the documentation, which -# will result in a user-defined paragraph with heading "Side Effects:". -# You can put \n's in the value part of an alias to insert newlines. - -ALIASES = ffp_rtss_only="@note Only has an effect with the fixed-function pipeline or the @ref rtss" -ALIASES += shaderparam="@note When using shader programs, you have to explicitely forward this property in the @ref Program-Parameter-Specification" - -# This tag can be used to specify a number of word-keyword mappings (TCL only). -# A mapping has the form "name=value". For example adding -# "class=itcl::class" will allow you to use the command class in the -# itcl::class meaning. - -TCL_SUBST = - -# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C -# sources only. Doxygen will then generate output that is more tailored for C. -# For instance, some of the names that are used will be different. The list -# of all members will be omitted, etc. - -OPTIMIZE_OUTPUT_FOR_C = NO - -# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java -# sources only. Doxygen will then generate output that is more tailored for -# Java. For instance, namespaces will be presented as packages, qualified -# scopes will look different, etc. - -OPTIMIZE_OUTPUT_JAVA = NO - -# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran -# sources only. Doxygen will then generate output that is more tailored for -# Fortran. - -OPTIMIZE_FOR_FORTRAN = NO - -# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL -# sources. Doxygen will then generate output that is tailored for -# VHDL. - -OPTIMIZE_OUTPUT_VHDL = NO - -# Doxygen selects the parser to use depending on the extension of the files it -# parses. With this tag you can assign which parser to use for a given -# extension. Doxygen has a built-in mapping, but you can override or extend it -# using this tag. The format is ext=language, where ext is a file extension, -# and language is one of the parsers supported by doxygen: IDL, Java, -# Javascript, CSharp, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, -# C++. For instance to make doxygen treat .inc files as Fortran files (default -# is PHP), and .f files as C (default is Fortran), use: inc=Fortran f=C. Note -# that for custom extensions you also need to set FILE_PATTERNS otherwise the -# files are not read by doxygen. - -EXTENSION_MAPPING = material=C++ compositor=C++ particle=C++ txt=Python glsl=C++ - -# If MARKDOWN_SUPPORT is enabled (the default) then doxygen pre-processes all -# comments according to the Markdown format, which allows for more readable -# documentation. See http://daringfireball.net/projects/markdown/ for details. -# The output of markdown processing is further processed by doxygen, so you -# can mix doxygen, HTML, and XML commands with Markdown formatting. -# Disable only in case of backward compatibilities issues. - -MARKDOWN_SUPPORT = YES - -# When enabled doxygen tries to link words that correspond to documented classes, -# or namespaces to their corresponding documentation. Such a link can be -# prevented in individual cases by by putting a % sign in front of the word or -# globally by setting AUTOLINK_SUPPORT to NO. - -AUTOLINK_SUPPORT = YES - -# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want -# to include (a tag file for) the STL sources as input, then you should -# set this tag to YES in order to let doxygen match functions declarations and -# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. -# func(std::string) {}). This also makes the inheritance and collaboration -# diagrams that involve STL classes more complete and accurate. - -BUILTIN_STL_SUPPORT = NO - -# If you use Microsoft's C++/CLI language, you should set this option to YES to -# enable parsing support. - -CPP_CLI_SUPPORT = NO - -# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. -# Doxygen will parse them like normal C++ but will assume all classes use public -# instead of private inheritance when no explicit protection keyword is present. - -SIP_SUPPORT = NO - -# For Microsoft's IDL there are propget and propput attributes to indicate -# getter and setter methods for a property. Setting this option to YES (the -# default) will make doxygen replace the get and set methods by a property in -# the documentation. This will only work if the methods are indeed getting or -# setting a simple type. If this is not the case, or you want to show the -# methods anyway, you should set this option to NO. - -IDL_PROPERTY_SUPPORT = YES - -# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC -# tag is set to YES, then doxygen will reuse the documentation of the first -# member in the group (if any) for the other members of the group. By default -# all members of a group must be documented explicitly. - -DISTRIBUTE_GROUP_DOC = NO - -# Set the SUBGROUPING tag to YES (the default) to allow class member groups of -# the same type (for instance a group of public functions) to be put as a -# subgroup of that type (e.g. under the Public Functions section). Set it to -# NO to prevent subgrouping. Alternatively, this can be done per class using -# the \nosubgrouping command. - -SUBGROUPING = YES - -# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and -# unions are shown inside the group in which they are included (e.g. using -# @ingroup) instead of on a separate page (for HTML and Man pages) or -# section (for LaTeX and RTF). - -INLINE_GROUPED_CLASSES = NO - -# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and -# unions with only public data fields will be shown inline in the documentation -# of the scope in which they are defined (i.e. file, namespace, or group -# documentation), provided this scope is documented. If set to NO (the default), -# structs, classes, and unions are shown on a separate page (for HTML and Man -# pages) or section (for LaTeX and RTF). - -INLINE_SIMPLE_STRUCTS = NO - -# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum -# is documented as struct, union, or enum with the name of the typedef. So -# typedef struct TypeS {} TypeT, will appear in the documentation as a struct -# with name TypeT. When disabled the typedef will appear as a member of a file, -# namespace, or class. And the struct will be named TypeS. This can typically -# be useful for C code in case the coding convention dictates that all compound -# types are typedef'ed and only the typedef is referenced, never the tag name. - -TYPEDEF_HIDES_STRUCT = NO - -# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This -# cache is used to resolve symbols given their name and scope. Since this can be -# an expensive process and often the same symbol appears multiple times in the -# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small -# doxygen will become slower. If the cache is too large, memory is wasted. The -# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range -# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 -# symbols. At the end of a run doxygen will report the cache usage and suggest -# the optimal cache size from a speed point of view. -# Minimum value: 0, maximum value: 9, default value: 0. - -LOOKUP_CACHE_SIZE = 1 - -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- - -# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in -# documentation are documented, even if no documentation was available. -# Private class members and static file members will be hidden unless -# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES - -EXTRACT_ALL = YES - -# If the EXTRACT_PRIVATE tag is set to YES all private members of a class -# will be included in the documentation. - -EXTRACT_PRIVATE = NO - -# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal -# scope will be included in the documentation. - -EXTRACT_PACKAGE = NO - -# If the EXTRACT_STATIC tag is set to YES all static members of a file -# will be included in the documentation. - -EXTRACT_STATIC = YES - -# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) -# defined locally in source files will be included in the documentation. -# If set to NO only classes defined in header files are included. - -EXTRACT_LOCAL_CLASSES = YES - -# This flag is only useful for Objective-C code. When set to YES local -# methods, which are defined in the implementation section but not in -# the interface are included in the documentation. -# If set to NO (the default) only methods in the interface are included. - -EXTRACT_LOCAL_METHODS = NO - -# If this flag is set to YES, the members of anonymous namespaces will be -# extracted and appear in the documentation as a namespace called -# 'anonymous_namespace{file}', where file will be replaced with the base -# name of the file that contains the anonymous namespace. By default -# anonymous namespaces are hidden. - -EXTRACT_ANON_NSPACES = NO - -# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all -# undocumented members of documented classes, files or namespaces. -# If set to NO (the default) these members will be included in the -# various overviews, but no documentation section is generated. -# This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_MEMBERS = NO - -# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all -# undocumented classes that are normally visible in the class hierarchy. -# If set to NO (the default) these classes will be included in the various -# overviews. This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_CLASSES = NO - -# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all -# friend (class|struct|union) declarations. -# If set to NO (the default) these declarations will be included in the -# documentation. - -HIDE_FRIEND_COMPOUNDS = YES - -# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any -# documentation blocks found inside the body of a function. -# If set to NO (the default) these blocks will be appended to the -# function's detailed documentation block. - -HIDE_IN_BODY_DOCS = NO - -# The INTERNAL_DOCS tag determines if documentation -# that is typed after a \internal command is included. If the tag is set -# to NO (the default) then the documentation will be excluded. -# Set it to YES to include the internal documentation. - -INTERNAL_DOCS = NO - -# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate -# file names in lower-case letters. If set to YES upper-case letters are also -# allowed. This is useful if you have classes or files whose names only differ -# in case and if your file system supports case sensitive file names. Windows -# and Mac users are advised to set this option to NO. - -CASE_SENSE_NAMES = NO - -# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen -# will show members with their full class and namespace scopes in the -# documentation. If set to YES the scope will be hidden. - -HIDE_SCOPE_NAMES = NO - -# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen -# will put a list of the files that are included by a file in the documentation -# of that file. - -SHOW_INCLUDE_FILES = YES - -# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen -# will list include files with double quotes in the documentation -# rather than with sharp brackets. - -FORCE_LOCAL_INCLUDES = NO - -# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] -# is inserted in the documentation for inline members. - -INLINE_INFO = YES - -# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen -# will sort the (detailed) documentation of file and class members -# alphabetically by member name. If set to NO the members will appear in -# declaration order. - -SORT_MEMBER_DOCS = NO - -# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the -# brief documentation of file, namespace and class members alphabetically -# by member name. If set to NO (the default) the members will appear in -# declaration order. - -SORT_BRIEF_DOCS = YES - -# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen -# will sort the (brief and detailed) documentation of class members so that -# constructors and destructors are listed first. If set to NO (the default) -# the constructors will appear in the respective orders defined by -# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. -# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO -# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. - -SORT_MEMBERS_CTORS_1ST = YES - -# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the -# hierarchy of group names into alphabetical order. If set to NO (the default) -# the group names will appear in their defined order. - -SORT_GROUP_NAMES = YES - -# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be -# sorted by fully-qualified names, including namespaces. If set to -# NO (the default), the class list will be sorted only by class name, -# not including the namespace part. -# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. -# Note: This option applies only to the class list, not to the -# alphabetical list. - -SORT_BY_SCOPE_NAME = YES - -# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to -# do proper type resolution of all parameters of a function it will reject a -# match between the prototype and the implementation of a member function even -# if there is only one candidate or it is obvious which candidate to choose -# by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen -# will still accept a match between prototype and implementation in such cases. - -STRICT_PROTO_MATCHING = NO - -# The GENERATE_TODOLIST tag can be used to enable (YES) or -# disable (NO) the todo list. This list is created by putting \todo -# commands in the documentation. - -GENERATE_TODOLIST = NO - -# The GENERATE_TESTLIST tag can be used to enable (YES) or -# disable (NO) the test list. This list is created by putting \test -# commands in the documentation. - -GENERATE_TESTLIST = YES - -# The GENERATE_BUGLIST tag can be used to enable (YES) or -# disable (NO) the bug list. This list is created by putting \bug -# commands in the documentation. - -GENERATE_BUGLIST = YES - -# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or -# disable (NO) the deprecated list. This list is created by putting -# \deprecated commands in the documentation. - -GENERATE_DEPRECATEDLIST= YES - -# The ENABLED_SECTIONS tag can be used to enable conditional -# documentation sections, marked by \if section-label ... \endif -# and \cond section-label ... \endcond blocks. - -ENABLED_SECTIONS = - -# The MAX_INITIALIZER_LINES tag determines the maximum number of lines -# the initial value of a variable or macro consists of for it to appear in -# the documentation. If the initializer consists of more lines than specified -# here it will be hidden. Use a value of 0 to hide initializers completely. -# The appearance of the initializer of individual variables and macros in the -# documentation can be controlled using \showinitializer or \hideinitializer -# command in the documentation regardless of this setting. - -MAX_INITIALIZER_LINES = 30 - -# Set the SHOW_USED_FILES tag to NO to disable the list of files generated -# at the bottom of the documentation of classes and structs. If set to YES the -# list will mention the files that were used to generate the documentation. - -SHOW_USED_FILES = YES - -# Set the SHOW_FILES tag to NO to disable the generation of the Files page. -# This will remove the Files entry from the Quick Index and from the -# Folder Tree View (if specified). The default is YES. - -SHOW_FILES = YES - -# Set the SHOW_NAMESPACES tag to NO to disable the generation of the -# Namespaces page. -# This will remove the Namespaces entry from the Quick Index -# and from the Folder Tree View (if specified). The default is YES. - -SHOW_NAMESPACES = YES - -# The FILE_VERSION_FILTER tag can be used to specify a program or script that -# doxygen should invoke to get the current version for each file (typically from -# the version control system). Doxygen will invoke the program by executing (via -# popen()) the command , where is the value of -# the FILE_VERSION_FILTER tag, and is the name of an input file -# provided by doxygen. Whatever the program writes to standard output -# is used as the file version. See the manual for examples. - -FILE_VERSION_FILTER = - -# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed -# by doxygen. The layout file controls the global structure of the generated -# output files in an output format independent way. To create the layout file -# that represents doxygen's defaults, run doxygen with the -l option. -# You can optionally specify a file name after the option, if omitted -# DoxygenLayout.xml will be used as the name of the layout file. - -LAYOUT_FILE = - -# The CITE_BIB_FILES tag can be used to specify one or more bib files -# containing the references data. This must be a list of .bib files. The -# .bib extension is automatically appended if omitted. Using this command -# requires the bibtex tool to be installed. See also -# http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style -# of the bibliography can be controlled using LATEX_BIB_STYLE. To use this -# feature you need bibtex and perl available in the search path. Do not use -# file names with spaces, bibtex cannot handle them. - -CITE_BIB_FILES = "${PROJECT_SOURCE_DIR}/Docs/src/bibliography.bib" - -# The LATEX_BIB_STYLE tag can be used to specify the style to use for the -# bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See -# http://en.wikipedia.org/wiki/BibTeX for more info. - -LATEX_BIB_STYLE = plain - -#--------------------------------------------------------------------------- -# configuration options related to warning and progress messages -#--------------------------------------------------------------------------- - -# The QUIET tag can be used to turn on/off the messages that are generated -# by doxygen. Possible values are YES and NO. If left blank NO is used. - -QUIET = NO - -# The WARNINGS tag can be used to turn on/off the warning messages that are -# generated by doxygen. Possible values are YES and NO. If left blank -# NO is used. - -WARNINGS = YES - -# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings -# for undocumented members. If EXTRACT_ALL is set to YES then this flag will -# automatically be disabled. - -WARN_IF_UNDOCUMENTED = YES - -# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for -# potential errors in the documentation, such as not documenting some -# parameters in a documented function, or documenting parameters that -# don't exist or using markup commands wrongly. - -WARN_IF_DOC_ERROR = YES - -# The WARN_NO_PARAMDOC option can be enabled to get warnings for -# functions that are documented, but have no documentation for their parameters -# or return value. If set to NO (the default) doxygen will only warn about -# wrong or incomplete parameter documentation, but not about the absence of -# documentation. - -WARN_NO_PARAMDOC = NO - -# The WARN_FORMAT tag determines the format of the warning messages that -# doxygen can produce. The string should contain the $file, $line, and $text -# tags, which will be replaced by the file and line number from which the -# warning originated and the warning text. Optionally the format may contain -# $version, which will be replaced by the version of the file (if it could -# be obtained via FILE_VERSION_FILTER) - -WARN_FORMAT = "$file:$line: $text" - -# The WARN_LOGFILE tag can be used to specify a file to which warning -# and error messages should be written. If left blank the output is written -# to stderr. - -WARN_LOGFILE = "${PROJECT_BINARY_DIR}/doxygen_warnings.log" - -#--------------------------------------------------------------------------- -# configuration options related to the input files -#--------------------------------------------------------------------------- - -# The INPUT tag can be used to specify the files and/or directories that contain -# documented source files. You may enter file names like "myfile.cpp" or -# directories like "/usr/src/myproject". Separate the files or directories -# with spaces. - -INPUT = ${CMAKE_DOXYGEN_INPUT_LIST} - -# This tag can be used to specify the character encoding of the source files -# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is -# also the default input encoding. Doxygen uses libiconv (or the iconv built -# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for -# the list of possible encodings. - -INPUT_ENCODING = UTF-8 - -# If the value of the INPUT tag contains directories, you can use the -# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp -# and *.h) to filter out the source-files in the directories. If left -# blank the following patterns are tested: -# *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh -# *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py -# *.f90 *.f *.for *.vhd *.vhdl - -FILE_PATTERNS = Ogre*.h - -# The RECURSIVE tag can be used to turn specify whether or not subdirectories -# should be searched for input files as well. Possible values are YES and NO. -# If left blank NO is used. - -RECURSIVE = YES - -# The EXCLUDE tag can be used to specify files and/or directories that should be -# excluded from the INPUT source files. This way you can easily exclude a -# subdirectory from a directory tree whose root is specified with the INPUT tag. -# Note that relative paths are relative to the directory from which doxygen is -# run. - -EXCLUDE = - -# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or -# directories that are symbolic links (a Unix file system feature) are excluded -# from the input. - -EXCLUDE_SYMLINKS = NO - -# If the value of the INPUT tag contains directories, you can use the -# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude -# certain files from those directories. Note that the wildcards are matched -# against the file with absolute path, so to exclude all test directories -# for example use the pattern */test/* - -EXCLUDE_PATTERNS = *UTF* \ - */GLSupport/include/EGL/* \ - */GLSupport/include/GLX/* \ - */GLSupport/include/OSX/* \ - */GLSupport/include/win32/* \ - */include/Threading/* \ - */OgreMemoryAllocatorConfig.h \ - *EAGL* \ - */RenderSystems/GLES/* - -# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names -# (namespaces, classes, functions, etc.) that should be excluded from the -# output. The symbol name can be a fully qualified name, a word, or if the -# wildcard * is used, a substring. Examples: ANamespace, AClass, -# AClass::ANamespace, ANamespace::*Test - -EXCLUDE_SYMBOLS = Ogre::AllocatedObject Ogre::ParamCommand - -# The EXAMPLE_PATH tag can be used to specify one or more files or -# directories that contain example code fragments that are included (see -# the \include command). - -EXAMPLE_PATH = "${PROJECT_SOURCE_DIR}" - -# If the value of the EXAMPLE_PATH tag contains directories, you can use the -# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp -# and *.h) to filter out the source-files in the directories. If left -# blank all files are included. - -EXAMPLE_PATTERNS = - -# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be -# searched for input files to be used with the \include or \dontinclude -# commands irrespective of the value of the RECURSIVE tag. -# Possible values are YES and NO. If left blank NO is used. - -EXAMPLE_RECURSIVE = NO - -# The IMAGE_PATH tag can be used to specify one or more files or -# directories that contain image that are included in the documentation (see -# the \image command). - -IMAGE_PATH = "${PROJECT_SOURCE_DIR}/Docs/src/tutorials/" \ - "${PROJECT_SOURCE_DIR}/Docs/src/images/" - -# The INPUT_FILTER tag can be used to specify a program that doxygen should -# invoke to filter for each input file. Doxygen will invoke the filter program -# by executing (via popen()) the command , where -# is the value of the INPUT_FILTER tag, and is the name of an -# input file. Doxygen will then use the output that the filter program writes -# to standard output. -# If FILTER_PATTERNS is specified, this tag will be -# ignored. - -INPUT_FILTER = - -# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern -# basis. -# Doxygen will compare the file name with each pattern and apply the -# filter if there is a match. -# The filters are a list of the form: -# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further -# info on how filters are used. If FILTER_PATTERNS is empty or if -# non of the patterns match the file name, INPUT_FILTER is applied. - -FILTER_PATTERNS = - -# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using -# INPUT_FILTER) will be used to filter the input files when producing source -# files to browse (i.e. when SOURCE_BROWSER is set to YES). - -FILTER_SOURCE_FILES = NO - -# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file -# pattern. A pattern will override the setting for FILTER_PATTERN (if any) -# and it is also possible to disable source filtering for a specific pattern -# using *.ext= (so without naming a filter). This option only has effect when -# FILTER_SOURCE_FILES is enabled. - -FILTER_SOURCE_PATTERNS = - -# If the USE_MD_FILE_AS_MAINPAGE tag refers to the name of a markdown file that -# is part of the input, its contents will be placed on the main page (index.html). -# This can be useful if you have a project on for instance GitHub and want reuse -# the introduction page also for the doxygen output. - -USE_MDFILE_AS_MAINPAGE = - -#--------------------------------------------------------------------------- -# configuration options related to source browsing -#--------------------------------------------------------------------------- - -# If the SOURCE_BROWSER tag is set to YES then a list of source files will -# be generated. Documented entities will be cross-referenced with these sources. -# Note: To get rid of all source code in the generated output, make sure also -# VERBATIM_HEADERS is set to NO. - -SOURCE_BROWSER = NO - -# Setting the INLINE_SOURCES tag to YES will include the body -# of functions and classes directly in the documentation. - -INLINE_SOURCES = NO - -# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct -# doxygen to hide any special comment blocks from generated source code -# fragments. Normal C, C++ and Fortran comments will always remain visible. - -STRIP_CODE_COMMENTS = YES - -# If the REFERENCED_BY_RELATION tag is set to YES -# then for each documented function all documented -# functions referencing it will be listed. - -REFERENCED_BY_RELATION = YES - -# If the REFERENCES_RELATION tag is set to YES -# then for each documented function all documented entities -# called/used by that function will be listed. - -REFERENCES_RELATION = YES - -# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) -# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from -# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will -# link to the source code. -# Otherwise they will link to the documentation. - -REFERENCES_LINK_SOURCE = YES - -# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the -# source code will show a tooltip with additional information such as prototype, -# brief description and links to the definition and documentation. Since this -# will make the HTML file larger and loading of large files a bit slower, you -# can opt to disable this feature. -# The default value is: YES. -# This tag requires that the tag SOURCE_BROWSER is set to YES. - -SOURCE_TOOLTIPS = YES -# If the USE_HTAGS tag is set to YES then the references to source code -# will point to the HTML generated by the htags(1) tool instead of doxygen -# built-in source browser. The htags tool is part of GNU's global source -# tagging system (see http://www.gnu.org/software/global/global.html). You -# will need version 4.8.6 or higher. - -USE_HTAGS = NO - -# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen -# will generate a verbatim copy of the header file for each class for -# which an include is specified. Set to NO to disable this. - -VERBATIM_HEADERS = NO - -#--------------------------------------------------------------------------- -# configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- - -# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index -# of all compounds will be generated. Enable this if the project -# contains a lot of classes, structs, unions or interfaces. - -ALPHABETICAL_INDEX = YES - -# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then -# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns -# in which this list will be split (can be a number in the range [1..20]) - -COLS_IN_ALPHA_INDEX = 3 - -# In case all classes in a project start with a common prefix, all -# classes will be put under the same header in the alphabetical index. -# The IGNORE_PREFIX tag can be used to specify one or more prefixes that -# should be ignored while generating the index headers. - -IGNORE_PREFIX = - -#--------------------------------------------------------------------------- -# configuration options related to the HTML output -#--------------------------------------------------------------------------- - -# If the GENERATE_HTML tag is set to YES (the default) Doxygen will -# generate HTML output. - -GENERATE_HTML = YES - -GENERATE_LATEX = NO - -# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `html' will be used as the default path. - -HTML_OUTPUT = html - -# The HTML_FILE_EXTENSION tag can be used to specify the file extension for -# each generated HTML page (for example: .htm,.php,.asp). If it is left blank -# doxygen will generate files with .html extension. - -HTML_FILE_EXTENSION = .html - -# The HTML_HEADER tag can be used to specify a personal HTML header for -# each generated HTML page. If it is left blank doxygen will generate a -# standard header. Note that when using a custom header you are responsible -# for the proper inclusion of any scripts and style sheets that doxygen -# needs, which is dependent on the configuration options used. -# It is advised to generate a default header using "doxygen -w html -# header.html footer.html stylesheet.css YourConfigFile" and then modify -# that header. Note that the header is subject to change so you typically -# have to redo this when upgrading to a newer version of doxygen or when -# changing the value of configuration settings such as GENERATE_TREEVIEW! - -HTML_HEADER = - -# The HTML_FOOTER tag can be used to specify a personal HTML footer for -# each generated HTML page. If it is left blank doxygen will generate a -# standard footer. - -HTML_FOOTER = - -# The HTML_STYLESHEET tag can be used to specify a user-defined cascading -# style sheet that is used by each HTML page. It can be used to -# fine-tune the look of the HTML output. If left blank doxygen will -# generate a default style sheet. Note that it is recommended to use -# HTML_EXTRA_STYLESHEET instead of this one, as it is more robust and this -# tag will in the future become obsolete. - -HTML_STYLESHEET = - -# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional -# user-defined cascading style sheet that is included after the standard -# style sheets created by doxygen. Using this option one can overrule -# certain style aspects. This is preferred over using HTML_STYLESHEET -# since it does not replace the standard style sheet and is therefor more -# robust against future updates. Doxygen will copy the style sheet file to -# the output directory. - -HTML_EXTRA_STYLESHEET = "${PROJECT_SOURCE_DIR}/Docs/doxygen-awesome.css" "${PROJECT_SOURCE_DIR}/Docs/ogre_style.css" - -# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or -# other source files which should be copied to the HTML output directory. Note -# that these files will be copied to the base HTML output directory. Use the -# $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these -# files. In the HTML_STYLESHEET file, use the file name only. Also note that -# the files will be copied as-is; there are no commands or markers available. - -HTML_EXTRA_FILES = - -# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. -# Doxygen will adjust the colors in the style sheet and background images -# according to this color. Hue is specified as an angle on a colorwheel, -# see http://en.wikipedia.org/wiki/Hue for more information. -# For instance the value 0 represents red, 60 is yellow, 120 is green, -# 180 is cyan, 240 is blue, 300 purple, and 360 is red again. -# The allowed range is 0 to 359. - -HTML_COLORSTYLE_HUE = 130 - -# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of -# the colors in the HTML output. For a value of 0 the output will use -# grayscales only. A value of 255 will produce the most vivid colors. - -HTML_COLORSTYLE_SAT = 40 - -# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to -# the luminance component of the colors in the HTML output. Values below -# 100 gradually make the output lighter, whereas values above 100 make -# the output darker. The value divided by 100 is the actual gamma applied, -# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, -# and 100 does not change the gamma. - -HTML_COLORSTYLE_GAMMA = 80 - -# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML -# page will contain the date and time when the page was generated. Setting -# this to NO can help when comparing the output of multiple runs. - -HTML_TIMESTAMP = NO - -# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML -# documentation will contain sections that can be hidden and shown after the -# page has loaded. - -HTML_DYNAMIC_SECTIONS = YES - -# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of -# entries shown in the various tree structured indices initially; the user -# can expand and collapse entries dynamically later on. Doxygen will expand -# the tree to such a level that at most the specified number of entries are -# visible (unless a fully collapsed tree already exceeds this amount). -# So setting the number of entries 1 will produce a full collapsed tree by -# default. 0 is a special value representing an infinite number of entries -# and will result in a full expanded tree by default. - -HTML_INDEX_NUM_ENTRIES = 100 - -# The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) -# at top of each HTML page. The value NO (the default) enables the index and -# the value YES disables it. Since the tabs have the same information as the -# navigation tree you can set this option to NO if you already set -# GENERATE_TREEVIEW to YES. - -DISABLE_INDEX = NO - -# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index -# structure should be generated to display hierarchical information. -# If the tag value is set to YES, a side panel will be generated -# containing a tree-like index structure (just like the one that -# is generated for HTML Help). For this to work a browser that supports -# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). -# Windows users are probably better off using the HTML help feature. -# Since the tree basically has the same information as the tab index you -# could consider to set DISABLE_INDEX to NO when enabling this option. - -GENERATE_TREEVIEW = YES - -# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values -# (range [0,1..20]) that doxygen will group on one line in the generated HTML -# documentation. Note that a value of 0 will completely suppress the enum -# values from appearing in the overview section. - -ENUM_VALUES_PER_LINE = 4 - -# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be -# used to set the initial width (in pixels) of the frame in which the tree -# is shown. - -TREEVIEW_WIDTH = 250 - -# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open -# links to external symbols imported via tag files in a separate window. - -EXT_LINKS_IN_WINDOW = NO - -# Use this tag to change the font size of Latex formulas included -# as images in the HTML documentation. The default is 10. Note that -# when you change the font size after a successful doxygen run you need -# to manually remove any form_*.png images from the HTML output directory -# to force them to be regenerated. - -FORMULA_FONTSIZE = 10 - -# Use the FORMULA_TRANPARENT tag to determine whether or not the images -# generated for formulas are transparent PNGs. Transparent PNGs are -# not supported properly for IE 6.0, but are supported on all modern browsers. -# Note that when changing this option you need to delete any form_*.png files -# in the HTML output before the changes have effect. - -FORMULA_TRANSPARENT = YES - -# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax -# (see http://www.mathjax.org) which uses client side Javascript for the -# rendering instead of using prerendered bitmaps. Use this if you do not -# have LaTeX installed or if you want to formulas look prettier in the HTML -# output. When enabled you may also need to install MathJax separately and -# configure the path to it using the MATHJAX_RELPATH option. - -USE_MATHJAX = YES - -# When MathJax is enabled you can set the default output format to be used for -# thA MathJax output. Supported types are HTML-CSS, NativeMML (i.e. MathML) and -# SVG. The default value is HTML-CSS, which is slower, but has the best -# compatibility. - -MATHJAX_FORMAT = HTML-CSS - -# When MathJax is enabled you need to specify the location relative to the -# HTML output directory using the MATHJAX_RELPATH option. The destination -# directory should contain the MathJax.js script. For instance, if the mathjax -# directory is located at the same level as the HTML output directory, then -# MATHJAX_RELPATH should be ../mathjax. The default value points to -# the MathJax Content Delivery Network so you can quickly see the result without -# installing MathJax. -# However, it is strongly recommended to install a local -# copy of MathJax from http://www.mathjax.org before deployment. - -MATHJAX_RELPATH = https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0 - -# The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension -# names that should be enabled during MathJax rendering. - -MATHJAX_EXTENSIONS = - -# When the SEARCHENGINE tag is enabled doxygen will generate a search box -# for the HTML output. The underlying search engine uses javascript -# and DHTML and should work on any modern browser. Note that when using -# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets -# (GENERATE_DOCSET) there is already a search function so this one should -# typically be disabled. For large projects the javascript based search engine -# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. - -SEARCHENGINE = YES - -# When the SERVER_BASED_SEARCH tag is enabled the search engine will be -# implemented using a web server instead of a web client using Javascript. -# There are two flavours of web server based search depending on the -# EXTERNAL_SEARCH setting. When disabled, doxygen will generate a PHP script for -# searching and an index file used by the script. When EXTERNAL_SEARCH is -# enabled the indexing and searching needs to be provided by external tools. -# See the manual for details. - -SERVER_BASED_SEARCH = NO - -# When EXTERNAL_SEARCH is enabled doxygen will no longer generate the PHP -# script for searching. Instead the search results are written to an XML file -# which needs to be processed by an external indexer. Doxygen will invoke an -# external search engine pointed to by the SEARCHENGINE_URL option to obtain -# the search results. Doxygen ships with an example indexer (doxyindexer) and -# search engine (doxysearch.cgi) which are based on the open source search engine -# library Xapian. See the manual for configuration details. - -EXTERNAL_SEARCH = NO - -# The SEARCHENGINE_URL should point to a search engine hosted by a web server -# which will returned the search results when EXTERNAL_SEARCH is enabled. -# Doxygen ships with an example search engine (doxysearch) which is based on -# the open source search engine library Xapian. See the manual for configuration -# details. - -SEARCHENGINE_URL = - -# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed -# search data is written to a file for indexing by an external tool. With the -# SEARCHDATA_FILE tag the name of this file can be specified. - -SEARCHDATA_FILE = searchdata.xml - -# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through other -# doxygen projects that are not otherwise connected via tags files, but are -# all added to the same search index. Each project needs to have a tag file set -# via GENERATE_TAGFILE. The search mapping then maps the name of the tag file -# to a relative location where the documentation can be found, -# similar to the -# TAGFILES option but without actually processing the tag file. -# The format is: EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ... - -EXTRA_SEARCH_MAPPINGS = - -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- - -# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will -# evaluate all C-preprocessor directives found in the sources and include -# files. - -ENABLE_PREPROCESSING = YES - -# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro -# names in the source code. If set to NO (the default) only conditional -# compilation will be performed. Macro expansion can be done in a controlled -# way by setting EXPAND_ONLY_PREDEF to YES. - -MACRO_EXPANSION = YES - -# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES -# then the macro expansion is limited to the macros specified with the -# PREDEFINED and EXPAND_AS_DEFINED tags. - -EXPAND_ONLY_PREDEF = YES - -# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files -# pointed to by INCLUDE_PATH will be searched when a #include is found. - -SEARCH_INCLUDES = YES - -# The INCLUDE_PATH tag can be used to specify one or more directories that -# contain include files that are not input files but should be processed by -# the preprocessor. - -INCLUDE_PATH = - -# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard -# patterns (like *.h and *.hpp) to filter out the header-files in the -# directories. If left blank, the patterns specified with FILE_PATTERNS will -# be used. - -INCLUDE_FILE_PATTERNS = - -# The PREDEFINED tag can be used to specify one or more macro names that -# are defined before the preprocessor is started (similar to the -D option of -# gcc). The argument of the tag is a list of macros of the form: name -# or name=definition (no spaces). If the definition and the = are -# omitted =1 is assumed. To prevent a macro definition from being -# undefined via #undef or recursively expanded use the := operator -# instead of the = operator. - -PREDEFINED = OGRE_MEMORY_ALLOCATOR=1 \ - RTSHADER_SYSTEM_BUILD_CORE_SHADERS \ - RTSHADER_SYSTEM_BUILD_EXT_SHADERS \ - OGRE_PLATFORM=10 \ - OGRE_DEPRECATED= \ - OGRE_NODISCARD= \ - OGRE_NORETURN= \ - DECL_MALLOC= \ - OGRE_FORCE_INLINE=inline \ - OGRE_NODELESS_POSITIONING= \ - MANAGED_RESOURCE= \ - OGRE_AUTO_MUTEX= \ - OGRE_FORMAT_PRINTF=;// \ - OGRE_RESOURCE_GROUP_INIT==RGN_DEFAULT \ - protected=private - -# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then -# this tag can be used to specify a list of macro names that should be expanded. -# The macro definition that is found in the sources will be used. -# Use the PREDEFINED tag if you want to use a different macro definition that -# overrules the definition found in the source code. - -EXPAND_AS_DEFINED = - -# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then -# doxygen's preprocessor will remove all references to function-like macros -# that are alone on a line, have an all uppercase name, and do not end with a -# semicolon, because these will confuse the parser if not removed. - -SKIP_FUNCTION_MACROS = YES - -#--------------------------------------------------------------------------- -# Configuration::additions related to external references -#--------------------------------------------------------------------------- - -# The TAGFILES option can be used to specify one or more tagfiles. For each -# tag file the location of the external documentation should be added. The -# format of a tag file without this location is as follows: -# -# TAGFILES = file1 file2 ... -# Adding location for the tag files is done as follows: -# -# TAGFILES = file1=loc1 "file2 = loc2" ... -# where "loc1" and "loc2" can be relative or absolute paths -# or URLs. Note that each tag file must have a unique name (where the name does -# NOT include the path). If a tag file is not located in the directory in which -# doxygen is run, you must also specify the path to the tagfile here. - -TAGFILES = - -# When a file name is specified after GENERATE_TAGFILE, doxygen will create -# a tag file that is based on the input files it reads. - -GENERATE_TAGFILE = "${PROJECT_BINARY_DIR}/api/Ogre.tag" - -# If the ALLEXTERNALS tag is set to YES all external classes will be listed -# in the class index. If set to NO only the inherited external classes -# will be listed. - -ALLEXTERNALS = NO - -# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed -# in the modules index. If set to NO, only the current project's groups will -# be listed. - -EXTERNAL_GROUPS = YES - - -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- - -# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will -# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base -# or super classes. Setting the tag to NO turns the diagrams off. Note that -# this option also works with HAVE_DOT disabled, but it is recommended to -# install and use dot, since it yields more powerful graphs. - -CLASS_DIAGRAMS = YES - -# You can define message sequence charts within doxygen comments using the \msc -# command. Doxygen will then run the mscgen tool (see -# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the -# documentation. The MSCGEN_PATH tag allows you to specify the directory where -# the mscgen tool resides. If left empty the tool is assumed to be found in the -# default search path. - -MSCGEN_PATH = - -# If set to YES, the inheritance and collaboration graphs will hide -# inheritance and usage relations if the target is undocumented -# or is not a class. - -HIDE_UNDOC_RELATIONS = YES - -# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is -# available from the path. This tool is part of Graphviz, a graph visualization -# toolkit from AT&T and Lucent Bell Labs. The other options in this section -# have no effect if this option is set to NO (the default) - -HAVE_DOT = YES - -# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is -# allowed to run in parallel. When set to 0 (the default) doxygen will -# base this on the number of processors available in the system. You can set it -# explicitly to a value larger than 0 to get control over the balance -# between CPU load and processing speed. - -DOT_NUM_THREADS = 0 - -# By default doxygen will use the Helvetica font for all dot files that -# doxygen generates. When you want a differently looking font you can specify -# the font name using DOT_FONTNAME. You need to make sure dot is able to find -# the font, which can be done by putting it in a standard location or by setting -# the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the -# directory containing the font. - -DOT_FONTNAME = Helvetica - -# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. -# The default size is 10pt. - -DOT_FONTSIZE = 10 - -# By default doxygen will tell dot to use the Helvetica font. -# If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to -# set the path where dot can find it. - -DOT_FONTPATH = - -# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for each documented class showing the direct and -# indirect inheritance relations. Setting this tag to YES will force the -# CLASS_DIAGRAMS tag to NO. - -CLASS_GRAPH = YES - -# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for each documented class showing the direct and -# indirect implementation dependencies (inheritance, containment, and -# class references variables) of the class with other documented classes. - -COLLABORATION_GRAPH = NO - -# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for groups, showing the direct groups dependencies - -GROUP_GRAPHS = NO - -# If the UML_LOOK tag is set to YES doxygen will generate inheritance and -# collaboration diagrams in a style similar to the OMG's Unified Modeling -# Language. - -UML_LOOK = NO - -# If the UML_LOOK tag is enabled, the fields and methods are shown inside -# the class node. If there are many fields or methods and many nodes the -# graph may become too big to be useful. The UML_LIMIT_NUM_FIELDS -# threshold limits the number of items for each type to make the size more -# managable. Set this to 0 for no limit. Note that the threshold may be -# exceeded by 50% before the limit is enforced. - -UML_LIMIT_NUM_FIELDS = 10 - -# If set to YES, the inheritance and collaboration graphs will show the -# relations between templates and their instances. - -TEMPLATE_RELATIONS = NO - -# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT -# tags are set to YES then doxygen will generate a graph for each documented -# file showing the direct and indirect include dependencies of the file with -# other documented files. - -INCLUDE_GRAPH = NO - -# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and -# HAVE_DOT tags are set to YES then doxygen will generate a graph for each -# documented header file showing the documented files that directly or -# indirectly include this file. - -INCLUDED_BY_GRAPH = NO - -# If the CALL_GRAPH and HAVE_DOT options are set to YES then -# doxygen will generate a call dependency graph for every global function -# or class method. Note that enabling this option will significantly increase -# the time of a run. So in most cases it will be better to enable call graphs -# for selected functions only using the \callgraph command. - -CALL_GRAPH = NO - -# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then -# doxygen will generate a caller dependency graph for every global function -# or class method. Note that enabling this option will significantly increase -# the time of a run. So in most cases it will be better to enable caller -# graphs for selected functions only using the \callergraph command. - -CALLER_GRAPH = NO - -# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen -# will generate a graphical hierarchy of all classes instead of a textual one. - -GRAPHICAL_HIERARCHY = YES - -# If the DIRECTORY_GRAPH and HAVE_DOT tags are set to YES -# then doxygen will show the dependencies a directory has on other directories -# in a graphical way. The dependency relations are determined by the #include -# relations between the files in the directories. - -DIRECTORY_GRAPH = NO - -# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images -# generated by dot. Possible values are svg, png, jpg, or gif. -# If left blank png will be used. If you choose svg you need to set -# HTML_FILE_EXTENSION to xhtml in order to make the SVG files -# visible in IE 9+ (other browsers do not have this requirement). - -DOT_IMAGE_FORMAT = svg - -# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to -# enable generation of interactive SVG images that allow zooming and panning. -# Note that this requires a modern browser other than Internet Explorer. -# Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you -# need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files -# visible. Older versions of IE do not have SVG support. - -INTERACTIVE_SVG = NO - -# The tag DOT_PATH can be used to specify the path where the dot tool can be -# found. If left blank, it is assumed the dot tool can be found in the path. - -DOT_PATH = ${DOXYGEN_DOT_PATH} - -# The DOTFILE_DIRS tag can be used to specify one or more directories that -# contain dot files that are included in the documentation (see the -# \dotfile command). - -DOTFILE_DIRS = - -# The MSCFILE_DIRS tag can be used to specify one or more directories that -# contain msc files that are included in the documentation (see the -# \mscfile command). - -MSCFILE_DIRS = - -# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of -# nodes that will be shown in the graph. If the number of nodes in a graph -# becomes larger than this value, doxygen will truncate the graph, which is -# visualized by representing a node as a red box. Note that doxygen if the -# number of direct children of the root node in a graph is already larger than -# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note -# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. - -DOT_GRAPH_MAX_NODES = 50 - -# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the -# graphs generated by dot. A depth value of 3 means that only nodes reachable -# from the root by following a path via at most 3 edges will be shown. Nodes -# that lay further from the root node will be omitted. Note that setting this -# option to 1 or 2 may greatly reduce the computation time needed for large -# code bases. Also note that the size of a graph can be further restricted by -# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. - -MAX_DOT_GRAPH_DEPTH = 4 - -# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent -# background. This is disabled by default, because dot on Windows does not -# seem to support this out of the box. Warning: Depending on the platform used, -# enabling this option may lead to badly anti-aliased labels on the edges of -# a graph (i.e. they become hard to read). - -DOT_TRANSPARENT = YES - -# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output -# files in one run (i.e. multiple -o and -T options on the command line). This -# makes dot run faster, but since only newer versions of dot (>1.8.10) -# support this, this feature is disabled by default. - -DOT_MULTI_TARGETS = YES - -# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will -# generate a legend page explaining the meaning of the various boxes and -# arrows in the dot generated graphs. - -GENERATE_LEGEND = YES - -# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will -# remove the intermediate dot files that are used to generate -# the various graphs. - -DOT_CLEANUP = YES diff --git a/CMake/Templates/imconfig.h b/CMake/Templates/imconfig.h deleted file mode 100644 index 7f6a28ce213..00000000000 --- a/CMake/Templates/imconfig.h +++ /dev/null @@ -1,5 +0,0 @@ -#pragma once -#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS -#include -#define IMGUI_API _OgreOverlayExport -#cmakedefine IMGUI_ENABLE_FREETYPE \ No newline at end of file diff --git a/CMake/Templates/plugins.cfg.in b/CMake/Templates/plugins.cfg.in deleted file mode 100644 index fce8e27b58a..00000000000 --- a/CMake/Templates/plugins.cfg.in +++ /dev/null @@ -1,27 +0,0 @@ -# Defines plugins to load - -# Define plugin folder -PluginFolder=@OGRE_PLUGIN_DIR_REL@ - -# Define plugins -@OGRE_COMMENT_RENDERSYSTEM_D3D9@ Plugin=RenderSystem_Direct3D9 -@OGRE_COMMENT_RENDERSYSTEM_D3D11@ Plugin=RenderSystem_Direct3D11 -@OGRE_COMMENT_RENDERSYSTEM_GL@ Plugin=RenderSystem_GL -@OGRE_COMMENT_RENDERSYSTEM_GL3PLUS@ Plugin=RenderSystem_GL3Plus -@OGRE_COMMENT_RENDERSYSTEM_GLES2@ Plugin=RenderSystem_GLES2 -@OGRE_COMMENT_RENDERSYSTEM_METAL@ Plugin=RenderSystem_Metal -@OGRE_COMMENT_RENDERSYSTEM_TINY@ Plugin=RenderSystem_Tiny -@OGRE_COMMENT_RENDERSYSTEM_VULKAN@ Plugin=RenderSystem_Vulkan -@OGRE_COMMENT_PLUGIN_PARTICLEFX@ Plugin=Plugin_ParticleFX -@OGRE_COMMENT_PLUGIN_BSP@ Plugin=Plugin_BSPSceneManager -@OGRE_COMMENT_PLUGIN_CG@ Plugin=Plugin_CgProgramManager -@OGRE_COMMENT_PLUGIN_GLSLANG@ Plugin=Plugin_GLSLangProgramManager -@OGRE_COMMENT_PLUGIN_EXRCODEC@ Plugin=Codec_EXR -@OGRE_COMMENT_PLUGIN_STBI@ Plugin=Codec_STBI -@OGRE_COMMENT_PLUGIN_RSIMAGE@ Plugin=Codec_RsImage -@OGRE_COMMENT_PLUGIN_FREEIMAGE@ Plugin=Codec_FreeImage -@OGRE_COMMENT_PLUGIN_PCZ@ Plugin=Plugin_PCZSceneManager -@OGRE_COMMENT_PLUGIN_PCZ@ Plugin=Plugin_OctreeZone -@OGRE_COMMENT_PLUGIN_OCTREE@ Plugin=Plugin_OctreeSceneManager -@OGRE_COMMENT_PLUGIN_DOT_SCENE@ Plugin=Plugin_DotScene -@OGRE_COMMENT_PLUGIN_ASSIMP@ Plugin=Codec_Assimp diff --git a/CMake/Templates/project.gradle b/CMake/Templates/project.gradle deleted file mode 100644 index c49416dd5c2..00000000000 --- a/CMake/Templates/project.gradle +++ /dev/null @@ -1,17 +0,0 @@ -// Top-level build file where you can add configuration options common to all sub-projects/modules. -buildscript { - repositories { - mavenCentral() - google() - } - dependencies { - classpath 'com.android.tools.build:gradle:7.4.2' - } -} - -allprojects { - repositories { - mavenCentral() - google() - } -} diff --git a/CMake/Templates/resources.cfg.in b/CMake/Templates/resources.cfg.in deleted file mode 100644 index c022537f8a0..00000000000 --- a/CMake/Templates/resources.cfg.in +++ /dev/null @@ -1,12 +0,0 @@ -# Ogre Core Resources -[OgreInternal] -FileSystem=@OGRE_CORE_MEDIA_DIR@/Main -FileSystem=@OGRE_CORE_MEDIA_DIR@/RTShaderLib -FileSystem=@OGRE_CORE_MEDIA_DIR@/Terrain/ - -# Resources required by OgreBites::Trays -[Essential] -Zip=@OGRE_CORE_MEDIA_DIR@/packs/SdkTrays.zip -Zip=@OGRE_CORE_MEDIA_DIR@/packs/profiler.zip - -@OGRE_SAMPLE_RESOURCES@ diff --git a/CMake/Templates/sample_resources.cfg.in b/CMake/Templates/sample_resources.cfg.in deleted file mode 100644 index c3047be0f01..00000000000 --- a/CMake/Templates/sample_resources.cfg.in +++ /dev/null @@ -1,51 +0,0 @@ -# this line will end up in the [Essential] group -FileSystem=@OGRE_MEDIA_DIR_REL@/thumbnails - -# Common sample resources needed by many of the samples. -# Rarely used resources should be separately loaded by the -# samples which require them. -[General] -# PBR media must come before the scripts that reference it -FileSystem=@OGRE_MEDIA_DIR_REL@/PBR -FileSystem=@OGRE_MEDIA_DIR_REL@/PBR/filament - -FileSystem=@OGRE_MEDIA_DIR_REL@/materials/programs/GLSL -FileSystem=@OGRE_MEDIA_DIR_REL@/materials/programs/GLSL120 -FileSystem=@OGRE_MEDIA_DIR_REL@/materials/programs/GLSL150 -FileSystem=@OGRE_MEDIA_DIR_REL@/materials/programs/GLSL400 -FileSystem=@OGRE_MEDIA_DIR_REL@/materials/programs/GLSLES -FileSystem=@OGRE_MEDIA_DIR_REL@/materials/programs/SPIRV -FileSystem=@OGRE_MEDIA_DIR_REL@/materials/programs/Cg -FileSystem=@OGRE_MEDIA_DIR_REL@/materials/programs/HLSL -FileSystem=@OGRE_MEDIA_DIR_REL@/materials/programs/HLSL_Cg -FileSystem=@OGRE_MEDIA_DIR_REL@/materials/scripts -FileSystem=@OGRE_MEDIA_DIR_REL@/materials/textures -FileSystem=@OGRE_MEDIA_DIR_REL@/materials/textures/terrain -FileSystem=@OGRE_MEDIA_DIR_REL@/models -FileSystem=@OGRE_MEDIA_DIR_REL@/particle -FileSystem=@OGRE_MEDIA_DIR_REL@/DeferredShadingMedia -FileSystem=@OGRE_MEDIA_DIR_REL@/DeferredShadingMedia/DeferredShading/post -FileSystem=@OGRE_MEDIA_DIR_REL@/PCZAppMedia -FileSystem=@OGRE_MEDIA_DIR_REL@/materials/scripts/SSAO -FileSystem=@OGRE_MEDIA_DIR_REL@/materials/textures/SSAO -FileSystem=@OGRE_MEDIA_DIR_REL@/volumeTerrain -FileSystem=@OGRE_MEDIA_DIR_REL@/CSMShadows -Zip=@OGRE_MEDIA_DIR_REL@/packs/cubemap.zip -Zip=@OGRE_MEDIA_DIR_REL@/packs/cubemapsJS.zip -Zip=@OGRE_MEDIA_DIR_REL@/packs/dragon.zip -Zip=@OGRE_MEDIA_DIR_REL@/packs/fresneldemo.zip -Zip=@OGRE_MEDIA_DIR_REL@/packs/ogredance.zip -Zip=@OGRE_MEDIA_DIR_REL@/packs/Sinbad.zip -Zip=@OGRE_MEDIA_DIR_REL@/packs/skybox.zip -Zip=@OGRE_MEDIA_DIR_REL@/volumeTerrain/volumeTerrainBig.zip - -Zip=@OGRE_MEDIA_DIR_REL@/packs/DamagedHelmet.zip -Zip=@OGRE_MEDIA_DIR_REL@/packs/filament_shaders.zip - -[BSPWorld] -Zip=@OGRE_MEDIA_DIR_REL@/packs/oa_rpg3dm2.pk3 -Zip=@OGRE_MEDIA_DIR_REL@/packs/ogretestmap.zip - -# Materials for visual tests -[Tests] -FileSystem=@OGRE_TEST_MEDIA_DIR_REL@ \ No newline at end of file diff --git a/CMake/Templates/samples.cfg.in b/CMake/Templates/samples.cfg.in deleted file mode 100644 index 69d861c0093..00000000000 --- a/CMake/Templates/samples.cfg.in +++ /dev/null @@ -1,3 +0,0 @@ -SampleFolder=@OGRE_SAMPLES_DIR_REL@ -SamplePlugin=DefaultSamples -@OGRE_COMMENT_PLAYPENTESTS@SamplePlugin=PlayPenTests diff --git a/CMake/Templates/version.txt.in b/CMake/Templates/version.txt.in deleted file mode 100644 index fe892f285a3..00000000000 --- a/CMake/Templates/version.txt.in +++ /dev/null @@ -1 +0,0 @@ -@OGRE_VERSION_DASH_SEPARATED@ \ No newline at end of file diff --git a/CMake/Utils/AndroidMacros.cmake b/CMake/Utils/AndroidMacros.cmake deleted file mode 100644 index 59252fdd97c..00000000000 --- a/CMake/Utils/AndroidMacros.cmake +++ /dev/null @@ -1,90 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -macro(add_ndk_cpufeatures_library) - include_directories(${ANDROID_NDK}/sources/android/cpufeatures) - if(NOT TARGET cpufeatures) - add_library(cpufeatures STATIC ${ANDROID_NDK}/sources/android/cpufeatures/cpu-features.c) - target_link_libraries(cpufeatures dl) - endif(NOT TARGET cpufeatures) -endmacro(add_ndk_cpufeatures_library) - -macro(add_ndk_native_app_glue_library) - include_directories(${ANDROID_NDK}/sources/android/native_app_glue) - if(NOT TARGET native_app_glue) - add_library(native_app_glue STATIC ${ANDROID_NDK}/sources/android/native_app_glue/android_native_app_glue.c) - target_link_libraries(native_app_glue log) - endif(NOT TARGET native_app_glue) -endmacro(add_ndk_native_app_glue_library) - -macro(copy_assets_to_android_proj) - configure_file("${OGRE_TEMPLATES_DIR}/Android_resources.cfg.in" "${NDKOUT}/app/src/main/assets/resources.cfg" @ONLY) - configure_file("${OGRE_TEMPLATES_DIR}/samples.cfg.in" "${NDKOUT}/app/src/main/assets/samples.cfg" @ONLY) - - file(COPY "${PROJECT_SOURCE_DIR}/Media/" DESTINATION "${NDKOUT}/app/src/main/assets") - - file(COPY "${PROJECT_SOURCE_DIR}/Samples/Media/models" DESTINATION "${NDKOUT}/app/src/main/assets") - file(COPY "${PROJECT_SOURCE_DIR}/Samples/Media/particle" DESTINATION "${NDKOUT}/app/src/main/assets") - file(COPY "${PROJECT_SOURCE_DIR}/Samples/Media/thumbnails" DESTINATION "${NDKOUT}/app/src/main/assets") - file(COPY "${PROJECT_SOURCE_DIR}/Samples/Media/packs" DESTINATION "${NDKOUT}/app/src/main/assets") - file(COPY "${PROJECT_SOURCE_DIR}/Samples/Media/materials" DESTINATION "${NDKOUT}/app/src/main/assets") - file(COPY "${PROJECT_SOURCE_DIR}/Samples/Media/PBR" DESTINATION "${NDKOUT}/app/src/main/assets") - file(COPY "${PROJECT_SOURCE_DIR}/Samples/Media/DeferredShadingMedia" DESTINATION "${NDKOUT}/app/src/main/assets") - - file(COPY "${PROJECT_SOURCE_DIR}/SDK/Android/drawable-hdpi" DESTINATION "${NDKOUT}/app/src/main/res") - file(COPY "${PROJECT_SOURCE_DIR}/SDK/Android/drawable-ldpi" DESTINATION "${NDKOUT}/app/src/main/res") - file(COPY "${PROJECT_SOURCE_DIR}/SDK/Android/drawable-mdpi" DESTINATION "${NDKOUT}/app/src/main/res") - file(COPY "${PROJECT_SOURCE_DIR}/SDK/Android/drawable-xhdpi" DESTINATION "${NDKOUT}/app/src/main/res") -endmacro() - -macro(create_android_proj ANDROID_PROJECT_TARGET) - ################################################################## - # Creates a basic android JNI project - # Expects : - # - ANDROID_MOD_NAME Name of the android module - # - PKG_NAME The name of the output android package ex"Org.Ogre.OgreJNI" - # - NDKOUT The directory for the Ndk project to be written to - # - HAS_CODE Set this variable to "false" if no java code will be present - # (google android:hasCode for more info) - # - MAIN_ACTIVITY Name of the main java activity ex "android.app.MainActivity" - # - EXTRA_ACTIVITIES Name of additional java activities - ################################################################## - - SET(ANDROID_SDK_API_LEVEL "${ANDROID_NATIVE_API_LEVEL}") - SET(ANDROID_TARGET "android-${ANDROID_SDK_API_LEVEL}") - - file(MAKE_DIRECTORY "${NDKOUT}/app/src/main/assets") - file(MAKE_DIRECTORY "${NDKOUT}/app/src/main/res") - - foreach(ACTIVITY_NAME ${MAIN_ACTIVITY} ${EXTRA_ACTIVITIES}) - if(EXTRA_ACTIVITIES) - string(FIND ${ACTIVITY_NAME} "." DOT REVERSE) - math(EXPR DOT "${DOT} + 1") - string(SUBSTRING ${ACTIVITY_NAME} ${DOT} -1 LABEL) - else() - set(LABEL ${ANDROID_MOD_NAME}) - endif() - set(ANDROID_ACTIVITIES "${ANDROID_ACTIVITIES} - - - - - - - ") - endforeach() - configure_file("${OGRE_TEMPLATES_DIR}/AndroidManifest.xml.in" "${NDKOUT}/app/src/main/AndroidManifest.xml" @ONLY) - configure_file("${OGRE_TEMPLATES_DIR}/app.gradle.in" "${NDKOUT}/app/build.gradle" @ONLY) - configure_file("${OGRE_TEMPLATES_DIR}/project.gradle" "${NDKOUT}/build.gradle" @ONLY) - configure_file("${OGRE_TEMPLATES_DIR}/gradle.properties" "${NDKOUT}/gradle.properties" @ONLY) - file(WRITE "${NDKOUT}/settings.gradle" "include ':app'") -endmacro(create_android_proj) diff --git a/CMake/Utils/FindPkgMacros.cmake b/CMake/Utils/FindPkgMacros.cmake deleted file mode 100644 index 374f84beae4..00000000000 --- a/CMake/Utils/FindPkgMacros.cmake +++ /dev/null @@ -1,165 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -################################################################## -# Provides some common functionality for the FindPackage modules -################################################################## - -# Begin processing of package -macro(findpkg_begin PREFIX) - if (NOT ${PREFIX}_FIND_QUIETLY) - message(STATUS "Looking for ${PREFIX}...") - endif () -endmacro(findpkg_begin) - -# Display a status message unless FIND_QUIETLY is set -macro(pkg_message PREFIX) - if (NOT ${PREFIX}_FIND_QUIETLY) - message(STATUS ${ARGN}) - endif () -endmacro(pkg_message) - -# Get environment variable, define it as ENV_$var and make sure backslashes are converted to forward slashes -macro(getenv_path VAR) - set(ENV_${VAR} $ENV{${VAR}}) - # replace won't work if var is blank - if (ENV_${VAR}) - string( REGEX REPLACE "\\\\" "/" ENV_${VAR} ${ENV_${VAR}} ) - endif () -endmacro(getenv_path) - -# Construct search paths for includes and libraries from a PREFIX_PATH -macro(create_search_paths PREFIX) - foreach(dir ${${PREFIX}_PREFIX_PATH}) - set(${PREFIX}_INC_SEARCH_PATH ${${PREFIX}_INC_SEARCH_PATH} - ${dir}/include ${dir}/Include ${dir}/include/${PREFIX} ${dir}/Headers) - set(${PREFIX}_LIB_SEARCH_PATH ${${PREFIX}_LIB_SEARCH_PATH} - ${dir}/lib ${dir}/Lib ${dir}/lib/${PREFIX} ${dir}/Libs) - set(${PREFIX}_BIN_SEARCH_PATH ${${PREFIX}_BIN_SEARCH_PATH} - ${dir}/bin) - endforeach(dir) - if(ANDROID) - set(${PREFIX}_LIB_SEARCH_PATH ${${PREFIX}_LIB_SEARCH_PATH} ${OGRE_DEPENDENCIES_DIR}/lib/${ANDROID_ABI}) - endif() - set(${PREFIX}_FRAMEWORK_SEARCH_PATH ${${PREFIX}_PREFIX_PATH}) -endmacro(create_search_paths) - -# clear cache variables if a certain variable changed -macro(clear_if_changed TESTVAR) - # test against internal check variable - # HACK: Apparently, adding a variable to the cache cleans up the list - # a bit. We need to also remove any empty strings from the list, but - # at the same time ensure that we are actually dealing with a list. - list(APPEND ${TESTVAR} "") - list(REMOVE_ITEM ${TESTVAR} "") - if (NOT "${${TESTVAR}}" STREQUAL "${${TESTVAR}_INT_CHECK}") - message(STATUS "${TESTVAR} changed.") - foreach(var ${ARGN}) - set(${var} "NOTFOUND" CACHE STRING "x" FORCE) - endforeach(var) - endif () - set(${TESTVAR}_INT_CHECK ${${TESTVAR}} CACHE INTERNAL "x" FORCE) -endmacro(clear_if_changed) - -# Try to get some hints from pkg-config, if available -macro(use_pkgconfig PREFIX PKGNAME) - if(NOT ANDROID) - find_package(PkgConfig) - if (PKG_CONFIG_FOUND) - pkg_check_modules(${PREFIX} ${PKGNAME}) - endif () - endif() -endmacro (use_pkgconfig) - -# Couple a set of release AND debug libraries (or frameworks) -macro(make_library_set PREFIX) - if (${PREFIX}_FWK) - set(${PREFIX} ${${PREFIX}_FWK}) - elseif (${PREFIX}_REL AND ${PREFIX}_DBG) - set(${PREFIX} optimized ${${PREFIX}_REL} debug ${${PREFIX}_DBG}) - elseif (${PREFIX}_REL) - set(${PREFIX} ${${PREFIX}_REL}) - elseif (${PREFIX}_DBG) - set(${PREFIX} ${${PREFIX}_DBG}) - endif () -endmacro(make_library_set) - -# Generate debug names from given release names -macro(get_debug_names PREFIX) - foreach(i ${${PREFIX}}) - set(${PREFIX}_DBG ${${PREFIX}_DBG} ${i}d ${i}D ${i}_d ${i}_D ${i}_debug) - endforeach(i) -endmacro(get_debug_names) - -# Add the parent dir from DIR to VAR -macro(add_parent_dir VAR DIR) - get_filename_component(${DIR}_TEMP "${${DIR}}/.." ABSOLUTE) - set(${VAR} ${${VAR}} ${${DIR}_TEMP}) -endmacro(add_parent_dir) - -# Do the final processing for the package find. -macro(findpkg_finish PREFIX) - # skip if already processed during this run - if (NOT ${PREFIX}_FOUND) - if (${PREFIX}_INCLUDE_DIR AND ${PREFIX}_LIBRARY) - set(${PREFIX}_FOUND TRUE) - set(${PREFIX}_INCLUDE_DIRS ${${PREFIX}_INCLUDE_DIR}) - set(${PREFIX}_LIBRARIES ${${PREFIX}_LIBRARY}) - if (NOT ${PREFIX}_FIND_QUIETLY) - message(STATUS "Found ${PREFIX}: ${${PREFIX}_LIBRARIES}") - endif () - else () - if (NOT ${PREFIX}_FIND_QUIETLY) - message(STATUS "Could not locate ${PREFIX}") - endif () - if (${PREFIX}_FIND_REQUIRED) - message(FATAL_ERROR "Required library ${PREFIX} not found! Install the library (including dev packages) and try again. If the library is already installed, set the missing variables manually in cmake.") - endif () - endif () - - mark_as_advanced(${PREFIX}_INCLUDE_DIR ${PREFIX}_LIBRARY ${PREFIX}_LIBRARY_REL ${PREFIX}_LIBRARY_DBG ${PREFIX}_LIBRARY_FWK) - endif () -endmacro(findpkg_finish) - - -# Slightly customised framework finder -macro(findpkg_framework fwk) - if(APPLE) - set(${fwk}_FRAMEWORK_PATH - ${${fwk}_FRAMEWORK_SEARCH_PATH} - ${CMAKE_FRAMEWORK_PATH} - ~/Library/Frameworks - /Library/Frameworks - /System/Library/Frameworks - /Network/Library/Frameworks - ${CMAKE_CURRENT_SOURCE_DIR}/lib/macosx/Release - ${CMAKE_CURRENT_SOURCE_DIR}/lib/macosx/Debug - ) - # These could be arrays of paths, add each individually to the search paths - foreach(i ${OGRE_PREFIX_PATH}) - set(${fwk}_FRAMEWORK_PATH ${${fwk}_FRAMEWORK_PATH} ${i}/lib/macosx/Release ${i}/lib/macosx/Debug) - endforeach(i) - - foreach(i ${OGRE_PREFIX_BUILD}) - set(${fwk}_FRAMEWORK_PATH ${${fwk}_FRAMEWORK_PATH} ${i}/lib/macosx/Release ${i}/lib/macosx/Debug) - endforeach(i) - - foreach(dir ${${fwk}_FRAMEWORK_PATH}) - set(fwkpath ${dir}/${fwk}.framework) - if(EXISTS ${fwkpath}) - set(${fwk}_FRAMEWORK_INCLUDES ${${fwk}_FRAMEWORK_INCLUDES} - ${fwkpath}/Headers ${fwkpath}/PrivateHeaders) - set(${fwk}_FRAMEWORK_PATH ${dir}) - if (NOT ${fwk}_LIBRARY_FWK) - set(${fwk}_LIBRARY_FWK "-framework ${fwk}") - endif () - endif(EXISTS ${fwkpath}) - endforeach(dir) - endif(APPLE) -endmacro(findpkg_framework) diff --git a/CMake/Utils/MacroLogFeature.cmake b/CMake/Utils/MacroLogFeature.cmake deleted file mode 100644 index b3a4eee656b..00000000000 --- a/CMake/Utils/MacroLogFeature.cmake +++ /dev/null @@ -1,134 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# This file defines the Feature Logging macros. -# -# MACRO_LOG_FEATURE(VAR FEATURE DESCRIPTION URL [REQUIRED [MIN_VERSION [COMMENTS]]]) -# Logs the information so that it can be displayed at the end -# of the configure run -# VAR : TRUE or FALSE, indicating whether the feature is supported -# FEATURE: name of the feature, e.g. "libjpeg" -# DESCRIPTION: description what this feature provides -# URL: home page -# REQUIRED: TRUE or FALSE, indicating whether the feature is required -# MIN_VERSION: minimum version number. empty string if unneeded -# COMMENTS: More info you may want to provide. empty string if unnecessary -# -# MACRO_DISPLAY_FEATURE_LOG() -# Call this to display the collected results. -# Exits CMake with a FATAL error message if a required feature is missing -# -# Example: -# -# INCLUDE(MacroLogFeature) -# -# FIND_PACKAGE(JPEG) -# MACRO_LOG_FEATURE(JPEG_FOUND "libjpeg" "Support JPEG images" "http://www.ijg.org" TRUE "3.2a" "") -# ... -# MACRO_DISPLAY_FEATURE_LOG() - -# Copyright (c) 2006, Alexander Neundorf, -# Copyright (c) 2006, Allen Winter, -# -# Redistribution and use is allowed according to the terms of the BSD license. -# For details see the accompanying COPYING-CMAKE-SCRIPTS file. - -IF (NOT _macroLogFeatureAlreadyIncluded) - SET(_file ${PROJECT_BINARY_DIR}/MissingRequirements.txt) - IF (EXISTS ${_file}) - FILE(REMOVE ${_file}) - ENDIF (EXISTS ${_file}) - - SET(_file ${PROJECT_BINARY_DIR}/EnabledFeatures.txt) - IF (EXISTS ${_file}) - FILE(REMOVE ${_file}) - ENDIF (EXISTS ${_file}) - - SET(_file ${PROJECT_BINARY_DIR}/DisabledFeatures.txt) - IF (EXISTS ${_file}) - FILE(REMOVE ${_file}) - ENDIF (EXISTS ${_file}) - - SET(_macroLogFeatureAlreadyIncluded TRUE) -ENDIF (NOT _macroLogFeatureAlreadyIncluded) - - -MACRO(MACRO_LOG_FEATURE _var _package _description _url ) # _required _minvers _comments) - - SET(_required "${ARGV4}") - SET(_minvers "${ARGV5}") - SET(_comments "${ARGV6}") - - IF (${_var}) - SET(_LOGFILENAME ${PROJECT_BINARY_DIR}/EnabledFeatures.txt) - ELSE (${_var}) - IF (${_required} MATCHES "[Tt][Rr][Uu][Ee]") - SET(_LOGFILENAME ${PROJECT_BINARY_DIR}/MissingRequirements.txt) - ELSE (${_required} MATCHES "[Tt][Rr][Uu][Ee]") - SET(_LOGFILENAME ${PROJECT_BINARY_DIR}/DisabledFeatures.txt) - ENDIF (${_required} MATCHES "[Tt][Rr][Uu][Ee]") - ENDIF (${_var}) - - SET(_logtext "+ ${_package}") - - IF (NOT ${_var}) - IF (${_minvers} MATCHES ".*") - SET(_logtext "${_logtext}, ${_minvers}") - ENDIF (${_minvers} MATCHES ".*") - SET(_logtext "${_logtext}: ${_description} <${_url}>") - IF (${_comments} MATCHES ".*") - SET(_logtext "${_logtext}\n${_comments}") - ENDIF (${_comments} MATCHES ".*") -# SET(_logtext "${_logtext}\n") #double-space missing features? - ENDIF (NOT ${_var}) - FILE(APPEND "${_LOGFILENAME}" "${_logtext}\n") - -ENDMACRO(MACRO_LOG_FEATURE) - - -MACRO(MACRO_DISPLAY_FEATURE_LOG) - - SET(_file ${PROJECT_BINARY_DIR}/MissingRequirements.txt) - IF (EXISTS ${_file}) - FILE(READ ${_file} _requirements) - MESSAGE(FATAL_ERROR "\n-----------------------------------------------------------------------------\n-- The following REQUIRED packages could NOT be located on your system.\n-- Please install them before continuing this software installation.\n-- If you are in Windows, try passing -DOGRE_DEPENDENCIES_DIR=\n-----------------------------------------------------------------------------\n${_requirements}-----------------------------------------------------------------------------") - FILE(REMOVE ${_file}) - MESSAGE(FATAL_ERROR "Exiting: Missing Requirements") - ENDIF (EXISTS ${_file}) - - SET(_summary "\n") - - SET(_elist 0) - SET(_file ${PROJECT_BINARY_DIR}/EnabledFeatures.txt) - IF (EXISTS ${_file}) - SET(_elist 1) - FILE(READ ${_file} _enabled) - FILE(REMOVE ${_file}) - SET(_summary "${_summary}-----------------------------------------------------------------------------\n-- The following external packages were located on your system.\n-- This installation will have the extra features provided by these packages.\n${_enabled}") - ENDIF (EXISTS ${_file}) - - SET(_dlist 0) - SET(_file ${PROJECT_BINARY_DIR}/DisabledFeatures.txt) - IF (EXISTS ${_file}) - SET(_dlist 1) - FILE(READ ${_file} _disabled) - FILE(REMOVE ${_file}) - SET(_summary "${_summary}-----------------------------------------------------------------------------\n-- The following OPTIONAL packages could NOT be located on your system.\n-- Consider installing them to enable more features from this software.\n${_disabled}") - ELSE (EXISTS ${_file}) - IF (${_elist}) - SET(_summary "${_summary}Congratulations! All external packages have been found.\n") - ENDIF (${_elist}) - ENDIF (EXISTS ${_file}) - - IF (${_elist} OR ${_dlist}) - SET(_summary "${_summary}-----------------------------------------------------------------------------\n") - ENDIF (${_elist} OR ${_dlist}) - MESSAGE(STATUS "${_summary}") - -ENDMACRO(MACRO_DISPLAY_FEATURE_LOG) diff --git a/CMake/Utils/OgreConfigTargets.cmake b/CMake/Utils/OgreConfigTargets.cmake deleted file mode 100644 index c4e6de897eb..00000000000 --- a/CMake/Utils/OgreConfigTargets.cmake +++ /dev/null @@ -1,385 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure settings and install targets -if(APPLE) - macro(set_xcode_property targ xc_prop_name xc_prop_val) - set_property( TARGET ${targ} PROPERTY XCODE_ATTRIBUTE_${xc_prop_name} ${xc_prop_val} ) - endmacro(set_xcode_property) - - if(NOT OGRE_BUILD_PLATFORM_ANDROID AND NOT APPLE_IOS) - set(PLATFORM_NAME "macosx") - elseif(APPLE_IOS) - set(PLATFORM_NAME "$(PLATFORM_NAME)") - endif() -endif() - -# Default build output paths -if (NOT OGRE_ARCHIVE_OUTPUT) - if(APPLE AND NOT OGRE_BUILD_PLATFORM_ANDROID) - set(OGRE_ARCHIVE_OUTPUT ${PROJECT_BINARY_DIR}/lib/${PLATFORM_NAME}) - else() - set(OGRE_ARCHIVE_OUTPUT ${PROJECT_BINARY_DIR}/lib) - endif() -endif () -if (NOT OGRE_LIBRARY_OUTPUT) - if(APPLE AND NOT OGRE_BUILD_PLATFORM_ANDROID) - set(OGRE_LIBRARY_OUTPUT ${PROJECT_BINARY_DIR}/lib/${PLATFORM_NAME}) - else() - set(OGRE_LIBRARY_OUTPUT ${PROJECT_BINARY_DIR}/lib) - endif() -endif () -if (NOT OGRE_RUNTIME_OUTPUT) - set(OGRE_RUNTIME_OUTPUT ${PROJECT_BINARY_DIR}/bin) -endif () - -if (WIN32) - set(OGRE_RELEASE_PATH "") - set(OGRE_RELWDBG_PATH "") - set(OGRE_DEBUG_PATH "") - set(OGRE_LIB_RELEASE_PATH "") - set(OGRE_LIB_RELWDBG_PATH "") - set(OGRE_LIB_DEBUG_PATH "") -elseif (UNIX) - set(OGRE_RELEASE_PATH "") - set(OGRE_RELWDBG_PATH "") - set(OGRE_DEBUG_PATH "/debug") - if (NOT APPLE) - set(OGRE_DEBUG_PATH "") - endif () - set(OGRE_LIB_RELEASE_PATH "") - set(OGRE_LIB_RELWDBG_PATH "") - set(OGRE_LIB_DEBUG_PATH "") - if(APPLE AND NOT APPLE_IOS) - set(OGRE_RELEASE_PATH "/${PLATFORM_NAME}") - endif() - if(APPLE AND APPLE_IOS) - set(OGRE_LIB_RELEASE_PATH "/Release") - endif(APPLE AND APPLE_IOS) -endif () - -set(OGRE_SAMPLE_PATH "/OGRE/Samples") - -# install targets according to current build type -function(ogre_install_target TARGETNAME SUFFIX EXPORT) - if(EXPORT) - install(TARGETS ${TARGETNAME} EXPORT OgreTargetsRelease - CONFIGURATIONS Release MinSizeRel None "" - BUNDLE DESTINATION "${OGRE_BIN_DIRECTORY}${OGRE_RELEASE_PATH}" - RUNTIME DESTINATION "${OGRE_BIN_DIRECTORY}${OGRE_RELEASE_PATH}" - LIBRARY DESTINATION "${OGRE_LIB_DIRECTORY}${OGRE_LIB_RELEASE_PATH}${SUFFIX}" - ARCHIVE DESTINATION "${OGRE_LIB_DIRECTORY}${OGRE_LIB_RELEASE_PATH}${SUFFIX}" - FRAMEWORK DESTINATION "${OGRE_LIB_DIRECTORY}${OGRE_RELEASE_PATH}/Release") - install(TARGETS ${TARGETNAME} EXPORT OgreTargetsRelWithDebInfo - CONFIGURATIONS RelWithDebInfo - BUNDLE DESTINATION "${OGRE_BIN_DIRECTORY}${OGRE_RELWDBG_PATH}" - RUNTIME DESTINATION "${OGRE_BIN_DIRECTORY}${OGRE_RELWDBG_PATH}" - LIBRARY DESTINATION "${OGRE_LIB_DIRECTORY}${OGRE_LIB_RELWDBG_PATH}${SUFFIX}" - ARCHIVE DESTINATION "${OGRE_LIB_DIRECTORY}${OGRE_LIB_RELWDBG_PATH}${SUFFIX}" - FRAMEWORK DESTINATION "${OGRE_LIB_DIRECTORY}${OGRE_RELWDBG_PATH}/RelWithDebInfo") - install(TARGETS ${TARGETNAME} EXPORT OgreTargetsDebug - CONFIGURATIONS Debug - BUNDLE DESTINATION "${OGRE_BIN_DIRECTORY}${OGRE_DEBUG_PATH}" - RUNTIME DESTINATION "${OGRE_BIN_DIRECTORY}${OGRE_DEBUG_PATH}" - LIBRARY DESTINATION "${OGRE_LIB_DIRECTORY}${OGRE_LIB_DEBUG_PATH}${SUFFIX}" - ARCHIVE DESTINATION "${OGRE_LIB_DIRECTORY}${OGRE_LIB_DEBUG_PATH}${SUFFIX}" - FRAMEWORK DESTINATION "${OGRE_LIB_DIRECTORY}${OGRE_DEBUG_PATH}/Debug") - else() - install(TARGETS ${TARGETNAME} - CONFIGURATIONS Release None "" - BUNDLE DESTINATION "${OGRE_BIN_DIRECTORY}${OGRE_RELEASE_PATH}" - RUNTIME DESTINATION "${OGRE_BIN_DIRECTORY}${OGRE_RELEASE_PATH}" - LIBRARY DESTINATION "${OGRE_LIB_DIRECTORY}${OGRE_LIB_RELEASE_PATH}${SUFFIX}" - ARCHIVE DESTINATION "${OGRE_LIB_DIRECTORY}${OGRE_LIB_RELEASE_PATH}${SUFFIX}" - FRAMEWORK DESTINATION "${OGRE_LIB_DIRECTORY}${OGRE_RELEASE_PATH}/Release") - install(TARGETS ${TARGETNAME} - CONFIGURATIONS RelWithDebInfo - BUNDLE DESTINATION "${OGRE_BIN_DIRECTORY}${OGRE_RELWDBG_PATH}" - RUNTIME DESTINATION "${OGRE_BIN_DIRECTORY}${OGRE_RELWDBG_PATH}" - LIBRARY DESTINATION "${OGRE_LIB_DIRECTORY}${OGRE_LIB_RELWDBG_PATH}${SUFFIX}" - ARCHIVE DESTINATION "${OGRE_LIB_DIRECTORY}${OGRE_LIB_RELWDBG_PATH}${SUFFIX}" - FRAMEWORK DESTINATION "${OGRE_LIB_DIRECTORY}${OGRE_RELWDBG_PATH}/RelWithDebInfo") - install(TARGETS ${TARGETNAME} - CONFIGURATIONS Debug - BUNDLE DESTINATION "${OGRE_BIN_DIRECTORY}${OGRE_DEBUG_PATH}" - RUNTIME DESTINATION "${OGRE_BIN_DIRECTORY}${OGRE_DEBUG_PATH}" - LIBRARY DESTINATION "${OGRE_LIB_DIRECTORY}${OGRE_LIB_DEBUG_PATH}${SUFFIX}" - ARCHIVE DESTINATION "${OGRE_LIB_DIRECTORY}${OGRE_LIB_DEBUG_PATH}${SUFFIX}" - FRAMEWORK DESTINATION "${OGRE_LIB_DIRECTORY}${OGRE_DEBUG_PATH}/Debug") - endif() -endfunction(ogre_install_target) - -function(ogre_install_plugin TARGETNAME) - if (OGRE_BUILD_LIBS_AS_FRAMEWORKS) - ogre_install_target(${TARGETNAME} "" TRUE) - else() - install(TARGETS ${TARGETNAME} EXPORT OgreTargetsRelease CONFIGURATIONS MinSizeRel Release None "" DESTINATION ${OGRE_PLUGINS_PATH}) - install(TARGETS ${TARGETNAME} EXPORT OgreTargetsRelWithDebInfo CONFIGURATIONS RelWithDebInfo DESTINATION ${OGRE_PLUGINS_PATH}) - install(TARGETS ${TARGETNAME} EXPORT OgreTargetsDebug CONFIGURATIONS Debug DESTINATION ${OGRE_PLUGINS_PATH}) - endif() -endfunction(ogre_install_plugin) - -# setup common target settings -function(ogre_config_common TARGETNAME) - set_target_properties(${TARGETNAME} PROPERTIES - ARCHIVE_OUTPUT_DIRECTORY ${OGRE_ARCHIVE_OUTPUT} - LIBRARY_OUTPUT_DIRECTORY ${OGRE_LIBRARY_OUTPUT} - RUNTIME_OUTPUT_DIRECTORY ${OGRE_RUNTIME_OUTPUT} - ) - if(APPLE_IOS) - set_target_properties(${TARGETNAME} PROPERTIES XCODE_ATTRIBUTE_GCC_THUMB_SUPPORT "NO") - set_target_properties(${TARGETNAME} PROPERTIES XCODE_ATTRIBUTE_GCC_UNROLL_LOOPS "YES") - set_target_properties(${TARGETNAME} PROPERTIES XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "iPhone Developer") - set_target_properties(${TARGETNAME} PROPERTIES XCODE_ATTRIBUTE_GCC_PRECOMPILE_PREFIX_HEADER "YES") - set_target_properties(${TARGETNAME} PROPERTIES XCODE_ATTRIBUTE_DEBUG_INFORMATION_FORMAT "dwarf$<$>:-with-dsym>") - endif(APPLE_IOS) - - if(NOT OGRE_STATIC AND (CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")) - set_target_properties(${TARGETNAME} PROPERTIES XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH "NO") - endif() -endfunction(ogre_config_common) - -# checks whether the target LIBNAME produces a pdb file -function(ogre_produces_pdb VARNAME LIBNAME) - get_target_property(TYPE ${LIBNAME} TYPE) - if (TYPE STREQUAL "SHARED_LIBRARY" OR TYPE STREQUAL "MODULE_LIBRARY" OR TYPE STREQUAL "EXECUTABLE") - set(${VARNAME} ON PARENT_SCOPE) - else () - set(${VARNAME} OFF PARENT_SCOPE) - endif () -endfunction(ogre_produces_pdb) - -# setup library build -function(ogre_config_lib LIBNAME EXPORT) - ogre_config_common(${LIBNAME}) - if (OGRE_STATIC) - # add static prefix, if compiling static version - set_target_properties(${LIBNAME} PROPERTIES OUTPUT_NAME ${LIBNAME}Static) - else (OGRE_STATIC) - if (MINGW) - # remove lib prefix from DLL outputs - set_target_properties(${LIBNAME} PROPERTIES PREFIX "") - endif () - endif (OGRE_STATIC) - ogre_install_target(${LIBNAME} "" ${EXPORT}) - - if (OGRE_INSTALL_PDB) - # install debug pdb files - if (OGRE_STATIC) - install(FILES ${PROJECT_BINARY_DIR}/lib${OGRE_LIB_DEBUG_PATH}/${LIBNAME}Static_d.pdb - DESTINATION ${OGRE_LIB_DIRECTORY}${OGRE_LIB_DEBUG_PATH} - CONFIGURATIONS Debug - ) - install(FILES ${PROJECT_BINARY_DIR}/lib${OGRE_LIB_RELWDBG_PATH}/${LIBNAME}Static.pdb - DESTINATION ${OGRE_LIB_DIRECTORY}${OGRE_LIB_RELWDBG_PATH} - CONFIGURATIONS RelWithDebInfo - ) - else () - ogre_produces_pdb(PRODUCES_PDB ${LIBNAME}) - if (PRODUCES_PDB) - install(FILES $ - DESTINATION bin${OGRE_DEBUG_PATH} - CONFIGURATIONS Debug - ) - install(FILES $ - DESTINATION bin${OGRE_RELWDBG_PATH} - CONFIGURATIONS RelWithDebInfo - ) - endif () - endif () - endif () -endfunction(ogre_config_lib) - -function(ogre_config_component LIBNAME) - ogre_config_lib(${LIBNAME} TRUE) - if (OGRE_PROJECT_FOLDERS) - set_property(TARGET ${LIBNAME} PROPERTY FOLDER Components) - endif () -endfunction(ogre_config_component) - -function(ogre_config_framework LIBNAME) - if (OGRE_BUILD_LIBS_AS_FRAMEWORKS) - set_target_properties(${LIBNAME} PROPERTIES FRAMEWORK TRUE) - - # Set the INSTALL_PATH so that frameworks can be installed in the application package - set_target_properties(${LIBNAME} - PROPERTIES BUILD_WITH_INSTALL_RPATH 1 - INSTALL_NAME_DIR "@rpath" - ) - set_target_properties(${LIBNAME} PROPERTIES PUBLIC_HEADER "${HEADER_FILES};${PLATFORM_HEADERS};" ) - set_target_properties(${LIBNAME} PROPERTIES RESOURCE "${RESOURCE_FILES}") - set_source_files_properties("${RESOURCE_FILES}" PROPERTIES MACOSX_PACKAGE_LOCATION Resources) - - set_target_properties(${LIBNAME} PROPERTIES OUTPUT_NAME ${LIBNAME}) - endif() -endfunction(ogre_config_framework) - -# setup plugin build -function(ogre_config_plugin PLUGINNAME) - ogre_config_common(${PLUGINNAME}) - - if (OGRE_PROJECT_FOLDERS) - set_property(TARGET ${LIBNAME} PROPERTY FOLDER Plugins) - endif () - - set_target_properties(${PLUGINNAME} PROPERTIES VERSION ${OGRE_SOVERSION}) - if (OGRE_STATIC) - # add static prefix, if compiling static version - set_target_properties(${PLUGINNAME} PROPERTIES OUTPUT_NAME ${PLUGINNAME}Static) - - if(APPLE_IOS) - set_target_properties(${PLUGINNAME} PROPERTIES XCODE_ATTRIBUTE_GCC_THUMB_SUPPORT "NO") - set_target_properties(${PLUGINNAME} PROPERTIES XCODE_ATTRIBUTE_GCC_UNROLL_LOOPS "YES") - set_target_properties(${PLUGINNAME} PROPERTIES XCODE_ATTRIBUTE_GCC_PRECOMPILE_PREFIX_HEADER "YES") - endif(APPLE_IOS) - else (OGRE_STATIC) - if (CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") - # disable "lib" prefix on Unix - set_target_properties(${PLUGINNAME} PROPERTIES PREFIX "") - endif (CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") - endif (OGRE_STATIC) - - ogre_install_plugin(${PLUGINNAME}) - - if (OGRE_INSTALL_PDB) - # install debug pdb files - if (OGRE_STATIC) - install(FILES ${PROJECT_BINARY_DIR}/lib${OGRE_LIB_DEBUG_PATH}/${PLUGINNAME}Static_d.pdb - DESTINATION ${OGRE_LIB_DIRECTORY}${OGRE_LIB_DEBUG_PATH}/opt - CONFIGURATIONS Debug - ) - install(FILES ${PROJECT_BINARY_DIR}/lib${OGRE_LIB_RELWDBG_PATH}/${PLUGINNAME}Static.pdb - DESTINATION ${OGRE_LIB_DIRECTORY}${OGRE_LIB_RELWDBG_PATH}/opt - CONFIGURATIONS RelWithDebInfo - ) - else () - ogre_produces_pdb(PRODUCES_PDB ${PLUGINNAME}) - if(PRODUCES_PDB) - install(FILES $ - DESTINATION bin${OGRE_DEBUG_PATH} - CONFIGURATIONS Debug - ) - install(FILES $ - DESTINATION bin${OGRE_RELWDBG_PATH} - CONFIGURATIONS RelWithDebInfo - ) - endif () - endif () - endif () -endfunction(ogre_config_plugin) - -# setup Ogre sample build -function(ogre_config_sample_common SAMPLENAME) - ogre_config_common(${SAMPLENAME}) - - if (OGRE_PROJECT_FOLDERS) - set_property(TARGET ${LIBNAME} PROPERTY FOLDER Samples) - endif () - - if (APPLE) - # On OS X, create .app bundle - set_property(TARGET ${SAMPLENAME} PROPERTY MACOSX_BUNDLE TRUE) - if (NOT APPLE_IOS) - # Add the path where the Ogre framework was found - if(${OGRE_FRAMEWORK_PATH}) - set_target_properties(${SAMPLENAME} PROPERTIES - COMPILE_FLAGS "-F${OGRE_FRAMEWORK_PATH}" - LINK_FLAGS "-F${OGRE_FRAMEWORK_PATH}" - ) - endif() - endif() - endif (APPLE) - if (NOT OGRE_STATIC) - if (CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") - # disable "lib" prefix on Unix - set_target_properties(${SAMPLENAME} PROPERTIES PREFIX "") - endif (CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") - endif() - - if (NOT WIN32) - set_target_properties(${SAMPLENAME} PROPERTIES VERSION ${OGRE_SOVERSION} SOVERSION ${OGRE_SOVERSION}) - endif() - - if (OGRE_INSTALL_SAMPLES AND NOT OGRE_STATIC) - ogre_install_target(${SAMPLENAME} ${OGRE_SAMPLE_PATH} FALSE) - endif() - -endfunction(ogre_config_sample_common) - -function(ogre_config_sample_exe SAMPLENAME) - ogre_config_sample_common(${SAMPLENAME}) - if (OGRE_INSTALL_PDB AND OGRE_INSTALL_SAMPLES) - # install debug pdb files - no _d on exe - install(FILES $ - DESTINATION bin${OGRE_DEBUG_PATH} - CONFIGURATIONS Debug - ) - install(FILES $ - DESTINATION bin${OGRE_RELWDBG_PATH} - CONFIGURATIONS RelWithDebInfo - ) - endif () -endfunction(ogre_config_sample_exe) - -function(ogre_config_sample_lib SAMPLENAME) - ogre_config_sample_common(${SAMPLENAME}) - if (OGRE_INSTALL_PDB AND OGRE_INSTALL_SAMPLES) - # install debug pdb files - with a _d on lib - ogre_produces_pdb(PRODUCES_PDB ${SAMPLENAME}) - if (PRODUCES_PDB) - install(FILES $ - DESTINATION bin${OGRE_DEBUG_PATH} - CONFIGURATIONS Debug - ) - install(FILES $ - DESTINATION bin${OGRE_RELWDBG_PATH} - CONFIGURATIONS RelWithDebInfo - ) - endif () - endif () - - if(NOT OGRE_STATIC AND (CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")) - # add GCC visibility flags to shared library build - set_target_properties(${SAMPLENAME} PROPERTIES COMPILE_FLAGS "${OGRE_VISIBILITY_FLAGS}") - endif() - - # Add sample to the list of link targets - # Global property so that we can build this up across entire sample tree - # since vars are local to containing scope of directories / functions - get_property(OGRE_SAMPLES_LIST GLOBAL PROPERTY "OGRE_SAMPLES_LIST") - set_property (GLOBAL PROPERTY "OGRE_SAMPLES_LIST" ${OGRE_SAMPLES_LIST} ${SAMPLENAME}) - -endfunction(ogre_config_sample_lib) - - -# setup Ogre tool build -function(ogre_config_tool TOOLNAME) - ogre_config_common(${TOOLNAME}) - - #set _d debug postfix - if (WIN32) - set_property(TARGET ${TOOLNAME} APPEND PROPERTY DEBUG_POSTFIX "_d") - endif () - - if (OGRE_INSTALL_TOOLS) - ogre_install_target(${TOOLNAME} "" FALSE) - if (OGRE_INSTALL_PDB) - # install debug pdb files - install(FILES $ - DESTINATION bin${OGRE_DEBUG_PATH} - CONFIGURATIONS Debug - ) - install(FILES $ - DESTINATION bin${OGRE_RELWDBG_PATH} - CONFIGURATIONS RelWithDebInfo - ) - endif () - endif () - -endfunction(ogre_config_tool) diff --git a/CMake/Utils/OgreFindFrameworks.cmake b/CMake/Utils/OgreFindFrameworks.cmake deleted file mode 100644 index a8052d305bf..00000000000 --- a/CMake/Utils/OgreFindFrameworks.cmake +++ /dev/null @@ -1,35 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# - helper module to find OSX frameworks -# Adapted from standard CMake version, but added dependencies -# Standard finder does not look in any variable locations such as -# CMAKE_FRAMEWORK_PATH (not sure why not) - -IF(NOT OGRE_FIND_FRAMEWORKS_INCLUDED) - SET(OGRE_FIND_FRAMEWORKS_INCLUDED 1) - MACRO(OGRE_FIND_FRAMEWORKS fwk) - IF(APPLE) - SET(${fwk}_FRAMEWORKS) - SET(OGRE_FRAMEWORK_PATH - ${OGRE_DEPENDENCIES_DIR} - ~/Library/Frameworks - /Library/Frameworks - /System/Library/Frameworks - /Network/Library/Frameworks - ) - FOREACH(dir ${OGRE_FRAMEWORK_PATH}) - SET(fwkpath ${dir}/${fwk}.framework) - IF(EXISTS ${fwkpath}) - SET(${fwk}_FRAMEWORKS ${${fwk}_FRAMEWORKS} ${fwkpath}) - ENDIF(EXISTS ${fwkpath}) - ENDFOREACH(dir) - ENDIF(APPLE) - ENDMACRO(OGRE_FIND_FRAMEWORKS) -ENDIF(NOT OGRE_FIND_FRAMEWORKS_INCLUDED) diff --git a/CMake/Utils/PrecompiledHeader.cmake b/CMake/Utils/PrecompiledHeader.cmake deleted file mode 100644 index 799741e0125..00000000000 --- a/CMake/Utils/PrecompiledHeader.cmake +++ /dev/null @@ -1,399 +0,0 @@ -# taken from http://public.kitware.com/Bug/view.php?id=1260 and slightly adjusted - -# - Try to find precompiled headers support for GCC 3.4 and 4.x -# Once done this will define: -# -# Variable: -# PCHSupport_FOUND -# -# Macro: -# ADD_PRECOMPILED_HEADER _targetName _input _dowarn -# ADD_PRECOMPILED_HEADER_TO_TARGET _targetName _input _pch_output_to_use _dowarn -# ADD_NATIVE_PRECOMPILED_HEADER _targetName _input _dowarn -# GET_NATIVE_PRECOMPILED_HEADER _targetName _input - -IF(CMAKE_COMPILER_IS_GNUCXX) - - IF(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS "4.2.0") - SET(PCHSupport_FOUND TRUE) - ENDIF() - - SET(_PCH_include_prefix "-I") - SET(_PCH_isystem_prefix "-isystem") - SET(_PCH_define_prefix "-D") - -ELSEIF(CMAKE_GENERATOR MATCHES "^Visual.*$") - SET(PCHSupport_FOUND TRUE) - SET(_PCH_include_prefix "/I") - SET(_PCH_isystem_prefix "/I") - SET(_PCH_define_prefix "/D") -ELSE() - SET(PCHSupport_FOUND FALSE) -ENDIF() - -MACRO(_PCH_GET_COMPILE_FLAGS _out_compile_flags) - - STRING(TOUPPER "CMAKE_CXX_FLAGS_${CMAKE_BUILD_TYPE}" _flags_var_name) - SET(${_out_compile_flags} ${${_flags_var_name}} ) - - IF(CMAKE_COMPILER_IS_GNUCXX) - - GET_TARGET_PROPERTY(_targetType ${_PCH_current_target} TYPE) - IF(${_targetType} STREQUAL SHARED_LIBRARY AND NOT WIN32) - LIST(APPEND ${_out_compile_flags} "-fPIC") - ENDIF() - - GET_PROPERTY(_definitions DIRECTORY PROPERTY COMPILE_DEFINITIONS) - if(_definitions) - foreach(_def ${_definitions}) - LIST(APPEND ${_out_compile_flags} "\"-D${_def}\"") - endforeach() - endif() - GET_TARGET_PROPERTY(_target_definitions ${_PCH_current_target} COMPILE_DEFINITIONS) - if(_target_definitions) - foreach(_def ${_target_definitions}) - LIST(APPEND ${_out_compile_flags} "\"-D${_def}\"") - endforeach() - endif() - - GET_TARGET_PROPERTY(_cxx_standard ${_PCH_current_target} CXX_STANDARD) - if (_cxx_standard) - GET_TARGET_PROPERTY(_cxx_extensions ${_PCH_current_target} CXX_EXTENSIONS) - if (_cxx_extensions) - LIST(APPEND ${_out_compile_flags} "${CMAKE_CXX${_cxx_standard}_EXTENSION_COMPILE_OPTION}") - else() - LIST(APPEND ${_out_compile_flags} "${CMAKE_CXX${_cxx_standard}_STANDARD_COMPILE_OPTION}") - endif() - endif() - - GET_TARGET_PROPERTY(_visibility ${_PCH_current_target} CXX_VISIBILITY_PRESET) - if (_visibility AND ${_targetType} STREQUAL SHARED_LIBRARY) - LIST(APPEND ${_out_compile_flags} "-D${_PCH_current_target}_EXPORTS") - endif() - ELSE() - ## TODO ... ? or does it work out of the box - ENDIF() - - GET_DIRECTORY_PROPERTY(DIRINC INCLUDE_DIRECTORIES ) - FOREACH(item ${DIRINC}) - if(CMAKE_COMPILER_IS_GNUCXX AND NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS "6.0" AND - item MATCHES "/usr/include$") - # workaround for GCC 6.x bug - else() - LIST(APPEND ${_out_compile_flags} "${_PCH_isystem_prefix} \"${item}\"") - endif() - ENDFOREACH(item) - - get_target_property(DIRINC ${_PCH_current_target} INCLUDE_DIRECTORIES ) - FOREACH(item ${DIRINC}) - if(CMAKE_COMPILER_IS_GNUCXX AND NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS "6.0" AND - item MATCHES "/usr/include$") - # workaround for GCC 6.x bug - else() - LIST(APPEND ${_out_compile_flags} "${_PCH_isystem_prefix} \"${item}\"") - endif() - ENDFOREACH(item) - - LIST(APPEND ${_out_compile_flags} ${CMAKE_CXX_FLAGS}) - - SEPARATE_ARGUMENTS(${_out_compile_flags}) - -ENDMACRO(_PCH_GET_COMPILE_FLAGS) - - -MACRO(_PCH_WRITE_PCHDEP_CXX _targetName _include_file _dephelp) - - set(${_dephelp} "${CMAKE_CURRENT_BINARY_DIR}/${_targetName}_pch_dephelp.cxx") - set(_content "") - if(EXISTS "${${_dephelp}}") - file(READ "${${_dephelp}}" _content) - endif() - set(_dummy_str -"#include \"${_include_file}\" -int testfunction(); -int testfunction() -{ - return 0; -} -") - if(NOT _content STREQUAL _dummy_str) - file(WRITE "${${_dephelp}}" "${_dummy_str}") - endif() - -ENDMACRO(_PCH_WRITE_PCHDEP_CXX ) - -MACRO(_PCH_GET_COMPILE_COMMAND out_command _input _output) - - FILE(TO_NATIVE_PATH ${_input} _native_input) - FILE(TO_NATIVE_PATH ${_output} _native_output) - - IF(CMAKE_COMPILER_IS_GNUCXX) - IF(CMAKE_CXX_COMPILER_ARG1) - # remove leading space in compiler argument - STRING(REGEX REPLACE "^ +" "" pchsupport_compiler_cxx_arg1 ${CMAKE_CXX_COMPILER_ARG1}) - - SET(${out_command} - ${CMAKE_CXX_COMPILER} ${pchsupport_compiler_cxx_arg1} ${_compile_FLAGS} -x c++-header -c -o ${_output} ${_input} - ) - ELSE(CMAKE_CXX_COMPILER_ARG1) - SET(${out_command} - ${CMAKE_CXX_COMPILER} ${_compile_FLAGS} -x c++-header -c -o ${_output} ${_input} - ) - ENDIF(CMAKE_CXX_COMPILER_ARG1) - ELSE(CMAKE_COMPILER_IS_GNUCXX) - - SET(_dummy_str "#include <${_input}>") - FILE(WRITE ${CMAKE_CURRENT_BINARY_DIR}/pch_dummy.cpp ${_dummy_str}) - - SET(${out_command} - ${CMAKE_CXX_COMPILER} ${_compile_FLAGS} /c /Fp${_native_output} /Yc${_native_input} pch_dummy.cpp - ) - #/out:${_output} - - ENDIF(CMAKE_COMPILER_IS_GNUCXX) - -ENDMACRO(_PCH_GET_COMPILE_COMMAND ) - - -MACRO(_PCH_GET_TARGET_COMPILE_FLAGS _cflags _header_name _pch_path _dowarn ) - - FILE(TO_NATIVE_PATH ${_pch_path} _native_pch_path) - - IF(CMAKE_COMPILER_IS_GNUCXX) - # for use with distcc and gcc >4.0.1 if preprocessed files are accessible - # on all remote machines set - # PCH_ADDITIONAL_COMPILER_FLAGS to -fpch-preprocess - # if you want warnings for invalid header files (which is very inconvenient - # if you have different versions of the headers for different build types - # you may set _pch_dowarn - IF (_dowarn) - SET(${_cflags} "${PCH_ADDITIONAL_COMPILER_FLAGS} -Winvalid-pch " ) - ELSE (_dowarn) - SET(${_cflags} "${PCH_ADDITIONAL_COMPILER_FLAGS} " ) - ENDIF (_dowarn) - - ELSE(CMAKE_COMPILER_IS_GNUCXX) - - set(${_cflags} "/Fp${_native_pch_path} /Yu${_header_name}" ) - - ENDIF(CMAKE_COMPILER_IS_GNUCXX) - -ENDMACRO(_PCH_GET_TARGET_COMPILE_FLAGS ) - - -MACRO(GET_PRECOMPILED_HEADER_OUTPUT _targetName _input _output) - - GET_FILENAME_COMPONENT(_name ${_input} NAME) - GET_FILENAME_COMPONENT(_path ${_input} PATH) - SET(${_output} "${CMAKE_CURRENT_BINARY_DIR}/${_name}.gch/${_targetName}_${CMAKE_BUILD_TYPE}.gch") - -ENDMACRO(GET_PRECOMPILED_HEADER_OUTPUT _targetName _input) - - -MACRO(ADD_PRECOMPILED_HEADER_TO_TARGET _targetName _input _pch_output_to_use ) - - # to do: test whether compiler flags match between target _targetName - # and _pch_output_to_use - GET_FILENAME_COMPONENT(_name ${_input} NAME) - - IF(ARGN STREQUAL "0") - SET(_dowarn 0) - ELSE() - SET(_dowarn 1) - ENDIF() - - _PCH_GET_TARGET_COMPILE_FLAGS(_target_cflags ${_name} ${_pch_output_to_use} ${_dowarn}) - #MESSAGE("Add flags ${_target_cflags} to ${_targetName} " ) - if(CMAKE_COMPILER_IS_GNUCXX) - set(_target_cflags "${_target_cflags} -include \"${CMAKE_CURRENT_BINARY_DIR}/${_name}\"") - endif() - - GET_TARGET_PROPERTY(_sources ${_targetName} SOURCES) - FOREACH(src ${_sources}) - if(NOT "${src}" MATCHES "\\.mm$") - get_source_file_property(_flags "${src}" COMPILE_FLAGS) - get_source_file_property(_flags2 "${src}" COMPILE_DEFINITIONS) - if(NOT _flags AND NOT _flags2) - set_source_files_properties("${src}" PROPERTIES COMPILE_FLAGS "${_target_cflags}") - else() - #ocv_debug_message("Skip PCH, flags: ${oldProps} defines: ${oldProps2}, file: ${src}") - endif() - endif() - ENDFOREACH() - - ADD_CUSTOM_TARGET(pch_Generate_${_targetName} - DEPENDS ${_pch_output_to_use} - ) - - ADD_DEPENDENCIES(${_targetName} pch_Generate_${_targetName} ) - -ENDMACRO(ADD_PRECOMPILED_HEADER_TO_TARGET) - -MACRO(ADD_PRECOMPILED_HEADER _targetName _input) - - SET(_PCH_current_target ${_targetName}) - - IF(NOT CMAKE_BUILD_TYPE) - MESSAGE(FATAL_ERROR - "This is the ADD_PRECOMPILED_HEADER macro. " - "You must set CMAKE_BUILD_TYPE!" - ) - ENDIF() - - IF(ARGN STREQUAL "0") - SET(_dowarn 0) - ELSE() - SET(_dowarn 1) - ENDIF() - - GET_FILENAME_COMPONENT(_name ${_input} NAME) - GET_FILENAME_COMPONENT(_path ${_input} PATH) - GET_PRECOMPILED_HEADER_OUTPUT( ${_targetName} ${_input} _output) - - _PCH_WRITE_PCHDEP_CXX(${_targetName} "${_input}" _pch_dephelp_cxx) - - ADD_LIBRARY(${_targetName}_pch_dephelp STATIC "${_pch_dephelp_cxx}" "${_input}" ) - - set_target_properties(${_targetName}_pch_dephelp PROPERTIES - DEBUG_POSTFIX "${OPENCV_DEBUG_POSTFIX}" - ARCHIVE_OUTPUT_DIRECTORY "${LIBRARY_OUTPUT_PATH}" - ) - - _PCH_GET_COMPILE_FLAGS(_compile_FLAGS) - - get_target_property(type ${_targetName} TYPE) - if(type STREQUAL "SHARED_LIBRARY") - get_target_property(__DEFINES ${_targetName} DEFINE_SYMBOL) - if(NOT __DEFINES MATCHES __DEFINES-NOTFOUND) - list(APPEND _compile_FLAGS "${_PCH_define_prefix}${__DEFINES}") - endif() - endif() - - if(type STREQUAL "SHARED_LIBRARY" OR type STREQUAL "STATIC_LIBRARY") - get_target_property(__pic ${_targetName} POSITION_INDEPENDENT_CODE) - if(__pic AND CMAKE_CXX_COMPILE_OPTIONS_PIC - AND NOT OPENCV_SKIP_PCH_PIC_HANDLING - AND NOT OPENCV_SKIP_PCH_PIC_HANDLING_${_targetName} - ) - list(APPEND _compile_FLAGS "${CMAKE_CXX_COMPILE_OPTIONS_PIC}") - endif() - elseif(type STREQUAL "EXECUTABLE") - get_target_property(__pie ${_targetName} POSITION_INDEPENDENT_CODE) - if(__pie AND CMAKE_CXX_COMPILE_OPTIONS_PIE - AND NOT OPENCV_SKIP_PCH_PIE_HANDLING - AND NOT OPENCV_SKIP_PCH_PIE_HANDLING_${_targetName} - ) - list(APPEND _compile_FLAGS "${CMAKE_CXX_COMPILE_OPTIONS_PIE}") - endif() - endif() - - get_target_property(DIRINC ${_targetName} INCLUDE_DIRECTORIES) - set_target_properties(${_targetName}_pch_dephelp PROPERTIES INCLUDE_DIRECTORIES "${DIRINC}") - - #MESSAGE("_compile_FLAGS: ${_compile_FLAGS}") - #message("COMMAND ${CMAKE_CXX_COMPILER} ${_compile_FLAGS} -x c++-header -c -o ${_output} ${_input}") - - ADD_CUSTOM_COMMAND( - OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${_name}" - COMMAND ${CMAKE_COMMAND} -E copy_if_different "${_input}" "${CMAKE_CURRENT_BINARY_DIR}/${_name}" # ensure same directory! Required by gcc - DEPENDS "${_input}" - ) - - #message("_command ${_input} ${_output}") - _PCH_GET_COMPILE_COMMAND(_command ${CMAKE_CURRENT_BINARY_DIR}/${_name} ${_output} ) - - GET_FILENAME_COMPONENT(_outdir ${_output} PATH) - ADD_CUSTOM_COMMAND( - OUTPUT "${_output}" - COMMAND ${CMAKE_COMMAND} -E make_directory "${_outdir}" - COMMAND ${_command} - DEPENDS "${_input}" - DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/${_name}" - DEPENDS ${_targetName}_pch_dephelp - ) - - ADD_PRECOMPILED_HEADER_TO_TARGET(${_targetName} ${_input} ${_output} ${_dowarn}) - -ENDMACRO(ADD_PRECOMPILED_HEADER) - - -# Generates the use of precompiled in a target, -# without using depency targets (2 extra for each target) -# Using Visual, must also add ${_targetName}_pch to sources -# Not needed by Xcode - -MACRO(GET_NATIVE_PRECOMPILED_HEADER _targetName) - if(CMAKE_GENERATOR MATCHES "^Visual.*$" AND CMAKE_VERSION LESS "3.16") - set(${_targetName}_pch ${CMAKE_CURRENT_BINARY_DIR}/${_targetName}_pch.cpp) - endif() -ENDMACRO(GET_NATIVE_PRECOMPILED_HEADER) - - -MACRO(ADD_NATIVE_PRECOMPILED_HEADER _targetName _input) - - IF(ARGN STREQUAL "0") - SET(_dowarn 0) - ELSE() - SET(_dowarn 1) - ENDIF() - - if(NOT OGRE_ENABLE_PRECOMPILED_HEADERS) - # do nothing - elseif(NOT CMAKE_VERSION VERSION_LESS "3.16") - target_precompile_headers(${_targetName} PRIVATE ${_input}) - elseif(CMAKE_GENERATOR MATCHES "^Visual.*$") - - # Auto include the precompile (useful for moc processing, since the use of - # precompiled is specified at the target level - # and I don't want to specifiy /F- for each moc/res/ui generated files (using Qt) - - get_target_property(_sources ${_targetName} SOURCES) - foreach(src ${_sources}) - if("${src}" MATCHES "\\.c(pp|xx)?$") - get_source_file_property(oldProps "${src}" COMPILE_FLAGS) - get_source_file_property(oldProps2 "${src}" COMPILE_DEFINITIONS) - if(NOT oldProps AND NOT oldProps2) - set(newProperties "/Yu\"${_input}\" /FI\"${_input}\"") - set_source_files_properties("${src}" PROPERTIES COMPILE_FLAGS "${newProperties}") - else() - message(STATUS "Skip PCH, flags: ${oldProps} defines: ${oldProps2}, file: ${src}") - endif() - endif() - endforeach() - - #also inlude ${oldProps} to have the same compile options - GET_TARGET_PROPERTY(oldProps ${_targetName} COMPILE_FLAGS) - if (oldProps MATCHES NOTFOUND) - SET(oldProps "") - endif() - SET_SOURCE_FILES_PROPERTIES(${${_targetName}_pch} PROPERTIES COMPILE_FLAGS "${oldProps} /Yc\"${_input}\"") - - set(_dummy_str "#include \"${_input}\"\n") - set(${_targetName}_pch ${CMAKE_CURRENT_BINARY_DIR}/${_targetName}_pch.cpp) - if(EXISTS ${${_targetName}_pch}) - file(READ "${${_targetName}_pch}" _contents) - endif() - if(NOT _dummy_str STREQUAL "${_contents}") - file(WRITE ${${_targetName}_pch} ${_dummy_str}) - endif() - - elseif (CMAKE_GENERATOR MATCHES Xcode) - - # For Xcode, cmake needs my patch to process - # GCC_PREFIX_HEADER and GCC_PRECOMPILE_PREFIX_HEADER as target properties - - # When building out of the tree, precompiled may not be located - # Use full path instead. - GET_FILENAME_COMPONENT(fullPath ${_input} ABSOLUTE) - - SET_TARGET_PROPERTIES(${_targetName} PROPERTIES XCODE_ATTRIBUTE_GCC_PREFIX_HEADER "${fullPath}") - SET_TARGET_PROPERTIES(${_targetName} PROPERTIES XCODE_ATTRIBUTE_GCC_PRECOMPILE_PREFIX_HEADER "YES") - - elseif(CMAKE_COMPILER_IS_GNUCXX AND CMAKE_GENERATOR MATCHES "Makefiles|Ninja") - - #Fallback to the "old" precompiled suppport - ADD_PRECOMPILED_HEADER(${_targetName} ${_input}) - - endif() - -ENDMACRO(ADD_NATIVE_PRECOMPILED_HEADER) diff --git a/CMake/toolchain/ios.toolchain.xcode.cmake b/CMake/toolchain/ios.toolchain.xcode.cmake deleted file mode 100644 index c13b85226ed..00000000000 --- a/CMake/toolchain/ios.toolchain.xcode.cmake +++ /dev/null @@ -1,199 +0,0 @@ -# This file is based off of the Platform/Darwin.cmake and Platform/UnixPaths.cmake -# files which are included with CMake 2.8.4 -# It has been altered for iOS development - -# Options: -# -# IOS_PLATFORM = OS (default) or SIMULATOR -# This decides if SDKS will be selected from the iPhoneOS.platform or iPhoneSimulator.platform folders -# OS - the default, used to build for iPhone and iPad physical devices, which have an arm arch. -# SIMULATOR - used to build for the Simulator platforms, which have an x86 arch. -# -# CMAKE_IOS_DEVELOPER_ROOT = automatic(default) or /path/to/platform/Developer folder -# By default this location is automatcially chosen based on the IOS_PLATFORM value above. -# If set manually, it will override the default location and force the user of a particular Developer Platform -# -# CMAKE_IOS_SDK_ROOT = automatic(default) or /path/to/platform/Developer/SDKs/SDK folder -# By default this location is automatcially chosen based on the CMAKE_IOS_DEVELOPER_ROOT value. -# In this case it will always be the most up-to-date SDK found in the CMAKE_IOS_DEVELOPER_ROOT path. -# If set manually, this will force the use of a specific SDK version - -# Macros: -# -# set_xcode_property (TARGET XCODE_PROPERTY XCODE_VALUE) -# A convenience macro for setting xcode specific properties on targets -# example: set_xcode_property (myioslib IPHONEOS_DEPLOYMENT_TARGET "3.1") -# -# find_host_package (PROGRAM ARGS) -# A macro used to find executable programs on the host system, not within the iOS environment. -# Thanks to the android-cmake project for providing the command - -# Standard settings -set (CMAKE_SYSTEM_NAME Darwin) -set (CMAKE_SYSTEM_VERSION 1) -set (UNIX True) -set (APPLE True) -set (IOS True) -set (APPLE_IOS True) - -# make sure all executables are bundles otherwise try compiles will fail -set (CMAKE_MACOSX_BUNDLE True) -set (CMAKE_XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "iPhone Developer" CACHE STRING "how to sign executables") - -# Required as of cmake 2.8.10 -set (CMAKE_OSX_DEPLOYMENT_TARGET "" CACHE STRING "Force unset of the deployment target for iOS" FORCE) - -# Determine the cmake host system version so we know where to find the iOS SDKs -find_program (CMAKE_UNAME uname /bin /usr/bin /usr/local/bin) -if (CMAKE_UNAME) - exec_program(uname ARGS -r OUTPUT_VARIABLE CMAKE_HOST_SYSTEM_VERSION) - string (REGEX REPLACE "^([0-9]+)\\.([0-9]+).*$" "\\1" DARWIN_MAJOR_VERSION "${CMAKE_HOST_SYSTEM_VERSION}") -endif () - -# Force the compilers for iOS -# deprecated with CMake 3.5. uncomment below if you use an older version. -# include (CMakeForceCompiler) -# CMAKE_FORCE_C_COMPILER (/usr/bin/clang Apple) -# CMAKE_FORCE_CXX_COMPILER (/usr/bin/clang++ Apple) -set(CMAKE_AR ar CACHE FILEPATH "" FORCE) - -# Skip the platform compiler checks for cross compiling -set (CMAKE_CXX_COMPILER_WORKS TRUE) -set (CMAKE_C_COMPILER_WORKS TRUE) - -# All iOS/Darwin specific settings - some may be redundant -set (CMAKE_SHARED_LIBRARY_PREFIX "lib") -set (CMAKE_SHARED_LIBRARY_SUFFIX ".dylib") -set (CMAKE_SHARED_MODULE_PREFIX "lib") -set (CMAKE_SHARED_MODULE_SUFFIX ".so") -set (CMAKE_MODULE_EXISTS 1) -set (CMAKE_DL_LIBS "") - -set (CMAKE_C_OSX_COMPATIBILITY_VERSION_FLAG "-compatibility_version ") -set (CMAKE_C_OSX_CURRENT_VERSION_FLAG "-current_version ") -set (CMAKE_CXX_OSX_COMPATIBILITY_VERSION_FLAG "${CMAKE_C_OSX_COMPATIBILITY_VERSION_FLAG}") -set (CMAKE_CXX_OSX_CURRENT_VERSION_FLAG "${CMAKE_C_OSX_CURRENT_VERSION_FLAG}") - -set (CMAKE_C_FLAGS_INIT "") - -set (CMAKE_C_LINK_FLAGS "-Wl,-search_paths_first ${CMAKE_C_LINK_FLAGS}") -set (CMAKE_CXX_LINK_FLAGS "-Wl,-search_paths_first ${CMAKE_CXX_LINK_FLAGS}") - -set (CMAKE_PLATFORM_HAS_INSTALLNAME 1) -set (CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS "-dynamiclib -headerpad_max_install_names") -set (CMAKE_SHARED_MODULE_CREATE_C_FLAGS "-bundle -headerpad_max_install_names") -set (CMAKE_SHARED_MODULE_LOADER_C_FLAG "-Wl,-bundle_loader,") -set (CMAKE_SHARED_MODULE_LOADER_CXX_FLAG "-Wl,-bundle_loader,") -set (CMAKE_FIND_LIBRARY_SUFFIXES ".dylib" ".so" ".a") - -# hack: if a new cmake (which uses CMAKE_INSTALL_NAME_TOOL) runs on an old build tree -# (where install_name_tool was hardcoded) and where CMAKE_INSTALL_NAME_TOOL isn't in the cache -# and still cmake didn't fail in CMakeFindBinUtils.cmake (because it isn't rerun) -# hardcode CMAKE_INSTALL_NAME_TOOL here to install_name_tool, so it behaves as it did before, Alex -if (NOT DEFINED CMAKE_INSTALL_NAME_TOOL) - find_program(CMAKE_INSTALL_NAME_TOOL install_name_tool) -endif () - -# Setup iOS platform unless specified manually with IOS_PLATFORM -if (NOT DEFINED IOS_PLATFORM) - set (IOS_PLATFORM "OS") -endif () -set (IOS_PLATFORM ${IOS_PLATFORM} CACHE STRING "Type of iOS Platform") - -# Check the platform selection and setup for developer root -if (${IOS_PLATFORM} STREQUAL "OS") - set (IOS_PLATFORM_LOCATION "iPhoneOS.platform") - - # This causes the installers to properly locate the output libraries - set (CMAKE_XCODE_EFFECTIVE_PLATFORMS "-iphoneos") -elseif (${IOS_PLATFORM} STREQUAL "SIMULATOR") - set (IOS_PLATFORM_LOCATION "iPhoneSimulator.platform") - - # This causes the installers to properly locate the output libraries - set (CMAKE_XCODE_EFFECTIVE_PLATFORMS "-iphonesimulator") -else () - message (FATAL_ERROR "Unsupported IOS_PLATFORM value selected. Please choose OS or SIMULATOR") -endif () - -# Setup iOS developer location unless specified manually with CMAKE_IOS_DEVELOPER_ROOT -# Note Xcode 4.3 changed the installation location, choose the most recent one available -set (XCODE_POST_43_ROOT "/Applications/Xcode.app/Contents/Developer/Platforms/${IOS_PLATFORM_LOCATION}/Developer") -set (XCODE_PRE_43_ROOT "/Developer/Platforms/${IOS_PLATFORM_LOCATION}/Developer") -if (NOT DEFINED CMAKE_IOS_DEVELOPER_ROOT) - if (EXISTS ${XCODE_POST_43_ROOT}) - set (CMAKE_IOS_DEVELOPER_ROOT ${XCODE_POST_43_ROOT}) - elseif(EXISTS ${XCODE_PRE_43_ROOT}) - set (CMAKE_IOS_DEVELOPER_ROOT ${XCODE_PRE_43_ROOT}) - endif () -endif () -set (CMAKE_IOS_DEVELOPER_ROOT ${CMAKE_IOS_DEVELOPER_ROOT} CACHE PATH "Location of iOS Platform") - -# Find and use the most recent iOS sdk unless specified manually with CMAKE_IOS_SDK_ROOT -if (NOT DEFINED CMAKE_IOS_SDK_ROOT) - file (GLOB _CMAKE_IOS_SDKS "${CMAKE_IOS_DEVELOPER_ROOT}/SDKs/*") - if (_CMAKE_IOS_SDKS) - list (SORT _CMAKE_IOS_SDKS) - list (REVERSE _CMAKE_IOS_SDKS) - list (GET _CMAKE_IOS_SDKS 0 CMAKE_IOS_SDK_ROOT) - else () - message (FATAL_ERROR "No iOS SDK's found in default search path ${CMAKE_IOS_DEVELOPER_ROOT}. Manually set CMAKE_IOS_SDK_ROOT or install the iOS SDK.") - endif () - message (STATUS "Toolchain using default iOS SDK: ${CMAKE_IOS_SDK_ROOT}") -endif () -set (CMAKE_IOS_SDK_ROOT ${CMAKE_IOS_SDK_ROOT} CACHE PATH "Location of the selected iOS SDK") - -# Set the sysroot default to the most recent SDK -set (CMAKE_OSX_SYSROOT ${CMAKE_IOS_SDK_ROOT} CACHE PATH "Sysroot used for iOS support") - -# Hidden visibilty is required for cxx on iOS -set (CMAKE_CXX_FLAGS_INIT "-fvisibility=hidden -fvisibility-inlines-hidden -isysroot ${CMAKE_OSX_SYSROOT}") - -# set the architecture for iOS -# NOTE: Currently both ARCHS_STANDARD_32_BIT and ARCHS_UNIVERSAL_IPHONE_OS set armv7 only, so set both manually -if (${IOS_PLATFORM} STREQUAL "OS") - set (IOS_ARCH armv7 arm64) -else () - set (IOS_ARCH x86_64) -endif () - -set (CMAKE_OSX_ARCHITECTURES ${IOS_ARCH} CACHE STRING "Build architecture for iOS") - -# Set the find root to the iOS developer roots and to user defined paths -set (CMAKE_FIND_ROOT_PATH ${CMAKE_IOS_DEVELOPER_ROOT} ${CMAKE_IOS_SDK_ROOT} ${CMAKE_PREFIX_PATH} CACHE STRING "iOS find search path root") - -# default to searching for frameworks first -set (CMAKE_FIND_FRAMEWORK FIRST) - -# set up the default search directories for frameworks -set (CMAKE_SYSTEM_FRAMEWORK_PATH - ${CMAKE_IOS_SDK_ROOT}/System/Library/Frameworks - ${CMAKE_IOS_SDK_ROOT}/System/Library/PrivateFrameworks - ${CMAKE_IOS_SDK_ROOT}/Developer/Library/Frameworks -) - -# only search the iOS sdks, not the remainder of the host filesystem -set (CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY) -set (CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) -set (CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) - - -# This little macro lets you set any XCode specific property -macro (set_xcode_property TARGET XCODE_PROPERTY XCODE_VALUE) - set_property (TARGET ${TARGET} PROPERTY XCODE_ATTRIBUTE_${XCODE_PROPERTY} ${XCODE_VALUE}) -endmacro () - - -# This macro lets you find executable programs on the host system -macro (find_host_package) - set (CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) - set (CMAKE_FIND_ROOT_PATH_MODE_LIBRARY NEVER) - set (CMAKE_FIND_ROOT_PATH_MODE_INCLUDE NEVER) - set (IOS FALSE) - - find_package(${ARGN}) - - set (IOS TRUE) - set (CMAKE_FIND_ROOT_PATH_MODE_PROGRAM ONLY) - set (CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) - set (CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) -endmacro () diff --git a/CMakeLists.txt b/CMakeLists.txt deleted file mode 100644 index 4392af57791..00000000000 --- a/CMakeLists.txt +++ /dev/null @@ -1,495 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -###################################################################### -# OGRE BUILD SYSTEM -# Welcome to the CMake build system for OGRE. -# This is the main file where we prepare the general build environment -# and provide build configuration options. -###################################################################### - -cmake_minimum_required(VERSION 3.13.0) - -set(CMAKE_CXX_STANDARD 14) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) - -if(CMAKE_VS_PLATFORM_NAME STREQUAL "Tegra-Android") - set(CMAKE_LINK_LIBRARY_FLAG "") -endif() - -# Use relative paths -# This is mostly to reduce path size for command-line limits on windows -if(WIN32) - # This seems to break Xcode projects so definitely don't enable on Apple builds - set(CMAKE_USE_RELATIVE_PATHS true) - set(CMAKE_SUPPRESS_REGENERATION true) -endif() - -# prefer GLVND -if(POLICY CMP0072) - cmake_policy(SET CMP0072 NEW) -endif() -if(POLICY CMP0078) - cmake_policy(SET CMP0078 NEW) -endif() -if(POLICY CMP0086) - cmake_policy(SET CMP0086 NEW) -endif() - -if (APPLE AND NOT ANDROID AND NOT EMSCRIPTEN) - SET(CMAKE_SIZEOF_VOID_P 4) - - if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.16.0") - enable_language(OBJC) - enable_language(OBJCXX) - endif() - - if(POLICY CMP0068) - cmake_policy(SET CMP0068 NEW) # CMake 3.9+: `RPATH` settings on macOS do not affect `install_name`. - endif() - - if (NOT CMAKE_OSX_ARCHITECTURES) - set(CMAKE_OSX_ARCHITECTURES "x86_64" CACHE STRING "") # target the common case - endif() - - # otherwise apple defines a macro named check that conflicts with boost - add_definitions(-D__ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES=0) -endif () - -project(OGRE VERSION 14.2.0) - -# extra version info -set(OGRE_VERSION_SUFFIX "") -set(OGRE_VERSION_NAME "Tsathoggua") - -# legacy defines -set(OGRE_SOVERSION ${OGRE_VERSION_MAJOR}.${OGRE_VERSION_MINOR}) -set(OGRE_VERSION_DASH_SEPARATED "${OGRE_VERSION_MAJOR}-${OGRE_VERSION_MINOR}-${OGRE_VERSION_PATCH}") - - -# Include necessary submodules -set(CMAKE_MODULE_PATH - "${PROJECT_SOURCE_DIR}/CMake" - "${PROJECT_SOURCE_DIR}/CMake/Utils" - "${PROJECT_SOURCE_DIR}/CMake/Packages" -) - -include(CMakeDependentOption) -include(MacroLogFeature) -include(OgreConfigTargets) -set(OGRE_TEMPLATES_DIR "${PROJECT_SOURCE_DIR}/CMake/Templates") -set(OGRE_WORK_DIR ${PROJECT_BINARY_DIR}) - - -##################################################################### -# Set up the basic build environment -##################################################################### - -if (NOT CMAKE_BUILD_TYPE) - # CMake defaults to leaving CMAKE_BUILD_TYPE empty. This screws up - # differentiation between debug and release builds. - set(CMAKE_BUILD_TYPE "RelWithDebInfo" CACHE STRING "Choose the type of build, options are: None (CMAKE_CXX_FLAGS or CMAKE_C_FLAGS used) Debug Release RelWithDebInfo MinSizeRel." FORCE) -endif () - -# determine Ogre version numbers -message(STATUS "Configuring OGRE ${OGRE_VERSION}") -# Configure version file for use by scripts -configure_file("${OGRE_TEMPLATES_DIR}/version.txt.in" "${PROJECT_BINARY_DIR}/version.txt" @ONLY) - -# determine if we are compiling for a 32bit or 64bit system -include(CheckTypeSize) -CHECK_TYPE_SIZE("void*" OGRE_PTR_SIZE BUILTIN_TYPES_ONLY) -if (OGRE_PTR_SIZE EQUAL 8) - set(OGRE_PLATFORM_X64 TRUE) -else () - set(OGRE_PLATFORM_X64 FALSE) -endif () - -if (WIN32) - # Create debug libraries with _d postfix - set(CMAKE_DEBUG_POSTFIX "_d") -endif () - -# Set compiler specific build flags -if (NOT ANDROID AND NOT EMSCRIPTEN AND UNIX OR MINGW) - if (CMAKE_SYSTEM_PROCESSOR MATCHES "x86|X86|amd64|AMD64") - include(CheckCXXCompilerFlag) - check_cxx_compiler_flag(-msse OGRE_GCC_HAS_SSE) - if (OGRE_GCC_HAS_SSE) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse") - endif () - endif() -endif() - -if(UNIX) - # This is a set of sensible warnings that provide meaningful output - set(OGRE_WARNING_FLAGS "-Wall -Winit-self -Wcast-qual -Wwrite-strings -Wextra -Wundef -Wmissing-declarations -Wno-unused-parameter -Wshadow -Wno-missing-field-initializers -Wno-long-long") - if (EMSCRIPTEN) - set(OGRE_WARNING_FLAGS "${OGRE_WARNING_FLAGS} -Wno-warn-absolute-paths") - endif () - if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") - set(OGRE_WARNING_FLAGS "${OGRE_WARNING_FLAGS} -Wno-missing-braces") - else() - set(OGRE_WARNING_FLAGS "${OGRE_WARNING_FLAGS} -Wsuggest-override") - endif() - set(CMAKE_CXX_FLAGS "${OGRE_WARNING_FLAGS} ${CMAKE_CXX_FLAGS}") -endif () -if (MSVC) - add_definitions(-D_MT -D_USRDLL) - # MSVC does not like Ogre::Singleton (header pragma is enough for MSVC2015+ though) - add_definitions(/wd4661) - if (CMAKE_BUILD_TOOL STREQUAL "nmake") - # set variable to state that we are using nmake makefiles - set(NMAKE TRUE) - endif () - - # Enable intrinsics on MSVC in debug mode - set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /Oi") - if (MSVC AND CMAKE_SIZEOF_VOID_P EQUAL 8) - # Visual Studio bails out on debug builds in 64bit mode unless - # this flag is set... - set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /bigobj") - set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} /bigobj") - endif () - - if (OGRE_PROJECT_FOLDERS) - # Turn on the ability to create folders to organize projects (.vcproj) - # It creates "CMakePredefinedTargets" folder by default and adds CMake - # defined projects like INSTALL.vcproj and ZERO_CHECK.vcproj - set_property(GLOBAL PROPERTY USE_FOLDERS ON) - endif() - - option(OGRE_BUILD_MSVC_MP "Enable build with multiple processes in Visual Studio" TRUE) - if(OGRE_BUILD_MSVC_MP) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP") - endif () - option(OGRE_BUILD_MSVC_ZM "Add /Zm256 compiler option to fix PCH errors on Visual Studio 2013" TRUE) - if(OGRE_BUILD_MSVC_ZM) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /Zm256") - endif () -endif () -if (MINGW) - add_definitions(-D_WIN32_WINNT=0x0501) - if( CMAKE_SIZEOF_VOID_P EQUAL 4 ) - # set architecture to i686, since otherwise some versions of MinGW can't link - # the atomic primitives - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=i686") - endif () - # disable this optimisation because it breaks release builds (reason unknown) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-tree-slp-vectorize") - # Ignore some really annoying warnings which also happen in dependencies - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error=cast-qual -Wno-unused-local-typedefs") -endif () - -include(GenerateExportHeader) -set(CMAKE_CXX_VISIBILITY_PRESET hidden) -set(CMAKE_VISIBILITY_INLINES_HIDDEN TRUE) - -if((CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU") AND NOT OGRE_STATIC) - set(OGRE_VISIBILITY_FLAGS "-DOGRE_GCC_VISIBILITY") # for legacy headers -endif() - -# determine system endianess -if (MSVC OR ANDROID OR EMSCRIPTEN OR APPLE_IOS) - # This doesn't work on VS 2010 - # MSVC only builds for intel anyway - # all IOS devices are little endian - set(OGRE_TEST_BIG_ENDIAN FALSE) -else() - include(TestBigEndian) - test_big_endian(OGRE_TEST_BIG_ENDIAN) -endif() - -# definitions for samples -set(OGRE_LIBRARIES OgreMain) - -# Specify build paths -set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") -set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/lib") -set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin") -if (WIN32 OR APPLE) - if (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) - # We don't want to install in default system location, install is really for the SDK, so call it that - set(CMAKE_INSTALL_PREFIX - "${PROJECT_BINARY_DIR}/sdk" CACHE PATH "OGRE install prefix" FORCE - ) - endif (CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) -endif(WIN32 OR APPLE) - -# Set up iOS overrides. -if (APPLE_IOS) - set(CMAKE_EXE_LINKER_FLAGS "-framework OpenGLES -framework Foundation -framework CoreGraphics -framework QuartzCore -framework UIKit") - set(XCODE_ATTRIBUTE_GCC_UNROLL_LOOPS "YES") - set(XCODE_ATTRIBUTE_LLVM_VECTORIZE_LOOPS "YES") - set(XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "iPhone Developer") - set(XCODE_ATTRIBUTE_GCC_PRECOMPILE_PREFIX_HEADER "YES") - set(OGRE_BUILD_RENDERSYSTEM_GLES2 TRUE CACHE BOOL "Forcing OpenGL ES 2 RenderSystem for iOS" FORCE) - set(OGRE_STATIC TRUE CACHE BOOL "Forcing static build for iOS" FORCE) - set(MACOSX_BUNDLE_GUI_IDENTIFIER "com.yourcompany.\${PRODUCT_NAME:rfc1034identifier}") -elseif (ANDROID) - set(TargetPlatform "Android") - set(OGRE_PLATFORM OGRE_PLATFORM_ANDROID) - option(OGRE_BUILD_ANDROID_JNI_SAMPLE "Enable JNI Sample" FALSE) - - set(OGRE_BUILD_RENDERSYSTEM_GLES2 TRUE CACHE BOOL "Forcing OpenGL ES 2 RenderSystem for Android" FORCE) - - set(OGRE_BUILD_PLUGIN_PCZ FALSE CACHE BOOL "Disable pcz on Android" FORCE) - set(OGRE_BUILD_TOOLS FALSE CACHE BOOL "Disable tools on Android" FORCE) - set(OGRE_STATIC TRUE CACHE BOOL "Forcing static build for Android" FORCE) - - # workaround for the legacy android toolchain - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") -elseif(EMSCRIPTEN) - add_definitions(-DEMSCRIPTEN=1 -D__EMSCRIPTEN__=1) - set(TargetPlatform "Emscripten") - set(OGRE_PLATFORM OGRE_PLATFORM_EMSCRIPTEN) - - set(OGRE_BUILD_RENDERSYSTEM_GLES2 TRUE CACHE BOOL "Forcing OpenGL ES 2 RenderSystem for Emscripten" FORCE) - set(OGRE_BUILD_RENDERSYSTEM_GL FALSE CACHE BOOL "Disable OpenGL RenderSystem for Emscripten" FORCE) - - set(OGRE_BUILD_PLUGIN_STBI TRUE CACHE BOOL "Enable STBIImageCodec on Emscripten (Smaller Footprint)" FORCE) - set(OGRE_BUILD_PLUGIN_FREEIMAGE FALSE CACHE BOOL "Disable Freeimage on Emscripten (Smaller Footprint)" FORCE) - set(OGRE_BUILD_PLUGIN_PCZ FALSE CACHE BOOL "Disable pcz on Emscripten" FORCE) - set(OGRE_BUILD_PLUGIN_BSP FALSE CACHE BOOL "Disable pcz on Emscripten" FORCE) - set(OGRE_BUILD_TOOLS FALSE CACHE BOOL "Disable tools on Emscripten" FORCE) - set(OGRE_BUILD_TESTS FALSE CACHE BOOL "Disable tests on Emscripten" FORCE) - set(OGRE_BUILD_COMPONENT_VOLUME FALSE CACHE BOOL "Disable volume component on Emscripten" FORCE) - set(OGRE_BUILD_COMPONENT_PAGING FALSE CACHE BOOL "Disable paging component on Emscripten" FORCE) - set(OGRE_BUILD_COMPONENT_TERRAIN FALSE CACHE BOOL "Disable terrain component on Emscripten" FORCE) - set(OGRE_STATIC TRUE CACHE BOOL "Forcing static build for Emscripten" FORCE) - - set(OGRE_CONFIG_THREADS "0" CACHE STRING "Threading is unstable on Emscripten" FORCE) -elseif (APPLE AND NOT APPLE_IOS) - # Make sure that the GLES2 render system is disabled for non-iOS Apple builds - set(OGRE_BUILD_RENDERSYSTEM_GLES2 FALSE CACHE BOOL "" FORCE) -endif () - -if(OGRE_BUILD_COMPONENT_MESHLODGENERATOR) - set(OGRE_CONFIG_ENABLE_MESHLOD TRUE CACHE BOOL "Forcing Mesh Lod" FORCE) -endif() - -# Find dependencies -include(Dependencies) - -###################################################################### -# Provide user options to customise the build process -###################################################################### - -# Customise what to build -option(OGRE_STATIC "Static build" FALSE) -cmake_dependent_option(OGRE_ENABLE_PRECOMPILED_HEADERS "Use precompiled headers to speed up build" TRUE "NOT MINGW; NOT EMSCRIPTEN" FALSE) -set(OGRE_RESOURCEMANAGER_STRICT "2" CACHE STRING - "Make ResourceManager strict for faster operation. Possible values: - 0 - OFF search in all groups twice - for case sensitive and insensitive lookup [DEPRECATED] - 1 - PEDANTIC require an explicit resource group. Case sensitive lookup. - 2 - STRICT search in default group if not specified otherwise. Case sensitive lookup. - ") -set_property(CACHE OGRE_RESOURCEMANAGER_STRICT PROPERTY STRINGS 0 1 2) - -option(OGRE_NODELESS_POSITIONING "use Lights and Cameras without attaching them to nodes [DEPRECATED]" FALSE) - -cmake_dependent_option(OGRE_BUILD_RENDERSYSTEM_D3D9 "Build Direct3D9 RenderSystem" TRUE "WIN32;DirectX9_FOUND;NOT WINDOWS_STORE;NOT WINDOWS_PHONE" FALSE) -cmake_dependent_option(OGRE_BUILD_RENDERSYSTEM_D3D11 "Build Direct3D11 RenderSystem" TRUE "WIN32;DirectX11_FOUND OR WINDOWS_STORE OR WINDOWS_PHONE" FALSE) -cmake_dependent_option(OGRE_BUILD_RENDERSYSTEM_GL3PLUS "Build OpenGL 3+ RenderSystem" TRUE "OPENGL_FOUND;NOT WINDOWS_STORE;NOT WINDOWS_PHONE" FALSE) -cmake_dependent_option(OGRE_BUILD_RENDERSYSTEM_GL "Build OpenGL RenderSystem" TRUE "OPENGL_FOUND;NOT APPLE_IOS;NOT WINDOWS_STORE;NOT WINDOWS_PHONE" FALSE) -cmake_dependent_option(OGRE_BUILD_RENDERSYSTEM_GLES2 "Build OpenGL ES 2.x RenderSystem" TRUE "OPENGLES2_FOUND;NOT WINDOWS_STORE;NOT WINDOWS_PHONE" FALSE) -cmake_dependent_option(OGRE_BUILD_RENDERSYSTEM_METAL "Build Metal RenderSystem" FALSE "APPLE" FALSE) -option(OGRE_BUILD_RENDERSYSTEM_VULKAN "Build Vulkan RenderSystem" FALSE) -cmake_dependent_option(OGRE_BUILD_PLUGIN_ASSIMP "Build Open Asset Import plugin" TRUE "assimp_FOUND" FALSE) -cmake_dependent_option(OGRE_BUILD_RENDERSYSTEM_TINY "Build Tiny RenderSystem (software-rendering)" FALSE "NOT ANDROID" FALSE) -option(OGRE_BUILD_PLUGIN_BSP "Build BSP SceneManager plugin" TRUE) -option(OGRE_BUILD_PLUGIN_OCTREE "Build Octree SceneManager plugin" TRUE) -option(OGRE_BUILD_PLUGIN_PFX "Build ParticleFX plugin" TRUE) -option(OGRE_BUILD_PLUGIN_DOT_SCENE "Build .scene plugin" TRUE) -cmake_dependent_option(OGRE_BUILD_PLUGIN_PCZ "Build PCZ SceneManager plugin" TRUE "" FALSE) -cmake_dependent_option(OGRE_BUILD_COMPONENT_PAGING "Build Paging component" TRUE "" FALSE) -cmake_dependent_option(OGRE_BUILD_COMPONENT_MESHLODGENERATOR "Build MeshLodGenerator component" TRUE "" FALSE) -cmake_dependent_option(OGRE_BUILD_COMPONENT_TERRAIN "Build Terrain component" TRUE "" FALSE) -cmake_dependent_option(OGRE_BUILD_COMPONENT_VOLUME "Build Volume component" TRUE "" FALSE) -cmake_dependent_option(OGRE_BUILD_COMPONENT_PROPERTY "Build Property component" TRUE "" FALSE) -cmake_dependent_option(OGRE_BUILD_PLUGIN_CG "Build Cg plugin" TRUE "Cg_FOUND;NOT APPLE_IOS;NOT WINDOWS_STORE;NOT WINDOWS_PHONE" FALSE) -option(OGRE_BUILD_PLUGIN_GLSLANG "Build glslang plugin" ${OGRE_BUILD_RENDERSYSTEM_VULKAN}) # no way to determine whether glslang is present -option(OGRE_BUILD_COMPONENT_OVERLAY "Build Overlay component" TRUE) - -cmake_dependent_option(OGRE_BUILD_COMPONENT_OVERLAY_IMGUI "Include dear imgui in Overlays" TRUE "OGRE_BUILD_COMPONENT_OVERLAY" FALSE) - -cmake_dependent_option(OGRE_BUILD_COMPONENT_BITES "Build OgreBites component" TRUE "OGRE_BUILD_COMPONENT_OVERLAY" FALSE) -cmake_dependent_option(OGRE_BUILD_COMPONENT_BULLET "Build Bullet physics component" TRUE "BULLET_FOUND" FALSE) -cmake_dependent_option(OGRE_BITES_STATIC_PLUGINS "Skip plugins.cfg and statically load plugins via OgreBites" FALSE "NOT OGRE_STATIC;OGRE_BUILD_COMPONENT_BITES" FALSE) -cmake_dependent_option(OGRE_BUILD_COMPONENT_PYTHON "Build Python bindings" TRUE "NOT OGRE_STATIC" FALSE) -cmake_dependent_option(OGRE_BUILD_COMPONENT_JAVA "Build Java (JNI) bindings" TRUE "NOT OGRE_STATIC OR ANDROID" FALSE) -cmake_dependent_option(OGRE_BUILD_COMPONENT_CSHARP "Build Csharp bindings" TRUE "NOT OGRE_STATIC" FALSE) -option(OGRE_BUILD_COMPONENT_RTSHADERSYSTEM "Build RTShader System component" TRUE) -cmake_dependent_option(OGRE_BUILD_RTSHADERSYSTEM_SHADERS "Build RTShader System FFP shaders" TRUE "OGRE_BUILD_COMPONENT_RTSHADERSYSTEM" FALSE) - -cmake_dependent_option(OGRE_BUILD_SAMPLES "Build Ogre demos" TRUE "OGRE_BUILD_COMPONENT_OVERLAY;OGRE_BUILD_COMPONENT_BITES" FALSE) -cmake_dependent_option(OGRE_BUILD_TOOLS "Build the command-line tools" TRUE "NOT APPLE_IOS;NOT WINDOWS_STORE;NOT WINDOWS_PHONE" FALSE) -cmake_dependent_option(OGRE_BUILD_XSIEXPORTER "Build the Softimage exporter" FALSE "Softimage_FOUND" FALSE) -cmake_dependent_option(OGRE_BUILD_LIBS_AS_FRAMEWORKS "Build frameworks for libraries on OS X." TRUE "APPLE;NOT OGRE_BUILD_PLATFORM_APPLE_IOS" FALSE) -cmake_dependent_option(OGRE_BUILD_TESTS "Build the unit tests & PlayPen" FALSE "OGRE_BUILD_COMPONENT_BITES" FALSE) -option(OGRE_CONFIG_DOUBLE "Use doubles instead of floats in Ogre" FALSE) -option(OGRE_CONFIG_NODE_INHERIT_TRANSFORM "Tells the node whether it should inherit full transform from it's parent node or derived position, orientation and scale" FALSE) -set(OGRE_CONFIG_THREADS "3" CACHE STRING - "Enable Ogre thread safety support for multithreading. Possible values: - 0 - no thread safety. DefaultWorkQueue is not threaded. - 1 - background resource preparation and loading is thread safe. Threaded DefaultWorkQueue. [DEPRECATED] - 2 - only background resource preparation is thread safe. Threaded DefaultWorkQueue. [DEPRECATED] - 3 - no thread safety. Threaded DefaultWorkQueue." -) -set_property(CACHE OGRE_CONFIG_THREADS PROPERTY STRINGS 0 1 2 3) -set(OGRE_CONFIG_THREAD_PROVIDER "std" CACHE STRING - "Select the library to use for thread support. Possible values: - boost - Boost thread library. [DEPRECATED] - poco - Poco thread library. [DEPRECATED] - tbb - ThreadingBuildingBlocks library. [DEPRECATED] - std - STL thread library (requires compiler support)." -) -set_property(CACHE OGRE_CONFIG_THREAD_PROVIDER PROPERTY STRINGS boost poco tbb std) -cmake_dependent_option(OGRE_BUILD_PLUGIN_FREEIMAGE "Build FreeImage codec." TRUE "FreeImage_FOUND" FALSE) -cmake_dependent_option(OGRE_BUILD_PLUGIN_EXRCODEC "Build EXR Codec plugin" TRUE "OPENEXR_FOUND;" FALSE) -option(OGRE_BUILD_PLUGIN_STBI "Enable STBI image codec." TRUE) -option(OGRE_BUILD_PLUGIN_RSIMAGE "Enable image-rs codec." FALSE) -option(OGRE_CONFIG_ENABLE_MESHLOD "Enable Mesh Lod." TRUE) -option(OGRE_CONFIG_ENABLE_DDS "Build DDS codec." TRUE) -option(OGRE_CONFIG_ENABLE_PVRTC "Build PVRTC codec." ${APPLE_IOS}) -option(OGRE_CONFIG_ENABLE_ETC "Build ETC codec." TRUE) -option(OGRE_CONFIG_ENABLE_ASTC "Build ASTC codec." TRUE) -option(OGRE_CONFIG_ENABLE_QUAD_BUFFER_STEREO "Enable stereoscopic 3D support" FALSE) -option(OGRE_CONFIG_ENABLE_ZIP "Build ZIP archive support. If you disable this option, you cannot use ZIP archives resource locations. The samples won't work." TRUE) -cmake_dependent_option(OGRE_CONFIG_ENABLE_GLES2_CG_SUPPORT "Enable Cg support to ES 2 render system" FALSE "OGRE_BUILD_RENDERSYSTEM_GLES2" FALSE) -cmake_dependent_option(OGRE_CONFIG_ENABLE_GLES2_GLSL_OPTIMISER "Enable GLSL optimiser use in GLES 2 render system" FALSE "OGRE_BUILD_RENDERSYSTEM_GLES2" FALSE) -cmake_dependent_option(OGRE_CONFIG_ENABLE_GL_STATE_CACHE_SUPPORT "Enable OpenGL state cache management" FALSE "OGRE_BUILD_RENDERSYSTEM_GL OR OGRE_BUILD_RENDERSYSTEM_GLES2 OR OGRE_BUILD_RENDERSYSTEM_GL3PLUS" FALSE) -option(OGRE_CONFIG_ENABLE_TBB_SCHEDULER "Enable TBB's scheduler initialisation/shutdown." TRUE) -cmake_dependent_option(OGRE_CONFIG_FILESYSTEM_UNICODE "paths expected to be in UTF-8 and wchar_t file IO routines are used" TRUE "MSVC" FALSE) -# Customise what to install -cmake_dependent_option(OGRE_INSTALL_SAMPLES "Install Ogre demos." TRUE "OGRE_BUILD_SAMPLES" FALSE) -option(OGRE_INSTALL_TOOLS "Install Ogre tools." TRUE) -option(OGRE_INSTALL_DOCS "Install documentation." TRUE) -cmake_dependent_option(OGRE_INSTALL_PDB "Install debug pdb files" TRUE "MSVC" FALSE) -option(OGRE_PROFILING "Enable internal instrumentation." FALSE) -set(OGRE_PROFILING_REMOTERY_PATH "" CACHE PATH "set this to Remotery/lib to use Remotery instead of the buildin profiler") -cmake_dependent_option(OGRE_CONFIG_STATIC_LINK_CRT "Statically link the MS CRT dlls (msvcrt)" FALSE "MSVC" FALSE) -set(OGRE_LIB_DIRECTORY "lib${LIB_SUFFIX}" CACHE STRING "Install path for libraries, e.g. 'lib64' on some 64-bit Linux distros.") -set(OGRE_BIN_DIRECTORY "bin" CACHE STRING "Install path for binaries") - -cmake_dependent_option(OGRE_INSTALL_VSPROPS "Install Visual Studio Property Page." FALSE "MSVC" FALSE) -if (OGRE_INSTALL_VSPROPS) - configure_file(${OGRE_TEMPLATES_DIR}/OGRE.props.in ${PROJECT_BINARY_DIR}/OGRE.props) - install(FILES ${PROJECT_BINARY_DIR}/OGRE.props DESTINATION "${CMAKE_INSTALL_PREFIX}") -endif () - -# provide option to install dependencies -include(InstallDependencies) - -# determine threading options -include(PrepareThreadingOptions) - -# Enable project folders by default if the IDE supportes them -# Hide option from other compilers. -if (MSVC OR CMAKE_GENERATOR MATCHES Xcode) - option(OGRE_PROJECT_FOLDERS "Organize project into project folders." TRUE) -endif () - -# hide advanced options -mark_as_advanced( - OGRE_BUILD_RTSHADERSYSTEM_CORE_SHADERS - OGRE_BUILD_RTSHADERSYSTEM_EXT_SHADERS - OGRE_CONFIG_DOUBLE - OGRE_CONFIG_NODE_INHERIT_TRANSFORM - OGRE_CONFIG_ENABLE_MESHLOD - OGRE_CONFIG_ENABLE_DDS - OGRE_CONFIG_ENABLE_PVRTC - OGRE_CONFIG_ENABLE_ETC - OGRE_CONFIG_ENABLE_ASTC - OGRE_CONFIG_ENABLE_ZIP - OGRE_CONFIG_ENABLE_GL_STATE_CACHE_SUPPORT - OGRE_CONFIG_ENABLE_GLES2_CG_SUPPORT - OGRE_CONFIG_ENABLE_GLES2_GLSL_OPTIMISER - OGRE_CONFIG_ENABLE_TBB_SCHEDULER - OGRE_PROFILING - OGRE_CONFIG_STATIC_LINK_CRT - OGRE_LIB_DIRECTORY - OGRE_BIN_DIRECTORY -) - -################################################################### -# configure global build settings based on selected build options -################################################################### -include(ConfigureBuild) - -set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_RPATH};${CMAKE_INSTALL_PREFIX}/${OGRE_LIB_DIRECTORY}") -set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) - -################################################################### -# disable way too common compiler warnings on project level -################################################################### -if(MSVC) - add_definitions( /wd4251 /wd4275 ) -endif() - -################################################################## -# Now setup targets -################################################################## - -# install resource files -include(InstallResources) - -# enable PCH support -include(PrecompiledHeader) - -# Setup OgreMain project -add_subdirectory(OgreMain) - -# Setup RenderSystems -add_subdirectory(RenderSystems) - -# Setup Plugins -add_subdirectory(PlugIns) - -# Setup Components -add_subdirectory(Components) - -# Setup tests (before samples so that PlayPen is included in browser) -if (OGRE_BUILD_TESTS) - # enable CTest - ENABLE_TESTING() - INCLUDE(CTest) - add_subdirectory(Tests) -endif () - -# Setup samples -add_subdirectory(Samples) - -# Setup command-line tools -if (OGRE_BUILD_TOOLS) - add_subdirectory(Tools) -endif () - -# Setup XSIExporter -if (OGRE_BUILD_XSIEXPORTER) - add_subdirectory(Tools/XSIExport) -endif () - -# Install documentation -add_subdirectory(Docs) - -# Install sample media files -install(DIRECTORY Media/Main DESTINATION "${OGRE_MEDIA_PATH}/") -install(DIRECTORY Media/RTShaderLib DESTINATION "${OGRE_MEDIA_PATH}/") -if (OGRE_INSTALL_SAMPLES) - install(DIRECTORY Samples/Media/ DESTINATION ${OGRE_MEDIA_PATH}) -endif () - -# Provide CPack packaging target -include(Packaging) - - -# Show feature summary -include(OgreFeatureSummary) diff --git a/Components/Bites/CMakeLists.txt b/Components/Bites/CMakeLists.txt deleted file mode 100644 index daf17abf6e0..00000000000 --- a/Components/Bites/CMakeLists.txt +++ /dev/null @@ -1,203 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -############################################################ -# Paging optional component -############################################################ - -if(ANDROID) - include_directories(${ANDROID_NDK}/sources/android/native_app_glue) -endif() - -if(EMSCRIPTEN) - add_definitions(-s USE_SDL=2) -endif() - -# Find X11 -if (UNIX AND NOT APPLE AND NOT ANDROID AND NOT EMSCRIPTEN) - find_library(XAW_LIBRARY NAMES Xaw Xaw7 PATHS ${OGRE_DEP_SEARCH_PATH} ${DEP_LIB_SEARCH_DIR} ${X11_LIB_SEARCH_PATH}) - macro_log_feature(XAW_LIBRARY "Xaw" "X11 Athena widget set for ConfigDialog" "http://www.x.org") - mark_as_advanced(XAW_LIBRARY) -endif () - -if (OGRE_STATIC OR OGRE_BITES_STATIC_PLUGINS) - # Link to all enabled plugins - if (OGRE_BUILD_PLUGIN_OCTREE) - set(DEPENDENCIES ${DEPENDENCIES} Plugin_OctreeSceneManager) - endif () - if (OGRE_BUILD_PLUGIN_BSP) - set(DEPENDENCIES ${DEPENDENCIES} Plugin_BSPSceneManager) - endif () - if (OGRE_BUILD_PLUGIN_CG) - set(DEPENDENCIES ${DEPENDENCIES} Plugin_CgProgramManager) - endif () - if (OGRE_BUILD_PLUGIN_GLSLANG) - set(DEPENDENCIES ${DEPENDENCIES} Plugin_GLSLangProgramManager) - endif () - if (OGRE_BUILD_PLUGIN_PFX) - set(DEPENDENCIES ${DEPENDENCIES} Plugin_ParticleFX) - endif () - if (OGRE_BUILD_PLUGIN_PCZ) - set(DEPENDENCIES ${DEPENDENCIES} Plugin_PCZSceneManager) - endif () - if (OGRE_BUILD_PLUGIN_DOT_SCENE) - set(DEPENDENCIES ${DEPENDENCIES} Plugin_DotScene) - endif () - if (OGRE_BUILD_PLUGIN_ASSIMP) - set(DEPENDENCIES ${DEPENDENCIES} Codec_Assimp) - endif () - if (OGRE_BUILD_PLUGIN_STBI) - set(DEPENDENCIES ${DEPENDENCIES} Codec_STBI) - endif () - if (OGRE_BUILD_PLUGIN_RSIMAGE) - set(DEPENDENCIES ${DEPENDENCIES} Codec_RsImage) - endif () - if (OGRE_BUILD_PLUGIN_FREEIMAGE) - set(DEPENDENCIES ${DEPENDENCIES} Codec_FreeImage) - endif () - if (OGRE_BUILD_RENDERSYSTEM_D3D9) - include_directories(${PROJECT_SOURCE_DIR}/RenderSystems/Direct3D9/include ${DirectX9_INCLUDE_DIR}) - set(DEPENDENCIES ${DEPENDENCIES} RenderSystem_Direct3D9) - endif () - if (OGRE_BUILD_RENDERSYSTEM_D3D11) - include_directories(${PROJECT_SOURCE_DIR}/RenderSystems/Direct3D11/include) - set(DEPENDENCIES ${DEPENDENCIES} RenderSystem_Direct3D11) - endif () - if (OGRE_BUILD_RENDERSYSTEM_GL) - set(DEPENDENCIES ${DEPENDENCIES} RenderSystem_GL) - endif () - if (OGRE_BUILD_RENDERSYSTEM_GL3PLUS) - set(DEPENDENCIES ${DEPENDENCIES} RenderSystem_GL3Plus) - endif () - if (OGRE_BUILD_RENDERSYSTEM_GLES2) - set(DEPENDENCIES ${DEPENDENCIES} RenderSystem_GLES2) - endif () - if (OGRE_BUILD_RENDERSYSTEM_TINY) - set(DEPENDENCIES ${DEPENDENCIES} RenderSystem_Tiny) - endif () - if (OGRE_BUILD_RENDERSYSTEM_VULKAN) - set(DEPENDENCIES ${DEPENDENCIES} RenderSystem_Vulkan) - endif () -endif () - -# define header and source files for the library -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES - ${PROJECT_BINARY_DIR}/include/OgreBitesPrerequisites.h - ${CMAKE_CURRENT_SOURCE_DIR}/include/OgreBites.i) -set(SOURCES - "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreAdvancedRenderControls.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreApplicationContextBase.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreBitesConfigDialog.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreCameraMan.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreSGTechniqueResolverListener.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreStaticPluginLoader.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreTrays.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreWindowEventUtilities.cpp") - -if(SDL2_FOUND OR EMSCRIPTEN) - list(APPEND SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreApplicationContextSDL.cpp") -elseif(ANDROID) - list(APPEND SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreApplicationContextAndroid.cpp") -endif() - -if(ANDROID OR EMSCRIPTEN OR APPLE_IOS OR WINDOWS_STORE OR WINDOWS_PHONE) - # no config dialog available -elseif(WIN32) - include_directories("${CMAKE_CURRENT_SOURCE_DIR}/src") - list(APPEND SOURCES - "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreWIN32ConfigDialog.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/resource.h" - "${CMAKE_CURRENT_SOURCE_DIR}/misc/OgreWin32Resources.rc") - # Need to include resource files so that icons are linked - set(RESOURCE_FILES - "${CMAKE_CURRENT_SOURCE_DIR}/src/resource.h" - "${CMAKE_CURRENT_SOURCE_DIR}/misc/OgreWin32Resources.rc" - ) - source_group(Resources FILES ${RESOURCE_FILES}) -elseif(APPLE) - list(APPEND SOURCES - "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreOSXConfigDialog.mm" - "${CMAKE_CURRENT_SOURCE_DIR}/misc/ogrelogo.png") - set_source_files_properties("${CMAKE_CURRENT_SOURCE_DIR}/src/OgreOSXConfigDialog.mm" - PROPERTIES COMPILE_FLAGS "-Wno-deprecated-declarations" - ) - set(RESOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/misc/ogrelogo.png") - source_group(Resources FILES ${RESOURCE_FILES}) - set(DEPENDENCIES ${DEPENDENCIES} "-framework Cocoa") -elseif(UNIX) - list(APPEND DEPENDENCIES ${X11_X11_LIB}) - set(NATIVE_INCLUDES ${X11_Xlib_INCLUDE_PATH}) - if(XAW_LIBRARY) - set_source_files_properties(src/OgreBitesConfigDialog.cpp PROPERTIES COMPILE_DEFINITIONS HAVE_XAW) - list(APPEND SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreGLXConfigDialog.cpp") - list(APPEND DEPENDENCIES ${X11_Xt_LIB} ${XAW_LIBRARY}) - install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/misc/GLX_backdrop.png" DESTINATION "${OGRE_MEDIA_PATH}/../") - endif() -endif() - -if(OGRE_BUILD_COMPONENT_OVERLAY_IMGUI) - list(APPEND SOURCES - "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreImGuiInputListener.cpp") -endif() - -# setup target -add_library(OgreBites ${OGRE_COMP_LIB_TYPE} ${HEADER_FILES} ${SOURCES}) -set_target_properties(OgreBites PROPERTIES VERSION ${OGRE_SOVERSION} SOVERSION ${OGRE_SOVERSION}) -target_link_libraries(OgreBites PUBLIC OgreMain OgreOverlay PRIVATE ${DEPENDENCIES}) -if (OGRE_BUILD_COMPONENT_RTSHADERSYSTEM) - target_link_libraries(OgreBites PUBLIC OgreRTShaderSystem) -endif () -target_include_directories(OgreBites PUBLIC - "$" - "$" - $) - -if (OGRE_STATIC OR OGRE_BITES_STATIC_PLUGINS) - target_compile_definitions(OgreBites PRIVATE OGRE_BITES_STATIC_PLUGINS) -endif() - -if(OGRE_STATIC AND APPLE AND OGRE_BUILD_PLUGIN_CG) - # workaround so the Cg framework is found in the above condition - target_include_directories(OgreBites PUBLIC ${Cg_INCLUDE_DIRS}) -endif() - -if(SDL2_FOUND) - target_link_libraries(OgreBites PRIVATE SDL2::SDL2) -elseif(NOT EMSCRIPTEN) - message(WARNING "SDL2 not found - no input handling and reduced window creation capabilites") -endif() - -generate_export_header(OgreBites - EXPORT_MACRO_NAME _OgreBitesExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreBitesPrerequisites.h) - -if(Qt6_FOUND OR Qt5_FOUND) - if(Qt6_FOUND) - qt6_wrap_cpp(MOC_SRC "${CMAKE_CURRENT_SOURCE_DIR}/include/OgreApplicationContextQt.h") - else() - qt5_wrap_cpp(MOC_SRC "${CMAKE_CURRENT_SOURCE_DIR}/include/OgreApplicationContextQt.h") - endif() - - add_library(OgreBitesQt ${OGRE_COMP_LIB_TYPE} ${MOC_SRC} "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreApplicationContextQt.cpp") - set_target_properties(OgreBitesQt PROPERTIES VERSION ${OGRE_SOVERSION} SOVERSION ${OGRE_SOVERSION}) - target_link_libraries(OgreBitesQt PUBLIC Qt${QT_VERSION_MAJOR}::Gui OgreBites) - ogre_config_component(OgreBitesQt) -endif() - -# install -ogre_config_framework(OgreBites) -ogre_config_component(OgreBites) - -install(FILES ${HEADER_FILES} - DESTINATION include/OGRE/Bites -) -install(FILES "${PROJECT_SOURCE_DIR}/Media/packs/SdkTrays.zip" - DESTINATION "${OGRE_MEDIA_PATH}/packs/" -) diff --git a/Components/Bites/include/OgreAdvancedRenderControls.h b/Components/Bites/include/OgreAdvancedRenderControls.h deleted file mode 100644 index 1c21f0f1217..00000000000 --- a/Components/Bites/include/OgreAdvancedRenderControls.h +++ /dev/null @@ -1,94 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef COMPONENTS_BITES_INCLUDE_OGREADVANCEDRENDERCONTROLS_H_ -#define COMPONENTS_BITES_INCLUDE_OGREADVANCEDRENDERCONTROLS_H_ - -#include "OgreInput.h" -#include "OgreRoot.h" -#include "OgreCamera.h" -#include "OgreComponents.h" - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM -#include "OgreRTShaderSystem.h" -#endif - -namespace OgreBites { - -class TrayManager; -class ParamsPanel; - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup Bites -* @{ -*/ - -/** - - F: Toggle frame rate stats on/off - - G: Toggle advanced frame stats on/off - - P Toggle profiler window on/ off - - R: Render mode - - Wireframe - - Points - - Solid - - T: Cycle texture filtering - - Bilinear - - Trilinear - - Anisotropic(8) - - None - - F2: RTSS: Set the main viewport material scheme to default material manager scheme. - - F3: RTSS: Toggle default shader generator lighting model from per vertex to per pixel. - - F4: RTSS: Switch vertex shader outputs compaction policy. - - F5: Reload all textures - - F6: Take a screenshot - */ -class _OgreBitesExport AdvancedRenderControls : public InputListener { -public: - AdvancedRenderControls(TrayManager* trayMgr, Ogre::Camera* cam); - ~AdvancedRenderControls(); - - bool keyPressed(const KeyboardEvent& evt) override; - - void frameRendered(const Ogre::FrameEvent& evt) override; - -protected: - Ogre::Root* mRoot; - Ogre::Camera* mCamera; // main camera - TrayManager* mTrayMgr; // tray interface manager - ParamsPanel* mDetailsPanel; // sample details panel -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - Ogre::RTShader::ShaderGenerator* mShaderGenerator; -#endif -}; -/** @} */ -/** @} */ -} /* namespace OgreBites */ - -#endif /* COMPONENTS_BITES_INCLUDE_OGREADVANCEDRENDERCONTROLS_H_ */ diff --git a/Components/Bites/include/OgreApplicationContext.h b/Components/Bites/include/OgreApplicationContext.h deleted file mode 100644 index bd7269cda01..00000000000 --- a/Components/Bites/include/OgreApplicationContext.h +++ /dev/null @@ -1,107 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#ifndef __ApplicationContext_H__ -#define __ApplicationContext_H__ - -#include "OgreBitesPrerequisites.h" -#include "OgreBuildSettings.h" -#include "OgreApplicationContextBase.h" - - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID -#include -#include -#include -#include -#endif - -#include "OgreInput.h" - -namespace OgreBites -{ - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Bites - * @{ - */ - -#if OGRE_BITES_HAVE_SDL - class _OgreBitesExport ApplicationContextSDL : public ApplicationContextBase - { - protected: - void _destroyWindow(const NativeWindowPair& win) override; - public: - explicit ApplicationContextSDL(const Ogre::String& appName = "Ogre3D"); - - void setWindowGrab(NativeWindowType* win, bool grab) override; - float getDisplayDPI() const override; - void shutdown() override; - void pollEvents() override; - void addInputListener(NativeWindowType* win, InputListener* lis) override; - void removeInputListener(NativeWindowType* win, InputListener* lis) override; - NativeWindowPair - createWindow(const Ogre::String& name, uint32_t w = 0, uint32_t h = 0, - Ogre::NameValuePairList miscParams = Ogre::NameValuePairList()) override; - - using ApplicationContextBase::setWindowGrab; - using ApplicationContextBase::addInputListener; - using ApplicationContextBase::removeInputListener; - }; - - typedef ApplicationContextSDL ApplicationContext; -#elif OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - class _OgreBitesExport ApplicationContextAndroid : public ApplicationContextBase - { - public: - explicit ApplicationContextAndroid(const Ogre::String& appName = "Ogre3D"); - - void initAppForAndroid(AAssetManager* assetMgr, ANativeWindow* window); - void _fireInputEventAndroid(AInputEvent* event, int wheel = 0); - - void locateResources() override; - void shutdown() override; - void pollEvents() override; - - NativeWindowPair - createWindow(const Ogre::String& name, uint32_t w = 0, uint32_t h = 0, - Ogre::NameValuePairList miscParams = Ogre::NameValuePairList()) override; - - protected: - AAssetManager* mAAssetMgr; - AConfiguration* mAConfig; - }; - - typedef ApplicationContextAndroid ApplicationContext; -#else - typedef ApplicationContextBase ApplicationContext; -#endif - /** @} */ - /** @} */ -} -#endif diff --git a/Components/Bites/include/OgreApplicationContextBase.h b/Components/Bites/include/OgreApplicationContextBase.h deleted file mode 100644 index 32d745eb776..00000000000 --- a/Components/Bites/include/OgreApplicationContextBase.h +++ /dev/null @@ -1,316 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#ifndef __ApplicationContextBase_H__ -#define __ApplicationContextBase_H__ - -#include "OgreBitesPrerequisites.h" -#include "OgreBuildSettings.h" -#include "OgreComponents.h" -#include "OgreLogManager.h" -#include "OgrePlugin.h" -#include "OgreFileSystemLayer.h" -#include "OgreFrameListener.h" -#include "OgreStaticPluginLoader.h" - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM -#include "OgreSGTechniqueResolverListener.h" -#endif // INCLUDE_RTSHADER_SYSTEM - -// forward declarations -extern "C" struct SDL_Window; - -namespace Ogre { - class OverlaySystem; -} - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID -#include -#endif - -#include "OgreInput.h" - -namespace OgreBites -{ -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - typedef ANativeWindow NativeWindowType; -#else - typedef SDL_Window NativeWindowType; -#endif - - /** \addtogroup Optional Optional Components - * @{ - */ - /** \defgroup Bites Bites - * reusable utilities for rapid prototyping - * @{ - */ - - /** - * link between a renderwindow and a platform specific window - */ - struct NativeWindowPair - { - Ogre::RenderWindow* render; - NativeWindowType* native; - }; - - /** - Base class responsible for setting up a common context for applications. - Subclass to implement specific event callbacks. - */ - class _OgreBitesExport ApplicationContextBase : public Ogre::FrameListener - { - public: - explicit ApplicationContextBase(const Ogre::String& appName = "Ogre3D"); - - virtual ~ApplicationContextBase(); - - /** - * get the main RenderWindow - * owns the context on OpenGL - */ - Ogre::RenderWindow* getRenderWindow() const - { - return mWindows.empty() ? NULL : mWindows[0].render; - } - - Ogre::Root* getRoot() const { - return mRoot; - } - - Ogre::OverlaySystem* getOverlaySystem() const { - return mOverlaySystem; - } - - /** - This function initializes the render system and resources. - */ - void initApp(); - - /** - This function closes down the application - saves the configuration then - shutdowns. - */ - void closeApp(); - - // callback interface copied from various listeners to be used by ApplicationContext - bool frameStarted(const Ogre::FrameEvent& evt) override { - pollEvents(); - return true; - } - bool frameRenderingQueued(const Ogre::FrameEvent& evt) override; - bool frameEnded(const Ogre::FrameEvent& evt) override { return true; } - virtual void windowMoved(Ogre::RenderWindow* rw) {} - virtual void windowResized(Ogre::RenderWindow* rw) {} - virtual bool windowClosing(Ogre::RenderWindow* rw) { return true; } - virtual void windowClosed(Ogre::RenderWindow* rw) {} - virtual void windowFocusChange(Ogre::RenderWindow* rw) {} - - /** - * inspect the event and call one of the corresponding functions on the registered InputListener - * @param event Input Event - * @param windowID only call listeners of this window - */ - void _fireInputEvent(const Event& event, uint32_t windowID) const; - - /** - Initialize the RT Shader system. - */ - bool initialiseRTShaderSystem(); - - /** - * make the RTSS write out the generated shaders for caching and debugging - * - * by default all shaders are generated to system memory. - * Must be called before loadResources - * @param write Whether to write out the generated shaders - */ - void setRTSSWriteShadersToDisk(bool write); - - /** - Destroy the RT Shader system. - */ - void destroyRTShaderSystem(); - - /** - Sets up the context after configuration. - */ - virtual void setup(); - - /** - Creates the OGRE root. - */ - virtual void createRoot(); - - /** - Configures the startup settings for OGRE. I use the config dialog here, - but you can also restore from a config file. Note that this only happens - when you start the context, and not when you reset it. - */ - virtual bool oneTimeConfig(); - - /** - When input is grabbed the mouse is confined to the window. - */ - virtual void setWindowGrab(NativeWindowType* win, bool grab = true) {} - - /// get the vertical DPI of the display - virtual float getDisplayDPI() const { return 96.0f; } - - /// @overload - void setWindowGrab(bool grab = true) { - OgreAssert(!mWindows.empty(), "create a window first"); - setWindowGrab(mWindows[0].native, grab); - } - - /** - Finds context-wide resource groups. I load paths from a config file here, - but you can choose your resource locations however you want. - */ - virtual void locateResources(); - - /** - Loads context-wide resource groups. I chose here to simply initialise all - groups, but you can fully load specific ones if you wish. - */ - virtual void loadResources(); - - /** - Reconfigures the context. Attempts to preserve the current sample state. - */ - virtual void reconfigure(const Ogre::String& renderer, Ogre::NameValuePairList& options); - - - /** - Cleans up and shuts down the context. - */ - virtual void shutdown(); - - /** - process all window events since last call - */ - virtual void pollEvents(); - - /** - Creates dummy scene to allow rendering GUI in viewport. - */ - void createDummyScene(); - - /** - Destroys dummy scene. - */ - void destroyDummyScene(); - - /** - * enables the caching of compiled shaders to file - * - * also loads any existing cache - */ - void enableShaderCache() const; - - /** attach input listener - * - * @param lis the listener - * @param win the window to receive the events for. - */ - virtual void addInputListener(NativeWindowType* win, InputListener* lis); - - /// @overload - void addInputListener(InputListener* lis) { - OgreAssert(!mWindows.empty(), "create a window first"); - addInputListener(mWindows[0].native, lis); - } - - /** detatch input listener - * - * @param lis the listener - * @param win the window to receive the events for. - */ - virtual void removeInputListener(NativeWindowType* win, InputListener* lis); - - /// @overload - void removeInputListener(InputListener* lis) { - OgreAssert(!mWindows.empty(), "called after all windows were deleted"); - removeInputListener(mWindows[0].native, lis); - } - - /** - * Create a new render window - * - * You must use SDL and not an auto-created window as SDL does not get the events - * otherwise. - * - * By default the values from ogre.cfg are used for w, h and miscParams. - */ - virtual NativeWindowPair - createWindow(const Ogre::String& name, uint32_t w = 0, uint32_t h = 0, - Ogre::NameValuePairList miscParams = Ogre::NameValuePairList()); - - /// destroy and erase an NativeWindowPair by name - void destroyWindow(const Ogre::String& name); - - /** - * get the FileSystemLayer instace pointing to an application specific directory - */ - Ogre::FileSystemLayer& getFSLayer() { return *mFSLayer; } - - /** - * the directory where the media files were installed - * - * same as OGRE_MEDIA_DIR in CMake - */ - static Ogre::String getDefaultMediaDir(); - protected: - /// internal method to destroy both the render and the native window - virtual void _destroyWindow(const NativeWindowPair& win); - - Ogre::OverlaySystem* mOverlaySystem; // Overlay system - - Ogre::FileSystemLayer* mFSLayer; // File system abstraction layer - Ogre::Root* mRoot; // OGRE root - StaticPluginLoader mStaticPluginLoader; - bool mFirstRun; - Ogre::String mNextRenderer; // name of renderer used for next run - Ogre::String mAppName; - - typedef std::vector WindowList; - WindowList mWindows; // all windows - - typedef std::set > InputListenerList; - InputListenerList mInputListeners; - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - Ogre::RTShader::ShaderGenerator* mShaderGenerator; // The Shader generator instance. - SGTechniqueResolverListener* mMaterialMgrListener; // Shader generator material manager listener. -#endif // INCLUDE_RTSHADER_SYSTEM - }; - - /** @} */ - /** @} */ -} -#endif diff --git a/Components/Bites/include/OgreApplicationContextQt.h b/Components/Bites/include/OgreApplicationContextQt.h deleted file mode 100644 index ec3ea8c18ef..00000000000 --- a/Components/Bites/include/OgreApplicationContextQt.h +++ /dev/null @@ -1,95 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -#ifndef COMPONENTS_BITES_INCLUDE_APPLICATIONCONTEXTQT_H_ -#define COMPONENTS_BITES_INCLUDE_APPLICATIONCONTEXTQT_H_ - -#include "OgreApplicationContextBase.h" - -#include -#include - -#if defined(OgreBitesQt_EXPORTS) -# define _OgreBitesQtExport Q_DECL_EXPORT -#else -# define _OgreBitesQtExport Q_DECL_IMPORT -#endif - -namespace OgreBites -{ -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup Bites -* @{ -*/ - -/** -Specialization for connecting with Qt - -- Set a QBasicTimer on this or call startTimer() to update all associated windows using Root::renderOneFrame. -- Use the QWindow::requestUpdate() slot to refresh a single Window using RenderWindow::update -- QWidget::createWindowContainer and QWidget::windowHandle() provide translation between QWidget and QWindow - -Assumes that Ogre Main loop is used for compatibility with other implementations. - */ -class _OgreBitesQtExport ApplicationContextQt : public QObject, public ApplicationContextBase -{ - Q_OBJECT -public: - explicit ApplicationContextQt(const Ogre::String& appName = "Ogre3D") - : ApplicationContextBase(appName), mWindowOverride(NULL), mQtEventLoop(false) - { - } - - NativeWindowPair - createWindow(const Ogre::String& name, uint32_t w = 0, uint32_t h = 0, - Ogre::NameValuePairList miscParams = Ogre::NameValuePairList()) override; - - /// @overload - NativeWindowPair createWindow(QWindow* window, - Ogre::NameValuePairList miscParams = Ogre::NameValuePairList()); - - /** - * allows overriding the main (first) Window with a pre-created QWindow - * @param window - */ - void injectMainWindow(QWindow* window) - { - OgreAssert(window, "window is null. Did you set WA_NativeWindow on your QWidget?"); - mWindowOverride = window; - } - - /** - * signal that you want to use the Qt event loop - * - * aka QApplication::exec() instead of Root::startRendering. - * In this case you may want to call startTimer on this QObject - * which ensures that Root::renderOneFrame is called periodically. - * @param enable - */ - void useQtEventLoop(bool enable) { mQtEventLoop = enable; } - - using ApplicationContextBase::setWindowGrab; - - void setWindowGrab(NativeWindowType* win, bool grab) override; - - using ApplicationContextBase::addInputListener; - using ApplicationContextBase::removeInputListener; - void addInputListener(NativeWindowType* win, InputListener* lis) override; - void removeInputListener(NativeWindowType* win, InputListener* lis) override; - - void pollEvents() override; - void shutdown() override; - -private: - void timerEvent(QTimerEvent *e) override; - bool eventFilter(QObject *obj, QEvent *event) override; - QWindow* mWindowOverride; - bool mQtEventLoop; -}; -/** @} */ -/** @} */ -} /* namespace Ogre */ - -#endif /* COMPONENTS_BITES_INCLUDE_OGREAPPLICATIONCONTEXTQT_H_ */ diff --git a/Components/Bites/include/OgreBites.i b/Components/Bites/include/OgreBites.i deleted file mode 100644 index 99326d96326..00000000000 --- a/Components/Bites/include/OgreBites.i +++ /dev/null @@ -1,75 +0,0 @@ -%module(package="Ogre", directors="1") Bites -%{ -/* Includes the header in the wrapper code */ -#include "Ogre.h" -#include "OgreBuildSettings.h" -#include "OgreComponents.h" -#include "OgreApplicationContextBase.h" -#include "OgreApplicationContext.h" -#include "OgreSGTechniqueResolverListener.h" -#include "OgreCameraMan.h" -#include "OgreTrays.h" -#include "OgreAdvancedRenderControls.h" -#include "OgrePredefinedControllers.h" - -#include "OgreImGuiInputListener.h" -%} - -%include std_vector.i -%include std_string.i -%include exception.i -%include stdint.i -%import "Ogre.i" - -#define _OgreBitesExport - -%include "OgreSGTechniqueResolverListener.h" -%template(InputListenerList) std::vector; -%feature("director") OgreBites::ApplicationContextBase; -%feature("director") OgreBites::InputListener; -%include "OgreInput.h" - -#ifdef HAVE_IMGUI -%include "OgreImGuiInputListener.h" -#endif - -#ifdef __ANDROID__ -%{ -#include -#include - -JNIEnv* OgreJNIGetEnv(); -%} - -%ignore OgreBites::ApplicationContextAndroid::initApp; -%ignore OgreBites::ApplicationContextAndroid::initAppForAndroid(AAssetManager*, ANativeWindow*); -%extend OgreBites::ApplicationContextAndroid { - void initAppForAndroid(jobject assetManager, jobject surface) { - OgreAssert(assetManager, "assetManager is NULL"); - OgreAssert(surface, "surface is NULL"); - - AAssetManager* assetMgr = AAssetManager_fromJava(OgreJNIGetEnv(), assetManager); - ANativeWindow* nativeWnd = ANativeWindow_fromSurface(OgreJNIGetEnv(), surface); - $self->initAppForAndroid(assetMgr, nativeWnd); - } -} -%feature("director") OgreBites::ApplicationContextAndroid; -%rename(ApplicationContext) ApplicationContextAndroid; -#else -%feature("director") OgreBites::ApplicationContextSDL; -%rename(ApplicationContext) ApplicationContextSDL; // keep the pre 1.12 name -#endif - -%include "OgreComponents.h" -%include "OgreApplicationContextBase.h" -%include "OgreApplicationContext.h" -%include "OgreCameraMan.h" -// deprecated -%ignore OgreBites::TrayManager::getWidget(TrayLocation, unsigned int); -%ignore OgreBites::TrayManager::getNumWidgets(TrayLocation); -%ignore OgreBites::TrayManager::getWidgetIterator; -%ignore OgreBites::SelectMenu::getItemsCount; -#ifndef SWIGCSHARP -%include "OgreTrays.h" -%include "OgreAdvancedRenderControls.h" -#endif \ No newline at end of file diff --git a/Components/Bites/include/OgreBitesConfigDialog.h b/Components/Bites/include/OgreBitesConfigDialog.h deleted file mode 100644 index 8159b3fe2da..00000000000 --- a/Components/Bites/include/OgreBitesConfigDialog.h +++ /dev/null @@ -1,51 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef COMPONENTS_BITES_INCLUDE_OGREBITESCONFIGDIALOG_H_ -#define COMPONENTS_BITES_INCLUDE_OGREBITESCONFIGDIALOG_H_ - -#include "OgreBitesPrerequisites.h" -#include "OgreConfigDialog.h" - -namespace OgreBites { - - /** - OGRE comes with it's own renderer configuration dialog, which - applications can use to easily allow the user to configure the - settings appropriate to their machine. This defines the - interface to this standard dialog. Because dialogs are inherently - tied to a particular platform's windowing system, there will be a - different subclass for each platform. - - * @return pointer to Ogre::ConfigDialog or NULL if not available on the current platform. - */ - _OgreBitesExport Ogre::ConfigDialog* getNativeConfigDialog(); - -} /* namespace OgreBites */ - -#endif /* COMPONENTS_BITES_INCLUDE_OGREBITESCONFIGDIALOG_H_ */ diff --git a/Components/Bites/include/OgreCameraMan.h b/Components/Bites/include/OgreCameraMan.h deleted file mode 100644 index 6dfc20f7116..00000000000 --- a/Components/Bites/include/OgreCameraMan.h +++ /dev/null @@ -1,178 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#ifndef __SdkCameraMan_H__ -#define __SdkCameraMan_H__ - -#include "OgreBitesPrerequisites.h" -#include "OgreCamera.h" -#include "OgreSceneNode.h" -#include "OgreFrameListener.h" - -#include "OgreInput.h" - -namespace OgreBites -{ - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Bites - * @{ - */ - enum CameraStyle /// enumerator values for different styles of camera movement - { - CS_FREELOOK, - CS_ORBIT, - CS_MANUAL - }; - - /** - Utility class for controlling the camera in samples. - */ - class _OgreBitesExport CameraMan : public InputListener - { - public: - CameraMan(Ogre::SceneNode* cam); - - /** - Swaps the camera on our camera man for another camera. - */ - void setCamera(Ogre::SceneNode* cam); - - Ogre::SceneNode* getCamera() - { - return mCamera; - } - - /** - Sets the target we will revolve around. Only applies for orbit style. - */ - virtual void setTarget(Ogre::SceneNode* target); - - Ogre::SceneNode* getTarget() - { - return mTarget; - } - - /** - Sets the spatial offset from the target. Only applies for orbit style. - */ - void setYawPitchDist(const Ogre::Radian& yaw, const Ogre::Radian& pitch, Ogre::Real dist); - - /** - Sets the camera's top speed. Only applies for free-look style. - */ - void setTopSpeed(Ogre::Real topSpeed) - { - mTopSpeed = topSpeed; - } - - Ogre::Real getTopSpeed() - { - return mTopSpeed; - } - - /** - Sets the movement style of our camera man. - */ - virtual void setStyle(CameraStyle style); - - CameraStyle getStyle() - { - return mStyle; - } - - /** - Manually stops the camera when in free-look mode. - */ - void manualStop(); - - void frameRendered(const Ogre::FrameEvent& evt) override; - - /** - Processes key presses for free-look style movement. - */ - bool keyPressed(const KeyboardEvent& evt) override; - - /** - Processes key releases for free-look style movement. - */ - bool keyReleased(const KeyboardEvent& evt) override; - - /** - Processes mouse movement differently for each style. - */ - bool mouseMoved(const MouseMotionEvent& evt) override; - - bool mouseWheelRolled(const MouseWheelEvent& evt) override; - - /** - Processes mouse presses. Only applies for orbit style. - Left button is for orbiting, and right button is for zooming. - */ - bool mousePressed(const MouseButtonEvent& evt) override; - - /** - Processes mouse releases. Only applies for orbit style. - Left button is for orbiting, and right button is for zooming. - */ - bool mouseReleased(const MouseButtonEvent& evt) override; - - /** - * fix the yaw axis to be Vector3::UNIT_Y of the parent node (tabletop mode) - * - * otherwise the yaw axis can change freely - */ - void setFixedYaw(bool fixed) - { - mYawSpace = fixed ? Ogre::Node::TS_PARENT : Ogre::Node::TS_LOCAL; - } - - void setPivotOffset(const Ogre::Vector3& offset); - protected: - Ogre::Real getDistToTarget(); - Ogre::Node::TransformSpace mYawSpace; - Ogre::SceneNode* mCamera; - CameraStyle mStyle; - Ogre::SceneNode* mTarget; - bool mOrbiting; - bool mMoving; - Ogre::Real mTopSpeed; - Ogre::Vector3 mVelocity; - bool mGoingForward; - bool mGoingBack; - bool mGoingLeft; - bool mGoingRight; - bool mGoingUp; - bool mGoingDown; - bool mFastMove; - Ogre::Vector3 mOffset; - }; - /** @} */ - /** @} */ -} -#endif diff --git a/Components/Bites/include/OgreImGuiInputListener.h b/Components/Bites/include/OgreImGuiInputListener.h deleted file mode 100644 index 990a8fb1458..00000000000 --- a/Components/Bites/include/OgreImGuiInputListener.h +++ /dev/null @@ -1,32 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. - -#ifndef COMPONENTS_BITES_INCLUDE_OGREIMGUIINPUTLISTENER_H_ -#define COMPONENTS_BITES_INCLUDE_OGREIMGUIINPUTLISTENER_H_ - -#include "OgreBitesPrerequisites.h" -#include "OgreInput.h" - -namespace OgreBites -{ - /** \addtogroup Optional - * \addtogroup Bites - * \addtogroup Input - */ - struct _OgreBitesExport ImGuiInputListener : public InputListener - { - ImGuiInputListener(); - bool keyPressed(const KeyboardEvent& evt) override; - bool keyReleased(const KeyboardEvent& evt) override; - bool mouseMoved(const MouseMotionEvent& evt) override; - bool mouseWheelRolled(const MouseWheelEvent& evt) override; - bool mousePressed(const MouseButtonEvent& evt) override; - bool mouseReleased(const MouseButtonEvent& evt) override; - bool textInput (const TextInputEvent& evt) override; - bool buttonPressed(const ButtonEvent& evt) override; - bool buttonReleased(const ButtonEvent& evt) override; - }; -} - -#endif /* COMPONENTS_BITES_INCLUDE_OGREIMGUIINPUTLISTENER_H_ */ diff --git a/Components/Bites/include/OgreInput.h b/Components/Bites/include/OgreInput.h deleted file mode 100644 index 5be50593991..00000000000 --- a/Components/Bites/include/OgreInput.h +++ /dev/null @@ -1,308 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#ifndef SAMPLES_COMMON_INCLUDE_INPUT_H_ -#define SAMPLES_COMMON_INCLUDE_INPUT_H_ - -#include "OgreBitesPrerequisites.h" -#include - -namespace Ogre { - struct FrameEvent; -} - -namespace OgreBites { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup Bites -* @{ -*/ -/** @defgroup Input Input - * SDL2 inspired input abstraction layer providing basic events - * @{ - */ -enum ButtonType { - BUTTON_LEFT = 1, - BUTTON_MIDDLE, - BUTTON_RIGHT, -}; - -enum EventType { - KEYDOWN = 1, - KEYUP, - MOUSEBUTTONDOWN, - MOUSEBUTTONUP, - MOUSEWHEEL, - MOUSEMOTION, - FINGERDOWN, - FINGERUP, - FINGERMOTION, - TEXTINPUT, - CONTROLLERAXISMOTION, - CONTROLLERBUTTONDOWN, - CONTROLLERBUTTONUP, - JOYAXISMOTION -}; - -typedef int Keycode; - -struct Keysym { - Keycode sym; - unsigned short mod; -}; - -struct KeyboardEvent { - int type; - Keysym keysym; - unsigned char repeat; -}; -struct MouseMotionEvent { - int type; - int x, y; - int xrel, yrel; - int windowID; -}; -struct MouseButtonEvent { - int type; - int x, y; - unsigned char button; - unsigned char clicks; -}; -struct MouseWheelEvent { - int type; - int y; -}; -struct TouchFingerEvent { - int type; - int fingerId; - float x, y; - float dx, dy; -}; -struct TextInputEvent { - int type; - const char* chars; -}; -struct AxisEvent { - int type; - int which; - unsigned char axis; - short value; -}; -struct ButtonEvent { - int type; - int which; - unsigned char button; -}; - -union Event -{ - int type; - KeyboardEvent key; - MouseButtonEvent button; - MouseWheelEvent wheel; - MouseMotionEvent motion; - TouchFingerEvent tfinger; - TextInputEvent text; - AxisEvent axis; - ButtonEvent cbutton; -}; - -// SDL compat -enum { - SDLK_DELETE = int('\177'), - SDLK_RETURN = int('\r'), - SDLK_ESCAPE = int('\033'), - SDLK_SPACE = int(' '), - SDLK_F1 = (1 << 30) | 0x3A, - SDLK_F2, - SDLK_F3, - SDLK_F4, - SDLK_F5, - SDLK_F6, - SDLK_F7, - SDLK_F8, - SDLK_F9, - SDLK_F10, - SDLK_F11, - SDLK_F12, - SDLK_PRINTSCREEN, - SDLK_SCROLLLOCK, - SDLK_PAUSE, - SDLK_INSERT, - SDLK_HOME, - SDLK_PAGEUP, - SDLK_END = (1 << 30) | 0x4D, - SDLK_PAGEDOWN, - SDLK_RIGHT, - SDLK_LEFT, - SDLK_DOWN, - SDLK_UP, - SDLK_NUMLOCKCLEAR, - SDLK_KP_DIVIDE, - SDLK_KP_MULTIPLY, - SDLK_KP_MINUS, - SDLK_KP_PLUS, - SDLK_KP_ENTER, - SDLK_KP_1, - SDLK_KP_2, - SDLK_KP_3, - SDLK_KP_4, - SDLK_KP_5, - SDLK_KP_6, - SDLK_KP_7, - SDLK_KP_8, - SDLK_KP_9, - SDLK_KP_0, - SDLK_KP_PERIOD, - SDLK_LSHIFT = (1 << 30) | 0xE1, - KMOD_ALT = 0x0100 | 0x0200, - KMOD_CTRL = 0x0040 | 0x0080, - KMOD_GUI = 0x0400 | 0x0800, - KMOD_SHIFT = 0x0001 | 0x0002, - KMOD_NUM = 0x1000, -}; - -/** -the return values of the callbacks are ignored by ApplicationContext -however they can be used to control event propagation in a hierarchy. -The convention is to return true if the event was handled and false if it should be further propagated. -*/ -struct _OgreBitesExport InputListener { - virtual ~InputListener() {} - virtual void frameRendered(const Ogre::FrameEvent& evt) { } - virtual bool keyPressed(const KeyboardEvent& evt) { return false;} - virtual bool keyReleased(const KeyboardEvent& evt) { return false; } - virtual bool touchMoved(const TouchFingerEvent& evt) { return false; } - virtual bool touchPressed(const TouchFingerEvent& evt) { return false; } - virtual bool touchReleased(const TouchFingerEvent& evt) { return false; } - virtual bool mouseMoved(const MouseMotionEvent& evt) { return false; } - virtual bool mouseWheelRolled(const MouseWheelEvent& evt) { return false; } - virtual bool mousePressed(const MouseButtonEvent& evt) { return false; } - virtual bool mouseReleased(const MouseButtonEvent& evt) { return false; } - virtual bool textInput(const TextInputEvent& evt) { return false; } - virtual bool axisMoved(const AxisEvent& evt) { return false; } - virtual bool buttonPressed(const ButtonEvent& evt) { return false; } - virtual bool buttonReleased(const ButtonEvent& evt) { return false; } -}; - -/** - * Chain of multiple InputListeners that acts as a single InputListener - * - * input events are propagated front to back until a listener returns true - */ -class _OgreBitesExport InputListenerChain : public InputListener -{ -protected: - std::vector mListenerChain; - -public: - InputListenerChain() {} - InputListenerChain(std::vector chain) : mListenerChain(chain) {} - - InputListenerChain& operator=(const InputListenerChain& o) - { - mListenerChain = o.mListenerChain; - return *this; - } - - bool keyPressed(const KeyboardEvent& evt) override - { - for (auto listner : mListenerChain) - { - if (listner->keyPressed(evt)) - return true; - } - return false; - } - bool keyReleased(const KeyboardEvent& evt) override - { - for (auto listner : mListenerChain) - { - if (listner->keyReleased(evt)) - return true; - } - return false; - } - bool touchMoved(const TouchFingerEvent& evt) override - { - for (auto listner : mListenerChain) - { - if (listner->touchMoved(evt)) - return true; - } - return false; - } - bool touchPressed(const TouchFingerEvent& evt) override - { - for (auto listner : mListenerChain) - { - if (listner->touchPressed(evt)) - return true; - } - return false; - } - bool touchReleased(const TouchFingerEvent& evt) override - { - for (auto listner : mListenerChain) - { - if (listner->touchReleased(evt)) - return true; - } - return false; - } - bool mouseMoved(const MouseMotionEvent& evt) override - { - for (auto listner : mListenerChain) - { - if (listner->mouseMoved(evt)) - return true; - } - return false; - } - bool mouseWheelRolled(const MouseWheelEvent& evt) override - { - for (auto listner : mListenerChain) - { - if (listner->mouseWheelRolled(evt)) - return true; - } - return false; - } - bool mousePressed(const MouseButtonEvent& evt) override - { - for (auto listner : mListenerChain) - { - if (listner->mousePressed(evt)) - return true; - } - return false; - } - bool mouseReleased(const MouseButtonEvent& evt) override - { - for (auto listner : mListenerChain) - { - if (listner->mouseReleased(evt)) - return true; - } - return false; - } - bool textInput (const TextInputEvent& evt) override - { - for (auto listner : mListenerChain) - { - if (listner->textInput (evt)) - return true; - } - return false; - } -}; -/** @} */ -/** @} */ -/** @} */ -} - -#endif /* SAMPLES_COMMON_INCLUDE_INPUT_H_ */ diff --git a/Components/Bites/include/OgreSGTechniqueResolverListener.h b/Components/Bites/include/OgreSGTechniqueResolverListener.h deleted file mode 100644 index 85db17f00b7..00000000000 --- a/Components/Bites/include/OgreSGTechniqueResolverListener.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ - -#pragma once - -#include "OgreBitesPrerequisites.h" -#include "OgreRTShaderSystem.h" -#include "OgreMaterialManager.h" - -namespace OgreBites { -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup Bites -* @{ -*/ -/** Default implementation of a Listener to use with the Ogre::RTShader system. - When a target scheme callback is invoked with the shader generator scheme it tries to create an equivalent shader - based technique based on the default technique of the given material. -*/ -class _OgreBitesExport SGTechniqueResolverListener : public Ogre::MaterialManager::Listener { -public: - explicit SGTechniqueResolverListener(Ogre::RTShader::ShaderGenerator* pShaderGenerator); - - /** This is the hook point where shader based technique will be created. - It will be called whenever the material manager won't find appropriate technique - that satisfy the target scheme name. If the scheme name is out target RT Shader System - scheme name we will try to create shader generated technique for it. - */ - Ogre::Technique* handleSchemeNotFound(unsigned short schemeIndex, - const Ogre::String& schemeName, - Ogre::Material* originalMaterial, unsigned short lodIndex, - const Ogre::Renderable* rend) override; - - bool afterIlluminationPassesCreated(Ogre::Technique* tech) override; - - bool beforeIlluminationPassesCleared(Ogre::Technique* tech) override; - -protected: - Ogre::RTShader::ShaderGenerator* mShaderGenerator; // The shader generator instance. -}; -/** @} */ -/** @} */ -} diff --git a/Components/Bites/include/OgreStaticPluginLoader.h b/Components/Bites/include/OgreStaticPluginLoader.h deleted file mode 100644 index 352c2f390a8..00000000000 --- a/Components/Bites/include/OgreStaticPluginLoader.h +++ /dev/null @@ -1,39 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#ifndef __StaticPluginLoader_H__ -#define __StaticPluginLoader_H__ - -#include "OgreBitesPrerequisites.h" -#include "OgrePrerequisites.h" - -namespace OgreBites -{ - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Bites - * @{ - */ - /** Utility class for loading the plugins statically. - - When loading plugins statically, you are limited to loading plugins - that are known about at compile time. This class will load all built - plugins based on OgreBuildSettings.h - */ - class _OgreBitesExport StaticPluginLoader { - std::vector mPlugins; - - public: - /** Load all the enabled plugins */ - void load(); - - void unload(); - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/Components/Bites/include/OgreTrays.h b/Components/Bites/include/OgreTrays.h deleted file mode 100644 index 9501fcf3fe7..00000000000 --- a/Components/Bites/include/OgreTrays.h +++ /dev/null @@ -1,1211 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#ifndef __SdkTrays_H__ -#define __SdkTrays_H__ - -#include "OgreBitesPrerequisites.h" -#include "OgreOverlay.h" -#include "OgreOverlaySystem.h" -#include "OgreOverlayManager.h" -#include "OgreBorderPanelOverlayElement.h" -#include "OgreTextAreaOverlayElement.h" -#include "OgreFontManager.h" -#include "OgreTimer.h" -#include "OgreRoot.h" -#include "OgreCamera.h" -#include "OgreRenderWindow.h" -#include "OgreInput.h" - -#include - -namespace OgreBites -{ - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Bites - * @{ - */ - /** @defgroup Trays Trays - * Simplistic GUI System build with Overlays - * @{ - */ - enum TrayLocation /// enumerator values for widget tray anchoring locations - { - TL_TOPLEFT, - TL_TOP, - TL_TOPRIGHT, - TL_LEFT, - TL_CENTER, - TL_RIGHT, - TL_BOTTOMLEFT, - TL_BOTTOM, - TL_BOTTOMRIGHT, - TL_NONE - }; - - enum ButtonState /// enumerator values for button states - { - BS_UP, - BS_OVER, - BS_DOWN - }; - - // forward widget class declarations - class Widget; - class Button; - class SelectMenu; - class Label; - class Slider; - class CheckBox; - - /** - Listener class for responding to tray events. - */ - class _OgreBitesExport TrayListener - { - public: - - virtual ~TrayListener() {} - virtual void buttonHit(Button* button) {} - virtual void itemSelected(SelectMenu* menu) {} - virtual void labelHit(Label* label) {} - virtual void sliderMoved(Slider* slider) {} - virtual void checkBoxToggled(CheckBox* box) {} - virtual void okDialogClosed(const Ogre::DisplayString& message) {} - virtual void yesNoDialogClosed(const Ogre::DisplayString& question, bool yesHit) {} - }; - - /** - Abstract base class for all widgets. - */ - class _OgreBitesExport Widget - { - public: - - Widget(); - - virtual ~Widget() {} - - void cleanup(); - - /** - Static utility method to recursively delete an overlay element plus - all of its children from the system. - */ - static void nukeOverlayElement(Ogre::OverlayElement* element); - - /** - Static utility method to check if the cursor is over an overlay element. - */ - static bool isCursorOver(Ogre::OverlayElement* element, const Ogre::Vector2& cursorPos, Ogre::Real voidBorder = 0); - - /** - Static utility method used to get the cursor's offset from the center - of an overlay element in pixels. - */ - static Ogre::Vector2 cursorOffset(Ogre::OverlayElement* element, const Ogre::Vector2& cursorPos); - - /** - Static utility method used to get the width of a caption in a text area. - */ - static Ogre::Real getCaptionWidth(const Ogre::DisplayString& caption, Ogre::TextAreaOverlayElement* area); - - /** - Static utility method to cut off a string to fit in a text area. - */ - static void fitCaptionToArea(const Ogre::DisplayString& caption, Ogre::TextAreaOverlayElement* area, Ogre::Real maxWidth); - - Ogre::OverlayElement* getOverlayElement() - { - return mElement; - } - - const Ogre::String& getName() - { - return mElement->getName(); - } - - TrayLocation getTrayLocation() - { - return mTrayLoc; - } - - void hide() - { - mElement->hide(); - } - - void show() - { - mElement->show(); - } - - bool isVisible() - { - return mElement->isVisible(); - } - - // callbacks - - virtual void _cursorPressed(const Ogre::Vector2& cursorPos) {} - virtual void _cursorReleased(const Ogre::Vector2& cursorPos) {} - virtual void _cursorMoved(const Ogre::Vector2& cursorPos, float wheelDelta) {} - virtual void _focusLost() {} - - // internal methods used by TrayManager. do not call directly. - - void _assignToTray(TrayLocation trayLoc) { mTrayLoc = trayLoc; } - void _assignListener(TrayListener* listener) { mListener = listener; } - - protected: - - Ogre::OverlayElement* mElement; - TrayLocation mTrayLoc; - TrayListener* mListener; - }; - - typedef std::vector WidgetList; - - /** - Basic button class. - */ - class _OgreBitesExport Button : public Widget - { - public: - - /// Do not instantiate any widgets directly. Use TrayManager. - Button(const Ogre::String& name, const Ogre::DisplayString& caption, Ogre::Real width); - - virtual ~Button() {} - - const Ogre::DisplayString& getCaption() - { - return mTextArea->getCaption(); - } - - void setCaption(const Ogre::DisplayString& caption); - - const ButtonState& getState() { return mState; } - - void _cursorPressed(const Ogre::Vector2& cursorPos) override; - - void _cursorReleased(const Ogre::Vector2& cursorPos) override; - - void _cursorMoved(const Ogre::Vector2& cursorPos, float wheelDelta) override; - - void _focusLost() override; - - protected: - - void setState(const ButtonState& bs); - - ButtonState mState; - Ogre::BorderPanelOverlayElement* mBP; - Ogre::TextAreaOverlayElement* mTextArea; - bool mFitToContents; - }; - - /** - Scrollable text box widget. - */ - class _OgreBitesExport TextBox : public Widget - { - public: - - /// Do not instantiate any widgets directly. Use TrayManager. - TextBox(const Ogre::String& name, const Ogre::DisplayString& caption, Ogre::Real width, Ogre::Real height); - - void setPadding(Ogre::Real padding); - - Ogre::Real getPadding() - { - return mPadding; - } - - const Ogre::DisplayString& getCaption() - { - return mCaptionTextArea->getCaption(); - } - - void setCaption(const Ogre::DisplayString& caption) - { - mCaptionTextArea->setCaption(caption); - } - - const Ogre::DisplayString& getText() - { - return mText; - } - - /** - Sets text box content. Most of this method is for wordwrap. - */ - void setText(const Ogre::DisplayString& text); - - /** - Sets text box content horizontal alignment. - */ - void setTextAlignment(Ogre::TextAreaOverlayElement::Alignment ta); - - void clearText() - { - setText(""); - } - - void appendText(const Ogre::DisplayString& text) - { - setText(getText() + text); - } - - /** - Makes adjustments based on new padding, size, or alignment info. - */ - void refitContents(); - - /** - Sets how far scrolled down the text is as a percentage. - */ - void setScrollPercentage(Ogre::Real percentage); - - /** - Gets how far scrolled down the text is as a percentage. - */ - Ogre::Real getScrollPercentage() - { - return mScrollPercentage; - } - - /** - Gets how many lines of text can fit in this window. - */ - unsigned int getHeightInLines() - { - return (unsigned int) ((mElement->getHeight() - 2 * mPadding - mCaptionBar->getHeight() + 5) / mTextArea->getCharHeight()); - } - - void _cursorPressed(const Ogre::Vector2& cursorPos) override; - - void _cursorReleased(const Ogre::Vector2& cursorPos) override - { - mDragging = false; - } - - void _cursorMoved(const Ogre::Vector2& cursorPos, float wheelDelta) override; - - void _focusLost() override - { - mDragging = false; // stop dragging if cursor was lost - } - - protected: - - /** - Decides which lines to show. - */ - void filterLines(); - - Ogre::TextAreaOverlayElement* mTextArea; - Ogre::BorderPanelOverlayElement* mCaptionBar; - Ogre::TextAreaOverlayElement* mCaptionTextArea; - Ogre::BorderPanelOverlayElement* mScrollTrack; - Ogre::PanelOverlayElement* mScrollHandle; - Ogre::DisplayString mText; - Ogre::StringVector mLines; - Ogre::Real mPadding; - bool mDragging; - Ogre::Real mScrollPercentage; - Ogre::Real mDragOffset; - unsigned int mStartingLine; - }; - - /** - Basic selection menu widget. - */ - class _OgreBitesExport SelectMenu : public Widget - { - public: - - /// Do not instantiate any widgets directly. Use TrayManager. - SelectMenu(const Ogre::String& name, const Ogre::DisplayString& caption, Ogre::Real width, - Ogre::Real boxWidth, size_t maxItemsShown); - void copyItemsFrom(SelectMenu* other); - bool isExpanded() - { - return mExpanded; - } - - const Ogre::DisplayString& getCaption() - { - return mTextArea->getCaption(); - } - - void setCaption(const Ogre::DisplayString& caption); - - const Ogre::StringVector& getItems() - { - return mItems; - } - - size_t getNumItems() - { - return mItems.size(); - } - - void setItems(const Ogre::StringVector& items); - - void addItem(const Ogre::DisplayString& item) - { - mItems.push_back(item); - setItems(mItems); - } - - void insertItem(size_t index, const Ogre::DisplayString& item) - { - mItems.insert(mItems.begin() + index, item); - setItems(mItems); - } - - void removeItem(const Ogre::DisplayString& item); - - void removeItem(size_t index); - - void clearItems(); - - void selectItem(size_t index, bool notifyListener = true); - - bool containsItem(const Ogre::DisplayString& item); - - void selectItem(const Ogre::DisplayString& item, bool notifyListener = true); - - Ogre::DisplayString getSelectedItem(); - - int getSelectionIndex() - { - return mSelectionIndex; - } - - void _cursorPressed(const Ogre::Vector2& cursorPos) override; - - void _cursorReleased(const Ogre::Vector2& cursorPos) override - { - mDragging = false; - } - - void _cursorMoved(const Ogre::Vector2& cursorPos, float wheelDelta) override; - - void _focusLost() override - { - if (mExpandedBox->isVisible()) retract(); - } - - protected: - - /** - Internal method - sets which item goes at the top of the expanded menu. - */ - void setDisplayIndex(unsigned int index); - - /** - Internal method - cleans up an expanded menu. - */ - void retract(); - - Ogre::BorderPanelOverlayElement* mSmallBox; - Ogre::BorderPanelOverlayElement* mExpandedBox; - Ogre::TextAreaOverlayElement* mTextArea; - Ogre::TextAreaOverlayElement* mSmallTextArea; - Ogre::BorderPanelOverlayElement* mScrollTrack; - Ogre::PanelOverlayElement* mScrollHandle; - std::vector mItemElements; - size_t mMaxItemsShown; - size_t mItemsShown; - bool mCursorOver; - bool mExpanded; - bool mFitToContents; - bool mDragging; - Ogre::StringVector mItems; - int mSelectionIndex; - int mHighlightIndex; - int mDisplayIndex; - Ogre::Real mDragOffset; - }; - - /** - Basic label widget. - */ - class _OgreBitesExport Label : public Widget - { - public: - - /// Do not instantiate any widgets directly. Use TrayManager. - Label(const Ogre::String& name, const Ogre::DisplayString& caption, Ogre::Real width); - - const Ogre::DisplayString& getCaption() - { - return mTextArea->getCaption(); - } - - void setCaption(const Ogre::DisplayString& caption) - { - mTextArea->setCaption(caption); - } - - void _cursorPressed(const Ogre::Vector2& cursorPos) override; - - bool _isFitToTray() - { - return mFitToTray; - } - - protected: - - Ogre::TextAreaOverlayElement* mTextArea; - bool mFitToTray; - }; - - /** - Basic separator widget. - */ - class _OgreBitesExport Separator : public Widget - { - public: - - /// Do not instantiate any widgets directly. Use TrayManager. - Separator(const Ogre::String& name, Ogre::Real width); - - bool _isFitToTray() - { - return mFitToTray; - } - - protected: - - bool mFitToTray; - }; - - /** - Basic slider widget. - */ - class _OgreBitesExport Slider : public Widget - { - public: - - /// Do not instantiate any widgets directly. Use TrayManager. - Slider(const Ogre::String& name, const Ogre::DisplayString& caption, Ogre::Real width, Ogre::Real trackWidth, - Ogre::Real valueBoxWidth, Ogre::Real minValue, Ogre::Real maxValue, unsigned int snaps); - - /** - Sets the minimum value, maximum value, and the number of snapping points. - */ - void setRange(Ogre::Real minValue, Ogre::Real maxValue, unsigned int snaps, bool notifyListener = true); - - const Ogre::DisplayString& getValueCaption() - { - return mValueTextArea->getCaption(); - } - - /** - You can use this method to manually format how the value is displayed. - */ - void setValueCaption(const Ogre::DisplayString& caption) - { - mValueTextArea->setCaption(caption); - } - - void setValue(Ogre::Real value, bool notifyListener = true); - - Ogre::Real getValue() - { - return mValue; - } - - const Ogre::DisplayString& getCaption() - { - return mTextArea->getCaption(); - } - - void setCaption(const Ogre::DisplayString& caption); - - void _cursorPressed(const Ogre::Vector2& cursorPos) override; - - void _cursorReleased(const Ogre::Vector2& cursorPos) override; - - void _cursorMoved(const Ogre::Vector2& cursorPos, float wheelDelta) override; - - void _focusLost() override - { - mDragging = false; - } - - protected: - - /** - Internal method - given a percentage (from left to right), gets the - value of the nearest marker. - */ - Ogre::Real getSnappedValue(Ogre::Real percentage) - { - percentage = Ogre::Math::saturate(percentage); - unsigned int whichMarker = (unsigned int) (percentage * (mMaxValue - mMinValue) / mInterval + 0.5); - return float(whichMarker) * mInterval + mMinValue; - } - - Ogre::TextAreaOverlayElement* mTextArea; - Ogre::TextAreaOverlayElement* mValueTextArea; - Ogre::BorderPanelOverlayElement* mTrack; - Ogre::PanelOverlayElement* mHandle; - bool mDragging; - bool mFitToContents; - Ogre::Real mDragOffset; - Ogre::Real mValue; - Ogre::Real mMinValue; - Ogre::Real mMaxValue; - Ogre::Real mInterval; - }; - - /** - Basic parameters panel widget. - */ - class _OgreBitesExport ParamsPanel : public Widget - { - public: - - /// Do not instantiate any widgets directly. Use TrayManager. - ParamsPanel(const Ogre::String& name, Ogre::Real width, unsigned int lines); - - void setAllParamNames(const Ogre::StringVector& paramNames); - - const Ogre::StringVector& getAllParamNames() - { - return mNames; - } - - void setAllParamValues(const Ogre::StringVector& paramValues); - - void setParamValue(const Ogre::DisplayString& paramName, const Ogre::DisplayString& paramValue); - - void setParamValue(unsigned int index, const Ogre::DisplayString& paramValue); - - Ogre::DisplayString getParamValue(const Ogre::DisplayString& paramName); - - Ogre::DisplayString getParamValue(unsigned int index); - - const Ogre::StringVector& getAllParamValues() - { - return mValues; - } - - protected: - - /** - Internal method - updates text areas based on name and value lists. - */ - void updateText(); - - Ogre::TextAreaOverlayElement* mNamesArea; - Ogre::TextAreaOverlayElement* mValuesArea; - Ogre::StringVector mNames; - Ogre::StringVector mValues; - }; - - /** - Basic check box widget. - */ - class _OgreBitesExport CheckBox : public Widget - { - public: - - /// Do not instantiate any widgets directly. Use TrayManager. - CheckBox(const Ogre::String& name, const Ogre::DisplayString& caption, Ogre::Real width); - - const Ogre::DisplayString& getCaption() - { - return mTextArea->getCaption(); - } - - void setCaption(const Ogre::DisplayString& caption); - - bool isChecked() - { - return mX->isVisible(); - } - - void setChecked(bool checked, bool notifyListener = true); - - void toggle(bool notifyListener = true); - - void _cursorPressed(const Ogre::Vector2& cursorPos) override; - - void _cursorMoved(const Ogre::Vector2& cursorPos, float wheelDelta) override; - - void _focusLost() override; - - protected: - - Ogre::TextAreaOverlayElement* mTextArea; - Ogre::BorderPanelOverlayElement* mSquare; - Ogre::OverlayElement* mX; - bool mFitToContents; - bool mCursorOver; - }; - - /** - Custom, decorative widget created from a template. - */ - class _OgreBitesExport DecorWidget : public Widget - { - public: - - /// Do not instantiate any widgets directly. Use TrayManager. - DecorWidget(const Ogre::String& name, const Ogre::String& templateName); - }; - - /** - Basic progress bar widget. - */ - class _OgreBitesExport ProgressBar : public Widget - { - public: - - /// Do not instantiate any widgets directly. Use TrayManager. - ProgressBar(const Ogre::String& name, const Ogre::DisplayString& caption, Ogre::Real width, Ogre::Real commentBoxWidth); - - /** - Sets the progress as a percentage. - */ - void setProgress(Ogre::Real progress); - - /** - Gets the progress as a percentage. - */ - Ogre::Real getProgress() - { - return mProgress; - } - - const Ogre::DisplayString& getCaption() - { - return mTextArea->getCaption(); - } - - void setCaption(const Ogre::DisplayString& caption) - { - mTextArea->setCaption(caption); - } - - const Ogre::DisplayString& getComment() - { - return mCommentTextArea->getCaption(); - } - - void setComment(const Ogre::DisplayString& comment) - { - mCommentTextArea->setCaption(comment); - } - - - protected: - - Ogre::TextAreaOverlayElement* mTextArea; - Ogre::TextAreaOverlayElement* mCommentTextArea; - Ogre::OverlayElement* mMeter; - Ogre::OverlayElement* mFill; - Ogre::Real mProgress; - }; - - /** - Main class to manage a cursor, backdrop, trays and widgets. - */ - class _OgreBitesExport TrayManager : public TrayListener, public Ogre::ResourceGroupListener, public InputListener - { - public: - - /** - Creates backdrop, cursor, and trays. - */ - TrayManager(const Ogre::String& name, Ogre::RenderWindow* window, TrayListener* listener = 0); - - /** - Destroys background, cursor, widgets, and trays. - */ - virtual ~TrayManager(); - - /** - Converts a 2D screen coordinate (in pixels) to a 3D ray into the scene. - */ - static Ogre::Ray screenToScene(Ogre::Camera* cam, const Ogre::Vector2& pt); - - /** - Converts a 3D scene position to a 2D screen position (in relative screen size, 0.0-1.0). - */ - static Ogre::Vector2 sceneToScreen(Ogre::Camera* cam, const Ogre::Vector3& pt); - - // these methods get the underlying overlays and overlay elements - - Ogre::OverlayContainer* getTrayContainer(TrayLocation trayLoc) { return mTrays[trayLoc]; } - Ogre::Overlay* getBackdropLayer() { return mBackdropLayer; } - Ogre::Overlay* getTraysLayer() { return mTraysLayer; } - Ogre::Overlay* getCursorLayer() { return mCursorLayer; } - Ogre::OverlayContainer* getBackdropContainer() { return mBackdrop; } - Ogre::OverlayContainer* getCursorContainer() { return mCursor; } - Ogre::OverlayElement* getCursorImage() { return mCursor->getChild(mCursor->getName() + "/CursorImage"); } - - void setListener(TrayListener* listener) - { - mListener = listener; - } - - TrayListener* getListener() - { - return mListener; - } - - void showAll(); - - void hideAll(); - - /** - Displays specified material on backdrop, or the last material used if - none specified. Good for pause menus like in the browser. - */ - void showBackdrop(const Ogre::String& materialName = Ogre::BLANKSTRING); - - void hideBackdrop() - { - mBackdropLayer->hide(); - } - - /** - Displays specified material on cursor, or the last material used if - none specified. Used to change cursor type. - */ - void showCursor(const Ogre::String& materialName = Ogre::BLANKSTRING); - - void hideCursor(); - - /** - Updates cursor position based on unbuffered mouse state. This is necessary - because if the tray manager has been cut off from mouse events for a time, - the cursor position will be out of date. - */ - void refreshCursor(); - - void showTrays(); - - void hideTrays(); - - bool isCursorVisible() { return mCursorLayer->isVisible(); } - bool isBackdropVisible() { return mBackdropLayer->isVisible(); } - bool areTraysVisible() { return mTraysLayer->isVisible(); } - - /** - Sets horizontal alignment of a tray's contents. - */ - void setTrayWidgetAlignment(TrayLocation trayLoc, Ogre::GuiHorizontalAlignment gha); - - // padding and spacing methods - - void setWidgetPadding(Ogre::Real padding); - - void setWidgetSpacing(Ogre::Real spacing); - void setTrayPadding(Ogre::Real padding); - - virtual Ogre::Real getWidgetPadding() const { return mWidgetPadding; } - virtual Ogre::Real getWidgetSpacing() const { return mWidgetSpacing; } - virtual Ogre::Real getTrayPadding() const { return mTrayPadding; } - - /** - Fits trays to their contents and snaps them to their anchor locations. - */ - virtual void adjustTrays(); - - /** - Returns a 3D ray into the scene that is directly underneath the cursor. - */ - Ogre::Ray getCursorRay(Ogre::Camera* cam); - - Button* createButton(TrayLocation trayLoc, const Ogre::String& name, const Ogre::String& caption, Ogre::Real width = 0); - - TextBox* createTextBox(TrayLocation trayLoc, const Ogre::String& name, const Ogre::DisplayString& caption, - Ogre::Real width, Ogre::Real height); - - SelectMenu* createThickSelectMenu(TrayLocation trayLoc, const Ogre::String& name, const Ogre::DisplayString& caption, - Ogre::Real width, unsigned int maxItemsShown, const Ogre::StringVector& items = Ogre::StringVector()); - - SelectMenu* createLongSelectMenu(TrayLocation trayLoc, const Ogre::String& name, const Ogre::DisplayString& caption, - Ogre::Real width, Ogre::Real boxWidth, unsigned int maxItemsShown, const Ogre::StringVector& items = Ogre::StringVector()); - - SelectMenu* createLongSelectMenu(TrayLocation trayLoc, const Ogre::String& name, const Ogre::DisplayString& caption, - Ogre::Real boxWidth, unsigned int maxItemsShown, const Ogre::StringVector& items = Ogre::StringVector()); - - Label* createLabel(TrayLocation trayLoc, const Ogre::String& name, const Ogre::DisplayString& caption, Ogre::Real width = 0); - - Separator* createSeparator(TrayLocation trayLoc, const Ogre::String& name, Ogre::Real width = 0); - - Slider* createThickSlider(TrayLocation trayLoc, const Ogre::String& name, const Ogre::DisplayString& caption, - Ogre::Real width, Ogre::Real valueBoxWidth, Ogre::Real minValue, Ogre::Real maxValue, unsigned int snaps); - - Slider* createLongSlider(TrayLocation trayLoc, const Ogre::String& name, const Ogre::DisplayString& caption, Ogre::Real width, - Ogre::Real trackWidth, Ogre::Real valueBoxWidth, Ogre::Real minValue, Ogre::Real maxValue, unsigned int snaps); - - Slider* createLongSlider(TrayLocation trayLoc, const Ogre::String& name, const Ogre::DisplayString& caption, - Ogre::Real trackWidth, Ogre::Real valueBoxWidth, Ogre::Real minValue, Ogre::Real maxValue, unsigned int snaps); - - ParamsPanel* createParamsPanel(TrayLocation trayLoc, const Ogre::String& name, Ogre::Real width, unsigned int lines); - - ParamsPanel* createParamsPanel(TrayLocation trayLoc, const Ogre::String& name, Ogre::Real width, - const Ogre::StringVector& paramNames); - - CheckBox* createCheckBox(TrayLocation trayLoc, const Ogre::String& name, const Ogre::DisplayString& caption, - Ogre::Real width = 0); - - DecorWidget* createDecorWidget(TrayLocation trayLoc, const Ogre::String& name, const Ogre::String& templateName); - - ProgressBar* createProgressBar(TrayLocation trayLoc, const Ogre::String& name, const Ogre::DisplayString& caption, - Ogre::Real width, Ogre::Real commentBoxWidth); - - /** - Shows frame statistics widget set in the specified location. - */ - void showFrameStats(TrayLocation trayLoc, size_t place = -1); - - /** - Hides frame statistics widget set. - */ - void hideFrameStats(); - - bool areFrameStatsVisible() - { - return mFpsLabel != 0; - } - - /** - Toggles visibility of advanced statistics. - */ - void toggleAdvancedFrameStats() - { - if (mFpsLabel) labelHit(mFpsLabel); - } - - /** - Shows logo in the specified location. - */ - void showLogo(TrayLocation trayLoc, size_t place = -1); - - void hideLogo(); - - bool isLogoVisible() - { - return mLogo != 0; - } - - /** - Shows loading bar. Also takes job settings: the number of resource groups - to be initialised, the number of resource groups to be loaded, and the - proportion of the job that will be taken up by initialisation. Usually, - script parsing takes up most time, so the default value is 0.7. - */ - void showLoadingBar(unsigned int numGroupsInit = 1, unsigned int numGroupsLoad = 1, - Ogre::Real initProportion = 0.7f); - - void hideLoadingBar(); - - bool isLoadingBarVisible() - { - return mLoadBar != 0; - } - - /** - Pops up a message dialog with an OK button. - */ - void showOkDialog(const Ogre::DisplayString& caption, const Ogre::DisplayString& message); - - /** - Pops up a question dialog with Yes and No buttons. - */ - void showYesNoDialog(const Ogre::DisplayString& caption, const Ogre::DisplayString& question); - - /** - Hides whatever dialog is currently showing. - */ - void closeDialog(); - - /** - Determines if any dialog is currently visible. - */ - bool isDialogVisible(); - - /** - Gets a widget from a tray by name. - */ - Widget* getWidget(TrayLocation trayLoc, const Ogre::String& name); - - /** - Gets a widget by name. - */ - Widget* getWidget(const Ogre::String& name); - - /** - Gets the number of widgets in total. - */ - unsigned int getNumWidgets(); - - /** - Gets all the widgets of a specific tray. - */ - const WidgetList& getWidgets(TrayLocation trayLoc) const { - return mWidgets[trayLoc]; - } - - /** - Gets a widget's position in its tray. - */ - int locateWidgetInTray(Widget* widget); - - /** - Destroys a widget. - */ - void destroyWidget(Widget* widget); - - void destroyWidget(TrayLocation trayLoc, size_t place) - { - destroyWidget(mWidgets[trayLoc][place]); - } - - void destroyWidget(TrayLocation trayLoc, const Ogre::String& name) - { - destroyWidget(getWidget(trayLoc, name)); - } - - void destroyWidget(const Ogre::String& name) - { - destroyWidget(getWidget(name)); - } - - /** - Destroys all widgets in a tray. - */ - void destroyAllWidgetsInTray(TrayLocation trayLoc); - - /** - Destroys all widgets. - */ - void destroyAllWidgets(); - - /** - Adds a widget to a specified tray at given position, or at the end if unspecified or invalid - */ - void moveWidgetToTray(Widget* widget, TrayLocation trayLoc, size_t place = -1); - - void moveWidgetToTray(const Ogre::String& name, TrayLocation trayLoc, size_t place = -1) - { - moveWidgetToTray(getWidget(name), trayLoc, place); - } - - void moveWidgetToTray(TrayLocation currentTrayLoc, const Ogre::String& name, TrayLocation targetTrayLoc, - size_t place = -1) - { - moveWidgetToTray(getWidget(currentTrayLoc, name), targetTrayLoc, place); - } - - void moveWidgetToTray(TrayLocation currentTrayLoc, size_t currentPlace, TrayLocation targetTrayLoc, - size_t targetPlace = -1) - { - moveWidgetToTray(mWidgets[currentTrayLoc][currentPlace], targetTrayLoc, targetPlace); - } - - /** - Removes a widget from its tray. Same as moving it to the null tray. - */ - void removeWidgetFromTray(Widget* widget) - { - moveWidgetToTray(widget, TL_NONE); - } - - void removeWidgetFromTray(const Ogre::String& name) - { - removeWidgetFromTray(getWidget(name)); - } - - void removeWidgetFromTray(TrayLocation trayLoc, const Ogre::String& name) - { - removeWidgetFromTray(getWidget(trayLoc, name)); - } - - void removeWidgetFromTray(TrayLocation trayLoc, size_t place) - { - removeWidgetFromTray(mWidgets[trayLoc][place]); - } - - /** - Removes all widgets from a widget tray. - */ - void clearTray(TrayLocation trayLoc); - - /** - Removes all widgets from all widget trays. - */ - void clearAllTrays(); - - /** - Process frame events. Updates frame statistics widget set and deletes - all widgets queued for destruction. - */ - void frameRendered(const Ogre::FrameEvent& evt) override; - - void windowUpdate(); - - void resourceGroupScriptingStarted(const Ogre::String& groupName, size_t scriptCount) override - { - mLoadInc = mGroupInitProportion / float(scriptCount); - mLoadBar->setCaption("Parsing..."); - windowUpdate(); - } - - void scriptParseStarted(const Ogre::String& scriptName, bool& skipThisScript) override - { - mLoadBar->setComment(scriptName); - windowUpdate(); - } - - void scriptParseEnded(const Ogre::String& scriptName, bool skipped) override - { - mLoadBar->setProgress(mLoadBar->getProgress() + mLoadInc); - windowUpdate(); - } - - void resourceGroupLoadStarted(const Ogre::String& groupName, size_t resourceCount) override - { - mLoadInc = mGroupLoadProportion / float(resourceCount); - mLoadBar->setCaption("Loading..."); - windowUpdate(); - } - - void resourceLoadStarted(const Ogre::ResourcePtr& resource) override - { - mLoadBar->setComment(resource->getName()); - windowUpdate(); - } - - void resourceLoadEnded() override - { - mLoadBar->setProgress(mLoadBar->getProgress() + mLoadInc); - windowUpdate(); - } - - void customStageStarted(const Ogre::String& description) override - { - mLoadBar->setComment(description); - windowUpdate(); - } - - void customStageEnded() override - { - mLoadBar->setProgress(mLoadBar->getProgress() + mLoadInc); - windowUpdate(); - } - - /** - Toggles visibility of advanced statistics. - */ - void labelHit(Label* label) override; - - /** - Destroys dialog widgets, notifies listener, and ends high priority session. - */ - void buttonHit(Button* button) override; - - /** - Processes mouse button down events. Returns true if the event was - consumed and should not be passed on to other handlers. - */ - bool mousePressed(const MouseButtonEvent& evt) override; - - /** - Processes mouse button up events. Returns true if the event was - consumed and should not be passed on to other handlers. - */ - bool mouseReleased(const MouseButtonEvent& evt) override; - - /** - Updates cursor position. Returns true if the event was - consumed and should not be passed on to other handlers. - */ - bool mouseMoved(const MouseMotionEvent& evt) override; - - bool mouseWheelRolled(const MouseWheelEvent& evt) override; - - protected: - - /** - Internal method to prioritise / deprioritise expanded menus. - */ - void setExpandedMenu(SelectMenu* m); - - Ogre::String mName; // name of this tray system - Ogre::RenderWindow* mWindow; // render window - Ogre::Overlay* mBackdropLayer; // backdrop layer - Ogre::Overlay* mTraysLayer; // widget layer - Ogre::Overlay* mPriorityLayer; // top priority layer - Ogre::Overlay* mCursorLayer; // cursor layer - Ogre::OverlayContainer* mBackdrop; // backdrop - Ogre::OverlayContainer* mTrays[10]; // widget trays - WidgetList mWidgets[10]; // widgets - WidgetList mWidgetDeathRow; // widget queue for deletion - Ogre::OverlayContainer* mCursor; // cursor - TrayListener* mListener; // tray listener - Ogre::Real mWidgetPadding; // widget padding - Ogre::Real mWidgetSpacing; // widget spacing - Ogre::Real mTrayPadding; // tray padding - bool mTrayDrag; // a mouse press was initiated on a tray - SelectMenu* mExpandedMenu; // top priority expanded menu widget - TextBox* mDialog; // top priority dialog widget - Ogre::OverlayContainer* mDialogShade; // top priority dialog shade - Button* mOk; // top priority OK button - Button* mYes; // top priority Yes button - Button* mNo; // top priority No button - bool mCursorWasVisible; // cursor state before showing dialog - Label* mFpsLabel; // FPS label - ParamsPanel* mStatsPanel; // frame stats panel - DecorWidget* mLogo; // logo - ProgressBar* mLoadBar; // loading bar - Ogre::Real mGroupInitProportion; // proportion of load job assigned to initialising one resource group - Ogre::Real mGroupLoadProportion; // proportion of load job assigned to loading one resource group - Ogre::Real mLoadInc; // loading increment - Ogre::GuiHorizontalAlignment mTrayWidgetAlign[10]; // tray widget alignments - Ogre::Timer* mTimer; // Root::getSingleton().getTimer() - unsigned long mLastStatUpdateTime; // The last time the stat text were updated - Ogre::Vector2 mCursorPos; // current cursor position - - }; - /** @} */ - /** @} */ - /** @} */ -} -#endif diff --git a/Components/Bites/include/OgreWindowEventUtilities.h b/Components/Bites/include/OgreWindowEventUtilities.h deleted file mode 100644 index db20d4a1745..00000000000 --- a/Components/Bites/include/OgreWindowEventUtilities.h +++ /dev/null @@ -1,169 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OgreWindowEventUtils_H__ -#define __OgreWindowEventUtils_H__ - -#include "OgrePrerequisites.h" -#include "OgreBitesPrerequisites.h" -#include "OgrePlatform.h" -#include "OgreCommon.h" -#include "OgreHeaderPrefix.h" - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 -#include -#endif - -namespace OgreBites -{ - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Bites - * @{ - */ - /** - Callback class used to send out window events to client app - */ - class _OgreBitesExport WindowEventListener - { - public: - virtual ~WindowEventListener() {} - - /** - Window has moved position - @param rw - The RenderWindow which created this events - */ - virtual void windowMoved(Ogre::RenderWindow* rw) { (void)rw; } - - /** - Window has resized - @param rw - The RenderWindow which created this events - */ - virtual void windowResized(Ogre::RenderWindow* rw) { (void)rw; } - - /** - Window is closing (Only triggered if user pressed the [X] button) - @param rw - The RenderWindow which created this events - @return True will close the window(default). - */ - virtual bool windowClosing(Ogre::RenderWindow* rw) { return true; } - - /** - - Window has been closed (Only triggered if user pressed the [X] button) - @param rw - The RenderWindow which created this events - @note - The window has not actually close yet when this event triggers. It's only closed after - all windowClosed events are triggered. This allows apps to deinitialise properly if they - have services that needs the window to exist when deinitialising. - */ - virtual void windowClosed(Ogre::RenderWindow* rw) { (void)rw; } - - /** - Window has lost/gained focus - @param rw - The RenderWindow which created this events - */ - virtual void windowFocusChange(Ogre::RenderWindow* rw) { (void)rw; } - }; - - /** - Utility class to handle Window Messages - - This only provides a minimal implementation for moving/ resizing windows. - @note For input handling and proper platform integration rather use SDL2/ Qt/ whatever. - @see ApplicationContext - */ - class _OgreBitesExport WindowEventUtilities - { - public: - /** - Call this once per frame. This will update all registered RenderWindows. - */ - static void messagePump(); - - /** - Add a listener to listen to renderwindow events (multiple listener's per renderwindow is fine) - The same listener can listen to multiple windows, as the Window Pointer is sent along with - any messages. - @param window - The RenderWindow you are interested in monitoring - @param listener - Your callback listener - */ - static void addWindowEventListener( Ogre::RenderWindow* window, WindowEventListener* listener ); - - /** - Remove previously added listener - @param window - The RenderWindow you registered with - @param listener - The listener registered - */ - static void removeWindowEventListener( Ogre::RenderWindow* window, WindowEventListener* listener ); - - /** - - Call upon creation of Ogre windows. You are free to add your - external windows here too if needed. - @param window - The RenderWindow to monitor - */ - static void _addRenderWindow(Ogre::RenderWindow* window); - - /** - Called upon deletion of previously registered windows. - @param window - The RenderWindow to remove from list - */ - static void _removeRenderWindow(Ogre::RenderWindow* window); - - // backwards compatibility -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - //! Internal winProc (RenderWindow's use this when creating the Win32 Window) - static LRESULT CALLBACK _WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); -#endif - }; - /** @} */ - /** @} */ -} - -namespace Ogre -{ - // backwards compatibility - typedef OGRE_DEPRECATED OgreBites::WindowEventListener WindowEventListener; - typedef OGRE_DEPRECATED OgreBites::WindowEventUtilities WindowEventUtilities; -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/Components/Bites/misc/GLX_backdrop.png b/Components/Bites/misc/GLX_backdrop.png deleted file mode 100644 index ae51b7d7f98..00000000000 Binary files a/Components/Bites/misc/GLX_backdrop.png and /dev/null differ diff --git a/Components/Bites/misc/OgreWin32Resources.rc b/Components/Bites/misc/OgreWin32Resources.rc deleted file mode 100644 index b078b790b82..00000000000 --- a/Components/Bites/misc/OgreWin32Resources.rc +++ /dev/null @@ -1,155 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include - -#ifdef IDC_OGRE_ICON -#undef IDC_OGRE_ICON -#endif -#define IDC_OGRE_ICON (-1) - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// Neutral resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEU) -#ifdef _WIN32 -LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Bitmap -// - -IDB_SPLASH BITMAP "ogrelogo.bmp" - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_OGREICON ICON "ogre.ico" -#endif // Neutral resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// English (U.K.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENG) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_UK -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include \r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_DLG_CONFIG DIALOGEX 0, 0, 329, 270 -STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION -CAPTION "OGRE Engine Rendering Setup" -FONT 8, "MS Sans Serif", 0, 0, 0x0 -BEGIN - DEFPUSHBUTTON "&OK",IDOK,205,253,60,14 - PUSHBUTTON "&Cancel",IDCANCEL,267,253,60,14 - LTEXT "Rendering Subsystem:",IDC_OGRE_ICON,21,76,73,12 - COMBOBOX IDC_CBO_RENDERSYSTEM,95,74,219,57,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP - GROUPBOX "Rendering System Options",IDC_OPTFRAME,5,96,322,157 - LISTBOX IDC_LST_OPTIONS,13,107,310,124,LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP - RTEXT "[Click On An Option]:",IDC_LBL_OPTION,14,237,125,11 - COMBOBOX IDC_CBO_OPTION,143,235,180,94,CBS_DROPDOWNLIST | WS_DISABLED | WS_VSCROLL | WS_TABSTOP - CONTROL IDB_SPLASH,IDC_OGRE_ICON,"Static",SS_BITMAP,0,0,327,66 -END - -IDD_DLG_ERROR DIALOG 0, 0, 243, 178 -STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION -CAPTION "Error" -FONT 8, "MS Sans Serif" -BEGIN - DEFPUSHBUTTON "&Close",IDOK,81,157,80,14 - LTEXT "The Ogre engine has encountered an error from which it cannot recover. The last message was:",IDC_OGRE_ICON,7,7,229,19 - LTEXT "",IDC_ERRMSG,17,29,209,84,SS_SUNKEN - LTEXT "If you cannot resolve this issue yourself, please report it through the web site at http://www.ogre3d.org.",IDC_OGRE_ICON,7,118,229,19 - LTEXT "If you report the error, please include details of your hardware setup, and attach a copy of the 'ogre.log' file which you will find in the local folder.",IDC_OGRE_ICON,7,138,229,17 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO -BEGIN - IDD_DLG_CONFIG, DIALOG - BEGIN - RIGHTMARGIN, 300 - BOTTOMMARGIN, 267 - END - - IDD_DLG_ERROR, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 236 - TOPMARGIN, 7 - BOTTOMMARGIN, 171 - END -END -#endif // APSTUDIO_INVOKED - -#endif // English (U.K.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/Components/Bites/misc/ogre.ico b/Components/Bites/misc/ogre.ico deleted file mode 100644 index f8afd373679..00000000000 Binary files a/Components/Bites/misc/ogre.ico and /dev/null differ diff --git a/Components/Bites/misc/ogrelogo.bmp b/Components/Bites/misc/ogrelogo.bmp deleted file mode 100644 index 48a39b17a48..00000000000 Binary files a/Components/Bites/misc/ogrelogo.bmp and /dev/null differ diff --git a/Components/Bites/misc/ogrelogo.png b/Components/Bites/misc/ogrelogo.png deleted file mode 100644 index 9e81eff6ae7..00000000000 Binary files a/Components/Bites/misc/ogrelogo.png and /dev/null differ diff --git a/Components/Bites/src/OgreAdvancedRenderControls.cpp b/Components/Bites/src/OgreAdvancedRenderControls.cpp deleted file mode 100644 index 3c1af1983d1..00000000000 --- a/Components/Bites/src/OgreAdvancedRenderControls.cpp +++ /dev/null @@ -1,257 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#include "OgreAdvancedRenderControls.h" -#include "OgreTextureManager.h" -#include "OgreMaterialManager.h" - -#include "OgreTrays.h" - -namespace OgreBites { -AdvancedRenderControls::AdvancedRenderControls(TrayManager* trayMgr, Ogre::Camera* cam) - : mCamera(cam), mTrayMgr(trayMgr) { - mRoot = Ogre::Root::getSingletonPtr(); - - // create a params panel for displaying sample details - Ogre::StringVector items; - items.push_back("cam.pX"); - items.push_back("cam.pY"); - items.push_back("cam.pZ"); - items.push_back(""); - items.push_back("cam.oW"); - items.push_back("cam.oX"); - items.push_back("cam.oY"); - items.push_back("cam.oZ"); - items.push_back(""); - items.push_back("Filtering"); - items.push_back("Poly Mode"); - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - mShaderGenerator = Ogre::RTShader::ShaderGenerator::getSingletonPtr(); - items.push_back("RT Shaders"); - items.push_back("Lighting Model"); - items.push_back("Compact Policy"); - items.push_back("Generated VS"); - items.push_back("Generated FS"); -#endif - - mDetailsPanel = mTrayMgr->createParamsPanel(TL_NONE, "DetailsPanel", 200, items); - mDetailsPanel->hide(); - - mDetailsPanel->setParamValue(9, "Bilinear"); - mDetailsPanel->setParamValue(10, "Solid"); - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - mDetailsPanel->setParamValue(11, "Off"); - if (!mRoot->getRenderSystem()->getCapabilities()->hasCapability(Ogre::RSC_FIXED_FUNCTION)) { - mDetailsPanel->setParamValue(11, "On"); - } - - mDetailsPanel->setParamValue(12, "Pixel"); - mDetailsPanel->setParamValue(13, "Low"); - mDetailsPanel->setParamValue(14, "0"); - mDetailsPanel->setParamValue(15, "0"); -#endif -} - -AdvancedRenderControls::~AdvancedRenderControls() { - mTrayMgr->destroyWidget(mDetailsPanel); -} - -bool AdvancedRenderControls::keyPressed(const KeyboardEvent& evt) { - if (mTrayMgr->isDialogVisible()) - return true; // don't process any more keys if dialog is up - - int key = evt.keysym.sym; - - if (key == 'f') // toggle visibility of advanced frame stats - { - mTrayMgr->toggleAdvancedFrameStats(); - } else if (key == 'g') // toggle visibility of even rarer debugging details - { - if (mDetailsPanel->getTrayLocation() == TL_NONE) { - mTrayMgr->moveWidgetToTray(mDetailsPanel, TL_TOPRIGHT, 0); - mDetailsPanel->show(); - } else { - mTrayMgr->removeWidgetFromTray(mDetailsPanel); - mDetailsPanel->hide(); - } - } else if (key == 't') // cycle texture filtering mode - { - Ogre::String newVal; - Ogre::TextureFilterOptions tfo; - unsigned int aniso; - - Ogre::FilterOptions mip = Ogre::MaterialManager::getSingleton().getDefaultTextureFiltering(Ogre::FT_MIP); - - switch (Ogre::MaterialManager::getSingleton().getDefaultTextureFiltering(Ogre::FT_MAG)) { - case Ogre::FO_LINEAR: - if (mip == Ogre::FO_POINT) { - newVal = "Trilinear"; - tfo = Ogre::TFO_TRILINEAR; - aniso = 1; - } else { - newVal = "Anisotropic"; - tfo = Ogre::TFO_ANISOTROPIC; - aniso = 8; - } - break; - case Ogre::FO_ANISOTROPIC: - newVal = "None"; - tfo = Ogre::TFO_NONE; - aniso = 1; - break; - default: - newVal = "Bilinear"; - tfo = Ogre::TFO_BILINEAR; - aniso = 1; - break; - } - - Ogre::MaterialManager::getSingleton().setDefaultTextureFiltering(tfo); - Ogre::MaterialManager::getSingleton().setDefaultAnisotropy(aniso); - mDetailsPanel->setParamValue(9, newVal); - } else if (key == 'r') // cycle polygon rendering mode - { - Ogre::String newVal; - Ogre::PolygonMode pm; - - switch (mCamera->getPolygonMode()) { - case Ogre::PM_SOLID: - newVal = "Wireframe"; - pm = Ogre::PM_WIREFRAME; - break; - case Ogre::PM_WIREFRAME: - newVal = "Points"; - pm = Ogre::PM_POINTS; - break; - default: - newVal = "Solid"; - pm = Ogre::PM_SOLID; - break; - } - - mCamera->setPolygonMode(pm); - mDetailsPanel->setParamValue(10, newVal); - } else if (key == SDLK_F5) // refresh all textures - { - Ogre::TextureManager::getSingleton().reloadAll(); - } - else if (key == SDLK_F6) // take a screenshot - { - mCamera->getViewport()->getTarget()->writeContentsToTimestampedFile("screenshot", ".png"); - } - // Toggle visibility of profiler window - else if (key == 'p') - { - if (auto prof = Ogre::Profiler::getSingletonPtr()) - prof->setEnabled(!prof->getEnabled()); - } -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - // Toggle schemes. - else if (key == SDLK_F2) { - if (mRoot->getRenderSystem()->getCapabilities()->hasCapability(Ogre::RSC_FIXED_FUNCTION)) { - Ogre::Viewport* mainVP = mCamera->getViewport(); - const Ogre::String& curMaterialScheme = mainVP->getMaterialScheme(); - - if (curMaterialScheme == Ogre::MSN_DEFAULT) - { - mainVP->setMaterialScheme(Ogre::MSN_SHADERGEN); - mDetailsPanel->setParamValue(11, "On"); - } - else if (curMaterialScheme == Ogre::MSN_SHADERGEN) - { - mainVP->setMaterialScheme(Ogre::MSN_DEFAULT); - mDetailsPanel->setParamValue(11, "Off"); - } - } - } -# ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS - // Toggles per pixel per light model. - else if (key == SDLK_F3) { - static bool useFFPLighting = true; - - //![rtss_per_pixel] - // Grab the scheme render state. - Ogre::RTShader::RenderState* schemRenderState = mShaderGenerator->getRenderState(Ogre::MSN_SHADERGEN); - - // Add per vertex lighting sub render state to the global scheme render state. - // It will override the default lighting sub render state. - if (useFFPLighting) { - auto perPixelLightModel = mShaderGenerator->createSubRenderState(Ogre::RTShader::SRS_PER_VERTEX_LIGHTING); - - schemRenderState->addTemplateSubRenderState(perPixelLightModel); - } - //![rtss_per_pixel] - - // Search the per pixel sub render state and remove it. - else { - if (auto srs = schemRenderState->getSubRenderState(Ogre::RTShader::SRS_PER_VERTEX_LIGHTING)) - { - schemRenderState->removeSubRenderState(srs); - } - } - - // Invalidate the scheme in order to re-generate all shaders based technique related to this - // scheme. - mShaderGenerator->invalidateScheme(Ogre::MSN_SHADERGEN); - - // Update UI. - if (!useFFPLighting) - mDetailsPanel->setParamValue(12, "Pixel"); - else - mDetailsPanel->setParamValue(12, "Vertex"); - useFFPLighting = !useFFPLighting; - } -# endif - // Switch vertex shader outputs compaction policy. - else if (key == SDLK_F4) { - switch (mShaderGenerator->getVertexShaderOutputsCompactPolicy()) { - case Ogre::RTShader::VSOCP_LOW: - mShaderGenerator->setVertexShaderOutputsCompactPolicy(Ogre::RTShader::VSOCP_MEDIUM); - mDetailsPanel->setParamValue(13, "Medium"); - break; - - case Ogre::RTShader::VSOCP_MEDIUM: - mShaderGenerator->setVertexShaderOutputsCompactPolicy(Ogre::RTShader::VSOCP_HIGH); - mDetailsPanel->setParamValue(13, "High"); - break; - - case Ogre::RTShader::VSOCP_HIGH: - mShaderGenerator->setVertexShaderOutputsCompactPolicy(Ogre::RTShader::VSOCP_LOW); - mDetailsPanel->setParamValue(13, "Low"); - break; - } - - // Invalidate the scheme in order to re-generate all shaders based technique related to this - // scheme. - mShaderGenerator->invalidateScheme(Ogre::MSN_SHADERGEN); - } -#endif // INCLUDE_RTSHADER_SYSTEM - - return InputListener::keyPressed(evt); -} - -void AdvancedRenderControls::frameRendered(const Ogre::FrameEvent& evt) { - using namespace Ogre; - if (!mTrayMgr->isDialogVisible() && mDetailsPanel->isVisible()) - { - // if details panel is visible, then update its contents - mDetailsPanel->setParamValue(0, Ogre::StringConverter::toString(mCamera->getDerivedPosition().x)); - mDetailsPanel->setParamValue(1, Ogre::StringConverter::toString(mCamera->getDerivedPosition().y)); - mDetailsPanel->setParamValue(2, Ogre::StringConverter::toString(mCamera->getDerivedPosition().z)); - mDetailsPanel->setParamValue(4, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().w)); - mDetailsPanel->setParamValue(5, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().x)); - mDetailsPanel->setParamValue(6, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().y)); - mDetailsPanel->setParamValue(7, Ogre::StringConverter::toString(mCamera->getDerivedOrientation().z)); - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - mDetailsPanel->setParamValue(14, StringConverter::toString(mShaderGenerator->getShaderCount(GPT_VERTEX_PROGRAM))); - mDetailsPanel->setParamValue(15, StringConverter::toString(mShaderGenerator->getShaderCount(GPT_FRAGMENT_PROGRAM))); -#endif - } -} - -} /* namespace OgreBites */ diff --git a/Components/Bites/src/OgreApplicationContextAndroid.cpp b/Components/Bites/src/OgreApplicationContextAndroid.cpp deleted file mode 100644 index a95fea6e039..00000000000 --- a/Components/Bites/src/OgreApplicationContextAndroid.cpp +++ /dev/null @@ -1,127 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. - -#include "OgreApplicationContext.h" - -#include "OgreRoot.h" -#include "OgreRenderWindow.h" - -#include "OgreArchiveManager.h" -#include "OgreFileSystem.h" -#include "OgreZip.h" - -namespace OgreBites { - -ApplicationContextAndroid::ApplicationContextAndroid(const Ogre::String& appName) : ApplicationContextBase(appName) -{ - mAAssetMgr = NULL; - mAConfig = NULL; -} - -NativeWindowPair ApplicationContextAndroid::createWindow(const Ogre::String& name, Ogre::uint32 w, Ogre::uint32 h, Ogre::NameValuePairList miscParams) -{ - miscParams["externalWindowHandle"] = Ogre::StringConverter::toString(reinterpret_cast(mWindows[0].native)); - miscParams["androidConfig"] = Ogre::StringConverter::toString(reinterpret_cast(mAConfig)); - miscParams["preserveContext"] = "true"; //Optionally preserve the gl context, prevents reloading all resources, this is false by default - - auto p = mRoot->getRenderSystem()->getRenderWindowDescription(); - miscParams.insert(p.miscParams.begin(), p.miscParams.end()); - p.miscParams = miscParams; - p.name = name; - - mWindows[0].render = mRoot->createRenderWindow(p); - return mWindows[0]; -} - -void ApplicationContextAndroid::initAppForAndroid(AAssetManager* assetMgr, ANativeWindow* window) -{ - mAConfig = AConfiguration_new(); - AConfiguration_fromAssetManager(mAConfig, assetMgr); - mAAssetMgr = assetMgr; - - mWindows.resize(1); - mWindows[0].native = window; - - initApp(); -} - -void ApplicationContextAndroid::_fireInputEventAndroid(AInputEvent* event, int wheel) { - Event evt = {0}; - - static TouchFingerEvent lastTouch = {0}; - - if(wheel) { - evt.type = MOUSEWHEEL; - evt.wheel.y = wheel; - _fireInputEvent(evt, 0); - lastTouch.fingerId = -1; // prevent move-jump after pinch is over - return; - } - - if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) { - int32_t action = AMOTION_EVENT_ACTION_MASK & AMotionEvent_getAction(event); - - switch (action) { - case AMOTION_EVENT_ACTION_DOWN: - evt.type = FINGERDOWN; - break; - case AMOTION_EVENT_ACTION_UP: - evt.type = FINGERUP; - break; - case AMOTION_EVENT_ACTION_MOVE: - evt.type = FINGERMOTION; - break; - default: - return; - } - - Ogre::RenderWindow* win = getRenderWindow(); - - evt.tfinger.fingerId = AMotionEvent_getPointerId(event, 0); - evt.tfinger.x = AMotionEvent_getRawX(event, 0) / win->getWidth() * win->getViewPointToPixelScale(); - evt.tfinger.y = AMotionEvent_getRawY(event, 0) / win->getHeight() * win->getViewPointToPixelScale(); - - if(evt.type == FINGERMOTION) { - if(evt.tfinger.fingerId != lastTouch.fingerId) - return; // wrong finger - - evt.tfinger.dx = evt.tfinger.x - lastTouch.x; - evt.tfinger.dy = evt.tfinger.y - lastTouch.y; - } - - lastTouch = evt.tfinger; - } else { - if(AKeyEvent_getKeyCode(event) != AKEYCODE_BACK) - return; - - evt.type = AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_DOWN ? KEYDOWN : KEYUP; - evt.key.keysym.sym = SDLK_ESCAPE; - } - - _fireInputEvent(evt, 0); -} - -void ApplicationContextAndroid::locateResources() -{ - Ogre::ArchiveManager::getSingleton().addArchiveFactory( new Ogre::APKFileSystemArchiveFactory(mAAssetMgr) ); - Ogre::ArchiveManager::getSingleton().addArchiveFactory( new Ogre::APKZipArchiveFactory(mAAssetMgr) ); - ApplicationContextBase::locateResources(); -} - -void ApplicationContextAndroid::shutdown() -{ - ApplicationContextBase::shutdown(); - AConfiguration_delete(mAConfig); -} - -void ApplicationContextAndroid::pollEvents() -{ - for(auto& w : mWindows) - { - w.render->windowMovedOrResized(); - windowResized(w.render); - } -} - -} diff --git a/Components/Bites/src/OgreApplicationContextBase.cpp b/Components/Bites/src/OgreApplicationContextBase.cpp deleted file mode 100644 index 848179bf038..00000000000 --- a/Components/Bites/src/OgreApplicationContextBase.cpp +++ /dev/null @@ -1,559 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. - -#include "OgreApplicationContextBase.h" - -#include "OgreRoot.h" -#include "OgreGpuProgramManager.h" -#include "OgreConfigFile.h" -#include "OgreRenderWindow.h" -#include "OgreViewport.h" -#include "OgreOverlaySystem.h" -#include "OgreDataStream.h" -#include "OgreBitesConfigDialog.h" -#include "OgreWindowEventUtilities.h" -#include "OgreSceneNode.h" -#include "OgreCamera.h" - -#include "OgreArchiveManager.h" - -#include "OgreConfigPaths.h" - -namespace OgreBites { - -static const char* SHADER_CACHE_FILENAME = "cache.bin"; - -ApplicationContextBase::ApplicationContextBase(const Ogre::String& appName) -{ - mAppName = appName; - mFSLayer = new Ogre::FileSystemLayer(mAppName); - - if (char* val = getenv("OGRE_CONFIG_DIR")) - { - Ogre::String configDir = Ogre::StringUtil::standardisePath(val); - mFSLayer->setConfigPaths({ configDir }); - } - - mRoot = NULL; - mOverlaySystem = NULL; - mFirstRun = true; - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - mMaterialMgrListener = NULL; - mShaderGenerator = NULL; -#endif -} - -ApplicationContextBase::~ApplicationContextBase() -{ - delete mFSLayer; -} - -void ApplicationContextBase::initApp() -{ - createRoot(); - if (!oneTimeConfig()) return; - -#if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID - // if the context was reconfigured, set requested renderer - if (!mFirstRun) mRoot->setRenderSystem(mRoot->getRenderSystemByName(mNextRenderer)); -#endif - - setup(); - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - mRoot->saveConfig(); - - Ogre::Root::getSingleton().getRenderSystem()->_initRenderTargets(); - - // Clear event times - Ogre::Root::getSingleton().clearEventTimes(); -#endif -} - -void ApplicationContextBase::closeApp() -{ - shutdown(); - if (mRoot) - { -#if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID - mRoot->saveConfig(); -#endif - OGRE_DELETE mRoot; - mRoot = NULL; - } - -#ifdef OGRE_BITES_STATIC_PLUGINS - mStaticPluginLoader.unload(); -#endif -} - -bool ApplicationContextBase::initialiseRTShaderSystem() -{ -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - if (Ogre::RTShader::ShaderGenerator::initialize()) - { - mShaderGenerator = Ogre::RTShader::ShaderGenerator::getSingletonPtr(); - - // Create and register the material manager listener if it doesn't exist yet. - if (!mMaterialMgrListener) { - mMaterialMgrListener = new SGTechniqueResolverListener(mShaderGenerator); - Ogre::MaterialManager::getSingleton().addListener(mMaterialMgrListener); - } - - return true; - } -#endif - return false; -} - -void ApplicationContextBase::setRTSSWriteShadersToDisk(bool write) -{ -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - if(!write) { - mShaderGenerator->setShaderCachePath(""); - return; - } - - // Set shader cache path. -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - auto subdir = ""; -#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE - auto subdir = "org.ogre3d.RTShaderCache/"; -#else - auto subdir = "RTShaderCache"; -#endif - auto path = mFSLayer->getWritablePath(subdir); - if (!Ogre::FileSystemLayer::fileExists(path)) - { - Ogre::FileSystemLayer::createDirectory(path); - } - mShaderGenerator->setShaderCachePath(path); -#endif -} - -void ApplicationContextBase::destroyRTShaderSystem() -{ -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - //mShaderGenerator->removeAllShaderBasedTechniques(); - //mShaderGenerator->flushShaderCache(); - - // Restore default scheme. - Ogre::MaterialManager::getSingleton().setActiveScheme(Ogre::MaterialManager::DEFAULT_SCHEME_NAME); - - // Unregister the material manager listener. - if (mMaterialMgrListener != NULL) - { - Ogre::MaterialManager::getSingleton().removeListener(mMaterialMgrListener); - delete mMaterialMgrListener; - mMaterialMgrListener = NULL; - } - - // Destroy RTShader system. - if (mShaderGenerator != NULL) - { - Ogre::RTShader::ShaderGenerator::destroy(); - mShaderGenerator = NULL; - } -#endif -} - -void ApplicationContextBase::setup() -{ - mRoot->initialise(false); - createWindow(mAppName); - - locateResources(); - initialiseRTShaderSystem(); - loadResources(); - - // adds context as listener to process context-level (above the sample level) events - mRoot->addFrameListener(this); -} - -void ApplicationContextBase::createRoot() -{ -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - mRoot = OGRE_NEW Ogre::Root(""); -#else - Ogre::String pluginsPath; -# ifndef OGRE_BITES_STATIC_PLUGINS - pluginsPath = mFSLayer->getConfigFilePath("plugins.cfg"); - - if (!Ogre::FileSystemLayer::fileExists(pluginsPath)) - { - pluginsPath = Ogre::FileSystemLayer::resolveBundlePath(OGRE_CONFIG_DIR "/plugins.cfg"); - } -# endif - - mRoot = OGRE_NEW Ogre::Root(pluginsPath, mFSLayer->getWritablePath("ogre.cfg"), - mFSLayer->getWritablePath("ogre.log")); -#endif - -#ifdef OGRE_BITES_STATIC_PLUGINS - mStaticPluginLoader.load(); -#endif - mOverlaySystem = OGRE_NEW Ogre::OverlaySystem(); -} - -bool ApplicationContextBase::oneTimeConfig() -{ - if(mRoot->getAvailableRenderers().empty()) - { - Ogre::LogManager::getSingleton().logError("No RenderSystems available"); - return false; - } - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - mRoot->setRenderSystem(mRoot->getAvailableRenderers().front()); -#else - if (!mRoot->restoreConfig()) { - return mRoot->showConfigDialog(OgreBites::getNativeConfigDialog()); - } -#endif - return true; -} - -void ApplicationContextBase::createDummyScene() -{ - mWindows[0].render->removeAllViewports(); - Ogre::SceneManager* sm = mRoot->createSceneManager("DefaultSceneManager", "DummyScene"); - sm->addRenderQueueListener(mOverlaySystem); - Ogre::Camera* cam = sm->createCamera("DummyCamera"); - sm->getRootSceneNode()->attachObject(cam); - mWindows[0].render->addViewport(cam); -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - // Initialize shader generator. - // Must be before resource loading in order to allow parsing extended material attributes. - if (!initialiseRTShaderSystem()) - { - OGRE_EXCEPT(Ogre::Exception::ERR_FILE_NOT_FOUND, - "Shader Generator Initialization failed - Core shader libs path not found", - "ApplicationContextBase::createDummyScene"); - } - - mShaderGenerator->addSceneManager(sm); -#endif // OGRE_BUILD_COMPONENT_RTSHADERSYSTEM -} - -void ApplicationContextBase::destroyDummyScene() -{ - if(!mRoot->hasSceneManager("DummyScene")) - return; - - Ogre::SceneManager* dummyScene = mRoot->getSceneManager("DummyScene"); -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - mShaderGenerator->removeSceneManager(dummyScene); -#endif - dummyScene->removeRenderQueueListener(mOverlaySystem); - mWindows[0].render->removeAllViewports(); - mRoot->destroySceneManager(dummyScene); -} - -void ApplicationContextBase::enableShaderCache() const -{ - Ogre::GpuProgramManager::getSingleton().setSaveMicrocodesToCache(true); - - // Load for a package version of the shaders. - Ogre::String path = mFSLayer->getWritablePath(SHADER_CACHE_FILENAME); - std::ifstream inFile(path.c_str(), std::ios::binary); - if (!inFile.is_open()) - { - Ogre::LogManager::getSingleton().logWarning("Could not open '"+path+"'"); - return; - } - Ogre::LogManager::getSingleton().logMessage("Loading shader cache from '"+path+"'"); - Ogre::DataStreamPtr istream(new Ogre::FileStreamDataStream(path, &inFile, false)); - Ogre::GpuProgramManager::getSingleton().loadMicrocodeCache(istream); -} - -void ApplicationContextBase::addInputListener(NativeWindowType* win, InputListener* lis) -{ - mInputListeners.insert(std::make_pair(0, lis)); -} - - -void ApplicationContextBase::removeInputListener(NativeWindowType* win, InputListener* lis) -{ - mInputListeners.erase(std::make_pair(0, lis)); -} - -bool ApplicationContextBase::frameRenderingQueued(const Ogre::FrameEvent& evt) -{ - for(const auto & li : mInputListeners) { - li.second->frameRendered(evt); - } - - return true; -} - -NativeWindowPair ApplicationContextBase::createWindow(const Ogre::String& name, Ogre::uint32 w, Ogre::uint32 h, Ogre::NameValuePairList miscParams) -{ - NativeWindowPair ret = {NULL, NULL}; - - if(!mWindows.empty()) - { - // additional windows should reuse the context - miscParams["currentGLContext"] = "true"; - } - - auto p = mRoot->getRenderSystem()->getRenderWindowDescription(); - miscParams.insert(p.miscParams.begin(), p.miscParams.end()); - p.miscParams = miscParams; - p.name = name; - - if(w > 0 && h > 0) - { - p.width = w; - p.height= h; - } - - ret.render = mRoot->createRenderWindow(p); - - mWindows.push_back(ret); - - WindowEventUtilities::_addRenderWindow(ret.render); - - return ret; -} - -void ApplicationContextBase::destroyWindow(const Ogre::String& name) -{ - for (auto it = mWindows.begin(); it != mWindows.end(); ++it) - { - if (it->render->getName() != name) - continue; - _destroyWindow(*it); - mWindows.erase(it); - return; - } - - OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, "No window named '"+name+"'"); -} - -void ApplicationContextBase::_destroyWindow(const NativeWindowPair& win) -{ -#if !OGRE_BITES_HAVE_SDL - // remove window event listener before destroying it - WindowEventUtilities::_removeRenderWindow(win.render); -#endif - mRoot->destroyRenderTarget(win.render); -} - -void ApplicationContextBase::_fireInputEvent(const Event& event, uint32_t windowID) const -{ - Event scaled = event; -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE - if (event.type == MOUSEMOTION) - { - // assumes all windows have the same scale - float viewScale = getRenderWindow()->getViewPointToPixelScale(); - scaled.motion.x *= viewScale; - scaled.motion.y *= viewScale; - } - else if(event.type == MOUSEBUTTONDOWN || event.type == MOUSEBUTTONUP) - { - float viewScale = getRenderWindow()->getViewPointToPixelScale(); - scaled.button.x *= viewScale; - scaled.button.y *= viewScale; - } -#endif - - for(const auto & li : mInputListeners) - { - // gamepad events are not window specific - if(li.first != windowID && event.type <= TEXTINPUT) continue; - - InputListener& l = *li.second; - - switch (event.type) - { - case KEYDOWN: - l.keyPressed(event.key); - break; - case KEYUP: - l.keyReleased(event.key); - break; - case MOUSEBUTTONDOWN: - l.mousePressed(scaled.button); - break; - case MOUSEBUTTONUP: - l.mouseReleased(scaled.button); - break; - case MOUSEWHEEL: - l.mouseWheelRolled(event.wheel); - break; - case MOUSEMOTION: - l.mouseMoved(scaled.motion); - break; - case FINGERDOWN: - // for finger down we have to move the pointer first - l.touchMoved(event.tfinger); - l.touchPressed(event.tfinger); - break; - case FINGERUP: - l.touchReleased(event.tfinger); - break; - case FINGERMOTION: - l.touchMoved(event.tfinger); - break; - case TEXTINPUT: - l.textInput(event.text); - break; - case JOYAXISMOTION: - case CONTROLLERAXISMOTION: - l.axisMoved(event.axis); - break; - case CONTROLLERBUTTONDOWN: - l.buttonPressed(event.cbutton); - break; - case CONTROLLERBUTTONUP: - l.buttonReleased(event.cbutton); - break; - } - } -} - -Ogre::String ApplicationContextBase::getDefaultMediaDir() -{ - return Ogre::FileSystemLayer::resolveBundlePath(OGRE_MEDIA_DIR); -} - -void ApplicationContextBase::locateResources() -{ - auto& rgm = Ogre::ResourceGroupManager::getSingleton(); - // load resource paths from config file - Ogre::ConfigFile cf; - Ogre::String resourcesPath = mFSLayer->getConfigFilePath("resources.cfg"); -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - Ogre::Archive* apk = Ogre::ArchiveManager::getSingleton().load("", "APKFileSystem", true); - cf.load(apk->open(resourcesPath)); -#else - - if (Ogre::FileSystemLayer::fileExists(resourcesPath) || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN) - { - Ogre::LogManager::getSingleton().logMessage("Parsing '"+resourcesPath+"'"); - cf.load(resourcesPath); - } - else - { - rgm.addResourceLocation(getDefaultMediaDir(), "FileSystem", Ogre::RGN_DEFAULT); - } - -#endif - - Ogre::String sec, type, arch; - // go through all specified resource groups - for(auto& s : cf.getSettingsBySection()) { - sec = s.first; - // go through all resource paths - for (auto& t : s.second) - { - type = t.first; - arch = t.second; - - Ogre::StringUtil::trim(arch); - if (arch.empty() || arch[0] == '.') - { - // resolve relative path with regards to configfile - Ogre::String baseDir, filename; - Ogre::StringUtil::splitFilename(resourcesPath, filename, baseDir); - arch = baseDir + arch; - } - - arch = Ogre::FileSystemLayer::resolveBundlePath(arch); - -#if OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN - if((type == "Zip" || type == "FileSystem") && !Ogre::FileSystemLayer::fileExists(arch)) - { - Ogre::LogManager::getSingleton().logWarning("resource location '"+arch+"' does not exist - skipping"); - continue; - } -#endif - - rgm.addResourceLocation(arch, type, sec); - } - } - - if(rgm.getResourceLocationList(Ogre::RGN_INTERNAL).empty()) - { - const auto& mediaDir = getDefaultMediaDir(); - // add default locations - rgm.addResourceLocation(mediaDir + "/Main", "FileSystem", Ogre::RGN_INTERNAL); -#ifdef OGRE_BUILD_COMPONENT_TERRAIN - rgm.addResourceLocation(mediaDir + "/Terrain", "FileSystem", Ogre::RGN_INTERNAL); -#endif -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - rgm.addResourceLocation(mediaDir + "/RTShaderLib", "FileSystem", Ogre::RGN_INTERNAL); -#endif - } -} - -void ApplicationContextBase::loadResources() -{ - Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); -} - -void ApplicationContextBase::reconfigure(const Ogre::String &renderer, Ogre::NameValuePairList &options) -{ - mNextRenderer = renderer; - Ogre::RenderSystem* rs = mRoot->getRenderSystemByName(renderer); - - // set all given render system options - for (auto & option : options) - { - rs->setConfigOption(option.first, option.second); - } - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - // Need to save the config on iOS to make sure that changes are kept on disk - mRoot->saveConfig(); -#endif - mRoot->queueEndRendering(); // break from render loop -} - -void ApplicationContextBase::shutdown() -{ - const auto& gpuMgr = Ogre::GpuProgramManager::getSingleton(); - if (gpuMgr.getSaveMicrocodesToCache() && gpuMgr.isCacheDirty()) - { - Ogre::String path = mFSLayer->getWritablePath(SHADER_CACHE_FILENAME); - std::fstream outFile(path.c_str(), std::ios::out | std::ios::binary); - - if (outFile.is_open()) - { - Ogre::LogManager::getSingleton().logMessage("Writing shader cache to "+path); - Ogre::DataStreamPtr ostream(new Ogre::FileStreamDataStream(path, &outFile, false)); - gpuMgr.saveMicrocodeCache(ostream); - } - else - Ogre::LogManager::getSingleton().logWarning("Cannot open shader cache for writing "+path); - } - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - // Destroy the RT Shader System. - destroyRTShaderSystem(); -#endif - - for(auto it = mWindows.rbegin(); it != mWindows.rend(); ++it) - { - _destroyWindow(*it); - } - mWindows.clear(); - - if (mOverlaySystem) - { - OGRE_DELETE mOverlaySystem; - } - - mInputListeners.clear(); -} - -void ApplicationContextBase::pollEvents() -{ - // just avoid "window not responding" - WindowEventUtilities::messagePump(); -} - -} diff --git a/Components/Bites/src/OgreApplicationContextQt.cpp b/Components/Bites/src/OgreApplicationContextQt.cpp deleted file mode 100644 index 45c0fe87218..00000000000 --- a/Components/Bites/src/OgreApplicationContextQt.cpp +++ /dev/null @@ -1,263 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#include "OgreApplicationContextQt.h" - -#include - -#include "OgreRoot.h" -#include "OgreRenderWindow.h" - -#include -#include -#include -#include -#include - -namespace OgreBites -{ - static Event convert(const QEvent* in) - { - static QPoint lastMousePos; - - Event out; - - out.type = 0; - - switch(in->type()) - { - case QEvent::KeyPress: - out.type = KEYDOWN; - OGRE_FALLTHROUGH; - case QEvent::KeyRelease: - // ignore auto repeated key-up events to match SDL - if (!out.type && !static_cast(in)->isAutoRepeat()) - out.type = KEYUP; - { - auto* key = static_cast(in); - out.key.repeat = key->isAutoRepeat(); - switch(key->key()) - { - case Qt::Key_Escape: - out.key.keysym.sym = SDLK_ESCAPE; - break; - case Qt::Key_Return: - out.key.keysym.sym = SDLK_RETURN; - break; - default: - out.key.keysym.sym = std::tolower(key->key()); - break; - } - // out.key.keysym.mod = key->modifiers(); - } - break; - case QEvent::MouseButtonRelease: - out.type = MOUSEBUTTONUP; - OGRE_FALLTHROUGH; - case QEvent::MouseButtonPress: - if(!out.type) - out.type = MOUSEBUTTONDOWN; - - { - auto* mouse = static_cast(in); - out.button.x = mouse->x(); - out.button.y = mouse->y(); - out.button.button = mouse->button(); - - if(out.button.button == Qt::RightButton) - out.button.button = BUTTON_RIGHT; - } - break; - case QEvent::Wheel: - out.type = MOUSEWHEEL; - out.wheel.y = static_cast(in)->angleDelta().y(); - out.wheel.y = out.wheel.y > 0 ? 1 : -1; - break; - case QEvent::MouseMove: - out.type = MOUSEMOTION; - { - auto* mouse = static_cast(in); - out.motion.x = mouse->x(); - out.motion.y = mouse->y(); - out.motion.xrel = mouse->x() - lastMousePos.x(); - out.motion.yrel = mouse->y() - lastMousePos.y(); - - lastMousePos = mouse->pos(); - - //out.motion.windowID = in.motion.windowID; - } - break; - case QEvent::TouchBegin: - out.type = FINGERDOWN; - OGRE_FALLTHROUGH; - case QEvent::TouchEnd: - if(!out.type) - out.type = FINGERUP; - OGRE_FALLTHROUGH; - case QEvent::TouchUpdate: - if(!out.type) - out.type = FINGERMOTION; - { - auto* touch = static_cast(in); - out.tfinger.x = touch->touchPoints()[0].pos().x(); - out.tfinger.y = touch->touchPoints()[0].pos().y(); - //out.tfinger.dx = in.tfinger.dx; - //out.tfinger.dy = in.tfinger.dy; - out.tfinger.fingerId = touch->touchPoints()[0].id(); - } - break; - default: - break; - } - return out; - } - - NativeWindowPair ApplicationContextQt::createWindow(QWindow* window, Ogre::NameValuePairList miscParams) - { - OgreAssert(QGuiApplication::instance(), "you must create a QGuiApplication first"); - if(mWindows.empty()) - { - QGuiApplication::instance()->installEventFilter(this); - } - - auto p = mRoot->getRenderSystem()->getRenderWindowDescription(); - miscParams.insert(p.miscParams.begin(), p.miscParams.end()); - p.miscParams = miscParams; - p.name = window->title().toStdString(); - p.width = window->width(); - p.height= window->height(); - - p.miscParams["externalWindowHandle"] = std::to_string(size_t(window->winId())); - - if (!mWindows.empty()) - { - // additional windows should reuse the context - p.miscParams["currentGLContext"] = "true"; - } - - NativeWindowPair ret; - ret.native = (NativeWindowType*)window; - ret.render = mRoot->createRenderWindow(p); - mWindows.push_back(ret); - - return ret; - } - - void ApplicationContextQt::setWindowGrab(NativeWindowType* win, bool grab) - { - grab ? ((QWindow*)win)->setCursor(Qt::BlankCursor) : ((QWindow*)win)->unsetCursor(); - } - - NativeWindowPair ApplicationContextQt::createWindow(const Ogre::String& name, uint32_t w, uint32_t h, - Ogre::NameValuePairList miscParams) - { - if(mWindowOverride) - { - return createWindow(mWindowOverride, miscParams); - } - - auto p = mRoot->getRenderSystem()->getRenderWindowDescription(); - if(w > 0 && h > 0) - { - p.width = w; - p.height= h; - } - - QWindow* win = new QWindow(); - win->setTitle(QString::fromStdString(name)); - win->resize(p.width, p.height); - - if(p.useFullScreen){ - win->showFullScreen(); - } - - auto ret = createWindow(win, miscParams); - win->show(); - return ret; - } - - void ApplicationContextQt::addInputListener(NativeWindowType* win, InputListener* lis) - { - mInputListeners.insert(std::make_pair(((QWindow*)win)->winId(), lis)); - } - - - void ApplicationContextQt::removeInputListener(NativeWindowType* win, InputListener* lis) - { - mInputListeners.erase(std::make_pair(((QWindow*)win)->winId(), lis)); - } - - void ApplicationContextQt::pollEvents() - { - // assume events get polled by QApplication otherwise - if(!mQtEventLoop) - QCoreApplication::instance()->processEvents(); - } - - void ApplicationContextQt::timerEvent(QTimerEvent *e) - { - getRoot()->renderOneFrame(); - } - - bool ApplicationContextQt::eventFilter(QObject *obj, QEvent *event) - { - QWindow* w = dynamic_cast(obj); - - if(mWindows.empty() || !w) - { - // not applicable - return QObject::eventFilter(obj, event); - } - - switch (event->type()) - { - case QEvent::Quit: - mRoot->queueEndRendering(); - break; - case QEvent::UpdateRequest: - for(auto & window : mWindows) - { - if(w->winId() != ((QWindow*)window.native)->winId()) - continue; - window.render->update(); - } - break; - case QEvent::Resize: - for(auto & window : mWindows) - { - if(w->winId() != ((QWindow*)window.native)->winId()) - continue; - - Ogre::RenderWindow* win = window.render; - win->resize(w->width(), w->height()); - windowResized(win); - } - break; - default: - _fireInputEvent(convert(event), w->winId()); - break; - } - - return QObject::eventFilter(obj, event); - } - - void ApplicationContextQt::shutdown() - { - ApplicationContextBase::shutdown(); - - for(WindowList::iterator it = mWindows.begin(); it != mWindows.end(); ++it) - { - // FIXME: what if native is created externally? rather leak then risking double free - //if(it->native) - // delete (QWidget*)it->native; - } - if(!mWindows.empty()) { - QGuiApplication::instance()->removeEventFilter(this); - } - - mWindows.clear(); - } - -} /* namespace Ogre */ diff --git a/Components/Bites/src/OgreApplicationContextSDL.cpp b/Components/Bites/src/OgreApplicationContextSDL.cpp deleted file mode 100644 index 78dcd292915..00000000000 --- a/Components/Bites/src/OgreApplicationContextSDL.cpp +++ /dev/null @@ -1,180 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. - -#include "OgreApplicationContext.h" - -#include "OgreRoot.h" -#include "OgreRenderWindow.h" - -#include -#include -#include - -#include "SDLInputMapping.h" - -namespace OgreBites { - -ApplicationContextSDL::ApplicationContextSDL(const Ogre::String& appName) : ApplicationContextBase(appName) -{ -} - -void ApplicationContextSDL::addInputListener(NativeWindowType* win, InputListener* lis) -{ - mInputListeners.insert(std::make_pair(SDL_GetWindowID(win), lis)); -} - - -void ApplicationContextSDL::removeInputListener(NativeWindowType* win, InputListener* lis) -{ - mInputListeners.erase(std::make_pair(SDL_GetWindowID(win), lis)); -} - -NativeWindowPair ApplicationContextSDL::createWindow(const Ogre::String& name, Ogre::uint32 w, Ogre::uint32 h, Ogre::NameValuePairList miscParams) -{ - NativeWindowPair ret = {NULL, NULL}; - - if(!SDL_WasInit(SDL_INIT_VIDEO)) { - if(SDL_GameControllerAddMappingsFromFile("gamecontrollerdb.txt") > 0) - Ogre::LogManager::getSingleton().logMessage("[SDL] gamecontrollerdb.txt loaded"); - - SDL_InitSubSystem(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER); - } - - auto p = mRoot->getRenderSystem()->getRenderWindowDescription(); - miscParams.insert(p.miscParams.begin(), p.miscParams.end()); - p.miscParams = miscParams; - p.name = name; - - if(w > 0 && h > 0) - { - p.width = w; - p.height= h; - } - - int flags = p.useFullScreen ? SDL_WINDOW_FULLSCREEN : SDL_WINDOW_RESIZABLE; - int d = Ogre::StringConverter::parseInt(miscParams["monitorIndex"], 1) - 1; - ret.native = - SDL_CreateWindow(p.name.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(d), - SDL_WINDOWPOS_UNDEFINED_DISPLAY(d), p.width, p.height, flags); - -#if OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN - SDL_SysWMinfo wmInfo; - SDL_VERSION(&wmInfo.version); - SDL_GetWindowWMInfo(ret.native, &wmInfo); -#endif - - // for tiny rendersystem - p.miscParams["sdlwin"] = Ogre::StringConverter::toString(size_t(ret.native)); - -#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX - p.miscParams["externalWindowHandle"] = Ogre::StringConverter::toString(size_t(wmInfo.info.x11.window)); -#elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - p.miscParams["externalWindowHandle"] = Ogre::StringConverter::toString(size_t(wmInfo.info.win.window)); -#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE - assert(wmInfo.subsystem == SDL_SYSWM_COCOA); - p.miscParams["externalWindowHandle"] = Ogre::StringConverter::toString(size_t(wmInfo.info.cocoa.window)); -#endif - - if(!mWindows.empty()) - { - // additional windows should reuse the context - p.miscParams["currentGLContext"] = "true"; - } - - ret.render = mRoot->createRenderWindow(p); - mWindows.push_back(ret); - return ret; -} - -void ApplicationContextSDL::_destroyWindow(const NativeWindowPair& win) -{ - ApplicationContextBase::_destroyWindow(win); - if(win.native) - SDL_DestroyWindow(win.native); -} - -void ApplicationContextSDL::setWindowGrab(NativeWindowType* win, bool _grab) -{ - SDL_bool grab = SDL_bool(_grab); - - SDL_SetWindowGrab(win, grab); -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE - // osx workaround: mouse motion events are gone otherwise - SDL_SetRelativeMouseMode(grab); -#else - SDL_ShowCursor(!grab); -#endif -} - -float ApplicationContextSDL::getDisplayDPI() const -{ - OgreAssert(!mWindows.empty(), "create a window first"); - float vdpi = -1; - if(SDL_GetDisplayDPI(0, NULL, NULL, &vdpi) == 0 && vdpi > 0) - return vdpi; - - return ApplicationContextBase::getDisplayDPI(); -} - -void ApplicationContextSDL::shutdown() -{ - ApplicationContextBase::shutdown(); - - if(SDL_WasInit(SDL_INIT_VIDEO)) { - SDL_QuitSubSystem(SDL_INIT_VIDEO); - } -} - -void ApplicationContextSDL::pollEvents() -{ - if(mWindows.empty()) - { - // SDL events not initialized - return; - } - - SDL_Event event; - while (SDL_PollEvent(&event)) - { - switch (event.type) - { - case SDL_QUIT: - mRoot->queueEndRendering(); - break; - case SDL_WINDOWEVENT: - if(event.window.event != SDL_WINDOWEVENT_RESIZED) - continue; - - for(auto & window : mWindows) - { - if(event.window.windowID != SDL_GetWindowID(window.native)) - continue; - - Ogre::RenderWindow* win = window.render; - win->resize(event.window.data1, event.window.data2); - windowResized(win); - } - break; - case SDL_JOYDEVICEADDED: - if(!SDL_IsGameController(event.cdevice.which)) - { - SDL_JoystickOpen(event.cdevice.which); - Ogre::LogManager::getSingleton().logMessage("Opened Joystick"); - } - break; - case SDL_CONTROLLERDEVICEADDED: - if(auto c = SDL_GameControllerOpen(event.cdevice.which)) - { - const char* name = SDL_GameControllerName(c); - Ogre::LogManager::getSingleton().stream() << "Opened Gamepad: " << (name ? name : "unnamed"); - } - break; - default: - _fireInputEvent(convert(event), event.window.windowID); - break; - } - } -} - -} diff --git a/Components/Bites/src/OgreBitesConfigDialog.cpp b/Components/Bites/src/OgreBitesConfigDialog.cpp deleted file mode 100644 index dd43da53e09..00000000000 --- a/Components/Bites/src/OgreBitesConfigDialog.cpp +++ /dev/null @@ -1,18 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#include "OgreBitesConfigDialog.h" -#include "OgreConfigDialogImp.h" - -namespace OgreBites { - Ogre::ConfigDialog* getNativeConfigDialog() { -#if defined(HAVE_XAW) || (OGRE_PLATFORM == OGRE_PLATFORM_WIN32 && !defined(__MINGW32__)) || OGRE_PLATFORM == OGRE_PLATFORM_APPLE - static ConfigDialog dialog; - return &dialog; -#else - return NULL; -#endif - } -} /* namespace OgreBites */ diff --git a/Components/Bites/src/OgreCameraMan.cpp b/Components/Bites/src/OgreCameraMan.cpp deleted file mode 100644 index 54cc5eb9d32..00000000000 --- a/Components/Bites/src/OgreCameraMan.cpp +++ /dev/null @@ -1,247 +0,0 @@ -#include "OgreCameraMan.h" -#include "OgreSceneManager.h" - -namespace OgreBites { - -CameraMan::CameraMan(Ogre::SceneNode *cam) - : mYawSpace(Ogre::Node::TS_PARENT) - , mCamera(0) - , mStyle(CS_MANUAL) - , mTarget(0) - , mOrbiting(false) - , mMoving(false) - , mTopSpeed(150) - , mVelocity(Ogre::Vector3::ZERO) - , mGoingForward(false) - , mGoingBack(false) - , mGoingLeft(false) - , mGoingRight(false) - , mGoingUp(false) - , mGoingDown(false) - , mFastMove(false) - , mOffset(0, 0, 0) -{ - - setCamera(cam); - setStyle(CS_FREELOOK); -} - -void CameraMan::setCamera(Ogre::SceneNode *cam) -{ - mCamera = cam; -} - -void CameraMan::setTarget(Ogre::SceneNode *target) -{ - if (target == mTarget) - return; - - mTarget = target; -} - -void CameraMan::setYawPitchDist(const Ogre::Radian& yaw, const Ogre::Radian& pitch, Ogre::Real dist) -{ - OgreAssert(mTarget, "no target set"); - - mOffset = Ogre::Vector3::ZERO; - mCamera->setPosition(mTarget->_getDerivedPosition()); - mCamera->setOrientation(mTarget->_getDerivedOrientation()); - mCamera->yaw(yaw); - mCamera->pitch(-pitch); - mCamera->translate(Ogre::Vector3(0, 0, dist), Ogre::Node::TS_LOCAL); -} - -void CameraMan::setStyle(CameraStyle style) -{ - if (mStyle != CS_ORBIT && style == CS_ORBIT) - { - setTarget(mTarget ? mTarget : mCamera->getCreator()->getRootSceneNode()); - // fix the yaw axis if requested - mCamera->setFixedYawAxis(mYawSpace == Ogre::Node::TS_PARENT); - manualStop(); - - // try to replicate the camera configuration - Ogre::Real dist = getDistToTarget(); - const Ogre::Quaternion& q = mCamera->getOrientation(); - setYawPitchDist(q.getYaw(), q.getPitch(), dist == 0 ? 150 : dist); // enforce some distance - } - else if (mStyle != CS_FREELOOK && style == CS_FREELOOK) - { - mCamera->setFixedYawAxis(true); // also fix axis with lookAt calls - } - else if (mStyle != CS_MANUAL && style == CS_MANUAL) - { - manualStop(); - } - mStyle = style; - mCamera->setAutoTracking(false); -} - -void CameraMan::manualStop() -{ - if (mStyle == CS_FREELOOK) - { - mGoingForward = false; - mGoingBack = false; - mGoingLeft = false; - mGoingRight = false; - mGoingUp = false; - mGoingDown = false; - mVelocity = Ogre::Vector3::ZERO; - } -} - -void CameraMan::frameRendered(const Ogre::FrameEvent &evt) -{ - if (mStyle == CS_FREELOOK) - { - // build our acceleration vector based on keyboard input composite - Ogre::Vector3 accel = Ogre::Vector3::ZERO; - Ogre::Matrix3 axes = mCamera->getLocalAxes(); - if (mGoingForward) accel -= axes.GetColumn(2); - if (mGoingBack) accel += axes.GetColumn(2); - if (mGoingRight) accel += axes.GetColumn(0); - if (mGoingLeft) accel -= axes.GetColumn(0); - if (mGoingUp) accel += axes.GetColumn(1); - if (mGoingDown) accel -= axes.GetColumn(1); - - // if accelerating, try to reach top speed in a certain time - Ogre::Real topSpeed = mFastMove ? mTopSpeed * 20 : mTopSpeed; - if (accel.squaredLength() != 0) - { - accel.normalise(); - mVelocity += accel * topSpeed * evt.timeSinceLastFrame * 10; - } - // if not accelerating, try to stop in a certain time - else mVelocity -= mVelocity * evt.timeSinceLastFrame * 10; - - Ogre::Real tooSmall = std::numeric_limits::epsilon(); - - // keep camera velocity below top speed and above epsilon - if (mVelocity.squaredLength() > topSpeed * topSpeed) - { - mVelocity.normalise(); - mVelocity *= topSpeed; - } - else if (mVelocity.squaredLength() < tooSmall * tooSmall) - mVelocity = Ogre::Vector3::ZERO; - - if (mVelocity != Ogre::Vector3::ZERO) mCamera->translate(mVelocity * evt.timeSinceLastFrame); - } -} - -bool CameraMan::keyPressed(const KeyboardEvent &evt) -{ - if (mStyle == CS_FREELOOK) - { - Keycode key = evt.keysym.sym; - if (key == 'w' || key == SDLK_UP) mGoingForward = true; - else if (key == 's' || key == SDLK_DOWN) mGoingBack = true; - else if (key == 'a' || key == SDLK_LEFT) mGoingLeft = true; - else if (key == 'd' || key == SDLK_RIGHT) mGoingRight = true; - else if (key == SDLK_PAGEUP) mGoingUp = true; - else if (key == SDLK_PAGEDOWN) mGoingDown = true; - else if (key == SDLK_LSHIFT) mFastMove = true; - } - - return InputListener::keyPressed(evt); -} - -bool CameraMan::keyReleased(const KeyboardEvent &evt) -{ - if (mStyle == CS_FREELOOK) - { - Keycode key = evt.keysym.sym; - if (key == 'w' || key == SDLK_UP) mGoingForward = false; - else if (key == 's' || key == SDLK_DOWN) mGoingBack = false; - else if (key == 'a' || key == SDLK_LEFT) mGoingLeft = false; - else if (key == 'd' || key == SDLK_RIGHT) mGoingRight = false; - else if (key == SDLK_PAGEUP) mGoingUp = false; - else if (key == SDLK_PAGEDOWN) mGoingDown = false; - else if (key == SDLK_LSHIFT) mFastMove = false; - } - - return InputListener::keyReleased(evt); -} - -Ogre::Real CameraMan::getDistToTarget() -{ - Ogre::Vector3 offset = mCamera->getPosition() - mTarget->_getDerivedPosition() - mOffset; - return offset.length(); -} - -void CameraMan::setPivotOffset(const Ogre::Vector3& pivot) -{ - Ogre::Real dist = getDistToTarget(); - mOffset = pivot; - mCamera->setPosition(mTarget->_getDerivedPosition() + mOffset); - mCamera->translate(Ogre::Vector3(0, 0, dist), Ogre::Node::TS_LOCAL); -} - -bool CameraMan::mouseMoved(const MouseMotionEvent &evt) -{ - if (mStyle == CS_ORBIT) - { - Ogre::Real dist = getDistToTarget(); - - if (mOrbiting) // yaw around the target, and pitch locally - { - mCamera->setPosition(mTarget->_getDerivedPosition() + mOffset); - - mCamera->yaw(Ogre::Degree(-evt.xrel * 0.25f), mYawSpace); - mCamera->pitch(Ogre::Degree(-evt.yrel * 0.25f)); - - mCamera->translate(Ogre::Vector3(0, 0, dist), Ogre::Node::TS_LOCAL); - // don't let the camera go over the top or around the bottom of the target - } - else if (mMoving) // move the camera along the image plane - { - Ogre::Vector3 delta = mCamera->getOrientation() * Ogre::Vector3(-evt.xrel, evt.yrel, 0); - // the further the camera is, the faster it moves - delta *= dist / 1000.0f; - mOffset += delta; - mCamera->translate(delta); - } - } - else if (mStyle == CS_FREELOOK) - { - mCamera->yaw(Ogre::Degree(-evt.xrel * 0.15f), Ogre::Node::TS_PARENT); - mCamera->pitch(Ogre::Degree(-evt.yrel * 0.15f)); - } - - return InputListener::mouseMoved(evt); -} - -bool CameraMan::mouseWheelRolled(const MouseWheelEvent &evt) { - if (mStyle == CS_ORBIT && evt.y != 0) - { - Ogre::Real dist = (mCamera->getPosition() - mTarget->_getDerivedPosition()).length(); - mCamera->translate(Ogre::Vector3(0, 0, -evt.y * 0.08f * dist), Ogre::Node::TS_LOCAL); - } - - return InputListener::mouseWheelRolled(evt); -} - -bool CameraMan::mousePressed(const MouseButtonEvent &evt) -{ - if (mStyle == CS_ORBIT) - { - if (evt.button == BUTTON_LEFT) mOrbiting = true; - else if (evt.button == BUTTON_RIGHT) mMoving = true; - } - - return InputListener::mousePressed(evt); -} - -bool CameraMan::mouseReleased(const MouseButtonEvent &evt) -{ - if (mStyle == CS_ORBIT) - { - if (evt.button == BUTTON_LEFT) mOrbiting = false; - else if (evt.button == BUTTON_RIGHT) mMoving = false; - } - - return InputListener::mouseReleased(evt); -} - -} diff --git a/Components/Bites/src/OgreConfigDialogImp.h b/Components/Bites/src/OgreConfigDialogImp.h deleted file mode 100644 index 1a434274738..00000000000 --- a/Components/Bites/src/OgreConfigDialogImp.h +++ /dev/null @@ -1,52 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __CommonConfigDialogImp_H__ -#define __CommonConfigDialogImp_H__ - -#include "OgrePrerequisites.h" -#include "OgreConfigDialog.h" - -namespace OgreBites -{ - - class ConfigDialog : public Ogre::ConfigDialog - { - public: - ConfigDialog(); - virtual ~ConfigDialog(); - - bool display() override; - - protected: - // platform specific implementation - struct PrivateData; - PrivateData* mImpl; - }; -} - -#endif diff --git a/Components/Bites/src/OgreGLXConfigDialog.cpp b/Components/Bites/src/OgreGLXConfigDialog.cpp deleted file mode 100644 index 9ce1157e3d3..00000000000 --- a/Components/Bites/src/OgreGLXConfigDialog.cpp +++ /dev/null @@ -1,504 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreException.h" -#include "OgreImage.h" -#include "OgreLogManager.h" -#include "OgreRoot.h" -#include "OgreConfigPaths.h" -#include "OgreFileSystemLayer.h" - -#include -#include - -#include -#include "OgreConfigDialogImp.h" - -#define XTSTRINGDEFINES - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -using namespace Ogre; - -namespace OgreBites { - using Ogre::String; - -/** - * Single X window with image backdrop, making it possible to configure - * OGRE in a graphical way. - * XaW uses a not-very-smart widget positioning system, so I override it to use - * fixed positions. This works great, but it means you need to define the various - * positions manually. - * Furthermore, it has no OptionMenu by default, so I simulate this with dropdown - * buttons. - */ -class GLXConfigurator { - /* GUI constants */ - static const int wWidth = 500; // Width of window - static const int wHeight = 400; // Height of window - static const int col1x = 20; // Starting x of column 1 (labels) - static const int col2x = 230; // Starting x of column 2 (options) - static const int col1w = 200; // Width of column 1 (labels) - static const int col2w = 250; // Width of column 2 (options) - static const int ystart = 105; // Starting y of option table rows - static const int rowh = 20; // Height of one row in the option table - -public: - GLXConfigurator(); - virtual ~GLXConfigurator(); - - bool CreateWindow(); - void Main(); - /** - * Exit from main loop. - */ - void Exit(); -protected: - Display *mDisplay; - Window mWindow; - Pixmap mBackDrop; - - int mWidth, mHeight; - // Xt - XtAppContext appContext; - Widget toplevel; - - /** - * Create backdrop image, and return it as a Pixmap. - */ - virtual Pixmap CreateBackdrop(Window rootWindow, int depth); - /** - * Called after window initialisation. - */ - virtual bool Init(); - /** - * Called initially, and on expose. - */ - virtual void Draw(); -public: - /* Local */ - bool accept; - /* Class that binds a callback to a RenderSystem */ - class RendererCallbackData { - public: - RendererCallbackData(GLXConfigurator *parent_, RenderSystem *renderer_, Widget optionmenu_): - parent(parent_), - renderer(renderer_), - optionmenu(optionmenu_) { - } - GLXConfigurator *parent; - RenderSystem *renderer; - Widget optionmenu; - }; - std::list mRendererCallbackData; - - RenderSystem *mRenderer; - Widget box; // Box'o control widgets - std::list mRenderOptionWidgets; // List of RenderSystem specific - // widgets for visibility management (cleared when another rendersystem is selected) - /* Class that binds a callback to a certain configuration option/value */ - class ConfigCallbackData { - public: - ConfigCallbackData(GLXConfigurator *parent_, const String &optionName_, const String &valueName_, Widget optionmenu_): - parent(parent_), - optionName(optionName_), - valueName(valueName_), - optionmenu(optionmenu_) { - } - GLXConfigurator *parent; - String optionName, valueName; - Widget optionmenu; - }; - std::list mConfigCallbackData; - - void SetRenderSystem(RenderSystem *sys) { - mRenderer = sys; - } -private: - /* Callbacks that terminate modal dialog loop */ - static void acceptHandler(Widget w, GLXConfigurator *obj, XtPointer callData) { - // Check if a renderer was selected, if not, don't accept - if(!obj->mRenderer) - return; - obj->accept = true; - obj->Exit(); - } - static void cancelHandler(Widget w, GLXConfigurator *obj, XtPointer callData) { - obj->Exit(); - } - /* Callbacks that set a setting */ - static void renderSystemHandler(Widget w, RendererCallbackData *cdata, XtPointer callData) { - // Set selected renderer its name - XtVaSetValues(cdata->optionmenu, XtNlabel, cdata->renderer->getName().c_str(), 0, NULL); - // Notify Configurator (and Ogre) - cdata->parent->SetRenderer(cdata->renderer); - } - static void configOptionHandler(Widget w, ConfigCallbackData *cdata, XtPointer callData) { - // Set selected renderer its name - XtVaSetValues(cdata->optionmenu, XtNlabel, cdata->valueName.c_str(), 0, NULL); - // Notify Configurator (and Ogre) - cdata->parent->SetConfigOption(cdata->optionName, cdata->valueName); - } - - /* Functions reacting to GUI */ - void SetRenderer(RenderSystem *); - void SetConfigOption(const String &optionName, const String &valueName); -}; - -GLXConfigurator::GLXConfigurator(): - mDisplay(0), mWindow(0), mBackDrop(0), - mWidth(wWidth), mHeight(wHeight), - appContext(0), toplevel(0), - - accept(false), - mRenderer(0) { -} -GLXConfigurator::~GLXConfigurator() { - if(mBackDrop) - XFreePixmap(mDisplay, mBackDrop); - if(toplevel) { - XtUnrealizeWidget(toplevel); - XtDestroyWidget(toplevel); - } - if(mDisplay) { - XCloseDisplay(mDisplay); - } -} - -bool GLXConfigurator::CreateWindow() { - - - const char *bla[] = {"Rendering Settings", "-bg", "honeydew3", "-fg", "black","-bd","darkseagreen4"}; - int argc = sizeof(bla)/sizeof(*bla); - - toplevel = XtVaOpenApplication(&appContext, "OGRE", NULL, 0, &argc, const_cast(bla), NULL,sessionShellWidgetClass, - XtNwidth, mWidth, - XtNheight, mHeight, - XtNminWidth, mWidth, - XtNmaxWidth, mWidth, - XtNminHeight, mHeight, - XtNmaxHeight, mHeight, - XtNallowShellResize, False, - XtNborderWidth, 0, - XtNoverrideRedirect, False, - NULL, NULL); - - /* Find out display and screen used */ - mDisplay = XtDisplay(toplevel); - int screen = DefaultScreen(mDisplay); - Window rootWindow = RootWindow(mDisplay,screen); - - /* Move to center of display */ - int w = DisplayWidth(mDisplay, screen); - int h = DisplayHeight(mDisplay, screen); - XtVaSetValues(toplevel, - XtNx, w/2-mWidth/2, - XtNy, h/2-mHeight/2, 0, NULL); - - /* Backdrop stuff */ - mBackDrop = CreateBackdrop(rootWindow, DefaultDepth(mDisplay,screen)); - - /* Create toplevel */ - box = XtVaCreateManagedWidget("box",formWidgetClass,toplevel, - XtNbackgroundPixmap, mBackDrop, - 0,NULL); - - /* Create renderer selection */ - int cury = ystart + 0*rowh; - - XtVaCreateManagedWidget("topLabel", labelWidgetClass, box, XtNlabel, "Select Renderer", XtNborderWidth, 0, - XtNwidth, col1w, // Fixed width - XtNheight, 18, - XtNleft, XawChainLeft, - XtNtop, XawChainTop, - XtNright, XawChainLeft, - XtNbottom, XawChainTop, - XtNhorizDistance, col1x, - XtNvertDistance, cury, - XtNjustify, XtJustifyLeft, - NULL); - - const char *curRenderName = " Select One "; // Name of current renderer, or hint to select one - if(mRenderer) - curRenderName = mRenderer->getName().c_str(); - Widget mb1 = XtVaCreateManagedWidget("Menu", menuButtonWidgetClass, box, XtNlabel,curRenderName, - XtNresize, false, - XtNresizable, false, - XtNwidth, col2w, // Fixed width - XtNheight, 18, - XtNleft, XawChainLeft, - XtNtop, XawChainTop, - XtNright, XawChainLeft, - XtNbottom, XawChainTop, - XtNhorizDistance, col2x, - XtNvertDistance, cury, - NULL); - - Widget menu = XtVaCreatePopupShell("menu", simpleMenuWidgetClass, mb1, - 0, NULL); - - const RenderSystemList& renderers = Root::getSingleton().getAvailableRenderers(); - for (RenderSystemList::const_iterator pRend = renderers.begin(); - pRend != renderers.end(); pRend++) { - // Create callback data - mRendererCallbackData.push_back(RendererCallbackData(this, *pRend, mb1)); - - Widget entry = XtVaCreateManagedWidget("menuentry", smeBSBObjectClass, menu, - XtNlabel, (*pRend)->getName().c_str(), - 0, NULL); - XtAddCallback(entry, XtNcallback, (XtCallbackProc)&GLXConfigurator::renderSystemHandler, &mRendererCallbackData.back()); - } - - Widget bottomPanel = XtVaCreateManagedWidget("bottomPanel", formWidgetClass, box, - XtNsensitive, True, - XtNborderWidth, 0, - XtNwidth, 150, // Fixed width - XtNleft, XawChainLeft, - XtNtop, XawChainTop, - XtNright, XawChainLeft, - XtNbottom, XawChainTop, - XtNhorizDistance, mWidth - 160, - XtNvertDistance, mHeight - 40, - NULL); - - Widget helloButton = XtVaCreateManagedWidget("cancelButton", commandWidgetClass, bottomPanel, XtNlabel," Cancel ", NULL); - XtAddCallback(helloButton, XtNcallback, (XtCallbackProc)&GLXConfigurator::cancelHandler, this); - - Widget exitButton = XtVaCreateManagedWidget("acceptButton", commandWidgetClass, bottomPanel, XtNlabel," Accept ", XtNfromHoriz,helloButton, NULL); - XtAddCallback(exitButton, XtNcallback, (XtCallbackProc)&GLXConfigurator::acceptHandler, this); - - XtRealizeWidget(toplevel); - - if(mRenderer) - /* There was already a renderer selected; display its options */ - SetRenderer(mRenderer); - - return true; -} - -Pixmap GLXConfigurator::CreateBackdrop(Window rootWindow, int depth) { - int bpl; - /* Find out number of bytes per pixel */ - switch(depth) { - default: - LogManager::getSingleton().logMessage("GLX backdrop: Unsupported bit depth"); - /* Unsupported bit depth */ - return 0; - case 15: - case 16: - bpl = 2; break; - case 24: - case 32: - bpl = 4; break; - } - /* Create background pixmap */ - unsigned char *data = 0; // Must be allocated with malloc - - try { - Image img; - - // Load backdrop image using OGRE - String path = FileSystemLayer::resolveBundlePath(OGRE_MEDIA_DIR "/../GLX_backdrop.png"); - DataStreamPtr imgStreamPtr = Root::openFileStream(path); - img.load(imgStreamPtr, "png"); - - PixelBox src = img.getPixelBox(0, 0); - - // Convert and copy image - data = (unsigned char*)malloc(mWidth * mHeight * bpl); // Must be allocated with malloc - PixelBox dst(mWidth, mHeight, 1, bpl == 2 ? PF_B5G6R5 : PF_A8R8G8B8, data); - - memset(data, 0, dst.getConsecutiveSize()); - dst.bottom = src.bottom; - PixelUtil::bulkPixelConversion(src, dst); - } catch(Exception &e) { - // Could not find image; never mind - LogManager::getSingleton().logWarning("Can not load backdrop for config dialog: " + e.getDescription()); - return 0; - } - - GC context = XCreateGC (mDisplay, rootWindow, 0, NULL); - - /* put my pixmap data into the client side X image data structure */ - XImage *image = XCreateImage (mDisplay, NULL, depth, ZPixmap, 0, - (char*)data, - mWidth, mHeight, 8, - mWidth*bpl); -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - image->byte_order = MSBFirst; -#else - image->byte_order = LSBFirst; -#endif - - /* tell server to start managing my pixmap */ - Pixmap rv = XCreatePixmap(mDisplay, rootWindow, mWidth, - mHeight, depth); - - /* copy from client to server */ - XPutImage(mDisplay, rv, context, image, 0, 0, 0, 0, - mWidth, mHeight); - - /* free up the client side pixmap data area */ - XDestroyImage(image); // also cleans data - XFreeGC(mDisplay, context); - - return rv; -} -bool GLXConfigurator::Init() { - // Init misc resources - return true; -} -void GLXConfigurator::Draw() { -} -void GLXConfigurator::Main() { - XtAppMainLoop(appContext); -} -void GLXConfigurator::Exit() { - XtAppSetExitFlag(appContext); -} - -void GLXConfigurator::SetRenderer(RenderSystem *r) { - mRenderer = r; - - // Destroy each widget of GUI of previously selected renderer - for(std::list::iterator i=mRenderOptionWidgets.begin(); i!=mRenderOptionWidgets.end(); i++) - XtDestroyWidget(*i); - mRenderOptionWidgets.clear(); - - // Create option GUI - int cury = ystart + 1*rowh + 10; - - ConfigOptionMap options = mRenderer->getConfigOptions(); - // Process each option and create an optionmenu widget for it - for (ConfigOptionMap::iterator it = options.begin(); - it != options.end(); it++) { - // if the config option does not have any possible value, then skip it. - // if we create a popup with zero entries, it will crash when you click - // on it. - if (it->second.possibleValues.empty()) - continue; - - Widget lb1 = XtVaCreateManagedWidget("topLabel", labelWidgetClass, box, XtNlabel, it->second.name.c_str(), XtNborderWidth, 0, - XtNwidth, col1w, // Fixed width - XtNheight, 18, - XtNleft, XawChainLeft, - XtNtop, XawChainTop, - XtNright, XawChainLeft, - XtNbottom, XawChainTop, - XtNhorizDistance, col1x, - XtNvertDistance, cury, - XtNjustify, XtJustifyLeft, - NULL); - mRenderOptionWidgets.push_back(lb1); - Widget mb1 = XtVaCreateManagedWidget("Menu", menuButtonWidgetClass, box, XtNlabel, it->second.currentValue.c_str(), - XtNresize, false, - XtNresizable, false, - XtNwidth, col2w, // Fixed width - XtNheight, 18, - XtNleft, XawChainLeft, - XtNtop, XawChainTop, - XtNright, XawChainLeft, - XtNbottom, XawChainTop, - XtNhorizDistance, col2x, - XtNvertDistance, cury, - NULL); - mRenderOptionWidgets.push_back(mb1); - - Widget menu = XtVaCreatePopupShell("menu", simpleMenuWidgetClass, mb1, - 0, NULL); - - // Process each choice - StringVector::iterator opt_it; - for (opt_it = it->second.possibleValues.begin(); - opt_it != it->second.possibleValues.end(); opt_it++) { - // Create callback data - mConfigCallbackData.push_back(ConfigCallbackData(this, it->second.name, *opt_it, mb1)); - - Widget entry = XtVaCreateManagedWidget("menuentry", smeBSBObjectClass, menu, - XtNlabel, (*opt_it).c_str(), - 0, NULL); - XtAddCallback(entry, XtNcallback, (XtCallbackProc)&GLXConfigurator::configOptionHandler, &mConfigCallbackData.back()); - } - cury += rowh; - } -} - -void GLXConfigurator::SetConfigOption(const String &optionName, const String &valueName) { - if(!mRenderer) - // No renderer set -- how can this be called? - return; - mRenderer->setConfigOption(optionName, valueName); - SetRenderer(mRenderer); -} - -//------------------------------------------------------------------------------------// -ConfigDialog::ConfigDialog() : mImpl(NULL) -{ -} -//------------------------------------------------------------------------------------// -ConfigDialog::~ConfigDialog() -{ -} -//------------------------------------------------------------------------------------// -bool ConfigDialog::display() -{ - GLXConfigurator test; - /* Select previously selected rendersystem */ - if(Root::getSingleton().getRenderSystem()) - test.SetRenderSystem(Root::getSingleton().getRenderSystem()); - /* Attempt to create the window */ - if(!test.CreateWindow()) - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Could not create configuration dialog", - "GLXConfig::display"); - - // Modal loop - test.Main(); - if(!test.accept) // User did not accept - return false; - - /* All done */ - Root::getSingleton().setRenderSystem(test.mRenderer); - - return true; -} -} - diff --git a/Components/Bites/src/OgreImGuiInputListener.cpp b/Components/Bites/src/OgreImGuiInputListener.cpp deleted file mode 100644 index fc08450fb32..00000000000 --- a/Components/Bites/src/OgreImGuiInputListener.cpp +++ /dev/null @@ -1,201 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. - -#include - -#include - -#include - -// map sdl2 mouse buttons to imgui -static int sdl2imgui(int b) -{ - switch (b) - { - case 2: - return 2; - case 3: - return 1; - default: - return b - 1; - } -} - -namespace OgreBites -{ -static ImGuiKey ImGui_ImplSDL2_KeycodeToImGuiKey(int keycode) -{ - switch (keycode) - { - case '\t': return ImGuiKey_Tab; - case SDLK_LEFT: return ImGuiKey_LeftArrow; - case SDLK_RIGHT: return ImGuiKey_RightArrow; - case SDLK_UP: return ImGuiKey_UpArrow; - case SDLK_DOWN: return ImGuiKey_DownArrow; - case SDLK_PAGEUP: return ImGuiKey_PageUp; - case SDLK_PAGEDOWN: return ImGuiKey_PageDown; - case SDLK_HOME: return ImGuiKey_Home; - case SDLK_END: return ImGuiKey_End; - case SDLK_INSERT: return ImGuiKey_Insert; - case SDLK_DELETE: return ImGuiKey_Delete; - case '\b': return ImGuiKey_Backspace; - case SDLK_SPACE: return ImGuiKey_Space; - case SDLK_RETURN: return ImGuiKey_Enter; - case SDLK_ESCAPE: return ImGuiKey_Escape; - case '\'': return ImGuiKey_Apostrophe; - case ',': return ImGuiKey_Comma; - case '-': return ImGuiKey_Minus; - case '.': return ImGuiKey_Period; - case '/': return ImGuiKey_Slash; - case ';': return ImGuiKey_Semicolon; - case '=': return ImGuiKey_Equal; - case '[': return ImGuiKey_LeftBracket; - case '\\': return ImGuiKey_Backslash; - case ']': return ImGuiKey_RightBracket; - case '`': return ImGuiKey_GraveAccent; - //case SDLK_CAPSLOCK: return ImGuiKey_CapsLock; - case SDLK_SCROLLLOCK: return ImGuiKey_ScrollLock; - case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock; - case SDLK_PRINTSCREEN: return ImGuiKey_PrintScreen; - case SDLK_PAUSE: return ImGuiKey_Pause; - case SDLK_KP_0: return ImGuiKey_Keypad0; - case SDLK_KP_1: return ImGuiKey_Keypad1; - case SDLK_KP_2: return ImGuiKey_Keypad2; - case SDLK_KP_3: return ImGuiKey_Keypad3; - case SDLK_KP_4: return ImGuiKey_Keypad4; - case SDLK_KP_5: return ImGuiKey_Keypad5; - case SDLK_KP_6: return ImGuiKey_Keypad6; - case SDLK_KP_7: return ImGuiKey_Keypad7; - case SDLK_KP_8: return ImGuiKey_Keypad8; - case SDLK_KP_9: return ImGuiKey_Keypad9; - case SDLK_KP_PERIOD: return ImGuiKey_KeypadDecimal; - case SDLK_KP_DIVIDE: return ImGuiKey_KeypadDivide; - case SDLK_KP_MULTIPLY: return ImGuiKey_KeypadMultiply; - case SDLK_KP_MINUS: return ImGuiKey_KeypadSubtract; - case SDLK_KP_PLUS: return ImGuiKey_KeypadAdd; - case SDLK_KP_ENTER: return ImGuiKey_KeypadEnter; - //case SDLK_KP_EQUALS: return ImGuiKey_KeypadEqual; - //case SDLK_LCTRL: return ImGuiKey_LeftCtrl; - case SDLK_LSHIFT: return ImGuiKey_LeftShift; - /*case SDLK_LALT: return ImGuiKey_LeftAlt; - case SDLK_LGUI: return ImGuiKey_LeftSuper; - case SDLK_RCTRL: return ImGuiKey_RightCtrl; - case SDLK_RSHIFT: return ImGuiKey_RightShift; - case SDLK_RALT: return ImGuiKey_RightAlt; - case SDLK_RGUI: return ImGuiKey_RightSuper; - case SDLK_APPLICATION: return ImGuiKey_Menu;*/ - } - return ImGuiKey_None; -} - -static bool keyEvent(const KeyboardEvent& arg) -{ - ImGuiIO& io = ImGui::GetIO(); - - int key = arg.keysym.sym; - - if(key >= '0' && key <= '9') - key = key - '0' + ImGuiKey_0; - else if(key >= 'a' && key <= 'z') - key = key - 'a' + ImGuiKey_A; - else if(key >= SDLK_F1 && key <= SDLK_F12) - key = key - SDLK_F1 + ImGuiKey_F1; - else - key = ImGui_ImplSDL2_KeycodeToImGuiKey(key); - - io.AddKeyEvent(ImGuiMod_Shift, arg.keysym.mod & KMOD_SHIFT); - io.AddKeyEvent(ImGuiMod_Ctrl, arg.keysym.mod & KMOD_CTRL); - io.AddKeyEvent(ImGuiMod_Alt, arg.keysym.mod & KMOD_ALT); - io.AddKeyEvent(ImGuiMod_Super, arg.keysym.mod & KMOD_GUI); - - if (key == ImGuiKey_None) - return io.WantCaptureKeyboard; - - io.AddKeyEvent(ImGuiKey(key), arg.type == OgreBites::KEYDOWN); - return io.WantCaptureKeyboard; -} - -static bool buttonEvent(const ButtonEvent& evt) -{ - ImGuiIO& io = ImGui::GetIO(); - bool down = evt.type == OgreBites::CONTROLLERBUTTONDOWN; - switch(evt.button) - { - case 0: - io.AddKeyEvent(ImGuiKey_GamepadFaceDown, down); - break; - case 1: - io.AddKeyEvent(ImGuiKey_GamepadFaceRight, down); - break; - case 2: - io.AddKeyEvent(ImGuiKey_GamepadFaceLeft, down); - break; - case 11: - io.AddKeyEvent(ImGuiKey_GamepadDpadUp, down); - break; - case 12: - io.AddKeyEvent(ImGuiKey_GamepadDpadDown, down); - break; - case 13: - io.AddKeyEvent(ImGuiKey_GamepadDpadLeft, down); - break; - case 14: - io.AddKeyEvent(ImGuiKey_GamepadDpadRight, down); - break; - } - return true; -} - -ImGuiInputListener::ImGuiInputListener() -{ - ImGuiIO& io = ImGui::GetIO(); - io.BackendFlags |= ImGuiBackendFlags_HasGamepad; -} - -bool ImGuiInputListener::mouseWheelRolled(const MouseWheelEvent& arg) -{ - ImGuiIO& io = ImGui::GetIO(); - io.AddMouseWheelEvent(0.f, Ogre::Math::Sign(arg.y)); - return io.WantCaptureMouse; -} - -bool ImGuiInputListener::mouseMoved(const MouseMotionEvent& arg) -{ - - ImGuiIO& io = ImGui::GetIO(); - io.AddMousePosEvent(arg.x, arg.y); - return io.WantCaptureMouse; -} - -bool ImGuiInputListener::mousePressed(const MouseButtonEvent& arg) -{ - ImGuiIO& io = ImGui::GetIO(); - int b = sdl2imgui(arg.button); - if (b < 5) - { - io.AddMouseButtonEvent(b, true); - } - return io.WantCaptureMouse; -} -bool ImGuiInputListener::mouseReleased(const MouseButtonEvent& arg) -{ - ImGuiIO& io = ImGui::GetIO(); - int b = sdl2imgui(arg.button); - if (b < 5) - { - io.AddMouseButtonEvent(b, false); - } - return io.WantCaptureMouse; -} -bool ImGuiInputListener::textInput (const TextInputEvent& evt) -{ - ImGuiIO& io = ImGui::GetIO (); - io.AddInputCharactersUTF8 (evt.chars); - return true; -} -bool ImGuiInputListener::keyPressed(const KeyboardEvent& arg) { return keyEvent(arg); } -bool ImGuiInputListener::keyReleased(const KeyboardEvent& arg) { return keyEvent(arg); } -bool ImGuiInputListener::buttonPressed(const ButtonEvent& evt) { return buttonEvent(evt); } -bool ImGuiInputListener::buttonReleased(const ButtonEvent& evt) { return buttonEvent(evt); } -} // namespace OgreBites diff --git a/Components/Bites/src/OgreOSXConfigDialog.mm b/Components/Bites/src/OgreOSXConfigDialog.mm deleted file mode 100644 index 7ecef87ddb7..00000000000 --- a/Components/Bites/src/OgreOSXConfigDialog.mm +++ /dev/null @@ -1,479 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#import "OgreLogManager.h" -#import "OgreRoot.h" -#import "OgreRenderSystem.h" -#import "OgreConfigOptionMap.h" - -#import -#import -#include "OgreConfigDialogImp.h" - -using namespace Ogre; - -#if defined(MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6 -@interface OgreConfigWindowDelegate : NSObject -#else -@interface OgreConfigWindowDelegate : NSObject -#endif -{ - NSWindow *mConfigWindow; - NSImageView *mOgreLogo; - NSPopUpButton *mRenderSystemsPopUp; - NSPopUpButton *mOptionsPopUp; - NSTableView *mOptionsTable; - NSButton *mOkButton; - NSButton *mCancelButton; - NSTextField *mOptionLabel; - - NSDictionary *mOptions; -} - -- (void)cancelButtonPressed:(id)sender; -- (void)okButtonPressed:(id)sender; -- (void)popUpValueChanged:(id)sender; -- (void)renderSystemChanged:(id)sender; - -// Getters and setters -- (void)setOptions:(NSDictionary *)dict; -- (NSDictionary *)getOptions; -- (void)setRenderSystemsPopUp:(NSPopUpButton *)button; -- (NSPopUpButton *)getRenderSystemsPopUp; -- (void)setOgreLogo:(NSImageView *)image; -- (NSImageView *)getOgreLogo; -- (void)setConfigWindow:(NSWindow *)window; -- (NSWindow *)getConfigWindow; -- (void)setOptionsTable:(NSTableView *)table; -- (NSTableView *)getOptionsTable; -- (void)setOptionsPopUp:(NSPopUpButton *)button; -- (NSPopUpButton *)getOptionsPopUp; - -@end - -namespace OgreBites { - - struct ConfigDialog::PrivateData { - OgreConfigWindowDelegate *mWindowDelegate; - RenderSystem *mSelectedRenderSystem; - }; - - static ConfigDialog* dlg = NULL; - - ConfigDialog::ConfigDialog() : mImpl(new ConfigDialog::PrivateData()) - { - dlg = this; - } - - ConfigDialog::~ConfigDialog() - { - [mImpl->mWindowDelegate release]; mImpl->mWindowDelegate = nil; - delete mImpl; - } - - static void initialise(OgreConfigWindowDelegate*& mWindowDelegate) - { - mWindowDelegate = [[OgreConfigWindowDelegate alloc] init]; - - if (!mWindowDelegate) - OGRE_EXCEPT (Exception::ERR_INTERNAL_ERROR, "Could not load config dialog"); - } - - bool ConfigDialog::display() - { - // Select previously selected rendersystem - mImpl->mSelectedRenderSystem = Root::getSingleton().getRenderSystem(); - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - initialise(mImpl->mWindowDelegate); - - // Run a modal dialog, Abort means cancel, Stop means Ok - long retVal = 0; - NSModalSession modalSession = [NSApp beginModalSessionForWindow:[mImpl->mWindowDelegate getConfigWindow]]; - for (;;) { - retVal = [NSApp runModalSession:modalSession]; - - // User pressed a button - if (retVal != NSRunContinuesResponse) - break; - } - [NSApp endModalSession:modalSession]; - - // Set the rendersystem - String selectedRenderSystemName = String([[[[mImpl->mWindowDelegate getRenderSystemsPopUp] selectedItem] title] UTF8String]); - RenderSystem *rs = Root::getSingleton().getRenderSystemByName(selectedRenderSystemName); - Root::getSingleton().setRenderSystem(rs); - - // Relinquish control of the table - [[mImpl->mWindowDelegate getOptionsTable] setDataSource:nil]; - [[mImpl->mWindowDelegate getOptionsTable] setDelegate:nil]; - - // Drain the auto release pool - [pool drain]; - - return (retVal == NSRunStoppedResponse) ? true : false; - } - -} - -@implementation OgreConfigWindowDelegate - -- (id)init -{ - if((self = [super init])) - { - // This needs to be called in order to use Cocoa from a Carbon app - NSApplicationLoad(); - - // Construct the window manually - mConfigWindow = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 512, 512) - styleMask:(NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask) - backing:NSBackingStoreBuffered - defer:NO]; - - // Make ourselves the delegate - [mConfigWindow setDelegate:self]; - - // First do the buttons - mOkButton = [[NSButton alloc] initWithFrame:NSMakeRect(414, 12, 84, 32)]; - [mOkButton setButtonType:NSMomentaryPushInButton]; - [mOkButton setBezelStyle:NSRoundedBezelStyle]; - [mOkButton setTitle:NSLocalizedString(@"OK", @"okButtonString")]; - [mOkButton setAction:@selector(okButtonPressed:)]; - [mOkButton setTarget:self]; - [mOkButton setKeyEquivalent:@"\r"]; - [[mConfigWindow contentView] addSubview:mOkButton]; - - mCancelButton = [[NSButton alloc] initWithFrame:NSMakeRect(330, 12, 84, 32)]; - [mCancelButton setButtonType:NSMomentaryPushInButton]; - [mCancelButton setBezelStyle:NSRoundedBezelStyle]; - [mCancelButton setAction:@selector(cancelButtonPressed:)]; - [mCancelButton setTarget:self]; - [mCancelButton setKeyEquivalent:@"\e"]; - [mCancelButton setTitle:NSLocalizedString(@"Cancel", @"cancelButtonString")]; - [[mConfigWindow contentView] addSubview:mCancelButton]; - - // Then the Ogre logo out of the framework bundle - mOgreLogo = [[NSImageView alloc] initWithFrame:NSMakeRect(0, 395, 512, 120)]; - NSMutableString *logoPath = [[[NSBundle bundleForClass:[self class]] resourcePath] mutableCopy]; - [logoPath appendString:@"/ogrelogo.png"]; - - NSImage *image = [[NSImage alloc] initWithContentsOfFile:logoPath]; - [logoPath release]; - [mOgreLogo setImage:image]; - [mOgreLogo setImageScaling:NSScaleToFit]; - [mOgreLogo setEditable:NO]; - [image release]; - [[mConfigWindow contentView] addSubview:mOgreLogo]; - - // Popup menu for rendersystems. On OS X this is always OpenGL - mRenderSystemsPopUp = [[NSPopUpButton alloc] initWithFrame:NSMakeRect(168, 359, 327, 26) pullsDown:NO]; - [[mConfigWindow contentView] addSubview:mRenderSystemsPopUp]; - - [mRenderSystemsPopUp setAction:@selector(renderSystemChanged:)]; - [mRenderSystemsPopUp setTarget:self]; - - NSTextField *renderSystemLabel = [[NSTextField alloc] initWithFrame:NSMakeRect(18, 365, 148, 17)]; - [renderSystemLabel setStringValue:NSLocalizedString(@"Rendering Subsystem", @"renderingSubsystemString")]; - [renderSystemLabel setEditable:NO]; - [renderSystemLabel setSelectable:NO]; - [renderSystemLabel setDrawsBackground:NO]; - [renderSystemLabel setAlignment:NSNaturalTextAlignment]; - [renderSystemLabel setBezeled:NO]; - [[mConfigWindow contentView] addSubview:renderSystemLabel]; - [renderSystemLabel release]; - - // The pretty box to contain the table and options - NSBox *tableBox = [[NSBox alloc] initWithFrame:NSMakeRect(19, 54, 477, 303)]; - [tableBox setTitle:NSLocalizedString(@"Rendering System Options", @"optionsBoxString")]; - [tableBox setContentViewMargins:NSMakeSize(0, 0)]; - [tableBox setFocusRingType:NSFocusRingTypeNone]; - [tableBox setBorderType:NSLineBorder]; - - // Set up the tableview - mOptionsTable = [[NSTableView alloc] init]; - [mOptionsTable setDelegate:self]; - [mOptionsTable setDataSource:self]; - [mOptionsTable setHeaderView:nil]; - [mOptionsTable setUsesAlternatingRowBackgroundColors:YES]; - [mOptionsTable sizeToFit]; - - // Table column to hold option names - NSTableColumn *column = [[NSTableColumn alloc] initWithIdentifier: @"optionName"]; - [column setEditable:NO]; - [column setMinWidth:437]; - [mOptionsTable addTableColumn:column]; - [column release]; - - // Scroll view to hold the table in case the list grows some day - NSScrollView *scrollView = [[NSScrollView alloc] initWithFrame:NSMakeRect(22, 42, 439, 235)]; - [scrollView setBorderType:NSBezelBorder]; - [scrollView setAutoresizesSubviews:YES]; - [scrollView setAutohidesScrollers:YES]; - [scrollView setDocumentView:mOptionsTable]; - - [[tableBox contentView] addSubview:scrollView]; - [scrollView release]; - - mOptionLabel = [[NSTextField alloc] initWithFrame:NSMakeRect(15, 15, 173, 17)]; - [mOptionLabel setStringValue:NSLocalizedString(@"Select an Option", @"optionLabelString")]; - [mOptionLabel setEditable:NO]; - [mOptionLabel setSelectable:NO]; - [mOptionLabel setDrawsBackground:NO]; - [mOptionLabel setAlignment:NSRightTextAlignment]; - [mOptionLabel setBezeled:NO]; - [[tableBox contentView] addSubview:mOptionLabel]; - - mOptionsPopUp = [[NSPopUpButton alloc] initWithFrame:NSMakeRect(190, 10, 270, 26) pullsDown:NO]; - [[tableBox contentView] addSubview:mOptionsPopUp]; - [mOptionsPopUp setAction:@selector(popUpValueChanged:)]; - [mOptionsPopUp setTarget:self]; - - [[mConfigWindow contentView] addSubview:tableBox]; - [tableBox release]; - - // Add renderers to the drop down - const RenderSystemList& renderers = Root::getSingleton().getAvailableRenderers(); - for (RenderSystemList::const_iterator pRend = renderers.begin(); pRend != renderers.end(); ++pRend) - { - NSString *renderSystemName = [[NSString alloc] initWithCString:(*pRend)->getName().c_str() encoding:NSASCIIStringEncoding]; - [mRenderSystemsPopUp addItemWithTitle:renderSystemName]; - } - - [self refreshConfigOptions]; - } - return self; -} - --(void) refreshConfigOptions -{ - NSMutableDictionary* dict = [NSMutableDictionary dictionary]; - - // Get detected option values and add them to our config dictionary - String selectedRenderSystemName = String([[[mRenderSystemsPopUp selectedItem] title] UTF8String]); - RenderSystem *rs = Root::getSingleton().getRenderSystemByName(selectedRenderSystemName); - const ConfigOptionMap& opts = rs->getConfigOptions(); - for (ConfigOptionMap::const_iterator pOpt = opts.begin(); pOpt != opts.end(); ++pOpt) - { - NSString* key = [[NSString alloc] initWithCString:pOpt->first.c_str()]; - NSMutableArray* values = [[NSMutableArray alloc] initWithCapacity:10]; - for(uint i = 0; i < pOpt->second.possibleValues.size(); i++) - { - NSString *value = [[NSString alloc] initWithCString:pOpt->second.possibleValues[i].c_str() - encoding:NSASCIIStringEncoding]; - [values addObject:value]; - } - - [dict setObject:values forKey:key]; - } - - [self setOptions:dict]; -} - -- (void)dealloc -{ - [mOptions release]; mOptions = nil; - [mConfigWindow release]; mConfigWindow = nil; - [mOptionsPopUp release]; mOptionsPopUp = nil; - [mOptionLabel release]; mOptionLabel = nil; - [mOptionsTable release]; mOptionsTable = nil; - [mRenderSystemsPopUp release]; mRenderSystemsPopUp = nil; - [mOgreLogo release]; mOgreLogo = nil; - [mCancelButton release]; mCancelButton = nil; - [mOkButton release]; mOkButton = nil; - - [super dealloc]; -} - -#pragma mark Window and Control delegate methods - -- (void)renderSystemChanged:(id)sender -{ - [self refreshConfigOptions]; -} - -- (void)popUpValueChanged:(id)sender -{ -#pragma unused(sender) - // Grab a copy of the selected RenderSystem name in String format - String selectedRenderSystemName = String([[[mRenderSystemsPopUp selectedItem] title] UTF8String]); - - // Save the current config value - if((0 <= [mOptionsTable selectedRow]) && [mOptionsPopUp selectedItem]) - { - String value = String([[[mOptionsPopUp selectedItem] title] UTF8String]); - String name = String([[[[mOptions keyEnumerator] allObjects] objectAtIndex:[mOptionsTable selectedRow]] UTF8String]); - - Root::getSingleton().getRenderSystemByName(selectedRenderSystemName)->setConfigOption(name, value); - } -} - -- (BOOL)windowShouldClose:(id)sender -{ -#pragma unused(sender) - // Hide the window - [mConfigWindow orderOut:nil]; - - [NSApp abortModal]; - - return true; -} - -- (void)cancelButtonPressed:(id)sender -{ -#pragma unused(sender) - // Hide the window - [mConfigWindow orderOut:nil]; - - [NSApp abortModal]; - [NSApp terminate:nil]; -} - -- (void)okButtonPressed:(id)sender -{ -#pragma unused(sender) - // Hide the window - [mConfigWindow orderOut:nil]; - - [NSApp stopModal]; -} - -#pragma mark NSTableView delegate and datasource methods -- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex -{ -#pragma unused(aTableView) - return [[[mOptions keyEnumerator] allObjects] objectAtIndex:rowIndex]; -} - -- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView -{ -#pragma unused(aTableView) - return [mOptions count]; -} - -// Intercept the request to select a new row. Update the popup's values. -- (BOOL)tableView:(NSTableView *)aTableView shouldSelectRow:(NSInteger)rowIndex -{ -#pragma unused(aTableView) - // Clear out the options popup menu - [mOptionsPopUp removeAllItems]; - - // Get the key for the selected table row - NSString *key = [[[mOptions keyEnumerator] allObjects] objectAtIndex:rowIndex]; - - // Add the available options - [mOptionsPopUp addItemsWithTitles:[mOptions objectForKey:key]]; - - // Grab a copy of the selected RenderSystem name in String format - if([mRenderSystemsPopUp numberOfItems] > 0) - { - String selectedRenderSystemName = String([[[mRenderSystemsPopUp selectedItem] title] UTF8String]); - const ConfigOptionMap& opts = Root::getSingleton().getRenderSystemByName(selectedRenderSystemName)->getConfigOptions(); - - // Select the item that is the current config option, if there is no current setting, just pick the top of the list - ConfigOptionMap::const_iterator it = opts.find([key UTF8String]); - if (it != opts.end()) - [mOptionsPopUp selectItemWithTitle:[NSString stringWithCString:it->second.currentValue.c_str() - encoding:NSASCIIStringEncoding]]; - - if([mOptionsPopUp indexOfSelectedItem] < 0) - [mOptionsPopUp selectItemAtIndex:0]; - - // Always allow the new selection - return YES; - } - else - { - return NO; - } -} - -#pragma mark Getters and Setters -- (NSWindow *)getConfigWindow -{ - return mConfigWindow; -} - -- (void)setConfigWindow:(NSWindow *)window -{ - mConfigWindow = window; -} - -- (NSDictionary *)getOptions -{ - return mOptions; -} - -- (void)setOptions:(NSDictionary *)dict -{ - [dict retain]; - [mOptions release]; - mOptions = dict; - [mOptionsTable reloadData]; -} - -- (NSPopUpButton *)getRenderSystemsPopUp -{ - return mRenderSystemsPopUp; -} - -- (void)setRenderSystemsPopUp:(NSPopUpButton *)button -{ - mRenderSystemsPopUp = button; -} - -- (void)setOgreLogo:(NSImageView *)image -{ - mOgreLogo = image; -} - -- (NSImageView *)getOgreLogo -{ - return mOgreLogo; -} - -- (void)setOptionsTable:(NSTableView *)table -{ - mOptionsTable = table; -} - -- (NSTableView *)getOptionsTable -{ - return mOptionsTable; -} - -- (void)setOptionsPopUp:(NSPopUpButton *)button -{ - mOptionsPopUp = button; -} - -- (NSPopUpButton *)getOptionsPopUp -{ - return mOptionsPopUp; -} - -@end diff --git a/Components/Bites/src/OgreSGTechniqueResolverListener.cpp b/Components/Bites/src/OgreSGTechniqueResolverListener.cpp deleted file mode 100644 index 9dee898769c..00000000000 --- a/Components/Bites/src/OgreSGTechniqueResolverListener.cpp +++ /dev/null @@ -1,70 +0,0 @@ -#include "OgreSGTechniqueResolverListener.h" - -#include "OgreTechnique.h" - -namespace OgreBites { - -SGTechniqueResolverListener::SGTechniqueResolverListener(Ogre::RTShader::ShaderGenerator *pShaderGenerator) -{ - mShaderGenerator = pShaderGenerator; -} - -Ogre::Technique *SGTechniqueResolverListener::handleSchemeNotFound(unsigned short schemeIndex, const Ogre::String &schemeName, Ogre::Material *originalMaterial, unsigned short lodIndex, const Ogre::Renderable *rend) { - if (!mShaderGenerator->hasRenderState(schemeName)) - { - return NULL; - } - // Case this is the default shader generator scheme. - - // Create shader generated technique for this material. - bool techniqueCreated = mShaderGenerator->createShaderBasedTechnique( - *originalMaterial, - Ogre::MaterialManager::DEFAULT_SCHEME_NAME, - schemeName); - - if (!techniqueCreated) - { - return NULL; - } - // Case technique registration succeeded. - - // Force creating the shaders for the generated technique. - mShaderGenerator->validateMaterial(schemeName, *originalMaterial); - - // Grab the generated technique. - for(auto *t : originalMaterial->getTechniques()) - { - if (t->getSchemeName() == schemeName) - { - return t; - } - } - - return NULL; -} - -bool SGTechniqueResolverListener::afterIlluminationPassesCreated(Ogre::Technique *tech) -{ - if(mShaderGenerator->hasRenderState(tech->getSchemeName())) - { - Ogre::Material* mat = tech->getParent(); - mShaderGenerator->validateMaterialIlluminationPasses(tech->getSchemeName(), - mat->getName(), mat->getGroup()); - return true; - } - return false; -} - -bool SGTechniqueResolverListener::beforeIlluminationPassesCleared(Ogre::Technique *tech) -{ - if(mShaderGenerator->hasRenderState(tech->getSchemeName())) - { - Ogre::Material* mat = tech->getParent(); - mShaderGenerator->invalidateMaterialIlluminationPasses(tech->getSchemeName(), - mat->getName(), mat->getGroup()); - return true; - } - return false; -} - -} diff --git a/Components/Bites/src/OgreStaticPluginLoader.cpp b/Components/Bites/src/OgreStaticPluginLoader.cpp deleted file mode 100644 index cd0c8128ebb..00000000000 --- a/Components/Bites/src/OgreStaticPluginLoader.cpp +++ /dev/null @@ -1,210 +0,0 @@ -#include "OgreStaticPluginLoader.h" -#include "OgreBuildSettings.h" -#include "OgreComponents.h" -#include "OgreRoot.h" -#include "OgrePlugin.h" - -#ifdef OGRE_BUILD_RENDERSYSTEM_GL -#define OGRE_STATIC_GL -#endif -#ifdef OGRE_BUILD_RENDERSYSTEM_GL3PLUS -#define OGRE_STATIC_GL3Plus -#endif -#ifdef OGRE_BUILD_RENDERSYSTEM_GLES2 -#define OGRE_STATIC_GLES2 -#endif -#ifdef OGRE_BUILD_RENDERSYSTEM_D3D9 -#define OGRE_STATIC_Direct3D9 -#endif -// dx11 will only work on vista and above, so be careful about statically linking -#ifdef OGRE_BUILD_RENDERSYSTEM_D3D11 -#define OGRE_STATIC_Direct3D11 -#endif - -#ifdef OGRE_BUILD_PLUGIN_BSP -#define OGRE_STATIC_BSPSceneManager -#endif -#ifdef OGRE_BUILD_PLUGIN_PFX -#define OGRE_STATIC_ParticleFX -#endif -#ifdef OGRE_BUILD_PLUGIN_CG -#define OGRE_STATIC_CgProgramManager -#endif - -#ifdef OGRE_USE_PCZ - #ifdef OGRE_BUILD_PLUGIN_PCZ - #define OGRE_STATIC_PCZSceneManager - #define OGRE_STATIC_OctreeZone - #endif -#else - #ifdef OGRE_BUILD_PLUGIN_OCTREE - #define OGRE_STATIC_OctreeSceneManager - #endif -#endif - -#ifdef OGRE_BITES_STATIC_PLUGINS -// Static plugin headers -#ifdef OGRE_STATIC_CgProgramManager -# include "OgreCgPlugin.h" -#endif -#ifdef OGRE_BUILD_PLUGIN_GLSLANG -# include "OgreGLSLangProgramManager.h" -#endif -#ifdef OGRE_BUILD_PLUGIN_ASSIMP -# include "OgreAssimpLoader.h" -#endif -#ifdef OGRE_STATIC_OctreeSceneManager -# include "OgreOctreePlugin.h" -#endif -#ifdef OGRE_STATIC_ParticleFX -# include "OgreParticleFXPlugin.h" -#endif -#ifdef OGRE_STATIC_BSPSceneManager -# include "OgreBspSceneManagerPlugin.h" -#endif -#ifdef OGRE_STATIC_GL -# include "OgreGLPlugin.h" -#endif -#ifdef OGRE_STATIC_GL3Plus -# include "OgreGL3PlusPlugin.h" -#endif -#ifdef OGRE_STATIC_GLES2 -# include "OgreGLES2Plugin.h" -#endif -#ifdef OGRE_STATIC_Direct3D9 -# include "OgreD3D9Plugin.h" -#endif -#ifdef OGRE_STATIC_Direct3D11 -# include "OgreD3D11Plugin.h" -#endif -#ifdef OGRE_BUILD_RENDERSYSTEM_TINY -# include "OgreTinyPlugin.h" -#endif -#ifdef OGRE_BUILD_RENDERSYSTEM_VULKAN -# include "OgreVulkanPlugin.h" -#endif -#ifdef OGRE_STATIC_PCZSceneManager -# include "OgrePCZPlugin.h" -#endif -#ifdef OGRE_STATIC_OctreeZone -# include "OgreOctreeZonePlugin.h" -#endif -#ifdef OGRE_BUILD_PLUGIN_STBI -# include "OgreSTBICodec.h" -#endif -#ifdef OGRE_BUILD_PLUGIN_DOT_SCENE -# include "OgreDotSceneLoader.h" -#endif -#if defined(OGRE_BUILD_PLUGIN_FREEIMAGE) && !defined(OGRE_BUILD_PLUGIN_STBI) -# include "OgreFreeImageCodec.h" -#endif -#if defined(OGRE_BUILD_PLUGIN_RSIMAGE) && !defined(OGRE_BUILD_PLUGIN_STBI) -# include "OgreRsImageCodec.h" -#endif -#endif - -void OgreBites::StaticPluginLoader::load() -{ - using namespace Ogre; -#ifdef OGRE_BITES_STATIC_PLUGINS - Plugin* plugin = NULL; -#ifdef OGRE_STATIC_GL - plugin = OGRE_NEW GLPlugin(); - mPlugins.push_back(plugin); -#endif -#ifdef OGRE_STATIC_GL3Plus - plugin = OGRE_NEW GL3PlusPlugin(); - mPlugins.push_back(plugin); -#endif -#ifdef OGRE_STATIC_GLES2 - plugin = OGRE_NEW GLES2Plugin(); - mPlugins.push_back(plugin); -#endif -#ifdef OGRE_STATIC_Direct3D9 - plugin = OGRE_NEW D3D9Plugin(); - mPlugins.push_back(plugin); -#endif -#ifdef OGRE_BUILD_RENDERSYSTEM_TINY - plugin = OGRE_NEW TinyPlugin(); - mPlugins.push_back(plugin); -#endif -#ifdef OGRE_BUILD_RENDERSYSTEM_VULKAN - plugin = OGRE_NEW VulkanPlugin(); - mPlugins.push_back(plugin); -#endif -#ifdef OGRE_STATIC_Direct3D11 - plugin = OGRE_NEW D3D11Plugin(); - mPlugins.push_back(plugin); -#endif -#ifdef OGRE_STATIC_CgProgramManager - plugin = OGRE_NEW CgPlugin(); - mPlugins.push_back(plugin); -#endif -#ifdef OGRE_STATIC_OctreeSceneManager - plugin = OGRE_NEW OctreePlugin(); - mPlugins.push_back(plugin); -#endif -#ifdef OGRE_STATIC_ParticleFX - plugin = OGRE_NEW ParticleFXPlugin(); - mPlugins.push_back(plugin); -#endif -#ifdef OGRE_STATIC_BSPSceneManager - plugin = OGRE_NEW BspSceneManagerPlugin(); - mPlugins.push_back(plugin); -#endif -#ifdef OGRE_STATIC_PCZSceneManager - plugin = OGRE_NEW PCZPlugin(); - mPlugins.push_back(plugin); -#endif -#ifdef OGRE_STATIC_OctreeZone - plugin = OGRE_NEW OctreeZonePlugin(); - mPlugins.push_back(plugin); -#endif -#ifdef OGRE_BUILD_PLUGIN_STBI - STBIImageCodec::startup(); -#endif -#if defined(OGRE_BUILD_PLUGIN_RSIMAGE) && !defined(OGRE_BUILD_PLUGIN_STBI) - RsImageCodec::startup(); -#endif -#ifdef OGRE_BUILD_PLUGIN_DOT_SCENE - plugin = OGRE_NEW DotScenePlugin(); - mPlugins.push_back(plugin); -#endif -#if defined(OGRE_BUILD_PLUGIN_FREEIMAGE) && !defined(OGRE_BUILD_PLUGIN_STBI) && !defined(OGRE_BUILD_PLUGIN_RSIMAGE) - FreeImageCodec::startup(); -#endif -#ifdef OGRE_BUILD_PLUGIN_ASSIMP - plugin = OGRE_NEW AssimpPlugin(); - mPlugins.push_back(plugin); -#endif -#ifdef OGRE_BUILD_PLUGIN_GLSLANG - plugin = OGRE_NEW GLSLangPlugin(); - mPlugins.push_back(plugin); -#endif -#endif - - Root& root = Root::getSingleton(); - for (auto & p : mPlugins) { - root.installPlugin(p); - } -} - -void OgreBites::StaticPluginLoader::unload() -{ - // don't unload plugins, since Root will have done that. Destroy here. - for (auto & p : mPlugins) { - OGRE_DELETE p; - } - mPlugins.clear(); -#ifdef OGRE_BITES_STATIC_PLUGINS -#ifdef OGRE_BUILD_PLUGIN_STBI - Ogre::STBIImageCodec::shutdown(); -#endif -#if defined(OGRE_BUILD_PLUGIN_RSIMAGE) - Ogre::RsImageCodec::shutdown(); -#endif -#if defined(OGRE_BUILD_PLUGIN_FREEIMAGE) && !defined(OGRE_BUILD_PLUGIN_STBI) && !defined(OGRE_BUILD_PLUGIN_RSIMAGE) - Ogre::FreeImageCodec::shutdown(); -#endif -#endif -} diff --git a/Components/Bites/src/OgreTrays.cpp b/Components/Bites/src/OgreTrays.cpp deleted file mode 100644 index f4dd15bd249..00000000000 --- a/Components/Bites/src/OgreTrays.cpp +++ /dev/null @@ -1,2209 +0,0 @@ -/* - * SdkTrays.cpp - * - * Created on: 01.07.2016 - * Author: parojtbe - */ - -#include "OgreTrays.h" - -namespace OgreBites -{ - -// maximal rate to update widgets internally -static unsigned FRAME_UPDATE_DELAY = 250; // ms - -Widget::Widget() -{ - mTrayLoc = TL_NONE; - mElement = 0; - mListener = 0; -} - -void Widget::cleanup() -{ - if (mElement) nukeOverlayElement(mElement); - mElement = 0; -} - -void Widget::nukeOverlayElement(Ogre::OverlayElement *element) -{ - Ogre::OverlayContainer* container = dynamic_cast(element); - if (container) - { - std::vector toDelete; - for (const auto& p : container->getChildren()) - { - toDelete.push_back(p.second); - } - - for (unsigned int i = 0; i < toDelete.size(); i++) - { - nukeOverlayElement(toDelete[i]); - } - } - if (element) - { - Ogre::OverlayContainer* parent = element->getParent(); - if (parent) parent->removeChild(element->getName()); - Ogre::OverlayManager::getSingleton().destroyOverlayElement(element); - } -} - -bool Widget::isCursorOver(Ogre::OverlayElement *element, const Ogre::Vector2 &cursorPos, Ogre::Real voidBorder) -{ - Ogre::OverlayManager& om = Ogre::OverlayManager::getSingleton(); - Ogre::Real l = element->_getDerivedLeft() * om.getViewportWidth(); - Ogre::Real t = element->_getDerivedTop() * om.getViewportHeight(); - Ogre::Real r = l + element->getWidth(); - Ogre::Real b = t + element->getHeight(); - - return (cursorPos.x >= l + voidBorder && cursorPos.x <= r - voidBorder && - cursorPos.y >= t + voidBorder && cursorPos.y <= b - voidBorder); -} - -Ogre::Vector2 Widget::cursorOffset(Ogre::OverlayElement *element, const Ogre::Vector2 &cursorPos) -{ - Ogre::OverlayManager& om = Ogre::OverlayManager::getSingleton(); - return Ogre::Vector2(cursorPos.x - (element->_getDerivedLeft() * om.getViewportWidth() + element->getWidth() / 2), - cursorPos.y - (element->_getDerivedTop() * om.getViewportHeight() + element->getHeight() / 2)); -} - -Ogre::Real Widget::getCaptionWidth(const Ogre::DisplayString &caption, Ogre::TextAreaOverlayElement *area) -{ - const Ogre::FontPtr& font = area->getFont(); - font->load(); // ensure glyph info is there - Ogre::Real lineWidth = 0; - - for (unsigned int i = 0; i < caption.length(); i++) - { - // be sure to provide a line width in the text area - if (caption[i] == ' ') - { - if (area->getSpaceWidth() != 0) lineWidth += area->getSpaceWidth(); - else lineWidth += font->getGlyphInfo(' ').advance * area->getCharHeight(); - } - else if (caption[i] == '\n') break; - // use glyph information to calculate line width - else lineWidth += font->getGlyphInfo(caption[i]).advance * area->getCharHeight(); - } - - return (unsigned int)lineWidth; -} - -void Widget::fitCaptionToArea(const Ogre::DisplayString &caption, Ogre::TextAreaOverlayElement *area, Ogre::Real maxWidth) -{ - Ogre::FontPtr f = area->getFont(); - f->load(); - Ogre::String s = caption; - - size_t nl = s.find('\n'); - if (nl != Ogre::String::npos) s = s.substr(0, nl); - - Ogre::Real width = 0; - - for (unsigned int i = 0; i < s.length(); i++) - { - if (s[i] == ' ' && area->getSpaceWidth() != 0) width += area->getSpaceWidth(); - else width += f->getGlyphInfo(s[i]).advance * area->getCharHeight(); - if (width > maxWidth) - { - s = s.substr(0, i); - break; - } - } - - area->setCaption(s); -} - -Button::Button(const Ogre::String &name, const Ogre::DisplayString &caption, Ogre::Real width) -{ - mElement = Ogre::OverlayManager::getSingleton().createOverlayElementFromTemplate("SdkTrays/Button", "BorderPanel", name); - mBP = (Ogre::BorderPanelOverlayElement*)mElement; - mTextArea = (Ogre::TextAreaOverlayElement*)mBP->getChild(mBP->getName() + "/ButtonCaption"); -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - mTextArea->setCharHeight(mTextArea->getCharHeight() - 3); -#endif - mTextArea->setTop(-(mTextArea->getCharHeight() / 2)); - - if (width > 0) - { - mElement->setWidth(width); - mFitToContents = false; - } - else mFitToContents = true; - - setCaption(caption); - mState = BS_UP; -} - -void Button::setCaption(const Ogre::DisplayString &caption) -{ - mTextArea->setCaption(caption); - if (mFitToContents) mElement->setWidth(getCaptionWidth(caption, mTextArea) + mElement->getHeight() - 12); -} - -void Button::_cursorPressed(const Ogre::Vector2 &cursorPos) -{ - if (isCursorOver(mElement, cursorPos, 4)) setState(BS_DOWN); -} - -void Button::_cursorReleased(const Ogre::Vector2 &cursorPos) -{ - if (mState == BS_DOWN) - { - setState(BS_OVER); - if (mListener) mListener->buttonHit(this); - } -} - -void Button::_cursorMoved(const Ogre::Vector2 &cursorPos, float wheelDelta) -{ - if (isCursorOver(mElement, cursorPos, 4)) - { - if (mState == BS_UP) setState(BS_OVER); - } - else - { - if (mState != BS_UP) setState(BS_UP); - } -} - -void Button::_focusLost() -{ - setState(BS_UP); // reset button if cursor was lost -} - -void Button::setState(const ButtonState &bs) -{ - if (bs == BS_OVER) - { - mBP->setBorderMaterialName("SdkTrays/Button/Over"); - mBP->setMaterialName("SdkTrays/Button/Over"); - } - else if (bs == BS_UP) - { - mBP->setBorderMaterialName("SdkTrays/Button/Up"); - mBP->setMaterialName("SdkTrays/Button/Up"); - } - else - { - mBP->setBorderMaterialName("SdkTrays/Button/Down"); - mBP->setMaterialName("SdkTrays/Button/Down"); - } - - mState = bs; -} - -TextBox::TextBox(const Ogre::String &name, const Ogre::DisplayString &caption, Ogre::Real width, Ogre::Real height) -{ - mElement = Ogre::OverlayManager::getSingleton().createOverlayElementFromTemplate("SdkTrays/TextBox", "BorderPanel", name); - mElement->setWidth(width); - mElement->setHeight(height); - Ogre::OverlayContainer* container = (Ogre::OverlayContainer*)mElement; - mTextArea = (Ogre::TextAreaOverlayElement*)container->getChild(getName() + "/TextBoxText"); - mCaptionBar = (Ogre::BorderPanelOverlayElement*)container->getChild(getName() + "/TextBoxCaptionBar"); - mCaptionBar->setWidth(width - 4); - mCaptionTextArea = (Ogre::TextAreaOverlayElement*)mCaptionBar->getChild(mCaptionBar->getName() + "/TextBoxCaption"); - setCaption(caption); - mScrollTrack = (Ogre::BorderPanelOverlayElement*)container->getChild(getName() + "/TextBoxScrollTrack"); - mScrollHandle = (Ogre::PanelOverlayElement*)mScrollTrack->getChild(mScrollTrack->getName() + "/TextBoxScrollHandle"); - mScrollHandle->hide(); - mDragging = false; - mScrollPercentage = 0; - mStartingLine = 0; - mPadding = 15; - mText = ""; -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - mTextArea->setCharHeight(mTextArea->getCharHeight() - 3); - mCaptionTextArea->setCharHeight(mCaptionTextArea->getCharHeight() - 3); -#endif - refitContents(); -} - -void TextBox::setPadding(Ogre::Real padding) -{ - mPadding = padding; - refitContents(); -} - -void TextBox::setText(const Ogre::DisplayString &text) -{ - mText = text; - mLines.clear(); - - Ogre::FontPtr font = mTextArea->getFont(); - font->load(); // ensure glyph info is there - - Ogre::String current = text; - bool firstWord = true; - unsigned int lastSpace = 0; - unsigned int lineBegin = 0; - Ogre::Real lineWidth = 0; - Ogre::Real rightBoundary = mElement->getWidth() - 2 * mPadding + mScrollTrack->getLeft() + 10; - - for (unsigned int i = 0; i < current.length(); i++) - { - if (current[i] == ' ') - { - if (mTextArea->getSpaceWidth() != 0) lineWidth += mTextArea->getSpaceWidth(); - else lineWidth += font->getGlyphInfo(' ').advance * mTextArea->getCharHeight(); - firstWord = false; - lastSpace = i; - } - else if (current[i] == '\n') - { - firstWord = true; - lineWidth = 0; - mLines.push_back(current.substr(lineBegin, i - lineBegin)); - lineBegin = i + 1; - } - else - { - // use glyph information to calculate line width - lineWidth += font->getGlyphInfo(current[i]).advance * mTextArea->getCharHeight(); - if (lineWidth > rightBoundary) - { - if (firstWord) - { - current.insert(i, "\n"); - i = i - 1; - } - else - { - current[lastSpace] = '\n'; - i = lastSpace - 1; - } - } - } - } - - mLines.push_back(current.substr(lineBegin)); - - unsigned int maxLines = getHeightInLines(); - - if (mLines.size() > maxLines) // if too much text, filter based on scroll percentage - { - mScrollHandle->show(); - filterLines(); - } - else // otherwise just show all the text - { - mTextArea->setCaption(current); - mScrollHandle->hide(); - mScrollPercentage = 0; - mScrollHandle->setTop(0); - } -} - -void TextBox::setTextAlignment(Ogre::TextAreaOverlayElement::Alignment ta) -{ - if (ta == Ogre::TextAreaOverlayElement::Left) mTextArea->setHorizontalAlignment(Ogre::GHA_LEFT); - else if (ta == Ogre::TextAreaOverlayElement::Center) mTextArea->setHorizontalAlignment(Ogre::GHA_CENTER); - else mTextArea->setHorizontalAlignment(Ogre::GHA_RIGHT); - refitContents(); -} - -void TextBox::refitContents() -{ - mScrollTrack->setHeight(mElement->getHeight() - mCaptionBar->getHeight() - 20); - mScrollTrack->setTop(mCaptionBar->getHeight() + 10); - - mTextArea->setTop(mCaptionBar->getHeight() + mPadding - 5); - if (mTextArea->getHorizontalAlignment() == Ogre::GHA_RIGHT) mTextArea->setLeft(-mPadding + mScrollTrack->getLeft()); - else if (mTextArea->getHorizontalAlignment() == Ogre::GHA_LEFT) mTextArea->setLeft(mPadding); - else mTextArea->setLeft(mScrollTrack->getLeft() / 2); - - setText(getText()); -} - -void TextBox::setScrollPercentage(Ogre::Real percentage) -{ - mScrollPercentage = Ogre::Math::Clamp(percentage, 0, 1); - mScrollHandle->setTop((int)(percentage * (mScrollTrack->getHeight() - mScrollHandle->getHeight()))); - filterLines(); -} - -void TextBox::_cursorPressed(const Ogre::Vector2 &cursorPos) -{ - if (!mScrollHandle->isVisible()) return; // don't care about clicks if text not scrollable - - Ogre::Vector2 co = Widget::cursorOffset(mScrollHandle, cursorPos); - - if (co.squaredLength() <= 81) - { - mDragging = true; - mDragOffset = co.y; - } - else if (Widget::isCursorOver(mScrollTrack, cursorPos)) - { - Ogre::Real newTop = mScrollHandle->getTop() + co.y; - Ogre::Real lowerBoundary = mScrollTrack->getHeight() - mScrollHandle->getHeight(); - mScrollHandle->setTop(Ogre::Math::Clamp((int)newTop, 0, (int)lowerBoundary)); - - // update text area contents based on new scroll percentage - mScrollPercentage = Ogre::Math::Clamp(newTop / lowerBoundary, 0, 1); - filterLines(); - } -} - -void TextBox::_cursorMoved(const Ogre::Vector2 &cursorPos, float wheelDelta) -{ - if (mDragging) - { - Ogre::Vector2 co = Widget::cursorOffset(mScrollHandle, cursorPos); - Ogre::Real newTop = mScrollHandle->getTop() + co.y - mDragOffset; - Ogre::Real lowerBoundary = mScrollTrack->getHeight() - mScrollHandle->getHeight(); - mScrollHandle->setTop(Ogre::Math::Clamp((int)newTop, 0, (int)lowerBoundary)); - - // update text area contents based on new scroll percentage - mScrollPercentage = Ogre::Math::Clamp(newTop / lowerBoundary, 0, 1); - filterLines(); - } -} - -void TextBox::filterLines() -{ - Ogre::String shown = ""; - unsigned int maxLines = getHeightInLines(); - unsigned int newStart = (unsigned int) (mScrollPercentage * (mLines.size() - maxLines) + 0.5); - - mStartingLine = newStart; - - for (unsigned int i = 0; i < maxLines; i++) - { - shown += mLines[mStartingLine + i] + "\n"; - } - - mTextArea->setCaption(shown); // show just the filtered lines -} - -SelectMenu::SelectMenu(const Ogre::String &name, const Ogre::DisplayString &caption, Ogre::Real width, Ogre::Real boxWidth, size_t maxItemsShown) - : mHighlightIndex(0) - , mDisplayIndex(0) - , mDragOffset(0.0f) -{ - mSelectionIndex = -1; - mFitToContents = false; - mCursorOver = false; - mExpanded = false; - mDragging = false; - mMaxItemsShown = maxItemsShown; - mItemsShown = 0; - mElement = (Ogre::BorderPanelOverlayElement*)Ogre::OverlayManager::getSingleton().createOverlayElementFromTemplate - ("SdkTrays/SelectMenu", "BorderPanel", name); - mTextArea = (Ogre::TextAreaOverlayElement*)((Ogre::OverlayContainer*)mElement)->getChild(name + "/MenuCaption"); - mSmallBox = (Ogre::BorderPanelOverlayElement*)((Ogre::OverlayContainer*)mElement)->getChild(name + "/MenuSmallBox"); - mSmallBox->setWidth(width - 10); - mSmallTextArea = (Ogre::TextAreaOverlayElement*)mSmallBox->getChild(name + "/MenuSmallBox/MenuSmallText"); - mElement->setWidth(width); -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - mTextArea->setCharHeight(mTextArea->getCharHeight() - 3); - mSmallTextArea->setCharHeight(mSmallTextArea->getCharHeight() - 3); -#endif - - if (boxWidth > 0) // long style - { - if (width <= 0) mFitToContents = true; - mSmallBox->setWidth(boxWidth); - mSmallBox->setTop(2); - mSmallBox->setLeft(width - boxWidth - 5); - mElement->setHeight(mSmallBox->getHeight() + 4); - mTextArea->setHorizontalAlignment(Ogre::GHA_LEFT); - mTextArea->setAlignment(Ogre::TextAreaOverlayElement::Left); - mTextArea->setLeft(12); - mTextArea->setTop(10); - } - - mExpandedBox = (Ogre::BorderPanelOverlayElement*)((Ogre::OverlayContainer*)mElement)->getChild(name + "/MenuExpandedBox"); - mExpandedBox->setWidth(mSmallBox->getWidth() + 10); - mExpandedBox->hide(); - mScrollTrack = (Ogre::BorderPanelOverlayElement*)mExpandedBox->getChild(mExpandedBox->getName() + "/MenuScrollTrack"); - mScrollHandle = (Ogre::PanelOverlayElement*)mScrollTrack->getChild(mScrollTrack->getName() + "/MenuScrollHandle"); - - setCaption(caption); -} - -void SelectMenu::copyItemsFrom(SelectMenu *other){ - const Ogre::StringVector& items = other->getItems(); - Ogre::StringVector::const_iterator it, itEnd; - itEnd = items.end(); - for(it=items.begin(); it != itEnd; it++){ - this->addItem(*it); - } -} - -void SelectMenu::setCaption(const Ogre::DisplayString &caption) -{ - mTextArea->setCaption(caption); - if (mFitToContents) - { - mElement->setWidth(getCaptionWidth(caption, mTextArea) + mSmallBox->getWidth() + 23); - mSmallBox->setLeft(mElement->getWidth() - mSmallBox->getWidth() - 5); - } -} - -void SelectMenu::setItems(const Ogre::StringVector &items) -{ - mItems = items; - mSelectionIndex = -1; - - for (unsigned int i = 0; i < mItemElements.size(); i++) // destroy all the item elements - { - nukeOverlayElement(mItemElements[i]); - } - mItemElements.clear(); - - mItemsShown = Ogre::Math::Clamp(mMaxItemsShown, 1, mItems.size()); - - for (unsigned int i = 0; i < mItemsShown; i++) // create all the item elements - { - Ogre::BorderPanelOverlayElement* e = - (Ogre::BorderPanelOverlayElement*)Ogre::OverlayManager::getSingleton().createOverlayElementFromTemplate - ("SdkTrays/SelectMenuItem", "BorderPanel", - mExpandedBox->getName() + "/Item" + Ogre::StringConverter::toString(i + 1)); - - e->setTop(6 + i * (mSmallBox->getHeight() - 8)); - e->setWidth(mExpandedBox->getWidth() - 32); - - mExpandedBox->addChild(e); - mItemElements.push_back(e); - } - - if (!items.empty()) selectItem(0, false); - else mSmallTextArea->setCaption(""); -} - -void SelectMenu::removeItem(const Ogre::DisplayString &item) -{ - for (size_t i=0; i < mItems.size(); i++) - { - if (item == mItems[i]) { - removeItem(static_cast(i)); - i--; // check again same index - } - } -} - -void SelectMenu::removeItem(size_t index) -{ - if(index >= mItems.size()){ - Ogre::String desc = "Menu \"" + getName() + "\" contains no item at position " + - Ogre::StringConverter::toString(index) + "."; - OGRE_EXCEPT(Ogre::Exception::ERR_ITEM_NOT_FOUND, desc, "SelectMenu::removeItem"); - } - mItems.erase(mItems.begin() + index); - - if (mItems.size() < mItemsShown) - { - mItemsShown = static_cast(mItems.size()); - nukeOverlayElement(mItemElements.back()); - mItemElements.pop_back(); - } - if((size_t)mSelectionIndex == index){ - if(index < mItems.size()) { - // update the text of the menu - selectItem(index); - } else if (!mItems.empty()){ - // last item was selected and we removed it - selectItem(index - 1); - } else { - // we had only 1 item, but we removed it, so clear caption - mSmallTextArea->setCaption(""); - } - } -} - -void SelectMenu::clearItems() -{ - mItems.clear(); - mSelectionIndex = -1; - mSmallTextArea->setCaption(""); -} - -void SelectMenu::selectItem(size_t index, bool notifyListener) -{ - if (index >= mItems.size()) - { - Ogre::String desc = "Menu \"" + getName() + "\" contains no item at position " + - Ogre::StringConverter::toString(index) + "."; - OGRE_EXCEPT(Ogre::Exception::ERR_ITEM_NOT_FOUND, desc, "SelectMenu::selectItem"); - } - - mSelectionIndex = (int)index; - fitCaptionToArea(mItems[index], mSmallTextArea, mSmallBox->getWidth() - mSmallTextArea->getLeft() * 2); - - if (mListener && notifyListener) mListener->itemSelected(this); -} - -bool SelectMenu::containsItem(const Ogre::DisplayString &item) -{ - bool res = false; - for (unsigned int i = 0; i < mItems.size(); i++) - { - if (item == mItems[i]) - { - res = true; - break; - } - } - - return res; -} - -void SelectMenu::selectItem(const Ogre::DisplayString &item, bool notifyListener) -{ - for (unsigned int i = 0; i < mItems.size(); i++) - { - if (item == mItems[i]) - { - selectItem(i, notifyListener); - return; - } - } - - Ogre::String desc = "Menu \"" + getName() + "\" contains no item \"" + item + "\"."; - OGRE_EXCEPT(Ogre::Exception::ERR_ITEM_NOT_FOUND, desc, "SelectMenu::selectItem"); -} - -Ogre::DisplayString SelectMenu::getSelectedItem() -{ - if (mSelectionIndex == -1) - { - Ogre::String desc = "Menu \"" + getName() + "\" has no item selected."; - OGRE_EXCEPT(Ogre::Exception::ERR_ITEM_NOT_FOUND, desc, "SelectMenu::getSelectedItem"); - return ""; - } - else return mItems[mSelectionIndex]; -} - -void SelectMenu::_cursorPressed(const Ogre::Vector2 &cursorPos) -{ - Ogre::OverlayManager& om = Ogre::OverlayManager::getSingleton(); - - if (mExpanded) - { - if (mScrollHandle->isVisible()) // check for scrolling - { - Ogre::Vector2 co = Widget::cursorOffset(mScrollHandle, cursorPos); - - if (co.squaredLength() <= 81) - { - mDragging = true; - mDragOffset = co.y; - return; - } - else if (Widget::isCursorOver(mScrollTrack, cursorPos)) - { - Ogre::Real newTop = mScrollHandle->getTop() + co.y; - Ogre::Real lowerBoundary = mScrollTrack->getHeight() - mScrollHandle->getHeight(); - mScrollHandle->setTop(Ogre::Math::Clamp((int)newTop, 0, (int)lowerBoundary)); - - Ogre::Real scrollPercentage = Ogre::Math::Clamp(newTop / lowerBoundary, 0, 1); - setDisplayIndex((unsigned int)(scrollPercentage * (mItems.size() - mItemElements.size()) + 0.5)); - return; - } - } - - if (!isCursorOver(mExpandedBox, cursorPos, 3)) retract(); - else - { - Ogre::Real l = mItemElements.front()->_getDerivedLeft() * om.getViewportWidth() + 5; - Ogre::Real t = mItemElements.front()->_getDerivedTop() * om.getViewportHeight() + 5; - Ogre::Real r = l + mItemElements.back()->getWidth() - 10; - Ogre::Real b = mItemElements.back()->_getDerivedTop() * om.getViewportHeight() + - mItemElements.back()->getHeight() - 5; - - if (cursorPos.x >= l && cursorPos.x <= r && cursorPos.y >= t && cursorPos.y <= b) - { - if (mHighlightIndex != mSelectionIndex) selectItem(mHighlightIndex); - retract(); - } - } - } - else - { - if (mItems.size() < 2) return; // don't waste time showing a menu if there's no choice - - if (isCursorOver(mSmallBox, cursorPos, 4)) - { - mExpandedBox->show(); - mSmallBox->hide(); - - // calculate how much vertical space we need - Ogre::Real idealHeight = mItemsShown * (mSmallBox->getHeight() - 8) + 20; - mExpandedBox->setHeight(idealHeight); - mScrollTrack->setHeight(mExpandedBox->getHeight() - 20); - - mExpandedBox->setLeft(mSmallBox->getLeft() - 4); - - // if the expanded menu goes down off the screen, make it go up instead - if (mSmallBox->_getDerivedTop() * om.getViewportHeight() + idealHeight > om.getViewportHeight()) - { - mExpandedBox->setTop(mSmallBox->getTop() + mSmallBox->getHeight() - idealHeight + 3); - // if we're in thick style, hide the caption because it will interfere with the expanded menu - if (mTextArea->getHorizontalAlignment() == Ogre::GHA_CENTER) mTextArea->hide(); - } - else mExpandedBox->setTop(mSmallBox->getTop() + 3); - - mExpanded = true; - mHighlightIndex = mSelectionIndex; - setDisplayIndex(mHighlightIndex); - - if (mItemsShown < mItems.size()) // update scrollbar position - { - mScrollHandle->show(); - Ogre::Real lowerBoundary = mScrollTrack->getHeight() - mScrollHandle->getHeight(); - mScrollHandle->setTop((int)(mDisplayIndex * lowerBoundary / (mItems.size() - mItemElements.size()))); - } - else mScrollHandle->hide(); - } - } -} - -void SelectMenu::_cursorMoved(const Ogre::Vector2 &cursorPos, float wheelDelta) -{ - Ogre::OverlayManager& om = Ogre::OverlayManager::getSingleton(); - - if (mExpanded) - { - if (mDragging) - { - Ogre::Vector2 co = Widget::cursorOffset(mScrollHandle, cursorPos); - Ogre::Real newTop = mScrollHandle->getTop() + co.y - mDragOffset; - Ogre::Real lowerBoundary = mScrollTrack->getHeight() - mScrollHandle->getHeight(); - mScrollHandle->setTop(Ogre::Math::Clamp((int)newTop, 0, (int)lowerBoundary)); - - Ogre::Real scrollPercentage = Ogre::Math::Clamp(newTop / lowerBoundary, 0, 1); - int newIndex = (int) (scrollPercentage * (mItems.size() - mItemElements.size()) + 0.5); - if (newIndex != mDisplayIndex) setDisplayIndex(newIndex); - return; - } - else if(fabsf(wheelDelta) > 0.5f) - { - int newIndex = Ogre::Math::Clamp(mDisplayIndex + (wheelDelta > 0 ? -1 : 1), 0, (int)(mItems.size() - mItemElements.size())); - Ogre::Real lowerBoundary = mScrollTrack->getHeight() - mScrollHandle->getHeight(); - mScrollHandle->setTop((int)(newIndex * lowerBoundary / (mItems.size() - mItemElements.size()))); - setDisplayIndex(newIndex); - } - - Ogre::Real l = mItemElements.front()->_getDerivedLeft() * om.getViewportWidth() + 5; - Ogre::Real t = mItemElements.front()->_getDerivedTop() * om.getViewportHeight() + 5; - Ogre::Real r = l + mItemElements.back()->getWidth() - 10; - Ogre::Real b = mItemElements.back()->_getDerivedTop() * om.getViewportHeight() + - mItemElements.back()->getHeight() - 5; - - if (cursorPos.x >= l && cursorPos.x <= r && cursorPos.y >= t && cursorPos.y <= b) - { - int newIndex = (int)(mDisplayIndex + (cursorPos.y - t) / (b - t) * mItemElements.size()); - if (mHighlightIndex != newIndex) - { - mHighlightIndex = newIndex; - setDisplayIndex(mDisplayIndex); - } - } - } - else - { - if (isCursorOver(mSmallBox, cursorPos, 4)) - { - mSmallBox->setMaterialName("SdkTrays/MiniTextBox/Over"); - mSmallBox->setBorderMaterialName("SdkTrays/MiniTextBox/Over"); - mCursorOver = true; - } - else - { - if (mCursorOver) - { - mSmallBox->setMaterialName("SdkTrays/MiniTextBox"); - mSmallBox->setBorderMaterialName("SdkTrays/MiniTextBox"); - mCursorOver = false; - } - } - } -} - -void SelectMenu::setDisplayIndex(unsigned int index) -{ - index = std::min(index, (int)(mItems.size() - mItemElements.size())); - mDisplayIndex = index; - - for (int i = 0; i < (int)mItemElements.size(); i++) - { - Ogre::BorderPanelOverlayElement *ie = mItemElements[i]; - Ogre::TextAreaOverlayElement *ta = (Ogre::TextAreaOverlayElement*)ie->getChild(ie->getName() + "/MenuItemText"); - - fitCaptionToArea(mItems[mDisplayIndex + i], ta, ie->getWidth() - 2 * ta->getLeft()); - - if ((mDisplayIndex + i) == mHighlightIndex) - { - ie->setMaterialName("SdkTrays/MiniTextBox/Over"); - ie->setBorderMaterialName("SdkTrays/MiniTextBox/Over"); - } - else - { - ie->setMaterialName("SdkTrays/MiniTextBox"); - ie->setBorderMaterialName("SdkTrays/MiniTextBox"); - } - } -} - -void SelectMenu::retract() -{ - mDragging = false; - mExpanded = false; - mExpandedBox->hide(); - mTextArea->show(); - mSmallBox->show(); - mSmallBox->setMaterialName("SdkTrays/MiniTextBox"); - mSmallBox->setBorderMaterialName("SdkTrays/MiniTextBox"); -} - -Label::Label(const Ogre::String &name, const Ogre::DisplayString &caption, Ogre::Real width) -{ - mElement = Ogre::OverlayManager::getSingleton().createOverlayElementFromTemplate("SdkTrays/Label", "BorderPanel", name); - mTextArea = (Ogre::TextAreaOverlayElement*)((Ogre::OverlayContainer*)mElement)->getChild(getName() + "/LabelCaption"); -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - mTextArea->setCharHeight(mTextArea->getCharHeight() - 3); -#endif - setCaption(caption); - if (width <= 0) mFitToTray = true; - else - { - mFitToTray = false; - mElement->setWidth(width); - } -} - -void Label::_cursorPressed(const Ogre::Vector2 &cursorPos) -{ - if (mListener && isCursorOver(mElement, cursorPos, 3)) mListener->labelHit(this); -} - -Separator::Separator(const Ogre::String &name, Ogre::Real width) -{ - mElement = Ogre::OverlayManager::getSingleton().createOverlayElementFromTemplate("SdkTrays/Separator", "Panel", name); - if (width <= 0) mFitToTray = true; - else - { - mFitToTray = false; - mElement->setWidth(width); - } -} - -Slider::Slider(const Ogre::String &name, const Ogre::DisplayString &caption, Ogre::Real width, Ogre::Real trackWidth, Ogre::Real valueBoxWidth, Ogre::Real minValue, Ogre::Real maxValue, unsigned int snaps) - : mDragOffset(0.0f) - , mValue(0.0f) - , mMinValue(0.0f) - , mMaxValue(0.0f) - , mInterval(0.0f) -{ - mDragging = false; - mFitToContents = false; - mElement = Ogre::OverlayManager::getSingleton().createOverlayElementFromTemplate - ("SdkTrays/Slider", "BorderPanel", name); - mElement->setWidth(width); - Ogre::OverlayContainer* c = (Ogre::OverlayContainer*)mElement; - mTextArea = (Ogre::TextAreaOverlayElement*)c->getChild(getName() + "/SliderCaption"); - Ogre::OverlayContainer* valueBox = (Ogre::OverlayContainer*)c->getChild(getName() + "/SliderValueBox"); - valueBox->setWidth(valueBoxWidth); - valueBox->setLeft(-(valueBoxWidth + 5)); - mValueTextArea = (Ogre::TextAreaOverlayElement*)valueBox->getChild(valueBox->getName() + "/SliderValueText"); - mTrack = (Ogre::BorderPanelOverlayElement*)c->getChild(getName() + "/SliderTrack"); - mHandle = (Ogre::PanelOverlayElement*)mTrack->getChild(mTrack->getName() + "/SliderHandle"); -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - mTextArea->setCharHeight(mTextArea->getCharHeight() - 3); - mValueTextArea->setCharHeight(mValueTextArea->getCharHeight() - 3); -#endif - - if (trackWidth <= 0) // tall style - { - mTrack->setWidth(width - 16); - } - else // long style - { - if (width <= 0) mFitToContents = true; - mElement->setHeight(34); - mTextArea->setTop(10); - valueBox->setTop(2); - mTrack->setTop(-23); - mTrack->setWidth(trackWidth); - mTrack->setHorizontalAlignment(Ogre::GHA_RIGHT); - mTrack->setLeft(-(trackWidth + valueBoxWidth + 5)); - } - - setCaption(caption); - setRange(minValue, maxValue, snaps, false); -} - -void Slider::setRange(Ogre::Real minValue, Ogre::Real maxValue, unsigned int snaps, bool notifyListener) -{ - mMinValue = minValue; - mMaxValue = maxValue; - - if (snaps <= 1 || mMinValue >= mMaxValue) - { - mInterval = 0; - mHandle->hide(); - mValue = minValue; - if (snaps == 1) mValueTextArea->setCaption(Ogre::StringConverter::toString(mMinValue)); - else mValueTextArea->setCaption(""); - } - else - { - mHandle->show(); - mInterval = (maxValue - minValue) / (snaps - 1); - setValue(minValue, notifyListener); - } -} - -void Slider::setValue(Ogre::Real value, bool notifyListener) -{ - if (mInterval == 0) return; - - mValue = Ogre::Math::Clamp(value, mMinValue, mMaxValue); - - setValueCaption(Ogre::StringConverter::toString(mValue)); - - if (mListener && notifyListener) mListener->sliderMoved(this); - - if (!mDragging) mHandle->setLeft((int)((mValue - mMinValue) / (mMaxValue - mMinValue) * - (mTrack->getWidth() - mHandle->getWidth()))); -} - -void Slider::setCaption(const Ogre::DisplayString &caption) -{ - mTextArea->setCaption(caption); - - if (mFitToContents) mElement->setWidth(getCaptionWidth(caption, mTextArea) + - mValueTextArea->getParent()->getWidth() + mTrack->getWidth() + 26); -} - -void Slider::_cursorPressed(const Ogre::Vector2 &cursorPos) -{ - if (!mHandle->isVisible()) return; - - Ogre::Vector2 co = Widget::cursorOffset(mHandle, cursorPos); - - if (co.squaredLength() <= 81) - { - mDragging = true; - mDragOffset = co.x; - } - else if (Widget::isCursorOver(mTrack, cursorPos)) - { - Ogre::Real newLeft = mHandle->getLeft() + co.x; - Ogre::Real rightBoundary = mTrack->getWidth() - mHandle->getWidth(); - - mHandle->setLeft(Ogre::Math::Clamp((int)newLeft, 0, (int)rightBoundary)); - setValue(getSnappedValue(newLeft / rightBoundary)); - } -} - -void Slider::_cursorReleased(const Ogre::Vector2 &cursorPos) -{ - if (mDragging) - { - mDragging = false; - mHandle->setLeft((int)((mValue - mMinValue) / (mMaxValue - mMinValue) * - (mTrack->getWidth() - mHandle->getWidth()))); - } -} - -void Slider::_cursorMoved(const Ogre::Vector2 &cursorPos, float wheelDelta) -{ - if (mDragging) - { - Ogre::Vector2 co = Widget::cursorOffset(mHandle, cursorPos); - Ogre::Real newLeft = mHandle->getLeft() + co.x - mDragOffset; - Ogre::Real rightBoundary = mTrack->getWidth() - mHandle->getWidth(); - - mHandle->setLeft(Ogre::Math::Clamp((int)newLeft, 0, (int)rightBoundary)); - setValue(getSnappedValue(newLeft / rightBoundary)); - - // sync mHandle's mPixelLeft with mLeft - // if multiple "mouseMoved" happened during one frame, mLeft could be incorrect otherwise - mHandle->_update(); - } -} - -ParamsPanel::ParamsPanel(const Ogre::String &name, Ogre::Real width, unsigned int lines) -{ - mElement = Ogre::OverlayManager::getSingleton().createOverlayElementFromTemplate - ("SdkTrays/ParamsPanel", "BorderPanel", name); - Ogre::OverlayContainer* c = (Ogre::OverlayContainer*)mElement; - mNamesArea = (Ogre::TextAreaOverlayElement*)c->getChild(getName() + "/ParamsPanelNames"); - mValuesArea = (Ogre::TextAreaOverlayElement*)c->getChild(getName() + "/ParamsPanelValues"); -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - mNamesArea->setCharHeight(mNamesArea->getCharHeight() - 3); - mValuesArea->setCharHeight(mValuesArea->getCharHeight() - 3); -#endif - mElement->setWidth(width); - mElement->setHeight(mNamesArea->getTop() * 2 + lines * mNamesArea->getCharHeight()); -} - -void ParamsPanel::setAllParamNames(const Ogre::StringVector ¶mNames) -{ - mNames = paramNames; - mValues.clear(); - mValues.resize(mNames.size(), ""); - mElement->setHeight(mNamesArea->getTop() * 2 + mNames.size() * mNamesArea->getCharHeight()); - updateText(); -} - -void ParamsPanel::setAllParamValues(const Ogre::StringVector ¶mValues) -{ - mValues = paramValues; - mValues.resize(mNames.size(), ""); - updateText(); -} - -void ParamsPanel::setParamValue(const Ogre::DisplayString ¶mName, const Ogre::DisplayString ¶mValue) -{ - for (unsigned int i = 0; i < mNames.size(); i++) - { - if (mNames[i] == paramName) - { - mValues[i] = paramValue; - updateText(); - return; - } - } - - Ogre::String desc = "ParamsPanel \"" + getName() + "\" has no parameter \"" + paramName + "\"."; - OGRE_EXCEPT(Ogre::Exception::ERR_ITEM_NOT_FOUND, desc, "ParamsPanel::setParamValue"); -} - -void ParamsPanel::setParamValue(unsigned int index, const Ogre::DisplayString ¶mValue) -{ - if (index >= mNames.size()) - { - Ogre::String desc = "ParamsPanel \"" + getName() + "\" has no parameter at position " + - Ogre::StringConverter::toString(index) + "."; - OGRE_EXCEPT(Ogre::Exception::ERR_ITEM_NOT_FOUND, desc, "ParamsPanel::setParamValue"); - } - - mValues[index] = paramValue; - updateText(); -} - -Ogre::DisplayString ParamsPanel::getParamValue(const Ogre::DisplayString ¶mName) -{ - for (unsigned int i = 0; i < mNames.size(); i++) - { - if (mNames[i] == paramName) return mValues[i]; - } - - Ogre::String desc = "ParamsPanel \"" + getName() + "\" has no parameter \"" + paramName + "\"."; - OGRE_EXCEPT(Ogre::Exception::ERR_ITEM_NOT_FOUND, desc, "ParamsPanel::getParamValue"); - return ""; -} - -Ogre::DisplayString ParamsPanel::getParamValue(unsigned int index) -{ - if (index >= mNames.size()) - { - Ogre::String desc = "ParamsPanel \"" + getName() + "\" has no parameter at position " + - Ogre::StringConverter::toString(index) + "."; - OGRE_EXCEPT(Ogre::Exception::ERR_ITEM_NOT_FOUND, desc, "ParamsPanel::getParamValue"); - } - - return mValues[index]; -} - -void ParamsPanel::updateText() -{ - Ogre::DisplayString namesDS; - Ogre::DisplayString valuesDS; - - for (unsigned int i = 0; i < mNames.size(); i++) - { - namesDS.append(mNames[i] + ":\n"); - valuesDS.append(mValues[i] + "\n"); - } - - mNamesArea->setCaption(namesDS); - mValuesArea->setCaption(valuesDS); -} - -CheckBox::CheckBox(const Ogre::String &name, const Ogre::DisplayString &caption, Ogre::Real width) -{ - mCursorOver = false; - mFitToContents = width <= 0; - mElement = Ogre::OverlayManager::getSingleton().createOverlayElementFromTemplate - ("SdkTrays/CheckBox", "BorderPanel", name); - Ogre::OverlayContainer* c = (Ogre::OverlayContainer*)mElement; - mTextArea = (Ogre::TextAreaOverlayElement*)c->getChild(getName() + "/CheckBoxCaption"); - mSquare = (Ogre::BorderPanelOverlayElement*)c->getChild(getName() + "/CheckBoxSquare"); - mX = mSquare->getChild(mSquare->getName() + "/CheckBoxX"); - mX->hide(); - mElement->setWidth(width); -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - mTextArea->setCharHeight(mTextArea->getCharHeight() - 3); -#endif - setCaption(caption); -} - -void CheckBox::setCaption(const Ogre::DisplayString &caption) -{ - mTextArea->setCaption(caption); - if (mFitToContents) mElement->setWidth(getCaptionWidth(caption, mTextArea) + mSquare->getWidth() + 23); -} - -void CheckBox::setChecked(bool checked, bool notifyListener) -{ - if (checked) mX->show(); - else mX->hide(); - if (mListener && notifyListener) mListener->checkBoxToggled(this); -} - -void CheckBox::toggle(bool notifyListener) -{ - setChecked(!isChecked(), notifyListener); -} - -void CheckBox::_cursorPressed(const Ogre::Vector2 &cursorPos) -{ - if (mCursorOver && mListener) toggle(); -} - -void CheckBox::_cursorMoved(const Ogre::Vector2 &cursorPos, float wheelDelta) -{ - if (isCursorOver(mSquare, cursorPos, 5)) - { - if (!mCursorOver) - { - mCursorOver = true; - mSquare->setMaterialName("SdkTrays/MiniTextBox/Over"); - mSquare->setBorderMaterialName("SdkTrays/MiniTextBox/Over"); - } - } - else - { - if (mCursorOver) - { - mCursorOver = false; - mSquare->setMaterialName("SdkTrays/MiniTextBox"); - mSquare->setBorderMaterialName("SdkTrays/MiniTextBox"); - } - } -} - -void CheckBox::_focusLost() -{ - mSquare->setMaterialName("SdkTrays/MiniTextBox"); - mSquare->setBorderMaterialName("SdkTrays/MiniTextBox"); - mCursorOver = false; -} - -DecorWidget::DecorWidget(const Ogre::String &name, const Ogre::String &templateName) -{ - mElement = Ogre::OverlayManager::getSingleton().createOverlayElementFromTemplate(templateName, "", name); -} - -ProgressBar::ProgressBar(const Ogre::String &name, const Ogre::DisplayString &caption, Ogre::Real width, Ogre::Real commentBoxWidth) - : mProgress(0.0f) -{ - mElement = Ogre::OverlayManager::getSingleton().createOverlayElementFromTemplate - ("SdkTrays/ProgressBar", "BorderPanel", name); - mElement->setWidth(width); - Ogre::OverlayContainer* c = (Ogre::OverlayContainer*)mElement; - mTextArea = (Ogre::TextAreaOverlayElement*)c->getChild(getName() + "/ProgressCaption"); - Ogre::OverlayContainer* commentBox = (Ogre::OverlayContainer*)c->getChild(getName() + "/ProgressCommentBox"); - commentBox->setWidth(commentBoxWidth); - commentBox->setLeft(-(commentBoxWidth + 5)); - mCommentTextArea = (Ogre::TextAreaOverlayElement*)commentBox->getChild(commentBox->getName() + "/ProgressCommentText"); - mMeter = c->getChild(getName() + "/ProgressMeter"); - mMeter->setWidth(width - 10); - mFill = ((Ogre::OverlayContainer*)mMeter)->getChild(mMeter->getName() + "/ProgressFill"); - setCaption(caption); -} - -void ProgressBar::setProgress(Ogre::Real progress) -{ - mProgress = Ogre::Math::Clamp(progress, 0, 1); - mFill->setWidth(std::max((int)mFill->getHeight(), (int)(mProgress * (mMeter->getWidth() - 2 * mFill->getLeft())))); -} - -TrayManager::TrayManager(const Ogre::String &name, Ogre::RenderWindow *window, TrayListener *listener) : - mName(name), mWindow(window), mWidgetDeathRow(), mListener(listener), mWidgetPadding(8), - mWidgetSpacing(2), mTrayPadding(0), mTrayDrag(false), mExpandedMenu(0), mDialog(0), mOk(0), mYes(0), - mNo(0), mCursorWasVisible(false), mFpsLabel(0), mStatsPanel(0), mLogo(0), mLoadBar(0), - mGroupInitProportion(0.0f), mGroupLoadProportion(0.0f), mLoadInc(0.0f) -{ - mTimer = Ogre::Root::getSingleton().getTimer(); - mLastStatUpdateTime = -FRAME_UPDATE_DELAY; // update immediately on first call - - Ogre::OverlayManager& om = Ogre::OverlayManager::getSingleton(); - - Ogre::String nameBase = mName + "/"; - std::replace(nameBase.begin(), nameBase.end(), ' ', '_'); - - // create overlay layers for everything - mBackdropLayer = om.create(nameBase + "BackdropLayer"); - mTraysLayer = om.create(nameBase + "WidgetsLayer"); - mPriorityLayer = om.create(nameBase + "PriorityLayer"); - mCursorLayer = om.create(nameBase + "CursorLayer"); - mBackdropLayer->setZOrder(100); - mTraysLayer->setZOrder(200); - mPriorityLayer->setZOrder(300); - mCursorLayer->setZOrder(400); - - // make backdrop and cursor overlay containers - mCursor = (Ogre::OverlayContainer*)om.createOverlayElementFromTemplate("SdkTrays/Cursor", "Panel", nameBase + "Cursor"); - mCursorLayer->add2D(mCursor); - mBackdrop = (Ogre::OverlayContainer*)om.createOverlayElement("Panel", nameBase + "Backdrop"); - mBackdropLayer->add2D(mBackdrop); - mDialogShade = (Ogre::OverlayContainer*)om.createOverlayElement("Panel", nameBase + "DialogShade"); - mDialogShade->setMaterialName("SdkTrays/Shade"); - mDialogShade->hide(); - mPriorityLayer->add2D(mDialogShade); - - Ogre::String trayNames[] = - { "TopLeft", "Top", "TopRight", "Left", "Center", "Right", "BottomLeft", "Bottom", "BottomRight" }; - - for (unsigned int i = 0; i < 9; i++) // make the real trays - { - mTrays[i] = (Ogre::OverlayContainer*)om.createOverlayElementFromTemplate - ("SdkTrays/Tray", "BorderPanel", nameBase + trayNames[i] + "Tray"); - mTraysLayer->add2D(mTrays[i]); - - mTrayWidgetAlign[i] = Ogre::GHA_CENTER; - - // align trays based on location - if (i == TL_TOP || i == TL_CENTER || i == TL_BOTTOM) mTrays[i]->setHorizontalAlignment(Ogre::GHA_CENTER); - if (i == TL_LEFT || i == TL_CENTER || i == TL_RIGHT) mTrays[i]->setVerticalAlignment(Ogre::GVA_CENTER); - if (i == TL_TOPRIGHT || i == TL_RIGHT || i == TL_BOTTOMRIGHT) mTrays[i]->setHorizontalAlignment(Ogre::GHA_RIGHT); - if (i == TL_BOTTOMLEFT || i == TL_BOTTOM || i == TL_BOTTOMRIGHT) mTrays[i]->setVerticalAlignment(Ogre::GVA_BOTTOM); - } - - // create the null tray for free-floating widgets - mTrays[9] = (Ogre::OverlayContainer*)om.createOverlayElement("Panel", nameBase + "NullTray"); - mTrayWidgetAlign[9] = Ogre::GHA_LEFT; - mTraysLayer->add2D(mTrays[9]); - adjustTrays(); - - showTrays(); - showCursor(); -} - -TrayManager::~TrayManager() -{ - Ogre::OverlayManager& om = Ogre::OverlayManager::getSingleton(); - - destroyAllWidgets(); - - for (unsigned int i = 0; i < mWidgetDeathRow.size(); i++) // delete widgets queued for destruction - { - delete mWidgetDeathRow[i]; - } - mWidgetDeathRow.clear(); - - om.destroy(mBackdropLayer); - om.destroy(mTraysLayer); - om.destroy(mPriorityLayer); - om.destroy(mCursorLayer); - - closeDialog(); - hideLoadingBar(); - - Widget::nukeOverlayElement(mBackdrop); - Widget::nukeOverlayElement(mCursor); - Widget::nukeOverlayElement(mDialogShade); - - for (unsigned int i = 0; i < 10; i++) - { - Widget::nukeOverlayElement(mTrays[i]); - } -} - -Ogre::Ray TrayManager::screenToScene(Ogre::Camera *cam, const Ogre::Vector2 &pt) -{ - return cam->getCameraToViewportRay(pt.x, pt.y); -} - -Ogre::Vector2 TrayManager::sceneToScreen(Ogre::Camera *cam, const Ogre::Vector3 &pt) -{ - Ogre::Vector3 result = cam->getProjectionMatrix() * cam->getViewMatrix() * pt; - return Ogre::Vector2((result.x + 1) / 2, (-result.y + 1) / 2); -} - -void TrayManager::showAll() -{ - showBackdrop(); - showTrays(); - showCursor(); -} - -void TrayManager::hideAll() -{ - hideBackdrop(); - hideTrays(); - hideCursor(); -} - -void TrayManager::showBackdrop(const Ogre::String &materialName) -{ - if (!materialName.empty()) mBackdrop->setMaterialName(materialName); - mBackdropLayer->show(); -} - -void TrayManager::showCursor(const Ogre::String &materialName) -{ - if (!materialName.empty()) getCursorImage()->setMaterialName(materialName); - - if (!mCursorLayer->isVisible()) - { - mCursorLayer->show(); - refreshCursor(); - } -} - -void TrayManager::hideCursor() -{ - mCursorLayer->hide(); - - // give widgets a chance to reset in case they're in the middle of something - for (unsigned int i = 0; i < 10; i++) - { - for (unsigned int j = 0; j < mWidgets[i].size(); j++) - { - mWidgets[i][j]->_focusLost(); - } - } - - setExpandedMenu(0); -} - -void TrayManager::refreshCursor() -{ - mCursor->setPosition(mCursorPos.x, mCursorPos.y); -} - -void TrayManager::showTrays() -{ - mTraysLayer->show(); - mPriorityLayer->show(); -} - -void TrayManager::hideTrays() -{ - mTraysLayer->hide(); - mPriorityLayer->hide(); - - // give widgets a chance to reset in case they're in the middle of something - for (unsigned int i = 0; i < 10; i++) - { - for (unsigned int j = 0; j < mWidgets[i].size(); j++) - { - mWidgets[i][j]->_focusLost(); - } - } - - setExpandedMenu(0); -} - -void TrayManager::setTrayWidgetAlignment(TrayLocation trayLoc, Ogre::GuiHorizontalAlignment gha) -{ - mTrayWidgetAlign[trayLoc] = gha; - - for (unsigned int i = 0; i < mWidgets[trayLoc].size(); i++) - { - mWidgets[trayLoc][i]->getOverlayElement()->setHorizontalAlignment(gha); - } -} - -void TrayManager::setWidgetPadding(Ogre::Real padding) -{ - mWidgetPadding = std::max((int)padding, 0); - adjustTrays(); -} - -void TrayManager::setWidgetSpacing(Ogre::Real spacing) -{ - mWidgetSpacing = std::max((int)spacing, 0); - adjustTrays(); -} - -void TrayManager::setTrayPadding(Ogre::Real padding) -{ - mTrayPadding = std::max((int)padding, 0); - adjustTrays(); -} - -void TrayManager::adjustTrays() -{ - for (unsigned int i = 0; i < 9; i++) // resizes and hides trays if necessary - { - Ogre::Real trayWidth = 0; - Ogre::Real trayHeight = mWidgetPadding; - std::vector labelsAndSeps; - - if (mWidgets[i].empty()) // hide tray if empty - { - mTrays[i]->hide(); - continue; - } - else mTrays[i]->show(); - - // arrange widgets and calculate final tray size and position - for (unsigned int j = 0; j < mWidgets[i].size(); j++) - { - Ogre::OverlayElement* e = mWidgets[i][j]->getOverlayElement(); - - if (j != 0) trayHeight += mWidgetSpacing; // don't space first widget - - e->setVerticalAlignment(Ogre::GVA_TOP); - e->setTop(trayHeight); - - switch (e->getHorizontalAlignment()) - { - case Ogre::GHA_LEFT: - e->setLeft(mWidgetPadding); - break; - case Ogre::GHA_RIGHT: - e->setLeft(-(e->getWidth() + mWidgetPadding)); - break; - default: - e->setLeft(-(e->getWidth() / 2)); - } - - // prevents some weird texture filtering problems (just some) - e->setPosition((int)e->getLeft(), (int)e->getTop()); - e->setDimensions((int)e->getWidth(), (int)e->getHeight()); - - trayHeight += e->getHeight(); - - Label* l = dynamic_cast(mWidgets[i][j]); - if (l && l->_isFitToTray()) - { - labelsAndSeps.push_back(e); - continue; - } - Separator* s = dynamic_cast(mWidgets[i][j]); - if (s && s->_isFitToTray()) - { - labelsAndSeps.push_back(e); - continue; - } - - if (e->getWidth() > trayWidth) trayWidth = e->getWidth(); - } - - // add paddings and resize trays - mTrays[i]->setWidth(trayWidth + 2 * mWidgetPadding); - mTrays[i]->setHeight(trayHeight + mWidgetPadding); - - for (unsigned int j = 0; j < labelsAndSeps.size(); j++) - { - labelsAndSeps[j]->setWidth((int)trayWidth); - labelsAndSeps[j]->setLeft(-(int)(trayWidth / 2)); - } - } - - for (unsigned int i = 0; i < 9; i++) // snap trays to anchors - { - if (i == TL_TOPLEFT || i == TL_LEFT || i == TL_BOTTOMLEFT) - mTrays[i]->setLeft(mTrayPadding); - if (i == TL_TOP || i == TL_CENTER || i == TL_BOTTOM) - mTrays[i]->setLeft(-mTrays[i]->getWidth() / 2); - if (i == TL_TOPRIGHT || i == TL_RIGHT || i == TL_BOTTOMRIGHT) - mTrays[i]->setLeft(-(mTrays[i]->getWidth() + mTrayPadding)); - - if (i == TL_TOPLEFT || i == TL_TOP || i == TL_TOPRIGHT) - mTrays[i]->setTop(mTrayPadding); - if (i == TL_LEFT || i == TL_CENTER || i == TL_RIGHT) - mTrays[i]->setTop(-mTrays[i]->getHeight() / 2); - if (i == TL_BOTTOMLEFT || i == TL_BOTTOM || i == TL_BOTTOMRIGHT) - mTrays[i]->setTop(-mTrays[i]->getHeight() - mTrayPadding); - - // prevents some weird texture filtering problems (just some) - mTrays[i]->setPosition((int)mTrays[i]->getLeft(), (int)mTrays[i]->getTop()); - mTrays[i]->setDimensions((int)mTrays[i]->getWidth(), (int)mTrays[i]->getHeight()); - } -} - -Ogre::Ray TrayManager::getCursorRay(Ogre::Camera *cam) -{ - return screenToScene(cam, Ogre::Vector2(mCursor->_getLeft(), mCursor->_getTop())); -} - -Button *TrayManager::createButton(TrayLocation trayLoc, const Ogre::String &name, const Ogre::String &caption, Ogre::Real width) -{ - Button* b = new Button(name, caption, width); - moveWidgetToTray(b, trayLoc); - b->_assignListener(mListener); - return b; -} - -TextBox *TrayManager::createTextBox(TrayLocation trayLoc, const Ogre::String &name, const Ogre::DisplayString &caption, Ogre::Real width, Ogre::Real height) -{ - TextBox* tb = new TextBox(name, caption, width, height); - moveWidgetToTray(tb, trayLoc); - tb->_assignListener(mListener); - return tb; -} - -SelectMenu *TrayManager::createThickSelectMenu(TrayLocation trayLoc, const Ogre::String &name, const Ogre::DisplayString &caption, Ogre::Real width, unsigned int maxItemsShown, const Ogre::StringVector &items) -{ - SelectMenu* sm = new SelectMenu(name, caption, width, 0, maxItemsShown); - moveWidgetToTray(sm, trayLoc); - sm->_assignListener(mListener); - if (!items.empty()) sm->setItems(items); - return sm; -} - -SelectMenu *TrayManager::createLongSelectMenu(TrayLocation trayLoc, const Ogre::String &name, const Ogre::DisplayString &caption, Ogre::Real width, Ogre::Real boxWidth, unsigned int maxItemsShown, const Ogre::StringVector &items) -{ - SelectMenu* sm = new SelectMenu(name, caption, width, boxWidth, maxItemsShown); - moveWidgetToTray(sm, trayLoc); - sm->_assignListener(mListener); - if (!items.empty()) sm->setItems(items); - return sm; -} - -SelectMenu *TrayManager::createLongSelectMenu(TrayLocation trayLoc, const Ogre::String &name, const Ogre::DisplayString &caption, Ogre::Real boxWidth, unsigned int maxItemsShown, const Ogre::StringVector &items) -{ - return createLongSelectMenu(trayLoc, name, caption, 0, boxWidth, maxItemsShown, items); -} - -Label *TrayManager::createLabel(TrayLocation trayLoc, const Ogre::String &name, const Ogre::DisplayString &caption, Ogre::Real width) -{ - Label* l = new Label(name, caption, width); - moveWidgetToTray(l, trayLoc); - l->_assignListener(mListener); - return l; -} - -Separator *TrayManager::createSeparator(TrayLocation trayLoc, const Ogre::String &name, Ogre::Real width) -{ - Separator* s = new Separator(name, width); - moveWidgetToTray(s, trayLoc); - return s; -} - -Slider *TrayManager::createThickSlider(TrayLocation trayLoc, const Ogre::String &name, const Ogre::DisplayString &caption, Ogre::Real width, Ogre::Real valueBoxWidth, Ogre::Real minValue, Ogre::Real maxValue, unsigned int snaps) -{ - Slider* s = new Slider(name, caption, width, 0, valueBoxWidth, minValue, maxValue, snaps); - moveWidgetToTray(s, trayLoc); - s->_assignListener(mListener); - return s; -} - -Slider *TrayManager::createLongSlider(TrayLocation trayLoc, const Ogre::String &name, const Ogre::DisplayString &caption, Ogre::Real width, Ogre::Real trackWidth, Ogre::Real valueBoxWidth, Ogre::Real minValue, Ogre::Real maxValue, unsigned int snaps) -{ - if (trackWidth <= 0) trackWidth = 1; - Slider* s = new Slider(name, caption, width, trackWidth, valueBoxWidth, minValue, maxValue, snaps); - moveWidgetToTray(s, trayLoc); - s->_assignListener(mListener); - return s; -} - -Slider *TrayManager::createLongSlider(TrayLocation trayLoc, const Ogre::String &name, const Ogre::DisplayString &caption, Ogre::Real trackWidth, Ogre::Real valueBoxWidth, Ogre::Real minValue, Ogre::Real maxValue, unsigned int snaps) -{ - return createLongSlider(trayLoc, name, caption, 0, trackWidth, valueBoxWidth, minValue, maxValue, snaps); -} - -ParamsPanel *TrayManager::createParamsPanel(TrayLocation trayLoc, const Ogre::String &name, Ogre::Real width, unsigned int lines) -{ - ParamsPanel* pp = new ParamsPanel(name, width, lines); - moveWidgetToTray(pp, trayLoc); - return pp; -} - -ParamsPanel *TrayManager::createParamsPanel(TrayLocation trayLoc, const Ogre::String &name, Ogre::Real width, const Ogre::StringVector ¶mNames) -{ - ParamsPanel* pp = new ParamsPanel(name, width, (Ogre::uint)paramNames.size()); - pp->setAllParamNames(paramNames); - moveWidgetToTray(pp, trayLoc); - return pp; -} - -CheckBox *TrayManager::createCheckBox(TrayLocation trayLoc, const Ogre::String &name, const Ogre::DisplayString &caption, Ogre::Real width) -{ - CheckBox* cb = new CheckBox(name, caption, width); - moveWidgetToTray(cb, trayLoc); - cb->_assignListener(mListener); - return cb; -} - -DecorWidget *TrayManager::createDecorWidget(TrayLocation trayLoc, const Ogre::String &name, const Ogre::String &templateName) -{ - DecorWidget* dw = new DecorWidget(name, templateName); - moveWidgetToTray(dw, trayLoc); - return dw; -} - -ProgressBar *TrayManager::createProgressBar(TrayLocation trayLoc, const Ogre::String &name, const Ogre::DisplayString &caption, Ogre::Real width, Ogre::Real commentBoxWidth) -{ - ProgressBar* pb = new ProgressBar(name, caption, width, commentBoxWidth); - moveWidgetToTray(pb, trayLoc); - return pb; -} - -void TrayManager::showFrameStats(TrayLocation trayLoc, size_t place) -{ - if (!areFrameStatsVisible()) - { - Ogre::StringVector stats; - stats.push_back("Average FPS"); - stats.push_back("Best FPS"); - stats.push_back("Worst FPS"); - stats.push_back("Triangles"); - stats.push_back("Batches"); - - mFpsLabel = createLabel(TL_NONE, mName + "/FpsLabel", "FPS:", 180); - mFpsLabel->_assignListener(this); - mStatsPanel = createParamsPanel(TL_NONE, mName + "/StatsPanel", 180, stats); - } - - moveWidgetToTray(mFpsLabel, trayLoc, place); - moveWidgetToTray(mStatsPanel, trayLoc, locateWidgetInTray(mFpsLabel) + 1); -} - -void TrayManager::hideFrameStats() -{ - if (areFrameStatsVisible()) - { - destroyWidget(mFpsLabel); - destroyWidget(mStatsPanel); - mFpsLabel = 0; - mStatsPanel = 0; - } -} - -void TrayManager::showLogo(TrayLocation trayLoc, size_t place) -{ - if (!isLogoVisible()) mLogo = createDecorWidget(TL_NONE, mName + "/Logo", "SdkTrays/Logo"); - moveWidgetToTray(mLogo, trayLoc, place); -} - -void TrayManager::hideLogo() -{ - if (isLogoVisible()) - { - destroyWidget(mLogo); - mLogo = 0; - } -} - -void TrayManager::showLoadingBar(unsigned int numGroupsInit, unsigned int numGroupsLoad, Ogre::Real initProportion) -{ - if (mDialog) closeDialog(); - if (mLoadBar) hideLoadingBar(); - - mLoadBar = new ProgressBar(mName + "/LoadingBar", "Loading...", 400, 308); - Ogre::OverlayElement* e = mLoadBar->getOverlayElement(); - mDialogShade->addChild(e); - e->setVerticalAlignment(Ogre::GVA_CENTER); - e->setLeft(-(e->getWidth() / 2)); - e->setTop(-(e->getHeight() / 2)); - - Ogre::ResourceGroupManager::getSingleton().addResourceGroupListener(this); - mCursorWasVisible = isCursorVisible(); - hideCursor(); - mDialogShade->show(); - - // calculate the proportion of job required to init/load one group - - if (numGroupsInit == 0 && numGroupsLoad != 0) - { - mGroupInitProportion = 0; - mGroupLoadProportion = 1; - } - else if (numGroupsLoad == 0 && numGroupsInit != 0) - { - mGroupLoadProportion = 0; - if (numGroupsInit != 0) mGroupInitProportion = 1; - } - else if (numGroupsInit == 0 && numGroupsLoad == 0) - { - mGroupInitProportion = 0; - mGroupLoadProportion = 0; - } - else - { - mGroupInitProportion = initProportion / numGroupsInit; - mGroupLoadProportion = (1 - initProportion) / numGroupsLoad; - } -} - -void TrayManager::hideLoadingBar() -{ - if (mLoadBar) - { - mLoadBar->cleanup(); - delete mLoadBar; - mLoadBar = 0; - - Ogre::ResourceGroupManager::getSingleton().removeResourceGroupListener(this); - if (mCursorWasVisible) showCursor(); - mDialogShade->hide(); - } -} - -void TrayManager::showOkDialog(const Ogre::DisplayString &caption, const Ogre::DisplayString &message) -{ - if (mLoadBar) hideLoadingBar(); - - Ogre::OverlayElement* e; - - if (mDialog) - { - mDialog->setCaption(caption); - mDialog->setText(message); - - if (mOk) return; - else - { - mYes->cleanup(); - mNo->cleanup(); - delete mYes; - delete mNo; - mYes = 0; - mNo = 0; - } - } - else - { - // give widgets a chance to reset in case they're in the middle of something - for (unsigned int i = 0; i < 10; i++) - { - for (unsigned int j = 0; j < mWidgets[i].size(); j++) - { - mWidgets[i][j]->_focusLost(); - } - } - - mDialogShade->show(); - - mDialog = new TextBox(mName + "/DialogBox", caption, 300, 208); - mDialog->setText(message); - e = mDialog->getOverlayElement(); - mDialogShade->addChild(e); - e->setVerticalAlignment(Ogre::GVA_CENTER); - e->setLeft(-(e->getWidth() / 2)); - e->setTop(-(e->getHeight() / 2)); - - mCursorWasVisible = isCursorVisible(); - showCursor(); - } - - mOk = new Button(mName + "/OkButton", "OK", 60); - mOk->_assignListener(this); - e = mOk->getOverlayElement(); - mDialogShade->addChild(e); - e->setVerticalAlignment(Ogre::GVA_CENTER); - e->setLeft(-(e->getWidth() / 2)); - e->setTop(mDialog->getOverlayElement()->getTop() + mDialog->getOverlayElement()->getHeight() + 5); -} - -void TrayManager::showYesNoDialog(const Ogre::DisplayString &caption, const Ogre::DisplayString &question) -{ - if (mLoadBar) hideLoadingBar(); - - Ogre::OverlayElement* e; - - if (mDialog) - { - mDialog->setCaption(caption); - mDialog->setText(question); - - if (mOk) - { - mOk->cleanup(); - delete mOk; - mOk = 0; - } - else return; - } - else - { - // give widgets a chance to reset in case they're in the middle of something - for (unsigned int i = 0; i < 10; i++) - { - for (unsigned int j = 0; j < mWidgets[i].size(); j++) - { - mWidgets[i][j]->_focusLost(); - } - } - - mDialogShade->show(); - - mDialog = new TextBox(mName + "/DialogBox", caption, 300, 208); - mDialog->setText(question); - e = mDialog->getOverlayElement(); - mDialogShade->addChild(e); - e->setVerticalAlignment(Ogre::GVA_CENTER); - e->setLeft(-(e->getWidth() / 2)); - e->setTop(-(e->getHeight() / 2)); - - mCursorWasVisible = isCursorVisible(); - showCursor(); - } - - mYes = new Button(mName + "/YesButton", "Yes", 58); - mYes->_assignListener(this); - e = mYes->getOverlayElement(); - mDialogShade->addChild(e); - e->setVerticalAlignment(Ogre::GVA_CENTER); - e->setLeft(-(e->getWidth() + 2)); - e->setTop(mDialog->getOverlayElement()->getTop() + mDialog->getOverlayElement()->getHeight() + 5); - - mNo = new Button(mName + "/NoButton", "No", 50); - mNo->_assignListener(this); - e = mNo->getOverlayElement(); - mDialogShade->addChild(e); - e->setVerticalAlignment(Ogre::GVA_CENTER); - e->setLeft(3); - e->setTop(mDialog->getOverlayElement()->getTop() + mDialog->getOverlayElement()->getHeight() + 5); -} - -void TrayManager::closeDialog() -{ - if (mDialog) - { - if (mOk) - { - mOk->cleanup(); - delete mOk; - mOk = 0; - } - else - { - mYes->cleanup(); - mNo->cleanup(); - delete mYes; - delete mNo; - mYes = 0; - mNo = 0; - } - - mDialogShade->hide(); - mDialog->cleanup(); - delete mDialog; - mDialog = 0; - - if (!mCursorWasVisible) hideCursor(); - } -} - -bool TrayManager::isDialogVisible() -{ - return mDialog != 0; -} - -Widget *TrayManager::getWidget(TrayLocation trayLoc, const Ogre::String &name) -{ - for (unsigned int i = 0; i < mWidgets[trayLoc].size(); i++) - { - if (mWidgets[trayLoc][i]->getName() == name) return mWidgets[trayLoc][i]; - } - return 0; -} - -Widget *TrayManager::getWidget(const Ogre::String &name) -{ - for (unsigned int i = 0; i < 10; i++) - { - for (unsigned int j = 0; j < mWidgets[i].size(); j++) - { - if (mWidgets[i][j]->getName() == name) return mWidgets[i][j]; - } - } - return 0; -} - -unsigned int TrayManager::getNumWidgets() -{ - unsigned int total = 0; - - for (unsigned int i = 0; i < 10; i++) - { - total += mWidgets[i].size(); - } - - return total; -} - -int TrayManager::locateWidgetInTray(Widget *widget) -{ - for (unsigned int i = 0; i < mWidgets[widget->getTrayLocation()].size(); i++) - { - if (mWidgets[widget->getTrayLocation()][i] == widget) return i; - } - return -1; -} - -void TrayManager::destroyWidget(Widget *widget) -{ - if (!widget) OGRE_EXCEPT(Ogre::Exception::ERR_ITEM_NOT_FOUND, "Widget does not exist.", "TrayManager::destroyWidget"); - - // in case special widgets are destroyed manually, set them to 0 - if (widget == mLogo) mLogo = 0; - else if (widget == mStatsPanel) mStatsPanel = 0; - else if (widget == mFpsLabel) mFpsLabel = 0; - - mTrays[widget->getTrayLocation()]->removeChild(widget->getName()); - - WidgetList& wList = mWidgets[widget->getTrayLocation()]; - WidgetList::iterator it = std::find(wList.begin(), wList.end(), widget); - if(it != wList.end()) - wList.erase(it); - - if (widget == mExpandedMenu) setExpandedMenu(0); - - widget->cleanup(); - - mWidgetDeathRow.push_back(widget); - - adjustTrays(); -} - -void TrayManager::destroyAllWidgetsInTray(TrayLocation trayLoc) -{ - while (!mWidgets[trayLoc].empty()) destroyWidget(mWidgets[trayLoc][0]); -} - -void TrayManager::destroyAllWidgets() -{ - for (unsigned int i = 0; i < 10; i++) // destroy every widget in every tray (including null tray) - { - destroyAllWidgetsInTray((TrayLocation)i); - } -} - -void TrayManager::moveWidgetToTray(Widget *widget, TrayLocation trayLoc, size_t place) -{ - if (!widget) OGRE_EXCEPT(Ogre::Exception::ERR_ITEM_NOT_FOUND, "Widget does not exist.", "TrayManager::moveWidgetToTray"); - - // remove widget from old tray - WidgetList& wList = mWidgets[widget->getTrayLocation()]; - WidgetList::iterator it = std::find(wList.begin(), wList.end(), widget); - if (it != wList.end()) - { - wList.erase(it); - mTrays[widget->getTrayLocation()]->removeChild(widget->getName()); - } - - // insert widget into new tray at given position, or at the end if unspecified or invalid - if (place > mWidgets[trayLoc].size()) place = mWidgets[trayLoc].size(); - mWidgets[trayLoc].insert(mWidgets[trayLoc].begin() + place, widget); - mTrays[trayLoc]->addChild(widget->getOverlayElement()); - - widget->getOverlayElement()->setHorizontalAlignment(mTrayWidgetAlign[trayLoc]); - - // adjust trays if necessary - if (widget->getTrayLocation() != TL_NONE || trayLoc != TL_NONE) adjustTrays(); - - widget->_assignToTray(trayLoc); -} - -void TrayManager::clearTray(TrayLocation trayLoc) -{ - if (trayLoc == TL_NONE) return; // can't clear the null tray - - while (!mWidgets[trayLoc].empty()) // remove every widget from given tray - { - removeWidgetFromTray(mWidgets[trayLoc][0]); - } -} - -void TrayManager::clearAllTrays() -{ - for (unsigned int i = 0; i < 9; i++) - { - clearTray((TrayLocation)i); - } -} - -void TrayManager::frameRendered(const Ogre::FrameEvent &evt) -{ - for (unsigned int i = 0; i < mWidgetDeathRow.size(); i++) - { - delete mWidgetDeathRow[i]; - } - mWidgetDeathRow.clear(); - - - unsigned long currentTime = mTimer->getMilliseconds(); - if (areFrameStatsVisible() && currentTime - mLastStatUpdateTime >= FRAME_UPDATE_DELAY) - { - Ogre::RenderTarget::FrameStats stats = mWindow->getStatistics(); - - mLastStatUpdateTime = currentTime; - - Ogre::String s("FPS: "); - s += Ogre::StringConverter::toString((int)stats.lastFPS); - - mFpsLabel->setCaption(s); - - if (mStatsPanel->getOverlayElement()->isVisible()) - { - Ogre::StringVector values; - Ogre::StringStream oss; - - oss.str(""); - oss << std::fixed << std::setprecision(1) << stats.avgFPS; - Ogre::String str = oss.str(); - values.push_back(str); - - oss.str(""); - oss << std::fixed << std::setprecision(1) << stats.bestFPS; - str = oss.str(); - values.push_back(str); - - oss.str(""); - oss << std::fixed << std::setprecision(1) << stats.worstFPS; - str = oss.str(); - values.push_back(str); - - str = Ogre::StringConverter::toString(stats.triangleCount); - values.push_back(str); - - str = Ogre::StringConverter::toString(stats.batchCount); - values.push_back(str); - - mStatsPanel->setAllParamValues(values); - } - } -} - -void TrayManager::windowUpdate() -{ -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - unsigned long currentTime = mTimer->getMilliseconds(); - if (currentTime - mLastStatUpdateTime >= FRAME_UPDATE_DELAY) - { - mLastStatUpdateTime = currentTime; - mWindow->update(); - } -#endif -} - -void TrayManager::labelHit(Label *label) -{ - if (mStatsPanel->getOverlayElement()->isVisible()) - { - mStatsPanel->getOverlayElement()->hide(); - mFpsLabel->getOverlayElement()->setWidth(150); - removeWidgetFromTray(mStatsPanel); - } - else - { - mStatsPanel->getOverlayElement()->show(); - mFpsLabel->getOverlayElement()->setWidth(180); - moveWidgetToTray(mStatsPanel, mFpsLabel->getTrayLocation(), locateWidgetInTray(mFpsLabel) + 1); - } -} - -void TrayManager::buttonHit(Button *button) -{ - if (mListener) - { - if (button == mOk) mListener->okDialogClosed(mDialog->getText()); - else mListener->yesNoDialogClosed(mDialog->getText(), button == mYes); - } - closeDialog(); -} - -bool TrayManager::mousePressed(const MouseButtonEvent &evt) -{ - if (evt.button != BUTTON_LEFT) return false; - - Ogre::Vector2 cursorPos(mCursor->getLeft(), mCursor->getTop()); - - mTrayDrag = false; - - if (mExpandedMenu) // only check top priority widget until it passes on - { - mExpandedMenu->_cursorPressed(cursorPos); - if (!mExpandedMenu->isExpanded()) setExpandedMenu(0); - return true; - } - - if (mDialog) // only check top priority widget until it passes on - { - mDialog->_cursorPressed(cursorPos); - if (mOk) mOk->_cursorPressed(cursorPos); - else - { - mYes->_cursorPressed(cursorPos); - mNo->_cursorPressed(cursorPos); - } - return true; - } - - // process widgets in reverse ZOrder - for (int i = 8; i >= 0; --i) // check if mouse is over a non-null tray - { - if (mTrays[i]->isVisible() && Widget::isCursorOver(mTrays[i], cursorPos, 2)) - { - mTrayDrag = true; // initiate a drag that originates in a tray - break; - } - } - - for (int j = (int)mWidgets[9].size() - 1; j >= 0 ; --j) // check if mouse is over a non-null tray's widgets - { - if(j >= (int)mWidgets[9].size()) continue; - Widget* w = mWidgets[9][j]; - if (w->getOverlayElement()->isVisible() && Widget::isCursorOver(w->getOverlayElement(), cursorPos)) - { - mTrayDrag = true; // initiate a drag that originates in a tray - break; - } - } - - if (!mTrayDrag) return false; // don't process if mouse press is not in tray - - for (int i = 9; i >= 0; --i) - { - if (!mTrays[i]->isVisible()) continue; - - for (int j = (int)mWidgets[i].size() - 1; j >= 0; --j) - { - if(j >= (int)mWidgets[i].size()) continue; - Widget* w = mWidgets[i][j]; - if (!w->getOverlayElement()->isVisible()) continue; - w->_cursorPressed(cursorPos); // send event to widget - - SelectMenu* m = dynamic_cast(w); - if (m && m->isExpanded()) // a menu has begun a top priority session - { - setExpandedMenu(m); - return true; - } - } - } - - return true; // a tray click is not to be handled by another party -} - -bool TrayManager::mouseReleased(const MouseButtonEvent &evt) -{ - if (evt.button != BUTTON_LEFT) return false; - - Ogre::Vector2 cursorPos(mCursor->getLeft(), mCursor->getTop()); - - if (mExpandedMenu) // only check top priority widget until it passes on - { - mExpandedMenu->_cursorReleased(cursorPos); - return true; - } - - if (mDialog) // only check top priority widget until it passes on - { - mDialog->_cursorReleased(cursorPos); - if (mOk) mOk->_cursorReleased(cursorPos); - else - { - mYes->_cursorReleased(cursorPos); - // very important to check if second button still exists, because first button could've closed the popup - if (mNo) mNo->_cursorReleased(cursorPos); - } - return true; - } - - if (!mTrayDrag) return false; // this click did not originate in a tray, so don't process - - // process trays and widgets in reverse ZOrder - for (int i = 9; i >= 0; --i) - { - if (!mTrays[i]->isVisible()) continue; - - for (int j = (int)mWidgets[i].size() - 1; j >= 0; --j) - { - if(j >= (int)mWidgets[i].size()) continue; - Widget* w = mWidgets[i][j]; - if (!w->getOverlayElement()->isVisible()) continue; - w->_cursorReleased(cursorPos); // send event to widget - } - } - - mTrayDrag = false; // stop this drag - return true; // this click did originate in this tray, so don't pass it on -} - -bool TrayManager::mouseMoved(const MouseMotionEvent &evt) -{ - // thats a separate event. Ignore for now. - static float wheelDelta = 0; - - auto vpScale = Ogre::OverlayManager::getSingleton().getPixelRatio(); - - // always keep track of the mouse pos for refreshCursor() - mCursorPos = Ogre::Vector2(evt.x, evt.y) / vpScale; - mCursor->setPosition(mCursorPos.x, mCursorPos.y); - - if (mExpandedMenu) // only check top priority widget until it passes on - { - mExpandedMenu->_cursorMoved(mCursorPos, wheelDelta); - return true; - } - - if (mDialog) // only check top priority widget until it passes on - { - mDialog->_cursorMoved(mCursorPos, wheelDelta); - if(mOk) mOk->_cursorMoved(mCursorPos, wheelDelta); - else - { - mYes->_cursorMoved(mCursorPos, wheelDelta); - mNo->_cursorMoved(mCursorPos, wheelDelta); - } - return true; - } - - // process trays and widgets in reverse ZOrder - for (int i = 9; i >= 0; --i) - { - if (!mTrays[i]->isVisible()) continue; - - for (int j = (int)mWidgets[i].size() - 1; j >= 0; --j) - { - if(j >= (int)mWidgets[i].size()) continue; - Widget* w = mWidgets[i][j]; - if (!w->getOverlayElement()->isVisible()) continue; - w->_cursorMoved(mCursorPos, wheelDelta); // send event to widget - } - } - - if (mTrayDrag) return true; // don't pass this event on if we're in the middle of a drag - return false; -} - -bool TrayManager::mouseWheelRolled(const MouseWheelEvent& evt) -{ - if (mExpandedMenu) - { - mExpandedMenu->_cursorMoved(mCursorPos, evt.y); - return true; - } - return false; -} - -void TrayManager::setExpandedMenu(SelectMenu *m) -{ - if (!mExpandedMenu && m) - { - Ogre::OverlayContainer* c = (Ogre::OverlayContainer*)m->getOverlayElement(); - Ogre::OverlayContainer* eb = (Ogre::OverlayContainer*)c->getChild(m->getName() + "/MenuExpandedBox"); - eb->_update(); - eb->setPosition - ((unsigned int)(eb->_getDerivedLeft() * Ogre::OverlayManager::getSingleton().getViewportWidth()), - (unsigned int)(eb->_getDerivedTop() * Ogre::OverlayManager::getSingleton().getViewportHeight())); - c->removeChild(eb->getName()); - mPriorityLayer->add2D(eb); - } - else if(mExpandedMenu && !m) - { - Ogre::OverlayContainer* eb = mPriorityLayer->getChild(mExpandedMenu->getName() + "/MenuExpandedBox"); - mPriorityLayer->remove2D(eb); - ((Ogre::OverlayContainer*)mExpandedMenu->getOverlayElement())->addChild(eb); - } - - mExpandedMenu = m; -} - -} - diff --git a/Components/Bites/src/OgreWIN32ConfigDialog.cpp b/Components/Bites/src/OgreWIN32ConfigDialog.cpp deleted file mode 100644 index ec7f30bd559..00000000000 --- a/Components/Bites/src/OgreWIN32ConfigDialog.cpp +++ /dev/null @@ -1,356 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreConfigDialogImp.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" -#include "OgreException.h" -#include "resource.h" - -#define WIN32_LEAN_AND_MEAN -#if !defined(NOMINMAX) && defined(_MSC_VER) -# define NOMINMAX // required to stop windows.h messing up std::min -#endif -#include - -namespace -{ - OgreBites::ConfigDialog* dlg; // This is a pointer to instance, since this is a static member -} - - -using namespace Ogre; - -namespace OgreBites -{ - struct ConfigDialog::PrivateData { - RenderSystem* mSelectedRenderSystem; - HINSTANCE mHInstance; // HInstance of application, for dialog - - /** Callback to process window events */ -#if OGRE_ARCHITECTURE_64 == OGRE_ARCH_TYPE - static INT_PTR CALLBACK DlgProc(HWND hDlg, UINT iMsg, WPARAM wParam, LPARAM lParam); -#else - static BOOL CALLBACK DlgProc(HWND hDlg, UINT iMsg, WPARAM wParam, LPARAM lParam); -#endif - }; - - ConfigDialog::ConfigDialog() : mImpl(new ConfigDialog::PrivateData()) - { - #ifdef __MINGW32__ - #ifdef OGRE_STATIC_LIB - mImpl->mHInstance = GetModuleHandle( NULL ); - #else - #if OGRE_DEBUG_MODE == 1 - mImpl->mHInstance = GetModuleHandle("OgreMain_d.dll"); - #else - mImpl->mHInstance = GetModuleHandle("OgreMain.dll"); - #endif - #endif - #else - static const TCHAR staticVar; - GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, &staticVar, &mImpl->mHInstance); - #endif - - mImpl->mSelectedRenderSystem = 0; - } - - ConfigDialog::~ConfigDialog() - { - delete mImpl; - } - -#if OGRE_ARCHITECTURE_64 == OGRE_ARCH_TYPE - INT_PTR ConfigDialog::PrivateData::DlgProc(HWND hDlg, UINT iMsg, WPARAM wParam, LPARAM lParam) -#else - BOOL ConfigDialog::PrivateData::DlgProc(HWND hDlg, UINT iMsg, WPARAM wParam, LPARAM lParam) -#endif - { - HWND hwndDlgItem; - static const RenderSystemList* lstRend; - RenderSystemList::const_iterator pRend; - static ConfigOptionMap opts; - String err; - - int i, sel, savedSel; - - switch (iMsg) - { - - case WM_INITDIALOG: - // Load saved settings - dlg->mImpl->mSelectedRenderSystem = Root::getSingleton().getRenderSystem(); - // Get all render systems - lstRend = &Root::getSingleton().getAvailableRenderers(); - pRend = lstRend->begin(); - i = 0; - while (pRend != lstRend->end()) - { - hwndDlgItem = GetDlgItem(hDlg, IDC_CBO_RENDERSYSTEM); - - SendMessage(hwndDlgItem, CB_ADDSTRING, 0, - (LPARAM)(char*)(*pRend)->getName().c_str()); - - if (*pRend == dlg->mImpl->mSelectedRenderSystem) - { - // Select - SendMessage(hwndDlgItem, CB_SETCURSEL, (WPARAM)i, 0); - // Refresh Options - // Get options from render system - opts = (*pRend)->getConfigOptions(); - // Reset list box - hwndDlgItem = GetDlgItem(hDlg, IDC_LST_OPTIONS); - //SendMessage(hwndDlgItem, LB_RESETCONTENT, 0, 0); - // Iterate through options - ConfigOptionMap::iterator pOpt = opts.begin(); - String strLine; - while( pOpt!= opts.end() ) - { - strLine = pOpt->second.name + ": " + pOpt->second.currentValue; - SendMessage(hwndDlgItem, LB_ADDSTRING, 0, (LPARAM)strLine.c_str()); - ++pOpt; - } - } - - ++pRend; - ++i; - } - - // Center myself - int x, y, screenWidth, screenHeight; - RECT rcDlg; - GetWindowRect(hDlg, &rcDlg); - screenWidth = GetSystemMetrics(SM_CXFULLSCREEN); - screenHeight = GetSystemMetrics(SM_CYFULLSCREEN); - - x = (screenWidth / 2) - ((rcDlg.right - rcDlg.left) / 2); - y = (screenHeight / 2) - ((rcDlg.bottom - rcDlg.top) / 2); - - MoveWindow(hDlg, x, y, (rcDlg.right - rcDlg.left), - (rcDlg.bottom - rcDlg.top), TRUE); - - return TRUE; - - case WM_COMMAND: - switch (LOWORD(wParam)) - { - case IDC_CBO_RENDERSYSTEM: - hwndDlgItem = GetDlgItem(hDlg, IDC_CBO_RENDERSYSTEM); - sel = SendMessage( hwndDlgItem, CB_GETCOUNT, 0, 0 ); - - if (HIWORD(wParam) == CBN_SELCHANGE ) - { - // RenderSystem selected - // Get selected index - hwndDlgItem = GetDlgItem(hDlg, IDC_CBO_RENDERSYSTEM); - sel = SendMessage(hwndDlgItem, CB_GETCURSEL,0,0); - if (sel != -1) - { - // Get RenderSystem selected - pRend = lstRend->begin(); - dlg->mImpl->mSelectedRenderSystem = pRend[sel]; - // refresh options - // Get options from render system - opts = pRend[sel]->getConfigOptions(); - // Reset list box - hwndDlgItem = GetDlgItem(hDlg, IDC_LST_OPTIONS); - SendMessage(hwndDlgItem, LB_RESETCONTENT, 0, 0); - // Iterate through options - ConfigOptionMap::iterator pOpt = opts.begin(); - String strLine; - while (pOpt!=opts.end()) - { - strLine = pOpt->second.name + ": " + pOpt->second.currentValue; - SendMessage(hwndDlgItem, LB_ADDSTRING, 0, (LPARAM)strLine.c_str()); - ++pOpt; - } - } - } - - return TRUE; - - case IDC_LST_OPTIONS: - if (HIWORD(wParam) == LBN_SELCHANGE) - { - // Selection in list box of options changed - // Update combo and label in edit section - hwndDlgItem = GetDlgItem(hDlg, IDC_LST_OPTIONS); - sel = SendMessage(hwndDlgItem, LB_GETCURSEL, 0, 0); - if (sel != -1) - { - ConfigOptionMap::iterator pOpt = opts.begin(); - for (i = 0; i < sel; i++) - ++pOpt; - // Set label text - hwndDlgItem = GetDlgItem(hDlg, IDC_LBL_OPTION); - SetWindowText(hwndDlgItem, pOpt->second.name.c_str()); - // Set combo options - hwndDlgItem = GetDlgItem(hDlg, IDC_CBO_OPTION); - SendMessage(hwndDlgItem, CB_RESETCONTENT, 0, 0); - StringVector::iterator pPoss = pOpt->second.possibleValues.begin(); - i = 0; - while (pPoss!=pOpt->second.possibleValues.end()) - { - SendMessage(hwndDlgItem, CB_ADDSTRING, 0, (LPARAM)pPoss[0].c_str()); - if (pPoss[0] == pOpt->second.currentValue) - // Select current value - SendMessage(hwndDlgItem, CB_SETCURSEL, (WPARAM)i, 0); - ++pPoss; - ++i; - } - // Enable/disable combo depending on (not)immutable - EnableWindow(hwndDlgItem, !(pOpt->second.immutable)); - } - } - - return TRUE; - - case IDC_CBO_OPTION: - if (HIWORD(wParam) == CBN_SELCHANGE) - { - // Updated an option - // Get option - hwndDlgItem = GetDlgItem(hDlg, IDC_LST_OPTIONS); - sel = SendMessage(hwndDlgItem, LB_GETCURSEL, 0, 0); - savedSel = sel; - ConfigOptionMap::iterator pOpt = opts.begin(); - for (i = 0; i < sel; i++) - ++pOpt; - // Get selected value - hwndDlgItem = GetDlgItem(hDlg, IDC_CBO_OPTION); - sel = SendMessage(hwndDlgItem, CB_GETCURSEL, 0, 0); - - if (sel != -1) - { - StringVector::iterator pPoss = pOpt->second.possibleValues.begin(); - - // Set option - dlg->mImpl->mSelectedRenderSystem->setConfigOption( - pOpt->second.name, pPoss[sel]); - // Re-retrieve options - opts = dlg->mImpl->mSelectedRenderSystem->getConfigOptions(); - - // Reset options list box - hwndDlgItem = GetDlgItem(hDlg, IDC_LST_OPTIONS); - SendMessage(hwndDlgItem, LB_RESETCONTENT, 0, 0); - // Iterate through options - pOpt = opts.begin(); - String strLine; - while (pOpt!=opts.end()) - { - strLine = pOpt->second.name + ": " + pOpt->second.currentValue; - SendMessage(hwndDlgItem, LB_ADDSTRING, 0, (LPARAM)strLine.c_str()); - ++pOpt; - } - // Select previously selected item - SendMessage(hwndDlgItem, LB_SETCURSEL, savedSel, 0); - } - - } - return TRUE; - - case IDOK: - // Set render system - if (!dlg->mImpl->mSelectedRenderSystem) - { - MessageBox(NULL, "Please choose a rendering system.", "OGRE", MB_OK | MB_ICONEXCLAMATION); - return TRUE; - } - err = dlg->mImpl->mSelectedRenderSystem->validateConfigOptions(); - if (err.length() > 0) - { - // refresh options incase updated by validation - // Get options from render system - opts = dlg->mImpl->mSelectedRenderSystem->getConfigOptions(); - // Reset list box - hwndDlgItem = GetDlgItem(hDlg, IDC_LST_OPTIONS); - SendMessage(hwndDlgItem, LB_RESETCONTENT, 0, 0); - // Iterate through options - ConfigOptionMap::iterator pOpt = opts.begin(); - String strLine; - while (pOpt!=opts.end()) - { - strLine = pOpt->second.name + ": " + pOpt->second.currentValue; - SendMessage(hwndDlgItem, LB_ADDSTRING, 0, (LPARAM)strLine.c_str()); - ++pOpt; - } - MessageBox(NULL, err.c_str(), "OGRE", MB_OK | MB_ICONEXCLAMATION); - return TRUE; - } - - Root::getSingleton().setRenderSystem(dlg->mImpl->mSelectedRenderSystem); - - EndDialog(hDlg, TRUE); - return TRUE; - - case IDCANCEL: - EndDialog(hDlg, FALSE); - return TRUE; - } - } - - return FALSE; - } - - - bool ConfigDialog::display(void) - { - // Display dialog - // Don't return to caller until dialog dismissed - int i; - dlg = this; - - i = DialogBox(mImpl->mHInstance, MAKEINTRESOURCE(IDD_DLG_CONFIG), NULL, ConfigDialog::PrivateData::DlgProc); - - if (i == -1) - { - int winError = GetLastError(); - char* errDesc; - int i; - - errDesc = new char[255]; - // Try windows errors first - i = FormatMessage( - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - winError, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language - (LPTSTR) errDesc, - 255, - NULL - ); - - throw Exception(winError,errDesc, "ConfigDialog::display"); - } - if (i) - return true; - else - return false; - - } -} diff --git a/Components/Bites/src/OgreWindowEventUtilities.cpp b/Components/Bites/src/OgreWindowEventUtilities.cpp deleted file mode 100644 index 3260cd60452..00000000000 --- a/Components/Bites/src/OgreWindowEventUtilities.cpp +++ /dev/null @@ -1,363 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreWindowEventUtilities.h" -#include "OgreRenderWindow.h" - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 -# if !defined(WIN32_LEAN_AND_MEAN) -# define WIN32_LEAN_AND_MEAN -# endif -# if !defined(NOMINMAX) && defined(_MSC_VER) -# define NOMINMAX // required to stop windows.h messing up std::min -# endif -# include -#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX -#include -#endif - -using namespace Ogre; - -namespace OgreBites { -typedef std::multimap WindowEventListeners; -static WindowEventListeners _msListeners; -static RenderWindowList _msWindows; - -#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX -static void GLXProc( RenderWindow *win, const XEvent &event ); -#endif - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 -//--------------------------------------------------------------------------------// -LRESULT CALLBACK WindowEventUtilities::_WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - if (uMsg == WM_CREATE) - { // Store pointer to Win32Window in user data area - SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)(((LPCREATESTRUCT)lParam)->lpCreateParams)); - return 0; - } - - // look up window instance - // note: it is possible to get a WM_SIZE before WM_CREATE - RenderWindow* win = (RenderWindow*)GetWindowLongPtr(hWnd, GWLP_USERDATA); - if (!win) - return DefWindowProc(hWnd, uMsg, wParam, lParam); - - //LogManager* log = LogManager::getSingletonPtr(); - //Iterator of all listeners registered to this RenderWindow - WindowEventListeners::iterator index, - start = _msListeners.lower_bound(win), - end = _msListeners.upper_bound(win); - - switch( uMsg ) - { - case WM_ACTIVATE: - { - bool active = (LOWORD(wParam) != WA_INACTIVE); - if( active ) - { - win->setActive( true ); - } - else - { - if( win->isDeactivatedOnFocusChange() ) - { - win->setActive( false ); - } - } - - for( ; start != end; ++start ) - (start->second)->windowFocusChange(win); - break; - } - case WM_SYSKEYDOWN: - switch( wParam ) - { - case VK_CONTROL: - case VK_SHIFT: - case VK_MENU: //ALT - //return zero to bypass defProc and signal we processed the message - return 0; - } - break; - case WM_SYSKEYUP: - switch( wParam ) - { - case VK_CONTROL: - case VK_SHIFT: - case VK_MENU: //ALT - case VK_F10: - //return zero to bypass defProc and signal we processed the message - return 0; - } - break; - case WM_SYSCHAR: - // return zero to bypass defProc and signal we processed the message, unless it's an ALT-space - if (wParam != VK_SPACE) - return 0; - break; - case WM_ENTERSIZEMOVE: - //log->logMessage("WM_ENTERSIZEMOVE"); - break; - case WM_EXITSIZEMOVE: - //log->logMessage("WM_EXITSIZEMOVE"); - break; - case WM_MOVE: - //log->logMessage("WM_MOVE"); - win->windowMovedOrResized(); - for(index = start; index != end; ++index) - (index->second)->windowMoved(win); - break; - case WM_DISPLAYCHANGE: - win->windowMovedOrResized(); - for(index = start; index != end; ++index) - (index->second)->windowResized(win); - break; - case WM_SIZE: - //log->logMessage("WM_SIZE"); - { - UINT width = LOWORD(lParam); - UINT height = HIWORD(lParam); - win->resize(width, height); - } - for(index = start; index != end; ++index) - (index->second)->windowResized(win); - break; - case WM_GETMINMAXINFO: - // Prevent the window from going smaller than some minimu size - ((MINMAXINFO*)lParam)->ptMinTrackSize.x = 100; - ((MINMAXINFO*)lParam)->ptMinTrackSize.y = 100; - break; - case WM_CLOSE: - { - //log->logMessage("WM_CLOSE"); - bool close = true; - for(index = start; index != end; ++index) - { - if (!(index->second)->windowClosing(win)) - close = false; - } - if (!close) return 0; - - for(index = _msListeners.lower_bound(win); index != end; ++index) - (index->second)->windowClosed(win); - win->destroy(); - return 0; - } - } - - return DefWindowProc( hWnd, uMsg, wParam, lParam ); -} -#endif // OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - -//--------------------------------------------------------------------------------// -void WindowEventUtilities::messagePump() -{ -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - // Windows Message Loop (NULL means check all HWNDs belonging to this context) - MSG msg; - while( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) ) - { - TranslateMessage( &msg ); - DispatchMessage( &msg ); - } -#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX - //GLX Message Pump - Ogre::RenderWindowList::iterator win = _msWindows.begin(); - Ogre::RenderWindowList::iterator end = _msWindows.end(); - - Display* xDisplay = 0; // same for all windows - - for (; win != end; win++) - { - XID xid; - XEvent event; - - if (!xDisplay) - (*win)->getCustomAttribute("XDISPLAY", &xDisplay); - - (*win)->getCustomAttribute("WINDOW", &xid); - - while (XCheckWindowEvent (xDisplay, xid, StructureNotifyMask | VisibilityChangeMask | FocusChangeMask, &event)) - { - GLXProc(*win, event); - } - - // The ClientMessage event does not appear under any Event Mask - while (XCheckTypedWindowEvent (xDisplay, xid, ClientMessage, &event)) - { - GLXProc(*win, event); - } - } -#endif -} - -//--------------------------------------------------------------------------------// -void WindowEventUtilities::addWindowEventListener( RenderWindow* window, WindowEventListener* listener ) -{ - _msListeners.insert(std::make_pair(window, listener)); -} - -//--------------------------------------------------------------------------------// -void WindowEventUtilities::removeWindowEventListener( RenderWindow* window, WindowEventListener* listener ) -{ - WindowEventListeners::iterator i = _msListeners.begin(), e = _msListeners.end(); - - for( ; i != e; ++i ) - { - if( i->first == window && i->second == listener ) - { - _msListeners.erase(i); - break; - } - } -} - -//--------------------------------------------------------------------------------// -void WindowEventUtilities::_addRenderWindow(RenderWindow* window) -{ - _msWindows.push_back(window); -} - -//--------------------------------------------------------------------------------// -void WindowEventUtilities::_removeRenderWindow(RenderWindow* window) -{ - RenderWindowList::iterator i = std::find(_msWindows.begin(), _msWindows.end(), window); - if( i != _msWindows.end() ) - _msWindows.erase( i ); -} - -#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX -//--------------------------------------------------------------------------------// -static void GLXProc( Ogre::RenderWindow *win, const XEvent &event ) -{ - //An iterator for the window listeners - WindowEventListeners::iterator index, - start = _msListeners.lower_bound(win), - end = _msListeners.upper_bound(win); - - switch(event.type) - { - case ClientMessage: - { - ::Atom atom; - win->getCustomAttribute("ATOM", &atom); - if(event.xclient.format == 32 && event.xclient.data.l[0] == (long)atom) - { //Window closed by window manager - //Send message first, to allow app chance to unregister things that need done before - //window is shutdown - bool close = true; - for(index = start ; index != end; ++index) - { - if (!(index->second)->windowClosing(win)) - close = false; - } - if (!close) return; - - for(index = start ; index != end; ++index) - (index->second)->windowClosed(win); - win->destroy(); - } - break; - } - case DestroyNotify: - { - if (!win->isClosed()) - { - // Window closed without window manager warning. - for(index = start ; index != end; ++index) - (index->second)->windowClosed(win); - win->destroy(); - } - break; - } - case ConfigureNotify: - { - unsigned int oldWidth, oldHeight; - int oldLeft, oldTop; - win->getMetrics(oldWidth, oldHeight, oldLeft, oldTop); - win->resize(event.xconfigurerequest.width, event.xconfigurerequest.height); - - unsigned int newWidth, newHeight; - int newLeft, newTop; - win->getMetrics(newWidth, newHeight, newLeft, newTop); - - if (newLeft != oldLeft || newTop != oldTop) - { - for(index = start ; index != end; ++index) - (index->second)->windowMoved(win); - } - - if (newWidth != oldWidth || newHeight != oldHeight) - { - for(index = start ; index != end; ++index) - (index->second)->windowResized(win); - } - break; - } - case FocusIn: // Gained keyboard focus - case FocusOut: // Lost keyboard focus - for(index = start ; index != end; ++index) - (index->second)->windowFocusChange(win); - break; - case MapNotify: //Restored - win->setActive( true ); - for(index = start ; index != end; ++index) - (index->second)->windowFocusChange(win); - break; - case UnmapNotify: //Minimised - win->setActive( false ); - win->setVisible( false ); - for(index = start ; index != end; ++index) - (index->second)->windowFocusChange(win); - break; - case VisibilityNotify: - switch(event.xvisibility.state) - { - case VisibilityUnobscured: - win->setActive( true ); - win->setVisible( true ); - break; - case VisibilityPartiallyObscured: - win->setActive( true ); - win->setVisible( true ); - break; - case VisibilityFullyObscured: - win->setActive( false ); - win->setVisible( false ); - break; - } - for(index = start ; index != end; ++index) - (index->second)->windowFocusChange(win); - break; - default: - break; - } //End switch event.type -} -#endif - -} diff --git a/Components/Bites/src/SDLInputMapping.h b/Components/Bites/src/SDLInputMapping.h deleted file mode 100644 index 51e06698fe5..00000000000 --- a/Components/Bites/src/SDLInputMapping.h +++ /dev/null @@ -1,98 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#ifndef BITES_SDL_INPUTMAPPING -#define BITES_SDL_INPUTMAPPING - -namespace { - OgreBites::Event convert(const SDL_Event& in) - { - OgreBites::Event out; - - out.type = 0; - - switch(in.type) - { - case SDL_KEYDOWN: - out.type = OgreBites::KEYDOWN; - OGRE_FALLTHROUGH; - case SDL_KEYUP: - if(!out.type) - out.type = OgreBites::KEYUP; - out.key.repeat = in.key.repeat; - out.key.keysym.sym = in.key.keysym.sym; - out.key.keysym.mod = in.key.keysym.mod; - break; - case SDL_MOUSEBUTTONUP: - out.type = OgreBites::MOUSEBUTTONUP; - OGRE_FALLTHROUGH; - case SDL_MOUSEBUTTONDOWN: - if(!out.type) - out.type = OgreBites::MOUSEBUTTONDOWN; - out.button.x = in.button.x; - out.button.y = in.button.y; - out.button.button = in.button.button; - out.button.clicks = in.button.clicks; - break; - case SDL_MOUSEWHEEL: - out.type = OgreBites::MOUSEWHEEL; - out.wheel.y = in.wheel.y; - break; - case SDL_MOUSEMOTION: - out.type = OgreBites::MOUSEMOTION; - out.motion.x = in.motion.x; - out.motion.y = in.motion.y; - out.motion.xrel = in.motion.xrel; - out.motion.yrel = in.motion.yrel; - out.motion.windowID = in.motion.windowID; - break; - case SDL_FINGERDOWN: - out.type = OgreBites::FINGERDOWN; - OGRE_FALLTHROUGH; - case SDL_FINGERUP: - if(!out.type) - out.type = OgreBites::FINGERUP; - OGRE_FALLTHROUGH; - case SDL_FINGERMOTION: - if(!out.type) - out.type = OgreBites::FINGERMOTION; - out.tfinger.x = in.tfinger.x; - out.tfinger.y = in.tfinger.y; - out.tfinger.dx = in.tfinger.dx; - out.tfinger.dy = in.tfinger.dy; - out.tfinger.fingerId = in.tfinger.fingerId; - break; - case SDL_TEXTINPUT: - out.type = OgreBites::TEXTINPUT; - out.text.chars = in.text.text; - break; - case SDL_JOYAXISMOTION: - out.type = OgreBites::JOYAXISMOTION; - out.axis.which = in.jaxis.which; - out.axis.axis = in.jaxis.axis; - out.axis.value = in.jaxis.value; - break; - case SDL_CONTROLLERAXISMOTION: - out.type = OgreBites::CONTROLLERAXISMOTION; - out.axis.which = in.caxis.which; - out.axis.axis = in.caxis.axis; - out.axis.value = in.caxis.value; - break; - case SDL_CONTROLLERBUTTONDOWN: - out.type = OgreBites::CONTROLLERBUTTONDOWN; - OGRE_FALLTHROUGH; - case SDL_CONTROLLERBUTTONUP: - if(!out.type) - out.type = OgreBites::CONTROLLERBUTTONUP; - out.cbutton.which = in.cbutton.which; - out.cbutton.button = in.cbutton.button; - break; - } - - return out; - } -} - -#endif diff --git a/Components/Bites/src/resource.h b/Components/Bites/src/resource.h deleted file mode 100644 index a019861e7fc..00000000000 --- a/Components/Bites/src/resource.h +++ /dev/null @@ -1,36 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by OgreWin32Resources.rc -// -#define IDD_DLG_VIDEO 101 -#define IDD_DLG_CONFIG 101 -#define IDI_ICON1 103 -#define IDB_SPLASH 106 -#define IDD_DLG_ERROR 107 -#define IDI_OGREICON 111 -#define IDC_CBO_VIDEO 1001 -#define IDC_VIDEO_MODE 1002 -#define ID_LBL_RES 1003 -#define IDC_CBO_RESOLUTION 1004 -#define IDC_CBO_VIDEOMODE 1004 -#define IDC_COLOUR_DEPTH 1005 -#define IDC_CBO_COLOUR_DEPTH 1006 -#define IDC_CHK_FULLSCREEN 1007 -#define IDC_CBO_RENDERSYSTEM 1009 -#define IDC_OPTFRAME 1010 -#define IDC_CBO_OPTION 1011 -#define IDC_LST_OPTIONS 1013 -#define IDC_LBL_OPTION 1014 -#define IDC_ERRMSG 1018 -#define IDC_SELECT_VIDEO -1 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 115 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1020 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/Components/Bullet/CMakeLists.txt b/Components/Bullet/CMakeLists.txt deleted file mode 100644 index 670f85a2ce3..00000000000 --- a/Components/Bullet/CMakeLists.txt +++ /dev/null @@ -1,26 +0,0 @@ -set(HEADER_FILES - include/OgreBullet.h - ${PROJECT_BINARY_DIR}/include/OgreBulletExports.h) - -add_library(OgreBullet ${OGRE_COMP_LIB_TYPE} ${HEADER_FILES} src/OgreBullet.cpp) -target_link_libraries(OgreBullet PUBLIC OgreMain) -target_include_directories(OgreBullet PUBLIC - "$" - $) -target_include_directories(OgreBullet SYSTEM PUBLIC "$") - -if(OGRE_BUILD_DEPENDENCIES) - target_include_directories(OgreBullet PUBLIC "$") - target_link_libraries(OgreBullet PUBLIC "$") -else() - target_link_libraries(OgreBullet PUBLIC ${BULLET_LIBRARIES}) -endif() - -generate_export_header(OgreBullet - EXPORT_MACRO_NAME _OgreBulletExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreBulletExports.h) - -ogre_config_framework(OgreBullet) -ogre_config_component(OgreBullet) - -install(FILES ${HEADER_FILES} DESTINATION include/OGRE/Bullet) diff --git a/Components/Bullet/include/OgreBullet.h b/Components/Bullet/include/OgreBullet.h deleted file mode 100644 index 107204c5a81..00000000000 --- a/Components/Bullet/include/OgreBullet.h +++ /dev/null @@ -1,191 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#ifndef COMPONENTS_BULLET_H_ -#define COMPONENTS_BULLET_H_ - -#include "OgreBulletExports.h" - -#include "btBulletDynamicsCommon.h" -#include "Ogre.h" - -namespace Ogre -{ -namespace Bullet -{ - -/** \addtogroup Optional -* @{ -*/ -/** \defgroup Bullet Bullet - * [Bullet-Physics](https://pybullet.org) to %Ogre connection - * @{ - */ - -enum ColliderType -{ - CT_BOX, - CT_SPHERE, - CT_CYLINDER, - CT_CAPSULE, - CT_TRIMESH, - CT_HULL -}; - -inline btQuaternion convert(const Quaternion& q) { return btQuaternion(q.x, q.y, q.z, q.w); } -inline btVector3 convert(const Vector3& v) { return btVector3(v.x, v.y, v.z); } - -inline Quaternion convert(const btQuaternion& q) { return Quaternion(q.w(), q.x(), q.y(), q.z()); } -inline Vector3 convert(const btVector3& v) { return Vector3(v.x(), v.y(), v.z()); } - -/** A MotionState is Bullet's way of informing you about updates to an object. - * Pass this MotionState to a btRigidBody to have your SceneNode updated automaticaly. - */ -class _OgreBulletExport RigidBodyState : public btMotionState -{ - Node* mNode; - -public: - RigidBodyState(Node* node) : mNode(node) {} - - void getWorldTransform(btTransform& ret) const override - { - ret = btTransform(convert(mNode->getOrientation()), convert(mNode->getPosition())); - } - - void setWorldTransform(const btTransform& in) override - { - btQuaternion rot = in.getRotation(); - btVector3 pos = in.getOrigin(); - mNode->setOrientation(rot.w(), rot.x(), rot.y(), rot.z()); - mNode->setPosition(pos.x(), pos.y(), pos.z()); - } -}; - -/// create sphere collider using ogre provided data -_OgreBulletExport btSphereShape* createSphereCollider(const MovableObject* mo); -/// create box collider using ogre provided data -_OgreBulletExport btBoxShape* createBoxCollider(const MovableObject* mo); -/// create capsule collider using ogre provided data -_OgreBulletExport btCapsuleShape* createCapsuleCollider(const MovableObject* mo); -/// create capsule collider using ogre provided data -_OgreBulletExport btCylinderShape* createCylinderCollider(const MovableObject* mo); - -struct _OgreBulletExport CollisionListener -{ - virtual ~CollisionListener() {} - /** Called when two objects collide - * @param other the other object - * @param manifoldPoint the collision point - */ - virtual void contact(const MovableObject* other, const btManifoldPoint& manifoldPoint) = 0; -}; - -struct _OgreBulletExport RayResultCallback -{ - virtual ~RayResultCallback() {} - /** Called for each object hit by the ray - * @param other the other object - * @param distance the distance from ray origin to hit point - */ - virtual void addSingleResult(const MovableObject* other, float distance) = 0; -}; - -/// simplified wrapper with automatic memory management -class _OgreBulletExport CollisionWorld -{ -protected: - std::unique_ptr mCollisionConfig; - std::unique_ptr mDispatcher; - std::unique_ptr mBroadphase; - - btCollisionWorld* mBtWorld; - -public: - CollisionWorld(btCollisionWorld* btWorld) : mBtWorld(btWorld) {} - virtual ~CollisionWorld(); - - btCollisionObject* addCollisionObject(Entity* ent, ColliderType ct, int group = 1, int mask = -1); - - void rayTest(const Ray& ray, RayResultCallback* callback, float maxDist = 1000); -}; - -/// simplified wrapper with automatic memory management -class _OgreBulletExport DynamicsWorld : public CollisionWorld -{ - std::unique_ptr mSolver; - -public: - explicit DynamicsWorld(const Vector3& gravity); - DynamicsWorld(btDynamicsWorld* btWorld) : CollisionWorld(btWorld) {} - - /** Add an Entity as a rigid body to the DynamicsWorld - * @param mass the mass of the object - * @param ent the entity to control - * @param ct the collider type - * @param listener a listener to call on collision with other objects - * @param group the collision group - * @param mask the collision mask - */ - btRigidBody* addRigidBody(float mass, Entity* ent, ColliderType ct, CollisionListener* listener = nullptr, - int group = 1, int mask = -1); - - btDynamicsWorld* getBtWorld() const { return (btDynamicsWorld*)mBtWorld; } -}; - -class _OgreBulletExport DebugDrawer : public btIDebugDraw -{ - SceneNode* mNode; - btCollisionWorld* mWorld; - - ManualObject mLines; - int mDebugMode; - -public: - DebugDrawer(SceneNode* node, btCollisionWorld* world) - : mNode(node), mWorld(world), mLines(""), mDebugMode(DBG_DrawWireframe) - { - mLines.setCastShadows(false); - mNode->attachObject(&mLines); - mWorld->setDebugDrawer(this); - } - - void update() - { - mWorld->debugDrawWorld(); - if (!mLines.getSections().empty()) // begin was called - mLines.end(); - } - - void drawLine(const btVector3& from, const btVector3& to, const btVector3& color) override; - - void drawContactPoint(const btVector3& PointOnB, const btVector3& normalOnB, btScalar distance, int lifeTime, - const btVector3& color) override - { - drawLine(PointOnB, PointOnB + normalOnB * distance * 20, color); - } - - void reportErrorWarning(const char* warningString) override { LogManager::getSingleton().logWarning(warningString); } - - void draw3dText(const btVector3& location, const char* textString) override {} - - void setDebugMode(int mode) override - { - mDebugMode = mode; - - if (mDebugMode == DBG_NoDebug) - clear(); - } - - void clear() { mLines.clear(); } - - int getDebugMode() const override { return mDebugMode; } -}; -/** @} */ -/** @} */ -} // namespace Bullet -} // namespace Ogre - -#endif diff --git a/Components/Bullet/include/OgreBullet.i b/Components/Bullet/include/OgreBullet.i deleted file mode 100644 index f89543ac600..00000000000 --- a/Components/Bullet/include/OgreBullet.i +++ /dev/null @@ -1,49 +0,0 @@ - -#ifdef SWIGPYTHON -%module(package="Ogre", directors="1") Bullet -#else -%module(directors="1") OgreBullet -#endif - -%{ -#include "Ogre.h" -#include "OgreBullet.h" -%} - -%include std_string.i -%include exception.i -%include stdint.i -%include typemaps.i -%import "Ogre.i" - -%feature("director") Ogre::Bullet::CollisionListener; -%feature("director") Ogre::Bullet::RayResultCallback; - -#ifndef SWIGPYTHON -%rename(BulletDebugDrawer) Ogre::Bullet::DebugDrawer; -#endif - -// avoid wrapping BtWorld for now.. -%extend Ogre::Bullet::DynamicsWorld -{ - int stepSimulation(float timeStep) - { - return $self->getBtWorld()->stepSimulation(timeStep); - } -} - -#define _OgreBulletExport - -%include "OgreBullet.h" - -// bullet subset -#define SIMD_FORCE_INLINE -#define ATTRIBUTE_ALIGNED16(a) a -typedef float btScalar; -%include "LinearMath/btVector3.h" -%include "BulletCollision/NarrowPhaseCollision/btManifoldPoint.h" -%include "BulletCollision/CollisionDispatch/btCollisionObject.h" -%include "BulletDynamics/Dynamics/btRigidBody.h" - -%include "BulletCollision/CollisionDispatch/btCollisionWorld.h" -%include "BulletDynamics/Dynamics/btDynamicsWorld.h" \ No newline at end of file diff --git a/Components/Bullet/src/OgreBullet.cpp b/Components/Bullet/src/OgreBullet.cpp deleted file mode 100644 index 58ce70df34d..00000000000 --- a/Components/Bullet/src/OgreBullet.cpp +++ /dev/null @@ -1,731 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#include "OgreBullet.h" - -namespace Ogre -{ -namespace Bullet -{ - -typedef std::vector Vector3Array; -typedef std::pair BoneKeyIndex; - -btSphereShape* createSphereCollider(const MovableObject* mo) -{ - OgreAssert(mo->getParentSceneNode(), "MovableObject must be attached"); - - auto shape = new btSphereShape(mo->getBoundingRadius()); - shape->setLocalScaling(convert(mo->getParentSceneNode()->getScale())); - - return shape; -} -btBoxShape* createBoxCollider(const MovableObject* mo) -{ - OgreAssert(mo->getParentSceneNode(), "MovableObject must be attached"); - - auto shape = new btBoxShape(convert(mo->getBoundingBox().getHalfSize())); - shape->setLocalScaling(convert(mo->getParentSceneNode()->getScale())); - - return shape; -} - -btCapsuleShape* createCapsuleCollider(const MovableObject* mo) -{ - OgreAssert(mo->getParentSceneNode(), "MovableObject must be attached"); - - auto sz = mo->getBoundingBox().getHalfSize(); - - btScalar height = std::max(sz.x, std::max(sz.y, sz.z)); - btScalar radius; - btCapsuleShape* shape; - // Orient the capsule such that its height is aligned with the largest dimension. - if (height == sz.y) - { - radius = std::max(sz.x, sz.z); - shape = new btCapsuleShape(radius, 2 * height - 2 * radius); - } - else if (height == sz.x) - { - radius = std::max(sz.y, sz.z); - shape = new btCapsuleShapeX(radius, 2 * height - 2 * radius); - } - else - { - radius = std::max(sz.x, sz.y); - shape = new btCapsuleShapeZ(radius, 2 * height - 2 * radius); - } - - shape->setLocalScaling(convert(mo->getParentSceneNode()->getScale())); - - return shape; -} - -/// create capsule collider using ogre provided data -btCylinderShape* createCylinderCollider(const MovableObject* mo) -{ - OgreAssert(mo->getParentSceneNode(), "MovableObject must be attached"); - - auto sz = convert(mo->getBoundingBox().getHalfSize()); - - btScalar height = std::max(sz.x(), std::max(sz.y(), sz.z())); - btCylinderShape* shape; - // Orient the capsule such that its height is aligned with the largest dimension. - if (height == sz.y()) - { - shape = new btCylinderShape(sz); - } - else if (height == sz.x()) - { - shape = new btCylinderShapeX(sz); - } - else - { - shape = new btCylinderShapeZ(sz); - } - - shape->setLocalScaling(convert(mo->getParentSceneNode()->getScale())); - - return shape; -} - -struct EntityCollisionListener -{ - const MovableObject* entity; - CollisionListener* listener; -}; - -static void onTick(btDynamicsWorld* world, btScalar timeStep) -{ - int numManifolds = world->getDispatcher()->getNumManifolds(); - auto manifolds = world->getDispatcher()->getInternalManifoldPointer(); - for (int i = 0; i < numManifolds; i++) - { - btPersistentManifold* manifold = manifolds[i]; - - for (int j = 0; j < manifold->getNumContacts(); j++) - { - const btManifoldPoint& mp = manifold->getContactPoint(i); - auto body0 = static_cast(manifold->getBody0()->getUserPointer()); - auto body1 = static_cast(manifold->getBody1()->getUserPointer()); - if (body0->listener) - body0->listener->contact(body1->entity, mp); - if (body1->listener) - body1->listener->contact(body0->entity, mp); - } - } -} - -class VertexIndexToShape -{ -public: - VertexIndexToShape(const Affine3& transform = Affine3::IDENTITY); - VertexIndexToShape(Renderable* rend, const Affine3& transform = Affine3::IDENTITY); - VertexIndexToShape(const Entity* entity, const Affine3& transform = Affine3::IDENTITY); - ~VertexIndexToShape(); - - Real getRadius(); - Vector3 getSize(); - - btBvhTriangleMeshShape* createTrimesh(); - btConvexHullShape* createConvex(); - - void addEntity(const Entity* entity, const Affine3& transform = Affine3::IDENTITY); - void addMesh(const MeshPtr& mesh, const Affine3& transform = Affine3::IDENTITY); - - const Vector3* getVertices() { return mVertexBuffer; } - unsigned int getVertexCount() { return mVertexCount; }; - -private: - void addStaticVertexData(const VertexData* vertex_data); - - void addAnimatedVertexData(const VertexData* vertex_data, const VertexData* blended_data, - const Mesh::IndexMap* indexMap); - - void addIndexData(IndexData* data, const unsigned int offset = 0); - - Vector3* mVertexBuffer; - unsigned int* mIndexBuffer; - unsigned int mVertexCount; - unsigned int mIndexCount; - - Vector3 mBounds; - Real mBoundRadius; - - typedef std::map*> BoneIndex; - BoneIndex* mBoneIndex; - - Affine3 mTransform; - - Vector3 mScale; -}; - -/// wrapper with automatic memory management -class CollisionObject -{ -protected: - btCollisionObject* mBtBody; - btCollisionWorld* mBtWorld; - -public: - CollisionObject(btCollisionObject* btBody, btCollisionWorld* btWorld) : mBtBody(btBody), mBtWorld(btWorld) {} - virtual ~CollisionObject() - { - mBtWorld->removeCollisionObject(mBtBody); - delete mBtBody->getCollisionShape(); - delete mBtBody; - } -}; -class RigidBody : public CollisionObject -{ -public: - using CollisionObject::CollisionObject; - - ~RigidBody() - { - delete (EntityCollisionListener*)(mBtBody)->getUserPointer(); - delete ((btRigidBody*)mBtBody)->getMotionState(); - } -}; - -DynamicsWorld::DynamicsWorld(const Vector3& gravity) : CollisionWorld(NULL) // prevent CollisionWorld from creating a world -{ - // Bullet initialisation. - mCollisionConfig.reset(new btDefaultCollisionConfiguration()); - mDispatcher.reset(new btCollisionDispatcher(mCollisionConfig.get())); - mSolver.reset(new btSequentialImpulseConstraintSolver()); - mBroadphase.reset(new btDbvtBroadphase()); - - auto btworld = new btDiscreteDynamicsWorld(mDispatcher.get(), mBroadphase.get(), mSolver.get(), mCollisionConfig.get()); - btworld->setGravity(convert(gravity)); - btworld->setInternalTickCallback(onTick); - mBtWorld = btworld; -} - -static btCollisionShape* getCollisionShape(Entity* ent, ColliderType ct) -{ - if (ent->hasSkeleton()) - { - ent->addSoftwareAnimationRequest(false); - ent->_updateAnimation(); - ent->setUpdateBoundingBoxFromSkeleton(true); - } - - btCollisionShape* cs = NULL; - switch (ct) - { - case CT_BOX: - cs = createBoxCollider(ent); - break; - case CT_SPHERE: - cs = createSphereCollider(ent); - break; - case CT_CYLINDER: - cs = createCylinderCollider(ent); - break; - case CT_CAPSULE: - cs = createCapsuleCollider(ent); - break; - case CT_TRIMESH: - cs = VertexIndexToShape(ent).createTrimesh(); - break; - case CT_HULL: - cs = VertexIndexToShape(ent).createConvex(); - break; - } - - if (ent->hasSkeleton()) - ent->removeSoftwareAnimationRequest(false); - - return cs; -} - -btRigidBody* DynamicsWorld::addRigidBody(float mass, Entity* ent, ColliderType ct, CollisionListener* listener, - int group, int mask) -{ - auto node = ent->getParentSceneNode(); - OgreAssert(node, "entity must be attached"); - RigidBodyState* state = new RigidBodyState(node); - - btCollisionShape* cs = getCollisionShape(ent, ct); - - btVector3 inertia(0, 0, 0); - if (mass != 0) // mass = 0 -> static - cs->calculateLocalInertia(mass, inertia); - - auto rb = new btRigidBody(mass, state, cs, inertia); - getBtWorld()->addRigidBody(rb, group, mask); - rb->setUserPointer(new EntityCollisionListener{ent, listener}); - - // transfer ownership to node - auto objWrapper = std::make_shared(rb, mBtWorld); - node->getUserObjectBindings().setUserAny("BtCollisionObject", objWrapper); - - return rb; -} - -btCollisionObject* CollisionWorld::addCollisionObject(Entity* ent, ColliderType ct, int group, int mask) -{ - auto node = ent->getParentSceneNode(); - OgreAssert(node, "entity must be attached"); - - btCollisionShape* cs = getCollisionShape(ent, ct); - - auto co = new btCollisionObject(); - co->setCollisionShape(cs); - mBtWorld->addCollisionObject(co, group, mask); - - // transfer ownership to node - auto objWrapper = std::make_shared(co, mBtWorld); - node->getUserObjectBindings().setUserAny("BtCollisionObject", objWrapper); - - return co; -} - -struct RayResultCallbackWrapper : public btCollisionWorld::RayResultCallback -{ - Bullet::RayResultCallback* mCallback; - float mMaxDistance; - RayResultCallbackWrapper(Bullet::RayResultCallback* callback, float maxDist) - : mCallback(callback), mMaxDistance(maxDist) - { - } - btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult, bool normalInWorldSpace) override - { - auto body0 = static_cast(rayResult.m_collisionObject->getUserPointer()); - mCallback->addSingleResult(body0->entity, rayResult.m_hitFraction * mMaxDistance); - return rayResult.m_hitFraction; - } -}; - -void CollisionWorld::rayTest(const Ray& ray, RayResultCallback* callback, float maxDist) -{ - RayResultCallbackWrapper wrapper(callback, maxDist); - btVector3 from = convert(ray.getOrigin()); - btVector3 to = convert(ray.getPoint(maxDist)); - mBtWorld->rayTest(from, to, wrapper); -} - -CollisionWorld::~CollisionWorld() { delete mBtWorld; } - -/* - * ============================================================================================= - * BtVertexIndexToShape - * ============================================================================================= - */ - -void VertexIndexToShape::addStaticVertexData(const VertexData* vertex_data) -{ - if (!vertex_data) - return; - - const VertexData* data = vertex_data; - - const unsigned int prev_size = mVertexCount; - mVertexCount += (unsigned int)data->vertexCount; - - Vector3* tmp_vert = new Vector3[mVertexCount]; - if (mVertexBuffer) - { - memcpy(tmp_vert, mVertexBuffer, sizeof(Vector3) * prev_size); - delete[] mVertexBuffer; - } - mVertexBuffer = tmp_vert; - - // Get the positional buffer element - { - const VertexElement* posElem = data->vertexDeclaration->findElementBySemantic(VES_POSITION); - HardwareVertexBufferSharedPtr vbuf = data->vertexBufferBinding->getBuffer(posElem->getSource()); - const unsigned int vSize = (unsigned int)vbuf->getVertexSize(); - - unsigned char* vertex = static_cast(vbuf->lock(HardwareBuffer::HBL_READ_ONLY)); - float* pReal; - Vector3* curVertices = &mVertexBuffer[prev_size]; - const unsigned int vertexCount = (unsigned int)data->vertexCount; - for (unsigned int j = 0; j < vertexCount; ++j) - { - posElem->baseVertexPointerToElement(vertex, &pReal); - vertex += vSize; - - curVertices->x = (*pReal++); - curVertices->y = (*pReal++); - curVertices->z = (*pReal++); - - *curVertices = mTransform * (*curVertices); - - curVertices++; - } - vbuf->unlock(); - } -} -//------------------------------------------------------------------------------------------------ -void VertexIndexToShape::addAnimatedVertexData(const VertexData* vertex_data, const VertexData* blend_data, - const Mesh::IndexMap* indexMap) -{ - // Get the bone index element - assert(vertex_data); - - const VertexData* data = blend_data; - const unsigned int prev_size = mVertexCount; - mVertexCount += (unsigned int)data->vertexCount; - Vector3* tmp_vert = new Vector3[mVertexCount]; - if (mVertexBuffer) - { - memcpy(tmp_vert, mVertexBuffer, sizeof(Vector3) * prev_size); - delete[] mVertexBuffer; - } - mVertexBuffer = tmp_vert; - - // Get the positional buffer element - { - const VertexElement* posElem = data->vertexDeclaration->findElementBySemantic(VES_POSITION); - assert(posElem); - HardwareVertexBufferSharedPtr vbuf = data->vertexBufferBinding->getBuffer(posElem->getSource()); - const unsigned int vSize = (unsigned int)vbuf->getVertexSize(); - - unsigned char* vertex = static_cast(vbuf->lock(HardwareBuffer::HBL_READ_ONLY)); - float* pReal; - Vector3* curVertices = &mVertexBuffer[prev_size]; - const unsigned int vertexCount = (unsigned int)data->vertexCount; - for (unsigned int j = 0; j < vertexCount; ++j) - { - posElem->baseVertexPointerToElement(vertex, &pReal); - vertex += vSize; - - curVertices->x = (*pReal++); - curVertices->y = (*pReal++); - curVertices->z = (*pReal++); - - *curVertices = mTransform * (*curVertices); - - curVertices++; - } - vbuf->unlock(); - } - { - const VertexElement* bneElem = vertex_data->vertexDeclaration->findElementBySemantic(VES_BLEND_INDICES); - assert(bneElem); - - HardwareVertexBufferSharedPtr vbuf = vertex_data->vertexBufferBinding->getBuffer(bneElem->getSource()); - const unsigned int vSize = (unsigned int)vbuf->getVertexSize(); - unsigned char* vertex = static_cast(vbuf->lock(HardwareBuffer::HBL_READ_ONLY)); - - unsigned char* pBone; - - if (!mBoneIndex) - mBoneIndex = new BoneIndex(); - BoneIndex::iterator i; - - Vector3* curVertices = &mVertexBuffer[prev_size]; - - const unsigned int vertexCount = (unsigned int)vertex_data->vertexCount; - for (unsigned int j = 0; j < vertexCount; ++j) - { - bneElem->baseVertexPointerToElement(vertex, &pBone); - vertex += vSize; - - const unsigned char currBone = (indexMap) ? (*indexMap)[*pBone] : *pBone; - i = mBoneIndex->find(currBone); - Vector3Array* l = 0; - if (i == mBoneIndex->end()) - { - l = new Vector3Array; - mBoneIndex->emplace(currBone, l); - } - else - { - l = i->second; - } - - l->push_back(*curVertices); - - curVertices++; - } - vbuf->unlock(); - } -} -//------------------------------------------------------------------------------------------------ -void VertexIndexToShape::addIndexData(IndexData* data, const unsigned int offset) -{ - const unsigned int prev_size = mIndexCount; - mIndexCount += (unsigned int)data->indexCount; - - unsigned int* tmp_ind = new unsigned int[mIndexCount]; - if (mIndexBuffer) - { - memcpy(tmp_ind, mIndexBuffer, sizeof(unsigned int) * prev_size); - delete[] mIndexBuffer; - } - mIndexBuffer = tmp_ind; - - const unsigned int numTris = (unsigned int)data->indexCount / 3; - HardwareIndexBufferSharedPtr ibuf = data->indexBuffer; - const bool use32bitindexes = (ibuf->getType() == HardwareIndexBuffer::IT_32BIT); - unsigned int index_offset = prev_size; - - if (use32bitindexes) - { - const unsigned int* pInt = static_cast(ibuf->lock(HardwareBuffer::HBL_READ_ONLY)); - for (unsigned int k = 0; k < numTris; ++k) - { - mIndexBuffer[index_offset++] = offset + *pInt++; - mIndexBuffer[index_offset++] = offset + *pInt++; - mIndexBuffer[index_offset++] = offset + *pInt++; - } - ibuf->unlock(); - } - else - { - const unsigned short* pShort = static_cast(ibuf->lock(HardwareBuffer::HBL_READ_ONLY)); - for (unsigned int k = 0; k < numTris; ++k) - { - mIndexBuffer[index_offset++] = offset + static_cast(*pShort++); - mIndexBuffer[index_offset++] = offset + static_cast(*pShort++); - mIndexBuffer[index_offset++] = offset + static_cast(*pShort++); - } - ibuf->unlock(); - } -} -//------------------------------------------------------------------------------------------------ -Real VertexIndexToShape::getRadius() -{ - if (mBoundRadius == (-1)) - { - getSize(); - mBoundRadius = (std::max(mBounds.x, std::max(mBounds.y, mBounds.z)) * 0.5); - } - return mBoundRadius; -} -//------------------------------------------------------------------------------------------------ -Vector3 VertexIndexToShape::getSize() -{ - const unsigned int vCount = getVertexCount(); - if (mBounds == Vector3(-1, -1, -1) && vCount > 0) - { - - const Vector3* const v = getVertices(); - - Vector3 vmin(v[0]); - Vector3 vmax(v[0]); - - for (unsigned int j = 1; j < vCount; j++) - { - vmin.x = std::min(vmin.x, v[j].x); - vmin.y = std::min(vmin.y, v[j].y); - vmin.z = std::min(vmin.z, v[j].z); - - vmax.x = std::max(vmax.x, v[j].x); - vmax.y = std::max(vmax.y, v[j].y); - vmax.z = std::max(vmax.z, v[j].z); - } - - mBounds.x = vmax.x - vmin.x; - mBounds.y = vmax.y - vmin.y; - mBounds.z = vmax.z - vmin.z; - } - - return mBounds; -} -//------------------------------------------------------------------------------------------------ -btConvexHullShape* VertexIndexToShape::createConvex() -{ - assert(mVertexCount && (mIndexCount >= 6) && ("Mesh must have some vertices and at least 6 indices (2 triangles)")); - - btConvexHullShape* shape = new btConvexHullShape((btScalar*)&mVertexBuffer[0].x, mVertexCount, sizeof(Vector3)); - - shape->setLocalScaling(convert(mScale)); - - return shape; -} -//------------------------------------------------------------------------------------------------ -btBvhTriangleMeshShape* VertexIndexToShape::createTrimesh() -{ - assert(mVertexCount && (mIndexCount >= 6) && ("Mesh must have some vertices and at least 6 indices (2 triangles)")); - - unsigned int numFaces = mIndexCount / 3; - - btTriangleMesh* trimesh = new btTriangleMesh(); - unsigned int* indices = mIndexBuffer; - Vector3* vertices = mVertexBuffer; - - btVector3 vertexPos[3]; - for (unsigned int n = 0; n < numFaces; ++n) - { - { - const Vector3& vec = vertices[*indices]; - vertexPos[0][0] = vec.x; - vertexPos[0][1] = vec.y; - vertexPos[0][2] = vec.z; - } - { - const Vector3& vec = vertices[*(indices + 1)]; - vertexPos[1][0] = vec.x; - vertexPos[1][1] = vec.y; - vertexPos[1][2] = vec.z; - } - { - const Vector3& vec = vertices[*(indices + 2)]; - vertexPos[2][0] = vec.x; - vertexPos[2][1] = vec.y; - vertexPos[2][2] = vec.z; - } - - indices += 3; - - trimesh->addTriangle(vertexPos[0], vertexPos[1], vertexPos[2]); - } - - const bool useQuantizedAABB = true; - btBvhTriangleMeshShape* shape = new btBvhTriangleMeshShape(trimesh, useQuantizedAABB); - - shape->setLocalScaling(convert(mScale)); - - return shape; -} -//------------------------------------------------------------------------------------------------ -VertexIndexToShape::~VertexIndexToShape() -{ - delete[] mVertexBuffer; - delete[] mIndexBuffer; - - if (mBoneIndex) - { - for (auto & i : *mBoneIndex) - { - delete i.second; - } - delete mBoneIndex; - } -} -//------------------------------------------------------------------------------------------------ -VertexIndexToShape::VertexIndexToShape(const Affine3& transform) - : mVertexBuffer(0), mIndexBuffer(0), mVertexCount(0), mIndexCount(0), mBounds(Vector3(-1, -1, -1)), - mBoundRadius(-1), mBoneIndex(0), mTransform(transform), mScale(1) -{ -} -//------------------------------------------------------------------------------------------------ -VertexIndexToShape::VertexIndexToShape(const Entity* entity, const Affine3& transform) : VertexIndexToShape(transform) -{ - addEntity(entity, transform); -} -//------------------------------------------------------------------------------------------------ -VertexIndexToShape::VertexIndexToShape(Renderable* rend, const Affine3& transform) : VertexIndexToShape(transform) -{ - RenderOperation op; - rend->getRenderOperation(op); - addStaticVertexData(op.vertexData); - if (op.useIndexes) - addIndexData(op.indexData); -} -//------------------------------------------------------------------------------------------------ -void VertexIndexToShape::addEntity(const Entity* entity, const Affine3& transform) -{ - // Each entity added need to reset size and radius - // next time getRadius and getSize are asked, they're computed. - mBounds = Vector3(-1, -1, -1); - mBoundRadius = -1; - - auto node = entity->getParentSceneNode(); - mTransform = transform; - mScale = node ? node->getScale() : Vector3(1, 1, 1); - - bool hasSkeleton = entity->hasSkeleton(); - - if (entity->getMesh()->sharedVertexData) - { - if (hasSkeleton) - addAnimatedVertexData(entity->getMesh()->sharedVertexData, entity->_getSkelAnimVertexData(), - &entity->getMesh()->sharedBlendIndexToBoneIndexMap); - else - addStaticVertexData(entity->getMesh()->sharedVertexData); - } - - for (unsigned int i = 0; i < entity->getNumSubEntities(); ++i) - { - SubMesh* sub_mesh = entity->getSubEntity(i)->getSubMesh(); - - if (!sub_mesh->useSharedVertices) - { - addIndexData(sub_mesh->indexData, mVertexCount); - - if (hasSkeleton) - addAnimatedVertexData(sub_mesh->vertexData, entity->getSubEntity(i)->_getSkelAnimVertexData(), - &sub_mesh->blendIndexToBoneIndexMap); - else - addStaticVertexData(sub_mesh->vertexData); - } - else - { - addIndexData(sub_mesh->indexData); - } - } -} -//------------------------------------------------------------------------------------------------ -void VertexIndexToShape::addMesh(const MeshPtr& mesh, const Affine3& transform) -{ - // Each entity added need to reset size and radius - // next time getRadius and getSize are asked, they're computed. - mBounds = Vector3(-1, -1, -1); - mBoundRadius = -1; - - mTransform = transform; - - if (mesh->hasSkeleton()) - LogManager::getSingleton().logWarning("Mesh " + mesh->getName() + " has a skeleton but added non animated"); - - if (mesh->sharedVertexData) - { - VertexIndexToShape::addStaticVertexData(mesh->sharedVertexData); - } - - for (unsigned int i = 0; i < mesh->getNumSubMeshes(); ++i) - { - SubMesh* sub_mesh = mesh->getSubMesh(i); - - if (!sub_mesh->useSharedVertices) - { - VertexIndexToShape::addIndexData(sub_mesh->indexData, mVertexCount); - VertexIndexToShape::addStaticVertexData(sub_mesh->vertexData); - } - else - { - VertexIndexToShape::addIndexData(sub_mesh->indexData); - } - } -} - -/* - * ============================================================================================= - * BtDebugDrawer - * ============================================================================================= - */ -//------------------------------------------------------------------------------------------------ -void DebugDrawer::drawLine(const btVector3& from, const btVector3& to, const btVector3& color) -{ - if (mLines.getSections().empty()) - { - const char* matName = "Ogre/Debug/LinesMat"; - auto mat = MaterialManager::getSingleton().getByName(matName, RGN_INTERNAL); - if (!mat) - { - mat = MaterialManager::getSingleton().create(matName, RGN_INTERNAL); - auto p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->setVertexColourTracking(TVC_AMBIENT); - } - mLines.setBufferUsage(HBU_CPU_TO_GPU); - mLines.begin(mat, RenderOperation::OT_LINE_LIST); - } - else if (mLines.getCurrentVertexCount() == 0) - mLines.beginUpdate(0); - - ColourValue col(color.x(), color.x(), color.z()); - mLines.position(convert(from)); - mLines.colour(col); - mLines.position(convert(to)); - mLines.colour(col); -} -} // namespace Bullet -} // namespace Ogre diff --git a/Components/CMakeLists.txt b/Components/CMakeLists.txt deleted file mode 100644 index 8ef93900fbe..00000000000 --- a/Components/CMakeLists.txt +++ /dev/null @@ -1,61 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure Components build - -# Use same build type for components as main build -set(OGRE_COMP_LIB_TYPE ${OGRE_LIB_TYPE}) - -if (OGRE_BUILD_COMPONENT_BITES) - add_subdirectory(Bites) -endif() - -if (OGRE_BUILD_COMPONENT_BULLET) - add_subdirectory(Bullet) -endif() - -if (OGRE_BUILD_COMPONENT_PAGING) - add_subdirectory(Paging) -endif () - -if (OGRE_BUILD_COMPONENT_MESHLODGENERATOR) - add_subdirectory(MeshLodGenerator) -endif () - -if (OGRE_BUILD_COMPONENT_PROPERTY) - add_subdirectory(Property) -endif () - -if (OGRE_BUILD_COMPONENT_TERRAIN) - add_subdirectory(Terrain) -endif () - -if (OGRE_BUILD_COMPONENT_RTSHADERSYSTEM) - add_subdirectory(RTShaderSystem) -endif () - -if (OGRE_BUILD_COMPONENT_VOLUME) - add_subdirectory(Volume) -endif () - -if (OGRE_BUILD_COMPONENT_OVERLAY) - add_subdirectory(Overlay) -endif () - -if (OGRE_BUILD_COMPONENT_PYTHON) - add_subdirectory(Python) -endif() - -if (OGRE_BUILD_COMPONENT_CSHARP) - add_subdirectory(Csharp) -endif() - -if (OGRE_BUILD_COMPONENT_JAVA) - add_subdirectory(Java) -endif() \ No newline at end of file diff --git a/Components/Csharp/CMakeLists.txt b/Components/Csharp/CMakeLists.txt deleted file mode 100644 index 36d4e1e3442..00000000000 --- a/Components/Csharp/CMakeLists.txt +++ /dev/null @@ -1,92 +0,0 @@ -if(NOT SWIG_FOUND) - set(OGRE_BUILD_COMPONENT_CSHARP OFF CACHE BOOL "" FORCE) - message(WARNING "Csharp Component disabled because SWIG was not found") - return() -endif() - -if(MSVC) - enable_language(CSharp) -else() - find_program(CMAKE_CSharp_COMPILER mcs) -endif() - -if(NOT CMAKE_CSharp_COMPILER) - message(WARNING "Csharp Component disabled because Csharp was not found") - return() -endif() - -include_directories("${PROJECT_BINARY_DIR}/include" "${PROJECT_SOURCE_DIR}/OgreMain/include") -include(${SWIG_USE_FILE}) - -if(MSVC) - add_definitions(/bigobj /wd4700) -else() - if(CMAKE_COMPILER_IS_GNUCXX) - add_definitions(-Wno-suggest-override) - endif() - add_definitions(-Wno-strict-aliasing -Wno-cast-qual -Wno-shadow -Wno-missing-declarations -Wno-unused-but-set-variable) -endif() - -set(CMAKE_SWIG_FLAGS -w401,314 -namespace org.ogre) - -if(SWIG_VERSION VERSION_LESS "4.1") - list(APPEND CMAKE_SWIG_FLAGS -Dfinal) -endif() - -set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/csharp/") -set(CMAKE_SWIG_OUTDIR "${PROJECT_BINARY_DIR}/csharp/") - -set_source_files_properties(../../OgreMain/include/Ogre.i PROPERTIES CPLUSPLUS ON) -set(SWIG_INPUT_MODULES ../../OgreMain/include/Ogre.i) -set(SWIG_COMPONENT_LIBRARIES OgreMain) - -if(OGRE_BUILD_COMPONENT_RTSHADERSYSTEM) - set_source_files_properties(../RTShaderSystem/include/OgreRTShader.i PROPERTIES CPLUSPLUS ON) - list(APPEND SWIG_INPUT_MODULES ../RTShaderSystem/include/OgreRTShader.i) - list(APPEND SWIG_COMPONENT_LIBRARIES "OgreRTShaderSystem") -endif() - -if(OGRE_BUILD_COMPONENT_TERRAIN) - set_source_files_properties(../Terrain/include/OgreTerrain.i PROPERTIES CPLUSPLUS ON) - list(APPEND SWIG_INPUT_MODULES ../Terrain/include/OgreTerrain.i) - list(APPEND SWIG_COMPONENT_LIBRARIES "OgreTerrain") -endif() - -if(OGRE_BUILD_COMPONENT_OVERLAY) - set_source_files_properties(../Overlay/include/OgreOverlay.i PROPERTIES CPLUSPLUS ON) - list(APPEND SWIG_INPUT_MODULES ../Overlay/include/OgreOverlay.i) - list(APPEND SWIG_COMPONENT_LIBRARIES "OgreOverlay") -endif() - -if(OGRE_BUILD_COMPONENT_OVERLAY_IMGUI) - include_directories("${IMGUI_DIR}") - list(APPEND CMAKE_SWIG_FLAGS -DHAVE_IMGUI -DIMGUI_DISABLE_OBSOLETE_FUNCTIONS) - set_source_files_properties(../Overlay/include/ImGui.i PROPERTIES CPLUSPLUS ON) - list(APPEND SWIG_INPUT_MODULE ../Overlay/include/ImGui.i) -endif() - -if(OGRE_BUILD_COMPONENT_BITES) - set_source_files_properties(../Bites/include/OgreBites.i PROPERTIES CPLUSPLUS ON) - list(APPEND SWIG_INPUT_MODULES ../Bites/include/OgreBites.i) - list(APPEND SWIG_COMPONENT_LIBRARIES "OgreBites") -endif() - -if(OGRE_BUILD_COMPONENT_BULLET) - include_directories("${BULLET_INCLUDE_DIRS}") - set_source_files_properties(../Bullet/include/OgreBullet.i PROPERTIES CPLUSPLUS ON) - list(APPEND SWIG_INPUT_MODULES ../Bullet/include/OgreBullet.i) - list(APPEND SWIG_COMPONENT_LIBRARIES "OgreBullet") -endif() - -swig_add_library(libOgre LANGUAGE csharp SOURCES ${SWIG_INPUT_MODULES}) -SWIG_LINK_LIBRARIES(libOgre ${SWIG_COMPONENT_LIBRARIES}) - -set(CLI_DEST lib/cli/ogre-sharp-${OGRE_VERSION}) -install(TARGETS libOgre LIBRARY DESTINATION ${CLI_DEST}/) - -# compile C# DLL -add_custom_command(TARGET libOgre POST_BUILD - COMMAND "${CMAKE_CSharp_COMPILER}" -target:library -out:Ogre.dll "${PROJECT_BINARY_DIR}/csharp/*.cs" - WORKING_DIRECTORY "${PROJECT_BINARY_DIR}/csharp/") - -install(FILES "${PROJECT_BINARY_DIR}/csharp/Ogre.dll" DESTINATION ${CLI_DEST}) diff --git a/Components/Java/CMakeLists.txt b/Components/Java/CMakeLists.txt deleted file mode 100644 index baa72dcddc1..00000000000 --- a/Components/Java/CMakeLists.txt +++ /dev/null @@ -1,115 +0,0 @@ -if(ANDROID) - set(JNI_FOUND TRUE) - add_library(cpufeatures STATIC ${ANDROID_NDK}/sources/android/cpufeatures/cpu-features.c) - set(JNI_LIBRARIES android log cpufeatures) - set(JNI_INCLUDE_DIRS "") -else() - find_package(JNI) - find_package(Java QUIET) -endif() - -if(NOT JNI_FOUND OR NOT SWIG_FOUND) - set(OGRE_BUILD_COMPONENT_JAVA OFF CACHE BOOL "" FORCE) - message(WARNING "Java Component disabled because SWIG or Java was not found") - return() -endif() - -include_directories(${JNI_INCLUDE_DIRS}) -include_directories("${PROJECT_BINARY_DIR}/include" "${PROJECT_SOURCE_DIR}/OgreMain/include") -include(${SWIG_USE_FILE}) - -if(MSVC) - add_definitions(/bigobj /wd4700) -else() - add_definitions(-Wno-strict-aliasing -Wno-cast-qual -Wno-shadow -Wno-missing-declarations -Wno-unused-but-set-variable ) - if(CMAKE_COMPILER_IS_GNUCXX) - add_definitions(-Wno-suggest-override) - endif() -endif() - -set(CMAKE_SWIG_FLAGS -w401,314 -package org.ogre) - -if(SWIG_VERSION VERSION_LESS "4.1") - list(APPEND CMAKE_SWIG_FLAGS -Dfinal) -endif() - -if (APPLE AND NOT ANDROID) - # we are using libc++ on OSX - list(APPEND CMAKE_SWIG_FLAGS -D_LIBCPP_VERSION) -endif() - -set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/java/libs") -set(CMAKE_SWIG_OUTDIR "${PROJECT_BINARY_DIR}/java/src/org/ogre") - -if(ANDROID) - set(CMAKE_SWIG_OUTDIR "${PROJECT_BINARY_DIR}/java/app/src/main/java/org/ogre") - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/java/app/src/main/jniLibs/${ANDROID_NDK_ABI_NAME}") - list(APPEND CMAKE_SWIG_FLAGS -D__ANDROID__) -endif() - -set_source_files_properties(../../OgreMain/include/Ogre.i PROPERTIES CPLUSPLUS ON) -set(SWIG_INPUT_MODULES ../../OgreMain/include/Ogre.i) -set(SWIG_COMPONENT_LIBRARIES OgreMain) - -if(OGRE_BUILD_COMPONENT_RTSHADERSYSTEM) - set_source_files_properties(../RTShaderSystem/include/OgreRTShader.i PROPERTIES CPLUSPLUS ON) - list(APPEND SWIG_INPUT_MODULES ../RTShaderSystem/include/OgreRTShader.i) - list(APPEND SWIG_COMPONENT_LIBRARIES "OgreRTShaderSystem") -endif() - -if(OGRE_BUILD_COMPONENT_TERRAIN) - set_source_files_properties(../Terrain/include/OgreTerrain.i PROPERTIES CPLUSPLUS ON) - list(APPEND SWIG_INPUT_MODULES ../Terrain/include/OgreTerrain.i) - list(APPEND SWIG_COMPONENT_LIBRARIES "OgreTerrain") -endif() - -if(OGRE_BUILD_COMPONENT_OVERLAY) - set_source_files_properties(../Overlay/include/OgreOverlay.i PROPERTIES CPLUSPLUS ON) - list(APPEND SWIG_INPUT_MODULES ../Overlay/include/OgreOverlay.i) - list(APPEND SWIG_COMPONENT_LIBRARIES "OgreOverlay") -endif() - -if(OGRE_BUILD_COMPONENT_OVERLAY_IMGUI) - include_directories("${IMGUI_DIR}") - list(APPEND CMAKE_SWIG_FLAGS -DHAVE_IMGUI -DIMGUI_DISABLE_OBSOLETE_FUNCTIONS) - set_source_files_properties(../Overlay/include/ImGui.i PROPERTIES CPLUSPLUS ON) - list(APPEND SWIG_INPUT_MODULE ../Overlay/include/ImGui.i) -endif() - -if(OGRE_BUILD_COMPONENT_BITES) - set_source_files_properties(../Bites/include/OgreBites.i PROPERTIES CPLUSPLUS ON) - - if(ANDROID) - set(JNI_LIBRARIES Plugin_ParticleFX Plugin_OctreeSceneManager RenderSystem_GLES2 EGL ${JNI_LIBRARIES}) - endif() - - list(APPEND SWIG_INPUT_MODULES ../Bites/include/OgreBites.i) - list(APPEND SWIG_COMPONENT_LIBRARIES "OgreBites") -endif() - -if(OGRE_BUILD_COMPONENT_BULLET) - include_directories("${BULLET_INCLUDE_DIRS}") - set_source_files_properties(../Bullet/include/OgreBullet.i PROPERTIES CPLUSPLUS ON) - list(APPEND SWIG_INPUT_MODULES ../Bullet/include/OgreBullet.i) - list(APPEND SWIG_COMPONENT_LIBRARIES "OgreBullet") -endif() - -swig_add_library(OgreJNI LANGUAGE java SOURCES ${SWIG_INPUT_MODULES}) -swig_link_libraries(OgreJNI ${SWIG_COMPONENT_LIBRARIES} ${JNI_LIBRARIES}) - -if(${Java_FOUND}) - set(CLASS_OUTPUT_PATH "${PROJECT_BINARY_DIR}/java/classes") - set(JAR_NAME "${PROJECT_BINARY_DIR}/java/Ogre-${OGRE_VERSION}.jar") - file(MAKE_DIRECTORY ${CLASS_OUTPUT_PATH}) - add_custom_command(TARGET OgreJNI POST_BUILD - COMMAND "${Java_JAVAC_EXECUTABLE}" -d ${CLASS_OUTPUT_PATH} "${PROJECT_BINARY_DIR}/java/src/org/ogre/*.java" - COMMAND "${Java_JAR_EXECUTABLE}" cf ${JAR_NAME} -C ${CLASS_OUTPUT_PATH} . - ) - - install(FILES ${JAR_NAME} DESTINATION share/java/) - ogre_install_target(OgreJNI "" FALSE) -endif() - -if(ANDROID) - set_target_properties(OgreJNI PROPERTIES LINK_FLAGS -s) # strip symbols -endif() diff --git a/Components/MeshLodGenerator/CMakeLists.txt b/Components/MeshLodGenerator/CMakeLists.txt deleted file mode 100644 index d6d0429ea7b..00000000000 --- a/Components/MeshLodGenerator/CMakeLists.txt +++ /dev/null @@ -1,41 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -############################################################ -# MeshLodGenerator optional component -############################################################ - -# define header and source files for the library -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") - -# Add needed definitions -add_definitions(-DOGRE_MESHLODGENERATOR_EXPORTS ${OGRE_VISIBILITY_FLAGS}) - -# setup target -get_native_precompiled_header(OgreMeshLodGenerator) -add_library(OgreMeshLodGenerator ${OGRE_COMP_LIB_TYPE} ${OgreMeshLodGenerator_pch} ${HEADER_FILES} ${SOURCE_FILES} ${PLATFORM_HEADER_FILES} ${PLATFORM_SOURCE_FILES}) -set_target_properties(OgreMeshLodGenerator PROPERTIES VERSION ${OGRE_SOVERSION} SOVERSION ${OGRE_SOVERSION}) -target_link_libraries(OgreMeshLodGenerator PUBLIC OgreMain) - -target_include_directories(OgreMeshLodGenerator PUBLIC - "$" - $) - -# repeat for PCH -include_directories("${PROJECT_SOURCE_DIR}/OgreMain/include" "${PROJECT_BINARY_DIR}/include" "${CMAKE_CURRENT_SOURCE_DIR}/include") -add_native_precompiled_header(OgreMeshLodGenerator "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreMeshLodPrecompiledHeaders.h") - -# install -ogre_config_framework(OgreMeshLodGenerator) -ogre_config_component(OgreMeshLodGenerator) - -install(FILES ${HEADER_FILES} - DESTINATION include/OGRE/MeshLodGenerator -) diff --git a/Components/MeshLodGenerator/include/OgreLod0Stripifier.h b/Components/MeshLodGenerator/include/OgreLod0Stripifier.h deleted file mode 100644 index 3d6d52de483..00000000000 --- a/Components/MeshLodGenerator/include/OgreLod0Stripifier.h +++ /dev/null @@ -1,362 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef _Lod0Stripifier_H__ -#define _Lod0Stripifier_H__ - -#include "OgreLodPrerequisites.h" -#include "OgreMesh.h" -#include "OgreSubMesh.h" -#include "OgreKeyFrame.h" -#include "OgreHardwareBufferManager.h" - -namespace Ogre -{ - class Lod0Stripifier - { - public: - Lod0Stripifier(); - ~Lod0Stripifier(); - bool StripLod0Vertices(const MeshPtr& mesh, bool stableVertexOrder = false); - - private: - struct RemapInfo; - void generateRemapInfo(const MeshPtr& mesh, bool stableVertexOrder); - static void performIndexDataRemap(HardwareBufferManagerBase* pHWBufferManager, IndexData* indexData, const RemapInfo& remapInfo); - static void performVertexDataRemap(HardwareBufferManagerBase* pHWBufferManager, VertexData* vertexData, const RemapInfo& remapInfo); - static HardwareVertexBufferSharedPtr getRemappedVertexBuffer(HardwareBufferManagerBase* pHWBufferManager, const HardwareVertexBufferSharedPtr& vb, size_t srcStart, size_t srcCount, const RemapInfo& remapInfo); - template static void performBoneAssignmentRemap(MeshOrSubmesh* m, const RemapInfo& remapInfo); - static void performPoseRemap(Pose* pose, const RemapInfo& remapInfo); - static void performAnimationTrackRemap(HardwareBufferManagerBase* pHWBufferManager, VertexAnimationTrack* track, const RemapInfo& remapInfo); - - private: - std::vector remapInfos; // 0 for shared geometry, 1+ for submesh index + 1 - }; - - - // Implementation ------------------------------------------------------------------------------------ - - struct Lod0Stripifier::RemapInfo - { - RemapInfo() : usedCount(0) { } - void prepare(size_t originalSize) { usedCount = 0; indexMap.resize(originalSize, UnusedIdx); } - template void markUsedIndices(IDX* indices, size_t indexCount) - { - for(IDX *idx = indices, *idx_end = idx + indexCount; idx < idx_end; ++idx) - if(indexMap[*idx] == UnusedIdx) - indexMap[*idx] = usedCount++; - } - void renumerate() - { - usedCount = 0; - for(size_t idx = 0, idx_end = indexMap.size(); idx < idx_end; ++idx) - if(indexMap[idx] != UnusedIdx) - indexMap[idx] = usedCount++; - } - bool nothingToStrip() const { return usedCount == indexMap.size(); } - HardwareIndexBuffer::IndexType minimalIndexType() const { return usedCount < 0xFFFF ? HardwareIndexBuffer::IT_16BIT : HardwareIndexBuffer::IT_32BIT; } - - public: - enum{ UnusedIdx = (unsigned)-1 }; - std::vector indexMap; // returns new index if indexed by old index, or UnusedIdx - unsigned usedCount; - }; - - inline Lod0Stripifier::Lod0Stripifier() - { - } - inline Lod0Stripifier::~Lod0Stripifier() - { - } - - inline void Lod0Stripifier::generateRemapInfo(const MeshPtr& mesh, bool stableVertexOrder) - { - size_t submeshCount = mesh->getNumSubMeshes(); - remapInfos.resize(1 + submeshCount); - remapInfos[0].prepare(mesh->sharedVertexData ? mesh->sharedVertexData->vertexCount : 0); - for(ushort i = 0; i < submeshCount; i++) - { - const SubMesh* submesh = mesh->getSubMesh(i); - remapInfos[1 + i].prepare(submesh->useSharedVertices ? 0 : submesh->vertexData->vertexCount); - - RemapInfo& remapInfo = remapInfos[submesh->useSharedVertices ? 0 : 1 + i]; - - for(int lod = mesh->getNumLodLevels() - 1; lod > 0; --lod) // intentionally skip lod0, visit in reverse order to improve vertex locality for high lods - { - IndexData *lodIndexData = submesh->mLodFaceList[lod - 1]; - void* ptr = lodIndexData->indexBuffer->lock( - lodIndexData->indexStart * lodIndexData->indexBuffer->getIndexSize(), - lodIndexData->indexCount * lodIndexData->indexBuffer->getIndexSize(), - HardwareBuffer::HBL_READ_ONLY); - - if(lodIndexData->indexBuffer->getType() == HardwareIndexBuffer::IT_32BIT) - remapInfo.markUsedIndices((uint32*)ptr, lodIndexData->indexCount); - else - remapInfo.markUsedIndices((uint16*)ptr, lodIndexData->indexCount); - - lodIndexData->indexBuffer->unlock(); - } - - if(stableVertexOrder) - remapInfos[1 + i].renumerate(); - } - if(stableVertexOrder) - remapInfos[0].renumerate(); - } - - inline void Lod0Stripifier::performIndexDataRemap(HardwareBufferManagerBase* pHWBufferManager, IndexData* indexData, const RemapInfo& remapInfo) - { - if(remapInfo.nothingToStrip()) - return; - - size_t indexCount = indexData->indexCount; - HardwareIndexBuffer::IndexType indexType = indexData->indexBuffer->getType(); - HardwareIndexBuffer::IndexType newIndexType = remapInfo.minimalIndexType(); - HardwareIndexBufferSharedPtr newIndexBuffer = - pHWBufferManager->createIndexBuffer( - newIndexType, indexCount, indexData->indexBuffer->getUsage(), indexData->indexBuffer->hasShadowBuffer()); - - void* pSrc = indexData->indexBuffer->lock( - indexData->indexStart * indexData->indexBuffer->getIndexSize(), - indexData->indexCount * indexData->indexBuffer->getIndexSize(), - HardwareBuffer::HBL_READ_ONLY); - void* pDst = newIndexBuffer->lock(HardwareBuffer::HBL_DISCARD); - - if(indexType == HardwareIndexBuffer::IT_32BIT && newIndexType == HardwareIndexBuffer::IT_32BIT) - { - uint32 *pSrc32 = (uint32*)pSrc, *pDst32 = (uint32*)pDst; - for(size_t i = 0; i < indexCount; ++i) - pDst32[i] = remapInfo.indexMap[pSrc32[i]]; - } - else if(indexType == HardwareIndexBuffer::IT_32BIT && newIndexType == HardwareIndexBuffer::IT_16BIT) - { - uint32 *pSrc32 = (uint32*)pSrc; uint16 *pDst16 = (uint16*)pDst; - for(size_t i = 0; i < indexCount; ++i) - pDst16[i] = (uint16)remapInfo.indexMap[pSrc32[i]]; - } - else if(indexType == HardwareIndexBuffer::IT_16BIT && newIndexType == HardwareIndexBuffer::IT_32BIT) - { - uint16 *pSrc16 = (uint16*)pSrc; uint32 *pDst32 = (uint32*)pDst; - for(size_t i = 0; i < indexCount; ++i) - pDst32[i] = remapInfo.indexMap[pSrc16[i]]; - } - else // indexType == HardwareIndexBuffer::IT_16BIT && newIndexType == HardwareIndexBuffer::IT_16BIT - { - uint16 *pSrc16 = (uint16*)pSrc, *pDst16 = (uint16*)pDst; - for(size_t i = 0; i < indexCount; ++i) - pDst16[i] = (uint16)remapInfo.indexMap[pSrc16[i]]; - } - - indexData->indexBuffer->unlock(); - newIndexBuffer->unlock(); - - indexData->indexBuffer = newIndexBuffer; - indexData->indexStart = 0; - } - - inline void Lod0Stripifier::performVertexDataRemap(HardwareBufferManagerBase* pHWBufferManager, VertexData* vertexData, const RemapInfo& remapInfo) - { - if(remapInfo.nothingToStrip()) - return; - - // Copy vertex buffers in turn - typedef std::map VBMap; - VBMap alreadyProcessed; // prevent duplication of the same buffer bound under several indices - const VertexBufferBinding::VertexBufferBindingMap& bindings = vertexData->vertexBufferBinding->getBindings(); - VertexBufferBinding::VertexBufferBindingMap::const_iterator vbi, vbend; - for(vbi = bindings.begin(), vbend = bindings.end(); vbi != vbend; ++vbi) - { - HardwareVertexBufferSharedPtr srcbuf = vbi->second; - VBMap::iterator it = alreadyProcessed.find(srcbuf); - if(it != alreadyProcessed.end()) - { - vertexData->vertexBufferBinding->setBinding(vbi->first, it->second); - continue; - } - - HardwareVertexBufferSharedPtr dstbuf = getRemappedVertexBuffer(pHWBufferManager, srcbuf, vertexData->vertexStart, vertexData->vertexCount, remapInfo); - vertexData->vertexBufferBinding->setBinding(vbi->first, dstbuf); - alreadyProcessed[srcbuf] = dstbuf; - } - - vertexData->vertexStart = 0; - vertexData->vertexCount = remapInfo.usedCount; - - vertexData->hardwareShadowVolWBuffer = HardwareVertexBufferSharedPtr(); // TODO: check this - vertexData->hwAnimationDataList.clear(); // TODO: check this - vertexData->hwAnimDataItemsUsed = 0; // TODO: check this - } - - inline HardwareVertexBufferSharedPtr Lod0Stripifier::getRemappedVertexBuffer(HardwareBufferManagerBase* pHWBufferManager, - const HardwareVertexBufferSharedPtr& srcbuf, size_t srcStart, size_t srcCount, const RemapInfo& remapInfo) - { - assert(!remapInfo.nothingToStrip()); - - size_t vertexSize = srcbuf->getVertexSize(); - HardwareVertexBufferSharedPtr dstbuf = - pHWBufferManager->createVertexBuffer( - vertexSize, remapInfo.usedCount, srcbuf->getUsage(), srcbuf->hasShadowBuffer()); - - char* pSrc = (char*)srcbuf->lock(srcStart * vertexSize, srcCount * vertexSize, HardwareBuffer::HBL_READ_ONLY); - char* pDst = (char*)dstbuf->lock(HardwareBuffer::HBL_DISCARD); - - for(size_t oldIdx = 0, oldIdxEnd = remapInfo.indexMap.size(); oldIdx < oldIdxEnd; ++oldIdx) - { - unsigned newIdx = remapInfo.indexMap[oldIdx]; - if(newIdx != RemapInfo::UnusedIdx) - memcpy(pDst + newIdx * vertexSize, pSrc + oldIdx * vertexSize, vertexSize); - } - - srcbuf->unlock(); - dstbuf->unlock(); - return dstbuf; - } - - template - inline void Lod0Stripifier::performBoneAssignmentRemap(MeshOrSubmesh* m, const RemapInfo& remapInfo) - { - if(remapInfo.nothingToStrip() || m->getBoneAssignments().empty()) - return; - - Mesh::VertexBoneAssignmentList tmp = m->getBoneAssignments(); - m->clearBoneAssignments(); - for(Mesh::VertexBoneAssignmentList::const_iterator it = tmp.begin(), it_end = tmp.end(); it != it_end; ++it) - { - VertexBoneAssignment vba = it->second; - unsigned newIdx = remapInfo.indexMap[vba.vertexIndex]; - if(newIdx != RemapInfo::UnusedIdx) - { - vba.vertexIndex = newIdx; - m->addBoneAssignment(vba); - } - } - } - - inline void Lod0Stripifier::performPoseRemap(Pose* pose, const RemapInfo& remapInfo) - { - if(remapInfo.nothingToStrip() || (pose->getVertexOffsets().empty() && pose->getNormals().empty())) - return; - - Pose::VertexOffsetMap vv = pose->getVertexOffsets(); - Pose::NormalsMap nn = pose->getNormals(); - pose->clearVertices(); - for(Pose::VertexOffsetMap::const_iterator vit = vv.begin(), vit_end = vv.end(); vit != vit_end; ++vit) - { - unsigned newIdx = remapInfo.indexMap[vit->first]; - if(newIdx != RemapInfo::UnusedIdx) - { - if(pose->getIncludesNormals()) - pose->addVertex(newIdx, vit->second, nn[vit->first]); - else - pose->addVertex(newIdx, vit->second); - } - } - } - - inline void Lod0Stripifier::performAnimationTrackRemap(HardwareBufferManagerBase* pHWBufferManager, VertexAnimationTrack* track, const RemapInfo& remapInfo) - { - if(remapInfo.nothingToStrip()) - return; - - if(track->getAnimationType() == VAT_MORPH) - { - for(unsigned short i = 0; i < track->getNumKeyFrames(); ++i) - { - VertexMorphKeyFrame* kf = track->getVertexMorphKeyFrame(i); - HardwareVertexBufferSharedPtr VB = kf->getVertexBuffer(); - kf->setVertexBuffer(getRemappedVertexBuffer(pHWBufferManager, VB, 0, VB->getNumVertices(), remapInfo)); - } - } - } - - inline bool Lod0Stripifier::StripLod0Vertices(const MeshPtr& mesh, bool stableVertexOrder) - { - // we need at least one lod level except lod0 that would be stripped - ushort numLods = mesh->hasManualLodLevel() ? 1 : mesh->getNumLodLevels(); - if(numLods <= 1) - return false; - - bool edgeListWasBuilt = mesh->isEdgeListBuilt(); - mesh->freeEdgeList(); - - generateRemapInfo(mesh, stableVertexOrder); - - if(mesh->sharedVertexData) - performVertexDataRemap(mesh->getHardwareBufferManager(), mesh->sharedVertexData, remapInfos[0]); - performBoneAssignmentRemap(mesh.get(), remapInfos[0]); - - size_t submeshCount = mesh->getNumSubMeshes(); - for(size_t i = 0; i < submeshCount; i++) - { - SubMesh* submesh = mesh->getSubMesh(i); - const RemapInfo& remapInfo = remapInfos[submesh->useSharedVertices ? 0 : 1 + i]; - - if(!submesh->useSharedVertices) - performVertexDataRemap(mesh->getHardwareBufferManager(), submesh->vertexData, remapInfo); - performBoneAssignmentRemap(submesh, remapInfo); - - for(int lod = numLods - 1; lod > 0; --lod) // intentionally skip lod0 - { - IndexData *lodIndexData = submesh->mLodFaceList[lod - 1]; // lod0 is stored separately - performIndexDataRemap(mesh->getHardwareBufferManager(), lodIndexData, remapInfo); - } - - OGRE_DELETE submesh->indexData; - submesh->indexData = submesh->mLodFaceList[0]; - submesh->mLodFaceList.erase(submesh->mLodFaceList.begin()); - } - - for(ushort lod = 1; lod < numLods - 1; ++lod) - mesh->_setLodUsage(lod, mesh->getLodLevel(ushort(lod + 1))); - mesh->_setLodInfo(ushort(numLods - 1)); - - - PoseList::const_iterator it; - for( it = mesh->getPoseList().begin(); it != mesh->getPoseList().end(); ++it) - { - Pose* pose = *it; - performPoseRemap(pose, remapInfos[pose->getTarget()]); - } - - for(unsigned short a = 0; a < mesh->getNumAnimations(); ++a) - { - Animation* anim = mesh->getAnimation(a); - for (const auto& trackIt : anim->_getVertexTrackList()) - { - performAnimationTrackRemap(mesh->getHardwareBufferManager(), trackIt.second, remapInfos[trackIt.first]); - } - } - - if(edgeListWasBuilt) - mesh->buildEdgeList(); - - return true; - } -} - -#endif diff --git a/Components/MeshLodGenerator/include/OgreLodCollapseCost.h b/Components/MeshLodGenerator/include/OgreLodCollapseCost.h deleted file mode 100644 index 0527bfe0410..00000000000 --- a/Components/MeshLodGenerator/include/OgreLodCollapseCost.h +++ /dev/null @@ -1,75 +0,0 @@ - -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef _LodCollapseCost_H__ -#define _LodCollapseCost_H__ - -#include "OgreLodPrerequisites.h" -#include "OgreLodData.h" - -namespace Ogre -{ -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup MeshLodGenerator -* @{ -*/ -class _OgreLodExport LodCollapseCost { -public: - LodCollapseCost() : mPreventPunchingHoles(false), mPreventBreakingLines(false) {} - virtual ~LodCollapseCost() {} - /// This is called after the LodInputProvider has initialized LodData. - virtual void initCollapseCosts(LodData* data); - /// Called from initCollapseCosts for every edge. - virtual void initVertexCollapseCost(LodData* data, LodData::Vertex* vertex); - /// Called when edge cost gets invalid. - virtual void updateVertexCollapseCost(LodData* data, LodData::Vertex* vertex); - /// Called by initVertexCollapseCost and updateVertexCollapseCost, when the vertex minimal cost needs to be updated. - virtual void computeVertexCollapseCost(LodData* data, LodData::Vertex* vertex, Real& collapseCost, LodData::Vertex*& collapseTo); - /// Returns the collapse cost of the given edge. - virtual Real computeEdgeCollapseCost(LodData* data, LodData::Vertex* src, LodData::Edge* dstEdge) = 0; - /// Set true to prevent collapsing edges that would result in the destruction of a triangle. - void setPreventPunchingHoles(bool prevent) { mPreventPunchingHoles = prevent; } - /// Set true to prevent collapsing edges that would result in the destruction of a line. - void setPreventBreakingLines(bool prevent) { mPreventBreakingLines = prevent; } -protected: - // Helper functions: - bool isBorderVertex(const LodData::Vertex* vertex) const; -private: - bool isEdgeCollapsible(LodData::Vertex * src, LodData::Vertex * dst); - bool mPreventPunchingHoles; - bool mPreventBreakingLines; -}; -/** @} */ -/** @} */ -} -#endif - - diff --git a/Components/MeshLodGenerator/include/OgreLodCollapseCostCurvature.h b/Components/MeshLodGenerator/include/OgreLodCollapseCostCurvature.h deleted file mode 100644 index ca324a149fb..00000000000 --- a/Components/MeshLodGenerator/include/OgreLodCollapseCostCurvature.h +++ /dev/null @@ -1,50 +0,0 @@ - -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef _LodCollapseCostCurvature_H__ -#define _LodCollapseCostCurvature_H__ - -#include "OgreLodPrerequisites.h" -#include "OgreLodCollapseCost.h" -#include "OgreLodData.h" - -namespace Ogre -{ - -class _OgreLodExport LodCollapseCostCurvature : - public LodCollapseCost -{ -public: - Real computeEdgeCollapseCost(LodData* data, LodData::Vertex* src, LodData::Edge* dstEdge) override; -}; - -} -#endif - - diff --git a/Components/MeshLodGenerator/include/OgreLodCollapseCostOutside.h b/Components/MeshLodGenerator/include/OgreLodCollapseCostOutside.h deleted file mode 100644 index 4e9bc8f917e..00000000000 --- a/Components/MeshLodGenerator/include/OgreLodCollapseCostOutside.h +++ /dev/null @@ -1,66 +0,0 @@ - -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef _LodCollapseCostOutside_H__ -#define _LodCollapseCostOutside_H__ - -#include "OgreLodPrerequisites.h" -#include "OgreLodCollapseCost.h" -#include "OgreLodData.h" -#include "OgreSharedPtr.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - -class _OgreLodExport LodCollapseCostOutside : - public LodCollapseCost -{ -public: - LodCollapseCostOutside(LodCollapseCostPtr costCalculator, Real outsideWeight, Real outsideWalkAngle); - ~LodCollapseCostOutside(); - void initCollapseCosts(LodData* data) override; - Real computeEdgeCollapseCost(LodData* data, LodData::Vertex* src, LodData::Edge* dstEdge) override; -private: - - Real mOutsideWeight; - Real mOutsideWalkAngle; - - // Result of this collapse cost algorithm will be modified, if it is outside. - LodCollapseCostPtr mCostCalculator; - LodOutsideMarker* mOutsideMarker; -}; - -} - -#include "OgreHeaderSuffix.h" - -#endif - - diff --git a/Components/MeshLodGenerator/include/OgreLodCollapseCostProfiler.h b/Components/MeshLodGenerator/include/OgreLodCollapseCostProfiler.h deleted file mode 100644 index e32a01327b4..00000000000 --- a/Components/MeshLodGenerator/include/OgreLodCollapseCostProfiler.h +++ /dev/null @@ -1,75 +0,0 @@ - -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef _LodCollapseCostProfiler_H__ -#define _LodCollapseCostProfiler_H__ - -#include "OgreLodPrerequisites.h" -#include "OgreLodCollapseCost.h" -#include "OgreLodData.h" -#include "OgreLodConfig.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - -class _OgreLodExport LodCollapseCostProfiler : - public LodCollapseCost -{ -public: - LodCollapseCostProfiler(LodProfile& profile, LodCollapseCostPtr& costCalculator) : mProfile(profile), mCostCalculator(costCalculator) {} - void initCollapseCosts(LodData* data) override; - void computeVertexCollapseCost(LodData* data, LodData::Vertex* vertex, Real& collapseCost, LodData::Vertex*& collapseTo) override; - Real computeEdgeCollapseCost(LodData* data, LodData::Vertex* src, LodData::Edge* dstEdge) override; -private: - - struct ProfiledEdge { - LodData::Vertex* dst; - Real cost; - }; - - typedef std::vector HasVertexProfileList; - - HasVertexProfileList mHasProfile; - - typedef std::unordered_multimap ProfileLookup; - ProfileLookup mProfileLookup; - LodProfile mProfile; - - // If an edge doesn't have a profile, this collapsecost algorithm will be used. - LodCollapseCostPtr mCostCalculator; - - void injectProfile(LodData* data); -}; - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/Components/MeshLodGenerator/include/OgreLodCollapseCostQuadric.h b/Components/MeshLodGenerator/include/OgreLodCollapseCostQuadric.h deleted file mode 100644 index 3961bb741d0..00000000000 --- a/Components/MeshLodGenerator/include/OgreLodCollapseCostQuadric.h +++ /dev/null @@ -1,66 +0,0 @@ - -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef _LodCollapseCostQuadric_H__ -#define _LodCollapseCostQuadric_H__ - -#include "OgreLodPrerequisites.h" -#include "OgreLodCollapseCost.h" -#include "OgreLodData.h" -#include "OgreMatrix4.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - -class _OgreLodExport LodCollapseCostQuadric : - public LodCollapseCost -{ -public: - void initCollapseCosts(LodData* data) override; - void updateVertexCollapseCost(LodData* data, LodData::Vertex* vertex) override; - Real computeEdgeCollapseCost(LodData* data, LodData::Vertex* src, LodData::Edge* dstEdge) override; -protected: - - struct TriangleQuadricPlane { - Matrix4 quadric; - }; - std::vector mTrianglePlaneQuadricList; - std::vector mVertexQuadricList; - void computeTrianglePlaneQuadric(LodData* data, size_t triangleID); - void computeVertexQuadric(LodData* data, size_t vertexID); -}; - -} - -#include "OgreHeaderSuffix.h" - -#endif - - diff --git a/Components/MeshLodGenerator/include/OgreLodCollapser.h b/Components/MeshLodGenerator/include/OgreLodCollapser.h deleted file mode 100644 index a6f5b210f1f..00000000000 --- a/Components/MeshLodGenerator/include/OgreLodCollapser.h +++ /dev/null @@ -1,108 +0,0 @@ - -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef _LodCollapser_H__ -#define _LodCollapser_H__ - -#include "OgreLodPrerequisites.h" -#include "OgreLodData.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup MeshLodGenerator -* @{ -*/ -class _OgreLodExport LodCollapser -{ -public: - virtual ~LodCollapser() {} - /// Reduces vertices until vertexCountLimit or collapseCostLimit is reached. - virtual void collapse(LodData* data, LodCollapseCost* cost, LodOutputProvider* output, int vertexCountLimit, Real collapseCostLimit); - - /** - * @brief Returns the last reduced vertex. - * - * You should call this function after generateLodLevels! - * - * @param data This parameter is not used, but this will guarantee that data is alive. - * @param outVec The vector receiving the position of the vertex. - * @return Whether the outVec was changed. If the mesh is reduced at least 1 vertex, then it returns true. - */ - bool _getLastVertexPos(LodData* data, Vector3& outVec); - - /** - * @brief Returns the destination of the edge, which was last reduced. - * - * You should call this function after generateLodLevels! - * - * @param data This parameter is not used, but this will guarantee that data is alive. - * @param outVec The vector receiving the CollapseTo position. - * @return Whether the outVec was changed. If the mesh is reduced at least 1 vertex, then it returns true. - */ - bool _getLastVertexCollapseTo(LodData* data, Vector3& outVec); -protected: - struct CollapsedEdge { - unsigned int srcID; - unsigned int dstID; - unsigned short submeshID; - }; - - typedef std::vector CollapsedEdges; - - /// tmp variable, to overcome allocation on every collapse. - CollapsedEdges tmpCollapsedEdges; - - /// Last reduced vertex. Can be used for debugging purposes. For example the Mesh Lod Editor uses it to select edge. - LodData::Vertex* mLastReducedVertex; - - /// Collapses a single vertex. - void collapseVertex(LodData* data, LodCollapseCost* cost, LodOutputProvider* output, LodData::Vertex* src); - void assertOutdatedCollapseCost(LodData* data, LodCollapseCost* cost, LodData::Vertex* vertex); - void assertValidMesh(LodData* data); - void assertValidVertex(LodData* data, LodData::Vertex* v); - bool hasSrcID(unsigned int srcID, size_t submeshID); - void removeTriangleFromEdges(LodData::Triangle* triangle, LodData::Vertex* skip); - void removeLine(LodData::Line* triangle, LodData::Vertex* skip); - size_t findDstID(unsigned int srcID, size_t submeshID); - void replaceVertexID(LodData::Triangle* triangle, unsigned int oldID, unsigned int newID, LodData::Vertex* dst); - void replaceVertexID(LodData::Line* line, unsigned int oldID, unsigned int newID, LodData::Vertex* dst); -}; -/** @} */ -/** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif - - diff --git a/Components/MeshLodGenerator/include/OgreLodConfig.h b/Components/MeshLodGenerator/include/OgreLodConfig.h deleted file mode 100644 index ec659094c57..00000000000 --- a/Components/MeshLodGenerator/include/OgreLodConfig.h +++ /dev/null @@ -1,181 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef __LogConfig_H_ -#define __LogConfig_H_ - -#include "OgreLodPrerequisites.h" -#include "OgreDistanceLodStrategy.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup MeshLodGenerator -* @{ -*/ -struct _OgreLodExport ProfiledEdge { - Vector3 src; // Vertex identifier - Vector3 dst; // Direction of collapse - Real cost; // Requested collapse cost -}; - -typedef std::vector LodProfile; - -/** - * @brief Structure for automatic Lod configuration. - */ -struct _OgreLodExport LodLevel { - /** - * @brief Type of the reduction. - * - * Note: The vertex count is determined by unique vertices per submesh. - * A mesh may have duplicate vertices with same position. - */ - enum VertexReductionMethod { - /** - * @brief Percentage of vertexes to be removed from each submesh. - * - * Valid range is a number between 0.0 and 1.0 - */ - VRM_PROPORTIONAL, - - /** - * @brief Exact vertex count to be removed from each submesh. - * - * Pass only integers or it will be rounded. - */ - VRM_CONSTANT, - - /** - * @brief Reduces the vertices, until the cost is bigger then the given value. - * - * Collapse cost is equal to the amount of artifact the reduction causes. - * This generates the best Lod output, but the collapse cost depends on implementation. - */ - VRM_COLLAPSE_COST - }; - - /** - * @brief Distance to swap the Lod. - * - * This depends on LodStrategy. - */ - Real distance; - - /** - * @brief Reduction method to use. - * - * @see ProgressiveMeshGenerator::VertexReductionMethod - */ - VertexReductionMethod reductionMethod; - - /** - * @brief The value, which depends on reductionMethod. - */ - Real reductionValue; - - /** - * @brief Set's a mesh as the Lod Level for given distance. - * - * This allows to generate the Lod levels in third party editors. - * The mesh should have the same submeshes, same bones and animations, like the original mesh. - * If you use this parameter, the reduction value and method will be ignored. - * Using manual mesh is less efficient, because it needs separated vertex buffers. - */ - String manualMeshName; - - /** - * @brief This is set by ProgressiveMeshGenerator::build() function. - * - * Use Mesh::getNumLodLevels() for generated Lod count. - */ - size_t outUniqueVertexCount; - - /** - * @brief Whether the Lod level generation was skipped, because it has same vertex count as the previous Lod level. - */ - bool outSkipped; -}; - -struct _OgreLodExport LodConfig { - MeshPtr mesh; /// The mesh which we want to reduce. - LodStrategy* strategy; /// Lod strategy to use. - - typedef std::vector LodLevelList; - LodLevelList levels; /// Info about Lod levels - - LodConfig(MeshPtr & _mesh, LodStrategy * _strategy = DistanceLodBoxStrategy::getSingletonPtr()); - LodConfig(); - - // Helper functions: - void createManualLodLevel(Ogre::Real distance, const String& manualMeshName); - void createGeneratedLodLevel(Ogre::Real distance, - Real reductionValue, - LodLevel::VertexReductionMethod reductionMethod = LodLevel::VRM_PROPORTIONAL); - - struct _OgreLodExport Advanced { - /// Whether you want to process it immediatelly on main thread or you want to use Ogre::WorkQueue. - /// If you use workqueue the generator will return immediately. After processed in background, - /// the LodWorkQueueInjector will inject it in frameEnd event when rendering next frame. - /// Ready LODs can also be injected by calling Root::getSingleton().getWorkQueue()->processMainThreadTasks(). - /// (disabled by default) - bool useBackgroundQueue; - /// If enabled, it allows up to 50% smaller index buffers by storing once shared faces with frame shifting. - /// There is no performance disadvantage! (enabled by default) - bool useCompression; - /// Use vertex normals to improve quality. Bit slower to generate, but it has better quality most of the time. - /// (enabled by default) - bool useVertexNormals; - /// When an edge is collapsed, triangles may be destroyed if they cannot be adjusted to the new vertex. - /// Set this option to true to prevent collapsing edges that will result in destruction of triangles. - bool preventPunchingHoles; - /// When an edge is collapsed, lines may be destroyed if they cannot be adjusted to the new vertex. - /// Set this option to true to prevent collapsing edges that will result in destruction of lines. - bool preventBreakingLines; - /// Faces inside a house can't be seen from far away. Weightening outside allows to remove those internal faces. - /// It makes generation smaller and it is not 100% accurate. Set it to 0.0 to disable. - /// (disabled by default) - Ogre::Real outsideWeight; - /// If outsideWeight is enabled, this will set the angle how deep the algorithm can walk inside the mesh. - /// This value is an acos number between -1 and 1. (by default it is 0 which means 90 degree) - Ogre::Real outsideWalkAngle; - /// If the algorithm makes errors, you can fix it, by adding the edge to the profile. - LodProfile profile; - Advanced(); - } advanced; -}; -/** @} */ -/** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/Components/MeshLodGenerator/include/OgreLodConfigSerializer.h b/Components/MeshLodGenerator/include/OgreLodConfigSerializer.h deleted file mode 100644 index 2f4120da961..00000000000 --- a/Components/MeshLodGenerator/include/OgreLodConfigSerializer.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef __LogConfigSerializer_H_ -#define __LogConfigSerializer_H_ - -#include "OgreLodPrerequisites.h" - -#include "OgreDataStream.h" -#include "OgreSerializer.h" - -namespace Ogre -{ - -class _OgreLodExport LodConfigSerializer : - public Ogre::Serializer -{ - -public: - - LodConfigSerializer(); - - void exportLodConfig(Ogre::LodConfig& config, const Ogre::String& filename, - Endian endianMode = ENDIAN_NATIVE); - void exportLodConfig(Ogre::LodConfig& config, Ogre::DataStreamPtr stream, - Endian endianMode = ENDIAN_NATIVE); - - void importLodConfig(Ogre::LodConfig* config, const Ogre::String& filename); - void importLodConfig(Ogre::LodConfig* config, DataStreamPtr& stream); - -private: - - enum LodConfigChunkID { - LCCID_FILE_HEADER = 0x300, - LCCID_LOD_CONFIG = 0x400, - LCCID_BASIC_INFO = 0x500, - LCCID_LOD_LEVELS = 0x600, - LCCID_ADVANCED_INFO = 0x700, - LCCID_PROFILE = 0x800, - }; - - void readLodConfig(); - void readLodBasicInfo(); - void readLodLevels(); - void readLodAdvancedInfo(); - void readLodProfile(); - - void writeLodConfig(); - size_t calcLodConfigSize(); - void writeLodBasicInfo(); - size_t calcLodBasicInfoSize(); - void writeLodLevels(); - size_t calcLodLevelsSize(); - void writeLodAdvancedInfo(); - size_t calcLodAdvancedInfoSize(); - void writeLodProfile(); - size_t calcLodProfileSize(); - - LodConfig* mLodConfig; -}; -} -#endif \ No newline at end of file diff --git a/Components/MeshLodGenerator/include/OgreLodData.h b/Components/MeshLodGenerator/include/OgreLodData.h deleted file mode 100644 index 7b2675bc892..00000000000 --- a/Components/MeshLodGenerator/include/OgreLodData.h +++ /dev/null @@ -1,219 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef _LodData_H__ -#define _LodData_H__ - -#include "OgreLodPrerequisites.h" -#include "OgreVectorSet.h" -#include "OgreVectorSetImpl.h" -#include "OgreVector.h" -#include "OgreHeaderPrefix.h" - -#include - -#ifndef MESHLOD_QUALITY -/// MESHLOD_QUALITY=1 is fastest processing time. -/// MESHLOD_QUALITY=2 is balanced performance/quality (default) -/// MESHLOD_QUALITY=3 is best quality. -#define MESHLOD_QUALITY 2 -#endif - -namespace Ogre -{ -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup MeshLodGenerator -* @{ -*/ -struct _OgreLodExport LodData { - - static const Real NEVER_COLLAPSE_COST /*= std::numeric_limits::max()*/; - static const Real UNINITIALIZED_COLLAPSE_COST /*= std::numeric_limits::infinity()*/; - - struct Edge; - struct Vertex; - struct Line; - struct Triangle; - struct VertexHash; - struct VertexEqual; - - typedef std::vector VertexList; - typedef std::vector LineList; - typedef std::vector TriangleList; - typedef std::unordered_set UniqueVertexSet; - typedef std::multimap CollapseCostHeap; - - typedef VectorSet VEdges; - typedef VectorSet VLines; - typedef VectorSet VTriangles; - - /// Hash function for UniqueVertexSet. - struct VertexHash { - LodData* mGen; - - VertexHash() : mGen(0) { assert(0); } - VertexHash(LodData* gen) { mGen = gen; } - size_t operator() (const Vertex* v) const; - }; - - /// Equality function for UniqueVertexSet. - struct VertexEqual { - bool operator() (const Vertex* lhs, const Vertex* rhs) const; - }; - - // Directed edge - struct Edge { - Vertex* dst; // destination vertex. (other end of the edge) - Real collapseCost; // cost of the edge. - int refCount; // Reference count on how many triangles are using this edge. The edge will be removed when it gets 0. - - explicit Edge(Vertex* destination); - bool operator== (const Edge& other) const; - Edge& operator= (const Edge& b); - Edge(const Edge& b); - bool operator< (const Edge& other) const; - }; - - struct Vertex { - Vector3 position; - Vector3 normal; - VEdges edges; - VLines lines; - VTriangles triangles; - - Vertex* collapseTo; - bool seam; - CollapseCostHeap::iterator costHeapPosition; /// Iterator pointing to the position in the mCollapseCostSet, which allows fast remove. - - void addEdge(const Edge& edge); - void removeEdge(const Edge& edge); - }; - - struct Line { - Vertex* vertex[2]; - bool isRemoved; - unsigned short submeshID; /// ID of the submesh. Usable with mMesh.getSubMesh() function. - unsigned int vertexID[2]; /// Vertex ID in the buffer associated with the submeshID. - - bool hasVertex(const Vertex* v) const - { - return (v == vertex[0] || v == vertex[1]); - } - - unsigned int getVertexID(const Vertex* v) const; - bool isMalformed(); - }; - - struct Triangle { - Vertex* vertex[3]; - Vector3 normal; - bool isRemoved; - unsigned short submeshID; /// ID of the submesh. Usable with mMesh.getSubMesh() function. - unsigned int vertexID[3]; /// Vertex ID in the buffer associated with the submeshID. - - void computeNormal() - { - normal = Math::calculateBasicFaceNormal(vertex[0]->position, vertex[1]->position, - vertex[2]->position); - } - bool hasVertex(const Vertex* v) const - { - return (v == vertex[0] || v == vertex[1] || v == vertex[2]); - } - - unsigned int getVertexID(const Vertex* v) const; - bool isMalformed(); - }; - - union IndexBufferPointer { - unsigned short* pshort; - unsigned int* pint; - }; - - struct IndexBufferInfo { - size_t indexSize; - size_t indexCount; - IndexBufferPointer buf; /// Used by output providers only! - size_t prevOnlyIndexCount; /// Used by output providers only! - size_t prevIndexCount; /// Used by output providers only! - }; - - typedef std::vector IndexBufferInfoList; - - /// Provides position based vertex lookup. Position is the real identifier of a vertex. - UniqueVertexSet mUniqueVertexSet; - - VertexList mVertexList; - LineList mLineList; - TriangleList mTriangleList; - - /// Makes possible to get the vertices with the smallest collapse cost. - CollapseCostHeap mCollapseCostHeap; - IndexBufferInfoList mIndexBufferInfoList; -#if OGRE_DEBUG_MODE - /** - * @brief The name of the mesh being processed. - * - * This is separate from mMesh in order to allow for access from background threads. - */ - String mMeshName; -#endif - Real mMeshBoundingSphereRadius; - bool mUseVertexNormals; - - template - static size_t getVectorIDFromPointer(const std::vector& vec, const T* pointer) { - size_t id = pointer - &vec.at(0); - OgreAssertDbg(id < vec.size() && (&vec[id] == pointer), "Invalid pointer"); - return id; - } - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC - // We know it's safe to pass this pointer to VertexHash because it's not used there yet. -# pragma warning ( push ) -# pragma warning ( disable: 4355 ) -#endif - LodData() : - mUniqueVertexSet((UniqueVertexSet::size_type) 0, - (const UniqueVertexSet::hasher&) VertexHash(this)), - mMeshBoundingSphereRadius(0.0f), - mUseVertexNormals(true) - {} -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -# pragma warning ( pop ) -#endif -}; -/** @} */ -/** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/Components/MeshLodGenerator/include/OgreLodInputProvider.h b/Components/MeshLodGenerator/include/OgreLodInputProvider.h deleted file mode 100644 index d6eb5133b4f..00000000000 --- a/Components/MeshLodGenerator/include/OgreLodInputProvider.h +++ /dev/null @@ -1,73 +0,0 @@ - -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef _LodInputProvider_H__ -#define _LodInputProvider_H__ - -#include "OgreLodPrerequisites.h" -#include "OgreLodData.h" - -namespace Ogre -{ - -class _OgreLodExport LodInputProvider { -public: - virtual ~LodInputProvider() {} - /// Called when the data should be filled with the input. - virtual void initData(LodData* data); - -protected: - // This helps to find the vertex* in LodData for index buffer indices - typedef std::vector VertexLookupList; - VertexLookupList mSharedVertexLookup; - VertexLookupList mVertexLookup; - - virtual void addVertexData(LodData* data, size_t subMeshIndex) = 0; - virtual const String & getMeshName() = 0; - virtual size_t getMeshSharedVertexCount() = 0; - virtual float getMeshBoundingSphereRadius() = 0; - - virtual size_t getSubMeshCount() = 0; - - virtual bool getSubMeshUseSharedVertices(size_t subMeshIndex) = 0; - virtual size_t getSubMeshOwnVertexCount(size_t subMeshIndex) = 0; - virtual size_t getSubMeshIndexCount(size_t subMeshIndex) = 0; - virtual const IndexData* getSubMeshIndexData(size_t subMeshIndex) const = 0; - virtual RenderOperation::OperationType getSubMeshRenderOp(size_t subMeshIndex) = 0; - -private: - void addIndexData(LodData* data, size_t subMeshIndex); - void tuneContainerSize(LodData* data); - void initialize(LodData* data); -}; - -} -#endif - - diff --git a/Components/MeshLodGenerator/include/OgreLodOutputProvider.h b/Components/MeshLodGenerator/include/OgreLodOutputProvider.h deleted file mode 100644 index bd62a55bd91..00000000000 --- a/Components/MeshLodGenerator/include/OgreLodOutputProvider.h +++ /dev/null @@ -1,95 +0,0 @@ - -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef _LodOutputProvider_H__ -#define _LodOutputProvider_H__ - -#include "OgreLodPrerequisites.h" -#include "OgreLodData.h" -#include "OgreHardwareIndexBuffer.h" - -namespace Ogre -{ - -class _OgreLodExport LodOutputProvider { -public: - LodOutputProvider(bool useCompression = false); - virtual ~LodOutputProvider() {} - virtual void prepare(LodData* data); - virtual void finalize(LodData* data); - virtual void bakeManualLodLevel(LodData* data, String& manualMeshName, int lodIndex); - virtual void bakeLodLevel(LodData* data, int lodIndex); - virtual void triangleRemoved(LodData* data, LodData::Triangle* tri); - virtual void triangleChanged(LodData* data, LodData::Triangle* tri); - virtual void lineRemoved(LodData* data, LodData::Line* tri); - virtual void lineChanged(LodData* data, LodData::Line* tri); - virtual void inject(){} - -protected: - bool mUseCompression; - - struct TriangleCache { - unsigned int vertexID[3]; - bool vertexChanged; - }; - struct LineCache { - unsigned int vertexID[2]; - bool vertexChanged; - }; - - typedef std::vector TriangleCacheList; - typedef std::vector LineCacheList; - - /// First pass will create the mTriangleCacheList and second pass will use it. - /// This is required, because the triangles from first pass will be changed and we need to keep the information. - TriangleCacheList mTriangleCacheList; - LineCacheList mLineCacheList; - - bool mFirstBufferPass; - int mLastIndexBufferID; - - void bakeUncompressed(LodData* data, int lodIndex); - void bakeFirstPass(LodData* data, int lodIndex); - void bakeSecondPass(LodData* data, int lodIndex); - - - // TODO: remove implementation and make pure virtual. These are just to make the compressed version work. - virtual size_t getSubMeshCount() { return 0; } // = 0; - - HardwareIndexBufferPtr createIndexBuffer(size_t indexCount); - // TODO: remove implementation and make pure virtual. These are just to make the compressed version work. - virtual HardwareIndexBufferPtr createIndexBufferImpl(size_t indexCount) { return nullptr; } // = 0; - - // TODO: remove implementation and make pure virtual. These are just to make the compressed version work. - virtual void createSubMeshLodIndexData(size_t subMeshIndex, int lodIndex, const HardwareIndexBufferPtr & indexBuffer, size_t indexStart, size_t indexCount) {} // = 0; -}; -} -#endif - - diff --git a/Components/MeshLodGenerator/include/OgreLodOutsideMarker.h b/Components/MeshLodGenerator/include/OgreLodOutsideMarker.h deleted file mode 100644 index 29164eedb98..00000000000 --- a/Components/MeshLodGenerator/include/OgreLodOutsideMarker.h +++ /dev/null @@ -1,139 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OutsideMarker_H__ -#define __OutsideMarker_H__ - -#include "OgreLodPrerequisites.h" -#include "OgreLodData.h" -#include "OgreResourceGroupManager.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup MeshLodGenerator -* @{ -*/ -/// This class will mark vertices of a mesh, which are visible from far away (from outside). -/// Triangle is visible if each vertex of it is visible. -class _OgreLodExport LodOutsideMarker -{ -public: - /** - * @param vertexList List of vertices. vertex.position is the input and vertex.isOuterWallVertex is the output of the algorithm. - * @param boundingSphereRadius - * @param walkAngle Walk angle in dot product values. Allowed range is from -1 to 1. Default = 0. Smaller value is bigger angle. - * If you set it to 1 then you can disable walking and it will only mark the vertices on the convex hull. - */ - LodOutsideMarker(LodData::VertexList & vertexList, Real boundingSphereRadius, Real walkAngle); - void markOutside(); /// Mark vertices, which are visible from outside. - MeshPtr createConvexHullMesh(const String& meshName, - const String& resourceGroupName = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); /// Returns a mesh containing the Convex Hull shape. - - bool isVertexOutside(LodData::Vertex* v) { - return getOutsideData(v)->isOuterWallVertex; - } - -private: - typedef LodData::Vertex CHVertex; - - struct CHTriangle { - bool removed; // Whether the triangle is excluded from hull. - CHVertex* vertex[3]; - Vector3 normal; - void computeNormal() - { - normal = Math::calculateBasicFaceNormal(vertex[0]->position, vertex[1]->position, - vertex[2]->position); - } - }; - - - struct OutsideData - { - bool isOuterWallVertex; - bool isOuterWallVertexInPass; - bool isInsideHull; - }; - - typedef std::vector OutsideDataList; - typedef std::vector CHTriangleList; - typedef std::vector CHTrianglePList; - typedef std::vector > CHEdgeList; - - - - - const Real mEpsilon; /// Amount of allowed floating point error if 4 vertices are on the same plane. - CHTriangleList mHull; /// Contains the current triangles of the convex hull. - CHTrianglePList mVisibleTriangles; /// Temporary vector for addVisibleEdges function (prevent allocation every call). - CHEdgeList mEdges; /// Temporary vector for the horizon edges, when inserting a new vertex into the hull. - LodData::VertexList& mVertexListOrig; /// Source of input and output of the algorithm. - - OutsideDataList mOutsideData; - Vector3 mCentroid; /// Centroid of the convex hull. - Real mWalkAngle; /// Angle limit, when walking inside for marking vertices. - - LodData::Vertex* getVertex(OutsideData* d) { - return &mVertexListOrig[LodData::getVectorIDFromPointer(mOutsideData, d)]; - } - OutsideData* getOutsideData(LodData::Vertex* v) { - return &mOutsideData[LodData::getVectorIDFromPointer(mVertexListOrig, v)]; - } - - void initHull(); /// Initializes the hull for expansion. - void createTriangle(CHVertex* v1, CHVertex* v2, CHVertex* v3); /// Sets the vertices of a triangle (called from initHull only). - Real getTetrahedronVolume(CHVertex* v0, CHVertex* v1, CHVertex* v2, CHVertex* v3); - Real getPointToLineSqraredDistance(CHVertex* x1, CHVertex* x2, CHVertex* vertex); - void generateHull(); /// Generates the hull. - size_t addVertex(CHVertex* vertex); /// Adds vertex to hull. - void addEdge(CHEdgeList& edges, CHVertex* a, CHVertex* b); /// Add edge to the list of removable edges. - void cleanHull(); /// Removes Triangles, which are having CHTriangle::removed = true. - bool isVisible(CHTriangle* triangle, Vector3& vertex); /// Whether face is visible from point. - CHVertex* getFurthestVertex(CHTriangle* hull); /// Gets furthest vertex from face. - void getVisibleTriangles(const CHVertex* target, CHTrianglePList& visibleTriangles); /// Adds visible edges to the list, when viewing from target point. - void getHorizon(const CHTrianglePList& tri, CHEdgeList& ); /// Removes edges, which are not on the horizon. - void fillHorizon(CHEdgeList& e, CHVertex* target); /// Caps the hole with faces connecting to target vertex. - void markVertices(); /// if we have the convex hull, this will walk on the faces which have less then 90 degree difference. - template - void addHullTriangleVertices(std::vector& stack, T tri); /// Add triangle to stack (called from markVertices only). - /// Determines whether ptarget is on the same side of the p0-p1 line as p2. Assuming each point is on the same plane. - Real pointToLineDir(const Vector3& ptarget, const Vector3& p0, const Vector3& p1, const Vector3& p2, const Vector3& n); - bool isInsideTriangle(const Vector3& ptarget, const CHTriangle& tri); /// Whether the vertex is inside the triangle. We assume that it is on the same plane - bool isInsideLine(const Vector3& ptarget, const Vector3& p0, const Vector3& p1); /// Whether ptarget is between p0 and p1. Assuming they are on the same line. - bool isSamePosition(const Vector3& p0, const Vector3& p1); /// Whether p0 = p1 with mEpsilon allowed float error. -}; -/** @} */ -/** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif /* ifndef __OutsideMarker_H__ */ diff --git a/Components/MeshLodGenerator/include/OgreLodPrerequisites.h b/Components/MeshLodGenerator/include/OgreLodPrerequisites.h deleted file mode 100644 index ca059bacc3e..00000000000 --- a/Components/MeshLodGenerator/include/OgreLodPrerequisites.h +++ /dev/null @@ -1,91 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef _LodPrerequisites_H__ -#define _LodPrerequisites_H__ - -#include "OgrePrerequisites.h" - -namespace Ogre -{ - // forward decls - class LodCollapseCost; - class LodCollapseCostCurvature; - class LodCollapseCostOutside; - class LodCollapseCostProfiler; - - class LodInputProvider; - class LodInputProviderMesh; - class LodInputProviderBuffer; - class LodOutputProvider; - class LodOutputProviderMesh; - class LodOutputProviderBuffer; - class LodOutsideMarker; - - - class LodCollapser; - struct LodConfig; - struct LodLevel; - class LodConfigSerializer; - class MeshLodGenerator; - class LodWorkQueueWorker; - class LodWorkQueueInjector; - struct LodWorkQueueRequest; - class LodWorkQueueInjectorListener; - struct LodData; - - typedef shared_ptr LodCollapseCostPtr; - typedef shared_ptr LodCollapserPtr; - typedef shared_ptr LodDataPtr; - typedef shared_ptr LodInputProviderPtr; - typedef shared_ptr LodOutputProviderPtr; - - typedef GeneralAllocatedObject MeshLodAlloc; -} - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT -# if defined( OGRE_STATIC_LIB ) -# define _OgreLodExport -# else -# if defined( OGRE_MESHLODGENERATOR_EXPORTS ) -# define _OgreLodExport __declspec( dllexport ) -# else -# if defined( __MINGW32__ ) -# define _OgreLodExport -# else -# define _OgreLodExport __declspec( dllimport ) -# endif -# endif -# endif -#elif defined ( OGRE_GCC_VISIBILITY ) -# define _OgreLodExport __attribute__ ((visibility("default"))) -#else -# define _OgreLodExport -#endif - -#endif diff --git a/Components/MeshLodGenerator/include/OgreLodWorkQueueInjectorListener.h b/Components/MeshLodGenerator/include/OgreLodWorkQueueInjectorListener.h deleted file mode 100644 index c787c567f63..00000000000 --- a/Components/MeshLodGenerator/include/OgreLodWorkQueueInjectorListener.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef _LodWorkQueueInjectorListener_H__ -#define _LodWorkQueueInjectorListener_H__ - -#include "OgreLodPrerequisites.h" - -namespace Ogre -{ - -class _OgreLodExport LodWorkQueueInjectorListener -{ -public: - LodWorkQueueInjectorListener(){} - virtual ~LodWorkQueueInjectorListener(){} - virtual bool shouldInject(LodWorkQueueRequest* request) = 0; - virtual void injectionCompleted(LodWorkQueueRequest* request) = 0; -}; - -} -#endif diff --git a/Components/MeshLodGenerator/include/OgreMeshLodGenerator.h b/Components/MeshLodGenerator/include/OgreMeshLodGenerator.h deleted file mode 100644 index b916b0ade7f..00000000000 --- a/Components/MeshLodGenerator/include/OgreMeshLodGenerator.h +++ /dev/null @@ -1,118 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef __MeshLodGenerator_H_ -#define __MeshLodGenerator_H_ - -#include "OgreLodPrerequisites.h" -#include "OgreLodConfig.h" -#include "OgreLodData.h" -#include "OgreLodInputProvider.h" -#include "OgreLodOutputProvider.h" -#include "OgreLodCollapseCost.h" -#include "OgreLodCollapser.h" -#include "OgreSharedPtr.h" -#include "OgreSingleton.h" -#include "OgreWorkQueue.h" - -namespace Ogre -{ - -/** \addtogroup Optional -* @{ -*/ -/** \defgroup MeshLodGenerator MeshLodGenerator -* Generate Low-poly models from High-poly models automatically -* @{ -*/ - -class _OgreLodExport MeshLodGenerator : -public Singleton -{ -public: - - static MeshLodGenerator* getSingletonPtr(); - static MeshLodGenerator& getSingleton(); - - /** - * @brief Generates the Lod levels for a mesh. - */ - MeshLodGenerator(); - virtual ~MeshLodGenerator(); - - /** - * @brief Generates the Lod levels for a mesh. - */ - virtual void generateLodLevels(LodConfig& lodConfig, LodCollapseCostPtr cost = LodCollapseCostPtr(), LodDataPtr data = LodDataPtr(), LodInputProviderPtr input = LodInputProviderPtr(), LodOutputProviderPtr output = LodOutputProviderPtr(), LodCollapserPtr collapser = LodCollapserPtr()); - - /** - * @brief Generates the Lod levels for a mesh without configuring it. - * - * @param mesh Generate the Lod for this mesh. - */ - void generateAutoconfiguredLodLevels(MeshPtr& mesh); - - /** - * @brief Fills Lod Config with a config, which works on any mesh. - * - * @param inMesh Optimize for this mesh. - * @param outLodConfig Lod configuration storing the output. - */ - void getAutoconfig(MeshPtr& inMesh, LodConfig& outLodConfig); - - void clearPendingLodRequests(); - - static void _configureMeshLodUsage(const LodConfig& lodConfig); - void _resolveComponents(LodConfig& lodConfig, LodCollapseCostPtr& cost, LodDataPtr& data, LodInputProviderPtr& input, LodOutputProviderPtr& output, LodCollapserPtr& collapser); - - /// If you only use manual Lod levels, then you don't need to build LodData mesh representation. - /// This function will generate manual Lod levels without overhead, but every Lod level needs to be a manual Lod level. - void _generateManualLodLevels(LodConfig& lodConfig); - - void setInjectorListener(LodWorkQueueInjectorListener* injectorListener) {mInjectorListener = injectorListener;} - LodWorkQueueInjectorListener* getInjectorListener() {return mInjectorListener;} - void removeInjectorListener() {mInjectorListener = 0;} -private: - void _process(LodConfig& lodConfig, LodCollapseCost* cost, LodData* data, LodInputProvider* input, LodOutputProvider* output, LodCollapser* collapser); - - void computeLods(LodConfig& lodConfig, LodData* data, LodCollapseCost* cost, LodOutputProvider* output, LodCollapser* collapser); - void calcLodVertexCount(const LodLevel& lodLevel, size_t uniqueVertexCount, size_t& outVertexCountLimit, Real& outCollapseCostLimit); - - OGRE_WQ_MUTEX(mQueueMutex); - std::list mPendingLodRequests; - - LodWorkQueueInjectorListener* mInjectorListener; - - void addRequestToQueue(LodConfig& lodConfig, LodCollapseCostPtr& cost, LodDataPtr& data, LodInputProviderPtr& input, LodOutputProviderPtr& output, LodCollapserPtr& collapser); - WorkQueue::Response* handleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ); - void handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ); -}; -/** @} */ -/** @} */ -} -#endif diff --git a/Components/MeshLodGenerator/include/OgreSmallVector.h b/Components/MeshLodGenerator/include/OgreSmallVector.h deleted file mode 100644 index be79bd066ec..00000000000 --- a/Components/MeshLodGenerator/include/OgreSmallVector.h +++ /dev/null @@ -1,790 +0,0 @@ -//===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. -// ============================================================================== -// LLVM Release License -// ============================================================================== -// University of Illinois/NCSA -// Open Source License -// -// Copyright (c) 2003-2010 University of Illinois at Urbana-Champaign. -// All rights reserved. -// -// Developed by: -// -// LLVM Team -// -// University of Illinois at Urbana-Champaign -// -// http://llvm.org -// -// Permission is hereby granted, free of charge, to any person obtaining a copy of -// this software and associated documentation files (the "Software"), to deal with -// the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -// of the Software, and to permit persons to whom the Software is furnished to do -// so, subject to the following conditions: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimers. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimers in the -// documentation and/or other materials provided with the distribution. -// -// * Neither the names of the LLVM Team, University of Illinois at -// Urbana-Champaign, nor the names of its contributors may be used to -// endorse or promote products derived from this Software without specific -// prior written permission. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE -// SOFTWARE. -// -//===----------------------------------------------------------------------===// -// -// This file defines the SmallVector class. -// -//===----------------------------------------------------------------------===// - -#ifndef __SmallVector_H -#define __SmallVector_H - -#include -#include -#include -#include -#include -#include -#include - -namespace Ogre { - - // some type traits - template struct isPodLike { static const bool value = false; }; - - template <> struct isPodLike { static const bool value = true; }; - template <> struct isPodLike { static const bool value = true; }; - template <> struct isPodLike { static const bool value = true; }; - template <> struct isPodLike { static const bool value = true; }; - template <> struct isPodLike { static const bool value = true; }; - template <> struct isPodLike { static const bool value = true; }; - template <> struct isPodLike { static const bool value = true; }; - template <> struct isPodLike { static const bool value = true; }; - template <> struct isPodLike { static const bool value = true; }; - template <> struct isPodLike { static const bool value = true; }; - template <> struct isPodLike { static const bool value = true; }; - template <> struct isPodLike { static const bool value = true; }; - template struct isPodLike { static const bool value = true; }; - - template - struct isPodLike > { static const bool value = isPodLike::value & isPodLike::value; }; - - /// SmallVectorBase - This is all the non-templated stuff common to all - /// SmallVectors. - class SmallVectorBase { - protected: - void *BeginX, *EndX, *CapacityX; - - // Allocate raw space for N elements of type T. If T has a ctor or dtor, we - // don't want it to be automatically run, so we need to represent the space as - // something else. An array of char would work great, but might not be - // aligned sufficiently. Instead we use some number of union instances for - // the space, which guarantee maximal alignment. - union U { - double D; - long double LD; - long long L; - void *P; - } FirstEl; - // Space after 'FirstEl' is clobbered, do not add any instance vars after it. - - protected: - SmallVectorBase(size_t Size) - : BeginX(&FirstEl), EndX(&FirstEl), CapacityX((char*)&FirstEl+Size) {} - - /// isSmall - Return true if this is a smallvector which has not had dynamic - /// memory allocated for it. - bool isSmall() const { - return BeginX == static_cast(&FirstEl); - } - - /// size_in_bytes - This returns size()*sizeof(T). - size_t size_in_bytes() const { - return size_t((char*)EndX - (char*)BeginX); - } - - /// capacity_in_bytes - This returns capacity()*sizeof(T). - size_t capacity_in_bytes() const { - return size_t((char*)CapacityX - (char*)BeginX); - } - - /// grow_pod - This is an implementation of the grow() method which only works - /// on POD-like data types and is out of line to reduce code duplication. - void grow_pod(size_t MinSizeInBytes, size_t TSize); - - public: - bool empty() const { return BeginX == EndX; } - }; - - - template - class SmallVectorTemplateCommon : public SmallVectorBase { - protected: - void setEnd(T *P) { this->EndX = P; } - public: - SmallVectorTemplateCommon(size_t Size) : SmallVectorBase(Size) {} - - typedef size_t size_type; - typedef ptrdiff_t difference_type; - typedef T value_type; - typedef T *iterator; - typedef const T *const_iterator; - - typedef std::reverse_iterator const_reverse_iterator; - typedef std::reverse_iterator reverse_iterator; - - typedef T &reference; - typedef const T &const_reference; - typedef T *pointer; - typedef const T *const_pointer; - - // forward iterator creation methods. - iterator begin() { return (iterator)this->BeginX; } - const_iterator begin() const { return (const_iterator)this->BeginX; } - iterator end() { return (iterator)this->EndX; } - const_iterator end() const { return (const_iterator)this->EndX; } - protected: - iterator capacity_ptr() { return (iterator)this->CapacityX; } - const_iterator capacity_ptr() const { return (const_iterator)this->CapacityX;} - public: - - // reverse iterator creation methods. - reverse_iterator rbegin() { return reverse_iterator(end()); } - const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); } - reverse_iterator rend() { return reverse_iterator(begin()); } - const_reverse_iterator rend() const { return const_reverse_iterator(begin());} - - size_type size() const { return end()-begin(); } - size_type max_size() const { return size_type(-1) / sizeof(T); } - - /// capacity - Return the total number of elements in the currently allocated - /// buffer. - size_t capacity() const { return capacity_ptr() - begin(); } - - /// data - Return a pointer to the vector's buffer, even if empty(). - pointer data() { return pointer(begin()); } - /// data - Return a pointer to the vector's buffer, even if empty(). - const_pointer data() const { return const_pointer(begin()); } - - reference operator[](unsigned idx) { - assert(begin() + idx < end()); - return begin()[idx]; - } - const_reference operator[](unsigned idx) const { - assert(begin() + idx < end()); - return begin()[idx]; - } - - reference front() { - return begin()[0]; - } - const_reference front() const { - return begin()[0]; - } - - reference back() { - return end()[-1]; - } - const_reference back() const { - return end()[-1]; - } - }; - - /// SmallVectorTemplateBase - This is where we put method - /// implementations that are designed to work with non-POD-like T's. - template - class SmallVectorTemplateBase : public SmallVectorTemplateCommon { - public: - SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon(Size) {} - - static void destroy_range(T *S, T *E) { - while (S != E) { - --E; - E->~T(); - } - } - - /// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory - /// starting with "Dest", constructing elements into it as needed. - template - static void uninitialized_copy(It1 I, It1 E, It2 Dest) { - std::uninitialized_copy(I, E, Dest); - } - - /// grow - double the size of the allocated memory, guaranteeing space for at - /// least one more element or MinSize if specified. - void grow(size_t MinSize = 0); - }; - - // Define this out-of-line to dissuade the C++ compiler from inlining it. - template - void SmallVectorTemplateBase::grow(size_t MinSize) { - size_t CurCapacity = this->capacity(); - size_t CurSize = this->size(); - size_t NewCapacity = 2*CurCapacity + 1; // Always grow, even from zero. - if (NewCapacity < MinSize) - NewCapacity = MinSize; - T *NewElts = static_cast(malloc(NewCapacity*sizeof(T))); - - // Copy the elements over. - this->uninitialized_copy(this->begin(), this->end(), NewElts); - - // Destroy the original elements. - destroy_range(this->begin(), this->end()); - - // If this wasn't grown from the inline copy, deallocate the old space. - if (!this->isSmall()) - free(this->begin()); - - this->setEnd(NewElts+CurSize); - this->BeginX = NewElts; - this->CapacityX = this->begin()+NewCapacity; - } - - - /// SmallVectorTemplateBase - This is where we put method - /// implementations that are designed to work with POD-like T's. - template - class SmallVectorTemplateBase : public SmallVectorTemplateCommon { - public: - SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon(Size) {} - - // No need to do a destroy loop for POD's. - static void destroy_range(T *, T *) {} - - /// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory - /// starting with "Dest", constructing elements into it as needed. - template - static void uninitialized_copy(It1 I, It1 E, It2 Dest) { - // Arbitrary iterator types; just use the basic implementation. - std::uninitialized_copy(I, E, Dest); - } - - /// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory - /// starting with "Dest", constructing elements into it as needed. - template - static void uninitialized_copy(T1 *I, T1 *E, T2 *Dest) { - // Use memcpy for PODs iterated by pointers (which includes SmallVector - // iterators): std::uninitialized_copy optimizes to memmove, but we can - // use memcpy here. - memcpy(Dest, I, (E-I)*sizeof(T)); - } - - /// grow - double the size of the allocated memory, guaranteeing space for at - /// least one more element or MinSize if specified. - void grow(size_t MinSize = 0) { - this->grow_pod(MinSize*sizeof(T), sizeof(T)); - } - }; - - - /// SmallVectorImpl - This class consists of common code factored out of the - /// SmallVector class to reduce code duplication based on the SmallVector 'N' - /// template parameter. - template - class SmallVectorImpl : public SmallVectorTemplateBase::value> { - typedef SmallVectorTemplateBase::value > SuperClass; - - SmallVectorImpl(const SmallVectorImpl&); // DISABLED. - public: - typedef typename SuperClass::iterator iterator; - typedef typename SuperClass::size_type size_type; - - // Default ctor - Initialize to empty. - explicit SmallVectorImpl(unsigned N) - : SmallVectorTemplateBase::value>(N*sizeof(T)) { - } - - ~SmallVectorImpl() { - // Destroy the constructed elements in the vector. - this->destroy_range(this->begin(), this->end()); - - // If this wasn't grown from the inline copy, deallocate the old space. - if (!this->isSmall()) - free(this->begin()); - } - - - void clear() { - this->destroy_range(this->begin(), this->end()); - this->EndX = this->BeginX; - } - - void resize(unsigned N) { - if (N < this->size()) { - this->destroy_range(this->begin()+N, this->end()); - this->setEnd(this->begin()+N); - } else if (N > this->size()) { - if (this->capacity() < N) - this->grow(N); - this->construct_range(this->end(), this->begin()+N, T()); - this->setEnd(this->begin()+N); - } - } - - void resize(unsigned N, const T &NV) { - if (N < this->size()) { - this->destroy_range(this->begin()+N, this->end()); - this->setEnd(this->begin()+N); - } else if (N > this->size()) { - if (this->capacity() < N) - this->grow(N); - construct_range(this->end(), this->begin()+N, NV); - this->setEnd(this->begin()+N); - } - } - - void reserve(unsigned N) { - if (this->capacity() < N) - this->grow(N); - } - - void push_back(const T &Elt) { - if (this->EndX < this->CapacityX) { - Retry: - new (this->end()) T(Elt); - this->setEnd(this->end()+1); - return; - } - this->grow(); - goto Retry; - } - - void pop_back() { - this->setEnd(this->end()-1); - this->end()->~T(); - } - - T pop_back_val() { - T Result = this->back(); - pop_back(); - return Result; - } - - void swap(SmallVectorImpl &RHS); - - /// append - Add the specified range to the end of the SmallVector. - /// - template - void append(in_iter in_start, in_iter in_end) { - size_type NumInputs = std::distance(in_start, in_end); - // Grow allocated space if needed. - if (NumInputs > size_type(this->capacity_ptr()-this->end())) - this->grow(this->size()+NumInputs); - - // Copy the new elements over. - // TODO: NEED To compile time dispatch on whether in_iter is a random access - // iterator to use the fast uninitialized_copy. - std::uninitialized_copy(in_start, in_end, this->end()); - this->setEnd(this->end() + NumInputs); - } - - /// append - Add the specified range to the end of the SmallVector. - /// - void append(size_type NumInputs, const T &Elt) { - // Grow allocated space if needed. - if (NumInputs > size_type(this->capacity_ptr()-this->end())) - this->grow(this->size()+NumInputs); - - // Copy the new elements over. - std::uninitialized_fill_n(this->end(), NumInputs, Elt); - this->setEnd(this->end() + NumInputs); - } - - void assign(unsigned NumElts, const T &Elt) { - clear(); - if (this->capacity() < NumElts) - this->grow(NumElts); - this->setEnd(this->begin()+NumElts); - construct_range(this->begin(), this->end(), Elt); - } - - iterator erase(iterator I) { - iterator N = I; - // Shift all elts down one. - std::copy(I+1, this->end(), I); - // Drop the last elt. - pop_back(); - return(N); - } - - iterator erase(iterator S, iterator E) { - iterator N = S; - // Shift all elts down. - iterator I = std::copy(E, this->end(), S); - // Drop the last elts. - this->destroy_range(I, this->end()); - this->setEnd(I); - return(N); - } - - iterator insert(iterator I, const T &Elt) { - if (I == this->end()) { // Important special case for empty vector. - push_back(Elt); - return this->end()-1; - } - - if (this->EndX < this->CapacityX) { - Retry: - new (this->end()) T(this->back()); - this->setEnd(this->end()+1); - // Push everything else over. - std::copy_backward(I, this->end()-1, this->end()); - *I = Elt; - return I; - } - size_t EltNo = I-this->begin(); - this->grow(); - I = this->begin()+EltNo; - goto Retry; - } - - iterator insert(iterator I, size_type NumToInsert, const T &Elt) { - if (I == this->end()) { // Important special case for empty vector. - append(NumToInsert, Elt); - return this->end()-1; - } - - // Convert iterator to elt# to avoid invalidating iterator when we reserve() - size_t InsertElt = I - this->begin(); - - // Ensure there is enough space. - reserve(static_cast(this->size() + NumToInsert)); - - // Uninvalidate the iterator. - I = this->begin()+InsertElt; - - // If there are more elements between the insertion point and the end of the - // range than there are being inserted, we can use a simple approach to - // insertion. Since we already reserved space, we know that this won't - // reallocate the vector. - if (size_t(this->end()-I) >= NumToInsert) { - T *OldEnd = this->end(); - append(this->end()-NumToInsert, this->end()); - - // Copy the existing elements that get replaced. - std::copy_backward(I, OldEnd-NumToInsert, OldEnd); - - std::fill_n(I, NumToInsert, Elt); - return I; - } - - // Otherwise, we're inserting more elements than exist already, and we're - // not inserting at the end. - - // Copy over the elements that we're about to overwrite. - T *OldEnd = this->end(); - this->setEnd(this->end() + NumToInsert); - size_t NumOverwritten = OldEnd-I; - this->uninitialized_copy(I, OldEnd, this->end()-NumOverwritten); - - // Replace the overwritten part. - std::fill_n(I, NumOverwritten, Elt); - - // Insert the non-overwritten middle part. - std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt); - return I; - } - - template - iterator insert(iterator I, ItTy From, ItTy To) { - if (I == this->end()) { // Important special case for empty vector. - append(From, To); - return this->end()-1; - } - - size_t NumToInsert = std::distance(From, To); - // Convert iterator to elt# to avoid invalidating iterator when we reserve() - size_t InsertElt = I - this->begin(); - - // Ensure there is enough space. - reserve(static_cast(this->size() + NumToInsert)); - - // Uninvalidate the iterator. - I = this->begin()+InsertElt; - - // If there are more elements between the insertion point and the end of the - // range than there are being inserted, we can use a simple approach to - // insertion. Since we already reserved space, we know that this won't - // reallocate the vector. - if (size_t(this->end()-I) >= NumToInsert) { - T *OldEnd = this->end(); - append(this->end()-NumToInsert, this->end()); - - // Copy the existing elements that get replaced. - std::copy_backward(I, OldEnd-NumToInsert, OldEnd); - - std::copy(From, To, I); - return I; - } - - // Otherwise, we're inserting more elements than exist already, and we're - // not inserting at the end. - - // Copy over the elements that we're about to overwrite. - T *OldEnd = this->end(); - this->setEnd(this->end() + NumToInsert); - size_t NumOverwritten = OldEnd-I; - this->uninitialized_copy(I, OldEnd, this->end()-NumOverwritten); - - // Replace the overwritten part. - for (; NumOverwritten > 0; --NumOverwritten) { - *I = *From; - ++I; ++From; - } - - // Insert the non-overwritten middle part. - this->uninitialized_copy(From, To, OldEnd); - return I; - } - - const SmallVectorImpl - &operator=(const SmallVectorImpl &RHS); - - bool operator==(const SmallVectorImpl &RHS) const { - if (this->size() != RHS.size()) return false; - return std::equal(this->begin(), this->end(), RHS.begin()); - } - bool operator!=(const SmallVectorImpl &RHS) const { - return !(*this == RHS); - } - - bool operator<(const SmallVectorImpl &RHS) const { - return std::lexicographical_compare(this->begin(), this->end(), - RHS.begin(), RHS.end()); - } - - /// set_size - Set the array size to \arg N, which the current array must have - /// enough capacity for. - /// - /// This does not construct or destroy any elements in the vector. - /// - /// Clients can use this in conjunction with capacity() to write past the end - /// of the buffer when they know that more elements are available, and only - /// update the size later. This avoids the cost of value initializing elements - /// which will only be overwritten. - void set_size(unsigned N) { - assert(N <= this->capacity()); - this->setEnd(this->begin() + N); - } - - private: - static void construct_range(T *S, T *E, const T &Elt) { - for (; S != E; ++S) - new (S) T(Elt); - } - }; - - - template - void SmallVectorImpl::swap(SmallVectorImpl &RHS) { - if (this == &RHS) return; - - // We can only avoid copying elements if neither vector is small. - if (!this->isSmall() && !RHS.isSmall()) { - std::swap(this->BeginX, RHS.BeginX); - std::swap(this->EndX, RHS.EndX); - std::swap(this->CapacityX, RHS.CapacityX); - return; - } - if (RHS.size() > this->capacity()) - this->grow(RHS.size()); - if (this->size() > RHS.capacity()) - RHS.grow(this->size()); - - // Swap the shared elements. - size_t NumShared = this->size(); - if (NumShared > RHS.size()) NumShared = RHS.size(); - for (unsigned i = 0; i != static_cast(NumShared); ++i) - std::swap((*this)[i], RHS[i]); - - // Copy over the extra elts. - if (this->size() > RHS.size()) { - size_t EltDiff = this->size() - RHS.size(); - this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end()); - RHS.setEnd(RHS.end()+EltDiff); - this->destroy_range(this->begin()+NumShared, this->end()); - this->setEnd(this->begin()+NumShared); - } else if (RHS.size() > this->size()) { - size_t EltDiff = RHS.size() - this->size(); - this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end()); - this->setEnd(this->end() + EltDiff); - this->destroy_range(RHS.begin()+NumShared, RHS.end()); - RHS.setEnd(RHS.begin()+NumShared); - } - } - - template - const SmallVectorImpl &SmallVectorImpl:: - operator=(const SmallVectorImpl &RHS) { - // Avoid self-assignment. - if (this == &RHS) return *this; - - // If we already have sufficient space, assign the common elements, then - // destroy any excess. - size_t RHSSize = RHS.size(); - size_t CurSize = this->size(); - if (CurSize >= RHSSize) { - // Assign common elements. - iterator NewEnd; - if (RHSSize) - NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin()); - else - NewEnd = this->begin(); - - // Destroy excess elements. - this->destroy_range(NewEnd, this->end()); - - // Trim. - this->setEnd(NewEnd); - return *this; - } - - // If we have to grow to have enough elements, destroy the current elements. - // This allows us to avoid copying them during the grow. - if (this->capacity() < RHSSize) { - // Destroy current elements. - this->destroy_range(this->begin(), this->end()); - this->setEnd(this->begin()); - CurSize = 0; - this->grow(RHSSize); - } else if (CurSize) { - // Otherwise, use assignment for the already-constructed elements. - std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin()); - } - - // Copy construct the new elements in place. - this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(), - this->begin()+CurSize); - - // Set end. - this->setEnd(this->begin()+RHSSize); - return *this; - } - - - /// SmallVector - This is a 'vector' (really, a variable-sized array), optimized - /// for the case when the array is small. It contains some number of elements - /// in-place, which allows it to avoid heap allocation when the actual number of - /// elements is below that threshold. This allows normal "small" cases to be - /// fast without losing generality for large inputs. - /// - /// Note that this does not attempt to be exception safe. - /// - template - class SmallVector : public SmallVectorImpl { - /// InlineElts - These are 'N-1' elements that are stored inline in the body - /// of the vector. The extra '1' element is stored in SmallVectorImpl. - typedef typename SmallVectorImpl::U U; - enum { - // MinUs - The number of U's require to cover N T's. - MinUs = (static_cast(sizeof(T))*N + - static_cast(sizeof(U)) - 1) / - static_cast(sizeof(U)), - - // NumInlineEltsElts - The number of elements actually in this array. There - // is already one in the parent class, and we have to round up to avoid - // having a zero-element array. - NumInlineEltsElts = MinUs > 1 ? (MinUs - 1) : 1, - - // NumTsAvailable - The number of T's we actually have space for, which may - // be more than N due to rounding. - NumTsAvailable = (NumInlineEltsElts+1)*static_cast(sizeof(U))/ - static_cast(sizeof(T)) - }; - U InlineElts[NumInlineEltsElts]; - public: - SmallVector() : SmallVectorImpl(NumTsAvailable) { - } - - explicit SmallVector(unsigned Size, const T &Value = T()) - : SmallVectorImpl(NumTsAvailable) { - this->reserve(Size); - while (Size--) - this->push_back(Value); - } - - template - SmallVector(ItTy S, ItTy E) : SmallVectorImpl(NumTsAvailable) { - this->append(S, E); - } - - SmallVector(const SmallVector &RHS) : SmallVectorImpl(NumTsAvailable) { - if (!RHS.empty()) - SmallVectorImpl::operator=(RHS); - } - - const SmallVector &operator=(const SmallVector &RHS) { - SmallVectorImpl::operator=(RHS); - return *this; - } - - }; - -/// Specialize SmallVector at N=0. This specialization guarantees -/// that it can be instantiated at an incomplete T if none of its -/// members are required. -template -class SmallVector : public SmallVectorImpl { -public: - SmallVector() : SmallVectorImpl(0) {} - - explicit SmallVector(unsigned Size, const T &Value = T()) - : SmallVectorImpl(0) { - this->reserve(Size); - while (Size--) - this->push_back(Value); - } - - template - SmallVector(ItTy S, ItTy E) : SmallVectorImpl(0) { - this->append(S, E); - } - - SmallVector(const SmallVector &RHS) : SmallVectorImpl(0) { - SmallVectorImpl::operator=(RHS); - } - - SmallVector &operator=(const SmallVectorImpl &RHS) { - return SmallVectorImpl::operator=(RHS); - } - -}; - -} // End Ogre namespace - -namespace std { - /// Implement std::swap in terms of SmallVector swap. - template - inline void - swap(Ogre::SmallVectorImpl &LHS, Ogre::SmallVectorImpl &RHS) { - LHS.swap(RHS); - } - - /// Implement std::swap in terms of SmallVector swap. - template - inline void - swap(Ogre::SmallVector &LHS, Ogre::SmallVector &RHS) { - LHS.swap(RHS); - } -} - -#endif diff --git a/Components/MeshLodGenerator/include/OgreVectorSet.h b/Components/MeshLodGenerator/include/OgreVectorSet.h deleted file mode 100644 index cb2dff877cc..00000000000 --- a/Components/MeshLodGenerator/include/OgreVectorSet.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef _VectorSet_H__ -#define _VectorSet_H__ - -#include "OgreSmallVector.h" - -namespace Ogre -{ - -/// VectorSet is basically a helper to use a vector as a small set container. -/// Also these functions keep the code clean and fast. -/// You can insert in O(1) time, if you know that it doesn't exists. -/// You can remove in O(1) time, if you know the position of the item. -template -struct VectorSet : - public SmallVector -{ - - typedef typename SmallVector::iterator iterator; - - void addNotExists(const T& item); // Complexity: O(1)!! - void remove(iterator it); // Complexity: O(1)!! - iterator add(const T& item); // Complexity: O(N) - void removeExists(const T& item); // Complexity: O(N) - bool remove(const T& item); // Complexity: O(N) - void replaceExists(const T& oldItem, const T& newItem); // Complexity: O(N) - bool has(const T& item); // Complexity: O(N) - iterator find(const T& item); // Complexity: O(N) - iterator findExists(const T& item); // Complexity: O(N) -}; - -} -#endif diff --git a/Components/MeshLodGenerator/include/OgreVectorSetImpl.h b/Components/MeshLodGenerator/include/OgreVectorSetImpl.h deleted file mode 100644 index 93caad3f175..00000000000 --- a/Components/MeshLodGenerator/include/OgreVectorSetImpl.h +++ /dev/null @@ -1,117 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef _VectorSetImpl_H__ -#define _VectorSetImpl_H__ - -#include "OgreVectorSet.h" - -#include "OgreException.h" // for OgreAssert - -namespace Ogre -{ - - template - void VectorSet::addNotExists(const T& item) - { - OgreAssertDbg(find(item) == this->end(), ""); - this->push_back(item); - } - - template - void VectorSet::remove(iterator it) - { - // Thats my trick to remove an item from the vector very fast! - // It works similar to the heap_pop(). - // It swaps the removable item to the back, then pops it. - *it = this->back(); - this->pop_back(); - } - - template - typename VectorSet::iterator VectorSet::add(const T& item) - { - iterator it = find(item); - if (it == this->end()) { - this->push_back(item); - return this->end(); - } - return it; - } - - template - void VectorSet::removeExists(const T& item) - { - iterator it = find(item); - OgreAssertDbg(it != this->end(), ""); - remove(it); - } - - template - bool VectorSet::remove(const T& item) - { - iterator it = find(item); - if (it != this->end()) { - remove(it); - return true; - } else { - return false; - } - } - - template - void VectorSet::replaceExists(const T& oldItem, const T& newItem) - { - iterator it = find(oldItem); - OgreAssertDbg(it != this->end(), ""); - *it = newItem; - } - - template - bool VectorSet::has(const T& item) - { - return find(item) != this->end(); - } - - template - typename VectorSet::iterator VectorSet::find(const T& item) - { - return std::find(this->begin(), this->end(), item); - } - - template - typename VectorSet::iterator VectorSet::findExists( - const T& item) - { - iterator it = find(item); - OgreAssertDbg(it != this->end(), ""); - return it; - } - -} -#endif diff --git a/Components/MeshLodGenerator/src/OgreLodBuffer.cpp b/Components/MeshLodGenerator/src/OgreLodBuffer.cpp deleted file mode 100644 index aff692ad281..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodBuffer.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#include "OgreMeshLodPrecompiledHeaders.h" -#include "OgreDefaultHardwareBufferManager.h" - -namespace Ogre -{ - void LodVertexBuffer::fillBuffer( Ogre::VertexData* data ) - { - vertexCount = data->vertexCount; - if (vertexCount > 0) { - // Locate position element and the buffer to go with it. - const VertexElement* elemPos = data->vertexDeclaration->findElementBySemantic(VES_POSITION); - - // Only float supported. - OgreAssert(elemPos->getType() == VET_FLOAT3, ""); - - HardwareVertexBufferSharedPtr vbuf = data->vertexBufferBinding->getBuffer(elemPos->getSource()); - vertexBuffer = std::make_shared(vertexCount * 3 * sizeof(float)); - - // Lock the buffer for reading. - unsigned char* vStart = static_cast(vbuf->lock(HardwareBuffer::HBL_READ_ONLY)); - unsigned char* vertex = vStart; - size_t vSize = vbuf->getVertexSize(); - - const VertexElement* elemNormal = 0; - HardwareVertexBufferSharedPtr vNormalBuf; - unsigned char* vNormal = NULL; - Vector3f* pNormalOut = NULL; - size_t vNormalSize = 0; - bool useVertexNormals = true; - elemNormal = data->vertexDeclaration->findElementBySemantic(VES_NORMAL); - useVertexNormals = useVertexNormals && (elemNormal != 0); - if(useVertexNormals){ - vertexNormalBuffer = std::make_shared(vertexCount * sizeof(Vector3f)); - pNormalOut = (Vector3f *)vertexNormalBuffer->lock(HardwareBuffer::HBL_DISCARD); - if(elemNormal->getSource() == elemPos->getSource()){ - vNormalBuf = vbuf; - vNormal = vStart; - } else { - vNormalBuf = data->vertexBufferBinding->getBuffer(elemNormal->getSource()); - vNormal = static_cast(vNormalBuf->lock(HardwareBuffer::HBL_READ_ONLY)); - } - vNormalSize = vNormalBuf->getVertexSize(); - } - - // Loop through all vertices and insert them to the Unordered Map. - Vector3f* pOut = (Vector3f *)vertexBuffer->lock(HardwareBuffer::HBL_DISCARD); - Vector3f* pEnd = pOut + vertexCount; - for (; pOut < pEnd; pOut++) { - memcpy(pOut, vertex + elemPos->getOffset(), sizeof(Vector3f)); - vertex += vSize; - if(useVertexNormals){ - memcpy(pNormalOut, vNormal + elemNormal->getOffset(), sizeof(Vector3f)); - pNormalOut++; - vNormal += vNormalSize; - } - } - vbuf->unlock(); - if(elemNormal && elemNormal->getSource() != elemPos->getSource()){ - vNormalBuf->unlock(); - } - vertexBuffer->unlock(); - if (useVertexNormals){ - vertexNormalBuffer->unlock(); - } - } - } - - void LodInputBuffer::fillBuffer( Ogre::MeshPtr mesh ) - { - meshName = mesh->getName(); - boundingSphereRadius = mesh->getBoundingSphereRadius(); - bool sharedVerticesAdded = false; - size_t submeshCount = mesh->getNumSubMeshes(); - submesh.resize(submeshCount); - DefaultHardwareBufferManagerBase bfrMgr; - for (size_t i = 0; i < submeshCount; i++) { - const SubMesh* ogresubmesh = mesh->getSubMesh(i); - LodInputBuffer::Submesh& outsubmesh = submesh[i]; - outsubmesh.operationType = ogresubmesh->operationType; - - std::unique_ptr tmp(ogresubmesh->indexData->clone(true, &bfrMgr)); - outsubmesh.indexBuffer = *tmp; - - outsubmesh.useSharedVertexBuffer = ogresubmesh->useSharedVertices; - if (!outsubmesh.useSharedVertexBuffer) { - outsubmesh.vertexBuffer.fillBuffer(ogresubmesh->vertexData); - } else if (!sharedVerticesAdded) { - sharedVerticesAdded = true; - sharedVertexBuffer.fillBuffer(mesh->sharedVertexData); - } - } - } - - } diff --git a/Components/MeshLodGenerator/src/OgreLodBuffer.h b/Components/MeshLodGenerator/src/OgreLodBuffer.h deleted file mode 100644 index 728d7386b30..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodBuffer.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef _LodBuffer_H__ -#define _LodBuffer_H__ - -#include "OgreLodPrerequisites.h" -#include "OgreSharedPtr.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup MeshLodGenerator -* @{ -*/ -/// Thread-safe buffer for storing Hardware vertex buffer -struct LodVertexBuffer { - size_t vertexCount; - HardwareBufferPtr vertexBuffer; - HardwareBufferPtr vertexNormalBuffer; - void fillBuffer(Ogre::VertexData* data); -}; -/// Data representing all required information from a Mesh. Used by LodInputProviderBuffer. -struct LodInputBuffer -{ - struct _OgreLodExport Submesh { - IndexData indexBuffer; - LodVertexBuffer vertexBuffer; - bool useSharedVertexBuffer; - RenderOperation::OperationType operationType; - }; - std::vector submesh; - LodVertexBuffer sharedVertexBuffer; - String meshName; - Real boundingSphereRadius; - void fillBuffer(Ogre::MeshPtr mesh); -}; -/// Data representing the output of the Mesh reduction. Used by LodOutputProviderBuffer. -struct LodOutputBuffer { - - struct _OgreLodExport Submesh { - std::vector genIndexBuffers; - }; - /// Contains every generated indexBuffer from every submesh. submeshCount*lodLevelCount buffers. - std::vector submesh; -}; -/** @} */ -/** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/Components/MeshLodGenerator/src/OgreLodCollapseCost.cpp b/Components/MeshLodGenerator/src/OgreLodCollapseCost.cpp deleted file mode 100644 index 0044df2e3cd..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodCollapseCost.cpp +++ /dev/null @@ -1,160 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#include "OgreMeshLodPrecompiledHeaders.h" - -namespace Ogre -{ - void LodCollapseCost::initCollapseCosts( LodData* data ) - { - data->mCollapseCostHeap.clear(); - LodData::VertexList::iterator it = data->mVertexList.begin(); - LodData::VertexList::iterator itEnd = data->mVertexList.end(); - for (; it != itEnd; it++) { - if (!it->edges.empty()) { - initVertexCollapseCost(data, &*it); - } else { -#if OGRE_DEBUG_MODE - LogManager::getSingleton().stream() << "In " << data->mMeshName << " never used vertex found with ID: " << data->mCollapseCostHeap.size() << ". " - << "Vertex position: (" - << it->position.x << ", " - << it->position.y << ", " - << it->position.z << ") " - << "It will be excluded from Lod level calculations."; -#endif - } - } - } - - bool LodCollapseCost::isEdgeCollapsible(LodData::Vertex * src, LodData::Vertex * dst) - { - // For every primitive on the src vertex we need a primitive in the same submesh connecting src and dst. - if (mPreventPunchingHoles) - { - for (auto & testTri : src->triangles) - { - auto srcSubmeshID = testTri->submeshID; - bool canConnect = false; - - for (auto & solveTri : dst->triangles) - { - if (solveTri->submeshID == srcSubmeshID && solveTri->hasVertex(src) && solveTri->hasVertex(dst)) - { - canConnect = true; - break; - } - } - - if (canConnect == false) - return false; - } - } - if (mPreventBreakingLines) - { - for (auto & testLine : src->lines) - { - auto srcSubmeshID = testLine->submeshID; - bool canConnect = false; - - for (auto & solveLine : dst->lines) - { - if (solveLine->submeshID == srcSubmeshID && solveLine->hasVertex(src) && solveLine->hasVertex(dst)) - { - canConnect = true; - break; - } - } - - if (canConnect == false) - return false; - } - } - return true; - } - - void LodCollapseCost::computeVertexCollapseCost( LodData* data, LodData::Vertex* vertex, Real& collapseCost, LodData::Vertex*& collapseTo ) - { - LodData::VEdges::iterator it = vertex->edges.begin(); - for (; it != vertex->edges.end(); ++it) { - if (isEdgeCollapsible(vertex, it->dst)) { - it->collapseCost = computeEdgeCollapseCost(data, vertex, &*it); - } else { - it->collapseCost = LodData::NEVER_COLLAPSE_COST; - } - if (collapseCost > it->collapseCost) { - collapseCost = it->collapseCost; - collapseTo = it->dst; - } - } - } - void LodCollapseCost::initVertexCollapseCost( LodData* data, LodData::Vertex* vertex ) - { - OgreAssert(!vertex->edges.empty(), ""); - - Real collapseCost = LodData::UNINITIALIZED_COLLAPSE_COST; - LodData::Vertex* collapseTo = NULL; - computeVertexCollapseCost(data, vertex, collapseCost, collapseTo); - - vertex->collapseTo = collapseTo; - vertex->costHeapPosition = data->mCollapseCostHeap.emplace(collapseCost, vertex); - } - - void LodCollapseCost::updateVertexCollapseCost( LodData* data, LodData::Vertex* vertex ) - { - Real collapseCost = LodData::UNINITIALIZED_COLLAPSE_COST; - LodData::Vertex* collapseTo = NULL; - computeVertexCollapseCost(data, vertex, collapseCost, collapseTo); - - if (vertex->collapseTo != collapseTo || collapseCost != vertex->costHeapPosition->first) { - OgreAssert(vertex->costHeapPosition != data->mCollapseCostHeap.end(), ""); - data->mCollapseCostHeap.erase(vertex->costHeapPosition); - if (collapseCost != LodData::UNINITIALIZED_COLLAPSE_COST) { - vertex->collapseTo = collapseTo; - vertex->costHeapPosition = data->mCollapseCostHeap.emplace(collapseCost, vertex); - } else { -#if OGRE_DEBUG_MODE - vertex->collapseTo = NULL; - vertex->costHeapPosition = data->mCollapseCostHeap.end(); -#endif - } - } - } - - bool LodCollapseCost::isBorderVertex(const LodData::Vertex* vertex) const - { - LodData::VEdges::const_iterator it = vertex->edges.begin(); - LodData::VEdges::const_iterator itEnd = vertex->edges.end(); - for (; it != itEnd; ++it) { - if (it->refCount == 1) { - return true; - } - } - return false; - } -} - diff --git a/Components/MeshLodGenerator/src/OgreLodCollapseCostCurvature.cpp b/Components/MeshLodGenerator/src/OgreLodCollapseCostCurvature.cpp deleted file mode 100644 index d43feeac3ce..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodCollapseCostCurvature.cpp +++ /dev/null @@ -1,204 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -// The algorithm in this file is based heavily on: -/* - * Progressive Mesh type Polygon Reduction Algorithm - * by Stan Melax (c) 1998 - */ - -#include "OgreMeshLodPrecompiledHeaders.h" - -namespace Ogre -{ - Real LodCollapseCostCurvature::computeEdgeCollapseCost( LodData* data, LodData::Vertex* src, LodData::Edge* dstEdge ) - { - LodData::Vertex* dst = dstEdge->dst; - - // Degenerate case check - // Are we going to invert a face normal of one of the neighboring faces? - // Can occur when we have a very small remaining edge and collapse crosses it - // Look for a face normal changing by > 90 degrees - if(MESHLOD_QUALITY >= 2) { // 30% speedup if disabled. - LodData::VTriangles::iterator it = src->triangles.begin(); - LodData::VTriangles::iterator itEnd = src->triangles.end(); - for (; it != itEnd; ++it) { - LodData::Triangle* triangle = *it; - // Ignore the deleted faces (those including src & dest) - if (!triangle->hasVertex(dst)) { - // Test the new face normal - LodData::Vertex* pv0, * pv1, * pv2; - - // Replace src with dest wherever it is - pv0 = (triangle->vertex[0] == src) ? dst : triangle->vertex[0]; - pv1 = (triangle->vertex[1] == src) ? dst : triangle->vertex[1]; - pv2 = (triangle->vertex[2] == src) ? dst : triangle->vertex[2]; - - Vector3 newNormal = Math::calculateBasicFaceNormalWithoutNormalize( - pv0->position, pv1->position, pv2->position); - - // Dot old and new face normal - // If < 0 then more than 90 degree difference - if (newNormal.dotProduct(triangle->normal) < 0.0f) { - // Don't do it! - return LodData::NEVER_COLLAPSE_COST; - } - } - } - } - - Real cost; - - // Special cases - // If we're looking at a border vertex - if (isBorderVertex(src)) { - if (dstEdge->refCount > 1) { - // src is on a border, but the src-dest edge has more than one tri on it - // So it must be collapsing inwards - // Mark as very high-value cost - // curvature = 1.0f; - cost = 1.0f; - } else { - // Collapsing ALONG a border - // We can't use curvature to measure the effect on the model - // Instead, see what effect it has on 'pulling' the other border edges - // The more colinear, the less effect it will have - // So measure the 'kinkiness' (for want of a better term) - - // Find the only triangle using this edge. - // PMTriangle* triangle = findSideTriangle(src, dst); - - cost = -1.0f; - Vector3 collapseEdge = src->position - dst->position; - collapseEdge.normalise(); - LodData::VEdges::iterator it = src->edges.begin(); - LodData::VEdges::iterator itEnd = src->edges.end(); - for (; it != itEnd; it++) { - LodData::Vertex* neighbor = it->dst; - if (neighbor != dst && it->refCount == 1) { - Vector3 otherBorderEdge = src->position - neighbor->position; - otherBorderEdge.normalise(); - // This time, the nearer the dot is to -1, the better, because that means - // the edges are opposite each other, therefore less kinkiness - // Scale into [0..1] - Real kinkiness = otherBorderEdge.dotProduct(collapseEdge); - cost = std::max(cost, kinkiness); - } - } - cost = (1.002f + cost) * 0.5f; - } - } else { // not a border - - // Standard inner vertex - // Calculate curvature - // use the triangle facing most away from the sides - // to determine our curvature term - // Iterate over src's faces again - cost = 1.0f; - LodData::VTriangles::iterator it = src->triangles.begin(); - LodData::VTriangles::iterator itEnd = src->triangles.end(); - for (; it != itEnd; ++it) { - Real mincurv = -1.0f; // curve for face i and closer side to it - LodData::Triangle* triangle = *it; - LodData::VTriangles::iterator it2 = src->triangles.begin(); - for (; it2 != itEnd; ++it2) { - LodData::Triangle* triangle2 = *it2; - if (triangle2->hasVertex(dst)) { - - // Dot product of face normal gives a good delta angle - Real dotprod = triangle->normal.dotProduct(triangle2->normal); - // NB we do (1-..) to invert curvature where 1 is high curvature [0..1] - // Whilst dot product is high when angle difference is low - mincurv = std::max(mincurv, dotprod); - } - } - cost = std::min(cost, mincurv); - } - cost = (1.002f - cost) * 0.5f; - } - - // check for texture seam ripping and multiple submeshes - if (src->seam) { - if (!dst->seam) { - cost = std::max(cost, (Real)0.05f); - cost *= 64; - } else { - if(MESHLOD_QUALITY >= 3) { - int seamNeighbors = 0; - LodData::Vertex* otherSeam; - LodData::VEdges::iterator it = src->edges.begin(); - LodData::VEdges::iterator itEnd = src->edges.end(); - for (; it != itEnd; it++) { - LodData::Vertex* neighbor = it->dst; - if(neighbor->seam) { - seamNeighbors++; - if(neighbor != dst){ - otherSeam = neighbor; - } - } - } - if(seamNeighbors != 2 || (seamNeighbors == 2 && dst->edges.has(LodData::Edge(otherSeam)))) { - cost = std::max(cost, 0.05f); - cost *= 64; - } else { - cost = std::max(cost, 0.005f); - cost *= 8; - } - } else { - cost = std::max(cost, 0.005f); - cost *= 8; - } - - } - } - - Real diff = src->normal.dotProduct(dst->normal) / 8.0f; - Real dist = src->position.distance(dst->position); - cost = cost * dist; - if(data->mUseVertexNormals){ - //Take into account vertex normals. - Real normalCost = 0; - LodData::VEdges::iterator it = src->edges.begin(); - LodData::VEdges::iterator itEnd = src->edges.end(); - for (; it != itEnd; ++it) { - LodData::Vertex* neighbor = it->dst; - Real beforeDist = neighbor->position.distance(src->position); - Real afterDist = neighbor->position.distance(dst->position); - Real beforeDot = neighbor->normal.dotProduct(src->normal); - Real afterDot = neighbor->normal.dotProduct(dst->normal); - normalCost = std::max(normalCost, std::max(diff, std::abs(beforeDot - afterDot)) * - std::max(afterDist/8.0f, std::max(dist, std::abs(beforeDist - afterDist)))); - } - cost = std::max(normalCost * 0.25f, cost); - } - - OgreAssert(cost >= 0 && cost != LodData::UNINITIALIZED_COLLAPSE_COST, "Invalid collapse cost"); - return cost; - } -} - diff --git a/Components/MeshLodGenerator/src/OgreLodCollapseCostOutside.cpp b/Components/MeshLodGenerator/src/OgreLodCollapseCostOutside.cpp deleted file mode 100644 index 9912b5bd618..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodCollapseCostOutside.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#include "OgreMeshLodPrecompiledHeaders.h" - -namespace Ogre -{ - LodCollapseCostOutside::LodCollapseCostOutside( LodCollapseCostPtr costCalculator, Real outsideWeight, Real outsideWalkAngle ) : - mOutsideWeight(outsideWeight), - mOutsideWalkAngle(outsideWalkAngle), - mCostCalculator(costCalculator), - mOutsideMarker(NULL) - { - } - - LodCollapseCostOutside::~LodCollapseCostOutside() - { - delete mOutsideMarker; - } - - void LodCollapseCostOutside::initCollapseCosts( LodData* data ) - { - OgreAssert(mOutsideWeight != 0.0, ""); - - delete mOutsideMarker; - mOutsideMarker = new LodOutsideMarker(data->mVertexList, data->mMeshBoundingSphereRadius, mOutsideWalkAngle); - mOutsideMarker->markOutside(); - - - mCostCalculator->initCollapseCosts(data); - } - - Real LodCollapseCostOutside::computeEdgeCollapseCost( LodData* data, LodData::Vertex* src, LodData::Edge* dstEdge ) - { - Real cost = mCostCalculator->computeEdgeCollapseCost(data, src, dstEdge); - if(mOutsideMarker->isVertexOutside(src) || mOutsideMarker->isVertexOutside(dstEdge->dst)) { - if(mOutsideWeight != LodData::NEVER_COLLAPSE_COST && cost != LodData::NEVER_COLLAPSE_COST) { - cost *= std::max(0.0078125f, mOutsideWeight * 8.0f); - } else { - return LodData::NEVER_COLLAPSE_COST; - } - } - OgreAssert(cost >= 0 && cost != LodData::UNINITIALIZED_COLLAPSE_COST, "Invalid collapse cost"); - return cost; - } -} - diff --git a/Components/MeshLodGenerator/src/OgreLodCollapseCostProfiler.cpp b/Components/MeshLodGenerator/src/OgreLodCollapseCostProfiler.cpp deleted file mode 100644 index 109951d5732..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodCollapseCostProfiler.cpp +++ /dev/null @@ -1,103 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#include "OgreMeshLodPrecompiledHeaders.h" - -namespace Ogre -{ - - Real LodCollapseCostProfiler::computeEdgeCollapseCost( LodData* data, LodData::Vertex* src, LodData::Edge* dstEdge ) - { - OgreAssert(0, "Only computeVertexCollapseCost should call this function."); - return 0; - } - - void LodCollapseCostProfiler::computeVertexCollapseCost( LodData* data, LodData::Vertex* vertex, Real& collapseCost, LodData::Vertex*& collapseTo ) - { - LodData::VEdges::iterator it = vertex->edges.begin(); - if(!mHasProfile[LodData::getVectorIDFromPointer(data->mVertexList, vertex)]){ - for (; it != vertex->edges.end(); ++it) { - it->collapseCost = mCostCalculator->computeEdgeCollapseCost(data, vertex, &*it); - if (collapseCost > it->collapseCost) { - collapseCost = it->collapseCost; - collapseTo = it->dst; - } - } - } else { - std::pair ret = mProfileLookup.equal_range(vertex); - for (; it != vertex->edges.end(); ++it) { - it->collapseCost = LodData::UNINITIALIZED_COLLAPSE_COST; - for(ProfileLookup::iterator it2 = ret.first; it2 != ret.second; ++it2){ - if(it2->second.dst == it->dst ){ - it->collapseCost = it2->second.cost; - break; - } - } - if(it->collapseCost == LodData::UNINITIALIZED_COLLAPSE_COST){ - it->collapseCost = mCostCalculator->computeEdgeCollapseCost(data, vertex, &*it); - } - if (collapseCost > it->collapseCost) { - collapseCost = it->collapseCost; - collapseTo = it->dst; - } - } - } - } - - void LodCollapseCostProfiler::injectProfile( LodData* data) - { - mHasProfile.clear(); - mHasProfile.resize(data->mVertexList.size(), false); - LodProfile::iterator it = mProfile.begin(); - LodProfile::iterator itEnd = mProfile.end(); - for(;it != itEnd;it++){ - LodData::Vertex v; - v.position = it->src; - LodData::UniqueVertexSet::iterator src = data->mUniqueVertexSet.find(&v); - OgreAssert(src != data->mUniqueVertexSet.end(), "Invalid vertex position in Lod profile"); - mHasProfile[LodData::getVectorIDFromPointer(data->mVertexList, *src)] = true; - v.position = it->dst; - LodData::UniqueVertexSet::iterator dst = data->mUniqueVertexSet.find(&v); - OgreAssert(dst != data->mUniqueVertexSet.end(), "Invalid vertex position in Lod profile"); - ProfiledEdge e; - e.dst = *dst; - e.cost = it->cost; - OgreAssert(e.cost >= 0 && e.cost != LodData::UNINITIALIZED_COLLAPSE_COST, "Invalid collapse cost"); - mProfileLookup.emplace(*src, e); - } - } - - void LodCollapseCostProfiler::initCollapseCosts( LodData* data ) - { - injectProfile(data); - mProfile.clear(); - mCostCalculator->initCollapseCosts(data); - } - -} - diff --git a/Components/MeshLodGenerator/src/OgreLodCollapseCostQuadric.cpp b/Components/MeshLodGenerator/src/OgreLodCollapseCostQuadric.cpp deleted file mode 100644 index 066b70f1b49..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodCollapseCostQuadric.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -// The algorithm in this file is based heavily on: -/* - * Progressive Mesh type Polygon Reduction Algorithm - * by Stan Melax (c) 1998 - */ - -#include "OgreLodCollapseCostQuadric.h" -#include "OgreVector.h" - -namespace Ogre -{ - - void LodCollapseCostQuadric::initCollapseCosts( LodData* data ) - { - mTrianglePlaneQuadricList.resize(data->mTriangleList.size()); - for(size_t i=0;imVertexList.size()); - for (size_t i=0;imTriangleList[triangleID]; - Matrix4& quadric = mTrianglePlaneQuadricList[triangleID]; - Real plane[4]; - plane[0] = triangle.normal.x; - plane[1] = triangle.normal.y; - plane[2] = triangle.normal.z; - Vector3& v0 = triangle.vertex[0]->position; - plane[3] = -v0.dotProduct(triangle.normal); - for(int i=0;i<4;i++){ - for(int n=0;n<4;n++){ - quadric[i][n] = plane[i] * plane[n]; - } - } - } - - Real LodCollapseCostQuadric::computeEdgeCollapseCost( LodData* data, LodData::Vertex* src, LodData::Edge* dstEdge ) - { - LodData::Vertex* dst = dstEdge->dst; - - if (isBorderVertex(src)) { - return LodData::NEVER_COLLAPSE_COST; - } - if (src->seam && !dst->seam) { - return LodData::NEVER_COLLAPSE_COST; - } - - Matrix4 Qnew = mVertexQuadricList[LodData::getVectorIDFromPointer(data->mVertexList, src)] + - mVertexQuadricList[LodData::getVectorIDFromPointer(data->mVertexList, dst)]; - - Vector4 Vnew(dst->position); - - // error = Vnew^T * Qnew * Vnew - Real cost = - (Vnew[0] * Qnew[0][0] + Vnew[1] * Qnew[0][1] + Vnew[2] * Qnew[0][2] + Vnew[3] * Qnew[0][3]) * Vnew[0] + - (Vnew[0] * Qnew[1][0] + Vnew[1] * Qnew[1][1] + Vnew[2] * Qnew[1][2] + Vnew[3] * Qnew[1][3]) * Vnew[1] + - (Vnew[0] * Qnew[2][0] + Vnew[1] * Qnew[2][1] + Vnew[2] * Qnew[2][2] + Vnew[3] * Qnew[2][3]) * Vnew[2] + - (Vnew[0] * Qnew[3][0] + Vnew[1] * Qnew[3][1] + Vnew[2] * Qnew[3][2] + Vnew[3] * Qnew[3][3]) * Vnew[3]; - - if (dst->seam) { - cost *= 8; - } - - return cost; - - } - - void LodCollapseCostQuadric::computeVertexQuadric( LodData* data, size_t vertexID ) - { - Matrix4& quadric = mVertexQuadricList[vertexID]; - quadric = Matrix4::ZERO; - LodData::Vertex& vertex = data->mVertexList[vertexID]; - LodData::VTriangles::iterator tri, triEnd; - tri = vertex.triangles.begin(); - triEnd = vertex.triangles.end(); - for (;tri != triEnd; ++tri) { - size_t id = LodData::getVectorIDFromPointer(data->mTriangleList, *tri); - quadric = quadric + mTrianglePlaneQuadricList[id]; - } - } - - void LodCollapseCostQuadric::updateVertexCollapseCost( LodData* data, LodData::Vertex* vertex ) - { - computeVertexQuadric(data, LodData::getVectorIDFromPointer(data->mVertexList, vertex)); - - LodCollapseCost::updateVertexCollapseCost(data, vertex); - } - - - - } diff --git a/Components/MeshLodGenerator/src/OgreLodCollapser.cpp b/Components/MeshLodGenerator/src/OgreLodCollapser.cpp deleted file mode 100644 index c3d31e41c1f..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodCollapser.cpp +++ /dev/null @@ -1,416 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ -#include "OgreMeshLodPrecompiledHeaders.h" - -namespace Ogre -{ - - void LodCollapser::collapse( LodData* data, LodCollapseCost* cost, LodOutputProvider* output, int vertexCountLimit, Real collapseCostLimit ) - { - while (data->mCollapseCostHeap.size() > static_cast(vertexCountLimit)) - { - LodData::CollapseCostHeap::iterator nextVertex = data->mCollapseCostHeap.begin(); - if (nextVertex->first < collapseCostLimit) - { - mLastReducedVertex = nextVertex->second; - collapseVertex(data, cost, output, mLastReducedVertex); - } else { - break; - } - } - } - -#if OGRE_DEBUG_MODE - void LodCollapser::assertValidMesh(LodData* data) - { - // Allows to find bugs in collapsing. - // size_t s1 = mUniqueVertexSet.size(); - // size_t s2 = mCollapseCostHeap.size(); - LodData::CollapseCostHeap::iterator it = data->mCollapseCostHeap.begin(); - LodData::CollapseCostHeap::iterator itEnd = data->mCollapseCostHeap.end(); - while (it != itEnd) { - assertValidVertex(data, it->second); - it++; - } - } - - void LodCollapser::assertValidVertex(LodData* data, LodData::Vertex* v) - { - // Allows to find bugs in collapsing. - LodData::VTriangles::iterator it = v->triangles.begin(); - LodData::VTriangles::iterator itEnd = v->triangles.end(); - for (; it != itEnd; it++) { - LodData::Triangle* t = *it; - for (int i = 0; i < 3; i++) { - OgreAssert(t->vertex[i]->costHeapPosition != data->mCollapseCostHeap.end(), ""); - t->vertex[i]->edges.findExists(LodData::Edge(t->vertex[i]->collapseTo)); - for (int n = 0; n < 3; n++) { - if (i != n) { - LodData::VEdges::iterator edgeIt = t->vertex[i]->edges.findExists(LodData::Edge(t->vertex[n])); - OgreAssert(edgeIt->collapseCost != LodData::UNINITIALIZED_COLLAPSE_COST, ""); - } else { - OgreAssert(t->vertex[i]->edges.find(LodData::Edge(t->vertex[n])) == t->vertex[i]->edges.end(), ""); - } - } - } - } - } - - void LodCollapser::assertOutdatedCollapseCost( LodData* data, LodCollapseCost* cost, LodData::Vertex* vertex ) - { - // Validates that collapsing has updated all edges needed by computeEdgeCollapseCost. - // This will OgreAssert if the dependencies inside computeEdgeCollapseCost changes. - LodData::VEdges::iterator it = vertex->edges.begin(); - LodData::VEdges::iterator itEnd = vertex->edges.end(); - for (; it != itEnd; it++) { - OgreAssert(it->collapseCost == cost->computeEdgeCollapseCost(data, vertex, &*it), ""); - LodData::Vertex* neighbor = it->dst; - LodData::VEdges::iterator it2 = neighbor->edges.begin(); - LodData::VEdges::iterator it2End = neighbor->edges.end(); - for (; it2 != it2End; it2++) { - OgreAssert(it2->collapseCost == cost->computeEdgeCollapseCost(data, neighbor, &*it2), ""); - } - } - } -#endif // if OGRE_DEBUG_MODE - - bool LodCollapser::hasSrcID(unsigned int srcID, size_t submeshID) - { - // This will only return exact matches. - for (auto & tmpCollapsedEdge : tmpCollapsedEdges) { - if (tmpCollapsedEdge.srcID == srcID && tmpCollapsedEdge.submeshID == submeshID) { - return true; - } - } - return false; // Not found - } - void LodCollapser::removeTriangleFromEdges(LodData::Triangle* triangle, LodData::Vertex* skip) - { - triangle->isRemoved = true; - // skip is needed if we are iterating on the vertex's edges or triangles. - for (auto & i : triangle->vertex) { - if (i != skip) { - i->triangles.removeExists(triangle); - } - } - for (int i = 0; i < 3; i++) { - for (int n = 0; n < 3; n++) { - if (i != n && triangle->vertex[i] != skip) { - triangle->vertex[i]->removeEdge(LodData::Edge(triangle->vertex[n])); - } - } - } - } - void LodCollapser::removeLine(LodData::Line* line, LodData::Vertex* skip) - { - line->isRemoved = true; - - for (auto & i : line->vertex) { - if (i != skip) { - i->lines.removeExists(line); - } - } - } - - size_t LodCollapser::findDstID(unsigned int srcID, size_t submeshID) - { - // Tries to find a compatible edge. - - // Exact match search. - for (size_t i = 0; i < tmpCollapsedEdges.size(); i++) { - if (tmpCollapsedEdges[i].srcID == srcID && tmpCollapsedEdges[i].submeshID == submeshID) { - return i; - } - } - - // Usable match search. - for (size_t i = 0; i < tmpCollapsedEdges.size(); i++) { - if (tmpCollapsedEdges[i].submeshID == submeshID) { - return i; - } - } - return std::numeric_limits::max(); // Not found - } - void LodCollapser::replaceVertexID(LodData::Triangle* triangle, unsigned int oldID, unsigned int newID, LodData::Vertex* dst) - { - dst->triangles.addNotExists(triangle); - // NOTE: triangle is not removed from src. This is implementation specific optimization. - - // Its up to the compiler to unroll everything. - for (int i = 0; i < 3; i++) { - if (triangle->vertexID[i] == oldID) { - for (int n = 0; n < 3; n++) { - if (i != n) { - // This is implementation specific optimization to remove following line. - // triangle->vertex[i]->removeEdge(LodData::Edge(triangle->vertex[n])); - - triangle->vertex[n]->removeEdge(LodData::Edge(triangle->vertex[i])); - triangle->vertex[n]->addEdge(LodData::Edge(dst)); - dst->addEdge(LodData::Edge(triangle->vertex[n])); - } - } - triangle->vertex[i] = dst; - triangle->vertexID[i] = newID; - return; - } - } - OgreAssert(0, ""); - } - void LodCollapser::replaceVertexID(LodData::Line* line, unsigned int oldID, unsigned int newID, LodData::Vertex* dst) - { - dst->lines.addNotExists(line); - // NOTE: line is not removed from src. This is implementation specific optimization. - - for (int i = 0; i < 2; i++) { - if (line->vertexID[i] == oldID) { - line->vertex[i] = dst; - line->vertexID[i] = newID; - return; - } - } - OgreAssert(0, ""); - } - void LodCollapser::collapseVertex( LodData* data, LodCollapseCost* cost, LodOutputProvider* output, LodData::Vertex* src ) - { - LodData::Vertex* dst = src->collapseTo; -#if OGRE_DEBUG_MODE - assertValidVertex(data, dst); - assertValidVertex(data, src); -#endif - OgreAssert(src->costHeapPosition->first != LodData::NEVER_COLLAPSE_COST, ""); - OgreAssert(src->costHeapPosition->first != LodData::UNINITIALIZED_COLLAPSE_COST, ""); - OgreAssert(!src->edges.empty(), ""); - OgreAssert(!src->triangles.empty(), ""); - OgreAssert(src->edges.find(LodData::Edge(dst)) != src->edges.end(), ""); - - // It may have vertexIDs and triangles from different submeshes(different vertex buffers), - // so we need to connect them correctly based on deleted triangle's edge. - // mCollapsedEdgeIDs will be used, when looking up the connections for replacement. - tmpCollapsedEdges.clear(); - LodData::VTriangles::iterator it = src->triangles.begin(); - LodData::VTriangles::iterator itEnd = src->triangles.end(); - for (; it != itEnd; ++it) { - LodData::Triangle* triangle = *it; - if (triangle->hasVertex(dst)) { - // Remove a triangle - // Tasks: - // 1. Add it to the collapsed edges list. - // 2. Reduce index count for the Lods, which will not have this triangle. - // 3. Remove references/pointers to this triangle and mark as removed. - - // 1. task - unsigned int srcID = triangle->getVertexID(src); - if (!hasSrcID(srcID, triangle->submeshID)) { - tmpCollapsedEdges.push_back(CollapsedEdge()); - tmpCollapsedEdges.back().srcID = srcID; - tmpCollapsedEdges.back().dstID = triangle->getVertexID(dst); - tmpCollapsedEdges.back().submeshID = triangle->submeshID; - } - - // 2. task - data->mIndexBufferInfoList[triangle->submeshID].indexCount -= 3; - output->triangleRemoved(data, triangle); - // 3. task - removeTriangleFromEdges(triangle, src); - - } - } - OgreAssert(tmpCollapsedEdges.size(), ""); - OgreAssert(dst->edges.find(LodData::Edge(src)) == dst->edges.end(), ""); - - LodData::VLines::iterator lineIt = src->lines.begin(); - LodData::VLines::iterator lineItEnd = src->lines.end(); - for (; lineIt != lineItEnd; ++lineIt) - { - LodData::Line* line = *lineIt; - if (line->hasVertex(dst)) - { - // Remove a line - // Tasks: - // 1. Add it to the collapsed edges list. - // 2. Reduce index count for the Lods, which will not have this line. - // 3. Remove references/pointers to this line and mark as removed. - - // 1. task - unsigned int srcID = line->getVertexID(src); - if (!hasSrcID(srcID, line->submeshID)) { - tmpCollapsedEdges.push_back(CollapsedEdge()); - tmpCollapsedEdges.back().srcID = srcID; - tmpCollapsedEdges.back().dstID = line->getVertexID(dst); - tmpCollapsedEdges.back().submeshID = line->submeshID; - } - - // 2. task - data->mIndexBufferInfoList[line->submeshID].indexCount -= 2; - output->lineRemoved(data, line); - // 3. task - removeLine(line, src); - } - } - - it = src->triangles.begin(); - for (; it != itEnd; ++it) { - LodData::Triangle* triangle = *it; - if (!triangle->hasVertex(dst)) { - // Replace a triangle - // Tasks: - // 1. Determine the edge which we will move along. (we need to modify single vertex only) - // 2. Move along the selected edge. - - // 1. task - unsigned int srcID = triangle->getVertexID(src); - size_t id = findDstID(srcID, triangle->submeshID); - if (id == std::numeric_limits::max()) { - // Not found any edge to move along. - // Destroy the triangle. - data->mIndexBufferInfoList[triangle->submeshID].indexCount -= 3; - output->triangleRemoved(data, triangle); - removeTriangleFromEdges(triangle, src); - continue; - } - unsigned int dstID = tmpCollapsedEdges[id].dstID; - - // 2. task - replaceVertexID(triangle, srcID, dstID, dst); - - output->triangleChanged(data, triangle); - -#if MESHLOD_QUALITY >= 3 - triangle->computeNormal(); -#endif - } - } - - lineIt = src->lines.begin(); - for (; lineIt != lineItEnd; ++lineIt) - { - LodData::Line* line = *lineIt; - if (!line->hasVertex(dst)) - { - // Replace a line - // Tasks: - // 1. Determine the edge which we will move along. (we need to modify single vertex only) - // 2. Move along the selected edge. - - // 1. task - unsigned int srcID = line->getVertexID(src); - size_t id = findDstID(srcID, line->submeshID); - if (id == std::numeric_limits::max()) { - // Not found any edge to move along. - // Destroy the triangle. - data->mIndexBufferInfoList[line->submeshID].indexCount -= 2; - output->lineRemoved(data, line); - removeLine(line, src); - continue; - } - unsigned int dstID = tmpCollapsedEdges[id].dstID; - - // 2. task - replaceVertexID(line, srcID, dstID, dst); - - output->lineChanged(data, line); - } - } - - dst->seam |= src->seam; // Inherit seam property - -#if MESHLOD_QUALITY <= 2 - LodData::VEdges::iterator it3 = src->edges.begin(); - LodData::VEdges::iterator it3End = src->edges.end(); - for (; it3 != it3End; ++it3) { - cost->updateVertexCollapseCost(data, it3->dst); - } -#else - // TODO: Find out why is this needed. assertOutdatedCollapseCost() fails on some - // rare situations without this. For example goblin.mesh fails. - typedef SmallVector UpdatableList; - UpdatableList updatable; - LodData::VEdges::iterator it3 = src->edges.begin(); - LodData::VEdges::iterator it3End = src->edges.end(); - for (; it3 != it3End; it3++) { - updatable.push_back(it3->dst); - LodData::VEdges::iterator it4End = it3->dst->edges.end(); - LodData::VEdges::iterator it4 = it3->dst->edges.begin(); - for (; it4 != it4End; it4++) { - updatable.push_back(it4->dst); - } - } - - // Remove duplicates. - UpdatableList::iterator it5 = updatable.begin(); - UpdatableList::iterator it5End = updatable.end(); - std::sort(it5, it5End); - it5End = std::unique(it5, it5End); - - for (; it5 != it5End; it5++) { - cost->updateVertexCollapseCost(data, *it5); - } -#if OGRE_DEBUG_MODE - it3 = src->edges.begin(); - it3End = src->edges.end(); - for (; it3 != it3End; it3++) { - assertOutdatedCollapseCost(data, cost, it3->dst); - } - it3 = dst->edges.begin(); - it3End = dst->edges.end(); - for (; it3 != it3End; it3++) { - assertOutdatedCollapseCost(data, cost, it3->dst); - } - assertOutdatedCollapseCost(data, cost, dst); -#endif // ifndef OGRE_DEBUG_MODE -#endif // ifndef MESHLOD_QUALITY - data->mCollapseCostHeap.erase(src->costHeapPosition); // Remove src from collapse costs. - src->edges.clear(); // Free memory - src->lines.clear(); // Free memory - src->triangles.clear(); // Free memory -#if OGRE_DEBUG_MODE - src->costHeapPosition = data->mCollapseCostHeap.end(); - assertValidVertex(data, dst); -#endif - } - - bool LodCollapser::_getLastVertexPos(LodData* data, Vector3& outVec) - { - if(mLastReducedVertex){ - outVec = mLastReducedVertex->position; - return true; - } else { - return false; - } - } - - bool LodCollapser::_getLastVertexCollapseTo(LodData* data, Vector3& outVec ) - { - if(mLastReducedVertex){ - outVec = mLastReducedVertex->collapseTo->position; - return true; - } else { - return false; - } - } -} diff --git a/Components/MeshLodGenerator/src/OgreLodConfig.cpp b/Components/MeshLodGenerator/src/OgreLodConfig.cpp deleted file mode 100644 index cb263deb575..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodConfig.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#include "OgreMeshLodPrecompiledHeaders.h" - -namespace Ogre -{ - -LodConfig::Advanced::Advanced() : - useBackgroundQueue(false), - useCompression(true), - useVertexNormals(true), - outsideWeight(0.0), - outsideWalkAngle(0.0) -{ -} - -LodConfig::LodConfig(MeshPtr& _mesh, LodStrategy* _strategy /*= DistanceLodStrategy::getSingletonPtr()*/) : - mesh(_mesh), strategy(_strategy) -{ -} - -LodConfig::LodConfig() -{ -} - -void LodConfig::createManualLodLevel(Ogre::Real distance, const String& manualMeshName) -{ - LodLevel lodLevel; - lodLevel.distance = distance; - lodLevel.manualMeshName = manualMeshName; - levels.push_back(lodLevel); -} - -void LodConfig::createGeneratedLodLevel(Ogre::Real distance, - Real reductionValue, - LodLevel::VertexReductionMethod reductionMethod /*= LodLevel::VRM_PROPORTIONAL*/) -{ - LodLevel lodLevel; - lodLevel.distance = distance; - lodLevel.reductionValue = reductionValue; - lodLevel.reductionMethod = reductionMethod; - levels.push_back(lodLevel); -} - -} diff --git a/Components/MeshLodGenerator/src/OgreLodConfigSerializer.cpp b/Components/MeshLodGenerator/src/OgreLodConfigSerializer.cpp deleted file mode 100644 index a5a160c8d92..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodConfigSerializer.cpp +++ /dev/null @@ -1,355 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreMeshLodPrecompiledHeaders.h" - -namespace Ogre -{ - - LodConfigSerializer::LodConfigSerializer() - { - mVersion = "[LodConfigSerializer_v1.0]"; - mLodConfig = 0; - } - - void LodConfigSerializer::importLodConfig(Ogre::LodConfig* config, const Ogre::String& filename) - { - std::fstream *f = OGRE_NEW_T(std::fstream, MEMCATEGORY_GENERAL)(); - f->open(filename.c_str(), std::ios::binary | std::ios::in); - if(f->is_open()){ - Ogre::DataStreamPtr stream(OGRE_NEW Ogre::FileStreamDataStream(f)); - - importLodConfig(config, stream); - - stream->close(); - } - } - - void LodConfigSerializer::importLodConfig(Ogre::LodConfig* config, DataStreamPtr& stream) - { - mStream = stream; - mLodConfig = config; - - // Determine endianness (must be the first thing we do!) - determineEndianness(mStream); - - // Check header - readFileHeader(mStream); - - pushInnerChunk(mStream); - while (!mStream->eof()) - { - unsigned short streamID = readChunk(mStream); - switch (streamID) - { - case LCCID_LOD_CONFIG: - readLodConfig(); - break; - default: - backpedalChunkHeader(mStream); - popInnerChunk(mStream); - return; - } - } - popInnerChunk(mStream); - } - - void LodConfigSerializer::readLodConfig() - { - pushInnerChunk(mStream); - unsigned short streamID = readChunk(mStream); - while(!mStream->eof()) - { - switch(streamID) - { - case LCCID_BASIC_INFO: - readLodBasicInfo(); - break; - case LCCID_LOD_LEVELS: - readLodLevels(); - break; - case LCCID_ADVANCED_INFO: - readLodAdvancedInfo(); - break; - case LCCID_PROFILE: - readLodProfile(); - break; - default: - // Backpedal back to start of stream - backpedalChunkHeader(mStream); - popInnerChunk(mStream); - return; - } - - streamID = readChunk(mStream); - } - popInnerChunk(mStream); - } - - void LodConfigSerializer::readLodBasicInfo() - { - String group = readString(mStream); - String name = readString(mStream); - mLodConfig->mesh = MeshManager::getSingleton().load(name, group); - - String strategyName = readString(mStream); - mLodConfig->strategy = LodStrategyManager::getSingleton().getStrategy(strategyName); - } - - void LodConfigSerializer::readLodLevels() - { - uint32 size = 0; - readInts(mStream, &size, 1); - mLodConfig->levels.clear(); - while(size--){ - LodLevel level; - readFloats(mStream, &level.distance, 1); - readInts(mStream, (Ogre::uint32*)&level.reductionMethod, 1); - readFloats(mStream, &level.reductionValue, 1); - level.manualMeshName = readString(mStream); - mLodConfig->levels.push_back(level); - } - } - - void LodConfigSerializer::readLodAdvancedInfo() - { - readBools(mStream, &mLodConfig->advanced.useCompression, 1); - readBools(mStream, &mLodConfig->advanced.useVertexNormals, 1); - readBools(mStream, &mLodConfig->advanced.useBackgroundQueue, 1); - readFloats(mStream, &mLodConfig->advanced.outsideWeight, 1); - readFloats(mStream, &mLodConfig->advanced.outsideWalkAngle, 1); - } - - void LodConfigSerializer::readLodProfile() - { - uint32 size = 0; - readInts(mStream, &size, 1); - mLodConfig->advanced.profile.clear(); - while(size--){ - ProfiledEdge pv; - readObject(mStream, pv.src); - readObject(mStream, pv.dst); - readFloats(mStream, &pv.cost, 1); - mLodConfig->advanced.profile.push_back(pv); - } - } - - void LodConfigSerializer::exportLodConfig(Ogre::LodConfig& config, const Ogre::String& filename, Endian endianMode /*= ENDIAN_NATIVE*/ ) - { - std::fstream *f = OGRE_NEW_T(std::fstream, MEMCATEGORY_GENERAL)(); - f->open(filename.c_str(), std::ios::binary | std::ios::out); - Ogre::DataStreamPtr stream(OGRE_NEW Ogre::FileStreamDataStream(f)); - - exportLodConfig(config, stream, endianMode); - - stream->close(); - } - - void LodConfigSerializer::exportLodConfig(Ogre::LodConfig& config, Ogre::DataStreamPtr stream, Endian endianMode /*= ENDIAN_NATIVE*/ ) - { - Ogre::LogManager::getSingleton().logMessage("MeshSerializer writing mesh data to stream " + stream->getName() + "..."); - - // Decide on endian mode - determineEndianness(endianMode); - mLodConfig = &config; - mStream = stream; - if (!stream->isWriteable()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Unable to use stream " + stream->getName() + " for writing", - "LodConfigSerializer::export"); - } - - writeFileHeader(); - LogManager::getSingleton().logMessage("File header written."); - - - LogManager::getSingleton().logMessage("Writing Lod Config..."); - pushInnerChunk(mStream); - writeLodConfig(); - popInnerChunk(mStream); - LogManager::getSingleton().logMessage("LodConfigSerializer export successful."); - } - - void LodConfigSerializer::writeLodConfig() - { - writeChunkHeader(LCCID_LOD_CONFIG, calcLodConfigSize()); - pushInnerChunk(mStream); - writeLodBasicInfo(); - writeLodLevels(); - writeLodAdvancedInfo(); - writeLodProfile(); - popInnerChunk(mStream); - } - - size_t LodConfigSerializer::calcLodConfigSize() - { - size_t size = calcChunkHeaderSize(); - - size += calcLodBasicInfoSize(); - - size += calcLodLevelsSize(); - - size += calcLodAdvancedInfoSize(); - - size += calcLodProfileSize(); - - return size; - } - - void LodConfigSerializer::writeLodBasicInfo() - { - writeChunkHeader(LCCID_BASIC_INFO, calcLodBasicInfoSize()); - writeString(mLodConfig->mesh->getGroup()); - writeString(mLodConfig->mesh->getName()); - writeString(mLodConfig->strategy->getName()); - } - - size_t LodConfigSerializer::calcLodBasicInfoSize() - { - size_t size = calcChunkHeaderSize(); - - size += calcStringSize(mLodConfig->mesh->getGroup()); - size += calcStringSize(mLodConfig->mesh->getName()); - size += calcStringSize(mLodConfig->strategy->getName()); - - return size; - } - - void LodConfigSerializer::writeLodLevels() - { - writeChunkHeader(LCCID_LOD_LEVELS, calcLodLevelsSize()); - uint32 size = static_cast(mLodConfig->levels.size()); - writeInts(&size, 1); - - LodConfig::LodLevelList::iterator it = mLodConfig->levels.begin(); - LodConfig::LodLevelList::iterator itEnd = mLodConfig->levels.end(); - for(;it != itEnd; it++){ - writeFloats(&it->distance, 1); - writeInts((Ogre::uint32*)&it->reductionMethod, 1); - writeFloats(&it->reductionValue, 1); - writeString(it->manualMeshName); - } - } - - size_t LodConfigSerializer::calcLodLevelsSize() - { - //lodLevel.distance - size_t levelSize = sizeof(float); - - //lodLevel.reductionMethod; - levelSize += sizeof(Ogre::uint32); - - //lodLevel.reductionValue; - levelSize += sizeof(float); - - size_t size = calcChunkHeaderSize(); - - // mLodConfig->levels.size() - size += sizeof(Ogre::uint32); - - size += levelSize * mLodConfig->levels.size(); - - for(auto & level : mLodConfig->levels) { - size += calcStringSize(level.manualMeshName); - } - - return size; - } - - void LodConfigSerializer::writeLodAdvancedInfo() - { - writeChunkHeader(LCCID_ADVANCED_INFO, calcLodAdvancedInfoSize()); - writeBools(&mLodConfig->advanced.useCompression, 1); - writeBools(&mLodConfig->advanced.useVertexNormals, 1); - writeBools(&mLodConfig->advanced.useBackgroundQueue, 1); - writeFloats(&mLodConfig->advanced.outsideWeight, 1); - writeFloats(&mLodConfig->advanced.outsideWalkAngle, 1); - } - - size_t LodConfigSerializer::calcLodAdvancedInfoSize() - { - size_t size = calcChunkHeaderSize(); - - // mLodConfig->advanced.useCompression - size += sizeof(bool); - // mLodConfig->advanced.useVertexNormals - size += sizeof(bool); - // mLodConfig->advanced.useBackgroundQueue - size += sizeof(bool); - // mLodConfig->advanced.outsideWeight - size += sizeof(float); - // mLodConfig->advanced.outsideWalkAngle - size += sizeof(float); - - return size; - } - - void LodConfigSerializer::writeLodProfile() - { - if(mLodConfig->advanced.profile.empty()){ - return; - } - writeChunkHeader(LCCID_PROFILE, calcLodProfileSize()); - uint32 size = static_cast(mLodConfig->advanced.profile.size()); - writeInts(&size, 1); - LodProfile::iterator it = mLodConfig->advanced.profile.begin(); - LodProfile::iterator itEnd = mLodConfig->advanced.profile.end(); - for(;it != itEnd; it++){ - writeObject(it->src); - writeObject(it->dst); - writeFloats(&it->cost, 1); - } - } - - size_t LodConfigSerializer::calcLodProfileSize() - { - if(mLodConfig->advanced.profile.empty()){ - return 0; - } - // Vector3, LodProfile::ProfiledVertex::src - size_t profiledVertexSize = sizeof(float) * 3; - - // Vector3, LodProfile::ProfiledVertex::dst - profiledVertexSize += sizeof(float) * 3; - - // LodProfile::ProfiledVertex::cost - profiledVertexSize += sizeof(float); - - - size_t size = calcChunkHeaderSize(); - - // mLodConfig->advanced.profile->data.size() - size += sizeof(uint32); - - size += profiledVertexSize * mLodConfig->advanced.profile.size(); - - return size; - } - -} diff --git a/Components/MeshLodGenerator/src/OgreLodData.cpp b/Components/MeshLodGenerator/src/OgreLodData.cpp deleted file mode 100644 index bfdff06a838..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodData.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ -#include "OgreMeshLodPrecompiledHeaders.h" - -namespace Ogre -{ -// Use float limits instead of Real limits, because LodConfigSerializer may convert them to float. -const Real LodData::NEVER_COLLAPSE_COST = std::numeric_limits::max(); -const Real LodData::UNINITIALIZED_COLLAPSE_COST = std::numeric_limits::infinity(); - -void LodData::Vertex::addEdge( const LodData::Edge& edge ) -{ - OgreAssert(edge.dst != this, ""); - VEdges::iterator it; - it = edges.add(edge); - if (it == edges.end()) { - edges.back().refCount = 1; - } else { - it->refCount++; - } -} - -void LodData::Vertex::removeEdge( const LodData::Edge& edge ) -{ - VEdges::iterator it = edges.findExists(edge); - if (it->refCount == 1) { - edges.remove(it); - } else { - it->refCount--; - } -} - -bool LodData::VertexEqual::operator() (const LodData::Vertex* lhs, const LodData::Vertex* rhs) const -{ - return lhs->position == rhs->position; -} - -size_t LodData::VertexHash::operator() (const LodData::Vertex* v) const -{ - // Stretch the values to an integer grid. - Real stretch = (Real)0x7fffffff / mGen->mMeshBoundingSphereRadius; - int hash = (int)(v->position.x * stretch); - hash ^= (int)(v->position.y * stretch) * 0x100; - hash ^= (int)(v->position.z * stretch) * 0x10000; - return (size_t)hash; -} - -unsigned int LodData::Line::getVertexID(const LodData::Vertex* v) const -{ - for (int i = 0; i < 2; i++) { - if (vertex[i] == v) { - return vertexID[i]; - } - } - OgreAssert(0, ""); - return 0; -} -bool LodData::Line::isMalformed() -{ - return vertex[0] == vertex[1]; -} - -unsigned int LodData::Triangle::getVertexID(const LodData::Vertex* v) const -{ - for (int i = 0; i < 3; i++) { - if (vertex[i] == v) { - return vertexID[i]; - } - } - OgreAssert(0, ""); - return 0; -} -bool LodData::Triangle::isMalformed() -{ - return vertex[0] == vertex[1] || vertex[0] == vertex[2] || vertex[1] == vertex[2]; -} - -LodData::Edge::Edge(LodData::Vertex* destination) : - dst(destination) -#if OGRE_DEBUG_MODE - , collapseCost(UNINITIALIZED_COLLAPSE_COST) -#endif - , refCount(0) -{ - -} - -LodData::Edge::Edge(const LodData::Edge& b) -{ - *this = b; -} - -bool LodData::Edge::operator< (const LodData::Edge& other) const -{ - return (size_t) dst < (size_t) other.dst; // Comparing pointers for uniqueness. -} - -LodData::Edge& LodData::Edge::operator= (const LodData::Edge& b) -{ - dst = b.dst; - collapseCost = b.collapseCost; - refCount = b.refCount; - return *this; -} - -bool LodData::Edge::operator== (const LodData::Edge& other) const -{ - return dst == other.dst; -} - -} diff --git a/Components/MeshLodGenerator/src/OgreLodInputProvider.cpp b/Components/MeshLodGenerator/src/OgreLodInputProvider.cpp deleted file mode 100644 index f7aa892ff6e..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodInputProvider.cpp +++ /dev/null @@ -1,364 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#include "OgreMeshLodPrecompiledHeaders.h" - -namespace Ogre -{ -#if OGRE_DEBUG_MODE - static void printTriangle(LodData::Triangle* triangle, std::ostream& str) - { - for (int i = 0; i < 3; i++) { - str << (i + 1) << ". vertex position: (" - << triangle->vertex[i]->position.x << ", " - << triangle->vertex[i]->position.y << ", " - << triangle->vertex[i]->position.z << ") " - << "vertex ID: " << triangle->vertexID[i] << std::endl; - } - } -#endif - - static bool isDuplicateTriangle(LodData::Triangle* triangle, LodData::Triangle* triangle2) - { - for (auto & i : triangle->vertex) { - if (i != triangle2->vertex[0] || - i != triangle2->vertex[1] || - i != triangle2->vertex[2]) { - return false; - } - } - return true; - } - - static LodData::Triangle* isDuplicateTriangle(LodData::Triangle* triangle) - { - // duplicate triangle detection (where all vertices has the same position) - LodData::VTriangles::iterator itEnd = triangle->vertex[0]->triangles.end(); - LodData::VTriangles::iterator it = triangle->vertex[0]->triangles.begin(); - for (; it != itEnd; ++it) { - LodData::Triangle* t = *it; - if (isDuplicateTriangle(triangle, t)) { - return *it; - } - } - return NULL; - } - - static void addTriangleToEdges(LodData* data, LodData::Triangle* triangle) - { - if(MESHLOD_QUALITY >= 3) { - LodData::Triangle* duplicate = isDuplicateTriangle(triangle); - if (duplicate != NULL) { -#if OGRE_DEBUG_MODE - std::stringstream str; - str << "In " << data->mMeshName << " duplicate triangle found." << std::endl; - str << "Triangle " << LodData::getVectorIDFromPointer(data->mTriangleList, triangle) << " positions:" << std::endl; - printTriangle(triangle, str); - str << "Triangle " << LodData::getVectorIDFromPointer(data->mTriangleList, duplicate) << " positions:" << std::endl; - printTriangle(duplicate, str); - str << "Triangle " << LodData::getVectorIDFromPointer(data->mTriangleList, triangle) << " will be excluded from Lod level calculations."; - LogManager::getSingleton().stream() << str.str(); -#endif - triangle->isRemoved = true; - data->mIndexBufferInfoList[triangle->submeshID].indexCount -= 3; - return; - } - } - for (auto & i : triangle->vertex) { - i->triangles.addNotExists(triangle); - } - for (int i = 0; i < 3; i++) { - for (int n = 0; n < 3; n++) { - if (i != n) { - triangle->vertex[i]->addEdge(LodData::Edge(triangle->vertex[n])); - } - } - } - } - - static void addLineToVertices(LodData* data, LodData::Line* line) - { - for (auto & i : line->vertex) { - i->lines.addNotExists(line); - } - } - - inline size_t getTriangleCount(RenderOperation::OperationType renderOp, size_t indexCount) - { - if(renderOp == RenderOperation::OT_TRIANGLE_LIST) - return indexCount / 3; - else if(renderOp == RenderOperation::OT_TRIANGLE_STRIP || renderOp == RenderOperation::OT_TRIANGLE_FAN) - return indexCount >= 3 ? indexCount - 2 : 0; - return 0; - } - - inline size_t getLineCount(RenderOperation::OperationType renderOp, size_t indexCount) - { - if(renderOp == RenderOperation::OT_LINE_LIST) - return indexCount / 2; - else if(renderOp == RenderOperation::OT_LINE_STRIP) - return indexCount >= 2 ? indexCount - 1 : 0; - return 0; - } - - void LodInputProvider::initData( LodData* data ) - { - tuneContainerSize(data); - initialize(data); - } - void LodInputProvider::tuneContainerSize(LodData* data) - { - // Get Vertex count for container tuning. - bool sharedVerticesAdded = false; - size_t triangleCount = 0; - size_t lineCount = 0; - size_t vertexCount = 0; - size_t vertexLookupSize = 0; - size_t sharedVertexLookupSize = 0; - size_t submeshCount = getSubMeshCount(); - for (size_t i = 0; i < submeshCount; i++) { - triangleCount += getTriangleCount(getSubMeshRenderOp(i), getSubMeshIndexCount(i)); - lineCount += getLineCount(getSubMeshRenderOp(i), getSubMeshIndexCount(i)); - if (!getSubMeshUseSharedVertices(i)) { - size_t count = getSubMeshOwnVertexCount(i); - vertexLookupSize = std::max(vertexLookupSize, count); - vertexCount += count; - } else if (!sharedVerticesAdded) { - sharedVerticesAdded = true; - sharedVertexLookupSize = getMeshSharedVertexCount(); - vertexCount += sharedVertexLookupSize; - } - } - - // Tune containers: - data->mUniqueVertexSet.rehash(4 * vertexCount); // less then 0.25 item/bucket for low collision rate - - data->mTriangleList.reserve(triangleCount); - data->mLineList.reserve(lineCount); - - data->mVertexList.reserve(vertexCount); - mSharedVertexLookup.reserve(sharedVertexLookupSize); - mVertexLookup.reserve(vertexLookupSize); - data->mIndexBufferInfoList.resize(submeshCount); - } - void LodInputProvider::initialize( LodData* data ) - { -#if OGRE_DEBUG_MODE - data->mMeshName = getMeshName(); -#endif - data->mMeshBoundingSphereRadius = getMeshBoundingSphereRadius(); - size_t submeshCount = getSubMeshCount(); - for (size_t i = 0; i < submeshCount; ++i) { - addVertexData(data, i); - addIndexData(data, i); - } - - // These were only needed for addIndexData() and addVertexData(). - mSharedVertexLookup.clear(); - mVertexLookup.clear(); - } - - - template - void addTriangleIndices(LodData* data, IndexType* iPos, const IndexType* iEnd, - std::vector& lookup, ushort submeshID, - RenderOperation::OperationType renderOp) - { - IndexType i0 = iPos[0], i1 = iPos[1], i2 = iPos[2]; - unsigned inc = (renderOp==RenderOperation::OT_TRIANGLE_LIST) ? 3 : 1; - unsigned triangleIdx = 0; - - // Loop through all triangles and connect them to the vertices. - for (iPos += (3 - inc); iPos < iEnd; iPos += inc, ++triangleIdx) { - // It should never reallocate or every pointer will be invalid. - OgreAssertDbg(data->mTriangleList.capacity() > data->mTriangleList.size(), ""); - data->mTriangleList.push_back(LodData::Triangle()); - LodData::Triangle* tri = &data->mTriangleList.back(); - tri->isRemoved = false; - tri->submeshID = submeshID; - - if(triangleIdx > 0) - { - switch(renderOp) - { - case RenderOperation::OT_TRIANGLE_LIST: - i0 = iPos[0]; - i1 = iPos[1]; - i2 = iPos[2]; - break; - case RenderOperation::OT_TRIANGLE_STRIP: - if(triangleIdx & 1) - i0 = i2; - else - i1 = i2; - i2 = iPos[0]; - break; - case RenderOperation::OT_TRIANGLE_FAN: - i1 = i2; - i2 = iPos[0]; - break; - default: - OgreAssert(false, "Invalid RenderOperation"); - break; - } - } - - // Invalid index: Index is bigger then vertex buffer size. - OgreAssertDbg(i0 < lookup.size() && i1 < lookup.size() && i2 < lookup.size(), ""); - tri->vertexID[0] = i0; - tri->vertexID[1] = i1; - tri->vertexID[2] = i2; - tri->vertex[0] = lookup[i0]; - tri->vertex[1] = lookup[i1]; - tri->vertex[2] = lookup[i2]; - - if (tri->isMalformed()) { -#if OGRE_DEBUG_MODE - std::stringstream str; - str << "In " << data->mMeshName << " malformed triangle found with ID: " << LodData::getVectorIDFromPointer(data->mTriangleList, tri) << ". " << - std::endl; - printTriangle(tri, str); - str << "It will be excluded from Lod level calculations."; - LogManager::getSingleton().stream() << str.str(); -#endif - tri->isRemoved = true; - data->mIndexBufferInfoList[tri->submeshID].indexCount -= 3; - continue; - } - tri->computeNormal(); - addTriangleToEdges(data, tri); - } - } - - template - void addLineIndices(LodData* data, IndexType* iPos, const IndexType* iEnd, - std::vector& lookup, ushort submeshID, - RenderOperation::OperationType renderOp) - { - IndexType i0 = iPos[0], i1 = iPos[1]; - unsigned inc = (renderOp==RenderOperation::OT_LINE_LIST) ? 2 : 1; - unsigned lineIdx = 0; - - // Loop through all lines and connect them to the vertices. - for (iPos += (2 - inc); iPos < iEnd; iPos += inc, ++lineIdx) { - // It should never reallocate or every pointer will be invalid. - OgreAssertDbg(data->mLineList.capacity() > data->mLineList.size(), ""); - data->mLineList.push_back(LodData::Line()); - LodData::Line* line = &data->mLineList.back(); - line->isRemoved = false; - line->submeshID = submeshID; - - if(lineIdx > 0) - { - switch(renderOp) - { - case RenderOperation::OT_LINE_LIST: - i0 = iPos[0]; - i1 = iPos[1]; - break; - case RenderOperation::OT_LINE_STRIP: - i0 = i1; - i1 = iPos[0]; - break; - default: - OgreAssert(false, "Invalid RenderOperation"); - break; - } - } - - // Invalid index: Index is bigger then vertex buffer size. - OgreAssertDbg(i0 < lookup.size() && i1 < lookup.size(), ""); - line->vertexID[0] = i0; - line->vertexID[1] = i1; - line->vertex[0] = lookup[i0]; - line->vertex[1] = lookup[i1]; - - if (line->isMalformed()) { -#if OGRE_DEBUG_MODE - std::stringstream str; - str << "In " << data->mMeshName << " malformed line found with ID: " << LodData::getVectorIDFromPointer(data->mLineList, line) << ". " << - std::endl; -// printLine(tri, str); - str << "It will be excluded from Lod level calculations."; - LogManager::getSingleton().stream() << str.str(); -#endif - line->isRemoved = true; - data->mIndexBufferInfoList[line->submeshID].indexCount -= 2; - continue; - } - addLineToVertices(data, line); - } - } - - void LodInputProvider::addIndexData(LodData* data, size_t subMeshIndex) - { - const IndexData* id = getSubMeshIndexData(subMeshIndex); - - if (!id->indexCount || !id->indexBuffer) { - // Locking a zero length buffer on Linux with nvidia cards fails. - return; - } - - data->mIndexBufferInfoList[subMeshIndex].indexSize = id->indexBuffer->getIndexSize(); - data->mIndexBufferInfoList[subMeshIndex].indexCount = id->indexCount; - - bool useSharedVertexLookup = getSubMeshUseSharedVertices(subMeshIndex); - auto renderOp = getSubMeshRenderOp(subMeshIndex); - VertexLookupList& lookup = useSharedVertexLookup ? mSharedVertexLookup : mVertexLookup; - - // Lock the buffer for reading. - HardwareBufferLockGuard lock(id->indexBuffer, HardwareBuffer::HBL_READ_ONLY); - size_t isize = id->indexBuffer->getIndexSize(); - uchar* iStart = (uchar*)lock.pData + id->indexStart * isize; - uchar* iEnd = iStart + id->indexCount * isize; - - if (renderOp == RenderOperation::OT_TRIANGLE_LIST || - renderOp == RenderOperation::OT_TRIANGLE_STRIP || - renderOp == RenderOperation::OT_TRIANGLE_FAN) - { - if (isize == sizeof(unsigned short)) { - addTriangleIndices(data, (unsigned short*) iStart, (const unsigned short*) iEnd, lookup, subMeshIndex, renderOp); - } else { - // Unsupported index size. - OgreAssert(isize == sizeof(unsigned int), ""); - addTriangleIndices(data, (unsigned int*) iStart, (const unsigned int*) iEnd, lookup, subMeshIndex, renderOp); - } - } - else if (renderOp == RenderOperation::OT_LINE_LIST || - renderOp == RenderOperation::OT_LINE_STRIP) - { - if (isize == sizeof(unsigned short)) { - addLineIndices(data, (unsigned short*) iStart, (const unsigned short*) iEnd, lookup, subMeshIndex, renderOp); - } else { - // Unsupported index size. - OgreAssert(isize == sizeof(unsigned int), ""); - addLineIndices(data, (unsigned int*) iStart, (const unsigned int*) iEnd, lookup, subMeshIndex, renderOp); - } - } - } -} diff --git a/Components/MeshLodGenerator/src/OgreLodInputProviderBuffer.cpp b/Components/MeshLodGenerator/src/OgreLodInputProviderBuffer.cpp deleted file mode 100644 index 17eb005b5a7..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodInputProviderBuffer.cpp +++ /dev/null @@ -1,135 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#include "OgreMeshLodPrecompiledHeaders.h" - -namespace Ogre -{ - LodInputProviderBuffer::LodInputProviderBuffer( MeshPtr mesh ) - { - mBuffer.fillBuffer(mesh); - } - - void LodInputProviderBuffer::addVertexData(LodData* data, size_t subMeshIndex) - { - bool useSharedVertices = getSubMeshUseSharedVertices(subMeshIndex); - - if (useSharedVertices && !mSharedVertexLookup.empty()) { - return; // We already loaded the shared vertex buffer. - } - - VertexLookupList& lookup = useSharedVertices ? mSharedVertexLookup : mVertexLookup; - lookup.clear(); - - LodVertexBuffer& vertexBuffer = useSharedVertices ? mBuffer.sharedVertexBuffer : mBuffer.submesh[subMeshIndex].vertexBuffer; - const Vector3f* pNormalOut = (Vector3f *)vertexBuffer.vertexNormalBuffer->lock(HardwareBuffer::HBL_READ_ONLY); - data->mUseVertexNormals = data->mUseVertexNormals && (pNormalOut != NULL); - - if(!data->mUseVertexNormals) - { - static Vector3f zeroNormal(0, 0, 0); - pNormalOut = &zeroNormal; - } - - // Loop through all vertices and insert them to the Unordered Map. - const Vector3f* pOut = (Vector3f *)vertexBuffer.vertexBuffer->lock(HardwareBuffer::HBL_READ_ONLY); - const Vector3f* pEnd = pOut + vertexBuffer.vertexCount; - for (; pOut < pEnd; pOut++) { - data->mVertexList.push_back({Vector3(*pOut), Vector3(*pNormalOut)}); - LodData::Vertex* v = &data->mVertexList.back(); - std::pair ret; - ret = data->mUniqueVertexSet.insert(v); - if (!ret.second) { - // Vertex position already exists. - data->mVertexList.pop_back(); - v = *ret.first; // Point to the existing vertex. - v->seam = true; - if(data->mUseVertexNormals){ - if(v->normal.x != (*pNormalOut)[0]){ - v->normal += Vector3(*pNormalOut); - if(v->normal.isZeroLength()){ - v->normal = Vector3(1.0, 0.0, 0.0); - } - v->normal.normalise(); - } - pNormalOut++; - } - } else { -#if OGRE_DEBUG_MODE - v->costHeapPosition = data->mCollapseCostHeap.end(); -#endif - v->seam = false; - if(data->mUseVertexNormals){ - v->normal.normalise(); - pNormalOut++; - } - } - lookup.push_back(v); - } - vertexBuffer.vertexBuffer->unlock(); - vertexBuffer.vertexNormalBuffer->unlock(); - } - - const IndexData* LodInputProviderBuffer::getSubMeshIndexData(size_t subMeshIndex) const - { - return &mBuffer.submesh[subMeshIndex].indexBuffer; - } - - const String & LodInputProviderBuffer::getMeshName() - { - return mBuffer.meshName; - } - size_t LodInputProviderBuffer::getMeshSharedVertexCount() - { - return mBuffer.sharedVertexBuffer.vertexCount; - } - float LodInputProviderBuffer::getMeshBoundingSphereRadius() - { - return mBuffer.boundingSphereRadius; - } - size_t LodInputProviderBuffer::getSubMeshCount() - { - return mBuffer.submesh.size(); - } - bool LodInputProviderBuffer::getSubMeshUseSharedVertices(size_t subMeshIndex) - { - return mBuffer.submesh[subMeshIndex].useSharedVertexBuffer; - } - size_t LodInputProviderBuffer::getSubMeshOwnVertexCount(size_t subMeshIndex) - { - return mBuffer.submesh[subMeshIndex].vertexBuffer.vertexCount; - } - size_t LodInputProviderBuffer::getSubMeshIndexCount(size_t subMeshIndex) - { - return mBuffer.submesh[subMeshIndex].indexBuffer.indexCount; - } - RenderOperation::OperationType LodInputProviderBuffer::getSubMeshRenderOp(size_t subMeshIndex) - { - return mBuffer.submesh[subMeshIndex].operationType; - } -} diff --git a/Components/MeshLodGenerator/src/OgreLodInputProviderBuffer.h b/Components/MeshLodGenerator/src/OgreLodInputProviderBuffer.h deleted file mode 100644 index 7f44c650f63..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodInputProviderBuffer.h +++ /dev/null @@ -1,73 +0,0 @@ - -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef _LodInputProviderBuffer_H__ -#define _LodInputProviderBuffer_H__ - -#include "OgreLodPrerequisites.h" -#include "OgreLodInputProvider.h" -#include "OgreLodData.h" -#include "OgreLodBuffer.h" -#include "OgreLogManager.h" -#include "OgreHeaderPrefix.h" - -#include - -namespace Ogre -{ - -class LodInputProviderBuffer : - public LodInputProvider -{ -public: - LodInputProviderBuffer(MeshPtr mesh); - -protected: - LodInputBuffer mBuffer; - - void addVertexData(LodData* data, size_t subMeshIndex) override; - const IndexData* getSubMeshIndexData(size_t subMeshIndex) const override; - - const String & getMeshName() override; - size_t getMeshSharedVertexCount() override; - float getMeshBoundingSphereRadius() override; - - size_t getSubMeshCount() override; - - bool getSubMeshUseSharedVertices(size_t subMeshIndex) override; - size_t getSubMeshOwnVertexCount(size_t subMeshIndex) override; - size_t getSubMeshIndexCount(size_t subMeshIndex) override; - RenderOperation::OperationType getSubMeshRenderOp(size_t subMeshIndex) override; -}; - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/Components/MeshLodGenerator/src/OgreLodInputProviderMesh.cpp b/Components/MeshLodGenerator/src/OgreLodInputProviderMesh.cpp deleted file mode 100644 index 633c00cd9f8..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodInputProviderMesh.cpp +++ /dev/null @@ -1,174 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#include "OgreMeshLodPrecompiledHeaders.h" - -namespace Ogre -{ - LodInputProviderMesh::LodInputProviderMesh( MeshPtr mesh ) : mMesh(mesh) - { - - } - - void LodInputProviderMesh::addVertexData(LodData* data, size_t subMeshIndex) - { - bool useSharedVertices = getSubMeshUseSharedVertices(subMeshIndex); - - if (useSharedVertices && !mSharedVertexLookup.empty()) { - return; // We already loaded the shared vertex buffer. - } - - const SubMesh* submesh = mMesh->getSubMesh(subMeshIndex); - VertexData* vertexData = (submesh->useSharedVertices ? mMesh->sharedVertexData : submesh->vertexData); - - OgreAssert(vertexData->vertexCount != 0, ""); - - // Locate position element and the buffer to go with it. - const VertexElement* elemPos = vertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); - - // Only float supported. - OgreAssert(elemPos->getSize() == 12, ""); - - HardwareVertexBufferSharedPtr vbuf = vertexData->vertexBufferBinding->getBuffer(elemPos->getSource()); - - // Lock the buffer for reading. - unsigned char* vStart = static_cast(vbuf->lock(HardwareBuffer::HBL_READ_ONLY)); - unsigned char* vertex = vStart; - size_t vSize = vbuf->getVertexSize(); - unsigned char* vEnd = vertex + vertexData->vertexCount * vSize; - - VertexLookupList& lookup = useSharedVertices ? mSharedVertexLookup : mVertexLookup; - lookup.clear(); - - HardwareVertexBufferSharedPtr vNormalBuf; - unsigned char* vNormal = NULL; - const VertexElement* elemNormal = vertexData->vertexDeclaration->findElementBySemantic(VES_NORMAL); - - data->mUseVertexNormals &= (elemNormal != NULL); - if(data->mUseVertexNormals){ - if(elemNormal->getSource() == elemPos->getSource()){ - // Don't open the same buffer twice. Just copy the pointer. - vNormalBuf = vbuf; - vNormal = vStart; - } else { - vNormalBuf = vertexData->vertexBufferBinding->getBuffer(elemNormal->getSource()); - vNormal = static_cast(vNormalBuf->lock(HardwareBuffer::HBL_READ_ONLY)); - } - } - - - // Loop through all vertices and insert them to the Unordered Map. - for (; vertex < vEnd; vertex += vSize) { - float* pFloat; - elemPos->baseVertexPointerToElement(vertex, &pFloat); - data->mVertexList.push_back(LodData::Vertex()); - LodData::Vertex* v = &data->mVertexList.back(); - v->position.x = pFloat[0]; - v->position.y = pFloat[1]; - v->position.z = pFloat[2]; - std::pair ret; - ret = data->mUniqueVertexSet.insert(v); - if (!ret.second) { - // Vertex position already exists. - data->mVertexList.pop_back(); - v = *ret.first; // Point to the existing vertex. - v->seam = true; - } else { -#if OGRE_DEBUG_MODE - // Needed for an assert, don't remove it. - v->costHeapPosition = data->mCollapseCostHeap.end(); -#endif - v->seam = false; - } - lookup.push_back(v); - - if(data->mUseVertexNormals){ - elemNormal->baseVertexPointerToElement(vNormal, &pFloat); - if (!ret.second) { - if(v->normal.x != pFloat[0]){ - v->normal.x += pFloat[0]; - v->normal.y += pFloat[1]; - v->normal.z += pFloat[2]; - if(v->normal.isZeroLength()){ - v->normal = Vector3(1.0, 0.0, 0.0); - } - v->normal.normalise(); - } - } else { - v->normal.x = pFloat[0]; - v->normal.y = pFloat[1]; - v->normal.z = pFloat[2]; - v->normal.normalise(); - } - vNormal += vNormalBuf->getVertexSize();; - } - } - vbuf->unlock(); - if(data->mUseVertexNormals && elemNormal->getSource() != elemPos->getSource()){ - vNormalBuf->unlock(); - } - } - - const IndexData* LodInputProviderMesh::getSubMeshIndexData(size_t subMeshIndex) const - { - return mMesh->getSubMesh(subMeshIndex)->indexData; - } - - const String & LodInputProviderMesh::getMeshName() - { - return mMesh->getName(); - } - size_t LodInputProviderMesh::getMeshSharedVertexCount() - { - return mMesh->sharedVertexData->vertexCount; - } - float LodInputProviderMesh::getMeshBoundingSphereRadius() - { - return mMesh->getBoundingSphereRadius(); - } - size_t LodInputProviderMesh::getSubMeshCount() - { - return mMesh->getNumSubMeshes(); - } - bool LodInputProviderMesh::getSubMeshUseSharedVertices(size_t subMeshIndex) - { - return mMesh->getSubMesh(subMeshIndex)->useSharedVertices; - } - size_t LodInputProviderMesh::getSubMeshOwnVertexCount(size_t subMeshIndex) - { - return mMesh->getSubMesh(subMeshIndex)->vertexData->vertexCount; - } - size_t LodInputProviderMesh::getSubMeshIndexCount(size_t subMeshIndex) - { - return mMesh->getSubMesh(subMeshIndex)->indexData->indexCount; - } - RenderOperation::OperationType LodInputProviderMesh::getSubMeshRenderOp(size_t subMeshIndex) - { - return mMesh->getSubMesh(subMeshIndex)->operationType; - } -} diff --git a/Components/MeshLodGenerator/src/OgreLodInputProviderMesh.h b/Components/MeshLodGenerator/src/OgreLodInputProviderMesh.h deleted file mode 100644 index f6e4bcad58e..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodInputProviderMesh.h +++ /dev/null @@ -1,74 +0,0 @@ - -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef _LodInputProviderMesh_H__ -#define _LodInputProviderMesh_H__ - -#include "OgreLodPrerequisites.h" -#include "OgreLodInputProvider.h" -#include "OgreLodData.h" -#include "OgreSharedPtr.h" -#include "OgreLogManager.h" -#include "OgreRenderOperation.h" -#include "OgreHeaderPrefix.h" - -#include - -namespace Ogre -{ - -class LodInputProviderMesh : - public LodInputProvider -{ -public: - LodInputProviderMesh(MeshPtr mesh); - -protected: - MeshPtr mMesh; - - const IndexData* getSubMeshIndexData(size_t subMeshIndex) const override; - void addVertexData(LodData* data, size_t subMeshIndex) override; - - const String & getMeshName() override; - size_t getMeshSharedVertexCount() override; - float getMeshBoundingSphereRadius() override; - - size_t getSubMeshCount() override; - - bool getSubMeshUseSharedVertices(size_t subMeshIndex) override; - size_t getSubMeshOwnVertexCount(size_t subMeshIndex) override; - size_t getSubMeshIndexCount(size_t subMeshIndex) override; - RenderOperation::OperationType getSubMeshRenderOp(size_t subMeshIndex) override; -}; - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/Components/MeshLodGenerator/src/OgreLodOutputProvider.cpp b/Components/MeshLodGenerator/src/OgreLodOutputProvider.cpp deleted file mode 100644 index 32a1b2b302c..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodOutputProvider.cpp +++ /dev/null @@ -1,361 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#include "OgreLodOutputProvider.h" - -namespace Ogre -{ - LodOutputProvider::LodOutputProvider(bool useCompression) - : mUseCompression(useCompression) - , mFirstBufferPass(true) - , mLastIndexBufferID(0) - {} - - void LodOutputProvider::prepare(LodData *data) - { - if (mUseCompression) - { - mFirstBufferPass = true; - mTriangleCacheList.resize(data->mTriangleList.size()); - mLineCacheList.resize(data->mLineList.size()); - } - } - - void LodOutputProvider::finalize(LodData *data) - { - if (mUseCompression) - { - if (!mFirstBufferPass) - { - // Uneven number of Lod levels. We need to bake the last one separately. - bakeUncompressed(data, mLastIndexBufferID); - } - } - } - - void LodOutputProvider::bakeManualLodLevel( LodData* data, String& manualMeshName, int lodIndex) - { - if (mUseCompression && !mFirstBufferPass) - { - // If we are using compression then pairs of lod levels share the same index buffer - // and are both created after the second one is processed. - // If this manual lod level comes after the first of a pair but before the second, - // then we haven't yet created the lod level for that first lod and a slot in the - // vector is missing. Instead of skipping the slot, we decrement the lodIndex here - // so that this manual level still goes at the end of the vector. - // When we eventually do create that first lod level it will get inserted in the - // correct spot, pushing this one into its correct spot. - lodIndex--; - } - - // placeholder dummy - size_t submeshCount = getSubMeshCount(); - - for (size_t i = 0; i < submeshCount; i++) { - createSubMeshLodIndexData(i, lodIndex, nullptr, 0, 0); - } - } - - void LodOutputProvider::bakeLodLevel(LodData* data, int lodIndex) - { - if (mUseCompression) - { - if (mFirstBufferPass) - { - bakeFirstPass(data, lodIndex); - } - else - { - bakeSecondPass(data, lodIndex); - } - mFirstBufferPass = !mFirstBufferPass; - } - else - { - bakeUncompressed(data, lodIndex); - } - } - - inline void writeTriangle(LodData * data, size_t i) - { - if (data->mIndexBufferInfoList[data->mTriangleList[i].submeshID].indexSize == 2) { - for (unsigned int m : data->mTriangleList[i].vertexID) { - *(data->mIndexBufferInfoList[data->mTriangleList[i].submeshID].buf.pshort++) = - static_cast(m); - } - } else { - for (unsigned int m : data->mTriangleList[i].vertexID) { - *(data->mIndexBufferInfoList[data->mTriangleList[i].submeshID].buf.pint++) = - static_cast(m); - } - } - } - - inline void writeLine(LodData * data, size_t i) - { - if (data->mIndexBufferInfoList[data->mLineList[i].submeshID].indexSize == 2) { - for (unsigned int m : data->mLineList[i].vertexID) { - *(data->mIndexBufferInfoList[data->mLineList[i].submeshID].buf.pshort++) = - static_cast(m); - } - } else { - for (unsigned int m : data->mLineList[i].vertexID) { - *(data->mIndexBufferInfoList[data->mLineList[i].submeshID].buf.pint++) = - static_cast(m); - } - } - } - - void LodOutputProvider::bakeUncompressed(LodData* data, int lodIndex) - { - std::vector lockedBuffers; - - size_t submeshCount = getSubMeshCount(); - - // Create buffers. - for (size_t i = 0; i < submeshCount; i++) { - size_t indexCount = data->mIndexBufferInfoList[i].indexCount; - HardwareIndexBufferPtr indexBuffer = createIndexBuffer(indexCount); - - createSubMeshLodIndexData(i, lodIndex, indexBuffer, 0, indexBuffer->getNumIndexes()); - - data->mIndexBufferInfoList[i].buf.pshort = (unsigned short*) indexBuffer->lock(HardwareBuffer::HBL_DISCARD); - - lockedBuffers.push_back(indexBuffer); - } - - // Fill buffers. - size_t triangleCount = data->mTriangleList.size(); - for (size_t i = 0; i < triangleCount; i++) { - if (!data->mTriangleList[i].isRemoved) { - assert(data->mIndexBufferInfoList[data->mTriangleList[i].submeshID].indexCount != 0); - writeTriangle(data, i); - } - } - size_t lineCount = data->mLineList.size(); - for (size_t i = 0; i < lineCount; i++) { - if (!data->mLineList[i].isRemoved) { - assert(data->mIndexBufferInfoList[data->mLineList[i].submeshID].indexCount != 0); - writeLine(data, i); - } - } - - // Close buffers. - for (auto & buffer : lockedBuffers) { - buffer->unlock(); - } - } - - void LodOutputProvider::bakeFirstPass(LodData* data, int lodIndex) - { - size_t submeshCount = getSubMeshCount(); - assert(mTriangleCacheList.size() == data->mTriangleList.size()); - assert(mLineCacheList.size() == data->mLineList.size()); - mLastIndexBufferID = lodIndex; - - for (size_t i = 0; i < submeshCount; i++) { - data->mIndexBufferInfoList[i].prevIndexCount = data->mIndexBufferInfoList[i].indexCount; - data->mIndexBufferInfoList[i].prevOnlyIndexCount = 0; - } - - size_t triangleCount = mTriangleCacheList.size(); - for (size_t i = 0; i < triangleCount; i++) { - mTriangleCacheList[i].vertexChanged = false; - if (!data->mTriangleList[i].isRemoved) { - mTriangleCacheList[i].vertexID[0] = data->mTriangleList[i].vertexID[0]; - mTriangleCacheList[i].vertexID[1] = data->mTriangleList[i].vertexID[1]; - mTriangleCacheList[i].vertexID[2] = data->mTriangleList[i].vertexID[2]; - } - } - - size_t lineCount = mLineCacheList.size(); - for (size_t i = 0; i < lineCount; i++) { - mLineCacheList[i].vertexChanged = false; - if (!data->mLineList[i].isRemoved) { - mLineCacheList[i].vertexID[0] = data->mLineList[i].vertexID[0]; - mLineCacheList[i].vertexID[1] = data->mLineList[i].vertexID[1]; - } - } - } - - void LodOutputProvider::bakeSecondPass(LodData* data, int lodIndex) - { - std::vector lockedBuffers; - - size_t submeshCount = getSubMeshCount(); - assert(mTriangleCacheList.size() == data->mTriangleList.size()); - assert(mLineCacheList.size() == data->mLineList.size()); - assert(lodIndex > mLastIndexBufferID); // Implementation limitation - - // Create buffers. - for (size_t i = 0; i < submeshCount; i++) { - assert(data->mIndexBufferInfoList[i].prevIndexCount >= data->mIndexBufferInfoList[i].indexCount); - assert(data->mIndexBufferInfoList[i].prevIndexCount >= data->mIndexBufferInfoList[i].prevOnlyIndexCount); - - HardwareIndexBufferPtr indexBuffer = createIndexBuffer(data->mIndexBufferInfoList[i].indexCount + data->mIndexBufferInfoList[i].prevOnlyIndexCount); - lockedBuffers.push_back(indexBuffer); - - data->mIndexBufferInfoList[i].buf.pshort = (unsigned short*) indexBuffer->lock(HardwareBuffer::HBL_DISCARD); - - // Set up one Lod - size_t indexCount = std::max(data->mIndexBufferInfoList[i].prevIndexCount, 3u); - createSubMeshLodIndexData(i, mLastIndexBufferID, indexBuffer, 0, indexCount); - - // Set up the other Lod - indexCount = std::max(data->mIndexBufferInfoList[i].indexCount, 3u); - createSubMeshLodIndexData(i, lodIndex, indexBuffer, indexBuffer->getNumIndexes() - indexCount, indexCount); - } - - // Fill buffers. - // Filling will be done in 3 parts. - // 1. prevLod only indices. - size_t triangleCount = mTriangleCacheList.size(); - for (size_t i = 0; i < triangleCount; i++) { - if (mTriangleCacheList[i].vertexChanged) { - assert(data->mIndexBufferInfoList[data->mTriangleList[i].submeshID].prevIndexCount != 0); - assert(mTriangleCacheList[i].vertexID[0] != mTriangleCacheList[i].vertexID[1]); - assert(mTriangleCacheList[i].vertexID[1] != mTriangleCacheList[i].vertexID[2]); - assert(mTriangleCacheList[i].vertexID[2] != mTriangleCacheList[i].vertexID[0]); - writeTriangle(data, i); - } - } - size_t lineCount = mLineCacheList.size(); - for (size_t i = 0; i < lineCount; i++) { - if (mLineCacheList[i].vertexChanged) { - assert(data->mIndexBufferInfoList[data->mLineList[i].submeshID].prevIndexCount != 0); - assert(mLineCacheList[i].vertexID[0] != mLineCacheList[i].vertexID[1]); - writeLine(data, i); - } - } - - // 2. shared indices. - for (size_t i = 0; i < triangleCount; i++) { - if (!data->mTriangleList[i].isRemoved && !mTriangleCacheList[i].vertexChanged) { - assert(mTriangleCacheList[i].vertexID[0] == data->mTriangleList[i].vertexID[0]); - assert(mTriangleCacheList[i].vertexID[1] == data->mTriangleList[i].vertexID[1]); - assert(mTriangleCacheList[i].vertexID[2] == data->mTriangleList[i].vertexID[2]); - - assert(data->mIndexBufferInfoList[data->mTriangleList[i].submeshID].indexCount != 0); - assert(data->mIndexBufferInfoList[data->mTriangleList[i].submeshID].prevIndexCount != 0); - writeTriangle(data, i); - } - } - for (size_t i = 0; i < lineCount; i++) { - if (!data->mLineList[i].isRemoved && !mLineCacheList[i].vertexChanged) { - assert(mLineCacheList[i].vertexID[0] == data->mLineList[i].vertexID[0]); - assert(mLineCacheList[i].vertexID[1] == data->mLineList[i].vertexID[1]); - - assert(data->mIndexBufferInfoList[data->mLineList[i].submeshID].indexCount != 0); - assert(data->mIndexBufferInfoList[data->mLineList[i].submeshID].prevIndexCount != 0); - writeLine(data, i); - } - } - - // 3. curLod indices only. - for (size_t i = 0; i < triangleCount; i++) { - if (!data->mTriangleList[i].isRemoved && mTriangleCacheList[i].vertexChanged) { - assert(data->mIndexBufferInfoList[data->mTriangleList[i].submeshID].indexCount != 0); - writeTriangle(data, i); - } - } - for (size_t i = 0; i < lineCount; i++) { - if (!data->mLineList[i].isRemoved && mLineCacheList[i].vertexChanged) { - assert(data->mIndexBufferInfoList[data->mLineList[i].submeshID].indexCount != 0); - writeLine(data, i); - } - } - - // Close buffers. - for (auto & buffer : lockedBuffers) - { - buffer->unlock(); - } - } - - void LodOutputProvider::triangleRemoved( LodData* data, LodData::Triangle* tri ) - { - if (mUseCompression) - { - triangleChanged(data, tri); - } - } - - void LodOutputProvider::triangleChanged( LodData* data, LodData::Triangle* tri ) - { - if (mUseCompression) - { - assert(!tri->isRemoved); - TriangleCache& cache = mTriangleCacheList[LodData::getVectorIDFromPointer(data->mTriangleList, tri)]; - if(!cache.vertexChanged){ - cache.vertexChanged = true; - data->mIndexBufferInfoList[tri->submeshID].prevOnlyIndexCount += 3; - } - } - } - - void LodOutputProvider::lineRemoved( LodData* data, LodData::Line* line ) - { - if (mUseCompression) - { - lineChanged(data, line); - } - } - - void LodOutputProvider::lineChanged( LodData* data, LodData::Line* line ) - { - if (mUseCompression) - { - assert(!line->isRemoved); - LineCache& cache = mLineCacheList[LodData::getVectorIDFromPointer(data->mLineList, line)]; - if(!cache.vertexChanged){ - cache.vertexChanged = true; - data->mIndexBufferInfoList[line->submeshID].prevOnlyIndexCount += 2; - } - } - } - - HardwareIndexBufferPtr LodOutputProvider::createIndexBuffer(size_t indexCount) - { - //If the index is empty we need to create a "dummy" triangle, just to keep the index buffer from being empty. - //The main reason for this is that the OpenGL render system will crash with a segfault unless the index has some values. - //This should hopefully be removed with future versions of Ogre. The most preferred solution would be to add the - //ability for a submesh to be excluded from rendering for a given LOD (which isn't possible currently 2012-12-09). - HardwareIndexBufferPtr buffer = createIndexBufferImpl(indexCount ? indexCount : 3); - - //Check if we should fill it with a "dummy" triangle. - if (indexCount == 0) - { - void * addr = buffer->lock(HardwareBuffer::HBL_DISCARD); - memset(addr, 0, 3 * buffer->getIndexSize()); - buffer->unlock(); - } - - return buffer; - } - -} diff --git a/Components/MeshLodGenerator/src/OgreLodOutputProviderBuffer.cpp b/Components/MeshLodGenerator/src/OgreLodOutputProviderBuffer.cpp deleted file mode 100644 index c094c26cc39..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodOutputProviderBuffer.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#include "OgreMeshLodPrecompiledHeaders.h" -#include "OgreDefaultHardwareBufferManager.h" - -namespace Ogre -{ - void LodOutputProviderBuffer::prepare( LodData* data ) - { - LodOutputProvider::prepare(data); - - mBuffer.submesh.resize(data->mIndexBufferInfoList.size()); - } - - void LodOutputProviderBuffer::inject() - { - ushort submeshCount = Math::uint16Cast(mBuffer.submesh.size()); - OgreAssert(mMesh->getNumSubMeshes() == submeshCount, ""); - mMesh->removeLodLevels(); - for (unsigned short i = 0; i < submeshCount; i++) { - SubMesh::LODFaceList& lods = mMesh->getSubMesh(i)->mLodFaceList; - typedef std::vector GenBuffers; - GenBuffers& buffers = mBuffer.submesh[i].genIndexBuffers; - - size_t buffCount = buffers.size(); - for (size_t n=0; n= 0, ""); - lods.push_back(OGRE_NEW IndexData()); - lods.back()->indexStart = buff.indexStart; - lods.back()->indexCount = buff.indexCount; - if(buff.indexBuffer->getNumIndexes() != 0) { - if(n > 0 && buffers[n-1].indexBuffer == buff.indexBuffer){ - lods.back()->indexBuffer = (*(++lods.rbegin()))->indexBuffer; - } else { - lods.back()->indexBuffer = mMesh->getHardwareBufferManager()->createIndexBuffer( - buff.indexBuffer->getType(), buff.indexBuffer->getNumIndexes(), - mMesh->getIndexBufferUsage(), mMesh->isIndexBufferShadowed()); - lods.back()->indexBuffer->copyData(*buff.indexBuffer); - } - } - } - } - } - - size_t LodOutputProviderBuffer::getSubMeshCount() - { - return mBuffer.submesh.size(); - } - - HardwareIndexBufferPtr LodOutputProviderBuffer::createIndexBufferImpl(size_t indexCount) - { - auto indexType = indexCount - 1 <= std::numeric_limits::max() ? HardwareIndexBuffer::IT_16BIT : HardwareIndexBuffer::IT_32BIT; - DefaultHardwareBufferManagerBase bfrMgr; - return bfrMgr.createIndexBuffer(indexType, indexCount, HBU_CPU_ONLY); - } - - void LodOutputProviderBuffer::createSubMeshLodIndexData(size_t subMeshIndex, int lodIndex, const HardwareIndexBufferPtr & indexBuffer, size_t indexStart, size_t indexCount) - { - auto& lods = mBuffer.submesh[subMeshIndex].genIndexBuffers; - lods.reserve(lods.size() + 1); - IndexData * curLod; - - // I don't know what the negative lodIndex should mean but this logic - // was present in the original code. - if (lodIndex < 0) - { - lods.push_back(IndexData()); - curLod = &lods.back(); - } - else - { - curLod = &*lods.insert(lods.begin() + lodIndex, IndexData()); - } - - curLod->indexStart = indexStart; - curLod->indexCount = indexCount; - curLod->indexBuffer = indexBuffer; - } -} diff --git a/Components/MeshLodGenerator/src/OgreLodOutputProviderBuffer.h b/Components/MeshLodGenerator/src/OgreLodOutputProviderBuffer.h deleted file mode 100644 index 223e58317c6..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodOutputProviderBuffer.h +++ /dev/null @@ -1,66 +0,0 @@ - -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef _LodOutputProviderBuffer_H__ -#define _LodOutputProviderBuffer_H__ - -#include "OgreLodPrerequisites.h" -#include "OgreLodOutputProvider.h" -#include "OgreLodBuffer.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - -class LodOutputProviderBuffer : - public LodOutputProvider -{ -public: - LodOutputProviderBuffer(MeshPtr mesh, bool useCompression = false) - : LodOutputProvider(useCompression) - , mMesh(mesh) - {} - void prepare(LodData* data) override; - void inject() override; -protected: - MeshPtr mMesh; - LodOutputBuffer mBuffer; - - size_t getSubMeshCount() override; - - HardwareIndexBufferPtr createIndexBufferImpl(size_t indexCount) override; - - void createSubMeshLodIndexData(size_t subMeshIndex, int lodIndex, const HardwareIndexBufferPtr & indexBuffer, size_t indexStart, size_t indexCount) override; -}; - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/Components/MeshLodGenerator/src/OgreLodOutputProviderMesh.cpp b/Components/MeshLodGenerator/src/OgreLodOutputProviderMesh.cpp deleted file mode 100644 index 57c3d77fe78..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodOutputProviderMesh.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#include "OgreMeshLodPrecompiledHeaders.h" - -namespace Ogre -{ - - void LodOutputProviderMesh::prepare( LodData* data ) - { - LodOutputProvider::prepare(data); - - size_t submeshCount = mMesh->getNumSubMeshes(); - - // Create buffers. - for (size_t i = 0; i < submeshCount; i++) { - SubMesh::LODFaceList& lods = mMesh->getSubMesh(i)->mLodFaceList; - lods.resize(1); - } - } - - size_t LodOutputProviderMesh::getSubMeshCount() - { - return mMesh->getNumSubMeshes(); - } - - HardwareIndexBufferPtr LodOutputProviderMesh::createIndexBufferImpl(size_t indexCount) - { - auto indexType = indexCount - 1 <= std::numeric_limits::max() ? HardwareIndexBuffer::IT_16BIT : HardwareIndexBuffer::IT_32BIT; - - return mMesh->getHardwareBufferManager()->createIndexBuffer(indexType, indexCount, mMesh->getIndexBufferUsage(), mMesh->isIndexBufferShadowed()); - } - - void LodOutputProviderMesh::createSubMeshLodIndexData(size_t subMeshIndex, int lodIndex, const HardwareIndexBufferPtr & indexBuffer, size_t indexStart, size_t indexCount) - { - IndexData* curLod = OGRE_NEW IndexData(); - SubMesh::LODFaceList& lods = mMesh->getSubMesh(subMeshIndex)->mLodFaceList; - lods.insert(lods.begin() + lodIndex, curLod); - - curLod->indexStart = 0; - curLod->indexCount = indexCount; - curLod->indexBuffer = indexBuffer; - } -} diff --git a/Components/MeshLodGenerator/src/OgreLodOutputProviderMesh.h b/Components/MeshLodGenerator/src/OgreLodOutputProviderMesh.h deleted file mode 100644 index 2e1b693bc9b..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodOutputProviderMesh.h +++ /dev/null @@ -1,65 +0,0 @@ - -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#ifndef _LodOutputProviderMesh_H__ -#define _LodOutputProviderMesh_H__ - -#include "OgreLodPrerequisites.h" -#include "OgreLodOutputProvider.h" -#include "OgreSharedPtr.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - -class LodOutputProviderMesh : - public LodOutputProvider -{ -public: - LodOutputProviderMesh(MeshPtr mesh, bool useCompression = false) - : LodOutputProvider(useCompression) - , mMesh(mesh) - {} - void prepare(LodData* data) override; - -protected: - MeshPtr mMesh; - - size_t getSubMeshCount() override; - - HardwareIndexBufferPtr createIndexBufferImpl(size_t indexCount) override; - - void createSubMeshLodIndexData(size_t subMeshIndex, int lodIndex, const HardwareIndexBufferPtr & indexBuffer, size_t indexStart, size_t indexCount) override; -}; - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/Components/MeshLodGenerator/src/OgreLodOutsideMarker.cpp b/Components/MeshLodGenerator/src/OgreLodOutsideMarker.cpp deleted file mode 100644 index 7246963ede0..00000000000 --- a/Components/MeshLodGenerator/src/OgreLodOutsideMarker.cpp +++ /dev/null @@ -1,581 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreMeshLodPrecompiledHeaders.h" - -namespace Ogre -{ - -LodOutsideMarker::LodOutsideMarker(LodData::VertexList & vertexList, Real boundingSphereRadius, Real walkAngle) : - mEpsilon(boundingSphereRadius * std::numeric_limits::epsilon() * (Real)4.0), // How much floating point math error you have for equal values. This may depend on compiler flags. - mVertexListOrig(vertexList), - mWalkAngle(walkAngle) -{ - assert(!vertexList.empty()); - assert(mWalkAngle >= -1.0001f && mWalkAngle <= 1.0001f); // dot product range - assert(boundingSphereRadius > 0.0f); // invalid meshes are having a bounding sphere radius of 0.0! -} - -void LodOutsideMarker::markOutside() -{ - generateHull(); - markVertices(); -} - -void LodOutsideMarker::generateHull() -{ - initHull(); - { - for (auto & t : mHull) { - if (!t.removed) { - CHVertex* furthestVertex = getFurthestVertex(&t); - if (!furthestVertex) { - continue; - } - addVertex(furthestVertex); - } - } - } - cleanHull(); -} - -void LodOutsideMarker::initHull() -{ - mHull.clear(); - mHull.reserve(mVertexListOrig.size()); - mOutsideData.clear(); - OutsideDataList::iterator itOut, itOutEnd; - mOutsideData.resize(mVertexListOrig.size()); - itOut = mOutsideData.begin(); - itOutEnd = mOutsideData.end(); - for (; itOut != itOutEnd; itOut++) { - // reset output variables - itOut->isOuterWallVertex = false; - itOut->isInsideHull = false; - } - // We need to find 4 vertices, which are on the convex hull to start the algorithm. - CHVertex* vertex[4] = { NULL, NULL, NULL, NULL }; - - { - // Get 1. vertex: minimum y vertex - Real miny = std::numeric_limits::max(); - LodData::VertexList::iterator v, vEnd; - v = mVertexListOrig.begin(); - vEnd = mVertexListOrig.end(); - for (; v != vEnd; v++) { - Vector3& pos = v->position; - if (pos.y < miny) { - miny = pos.y; - vertex[0] = &*v; - } - } - assert(vertex[0]); // Vertex not found! - } - - { - // Get 2. vertex: furthest from 1. vertex - Real maxdist = 0.0; - LodData::VertexList::iterator v, vEnd; - v = mVertexListOrig.begin(); - vEnd = mVertexListOrig.end(); - for (; v != vEnd; v++) { - Real dist = vertex[0]->position.squaredDistance(v->position); - if (dist > maxdist) { - maxdist = dist; - vertex[1] = &*v; - } - } - assert(vertex[1]); // Vertex not found! - } - - { - // Get 3. vertex: furthest from 1. vertex and 2. vertex - Real maxdist = 0.0; - LodData::VertexList::iterator v, vEnd; - v = mVertexListOrig.begin(); - vEnd = mVertexListOrig.end(); - for (; v != vEnd; v++) { - Real dist = getPointToLineSqraredDistance(vertex[0], vertex[1], &*v); - if (dist > maxdist) { - maxdist = dist; - vertex[2] = &*v; - } - } - assert(vertex[2]); // Vertex not found! - } - - { - // Get 4. vertex: furthest from 1-2-3 triangle - Real maxdist = 0.0f; - Plane plane(vertex[0]->position, vertex[1]->position, vertex[2]->position); - plane.normalise(); - LodData::VertexList::iterator v, vEnd; - v = mVertexListOrig.begin(); - vEnd = mVertexListOrig.end(); - for (; v != vEnd; v++) { - Real dist = std::abs(plane.getDistance(v->position)); - if (dist > maxdist) { - maxdist = dist; - vertex[3] = &*v; - } - } - assert(vertex[3]); // Vertex not found! - } - - // Volume should be bigger than 0, so that we can guarantee that the centroid point is inside the hull - assert(getTetrahedronVolume(vertex[0], vertex[1], vertex[2], vertex[3]) > mEpsilon); - // Centroid = (a + b + c + d) / 4 - mCentroid = vertex[0]->position + vertex[1]->position + vertex[2]->position + vertex[3]->position; - mCentroid /= 4.0f; - - // Mark vertices, so that they will not be processed again. - getOutsideData(vertex[0])->isInsideHull = true; - getOutsideData(vertex[1])->isInsideHull = true; - getOutsideData(vertex[2])->isInsideHull = true; - getOutsideData(vertex[3])->isInsideHull = true; - - // Create the triangles - createTriangle(vertex[0], vertex[1], vertex[2]); - createTriangle(vertex[0], vertex[1], vertex[3]); - createTriangle(vertex[0], vertex[2], vertex[3]); - createTriangle(vertex[1], vertex[2], vertex[3]); -} - -void LodOutsideMarker::createTriangle( CHVertex* v1, CHVertex* v2, CHVertex* v3 ) -{ - CHTriangle tri; - tri.removed = false; - tri.vertex[0] = v1; - tri.vertex[1] = v2; - tri.vertex[2] = v3; - tri.computeNormal(); - if (isVisible(&tri, mCentroid)) { - std::swap(tri.vertex[0], tri.vertex[1]); - tri.computeNormal(); - } - mHull.push_back(tri); -} - -Real LodOutsideMarker::getPointToLineSqraredDistance(CHVertex* x1, CHVertex* x2, CHVertex* p) -{ - Real up = ((x2->position - x1->position).crossProduct(x1->position - p->position)).squaredLength(); - Real down = (x2->position - x1->position).squaredLength(); - return up / down; -} - -Real LodOutsideMarker::getTetrahedronVolume(CHVertex* a, CHVertex* b, CHVertex* c, CHVertex* d) -{ - // V = |(a-d)*[(b-d)x(c-d)]| / 6 - return std::abs((a->position - d->position).dotProduct((b->position - d->position).crossProduct(c->position - d->position))) / 6.0f; -} - -LodOutsideMarker::CHVertex* LodOutsideMarker::getFurthestVertex(CHTriangle* tri) -{ - // Find the furthest vertex from triangle plane towards the facing direction. - CHVertex* furthestVertex = NULL; - Real furthestDistance = 0; - Plane plane(tri->normal, -tri->normal.dotProduct(tri->vertex[0]->position)); - plane.normalise(); - LodData::VertexList::iterator v, vEnd; - v = mVertexListOrig.begin(); - vEnd = mVertexListOrig.end(); - for (; v != vEnd; v++) { - if (getOutsideData(&*v)->isInsideHull) { - continue; - } - Real dist = plane.getDistance(v->position); - if (dist > furthestDistance) { - furthestDistance = dist; - furthestVertex = &*v; - } - } - return furthestVertex; -} - -size_t LodOutsideMarker::addVertex( CHVertex* vertex ) -{ - getOutsideData(vertex)->isInsideHull = true; - // We use class members for triangles and edges only to prevent allocation. - mVisibleTriangles.clear(); - mEdges.clear(); - getVisibleTriangles(vertex, mVisibleTriangles); // get the hull triangles, which are facing the vertex. - if (mVisibleTriangles.empty()) { - return 0; // It's inside the Hull. - } - getHorizon(mVisibleTriangles, mEdges); // Returns the edges of a circle around the triangles. Also removes the triangles - fillHorizon(mEdges, vertex); // Creates triangles from the edges towards the vertex. - return mEdges.size(); -} - -void LodOutsideMarker::getVisibleTriangles( const CHVertex* target, CHTrianglePList& visibleTriangles ) -{ - - CHTriangleList::iterator it = mHull.begin(); - CHTriangleList::iterator itEnd = mHull.end(); - for (; it != itEnd; it++) { - if (it->removed) { - continue; - } - Real dot1 = it->normal.dotProduct(it->vertex[0]->position); - Real dot2 = it->normal.dotProduct(target->position); - if(std::abs(dot2 - dot1) <= mEpsilon) { - //Special case: The vertex is on the plane of the triangle - //mVisibleTriangles.push_back(&*it); - if (isInsideTriangle(target->position, *it)) { - // Vertex is inside of a convex hull triangle. - mVisibleTriangles.clear(); - return; - } else { - // If the vertex is outside, then we should add it to the hull. - visibleTriangles.push_back(&*it); - } - } else if (dot1 < dot2) { - visibleTriangles.push_back(&*it); - } - } -} - -void LodOutsideMarker::addEdge(CHEdgeList& edges, CHVertex* a, CHVertex* b) -{ - // We need undirectional edges, so we sort the vertices by their pointer like integers. - // This is needed, because we want to remove edges which were inside multiple triangles, - // because those are not on the horizon. - if (a <= b) { - edges.push_back(CHEdgeList::value_type(a, b)); - } else { - edges.push_back(CHEdgeList::value_type(b, a)); - } -} - -bool LodOutsideMarker::isInsideTriangle(const Vector3& ptarget, const CHTriangle& tri){ - - // The idea is that if all angle is smaller to that point, than it should be inside. - // NOTE: We assume that the vertex is on the triangle plane! - - const Vector3& p0 = tri.vertex[0]->position; - const Vector3& p1 = tri.vertex[1]->position; - const Vector3& p2 = tri.vertex[2]->position; - const Vector3& n = tri.normal; - - bool b0, b1, b2; - - // It should not contain malformed triangles! - assert(!isSamePosition(p0, p1) && !isSamePosition(p1, p2) && !isSamePosition(p2, p0)); - - { - Real d0 = pointToLineDir(ptarget, p0, p1, p2, n); - if (std::abs(d0) <= mEpsilon){ - //Vertex is on the edge, so we need to compare length. - return isInsideLine(ptarget, p0, p1); - } - b0 = d0 < 0.0f; - } - - { - Real d1 = pointToLineDir(ptarget, p1, p2, p0, n); - if (std::abs(d1) <= mEpsilon){ - //Vertex is on the edge, so we need to compare length. - return isInsideLine(ptarget, p1, p2); - } - b1 = d1 < 0.0f; - } - - if (b0 != b1) { - return false; - } - - { - Real d2 = pointToLineDir(ptarget, p2, p0, p1, n); - if (std::abs(d2) <= mEpsilon){ - //Vertex is on the edge, so we need to compare length. - return isInsideLine(ptarget, p2, p0); - } - b2 = d2 < 0.0f; - } - - return (b1 == b2); -} - -bool LodOutsideMarker::isSamePosition( const Vector3& p0, const Vector3& p1 ) -{ - return (std::abs(p0.x - p1.x) <= mEpsilon && std::abs(p0.y - p1.y) <= mEpsilon && std::abs(p0.z - p1.z) <= mEpsilon); -} - -Real LodOutsideMarker::pointToLineDir(const Vector3& ptarget, const Vector3& p0, const Vector3& p1, const Vector3& p2, const Vector3& n) -{ - return n.crossProduct(p1 - p0).dotProduct(ptarget - p0); -} - -bool LodOutsideMarker::isInsideLine( const Vector3& ptarget, const Vector3& p0, const Vector3& p1 ) -{ - // This function returns whether ptarget is between p0 and p1. - // It is outside if: - // -the dir vector is in the opposite direction - // -the length is smaller. - // -ptarget is not p0 or p1 - // NOTE: We assume that the 3 points are on the same line! - - Vector3 v1 = p1 - p0; - Vector3 v2 = ptarget - p0; - Real len1 = v1.squaredLength(); - Real len2 = v2.squaredLength(); - Real dot = v1.dotProduct(v2); - return isSamePosition(ptarget, p1) || ( - dot > 0.0 // Same direction - && len1 > len2); // Shorter -} - -void LodOutsideMarker::getHorizon( const CHTrianglePList& tri, CHEdgeList& horizon) -{ - // Create edge list and remove triangles - CHTrianglePList::const_iterator it2 = tri.begin(); - CHTrianglePList::const_iterator it2End = tri.end(); - for (; it2 != it2End; it2++) { - addEdge(horizon, (*it2)->vertex[0], (*it2)->vertex[1]); - addEdge(horizon, (*it2)->vertex[1], (*it2)->vertex[2]); - addEdge(horizon, (*it2)->vertex[2], (*it2)->vertex[0]); - (*it2)->removed = true; - } - // inside edges are twice in the edge list, because it was added by 2 triangles. - assert(!horizon.empty()); - std::sort(horizon.begin(), horizon.end()); - size_t end = horizon.size(); - size_t first = 0; - size_t last = 0; - size_t result = 0; - // Removes edges, which are 2+ times in the sorted edge list. - while (++first != end) { - if (!(horizon[result] == horizon[first])) { - if (!(horizon[last] == horizon[first])) { - size_t dist = first - last; - if (dist == 1) { - horizon[result++] = horizon[last]; - } - last = first; - } - } - } - if (first - last == 1) { - horizon[result++] = horizon[last]; - } - horizon.resize(result); -} - -void LodOutsideMarker::fillHorizon(CHEdgeList& horizon, CHVertex* target) -{ - CHTriangle tri; - tri.vertex[2] = target; - tri.removed = false; - CHEdgeList::iterator it = horizon.begin(); - CHEdgeList::iterator itEnd = horizon.end(); - for (;it != itEnd; it++) { - tri.vertex[0] = it->first; - tri.vertex[1] = it->second; - tri.computeNormal(); - if (isVisible(&tri, mCentroid)) { - std::swap(tri.vertex[0], tri.vertex[1]); - tri.computeNormal(); - } - mHull.push_back(tri); - } -} - -bool LodOutsideMarker::isVisible(CHTriangle* t, Vector3& v) -{ - // We don't need epsilon here, because we assume, that the centroid is not on the triangle. - return t->normal.dotProduct(t->vertex[0]->position) < t->normal.dotProduct(v); -} - -void LodOutsideMarker::cleanHull() -{ - // cleanHull will remove triangles, which are marked as "removed" - // For fast performance, it will swap last item into the place of removed items. - size_t end = mHull.size() - 1; - size_t start = 0; - while (start <= end) { - if (mHull[start].removed) { - // Replace removed item with last item - mHull[start].removed = mHull[end].removed; - mHull[start].vertex[0] = mHull[end].vertex[0]; - mHull[start].vertex[1] = mHull[end].vertex[1]; - mHull[start].vertex[2] = mHull[end].vertex[2]; - mHull[start].normal = mHull[end].normal; - end--; - } else { - start++; - } - } - end++; - mHull.resize(end); -} - -Ogre::MeshPtr LodOutsideMarker::createConvexHullMesh(const String& meshName, const String& resourceGroupName) -{ - // Based on the wiki sample: http://www.ogre3d.org/tikiwiki/tiki-index.php?page=Generating+A+Mesh - OgreAssert(!MeshManager::getSingleton().getByName(meshName, resourceGroupName), "Resource with given name should not exist"); - - generateHull(); // calculate mHull triangles. - - // Convex hull can't be empty! - assert(!mHull.empty()); - - MeshPtr mesh = MeshManager::getSingleton().createManual(meshName, resourceGroupName, NULL); - SubMesh* subMesh = mesh->createSubMesh(); - - std::vector vertexBuffer; - std::vector indexBuffer; - // 3 position/triangle * 3 Real/position - vertexBuffer.reserve(mHull.size() * 9); - // 3 index / triangle - indexBuffer.reserve(mHull.size() * 3); - int id=0; - // min & max position - AxisAlignedBox bounds; - - for (auto & t : mHull) { - assert(!t.removed); - for(size_t n = 0; n < 3; n++){ - indexBuffer.push_back(id++); - vertexBuffer.push_back(t.vertex[n]->position.x); - vertexBuffer.push_back(t.vertex[n]->position.y); - vertexBuffer.push_back(t.vertex[n]->position.z); - bounds.merge(t.vertex[n]->position); - } - } - - /// Create vertex data structure for 8 vertices shared between submeshes - mesh->createVertexData(); - mesh->sharedVertexData->vertexCount = mHull.size() * 3; - - /// Create declaration (memory format) of vertex data - VertexDeclaration* decl = mesh->sharedVertexData->vertexDeclaration; - size_t offset = 0; - // 1st buffer - offset += decl->addElement(0, offset, VET_FLOAT3, VES_POSITION).getSize(); - - /// Allocate vertex buffer of the requested number of vertices (vertexCount) - /// and bytes per vertex (offset) - HardwareVertexBufferSharedPtr vbuf = - HardwareBufferManager::getSingleton().createVertexBuffer( - offset, mesh->sharedVertexData->vertexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY); - /// Upload the vertex data to the card - vbuf->writeData(0, vbuf->getSizeInBytes(), &vertexBuffer[0], true); - - /// Set vertex buffer binding so buffer 0 is bound to our vertex buffer - VertexBufferBinding* bind = mesh->sharedVertexData->vertexBufferBinding; - bind->setBinding(0, vbuf); - - /// Allocate index buffer of the requested number of vertices (ibufCount) - HardwareIndexBufferSharedPtr ibuf = HardwareBufferManager::getSingleton(). - createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, - indexBuffer.size(), - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - /// Upload the index data to the card - ibuf->writeData(0, ibuf->getSizeInBytes(), &indexBuffer[0], true); - - /// Set parameters of the submesh - subMesh->useSharedVertices = true; - subMesh->indexData->indexBuffer = ibuf; - subMesh->indexData->indexCount = indexBuffer.size(); - subMesh->indexData->indexStart = 0; - - /// Set bounding information (for culling) - mesh->_setBounds(bounds); - mesh->_setBoundingSphereRadius(bounds.getSize().length() / 2.0f); - - /// Set material to transparent blue - subMesh->setMaterialName("Examples/TransparentBlue50"); - - /// Notify -Mesh object that it has been loaded - mesh->load(); - - return mesh; -} - -template -void LodOutsideMarker::addHullTriangleVertices(std::vector& stack, T tri) -{ - OutsideData* v0 = getOutsideData(tri->vertex[0]); - OutsideData* v1 = getOutsideData(tri->vertex[1]); - OutsideData* v2 = getOutsideData(tri->vertex[2]); - - if (!v0->isOuterWallVertexInPass) { - v0->isOuterWallVertexInPass = true; - v0->isOuterWallVertex = true; - stack.push_back(tri->vertex[0]); - } - if (!v1->isOuterWallVertexInPass) { - v1->isOuterWallVertexInPass = true; - v1->isOuterWallVertex = true; - stack.push_back(tri->vertex[1]); - } - - if (!v2->isOuterWallVertexInPass) { - v2->isOuterWallVertexInPass = true; - v2->isOuterWallVertex = true; - stack.push_back(tri->vertex[2]); - } -} - -void LodOutsideMarker::markVertices() -{ - OutsideDataList::iterator v, vEnd; - v = mOutsideData.begin(); - vEnd = mOutsideData.end(); - for (;v != vEnd; v++) { - v->isOuterWallVertex = false; - } - std::vector stack; - CHTriangleList::iterator tri, triEnd; - tri = mHull.begin(); - triEnd = mHull.end(); - for (; tri != triEnd; tri++) { - stack.clear(); - v = mOutsideData.begin(); - vEnd = mOutsideData.end(); - for (;v != vEnd; v++) { - v->isOuterWallVertexInPass = false; - } - addHullTriangleVertices(stack, &*tri); - while (!stack.empty()) { - CHVertex* vert = stack.back(); - stack.pop_back(); - LodData::VTriangles::iterator it, itEnd; - it = vert->triangles.begin(); - itEnd = vert->triangles.end(); - for (; it != itEnd; it++) { - if (tri->normal.dotProduct((*it)->normal) > mWalkAngle) { - addHullTriangleVertices(stack, *it); - } - } - } - } -} - -} diff --git a/Components/MeshLodGenerator/src/OgreMeshLodGenerator.cpp b/Components/MeshLodGenerator/src/OgreMeshLodGenerator.cpp deleted file mode 100644 index 552b33034aa..00000000000 --- a/Components/MeshLodGenerator/src/OgreMeshLodGenerator.cpp +++ /dev/null @@ -1,375 +0,0 @@ -/* - * ----------------------------------------------------------------------------- - * This source file is part of OGRE - * (Object-oriented Graphics Rendering Engine) - * For the latest info, see http://www.ogre3d.org/ - * - * Copyright (c) 2000-2014 Torus Knot Software Ltd - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * ----------------------------------------------------------------------------- - */ - -#include - -#include "OgreMeshLodPrecompiledHeaders.h" - -namespace Ogre -{ - -struct LodWorkQueueRequest { - LodConfig config; - LodDataPtr data; - LodInputProviderPtr input; - LodOutputProviderPtr output; - LodCollapseCostPtr cost; - LodCollapserPtr collapser; - bool isCancelled; -}; - -template<> MeshLodGenerator* Singleton::msSingleton = 0; -MeshLodGenerator* MeshLodGenerator::getSingletonPtr() -{ - return msSingleton; -} -MeshLodGenerator& MeshLodGenerator::getSingleton() -{ - assert(msSingleton); - return (*msSingleton); -} -void MeshLodGenerator::getAutoconfig(MeshPtr& inMesh, LodConfig& outLodConfig) -{ - outLodConfig.mesh = inMesh; - outLodConfig.strategy = PixelCountLodStrategy::getSingletonPtr(); - LodLevel lodLevel; - lodLevel.reductionMethod = LodLevel::VRM_COLLAPSE_COST; - Real radius = inMesh->getBoundingSphereRadius(); - for(int i = 2; i < 6; i++) { - Real i4 = (Real) (i * i * i * i); - Real i5 = i4 * (Real) i; - // Distance = pixel count - // Constant: zoom of the Lod. This could be scaled based on resolution. - // Higher constant means first Lod is nearer to camera. Smaller constant means the first Lod is further away from camera. - // i4: The stretching. Normally you want to have more Lods in the near, then in far away. - // i4 means distance is divided by 16=(2*2*2*2), 81, 256, 625=(5*5*5*5). - // if 16 would be smaller, the first Lod would be nearer. if 625 would be bigger, the last Lod would be further awaay. - // if you increase 16 and decrease 625, first and Last Lod distance would be smaller. - lodLevel.distance = 3388608.f / i4; - - // reductionValue = collapse cost - // Radius: Edges are multiplied by the length, when calculating collapse cost. So as a base value we use radius, which should help in balancing collapse cost to any mesh size. - // The constant and i5 are playing together. 1/(1/100k*i5) - // You need to determine the quality of nearest Lod and the furthest away first. - // I have chosen 1/(1/100k*(2^5)) = 3125 for nearest Lod and 1/(1/100k*(5^5)) = 32 for nearest Lod. - // if you divide radius by a bigger number, it means smaller reduction. So radius/3125 is very small reduction for nearest Lod. - // if you divide radius by a smaller number, it means bigger reduction. So radius/32 means aggressive reduction for furthest away lod. - // current values: 3125, 411, 97, 32 - lodLevel.reductionValue = radius / 100000.f * i5; - outLodConfig.levels.push_back(lodLevel); - } -} - -void MeshLodGenerator::generateAutoconfiguredLodLevels(MeshPtr& mesh) -{ - LodConfig lodConfig; - getAutoconfig(mesh, lodConfig); - generateLodLevels(lodConfig); -} - -void MeshLodGenerator::_configureMeshLodUsage(const LodConfig& lodConfig) -{ - bool edgeListWasBuilt = lodConfig.mesh->isEdgeListBuilt(); - lodConfig.mesh->freeEdgeList(); - lodConfig.mesh->setLodStrategy(lodConfig.strategy); - MeshLodUsage usage; - ushort n = 0; - lodConfig.mesh->_setLodInfo(Math::uint16Cast(lodConfig.levels.size() + 1)); // add Lod levels - for(size_t i = 0; i < lodConfig.levels.size(); i++) { - // Record usages. First Lod usage is the mesh itself. - - // Skip lods, which have the same amount of vertices. No buffer generated for them. - if(!lodConfig.levels[i].outSkipped) { - - usage.userValue = lodConfig.levels[i].distance; - usage.value = lodConfig.mesh->getLodStrategy()->transformUserValue(usage.userValue); - usage.edgeData = NULL; - usage.manualMesh.reset(); - usage.manualName = lodConfig.levels[i].manualMeshName; - lodConfig.mesh->_setLodUsage(++n, usage); - } - } - // Remove skipped Lod levels - lodConfig.mesh->_setLodInfo(n + 1); - if(edgeListWasBuilt) - lodConfig.mesh->buildEdgeList(); -} - -MeshLodGenerator::MeshLodGenerator() : mInjectorListener(NULL) {} -MeshLodGenerator::~MeshLodGenerator() {} - -void MeshLodGenerator::_resolveComponents(LodConfig& lodConfig, - LodCollapseCostPtr& cost, - LodDataPtr& data, - LodInputProviderPtr& input, - LodOutputProviderPtr& output, - LodCollapserPtr& collapser) -{ - if(!cost) { - cost = LodCollapseCostPtr(new LodCollapseCostCurvature); - cost->setPreventPunchingHoles(lodConfig.advanced.preventPunchingHoles); - cost->setPreventBreakingLines(lodConfig.advanced.preventBreakingLines); - if(lodConfig.advanced.outsideWeight != 0) { - cost = - LodCollapseCostPtr(new LodCollapseCostOutside(cost, lodConfig.advanced.outsideWeight, - lodConfig.advanced.outsideWalkAngle)); - cost->setPreventPunchingHoles(lodConfig.advanced.preventPunchingHoles); - cost->setPreventBreakingLines(lodConfig.advanced.preventBreakingLines); - } - if(!lodConfig.advanced.profile.empty()) { - cost = LodCollapseCostPtr(new LodCollapseCostProfiler(lodConfig.advanced.profile, cost)); - cost->setPreventPunchingHoles(lodConfig.advanced.preventPunchingHoles); - cost->setPreventBreakingLines(lodConfig.advanced.preventBreakingLines); - } - - } - if(!data) { - data = std::make_shared(); - } - if(!collapser) { - collapser = std::make_shared(); - } - if(lodConfig.advanced.useBackgroundQueue) { - if(!input) { - input = LodInputProviderPtr(new LodInputProviderBuffer(lodConfig.mesh)); - } - if(!output) { - output = LodOutputProviderPtr(new LodOutputProviderBuffer(lodConfig.mesh, lodConfig.advanced.useCompression)); - } - } else { - if(!input) { - input = LodInputProviderPtr(new LodInputProviderMesh(lodConfig.mesh)); - } - if(!output) { - output = LodOutputProviderPtr(new LodOutputProviderMesh(lodConfig.mesh, lodConfig.advanced.useCompression)); - } - } -} -void MeshLodGenerator::_process(LodConfig& lodConfig, - LodCollapseCost* cost, - LodData* data, - LodInputProvider* input, - LodOutputProvider* output, - LodCollapser* collapser) -{ - input->initData(data); - data->mUseVertexNormals = data->mUseVertexNormals && lodConfig.advanced.useVertexNormals; - cost->initCollapseCosts(data); - output->prepare(data); - computeLods(lodConfig, data, cost, output, collapser); - output->finalize(data); - if(!lodConfig.advanced.useBackgroundQueue) { - // This will be processed in LodWorkQueueInjector if we use background queue. - output->inject(); - _configureMeshLodUsage(lodConfig); - //lodConfig.mesh->buildEdgeList(); - } -} -void MeshLodGenerator::generateLodLevels(LodConfig& lodConfig, - LodCollapseCostPtr cost, - LodDataPtr data, - LodInputProviderPtr input, - LodOutputProviderPtr output, - LodCollapserPtr collapser) -{ - // If we don't have generated Lod levels, we can use _generateManualLodLevels. - bool hasGeneratedLevels = false; - for(auto & level : lodConfig.levels) { - if(level.manualMeshName.empty()) { - hasGeneratedLevels = true; - break; - } - } - if(hasGeneratedLevels || mInjectorListener) { - _resolveComponents(lodConfig, cost, data, input, output, collapser); - if(lodConfig.advanced.useBackgroundQueue) { - addRequestToQueue(lodConfig, cost, data, input, output, collapser); - } else { - _process(lodConfig, cost.get(), data.get(), input.get(), output.get(), collapser.get()); - } - } else { - _generateManualLodLevels(lodConfig); - } -} - -void MeshLodGenerator::computeLods(LodConfig& lodConfig, - LodData* data, - LodCollapseCost* cost, - LodOutputProvider* output, - LodCollapser* collapser) -{ - int lodID = 0; - size_t lastBakeVertexCount = data->mVertexList.size(); - for(unsigned short curLod = 0; curLod < lodConfig.levels.size(); curLod++) { - if(!lodConfig.levels[curLod].manualMeshName.empty()) { - // Manual Lod level - lodConfig.levels[curLod].outSkipped = - (curLod != 0 && lodConfig.levels[curLod].manualMeshName == lodConfig.levels[curLod - 1].manualMeshName); - lodConfig.levels[curLod].outUniqueVertexCount = 0; - lastBakeVertexCount = -1; - if(!lodConfig.levels[curLod].outSkipped) { - output->bakeManualLodLevel(data, lodConfig.levels[curLod].manualMeshName, lodID++); - } - } else { - size_t vertexCountLimit; - Real collapseCostLimit; - calcLodVertexCount(lodConfig.levels[curLod], data->mVertexList.size(), vertexCountLimit, collapseCostLimit); - collapser->collapse(data, cost, output, static_cast(vertexCountLimit), collapseCostLimit); - size_t vertexCount = data->mCollapseCostHeap.size(); - lodConfig.levels[curLod].outUniqueVertexCount = vertexCount; - lodConfig.levels[curLod].outSkipped = (vertexCount == lastBakeVertexCount); - if(!lodConfig.levels[curLod].outSkipped) { - lastBakeVertexCount = vertexCount; - output->bakeLodLevel(data, lodID++); - } - } - } -} -void MeshLodGenerator::calcLodVertexCount(const LodLevel& lodLevel, - size_t uniqueVertexCount, - size_t& outVertexCountLimit, - Real& outCollapseCostLimit) -{ - switch(lodLevel.reductionMethod) { - case LodLevel::VRM_PROPORTIONAL: - outCollapseCostLimit = LodData::NEVER_COLLAPSE_COST; - outVertexCountLimit = uniqueVertexCount - (size_t) ((Real) uniqueVertexCount * lodLevel.reductionValue); - break; - - case LodLevel::VRM_CONSTANT: - outCollapseCostLimit = LodData::NEVER_COLLAPSE_COST; - outVertexCountLimit = (size_t) lodLevel.reductionValue; - if(outVertexCountLimit < uniqueVertexCount) { - outVertexCountLimit = uniqueVertexCount - outVertexCountLimit; - } else { - outVertexCountLimit = 0; - } - break; - - case LodLevel::VRM_COLLAPSE_COST: - outCollapseCostLimit = lodLevel.reductionValue; - outVertexCountLimit = 0; - break; - - default: - OgreAssert(0, ""); - outCollapseCostLimit = LodData::NEVER_COLLAPSE_COST; - outVertexCountLimit = uniqueVertexCount; - break; - } -} - -void MeshLodGenerator::_generateManualLodLevels(LodConfig& lodConfig) -{ - LodOutputProviderMesh output(lodConfig.mesh); - output.prepare(NULL); - for(unsigned short curLod = 0; curLod < lodConfig.levels.size(); curLod++) { - OgreAssert( - !lodConfig.levels[curLod].manualMeshName.empty(), - "Only manual Lod levels are supported! Call generateLodLevels() instead!"); - lodConfig.levels[curLod].outSkipped = false; - lodConfig.levels[curLod].outUniqueVertexCount = 0; - output.bakeManualLodLevel(NULL, lodConfig.levels[curLod].manualMeshName, curLod); - } - output.finalize(NULL); - output.inject(); - _configureMeshLodUsage(lodConfig); -} - -void MeshLodGenerator::addRequestToQueue( LodConfig& lodConfig, LodCollapseCostPtr& cost, LodDataPtr& data, LodInputProviderPtr& input, LodOutputProviderPtr& output, LodCollapserPtr& collapser ) -{ - LodWorkQueueRequest* req = new LodWorkQueueRequest(); - req->config = lodConfig; - req->cost = cost; - req->data = data; - req->input = input; - req->output = output; - req->collapser = collapser; - req->isCancelled = false; - - { - OGRE_WQ_LOCK_MUTEX(mQueueMutex); - mPendingLodRequests.push_back(req); - - Root::getSingleton().getWorkQueue()->addTask([this, req]() - { handleRequest(new WorkQueue::Request(0, 0, req, 0, 0), NULL); }); - } -} - -void MeshLodGenerator::clearPendingLodRequests() -{ - OGRE_WQ_LOCK_MUTEX(mQueueMutex); - for(auto r : mPendingLodRequests) - r->isCancelled = true; -} - -WorkQueue::Response* MeshLodGenerator::handleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ) -{ - // Called on worker thread by WorkQueue. - LodWorkQueueRequest* request = any_cast(req->getData()); - { - OGRE_WQ_LOCK_MUTEX(mQueueMutex); - mPendingLodRequests.remove(request); - if(request->isCancelled) - { - delete request; - return NULL; - } - } - - _process(request->config, request->cost.get(), request->data.get(), request->input.get(), request->output.get(), request->collapser.get()); - - Root::getSingleton().getWorkQueue()->addMainThreadTask( - [this, request]() { - WorkQueue::Response res(NULL, true, request); - handleResponse(&res, NULL); - delete request; - }); - return NULL; -} - -void MeshLodGenerator::handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ) -{ - LodWorkQueueRequest* request = any_cast(res->getData()); - - if(mInjectorListener){ - if(!mInjectorListener->shouldInject(request)) { - return; - } - } - - request->output->inject(); - MeshLodGenerator::_configureMeshLodUsage(request->config); - //lodConfig.mesh->buildEdgeList(); - - if(mInjectorListener){ - mInjectorListener->injectionCompleted(request); - } -} - -} diff --git a/Components/MeshLodGenerator/src/OgreMeshLodPrecompiledHeaders.h b/Components/MeshLodGenerator/src/OgreMeshLodPrecompiledHeaders.h deleted file mode 100644 index 2a464ab3802..00000000000 --- a/Components/MeshLodGenerator/src/OgreMeshLodPrecompiledHeaders.h +++ /dev/null @@ -1,60 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __OgreMeshLodPrecompiledHeaders__ -#define __OgreMeshLodPrecompiledHeaders__ - -#include "OgreRoot.h" -#include "OgrePixelCountLodStrategy.h" -#include "OgreHardwareBufferManager.h" -#include "OgreHardwareIndexBuffer.h" -#include "OgreMeshManager.h" -#include "OgreMesh.h" -#include "OgreSubMesh.h" -#include "OgreLogManager.h" - -#include "OgreMeshLodGenerator.h" -#include "OgreLodWorkQueueInjectorListener.h" -#include "OgreLodInputProvider.h" -#include "OgreLodInputProviderMesh.h" -#include "OgreLodInputProviderBuffer.h" -#include "OgreLodOutputProvider.h" -#include "OgreLodOutputProviderMesh.h" -#include "OgreLodOutputProviderBuffer.h" -#include "OgreLodOutsideMarker.h" -#include "OgreLodCollapseCost.h" -#include "OgreLodCollapseCostCurvature.h" -#include "OgreLodCollapseCostProfiler.h" -#include "OgreLodCollapseCostOutside.h" -#include "OgreLodConfig.h" -#include "OgreLodConfigSerializer.h" -#include "OgreLodData.h" -#include "OgreLodCollapser.h" -#include "OgreLodStrategyManager.h" - -#endif diff --git a/Components/MeshLodGenerator/src/OgreSmallVector.cpp b/Components/MeshLodGenerator/src/OgreSmallVector.cpp deleted file mode 100644 index d01dba6206b..00000000000 --- a/Components/MeshLodGenerator/src/OgreSmallVector.cpp +++ /dev/null @@ -1,86 +0,0 @@ -//===- llvm/ADT/SmallVector.cpp - 'Normally small' vectors ----------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. -// ============================================================================== -// LLVM Release License -// ============================================================================== -// University of Illinois/NCSA -// Open Source License -// -// Copyright (c) 2003-2010 University of Illinois at Urbana-Champaign. -// All rights reserved. -// -// Developed by: -// -// LLVM Team -// -// University of Illinois at Urbana-Champaign -// -// http://llvm.org -// -// Permission is hereby granted, free of charge, to any person obtaining a copy of -// this software and associated documentation files (the "Software"), to deal with -// the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -// of the Software, and to permit persons to whom the Software is furnished to do -// so, subject to the following conditions: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimers. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimers in the -// documentation and/or other materials provided with the distribution. -// -// * Neither the names of the LLVM Team, University of Illinois at -// Urbana-Champaign, nor the names of its contributors may be used to -// endorse or promote products derived from this Software without specific -// prior written permission. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE -// SOFTWARE. -// -//===----------------------------------------------------------------------===// -// -// This file implements the SmallVector class. -// -//===----------------------------------------------------------------------===// - - -#include "OgreSmallVector.h" - -namespace Ogre { - -/// grow_pod - This is an implementation of the grow() method which only works -/// on POD-like datatypes and is out of line to reduce code duplication. -void SmallVectorBase::grow_pod(size_t MinSizeInBytes, size_t TSize) { - size_t CurSizeBytes = size_in_bytes(); - size_t NewCapacityInBytes = 2 * capacity_in_bytes() + TSize; // Always grow. - if (NewCapacityInBytes < MinSizeInBytes) - NewCapacityInBytes = MinSizeInBytes; - - void *NewElts; - if (this->isSmall()) { - NewElts = malloc(NewCapacityInBytes); - - // Copy the elements over. No need to run dtors on PODs. - memcpy(NewElts, this->BeginX, CurSizeBytes); - } else { - // If this wasn't grown from the inline copy, grow the allocated space. - NewElts = realloc(this->BeginX, NewCapacityInBytes); - } - - this->EndX = (char*)NewElts+CurSizeBytes; - this->BeginX = NewElts; - this->CapacityX = (char*)this->BeginX + NewCapacityInBytes; -} - -} diff --git a/Components/Overlay/CMakeLists.txt b/Components/Overlay/CMakeLists.txt deleted file mode 100644 index ce4df6f2959..00000000000 --- a/Components/Overlay/CMakeLists.txt +++ /dev/null @@ -1,110 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -############################################################ -# Overlay optional component -############################################################ - -# define header and source files for the library -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES - ${PROJECT_BINARY_DIR}/include/OgreOverlayPrerequisites.h - ${CMAKE_CURRENT_SOURCE_DIR}/include/OgreOverlay.i) -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") - -if(OGRE_BUILD_COMPONENT_OVERLAY_IMGUI) - set(IMGUI_DIR "${PROJECT_BINARY_DIR}/imgui-1.90" CACHE PATH "") - if(NOT EXISTS ${IMGUI_DIR}) - message(STATUS "Downloading imgui") - file(DOWNLOAD - https://github.com/ocornut/imgui/archive/v1.90.tar.gz - ${PROJECT_BINARY_DIR}/imgui.tar.gz) - execute_process(COMMAND ${CMAKE_COMMAND} - -E tar xf imgui.tar.gz WORKING_DIRECTORY ${PROJECT_BINARY_DIR}) - endif() - list(APPEND SOURCE_FILES - ${IMGUI_DIR}/imgui.cpp - ${IMGUI_DIR}/imgui_draw.cpp - ${IMGUI_DIR}/imgui_tables.cpp - ${IMGUI_DIR}/imgui_widgets.cpp - ${IMGUI_DIR}/imgui_demo.cpp) - if(FREETYPE_FOUND) - set(IMGUI_ENABLE_FREETYPE TRUE) - list(APPEND SOURCE_FILES ${IMGUI_DIR}/misc/freetype/imgui_freetype.cpp) - endif() -else() - list(REMOVE_ITEM SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreImGuiOverlay.cpp") -endif() - -# setup target -add_library(OgreOverlay ${OGRE_COMP_LIB_TYPE} ${HEADER_FILES} ${SOURCE_FILES}) -set_target_properties(OgreOverlay PROPERTIES VERSION ${OGRE_SOVERSION} SOVERSION ${OGRE_SOVERSION}) -target_link_libraries(OgreOverlay PUBLIC OgreMain) -target_include_directories(OgreOverlay PUBLIC - "$" - $) - -if(FREETYPE_FOUND) - target_compile_definitions(OgreOverlay PRIVATE HAVE_FREETYPE) - target_link_libraries(OgreOverlay PRIVATE ${FREETYPE_LIBRARIES}) - target_include_directories(OgreOverlay PRIVATE ${FREETYPE_INCLUDE_DIRS}) - if(ZLIB_FOUND) - target_link_libraries(OgreOverlay PRIVATE ZLIB::ZLIB) - endif() -elseif(UNIX) - set_source_files_properties(src/OgreFont.cpp PROPERTIES - COMPILE_FLAGS "-Wno-cast-qual -Wno-unused-function") -endif() - -if(OGRE_BUILD_COMPONENT_OVERLAY_IMGUI) - target_include_directories(OgreOverlay PUBLIC - PUBLIC "$" - PRIVATE "$") - - if(UNIX) - set_source_files_properties(${IMGUI_DIR}/misc/freetype/imgui_freetype.cpp PROPERTIES - COMPILE_FLAGS "-Wno-missing-declarations") - - set_source_files_properties(${IMGUI_DIR}/imgui_widgets.cpp PROPERTIES - COMPILE_FLAGS "-Wno-cast-qual") - set_source_files_properties(${IMGUI_DIR}/imgui_draw.cpp PROPERTIES - COMPILE_FLAGS "-Wno-cast-qual") - set_source_files_properties(${IMGUI_DIR}/imgui.cpp PROPERTIES - COMPILE_FLAGS "-Wno-cast-qual") - if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") - set_property(SOURCE ${IMGUI_DIR}/misc/freetype/imgui_freetype.cpp - APPEND PROPERTY COMPILE_OPTIONS "-Wno-unknown-warning-option") - endif() - endif() - - if(MINGW) - target_link_libraries(OgreOverlay PRIVATE imm32) - endif() - - configure_file(${OGRE_TEMPLATES_DIR}/imconfig.h ${IMGUI_DIR}/imconfig.h) - - list(APPEND HEADER_FILES - ${IMGUI_DIR}/imgui.h - ${IMGUI_DIR}/imconfig.h) -endif() - -generate_export_header(OgreOverlay - EXPORT_MACRO_NAME _OgreOverlayExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreOverlayPrerequisites.h) - -# install -ogre_config_framework(OgreOverlay) -ogre_config_component(OgreOverlay) - -install(FILES ${HEADER_FILES} - DESTINATION include/OGRE/Overlay -) -install(FILES "${PROJECT_SOURCE_DIR}/Media/packs/profiler.zip" - DESTINATION "${OGRE_MEDIA_PATH}/packs/" -) diff --git a/Components/Overlay/include/ImGui.i b/Components/Overlay/include/ImGui.i deleted file mode 100644 index 63b51ff667e..00000000000 --- a/Components/Overlay/include/ImGui.i +++ /dev/null @@ -1,80 +0,0 @@ -%module(package="Ogre", directors="1") ImGui -%{ -#include "imgui.h" -%} - -#define IMGUI_API - -%include stdint.i -%include typemaps.i - -// ignore va list methods -%ignore ImGui::TextV; -%ignore ImGui::TextColoredV; -%ignore ImGui::TextDisabledV; -%ignore ImGui::TextWrappedV; -%ignore ImGui::LabelTextV; -%ignore ImGui::LogTextV; -%ignore ImGui::BulletTextV; -%ignore ImGui::TreeNodeV; -%ignore ImGui::TreeNodeExV; -%ignore ImGui::SetTooltipV; -%ignore ImGui::SetItemTooltipV; -%ignore ImGuiTextBuffer::appendfv; - -%typemap(in) ImTextureID { - size_t argp; - int res = SWIG_AsVal_size_t($input, &argp); - if(SWIG_IsOK(res)) - $1 = ($ltype)(argp); - else - SWIG_exception_fail(SWIG_TypeError, "Expected size_t"); -} -%typecheck(SWIG_TYPECHECK_POINTER) ImTextureID { - $1 = true; // actual check in the typemap -} - -%typemap(in) float[4], float[3], float[2] { - void* argp; - int res = SWIG_ConvertPtr($input, &argp, $descriptor(ImVec4*), $disown); - if (SWIG_IsOK(res)) { - $1 = ($ltype)argp; - } else { - SWIG_exception_fail(SWIG_TypeError, "Expected ImVec4"); - } -} - -#ifdef SWIGPYTHON -// match the signature of the by value variants -%typemap(argout) float[4], float[3], float[2] { - $result = SWIG_Python_AppendOutput($result, SWIG_NewPointerObj($1, $descriptor(ImVec4*), 0)); -} -#endif - -%typecheck(SWIG_TYPECHECK_STRING) float[4], float[3], float[2] { - $1 = true; // actual check in the typemap -} - -#ifdef SWIGPYTHON -%rename("__version__") "IMGUI_VERSION"; -#endif - -// strip duplicate namespace for ImGuiSomething_FlagName flags -%rename("%(strip:[ImGui])s", regextarget=1) "^ImGui.+_.+"; - -%apply bool* INOUT { bool* p_open }; -%apply bool* INOUT { bool* v }; -%apply float* INOUT { float* v }; -%apply int* INOUT { int* v }; -%include "imgui.h" - -%extend ImGuiStyle -{ - const ImVec4& getColor(int i) const { - return $self->Colors[i]; - } - - void setColor(int i, const ImVec4& v) { - $self->Colors[i] = v; - } -} \ No newline at end of file diff --git a/Components/Overlay/include/OgreBorderPanelOverlayElement.h b/Components/Overlay/include/OgreBorderPanelOverlayElement.h deleted file mode 100644 index 4629f6392c5..00000000000 --- a/Components/Overlay/include/OgreBorderPanelOverlayElement.h +++ /dev/null @@ -1,257 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __BorderPanelOverlayElement_H__ -#define __BorderPanelOverlayElement_H__ - -#include "OgrePanelOverlayElement.h" - -namespace Ogre { - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Overlays - * @{ - */ - - class BorderRenderable; - - /** A specialisation of the PanelOverlayElement to provide a panel with a border. - - Whilst the standard panel can use a single tiled material, this class allows - panels with a tileable backdrop plus a border texture. This is handy for large - panels that are too big to use a single large texture with a border, or - for multiple different size panels where you want the border a constant width - but the center to repeat. - @par - In addition to the usual PanelOverlayElement properties, this class has a 'border - material', which specifies the material used for the edges of the panel, - a border width (which can either be constant all the way around, or specified - per edge), and the texture coordinates for each of the border sections. - */ - class _OgreOverlayExport BorderPanelOverlayElement : public PanelOverlayElement - { - friend class BorderRenderable; - public: - /** Constructor */ - BorderPanelOverlayElement(const String& name); - virtual ~BorderPanelOverlayElement(); - - void initialise(void) override; - - /** @copydoc OverlayElement::_releaseManualHardwareResources */ - void _releaseManualHardwareResources() override; - /** @copydoc OverlayElement::_restoreManualHardwareResources */ - void _restoreManualHardwareResources() override; - - const String& getTypeName(void) const override; - /** @name Border Size - Remember that the dimensions specified here are in relation to the size of - the screen, so 0.1 is 1/10th of the screen width or height. Also note that because - most screen resolutions are 1.333:1 width:height ratio that using the same - border size will look slightly bigger across than up. - */ - /// @{ - /** Sets the size of the border. - - This method sets a constant size for all borders. - @param size The size of the border as a factor of the screen dimensions ie 0.2 is one-fifth - of the screen size. - */ - void setBorderSize(Real size); - - /** Sets the size of the border, with different sizes for vertical and horizontal borders. - - This method sets a size for the side and top / bottom borders separately. - @param sides The size of the side borders as a factor of the screen dimensions ie 0.2 is one-fifth - of the screen size. - @param topAndBottom The size of the top and bottom borders as a factor of the screen dimensions. - */ - void setBorderSize(Real sides, Real topAndBottom); - - /** Sets the size of the border separately for all borders. - - This method sets a size all borders separately. - @param left The size of the left border as a factor of the screen dimensions ie 0.2 is one-fifth - of the screen size. - @param right The size of the left border as a factor of the screen dimensions. - @param top The size of the top border as a factor of the screen dimensions. - @param bottom The size of the bottom border as a factor of the screen dimensions. - */ - void setBorderSize(Real left, Real right, Real top, Real bottom); - - /** Gets the size of the left border. */ - Real getLeftBorderSize(void) const; - /** Gets the size of the right border. */ - Real getRightBorderSize(void) const; - /** Gets the size of the top border. */ - Real getTopBorderSize(void) const; - /** Gets the size of the bottom border. */ - Real getBottomBorderSize(void) const; - /// @} - - /** @name Border UV Coordinates - The border panel uses 8 panels for the border (9 including the center). - Imagine a table with 3 rows and 3 columns. The corners are always the same size, - but the edges stretch depending on how big the panel is. Those who have done - resizable HTML tables will be familiar with this approach. - - We only require 2 sets of uv coordinates, one for the top-left and one for the - bottom-right of the panel, since it is assumed the sections are aligned on the texture. - */ - /// @{ - /** Sets the texture coordinates for the left edge of the border. - */ - void setLeftBorderUV(Real u1, Real v1, Real u2, Real v2); - /** Sets the texture coordinates for the right edge of the border. - */ - void setRightBorderUV(Real u1, Real v1, Real u2, Real v2); - /** Sets the texture coordinates for the top edge of the border. - */ - void setTopBorderUV(Real u1, Real v1, Real u2, Real v2); - /** Sets the texture coordinates for the bottom edge of the border. - */ - void setBottomBorderUV(Real u1, Real v1, Real u2, Real v2); - /** Sets the texture coordinates for the top-left corner of the border. - */ - void setTopLeftBorderUV(Real u1, Real v1, Real u2, Real v2); - /** Sets the texture coordinates for the top-right corner of the border. - */ - void setTopRightBorderUV(Real u1, Real v1, Real u2, Real v2); - /** Sets the texture coordinates for the bottom-left corner of the border. - */ - void setBottomLeftBorderUV(Real u1, Real v1, Real u2, Real v2); - /** Sets the texture coordinates for the bottom-right corner of the border. - */ - void setBottomRightBorderUV(Real u1, Real v1, Real u2, Real v2); - - String getLeftBorderUVString() const; - String getRightBorderUVString() const; - String getTopBorderUVString() const; - String getBottomBorderUVString() const; - String getTopLeftBorderUVString() const; - String getTopRightBorderUVString() const; - String getBottomLeftBorderUVString() const; - String getBottomRightBorderUVString() const; - /// @} - - /** Sets the name of the material to use for the borders. */ - void setBorderMaterialName(const String& name, const String& group = DEFAULT_RESOURCE_GROUP ); - /** Gets the name of the material to use for the borders. */ - const String& getBorderMaterialName(void) const; - - /** @copydoc OverlayContainer::_updateRenderQueue */ - void _updateRenderQueue(RenderQueue* queue) override; - /// @copydoc OverlayElement::visitRenderables - void visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables = false); - - /** @copydoc OverlayElement::setMetricsMode */ - void setMetricsMode(GuiMetricsMode gmm) override; - - /** @copydoc OverlayElement::_update */ - void _update(void) override; - private: - float mLeftBorderSize; - float mRightBorderSize; - float mTopBorderSize; - float mBottomBorderSize; - struct CellUV { - float u1, v1, u2, v2; - }; - CellUV mBorderUV[8]; - - ushort mPixelLeftBorderSize; - ushort mPixelRightBorderSize; - ushort mPixelTopBorderSize; - ushort mPixelBottomBorderSize; - - MaterialPtr mBorderMaterial; - - /// Render operation for the border area - RenderOperation mRenderOp2; - - static String msTypeName; - - /// Internal method for setting up geometry, called by OverlayElement::update - void updatePositionGeometry(void) override; - /// Internal method for setting up geometry, called by OverlayElement::update - void updateTextureGeometry(void) override; - /// Internal method for setting up parameters - void addBaseParameters(void) override; - - enum BorderCellIndex { - BCELL_TOP_LEFT = 0, - BCELL_TOP = 1, - BCELL_TOP_RIGHT = 2, - BCELL_LEFT = 3, - BCELL_RIGHT = 4, - BCELL_BOTTOM_LEFT = 5, - BCELL_BOTTOM = 6, - BCELL_BOTTOM_RIGHT = 7 - }; - String getCellUVString(BorderCellIndex idx) const; - - BorderRenderable* mBorderRenderable; - }; - - /** Class for rendering the border of a BorderPanelOverlayElement. - - We need this because we have to render twice, once with the inner panel's repeating - material (handled by superclass) and once for the border's separate material. - */ - class _OgreOverlayExport BorderRenderable : public Renderable, public OverlayAlloc - { - private: - BorderPanelOverlayElement* mParent; - public: - /** Constructed with pointers to parent. */ - BorderRenderable(BorderPanelOverlayElement* parent) : mParent(parent) - { - mUseIdentityProjection = true; - mUseIdentityView = true; - mPolygonModeOverrideable = parent->getPolygonModeOverrideable(); - } - const MaterialPtr& getMaterial(void) const override { return mParent->mBorderMaterial; } - void getRenderOperation(RenderOperation& op) override { op = mParent->mRenderOp2; } - void getWorldTransforms(Matrix4* xform) const override { mParent->getWorldTransforms(xform); } - unsigned short getNumWorldTransforms(void) const override { return 1; } - Real getSquaredViewDepth(const Camera* cam) const override { return mParent->getSquaredViewDepth(cam); } - const LightList& getLights(void) const override - { - // N/A, panels are not lit - static LightList ll; - return ll; - } - }; - /** @} */ - /** @} */ - -} // namespace Ogre - -#endif // __BorderPanelOverlayElement_H__ diff --git a/Components/Overlay/include/OgreFont.h b/Components/Overlay/include/OgreFont.h deleted file mode 100644 index 127465cb944..00000000000 --- a/Components/Overlay/include/OgreFont.h +++ /dev/null @@ -1,352 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ - -#ifndef _Font_H__ -#define _Font_H__ - -#include "OgreOverlayPrerequisites.h" -#include "OgreResource.h" -#include "OgreCommon.h" -#include "OgreSharedPtr.h" -#include "OgreColourValue.h" -#include "OgreException.h" - -namespace Ogre -{ - class BillboardSet; - - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Overlays - * @{ - */ - - /// decode UTF8 encoded bytestream to uint32 codepoints - _OgreOverlayExport std::vector utftoc32(String str); - - /** Enumerates the types of Font usable in the engine. */ - enum FontType - { - /// Generated from a truetype (.ttf) font - FT_TRUETYPE = 1, - /// Loaded from an image created by an artist - FT_IMAGE = 2 - }; - - - /// Information about the position and size of a glyph in a texture - struct GlyphInfo - { - typedef uint32 CodePoint; - typedef FloatRect UVRect; - - CodePoint codePoint; - UVRect uvRect; - float aspectRatio; // width/ height - float bearing; // bearingX/ height - float advance; // advanceX/ height - }; - - /** Class representing a font in the system. - - This class is simply a way of getting a font texture into the OGRE system and - to easily retrieve the texture coordinates required to accurately render them. - Fonts can either be loaded from precreated textures, or the texture can be generated - using a truetype font. You can either create the texture manually in code, or you - can use a .fontdef script to define it (probably more practical since you can reuse - the definition more easily) - @note - This class extends both Resource and ManualResourceLoader since it is - both a resource in it's own right, but it also provides the manual load - implementation for the Texture it creates. - */ - class _OgreOverlayExport Font final : public Resource, public ManualResourceLoader - { - protected: - /// The type of font - FontType mType; - - /// Source of the font (either an image name or a truetype font) - String mSource; - - /// Size of the truetype font, in points - Real mTtfSize; - /// Resolution (dpi) of truetype font - uint mTtfResolution; - /// Max distance to baseline of this (truetype) font - int mTtfMaxBearingY; - - - public: - typedef GlyphInfo::CodePoint CodePoint; - typedef GlyphInfo::UVRect UVRect; - /// A range of code points, inclusive on both ends - typedef std::pair CodePointRange; - typedef std::vector CodePointRangeList; - protected: - /// Map from unicode code point to texture coordinates - typedef std::map CodePointMap; - CodePointMap mCodePointMap; - - /// The material which is generated for this font - MaterialPtr mMaterial; - - /// Texture pointer - TexturePtr mTexture; - - /// For TRUE_TYPE font only - bool mAntialiasColour; - - /// Range of code points to generate glyphs for (truetype only) - CodePointRangeList mCodePointRangeList; - - /// Internal method for loading from ttf - void createTextureFromFont(void); - - void loadImpl() override; - void unloadImpl() override; - size_t calculateSize(void) const override { return 0; } // permanent resource is in the texture - public: - - /** Constructor. - @see Resource - */ - Font(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual = false, ManualResourceLoader* loader = 0); - virtual ~Font(); - - /** Sets the type of font. Must be set before loading. */ - void setType(FontType ftype); - - /** Gets the type of font. */ - FontType getType(void) const; - - /** Sets the source of the font. - - If you have created a font of type FT_IMAGE, this method tells the - Font which image to use as the source for the characters. So the parameter - should be the name of an appropriate image file. Note that when using an image - as a font source, you will also need to tell the font where each character is - located using setGlyphTexCoords (for each character). - @par - If you have created a font of type FT_TRUETYPE, this method tells the - Font which .ttf file to use to generate the text. You will also need to call - setTrueTypeSize and setTrueTypeResolution, and call addCodePointRange - as many times as required to define the range of glyphs you want to be - available. - @param source An image file or a truetype font, depending on the type of this font - */ - void setSource(const String& source); - - /** Gets the source this font (either an image or a truetype font). - */ - const String& getSource(void) const; - - /** Sets the size of a truetype font (only required for FT_TRUETYPE). - @param ttfSize The size of the font in points. Note that the - size of the font does not affect how big it is on the screen, just how large it is in - the texture and thus how detailed it is. - */ - void setTrueTypeSize(Real ttfSize); - /** Gets the resolution (dpi) of the font used to generate the texture - (only required for FT_TRUETYPE). - @param ttfResolution The resolution in dpi - */ - void setTrueTypeResolution(uint ttfResolution); - - /** Gets the point size of the font used to generate the texture. - - Only applicable for FT_TRUETYPE Font objects. - Note that the size of the font does not affect how big it is on the screen, - just how large it is in the texture and thus how detailed it is. - */ - Real getTrueTypeSize(void) const; - /** Gets the resolution (dpi) of the font used to generate the texture. - - Only applicable for FT_TRUETYPE Font objects. - */ - uint getTrueTypeResolution(void) const; - /** Gets the maximum baseline distance of all glyphs used in the texture. - - Only applicable for FT_TRUETYPE Font objects. - The baseline is the vertical origin of horizontal based glyphs. The bearingY - attribute is the distance from the baseline (origin) to the top of the glyph's - bounding box. - @note - This value is only available after the font has been loaded. - */ - int getTrueTypeMaxBearingY() const; - - - /** Returns the texture coordinates of the associated glyph. - @remarks Parameter is a short to allow both ASCII and wide chars. - @param id The code point (unicode) - @return A rectangle with the UV coordinates, or null UVs if the - code point was not present - */ - const UVRect& getGlyphTexCoords(CodePoint id) const { return getGlyphInfo(id).uvRect; } - - /** Sets the texture coordinates of a glyph. - - You only need to call this if you're setting up a font loaded from a texture manually. - @note - Also sets the aspect ratio (width / height) of this character. textureAspect - is the width/height of the texture (may be non-square) - */ - void setGlyphInfoFromTexCoords(CodePoint id, const UVRect& rect, float textureAspect = 1.0) - { - auto glyphAspect = textureAspect * rect.width() / rect.height(); - setGlyphInfo({id, rect, glyphAspect, 0, glyphAspect}); - } - - void setGlyphInfo(const GlyphInfo& info) { mCodePointMap[info.codePoint] = info; } - - /** Gets the aspect ratio (width / height) of this character. */ - float getGlyphAspectRatio(CodePoint id) const { return getGlyphInfo(id).aspectRatio; } - /** Sets the aspect ratio (width / height) of this character. - - You only need to call this if you're setting up a font loaded from a - texture manually. - */ - void setGlyphAspectRatio(CodePoint id, Real ratio) - { - CodePointMap::iterator i = mCodePointMap.find(id); - if (i != mCodePointMap.end()) - { - i->second.aspectRatio = ratio; - } - } - - /** Gets the information available for a glyph corresponding to a - given code point, or throws an exception if it doesn't exist; - */ - const GlyphInfo& getGlyphInfo(CodePoint id) const - { - CodePointMap::const_iterator i = mCodePointMap.find(id); - if (i == mCodePointMap.end()) - { - // Try a fallback first. - i = mCodePointMap.find(static_cast('?')); - - if (i == mCodePointMap.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, StringUtil::format( - "Code point %d and fallback 63 not found in font %s", id, mName.c_str())); - } - } - return i->second; - } - - /** Adds a range of code points to the list of code point ranges to generate - glyphs for, if this is a truetype based font. - - In order to save texture space, only the glyphs which are actually - needed by the application are generated into the texture. Before this - object is loaded you must call this method as many times as necessary - to define the code point range that you need. - */ - void addCodePointRange(const CodePointRange& range) - { - mCodePointRangeList.push_back(range); - } - - /** Clear the list of code point ranges. - */ - void clearCodePointRanges() - { - mCodePointRangeList.clear(); - } - /** Get a const reference to the list of code point ranges to be used to - generate glyphs from a truetype font. - */ - const CodePointRangeList& getCodePointRangeList() const - { - return mCodePointRangeList; - } - /** Gets the material generated for this font, as a weak reference. - - This will only be valid after the Font has been loaded. - */ - inline const MaterialPtr& getMaterial() const - { - return mMaterial; - } - - /** - * Write a text into a BillboardSet for positioning in Space - * - * Text is laid out in the x-y plane, running into x+ and using y+ as up - * @param bbs the target BillboardSet - * @param text text to write - * @param height character height in world units - * @param colour text colour - */ - void putText(BillboardSet* bbs, String text, float height, const ColourValue& colour = ColourValue::White); - - /** Sets whether the colour of this font is multiplied with alpha as it is generated - from a true type font. - - This is valid only for a FT_TRUETYPE font. If you are planning on using - alpha blending to draw your font, then set this to - false (which is the default), otherwise the darkening of the font will combine - with the fading out of the alpha around the edges and make your font look thinner - than it should. However, if you intend to use premultipled alpha or a colour blending - mode (add or modulate for example) then set this to true, in - order to soften your font edges. - */ - inline void setAntialiasColour(bool enabled) - { - mAntialiasColour = enabled; - } - - /** Gets whether or not the colour of this font is antialiased as it is generated - from a true type font. - */ - inline bool getAntialiasColour(void) const - { - return mAntialiasColour; - } - - /** Implementation of ManualResourceLoader::loadResource, called - when the Texture that this font creates needs to (re)load. - */ - void loadResource(Resource* resource) override; - - /** Manually set the material used for this font. - - This should only be used when the font is being loaded from a - ManualResourceLoader. - */ - void _setMaterial(const MaterialPtr& mat); - }; - - typedef SharedPtr FontPtr; - /** @} */ - /** @} */ -} - -#endif diff --git a/Components/Overlay/include/OgreFontManager.h b/Components/Overlay/include/OgreFontManager.h deleted file mode 100644 index fd154982083..00000000000 --- a/Components/Overlay/include/OgreFontManager.h +++ /dev/null @@ -1,96 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ - -#ifndef _FontManager_H__ -#define _FontManager_H__ - -#include "OgreOverlayPrerequisites.h" -#include "OgreSingleton.h" -#include "OgreResourceManager.h" -#include "OgreFont.h" - -namespace Ogre -{ - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Overlays - * @{ - */ - /** Manages Font resources, parsing .fontdef files and generally organising them.*/ - class _OgreOverlayExport FontManager : public ResourceManager, public Singleton< FontManager > - { - public: - - FontManager(); - ~FontManager(); - - /// Create a new font - /// @see ResourceManager::createResource - FontPtr create (const String& name, const String& group, - bool isManual = false, ManualResourceLoader* loader = 0, - const NameValuePairList* createParams = 0); - - /// Get a font by name. For example, one defined in some .fontdef file. - /// @see ResourceManager::getResourceByName - FontPtr getByName(const String& name, const String& groupName OGRE_RESOURCE_GROUP_INIT) const; - - /** Override standard Singleton retrieval. - - Why do we do this? Well, it's because the Singleton - implementation is in a .h file, which means it gets compiled - into anybody who includes it. This is needed for the - Singleton template to work, but we actually only want it - compiled into the implementation of the class based on the - Singleton, not all of them. If we don't change this, we get - link errors when trying to use the Singleton-based class from - an outside dll. - @par - This method just delegates to the template version anyway, - but the implementation stays in this single compilation unit, - preventing link errors. - */ - static FontManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static FontManager* getSingletonPtr(void); - - private: - - /// Internal methods - Resource* createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* params) override; - void parseAttribute(const String& line, FontPtr& pFont); - - void logBadAttrib(const String& line, FontPtr& pFont); - - - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/Components/Overlay/include/OgreImGuiOverlay.h b/Components/Overlay/include/OgreImGuiOverlay.h deleted file mode 100644 index e24eb2d2f61..00000000000 --- a/Components/Overlay/include/OgreImGuiOverlay.h +++ /dev/null @@ -1,84 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. - -#ifndef COMPONENTS_OVERLAY_INCLUDE_OGREIMGUIOVERLAY_H_ -#define COMPONENTS_OVERLAY_INCLUDE_OGREIMGUIOVERLAY_H_ - -#include "OgreOverlay.h" -#include "OgreOverlayPrerequisites.h" -#include - -#include - -namespace Ogre -{ -///Ogre's integrated support for [Dear ImGui](https://github.com/ocornut/imgui) -class _OgreOverlayExport ImGuiOverlay : public Overlay -{ -public: - ImGuiOverlay(); - ~ImGuiOverlay(); - - /// add font from ogre .fontdef file. - /// Must be called before first show() - /// for the new font to be used. - ImFont* addFont(const String& name, const String& group OGRE_RESOURCE_GROUP_INIT); - - /// generally should be called before every frame, - /// before you render things with ImGui - /// for example, at the start of a RenderTargetListener::preViewportUpdate - /// - /// Must be called before the first frame - /// with a visible ImGuiOverlay is rendered - /// or else ImgGUI will SegFault. - /// - /// Must be called before many ImgGUI functions - /// or else they will SegFault. - static void NewFrame(); - - void _findVisibleObjects(Camera* cam, RenderQueue* queue, Viewport* vp) override; - -private: - void initialise() override; - - typedef std::vector CodePointRange; - std::vector mCodePointRanges; - - class ImGUIRenderable : public Ogre::Renderable - { - public: - ImGUIRenderable(); - ~ImGUIRenderable(); - - void initialise(); - - void updateVertexData(ImDrawData* draw_data); - - bool preRender(SceneManager* sm, RenderSystem* rsys) override; - - void getWorldTransforms(Matrix4* xform) const override { *xform = mXform; } - void getRenderOperation(RenderOperation& op) override { op = mRenderOp; } - - const LightList& getLights(void) const override; - - void createMaterial(); - void createFontTexture(); - - const MaterialPtr& getMaterial() const override { return mMaterial; } - - Real getSquaredViewDepth(const Camera*) const override { return 0; } - - void _update(); - - Matrix4 mXform; - RenderOperation mRenderOp; - TexturePtr mFontTex; - MaterialPtr mMaterial; - }; - - ImGUIRenderable mRenderable; -}; -} // namespace Ogre - -#endif /* COMPONENTS_OVERLAY_INCLUDE_OGREIMGUIOVERLAY_H_ */ diff --git a/Components/Overlay/include/OgreOverlay.h b/Components/Overlay/include/OgreOverlay.h deleted file mode 100644 index 4e497f3f7ff..00000000000 --- a/Components/Overlay/include/OgreOverlay.h +++ /dev/null @@ -1,284 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Overlay_H__ -#define __Overlay_H__ - -#include "OgreOverlayPrerequisites.h" -#include "OgreMatrix4.h" -#include "OgreViewport.h" - -namespace Ogre { - class OverlayContainer; - class OverlayElement; - - /** \addtogroup Optional - * @{ - */ - /** \defgroup Overlays Overlay - * Layers which is rendered on top of the 'normal' scene contents - * @{ - */ - /** Represents a layer which is rendered on top of the 'normal' scene contents. - - An overlay is a container for visual components (2D and 3D) which will be - rendered after the main scene in order to composite heads-up-displays, menus - or other layers on top of the contents of the scene. - @par - An overlay always takes up the entire size of the viewport, although the - components attached to it do not have to. An overlay has no visual element - in itself, it it merely a container for visual elements. - @par - Overlays are created by calling OverlayManager::create, or by defining them - in special text scripts (.overlay files). As many overlays - as you like can be defined; after creation an overlay is hidden i.e. not - visible until you specifically enable it by calling 'show'. This allows you to have multiple - overlays predefined (menus etc) which you make visible only when you want. - It is possible to have multiple overlays enabled at once; in this case the - relative 'zorder' parameter of the overlays determine which one is displayed - on top. - @par - By default overlays are rendered into all viewports. This is fine when you only - have fullscreen viewports, but if you have picture-in-picture views, you probably - don't want the overlay displayed in the smaller viewports. You turn this off for - a specific viewport by calling the Viewport::setDisplayOverlays method. - */ - class _OgreOverlayExport Overlay : public OverlayAlloc - { - - public: - typedef std::list OverlayContainerList; - protected: - String mName; - /// Internal root node, used as parent for 3D objects - SceneNode* mRootNode; - /** 2D elements - OverlayContainers, linked list for easy sorting by zorder later - Not a map because sort can be saved since changes infrequent (unlike render queue) */ - OverlayContainerList m2DElements; - - /// Degrees of rotation around center - Radian mRotate; - /// Scroll values, offsets - Real mScrollX, mScrollY; - /// Scale values - Real mScaleX, mScaleY; - - int mLastViewportWidth, mLastViewportHeight; - - mutable Matrix4 mTransform; - mutable bool mTransformOutOfDate; - bool mTransformUpdated; - ulong mZOrder; - bool mVisible; - bool mInitialised; - String mOrigin; - /** Internal lazy update method. */ - void updateTransform(void) const; - /** Internal method for initialising an overlay */ - virtual void initialise(void); - /** Internal method for updating container elements' Z-ordering */ - void assignZOrders(void); - - public: - /// Constructor: do not call direct, use OverlayManager::create - Overlay(const String& name); - virtual ~Overlay(); - - - OverlayContainer* getChild(const String& name); - - /** Gets the name of this overlay. */ - const String& getName(void) const; - - /** Alters the Z-order of this overlay. - - Values between 0 and 650 are valid here. - */ - void setZOrder(ushort zorder); - /** Gets the Z-order of this overlay. */ - ushort getZOrder(void) const; - - /** Gets whether the overlay is displayed or not. */ - bool isVisible(void) const; - - /** Gets whether the overlay is initialised or not. */ - bool isInitialised(void) const { return mInitialised; } - - /** Shows the overlay if it was hidden. */ - void show(void); - - /** Hides the overlay if it was visible. */ - void hide(void); - - /** Shows or hides this overlay. */ - void setVisible(bool visible); - - /** Adds a 2D 'container' to the overlay. - - Containers are created and managed using the OverlayManager. A container - could be as simple as a square panel, or something more complex like - a grid or tree view. Containers group collections of other elements, - giving them a relative coordinate space and a common z-order. - If you want to attach a GUI widget to an overlay, you have to do it via - a container. - @param cont Pointer to a container to add, created using OverlayManager. - */ - void add2D(OverlayContainer* cont); - - - /** Removes a 2D container from the overlay. - - NOT FAST. Consider OverlayElement::hide. - */ - void remove2D(OverlayContainer* cont); - - /** Adds a node capable of holding 3D objects to the overlay. - - Although overlays are traditionally associated with 2D elements, there - are reasons why you might want to attach 3D elements to the overlay too. - For example, if you wanted to have a 3D cockpit, which was overlaid with a - HUD, then you would create 2 overlays, one with a 3D object attached for the - cockpit, and one with the HUD elements attached (the zorder of the HUD - overlay would be higher than the cockpit to ensure it was always on top). - @par - A SceneNode can have any number of 3D objects attached to it. SceneNodes - are usually created using SceneManager::createSceneNode, but in this case - you should create a standard SceneNode instance manually; this is - because these scene nodes are not managed by the SceneManager and some custom - SceneManager plugins will rely on specialist behaviour the overlay does not - support. By attaching a SceneNode to an overlay, you indicate that:
    -
  1. You want the contents of this node to only appear when the overlay is active
  2. -
  3. You want the node to inherit a coordinate space relative to the camera, - rather than relative to the root scene node
  4. -
  5. You want these objects to be rendered after the contents of the main scene - to ensure they are rendered on top
  6. -
- One major consideration when using 3D objects in overlays is the behaviour of - the depth buffer. Overlays should use materials with depth checking off, to ensure - that their contents are always displayed on top of the main scene (to do - otherwise would result in objects 'poking through' the overlay). The problem - with using 3D objects is that if they are concave, or self-overlap, then you - can get artefacts because of the lack of depth buffer checking. So you should - ensure that any 3D objects you us in the overlay are convex, and don't overlap - each other. If they must overlap, split them up and put them in 2 overlays. - Alternatively, use a 2D element underneath them which will clear the depth buffer - values underneath ready for the 3D element to be rendered correctly. - */ - void add3D(SceneNode* node); - - /** Removes a 3D element from the overlay. */ - void remove3D(SceneNode* node); - - /** Clears the overlay of all attached items. */ - void clear(); - - /** Sets the scrolling factor of this overlay. - - You can use this to set an offset to be used to scroll an - overlay around the screen. - @param x Horizontal scroll value, where 0 = normal, -0.5 = scroll so that only - the right half the screen is visible etc - @param y Vertical scroll value, where 0 = normal, 0.5 = scroll down by half - a screen etc. - */ - void setScroll(Real x, Real y); - - /** Gets the current X scroll value */ - Real getScrollX(void) const; - - /** Gets the current Y scroll value */ - Real getScrollY(void) const; - - /** Scrolls the overlay by the offsets provided. - - This method moves the overlay by the amounts provided. As with - other methods on this object, a full screen width / height is represented - by the value 1.0. - */ - void scroll(Real xoff, Real yoff); - - /** Sets the rotation applied to this overlay.*/ - void setRotate(const Radian& angle); - - /** Gets the rotation applied to this overlay, in degrees.*/ - const Radian &getRotate(void) const { return mRotate; } - - /** Adds the passed in angle to the rotation applied to this overlay. */ - void rotate(const Radian& angle); - - /** Sets the scaling factor of this overlay. - - You can use this to set an scale factor to be used to zoom an - overlay. - @param x Horizontal scale value, where 1.0 = normal, 0.5 = half size etc - @param y Vertical scale value, where 1.0 = normal, 0.5 = half size etc - */ - void setScale(Real x, Real y); - - /** Gets the current X scale value */ - Real getScaleX(void) const; - - /** Gets the current Y scale value */ - Real getScaleY(void) const; - - /** Used to transform the overlay when scrolling, scaling etc. */ - void _getWorldTransforms(Matrix4* xform) const; - - /** Internal method to put the overlay contents onto the render queue. */ - virtual void _findVisibleObjects(Camera* cam, RenderQueue* queue, Viewport* vp); - - /** This returns a OverlayElement at position x,y. */ - virtual OverlayElement* findElementAt(Real x, Real y); - - /** Returns all 2D elements in this manager. - */ - const OverlayContainerList& get2DElements() const { - return m2DElements; - } - - /** Get the origin of this overlay, e.g. a script file name. - - This property will only contain something if the creator of - this overlay chose to populate it. Script loaders are advised - to populate it. - */ - const String& getOrigin(void) const { return mOrigin; } - /// Notify this overlay of it's origin - void _notifyOrigin(const String& origin) { mOrigin = origin; } - - - }; - /** @} */ - /** @} */ - -} - - -#endif - diff --git a/Components/Overlay/include/OgreOverlay.i b/Components/Overlay/include/OgreOverlay.i deleted file mode 100644 index 53bf83ad5a1..00000000000 --- a/Components/Overlay/include/OgreOverlay.i +++ /dev/null @@ -1,86 +0,0 @@ -#ifdef SWIGPYTHON -%module(package="Ogre", directors="1") Overlay -#else -%module OgreOverlay -#endif -%{ -/* Includes the header in the wrapper code */ -#include "Ogre.h" - -#include "OgreOverlayPrerequisites.h" -#include "OgreFont.h" -#include "OgreFontManager.h" -#include "OgreOverlay.h" -#include "OgreOverlaySystem.h" -#include "OgreOverlayContainer.h" -#include "OgreOverlayElement.h" -#include "OgreOverlayElementFactory.h" -#include "OgreOverlayManager.h" -#include "OgrePanelOverlayElement.h" -#include "OgreTextAreaOverlayElement.h" - -%} -#ifdef HAVE_IMGUI -%{ -#include "OgreImGuiOverlay.h" -%} -#endif - -%include std_string.i -%include exception.i -#ifdef SWIGPYTHON -%include factory.i -#endif -%import "Ogre.i" - -#define _OgreOverlayExport - -#ifdef SWIGCSHARP -%csmethodmodifiers Ogre::OverlaySystem::eventOccurred "public"; -#endif - -%include "OgreOverlayPrerequisites.h" -SHARED_PTR(Font); -%include "OgreFont.h" -%include "OgreFontManager.h" -%ignore Ogre::Overlay::get2DElementsIterator; -%include "OgreOverlay.h" -SHARED_PTR(OverlayElement); -%extend Ogre::OverlayElement { - OverlayContainer* castOverlayContainer() - { - return dynamic_cast($self); - } - Ogre::PanelOverlayElement* castPanelOverlayElement() - { - return dynamic_cast($self); - } - Ogre::TextAreaOverlayElement* castTextAreaOverlayElement() - { - return dynamic_cast($self); - } -} -%include "OgreOverlayElement.h" -%feature("director") Ogre::OverlayElementFactory; -%include "OgreOverlayElementFactory.h" -SHARED_PTR(OverlayContainer); -%ignore Ogre::OverlayContainer::getChildIterator; -%ignore Ogre::OverlayContainer::getChildContainerIterator; -%include "OgreOverlayContainer.h" -#ifdef SWIGPYTHON -%factory(Ogre::OverlayElement* Ogre::OverlayManager::createOverlayElement, Ogre::OverlayContainer); -#endif -%ignore Ogre::OverlayManager::getTemplateIterator; -%ignore Ogre::OverlayManager::getOverlayIterator; -%include "OgreOverlayManager.h" -SHARED_PTR(OverlaySystem); -%include "OgreOverlaySystem.h" -SHARED_PTR(PanelOverlayElement); -%include "OgrePanelOverlayElement.h" -%ignore Ogre::TextAreaOverlayElement::getFontName; -SHARED_PTR(TextAreaOverlayElement); -%include "OgreTextAreaOverlayElement.h" - -#ifdef HAVE_IMGUI -%include "OgreImGuiOverlay.h" -#endif \ No newline at end of file diff --git a/Components/Overlay/include/OgreOverlayContainer.h b/Components/Overlay/include/OgreOverlayContainer.h deleted file mode 100644 index fbb0369aa41..00000000000 --- a/Components/Overlay/include/OgreOverlayContainer.h +++ /dev/null @@ -1,154 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __OverlayContainer_H__ -#define __OverlayContainer_H__ - -#include "OgreOverlayPrerequisites.h" -#include "OgreOverlayElement.h" - - -namespace Ogre { - template class MapIterator; - - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Overlays - * @{ - */ - /** A 2D element which contains other OverlayElement instances. - - This is a specialisation of OverlayElement for 2D elements that contain other - elements. These are also the smallest elements that can be attached directly - to an Overlay. - - OverlayContainers should be managed using OverlayManager. This class is responsible for - instantiating / deleting elements, and also for accepting new types of element - from plugins etc. - */ - class _OgreOverlayExport OverlayContainer : public OverlayElement - { - public: - typedef std::map ChildMap; - typedef MapIterator ChildIterator; - typedef std::map ChildContainerMap; - typedef MapIterator ChildContainerIterator; - private: - /// Map of all children - ChildMap mChildren; - /// Map of container children (subset of mChildren) - ChildContainerMap mChildContainers; - - bool mChildrenProcessEvents; - - public: - /// Constructor: do not call direct, use OverlayManager::createOverlayElement - OverlayContainer(const String& name); - virtual ~OverlayContainer(); - - /** Adds another OverlayElement to this container. */ - virtual void addChild(OverlayElement* elem); - /** Adds another OverlayElement to this container. */ - virtual void addChildImpl(OverlayElement* elem); - /** Add a nested container to this container. */ - virtual void addChildImpl(OverlayContainer* cont); - /** Removes a named element from this container. */ - virtual void removeChild(const String& name); - /** Gets the named child of this container. */ - virtual OverlayElement* getChild(const String& name); - - /** @copydoc OverlayElement::initialise */ - void initialise(void) override; - - void _addChild(OverlayElement* elem); - void _removeChild(OverlayElement* elem) { _removeChild(elem->getName()); } - void _removeChild(const String& name); - - /** Gets all the children of this object. */ - const ChildMap& getChildren() const { return mChildren; } - - /// @deprecated use getChildren( - OGRE_DEPRECATED virtual ChildIterator getChildIterator(void); - - /** Gets an iterator for just the container children of this object. - - Good for cascading updates without having to use RTTI - */ - virtual ChildContainerIterator getChildContainerIterator(void); - - /** Tell the object and its children to recalculate */ - void _positionsOutOfDate(void) override; - - /** Overridden from OverlayElement. */ - void _update(void) override; - - /** Overridden from OverlayElement. */ - ushort _notifyZOrder(ushort newZOrder) override; - - /** Overridden from OverlayElement. */ - void _notifyViewport() override; - - /** Overridden from OverlayElement. */ - void _notifyWorldTransforms(const Matrix4& xform) override; - - /** Overridden from OverlayElement. */ - void _notifyParent(OverlayContainer* parent, Overlay* overlay) override; - - /** Overridden from OverlayElement. */ - void _updateRenderQueue(RenderQueue* queue) override; - - /** Overridden from OverlayElement. */ - inline bool isContainer() const override - { return true; } - - /** Should this container pass events to their children */ - virtual inline bool isChildrenProcessEvents() const - { return true; } - - /** Should this container pass events to their children */ - virtual inline void setChildrenProcessEvents(bool val) - { mChildrenProcessEvents = val; } - - /** This returns a OverlayElement at position x,y. */ - OverlayElement* findElementAt(Real x, Real y) override; // relative to parent - - void copyFromTemplate(OverlayElement* templateOverlay) override; - OverlayElement* clone(const String& instanceName) override; - - }; - - - /** @} */ - /** @} */ - -} - - -#endif - diff --git a/Components/Overlay/include/OgreOverlayElement.h b/Components/Overlay/include/OgreOverlayElement.h deleted file mode 100644 index df0bcc8ac14..00000000000 --- a/Components/Overlay/include/OgreOverlayElement.h +++ /dev/null @@ -1,472 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __OverlayElement_H__ -#define __OverlayElement_H__ - -#include "OgreOverlayPrerequisites.h" -#include "OgreRenderable.h" -#include "OgreStringInterface.h" -#include "OgreColourValue.h" - -namespace Ogre { - class Overlay; - class OverlayContainer; - - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Overlays - * @{ - */ - - typedef String DisplayString; - - /** Enum describing how the position / size of an element is to be recorded. - */ - enum GuiMetricsMode - { - /// 'left', 'top', 'height' and 'width' are parametrics from 0.0 to 1.0 - GMM_RELATIVE, - /// Positions & sizes are in absolute pixels - GMM_PIXELS, - /// Positions & sizes are in virtual pixels - GMM_RELATIVE_ASPECT_ADJUSTED - }; - - /** Enum describing where '0' is in relation to the parent in the horizontal dimension. - @remarks Affects how 'left' is interpreted. - */ - enum GuiHorizontalAlignment - { - GHA_LEFT, - GHA_CENTER, - GHA_RIGHT - }; - /** Enum describing where '0' is in relation to the parent in the vertical dimension. - @remarks Affects how 'top' is interpreted. - */ - enum GuiVerticalAlignment - { - GVA_TOP, - GVA_CENTER, - GVA_BOTTOM - }; - - /** Abstract definition of a 2D element to be displayed in an Overlay. - - This class abstracts all the details of a 2D element which will appear in - an overlay. In fact, not all OverlayElement instances can be directly added to an - Overlay, only those which are OverlayContainer instances (a subclass of this class). - OverlayContainer objects can contain any OverlayElement however. This is just to - enforce some level of grouping on widgets. - @par - OverlayElements should be managed using OverlayManager. This class is responsible for - instantiating / deleting elements, and also for accepting new types of element - from plugins etc. - @par - Note that positions / dimensions of 2D screen elements are expressed as parametric - values (0.0 - 1.0) because this makes them resolution-independent. However, most - screen resolutions have an aspect ratio of 1.3333:1 (width : height) so note that - in physical pixels 0.5 is wider than it is tall, so a 0.5x0.5 panel will not be - square on the screen (but it will take up exactly half the screen in both dimensions). - @par - Because this class is designed to be extensible, it subclasses from StringInterface - so its parameters can be set in a generic way. - */ - class _OgreOverlayExport OverlayElement : public StringInterface, public Renderable, public OverlayAlloc - { - public: - static const String& DEFAULT_RESOURCE_GROUP; - protected: - String mName; - bool mVisible; - bool mCloneable; - Real mLeft; - Real mTop; - Real mWidth; - Real mHeight; - MaterialPtr mMaterial; - DisplayString mCaption; - ColourValue mColour; - RealRect mClippingRegion; - - GuiMetricsMode mMetricsMode; - GuiHorizontalAlignment mHorzAlign; - GuiVerticalAlignment mVertAlign; - - // metric-mode positions, used in GMM_PIXELS & GMM_RELATIVE_ASPECT_ADJUSTED mode. - Real mPixelTop; - Real mPixelLeft; - Real mPixelWidth; - Real mPixelHeight; - Real mPixelScaleX; - Real mPixelScaleY; - - /// Parent pointer - OverlayContainer* mParent; - /// Overlay attached to - Overlay* mOverlay; - - // Derived positions from parent - Real mDerivedLeft; - Real mDerivedTop; - bool mDerivedOutOfDate; - - /// Flag indicating if the vertex positions need recalculating - bool mGeomPositionsOutOfDate; - /// Flag indicating if the vertex uvs need recalculating - bool mGeomUVsOutOfDate; - - /** Zorder for when sending to render queue. - Derived from parent */ - ushort mZOrder; - - /// World transforms - Matrix4 mXForm; - - /// Is element enabled? - bool mEnabled; - - /// Is element initialised? - bool mInitialised; - - /** Internal method which is triggered when the positions of the element get updated, - meaning the element should be rebuilding it's mesh positions. Abstract since - subclasses must implement this. - */ - virtual void updatePositionGeometry(void) = 0; - /** Internal method which is triggered when the UVs of the element get updated, - meaning the element should be rebuilding it's mesh UVs. Abstract since - subclasses must implement this. - */ - virtual void updateTextureGeometry(void) = 0; - - /** Internal method for setting up the basic parameter definitions for a subclass. - - Because StringInterface holds a dictionary of parameters per class, subclasses need to - call this to ask the base class to add it's parameters to their dictionary as well. - Can't do this in the constructor because that runs in a non-virtual context. - @par - The subclass must have called it's own createParamDictionary before calling this method. - */ - virtual void addBaseParameters(void); - - public: - /// Constructor: do not call direct, use OverlayManager::createElement - OverlayElement(const String& name); - virtual ~OverlayElement(); - - /** Initialise gui element */ - virtual void initialise(void) = 0; - - /** Notifies that hardware resources were lost */ - virtual void _releaseManualHardwareResources() {} - /** Notifies that hardware resources should be restored */ - virtual void _restoreManualHardwareResources() {} - - /** Gets the name of this overlay. */ - const String& getName(void) const { return mName; } - - - /** Shows this element if it was hidden. */ - void show(void) { setVisible(true); } - - /** Hides this element if it was visible. */ - void hide(void) { setVisible(false); } - - /** Shows or hides this element. */ - void setVisible(bool visible) { mVisible = visible; } - - /** Returns whether or not the element is visible. */ - bool isVisible(void) const { return mVisible; } - - bool isEnabled() const { return mEnabled; } - void setEnabled(bool b) { mEnabled = b; } - - - /** Sets the dimensions of this element in relation to the current #GuiMetricsMode. */ - void setDimensions(Real width, Real height); - - /** Sets the position of the top-left corner in relation to the current #GuiMetricsMode (where 0 = top). */ - void setPosition(Real left, Real top); - - /** Sets the width of this element in relation to the current #GuiMetricsMode. */ - void setWidth(Real width); - /** Gets the width of this element in relation to the current #GuiMetricsMode. */ - Real getWidth(void) const; - - /** Sets the height of this element in relation to the current #GuiMetricsMode. */ - void setHeight(Real height); - /** Gets the height of this element in relation to the current #GuiMetricsMode. */ - Real getHeight(void) const; - - /** Sets the left of this element in relation to the current #GuiMetricsMode. */ - void setLeft(Real left); - /** Gets the left of this element in relation to the current #GuiMetricsMode. */ - Real getLeft(void) const; - - /** Sets the top of this element in relation to the current #GuiMetricsMode (where 0 = top). */ - void setTop(Real Top); - /** Gets the top of this element in relation to the current #GuiMetricsMode (where 0 = top). */ - Real getTop(void) const; - - /** Gets the left of this element in relation to the screen (where 0 = far left, 1.0 = far right) */ - Real _getLeft(void) const { return mLeft; } - /** Gets the top of this element in relation to the screen (where 0 = far top, 1.0 = far bottom) */ - Real _getTop(void) const { return mTop; } - /** Gets the width of this element in relation to the screen (where 1.0 = screen width) */ - Real _getWidth(void) const { return mWidth; } - /** Gets the height of this element in relation to the screen (where 1.0 = screen height) */ - Real _getHeight(void) const { return mHeight; } - /** Sets the left of this element in relation to the screen (where 1.0 = screen width) */ - void _setLeft(Real left); - /** Sets the top of this element in relation to the screen (where 1.0 = screen height) */ - void _setTop(Real top); - /** Sets the width of this element in relation to the screen (where 1.0 = screen width) */ - void _setWidth(Real width); - /** Sets the height of this element in relation to the screen (where 1.0 = screen height) */ - void _setHeight(Real height); - /** Sets the left and top of this element in relation to the screen (where 1.0 = screen width/height) */ - void _setPosition(Real left, Real top); - /** Sets the width and height of this element in relation to the screen (where 1.0 = screen width/height) */ - void _setDimensions(Real width, Real height); - - /** Gets the name of the material this element uses. */ - virtual const String& getMaterialName(void) const; - - /** Sets the the material this element will use. - - Different elements will use different materials. One constant about them - all though is that a Material used for a OverlayElement must have it's depth - checking set to 'off', which means it always gets rendered on top. OGRE - will set this flag for you if necessary. What it does mean though is that - you should not use the same Material for rendering OverlayElements as standard - scene objects. It's fine to use the same textures, just not the same - Material. - */ - - void setMaterial(const MaterialPtr& mat); - - /// @overload - void setMaterialName(const String& matName, const String& group = DEFAULT_RESOURCE_GROUP ); - - - // --- Renderable Overrides --- - const MaterialPtr& getMaterial(void) const override; - - // NB getRenderOperation not implemented, still abstract here - - void getWorldTransforms(Matrix4* xform) const override; - - /** Tell the object to recalculate */ - virtual void _positionsOutOfDate(void); - - /** Internal method to update the element based on transforms applied. */ - virtual void _update(void); - - /** Updates this elements transform based on it's parent. */ - virtual void _updateFromParent(void); - - /** Internal method for notifying the GUI element of it's parent and ultimate overlay. */ - virtual void _notifyParent(OverlayContainer* parent, Overlay* overlay); - - /** Gets the 'left' position as derived from own left and that of parents. */ - virtual Real _getDerivedLeft(void); - - /** Gets the 'top' position as derived from own left and that of parents. */ - virtual Real _getDerivedTop(void); - - /** Gets the 'width' as derived from own width and metrics mode. */ - virtual Real _getRelativeWidth(void); - /** Gets the 'height' as derived from own height and metrics mode. */ - virtual Real _getRelativeHeight(void); - - - /** Gets the clipping region of the element */ - virtual void _getClippingRegion(RealRect &clippingRegion); - - /** Internal method to notify the element when Z-order of parent overlay - has changed. - - Overlays have explicit Z-orders. OverlayElements do not, they inherit the - Z-order of the overlay, and the Z-order is incremented for every container - nested within this to ensure that containers are displayed behind contained - items. This method is used internally to notify the element of a change in - final Z-order which is used to render the element. - @return Return the next Z-ordering number available. For single elements, this - is simply 'newZOrder + 1', except for containers. They increment it once for each - child (or even more if those children are also containers with their own elements). - */ - virtual ushort _notifyZOrder(ushort newZOrder); - - /** Internal method to notify the element when it's world transform - of parent overlay has changed. - */ - virtual void _notifyWorldTransforms(const Matrix4& xform); - - /** Internal method to notify the element when the viewport - of parent overlay has changed. - */ - virtual void _notifyViewport(); - - /** Internal method to put the contents onto the render queue. */ - virtual void _updateRenderQueue(RenderQueue* queue); - - /// @copydoc MovableObject::visitRenderables - void visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables = false); - - /** Gets the type name of the element. All concrete subclasses must implement this. */ - virtual const String& getTypeName(void) const = 0; - - /** Sets the caption on elements that support it. - - This property doesn't do something on all elements, just those that support it. - However, being a common requirement it is in the top-level interface to avoid - having to set it via the StringInterface all the time. - */ - virtual void setCaption(const DisplayString& text); - /** Gets the caption for this element. */ - const DisplayString& getCaption(void) const { return mCaption; } - /** Sets the colour on elements that support it. - - This property doesn't do something on all elements, just those that support it. - However, being a common requirement it is in the top-level interface to avoid - having to set it via the StringInterface all the time. - */ - virtual void setColour(const ColourValue& col); - - /** Gets the colour for this element. */ - virtual const ColourValue& getColour(void) const; - - /** Tells this element how to interpret the position and dimension values it is given. - - By default, OverlayElements are positioned and sized according to relative dimensions - of the screen. This is to ensure portability between different resolutions when you - want things to be positioned and sized the same way across all resolutions. However, - sometimes you want things to be sized according to fixed pixels. In order to do this, - you can call this method with the parameter GMM_PIXELS. Note that if you then want - to place your element relative to the center, right or bottom of it's parent, you will - need to use the setHorizontalAlignment and setVerticalAlignment methods. - */ - virtual void setMetricsMode(GuiMetricsMode gmm); - /** Retrieves the current settings of how the element metrics are interpreted. */ - GuiMetricsMode getMetricsMode(void) const { return mMetricsMode; } - /** Sets the horizontal origin for this element. - - By default, the horizontal origin for a OverlayElement is the left edge of the parent container - (or the screen if this is a root element). You can alter this by calling this method, which is - especially useful when you want to use pixel-based metrics (see setMetricsMode) since in this - mode you can't use relative positioning. - @par - For example, if you were using GMM_PIXELS metrics mode, and you wanted to place a 30x30 pixel - crosshair in the center of the screen, you would use GHA_CENTER with a 'left' property of -15. - @par - Note that neither GHA_CENTER or GHA_RIGHT alter the position of the element based - on it's width, you have to alter the 'left' to a negative number to do that; all this - does is establish the origin. This is because this way you can align multiple things - in the center and right with different 'left' offsets for maximum flexibility. - */ - virtual void setHorizontalAlignment(GuiHorizontalAlignment gha); - /** Gets the horizontal alignment for this element. */ - GuiHorizontalAlignment getHorizontalAlignment(void) const { return mHorzAlign; } - /** Sets the vertical origin for this element. - - By default, the vertical origin for a OverlayElement is the top edge of the parent container - (or the screen if this is a root element). You can alter this by calling this method, which is - especially useful when you want to use pixel-based metrics (see setMetricsMode) since in this - mode you can't use relative positioning. - @par - For example, if you were using GMM_PIXELS metrics mode, and you wanted to place a 30x30 pixel - crosshair in the center of the screen, you would use GHA_CENTER with a 'top' property of -15. - @par - Note that neither GVA_CENTER or GVA_BOTTOM alter the position of the element based - on it's height, you have to alter the 'top' to a negative number to do that; all this - does is establish the origin. This is because this way you can align multiple things - in the center and bottom with different 'top' offsets for maximum flexibility. - */ - virtual void setVerticalAlignment(GuiVerticalAlignment gva); - /** Gets the vertical alignment for this element. */ - GuiVerticalAlignment getVerticalAlignment(void) const { return mVertAlign; } - - - - - /** Returns true if xy is within the constraints of the component */ - virtual bool contains(Real x, Real y) const; - - /** Returns true if xy is within the constraints of the component */ - virtual OverlayElement* findElementAt(Real x, Real y); // relative to parent - - /** - * returns false as this class is not a container type - */ - virtual bool isContainer() const { return false; } - virtual bool isKeyEnabled() const { return false; } - bool isCloneable() const { return mCloneable; } - void setCloneable(bool c) { mCloneable = c; } - - /** - * Returns the parent container. - */ - OverlayContainer* getParent() { return mParent; } - void _setParent(OverlayContainer* parent) { mParent = parent; } - - /** - * Returns the zOrder of the element - */ - ushort getZOrder() const { return mZOrder; } - - Real getSquaredViewDepth(const Camera* cam) const override - { - (void)cam; - return 10000.0f - (Real)getZOrder(); - } - - /** @copydoc Renderable::getLights */ - const LightList& getLights(void) const override - { - // Overlayelements should not be lit by the scene, this will not get called - static LightList ll; - return ll; - } - - virtual void copyFromTemplate(OverlayElement* templateOverlay) { templateOverlay->copyParametersTo(this); } - virtual OverlayElement* clone(const String& instanceName); - }; - - - /** @} */ - /** @} */ - -} - - -#endif - diff --git a/Components/Overlay/include/OgreOverlayElementFactory.h b/Components/Overlay/include/OgreOverlayElementFactory.h deleted file mode 100644 index 04302f3320c..00000000000 --- a/Components/Overlay/include/OgreOverlayElementFactory.h +++ /dev/null @@ -1,76 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OverlayElementFactory_H__ -#define __OverlayElementFactory_H__ - -#include "OgreOverlayPrerequisites.h" -#include "OgreOverlayElement.h" -#include "OgrePanelOverlayElement.h" -#include "OgreBorderPanelOverlayElement.h" -#include "OgreTextAreaOverlayElement.h" - -namespace Ogre { - - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Overlays - * @{ - */ - /** Defines the interface which all components wishing to - supply OverlayElement subclasses must implement. - - To allow the OverlayElement types available for inclusion on - overlays to be extended, OGRE allows external apps or plugins - to register their ability to create custom OverlayElements with - the OverlayManager, using the addOverlayElementFactory method. Classes - wanting to do this must implement this interface. - @par - Each OverlayElementFactory creates a single type of OverlayElement, - identified by a 'type name' which must be unique. - */ - class _OgreOverlayExport OverlayElementFactory : public OverlayAlloc - { - public: - /** Destroy the overlay element factory */ - virtual ~OverlayElementFactory () {} - /** Creates a new OverlayElement instance with the name supplied. */ - virtual OverlayElement* createOverlayElement(const String& instanceName) OGRE_NODISCARD = 0; - /** Destroys a OverlayElement which this factory created previously. */ - virtual void destroyOverlayElement(OverlayElement* pElement) { delete pElement; } - /** Gets the string uniquely identifying the type of element this factory creates. */ - virtual const String& getTypeName(void) const = 0; - }; - /** @} */ - /** @} */ - -} - - - -#endif diff --git a/Components/Overlay/include/OgreOverlayManager.h b/Components/Overlay/include/OgreOverlayManager.h deleted file mode 100644 index 9a103efa1b1..00000000000 --- a/Components/Overlay/include/OgreOverlayManager.h +++ /dev/null @@ -1,215 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OverlayManager_H__ -#define __OverlayManager_H__ - -#include "OgreOverlayPrerequisites.h" -#include "OgreSingleton.h" -#include "OgreStringVector.h" -#include "OgreScriptLoader.h" -#include "OgreFrustum.h" -#include "OgreScriptTranslator.h" - -namespace Ogre { - class Overlay; - class OverlayContainer; - class OverlayElement; - class OverlayElementFactory; - template class MapIterator; - - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Overlays - * @{ - */ - /** Manages Overlay objects, parsing them from .overlay files and - storing a lookup library of them. Also manages the creation of - OverlayContainers and OverlayElements, used for non-interactive 2D - elements such as HUDs. - */ - class _OgreOverlayExport OverlayManager : public Singleton, public ScriptLoader, public OverlayAlloc - { - public: - typedef std::map OverlayMap; - typedef std::map ElementMap; - typedef std::map FactoryMap; - private: - OverlayMap mOverlayMap; - StringVector mScriptPatterns; - - int mLastViewportWidth, mLastViewportHeight; - float mPixelRatio; - - bool parseChildren( DataStreamPtr& chunk, const String& line, int& l, - Overlay* pOverlay, bool isTemplate, OverlayContainer* parent = NULL); - - FactoryMap mFactories; - - ElementMap mElements; - - typedef std::set LoadedScripts; - LoadedScripts mLoadedScripts; - - std::unique_ptr mTranslatorManager; - - public: - OverlayManager(); - virtual ~OverlayManager(); - - /** Notifies that hardware resources were lost */ - void _releaseManualHardwareResources(); - /** Notifies that hardware resources should be restored */ - void _restoreManualHardwareResources(); - - /// @copydoc ScriptLoader::getScriptPatterns - const StringVector& getScriptPatterns(void) const override; - /// @copydoc ScriptLoader::parseScript - void parseScript(DataStreamPtr& stream, const String& groupName) override; - /// @copydoc ScriptLoader::getLoadingOrder - Real getLoadingOrder(void) const override; - - void addOverlay(Overlay* overlay); - - /** Create a new Overlay. */ - Overlay* create(const String& name); - /** Retrieve an Overlay by name. For example, one defined in some .overlay file. - @return A pointer to the Overlay, or 0 if not found - */ - Overlay* getByName(const String& name); - /** Destroys an existing overlay by name */ - void destroy(const String& name); - /** Destroys an existing overlay */ - void destroy(Overlay* overlay); - /** Destroys all existing overlays */ - void destroyAll(void); - typedef MapIterator OverlayMapIterator; - OverlayMapIterator getOverlayIterator(void); - - /** Internal method for queueing the visible overlays for rendering. */ - void _queueOverlaysForRendering(Camera* cam, RenderQueue* pQueue, Viewport *vp); - - /** Gets the height of the destination viewport in pixels. */ - int getViewportHeight(void) const; - - /** Gets the width of the destination viewport in pixels. */ - int getViewportWidth(void) const; - Real getViewportAspectRatio(void) const; - - /** Sets the pixel ratio: how many viewport pixels represent a single overlay pixel (in one dimension). - - By default this is an 1:1 mapping. However on HiDPI screens you want to increase that to scale up your Overlay. - @see RenderWindow::getViewPointToPixelScale */ - void setPixelRatio(float ratio); - float getPixelRatio() const; - - /** Creates a new OverlayElement of the type requested. - - The type of element to create is passed in as a string because this - allows plugins to register new types of component. - @param typeName The type of element to create. - @param instanceName The name to give the new instance. - */ - OverlayElement* createOverlayElement(const String& typeName, const String& instanceName, bool = false); - - /** Gets a reference to an existing element. */ - OverlayElement* getOverlayElement(const String& name, bool = false); - - /** Tests if an element exists. */ - bool hasOverlayElement(const String& name, bool = false); - - /** Destroys a OverlayElement. - - Make sure you're not still using this in an Overlay. If in - doubt, let OGRE destroy elements on shutdown. - */ - void destroyOverlayElement(const String& instanceName, bool = false); - - /** Destroys a OverlayElement. - - Make sure you're not still using this in an Overlay. If in - doubt, let OGRE destroy elements on shutdown. - */ - void destroyOverlayElement(OverlayElement* pInstance, bool = false); - - /** Destroys all the OverlayElement created so far. - - Best to leave this to the engine to call internally, there - should rarely be a need to call it yourself. - */ - void destroyAllOverlayElements(bool = false); - - /** Registers a new OverlayElementFactory with this manager. - - Should be used by plugins or other apps wishing to provide - a new OverlayElement subclass. - */ - void addOverlayElementFactory(OverlayElementFactory* elemFactory); - - /** Get const access to the list of registered OverlayElement factories. */ - const FactoryMap& getOverlayElementFactoryMap() const { - return mFactories; - } - - OverlayElement* createOverlayElementFromTemplate(const String& templateName, const String& typeName, const String& instanceName, bool = false); - /** - * Creates a new OverlayElement object from the specified template name. The new - * object's name, and all of it's children, will be instanceName/orignalName. - */ - OverlayElement* cloneOverlayElementFromTemplate(const String& templateName, const String& instanceName); - - OverlayElement* createOverlayElementFromFactory(const String& typeName, const String& instanceName); - - /** Override standard Singleton retrieval. - - Why do we do this? Well, it's because the Singleton - implementation is in a .h file, which means it gets compiled - into anybody who includes it. This is needed for the - Singleton template to work, but we actually only want it - compiled into the implementation of the class based on the - Singleton, not all of them. If we don't change this, we get - link errors when trying to use the Singleton-based class from - an outside dll. - @par - This method just delegates to the template version anyway, - but the implementation stays in this single compilation unit, - preventing link errors. - */ - static OverlayManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static OverlayManager* getSingletonPtr(void); - }; - - - /** @} */ - /** @} */ - -} - - -#endif diff --git a/Components/Overlay/include/OgreOverlayProfileSessionListener.h b/Components/Overlay/include/OgreOverlayProfileSessionListener.h deleted file mode 100644 index e5eb3bcddbc..00000000000 --- a/Components/Overlay/include/OgreOverlayProfileSessionListener.h +++ /dev/null @@ -1,154 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __OverlayProfileSessionListener_H__ -#define __OverlayProfileSessionListener_H__ - -#include "OgreOverlayPrerequisites.h" -#include "OgreProfiler.h" - -namespace Ogre { - class Overlay; - class OverlayContainer; - class OverlayElement; - - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Overlays - * @{ - */ - - /** Concrete impl. of the ProfileSessionListener which visualizes - the profling results using overlays. - */ - class _OgreOverlayExport OverlayProfileSessionListener : public ProfileSessionListener - { - public: - enum DisplayMode - { - /// Display % frame usage on the overlay - DISPLAY_PERCENTAGE, - /// Display milliseconds on the overlay - DISPLAY_MILLISECONDS - }; - - OverlayProfileSessionListener(); - virtual ~OverlayProfileSessionListener(); - - /// @see ProfileSessionListener::initializeSession - void initializeSession() override; - - /// @see ProfileSessionListener::finializeSession - void finializeSession() override; - - /// @see ProfileSessionListener::displayResults - void displayResults(const ProfileInstance& instance, ulong maxTotalFrameTime) override; - - /// @see ProfileSessionListener::changeEnableState - void changeEnableState(bool enabled) override; - - /** Set the size of the profiler overlay, in pixels. */ - void setOverlayDimensions(Real width, Real height); - - /** Set the position of the profiler overlay, in pixels. */ - void setOverlayPosition(Real left, Real top); - - Real getOverlayWidth() const; - Real getOverlayHeight() const; - Real getOverlayLeft() const; - Real getOverlayTop() const; - - /// Set the display mode for the overlay. - void setDisplayMode(DisplayMode d) { mDisplayMode = d; } - - /// Get the display mode for the overlay. - DisplayMode getDisplayMode() const { return mDisplayMode; } - - private: - typedef std::list ProfileBarList; - - /** Prints the profiling results of each frame - @remarks Recursive, for all the little children. */ - void displayResults(ProfileInstance* instance, ProfileBarList::const_iterator& bIter, Real& maxTimeMillisecs, Real& newGuiHeight, int& profileCount); - - /** An internal function to create the container which will hold our display elements*/ - OverlayContainer* createContainer(); - - /** An internal function to create a text area */ - OverlayElement* createTextArea(const String& name, Real width, Real height, Real top, Real left, - uint fontSize, const String& caption, bool show = true); - - /** An internal function to create a panel */ - OverlayElement* createPanel(const String& name, Real width, Real height, Real top, Real left, - const String& materialName, bool show = true); - - /// Holds the display bars for each profile results - ProfileBarList mProfileBars; - - /// The overlay which contains our profiler results display - Overlay* mOverlay; - - /// The window that displays the profiler results - OverlayContainer* mProfileGui; - - /// The height of each bar - Real mBarHeight; - - /// The height of the stats window - Real mGuiHeight; - - /// The width of the stats window - Real mGuiWidth; - - /// The horz position of the stats window - Real mGuiLeft; - - /// The vertical position of the stats window - Real mGuiTop; - - /// The size of the indent for each profile display bar - Real mBarIndent; - - /// The width of the border between the profile window and each bar - Real mGuiBorderWidth; - - /// The width of the min, avg, and max lines in a profile display - Real mBarLineWidth; - - /// The distance between bars - Real mBarSpacing; - - /// The max number of profiles we can display - uint mMaxDisplayProfiles; - - /// How to display the overlay - DisplayMode mDisplayMode; - }; -} -#endif diff --git a/Components/Overlay/include/OgreOverlaySystem.h b/Components/Overlay/include/OgreOverlaySystem.h deleted file mode 100644 index 7cd355dfa2d..00000000000 --- a/Components/Overlay/include/OgreOverlaySystem.h +++ /dev/null @@ -1,78 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __OverlaySystem_H__ -#define __OverlaySystem_H__ - -#include "OgreOverlayPrerequisites.h" -#include "OgreRenderQueueListener.h" -#include "OgreRenderSystem.h" -#include "OgreOverlayProfileSessionListener.h" - -namespace Ogre { - class OverlayManager; - class FontManager; - - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Overlays - * @{ - */ - /** This class simplify initialization / finalization of the overlay system. - OGRE root did this steps before the overlay system transformed into a component. - - Before you create a concrete instance of the OverlaySystem the OGRE::Root must be created - but not initialized. In the ctor all relevant systems are created and registered. The dtor - must be called before you delete OGRE::Root. - To make the overlays visible (= render into your viewports) you have to register this - instance as a RenderQueueListener in your scenemanager(s). - */ - class _OgreOverlayExport OverlaySystem - : public Singleton - , public Ogre::RenderQueueListener - , public Ogre::RenderSystem::Listener - { - public: - OverlaySystem(); - virtual ~OverlaySystem(); - - void renderQueueStarted(uint8 queueGroupId, const String& cameraName, bool& skipThisInvocation) override; - - void eventOccurred(const String& eventName, const NameValuePairList* parameters) override; - - static OverlaySystem& getSingleton(); - static OverlaySystem* getSingletonPtr(); - private: - OverlayManager* mOverlayManager; - FontManager* mFontManager; - OverlayProfileSessionListener* mProfileListener; - }; - -} -#endif diff --git a/Components/Overlay/include/OgrePanelOverlayElement.h b/Components/Overlay/include/OgrePanelOverlayElement.h deleted file mode 100644 index 52a4128dd1b..00000000000 --- a/Components/Overlay/include/OgrePanelOverlayElement.h +++ /dev/null @@ -1,134 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __PanelOverlayElement_H__ -#define __PanelOverlayElement_H__ - -#include "OgreOverlayContainer.h" -#include "OgreRenderOperation.h" - -namespace Ogre { - - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Overlays - * @{ - */ - /** OverlayElement representing a flat, single-material (or transparent) panel which can contain other elements. - - This class subclasses OverlayContainer because it can contain other elements. Like other - containers, if hidden it's contents are also hidden, if moved it's contents also move etc. - The panel itself is a 2D rectangle which is either completely transparent, or is rendered - with a single material. The texture(s) on the panel can be tiled depending on your requirements. - @par - This component is suitable for backgrounds and grouping other elements. Note that because - it has a single repeating material it cannot have a discrete border (unless the texture has one and - the texture is tiled only once). For a bordered panel, see it's subclass BorderPanelOverlayElement. - @par - Note that the material can have all the usual effects applied to it like multiple texture - layers, scrolling / animated textures etc. For multiple texture layers, you have to set - the tiling level for each layer. - */ - class _OgreOverlayExport PanelOverlayElement : public OverlayContainer - { - public: - /** Constructor. */ - PanelOverlayElement(const String& name); - virtual ~PanelOverlayElement(); - - /** Initialise */ - void initialise(void) override; - - /** @copydoc OverlayElement::_releaseManualHardwareResources */ - void _releaseManualHardwareResources() override; - /** @copydoc OverlayElement::_restoreManualHardwareResources */ - void _restoreManualHardwareResources() override; - - /** Sets the number of times textures should repeat. - @param x The number of times the texture should repeat horizontally - @param y The number of times the texture should repeat vertically - @param layer The texture layer to specify (only needs to be altered if - you're using a multi-texture layer material) - */ - void setTiling(Real x, Real y, ushort layer = 0); - - Real getTileX(ushort layer = 0) const; - /** Gets the number of times the texture should repeat vertically. - @param layer The texture layer to specify (only needs to be altered if - you're using a multi-texture layer material) - */ - Real getTileY(ushort layer = 0) const; - - /** Sets the texture coordinates for the panel. */ - void setUV(Real u1, Real v1, Real u2, Real v2); - - /** Get the uv coordinates for the panel*/ - void getUV(Real& u1, Real& v1, Real& u2, Real& v2) const; - - /** Sets whether this panel is transparent (used only as a grouping level), or - if it is actually rendered. - */ - void setTransparent(bool isTransparent); - - /** Returns whether this panel is transparent. */ - bool isTransparent(void) const; - - const String& getTypeName(void) const override; - void getRenderOperation(RenderOperation& op) override; - /** Overridden from OverlayContainer */ - void _updateRenderQueue(RenderQueue* queue) override; - - protected: - /// Flag indicating if this panel should be visual or just group things - bool mTransparent; - // Texture tiling - Real mTileX[OGRE_MAX_TEXTURE_LAYERS]; - Real mTileY[OGRE_MAX_TEXTURE_LAYERS]; - size_t mNumTexCoordsInBuffer; - Real mU1, mV1, mU2, mV2; - - RenderOperation mRenderOp; - - /// Internal method for setting up geometry, called by OverlayElement::update - void updatePositionGeometry(void) override; - - /// Called to update the texture coords when layers change - void updateTextureGeometry(void) override; - - /// Method for setting up base parameters for this class - void addBaseParameters(void) override; - - static String msTypeName; - }; - /** @} */ - /** @} */ - -} - -#endif diff --git a/Components/Overlay/include/OgreTextAreaOverlayElement.h b/Components/Overlay/include/OgreTextAreaOverlayElement.h deleted file mode 100644 index e50419b39f6..00000000000 --- a/Components/Overlay/include/OgreTextAreaOverlayElement.h +++ /dev/null @@ -1,173 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ - -#ifndef _TextAreaOverlayElement_H__ -#define _TextAreaOverlayElement_H__ - -#include "OgreOverlayElement.h" -#include "OgreRenderOperation.h" -#include "OgreFont.h" - -namespace Ogre -{ - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Overlays - * @{ - */ - /** This class implements an overlay element which contains simple unformatted text. - */ - class _OgreOverlayExport TextAreaOverlayElement : public OverlayElement - { - public: - enum Alignment - { - Left, - Right, - Center - }; - - public: - /** Constructor. */ - TextAreaOverlayElement(const String& name); - virtual ~TextAreaOverlayElement(); - - void initialise(void) override; - - /** @copydoc OverlayElement::_releaseManualHardwareResources */ - void _releaseManualHardwareResources() override; - /** @copydoc OverlayElement::_restoreManualHardwareResources */ - void _restoreManualHardwareResources() override; - - void setCaption(const DisplayString& text) override; - - void setCharHeight( Real height ); - Real getCharHeight() const; - - void setSpaceWidth( Real width ); - Real getSpaceWidth() const; - - void setFontName( const String& font, const String& group = DEFAULT_RESOURCE_GROUP ); - /// @deprecated use getFont() - OGRE_DEPRECATED const String& getFontName() const; - - const FontPtr& getFont() const { - return mFont; - } - - const String& getTypeName(void) const override; - const MaterialPtr& getMaterial(void) const override; - void getRenderOperation(RenderOperation& op) override; - - /** Sets the colour of the text. - - This method establishes a constant colour for - the entire text. Also see setColourBottom and - setColourTop which allow you to set a colour gradient. - */ - void setColour(const ColourValue& col) override; - - /** Gets the colour of the text. */ - const ColourValue& getColour(void) const override; - /** Sets the colour of the bottom of the letters. - - By setting a separate top and bottom colour, you - can create a text area which has a graduated colour - effect to it. - */ - void setColourBottom(const ColourValue& col); - /** Gets the colour of the bottom of the letters. */ - const ColourValue& getColourBottom(void) const; - /** Sets the colour of the top of the letters. - - By setting a separate top and bottom colour, you - can create a text area which has a graduated colour - effect to it. - */ - void setColourTop(const ColourValue& col); - /** Gets the colour of the top of the letters. */ - const ColourValue& getColourTop(void) const; - - inline void setAlignment( Alignment a ) - { - mAlignment = a; - mGeomPositionsOutOfDate = true; - } - inline Alignment getAlignment() const - { - return mAlignment; - } - - /** Overridden from OverlayElement */ - void setMetricsMode(GuiMetricsMode gmm) override; - - /** Overridden from OverlayElement */ - void _update(void) override; - private: - /// The text alignment - Alignment mAlignment; - - /// Flag indicating if this panel should be visual or just group things - bool mTransparent; - - /// Render operation - RenderOperation mRenderOp; - - /// Method for setting up base parameters for this class - void addBaseParameters(void) override; - - static String msTypeName; - - FontPtr mFont; - Real mCharHeight; - ushort mPixelCharHeight; - Real mSpaceWidth; - ushort mPixelSpaceWidth; - size_t mAllocSize; - Real mViewportAspectCoef; - - /// Colours to use for the vertices - ColourValue mColourBottom; - ColourValue mColourTop; - bool mColoursChanged; - - - /// Internal method to allocate memory, only reallocates when necessary - void checkMemoryAllocation( size_t numChars ); - /// Inherited function - void updatePositionGeometry() override; - /// Inherited function - void updateTextureGeometry() override; - /// Updates vertex colours - virtual void updateColours(void); - }; - /** @} */ - /** @} */ -} - -#endif - diff --git a/Components/Overlay/src/OgreBorderPanelOverlayElement.cpp b/Components/Overlay/src/OgreBorderPanelOverlayElement.cpp deleted file mode 100644 index e419e613b27..00000000000 --- a/Components/Overlay/src/OgreBorderPanelOverlayElement.cpp +++ /dev/null @@ -1,916 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreBorderPanelOverlayElement.h" -#include "OgreMaterialManager.h" -#include "OgreOverlayManager.h" -#include "OgreHardwareBufferManager.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreException.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" - -namespace Ogre { - //--------------------------------------------------------------------- - String BorderPanelOverlayElement::msTypeName = "BorderPanel"; - /** Command object for specifying border sizes (see ParamCommand).*/ - class _OgrePrivate CmdBorderSize : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for specifying the Material for the border (see ParamCommand).*/ - class _OgrePrivate CmdBorderMaterial : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for specifying texture coordinates for the border (see ParamCommand).*/ - class _OgrePrivate CmdBorderLeftUV : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for specifying texture coordinates for the border (see ParamCommand).*/ - class _OgrePrivate CmdBorderTopUV : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for specifying texture coordinates for the border (see ParamCommand).*/ - class _OgrePrivate CmdBorderRightUV : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for specifying texture coordinates for the border (see ParamCommand).*/ - class _OgrePrivate CmdBorderBottomUV : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for specifying texture coordinates for the border (see ParamCommand).*/ - class _OgrePrivate CmdBorderTopLeftUV : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for specifying texture coordinates for the border (see ParamCommand).*/ - class _OgrePrivate CmdBorderBottomLeftUV : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for specifying texture coordinates for the border (see ParamCommand).*/ - class _OgrePrivate CmdBorderBottomRightUV : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for specifying texture coordinates for the border (see ParamCommand).*/ - class _OgrePrivate CmdBorderTopRightUV : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - // Command objects - static CmdBorderSize msCmdBorderSize; - static CmdBorderMaterial msCmdBorderMaterial; - static CmdBorderLeftUV msCmdBorderLeftUV; - static CmdBorderTopUV msCmdBorderTopUV; - static CmdBorderBottomUV msCmdBorderBottomUV; - static CmdBorderRightUV msCmdBorderRightUV; - static CmdBorderTopLeftUV msCmdBorderTopLeftUV; - static CmdBorderBottomLeftUV msCmdBorderBottomLeftUV; - static CmdBorderTopRightUV msCmdBorderTopRightUV; - static CmdBorderBottomRightUV msCmdBorderBottomRightUV; - - #define BCELL_UV(x) (x * 4 * 2) - #define POSITION_BINDING 0 - #define TEXCOORD_BINDING 1 - //--------------------------------------------------------------------- - BorderPanelOverlayElement::BorderPanelOverlayElement(const String& name) - : PanelOverlayElement(name), - mLeftBorderSize(0), - mRightBorderSize(0), - mTopBorderSize(0), - mBottomBorderSize(0), - mPixelLeftBorderSize(0), - mPixelRightBorderSize(0), - mPixelTopBorderSize(0), - mPixelBottomBorderSize(0), - mBorderMaterial(), - mBorderRenderable(0) - { - mBorderUV->u1 = mBorderUV->u2 = mBorderUV->v1 = mBorderUV->v2 = 0; - - if (createParamDictionary("BorderPanelOverlayElement")) - { - addBaseParameters(); - } - } - //--------------------------------------------------------------------- - BorderPanelOverlayElement::~BorderPanelOverlayElement() - { - OGRE_DELETE mRenderOp2.vertexData; - OGRE_DELETE mRenderOp2.indexData; - OGRE_DELETE mBorderRenderable; - } - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::initialise(void) - { - bool init = !mInitialised; - - // init mRenderOp2 before calling superclass, as virtual _restoreManualHardwareResources would be called within - if (init) - { - // Setup render op in advance - mRenderOp2.vertexData = OGRE_NEW VertexData(); - mRenderOp2.vertexData->vertexCount = 4 * 8; // 8 cells, can't necessarily share vertices cos - // texcoords may differ - mRenderOp2.vertexData->vertexStart = 0; - - // Vertex declaration - VertexDeclaration* decl = mRenderOp2.vertexData->vertexDeclaration; - // Position and texture coords each have their own buffers to allow - // each to be edited separately with the discard flag - decl->addElement(POSITION_BINDING, 0, VET_FLOAT3, VES_POSITION); - decl->addElement(TEXCOORD_BINDING, 0, VET_FLOAT2, VES_TEXTURE_COORDINATES, 0); - - // Index data - mRenderOp2.operationType = RenderOperation::OT_TRIANGLE_LIST; - mRenderOp2.useIndexes = true; - mRenderOp2.indexData = OGRE_NEW IndexData(); - mRenderOp2.indexData->indexCount = 8 * 6; - mRenderOp2.indexData->indexStart = 0; - mRenderOp2.useGlobalInstancing = false; - - // Create sub-object for rendering border - mBorderRenderable = OGRE_NEW BorderRenderable(this); - } - - // superclass will handle the interior panel area and call _restoreManualHardwareResources - PanelOverlayElement::initialise(); - } - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::_restoreManualHardwareResources() - { - if(!mInitialised) - return; - - PanelOverlayElement::_restoreManualHardwareResources(); - - // Vertex data - - VertexDeclaration* decl = mRenderOp2.vertexData->vertexDeclaration; - - // Vertex buffer #1, position - HardwareVertexBufferSharedPtr vbuf = - HardwareBufferManager::getSingleton().createVertexBuffer( - decl->getVertexSize(POSITION_BINDING), - mRenderOp2.vertexData->vertexCount, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY, - true);//Workaround, using shadow buffer to avoid stall due to buffer mapping - // bind position - VertexBufferBinding* binding = mRenderOp2.vertexData->vertexBufferBinding; - binding->setBinding(POSITION_BINDING, vbuf); - - // Vertex buffer #2, texcoords - vbuf = HardwareBufferManager::getSingleton().createVertexBuffer( - decl->getVertexSize(TEXCOORD_BINDING), - mRenderOp2.vertexData->vertexCount, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY, - true);//Workaround, using shadow buffer to avoid stall due to buffer mapping - // bind texcoord - binding->setBinding(TEXCOORD_BINDING, vbuf); - - - // Index data - - /* Each cell is - 0-----2 - | /| - | / | - |/ | - 1-----3 - */ - mRenderOp2.indexData->indexBuffer = - HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, - mRenderOp2.indexData->indexCount, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY, - true);//Workaround, using shadow buffer to avoid stall due to buffer mapping - - HardwareBufferLockGuard indexLock(mRenderOp2.indexData->indexBuffer, HardwareBuffer::HBL_DISCARD); - ushort* pIdx = static_cast(indexLock.pData); - - for (ushort cell = 0; cell < 8; ++cell) - { - ushort base = cell * 4; - *pIdx++ = base; - *pIdx++ = base + 1; - *pIdx++ = base + 2; - - *pIdx++ = base + 2; - *pIdx++ = base + 1; - *pIdx++ = base + 3; - } - } - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::_releaseManualHardwareResources() - { - if(!mInitialised) - return; - - mRenderOp2.vertexData->vertexBufferBinding->unsetAllBindings(); - mRenderOp2.indexData->indexBuffer.reset(); - - PanelOverlayElement::_releaseManualHardwareResources(); - } - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::addBaseParameters(void) - { - PanelOverlayElement::addBaseParameters(); - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter(ParameterDef("border_size", - "The sizes of the borders relative to the screen size, in the order " - "left, right, top, bottom." - , PT_STRING), - &msCmdBorderSize); - dict->addParameter(ParameterDef("border_material", - "The material to use for the border." - , PT_STRING), - &msCmdBorderMaterial); - dict->addParameter(ParameterDef("border_topleft_uv", - "The texture coordinates for the top-left corner border texture. 2 sets of uv values, " - "one for the top-left corner, the other for the bottom-right corner." - , PT_STRING), - &msCmdBorderTopLeftUV); - dict->addParameter(ParameterDef("border_topright_uv", - "The texture coordinates for the top-right corner border texture. 2 sets of uv values, " - "one for the top-left corner, the other for the bottom-right corner." - , PT_STRING), - &msCmdBorderTopRightUV); - dict->addParameter(ParameterDef("border_bottomright_uv", - "The texture coordinates for the bottom-right corner border texture. 2 sets of uv values, " - "one for the top-left corner, the other for the bottom-right corner." - , PT_STRING), - &msCmdBorderBottomRightUV); - dict->addParameter(ParameterDef("border_bottomleft_uv", - "The texture coordinates for the bottom-left corner border texture. 2 sets of uv values, " - "one for the top-left corner, the other for the bottom-right corner." - , PT_STRING), - &msCmdBorderBottomLeftUV); - dict->addParameter(ParameterDef("border_left_uv", - "The texture coordinates for the left edge border texture. 2 sets of uv values, " - "one for the top-left corner, the other for the bottom-right corner." - , PT_STRING), - &msCmdBorderLeftUV); - dict->addParameter(ParameterDef("border_top_uv", - "The texture coordinates for the top edge border texture. 2 sets of uv values, " - "one for the top-left corner, the other for the bottom-right corner." - , PT_STRING), - &msCmdBorderTopUV); - dict->addParameter(ParameterDef("border_right_uv", - "The texture coordinates for the right edge border texture. 2 sets of uv values, " - "one for the top-left corner, the other for the bottom-right corner." - , PT_STRING), - &msCmdBorderRightUV); - dict->addParameter(ParameterDef("border_bottom_uv", - "The texture coordinates for the bottom edge border texture. 2 sets of uv values, " - "one for the top-left corner, the other for the bottom-right corner." - , PT_STRING), - &msCmdBorderBottomUV); - - } - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::setBorderSize(Real size) - { - if (mMetricsMode != GMM_RELATIVE) - { - mPixelLeftBorderSize = mPixelRightBorderSize = - mPixelTopBorderSize = mPixelBottomBorderSize = static_cast(size); - } - else - { - mLeftBorderSize = mRightBorderSize = - mTopBorderSize = mBottomBorderSize = size; - } - mGeomPositionsOutOfDate = true; - } - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::setBorderSize(Real sides, Real topAndBottom) - { - if (mMetricsMode != GMM_RELATIVE) - { - mPixelLeftBorderSize = mPixelRightBorderSize = static_cast(sides); - mPixelTopBorderSize = mPixelBottomBorderSize = static_cast(topAndBottom); - } - else - { - mLeftBorderSize = mRightBorderSize = sides; - mTopBorderSize = mBottomBorderSize = topAndBottom; - } - mGeomPositionsOutOfDate = true; - - - } - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::setBorderSize(Real left, Real right, Real top, Real bottom) - { - if (mMetricsMode != GMM_RELATIVE) - { - mPixelLeftBorderSize = static_cast(left); - mPixelRightBorderSize = static_cast(right); - mPixelTopBorderSize = static_cast(top); - mPixelBottomBorderSize = static_cast(bottom); - } - else - { - mLeftBorderSize = left; - mRightBorderSize = right; - mTopBorderSize = top; - mBottomBorderSize = bottom; - } - mGeomPositionsOutOfDate = true; - } - //--------------------------------------------------------------------- - Real BorderPanelOverlayElement::getLeftBorderSize(void) const - { - if (mMetricsMode == GMM_PIXELS) - { - return mPixelLeftBorderSize; - } - else - { - return mLeftBorderSize; - } - } - //--------------------------------------------------------------------- - Real BorderPanelOverlayElement::getRightBorderSize(void) const - { - if (mMetricsMode == GMM_PIXELS) - { - return mPixelRightBorderSize; - } - else - { - return mRightBorderSize; - } - } - //--------------------------------------------------------------------- - Real BorderPanelOverlayElement::getTopBorderSize(void) const - { - if (mMetricsMode == GMM_PIXELS) - { - return mPixelTopBorderSize; - } - else - { - return mTopBorderSize; - } - } - //--------------------------------------------------------------------- - Real BorderPanelOverlayElement::getBottomBorderSize(void) const - { - if (mMetricsMode == GMM_PIXELS) - { - return mPixelBottomBorderSize; - } - else - { - return mBottomBorderSize; - } - } - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::updateTextureGeometry() - { - PanelOverlayElement::updateTextureGeometry(); - /* Each cell is - 0-----2 - | /| - | / | - |/ | - 1-----3 - */ - // No choice but to lock / unlock each time here, but lock only small sections - - HardwareVertexBufferSharedPtr vbuf = - mRenderOp2.vertexData->vertexBufferBinding->getBuffer(TEXCOORD_BINDING); - // Can't use discard since this discards whole buffer - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - float* pUV = static_cast(vbufLock.pData); - - for (uint i = 0; i < 8; ++i) - { - *pUV++ = mBorderUV[i].u1; *pUV++ = mBorderUV[i].v1; - *pUV++ = mBorderUV[i].u1; *pUV++ = mBorderUV[i].v2; - *pUV++ = mBorderUV[i].u2; *pUV++ = mBorderUV[i].v1; - *pUV++ = mBorderUV[i].u2; *pUV++ = mBorderUV[i].v2; - } - } - //--------------------------------------------------------------------- - String BorderPanelOverlayElement::getCellUVString(BorderCellIndex idx) const - { - String ret = StringConverter::toString(mBorderUV[idx].u1) + " " + - StringConverter::toString(mBorderUV[idx].v1) + " " + - StringConverter::toString(mBorderUV[idx].u2) + " " + - StringConverter::toString(mBorderUV[idx].v2); - return ret; - } - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::setLeftBorderUV(Real u1, Real v1, Real u2, Real v2) - { - mBorderUV[BCELL_LEFT].u1 = u1; - mBorderUV[BCELL_LEFT].u2 = u2; - mBorderUV[BCELL_LEFT].v1 = v1; - mBorderUV[BCELL_LEFT].v2 = v2; - mGeomUVsOutOfDate = true; - } - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::setRightBorderUV(Real u1, Real v1, Real u2, Real v2) - { - mBorderUV[BCELL_RIGHT].u1 = u1; - mBorderUV[BCELL_RIGHT].u2 = u2; - mBorderUV[BCELL_RIGHT].v1 = v1; - mBorderUV[BCELL_RIGHT].v2 = v2; - mGeomUVsOutOfDate = true; - } - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::setTopBorderUV(Real u1, Real v1, Real u2, Real v2) - { - mBorderUV[BCELL_TOP].u1 = u1; - mBorderUV[BCELL_TOP].u2 = u2; - mBorderUV[BCELL_TOP].v1 = v1; - mBorderUV[BCELL_TOP].v2 = v2; - mGeomUVsOutOfDate = true; - } - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::setBottomBorderUV(Real u1, Real v1, Real u2, Real v2) - { - mBorderUV[BCELL_BOTTOM].u1 = u1; - mBorderUV[BCELL_BOTTOM].u2 = u2; - mBorderUV[BCELL_BOTTOM].v1 = v1; - mBorderUV[BCELL_BOTTOM].v2 = v2; - mGeomUVsOutOfDate = true; - } - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::setTopLeftBorderUV(Real u1, Real v1, Real u2, Real v2) - { - mBorderUV[BCELL_TOP_LEFT].u1 = u1; - mBorderUV[BCELL_TOP_LEFT].u2 = u2; - mBorderUV[BCELL_TOP_LEFT].v1 = v1; - mBorderUV[BCELL_TOP_LEFT].v2 = v2; - mGeomUVsOutOfDate = true; - } - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::setTopRightBorderUV(Real u1, Real v1, Real u2, Real v2) - { - mBorderUV[BCELL_TOP_RIGHT].u1 = u1; - mBorderUV[BCELL_TOP_RIGHT].u2 = u2; - mBorderUV[BCELL_TOP_RIGHT].v1 = v1; - mBorderUV[BCELL_TOP_RIGHT].v2 = v2; - mGeomUVsOutOfDate = true; - } - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::setBottomLeftBorderUV(Real u1, Real v1, Real u2, Real v2) - { - mBorderUV[BCELL_BOTTOM_LEFT].u1 = u1; - mBorderUV[BCELL_BOTTOM_LEFT].u2 = u2; - mBorderUV[BCELL_BOTTOM_LEFT].v1 = v1; - mBorderUV[BCELL_BOTTOM_LEFT].v2 = v2; - mGeomUVsOutOfDate = true; - } - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::setBottomRightBorderUV(Real u1, Real v1, Real u2, Real v2) - { - mBorderUV[BCELL_BOTTOM_RIGHT].u1 = u1; - mBorderUV[BCELL_BOTTOM_RIGHT].u2 = u2; - mBorderUV[BCELL_BOTTOM_RIGHT].v1 = v1; - mBorderUV[BCELL_BOTTOM_RIGHT].v2 = v2; - mGeomUVsOutOfDate = true; - } - - //--------------------------------------------------------------------- - String BorderPanelOverlayElement::getLeftBorderUVString() const - { - return getCellUVString(BCELL_LEFT); - } - //--------------------------------------------------------------------- - String BorderPanelOverlayElement::getRightBorderUVString() const - { - return getCellUVString(BCELL_RIGHT); - } - //--------------------------------------------------------------------- - String BorderPanelOverlayElement::getTopBorderUVString() const - { - return getCellUVString(BCELL_TOP); - } - //--------------------------------------------------------------------- - String BorderPanelOverlayElement::getBottomBorderUVString() const - { - return getCellUVString(BCELL_BOTTOM); - } - //--------------------------------------------------------------------- - String BorderPanelOverlayElement::getTopLeftBorderUVString() const - { - return getCellUVString(BCELL_TOP_LEFT); - } - //--------------------------------------------------------------------- - String BorderPanelOverlayElement::getTopRightBorderUVString() const - { - return getCellUVString(BCELL_TOP_RIGHT); - } - //--------------------------------------------------------------------- - String BorderPanelOverlayElement::getBottomLeftBorderUVString() const - { - return getCellUVString(BCELL_BOTTOM_LEFT); - } - //--------------------------------------------------------------------- - String BorderPanelOverlayElement::getBottomRightBorderUVString() const - { - return getCellUVString(BCELL_BOTTOM_RIGHT); - } - - - - - - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::setBorderMaterialName(const String& name, const String& group) - { - mBorderMaterial = MaterialManager::getSingleton().getByName(name, group); - if (!mBorderMaterial) - OGRE_EXCEPT( Exception::ERR_ITEM_NOT_FOUND, "Could not find material " + name, - "BorderPanelOverlayElement::setBorderMaterialName" ); - mBorderMaterial->load(); - // Set some prerequisites to be sure - mBorderMaterial->setLightingEnabled(false); - mBorderMaterial->setDepthCheckEnabled(false); - mBorderMaterial->setReceiveShadows(false); - - } - //--------------------------------------------------------------------- - const String& BorderPanelOverlayElement::getBorderMaterialName(void) const - { - return mBorderMaterial ? mBorderMaterial->getName() : BLANKSTRING; - } - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::updatePositionGeometry(void) - { - /* - Grid is like this: - +--+---------------+--+ - |0 | 1 |2 | - +--+---------------+--+ - | | | | - | | | | - |3 | center |4 | - | | | | - +--+---------------+--+ - |5 | 6 |7 | - +--+---------------+--+ - */ - // Convert positions into -1, 1 coordinate space (homogenous clip space) - // Top / bottom also need inverting since y is upside down - float left[8], right[8], top[8], bottom[8]; - // Horizontal - left[0] = left[3] = left[5] = _getDerivedLeft() * 2 - 1; - left[1] = left[6] = right[0] = right[3] = right[5] = left[0] + (mLeftBorderSize * 2); - right[2] = right[4] = right[7] = left[0] + (mWidth * 2); - left[2] = left[4] = left[7] = right[1] = right[6] = right[2] - (mRightBorderSize * 2); - // Vertical - top[0] = top[1] = top[2] = -((_getDerivedTop() * 2) - 1); - top[3] = top[4] = bottom[0] = bottom[1] = bottom[2] = top[0] - (mTopBorderSize * 2); - bottom[5] = bottom[6] = bottom[7] = top[0] - (mHeight * 2); - top[5] = top[6] = top[7] = bottom[3] = bottom[4] = bottom[5] + (mBottomBorderSize * 2); - - // Lock the whole position buffer in discard mode - HardwareVertexBufferSharedPtr vbuf = - mRenderOp2.vertexData->vertexBufferBinding->getBuffer(POSITION_BINDING); - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - float* pPos = static_cast(vbufLock.pData); - // Use the furthest away depth value, since materials should have depth-check off - // This initialised the depth buffer for any 3D objects in front - float zValue = Root::getSingleton().getRenderSystem()->getMaximumDepthInputValue(); - for (ushort cell = 0; cell < 8; ++cell) - { - /* - 0-----2 - | /| - | / | - |/ | - 1-----3 - */ - *pPos++ = left[cell]; - *pPos++ = top[cell]; - *pPos++ = zValue; - - *pPos++ = left[cell]; - *pPos++ = bottom[cell]; - *pPos++ = zValue; - - *pPos++ = right[cell]; - *pPos++ = top[cell]; - *pPos++ = zValue; - - *pPos++ = right[cell]; - *pPos++ = bottom[cell]; - *pPos++ = zValue; - - } - vbufLock.unlock(); - - // Also update center geometry - // NB don't use superclass because we need to make it smaller because of border - vbuf = mRenderOp.vertexData->vertexBufferBinding->getBuffer(POSITION_BINDING); - vbufLock.lock(vbuf, HardwareBuffer::HBL_DISCARD); - pPos = static_cast(vbufLock.pData); - // Use cell 1 and 3 to determine positions - *pPos++ = left[1]; - *pPos++ = top[3]; - *pPos++ = zValue; - - *pPos++ = left[1]; - *pPos++ = bottom[3]; - *pPos++ = zValue; - - *pPos++ = right[1]; - *pPos++ = top[3]; - *pPos++ = zValue; - - *pPos++ = right[1]; - *pPos++ = bottom[3]; - *pPos++ = zValue; - - vbufLock.unlock(); - } - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::_updateRenderQueue(RenderQueue* queue) - { - // Add self twice to the queue - // Have to do this to allow 2 materials - if (mVisible) - { - - // Add outer - queue->addRenderable(mBorderRenderable, RENDER_QUEUE_OVERLAY, mZOrder); - - // do inner last so the border artifacts don't overwrite the children - // Add inner - PanelOverlayElement::_updateRenderQueue(queue); - } - } - //--------------------------------------------------------------------- - void BorderPanelOverlayElement::visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables) - { - visitor->visit(mBorderRenderable, 0, false); - PanelOverlayElement::visitRenderables(visitor, debugRenderables); - } - //----------------------------------------------------------------------- - void BorderPanelOverlayElement::setMetricsMode(GuiMetricsMode gmm) - { - PanelOverlayElement::setMetricsMode(gmm); - if (gmm != GMM_RELATIVE) - { - mPixelBottomBorderSize = static_cast(mBottomBorderSize); - mPixelLeftBorderSize = static_cast(mLeftBorderSize); - mPixelRightBorderSize = static_cast(mRightBorderSize); - mPixelTopBorderSize = static_cast(mTopBorderSize); - } - } - //----------------------------------------------------------------------- - void BorderPanelOverlayElement::_update(void) - { - if (mMetricsMode != GMM_RELATIVE && - mGeomPositionsOutOfDate) - { - mLeftBorderSize = mPixelLeftBorderSize * mPixelScaleX; - mRightBorderSize = mPixelRightBorderSize * mPixelScaleX; - mTopBorderSize = mPixelTopBorderSize * mPixelScaleY; - mBottomBorderSize = mPixelBottomBorderSize * mPixelScaleY; - mGeomPositionsOutOfDate = true; - } - PanelOverlayElement::_update(); - } - //----------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - // Command objects - //--------------------------------------------------------------------- - //----------------------------------------------------------------------- - String CmdBorderSize::doGet(const void* target) const - { - const BorderPanelOverlayElement* t = static_cast(target); - return String( - StringConverter::toString(t->getLeftBorderSize()) + " " + - StringConverter::toString(t->getRightBorderSize()) + " " + - StringConverter::toString(t->getTopBorderSize()) + " " + - StringConverter::toString(t->getBottomBorderSize()) ); - } - void CmdBorderSize::doSet(void* target, const String& val) - { - std::vector vec = StringUtil::split(val); - - static_cast(target)->setBorderSize( - StringConverter::parseReal(vec[0]), - StringConverter::parseReal(vec[1]), - StringConverter::parseReal(vec[2]), - StringConverter::parseReal(vec[3]) - ); - } - //----------------------------------------------------------------------- - String CmdBorderMaterial::doGet(const void* target) const - { - // No need right now.. - return static_cast(target)->getBorderMaterialName(); - } - void CmdBorderMaterial::doSet(void* target, const String& val) - { - std::vector vec = StringUtil::split(val); - - static_cast(target)->setBorderMaterialName(val); - } - //----------------------------------------------------------------------- - String CmdBorderBottomLeftUV::doGet(const void* target) const - { - // No need right now.. - return static_cast(target)->getBottomLeftBorderUVString(); - } - void CmdBorderBottomLeftUV::doSet(void* target, const String& val) - { - std::vector vec = StringUtil::split(val); - - static_cast(target)->setBottomLeftBorderUV( - StringConverter::parseReal(vec[0]), - StringConverter::parseReal(vec[1]), - StringConverter::parseReal(vec[2]), - StringConverter::parseReal(vec[3]) - ); - } - //----------------------------------------------------------------------- - String CmdBorderBottomRightUV::doGet(const void* target) const - { - // No need right now.. - return static_cast(target)->getBottomRightBorderUVString(); - } - void CmdBorderBottomRightUV::doSet(void* target, const String& val) - { - std::vector vec = StringUtil::split(val); - - static_cast(target)->setBottomRightBorderUV( - StringConverter::parseReal(vec[0]), - StringConverter::parseReal(vec[1]), - StringConverter::parseReal(vec[2]), - StringConverter::parseReal(vec[3]) - ); - } - //----------------------------------------------------------------------- - String CmdBorderTopLeftUV::doGet(const void* target) const - { - // No need right now.. - return static_cast(target)->getTopLeftBorderUVString(); - } - void CmdBorderTopLeftUV::doSet(void* target, const String& val) - { - std::vector vec = StringUtil::split(val); - - static_cast(target)->setTopLeftBorderUV( - StringConverter::parseReal(vec[0]), - StringConverter::parseReal(vec[1]), - StringConverter::parseReal(vec[2]), - StringConverter::parseReal(vec[3]) - ); - } - //----------------------------------------------------------------------- - String CmdBorderTopRightUV::doGet(const void* target) const - { - // No need right now.. - return static_cast(target)->getTopRightBorderUVString(); - } - void CmdBorderTopRightUV::doSet(void* target, const String& val) - { - std::vector vec = StringUtil::split(val); - - static_cast(target)->setTopRightBorderUV( - StringConverter::parseReal(vec[0]), - StringConverter::parseReal(vec[1]), - StringConverter::parseReal(vec[2]), - StringConverter::parseReal(vec[3]) - ); - } - //----------------------------------------------------------------------- - String CmdBorderLeftUV::doGet(const void* target) const - { - // No need right now.. - return static_cast(target)->getLeftBorderUVString(); - } - void CmdBorderLeftUV::doSet(void* target, const String& val) - { - std::vector vec = StringUtil::split(val); - - static_cast(target)->setLeftBorderUV( - StringConverter::parseReal(vec[0]), - StringConverter::parseReal(vec[1]), - StringConverter::parseReal(vec[2]), - StringConverter::parseReal(vec[3]) - ); - } - //----------------------------------------------------------------------- - String CmdBorderRightUV::doGet(const void* target) const - { - // No need right now.. - return static_cast(target)->getRightBorderUVString(); - } - void CmdBorderRightUV::doSet(void* target, const String& val) - { - std::vector vec = StringUtil::split(val); - - static_cast(target)->setRightBorderUV( - StringConverter::parseReal(vec[0]), - StringConverter::parseReal(vec[1]), - StringConverter::parseReal(vec[2]), - StringConverter::parseReal(vec[3]) - ); - } - //----------------------------------------------------------------------- - String CmdBorderTopUV::doGet(const void* target) const - { - // No need right now.. - return static_cast(target)->getTopBorderUVString(); - } - void CmdBorderTopUV::doSet(void* target, const String& val) - { - std::vector vec = StringUtil::split(val); - - static_cast(target)->setTopBorderUV( - StringConverter::parseReal(vec[0]), - StringConverter::parseReal(vec[1]), - StringConverter::parseReal(vec[2]), - StringConverter::parseReal(vec[3]) - ); - } - //----------------------------------------------------------------------- - String CmdBorderBottomUV::doGet(const void* target) const - { - // No need right now.. - return static_cast(target)->getBottomBorderUVString(); - } - void CmdBorderBottomUV::doSet(void* target, const String& val) - { - std::vector vec = StringUtil::split(val); - - static_cast(target)->setBottomBorderUV( - StringConverter::parseReal(vec[0]), - StringConverter::parseReal(vec[1]), - StringConverter::parseReal(vec[2]), - StringConverter::parseReal(vec[3]) - ); - } - //--------------------------------------------------------------------- - const String& BorderPanelOverlayElement::getTypeName(void) const - { - return msTypeName; - } - - - -} - diff --git a/Components/Overlay/src/OgreFont.cpp b/Components/Overlay/src/OgreFont.cpp deleted file mode 100644 index 2eb7d422705..00000000000 --- a/Components/Overlay/src/OgreFont.cpp +++ /dev/null @@ -1,629 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ - -#include "OgreFont.h" -#include "OgreMaterialManager.h" -#include "OgreTextureManager.h" -#include "OgreTexture.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreTextureUnitState.h" -#include "OgreTechnique.h" -#include "OgreBitwise.h" -#include "OgreOverlayManager.h" - -#include "utf8.h" -#include "OgreBillboardSet.h" -#include "OgreBillboard.h" - -#ifdef HAVE_FREETYPE -#define generic _generic // keyword for C++/CX -#include -#include FT_FREETYPE_H -#include FT_GLYPH_H -#undef generic -#else -#define STBTT_STATIC -#define STB_TRUETYPE_IMPLEMENTATION -#include "stb_truetype.h" -#endif - -namespace Ogre -{ - //--------------------------------------------------------------------- - namespace { - class CmdType : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - class CmdSource : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - class CmdSize : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - class CmdResolution : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - class CmdCodePoints : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - // Command object for setting / getting parameters - static CmdType msTypeCmd; - static CmdSource msSourceCmd; - static CmdSize msSizeCmd; - static CmdResolution msResolutionCmd; - static CmdCodePoints msCodePointsCmd; - } - - std::vector utftoc32(String str) - { - std::vector decoded; - decoded.reserve(str.size()); - - str.resize(str.size() + 3); // add padding for decoder - auto it = str.c_str(); - auto end = str.c_str() + str.size() - 3; - while(it < end) - { - uint32 cpId; - int err = 0; - it = utf8_decode(it, &cpId, &err); - if(err) - continue; - decoded.push_back(cpId); - } - return decoded; - } - - //--------------------------------------------------------------------- - Font::Font(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - :Resource (creator, name, handle, group, isManual, loader), - mType(FT_TRUETYPE), mTtfSize(0), mTtfResolution(0), mTtfMaxBearingY(0), mAntialiasColour(true) - { - - if (createParamDictionary("Font")) - { - ParamDictionary* dict = getParamDictionary(); - dict->addParameter( - ParameterDef("type", "'truetype' or 'image' based font", PT_STRING), - &msTypeCmd); - dict->addParameter( - ParameterDef("source", "Filename of the source of the font.", PT_STRING), - &msSourceCmd); - dict->addParameter( - ParameterDef("size", "True type size", PT_REAL), - &msSizeCmd); - dict->addParameter( - ParameterDef("resolution", "True type resolution", PT_UNSIGNED_INT), - &msResolutionCmd); - dict->addParameter( - ParameterDef("code_points", "Add a range of code points", PT_STRING), - &msCodePointsCmd); - } - - } - //--------------------------------------------------------------------- - Font::~Font() - { - // have to call this here reather than in Resource destructor - // since calling virtual methods in base destructors causes crash - unload(); - } - //--------------------------------------------------------------------- - void Font::setType(FontType ftype) - { - mType = ftype; - } - //--------------------------------------------------------------------- - FontType Font::getType(void) const - { - return mType; - } - //--------------------------------------------------------------------- - void Font::setSource(const String& source) - { - mSource = source; - } - //--------------------------------------------------------------------- - void Font::setTrueTypeSize(Real ttfSize) - { - mTtfSize = ttfSize; - } - //--------------------------------------------------------------------- - void Font::setTrueTypeResolution(uint ttfResolution) - { - mTtfResolution = ttfResolution; - } - //--------------------------------------------------------------------- - const String& Font::getSource(void) const - { - return mSource; - } - //--------------------------------------------------------------------- - Real Font::getTrueTypeSize(void) const - { - return mTtfSize; - } - //--------------------------------------------------------------------- - uint Font::getTrueTypeResolution(void) const - { - return mTtfResolution; - } - //--------------------------------------------------------------------- - int Font::getTrueTypeMaxBearingY() const - { - return mTtfMaxBearingY; - } - //--------------------------------------------------------------------- - void Font::_setMaterial(const MaterialPtr &mat) - { - mMaterial = mat; - } - - void Font::putText(BillboardSet* bbs, String text, float height, const ColourValue& colour) - { - // ensure loaded - load(); - // configure Billboard for display - bbs->setMaterial(mMaterial); - bbs->setBillboardType(BBT_PERPENDICULAR_COMMON); - bbs->setBillboardOrigin(BBO_CENTER_LEFT); - bbs->setDefaultDimensions(0, 0); - - text.resize(text.size() + 3); // add padding for decoder - auto it = text.c_str(); - auto end = text.c_str() + text.size() - 3; - - const auto& bbox = bbs->getBoundingBox(); - - float left = 0; - float top = bbox == AxisAlignedBox::BOX_NULL ? 0 : bbox.getMinimum().y - height; - while (it < end) - { - uint32 cpId; - int err = 0; - it = utf8_decode(it, &cpId, &err); - if(err) - continue; - - if(cpId == '\n') - { - top -= height; - left = 0; - continue; - } - - const auto& cp = getGlyphInfo(cpId); - - left += cp.bearing * height; - - if(!cp.uvRect.isNull()) - { - auto bb = bbs->createBillboard(Vector3(left, top, 0), colour); - bb->setDimensions(cp.aspectRatio * height, height); - bb->setTexcoordRect(cp.uvRect); - } - - left += (cp.advance - cp.bearing) * height; - } - } - - //--------------------------------------------------------------------- - void Font::loadImpl() - { - // Create a new material - mMaterial = MaterialManager::getSingleton().create( - "Fonts/" + mName, mGroup); - - if (!mMaterial) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Error creating new material!", "Font::load" ); - } - - if (mType == FT_TRUETYPE) - { - createTextureFromFont(); - } - else - { - // Manually load since we need to load to get alpha - mTexture = TextureManager::getSingleton().load(mSource, mGroup, TEX_TYPE_2D, 0); - } - - // Make sure material is aware of colour per vertex. - auto pass = mMaterial->getTechnique(0)->getPass(0); - pass->setVertexColourTracking(TVC_DIFFUSE); - - // lighting and culling also do not make much sense - pass->setCullingMode(CULL_NONE); - pass->setLightingEnabled(false); - mMaterial->setReceiveShadows(false); - // font quads should not occlude things - pass->setDepthWriteEnabled(false); - - TextureUnitState *texLayer = mMaterial->getTechnique(0)->getPass(0)->createTextureUnitState(); - texLayer->setTexture(mTexture); - // Clamp to avoid fuzzy edges - texLayer->setTextureAddressingMode( TextureUnitState::TAM_CLAMP ); - // Allow min/mag filter, but no mip - texLayer->setTextureFiltering(FO_LINEAR, FO_LINEAR, FO_NONE); - - - // Set up blending - if (mTexture->hasAlpha()) - { - mMaterial->setSceneBlending(mAntialiasColour ? SBF_ONE : SBF_SOURCE_ALPHA, SBF_ONE_MINUS_SOURCE_ALPHA); - mMaterial->getTechnique(0)->getPass(0)->setTransparentSortingEnabled(false); - } - else - { - // Use add if no alpha (assume black background) - mMaterial->setSceneBlending(SBT_ADD); - } - } - //--------------------------------------------------------------------- - void Font::unloadImpl() - { - if (mMaterial) - { - MaterialManager::getSingleton().remove(mMaterial); - mMaterial.reset(); - } - - if (mTexture) - { - TextureManager::getSingleton().remove(mTexture); - mTexture.reset(); - } - } - //--------------------------------------------------------------------- - void Font::createTextureFromFont(void) - { - // Just create the texture here, and point it at ourselves for when - // it wants to (re)load for real - mTexture = TextureManager::getSingleton().create(mName + "Texture", mGroup, true, this); - mTexture->setTextureType(TEX_TYPE_2D); - mTexture->setNumMipmaps(0); - mTexture->load(); - } - //--------------------------------------------------------------------- - void Font::loadResource(Resource* res) - { - // Locate ttf file, load it pre-buffered into memory by wrapping the - // original DataStream in a MemoryDataStream - DataStreamPtr dataStreamPtr = - ResourceGroupManager::getSingleton().openResource( - mSource, mGroup, this); - MemoryDataStream ttfchunk(dataStreamPtr); - - // If codepoints not supplied, assume ASCII - if (mCodePointRangeList.empty()) - { - mCodePointRangeList.push_back(CodePointRange(32, 126)); - } - float vpScale = OverlayManager::getSingleton().getPixelRatio(); -#ifdef HAVE_FREETYPE - // ManualResourceLoader implementation - load the texture - FT_Library ftLibrary; - // Init freetype - if( FT_Init_FreeType( &ftLibrary ) ) - OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, "Could not init FreeType library!", - "Font::Font"); - - FT_Face face; - - // Load font - if( FT_New_Memory_Face( ftLibrary, ttfchunk.getPtr(), (FT_Long)ttfchunk.size() , 0, &face ) ) - OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, - "Could not open font face!", "Font::createTextureFromFont" ); - - - // Convert our point size to freetype 26.6 fixed point format - FT_F26Dot6 ftSize = (FT_F26Dot6)(mTtfSize * (1 << 6)); - if (FT_Set_Char_Size(face, ftSize, 0, mTtfResolution * vpScale, mTtfResolution * vpScale)) - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Could not set char size!"); - - //FILE *fo_def = stdout; - - FT_Pos max_height = 0, max_width = 0; - - // Calculate maximum width, height and bearing - size_t glyphCount = 0; - for (const CodePointRange& range : mCodePointRangeList) - { - for(CodePoint cp = range.first; cp <= range.second; ++cp, ++glyphCount) - { - FT_Load_Char( face, cp, FT_LOAD_RENDER ); - - max_height = std::max(2 * face->glyph->bitmap.rows - (face->glyph->metrics.horiBearingY >> 6), max_height); - mTtfMaxBearingY = std::max(int(face->glyph->metrics.horiBearingY >> 6), mTtfMaxBearingY); - max_width = std::max(face->glyph->bitmap.width, max_width); - } - - } -#else - stbtt_fontinfo font; - stbtt_InitFont(&font, ttfchunk.getPtr(), 0); - // 64 gives the same texture resolution as freetype. - float scale = stbtt_ScaleForPixelHeight(&font, vpScale * mTtfSize * mTtfResolution / 64); - - int max_width = 0, max_height = 0; - // Calculate maximum width, height and bearing - size_t glyphCount = 0; - for (const CodePointRange& range : mCodePointRangeList) - { - for(CodePoint cp = range.first; cp <= range.second; ++cp, ++glyphCount) - { - int idx = stbtt_FindGlyphIndex(&font, cp); - if (!idx) // It is actually in the font? - continue; - TRect r; - stbtt_GetGlyphBitmapBox(&font, idx, scale, scale, &r.left, &r.top, &r.right, &r.bottom); - max_height = std::max(r.height(), max_height); - mTtfMaxBearingY = std::max(-r.top, mTtfMaxBearingY); - max_width = std::max(r.width(), max_width); - } - } - - max_height *= 1.125; -#endif - uint char_spacer = 1; - - // Now work out how big our texture needs to be - size_t rawSize = (max_width + char_spacer) * (max_height + char_spacer) * glyphCount; - - uint32 tex_side = static_cast(Math::Sqrt((Real)rawSize)); - // Now round up to nearest power of two - uint32 roundUpSize = Bitwise::firstPO2From(tex_side); - - // Would we benefit from using a non-square texture (2X width) - uint32 finalWidth, finalHeight; - if (roundUpSize * roundUpSize * 0.5 >= rawSize) - { - finalHeight = static_cast(roundUpSize * 0.5); - } - else - { - finalHeight = roundUpSize; - } - finalWidth = roundUpSize; - - Real textureAspect = (Real)finalWidth / (Real)finalHeight; - - Image img(PF_BYTE_LA, finalWidth, finalHeight); - // Reset content (transparent) - img.setTo(ColourValue::ZERO); - - uint32 l = 0, m = 0; - for (const CodePointRange& range : mCodePointRangeList) - { - for(CodePoint cp = range.first; cp <= range.second; ++cp ) - { - uchar* buffer; - int buffer_h = 0, buffer_pitch = 0; -#ifdef HAVE_FREETYPE - // Load & render glyph - FT_Error ftResult = FT_Load_Char( face, cp, FT_LOAD_RENDER ); - if (ftResult) - { - // problem loading this glyph, continue - LogManager::getSingleton().logError( - StringUtil::format("Charcode %u is not in font %s", cp, mSource.c_str())); - continue; - } - - buffer = face->glyph->bitmap.buffer; - OgreAssertDbg(buffer || (!face->glyph->bitmap.width && !face->glyph->bitmap.rows), "attempting to load NULL buffer"); - - uint advance = face->glyph->advance.x >> 6; - uint width = face->glyph->bitmap.width; - buffer_pitch = face->glyph->bitmap.pitch; - buffer_h = face->glyph->bitmap.rows; - - FT_Pos y_bearing = mTtfMaxBearingY - (face->glyph->metrics.horiBearingY >> 6); - FT_Pos x_bearing = face->glyph->metrics.horiBearingX >> 6; -#else - int idx = stbtt_FindGlyphIndex(&font, cp); - if (!idx) - { - LogManager::getSingleton().logWarning( - StringUtil::format("Charcode %u is not in font %s", cp, mSource.c_str())); - continue; - } - - if(cp == ' ') // should figure out how advance works for stbtt.. - idx = stbtt_FindGlyphIndex(&font, '0'); - - TRect r; - stbtt_GetGlyphBitmapBox(&font, idx, scale, scale, &r.left, &r.top, &r.right, &r.bottom); - - uint width = r.width(); - - int y_bearing = mTtfMaxBearingY + r.top; - int xoff = 0, yoff = 0; - buffer = stbtt_GetCodepointBitmap(&font, scale, scale, cp, &buffer_pitch, &buffer_h, &xoff, &yoff); - - int advance = xoff + width, x_bearing = xoff; - // should be multiplied with scale, but still does not seem to do the right thing - // stbtt_GetGlyphHMetrics(&font, cp, &advance, &x_bearing); -#endif - // If at end of row - if( finalWidth - 1 < l + width ) - { - m += max_height + char_spacer; - l = 0; - } - - for(int j = 0; j < buffer_h; j++ ) - { - uchar* pSrc = buffer + j * buffer_pitch; - uint32 row = j + m + y_bearing; - uchar* pDest = img.getData(l, row); - for(unsigned int k = 0; k < width; k++ ) - { - if (mAntialiasColour) - { - // Use the same greyscale pixel for all components RGBA - *pDest++= *pSrc; - } - else - { - // Always white whether 'on' or 'off' pixel, since alpha - // will turn off - *pDest++= 0xFF; - } - // Always use the greyscale value for alpha - *pDest++= *pSrc++; - } - } - - UVRect uvs((Real)l / (Real)finalWidth, // u1 - (Real)m / (Real)finalHeight, // v1 - (Real)(l + width) / (Real)finalWidth, // u2 - (m + max_height) / (Real)finalHeight); // v2 - this->setGlyphInfo({cp, uvs, float(textureAspect * uvs.width() / uvs.height()), - float(x_bearing) / max_height, float(advance) / max_height}); - - // Advance a column - if(width) - l += (width + char_spacer); - } - } -#ifdef HAVE_FREETYPE - FT_Done_FreeType(ftLibrary); -#endif - Texture* tex = static_cast(res); - // Call internal _loadImages, not loadImage since that's external and - // will determine load status etc again, and this is a manual loader inside load() - tex->_loadImages({&img}); - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String CmdType::doGet(const void* target) const - { - const Font* f = static_cast(target); - if (f->getType() == FT_TRUETYPE) - { - return "truetype"; - } - else - { - return "image"; - } - } - void CmdType::doSet(void* target, const String& val) - { - Font* f = static_cast(target); - if (val == "truetype") - { - f->setType(FT_TRUETYPE); - } - else - { - f->setType(FT_IMAGE); - } - } - //----------------------------------------------------------------------- - String CmdSource::doGet(const void* target) const - { - const Font* f = static_cast(target); - return f->getSource(); - } - void CmdSource::doSet(void* target, const String& val) - { - Font* f = static_cast(target); - f->setSource(val); - } - //----------------------------------------------------------------------- - String CmdSize::doGet(const void* target) const - { - const Font* f = static_cast(target); - return StringConverter::toString(f->getTrueTypeSize()); - } - void CmdSize::doSet(void* target, const String& val) - { - Font* f = static_cast(target); - f->setTrueTypeSize(StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String CmdResolution::doGet(const void* target) const - { - const Font* f = static_cast(target); - return StringConverter::toString(f->getTrueTypeResolution()); - } - void CmdResolution::doSet(void* target, const String& val) - { - Font* f = static_cast(target); - f->setTrueTypeResolution(StringConverter::parseUnsignedInt(val)); - } - //----------------------------------------------------------------------- - String CmdCodePoints::doGet(const void* target) const - { - const Font* f = static_cast(target); - StringStream str; - for (const auto& i : f->getCodePointRangeList()) - { - str << i.first << "-" << i.second << " "; - } - return str.str(); - } - void CmdCodePoints::doSet(void* target, const String& val) - { - // Format is "code_points start1-end1 start2-end2" - Font* f = static_cast(target); - - StringVector vec = StringUtil::split(val, " \t"); - for (auto & item : vec) - { - StringVector itemVec = StringUtil::split(item, "-"); - if (itemVec.size() == 2) - { - f->addCodePointRange({StringConverter::parseUnsignedInt(itemVec[0]), - StringConverter::parseUnsignedInt(itemVec[1])}); - } - } - } - - -} diff --git a/Components/Overlay/src/OgreFontManager.cpp b/Components/Overlay/src/OgreFontManager.cpp deleted file mode 100644 index 16e3c77ec75..00000000000 --- a/Components/Overlay/src/OgreFontManager.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ - -#include "OgreFontManager.h" - -#include "OgreResourceGroupManager.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - template<> FontManager * Singleton< FontManager >::msSingleton = 0; - FontManager* FontManager::getSingletonPtr(void) - { - return msSingleton; - } - FontManager& FontManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //--------------------------------------------------------------------- - FontManager::FontManager() : ResourceManager() - { - // Loading order - mLoadOrder = 200.0f; - // Scripting is supported by this manager - mScriptPatterns.push_back("*.fontdef"); - // Register scripting with resource group manager - ResourceGroupManager::getSingleton()._registerScriptLoader(this); - - // Resource type - mResourceType = "Font"; - - // Register with resource group manager - ResourceGroupManager::getSingleton()._registerResourceManager(mResourceType, this); - } - //--------------------------------------------------------------------- - FontManager::~FontManager() - { - // Unregister with resource group manager - ResourceGroupManager::getSingleton()._unregisterResourceManager(mResourceType); - // Unegister scripting with resource group manager - ResourceGroupManager::getSingleton()._unregisterScriptLoader(this); - - } - //--------------------------------------------------------------------- - Resource* FontManager::createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* params) - { - return OGRE_NEW Font(this, name, handle, group, isManual, loader); - } - //----------------------------------------------------------------------- - FontPtr FontManager::getByName(const String& name, const String& groupName) const - { - return static_pointer_cast(getResourceByName(name, groupName)); - } - //--------------------------------------------------------------------- - FontPtr FontManager::create (const String& name, const String& group, - bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams) - { - return static_pointer_cast(createResource(name,group,isManual,loader,createParams)); - } -} diff --git a/Components/Overlay/src/OgreImGuiOverlay.cpp b/Components/Overlay/src/OgreImGuiOverlay.cpp deleted file mode 100644 index 38e4a03f2af..00000000000 --- a/Components/Overlay/src/OgreImGuiOverlay.cpp +++ /dev/null @@ -1,336 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Ogre -{ - -ImGuiOverlay::ImGuiOverlay() : Overlay("ImGuiOverlay") -{ - ImGui::CreateContext(); - ImGuiIO& io = ImGui::GetIO(); - - io.BackendPlatformName = "OGRE"; -} -ImGuiOverlay::~ImGuiOverlay() -{ - ImGui::DestroyContext(); -} - -void ImGuiOverlay::initialise() -{ - if (!mInitialised) - { - mRenderable.initialise(); - mCodePointRanges.clear(); - } - mInitialised = true; -} - -//----------------------------------------------------------------------------------- -void ImGuiOverlay::_findVisibleObjects(Camera* cam, RenderQueue* queue, Viewport* vp) -{ - if (!mVisible) - return; - - mRenderable._update(); - queue->addRenderable(&mRenderable, RENDER_QUEUE_OVERLAY, mZOrder * 100); -} -//----------------------------------------------------------------------------------- -void ImGuiOverlay::ImGUIRenderable::createMaterial() -{ - mMaterial = MaterialManager::getSingleton().create("ImGui/material", RGN_INTERNAL); - Pass* mPass = mMaterial->getTechnique(0)->getPass(0); - mPass->setCullingMode(CULL_NONE); - mPass->setVertexColourTracking(TVC_DIFFUSE); - mPass->setSceneBlending(SBT_TRANSPARENT_ALPHA); - mPass->setSeparateSceneBlendingOperation(SBO_ADD, SBO_ADD); - mPass->setSeparateSceneBlending(SBF_SOURCE_ALPHA, SBF_ONE_MINUS_SOURCE_ALPHA, - SBF_ONE_MINUS_SOURCE_ALPHA, SBF_ZERO); - - TextureUnitState* mTexUnit = mPass->createTextureUnitState(); - mTexUnit->setTexture(mFontTex); - mTexUnit->setTextureFiltering(TFO_NONE); - - mMaterial->load(); - mMaterial->setLightingEnabled(false); - mMaterial->setDepthCheckEnabled(false); - mMaterial->setReceiveShadows(false); -} - -ImFont* ImGuiOverlay::addFont(const String& name, const String& group) -{ - FontPtr font = FontManager::getSingleton().getByName(name, group); - OgreAssert(font, "font does not exist"); - OgreAssert(font->getType() == FT_TRUETYPE, "font must be of FT_TRUETYPE"); - DataStreamPtr dataStreamPtr = - ResourceGroupManager::getSingleton().openResource(font->getSource(), font->getGroup()); - MemoryDataStream ttfchunk(dataStreamPtr, false); // transfer ownership to imgui - - // convert codepoint ranges for imgui - CodePointRange cprange; - for (const auto& r : font->getCodePointRangeList()) - { - cprange.push_back(r.first); - cprange.push_back(r.second); - } - - ImGuiIO& io = ImGui::GetIO(); - const ImWchar* cprangePtr = io.Fonts->GetGlyphRangesDefault(); - if (cprange.empty()) - cprange = {32, 126}; // ogre default - - cprange.push_back(0); // terminate - mCodePointRanges.push_back(cprange); - // ptr must persist until createFontTexture - cprangePtr = mCodePointRanges.back().data(); - - float vpScale = OverlayManager::getSingleton().getPixelRatio(); - - ImFontConfig cfg; - strncpy(cfg.Name, name.c_str(), IM_ARRAYSIZE(cfg.Name) - 1); - return io.Fonts->AddFontFromMemoryTTF(ttfchunk.getPtr(), ttfchunk.size(), font->getTrueTypeSize() * vpScale, &cfg, - cprangePtr); -} - -void ImGuiOverlay::ImGUIRenderable::createFontTexture() -{ - // Build texture atlas - ImGuiIO& io = ImGui::GetIO(); - if (io.Fonts->Fonts.empty()) - io.Fonts->AddFontDefault(); - unsigned char* pixels; - int width, height; - io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); - - mFontTex = TextureManager::getSingleton().createManual("ImGui/FontTex", RGN_INTERNAL, TEX_TYPE_2D, - width, height, 1, 1, PF_BYTE_RGBA); - - mFontTex->getBuffer()->blitFromMemory(PixelBox(Box(0, 0, width, height), PF_BYTE_RGBA, pixels)); -} -void ImGuiOverlay::NewFrame() -{ - static auto lastTime = Root::getSingleton().getTimer()->getMilliseconds(); - auto now = Root::getSingleton().getTimer()->getMilliseconds(); - - ImGuiIO& io = ImGui::GetIO(); - io.DeltaTime = std::max( - float(now - lastTime)/1000, - 1e-4f); // see https://github.com/ocornut/imgui/commit/3c07ec6a6126fb6b98523a9685d1f0f78ca3c40c - - lastTime = now; - - // Read keyboard modifiers inputs - io.KeyAlt = false; - io.KeySuper = false; - - OverlayManager& oMgr = OverlayManager::getSingleton(); - - // Setup display size (every frame to accommodate for window resizing) - auto vpScale = oMgr.getPixelRatio(); - io.DisplaySize = ImVec2(oMgr.getViewportWidth() * vpScale, oMgr.getViewportHeight() * vpScale); - - // Start the frame - ImGui::NewFrame(); -} - -void ImGuiOverlay::ImGUIRenderable::_update() -{ - if (mMaterial->getSupportedTechniques().empty()) - { - mMaterial->load(); // Support for adding lights run time - } - - RenderSystem* rSys = Root::getSingleton().getRenderSystem(); - - // Construct projection matrix, taking texel offset corrections in account (important for DirectX9) - // See also: - // - OGRE-API specific hint: http://www.ogre3d.org/forums/viewtopic.php?f=5&p=536881#p536881 - // - IMGUI Dx9 demo solution: - // https://github.com/ocornut/imgui/blob/v1.50/examples/directx9_example/imgui_impl_dx9.cpp#L127-L138 - ImGuiIO& io = ImGui::GetIO(); - float texelOffsetX = rSys->getHorizontalTexelOffset(); - float texelOffsetY = rSys->getVerticalTexelOffset(); - float L = texelOffsetX; - float R = io.DisplaySize.x + texelOffsetX; - float T = texelOffsetY; - float B = io.DisplaySize.y + texelOffsetY; - - mXform = Matrix4(2.0f / (R - L), 0.0f, 0.0f, (L + R) / (L - R), 0.0f, -2.0f / (B - T), 0.0f, - (T + B) / (B - T), 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); -} - -bool ImGuiOverlay::ImGUIRenderable::preRender(SceneManager* sm, RenderSystem* rsys) -{ - Viewport* vp = rsys->_getViewport(); - - // Instruct ImGui to Render() and process the resulting CmdList-s - // Adopted from https://bitbucket.org/ChaosCreator/imgui-ogre2.1-binding - // ... Commentary on OGRE forums: http://www.ogre3d.org/forums/viewtopic.php?f=5&t=89081#p531059 - ImGui::Render(); - ImDrawData* draw_data = ImGui::GetDrawData(); - int vpWidth = vp->getActualWidth(); - int vpHeight = vp->getActualHeight(); - - TextureUnitState* tu = mMaterial->getBestTechnique()->getPass(0)->getTextureUnitState(0); - - updateVertexData(draw_data); - - mRenderOp.indexData->indexStart = 0; - mRenderOp.vertexData->vertexStart = 0; - - for (int i = 0; i < draw_data->CmdListsCount; ++i) - { - const ImDrawList* draw_list = draw_data->CmdLists[i]; - mRenderOp.vertexData->vertexCount = draw_list->VtxBuffer.size(); - - for (int j = 0; j < draw_list->CmdBuffer.Size; ++j) - { - // Create a renderable and fill it's buffers - const ImDrawCmd* drawCmd = &draw_list->CmdBuffer[j]; - - // Set scissoring - Rect scissor(drawCmd->ClipRect.x, drawCmd->ClipRect.y, drawCmd->ClipRect.z, - drawCmd->ClipRect.w); - - // Clamp bounds to viewport dimensions - scissor = scissor.intersect(Rect(0, 0, vpWidth, vpHeight)); - - if (drawCmd->TextureId) - { - auto handle = (ResourceHandle)drawCmd->TextureId; - auto tex = static_pointer_cast(TextureManager::getSingleton().getByHandle(handle)); - if (tex) - { - rsys->_setTexture(0, true, tex); - rsys->_setSampler(0, *TextureManager::getSingleton().getDefaultSampler()); - } - } - - rsys->setScissorTest(true, scissor); - - // Render! - mRenderOp.indexData->indexCount = drawCmd->ElemCount; - - rsys->_render(mRenderOp); - - if (drawCmd->TextureId) - { - // reset to pass state - rsys->_setTexture(0, true, mFontTex); - rsys->_setSampler(0, *tu->getSampler()); - } - - // Update counts - mRenderOp.indexData->indexStart += drawCmd->ElemCount; - } - mRenderOp.vertexData->vertexStart += draw_list->VtxBuffer.size(); - } - rsys->setScissorTest(false); - return false; -} - -const LightList& ImGuiOverlay::ImGUIRenderable::getLights() const -{ - // Overlayelements should not be lit by the scene, this will not get called - static LightList ll; - return ll; -} - -ImGuiOverlay::ImGUIRenderable::ImGUIRenderable() -{ - // default overlays to preserve their own detail level - mPolygonModeOverrideable = false; - - // use identity projection and view matrices - mUseIdentityProjection = true; - mUseIdentityView = true; -} -//----------------------------------------------------------------------------------- -void ImGuiOverlay::ImGUIRenderable::initialise(void) -{ - createFontTexture(); - createMaterial(); - - mRenderOp.vertexData = OGRE_NEW VertexData(); - mRenderOp.indexData = OGRE_NEW IndexData(); - - mRenderOp.vertexData->vertexCount = 0; - mRenderOp.vertexData->vertexStart = 0; - - mRenderOp.indexData->indexCount = 0; - mRenderOp.indexData->indexStart = 0; - mRenderOp.operationType = RenderOperation::OT_TRIANGLE_LIST; - mRenderOp.useIndexes = true; - mRenderOp.useGlobalInstancing = false; - - VertexDeclaration* decl = mRenderOp.vertexData->vertexDeclaration; - - // vertex declaration - size_t offset = 0; - decl->addElement(0, offset, VET_FLOAT2, VES_POSITION); - offset += VertexElement::getTypeSize(VET_FLOAT2); - decl->addElement(0, offset, VET_FLOAT2, VES_TEXTURE_COORDINATES, 0); - offset += VertexElement::getTypeSize(VET_FLOAT2); - decl->addElement(0, offset, VET_UBYTE4_NORM, VES_DIFFUSE); -} -//----------------------------------------------------------------------------------- -ImGuiOverlay::ImGUIRenderable::~ImGUIRenderable() -{ - OGRE_DELETE mRenderOp.vertexData; - OGRE_DELETE mRenderOp.indexData; -} -//----------------------------------------------------------------------------------- -void ImGuiOverlay::ImGUIRenderable::updateVertexData(ImDrawData* draw_data) -{ - if(!draw_data->TotalVtxCount) - return; - - VertexBufferBinding* bind = mRenderOp.vertexData->vertexBufferBinding; - - if (bind->getBindings().empty() || bind->getBuffer(0)->getNumVertices() < size_t(draw_data->TotalVtxCount)) - { - bind->setBinding(0, HardwareBufferManager::getSingleton().createVertexBuffer( - sizeof(ImDrawVert), draw_data->TotalVtxCount, HBU_CPU_TO_GPU)); - } - if (!mRenderOp.indexData->indexBuffer || - mRenderOp.indexData->indexBuffer->getNumIndexes() < size_t(draw_data->TotalIdxCount)) - { - mRenderOp.indexData->indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, draw_data->TotalIdxCount, HBU_CPU_TO_GPU); - } - - // Copy all vertices - size_t vtx_offset = 0; - size_t idx_offset = 0; - for (int i = 0; i < draw_data->CmdListsCount; ++i) - { - const ImDrawList* draw_list = draw_data->CmdLists[i]; - bind->getBuffer(0)->writeData(vtx_offset, draw_list->VtxBuffer.size_in_bytes(), draw_list->VtxBuffer.Data, - i == 0); // discard on first write - mRenderOp.indexData->indexBuffer->writeData(idx_offset, draw_list->IdxBuffer.size_in_bytes(), - draw_list->IdxBuffer.Data, i == 0); - vtx_offset += draw_list->VtxBuffer.size_in_bytes(); - idx_offset += draw_list->IdxBuffer.size_in_bytes(); - } -} -} // namespace Ogre diff --git a/Components/Overlay/src/OgreOverlay.cpp b/Components/Overlay/src/OgreOverlay.cpp deleted file mode 100644 index 3b070e95e94..00000000000 --- a/Components/Overlay/src/OgreOverlay.cpp +++ /dev/null @@ -1,346 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreOverlay.h" -#include "OgreOverlayContainer.h" -#include "OgreOverlayManager.h" -#include "OgreVector.h" -#include "OgreSceneNode.h" -#include "OgreRenderQueue.h" -#include "OgreCamera.h" - -namespace Ogre { - - //--------------------------------------------------------------------- - Overlay::Overlay(const String& name) : - mName(name), - mRotate(0.0f), - mScrollX(0.0f), mScrollY(0.0f), - mScaleX(1.0f), mScaleY(1.0f), - mLastViewportWidth(0), mLastViewportHeight(0), - mTransformOutOfDate(true), mTransformUpdated(true), - mZOrder(100), mVisible(false), mInitialised(false) - - { - mRootNode = OGRE_NEW SceneNode(NULL); - - } - //--------------------------------------------------------------------- - Overlay::~Overlay() - { - // remove children - - OGRE_DELETE mRootNode; - - for (auto *e : m2DElements) - { - e->_notifyParent(0, 0); - } - } - //--------------------------------------------------------------------- - const String& Overlay::getName(void) const - { - return mName; - } - //--------------------------------------------------------------------- - void Overlay::assignZOrders() - { - ushort zorder = static_cast(mZOrder * 100.0f); - - // Notify attached 2D elements - for (auto *e : m2DElements) - { - zorder = e->_notifyZOrder(zorder); - } - } - //--------------------------------------------------------------------- - void Overlay::setZOrder(ushort zorder) - { - // Limit to 650 since this is multiplied by 100 to pad out for containers - assert (zorder <= 650 && "Overlay Z-order cannot be greater than 650!"); - - mZOrder = zorder; - - assignZOrders(); - } - //--------------------------------------------------------------------- - ushort Overlay::getZOrder(void) const - { - return (ushort)mZOrder; - } - //--------------------------------------------------------------------- - bool Overlay::isVisible(void) const - { - return mVisible; - } - //--------------------------------------------------------------------- - void Overlay::show(void) - { - mVisible = true; - if (!mInitialised) - { - initialise(); - } - } - //--------------------------------------------------------------------- - void Overlay::hide(void) - { - mVisible = false; - } - //--------------------------------------------------------------------- - void Overlay::setVisible(bool visible) - { - mVisible = visible; - } - //--------------------------------------------------------------------- - void Overlay::initialise(void) - { - for (auto *e : m2DElements) - { - e->initialise(); - } - mInitialised = true; - } - //--------------------------------------------------------------------- - void Overlay::add2D(OverlayContainer* cont) - { - m2DElements.push_back(cont); - // Notify parent - cont->_notifyParent(0, this); - - assignZOrders(); - - Matrix4 xform; - _getWorldTransforms(&xform); - cont->_notifyWorldTransforms(xform); - } - //--------------------------------------------------------------------- - void Overlay::remove2D(OverlayContainer* cont) - { - m2DElements.remove(cont); - cont->_notifyParent(0, 0); - assignZOrders(); - } - //--------------------------------------------------------------------- - void Overlay::add3D(SceneNode* node) - { - mRootNode->addChild(node); - } - //--------------------------------------------------------------------- - void Overlay::remove3D(SceneNode* node) - { - mRootNode->removeChild(node); - } - //--------------------------------------------------------------------- - void Overlay::clear(void) - { - mRootNode->removeAllChildren(); - m2DElements.clear(); - // Note no deallocation, memory handled by OverlayManager & SceneManager - } - //--------------------------------------------------------------------- - void Overlay::setScroll(Real x, Real y) - { - mScrollX = x; - mScrollY = y; - mTransformOutOfDate = true; - mTransformUpdated = true; - } - //--------------------------------------------------------------------- - Real Overlay::getScrollX(void) const - { - return mScrollX; - } - //--------------------------------------------------------------------- - Real Overlay::getScrollY(void) const - { - return mScrollY; - } - //--------------------------------------------------------------------- - OverlayContainer* Overlay::getChild(const String& name) - { - for (auto *e : m2DElements) - { - if (e->getName() == name) - return e; - } - return NULL; - } - //--------------------------------------------------------------------- - void Overlay::scroll(Real xoff, Real yoff) - { - mScrollX += xoff; - mScrollY += yoff; - mTransformOutOfDate = true; - mTransformUpdated = true; - } - //--------------------------------------------------------------------- - void Overlay::setRotate(const Radian& angle) - { - mRotate = angle; - mTransformOutOfDate = true; - mTransformUpdated = true; - } - //--------------------------------------------------------------------- - void Overlay::rotate(const Radian& angle) - { - setRotate(mRotate + angle); - } - //--------------------------------------------------------------------- - void Overlay::setScale(Real x, Real y) - { - mScaleX = x; - mScaleY = y; - mTransformOutOfDate = true; - mTransformUpdated = true; - } - //--------------------------------------------------------------------- - Real Overlay::getScaleX(void) const - { - return mScaleX; - } - //--------------------------------------------------------------------- - Real Overlay::getScaleY(void) const - { - return mScaleY; - } - //--------------------------------------------------------------------- - void Overlay::_getWorldTransforms(Matrix4* xform) const - { - if (mTransformOutOfDate) - { - updateTransform(); - } - *xform = mTransform; - - } - //--------------------------------------------------------------------- - void Overlay::_findVisibleObjects(Camera* cam, RenderQueue* queue, Viewport* vp) - { - if (mVisible) - { - // Flag for update pixel-based GUIElements if viewport has changed dimensions - bool tmpViewportDimensionsChanged = false; - if (mLastViewportWidth != vp->getActualWidth() || - mLastViewportHeight != vp->getActualHeight()) - { - tmpViewportDimensionsChanged = true; - mLastViewportWidth = vp->getActualWidth(); - mLastViewportHeight = vp->getActualHeight(); - } - - OverlayContainerList::iterator i, iend; - - if(tmpViewportDimensionsChanged) - { - for (auto *e : m2DElements) - { - e->_notifyViewport(); - } - } - - // update elements - if (mTransformUpdated) - { - Matrix4 xform; - _getWorldTransforms(&xform); - - for (auto *e : m2DElements) - { - e->_notifyWorldTransforms(xform); - } - - mTransformUpdated = false; - } - - // Add 3D elements - mRootNode->setPosition(cam->getDerivedPosition()); - mRootNode->setOrientation(cam->getDerivedOrientation()); - mRootNode->_update(true, false); - // Set up the default queue group for the objects about to be added - uint8 oldgrp = queue->getDefaultQueueGroup(); - ushort oldPriority = queue-> getDefaultRenderablePriority(); - queue->setDefaultQueueGroup(RENDER_QUEUE_OVERLAY); - queue->setDefaultRenderablePriority(static_cast((mZOrder*100)-1)); - mRootNode->_findVisibleObjects(cam, queue, NULL, true, false); - // Reset the group - queue->setDefaultQueueGroup(oldgrp); - queue->setDefaultRenderablePriority(oldPriority); - // Add 2D elements - for (auto *e : m2DElements) - { - e->_update(); - e->_updateRenderQueue(queue); - } - } - } - //--------------------------------------------------------------------- - void Overlay::updateTransform(void) const - { - // Ordering: - // 1. Scale - // 2. Rotate - // 3. Translate - - Radian orientationRotation = Radian(0); - - Matrix3 rot3x3, scale3x3; - rot3x3.FromEulerAnglesXYZ(Radian(0), Radian(0), mRotate + orientationRotation); - scale3x3 = Matrix3::ZERO; - scale3x3[0][0] = mScaleX; - scale3x3[1][1] = mScaleY; - scale3x3[2][2] = 1.0f; - - mTransform = Matrix4::IDENTITY; - mTransform = rot3x3 * scale3x3; - mTransform.setTrans(Vector3(mScrollX, mScrollY, 0)); - - mTransformOutOfDate = false; - } - //--------------------------------------------------------------------- - OverlayElement* Overlay::findElementAt(Real x, Real y) - { - OverlayElement* ret = NULL; - int currZ = -1; - for (auto *e : m2DElements) - { - int z = e->getZOrder(); - if (z > currZ) - { - OverlayElement* elementFound = e->findElementAt(x,y); - if(elementFound) - { - currZ = elementFound->getZOrder(); - ret = elementFound; - } - } - } - return ret; - } -} - diff --git a/Components/Overlay/src/OgreOverlayContainer.cpp b/Components/Overlay/src/OgreOverlayContainer.cpp deleted file mode 100644 index 24ea219bc5f..00000000000 --- a/Components/Overlay/src/OgreOverlayContainer.cpp +++ /dev/null @@ -1,371 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreOverlayContainer.h" -#include "OgreException.h" -#include "OgreOverlayManager.h" -#include "OgreOverlay.h" -#include "OgreIteratorWrapper.h" - -namespace Ogre { - - //--------------------------------------------------------------------- - OverlayContainer::OverlayContainer(const String& name) - : OverlayElement(name), - mChildrenProcessEvents(true) - { - } - //--------------------------------------------------------------------- - OverlayContainer::~OverlayContainer() - { - // remove from parent overlay if root - if (mOverlay && !mParent) - { - mOverlay->remove2D(this); - } - - for (const auto& p : mChildren) - { - p.second->_notifyParent(0, 0); - } - } - //--------------------------------------------------------------------- - void OverlayContainer::addChild(OverlayElement* elem) - { - if (elem->isContainer()) - { - addChildImpl(static_cast(elem)); - } - else - { - addChildImpl(elem); - } - - } - //--------------------------------------------------------------------- - void OverlayContainer::addChildImpl(OverlayElement* elem) - { - String name = elem->getName(); - ChildMap::iterator i = mChildren.find(name); - if (i != mChildren.end()) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, "Child with name " + name + - " already defined.", "OverlayContainer::addChild"); - } - - mChildren.emplace(name, elem); - // tell child about parent & Z-order - elem->_notifyParent(this, mOverlay); - elem->_notifyZOrder(Math::uint16Cast(mZOrder + 1)); - elem->_notifyWorldTransforms(mXForm); - } - //--------------------------------------------------------------------- - void OverlayContainer::addChildImpl(OverlayContainer* cont) - { - // Add to main map first - // This will pick up duplicates - OverlayElement* pElem = cont; - addChildImpl(pElem); - - /* - cont->_notifyParent(this, mOverlay); - cont->_notifyZOrder(mZOrder + 1); - cont->_notifyWorldTransforms(mXForm); - - // tell children of new container the current overlay - ChildIterator it = cont->getChildIterator(); - while (it.hasMoreElements()) - { - // Give children Z-order 1 higher than this - GuiElement* pElemChild = it.getNext(); - pElemChild->_notifyParent(cont, mOverlay); - pElemChild->_notifyZOrder(cont->getZOrder() + 1); - pElemChild->_notifyWorldTransforms(mXForm); - } - */ - - // Now add to specific map too - mChildContainers.emplace(cont->getName(), cont); - - } - //--------------------------------------------------------------------- - void OverlayContainer::removeChild(const String& name) - { - ChildMap::iterator i = mChildren.find(name); - if (i == mChildren.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Child with name " + name + - " not found.", "OverlayContainer::removeChild"); - } - - OverlayElement* element = i->second; - mChildren.erase(i); - - // Remove from container list (if found) - ChildContainerMap::iterator j = mChildContainers.find(name); - if (j != mChildContainers.end()) - mChildContainers.erase(j); - - element->_setParent(0); - } - //--------------------------------------------------------------------- - void OverlayContainer::_addChild(OverlayElement* elem) - { - if (elem->isContainer()) - { - addChildImpl(static_cast(elem)); - } - else - { - addChildImpl(elem); - } - } - //--------------------------------------------------------------------- - void OverlayContainer::_removeChild(const String& name) - { - ChildMap::iterator i = mChildren.find(name); - if (i == mChildren.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Child with name " + name + - " not found.", "OverlayContainer::removeChild"); - } - - OverlayElement* element = i->second; - mChildren.erase(i); - - // Remove from container list (if found) - ChildContainerMap::iterator j = mChildContainers.find(name); - if (j != mChildContainers.end()) - mChildContainers.erase(j); - - element->_setParent(0); - } - //--------------------------------------------------------------------- - OverlayElement* OverlayContainer::getChild(const String& name) - { - ChildMap::iterator i = mChildren.find(name); - if (i == mChildren.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Child with name " + name + - " not found.", "OverlayContainer::getChild"); - } - - return i->second; - } - //--------------------------------------------------------------------- - OverlayContainer::ChildIterator OverlayContainer::getChildIterator(void) - { - return ChildIterator(mChildren.begin(), mChildren.end()); - } - //--------------------------------------------------------------------- - OverlayContainer::ChildContainerIterator OverlayContainer::getChildContainerIterator(void) - { - return ChildContainerIterator(mChildContainers.begin(), mChildContainers.end()); - } - //--------------------------------------------------------------------- - void OverlayContainer::initialise(void) - { - for (const auto& c : mChildContainers) - { - c.second->initialise(); - } - for (const auto& c : mChildren) - { - c.second->initialise(); - } - } - //--------------------------------------------------------------------- - void OverlayContainer::_positionsOutOfDate(void) - { - OverlayElement::_positionsOutOfDate(); - - for (const auto& p : mChildren) - { - p.second->_positionsOutOfDate(); - } - } - - //--------------------------------------------------------------------- - void OverlayContainer::_update(void) - { - // call superclass - OverlayElement::_update(); - - // Update children - for (const auto& p : mChildren) - { - p.second->_update(); - } - } - //--------------------------------------------------------------------- - ushort OverlayContainer::_notifyZOrder(ushort newZOrder) - { - OverlayElement::_notifyZOrder(newZOrder); - // One for us - newZOrder++; - - // Update children - for (const auto& p : mChildren) - { - // Children "consume" Z-order values, so keep track of them - newZOrder = p.second->_notifyZOrder(newZOrder); - } - - return newZOrder; - } - //--------------------------------------------------------------------- - void OverlayContainer::_notifyWorldTransforms(const Matrix4& xform) - { - OverlayElement::_notifyWorldTransforms(xform); - - // Update children - for (const auto& p : mChildren) - { - p.second->_notifyWorldTransforms(xform); - } - } - //--------------------------------------------------------------------- - void OverlayContainer::_notifyViewport() - { - OverlayElement::_notifyViewport(); - - // Update children - for (const auto& p : mChildren) - { - p.second->_notifyViewport(); - } - } - //--------------------------------------------------------------------- - void OverlayContainer::_notifyParent(OverlayContainer* parent, Overlay* overlay) - { - OverlayElement::_notifyParent(parent, overlay); - - // Update children - for (const auto& p : mChildren) - { - // Notify the children of the overlay - p.second->_notifyParent(this, overlay); - } - } - - //--------------------------------------------------------------------- - void OverlayContainer::_updateRenderQueue(RenderQueue* queue) - { - if (mVisible) - { - - OverlayElement::_updateRenderQueue(queue); - - // Also add children - for (const auto& p : mChildren) - { - // Give children Z-order 1 higher than this - p.second->_updateRenderQueue(queue); - } - } - - } - - - OverlayElement* OverlayContainer::findElementAt(Real x, Real y) // relative to parent - { - - OverlayElement* ret = NULL; - - int currZ = -1; - - if (mVisible) - { - ret = OverlayElement::findElementAt(x,y); //default to the current container if no others are found - if (ret && mChildrenProcessEvents) - { - for (const auto& p : mChildren) - { - OverlayElement* currentOverlayElement = p.second; - if (currentOverlayElement->isVisible() && currentOverlayElement->isEnabled()) - { - int z = currentOverlayElement->getZOrder(); - if (z > currZ) - { - OverlayElement* elementFound = currentOverlayElement->findElementAt(x ,y ); - if (elementFound) - { - currZ = z; - ret = elementFound; - } - } - } - } - } - } - return ret; - } - - void OverlayContainer::copyFromTemplate(OverlayElement* templateOverlay) - { - OverlayElement::copyFromTemplate(templateOverlay); - - if (templateOverlay->isContainer() && isContainer()) - { - for (const auto& p : static_cast(templateOverlay)->getChildren()) - { - OverlayElement* oldChildElement = p.second; - if (oldChildElement->isCloneable()) - { - OverlayElement* newChildElement = - OverlayManager::getSingleton().createOverlayElement( - oldChildElement->getTypeName(), - mName+"/"+oldChildElement->getName()); - newChildElement->copyFromTemplate(oldChildElement); - addChild(newChildElement); - } - } - } - } - - OverlayElement* OverlayContainer::clone(const String& instanceName) - { - OverlayContainer *newContainer; - - newContainer = static_cast(OverlayElement::clone(instanceName)); - - for (const auto& p : mChildren) - { - OverlayElement* oldChildElement = p.second; - if (oldChildElement->isCloneable()) - { - OverlayElement* newChildElement = oldChildElement->clone(instanceName); - newContainer->_addChild(newChildElement); - } - } - - return newContainer; - } - -} - diff --git a/Components/Overlay/src/OgreOverlayElement.cpp b/Components/Overlay/src/OgreOverlayElement.cpp deleted file mode 100644 index c1f5d90a274..00000000000 --- a/Components/Overlay/src/OgreOverlayElement.cpp +++ /dev/null @@ -1,810 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreRoot.h" -#include "OgreRenderSystem.h" -#include "OgreOverlayElement.h" -#include "OgreOverlay.h" -#include "OgreOverlayManager.h" -#include "OgreException.h" -#include "OgreMaterialManager.h" -#include "OgreOverlayContainer.h" -#include "OgreResourceGroupManager.h" -#include "OgreOverlayElementCommands.h" -#include "OgreTechnique.h" -#include "OgreLogManager.h" - -namespace Ogre { - - - //--------------------------------------------------------------------- - // Define static members - // Command object for setting / getting parameters - static OverlayElementCommands::CmdLeft msLeftCmd; - static OverlayElementCommands::CmdTop msTopCmd; - static OverlayElementCommands::CmdWidth msWidthCmd; - static OverlayElementCommands::CmdHeight msHeightCmd; - static OverlayElementCommands::CmdMaterial msMaterialCmd; - static OverlayElementCommands::CmdCaption msCaptionCmd; - static OverlayElementCommands::CmdMetricsMode msMetricsModeCmd; - static OverlayElementCommands::CmdHorizontalAlign msHorizontalAlignCmd; - static OverlayElementCommands::CmdVerticalAlign msVerticalAlignCmd; - static OverlayElementCommands::CmdVisible msVisibleCmd; - - const String& OverlayElement::DEFAULT_RESOURCE_GROUP = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME; - //--------------------------------------------------------------------- - OverlayElement::OverlayElement(const String& name) - : mName(name) - , mVisible(true) - , mCloneable(true) - , mLeft(0.0f) - , mTop(0.0f) - , mWidth(1.0f) - , mHeight(1.0f) - , mMetricsMode(GMM_RELATIVE) - , mHorzAlign(GHA_LEFT) - , mVertAlign(GVA_TOP) - , mPixelTop(0.0) - , mPixelLeft(0.0) - , mPixelWidth(1.0) - , mPixelHeight(1.0) - , mPixelScaleX(1.0) - , mPixelScaleY(1.0) - , mParent(0) - , mOverlay(0) - , mDerivedLeft(0) - , mDerivedTop(0) - , mDerivedOutOfDate(true) - , mGeomPositionsOutOfDate(true) - , mGeomUVsOutOfDate(true) - , mZOrder(0) - , mEnabled(true) - , mInitialised(false) - { - // default overlays to preserve their own detail level - mPolygonModeOverrideable = false; - - // use identity projection and view matrices - mUseIdentityProjection = true; - mUseIdentityView = true; - } - //--------------------------------------------------------------------- - OverlayElement::~OverlayElement() - { - if (mParent) - { - mParent->removeChild(mName); - mParent = 0; - } - } - //--------------------------------------------------------------------- - void OverlayElement::setDimensions(Real width, Real height) - { - if (mMetricsMode != GMM_RELATIVE) - { - mPixelWidth = width; - mPixelHeight = height; - } - else - { - mWidth = width; - mHeight = height; - } - mDerivedOutOfDate = true; - _positionsOutOfDate(); - } - //--------------------------------------------------------------------- - void OverlayElement::setPosition(Real left, Real top) - { - if (mMetricsMode != GMM_RELATIVE) - { - mPixelLeft = left; - mPixelTop = top; - } - else - { - mLeft = left; - mTop = top; - } - mDerivedOutOfDate = true; - _positionsOutOfDate(); - } - //--------------------------------------------------------------------- - void OverlayElement::setWidth(Real width) - { - if (mMetricsMode != GMM_RELATIVE) - { - mPixelWidth = width; - } - else - { - mWidth = width; - } - mDerivedOutOfDate = true; - _positionsOutOfDate(); - } - //--------------------------------------------------------------------- - Real OverlayElement::getWidth(void) const - { - if (mMetricsMode != GMM_RELATIVE) - { - return mPixelWidth; - } - else - { - return mWidth; - } - } - //--------------------------------------------------------------------- - void OverlayElement::setHeight(Real height) - { - if (mMetricsMode != GMM_RELATIVE) - { - mPixelHeight = height; - } - else - { - mHeight = height; - } - mDerivedOutOfDate = true; - _positionsOutOfDate(); - } - //--------------------------------------------------------------------- - Real OverlayElement::getHeight(void) const - { - if (mMetricsMode != GMM_RELATIVE) - { - return mPixelHeight; - } - else - { - return mHeight; - } - } - //--------------------------------------------------------------------- - void OverlayElement::setLeft(Real left) - { - if (mMetricsMode != GMM_RELATIVE) - { - mPixelLeft = left; - } - else - { - mLeft = left; - } - mDerivedOutOfDate = true; - _positionsOutOfDate(); - } - //--------------------------------------------------------------------- - Real OverlayElement::getLeft(void) const - { - if (mMetricsMode != GMM_RELATIVE) - { - return mPixelLeft; - } - else - { - return mLeft; - } - } - //--------------------------------------------------------------------- - void OverlayElement::setTop(Real top) - { - if (mMetricsMode != GMM_RELATIVE) - { - mPixelTop = top; - } - else - { - mTop = top; - } - - mDerivedOutOfDate = true; - _positionsOutOfDate(); - } - //--------------------------------------------------------------------- - Real OverlayElement::getTop(void) const - { - if (mMetricsMode != GMM_RELATIVE) - { - return mPixelTop; - } - else - { - return mTop; - } - } - //--------------------------------------------------------------------- - void OverlayElement::_setLeft(Real left) - { - mLeft = left; - mPixelLeft = left / mPixelScaleX; - - mDerivedOutOfDate = true; - _positionsOutOfDate(); - } - //--------------------------------------------------------------------- - void OverlayElement::_setTop(Real top) - { - mTop = top; - mPixelTop = top / mPixelScaleY; - - mDerivedOutOfDate = true; - _positionsOutOfDate(); - } - //--------------------------------------------------------------------- - void OverlayElement::_setWidth(Real width) - { - mWidth = width; - mPixelWidth = width / mPixelScaleX; - - mDerivedOutOfDate = true; - _positionsOutOfDate(); - } - //--------------------------------------------------------------------- - void OverlayElement::_setHeight(Real height) - { - mHeight = height; - mPixelHeight = height / mPixelScaleY; - - mDerivedOutOfDate = true; - _positionsOutOfDate(); - } - //--------------------------------------------------------------------- - void OverlayElement::_setPosition(Real left, Real top) - { - mLeft = left; - mTop = top; - mPixelLeft = left / mPixelScaleX; - mPixelTop = top / mPixelScaleY; - - mDerivedOutOfDate = true; - _positionsOutOfDate(); - } - //--------------------------------------------------------------------- - void OverlayElement::_setDimensions(Real width, Real height) - { - mWidth = width; - mHeight = height; - mPixelWidth = width / mPixelScaleX; - mPixelHeight = height / mPixelScaleY; - - mDerivedOutOfDate = true; - _positionsOutOfDate(); - } - //--------------------------------------------------------------------- - const String& OverlayElement::getMaterialName(void) const - { - return mMaterial ? mMaterial->getName() : BLANKSTRING; - } - //--------------------------------------------------------------------- - void OverlayElement::setMaterial(const MaterialPtr& mat) - { - mMaterial = mat; - - if(!mMaterial) - return; - - mMaterial->load(); - - auto dstPass = mMaterial->getTechnique(0)->getPass(0); // assume this is representative - if (dstPass->getLightingEnabled() || dstPass->getDepthCheckEnabled()) - { - LogManager::getSingleton().logWarning( - "force-disabling 'lighting' and 'depth_check' of Material " + mat->getName() + - " for use with OverlayElement " + getName()); - } - - // Set some prerequisites to be sure - mMaterial->setLightingEnabled(false); - mMaterial->setReceiveShadows(false); - mMaterial->setDepthCheckEnabled(false); - } - - void OverlayElement::setMaterialName(const String& matName, const String& group) - { - if (!matName.empty()) - { - mMaterial = MaterialManager::getSingleton().getByName(matName, group); - if (!mMaterial) - OGRE_EXCEPT( Exception::ERR_ITEM_NOT_FOUND, "Could not find material " + matName, - "OverlayElement::setMaterialName" ); - - setMaterial(mMaterial); - } - else - { - mMaterial.reset(); - } - } - //--------------------------------------------------------------------- - const MaterialPtr& OverlayElement::getMaterial(void) const - { - return mMaterial; - } - //--------------------------------------------------------------------- - void OverlayElement::getWorldTransforms(Matrix4* xform) const - { - mOverlay->_getWorldTransforms(xform); - } - //--------------------------------------------------------------------- - void OverlayElement::_positionsOutOfDate(void) - { - mGeomPositionsOutOfDate = true; - } - //--------------------------------------------------------------------- - void OverlayElement::_update(void) - { - Real vpWidth, vpHeight; - OverlayManager& oMgr = OverlayManager::getSingleton(); - vpWidth = (Real) (oMgr.getViewportWidth()); - vpHeight = (Real) (oMgr.getViewportHeight()); - - // Check size if pixel-based or relative-aspect-adjusted - switch (mMetricsMode) - { - case GMM_PIXELS : - if (mGeomPositionsOutOfDate) - { - mPixelScaleX = 1.0f / vpWidth; - mPixelScaleY = 1.0f / vpHeight; - } - break; - - case GMM_RELATIVE_ASPECT_ADJUSTED : - if (mGeomPositionsOutOfDate) - { - mPixelScaleX = 1.0f / (10000.0f * (vpWidth / vpHeight)); - mPixelScaleY = 1.0f / 10000.0f; - } - break; - - default: - case GMM_RELATIVE : - mPixelScaleX = 1.0; - mPixelScaleY = 1.0; - mPixelLeft = mLeft; - mPixelTop = mTop; - mPixelWidth = mWidth; - mPixelHeight = mHeight; - break; - } - - mLeft = mPixelLeft * mPixelScaleX; - mTop = mPixelTop * mPixelScaleY; - mWidth = mPixelWidth * mPixelScaleX; - mHeight = mPixelHeight * mPixelScaleY; - - Real tmpPixelWidth = mPixelWidth; - - _updateFromParent(); - // NB container subclasses will update children too - - // Tell self to update own position geometry - if (mGeomPositionsOutOfDate && mInitialised) - { - updatePositionGeometry(); - - // Within updatePositionGeometry() of TextOverlayElements, - // the needed pixel width is calculated and as a result a new - // second update call is needed, so leave the dirty flag on 'true' - // so that that in a second call in the next frame, the element - // width can be correctly set and the text gets displayed. - if(mMetricsMode == GMM_PIXELS && tmpPixelWidth != mPixelWidth) - mGeomPositionsOutOfDate = true; - else - mGeomPositionsOutOfDate = false; - } - - // Tell self to update own texture geometry - if (mGeomUVsOutOfDate && mInitialised) - { - updateTextureGeometry(); - mGeomUVsOutOfDate = false; - } - } - //--------------------------------------------------------------------- - void OverlayElement::_updateFromParent(void) - { - Real parentLeft = 0, parentTop = 0, parentBottom = 0, parentRight = 0; - - if (mParent) - { - parentLeft = mParent->_getDerivedLeft(); - parentTop = mParent->_getDerivedTop(); - if (mHorzAlign == GHA_CENTER || mHorzAlign == GHA_RIGHT) - { - parentRight = parentLeft + mParent->_getRelativeWidth(); - } - if (mVertAlign == GVA_CENTER || mVertAlign == GVA_BOTTOM) - { - parentBottom = parentTop + mParent->_getRelativeHeight(); - } - } - else - { - RenderSystem* rSys = Root::getSingleton().getRenderSystem(); - OverlayManager& oMgr = OverlayManager::getSingleton(); - - // Calculate offsets required for mapping texel origins to pixel origins in the - // current rendersystem - Real hOffset = rSys->getHorizontalTexelOffset() / oMgr.getViewportWidth(); - Real vOffset = rSys->getVerticalTexelOffset() / oMgr.getViewportHeight(); - - parentLeft = 0.0f + hOffset; - parentTop = 0.0f + vOffset; - parentRight = 1.0f + hOffset; - parentBottom = 1.0f + vOffset; - } - - // Sort out position based on alignment - // NB all we do is derived the origin, we don't automatically sort out the position - // This is more flexible than forcing absolute right & middle - switch(mHorzAlign) - { - case GHA_CENTER: - mDerivedLeft = ((parentLeft + parentRight) * 0.5f) + mLeft; - break; - case GHA_LEFT: - mDerivedLeft = parentLeft + mLeft; - break; - case GHA_RIGHT: - mDerivedLeft = parentRight + mLeft; - break; - }; - switch(mVertAlign) - { - case GVA_CENTER: - mDerivedTop = ((parentTop + parentBottom) * 0.5f) + mTop; - break; - case GVA_TOP: - mDerivedTop = parentTop + mTop; - break; - case GVA_BOTTOM: - mDerivedTop = parentBottom + mTop; - break; - }; - - mDerivedOutOfDate = false; - - if (mParent != 0) - { - RealRect parent; - RealRect child; - - mParent->_getClippingRegion(parent); - - child.left = mDerivedLeft; - child.top = mDerivedTop; - child.right = mDerivedLeft + mWidth; - child.bottom = mDerivedTop + mHeight; - - mClippingRegion = parent.intersect(child); - } - else - { - mClippingRegion.left = mDerivedLeft; - mClippingRegion.top = mDerivedTop; - mClippingRegion.right = mDerivedLeft + mWidth; - mClippingRegion.bottom = mDerivedTop + mHeight; - } - } - //--------------------------------------------------------------------- - void OverlayElement::_notifyParent(OverlayContainer* parent, Overlay* overlay) - { - mParent = parent; - mOverlay = overlay; - - if (mOverlay && mOverlay->isInitialised() && !mInitialised) - { - initialise(); - } - - mDerivedOutOfDate = true; - } - //--------------------------------------------------------------------- - Real OverlayElement::_getDerivedLeft(void) - { - if (mDerivedOutOfDate) - { - _updateFromParent(); - } - return mDerivedLeft; - } - //--------------------------------------------------------------------- - Real OverlayElement::_getDerivedTop(void) - { - if (mDerivedOutOfDate) - { - _updateFromParent(); - } - return mDerivedTop; - } - //--------------------------------------------------------------------- - Real OverlayElement::_getRelativeWidth(void) - { - return mWidth; - } - //--------------------------------------------------------------------- - Real OverlayElement::_getRelativeHeight(void) - { - return mHeight; - } - //--------------------------------------------------------------------- - void OverlayElement::_getClippingRegion(RealRect &clippingRegion) - { - if (mDerivedOutOfDate) - { - _updateFromParent(); - } - clippingRegion = mClippingRegion; - } - //--------------------------------------------------------------------- - ushort OverlayElement::_notifyZOrder(ushort newZOrder) - { - mZOrder = newZOrder; - return mZOrder + 1; - } - //--------------------------------------------------------------------- - void OverlayElement::_notifyWorldTransforms(const Matrix4& xform) - { - mXForm = xform; - } - //--------------------------------------------------------------------- - void OverlayElement::_notifyViewport() - { - switch (mMetricsMode) - { - case GMM_PIXELS : - { - Real vpWidth, vpHeight; - OverlayManager& oMgr = OverlayManager::getSingleton(); - vpWidth = (Real) (oMgr.getViewportWidth()); - vpHeight = (Real) (oMgr.getViewportHeight()); - - mPixelScaleX = 1.0f / vpWidth; - mPixelScaleY = 1.0f / vpHeight; - } - break; - - case GMM_RELATIVE_ASPECT_ADJUSTED : - { - Real vpWidth, vpHeight; - OverlayManager& oMgr = OverlayManager::getSingleton(); - vpWidth = (Real) (oMgr.getViewportWidth()); - vpHeight = (Real) (oMgr.getViewportHeight()); - - mPixelScaleX = 1.0f / (10000.0f * (vpWidth / vpHeight)); - mPixelScaleY = 1.0f / 10000.0f; - } - break; - - default: - case GMM_RELATIVE : - mPixelScaleX = 1.0; - mPixelScaleY = 1.0; - mPixelLeft = mLeft; - mPixelTop = mTop; - mPixelWidth = mWidth; - mPixelHeight = mHeight; - break; - } - - mLeft = mPixelLeft * mPixelScaleX; - mTop = mPixelTop * mPixelScaleY; - mWidth = mPixelWidth * mPixelScaleX; - mHeight = mPixelHeight * mPixelScaleY; - - mGeomPositionsOutOfDate = true; - } - //--------------------------------------------------------------------- - void OverlayElement::_updateRenderQueue(RenderQueue* queue) - { - if (mVisible) - { - queue->addRenderable(this, RENDER_QUEUE_OVERLAY, mZOrder); - } - } - //--------------------------------------------------------------------- - void OverlayElement::visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables) - { - visitor->visit(this, 0, false); - } - //----------------------------------------------------------------------- - void OverlayElement::addBaseParameters(void) - { - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter(ParameterDef("left", - "The position of the left border of the gui element." - , PT_REAL), - &msLeftCmd); - dict->addParameter(ParameterDef("top", - "The position of the top border of the gui element." - , PT_REAL), - &msTopCmd); - dict->addParameter(ParameterDef("width", - "The width of the element." - , PT_REAL), - &msWidthCmd); - dict->addParameter(ParameterDef("height", - "The height of the element." - , PT_REAL), - &msHeightCmd); - dict->addParameter(ParameterDef("material", - "The name of the material to use." - , PT_STRING), - &msMaterialCmd); - dict->addParameter(ParameterDef("caption", - "The element caption, if supported." - , PT_STRING), - &msCaptionCmd); - dict->addParameter(ParameterDef("metrics_mode", - "The type of metrics to use, either 'relative' to the screen, 'pixels' or 'relative_aspect_adjusted'." - , PT_STRING), - &msMetricsModeCmd); - dict->addParameter(ParameterDef("horz_align", - "The horizontal alignment, 'left', 'right' or 'center'." - , PT_STRING), - &msHorizontalAlignCmd); - dict->addParameter(ParameterDef("vert_align", - "The vertical alignment, 'top', 'bottom' or 'center'." - , PT_STRING), - &msVerticalAlignCmd); - dict->addParameter(ParameterDef("visible", - "Initial visibility of element, either 'true' or 'false' (default true)." - , PT_STRING), - &msVisibleCmd); - } - //----------------------------------------------------------------------- - void OverlayElement::setCaption( const DisplayString& caption ) - { - mCaption = caption; - _positionsOutOfDate(); - } - //----------------------------------------------------------------------- - void OverlayElement::setColour(const ColourValue& col) - { - mColour = col; - } - //----------------------------------------------------------------------- - const ColourValue& OverlayElement::getColour(void) const - { - return mColour; - } - //----------------------------------------------------------------------- - void OverlayElement::setMetricsMode(GuiMetricsMode gmm) - { - switch (gmm) - { - case GMM_PIXELS : - { - Real vpWidth, vpHeight; - OverlayManager& oMgr = OverlayManager::getSingleton(); - vpWidth = (Real) (oMgr.getViewportWidth()); - vpHeight = (Real) (oMgr.getViewportHeight()); - - // cope with temporarily zero dimensions, avoid divide by zero - vpWidth = vpWidth == 0.0f? 1.0f : vpWidth; - vpHeight = vpHeight == 0.0f? 1.0f : vpHeight; - - mPixelScaleX = 1.0f / vpWidth; - mPixelScaleY = 1.0f / vpHeight; - - if (mMetricsMode == GMM_RELATIVE) - { - mPixelLeft = mLeft; - mPixelTop = mTop; - mPixelWidth = mWidth; - mPixelHeight = mHeight; - } - } - break; - - case GMM_RELATIVE_ASPECT_ADJUSTED : - { - Real vpWidth, vpHeight; - OverlayManager& oMgr = OverlayManager::getSingleton(); - vpWidth = (Real) (oMgr.getViewportWidth()); - vpHeight = (Real) (oMgr.getViewportHeight()); - - mPixelScaleX = 1.0f / (10000.0f * (vpWidth / vpHeight)); - mPixelScaleY = 1.0f / 10000.0f; - - if (mMetricsMode == GMM_RELATIVE) - { - mPixelLeft = mLeft; - mPixelTop = mTop; - mPixelWidth = mWidth; - mPixelHeight = mHeight; - } - } - break; - - default: - case GMM_RELATIVE : - mPixelScaleX = 1.0; - mPixelScaleY = 1.0; - mPixelLeft = mLeft; - mPixelTop = mTop; - mPixelWidth = mWidth; - mPixelHeight = mHeight; - break; - } - - mLeft = mPixelLeft * mPixelScaleX; - mTop = mPixelTop * mPixelScaleY; - mWidth = mPixelWidth * mPixelScaleX; - mHeight = mPixelHeight * mPixelScaleY; - - mMetricsMode = gmm; - mDerivedOutOfDate = true; - _positionsOutOfDate(); - } - //----------------------------------------------------------------------- - void OverlayElement::setHorizontalAlignment(GuiHorizontalAlignment gha) - { - mHorzAlign = gha; - _positionsOutOfDate(); - } - //----------------------------------------------------------------------- - void OverlayElement::setVerticalAlignment(GuiVerticalAlignment gva) - { - mVertAlign = gva; - _positionsOutOfDate(); - } - //----------------------------------------------------------------------- - bool OverlayElement::contains(Real x, Real y) const - { - return x >= mClippingRegion.left && x <= mClippingRegion.right && y >= mClippingRegion.top && y <= mClippingRegion.bottom; - } - //----------------------------------------------------------------------- - OverlayElement* OverlayElement::findElementAt(Real x, Real y) // relative to parent - { - OverlayElement* ret = NULL; - if (contains(x , y )) - { - ret = this; - } - return ret; - } - //----------------------------------------------------------------------- - OverlayElement* OverlayElement::clone(const String& instanceName) - { - OverlayElement* newElement; - - newElement = OverlayManager::getSingleton().createOverlayElement( - getTypeName(), instanceName + "/" + mName); - copyParametersTo(newElement); - - return newElement; - } - //----------------------------------------------------------------------- - -} - diff --git a/Components/Overlay/src/OgreOverlayElementCommands.cpp b/Components/Overlay/src/OgreOverlayElementCommands.cpp deleted file mode 100644 index 6420dc1335b..00000000000 --- a/Components/Overlay/src/OgreOverlayElementCommands.cpp +++ /dev/null @@ -1,187 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreOverlayElementCommands.h" -#include "OgreOverlayElement.h" -#include "OgreStringConverter.h" -#include "OgreLogManager.h" - - -namespace Ogre { - - namespace OverlayElementCommands { - - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String CmdMaterial::doGet(const void* target) const - { - return static_cast(target)->getMaterialName(); - } - void CmdMaterial::doSet(void* target, const String& val) - { - if (val != "") - { - static_cast(target)->setMaterialName(val); - } - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String CmdCaption::doGet(const void* target) const - { - return static_cast(target)->getCaption(); - } - void CmdCaption::doSet(void* target, const String& val) - { - static_cast(target)->setCaption(val); - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String CmdMetricsMode::doGet(const void* target) const - { - GuiMetricsMode gmm = - static_cast(target)->getMetricsMode(); - - switch (gmm) - { - case GMM_PIXELS : - return "pixels"; - - case GMM_RELATIVE_ASPECT_ADJUSTED : - return "relative_aspect_adjusted"; - - default : - return "relative"; - } - } - void CmdMetricsMode::doSet(void* target, const String& val) - { - if (val == "pixels") - { - static_cast(target)->setMetricsMode(GMM_PIXELS); - } - else if (val == "relative_aspect_adjusted") - { - static_cast(target)->setMetricsMode(GMM_RELATIVE_ASPECT_ADJUSTED); - } - else - { - static_cast(target)->setMetricsMode(GMM_RELATIVE); - } - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String CmdHorizontalAlign::doGet(const void* target) const - { - GuiHorizontalAlignment gha = - static_cast(target)->getHorizontalAlignment(); - switch(gha) - { - case GHA_LEFT: - return "left"; - case GHA_RIGHT: - return "right"; - case GHA_CENTER: - return "center"; - } - // To keep compiler happy - return "center"; - } - void CmdHorizontalAlign::doSet(void* target, const String& val) - { - if (val == "left") - { - static_cast(target)->setHorizontalAlignment(GHA_LEFT); - } - else if (val == "right") - { - static_cast(target)->setHorizontalAlignment(GHA_RIGHT); - } - else - { - static_cast(target)->setHorizontalAlignment(GHA_CENTER); - } - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String CmdVerticalAlign::doGet(const void* target) const - { - GuiVerticalAlignment gva = - static_cast(target)->getVerticalAlignment(); - switch(gva) - { - case GVA_TOP: - return "top"; - case GVA_BOTTOM: - return "bottom"; - case GVA_CENTER: - return "center"; - } - // To keep compiler happy - return "center"; - } - void CmdVerticalAlign::doSet(void* target, const String& val) - { - if (val == "top") - { - static_cast(target)->setVerticalAlignment(GVA_TOP); - } - else if (val == "bottom") - { - static_cast(target)->setVerticalAlignment(GVA_BOTTOM); - } - else - { - static_cast(target)->setVerticalAlignment(GVA_CENTER); - } - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String CmdVisible::doGet(const void* target) const - { - return StringConverter::toString(static_cast(target)->isVisible()); - } - void CmdVisible::doSet(void* target, const String& val) - { - if (val == "true") - { - static_cast(target)->show(); - } - else if (val == "false") - { - static_cast(target)->hide(); - } - } - //----------------------------------------------------------------------- - } -} - diff --git a/Components/Overlay/src/OgreOverlayElementCommands.h b/Components/Overlay/src/OgreOverlayElementCommands.h deleted file mode 100644 index e5654946e1e..00000000000 --- a/Components/Overlay/src/OgreOverlayElementCommands.h +++ /dev/null @@ -1,108 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OverlayElementEmitterCommands_H__ -#define __OverlayElementEmitterCommands_H__ - -#include "OgreOverlayPrerequisites.h" -#include "OgreStringInterface.h" - -#include "OgreOverlayElement.h" - -namespace Ogre { - - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Overlays - * @{ - */ - - namespace OverlayElementCommands { - typedef SimpleParamCommand - CmdLeft; - - typedef SimpleParamCommand - CmdTop; - - typedef SimpleParamCommand - CmdWidth; - - typedef SimpleParamCommand - CmdHeight; - - /// Command object for OverlayElement - see ParamCommand - class CmdMaterial : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for OverlayElement - see ParamCommand - class CmdCaption : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for OverlayElement - see ParamCommand - class CmdMetricsMode : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for OverlayElement - see ParamCommand - class CmdHorizontalAlign : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for OverlayElement - see ParamCommand - class CmdVerticalAlign : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for OverlayElement - see ParamCommand - class CmdVisible : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - } - /** @} */ - /** @} */ -} - -#endif - - diff --git a/Components/Overlay/src/OgreOverlayManager.cpp b/Components/Overlay/src/OgreOverlayManager.cpp deleted file mode 100644 index 1ffd24b6c06..00000000000 --- a/Components/Overlay/src/OgreOverlayManager.cpp +++ /dev/null @@ -1,411 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreOverlayManager.h" -#include "OgreOverlayContainer.h" -#include "OgreLogManager.h" -#include "OgreException.h" -#include "OgreViewport.h" -#include "OgreOverlay.h" -#include "OgreResourceGroupManager.h" -#include "OgreOverlayElementFactory.h" -#include "OgreStringConverter.h" -#include "OgreOverlayTranslator.h" - -namespace Ogre { - - //--------------------------------------------------------------------- - template<> OverlayManager *Singleton::msSingleton = 0; - OverlayManager* OverlayManager::getSingletonPtr(void) - { - return msSingleton; - } - OverlayManager& OverlayManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //--------------------------------------------------------------------- - OverlayManager::OverlayManager() - : mLastViewportWidth(0), - mLastViewportHeight(0), - mPixelRatio(1) - { - - // Scripting is supported by this manager - mScriptPatterns.push_back("*.overlay"); - ResourceGroupManager::getSingleton()._registerScriptLoader(this); - mTranslatorManager.reset(new OverlayTranslatorManager()); - } - //--------------------------------------------------------------------- - OverlayManager::~OverlayManager() - { - destroyAll(); - // Overlays notify OverlayElements of their destruction, so we destroy Overlays first - destroyAllOverlayElements(false); - destroyAllOverlayElements(true); - - for(auto& f : mFactories) - { - OGRE_DELETE f.second; - } - - // Unregister with resource group manager - ResourceGroupManager::getSingleton()._unregisterScriptLoader(this); - } - //--------------------------------------------------------------------- - void OverlayManager::_releaseManualHardwareResources() - { - for(auto& e : mElements) - e.second->_releaseManualHardwareResources(); - } - //--------------------------------------------------------------------- - void OverlayManager::_restoreManualHardwareResources() - { - for(auto& e : mElements) - e.second->_restoreManualHardwareResources(); - } - //--------------------------------------------------------------------- - const StringVector& OverlayManager::getScriptPatterns(void) const - { - return mScriptPatterns; - } - //--------------------------------------------------------------------- - Real OverlayManager::getLoadingOrder(void) const - { - // Load late - return 1100.0f; - } - //--------------------------------------------------------------------- - Overlay* OverlayManager::create(const String& name) - { - Overlay* ret = 0; - OverlayMap::iterator i = mOverlayMap.find(name); - - if (i == mOverlayMap.end()) - { - ret = OGRE_NEW Overlay(name); - assert(ret && "Overlay creation failed"); - mOverlayMap[name] = ret; - } - else - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "Overlay with name '" + name + "' already exists!", - "OverlayManager::create"); - } - - return ret; - - } - //--------------------------------------------------------------------- - Overlay* OverlayManager::getByName(const String& name) - { - OverlayMap::iterator i = mOverlayMap.find(name); - if (i == mOverlayMap.end()) - { - return 0; - } - else - { - return i->second; - } - - } - - void OverlayManager::addOverlay(Overlay* overlay) - { - bool succ = mOverlayMap.emplace(overlay->getName(), overlay).second; - if(succ) return; - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "Overlay with name '" + overlay->getName() + "' already exists!"); - } - //--------------------------------------------------------------------- - void OverlayManager::destroy(const String& name) - { - OverlayMap::iterator i = mOverlayMap.find(name); - if (i == mOverlayMap.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Overlay with name '" + name + "' not found.", - "OverlayManager::destroy"); - } - else - { - OGRE_DELETE i->second; - mOverlayMap.erase(i); - } - } - //--------------------------------------------------------------------- - void OverlayManager::destroy(Overlay* overlay) - { - for (OverlayMap::iterator i = mOverlayMap.begin(); - i != mOverlayMap.end(); ++i) - { - if (i->second == overlay) - { - OGRE_DELETE i->second; - mOverlayMap.erase(i); - return; - } - } - - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Overlay not found.", - "OverlayManager::destroy"); - } - //--------------------------------------------------------------------- - void OverlayManager::destroyAll(void) - { - for (auto& o : mOverlayMap) - { - OGRE_DELETE o.second; - } - mOverlayMap.clear(); - } - //--------------------------------------------------------------------- - OverlayManager::OverlayMapIterator OverlayManager::getOverlayIterator(void) - { - return OverlayMapIterator(mOverlayMap.begin(), mOverlayMap.end()); - } - void OverlayManager::parseScript(DataStreamPtr& stream, const String& groupName) - { - // skip scripts that were already loaded as we lack proper re-loading support - if(!stream->getName().empty() && !mLoadedScripts.emplace(stream->getName()).second) - { - LogManager::getSingleton().logWarning( - StringUtil::format("Skipping loading '%s' as it is already loaded", stream->getName().c_str())); - return; - } - - ScriptCompilerManager::getSingleton().parseScript(stream, groupName); - } - //--------------------------------------------------------------------- - void OverlayManager::_queueOverlaysForRendering(Camera* cam, - RenderQueue* pQueue, Viewport* vp) - { - // Flag for update pixel-based GUIElements if viewport has changed dimensions - if (mLastViewportWidth != int(vp->getActualWidth() / mPixelRatio) || - mLastViewportHeight != int(vp->getActualHeight() / mPixelRatio)) - { - mLastViewportWidth = int(vp->getActualWidth() / mPixelRatio); - mLastViewportHeight = int(vp->getActualHeight() / mPixelRatio); - } - - for (auto& o : mOverlayMap) - { - o.second->_findVisibleObjects(cam, pQueue, vp); - } - } - //--------------------------------------------------------------------- - int OverlayManager::getViewportHeight(void) const - { - return mLastViewportHeight; - } - //--------------------------------------------------------------------- - int OverlayManager::getViewportWidth(void) const - { - return mLastViewportWidth; - } - //--------------------------------------------------------------------- - Real OverlayManager::getViewportAspectRatio(void) const - { - return (Real)mLastViewportWidth / (Real)mLastViewportHeight; - } - //--------------------------------------------------------------------- - float OverlayManager::getPixelRatio(void) const - { - return mPixelRatio; - } - //--------------------------------------------------------------------- - void OverlayManager::setPixelRatio(float ratio) - { - mPixelRatio = ratio; - } - //--------------------------------------------------------------------- - OverlayElement* OverlayManager::createOverlayElementFromTemplate(const String& templateName, const String& typeName, const String& instanceName, bool) - { - - OverlayElement* newObj = NULL; - - if (templateName.empty()) - { - newObj = createOverlayElement(typeName, instanceName); - } - else - { - // no template - OverlayElement* templateGui = getOverlayElement(templateName, true); - - String typeNameToCreate; - if (typeName.empty()) - { - typeNameToCreate = templateGui->getTypeName(); - } - else - { - typeNameToCreate = typeName; - } - - newObj = createOverlayElement(typeNameToCreate, instanceName); - - ((OverlayContainer*)newObj)->copyFromTemplate(templateGui); - } - - return newObj; - } - - - //--------------------------------------------------------------------- - OverlayElement* OverlayManager::cloneOverlayElementFromTemplate(const String& templateName, const String& instanceName) - { - OverlayElement* templateGui = getOverlayElement(templateName, true); - return templateGui->clone(instanceName); - } - - //--------------------------------------------------------------------- - OverlayElement* OverlayManager::createOverlayElement(const String& typeName, const String& instanceName, bool) - { - // Check not duplicated - ElementMap::iterator ii = mElements.find(instanceName); - if (ii != mElements.end()) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, "OverlayElement with name " + instanceName + - " already exists.", "OverlayManager::createOverlayElement" ); - } - OverlayElement* newElem = createOverlayElementFromFactory(typeName, instanceName); - - // Register - mElements.emplace(instanceName, newElem); - - return newElem; - - - } - - //--------------------------------------------------------------------- - OverlayElement* OverlayManager::createOverlayElementFromFactory(const String& typeName, const String& instanceName) - { - // Look up factory - FactoryMap::iterator fi = mFactories.find(typeName); - if (fi == mFactories.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Cannot locate factory for element type " + typeName, - "OverlayManager::createOverlayElement"); - } - - // create - return fi->second->createOverlayElement(instanceName); - } - //--------------------------------------------------------------------- - OverlayElement* OverlayManager::getOverlayElement(const String& name,bool) - { - // Locate instance - ElementMap::iterator ii = mElements.find(name); - if (ii == mElements.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "OverlayElement with name " + name + " not found."); - } - - return ii->second; - } - //--------------------------------------------------------------------- - bool OverlayManager::hasOverlayElement(const String& name,bool) - { - ElementMap::iterator ii = mElements.find(name); - return ii != mElements.end(); - } - - //--------------------------------------------------------------------- - void OverlayManager::destroyOverlayElement(OverlayElement* pInstance,bool) - { - destroyOverlayElement(pInstance->getName()); - } - //--------------------------------------------------------------------- - void OverlayManager::destroyOverlayElement(const String& instanceName,bool) - { - // Locate instance - ElementMap::iterator ii = mElements.find(instanceName); - if (ii == mElements.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "OverlayElement with name " + instanceName + - " not found.", "OverlayManager::destroyOverlayElement" ); - } - // Look up factory - const String& typeName = ii->second->getTypeName(); - FactoryMap::iterator fi = mFactories.find(typeName); - if (fi == mFactories.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Cannot locate factory for element type " + typeName, - "OverlayManager::destroyOverlayElement"); - } - - fi->second->destroyOverlayElement(ii->second); - mElements.erase(ii); - } - //--------------------------------------------------------------------- - void OverlayManager::destroyAllOverlayElements(bool) - { - ElementMap::iterator i; - - while ((i = mElements.begin()) != mElements.end()) - { - OverlayElement* element = i->second; - - // Get factory to delete - FactoryMap::iterator fi = mFactories.find(element->getTypeName()); - if (fi == mFactories.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Cannot locate factory for element " - + element->getName(), - "OverlayManager::destroyAllOverlayElements"); - } - - // remove from parent, if any - OverlayContainer* parent; - if ((parent = element->getParent()) != 0) - { - parent->_removeChild(element->getName()); - } - - // children of containers will be auto-removed when container is destroyed. - // destroy the element and remove it from the list - fi->second->destroyOverlayElement(element); - mElements.erase(i); - } - } - //--------------------------------------------------------------------- - void OverlayManager::addOverlayElementFactory(OverlayElementFactory* elemFactory) - { - // Add / replace - mFactories[elemFactory->getTypeName()] = elemFactory; - - LogManager::getSingleton().logMessage("OverlayElementFactory for type " + elemFactory->getTypeName() - + " registered."); - } -} - diff --git a/Components/Overlay/src/OgreOverlayProfileSessionListener.cpp b/Components/Overlay/src/OgreOverlayProfileSessionListener.cpp deleted file mode 100644 index 8b210c1f0b9..00000000000 --- a/Components/Overlay/src/OgreOverlayProfileSessionListener.cpp +++ /dev/null @@ -1,367 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreOverlayProfileSessionListener.h" -#include "OgreOverlayManager.h" -#include "OgreOverlayContainer.h" -#include "OgreOverlayElement.h" -#include "OgreOverlay.h" -#include "OgreStringConverter.h" - -namespace Ogre -{ - //----------------------------------------------------------------------- - OverlayProfileSessionListener::OverlayProfileSessionListener() - : mOverlay(0) - , mProfileGui(0) - , mBarHeight(10) - , mGuiHeight(25) - , mGuiWidth(250) - , mGuiLeft(0) - , mGuiTop(0) - , mBarIndent(250) - , mGuiBorderWidth(10) - , mBarLineWidth(2) - , mBarSpacing(3) - , mMaxDisplayProfiles(50) - , mDisplayMode(DISPLAY_MILLISECONDS) - { - } - //----------------------------------------------------------------------- - OverlayProfileSessionListener::~OverlayProfileSessionListener() - { - mProfileBars.clear(); - } - //----------------------------------------------------------------------- - void OverlayProfileSessionListener::initializeSession() - { - // create a new overlay to hold our Profiler display - mOverlay = OverlayManager::getSingleton().create("Profiler"); - mOverlay->setZOrder(500); - - // this panel will be the main container for our profile bars - mProfileGui = createContainer(); - - // we create an initial pool of 50 profile bars - for (uint i = 0; i < mMaxDisplayProfiles; ++i) - { - // this is for the profile name and the number of times it was called in a frame - OverlayElement* element = createTextArea("profileText" + StringConverter::toString(i), 90, mBarHeight, mGuiBorderWidth + (mBarHeight + mBarSpacing) * i, 0, 14, "", false); - mProfileGui->addChild(element); - mProfileBars.push_back(element); - - // this indicates the current frame time - element = createPanel("currBar" + StringConverter::toString(i), 0, mBarHeight, mGuiBorderWidth + (mBarHeight + mBarSpacing) * i, mBarIndent, "Core/ProfilerCurrent", false); - mProfileGui->addChild(element); - mProfileBars.push_back(element); - - // this indicates the minimum frame time - element = createPanel("minBar" + StringConverter::toString(i), mBarLineWidth, mBarHeight, mGuiBorderWidth + (mBarHeight + mBarSpacing) * i, 0, "Core/ProfilerMin", false); - mProfileGui->addChild(element); - mProfileBars.push_back(element); - - // this indicates the maximum frame time - element = createPanel("maxBar" + StringConverter::toString(i), mBarLineWidth, mBarHeight, mGuiBorderWidth + (mBarHeight + mBarSpacing) * i, 0, "Core/ProfilerMax", false); - mProfileGui->addChild(element); - mProfileBars.push_back(element); - - // this indicates the average frame time - element = createPanel("avgBar" + StringConverter::toString(i), mBarLineWidth, mBarHeight, mGuiBorderWidth + (mBarHeight + mBarSpacing) * i, 0, "Core/ProfilerAvg", false); - mProfileGui->addChild(element); - mProfileBars.push_back(element); - - // this indicates the text of the frame time - element = createTextArea("statText" + StringConverter::toString(i), 20, mBarHeight, mGuiBorderWidth + (mBarHeight + mBarSpacing) * i, 0, 14, "", false); - mProfileGui->addChild(element); - mProfileBars.push_back(element); - } - - // throw everything all the GUI stuff into the overlay and display it - mOverlay->add2D(mProfileGui); - } - //----------------------------------------------------------------------- - void OverlayProfileSessionListener::finializeSession() - { - OverlayContainer* container = dynamic_cast(mProfileGui); - if (container) - { - for (const auto& p : container->getChildren()) - { - OverlayElement* element = p.second; - OverlayContainer* parent = element->getParent(); - if (parent) parent->removeChild(element->getName()); - OverlayManager::getSingleton().destroyOverlayElement(element); - } - } - if(mProfileGui) - OverlayManager::getSingleton().destroyOverlayElement(mProfileGui); - if(mOverlay) - OverlayManager::getSingleton().destroy(mOverlay); - - mProfileBars.clear(); - } - //----------------------------------------------------------------------- - void OverlayProfileSessionListener::displayResults(const ProfileInstance& root, ulong maxTotalFrameTime) - { - Real newGuiHeight = mGuiHeight; - int profileCount = 0; - Real maxTimeMillisecs = (Real)maxTotalFrameTime / 1000.0f; - - ProfileBarList::const_iterator bIter = mProfileBars.begin(); - for (auto& c : root.children) - { - displayResults(c.second, bIter, maxTimeMillisecs, newGuiHeight, profileCount); - } - - // set the main display dimensions - mProfileGui->setMetricsMode(GMM_PIXELS); - mProfileGui->setHeight(newGuiHeight); - mProfileGui->setWidth(mGuiWidth * 2 + 15); - mProfileGui->setTop(5); - mProfileGui->setLeft(5); - - // we hide all the remaining pre-created bars - for (; bIter != mProfileBars.end(); ++bIter) - { - (*bIter)->hide(); - } - } - //----------------------------------------------------------------------- - void OverlayProfileSessionListener::displayResults(ProfileInstance* instance, ProfileBarList::const_iterator& bIter, Real& maxTimeMillisecs, Real& newGuiHeight, int& profileCount) - { - OverlayElement* g; - - // display the profile's name and the number of times it was called in a frame - g = *bIter; - ++bIter; - g->show(); - g->setCaption(String(instance->name + " (" + StringConverter::toString(instance->history.numCallsThisFrame) + ")")); - g->setLeft(10 + instance->hierarchicalLvl * 15.0f); - - - // display the main bar that show the percentage of the frame time that this - // profile has taken - g = *bIter; - ++bIter; - g->show(); - // most of this junk has been set before, but we do this to get around a weird - // Ogre gui issue (bug?) - g->setMetricsMode(GMM_PIXELS); - g->setHeight(mBarHeight); - - if (mDisplayMode == DISPLAY_PERCENTAGE) - g->setWidth( (instance->history.currentTimePercent) * mGuiWidth); - else - g->setWidth( (instance->history.currentTimeMillisecs / maxTimeMillisecs) * mGuiWidth); - - g->setLeft(mGuiWidth); - g->setTop(mGuiBorderWidth + profileCount * (mBarHeight + mBarSpacing)); - - - - // display line to indicate the minimum frame time for this profile - g = *bIter; - ++bIter; - g->show(); - if(mDisplayMode == DISPLAY_PERCENTAGE) - g->setLeft(mBarIndent + instance->history.minTimePercent * mGuiWidth); - else - g->setLeft(mBarIndent + (instance->history.minTimeMillisecs / maxTimeMillisecs) * mGuiWidth); - - // display line to indicate the maximum frame time for this profile - g = *bIter; - ++bIter; - g->show(); - if(mDisplayMode == DISPLAY_PERCENTAGE) - g->setLeft(mBarIndent + instance->history.maxTimePercent * mGuiWidth); - else - g->setLeft(mBarIndent + (instance->history.maxTimeMillisecs / maxTimeMillisecs) * mGuiWidth); - - // display line to indicate the average frame time for this profile - g = *bIter; - ++bIter; - g->show(); - if(instance->history.totalCalls != 0) - { - if (mDisplayMode == DISPLAY_PERCENTAGE) - g->setLeft(mBarIndent + (instance->history.totalTimePercent / instance->history.totalCalls) * mGuiWidth); - else - g->setLeft(mBarIndent + ((instance->history.totalTimeMillisecs / instance->history.totalCalls) / maxTimeMillisecs) * mGuiWidth); - } - else - g->setLeft(mBarIndent); - - // display text - g = *bIter; - ++bIter; - g->show(); - if (mDisplayMode == DISPLAY_PERCENTAGE) - { - g->setLeft(mBarIndent + instance->history.currentTimePercent * mGuiWidth + 2); - g->setCaption(StringConverter::toString(instance->history.currentTimePercent * 100.0f, 3, 3) + "%"); - } - else - { - g->setLeft(mBarIndent + (instance->history.currentTimeMillisecs / maxTimeMillisecs) * mGuiWidth + 2); - g->setCaption(StringConverter::toString(instance->history.currentTimeMillisecs, 3, 3) + "ms"); - } - - // we set the height of the display with respect to the number of profiles displayed - newGuiHeight += mBarHeight + mBarSpacing; - - ++profileCount; - - // display children - for(auto& c : instance->children) - { - displayResults(c.second, bIter, maxTimeMillisecs, newGuiHeight, profileCount); - } - } - //----------------------------------------------------------------------- - void OverlayProfileSessionListener::changeEnableState(bool enabled) - { - if (enabled) - { - mOverlay->show(); - } - else - { - mOverlay->hide(); - } - } - //----------------------------------------------------------------------- - OverlayContainer* OverlayProfileSessionListener::createContainer() - { - OverlayContainer* container = (OverlayContainer*) - OverlayManager::getSingleton().createOverlayElement( - "BorderPanel", "profiler"); - container->setMetricsMode(GMM_PIXELS); - container->setMaterialName("Core/StatsBlockCenter"); - container->setHeight(mGuiHeight); - container->setWidth(mGuiWidth * 2 + 15); - container->setParameter("border_size", "1 1 1 1"); - container->setParameter("border_material", "Core/StatsBlockBorder"); - container->setParameter("border_topleft_uv", "0.0000 1.0000 0.0039 0.9961"); - container->setParameter("border_top_uv", "0.0039 1.0000 0.9961 0.9961"); - container->setParameter("border_topright_uv", "0.9961 1.0000 1.0000 0.9961"); - container->setParameter("border_left_uv","0.0000 0.9961 0.0039 0.0039"); - container->setParameter("border_right_uv","0.9961 0.9961 1.0000 0.0039"); - container->setParameter("border_bottomleft_uv","0.0000 0.0039 0.0039 0.0000"); - container->setParameter("border_bottom_uv","0.0039 0.0039 0.9961 0.0000"); - container->setParameter("border_bottomright_uv","0.9961 0.0039 1.0000 0.0000"); - container->setLeft(5); - container->setTop(5); - - return container; - } - //----------------------------------------------------------------------- - OverlayElement* OverlayProfileSessionListener::createTextArea(const String& name, Real width, Real height, Real top, Real left, - uint fontSize, const String& caption, bool show) - { - OverlayElement* textArea = OverlayManager::getSingleton().createOverlayElement("TextArea", name); - textArea->setMetricsMode(GMM_PIXELS); - textArea->setWidth(width); - textArea->setHeight(height); - textArea->setTop(top); - textArea->setLeft(left); - textArea->setParameter("font_name", "SdkTrays/Value"); - textArea->setParameter("char_height", StringConverter::toString(fontSize)); - textArea->setCaption(caption); - textArea->setParameter("colour_top", "1 1 1"); - textArea->setParameter("colour_bottom", "1 1 1"); - - if (show) { - textArea->show(); - } - else { - textArea->hide(); - } - - return textArea; - } - //----------------------------------------------------------------------- - OverlayElement* OverlayProfileSessionListener::createPanel(const String& name, Real width, Real height, Real top, Real left, - const String& materialName, bool show) - { - OverlayElement* panel = - OverlayManager::getSingleton().createOverlayElement("Panel", name); - panel->setMetricsMode(GMM_PIXELS); - panel->setWidth(width); - panel->setHeight(height); - panel->setTop(top); - panel->setLeft(left); - panel->setMaterialName(materialName); - - if (show) { - panel->show(); - } - else { - panel->hide(); - } - - return panel; - } - //----------------------------------------------------------------------- - void OverlayProfileSessionListener::setOverlayPosition(Real left, Real top) - { - mGuiLeft = left; - mGuiTop = top; - - mProfileGui->setPosition(left, top); - } - //--------------------------------------------------------------------- - Real OverlayProfileSessionListener::getOverlayWidth() const - { - return mGuiWidth; - } - //--------------------------------------------------------------------- - Real OverlayProfileSessionListener::getOverlayHeight() const - { - return mGuiHeight; - } - //--------------------------------------------------------------------- - Real OverlayProfileSessionListener::getOverlayLeft() const - { - return mGuiLeft; - } - //--------------------------------------------------------------------- - Real OverlayProfileSessionListener::getOverlayTop() const - { - return mGuiTop; - } - //----------------------------------------------------------------------- - void OverlayProfileSessionListener::setOverlayDimensions(Real width, Real height) - { - mGuiWidth = width; - mGuiHeight = height; - mBarIndent = mGuiWidth; - - mProfileGui->setDimensions(width, height); - } - //----------------------------------------------------------------------- -} diff --git a/Components/Overlay/src/OgreOverlaySystem.cpp b/Components/Overlay/src/OgreOverlaySystem.cpp deleted file mode 100644 index e4746a671b9..00000000000 --- a/Components/Overlay/src/OgreOverlaySystem.cpp +++ /dev/null @@ -1,156 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreOverlaySystem.h" -#include "OgreCamera.h" -#include "OgreRoot.h" -#include "OgreViewport.h" -#include "OgreOverlayManager.h" -#include "OgreOverlayElementFactory.h" -#include "OgreFontManager.h" - -namespace Ogre { - //--------------------------------------------------------------------- - /** Factory for creating PanelOverlayElement instances. */ - class PanelOverlayElementFactory: public OverlayElementFactory - { - public: - OverlayElement* createOverlayElement(const String& instanceName) override - { - return OGRE_NEW PanelOverlayElement(instanceName); - } - const String& getTypeName(void) const override - { - static String name = "Panel"; - return name; - } - }; - - /** Factory for creating BorderPanelOverlayElement instances. */ - class BorderPanelOverlayElementFactory: public OverlayElementFactory - { - public: - OverlayElement* createOverlayElement(const String& instanceName) override - { - return OGRE_NEW BorderPanelOverlayElement(instanceName); - } - const String& getTypeName(void) const override - { - static String name = "BorderPanel"; - return name; - } - }; - - /** Factory for creating TextAreaOverlayElement instances. */ - class TextAreaOverlayElementFactory: public OverlayElementFactory - { - public: - OverlayElement* createOverlayElement(const String& instanceName) override - { - return OGRE_NEW TextAreaOverlayElement(instanceName); - } - const String& getTypeName(void) const override - { - static String name = "TextArea"; - return name; - } - }; - - template<> OverlaySystem *Singleton::msSingleton = 0; - OverlaySystem* OverlaySystem::getSingletonPtr() - { - return msSingleton; - } - OverlaySystem& OverlaySystem::getSingleton() - { - assert( msSingleton ); return ( *msSingleton ); - } - //--------------------------------------------------------------------- - OverlaySystem::OverlaySystem() - { - RenderSystem::setSharedListener(this); - - mOverlayManager = OGRE_NEW Ogre::OverlayManager(); - mOverlayManager->addOverlayElementFactory(OGRE_NEW Ogre::PanelOverlayElementFactory()); - - mOverlayManager->addOverlayElementFactory(OGRE_NEW Ogre::BorderPanelOverlayElementFactory()); - - mOverlayManager->addOverlayElementFactory(OGRE_NEW Ogre::TextAreaOverlayElementFactory()); - - mFontManager = OGRE_NEW FontManager(); - if (auto prof = Profiler::getSingletonPtr()) - { - mProfileListener = new Ogre::OverlayProfileSessionListener(); - prof->addListener(mProfileListener); - } - } - //--------------------------------------------------------------------- - OverlaySystem::~OverlaySystem() - { - if(RenderSystem::getSharedListener() == this) - RenderSystem::setSharedListener(0); - - if (auto prof = Profiler::getSingletonPtr()) - { - prof->removeListener(mProfileListener); - delete mProfileListener; - } - - OGRE_DELETE mOverlayManager; - OGRE_DELETE mFontManager; - } - //--------------------------------------------------------------------- - void OverlaySystem::renderQueueStarted(uint8 queueGroupId, const String& cameraName, bool& skipThisInvocation) - { - if(queueGroupId == Ogre::RENDER_QUEUE_OVERLAY) - { - Ogre::Viewport* vp = Ogre::Root::getSingletonPtr()->getRenderSystem()->_getViewport(); - if(vp != NULL) - { - Ogre::SceneManager* sceneMgr = vp->getCamera()->getSceneManager(); - if (vp->getOverlaysEnabled() && sceneMgr->_getCurrentRenderStage() != Ogre::SceneManager::IRS_RENDER_TO_TEXTURE) - { - OverlayManager::getSingleton()._queueOverlaysForRendering(vp->getCamera(), sceneMgr->getRenderQueue(), vp); - } - } - } - } - //--------------------------------------------------------------------- - void OverlaySystem::eventOccurred(const String& eventName, const NameValuePairList* parameters) - { - if(eventName == "DeviceLost") - { - mOverlayManager->_releaseManualHardwareResources(); - } - else if(eventName == "DeviceRestored") - { - mOverlayManager->_restoreManualHardwareResources(); - } - } - //--------------------------------------------------------------------- -} diff --git a/Components/Overlay/src/OgreOverlayTranslator.cpp b/Components/Overlay/src/OgreOverlayTranslator.cpp deleted file mode 100644 index 57fcb4760bf..00000000000 --- a/Components/Overlay/src/OgreOverlayTranslator.cpp +++ /dev/null @@ -1,311 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreOverlayTranslator.h" -#include "OgreFontManager.h" -#include "OgreScriptTranslator.h" -#include "OgreOverlayManager.h" -#include "OgreOverlayContainer.h" - -#include - -namespace Ogre -{ -//! [font_translate] -void FontTranslator::translate(ScriptCompiler* compiler, const AbstractNodePtr& node) -{ - ObjectAbstractNode* obj = static_cast(node.get()); - - // Must have a name - unless we are in legacy mode. Then the class is the name. - if (obj->name.empty() && obj->cls == "font") - { - compiler->addError(ScriptCompiler::CE_OBJECTNAMEEXPECTED, obj->file, obj->line, - "font must be given a name"); - return; - } - - String& name = obj->cls == "font" ? obj->name : obj->cls; - - FontPtr font = FontManager::getSingleton().create(name, compiler->getResourceGroup()); - font->_notifyOrigin(obj->file); - - for (auto& c : obj->children) - { - if (c->type == ANT_PROPERTY) - { - parseAttribute(compiler, font, static_cast(c.get())); - } - } -} -//! [font_translate] - -void FontTranslator::parseAttribute(ScriptCompiler* compiler, FontPtr& pFont, - PropertyAbstractNode* prop) -{ - String& attrib = prop->name; - String val; - - if (attrib == "glyph") - { - std::vector coords; - if (prop->values.size() != 5 || !getString(prop->values.front(), &val) || - !getVector(++prop->values.begin(), prop->values.end(), coords, 4)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - return; - } - - // Set - // Support numeric and character glyph specification - Font::CodePoint cp; - if (val.size() > 1 && val[0] == 'u') - { - // Unicode glyph spec - String trimmed = val.substr(1); - cp = StringConverter::parseUnsignedInt(trimmed); - } - else - { - // Direct character - cp = val[0]; - } - pFont->setGlyphInfoFromTexCoords( - cp, FloatRect(coords[0], coords[1], coords[2], coords[3])); // assume image is square - } - else if (attrib == "antialias_colour") - { - bool flag; - if (prop->values.empty() || !getBoolean(prop->values.front(), &flag)) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - return; - } - pFont->setAntialiasColour(flag); - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, prop->file, prop->line, attrib); - } - else if (attrib == "code_points") - { - if (prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - return; - } - - for (auto& v : prop->values) - { - - bool succ = getString(v, &val); - StringVector itemVec = StringUtil::split(val, "-"); - if (succ && itemVec.size() == 2) - { - pFont->addCodePointRange( - Font::CodePointRange(StringConverter::parseUnsignedInt(itemVec[0]), - StringConverter::parseUnsignedInt(itemVec[1]))); - } - } - } - else if(attrib == "character_spacer") - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, prop->file, prop->line, attrib); - else if (prop->values.empty() || !getString(prop->values.front(), &val) || - !pFont->setParameter(attrib, val)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } -} - -void ElementTranslator::translate(ScriptCompiler* compiler, const AbstractNodePtr& node) -{ - ObjectAbstractNode* obj = static_cast(node.get()); - - String name; - // legacy compat - if ((obj->cls == "template") && !obj->values.empty()) - { - getString(obj->values.front(), &name); - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, obj->file, obj->line, "template. use overlay_element"); - } - else - name = obj->name; - - String type; - if(obj->values.empty() || ((obj->cls == "template") && obj->values.size() == 1)) - { - // legacy naming support - std::vector params = StringUtil::split(name, "()", 2); - - if (params.size() != 2) - { - compiler->addError(ScriptCompiler::CE_OBJECTNAMEEXPECTED, obj->file, obj->line, - "expecting 'element type(name)' or 'overlay_element name type'"); - return; - } - - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, obj->file, obj->line, "'element type(name)'. use 'overlay_element name type'"); - - type = params[0]; - name = params[1]; - } - else - getString(obj->values.front(), &type); - - String templateName; - if(!obj->bases.empty()) - templateName = obj->bases.front(); - - OverlayElement* newElement = - OverlayManager::getSingleton().createOverlayElementFromTemplate(templateName, type, name); - - if(obj->parent && obj->parent->context.has_value()) - { - Overlay** overlay = any_cast(&obj->parent->context); - if(overlay) - if(newElement->isContainer()) - (*overlay)->add2D((OverlayContainer*)newElement); - else - compiler->addError(ScriptCompiler::CE_OBJECTALLOCATIONERROR, obj->file, obj->line, - "Top level components must be containers, but '" + type + "' is an element"); - else - any_cast(obj->parent->context)->addChild(newElement); - } - - if(newElement->isContainer()) - obj->context = (OverlayContainer*)newElement; - - String val; - for (auto& c : obj->children) - { - if (c->type == ANT_PROPERTY) - { - PropertyAbstractNode* prop = static_cast(c.get()); - - bool succ = true; - if(prop->values.size() > 1) - { - // FIXME: joining string, just so setParameter can split it again.. - StringStream ss; - for(auto& v : prop->values) { - succ = succ && getString(v, &val); - ss << val << " "; - } - val = ss.str(); - } - else - { - succ = getString(prop->values.front(), &val); - } - - if(prop->name == "space_width") - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, prop->file, prop->line, prop->name); - - if(!succ || !newElement->setParameter(prop->name, val)) - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - else if(c->type == ANT_OBJECT) - translate(compiler, c); // recurse - } -} - -void OverlayTranslator::translate(ScriptCompiler* compiler, const AbstractNodePtr& node) -{ - ObjectAbstractNode* obj = static_cast(node.get()); - - // Must have a name - unless we are in legacy mode. Then the class is the name. - if (obj->name.empty() && obj->cls == "overlay") - { - compiler->addError(ScriptCompiler::CE_OBJECTNAMEEXPECTED, obj->file, obj->line, - "overlay must be given a name"); - return; - } - - String& name = obj->cls == "overlay" ? obj->name : obj->cls; - Overlay* overlay = OverlayManager::getSingleton().create(name); - overlay->_notifyOrigin(obj->file); - - obj->context = overlay; - - for (auto& c : obj->children) - { - if (c->type == ANT_PROPERTY) - { - PropertyAbstractNode* prop = static_cast(c.get()); - - uint32 zorder; - if (prop->name != "zorder" || prop->values.empty() || !getUInt(prop->values.front(), &zorder)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, obj->file, obj->line, prop->name); - continue; - } - overlay->setZOrder(Math::uint16Cast(zorder)); - } - else if(c->type == ANT_OBJECT) - processNode(compiler, c); - } -} - -OverlayTranslatorManager::OverlayTranslatorManager() -{ -//! [font_register] - ScriptCompilerManager::getSingleton().addTranslatorManager(this); - ID_FONT = ScriptCompilerManager::getSingleton().registerCustomWordId("font"); -//! [font_register] - ID_OVERLAY_ELEMENT = ScriptCompilerManager::getSingleton().registerCustomWordId("overlay_element"); - ID_OVERLAY = ScriptCompilerManager::getSingleton().registerCustomWordId("overlay"); - ID_CONTAINER = ScriptCompilerManager::getSingleton().registerCustomWordId("container"); - ID_ELEMENT = ScriptCompilerManager::getSingleton().registerCustomWordId("element"); - ID_TEMPLATE = ScriptCompilerManager::getSingleton().registerCustomWordId("template"); -} - -OverlayTranslatorManager::~OverlayTranslatorManager() -{ - ScriptCompilerManager::getSingleton().removeTranslatorManager(this); -} - -//! [font_get_translator] -ScriptTranslator* OverlayTranslatorManager::getTranslator(const AbstractNodePtr& node) -{ - if (node->type != ANT_OBJECT) - return NULL; - - ObjectAbstractNode* obj = static_cast(node.get()); - - if (obj->id == ID_FONT) - return &mFontTranslator; -//! [font_get_translator] - - // legacy compatibility: assume this is a font if we are in a .fontdef file - if (obj->id == 0 && StringUtil::endsWith(node->file, ".fontdef")) - return &mFontTranslator; - - if (obj->id == ID_CONTAINER || obj->id == ID_TEMPLATE || obj->id == ID_ELEMENT || obj->id == ID_OVERLAY_ELEMENT) - return &mElementTranslator; - - // legacy compatibility: assume this is an overlay if we are in a .overlay file - if(obj->id == ID_OVERLAY || (obj->id == 0 && StringUtil::endsWith(node->file, ".overlay"))) - return &mOverlayTranslator; - - return NULL; -} -} diff --git a/Components/Overlay/src/OgreOverlayTranslator.h b/Components/Overlay/src/OgreOverlayTranslator.h deleted file mode 100644 index 805fe763b16..00000000000 --- a/Components/Overlay/src/OgreOverlayTranslator.h +++ /dev/null @@ -1,72 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _OverlayScriptTranslator_ -#define _OverlayScriptTranslator_ - -#include "OgreOverlay.h" -#include "OgreScriptTranslator.h" -#include "OgreFont.h" - -namespace Ogre -{ -//! [font_translator] -struct FontTranslator : public ScriptTranslator -{ - void translate(ScriptCompiler* compiler, const AbstractNodePtr& node) override; - void parseAttribute(ScriptCompiler* compiler, FontPtr& pFont, PropertyAbstractNode* prop); -}; -//! [font_translator] - -struct ElementTranslator : public ScriptTranslator -{ - void translate(ScriptCompiler* compiler, const AbstractNodePtr& node) override; -}; - -struct OverlayTranslator : public ScriptTranslator -{ - void translate(ScriptCompiler* compiler, const AbstractNodePtr& node) override; -}; - -class OverlayTranslatorManager : public ScriptTranslatorManager -{ - FontTranslator mFontTranslator; - ElementTranslator mElementTranslator; - OverlayTranslator mOverlayTranslator; - uint32 ID_FONT; - uint32 ID_OVERLAY_ELEMENT; - uint32 ID_OVERLAY; - uint32 ID_CONTAINER; - uint32 ID_ELEMENT; - uint32 ID_TEMPLATE; -public: - OverlayTranslatorManager(); - ~OverlayTranslatorManager(); - ScriptTranslator* getTranslator(const AbstractNodePtr& node) override; -}; -} - -#endif diff --git a/Components/Overlay/src/OgrePanelOverlayElement.cpp b/Components/Overlay/src/OgrePanelOverlayElement.cpp deleted file mode 100644 index 2d7fde76ab9..00000000000 --- a/Components/Overlay/src/OgrePanelOverlayElement.cpp +++ /dev/null @@ -1,474 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgrePanelOverlayElement.h" -#include "OgreTechnique.h" -#include "OgreStringConverter.h" -#include "OgreHardwareBufferManager.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" - -namespace Ogre { - //--------------------------------------------------------------------- - String PanelOverlayElement::msTypeName = "Panel"; - /** Command object for specifying tiling (see ParamCommand).*/ - class _OgrePrivate CmdTiling : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for specifying transparency (see ParamCommand).*/ - class _OgrePrivate CmdTransparent : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for specifying UV coordinates (see ParamCommand).*/ - class _OgrePrivate CmdUVCoords : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - // Command objects - static CmdTiling msCmdTiling; - static CmdTransparent msCmdTransparent; - static CmdUVCoords msCmdUVCoords; - //--------------------------------------------------------------------- - // vertex buffer bindings, set at compile time (we could look these up but no point) - #define POSITION_BINDING 0 - #define TEXCOORD_BINDING 1 - - //--------------------------------------------------------------------- - PanelOverlayElement::PanelOverlayElement(const String& name) - : OverlayContainer(name) - , mTransparent(false) - // Defer creation of texcoord buffer until we know how big it needs to be - , mNumTexCoordsInBuffer(0) - , mU1(0.0) - , mV1(0.0) - , mU2(1.0) - , mV2(1.0) - - { - // Init tiling - for (ushort i = 0; i < OGRE_MAX_TEXTURE_COORD_SETS; ++i) - { - mTileX[i] = 1.0f; - mTileY[i] = 1.0f; - } - - // No normals or colours - if (createParamDictionary("PanelOverlayElement")) - { - addBaseParameters(); - } - - } - //--------------------------------------------------------------------- - PanelOverlayElement::~PanelOverlayElement() - { - OGRE_DELETE mRenderOp.vertexData; - } - //--------------------------------------------------------------------- - void PanelOverlayElement::initialise(void) - { - bool init = !mInitialised; - - OverlayContainer::initialise(); - if (init) - { - // Setup render op in advance - mRenderOp.vertexData = OGRE_NEW VertexData(); - // Vertex declaration: 1 position, add texcoords later depending on #layers - // Create as separate buffers so we can lock & discard separately - VertexDeclaration* decl = mRenderOp.vertexData->vertexDeclaration; - decl->addElement(POSITION_BINDING, 0, VET_FLOAT3, VES_POSITION); - - // Basic vertex data - mRenderOp.vertexData->vertexStart = 0; - mRenderOp.vertexData->vertexCount = 4; - // No indexes & issue as a strip - mRenderOp.useIndexes = false; - mRenderOp.operationType = RenderOperation::OT_TRIANGLE_STRIP; - mRenderOp.useGlobalInstancing = false; - - mInitialised = true; - - _restoreManualHardwareResources(); - } - } - //--------------------------------------------------------------------- - void PanelOverlayElement::_restoreManualHardwareResources() - { - if(!mInitialised) - return; - - VertexDeclaration* decl = mRenderOp.vertexData->vertexDeclaration; - - // Vertex buffer #1 - HardwareVertexBufferSharedPtr vbuf = - HardwareBufferManager::getSingleton().createVertexBuffer( - decl->getVertexSize(POSITION_BINDING), mRenderOp.vertexData->vertexCount, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY,// mostly static except during resizing - true);//Workaround, using shadow buffer to avoid stall due to buffer mapping - // Bind buffer - mRenderOp.vertexData->vertexBufferBinding->setBinding(POSITION_BINDING, vbuf); - - // Buffers are restored, but with trash within - mGeomPositionsOutOfDate = true; - mGeomUVsOutOfDate = true; - } - //--------------------------------------------------------------------- - void PanelOverlayElement::_releaseManualHardwareResources() - { - if(!mInitialised) - return; - - VertexBufferBinding* bind = mRenderOp.vertexData->vertexBufferBinding; - if (bind->isBufferBound(POSITION_BINDING)) - bind->unsetBinding(POSITION_BINDING); - - // Remove all texcoord element declarations - if(mNumTexCoordsInBuffer > 0) - { - if (bind->isBufferBound (TEXCOORD_BINDING)) - bind->unsetBinding(TEXCOORD_BINDING); - - VertexDeclaration* decl = mRenderOp.vertexData->vertexDeclaration; - for(size_t i = mNumTexCoordsInBuffer; i > 0; --i) - { - decl->removeElement(VES_TEXTURE_COORDINATES, - static_cast(i - 1)); - } - mNumTexCoordsInBuffer = 0; - } - } - //--------------------------------------------------------------------- - void PanelOverlayElement::setTiling(Real x, Real y, ushort layer) - { - OgreAssert (layer < OGRE_MAX_TEXTURE_COORD_SETS, "out of bounds"); - OgreAssert (x != 0 && y != 0, "tile number must be > 0"); - - mTileX[layer] = x; - mTileY[layer] = y; - - mGeomUVsOutOfDate = true; - - } - //--------------------------------------------------------------------- - Real PanelOverlayElement::getTileX(ushort layer) const - { - return mTileX[layer]; - } - //--------------------------------------------------------------------- - Real PanelOverlayElement::getTileY(ushort layer) const - { - return mTileY[layer]; - } - //--------------------------------------------------------------------- - void PanelOverlayElement::setTransparent(bool inTransparent) - { - mTransparent = inTransparent; - } - //--------------------------------------------------------------------- - bool PanelOverlayElement::isTransparent(void) const - { - return mTransparent; - } - //--------------------------------------------------------------------- - void PanelOverlayElement::setUV(Real u1, Real v1, Real u2, Real v2) - { - mU1 = u1; - mU2 = u2; - mV1 = v1; - mV2 = v2; - mGeomUVsOutOfDate = true; - } - void PanelOverlayElement::getUV(Real& u1, Real& v1, Real& u2, Real& v2) const - { - u1 = mU1; - u2 = mU2; - v1 = mV1; - v2 = mV2; - } - //--------------------------------------------------------------------- - const String& PanelOverlayElement::getTypeName(void) const - { - return msTypeName; - } - //--------------------------------------------------------------------- - void PanelOverlayElement::getRenderOperation(RenderOperation& op) - { - op = mRenderOp; - } - //--------------------------------------------------------------------- - void PanelOverlayElement::_updateRenderQueue(RenderQueue* queue) - { - if (mVisible) - { - - if (!mTransparent && mMaterial) - { - OverlayElement::_updateRenderQueue(queue); - } - - // Also add children - for (const auto& p : getChildren()) - { - // Give children Z-order 1 higher than this - p.second->_updateRenderQueue(queue); - } - } - } - //--------------------------------------------------------------------- - void PanelOverlayElement::updatePositionGeometry(void) - { - /* - 0-----2 - | /| - | / | - |/ | - 1-----3 - */ - Real left, right, top, bottom; - - /* Convert positions into -1, 1 coordinate space (homogenous clip space). - - Left / right is simple range conversion - - Top / bottom also need inverting since y is upside down - this means - that top will end up greater than bottom and when computing texture - coordinates, we have to flip the v-axis (ie. subtract the value from - 1.0 to get the actual correct value). - */ - left = _getDerivedLeft() * 2 - 1; - right = left + (mWidth * 2); - top = -((_getDerivedTop() * 2) - 1); - bottom = top - (mHeight * 2); - - HardwareVertexBufferSharedPtr vbuf = - mRenderOp.vertexData->vertexBufferBinding->getBuffer(POSITION_BINDING); - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - float* pPos = static_cast(vbufLock.pData); - - // Use the furthest away depth value, since materials should have depth-check off - // This initialised the depth buffer for any 3D objects in front - Real zValue = Root::getSingleton().getRenderSystem()->getMaximumDepthInputValue(); - *pPos++ = left; - *pPos++ = top; - *pPos++ = zValue; - - *pPos++ = left; - *pPos++ = bottom; - *pPos++ = zValue; - - *pPos++ = right; - *pPos++ = top; - *pPos++ = zValue; - - *pPos++ = right; - *pPos++ = bottom; - *pPos++ = zValue; - } - //--------------------------------------------------------------------- - void PanelOverlayElement::updateTextureGeometry(void) - { - // Generate for as many texture layers as there are in material - if (mMaterial && mInitialised) - { - // Assume one technique and pass for the moment - size_t numLayers = mMaterial->getTechnique(0)->getPass(0)->getNumTextureUnitStates(); - - VertexDeclaration* decl = mRenderOp.vertexData->vertexDeclaration; - // Check the number of texcoords we have in our buffer now - if (mNumTexCoordsInBuffer > numLayers) - { - // remove extras - for (size_t i = mNumTexCoordsInBuffer; i > numLayers; --i) - { - decl->removeElement(VES_TEXTURE_COORDINATES, - static_cast(i - 1)); - } - } - else if (mNumTexCoordsInBuffer < numLayers) - { - // Add extra texcoord elements - size_t offset = VertexElement::getTypeSize(VET_FLOAT2) * mNumTexCoordsInBuffer; - for (size_t i = mNumTexCoordsInBuffer; i < numLayers; ++i) - { - offset += decl->addElement(TEXCOORD_BINDING, offset, VET_FLOAT2, - VES_TEXTURE_COORDINATES, ushort(i)) - .getSize(); - } - } - - // if number of layers changed at all, we'll need to reallocate buffer - if (mNumTexCoordsInBuffer != numLayers) - { - // NB reference counting will take care of the old one if it exists - HardwareVertexBufferSharedPtr newbuf = - HardwareBufferManager::getSingleton().createVertexBuffer( - decl->getVertexSize(TEXCOORD_BINDING), mRenderOp.vertexData->vertexCount, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY, // mostly static except during resizing - true);//Workaround, using shadow buffer to avoid stall due to buffer mapping - // Bind buffer, note this will unbind the old one and destroy the buffer it had - mRenderOp.vertexData->vertexBufferBinding->setBinding(TEXCOORD_BINDING, newbuf); - // Set num tex coords in use now - mNumTexCoordsInBuffer = numLayers; - } - - // Get the tcoord buffer & lock - if (mNumTexCoordsInBuffer) - { - HardwareVertexBufferSharedPtr vbuf = - mRenderOp.vertexData->vertexBufferBinding->getBuffer(TEXCOORD_BINDING); - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - float* pVBStart = static_cast(vbufLock.pData); - - size_t uvSize = VertexElement::getTypeSize(VET_FLOAT2) / sizeof(float); - size_t vertexSize = decl->getVertexSize(TEXCOORD_BINDING) / sizeof(float); - for (ushort i = 0; i < numLayers; ++i) - { - // Calc upper tex coords - Real upperX = mU2 * mTileX[i]; - Real upperY = mV2 * mTileY[i]; - - - /* - 0-----2 - | /| - | / | - |/ | - 1-----3 - */ - // Find start offset for this set - float* pTex = pVBStart + (i * uvSize); - - pTex[0] = mU1; - pTex[1] = mV1; - - pTex += vertexSize; // jump by 1 vertex stride - pTex[0] = mU1; - pTex[1] = upperY; - - pTex += vertexSize; - pTex[0] = upperX; - pTex[1] = mV1; - - pTex += vertexSize; - pTex[0] = upperX; - pTex[1] = upperY; - } - } - } - } - //----------------------------------------------------------------------- - void PanelOverlayElement::addBaseParameters(void) - { - OverlayContainer::addBaseParameters(); - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter(ParameterDef("uv_coords", - "The texture coordinates for the texture. 1 set of uv values." - , PT_STRING), - &msCmdUVCoords); - - dict->addParameter(ParameterDef("tiling", - "The number of times to repeat the background texture." - , PT_STRING), - &msCmdTiling); - - dict->addParameter(ParameterDef("transparent", - "Sets whether the panel is transparent, i.e. invisible itself " - "but it's contents are still displayed." - , PT_BOOL), - &msCmdTransparent); - } - //----------------------------------------------------------------------- - // Command objects - //----------------------------------------------------------------------- - String CmdTiling::doGet(const void* target) const - { - // NB only returns 1st layer tiling - String ret = "0 " + StringConverter::toString( - static_cast(target)->getTileX() ); - ret += " " + StringConverter::toString( - static_cast(target)->getTileY() ); - return ret; - } - void CmdTiling::doSet(void* target, const String& val) - { - // 3 params: - // Param count is validated higher up - std::vector vec = StringUtil::split(val); - ushort layer = (ushort)StringConverter::parseUnsignedInt(vec[0]); - Real x_tile = StringConverter::parseReal(vec[1]); - Real y_tile = StringConverter::parseReal(vec[2]); - - static_cast(target)->setTiling(x_tile, y_tile, layer); - } - //----------------------------------------------------------------------- - String CmdTransparent::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->isTransparent() ); - } - void CmdTransparent::doSet(void* target, const String& val) - { - static_cast(target)->setTransparent( - StringConverter::parseBool(val)); - } - //----------------------------------------------------------------------- - String CmdUVCoords::doGet(const void* target) const - { - Real u1, v1, u2, v2; - - static_cast(target)->getUV(u1, v1, u2, v2); - String ret = " " + StringConverter::toString(u1) + " " - + StringConverter::toString(v1) + " " + StringConverter::toString(u2) + " " - + StringConverter::toString(v2); - - return ret; - } - void CmdUVCoords::doSet(void* target, const String& val) - { - std::vector vec = StringUtil::split(val); - - static_cast(target)->setUV( - StringConverter::parseReal(vec[0]), - StringConverter::parseReal(vec[1]), - StringConverter::parseReal(vec[2]), - StringConverter::parseReal(vec[3]) - ); - } - -} - - - diff --git a/Components/Overlay/src/OgreTextAreaOverlayElement.cpp b/Components/Overlay/src/OgreTextAreaOverlayElement.cpp deleted file mode 100644 index 09f199a05cb..00000000000 --- a/Components/Overlay/src/OgreTextAreaOverlayElement.cpp +++ /dev/null @@ -1,820 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ - -#include "OgreTextAreaOverlayElement.h" -#include "OgreRoot.h" -#include "OgreLogManager.h" -#include "OgreOverlayManager.h" -#include "OgreHardwareBufferManager.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreException.h" -#include "OgreStringConverter.h" -#include "OgreFont.h" -#include "OgreFontManager.h" -#include "OgreOverlayElement.h" - -namespace Ogre { - -#define DEFAULT_INITIAL_CHARS 12 - //--------------------------------------------------------------------- - String TextAreaOverlayElement::msTypeName = "TextArea"; - //----------------------------------------------------------------------------------------- - class _OgrePrivate CmdCaption : public ParamCommand - { - public: - String doGet( const void* target ) const override; - void doSet( void* target, const String& val ) override; - }; - class _OgrePrivate CmdCharHeight : public ParamCommand - { - public: - String doGet( const void* target ) const override; - void doSet( void* target, const String& val ) override; - }; - class _OgrePrivate CmdSpaceWidth : public ParamCommand - { - public: - String doGet( const void* target ) const override; - void doSet( void* target, const String& val ) override; - }; - class _OgrePrivate CmdFontName : public ParamCommand - { - public: - String doGet( const void* target ) const override; - void doSet( void* target, const String& val ) override; - }; - class _OgrePrivate CmdColourTop : public ParamCommand - { - public: - String doGet( const void* target ) const override; - void doSet( void* target, const String& val ) override; - }; - class _OgrePrivate CmdColourBottom : public ParamCommand - { - public: - String doGet( const void* target ) const override; - void doSet( void* target, const String& val ) override; - }; - class _OgrePrivate CmdColour : public ParamCommand - { - public: - String doGet( const void* target ) const override; - void doSet( void* target, const String& val ) override; - }; - class _OgrePrivate CmdAlignment : public ParamCommand - { - public: - String doGet( const void* target ) const override; - void doSet( void* target, const String& val ) override; - }; - // Command objects - static CmdCharHeight msCmdCharHeight; - static CmdSpaceWidth msCmdSpaceWidth; - static CmdFontName msCmdFontName; - static CmdColour msCmdColour; - static CmdColourTop msCmdColourTop; - static CmdColourBottom msCmdColourBottom; - static CmdAlignment msCmdAlignment; - //--------------------------------------------------------------------- - #define POS_TEX_BINDING 0 - #define COLOUR_BINDING 1 - #define UNICODE_NEL 0x0085 - #define UNICODE_CR 0x000D - #define UNICODE_LF 0x000A - #define UNICODE_SPACE 0x0020 - //--------------------------------------------------------------------- - TextAreaOverlayElement::TextAreaOverlayElement(const String& name) - : OverlayElement(name), mColourBottom(ColourValue::White), mColourTop(ColourValue::White) - { - mTransparent = false; - mAlignment = Left; - - mColoursChanged = true; - - mAllocSize = 0; - - mCharHeight = 0.02; - mPixelCharHeight = 12; - mSpaceWidth = 0; - mPixelSpaceWidth = 0; - mViewportAspectCoef = 1; - - if (createParamDictionary("TextAreaOverlayElement")) - { - addBaseParameters(); - } - } - - void TextAreaOverlayElement::initialise(void) - { - if (!mInitialised) - { - // Set up the render op - // Combine positions and texture coords since they tend to change together - // since character sizes are different - mRenderOp.vertexData = OGRE_NEW VertexData(); - VertexDeclaration* decl = mRenderOp.vertexData->vertexDeclaration; - size_t offset = 0; - // Positions - offset += decl->addElement(POS_TEX_BINDING, offset, VET_FLOAT3, VES_POSITION).getSize(); - // Texcoords - decl->addElement(POS_TEX_BINDING, offset, VET_FLOAT2, VES_TEXTURE_COORDINATES, 0); - // Colours - store these in a separate buffer because they change less often - decl->addElement(COLOUR_BINDING, 0, VET_UBYTE4_NORM, VES_DIFFUSE); - - mRenderOp.operationType = RenderOperation::OT_TRIANGLE_LIST; - mRenderOp.useIndexes = false; - mRenderOp.vertexData->vertexStart = 0; - mRenderOp.useGlobalInstancing = false; - // Vertex buffer will be created in checkMemoryAllocation - - mInitialised = true; - - checkMemoryAllocation( DEFAULT_INITIAL_CHARS ); - } - - } - //--------------------------------------------------------------------- - void TextAreaOverlayElement::checkMemoryAllocation( size_t numChars ) - { - if( mAllocSize < numChars) - { - mAllocSize = numChars; - - // Create and bind new buffers - // Note that old buffers will be deleted automatically through reference counting - _restoreManualHardwareResources(); - } - } - //--------------------------------------------------------------------- - void TextAreaOverlayElement::_restoreManualHardwareResources() - { - if(!mInitialised) - return; - - // 6 verts per char since we're doing tri lists without indexes - // Allocate space for positions & texture coords - // Note - mRenderOp.vertexData->vertexCount will be less than allocatedVertexCount - size_t allocatedVertexCount = mAllocSize * 6; - VertexDeclaration* decl = mRenderOp.vertexData->vertexDeclaration; - VertexBufferBinding* bind = mRenderOp.vertexData->vertexBufferBinding; - - // Create dynamic since text tends to change a lot - // positions & texcoords - HardwareVertexBufferSharedPtr vbuf = - HardwareBufferManager::getSingleton(). - createVertexBuffer( - decl->getVertexSize(POS_TEX_BINDING), - allocatedVertexCount, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY, - true);//Workaround, using shadow buffer to avoid stall due to buffer mapping - bind->setBinding(POS_TEX_BINDING, vbuf); - - // colours - vbuf = HardwareBufferManager::getSingleton(). - createVertexBuffer( - decl->getVertexSize(COLOUR_BINDING), - allocatedVertexCount, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY, - true);//Workaround, using shadow buffer to avoid stall due to buffer mapping - bind->setBinding(COLOUR_BINDING, vbuf); - - // Buffers are restored, but with trash within - mGeomPositionsOutOfDate = true; - mGeomUVsOutOfDate = true; - mColoursChanged = true; - } - //--------------------------------------------------------------------- - void TextAreaOverlayElement::_releaseManualHardwareResources() - { - if(!mInitialised) - return; - - VertexBufferBinding* bind = mRenderOp.vertexData->vertexBufferBinding; - bind->unsetAllBindings(); - } - //--------------------------------------------------------------------- - - void TextAreaOverlayElement::updatePositionGeometry() - { - float *pVert; - - if (!mFont) - { - // not initialised yet, probably due to the order of creation in a template - return; - } - - mFont->load(); // ensure glyph info is there - - auto decoded = utftoc32(mCaption); - size_t charlen = decoded.size(); - checkMemoryAllocation( charlen ); - - mRenderOp.vertexData->vertexCount = charlen * 6; - // Get position / texcoord buffer - const HardwareVertexBufferSharedPtr& vbuf = - mRenderOp.vertexData->vertexBufferBinding->getBuffer(POS_TEX_BINDING); - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - pVert = static_cast(vbufLock.pData); - - float largestWidth = 0; - float left = _getDerivedLeft() * 2.0f - 1.0f; - float top = -( (_getDerivedTop() * 2.0f ) - 1.0f ); - - // Use iterator - auto iend = decoded.end(); - bool newLine = true; - for( auto i = decoded.begin(); i != iend; ++i ) - { - if( newLine ) - { - Real len = 0.0f; - for( auto j = i; j != iend; j++ ) - { - Font::CodePoint character = *j; - if (character == UNICODE_CR - || character == UNICODE_NEL - || character == UNICODE_LF) - { - break; - } - else if (character == UNICODE_SPACE && mSpaceWidth) // space - { - len += mSpaceWidth * 2.0f * mViewportAspectCoef; - } - else - { - len += mFont->getGlyphInfo(character).advance * mCharHeight * 2.0f * mViewportAspectCoef; - } - } - - if( mAlignment == Right ) - left -= len; - else if( mAlignment == Center ) - left -= len * 0.5f; - - newLine = false; - } - - Font::CodePoint character = *i; - if (character == UNICODE_CR - || character == UNICODE_NEL - || character == UNICODE_LF) - { - left = _getDerivedLeft() * 2.0f - 1.0f; - top -= mCharHeight * 2.0f; - newLine = true; - // Also reduce tri count - mRenderOp.vertexData->vertexCount -= 6; - - // consume CR/LF in one - if (character == UNICODE_CR) - { - auto peeki = i + 1; - if (peeki != iend && *peeki == UNICODE_LF) - { - i = peeki; // skip both as one newline - // Also reduce tri count - mRenderOp.vertexData->vertexCount -= 6; - } - - } - continue; - } - else if (character == UNICODE_SPACE && mSpaceWidth) // space - { - // Just leave a gap, no tris - left += mSpaceWidth * 2.0f * mViewportAspectCoef; - // Also reduce tri count - mRenderOp.vertexData->vertexCount -= 6; - continue; - } - - const auto& glyphInfo = mFont->getGlyphInfo(character); - Real horiz_height = glyphInfo.aspectRatio * mViewportAspectCoef ; - const Font::UVRect& uvRect = glyphInfo.uvRect; - - if(uvRect.isNull()) - { - // Just leave a gap, no tris - left += glyphInfo.advance * mCharHeight * 2.0f * mViewportAspectCoef; - // Also reduce tri count - mRenderOp.vertexData->vertexCount -= 6; - continue; - } - - left += glyphInfo.bearing * mCharHeight * 2 * mViewportAspectCoef; - - // each vert is (x, y, z, u, v) - //------------------------------------------------------------------------------------- - // First tri - // - // Upper left - *pVert++ = left; - *pVert++ = top; - *pVert++ = -1.0; - *pVert++ = uvRect.left; - *pVert++ = uvRect.top; - - top -= mCharHeight * 2.0f; - - // Bottom left - *pVert++ = left; - *pVert++ = top; - *pVert++ = -1.0; - *pVert++ = uvRect.left; - *pVert++ = uvRect.bottom; - - top += mCharHeight * 2.0f; - left += horiz_height * mCharHeight * 2.0f; - - // Top right - *pVert++ = left; - *pVert++ = top; - *pVert++ = -1.0; - *pVert++ = uvRect.right; - *pVert++ = uvRect.top; - //------------------------------------------------------------------------------------- - - //------------------------------------------------------------------------------------- - // Second tri - // - // Top right (again) - *pVert++ = left; - *pVert++ = top; - *pVert++ = -1.0; - *pVert++ = uvRect.right; - *pVert++ = uvRect.top; - - top -= mCharHeight * 2.0f; - left -= horiz_height * mCharHeight * 2.0f; - - // Bottom left (again) - *pVert++ = left; - *pVert++ = top; - *pVert++ = -1.0; - *pVert++ = uvRect.left; - *pVert++ = uvRect.bottom; - - left += horiz_height * mCharHeight * 2.0f; - - // Bottom right - *pVert++ = left; - *pVert++ = top; - *pVert++ = -1.0; - *pVert++ = uvRect.right; - *pVert++ = uvRect.bottom; - //------------------------------------------------------------------------------------- - - // Go back up with top - top += mCharHeight * 2.0f; - - // advance - left -= horiz_height * mCharHeight * 2.0f; - left += (glyphInfo.advance - glyphInfo.bearing) * mCharHeight * 2.0f * mViewportAspectCoef; - - float currentWidth = (left + 1)/2 - _getDerivedLeft(); - if (currentWidth > largestWidth) - { - largestWidth = currentWidth; - - } - } - - if (mMetricsMode == GMM_PIXELS) - { - // Derive parametric version of dimensions - Real vpWidth; - vpWidth = (Real) (OverlayManager::getSingleton().getViewportWidth()); - - largestWidth *= vpWidth; - }; - - if (getWidth() < largestWidth) - setWidth(largestWidth); - } - - void TextAreaOverlayElement::updateTextureGeometry() - { - // Nothing to do, we combine positions and textures - } - - void TextAreaOverlayElement::setCaption( const DisplayString& caption ) - { - mCaption = caption; - mGeomPositionsOutOfDate = true; - mGeomUVsOutOfDate = true; - } - - void TextAreaOverlayElement::setFontName( const String& font, const String& group ) - { - mFont = FontManager::getSingleton().getByName(font, group); - if (!mFont) - OGRE_EXCEPT( Exception::ERR_ITEM_NOT_FOUND, "Could not find font " + font, - "TextAreaOverlayElement::setFontName" ); - mMaterial.reset(); - - mGeomPositionsOutOfDate = true; - mGeomUVsOutOfDate = true; - } - const String& TextAreaOverlayElement::getFontName() const - { - return mFont->getName(); - } - - void TextAreaOverlayElement::setCharHeight( Real height ) - { - if (mMetricsMode != GMM_RELATIVE) - { - mPixelCharHeight = static_cast(height); - } - else - { - mCharHeight = height; - } - mGeomPositionsOutOfDate = true; - } - Real TextAreaOverlayElement::getCharHeight() const - { - if (mMetricsMode == GMM_PIXELS) - { - return mPixelCharHeight; - } - else - { - return mCharHeight; - } - } - - void TextAreaOverlayElement::setSpaceWidth( Real width ) - { - if (mMetricsMode != GMM_RELATIVE) - { - mPixelSpaceWidth = static_cast(width); - } - else - { - mSpaceWidth = width; - } - - mGeomPositionsOutOfDate = true; - } - Real TextAreaOverlayElement::getSpaceWidth() const - { - if (mMetricsMode == GMM_PIXELS) - { - return mPixelSpaceWidth; - } - else - { - return mSpaceWidth; - } - } - - //--------------------------------------------------------------------- - TextAreaOverlayElement::~TextAreaOverlayElement() - { - OGRE_DELETE mRenderOp.vertexData; - } - //--------------------------------------------------------------------- - const String& TextAreaOverlayElement::getTypeName(void) const - { - return msTypeName; - } - //--------------------------------------------------------------------- - const MaterialPtr& TextAreaOverlayElement::getMaterial(void) const - { - // On-demand load - // Moved from setFontName to avoid issues with background parsing of scripts - if (!mMaterial && mFont) - { - mFont->load(); - // Ugly hack, but we need to override for lazy-load - *const_cast(&mMaterial) = mFont->getMaterial(); - mMaterial->setDepthCheckEnabled(false); - } - return mMaterial; - } - //--------------------------------------------------------------------- - void TextAreaOverlayElement::getRenderOperation(RenderOperation& op) - { - op = mRenderOp; - } - //--------------------------------------------------------------------- - void TextAreaOverlayElement::addBaseParameters(void) - { - OverlayElement::addBaseParameters(); - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter(ParameterDef("char_height", - "Sets the height of the characters in relation to the screen." - , PT_REAL), - &msCmdCharHeight); - - dict->addParameter(ParameterDef("space_width", - "Sets the width of a space in relation to the screen." - , PT_REAL), - &msCmdSpaceWidth); - - dict->addParameter(ParameterDef("font_name", - "Sets the name of the font to use." - , PT_STRING), - &msCmdFontName); - - dict->addParameter(ParameterDef("colour", - "Sets the colour of the font (a solid colour)." - , PT_STRING), - &msCmdColour); - - dict->addParameter(ParameterDef("colour_bottom", - "Sets the colour of the font at the bottom (a gradient colour)." - , PT_STRING), - &msCmdColourBottom); - - dict->addParameter(ParameterDef("colour_top", - "Sets the colour of the font at the top (a gradient colour)." - , PT_STRING), - &msCmdColourTop); - - dict->addParameter(ParameterDef("alignment", - "Sets the alignment of the text: 'left', 'center' or 'right'." - , PT_STRING), - &msCmdAlignment); - } - //--------------------------------------------------------------------- - void TextAreaOverlayElement::setColour(const ColourValue& col) - { - mColourBottom = mColourTop = col; - mColoursChanged = true; - } - //--------------------------------------------------------------------- - const ColourValue& TextAreaOverlayElement::getColour(void) const - { - // Either one - return mColourTop; - } - //--------------------------------------------------------------------- - void TextAreaOverlayElement::setColourBottom(const ColourValue& col) - { - mColourBottom = col; - mColoursChanged = true; - } - //--------------------------------------------------------------------- - const ColourValue& TextAreaOverlayElement::getColourBottom(void) const - { - return mColourBottom; - } - //--------------------------------------------------------------------- - void TextAreaOverlayElement::setColourTop(const ColourValue& col) - { - mColourTop = col; - mColoursChanged = true; - } - //--------------------------------------------------------------------- - const ColourValue& TextAreaOverlayElement::getColourTop(void) const - { - return mColourTop; - } - //--------------------------------------------------------------------- - void TextAreaOverlayElement::updateColours(void) - { - // Convert to system-specific - RGBA topColour = mColourTop.getAsBYTE(); - RGBA bottomColour = mColourBottom.getAsBYTE(); - - HardwareVertexBufferSharedPtr vbuf = - mRenderOp.vertexData->vertexBufferBinding->getBuffer(COLOUR_BINDING); - - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - RGBA* pDest = static_cast(vbufLock.pData); - - for (size_t i = 0; i < mAllocSize; ++i) - { - // First tri (top, bottom, top) - *pDest++ = topColour; - *pDest++ = bottomColour; - *pDest++ = topColour; - // Second tri (top, bottom, bottom) - *pDest++ = topColour; - *pDest++ = bottomColour; - *pDest++ = bottomColour; - } - } - //----------------------------------------------------------------------- - void TextAreaOverlayElement::setMetricsMode(GuiMetricsMode gmm) - { - Real vpWidth, vpHeight; - vpWidth = (Real) (OverlayManager::getSingleton().getViewportWidth()); - vpHeight = (Real) (OverlayManager::getSingleton().getViewportHeight()); - - mViewportAspectCoef = vpHeight/vpWidth; - - OverlayElement::setMetricsMode(gmm); - - switch (mMetricsMode) - { - case GMM_PIXELS: - // set pixel variables based on viewport multipliers - mPixelCharHeight = static_cast(mCharHeight * vpHeight); - mPixelSpaceWidth = static_cast(mSpaceWidth * vpHeight); - break; - - case GMM_RELATIVE_ASPECT_ADJUSTED: - // set pixel variables multiplied by the height constant - mPixelCharHeight = static_cast(mCharHeight * 10000.0); - mPixelSpaceWidth = static_cast(mSpaceWidth * 10000.0); - break; - - default: - break; - } - } - //----------------------------------------------------------------------- - void TextAreaOverlayElement::_update(void) - { - Real vpWidth, vpHeight; - vpWidth = (Real) (OverlayManager::getSingleton().getViewportWidth()); - vpHeight = (Real) (OverlayManager::getSingleton().getViewportHeight()); - - mViewportAspectCoef = vpHeight/vpWidth; - - // Check size if pixel-based / relative-aspect-adjusted - switch (mMetricsMode) - { - case GMM_PIXELS: - if(mGeomPositionsOutOfDate) - { - // recalculate character size - mCharHeight = (Real) mPixelCharHeight / vpHeight; - mSpaceWidth = (Real) mPixelSpaceWidth / vpHeight; - mGeomPositionsOutOfDate = true; - } - break; - - case GMM_RELATIVE_ASPECT_ADJUSTED: - if(mGeomPositionsOutOfDate) - { - // recalculate character size - mCharHeight = (Real) mPixelCharHeight / 10000.0f; - mSpaceWidth = (Real) mPixelSpaceWidth / 10000.0f; - mGeomPositionsOutOfDate = true; - } - break; - - default: - break; - } - - OverlayElement::_update(); - - if (mColoursChanged && mInitialised) - { - updateColours(); - mColoursChanged = false; - } - } - //--------------------------------------------------------------------------------------------- - // Char height command object - // - String CmdCharHeight::doGet( const void* target ) const - { - return StringConverter::toString( - static_cast< const TextAreaOverlayElement* >( target )->getCharHeight() ); - } - void CmdCharHeight::doSet( void* target, const String& val ) - { - static_cast< TextAreaOverlayElement* >( target )->setCharHeight( - StringConverter::parseReal( val ) ); - } - //--------------------------------------------------------------------------------------------- - // Space width command object - // - String CmdSpaceWidth::doGet( const void* target ) const - { - return StringConverter::toString( - static_cast< const TextAreaOverlayElement* >( target )->getSpaceWidth() ); - } - void CmdSpaceWidth::doSet( void* target, const String& val ) - { - static_cast< TextAreaOverlayElement* >( target )->setSpaceWidth( - StringConverter::parseReal( val ) ); - } - //--------------------------------------------------------------------------------------------- - - //--------------------------------------------------------------------------------------------- - // Font name command object - // - String CmdFontName::doGet( const void* target ) const - { - return static_cast< const TextAreaOverlayElement* >( target )->getFont()->getName(); - } - void CmdFontName::doSet( void* target, const String& val ) - { - static_cast< TextAreaOverlayElement* >( target )->setFontName( val ); - } - //--------------------------------------------------------------------------------------------- - //--------------------------------------------------------------------------------------------- - // Colour command object - // - String CmdColour::doGet( const void* target ) const - { - return StringConverter::toString ( - static_cast< const TextAreaOverlayElement* >( target )->getColour()); - } - void CmdColour::doSet( void* target, const String& val ) - { - static_cast< TextAreaOverlayElement* >( target )->setColour( - StringConverter::parseColourValue(val) ); - } - //--------------------------------------------------------------------------------------------- - //--------------------------------------------------------------------------------------------- - //--------------------------------------------------------------------------------------------- - // Top colour command object - // - String CmdColourTop::doGet( const void* target ) const - { - return StringConverter::toString ( - static_cast< const TextAreaOverlayElement* >( target )->getColourTop()); - } - void CmdColourTop::doSet( void* target, const String& val ) - { - static_cast< TextAreaOverlayElement* >( target )->setColourTop( - StringConverter::parseColourValue(val) ); - } - //--------------------------------------------------------------------------------------------- - //--------------------------------------------------------------------------------------------- - //--------------------------------------------------------------------------------------------- - // Bottom colour command object - // - String CmdColourBottom::doGet( const void* target ) const - { - return StringConverter::toString ( - static_cast< const TextAreaOverlayElement* >( target )->getColourBottom()); - } - void CmdColourBottom::doSet( void* target, const String& val ) - { - static_cast< TextAreaOverlayElement* >( target )->setColourBottom( - StringConverter::parseColourValue(val) ); - } - //--------------------------------------------------------------------------------------------- - //--------------------------------------------------------------------------------------------- - //--------------------------------------------------------------------------------------------- - // Alignment command object - // - String CmdAlignment::doGet( const void* target ) const - { - TextAreaOverlayElement::Alignment align = static_cast< const TextAreaOverlayElement* >( target )->getAlignment(); - switch (align) - { - case TextAreaOverlayElement::Left: - return "left"; - case TextAreaOverlayElement::Center: - return "center"; - case TextAreaOverlayElement::Right: - return "right"; - - } - // To keep compiler happy - return "left"; - } - void CmdAlignment::doSet( void* target, const String& val ) - { - if (val == "center") - { - static_cast< TextAreaOverlayElement* >( target )->setAlignment(TextAreaOverlayElement::Center); - } - else if (val == "right") - { - static_cast< TextAreaOverlayElement* >( target )->setAlignment(TextAreaOverlayElement::Right); - } - else - { - static_cast< TextAreaOverlayElement* >( target )->setAlignment(TextAreaOverlayElement::Left); - } - } - //--------------------------------------------------------------------------------------------- -} diff --git a/Components/Overlay/src/stb_truetype.h b/Components/Overlay/src/stb_truetype.h deleted file mode 100644 index bbf2284b164..00000000000 --- a/Components/Overlay/src/stb_truetype.h +++ /dev/null @@ -1,5077 +0,0 @@ -// stb_truetype.h - v1.26 - public domain -// authored from 2009-2021 by Sean Barrett / RAD Game Tools -// -// ======================================================================= -// -// NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES -// -// This library does no range checking of the offsets found in the file, -// meaning an attacker can use it to read arbitrary memory. -// -// ======================================================================= -// -// This library processes TrueType files: -// parse files -// extract glyph metrics -// extract glyph shapes -// render glyphs to one-channel bitmaps with antialiasing (box filter) -// render glyphs to one-channel SDF bitmaps (signed-distance field/function) -// -// Todo: -// non-MS cmaps -// crashproof on bad data -// hinting? (no longer patented) -// cleartype-style AA? -// optimize: use simple memory allocator for intermediates -// optimize: build edge-list directly from curves -// optimize: rasterize directly from curves? -// -// ADDITIONAL CONTRIBUTORS -// -// Mikko Mononen: compound shape support, more cmap formats -// Tor Andersson: kerning, subpixel rendering -// Dougall Johnson: OpenType / Type 2 font handling -// Daniel Ribeiro Maciel: basic GPOS-based kerning -// -// Misc other: -// Ryan Gordon -// Simon Glass -// github:IntellectualKitty -// Imanol Celaya -// Daniel Ribeiro Maciel -// -// Bug/warning reports/fixes: -// "Zer" on mollyrocket Fabian "ryg" Giesen github:NiLuJe -// Cass Everitt Martins Mozeiko github:aloucks -// stoiko (Haemimont Games) Cap Petschulat github:oyvindjam -// Brian Hook Omar Cornut github:vassvik -// Walter van Niftrik Ryan Griege -// David Gow Peter LaValle -// David Given Sergey Popov -// Ivan-Assen Ivanov Giumo X. Clanjor -// Anthony Pesch Higor Euripedes -// Johan Duparc Thomas Fields -// Hou Qiming Derek Vinyard -// Rob Loach Cort Stratton -// Kenney Phillis Jr. Brian Costabile -// Ken Voskuil (kaesve) -// -// VERSION HISTORY -// -// 1.26 (2021-08-28) fix broken rasterizer -// 1.25 (2021-07-11) many fixes -// 1.24 (2020-02-05) fix warning -// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) -// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined -// 1.21 (2019-02-25) fix warning -// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() -// 1.19 (2018-02-11) GPOS kerning, STBTT_fmod -// 1.18 (2018-01-29) add missing function -// 1.17 (2017-07-23) make more arguments const; doc fix -// 1.16 (2017-07-12) SDF support -// 1.15 (2017-03-03) make more arguments const -// 1.14 (2017-01-16) num-fonts-in-TTC function -// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts -// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual -// 1.11 (2016-04-02) fix unused-variable warning -// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef -// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly -// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges -// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; -// variant PackFontRanges to pack and render in separate phases; -// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); -// fixed an assert() bug in the new rasterizer -// replace assert() with STBTT_assert() in new rasterizer -// -// Full history can be found at the end of this file. -// -// LICENSE -// -// See end of file for license information. -// -// USAGE -// -// Include this file in whatever places need to refer to it. In ONE C/C++ -// file, write: -// #define STB_TRUETYPE_IMPLEMENTATION -// before the #include of this file. This expands out the actual -// implementation into that C/C++ file. -// -// To make the implementation private to the file that generates the implementation, -// #define STBTT_STATIC -// -// Simple 3D API (don't ship this, but it's fine for tools and quick start) -// stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture -// stbtt_GetBakedQuad() -- compute quad to draw for a given char -// -// Improved 3D API (more shippable): -// #include "stb_rect_pack.h" -- optional, but you really want it -// stbtt_PackBegin() -// stbtt_PackSetOversampling() -- for improved quality on small fonts -// stbtt_PackFontRanges() -- pack and renders -// stbtt_PackEnd() -// stbtt_GetPackedQuad() -// -// "Load" a font file from a memory buffer (you have to keep the buffer loaded) -// stbtt_InitFont() -// stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections -// stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections -// -// Render a unicode codepoint to a bitmap -// stbtt_GetCodepointBitmap() -- allocates and returns a bitmap -// stbtt_MakeCodepointBitmap() -- renders into bitmap you provide -// stbtt_GetCodepointBitmapBox() -- how big the bitmap must be -// -// Character advance/positioning -// stbtt_GetCodepointHMetrics() -// stbtt_GetFontVMetrics() -// stbtt_GetFontVMetricsOS2() -// stbtt_GetCodepointKernAdvance() -// -// Starting with version 1.06, the rasterizer was replaced with a new, -// faster and generally-more-precise rasterizer. The new rasterizer more -// accurately measures pixel coverage for anti-aliasing, except in the case -// where multiple shapes overlap, in which case it overestimates the AA pixel -// coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If -// this turns out to be a problem, you can re-enable the old rasterizer with -// #define STBTT_RASTERIZER_VERSION 1 -// which will incur about a 15% speed hit. -// -// ADDITIONAL DOCUMENTATION -// -// Immediately after this block comment are a series of sample programs. -// -// After the sample programs is the "header file" section. This section -// includes documentation for each API function. -// -// Some important concepts to understand to use this library: -// -// Codepoint -// Characters are defined by unicode codepoints, e.g. 65 is -// uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is -// the hiragana for "ma". -// -// Glyph -// A visual character shape (every codepoint is rendered as -// some glyph) -// -// Glyph index -// A font-specific integer ID representing a glyph -// -// Baseline -// Glyph shapes are defined relative to a baseline, which is the -// bottom of uppercase characters. Characters extend both above -// and below the baseline. -// -// Current Point -// As you draw text to the screen, you keep track of a "current point" -// which is the origin of each character. The current point's vertical -// position is the baseline. Even "baked fonts" use this model. -// -// Vertical Font Metrics -// The vertical qualities of the font, used to vertically position -// and space the characters. See docs for stbtt_GetFontVMetrics. -// -// Font Size in Pixels or Points -// The preferred interface for specifying font sizes in stb_truetype -// is to specify how tall the font's vertical extent should be in pixels. -// If that sounds good enough, skip the next paragraph. -// -// Most font APIs instead use "points", which are a common typographic -// measurement for describing font size, defined as 72 points per inch. -// stb_truetype provides a point API for compatibility. However, true -// "per inch" conventions don't make much sense on computer displays -// since different monitors have different number of pixels per -// inch. For example, Windows traditionally uses a convention that -// there are 96 pixels per inch, thus making 'inch' measurements have -// nothing to do with inches, and thus effectively defining a point to -// be 1.333 pixels. Additionally, the TrueType font data provides -// an explicit scale factor to scale a given font's glyphs to points, -// but the author has observed that this scale factor is often wrong -// for non-commercial fonts, thus making fonts scaled in points -// according to the TrueType spec incoherently sized in practice. -// -// DETAILED USAGE: -// -// Scale: -// Select how high you want the font to be, in points or pixels. -// Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute -// a scale factor SF that will be used by all other functions. -// -// Baseline: -// You need to select a y-coordinate that is the baseline of where -// your text will appear. Call GetFontBoundingBox to get the baseline-relative -// bounding box for all characters. SF*-y0 will be the distance in pixels -// that the worst-case character could extend above the baseline, so if -// you want the top edge of characters to appear at the top of the -// screen where y=0, then you would set the baseline to SF*-y0. -// -// Current point: -// Set the current point where the first character will appear. The -// first character could extend left of the current point; this is font -// dependent. You can either choose a current point that is the leftmost -// point and hope, or add some padding, or check the bounding box or -// left-side-bearing of the first character to be displayed and set -// the current point based on that. -// -// Displaying a character: -// Compute the bounding box of the character. It will contain signed values -// relative to . I.e. if it returns x0,y0,x1,y1, -// then the character should be displayed in the rectangle from -// to = 32 && *text < 128) { - stbtt_aligned_quad q; - stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9 - glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y0); - glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y0); - glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y1); - glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y1); - } - ++text; - } - glEnd(); -} -#endif -// -// -////////////////////////////////////////////////////////////////////////////// -// -// Complete program (this compiles): get a single bitmap, print as ASCII art -// -#if 0 -#include -#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation -#include "stb_truetype.h" - -char ttf_buffer[1<<25]; - -int main(int argc, char **argv) -{ - stbtt_fontinfo font; - unsigned char *bitmap; - int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20); - - fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); - - stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); - bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); - - for (j=0; j < h; ++j) { - for (i=0; i < w; ++i) - putchar(" .:ioVM@"[bitmap[j*w+i]>>5]); - putchar('\n'); - } - return 0; -} -#endif -// -// Output: -// -// .ii. -// @@@@@@. -// V@Mio@@o -// :i. V@V -// :oM@@M -// :@@@MM@M -// @@o o@M -// :@@. M@M -// @@@o@@@@ -// :M@@V:@@. -// -////////////////////////////////////////////////////////////////////////////// -// -// Complete program: print "Hello World!" banner, with bugs -// -#if 0 -char buffer[24<<20]; -unsigned char screen[20][79]; - -int main(int arg, char **argv) -{ - stbtt_fontinfo font; - int i,j,ascent,baseline,ch=0; - float scale, xpos=2; // leave a little padding in case the character extends left - char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness - - fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb")); - stbtt_InitFont(&font, buffer, 0); - - scale = stbtt_ScaleForPixelHeight(&font, 15); - stbtt_GetFontVMetrics(&font, &ascent,0,0); - baseline = (int) (ascent*scale); - - while (text[ch]) { - int advance,lsb,x0,y0,x1,y1; - float x_shift = xpos - (float) floor(xpos); - stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb); - stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1); - stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]); - // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong - // because this API is really for baking character bitmaps into textures. if you want to render - // a sequence of characters, you really need to render each bitmap to a temp buffer, then - // "alpha blend" that into the working buffer - xpos += (advance * scale); - if (text[ch+1]) - xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]); - ++ch; - } - - for (j=0; j < 20; ++j) { - for (i=0; i < 78; ++i) - putchar(" .:ioVM@"[screen[j][i]>>5]); - putchar('\n'); - } - - return 0; -} -#endif - - -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// -//// -//// INTEGRATION WITH YOUR CODEBASE -//// -//// The following sections allow you to supply alternate definitions -//// of C library functions used by stb_truetype, e.g. if you don't -//// link with the C runtime library. - -#ifdef STB_TRUETYPE_IMPLEMENTATION - // #define your own (u)stbtt_int8/16/32 before including to override this - #ifndef stbtt_uint8 - typedef unsigned char stbtt_uint8; - typedef signed char stbtt_int8; - typedef unsigned short stbtt_uint16; - typedef signed short stbtt_int16; - typedef unsigned int stbtt_uint32; - typedef signed int stbtt_int32; - #endif - - typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1]; - typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1]; - - // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h - #ifndef STBTT_ifloor - #include - #define STBTT_ifloor(x) ((int) floor(x)) - #define STBTT_iceil(x) ((int) ceil(x)) - #endif - - #ifndef STBTT_sqrt - #include - #define STBTT_sqrt(x) sqrt(x) - #define STBTT_pow(x,y) pow(x,y) - #endif - - #ifndef STBTT_fmod - #include - #define STBTT_fmod(x,y) fmod(x,y) - #endif - - #ifndef STBTT_cos - #include - #define STBTT_cos(x) cos(x) - #define STBTT_acos(x) acos(x) - #endif - - #ifndef STBTT_fabs - #include - #define STBTT_fabs(x) fabs(x) - #endif - - // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h - #ifndef STBTT_malloc - #include - #define STBTT_malloc(x,u) ((void)(u),malloc(x)) - #define STBTT_free(x,u) ((void)(u),free(x)) - #endif - - #ifndef STBTT_assert - #include - #define STBTT_assert(x) assert(x) - #endif - - #ifndef STBTT_strlen - #include - #define STBTT_strlen(x) strlen(x) - #endif - - #ifndef STBTT_memcpy - #include - #define STBTT_memcpy memcpy - #define STBTT_memset memset - #endif -#endif - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -//// -//// INTERFACE -//// -//// - -#ifndef __STB_INCLUDE_STB_TRUETYPE_H__ -#define __STB_INCLUDE_STB_TRUETYPE_H__ - -#ifdef STBTT_STATIC -#define STBTT_DEF static -#else -#define STBTT_DEF extern -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -// private structure -typedef struct -{ - unsigned char *data; - int cursor; - int size; -} stbtt__buf; - -////////////////////////////////////////////////////////////////////////////// -// -// TEXTURE BAKING API -// -// If you use this API, you only have to call two functions ever. -// - -typedef struct -{ - unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap - float xoff,yoff,xadvance; -} stbtt_bakedchar; - -STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) - float pixel_height, // height of font in pixels - unsigned char *pixels, int pw, int ph, // bitmap to be filled in - int first_char, int num_chars, // characters to bake - stbtt_bakedchar *chardata); // you allocate this, it's num_chars long -// if return is positive, the first unused row of the bitmap -// if return is negative, returns the negative of the number of characters that fit -// if return is 0, no characters fit and no rows were used -// This uses a very crappy packing. - -typedef struct -{ - float x0,y0,s0,t0; // top-left - float x1,y1,s1,t1; // bottom-right -} stbtt_aligned_quad; - -STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above - int char_index, // character to display - float *xpos, float *ypos, // pointers to current position in screen pixel space - stbtt_aligned_quad *q, // output: quad to draw - int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier -// Call GetBakedQuad with char_index = 'character - first_char', and it -// creates the quad you need to draw and advances the current position. -// -// The coordinate system used assumes y increases downwards. -// -// Characters will extend both above and below the current position; -// see discussion of "BASELINE" above. -// -// It's inefficient; you might want to c&p it and optimize it. - -STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap); -// Query the font vertical metrics without having to create a font first. - - -////////////////////////////////////////////////////////////////////////////// -// -// NEW TEXTURE BAKING API -// -// This provides options for packing multiple fonts into one atlas, not -// perfectly but better than nothing. - -typedef struct -{ - unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap - float xoff,yoff,xadvance; - float xoff2,yoff2; -} stbtt_packedchar; - -typedef struct stbtt_pack_context stbtt_pack_context; -typedef struct stbtt_fontinfo stbtt_fontinfo; -#ifndef STB_RECT_PACK_VERSION -typedef struct stbrp_rect stbrp_rect; -#endif - -STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context); -// Initializes a packing context stored in the passed-in stbtt_pack_context. -// Future calls using this context will pack characters into the bitmap passed -// in here: a 1-channel bitmap that is width * height. stride_in_bytes is -// the distance from one row to the next (or 0 to mean they are packed tightly -// together). "padding" is the amount of padding to leave between each -// character (normally you want '1' for bitmaps you'll use as textures with -// bilinear filtering). -// -// Returns 0 on failure, 1 on success. - -STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc); -// Cleans up the packing context and frees all memory. - -#define STBTT_POINT_SIZE(x) (-(x)) - -STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, - int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range); -// Creates character bitmaps from the font_index'th font found in fontdata (use -// font_index=0 if you don't know what that is). It creates num_chars_in_range -// bitmaps for characters with unicode values starting at first_unicode_char_in_range -// and increasing. Data for how to render them is stored in chardata_for_range; -// pass these to stbtt_GetPackedQuad to get back renderable quads. -// -// font_size is the full height of the character from ascender to descender, -// as computed by stbtt_ScaleForPixelHeight. To use a point size as computed -// by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE() -// and pass that result as 'font_size': -// ..., 20 , ... // font max minus min y is 20 pixels tall -// ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall - -typedef struct -{ - float font_size; - int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint - int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints - int num_chars; - stbtt_packedchar *chardata_for_range; // output - unsigned char h_oversample, v_oversample; // don't set these, they're used internally -} stbtt_pack_range; - -STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges); -// Creates character bitmaps from multiple ranges of characters stored in -// ranges. This will usually create a better-packed bitmap than multiple -// calls to stbtt_PackFontRange. Note that you can call this multiple -// times within a single PackBegin/PackEnd. - -STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample); -// Oversampling a font increases the quality by allowing higher-quality subpixel -// positioning, and is especially valuable at smaller text sizes. -// -// This function sets the amount of oversampling for all following calls to -// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given -// pack context. The default (no oversampling) is achieved by h_oversample=1 -// and v_oversample=1. The total number of pixels required is -// h_oversample*v_oversample larger than the default; for example, 2x2 -// oversampling requires 4x the storage of 1x1. For best results, render -// oversampled textures with bilinear filtering. Look at the readme in -// stb/tests/oversample for information about oversampled fonts -// -// To use with PackFontRangesGather etc., you must set it before calls -// call to PackFontRangesGatherRects. - -STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip); -// If skip != 0, this tells stb_truetype to skip any codepoints for which -// there is no corresponding glyph. If skip=0, which is the default, then -// codepoints without a glyph recived the font's "missing character" glyph, -// typically an empty box by convention. - -STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above - int char_index, // character to display - float *xpos, float *ypos, // pointers to current position in screen pixel space - stbtt_aligned_quad *q, // output: quad to draw - int align_to_integer); - -STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); -STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects); -STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); -// Calling these functions in sequence is roughly equivalent to calling -// stbtt_PackFontRanges(). If you more control over the packing of multiple -// fonts, or if you want to pack custom data into a font texture, take a look -// at the source to of stbtt_PackFontRanges() and create a custom version -// using these functions, e.g. call GatherRects multiple times, -// building up a single array of rects, then call PackRects once, -// then call RenderIntoRects repeatedly. This may result in a -// better packing than calling PackFontRanges multiple times -// (or it may not). - -// this is an opaque structure that you shouldn't mess with which holds -// all the context needed from PackBegin to PackEnd. -struct stbtt_pack_context { - void *user_allocator_context; - void *pack_info; - int width; - int height; - int stride_in_bytes; - int padding; - int skip_missing; - unsigned int h_oversample, v_oversample; - unsigned char *pixels; - void *nodes; -}; - -////////////////////////////////////////////////////////////////////////////// -// -// FONT LOADING -// -// - -STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data); -// This function will determine the number of fonts in a font file. TrueType -// collection (.ttc) files may contain multiple fonts, while TrueType font -// (.ttf) files only contain one font. The number of fonts can be used for -// indexing with the previous function where the index is between zero and one -// less than the total fonts. If an error occurs, -1 is returned. - -STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); -// Each .ttf/.ttc file may have more than one font. Each font has a sequential -// index number starting from 0. Call this function to get the font offset for -// a given index; it returns -1 if the index is out of range. A regular .ttf -// file will only define one font and it always be at offset 0, so it will -// return '0' for index 0, and -1 for all other indices. - -// The following structure is defined publicly so you can declare one on -// the stack or as a global or etc, but you should treat it as opaque. -struct stbtt_fontinfo -{ - void * userdata; - unsigned char * data; // pointer to .ttf file - int fontstart; // offset of start of font - - int numGlyphs; // number of glyphs, needed for range checking - - int loca,head,glyf,hhea,hmtx,kern,gpos,svg; // table locations as offset from start of .ttf - int index_map; // a cmap mapping for our chosen character encoding - int indexToLocFormat; // format needed to map from glyph index to glyph - - stbtt__buf cff; // cff font data - stbtt__buf charstrings; // the charstring index - stbtt__buf gsubrs; // global charstring subroutines index - stbtt__buf subrs; // private charstring subroutines index - stbtt__buf fontdicts; // array of font dicts - stbtt__buf fdselect; // map from glyph to fontdict -}; - -STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset); -// Given an offset into the file that defines a font, this function builds -// the necessary cached info for the rest of the system. You must allocate -// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't -// need to do anything special to free it, because the contents are pure -// value data with no additional data structures. Returns 0 on failure. - - -////////////////////////////////////////////////////////////////////////////// -// -// CHARACTER TO GLYPH-INDEX CONVERSIOn - -STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); -// If you're going to perform multiple operations on the same character -// and you want a speed-up, call this function with the character you're -// going to process, then use glyph-based functions instead of the -// codepoint-based functions. -// Returns 0 if the character codepoint is not defined in the font. - - -////////////////////////////////////////////////////////////////////////////// -// -// CHARACTER PROPERTIES -// - -STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels); -// computes a scale factor to produce a font whose "height" is 'pixels' tall. -// Height is measured as the distance from the highest ascender to the lowest -// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics -// and computing: -// scale = pixels / (ascent - descent) -// so if you prefer to measure height by the ascent only, use a similar calculation. - -STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); -// computes a scale factor to produce a font whose EM size is mapped to -// 'pixels' tall. This is probably what traditional APIs compute, but -// I'm not positive. - -STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap); -// ascent is the coordinate above the baseline the font extends; descent -// is the coordinate below the baseline the font extends (i.e. it is typically negative) -// lineGap is the spacing between one row's descent and the next row's ascent... -// so you should advance the vertical position by "*ascent - *descent + *lineGap" -// these are expressed in unscaled coordinates, so you must multiply by -// the scale factor for a given size - -STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap); -// analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2 -// table (specific to MS/Windows TTF files). -// -// Returns 1 on success (table present), 0 on failure. - -STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); -// the bounding box around all possible characters - -STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); -// leftSideBearing is the offset from the current horizontal position to the left edge of the character -// advanceWidth is the offset from the current horizontal position to the next horizontal position -// these are expressed in unscaled coordinates - -STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2); -// an additional amount to add to the 'advance' value between ch1 and ch2 - -STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1); -// Gets the bounding box of the visible part of the glyph, in unscaled coordinates - -STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); -STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); -STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); -// as above, but takes one or more glyph indices for greater efficiency - -typedef struct stbtt_kerningentry -{ - int glyph1; // use stbtt_FindGlyphIndex - int glyph2; - int advance; -} stbtt_kerningentry; - -STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info); -STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length); -// Retrieves a complete list of all of the kerning pairs provided by the font -// stbtt_GetKerningTable never writes more than table_length entries and returns how many entries it did write. -// The table will be sorted by (a.glyph1 == b.glyph1)?(a.glyph2 < b.glyph2):(a.glyph1 < b.glyph1) - -////////////////////////////////////////////////////////////////////////////// -// -// GLYPH SHAPES (you probably don't need these, but they have to go before -// the bitmaps for C declaration-order reasons) -// - -#ifndef STBTT_vmove // you can predefine these to use different values (but why?) - enum { - STBTT_vmove=1, - STBTT_vline, - STBTT_vcurve, - STBTT_vcubic - }; -#endif - -#ifndef stbtt_vertex // you can predefine this to use different values - // (we share this with other code at RAD) - #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file - typedef struct - { - stbtt_vertex_type x,y,cx,cy,cx1,cy1; - unsigned char type,padding; - } stbtt_vertex; -#endif - -STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index); -// returns non-zero if nothing is drawn for this glyph - -STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices); -STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices); -// returns # of vertices and fills *vertices with the pointer to them -// these are expressed in "unscaled" coordinates -// -// The shape is a series of contours. Each one starts with -// a STBTT_moveto, then consists of a series of mixed -// STBTT_lineto and STBTT_curveto segments. A lineto -// draws a line from previous endpoint to its x,y; a curveto -// draws a quadratic bezier from previous endpoint to -// its x,y, using cx,cy as the bezier control point. - -STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices); -// frees the data allocated above - -STBTT_DEF unsigned char *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl); -STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg); -STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg); -// fills svg with the character's SVG data. -// returns data size or 0 if SVG not found. - -////////////////////////////////////////////////////////////////////////////// -// -// BITMAP RENDERING -// - -STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata); -// frees the bitmap allocated below - -STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff); -// allocates a large-enough single-channel 8bpp bitmap and renders the -// specified character/glyph at the specified scale into it, with -// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque). -// *width & *height are filled out with the width & height of the bitmap, -// which is stored left-to-right, top-to-bottom. -// -// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap - -STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff); -// the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel -// shift for the character - -STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint); -// the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap -// in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap -// is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the -// width and height and positioning info for it first. - -STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint); -// same as stbtt_MakeCodepointBitmap, but you can specify a subpixel -// shift for the character - -STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint); -// same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering -// is performed (see stbtt_PackSetOversampling) - -STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); -// get the bbox of the bitmap centered around the glyph origin; so the -// bitmap width is ix1-ix0, height is iy1-iy0, and location to place -// the bitmap top left is (leftSideBearing*scale,iy0). -// (Note that the bitmap uses y-increases-down, but the shape uses -// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.) - -STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); -// same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel -// shift for the character - -// the following functions are equivalent to the above functions, but operate -// on glyph indices instead of Unicode codepoints (for efficiency) -STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff); -STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff); -STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph); -STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph); -STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph); -STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); -STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); - - -// @TODO: don't expose this structure -typedef struct -{ - int w,h,stride; - unsigned char *pixels; -} stbtt__bitmap; - -// rasterize a shape with quadratic beziers into a bitmap -STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into - float flatness_in_pixels, // allowable error of curve in pixels - stbtt_vertex *vertices, // array of vertices defining shape - int num_verts, // number of vertices in above array - float scale_x, float scale_y, // scale applied to input vertices - float shift_x, float shift_y, // translation applied to input vertices - int x_off, int y_off, // another translation applied to input - int invert, // if non-zero, vertically flip shape - void *userdata); // context for to STBTT_MALLOC - -////////////////////////////////////////////////////////////////////////////// -// -// Signed Distance Function (or Field) rendering - -STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata); -// frees the SDF bitmap allocated below - -STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); -STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); -// These functions compute a discretized SDF field for a single character, suitable for storing -// in a single-channel texture, sampling with bilinear filtering, and testing against -// larger than some threshold to produce scalable fonts. -// info -- the font -// scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap -// glyph/codepoint -- the character to generate the SDF for -// padding -- extra "pixels" around the character which are filled with the distance to the character (not 0), -// which allows effects like bit outlines -// onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character) -// pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale) -// if positive, > onedge_value is inside; if negative, < onedge_value is inside -// width,height -- output height & width of the SDF bitmap (including padding) -// xoff,yoff -- output origin of the character -// return value -- a 2D array of bytes 0..255, width*height in size -// -// pixel_dist_scale & onedge_value are a scale & bias that allows you to make -// optimal use of the limited 0..255 for your application, trading off precision -// and special effects. SDF values outside the range 0..255 are clamped to 0..255. -// -// Example: -// scale = stbtt_ScaleForPixelHeight(22) -// padding = 5 -// onedge_value = 180 -// pixel_dist_scale = 180/5.0 = 36.0 -// -// This will create an SDF bitmap in which the character is about 22 pixels -// high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled -// shape, sample the SDF at each pixel and fill the pixel if the SDF value -// is greater than or equal to 180/255. (You'll actually want to antialias, -// which is beyond the scope of this example.) Additionally, you can compute -// offset outlines (e.g. to stroke the character border inside & outside, -// or only outside). For example, to fill outside the character up to 3 SDF -// pixels, you would compare against (180-36.0*3)/255 = 72/255. The above -// choice of variables maps a range from 5 pixels outside the shape to -// 2 pixels inside the shape to 0..255; this is intended primarily for apply -// outside effects only (the interior range is needed to allow proper -// antialiasing of the font at *smaller* sizes) -// -// The function computes the SDF analytically at each SDF pixel, not by e.g. -// building a higher-res bitmap and approximating it. In theory the quality -// should be as high as possible for an SDF of this size & representation, but -// unclear if this is true in practice (perhaps building a higher-res bitmap -// and computing from that can allow drop-out prevention). -// -// The algorithm has not been optimized at all, so expect it to be slow -// if computing lots of characters or very large sizes. - - - -////////////////////////////////////////////////////////////////////////////// -// -// Finding the right font... -// -// You should really just solve this offline, keep your own tables -// of what font is what, and don't try to get it out of the .ttf file. -// That's because getting it out of the .ttf file is really hard, because -// the names in the file can appear in many possible encodings, in many -// possible languages, and e.g. if you need a case-insensitive comparison, -// the details of that depend on the encoding & language in a complex way -// (actually underspecified in truetype, but also gigantic). -// -// But you can use the provided functions in two possible ways: -// stbtt_FindMatchingFont() will use *case-sensitive* comparisons on -// unicode-encoded names to try to find the font you want; -// you can run this before calling stbtt_InitFont() -// -// stbtt_GetFontNameString() lets you get any of the various strings -// from the file yourself and do your own comparisons on them. -// You have to have called stbtt_InitFont() first. - - -STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags); -// returns the offset (not index) of the font that matches, or -1 if none -// if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold". -// if you use any other flag, use a font name like "Arial"; this checks -// the 'macStyle' header field; i don't know if fonts set this consistently -#define STBTT_MACSTYLE_DONTCARE 0 -#define STBTT_MACSTYLE_BOLD 1 -#define STBTT_MACSTYLE_ITALIC 2 -#define STBTT_MACSTYLE_UNDERSCORE 4 -#define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0 - -STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2); -// returns 1/0 whether the first string interpreted as utf8 is identical to -// the second string interpreted as big-endian utf16... useful for strings from next func - -STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID); -// returns the string (which may be big-endian double byte, e.g. for unicode) -// and puts the length in bytes in *length. -// -// some of the values for the IDs are below; for more see the truetype spec: -// http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html -// http://www.microsoft.com/typography/otspec/name.htm - -enum { // platformID - STBTT_PLATFORM_ID_UNICODE =0, - STBTT_PLATFORM_ID_MAC =1, - STBTT_PLATFORM_ID_ISO =2, - STBTT_PLATFORM_ID_MICROSOFT =3 -}; - -enum { // encodingID for STBTT_PLATFORM_ID_UNICODE - STBTT_UNICODE_EID_UNICODE_1_0 =0, - STBTT_UNICODE_EID_UNICODE_1_1 =1, - STBTT_UNICODE_EID_ISO_10646 =2, - STBTT_UNICODE_EID_UNICODE_2_0_BMP=3, - STBTT_UNICODE_EID_UNICODE_2_0_FULL=4 -}; - -enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT - STBTT_MS_EID_SYMBOL =0, - STBTT_MS_EID_UNICODE_BMP =1, - STBTT_MS_EID_SHIFTJIS =2, - STBTT_MS_EID_UNICODE_FULL =10 -}; - -enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes - STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4, - STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5, - STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6, - STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7 -}; - -enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID... - // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs - STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410, - STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411, - STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412, - STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419, - STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409, - STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D -}; - -enum { // languageID for STBTT_PLATFORM_ID_MAC - STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11, - STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23, - STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32, - STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 , - STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 , - STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33, - STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19 -}; - -#ifdef __cplusplus -} -#endif - -#endif // __STB_INCLUDE_STB_TRUETYPE_H__ - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -//// -//// IMPLEMENTATION -//// -//// - -#ifdef STB_TRUETYPE_IMPLEMENTATION - -#ifndef STBTT_MAX_OVERSAMPLE -#define STBTT_MAX_OVERSAMPLE 8 -#endif - -#if STBTT_MAX_OVERSAMPLE > 255 -#error "STBTT_MAX_OVERSAMPLE cannot be > 255" -#endif - -typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1]; - -#ifndef STBTT_RASTERIZER_VERSION -#define STBTT_RASTERIZER_VERSION 2 -#endif - -#ifdef _MSC_VER -#define STBTT__NOTUSED(v) (void)(v) -#else -#define STBTT__NOTUSED(v) (void)sizeof(v) -#endif - -////////////////////////////////////////////////////////////////////////// -// -// stbtt__buf helpers to parse data from file -// - -static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b) -{ - if (b->cursor >= b->size) - return 0; - return b->data[b->cursor++]; -} - -static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b) -{ - if (b->cursor >= b->size) - return 0; - return b->data[b->cursor]; -} - -static void stbtt__buf_seek(stbtt__buf *b, int o) -{ - STBTT_assert(!(o > b->size || o < 0)); - b->cursor = (o > b->size || o < 0) ? b->size : o; -} - -static void stbtt__buf_skip(stbtt__buf *b, int o) -{ - stbtt__buf_seek(b, b->cursor + o); -} - -static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n) -{ - stbtt_uint32 v = 0; - int i; - STBTT_assert(n >= 1 && n <= 4); - for (i = 0; i < n; i++) - v = (v << 8) | stbtt__buf_get8(b); - return v; -} - -static stbtt__buf stbtt__new_buf(const void *p, size_t size) -{ - stbtt__buf r; - STBTT_assert(size < 0x40000000); - r.data = (stbtt_uint8*) p; - r.size = (int) size; - r.cursor = 0; - return r; -} - -#define stbtt__buf_get16(b) stbtt__buf_get((b), 2) -#define stbtt__buf_get32(b) stbtt__buf_get((b), 4) - -static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s) -{ - stbtt__buf r = stbtt__new_buf(NULL, 0); - if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r; - r.data = b->data + o; - r.size = s; - return r; -} - -static stbtt__buf stbtt__cff_get_index(stbtt__buf *b) -{ - int count, start, offsize; - start = b->cursor; - count = stbtt__buf_get16(b); - if (count) { - offsize = stbtt__buf_get8(b); - STBTT_assert(offsize >= 1 && offsize <= 4); - stbtt__buf_skip(b, offsize * count); - stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1); - } - return stbtt__buf_range(b, start, b->cursor - start); -} - -static stbtt_uint32 stbtt__cff_int(stbtt__buf *b) -{ - int b0 = stbtt__buf_get8(b); - if (b0 >= 32 && b0 <= 246) return b0 - 139; - else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108; - else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108; - else if (b0 == 28) return stbtt__buf_get16(b); - else if (b0 == 29) return stbtt__buf_get32(b); - STBTT_assert(0); - return 0; -} - -static void stbtt__cff_skip_operand(stbtt__buf *b) { - int v, b0 = stbtt__buf_peek8(b); - STBTT_assert(b0 >= 28); - if (b0 == 30) { - stbtt__buf_skip(b, 1); - while (b->cursor < b->size) { - v = stbtt__buf_get8(b); - if ((v & 0xF) == 0xF || (v >> 4) == 0xF) - break; - } - } else { - stbtt__cff_int(b); - } -} - -static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key) -{ - stbtt__buf_seek(b, 0); - while (b->cursor < b->size) { - int start = b->cursor, end, op; - while (stbtt__buf_peek8(b) >= 28) - stbtt__cff_skip_operand(b); - end = b->cursor; - op = stbtt__buf_get8(b); - if (op == 12) op = stbtt__buf_get8(b) | 0x100; - if (op == key) return stbtt__buf_range(b, start, end-start); - } - return stbtt__buf_range(b, 0, 0); -} - -static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out) -{ - int i; - stbtt__buf operands = stbtt__dict_get(b, key); - for (i = 0; i < outcount && operands.cursor < operands.size; i++) - out[i] = stbtt__cff_int(&operands); -} - -static int stbtt__cff_index_count(stbtt__buf *b) -{ - stbtt__buf_seek(b, 0); - return stbtt__buf_get16(b); -} - -static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i) -{ - int count, offsize, start, end; - stbtt__buf_seek(&b, 0); - count = stbtt__buf_get16(&b); - offsize = stbtt__buf_get8(&b); - STBTT_assert(i >= 0 && i < count); - STBTT_assert(offsize >= 1 && offsize <= 4); - stbtt__buf_skip(&b, i*offsize); - start = stbtt__buf_get(&b, offsize); - end = stbtt__buf_get(&b, offsize); - return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start); -} - -////////////////////////////////////////////////////////////////////////// -// -// accessors to parse data from file -// - -// on platforms that don't allow misaligned reads, if we want to allow -// truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE - -#define ttBYTE(p) (* (stbtt_uint8 *) (p)) -#define ttCHAR(p) (* (stbtt_int8 *) (p)) -#define ttFixed(p) ttLONG(p) - -static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } -static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } -static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } -static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } - -#define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)) -#define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3]) - -static int stbtt__isfont(stbtt_uint8 *font) -{ - // check the version number - if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1 - if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this! - if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF - if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0 - if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts - return 0; -} - -// @OPTIMIZE: binary search -static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag) -{ - stbtt_int32 num_tables = ttUSHORT(data+fontstart+4); - stbtt_uint32 tabledir = fontstart + 12; - stbtt_int32 i; - for (i=0; i < num_tables; ++i) { - stbtt_uint32 loc = tabledir + 16*i; - if (stbtt_tag(data+loc+0, tag)) - return ttULONG(data+loc+8); - } - return 0; -} - -static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index) -{ - // if it's just a font, there's only one valid index - if (stbtt__isfont(font_collection)) - return index == 0 ? 0 : -1; - - // check if it's a TTC - if (stbtt_tag(font_collection, "ttcf")) { - // version 1? - if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { - stbtt_int32 n = ttLONG(font_collection+8); - if (index >= n) - return -1; - return ttULONG(font_collection+12+index*4); - } - } - return -1; -} - -static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection) -{ - // if it's just a font, there's only one valid font - if (stbtt__isfont(font_collection)) - return 1; - - // check if it's a TTC - if (stbtt_tag(font_collection, "ttcf")) { - // version 1? - if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { - return ttLONG(font_collection+8); - } - } - return 0; -} - -static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict) -{ - stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 }; - stbtt__buf pdict; - stbtt__dict_get_ints(&fontdict, 18, 2, private_loc); - if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0); - pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]); - stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff); - if (!subrsoff) return stbtt__new_buf(NULL, 0); - stbtt__buf_seek(&cff, private_loc[1]+subrsoff); - return stbtt__cff_get_index(&cff); -} - -// since most people won't use this, find this table the first time it's needed -static int stbtt__get_svg(stbtt_fontinfo *info) -{ - stbtt_uint32 t; - if (info->svg < 0) { - t = stbtt__find_table(info->data, info->fontstart, "SVG "); - if (t) { - stbtt_uint32 offset = ttULONG(info->data + t + 2); - info->svg = t + offset; - } else { - info->svg = 0; - } - } - return info->svg; -} - -static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart) -{ - stbtt_uint32 cmap, t; - stbtt_int32 i,numTables; - - info->data = data; - info->fontstart = fontstart; - info->cff = stbtt__new_buf(NULL, 0); - - cmap = stbtt__find_table(data, fontstart, "cmap"); // required - info->loca = stbtt__find_table(data, fontstart, "loca"); // required - info->head = stbtt__find_table(data, fontstart, "head"); // required - info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required - info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required - info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required - info->kern = stbtt__find_table(data, fontstart, "kern"); // not required - info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required - - if (!cmap || !info->head || !info->hhea || !info->hmtx) - return 0; - if (info->glyf) { - // required for truetype - if (!info->loca) return 0; - } else { - // initialization for CFF / Type2 fonts (OTF) - stbtt__buf b, topdict, topdictidx; - stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0; - stbtt_uint32 cff; - - cff = stbtt__find_table(data, fontstart, "CFF "); - if (!cff) return 0; - - info->fontdicts = stbtt__new_buf(NULL, 0); - info->fdselect = stbtt__new_buf(NULL, 0); - - // @TODO this should use size from table (not 512MB) - info->cff = stbtt__new_buf(data+cff, 512*1024*1024); - b = info->cff; - - // read the header - stbtt__buf_skip(&b, 2); - stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize - - // @TODO the name INDEX could list multiple fonts, - // but we just use the first one. - stbtt__cff_get_index(&b); // name INDEX - topdictidx = stbtt__cff_get_index(&b); - topdict = stbtt__cff_index_get(topdictidx, 0); - stbtt__cff_get_index(&b); // string INDEX - info->gsubrs = stbtt__cff_get_index(&b); - - stbtt__dict_get_ints(&topdict, 17, 1, &charstrings); - stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype); - stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff); - stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff); - info->subrs = stbtt__get_subrs(b, topdict); - - // we only support Type 2 charstrings - if (cstype != 2) return 0; - if (charstrings == 0) return 0; - - if (fdarrayoff) { - // looks like a CID font - if (!fdselectoff) return 0; - stbtt__buf_seek(&b, fdarrayoff); - info->fontdicts = stbtt__cff_get_index(&b); - info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff); - } - - stbtt__buf_seek(&b, charstrings); - info->charstrings = stbtt__cff_get_index(&b); - } - - t = stbtt__find_table(data, fontstart, "maxp"); - if (t) - info->numGlyphs = ttUSHORT(data+t+4); - else - info->numGlyphs = 0xffff; - - info->svg = -1; - - // find a cmap encoding table we understand *now* to avoid searching - // later. (todo: could make this installable) - // the same regardless of glyph. - numTables = ttUSHORT(data + cmap + 2); - info->index_map = 0; - for (i=0; i < numTables; ++i) { - stbtt_uint32 encoding_record = cmap + 4 + 8 * i; - // find an encoding we understand: - switch(ttUSHORT(data+encoding_record)) { - case STBTT_PLATFORM_ID_MICROSOFT: - switch (ttUSHORT(data+encoding_record+2)) { - case STBTT_MS_EID_UNICODE_BMP: - case STBTT_MS_EID_UNICODE_FULL: - // MS/Unicode - info->index_map = cmap + ttULONG(data+encoding_record+4); - break; - } - break; - case STBTT_PLATFORM_ID_UNICODE: - // Mac/iOS has these - // all the encodingIDs are unicode, so we don't bother to check it - info->index_map = cmap + ttULONG(data+encoding_record+4); - break; - } - } - if (info->index_map == 0) - return 0; - - info->indexToLocFormat = ttUSHORT(data+info->head + 50); - return 1; -} - -STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint) -{ - stbtt_uint8 *data = info->data; - stbtt_uint32 index_map = info->index_map; - - stbtt_uint16 format = ttUSHORT(data + index_map + 0); - if (format == 0) { // apple byte encoding - stbtt_int32 bytes = ttUSHORT(data + index_map + 2); - if (unicode_codepoint < bytes-6) - return ttBYTE(data + index_map + 6 + unicode_codepoint); - return 0; - } else if (format == 6) { - stbtt_uint32 first = ttUSHORT(data + index_map + 6); - stbtt_uint32 count = ttUSHORT(data + index_map + 8); - if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count) - return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2); - return 0; - } else if (format == 2) { - STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean - return 0; - } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges - stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1; - stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1; - stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10); - stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1; - - // do a binary search of the segments - stbtt_uint32 endCount = index_map + 14; - stbtt_uint32 search = endCount; - - if (unicode_codepoint > 0xffff) - return 0; - - // they lie from endCount .. endCount + segCount - // but searchRange is the nearest power of two, so... - if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2)) - search += rangeShift*2; - - // now decrement to bias correctly to find smallest - search -= 2; - while (entrySelector) { - stbtt_uint16 end; - searchRange >>= 1; - end = ttUSHORT(data + search + searchRange*2); - if (unicode_codepoint > end) - search += searchRange*2; - --entrySelector; - } - search += 2; - - { - stbtt_uint16 offset, start, last; - stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1); - - start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); - last = ttUSHORT(data + endCount + 2*item); - if (unicode_codepoint < start || unicode_codepoint > last) - return 0; - - offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); - if (offset == 0) - return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); - - return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); - } - } else if (format == 12 || format == 13) { - stbtt_uint32 ngroups = ttULONG(data+index_map+12); - stbtt_int32 low,high; - low = 0; high = (stbtt_int32)ngroups; - // Binary search the right group. - while (low < high) { - stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high - stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12); - stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4); - if ((stbtt_uint32) unicode_codepoint < start_char) - high = mid; - else if ((stbtt_uint32) unicode_codepoint > end_char) - low = mid+1; - else { - stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8); - if (format == 12) - return start_glyph + unicode_codepoint-start_char; - else // format == 13 - return start_glyph; - } - } - return 0; // not found - } - // @TODO - STBTT_assert(0); - return 0; -} - -STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices) -{ - return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices); -} - -static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy) -{ - v->type = type; - v->x = (stbtt_int16) x; - v->y = (stbtt_int16) y; - v->cx = (stbtt_int16) cx; - v->cy = (stbtt_int16) cy; -} - -static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index) -{ - int g1,g2; - - STBTT_assert(!info->cff.size); - - if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range - if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format - - if (info->indexToLocFormat == 0) { - g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2; - g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2; - } else { - g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4); - g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4); - } - - return g1==g2 ? -1 : g1; // if length is 0, return -1 -} - -static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); - -STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) -{ - if (info->cff.size) { - stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); - } else { - int g = stbtt__GetGlyfOffset(info, glyph_index); - if (g < 0) return 0; - - if (x0) *x0 = ttSHORT(info->data + g + 2); - if (y0) *y0 = ttSHORT(info->data + g + 4); - if (x1) *x1 = ttSHORT(info->data + g + 6); - if (y1) *y1 = ttSHORT(info->data + g + 8); - } - return 1; -} - -STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1) -{ - return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1); -} - -STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index) -{ - stbtt_int16 numberOfContours; - int g; - if (info->cff.size) - return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0; - g = stbtt__GetGlyfOffset(info, glyph_index); - if (g < 0) return 1; - numberOfContours = ttSHORT(info->data + g); - return numberOfContours == 0; -} - -static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off, - stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy) -{ - if (start_off) { - if (was_off) - stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy); - stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy); - } else { - if (was_off) - stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy); - else - stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0); - } - return num_vertices; -} - -static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) -{ - stbtt_int16 numberOfContours; - stbtt_uint8 *endPtsOfContours; - stbtt_uint8 *data = info->data; - stbtt_vertex *vertices=0; - int num_vertices=0; - int g = stbtt__GetGlyfOffset(info, glyph_index); - - *pvertices = NULL; - - if (g < 0) return 0; - - numberOfContours = ttSHORT(data + g); - - if (numberOfContours > 0) { - stbtt_uint8 flags=0,flagcount; - stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0; - stbtt_int32 x,y,cx,cy,sx,sy, scx,scy; - stbtt_uint8 *points; - endPtsOfContours = (data + g + 10); - ins = ttUSHORT(data + g + 10 + numberOfContours * 2); - points = data + g + 10 + numberOfContours * 2 + 2 + ins; - - n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2); - - m = n + 2*numberOfContours; // a loose bound on how many vertices we might need - vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata); - if (vertices == 0) - return 0; - - next_move = 0; - flagcount=0; - - // in first pass, we load uninterpreted data into the allocated array - // above, shifted to the end of the array so we won't overwrite it when - // we create our final data starting from the front - - off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated - - // first load flags - - for (i=0; i < n; ++i) { - if (flagcount == 0) { - flags = *points++; - if (flags & 8) - flagcount = *points++; - } else - --flagcount; - vertices[off+i].type = flags; - } - - // now load x coordinates - x=0; - for (i=0; i < n; ++i) { - flags = vertices[off+i].type; - if (flags & 2) { - stbtt_int16 dx = *points++; - x += (flags & 16) ? dx : -dx; // ??? - } else { - if (!(flags & 16)) { - x = x + (stbtt_int16) (points[0]*256 + points[1]); - points += 2; - } - } - vertices[off+i].x = (stbtt_int16) x; - } - - // now load y coordinates - y=0; - for (i=0; i < n; ++i) { - flags = vertices[off+i].type; - if (flags & 4) { - stbtt_int16 dy = *points++; - y += (flags & 32) ? dy : -dy; // ??? - } else { - if (!(flags & 32)) { - y = y + (stbtt_int16) (points[0]*256 + points[1]); - points += 2; - } - } - vertices[off+i].y = (stbtt_int16) y; - } - - // now convert them to our format - num_vertices=0; - sx = sy = cx = cy = scx = scy = 0; - for (i=0; i < n; ++i) { - flags = vertices[off+i].type; - x = (stbtt_int16) vertices[off+i].x; - y = (stbtt_int16) vertices[off+i].y; - - if (next_move == i) { - if (i != 0) - num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); - - // now start the new one - start_off = !(flags & 1); - if (start_off) { - // if we start off with an off-curve point, then when we need to find a point on the curve - // where we can start, and we need to save some state for when we wraparound. - scx = x; - scy = y; - if (!(vertices[off+i+1].type & 1)) { - // next point is also a curve point, so interpolate an on-point curve - sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1; - sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1; - } else { - // otherwise just use the next point as our start point - sx = (stbtt_int32) vertices[off+i+1].x; - sy = (stbtt_int32) vertices[off+i+1].y; - ++i; // we're using point i+1 as the starting point, so skip it - } - } else { - sx = x; - sy = y; - } - stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0); - was_off = 0; - next_move = 1 + ttUSHORT(endPtsOfContours+j*2); - ++j; - } else { - if (!(flags & 1)) { // if it's a curve - if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint - stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy); - cx = x; - cy = y; - was_off = 1; - } else { - if (was_off) - stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy); - else - stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0); - was_off = 0; - } - } - } - num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); - } else if (numberOfContours < 0) { - // Compound shapes. - int more = 1; - stbtt_uint8 *comp = data + g + 10; - num_vertices = 0; - vertices = 0; - while (more) { - stbtt_uint16 flags, gidx; - int comp_num_verts = 0, i; - stbtt_vertex *comp_verts = 0, *tmp = 0; - float mtx[6] = {1,0,0,1,0,0}, m, n; - - flags = ttSHORT(comp); comp+=2; - gidx = ttSHORT(comp); comp+=2; - - if (flags & 2) { // XY values - if (flags & 1) { // shorts - mtx[4] = ttSHORT(comp); comp+=2; - mtx[5] = ttSHORT(comp); comp+=2; - } else { - mtx[4] = ttCHAR(comp); comp+=1; - mtx[5] = ttCHAR(comp); comp+=1; - } - } - else { - // @TODO handle matching point - STBTT_assert(0); - } - if (flags & (1<<3)) { // WE_HAVE_A_SCALE - mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; - mtx[1] = mtx[2] = 0; - } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE - mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; - mtx[1] = mtx[2] = 0; - mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; - } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO - mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; - mtx[1] = ttSHORT(comp)/16384.0f; comp+=2; - mtx[2] = ttSHORT(comp)/16384.0f; comp+=2; - mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; - } - - // Find transformation scales. - m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]); - n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]); - - // Get indexed glyph. - comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts); - if (comp_num_verts > 0) { - // Transform vertices. - for (i = 0; i < comp_num_verts; ++i) { - stbtt_vertex* v = &comp_verts[i]; - stbtt_vertex_type x,y; - x=v->x; y=v->y; - v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); - v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); - x=v->cx; y=v->cy; - v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4])); - v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5])); - } - // Append vertices. - tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata); - if (!tmp) { - if (vertices) STBTT_free(vertices, info->userdata); - if (comp_verts) STBTT_free(comp_verts, info->userdata); - return 0; - } - if (num_vertices > 0 && vertices) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex)); - STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex)); - if (vertices) STBTT_free(vertices, info->userdata); - vertices = tmp; - STBTT_free(comp_verts, info->userdata); - num_vertices += comp_num_verts; - } - // More components ? - more = flags & (1<<5); - } - } else { - // numberOfCounters == 0, do nothing - } - - *pvertices = vertices; - return num_vertices; -} - -typedef struct -{ - int bounds; - int started; - float first_x, first_y; - float x, y; - stbtt_int32 min_x, max_x, min_y, max_y; - - stbtt_vertex *pvertices; - int num_vertices; -} stbtt__csctx; - -#define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0} - -static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y) -{ - if (x > c->max_x || !c->started) c->max_x = x; - if (y > c->max_y || !c->started) c->max_y = y; - if (x < c->min_x || !c->started) c->min_x = x; - if (y < c->min_y || !c->started) c->min_y = y; - c->started = 1; -} - -static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1) -{ - if (c->bounds) { - stbtt__track_vertex(c, x, y); - if (type == STBTT_vcubic) { - stbtt__track_vertex(c, cx, cy); - stbtt__track_vertex(c, cx1, cy1); - } - } else { - stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy); - c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1; - c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1; - } - c->num_vertices++; -} - -static void stbtt__csctx_close_shape(stbtt__csctx *ctx) -{ - if (ctx->first_x != ctx->x || ctx->first_y != ctx->y) - stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0); -} - -static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy) -{ - stbtt__csctx_close_shape(ctx); - ctx->first_x = ctx->x = ctx->x + dx; - ctx->first_y = ctx->y = ctx->y + dy; - stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); -} - -static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy) -{ - ctx->x += dx; - ctx->y += dy; - stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); -} - -static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) -{ - float cx1 = ctx->x + dx1; - float cy1 = ctx->y + dy1; - float cx2 = cx1 + dx2; - float cy2 = cy1 + dy2; - ctx->x = cx2 + dx3; - ctx->y = cy2 + dy3; - stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2); -} - -static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n) -{ - int count = stbtt__cff_index_count(&idx); - int bias = 107; - if (count >= 33900) - bias = 32768; - else if (count >= 1240) - bias = 1131; - n += bias; - if (n < 0 || n >= count) - return stbtt__new_buf(NULL, 0); - return stbtt__cff_index_get(idx, n); -} - -static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index) -{ - stbtt__buf fdselect = info->fdselect; - int nranges, start, end, v, fmt, fdselector = -1, i; - - stbtt__buf_seek(&fdselect, 0); - fmt = stbtt__buf_get8(&fdselect); - if (fmt == 0) { - // untested - stbtt__buf_skip(&fdselect, glyph_index); - fdselector = stbtt__buf_get8(&fdselect); - } else if (fmt == 3) { - nranges = stbtt__buf_get16(&fdselect); - start = stbtt__buf_get16(&fdselect); - for (i = 0; i < nranges; i++) { - v = stbtt__buf_get8(&fdselect); - end = stbtt__buf_get16(&fdselect); - if (glyph_index >= start && glyph_index < end) { - fdselector = v; - break; - } - start = end; - } - } - if (fdselector == -1) stbtt__new_buf(NULL, 0); - return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector)); -} - -static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c) -{ - int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0; - int has_subrs = 0, clear_stack; - float s[48]; - stbtt__buf subr_stack[10], subrs = info->subrs, b; - float f; - -#define STBTT__CSERR(s) (0) - - // this currently ignores the initial width value, which isn't needed if we have hmtx - b = stbtt__cff_index_get(info->charstrings, glyph_index); - while (b.cursor < b.size) { - i = 0; - clear_stack = 1; - b0 = stbtt__buf_get8(&b); - switch (b0) { - // @TODO implement hinting - case 0x13: // hintmask - case 0x14: // cntrmask - if (in_header) - maskbits += (sp / 2); // implicit "vstem" - in_header = 0; - stbtt__buf_skip(&b, (maskbits + 7) / 8); - break; - - case 0x01: // hstem - case 0x03: // vstem - case 0x12: // hstemhm - case 0x17: // vstemhm - maskbits += (sp / 2); - break; - - case 0x15: // rmoveto - in_header = 0; - if (sp < 2) return STBTT__CSERR("rmoveto stack"); - stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]); - break; - case 0x04: // vmoveto - in_header = 0; - if (sp < 1) return STBTT__CSERR("vmoveto stack"); - stbtt__csctx_rmove_to(c, 0, s[sp-1]); - break; - case 0x16: // hmoveto - in_header = 0; - if (sp < 1) return STBTT__CSERR("hmoveto stack"); - stbtt__csctx_rmove_to(c, s[sp-1], 0); - break; - - case 0x05: // rlineto - if (sp < 2) return STBTT__CSERR("rlineto stack"); - for (; i + 1 < sp; i += 2) - stbtt__csctx_rline_to(c, s[i], s[i+1]); - break; - - // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical - // starting from a different place. - - case 0x07: // vlineto - if (sp < 1) return STBTT__CSERR("vlineto stack"); - goto vlineto; - case 0x06: // hlineto - if (sp < 1) return STBTT__CSERR("hlineto stack"); - for (;;) { - if (i >= sp) break; - stbtt__csctx_rline_to(c, s[i], 0); - i++; - vlineto: - if (i >= sp) break; - stbtt__csctx_rline_to(c, 0, s[i]); - i++; - } - break; - - case 0x1F: // hvcurveto - if (sp < 4) return STBTT__CSERR("hvcurveto stack"); - goto hvcurveto; - case 0x1E: // vhcurveto - if (sp < 4) return STBTT__CSERR("vhcurveto stack"); - for (;;) { - if (i + 3 >= sp) break; - stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f); - i += 4; - hvcurveto: - if (i + 3 >= sp) break; - stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]); - i += 4; - } - break; - - case 0x08: // rrcurveto - if (sp < 6) return STBTT__CSERR("rcurveline stack"); - for (; i + 5 < sp; i += 6) - stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); - break; - - case 0x18: // rcurveline - if (sp < 8) return STBTT__CSERR("rcurveline stack"); - for (; i + 5 < sp - 2; i += 6) - stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); - if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack"); - stbtt__csctx_rline_to(c, s[i], s[i+1]); - break; - - case 0x19: // rlinecurve - if (sp < 8) return STBTT__CSERR("rlinecurve stack"); - for (; i + 1 < sp - 6; i += 2) - stbtt__csctx_rline_to(c, s[i], s[i+1]); - if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack"); - stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); - break; - - case 0x1A: // vvcurveto - case 0x1B: // hhcurveto - if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack"); - f = 0.0; - if (sp & 1) { f = s[i]; i++; } - for (; i + 3 < sp; i += 4) { - if (b0 == 0x1B) - stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0); - else - stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]); - f = 0.0; - } - break; - - case 0x0A: // callsubr - if (!has_subrs) { - if (info->fdselect.size) - subrs = stbtt__cid_get_glyph_subrs(info, glyph_index); - has_subrs = 1; - } - // FALLTHROUGH - case 0x1D: // callgsubr - if (sp < 1) return STBTT__CSERR("call(g|)subr stack"); - v = (int) s[--sp]; - if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit"); - subr_stack[subr_stack_height++] = b; - b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v); - if (b.size == 0) return STBTT__CSERR("subr not found"); - b.cursor = 0; - clear_stack = 0; - break; - - case 0x0B: // return - if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr"); - b = subr_stack[--subr_stack_height]; - clear_stack = 0; - break; - - case 0x0E: // endchar - stbtt__csctx_close_shape(c); - return 1; - - case 0x0C: { // two-byte escape - float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6; - float dx, dy; - int b1 = stbtt__buf_get8(&b); - switch (b1) { - // @TODO These "flex" implementations ignore the flex-depth and resolution, - // and always draw beziers. - case 0x22: // hflex - if (sp < 7) return STBTT__CSERR("hflex stack"); - dx1 = s[0]; - dx2 = s[1]; - dy2 = s[2]; - dx3 = s[3]; - dx4 = s[4]; - dx5 = s[5]; - dx6 = s[6]; - stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0); - stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0); - break; - - case 0x23: // flex - if (sp < 13) return STBTT__CSERR("flex stack"); - dx1 = s[0]; - dy1 = s[1]; - dx2 = s[2]; - dy2 = s[3]; - dx3 = s[4]; - dy3 = s[5]; - dx4 = s[6]; - dy4 = s[7]; - dx5 = s[8]; - dy5 = s[9]; - dx6 = s[10]; - dy6 = s[11]; - //fd is s[12] - stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); - stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); - break; - - case 0x24: // hflex1 - if (sp < 9) return STBTT__CSERR("hflex1 stack"); - dx1 = s[0]; - dy1 = s[1]; - dx2 = s[2]; - dy2 = s[3]; - dx3 = s[4]; - dx4 = s[5]; - dx5 = s[6]; - dy5 = s[7]; - dx6 = s[8]; - stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0); - stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5)); - break; - - case 0x25: // flex1 - if (sp < 11) return STBTT__CSERR("flex1 stack"); - dx1 = s[0]; - dy1 = s[1]; - dx2 = s[2]; - dy2 = s[3]; - dx3 = s[4]; - dy3 = s[5]; - dx4 = s[6]; - dy4 = s[7]; - dx5 = s[8]; - dy5 = s[9]; - dx6 = dy6 = s[10]; - dx = dx1+dx2+dx3+dx4+dx5; - dy = dy1+dy2+dy3+dy4+dy5; - if (STBTT_fabs(dx) > STBTT_fabs(dy)) - dy6 = -dy; - else - dx6 = -dx; - stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); - stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); - break; - - default: - return STBTT__CSERR("unimplemented"); - } - } break; - - default: - if (b0 != 255 && b0 != 28 && b0 < 32) - return STBTT__CSERR("reserved operator"); - - // push immediate - if (b0 == 255) { - f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000; - } else { - stbtt__buf_skip(&b, -1); - f = (float)(stbtt_int16)stbtt__cff_int(&b); - } - if (sp >= 48) return STBTT__CSERR("push stack overflow"); - s[sp++] = f; - clear_stack = 0; - break; - } - if (clear_stack) sp = 0; - } - return STBTT__CSERR("no endchar"); - -#undef STBTT__CSERR -} - -static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) -{ - // runs the charstring twice, once to count and once to output (to avoid realloc) - stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1); - stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0); - if (stbtt__run_charstring(info, glyph_index, &count_ctx)) { - *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata); - output_ctx.pvertices = *pvertices; - if (stbtt__run_charstring(info, glyph_index, &output_ctx)) { - STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices); - return output_ctx.num_vertices; - } - } - *pvertices = NULL; - return 0; -} - -static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) -{ - stbtt__csctx c = STBTT__CSCTX_INIT(1); - int r = stbtt__run_charstring(info, glyph_index, &c); - if (x0) *x0 = r ? c.min_x : 0; - if (y0) *y0 = r ? c.min_y : 0; - if (x1) *x1 = r ? c.max_x : 0; - if (y1) *y1 = r ? c.max_y : 0; - return r ? c.num_vertices : 0; -} - -STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) -{ - if (!info->cff.size) - return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices); - else - return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices); -} - -STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing) -{ - stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34); - if (glyph_index < numOfLongHorMetrics) { - if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index); - if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2); - } else { - if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1)); - if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics)); - } -} - -STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info) -{ - stbtt_uint8 *data = info->data + info->kern; - - // we only look at the first table. it must be 'horizontal' and format 0. - if (!info->kern) - return 0; - if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 - return 0; - if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format - return 0; - - return ttUSHORT(data+10); -} - -STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length) -{ - stbtt_uint8 *data = info->data + info->kern; - int k, length; - - // we only look at the first table. it must be 'horizontal' and format 0. - if (!info->kern) - return 0; - if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 - return 0; - if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format - return 0; - - length = ttUSHORT(data+10); - if (table_length < length) - length = table_length; - - for (k = 0; k < length; k++) - { - table[k].glyph1 = ttUSHORT(data+18+(k*6)); - table[k].glyph2 = ttUSHORT(data+20+(k*6)); - table[k].advance = ttSHORT(data+22+(k*6)); - } - - return length; -} - -static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) -{ - stbtt_uint8 *data = info->data + info->kern; - stbtt_uint32 needle, straw; - int l, r, m; - - // we only look at the first table. it must be 'horizontal' and format 0. - if (!info->kern) - return 0; - if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 - return 0; - if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format - return 0; - - l = 0; - r = ttUSHORT(data+10) - 1; - needle = glyph1 << 16 | glyph2; - while (l <= r) { - m = (l + r) >> 1; - straw = ttULONG(data+18+(m*6)); // note: unaligned read - if (needle < straw) - r = m - 1; - else if (needle > straw) - l = m + 1; - else - return ttSHORT(data+22+(m*6)); - } - return 0; -} - -static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph) -{ - stbtt_uint16 coverageFormat = ttUSHORT(coverageTable); - switch (coverageFormat) { - case 1: { - stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2); - - // Binary search. - stbtt_int32 l=0, r=glyphCount-1, m; - int straw, needle=glyph; - while (l <= r) { - stbtt_uint8 *glyphArray = coverageTable + 4; - stbtt_uint16 glyphID; - m = (l + r) >> 1; - glyphID = ttUSHORT(glyphArray + 2 * m); - straw = glyphID; - if (needle < straw) - r = m - 1; - else if (needle > straw) - l = m + 1; - else { - return m; - } - } - break; - } - - case 2: { - stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2); - stbtt_uint8 *rangeArray = coverageTable + 4; - - // Binary search. - stbtt_int32 l=0, r=rangeCount-1, m; - int strawStart, strawEnd, needle=glyph; - while (l <= r) { - stbtt_uint8 *rangeRecord; - m = (l + r) >> 1; - rangeRecord = rangeArray + 6 * m; - strawStart = ttUSHORT(rangeRecord); - strawEnd = ttUSHORT(rangeRecord + 2); - if (needle < strawStart) - r = m - 1; - else if (needle > strawEnd) - l = m + 1; - else { - stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4); - return startCoverageIndex + glyph - strawStart; - } - } - break; - } - - default: return -1; // unsupported - } - - return -1; -} - -static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph) -{ - stbtt_uint16 classDefFormat = ttUSHORT(classDefTable); - switch (classDefFormat) - { - case 1: { - stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2); - stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4); - stbtt_uint8 *classDef1ValueArray = classDefTable + 6; - - if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount) - return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID)); - break; - } - - case 2: { - stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2); - stbtt_uint8 *classRangeRecords = classDefTable + 4; - - // Binary search. - stbtt_int32 l=0, r=classRangeCount-1, m; - int strawStart, strawEnd, needle=glyph; - while (l <= r) { - stbtt_uint8 *classRangeRecord; - m = (l + r) >> 1; - classRangeRecord = classRangeRecords + 6 * m; - strawStart = ttUSHORT(classRangeRecord); - strawEnd = ttUSHORT(classRangeRecord + 2); - if (needle < strawStart) - r = m - 1; - else if (needle > strawEnd) - l = m + 1; - else - return (stbtt_int32)ttUSHORT(classRangeRecord + 4); - } - break; - } - - default: - return -1; // Unsupported definition type, return an error. - } - - // "All glyphs not assigned to a class fall into class 0". (OpenType spec) - return 0; -} - -// Define to STBTT_assert(x) if you want to break on unimplemented formats. -#define STBTT_GPOS_TODO_assert(x) - -static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) -{ - stbtt_uint16 lookupListOffset; - stbtt_uint8 *lookupList; - stbtt_uint16 lookupCount; - stbtt_uint8 *data; - stbtt_int32 i, sti; - - if (!info->gpos) return 0; - - data = info->data + info->gpos; - - if (ttUSHORT(data+0) != 1) return 0; // Major version 1 - if (ttUSHORT(data+2) != 0) return 0; // Minor version 0 - - lookupListOffset = ttUSHORT(data+8); - lookupList = data + lookupListOffset; - lookupCount = ttUSHORT(lookupList); - - for (i=0; i= pairSetCount) return 0; - - needle=glyph2; - r=pairValueCount-1; - l=0; - - // Binary search. - while (l <= r) { - stbtt_uint16 secondGlyph; - stbtt_uint8 *pairValue; - m = (l + r) >> 1; - pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m; - secondGlyph = ttUSHORT(pairValue); - straw = secondGlyph; - if (needle < straw) - r = m - 1; - else if (needle > straw) - l = m + 1; - else { - stbtt_int16 xAdvance = ttSHORT(pairValue + 2); - return xAdvance; - } - } - } else - return 0; - break; - } - - case 2: { - stbtt_uint16 valueFormat1 = ttUSHORT(table + 4); - stbtt_uint16 valueFormat2 = ttUSHORT(table + 6); - if (valueFormat1 == 4 && valueFormat2 == 0) { // Support more formats? - stbtt_uint16 classDef1Offset = ttUSHORT(table + 8); - stbtt_uint16 classDef2Offset = ttUSHORT(table + 10); - int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1); - int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2); - - stbtt_uint16 class1Count = ttUSHORT(table + 12); - stbtt_uint16 class2Count = ttUSHORT(table + 14); - stbtt_uint8 *class1Records, *class2Records; - stbtt_int16 xAdvance; - - if (glyph1class < 0 || glyph1class >= class1Count) return 0; // malformed - if (glyph2class < 0 || glyph2class >= class2Count) return 0; // malformed - - class1Records = table + 16; - class2Records = class1Records + 2 * (glyph1class * class2Count); - xAdvance = ttSHORT(class2Records + 2 * glyph2class); - return xAdvance; - } else - return 0; - break; - } - - default: - return 0; // Unsupported position format - } - } - } - - return 0; -} - -STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2) -{ - int xAdvance = 0; - - if (info->gpos) - xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2); - else if (info->kern) - xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2); - - return xAdvance; -} - -STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2) -{ - if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs - return 0; - return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2)); -} - -STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing) -{ - stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing); -} - -STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap) -{ - if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4); - if (descent) *descent = ttSHORT(info->data+info->hhea + 6); - if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8); -} - -STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap) -{ - int tab = stbtt__find_table(info->data, info->fontstart, "OS/2"); - if (!tab) - return 0; - if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68); - if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70); - if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72); - return 1; -} - -STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1) -{ - *x0 = ttSHORT(info->data + info->head + 36); - *y0 = ttSHORT(info->data + info->head + 38); - *x1 = ttSHORT(info->data + info->head + 40); - *y1 = ttSHORT(info->data + info->head + 42); -} - -STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) -{ - int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); - return (float) height / fheight; -} - -STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) -{ - int unitsPerEm = ttUSHORT(info->data + info->head + 18); - return pixels / unitsPerEm; -} - -STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v) -{ - STBTT_free(v, info->userdata); -} - -STBTT_DEF stbtt_uint8 *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl) -{ - int i; - stbtt_uint8 *data = info->data; - stbtt_uint8 *svg_doc_list = data + stbtt__get_svg((stbtt_fontinfo *) info); - - int numEntries = ttUSHORT(svg_doc_list); - stbtt_uint8 *svg_docs = svg_doc_list + 2; - - for(i=0; i= ttUSHORT(svg_doc)) && (gl <= ttUSHORT(svg_doc + 2))) - return svg_doc; - } - return 0; -} - -STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg) -{ - stbtt_uint8 *data = info->data; - stbtt_uint8 *svg_doc; - - if (info->svg == 0) - return 0; - - svg_doc = stbtt_FindSVGDoc(info, gl); - if (svg_doc != NULL) { - *svg = (char *) data + info->svg + ttULONG(svg_doc + 4); - return ttULONG(svg_doc + 8); - } else { - return 0; - } -} - -STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg) -{ - return stbtt_GetGlyphSVG(info, stbtt_FindGlyphIndex(info, unicode_codepoint), svg); -} - -////////////////////////////////////////////////////////////////////////////// -// -// antialiasing software rasterizer -// - -STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) -{ - int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning - if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) { - // e.g. space character - if (ix0) *ix0 = 0; - if (iy0) *iy0 = 0; - if (ix1) *ix1 = 0; - if (iy1) *iy1 = 0; - } else { - // move to integral bboxes (treating pixels as little squares, what pixels get touched)? - if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x); - if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y); - if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x); - if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y); - } -} - -STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) -{ - stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1); -} - -STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) -{ - stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1); -} - -STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) -{ - stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1); -} - -////////////////////////////////////////////////////////////////////////////// -// -// Rasterizer - -typedef struct stbtt__hheap_chunk -{ - struct stbtt__hheap_chunk *next; -} stbtt__hheap_chunk; - -typedef struct stbtt__hheap -{ - struct stbtt__hheap_chunk *head; - void *first_free; - int num_remaining_in_head_chunk; -} stbtt__hheap; - -static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata) -{ - if (hh->first_free) { - void *p = hh->first_free; - hh->first_free = * (void **) p; - return p; - } else { - if (hh->num_remaining_in_head_chunk == 0) { - int count = (size < 32 ? 2000 : size < 128 ? 800 : 100); - stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata); - if (c == NULL) - return NULL; - c->next = hh->head; - hh->head = c; - hh->num_remaining_in_head_chunk = count; - } - --hh->num_remaining_in_head_chunk; - return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk; - } -} - -static void stbtt__hheap_free(stbtt__hheap *hh, void *p) -{ - *(void **) p = hh->first_free; - hh->first_free = p; -} - -static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata) -{ - stbtt__hheap_chunk *c = hh->head; - while (c) { - stbtt__hheap_chunk *n = c->next; - STBTT_free(c, userdata); - c = n; - } -} - -typedef struct stbtt__edge { - float x0,y0, x1,y1; - int invert; -} stbtt__edge; - - -typedef struct stbtt__active_edge -{ - struct stbtt__active_edge *next; - #if STBTT_RASTERIZER_VERSION==1 - int x,dx; - float ey; - int direction; - #elif STBTT_RASTERIZER_VERSION==2 - float fx,fdx,fdy; - float direction; - float sy; - float ey; - #else - #error "Unrecognized value of STBTT_RASTERIZER_VERSION" - #endif -} stbtt__active_edge; - -#if STBTT_RASTERIZER_VERSION == 1 -#define STBTT_FIXSHIFT 10 -#define STBTT_FIX (1 << STBTT_FIXSHIFT) -#define STBTT_FIXMASK (STBTT_FIX-1) - -static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) -{ - stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); - float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); - STBTT_assert(z != NULL); - if (!z) return z; - - // round dx down to avoid overshooting - if (dxdy < 0) - z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy); - else - z->dx = STBTT_ifloor(STBTT_FIX * dxdy); - - z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount - z->x -= off_x * STBTT_FIX; - - z->ey = e->y1; - z->next = 0; - z->direction = e->invert ? 1 : -1; - return z; -} -#elif STBTT_RASTERIZER_VERSION == 2 -static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) -{ - stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); - float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); - STBTT_assert(z != NULL); - //STBTT_assert(e->y0 <= start_point); - if (!z) return z; - z->fdx = dxdy; - z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f; - z->fx = e->x0 + dxdy * (start_point - e->y0); - z->fx -= off_x; - z->direction = e->invert ? 1.0f : -1.0f; - z->sy = e->y0; - z->ey = e->y1; - z->next = 0; - return z; -} -#else -#error "Unrecognized value of STBTT_RASTERIZER_VERSION" -#endif - -#if STBTT_RASTERIZER_VERSION == 1 -// note: this routine clips fills that extend off the edges... ideally this -// wouldn't happen, but it could happen if the truetype glyph bounding boxes -// are wrong, or if the user supplies a too-small bitmap -static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight) -{ - // non-zero winding fill - int x0=0, w=0; - - while (e) { - if (w == 0) { - // if we're currently at zero, we need to record the edge start point - x0 = e->x; w += e->direction; - } else { - int x1 = e->x; w += e->direction; - // if we went to zero, we need to draw - if (w == 0) { - int i = x0 >> STBTT_FIXSHIFT; - int j = x1 >> STBTT_FIXSHIFT; - - if (i < len && j >= 0) { - if (i == j) { - // x0,x1 are the same pixel, so compute combined coverage - scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT); - } else { - if (i >= 0) // add antialiasing for x0 - scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT); - else - i = -1; // clip - - if (j < len) // add antialiasing for x1 - scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT); - else - j = len; // clip - - for (++i; i < j; ++i) // fill pixels between x0 and x1 - scanline[i] = scanline[i] + (stbtt_uint8) max_weight; - } - } - } - } - - e = e->next; - } -} - -static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) -{ - stbtt__hheap hh = { 0, 0, 0 }; - stbtt__active_edge *active = NULL; - int y,j=0; - int max_weight = (255 / vsubsample); // weight per vertical scanline - int s; // vertical subsample index - unsigned char scanline_data[512], *scanline; - - if (result->w > 512) - scanline = (unsigned char *) STBTT_malloc(result->w, userdata); - else - scanline = scanline_data; - - y = off_y * vsubsample; - e[n].y0 = (off_y + result->h) * (float) vsubsample + 1; - - while (j < result->h) { - STBTT_memset(scanline, 0, result->w); - for (s=0; s < vsubsample; ++s) { - // find center of pixel for this scanline - float scan_y = y + 0.5f; - stbtt__active_edge **step = &active; - - // update all active edges; - // remove all active edges that terminate before the center of this scanline - while (*step) { - stbtt__active_edge * z = *step; - if (z->ey <= scan_y) { - *step = z->next; // delete from list - STBTT_assert(z->direction); - z->direction = 0; - stbtt__hheap_free(&hh, z); - } else { - z->x += z->dx; // advance to position for current scanline - step = &((*step)->next); // advance through list - } - } - - // resort the list if needed - for(;;) { - int changed=0; - step = &active; - while (*step && (*step)->next) { - if ((*step)->x > (*step)->next->x) { - stbtt__active_edge *t = *step; - stbtt__active_edge *q = t->next; - - t->next = q->next; - q->next = t; - *step = q; - changed = 1; - } - step = &(*step)->next; - } - if (!changed) break; - } - - // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline - while (e->y0 <= scan_y) { - if (e->y1 > scan_y) { - stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata); - if (z != NULL) { - // find insertion point - if (active == NULL) - active = z; - else if (z->x < active->x) { - // insert at front - z->next = active; - active = z; - } else { - // find thing to insert AFTER - stbtt__active_edge *p = active; - while (p->next && p->next->x < z->x) - p = p->next; - // at this point, p->next->x is NOT < z->x - z->next = p->next; - p->next = z; - } - } - } - ++e; - } - - // now process all active edges in XOR fashion - if (active) - stbtt__fill_active_edges(scanline, result->w, active, max_weight); - - ++y; - } - STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w); - ++j; - } - - stbtt__hheap_cleanup(&hh, userdata); - - if (scanline != scanline_data) - STBTT_free(scanline, userdata); -} - -#elif STBTT_RASTERIZER_VERSION == 2 - -// the edge passed in here does not cross the vertical line at x or the vertical line at x+1 -// (i.e. it has already been clipped to those) -static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1) -{ - if (y0 == y1) return; - STBTT_assert(y0 < y1); - STBTT_assert(e->sy <= e->ey); - if (y0 > e->ey) return; - if (y1 < e->sy) return; - if (y0 < e->sy) { - x0 += (x1-x0) * (e->sy - y0) / (y1-y0); - y0 = e->sy; - } - if (y1 > e->ey) { - x1 += (x1-x0) * (e->ey - y1) / (y1-y0); - y1 = e->ey; - } - - if (x0 == x) - STBTT_assert(x1 <= x+1); - else if (x0 == x+1) - STBTT_assert(x1 >= x); - else if (x0 <= x) - STBTT_assert(x1 <= x); - else if (x0 >= x+1) - STBTT_assert(x1 >= x+1); - else - STBTT_assert(x1 >= x && x1 <= x+1); - - if (x0 <= x && x1 <= x) - scanline[x] += e->direction * (y1-y0); - else if (x0 >= x+1 && x1 >= x+1) - ; - else { - STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1); - scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position - } -} - -static float stbtt__sized_trapezoid_area(float height, float top_width, float bottom_width) -{ - STBTT_assert(top_width >= 0); - STBTT_assert(bottom_width >= 0); - return (top_width + bottom_width) / 2.0f * height; -} - -static float stbtt__position_trapezoid_area(float height, float tx0, float tx1, float bx0, float bx1) -{ - return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0); -} - -static float stbtt__sized_triangle_area(float height, float width) -{ - return height * width / 2; -} - -static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top) -{ - float y_bottom = y_top+1; - - while (e) { - // brute force every pixel - - // compute intersection points with top & bottom - STBTT_assert(e->ey >= y_top); - - if (e->fdx == 0) { - float x0 = e->fx; - if (x0 < len) { - if (x0 >= 0) { - stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom); - stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom); - } else { - stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom); - } - } - } else { - float x0 = e->fx; - float dx = e->fdx; - float xb = x0 + dx; - float x_top, x_bottom; - float sy0,sy1; - float dy = e->fdy; - STBTT_assert(e->sy <= y_bottom && e->ey >= y_top); - - // compute endpoints of line segment clipped to this scanline (if the - // line segment starts on this scanline. x0 is the intersection of the - // line with y_top, but that may be off the line segment. - if (e->sy > y_top) { - x_top = x0 + dx * (e->sy - y_top); - sy0 = e->sy; - } else { - x_top = x0; - sy0 = y_top; - } - if (e->ey < y_bottom) { - x_bottom = x0 + dx * (e->ey - y_top); - sy1 = e->ey; - } else { - x_bottom = xb; - sy1 = y_bottom; - } - - if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) { - // from here on, we don't have to range check x values - - if ((int) x_top == (int) x_bottom) { - float height; - // simple case, only spans one pixel - int x = (int) x_top; - height = (sy1 - sy0) * e->direction; - STBTT_assert(x >= 0 && x < len); - scanline[x] += stbtt__position_trapezoid_area(height, x_top, x+1.0f, x_bottom, x+1.0f); - scanline_fill[x] += height; // everything right of this pixel is filled - } else { - int x,x1,x2; - float y_crossing, y_final, step, sign, area; - // covers 2+ pixels - if (x_top > x_bottom) { - // flip scanline vertically; signed area is the same - float t; - sy0 = y_bottom - (sy0 - y_top); - sy1 = y_bottom - (sy1 - y_top); - t = sy0, sy0 = sy1, sy1 = t; - t = x_bottom, x_bottom = x_top, x_top = t; - dx = -dx; - dy = -dy; - t = x0, x0 = xb, xb = t; - } - STBTT_assert(dy >= 0); - STBTT_assert(dx >= 0); - - x1 = (int) x_top; - x2 = (int) x_bottom; - // compute intersection with y axis at x1+1 - y_crossing = y_top + dy * (x1+1 - x0); - - // compute intersection with y axis at x2 - y_final = y_top + dy * (x2 - x0); - - // x1 x_top x2 x_bottom - // y_top +------|-----+------------+------------+--------|---+------------+ - // | | | | | | - // | | | | | | - // sy0 | Txxxxx|............|............|............|............| - // y_crossing | *xxxxx.......|............|............|............| - // | | xxxxx..|............|............|............| - // | | /- xx*xxxx........|............|............| - // | | dy < | xxxxxx..|............|............| - // y_final | | \- | xx*xxx.........|............| - // sy1 | | | | xxxxxB...|............| - // | | | | | | - // | | | | | | - // y_bottom +------------+------------+------------+------------+------------+ - // - // goal is to measure the area covered by '.' in each pixel - - // if x2 is right at the right edge of x1, y_crossing can blow up, github #1057 - // @TODO: maybe test against sy1 rather than y_bottom? - if (y_crossing > y_bottom) - y_crossing = y_bottom; - - sign = e->direction; - - // area of the rectangle covered from sy0..y_crossing - area = sign * (y_crossing-sy0); - - // area of the triangle (x_top,sy0), (x1+1,sy0), (x1+1,y_crossing) - scanline[x1] += stbtt__sized_triangle_area(area, x1+1 - x_top); - - // check if final y_crossing is blown up; no test case for this - if (y_final > y_bottom) { - y_final = y_bottom; - dy = (y_final - y_crossing ) / (x2 - (x1+1)); // if denom=0, y_final = y_crossing, so y_final <= y_bottom - } - - // in second pixel, area covered by line segment found in first pixel - // is always a rectangle 1 wide * the height of that line segment; this - // is exactly what the variable 'area' stores. it also gets a contribution - // from the line segment within it. the THIRD pixel will get the first - // pixel's rectangle contribution, the second pixel's rectangle contribution, - // and its own contribution. the 'own contribution' is the same in every pixel except - // the leftmost and rightmost, a trapezoid that slides down in each pixel. - // the second pixel's contribution to the third pixel will be the - // rectangle 1 wide times the height change in the second pixel, which is dy. - - step = sign * dy * 1; // dy is dy/dx, change in y for every 1 change in x, - // which multiplied by 1-pixel-width is how much pixel area changes for each step in x - // so the area advances by 'step' every time - - for (x = x1+1; x < x2; ++x) { - scanline[x] += area + step/2; // area of trapezoid is 1*step/2 - area += step; - } - STBTT_assert(STBTT_fabs(area) <= 1.01f); // accumulated error from area += step unless we round step down - STBTT_assert(sy1 > y_final-0.01f); - - // area covered in the last pixel is the rectangle from all the pixels to the left, - // plus the trapezoid filled by the line segment in this pixel all the way to the right edge - scanline[x2] += area + sign * stbtt__position_trapezoid_area(sy1-y_final, (float) x2, x2+1.0f, x_bottom, x2+1.0f); - - // the rest of the line is filled based on the total height of the line segment in this pixel - scanline_fill[x2] += sign * (sy1-sy0); - } - } else { - // if edge goes outside of box we're drawing, we require - // clipping logic. since this does not match the intended use - // of this library, we use a different, very slow brute - // force implementation - // note though that this does happen some of the time because - // x_top and x_bottom can be extrapolated at the top & bottom of - // the shape and actually lie outside the bounding box - int x; - for (x=0; x < len; ++x) { - // cases: - // - // there can be up to two intersections with the pixel. any intersection - // with left or right edges can be handled by splitting into two (or three) - // regions. intersections with top & bottom do not necessitate case-wise logic. - // - // the old way of doing this found the intersections with the left & right edges, - // then used some simple logic to produce up to three segments in sorted order - // from top-to-bottom. however, this had a problem: if an x edge was epsilon - // across the x border, then the corresponding y position might not be distinct - // from the other y segment, and it might ignored as an empty segment. to avoid - // that, we need to explicitly produce segments based on x positions. - - // rename variables to clearly-defined pairs - float y0 = y_top; - float x1 = (float) (x); - float x2 = (float) (x+1); - float x3 = xb; - float y3 = y_bottom; - - // x = e->x + e->dx * (y-y_top) - // (y-y_top) = (x - e->x) / e->dx - // y = (x - e->x) / e->dx + y_top - float y1 = (x - x0) / dx + y_top; - float y2 = (x+1 - x0) / dx + y_top; - - if (x0 < x1 && x3 > x2) { // three segments descending down-right - stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); - stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2); - stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); - } else if (x3 < x1 && x0 > x2) { // three segments descending down-left - stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); - stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1); - stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); - } else if (x0 < x1 && x3 > x1) { // two segments across x, down-right - stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); - stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); - } else if (x3 < x1 && x0 > x1) { // two segments across x, down-left - stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); - stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); - } else if (x0 < x2 && x3 > x2) { // two segments across x+1, down-right - stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); - stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); - } else if (x3 < x2 && x0 > x2) { // two segments across x+1, down-left - stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); - stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); - } else { // one segment - stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3); - } - } - } - } - e = e->next; - } -} - -// directly AA rasterize edges w/o supersampling -static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) -{ - stbtt__hheap hh = { 0, 0, 0 }; - stbtt__active_edge *active = NULL; - int y,j=0, i; - float scanline_data[129], *scanline, *scanline2; - - STBTT__NOTUSED(vsubsample); - - if (result->w > 64) - scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata); - else - scanline = scanline_data; - - scanline2 = scanline + result->w; - - y = off_y; - e[n].y0 = (float) (off_y + result->h) + 1; - - while (j < result->h) { - // find center of pixel for this scanline - float scan_y_top = y + 0.0f; - float scan_y_bottom = y + 1.0f; - stbtt__active_edge **step = &active; - - STBTT_memset(scanline , 0, result->w*sizeof(scanline[0])); - STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0])); - - // update all active edges; - // remove all active edges that terminate before the top of this scanline - while (*step) { - stbtt__active_edge * z = *step; - if (z->ey <= scan_y_top) { - *step = z->next; // delete from list - STBTT_assert(z->direction); - z->direction = 0; - stbtt__hheap_free(&hh, z); - } else { - step = &((*step)->next); // advance through list - } - } - - // insert all edges that start before the bottom of this scanline - while (e->y0 <= scan_y_bottom) { - if (e->y0 != e->y1) { - stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata); - if (z != NULL) { - if (j == 0 && off_y != 0) { - if (z->ey < scan_y_top) { - // this can happen due to subpixel positioning and some kind of fp rounding error i think - z->ey = scan_y_top; - } - } - STBTT_assert(z->ey >= scan_y_top); // if we get really unlucky a tiny bit of an edge can be out of bounds - // insert at front - z->next = active; - active = z; - } - } - ++e; - } - - // now process all active edges - if (active) - stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top); - - { - float sum = 0; - for (i=0; i < result->w; ++i) { - float k; - int m; - sum += scanline2[i]; - k = scanline[i] + sum; - k = (float) STBTT_fabs(k)*255 + 0.5f; - m = (int) k; - if (m > 255) m = 255; - result->pixels[j*result->stride + i] = (unsigned char) m; - } - } - // advance all the edges - step = &active; - while (*step) { - stbtt__active_edge *z = *step; - z->fx += z->fdx; // advance to position for current scanline - step = &((*step)->next); // advance through list - } - - ++y; - ++j; - } - - stbtt__hheap_cleanup(&hh, userdata); - - if (scanline != scanline_data) - STBTT_free(scanline, userdata); -} -#else -#error "Unrecognized value of STBTT_RASTERIZER_VERSION" -#endif - -#define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0) - -static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n) -{ - int i,j; - for (i=1; i < n; ++i) { - stbtt__edge t = p[i], *a = &t; - j = i; - while (j > 0) { - stbtt__edge *b = &p[j-1]; - int c = STBTT__COMPARE(a,b); - if (!c) break; - p[j] = p[j-1]; - --j; - } - if (i != j) - p[j] = t; - } -} - -static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n) -{ - /* threshold for transitioning to insertion sort */ - while (n > 12) { - stbtt__edge t; - int c01,c12,c,m,i,j; - - /* compute median of three */ - m = n >> 1; - c01 = STBTT__COMPARE(&p[0],&p[m]); - c12 = STBTT__COMPARE(&p[m],&p[n-1]); - /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ - if (c01 != c12) { - /* otherwise, we'll need to swap something else to middle */ - int z; - c = STBTT__COMPARE(&p[0],&p[n-1]); - /* 0>mid && midn => n; 0 0 */ - /* 0n: 0>n => 0; 0 n */ - z = (c == c12) ? 0 : n-1; - t = p[z]; - p[z] = p[m]; - p[m] = t; - } - /* now p[m] is the median-of-three */ - /* swap it to the beginning so it won't move around */ - t = p[0]; - p[0] = p[m]; - p[m] = t; - - /* partition loop */ - i=1; - j=n-1; - for(;;) { - /* handling of equality is crucial here */ - /* for sentinels & efficiency with duplicates */ - for (;;++i) { - if (!STBTT__COMPARE(&p[i], &p[0])) break; - } - for (;;--j) { - if (!STBTT__COMPARE(&p[0], &p[j])) break; - } - /* make sure we haven't crossed */ - if (i >= j) break; - t = p[i]; - p[i] = p[j]; - p[j] = t; - - ++i; - --j; - } - /* recurse on smaller side, iterate on larger */ - if (j < (n-i)) { - stbtt__sort_edges_quicksort(p,j); - p = p+i; - n = n-i; - } else { - stbtt__sort_edges_quicksort(p+i, n-i); - n = j; - } - } -} - -static void stbtt__sort_edges(stbtt__edge *p, int n) -{ - stbtt__sort_edges_quicksort(p, n); - stbtt__sort_edges_ins_sort(p, n); -} - -typedef struct -{ - float x,y; -} stbtt__point; - -static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata) -{ - float y_scale_inv = invert ? -scale_y : scale_y; - stbtt__edge *e; - int n,i,j,k,m; -#if STBTT_RASTERIZER_VERSION == 1 - int vsubsample = result->h < 8 ? 15 : 5; -#elif STBTT_RASTERIZER_VERSION == 2 - int vsubsample = 1; -#else - #error "Unrecognized value of STBTT_RASTERIZER_VERSION" -#endif - // vsubsample should divide 255 evenly; otherwise we won't reach full opacity - - // now we have to blow out the windings into explicit edge lists - n = 0; - for (i=0; i < windings; ++i) - n += wcount[i]; - - e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel - if (e == 0) return; - n = 0; - - m=0; - for (i=0; i < windings; ++i) { - stbtt__point *p = pts + m; - m += wcount[i]; - j = wcount[i]-1; - for (k=0; k < wcount[i]; j=k++) { - int a=k,b=j; - // skip the edge if horizontal - if (p[j].y == p[k].y) - continue; - // add edge from j to k to the list - e[n].invert = 0; - if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) { - e[n].invert = 1; - a=j,b=k; - } - e[n].x0 = p[a].x * scale_x + shift_x; - e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample; - e[n].x1 = p[b].x * scale_x + shift_x; - e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample; - ++n; - } - } - - // now sort the edges by their highest point (should snap to integer, and then by x) - //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); - stbtt__sort_edges(e, n); - - // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule - stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata); - - STBTT_free(e, userdata); -} - -static void stbtt__add_point(stbtt__point *points, int n, float x, float y) -{ - if (!points) return; // during first pass, it's unallocated - points[n].x = x; - points[n].y = y; -} - -// tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching -static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n) -{ - // midpoint - float mx = (x0 + 2*x1 + x2)/4; - float my = (y0 + 2*y1 + y2)/4; - // versus directly drawn line - float dx = (x0+x2)/2 - mx; - float dy = (y0+y2)/2 - my; - if (n > 16) // 65536 segments on one curve better be enough! - return 1; - if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA - stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1); - stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1); - } else { - stbtt__add_point(points, *num_points,x2,y2); - *num_points = *num_points+1; - } - return 1; -} - -static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n) -{ - // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough - float dx0 = x1-x0; - float dy0 = y1-y0; - float dx1 = x2-x1; - float dy1 = y2-y1; - float dx2 = x3-x2; - float dy2 = y3-y2; - float dx = x3-x0; - float dy = y3-y0; - float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2)); - float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy); - float flatness_squared = longlen*longlen-shortlen*shortlen; - - if (n > 16) // 65536 segments on one curve better be enough! - return; - - if (flatness_squared > objspace_flatness_squared) { - float x01 = (x0+x1)/2; - float y01 = (y0+y1)/2; - float x12 = (x1+x2)/2; - float y12 = (y1+y2)/2; - float x23 = (x2+x3)/2; - float y23 = (y2+y3)/2; - - float xa = (x01+x12)/2; - float ya = (y01+y12)/2; - float xb = (x12+x23)/2; - float yb = (y12+y23)/2; - - float mx = (xa+xb)/2; - float my = (ya+yb)/2; - - stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1); - stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1); - } else { - stbtt__add_point(points, *num_points,x3,y3); - *num_points = *num_points+1; - } -} - -// returns number of contours -static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata) -{ - stbtt__point *points=0; - int num_points=0; - - float objspace_flatness_squared = objspace_flatness * objspace_flatness; - int i,n=0,start=0, pass; - - // count how many "moves" there are to get the contour count - for (i=0; i < num_verts; ++i) - if (vertices[i].type == STBTT_vmove) - ++n; - - *num_contours = n; - if (n == 0) return 0; - - *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata); - - if (*contour_lengths == 0) { - *num_contours = 0; - return 0; - } - - // make two passes through the points so we don't need to realloc - for (pass=0; pass < 2; ++pass) { - float x=0,y=0; - if (pass == 1) { - points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata); - if (points == NULL) goto error; - } - num_points = 0; - n= -1; - for (i=0; i < num_verts; ++i) { - switch (vertices[i].type) { - case STBTT_vmove: - // start the next contour - if (n >= 0) - (*contour_lengths)[n] = num_points - start; - ++n; - start = num_points; - - x = vertices[i].x, y = vertices[i].y; - stbtt__add_point(points, num_points++, x,y); - break; - case STBTT_vline: - x = vertices[i].x, y = vertices[i].y; - stbtt__add_point(points, num_points++, x, y); - break; - case STBTT_vcurve: - stbtt__tesselate_curve(points, &num_points, x,y, - vertices[i].cx, vertices[i].cy, - vertices[i].x, vertices[i].y, - objspace_flatness_squared, 0); - x = vertices[i].x, y = vertices[i].y; - break; - case STBTT_vcubic: - stbtt__tesselate_cubic(points, &num_points, x,y, - vertices[i].cx, vertices[i].cy, - vertices[i].cx1, vertices[i].cy1, - vertices[i].x, vertices[i].y, - objspace_flatness_squared, 0); - x = vertices[i].x, y = vertices[i].y; - break; - } - } - (*contour_lengths)[n] = num_points - start; - } - - return points; -error: - STBTT_free(points, userdata); - STBTT_free(*contour_lengths, userdata); - *contour_lengths = 0; - *num_contours = 0; - return NULL; -} - -STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata) -{ - float scale = scale_x > scale_y ? scale_y : scale_x; - int winding_count = 0; - int *winding_lengths = NULL; - stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata); - if (windings) { - stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata); - STBTT_free(winding_lengths, userdata); - STBTT_free(windings, userdata); - } -} - -STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata) -{ - STBTT_free(bitmap, userdata); -} - -STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff) -{ - int ix0,iy0,ix1,iy1; - stbtt__bitmap gbm; - stbtt_vertex *vertices; - int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); - - if (scale_x == 0) scale_x = scale_y; - if (scale_y == 0) { - if (scale_x == 0) { - STBTT_free(vertices, info->userdata); - return NULL; - } - scale_y = scale_x; - } - - stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1); - - // now we get the size - gbm.w = (ix1 - ix0); - gbm.h = (iy1 - iy0); - gbm.pixels = NULL; // in case we error - - if (width ) *width = gbm.w; - if (height) *height = gbm.h; - if (xoff ) *xoff = ix0; - if (yoff ) *yoff = iy0; - - if (gbm.w && gbm.h) { - gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata); - if (gbm.pixels) { - gbm.stride = gbm.w; - - stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata); - } - } - STBTT_free(vertices, info->userdata); - return gbm.pixels; -} - -STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff) -{ - return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff); -} - -STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph) -{ - int ix0,iy0; - stbtt_vertex *vertices; - int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); - stbtt__bitmap gbm; - - stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0); - gbm.pixels = output; - gbm.w = out_w; - gbm.h = out_h; - gbm.stride = out_stride; - - if (gbm.w && gbm.h) - stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata); - - STBTT_free(vertices, info->userdata); -} - -STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph) -{ - stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph); -} - -STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff) -{ - return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff); -} - -STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint) -{ - stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint)); -} - -STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint) -{ - stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint)); -} - -STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff) -{ - return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff); -} - -STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint) -{ - stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint); -} - -////////////////////////////////////////////////////////////////////////////// -// -// bitmap baking -// -// This is SUPER-CRAPPY packing to keep source code small - -static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) - float pixel_height, // height of font in pixels - unsigned char *pixels, int pw, int ph, // bitmap to be filled in - int first_char, int num_chars, // characters to bake - stbtt_bakedchar *chardata) -{ - float scale; - int x,y,bottom_y, i; - stbtt_fontinfo f; - f.userdata = NULL; - if (!stbtt_InitFont(&f, data, offset)) - return -1; - STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels - x=y=1; - bottom_y = 1; - - scale = stbtt_ScaleForPixelHeight(&f, pixel_height); - - for (i=0; i < num_chars; ++i) { - int advance, lsb, x0,y0,x1,y1,gw,gh; - int g = stbtt_FindGlyphIndex(&f, first_char + i); - stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb); - stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1); - gw = x1-x0; - gh = y1-y0; - if (x + gw + 1 >= pw) - y = bottom_y, x = 1; // advance to next row - if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row - return -i; - STBTT_assert(x+gw < pw); - STBTT_assert(y+gh < ph); - stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g); - chardata[i].x0 = (stbtt_int16) x; - chardata[i].y0 = (stbtt_int16) y; - chardata[i].x1 = (stbtt_int16) (x + gw); - chardata[i].y1 = (stbtt_int16) (y + gh); - chardata[i].xadvance = scale * advance; - chardata[i].xoff = (float) x0; - chardata[i].yoff = (float) y0; - x = x + gw + 1; - if (y+gh+1 > bottom_y) - bottom_y = y+gh+1; - } - return bottom_y; -} - -STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule) -{ - float d3d_bias = opengl_fillrule ? 0 : -0.5f; - float ipw = 1.0f / pw, iph = 1.0f / ph; - const stbtt_bakedchar *b = chardata + char_index; - int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f); - int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f); - - q->x0 = round_x + d3d_bias; - q->y0 = round_y + d3d_bias; - q->x1 = round_x + b->x1 - b->x0 + d3d_bias; - q->y1 = round_y + b->y1 - b->y0 + d3d_bias; - - q->s0 = b->x0 * ipw; - q->t0 = b->y0 * iph; - q->s1 = b->x1 * ipw; - q->t1 = b->y1 * iph; - - *xpos += b->xadvance; -} - -////////////////////////////////////////////////////////////////////////////// -// -// rectangle packing replacement routines if you don't have stb_rect_pack.h -// - -#ifndef STB_RECT_PACK_VERSION - -typedef int stbrp_coord; - -//////////////////////////////////////////////////////////////////////////////////// -// // -// // -// COMPILER WARNING ?!?!? // -// // -// // -// if you get a compile warning due to these symbols being defined more than // -// once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" // -// // -//////////////////////////////////////////////////////////////////////////////////// - -typedef struct -{ - int width,height; - int x,y,bottom_y; -} stbrp_context; - -typedef struct -{ - unsigned char x; -} stbrp_node; - -struct stbrp_rect -{ - stbrp_coord x,y; - int id,w,h,was_packed; -}; - -static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes) -{ - con->width = pw; - con->height = ph; - con->x = 0; - con->y = 0; - con->bottom_y = 0; - STBTT__NOTUSED(nodes); - STBTT__NOTUSED(num_nodes); -} - -static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects) -{ - int i; - for (i=0; i < num_rects; ++i) { - if (con->x + rects[i].w > con->width) { - con->x = 0; - con->y = con->bottom_y; - } - if (con->y + rects[i].h > con->height) - break; - rects[i].x = con->x; - rects[i].y = con->y; - rects[i].was_packed = 1; - con->x += rects[i].w; - if (con->y + rects[i].h > con->bottom_y) - con->bottom_y = con->y + rects[i].h; - } - for ( ; i < num_rects; ++i) - rects[i].was_packed = 0; -} -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// bitmap baking -// -// This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If -// stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy. - -STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context) -{ - stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context); - int num_nodes = pw - padding; - stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context); - - if (context == NULL || nodes == NULL) { - if (context != NULL) STBTT_free(context, alloc_context); - if (nodes != NULL) STBTT_free(nodes , alloc_context); - return 0; - } - - spc->user_allocator_context = alloc_context; - spc->width = pw; - spc->height = ph; - spc->pixels = pixels; - spc->pack_info = context; - spc->nodes = nodes; - spc->padding = padding; - spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw; - spc->h_oversample = 1; - spc->v_oversample = 1; - spc->skip_missing = 0; - - stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes); - - if (pixels) - STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels - - return 1; -} - -STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc) -{ - STBTT_free(spc->nodes , spc->user_allocator_context); - STBTT_free(spc->pack_info, spc->user_allocator_context); -} - -STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample) -{ - STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE); - STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE); - if (h_oversample <= STBTT_MAX_OVERSAMPLE) - spc->h_oversample = h_oversample; - if (v_oversample <= STBTT_MAX_OVERSAMPLE) - spc->v_oversample = v_oversample; -} - -STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip) -{ - spc->skip_missing = skip; -} - -#define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1) - -static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) -{ - unsigned char buffer[STBTT_MAX_OVERSAMPLE]; - int safe_w = w - kernel_width; - int j; - STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze - for (j=0; j < h; ++j) { - int i; - unsigned int total; - STBTT_memset(buffer, 0, kernel_width); - - total = 0; - - // make kernel_width a constant in common cases so compiler can optimize out the divide - switch (kernel_width) { - case 2: - for (i=0; i <= safe_w; ++i) { - total += pixels[i] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; - pixels[i] = (unsigned char) (total / 2); - } - break; - case 3: - for (i=0; i <= safe_w; ++i) { - total += pixels[i] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; - pixels[i] = (unsigned char) (total / 3); - } - break; - case 4: - for (i=0; i <= safe_w; ++i) { - total += pixels[i] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; - pixels[i] = (unsigned char) (total / 4); - } - break; - case 5: - for (i=0; i <= safe_w; ++i) { - total += pixels[i] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; - pixels[i] = (unsigned char) (total / 5); - } - break; - default: - for (i=0; i <= safe_w; ++i) { - total += pixels[i] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; - pixels[i] = (unsigned char) (total / kernel_width); - } - break; - } - - for (; i < w; ++i) { - STBTT_assert(pixels[i] == 0); - total -= buffer[i & STBTT__OVER_MASK]; - pixels[i] = (unsigned char) (total / kernel_width); - } - - pixels += stride_in_bytes; - } -} - -static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) -{ - unsigned char buffer[STBTT_MAX_OVERSAMPLE]; - int safe_h = h - kernel_width; - int j; - STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze - for (j=0; j < w; ++j) { - int i; - unsigned int total; - STBTT_memset(buffer, 0, kernel_width); - - total = 0; - - // make kernel_width a constant in common cases so compiler can optimize out the divide - switch (kernel_width) { - case 2: - for (i=0; i <= safe_h; ++i) { - total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; - pixels[i*stride_in_bytes] = (unsigned char) (total / 2); - } - break; - case 3: - for (i=0; i <= safe_h; ++i) { - total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; - pixels[i*stride_in_bytes] = (unsigned char) (total / 3); - } - break; - case 4: - for (i=0; i <= safe_h; ++i) { - total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; - pixels[i*stride_in_bytes] = (unsigned char) (total / 4); - } - break; - case 5: - for (i=0; i <= safe_h; ++i) { - total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; - pixels[i*stride_in_bytes] = (unsigned char) (total / 5); - } - break; - default: - for (i=0; i <= safe_h; ++i) { - total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; - buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; - pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); - } - break; - } - - for (; i < h; ++i) { - STBTT_assert(pixels[i*stride_in_bytes] == 0); - total -= buffer[i & STBTT__OVER_MASK]; - pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); - } - - pixels += 1; - } -} - -static float stbtt__oversample_shift(int oversample) -{ - if (!oversample) - return 0.0f; - - // The prefilter is a box filter of width "oversample", - // which shifts phase by (oversample - 1)/2 pixels in - // oversampled space. We want to shift in the opposite - // direction to counter this. - return (float)-(oversample - 1) / (2.0f * (float)oversample); -} - -// rects array must be big enough to accommodate all characters in the given ranges -STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) -{ - int i,j,k; - int missing_glyph_added = 0; - - k=0; - for (i=0; i < num_ranges; ++i) { - float fh = ranges[i].font_size; - float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); - ranges[i].h_oversample = (unsigned char) spc->h_oversample; - ranges[i].v_oversample = (unsigned char) spc->v_oversample; - for (j=0; j < ranges[i].num_chars; ++j) { - int x0,y0,x1,y1; - int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; - int glyph = stbtt_FindGlyphIndex(info, codepoint); - if (glyph == 0 && (spc->skip_missing || missing_glyph_added)) { - rects[k].w = rects[k].h = 0; - } else { - stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, - scale * spc->h_oversample, - scale * spc->v_oversample, - 0,0, - &x0,&y0,&x1,&y1); - rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1); - rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1); - if (glyph == 0) - missing_glyph_added = 1; - } - ++k; - } - } - - return k; -} - -STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph) -{ - stbtt_MakeGlyphBitmapSubpixel(info, - output, - out_w - (prefilter_x - 1), - out_h - (prefilter_y - 1), - out_stride, - scale_x, - scale_y, - shift_x, - shift_y, - glyph); - - if (prefilter_x > 1) - stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x); - - if (prefilter_y > 1) - stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y); - - *sub_x = stbtt__oversample_shift(prefilter_x); - *sub_y = stbtt__oversample_shift(prefilter_y); -} - -// rects array must be big enough to accommodate all characters in the given ranges -STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) -{ - int i,j,k, missing_glyph = -1, return_value = 1; - - // save current values - int old_h_over = spc->h_oversample; - int old_v_over = spc->v_oversample; - - k = 0; - for (i=0; i < num_ranges; ++i) { - float fh = ranges[i].font_size; - float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); - float recip_h,recip_v,sub_x,sub_y; - spc->h_oversample = ranges[i].h_oversample; - spc->v_oversample = ranges[i].v_oversample; - recip_h = 1.0f / spc->h_oversample; - recip_v = 1.0f / spc->v_oversample; - sub_x = stbtt__oversample_shift(spc->h_oversample); - sub_y = stbtt__oversample_shift(spc->v_oversample); - for (j=0; j < ranges[i].num_chars; ++j) { - stbrp_rect *r = &rects[k]; - if (r->was_packed && r->w != 0 && r->h != 0) { - stbtt_packedchar *bc = &ranges[i].chardata_for_range[j]; - int advance, lsb, x0,y0,x1,y1; - int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; - int glyph = stbtt_FindGlyphIndex(info, codepoint); - stbrp_coord pad = (stbrp_coord) spc->padding; - - // pad on left and top - r->x += pad; - r->y += pad; - r->w -= pad; - r->h -= pad; - stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb); - stbtt_GetGlyphBitmapBox(info, glyph, - scale * spc->h_oversample, - scale * spc->v_oversample, - &x0,&y0,&x1,&y1); - stbtt_MakeGlyphBitmapSubpixel(info, - spc->pixels + r->x + r->y*spc->stride_in_bytes, - r->w - spc->h_oversample+1, - r->h - spc->v_oversample+1, - spc->stride_in_bytes, - scale * spc->h_oversample, - scale * spc->v_oversample, - 0,0, - glyph); - - if (spc->h_oversample > 1) - stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, - r->w, r->h, spc->stride_in_bytes, - spc->h_oversample); - - if (spc->v_oversample > 1) - stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, - r->w, r->h, spc->stride_in_bytes, - spc->v_oversample); - - bc->x0 = (stbtt_int16) r->x; - bc->y0 = (stbtt_int16) r->y; - bc->x1 = (stbtt_int16) (r->x + r->w); - bc->y1 = (stbtt_int16) (r->y + r->h); - bc->xadvance = scale * advance; - bc->xoff = (float) x0 * recip_h + sub_x; - bc->yoff = (float) y0 * recip_v + sub_y; - bc->xoff2 = (x0 + r->w) * recip_h + sub_x; - bc->yoff2 = (y0 + r->h) * recip_v + sub_y; - - if (glyph == 0) - missing_glyph = j; - } else if (spc->skip_missing) { - return_value = 0; - } else if (r->was_packed && r->w == 0 && r->h == 0 && missing_glyph >= 0) { - ranges[i].chardata_for_range[j] = ranges[i].chardata_for_range[missing_glyph]; - } else { - return_value = 0; // if any fail, report failure - } - - ++k; - } - } - - // restore original values - spc->h_oversample = old_h_over; - spc->v_oversample = old_v_over; - - return return_value; -} - -STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects) -{ - stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects); -} - -STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges) -{ - stbtt_fontinfo info; - int i,j,n, return_value = 1; - //stbrp_context *context = (stbrp_context *) spc->pack_info; - stbrp_rect *rects; - - // flag all characters as NOT packed - for (i=0; i < num_ranges; ++i) - for (j=0; j < ranges[i].num_chars; ++j) - ranges[i].chardata_for_range[j].x0 = - ranges[i].chardata_for_range[j].y0 = - ranges[i].chardata_for_range[j].x1 = - ranges[i].chardata_for_range[j].y1 = 0; - - n = 0; - for (i=0; i < num_ranges; ++i) - n += ranges[i].num_chars; - - rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context); - if (rects == NULL) - return 0; - - info.userdata = spc->user_allocator_context; - stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index)); - - n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects); - - stbtt_PackFontRangesPackRects(spc, rects, n); - - return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects); - - STBTT_free(rects, spc->user_allocator_context); - return return_value; -} - -STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, - int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range) -{ - stbtt_pack_range range; - range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range; - range.array_of_unicode_codepoints = NULL; - range.num_chars = num_chars_in_range; - range.chardata_for_range = chardata_for_range; - range.font_size = font_size; - return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1); -} - -STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap) -{ - int i_ascent, i_descent, i_lineGap; - float scale; - stbtt_fontinfo info; - stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index)); - scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size); - stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap); - *ascent = (float) i_ascent * scale; - *descent = (float) i_descent * scale; - *lineGap = (float) i_lineGap * scale; -} - -STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer) -{ - float ipw = 1.0f / pw, iph = 1.0f / ph; - const stbtt_packedchar *b = chardata + char_index; - - if (align_to_integer) { - float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f); - float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f); - q->x0 = x; - q->y0 = y; - q->x1 = x + b->xoff2 - b->xoff; - q->y1 = y + b->yoff2 - b->yoff; - } else { - q->x0 = *xpos + b->xoff; - q->y0 = *ypos + b->yoff; - q->x1 = *xpos + b->xoff2; - q->y1 = *ypos + b->yoff2; - } - - q->s0 = b->x0 * ipw; - q->t0 = b->y0 * iph; - q->s1 = b->x1 * ipw; - q->t1 = b->y1 * iph; - - *xpos += b->xadvance; -} - -////////////////////////////////////////////////////////////////////////////// -// -// sdf computation -// - -#define STBTT_min(a,b) ((a) < (b) ? (a) : (b)) -#define STBTT_max(a,b) ((a) < (b) ? (b) : (a)) - -static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2]) -{ - float q0perp = q0[1]*ray[0] - q0[0]*ray[1]; - float q1perp = q1[1]*ray[0] - q1[0]*ray[1]; - float q2perp = q2[1]*ray[0] - q2[0]*ray[1]; - float roperp = orig[1]*ray[0] - orig[0]*ray[1]; - - float a = q0perp - 2*q1perp + q2perp; - float b = q1perp - q0perp; - float c = q0perp - roperp; - - float s0 = 0., s1 = 0.; - int num_s = 0; - - if (a != 0.0) { - float discr = b*b - a*c; - if (discr > 0.0) { - float rcpna = -1 / a; - float d = (float) STBTT_sqrt(discr); - s0 = (b+d) * rcpna; - s1 = (b-d) * rcpna; - if (s0 >= 0.0 && s0 <= 1.0) - num_s = 1; - if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) { - if (num_s == 0) s0 = s1; - ++num_s; - } - } - } else { - // 2*b*s + c = 0 - // s = -c / (2*b) - s0 = c / (-2 * b); - if (s0 >= 0.0 && s0 <= 1.0) - num_s = 1; - } - - if (num_s == 0) - return 0; - else { - float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]); - float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2; - - float q0d = q0[0]*rayn_x + q0[1]*rayn_y; - float q1d = q1[0]*rayn_x + q1[1]*rayn_y; - float q2d = q2[0]*rayn_x + q2[1]*rayn_y; - float rod = orig[0]*rayn_x + orig[1]*rayn_y; - - float q10d = q1d - q0d; - float q20d = q2d - q0d; - float q0rd = q0d - rod; - - hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d; - hits[0][1] = a*s0+b; - - if (num_s > 1) { - hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d; - hits[1][1] = a*s1+b; - return 2; - } else { - return 1; - } - } -} - -static int equal(float *a, float *b) -{ - return (a[0] == b[0] && a[1] == b[1]); -} - -static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts) -{ - int i; - float orig[2], ray[2] = { 1, 0 }; - float y_frac; - int winding = 0; - - // make sure y never passes through a vertex of the shape - y_frac = (float) STBTT_fmod(y, 1.0f); - if (y_frac < 0.01f) - y += 0.01f; - else if (y_frac > 0.99f) - y -= 0.01f; - - orig[0] = x; - orig[1] = y; - - // test a ray from (-infinity,y) to (x,y) - for (i=0; i < nverts; ++i) { - if (verts[i].type == STBTT_vline) { - int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y; - int x1 = (int) verts[i ].x, y1 = (int) verts[i ].y; - if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { - float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; - if (x_inter < x) - winding += (y0 < y1) ? 1 : -1; - } - } - if (verts[i].type == STBTT_vcurve) { - int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ; - int x1 = (int) verts[i ].cx, y1 = (int) verts[i ].cy; - int x2 = (int) verts[i ].x , y2 = (int) verts[i ].y ; - int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2)); - int by = STBTT_max(y0,STBTT_max(y1,y2)); - if (y > ay && y < by && x > ax) { - float q0[2],q1[2],q2[2]; - float hits[2][2]; - q0[0] = (float)x0; - q0[1] = (float)y0; - q1[0] = (float)x1; - q1[1] = (float)y1; - q2[0] = (float)x2; - q2[1] = (float)y2; - if (equal(q0,q1) || equal(q1,q2)) { - x0 = (int)verts[i-1].x; - y0 = (int)verts[i-1].y; - x1 = (int)verts[i ].x; - y1 = (int)verts[i ].y; - if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { - float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; - if (x_inter < x) - winding += (y0 < y1) ? 1 : -1; - } - } else { - int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits); - if (num_hits >= 1) - if (hits[0][0] < 0) - winding += (hits[0][1] < 0 ? -1 : 1); - if (num_hits >= 2) - if (hits[1][0] < 0) - winding += (hits[1][1] < 0 ? -1 : 1); - } - } - } - } - return winding; -} - -static float stbtt__cuberoot( float x ) -{ - if (x<0) - return -(float) STBTT_pow(-x,1.0f/3.0f); - else - return (float) STBTT_pow( x,1.0f/3.0f); -} - -// x^3 + a*x^2 + b*x + c = 0 -static int stbtt__solve_cubic(float a, float b, float c, float* r) -{ - float s = -a / 3; - float p = b - a*a / 3; - float q = a * (2*a*a - 9*b) / 27 + c; - float p3 = p*p*p; - float d = q*q + 4*p3 / 27; - if (d >= 0) { - float z = (float) STBTT_sqrt(d); - float u = (-q + z) / 2; - float v = (-q - z) / 2; - u = stbtt__cuberoot(u); - v = stbtt__cuberoot(v); - r[0] = s + u + v; - return 1; - } else { - float u = (float) STBTT_sqrt(-p/3); - float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative - float m = (float) STBTT_cos(v); - float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f; - r[0] = s + u * 2 * m; - r[1] = s - u * (m + n); - r[2] = s - u * (m - n); - - //STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe? - //STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f); - //STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f); - return 3; - } -} - -STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) -{ - float scale_x = scale, scale_y = scale; - int ix0,iy0,ix1,iy1; - int w,h; - unsigned char *data; - - if (scale == 0) return NULL; - - stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1); - - // if empty, return NULL - if (ix0 == ix1 || iy0 == iy1) - return NULL; - - ix0 -= padding; - iy0 -= padding; - ix1 += padding; - iy1 += padding; - - w = (ix1 - ix0); - h = (iy1 - iy0); - - if (width ) *width = w; - if (height) *height = h; - if (xoff ) *xoff = ix0; - if (yoff ) *yoff = iy0; - - // invert for y-downwards bitmaps - scale_y = -scale_y; - - { - int x,y,i,j; - float *precompute; - stbtt_vertex *verts; - int num_verts = stbtt_GetGlyphShape(info, glyph, &verts); - data = (unsigned char *) STBTT_malloc(w * h, info->userdata); - precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata); - - for (i=0,j=num_verts-1; i < num_verts; j=i++) { - if (verts[i].type == STBTT_vline) { - float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; - float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y; - float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)); - precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist; - } else if (verts[i].type == STBTT_vcurve) { - float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y; - float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y; - float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y; - float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; - float len2 = bx*bx + by*by; - if (len2 != 0.0f) - precompute[i] = 1.0f / (bx*bx + by*by); - else - precompute[i] = 0.0f; - } else - precompute[i] = 0.0f; - } - - for (y=iy0; y < iy1; ++y) { - for (x=ix0; x < ix1; ++x) { - float val; - float min_dist = 999999.0f; - float sx = (float) x + 0.5f; - float sy = (float) y + 0.5f; - float x_gspace = (sx / scale_x); - float y_gspace = (sy / scale_y); - - int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path - - for (i=0; i < num_verts; ++i) { - float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; - - if (verts[i].type == STBTT_vline && precompute[i] != 0.0f) { - float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y; - - float dist,dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); - if (dist2 < min_dist*min_dist) - min_dist = (float) STBTT_sqrt(dist2); - - // coarse culling against bbox - //if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist && - // sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist) - dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i]; - STBTT_assert(i != 0); - if (dist < min_dist) { - // check position along line - // x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0) - // minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy) - float dx = x1-x0, dy = y1-y0; - float px = x0-sx, py = y0-sy; - // minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy - // derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve - float t = -(px*dx + py*dy) / (dx*dx + dy*dy); - if (t >= 0.0f && t <= 1.0f) - min_dist = dist; - } - } else if (verts[i].type == STBTT_vcurve) { - float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y; - float x1 = verts[i ].cx*scale_x, y1 = verts[i ].cy*scale_y; - float box_x0 = STBTT_min(STBTT_min(x0,x1),x2); - float box_y0 = STBTT_min(STBTT_min(y0,y1),y2); - float box_x1 = STBTT_max(STBTT_max(x0,x1),x2); - float box_y1 = STBTT_max(STBTT_max(y0,y1),y2); - // coarse culling against bbox to avoid computing cubic unnecessarily - if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) { - int num=0; - float ax = x1-x0, ay = y1-y0; - float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; - float mx = x0 - sx, my = y0 - sy; - float res[3] = {0.f,0.f,0.f}; - float px,py,t,it,dist2; - float a_inv = precompute[i]; - if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula - float a = 3*(ax*bx + ay*by); - float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by); - float c = mx*ax+my*ay; - if (a == 0.0) { // if a is 0, it's linear - if (b != 0.0) { - res[num++] = -c/b; - } - } else { - float discriminant = b*b - 4*a*c; - if (discriminant < 0) - num = 0; - else { - float root = (float) STBTT_sqrt(discriminant); - res[0] = (-b - root)/(2*a); - res[1] = (-b + root)/(2*a); - num = 2; // don't bother distinguishing 1-solution case, as code below will still work - } - } - } else { - float b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point - float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv; - float d = (mx*ax+my*ay) * a_inv; - num = stbtt__solve_cubic(b, c, d, res); - } - dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); - if (dist2 < min_dist*min_dist) - min_dist = (float) STBTT_sqrt(dist2); - - if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) { - t = res[0], it = 1.0f - t; - px = it*it*x0 + 2*t*it*x1 + t*t*x2; - py = it*it*y0 + 2*t*it*y1 + t*t*y2; - dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); - if (dist2 < min_dist * min_dist) - min_dist = (float) STBTT_sqrt(dist2); - } - if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) { - t = res[1], it = 1.0f - t; - px = it*it*x0 + 2*t*it*x1 + t*t*x2; - py = it*it*y0 + 2*t*it*y1 + t*t*y2; - dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); - if (dist2 < min_dist * min_dist) - min_dist = (float) STBTT_sqrt(dist2); - } - if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) { - t = res[2], it = 1.0f - t; - px = it*it*x0 + 2*t*it*x1 + t*t*x2; - py = it*it*y0 + 2*t*it*y1 + t*t*y2; - dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); - if (dist2 < min_dist * min_dist) - min_dist = (float) STBTT_sqrt(dist2); - } - } - } - } - if (winding == 0) - min_dist = -min_dist; // if outside the shape, value is negative - val = onedge_value + pixel_dist_scale * min_dist; - if (val < 0) - val = 0; - else if (val > 255) - val = 255; - data[(y-iy0)*w+(x-ix0)] = (unsigned char) val; - } - } - STBTT_free(precompute, info->userdata); - STBTT_free(verts, info->userdata); - } - return data; -} - -STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) -{ - return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff); -} - -STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata) -{ - STBTT_free(bitmap, userdata); -} - -////////////////////////////////////////////////////////////////////////////// -// -// font name matching -- recommended not to use this -// - -// check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string -static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2) -{ - stbtt_int32 i=0; - - // convert utf16 to utf8 and compare the results while converting - while (len2) { - stbtt_uint16 ch = s2[0]*256 + s2[1]; - if (ch < 0x80) { - if (i >= len1) return -1; - if (s1[i++] != ch) return -1; - } else if (ch < 0x800) { - if (i+1 >= len1) return -1; - if (s1[i++] != 0xc0 + (ch >> 6)) return -1; - if (s1[i++] != 0x80 + (ch & 0x3f)) return -1; - } else if (ch >= 0xd800 && ch < 0xdc00) { - stbtt_uint32 c; - stbtt_uint16 ch2 = s2[2]*256 + s2[3]; - if (i+3 >= len1) return -1; - c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; - if (s1[i++] != 0xf0 + (c >> 18)) return -1; - if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1; - if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1; - if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1; - s2 += 2; // plus another 2 below - len2 -= 2; - } else if (ch >= 0xdc00 && ch < 0xe000) { - return -1; - } else { - if (i+2 >= len1) return -1; - if (s1[i++] != 0xe0 + (ch >> 12)) return -1; - if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1; - if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1; - } - s2 += 2; - len2 -= 2; - } - return i; -} - -static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2) -{ - return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2); -} - -// returns results in whatever encoding you request... but note that 2-byte encodings -// will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare -STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID) -{ - stbtt_int32 i,count,stringOffset; - stbtt_uint8 *fc = font->data; - stbtt_uint32 offset = font->fontstart; - stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); - if (!nm) return NULL; - - count = ttUSHORT(fc+nm+2); - stringOffset = nm + ttUSHORT(fc+nm+4); - for (i=0; i < count; ++i) { - stbtt_uint32 loc = nm + 6 + 12 * i; - if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2) - && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) { - *length = ttUSHORT(fc+loc+8); - return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10)); - } - } - return NULL; -} - -static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id) -{ - stbtt_int32 i; - stbtt_int32 count = ttUSHORT(fc+nm+2); - stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4); - - for (i=0; i < count; ++i) { - stbtt_uint32 loc = nm + 6 + 12 * i; - stbtt_int32 id = ttUSHORT(fc+loc+6); - if (id == target_id) { - // find the encoding - stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4); - - // is this a Unicode encoding? - if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) { - stbtt_int32 slen = ttUSHORT(fc+loc+8); - stbtt_int32 off = ttUSHORT(fc+loc+10); - - // check if there's a prefix match - stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen); - if (matchlen >= 0) { - // check for target_id+1 immediately following, with same encoding & language - if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) { - slen = ttUSHORT(fc+loc+12+8); - off = ttUSHORT(fc+loc+12+10); - if (slen == 0) { - if (matchlen == nlen) - return 1; - } else if (matchlen < nlen && name[matchlen] == ' ') { - ++matchlen; - if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen)) - return 1; - } - } else { - // if nothing immediately following - if (matchlen == nlen) - return 1; - } - } - } - - // @TODO handle other encodings - } - } - return 0; -} - -static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags) -{ - stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name); - stbtt_uint32 nm,hd; - if (!stbtt__isfont(fc+offset)) return 0; - - // check italics/bold/underline flags in macStyle... - if (flags) { - hd = stbtt__find_table(fc, offset, "head"); - if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0; - } - - nm = stbtt__find_table(fc, offset, "name"); - if (!nm) return 0; - - if (flags) { - // if we checked the macStyle flags, then just check the family and ignore the subfamily - if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1; - if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1; - if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; - } else { - if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1; - if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1; - if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; - } - - return 0; -} - -static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags) -{ - stbtt_int32 i; - for (i=0;;++i) { - stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i); - if (off < 0) return off; - if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags)) - return off; - } -} - -#if defined(__GNUC__) || defined(__clang__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wcast-qual" -#endif - -STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, - float pixel_height, unsigned char *pixels, int pw, int ph, - int first_char, int num_chars, stbtt_bakedchar *chardata) -{ - return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata); -} - -STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index) -{ - return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index); -} - -STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data) -{ - return stbtt_GetNumberOfFonts_internal((unsigned char *) data); -} - -STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset) -{ - return stbtt_InitFont_internal(info, (unsigned char *) data, offset); -} - -STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags) -{ - return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags); -} - -STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) -{ - return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2); -} - -#if defined(__GNUC__) || defined(__clang__) -#pragma GCC diagnostic pop -#endif - -#endif // STB_TRUETYPE_IMPLEMENTATION - - -// FULL VERSION HISTORY -// -// 1.25 (2021-07-11) many fixes -// 1.24 (2020-02-05) fix warning -// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) -// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined -// 1.21 (2019-02-25) fix warning -// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() -// 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod -// 1.18 (2018-01-29) add missing function -// 1.17 (2017-07-23) make more arguments const; doc fix -// 1.16 (2017-07-12) SDF support -// 1.15 (2017-03-03) make more arguments const -// 1.14 (2017-01-16) num-fonts-in-TTC function -// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts -// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual -// 1.11 (2016-04-02) fix unused-variable warning -// 1.10 (2016-04-02) allow user-defined fabs() replacement -// fix memory leak if fontsize=0.0 -// fix warning from duplicate typedef -// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges -// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges -// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; -// allow PackFontRanges to pack and render in separate phases; -// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); -// fixed an assert() bug in the new rasterizer -// replace assert() with STBTT_assert() in new rasterizer -// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine) -// also more precise AA rasterizer, except if shapes overlap -// remove need for STBTT_sort -// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC -// 1.04 (2015-04-15) typo in example -// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes -// 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++ -// 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match -// non-oversampled; STBTT_POINT_SIZE for packed case only -// 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling -// 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg) -// 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID -// 0.8b (2014-07-07) fix a warning -// 0.8 (2014-05-25) fix a few more warnings -// 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back -// 0.6c (2012-07-24) improve documentation -// 0.6b (2012-07-20) fix a few more warnings -// 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels, -// stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty -// 0.5 (2011-12-09) bugfixes: -// subpixel glyph renderer computed wrong bounding box -// first vertex of shape can be off-curve (FreeSans) -// 0.4b (2011-12-03) fixed an error in the font baking example -// 0.4 (2011-12-01) kerning, subpixel rendering (tor) -// bugfixes for: -// codepoint-to-glyph conversion using table fmt=12 -// codepoint-to-glyph conversion using table fmt=4 -// stbtt_GetBakedQuad with non-square texture (Zer) -// updated Hello World! sample to use kerning and subpixel -// fixed some warnings -// 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM) -// userdata, malloc-from-userdata, non-zero fill (stb) -// 0.2 (2009-03-11) Fix unsigned/signed char warnings -// 0.1 (2009-03-09) First public release -// - -/* ------------------------------------------------------------------------------- -This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------- -ALTERNATIVE A - MIT License -Copyright (c) 2017 Sean Barrett -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. ------------------------------------------------------------------------------- -ALTERNATIVE B - Public Domain (www.unlicense.org) -This is free and unencumbered software released into the public domain. -Anyone is free to copy, modify, publish, use, compile, sell, or distribute this -software, either in source code form or as a compiled binary, for any purpose, -commercial or non-commercial, and by any means. -In jurisdictions that recognize copyright laws, the author or authors of this -software dedicate any and all copyright interest in the software to the public -domain. We make this dedication for the benefit of the public at large and to -the detriment of our heirs and successors. We intend this dedication to be an -overt act of relinquishment in perpetuity of all present and future rights to -this software under copyright law. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- -*/ diff --git a/Components/Overlay/src/utf8.h b/Components/Overlay/src/utf8.h deleted file mode 100644 index b4e02703132..00000000000 --- a/Components/Overlay/src/utf8.h +++ /dev/null @@ -1,68 +0,0 @@ -/* Branchless UTF-8 decoder - * - * This is free and unencumbered software released into the public domain. - */ -#ifndef UTF8_H -#define UTF8_H - -#include - -/* Decode the next character, C, from BUF, reporting errors in E. - * - * Since this is a branchless decoder, four bytes will be read from the - * buffer regardless of the actual length of the next character. This - * means the buffer _must_ have at least three bytes of zero padding - * following the end of the data stream. - * - * Errors are reported in E, which will be non-zero if the parsed - * character was somehow invalid: invalid byte sequence, non-canonical - * encoding, or a surrogate half. - * - * The function returns a pointer to the next character. When an error - * occurs, this pointer will be a guess that depends on the particular - * error, but it will always advance at least one byte. - */ -static const char * -utf8_decode(const char *buf, uint32_t *c, int *e) -{ - static const char lengths[] = { - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 - }; - static const int masks[] = {0x00, 0x7f, 0x1f, 0x0f, 0x07}; - static const uint32_t mins[] = {4194304, 0, 128, 2048, 65536}; - static const int shiftc[] = {0, 18, 12, 6, 0}; - static const int shifte[] = {0, 6, 4, 2, 0}; - - const unsigned char *s = (const unsigned char *)buf; - int len = lengths[s[0] >> 3]; - - /* Compute the pointer to the next character early so that the next - * iteration can start working on the next character. Neither Clang - * nor GCC figure out this reordering on their own. - */ - const char *next = buf + len + !len; - - /* Assume a four-byte character and load four bytes. Unused bits are - * shifted out. - */ - *c = (uint32_t)(s[0] & masks[len]) << 18; - *c |= (uint32_t)(s[1] & 0x3f) << 12; - *c |= (uint32_t)(s[2] & 0x3f) << 6; - *c |= (uint32_t)(s[3] & 0x3f) << 0; - *c >>= shiftc[len]; - - /* Accumulate the various error conditions. */ - *e = (*c < mins[len]) << 6; // non-canonical encoding - *e |= ((*c >> 11) == 0x1b) << 7; // surrogate half? - *e |= (*c > 0x10FFFF) << 8; // out of range? - *e |= (s[1] & 0xc0) >> 2; - *e |= (s[2] & 0xc0) >> 4; - *e |= (s[3] ) >> 6; - *e ^= 0x2a; // top two bits of each tail byte correct? - *e >>= shifte[len]; - - return next; -} - -#endif \ No newline at end of file diff --git a/Components/Paging/CMakeLists.txt b/Components/Paging/CMakeLists.txt deleted file mode 100644 index dc90d7f2146..00000000000 --- a/Components/Paging/CMakeLists.txt +++ /dev/null @@ -1,35 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -############################################################ -# Paging optional component -############################################################ - -# define header and source files for the library -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") - -# Add needed definitions -add_definitions(-DOGRE_PAGING_EXPORTS ${OGRE_VISIBILITY_FLAGS}) - -# setup target -add_library(OgrePaging ${OGRE_COMP_LIB_TYPE} ${HEADER_FILES} ${SOURCE_FILES} ${PLATFORM_HEADER_FILES} ${PLATFORM_SOURCE_FILES}) -set_target_properties(OgrePaging PROPERTIES VERSION ${OGRE_SOVERSION} SOVERSION ${OGRE_SOVERSION}) -target_link_libraries(OgrePaging PUBLIC OgreMain) -target_include_directories(OgrePaging PUBLIC - "$" - $) - -# install -ogre_config_framework(OgrePaging) -ogre_config_component(OgrePaging) - -install(FILES ${HEADER_FILES} - DESTINATION include/OGRE/Paging -) diff --git a/Components/Paging/include/OgreGrid2DPageStrategy.h b/Components/Paging/include/OgreGrid2DPageStrategy.h deleted file mode 100644 index 9ec9ef85689..00000000000 --- a/Components/Paging/include/OgreGrid2DPageStrategy.h +++ /dev/null @@ -1,246 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_Grid2DPageStrategy_H__ -#define __Ogre_Grid2DPageStrategy_H__ - -#include "OgrePagingPrerequisites.h" -#include "OgrePageStrategy.h" -#include "OgreVector.h" - -namespace Ogre -{ - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Paging - * Some details on paging component - * @{ */ - - - /// The 2D grid mode - enum Grid2DMode - { - /// Grid is in the X/Z plane - G2D_X_Z = 0, - /// Grid is in the X/Y plane - G2D_X_Y = 1, - /// Grid is in the Y/Z plane - G2D_Y_Z = 2 - }; - /** Specialisation of PageStrategyData for Grid2DPageStrategy. - - Structurally this data defines with a grid of pages, with the logical - origin in the middle of the entire grid. - The grid cells are indexed from 0 as a 'centre' slot, supporting both - positive and negative values. so (0,0) is the centre cell, (1,0) is the - cell to the right of the centre, (1,0) is the cell above the centre, (-2,1) - is the cell two to the left of the centre and one up, etc. The maximum - extent of each axis is -32768 to +32767, so in other words enough for - over 4 billion entries. - @par - To limit the page load requests that are generated to a fixed region, - you can set the min and max cell indexes (inclusive)for each direction; - if a page request would address a cell outside this range it is ignored - so you don't have the expense of checking for page data that will never - exist. - @par - The data format for this in a file is:
- Grid2DPageStrategyData (Identifier 'G2DD')\n - [Version 1] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
Grid orientationuint8The orientation of the grid; XZ = 0, XY = 1, YZ = 2
Grid originVector3World origin of the grid.
Grid cell sizeRealThe size of each cell (page) in the grid
Grid cell range (minx, maxx, miny, maxy)int16 * 4The extents of the world in cell indexes
Load radiusRealThe outer radius at which new pages should start loading
Hold radiusRealThe radius at which existing pages should be held if already loaded - but not actively loaded (should be larger than Load radius)
- - @sa Grid3DPageStrategyData - */ - class _OgrePagingExport Grid2DPageStrategyData : public PageStrategyData - { - /// Orientation of the grid - Grid2DMode mMode; - /// Origin (world space) - Vector3 mWorldOrigin; - /// Origin (grid-aligned world space) - Vector2 mOrigin; - /// Grid cell (page) size - Real mCellSize; - /// Load radius - Real mLoadRadius; - /// Hold radius - Real mHoldRadius; - Real mLoadRadiusInCells; - Real mHoldRadiusInCells; - int32 mMinCellX; - int32 mMinCellY; - int32 mMaxCellX; - int32 mMaxCellY; - - void updateDerivedMetrics(); - - public: - static const uint32 CHUNK_ID; - static const uint16 CHUNK_VERSION; - - Grid2DPageStrategyData(); - ~Grid2DPageStrategyData(); - - /// Set the grid alignment mode - virtual void setMode(Grid2DMode mode); - - /// Set the grid alignment mode - virtual Grid2DMode getMode() const { return mMode; } - - /// Set the origin of the grid in world space - virtual void setOrigin(const Vector3& worldOrigin); - /// Get the origin of the grid in world space - virtual const Vector3& getOrigin(const Vector3& worldOrigin) { return mWorldOrigin; } - /// Set the size of the cells in the grid - virtual void setCellSize(Real sz); - /// Get the size of the cells in the grid - virtual Real getCellSize() const { return mCellSize; } - /// Set the loading radius - virtual void setLoadRadius(Real sz); - /// Get the loading radius - virtual Real getLoadRadius() const { return mLoadRadius; } - /// Set the Holding radius - virtual void setHoldRadius(Real sz); - /// Get the Holding radius - virtual Real getHoldRadius() const { return mHoldRadius; } - /// Get the load radius as a multiple of cells - virtual Real getLoadRadiusInCells() { return mLoadRadiusInCells; } - /// Get the Hold radius as a multiple of cells - virtual Real getHoldRadiusInCells(){ return mHoldRadiusInCells; } - - /// Set the index range of all cells (values outside this will be ignored) - virtual void setCellRange(int32 minX, int32 minY, int32 maxX, int32 maxY); - /// Set the index range of all cells (values outside this will be ignored) - virtual void setCellRangeMinX(int32 minX); - /// Set the index range of all cells (values outside this will be ignored) - virtual void setCellRangeMinY(int32 minY); - /// Set the index range of all cells (values outside this will be ignored) - virtual void setCellRangeMaxX(int32 maxX); - /// Set the index range of all cells (values outside this will be ignored) - virtual void setCellRangeMaxY(int32 maxY); - /// get the index range of all cells (values outside this will be ignored) - virtual int32 getCellRangeMinX() const { return mMinCellX; } - /// get the index range of all cells (values outside this will be ignored) - virtual int32 getCellRangeMinY() const { return mMinCellY; } - /// get the index range of all cells (values outside this will be ignored) - virtual int32 getCellRangeMaxX() const { return mMaxCellX; } - /// get the index range of all cells (values outside this will be ignored) - virtual int32 getCellRangeMaxY() const { return mMaxCellY; } - - /// Load this data from a stream (returns true if successful) - bool load(StreamSerialiser& stream) override; - /// Save this data to a stream - void save(StreamSerialiser& stream) override; - - /// Convert a world point to grid space (not relative to origin) - virtual void convertWorldToGridSpace(const Vector3& world, Vector2& grid); - /// Convert a grid point to world space - note only 2 axes populated - virtual void convertGridToWorldSpace(const Vector2& grid, Vector3& world); - /// Get the (grid space) mid point of a cell - virtual void getMidPointGridSpace(int32 x, int32 y, Vector2& mid); - /// Get the (grid space) bottom-left of a cell - virtual void getBottomLeftGridSpace(int32 x, int32 y, Vector2& bl); - /** Get the (grid space) corners of a cell. - - Populates pFourPoints in anticlockwise order from the bottom left point. - */ - virtual void getCornersGridSpace(int32 x, int32 y, Vector2* pFourPoints); - - /// Convert a grid position into a row and column index - void determineGridLocation(const Vector2& gridpos, int32* x, int32* y); - - PageID calculatePageID(int32 x, int32 y); - void calculateCell(PageID inPageID, int32* x, int32* y); - - }; - - - /** Page strategy which loads new pages based on a regular 2D grid. - - The grid can be up to 65536 x 65536 cells in size. PageIDs are generated - like this: (row * 65536) + col. The grid is centred around the grid origin, such - that the boundaries of the cell around that origin are [-CellSize/2, CellSize/2) - */ - class _OgrePagingExport Grid2DPageStrategy : public PageStrategy - { - public: - Grid2DPageStrategy(PageManager* manager); - - ~Grid2DPageStrategy(); - - // Overridden members - void notifyCamera(Camera* cam, PagedWorldSection* section) override; - PageStrategyData* createData() override; - void destroyData(PageStrategyData* d) override; - void updateDebugDisplay(Page* p, SceneNode* sn) override; - PageID getPageID(const Vector3& worldPos, PagedWorldSection* section) override; - }; - - /** @} */ - /** @} */ -} - -#endif diff --git a/Components/Paging/include/OgreGrid3DPageStrategy.h b/Components/Paging/include/OgreGrid3DPageStrategy.h deleted file mode 100644 index a6afd971df2..00000000000 --- a/Components/Paging/include/OgreGrid3DPageStrategy.h +++ /dev/null @@ -1,221 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_Grid3DPageStrategy_H__ -#define __Ogre_Grid3DPageStrategy_H__ - -#include "OgrePagingPrerequisites.h" -#include "OgrePageStrategy.h" -#include "OgreVector.h" - -namespace Ogre -{ - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Paging - * Some details on paging component - * @{ - */ - - - /** Specialisation of PageStrategyData for Grid3DPageStrategy. - - Structurally this data defines with a 3D grid of pages, with the logical - origin in the center of the entire grid. - The grid cells are indexed from 0 as a 'centre' slot, supporting both - positive and negative values. so (0,0,0) is the centre cell, (1,0,0) is the - cell to the right of the centre, (0,0,1) is the cell in front of the centre, - (0,1,0) the cell above the center, etc. - The maximum extent of each axis is -512 to +511, so in other words enough for - over 2 billion different entries. - @par - To limit the page load requests that are generated to a fixed region, - you can set the min and max cell indexes (inclusive)for each direction; - if a page request would address a cell outside this range it is ignored - so you don't have the expense of checking for page data that will never - exist. - @par - The data format for this in a file is:
- Grid3DPageStrategyData (Identifier 'G3DD')\n - [Version 1] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
Grid originVector3World origin of the grid.
Grid cell sizeVector3The size of each cell (page) in the grid
Grid cell range (minx, maxx, miny, maxy, minz, maxz)int16 * 6The extents of the world in cell indexes
Load radiusRealThe outer radius at which new pages should start loading
Hold radiusRealThe radius at which existing pages should be held if already loaded - but not actively loaded (should be larger than Load radius)
- - @sa Grid2DPageStrategyData - - */ - class _OgrePagingExport Grid3DPageStrategyData : public PageStrategyData - { - /// Origin (world space) - Vector3 mWorldOrigin; - /// Origin (grid-aligned world space) - Vector3 mOrigin; - /// Grid cell (page) size - Vector3 mCellSize; - /// Load radius - Real mLoadRadius; - /// Hold radius - Real mHoldRadius; - int32 mMinCellX; - int32 mMinCellY; - int32 mMinCellZ; - int32 mMaxCellX; - int32 mMaxCellY; - int32 mMaxCellZ; - - public: - static const uint32 CHUNK_ID; - static const uint16 CHUNK_VERSION; - - Grid3DPageStrategyData(); - ~Grid3DPageStrategyData(); - - /// Set the origin of the grid in world space - virtual void setOrigin(const Vector3& worldOrigin); - /// Get the origin of the grid in world space - virtual const Vector3& getOrigin(const Vector3& worldOrigin) { return mWorldOrigin; } - /// Set the size of the cells in the grid - virtual void setCellSize(const Vector3& sz); - /// Get the size of the cells in the grid - virtual Vector3 getCellSize() const { return mCellSize; } - /// Set the loading radius - virtual void setLoadRadius(Real sz); - /// Get the loading radius - virtual Real getLoadRadius() const { return mLoadRadius; } - /// Set the Holding radius - virtual void setHoldRadius(Real sz); - /// Get the Holding radius - virtual Real getHoldRadius() const { return mHoldRadius; } - - /// Set the index range of all cells (values outside this will be ignored) - virtual void setCellRange(int32 minX, int32 minY, int32 minZ, int32 maxX, int32 maxY, int32 maxZ); - /// Set the index range of all cells (values outside this will be ignored) - virtual void setCellRangeMinX(int32 minX); - /// Set the index range of all cells (values outside this will be ignored) - virtual void setCellRangeMinY(int32 minY); - /// Set the index range of all cells (values outside this will be ignored) - virtual void setCellRangeMinZ(int32 minZ); - /// Set the index range of all cells (values outside this will be ignored) - virtual void setCellRangeMaxX(int32 maxX); - /// Set the index range of all cells (values outside this will be ignored) - virtual void setCellRangeMaxY(int32 maxY); - /// get the index range of all cells (values outside this will be ignored) - virtual void setCellRangeMaxZ(int32 maxZ); - /// get the index range of all cells (values outside this will be ignored) - virtual int32 getCellRangeMinX() const { return mMinCellX; } - /// get the index range of all cells (values outside this will be ignored) - virtual int32 getCellRangeMinY() const { return mMinCellY; } - /// get the index range of all cells (values outside this will be ignored) - virtual int32 getCellRangeMinZ() const { return mMinCellZ; } - /// get the index range of all cells (values outside this will be ignored) - virtual int32 getCellRangeMaxX() const { return mMaxCellX; } - /// get the index range of all cells (values outside this will be ignored) - virtual int32 getCellRangeMaxY() const { return mMaxCellY; } - /// get the index range of all cells (values outside this will be ignored) - virtual int32 getCellRangeMaxZ() const { return mMaxCellZ; } - - /// Load this data from a stream (returns true if successful) - bool load(StreamSerialiser& stream) override; - /// Save this data to a stream - void save(StreamSerialiser& stream) override; - - virtual void getMidPointGridSpace(int32 x, int32 y, int32 z, Vector3& mid); - /// Get the (grid space) bottom-left of a cell - virtual void getBottomLeftGridSpace(int32 x, int32 y, int z, Vector3& bl); - /** Get the (grid space) corners of a cell. - - Populates pEightPoints in anticlockwise order from the bottom left point. - */ - virtual void getCornersGridSpace(int32 x, int32 y, int32 z, Vector3* pEightPoints); - - /// Convert a grid position into a row and column index - void determineGridLocation(const Vector3& gridpos, int32* x, int32* y, int32* z); - - PageID calculatePageID(int32 x, int32 y, int32 z); - void calculateCell(PageID inPageID, int32* x, int32* y, int32* z); - }; - - - /** Page strategy which loads new pages based on a regular 3D grid. - - The grid can be up to 1024 x 1024 x 1024 cells in size. PageIDs are generated - like this: (slice*1024 + row) * 1024 + col. The grid is centred around the grid origin, such - that the boundaries of the cell around that origin are [-CellSize/2, CellSize/2) - */ - class _OgrePagingExport Grid3DPageStrategy : public PageStrategy - { - public: - Grid3DPageStrategy(PageManager* manager); - - ~Grid3DPageStrategy(); - - // Overridden members - void notifyCamera(Camera* cam, PagedWorldSection* section) override; - PageStrategyData* createData() override; - void destroyData(PageStrategyData* d) override; - void updateDebugDisplay(Page* p, SceneNode* sn) override; - PageID getPageID(const Vector3& worldPos, PagedWorldSection* section) override; - }; - - /*@}*/ - /*@}*/ -} - -#endif diff --git a/Components/Paging/include/OgrePage.h b/Components/Paging/include/OgrePage.h deleted file mode 100644 index befac54ee68..00000000000 --- a/Components/Paging/include/OgrePage.h +++ /dev/null @@ -1,188 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_Page_H__ -#define __Ogre_Page_H__ - -#include "OgrePagingPrerequisites.h" -#include "Threading/OgreThreadHeaders.h" -#include "OgreWorkQueue.h" - - -namespace Ogre -{ - /** \addtogroup Optional - * @{ - */ - /** \defgroup Paging Paging - * Render large modular structures - * @{ - */ - - /** Page class - */ - class _OgrePagingExport Page - { - public: - typedef std::vector ContentCollectionList; - private: - PageID mID; - PagedWorldSection* mParent; - unsigned long mFrameLastHeld; - ContentCollectionList mContentCollections; - bool mDeferredProcessInProgress; - bool mModified; - - SceneNode* mDebugNode; - void updateDebugDisplay(); - - struct PageData : public PageAlloc - { - ContentCollectionList collectionsToAdd; - }; - /// Structure for holding background page requests - struct PageRequest - { - Page* srcPage; - PageRequest(Page* p): srcPage(p) {} - }; - struct PageResponse - { - PageData* pageData; - PageResponse() : pageData(0) {} - }; - - - - virtual bool prepareImpl(PageData* dataToPopulate); - virtual bool prepareImpl(StreamSerialiser& str, PageData* dataToPopulate); - virtual void loadImpl(); - - String generateFilename() const; - - /// WorkQueue::RequestHandler override - WorkQueue::Response* handleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ); - /// WorkQueue::ResponseHandler override - void handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ); - public: - static const uint32 CHUNK_ID; - static const uint16 CHUNK_VERSION; - - static const uint32 CHUNK_CONTENTCOLLECTION_DECLARATION_ID; - - Page(PageID pageID, PagedWorldSection* parent); - virtual ~Page(); - - PageManager* getManager() const; - SceneManager* getSceneManager() const; - - /// If true, it's not safe to access this Page at this time, contents may be changing - bool isDeferredProcessInProgress() const { return mDeferredProcessInProgress; } - - /// Get the ID of this page, unique within the parent - virtual PageID getID() const { return mID; } - /// Get the PagedWorldSection this page belongs to - virtual PagedWorldSection* getParentSection() const { return mParent; } - /** Get the frame number in which this Page was last loaded or held. - - A Page that has not been requested to be loaded or held in the recent - past will be a candidate for removal. - */ - virtual unsigned long getFrameLastHeld() { return mFrameLastHeld; } - /// 'Touch' the page to let it know it's being used - virtual void touch(); - - /** Load this page. - @param synchronous Whether to force this to happen synchronously. - */ - virtual void load(bool synchronous); - /** Unload this page. - */ - virtual void unload(); - - - /** Returns whether this page was 'held' in the last frame, that is - was it either directly needed, or requested to stay in memory (held - as - in a buffer region for example). If not, this page is eligible for - removal. - */ - virtual bool isHeld() const; - - /// Save page data to an automatically generated file name - virtual void save(); - /// Save page data to a file - virtual void save(const String& filename); - /// Save page data to a serialiser - virtual void save(StreamSerialiser& stream); - - /// Called when the frame starts - virtual void frameStart(Real timeSinceLastFrame); - /// Called when the frame ends - virtual void frameEnd(Real timeElapsed); - /// Notify a section of the current camera - virtual void notifyCamera(Camera* cam); - - /** Create a new PageContentCollection within this page. - This is equivalent to calling PageManager::createContentCollection and - then attachContentCollection. - @param typeName The name of the type of content collection (see PageManager::getContentCollectionFactories) - */ - virtual PageContentCollection* createContentCollection(const String& typeName); - - /** Destroy a PageContentCollection within this page. - This is equivalent to calling detachContentCollection and - PageManager::destroyContentCollection. - */ - virtual void destroyContentCollection(PageContentCollection* coll); - /** Destroy all PageContentCollections within this page. - */ - virtual void destroyAllContentCollections(); - /// Get the number of content collections - virtual size_t getContentCollectionCount() const; - /// Get a content collection - virtual PageContentCollection* getContentCollection(size_t index); - /// Get the list of content collections - const ContentCollectionList& getContentCollectionList() const; - - /// Tell the page that it is modified - void _notifyModified() { mModified = true; } - bool isModified() const { return mModified; } - - /** Function for writing to a stream. - */ - _OgrePagingExport friend std::ostream& operator <<( std::ostream& o, const Page& p ); - - - - }; - - /** @} */ - /** @} */ -} - -#endif diff --git a/Components/Paging/include/OgrePageConnection.h b/Components/Paging/include/OgrePageConnection.h deleted file mode 100644 index 230ca0fa5d4..00000000000 --- a/Components/Paging/include/OgrePageConnection.h +++ /dev/null @@ -1,50 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_PageConnection_H__ -#define __Ogre_PageConnection_H__ - -#include "OgrePagingPrerequisites.h" - - -namespace Ogre -{ - /** \addtogroup Optional - * @{ - */ - - /** \addtogroup Paging - * Some details on paging component - * @{ - */ - - /** @} */ - /** @} */ -} - -#endif diff --git a/Components/Paging/include/OgrePageContent.h b/Components/Paging/include/OgrePageContent.h deleted file mode 100644 index b5a688d9bd5..00000000000 --- a/Components/Paging/include/OgrePageContent.h +++ /dev/null @@ -1,90 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_PageContent_H__ -#define __Ogre_PageContent_H__ - -#include "OgrePagingPrerequisites.h" - - - -namespace Ogre -{ - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Paging - * Some details on paging component - * @{ - */ - - - /** Interface definition for a unit of content within a page. - */ - class _OgrePagingExport PageContent : public PageAlloc - { - protected: - PageContentFactory* mCreator; - PageContentCollection* mParent; - public: - PageContent(PageContentFactory* creator); - virtual ~PageContent(); - - PageManager* getManager() const; - SceneManager* getSceneManager() const; - - /// Internal method to notify a page that it is attached - virtual void _notifyAttached(PageContentCollection* parent); - /// Get the type of the content, which will match it's factory - virtual const String& getType() const; - - /// Save the content to a stream - virtual void save(StreamSerialiser& stream) = 0; - /// Called when the frame starts - virtual void frameStart(Real timeSinceLastFrame) {} - /// Called when the frame ends - virtual void frameEnd(Real timeElapsed) {} - /// Notify a section of the current camera - virtual void notifyCamera(Camera* cam) {} - - /// Prepare data - may be called in the background - virtual bool prepare(StreamSerialiser& ser) = 0; - /// Load - will be called in main thread - virtual void load() = 0; - /// Unload - will be called in main thread - virtual void unload() = 0; - /// Unprepare data - may be called in the background - virtual void unprepare() = 0; - - }; - - /** @} */ - /** @} */ -} - -#endif diff --git a/Components/Paging/include/OgrePageContentCollection.h b/Components/Paging/include/OgrePageContentCollection.h deleted file mode 100644 index 05022d4a038..00000000000 --- a/Components/Paging/include/OgrePageContentCollection.h +++ /dev/null @@ -1,102 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_PageContentCollection_H__ -#define __Ogre_PageContentCollection_H__ - -#include "OgrePagingPrerequisites.h" - - -namespace Ogre -{ - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Paging - * Some details on paging component - * @{ - */ - - - /** Definition of the interface for a collection of PageContent instances. - - This class acts as a grouping level for PageContent instances. Rather than - PageContent instances being held in a list directly under Page, which might - be the most obvious solution, this intermediate class is here to allow - the collection of relevant PageContent instances to be modified at runtime - if required. For example, potentially you might want to define Page-level LOD - in which different collections of PageContent are loaded at different times. - */ - class _OgrePagingExport PageContentCollection : public PageAlloc - { - PageContentCollectionFactory* mCreator; - Page* mParent; - public: - static const uint32 CHUNK_ID; - static const uint16 CHUNK_VERSION; - - PageContentCollection(PageContentCollectionFactory* creator); - virtual ~PageContentCollection(); - - PageManager* getManager() const; - Page* getParentPage() const { return mParent; } - SceneManager* getSceneManager() const; - - /// Get the type of the collection, which will match it's factory - virtual const String& getType() const; - - /// Internal method to notify a collection that it is attached - virtual void _notifyAttached(Page* parent); - /// Save the collection to a stream - virtual void save(StreamSerialiser& stream) = 0; - /// Called when the frame starts - virtual void frameStart(Real timeSinceLastFrame) = 0; - /// Called when the frame ends - virtual void frameEnd(Real timeElapsed) = 0; - /// Notify a section of the current camera - virtual void notifyCamera(Camera* cam) = 0; - - - /// Prepare data - may be called in the background - virtual bool prepare(StreamSerialiser& ser) = 0; - /// Load - will be called in main thread - virtual void load() = 0; - /// Unload - will be called in main thread - virtual void unload() = 0; - /// Unprepare data - may be called in the background - virtual void unprepare() = 0; - - - }; - - - /** @} */ - /** @} */ -} - -#endif diff --git a/Components/Paging/include/OgrePageContentCollectionFactory.h b/Components/Paging/include/OgrePageContentCollectionFactory.h deleted file mode 100644 index d6102f8360a..00000000000 --- a/Components/Paging/include/OgrePageContentCollectionFactory.h +++ /dev/null @@ -1,62 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_PageContentCollectionFactory_H__ -#define __Ogre_PageContentCollectionFactory_H__ - -#include "OgrePagingPrerequisites.h" - -namespace Ogre -{ - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Paging - * Some details on paging component - * @{ - */ - - /** Define the interface to a factory class that will create subclasses - of PageContentCollection. - */ - class PageContentCollectionFactory : public PageAlloc - { - public: - PageContentCollectionFactory() {} - virtual ~PageContentCollectionFactory() {} - - virtual const String& getName() const = 0; - virtual PageContentCollection* createInstance() = 0; - virtual void destroyInstance(PageContentCollection*) = 0; - }; - - /** @} */ - /** @} */ -} - -#endif diff --git a/Components/Paging/include/OgrePageContentFactory.h b/Components/Paging/include/OgrePageContentFactory.h deleted file mode 100644 index 39bf913b812..00000000000 --- a/Components/Paging/include/OgrePageContentFactory.h +++ /dev/null @@ -1,67 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_PageContentFaactory_H__ -#define __Ogre_PageContentFaactory_H__ - -#include "OgrePagingPrerequisites.h" - - - -namespace Ogre -{ - /** \addtogroup Optional - * @{ - */ - - /** \addtogroup Paging - * Some details on paging component - * @{ - */ - - /** Define the interface to a factory class that will create subclasses - of PageContent. - */ - class PageContentFactory : public PageAlloc - { - public: - PageContentFactory() {} - virtual ~PageContentFactory() {} - - virtual const String& getName() const = 0; - virtual PageContent* createInstance() = 0; - virtual void destroyInstance(PageContent*) = 0; - - }; - - - /** @} */ - /** @} */ -} - -#endif diff --git a/Components/Paging/include/OgrePageFileFormats.h b/Components/Paging/include/OgrePageFileFormats.h deleted file mode 100644 index 89023bdd327..00000000000 --- a/Components/Paging/include/OgrePageFileFormats.h +++ /dev/null @@ -1,219 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_PageFileFormats_H__ -#define __Ogre_PageFileFormats_H__ - -#include "OgrePagingPrerequisites.h" - -/** \addtogroup Optional -* @{ -*/ -/** \defgroup Paging Paging -* Render large modular structures - - # File Format - The paging file format is a composite one - a single file / stream can contain - data which is not necessarily all read by a single class. Instead, data - chunks can be read by different classes, allowing the format to be extended to - different types smoothly. - - Paging world files have by default an extension ".world", but that is not - a requirement. Internally, the only thing that matters is the data chunks - and their identifiers, which are 4-character codes embedded in a uint32 as - calculated by StreamSerialiser::makeIdentifier. All data will be read and - written using DataStream and the StreamSerialiser class. - - Data types are expressed at the lowest level exposed by the StreamSerialiser class, - which is used to read / write this file. - - ## Chunk Definitions - - @par - PagedWorld (Identifier 'PWLD')\n - [Version 1] - - - - - - - - - - - - - - - - -
NameTypeDescription
World Namechar*The name of the world - should be unique
PagedWorldSection ListChunk ListA variable-length list of nested PagedWorldSection chunks
- - @par - PagedWorldSection (Identifier 'PWSC')\n - [Version 1] - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
World Section Namechar*The name of the world section - should be unique within world
Bounding boxAABBAABB of this world section in world space
PageStrategy namechar*The name of the PageStrategy class this world section uses to manage pages
Page Strategy DataNested ChunkPageStrategy specific data for this world section
- - @par - PagedStrategyData (Identifier defined by subclass)\n - [Version 1] - - - - - - - - - - - -
NameTypeDescription
PageStrategy defined???This chunk will contain data as defined by the specific PageStrategyData used by the - parent PagedWorldSection
- @par - Page (Identifier 'PAGE')\n - [Version 1] - - - - - - - - - - - - - - - - -
NameTypeDescription
Page IDuint32The identifier of the page
PageContentCollection listNested chunk list1-n nested chunks of type PageContentCollection
- @par - PageContentCollection (Identifier 'PGCC')\n - [Version 1] - - - - - - - - - - - - - - - - -
NameTypeDescription
Factory namechar*The name of the content collection factory
PageContentCollectionData chunkNested chunkData required to initialise & configure the content collection
- @par - PageContentCollectionData (Identifier defined by subclass)\n - [Version 1] - - - - - - - - - - - -
NameTypeDescription
PageContentCollection subclass defined???This chunk will contain data as defined by the specific PageContentCollection subclass
- @par - PageContent (Identifier 'PGCN')\n - [Version 1] - - - - - - - - - - - - - - - - -
NameTypeDescription
Factory namechar*The name of the content factory
PageContentData chunkNested chunkData required to initialise & configure the content
- @par - PageContentData (Identifier defined by subclass)\n - [Version 1] - - - - - - - - - - - -
NameTypeDescription
PageContent subclass defined???This chunk will contain data as defined by the specific PageContent subclass
-*/ -/**@}*/ - - -#endif diff --git a/Components/Paging/include/OgrePageManager.h b/Components/Paging/include/OgrePageManager.h deleted file mode 100644 index 9d05453cb83..00000000000 --- a/Components/Paging/include/OgrePageManager.h +++ /dev/null @@ -1,479 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_PageManager_H__ -#define __Ogre_PageManager_H__ - -#include "OgrePagingPrerequisites.h" -#include "OgreCommon.h" -#include "OgreCamera.h" -#include "OgreFrameListener.h" -#include "OgreNameGenerator.h" - -namespace Ogre -{ - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Paging - * Some details on paging component - * @{ - */ - - class PagedWorldSection; - class PagedWorldSectionFactory; - - - /** Abstract class that can be implemented by the user application to - provide a way to retrieve or generate page data from a source of their choosing. - @note - All of the methods in this class can be called in a background, non-render thread. - */ - class PageProvider - { - public: - PageProvider() {} - virtual ~PageProvider() {} - - /** Give a provider the opportunity to prepare page content procedurally. - - This call may well happen in a separate thread so it should not access - GPU resources, use loadProceduralPage for that - @return true if the page was populated, false otherwise - */ - virtual bool prepareProceduralPage(Page* page, PagedWorldSection* section) { return false; } - /** Give a provider the opportunity to load page content procedurally. - - This call will happen in the main render thread so it can access GPU resources. - Use prepareProceduralPage for background preparation. - @return true if the page was populated, false otherwise - */ - virtual bool loadProceduralPage(Page* page, PagedWorldSection* section) { return false; } - /** Give a provider the opportunity to unload page content procedurally. - - You should not call this method directly. This call will happen in - the main render thread so it can access GPU resources. Use _unprepareProceduralPage - for background preparation. - @return true if the page was populated, false otherwise - */ - virtual bool unloadProceduralPage(Page* page, PagedWorldSection* section) { return false; } - /** Give a provider the opportunity to unprepare page content procedurally. - - You should not call this method directly. This call may well happen in - a separate thread so it should not access GPU resources, use _unloadProceduralPage - for that - @return true if the page was unpopulated, false otherwise - */ - virtual bool unprepareProceduralPage(Page* page, PagedWorldSection* section) { return false; } - - /** Get a serialiser set up to read PagedWorld data for the given world filename. - - The StreamSerialiser returned is the responsibility of the caller to - delete. - */ - virtual StreamSerialiser* readWorldStream(const String& filename) { return 0; } - /** Get a serialiser set up to write PagedWorld data for the given world filename. - - The StreamSerialiser returned is the responsibility of the caller to - delete. - */ - virtual StreamSerialiser* writeWorldStream(const String& filename) { return 0; } - /** Get a serialiser set up to read Page data for the given PageID, - or null if this provider cannot supply one. - - The StreamSerialiser returned is the responsibility of the caller to - delete. - @param pageID The ID of the page being requested - @param section The parent section to which this page will belong - */ - virtual StreamSerialiser* readPageStream(PageID pageID, PagedWorldSection* section) { return 0; } - - /** Get a serialiser set up to write Page data for the given PageID, - or null if this provider cannot supply one. - - The StreamSerialiser returned is the responsibility of the caller to - delete. - @param pageID The ID of the page being requested - @param section The parent section to which this page will belong - */ - virtual StreamSerialiser* writePageStream(PageID pageID, PagedWorldSection* section) { return 0; } - }; - - /** The PageManager is the entry point through which you load all PagedWorld instances, - and the place where PageStrategy instances and factory classes are - registered to customise the paging behaviour. - - To get started, the minimum you need is a PagedWorld with at least one PagedWorldSection - within it, and at least one Camera being tracked (see addCamera). - */ - class _OgrePagingExport PageManager : public PageAlloc - { - public: - PageManager(); - virtual ~PageManager(); - - /** Create a new PagedWorld instance. - @param name Optionally give a name to the world (if no name is given, one - will be generated). - */ - PagedWorld* createWorld(const String& name = BLANKSTRING); - - /** Destroy a world. */ - void destroyWorld(const String& name); - - /** Destroy a world. */ - void destroyWorld(PagedWorld* world); - - /** Load a new PagedWorld from a file. - @param filename The name of the file to load (standard is .world) - @param name Optionally give a name to the world (if no name is given, one - will be generated). - */ - PagedWorld* loadWorld(const String& filename, const String& name = BLANKSTRING); - /** Load a new PagedWorld from a stream. - @param stream A stream from which to load the world data - @param name Optionally give a name to the world (if no name is given, one - will be generated). - */ - PagedWorld* loadWorld(const DataStreamPtr& stream, const String& name = BLANKSTRING); - /** Save a PagedWorld instance to a file. - @param world The world to be saved - @param filename The filename to save the data to - */ - void saveWorld(PagedWorld* world, const String& filename); - /** Save a PagedWorld instance to a file. - @param world The world to be saved - @param stream The stream to save the data to - */ - void saveWorld(PagedWorld* world, const DataStreamPtr& stream); - /** Get a named world. - @param name The name of the world (not a filename, the identifying name) - @return The world, or null if the world doesn't exist. - */ - PagedWorld* getWorld(const String& name); - typedef std::map WorldMap; - /** Get a reference to the worlds that are currently loaded. */ - const WorldMap& getWorlds() const { return mWorlds; } - - - typedef std::map StrategyMap; - /** Add a new PageStrategy implementation. - - The caller remains resonsible for destruction of this instance. - */ - void addStrategy(PageStrategy* strategy); - - /** Remove a PageStrategy implementation. - */ - void removeStrategy(PageStrategy* strategy); - - /** Get a PageStrategy. - @param name The name of the strategy to retrieve - @return Pointer to a PageStrategy, or null if the strategy was not found. - */ - PageStrategy* getStrategy(const String& name); - - /** Get a reference to the registered strategies. - */ - const StrategyMap& getStrategies() const; - - - typedef std::map ContentCollectionFactoryMap; - /** Add a new PageContentCollectionFactory implementation. - - The caller remains resonsible for destruction of this instance. - */ - void addContentCollectionFactory(PageContentCollectionFactory* f); - - /** Remove a PageContentCollectionFactory implementation. - */ - void removeContentCollectionFactory(PageContentCollectionFactory* f); - - /** Get a PageContentCollectionFactory. - @param name The name of the factory to retrieve - @return Pointer to a PageContentCollectionFactory, or null if the ContentCollection was not found. - */ - PageContentCollectionFactory* getContentCollectionFactory(const String& name); - - /** Create a new instance of PageContentCollection using the registered - factories. - @param typeName The name of the type of collection to create - */ - PageContentCollection* createContentCollection(const String& typeName); - - /** Destroy an instance of PageContentCollection. */ - void destroyContentCollection(PageContentCollection* coll); - - /** Get a reference to the registered strategies. - */ - const ContentCollectionFactoryMap& getContentCollectionFactories() const; - - typedef std::map ContentFactoryMap; - /** Add a new PageContentFactory implementation. - - The caller remains resonsible for destruction of this instance. - */ - void addContentFactory(PageContentFactory* f); - - /** Remove a PageContentFactory implementation. - */ - void removeContentFactory(PageContentFactory* f); - - /** Get a PageContentFactory. - @param name The name of the factory to retrieve - @return Pointer to a PageContentFactory, or null if the Content was not found. - */ - PageContentFactory* getContentFactory(const String& name); - - /** Get a reference to the registered strategies. - */ - const ContentFactoryMap& getContentFactories() const; - - /** Create a new instance of PageContent using the registered - factories. - @param typeName The name of the type of content to create - */ - PageContent* createContent(const String& typeName); - - /** Destroy an instance of PageContent. */ - void destroyContent(PageContent* c); - - - typedef std::map WorldSectionFactoryMap; - /** Add a new PagedWorldSectionFactory implementation. - - The caller remains resonsible for destruction of this instance. - */ - void addWorldSectionFactory(PagedWorldSectionFactory* f); - - /** Remove a PagedWorldSectionFactory implementation. - */ - void removeWorldSectionFactory(PagedWorldSectionFactory* f); - - /** Get a PagedWorldSectionFactory. - @param name The name of the factory to retrieve - @return Pointer to a PagedWorldSectionFactory, or null if the WorldSection was not found. - */ - PagedWorldSectionFactory* getWorldSectionFactory(const String& name); - - /** Create a new instance of PagedWorldSection using the registered - factories. - @param typeName The name of the type of collection to create - @param name The instance name - @param parent The parent world - @param sm The SceneManager to use (can be null if this is to be loaded) - */ - PagedWorldSection* createWorldSection(const String& typeName, - const String& name, PagedWorld* parent, SceneManager* sm); - - /** Destroy an instance of PagedWorldSection. */ - void destroyWorldSection(PagedWorldSection* s); - - /** Get a reference to the registered strategies. - */ - const WorldSectionFactoryMap& getWorldSectionFactories() const; - - - /** Set the PageProvider which can provide streams for any Page. - - This is the top-level way that you can direct how Page data is loaded. - When data for a Page is requested for a PagedWorldSection, the following - sequence of classes will be checked to see if they have a provider willing - to supply the stream: PagedWorldSection, PagedWorld, PageManager. - If none of these do, then the default behaviour is to look for a file - called worldname_sectionname_pageID.page. - @note - The caller remains responsible for the destruction of the provider. - */ - void setPageProvider(PageProvider* provider) { mPageProvider = provider; } - - /** Get the PageProvider which can provide streams for any Page. */ - PageProvider* getPageProvider() const { return mPageProvider; } - - /** Give a provider the opportunity to prepare page content procedurally. - - You should not call this method directly. This call may well happen in - a separate thread so it should not access GPU resources, use _loadProceduralPage - for that - @return true if the page was populated, false otherwise - */ - virtual bool _prepareProceduralPage(Page* page, PagedWorldSection* section); - /** Give a provider the opportunity to prepare page content procedurally. - - You should not call this method directly. This call will happen in - the main render thread so it can access GPU resources. Use _prepareProceduralPage - for background preparation. - @return true if the page was populated, false otherwise - */ - virtual bool _loadProceduralPage(Page* page, PagedWorldSection* section); - /** Give a manager the opportunity to unload page content procedurally. - - You should not call this method directly. This call will happen in - the main render thread so it can access GPU resources. Use _unprepareProceduralPage - for background preparation. - @return true if the page was populated, false otherwise - */ - virtual bool _unloadProceduralPage(Page* page, PagedWorldSection* section); - /** Give a manager the opportunity to unprepare page content procedurally. - - You should not call this method directly. This call may well happen in - a separate thread so it should not access GPU resources, use _unloadProceduralPage - for that - @return true if the page was unpopulated, false otherwise - */ - virtual bool _unprepareProceduralPage(Page* page, PagedWorldSection* section); - /** Get a serialiser set up to read Page data for the given PageID. - @param pageID The ID of the page being requested - @param section The parent section to which this page will belong - - The StreamSerialiser returned is the responsibility of the caller to - delete. - */ - StreamSerialiser* _readPageStream(PageID pageID, PagedWorldSection* section); - - /** Get a serialiser set up to write Page data for the given PageID. - @param pageID The ID of the page being requested - @param section The parent section to which this page will belong - - The StreamSerialiser returned is the responsibility of the caller to - delete. - */ - StreamSerialiser* _writePageStream(PageID pageID, PagedWorldSection* section); - /** Get a serialiser set up to read PagedWorld data for the given world name. - - The StreamSerialiser returned is the responsibility of the caller to - delete. - */ - StreamSerialiser* _readWorldStream(const String& filename); - - /** Get a serialiser set up to write PagedWorld data. - - The StreamSerialiser returned is the responsibility of the caller to - delete. - */ - StreamSerialiser* _writeWorldStream(const String& filename); - - /** Get the resource group that will be used to read/write files when the - default load routines are used. - */ - const String& getPageResourceGroup() const { return mPageResourceGroup; } - /** Set the resource group that will be used to read/write files when the - default load routines are used. - */ - void setPageResourceGroup(const String& g) { mPageResourceGroup = g; } - - /** Tells the paging system to start tracking a given camera. - - In order for the paging system to function it needs to know which - Cameras to track. You may not want to have all your cameras affect - the paging system, so just add the cameras you want it to keep track of - here. - */ - void addCamera(Camera* c); - - /** Tells the paging system to stop tracking a given camera. - */ - void removeCamera(Camera* c); - - /** Returns whether or not a given camera is being watched by the paging system. - */ - bool hasCamera(Camera* c) const; - - typedef std::vector CameraList; - /** Returns a list of cameras being tracked. */ - const CameraList& getCameraList() const; - - /** Set the debug display level. - - This setting controls how much debug information is displayed in the scene. - The exact interpretation of this value depends on the PageStrategy you're - using, and whether the PageContent decides to also display debug information. - Generally speaking, 0 means no debug display, 1 means simple debug - display (usually the PageStrategy) and anything more than that is - up to the classes involved. - */ - void setDebugDisplayLevel(uint8 lvl) { mDebugDisplayLvl = lvl; } - /** Get the debug display level. */ - uint8 getDebugDisplayLevel() const { return mDebugDisplayLvl; } - - /** Pause or unpause all paging operations. - - Using this method you can stop pages being loaded or unloaded for a - period of time, 'freezing' the current page state as it is. - @param enabled True to proceed with normal paging operations, false to pause. - */ - void setPagingOperationsEnabled(bool enabled) { mPagingEnabled = enabled; } - - /** Get whether paging operations are currently allowed to happen. */ - bool getPagingOperationsEnabled() const { return mPagingEnabled; } - - - private: - - class EventRouter : public Camera::Listener, public FrameListener - { - public: - PageManager* pManager; - WorldMap* pWorldMap; - CameraList* pCameraList; - - EventRouter() : pManager(0), pWorldMap(0), pCameraList(0) {} - ~EventRouter() {} - - void cameraPreRenderScene(Camera* cam) override; - void cameraDestroyed(Camera* cam) override; - bool frameStarted(const FrameEvent& evt) override; - bool frameEnded(const FrameEvent& evt) override; - }; - - void createStandardStrategies(); - void createStandardContentFactories(); - - WorldMap mWorlds; - StrategyMap mStrategies; - ContentCollectionFactoryMap mContentCollectionFactories; - ContentFactoryMap mContentFactories; - WorldSectionFactoryMap mWorldSectionFactories; - NameGenerator mWorldNameGenerator; - PageProvider* mPageProvider; - String mPageResourceGroup; - CameraList mCameraList; - EventRouter mEventRouter; - uint8 mDebugDisplayLvl; - bool mPagingEnabled; - - Grid2DPageStrategy* mGrid2DPageStrategy; - Grid3DPageStrategy* mGrid3DPageStrategy; - SimplePageContentCollectionFactory* mSimpleCollectionFactory; - }; - - /** @} */ - /** @} */ -} - -#endif diff --git a/Components/Paging/include/OgrePageStrategy.h b/Components/Paging/include/OgrePageStrategy.h deleted file mode 100644 index 0b8b91932af..00000000000 --- a/Components/Paging/include/OgrePageStrategy.h +++ /dev/null @@ -1,139 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_PageStrategy_H__ -#define __Ogre_PageStrategy_H__ - -#include "OgrePagingPrerequisites.h" - - -namespace Ogre -{ - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Paging - * Some details on paging component - * @{ - */ - - - /** Abstract marker class representing the data held against the PagedWorldSection - which is specifically used by the PageStrategy. - */ - class _OgrePagingExport PageStrategyData : public PageAlloc - { - public: - PageStrategyData() {} - virtual ~PageStrategyData() {} - - /// Load this data from a stream (returns true if successful) - virtual bool load(StreamSerialiser& stream) = 0; - /// Save this data to a stream - virtual void save(StreamSerialiser& stream) = 0; - - - }; - - - /** Defines the interface to a strategy class which is responsible for deciding - when Page instances are requested for addition and removal from the - paging system. - - The interface is deliberately light, with no specific mention of requesting - new Page instances. It is entirely up to the PageStrategy to respond - to the events raised on it and to call methods on other classes (such as - requesting new pages). - */ - class _OgrePagingExport PageStrategy : public PageAlloc - { - protected: - String mName; - PageManager* mManager; - public: - PageStrategy(const String& name, PageManager* manager) - : mName(name), mManager(manager) - { - - } - - virtual ~PageStrategy() {} - - const String& getName() const { return mName; } - PageManager* getManager() const { return mManager; } - - /// Called when the frame starts - virtual void frameStart(Real timeSinceLastFrame, PagedWorldSection* section) {} - /// Called when the frame ends - virtual void frameEnd(Real timeElapsed, PagedWorldSection* section) {} - /** Called when a camera is used for any kind of rendering. - - This is probably the primary way in which the strategy will request - new pages. - @param cam Camera which is being used for rendering. Class should not - rely on this pointer remaining valid permanently because no notification - will be given when the camera is destroyed. - @param section - */ - virtual void notifyCamera(Camera* cam, PagedWorldSection* section) {} - - /** Create a PageStrategyData instance containing the data specific to this - PageStrategy. - @par - This data will be held by a given PagedWorldSection and the structure of - the data will be specific to the PageStrategy subclass. - */ - virtual PageStrategyData* createData() OGRE_NODISCARD = 0; - - /** Destroy a PageStrategyData instance containing the data specific to this - PageStrategy. - @par - This data will be held by a given PagedWorldSection and the structure of - the data will be specific to the PageStrategy subclass. - */ - virtual void destroyData(PageStrategyData* d) = 0; - - /** Update the contents of the passed in SceneNode to reflect the - debug display of a given page. - - The PageStrategy is to have complete control of the contents of this - SceneNode, it must not be altered / added to by others. - */ - virtual void updateDebugDisplay(Page* p, SceneNode* sn) = 0; - - /** Get the page ID for a given world position. - @return The page ID - */ - virtual PageID getPageID(const Vector3& worldPos, PagedWorldSection* section) = 0; - }; - - /*@}*/ - /*@}*/ -} - -#endif diff --git a/Components/Paging/include/OgrePagedWorld.h b/Components/Paging/include/OgrePagedWorld.h deleted file mode 100644 index 843b325e781..00000000000 --- a/Components/Paging/include/OgrePagedWorld.h +++ /dev/null @@ -1,250 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_PagedWorld_H__ -#define __Ogre_PagedWorld_H__ - -#include "OgrePagingPrerequisites.h" -#include "OgreCommon.h" -#include "OgreNameGenerator.h" - -namespace Ogre -{ - class PageManager; - - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Paging - * Some details on paging component - * @{ - */ - - - /** This class represents a collection of pages which make up a world. - - It's important to bear in mind that the PagedWorld only delineates the - world and knows how to find out about the contents of it. It does not, - by design, contain all elements of the world, in memory, at once. - */ - class _OgrePagingExport PagedWorld : public PageAlloc - { - String mName; - PageManager* mManager; - PageProvider* mPageProvider; - - public: - static const uint32 CHUNK_ID; - static const uint16 CHUNK_VERSION; - static const uint32 CHUNK_SECTIONDECLARATION_ID; - /** Constructor. - @param name The name of the world, which must be enough to identify the - place where data for it can be loaded from (doesn't have to be a filename - necessarily). - @param manager The PageManager that is in charge of providing this world with - services such as related object factories. - */ - PagedWorld(const String& name, PageManager* manager); - virtual ~PagedWorld(); - - const String& getName() const { return mName; } - /// Get the manager of this world - PageManager* getManager() const { return mManager; } - - /// Load world data from a file - void load(const String& filename); - /// Load world data from a stream - void load(const DataStreamPtr& stream); - /// Load world data from a serialiser (returns true if successful) - bool load(StreamSerialiser& stream); - /** Save world data to a file - @param filename The name of the file to create; this can either be an - absolute filename or - */ - void save(const String& filename); - /// Save world data to a stream - void save(const DataStreamPtr& stream); - /// Save world data to a serialiser - void save(StreamSerialiser& stream); - - /** Create a new section of the world based on a specialised type. - - World sections are areas of the world that use a particular - PageStrategy, with a certain set of parameters specific to that - strategy, and potentially some other rules. - So you would have more than one section in a world only - if you needed different simultaneous paging strategies, or you - wanted the same strategy but parameterised differently. - @param sceneMgr The SceneManager to use for this section. - @param typeName The type of section to use (must be registered - with PageManager), or blank to use the default type (simple grid) - @param sectionName An optional name to give the section (if none is - provided, one will be generated) - */ - PagedWorldSection* createSection(SceneManager* sceneMgr, - const String& typeName, - const String& sectionName = BLANKSTRING); - - - /** Create a new manually defined section of the world. - - World sections are areas of the world that use a particular - PageStrategy, with a certain set of parameters specific to that - strategy. So you would have more than one section in a world only - if you needed different simultaneous paging strategies, or you - wanted the same strategy but parameterised differently. - @param strategyName The name of the strategy to use (must be registered - with PageManager) - @param sceneMgr The SceneManager to use for this section - @param sectionName An optional name to give the section (if none is - provided, one will be generated) - */ - PagedWorldSection* createSection(const String& strategyName, SceneManager* sceneMgr, - const String& sectionName = BLANKSTRING); - - - /** Create a manually defined new section of the world. - - World sections are areas of the world that use a particular - PageStrategy, with a certain set of parameters specific to that - strategy. So you would have more than one section in a world only - if you needed different simultaneous paging strategies, or you - wanted the same strategy but parameterised differently. - @param strategy The strategy to use - @param sceneMgr The SceneManager to use for this section - @param sectionName An optional name to give the section (if none is - provided, one will be generated) - */ - PagedWorldSection* createSection(PageStrategy* strategy, SceneManager* sceneMgr, - const String& sectionName = BLANKSTRING); - /** Destroy a section of world. */ - void destroySection(const String& name); - /** Destroy a section of world. */ - void destroySection(PagedWorldSection* sec); - /** Destroy all world sections */ - void destroyAllSections(); - - /** Get the number of sections this world has. */ - size_t getSectionCount() const { return mSections.size(); } - - /** Retrieve a section of the world. */ - PagedWorldSection* getSection(const String& name); - - typedef std::map SectionMap; - /// Retrieve a const reference to all the sections in this world - const SectionMap& getSections() const { return mSections; } - - /** Set the PageProvider which can provide streams for Pages in this world. - - This is the top-level way that you can direct how Page data is loaded. - When data for a Page is requested for a PagedWorldSection, the following - sequence of classes will be checked to see if they have a provider willing - to supply the stream: PagedWorldSection, PagedWorld, PageManager. - If none of these do, then the default behaviour is to look for a file - called worldname_sectionname_pageID.page. - @note - The caller remains responsible for the destruction of the provider. - */ - void setPageProvider(PageProvider* provider) { mPageProvider = provider; } - - /** Get the PageProvider which can provide streams for Pages in this world. */ - PageProvider* getPageProvider() const { return mPageProvider; } - - /** Give a world the opportunity to prepare page content procedurally. - - You should not call this method directly. This call may well happen in - a separate thread so it should not access GPU resources, use _loadProceduralPage - for that - @return true if the page was populated, false otherwise - */ - virtual bool _prepareProceduralPage(Page* page, PagedWorldSection* section); - /** Give a world the opportunity to prepare page content procedurally. - - You should not call this method directly. This call will happen in - the main render thread so it can access GPU resources. Use _prepareProceduralPage - for background preparation. - @return true if the page was populated, false otherwise - */ - virtual bool _loadProceduralPage(Page* page, PagedWorldSection* section); - /** Give a world the opportunity to unload page content procedurally. - - You should not call this method directly. This call will happen in - the main render thread so it can access GPU resources. Use _unprepareProceduralPage - for background preparation. - @return true if the page was populated, false otherwise - */ - virtual bool _unloadProceduralPage(Page* page, PagedWorldSection* section); - /** Give a world the opportunity to unprepare page content procedurally. - - You should not call this method directly. This call may well happen in - a separate thread so it should not access GPU resources, use _unloadProceduralPage - for that - @return true if the page was unpopulated, false otherwise - */ - virtual bool _unprepareProceduralPage(Page* page, PagedWorldSection* section); - /** Get a serialiser set up to read Page data for the given PageID. - @param pageID The ID of the page being requested - @param section The parent section to which this page will belong - - The StreamSerialiser returned is the responsibility of the caller to - delete. - */ - StreamSerialiser* _readPageStream(PageID pageID, PagedWorldSection* section); - - /** Get a serialiser set up to read Page data for the given PageID. - @param pageID The ID of the page being requested - @param section The parent section to which this page will belong - - The StreamSerialiser returned is the responsibility of the caller to - delete. - */ - StreamSerialiser* _writePageStream(PageID pageID, PagedWorldSection* section); - - /// Called when the frame starts - virtual void frameStart(Real timeSinceLastFrame); - /// Called when the frame ends - virtual void frameEnd(Real timeElapsed); - /// Notify a world of the current camera - virtual void notifyCamera(Camera* cam); - - /** Function for writing to a stream. - */ - _OgrePagingExport friend std::ostream& operator <<( std::ostream& o, const PagedWorld& p ); - - - private: - SectionMap mSections; - NameGenerator mSectionNameGenerator; - }; - - /** @} */ - /** @} */ - -} - -#endif diff --git a/Components/Paging/include/OgrePagedWorldSection.h b/Components/Paging/include/OgrePagedWorldSection.h deleted file mode 100644 index 16f916341e9..00000000000 --- a/Components/Paging/include/OgrePagedWorldSection.h +++ /dev/null @@ -1,316 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_PagedWorldSection_H__ -#define __Ogre_PagedWorldSection_H__ - -#include "OgrePagingPrerequisites.h" -#include "OgreAxisAlignedBox.h" - -namespace Ogre -{ - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Paging - * Some details on paging component - * @{ - */ - - /** Represents a section of the PagedWorld which uses a given PageStrategy, and - which is made up of a generally localised set of Page instances. - - The reason for PagedWorldSection is that you may wish to cater for multiple - sections of your world which use a different approach to paging (ie a - different PageStrategy), or which are significantly far apart or separate - that the parameters you want to pass to the PageStrategy are different. - @par - PagedWorldSection instances are fully contained within the PagedWorld and - their definitions are loaded in their entirety when the PagedWorld is - loaded. However, no Page instances are initially loaded - those are the - responsibility of the PageStrategy. - @par - PagedWorldSection can be subclassed and derived types provided by a - PagedWorldSectionFactory. These subclasses might come preconfigured - with a strategy for example, or with additional metadata used only for - that particular type of section. - @par - A PagedWorldSection targets a specific SceneManager. When you create one - in code via PagedWorld::createSection, you pass that SceneManager in manually. - When loading from a saved world file however, the SceneManager type and - instance name are saved and that SceneManager is looked up on loading, or - created if it didn't exist. - */ - class _OgrePagingExport PagedWorldSection : public PageAlloc - { - public: - typedef std::map PageMap; - protected: - String mName; - AxisAlignedBox mAABB; - PagedWorld* mParent; - PageStrategy* mStrategy; - PageStrategyData* mStrategyData; - PageMap mPages; - PageProvider* mPageProvider; - SceneManager* mSceneMgr; - private: - /// Load data specific to a subtype of this class (if any) - virtual void loadSubtypeData(StreamSerialiser& ser) {} - virtual void saveSubtypeData(StreamSerialiser& ser) {} - - - public: - static const uint32 CHUNK_ID; - static const uint16 CHUNK_VERSION; - - /** Construct a new instance, specifying the parent and scene manager. */ - PagedWorldSection(const String& name, PagedWorld* parent, SceneManager* sm); - virtual ~PagedWorldSection(); - - PageManager* getManager() const; - - /// Get the name of this section - virtual const String& getName() const { return mName; } - /// Get the page strategy which this section is using - virtual PageStrategy* getStrategy() const { return mStrategy; } - /** Change the page strategy. - - Doing this will invalidate any pages attached to this world section, and - require the PageStrategyData to be repopulated. - */ - virtual void setStrategy(PageStrategy* strat); - /** Change the page strategy. - - Doing this will invalidate any pages attached to this world section, and - require the PageStrategyData to be repopulated. - */ - virtual void setStrategy(const String& stratName); - - /** Change the SceneManager. - - Doing this will invalidate any pages attached to this world section, and - require the pages to be reloaded. - */ - virtual void setSceneManager(SceneManager* sm); - - /** Change the SceneManager. - - Doing this will invalidate any pages attached to this world section, and - require the pages to be reloaded. - @param smName The instance name of the SceneManager - */ - virtual void setSceneManager(const String& smName); - /// Get the current SceneManager - virtual SceneManager* getSceneManager() const { return mSceneMgr; } - - /// Get the parent world - virtual PagedWorld* getWorld() const { return mParent; } - /// Get the data required by the PageStrategy which is specific to this world section - virtual PageStrategyData* getStrategyData() const { return mStrategyData; } - /// Set the bounds of this section - virtual void setBoundingBox(const AxisAlignedBox& box); - /// Get the bounds of this section - virtual const AxisAlignedBox& getBoundingBox() const; - - - /// Load this section from a stream (returns true if successful) - virtual bool load(StreamSerialiser& stream); - /// Save this section to a stream - virtual void save(StreamSerialiser& stream); - - - /// Called when the frame starts - virtual void frameStart(Real timeSinceLastFrame); - /// Called when the frame ends - virtual void frameEnd(Real timeElapsed); - /// Notify a section of the current camera - virtual void notifyCamera(Camera* cam); - - /** Load or create a page against this section covering the given world - space position. - - This method is designed mainly for editors - it will try to load - an existing page if there is one, otherwise it will create a new one - synchronously. - */ - virtual Page* loadOrCreatePage(const Vector3& worldPos); - - /** Get the page ID for a given world position. */ - virtual PageID getPageID(const Vector3& worldPos); - - - /** Ask for a page to be loaded with the given (section-relative) PageID - - You would not normally call this manually, the PageStrategy is in - charge of it usually. - If this page is already loaded, this request will not load it again. - If the page needs loading, then it may be an asynchronous process depending - on whether threading is enabled. - @param pageID The page ID to load - @param forceSynchronous If true, the page will always be loaded synchronously - */ - virtual void loadPage(PageID pageID, bool forceSynchronous = false); - - /** Ask for a page to be unloaded with the given (section-relative) PageID - - You would not normally call this manually, the PageStrategy is in - charge of it usually. - @param pageID The page ID to unload - @param forceSynchronous If true, the page will always be unloaded synchronously - */ - virtual void unloadPage(PageID pageID, bool forceSynchronous = false); - /** Ask for a page to be unloaded with the given (section-relative) PageID - - You would not normally call this manually, the PageStrategy is in - charge of it usually. - @param p The Page to unload - @param forceSynchronous If true, the page will always be unloaded synchronously - */ - virtual void unloadPage(Page* p, bool forceSynchronous = false); - /** Give a section the opportunity to prepare page content procedurally. - - You should not call this method directly. This call may well happen in - a separate thread so it should not access GPU resources, use _loadProceduralPage - for that - @return true if the page was populated, false otherwise - */ - virtual bool _prepareProceduralPage(Page* page); - /** Give a section the opportunity to prepare page content procedurally. - - You should not call this method directly. This call will happen in - the main render thread so it can access GPU resources. Use _prepareProceduralPage - for background preparation. - @return true if the page was populated, false otherwise - */ - virtual bool _loadProceduralPage(Page* page); - /** Give a section the opportunity to unload page content procedurally. - - You should not call this method directly. This call will happen in - the main render thread so it can access GPU resources. Use _unprepareProceduralPage - for background preparation. - @return true if the page was populated, false otherwise - */ - virtual bool _unloadProceduralPage(Page* page); - /** Give a section the opportunity to unprepare page content procedurally. - - You should not call this method directly. This call may well happen in - a separate thread so it should not access GPU resources, use _unloadProceduralPage - for that - @return true if the page was unpopulated, false otherwise - */ - virtual bool _unprepareProceduralPage(Page* page); - - /** Ask for a page to be kept in memory if it's loaded. - - This method indicates that a page should be retained if it's already - in memory, but if it's not then it won't trigger a load. This is useful - for retaining pages that have just gone out of range, but which you - don't want to unload just yet because it's quite possible they may come - back into the active set again very quickly / easily. But at the same - time, if they've already been purged you don't want to force them to load. - This is the 'maybe' region of pages. - @par - Any Page that is neither requested nor held in a frame will be - deemed a candidate for unloading. - */ - virtual void holdPage(PageID pageID); - - /** Retrieves a Page. - - This method will only return Page instances that are already loaded. It - will return null if a page is not loaded. - */ - virtual Page* getPage(PageID pageID); - - /** Remove all pages immediately. - - Effectively 'resets' this section by deleting all pages. - */ - virtual void removeAllPages(); - - /** Set the PageProvider which can provide streams Pages in this section. - - This is the top-level way that you can direct how Page data is loaded. - When data for a Page is requested for a PagedWorldSection, the following - sequence of classes will be checked to see if they have a provider willing - to supply the stream: PagedWorldSection, PagedWorld, PageManager. - If none of these do, then the default behaviour is to look for a file - called worldname_sectionname_pageID.page. - @note - The caller remains responsible for the destruction of the provider. - */ - virtual void setPageProvider(PageProvider* provider) { mPageProvider = provider; } - - /** Get the PageProvider which can provide streams for Pages in this section. */ - virtual PageProvider* getPageProvider() const { return mPageProvider; } - - /** Get a serialiser set up to read Page data for the given PageID. - @param pageID The ID of the page being requested - - The StreamSerialiser returned is the responsibility of the caller to - delete. - */ - virtual StreamSerialiser* _readPageStream(PageID pageID); - - /** Get a serialiser set up to write Page data for the given PageID. - @param pageID The ID of the page being requested - - The StreamSerialiser returned is the responsibility of the caller to - delete. - */ - virtual StreamSerialiser* _writePageStream(PageID pageID); - - /** Function for writing to a stream. - */ - _OgrePagingExport friend std::ostream& operator <<( std::ostream& o, const PagedWorldSection& p ); - - /** Get the type name of this section. */ - virtual const String& getType(); - - }; - - - /** A factory class for creating types of world section. - */ - class _OgrePagingExport PagedWorldSectionFactory : public PageAlloc - { - public: - virtual ~PagedWorldSectionFactory() {} - virtual const String& getName() const = 0; - virtual PagedWorldSection* createInstance(const String& name, PagedWorld* parent, SceneManager* sm) = 0; - virtual void destroyInstance(PagedWorldSection*) = 0; - - - }; - - /** @} */ - /** @} */ -} - -#endif diff --git a/Components/Paging/include/OgrePaging.h b/Components/Paging/include/OgrePaging.h deleted file mode 100644 index eca5684d2ef..00000000000 --- a/Components/Paging/include/OgrePaging.h +++ /dev/null @@ -1,45 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Ogre_Paging_H__ -#define __Ogre_Paging_H__ - -// Convenience header for user applications to reference all of the paging component - -#include "OgreGrid2DPageStrategy.h" -#include "OgrePage.h" -#include "OgrePageConnection.h" -#include "OgrePageContent.h" -#include "OgrePageContentCollection.h" -#include "OgrePagedWorld.h" -#include "OgrePagedWorldSection.h" -#include "OgrePageManager.h" -#include "OgrePageStrategy.h" -#include "OgreSimplePageContentCollection.h" - - -#endif diff --git a/Components/Paging/include/OgrePagingPrerequisites.h b/Components/Paging/include/OgrePagingPrerequisites.h deleted file mode 100644 index 3d61716c0b1..00000000000 --- a/Components/Paging/include/OgrePagingPrerequisites.h +++ /dev/null @@ -1,84 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_Paging_Prereq_H__ -#define __Ogre_Paging_Prereq_H__ - -#include "OgrePrerequisites.h" - -namespace Ogre -{ - // forward decls - class Grid2DPageStrategy; - class Grid3DPageStrategy; - class Page; - class PageConnection; - class PageContent; - class PageContentFactory; - class PageContentCollection; - class PageContentCollectionFactory; - class PagedWorld; - class PagedWorldSection; - class PageManager; - class PageStrategy; - class PageStrategyData; - class PageProvider; - class SimplePageContentCollection; - class SimplePageContentCollectionFactory; - - - typedef GeneralAllocatedObject PageAlloc; - - /// Identifier for a page - typedef uint32 PageID; - -} - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT -# if defined( OGRE_STATIC_LIB ) -# define _OgrePagingExport -# else -# if defined( OGRE_PAGING_EXPORTS ) -# define _OgrePagingExport __declspec( dllexport ) -# else -# if defined( __MINGW32__ ) -# define _OgrePagingExport -# else -# define _OgrePagingExport __declspec( dllimport ) -# endif -# endif -# endif -#elif defined ( OGRE_GCC_VISIBILITY ) -# define _OgrePagingExport __attribute__ ((visibility("default"))) -#else -# define _OgrePagingExport -#endif - - - -#endif diff --git a/Components/Paging/include/OgreSimplePageContentCollection.h b/Components/Paging/include/OgreSimplePageContentCollection.h deleted file mode 100644 index abf96ea862b..00000000000 --- a/Components/Paging/include/OgreSimplePageContentCollection.h +++ /dev/null @@ -1,137 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_SimplePageContentCollection_H__ -#define __Ogre_SimplePageContentCollection_H__ - -#include "OgrePagingPrerequisites.h" -#include "OgrePageContentCollection.h" -#include "OgrePageContentCollectionFactory.h" - -namespace Ogre -{ - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Paging - * Some details on paging component - * @{ - */ - - - /** Specialisation of PageContentCollection which just provides a simple list - of PageContent instances. - @par - The data format for this in a file is:
- SimplePageContentCollectionData (Identifier 'SPCD')\n - [Version 1] - - - - - - - - - - - -
NameTypeDescription
Nested contentsNested chunk listA sequence of nested PageContent chunks
- */ - class _OgrePagingExport SimplePageContentCollection : public PageContentCollection - { - public: - typedef std::vector ContentList; - static const uint32 SUBCLASS_CHUNK_ID; - static const uint16 SUBCLASS_CHUNK_VERSION; - private: - ContentList mContentList; - public: - SimplePageContentCollection(PageContentCollectionFactory* creator); - ~SimplePageContentCollection(); - - /** Create a new PageContent within this collection. - @param typeName The name of the type of content (see PageManager::getContentFactories) - */ - virtual PageContent* createContent(const String& typeName); - - /** Destroy a PageContent within this page. - This is equivalent to calling detachContent and - PageManager::destroyContent. - */ - virtual void destroyContent(PageContent* coll); - - /// Get const access to the list of content - virtual const ContentList& getContentList() const { return mContentList; } - - // Overridden from PageContentCollection - void save(StreamSerialiser& stream) override; - void frameStart(Real timeSinceLastFrame) override; - void frameEnd(Real timeElapsed) override; - void notifyCamera(Camera* cam) override; - bool prepare(StreamSerialiser& stream) override; - void load() override; - void unload() override; - void unprepare() override; - - protected: - - - - - }; - - - /// Factory class for SimplePageContentCollection - class _OgrePagingExport SimplePageContentCollectionFactory : public PageContentCollectionFactory - { - public: - static String FACTORY_NAME; - - SimplePageContentCollectionFactory() {} - ~SimplePageContentCollectionFactory() {} - - const String& getName() const override { return FACTORY_NAME; } - - PageContentCollection* createInstance() override OGRE_NODISCARD - { - return OGRE_NEW SimplePageContentCollection(this); - } - void destroyInstance(PageContentCollection* c) override - { - OGRE_DELETE c; - } - - - }; - - /*@}*/ - /*@}*/ -} - -#endif diff --git a/Components/Paging/src/OgreGrid2DPageStrategy.cpp b/Components/Paging/src/OgreGrid2DPageStrategy.cpp deleted file mode 100644 index 65cfea1ff64..00000000000 --- a/Components/Paging/src/OgreGrid2DPageStrategy.cpp +++ /dev/null @@ -1,459 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreGrid2DPageStrategy.h" - -#include -#include "OgreStreamSerialiser.h" -#include "OgreCamera.h" -#include "OgrePagedWorldSection.h" -#include "OgrePage.h" -#include "OgreSceneNode.h" -#include "OgreSceneManager.h" -#include "OgreMaterialManager.h" -#include "OgreManualObject.h" -#include "OgrePageManager.h" -#include "OgreTechnique.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - const uint32 Grid2DPageStrategyData::CHUNK_ID = StreamSerialiser::makeIdentifier("G2DD"); - const uint16 Grid2DPageStrategyData::CHUNK_VERSION = 1; - //--------------------------------------------------------------------- - Grid2DPageStrategyData::Grid2DPageStrategyData() - : PageStrategyData() - , mMode(G2D_X_Z) - , mWorldOrigin(Vector3::ZERO) - , mOrigin(Vector2::ZERO) - , mCellSize(1000) - , mLoadRadius(2000) - , mHoldRadius(3000) - , mMinCellX(-32768) - , mMinCellY(-32768) - , mMaxCellX(32767) - , mMaxCellY(32767) - { - updateDerivedMetrics(); - - } - //--------------------------------------------------------------------- - void Grid2DPageStrategyData::setCellRange(int32 minX, int32 minY, int32 maxX, int32 maxY) - { - mMinCellX = minX; - mMinCellY = minY; - mMaxCellX = maxX; - mMaxCellY = maxY; - } - //--------------------------------------------------------------------- - void Grid2DPageStrategyData::setCellRangeMinX(int32 minX) - { - mMinCellX = minX; - } - //--------------------------------------------------------------------- - void Grid2DPageStrategyData::setCellRangeMinY(int32 minY) - { - mMinCellY = minY; - } - //--------------------------------------------------------------------- - void Grid2DPageStrategyData::setCellRangeMaxX(int32 maxX) - { - mMaxCellX = maxX; - } - //--------------------------------------------------------------------- - void Grid2DPageStrategyData::setCellRangeMaxY(int32 maxY) - { - mMaxCellY = maxY; - } - //--------------------------------------------------------------------- - Grid2DPageStrategyData::~Grid2DPageStrategyData() - { - - } - //--------------------------------------------------------------------- - void Grid2DPageStrategyData::setMode(Grid2DMode mode) - { - mMode = mode; - // reset origin - setOrigin(mWorldOrigin); - } - //--------------------------------------------------------------------- - void Grid2DPageStrategyData::setOrigin(const Vector3& worldOrigin) - { - mWorldOrigin = worldOrigin; - convertWorldToGridSpace(mWorldOrigin, mOrigin); - updateDerivedMetrics(); - } - //--------------------------------------------------------------------- - void Grid2DPageStrategyData::convertWorldToGridSpace(const Vector3& world, Vector2& grid) - { - switch(mMode) - { - case G2D_X_Z: - grid.x = world.x; - grid.y = -world.z; - break; - case G2D_X_Y: - grid.x = world.x; - grid.y = world.y; - break; - case G2D_Y_Z: - grid.x = -world.z; - grid.y = world.y; - break; - } - } - //--------------------------------------------------------------------- - void Grid2DPageStrategyData::convertGridToWorldSpace(const Vector2& grid, Vector3& world) - { - // Note that we don't set the 3rd coordinate, let the caller determine that - switch(mMode) - { - case G2D_X_Z: - world.x = grid.x; - world.z = -grid.y; - break; - case G2D_X_Y: - world.x = grid.x; - world.y = grid.y; - break; - case G2D_Y_Z: - world.z = -grid.x; - world.y = grid.y; - break; - } - } - //--------------------------------------------------------------------- - void Grid2DPageStrategyData::updateDerivedMetrics() - { - mLoadRadiusInCells = mLoadRadius / mCellSize; - mHoldRadiusInCells = mHoldRadius / mCellSize; - } - //--------------------------------------------------------------------- - void Grid2DPageStrategyData::determineGridLocation(const Vector2& gridpos, int32 *x, int32 *y) - { - Vector2 relPos = gridpos - mOrigin; - Real offset = mCellSize * 0.5f; - relPos.x += offset; - relPos.y += offset; - - *x = static_cast(std::floor(relPos.x / mCellSize)); - *y = static_cast(std::floor(relPos.y / mCellSize)); - - } - //--------------------------------------------------------------------- - void Grid2DPageStrategyData::getBottomLeftGridSpace(int32 x, int32 y, Vector2& bl) - { - Real offset = mCellSize * 0.5f; - bl.x = mOrigin.x - offset + x * mCellSize; - bl.y = mOrigin.y - offset + y * mCellSize; - } - //--------------------------------------------------------------------- - void Grid2DPageStrategyData::getMidPointGridSpace(int32 x, int32 y, Vector2& mid) - { - mid.x = mOrigin.x + x * mCellSize; - mid.y = mOrigin.y + y * mCellSize; - } - //--------------------------------------------------------------------- - void Grid2DPageStrategyData::getCornersGridSpace(int32 x, int32 y, Vector2* pFourPoints) - { - getBottomLeftGridSpace(x, y, pFourPoints[0]); - pFourPoints[1] = pFourPoints[0] + Vector2(mCellSize, 0); - pFourPoints[2] = pFourPoints[0] + Vector2(mCellSize, mCellSize); - pFourPoints[3] = pFourPoints[0] + Vector2(0, mCellSize); - } - //--------------------------------------------------------------------- - void Grid2DPageStrategyData::setCellSize(Real sz) - { - mCellSize = sz; - updateDerivedMetrics(); - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - void Grid2DPageStrategyData::setLoadRadius(Real sz) - { - mLoadRadius = sz; - updateDerivedMetrics(); - } - //--------------------------------------------------------------------- - void Grid2DPageStrategyData::setHoldRadius(Real sz) - { - mHoldRadius = sz; - updateDerivedMetrics(); - } - //--------------------------------------------------------------------- - PageID Grid2DPageStrategyData::calculatePageID(int32 x, int32 y) - { - // Convert to signed 16-bit so sign bit is in bit 15 - int16 xs16 = static_cast(x); - int16 ys16 = static_cast(y); - - // convert to unsigned because we do not want to propagate sign bit to 32-bits - uint16 x16 = static_cast(xs16); - uint16 y16 = static_cast(ys16); - - uint32 key = 0; - key = (x16 << 16) | y16; - - return (PageID)key; - - } - //--------------------------------------------------------------------- - void Grid2DPageStrategyData::calculateCell(PageID inPageID, int32 *x, int32 *y) - { - // inverse of calculatePageID - // unsigned versions - uint16 y16 = static_cast(inPageID & 0xFFFF); - uint16 x16 = static_cast((inPageID >> 16) & 0xFFFF); - - *x = static_cast(x16); - *y = static_cast(y16); - - } - //--------------------------------------------------------------------- - bool Grid2DPageStrategyData::load(StreamSerialiser& ser) - { - if (!ser.readChunkBegin(CHUNK_ID, CHUNK_VERSION, "Grid2DPageStrategyData")) - return false; - - uint8 readMode; - ser.read(&readMode); - mMode = (Grid2DMode)readMode; - - Vector3 origin; - ser.read(&origin); - setOrigin(origin); - - ser.read(&mCellSize); - ser.read(&mLoadRadius); - ser.read(&mHoldRadius); - ser.read(&mMinCellX); - ser.read(&mMaxCellX); - ser.read(&mMinCellY); - ser.read(&mMaxCellY); - - ser.readChunkEnd(CHUNK_ID); - - return true; - } - //--------------------------------------------------------------------- - void Grid2DPageStrategyData::save(StreamSerialiser& ser) - { - ser.writeChunkBegin(CHUNK_ID, CHUNK_VERSION); - - uint8 readMode = (uint8)mMode; - ser.write(&readMode); - - ser.write(&mWorldOrigin); - ser.write(&mCellSize); - ser.write(&mLoadRadius); - ser.write(&mHoldRadius); - ser.write(&mMinCellX); - ser.write(&mMaxCellX); - ser.write(&mMinCellY); - ser.write(&mMaxCellY); - - ser.writeChunkEnd(CHUNK_ID); - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - Grid2DPageStrategy::Grid2DPageStrategy(PageManager* manager) - : PageStrategy("Grid2D", manager) - { - - } - //--------------------------------------------------------------------- - Grid2DPageStrategy::~Grid2DPageStrategy() - { - - } - //--------------------------------------------------------------------- - void Grid2DPageStrategy::notifyCamera(Camera* cam, PagedWorldSection* section) - { - Grid2DPageStrategyData* stratData = static_cast(section->getStrategyData()); - - const Vector3& pos = cam->getDerivedPosition(); - Vector2 gridpos; - stratData->convertWorldToGridSpace(pos, gridpos); - int32 x, y; - stratData->determineGridLocation(gridpos, &x, &y); - - Real loadRadius = stratData->getLoadRadiusInCells(); - Real holdRadius = stratData->getHoldRadiusInCells(); - // scan the whole Hold range - Real fxmin = (Real)x - holdRadius; - Real fxmax = (Real)x + holdRadius; - Real fymin = (Real)y - holdRadius; - Real fymax = (Real)y + holdRadius; - - int32 xmin = stratData->getCellRangeMinX(); - int32 xmax = stratData->getCellRangeMaxX(); - int32 ymin = stratData->getCellRangeMinY(); - int32 ymax = stratData->getCellRangeMaxY(); - - // Round UP max, round DOWN min - xmin = fxmin < xmin ? xmin : (int32)floor(fxmin); - xmax = fxmax > xmax ? xmax : (int32)ceil(fxmax); - ymin = fymin < ymin ? ymin : (int32)floor(fymin); - ymax = fymax > ymax ? ymax : (int32)ceil(fymax); - // the inner, active load range - fxmin = (Real)x - loadRadius; - fxmax = (Real)x + loadRadius; - fymin = (Real)y - loadRadius; - fymax = (Real)y + loadRadius; - // Round UP max, round DOWN min - int32 loadxmin = fxmin < xmin ? xmin : (int32)floor(fxmin); - int32 loadxmax = fxmax > xmax ? xmax : (int32)ceil(fxmax); - int32 loadymin = fymin < ymin ? ymin : (int32)floor(fymin); - int32 loadymax = fymax > ymax ? ymax : (int32)ceil(fymax); - - for (int32 cy = ymin; cy <= ymax; ++cy) - { - for (int32 cx = xmin; cx <= xmax; ++cx) - { - PageID pageID = stratData->calculatePageID(cx, cy); - if (cx >= loadxmin && cx <= loadxmax && cy >= loadymin && cy <= loadymax) - { - // in the 'load' range, request it - section->loadPage(pageID); - } - else - { - // in the outer 'hold' range, keep it but don't actively load - section->holdPage(pageID); - } - // other pages will by inference be marked for unloading - } - } - - - - } - //--------------------------------------------------------------------- - PageStrategyData* Grid2DPageStrategy::createData() - { - return OGRE_NEW Grid2DPageStrategyData(); - } - //--------------------------------------------------------------------- - void Grid2DPageStrategy::destroyData(PageStrategyData* d) - { - OGRE_DELETE d; - } - //--------------------------------------------------------------------- - void Grid2DPageStrategy::updateDebugDisplay(Page* p, SceneNode* sn) - { - uint8 dbglvl = mManager->getDebugDisplayLevel(); - if (dbglvl) - { - // we could try to avoid updating the geometry every time here, but this - // wouldn't easily deal with paging parameter changes. There shouldn't - // be that many pages anyway, and this is debug after all, so update every time - int32 x, y; - Grid2DPageStrategyData* stratData = static_cast( - p->getParentSection()->getStrategyData()); - stratData->calculateCell(p->getID(), &x, &y); - - Grid2DPageStrategyData* data = static_cast(p->getParentSection()->getStrategyData()); - - // Determine our centre point, we'll anchor here - // Note that world points are initialised to ZERO since only 2 dimensions - // are updated by the grid data (we could display this grid anywhere) - Vector2 gridMidPoint; - Vector3 worldMidPoint = Vector3::ZERO; - data->getMidPointGridSpace(x, y, gridMidPoint); - data->convertGridToWorldSpace(gridMidPoint, worldMidPoint); - - sn->setPosition(worldMidPoint); - - Vector2 gridCorners[4]; - Vector3 worldCorners[4]; - - data->getCornersGridSpace(x, y, gridCorners); - for (int i = 0; i < 4; ++i) - { - worldCorners[i] = Vector3::ZERO; - data->convertGridToWorldSpace(gridCorners[i], worldCorners[i]); - // make relative to mid point - worldCorners[i] -= worldMidPoint; - } - - String matName = "Ogre/G2D/Debug"; - MaterialPtr mat = MaterialManager::getSingleton().getByName(matName); - if (!mat) - { - mat = MaterialManager::getSingleton().create(matName, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - Pass* pass = mat->getTechnique(0)->getPass(0); - pass->setLightingEnabled(false); - pass->setVertexColourTracking(TVC_AMBIENT); - pass->setDepthWriteEnabled(false); - mat->load(); - } - - - ManualObject* mo = 0; - if (sn->numAttachedObjects() == 0) - { - mo = p->getParentSection()->getSceneManager()->createManualObject(); - mo->begin(matName, RenderOperation::OT_LINE_STRIP); - } - else - { - mo = static_cast(sn->getAttachedObject(0)); - mo->beginUpdate(0); - } - - ColourValue vcol = ColourValue::Green; - for(int i = 0; i < 5; ++i) - { - mo->position(worldCorners[i%4]); - mo->colour(vcol); - } - - mo->end(); - - if (sn->numAttachedObjects() == 0) - sn->attachObject(mo); - - } - - } - //--------------------------------------------------------------------- - PageID Grid2DPageStrategy::getPageID(const Vector3& worldPos, PagedWorldSection* section) - { - Grid2DPageStrategyData* stratData = static_cast(section->getStrategyData()); - - Vector2 gridpos; - stratData->convertWorldToGridSpace(worldPos, gridpos); - int32 x, y; - stratData->determineGridLocation(gridpos, &x, &y); - return stratData->calculatePageID(x, y); - - } - - -} - diff --git a/Components/Paging/src/OgreGrid3DPageStrategy.cpp b/Components/Paging/src/OgreGrid3DPageStrategy.cpp deleted file mode 100644 index f3c6431b373..00000000000 --- a/Components/Paging/src/OgreGrid3DPageStrategy.cpp +++ /dev/null @@ -1,424 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreGrid3DPageStrategy.h" - -#include - -#include "OgreStreamSerialiser.h" -#include "OgreCamera.h" -#include "OgrePagedWorldSection.h" -#include "OgrePage.h" -#include "OgreSceneNode.h" -#include "OgreSceneManager.h" -#include "OgreMaterialManager.h" -#include "OgreManualObject.h" -#include "OgrePageManager.h" -#include "OgreTechnique.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - const uint32 Grid3DPageStrategyData::CHUNK_ID = StreamSerialiser::makeIdentifier("G3DD"); - const uint16 Grid3DPageStrategyData::CHUNK_VERSION = 1; - //--------------------------------------------------------------------- - Grid3DPageStrategyData::Grid3DPageStrategyData() - : PageStrategyData() - , mWorldOrigin(Vector3::ZERO) - , mOrigin(Vector3::ZERO) - , mCellSize(1000,1000,1000) - , mLoadRadius(2000) - , mHoldRadius(3000) - , mMinCellX(-512) - , mMinCellY(-512) - , mMinCellZ(-512) - , mMaxCellX(511) - , mMaxCellY(511) - , mMaxCellZ(511) - { - } - //--------------------------------------------------------------------- - void Grid3DPageStrategyData::setCellRange(int32 minX, int32 minY, int32 minZ, int32 maxX, int32 maxY, int32 maxZ) - { - mMinCellX = minX; - mMinCellY = minY; - mMinCellZ = minZ; - mMaxCellX = maxX; - mMaxCellY = maxY; - mMaxCellZ = maxZ; - } - //--------------------------------------------------------------------- - void Grid3DPageStrategyData::setCellRangeMinX(int32 minX) - { - mMinCellX = minX; - } - //--------------------------------------------------------------------- - void Grid3DPageStrategyData::setCellRangeMinY(int32 minY) - { - mMinCellY = minY; - } - //--------------------------------------------------------------------- - void Grid3DPageStrategyData::setCellRangeMinZ(int32 minZ) - { - mMinCellZ = minZ; - } - //--------------------------------------------------------------------- - void Grid3DPageStrategyData::setCellRangeMaxX(int32 maxX) - { - mMaxCellX = maxX; - } - //--------------------------------------------------------------------- - void Grid3DPageStrategyData::setCellRangeMaxY(int32 maxY) - { - mMaxCellY = maxY; - } - //--------------------------------------------------------------------- - void Grid3DPageStrategyData::setCellRangeMaxZ(int32 maxZ) - { - mMaxCellZ = maxZ; - } - //--------------------------------------------------------------------- - Grid3DPageStrategyData::~Grid3DPageStrategyData() - { - } - //--------------------------------------------------------------------- - void Grid3DPageStrategyData::setOrigin(const Vector3& origin) - { - mWorldOrigin = origin; - } - //--------------------------------------------------------------------- - void Grid3DPageStrategyData::determineGridLocation(const Vector3& pos, int32 *x, int32 *y, int32 *z) - { - Vector3 relPos = pos - mOrigin + mCellSize * 0.5f; - - *x = static_cast(std::floor(relPos.x / mCellSize.x)); - *y = static_cast(std::floor(relPos.y / mCellSize.y)); - *z = static_cast(std::floor(relPos.z / mCellSize.z)); - } - //--------------------------------------------------------------------- - void Grid3DPageStrategyData::getBottomLeftGridSpace(int32 x, int32 y, int32 z, Vector3& bl) - { - bl.x = mOrigin.x + (x-0.5f) * mCellSize.x; - bl.y = mOrigin.y + (y-0.5f) * mCellSize.y; - bl.z = mOrigin.z + (z-0.5f) * mCellSize.z; - } - //--------------------------------------------------------------------- - void Grid3DPageStrategyData::getMidPointGridSpace(int32 x, int32 y, int32 z, Vector3& mid) - { - mid.x = mOrigin.x + float(x) * mCellSize.x; - mid.y = mOrigin.y + float(y) * mCellSize.y; - mid.z = mOrigin.z + float(z) * mCellSize.z; - } - //--------------------------------------------------------------------- - void Grid3DPageStrategyData::getCornersGridSpace(int32 x, int32 y, int32 z, Vector3* pEightPoints) - { - getBottomLeftGridSpace(x, y, z, pEightPoints[0]); - pEightPoints[1] = pEightPoints[0] + Vector3(mCellSize.x, 0, 0); - pEightPoints[2] = pEightPoints[0] + Vector3(mCellSize.x, mCellSize.y, 0); - pEightPoints[3] = pEightPoints[0] + Vector3(0, mCellSize.y, 0); - pEightPoints[4] = pEightPoints[0] + Vector3(0, 0, mCellSize.z); - pEightPoints[5] = pEightPoints[1] + Vector3(0, 0, mCellSize.z); - pEightPoints[6] = pEightPoints[2] + Vector3(0, 0, mCellSize.z); - pEightPoints[7] = pEightPoints[3] + Vector3(0, 0, mCellSize.z); - } - //--------------------------------------------------------------------- - void Grid3DPageStrategyData::setCellSize(const Vector3& sz) - { - mCellSize = sz; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - void Grid3DPageStrategyData::setLoadRadius(Real sz) - { - mLoadRadius = sz; - } - //--------------------------------------------------------------------- - void Grid3DPageStrategyData::setHoldRadius(Real sz) - { - mHoldRadius = sz; - } - //--------------------------------------------------------------------- - PageID Grid3DPageStrategyData::calculatePageID(int32 x, int32 y, int32 z) - { - // Go into positive range (simpler on decode) - x -= mMinCellX; - y -= mMinCellY; - z -= mMinCellZ; - // Push index bits into place - uint32 key = z & 1023; - key = (key<<10) | (y&1023); - key = (key<<10) | (x&1023); - return (PageID)key; - } - //--------------------------------------------------------------------- - void Grid3DPageStrategyData::calculateCell(PageID inPageID, int32 *x, int32 *y, int32* z) - { - // Pop bits from page index: - int32 ox = inPageID & 1023; inPageID >>= 10; - int32 oy = inPageID & 1023; inPageID >>= 10; - int32 oz = inPageID & 1023; - //// Hand made sign extension from 10bits to 32: - //NOT NEEDED ANYMORE because this is crafted positive... - //if( ox > 511 ) ox = 1024 - ox; - //if( oy > 511 ) oy = 1024 - oy; - //if( oz > 511 ) oz = 1024 - oz; - // Back in the [min..max] range: - *x = ox + mMinCellX; - *y = oy + mMinCellY; - *z = oz + mMinCellZ; - } - //--------------------------------------------------------------------- - bool Grid3DPageStrategyData::load(StreamSerialiser& ser) - { - if (!ser.readChunkBegin(CHUNK_ID, CHUNK_VERSION, "Grid3DPageStrategyData")) - return false; - - ser.read(&mOrigin); - ser.read(&mCellSize); - ser.read(&mLoadRadius); - ser.read(&mHoldRadius); - ser.read(&mMinCellX); - ser.read(&mMaxCellX); - ser.read(&mMinCellY); - ser.read(&mMaxCellY); - ser.read(&mMinCellZ); - ser.read(&mMaxCellZ); - - ser.readChunkEnd(CHUNK_ID); - - return true; - } - //--------------------------------------------------------------------- - void Grid3DPageStrategyData::save(StreamSerialiser& ser) - { - ser.writeChunkBegin(CHUNK_ID, CHUNK_VERSION); - - ser.write(&mWorldOrigin); - ser.write(&mCellSize); - ser.write(&mLoadRadius); - ser.write(&mHoldRadius); - ser.write(&mMinCellX); - ser.write(&mMaxCellX); - ser.write(&mMinCellY); - ser.write(&mMaxCellY); - ser.write(&mMinCellZ); - ser.write(&mMaxCellZ); - - ser.writeChunkEnd(CHUNK_ID); - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - Grid3DPageStrategy::Grid3DPageStrategy(PageManager* manager) - : PageStrategy("Grid3D", manager) - { - - } - //--------------------------------------------------------------------- - Grid3DPageStrategy::~Grid3DPageStrategy() - { - - } - //--------------------------------------------------------------------- - void Grid3DPageStrategy::notifyCamera(Camera* cam, PagedWorldSection* section) - { - Grid3DPageStrategyData* stratData = static_cast(section->getStrategyData()); - - const Vector3& pos = cam->getDerivedPosition(); - int32 x, y, z; - stratData->determineGridLocation(pos, &x, &y, &z); - - Real loadRadius = stratData->getLoadRadius(); - Real holdRadius = stratData->getHoldRadius(); - // scan the whole Hold range - Real fxmin = (Real)x - holdRadius/stratData->getCellSize().x; - Real fxmax = (Real)x + holdRadius/stratData->getCellSize().x; - Real fymin = (Real)y - holdRadius/stratData->getCellSize().y; - Real fymax = (Real)y + holdRadius/stratData->getCellSize().y; - Real fzmin = (Real)z - holdRadius/stratData->getCellSize().z; - Real fzmax = (Real)z + holdRadius/stratData->getCellSize().z; - - int32 xmin = stratData->getCellRangeMinX(); - int32 xmax = stratData->getCellRangeMaxX(); - int32 ymin = stratData->getCellRangeMinY(); - int32 ymax = stratData->getCellRangeMaxY(); - int32 zmin = stratData->getCellRangeMinZ(); - int32 zmax = stratData->getCellRangeMaxZ(); - - // Round UP max, round DOWN min - xmin = fxmin < xmin ? xmin : (int32)floor(fxmin); - xmax = fxmax > xmax ? xmax : (int32)ceil(fxmax); - ymin = fymin < ymin ? ymin : (int32)floor(fymin); - ymax = fymax > ymax ? ymax : (int32)ceil(fymax); - zmin = fzmin < zmin ? zmin : (int32)floor(fzmin); - zmax = fzmax > zmax ? zmax : (int32)ceil(fzmax); - // the inner, active load range - fxmin = (Real)x - loadRadius/stratData->getCellSize().x; - fxmax = (Real)x + loadRadius/stratData->getCellSize().x; - fymin = (Real)y - loadRadius/stratData->getCellSize().y; - fymax = (Real)y + loadRadius/stratData->getCellSize().y; - fzmin = (Real)z - loadRadius/stratData->getCellSize().z; - fzmax = (Real)z + loadRadius/stratData->getCellSize().z; - // Round UP max, round DOWN min - int32 loadxmin = fxmin < xmin ? xmin : (int32)floor(fxmin); - int32 loadxmax = fxmax > xmax ? xmax : (int32)ceil(fxmax); - int32 loadymin = fymin < ymin ? ymin : (int32)floor(fymin); - int32 loadymax = fymax > ymax ? ymax : (int32)ceil(fymax); - int32 loadzmin = fzmin < zmin ? zmin : (int32)floor(fzmin); - int32 loadzmax = fzmax > zmax ? zmax : (int32)ceil(fzmax); - - for (int32 cz = zmin; cz <= zmax; ++cz) - { - for (int32 cy = ymin; cy <= ymax; ++cy) - { - for (int32 cx = xmin; cx <= xmax; ++cx) - { - PageID pageID = stratData->calculatePageID(cx, cy, cz); - - if (cx >= loadxmin && cx <= loadxmax - && cy >= loadymin && cy <= loadymax - && cz >= loadzmin && cz <= loadzmax ) - { - Vector3 bl; - stratData->getBottomLeftGridSpace(cx, cy, cz, bl); - Ogre::AxisAlignedBox bbox(bl, bl+stratData->getCellSize()); - - if( cam->isVisible(bbox) ) - section->loadPage(pageID); - else - section->holdPage(pageID); - } - else - { - // in the outer 'hold' range, keep it but don't actively load - section->holdPage(pageID); - } - // other pages will by inference be marked for unloading - } - } - } - } - //--------------------------------------------------------------------- - PageStrategyData* Grid3DPageStrategy::createData() - { - return OGRE_NEW Grid3DPageStrategyData(); - } - //--------------------------------------------------------------------- - void Grid3DPageStrategy::destroyData(PageStrategyData* d) - { - OGRE_DELETE d; - } - //--------------------------------------------------------------------- - void Grid3DPageStrategy::updateDebugDisplay(Page* p, SceneNode* sn) - { - uint8 dbglvl = mManager->getDebugDisplayLevel(); - if (dbglvl) - { - // we could try to avoid updating the geometry every time here, but this - // wouldn't easily deal with paging parameter changes. There shouldn't - // be that many pages anyway, and this is debug after all, so update every time - int32 x, y, z; - Grid3DPageStrategyData* stratData = static_cast( - p->getParentSection()->getStrategyData()); - stratData->calculateCell(p->getID(), &x, &y, &z); - - Grid3DPageStrategyData* data = static_cast(p->getParentSection()->getStrategyData()); - - // Determine our centre point, we'll anchor here - Vector3 midPoint; - data->getMidPointGridSpace(x, y, z, midPoint); - sn->setPosition(midPoint); - - //--- Get coordinates, relative to midPoint : - Vector3 corners[8]; - Vector3 hSize = 0.500f * stratData->getCellSize(); - for (int i = 0; i < 8; ++i) - { - corners[i].x = i&1 ? hSize.x : -hSize.x; - corners[i].z = i&2 ? hSize.y : -hSize.y; - corners[i].y = i&4 ? hSize.z : -hSize.z; - } - - //--- Get a material - String matName = "Ogre/G3D/Debug"; - MaterialPtr mat = MaterialManager::getSingleton().getByName(matName); - if (!mat) - { - mat = MaterialManager::getSingleton().create(matName, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - Pass* pass = mat->getTechnique(0)->getPass(0); - pass->setLightingEnabled(false); - pass->setVertexColourTracking(TVC_AMBIENT); - pass->setDepthWriteEnabled(false); - mat->load(); - } - - ManualObject* mo = 0; - bool update = sn->numAttachedObjects() > 0; - if( update ) - { - mo = static_cast(sn->getAttachedObject(0)); - mo->beginUpdate(0); - } - else - { - mo = p->getParentSection()->getSceneManager()->createManualObject(); - mo->begin(matName, RenderOperation::OT_LINE_STRIP); - } - - ColourValue vcol = ColourValue::Green; - mo->position(corners[0]); mo->colour(vcol); // First Square... - mo->position(corners[1]); mo->colour(vcol); - mo->position(corners[3]); mo->colour(vcol); - mo->position(corners[2]); mo->colour(vcol); - mo->position(corners[0]); mo->colour(vcol); - mo->position(corners[4]); mo->colour(vcol); // 0-4 link + second square and - mo->position(corners[5]); mo->colour(vcol); - mo->position(corners[7]); mo->colour(vcol); - mo->position(corners[6]); mo->colour(vcol); - mo->position(corners[4]); mo->colour(vcol); - mo->position(corners[5]); mo->colour(vcol); // 5-1 link - mo->position(corners[1]); mo->colour(vcol); - mo->position(corners[3]); mo->colour(vcol); // 3-7 link - mo->position(corners[7]); mo->colour(vcol); - mo->position(corners[6]); mo->colour(vcol); // 6-2 link - mo->position(corners[2]); mo->colour(vcol); - mo->end(); - - if(!update) - sn->attachObject(mo); - } - } - - //--------------------------------------------------------------------- - PageID Grid3DPageStrategy::getPageID(const Vector3& pos, PagedWorldSection* section) - { - Grid3DPageStrategyData* stratData = static_cast(section->getStrategyData()); - - int32 x, y, z; - stratData->determineGridLocation(pos, &x, &y, &z); - return stratData->calculatePageID(x, y, z); - } -} diff --git a/Components/Paging/src/OgrePage.cpp b/Components/Paging/src/OgrePage.cpp deleted file mode 100644 index 1b2897d6761..00000000000 --- a/Components/Paging/src/OgrePage.cpp +++ /dev/null @@ -1,431 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgrePage.h" -#include "OgreRoot.h" -#include "OgrePagedWorldSection.h" -#include "OgrePagedWorld.h" -#include "OgrePageStrategy.h" -#include "OgrePageManager.h" -#include "OgreSceneNode.h" -#include "OgreSceneManager.h" -#include "OgreStreamSerialiser.h" -#include "OgrePageContentCollectionFactory.h" -#include "OgrePageContentCollection.h" -#include "OgreLogManager.h" -#include "OgreFileSystemLayer.h" -#include - -namespace Ogre -{ - //--------------------------------------------------------------------- - const uint32 Page::CHUNK_ID = StreamSerialiser::makeIdentifier("PAGE"); - const uint16 Page::CHUNK_VERSION = 1; - const uint32 Page::CHUNK_CONTENTCOLLECTION_DECLARATION_ID = StreamSerialiser::makeIdentifier("PCNT"); - - //--------------------------------------------------------------------- - Page::Page(PageID pageID, PagedWorldSection* parent) - : mID(pageID) - , mParent(parent) - , mDeferredProcessInProgress(false) - , mModified(false) - , mDebugNode(0) - { - touch(); - } - //--------------------------------------------------------------------- - Page::~Page() - { - destroyAllContentCollections(); - if (mDebugNode) - { - // destroy while we have the chance - for (auto mo : mDebugNode->getAttachedObjects()) - mParent->getSceneManager()->destroyMovableObject(mo); - mDebugNode->removeAndDestroyAllChildren(); - mParent->getSceneManager()->destroySceneNode(mDebugNode); - - mDebugNode = 0; - } - } - //--------------------------------------------------------------------- - void Page::destroyAllContentCollections() - { - for (auto & cc : mContentCollections) - { - delete cc; - } - mContentCollections.clear(); - } - //--------------------------------------------------------------------- - PageManager* Page::getManager() const - { - return mParent->getManager(); - } - //--------------------------------------------------------------------- - void Page::touch() - { - mFrameLastHeld = Root::getSingleton().getNextFrameNumber(); - } - //--------------------------------------------------------------------- - bool Page::isHeld() const - { - unsigned long nextFrame = Root::getSingleton().getNextFrameNumber(); - unsigned long dist; - if (nextFrame < mFrameLastHeld) - { - // we must have wrapped around - dist = nextFrame + (std::numeric_limits::max() - mFrameLastHeld); - } - else - dist = nextFrame - mFrameLastHeld; - - // 5-frame tolerance - return dist <= 5; - } - //--------------------------------------------------------------------- - bool Page::prepareImpl(StreamSerialiser& stream, PageData* dataToPopulate) - { - - // Now do the real loading - if (!stream.readChunkBegin(CHUNK_ID, CHUNK_VERSION, "Page")) - return false; - - // pageID check (we should know the ID we're expecting) - uint32 storedID; - stream.read(&storedID); - if (mID != storedID) - { - LogManager::getSingleton().stream(LML_CRITICAL) << "Error: Tried to populate Page ID " << mID - << " with data corresponding to page ID " << storedID; - stream.undoReadChunk(CHUNK_ID); - return false; - } - - PageManager* mgr = getManager(); - - while(stream.peekNextChunkID() == CHUNK_CONTENTCOLLECTION_DECLARATION_ID) - { - const StreamSerialiser::Chunk* collChunk = stream.readChunkBegin(); - String factoryName; - stream.read(&factoryName); - stream.readChunkEnd(CHUNK_CONTENTCOLLECTION_DECLARATION_ID); - // Supported type? - PageContentCollectionFactory* collFact = mgr->getContentCollectionFactory(factoryName); - if (collFact) - { - PageContentCollection* collInst = collFact->createInstance(); - if (collInst->prepare(stream)) // read type-specific data - { - dataToPopulate->collectionsToAdd.push_back(collInst); - } - else - { - LogManager::getSingleton().stream() << "Error preparing PageContentCollection type: " - << factoryName << " in " << *this; - collFact->destroyInstance(collInst); - } - } - else - { - LogManager::getSingleton().stream() << "Unsupported PageContentCollection type: " - << factoryName << " in " << *this; - // skip - stream.readChunkEnd(collChunk->id); - } - - } - - - mModified = false; - - return true; - } - //--------------------------------------------------------------------- - void Page::load(bool synchronous) - { - if (!mDeferredProcessInProgress) - { - destroyAllContentCollections(); - mDeferredProcessInProgress = true; - - if(synchronous) - { - auto res = handleRequest(NULL, NULL); - handleResponse(res, NULL); - delete res; - } - else - { - Root::getSingleton().getWorkQueue()->addTask([this]() { - auto res = handleRequest(NULL, NULL); - Root::getSingleton().getWorkQueue()->addMainThreadTask([this, res]() { - handleResponse(res, NULL); - delete res; - }); - }); - } - - } - - } - //--------------------------------------------------------------------- - void Page::unload() - { - destroyAllContentCollections(); - } - //--------------------------------------------------------------------- - WorkQueue::Response* Page::handleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ) - { - // Background thread (maybe) - PageResponse res; - res.pageData = OGRE_NEW PageData(); - WorkQueue::Response* response = 0; - try - { - prepareImpl(res.pageData); - response = OGRE_NEW WorkQueue::Response(req, true, res); - } - catch (Exception& e) - { - // oops - response = OGRE_NEW WorkQueue::Response(req, false, res, - e.getFullDescription()); - } - - return response; - } - //--------------------------------------------------------------------- - void Page::handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ) - { - // Main thread - PageResponse pres = any_cast(res->getData()); - - // final loading behaviour - if (res->succeeded()) - { - if(!pres.pageData->collectionsToAdd.empty()) - std::swap(mContentCollections, pres.pageData->collectionsToAdd); - - loadImpl(); - } - - OGRE_DELETE pres.pageData; - - mDeferredProcessInProgress = false; - - } - //--------------------------------------------------------------------- - bool Page::prepareImpl(PageData* dataToPopulate) - { - // Procedural preparation - if (mParent->_prepareProceduralPage(this)) - return true; - else - { - // Background loading - String filename = generateFilename(); - - DataStreamPtr stream = Root::getSingleton().openFileStream(filename, - getManager()->getPageResourceGroup()); - StreamSerialiser ser(stream); - return prepareImpl(ser, dataToPopulate); - } - - - } - //--------------------------------------------------------------------- - void Page::loadImpl() - { - mParent->_loadProceduralPage(this); - - for (auto & cc : mContentCollections) - { - cc->load(); - } - } - //--------------------------------------------------------------------- - void Page::save() - { - String filename = generateFilename(); - save(filename); - } - //--------------------------------------------------------------------- - void Page::save(const String& filename) - { - DataStreamPtr stream = Root::getSingleton().createFileStream(filename, - getManager()->getPageResourceGroup(), true); - StreamSerialiser ser(stream); - save(ser); - } - //--------------------------------------------------------------------- - void Page::save(StreamSerialiser& stream) - { - stream.writeChunkBegin(CHUNK_ID, CHUNK_VERSION); - - // page id - stream.write(&mID); - - // content collections - for (auto & cc : mContentCollections) - { - // declaration - stream.writeChunkBegin(CHUNK_CONTENTCOLLECTION_DECLARATION_ID); - stream.write(&cc->getType()); - stream.writeChunkEnd(CHUNK_CONTENTCOLLECTION_DECLARATION_ID); - // data - cc->save(stream); - } - - stream.writeChunkEnd(CHUNK_ID); - - mModified = false; - } - //--------------------------------------------------------------------- - void Page::frameStart(Real timeSinceLastFrame) - { - updateDebugDisplay(); - - // content collections - for (auto & cc : mContentCollections) - { - cc->frameStart(timeSinceLastFrame); - } - - - } - //--------------------------------------------------------------------- - void Page::frameEnd(Real timeElapsed) - { - // content collections - for (auto & cc : mContentCollections) - { - cc->frameEnd(timeElapsed); - } - - } - //--------------------------------------------------------------------- - void Page::notifyCamera(Camera* cam) - { - // content collections - for (auto & cc : mContentCollections) - { - cc->notifyCamera(cam); - } - - } - //--------------------------------------------------------------------- - void Page::updateDebugDisplay() - { - uint8 dbglvl = getManager()->getDebugDisplayLevel(); - if (dbglvl > 0) - { - // update debug display - if (!mDebugNode) - { - mDebugNode = mParent->getSceneManager()->getRootSceneNode()->createChildSceneNode(); - } - mParent->getStrategy()->updateDebugDisplay(this, mDebugNode); - - mDebugNode->setVisible(true); - } - else if (mDebugNode) - { - mDebugNode->setVisible(false); - } - - } - //--------------------------------------------------------------------- - PageContentCollection* Page::createContentCollection(const String& typeName) - { - PageContentCollection* coll = getManager()->createContentCollection(typeName); - coll->_notifyAttached(this); - mContentCollections.push_back(coll); - return coll; - } - //--------------------------------------------------------------------- - void Page::destroyContentCollection(PageContentCollection* coll) - { - ContentCollectionList::iterator i = std::find( - mContentCollections.begin(), mContentCollections.end(), coll); - if (i != mContentCollections.end()) - { - mContentCollections.erase(i); - } - getManager()->destroyContentCollection(coll); - } - //--------------------------------------------------------------------- - size_t Page::getContentCollectionCount() const - { - return mContentCollections.size(); - } - //--------------------------------------------------------------------- - PageContentCollection* Page::getContentCollection(size_t index) - { - assert(index < mContentCollections.size()); - - return mContentCollections[index]; - } - //--------------------------------------------------------------------- - const Page::ContentCollectionList& Page::getContentCollectionList() const - { - return mContentCollections; - } - //--------------------------------------------------------------------- - SceneManager* Page::getSceneManager() const - { - return mParent->getSceneManager(); - } - //--------------------------------------------------------------------- - std::ostream& operator <<( std::ostream& o, const Page& p ) - { - o << "Page(ID:" << p.getID() << ", section:" << p.getParentSection()->getName() - << ", world:" << p.getParentSection()->getWorld()->getName() << ")"; - return o; - } - //--------------------------------------------------------------------- - String Page::generateFilename() const - { - StringStream str; - if (mParent) - str << mParent->getWorld()->getName() << "_" << mParent->getName(); - - str << std::setw(8) << std::setfill('0') << std::hex << mID << ".page"; - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - static FileSystemLayer fs(""); - // For the iOS we need to prefix the file name with the path to the Caches folder - return fs.getWritablePath(str.str()); -#else - return str.str(); -#endif - } - - - -} - diff --git a/Components/Paging/src/OgrePageContent.cpp b/Components/Paging/src/OgrePageContent.cpp deleted file mode 100644 index 1aee21d84c7..00000000000 --- a/Components/Paging/src/OgrePageContent.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgrePageContent.h" -#include "OgrePageContentFactory.h" -#include "OgrePageContentCollection.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - PageContent::PageContent(PageContentFactory* creator) - : mCreator(creator), mParent(0) - { - - } - //--------------------------------------------------------------------- - PageContent::~PageContent() - { - // don't call destroy(), we're not the final subclass - } - //--------------------------------------------------------------------- - PageManager* PageContent::getManager() const - { - return mParent->getManager(); - } - //--------------------------------------------------------------------- - SceneManager* PageContent::getSceneManager() const - { - return mParent->getSceneManager(); - } - //--------------------------------------------------------------------- - const String& PageContent::getType() const - { - return mCreator->getName(); - } - //--------------------------------------------------------------------- - void PageContent::_notifyAttached(PageContentCollection* parent) - { - mParent = parent; - } - -} - diff --git a/Components/Paging/src/OgrePageContentCollection.cpp b/Components/Paging/src/OgrePageContentCollection.cpp deleted file mode 100644 index 95981630f9a..00000000000 --- a/Components/Paging/src/OgrePageContentCollection.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgrePageContentCollection.h" -#include "OgrePageContentCollectionFactory.h" -#include "OgreStreamSerialiser.h" -#include "OgrePage.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - const uint32 PageContentCollection::CHUNK_ID = StreamSerialiser::makeIdentifier("PGCC"); - const uint16 PageContentCollection::CHUNK_VERSION = 1; - //--------------------------------------------------------------------- - PageContentCollection::PageContentCollection(PageContentCollectionFactory* creator) - : mCreator(creator), mParent(0) - { - - } - //--------------------------------------------------------------------- - PageContentCollection::~PageContentCollection() - { - // don't call destroy(), we're not the final subclass - } - //--------------------------------------------------------------------- - PageManager* PageContentCollection::getManager() const - { - return mParent->getManager(); - } - //--------------------------------------------------------------------- - const String& PageContentCollection::getType() const - { - return mCreator->getName(); - } - //--------------------------------------------------------------------- - void PageContentCollection::_notifyAttached(Page* parent) - { - mParent = parent; - } - //--------------------------------------------------------------------- - SceneManager* PageContentCollection::getSceneManager() const - { - return mParent->getSceneManager(); - } - - -} - diff --git a/Components/Paging/src/OgrePageManager.cpp b/Components/Paging/src/OgrePageManager.cpp deleted file mode 100644 index c61b2ce1353..00000000000 --- a/Components/Paging/src/OgrePageManager.cpp +++ /dev/null @@ -1,554 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgrePageManager.h" -#include "OgrePageContentCollectionFactory.h" -#include "OgrePagedWorldSection.h" -#include "OgrePageContentFactory.h" -#include "OgreException.h" -#include "OgrePagedWorldSection.h" -#include "OgrePagedWorld.h" -#include "OgreGrid2DPageStrategy.h" -#include "OgreGrid3DPageStrategy.h" -#include "OgreSimplePageContentCollection.h" -#include "OgreStreamSerialiser.h" -#include "OgreRoot.h" -#include "OgrePageContent.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - PageManager::PageManager() - : mWorldNameGenerator("World") - , mPageProvider(0) - , mPageResourceGroup(ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME) - , mDebugDisplayLvl(0) - , mPagingEnabled(true) - , mGrid2DPageStrategy(0) - , mGrid3DPageStrategy(0) - , mSimpleCollectionFactory(0) - { - - mEventRouter.pManager = this; - mEventRouter.pWorldMap = &mWorlds; - mEventRouter.pCameraList = &mCameraList; - - Root::getSingleton().addFrameListener(&mEventRouter); - - createStandardStrategies(); - createStandardContentFactories(); - - } - //--------------------------------------------------------------------- - PageManager::~PageManager() - { - Root::getSingleton().removeFrameListener(&mEventRouter); - for (auto c : mCameraList) - { - c->removeListener(&mEventRouter); - } - mCameraList.clear(); - - OGRE_DELETE mGrid3DPageStrategy; - OGRE_DELETE mGrid2DPageStrategy; - OGRE_DELETE mSimpleCollectionFactory; - } - //--------------------------------------------------------------------- - void PageManager::createStandardStrategies() - { - mGrid2DPageStrategy = OGRE_NEW Grid2DPageStrategy(this); - addStrategy(mGrid2DPageStrategy); - - mGrid3DPageStrategy = OGRE_NEW Grid3DPageStrategy(this); - addStrategy(mGrid3DPageStrategy); - } - //--------------------------------------------------------------------- - void PageManager::createStandardContentFactories() - { - // collections - mSimpleCollectionFactory = OGRE_NEW SimplePageContentCollectionFactory(); - addContentCollectionFactory(mSimpleCollectionFactory); - - } - //--------------------------------------------------------------------- - PagedWorld* PageManager::createWorld(const String& name) - { - String theName = name; - if (theName.empty()) - { - do - { - theName = mWorldNameGenerator.generate(); - } while (mWorlds.find(theName) != mWorlds.end()); - } - else if(mWorlds.find(theName) != mWorlds.end()) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "World named '" + theName + "' already exists!", - "PageManager::createWorld"); - } - - PagedWorld* ret = OGRE_NEW PagedWorld(theName, this); - mWorlds[theName] = ret; - - return ret; - } - //--------------------------------------------------------------------- - void PageManager::destroyWorld(const String& name) - { - WorldMap::iterator i = mWorlds.find(name); - if (i != mWorlds.end()) - { - OGRE_DELETE i->second; - mWorlds.erase(i); - } - - } - //--------------------------------------------------------------------- - void PageManager::destroyWorld(PagedWorld* world) - { - destroyWorld(world->getName()); - } - //--------------------------------------------------------------------- - PagedWorld* PageManager::loadWorld(const String& filename, const String& name) - { - PagedWorld* ret = createWorld(name); - - StreamSerialiser* ser = _readWorldStream(filename); - ret->load(*ser); - OGRE_DELETE ser; - - return ret; - - - } - //--------------------------------------------------------------------- - PagedWorld* PageManager::loadWorld(const DataStreamPtr& stream, const String& name) - { - PagedWorld* ret = createWorld(name); - - ret->load(stream); - - return ret; - } - //--------------------------------------------------------------------- - void PageManager::saveWorld(PagedWorld* world, const String& filename) - { - world->save(filename); - } - //--------------------------------------------------------------------- - void PageManager::saveWorld(PagedWorld* world, const DataStreamPtr& stream) - { - world->save(stream); - } - //--------------------------------------------------------------------- - PagedWorld* PageManager::getWorld(const String& name) - { - WorldMap::iterator i = mWorlds.find(name); - if (i != mWorlds.end()) - return i->second; - else - return 0; - } - //--------------------------------------------------------------------- - void PageManager::addStrategy(PageStrategy* strategy) - { - // note - deliberately allowing overriding - mStrategies[strategy->getName()] = strategy; - } - //--------------------------------------------------------------------- - void PageManager::removeStrategy(PageStrategy* strategy) - { - StrategyMap::iterator i = mStrategies.find(strategy->getName()); - if (i != mStrategies.end() && i->second == strategy) - { - mStrategies.erase(i); - } - } - //--------------------------------------------------------------------- - PageStrategy* PageManager::getStrategy(const String& name) - { - StrategyMap::iterator i = mStrategies.find(name); - if (i != mStrategies.end()) - return i->second; - else - return 0; - - } - //--------------------------------------------------------------------- - const PageManager::StrategyMap& PageManager::getStrategies() const - { - return mStrategies; - } - //--------------------------------------------------------------------- - void PageManager::addContentCollectionFactory(PageContentCollectionFactory* f) - { - // note - deliberately allowing overriding - mContentCollectionFactories[f->getName()] = f; - } - //--------------------------------------------------------------------- - void PageManager::removeContentCollectionFactory(PageContentCollectionFactory* f) - { - ContentCollectionFactoryMap::iterator i = mContentCollectionFactories.find(f->getName()); - if (i != mContentCollectionFactories.end() && i->second == f) - { - mContentCollectionFactories.erase(i); - } - } - //--------------------------------------------------------------------- - PageContentCollectionFactory* PageManager::getContentCollectionFactory(const String& name) - { - ContentCollectionFactoryMap::iterator i = mContentCollectionFactories.find(name); - if (i != mContentCollectionFactories.end()) - return i->second; - else - return 0; - - } - //--------------------------------------------------------------------- - const PageManager::ContentCollectionFactoryMap& PageManager::getContentCollectionFactories() const - { - return mContentCollectionFactories; - } - //--------------------------------------------------------------------- - PageContentCollection* PageManager::createContentCollection(const String& typeName) - { - PageContentCollectionFactory* fact = getContentCollectionFactory(typeName); - if (!fact) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - typeName + " is not the name of a valid PageContentCollectionFactory", - "PageManager::createContentCollection"); - - return fact->createInstance(); - } - //--------------------------------------------------------------------- - void PageManager::destroyContentCollection(PageContentCollection* coll) - { - PageContentCollectionFactory* fact = getContentCollectionFactory(coll->getType()); - if (fact) - fact->destroyInstance(coll); - else - OGRE_DELETE coll; // normally a safe fallback - } - //--------------------------------------------------------------------- - void PageManager::addContentFactory(PageContentFactory* f) - { - // note - deliberately allowing overriding - mContentFactories[f->getName()] = f; - } - //--------------------------------------------------------------------- - void PageManager::removeContentFactory(PageContentFactory* f) - { - ContentFactoryMap::iterator i = mContentFactories.find(f->getName()); - if (i != mContentFactories.end() && i->second == f) - { - mContentFactories.erase(i); - } - } - //--------------------------------------------------------------------- - PageContentFactory* PageManager::getContentFactory(const String& name) - { - ContentFactoryMap::iterator i = mContentFactories.find(name); - if (i != mContentFactories.end()) - return i->second; - else - return 0; - - } - //--------------------------------------------------------------------- - const PageManager::ContentFactoryMap& PageManager::getContentFactories() const - { - return mContentFactories; - } - //--------------------------------------------------------------------- - PageContent* PageManager::createContent(const String& typeName) - { - PageContentFactory* fact = getContentFactory(typeName); - if (!fact) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - typeName + " is not the name of a valid PageContentFactory", - "PageManager::createContent"); - - return fact->createInstance(); - } - //--------------------------------------------------------------------- - void PageManager::destroyContent(PageContent* c) - { - PageContentFactory* fact = getContentFactory(c->getType()); - if (fact) - fact->destroyInstance(c); - else - OGRE_DELETE c; // normally a safe fallback - } - //--------------------------------------------------------------------- - void PageManager::addWorldSectionFactory(PagedWorldSectionFactory* f) - { - // note - deliberately allowing overriding - mWorldSectionFactories[f->getName()] = f; - } - //--------------------------------------------------------------------- - void PageManager::removeWorldSectionFactory(PagedWorldSectionFactory* f) - { - WorldSectionFactoryMap::iterator i = mWorldSectionFactories.find(f->getName()); - if (i != mWorldSectionFactories.end() && i->second == f) - { - mWorldSectionFactories.erase(i); - } - } - //--------------------------------------------------------------------- - PagedWorldSectionFactory* PageManager::getWorldSectionFactory(const String& name) - { - WorldSectionFactoryMap::iterator i = mWorldSectionFactories.find(name); - if (i != mWorldSectionFactories.end()) - return i->second; - else - return 0; - - } - //--------------------------------------------------------------------- - const PageManager::WorldSectionFactoryMap& PageManager::getWorldSectionFactories() const - { - return mWorldSectionFactories; - } - //--------------------------------------------------------------------- - PagedWorldSection* PageManager::createWorldSection(const String& typeName, - const String& name, PagedWorld* parent, SceneManager* sm) - { - PagedWorldSectionFactory* fact = getWorldSectionFactory(typeName); - if (!fact) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - typeName + " is not the name of a valid PagedWorldSectionFactory", - "PageManager::createWorldSection"); - - return fact->createInstance(name, parent, sm); - } - //--------------------------------------------------------------------- - void PageManager::destroyWorldSection(PagedWorldSection* coll) - { - PagedWorldSectionFactory* fact = getWorldSectionFactory(coll->getType()); - if (fact) - fact->destroyInstance(coll); - else - OGRE_DELETE coll; // normally a safe fallback - } - //--------------------------------------------------------------------- - StreamSerialiser* PageManager::_readPageStream(PageID pageID, PagedWorldSection* section) - { - StreamSerialiser* ser = 0; - if (mPageProvider) - ser = mPageProvider->readPageStream(pageID, section); - if (!ser) - { - // use default implementation - StringStream nameStr; - nameStr << section->getWorld()->getName() << "_" << section->getName() - << "_" << pageID << ".page"; - DataStreamPtr stream = ResourceGroupManager::getSingleton().openResource(nameStr.str()); - - ser = OGRE_NEW StreamSerialiser(stream); - - } - - return ser; - - } - //--------------------------------------------------------------------- - StreamSerialiser* PageManager::_writePageStream(PageID pageID, PagedWorldSection* section) - { - StreamSerialiser* ser = 0; - if (mPageProvider) - ser = mPageProvider->writePageStream(pageID, section); - if (!ser) - { - // use default implementation - StringStream nameStr; - nameStr << section->getWorld()->getName() << "_" << section->getName() - << "_" << pageID << ".page"; - - // create file, overwrite if necessary - DataStreamPtr stream = ResourceGroupManager::getSingleton().createResource( - nameStr.str(), mPageResourceGroup, true); - - ser = OGRE_NEW StreamSerialiser(stream); - - } - - return ser; - - } - //--------------------------------------------------------------------- - StreamSerialiser* PageManager::_readWorldStream(const String& filename) - { - StreamSerialiser* ser = 0; - if (mPageProvider) - ser = mPageProvider->readWorldStream(filename); - if (!ser) - { - // use default implementation - DataStreamPtr stream = ResourceGroupManager::getSingleton().openResource( - filename); - - ser = OGRE_NEW StreamSerialiser(stream); - - } - - return ser; - - } - //--------------------------------------------------------------------- - StreamSerialiser* PageManager::_writeWorldStream(const String& filename) - { - StreamSerialiser* ser = 0; - if (mPageProvider) - ser = mPageProvider->writeWorldStream(filename); - if (!ser) - { - // use default implementation - // create file, overwrite if necessary - DataStreamPtr stream = ResourceGroupManager::getSingleton().createResource( - filename, mPageResourceGroup, true); - - ser = OGRE_NEW StreamSerialiser(stream); - - } - - return ser; - - } - //--------------------------------------------------------------------- - bool PageManager::_prepareProceduralPage(Page* page, PagedWorldSection* section) - { - bool generated = false; - if (mPageProvider) - generated = mPageProvider->prepareProceduralPage(page, section); - - return generated; - } - //--------------------------------------------------------------------- - bool PageManager::_loadProceduralPage(Page* page, PagedWorldSection* section) - { - bool generated = false; - if (mPageProvider) - generated = mPageProvider->loadProceduralPage(page, section); - - return generated; - } - //--------------------------------------------------------------------- - bool PageManager::_unprepareProceduralPage(Page* page, PagedWorldSection* section) - { - bool generated = false; - if (mPageProvider) - generated = mPageProvider->unprepareProceduralPage(page, section); - - return generated; - } - //--------------------------------------------------------------------- - bool PageManager::_unloadProceduralPage(Page* page, PagedWorldSection* section) - { - bool generated = false; - if (mPageProvider) - generated = mPageProvider->unloadProceduralPage(page, section); - - return generated; - } - //--------------------------------------------------------------------- - void PageManager::addCamera(Camera* c) - { - if (std::find(mCameraList.begin(), mCameraList.end(), c) == mCameraList.end()) - { - mCameraList.push_back(c); - c->addListener(&mEventRouter); - } - } - //--------------------------------------------------------------------- - void PageManager::removeCamera(Camera* c) - { - CameraList::iterator i = std::find(mCameraList.begin(), mCameraList.end(), c); - if (i != mCameraList.end()) - { - c->removeListener(&mEventRouter); - mCameraList.erase(i); - } - } - //--------------------------------------------------------------------- - bool PageManager::hasCamera(Camera* c) const - { - return std::find(mCameraList.begin(), mCameraList.end(), c) != mCameraList.end(); - } - //--------------------------------------------------------------------- - const PageManager::CameraList& PageManager::getCameraList() const - { - return mCameraList; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - void PageManager::EventRouter::cameraPreRenderScene(Camera* cam) - { - } - //--------------------------------------------------------------------- - void PageManager::EventRouter::cameraDestroyed(Camera* cam) - { - pManager->removeCamera(cam); - } - //--------------------------------------------------------------------- - bool PageManager::EventRouter::frameStarted(const FrameEvent& evt) - { - if(pWorldMap->empty()) - return true; - - for(auto & i : *pWorldMap) - { - i.second->frameStart(evt.timeSinceLastFrame); - // Notify of all active cameras - // Previously we did this in cameraPreRenderScene, but that had the effect - // of causing unnecessary unloading of pages if a camera was rendered - // intermittently, so we assume that all cameras we're told to watch are 'active' - for (auto & c : *pCameraList) - { - i.second->notifyCamera(c); - } - } - - return true; - } - //--------------------------------------------------------------------- - bool PageManager::EventRouter::frameEnded(const FrameEvent& evt) - { - if(pWorldMap->empty()) - return true; - - for(auto & i : *pWorldMap) - i.second->frameEnd(evt.timeSinceLastFrame); - - return true; - } - - - - -} - diff --git a/Components/Paging/src/OgrePagedWorld.cpp b/Components/Paging/src/OgrePagedWorld.cpp deleted file mode 100644 index c5ab8438f19..00000000000 --- a/Components/Paging/src/OgrePagedWorld.cpp +++ /dev/null @@ -1,321 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgrePagedWorld.h" -#include "OgrePageManager.h" -#include "OgrePagedWorldSection.h" -#include "OgreStreamSerialiser.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - const uint32 PagedWorld::CHUNK_ID = StreamSerialiser::makeIdentifier("PWLD"); - const uint32 PagedWorld::CHUNK_SECTIONDECLARATION_ID = StreamSerialiser::makeIdentifier("PWLS"); - const uint16 PagedWorld::CHUNK_VERSION = 1; - //--------------------------------------------------------------------- - PagedWorld::PagedWorld(const String& name, PageManager* manager) - :mName(name), mManager(manager), mPageProvider(0), mSectionNameGenerator("Section") - { - - } - //--------------------------------------------------------------------- - PagedWorld::~PagedWorld() - { - destroyAllSections(); - } - //--------------------------------------------------------------------- - void PagedWorld::load(const String& filename) - { - StreamSerialiser* ser = mManager->_readWorldStream(filename); - load(*ser); - OGRE_DELETE ser; - } - //--------------------------------------------------------------------- - void PagedWorld::load(const DataStreamPtr& stream) - { - StreamSerialiser ser(stream); - load(ser); - } - //--------------------------------------------------------------------- - bool PagedWorld::load(StreamSerialiser& ser) - { - if (!ser.readChunkBegin(CHUNK_ID, CHUNK_VERSION, "PagedWorld")) - return false; - - // Name - ser.read(&mName); - // Sections - while(ser.peekNextChunkID() == CHUNK_SECTIONDECLARATION_ID) - { - ser.readChunkBegin(); - String sectionType, sectionName; - ser.read(§ionType); - ser.read(§ionName); - ser.readChunkEnd(CHUNK_SECTIONDECLARATION_ID); - // Scene manager will be loaded - PagedWorldSection* sec = createSection(0, sectionType, sectionName); - bool sectionsOk = sec->load(ser); - if (!sectionsOk) - destroySection(sec); - } - - ser.readChunkEnd(CHUNK_ID); - - return true; - - } - //--------------------------------------------------------------------- - void PagedWorld::save(const String& filename) - { - StreamSerialiser* ser = mManager->_writeWorldStream(filename); - save(*ser); - OGRE_DELETE ser; - } - //--------------------------------------------------------------------- - void PagedWorld::save(const DataStreamPtr& stream) - { - StreamSerialiser ser(stream); - save(ser); - } - //--------------------------------------------------------------------- - void PagedWorld::save(StreamSerialiser& ser) - { - ser.writeChunkBegin(CHUNK_ID, CHUNK_VERSION); - - // Name - ser.write(&mName); - // Sections - for (auto & s : mSections) - { - PagedWorldSection* sec = s.second; - // declaration - ser.writeChunkBegin(CHUNK_SECTIONDECLARATION_ID); - ser.write(&sec->getType()); - ser.write(&sec->getName()); - ser.writeChunkEnd(CHUNK_SECTIONDECLARATION_ID); - // data - s.second->save(ser); - } - - ser.writeChunkEnd(CHUNK_ID); - } - //--------------------------------------------------------------------- - PagedWorldSection* PagedWorld::createSection(SceneManager* sceneMgr, - const String& typeName, - const String& sectionName /*= BLANKSTRING*/) - { - String theName = sectionName; - if (theName.empty()) - { - do - { - theName = mSectionNameGenerator.generate(); - } while (mSections.find(theName) != mSections.end()); - } - else if(mSections.find(theName) != mSections.end()) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "World section named '" + theName + "' already exists!", - "PagedWorld::createSection"); - } - - PagedWorldSection* ret = 0; - if (typeName == "General") - ret = OGRE_NEW PagedWorldSection(theName, this, sceneMgr); - else - { - PagedWorldSectionFactory* fact = getManager()->getWorldSectionFactory(typeName); - if (!fact) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "World section type '" + typeName + "' does not exist!", - "PagedWorld::createSection"); - } - - ret = fact->createInstance(theName, this, sceneMgr); - - } - mSections[theName] = ret; - - return ret; - - - } - //--------------------------------------------------------------------- - PagedWorldSection* PagedWorld::createSection(const String& strategyName, SceneManager* sceneMgr, - const String& sectionName) - { - // get the strategy - PageStrategy* strategy = mManager->getStrategy(strategyName); - - return createSection(strategy, sceneMgr, sectionName); - - } - //--------------------------------------------------------------------- - PagedWorldSection* PagedWorld::createSection(PageStrategy* strategy, SceneManager* sceneMgr, - const String& sectionName) - { - PagedWorldSection* ret = createSection(sceneMgr, "General", sectionName); - ret->setStrategy(strategy); - - return ret; - } - - //--------------------------------------------------------------------- - void PagedWorld::destroySection(const String& name) - { - SectionMap::iterator i = mSections.find(name); - if (i != mSections.end()) - { - OGRE_DELETE i->second; - mSections.erase(i); - } - } - //--------------------------------------------------------------------- - void PagedWorld::destroySection(PagedWorldSection* sec) - { - destroySection(sec->getName()); - } - //--------------------------------------------------------------------- - void PagedWorld::destroyAllSections() - { - for (auto & s : mSections) - OGRE_DELETE s.second; - mSections.clear(); - } - //--------------------------------------------------------------------- - PagedWorldSection* PagedWorld::getSection(const String& name) - { - SectionMap::iterator i = mSections.find(name); - if (i != mSections.end()) - return i->second; - else - return 0; - - } - //--------------------------------------------------------------------- - bool PagedWorld::_prepareProceduralPage(Page* page, PagedWorldSection* section) - { - bool generated = false; - if (mPageProvider) - generated = mPageProvider->prepareProceduralPage(page, section); - if (!generated) - generated = mManager->_prepareProceduralPage(page, section); - return generated; - - } - //--------------------------------------------------------------------- - bool PagedWorld::_loadProceduralPage(Page* page, PagedWorldSection* section) - { - bool generated = false; - if (mPageProvider) - generated = mPageProvider->loadProceduralPage(page, section); - if (!generated) - generated = mManager->_loadProceduralPage(page, section); - return generated; - - } - //--------------------------------------------------------------------- - bool PagedWorld::_unprepareProceduralPage(Page* page, PagedWorldSection* section) - { - bool generated = false; - if (mPageProvider) - generated = mPageProvider->unprepareProceduralPage(page, section); - if (!generated) - generated = mManager->_unprepareProceduralPage(page, section); - return generated; - - } - //--------------------------------------------------------------------- - bool PagedWorld::_unloadProceduralPage(Page* page, PagedWorldSection* section) - { - bool generated = false; - if (mPageProvider) - generated = mPageProvider->unloadProceduralPage(page, section); - if (!generated) - generated = mManager->_unloadProceduralPage(page, section); - return generated; - - } - //--------------------------------------------------------------------- - StreamSerialiser* PagedWorld::_readPageStream(PageID pageID, PagedWorldSection* section) - { - StreamSerialiser* ser = 0; - if (mPageProvider) - ser = mPageProvider->readPageStream(pageID, section); - if (!ser) - ser = mManager->_readPageStream(pageID, section); - return ser; - - } - //--------------------------------------------------------------------- - StreamSerialiser* PagedWorld::_writePageStream(PageID pageID, PagedWorldSection* section) - { - StreamSerialiser* ser = 0; - if (mPageProvider) - ser = mPageProvider->writePageStream(pageID, section); - if (!ser) - ser = mManager->_writePageStream(pageID, section); - return ser; - - } - //--------------------------------------------------------------------- - void PagedWorld::frameStart(Real t) - { - for (auto & s : mSections) - { - s.second->frameStart(t); - } - } - //--------------------------------------------------------------------- - void PagedWorld::frameEnd(Real t) - { - for (auto & s : mSections) - { - s.second->frameEnd(t); - } - } - //--------------------------------------------------------------------- - void PagedWorld::notifyCamera(Camera* cam) - { - for (auto & s : mSections) - { - s.second->notifyCamera(cam); - } - } - //--------------------------------------------------------------------- - std::ostream& operator <<( std::ostream& o, const PagedWorld& p ) - { - o << "PagedWorld(" << p.getName() << ")"; - return o; - } - - - - -} - diff --git a/Components/Paging/src/OgrePagedWorldSection.cpp b/Components/Paging/src/OgrePagedWorldSection.cpp deleted file mode 100644 index a9706a4dae7..00000000000 --- a/Components/Paging/src/OgrePagedWorldSection.cpp +++ /dev/null @@ -1,395 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgrePagedWorldSection.h" -#include "OgrePageStrategy.h" -#include "OgreStreamSerialiser.h" -#include "OgrePagedWorld.h" -#include "OgrePageManager.h" -#include "OgrePage.h" -#include "OgreLogManager.h" -#include "OgreRoot.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - const uint32 PagedWorldSection::CHUNK_ID = StreamSerialiser::makeIdentifier("PWSC"); - const uint16 PagedWorldSection::CHUNK_VERSION = 1; - //--------------------------------------------------------------------- - PagedWorldSection::PagedWorldSection(const String& name, PagedWorld* parent, SceneManager* sm) - : mName(name), mParent(parent), mStrategy(0), mStrategyData(0), mPageProvider(0), mSceneMgr(sm) - { - } - //--------------------------------------------------------------------- - PagedWorldSection::~PagedWorldSection() - { - if (mStrategy) - { - mStrategy->destroyData(mStrategyData); - mStrategyData = 0; - } - - removeAllPages(); - } - //--------------------------------------------------------------------- - PageManager* PagedWorldSection::getManager() const - { - return mParent->getManager(); - } - //--------------------------------------------------------------------- - void PagedWorldSection::setBoundingBox(const AxisAlignedBox& box) - { - mAABB = box; - } - //--------------------------------------------------------------------- - const AxisAlignedBox& PagedWorldSection::getBoundingBox() const - { - return mAABB; - } - //--------------------------------------------------------------------- - void PagedWorldSection::setStrategy(PageStrategy* strat) - { - if (strat != mStrategy) - { - if (mStrategy) - { - mStrategy->destroyData(mStrategyData); - mStrategy = 0; - mStrategyData = 0; - } - - mStrategy = strat; - if (mStrategy) - mStrategyData = mStrategy->createData(); - - removeAllPages(); - } - - } - //--------------------------------------------------------------------- - void PagedWorldSection::setStrategy(const String& stratName) - { - setStrategy(getManager()->getStrategy(stratName)); - } - //--------------------------------------------------------------------- - void PagedWorldSection::setSceneManager(SceneManager* sm) - { - if (sm != mSceneMgr) - { - mSceneMgr = sm; - removeAllPages(); - } - - - } - //--------------------------------------------------------------------- - void PagedWorldSection::setSceneManager(const String& smName) - { - setSceneManager(Root::getSingleton().getSceneManager(smName)); - } - //--------------------------------------------------------------------- - bool PagedWorldSection::load(StreamSerialiser& ser) - { - if (!ser.readChunkBegin(CHUNK_ID, CHUNK_VERSION, "PagedWorldSection")) - return false; - - // Name - ser.read(&mName); - // AABB - ser.read(&mAABB); - // SceneManager type - String smType, smInstanceName; - SceneManager* sm = 0; - ser.read(&smType); - ser.read(&smInstanceName); - Root& root = Root::getSingleton(); - if (root.hasSceneManager(smInstanceName)) - sm = root.getSceneManager(smInstanceName); - else - sm = root.createSceneManager(smType, smInstanceName); - setSceneManager(sm); - // Page Strategy Name - String stratname; - ser.read(&stratname); - setStrategy(stratname); - // Page Strategy Data - bool strategyDataOk = mStrategyData->load(ser); - if (!strategyDataOk) - LogManager::getSingleton().stream(LML_CRITICAL) << "Error: PageStrategyData for section '" - << mName << "' was not loaded correctly, check file contents"; - - /// Load any data specific to a subtype of this class - loadSubtypeData(ser); - - ser.readChunkEnd(CHUNK_ID); - - return true; - - } - //--------------------------------------------------------------------- - void PagedWorldSection::save(StreamSerialiser& ser) - { - ser.writeChunkBegin(CHUNK_ID, CHUNK_VERSION); - - // Name - ser.write(&mName); - // AABB - ser.write(&mAABB); - // SceneManager type & name - ser.write(&mSceneMgr->getTypeName()); - ser.write(&mSceneMgr->getName()); - // Page Strategy Name - ser.write(&mStrategy->getName()); - // Page Strategy Data - mStrategyData->save(ser); - - /// Save any data specific to a subtype of this class - saveSubtypeData(ser); - - ser.writeChunkEnd(CHUNK_ID); - - // save all pages (in separate files) - for (auto & p : mPages) - { - p.second->save(); - } - - - } - //--------------------------------------------------------------------- - PageID PagedWorldSection::getPageID(const Vector3& worldPos) - { - return mStrategy->getPageID(worldPos, this); - } - //--------------------------------------------------------------------- - Page* PagedWorldSection::loadOrCreatePage(const Vector3& worldPos) - { - PageID id = getPageID(worldPos); - // this will create a Page instance no matter what, even if load fails - // we force the load attempt to happen immediately (forceSynchronous) - loadPage(id, true); - return getPage(id); - } - //--------------------------------------------------------------------- - void PagedWorldSection::loadPage(PageID pageID, bool sync) - { - if (!mParent->getManager()->getPagingOperationsEnabled()) - return; - - PageMap::iterator i = mPages.find(pageID); - if (i == mPages.end()) - { - Page* page = OGRE_NEW Page(pageID, this); - // try to insert - std::pair ret = mPages.emplace(page->getID(), page); - - if (!ret.second) - { - // page with this ID already in map - if (ret.first->second != page) - { - // replacing a page, delete the old one - OGRE_DELETE ret.first->second; - ret.first->second = page; - } - } - page->load(sync); - } - else - i->second->touch(); - } - //--------------------------------------------------------------------- - void PagedWorldSection::unloadPage(PageID pageID, bool sync) - { - if (!mParent->getManager()->getPagingOperationsEnabled()) - return; - - PageMap::iterator i = mPages.find(pageID); - if (i != mPages.end()) - { - Page* page = i->second; - mPages.erase(i); - - page->unload(); - - OGRE_DELETE page; - - } - } - //--------------------------------------------------------------------- - void PagedWorldSection::unloadPage(Page* p, bool sync) - { - unloadPage(p->getID(), sync); - } - //--------------------------------------------------------------------- - bool PagedWorldSection::_prepareProceduralPage(Page* page) - { - bool generated = false; - if (mPageProvider) - generated = mPageProvider->prepareProceduralPage(page, this); - if (!generated) - generated = mParent->_prepareProceduralPage(page, this); - return generated; - - } - //--------------------------------------------------------------------- - bool PagedWorldSection::_loadProceduralPage(Page* page) - { - bool generated = false; - if (mPageProvider) - generated = mPageProvider->loadProceduralPage(page, this); - if (!generated) - generated = mParent->_loadProceduralPage(page, this); - return generated; - - } - //--------------------------------------------------------------------- - bool PagedWorldSection::_unloadProceduralPage(Page* page) - { - bool generated = false; - if (mPageProvider) - generated = mPageProvider->unloadProceduralPage(page, this); - if (!generated) - generated = mParent->_unloadProceduralPage(page, this); - return generated; - - } - //--------------------------------------------------------------------- - bool PagedWorldSection::_unprepareProceduralPage(Page* page) - { - bool generated = false; - if (mPageProvider) - generated = mPageProvider->unprepareProceduralPage(page, this); - if (!generated) - generated = mParent->_unprepareProceduralPage(page, this); - return generated; - - } - //--------------------------------------------------------------------- - void PagedWorldSection::holdPage(PageID pageID) - { - PageMap::iterator i = mPages.find(pageID); - if (i != mPages.end()) - i->second->touch(); - } - //--------------------------------------------------------------------- - Page* PagedWorldSection::getPage(PageID pageID) - { - PageMap::iterator i = mPages.find(pageID); - if (i != mPages.end()) - return i->second; - else - return 0; - } - //--------------------------------------------------------------------- - void PagedWorldSection::removeAllPages() - { - if (!mParent->getManager()->getPagingOperationsEnabled()) - return; - - for (auto & p : mPages) - { - OGRE_DELETE p.second; - } - mPages.clear(); - - } - //--------------------------------------------------------------------- - void PagedWorldSection::frameStart(Real timeSinceLastFrame) - { - mStrategy->frameStart(timeSinceLastFrame, this); - - for (auto & p : mPages) - p.second->frameStart(timeSinceLastFrame); - } - //--------------------------------------------------------------------- - void PagedWorldSection::frameEnd(Real timeElapsed) - { - mStrategy->frameEnd(timeElapsed, this); - - for (PageMap::iterator i = mPages.begin(); i != mPages.end(); ) - { - // if this page wasn't used, unload - Page* p = i->second; - // pre-increment since unloading will remove it - ++i; - if (!p->isHeld()) - unloadPage(p); - else - p->frameEnd(timeElapsed); - } - - } - //--------------------------------------------------------------------- - void PagedWorldSection::notifyCamera(Camera* cam) - { - mStrategy->notifyCamera(cam, this); - - for (auto & p : mPages) - p.second->notifyCamera(cam); - } - //--------------------------------------------------------------------- - StreamSerialiser* PagedWorldSection::_readPageStream(PageID pageID) - { - StreamSerialiser* ser = 0; - if (mPageProvider) - ser = mPageProvider->readPageStream(pageID, this); - if (!ser) - ser = mParent->_readPageStream(pageID, this); - return ser; - - } - //--------------------------------------------------------------------- - StreamSerialiser* PagedWorldSection::_writePageStream(PageID pageID) - { - StreamSerialiser* ser = 0; - if (mPageProvider) - ser = mPageProvider->writePageStream(pageID, this); - if (!ser) - ser = mParent->_writePageStream(pageID, this); - return ser; - - } - //--------------------------------------------------------------------- - const String& PagedWorldSection::getType() - { - static const String stype("General"); - return stype; - } - //--------------------------------------------------------------------- - std::ostream& operator <<( std::ostream& o, const PagedWorldSection& p ) - { - o << "PagedWorldSection(" << p.getName() << ", world:" << p.getWorld()->getName() << ")"; - return o; - } - - - - - -} - diff --git a/Components/Paging/src/OgreSimplePageContentCollection.cpp b/Components/Paging/src/OgreSimplePageContentCollection.cpp deleted file mode 100644 index b54da7867b4..00000000000 --- a/Components/Paging/src/OgreSimplePageContentCollection.cpp +++ /dev/null @@ -1,139 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreSimplePageContentCollection.h" -#include "OgrePageContent.h" -#include "OgreStreamSerialiser.h" -#include "OgrePageManager.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - const uint32 SimplePageContentCollection::SUBCLASS_CHUNK_ID = StreamSerialiser::makeIdentifier("SPCD"); - const uint16 SimplePageContentCollection::SUBCLASS_CHUNK_VERSION = 1; - //--------------------------------------------------------------------- - SimplePageContentCollection::SimplePageContentCollection(PageContentCollectionFactory* creator) - : PageContentCollection(creator) - { - - } - //--------------------------------------------------------------------- - SimplePageContentCollection::~SimplePageContentCollection() - { - for (auto & i : mContentList) - delete i; - mContentList.clear(); - } - //--------------------------------------------------------------------- - PageContent* SimplePageContentCollection::createContent(const String& typeName) - { - PageContent* c = getManager()->createContent(typeName); - mContentList.push_back(c); - return c; - } - //--------------------------------------------------------------------- - void SimplePageContentCollection::destroyContent(PageContent* c) - { - ContentList::iterator i = std::find(mContentList.begin(), mContentList.end(), c); - if (i != mContentList.end()) - mContentList.erase(i); - getManager()->destroyContent(c); - } - //--------------------------------------------------------------------- - void SimplePageContentCollection::save(StreamSerialiser& stream) - { - stream.writeChunkBegin(SUBCLASS_CHUNK_ID, SUBCLASS_CHUNK_VERSION); - - for (auto & i : mContentList) - i->save(stream); - - stream.writeChunkEnd(SUBCLASS_CHUNK_ID); - } - //--------------------------------------------------------------------- - void SimplePageContentCollection::frameStart(Real timeSinceLastFrame) - { - for (auto & i : mContentList) - i->frameStart(timeSinceLastFrame); - - } - //--------------------------------------------------------------------- - void SimplePageContentCollection::frameEnd(Real timeElapsed) - { - for (auto & i : mContentList) - i->frameEnd(timeElapsed); - } - //--------------------------------------------------------------------- - void SimplePageContentCollection::notifyCamera(Camera* cam) - { - for (auto & i : mContentList) - i->notifyCamera(cam); - } - //--------------------------------------------------------------------- - bool SimplePageContentCollection::prepare(StreamSerialiser& stream) - { - if (!stream.readChunkBegin(SUBCLASS_CHUNK_ID, SUBCLASS_CHUNK_VERSION, "SimplePageContentCollection")) - return false; - - bool ret = true; - for (auto & i : mContentList) - ret = i->prepare(stream) && ret; - - - stream.readChunkEnd(SUBCLASS_CHUNK_ID); - - return ret; - - } - //--------------------------------------------------------------------- - void SimplePageContentCollection::load() - { - for (auto & i : mContentList) - i->load(); - - } - //--------------------------------------------------------------------- - void SimplePageContentCollection::unload() - { - for (auto & i : mContentList) - i->unload(); - - } - //--------------------------------------------------------------------- - void SimplePageContentCollection::unprepare() - { - for (auto & i : mContentList) - i->unprepare(); - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - String SimplePageContentCollectionFactory::FACTORY_NAME = "Simple"; - //--------------------------------------------------------------------- - - - -} - diff --git a/Components/Property/CMakeLists.txt b/Components/Property/CMakeLists.txt deleted file mode 100644 index a9de487369d..00000000000 --- a/Components/Property/CMakeLists.txt +++ /dev/null @@ -1,50 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -############################################################ -# Paging optional component -############################################################ - -# define header and source files for the library -set (HEADER_FILES - include/OgreProperty.h - ${PROJECT_BINARY_DIR}/include/OgrePropertyPrerequisites.h -) - -set (SOURCE_FILES - src/OgreProperty.cpp -) - -if(Boost_FOUND) - include_directories(${Boost_INCLUDE_DIRS}) - # workaround Wundef with boost - if(UNIX) - set_source_files_properties("${CMAKE_CURRENT_SOURCE_DIR}/src/OgreProperty.cpp" PROPERTIES COMPILE_FLAGS "-Wno-undef") - endif() -endif() - -# setup target -add_library(OgreProperty ${OGRE_COMP_LIB_TYPE} ${HEADER_FILES} ${SOURCE_FILES} ${PLATFORM_HEADER_FILES} ${PLATFORM_SOURCE_FILES}) -set_target_properties(OgreProperty PROPERTIES VERSION ${OGRE_SOVERSION} SOVERSION ${OGRE_SOVERSION}) -target_link_libraries(OgreProperty PUBLIC OgreMain) -target_include_directories(OgreProperty PUBLIC - "$" - $) - -generate_export_header(OgreProperty - EXPORT_MACRO_NAME _OgrePropertyExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgrePropertyPrerequisites.h) - -# install -ogre_config_framework(OgreProperty) -ogre_config_component(OgreProperty) - -install(FILES ${HEADER_FILES} - DESTINATION include/OGRE/Property -) diff --git a/Components/Property/include/OgreProperty.h b/Components/Property/include/OgreProperty.h deleted file mode 100644 index e68f79335cb..00000000000 --- a/Components/Property/include/OgreProperty.h +++ /dev/null @@ -1,384 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OGRE_PROPERTY_H__ -#define __OGRE_PROPERTY_H__ - -#include "OgrePropertyPrerequisites.h" -#include "OgreAny.h" -#include "OgreString.h" -#include "OgreException.h" -#include "OgreQuaternion.h" -#include "OgreMatrix4.h" - -#include -#include - -/** \addtogroup Optional -* @{ -*/ -/** \defgroup Property Property -* Associate values of arbitrary type with names - - OGRE's property system allows you to associate values of arbitrary type with - names, and have those values exposed via a self-describing interface. Unlike - Ogre::StringInterface, the values are passed as their native types without - needing conversion to or from strings; they are simply wrapped in an Ogre::Any - and casts are performed to access them. - - Property values are actually not stored in this system; instead the property - definitions reference getter & setter methods which provide the 'backing' for - the property. This means you can directly expose features of your classes as properties - without any duplication. - - There are two aspects to exposing a property on your class. One is exposing - the definition of the property (PropertyDef), which should be shared between - all instances and probably stored in a static PropertyDefMap somewhere. The second - is the instance 'wiring' which ensures that a call to set a property calls - a method on this particular instance of the class; this is formed by a number of - Property instances, contained in a PropertySet. Each Property has an explicit - binding to getter and setter instance methods. - - So, here's an example of setting up properties on an instance: - - @code - // Make sure the property definition is created - // propertyDefs is a variable of type PropertyDefMap, shared between instances - PropertyDefMap::iterator defi = propertyDefs.find("name"); - if (defi == propertyDefs.end()) - { - defi = propertyDefs.emplace("name", - PropertyDef("name", - "The name of the object.", PROP_STRING)).first; - } - // This has established the property definition, and its description. - // Now, we need to 'wire' a property instance for this object instance - // We assume the class is called 'Foo' and the instance is pointed to by a variable called 'inst' - // 'props' is a PropertySet, specific to the instance - props.addProperty( - OGRE_NEW Property(&(defi->second), - std::bind(&Foo::getName, inst), - std::bind(&Foo::setName, inst, _1))); - - @endcode - -*/ - -/** @} */ -namespace Ogre -{ - using std::function; - - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Property - * @{ - */ - - /// The type of a property - enum PropertyType - { - PROP_SHORT = 0, - PROP_UNSIGNED_SHORT = 1, - PROP_INT = 2, - PROP_UNSIGNED_INT = 3, - PROP_LONG = 4, - PROP_UNSIGNED_LONG = 5, - PROP_REAL = 6, - PROP_STRING = 7, - PROP_VECTOR2 = 8, - PROP_VECTOR3 = 9, - PROP_VECTOR4 = 10, - PROP_COLOUR = 11, - PROP_BOOL = 12, - PROP_QUATERNION = 13, - PROP_MATRIX3 = 14, - PROP_MATRIX4 = 15, - - PROP_UNKNOWN = 999 - }; - - typedef GeneralAllocatedObject PropertyAlloc; - - /** Definition of a property of an object. - - This definition is shared between all instances of an object and therefore - has no value. Property contains values. - */ - class _OgrePropertyExport PropertyDef : public PropertyAlloc - { - public: - - /** Construct a property. - @param name The name of the property - @param desc A (potentially) long description of the property - @param pType The type of the property - */ - PropertyDef(const String& name, const String& desc, PropertyType pType) - : mName(name), mDesc(desc), mType(pType) {} - - /// Get the name of the property - const String& getName() const { return mName; } - - /// Get the description of the property - const String& getDescription() const { return mDesc; } - - /// Get the type of the property - PropertyType getType() const { return mType; } - - /// Get a string name of a property type - static const String& getTypeName(PropertyType theType); - - static PropertyType getTypeForValue(const short& val) { return PROP_SHORT; } - static PropertyType getTypeForValue(const unsigned short& val) { return PROP_UNSIGNED_SHORT; } - static PropertyType getTypeForValue(const int& val) { return PROP_INT; } - static PropertyType getTypeForValue(const unsigned int& val) { return PROP_UNSIGNED_INT; } - static PropertyType getTypeForValue(const long& val) { return PROP_LONG; } - static PropertyType getTypeForValue(const unsigned long& val) { return PROP_UNSIGNED_LONG; } - static PropertyType getTypeForValue(const Real& val) { return PROP_REAL; } - static PropertyType getTypeForValue(const String& val) { return PROP_STRING; } - static PropertyType getTypeForValue(const Vector2& val) { return PROP_VECTOR2; } - static PropertyType getTypeForValue(const Vector3& val) { return PROP_VECTOR3; } - static PropertyType getTypeForValue(const Vector4& val) { return PROP_VECTOR4; } - static PropertyType getTypeForValue(const ColourValue& val) { return PROP_COLOUR; } - static PropertyType getTypeForValue(const bool& val) { return PROP_BOOL; } - static PropertyType getTypeForValue(const Quaternion& val) { return PROP_QUATERNION; } - static PropertyType getTypeForValue(const Matrix3& val) { return PROP_MATRIX3; } - static PropertyType getTypeForValue(const Matrix4& val) { return PROP_MATRIX4; } - - protected: - // no default construction - PropertyDef() {} - - String mName; - String mDesc; - PropertyType mType; - - }; - - /// Map from property name to shared definition - typedef std::map PropertyDefMap; - - /** Base interface for an instance of a property. - */ - class _OgrePropertyExport PropertyBase : public PropertyAlloc - { - public: - /// Constructor - PropertyBase(PropertyDef* def) : mDef(def) {} - virtual ~PropertyBase() {} - - /// Get the name of the property - const String& getName() const { return mDef->getName(); } - - /// Get the description of the property - const String& getDescription() const { return mDef->getDescription(); } - - /// Get the type of the property - PropertyType getType() const { return mDef->getType(); } - - /// Return the current value as an Any - virtual Ogre::Any getValue() const = 0; - - protected: - // disallow default construction - PropertyBase() {} - PropertyDef* mDef; - - }; - - /** Property instance with passthrough calls to a given object. */ - template - class Property : public PropertyBase - { - public: - typedef T value_type; - typedef function< T (void) > getter_func; - typedef function< void (T) > setter_func; - - /** Construct a property which is able to directly call a given - getter and setter on a specific object instance, via functors. - */ - Property(PropertyDef* def, getter_func getter, setter_func setter) - : PropertyBase(def) - , mGetter(getter) - , mSetter(setter) - { - } - - /** Set the property value. - */ - virtual void set(T val) - { - mSetter(val); - } - - virtual T get() const - { - return mGetter(); - } - - Ogre::Any getValue() const override - { - return Ogre::Any(get()); - } - - protected: - // disallow default construction - Property() {} - ~Property() {} - - getter_func mGetter; - setter_func mSetter; - }; - - /** A simple structure designed just as a holder of property values between - the instances of objects they might target. There is just enough information - here to be able to interpret the results accurately but no more. - */ - struct PropertyValue - { - PropertyType propType; - Ogre::Any val; - }; - /// Defines a transferable map of properties using wrapped value types (Ogre::Any) - typedef std::map PropertyValueMap; - - - /** Defines a complete set of properties for a single object instance. - */ - class _OgrePropertyExport PropertySet : public PropertyAlloc - { - public: - PropertySet(); - ~PropertySet(); - - /** Adds a property to this set. - - The PropertySet is responsible for deleting this object. - */ - void addProperty(PropertyBase* prop); - - /** Gets the property object for a given property name. - - Note that this property will need to be cast to a templated property - compatible with the type you will be setting. You might find the - overloaded set and get methods quicker if - you already know the type. - */ - PropertyBase* getProperty(const String& name) const; - - /** Reports whether this property set contains a named property. */ - bool hasProperty(const String& name) const; - - /** Removes the named property from the property set. */ - void removeProperty(const String& name); - - typedef std::map PropertyMap; - - /** Gets an independently usable collection of property values from the - current state. - */ - PropertyValueMap getValueMap() const; - - /** Sets the current state from a given value map. - */ - void setValueMap(const PropertyValueMap& values); - - /** Get a named property value. - */ - template - void getValue(const String& name, T& value) const - { - getPropertyImpl(name, value, PropertyDef::getTypeForValue(value)); - } - - /** Set a named property value (via pointer to avoid copy). - */ - template - void setValue(const String& name, const T* value) - { - setPropertyImpl(name, *value, PropertyDef::getTypeForValue(*value)); - } - /** Set a named property value. - */ - template - void setValue(const String& name, T value) - { - setPropertyImpl(name, value, PropertyDef::getTypeForValue(value)); - } - /** Special-case char*, convert to String automatically. - */ - void setValue(const String& name, const char* pChar) - { - String v(pChar); - setPropertyImpl(name, v, PROP_STRING); - } - - - protected: - PropertyMap mPropertyMap; - - /// Set a named property value, internal implementation (type match required) - template - void setPropertyImpl(const String& name, const T& val, PropertyType typeCheck) - { - PropertyBase* baseProp = getProperty(name); - if (baseProp->getType() != typeCheck) - { - StringStream msg; - msg << "Property error: type passed in: '" << PropertyDef::getTypeName(typeCheck) - << "', type of property: '" << PropertyDef::getTypeName(baseProp->getType()) << "'"; - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, msg.str(), "PropertySet::setPropertyImpl"); - } - static_cast*>(baseProp)->set(val); - } - - /// Get a named property value, internal implementation (type match required) - template - void getPropertyImpl(const String& name, T& refVal, PropertyType typeCheck) const - { - PropertyBase* baseProp = getProperty(name); - if (baseProp->getType() != typeCheck) - { - StringStream msg; - msg << "Property error: type requested: '" << PropertyDef::getTypeName(typeCheck) - << "', type of property: '" << PropertyDef::getTypeName(baseProp->getType()) << "'"; - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, msg.str(), "PropertySet::getPropertyImpl"); - } - refVal = static_cast*>(baseProp)->get(); - } - - }; - - /** @} */ - /** @} */ - -} - -#endif diff --git a/Components/Property/src/OgreProperty.cpp b/Components/Property/src/OgreProperty.cpp deleted file mode 100644 index b3fd7e1150a..00000000000 --- a/Components/Property/src/OgreProperty.cpp +++ /dev/null @@ -1,256 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreProperty.h" -#include "OgrePrerequisites.h" -#include "OgreColourValue.h" - -#include - -namespace Ogre -{ - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - const String& PropertyDef::getTypeName(PropertyType theType) - { - static const String sPropNames[] = { - "short", - "unsigned short", - "int", - "unsigned int", - "long", - "unsigned long", - "Real", - "String", - "Vector2", - "Vector3", - "Vector4", - "ColourValue", - "bool", - "Quaternion", - "Matrix3", - "Matrix4" - }; - - return sPropNames[(int)theType]; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - PropertySet::PropertySet() - { - - } - //--------------------------------------------------------------------- - PropertySet::~PropertySet() - { - for (PropertyMap::iterator i = mPropertyMap.begin(); i != mPropertyMap.end(); ++i) - { - OGRE_DELETE i->second; - } - mPropertyMap.clear(); - } - //--------------------------------------------------------------------- - void PropertySet::addProperty(PropertyBase* prop) - { - std::pair retPair = mPropertyMap.emplace(prop->getName(), prop); - if (!retPair.second) - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, "Duplicate property entry!", - "PropertySet::addProperty"); - } - //--------------------------------------------------------------------- - bool PropertySet::hasProperty(const String& name) const - { - PropertyMap::const_iterator i = mPropertyMap.find(name); - return i != mPropertyMap.end(); - } - //--------------------------------------------------------------------- - PropertyBase* PropertySet::getProperty(const String& name) const - { - PropertyMap::const_iterator i = mPropertyMap.find(name); - if (i != mPropertyMap.end()) - return i->second; - else - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, "Property not found!", - "PropertySet::getProperty"); - } - //--------------------------------------------------------------------- - void PropertySet::removeProperty(const String& name) - { - mPropertyMap.erase(name); - } - //--------------------------------------------------------------------- - PropertyValueMap PropertySet::getValueMap() const - { - PropertyValueMap ret; - for (PropertyMap::const_iterator i = mPropertyMap.begin(); i != mPropertyMap.end(); ++i) - { - PropertyValue val; - val.propType = i->second->getType(); - switch(val.propType) - { - case PROP_SHORT: - val.val = Ogre::Any(static_cast*>(i->second)->get()); - break; - case PROP_UNSIGNED_SHORT: - val.val = Ogre::Any(static_cast*>(i->second)->get()); - break; - case PROP_INT: - val.val = Ogre::Any(static_cast*>(i->second)->get()); - break; - case PROP_UNSIGNED_INT: - val.val = Ogre::Any(static_cast*>(i->second)->get()); - break; - case PROP_LONG: - val.val = Ogre::Any(static_cast*>(i->second)->get()); - break; - case PROP_UNSIGNED_LONG: - val.val = Ogre::Any(static_cast*>(i->second)->get()); - break; - case PROP_REAL: - val.val = Ogre::Any(static_cast*>(i->second)->get()); - break; - case PROP_STRING: - val.val = Ogre::Any(static_cast*>(i->second)->get()); - break; - case PROP_VECTOR2: - val.val = Ogre::Any(static_cast*>(i->second)->get()); - break; - case PROP_VECTOR3: - val.val = Ogre::Any(static_cast*>(i->second)->get()); - break; - case PROP_VECTOR4: - val.val = Ogre::Any(static_cast*>(i->second)->get()); - break; - case PROP_COLOUR: - val.val = Ogre::Any(static_cast*>(i->second)->get()); - break; - case PROP_BOOL: - val.val = Ogre::Any(static_cast*>(i->second)->get()); - break; - case PROP_QUATERNION: - val.val = Ogre::Any(static_cast*>(i->second)->get()); - break; - case PROP_MATRIX3: - val.val = Ogre::Any(static_cast*>(i->second)->get()); - break; - case PROP_MATRIX4: - val.val = Ogre::Any(static_cast*>(i->second)->get()); - break; - case PROP_UNKNOWN: - default: - break; - }; - ret[i->second->getName()] = val; - } - - return ret; - - - } - //--------------------------------------------------------------------- - void PropertySet::setValueMap(const PropertyValueMap& values) - { - for (PropertyValueMap::const_iterator i = values.begin(); i != values.end(); ++i) - { - PropertyMap::iterator j = mPropertyMap.find(i->first); - if (j != mPropertyMap.end()) - { - // matching properties - // check type - if (j->second->getType() != i->second.propType) - { - StringStream msg; - msg << "Property " << i->first << " mismatched type; incoming type: '" - << PropertyDef::getTypeName(i->second.propType) << "', property type: '" - << PropertyDef::getTypeName(j->second->getType()) << "'"; - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, msg.str(), "PropertySet::setValueMap"); - } - switch(i->second.propType) - { - case PROP_SHORT: - static_cast*>(j->second)->set(Ogre::any_cast(i->second.val)); - break; - case PROP_UNSIGNED_SHORT: - static_cast*>(j->second)->set(Ogre::any_cast(i->second.val)); - break; - case PROP_INT: - static_cast*>(j->second)->set(Ogre::any_cast(i->second.val)); - break; - case PROP_UNSIGNED_INT: - static_cast*>(j->second)->set(Ogre::any_cast(i->second.val)); - break; - case PROP_LONG: - static_cast*>(j->second)->set(Ogre::any_cast(i->second.val)); - break; - case PROP_UNSIGNED_LONG: - static_cast*>(j->second)->set(Ogre::any_cast(i->second.val)); - break; - case PROP_REAL: - static_cast*>(j->second)->set(Ogre::any_cast(i->second.val)); - break; - case PROP_STRING: - static_cast*>(j->second)->set(Ogre::any_cast(i->second.val)); - break; - case PROP_VECTOR2: - static_cast*>(j->second)->set(Ogre::any_cast(i->second.val)); - break; - case PROP_VECTOR3: - static_cast*>(j->second)->set(Ogre::any_cast(i->second.val)); - break; - case PROP_VECTOR4: - static_cast*>(j->second)->set(Ogre::any_cast(i->second.val)); - break; - case PROP_COLOUR: - static_cast*>(j->second)->set(Ogre::any_cast(i->second.val)); - break; - case PROP_BOOL: - static_cast*>(j->second)->set(Ogre::any_cast(i->second.val)); - break; - case PROP_QUATERNION: - static_cast*>(j->second)->set(Ogre::any_cast(i->second.val)); - break; - case PROP_MATRIX3: - static_cast*>(j->second)->set(Ogre::any_cast(i->second.val)); - break; - case PROP_MATRIX4: - static_cast*>(j->second)->set(Ogre::any_cast(i->second.val)); - break; - case PROP_UNKNOWN: - default: - break; - - }; - - - } - } - - - } - -} - diff --git a/Components/Python/CMakeLists.txt b/Components/Python/CMakeLists.txt deleted file mode 100644 index b4682021e4c..00000000000 --- a/Components/Python/CMakeLists.txt +++ /dev/null @@ -1,105 +0,0 @@ -if(NOT PYTHONLIBS_FOUND OR NOT SWIG_FOUND) - set(OGRE_BUILD_COMPONENT_PYTHON OFF CACHE BOOL "" FORCE) - message(WARNING "Python Component disabled because SWIG or Python was not found") - return() -endif() - -include_directories(${PYTHON_INCLUDE_PATH}) -include_directories("${PROJECT_BINARY_DIR}/include" "${PROJECT_SOURCE_DIR}/OgreMain/include") -include(${SWIG_USE_FILE}) - -set(PYTHON_SITE_PACKAGES lib/python${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}/dist-packages/Ogre/) - -if(SKBUILD) - set(PYTHON_SITE_PACKAGES Ogre/) -endif() - -set(CMAKE_SWIG_FLAGS -w401,314 -builtin) - -if(SWIG_VERSION VERSION_LESS "4.1") - list(APPEND CMAKE_SWIG_FLAGS -Dfinal) -endif() - -if (APPLE AND NOT ANDROID) - # we are using libc++ on OSX - list(APPEND CMAKE_SWIG_FLAGS -D_LIBCPP_VERSION) -endif() - -if(OGRE_BUILD_COMPONENT_OVERLAY_IMGUI) - include_directories("${IMGUI_DIR}") - list(APPEND CMAKE_SWIG_FLAGS -DHAVE_IMGUI -DIMGUI_DISABLE_OBSOLETE_FUNCTIONS) -endif() - -macro(ogre_python_module target) - set_target_properties(${target} PROPERTIES DEBUG_POSTFIX "") - install(TARGETS ${target} LIBRARY DESTINATION ${PYTHON_SITE_PACKAGES}) - install(FILES ${PROJECT_BINARY_DIR}/Components/Python/${target}.py DESTINATION ${PYTHON_SITE_PACKAGES}) -endmacro() - -if(MSVC) - # TODO: Set MSVC flags - add_definitions(/wd4101 /wd4102 /bigobj) -else() - if(CMAKE_COMPILER_IS_GNUCXX) - add_definitions(-Wno-suggest-override) - endif() - add_definitions(-Wno-cast-qual -Wno-shadow -Wno-maybe-uninitialized -Wno-unused-label -Wno-unused-but-set-variable -Wno-missing-declarations -Wno-unused-variable) -endif() -set_source_files_properties(../../OgreMain/include/Ogre.i PROPERTIES CPLUSPLUS ON) - -# weakly link libpython on Unix to allow relocation -if(APPLE) - set(PYTHON_LIBRARIES "-Wl,-undefined,dynamic_lookup") -elseif(UNIX) - set(PYTHON_LIBRARIES "") -endif() - -swig_add_library(Ogre LANGUAGE python SOURCES ../../OgreMain/include/Ogre.i) -swig_link_libraries(Ogre OgreMain ${PYTHON_LIBRARIES}) -ogre_python_module(Ogre) - -# always install pure python modules -install(FILES __init__.py Numpy.py DESTINATION ${PYTHON_SITE_PACKAGES}) - -if(OGRE_BUILD_COMPONENT_RTSHADERSYSTEM) - set_source_files_properties(../RTShaderSystem/include/OgreRTShader.i PROPERTIES CPLUSPLUS ON) - swig_add_library(RTShader LANGUAGE python SOURCES ../RTShaderSystem/include/OgreRTShader.i) - swig_link_libraries(RTShader OgreRTShaderSystem ${PYTHON_LIBRARIES}) - ogre_python_module(RTShader) -endif() - -if(OGRE_BUILD_COMPONENT_OVERLAY) - set_source_files_properties(../Overlay/include/OgreOverlay.i PROPERTIES CPLUSPLUS ON) - swig_add_library(Overlay LANGUAGE python SOURCES ../Overlay/include/OgreOverlay.i) - swig_link_libraries(Overlay OgreOverlay ${PYTHON_LIBRARIES}) - ogre_python_module(Overlay) -endif() - -if(OGRE_BUILD_COMPONENT_TERRAIN) - set_source_files_properties(../Terrain/include/OgreTerrain.i PROPERTIES CPLUSPLUS ON) - swig_add_library(Terrain LANGUAGE python SOURCES ../Terrain/include/OgreTerrain.i) - swig_link_libraries(Terrain OgreTerrain ${PYTHON_LIBRARIES}) - ogre_python_module(Terrain) -endif() - -if(OGRE_BUILD_COMPONENT_OVERLAY_IMGUI) - set_source_files_properties(../Overlay/include/ImGui.i PROPERTIES CPLUSPLUS ON) - swig_add_library(ImGui LANGUAGE python SOURCES ../Overlay/include/ImGui.i) - swig_link_libraries(ImGui OgreOverlay ${PYTHON_LIBRARIES}) - ogre_python_module(ImGui) -endif() - -if(OGRE_BUILD_COMPONENT_BITES) - set_source_files_properties(../Bites/include/OgreBites.i PROPERTIES CPLUSPLUS ON) - swig_add_library(Bites LANGUAGE python SOURCES ../Bites/include/OgreBites.i) - swig_link_libraries(Bites OgreMain OgreBites ${PYTHON_LIBRARIES}) - ogre_python_module(Bites) -endif() - -if(OGRE_BUILD_COMPONENT_BULLET) - include_directories("${BULLET_INCLUDE_DIRS}") - set_source_files_properties(../Bullet/include/OgreBullet.i PROPERTIES CPLUSPLUS ON) - swig_add_library(Bullet LANGUAGE python SOURCES ../Bullet/include/OgreBullet.i) - swig_link_libraries(Bullet OgreMain OgreBullet ${PYTHON_LIBRARIES}) - ogre_python_module(Bullet) -endif() diff --git a/Components/Python/Numpy.py b/Components/Python/Numpy.py deleted file mode 100644 index b1767484877..00000000000 --- a/Components/Python/Numpy.py +++ /dev/null @@ -1,59 +0,0 @@ -import Ogre - -import ctypes -import numpy.ctypeslib as npc -import numpy as np - -def AsDataStream(arr): - """ - copy numpy array to Ogre.MemoryDataStream that can be used in Ogre - @param arr: some numpy array - """ - size = int(np.prod(arr.shape) * arr.dtype.itemsize) - ret = Ogre.MemoryDataStream(size) - tp = ctypes.POINTER(ctypes.c_ubyte) - np_view = npc.as_array(ctypes.cast(int(ret.getPtr()), tp), (size, )) - np_view[:] = arr.ravel().view(np.ubyte) - - return ret - -def view(o): - """ - writable numpy view to the ogre data types - - take care that the ogre type does not get released while the view is used. - e.g. this is invalid - - v = Ogre.Vector3() - return OgreNumpy.view(v) - - instead do - return OgreNumpy.view(v).copy() - - to pass numpy arrays into Ogre use AsDataStream() - """ - tp = ctypes.POINTER(ctypes.c_float) - - if isinstance(o, Ogre.Vector2): - shape = (2,) - ptr = o.this - elif isinstance(o, Ogre.Vector3): - shape = (3,) - ptr = o.this - elif isinstance(o, Ogre.Vector4): - shape = (4,) - ptr = o.this - elif isinstance(o, Ogre.Matrix3): - shape = (3, 3) - ptr = o.this - elif isinstance(o, Ogre.Matrix4): - shape = (4, 4) - ptr = o.this - elif isinstance(o, Ogre.PixelBox): - tp = ctypes.POINTER(ctypes.c_uint8) - shape = (o.getHeight(), o.getWidth(), Ogre.PixelUtil.getNumElemBytes(o.format)) - ptr = o.data - else: - raise TypeError("do not know how to map '{}'".format(type(o).__name__)) - - return npc.as_array(ctypes.cast(int(ptr), tp), shape) diff --git a/Components/Python/__init__.py b/Components/Python/__init__.py deleted file mode 100644 index 22b56cc2261..00000000000 --- a/Components/Python/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from Ogre.Ogre import * -from Ogre.Ogre import __version__ diff --git a/Components/RTShaderSystem/CMakeLists.txt b/Components/RTShaderSystem/CMakeLists.txt deleted file mode 100644 index 2864a99177a..00000000000 --- a/Components/RTShaderSystem/CMakeLists.txt +++ /dev/null @@ -1,40 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure Ogre RTShader System build - -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES - ${PROJECT_BINARY_DIR}/include/OgreRTShaderExports.h - ${PROJECT_BINARY_DIR}/include/OgreRTShaderConfig.h - ${CMAKE_CURRENT_SOURCE_DIR}/include/OgreRTShader.i) -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") - -get_native_precompiled_header(OgreRTShaderSystem) -add_library(OgreRTShaderSystem ${OGRE_COMP_LIB_TYPE} ${OgreRTShaderSystem_pch} ${HEADER_FILES} ${SOURCE_FILES}) -set_target_properties(OgreRTShaderSystem PROPERTIES VERSION ${OGRE_SOVERSION} SOVERSION ${OGRE_SOVERSION}) -target_link_libraries(OgreRTShaderSystem PUBLIC OgreMain) -target_include_directories(OgreRTShaderSystem PUBLIC - "$" - $) - -# repeat for PCH -include_directories("${PROJECT_SOURCE_DIR}/OgreMain/include" "${PROJECT_BINARY_DIR}/include" "${CMAKE_CURRENT_SOURCE_DIR}/include" "${CMAKE_CURRENT_SOURCE_DIR}/src") -add_native_precompiled_header(OgreRTShaderSystem "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreShaderPrecompiledHeaders.h") - -generate_export_header(OgreRTShaderSystem - EXPORT_MACRO_NAME _OgreRTSSExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreRTShaderExports.h) - -ogre_config_framework(OgreRTShaderSystem) -ogre_config_component(OgreRTShaderSystem) - -install(FILES ${HEADER_FILES} - DESTINATION include/OGRE/RTShaderSystem -) \ No newline at end of file diff --git a/Components/RTShaderSystem/include/OgreRTShader.i b/Components/RTShaderSystem/include/OgreRTShader.i deleted file mode 100644 index 59537228748..00000000000 --- a/Components/RTShaderSystem/include/OgreRTShader.i +++ /dev/null @@ -1,26 +0,0 @@ -%module(package="Ogre") RTShader -%{ -/* Includes the header in the wrapper code */ -#include "Ogre.h" -#include "OgreRTShaderSystem.h" -%} - -%include std_string.i -%include exception.i -%import "Ogre.i" - -#define _OgreRTSSExport - -%include "OgreRTShaderConfig.h" -%include "OgreShaderPrerequisites.h" -%include "OgreShaderScriptTranslator.h" -%include "OgreShaderSubRenderState.h" -%include "OgreShaderProgramWriter.h" -%ignore Ogre::RTShader::ShaderGenerator::getRenderState(const String&, const String&, unsigned short); -%ignore Ogre::RTShader::ShaderGenerator::createShaderBasedTechnique(const String&, const String&, const String&); -%ignore Ogre::RTShader::ShaderGenerator::createShaderBasedTechnique(const String&, const String&, const String&, bool); -%ignore Ogre::RTShader::ShaderGenerator::removeShaderBasedTechnique(const String&, const String&, const String&); -%include "OgreShaderGenerator.h" -%include "OgreShaderRenderState.h" -%include "OgreShaderExLayeredBlending.h" -%include "OgreShaderExHardwareSkinning.h" diff --git a/Components/RTShaderSystem/include/OgreRTShaderSystem.h b/Components/RTShaderSystem/include/OgreRTShaderSystem.h deleted file mode 100644 index 7d4a648d302..00000000000 --- a/Components/RTShaderSystem/include/OgreRTShaderSystem.h +++ /dev/null @@ -1,63 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _RTShaderSystem_ -#define _RTShaderSystem_ - -#include "OgreShaderProgramManager.h" -#include "OgreShaderProgramWriter.h" -#include "OgreShaderGenerator.h" -#include "OgreShaderRenderState.h" -#include "OgreShaderFunction.h" -#include "OgreShaderExLayeredBlending.h" -#include "OgreShaderExHardwareSkinning.h" - -/** \addtogroup Optional -* @{ -*/ -/** \defgroup RTShader RTShaderSystem -* Real Time Shader System: enables GPU program generation during the runtime of a process -* -* The main interface to do that is the ShaderGenerator singleton. -* A typical usage of this system would be to create shader based technique from an existing technique and -* associate it with a destination scheme name (see ShaderGenerator::createShaderBasedTechnique). -* The source technique must include only fixed function based passes, otherwise the method will fail. -* Once this task accomplished, one may switch the scheme of the current viewport(s) he uses, to -* the scheme he associate previously, and then a technique based on the original one will be used but this -* time it will be based on GPU programs the were generated by this component. -* -* The following are the highlights applications of this system. -* - Fixed function emulation for Render Systems that supports only shader based rendering. (D3D11 for example). -* Using this component will allow one to seamlessly use existing FFP techniques on these render systems. -* - Global custom shader based pipeline. One can extended the system to allow creation of custom shader based -* rendering techniques such as per pixel lighting, bump map, etc and apply it to all of the materials. -* That approach has the advantages of low maintenance of shader code since the code is the same for all materials instead -* of being spread around many different materials and programs. -* -*/ -/** @} */ - -#endif diff --git a/Components/RTShaderSystem/include/OgreShaderExHardwareSkinning.h b/Components/RTShaderSystem/include/OgreShaderExHardwareSkinning.h deleted file mode 100644 index 6e577dba3c9..00000000000 --- a/Components/RTShaderSystem/include/OgreShaderExHardwareSkinning.h +++ /dev/null @@ -1,178 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderExHardwareSkinning_ -#define _ShaderExHardwareSkinning_ - -#include "OgreShaderPrerequisites.h" - -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS -#include "OgreShaderSubRenderState.h" - -namespace Ogre { -namespace RTShader { -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -enum SkinningType -{ - ST_LINEAR, - ST_DUAL_QUATERNION -}; - -/** -A factory that enables creation of HardwareSkinning instances. -@remarks Sub class of SubRenderStateFactory -*/ -class _OgreRTSSExport HardwareSkinningFactory : public SubRenderStateFactory, - public Singleton -{ -public: - HardwareSkinningFactory(); - ~HardwareSkinningFactory(); - - /** - @see SubRenderStateFactory::getType. - */ - const String& getType() const override; - - /** - @see SubRenderStateFactory::createInstance. - */ - SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) override; - - /** - @see SubRenderStateFactory::writeInstance. - */ - void writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, Pass* dstPass) override; - - /** - Sets the list of custom shadow caster materials - */ - static void setCustomShadowCasterMaterials(const SkinningType skinningType, const MaterialPtr& caster1Weight, - const MaterialPtr& caster2Weight, const MaterialPtr& caster3Weight, - const MaterialPtr& caster4Weight); - - /** - Sets the list of custom shadow receiver materials - */ - static void setCustomShadowReceiverMaterials(const SkinningType skinningType, const MaterialPtr& receiver1Weight, - const MaterialPtr& receiver2Weight, const MaterialPtr& receiver3Weight, - const MaterialPtr& receiver4Weight); - - /** - Returns the name of a custom shadow caster material for a given number of weights - */ - static const MaterialPtr& getCustomShadowCasterMaterial(const SkinningType skinningType, ushort index); - - /** - Returns the name of a custom shadow receiver material for a given number of weights - */ - static const MaterialPtr& getCustomShadowReceiverMaterial(const SkinningType skinningType, ushort index); - - /** - @brief - Prepares an entity's material for use in the hardware skinning (HS). - - This function prepares an entity's material for use by the HS sub-render - state. This function scans the entity and extracts the information of the amount - of bones and weights in the entity. This function replaces the need specify in - the material script the amount of bones and weights needed to make the HS work. - - Note that this class does not save the the bone and weight count information - internally. Rather this information is stored in the entity's materials as a - user binded object. - - @par pEntity A pointer to an entity who's materials need preparing. - */ - static void prepareEntityForSkinning(const Entity* pEntity, SkinningType skinningType = ST_LINEAR, - bool correctAntidpodalityHandling = false, bool shearScale = false); - - /** - @brief - The maximum number of bones for which hardware skinning is performed. - - This number should be limited to avoid problems of using to many parameters - in a shader. For example, in pixel shader 3 this should be around 70-90 - dependent on other sub-render states in the shader. - - The default value for this property is 70 which correspond to pixel shader model 3 limitations - */ - static ushort getMaxCalculableBoneCount() { return mMaxCalculableBoneCount; } - /** - Sets the maximum number of bones for which hardware skinning is performed. - @see getMaxCalculableBoneCount() - */ - static void setMaxCalculableBoneCount(ushort count) { mMaxCalculableBoneCount = count; } - - /** - Override standard Singleton retrieval. - - @remarks Why do we do this? Well, it's because the Singleton - implementation is in a .h file, which means it gets compiled - into anybody who includes it. This is needed for the - Singleton template to work, but we actually only want it - compiled into the implementation of the class based on the - Singleton, not all of them. If we don't change this, we get - link errors when trying to use the Singleton-based class from - an outside dll. - - @par - This method just delegates to the template version anyway, - but the implementation stays in this single compilation unit, - preventing link errors. - */ - static HardwareSkinningFactory& getSingleton(void); - - /// @copydoc Singleton::getSingleton() - static HardwareSkinningFactory* getSingletonPtr(void); - -private: - - /** - @see SubRenderStateFactory::createInstanceImpl. - */ - SubRenderState* createInstanceImpl() override; - - ///The maximum number of bones for which hardware skinning is performed. - ///@see getMaxCalculableBoneCount() - static ushort mMaxCalculableBoneCount; -}; - -/** @} */ -/** @} */ - - -} -} - -#endif -#endif - diff --git a/Components/RTShaderSystem/include/OgreShaderExLayeredBlending.h b/Components/RTShaderSystem/include/OgreShaderExLayeredBlending.h deleted file mode 100644 index a3e1e0c503d..00000000000 --- a/Components/RTShaderSystem/include/OgreShaderExLayeredBlending.h +++ /dev/null @@ -1,144 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _OgreShaderExLayeredBlending_ -#define _OgreShaderExLayeredBlending_ - -#include "OgreShaderPrerequisites.h" -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS -#include "OgreShaderFFPTexturing.h" -#include "OgreShaderSubRenderState.h" - -namespace Ogre { -namespace RTShader { - -enum BlendMode : int; -enum SourceModifier : int; - -class _OgreRTSSExport LayeredBlending : public FFPTexturing -{ -public: - /** Class default constructor */ - LayeredBlending(); - - /** - @see SubRenderState::getType. - */ - const Ogre::String& getType () const override; - - - /** - Set the blend mode of the given texture unit layer with the previous layer. - @param index The texture unit texture. Textures units (index-1) and (index) will be blended. - @param mode The blend mode to apply. - */ - bool setBlendMode(uint16 index, const String& mode); - - /** - Return the blend mode of the given texture unit index. - */ - BlendMode getBlendMode(unsigned short index) const; - - - - /** - Set the source modifier parameters for a given texture unit - @param index Texture blend index - @param modType The source modification type to use - @param customNum The custom parameter number used to control the modification - */ - bool setSourceModifier(unsigned short index, const String& modType, int customNum); - - /** - Returns the source modifier parameters for a given texture unit - @return True if a valid modifier exist for the given texture unit - @param index Texture blend index - @param modType The source modification type to use - @param customNum The custom parameter number used to control the modification - */ - bool getSourceModifier(unsigned short index, SourceModifier& modType, int& customNum) const; - - /** - @see SubRenderState::copyFrom. - */ - void copyFrom(const SubRenderState& rhs) override; - - static String Type; - -private: - - /** - @see SubRenderState::resolveParameters. - */ - bool resolveParameters(ProgramSet* programSet) override; - - /** - @see SubRenderState::resolveDependencies. - */ - bool resolveDependencies(Ogre::RTShader::ProgramSet* programSet) override; - - - void addPSBlendInvocations(Function* psMain, - ParameterPtr arg1, - ParameterPtr arg2, - ParameterPtr texel, - int samplerIndex, - const LayerBlendModeEx& blendMode, - const int groupOrder, - Operand::OpMask targetChannels) override; - /** - Adds the function invocation to the pixel shader which will modify - the blend sources according to the source modification parameters. - */ - void addPSModifierInvocation(Function* psMain, - int samplerIndex, - ParameterPtr arg1, - ParameterPtr arg2, - const int groupOrder, - Operand::OpMask targetChannels); - - struct TextureBlend - { - TextureBlend(); - //The blend mode to use - BlendMode blendMode; - //The source modification to use - SourceModifier sourceModifier; - // The number of the custom param controlling the source modification - int customNum; - //The parameter controlling the source modification - ParameterPtr modControlParam; - }; - std::vector mTextureBlends; - -}; - -} // namespace RTShader -} // namespace Ogre - -#endif // RTSHADER_SYSTEM_BUILD_EXT_SHADERS -#endif // _OgreShaderExLayeredBlending_ diff --git a/Components/RTShaderSystem/include/OgreShaderFFPRenderState.h b/Components/RTShaderSystem/include/OgreShaderFFPRenderState.h deleted file mode 100644 index f45299a4edd..00000000000 --- a/Components/RTShaderSystem/include/OgreShaderFFPRenderState.h +++ /dev/null @@ -1,87 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderFFPState_ -#define _ShaderFFPState_ - -#include "OgreShaderPrerequisites.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -// Fixed Function vertex shader stages. -enum FFPVertexShaderStage -{ - FFP_VS_PRE_PROCESS = 0, - FFP_VS_TRANSFORM = 100, - FFP_VS_COLOUR = 200, - FFP_VS_LIGHTING = 300, - FFP_VS_TEXTURING = 400, - FFP_VS_FOG = 500, - FFP_VS_POST_PROCESS = 2000 -}; - -// Fixed Function fragment shader stages. -enum FFPFragmentShaderStage -{ - FFP_PS_PRE_PROCESS = 0, - FFP_PS_COLOUR_BEGIN = 100, - FFP_PS_SAMPLING = 150, - FFP_PS_TEXTURING = 200, - FFP_PS_COLOUR_END = 300, - FFP_PS_FOG = 400, - FFP_PS_POST_PROCESS = 500, - FFP_PS_ALPHA_TEST = 1000 -}; - -// Fixed Function generic stages. -enum FFPShaderStage -{ - FFP_PRE_PROCESS = 0, - FFP_TRANSFORM = 100, - FFP_COLOUR = 200, - FFP_LIGHTING = 300, - FFP_TEXTURING = 400, - FFP_FOG = 500, - FFP_POST_PROCESS = 600, - FFP_ALPHA_TEST = 1000 -}; - -/** @} */ -/** @} */ - -} -} - -#endif - diff --git a/Components/RTShaderSystem/include/OgreShaderFFPTexturing.h b/Components/RTShaderSystem/include/OgreShaderFFPTexturing.h deleted file mode 100644 index ce2a77cf7bd..00000000000 --- a/Components/RTShaderSystem/include/OgreShaderFFPTexturing.h +++ /dev/null @@ -1,229 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderFFPTextureStage_ -#define _ShaderFFPTextureStage_ - -#include "OgreShaderPrerequisites.h" -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS -#include "OgreShaderSubRenderState.h" -#include "OgreRenderSystem.h" - -namespace Ogre { -namespace RTShader { - - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** Texturing sub render state implementation of the Fixed Function Pipeline. -Implements texture coordinate processing: -@see http://msdn.microsoft.com/en-us/library/bb206247.aspx -Implements texture blending operation: -@see http://msdn.microsoft.com/en-us/library/bb206241.aspx -Derives from SubRenderState class. -*/ -class _OgreRTSSExport FFPTexturing : public SubRenderState -{ - -// Interface. -public: - - /** Class default constructor */ - FFPTexturing(); - - /** - @see SubRenderState::getType. - */ - const String& getType() const override; - - /** - @see SubRenderState::getType. - */ - int getExecutionOrder() const override; - - /** - @see SubRenderState::copyFrom. - */ - void copyFrom(const SubRenderState& rhs) override; - - /** - @see SubRenderState::preAddToRenderState. - */ - bool preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) override; - - static String Type; - -private: - friend class LayeredBlending; - - // Per texture unit parameters. - struct TextureUnitParams - { - // Texture unit state. - TextureUnitState* mTextureUnitState; - // Texture sampler index. - unsigned short mTextureSamplerIndex; - // Texture sampler index. - GpuConstantType mTextureSamplerType; - // Vertex shader input texture coordinate type. - GpuConstantType mVSInTextureCoordinateType; - // Vertex shader output texture coordinates type. - GpuConstantType mVSOutTextureCoordinateType; - // Texture coordinates calculation method. - TexCoordCalcMethod mTexCoordCalcMethod; - // Texture matrix parameter. - UniformParameterPtr mTextureMatrix; - // Texture View Projection Image space matrix parameter. - UniformParameterPtr mTextureViewProjImageMatrix; - // Texture sampler parameter. - UniformParameterPtr mTextureSampler; - // Vertex shader input texture coordinates parameter. - ParameterPtr mVSInputTexCoord; - // Vertex shader output texture coordinates parameter. - ParameterPtr mVSOutputTexCoord; - // Pixel shader input texture coordinates parameter. - ParameterPtr mPSInputTexCoord; - }; - - typedef std::vector TextureUnitParamsList; - typedef TextureUnitParamsList::iterator TextureUnitParamsIterator; - typedef TextureUnitParamsList::const_iterator TextureUnitParamsConstIterator; - - /** - Set the number of texture units this texturing sub state has to handle. - @param count The number of texture unit states. - */ - void setTextureUnitCount(size_t count); - - /** - Return the number of texture units this sub state handle. - */ - size_t getTextureUnitCount() const { return mTextureUnitParamsList.size(); } - - /** - Set texture unit of a given stage index. - @param index The stage index of the given texture unit state. - @param textureUnitState The texture unit state to bound the the stage index. - */ - void setTextureUnit(unsigned short index, TextureUnitState* textureUnitState); - - /** - Internal method that resolves uniform parameters of the given texture unit parameters. - */ - bool resolveUniformParams(TextureUnitParams* textureUnitParams, ProgramSet* programSet); - - /** - Internal method that resolves functions parameters of the given texture unit parameters. - */ - bool resolveFunctionsParams(TextureUnitParams* textureUnitParams, ProgramSet* programSet); - -//protected: - /** - @see SubRenderState::resolveParameters. - */ - bool resolveParameters(ProgramSet* programSet) override; - - /** - @see SubRenderState::resolveDependencies. - */ - bool resolveDependencies(ProgramSet* programSet) override; - - virtual void addPSBlendInvocations(Function* psMain, ParameterPtr arg1, ParameterPtr arg2, - ParameterPtr texel,int samplerIndex, const LayerBlendModeEx& blendMode, - const int groupOrder, Operand::OpMask targetChannels); -private: - /** - @see SubRenderState::addFunctionInvocations. - */ - bool addFunctionInvocations(ProgramSet* programSet) override; - - - /** - Internal method that adds vertex shader functions invocations. - */ - bool addVSFunctionInvocations(TextureUnitParams* textureUnitParams, Function* vsMain); - - /** - Internal method that adds pixel shader functions invocations. - */ - bool addPSFunctionInvocations(TextureUnitParams* textureUnitParams, Function* psMain); - - /** - Adds the fragment shader code which samples the texel color in the texture - */ - void addPSSampleTexelInvocation(TextureUnitParams* textureUnitParams, Function* psMain, - const ParameterPtr& texel, int groupOrder); - - ParameterPtr getPSArgument(ParameterPtr texel, LayerBlendSource blendSrc, const ColourValue& colourValue, - Real alphaValue, bool isAlphaArgument) const; - - /** - Determines if the given texture unit state need to use texture transformation matrix. - */ - bool needsTextureMatrix(TextureUnitState* textureUnitState); - - bool setParameter(const String& name, const String& value) override; - - // Texture units list. - TextureUnitParamsList mTextureUnitParamsList; - // World matrix parameter. - UniformParameterPtr mWorldMatrix; - // World inverse transpose matrix parameter. - UniformParameterPtr mWorldITMatrix; - // View matrix parameter. - UniformParameterPtr mViewMatrix; - // Vertex shader input normal parameter. - ParameterPtr mVSInputNormal; - // Vertex shader input position parameter. - ParameterPtr mVSInputPos; -//protected: - // Pixel shader output colour. - ParameterPtr mPSOutDiffuse; -private: - // Pixel shader diffuse colour. - ParameterPtr mPSDiffuse; - // Pixel shader specular colour. - ParameterPtr mPSSpecular; - - bool mIsPointSprite; - bool mLateAddBlend; -}; - -/** @} */ -/** @} */ - - -} -} - -#endif -#endif - diff --git a/Components/RTShaderSystem/include/OgreShaderFunction.h b/Components/RTShaderSystem/include/OgreShaderFunction.h deleted file mode 100644 index 465284622ce..00000000000 --- a/Components/RTShaderSystem/include/OgreShaderFunction.h +++ /dev/null @@ -1,300 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderProgramFunction_ -#define _ShaderProgramFunction_ - -#include "OgreShaderPrerequisites.h" -#include "OgreShaderParameter.h" -#include "OgreShaderFunctionAtom.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/// represents a @ref FFPShaderStage, part of a Function -class _OgreRTSSExport FunctionStageRef -{ - friend class Function; -public: - /** call a library function - * @param name the function name - * @param inout function argument - */ - void callFunction(const char* name, const InOut& inout) const; - - /// @overload - void callFunction(const char* name, const std::vector& params) const; - /// @overload - void callFunction(const char* name, const In& arg, const Out& ret) const { callFunction(name, {arg, ret}); } - /// @overload - void callFunction(const char* name, const In& arg0, const In& arg1, const Out& ret) const - { - callFunction(name, {arg0, arg1, ret}); - } - - /// dst = texture(sampler, texcoord); - void sampleTexture(const In& sampler, const In& texcoord, const Out& dst) const - { - sampleTexture({sampler, texcoord, dst}); - } - /// @overload - void sampleTexture(const std::vector& params) const; - - /// to = from; - void assign(const In& from, const Out& to) const { assign({from, to}); } - /// @overload - void assign(const std::vector& params) const; - - /// dst = arg0 * arg1; - void mul(const In& arg0, const In& arg1, const Out& dst) const { binaryOp('*', {arg0, arg1, dst}); } - - /// dst = arg0 / arg1; - void div(const In& arg0, const In& arg1, const Out& dst) const { binaryOp('/', {arg0, arg1, dst}); } - - /// dst = arg0 - arg1; - void sub(const In& arg0, const In& arg1, const Out& dst) const { binaryOp('-', {arg0, arg1, dst}); } - - /// dst = arg0 + arg1; - void add(const In& arg0, const In& arg1, const Out& dst) const { binaryOp('+', {arg0, arg1, dst}); } - - /// dst = arg0 OP arg1; - void binaryOp(char op, const std::vector& params) const; - - /// shorthand for "dst = BUILTIN(args);" - void callBuiltin(const char* name, const std::vector& params) const; - /// @overload - void callBuiltin(const char* name, const In& arg, const Out& ret) const { callBuiltin(name, {arg, ret}); } - /// @overload - void callBuiltin(const char* name, const In& arg0, const In& arg1, const Out& ret) const - { - callBuiltin(name, {arg0, arg1, ret}); - } - /// @overload - void callBuiltin(const char* name, const In& arg0, const In& arg1, const In& arg2, const Out& ret) const - { - callBuiltin(name, {arg0, arg1, arg2, ret}); - } -private: - uint32 mStage; - Function* mParent; - FunctionStageRef(uint32 stage, Function* parent) : mStage(stage), mParent(parent) {} -}; - -/** A class that represents a shader based program function. -*/ -class _OgreRTSSExport Function : public RTShaderSystemAlloc -{ - friend class ProgramManager; -// Interface. -public: - /// @deprecated - ParameterPtr resolveInputParameter(Parameter::Semantic semantic, int index, const Parameter::Content content, GpuConstantType type); - - /** Resolve input parameter of this function - @param content The content of the parameter. - @param type The type of the desired parameter. - @return parameter instance in case of that resolve operation succeeded. - */ - ParameterPtr resolveInputParameter(Parameter::Content content, GpuConstantType type = GCT_UNKNOWN) - { - return resolveInputParameter(Parameter::SPS_UNKNOWN, 0, content, type); - } - - /// resolve input parameter from previous output - ParameterPtr resolveInputParameter(const ParameterPtr& out) - { - OgreAssert(out, "parameter must not be NULL"); - return resolveInputParameter(out->getSemantic(), out->getIndex(), out->getContent(), out->getType()); - } - - /** - * get input parameter by content - * @param content - * @param type The type of the desired parameter. - * @return parameter or NULL if not found - */ - ParameterPtr getInputParameter(Parameter::Content content, GpuConstantType type = GCT_UNKNOWN) - { - return _getParameterByContent(mInputParameters, content, type); - } - - /// @deprecated - ParameterPtr resolveOutputParameter(Parameter::Semantic semantic, int index, const Parameter::Content content, GpuConstantType type); - - /** Resolve output parameter of this function - @param content The content of the parameter. - @param type The type of the desired parameter. - @return parameter instance in case of that resolve operation succeeded. - */ - ParameterPtr resolveOutputParameter(Parameter::Content content, GpuConstantType type = GCT_UNKNOWN) - { - return resolveOutputParameter(Parameter::SPS_UNKNOWN, 0, content, type); - } - - /** - * get output parameter by content - * @param content - * @param type The type of the desired parameter. - * @return parameter or NULL if not found - */ - ParameterPtr getOutputParameter(Parameter::Content content, GpuConstantType type = GCT_UNKNOWN) - { - return _getParameterByContent(mOutputParameters, content, type); - } - - /** Resolve local parameter of this function - - local parameters do not have index or semantic. - @param name The name of the parameter. - @param type The type of the desired parameter. - @param arraySize If > 0, the parameter will be an array of the given size. - @return parameter instance in case of that resolve operation succeeded. - */ - ParameterPtr resolveLocalParameter(GpuConstantType type, const String& name, size_t arraySize = 0); - - /** Resolve local parameter of this function - - local parameters do not have index or semantic. - @param content The content of the parameter. - @param type The type of the desired parameter. - @return parameter instance in case of that resolve operation succeeded. - */ - ParameterPtr resolveLocalParameter(Parameter::Content content, GpuConstantType type = GCT_UNKNOWN); - - - ParameterPtr resolveLocalStructParameter(const String& type, const String& name); - - /** - * get local parameter by content - * @param content - * @return parameter or NULL if not found - */ - ParameterPtr getLocalParameter(Parameter::Content content) - { - return _getParameterByContent(mLocalParameters, content, GCT_UNKNOWN); - } - /// @overload - ParameterPtr getLocalParameter(const String& name) - { - return _getParameterByName(mLocalParameters, name); - } - - /** Return a list of input parameters. */ - const ShaderParameterList& getInputParameters() const { return mInputParameters; } - - /** Return a list of output parameters. */ - const ShaderParameterList& getOutputParameters() const { return mOutputParameters; } - - /** Return a list of local parameters. */ - const ShaderParameterList& getLocalParameters() const { return mLocalParameters; } - - /** Add a function atom instance to this function. - @param atomInstance The atom instance to add. - */ - void addAtomInstance(FunctionAtom* atomInstance); - - /// get a @ref FFPShaderStage of this function - FunctionStageRef getStage(uint32 s) - { - return FunctionStageRef(s, this); - } - - /** Delete a function atom instance from this function. - @param atomInstance The atom instance to OGRE_DELETE. - */ - bool deleteAtomInstance(FunctionAtom* atomInstance); - - /** Return list of atom instances composing this function. (Const version) */ - const FunctionAtomInstanceList& getAtomInstances(); - - /** Add input parameter to this function. */ - void addInputParameter(ParameterPtr parameter); - - /** Add output parameter to this function. */ - void addOutputParameter(ParameterPtr parameter); - - /** Delete input parameter from this function. */ - void deleteInputParameter(ParameterPtr parameter); - - /** Delete output parameter from this function. */ - void deleteOutputParameter(ParameterPtr parameter); - - /** Delete all input parameters from this function. */ - void deleteAllInputParameters(); - - /** Delete all output parameters from this function. */ - void deleteAllOutputParameters(); - - explicit Function(GpuProgramType type = GPT_VERTEX_PROGRAM); - -private: - - static ParameterPtr _getParameterByName(const ShaderParameterList& parameterList, const String& name); - static ParameterPtr _getParameterBySemantic(const ShaderParameterList& parameterList, const Parameter::Semantic semantic, int index); - static ParameterPtr _getParameterByContent(const ShaderParameterList& parameterList, const Parameter::Content content, GpuConstantType type); - - /** Class destructor */ - ~Function(); - - /** Add parameter to given list */ - void addParameter(ShaderParameterList& parameterList, ParameterPtr parameter); - - /** Delete parameter from a given list */ - void deleteParameter(ShaderParameterList& parameterList, ParameterPtr parameter); - - // Input parameters. - ShaderParameterList mInputParameters; - // Output parameters. - ShaderParameterList mOutputParameters; - // Local parameters. - ShaderParameterList mLocalParameters; - // Atom instances composing this function. - std::map mAtomInstances; - FunctionAtomInstanceList mSortedAtomInstances; - - GpuProgramType mType; - - friend class Program; -}; - -typedef std::vector ShaderFunctionList; -typedef ShaderFunctionList::iterator ShaderFunctionIterator; -typedef ShaderFunctionList::const_iterator ShaderFunctionConstIterator; - -/** @} */ -/** @} */ - -} -} - -#endif diff --git a/Components/RTShaderSystem/include/OgreShaderFunctionAtom.h b/Components/RTShaderSystem/include/OgreShaderFunctionAtom.h deleted file mode 100644 index a896b9e3ece..00000000000 --- a/Components/RTShaderSystem/include/OgreShaderFunctionAtom.h +++ /dev/null @@ -1,340 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderFunctionAtom_ -#define _ShaderFunctionAtom_ - -#include "OgreShaderPrerequisites.h" -#include "OgreStringVector.h" -#include "OgreGpuProgramParams.h" -#include "OgreShaderParameter.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** A class that represents a function operand (its the combination of a parameter the in/out semantic and the used fields) -*/ -class _OgreRTSSExport Operand : public RTShaderSystemAlloc -{ -public: - - // InOut semantic - enum OpSemantic - { - /// The parameter is a input parameter - OPS_IN, - /// The parameter is a output parameter - OPS_OUT, - /// The parameter is a input/output parameter - OPS_INOUT - }; - - // Used field mask - enum OpMask : uchar - { - OPM_NONE = 0, - OPM_X = 0x0001, - OPM_Y = 0x0002, - OPM_Z = 0x0004, - OPM_W = 0x0008, - OPM_XY = OPM_X | OPM_Y, - OPM_XZ = OPM_X | OPM_Z, - OPM_XW = OPM_X | OPM_W, - OPM_YZ = OPM_Y | OPM_Z, - OPM_YW = OPM_Y | OPM_W, - OPM_ZW = OPM_Z | OPM_W, - OPM_XYZ = OPM_X | OPM_Y | OPM_Z, - OPM_XYW = OPM_X | OPM_Y | OPM_W, - OPM_XZW = OPM_X | OPM_Z | OPM_W, - OPM_YZW = OPM_Y | OPM_Z | OPM_W, - OPM_XYZW = OPM_X | OPM_Y | OPM_Z | OPM_W, - OPM_ALL = OPM_XYZW - }; - - /** Class constructor - @param parameter A function parameter. - @param opSemantic The in/out semantic of the parameter. - @param opMask The field mask of the parameter. - @param indirectionLevel - */ - Operand(ParameterPtr parameter, OpSemantic opSemantic, OpMask opMask = OPM_ALL, ushort indirectionLevel = 0); - - /** Copy constructor */ - Operand(const Operand& rhs); - - /** Copy the given Operand to this Operand. - @param rhs The other Operand to copy to this state. - */ - Operand& operator= (const Operand & rhs); - - /** Class destructor */ - ~Operand(); - - /** Returns the parameter object as weak reference */ - const ParameterPtr& getParameter() const { return mParameter; } - - /** Returns true if not all fields used. (usage is described through semantic)*/ - bool hasFreeFields() const { return mMask != OPM_ALL; } - - /** Returns the mask bitfield. */ - OpMask getMask() const { return mMask; } - - Operand& x() { return mask(OPM_X); } - Operand& y() { return mask(OPM_Y); } - Operand& z() { return mask(OPM_Z); } - Operand& w() { return mask(OPM_W); } - Operand& xy() { return mask(OPM_XY); } - Operand& xyz() { return mask(OPM_XYZ); } - - Operand& mask(OpMask opMask) - { - mMask = opMask; - return *this; - } - - /// automatically set swizzle to match parameter arity - void setMaskToParamType(); - - /** Returns the operand semantic (do we read/write or both with the parameter). */ - OpSemantic getSemantic() const { return mSemantic; } - - /** Returns the level of indirection. - The greater the indirection level the more the parameter needs to be nested in brackets. - For example given 4 parameters x1...x4 with the indirections levels 0,1,1,2 - respectively. The parameters should form the following string: x1[x2][x3[x4]]. - */ - ushort getIndirectionLevel() const { return mIndirectionLevel; } - - /** write the parameter name and the usage mask like this 'color.xyz' */ - void write(std::ostream& os) const; - - /** Return the float count of the given mask. */ - static int getFloatCount(int mask); -protected: - /// The parameter being carried by the operand - ParameterPtr mParameter; - /// Tells if the parameter is of type input,output or both - OpSemantic mSemantic; - /// Which part of the parameter should be passed (x,y,z,w) - OpMask mMask; - /// The level of indirection. @see getIndirectionLevel - ushort mIndirectionLevel; -}; - -struct _OgreRTSSExport In : Operand -{ - In(const Operand& rhs) : Operand(rhs) { OgreAssert(mSemantic == OPS_IN, "invalid semantic"); } - In(ParameterPtr p) : Operand(p, OPS_IN) {} - In(UniformParameterPtr p) : Operand(p, OPS_IN) {} - - // implicitly construct const params - In(float f) : Operand(ParameterFactory::createConstParam(f), OPS_IN) {} - In(const Vector2& v) : Operand(ParameterFactory::createConstParam(v), OPS_IN) {} - In(const Vector3& v) : Operand(ParameterFactory::createConstParam(v), OPS_IN) {} - In(const Vector4& v) : Operand(ParameterFactory::createConstParam(v), OPS_IN) {} -}; - -struct _OgreRTSSExport Out : Operand -{ - Out(const Operand& rhs) : Operand(rhs) { OgreAssert(mSemantic == OPS_OUT, "invalid semantic"); } - Out(ParameterPtr p) : Operand(p, OPS_OUT) {} - Out(UniformParameterPtr p) : Operand(p, OPS_OUT) {} -}; - -struct _OgreRTSSExport InOut : Operand -{ - InOut(const Operand& rhs) : Operand(rhs) { OgreAssert(mSemantic == OPS_INOUT, "invalid semantic"); } - InOut(ParameterPtr p) : Operand(p, OPS_INOUT) {} - InOut(UniformParameterPtr p) : Operand(p, OPS_INOUT) {} -}; - -/// shorthand for operator[] on preceding operand. e.g. myArray[p] -struct _OgreRTSSExport At : Operand -{ - At(ParameterPtr p) : Operand(p, OPS_IN, OPM_ALL, 1) {} - At(int f) : Operand(ParameterFactory::createConstParam(f), OPS_IN, OPM_ALL, 1) {} -}; - -/** A class that represents an atomic code section of shader based program function. -*/ -class _OgreRTSSExport FunctionAtom : public RTShaderSystemAlloc -{ -// Interface. -public: - typedef std::vector OperandVector; - - /** Class default destructor. */ - virtual ~FunctionAtom() {} - - /** Get the group execution order of this function atom. */ - int getGroupExecutionOrder() const; - - /** Get a list of parameters this function invocation will use in the function call as arguments. */ - OperandVector& getOperandList() { return mOperands; } - - /** Push a new operand (on the end) to the function. - @param parameter A function parameter. - @param opSemantic The in/out semantic of the parameter. - @param opMask The field mask of the parameter. - @param indirectionLevel The level of nesting inside brackets - */ - void pushOperand(ParameterPtr parameter, Operand::OpSemantic opSemantic, Operand::OpMask opMask = Operand::OPM_ALL, int indirectionLevel = 0); - - void setOperands(const OperandVector& ops); - - /** Abstract method that writes a source code to the given output stream in the target shader language. */ - virtual void writeSourceCode(std::ostream& os, const String& targetLanguage) const = 0; - -// Attributes. -protected: - /** Class default constructor. */ - FunctionAtom(); - - void writeOperands(std::ostream& os, OperandVector::const_iterator begin, OperandVector::const_iterator end) const; - - // The owner group execution order. - int mGroupExecutionOrder; - OperandVector mOperands; - String mFunctionName; -}; - -/** A class that represents function invocation code from shader based program function. -*/ -class _OgreRTSSExport FunctionInvocation : public FunctionAtom -{ - // Interface. -public: - /** Class constructor - @param functionName The name of the function to invoke. - @param groupOrder The group order of this invocation. - @param returnType The return type of the used function. - */ - FunctionInvocation(const String& functionName, int groupOrder, const String& returnType = "void"); - - /** Copy constructor */ - FunctionInvocation(const FunctionInvocation& rhs); - - /** - @see FunctionAtom::writeSourceCode - */ - void writeSourceCode(std::ostream& os, const String& targetLanguage) const override; - - /** Return the function name */ - const String& getFunctionName() const { return mFunctionName; } - - /** Return the return type */ - const String& getReturnType() const { return mReturnType; } - - /** Determines if the current object is equal to the compared one. */ - bool operator == ( const FunctionInvocation& rhs ) const; - - /** Determines if the current object is not equal to the compared one. */ - bool operator != ( const FunctionInvocation& rhs ) const; - - /** Determines if the current object is less than the compared one. */ - bool operator < ( const FunctionInvocation& rhs ) const; - - /** Comparator function to be used for sorting. - Implemented as a struct to make it easier for the compiler to inline - */ - struct FunctionInvocationLessThan - { - bool operator()(FunctionInvocation const& lhs, FunctionInvocation const& rhs) const; - }; - - /** Comparator function to be used for comparisons. - Implemented as a struct to make it easier for the compiler to inline - */ - struct FunctionInvocationCompare - { - bool operator()(FunctionInvocation const& lhs, FunctionInvocation const& rhs) const; - }; - -private: - FunctionInvocation() {} - - String mReturnType; -}; - -/// shorthand for "lhs = rhs;" insted of using FFP_Assign(rhs, lhs) -class _OgreRTSSExport AssignmentAtom : public FunctionAtom -{ -public: - explicit AssignmentAtom(int groupOrder) { mGroupExecutionOrder = groupOrder; } - /// @note the argument order is reversed comered to all other function invocations - AssignmentAtom(const Out& lhs, const In& rhs, int groupOrder); - void writeSourceCode(std::ostream& os, const String& targetLanguage) const override; -}; - -/// shorthand for "dst = texture(sampler, uv);" instead of using FFP_SampleTexture -class _OgreRTSSExport SampleTextureAtom : public FunctionAtom -{ -public: - explicit SampleTextureAtom(int groupOrder) { mGroupExecutionOrder = groupOrder; } - SampleTextureAtom(const In& sampler, const In& texcoord, const Out& dst, int groupOrder); - void writeSourceCode(std::ostream& os, const String& targetLanguage) const override; -}; - -/// shorthand for "dst = a OP b;" -class _OgreRTSSExport BinaryOpAtom : public FunctionAtom -{ - char mOp; -public: - BinaryOpAtom(char op, int groupOrder) : mOp(op) { mGroupExecutionOrder = groupOrder; } - BinaryOpAtom(char op, const In& a, const In& b, const Out& dst, int groupOrder); - void writeSourceCode(std::ostream& os, const String& targetLanguage) const override; -}; - -/// shorthand for "dst = BUILTIN(args);" -class _OgreRTSSExport BuiltinFunctionAtom : public FunctionAtom -{ -public: - BuiltinFunctionAtom(const char* builtin, int groupOrder) - { - mFunctionName = builtin; - mGroupExecutionOrder = groupOrder; - } - void writeSourceCode(std::ostream& os, const String& targetLanguage) const override; -}; - -typedef std::vector FunctionAtomInstanceList; -typedef FunctionAtomInstanceList::iterator FunctionAtomInstanceIterator; -typedef FunctionAtomInstanceList::const_iterator FunctionAtomInstanceConstIterator; - -/** @} */ -/** @} */ - -} -} - -#endif diff --git a/Components/RTShaderSystem/include/OgreShaderGenerator.h b/Components/RTShaderSystem/include/OgreShaderGenerator.h deleted file mode 100644 index 55dab612f16..00000000000 --- a/Components/RTShaderSystem/include/OgreShaderGenerator.h +++ /dev/null @@ -1,882 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderGenerator_ -#define _ShaderGenerator_ - -#include "OgreShaderPrerequisites.h" -#include "OgreSingleton.h" -#include "OgreFileSystemLayer.h" -#include "OgreRenderObjectListener.h" -#include "OgreSceneManager.h" -#include "OgreShaderRenderState.h" -#include "OgreScriptTranslator.h" -#include "OgreShaderScriptTranslator.h" -#include "OgreMaterialSerializer.h" - - -namespace Ogre { - - -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -class SGRenderObjectListener; -class SGSceneManagerListener; -class SGScriptTranslatorManager; -class SGResourceGroupListener; -class SGMaterialSerializerListener; -class ProgramManager; - -/** Shader generator system main interface. This singleton based class -enables automatic generation of shader code based on existing material techniques. -*/ -class _OgreRTSSExport ShaderGenerator : public Singleton, public RTShaderSystemAlloc -{ -// Interface. -public: - - /** - Initialize the Shader Generator System. - Return true upon success. - */ - static bool initialize(); - - /** - Destroy the Shader Generator instance. - */ - static void destroy(); - - - /** Override standard Singleton retrieval. - - Why do we do this? Well, it's because the Singleton - implementation is in a .h file, which means it gets compiled - into anybody who includes it. This is needed for the - Singleton template to work, but we actually only want it - compiled into the implementation of the class based on the - Singleton, not all of them. If we don't change this, we get - link errors when trying to use the Singleton-based class from - an outside dll. - @par - This method just delegates to the template version anyway, - but the implementation stays in this single compilation unit, - preventing link errors. - */ - static ShaderGenerator& getSingleton(); - - - /// @copydoc Singleton::getSingleton() - static ShaderGenerator* getSingletonPtr(); - - /** - Add a scene manager to the shader generator scene managers list. - @param sceneMgr The scene manager to add to the list. - */ - void addSceneManager(SceneManager* sceneMgr); - - /** - Remove a scene manager from the shader generator scene managers list. - @param sceneMgr The scene manager to remove from the list. - */ - void removeSceneManager(SceneManager* sceneMgr); - - /** - Get the active scene manager that is doint the actual scene rendering. - This attribute will be update on the call to preFindVisibleObjects. - */ - SceneManager* getActiveSceneManager(); - - /** - Set the active scene manager against which new render states are compiled. - Note that normally the setting of the active scene manager is updated through the - preFindVisibleObjects method. - */ - - void _setActiveSceneManager(SceneManager* sceneManager); - - /** - Set the target shader language. - @param shaderLanguage The output shader language to use. - @remarks The default shader language is cg. - */ - void setTargetLanguage(const String& shaderLanguage); - - /** - Return the target shader language currently in use. - */ - const String& getTargetLanguage() const { return mShaderLanguage; } - - /** - Set the output shader target profiles. - @param type shader type - @param shaderProfiles The target profiles for the shader. - */ - void setShaderProfiles(GpuProgramType type, const String& shaderProfiles); - - /** - Get the output shader target profiles. - */ - const String& getShaderProfiles(GpuProgramType type) const; - - /** - Set the output shader cache path. Generated shader code will be written to this path. - In case of empty cache path shaders will be generated directly from system memory. - @param cachePath The cache path of the shader. - The default is empty cache path. - */ - void setShaderCachePath(const String& cachePath); - - /** - Get the output shader cache path. - */ - const String& getShaderCachePath() const { return mShaderCachePath; } - - /** - Flush the shader cache. This operation will cause all active schemes to be invalidated and will - destroy any CPU/GPU program that created by this shader generator. - */ - void flushShaderCache(); - - /** - Return a global render state associated with the given scheme name. - Modifying this render state will affect all techniques that belongs to that scheme. - This is the best way to apply global changes to all techniques. - After altering the render state one should call invalidateScheme method in order to - regenerate shaders. - @param schemeName The destination scheme name. - */ - RenderState* getRenderState(const String& schemeName); - - - typedef std::pair RenderStateCreateOrRetrieveResult; - /** - Returns a requested render state. If the render state does not exist this function creates it. - @param schemeName The scheme name to retrieve. - */ - RenderStateCreateOrRetrieveResult createOrRetrieveRenderState(const String& schemeName); - - - /** - Tells if a given render state exists - @param schemeName The scheme name to check. - */ - bool hasRenderState(const String& schemeName) const; - - /** - Get render state of specific pass. - Using this method allows the user to customize the behavior of a specific pass. - @param schemeName The destination scheme name. - @param materialName The specific material name. - @param groupName The specific material name. - @param passIndex The pass index. - */ - RenderState* getRenderState(const String& schemeName, const String& materialName, const String& groupName, unsigned short passIndex); - - /// @overload - RenderState* getRenderState(const String& schemeName, const Material& mat, uint16 passIndex = 0) - { - return getRenderState(schemeName, mat.getName(), mat.getGroup(), passIndex); - } - - /** - Add sub render state factory. Plugins or 3d party applications may implement sub classes of - SubRenderState interface. Add the matching factory will allow the application to create instances - of these sub classes. - @param factory The factory to add. - */ - void addSubRenderStateFactory(SubRenderStateFactory* factory); - - /** - Returns the number of existing factories - */ - size_t getNumSubRenderStateFactories() const; - - /** - Returns a sub render state factory by index - @note index must be lower than the value returned by getNumSubRenderStateFactories() - */ - SubRenderStateFactory* getSubRenderStateFactory(size_t index); - - /** - Returns a sub render state factory by name - */ - SubRenderStateFactory* getSubRenderStateFactory(const String& type); - - /** - Remove sub render state factory. - @param factory The factory to remove. - */ - void removeSubRenderStateFactory(SubRenderStateFactory* factory); - - /** - Create an instance of sub render state from a given type. - @param type The type of sub render state to create. - */ - SubRenderState* createSubRenderState(const String& type); - - /// @overload - template - T* createSubRenderState() - { - return static_cast(createSubRenderState(T::Type)); - } - - /** - Destroy an instance of sub render state. - @param subRenderState The instance to destroy. - */ - void destroySubRenderState(SubRenderState* subRenderState); - - /** - Checks if a shader based technique has been created for a given technique. - Return true if exist. False if not. - @param materialName The source material name. - @param groupName The source group name. - @param srcTechniqueSchemeName The source technique scheme name. - @param dstTechniqueSchemeName The destination shader based technique scheme name. - */ - bool hasShaderBasedTechnique(const String& materialName, const String& groupName, const String& srcTechniqueSchemeName, const String& dstTechniqueSchemeName) const; - - /// @overload - bool hasShaderBasedTechnique(const Material& mat, const String& srcTechniqueSchemeName, const String& dstTechniqueSchemeName) const - { - return hasShaderBasedTechnique(mat.getName(), mat.getGroup(), srcTechniqueSchemeName, dstTechniqueSchemeName); - } - - /** - Create shader based technique from a given technique. - Return true upon success. Failure may occur if the source technique is not FFP pure, or different - source technique is mapped to the requested destination scheme. - @param srcMat The source material. - @param srcTechniqueSchemeName The source technique scheme name. - @param dstTechniqueSchemeName The destination shader based technique scheme name. - @param overProgrammable If true a shader will be created even if the pass already has shaders - */ - bool createShaderBasedTechnique(const Material& srcMat, const String& srcTechniqueSchemeName, const String& dstTechniqueSchemeName, bool overProgrammable = false); - - /// @overload - bool createShaderBasedTechnique(const Technique* srcTech, const String& dstTechniqueSchemeName, bool overProgrammable = false); - - /** - Remove shader based technique from a given technique. - Return true upon success. Failure may occur if the given source technique was not previously - registered successfully using the createShaderBasedTechnique method. - @param srcTech The source technique. - @param dstTechniqueSchemeName The destination shader based technique scheme name. - */ - bool removeShaderBasedTechnique(const Technique* srcTech, const String& dstTechniqueSchemeName); - - /** - Remove all shader based techniques of the given material. - Return true upon success. - @param materialName The source material name. - @param groupName The source group name. - */ - bool removeAllShaderBasedTechniques(const String& materialName, const String& groupName OGRE_RESOURCE_GROUP_INIT); - - /// @overload - bool removeAllShaderBasedTechniques(const Material& mat) - { - return removeAllShaderBasedTechniques(mat.getName(), mat.getGroup()); - } - - /** - Clone all shader based techniques from one material to another. - This function can be used in conjunction with the Material::clone() function to copy - both material properties and RTSS state from one material to another. - @param srcMat The source material - @param dstMat The destination material - @return True if successful - */ - bool cloneShaderBasedTechniques(const Material& srcMat, Material& dstMat); - - /** - Remove all shader based techniques that created by this shader generator. - */ - void removeAllShaderBasedTechniques(); - - /** - Create a scheme. - @param schemeName The scheme name to create. - */ - void createScheme(const String& schemeName); - - /** - Invalidate a given scheme. This action will lead to shader regeneration of all techniques belongs to the - given scheme name. - @param schemeName The scheme to invalidate. - */ - void invalidateScheme(const String& schemeName); - - /** - Validate a given scheme. This action will generate shader programs for all techniques of the - given scheme name. - @param schemeName The scheme to validate. - */ - bool validateScheme(const String& schemeName); - - /** - Invalidate specific material scheme. This action will lead to shader regeneration of the technique belongs to the - given scheme name. - @param schemeName The scheme to invalidate. - @param materialName The material to invalidate. - @param groupName The source group name. - */ - void invalidateMaterial(const String& schemeName, const String& materialName, const String& groupName OGRE_RESOURCE_GROUP_INIT); - - /// @overload - void invalidateMaterial(const String& schemeName, const Material& mat) - { - invalidateMaterial(schemeName, mat.getName(), mat.getGroup()); - } - - /** - Validate specific material scheme. This action will generate shader programs for the technique of the - given scheme name. - @param schemeName The scheme to validate. - @param materialName The material to validate. - @param groupName The source group name. - */ - bool validateMaterial(const String& schemeName, const String& materialName, const String& groupName OGRE_RESOURCE_GROUP_INIT); - - /// @overload - void validateMaterial(const String& schemeName, const Material& mat) - { - validateMaterial(schemeName, mat.getName(), mat.getGroup()); - } - - /** - Invalidate specific material scheme. This action will lead to shader regeneration of the technique belongs to the - given scheme name. - @param schemeName The scheme to invalidate. - @param materialName The material to invalidate. - @param groupName The source group name. - */ - void invalidateMaterialIlluminationPasses(const String& schemeName, const String& materialName, const String& groupName OGRE_RESOURCE_GROUP_INIT); - - /** - Validate specific material scheme. This action will generate shader programs illumination passes of the technique of the - given scheme name. - @param schemeName The scheme to validate. - @param materialName The material to validate. - @param groupName The source group name. - */ - bool validateMaterialIlluminationPasses(const String& schemeName, const String& materialName, const String& groupName OGRE_RESOURCE_GROUP_INIT); - - /** - Return custom material Serializer of the shader generator. - This is useful when you'd like to export certain material that contains shader generator effects. - I.E - when writing an exporter you may want mark your material as shader generated material - so in the next time you will load it by your application it will automatically generate shaders with custom - attributes you wanted. To do it you'll have to do the following steps: - 1. Create shader based technique for you material via the createShaderBasedTechnique() method. - 2. Create MaterialSerializer instance. - 3. Add the return instance of serializer listener to the MaterialSerializer. - 4. Call one of the export methods of MaterialSerializer. - */ - MaterialSerializer::Listener* getMaterialSerializerListener(); - - /** Return the current number of generated shaders. */ - size_t getShaderCount(GpuProgramType type) const; - - /** Set the vertex shader outputs compaction policy. - @see VSOutputCompactPolicy. - @param policy The policy to set. - */ - void setVertexShaderOutputsCompactPolicy(VSOutputCompactPolicy policy) { mVSOutputCompactPolicy = policy; } - - /** Get the vertex shader outputs compaction policy. - @see VSOutputCompactPolicy. - */ - VSOutputCompactPolicy getVertexShaderOutputsCompactPolicy() const { return mVSOutputCompactPolicy; } - - - /** Sets whether shaders are created for passes with shaders. - Note that this only refers to when the system parses the materials itself. - Not for when calling the createShaderBasedTechnique() function directly - @param value The value to set this attribute pass. - */ - void setCreateShaderOverProgrammablePass(bool value) { mCreateShaderOverProgrammablePass = value; } - - /** Returns whether shaders are created for passes with shaders. - @see setCreateShaderOverProgrammablePass(). - */ - bool getCreateShaderOverProgrammablePass() const { return mCreateShaderOverProgrammablePass; } - - - /** Returns the amount of schemes used in the for RT shader generation - */ - size_t getRTShaderSchemeCount() const; - - /** Returns the scheme name used in the for RT shader generation by index - */ - const String& getRTShaderScheme(size_t index) const; - - /// mark the given texture unit as non-FFP - static void _markNonFFP(const TextureUnitState* tu); - - /// same as @ref MSN_SHADERGEN - static String DEFAULT_SCHEME_NAME; -private: - class SGPass; - class SGTechnique; - class SGMaterial; - class SGScheme; - - typedef std::pair MatGroupPair; - struct MatGroupPair_less - { - // ensure we arrange the list first by material name then by group name - bool operator()(const MatGroupPair& p1, const MatGroupPair& p2) const - { - int cmpVal = strcmp(p1.first.c_str(),p2.first.c_str()); - return (cmpVal < 0) || ((cmpVal == 0) && (strcmp(p1.second.c_str(),p2.second.c_str()) < 0)); - } - }; - - typedef std::vector SGPassList; - typedef SGPassList::iterator SGPassIterator; - typedef SGPassList::const_iterator SGPassConstIterator; - - typedef std::vector SGTechniqueList; - typedef SGTechniqueList::iterator SGTechniqueIterator; - typedef SGTechniqueList::const_iterator SGTechniqueConstIterator; - - typedef std::map SGTechniqueMap; - typedef SGTechniqueMap::iterator SGTechniqueMapIterator; - - typedef std::map SGMaterialMap; - typedef SGMaterialMap::iterator SGMaterialIterator; - typedef SGMaterialMap::const_iterator SGMaterialConstIterator; - - typedef std::map SGSchemeMap; - typedef SGSchemeMap::iterator SGSchemeIterator; - typedef SGSchemeMap::const_iterator SGSchemeConstIterator; - - typedef std::map SGScriptTranslatorMap; - typedef SGScriptTranslatorMap::iterator SGScriptTranslatorIterator; - typedef SGScriptTranslatorMap::const_iterator SGScriptTranslatorConstIterator; - - - - /** Shader generator pass wrapper class. */ - class _OgreRTSSExport SGPass : public RTShaderSystemAlloc - { - public: - SGPass(SGTechnique* parent, Pass* srcPass, Pass* dstPass, IlluminationStage stage); - ~SGPass(); - - /** Build the render state and acquire the CPU/GPU programs */ - void buildTargetRenderState(); - - /** Get source pass. */ - Pass* getSrcPass() { return mSrcPass; } - - /** Get destination pass. */ - Pass* getDstPass() { return mDstPass; } - - /** Get illumination stage. */ - IlluminationStage getIlluminationStage() { return mStage; } - - /** Get illumination state. */ - bool isIlluminationPass() { return mStage != IS_UNKNOWN; } - - /** Get custom render state of this pass. */ - RenderState* getCustomRenderState() { return mCustomRenderState; } - - /** Set the custom render state of this pass. */ - void setCustomRenderState(RenderState* customRenderState) { mCustomRenderState = customRenderState; } - - const SGTechnique* getParent() const { return mParent; } - protected: - // Parent technique. - SGTechnique* mParent; - // Source pass. - Pass* mSrcPass; - // Destination pass. - Pass* mDstPass; - // Illumination stage - IlluminationStage mStage; - // Custom render state. - RenderState* mCustomRenderState; - }; - - - /** Shader generator technique wrapper class. */ - class _OgreRTSSExport SGTechnique : public RTShaderSystemAlloc - { - public: - SGTechnique(SGMaterial* parent, const Technique* srcTechnique, - const String& dstTechniqueSchemeName, bool overProgrammable); - ~SGTechnique(); - - /** Get the parent SGMaterial */ - const SGMaterial* getParent() const { return mParent; } - - /** Get the source technique. */ - const Technique* getSourceTechnique() { return mSrcTechnique; } - - /** Get the destination technique. */ - Technique* getDestinationTechnique() { return mDstTechnique; } - - /** Get the destination technique scheme name. */ - const String& getDestinationTechniqueSchemeName() const { return mDstTechniqueSchemeName; } - - /** Build the render state. */ - void buildTargetRenderState(); - - /** Build the render state for illumination passes. */ - void buildIlluminationTargetRenderState(); - - /** Destroy the illumination passes entries. */ - void destroyIlluminationSGPasses(); - - /** Release the CPU/GPU programs of this technique. */ - void releasePrograms(); - - /** Tells the technique that it needs to generate shader code. */ - void setBuildDestinationTechnique(bool buildTechnique) { mBuildDstTechnique = buildTechnique; } - - /** Tells if the destination technique should be build. */ - bool getBuildDestinationTechnique() const { return mBuildDstTechnique; } - - /** Get render state of specific pass. - @param passIndex The pass index. - */ - RenderState* getRenderState(unsigned short passIndex); - /** Tells if a custom render state exists for the given pass. */ - bool hasRenderState(unsigned short passIndex); - - /// whether shaders are created for passes with shaders - bool overProgrammablePass() { return mOverProgrammable; } - - const SGPassList& getPassList() const { return mPassEntries; } - - // Key name for associating with a Technique instance. - static String UserKey; - - protected: - - /** Create the passes entries. */ - void createSGPasses(); - - /** Create the illumination passes entries. */ - void createIlluminationSGPasses(); - - /** Destroy the passes entries. */ - void destroySGPasses(); - - protected: - // Auto mutex. - OGRE_AUTO_MUTEX; - // Parent material. - SGMaterial* mParent; - // Source technique. - const Technique* mSrcTechnique; - // Destination technique. - Technique* mDstTechnique; - // All passes entries, both normal and illumination. - SGPassList mPassEntries; - // The custom render states of all passes. - typedef std::vector RenderStateList; - RenderStateList mCustomRenderStates; - // Flag that tells if destination technique should be build. - bool mBuildDstTechnique; - // Scheme name of destination technique. - String mDstTechniqueSchemeName; - bool mOverProgrammable; - }; - - - /** Shader generator material wrapper class. */ - class _OgreRTSSExport SGMaterial : public RTShaderSystemAlloc - { - - public: - /** Class constructor. */ - SGMaterial(const String& materialName, const String& groupName) : mName(materialName), mGroup(groupName) - {} - - /** Get the material name. */ - const String& getMaterialName() const { return mName; } - - /** Get the group name. */ - const String& getGroupName() const { return mGroup; } - - /** Get the const techniques list of this material. */ - const SGTechniqueList& getTechniqueList() const { return mTechniqueEntries; } - - /** Get the techniques list of this material. */ - SGTechniqueList& getTechniqueList() { return mTechniqueEntries; } - - protected: - // The material name. - String mName; - // The group name. - String mGroup; - // All passes entries. - SGTechniqueList mTechniqueEntries; - }; - - - /** Shader generator scheme class. */ - class _OgreRTSSExport SGScheme : public RTShaderSystemAlloc - { - public: - SGScheme(const String& schemeName); - ~SGScheme(); - - - /** Return true if this scheme dose not contains any techniques. - */ - bool empty() const { return mTechniqueEntries.empty(); } - - /** Invalidate the whole scheme. - @see ShaderGenerator::invalidateScheme. - */ - void invalidate(); - - /** Validate the whole scheme. - @see ShaderGenerator::validateScheme. - */ - void validate(); - - /** Invalidate specific material. - @see ShaderGenerator::invalidateMaterial. - */ - void invalidate(const String& materialName, const String& groupName); - - /** Validate specific material. - @see ShaderGenerator::validateMaterial. - */ - bool validate(const String& materialName, const String& groupName); - - /** Validate illumination passes of the specific material. - @see ShaderGenerator::invalidateMaterialIlluminationPasses. - */ - void invalidateIlluminationPasses(const String& materialName, const String& groupName); - - /** Validate illumination passes of the specific material. - @see ShaderGenerator::validateMaterialIlluminationPasses. - */ - bool validateIlluminationPasses(const String& materialName, const String& groupName); - - /** Add a technique to current techniques list. */ - void addTechniqueEntry(SGTechnique* techEntry); - - /** Remove a technique from the current techniques list. */ - void removeTechniqueEntry(SGTechnique* techEntry); - - - /** Get global render state of this scheme. - @see ShaderGenerator::getRenderState. - */ - RenderState* getRenderState(); - - /** Get specific pass render state. - @see ShaderGenerator::getRenderState. - */ - RenderState* getRenderState(const String& materialName, const String& groupName, unsigned short passIndex); - - protected: - /** Synchronize the current light settings of this scheme with the current settings of the scene. */ - void synchronizeWithLightSettings(); - - /** Synchronize the fog settings of this scheme with the current settings of the scene. */ - void synchronizeWithFogSettings(); - - - protected: - // Scheme name. - String mName; - // Technique entries. - SGTechniqueList mTechniqueEntries; - // Tells if this scheme is out of date. - bool mOutOfDate; - // The global render state of this scheme. - std::unique_ptr mRenderState; - // Current fog mode. - FogMode mFogMode; - }; - - //----------------------------------------------------------------------------- - typedef std::map SubRenderStateFactoryMap; - typedef SubRenderStateFactoryMap::iterator SubRenderStateFactoryIterator; - typedef SubRenderStateFactoryMap::const_iterator SubRenderStateFactoryConstIterator; - - //----------------------------------------------------------------------------- - typedef std::set SceneManagerMap; - typedef SceneManagerMap::iterator SceneManagerIterator; - typedef SceneManagerMap::const_iterator SceneManagerConstIterator; - - friend class SGRenderObjectListener; - friend class SGSceneManagerListener; - - /** Class default constructor */ - ShaderGenerator(); - - /** Class destructor */ - ~ShaderGenerator(); - - /** Initialize the shader generator instance. */ - bool _initialize(); - - /** Destory the shader generator instance. */ - void _destroy(); - - /** Called from the sub class of the RenderObjectLister when single object is rendered. */ - void notifyRenderSingleObject(Renderable* rend, const Pass* pass, const AutoParamDataSource* source, const LightList* pLightList, bool suppressRenderStateChanges); - - /** Called from the sub class of the SceneManager::Listener when finding visible object process starts. */ - void preFindVisibleObjects(SceneManager* source, SceneManager::IlluminationRenderStage irs, Viewport* v); - - /** Create sub render state core extensions factories */ - void createBuiltinSRSFactories(); - - /** Destroy sub render state core extensions factories */ - void destroyBuiltinSRSFactories(); - - /** Create an instance of the SubRenderState based on script properties using the - current sub render state factories. - @see SubRenderStateFactory::createInstance - @param compiler The compiler instance. - @param prop The abstract property node. - @param pass The pass that is the parent context of this node. - @param translator The translator for the specific SubRenderState - */ - SubRenderState* createSubRenderState(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator); - - /** Create an instance of the SubRenderState based on script properties using the - current sub render state factories. - @see SubRenderStateFactory::createInstance - @param compiler The compiler instance. - @param prop The abstract property node. - @param texState The texture unit state that is the parent context of this node. - @param translator The translator for the specific SubRenderState - */ - SubRenderState* createSubRenderState(ScriptCompiler* compiler, PropertyAbstractNode* prop, TextureUnitState* texState, SGScriptTranslator* translator); - - /** Return a matching script translator. */ - ScriptTranslator* getTranslator(const AbstractNodePtr& node); - - /** Finds an entry iterator in the mMaterialEntriesMap map. - This function is able to find materials with group specified as - AUTODETECT_RESOURCE_GROUP_NAME - */ - SGMaterialIterator findMaterialEntryIt(const String& materialName, const String& groupName); - SGMaterialConstIterator findMaterialEntryIt(const String& materialName, const String& groupName) const; - - - typedef std::pair SchemeCreateOrRetrieveResult; - /** - Returns a requested scheme. If the scheme does not exist this function creates it. - @param schemeName The scheme name to retrieve. - */ - SchemeCreateOrRetrieveResult createOrRetrieveScheme(const String& schemeName); - - /** Used to check if finalizing */ - bool getIsFinalizing() const; - - /** Internal method that creates list of SGPass instances composing the given material. */ - SGPassList createSGPassList(Material* mat) const; - - // Auto mutex. - OGRE_AUTO_MUTEX; - // The active scene manager. - SceneManager* mActiveSceneMgr; - // A map of all scene managers this generator is bound to. - SceneManagerMap mSceneManagerMap; - // Render object listener. - std::unique_ptr mRenderObjectListener; - // Scene manager listener. - std::unique_ptr mSceneManagerListener; - // Script translator manager. - std::unique_ptr mScriptTranslatorManager; - // Custom material Serializer listener - allows exporting material that contains shader generated techniques. - std::unique_ptr mMaterialSerializerListener; - // get notified if materials get dropped - std::unique_ptr mResourceGroupListener; - // The core translator of the RT Shader System. - SGScriptTranslator mCoreScriptTranslator; - // The target shader language (currently only cg supported). - String mShaderLanguage; - // The target vertex shader profile. Will be used as argument for program compilation. - String mVertexShaderProfiles; - // The target fragment shader profile. Will be used as argument for program compilation. - String mFragmentShaderProfiles; - // Path for caching the generated shaders. - String mShaderCachePath; - // Shader program manager. - std::unique_ptr mProgramManager; - // Shader program writer manager. - std::unique_ptr mProgramWriterManager; - // File system layer manager. - FileSystemLayer* mFSLayer; - // Material entries map. - SGMaterialMap mMaterialEntriesMap; - // Scheme entries map. - SGSchemeMap mSchemeEntriesMap; - // All technique entries map. - SGTechniqueMap mTechniqueEntriesMap; - // Sub render state registered factories. - SubRenderStateFactoryMap mSubRenderStateFactories; - // Sub render state core extension factories. - std::vector mBuiltinSRSFactories; - // True if active view port use a valid SGScheme. - bool mActiveViewportValid; - // Light count per light type. - int mLightCount[3]; - // Vertex shader outputs compact policy. - VSOutputCompactPolicy mVSOutputCompactPolicy; - // Tells whether shaders are created for passes with shaders - bool mCreateShaderOverProgrammablePass; - // A flag to indicate finalizing - bool mIsFinalizing; - - uint32 ID_RT_SHADER_SYSTEM; - - friend class SGPass; - friend class SGScriptTranslatorManager; - friend class SGScriptTranslator; - friend class SGMaterialSerializerListener; - -}; - -/** @} */ -/** @} */ - -} -} - -#endif - diff --git a/Components/RTShaderSystem/include/OgreShaderParameter.h b/Components/RTShaderSystem/include/OgreShaderParameter.h deleted file mode 100644 index 6a59fc36244..00000000000 --- a/Components/RTShaderSystem/include/OgreShaderParameter.h +++ /dev/null @@ -1,594 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderParameter_ -#define _ShaderParameter_ - -#include "OgreShaderPrerequisites.h" -#include "OgreVector.h" -#include "OgreMatrix4.h" -#include "OgreGpuProgramParams.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** A class that represents a shader based program parameter. -*/ -class _OgreRTSSExport Parameter : public RTShaderSystemAlloc -{ -public: - // Shader parameter semantic. - enum Semantic - { - /// Unknown semantic - SPS_UNKNOWN = 0, - /// Position - SPS_POSITION = 1, - /// Blending weights - SPS_BLEND_WEIGHTS = 2, - /// Blending indices - SPS_BLEND_INDICES = 3, - /// Normal, 3 reals per vertex - SPS_NORMAL = 4, - /// General floating point color. - SPS_COLOR = 5, - /// Texture coordinates - SPS_TEXTURE_COORDINATES = 7, - /// Binormal (Y axis if normal is Z) - SPS_BINORMAL = 8, - /// Tangent (X axis if normal is Z) - SPS_TANGENT = 9, - /// VFACE - SPS_FRONT_FACING - }; - - /** Shader parameter content - * - * used to resolve Parameters across different SubRenderState instances - * Think of it as Semantic extended to the actual parameter content. - */ - enum Content - { - /// Unknown content - SPC_UNKNOWN, - - /// Position in object space - SPC_POSITION_OBJECT_SPACE, - - /// Position in world space - SPC_POSITION_WORLD_SPACE, - - /// Position in view space - SPC_POSITION_VIEW_SPACE, - - /// Position in projective space - SPC_POSITION_PROJECTIVE_SPACE, - - /// Position in light space index 0-7 - SPC_POSITION_LIGHT_SPACE0, - SPC_POSITION_LIGHT_SPACE1, - SPC_POSITION_LIGHT_SPACE2, - SPC_POSITION_LIGHT_SPACE3, - SPC_POSITION_LIGHT_SPACE4, - SPC_POSITION_LIGHT_SPACE5, - SPC_POSITION_LIGHT_SPACE6, - SPC_POSITION_LIGHT_SPACE7, - - /// Normal in object space - SPC_NORMAL_OBJECT_SPACE, - - /// Normal in world space - SPC_NORMAL_WORLD_SPACE, - - /// Normal in view space - SPC_NORMAL_VIEW_SPACE, - - /// View vector in object space - SPC_POSTOCAMERA_OBJECT_SPACE, - - /// View vector in world space - SPC_POSTOCAMERA_WORLD_SPACE, - - /// View vector in view space - SPC_POSTOCAMERA_VIEW_SPACE, - - /// Blending weights - SPC_BLEND_WEIGHTS, - - /// Blending indices - SPC_BLEND_INDICES, - - /// Tangent in object space - SPC_TANGENT_OBJECT_SPACE, - - /// Tangent in world space - SPC_TANGENT_WORLD_SPACE, - - /// Tangent in view space - SPC_TANGENT_VIEW_SPACE, - - /// Binormal in object space - SPC_BINORMAL_OBJECT_SPACE, - - /// Binormal in world space - SPC_BINORMAL_WORLD_SPACE, - - /// Binormal in view space - SPC_BINORMAL_VIEW_SPACE, - - /// Diffuse color - SPC_COLOR_DIFFUSE, - - /// Specular color - SPC_COLOR_SPECULAR, - - /// Depth in world space - SPC_DEPTH_WORLD_SPACE, - - /// Depth in view space - SPC_DEPTH_VIEW_SPACE, - - /// Depth in projective space - SPC_DEPTH_PROJECTIVE_SPACE, - - /// Texture coordinate set index 0-7 - SPC_TEXTURE_COORDINATE0, - SPC_TEXTURE_COORDINATE1, - SPC_TEXTURE_COORDINATE2, - SPC_TEXTURE_COORDINATE3, - SPC_TEXTURE_COORDINATE4, - SPC_TEXTURE_COORDINATE5, - SPC_TEXTURE_COORDINATE6, - SPC_TEXTURE_COORDINATE7, - - /// point sprite coordinates - SPC_POINTSPRITE_COORDINATE, - - /// point sprite size - SPC_POINTSPRITE_SIZE, - - /// gl_FrontFacing - SPC_FRONT_FACING, - - /// Reserved custom content range to be used by user custom shader extensions. - SPC_CUSTOM_CONTENT_BEGIN = 1000, - SPC_CUSTOM_CONTENT_END = 2000 - }; - -// Interface. -public: - /** */ - Parameter(); - - /** Class constructor. - @param type The type of this parameter. - @param name The name of this parameter. - @param semantic The semantic of this parameter. - @param index The index of this parameter. - @param content The content of this parameter. - @param size - */ - Parameter(GpuConstantType type, const String& name, - const Semantic& semantic, int index, - const Content& content, size_t size = 0); - - /** Class destructor */ - virtual ~Parameter() {}; - - /** Get the name of this parameter. */ - const String& getName() const { return mName; } - - /// internal function for aliasing to GLSL builtins e.g. gl_Position - void _rename(const String& newName, bool onlyLocal = false) - { - if(onlyLocal) - mBindName = mName; - mName = newName; - } - - /** Get the type of this parameter. */ - GpuConstantType getType() const { return mType; } - - /** Get the semantic of this parameter. */ - const Semantic& getSemantic() const { return mSemantic; } - - /** Get the index of this parameter. */ - int getIndex() const { return mIndex; } - - /** Return the content of this parameter. */ - Content getContent() const { return mContent; } - - /** Returns true if this instance is a ConstParameter otherwise false. */ - virtual bool isConstParameter() const { return false; } - - /** Returns the string representation of this parameter. */ - virtual String toString() const { return mName; } - - /** Returns Whether this parameter is an array. */ - bool isArray() const { return mSize > 0; } - - /** Returns the number of elements in the parameter (for arrays). */ - size_t getSize() const { return mSize; } - - /** Sets the number of elements in the parameter (for arrays). */ - void setSize(size_t size) { mSize = size; } - - /// track whether this was used - void setUsed(bool used) { mUsed = used; } - bool isUsed() { return mUsed; } - - /// Is highp needed when using GLSL ES - bool isHighP() const { return mIsHighP; } - void setHighP(bool highP) { mIsHighP = highP; } - - const String& getStructType() const { return mStructType; } - void setStructType(const String& structType) { mStructType = structType; } - -// Attributes. -protected: - // Name of this parameter. - String mName; - - // only used for local renaming - String mBindName; - - // Type of this parameter. - GpuConstantType mType; - - // Type, if this is a struct - String mStructType; - - // Semantic of this parameter. - Semantic mSemantic; - // Index of this parameter. - int mIndex; - // The content of this parameter. - Content mContent; - // Number of elements in the parameter (for arrays) - size_t mSize; - - bool mUsed; - bool mIsHighP; -}; - -typedef ShaderParameterList::iterator ShaderParameterIterator; -typedef ShaderParameterList::const_iterator ShaderParameterConstIterator; - -/** Uniform parameter class. Allow fast access to GPU parameter updates. -*/ -class _OgreRTSSExport UniformParameter : public Parameter -{ -public: - - /** Class constructor. - @param type The type of this parameter. - @param name The name of this parameter. - @param semantic The semantic of this parameter. - @param index The index of this parameter. - @param content The content of this parameter. - @param variability How this parameter varies (bitwise combination of GpuProgramVariability). - @param size number of elements in the parameter. - */ - UniformParameter(GpuConstantType type, const String& name, - const Semantic& semantic, int index, - const Content& content, - uint16 variability, size_t size); - - /** Class constructor. - @param autoType The auto type of this parameter. - @param fAutoConstantData The real data for this auto constant parameter. - @param size number of elements in the parameter. - */ - UniformParameter(GpuProgramParameters::AutoConstantType autoType, float fAutoConstantData, size_t size); - - /** Class constructor. - @param autoType The auto type of this parameter. - @param fAutoConstantData The real data for this auto constant parameter. - @param size number of elements in the parameter. - @param type The desired data type of this auto constant parameter. - */ - UniformParameter(GpuProgramParameters::AutoConstantType autoType, float fAutoConstantData, size_t size, GpuConstantType type); - - /** Class constructor. - @param autoType The auto type of this parameter. - @param nAutoConstantData The int data for this auto constant parameter. - @param size number of elements in the parameter. - */ - UniformParameter(GpuProgramParameters::AutoConstantType autoType, uint32 nAutoConstantData, size_t size); - - /** Class constructor. - @param autoType The auto type of this parameter. - @param nAutoConstantData The int data for this auto constant parameter. - @param size number of elements in the parameter. - @param type The desired data type of this auto constant parameter. - */ - UniformParameter(GpuProgramParameters::AutoConstantType autoType, uint32 nAutoConstantData, size_t size, GpuConstantType type); - - - /** Get auto constant int data of this parameter, in case it is auto constant parameter. */ - uint32 getAutoConstantIntData() const { return isArray() ? getSize() : mAutoConstantIntData; } - - /** Get auto constant real data of this parameter, in case it is auto constant parameter. */ - float getAutoConstantRealData() const { return mAutoConstantRealData; } - - /** Return true if this parameter is a floating point type, false otherwise. */ - bool isFloat() const { return GpuConstantDefinition::isFloat(mType); } - - /** Return true if this parameter is a texture sampler type, false otherwise. */ - bool isSampler() const { return GpuConstantDefinition::isSampler(mType); } - - /** Return true if this parameter is an auto constant parameter, false otherwise. */ - bool isAutoConstantParameter() const { return mIsAutoConstantReal || mIsAutoConstantInt; } - - /** Return true if this parameter an auto constant with int data type, false otherwise. */ - bool isAutoConstantIntParameter() const { return mIsAutoConstantInt; } - - /** Return true if this parameter an auto constant with real data type, false otherwise. */ - bool isAutoConstantRealParameter() const { return mIsAutoConstantReal; } - - /** Return the auto constant type of this parameter. */ - GpuProgramParameters::AutoConstantType getAutoConstantType () const { return mAutoConstantType; } - - /** Return the variability of this parameter. */ - uint16 getVariability() const { return mVariability; } - - /** Bind this parameter to the corresponding GPU parameter. */ - void bind(GpuProgramParametersSharedPtr paramsPtr); - -public: - - /** Update the GPU parameter with the given value. */ - void setGpuParameter(int val) - { - if (mParamsPtr != NULL) - { - mParamsPtr->_writeRawConstant(mPhysicalIndex, val); - } - } - - /** Update the GPU parameter with the given value. */ - void setGpuParameter(Real val) - { - if (mParamsPtr != NULL) - { - mParamsPtr->_writeRawConstant(mPhysicalIndex, val); - } - } - - /** Update the GPU parameter with the given value. */ - void setGpuParameter(const ColourValue& val) - { - if (mParamsPtr != NULL) - { - mParamsPtr->_writeRawConstant(mPhysicalIndex, val); - } - } - - /** Update the GPU parameter with the given value. */ - void setGpuParameter(const Vector2& val) - { - if (mParamsPtr != NULL) - { - mParamsPtr->_writeRawConstants(mPhysicalIndex, val.ptr(), 2); - } - } - - /** Update the GPU parameter with the given value. */ - void setGpuParameter(const Vector3& val) - { - if (mParamsPtr != NULL) - { - mParamsPtr->_writeRawConstant(mPhysicalIndex, val); - } - } - - /** Update the GPU parameter with the given value. */ - void setGpuParameter(const Vector4& val) - { - if (mParamsPtr != NULL) - { - mParamsPtr->_writeRawConstant(mPhysicalIndex, val); - } - } - - void setGpuParameter(const Matrix3& val) - { - if (mParamsPtr == NULL) return; - - if(mElementSize == 9) // check if tight packing is supported - { - mParamsPtr->_writeRawConstant(mPhysicalIndex, val, 9); - } - else - { - mParamsPtr->_writeRawConstant(mPhysicalIndex, Matrix4(val), mElementSize); - } - } - - /** Update the GPU parameter with the given value. */ - void setGpuParameter(const Matrix4& val) - { - if (mParamsPtr != NULL) - { - mParamsPtr->_writeRawConstant(mPhysicalIndex, val, 16); - } - } - - /** Update the GPU parameter with the given value. */ - void setGpuParameter(const float *val, size_t count, size_t multiple = 4) - { - if (mParamsPtr != NULL) - { - mParamsPtr->_writeRawConstants(mPhysicalIndex, val, count * multiple); - } - } - - /** Update the GPU parameter with the given value. */ - void setGpuParameter(const double *val, size_t count, size_t multiple = 4) - { - if (mParamsPtr != NULL) - { - mParamsPtr->_writeRawConstants(mPhysicalIndex, val, count * multiple); - } - } - - /** Update the GPU parameter with the given value. */ - void setGpuParameter(const int *val, size_t count, size_t multiple = 4) - { - if (mParamsPtr != NULL) - { - mParamsPtr->_writeRawConstants(mPhysicalIndex, val, count * multiple); - } - } - - /// light index or array size - void updateExtraInfo(uint32 data) - { - if (!mParamsPtr) - return; - - mParamsPtr->_setRawAutoConstant(mPhysicalIndex, mAutoConstantType, data, mVariability, - mElementSize); - } - -private: - // Is it auto constant real based parameter. - bool mIsAutoConstantReal; - // Is it auto constant int based parameter. - bool mIsAutoConstantInt; - GpuProgramParameters::AutoConstantType mAutoConstantType; // The auto constant type of this parameter. - union - { - // Auto constant int data. - uint32 mAutoConstantIntData; - // Auto constant real data. - float mAutoConstantRealData; - }; - // How this parameter varies (bitwise combination of GpuProgramVariability). - uint16 mVariability; - // The actual GPU parameters pointer. - GpuProgramParameters* mParamsPtr; - // The physical index of this parameter in the GPU program. - size_t mPhysicalIndex; - // The size of this parameter in the GPU program - uint8 mElementSize; -}; - -typedef std::vector UniformParameterList; -typedef UniformParameterList::iterator UniformParameterIterator; -typedef UniformParameterList::const_iterator UniformParameterConstIterator; - -/** Helper template which is the base for our ConstParameters -*/ -template -class ConstParameter : public Parameter -{ -public: - - ConstParameter( valueType val, - GpuConstantType type, - const Semantic& semantic, - const Content& content) - : Parameter(type, "Constant", semantic, 0, content) - { - mValue = val; - } - - virtual ~ConstParameter () {} - - /** Returns the native value of this parameter. (for example a Vector3) */ - const valueType& getValue() const { return mValue; } - - /** - @see Parameter::isConstParameter. - */ - bool isConstParameter() const override { return true; } - - /** - @see Parameter::toString. - */ - String toString() const override = 0; - -protected: - valueType mValue; -}; - -/** Helper utility class that creates common parameters. -*/ -class _OgreRTSSExport ParameterFactory -{ - - // Interface. -public: - - static ParameterPtr createInPosition(int index, Parameter::Content content = Parameter::SPC_POSITION_OBJECT_SPACE); - static ParameterPtr createOutPosition(int index); - - static ParameterPtr createInNormal(int index); - static ParameterPtr createInWeights(int index); - static ParameterPtr createInIndices(int index); - static ParameterPtr createOutNormal(int index); - static ParameterPtr createInBiNormal(int index); - static ParameterPtr createOutBiNormal(int index); - static ParameterPtr createInTangent(int index); - static ParameterPtr createOutTangent(int index); - static ParameterPtr createInColor(int index); - static ParameterPtr createOutColor(int index); - - static ParameterPtr createInTexcoord(GpuConstantType type, int index, Parameter::Content content); - static ParameterPtr createOutTexcoord(GpuConstantType type, int index, Parameter::Content content); - - static ParameterPtr createConstParam(const Vector2& val); - static ParameterPtr createConstParam(const Vector3& val); - static ParameterPtr createConstParam(const Vector4& val); - static ParameterPtr createConstParam(float val); - - static UniformParameterPtr createSampler(GpuConstantType type, int index); - static UniformParameterPtr createSampler1D(int index); - static UniformParameterPtr createSampler2D(int index); - static UniformParameterPtr createSampler2DArray(int index); - static UniformParameterPtr createSampler3D(int index); - static UniformParameterPtr createSamplerCUBE(int index); - - static UniformParameterPtr createUniform(GpuConstantType type, int index, uint16 variability, const String& suggestedName, size_t size); -}; - - - -/** @} */ -/** @} */ - -} -} - -#endif diff --git a/Components/RTShaderSystem/include/OgreShaderPrerequisites.h b/Components/RTShaderSystem/include/OgreShaderPrerequisites.h deleted file mode 100644 index d63991f9d6b..00000000000 --- a/Components/RTShaderSystem/include/OgreShaderPrerequisites.h +++ /dev/null @@ -1,90 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ShaderPrerequisites_H__ -#define __ShaderPrerequisites_H__ - -#include "OgrePrerequisites.h" -#include "OgreCommon.h" - -namespace Ogre -{ - -/// Forward declarations from Ogre namespace. -class Technique; -class Pass; -class Renderable; -class Viewport; -class RenderObjectListener; -class TextureUnitState; -class Frustum; -class ScriptTranslator; -class ScriptCompiler; -class PropertyAbstractNode; -class MaterialSerializer; - -typedef GeneralAllocatedObject RTShaderSystemAlloc; - -namespace RTShader -{ - -/// Forward declarations from RTShader namespace. -class RenderState; -class TargetRenderState; -class SubRenderState; -class SubRenderStateAccessor; -class SubRenderStateFactory; -class Program; -class ProgramSet; -class RenderState; -class Parameter; -class UniformParameter; -class Function; -class FunctionStageRef; -class ShaderGenerator; -class ProgramWriterManager; - -typedef shared_ptr ParameterPtr; -typedef shared_ptr UniformParameterPtr; -typedef std::vector ShaderParameterList; - -// Vertex shader output parameters compact policy. -enum VSOutputCompactPolicy -{ - VSOCP_LOW = 0, // VS Outputs will be compacted just in case the maximum slot count exceeded. - VSOCP_MEDIUM = 1, // VS Outputs will be compacted always without parameter splits. - VSOCP_HIGH = 2 // VS Outputs will be compacted always including parameter splits. -}; - -} -} - -#include "OgreRTShaderExports.h" -#include "OgreRTShaderConfig.h" - - -#endif - diff --git a/Components/RTShaderSystem/include/OgreShaderProgram.h b/Components/RTShaderSystem/include/OgreShaderProgram.h deleted file mode 100644 index b6e948858e9..00000000000 --- a/Components/RTShaderSystem/include/OgreShaderProgram.h +++ /dev/null @@ -1,228 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderProgram_ -#define _ShaderProgram_ - -#include "OgreShaderPrerequisites.h" -#include "OgreGpuProgram.h" -#include "OgreSingleton.h" -#include "OgreShaderFunction.h" -#include "OgreStringVector.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** A class that represents a shader based program. -*/ -class _OgreRTSSExport Program : public RTShaderSystemAlloc -{ - -// Interface. -public: - /** Get the type of this program. */ - GpuProgramType getType() const; - - /** Resolve uniform auto constant parameter with associated real data of this program. - @param autoType The auto type of the desired parameter. - @param data The data to associate with the auto parameter. - @param size number of elements in the parameter. - @return parameter instance in case of that resolve operation succeeded. - */ - UniformParameterPtr resolveAutoParameterReal(GpuProgramParameters::AutoConstantType autoType, Real data, size_t size = 0); - - /** Resolve uniform auto constant parameter with associated real data of this program. - @param autoType The auto type of the desired parameter. - @param type The desired data type of the auto parameter. - @param data The data to associate with the auto parameter. - @param size number of elements in the parameter. - @return parameter instance in case of that resolve operation succeeded. - */ - UniformParameterPtr resolveAutoParameterReal(GpuProgramParameters::AutoConstantType autoType, GpuConstantType type, float data, size_t size = 0); - - /** Resolve uniform auto constant parameter with associated int data of this program. - @param autoType The auto type of the desired parameter. - @param type The desired data type of the auto parameter. - @param data The data to associate with the auto parameter. - @param size number of elements in the parameter. - @return parameter instance in case of that resolve operation succeeded. - */ - UniformParameterPtr resolveAutoParameterInt(GpuProgramParameters::AutoConstantType autoType, GpuConstantType type, uint32 data, size_t size = 0); - - /** Resolve uniform parameter of this program. - @param type The type of the desired parameter. - @param index The index of the desired parameter. - @param suggestedName The suggested name for the parameter in case new one should be create. - @param variability How this parameter varies (bitwise combination of GpuProgramVariability). - @param size number of elements in the parameter. - @return parameter instance in case of that resolve operation succeeded. - @remarks Pass -1 as index parameter to create a new parameter with the desired type and index. - */ - UniformParameterPtr resolveParameter(GpuConstantType type, int index, uint16 variability, const String& suggestedName, size_t size = 0); - - /// @overload - UniformParameterPtr resolveParameter(GpuConstantType type, const String& name, int index = -1) - { - return resolveParameter(type, index, GPV_GLOBAL, name); - } - - /** Resolve uniform auto constant parameter - @param autoType The auto type of the desired parameter - @param data The data to associate with the auto parameter. - @return parameter instance in case of that resolve operation succeeded. - */ - UniformParameterPtr resolveParameter(GpuProgramParameters::AutoConstantType autoType, uint32 data = 0); - - /** Get parameter by a given name. - @param name The name of the parameter to search for. - @remarks Return NULL if no matching parameter found. - */ - UniformParameterPtr getParameterByName(const String& name); - - /** Get parameter by a given auto constant type. - @param autoType The auto type of the parameter to search for. - @remarks Return NULL if no matching parameter found. - */ - UniformParameterPtr getParameterByAutoType(GpuProgramParameters::AutoConstantType autoType); - - /** Get parameter by a given type and index. - @param type The type of the parameter to search for. - @param index The index of the parameter to search for. - @remarks Return NULL if no matching parameter found. - */ - UniformParameterPtr getParameterByType(GpuConstantType type, int index); - - /** Get the list of uniform parameters of this program. - */ - const UniformParameterList& getParameters() const { return mParameters; }; - - /// @deprecated use getMain() - Function* getEntryPointFunction() { return mEntryPointFunction; } - - Function* getMain() { return mEntryPointFunction; } - - /** Add dependency for this program. Basically a filename that will be included in this - program and provide predefined shader functions code. - One should verify that the given library file he provides can be reached by the resource manager. - This step can be achieved using the ResourceGroupManager::addResourceLocation method. - */ - void addDependency(const String& libFileName); - - /** Get the number of external libs this program depends on */ - size_t getDependencyCount() const; - - /** Get the library name of the given index dependency. - @param index The index of the dependecy. - */ - const String& getDependency(unsigned int index) const; - - /// @copydoc GpuProgram::setSkeletalAnimationIncluded - void setSkeletalAnimationIncluded(bool value) { mSkeletalAnimation = value; } - - /// @copydoc GpuProgram::isSkeletalAnimationIncluded - bool getSkeletalAnimationIncluded() const { return mSkeletalAnimation; } - - /// @copydoc GpuProgram::setInstancingIncluded - void setInstancingIncluded(bool included) { mInstancing = included; } - - /// @copydoc GpuProgram::isInstancingIncluded - bool getInstancingIncluded(void) const { return mInstancing; } - - /** Tells Ogre whether auto-bound matrices should be sent in column or row-major order. - - This method has the same effect as column_major_matrices option used when declaring manually written hlsl program. - You want to use this method only when you use float3x4 type in a shader, e.g. for bone matrices. - In mentioned case you should call this method with false as parameter. - @par - For more detail see OGRE Manual, section 3.1.6 DirectX9 HLSL. - @note - This setting has any effect only when the target language is HLSL. - @param value Should Ogre pass auto-bound matrices as column-major? The default is true. - */ - void setUseColumnMajorMatrices(bool value) { mColumnMajorMatrices = value; } - - /** Returns whether Ogre will pass auto-bound matrices as column-major. - @return - true, when the matrices will be passed in column-major order, false, when they will be passed as row-major. - */ - bool getUseColumnMajorMatrices() const { return mColumnMajorMatrices; } - - void addPreprocessorDefines(const String& defines); - - const String& getPreprocessorDefines() const { return mPreprocessorDefines; } - - /** Class destructor */ - ~Program(); -// Protected methods. -private: - - /** Class constructor. - @param type The type of this program. - */ - Program(GpuProgramType type); - - /** Destroy all parameters of this program. */ - void destroyParameters(); - - /** Add parameter to this program. */ - void addParameter(UniformParameterPtr parameter); - - /** Remove parameter from this program. */ - void removeParameter(UniformParameterPtr parameter); - - // Program type. (Vertex, Fragment, Geometry). - GpuProgramType mType; - // Program uniform parameters. - UniformParameterList mParameters; - // Entry point function for this program. - Function* mEntryPointFunction; - // Program dependencies. - StringVector mDependencies; - /// preprocessor definitions - String mPreprocessorDefines; - // Skeletal animation calculation - bool mSkeletalAnimation; - // Whether to pass matrices as column-major. - bool mColumnMajorMatrices; - bool mInstancing; - friend class TargetRenderState; -}; - -/** @} */ -/** @} */ - -} -} - -#endif - diff --git a/Components/RTShaderSystem/include/OgreShaderProgramManager.h b/Components/RTShaderSystem/include/OgreShaderProgramManager.h deleted file mode 100644 index d1348c6e55b..00000000000 --- a/Components/RTShaderSystem/include/OgreShaderProgramManager.h +++ /dev/null @@ -1,179 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderProgramManager_ -#define _ShaderProgramManager_ - -#include "OgreShaderPrerequisites.h" -#include "OgreSingleton.h" -#include "OgreGpuProgram.h" -#include "OgreStringVector.h" - -namespace Ogre { -namespace RTShader { - - class ProgramWriter; - class ProgramProcessor; - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** A singleton manager class that manages shader based programs. -*/ -class _OgreRTSSExport ProgramManager : public Singleton, public RTShaderSystemAlloc -{ -// Interface. -public: - - /** Class default constructor */ - ProgramManager(); - - /** Class destructor */ - ~ProgramManager(); - - - /** Override standard Singleton retrieval. - - Why do we do this? Well, it's because the Singleton - implementation is in a .h file, which means it gets compiled - into anybody who includes it. This is needed for the - Singleton template to work, but we actually only want it - compiled into the implementation of the class based on the - Singleton, not all of them. If we don't change this, we get - link errors when trying to use the Singleton-based class from - an outside dll. - @par - This method just delegates to the template version anyway, - but the implementation stays in this single compilation unit, - preventing link errors. - */ - static ProgramManager& getSingleton(); - - /// @copydoc Singleton::getSingleton() - static ProgramManager* getSingletonPtr(); - - /** Release CPU/GPU programs set associated with the given ProgramSet - @param programSet The ProgramSet holds the programs. - */ - void releasePrograms(const ProgramSet* programSet); - - /** Flush the local GPU programs cache. - */ - void flushGpuProgramsCache(); - -private: - - //----------------------------------------------------------------------------- - typedef std::map GpuProgramsMap; - typedef GpuProgramsMap::iterator GpuProgramsMapIterator; - typedef GpuProgramsMap::const_iterator GpuProgramsMapConstIterator; - - //----------------------------------------------------------------------------- - typedef std::set ProgramList; - typedef ProgramList::iterator ProgramListIterator; - typedef std::map ProgramWriterMap; - typedef ProgramWriterMap::iterator ProgramWriterIterator; - - //----------------------------------------------------------------------------- - typedef std::map ProgramProcessorMap; - typedef ProgramProcessorMap::iterator ProgramProcessorIterator; - typedef ProgramProcessorMap::const_iterator ProgramProcessorConstIterator; - typedef std::vector ProgramProcessorList; - - - /** Create default program processors. */ - void createDefaultProgramProcessors(); - - /** Destroy default program processors. */ - void destroyDefaultProgramProcessors(); - - /** Create CPU program . - @param type The type of the program to create. - */ - Program* createCpuProgram(GpuProgramType type); - - /** Destroy a CPU program by name. - @param shaderProgram The CPU program instance to destroy. - */ - void destroyCpuProgram(Program* shaderProgram); - - /** Create GPU programs for the given program set based on the CPU programs it contains. - @param programSet The program set container. - */ - void createGpuPrograms(ProgramSet* programSet); - - /** - Generates a unique hash from a string - @param programString source code to generate a hash value for - @param defines defines for the final source code - @return A string representing a 128 bit hash value of the original string - */ - static String generateHash(const String& programString, const String& defines); - - /** Create GPU program based on the give CPU program. - @param shaderProgram The CPU program instance. - @param programWriter The program writer instance. - @param language The target shader language. - @param profiles The profiles string for program compilation. - @param profilesList The profiles string for program compilation as string list. - @param cachePath The output path to write the program into. - */ - GpuProgramPtr createGpuProgram(Program* shaderProgram, - ProgramWriter* programWriter, - const String& language, - const String& profiles, - const String& cachePath); - - /** Return the number of created shaders. */ - size_t getShaderCount(GpuProgramType type) const; - - /** Fix the input of the pixel shader to be the same as the output of the vertex shader */ - void matchVStoPSInterface(ProgramSet* programSet); - - // Map between target language and shader program processor. - ProgramProcessorMap mProgramProcessorsMap; - // The generated shaders. - std::vector mShaderList; - // The default program processors. - ProgramProcessorList mDefaultProgramProcessors; - - friend class ProgramSet; - friend class TargetRenderState; - friend class ShaderGenerator; -}; - -/** @} */ -/** @} */ - -} -} - -#endif - diff --git a/Components/RTShaderSystem/include/OgreShaderProgramSet.h b/Components/RTShaderSystem/include/OgreShaderProgramSet.h deleted file mode 100644 index 37cf83719d0..00000000000 --- a/Components/RTShaderSystem/include/OgreShaderProgramSet.h +++ /dev/null @@ -1,89 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderProgramSet_ -#define _ShaderProgramSet_ - -#include "OgreShaderPrerequisites.h" -#include "OgreGpuProgram.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** Container class for shader based programs. -Holds both a CPU representation and GPU representation of vertex and fragment program. -*/ -class _OgreRTSSExport ProgramSet : public RTShaderSystemAlloc -{ - - // Interface. -public: - /** Class default constructor */ - ProgramSet(); - - /** Class destructor */ - ~ProgramSet(); - - /** Get the shader CPU program. */ - Program* getCpuProgram(GpuProgramType type) const; - - /** Get the shader GPU program. */ - const GpuProgramPtr& getGpuProgram(GpuProgramType type) const; - - // Protected methods. -private: - void setCpuProgram(std::unique_ptr&& program); - void setGpuProgram(const GpuProgramPtr& program); - - // Vertex shader CPU program. - std::unique_ptr mVSCpuProgram; - // Fragment shader CPU program. - std::unique_ptr mPSCpuProgram; - // Vertex shader GPU program. - GpuProgramPtr mVSGpuProgram; - // Fragment shader CPU program. - GpuProgramPtr mPSGpuProgram; - - friend class ProgramManager; - friend class TargetRenderState; - -}; - -/** @} */ -/** @} */ - -} -} - -#endif - diff --git a/Components/RTShaderSystem/include/OgreShaderProgramWriter.h b/Components/RTShaderSystem/include/OgreShaderProgramWriter.h deleted file mode 100644 index b5348cf5452..00000000000 --- a/Components/RTShaderSystem/include/OgreShaderProgramWriter.h +++ /dev/null @@ -1,115 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderProgramWriter_ -#define _ShaderProgramWriter_ - -#include "OgreShaderPrerequisites.h" -#include "OgreCommon.h" -#include "OgreGpuProgramParams.h" -#include "OgreGpuProgram.h" -#include "OgreShaderParameter.h" - -namespace Ogre { -namespace RTShader { - -class FunctionAtom; - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** Base class interface for shader program writers. -The main usage of this class is to generate a shader source code from the given CPU program. -In order to support specific shader language one should subclass this interface and implement the pure methods. -*/ - -class _OgreRTSSExport ProgramWriter : public RTShaderSystemAlloc -{ -// Interface. -public: - ProgramWriter(); - /** Class destructor */ - virtual ~ProgramWriter(); - - - /** Write the program shader source code. - @param os The output stream to write to code into. - @param program The source CPU program for the GPU program code. - */ - virtual void writeSourceCode (std::ostream& os, Program* program) = 0; - - /** Return the target language of this writer. */ - virtual const String& getTargetLanguage () const = 0; - -// Protected methods. -protected: - /** Write the program title. */ - void writeProgramTitle (std::ostream& os, Program* program); - - /** Write the uniform parameters title. */ - void writeUniformParametersTitle (std::ostream& os, Program* program); - - /** Write a function title. */ - void writeFunctionTitle (std::ostream& os, Function* function); - - /** Write a uniform parameter. */ - void writeSamplerParameter(std::ostream& os, const UniformParameterPtr& parameter); - - /** Write a undecorated/ local parameter. */ - void writeParameter(std::ostream& os, const ParameterPtr& parameter); - - /** Write a function parameter. */ - void writeParameterSemantic(std::ostream& os, const ParameterPtr& parameter); - - void redirectGlobalWrites(std::ostream& os, FunctionAtom* func, const ShaderParameterList& inputs, - const UniformParameterList& uniform); - - /** Write the program dependencies. */ - void writeProgramDependencies(std::ostream& os, Program* program); - - typedef std::map GpuConstTypeToStringMap; - typedef std::map ParamSemanticToStringMap; - // Map between GPU constant type to string value. - GpuConstTypeToStringMap mGpuConstTypeMap; - // Map between parameter semantic to string value. - ParamSemanticToStringMap mParamSemanticMap; - - std::set mLocalRenames; -}; - -/** @} */ -/** @} */ - -} -} - - - -#endif diff --git a/Components/RTShaderSystem/include/OgreShaderProgramWriterManager.h b/Components/RTShaderSystem/include/OgreShaderProgramWriterManager.h deleted file mode 100644 index 69bc10cafe1..00000000000 --- a/Components/RTShaderSystem/include/OgreShaderProgramWriterManager.h +++ /dev/null @@ -1,95 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ShaderProgramWriterManager_H__ -#define __ShaderProgramWriterManager_H__ - -#include "OgreShaderPrerequisites.h" -#include "OgreSingleton.h" - -namespace Ogre { -namespace RTShader { - - class ProgramWriter; - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -class _OgreRTSSExport ProgramWriterManager - : public Singleton, public RTShaderSystemAlloc -{ - std::map mProgramWriters; -public: - ProgramWriterManager(); - ~ProgramWriterManager(); - - /// register and transfer ownership of writer - void addProgramWriter(const String& lang, ProgramWriter* writer); - - /** Returns whether a given high-level language is supported. */ - bool isLanguageSupported(const String& lang); - - ProgramWriter* getProgramWriter(const String& language) const - { - auto it = mProgramWriters.find(language); - if (it != mProgramWriters.end()) - return it->second; - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "No program writer for language " + language); - return nullptr; - } - - /** Override standard Singleton retrieval. - - Why do we do this? Well, it's because the Singleton - implementation is in a .h file, which means it gets compiled - into anybody who includes it. This is needed for the - Singleton template to work, but we actually only want it - compiled into the implementation of the class based on the - Singleton, not all of them. If we don't change this, we get - link errors when trying to use the Singleton-based class from - an outside dll. - @par - This method just delegates to the template version anyway, - but the implementation stays in this single compilation unit, - preventing link errors. - */ - static ProgramWriterManager& getSingleton(); - - /// @copydoc Singleton::getSingleton() - static ProgramWriterManager* getSingletonPtr(); -}; -/** @} */ -/** @} */ -} -} - - -#endif diff --git a/Components/RTShaderSystem/include/OgreShaderRenderState.h b/Components/RTShaderSystem/include/OgreShaderRenderState.h deleted file mode 100644 index db836688ca7..00000000000 --- a/Components/RTShaderSystem/include/OgreShaderRenderState.h +++ /dev/null @@ -1,216 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderRenderState_ -#define _ShaderRenderState_ - -#include "OgreShaderPrerequisites.h" -#include "OgreShaderSubRenderState.h" -#include "OgreShaderProgramSet.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** This is a container class for sub render state class. -A render state is defined by the sub render states that compose it. -The user should use this interface to define global or per material custom behavior. -I.E In order to apply per pixel to a specific material one should implement a sub class of SubRenderState that -perform a per pixel lighting model, get the render state of the target material and add the custom sub class to it. -*/ -class _OgreRTSSExport RenderState : public RTShaderSystemAlloc -{ - - // Interface. -public: - - /** Class default constructor. */ - RenderState(); - - /** Class destructor */ - virtual ~RenderState(); - - /** Reset this render state */ - void resetToBuiltinSubRenderStates(); - - /** Add a template sub render state to this render state. - @param subRenderState The sub render state template to add. - */ - void addTemplateSubRenderState(SubRenderState* subRenderState); - - /// Add multiple template sub render states by SRS type - void addTemplateSubRenderStates(const StringVector& srsTypes); - - /** Remove a sub render state from this render state. - @param subRenderState The sub render state to remove. - */ - void removeSubRenderState(SubRenderState* subRenderState); - - /** Get the list of the sub render states composing this render state. */ - const SubRenderStateList& getSubRenderStates() const { return mSubRenderStateList; } - - /// get sub render state by type (uniquely identified) or NULL if not found - SubRenderState* getSubRenderState(const String& type) const; - - /** - Set the maximal light count to consider - */ - void setLightCount(int32 lightCount) { mLightCount = lightCount;} - - /** - Get the maximal light count to consider - */ - int32 getLightCount() const { return mLightCount; } - - /** - Set the light count auto update state. - If the value is false the light count will remain static for the values that were set by the user. - If the value is true the light count will be updated from the owner shader generator scheme based on current scene lights. - The default is true. - */ - void setLightCountAutoUpdate(bool autoUpdate) { mLightCountAutoUpdate = autoUpdate; } - - /** - Return true if this render state override the light count. - If light count is not overridden it will be updated from the shader generator based on current scene lights. - */ - bool getLightCountAutoUpdate() const { return mLightCountAutoUpdate; } - - bool haveAreaLights() const { return mHaveAreaLights; } - void setHaveAreaLights(bool val) { mHaveAreaLights = val; } - - - // Attributes. -protected: - // The sub render states list. - SubRenderStateList mSubRenderStateList; - // The light count per light type definition. - int32 mLightCount; - // True if light count was explicitly set. - bool mLightCountAutoUpdate; - bool mHaveAreaLights; - -private: - void clear(); - friend class ProgramManager; -}; - -/** This is the target render state. This class will hold the actual generated CPU/GPU programs. -It will be initially build from the FFP state of a given Pass by the FFP builder and then will be linked -with the custom pass render state and the global scheme render state. See ShaderGenerator::SGPass::buildTargetRenderState(). -*/ -class _OgreRTSSExport TargetRenderState : public RenderState -{ - -// Interface. -public: - - /** Class default constructor. */ - TargetRenderState(); - ~TargetRenderState(); - - /** Add the SubRenderStates of the given render state as templates to this render state. - @note Only sub render states with non FFP execution order will be added. - @param templateRS The other render state to use as a template. - @param srcPass The source pass that this render state is constructed from. - @param dstPass The destination pass that constructed from this render state. - */ - void link(const RenderState& templateRS, Pass* srcPass, Pass* dstPass); - - /** Add the SubRenderStates to this render state. - */ - void link(const StringVector& srsTypes, Pass* srcPass, Pass* dstPass); - - /** Update the GPU programs constant parameters before a renderable is rendered. - @param rend The renderable object that is going to be rendered. - @param pass The pass that is used to do the rendering operation. - @param source The auto parameter auto source instance. - @param pLightList The light list used for the current rendering operation. - */ - void updateGpuProgramsParams(Renderable* rend, const Pass* pass, const AutoParamDataSource* source, const LightList* pLightList); - - /** Add sub render state to this render state. - @param subRenderState The sub render state to add. - */ - void addSubRenderStateInstance(SubRenderState* subRenderState); - - /** Acquire CPU/GPU programs set associated with the given render state and bind them to the pass. - @param pass The pass to bind the programs to. - */ - void acquirePrograms(Pass* pass); - - /** Release CPU/GPU programs set associated with the given render state and pass. - @param pass The pass to release the programs from. - */ - void releasePrograms(Pass* pass); - - /// Key name for associating with a Pass instance. - static const char* UserKey; -private: - /** Bind the uniform parameters of a given CPU and GPU program set. */ - static void bindUniformParameters(Program* pCpuProgram, const GpuProgramParametersSharedPtr& passParams); - - /** Sort the sub render states composing this render state. */ - void sortSubRenderStates(); - - /** Create CPU programs that represent this render state. - */ - void createCpuPrograms(); - - /** Create the program set of this render state. - */ - ProgramSet* createProgramSet(); - - /** Return the program set of this render state. - */ - ProgramSet* getProgramSet() { return mProgramSet.get(); } - - // Tells if the list of the sub render states is sorted. - bool mSubRenderStateSortValid; - // The program set of this RenderState. - std::unique_ptr mProgramSet; - Pass* mParent; - -private: - friend class ProgramManager; -}; - -typedef std::shared_ptr TargetRenderStatePtr; - -/** @} */ -/** @} */ - -} -} - -#endif - diff --git a/Components/RTShaderSystem/include/OgreShaderScriptTranslator.h b/Components/RTShaderSystem/include/OgreShaderScriptTranslator.h deleted file mode 100644 index 6cf0942be5d..00000000000 --- a/Components/RTShaderSystem/include/OgreShaderScriptTranslator.h +++ /dev/null @@ -1,118 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderScriptTranslator_ -#define _ShaderScriptTranslator_ - -#include "OgreShaderPrerequisites.h" -#include "OgreScriptTranslator.h" -#include "OgreScriptCompiler.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** This class responsible for translating core features of the RT Shader System for -Ogre material scripts. -*/ -class _OgreRTSSExport SGScriptTranslator : public ScriptTranslator -{ -public: - - SGScriptTranslator(); - - /** - *@see ScriptTranslator::translate. - */ - void translate(ScriptCompiler *compiler, const AbstractNodePtr &node) override; - - using ScriptTranslator::getBoolean; - using ScriptTranslator::getColour; - using ScriptTranslator::getFloat; - using ScriptTranslator::getInt; - using ScriptTranslator::getReal; - using ScriptTranslator::getUInt; - using ScriptTranslator::getVector; - - /** - * Returns a sub render state of a given name which has already - * been created for material currently being generated by the - * script translator - * @note - * This function is meant to be used from within the createInstance - * function of sub-render state factories to avoid creating multiple - * sub-render state to the same material. - * - * @param typeName The type of the sub-render state to find. - */ - virtual SubRenderState* getGeneratedSubRenderState(const String& typeName); - - -protected: - /** - * Translates RT Shader System section within a pass context. - * @param compiler The compiler invoking this translator - * @param node The current AST node to be translated - */ - void translatePass(ScriptCompiler *compiler, const AbstractNodePtr &node); - - /** - * Translates RT Shader System section within a texture_unit context. - * @param compiler The compiler invoking this translator - * @param node The current AST node to be translated - */ - void translateTextureUnit(ScriptCompiler *compiler, const AbstractNodePtr &node); - - /** - * Adds a newly created subrender state to the material being translated - * @param newSubRenderState The sub-render state to add - * @param dstTechniqueSchemeName The technique which the sub render state is associated with - * @param materialName The material name which the sub render state is associated with - * @param groupName The material group name which the sub render state is associated with - * @param passIndex The index of the pass which the sub render state is associated with - */ - void addSubRenderState(SubRenderState* newSubRenderState, - const String& dstTechniqueSchemeName, const String& materialName, - const String& groupName, unsigned short passIndex); - - -private: - - //Render state created as a result of the current node being parsed - RenderState* mGeneratedRenderState; - -}; - -} -} - -#endif diff --git a/Components/RTShaderSystem/include/OgreShaderSubRenderState.h b/Components/RTShaderSystem/include/OgreShaderSubRenderState.h deleted file mode 100644 index 07def5f61ed..00000000000 --- a/Components/RTShaderSystem/include/OgreShaderSubRenderState.h +++ /dev/null @@ -1,369 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderSubRenderState_ -#define _ShaderSubRenderState_ - -#include "OgreShaderPrerequisites.h" -#include "OgreShaderScriptTranslator.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -typedef SharedPtr SubRenderStateAccessorPtr; - -/// Computes the position of the vertex in projection space, allows using instancing -_OgreRTSSExport extern const String SRS_TRANSFORM; -/// Enables vertex-colors, always required. -_OgreRTSSExport extern const String SRS_VERTEX_COLOUR; -/// Computes FFP texture transform and blending based on the assigned textures -_OgreRTSSExport extern const String SRS_TEXTURING; -/// Adds per-vertex (FFP) lighting calulations (Gouraud Shading) -_OgreRTSSExport extern const String SRS_PER_VERTEX_LIGHTING; -/// Modulates the color of a pixel based on the scene or object fog parameters -_OgreRTSSExport extern const String SRS_FOG; -/// Enables alpha-testing -_OgreRTSSExport extern const String SRS_ALPHA_TEST; -/// @deprecated use #SRS_SHADOW_MAPPING -_OgreRTSSExport extern const String SRS_INTEGRATED_PSSM3; -/// shadow mapping receiver with multiple lights or single PSSM light with up to 3 custom splits. -_OgreRTSSExport extern const String SRS_SHADOW_MAPPING; -/// Adds per-pixel lighting calulations (Phong Shading) -_OgreRTSSExport extern const String SRS_PER_PIXEL_LIGHTING; -/// Use metal roughness parametrisation for lighting calulations -_OgreRTSSExport extern const String SRS_COOK_TORRANCE_LIGHTING; -/// Adds calculations for indirect image based lighting (IBL) -_OgreRTSSExport extern const String SRS_IMAGE_BASED_LIGHTING; -/// Use a normal map to derive normals -_OgreRTSSExport extern const String SRS_NORMALMAP; -/// Redirects rendering results into intermediate buffers for the WBOIT algorithm -_OgreRTSSExport extern const String SRS_WBOIT; -/// Redirects rendering results into gbuffers for e.g. deferred shading. -_OgreRTSSExport extern const String SRS_GBUFFER; -/// enable [triplanar texture mapping](https://www.volume-gfx.com/volume-rendering/triplanar-texturing/) -_OgreRTSSExport extern const String SRS_TRIPLANAR_TEXTURING; -/// Apply photoshop-like blend effects to texture layers -_OgreRTSSExport extern const String SRS_LAYERED_BLENDING; -/// Include skinning calculations for Skeletal Animation in the shader to move computations to the GPU -_OgreRTSSExport extern const String SRS_HARDWARE_SKINNING; - -/** This class is the base interface of sub part from a shader based rendering pipeline. -* All sub parts implementations should derive from it and implement the needed methods. -A simple example of sub class of this interface will be the transform sub state of the -fixed pipeline. -*/ -class _OgreRTSSExport SubRenderState : public RTShaderSystemAlloc -{ - -// Interface. -public: - - /** Class default constructor */ - SubRenderState(); - - /** Class destructor */ - virtual ~SubRenderState(); - - - /** Get the type of this sub render state. - - The type string should be unique among all registered sub render states. - */ - virtual const String& getType() const = 0; - - - /** Get the execution order of this sub render state. - - The return value should be synchronized with the predefined values - of the FFPShaderStage enum. - */ - virtual int getExecutionOrder() const = 0; - - - /** Copy details from a given sub render state to this one. - @param rhs the source sub state to copy from. - */ - virtual void copyFrom(const SubRenderState& rhs) = 0; - - /** Operator = declaration. Assign the given source sub state to this sub state. - @param rhs the source sub state to copy from. - */ - SubRenderState& operator= (const SubRenderState& rhs); - - /** Create sub programs that represents this sub render state as part of a program set. - The given program set contains CPU programs that represents a vertex shader and pixel shader. - One should use these program class API to create a representation of the sub state he wished to - implement. - @param programSet container class of CPU and GPU programs that this sub state will affect on. - */ - virtual bool createCpuSubPrograms(ProgramSet* programSet); - - /** Update GPU programs parameters before a rendering operation occurs. - This method is called in the context of SceneManager::renderSingle object via the RenderObjectListener interface and - lets this sub render state instance opportunity to update custom GPU program parameters before the rendering action occurs. - @see RenderObjectListener::notifyRenderSingleObject. - @param rend The renderable that is about to be rendered. - @param pass The pass that used for this rendering. - @param source The auto parameter source. - @param pLightList The light list used in the current rendering context. - */ - virtual void updateGpuProgramsParams(Renderable* rend, const Pass* pass, const AutoParamDataSource* source, const LightList* pLightList) { } - - /** Called before adding this sub render state to the given render state. - Allows this sub render state class to configure specific parameters depending on source pass or parent render state. - Return of false value will cause canceling the add operation. - @param renderState The target render state container this sub render state is about to be added. - @param srcPass The source pass. - @param dstPass The destination pass. - */ - virtual bool preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) { return true; } - - /** Return the accessor object to this sub render state. - @see SubRenderStateAccessor. - */ - SubRenderStateAccessorPtr getAccessor(); - - /** Return the accessor object to this sub render state. - @see SubRenderStateAccessor. - */ - SubRenderStateAccessorPtr getAccessor() const; - - /// generic set method for parameters that connot be derived in @ref preAddToRenderState - virtual bool setParameter(const String& name, const String& value) { return false; } - - /// @overload - bool setParameter(const String& name, const char* value) { return setParameter(name, String(value)); } - - /// @overload - virtual void setParameter(const String& name, const Any& value) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, name+": unsupported any type"); - } - -// Protected methods -protected: - - /** Resolve parameters that this sub render state requires. - @param programSet container class of CPU and GPU programs that this sub state will affect on. - @remarks Internal method called in the context of SubRenderState::createCpuSubPrograms implementation. - */ - virtual bool resolveParameters(ProgramSet* programSet); - - /** Resolve dependencies that this sub render state requires. - @param programSet container class of CPU and GPU programs that this sub state will affect on. - @remarks Internal method called in the context of SubRenderState::createCpuSubPrograms implementation. - */ - virtual bool resolveDependencies(ProgramSet* programSet); - - /** Add function invocation that this sub render state requires. - @param programSet container class of CPU and GPU programs that this sub state will affect on. - @remarks Internal method called in the context of SubRenderState::createCpuSubPrograms implementation. - */ - virtual bool addFunctionInvocations(ProgramSet* programSet); - -// Attributes. -private: - // The accessor of this instance. - mutable SubRenderStateAccessorPtr mThisAccessor; - // The accessor of the source instance which used as base to create this instance. - SubRenderStateAccessorPtr mOtherAccessor; - -}; - -typedef std::vector SubRenderStateList; -typedef SubRenderStateList::iterator SubRenderStateListIterator; -typedef SubRenderStateList::const_iterator SubRenderStateListConstIterator; - -typedef std::set SubRenderStateSet; -typedef SubRenderStateSet::iterator SubRenderStateSetIterator; -typedef SubRenderStateSet::const_iterator SubRenderStateSetConstIterator; - - -/** This class uses as accessor from a template SubRenderState to all of its instances that -created based on it. Since SubRenderState that added as templates to a RenderState are not directly used by the -system this class enable accessing the used instances. -A common usage will be add a SubRenderState to certain pass, obtain accessor and then call a method on the instanced SubRenderState -that will trigger some GPU uniform parameter updates. -*/ -class _OgreRTSSExport SubRenderStateAccessor -{ -public: - /** Add SubRenderState instance to this accessor. - */ - void addSubRenderStateInstance(SubRenderState* subRenderState) const - { - mSubRenderStateInstancesSet.insert(subRenderState); - } - - /** Remove SubRenderState instance to this accessor. - */ - void removeSubRenderStateInstance(SubRenderState* subRenderState) const - { - SubRenderStateSetIterator itFind = mSubRenderStateInstancesSet.find(subRenderState); - - if (itFind != mSubRenderStateInstancesSet.end()) - { - mSubRenderStateInstancesSet.erase(itFind); - } - } - - /** Return a set of all instances of the template SubRenderState. */ - SubRenderStateSet& getSubRenderStateInstanceSet() { return mSubRenderStateInstancesSet; } - - /** Return a set of all instances of the template SubRenderState. (const version). */ - const SubRenderStateSet& getSubRenderStateInstanceSet() const { return mSubRenderStateInstancesSet; } - -protected: - /** Construct SubRenderState accessor based on the given template SubRenderState. - */ - SubRenderStateAccessor(const SubRenderState* templateSubRenderState) : mTemplateSubRenderState(templateSubRenderState) {} - - -protected: - const SubRenderState* mTemplateSubRenderState; - mutable SubRenderStateSet mSubRenderStateInstancesSet; - -private: - friend class SubRenderState; - -}; - - -/** Abstract factory interface for creating SubRenderState implementation instances. - -Plugins or 3rd party applications can add new types of sub render states to the -RTShader System by creating subclasses of the SubRenderState class. -Because multiple instances of these sub class may be required, -a factory class to manage the instances is also required. -@par -SubRenderStateFactory subclasses must allow the creation and destruction of SubRenderState -subclasses. They must also be registered with the ShaderGenerator::addSubRenderStateFactory. -All factories have a type which identifies them and the sub class of SubRenderState they creates. -*/ -class _OgreRTSSExport SubRenderStateFactory : public RTShaderSystemAlloc -{ - -public: - SubRenderStateFactory() {} - virtual ~SubRenderStateFactory(); - - /** Get the type of this sub render state factory. - - The type string should be the same as the type of the SubRenderState sub class it is going to create. - @see SubRenderState::getType. - */ - virtual const String& getType() const = 0; - - /** Create an instance of the SubRenderState sub class it suppose to create. - */ - virtual SubRenderState* createInstance() OGRE_NODISCARD; - - /** Create an instance of the SubRenderState based on script properties. - This method is called in the context of script parsing and let this factory - the opportunity to create custom SubRenderState instances based on extended script properties. - @param compiler The compiler instance. - @param prop The abstract property node. - @param pass The pass that is the parent context of this node. - @param translator The translator instance holding existing scripts. - */ - virtual SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) OGRE_NODISCARD - { return NULL; } - - /** Create an instance of the SubRenderState based on script properties. - This method is called in the context of script parsing and let this factory - the opportunity to create custom SubRenderState instances based on extended script properties. - @param compiler The compiler instance. - @param prop The abstract property node. - @param texState The pass that is the parent context of this node. - @param translator The translator instance holding existing scripts. - */ - virtual SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, TextureUnitState* texState, SGScriptTranslator* translator) OGRE_NODISCARD - { return NULL; } - - /** Retrieve the previous instance the SRS in the script translator or - * create a new instance if not found - @param translator The translator instance holding existing scripts. - */ - virtual SubRenderState* createOrRetrieveInstance(SGScriptTranslator* translator); - - /** Destroy the given instance. - @param subRenderState The instance to destroy. - */ - virtual void destroyInstance(SubRenderState* subRenderState); - - /** Destroy all the instances that created by this factory. - */ - virtual void destroyAllInstances(); - - /** Write the given sub-render state instance using the material serializer. - This method is called in the context of material serialization. It is useful for integrating into - bigger context of material exporters from various environment that want to take advantage of the RT Shader System. - Sub classes of this interface should override in case they need to write custom properties into the script context. - @param ser The material serializer instance. - @param subRenderState The sub render state instance to write down. - @param srcPass The source pass. - @param dstPass The generated shader based pass. - */ - virtual void writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, Pass* dstPass) {} - - /** Write the given sub-render state instance using the material serializer. - This method is called in the context of material serialization. It is useful for integrating into - bigger context of material exporters from various environment that want to take advantage of the RT Shader System. - Sub classes of this interface should override in case they need to write custom properties into the script context. - @param ser The material serializer instance. - @param subRenderState The sub render state instance to write down. - @param srcTextureUnit The source texture unit state. - @param dstTextureUnit The generated shader based texture unit state. - */ - virtual void writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, const TextureUnitState* srcTextureUnit, const TextureUnitState* dstTextureUnit) {} -protected: - /** Create instance implementation method. Each sub class of this interface - must implement this method in which it will allocate the specific sub class of - the SubRenderState. - */ - virtual SubRenderState* createInstanceImpl() = 0; - -// Attributes. -protected: - // List of all sub render states instances this factory created. - SubRenderStateSet mSubRenderStateList; -}; - -/** @} */ -/** @} */ - -} -} - -#endif - diff --git a/Components/RTShaderSystem/src/OgreShaderCGProgramWriter.cpp b/Components/RTShaderSystem/src/OgreShaderCGProgramWriter.cpp deleted file mode 100644 index f36f349c87e..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderCGProgramWriter.cpp +++ /dev/null @@ -1,179 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreShaderPrecompiledHeaders.h" - -namespace Ogre { -namespace RTShader { - -String CGProgramWriter::TargetLanguage = "hlsl"; - -//----------------------------------------------------------------------- -CGProgramWriter::CGProgramWriter() -{ - initializeStringMaps(); - - if(GpuProgramManager::getSingleton().isSyntaxSupported("ps_4_0")) - { - mGpuConstTypeMap[GCT_SAMPLER2DARRAY] = "Sampler2DArray"; - mGpuConstTypeMap[GCT_SAMPLER2DSHADOW] = "Sampler2DShadow"; - } -} - -//----------------------------------------------------------------------- -CGProgramWriter::~CGProgramWriter() -{ - -} - -//----------------------------------------------------------------------- -void CGProgramWriter::initializeStringMaps() -{ - mGpuConstTypeMap[GCT_FLOAT1] = "float"; - mGpuConstTypeMap[GCT_FLOAT2] = "float2"; - mGpuConstTypeMap[GCT_FLOAT3] = "float3"; - mGpuConstTypeMap[GCT_FLOAT4] = "float4"; - mGpuConstTypeMap[GCT_SAMPLER1D] = "sampler1D"; - mGpuConstTypeMap[GCT_SAMPLER2D] = "sampler2D"; - mGpuConstTypeMap[GCT_SAMPLER3D] = "sampler3D"; - mGpuConstTypeMap[GCT_SAMPLERCUBE] = "samplerCUBE"; - mGpuConstTypeMap[GCT_MATRIX_2X2] = "float2x2"; - mGpuConstTypeMap[GCT_MATRIX_2X3] = "float2x3"; - mGpuConstTypeMap[GCT_MATRIX_2X4] = "float2x4"; - mGpuConstTypeMap[GCT_MATRIX_3X2] = "float3x2"; - mGpuConstTypeMap[GCT_MATRIX_3X3] = "float3x3"; - mGpuConstTypeMap[GCT_MATRIX_3X4] = "float3x4"; - mGpuConstTypeMap[GCT_MATRIX_4X2] = "float4x2"; - mGpuConstTypeMap[GCT_MATRIX_4X3] = "float4x3"; - mGpuConstTypeMap[GCT_MATRIX_4X4] = "float4x4"; - mGpuConstTypeMap[GCT_INT1] = "int"; - mGpuConstTypeMap[GCT_INT2] = "int2"; - mGpuConstTypeMap[GCT_INT3] = "int3"; - mGpuConstTypeMap[GCT_INT4] = "int4"; - mGpuConstTypeMap[GCT_UINT1] = "uint"; - mGpuConstTypeMap[GCT_UINT2] = "uint2"; - mGpuConstTypeMap[GCT_UINT3] = "uint3"; - mGpuConstTypeMap[GCT_UINT4] = "uint4"; - - mParamSemanticMap[Parameter::SPS_FRONT_FACING] = "VFACE"; -} - -//----------------------------------------------------------------------- -void CGProgramWriter::writeSourceCode(std::ostream& os, Program* program) -{ - // Generate source code header. - writeProgramTitle(os, program); - os << std::endl; - - // Generate dependencies. - writeProgramDependencies(os, program); - os << std::endl; - - // Generate global variable code. - writeUniformParametersTitle(os, program); - os << std::endl; - - for (const auto& p : program->getParameters()) - { - p->isSampler() ? writeSamplerParameter(os, p) : writeParameter(os, p); - os << ";" << std::endl; - } - os << std::endl; - - - Function* curFunction = program->getMain(); - - writeFunctionTitle(os, curFunction); - writeFunctionDeclaration(os, curFunction); - - os << "{" << std::endl; - - // Write local parameters. - for (const auto& p : curFunction->getLocalParameters()) - { - os << "\t"; - writeParameter(os, p); - os << ";" << std::endl; - } - - for (const auto& a : curFunction->getAtomInstances()) - { - redirectGlobalWrites(os, a, curFunction->getInputParameters(), program->getParameters()); - writeAtomInstance(os, a); - } - - - os << "}" << std::endl; - os << std::endl; -} - -//----------------------------------------------------------------------- -void CGProgramWriter::writeFunctionParameter(std::ostream& os, ParameterPtr parameter) -{ - writeParameter(os, parameter); - os << " : "; - writeParameterSemantic(os, parameter); -} - -//----------------------------------------------------------------------- -void CGProgramWriter::writeFunctionDeclaration(std::ostream& os, Function* function) -{ - os << "void main(\n"; - - // Write input parameters. - for (const auto& p : function->getInputParameters()) - { - os << "\t in "; - writeFunctionParameter(os, p); - os << ",\n"; - } - - - // Write output parameters. - for (const auto& p : function->getOutputParameters()) - { - os << "\t out "; - writeFunctionParameter(os, p); - os << ",\n"; - } - - os.seekp(-2, std::ios_base::end); - - os << "\n)\n"; -} - -//----------------------------------------------------------------------- -void CGProgramWriter::writeAtomInstance(std::ostream& os, FunctionAtom* atom) -{ - os << std::endl << "\t"; - atom->writeSourceCode(os, getTargetLanguage()); - os << std::endl; -} - -} -} diff --git a/Components/RTShaderSystem/src/OgreShaderCGProgramWriter.h b/Components/RTShaderSystem/src/OgreShaderCGProgramWriter.h deleted file mode 100644 index bd84632c9d4..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderCGProgramWriter.h +++ /dev/null @@ -1,98 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ShaderProgramWriterCG_H__ -#define __ShaderProgramWriterCG_H__ - -#include "OgreShaderPrerequisites.h" -#include "OgreShaderProgramWriterManager.h" -#include "OgreShaderProgramWriter.h" -#include "OgreShaderParameter.h" - -namespace Ogre { -namespace RTShader { - - class Function; - class FunctionAtom; - class Program; - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** CG target language writer implementation. -@see ProgramWriter. -*/ -class CGProgramWriter : public ProgramWriter -{ - -// Interface. -public: - - /** Class constructor. - */ - CGProgramWriter(); - - /** Class destructor */ - virtual ~CGProgramWriter(); - - /** - @see ProgramWriter::writeSourceCode. - */ - void writeSourceCode(std::ostream& os, Program* program) override; - - /** - @see ProgramWriter::getTargetLanguage. - */ - const String& getTargetLanguage() const override { return TargetLanguage; } - - static String TargetLanguage; - -// Protected methods. -protected: - - /** Initialize string maps. */ - void initializeStringMaps(); - - /** Write a function parameter. */ - void writeFunctionParameter(std::ostream& os, ParameterPtr parameter); - - /** Write a function declaration. */ - void writeFunctionDeclaration(std::ostream& os, Function* function); - - /** Write function atom instance. */ - void writeAtomInstance(std::ostream& os, FunctionAtom* atom); -}; -/** @} */ -/** @} */ -} -} - -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderCookTorranceLighting.cpp b/Components/RTShaderSystem/src/OgreShaderCookTorranceLighting.cpp deleted file mode 100644 index 0ccefd2cbc1..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderCookTorranceLighting.cpp +++ /dev/null @@ -1,250 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT -#include "OgreShaderPrecompiledHeaders.h" -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS - -namespace Ogre -{ -namespace RTShader -{ - -/************************************************************************/ -/* */ -/************************************************************************/ -const String SRS_COOK_TORRANCE_LIGHTING = "CookTorranceLighting"; - -//----------------------------------------------------------------------- -CookTorranceLighting::CookTorranceLighting() : mLightCount(0), mMRMapSamplerIndex(0), mLtcLUT1SamplerIndex(-1) {} - -//----------------------------------------------------------------------- -const String& CookTorranceLighting::getType() const { return SRS_COOK_TORRANCE_LIGHTING; } -//----------------------------------------------------------------------- -bool CookTorranceLighting::createCpuSubPrograms(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* psMain = psProgram->getEntryPointFunction(); - - vsProgram->addDependency(FFP_LIB_TRANSFORM); - - psProgram->addDependency(FFP_LIB_TRANSFORM); - psProgram->addDependency(FFP_LIB_TEXTURING); - psProgram->addDependency("SGXLib_CookTorrance"); - psProgram->addPreprocessorDefines(StringUtil::format("LIGHT_COUNT=%d", mLightCount)); - - // Resolve texture coordinates. - auto vsOutTexcoord = vsMain->getOutputParameter(Parameter::SPC_TEXTURE_COORDINATE0, GCT_FLOAT2); // allow override by others - ParameterPtr vsInTexcoord; - if(!vsOutTexcoord) - { - vsInTexcoord = vsMain->resolveInputParameter(Parameter::SPC_TEXTURE_COORDINATE0, GCT_FLOAT2); - vsOutTexcoord = vsMain->resolveOutputParameter(Parameter::SPC_TEXTURE_COORDINATE0, GCT_FLOAT2); - } - auto psInTexcoord = psMain->resolveInputParameter(vsOutTexcoord); - - // resolve view position - auto vsInPosition = vsMain->getLocalParameter(Parameter::SPC_POSITION_OBJECT_SPACE); - if (!vsInPosition) - vsInPosition = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE); - auto vsOutViewPos = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_VIEW_SPACE); - auto viewPos = psMain->resolveInputParameter(vsOutViewPos); - auto worldViewMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLDVIEW_MATRIX); - - // Resolve normal. - auto viewNormal = psMain->getLocalParameter(Parameter::SPC_NORMAL_VIEW_SPACE); - ParameterPtr vsInNormal, vsOutNormal; - - if (!viewNormal) - { - // Resolve input vertex shader normal. - vsInNormal = vsMain->resolveInputParameter(Parameter::SPC_NORMAL_OBJECT_SPACE); - - // Resolve output vertex shader normal. - vsOutNormal = vsMain->resolveOutputParameter(Parameter::SPC_NORMAL_VIEW_SPACE); - - // Resolve input pixel shader normal. - viewNormal = psMain->resolveInputParameter(vsOutNormal); - } - - // resolve light params - auto outDiffuse = psMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE); - auto outSpecular = psMain->resolveLocalParameter(Parameter::SPC_COLOR_SPECULAR); - - // insert after texturing - auto vstage = vsMain->getStage(FFP_PS_COLOUR_BEGIN + 1); - auto fstage = psMain->getStage(FFP_PS_COLOUR_END + 50); - - // Forward texture coordinates - if(vsInTexcoord) - vstage.assign(vsInTexcoord, vsOutTexcoord); - vstage.callFunction(FFP_FUNC_TRANSFORM, worldViewMatrix, vsInPosition, vsOutViewPos); - - // transform normal in VS - if (vsOutNormal) - { - auto worldViewITMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_NORMAL_MATRIX); - vstage.callBuiltin("mul", worldViewITMatrix, vsInNormal, vsOutNormal); - } - - // add the lighting computation - auto mrparams = psMain->resolveLocalParameter(GCT_FLOAT2, "metalRoughness"); - if(!mMetalRoughnessMapName.empty()) - { - auto metalRoughnessSampler = - psProgram->resolveParameter(GCT_SAMPLER2D, "metalRoughnessSampler", mMRMapSamplerIndex); - auto mrSample = psMain->resolveLocalParameter(GCT_FLOAT4, "mrSample"); - // Roughness is stored in the 'g' channel, metallic is stored in the 'b' channel. - // This layout intentionally reserves the 'r' channel for (optional) occlusion map data - fstage.sampleTexture(metalRoughnessSampler, psInTexcoord, mrSample); - fstage.assign(In(mrSample).mask(Operand::OPM_YZ), mrparams); - } - else - { - auto specular = psProgram->resolveParameter(GpuProgramParameters::ACT_SURFACE_SPECULAR_COLOUR); - fstage.assign(In(specular).xy(), mrparams); - } - - auto sceneCol = psProgram->resolveParameter(GpuProgramParameters::ACT_DERIVED_SCENE_COLOUR); - auto litResult = psMain->resolveLocalParameter(GCT_FLOAT4, "litResult"); - auto diffuse = psProgram->resolveParameter(GpuProgramParameters::ACT_SURFACE_DIFFUSE_COLOUR); - auto baseColor = psMain->resolveLocalParameter(GCT_FLOAT3, "baseColor"); - - auto pixelParams = psMain->resolveLocalStructParameter("PixelParams", "pixel"); - - fstage.mul(In(diffuse).xyz(), In(outDiffuse).xyz(), baseColor); - fstage.assign(Vector3(0), Out(outDiffuse).xyz()); - fstage.assign(In(diffuse).w(), Out(outDiffuse).w()); // forward alpha - - fstage.callFunction("PBR_MakeParams", {In(baseColor), In(mrparams), InOut(pixelParams)}); - - fstage = psMain->getStage(FFP_PS_COLOUR_END + 60); // make gap to inject IBL here - if(mLightCount > 0) - { - auto lightPos = psProgram->resolveParameter(GpuProgramParameters::ACT_LIGHT_POSITION_VIEW_SPACE_ARRAY, mLightCount); - auto lightDiffuse = psProgram->resolveParameter(GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR_POWER_SCALED_ARRAY, mLightCount); - auto pointParams = psProgram->resolveParameter(GpuProgramParameters::ACT_LIGHT_ATTENUATION_ARRAY, mLightCount); - auto spotParams = psProgram->resolveParameter(GpuProgramParameters::ACT_SPOTLIGHT_PARAMS_ARRAY, mLightCount); - auto lightDirView = psProgram->resolveParameter(GpuProgramParameters::ACT_LIGHT_DIRECTION_VIEW_SPACE_ARRAY, mLightCount); - - std::vector params = {In(viewNormal), In(viewPos), In(sceneCol), In(lightPos), - In(lightDiffuse), In(pointParams), In(lightDirView), In(spotParams), - In(pixelParams), InOut(outDiffuse).xyz()}; - - if(mLtcLUT1SamplerIndex > -1) - { - auto ltcLUT1 = psProgram->resolveParameter(GCT_SAMPLER2D, "ltcLUT1Sampler", mLtcLUT1SamplerIndex); - auto ltcLUT2 = psProgram->resolveParameter(GCT_SAMPLER2D, "ltcLUT2Sampler", mLtcLUT1SamplerIndex + 1); - params.insert(params.begin(), {In(ltcLUT1), In(ltcLUT2)}); - psProgram->addPreprocessorDefines("HAVE_AREA_LIGHTS"); - } - - if (auto shadowFactor = psMain->getLocalParameter("lShadowFactor")) - { - params.insert(params.begin(), In(shadowFactor)); - } - - fstage.callFunction("PBR_Lights", params); - } - - return true; -} - -//----------------------------------------------------------------------- -void CookTorranceLighting::copyFrom(const SubRenderState& rhs) -{ - const CookTorranceLighting& rhsLighting = static_cast(rhs); - mMetalRoughnessMapName = rhsLighting.mMetalRoughnessMapName; - mLightCount = rhsLighting.mLightCount; -} - -//----------------------------------------------------------------------- -bool CookTorranceLighting::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) -{ - if (!srcPass->getLightingEnabled()) - return false; - - mLightCount = renderState->getLightCount(); - - if(renderState->haveAreaLights()) - mLtcLUT1SamplerIndex = ensureLtcLUTPresent(dstPass); - - if(mMetalRoughnessMapName.empty()) - return true; - - dstPass->createTextureUnitState(mMetalRoughnessMapName); - mMRMapSamplerIndex = dstPass->getNumTextureUnitStates() - 1; - - return true; -} - -bool CookTorranceLighting::setParameter(const String& name, const String& value) -{ - if (name == "texture" && !value.empty()) - { - mMetalRoughnessMapName = value; - return true; - } - - return false; -} - -//----------------------------------------------------------------------- -const String& CookTorranceLightingFactory::getType() const { return SRS_COOK_TORRANCE_LIGHTING; } - -//----------------------------------------------------------------------- -SubRenderState* CookTorranceLightingFactory::createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, - Pass* pass, SGScriptTranslator* translator) -{ - if (prop->name == "lighting_stage" && prop->values.size() >= 1) - { - String strValue; - AbstractNodeList::const_iterator it = prop->values.begin(); - - // Read light model type. - if ((*it++)->getString()!= "metal_roughness") - return NULL; - - auto subRenderState = createOrRetrieveInstance(translator); - - if(prop->values.size() < 3) - return subRenderState; - - if ((*it++)->getString() != "texture") - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - return subRenderState; - } - - if(!subRenderState->setParameter("texture", (*it++)->getString())) - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - - return subRenderState; - } - - return NULL; -} - -//----------------------------------------------------------------------- -void CookTorranceLightingFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, - Pass* dstPass) -{ - auto ctSubRenderState = static_cast(subRenderState); - - ser->writeAttribute(4, "lighting_stage"); - ser->writeValue("metal_roughness"); - if(ctSubRenderState->getMetalRoughnessMapName().empty()) - return; - ser->writeValue("texture"); - ser->writeValue(ctSubRenderState->getMetalRoughnessMapName()); -} - -//----------------------------------------------------------------------- -SubRenderState* CookTorranceLightingFactory::createInstanceImpl() { return OGRE_NEW CookTorranceLighting; } - -} // namespace RTShader -} // namespace Ogre - -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderCookTorranceLighting.h b/Components/RTShaderSystem/src/OgreShaderCookTorranceLighting.h deleted file mode 100644 index f5db9c4623f..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderCookTorranceLighting.h +++ /dev/null @@ -1,76 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT -#ifndef _ShaderCookTorranceLighting_ -#define _ShaderCookTorranceLighting_ - -#include "OgreShaderPrerequisites.h" -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS -#include "OgreShaderExPerPixelLighting.h" -#include "OgreLight.h" -#include "OgreCommon.h" -#include "OgreShaderFFPRenderState.h" - -namespace Ogre -{ -namespace RTShader -{ - -/** \addtogroup Optional - * @{ - */ -/** \addtogroup RTShader - * @{ - */ - -class CookTorranceLighting : public SubRenderState -{ -public: - CookTorranceLighting(); - - const String& getType() const override; - - int getExecutionOrder() const override { return FFP_LIGHTING; } - - void copyFrom(const SubRenderState& rhs) override; - - bool preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) override; - - /** - Return the metallic-roughness map texture name. - */ - const String& getMetalRoughnessMapName() const { return mMetalRoughnessMapName; } - - bool setParameter(const String& name, const String& value) override; - - bool createCpuSubPrograms(ProgramSet* programSet) override; - -private: - String mMetalRoughnessMapName; - int mLightCount; - uint8 mMRMapSamplerIndex; - int8 mLtcLUT1SamplerIndex; -}; - -class CookTorranceLightingFactory : public SubRenderStateFactory -{ -public: - const String& getType() const override; - - SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, - SGScriptTranslator* translator) override; - void writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, Pass* dstPass) override; - -protected: - SubRenderState* createInstanceImpl() override; -}; - -/** @} */ -/** @} */ - -} // namespace RTShader -} // namespace Ogre - -#endif -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderExDualQuaternionSkinning.cpp b/Components/RTShaderSystem/src/OgreShaderExDualQuaternionSkinning.cpp deleted file mode 100644 index 5e3bf456bbb..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExDualQuaternionSkinning.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreShaderPrecompiledHeaders.h" - -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS - -#define SGX_LIB_DUAL_QUATERNION "SGXLib_DualQuaternion" -#define SGX_FUNC_CALCULATE_BLEND_POSITION "SGX_CalculateBlendPosition" -#define SGX_FUNC_CALCULATE_BLEND_NORMAL "SGX_CalculateBlendNormal" -#define SGX_FUNC_ADJOINT_TRANSPOSE_MATRIX "SGX_AdjointTransposeMatrix" - -namespace Ogre { - -namespace RTShader { - -/************************************************************************/ -/* */ -/************************************************************************/ -bool DualQuaternionSkinning::resolveParameters(Program* vsProgram) -{ - Function* vsMain = vsProgram->getEntryPointFunction(); - - mParamInWorldMatrices = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLD_DUALQUATERNION_ARRAY_2x4, mBoneCount); - mParamBlendDQ = vsMain->resolveLocalParameter(GCT_MATRIX_2X4, "blendDQ"); - - if(mScalingShearingSupport) - { - mParamInScaleShearMatrices = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLD_SCALE_SHEAR_MATRIX_ARRAY_3x4, mBoneCount); - mParamBlendS = vsMain->resolveLocalParameter(GCT_MATRIX_3X4, "blendS"); - mParamTempFloat3x3 = vsMain->resolveLocalParameter(GCT_MATRIX_3X3, "TempVal3x3"); - } - return true; -} -//----------------------------------------------------------------------- -void DualQuaternionSkinning::addPositionCalculations(const FunctionStageRef& stage) -{ - if (mScalingShearingSupport) - { - // Construct a scaling and shearing matrix based on the blend weights - stage.callFunction("blendBonesMat3x4", {In(mParamInScaleShearMatrices), In(mParamInIndices), - In(mParamInWeights), Out(mParamBlendS)}); - // Transform the position based by the scaling and shearing matrix - stage.callFunction(FFP_FUNC_TRANSFORM, mParamBlendS, mParamInPosition, Out(mParamInPosition).xyz()); - } - - // Calculate the resultant dual quaternion based on the weights given - stage.callFunction("blendBonesDQ", - {In(mParamInWorldMatrices), In(mParamInIndices), In(mParamInWeights), Out(mParamBlendDQ)}); - - // Calculate the blend position - stage.callFunction(SGX_FUNC_CALCULATE_BLEND_POSITION, In(mParamInPosition).xyz(), mParamBlendDQ, mParamInPosition); -} - -//----------------------------------------------------------------------- -void DualQuaternionSkinning::addNormalRelatedCalculations(const FunctionStageRef& stage) -{ - if (mScalingShearingSupport) - { - // Calculate the adjoint transpose of the blended scaling and shearing matrix - stage.callFunction(SGX_FUNC_ADJOINT_TRANSPOSE_MATRIX, mParamBlendS, mParamTempFloat3x3); - // Transform the normal by the adjoint transpose of the blended scaling and shearing matrix - stage.callBuiltin("mul", mParamTempFloat3x3, mParamInNormal, mParamInNormal); - // Need to normalize again after transforming the normal - stage.callBuiltin("normalize", mParamInNormal, mParamInNormal); - } - // Transform the normal according to the dual quaternion - stage.callFunction(SGX_FUNC_CALCULATE_BLEND_NORMAL, mParamInNormal, mParamBlendDQ, mParamInNormal); -} -} -} - -#endif - - - diff --git a/Components/RTShaderSystem/src/OgreShaderExDualQuaternionSkinning.h b/Components/RTShaderSystem/src/OgreShaderExDualQuaternionSkinning.h deleted file mode 100644 index f4714b72cd9..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExDualQuaternionSkinning.h +++ /dev/null @@ -1,68 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderExDualQuaternionSkinning_ -#define _ShaderExDualQuaternionSkinning_ - -#include "OgreShaderPrerequisites.h" - -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS -#include "OgreShaderExHardwareSkinningTechnique.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** Implement a sub render state which performs dual quaternion hardware skinning. - This sub render state uses bone matrices converted to dual quaternions and adds calculations - to transform the points and normals using their associated dual quaternions. -*/ -class DualQuaternionSkinning : public HardwareSkinningTechnique -{ - bool resolveParameters(Program* vsProgram) override; - void addPositionCalculations(const FunctionStageRef& stage) override; - void addNormalRelatedCalculations(const FunctionStageRef& stage) override; - - UniformParameterPtr mParamInScaleShearMatrices; - ParameterPtr mParamBlendS; - ParameterPtr mParamBlendDQ; - - ParameterPtr mParamTempFloat3x3; - ParameterPtr mParamTempFloat3x4; -}; - -} // namespace RTShader -} // namespace Ogre - -#endif // RTSHADER_SYSTEM_BUILD_EXT_SHADERS -#endif // _ShaderExDualQuaternionSkinning_ - diff --git a/Components/RTShaderSystem/src/OgreShaderExGBuffer.cpp b/Components/RTShaderSystem/src/OgreShaderExGBuffer.cpp deleted file mode 100644 index bba8339ba2a..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExGBuffer.cpp +++ /dev/null @@ -1,263 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderPrecompiledHeaders.h" -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS - -namespace Ogre -{ -namespace RTShader -{ - -/************************************************************************/ -/* */ -/************************************************************************/ -String GBuffer::Type = "GBuffer"; -const String SRS_GBUFFER = "GBuffer"; - -//----------------------------------------------------------------------- -const String& GBuffer::getType() const { return SRS_GBUFFER; } - -//----------------------------------------------------------------------- -int GBuffer::getExecutionOrder() const { return FFP_LIGHTING; } - -bool GBuffer::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) -{ - srcPass->getParent()->getParent()->setReceiveShadows(false); - return true; -} - -static GBuffer::TargetLayout translate(const String& val) -{ - if(val == "depth") - return GBuffer::TL_DEPTH; - if(val == "normal") - return GBuffer::TL_NORMAL; - if(val == "viewpos") - return GBuffer::TL_VIEWPOS; - if(val == "normal_viewdepth") - return GBuffer::TL_NORMAL_VIEWDEPTH; - return GBuffer::TL_DIFFUSE_SPECULAR; -} - -void GBuffer::setParameter(const String& name, const Any& value) -{ - if(name == "target_buffers") - { - auto buffers = any_cast(value); - mOutBuffers.clear(); - - for(const auto& buf : buffers) - mOutBuffers.push_back(translate(buf)); - return; - } - SubRenderState::setParameter(name, value); -} - -//----------------------------------------------------------------------- -bool GBuffer::createCpuSubPrograms(ProgramSet* programSet) -{ - Function* psMain = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM)->getMain(); - - for(size_t i = 0; i < mOutBuffers.size(); i++) - { - auto out = - psMain->resolveOutputParameter(i == 0 ? Parameter::SPC_COLOR_DIFFUSE : Parameter::SPC_COLOR_SPECULAR); - - switch(mOutBuffers[i]) - { - case TL_DEPTH: - addDepthInvocations(programSet, out); - break; - case TL_NORMAL_VIEWDEPTH: - addViewPosInvocations(programSet, out, true); - OGRE_FALLTHROUGH; - case TL_NORMAL: - addNormalInvocations(programSet, out); - break; - case TL_VIEWPOS: - addViewPosInvocations(programSet, out, false); - break; - case TL_DIFFUSE_SPECULAR: - addDiffuseSpecularInvocations(programSet, out); - break; - default: - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "unsupported TargetLayout"); - } - } - - return true; -} - -void GBuffer::addViewPosInvocations(ProgramSet* programSet, const ParameterPtr& out, bool depthOnly) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* vsMain = vsProgram->getMain(); - Function* psMain = psProgram->getMain(); - - // vertex shader - auto vstage = vsMain->getStage(FFP_VS_POST_PROCESS); - auto vsInPosition = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE); - auto vsOutPos = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_VIEW_SPACE); - auto worldViewMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLDVIEW_MATRIX); - vstage.callFunction(FFP_FUNC_TRANSFORM, worldViewMatrix, vsInPosition, vsOutPos); - - // fragment shader - auto fstage = psMain->getStage(FFP_PS_COLOUR_END); - auto viewPos = psMain->resolveInputParameter(vsOutPos); - - if(depthOnly) - { - auto far = psProgram->resolveParameter(GpuProgramParameters::ACT_FAR_CLIP_DISTANCE); - fstage.callBuiltin("length", viewPos, Out(out).w()); - fstage.div(In(out).w(), far, Out(out).w()); - return; - } - - fstage.assign(viewPos, Out(out).xyz()); - fstage.assign(0, Out(out).w()); -} - -void GBuffer::addDepthInvocations(ProgramSet* programSet, const ParameterPtr& out) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* vsMain = vsProgram->getMain(); - Function* psMain = psProgram->getMain(); - - // vertex shader - auto vsOutPos = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_PROJECTIVE_SPACE); - - bool isD3D9 = ShaderGenerator::getSingleton().getTargetLanguage() == "hlsl" && - !GpuProgramManager::getSingleton().isSyntaxSupported("vs_4_0_level_9_1"); - - if (isD3D9) - { - auto vstage = vsMain->getStage(FFP_VS_POST_PROCESS); - auto vsPos = vsMain->resolveOutputParameter(Parameter::SPC_UNKNOWN, GCT_FLOAT4); - vstage.assign(vsOutPos, vsPos); - std::swap(vsOutPos, vsPos); - } - - // fragment shader - auto fstage = psMain->getStage(FFP_PS_COLOUR_END); - auto viewPos = psMain->resolveInputParameter(vsOutPos); - - fstage.assign(In(viewPos).z(), Out(out).x()); - - if (isD3D9) - { - fstage.div(In(out).x(), In(viewPos).w(), Out(out).x()); - } -} - -void GBuffer::addNormalInvocations(ProgramSet* programSet, const ParameterPtr& out) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Function* vsMain = vsProgram->getMain(); - Function* psMain = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM)->getMain(); - - auto fstage = psMain->getStage(FFP_PS_COLOUR_END); - auto viewNormal = psMain->getLocalParameter(Parameter::SPC_NORMAL_VIEW_SPACE); - if(!viewNormal) - { - // compute vertex shader normal - auto vstage = vsMain->getStage(FFP_VS_LIGHTING); - auto vsInNormal = vsMain->resolveInputParameter(Parameter::SPC_NORMAL_OBJECT_SPACE); - auto vsOutNormal = vsMain->resolveOutputParameter(Parameter::SPC_NORMAL_VIEW_SPACE); - auto worldViewITMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_NORMAL_MATRIX); - vstage.callBuiltin("mul", worldViewITMatrix, vsInNormal, vsOutNormal); - vstage.callBuiltin("normalize", vsOutNormal, vsOutNormal); - - // pass through - viewNormal = psMain->resolveInputParameter(vsOutNormal); - } - fstage.assign(viewNormal, Out(out).xyz()); -} - -void GBuffer::addDiffuseSpecularInvocations(ProgramSet* programSet, const ParameterPtr& out) -{ - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* psMain = psProgram->getMain(); - - // set diffuse - TODO vertex color tracking - auto diffuse = psProgram->resolveParameter(GpuProgramParameters::ACT_SURFACE_DIFFUSE_COLOUR); - psMain->getStage(FFP_PS_COLOUR_BEGIN + 1).assign(diffuse, out); - - // set shininess - auto surfaceShininess = psProgram->resolveParameter(GpuProgramParameters::ACT_SURFACE_SHININESS); - psMain->getStage(FFP_PS_COLOUR_END).assign(surfaceShininess, Out(out).w()); -} - -//----------------------------------------------------------------------- -void GBuffer::copyFrom(const SubRenderState& rhs) -{ - const GBuffer& rhsTransform = static_cast(rhs); - mOutBuffers = rhsTransform.mOutBuffers; -} - -//----------------------------------------------------------------------- -const String& GBufferFactory::getType() const { return SRS_GBUFFER; } - -//----------------------------------------------------------------------- -SubRenderState* GBufferFactory::createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, - SGScriptTranslator* translator) -{ - if (prop->name != "lighting_stage" || prop->values.size() < 2) - return NULL; - - auto it = prop->values.begin(); - if((*it++)->getString() != "gbuffer") - return NULL; - - StringVector targets; - targets.push_back((*it++)->getString()); - - if(it != prop->values.end()) - targets.push_back((*it++)->getString()); - - auto ret = static_cast(createOrRetrieveInstance(translator)); - ret->setParameter("target_buffers", targets); - return ret; -} - -//----------------------------------------------------------------------- -void GBufferFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, - Pass* dstPass) -{ - ser->writeAttribute(4, "lighting_stage"); - ser->writeValue("gbuffer"); - ser->writeValue("depth"); -} - -//----------------------------------------------------------------------- -SubRenderState* GBufferFactory::createInstanceImpl() { return OGRE_NEW GBuffer; } - -} // namespace RTShader -} // namespace Ogre - -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderExGBuffer.h b/Components/RTShaderSystem/src/OgreShaderExGBuffer.h deleted file mode 100644 index 37680092125..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExGBuffer.h +++ /dev/null @@ -1,136 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderGBuffer_ -#define _ShaderGBuffer_ - -#include "OgreShaderPrerequisites.h" -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS -#include "OgreShaderParameter.h" -#include "OgreShaderSubRenderState.h" - -namespace Ogre -{ -namespace RTShader -{ - -/** \addtogroup Optional - * @{ - */ -/** \addtogroup RTShader - * @{ - */ - -/** Transform sub render state implementation of writing to GBuffers - */ -class GBuffer : public SubRenderState -{ - - // Interface. -public: - enum TargetLayout - { - TL_DEPTH, - TL_NORMAL, - TL_VIEWPOS, - TL_NORMAL_VIEWDEPTH, - TL_DIFFUSE_SPECULAR, - }; - typedef std::vector TargetBuffers; - - /** - @see SubRenderState::getType. - */ - const String& getType() const override; - - /** - @see SubRenderState::getExecutionOrder. - */ - int getExecutionOrder() const override; - - /** - @see SubRenderState::copyFrom. - */ - void copyFrom(const SubRenderState& rhs) override; - - /** - @see SubRenderState::createCpuSubPrograms. - */ - bool createCpuSubPrograms(ProgramSet* programSet) override; - - bool preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) override; - - void setParameter(const String& name, const Any& value) override; - - static String Type; - -private: - static void addViewPosInvocations(ProgramSet* programSet, const ParameterPtr& out, bool depthOnly); - static void addDepthInvocations(ProgramSet* programSet, const ParameterPtr& out); - static void addNormalInvocations(ProgramSet* programSet, const ParameterPtr& out) ; - static void addDiffuseSpecularInvocations(ProgramSet* programSet, const ParameterPtr& out); - - TargetBuffers mOutBuffers; -}; - -/** -A factory that enables creation of GBuffer instances. -@remarks Sub class of SubRenderStateFactory -*/ -class GBufferFactory : public SubRenderStateFactory -{ -public: - /** - @see SubRenderStateFactory::getType. - */ - const String& getType() const override; - - /** - @see SubRenderStateFactory::createInstance. - */ - SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, - SGScriptTranslator* translator) override; - - /** - @see SubRenderStateFactory::writeInstance. - */ - void writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, Pass* dstPass) override; - -protected: - /** - @see SubRenderStateFactory::createInstanceImpl. - */ - SubRenderState* createInstanceImpl() override; -}; - -/** @} */ -/** @} */ - -} // namespace RTShader -} // namespace Ogre - -#endif -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderExHardwareSkinning.cpp b/Components/RTShaderSystem/src/OgreShaderExHardwareSkinning.cpp deleted file mode 100644 index eddabdc2150..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExHardwareSkinning.cpp +++ /dev/null @@ -1,574 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderPrecompiledHeaders.h" - -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS - -#define HS_DATA_BIND_NAME "HS_SRS_DATA" - - -namespace Ogre { -template<> RTShader::HardwareSkinningFactory* Singleton::msSingleton = 0; - -namespace RTShader { - -HardwareSkinningFactory* HardwareSkinningFactory::getSingletonPtr(void) -{ - return msSingleton; -} -HardwareSkinningFactory& HardwareSkinningFactory::getSingleton(void) -{ - assert( msSingleton ); return ( *msSingleton ); -} - -String HardwareSkinning::Type = "SGX_HardwareSkinning"; -const String SRS_HARDWARE_SKINNING = "SGX_HardwareSkinning"; - -ushort HardwareSkinningFactory::mMaxCalculableBoneCount = 70; - -#define HS_MAX_WEIGHT_COUNT 4 - -/// A set of custom shadow caster materials -static MaterialPtr mCustomShadowCasterMaterialsLinear[HS_MAX_WEIGHT_COUNT]; -static MaterialPtr mCustomShadowCasterMaterialsDualQuaternion[HS_MAX_WEIGHT_COUNT]; - -/// A set of custom shadow receiver materials -static MaterialPtr mCustomShadowReceiverMaterialsLinear[HS_MAX_WEIGHT_COUNT]; -static MaterialPtr mCustomShadowReceiverMaterialsDualQuaternion[HS_MAX_WEIGHT_COUNT]; - -/************************************************************************/ -/* */ -/************************************************************************/ -HardwareSkinning::HardwareSkinning() : - mCreator(NULL), - mSkinningType(ST_LINEAR) -{ -} - -//----------------------------------------------------------------------- -const String& HardwareSkinning::getType() const -{ - return SRS_HARDWARE_SKINNING; -} - -//----------------------------------------------------------------------- -int HardwareSkinning::getExecutionOrder() const -{ - return FFP_TRANSFORM; -} - -//----------------------------------------------------------------------- -bool HardwareSkinning::setParameter(const String& name, const String& value) -{ - if (name == "type") - { - if (value == "dual_quaternion") - { - mSkinningType = ST_DUAL_QUATERNION; - if (!mDualQuat) - { - mDualQuat.reset(OGRE_NEW DualQuaternionSkinning); - } - - mActiveTechnique = mDualQuat; - return true; - } - else if(value == "linear") - { - mSkinningType = ST_LINEAR; - if (!mLinear) - { - mLinear.reset(OGRE_NEW LinearSkinning); - } - - mActiveTechnique = mLinear; - return true; - } - } - else if(mActiveTechnique) - { - return mActiveTechnique->setParameter(name, value); - } - return false; -} -//----------------------------------------------------------------------- -ushort HardwareSkinning::getBoneCount() -{ - assert(mActiveTechnique); - return mActiveTechnique->getBoneCount(); -} - -//----------------------------------------------------------------------- -ushort HardwareSkinning::getWeightCount() -{ - assert(mActiveTechnique); - return mActiveTechnique->getWeightCount(); -} - -//----------------------------------------------------------------------- -SkinningType HardwareSkinning::getSkinningType() -{ - assert(mActiveTechnique); - return mSkinningType; -} - -//----------------------------------------------------------------------- -bool HardwareSkinning::hasCorrectAntipodalityHandling() -{ - assert(mActiveTechnique); - return mActiveTechnique->hasCorrectAntipodalityHandling(); -} - -//----------------------------------------------------------------------- -bool HardwareSkinning::hasScalingShearingSupport() -{ - assert(mActiveTechnique); - return mActiveTechnique->hasScalingShearingSupport(); -} - -//----------------------------------------------------------------------- -void HardwareSkinning::copyFrom(const SubRenderState& rhs) -{ - const HardwareSkinning& hardSkin = static_cast(rhs); - - mDualQuat = hardSkin.mDualQuat; - mLinear = hardSkin.mLinear; - mActiveTechnique = hardSkin.mActiveTechnique; - - mCreator = hardSkin.mCreator; - mSkinningType = hardSkin.mSkinningType; -} - -//----------------------------------------------------------------------- -bool HardwareSkinning::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) -{ - bool isValid = true; - Technique* pFirstTech = srcPass->getParent()->getParent()->getTechnique(0); - const Any& hsAny = pFirstTech->getUserObjectBindings().getUserAny(HS_DATA_BIND_NAME); - - if (hsAny.has_value()) - { - HardwareSkinning::SkinningData pData = any_cast(hsAny); - isValid = pData.isValid; - - //If the skinning data is being passed through the material, we need to create an instance of the appropriate - //skinning type and set its parameters here - setParameter("type", pData.skinningType == ST_LINEAR ? "linear" : "dual_quaternion"); - mActiveTechnique->setHardwareSkinningParam(pData.maxBoneCount, pData.maxWeightCount, - pData.correctAntipodalityHandling, pData.scalingShearingSupport); - } - - //If there is no associated technique, default to linear skinning as a pass-through - if(!mActiveTechnique) - { - setParameter("type", "linear"); - } - - int boneCount = mActiveTechnique->getBoneCount(); - int weightCount = mActiveTechnique->getWeightCount(); - - bool doBoneCalculations = isValid && - (boneCount != 0) && (boneCount <= 256) && - (weightCount != 0) && (weightCount <= 4) && - ((mCreator == NULL) || (boneCount <= mCreator->getMaxCalculableBoneCount())); - - // This requires GLES3.0 - if (ShaderGenerator::getSingleton().getTargetLanguage() == "glsles" && - !GpuProgramManager::getSingleton().isSyntaxSupported("glsl300es")) - doBoneCalculations = false; - - mActiveTechnique->setDoBoneCalculations(doBoneCalculations); - mActiveTechnique->setDoLightCalculations(srcPass->getLightingEnabled()); - - if ((doBoneCalculations) && (mCreator)) - { - //update the receiver and caster materials - if (!dstPass->getParent()->getShadowCasterMaterial()) - { - auto casterMat = mCreator->getCustomShadowCasterMaterial(mSkinningType, weightCount - 1); - - // if the caster material itsefl uses RTSS hardware skinning - if(casterMat.get() != dstPass->getParent()->getParent()) - dstPass->getParent()->setShadowCasterMaterial(casterMat); - } - - if (!dstPass->getParent()->getShadowReceiverMaterial()) - { - dstPass->getParent()->setShadowReceiverMaterial( - mCreator->getCustomShadowReceiverMaterial(mSkinningType, weightCount - 1)); - } - } - - return true; -} - -//----------------------------------------------------------------------- -bool HardwareSkinning::resolveParameters(ProgramSet* programSet) -{ - assert(mActiveTechnique); - return mActiveTechnique->resolveParameters(programSet); -} - -//----------------------------------------------------------------------- -bool HardwareSkinning::resolveDependencies(ProgramSet* programSet) -{ - assert(mActiveTechnique); - return mActiveTechnique->resolveDependencies(programSet); -} - -//----------------------------------------------------------------------- -bool HardwareSkinning::addFunctionInvocations(ProgramSet* programSet) -{ - assert(mActiveTechnique); - return mActiveTechnique->addFunctionInvocations(programSet); -} - -//----------------------------------------------------------------------- -HardwareSkinningFactory::HardwareSkinningFactory() -{ - -} - -HardwareSkinningFactory::~HardwareSkinningFactory() {} - -//----------------------------------------------------------------------- -const String& HardwareSkinningFactory::getType() const -{ - return SRS_HARDWARE_SKINNING; -} - -//----------------------------------------------------------------------- -SubRenderState* HardwareSkinningFactory::createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) -{ - if (prop->name == "hardware_skinning") - { - String skinningType = "linear"; - - if(prop->values.size() < 2) - return NULL; - - std::map params; - AbstractNodeList::iterator it = prop->values.begin(); - params["max_bone_count"] = (*it)->getString(); - ++it; - params["weight_count"] = (*it)->getString(); - - if(prop->values.size() >= 3) - { - ++it; - skinningType = (*it)->getString(); - } - - if(skinningType != "dual_quaternion" && skinningType != "linear") - return NULL; - - if(prop->values.size() >= 5) - { - ++it; - params["correct_antipodality"] = (*it)->getString(); - ++it; - params["scale_shearing"] = (*it)->getString(); - } - - //create and update the hardware skinning sub render state - SubRenderState* subRenderState = createOrRetrieveInstance(translator); - subRenderState->setParameter("type", skinningType); - - for(const auto& p : params) - { - if(!subRenderState->setParameter(p.first, p.second)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, p.second); - } - } - - return subRenderState; - } - - return NULL; -} - -//----------------------------------------------------------------------- -void HardwareSkinningFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, - Pass* srcPass, Pass* dstPass) -{ - ser->writeAttribute(4, "hardware_skinning"); - - HardwareSkinning* hardSkinSrs = static_cast(subRenderState); - ser->writeValue(StringConverter::toString(hardSkinSrs->getBoneCount())); - ser->writeValue(StringConverter::toString(hardSkinSrs->getWeightCount())); - - //Correct antipodality handling and scaling and shearing support are only really valid for dual quaternion skinning - if(hardSkinSrs->getSkinningType() == ST_DUAL_QUATERNION) - { - ser->writeValue("dual_quaternion"); - ser->writeValue(StringConverter::toString(hardSkinSrs->hasCorrectAntipodalityHandling())); - ser->writeValue(StringConverter::toString(hardSkinSrs->hasScalingShearingSupport())); - } -} - -//----------------------------------------------------------------------- -SubRenderState* HardwareSkinningFactory::createInstanceImpl() -{ - HardwareSkinning* pSkin = OGRE_NEW HardwareSkinning; - - pSkin->_setCreator(this); - return pSkin; -} - -//----------------------------------------------------------------------- -void HardwareSkinningFactory::setCustomShadowCasterMaterials(const SkinningType skinningType, const MaterialPtr& caster1Weight, const MaterialPtr& caster2Weight, - const MaterialPtr& caster3Weight, const MaterialPtr& caster4Weight) -{ - if(skinningType == ST_DUAL_QUATERNION) - { - mCustomShadowCasterMaterialsDualQuaternion[0] = caster1Weight; - mCustomShadowCasterMaterialsDualQuaternion[1] = caster2Weight; - mCustomShadowCasterMaterialsDualQuaternion[2] = caster3Weight; - mCustomShadowCasterMaterialsDualQuaternion[3] = caster4Weight; - } - else //if(skinningType == ST_LINEAR) - { - mCustomShadowCasterMaterialsLinear[0] = caster1Weight; - mCustomShadowCasterMaterialsLinear[1] = caster2Weight; - mCustomShadowCasterMaterialsLinear[2] = caster3Weight; - mCustomShadowCasterMaterialsLinear[3] = caster4Weight; - } -} - -//----------------------------------------------------------------------- -void HardwareSkinningFactory::setCustomShadowReceiverMaterials(const SkinningType skinningType, const MaterialPtr& receiver1Weight, const MaterialPtr& receiver2Weight, - const MaterialPtr& receiver3Weight, const MaterialPtr& receiver4Weight) -{ - if(skinningType == ST_DUAL_QUATERNION) - { - mCustomShadowReceiverMaterialsDualQuaternion[0] = receiver1Weight; - mCustomShadowReceiverMaterialsDualQuaternion[1] = receiver2Weight; - mCustomShadowReceiverMaterialsDualQuaternion[2] = receiver3Weight; - mCustomShadowReceiverMaterialsDualQuaternion[3] = receiver4Weight; - } - else //if(skinningType == ST_LINEAR) - { - mCustomShadowReceiverMaterialsLinear[0] = receiver1Weight; - mCustomShadowReceiverMaterialsLinear[1] = receiver2Weight; - mCustomShadowReceiverMaterialsLinear[2] = receiver3Weight; - mCustomShadowReceiverMaterialsLinear[3] = receiver4Weight; - } -} - -//----------------------------------------------------------------------- -const MaterialPtr& HardwareSkinningFactory::getCustomShadowCasterMaterial(const SkinningType skinningType, ushort index) -{ - assert(index < HS_MAX_WEIGHT_COUNT); - - if(skinningType == ST_DUAL_QUATERNION) - { - return mCustomShadowCasterMaterialsDualQuaternion[index]; - } - else //if(skinningType = ST_LINEAR) - { - return mCustomShadowCasterMaterialsLinear[index]; - } -} - -//----------------------------------------------------------------------- -const MaterialPtr& HardwareSkinningFactory::getCustomShadowReceiverMaterial(const SkinningType skinningType, ushort index) -{ - assert(index < HS_MAX_WEIGHT_COUNT); - - if(skinningType == ST_DUAL_QUATERNION) - { - return mCustomShadowReceiverMaterialsDualQuaternion[index]; - } - else //if(skinningType == ST_LINEAR) - { - return mCustomShadowReceiverMaterialsLinear[index]; - } -} - -//---------------------------------------------------------------------- -/** - @brief - Extracts the maximum amount of bones and weights used in an specific subentity of given entity. - - @param pEntity The entity from which the information needs to be extracted. - @param subEntityIndex The index of subentity from which the information needs to be extracted. - @param boneCount The maximum number of bones used by the entity. - @param weightCount The maximum number of weights used by the entity. - @return Returns true if the entity can use HS. False if not. -*/ -static bool extractSkeletonData(const Entity* pEntity, size_t subEntityIndex, ushort& boneCount, ushort& weightCount) -{ - bool isValidData = false; - boneCount = 0; - weightCount = 0; - - //Check if we have pose animation which the HS sub render state does not - //know how to handle - bool hasVertexAnim = pEntity->getMesh()->hasVertexAnimation(); - - //gather data on the skeleton - if (!hasVertexAnim && pEntity->hasSkeleton()) - { - //get weights count - const MeshPtr& pMesh = pEntity->getMesh(); - - RenderOperation ro; - SubMesh* pSubMesh = pMesh->getSubMesh(subEntityIndex); - pSubMesh->_getRenderOperation(ro,0); - - //get the largest bone assignment - boneCount = ushort(std::max(pMesh->sharedBlendIndexToBoneIndexMap.size(), pSubMesh->blendIndexToBoneIndexMap.size())); - - //go over vertex deceleration - //check that they have blend indices and blend weights - const VertexElement* pDeclWeights = ro.vertexData->vertexDeclaration->findElementBySemantic(VES_BLEND_WEIGHTS,0); - const VertexElement* pDeclIndexes = ro.vertexData->vertexDeclaration->findElementBySemantic(VES_BLEND_INDICES,0); - if ((pDeclWeights != NULL) && (pDeclIndexes != NULL)) - { - isValidData = true; - switch (pDeclWeights->getType()) - { - case VET_FLOAT1: - weightCount = 1; - break; - case VET_USHORT2_NORM: - case VET_FLOAT2: - weightCount = 2; - break; - case VET_FLOAT3: - weightCount = 3; - break; - case VET_USHORT4_NORM: - case VET_UBYTE4_NORM: - case VET_FLOAT4: - weightCount = 4; - break; - default: - isValidData = false; - break; - } - } - } - return isValidData; -} - -/** - @brief - Updates an entity's the skeleton data onto one of it's materials. - - @param pMaterial The material to update with the information. - @param isValid Tells if the material can be used with HS. - @param boneCount The maximum number of bones used by the entity. - @param weightCount The maximum number of weights used by the entity. - @return Returns true if the data was updated on the material. False if not. -*/ -static bool imprintSkeletonData(const MaterialPtr& pMaterial, bool isVaild, - ushort boneCount, ushort weightCount, SkinningType skinningType, bool correctAntidpodalityHandling, bool scalingShearingSupport) -{ - bool isUpdated = false; - if (pMaterial->getNumTechniques() > 0) - { - HardwareSkinning::SkinningData data; - - //get the previous skinning data if available - UserObjectBindings& binding = pMaterial->getTechnique(0)->getUserObjectBindings(); - const Any& hsAny = binding.getUserAny(HS_DATA_BIND_NAME); - if (hsAny.has_value()) - { - data = any_cast(hsAny); - } - - //check if we need to update the data - if (((data.isValid == true) && (isVaild == false)) || - (data.maxBoneCount < boneCount) || - (data.maxWeightCount < weightCount)) - { - //update the data - isUpdated = true; - data.isValid &= isVaild; - data.maxBoneCount = std::max(data.maxBoneCount, boneCount); - data.maxWeightCount = std::max(data.maxWeightCount, weightCount); - data.skinningType = skinningType; - data.correctAntipodalityHandling = correctAntidpodalityHandling; - data.scalingShearingSupport = scalingShearingSupport; - - //update the data in the material and invalidate it in the RTShader system - //do it will be regenerated - binding.setUserAny(HS_DATA_BIND_NAME, data); - - size_t schemeCount = ShaderGenerator::getSingleton().getRTShaderSchemeCount(); - for(size_t i = 0 ; i < schemeCount ; ++i) - { - //invalidate the material so it will be recreated with the correct - //amount of bones and weights - const String& schemeName = ShaderGenerator::getSingleton().getRTShaderScheme(i); - ShaderGenerator::getSingleton().invalidateMaterial(schemeName, *pMaterial); - } - - } - } - return isUpdated; - -} - -void HardwareSkinningFactory::prepareEntityForSkinning(const Entity* pEntity, SkinningType skinningType, - bool correctAntidpodalityHandling, bool shearScale) -{ - // This requires GLES3.0 - if (ShaderGenerator::getSingleton().getTargetLanguage() == "glsles" && - !GpuProgramManager::getSingleton().isSyntaxSupported("glsl300es")) - return; - - if (pEntity != NULL) - { - size_t lodLevels = pEntity->getNumManualLodLevels() + 1; - for(size_t indexLod = 0 ; indexLod < lodLevels ; ++indexLod) - { - const Entity* pCurEntity = pEntity; - if (indexLod > 0) pCurEntity = pEntity->getManualLodLevel(indexLod - 1); - - size_t numSubEntities = pCurEntity->getNumSubEntities(); - for(size_t indexSub = 0 ; indexSub < numSubEntities ; ++indexSub) - { - ushort boneCount = 0,weightCount = 0; - bool isValid = extractSkeletonData(pCurEntity, indexSub, boneCount, weightCount); - - SubEntity* pSubEntity = pCurEntity->getSubEntity(indexSub); - const MaterialPtr& pMat = pSubEntity->getMaterial(); - imprintSkeletonData(pMat, isValid, boneCount, weightCount, skinningType, correctAntidpodalityHandling, shearScale); - } - } - } -} - -} -} - -#endif - - diff --git a/Components/RTShaderSystem/src/OgreShaderExHardwareSkinningTechnique.cpp b/Components/RTShaderSystem/src/OgreShaderExHardwareSkinningTechnique.cpp deleted file mode 100644 index 6156419d373..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExHardwareSkinningTechnique.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreShaderPrecompiledHeaders.h" -#include "OgreMeshManager.h" - -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS - -namespace Ogre { - -namespace RTShader { - -/************************************************************************/ -/* */ -/************************************************************************/ -HardwareSkinningTechnique::HardwareSkinningTechnique() : - mBoneCount(0), - mWeightCount(0), - mCorrectAntipodalityHandling(false), - mScalingShearingSupport(false), - mDoBoneCalculations(false), - mObjSpaceBones(MeshManager::getBonesUseObjectSpace()) -{ -} - -//----------------------------------------------------------------------- -HardwareSkinningTechnique::~HardwareSkinningTechnique() -{ -} - -//----------------------------------------------------------------------- -void HardwareSkinningTechnique::setHardwareSkinningParam(ushort boneCount, ushort weightCount, bool correctAntipodalityHandling, bool scalingShearingSupport) -{ - mBoneCount = std::min(boneCount, OGRE_MAX_NUM_BONES); - mWeightCount = std::min(weightCount, 4); - mCorrectAntipodalityHandling = correctAntipodalityHandling; - mScalingShearingSupport = scalingShearingSupport; -} - -bool HardwareSkinningTechnique::setParameter(const String& name, const String& value) -{ - if(name == "max_bone_count") - { - uint num = 0; - StringConverter::parse(value, num); - mBoneCount = std::min(num, OGRE_MAX_NUM_BONES); - return num && num < OGRE_MAX_NUM_BONES; - } - else if(name == "weight_count") - { - uint num = 0; - StringConverter::parse(value, num); - mWeightCount = std::min(num, 4); - return num && num < 5; - } - else if(name == "correct_antipodality") - { - return StringConverter::parse(value, mCorrectAntipodalityHandling); - } - else if(name == "scale_shearing") - { - return StringConverter::parse(value, mScalingShearingSupport); - } - - return false; -} - -//----------------------------------------------------------------------- -void HardwareSkinningTechnique::setDoBoneCalculations(bool doBoneCalculations) -{ - mDoBoneCalculations = doBoneCalculations; -} - -//----------------------------------------------------------------------- -ushort HardwareSkinningTechnique::getBoneCount() -{ - return mBoneCount; -} - -//----------------------------------------------------------------------- -ushort HardwareSkinningTechnique::getWeightCount() -{ - return mWeightCount; -} - -//----------------------------------------------------------------------- -bool HardwareSkinningTechnique::hasCorrectAntipodalityHandling() -{ - return mCorrectAntipodalityHandling; -} - -//----------------------------------------------------------------------- -bool HardwareSkinningTechnique::hasScalingShearingSupport() -{ - return mScalingShearingSupport; -} -//----------------------------------------------------------------------- -bool HardwareSkinningTechnique::resolveDependencies(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - vsProgram->addDependency(FFP_LIB_TRANSFORM); - if(mDoBoneCalculations) - { - vsProgram->addDependency("SGXLib_DualQuaternion"); - vsProgram->addPreprocessorDefines(StringUtil::format("BONE_COUNT=%d", mBoneCount)); - vsProgram->addPreprocessorDefines(StringUtil::format("WEIGHT_COUNT=%d", mWeightCount)); - if(mCorrectAntipodalityHandling) - vsProgram->addPreprocessorDefines("CORRECT_ANTIPODALITY"); - } - - return true; -} -bool HardwareSkinningTechnique::resolveParameters(ProgramSet* programSet) -{ - - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - - //if needed mark this vertex program as hardware skinned - if (mDoBoneCalculations == true) - { - vsProgram->setSkeletalAnimationIncluded(true); - } - - // - // get the parameters we need whether we are doing bone calculations or not - // - // Note: in order to be consistent we will always output position, normal, - // tangent and binormal in both object and world space. And output position - // in projective space to cover the responsibility of the transform stage - - //input param - mParamInPosition = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE); - - if(mDoLightCalculations) - mParamInNormal = vsMain->resolveInputParameter(Parameter::SPC_NORMAL_OBJECT_SPACE); - //mParamInBiNormal = vsMain->resolveInputParameter(Parameter::SPS_BINORMAL, 0, Parameter::SPC_BINORMAL_OBJECT_SPACE, GCT_FLOAT3); - //mParamInTangent = vsMain->resolveInputParameter(Parameter::SPS_TANGENT, 0, Parameter::SPC_TANGENT_OBJECT_SPACE, GCT_FLOAT3); - - //output param - mParamOutPositionProj = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_PROJECTIVE_SPACE); - - if (mDoBoneCalculations == true) - { - if (ShaderGenerator::getSingleton().getTargetLanguage() == "hlsl") - { - //set hlsl shader to use row-major matrices instead of column-major. - //it enables the use of 3x4 matrices in hlsl shader instead of full 4x4 matrix. - vsProgram->setUseColumnMajorMatrices(false); - } - - //input parameters - mParamInIndices = vsMain->resolveInputParameter(Parameter::SPC_BLEND_INDICES); - mParamInWeights = vsMain->resolveInputParameter(Parameter::SPC_BLEND_WEIGHTS); - if(!mObjSpaceBones) - mParamInInvWorldMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_INVERSE_WORLD_MATRIX); - - resolveParameters(vsProgram); - } - - mParamInWorldViewProjMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLDVIEWPROJ_MATRIX); - return true; -} -//----------------------------------------------------------------------- -bool HardwareSkinningTechnique::addFunctionInvocations(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - - auto stage = vsMain->getStage(FFP_VS_TRANSFORM); - //add functions to calculate position data object and projective space - if (mDoBoneCalculations) - { - addPositionCalculations(stage); - // update back the original position relative to the object - if (!mObjSpaceBones) - stage.callBuiltin("mul", mParamInInvWorldMatrix, mParamInPosition, mParamInPosition); - } - - // update from object to projective space - stage.callBuiltin("mul", mParamInWorldViewProjMatrix, mParamInPosition, mParamOutPositionProj); - - //add functions to calculate normal and normal related data in world and object space - if (mDoBoneCalculations && mDoLightCalculations) - { - addNormalRelatedCalculations(stage); - // update back the original position relative to the object - if (!mObjSpaceBones) - stage.callFunction(FFP_FUNC_TRANSFORM, mParamInInvWorldMatrix, mParamInNormal, mParamInNormal); - } - //addNormalRelatedCalculations(vsMain, mParamInTangent, mParamLocalTangentWorld, internalCounter); - //addNormalRelatedCalculations(vsMain, mParamInBiNormal, mParamLocalBinormalWorld, internalCounter); - return true; -} -//----------------------------------------------------------------------- -void HardwareSkinningTechnique::copyFrom(const HardwareSkinningTechnique* hardSkin) -{ - mWeightCount = hardSkin->mWeightCount; - mBoneCount = hardSkin->mBoneCount; - mDoBoneCalculations = hardSkin->mDoBoneCalculations; - mCorrectAntipodalityHandling = hardSkin->mCorrectAntipodalityHandling; - mScalingShearingSupport = hardSkin->mScalingShearingSupport; - mObjSpaceBones = hardSkin->mObjSpaceBones; -} - -} -} - -#endif - - diff --git a/Components/RTShaderSystem/src/OgreShaderExHardwareSkinningTechnique.h b/Components/RTShaderSystem/src/OgreShaderExHardwareSkinningTechnique.h deleted file mode 100644 index dfc5988fa35..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExHardwareSkinningTechnique.h +++ /dev/null @@ -1,266 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderExHardwareSkinningTechnique_ -#define _ShaderExHardwareSkinningTechnique_ - -#include "OgreShaderPrerequisites.h" - -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS -#include "OgreShaderFunctionAtom.h" -#include "OgreShaderExHardwareSkinning.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** Implement a sub render state which performs hardware skinning. -Meaning, this sub render states adds calculations which multiply -the points and normals by their assigned bone matricies. -*/ -class HardwareSkinningTechnique : public RTShaderSystemAlloc -{ -// Interface. -public: - /** Class default constructor */ - HardwareSkinningTechnique(); - - virtual ~HardwareSkinningTechnique(); - - /** - @see SubRenderState::copyFrom. - */ - virtual void copyFrom(const HardwareSkinningTechnique* hardSkin); - - void setHardwareSkinningParam(ushort boneCount, ushort weightCount, bool correctAntipodalityHandling, bool scalingShearingSupport); - - virtual bool setParameter(const String& name, const String& value); - - /** - Returns the number of bones in the model assigned to the material. - @see setHardwareSkinningParam() - */ - ushort getBoneCount(); - - /** - Returns the number of weights/bones affecting a vertex. - @see setHardwareSkinningParam() - */ - ushort getWeightCount(); - - /** - Only applicable for dual quaternion skinning. - @see setHardwareSkinningParam() - */ - bool hasCorrectAntipodalityHandling(); - - /** - Only applicable for dual quaternion skinning. - @see setHardwareSkinningParam() - */ - bool hasScalingShearingSupport(); - - - void setDoBoneCalculations(bool doBoneCalculations); - void setDoLightCalculations(bool val) { mDoLightCalculations = val; } - - bool resolveParameters(ProgramSet* programSet); - bool resolveDependencies(ProgramSet* programSet); - - bool addFunctionInvocations(ProgramSet* programSet); - -private: - /** Adds functions to calculate position data in world, object and projective space */ - virtual void addPositionCalculations(const FunctionStageRef& stage) = 0; - - /** Adds the calculations for calculating a normal related element */ - virtual void addNormalRelatedCalculations(const FunctionStageRef& stage) = 0; - - virtual bool resolveParameters(Program* vsProgram) = 0; -// Attributes. -protected: - ushort mBoneCount; - ushort mWeightCount; - - bool mCorrectAntipodalityHandling; - bool mScalingShearingSupport; - - bool mDoBoneCalculations; - bool mDoLightCalculations; - - bool mObjSpaceBones; - - ParameterPtr mParamInPosition; - ParameterPtr mParamInNormal; - //ParameterPtr mParamInBiNormal; - //ParameterPtr mParamInTangent; - ParameterPtr mParamInIndices; - ParameterPtr mParamInWeights; - UniformParameterPtr mParamInWorldMatrices; - UniformParameterPtr mParamInInvWorldMatrix; - UniformParameterPtr mParamInWorldViewProjMatrix; - - ParameterPtr mParamOutPositionProj; -}; - -class DualQuaternionSkinning; -class LinearSkinning; - -/** Implement a sub render state which performs hardware skinning. -Meaning, this sub render states adds calculations which multiply -the points and normals by their assigned bone matricies. -*/ -class HardwareSkinning : public SubRenderState -{ -public: - struct SkinningData - { - SkinningData() - : isValid(true), maxBoneCount(0), maxWeightCount(0), skinningType(ST_LINEAR), - correctAntipodalityHandling(false), scalingShearingSupport(false) - { - } - - bool isValid; - ushort maxBoneCount; - ushort maxWeightCount; - SkinningType skinningType; - bool correctAntipodalityHandling; - bool scalingShearingSupport; - }; - -// Interface. -public: - /** Class default constructor */ - HardwareSkinning(); - - /** - @see SubRenderState::getType. - */ - const String& getType() const override; - - /** - @see SubRenderState::getType. - */ - int getExecutionOrder() const override; - - /** - @see SubRenderState::copyFrom. - */ - void copyFrom(const SubRenderState& rhs) override; - - /** - Set the hardware skinning parameters. - @param boneCount The maximum number of bones in the model this material - is assigned to. Note that this parameter can be higher but not - lower than the actual number of bones. - @param weightCount The maximum number of weights/bones affecting a vertex. - @param skinningType The type of skinning desired. - @param correctAntipodalityHandling If correct antipodality handling should be utilized (Only applicable for dual quaternion skinning). - @param scalingShearingSupport If scaling and shearing support should be enabled (Only applicable for dual quaternion skinning). - */ - bool setParameter(const String& name, const String& value) override; - - /** - Returns the number of bones in the model assigned to the material. - @see setHardwareSkinningParam() - */ - ushort getBoneCount(); - - /** - Returns the number of weights/bones affecting a vertex. - @see setHardwareSkinningParam() - */ - ushort getWeightCount(); - - /** - Returns the current skinning type in use. - @see setHardwareSkinningParam() - */ - SkinningType getSkinningType(); - - /** - Only applicable for dual quaternion skinning. - @see setHardwareSkinningParam() - */ - bool hasCorrectAntipodalityHandling(); - - /** - Only applicable for dual quaternion skinning. - @see setHardwareSkinningParam() - */ - bool hasScalingShearingSupport(); - - /** - @see SubRenderState::preAddToRenderState. - */ - bool preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) override; - - /** - Set the factory which created this sub render state - */ - void _setCreator(const HardwareSkinningFactory* pCreator) { mCreator = pCreator; } - - static String Type; - -// Protected methods -protected: - /** - @see SubRenderState::resolveParameters. - */ - bool resolveParameters(ProgramSet* programSet) override; - - /** - @see SubRenderState::resolveDependencies. - */ - bool resolveDependencies(ProgramSet* programSet) override; - - /** - @see SubRenderState::addFunctionInvocations. - */ - bool addFunctionInvocations(ProgramSet* programSet) override; - - SharedPtr mLinear; - SharedPtr mDualQuat; - SharedPtr mActiveTechnique; - - ///The factory which created this sub render state - const HardwareSkinningFactory* mCreator; - SkinningType mSkinningType; -}; - -} -} - -#endif -#endif - diff --git a/Components/RTShaderSystem/src/OgreShaderExIntegratedPSSM3.cpp b/Components/RTShaderSystem/src/OgreShaderExIntegratedPSSM3.cpp deleted file mode 100644 index 28de672896e..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExIntegratedPSSM3.cpp +++ /dev/null @@ -1,429 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderPrecompiledHeaders.h" -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS - -#define SGX_LIB_INTEGRATEDPSSM "SGXLib_IntegratedPSSM" - -namespace Ogre { -namespace RTShader { - -/************************************************************************/ -/* */ -/************************************************************************/ -String IntegratedPSSM3::Type = "SGX_IntegratedPSSM3"; -const String SRS_INTEGRATED_PSSM3 = "SGX_IntegratedPSSM3"; -const String SRS_SHADOW_MAPPING = "SGX_IntegratedPSSM3"; - -//----------------------------------------------------------------------- -IntegratedPSSM3::IntegratedPSSM3() -{ - mPCFxSamples = 2; - mUseTextureCompare = false; - mUseColourShadows = false; - mDebug = false; - mIsD3D9 = false; - mShadowTextureParamsList.resize(1); // normal single texture depth shadowmapping - mMultiLightCount = 1; -} - -//----------------------------------------------------------------------- -int IntegratedPSSM3::getExecutionOrder() const -{ - return FFP_LIGHTING - 1; -} - -//----------------------------------------------------------------------- -void IntegratedPSSM3::updateGpuProgramsParams(Renderable* rend, const Pass* pass, - const AutoParamDataSource* source, - const LightList* pLightList) -{ - if (mMultiLightCount > 1) - return; - - Vector4 vSplitPoints; - - for(size_t i = 0; i < mShadowTextureParamsList.size() - 1; i++) - { - vSplitPoints[i] = mShadowTextureParamsList[i].mMaxRange; - } - vSplitPoints[3] = mShadowTextureParamsList.back().mMaxRange; - - const Matrix4& proj = source->getProjectionMatrix(); - - for(int i = 0; i < 4; i++) - { - auto tmp = proj * Vector4(0, 0, -vSplitPoints[i], 1); - vSplitPoints[i] = tmp[2] / tmp[3]; - } - - - mPSSplitPoints->setGpuParameter(vSplitPoints); - -} - -//----------------------------------------------------------------------- -void IntegratedPSSM3::copyFrom(const SubRenderState& rhs) -{ - const IntegratedPSSM3& rhsPssm= static_cast(rhs); - - mPCFxSamples = rhsPssm.mPCFxSamples; - mUseTextureCompare = rhsPssm.mUseTextureCompare; - mUseColourShadows = rhsPssm.mUseColourShadows; - mDebug = rhsPssm.mDebug; - mMultiLightCount = rhsPssm.mMultiLightCount; - mShadowTextureParamsList.resize(rhsPssm.mShadowTextureParamsList.size()); - - ShadowTextureParamsConstIterator itSrc = rhsPssm.mShadowTextureParamsList.begin(); - for (auto& p : mShadowTextureParamsList) - { - p.mMaxRange = itSrc->mMaxRange; - ++itSrc; - } -} - -//----------------------------------------------------------------------- -bool IntegratedPSSM3::preAddToRenderState(const RenderState* renderState, - Pass* srcPass, Pass* dstPass) -{ - if (!srcPass->getParent()->getParent()->getReceiveShadows() || - renderState->getLightCount() == 0) - return false; - - mIsD3D9 = ShaderGenerator::getSingleton().getTargetLanguage() == "hlsl" && - !GpuProgramManager::getSingleton().isSyntaxSupported("vs_4_0_level_9_1"); - - PixelFormat shadowTexFormat = PF_UNKNOWN; - const auto& configs = ShaderGenerator::getSingleton().getActiveSceneManager()->getShadowTextureConfigList(); - if (!configs.empty()) - shadowTexFormat = configs[0].format; // assume first texture is representative - mUseTextureCompare = PixelUtil::isDepth(shadowTexFormat) && !mIsD3D9; - mUseColourShadows = PixelUtil::getComponentType(shadowTexFormat) == PCT_BYTE; // use colour shadowmaps for byte textures - - if(mMultiLightCount > 1) - mShadowTextureParamsList.resize(mMultiLightCount); - - auto shadowSampler = TextureManager::getSingleton().getSampler(mUseTextureCompare ? "Ogre/DepthShadowSampler" - : "Ogre/ShadowSampler"); - for (auto& p : mShadowTextureParamsList) - { - TextureUnitState* curShadowTexture = dstPass->createTextureUnitState(); - curShadowTexture->setContentType(TextureUnitState::CONTENT_SHADOW); - curShadowTexture->setSampler(shadowSampler); - p.mTextureSamplerIndex = dstPass->getNumTextureUnitStates() - 1; - } - - return true; -} - -//----------------------------------------------------------------------- -void IntegratedPSSM3::setSplitPoints(const SplitPointList& newSplitPoints) -{ - OgreAssert(newSplitPoints.size() <= 5, "at most 5 split points are supported"); - - mShadowTextureParamsList.resize(newSplitPoints.size() - 1); - - for (size_t i = 1; i < newSplitPoints.size(); ++i) - { - mShadowTextureParamsList[i - 1].mMaxRange = newSplitPoints[i]; - } -} - -bool IntegratedPSSM3::setParameter(const String& name, const String& value) -{ - if(name == "debug") - { - return StringConverter::parse(value, mDebug); - } - else if (name == "filter") - { - if(value == "pcf4") - mPCFxSamples = 2; - else if(value == "pcf16") - mPCFxSamples = 4; - else - return false; - - return true; - } - else if (name == "light_count") - { - mMultiLightCount = StringConverter::parseInt(value); - return true; - } - - return false; -} - -void IntegratedPSSM3::setParameter(const String& name, const Any& value) -{ - if(name == "split_points") - { - setSplitPoints(any_cast(value)); - return; - } - else if (name == "debug") - { - mDebug = any_cast(value); - return; - } - - SubRenderState::setParameter(name, value); -} - -//----------------------------------------------------------------------- -bool IntegratedPSSM3::resolveParameters(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Function* psMain = psProgram->getEntryPointFunction(); - - // Get input position parameter. - mVSInPos = vsMain->getLocalParameter(Parameter::SPC_POSITION_OBJECT_SPACE); - if(!mVSInPos) - mVSInPos = vsMain->getInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE); - - // Get output position parameter. - mVSOutPos = vsMain->getOutputParameter(Parameter::SPC_POSITION_PROJECTIVE_SPACE); - - if (mIsD3D9) - { - mVSOutPos = vsMain->resolveOutputParameter(Parameter::SPC_UNKNOWN, GCT_FLOAT4); - } - - // Resolve input depth parameter. - mPSInDepth = psMain->resolveInputParameter(mVSOutPos); - - // Resolve computed local shadow colour parameter. - mPSLocalShadowFactor = psMain->resolveLocalParameter(GCT_FLOAT1, "lShadowFactor", mMultiLightCount); - - // Resolve computed local shadow colour parameter. - mPSSplitPoints = psProgram->resolveParameter(GCT_FLOAT4, "pssm_split_points"); - - int lightIndex = 0; - - for (auto& p : mShadowTextureParamsList) - { - p.mWorldViewProjMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_TEXTURE_WORLDVIEWPROJ_MATRIX, lightIndex); - p.mVSOutLightPosition = vsMain->resolveOutputParameter(Parameter::Content(Parameter::SPC_POSITION_LIGHT_SPACE0 + lightIndex)); - p.mPSInLightPosition = psMain->resolveInputParameter(p.mVSOutLightPosition); - auto stype = mUseTextureCompare ? GCT_SAMPLER2DSHADOW : GCT_SAMPLER2D; - p.mTextureSampler = psProgram->resolveParameter(stype, "shadow_map", p.mTextureSamplerIndex); - p.mInvTextureSize = psProgram->resolveParameter(GpuProgramParameters::ACT_INVERSE_TEXTURE_SIZE, p.mTextureSamplerIndex); - ++lightIndex; - } - - if (!(mVSInPos.get()) || !(mVSOutPos.get())) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Not all parameters could be constructed for the sub-render state."); - } - - return true; -} - -//----------------------------------------------------------------------- -bool IntegratedPSSM3::resolveDependencies(ProgramSet* programSet) -{ - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - psProgram->addDependency(SGX_LIB_INTEGRATEDPSSM); - - psProgram->addPreprocessorDefines(StringUtil::format("PSSM_NUM_SPLITS=%zu,PCF_XSAMPLES=%.1f,SHADOWLIGHT_COUNT=%d", - mShadowTextureParamsList.size(), mPCFxSamples, mMultiLightCount)); - - if(mDebug) - psProgram->addPreprocessorDefines("DEBUG_PSSM"); - - if(mUseTextureCompare) - psProgram->addPreprocessorDefines("PSSM_SAMPLE_CMP"); - - if(mUseColourShadows) - psProgram->addPreprocessorDefines("PSSM_SAMPLE_COLOUR"); - - return true; -} - -//----------------------------------------------------------------------- -bool IntegratedPSSM3::addFunctionInvocations(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - - // Add vertex shader invocations. - if (false == addVSInvocation(vsMain, FFP_VS_TEXTURING + 1)) - return false; - - // Add pixel shader invocations. - if (false == addPSInvocation(psProgram, FFP_PS_COLOUR_BEGIN)) - return false; - - return true; -} - -//----------------------------------------------------------------------- -bool IntegratedPSSM3::addVSInvocation(Function* vsMain, const int groupOrder) -{ - auto stage = vsMain->getStage(groupOrder); - - if(mIsD3D9) - { - auto vsOutPos = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_PROJECTIVE_SPACE); - stage.assign(vsOutPos, mVSOutPos); - } - - // Compute world space position. - for (auto& p : mShadowTextureParamsList) - { - stage.callBuiltin("mul", p.mWorldViewProjMatrix, mVSInPos, p.mVSOutLightPosition); - } - - return true; -} - -//----------------------------------------------------------------------- -bool IntegratedPSSM3::addPSInvocation(Program* psProgram, const int groupOrder) -{ - Function* psMain = psProgram->getEntryPointFunction(); - auto stage = psMain->getStage(groupOrder); - - if(mShadowTextureParamsList.size() < 2 || mMultiLightCount > 1) - { - for(uchar i = 0; i < mMultiLightCount; ++i) - { - ShadowTextureParams& params = mShadowTextureParamsList[i]; - stage.callFunction("SGX_ShadowPCF4", - {In(params.mTextureSampler), In(params.mPSInLightPosition), - In(params.mInvTextureSize).xy(), Out(mPSLocalShadowFactor), At(i)}); - } - } - else - { - auto fdepth = psMain->resolveLocalParameter(GCT_FLOAT1, "fdepth"); - if(mIsD3D9) - stage.div(In(mPSInDepth).z(), In(mPSInDepth).w(), fdepth); - else - stage.assign(In(mPSInDepth).z(), fdepth); - std::vector params = {In(fdepth), In(mPSSplitPoints)}; - - for(auto& texp : mShadowTextureParamsList) - { - params.push_back(In(texp.mPSInLightPosition)); - params.push_back(In(texp.mTextureSampler)); - params.push_back(In(texp.mInvTextureSize).xy()); - } - - params.push_back(Out(mPSLocalShadowFactor)); - params.push_back(At(0)); - - if(mDebug) - { - auto sceneCol = psProgram->resolveParameter(GpuProgramParameters::ACT_DERIVED_SCENE_COLOUR); - params.push_back(InOut(sceneCol)); - } - - // Compute shadow factor. - stage.callFunction("SGX_ComputeShadowFactor_PSSM3", params); - } - - // shadow factor is applied by lighting stages - return true; -} - -//----------------------------------------------------------------------- -SubRenderState* IntegratedPSSM3Factory::createInstance(ScriptCompiler* compiler, - PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) -{ - if (prop->name == "integrated_pssm4") - { - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, prop->file, prop->line, "integrated_pssm4. Use shadow_mapping instead."); - - SubRenderState* subRenderState = createOrRetrieveInstance(translator); - - auto it = prop->values.begin(); - auto itEnd = prop->values.end(); - - if (prop->values.size() >= 4) - { - IntegratedPSSM3::SplitPointList splitPointList; - if(SGScriptTranslator::getVector(it, itEnd, splitPointList, 4)) - subRenderState->setParameter("split_points", splitPointList); - - std::advance(it, 4); - } - - for (; it != itEnd; ++it) - { - const auto& val = (*it)->getString(); - if(val == "debug") - { - subRenderState->setParameter("debug", "true"); - } - else if(val == "pcf16") - { - subRenderState->setParameter("filter", "pcf16"); - } - } - - return subRenderState; - } - - if (prop->name == "shadow_mapping") - { - SubRenderState* subRenderState = createOrRetrieveInstance(translator); - - auto it = prop->values.begin(); - while(it != prop->values.end()) - { - String paramName = (*it)->getString(); - String paramValue = (*++it)->getString(); - - if (!subRenderState->setParameter(paramName, paramValue)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, paramName); - return subRenderState; - } - it++; - } - - return subRenderState; - } - - return NULL; -} - -//----------------------------------------------------------------------- -SubRenderState* IntegratedPSSM3Factory::createInstanceImpl() -{ - return OGRE_NEW IntegratedPSSM3; -} - -} -} - -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderExIntegratedPSSM3.h b/Components/RTShaderSystem/src/OgreShaderExIntegratedPSSM3.h deleted file mode 100644 index 4c61ed1b370..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExIntegratedPSSM3.h +++ /dev/null @@ -1,217 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderExIntegratedPSSM3_ -#define _ShaderExIntegratedPSSM3_ - -#include "OgreShaderPrerequisites.h" -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS -#include "OgreCommon.h" -#include "OgreShaderSubRenderState.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/// @copydoc SRS_INTEGRATED_PSSM3 -class IntegratedPSSM3 : public SubRenderState -{ - - // Interface. -public: - typedef std::vector SplitPointList; - - /** Class default constructor */ - IntegratedPSSM3(); - - const String& getType() const override { return SRS_INTEGRATED_PSSM3; } - - /** - @see SubRenderState::getType. - */ - int getExecutionOrder() const override; - - /** - @see SubRenderState::updateGpuProgramsParams. - */ - void updateGpuProgramsParams(Renderable* rend, const Pass* pass, const AutoParamDataSource* source, const LightList* pLightList) override; - - /** - @see SubRenderState::copyFrom. - */ - void copyFrom(const SubRenderState& rhs) override; - - - /** - @see SubRenderState::preAddToRenderState. - */ - bool preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) override; - - - - /** Manually configure a new splitting scheme. - @param value A list which is splitCount + 1 entries long, containing the - split points. The first value is the near point, the last value is the - far point, and each value in between is both a far point of the previous - split, and a near point for the next one. - */ - void setParameter(const String& name, const Any& value) override; - bool setParameter(const String& name, const String& value) override; - - - - static String Type; - - // Protected types: -protected: - - void setSplitPoints(const SplitPointList& newSplitPoints); - - // Shadow texture parameters. - struct ShadowTextureParams - { - // The max range of this shadow texture in terms of PSSM (far plane of viewing camera). - Real mMaxRange; - // The shadow map sampler index. - unsigned int mTextureSamplerIndex; - // The shadow map sampler. - UniformParameterPtr mTextureSampler; - // The inverse texture - UniformParameterPtr mInvTextureSize; - // The source light view projection matrix combined with world matrix. - UniformParameterPtr mWorldViewProjMatrix; - // The vertex shader output position in light space. - ParameterPtr mVSOutLightPosition; - // The pixel shader input position in light space. - ParameterPtr mPSInLightPosition; - - }; - - typedef std::vector ShadowTextureParamsList; - typedef ShadowTextureParamsList::iterator ShadowTextureParamsIterator; - typedef ShadowTextureParamsList::const_iterator ShadowTextureParamsConstIterator; - - // Protected methods -protected: - - - - /** - @see SubRenderState::resolveParameters. - */ - bool resolveParameters(ProgramSet* programSet) override; - - /** - @see SubRenderState::resolveDependencies. - */ - bool resolveDependencies(ProgramSet* programSet) override; - - /** - @see SubRenderState::addFunctionInvocations. - */ - bool addFunctionInvocations(ProgramSet* programSet) override; - - /** - Internal method that adds related vertex shader functions invocations. - */ - bool addVSInvocation(Function* vsMain, const int groupOrder); - - /** - Internal method that adds related pixel shader functions invocations. - */ - bool addPSInvocation(Program* psProgram, const int groupOrder); - - - - - - // Attributes. -protected: - // Shadow texture parameter list. - ShadowTextureParamsList mShadowTextureParamsList; - // Split points parameter. - UniformParameterPtr mPSSplitPoints; - // Vertex shader input position parameter. - ParameterPtr mVSInPos; - // Vertex shader output position (clip space) parameter. - ParameterPtr mVSOutPos; - // Vertex shader output depth (clip space) parameter. - ParameterPtr mVSOutDepth; - // Pixel shader input depth (clip space) parameter. - ParameterPtr mPSInDepth; - // Pixel shader local computed shadow colour parameter. - ParameterPtr mPSLocalShadowFactor; - - float mPCFxSamples; - bool mUseTextureCompare; - bool mUseColourShadows; - bool mDebug; - bool mIsD3D9; - uchar mMultiLightCount; -}; - - -/** -A factory that enables creation of IntegratedPSSM3 instances. -@remarks Sub class of SubRenderStateFactory -*/ -class IntegratedPSSM3Factory : public SubRenderStateFactory -{ -public: - const String& getType() const override { return SRS_INTEGRATED_PSSM3; } - - /** - @see SubRenderStateFactory::createInstance. - */ - SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) override; - - -protected: - - /** - @see SubRenderStateFactory::createInstanceImpl. - */ - SubRenderState* createInstanceImpl() override; - - -}; - -/** @} */ -/** @} */ - -} -} - -#endif -#endif - diff --git a/Components/RTShaderSystem/src/OgreShaderExLayeredBlending.cpp b/Components/RTShaderSystem/src/OgreShaderExLayeredBlending.cpp deleted file mode 100644 index 6d34c9d16a8..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExLayeredBlending.cpp +++ /dev/null @@ -1,563 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderPrecompiledHeaders.h" -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS - -namespace Ogre { -namespace RTShader { - - -String LayeredBlending::Type = "LayeredBlendRTSSEx"; -const String SRS_LAYERED_BLENDING = "LayeredBlendRTSSEx"; - -enum BlendMode : int -{ - LB_Invalid = -1, - LB_FFPBlend, - LB_BlendNormal, - LB_BlendLighten, - LB_BlendDarken, - LB_BlendMultiply, - LB_BlendAverage, - LB_BlendAdd, - LB_BlendSubtract, - LB_BlendDifference, - LB_BlendNegation, - LB_BlendExclusion, - LB_BlendScreen, - LB_BlendOverlay, - LB_BlendSoftLight, - LB_BlendHardLight, - LB_BlendColorDodge, - LB_BlendColorBurn, - LB_BlendLinearDodge, - LB_BlendLinearBurn, - LB_BlendLinearLight, - LB_BlendVividLight, - LB_BlendPinLight, - LB_BlendHardMix, - LB_BlendReflect, - LB_BlendGlow, - LB_BlendPhoenix, - LB_BlendSaturation, - LB_BlendColor, - LB_BlendLuminosity, - LB_MaxBlendModes -}; - -enum SourceModifier : int -{ - SM_Invalid = -1, - SM_None, - SM_Source1Modulate, - SM_Source2Modulate, - SM_Source1InvModulate, - SM_Source2InvModulate, - SM_MaxSourceModifiers -}; - -namespace { - - struct BlendModeDescription { - /* Type of the blend mode */ - BlendMode type; - /* name of the blend mode. */ - const char* name; - /* shader function name . */ - const char* funcName; - }; - -const BlendModeDescription _blendModes[(int)LB_MaxBlendModes] = { - { LB_FFPBlend ,"default", ""}, - { LB_BlendNormal ,"normal", "SGX_blend_normal"}, - { LB_BlendLighten,"lighten", "SGX_blend_lighten"}, - { LB_BlendDarken ,"darken", "SGX_blend_darken"}, - { LB_BlendMultiply ,"multiply", "SGX_blend_multiply"}, - { LB_BlendAverage ,"average", "SGX_blend_average"}, - { LB_BlendAdd ,"add", "SGX_blend_add"}, - { LB_BlendSubtract ,"subtract", "SGX_blend_subtract"}, - { LB_BlendDifference ,"difference", "SGX_blend_difference"}, - { LB_BlendNegation ,"negation", "SGX_blend_negation"}, - { LB_BlendExclusion ,"exclusion", "SGX_blend_exclusion"}, - { LB_BlendScreen ,"screen", "SGX_blend_screen"}, - { LB_BlendOverlay ,"overlay", "SGX_blend_overlay"}, - { LB_BlendHardLight ,"hard_light", "SGX_blend_hardLight"}, - { LB_BlendSoftLight ,"soft_light", "SGX_blend_softLight"}, - { LB_BlendColorDodge ,"color_dodge", "SGX_blend_colorDodge"}, - { LB_BlendColorBurn ,"color_burn", "SGX_blend_colorBurn"}, - { LB_BlendLinearDodge ,"linear_dodge", "SGX_blend_linearDodge"}, - { LB_BlendLinearBurn ,"linear_burn", "SGX_blend_linearBurn"}, - { LB_BlendLinearLight ,"linear_light", "SGX_blend_linearLight"}, - { LB_BlendVividLight ,"vivid_light", "SGX_blend_vividLight"}, - { LB_BlendPinLight ,"pin_light", "SGX_blend_pinLight"}, - { LB_BlendHardMix ,"hard_mix", "SGX_blend_hardMix"}, - { LB_BlendReflect ,"reflect", "SGX_blend_reflect"}, - { LB_BlendGlow ,"glow", "SGX_blend_glow"}, - { LB_BlendPhoenix ,"phoenix", "SGX_blend_phoenix"}, - { LB_BlendSaturation ,"saturation", "SGX_blend_saturation"}, - { LB_BlendColor ,"color", "SGX_blend_color"}, - { LB_BlendLuminosity, "luminosity", "SGX_blend_luminosity"} -}; - - - struct SourceModifierDescription { - /* Type of the source modifier*/ - SourceModifier type; - /* name of the source modifier. */ - const char* name; - }; - -const SourceModifierDescription _sourceModifiers[(int)SM_MaxSourceModifiers] = { - { SM_None ,""}, - { SM_Source1Modulate ,"src1_modulate"}, - { SM_Source2Modulate ,"src2_modulate"}, - { SM_Source1InvModulate ,"src1_inverse_modulate"}, - { SM_Source2InvModulate ,"src2_inverse_modulate"} - }; - -//----------------------------------------------------------------------- -BlendMode stringToBlendMode(const String &strValue) -{ - for(const auto & _blendMode : _blendModes) - { - if (_blendMode.name == strValue) - { - return _blendMode.type; - } - } - return LB_Invalid; -} - -//----------------------------------------------------------------------- -String blendModeToString(BlendMode blendMode) -{ - for(const auto & _blendMode : _blendModes) - { - if (_blendMode.type == blendMode) - { - return _blendMode.name; - } - } - return ""; -} - -//----------------------------------------------------------------------- -SourceModifier stringToSourceModifier(const String &strValue) -{ - for(const auto & _sourceModifier : _sourceModifiers) - { - if (_sourceModifier.name == strValue) - { - return _sourceModifier.type; - } - } - return SM_Invalid; -} - -//----------------------------------------------------------------------- -String sourceModifierToString(SourceModifier modifier) -{ - for(const auto & _sourceModifier : _sourceModifiers) - { - if (_sourceModifier.type == modifier) - { - return _sourceModifier.name; - } - } - return ""; -} -} - -LayeredBlending::TextureBlend::TextureBlend() : blendMode(LB_Invalid), sourceModifier(SM_Invalid), customNum(0) {} - -//----------------------------------------------------------------------- -LayeredBlending::LayeredBlending() -{ - -} - -//----------------------------------------------------------------------- -const Ogre::String& LayeredBlending::getType() const -{ - return SRS_LAYERED_BLENDING; -} - - -//----------------------------------------------------------------------- -bool LayeredBlending::resolveParameters(ProgramSet* programSet) -{ - - //resolve peremeter for normal texturing procedures - bool isSuccess = FFPTexturing::resolveParameters(programSet); - - if (isSuccess) - { - //resolve source modification parameters - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - - for(size_t i = mTextureBlends.size() - 1; i != (size_t)-1 ; --i) - { - TextureBlend& texBlend = mTextureBlends[i]; - if ((texBlend.sourceModifier != SM_Invalid) && - (texBlend.sourceModifier != SM_None)) - { - - texBlend.modControlParam = psProgram->resolveParameter( - GpuProgramParameters::ACT_CUSTOM, texBlend.customNum); - if (texBlend.modControlParam.get() == NULL) - { - isSuccess = false; - break; - } - } - } - } - return isSuccess; -} - - - -//----------------------------------------------------------------------- -bool LayeredBlending::resolveDependencies(ProgramSet* programSet) -{ - FFPTexturing::resolveDependencies(programSet); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - - psProgram->addDependency("SGXLib_LayeredBlending"); - - return true; -} - -//----------------------------------------------------------------------- -void LayeredBlending::copyFrom(const SubRenderState& rhs) -{ - FFPTexturing::copyFrom(rhs); - - const LayeredBlending& rhsTexture = static_cast(rhs); - mTextureBlends = rhsTexture.mTextureBlends; -} - -//----------------------------------------------------------------------- -void LayeredBlending::addPSBlendInvocations(Function* psMain, - ParameterPtr arg1, - ParameterPtr arg2, - ParameterPtr texel, - int samplerIndex, - const LayerBlendModeEx& blendMode, - const int groupOrder, - Operand::OpMask mask) -{ - // - // Add the modifier invocation - // - - addPSModifierInvocation(psMain, samplerIndex, arg1, arg2, groupOrder, mask); - - // - // Add the blending function invocations - // - - BlendMode mode = getBlendMode(samplerIndex); - - if ((LB_FFPBlend == mode) || (LB_Invalid == mode)) - { - FFPTexturing::addPSBlendInvocations(psMain, arg1, arg2, texel, samplerIndex, blendMode, groupOrder, mask); - } - else - { - //find the function name for the blend mode - const char* funcName = NULL; - for(const auto & _blendMode : _blendModes) - { - if (_blendMode.type == mode) - { - funcName = _blendMode.funcName; - break; - } - } - - //add the function of the blend mode - if (funcName) - { - psMain->getStage(groupOrder) - .callFunction(funcName, In(arg1).mask(mask), In(arg2).mask(mask), Out(mPSOutDiffuse).mask(mask)); - } - } -} - -//----------------------------------------------------------------------- -void LayeredBlending::addPSModifierInvocation(Function* psMain, - int samplerIndex, - ParameterPtr arg1, - ParameterPtr arg2, - const int groupOrder, - Operand::OpMask mask) -{ - SourceModifier modType; - int customNum; - if (getSourceModifier(samplerIndex, modType, customNum) == true) - { - ParameterPtr modifiedParam; - const char* funcName = NULL; - switch (modType) - { - case SM_Source1Modulate: - funcName = "SGX_src_mod_modulate"; - modifiedParam = arg1; - break; - case SM_Source2Modulate: - funcName = "SGX_src_mod_modulate"; - modifiedParam = arg2; - break; - case SM_Source1InvModulate: - funcName = "SGX_src_mod_inv_modulate"; - modifiedParam = arg1; - break; - case SM_Source2InvModulate: - funcName = "SGX_src_mod_inv_modulate"; - modifiedParam = arg2; - break; - default: - break; - } - - //add the function of the blend mode - if (funcName) - { - ParameterPtr& controlParam = mTextureBlends[samplerIndex].modControlParam; - psMain->getStage(groupOrder) - .callFunction(funcName, In(modifiedParam).mask(mask), In(controlParam).mask(mask), - Out(modifiedParam).mask(mask)); - } - } -} - -bool LayeredBlending::setBlendMode(uint16 index, const String& mode) -{ - auto blendMode = stringToBlendMode(mode); - if (blendMode == LB_Invalid) - return false; - - if(mTextureBlends.size() < (size_t)index + 1) - { - mTextureBlends.resize(index + 1); - } - mTextureBlends[index].blendMode = blendMode; - return true; -} - -//----------------------------------------------------------------------- -BlendMode LayeredBlending::getBlendMode(unsigned short index) const -{ - if(index < mTextureBlends.size()) - { - return mTextureBlends[index].blendMode; - } - return LB_Invalid; -} - - -//----------------------------------------------------------------------- -bool LayeredBlending::setSourceModifier(unsigned short index, const String& modType, int customNum) -{ - SourceModifier mod = stringToSourceModifier(modType); - if (mod == SM_Invalid) - return false; - - if(mTextureBlends.size() < (size_t)index + 1) - { - mTextureBlends.resize(index + 1); - } - mTextureBlends[index].sourceModifier = mod; - mTextureBlends[index].customNum = customNum; - return true; -} - -//----------------------------------------------------------------------- -bool LayeredBlending::getSourceModifier(unsigned short index, SourceModifier& modType, int& customNum) const -{ - modType = SM_Invalid; - customNum = 0; - if(index < mTextureBlends.size()) - { - modType = mTextureBlends[index].sourceModifier; - customNum = mTextureBlends[index].customNum; - } - return (modType != SM_Invalid); -} - - -//----------------------Factory Implementation--------------------------- -//----------------------------------------------------------------------- -const String& LayeredBlendingFactory::getType() const -{ - return SRS_LAYERED_BLENDING; -} - -//----------------------------------------------------------------------- -SubRenderState* LayeredBlendingFactory::createInstance(ScriptCompiler* compiler, - PropertyAbstractNode* prop, TextureUnitState* texState, SGScriptTranslator* translator) -{ - if (prop->name == "layered_blend") - { - if (stringToBlendMode(prop->values.front()->getString()) == LB_Invalid) - { - StringVector vec; - for (const auto& m : _blendModes) - vec.push_back(m.name); - - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "Expected one of the following blend modes: " + StringConverter::toString(vec)); - return NULL; - } - - - //get the layer blend sub-render state to work on - LayeredBlending* layeredBlendState = - createOrRetrieveSubRenderState(translator); - - //update the layer sub render state - unsigned short texIndex = texState->getParent()->getTextureUnitStateIndex(texState); - layeredBlendState->setBlendMode(texIndex, prop->values.front()->getString()); - - return layeredBlendState; - } - if (prop->name == "source_modifier") - { - if(prop->values.size() < 3) - return NULL; - - // Read light model type. - bool isParseSuccess; - String modifierString; - String paramType; - int customNum; - - AbstractNodeList::const_iterator itValue = prop->values.begin(); - modifierString = (*itValue)->getString(); - isParseSuccess = stringToSourceModifier(modifierString) != SM_Invalid; - if (isParseSuccess == false) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "Expected one of the following modifier type as first parameter: " \ - "src1_modulate, src2_modulate, src1_inverse_modulate, src2_inverse_modulate."); - return NULL; - } - - ++itValue; - isParseSuccess &= ((*itValue)->getString() == "custom"); - if(isParseSuccess == false) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "Expected reserved word custom as second parameter."); - return NULL; - } - ++itValue; - if(!SGScriptTranslator::getInt(*itValue, &customNum)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "Expected number of custom parameter as third parameter."); - return NULL; - } - - //get the layer blend sub-render state to work on - LayeredBlending* layeredBlendState = createOrRetrieveSubRenderState(translator); - - //update the layer sub render state - unsigned short texIndex = texState->getParent()->getTextureUnitStateIndex(texState); - layeredBlendState->setSourceModifier(texIndex, modifierString, customNum); - - return layeredBlendState; - - } - - return NULL; - -} - -//----------------------------------------------------------------------- -void LayeredBlendingFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, - const TextureUnitState* srcTextureState, const TextureUnitState* dstTextureState) -{ - unsigned short texIndex = srcTextureState->getParent()-> - getTextureUnitStateIndex(srcTextureState); - - //get blend mode for current texture unit - LayeredBlending* layeredBlendingSubRenderState = static_cast(subRenderState); - - //write the blend mode - BlendMode blendMode = layeredBlendingSubRenderState->getBlendMode(texIndex); - if (blendMode != LB_Invalid) - { - ser->writeAttribute(5, "layered_blend"); - ser->writeValue(blendModeToString(blendMode)); - } - - //write the source modifier - SourceModifier modType; - int customNum; - if (layeredBlendingSubRenderState->getSourceModifier(texIndex, modType, customNum) == true) - { - ser->writeAttribute(5, "source_modifier"); - ser->writeValue(sourceModifierToString(modType)); - ser->writeValue("custom"); - ser->writeValue(StringConverter::toString(customNum)); - } - -} - -//----------------------------------------------------------------------- -SubRenderState* LayeredBlendingFactory::createInstanceImpl() -{ - return OGRE_NEW LayeredBlending; -} - -//----------------------------------------------------------------------- -LayeredBlending* LayeredBlendingFactory::createOrRetrieveSubRenderState(SGScriptTranslator* translator) -{ - LayeredBlending* layeredBlendState; - //check if we already create a blend srs - SubRenderState* subState = translator->getGeneratedSubRenderState(getType()); - if (subState != NULL) - { - layeredBlendState = static_cast(subState); - } - else - { - SubRenderState* subRenderState = createOrRetrieveInstance(translator); - layeredBlendState = static_cast(subRenderState); - } - return layeredBlendState; -} - - -} -} -#endif - - diff --git a/Components/RTShaderSystem/src/OgreShaderExLinearSkinning.cpp b/Components/RTShaderSystem/src/OgreShaderExLinearSkinning.cpp deleted file mode 100644 index a49f2d21043..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExLinearSkinning.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreShaderPrecompiledHeaders.h" -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS - -namespace Ogre { - -namespace RTShader { - - -/************************************************************************/ -/* */ -/************************************************************************/ -bool LinearSkinning::resolveParameters(Program* vsProgram) -{ - Function* vsMain = vsProgram->getEntryPointFunction(); - mParamInWorldMatrices = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLD_MATRIX_ARRAY_3x4, mBoneCount); - mParamBlendMat = vsMain->resolveLocalParameter(GCT_MATRIX_3X4, "blendMat"); - return true; -} - -//----------------------------------------------------------------------- -void LinearSkinning::addPositionCalculations(const FunctionStageRef& stage) -{ - // Construct a scaling and shearing matrix based on the blend weights - stage.callFunction("blendBonesMat3x4", - {In(mParamInWorldMatrices), In(mParamInIndices), In(mParamInWeights), Out(mParamBlendMat)}); - - // multiply position with world matrix - stage.callFunction(FFP_FUNC_TRANSFORM, mParamBlendMat, mParamInPosition, Out(mParamInPosition).xyz()); - // set w value to 1 - stage.assign(1, Out(mParamInPosition).w()); -} - -//----------------------------------------------------------------------- -void LinearSkinning::addNormalRelatedCalculations(const FunctionStageRef& stage) -{ - // multiply normal with world matrix and put into temporary param - stage.callFunction(FFP_FUNC_TRANSFORM, mParamBlendMat, mParamInNormal, mParamInNormal); -} -} -} - -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderExLinearSkinning.h b/Components/RTShaderSystem/src/OgreShaderExLinearSkinning.h deleted file mode 100644 index 0d00846d650..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExLinearSkinning.h +++ /dev/null @@ -1,62 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderExLinearSkinning_ -#define _ShaderExLinearSkinning_ - -#include "OgreShaderPrerequisites.h" - -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS -#include "OgreShaderExHardwareSkinningTechnique.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** Implement a sub render state which performs hardware skinning. -Meaning, this sub render states adds calculations which multiply -the points and normals by their assigned bone matricies. -*/ -class LinearSkinning : public HardwareSkinningTechnique -{ - bool resolveParameters(Program* vsProgram) override; - void addPositionCalculations(const FunctionStageRef& stage) override; - void addNormalRelatedCalculations(const FunctionStageRef& stage) override; - - ParameterPtr mParamBlendMat; -}; - -} -} - -#endif -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderExNormalMapLighting.cpp b/Components/RTShaderSystem/src/OgreShaderExNormalMapLighting.cpp deleted file mode 100644 index 07356238572..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExNormalMapLighting.cpp +++ /dev/null @@ -1,360 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderPrecompiledHeaders.h" -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS - -#define SGX_LIB_NORMALMAP "SGXLib_NormalMap" -#define SGX_FUNC_FETCHNORMAL "SGX_FetchNormal" - -namespace Ogre -{ -namespace RTShader -{ - -/************************************************************************/ -/* */ -/************************************************************************/ -const String SRS_NORMALMAP = "NormalMap"; - -//----------------------------------------------------------------------- -NormalMapLighting::NormalMapLighting() -{ - mNormalMapSamplerIndex = -1; - mVSTexCoordSetIndex = 0; - mNormalMapSpace = NMS_TANGENT; - mParallaxHeightScale = 0.04f; -} - -//----------------------------------------------------------------------- -const String& NormalMapLighting::getType() const { return SRS_NORMALMAP; } -//----------------------------------------------------------------------- -bool NormalMapLighting::createCpuSubPrograms(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* psMain = psProgram->getEntryPointFunction(); - - vsProgram->addDependency(SGX_LIB_NORMALMAP); - - psProgram->addDependency(FFP_LIB_TEXTURING); - psProgram->addDependency(SGX_LIB_NORMALMAP); - - if (mNormalMapSpace == NMS_PARALLAX_OCCLUSION) - psProgram->addPreprocessorDefines("POM_LAYER_COUNT=32"); - - // Resolve texture coordinates. - auto vsInTexcoord = vsMain->resolveInputParameter( - Parameter::Content(Parameter::SPC_TEXTURE_COORDINATE0 + mVSTexCoordSetIndex), GCT_FLOAT2); - auto vsOutTexcoord = vsMain->resolveOutputParameter( - Parameter::Content(Parameter::SPC_TEXTURE_COORDINATE0 + mVSTexCoordSetIndex), GCT_FLOAT2); - auto psInTexcoord = psMain->resolveInputParameter(vsOutTexcoord); - - // Resolve normal. - auto vsInNormal = vsMain->resolveInputParameter(Parameter::SPC_NORMAL_OBJECT_SPACE); - auto vsOutNormal = vsMain->resolveOutputParameter(Parameter::SPC_NORMAL_VIEW_SPACE); - auto viewNormal = psMain->resolveInputParameter(vsOutNormal); - auto newViewNormal = psMain->resolveLocalParameter(Parameter::SPC_NORMAL_VIEW_SPACE); - - // Resolve vertex tangent - auto vsInTangent = vsMain->resolveInputParameter(Parameter::SPC_TANGENT_OBJECT_SPACE); - auto vsOutTangent = vsMain->resolveOutputParameter(Parameter::SPC_TANGENT_OBJECT_SPACE); - auto psInTangent = psMain->resolveInputParameter(vsOutTangent); - - // insert before lighting stage - auto vstage = vsMain->getStage(FFP_PS_COLOUR_BEGIN + 1); - auto fstage = psMain->getStage(FFP_PS_COLOUR_BEGIN + 1); - - // Output texture coordinates. - vstage.assign(vsInTexcoord, vsOutTexcoord); - - auto normalMapSampler = psProgram->resolveParameter(GCT_SAMPLER2D, "gNormalMapSampler", mNormalMapSamplerIndex); - - auto psOutTBN = psMain->resolveLocalParameter(GpuConstantType::GCT_MATRIX_3X3, "TBN"); - fstage.callFunction("SGX_CalculateTBN", {In(viewNormal), In(psInTangent), Out(psOutTBN)}); - - if (mNormalMapSpace == NMS_PARALLAX || mNormalMapSpace == NMS_PARALLAX_OCCLUSION) - { - // assuming: lighting stage computed this - auto vsOutViewPos = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_VIEW_SPACE); - auto viewPos = psMain->resolveInputParameter(vsOutViewPos); - - fstage.callFunction("SGX_Generate_Parallax_Texcoord", - {In(normalMapSampler), In(psInTexcoord), In(viewPos), In(mParallaxHeightScale), - In(psOutTBN), Out(psInTexcoord)}); - - // overwrite texcoord0 unconditionally, only one texcoord set is supported with parallax mapping - // we are before FFP_PS_TEXTURING, so the new value will be used - auto texcoord0 = psMain->resolveInputParameter(Parameter::SPC_TEXTURE_COORDINATE0, GCT_FLOAT2); - fstage.assign(psInTexcoord, texcoord0); - } - - // Add the normal fetch function invocation - fstage.callFunction(SGX_FUNC_FETCHNORMAL, normalMapSampler, psInTexcoord, newViewNormal); - - if (mNormalMapSpace & NMS_TANGENT) - { - // transform normal & tangent - auto normalMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_NORMAL_MATRIX); - vstage.callBuiltin("mul", normalMatrix, vsInNormal, vsOutNormal); - vstage.callBuiltin("normalize", vsOutNormal, vsOutNormal); - vstage.callBuiltin("mul", normalMatrix, In(vsInTangent).xyz(), Out(vsOutTangent).xyz()); - vstage.callBuiltin("normalize", In(vsOutTangent).xyz(), Out(vsOutTangent).xyz()); - vstage.assign(In(vsInTangent).w(), Out(vsOutTangent).w()); - - // transform normal - fstage.callBuiltin("mul", psOutTBN, newViewNormal, newViewNormal); - } - else if (mNormalMapSpace & NMS_OBJECT) - { - // transform normal in FS - auto normalMatrix = psProgram->resolveParameter(GpuProgramParameters::ACT_NORMAL_MATRIX); - fstage.callBuiltin("mul", normalMatrix, newViewNormal, newViewNormal); - } - - return true; -} - -//----------------------------------------------------------------------- -void NormalMapLighting::copyFrom(const SubRenderState& rhs) -{ - const NormalMapLighting& rhsLighting = static_cast(rhs); - - mNormalMapSpace = rhsLighting.mNormalMapSpace; - mNormalMapSamplerIndex = rhsLighting.mNormalMapSamplerIndex; - mParallaxHeightScale = rhsLighting.mParallaxHeightScale; -} - -//----------------------------------------------------------------------- -bool NormalMapLighting::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) -{ - if (mNormalMapSamplerIndex >= 0) - { - mVSTexCoordSetIndex = srcPass->getTextureUnitState(mNormalMapSamplerIndex)->getTextureCoordSet(); - return true; - } - - return false; -} - -bool NormalMapLighting::setParameter(const String& name, const String& value) -{ - if (name == "normalmap_space") - { - // Normal map defines normals in tangent space. - if (value == "tangent_space") - { - setNormalMapSpace(NMS_TANGENT); - return true; - } - // Normal map defines normals in object space. - if (value == "object_space") - { - setNormalMapSpace(NMS_OBJECT); - return true; - } - if (value == "parallax") - { - setNormalMapSpace(NMS_PARALLAX); - return true; - } - if (value == "parallax_occlusion") - { - setNormalMapSpace(NMS_PARALLAX_OCCLUSION); - return true; - } - return false; - } - - if (name == "texture_index") - { - return StringConverter::parse(value, mNormalMapSamplerIndex); - } - - if (name == "height_scale") - { - return StringConverter::parse(value, mParallaxHeightScale); - } - - return false; -} - -//----------------------------------------------------------------------- -const String& NormalMapLightingFactory::getType() const { return SRS_NORMALMAP; } - -//----------------------------------------------------------------------- -SubRenderState* NormalMapLightingFactory::createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, - Pass* pass, SGScriptTranslator* translator) -{ - if (prop->name == "lighting_stage") - { - if (prop->values.size() >= 2) - { - AbstractNodeList::const_iterator it = prop->values.begin(); - - // Case light model type is normal map - if ((*it)->getString() == "normal_map") - { - ++it; - SubRenderState* subRenderState = createOrRetrieveInstance(translator); - - TextureUnitState* normalMapTexture = pass->createTextureUnitState(); - uint16 texureIdx = pass->getNumTextureUnitStates() - 1; - normalMapTexture->setTextureName((*it)->getString()); - subRenderState->setParameter("texture_index", std::to_string(texureIdx)); - - ShaderGenerator::_markNonFFP(normalMapTexture); - - // Read normal map space type. - if (prop->values.size() >= 3) - { - ++it; - if (!subRenderState->setParameter("normalmap_space", (*it)->getString())) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - } - - // Read texture coordinate index. - if (prop->values.size() >= 4) - { - unsigned int textureCoordinateIndex = 0; - - ++it; - if (SGScriptTranslator::getUInt(*it, &textureCoordinateIndex)) - { - normalMapTexture->setTextureCoordSet(textureCoordinateIndex); - } - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, prop->file, prop->line, - "use the texture_unit format to specify tex_coord_set and sampler_ref"); - } - - // Read texture filtering format. - if (prop->values.size() >= 5) - { - ++it; - // sampler reference - if (auto sampler = TextureManager::getSingleton().getSampler((*it)->getString())) - { - normalMapTexture->setSampler(sampler); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - } - - return subRenderState; - } - } - } - return NULL; -} - -SubRenderState* NormalMapLightingFactory::createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, - TextureUnitState* texState, SGScriptTranslator* translator) -{ - if (prop->name == "normal_map" && !prop->values.empty()) - { - auto pass = texState->getParent(); - auto texureIdx = pass->getTextureUnitStateIndex(texState); - - // blacklist from FFP - ShaderGenerator::_markNonFFP(texState); - - SubRenderState* subRenderState = createOrRetrieveInstance(translator); - subRenderState->setParameter("texture_index", std::to_string(texureIdx)); - - auto it = prop->values.begin(); - if (!subRenderState->setParameter("normalmap_space", (*it)->getString())) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - return subRenderState; - } - - if (prop->values.size() % 2 != 1) // parameters must come in pairs now - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line); - return subRenderState; - } - - it++; - while(it != prop->values.end()) - { - String paramName = (*it)->getString(); - String paramValue = (*++it)->getString(); - - if (!subRenderState->setParameter(paramName, paramValue)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - return subRenderState; - } - it++; - } - - return subRenderState; - } - - return NULL; -} - -//----------------------------------------------------------------------- -void NormalMapLightingFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, - const TextureUnitState* srcTex, const TextureUnitState* dstTex) -{ - NormalMapLighting* normalMapSubRenderState = static_cast(subRenderState); - - auto textureIdx = srcTex->getParent()->getTextureUnitStateIndex(srcTex); - if(textureIdx != normalMapSubRenderState->getNormalMapSamplerIndex()) - return; - - ser->writeAttribute(5, "normal_map"); - - switch (normalMapSubRenderState->getNormalMapSpace()) - { - case NormalMapLighting::NMS_TANGENT: - ser->writeValue("tangent_space"); - break; - case NormalMapLighting::NMS_OBJECT: - ser->writeValue("object_space"); - break; - case NormalMapLighting::NMS_PARALLAX: - ser->writeValue("parallax"); - break; - case NormalMapLighting::NMS_PARALLAX_OCCLUSION: - ser->writeValue("parallax_occlusion"); - break; - } -} - -//----------------------------------------------------------------------- -SubRenderState* NormalMapLightingFactory::createInstanceImpl() { return OGRE_NEW NormalMapLighting; } - -} // namespace RTShader -} // namespace Ogre - -#endif \ No newline at end of file diff --git a/Components/RTShaderSystem/src/OgreShaderExNormalMapLighting.h b/Components/RTShaderSystem/src/OgreShaderExNormalMapLighting.h deleted file mode 100644 index 0428d5098f0..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExNormalMapLighting.h +++ /dev/null @@ -1,155 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderExNormalMapLighting_ -#define _ShaderExNormalMapLighting_ - -#include "OgreShaderPrerequisites.h" -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS -#include "OgreShaderExPerPixelLighting.h" -#include "OgreLight.h" -#include "OgreCommon.h" -#include "OgreShaderFFPRenderState.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -class NormalMapLighting : public SubRenderState -{ - -// Interface. -public: - /** Class default constructor */ - NormalMapLighting(); - - /** - @see SubRenderState::getType. - */ - const String& getType() const override; - - int getExecutionOrder() const override { return FFP_LIGHTING - 1; } - - /** - @see SubRenderState::copyFrom. - */ - void copyFrom(const SubRenderState& rhs) override; - - - /** - @see SubRenderState::preAddToRenderState. - */ - bool preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) override; - - enum NormalMapSpace - { - NMS_OBJECT = 1, - NMS_TANGENT = 2, - NMS_PARALLAX = 6, - NMS_PARALLAX_OCCLUSION = 7 - }; - - /** - Set the normal map space. - @param normalMapSpace The normal map space. - */ - void setNormalMapSpace(NormalMapSpace normalMapSpace) { mNormalMapSpace = normalMapSpace; } - - /** Return the normal map space. */ - NormalMapSpace getNormalMapSpace() const { return mNormalMapSpace; } - - int getNormalMapSamplerIndex() const { return mNormalMapSamplerIndex; } - - bool setParameter(const String& name, const String& value) override; - -// Protected methods -protected: - bool createCpuSubPrograms(ProgramSet* programSet) override; - -// Attributes. -protected: - // Normal map texture sampler index. - int mNormalMapSamplerIndex; - // Vertex shader input texture coordinate set index. - unsigned int mVSTexCoordSetIndex; - // The normal map space. - NormalMapSpace mNormalMapSpace; - // Parallax mapping scale - float mParallaxHeightScale; -}; - - -/** -A factory that enables creation of NormalMapLighting instances. -@remarks Sub class of SubRenderStateFactory -*/ -class NormalMapLightingFactory : public SubRenderStateFactory -{ -public: - - /** - @see SubRenderStateFactory::getType. - */ - const String& getType() const override; - - /** - @see SubRenderStateFactory::createInstance. - */ - SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) override; - - SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, TextureUnitState* texState, SGScriptTranslator* translator) override; - - /** - @see SubRenderStateFactory::writeInstance. - */ - void writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, const TextureUnitState* srcTex, const TextureUnitState* dstTex) override; - - -protected: - - /** - @see SubRenderStateFactory::createInstanceImpl. - */ - SubRenderState* createInstanceImpl() override; - - -}; - -/** @} */ -/** @} */ - -} -} - -#endif -#endif - diff --git a/Components/RTShaderSystem/src/OgreShaderExPerPixelLighting.cpp b/Components/RTShaderSystem/src/OgreShaderExPerPixelLighting.cpp deleted file mode 100644 index c7ac122731d..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExPerPixelLighting.cpp +++ /dev/null @@ -1,346 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderPrecompiledHeaders.h" -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS - -namespace Ogre { -namespace RTShader { - -/************************************************************************/ -/* */ -/************************************************************************/ -const String SRS_PER_PIXEL_LIGHTING = "SGX_PerPixelLighting"; - -//----------------------------------------------------------------------- -const String& PerPixelLighting::getType() const -{ - return SRS_PER_PIXEL_LIGHTING; -} - -bool PerPixelLighting::setParameter(const String& name, const String& value) -{ - if(name == "two_sided") - { - return StringConverter::parse(value, mTwoSidedLighting); - } - - return FFPLighting::setParameter(name, value); -} - -//----------------------------------------------------------------------- -bool PerPixelLighting::resolveParameters(ProgramSet* programSet) -{ - if (false == resolveGlobalParameters(programSet)) - return false; - - if (false == resolvePerLightParameters(programSet)) - return false; - - return true; -} - -//----------------------------------------------------------------------- -bool PerPixelLighting::resolveGlobalParameters(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Function* psMain = psProgram->getEntryPointFunction(); - - // Resolve world view IT matrix. - mWorldViewITMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_NORMAL_MATRIX); - - // Get surface ambient colour if need to. - if ((mTrackVertexColourType & TVC_AMBIENT) == 0) - { - mDerivedAmbientLightColour = psProgram->resolveParameter(GpuProgramParameters::ACT_DERIVED_AMBIENT_LIGHT_COLOUR); - } - else - { - mLightAmbientColour = psProgram->resolveParameter(GpuProgramParameters::ACT_AMBIENT_LIGHT_COLOUR); - } - - // Get surface emissive colour if need to. - if ((mTrackVertexColourType & TVC_EMISSIVE) == 0) - { - mSurfaceEmissiveColour = psProgram->resolveParameter(GpuProgramParameters::ACT_SURFACE_EMISSIVE_COLOUR); - } - - // Get derived scene colour. - mDerivedSceneColour = psProgram->resolveParameter(GpuProgramParameters::ACT_DERIVED_SCENE_COLOUR); - - mViewNormal = psMain->getLocalParameter(Parameter::SPC_NORMAL_VIEW_SPACE); - - if(!mViewNormal) - { - // Resolve input vertex shader normal. - mVSInNormal = vsMain->resolveInputParameter(Parameter::SPC_NORMAL_OBJECT_SPACE); - - // Resolve output vertex shader normal. - mVSOutNormal = vsMain->resolveOutputParameter(Parameter::SPC_NORMAL_VIEW_SPACE); - - // Resolve input pixel shader normal. - mViewNormal = psMain->resolveInputParameter(mVSOutNormal); - } - - mInDiffuse = psMain->getInputParameter(Parameter::SPC_COLOR_DIFFUSE); - if (mInDiffuse.get() == NULL) - { - mInDiffuse = psMain->getLocalParameter(Parameter::SPC_COLOR_DIFFUSE); - } - - OgreAssert(mInDiffuse, "mInDiffuse is NULL"); - - mOutDiffuse = psMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE); - - if (mSpecularEnable) - { - // Get surface shininess. - mSurfaceShininess = psProgram->resolveParameter(GpuProgramParameters::ACT_SURFACE_SHININESS); - - mOutSpecular = psMain->resolveLocalParameter(Parameter::SPC_COLOR_SPECULAR); - - mVSInPosition = vsMain->getLocalParameter(Parameter::SPC_POSITION_OBJECT_SPACE); - if(!mVSInPosition) - mVSInPosition = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE); - - mVSOutViewPos = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_VIEW_SPACE); - - mViewPos = psMain->resolveInputParameter(mVSOutViewPos); - - mWorldViewMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLDVIEW_MATRIX); - } - - if(mLtcLUT1SamplerIndex > -1) - { - mLTCLUT1 = psProgram->resolveParameter(GCT_SAMPLER2D, "ltcLUT1Sampler", mLtcLUT1SamplerIndex); - mLTCLUT2 = psProgram->resolveParameter(GCT_SAMPLER2D, "ltcLUT2Sampler", mLtcLUT1SamplerIndex + 1); - } - - return true; -} - -//----------------------------------------------------------------------- -bool PerPixelLighting::resolvePerLightParameters(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Function* psMain = psProgram->getEntryPointFunction(); - - // Resolve per light parameters. - mPositions = psProgram->resolveParameter(GpuProgramParameters::ACT_LIGHT_POSITION_VIEW_SPACE_ARRAY, mLightCount); - mDirections = psProgram->resolveParameter(GpuProgramParameters::ACT_LIGHT_DIRECTION_VIEW_SPACE_ARRAY, mLightCount); - mAttenuatParams = psProgram->resolveParameter(GpuProgramParameters::ACT_LIGHT_ATTENUATION_ARRAY, mLightCount); - mSpotParams = psProgram->resolveParameter(GpuProgramParameters::ACT_SPOTLIGHT_PARAMS_ARRAY, mLightCount); - - // Resolve diffuse colour. - if ((mTrackVertexColourType & TVC_DIFFUSE) == 0) - { - mDiffuseColours = psProgram->resolveParameter(GpuProgramParameters::ACT_DERIVED_LIGHT_DIFFUSE_COLOUR_ARRAY, mLightCount); - } - else - { - mDiffuseColours = psProgram->resolveParameter(GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR_POWER_SCALED_ARRAY, mLightCount); - } - - if (mSpecularEnable) - { - // Resolve specular colour. - if ((mTrackVertexColourType & TVC_SPECULAR) == 0) - { - mSpecularColours = psProgram->resolveParameter(GpuProgramParameters::ACT_DERIVED_LIGHT_SPECULAR_COLOUR_ARRAY, mLightCount); - } - else - { - mSpecularColours = psProgram->resolveParameter(GpuProgramParameters::ACT_LIGHT_SPECULAR_COLOUR_POWER_SCALED_ARRAY, mLightCount); - } - } - - //if (needViewPos) - { - mWorldViewMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLDVIEW_MATRIX); - if(!mVSInPosition) - mVSInPosition = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE); - mVSOutViewPos = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_VIEW_SPACE); - - mViewPos = psMain->resolveInputParameter(mVSOutViewPos); - } - - if(mTwoSidedLighting) - { - mFrontFacing = psMain->resolveInputParameter(Parameter::SPC_FRONT_FACING); - mTargetFlipped = psProgram->resolveParameter(GpuProgramParameters::ACT_RENDER_TARGET_FLIPPING); - } - - return true; -} - -//----------------------------------------------------------------------- -bool PerPixelLighting::resolveDependencies(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - - vsProgram->addDependency(FFP_LIB_TRANSFORM); - vsProgram->addDependency(SGX_LIB_PERPIXELLIGHTING); - - psProgram->addDependency(SGX_LIB_PERPIXELLIGHTING); - - addDefines(psProgram); - - if(mLtcLUT1SamplerIndex > -1) - psProgram->addPreprocessorDefines("HAVE_AREA_LIGHTS"); - - return true; -} - -//----------------------------------------------------------------------- -bool PerPixelLighting::addFunctionInvocations(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* psMain = psProgram->getEntryPointFunction(); - - // Add the global illumination functions. - addVSInvocation(vsMain->getStage(FFP_VS_LIGHTING)); - - auto stage = psMain->getStage(FFP_PS_COLOUR_BEGIN + 1); - // Add the global illumination functions. - addPSGlobalIlluminationInvocation(stage); - - if(mFrontFacing) - stage.callFunction("SGX_Flip_Backface_Normal", mFrontFacing, mTargetFlipped, mViewNormal); - - mShadowFactor = psMain->getLocalParameter("lShadowFactor"); - - // Add per light functions. - for (int i = 0; i < mLightCount; i++) - { - addIlluminationInvocation(i, stage); - } - - // Assign back temporary variables - stage.assign(mOutDiffuse, mInDiffuse); - - return true; -} - -//----------------------------------------------------------------------- -void PerPixelLighting::addVSInvocation(const FunctionStageRef& stage) -{ - // Transform normal in view space. - if(mLightCount && mVSInNormal) - stage.callBuiltin("mul", mWorldViewITMatrix, mVSInNormal, mVSOutNormal); - - // Transform view space position if need to. - if (mVSOutViewPos) - { - stage.callFunction(FFP_FUNC_TRANSFORM, mWorldViewMatrix, mVSInPosition, mVSOutViewPos); - } -} - - -//----------------------------------------------------------------------- -void PerPixelLighting::addPSGlobalIlluminationInvocation(const FunctionStageRef& stage) -{ - if ((mTrackVertexColourType & TVC_AMBIENT) == 0 && - (mTrackVertexColourType & TVC_EMISSIVE) == 0) - { - stage.assign(mDerivedSceneColour, mOutDiffuse); - } - else - { - if (mTrackVertexColourType & TVC_AMBIENT) - { - stage.mul(mLightAmbientColour, mInDiffuse, mOutDiffuse); - } - else - { - stage.assign(mDerivedAmbientLightColour, mOutDiffuse); - } - - if (mTrackVertexColourType & TVC_EMISSIVE) - { - stage.add(In(mInDiffuse).xyz(), In(mOutDiffuse).xyz(), Out(mOutDiffuse).xyz()); - } - else - { - stage.add(mSurfaceEmissiveColour, mOutDiffuse, mOutDiffuse); - } - } -} - -//----------------------------------------------------------------------- -const String& PerPixelLightingFactory::getType() const -{ - return SRS_PER_PIXEL_LIGHTING; -} - -//----------------------------------------------------------------------- -SubRenderState* PerPixelLightingFactory::createInstance(ScriptCompiler* compiler, - PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) -{ - if (prop->name != "lighting_stage" || prop->values.empty()) - return NULL; - - auto it = prop->values.begin(); - if((*it++)->getString() != "per_pixel") - return NULL; - - auto ret = createOrRetrieveInstance(translator); - - // process the flags - while(it != prop->values.end()) - { - const String& val = (*it++)->getString(); - if (!ret->setParameter(val, "true")) - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, val); - } - - return ret; -} - -//----------------------------------------------------------------------- -void PerPixelLightingFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, - Pass* srcPass, Pass* dstPass) -{ - ser->writeAttribute(4, "lighting_stage"); - ser->writeValue("per_pixel"); -} - -//----------------------------------------------------------------------- -SubRenderState* PerPixelLightingFactory::createInstanceImpl() -{ - return OGRE_NEW PerPixelLighting; -} - -} -} - -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderExPerPixelLighting.h b/Components/RTShaderSystem/src/OgreShaderExPerPixelLighting.h deleted file mode 100644 index 071cf99b002..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExPerPixelLighting.h +++ /dev/null @@ -1,149 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderExPerPixelLighting_ -#define _ShaderExPerPixelLighting_ - -#include "OgreShaderPrerequisites.h" -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS -#include "OgreShaderFFPLighting.h" -#include "OgreLight.h" -#include "OgreCommon.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** Per pixel Lighting extension sub render state implementation. -Derives from SubRenderState class. -*/ -class PerPixelLighting : public FFPLighting -{ - -// Interface. -public: - /** - @see SubRenderState::getType. - */ - const String& getType() const override; - - bool setParameter(const String& name, const String& value) override; - -// Protected methods -protected: - /** - @see SubRenderState::resolveParameters. - */ - bool resolveParameters(ProgramSet* programSet) override; - - /** Resolve global lighting parameters */ - virtual bool resolveGlobalParameters(ProgramSet* programSet); - - /** Resolve per light parameters */ - virtual bool resolvePerLightParameters(ProgramSet* programSet); - - /** - @see SubRenderState::resolveDependencies. - */ - bool resolveDependencies(ProgramSet* programSet) override; - - /** - @see SubRenderState::addFunctionInvocations. - */ - bool addFunctionInvocations(ProgramSet* programSet) override; - - - /** - Internal method that adds related vertex shader functions invocations. - */ - void addVSInvocation(const FunctionStageRef& stage); - - - /** - Internal method that adds global illumination component functions invocations. - */ - void addPSGlobalIlluminationInvocation(const FunctionStageRef& stage); - -// Attributes. -protected: - // Vertex shader output view position (position in camera space) parameter. - ParameterPtr mVSOutViewPos; - // Vertex shader output normal. - ParameterPtr mVSOutNormal; - ParameterPtr mFrontFacing; - ParameterPtr mTargetFlipped; -}; - - -/** -A factory that enables creation of PerPixelLighting instances. -@remarks Sub class of SubRenderStateFactory -*/ -class PerPixelLightingFactory : public SubRenderStateFactory -{ -public: - - /** - @see SubRenderStateFactory::getType. - */ - const String& getType() const override; - - /** - @see SubRenderStateFactory::createInstance. - */ - SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) override; - - /** - @see SubRenderStateFactory::writeInstance. - */ - void writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, Pass* dstPass) override; - - -protected: - - /** - @see SubRenderStateFactory::createInstanceImpl. - */ - SubRenderState* createInstanceImpl() override; - - -}; - -/** @} */ -/** @} */ - -} -} - -#endif -#endif - diff --git a/Components/RTShaderSystem/src/OgreShaderExTriplanarTexturing.cpp b/Components/RTShaderSystem/src/OgreShaderExTriplanarTexturing.cpp deleted file mode 100644 index 8e8590ababc..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExTriplanarTexturing.cpp +++ /dev/null @@ -1,263 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderPrecompiledHeaders.h" -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS - -#define SGX_FUNC_TRIPLANAR_TEXTURING "SGX_TriplanarTexturing" - -namespace Ogre { -namespace RTShader { - - String TriplanarTexturing::type = "SGX_TriplanarTexturing"; - const String SRS_TRIPLANAR_TEXTURING = "SGX_TriplanarTexturing"; - - //----------------------------------------------------------------------- - - bool TriplanarTexturing::resolveParameters(ProgramSet* programSet) - { - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Function* psMain = psProgram->getEntryPointFunction(); - - // Resolve input vertex shader normal. - mVSInNormal = vsMain->resolveInputParameter(Parameter::SPC_NORMAL_OBJECT_SPACE); - - // Resolve output vertex shader normal. - mVSOutNormal = vsMain->resolveOutputParameter(Parameter::SPC_NORMAL_OBJECT_SPACE); - - // Resolve pixel shader output diffuse color. - mPSInDiffuse = psMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE); - - // Resolve input pixel shader normal. - mPSInNormal = psMain->resolveInputParameter(mVSOutNormal); - - // Resolve input vertex shader normal. - mVSInPosition = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE); - - mVSOutPosition = vsMain->resolveOutputParameter(Parameter::SPS_TEXTURE_COORDINATES, -1, Parameter::SPC_POSITION_OBJECT_SPACE, GCT_FLOAT4); - mPSInPosition = psMain->resolveInputParameter(mVSOutPosition); - - mSamplerFromX = psProgram->resolveParameter(GCT_SAMPLER2D, "tp_sampler_from_x", mTextureSamplerIndexFromX); - if (mSamplerFromX.get() == NULL) - return false; - - mSamplerFromY = psProgram->resolveParameter(GCT_SAMPLER2D, "tp_sampler_from_y", mTextureSamplerIndexFromY); - if (mSamplerFromY.get() == NULL) - return false; - - mSamplerFromZ = psProgram->resolveParameter(GCT_SAMPLER2D, "tp_sampler_from_z", mTextureSamplerIndexFromZ); - if (mSamplerFromZ.get() == NULL) - return false; - - mPSOutDiffuse = psMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE); - if (mPSOutDiffuse.get() == NULL) - return false; - - mPSTPParams = psProgram->resolveParameter(GCT_FLOAT3, "gTPParams"); - if (mPSTPParams.get() == NULL) - return false; - return true; - } - - //----------------------------------------------------------------------- - bool TriplanarTexturing::resolveDependencies(ProgramSet* programSet) - { - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - psProgram->addDependency(FFP_LIB_TEXTURING); - psProgram->addDependency("SGXLib_TriplanarTexturing"); - return true; - } - - //----------------------------------------------------------------------- - bool TriplanarTexturing::addFunctionInvocations(ProgramSet* programSet) - { - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* psMain = psProgram->getEntryPointFunction(); - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - - auto vsStage = vsMain->getStage(FFP_PS_TEXTURING); - vsStage.assign(mVSInNormal, mVSOutNormal); - vsStage.assign(mVSInPosition, mVSOutPosition); - - psMain->getStage(FFP_PS_TEXTURING) - .callFunction("SGX_TriplanarTexturing", - {In(mPSInDiffuse), In(mPSInNormal), In(mPSInPosition), In(mSamplerFromX), - In(mSamplerFromY), In(mSamplerFromZ), In(mPSTPParams), Out(mPSOutDiffuse)}); - - return true; - } - - //----------------------------------------------------------------------- - const String& TriplanarTexturing::getType() const - { - return SRS_TRIPLANAR_TEXTURING; - } - - //----------------------------------------------------------------------- - int TriplanarTexturing::getExecutionOrder() const - { - return FFP_TEXTURING; - } - - //----------------------------------------------------------------------- - bool TriplanarTexturing::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass ) - { - TextureUnitState* textureUnit; - - // Create the mapping textures - textureUnit = dstPass->createTextureUnitState(); - textureUnit->setTextureName(mTextureNameFromX); - mTextureSamplerIndexFromX = dstPass->getNumTextureUnitStates() - 1; - - textureUnit = dstPass->createTextureUnitState(); - textureUnit->setTextureName(mTextureNameFromY); - mTextureSamplerIndexFromY = dstPass->getNumTextureUnitStates() - 1; - - textureUnit = dstPass->createTextureUnitState(); - textureUnit->setTextureName(mTextureNameFromZ); - mTextureSamplerIndexFromZ = dstPass->getNumTextureUnitStates() - 1; - return true; - } - - //----------------------------------------------------------------------- - void TriplanarTexturing::copyFrom(const SubRenderState& rhs) - { - const TriplanarTexturing& rhsTP = static_cast(rhs); - - mPSOutDiffuse = rhsTP.mPSOutDiffuse; - mPSInDiffuse = rhsTP.mPSInDiffuse; - - mVSOutNormal = rhsTP.mVSOutNormal; - mVSInNormal = rhsTP.mVSInNormal; - mPSInNormal = rhsTP.mPSInNormal; - - mVSOutPosition = rhsTP.mVSOutPosition; - mVSInPosition = rhsTP.mVSInPosition; - mPSInPosition = rhsTP.mPSInPosition; - - mSamplerFromX = rhsTP.mSamplerFromX; - mSamplerFromY = rhsTP.mSamplerFromY; - mSamplerFromZ = rhsTP.mSamplerFromZ; - - mPSTPParams = rhsTP.mPSTPParams; - mParameters = rhsTP.mParameters; - mTextureNameFromX = rhsTP.mTextureNameFromX; - mTextureNameFromY = rhsTP.mTextureNameFromY; - mTextureNameFromZ = rhsTP.mTextureNameFromZ; - } - - //----------------------------------------------------------------------- - void TriplanarTexturing::updateGpuProgramsParams(Renderable* rend, const Pass* pass, const AutoParamDataSource* source, - const LightList* pLightList) - { - mPSTPParams->setGpuParameter(mParameters); - } - - void TriplanarTexturing::setParameter(const String& name, const Any& value) - { - if (name == "parameters") - { - mParameters = any_cast(value); - return; - } - else if (name == "texture_names") - { - const StringVector& textureNames = any_cast(value); - if (textureNames.size() == 3) - { - mTextureNameFromX = textureNames[0]; - mTextureNameFromY = textureNames[1]; - mTextureNameFromZ = textureNames[2]; - return; - } - } - SubRenderState::setParameter(name, value); - } - - //----------------------------------------------------------------------- - const String& TriplanarTexturingFactory::getType() const - { - return SRS_TRIPLANAR_TEXTURING; - } - - //----------------------------------------------------------------------- - SubRenderState* TriplanarTexturingFactory::createInstance(ScriptCompiler* compiler, - PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) - { - if (prop->name == "triplanarTexturing") - { - if (prop->values.size() == 6) - { - SubRenderState* subRenderState = createOrRetrieveInstance(translator); - TriplanarTexturing* tpSubRenderState = static_cast(subRenderState); - - AbstractNodeList::const_iterator it = prop->values.begin(); - float parameters[3]; - if (false == SGScriptTranslator::getFloat(*it, parameters)) - { - return NULL; - } - ++it; - if (false == SGScriptTranslator::getFloat(*it, parameters + 1)) - { - return NULL; - } - ++it; - if (false == SGScriptTranslator::getFloat(*it, parameters + 2)) - { - return NULL; - } - ++it; - Vector3 vParameters(parameters[0], parameters[1], parameters[2]); - tpSubRenderState->setParameter("parameters", vParameters); - - StringVector textureNames = {(*it++)->getString(), (*it++)->getString(), (*it++)->getString()}; - - if(textureNames[0].empty() || textureNames[1].empty() || textureNames[2].empty()) - return NULL; - - tpSubRenderState->setParameter("texture_names", textureNames); - - return subRenderState; - } - } - return NULL; - } - - //----------------------------------------------------------------------- - SubRenderState* TriplanarTexturingFactory::createInstanceImpl() - { - return OGRE_NEW TriplanarTexturing; - } - - -} -} - -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderExTriplanarTexturing.h b/Components/RTShaderSystem/src/OgreShaderExTriplanarTexturing.h deleted file mode 100644 index 8ec6593e18a..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExTriplanarTexturing.h +++ /dev/null @@ -1,214 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderExTriplanarTexturing_ -#define _ShaderExTriplanarTexturing_ - -#include "OgreShaderPrerequisites.h" -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS -#include "OgreShaderSubRenderState.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -class TriplanarTexturing : public SubRenderState -{ - -protected: - - /// Parameters: Texturescale, Plateau-size (0 to 0.57, not bigger to avoid division by zero!), transition-speed - Vector3 mParameters; - - /// Parameters uniform. - UniformParameterPtr mPSTPParams; - - /// Normal vertex shader in. - ParameterPtr mVSInNormal; - - /// Normal vertex shader out. - ParameterPtr mVSOutNormal; - - /// Normal pixel shader in. - ParameterPtr mPSInNormal; - - /// Position vertex shader in. - ParameterPtr mVSInPosition; - - /// Position vertex shader out. - ParameterPtr mVSOutPosition; - - /// Position pixel shader in. - ParameterPtr mPSInPosition; - - /// Texture sampler for the x-direction planar mapping part. - UniformParameterPtr mSamplerFromX; - - /// Texture sampler state for the x-direction planar mapping part. - UniformParameterPtr mSamplerFromXState; - - /// Texture sampler for the y-direction planar mapping part. - UniformParameterPtr mSamplerFromY; - - /// Texture sampler state for the y-direction planar mapping part. - UniformParameterPtr mSamplerFromYState; - - /// Texture sampler for the z-direction planar mapping part. - UniformParameterPtr mSamplerFromZ; - - /// Texture sampler stae for the z-direction planar mapping part. - UniformParameterPtr mSamplerFromZState; - - /// Pixel shader input diffuse colour. - ParameterPtr mPSInDiffuse; - - /// Pixel shader output diffuse colour. - ParameterPtr mPSOutDiffuse; - - /// Texturename mapping from x. - String mTextureNameFromX; - - /// Texture sampler id mapping from x. - ushort mTextureSamplerIndexFromX; - - /// Texturename mapping from y. - String mTextureNameFromY; - - /// Texture sampler id mapping from y. - ushort mTextureSamplerIndexFromY; - - /// Texturename mapping from z. - String mTextureNameFromZ; - - /// Texture sampler id mapping from z. - ushort mTextureSamplerIndexFromZ; - - /** - @see SubRenderState::resolveParameters. - */ - bool resolveParameters(ProgramSet* programSet) override; - - /** - @see SubRenderState::resolveDependencies. - */ - bool resolveDependencies(ProgramSet* programSet) override; - - /** - @see SubRenderState::addFunctionInvocations. - */ - bool addFunctionInvocations(ProgramSet* programSet) override; - -public: - - /// The type. - static String type; - - /** Sets the parameters. - @param parameters - Parameters: Texturescale, Plateau-size (0 to 0.57, not bigger to avoid division by zero!), transition-speed. - - Sets the texture names for the mapping. - @param textureNameFromX - The texture mapping from x. - @param textureNameFromY - The texture mapping from y. - @param textureNameFromZ - The texture mapping from z. - */ - void setParameter(const String& name, const Any& value) override; - - /** - @see SubRenderState::getType. - */ - const String& getType() const override; - - /** - @see SubRenderState::getExecutionOrder. - */ - int getExecutionOrder() const override; - - /** - @see SubRenderState::preAddToRenderState. - */ - bool preAddToRenderState (const RenderState* renderState, Pass* srcPass, Pass* dstPass) override; - - /** - @see SubRenderState::copyFrom. - */ - void copyFrom(const SubRenderState& rhs) override; - - /** - @see SubRenderState::updateGpuProgramsParams. - */ - void updateGpuProgramsParams(Renderable* rend, const Pass* pass, const AutoParamDataSource* source, const LightList* pLightList) override; - -}; - - -/** -A factory that enables creation of TriplanarMapping instances. -@remarks Sub class of SubRenderStateFactory -*/ -class TriplanarTexturingFactory : public SubRenderStateFactory -{ -public: - - /** - @see SubRenderStateFactory::getType. - */ - const String& getType() const override; - - /** - @see SubRenderStateFactory::createInstance. - */ - SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) override; - -protected: - - /** - @see SubRenderStateFactory::createInstanceImpl. - */ - SubRenderState* createInstanceImpl() override; - - - -}; - -/** @} */ -/** @} */ - - -} -} - -#endif -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderExWBOIT.cpp b/Components/RTShaderSystem/src/OgreShaderExWBOIT.cpp deleted file mode 100644 index 515311caaab..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExWBOIT.cpp +++ /dev/null @@ -1,108 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#include "OgreShaderPrecompiledHeaders.h" -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS - -namespace Ogre -{ -namespace RTShader -{ - -/************************************************************************/ -/* */ -/************************************************************************/ -const String SRS_WBOIT = "WBOIT"; - -//----------------------------------------------------------------------- -const String& WBOIT::getType() const { return SRS_WBOIT; } - -//----------------------------------------------------------------------- -int WBOIT::getExecutionOrder() const { return FFP_POST_PROCESS; } - -bool WBOIT::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) -{ - dstPass->setTransparentSortingEnabled(false); - dstPass->setSeparateSceneBlending(SBF_ONE, SBF_ONE, SBF_ZERO, SBF_ONE_MINUS_SOURCE_ALPHA); - return true; -} - -bool WBOIT::createCpuSubPrograms(ProgramSet* programSet) -{ - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - psProgram->addDependency("SGXLib_WBOIT"); - - Function* vsMain = programSet->getCpuProgram(GPT_VERTEX_PROGRAM)->getMain(); - Function* psMain = psProgram->getMain(); - - auto vsOutPos = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_PROJECTIVE_SPACE); - - bool isD3D9 = ShaderGenerator::getSingleton().getTargetLanguage() == "hlsl" && - !GpuProgramManager::getSingleton().isSyntaxSupported("vs_4_0_level_9_1"); - - if (isD3D9) - { - auto vstage = vsMain->getStage(FFP_VS_POST_PROCESS); - auto vsPos = vsMain->resolveOutputParameter(Parameter::SPC_UNKNOWN, GCT_FLOAT4); - vstage.assign(vsOutPos, vsPos); - std::swap(vsOutPos, vsPos); - } - - auto viewPos = psMain->resolveInputParameter(vsOutPos); - - auto accum = psMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE); - auto revealage = psMain->resolveOutputParameter(Parameter::SPC_COLOR_SPECULAR); - - auto stage = psMain->getStage(FFP_PS_POST_PROCESS); - - if (isD3D9) - { - stage.div(viewPos, In(viewPos).w(), viewPos); - } - - stage.callFunction("SGX_WBOIT", {In(viewPos).z(), InOut(accum), Out(revealage)}); - - return true; -} - -//----------------------------------------------------------------------- -const String& WBOITFactory::getType() const { return SRS_WBOIT; } - -//----------------------------------------------------------------------- -SubRenderState* WBOITFactory::createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, - SGScriptTranslator* translator) -{ - if (prop->name != "weighted_blended_oit" || prop->values.empty()) - return NULL; - - auto it = prop->values.begin(); - bool val; - if(!SGScriptTranslator::getBoolean(*it++, &val)) - { - return NULL; - } - - if (!val) - return NULL; - - auto ret = static_cast(createOrRetrieveInstance(translator)); - return ret; -} - -//----------------------------------------------------------------------- -void WBOITFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, - Pass* dstPass) -{ - ser->writeAttribute(4, "weighted_blended_oit"); - ser->writeValue("true"); -} - -//----------------------------------------------------------------------- -SubRenderState* WBOITFactory::createInstanceImpl() { return OGRE_NEW WBOIT; } - -} // namespace RTShader -} // namespace Ogre - -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderExWBOIT.h b/Components/RTShaderSystem/src/OgreShaderExWBOIT.h deleted file mode 100644 index e48cfed7c73..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderExWBOIT.h +++ /dev/null @@ -1,62 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT -#ifndef _ShaderWBOIT_ -#define _ShaderWBOIT_ - -#include "OgreShaderPrerequisites.h" -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS -#include "OgreShaderParameter.h" -#include "OgreShaderSubRenderState.h" - -namespace Ogre -{ -namespace RTShader -{ - -/** \addtogroup Optional - * @{ - */ -/** \addtogroup RTShader - * @{ - */ - -/** Transform sub render state implementation of writing to WBOIT buffers - */ -class WBOIT : public SubRenderState -{ -public: - const String& getType() const override; - int getExecutionOrder() const override; - bool preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) override; - bool createCpuSubPrograms(ProgramSet* programSet) override; - void copyFrom(const SubRenderState& rhs) override {} -}; - -/** -A factory that enables creation of GBuffer instances. -@remarks Sub class of SubRenderStateFactory -*/ -class WBOITFactory : public SubRenderStateFactory -{ -public: - const String& getType() const override; - - SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, - SGScriptTranslator* translator) override; - - void writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, Pass* dstPass) override; - -protected: - SubRenderState* createInstanceImpl() override; -}; - -/** @} */ -/** @} */ - -} // namespace RTShader -} // namespace Ogre - -#endif -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderFFPAlphaTest.cpp b/Components/RTShaderSystem/src/OgreShaderFFPAlphaTest.cpp deleted file mode 100644 index b17f64db2d4..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderFFPAlphaTest.cpp +++ /dev/null @@ -1,117 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderPrecompiledHeaders.h" -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS - -namespace Ogre { - namespace RTShader { - - const String SRS_ALPHA_TEST = "FFP_Alpha_Test"; - - - //----------------------------------------------------------------------- - const Ogre::String& FFPAlphaTest::getType() const - { - return SRS_ALPHA_TEST; - } - - - //----------------------------------------------------------------------- - bool FFPAlphaTest::resolveParameters(ProgramSet* programSet) - { - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* psMain = psProgram->getEntryPointFunction(); - - mPSAlphaRef = psProgram->resolveParameter(GpuProgramParameters::ACT_SURFACE_ALPHA_REJECTION_VALUE); - mPSAlphaFunc = psProgram->resolveParameter(GCT_FLOAT1, "gAlphaFunc"); - - mPSOutDiffuse = psMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE); - - return true; - } - - - - //----------------------------------------------------------------------- - bool FFPAlphaTest::resolveDependencies(ProgramSet* programSet) - { - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - psProgram->addDependency(FFP_LIB_ALPHA_TEST); - return true; - } - - //----------------------------------------------------------------------- - - void FFPAlphaTest::copyFrom( const SubRenderState& rhs ) - { - - } - - bool FFPAlphaTest::addFunctionInvocations( ProgramSet* programSet ) - { - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* psMain = psProgram->getEntryPointFunction(); - - psMain->getStage(FFP_PS_ALPHA_TEST) - .callFunction(FFP_FUNC_ALPHA_TEST, {In(mPSAlphaFunc), In(mPSAlphaRef), In(mPSOutDiffuse)}); - - return true; - } - - int FFPAlphaTest::getExecutionOrder() const - { - return FFP_ALPHA_TEST; - } - - bool FFPAlphaTest::preAddToRenderState( const RenderState* renderState, Pass* srcPass, Pass* dstPass ) - { - return srcPass->getAlphaRejectFunction() != CMPF_ALWAYS_PASS; - } - - void FFPAlphaTest::updateGpuProgramsParams( Renderable* rend, const Pass* pass, const AutoParamDataSource* source, const LightList* pLightList ) - { - mPSAlphaFunc->setGpuParameter((float)pass->getAlphaRejectFunction()); - } - - //----------------------Factory Implementation--------------------------- - //----------------------------------------------------------------------- - const String& FFPAlphaTestFactory ::getType() const - { - return SRS_ALPHA_TEST; - } - - //----------------------------------------------------------------------- - SubRenderState* FFPAlphaTestFactory::createInstanceImpl() - { - return OGRE_NEW FFPAlphaTest; - } - } -} -#endif - - diff --git a/Components/RTShaderSystem/src/OgreShaderFFPAlphaTest.h b/Components/RTShaderSystem/src/OgreShaderFFPAlphaTest.h deleted file mode 100644 index bdba1176a62..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderFFPAlphaTest.h +++ /dev/null @@ -1,117 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rightsA -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _OgreShaderExAlphaTest_ -#define _OgreShaderExAlphaTest_ - -#include "OgreShaderPrerequisites.h" -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS -#include "OgreShaderFFPTexturing.h" -#include "OgreShaderSubRenderState.h" - -namespace Ogre { -namespace RTShader { - - class FFPAlphaTest : public SubRenderState - { - - private: - UniformParameterPtr mPSAlphaRef; - UniformParameterPtr mPSAlphaFunc; - ParameterPtr mPSOutDiffuse; - - - - protected: - - /** - @see SubRenderState::resolveParameters. - */ - bool resolveParameters(ProgramSet* programSet) override; - - /** - @see SubRenderState::resolveDependencies. - */ - bool resolveDependencies(ProgramSet* programSet) override; - - /** - @see SubRenderState::addFunctionInvocations. - */ - bool addFunctionInvocations(ProgramSet* programSet) override; - -public: - /** - @see SubRenderState::getType. - */ - const String& getType() const override; - - /** - @see SubRenderState::getExecutionOrder. - */ - int getExecutionOrder() const override; - - /** - @see SubRenderState::preAddToRenderState. - */ - bool preAddToRenderState (const RenderState* renderState, Pass* srcPass, Pass* dstPass) override; - - /** - @see SubRenderState::copyFrom. - */ - void copyFrom(const SubRenderState& rhs) override; - - /** - @see SubRenderState::updateGpuProgramsParams. - */ - void updateGpuProgramsParams(Renderable* rend, const Pass* pass, const AutoParamDataSource* source, const LightList* pLightList) override; - - }; - -class FFPAlphaTestFactory : public SubRenderStateFactory -{ - -public: -static String Type; - - /** - @see SubRenderStateFactory::getType. - */ - const String& getType() const override; - -protected: - - /** - @see SubRenderStateFactory::createInstanceImpl. - */ - SubRenderState* createInstanceImpl() override; -}; - -} // namespace RTShader -} // namespace Ogre - -#endif -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderFFPColour.cpp b/Components/RTShaderSystem/src/OgreShaderFFPColour.cpp deleted file mode 100644 index f534eb0c8ef..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderFFPColour.cpp +++ /dev/null @@ -1,233 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderPrecompiledHeaders.h" -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS - -namespace Ogre { -namespace RTShader { - -/************************************************************************/ -/* */ -/************************************************************************/ -const String SRS_VERTEX_COLOUR = "FFP_Colour"; - -//----------------------------------------------------------------------- -FFPColour::FFPColour() -{ - mResolveStageFlags = 0; -} - -//----------------------------------------------------------------------- -const String& FFPColour::getType() const -{ - return SRS_VERTEX_COLOUR; -} - - -//----------------------------------------------------------------------- -int FFPColour::getExecutionOrder() const -{ - return FFP_COLOUR; -} - -//----------------------------------------------------------------------- -bool FFPColour::resolveParameters(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Function* psMain = psProgram->getEntryPointFunction(); - - if (mResolveStageFlags & SF_VS_INPUT_DIFFUSE) - mVSInputDiffuse = vsMain->resolveInputParameter(Parameter::SPC_COLOR_DIFFUSE); - - // Resolve VS color outputs if have inputs from vertex stream. - if (mVSInputDiffuse.get() != NULL || mResolveStageFlags & SF_VS_OUTPUT_DIFFUSE) - mVSOutputDiffuse = vsMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE); - - if (mResolveStageFlags & SF_VS_OUTPUT_SPECULAR) - mVSOutputSpecular = vsMain->resolveOutputParameter(Parameter::SPC_COLOR_SPECULAR); - - // Resolve PS color inputs if have inputs from vertex shader. - if (mVSOutputDiffuse.get() != NULL || mResolveStageFlags & SF_PS_INPUT_DIFFUSE) - mPSInputDiffuse = psMain->resolveInputParameter(Parameter::SPC_COLOR_DIFFUSE); - - if (mVSOutputSpecular.get() != NULL || mResolveStageFlags & SF_PS_INPUT_SPECULAR) - mPSInputSpecular = psMain->resolveInputParameter(Parameter::SPC_COLOR_SPECULAR); - - - // Resolve PS output diffuse color. - mPSOutputDiffuse = psMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE); - - return true; -} - - -//----------------------------------------------------------------------- -bool FFPColour::resolveDependencies(ProgramSet* programSet) -{ - return true; -} - -//----------------------------------------------------------------------- -bool FFPColour::addFunctionInvocations(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Function* psMain = psProgram->getEntryPointFunction(); - - // Create vertex shader colour invocations. - ParameterPtr vsDiffuse; - ParameterPtr vsSpecular; - - auto vsStage = vsMain->getStage(FFP_VS_COLOUR); - if (mVSInputDiffuse) - { - vsDiffuse = mVSInputDiffuse; - } - else - { - vsDiffuse = vsMain->resolveLocalParameter(Parameter::SPC_COLOR_DIFFUSE); - vsStage.assign(Vector4(1.0), vsDiffuse); - } - - if (mVSOutputDiffuse) - { - vsStage.assign(vsDiffuse, mVSOutputDiffuse); - } - - vsSpecular = vsMain->resolveLocalParameter(Parameter::SPC_COLOR_SPECULAR); - vsStage.assign(Vector4::ZERO, vsSpecular); - - if (mVSOutputSpecular) - { - vsStage.assign(vsSpecular, mVSOutputSpecular); - } - - - - // Create fragment shader colour invocations. - ParameterPtr psDiffuse; - ParameterPtr psSpecular; - auto psStage = psMain->getStage(FFP_PS_COLOUR_BEGIN); - - // Handle diffuse colour. - if (mPSInputDiffuse.get() != NULL) - { - psDiffuse = mPSInputDiffuse; - } - else - { - psDiffuse = psMain->resolveLocalParameter(Parameter::SPC_COLOR_DIFFUSE); - psStage.assign(Vector4(1.0), psDiffuse); - } - - // Handle specular colour. - if (mPSInputSpecular) - { - psSpecular = mPSInputSpecular; - } - else - { - psSpecular = psMain->resolveLocalParameter(Parameter::SPC_COLOR_SPECULAR); - psStage.assign(Vector4::ZERO, psSpecular); - } - - // Assign diffuse colour. - psStage.assign(psDiffuse, mPSOutputDiffuse); - - // Add specular to out colour. - psMain->getStage(FFP_PS_COLOUR_END) - .add(In(mPSOutputDiffuse).xyz(), In(psSpecular).xyz(), Out(mPSOutputDiffuse).xyz()); - - return true; -} - - -//----------------------------------------------------------------------- -void FFPColour::copyFrom(const SubRenderState& rhs) -{ - const FFPColour& rhsColour = static_cast(rhs); - - setResolveStageFlags(rhsColour.mResolveStageFlags); -} - -//----------------------------------------------------------------------- -bool FFPColour::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) -{ - TrackVertexColourType trackColour = srcPass->getVertexColourTracking(); - - if (trackColour != 0) - addResolveStageMask(FFPColour::SF_VS_INPUT_DIFFUSE); - - return true; -} - -//----------------------------------------------------------------------- -const String& FFPColourFactory::getType() const -{ - return SRS_VERTEX_COLOUR; -} - -//----------------------------------------------------------------------- -SubRenderState* FFPColourFactory::createInstance(ScriptCompiler* compiler, - PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) -{ - if (prop->name == "colour_stage") - { - if(prop->values.size() == 1) - { - if (prop->values.front()->getString() == "ffp") - { - return createOrRetrieveInstance(translator); - } - } - } - - return NULL; -} - -//----------------------------------------------------------------------- -void FFPColourFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, - Pass* srcPass, Pass* dstPass) -{ - ser->writeAttribute(4, "colour_stage"); - ser->writeValue("ffp"); -} - -//----------------------------------------------------------------------- -SubRenderState* FFPColourFactory::createInstanceImpl() -{ - return OGRE_NEW FFPColour; -} - - -} -} - -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderFFPColour.h b/Components/RTShaderSystem/src/OgreShaderFFPColour.h deleted file mode 100644 index b333781ce81..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderFFPColour.h +++ /dev/null @@ -1,176 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderFFPColur_ -#define _ShaderFFPColur_ - -#include "OgreShaderPrerequisites.h" -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS -#include "OgreShaderSubRenderState.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -class FFPColour : public SubRenderState -{ -public: - - // Parameter stage flags of the colour component. - enum StageFlags - { - SF_VS_INPUT_DIFFUSE = 1 << 1, - SF_VS_OUTPUT_DIFFUSE = 1 << 2, - SF_VS_OUTPUT_SPECULAR = 1 << 3, - SF_PS_INPUT_DIFFUSE = 1 << 4, - SF_PS_INPUT_SPECULAR = 1 << 5 - }; - -// Interface. -public: - - /** Class default constructor */ - FFPColour(); - - - /** - @see SubRenderState::getType. - */ - const String& getType() const override; - - /** - @see SubRenderState::getType. - */ - int getExecutionOrder() const override; - - /** - @see SubRenderState::copyFrom. - */ - void copyFrom(const SubRenderState& rhs) override; - - /** - @see SubRenderState::preAddToRenderState. - */ - bool preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) override; - - /** - Set the resolve stage flags that this sub render state will produce. - I.E - If one want to specify that the vertex shader program needs to get a diffuse component - and the pixel shader should output diffuse component he should pass SF_VS_INPUT_DIFFUSE. - @param flags The stage flag to set. - */ - void setResolveStageFlags(unsigned int flags) { mResolveStageFlags = flags; } - - /** - Get the current resolve stage flags. - */ - unsigned int getResolveStageFlags() const { return mResolveStageFlags; } - - /** - Add the given mask to resolve stage flags that this sub render state will produce. - @param mask The mask to add to current flag set. - */ - void addResolveStageMask(unsigned int mask) { mResolveStageFlags |= mask; } - - /** - Remove the given mask from the resolve stage flags that this sub render state will produce. - @param mask The mask to remove from current flag set. - */ - void removeResolveStageMask(unsigned int mask) { mResolveStageFlags &= ~mask; } - -// Protected methods -protected: - bool resolveParameters(ProgramSet* programSet) override; - bool resolveDependencies(ProgramSet* programSet) override; - bool addFunctionInvocations(ProgramSet* programSet) override; - -// Attributes. -protected: - // Vertex shader input diffuse component. - ParameterPtr mVSInputDiffuse; - // Vertex shader output diffuse component. - ParameterPtr mVSOutputDiffuse; - // Vertex shader input specular component. - ParameterPtr mVSOutputSpecular; - // Pixel shader input diffuse component. - ParameterPtr mPSInputDiffuse; - // Pixel shader input specular component. - ParameterPtr mPSInputSpecular; - // Pixel shader output diffuse component. - ParameterPtr mPSOutputDiffuse; - // Stage flags that defines resolve parameters definitions. - unsigned int mResolveStageFlags; -}; - - -/** -A factory that enables creation of FFPColour instances. -@remarks Sub class of SubRenderStateFactory -*/ -class FFPColourFactory : public SubRenderStateFactory -{ -public: - - /** - @see SubRenderStateFactory::getType. - */ - const String& getType() const override; - - /** - @see SubRenderStateFactory::createInstance. - */ - SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) override; - - /** - @see SubRenderStateFactory::writeInstance. - */ - void writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, Pass* dstPass) override; - - -protected: - - /** - @see SubRenderStateFactory::createInstanceImpl. - */ - SubRenderState* createInstanceImpl() override; - - -}; - -/** @} */ -/** @} */ - -} -} - -#endif -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderFFPFog.cpp b/Components/RTShaderSystem/src/OgreShaderFFPFog.cpp deleted file mode 100644 index 2d63684d139..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderFFPFog.cpp +++ /dev/null @@ -1,264 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderPrecompiledHeaders.h" -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS - -namespace Ogre { -namespace RTShader { - -/************************************************************************/ -/* */ -/************************************************************************/ -const String SRS_FOG = "FFP_Fog"; - -//----------------------------------------------------------------------- -FFPFog::FFPFog() -{ - mFogMode = FOG_NONE; - mCalcMode = CM_PER_VERTEX; -} - -//----------------------------------------------------------------------- -const String& FFPFog::getType() const -{ - return SRS_FOG; -} - -//----------------------------------------------------------------------- -int FFPFog::getExecutionOrder() const -{ - return FFP_FOG; -} - -//----------------------------------------------------------------------- -bool FFPFog::resolveParameters(ProgramSet* programSet) -{ - if (mFogMode == FOG_NONE) - return true; - - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Function* psMain = psProgram->getEntryPointFunction(); - - // Resolve vertex shader output position. - mVSOutPos = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_PROJECTIVE_SPACE); - - // Resolve fog colour. - mFogColour = psProgram->resolveParameter(GpuProgramParameters::ACT_FOG_COLOUR); - - // Resolve pixel shader output diffuse color. - mPSOutDiffuse = psMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE); - - // Per pixel fog. - if (mCalcMode == CM_PER_PIXEL) - { - // Resolve fog params. - mFogParams = psProgram->resolveParameter(GpuProgramParameters::ACT_FOG_PARAMS); - - // Resolve vertex shader output depth. - mVSOutDepth = vsMain->resolveOutputParameter(Parameter::SPC_DEPTH_VIEW_SPACE); - - // Resolve pixel shader input depth. - mPSInDepth = psMain->resolveInputParameter(mVSOutDepth); - } - // Per vertex fog. - else - { - // Resolve fog params. - mFogParams = vsProgram->resolveParameter(GpuProgramParameters::ACT_FOG_PARAMS); - - // Resolve vertex shader output fog factor. - mVSOutFogFactor = vsMain->resolveOutputParameter(Parameter::SPC_UNKNOWN, GCT_FLOAT1); - - // Resolve pixel shader input fog factor. - mPSInFogFactor = psMain->resolveInputParameter(mVSOutFogFactor); - } - - return true; -} - -//----------------------------------------------------------------------- -bool FFPFog::resolveDependencies(ProgramSet* programSet) -{ - if (mFogMode == FOG_NONE) - return true; - - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - - // Per pixel fog. - if (mCalcMode == CM_PER_PIXEL) - { - psProgram->addDependency(FFP_LIB_FOG); - } - else - { - vsProgram->addDependency(FFP_LIB_FOG); - } - - return true; -} - -//----------------------------------------------------------------------- -bool FFPFog::addFunctionInvocations(ProgramSet* programSet) -{ - if (mFogMode == FOG_NONE) - return true; - - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Function* psMain = psProgram->getEntryPointFunction(); - - // Per pixel fog. - if (mCalcMode == CM_PER_PIXEL) - { - vsMain->getStage(FFP_VS_FOG).assign(In(mVSOutPos).w(), mVSOutDepth); - psProgram->addPreprocessorDefines(StringUtil::format("FOG_TYPE=%d", mFogMode)); - - psMain->getStage(FFP_PS_FOG) - .callFunction("FFP_PixelFog", - {In(mPSInDepth), In(mFogParams), In(mFogColour), In(mPSOutDiffuse), Out(mPSOutDiffuse)}); - } - - // Per vertex fog. - else - { - vsProgram->addPreprocessorDefines(StringUtil::format("FOG_TYPE=%d", mFogMode)); - //! [func_invoc] - auto vsFogStage = vsMain->getStage(FFP_VS_FOG); - vsFogStage.callFunction("FFP_FogFactor", In(mVSOutPos).w(), mFogParams, mVSOutFogFactor); - //! [func_invoc] - psMain->getStage(FFP_VS_FOG).callBuiltin("mix", mFogColour, mPSOutDiffuse, mPSInFogFactor, mPSOutDiffuse); - } - - return true; -} - -//----------------------------------------------------------------------- -void FFPFog::copyFrom(const SubRenderState& rhs) -{ - const FFPFog& rhsFog = static_cast(rhs); - - mFogMode = rhsFog.mFogMode; - - setCalcMode(rhsFog.mCalcMode); -} - -//----------------------------------------------------------------------- -bool FFPFog::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) -{ - if (srcPass->getFogOverride()) - { - mFogMode = srcPass->getFogMode(); - } - else if(SceneManager* sceneMgr = ShaderGenerator::getSingleton().getActiveSceneManager()) - { - mFogMode = sceneMgr->getFogMode(); - } - - return mFogMode != FOG_NONE; -} - -//----------------------------------------------------------------------- -bool FFPFog::setParameter(const String& name, const String& value) -{ - if(name == "calc_mode" && !value.empty()) - { - CalcMode cm = value == "per_vertex" ? CM_PER_VERTEX : CM_PER_PIXEL; - setCalcMode(cm); - return true; - } - - return false; -} - -//----------------------------------------------------------------------- -const String& FFPFogFactory::getType() const -{ - return SRS_FOG; -} - -//----------------------------------------------------------------------- -SubRenderState* FFPFogFactory::createInstance(ScriptCompiler* compiler, - PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) -{ - if (prop->name == "fog_stage") - { - if(prop->values.size() >= 1) - { - if (prop->values.front()->getString() == "ffp") - { - SubRenderState* subRenderState = createOrRetrieveInstance(translator); - AbstractNodeList::const_iterator it = prop->values.begin(); - - if(prop->values.size() >= 2) - { - ++it; - if(!subRenderState->setParameter("calc_mode", (*it)->getString())) - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - - return subRenderState; - } - } - } - - return NULL; -} - -//----------------------------------------------------------------------- -void FFPFogFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, - Pass* srcPass, Pass* dstPass) -{ - ser->writeAttribute(4, "fog_stage"); - ser->writeValue("ffp"); - - FFPFog* fogSubRenderState = static_cast(subRenderState); - - - if (fogSubRenderState->getCalcMode() == FFPFog::CM_PER_VERTEX) - { - ser->writeValue("per_vertex"); - } - else if (fogSubRenderState->getCalcMode() == FFPFog::CM_PER_PIXEL) - { - ser->writeValue("per_pixel"); - } -} - -//----------------------------------------------------------------------- -SubRenderState* FFPFogFactory::createInstanceImpl() -{ - return OGRE_NEW FFPFog; -} - -} -} - -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderFFPFog.h b/Components/RTShaderSystem/src/OgreShaderFFPFog.h deleted file mode 100644 index 6c7016b1a1a..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderFFPFog.h +++ /dev/null @@ -1,185 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderFFPFog_ -#define _ShaderFFPFog_ - -#include "OgreShaderPrerequisites.h" -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS -#include "OgreShaderSubRenderState.h" -#include "OgreVector.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** Fog sub render state implementation of the Fixed Function Pipeline. -@see http://msdn.microsoft.com/en-us/library/bb173398.aspx -Derives from SubRenderState class. -*/ -class FFPFog : public SubRenderState -{ -public: - - // Fog calculation mode enum. - enum CalcMode - { - CM_PER_VERTEX = 1, // Per vertex fog calculations. (Default). - CM_PER_PIXEL = 2 // Per pixel fog calculations. - }; - -// Interface. -public: - - /** Class default constructor */ - FFPFog(); - - /** - @see SubRenderState::getType. - */ - const String& getType() const override; - - /** - @see SubRenderState::getType. - */ - int getExecutionOrder() const override; - - /** - @see SubRenderState::copyFrom. - */ - void copyFrom(const SubRenderState& rhs) override; - - /** - @see SubRenderState::preAddToRenderState. - */ - bool preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) override; - - /** - Set the fog calculation mode. Either per vertex or per pixel. - @param calcMode The calculation mode to set. - */ - void setCalcMode(CalcMode calcMode) { mCalcMode = calcMode; } - - bool setParameter(const String& name, const String& value) override; - - /** - Return the current calculation mode. - */ - CalcMode getCalcMode() const { return mCalcMode; } - -// Protected methods -protected: - - /** - @see SubRenderState::resolveParameters. - */ - bool resolveParameters(ProgramSet* programSet) override; - - /** - @see SubRenderState::resolveDependencies. - */ - bool resolveDependencies(ProgramSet* programSet) override; - - /** - @see SubRenderState::addFunctionInvocations. - */ - bool addFunctionInvocations(ProgramSet* programSet) override; - -// Attributes. -protected: - // Fog calculation mode. - CalcMode mCalcMode; - // Fog formula. - FogMode mFogMode; - - // Fog colour parameter. - UniformParameterPtr mFogColour; - // Fog parameters program parameter. - UniformParameterPtr mFogParams; - // Vertex shader output position parameter. - ParameterPtr mVSOutPos; - // Vertex shader output fog colour parameter. - ParameterPtr mVSOutFogFactor; - // Pixel shader input fog factor. - ParameterPtr mPSInFogFactor; - // Vertex shader output depth. - ParameterPtr mVSOutDepth; - // Pixel shader input depth. - ParameterPtr mPSInDepth; - // Pixel shader output diffuse colour. - ParameterPtr mPSOutDiffuse; -}; - - -/** -A factory that enables creation of FFPFog instances. -@remarks Sub class of SubRenderStateFactory -*/ -class FFPFogFactory : public SubRenderStateFactory -{ -public: - - /** - @see SubRenderStateFactory::getType. - */ - const String& getType() const override; - - /** - @see SubRenderStateFactory::createInstance. - */ - SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) override; - - /** - @see SubRenderStateFactory::writeInstance. - */ - void writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, Pass* dstPass) override; - - -protected: - - /** - @see SubRenderStateFactory::createInstanceImpl. - */ - SubRenderState* createInstanceImpl() override; - - -}; - -/** @} */ -/** @} */ - -} -} - -#endif -#endif - diff --git a/Components/RTShaderSystem/src/OgreShaderFFPLighting.cpp b/Components/RTShaderSystem/src/OgreShaderFFPLighting.cpp deleted file mode 100644 index 8d077126371..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderFFPLighting.cpp +++ /dev/null @@ -1,414 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderPrecompiledHeaders.h" -#if defined(RTSHADER_SYSTEM_BUILD_CORE_SHADERS) || defined(RTSHADER_SYSTEM_BUILD_EXT_SHADERS) -namespace Ogre { -namespace RTShader { - -/************************************************************************/ -/* */ -/************************************************************************/ -const String SRS_PER_VERTEX_LIGHTING = "FFP_Lighting"; - -//----------------------------------------------------------------------- -FFPLighting::FFPLighting() -{ - mTrackVertexColourType = TVC_NONE; - mSpecularEnable = false; - mNormalisedEnable = false; - mTwoSidedLighting = false; - mLightCount = 0; - mLtcLUT1SamplerIndex = -1; -} - -//----------------------------------------------------------------------- -const String& FFPLighting::getType() const -{ - return SRS_PER_VERTEX_LIGHTING; -} - - -//----------------------------------------------------------------------- -int FFPLighting::getExecutionOrder() const -{ - return FFP_LIGHTING; -} - -//----------------------------------------------------------------------- -bool FFPLighting::resolveParameters(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - - // Resolve world view IT matrix. - mWorldViewITMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_NORMAL_MATRIX); - mViewNormal = vsMain->resolveLocalParameter(Parameter::SPC_NORMAL_VIEW_SPACE); - - // Get surface ambient colour if need to. - if ((mTrackVertexColourType & TVC_AMBIENT) == 0) - { - mDerivedAmbientLightColour = vsProgram->resolveParameter(GpuProgramParameters::ACT_DERIVED_AMBIENT_LIGHT_COLOUR); - } - else - { - mLightAmbientColour = vsProgram->resolveParameter(GpuProgramParameters::ACT_AMBIENT_LIGHT_COLOUR); - } - - // Get surface emissive colour if need to. - if ((mTrackVertexColourType & TVC_EMISSIVE) == 0) - { - mSurfaceEmissiveColour = vsProgram->resolveParameter(GpuProgramParameters::ACT_SURFACE_EMISSIVE_COLOUR); - } - - // Get derived scene colour. - mDerivedSceneColour = vsProgram->resolveParameter(GpuProgramParameters::ACT_DERIVED_SCENE_COLOUR); - - // Resolve input vertex shader normal. - mVSInNormal = vsMain->resolveInputParameter(Parameter::SPC_NORMAL_OBJECT_SPACE); - - if (mTrackVertexColourType != 0) - { - mInDiffuse = vsMain->resolveInputParameter(Parameter::SPC_COLOR_DIFFUSE); - } - - - // Resolve output vertex shader diffuse colour. - mOutDiffuse = vsMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE); - - // Resolve per light parameters. - mPositions = vsProgram->resolveParameter(GpuProgramParameters::ACT_LIGHT_POSITION_VIEW_SPACE_ARRAY, mLightCount); - mAttenuatParams = vsProgram->resolveParameter(GpuProgramParameters::ACT_LIGHT_ATTENUATION_ARRAY, mLightCount); - mDirections = vsProgram->resolveParameter(GpuProgramParameters::ACT_LIGHT_DIRECTION_VIEW_SPACE_ARRAY, mLightCount); - mSpotParams = vsProgram->resolveParameter(GpuProgramParameters::ACT_SPOTLIGHT_PARAMS_ARRAY, mLightCount); - - // Resolve diffuse colour. - if ((mTrackVertexColourType & TVC_DIFFUSE) == 0) - { - mDiffuseColours = vsProgram->resolveParameter(GpuProgramParameters::ACT_DERIVED_LIGHT_DIFFUSE_COLOUR_ARRAY, mLightCount); - } - else - { - mDiffuseColours = vsProgram->resolveParameter(GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR_POWER_SCALED_ARRAY, mLightCount); - } - - if (mSpecularEnable) - { - // Get surface shininess. - mSurfaceShininess = vsProgram->resolveParameter(GpuProgramParameters::ACT_SURFACE_SHININESS); - - // Resolve specular colour. - if ((mTrackVertexColourType & TVC_SPECULAR) == 0) - { - mSpecularColours = vsProgram->resolveParameter(GpuProgramParameters::ACT_DERIVED_LIGHT_SPECULAR_COLOUR_ARRAY, mLightCount); - } - else - { - mSpecularColours = vsProgram->resolveParameter(GpuProgramParameters::ACT_LIGHT_SPECULAR_COLOUR_POWER_SCALED_ARRAY, mLightCount); - } - - if (mOutSpecular.get() == NULL) - { - mOutSpecular = vsMain->resolveOutputParameter(Parameter::SPC_COLOR_SPECULAR); - } - } - - //if(needViewPos) - { - mWorldViewMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLDVIEW_MATRIX); - mVSInPosition = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE); - mViewPos = vsMain->resolveLocalParameter(Parameter::SPC_POSITION_VIEW_SPACE); - } - - return true; -} - -//----------------------------------------------------------------------- -bool FFPLighting::resolveDependencies(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - - vsProgram->addDependency(FFP_LIB_TRANSFORM); - vsProgram->addDependency(SGX_LIB_PERPIXELLIGHTING); - - addDefines(vsProgram); - - if(mSpecularEnable) - programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM)->addPreprocessorDefines("USE_SPECULAR"); - - return true; -} - -void FFPLighting::addDefines(Program* program) -{ - if(mNormalisedEnable) - program->addPreprocessorDefines("NORMALISED"); - - if(mSpecularEnable) - program->addPreprocessorDefines("USE_SPECULAR"); - - if(mTrackVertexColourType & TVC_DIFFUSE) - program->addPreprocessorDefines("TVC_DIFFUSE"); - - if(mTrackVertexColourType & TVC_SPECULAR) - program->addPreprocessorDefines("TVC_SPECULAR"); - - program->addPreprocessorDefines("LIGHT_COUNT=" + StringConverter::toString(mLightCount)); -} - -//----------------------------------------------------------------------- -bool FFPLighting::addFunctionInvocations(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - auto stage = vsMain->getStage(FFP_VS_LIGHTING); - - // Add the global illumination functions. - addGlobalIlluminationInvocation(stage); - - // Add per light functions. - for (int i = 0; i < mLightCount; i++) - { - addIlluminationInvocation(i, stage); - } - - auto psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - auto psMain = psProgram->getMain(); - if (auto shadowFactor = psMain->getLocalParameter("lShadowFactor")) - { - auto ambient = psProgram->resolveParameter(GpuProgramParameters::ACT_DERIVED_SCENE_COLOUR); - auto psOutDiffuse = psMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE); - - auto fstage = psMain->getStage(FFP_PS_COLOUR_BEGIN); - - std::vector args = {In(ambient), In(shadowFactor),InOut(psOutDiffuse)}; - - if (mSpecularEnable) - { - auto psSpecular = psMain->getInputParameter(Parameter::SPC_COLOR_SPECULAR); - if (!psSpecular) - psSpecular = psMain->getLocalParameter(Parameter::SPC_COLOR_SPECULAR); - args.push_back(InOut(psSpecular)); - } - - fstage.callFunction("SGX_ApplyShadowFactor_Modulative", args); - } - - return true; -} - -//----------------------------------------------------------------------- -void FFPLighting::addGlobalIlluminationInvocation(const FunctionStageRef& stage) -{ - // Transform normal to view space - if(mLightCount) - stage.callBuiltin("mul", mWorldViewITMatrix, mVSInNormal, mViewNormal); - - if(mViewPos) - { - // Transform position to view space. - stage.callFunction(FFP_FUNC_TRANSFORM, mWorldViewMatrix, mVSInPosition, mViewPos); - } - - if ((mTrackVertexColourType & TVC_AMBIENT) == 0 && - (mTrackVertexColourType & TVC_EMISSIVE) == 0) - { - stage.assign(mDerivedSceneColour, mOutDiffuse); - } - else - { - if (mTrackVertexColourType & TVC_AMBIENT) - { - stage.mul(mLightAmbientColour, mInDiffuse, mOutDiffuse); - } - else - { - stage.assign(mDerivedAmbientLightColour, mOutDiffuse); - } - - if (mTrackVertexColourType & TVC_EMISSIVE) - { - stage.add(In(mInDiffuse).xyz(), In(mOutDiffuse).xyz(), Out(mOutDiffuse).xyz()); - } - else - { - stage.add(mSurfaceEmissiveColour, mOutDiffuse, mOutDiffuse); - } - } -} - -//----------------------------------------------------------------------- -void FFPLighting::addIlluminationInvocation(int i, const FunctionStageRef& stage) -{ - std::vector args = {In(mViewNormal), In(mViewPos), In(mPositions), At(i), - In(mAttenuatParams), At(i), In(mDirections), At(i), - In(mSpotParams), At(i), In(mDiffuseColours), At(i), - InOut(mOutDiffuse).xyz()}; - - if (mTrackVertexColourType & (TVC_DIFFUSE | TVC_SPECULAR)) - { - args.push_back(In(mInDiffuse)); - } - - if (mSpecularEnable) - { - args.insert(args.end(), {In(mSpecularColours), At(i), In(mSurfaceShininess), InOut(mOutSpecular).xyz()}); - } - - if (mShadowFactor) - { - if(i < int(mShadowFactor->getSize())) - args.insert(args.end(), {In(mShadowFactor), At(i)}); - else - args.push_back(In(1)); - } - - if(mLTCLUT1) - { - args.insert(args.end(), {In(mLTCLUT1), In(mLTCLUT2)}); - } - - stage.callFunction("evaluateLight", args); -} - - -//----------------------------------------------------------------------- -void FFPLighting::copyFrom(const SubRenderState& rhs) -{ - const FFPLighting& rhsLighting = static_cast(rhs); - - mLightCount = rhsLighting.mLightCount; - mNormalisedEnable = rhsLighting.mNormalisedEnable; - mTwoSidedLighting = rhsLighting.mTwoSidedLighting; -} - -uint16 ensureLtcLUTPresent(Pass* dstPass) -{ - auto tus = dstPass->getTextureUnitState("ltc_1.dds"); - // return idx of existing texture unit - if(tus) - return dstPass->getTextureUnitStateIndex(tus); - - auto ltcSampler = TextureManager::getSingleton().getSampler("Ogre/LtcLUTSampler"); - tus = dstPass->createTextureUnitState("ltc_1.dds"); - tus->setNumMipmaps(0); - tus->setName("ltc_1.dds"); - tus->setSampler(ltcSampler); - tus = dstPass->createTextureUnitState("ltc_2.dds"); - tus->setNumMipmaps(0); - tus->setSampler(ltcSampler); - - return dstPass->getNumTextureUnitStates() - 2; // idx of first LUT -} - -//----------------------------------------------------------------------- -bool FFPLighting::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) -{ - //! [disable] - if (!srcPass->getLightingEnabled()) - return false; - //! [disable] - - mLightCount = renderState->getLightCount(); - - setTrackVertexColourType(srcPass->getVertexColourTracking()); - - mSpecularEnable = srcPass->getShininess() > 0.0 && srcPass->getSpecular() != ColourValue::Black; - - // Case this pass should run once per light(s) -> override the light policy. - if (srcPass->getIteratePerLight()) - { - mLightCount = srcPass->getLightCountPerIteration(); - } - - if(srcPass->getMaxSimultaneousLights() == 0) - { - mLightCount = 0; - } - - if (renderState->haveAreaLights()) - mLtcLUT1SamplerIndex = ensureLtcLUTPresent(dstPass); - - return true; -} - -bool FFPLighting::setParameter(const String& name, const String& value) -{ - if(name == "normalise" || name == "normalised") // allow both spelling variations - { - return StringConverter::parse(value, mNormalisedEnable); - } - - return false; -} - -//----------------------------------------------------------------------- -const String& FFPLightingFactory::getType() const -{ - return SRS_PER_VERTEX_LIGHTING; -} - -//----------------------------------------------------------------------- -SubRenderState* FFPLightingFactory::createInstance(ScriptCompiler* compiler, - PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) -{ - if (prop->name != "lighting_stage" || prop->values.empty()) - return NULL; - - auto it = prop->values.begin(); - - SubRenderState* ret = NULL; - if ((*it++)->getString() == "ffp") - { - ret = createOrRetrieveInstance(translator); - } - - if(ret && prop->values.size() >= 2) - { - ret->setParameter((*it)->getString(), "true"); // normalise - } - - return ret; -} - -//----------------------------------------------------------------------- -void FFPLightingFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, - Pass* srcPass, Pass* dstPass) -{ - ser->writeAttribute(4, "lighting_stage"); - ser->writeValue("ffp"); -} - -//----------------------------------------------------------------------- -SubRenderState* FFPLightingFactory::createInstanceImpl() -{ - return OGRE_NEW FFPLighting; -} - -} -} - -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderFFPLighting.h b/Components/RTShaderSystem/src/OgreShaderFFPLighting.h deleted file mode 100644 index bcf18aa3013..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderFFPLighting.h +++ /dev/null @@ -1,236 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderFFPLighting_ -#define _ShaderFFPLighting_ - -#include "OgreShaderPrerequisites.h" -#if defined(RTSHADER_SYSTEM_BUILD_CORE_SHADERS) || defined(RTSHADER_SYSTEM_BUILD_EXT_SHADERS) -#include "OgreShaderSubRenderState.h" -#include "OgreLight.h" -#include "OgreCommon.h" - -namespace Ogre { -namespace RTShader { - - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** Lighting sub render state implementation of the Fixed Function Pipeline. -@see http://msdn.microsoft.com/en-us/library/bb147178.aspx -Derives from SubRenderState class. -*/ -class FFPLighting : public SubRenderState -{ - -// Interface. -public: - - /** Class default constructor */ - FFPLighting(); - - /** - @see SubRenderState::getType. - */ - const String& getType() const override; - - /** - @see SubRenderState::getType. - */ - int getExecutionOrder() const override; - - /** - @see SubRenderState::copyFrom. - */ - void copyFrom(const SubRenderState& rhs) override; - - /** - @see SubRenderState::preAddToRenderState. - */ - bool preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) override; - - /** normalise the blinn-phong reflection model to make it energy conserving - * - * see [this for details](http://www.rorydriscoll.com/2009/01/25/energy-conservation-in-games/) - */ - void setNormaliseEnabled(bool enable) { mNormalisedEnable = enable; } - - bool setParameter(const String& name, const String& value) override; - - /** - Get the specular component state. - */ - bool getSpecularEnable() const { return mSpecularEnable; } - -// Protected types: -protected: - int mLightCount; - // Per light parameters. - // Light position. - UniformParameterPtr mPositions; - // Light direction. - UniformParameterPtr mDirections; - // Attenuation parameters. - UniformParameterPtr mAttenuatParams; - // Spot light parameters. - UniformParameterPtr mSpotParams; - // Diffuse colour. - UniformParameterPtr mDiffuseColours; - // Specular colour. - UniformParameterPtr mSpecularColours; - - void addDefines(Program* program); - - /** - Set the track per vertex colour type. Ambient, Diffuse, Specular and Emissive lighting components source - can be the vertex colour component. To establish such a link one should provide the matching flags to this - sub render state. - */ - void setTrackVertexColourType(TrackVertexColourType type) { mTrackVertexColourType = type; } - - /** - Return the current track per vertex type. - */ - TrackVertexColourType getTrackVertexColourType() const { return mTrackVertexColourType; } - - /** - @see SubRenderState::resolveParameters. - */ - bool resolveParameters(ProgramSet* programSet) override; - - /** - @see SubRenderState::resolveDependencies. - */ - bool resolveDependencies(ProgramSet* programSet) override; - - /** - @see SubRenderState::addFunctionInvocations. - */ - bool addFunctionInvocations(ProgramSet* programSet) override; - - - /** - Internal method that adds global illumination component functions invocations. - */ - void addGlobalIlluminationInvocation(const FunctionStageRef& stage); - - /** - Internal method that adds per light illumination component functions invocations. - */ - void addIlluminationInvocation(int i, const FunctionStageRef& stage); - - - // Track per vertex colour type. - TrackVertexColourType mTrackVertexColourType; - // Specular component enabled/disabled. - bool mSpecularEnable; - bool mNormalisedEnable; - bool mTwoSidedLighting; - int8 mLtcLUT1SamplerIndex; - - // World view matrix parameter. - UniformParameterPtr mWorldViewMatrix; - // World view matrix inverse transpose parameter. - UniformParameterPtr mWorldViewITMatrix; - // Transformed view normal - ParameterPtr mViewNormal; - // Transformed view position - ParameterPtr mViewPos; - // Vertex shader input position parameter. - ParameterPtr mVSInPosition; - // Vertex shader input normal. - ParameterPtr mVSInNormal; - // Vertex shader diffuse. - ParameterPtr mInDiffuse; - // Vertex shader output diffuse colour parameter. - ParameterPtr mOutDiffuse; - // Vertex shader output specular colour parameter. - ParameterPtr mOutSpecular; - // Derived scene colour parameter. - UniformParameterPtr mDerivedSceneColour; - // Ambient light colour parameter. - UniformParameterPtr mLightAmbientColour; - // Derived ambient light colour parameter. - UniformParameterPtr mDerivedAmbientLightColour; - // Surface emissive colour parameter. - UniformParameterPtr mSurfaceEmissiveColour; - // Surface shininess parameter. - UniformParameterPtr mSurfaceShininess; - - UniformParameterPtr mLTCLUT1; - UniformParameterPtr mLTCLUT2; - - ParameterPtr mShadowFactor; -}; - - -/** -A factory that enables creation of FFPLighting instances. -@remarks Sub class of SubRenderStateFactory -*/ -class FFPLightingFactory : public SubRenderStateFactory -{ -public: - - /** - @see SubRenderStateFactory::getType. - */ - const String& getType() const override; - - /** - @see SubRenderStateFactory::createInstance. - */ - SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) override; - - /** - @see SubRenderStateFactory::writeInstance. - */ - void writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, Pass* dstPass) override; - - -protected: - - /** - @see SubRenderStateFactory::createInstanceImpl. - */ - SubRenderState* createInstanceImpl() override; - - -}; - -/** @} */ -/** @} */ - -} -} - -#endif -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderFFPTexturing.cpp b/Components/RTShaderSystem/src/OgreShaderFFPTexturing.cpp deleted file mode 100644 index 1dfeffce957..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderFFPTexturing.cpp +++ /dev/null @@ -1,692 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderPrecompiledHeaders.h" -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS - -namespace Ogre { -namespace RTShader { - -/************************************************************************/ -/* */ -/************************************************************************/ -String FFPTexturing::Type = "FFP_Texturing"; -const String SRS_TEXTURING = "FFP_Texturing"; - -#define _INT_VALUE(f) (*(int*)(&(f))) - -const String c_ParamTexelEx("texel_"); - -//----------------------------------------------------------------------- -FFPTexturing::FFPTexturing() : mIsPointSprite(false), mLateAddBlend(false) -{ -} - -//----------------------------------------------------------------------- -const String& FFPTexturing::getType() const -{ - return SRS_TEXTURING; -} - -//----------------------------------------------------------------------- -int FFPTexturing::getExecutionOrder() const -{ - return FFP_TEXTURING; -} - -//----------------------------------------------------------------------- -bool FFPTexturing::resolveParameters(ProgramSet* programSet) -{ - for (auto & i : mTextureUnitParamsList) - { - TextureUnitParams* curParams = &i; - if(!curParams->mTextureUnitState) - continue; - - if (false == resolveUniformParams(curParams, programSet)) - return false; - - - if (false == resolveFunctionsParams(curParams, programSet)) - return false; - } - - - return true; -} - -//----------------------------------------------------------------------- -bool FFPTexturing::resolveUniformParams(TextureUnitParams* textureUnitParams, ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - - // Resolve texture sampler parameter. - textureUnitParams->mTextureSampler = psProgram->resolveParameter(textureUnitParams->mTextureSamplerType, "gTextureSampler", textureUnitParams->mTextureSamplerIndex); - - // Resolve texture matrix parameter. - if (needsTextureMatrix(textureUnitParams->mTextureUnitState)) - { - textureUnitParams->mTextureMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_TEXTURE_MATRIX, textureUnitParams->mTextureSamplerIndex); - } - - switch (textureUnitParams->mTexCoordCalcMethod) - { - case TEXCALC_NONE: - break; - - // Resolve World + View matrices. - case TEXCALC_ENVIRONMENT_MAP: - case TEXCALC_ENVIRONMENT_MAP_PLANAR: - mWorldMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLDVIEW_MATRIX); - OGRE_FALLTHROUGH; - case TEXCALC_ENVIRONMENT_MAP_NORMAL: - //TODO: change the following 'mWorldITMatrix' member to 'mWorldViewITMatrix' - mWorldITMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_NORMAL_MATRIX); - break; - - case TEXCALC_ENVIRONMENT_MAP_REFLECTION: - mWorldMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLD_MATRIX); - mWorldITMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_INVERSE_TRANSPOSE_WORLD_MATRIX); - mViewMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_CAMERA_POSITION); - break; - - case TEXCALC_PROJECTIVE_TEXTURE: - textureUnitParams->mTextureViewProjImageMatrix = vsProgram->resolveParameter( - GpuProgramParameters::ACT_TEXTURE_WORLDVIEWPROJ_MATRIX, textureUnitParams->mTextureSamplerIndex); - break; - } - - return true; -} - - - -//----------------------------------------------------------------------- -bool FFPTexturing::resolveFunctionsParams(TextureUnitParams* textureUnitParams, ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Function* psMain = psProgram->getEntryPointFunction(); - Parameter::Content texCoordContent = Parameter::SPC_UNKNOWN; - - switch (textureUnitParams->mTexCoordCalcMethod) - { - case TEXCALC_NONE: - // Resolve explicit vs input texture coordinates. - - if(mIsPointSprite) - break; - - if (textureUnitParams->mTextureMatrix.get() == NULL) - texCoordContent = Parameter::Content(Parameter::SPC_TEXTURE_COORDINATE0 + textureUnitParams->mTextureUnitState->getTextureCoordSet()); - - // assume already resolved - if(vsMain->getOutputParameter(texCoordContent, textureUnitParams->mVSInTextureCoordinateType)) - break; - - textureUnitParams->mVSInputTexCoord = vsMain->resolveInputParameter( - Parameter::Content(Parameter::SPC_TEXTURE_COORDINATE0 + - textureUnitParams->mTextureUnitState->getTextureCoordSet()), - textureUnitParams->mVSInTextureCoordinateType); - break; - - case TEXCALC_ENVIRONMENT_MAP: - case TEXCALC_ENVIRONMENT_MAP_PLANAR: - case TEXCALC_ENVIRONMENT_MAP_REFLECTION: - // Resolve vertex normal. - mVSInputPos = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE); - OGRE_FALLTHROUGH; - case TEXCALC_ENVIRONMENT_MAP_NORMAL: - mVSInputNormal = vsMain->resolveInputParameter(Parameter::SPC_NORMAL_OBJECT_SPACE); - break; - - case TEXCALC_PROJECTIVE_TEXTURE: - // Resolve vertex position. - mVSInputPos = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE); - break; - } - - if(mIsPointSprite) - { - textureUnitParams->mPSInputTexCoord = psMain->resolveInputParameter(Parameter::SPC_POINTSPRITE_COORDINATE); - } - else - { - // Resolve vs output texture coordinates. - textureUnitParams->mVSOutputTexCoord = - vsMain->resolveOutputParameter(texCoordContent, textureUnitParams->mVSOutTextureCoordinateType); - - // Resolve ps input texture coordinates. - textureUnitParams->mPSInputTexCoord = psMain->resolveInputParameter(textureUnitParams->mVSOutputTexCoord); - } - - mPSDiffuse = psMain->getInputParameter(Parameter::SPC_COLOR_DIFFUSE); - if (mPSDiffuse.get() == NULL) - { - mPSDiffuse = psMain->getLocalParameter(Parameter::SPC_COLOR_DIFFUSE); - } - - mPSSpecular = psMain->getInputParameter(Parameter::SPC_COLOR_SPECULAR); - if (mPSSpecular.get() == NULL) - { - mPSSpecular = psMain->getLocalParameter(Parameter::SPC_COLOR_SPECULAR); - } - - mPSOutDiffuse = psMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE); - - if (!mPSDiffuse || !mPSSpecular) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Not all parameters could be constructed for the sub-render state."); - } - return true; -} - -//----------------------------------------------------------------------- -bool FFPTexturing::resolveDependencies(ProgramSet* programSet) -{ - //! [deps_resolve] - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - - vsProgram->addDependency(FFP_LIB_TEXTURING); - psProgram->addDependency(FFP_LIB_TEXTURING); - //! [deps_resolve] - return true; -} - -//----------------------------------------------------------------------- -bool FFPTexturing::addFunctionInvocations(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Function* psMain = psProgram->getEntryPointFunction(); - - for (auto & i : mTextureUnitParamsList) - { - TextureUnitParams* curParams = &i; - if(!curParams->mTextureUnitState) - continue; - - if (false == addVSFunctionInvocations(curParams, vsMain)) - return false; - - if (false == addPSFunctionInvocations(curParams, psMain)) - return false; - } - - return true; -} - -//----------------------------------------------------------------------- -bool FFPTexturing::addVSFunctionInvocations(TextureUnitParams* textureUnitParams, Function* vsMain) -{ - if(mIsPointSprite) - return true; - - auto stage = vsMain->getStage(FFP_VS_TEXTURING); - - switch (textureUnitParams->mTexCoordCalcMethod) - { - case TEXCALC_NONE: - if(textureUnitParams->mVSInputTexCoord) - stage.assign(textureUnitParams->mVSInputTexCoord, textureUnitParams->mVSOutputTexCoord); - break; - case TEXCALC_ENVIRONMENT_MAP: - case TEXCALC_ENVIRONMENT_MAP_PLANAR: - stage.callFunction(FFP_FUNC_GENERATE_TEXCOORD_ENV_SPHERE, - {In(mWorldMatrix), In(mWorldITMatrix), In(mVSInputPos), In(mVSInputNormal), - Out(textureUnitParams->mVSOutputTexCoord)}); - break; - case TEXCALC_ENVIRONMENT_MAP_REFLECTION: - stage.callFunction(FFP_FUNC_GENERATE_TEXCOORD_ENV_REFLECT, - {In(mWorldMatrix), In(mWorldITMatrix), In(mViewMatrix), In(mVSInputNormal), In(mVSInputPos), - Out(textureUnitParams->mVSOutputTexCoord)}); - break; - case TEXCALC_ENVIRONMENT_MAP_NORMAL: - stage.callFunction(FFP_FUNC_GENERATE_TEXCOORD_ENV_NORMAL, - {In(mWorldITMatrix), In(mVSInputNormal), Out(textureUnitParams->mVSOutputTexCoord)}); - break; - case TEXCALC_PROJECTIVE_TEXTURE: - stage.callBuiltin("mul", textureUnitParams->mTextureViewProjImageMatrix, mVSInputPos, - textureUnitParams->mVSOutputTexCoord); - break; - default: - return false; - } - - if (textureUnitParams->mTextureMatrix) - { - stage.callFunction(FFP_FUNC_TRANSFORM_TEXCOORD, textureUnitParams->mTextureMatrix, - textureUnitParams->mVSOutputTexCoord, textureUnitParams->mVSOutputTexCoord); - } - - return true; -} -//----------------------------------------------------------------------- -bool FFPTexturing::addPSFunctionInvocations(TextureUnitParams* textureUnitParams, Function* psMain) -{ - const LayerBlendModeEx& colourBlend = textureUnitParams->mTextureUnitState->getColourBlendMode(); - const LayerBlendModeEx& alphaBlend = textureUnitParams->mTextureUnitState->getAlphaBlendMode(); - ParameterPtr source1; - ParameterPtr source2; - int groupOrder = FFP_PS_TEXTURING; - - - // Add texture sampling code. - ParameterPtr texel = psMain->resolveLocalParameter(GCT_FLOAT4, c_ParamTexelEx + StringConverter::toString(textureUnitParams->mTextureSamplerIndex)); - - // Build colour argument for source1. - source1 = getPSArgument(texel, colourBlend.source1, colourBlend.colourArg1, colourBlend.alphaArg1, false); - - // Build colour argument for source2. - source2 = getPSArgument(texel, colourBlend.source2, colourBlend.colourArg2, colourBlend.alphaArg2, false); - - if(source1 == texel || source2 == texel || colourBlend.operation == LBX_BLEND_TEXTURE_ALPHA) - addPSSampleTexelInvocation(textureUnitParams, psMain, texel, FFP_PS_SAMPLING); - - bool needDifferentAlphaBlend = false; - if (alphaBlend.operation != colourBlend.operation || - alphaBlend.source1 != colourBlend.source1 || - alphaBlend.source2 != colourBlend.source2 || - colourBlend.source1 == LBS_MANUAL || - colourBlend.source2 == LBS_MANUAL || - alphaBlend.source1 == LBS_MANUAL || - alphaBlend.source2 == LBS_MANUAL) - needDifferentAlphaBlend = true; - - if(mLateAddBlend && colourBlend.operation == LBX_ADD) - { - groupOrder = FFP_PS_COLOUR_END + 50 + 20; // after PBR lighting - } - - // Build colours blend - addPSBlendInvocations(psMain, source1, source2, texel, - textureUnitParams->mTextureSamplerIndex, - colourBlend, groupOrder, - needDifferentAlphaBlend ? Operand::OPM_XYZ : Operand::OPM_ALL); - - // Case we need different alpha channel code. - if (needDifferentAlphaBlend) - { - // Build alpha argument for source1. - source1 = getPSArgument(texel, alphaBlend.source1, alphaBlend.colourArg1, alphaBlend.alphaArg1, true); - - // Build alpha argument for source2. - source2 = getPSArgument(texel, alphaBlend.source2, alphaBlend.colourArg2, alphaBlend.alphaArg2, true); - - if(source1 == texel || source2 == texel || alphaBlend.operation == LBX_BLEND_TEXTURE_ALPHA) - addPSSampleTexelInvocation(textureUnitParams, psMain, texel, FFP_PS_SAMPLING); - - // Build alpha blend - addPSBlendInvocations(psMain, source1, source2, texel, - textureUnitParams->mTextureSamplerIndex, alphaBlend, groupOrder, - Operand::OPM_W); - } - - - - return true; -} - -//----------------------------------------------------------------------- -void FFPTexturing::addPSSampleTexelInvocation(TextureUnitParams* textureUnitParams, Function* psMain, - const ParameterPtr& texel, int groupOrder) -{ - auto stage = psMain->getStage(groupOrder); - - if (textureUnitParams->mTexCoordCalcMethod != TEXCALC_PROJECTIVE_TEXTURE) - { - stage.sampleTexture(textureUnitParams->mTextureSampler, textureUnitParams->mPSInputTexCoord, texel); - return; - } - - stage.callBuiltin("texture2DProj", textureUnitParams->mTextureSampler, textureUnitParams->mPSInputTexCoord, texel); -} - -//----------------------------------------------------------------------- -ParameterPtr FFPTexturing::getPSArgument(ParameterPtr texel, LayerBlendSource blendSrc, const ColourValue& colourValue, - Real alphaValue, bool isAlphaArgument) const -{ - switch(blendSrc) - { - case LBS_CURRENT: - return mPSOutDiffuse; - case LBS_TEXTURE: - return texel; - case LBS_DIFFUSE: - return mPSDiffuse; - case LBS_SPECULAR: - return mPSSpecular; - case LBS_MANUAL: - if (isAlphaArgument) - { - return ParameterFactory::createConstParam(Vector4(alphaValue)); - } - - return ParameterFactory::createConstParam(Vector4((Real)colourValue.r, (Real)colourValue.g, - (Real)colourValue.b, (Real)colourValue.a)); - } - - return ParameterPtr(); -} - -//----------------------------------------------------------------------- -void FFPTexturing::addPSBlendInvocations(Function* psMain, - ParameterPtr arg1, - ParameterPtr arg2, - ParameterPtr texel, - int samplerIndex, - const LayerBlendModeEx& blendMode, - const int groupOrder, - Operand::OpMask mask) -{ - auto stage = psMain->getStage(groupOrder); - switch(blendMode.operation) - { - case LBX_SOURCE1: - stage.assign(In(arg1).mask(mask), Out(mPSOutDiffuse).mask(mask)); - break; - case LBX_SOURCE2: - stage.assign(In(arg2).mask(mask), Out(mPSOutDiffuse).mask(mask)); - break; - case LBX_MODULATE: - case LBX_MODULATE_X2: - case LBX_MODULATE_X4: - stage.mul(In(arg1).mask(mask), In(arg2).mask(mask), Out(mPSOutDiffuse).mask(mask)); - if (blendMode.operation == LBX_MODULATE_X2) - stage.mul(In(mPSOutDiffuse).mask(mask), 2.0, Out(mPSOutDiffuse).mask(mask)); - if (blendMode.operation == LBX_MODULATE_X4) - stage.mul(In(mPSOutDiffuse).mask(mask), 4.0, Out(mPSOutDiffuse).mask(mask)); - break; - case LBX_ADD: - case LBX_ADD_SIGNED: - stage.add(In(arg1).mask(mask), In(arg2).mask(mask), Out(mPSOutDiffuse).mask(mask)); - if(blendMode.operation == LBX_ADD_SIGNED) - stage.sub(In(mPSOutDiffuse).mask(mask), 0.5, Out(mPSOutDiffuse).mask(mask)); - break; - case LBX_ADD_SMOOTH: - stage.callFunction(FFP_FUNC_ADDSMOOTH, In(arg1).mask(mask), In(arg2).mask(mask), - Out(mPSOutDiffuse).mask(mask)); - break; - case LBX_SUBTRACT: - stage.sub(In(arg1).mask(mask), In(arg2).mask(mask), Out(mPSOutDiffuse).mask(mask)); - break; - case LBX_BLEND_DIFFUSE_ALPHA: - stage.callBuiltin( - "mix", {In(arg2).mask(mask), In(arg1).mask(mask), In(mPSDiffuse).w(), Out(mPSOutDiffuse).mask(mask)}); - break; - case LBX_BLEND_TEXTURE_ALPHA: - stage.callBuiltin("mix", - {In(arg2).mask(mask), In(arg1).mask(mask), In(texel).w(), Out(mPSOutDiffuse).mask(mask)}); - break; - case LBX_BLEND_CURRENT_ALPHA: - stage.callBuiltin( - "mix", {In(arg2).mask(mask), In(arg1).mask(mask), In(mPSOutDiffuse).w(), Out(mPSOutDiffuse).mask(mask)}); - break; - case LBX_BLEND_MANUAL: - stage.callBuiltin( - "mix", {In(arg2).mask(mask), In(arg1).mask(mask), In(blendMode.factor), Out(mPSOutDiffuse).mask(mask)}); - break; - case LBX_DOTPRODUCT: - stage.callFunction(FFP_FUNC_DOTPRODUCT, In(arg2).mask(mask), In(arg1).mask(mask), - Out(mPSOutDiffuse).mask(mask)); - break; - case LBX_BLEND_DIFFUSE_COLOUR: - stage.callBuiltin("mix", {In(arg2).mask(mask), In(arg1).mask(mask), In(mPSDiffuse).mask(mask), - Out(mPSOutDiffuse).mask(mask)}); - break; - } -} - -//----------------------------------------------------------------------- -bool FFPTexturing::needsTextureMatrix(TextureUnitState* textureUnitState) -{ - const TextureUnitState::EffectMap& effectMap = textureUnitState->getEffects(); - TextureUnitState::EffectMap::const_iterator effi; - - for (effi = effectMap.begin(); effi != effectMap.end(); ++effi) - { - switch (effi->second.type) - { - - case TextureUnitState::ET_UVSCROLL: - case TextureUnitState::ET_USCROLL: - case TextureUnitState::ET_VSCROLL: - case TextureUnitState::ET_ROTATE: - case TextureUnitState::ET_TRANSFORM: - return true; - case TextureUnitState::ET_ENVIRONMENT_MAP: - case TextureUnitState::ET_PROJECTIVE_TEXTURE: - break; - } - } - - const Ogre::Matrix4 matTexture = textureUnitState->getTextureTransform(); - - // Resolve texture matrix parameter. - if (matTexture != Matrix4::IDENTITY) - return true; - - return false; -} - - -bool FFPTexturing::setParameter(const String& name, const String& value) -{ - if(name == "late_add_blend") - { - StringConverter::parse(value, mLateAddBlend); - return true; - } - return false; -} - -//----------------------------------------------------------------------- -void FFPTexturing::copyFrom(const SubRenderState& rhs) -{ - const FFPTexturing& rhsTexture = static_cast(rhs); - - mLateAddBlend = rhsTexture.mLateAddBlend; - setTextureUnitCount(rhsTexture.getTextureUnitCount()); - - for (unsigned int i=0; i < rhsTexture.getTextureUnitCount(); ++i) - { - setTextureUnit(i, rhsTexture.mTextureUnitParamsList[i].mTextureUnitState); - } -} - -//----------------------------------------------------------------------- -bool FFPTexturing::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) -{ - mIsPointSprite = srcPass->getPointSpritesEnabled(); - - if (auto rs = Root::getSingleton().getRenderSystem()) - { - if (mIsPointSprite && !rs->getCapabilities()->hasCapability(RSC_POINT_SPRITES)) - return false; - } - - setTextureUnitCount(srcPass->getTextureUnitStates().size()); - - std::set nonFFP_TUS; - auto nonFFPany = srcPass->getUserObjectBindings().getUserAny("_RTSS_nonFFP_TUS"); - if(nonFFPany.has_value()) - { - nonFFP_TUS = any_cast>(nonFFPany); - } - - // Build texture stage sub states. - for (unsigned short i=0; i < srcPass->getNumTextureUnitStates(); ++i) - { - if(nonFFP_TUS.find(i) != nonFFP_TUS.end()) - continue; - TextureUnitState* texUnitState = srcPass->getTextureUnitState(i); - setTextureUnit(i, texUnitState); - } - - return true; -} - -//----------------------------------------------------------------------- -void FFPTexturing::setTextureUnitCount(size_t count) -{ - mTextureUnitParamsList.resize(count); - - for (unsigned int i=0; i < count; ++i) - { - TextureUnitParams& curParams = mTextureUnitParamsList[i]; - - curParams.mTextureUnitState = NULL; - curParams.mTextureSamplerIndex = 0; - curParams.mTextureSamplerType = GCT_SAMPLER2D; - curParams.mVSInTextureCoordinateType = GCT_FLOAT2; - curParams.mVSOutTextureCoordinateType = GCT_FLOAT2; - } -} - -//----------------------------------------------------------------------- -void FFPTexturing::setTextureUnit(unsigned short index, TextureUnitState* textureUnitState) -{ - OgreAssert(index < mTextureUnitParamsList.size(), "FFPTexturing unit index out of bounds"); - - TextureUnitParams& curParams = mTextureUnitParamsList[index]; - - - curParams.mTextureSamplerIndex = index; - curParams.mTextureUnitState = textureUnitState; - - if(textureUnitState->isTextureLoadFailing()) // -> will be set to a 2D texture - return; - - bool isGLES2 = ShaderGenerator::getSingleton().getTargetLanguage() == "glsles"; - - switch (curParams.mTextureUnitState->getTextureType()) - { - case TEX_TYPE_1D: - curParams.mTextureSamplerType = GCT_SAMPLER1D; - curParams.mVSInTextureCoordinateType = GCT_FLOAT1; - if(!isGLES2) // no 1D texture support - break; - OGRE_FALLTHROUGH; - case TEX_TYPE_2D: - curParams.mTextureSamplerType = GCT_SAMPLER2D; - curParams.mVSInTextureCoordinateType = GCT_FLOAT2; - break; - case TEX_TYPE_EXTERNAL_OES: - curParams.mTextureSamplerType = GCT_SAMPLER_EXTERNAL_OES; - curParams.mVSInTextureCoordinateType = GCT_FLOAT2; - break; - case TEX_TYPE_2D_ARRAY: - curParams.mTextureSamplerType = GCT_SAMPLER2DARRAY; - curParams.mVSInTextureCoordinateType = GCT_FLOAT3; - break; - case TEX_TYPE_3D: - curParams.mTextureSamplerType = GCT_SAMPLER3D; - curParams.mVSInTextureCoordinateType = GCT_FLOAT3; - break; - case TEX_TYPE_CUBE_MAP: - curParams.mTextureSamplerType = GCT_SAMPLERCUBE; - curParams.mVSInTextureCoordinateType = GCT_FLOAT3; - break; - } - - curParams.mVSOutTextureCoordinateType = curParams.mVSInTextureCoordinateType; - curParams.mTexCoordCalcMethod = textureUnitState->_deriveTexCoordCalcMethod(); - - if (curParams.mTexCoordCalcMethod == TEXCALC_PROJECTIVE_TEXTURE) - curParams.mVSOutTextureCoordinateType = GCT_FLOAT4; - - // let TexCalcMethod override texture type, as it might be wrong for - // content_type shadow & content_type compositor - if (curParams.mTexCoordCalcMethod == TEXCALC_ENVIRONMENT_MAP_REFLECTION || - curParams.mTexCoordCalcMethod == TEXCALC_ENVIRONMENT_MAP_NORMAL) - { - curParams.mVSOutTextureCoordinateType = GCT_FLOAT3; - curParams.mTextureSamplerType = GCT_SAMPLERCUBE; - } - - if (curParams.mTexCoordCalcMethod == TEXCALC_ENVIRONMENT_MAP_PLANAR || - curParams.mTexCoordCalcMethod == TEXCALC_ENVIRONMENT_MAP) - { - curParams.mVSOutTextureCoordinateType = GCT_FLOAT2; - curParams.mTextureSamplerType = GCT_SAMPLER2D; - } -} - -//----------------------------------------------------------------------- -const String& FFPTexturingFactory::getType() const -{ - return SRS_TEXTURING; -} - -//----------------------------------------------------------------------- -SubRenderState* FFPTexturingFactory::createInstance(ScriptCompiler* compiler, - PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) -{ - if (prop->name == "texturing_stage") - { - if(prop->values.size() == 1) - { - const String& value = prop->values.front()->getString(); - - auto inst = createOrRetrieveInstance(translator); - - if (value == "ffp") - return inst; - - if (value == "late_add_blend") - inst->setParameter(value, "true"); - - return inst; - } - } - - return NULL; -} - -//----------------------------------------------------------------------- -void FFPTexturingFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, - Pass* srcPass, Pass* dstPass) -{ - ser->writeAttribute(4, "texturing_stage"); - ser->writeValue("late_add_blend"); // this is the only case where somebody would add this as a custom SRS -} - -//----------------------------------------------------------------------- -SubRenderState* FFPTexturingFactory::createInstanceImpl() -{ - return OGRE_NEW FFPTexturing; -} - - -} -} - -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderFFPTransform.cpp b/Components/RTShaderSystem/src/OgreShaderFFPTransform.cpp deleted file mode 100644 index a77685ac9fc..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderFFPTransform.cpp +++ /dev/null @@ -1,194 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderPrecompiledHeaders.h" -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS - -namespace Ogre { -namespace RTShader { - -/************************************************************************/ -/* */ -/************************************************************************/ -String FFPTransform::Type = "FFP_Transform"; -const String SRS_TRANSFORM = "FFP_Transform"; - -//----------------------------------------------------------------------- -const String& FFPTransform::getType() const -{ - return SRS_TRANSFORM; -} - - -//----------------------------------------------------------------------- -int FFPTransform::getExecutionOrder() const -{ - return FFP_TRANSFORM; -} - -bool FFPTransform::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) -{ - mSetPointSize = srcPass->getPointSize() != 1.0f || srcPass->isPointAttenuationEnabled(); - mDoLightCalculations = srcPass->getLightingEnabled(); - return true; -} - -//----------------------------------------------------------------------- -bool FFPTransform::createCpuSubPrograms(ProgramSet* programSet) -{ - //! [param_resolve] - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Function* vsEntry = vsProgram->getEntryPointFunction(); - - // Resolve World View Projection Matrix. - UniformParameterPtr wvpMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLDVIEWPROJ_MATRIX); - - // Resolve input position parameter. - ParameterPtr positionIn = vsEntry->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE); - - // Resolve output position parameter. - ParameterPtr positionOut = vsEntry->resolveOutputParameter(Parameter::SPC_POSITION_PROJECTIVE_SPACE); - //! [param_resolve] - - // Add dependency. - vsProgram->addDependency(FFP_LIB_TRANSFORM); - - bool isHLSL = ShaderGenerator::getSingleton().getTargetLanguage() == "hlsl"; - - // This requires GLES3.0 - if (ShaderGenerator::getSingleton().getTargetLanguage() == "glsles" && - !GpuProgramManager::getSingleton().isSyntaxSupported("glsl300es")) - mInstancingTexCoordIndex = 0; - - auto stage = vsEntry->getStage(FFP_VS_TRANSFORM); - if(mInstancingTexCoordIndex) - { - vsProgram->setInstancingIncluded(true); - // this at prevents software skinning, which is not supported with instancing - vsProgram->setSkeletalAnimationIncluded(true); - if (isHLSL) - { - // set hlsl shader to use row-major matrices instead of column-major. - // it enables the use of auto-bound 3x4 matrices in generated hlsl shader. - vsProgram->setUseColumnMajorMatrices(false); - } - - auto wMatrix = vsEntry->resolveInputParameter( - Parameter::Content(Parameter::SPC_TEXTURE_COORDINATE0 + mInstancingTexCoordIndex), GCT_MATRIX_3X4); - stage.callFunction(FFP_FUNC_TRANSFORM, wMatrix, positionIn, Out(positionIn).xyz()); - - if(mDoLightCalculations) - { - auto vsInNormal = vsEntry->resolveInputParameter(Parameter::SPC_NORMAL_OBJECT_SPACE); - stage.callFunction(FFP_FUNC_TRANSFORM, wMatrix, vsInNormal, vsInNormal); - } - // we can end here because the world matrix will be identity with instanced rendering - // so the code below will work as indended - } - stage.callBuiltin("mul", wvpMatrix, positionIn, positionOut); - - if(!mSetPointSize || isHLSL) // not supported with DX11 - return true; - - UniformParameterPtr pointParams = vsProgram->resolveParameter(GpuProgramParameters::ACT_POINT_PARAMS); - ParameterPtr pointSize = vsEntry->resolveOutputParameter(Parameter::SPC_POINTSPRITE_SIZE); - - // using eye space depth only instead of the eye real distance - // its faster to obtain, so lets call it close enough.. - stage.callFunction("FFP_DerivePointSize", pointParams, In(positionOut).w(), pointSize); - - return true; -} - - -//----------------------------------------------------------------------- -void FFPTransform::copyFrom(const SubRenderState& rhs) -{ - const FFPTransform& rhsTransform = static_cast(rhs); - mSetPointSize = rhsTransform.mSetPointSize; - mInstancingTexCoordIndex = rhsTransform.mInstancingTexCoordIndex; -} - -bool FFPTransform::setParameter(const String& name, const String& value) -{ - if (name == "instanced") - { - return StringConverter::parse(value, mInstancingTexCoordIndex); - } - return false; -} - -//----------------------------------------------------------------------- -const String& FFPTransformFactory::getType() const -{ - return SRS_TRANSFORM; -} - -//----------------------------------------------------------------------- -SubRenderState* FFPTransformFactory::createInstance(ScriptCompiler* compiler, - PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) -{ - if (prop->name == "transform_stage") - { - if(prop->values.size() > 0) - { - auto it = prop->values.begin(); - if((*it)->getString() != "instanced") - return NULL; - - int texCoordSlot = 1; - if(++it != prop->values.end() && !SGScriptTranslator::getInt(*++it, &texCoordSlot)) - return NULL; - - auto ret = createOrRetrieveInstance(translator); - ret->setParameter("instanced", std::to_string(texCoordSlot)); - - return ret; - } - } - - return NULL; -} - -//----------------------------------------------------------------------- -void FFPTransformFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, - Pass* srcPass, Pass* dstPass) -{ - ser->writeAttribute(4, "transform_stage"); - ser->writeValue("ffp"); -} - -//----------------------------------------------------------------------- -SubRenderState* FFPTransformFactory::createInstanceImpl() -{ - return OGRE_NEW FFPTransform; -} - - -} -} - -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderFFPTransform.h b/Components/RTShaderSystem/src/OgreShaderFFPTransform.h deleted file mode 100644 index ad01bd5c6ee..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderFFPTransform.h +++ /dev/null @@ -1,129 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderFFPTransform_ -#define _ShaderFFPTransform_ - -#include "OgreShaderPrerequisites.h" -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS -#include "OgreShaderSubRenderState.h" -#include "OgreShaderParameter.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** Transform sub render state implementation of the Fixed Function Pipeline. -@see http://msdn.microsoft.com/en-us/library/bb206269.aspx -Derives from SubRenderState class. -*/ -class FFPTransform : public SubRenderState -{ - -// Interface. -public: - - /** - @see SubRenderState::getType. - */ - const String& getType() const override; - - /** - @see SubRenderState::getExecutionOrder. - */ - int getExecutionOrder() const override; - - /** - @see SubRenderState::copyFrom. - */ - void copyFrom(const SubRenderState& rhs) override; - - /** - @see SubRenderState::createCpuSubPrograms. - */ - bool createCpuSubPrograms(ProgramSet* programSet) override; - - bool preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) override; - - bool setParameter(const String& name, const String& value) override; - - static String Type; -protected: - int mInstancingTexCoordIndex = 0; - bool mSetPointSize; - bool mDoLightCalculations; -}; - - -/** -A factory that enables creation of FFPTransform instances. -@remarks Sub class of SubRenderStateFactory -*/ -class FFPTransformFactory : public SubRenderStateFactory -{ -public: - - /** - @see SubRenderStateFactory::getType. - */ - const String& getType() const override; - - /** - @see SubRenderStateFactory::createInstance. - */ - SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) override; - - /** - @see SubRenderStateFactory::writeInstance. - */ - void writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, Pass* dstPass) override; - -protected: - - /** - @see SubRenderStateFactory::createInstanceImpl. - */ - SubRenderState* createInstanceImpl() override; - - - -}; - -/** @} */ -/** @} */ - - -} -} - -#endif -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderFunction.cpp b/Components/RTShaderSystem/src/OgreShaderFunction.cpp deleted file mode 100644 index dcae4b7eb86..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderFunction.cpp +++ /dev/null @@ -1,599 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreShaderPrecompiledHeaders.h" - -namespace Ogre { -namespace RTShader { - -static GpuConstantType typeFromContent(Parameter::Content content) -{ - switch (content) - { - case Parameter::SPC_BLEND_INDICES: - return GCT_UINT4; - case Parameter::SPC_COLOR_DIFFUSE: - case Parameter::SPC_COLOR_SPECULAR: - case Parameter::SPC_POSITION_PROJECTIVE_SPACE: - case Parameter::SPC_POSITION_OBJECT_SPACE: - case Parameter::SPC_BLEND_WEIGHTS: - case Parameter::SPC_POSITION_LIGHT_SPACE0: - case Parameter::SPC_POSITION_LIGHT_SPACE1: - case Parameter::SPC_POSITION_LIGHT_SPACE2: - case Parameter::SPC_POSITION_LIGHT_SPACE3: - case Parameter::SPC_POSITION_LIGHT_SPACE4: - case Parameter::SPC_POSITION_LIGHT_SPACE5: - case Parameter::SPC_POSITION_LIGHT_SPACE6: - case Parameter::SPC_POSITION_LIGHT_SPACE7: - case Parameter::SPC_TANGENT_OBJECT_SPACE: - return GCT_FLOAT4; - case Parameter::SPC_NORMAL_OBJECT_SPACE: - case Parameter::SPC_NORMAL_WORLD_SPACE: - case Parameter::SPC_NORMAL_VIEW_SPACE: - case Parameter::SPC_POSTOCAMERA_OBJECT_SPACE: - case Parameter::SPC_POSTOCAMERA_VIEW_SPACE: - case Parameter::SPC_POSITION_VIEW_SPACE: - case Parameter::SPC_POSITION_WORLD_SPACE: - return GCT_FLOAT3; - case Parameter::SPC_POINTSPRITE_COORDINATE: - return GCT_FLOAT2; - case Parameter::SPC_POINTSPRITE_SIZE: - case Parameter::SPC_DEPTH_VIEW_SPACE: - return GCT_FLOAT1; - case Parameter::SPC_FRONT_FACING: - return GCT_FLOAT1; - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "cannot derive type from content"); - break; - } -} - -static Parameter::Semantic semanticFromContent(Parameter::Content content, bool isVSOut = false) -{ - switch (content) - { - case Parameter::SPC_COLOR_DIFFUSE: - case Parameter::SPC_COLOR_SPECULAR: - return Parameter::SPS_COLOR; - case Parameter::SPC_POSITION_PROJECTIVE_SPACE: - return Parameter::SPS_POSITION; - case Parameter::SPC_BLEND_INDICES: - return Parameter::SPS_BLEND_INDICES; - case Parameter::SPC_BLEND_WEIGHTS: - return Parameter::SPS_BLEND_WEIGHTS; - case Parameter::SPC_POINTSPRITE_COORDINATE: - return Parameter::SPS_TEXTURE_COORDINATES; - case Parameter::SPC_BINORMAL_OBJECT_SPACE: - return Parameter::SPS_BINORMAL; - case Parameter::SPC_FRONT_FACING: - return Parameter::SPS_FRONT_FACING; - case Parameter::SPC_TANGENT_OBJECT_SPACE: - if(!isVSOut) return Parameter::SPS_TANGENT; - OGRE_FALLTHROUGH; - case Parameter::SPC_POSITION_OBJECT_SPACE: - if(!isVSOut) return Parameter::SPS_POSITION; - OGRE_FALLTHROUGH; - case Parameter::SPC_NORMAL_OBJECT_SPACE: - if(!isVSOut) return Parameter::SPS_NORMAL; - OGRE_FALLTHROUGH; - // the remaining types are VS output types only (or indeed texcoord) - // for out types we use the TEXCOORD[n] semantics for compatibility - // with Cg, HLSL SM2.0 where they are the only multivariate semantics - default: - return Parameter::SPS_TEXTURE_COORDINATES; - } -} - -/// fixed index for texcoords, next free semantic slot else -static int indexFromContent(Parameter::Content content) -{ - int c = int(content); - if(c < Parameter::SPC_TEXTURE_COORDINATE0 || c > Parameter::SPC_TEXTURE_COORDINATE7) - return -1; - - return c - Parameter::SPC_TEXTURE_COORDINATE0; -} - -void FunctionStageRef::callFunction(const char* name, const InOut& inout) const -{ - callFunction(name, std::vector{inout}); -} - -void FunctionStageRef::callFunction(const char* name, const std::vector& params) const -{ - auto function = new FunctionInvocation(name, mStage); - function->setOperands(params); - mParent->addAtomInstance(function); -} - -void FunctionStageRef::sampleTexture(const std::vector& params) const -{ - auto function = new SampleTextureAtom(mStage); - function->setOperands(params); - mParent->addAtomInstance(function); -} - -void FunctionStageRef::assign(const std::vector& params) const -{ - auto function = new AssignmentAtom(mStage); - function->setOperands(params); - mParent->addAtomInstance(function); -} - -void FunctionStageRef::binaryOp(char op, const std::vector& params) const -{ - auto function = new BinaryOpAtom(op, mStage); - function->setOperands(params); - mParent->addAtomInstance(function); -} - -void FunctionStageRef::callBuiltin(const char* name, const std::vector& params) const -{ - auto function = new BuiltinFunctionAtom(name, mStage); - function->setOperands(params); - mParent->addAtomInstance(function); -} - -//----------------------------------------------------------------------------- -Function::Function(GpuProgramType type) : mType(type) {} - -Function::~Function() -{ - for(const auto& j : mAtomInstances) - { - for (auto& i : j.second) - OGRE_DELETE i; - } - mAtomInstances.clear(); - - for (auto& p : mInputParameters) - p.reset(); - mInputParameters.clear(); - - for (auto& p : mOutputParameters) - p.reset(); - mOutputParameters.clear(); - - for (auto& p : mLocalParameters) - p.reset(); - mLocalParameters.clear(); -} - -static String getParameterName(const char* prefix, Parameter::Semantic semantic, int index) -{ - const char* name = ""; - switch (semantic) - { - case Parameter::SPS_POSITION: - name = "Pos"; - break; - case Parameter::SPS_BLEND_WEIGHTS: - name = "BlendWeights"; - break; - case Parameter::SPS_BLEND_INDICES: - name = "BlendIndices"; - break; - case Parameter::SPS_NORMAL: - name = "Normal"; - break; - case Parameter::SPS_COLOR: - name = "Color"; - break; - case Parameter::SPS_TEXTURE_COORDINATES: - name = "Texcoord"; - break; - case Parameter::SPS_BINORMAL: - name = "BiNormal"; - break; - case Parameter::SPS_TANGENT: - name = "Tangent"; - break; - case Parameter::SPS_FRONT_FACING: - name = "FrontFacing"; - break; - case Parameter::SPS_UNKNOWN: - name = "Param"; - break; - }; - return StringUtil::format("%s%s_%d", prefix, name, index); -} - -//----------------------------------------------------------------------------- -ParameterPtr Function::resolveInputParameter(Parameter::Semantic semantic, - int index, - const Parameter::Content content, - GpuConstantType type) -{ - if(type == GCT_UNKNOWN) - type = typeFromContent(content); - - ParameterPtr param; - - // Check if desired parameter already defined. - param = _getParameterByContent(mInputParameters, content, type); - if (param.get() != NULL) - return param; - - if(semantic == Parameter::SPS_UNKNOWN) - { - semantic = semanticFromContent(content); - index = indexFromContent(content); // create new parameter for this content - } - - // Case we have to create new parameter. - if (index == -1) - { - index = 0; - - // Find the next available index of the target semantic. - for (auto& p : mInputParameters) - { - if (p->getSemantic() == semantic) - index++; - } - } - else - { - // Check if desired parameter already defined. - param = _getParameterBySemantic(mInputParameters, semantic, index); - if (param.get() != NULL && param->getContent() == content) - { - if (param->getType() == type) - { - return param; - } - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - StringUtil::format("Can not resolve parameter due to type mismatch: semantic: %d, index: %d", - semantic, index)); - } - } - - const char* prefix = mType == GPT_VERTEX_PROGRAM ? "i" : "vs"; - - // No parameter found -> create new one. - OgreAssert(semantic != Parameter::SPS_UNKNOWN, "unknown semantic"); - param = - std::make_shared(type, getParameterName(prefix, semantic, index), semantic, index, content); - addInputParameter(param); - - return param; -} - -//----------------------------------------------------------------------------- -ParameterPtr Function::resolveOutputParameter(Parameter::Semantic semantic, - int index, - Parameter::Content content, - GpuConstantType type) -{ - if(type == GCT_UNKNOWN) - type = typeFromContent(content); - - ParameterPtr param; - - // Check if desired parameter already defined. - param = _getParameterByContent(mOutputParameters, content, type); - if (param.get() != NULL) - return param; - - if(semantic == Parameter::SPS_UNKNOWN) - { - semantic = semanticFromContent(content, true); - index = -1; // create new parameter for this content - } - - // Case we have to create new parameter. - if (index == -1) - { - index = 0; - - // Find the next available index of the target semantic. - for (auto& p : mOutputParameters) - { - if (p->getSemantic() == semantic) - index++; - } - } - else - { - // Check if desired parameter already defined. - param = _getParameterBySemantic(mOutputParameters, semantic, index); - if (param.get() != NULL && param->getContent() == content) - { - if (param->getType() == type) - { - return param; - } - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - StringUtil::format("Can not resolve parameter due to type mismatch: semantic: %d, index: %d", - semantic, index)); - } - } - - const char* prefix = mType == GPT_VERTEX_PROGRAM ? "vs" : "o"; - - // No parameter found -> create new one. - switch (semantic) - { - case Parameter::SPS_TEXTURE_COORDINATES: - case Parameter::SPS_COLOR: - case Parameter::SPS_POSITION: - param = std::make_shared(type, getParameterName(prefix, semantic, index), semantic, index, - content); - break; - - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - StringUtil::format("Semantic not supported as output parameter: %d", semantic)); - break; - } - - addOutputParameter(param); - - return param; -} - -//----------------------------------------------------------------------------- -ParameterPtr Function::resolveLocalParameter(GpuConstantType type, const String& name, size_t arraySize) -{ - ParameterPtr param; - - param = _getParameterByName(mLocalParameters, name); - if (param.get() != NULL) - { - if (param->getType() == type && param->getSize() == arraySize) - { - return param; - } - else - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Can not resolve local parameter due to type mismatch"); - } - } - - param = std::make_shared(type, name, Parameter::SPS_UNKNOWN, 0, Parameter::SPC_UNKNOWN, arraySize); - addParameter(mLocalParameters, param); - - return param; -} - -ParameterPtr Function::resolveLocalStructParameter(const String& type, const String& name) -{ - ParameterPtr param; - - param = _getParameterByName(mLocalParameters, name); - if (param) - { - OgreAssert(param->getStructType() == type, "A parameter with the same name but different type already exists"); - return param; - } - - param = std::make_shared(GCT_UNKNOWN, name, Parameter::SPS_UNKNOWN, 0, Parameter::SPC_UNKNOWN); - param->setStructType(type); - addParameter(mLocalParameters, param); - - return param; -} - -//----------------------------------------------------------------------------- -ParameterPtr Function::resolveLocalParameter(const Parameter::Content content, GpuConstantType type) -{ - ParameterPtr param; - - if(type == GCT_UNKNOWN) type = typeFromContent(content); - - param = _getParameterByContent(mLocalParameters, content, type); - if (param.get() != NULL) - return param; - - param = std::make_shared( - type, getParameterName("l", semanticFromContent(content), mLocalParameters.size()), - Parameter::SPS_UNKNOWN, 0, content); - addParameter(mLocalParameters, param); - - return param; -} - -//----------------------------------------------------------------------------- -void Function::addInputParameter(ParameterPtr parameter) -{ - - // Check that parameter with the same semantic and index in input parameters list. - if (_getParameterBySemantic(mInputParameters, parameter->getSemantic(), parameter->getIndex()).get() != NULL) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "Parameter <" + parameter->getName() + "> has equal semantic parameter"); - } - - addParameter(mInputParameters, parameter); -} - -//----------------------------------------------------------------------------- -void Function::addOutputParameter(ParameterPtr parameter) -{ - // Check that parameter with the same semantic and index in output parameters list. - if (_getParameterBySemantic(mOutputParameters, parameter->getSemantic(), parameter->getIndex()).get() != NULL) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "Parameter <" + parameter->getName() + "> has equal semantic parameter"); - } - - addParameter(mOutputParameters, parameter); -} - -//----------------------------------------------------------------------------- -void Function::deleteInputParameter(ParameterPtr parameter) -{ - deleteParameter(mInputParameters, parameter); -} - -//----------------------------------------------------------------------------- -void Function::deleteOutputParameter(ParameterPtr parameter) -{ - deleteParameter(mOutputParameters, parameter); -} - -//----------------------------------------------------------------------------- -void Function::deleteAllInputParameters() -{ - mInputParameters.clear(); -} - -//----------------------------------------------------------------------------- -void Function::deleteAllOutputParameters() -{ - mOutputParameters.clear(); -} -//----------------------------------------------------------------------------- -void Function::addParameter(ShaderParameterList& parameterList, ParameterPtr parameter) - -{ - // Check that parameter with the same name doest exist in input parameters list. - if (_getParameterByName(mInputParameters, parameter->getName()).get() != NULL) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "Parameter <" + parameter->getName() + "> already declared"); - } - - // Check that parameter with the same name doest exist in output parameters list. - if (_getParameterByName(mOutputParameters, parameter->getName()).get() != NULL) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "Parameter <" + parameter->getName() + "> already declared"); - } - - - // Add to given parameters list. - parameterList.push_back(parameter); -} - -//----------------------------------------------------------------------------- -void Function::deleteParameter(ShaderParameterList& parameterList, ParameterPtr parameter) -{ - ShaderParameterIterator it; - - for (it = parameterList.begin(); it != parameterList.end(); ++it) - { - if (*it == parameter) - { - (*it).reset(); - parameterList.erase(it); - break; - } - } -} - -//----------------------------------------------------------------------------- -ParameterPtr Function::_getParameterByName( const ShaderParameterList& parameterList, const String& name ) -{ - for (const auto& p : parameterList) - { - if (p->getName() == name) - return p; - } - - return ParameterPtr(); -} - -//----------------------------------------------------------------------------- -ParameterPtr Function::_getParameterBySemantic(const ShaderParameterList& parameterList, - const Parameter::Semantic semantic, - int index) -{ - for (const auto& p : parameterList) - { - if (p->getSemantic() == semantic && p->getIndex() == index) - return p; - } - - return ParameterPtr(); -} - -//----------------------------------------------------------------------------- -ParameterPtr Function::_getParameterByContent(const ShaderParameterList& parameterList, const Parameter::Content content, GpuConstantType type) -{ - if(type == GCT_UNKNOWN) - type = typeFromContent(content); - - // Search only for known content. - if (content != Parameter::SPC_UNKNOWN) - { - for (const auto& p : parameterList) - { - if (p->getContent() == content && p->getType() == type) - return p; - } - } - - return ParameterPtr(); -} - - -//----------------------------------------------------------------------------- -void Function::addAtomInstance(FunctionAtom* atomInstance) -{ - mAtomInstances[atomInstance->getGroupExecutionOrder()].push_back(atomInstance); - mSortedAtomInstances.clear(); -} - -//----------------------------------------------------------------------------- -bool Function::deleteAtomInstance(FunctionAtom* atomInstance) -{ - FunctionAtomInstanceIterator it; - size_t g = atomInstance->getGroupExecutionOrder(); - for (it=mAtomInstances[g].begin(); it != mAtomInstances[g].end(); ++it) - { - if (*it == atomInstance) - { - OGRE_DELETE atomInstance; - mAtomInstances[g].erase(it); - mSortedAtomInstances.clear(); - return true; - } - } - - return false; - -} - -//----------------------------------------------------------------------------- -const FunctionAtomInstanceList& Function::getAtomInstances() -{ - if(!mSortedAtomInstances.empty()) - return mSortedAtomInstances; - - // put atom instances into order - for(const auto& i : mAtomInstances) - { - mSortedAtomInstances.insert(mSortedAtomInstances.end(), i.second.begin(), i.second.end()); - } - - return mSortedAtomInstances; -} - -} -} diff --git a/Components/RTShaderSystem/src/OgreShaderFunctionAtom.cpp b/Components/RTShaderSystem/src/OgreShaderFunctionAtom.cpp deleted file mode 100644 index 9558ff3d272..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderFunctionAtom.cpp +++ /dev/null @@ -1,476 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreShaderPrecompiledHeaders.h" - -namespace Ogre { -namespace RTShader { -//----------------------------------------------------------------------------- -Operand::Operand(ParameterPtr parameter, OpSemantic opSemantic, OpMask opMask, ushort indirectionLevel) : mParameter(parameter), mSemantic(opSemantic), mMask(opMask), mIndirectionLevel(indirectionLevel) -{ - // delay null check until FunctionInvocation - if(parameter) - parameter->setUsed(true); -} -//----------------------------------------------------------------------------- -Operand::Operand(const Operand& other) -{ - *this = other; -} -//----------------------------------------------------------------------------- -Operand& Operand::operator= (const Operand & other) -{ - if (this != &other) - { - mParameter = other.mParameter; - mSemantic = other.mSemantic; - mMask = other.mMask; - mIndirectionLevel = other.mIndirectionLevel; - } - return *this; -} -//----------------------------------------------------------------------------- -Operand::~Operand() -{ - // nothing to do -} - -void Operand::setMaskToParamType() -{ - switch (mParameter->getType()) - { - case GCT_FLOAT1: - mMask = OPM_X; - break; - case GCT_FLOAT2: - mMask = OPM_XY; - break; - case GCT_FLOAT3: - mMask = OPM_XYZ; - break; - default: - mMask = OPM_ALL; - break; - } -} - -//----------------------------------------------------------------------------- -static void writeMask(std::ostream& os, int mask) -{ - if (mask != Operand::OPM_ALL) - { - os << '.'; - if (mask & Operand::OPM_X) - { - os << 'x'; - } - - if (mask & Operand::OPM_Y) - { - os << 'y'; - } - - if (mask & Operand::OPM_Z) - { - os << 'z'; - } - - if (mask & Operand::OPM_W) - { - os << 'w'; - } - } -} - -//----------------------------------------------------------------------------- -int Operand::getFloatCount(int mask) -{ - int floatCount = 0; - - while (mask != 0) - { - if ((mask & Operand::OPM_X) != 0) - { - floatCount++; - - } - mask = mask >> 1; - } - - return floatCount; -} - -//----------------------------------------------------------------------------- -void Operand::write(std::ostream& os) const -{ - os << mParameter->toString(); - writeMask(os, mMask); -} - -//----------------------------------------------------------------------------- -FunctionAtom::FunctionAtom() -{ - mGroupExecutionOrder = -1; -} - -//----------------------------------------------------------------------------- -int FunctionAtom::getGroupExecutionOrder() const -{ - return mGroupExecutionOrder; -} - -//----------------------------------------------------------------------- -FunctionInvocation::FunctionInvocation(const String& functionName, int groupOrder, - const String& returnType) - : mReturnType(returnType) -{ - mFunctionName = functionName; - mGroupExecutionOrder = groupOrder; -} - -//----------------------------------------------------------------------------- -FunctionInvocation::FunctionInvocation(const FunctionInvocation& other) : - mReturnType(other.mReturnType) -{ - mFunctionName = other.mFunctionName; - mGroupExecutionOrder = other.mGroupExecutionOrder; - - for ( OperandVector::const_iterator it = other.mOperands.begin(); it != other.mOperands.end(); ++it) - mOperands.push_back(Operand(*it)); -} - -//----------------------------------------------------------------------- -void FunctionInvocation::writeSourceCode(std::ostream& os, const String& targetLanguage) const -{ - // Write function name. - os << mFunctionName << "("; - writeOperands(os, mOperands.begin(), mOperands.end()); - // Write function call closer. - os << ");"; -} - -//----------------------------------------------------------------------- -static String parameterNullMsg(const String& name, size_t pos) -{ - return StringUtil::format("%s: parameter #%zu is NULL", name.c_str(), pos); -} - -void FunctionAtom::pushOperand(ParameterPtr parameter, Operand::OpSemantic opSemantic, Operand::OpMask opMask, int indirectionLevel) -{ - if (!parameter) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, parameterNullMsg(mFunctionName, mOperands.size())); - mOperands.push_back(Operand(parameter, opSemantic, opMask, indirectionLevel)); -} - -void FunctionAtom::setOperands(const OperandVector& ops) -{ - for (size_t i = 0; i < ops.size(); i++) - if(!ops[i].getParameter()) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, parameterNullMsg(mFunctionName, i)); - - mOperands = ops; -} - -void FunctionAtom::writeOperands(std::ostream& os, OperandVector::const_iterator begin, - OperandVector::const_iterator end) const -{ - // Write parameters. - ushort curIndLevel = 0; - for (OperandVector::const_iterator it = begin; it != end; ) - { - it->write(os); - ++it; - - ushort opIndLevel = 0; - if (it != mOperands.end()) - { - opIndLevel = it->getIndirectionLevel(); - } - - if (curIndLevel != 0) - { - os << ")"; - } - if (curIndLevel < opIndLevel) - { - while (curIndLevel < opIndLevel) - { - ++curIndLevel; - os << "["; - } - } - else //if (curIndLevel >= opIndLevel) - { - while (curIndLevel > opIndLevel) - { - --curIndLevel; - os << "]"; - } - if (opIndLevel != 0) - { - os << "]["; - } - else if (it != end) - { - os << ", "; - } - } - if (curIndLevel != 0) - { - os << "int("; // required by GLSL - } - } -} - -//----------------------------------------------------------------------- -bool FunctionInvocation::operator == ( const FunctionInvocation& rhs ) const -{ - return FunctionInvocationCompare()(*this, rhs); -} - -//----------------------------------------------------------------------- -bool FunctionInvocation::operator != ( const FunctionInvocation& rhs ) const -{ - return !(*this == rhs); -} - -//----------------------------------------------------------------------- -bool FunctionInvocation::operator < ( const FunctionInvocation& rhs ) const -{ - return FunctionInvocationLessThan()(*this, rhs); -} - -static uchar getSwizzledSize(const Operand& op) -{ - auto gct = op.getParameter()->getType(); - if (op.getMask() == Operand::OPM_ALL) - return GpuConstantDefinition::getElementSize(gct, false); - - return Operand::getFloatCount(op.getMask()); -} - -bool FunctionInvocation::FunctionInvocationLessThan::operator ()(FunctionInvocation const& lhs, FunctionInvocation const& rhs) const -{ - // Check the function names first - // Adding an exception to std::string sorting. I feel that functions beginning with an underscore should be placed before - // functions beginning with an alphanumeric character. By default strings are sorted based on the ASCII value of each character. - // Underscores have an ASCII value in between capital and lowercase characters. This is why the exception is needed. - if (lhs.getFunctionName() < rhs.getFunctionName()) - { - if(rhs.getFunctionName().at(0) == '_') - return false; - else - return true; - } - if (lhs.getFunctionName() > rhs.getFunctionName()) - { - if(lhs.getFunctionName().at(0) == '_') - return true; - else - return false; - } - - // Next check the return type - if (lhs.getReturnType() < rhs.getReturnType()) - return true; - if (lhs.getReturnType() > rhs.getReturnType()) - return false; - - // Check the number of operands - if (lhs.mOperands.size() < rhs.mOperands.size()) - return true; - if (lhs.mOperands.size() > rhs.mOperands.size()) - return false; - - // Now that we've gotten past the two quick tests, iterate over operands - // Check the semantic and type. The operands must be in the same order as well. - OperandVector::const_iterator itLHSOps = lhs.mOperands.begin(); - OperandVector::const_iterator itRHSOps = rhs.mOperands.begin(); - - for ( ; ((itLHSOps != lhs.mOperands.end()) && (itRHSOps != rhs.mOperands.end())); ++itLHSOps, ++itRHSOps) - { - if (itLHSOps->getSemantic() < itRHSOps->getSemantic()) - return true; - if (itLHSOps->getSemantic() > itRHSOps->getSemantic()) - return false; - - uchar leftType = getSwizzledSize(*itLHSOps); - uchar rightType = getSwizzledSize(*itRHSOps); - - if (leftType < rightType) - return true; - if (leftType > rightType) - return false; - } - - return false; -} - -bool FunctionInvocation::FunctionInvocationCompare::operator ()(FunctionInvocation const& lhs, FunctionInvocation const& rhs) const -{ - // Check the function names first - if (lhs.getFunctionName() != rhs.getFunctionName()) - return false; - - // Next check the return type - if (lhs.getReturnType() != rhs.getReturnType()) - return false; - - // filter indirect operands - std::vector lhsOps; - std::vector rhsOps; - for(const Operand& op : lhs.mOperands) - if(op.getIndirectionLevel() == 0) lhsOps.push_back(&op); - for(const Operand& op : rhs.mOperands) - if(op.getIndirectionLevel() == 0) rhsOps.push_back(&op); - - // Check the number of direct operands - if (lhsOps.size() != rhsOps.size()) - return false; - - // Now that we've gotten past the two quick tests, iterate over operands - // Check the semantic and type. The operands must be in the same order as well. - auto itLHSOps = lhsOps.begin(); - auto itRHSOps = rhsOps.begin(); - for ( ; ((itLHSOps != lhsOps.end()) && (itRHSOps != rhsOps.end())); ++itLHSOps, ++itRHSOps) - { - if ((*itLHSOps)->getSemantic() != (*itRHSOps)->getSemantic()) - return false; - - if (getSwizzledSize(**itLHSOps) != getSwizzledSize(**itRHSOps)) - return false; - } - - // Passed all tests, they are the same - return true; -} - -AssignmentAtom::AssignmentAtom(const Out& lhs, const In& rhs, int groupOrder) { - // do this backwards for compatibility with FFP_FUNC_ASSIGN calls - setOperands({rhs, lhs}); - mGroupExecutionOrder = groupOrder; - mFunctionName = "assign"; -} - -void AssignmentAtom::writeSourceCode(std::ostream& os, const String& targetLanguage) const -{ - OperandVector::const_iterator outOp = mOperands.begin(); - // find the output operand - while(outOp->getSemantic() != Operand::OPS_OUT) - outOp++; - writeOperands(os, outOp, mOperands.end()); - os << "\t=\t"; - writeOperands(os, mOperands.begin(), outOp); - os << ";"; -} - -SampleTextureAtom::SampleTextureAtom(const In& sampler, const In& texcoord, const Out& lhs, int groupOrder) -{ - setOperands({sampler, texcoord, lhs}); - mGroupExecutionOrder = groupOrder; - mFunctionName = "sampleTexture"; -} - -void SampleTextureAtom::writeSourceCode(std::ostream& os, const String& targetLanguage) const -{ - OperandVector::const_iterator outOp = mOperands.begin(); - // find the output operand - while(outOp->getSemantic() != Operand::OPS_OUT) - outOp++; - writeOperands(os, outOp, mOperands.end()); - os << "\t=\t"; - - os << "texture"; - const auto& sampler = mOperands.front().getParameter(); - switch(sampler->getType()) - { - case GCT_SAMPLER1D: - os << "1D"; - break; - case GCT_SAMPLER_EXTERNAL_OES: - case GCT_SAMPLER2D: - os << "2D"; - break; - case GCT_SAMPLER3D: - os << "3D"; - break; - case GCT_SAMPLERCUBE: - os << "Cube"; - break; - default: - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "unknown sampler"); - break; - } - - os << "("; - writeOperands(os, mOperands.begin(), outOp); - os << ");"; -} - -BinaryOpAtom::BinaryOpAtom(char op, const In& a, const In& b, const Out& dst, int groupOrder) { - // do this backwards for compatibility with FFP_FUNC_ASSIGN calls - setOperands({a, b, dst}); - mGroupExecutionOrder = groupOrder; - mOp = op; - mFunctionName = op; -} - -void BinaryOpAtom::writeSourceCode(std::ostream& os, const String& targetLanguage) const -{ - // find the output operand - OperandVector::const_iterator outOp = mOperands.begin(); - while(outOp->getSemantic() != Operand::OPS_OUT) - outOp++; - - // find the second operand - OperandVector::const_iterator secondOp = ++(mOperands.begin()); - while(outOp->getIndirectionLevel() != 0) - secondOp++; - - writeOperands(os, outOp, mOperands.end()); - os << "\t=\t"; - writeOperands(os, mOperands.begin(), secondOp); - os << mOp; - writeOperands(os, secondOp, outOp); - os << ";"; -} - -void BuiltinFunctionAtom::writeSourceCode(std::ostream& os, const String& targetLanguage) const -{ - // find the output operand - OperandVector::const_iterator outOp = mOperands.begin(); - while(outOp->getSemantic() != Operand::OPS_OUT) - outOp++; - - writeOperands(os, outOp, mOperands.end()); - os << "\t=\t" << mFunctionName << "("; - writeOperands(os, mOperands.begin(), outOp); - os << ");"; -} - -} -} diff --git a/Components/RTShaderSystem/src/OgreShaderGLSLESProgramWriter.cpp b/Components/RTShaderSystem/src/OgreShaderGLSLESProgramWriter.cpp deleted file mode 100644 index 1b5b02fa888..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderGLSLESProgramWriter.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreShaderPrecompiledHeaders.h" - -namespace Ogre { - namespace RTShader { - - String GLSLESProgramWriter::TargetLanguage = "glsles"; - - //----------------------------------------------------------------------- - GLSLESProgramWriter::GLSLESProgramWriter() - { - mIsGLSLES = true; - auto* rs = Root::getSingleton().getRenderSystem(); - mGLSLVersion = rs ? rs->getNativeShadingLanguageVersion() : 100; - initializeStringMaps(); - } - - //----------------------------------------------------------------------- - GLSLESProgramWriter::~GLSLESProgramWriter() - { - } - //----------------------------------------------------------------------- - void GLSLESProgramWriter::writeSourceCode( - std::ostream& os, - Program* program) - { - // Write the current version (this forces the driver to fulfill the glsl es standard) - os << "#version "<< mGLSLVersion; - - // Starting with ES 3.0 the version must contain the string "es" after the version number with a space separating them - if(mGLSLVersion > 100) - os << " es"; - - os << std::endl; - - for(const auto& p : program->getParameters()) - { - if(p->getType() != GCT_SAMPLER_EXTERNAL_OES) - continue; - if(mGLSLVersion > 100) - os << "#extension GL_OES_EGL_image_external_essl3 : require\n"; - else - os << "#extension GL_OES_EGL_image_external : require\n"; - - break; - } - - // Generate source code header. - writeProgramTitle(os, program); - os<< std::endl; - - // Embed dependencies. - writeProgramDependencies(os, program); - os << std::endl; - writeMainSourceCode(os, program); - } - - } -} diff --git a/Components/RTShaderSystem/src/OgreShaderGLSLESProgramWriter.h b/Components/RTShaderSystem/src/OgreShaderGLSLESProgramWriter.h deleted file mode 100644 index fb138f8078f..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderGLSLESProgramWriter.h +++ /dev/null @@ -1,84 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderProgramWriterGLSLES_ -#define _ShaderProgramWriterGLSLES_ - -#include "OgreShaderProgramWriterManager.h" -#include "OgreShaderGLSLProgramWriter.h" -#include "OgreShaderParameter.h" -#include "OgreStringVector.h" - -namespace Ogre { -namespace RTShader { - - class Function; - class FunctionInvocation; - class Operand; - class Program; - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** GLSL ES target language writer implementation. -@see ProgramWriter. -*/ -class GLSLESProgramWriter : public GLSLProgramWriter -{ - // Interface. -public: - - /** Class constructor. - */ - GLSLESProgramWriter (); - - /** Class destructor */ - virtual ~GLSLESProgramWriter (); - - - /** - @see ProgramWriter::writeSourceCode. - */ - void writeSourceCode (std::ostream& os, Program* program) override; - - /** - @see ProgramWriter::getTargetLanguage. - */ - const String& getTargetLanguage () const override { return TargetLanguage; } - - static String TargetLanguage; -}; -/** @} */ -/** @} */ - -} -} - -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderGLSLProgramWriter.cpp b/Components/RTShaderSystem/src/OgreShaderGLSLProgramWriter.cpp deleted file mode 100644 index f34b2572e4d..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderGLSLProgramWriter.cpp +++ /dev/null @@ -1,357 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreShaderPrecompiledHeaders.h" - -namespace Ogre { -namespace RTShader { - -String GLSLProgramWriter::TargetLanguage = "glsl"; - -//----------------------------------------------------------------------- -GLSLProgramWriter::GLSLProgramWriter() : mIsGLSLES(false), mIsVulkan(false) -{ - auto* rs = Root::getSingleton().getRenderSystem(); - mGLSLVersion = rs ? rs->getNativeShadingLanguageVersion() : 120; - - if(rs && rs->getCapabilities()->isShaderProfileSupported("spirv")) - { - mGLSLVersion = 460; - mIsVulkan = true; - } - - initializeStringMaps(); -} - -//----------------------------------------------------------------------- -GLSLProgramWriter::~GLSLProgramWriter() -{ - -} - -//----------------------------------------------------------------------- -void GLSLProgramWriter::initializeStringMaps() -{ - // basic glsl types - mGpuConstTypeMap[GCT_FLOAT1] = "float"; - mGpuConstTypeMap[GCT_FLOAT2] = "vec2"; - mGpuConstTypeMap[GCT_FLOAT3] = "vec3"; - mGpuConstTypeMap[GCT_FLOAT4] = "vec4"; - mGpuConstTypeMap[GCT_SAMPLER1D] = "sampler1D"; - mGpuConstTypeMap[GCT_SAMPLER2D] = "sampler2D"; - mGpuConstTypeMap[GCT_SAMPLER2DARRAY] = "sampler2DArray"; - mGpuConstTypeMap[GCT_SAMPLER3D] = "sampler3D"; - mGpuConstTypeMap[GCT_SAMPLERCUBE] = "samplerCube"; - mGpuConstTypeMap[GCT_SAMPLER1DSHADOW] = "sampler1DShadow"; - mGpuConstTypeMap[GCT_SAMPLER2DSHADOW] = "sampler2DShadow"; - mGpuConstTypeMap[GCT_SAMPLER_EXTERNAL_OES] = "samplerExternalOES"; - mGpuConstTypeMap[GCT_MATRIX_2X2] = "mat2"; - mGpuConstTypeMap[GCT_MATRIX_2X3] = "mat2x3"; - mGpuConstTypeMap[GCT_MATRIX_2X4] = "mat2x4"; - mGpuConstTypeMap[GCT_MATRIX_3X2] = "mat3x2"; - mGpuConstTypeMap[GCT_MATRIX_3X3] = "mat3"; - mGpuConstTypeMap[GCT_MATRIX_3X4] = "mat3x4"; - mGpuConstTypeMap[GCT_MATRIX_4X2] = "mat4x2"; - mGpuConstTypeMap[GCT_MATRIX_4X3] = "mat4x3"; - mGpuConstTypeMap[GCT_MATRIX_4X4] = "mat4"; - mGpuConstTypeMap[GCT_INT1] = "int"; - mGpuConstTypeMap[GCT_INT2] = "ivec2"; - mGpuConstTypeMap[GCT_INT3] = "ivec3"; - mGpuConstTypeMap[GCT_INT4] = "ivec4"; - mGpuConstTypeMap[GCT_UINT1] = "uint"; - mGpuConstTypeMap[GCT_UINT2] = "uvec2"; - mGpuConstTypeMap[GCT_UINT3] = "uvec3"; - mGpuConstTypeMap[GCT_UINT4] = "uvec4"; - - // Custom vertex attributes defined http://www.ogre3d.org/docs/manual/manual_21.html - mParamSemanticToNameMap[Parameter::SPS_POSITION] = "vertex"; - mParamSemanticToNameMap[Parameter::SPS_NORMAL] = "normal"; - mParamSemanticToNameMap[Parameter::SPS_TANGENT] = "tangent"; - mParamSemanticToNameMap[Parameter::SPS_BINORMAL] = "binormal"; - mParamSemanticToNameMap[Parameter::SPS_BLEND_INDICES] = "blendIndices"; - mParamSemanticToNameMap[Parameter::SPS_BLEND_WEIGHTS] = "blendWeights"; - - mParamSemanticToNameMap[Parameter::SPS_COLOR] = "colour"; -} - -//----------------------------------------------------------------------- -void GLSLProgramWriter::writeSourceCode(std::ostream& os, Program* program) -{ - // Write the current version (this force the driver to more fulfill the glsl standard) - os << "#version "<< mGLSLVersion << std::endl; - - // Generate dependencies. - writeProgramDependencies(os, program); - os << std::endl; - - writeMainSourceCode(os, program); -} - -void GLSLProgramWriter::writeUniformBlock(std::ostream& os, const String& name, int binding, - const UniformParameterList& uniforms) -{ - os << "layout(binding = " << binding << ", row_major) uniform " << name << " {\n"; - - for (const auto& uparam : uniforms) - { - if(uparam->getType() == GCT_MATRIX_3X4 || uparam->getType() == GCT_MATRIX_2X4) - os << "layout(column_major) "; - writeParameter(os, uparam); - os << ";\n"; - } - - os << "};\n"; -} - -void GLSLProgramWriter::writeMainSourceCode(std::ostream& os, Program* program) -{ - GpuProgramType gpuType = program->getType(); - if(gpuType == GPT_GEOMETRY_PROGRAM) - { - OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, - "Geometry Program not supported in GLSL writer ", - "GLSLProgramWriter::writeSourceCode" ); - } - - const UniformParameterList& parameterList = program->getParameters(); - - // Generate global variable code. - writeUniformParametersTitle(os, program); - os << std::endl; - - auto* rs = Root::getSingleton().getRenderSystem(); - auto hasSSO = rs ? rs->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS) : false; - - // Write the uniforms - UniformParameterList uniforms; - for (const auto& param : parameterList) - { - if(!param->isSampler()) - { - uniforms.push_back(param); - continue; - } - writeSamplerParameter(os, param); - os << ";" << std::endl; - } - if (mIsVulkan && !uniforms.empty()) - { - writeUniformBlock(os, "OgreUniforms", gpuType, uniforms); - uniforms.clear(); - } - - int uniformLoc = 0; - for (const auto& uparam : uniforms) - { - if(mGLSLVersion >= 430 && hasSSO) - { - os << "layout(location = " << uniformLoc << ") "; - auto esize = GpuConstantDefinition::getElementSize(uparam->getType(), true) / 4; - uniformLoc += esize * std::max(uparam->getSize(), 1); - } - - os << "uniform\t"; - if(mIsGLSLES) - os << "highp\t"; // force highp to avoid precision mismatch between VP/ FP - writeParameter(os, uparam); - os << ";\n"; - } - os << std::endl; - - Function* curFunction = program->getMain(); - const ShaderParameterList& inParams = curFunction->getInputParameters(); - - writeFunctionTitle(os, curFunction); - - // Write inout params and fill mInputToGLStatesMap - writeInputParameters(os, curFunction, gpuType); - writeOutParameters(os, curFunction, gpuType); - - // The function name must always main. - os << "void main(void) {" << std::endl; - - // Write local parameters. - const ShaderParameterList& localParams = curFunction->getLocalParameters(); - ShaderParameterConstIterator itParam = localParams.begin(); - ShaderParameterConstIterator itParamEnd = localParams.end(); - - for (; itParam != itParamEnd; ++itParam) - { - os << "\t"; - writeParameter(os, *itParam); - os << ";" << std::endl; - } - os << std::endl; - - for (const auto& pFuncInvoc : curFunction->getAtomInstances()) - { - redirectGlobalWrites(os, pFuncInvoc, inParams, parameterList); - for (auto& operand : pFuncInvoc->getOperandList()) - { - const ParameterPtr& param = operand.getParameter(); - if (gpuType != GPT_VERTEX_PROGRAM || param->getSemantic() != Parameter::SPS_TEXTURE_COORDINATES) - continue; - - bool isInputParam = std::find(inParams.begin(), inParams.end(), param) != inParams.end(); - - // Now that every texcoord is a vec4 (passed as vertex attributes) we - // have to swizzle them according the desired type. - if (isInputParam) - operand.setMaskToParamType(); - } - - os << "\t"; - pFuncInvoc->writeSourceCode(os, getTargetLanguage()); - os << std::endl; - } - os << "}" << std::endl; - os << std::endl; -} - -//----------------------------------------------------------------------- -void GLSLProgramWriter::writeInputParameters(std::ostream& os, Function* function, GpuProgramType gpuType) -{ - const ShaderParameterList& inParams = function->getInputParameters(); - - ShaderParameterConstIterator itParam = inParams.begin(); - ShaderParameterConstIterator itParamEnd = inParams.end(); - - int psInLocation = 0; - - for ( ; itParam != itParamEnd; ++itParam) - { - const ParameterPtr& pParam = *itParam; - auto paramContent = pParam->getContent(); - auto paramSemantic = pParam->getSemantic(); - const String& paramName = pParam->getName(); - - if (gpuType == GPT_FRAGMENT_PROGRAM) - { - if(paramContent == Parameter::SPC_POINTSPRITE_COORDINATE) - { - pParam->_rename("gl_PointCoord"); - continue; - } - else if(paramContent == Parameter::SPC_POINTSPRITE_SIZE) - { - // injected by matchVStoPSInterface, but only available in VS - continue; - } - else if(paramSemantic == Parameter::SPS_POSITION) - { - pParam->_rename("gl_FragCoord"); - continue; - } - else if(paramSemantic == Parameter::SPS_FRONT_FACING) - { - pParam->_rename("gl_FrontFacing"); - continue; - } - - os << "IN("; - if(pParam->isHighP()) - os << "f32"; // rely on unified shader vor f32vec4 etc. - os << mGpuConstTypeMap[pParam->getType()]; - os << "\t"; - os << paramName; - os << ", " << psInLocation++ << ")\n"; - } - else if (gpuType == GPT_VERTEX_PROGRAM) - { - // Due the fact that glsl does not have register like cg we have to rename the params - if(paramSemantic == Parameter::SPS_TEXTURE_COORDINATES) - pParam->_rename(StringUtil::format("uv%d", pParam->getIndex())); - else if(paramContent == Parameter::SPC_COLOR_SPECULAR) - pParam->_rename("secondary_colour"); - else - pParam->_rename(mParamSemanticToNameMap[paramSemantic]); - - os << "IN("; - // all uv texcoords passed by ogre are at least vec4 - if ((paramSemantic == Parameter::SPS_TEXTURE_COORDINATES) && (pParam->getType() < GCT_FLOAT4)) - { - os << "vec4"; - } - else - { - // the gl rendersystems only pass float attributes - GpuConstantType type = pParam->getType(); - if(!mIsVulkan && !GpuConstantDefinition::isFloat(type)) - type = GpuConstantType(type & ~GpuConstantDefinition::getBaseType(type)); - os << mGpuConstTypeMap[type]; - } - os << "\t"; - os << pParam->getName() << ", "; - writeParameterSemantic(os, pParam); // maps to location - os << ")\n"; - } - } -} - -//----------------------------------------------------------------------- -void GLSLProgramWriter::writeOutParameters(std::ostream& os, Function* function, GpuProgramType gpuType) -{ - const ShaderParameterList& outParams = function->getOutputParameters(); - int vsOutLocation = 0; - - for (const auto& p : outParams) - { - if(gpuType == GPT_VERTEX_PROGRAM) - { - // GLSL vertex program has to write always gl_Position (but this is also deprecated after version 130) - if(p->getSemantic() == Parameter::SPS_POSITION) - { - p->_rename("gl_Position"); - } - else if(p->getContent() == Parameter::SPC_POINTSPRITE_SIZE) - { - p->_rename("gl_PointSize"); - } - else - { - os << "OUT("; - writeParameter(os, p); - os << ", " << vsOutLocation++ << ")\n"; - } - } - else if(gpuType == GPT_FRAGMENT_PROGRAM && - p->getSemantic() == Parameter::SPS_COLOR) - { - if(p->getIndex() == 0) - { - // handled by UnifiedShader - p->_rename("gl_FragColor"); - continue; - } - - os << "OUT(vec4\t" << p->getName() << ", " << p->getIndex() << ")\n"; - } - } -} -//----------------------------------------------------------------------- -} -} diff --git a/Components/RTShaderSystem/src/OgreShaderGLSLProgramWriter.h b/Components/RTShaderSystem/src/OgreShaderGLSLProgramWriter.h deleted file mode 100644 index 0434dab4a04..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderGLSLProgramWriter.h +++ /dev/null @@ -1,108 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderProgramWriterGLSL_ -#define _ShaderProgramWriterGLSL_ - -#include "OgreShaderProgramWriterManager.h" -#include "OgreShaderProgramWriter.h" -#include "OgreShaderParameter.h" -#include "OgreStringVector.h" - -namespace Ogre { -namespace RTShader { - - class Function; - class Program; - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** GLSL target language writer implementation. -@see ProgramWriter. -*/ -class GLSLProgramWriter : public ProgramWriter -{ - // Interface. -public: - - /** Class constructor. - */ - GLSLProgramWriter(); - - /** Class destructor */ - virtual ~GLSLProgramWriter(); - - - /** - @see ProgramWriter::writeSourceCode. - */ - void writeSourceCode(std::ostream& os, Program* program) override; - - /** - @see ProgramWriter::getTargetLanguage. - */ - const String& getTargetLanguage() const override { return TargetLanguage; } - - static String TargetLanguage; - - // Protected methods. -protected: - void writeMainSourceCode(std::ostream& os, Program* program); - - /** Initialize string maps. */ - void initializeStringMaps(); - - /** Write the input params of the function */ - void writeInputParameters(std::ostream& os, Function* function, GpuProgramType gpuType); - - /** Write the output params of the function */ - void writeOutParameters(std::ostream& os, Function* function, GpuProgramType gpuType); - - void writeUniformBlock(std::ostream& os, const String& name, int binding, const UniformParameterList& uniforms); - -protected: - typedef std::map ParamSemanticToStringMap; - - // Map parameter content to vertex attributes - ParamSemanticToStringMap mParamSemanticToNameMap; - // Holds the current glsl version - int mGLSLVersion; - // set by derived class - bool mIsGLSLES; - bool mIsVulkan; -}; -/** @} */ -/** @} */ - -} -} - -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderGenerator.cpp b/Components/RTShaderSystem/src/OgreShaderGenerator.cpp deleted file mode 100644 index dac8f4c81e1..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderGenerator.cpp +++ /dev/null @@ -1,1870 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderPrecompiledHeaders.h" - -namespace Ogre { - -//----------------------------------------------------------------------- -template<> -RTShader::ShaderGenerator* Singleton::msSingleton = 0; - -namespace RTShader { - -/** Shader generator RenderObjectListener sub class. */ -class SGRenderObjectListener : public RenderObjectListener, public RTShaderSystemAlloc -{ -public: - SGRenderObjectListener(ShaderGenerator* owner) { mOwner = owner; } - - /** - Listener overridden function notify the shader generator when rendering single object. - */ - void notifyRenderSingleObject(Renderable* rend, const Pass* pass, - const AutoParamDataSource* source, const LightList* pLightList, - bool suppressRenderStateChanges) override - { - mOwner->notifyRenderSingleObject(rend, pass, source, pLightList, suppressRenderStateChanges); - } - -protected: - ShaderGenerator* mOwner; -}; - -/** Shader generator scene manager sub class. */ -class SGSceneManagerListener : public SceneManager::Listener, public RTShaderSystemAlloc -{ -public: - SGSceneManagerListener(ShaderGenerator* owner) { mOwner = owner; } - - /** - Listener overridden function notify the shader generator when finding visible objects process started. - */ - void preFindVisibleObjects(SceneManager* source, SceneManager::IlluminationRenderStage irs, - Viewport* v) override - { - mOwner->preFindVisibleObjects(source, irs, v); - } -protected: - // The shader generator instance. - ShaderGenerator* mOwner; -}; - -/** Shader generator ScriptTranslatorManager sub class. */ -class SGScriptTranslatorManager : public ScriptTranslatorManager -{ -public: - SGScriptTranslatorManager(ShaderGenerator* owner) { mOwner = owner; } - - /// Returns a manager for the given object abstract node, or null if it is not supported - ScriptTranslator* getTranslator(const AbstractNodePtr& node) override - { - return mOwner->getTranslator(node); - } - -protected: - // The shader generator instance. - ShaderGenerator* mOwner; -}; - -class SGResourceGroupListener : public ResourceGroupListener -{ -public: - SGResourceGroupListener(ShaderGenerator* owner) { mOwner = owner; } - - /// sync our internal list if material gets dropped - void resourceRemove(const ResourcePtr& resource) override - { - if (auto mat = dynamic_cast(resource.get())) - { - mOwner->removeAllShaderBasedTechniques(*mat); - } - } - -protected: - // The shader generator instance. - ShaderGenerator* mOwner; -}; - -String ShaderGenerator::DEFAULT_SCHEME_NAME = MSN_SHADERGEN; -String ShaderGenerator::SGTechnique::UserKey = "SGTechnique"; - -//----------------------------------------------------------------------- -ShaderGenerator* ShaderGenerator::getSingletonPtr() -{ - return msSingleton; -} - -//----------------------------------------------------------------------- -ShaderGenerator& ShaderGenerator::getSingleton() -{ - assert( msSingleton ); - return ( *msSingleton ); -} - -//----------------------------------------------------------------------------- -ShaderGenerator::ShaderGenerator() : - mActiveSceneMgr(NULL), mShaderLanguage(""), - mFSLayer(0), mActiveViewportValid(false), mVSOutputCompactPolicy(VSOCP_LOW), - mCreateShaderOverProgrammablePass(false), mIsFinalizing(false) -{ - mLightCount[0] = 0; - mLightCount[1] = 0; - mLightCount[2] = 0; - - HighLevelGpuProgramManager& hmgr = HighLevelGpuProgramManager::getSingleton(); - - if (hmgr.isLanguageSupported("glsles")) - { - mShaderLanguage = "glsles"; - } - else if (hmgr.isLanguageSupported("glsl")) - { - mShaderLanguage = "glsl"; - } - else if (hmgr.isLanguageSupported("hlsl")) - { - mShaderLanguage = "hlsl"; - } - else if (hmgr.isLanguageSupported("glslang")) - { - mShaderLanguage = "glslang"; - } - else - { - mShaderLanguage = "null"; // falling back to HLSL, for unit tests mainly - LogManager::getSingleton().logWarning("ShaderGenerator: No supported language found. Falling back to 'null'"); - } - - setShaderProfiles(GPT_VERTEX_PROGRAM, "vs_3_0 vs_2_a vs_2_0 vs_1_1"); - setShaderProfiles(GPT_FRAGMENT_PROGRAM, "ps_3_0 ps_2_a ps_2_b ps_2_0 ps_1_4 ps_1_3 ps_1_2 ps_1_1"); -} - -//----------------------------------------------------------------------------- -ShaderGenerator::~ShaderGenerator() -{ - -} - -//----------------------------------------------------------------------------- -bool ShaderGenerator::initialize() -{ - if (msSingleton == NULL) - { - msSingleton = OGRE_NEW ShaderGenerator; - if (false == msSingleton->_initialize()) - { - OGRE_DELETE msSingleton; - msSingleton = NULL; - return false; - } - } - - return true; -} - -//----------------------------------------------------------------------------- -bool ShaderGenerator::_initialize() -{ - OGRE_LOCK_AUTO_MUTEX; - - // Allocate program writer manager. - mProgramWriterManager.reset(new ProgramWriterManager); - - // Allocate program manager. - mProgramManager.reset(new ProgramManager); - - // Create extensions factories. - createBuiltinSRSFactories(); - - // Allocate script translator manager. - mScriptTranslatorManager.reset(new SGScriptTranslatorManager(this)); - ScriptCompilerManager::getSingleton().addTranslatorManager(mScriptTranslatorManager.get()); - ID_RT_SHADER_SYSTEM = ScriptCompilerManager::getSingleton().registerCustomWordId("rtshader_system"); - - // Create the default scheme. - createScheme(MSN_SHADERGEN); - - mResourceGroupListener.reset(new SGResourceGroupListener(this)); - ResourceGroupManager::getSingleton().addResourceGroupListener(mResourceGroupListener.get()); - - return true; -} - - - -//----------------------------------------------------------------------------- -void ShaderGenerator::createBuiltinSRSFactories() -{ - OGRE_LOCK_AUTO_MUTEX; - SubRenderStateFactory* curFactory; -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS - curFactory = OGRE_NEW FFPTransformFactory; - ShaderGenerator::getSingleton().addSubRenderStateFactory(curFactory); - mBuiltinSRSFactories.push_back(curFactory); - - curFactory = OGRE_NEW FFPColourFactory; - ShaderGenerator::getSingleton().addSubRenderStateFactory(curFactory); - mBuiltinSRSFactories.push_back(curFactory); - - curFactory = OGRE_NEW FFPLightingFactory; - ShaderGenerator::getSingleton().addSubRenderStateFactory(curFactory); - mBuiltinSRSFactories.push_back(curFactory); - - curFactory = OGRE_NEW FFPTexturingFactory; - ShaderGenerator::getSingleton().addSubRenderStateFactory(curFactory); - mBuiltinSRSFactories.push_back(curFactory); - - curFactory = OGRE_NEW FFPFogFactory; - ShaderGenerator::getSingleton().addSubRenderStateFactory(curFactory); - mBuiltinSRSFactories.push_back(curFactory); - - curFactory = OGRE_NEW FFPAlphaTestFactory; - ShaderGenerator::getSingleton().addSubRenderStateFactory(curFactory); - mBuiltinSRSFactories.push_back(curFactory); -#endif -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS - // check if we are running an old shader level in d3d11 - bool d3d11AndLowProfile = ( (GpuProgramManager::getSingleton().isSyntaxSupported("vs_4_0_level_9_1") || - GpuProgramManager::getSingleton().isSyntaxSupported("vs_4_0_level_9_3")) - && !GpuProgramManager::getSingleton().isSyntaxSupported("vs_4_0")); - if(!d3d11AndLowProfile) - { - curFactory = OGRE_NEW PerPixelLightingFactory; - addSubRenderStateFactory(curFactory); - mBuiltinSRSFactories.push_back(curFactory); - - curFactory = OGRE_NEW NormalMapLightingFactory; - addSubRenderStateFactory(curFactory); - mBuiltinSRSFactories.push_back(curFactory); - - curFactory = new CookTorranceLightingFactory; - addSubRenderStateFactory(curFactory); - mBuiltinSRSFactories.push_back(curFactory); - - curFactory = new ImageBasedLightingFactory; - addSubRenderStateFactory(curFactory); - mBuiltinSRSFactories.push_back(curFactory); - - curFactory = OGRE_NEW IntegratedPSSM3Factory; - addSubRenderStateFactory(curFactory); - mBuiltinSRSFactories.push_back(curFactory); - - curFactory = OGRE_NEW LayeredBlendingFactory; - addSubRenderStateFactory(curFactory); - mBuiltinSRSFactories.push_back(curFactory); - - curFactory = OGRE_NEW HardwareSkinningFactory; - addSubRenderStateFactory(curFactory); - mBuiltinSRSFactories.push_back(curFactory); - } - - curFactory = OGRE_NEW TriplanarTexturingFactory; - addSubRenderStateFactory(curFactory); - mBuiltinSRSFactories.push_back(curFactory); - - curFactory = OGRE_NEW GBufferFactory; - addSubRenderStateFactory(curFactory); - mBuiltinSRSFactories.push_back(curFactory); - - curFactory = OGRE_NEW WBOITFactory; - addSubRenderStateFactory(curFactory); - mBuiltinSRSFactories.push_back(curFactory); -#endif -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::destroy() -{ - if (msSingleton != NULL) - { - msSingleton->_destroy(); - - OGRE_DELETE msSingleton; - msSingleton = NULL; - } -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::_destroy() -{ - OGRE_LOCK_AUTO_MUTEX; - - mIsFinalizing = true; - - // Delete technique entries. - for (auto& e : mTechniqueEntriesMap) - { - OGRE_DELETE (e.second); - } - mTechniqueEntriesMap.clear(); - - // Delete material entries. - for (auto& m : mMaterialEntriesMap) - { - OGRE_DELETE (m.second); - } - mMaterialEntriesMap.clear(); - - // Delete scheme entries. - for (auto& s : mSchemeEntriesMap) - { - OGRE_DELETE (s.second); - } - mSchemeEntriesMap.clear(); - - // Destroy extensions factories. - destroyBuiltinSRSFactories(); - - mProgramManager.reset(); - mProgramWriterManager.reset(); - - // Delete script translator manager. - if (mScriptTranslatorManager) - { - ScriptCompilerManager::getSingleton().removeTranslatorManager(mScriptTranslatorManager.get()); - mScriptTranslatorManager.reset(); - } - - mMaterialSerializerListener.reset(); - - if (mResourceGroupListener) - { - ResourceGroupManager::getSingleton().removeResourceGroupListener(mResourceGroupListener.get()); - mResourceGroupListener.reset(); - } - - // Remove all scene managers. - while (mSceneManagerMap.empty() == false) - { - removeSceneManager(*mSceneManagerMap.begin()); - } - - mRenderObjectListener.reset(); - mSceneManagerListener.reset(); -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::destroyBuiltinSRSFactories() -{ - OGRE_LOCK_AUTO_MUTEX; - - for (auto f : mBuiltinSRSFactories) - { - removeSubRenderStateFactory(f); - delete f; - } - mBuiltinSRSFactories.clear(); -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::addSubRenderStateFactory(SubRenderStateFactory* factory) -{ - OGRE_LOCK_AUTO_MUTEX; - - SubRenderStateFactoryIterator itFind = mSubRenderStateFactories.find(factory->getType()); - - if (itFind != mSubRenderStateFactories.end()) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "A factory of type '" + factory->getType() + "' already exists.", - "ShaderGenerator::addSubRenderStateFactory"); - } - - mSubRenderStateFactories[factory->getType()] = factory; -} - -//----------------------------------------------------------------------------- -size_t ShaderGenerator::getNumSubRenderStateFactories() const -{ - return mSubRenderStateFactories.size(); -} - - -//----------------------------------------------------------------------------- -SubRenderStateFactory* ShaderGenerator::getSubRenderStateFactory(size_t index) -{ - { - OGRE_LOCK_AUTO_MUTEX; - - SubRenderStateFactoryIterator itFind = mSubRenderStateFactories.begin(); - for(; index != 0 && itFind != mSubRenderStateFactories.end(); --index , ++itFind); - - if (itFind != mSubRenderStateFactories.end()) - { - return itFind->second; - } - } - - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "A factory on index " + StringConverter::toString(index) + " does not exist.", - "ShaderGenerator::addSubRenderStateFactory"); - - return NULL; -} -//----------------------------------------------------------------------------- -SubRenderStateFactory* ShaderGenerator::getSubRenderStateFactory(const String& type) -{ - OGRE_LOCK_AUTO_MUTEX; - - SubRenderStateFactoryIterator itFind = mSubRenderStateFactories.find(type); - return (itFind != mSubRenderStateFactories.end()) ? itFind->second : NULL; -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::removeSubRenderStateFactory(SubRenderStateFactory* factory) -{ - OGRE_LOCK_AUTO_MUTEX; - - SubRenderStateFactoryIterator itFind = mSubRenderStateFactories.find(factory->getType()); - - if (itFind != mSubRenderStateFactories.end()) - mSubRenderStateFactories.erase(itFind); - -} - -//----------------------------------------------------------------------------- -SubRenderState* ShaderGenerator::createSubRenderState(const String& type) -{ - OGRE_LOCK_AUTO_MUTEX; - - SubRenderStateFactoryIterator itFind = mSubRenderStateFactories.find(type); - - if (itFind != mSubRenderStateFactories.end()) - return itFind->second->createInstance(); - - - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "A factory of type '" + type + "' doesn't exists.", - "ShaderGenerator::createSubRenderState"); - - return NULL; -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::destroySubRenderState(SubRenderState* subRenderState) -{ - OGRE_LOCK_AUTO_MUTEX; - - SubRenderStateFactoryIterator itFind = mSubRenderStateFactories.find(subRenderState->getType()); - - if (itFind != mSubRenderStateFactories.end()) - { - itFind->second->destroyInstance(subRenderState); - } -} - -//----------------------------------------------------------------------------- -SubRenderState* ShaderGenerator::createSubRenderState(ScriptCompiler* compiler, - PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) -{ - OGRE_LOCK_AUTO_MUTEX; - SubRenderState* subRenderState = NULL; - - for (auto& s : mSubRenderStateFactories) - { - subRenderState = s.second->createInstance(compiler, prop, pass, translator); - if (subRenderState != NULL) - break; - } - - return subRenderState; -} - - -//----------------------------------------------------------------------------- -SubRenderState* ShaderGenerator::createSubRenderState(ScriptCompiler* compiler, - PropertyAbstractNode* prop, TextureUnitState* texState, SGScriptTranslator* translator) -{ - OGRE_LOCK_AUTO_MUTEX; - SubRenderState* subRenderState = NULL; - - for (auto& s : mSubRenderStateFactories) - { - subRenderState = s.second->createInstance(compiler, prop, texState, translator); - if (subRenderState != NULL) - break; - } - - return subRenderState; -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::createScheme(const String& schemeName) -{ - createOrRetrieveScheme(schemeName); -} - -//----------------------------------------------------------------------------- -RenderState* ShaderGenerator::getRenderState(const String& schemeName) -{ - OGRE_LOCK_AUTO_MUTEX; - - SGSchemeIterator itFind = mSchemeEntriesMap.find(schemeName); - - if (itFind == mSchemeEntriesMap.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "A scheme named'" + schemeName + "' doesn't exists.", - "ShaderGenerator::getRenderState"); - } - - return itFind->second->getRenderState(); -} - -//----------------------------------------------------------------------------- -bool ShaderGenerator::hasRenderState(const String& schemeName) const -{ - OGRE_LOCK_AUTO_MUTEX; - - SGSchemeConstIterator itFind = mSchemeEntriesMap.find(schemeName); - return itFind != mSchemeEntriesMap.end(); -} - -//----------------------------------------------------------------------------- -ShaderGenerator::RenderStateCreateOrRetrieveResult ShaderGenerator::createOrRetrieveRenderState(const String& schemeName) -{ - SchemeCreateOrRetrieveResult res = createOrRetrieveScheme(schemeName); - return RenderStateCreateOrRetrieveResult(res.first->getRenderState(),res.second); -} - -//----------------------------------------------------------------------------- -ShaderGenerator::SchemeCreateOrRetrieveResult ShaderGenerator::createOrRetrieveScheme(const String& schemeName) -{ - OGRE_LOCK_AUTO_MUTEX; - - bool wasCreated = false; - SGSchemeIterator itScheme = mSchemeEntriesMap.find(schemeName); - SGScheme* schemeEntry = NULL; - - if (itScheme == mSchemeEntriesMap.end()) - { - schemeEntry = OGRE_NEW SGScheme(schemeName); - mSchemeEntriesMap.emplace(schemeName, schemeEntry); - wasCreated = true; - } - else - { - schemeEntry = itScheme->second; - } - - return SchemeCreateOrRetrieveResult(schemeEntry, wasCreated); -} -//----------------------------------------------------------------------------- -RenderState* ShaderGenerator::getRenderState(const String& schemeName, - const String& materialName, - const String& groupName, - unsigned short passIndex) -{ - OGRE_LOCK_AUTO_MUTEX; - - SGSchemeIterator itFind = mSchemeEntriesMap.find(schemeName); - - if (itFind == mSchemeEntriesMap.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "A scheme named'" + schemeName + "' doesn't exists.", - "ShaderGenerator::getRenderState"); - } - - return itFind->second->getRenderState(materialName, groupName, passIndex); -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::addSceneManager(SceneManager* sceneMgr) -{ - // Make sure this scene manager not exists in the set. - if (!mSceneManagerMap.insert(sceneMgr).second) - return; - - if (!mRenderObjectListener) - mRenderObjectListener.reset(new SGRenderObjectListener(this)); - - sceneMgr->addRenderObjectListener(mRenderObjectListener.get()); - - if (!mSceneManagerListener) - mSceneManagerListener.reset(new SGSceneManagerListener(this)); - - sceneMgr->addListener(mSceneManagerListener.get()); - - // Update the active scene manager. - if (mActiveSceneMgr == NULL) - mActiveSceneMgr = sceneMgr; -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::removeSceneManager(SceneManager* sceneMgr) -{ - // Make sure this scene manager exists in the map. - SceneManagerIterator itFind = mSceneManagerMap.find(sceneMgr); - - if (itFind != mSceneManagerMap.end()) - { - (*itFind)->removeRenderObjectListener(mRenderObjectListener.get()); - (*itFind)->removeListener(mSceneManagerListener.get()); - - mSceneManagerMap.erase(itFind); - - // Update the active scene manager. - if (mActiveSceneMgr == sceneMgr) { - mActiveSceneMgr = NULL; - - // force refresh global scene manager material - invalidateMaterial(MSN_SHADERGEN, "Ogre/TextureShadowReceiver", RGN_INTERNAL); - } - } -} - -//----------------------------------------------------------------------------- -SceneManager* ShaderGenerator::getActiveSceneManager() -{ - return mActiveSceneMgr; -} -//----------------------------------------------------------------------------- -void ShaderGenerator::_setActiveSceneManager(SceneManager* sceneManager) -{ - mActiveViewportValid &= (mActiveSceneMgr == sceneManager); - mActiveSceneMgr = sceneManager; -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::setShaderProfiles(GpuProgramType type, const String& shaderProfiles) -{ - switch(type) - { - case GPT_VERTEX_PROGRAM: - mVertexShaderProfiles = shaderProfiles; - break; - case GPT_FRAGMENT_PROGRAM: - mFragmentShaderProfiles = shaderProfiles; - break; - default: - OgreAssert(false, "not implemented"); - break; - } -} - -const String& ShaderGenerator::getShaderProfiles(GpuProgramType type) const -{ - switch(type) - { - case GPT_VERTEX_PROGRAM: - return mVertexShaderProfiles; - case GPT_FRAGMENT_PROGRAM: - return mFragmentShaderProfiles; - default: - return BLANKSTRING; - } -} -//----------------------------------------------------------------------------- -bool ShaderGenerator::hasShaderBasedTechnique(const String& materialName, - const String& groupName, - const String& srcTechniqueSchemeName, - const String& dstTechniqueSchemeName) const -{ - OGRE_LOCK_AUTO_MUTEX; - - // Make sure material exists; - if (false == MaterialManager::getSingleton().resourceExists(materialName, groupName)) - return false; - - - SGMaterialConstIterator itMatEntry = findMaterialEntryIt(materialName, groupName); - - // Check if technique already created. - if (itMatEntry != mMaterialEntriesMap.end()) - { - const SGTechniqueList& techniqueEntires = itMatEntry->second->getTechniqueList(); - for (auto* t : techniqueEntires) { - // Check requested mapping already exists. - if (t->getSourceTechnique()->getSchemeName() == srcTechniqueSchemeName && t->getDestinationTechniqueSchemeName() == dstTechniqueSchemeName) - return true; - } - } - return false; -} -//----------------------------------------------------------------------------- -static bool hasFixedFunctionPass(Technique* tech) -{ - for (unsigned short i=0; i < tech->getNumPasses(); ++i) - { - if (!tech->getPass(i)->isProgrammable()) - { - return true; - } - } - return false; -} - -static Technique* findSourceTechnique(const Material& mat, const String& srcTechniqueSchemeName, bool overProgrammable) -{ - // Find the source technique - for (auto *t : mat.getTechniques()) - { - if (t->getSchemeName() == srcTechniqueSchemeName && t->isSupported() && - (hasFixedFunctionPass(t) || overProgrammable)) - { - return t; - } - } - - return NULL; -} -//----------------------------------------------------------------------------- -bool ShaderGenerator::createShaderBasedTechnique(const Material& srcMat, - const String& srcTechniqueSchemeName, - const String& dstTechniqueSchemeName, - bool overProgrammable) -{ - // No technique created -> check if one can be created from the given source technique scheme. - Technique* srcTechnique = findSourceTechnique(srcMat, srcTechniqueSchemeName, overProgrammable); - - // No appropriate source technique found. - if (!srcTechnique) - { - return false; - } - - return createShaderBasedTechnique(srcTechnique, dstTechniqueSchemeName, overProgrammable); -} - -bool ShaderGenerator::createShaderBasedTechnique(const Technique* srcTechnique, const String& dstTechniqueSchemeName, - bool overProgrammable) -{ - OGRE_LOCK_AUTO_MUTEX; - - // Update group name in case it is AUTODETECT_RESOURCE_GROUP_NAME - Material* srcMat = srcTechnique->getParent(); - const String& materialName = srcMat->getName(); - const String& trueGroupName = srcMat->getGroup(); - - SGMaterialIterator itMatEntry = findMaterialEntryIt(materialName, trueGroupName); - - // Check if technique already created. - if (itMatEntry != mMaterialEntriesMap.end()) - { - const SGTechniqueList& techniqueEntires = itMatEntry->second->getTechniqueList(); - for (auto* t : techniqueEntires) - { - // Case the requested mapping already exists. - if (t->getSourceTechnique()->getSchemeName() == srcTechnique->getSchemeName() && t->getDestinationTechniqueSchemeName() == dstTechniqueSchemeName) - return true; - // Case a shader based technique with the same scheme name already defined based - // on different source technique. - // This state might lead to conflicts during shader generation - we prevent it by returning false here. - else if (t->getDestinationTechniqueSchemeName() == dstTechniqueSchemeName) - return false; - } - } - - // Create shader based technique from the given source technique. - SGMaterial* matEntry = NULL; - - if (itMatEntry == mMaterialEntriesMap.end()) - { - matEntry = OGRE_NEW SGMaterial(materialName, trueGroupName); - mMaterialEntriesMap.emplace(MatGroupPair(materialName, trueGroupName), matEntry); - } - else - { - matEntry = itMatEntry->second; - } - - // Create the new technique entry. - SGTechnique* techEntry = - OGRE_NEW SGTechnique(matEntry, srcTechnique, dstTechniqueSchemeName, overProgrammable); - - // Add to material entry map. - matEntry->getTechniqueList().push_back(techEntry); - - // Add to all technique map. - mTechniqueEntriesMap[techEntry] = techEntry; - - // Add to scheme. - SGScheme* schemeEntry = createOrRetrieveScheme(dstTechniqueSchemeName).first; - schemeEntry->addTechniqueEntry(techEntry); - - return true; -} - -bool ShaderGenerator::removeShaderBasedTechnique(const Technique* srcTech, const String& dstTechniqueSchemeName) -{ - OGRE_LOCK_AUTO_MUTEX; - - // Make sure scheme exists. - SGSchemeIterator itScheme = mSchemeEntriesMap.find(dstTechniqueSchemeName); - SGScheme* schemeEntry = NULL; - - if (itScheme == mSchemeEntriesMap.end()) - return false; - - schemeEntry = itScheme->second; - - // Find the material entry. - Material* srcMat = srcTech->getParent(); - SGMaterialIterator itMatEntry = findMaterialEntryIt(srcMat->getName(), srcMat->getGroup()); - - // Case material not found. - if (itMatEntry == mMaterialEntriesMap.end()) - return false; - - - SGTechniqueList& matTechniqueEntires = itMatEntry->second->getTechniqueList(); - SGTechniqueIterator itTechEntry = matTechniqueEntires.begin(); - SGTechnique* dstTechnique = NULL; - - // Remove destination technique entry from material techniques list. - for (; itTechEntry != matTechniqueEntires.end(); ++itTechEntry) - { - if ((*itTechEntry)->getSourceTechnique()->getSchemeName() == srcTech->getSchemeName() && - (*itTechEntry)->getDestinationTechniqueSchemeName() == dstTechniqueSchemeName) - { - dstTechnique = *itTechEntry; - matTechniqueEntires.erase(itTechEntry); - break; - } - } - - // Technique not found. - if (dstTechnique == NULL) - return false; - - schemeEntry->removeTechniqueEntry(dstTechnique); - - SGTechniqueMapIterator itTechMap = mTechniqueEntriesMap.find(dstTechnique); - - if (itTechMap != mTechniqueEntriesMap.end()) - mTechniqueEntriesMap.erase(itTechMap); - - OGRE_DELETE dstTechnique; - - return true; -} - -//----------------------------------------------------------------------------- -bool ShaderGenerator::removeAllShaderBasedTechniques(const String& materialName, const String& groupName) -{ - OGRE_LOCK_AUTO_MUTEX; - - // Find the material entry. - SGMaterialIterator itMatEntry = findMaterialEntryIt(materialName, groupName); - - // Case material not found. - if (itMatEntry == mMaterialEntriesMap.end()) - return false; - - - SGTechniqueList& matTechniqueEntires = itMatEntry->second->getTechniqueList(); - - // Remove all technique entries from material techniques list. - while (matTechniqueEntires.empty() == false) - { - SGTechniqueIterator itTechEntry = matTechniqueEntires.begin(); - - removeShaderBasedTechnique((*itTechEntry)->getSourceTechnique(), - (*itTechEntry)->getDestinationTechniqueSchemeName()); - } - - OGRE_DELETE itMatEntry->second; - mMaterialEntriesMap.erase(itMatEntry); - - return true; -} - -bool ShaderGenerator::cloneShaderBasedTechniques(const Material& srcMat, Material& dstMat) -{ - if(&srcMat == &dstMat) return true; // nothing to do - - SGMaterialIterator itSrcMatEntry = findMaterialEntryIt(srcMat.getName(), srcMat.getGroup()); - - //remove any techniques in the destination material so the new techniques may be copied - removeAllShaderBasedTechniques(dstMat); - - // - //remove any techniques from the destination material which have RTSS associated schemes from - //the source material. This code is performed in case the user performed a clone of a material - //which has already generated RTSS techniques in the source material. - // - - //first gather the techniques to remove - std::set schemesToRemove; - for(Technique* pSrcTech : srcMat.getTechniques()) - { - Pass* pSrcPass = pSrcTech->getNumPasses() > 0 ? pSrcTech->getPass(0) : NULL; - if (pSrcPass) - { - const Any& passUserData = pSrcPass->getUserObjectBindings().getUserAny(TargetRenderState::UserKey); - if (passUserData.has_value()) - { - schemesToRemove.insert(pSrcTech->_getSchemeIndex()); - } - } - } - //remove the techniques from the destination material - auto techCount = dstMat.getNumTechniques(); - for(unsigned short ti = techCount - 1 ; ti != (unsigned short)-1 ; --ti) - { - Technique* pDstTech = dstMat.getTechnique(ti); - if (schemesToRemove.find(pDstTech->_getSchemeIndex()) != schemesToRemove.end()) - { - dstMat.removeTechnique(ti); - } - } - - // - // Clone the render states from source to destination - // - - // Check if RTSS techniques exist in the source material - if (itSrcMatEntry != mMaterialEntriesMap.end()) - { - const SGTechniqueList& techniqueEntires = itSrcMatEntry->second->getTechniqueList(); - - //Go over all rtss techniques in the source material - for (auto* t : techniqueEntires) - { - String srcFromTechniqueScheme = t->getSourceTechnique()->getSchemeName(); - String srcToTechniqueScheme = t->getDestinationTechniqueSchemeName(); - - //for every technique in the source material create a shader based technique in the - //destination material - if (createShaderBasedTechnique(dstMat, srcFromTechniqueScheme, srcToTechniqueScheme)) - { - //check for custom render states in the source material - unsigned short passCount = t->getSourceTechnique()->getNumPasses(); - for(unsigned short pi = 0 ; pi < passCount ; ++pi) - { - if (t->hasRenderState(pi)) - { - //copy the custom render state from the source material to the destination material - RenderState* srcRenderState = t->getRenderState(pi); - RenderState* dstRenderState = getRenderState(srcToTechniqueScheme, dstMat, pi); - - const SubRenderStateList& srcSubRenderState = - srcRenderState->getSubRenderStates(); - - SubRenderStateList::const_iterator itSubState = srcSubRenderState.begin(), itSubStateEnd = srcSubRenderState.end(); - for(;itSubState != itSubStateEnd ; ++itSubState) - { - SubRenderState* srcSubState = *itSubState; - SubRenderState* dstSubState = createSubRenderState(srcSubState->getType()); - (*dstSubState) = (*srcSubState); - dstRenderState->addTemplateSubRenderState(dstSubState); - } - } - } - } - } - } - - return true; -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::removeAllShaderBasedTechniques() -{ - OGRE_LOCK_AUTO_MUTEX; - - while (!mMaterialEntriesMap.empty()) - { - SGMaterialIterator itMatEntry = mMaterialEntriesMap.begin(); - - removeAllShaderBasedTechniques(itMatEntry->first.first, itMatEntry->first.second); - } -} - -//----------------------------------------------------------------------------- - void ShaderGenerator::notifyRenderSingleObject(Renderable* rend, - const Pass* pass, - const AutoParamDataSource* source, - const LightList* pLightList, bool suppressRenderStateChanges) -{ - if (mActiveViewportValid) - { - const Any& passUserData = pass->getUserObjectBindings().getUserAny(TargetRenderState::UserKey); - - if (!passUserData.has_value() || suppressRenderStateChanges) - return; - - OGRE_LOCK_AUTO_MUTEX; - - auto renderState = any_cast(passUserData); - renderState->updateGpuProgramsParams(rend, pass, source, pLightList); - } -} - - -//----------------------------------------------------------------------------- -void ShaderGenerator::preFindVisibleObjects(SceneManager* source, - SceneManager::IlluminationRenderStage irs, - Viewport* v) -{ - OGRE_LOCK_AUTO_MUTEX; - - const String& curMaterialScheme = v->getMaterialScheme(); - - mActiveSceneMgr = source; - mActiveViewportValid = validateScheme(curMaterialScheme); -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::invalidateScheme(const String& schemeName) -{ - OGRE_LOCK_AUTO_MUTEX; - - SGSchemeIterator itScheme = mSchemeEntriesMap.find(schemeName); - - if (itScheme != mSchemeEntriesMap.end()) - itScheme->second->invalidate(); - -} - -//----------------------------------------------------------------------------- -bool ShaderGenerator::validateScheme(const String& schemeName) -{ - OGRE_LOCK_AUTO_MUTEX; - - SGSchemeIterator itScheme = mSchemeEntriesMap.find(schemeName); - - // No such scheme exists. - if (itScheme == mSchemeEntriesMap.end()) - return false; - - itScheme->second->validate(); - - return true; -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::invalidateMaterial(const String& schemeName, const String& materialName, const String& groupName) -{ - OGRE_LOCK_AUTO_MUTEX; - - SGSchemeIterator itScheme = mSchemeEntriesMap.find(schemeName); - - if (itScheme != mSchemeEntriesMap.end()) - itScheme->second->invalidate(materialName, groupName); -} - -//----------------------------------------------------------------------------- -bool ShaderGenerator::validateMaterial(const String& schemeName, const String& materialName, const String& groupName) -{ - OGRE_LOCK_AUTO_MUTEX; - - SGSchemeIterator itScheme = mSchemeEntriesMap.find(schemeName); - - // No such scheme exists. - if (itScheme == mSchemeEntriesMap.end()) - return false; - - return itScheme->second->validate(materialName, groupName); -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::invalidateMaterialIlluminationPasses(const String& schemeName, const String& materialName, const String& groupName) -{ - OGRE_LOCK_AUTO_MUTEX; - - SGSchemeIterator itScheme = mSchemeEntriesMap.find(schemeName); - - if(itScheme != mSchemeEntriesMap.end()) - itScheme->second->invalidateIlluminationPasses(materialName, groupName); -} - -//----------------------------------------------------------------------------- -bool ShaderGenerator::validateMaterialIlluminationPasses(const String& schemeName, const String& materialName, const String& groupName) -{ - OGRE_LOCK_AUTO_MUTEX; - - SGSchemeIterator itScheme = mSchemeEntriesMap.find(schemeName); - - // No such scheme exists. - if(itScheme == mSchemeEntriesMap.end()) - return false; - - return itScheme->second->validateIlluminationPasses(materialName, groupName); -} - -//----------------------------------------------------------------------------- -MaterialSerializer::Listener* ShaderGenerator::getMaterialSerializerListener() -{ - if (!mMaterialSerializerListener) - mMaterialSerializerListener.reset(new SGMaterialSerializerListener); - - return mMaterialSerializerListener.get(); -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::flushShaderCache() -{ - // Release all programs. - for (auto& t : mTechniqueEntriesMap) - { - t.second->releasePrograms(); - } - - ProgramManager::getSingleton().flushGpuProgramsCache(); - - // Invalidate all schemes. - for (auto& s : mSchemeEntriesMap) - { - s.second->invalidate(); - } -} - -//----------------------------------------------------------------------------- -ScriptTranslator* ShaderGenerator::getTranslator(const AbstractNodePtr& node) -{ - OGRE_LOCK_AUTO_MUTEX; - - if(node->type != ANT_OBJECT) - return NULL; - - ObjectAbstractNode *obj = static_cast(node.get()); - - if(obj->id == ID_RT_SHADER_SYSTEM) - return &mCoreScriptTranslator; - - return NULL; -} - -//----------------------------------------------------------------------------- -size_t ShaderGenerator::getShaderCount(GpuProgramType type) const -{ - return mProgramManager->getShaderCount(type); -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::setTargetLanguage(const String& shaderLanguage) -{ - // Make sure that the shader language is supported. - if (!mProgramWriterManager->isLanguageSupported(shaderLanguage)) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "'" + shaderLanguage + "' is not supported"); - } - - // Case target language changed -> flush the shaders cache. - if (mShaderLanguage != shaderLanguage) - { - mShaderLanguage = shaderLanguage; - flushShaderCache(); - } -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::setShaderCachePath( const String& cachePath ) -{ - String stdCachePath = cachePath; - - // Standardise the cache path in case of none empty string. - if (stdCachePath.empty() == false) - stdCachePath = StringUtil::standardisePath(stdCachePath); - - if (mShaderCachePath != stdCachePath) - { - mShaderCachePath = stdCachePath; - - // Case this is a valid file path -> add as resource location in order to make sure that - // generated shaders could be loaded by the file system archive. - if (mShaderCachePath.empty() == false) - { - // Make sure this is a valid writable path. - String outTestFileName(mShaderCachePath + "ShaderGenerator.tst"); - std::ofstream outFile(outTestFileName.c_str()); - - if (!outFile) - { - OGRE_EXCEPT(Exception::ERR_CANNOT_WRITE_TO_FILE, - "Could not create output files in the given shader cache path '" + mShaderCachePath, - "ShaderGenerator::setShaderCachePath"); - } - - // Close and remove the test file. - outFile.close(); - remove(outTestFileName.c_str()); - } - } -} - -//----------------------------------------------------------------------------- -ShaderGenerator::SGMaterialIterator ShaderGenerator::findMaterialEntryIt(const String& materialName, const String& groupName) -{ - SGMaterialIterator itMatEntry; - //check if we have auto detect request - if (groupName == ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME) - { - //find the possible first entry - itMatEntry = mMaterialEntriesMap.lower_bound(MatGroupPair(materialName,"")); - if ((itMatEntry != mMaterialEntriesMap.end()) && - (itMatEntry->first.first != materialName)) - { - //no entry found - itMatEntry = mMaterialEntriesMap.end(); - } - } - else - { - //find entry with group name specified - itMatEntry = mMaterialEntriesMap.find(MatGroupPair(materialName,groupName)); - } - return itMatEntry; -} - -//----------------------------------------------------------------------------- -ShaderGenerator::SGMaterialConstIterator ShaderGenerator::findMaterialEntryIt(const String& materialName, const String& groupName) const -{ - SGMaterialConstIterator itMatEntry; - //check if we have auto detect request - if (groupName == ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME) - { - //find the possible first entry - itMatEntry = mMaterialEntriesMap.lower_bound(MatGroupPair(materialName,"")); - if ((itMatEntry != mMaterialEntriesMap.end()) && - (itMatEntry->first.first != materialName)) - { - //no entry found - itMatEntry = mMaterialEntriesMap.end(); - } - } - else - { - //find entry with group name specified - itMatEntry = mMaterialEntriesMap.find(MatGroupPair(materialName,groupName)); - } - return itMatEntry; -} -//----------------------------------------------------------------------------- -size_t ShaderGenerator::getRTShaderSchemeCount() const -{ - OGRE_LOCK_AUTO_MUTEX; - return mSchemeEntriesMap.size(); -} -//----------------------------------------------------------------------------- -const String& ShaderGenerator::getRTShaderScheme(size_t index) const -{ - OGRE_LOCK_AUTO_MUTEX; - - SGSchemeMap::const_iterator it = mSchemeEntriesMap.begin(); - while ((index != 0) && (it != mSchemeEntriesMap.end())) - { - --index; - ++it; - } - - assert((it != mSchemeEntriesMap.end()) && "Index out of bounds"); - if (it != mSchemeEntriesMap.end()) - return it->first; - else return BLANKSTRING; -} - -void ShaderGenerator::_markNonFFP(const TextureUnitState* tu) -{ - auto pass = tu->getParent(); - auto texureIdx = pass->getTextureUnitStateIndex(tu); - - // add to blacklist - std::set nonFFP_TUS; - auto any = pass->getUserObjectBindings().getUserAny("_RTSS_nonFFP_TUS"); - if(any.has_value()) - nonFFP_TUS = any_cast>(any); - nonFFP_TUS.insert(texureIdx); - pass->getUserObjectBindings().setUserAny("_RTSS_nonFFP_TUS", nonFFP_TUS); -} - -//----------------------------------------------------------------------------- - -bool ShaderGenerator::getIsFinalizing() const -{ - return mIsFinalizing; -} - -//----------------------------------------------------------------------------- -ShaderGenerator::SGPassList ShaderGenerator::createSGPassList(Material* mat) const -{ - SGPassList passList; - - SGMaterialConstIterator itMatEntry = findMaterialEntryIt(mat->getName(), mat->getGroup()); - - // Check if material is managed. - if (itMatEntry == mMaterialEntriesMap.end()) - return passList; - - for (auto sgtech : itMatEntry->second->getTechniqueList()) - { - for(auto sgpass : sgtech->getPassList()) - { - passList.push_back(sgpass); - } - } - - return passList; -} - -//----------------------------------------------------------------------------- -ShaderGenerator::SGPass::SGPass(SGTechnique* parent, Pass* srcPass, Pass* dstPass, IlluminationStage stage) -{ - mParent = parent; - mSrcPass = srcPass; - mDstPass = dstPass; - mStage = stage; - mCustomRenderState = NULL; -} - -//----------------------------------------------------------------------------- -ShaderGenerator::SGPass::~SGPass() -{ - mDstPass->getUserObjectBindings().eraseUserAny(TargetRenderState::UserKey); -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::SGPass::buildTargetRenderState() -{ - if(mSrcPass->isProgrammable() && !mParent->overProgrammablePass() && !isIlluminationPass()) return; - const String& schemeName = mParent->getDestinationTechniqueSchemeName(); - const RenderState* renderStateGlobal = ShaderGenerator::getSingleton().getRenderState(schemeName); - - - auto targetRenderState = std::make_shared(); - - // Set light properties. - int32 lightCount = 0; - bool haveAreaLights = false; - - // Use light count definitions of the custom render state if exists. - if (mCustomRenderState != NULL && mCustomRenderState->getLightCountAutoUpdate() == false) - { - lightCount = mCustomRenderState->getLightCount(); - } - - // Use light count definitions of the global render state if exists. - else if (renderStateGlobal != NULL) - { - lightCount = renderStateGlobal->getLightCount(); - haveAreaLights = renderStateGlobal->haveAreaLights(); - } - - - targetRenderState->setLightCount(lightCount); - targetRenderState->setHaveAreaLights(haveAreaLights); - - // Link the target render state with the scheme render state of the shader generator. - if (renderStateGlobal != NULL) - { - targetRenderState->link(*renderStateGlobal, mSrcPass, mDstPass); - } - - // Link the target render state with the custom render state of this pass if exists. - if (mCustomRenderState != NULL) - { - targetRenderState->link(*mCustomRenderState, mSrcPass, mDstPass); - } - - targetRenderState->acquirePrograms(mDstPass); - mDstPass->getUserObjectBindings().setUserAny(TargetRenderState::UserKey, targetRenderState); -} - -//----------------------------------------------------------------------------- -ShaderGenerator::SGTechnique::SGTechnique(SGMaterial* parent, const Technique* srcTechnique, - const String& dstTechniqueSchemeName, - bool overProgrammable) - : mParent(parent), mSrcTechnique(srcTechnique), mDstTechnique(NULL), mBuildDstTechnique(true), - mDstTechniqueSchemeName(dstTechniqueSchemeName), mOverProgrammable(overProgrammable) -{ - -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::SGTechnique::createSGPasses() -{ - // Create pass entry for each pass. - for (unsigned short i=0; i < mSrcTechnique->getNumPasses(); ++i) - { - Pass* srcPass = mSrcTechnique->getPass(i); - Pass* dstPass = mDstTechnique->getPass(i); - - SGPass* passEntry = OGRE_NEW SGPass(this, srcPass, dstPass, IS_UNKNOWN); - - if (i < mCustomRenderStates.size()) - passEntry->setCustomRenderState(mCustomRenderStates[i]); - mPassEntries.push_back(passEntry); - } -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::SGTechnique::createIlluminationSGPasses() -{ - // Create pass entry for each illumination pass. - const IlluminationPassList& passes = mDstTechnique->getIlluminationPasses(); - - for(size_t i = 0; i < passes.size(); i++) - { - // process only autogenerated illumination passes - IlluminationPass* p = passes[i]; - if(p->pass == p->originalPass) - continue; - - SGPass* passEntry = OGRE_NEW SGPass(this, p->pass, p->pass, p->stage); - const Any& origPassUserData = p->originalPass->getUserObjectBindings().getUserAny(TargetRenderState::UserKey); - if(origPassUserData.has_value()) - { - for(auto *sgp : mPassEntries) - { - if(sgp->getDstPass() == p->originalPass) - { - passEntry->setCustomRenderState(sgp->getCustomRenderState()); - break; - } - } - } - - mPassEntries.push_back(passEntry); - } -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::SGTechnique::destroyIlluminationSGPasses() -{ - for(SGPassIterator itPass = mPassEntries.begin(); itPass != mPassEntries.end(); /* no increment*/ ) - { - if((*itPass)->isIlluminationPass()) - { - OGRE_DELETE(*itPass); - itPass = mPassEntries.erase(itPass); - } - else - { - ++itPass; - } - } -} - -//----------------------------------------------------------------------------- -ShaderGenerator::SGTechnique::~SGTechnique() -{ - const String& materialName = mParent->getMaterialName(); - const String& groupName = mParent->getGroupName(); - - // Destroy the passes. - destroySGPasses(); - - if (MaterialManager::getSingleton().resourceExists(materialName, groupName)) - { - MaterialPtr mat = MaterialManager::getSingleton().getByName(materialName, groupName); - - // Remove the destination technique from parent material. - for (ushort i=0; i < mat->getNumTechniques(); ++i) - { - if (mDstTechnique == mat->getTechnique(i)) - { - // Unload the generated technique in order tor free referenced resources. - mDstTechnique->_unload(); - - // Remove the generated technique in order to restore the material to its original state. - mat->removeTechnique(i); - - // touch when finalizing - will reload the textures - so no touch if finalizing - if (ShaderGenerator::getSingleton().getIsFinalizing() == false) - { - // Make sure the material goes back to its original state. - mat->touch(); - } - break; - } - } - } - - // Delete the custom render states of each pass if exist. - for (unsigned int i=0; i < mCustomRenderStates.size(); ++i) - { - if (mCustomRenderStates[i] != NULL) - { - OGRE_DELETE mCustomRenderStates[i]; - mCustomRenderStates[i] = NULL; - } - } - mCustomRenderStates.clear(); - -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::SGTechnique::destroySGPasses() -{ - for (auto& p : mPassEntries) - { - OGRE_DELETE p; - } - mPassEntries.clear(); -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::SGTechnique::buildTargetRenderState() -{ - // Remove existing destination technique and passes - // in order to build it again from scratch. - if (mDstTechnique != NULL) - { - Material* mat = mSrcTechnique->getParent(); - - for (unsigned short i=0; i < mat->getNumTechniques(); ++i) - { - if (mat->getTechnique(i) == mDstTechnique) - { - mat->removeTechnique(i); - break; - } - } - destroySGPasses(); - } - - // Create the destination technique and passes. - mDstTechnique = mSrcTechnique->getParent()->createTechnique(); - mDstTechnique->getUserObjectBindings().setUserAny(SGTechnique::UserKey, this); - *mDstTechnique = *mSrcTechnique; - mDstTechnique->setSchemeName(mDstTechniqueSchemeName); - createSGPasses(); - - // Build render state for each pass. - for (auto *p : mPassEntries) - { - assert(!p->isIlluminationPass()); // this is not so important, but intended to be so here. - p->buildTargetRenderState(); - } - - // Turn off the build destination technique flag. - mBuildDstTechnique = false; -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::SGTechnique::buildIlluminationTargetRenderState() -{ - assert(mDstTechnique != NULL); - assert(!getBuildDestinationTechnique()); - - // Create the illumination passes. - createIlluminationSGPasses(); - - // Build render state for each pass. - for(auto *p : mPassEntries) { - - if(p->isIlluminationPass()) - p->buildTargetRenderState(); - } -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::SGTechnique::releasePrograms() -{ - // Remove destination technique. - if (mDstTechnique != NULL) - { - Material* mat = mSrcTechnique->getParent(); - - for (unsigned short i=0; i < mat->getNumTechniques(); ++i) - { - if (mat->getTechnique(i) == mDstTechnique) - { - mat->removeTechnique(i); - break; - } - } - mDstTechnique = NULL; - } - - // Destroy the passes. - destroySGPasses(); -} - -//----------------------------------------------------------------------------- -RenderState* ShaderGenerator::SGTechnique::getRenderState(unsigned short passIndex) -{ - RenderState* renderState = NULL; - - if (passIndex >= mCustomRenderStates.size()) - mCustomRenderStates.resize(passIndex + 1, NULL); - - renderState = mCustomRenderStates[passIndex]; - if (renderState == NULL) - { - renderState = OGRE_NEW RenderState; - mCustomRenderStates[passIndex] = renderState; - } - - return renderState; -} -//----------------------------------------------------------------------------- -bool ShaderGenerator::SGTechnique::hasRenderState(unsigned short passIndex) -{ - return (passIndex < mCustomRenderStates.size()) && (mCustomRenderStates[passIndex] != NULL); -} - - -//----------------------------------------------------------------------------- -ShaderGenerator::SGScheme::SGScheme(const String& schemeName) : - mName(schemeName), mOutOfDate(true), mFogMode(FOG_NONE) -{ -} - -//----------------------------------------------------------------------------- -ShaderGenerator::SGScheme::~SGScheme() -{ -} - -//----------------------------------------------------------------------------- -RenderState* ShaderGenerator::SGScheme::getRenderState() -{ - if (!mRenderState) - { - mRenderState.reset(new RenderState); - mRenderState->resetToBuiltinSubRenderStates(); - } - - return mRenderState.get(); -} - -//----------------------------------------------------------------------------- -RenderState* ShaderGenerator::SGScheme::getRenderState(const String& materialName, const String& groupName, unsigned short passIndex) -{ - // Find the desired technique. - bool doAutoDetect = groupName == ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME; - for (auto *t : mTechniqueEntries) - { - Material* curMat = t->getSourceTechnique()->getParent(); - if ((curMat->getName() == materialName) && - ((doAutoDetect == true) || (curMat->getGroup() == groupName))) - { - return t->getRenderState(passIndex); - } - } - - return NULL; -} - - -//----------------------------------------------------------------------------- -void ShaderGenerator::SGScheme::addTechniqueEntry(SGTechnique* techEntry) -{ - mTechniqueEntries.push_back(techEntry); - - // Mark as out of data. - mOutOfDate = true; -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::SGScheme::removeTechniqueEntry(SGTechnique* techEntry) -{ - SGTechniqueIterator itTech; - - // Build render state for each technique. - for (itTech = mTechniqueEntries.begin(); itTech != mTechniqueEntries.end(); ++itTech) - { - SGTechnique* curTechEntry = *itTech; - - if (curTechEntry == techEntry) - { - mTechniqueEntries.erase(itTech); - break; - } - } -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::SGScheme::validate() -{ - // Synchronize with light settings. - synchronizeWithLightSettings(); - - // Synchronize with fog settings. - synchronizeWithFogSettings(); - - // The target scheme is up to date. - if (mOutOfDate == false) - return; - - // Build render state for each technique and acquire GPU programs. - for (SGTechnique* curTechEntry : mTechniqueEntries) - { - if (curTechEntry->getBuildDestinationTechnique()) - curTechEntry->buildTargetRenderState(); - } - - // Mark this scheme as up to date. - mOutOfDate = false; -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::SGScheme::synchronizeWithLightSettings() -{ - SceneManager* sceneManager = ShaderGenerator::getSingleton().getActiveSceneManager(); - RenderState* curRenderState = getRenderState(); - - if (curRenderState->getLightCountAutoUpdate()) - { - OgreAssert(sceneManager, "no active SceneManager. Did you forget to call ShaderGenerator::addSceneManager?"); - - const LightList& lightList = sceneManager->_getLightsAffectingFrustum(); - - // area lights a costy, so we check whether there are any in the scene - bool haveAreaLights = false; - for (const Light* l : lightList) - haveAreaLights = haveAreaLights || l->getType() == Light::LT_RECTLIGHT; - - int32 sceneLightCount = lightList.size(); - int32 currLightCount = mRenderState->getLightCount(); - - // Case new light appeared -> invalidate. But dont invalidate the other way as shader compilation is costly. - if ((currLightCount - sceneLightCount) < 0) - { - LogManager::getSingleton().stream(LML_TRIVIAL) - << "RTSS: invalidating scheme " << mName << " - lights changed " << currLightCount - << " -> " << sceneLightCount; - curRenderState->setLightCount(sceneLightCount); - invalidate(); - } - - if(!curRenderState->haveAreaLights() && haveAreaLights) - { - LogManager::getSingleton().stream(LML_TRIVIAL) - << "RTSS: invalidating scheme " << mName << " - enabling area lights"; - curRenderState->setHaveAreaLights(true); - invalidate(); - } - } -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::SGScheme::synchronizeWithFogSettings() -{ - SceneManager* sceneManager = ShaderGenerator::getSingleton().getActiveSceneManager(); - - if (sceneManager != NULL && sceneManager->getFogMode() != mFogMode) - { - LogManager::getSingleton().stream(LML_TRIVIAL) - << "RTSS: invalidating scheme " << mName << " - fog settings changed"; - mFogMode = sceneManager->getFogMode(); - invalidate(); - } -} - -//----------------------------------------------------------------------------- -bool ShaderGenerator::SGScheme::validate(const String& materialName, const String& groupName) -{ - // Synchronize with light settings. - synchronizeWithLightSettings(); - - // Synchronize with fog settings. - synchronizeWithFogSettings(); - - // Find the desired technique. - bool doAutoDetect = groupName == ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME; - for (auto *t : mTechniqueEntries) - { - const SGMaterial* curMat = t->getParent(); - if ((curMat->getMaterialName() == materialName) && - ((doAutoDetect == true) || (curMat->getGroupName() == groupName)) && (t->getBuildDestinationTechnique())) { - // Build render state for each technique and Acquire the CPU/GPU programs. - t->buildTargetRenderState(); - - return true; - } - } - - return false; -} -//----------------------------------------------------------------------------- -bool ShaderGenerator::SGScheme::validateIlluminationPasses(const String& materialName, const String& groupName) -{ - // Synchronize with light settings. - synchronizeWithLightSettings(); - - // Synchronize with fog settings. - synchronizeWithFogSettings(); - - // Find the desired technique. - bool doAutoDetect = groupName == ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME; - for(SGTechnique* curTechEntry : mTechniqueEntries) - { - const SGMaterial* curMat = curTechEntry->getParent(); - if((curMat->getMaterialName() == materialName) && - ((doAutoDetect == true) || (curMat->getGroupName() == groupName))) - { - // Build render state for each technique and Acquire the CPU/GPU programs. - curTechEntry->buildIlluminationTargetRenderState(); - - return true; - } - } - - return false; -} -//----------------------------------------------------------------------------- -void ShaderGenerator::SGScheme::invalidateIlluminationPasses(const String& materialName, const String& groupName) -{ - // Find the desired technique. - bool doAutoDetect = groupName == ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME; - for(auto *t : mTechniqueEntries) - { - const SGMaterial* curMat = t->getParent(); - if((curMat->getMaterialName() == materialName) && - ((doAutoDetect == true) || (curMat->getGroupName() == groupName))) - { - t->destroyIlluminationSGPasses(); - } - } -} -//----------------------------------------------------------------------------- -void ShaderGenerator::SGScheme::invalidate(const String& materialName, const String& groupName) -{ - // Find the desired technique. - bool doAutoDetect = groupName == ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME; - for (SGTechnique* curTechEntry : mTechniqueEntries) - { - const SGMaterial* curMaterial = curTechEntry->getParent(); - if ((curMaterial->getMaterialName() == materialName) && - ((doAutoDetect == true) || (curMaterial->getGroupName() == groupName))) - { - // Turn on the build destination technique flag. - curTechEntry->setBuildDestinationTechnique(true); - break; - } - } - - mOutOfDate = true; -} - -//----------------------------------------------------------------------------- -void ShaderGenerator::SGScheme::invalidate() -{ - // Turn on the build destination technique flag of all techniques. - for (SGTechnique* curTechEntry : mTechniqueEntries) - { - curTechEntry->setBuildDestinationTechnique(true); - } - - mOutOfDate = true; -} - -} -} diff --git a/Components/RTShaderSystem/src/OgreShaderImageBasedLighting.cpp b/Components/RTShaderSystem/src/OgreShaderImageBasedLighting.cpp deleted file mode 100644 index b2629f3a64a..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderImageBasedLighting.cpp +++ /dev/null @@ -1,172 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#include "OgreShaderPrecompiledHeaders.h" -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS - -namespace Ogre -{ -namespace RTShader -{ - -/************************************************************************/ -/* */ -/************************************************************************/ -const String SRS_IMAGE_BASED_LIGHTING = "ImageBasedLighting"; - -//----------------------------------------------------------------------- -const String& ImageBasedLighting::getType() const { return SRS_IMAGE_BASED_LIGHTING; } - -//----------------------------------------------------------------------- -int ImageBasedLighting::getExecutionOrder() const { return FFP_LIGHTING + 10; } - -bool ImageBasedLighting::setParameter(const String& name, const String& value) -{ - if (name == "texture" && !value.empty()) - { - mEnvMapName = value; - return true; - } - else if (name == "luminance") - { - mIsLuminanceParamDirty = true; - return StringConverter::parse(value, mLuminance); - } - - return false; -} - -void ImageBasedLighting::copyFrom(const SubRenderState& rhs) -{ - const ImageBasedLighting& rhsIBL = static_cast(rhs); - mEnvMapName = rhsIBL.mEnvMapName; - mLuminance = rhsIBL.mLuminance; -} - -bool ImageBasedLighting::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) -{ - if (!srcPass->getLightingEnabled()) - return false; - // generate with ./cmgen --size=64 --ibl-dfg-multiscatter --ibl-dfg=dfgLUTmultiscatter.dds - // see https://github.com/google/filament/blob/78554d231947bae965492eb5c47ad24a8d4a426e/filament/CMakeLists.txt#L510 - auto tus = dstPass->createTextureUnitState("dfgLUTmultiscatter.dds"); - tus->setNumMipmaps(0); - mDfgLUTSamplerIndex = dstPass->getNumTextureUnitStates() - 1; - - tus = dstPass->createTextureUnitState(); - tus->setTextureName(mEnvMapName, TEX_TYPE_CUBE_MAP); - tus->setHardwareGammaEnabled(true); - mEnvMapSamplerIndex = dstPass->getNumTextureUnitStates() - 1; - - return true; -} - -bool ImageBasedLighting::createCpuSubPrograms(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* psMain = psProgram->getEntryPointFunction(); - - auto vsOutViewPos = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_VIEW_SPACE); - auto viewPos = psMain->resolveInputParameter(vsOutViewPos); - - auto pixel = psMain->getLocalParameter("pixel"); - mLuminanceParam = psProgram->resolveParameter(GCT_FLOAT1, "luminance"); - - if (!pixel) - { - LogManager::getSingleton().logError("image_based_lighting must be used with the metal_roughness SRS"); - return true; - } - - auto viewNormal = psMain->getLocalParameter(Parameter::SPC_NORMAL_VIEW_SPACE); // allow normal map injection - if(!viewNormal) - { - auto vsOutNormal = vsMain->resolveOutputParameter(Parameter::SPC_NORMAL_VIEW_SPACE); - viewNormal = psMain->resolveInputParameter(vsOutNormal); - } - - psProgram->addDependency("RTSLib_IBL"); - - auto outDiffuse = psMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE); - - auto dfgLUTSampler = psProgram->resolveParameter(GCT_SAMPLER2D, "dfgLUTSampler", mDfgLUTSamplerIndex); - auto iblEnvSampler = psProgram->resolveParameter(GCT_SAMPLERCUBE, "iblEnvSampler", mEnvMapSamplerIndex); - - auto iblEnvSize = psProgram->resolveParameter(GpuProgramParameters::ACT_TEXTURE_SIZE, mEnvMapSamplerIndex); - auto invViewMat = psProgram->resolveParameter(GpuProgramParameters::ACT_INVERSE_VIEW_MATRIX); - - auto fstage = psMain->getStage(FFP_PS_COLOUR_END + 55); // run before CookTorrance evaluation - - fstage.callFunction("evaluateIBL", - {InOut(pixel), In(viewNormal), In(viewPos), In(invViewMat), In(dfgLUTSampler), In(iblEnvSampler), - In(iblEnvSize).w(), In(mLuminanceParam), InOut(outDiffuse).xyz()}); - - return true; -} - -void ImageBasedLighting::updateGpuProgramsParams(Renderable* rend, const Pass* pass, const AutoParamDataSource* source, const LightList* ll) -{ - if (mIsLuminanceParamDirty) - { - mLuminanceParam->setGpuParameter(mLuminance); - mIsLuminanceParamDirty = false; - } -} - - -//----------------------------------------------------------------------- -const String& ImageBasedLightingFactory::getType() const { return SRS_IMAGE_BASED_LIGHTING; } - -//----------------------------------------------------------------------- -SubRenderState* ImageBasedLightingFactory::createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, - SGScriptTranslator* translator) -{ - if (prop->name != "image_based_lighting" || prop->values.size() < 2) - return NULL; - - auto it = prop->values.begin(); - if((*it++)->getString() != "texture") - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - return NULL; - } - auto ret = static_cast(createOrRetrieveInstance(translator)); - ret->setParameter("texture", (*it++)->getString()); - - if (prop->values.size() < 4) - return ret; - - if((*it++)->getString() != "luminance") - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - return NULL; - } - - ret->setParameter("luminance", (*it++)->getString()); - - return ret; -} - -//----------------------------------------------------------------------- -void ImageBasedLightingFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, - Pass* dstPass) -{ - auto ibl = static_cast(subRenderState); - ser->writeAttribute(4, "image_based_lighting"); - ser->writeValue("texture"); - ser->writeValue(ibl->mEnvMapName); - ser->writeValue("luminance"); - ser->writeValue(std::to_string(ibl->mLuminance)); -} - -//----------------------------------------------------------------------- -SubRenderState* ImageBasedLightingFactory::createInstanceImpl() { return OGRE_NEW ImageBasedLighting; } - -} // namespace RTShader -} // namespace Ogre - -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderImageBasedLighting.h b/Components/RTShaderSystem/src/OgreShaderImageBasedLighting.h deleted file mode 100644 index 7c8f289d313..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderImageBasedLighting.h +++ /dev/null @@ -1,68 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT -#ifndef _ShaderIBL_ -#define _ShaderIBL_ - -#include "OgreShaderPrerequisites.h" -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS -#include "OgreShaderParameter.h" -#include "OgreShaderSubRenderState.h" - -namespace Ogre -{ -namespace RTShader -{ - -/** \addtogroup Optional - * @{ - */ -/** \addtogroup RTShader - * @{ - */ - -/** Transform sub render state implementation of ImageBasedLighting - */ -class ImageBasedLighting : public SubRenderState -{ - friend class ImageBasedLightingFactory; - int mDfgLUTSamplerIndex = 0; - int mEnvMapSamplerIndex = 0; - float mLuminance = 1.0f; - String mEnvMapName; - UniformParameterPtr mLuminanceParam; - bool mIsLuminanceParamDirty = true; -public: - const String& getType() const override; - int getExecutionOrder() const override; - bool preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) override; - bool createCpuSubPrograms(ProgramSet* programSet) override; - void copyFrom(const SubRenderState& rhs) override; - bool setParameter(const String& name, const String& value) override; - void updateGpuProgramsParams(Renderable* rend, const Pass* pass, const AutoParamDataSource* source, - const LightList* ll) override; -}; - -class ImageBasedLightingFactory : public SubRenderStateFactory -{ -public: - const String& getType() const override; - - SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, - SGScriptTranslator* translator) override; - - void writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, Pass* dstPass) override; - -protected: - SubRenderState* createInstanceImpl() override; -}; - -/** @} */ -/** @} */ - -} // namespace RTShader -} // namespace Ogre - -#endif -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderMaterialSerializerListener.cpp b/Components/RTShaderSystem/src/OgreShaderMaterialSerializerListener.cpp deleted file mode 100644 index c55197ee1f1..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderMaterialSerializerListener.cpp +++ /dev/null @@ -1,179 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderPrecompiledHeaders.h" - -namespace Ogre { -namespace RTShader { - -//----------------------------------------------------------------------------- -SGMaterialSerializerListener::SGMaterialSerializerListener() -{ - mSourceMaterial = NULL; -} - -//----------------------------------------------------------------------------- -void SGMaterialSerializerListener::materialEventRaised(MaterialSerializer* ser, - MaterialSerializer::SerializeEvent event, - bool& skip, const Material* mat) -{ - if (event == MaterialSerializer::MSE_PRE_WRITE) - { - MaterialPtr matPtr = MaterialManager::getSingleton().getByName(mat->getName()); - mSourceMaterial = matPtr.get(); - mSGPassList = ShaderGenerator::getSingleton().createSGPassList(mSourceMaterial); - } - - if (event == MaterialSerializer::MSE_POST_WRITE) - { - mSourceMaterial = NULL; - mSGPassList.clear(); - } -} - -//----------------------------------------------------------------------------- -void SGMaterialSerializerListener::techniqueEventRaised(MaterialSerializer* ser, - MaterialSerializer::SerializeEvent event, - bool& skip, const Technique* tech) -{ - // Pre technique write event. - if (event == MaterialSerializer::MSE_PRE_WRITE) - { - const Any& techUserData = tech->getUserObjectBindings().getUserAny(ShaderGenerator::SGTechnique::UserKey); - - // Skip writing this technique since it was generated by the Shader Generator. - if (techUserData.has_value()) - { - skip = true; - return; - } - } -} - -//----------------------------------------------------------------------------- -void SGMaterialSerializerListener::serializePassAttributes(MaterialSerializer* ser, ShaderGenerator::SGPass* passEntry) -{ - // Grab the custom render state this pass uses. - RenderState* customRenderState = passEntry->getCustomRenderState(); - - if (!customRenderState) - return; - - // Write section header and begin it. - ser->writeAttribute(3, "rtshader_system"); - ser->beginSection(3); - - // Write each of the sub-render states that composing the final render state. - for (SubRenderState* curSubRenderState : customRenderState->getSubRenderStates()) - { - if (SubRenderStateFactory* curFactory = - ShaderGenerator::getSingleton().getSubRenderStateFactory(curSubRenderState->getType())) - { - curFactory->writeInstance(ser, curSubRenderState, passEntry->getSrcPass(), passEntry->getDstPass()); - } - } - - // Write section end. - ser->endSection(3); -} - -//----------------------------------------------------------------------------- -void SGMaterialSerializerListener::serializeTextureUnitStateAttributes(MaterialSerializer* ser, - ShaderGenerator::SGPass* passEntry, - const TextureUnitState* srcTextureUnit) -{ - // Grab the custom render state this pass uses. - RenderState* customRenderState = passEntry->getCustomRenderState(); - - if (!customRenderState) - return; - - // Write section header and begin it. - ser->writeAttribute(4, "rtshader_system"); - ser->beginSection(4); - - //retrive the destintion texture unit state - TextureUnitState* dstTextureUnit = NULL; - unsigned short texIndex = srcTextureUnit->getParent()->getTextureUnitStateIndex(srcTextureUnit); - if (texIndex < passEntry->getDstPass()->getNumTextureUnitStates()) - { - dstTextureUnit = passEntry->getDstPass()->getTextureUnitState(texIndex); - } - - // Write each of the sub-render states that composing the final render state. - for (SubRenderState* curSubRenderState : customRenderState->getSubRenderStates()) - { - if (SubRenderStateFactory* curFactory = - ShaderGenerator::getSingleton().getSubRenderStateFactory(curSubRenderState->getType())) - curFactory->writeInstance(ser, curSubRenderState, srcTextureUnit, dstTextureUnit); - } - - // Write section end. - ser->endSection(4); -} - -//----------------------------------------------------------------------------- -void SGMaterialSerializerListener::passEventRaised(MaterialSerializer* ser, - MaterialSerializer::SerializeEvent event, - bool& skip, const Pass* pass) -{ - // End of pass writing event. - if (event == MaterialSerializer::MSE_WRITE_END) - { - // Case this pass use as source pass for shader generated pass. - if (auto passEntry = getShaderGeneratedPass(pass)) - serializePassAttributes(ser, passEntry); - } -} - -//----------------------------------------------------------------------------- -void SGMaterialSerializerListener::textureUnitStateEventRaised(MaterialSerializer* ser, - MaterialSerializer::SerializeEvent event, - bool& skip, const TextureUnitState* textureUnit) -{ - // End of pass writing event. - if (event == MaterialSerializer::MSE_WRITE_END) - { - // Case this pass use as source pass for shader generated pass. - if (auto passEntry = getShaderGeneratedPass(textureUnit->getParent())) - serializeTextureUnitStateAttributes(ser, passEntry, textureUnit); - } -} - -//----------------------------------------------------------------------------- -ShaderGenerator::SGPass* SGMaterialSerializerListener::getShaderGeneratedPass(const Pass* srcPass) -{ - for (auto *s : mSGPassList) - { - if (s->getSrcPass() == srcPass) - return s; - } - - return NULL; -} - -} -} diff --git a/Components/RTShaderSystem/src/OgreShaderMaterialSerializerListener.h b/Components/RTShaderSystem/src/OgreShaderMaterialSerializerListener.h deleted file mode 100644 index 6e5a923f11b..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderMaterialSerializerListener.h +++ /dev/null @@ -1,88 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderMaterialSerializerListener_ -#define _ShaderMaterialSerializerListener_ - -#include "OgreShaderPrerequisites.h" -#include "OgreMaterialSerializer.h" -#include "OgreShaderGenerator.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** This class responsible for translating core features of the RT Shader System for -Ogre material scripts. -*/ -class SGMaterialSerializerListener : public MaterialSerializer::Listener, public RTShaderSystemAlloc -{ -private: - void materialEventRaised(MaterialSerializer* ser, - MaterialSerializer::SerializeEvent event, bool& skip, const Material* mat) override; - - void techniqueEventRaised(MaterialSerializer* ser, - MaterialSerializer::SerializeEvent event, bool& skip, const Technique* tech) override; - - void passEventRaised(MaterialSerializer* ser, - MaterialSerializer::SerializeEvent event, bool& skip, const Pass* tech) override; - - void textureUnitStateEventRaised(MaterialSerializer* ser, - MaterialSerializer::SerializeEvent event, bool& skip, const TextureUnitState* textureUnit) override; - - typedef std::vector SGPassList; - typedef SGPassList::iterator SGPassListIterator; - typedef SGPassList::const_iterator SGPassListConstIterator; - - /** Will be create and destroyed via ShaderGenerator interface. */ - SGMaterialSerializerListener(); - - /** Internal method that returns SGPass instance from a given source pass. */ - ShaderGenerator::SGPass* getShaderGeneratedPass (const Pass* srcPass); - - void serializePassAttributes(MaterialSerializer* ser, ShaderGenerator::SGPass* passEntry); - - void serializeTextureUnitStateAttributes(MaterialSerializer* ser, ShaderGenerator::SGPass* passEntry, - const TextureUnitState* srcTextureUnit); - - // The current source material that is being written. - Material* mSourceMaterial; - // List of SGPass instances composing this material. - SGPassList mSGPassList; - - friend class ShaderGenerator; -}; - -} -} - -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderParameter.cpp b/Components/RTShaderSystem/src/OgreShaderParameter.cpp deleted file mode 100644 index 18a137ec0cc..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderParameter.cpp +++ /dev/null @@ -1,654 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include - -#include "OgreShaderPrecompiledHeaders.h" - -namespace Ogre { -namespace RTShader { - - //----------------------------------------------------------------------- - // Define some ConstParameterTypes - //----------------------------------------------------------------------- - - /** ConstParameterVec2 represents a Vector2 constant. - */ - class ConstParameterVec2 : public ConstParameter - { - public: - ConstParameterVec2( Vector2 val, - GpuConstantType type, - const Semantic& semantic, - const Content& content) - : ConstParameter(val, type, semantic, content) - { - } - - ~ConstParameterVec2() {} - - /** - @see Parameter::toString. - */ - String toString () const override - { - StringStream str; - str << "vec2(" << std::showpoint << mValue.x << "," << mValue.y << ")"; - return str.str(); - } - }; - - /** ConstParameterVec3 represents a Vector3 constant. - */ - class ConstParameterVec3 : public ConstParameter - { - public: - ConstParameterVec3( Vector3 val, - GpuConstantType type, - const Semantic& semantic, - const Content& content) - : ConstParameter(val, type, semantic, content) - { - } - ~ConstParameterVec3() {} - - /** - @see Parameter::toString. - */ - String toString () const override - { - StringStream str; - str << "vec3(" << std::showpoint << mValue.x << "," << mValue.y << "," << mValue.z << ")"; - return str.str(); - } - }; - - /** ConstParameterVec4 represents a Vector2 Vector4. - */ - class ConstParameterVec4 : public ConstParameter - { - public: - ConstParameterVec4( Vector4 val, - GpuConstantType type, - const Semantic& semantic, - const Content& content) - : ConstParameter(val, type, semantic, content) - { - } - ~ConstParameterVec4() {} - - /** - @see Parameter::toString. - */ - String toString () const override - { - StringStream str; - str << "vec4(" << std::showpoint << mValue.x << "," << mValue.y << "," << mValue.z << "," << mValue.w << ")"; - return str.str(); - } - }; - - /** ConstParameterFloat represents a float constant. - */ - class ConstParameterFloat : public ConstParameter - { - public: - ConstParameterFloat(float val, - GpuConstantType type, - const Semantic& semantic, - const Content& content) - : ConstParameter(val, type, semantic, content) - { - } - - ~ConstParameterFloat() {} - - /** - @see Parameter::toString. - */ - String toString () const override - { - return StringConverter::toString(mValue, 6, 0, ' ', std::ios::showpoint); - } - }; - /** ConstParameterInt represents an int constant. - */ - class ConstParameterInt : public ConstParameter - { - public: - ConstParameterInt(int val, - GpuConstantType type, - const Semantic& semantic, - const Content& content) - : ConstParameter(val, type, semantic, content) - { - } - - ~ConstParameterInt() {} - - /** - @see Parameter::toString. - */ - String toString () const override - { - return Ogre::StringConverter::toString(mValue); - } - }; - -//----------------------------------------------------------------------- -Parameter::Parameter() : mName(""), mType(GCT_UNKNOWN), mSemantic(SPS_UNKNOWN), mIndex(0), mContent(SPC_UNKNOWN), mSize(0), mUsed(false), mIsHighP(false) -{ -} - -//----------------------------------------------------------------------- -Parameter::Parameter(GpuConstantType type, const String& name, - const Semantic& semantic, int index, - const Content& content, size_t size) : - mName(name), mType(type), mSemantic(semantic), mIndex(index), mContent(content), mSize(size), mUsed(false), mIsHighP(false) -{ -} - -//----------------------------------------------------------------------- -UniformParameter::UniformParameter(GpuConstantType type, const String& name, - const Semantic& semantic, int index, - const Content& content, - uint16 variability, size_t size) : Parameter(type, name, semantic, index, content, size) -{ - mIsAutoConstantReal = false; - mIsAutoConstantInt = false; - mIsHighP = false; - mAutoConstantIntData = 0; - mVariability = variability; - mParamsPtr = NULL; - mPhysicalIndex = -1; - mAutoConstantType = GpuProgramParameters::ACT_TIME; -} - -static GpuConstantType getGCType(const GpuProgramParameters::AutoConstantDefinition* def) -{ - assert(def->elementType == GpuProgramParameters::ET_REAL); - - switch (def->elementCount) - { - default: - case 1: - return GCT_FLOAT1; - case 2: - return GCT_FLOAT2; - case 3: - return GCT_FLOAT3; - case 4: - return GCT_FLOAT4; - case 8: - return GCT_MATRIX_2X4; - case 9: - return GCT_MATRIX_3X3; - case 12: - return GCT_MATRIX_3X4; - case 16: - return GCT_MATRIX_4X4; - } -} - -//----------------------------------------------------------------------- -UniformParameter::UniformParameter(GpuProgramParameters::AutoConstantType autoType, float fAutoConstantData, size_t size) -{ - auto parameterDef = GpuProgramParameters::getAutoConstantDefinition(autoType); - assert(parameterDef); - - mName = parameterDef->name; - if (fAutoConstantData != 0.0) - { - mName += StringConverter::toString(fAutoConstantData); - //replace possible illegal point character in name - std::replace(mName.begin(), mName.end(), '.', '_'); - } - mType = getGCType(parameterDef); - mSemantic = SPS_UNKNOWN; - mIndex = -1; - mContent = SPC_UNKNOWN; - mIsAutoConstantReal = true; - mIsAutoConstantInt = false; - mAutoConstantType = autoType; - mAutoConstantRealData = fAutoConstantData; - mVariability = (uint16)GPV_GLOBAL; - mParamsPtr = NULL; - mPhysicalIndex = -1; - mSize = size; -} - -//----------------------------------------------------------------------- -UniformParameter::UniformParameter(GpuProgramParameters::AutoConstantType autoType, float fAutoConstantData, size_t size, GpuConstantType type) -{ - auto parameterDef = GpuProgramParameters::getAutoConstantDefinition(autoType); - assert(parameterDef); - - mName = parameterDef->name; - if (fAutoConstantData != 0.0) - { - mName += StringConverter::toString(fAutoConstantData); - //replace possible illegal point character in name - std::replace(mName.begin(), mName.end(), '.', '_'); - } - mType = type; - mSemantic = SPS_UNKNOWN; - mIndex = -1; - mContent = SPC_UNKNOWN; - mIsAutoConstantReal = true; - mIsAutoConstantInt = false; - mAutoConstantType = autoType; - mAutoConstantRealData = fAutoConstantData; - mVariability = (uint16)GPV_GLOBAL; - mParamsPtr = NULL; - mPhysicalIndex = -1; - mSize = size; -} - -//----------------------------------------------------------------------- -UniformParameter::UniformParameter(GpuProgramParameters::AutoConstantType autoType, uint32 nAutoConstantData, size_t size) -{ - auto parameterDef = GpuProgramParameters::getAutoConstantDefinition(autoType); - assert(parameterDef); - - mName = parameterDef->name; - if (nAutoConstantData != 0) - mName += StringConverter::toString(nAutoConstantData); - mType = getGCType(parameterDef); - mSemantic = SPS_UNKNOWN; - mIndex = -1; - mContent = SPC_UNKNOWN; - mIsAutoConstantReal = false; - mIsAutoConstantInt = true; - mAutoConstantType = autoType; - mAutoConstantIntData = nAutoConstantData; - mVariability = (uint16)GPV_GLOBAL; - mParamsPtr = NULL; - mPhysicalIndex = -1; - mSize = size; -} - -//----------------------------------------------------------------------- -UniformParameter::UniformParameter(GpuProgramParameters::AutoConstantType autoType, uint32 nAutoConstantData, size_t size, GpuConstantType type) -{ - auto parameterDef = GpuProgramParameters::getAutoConstantDefinition(autoType); - assert(parameterDef); - - mName = parameterDef->name; - if (nAutoConstantData != 0) - mName += StringConverter::toString(nAutoConstantData); - mType = type; - mSemantic = SPS_UNKNOWN; - mIndex = -1; - mContent = SPC_UNKNOWN; - mIsAutoConstantReal = false; - mIsAutoConstantInt = true; - mAutoConstantType = autoType; - mAutoConstantIntData = nAutoConstantData; - mVariability = (uint16)GPV_GLOBAL; - mParamsPtr = NULL; - mPhysicalIndex = -1; - mSize = size; -} - -//----------------------------------------------------------------------- -void UniformParameter::bind(GpuProgramParametersSharedPtr paramsPtr) -{ - // do not throw on failure: some RS optimize unused uniforms away. Also unit tests run without any RS - const GpuConstantDefinition* def = paramsPtr->_findNamedConstantDefinition(mBindName.empty() ? mName : mBindName, false); - - if (def != NULL) - { - mParamsPtr = paramsPtr.get(); - mPhysicalIndex = def->physicalIndex; - mElementSize = def->elementSize; - mVariability = def->variability; - } -} - -//----------------------------------------------------------------------- -ParameterPtr ParameterFactory::createInPosition(int index, Parameter::Content content) -{ - return std::make_shared(GCT_FLOAT4, "iPos_" + StringConverter::toString(index), - Parameter::SPS_POSITION, index, - content); -} - -//----------------------------------------------------------------------- -ParameterPtr ParameterFactory::createOutPosition(int index) -{ - return std::make_shared(GCT_FLOAT4, "oPos_" + StringConverter::toString(index), - Parameter::SPS_POSITION, index, - Parameter::SPC_POSITION_PROJECTIVE_SPACE); -} - -//----------------------------------------------------------------------- -ParameterPtr ParameterFactory::createInNormal(int index) -{ - return std::make_shared(GCT_FLOAT3, "iNormal_" + StringConverter::toString(index), - Parameter::SPS_NORMAL, index, - Parameter::SPC_NORMAL_OBJECT_SPACE); -} - - -//----------------------------------------------------------------------- -ParameterPtr ParameterFactory::createInWeights(int index) -{ - return std::make_shared(GCT_FLOAT4, "iBlendWeights_" + StringConverter::toString(index), - Parameter::SPS_BLEND_WEIGHTS, index, - Parameter::SPC_BLEND_WEIGHTS); -} - - -//----------------------------------------------------------------------- -ParameterPtr ParameterFactory::createInIndices(int index) -{ - return std::make_shared( - GCT_UINT4 - , "iBlendIndices_" + StringConverter::toString(index), - Parameter::SPS_BLEND_INDICES, index, - Parameter::SPC_BLEND_INDICES); -} - -//----------------------------------------------------------------------- -ParameterPtr ParameterFactory::createInBiNormal(int index) -{ - return std::make_shared(GCT_FLOAT3, "iBiNormal_" + StringConverter::toString(index), - Parameter::SPS_BINORMAL, index, - Parameter::SPC_BINORMAL_OBJECT_SPACE); -} - -//----------------------------------------------------------------------- -ParameterPtr ParameterFactory::createInTangent(int index) -{ - return std::make_shared(GCT_FLOAT3, "iTangent_" + StringConverter::toString(index), - Parameter::SPS_TANGENT, index, - Parameter::SPC_TANGENT_OBJECT_SPACE); -} - -//----------------------------------------------------------------------- -ParameterPtr ParameterFactory::createOutNormal(int index) -{ - return std::make_shared(GCT_FLOAT3, "oNormal_" + StringConverter::toString(index), - Parameter::SPS_NORMAL, index, - Parameter::SPC_NORMAL_OBJECT_SPACE); -} - -//----------------------------------------------------------------------- -ParameterPtr ParameterFactory::createOutBiNormal(int index) -{ - return std::make_shared(GCT_FLOAT3, "oBiNormal_" + StringConverter::toString(index), - Parameter::SPS_BINORMAL, index, - Parameter::SPC_BINORMAL_OBJECT_SPACE); -} - -//----------------------------------------------------------------------- -ParameterPtr ParameterFactory::createOutTangent(int index) -{ - return std::make_shared(GCT_FLOAT3, "oTangent_" + StringConverter::toString(index), - Parameter::SPS_TANGENT, index, - Parameter::SPC_TANGENT_OBJECT_SPACE); -} - -//----------------------------------------------------------------------- -ParameterPtr ParameterFactory::createInColor(int index) -{ - return std::make_shared(GCT_FLOAT4, "iColor_" + StringConverter::toString(index), - Parameter::SPS_COLOR, index, - index == 0 ? Parameter::SPC_COLOR_DIFFUSE : Parameter::SPC_COLOR_SPECULAR); -} - -//----------------------------------------------------------------------- -ParameterPtr ParameterFactory::createOutColor(int index) -{ - return std::make_shared(GCT_FLOAT4, "oColor_" + StringConverter::toString(index), - Parameter::SPS_COLOR, index, - index == 0 ? Parameter::SPC_COLOR_DIFFUSE : Parameter::SPC_COLOR_SPECULAR); -} - -//----------------------------------------------------------------------- -ParameterPtr ParameterFactory::createInTexcoord(GpuConstantType type, int index, Parameter::Content content) -{ - switch (type) - { - case GCT_FLOAT1: - case GCT_FLOAT2: - case GCT_FLOAT3: - case GCT_FLOAT4: - case GCT_MATRIX_2X2: - case GCT_MATRIX_2X3: - case GCT_MATRIX_2X4: - case GCT_MATRIX_3X2: - case GCT_MATRIX_3X3: - case GCT_MATRIX_3X4: - case GCT_MATRIX_4X2: - case GCT_MATRIX_4X3: - case GCT_MATRIX_4X4: - case GCT_INT1: - case GCT_INT2: - case GCT_INT3: - case GCT_INT4: - case GCT_UINT1: - case GCT_UINT2: - case GCT_UINT3: - case GCT_UINT4: - return std::make_shared(type, StringUtil::format("iTexcoord_%d", index), - Parameter::SPS_TEXTURE_COORDINATES, index, content); - default: - case GCT_SAMPLER1D: - case GCT_SAMPLER2D: - case GCT_SAMPLER2DARRAY: - case GCT_SAMPLER3D: - case GCT_SAMPLERCUBE: - case GCT_SAMPLER1DSHADOW: - case GCT_SAMPLER2DSHADOW: - case GCT_UNKNOWN: - break; - } - - return ParameterPtr(); -} - -//----------------------------------------------------------------------- -ParameterPtr ParameterFactory::createOutTexcoord(GpuConstantType type, int index, Parameter::Content content) -{ - switch (type) - { - case GCT_FLOAT1: - case GCT_FLOAT2: - case GCT_FLOAT3: - case GCT_FLOAT4: - return std::make_shared(type, StringUtil::format("oTexcoord_%d", index), - Parameter::SPS_TEXTURE_COORDINATES, index, content); - default: - case GCT_SAMPLER1D: - case GCT_SAMPLER2D: - case GCT_SAMPLER2DARRAY: - case GCT_SAMPLER3D: - case GCT_SAMPLERCUBE: - case GCT_SAMPLER1DSHADOW: - case GCT_SAMPLER2DSHADOW: - case GCT_MATRIX_2X2: - case GCT_MATRIX_2X3: - case GCT_MATRIX_2X4: - case GCT_MATRIX_3X2: - case GCT_MATRIX_3X3: - case GCT_MATRIX_3X4: - case GCT_MATRIX_4X2: - case GCT_MATRIX_4X3: - case GCT_MATRIX_4X4: - case GCT_INT1: - case GCT_INT2: - case GCT_INT3: - case GCT_INT4: - case GCT_UINT1: - case GCT_UINT2: - case GCT_UINT3: - case GCT_UINT4: - case GCT_UNKNOWN: - break; - } - - return ParameterPtr(); -} - -//----------------------------------------------------------------------- -UniformParameterPtr ParameterFactory::createSampler(GpuConstantType type, int index) -{ - switch (type) - { - case GCT_SAMPLER1D: - return createSampler1D(index); - - case GCT_SAMPLER2D: - return createSampler2D(index); - - case GCT_SAMPLER2DARRAY: - return createSampler2DArray(index); - - case GCT_SAMPLER3D: - return createSampler3D(index); - - case GCT_SAMPLERCUBE: - return createSamplerCUBE(index); - - default: - case GCT_SAMPLER1DSHADOW: - case GCT_SAMPLER2DSHADOW: - case GCT_MATRIX_2X2: - case GCT_MATRIX_2X3: - case GCT_MATRIX_2X4: - case GCT_MATRIX_3X2: - case GCT_MATRIX_3X3: - case GCT_MATRIX_3X4: - case GCT_MATRIX_4X2: - case GCT_MATRIX_4X3: - case GCT_MATRIX_4X4: - case GCT_INT1: - case GCT_INT2: - case GCT_INT3: - case GCT_INT4: - case GCT_UINT1: - case GCT_UINT2: - case GCT_UINT3: - case GCT_UINT4: - case GCT_UNKNOWN: - break; - } - - return UniformParameterPtr(); - -} - -//----------------------------------------------------------------------- -UniformParameterPtr ParameterFactory::createSampler1D(int index) -{ - return std::make_shared(GCT_SAMPLER1D, "gSampler1D_" + StringConverter::toString(index), - Parameter::SPS_UNKNOWN, index, - Parameter::SPC_UNKNOWN, - (uint16)GPV_GLOBAL, 1); -} - -//----------------------------------------------------------------------- -UniformParameterPtr ParameterFactory::createSampler2D(int index) -{ - return std::make_shared(GCT_SAMPLER2D, "gSampler2D_" + StringConverter::toString(index), - Parameter::SPS_UNKNOWN, index, - Parameter::SPC_UNKNOWN, - (uint16)GPV_GLOBAL, 1); -} - -//----------------------------------------------------------------------- -UniformParameterPtr ParameterFactory::createSampler2DArray(int index) -{ - return std::make_shared(GCT_SAMPLER2DARRAY, "gSampler2DArray_" + StringConverter::toString(index), - Parameter::SPS_UNKNOWN, index, - Parameter::SPC_UNKNOWN, - (uint16)GPV_GLOBAL, 1); -} - -//----------------------------------------------------------------------- -UniformParameterPtr ParameterFactory::createSampler3D(int index) -{ - return std::make_shared(GCT_SAMPLER3D, "gSampler3D_" + StringConverter::toString(index), - Parameter::SPS_UNKNOWN, index, - Parameter::SPC_UNKNOWN, - (uint16)GPV_GLOBAL, 1); -} - -//----------------------------------------------------------------------- -UniformParameterPtr ParameterFactory::createSamplerCUBE(int index) -{ - return std::make_shared(GCT_SAMPLERCUBE, "gSamplerCUBE_" + StringConverter::toString(index), - Parameter::SPS_UNKNOWN, index, - Parameter::SPC_UNKNOWN, - (uint16)GPV_GLOBAL, 1); -} -//----------------------------------------------------------------------- -ParameterPtr ParameterFactory::createConstParam(const Vector2& val) -{ - return ParameterPtr(OGRE_NEW ConstParameterVec2(val, GCT_FLOAT2, Parameter::SPS_UNKNOWN, - Parameter::SPC_UNKNOWN)); -} - -//----------------------------------------------------------------------- -ParameterPtr ParameterFactory::createConstParam(const Vector3& val) -{ - return ParameterPtr(OGRE_NEW ConstParameterVec3(val, GCT_FLOAT3, Parameter::SPS_UNKNOWN, - Parameter::SPC_UNKNOWN)); -} - -//----------------------------------------------------------------------- -ParameterPtr ParameterFactory::createConstParam(const Vector4& val) -{ - return ParameterPtr(OGRE_NEW ConstParameterVec4(val, GCT_FLOAT4, Parameter::SPS_UNKNOWN, - Parameter::SPC_UNKNOWN)); -} - -//----------------------------------------------------------------------- -ParameterPtr ParameterFactory::createConstParam(float val) -{ - return ParameterPtr(OGRE_NEW ConstParameterFloat(val, GCT_FLOAT1, Parameter::SPS_UNKNOWN, - Parameter::SPC_UNKNOWN)); -} - -//----------------------------------------------------------------------- -UniformParameterPtr ParameterFactory::createUniform(GpuConstantType type, - int index, uint16 variability, - const String& suggestedName, - size_t size) -{ - UniformParameterPtr param; - - param = std::make_shared(type, suggestedName + StringConverter::toString(index), - Parameter::SPS_UNKNOWN, index, - Parameter::SPC_UNKNOWN, variability, size); - - return param; -} - -} -} diff --git a/Components/RTShaderSystem/src/OgreShaderPrecompiledHeaders.h b/Components/RTShaderSystem/src/OgreShaderPrecompiledHeaders.h deleted file mode 100644 index 0e33e2632a1..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderPrecompiledHeaders.h +++ /dev/null @@ -1,146 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __OgreShaderPrecompiledHeaders__ -#define __OgreShaderPrecompiledHeaders__ - -#include // for std::sort - -#include "OgreMaterialManager.h" -#include "OgreTechnique.h" -#include "OgreSceneManager.h" -#include "OgreViewport.h" -#include "OgreGpuProgramManager.h" -#include "OgreHighLevelGpuProgram.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreRoot.h" -#include "OgreException.h" -#include "OgreStringConverter.h" -#include "OgreLogManager.h" -#include "OgreSceneManager.h" -#include "OgreMesh.h" -#include "OgreSubMesh.h" -#include "OgreEntity.h" -#include "OgreSubEntity.h" -#include "OgreTextureManager.h" - -#include "OgreShaderFunction.h" -#include "OgreShaderFunctionAtom.h" -#include "OgreShaderGenerator.h" -#include "OgreShaderProgram.h" -#include "OgreShaderProgramSet.h" -#include "OgreShaderProgramManager.h" -#include "OgreShaderProgramProcessor.h" -#include "OgreShaderRenderState.h" -#include "OgreShaderMaterialSerializerListener.h" -#include "OgreShaderProgramWriterManager.h" - -#include "OgreShaderFFPRenderState.h" -#include "OgreShaderFFPTransform.h" -#include "OgreShaderFFPLighting.h" -#include "OgreShaderFFPColour.h" -#include "OgreShaderFFPTexturing.h" -#include "OgreShaderFFPFog.h" -#include "OgreShaderFFPAlphaTest.h" - -#include "OgreShaderExPerPixelLighting.h" -#include "OgreShaderExNormalMapLighting.h" -#include "OgreShaderExIntegratedPSSM3.h" -#include "OgreShaderExLayeredBlending.h" -#include "OgreShaderExHardwareSkinningTechnique.h" -#include "OgreShaderExHardwareSkinning.h" -#include "OgreShaderExLinearSkinning.h" -#include "OgreShaderExDualQuaternionSkinning.h" -#include "OgreShaderExTriplanarTexturing.h" -#include "OgreShaderExGBuffer.h" -#include "OgreShaderExWBOIT.h" -#include "OgreShaderCookTorranceLighting.h" -#include "OgreShaderImageBasedLighting.h" - -#include "OgreShaderProgramWriter.h" -#include "OgreShaderProgramWriterManager.h" -#include "OgreShaderCGProgramWriter.h" -#include "OgreShaderGLSLProgramWriter.h" -#include "OgreShaderGLSLESProgramWriter.h" - -// Fixed Function Library: Transform functions -#define FFP_LIB_TRANSFORM "FFPLib_Transform" -#define FFP_FUNC_TRANSFORM "FFP_Transform" - -// Fixed Function Library: Texturing functions -#define FFP_LIB_TEXTURING "FFPLib_Texturing" -#define FFP_FUNC_TRANSFORM_TEXCOORD "FFP_TransformTexCoord" -#define FFP_FUNC_GENERATE_TEXCOORD_ENV_NORMAL "FFP_GenerateTexCoord_EnvMap_Normal" -#define FFP_FUNC_GENERATE_TEXCOORD_ENV_SPHERE "FFP_GenerateTexCoord_EnvMap_Sphere" -#define FFP_FUNC_GENERATE_TEXCOORD_ENV_REFLECT "FFP_GenerateTexCoord_EnvMap_Reflect" - -#define FFP_FUNC_ADDSMOOTH "FFP_AddSmooth" -#define FFP_FUNC_DOTPRODUCT "FFP_DotProduct" - -// Fixed Function Library: Fog functions -#define FFP_LIB_FOG "FFPLib_Fog" - -// Fixed Function Library: Alpha Test -#define FFP_LIB_ALPHA_TEST "FFPLib_AlphaTest" -#define FFP_FUNC_ALPHA_TEST "FFP_Alpha_Test" - -#define SGX_LIB_PERPIXELLIGHTING "SGXLib_PerPixelLighting" - -namespace Ogre { -namespace RTShader { -class LayeredBlendingFactory : public SubRenderStateFactory -{ -public: - const String& getType() const override; - SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, TextureUnitState* texState, - SGScriptTranslator* translator) override; - void writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, const TextureUnitState* srcTextureUnit, - const TextureUnitState* dstTextureUnit) override; - -private: - SubRenderState* createInstanceImpl() override; - LayeredBlending* createOrRetrieveSubRenderState(SGScriptTranslator* translator); -}; - -class FFPTexturingFactory : public SubRenderStateFactory -{ -public: - const String& getType() const override; - SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, - SGScriptTranslator* translator) override; - void writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, Pass* dstPass) override; -protected: - SubRenderState* createInstanceImpl() override; -}; - -uint16 ensureLtcLUTPresent(Pass* dstPass); - -} // namespace RTShader -} // namespace Ogre - -#endif diff --git a/Components/RTShaderSystem/src/OgreShaderProgram.cpp b/Components/RTShaderSystem/src/OgreShaderProgram.cpp deleted file mode 100644 index 4ca69e8c36c..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderProgram.cpp +++ /dev/null @@ -1,349 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include - -#include "OgreShaderPrecompiledHeaders.h" - -namespace Ogre { -namespace RTShader { - -//----------------------------------------------------------------------------- -Program::Program(GpuProgramType type) -{ - mType = type; - // all programs must have an entry point - mEntryPointFunction = new Function(type); - mSkeletalAnimation = false; - mColumnMajorMatrices = true; - mInstancing = false; -} - -//----------------------------------------------------------------------------- -Program::~Program() -{ - destroyParameters(); - - delete mEntryPointFunction; -} - -//----------------------------------------------------------------------------- -void Program::destroyParameters() -{ - mParameters.clear(); -} - -//----------------------------------------------------------------------------- -GpuProgramType Program::getType() const -{ - return mType; -} - -//----------------------------------------------------------------------------- -void Program::addParameter(UniformParameterPtr parameter) -{ - if (getParameterByName(parameter->getName()).get() != NULL) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "Parameter <" + parameter->getName() + "> already declared in program.", - "Program::addParameter" ); - } - - mParameters.push_back(parameter); -} - -//----------------------------------------------------------------------------- -void Program::removeParameter(UniformParameterPtr parameter) -{ - UniformParameterIterator it; - - for (it = mParameters.begin(); it != mParameters.end(); ++it) - { - if ((*it) == parameter) - { - (*it).reset(); - mParameters.erase(it); - break; - } - } -} - -//----------------------------------------------------------------------------- - -static bool isArray(GpuProgramParameters::AutoConstantType autoType) -{ - switch (autoType) - { - case GpuProgramParameters::ACT_WORLD_MATRIX_ARRAY_3x4: - case GpuProgramParameters::ACT_WORLD_MATRIX_ARRAY: - case GpuProgramParameters::ACT_WORLD_DUALQUATERNION_ARRAY_2x4: - case GpuProgramParameters::ACT_WORLD_SCALE_SHEAR_MATRIX_ARRAY_3x4: - case GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR_ARRAY: - case GpuProgramParameters::ACT_LIGHT_SPECULAR_COLOUR_ARRAY: - case GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR_POWER_SCALED_ARRAY: - case GpuProgramParameters::ACT_LIGHT_SPECULAR_COLOUR_POWER_SCALED_ARRAY: - case GpuProgramParameters::ACT_LIGHT_ATTENUATION_ARRAY: - case GpuProgramParameters::ACT_LIGHT_POSITION_ARRAY: - case GpuProgramParameters::ACT_LIGHT_POSITION_OBJECT_SPACE_ARRAY: - case GpuProgramParameters::ACT_LIGHT_POSITION_VIEW_SPACE_ARRAY: - case GpuProgramParameters::ACT_LIGHT_DIRECTION_ARRAY: - case GpuProgramParameters::ACT_LIGHT_DIRECTION_OBJECT_SPACE_ARRAY: - case GpuProgramParameters::ACT_LIGHT_DIRECTION_VIEW_SPACE_ARRAY: - case GpuProgramParameters::ACT_LIGHT_DISTANCE_OBJECT_SPACE_ARRAY: - case GpuProgramParameters::ACT_LIGHT_POWER_SCALE_ARRAY: - case GpuProgramParameters::ACT_SPOTLIGHT_PARAMS_ARRAY: - case GpuProgramParameters::ACT_DERIVED_LIGHT_DIFFUSE_COLOUR_ARRAY: - case GpuProgramParameters::ACT_DERIVED_LIGHT_SPECULAR_COLOUR_ARRAY: - case GpuProgramParameters::ACT_LIGHT_CASTS_SHADOWS_ARRAY: - case GpuProgramParameters::ACT_TEXTURE_VIEWPROJ_MATRIX_ARRAY: - case GpuProgramParameters::ACT_TEXTURE_WORLDVIEWPROJ_MATRIX_ARRAY: - case GpuProgramParameters::ACT_SPOTLIGHT_VIEWPROJ_MATRIX_ARRAY: - case GpuProgramParameters::ACT_SPOTLIGHT_WORLDVIEWPROJ_MATRIX_ARRAY: - case GpuProgramParameters::ACT_SHADOW_SCENE_DEPTH_RANGE_ARRAY: - return true; - default: - return false; - } -} - -UniformParameterPtr Program::resolveParameter(GpuProgramParameters::AutoConstantType autoType, uint32 data) -{ - UniformParameterPtr param; - - // Check if parameter already exists. - param = getParameterByAutoType(autoType); - - if (param && param->getAutoConstantIntData() == data) - { - return param; - } - - uint32 size = 0; - if(isArray(autoType)) std::swap(size, data); // for array autotypes the extra parameter is the size - - // Create new parameter - param = std::make_shared(autoType, data, size); - addParameter(param); - - return param; -} - -UniformParameterPtr Program::resolveAutoParameterReal(GpuProgramParameters::AutoConstantType autoType, - Real data, size_t size) -{ - UniformParameterPtr param; - - // Check if parameter already exists. - param = getParameterByAutoType(autoType); - if (param.get() != NULL) - { - if (param->isAutoConstantRealParameter() && - param->getAutoConstantRealData() == data) - { - param->setSize(std::max(size, param->getSize())); - return param; - } - } - - // Create new parameter. - param = std::make_shared(autoType, float(data), size); - addParameter(param); - - return param; -} - -//----------------------------------------------------------------------------- -UniformParameterPtr Program::resolveAutoParameterReal(GpuProgramParameters::AutoConstantType autoType, GpuConstantType type, - float data, size_t size) -{ - UniformParameterPtr param; - - // Check if parameter already exists. - param = getParameterByAutoType(autoType); - if (param.get() != NULL) - { - if (param->isAutoConstantRealParameter() && - param->getAutoConstantRealData() == data) - { - param->setSize(std::max(size, param->getSize())); - return param; - } - } - - // Create new parameter. - param = std::make_shared(autoType, data, size, type); - addParameter(param); - - return param; -} - -//----------------------------------------------------------------------------- -UniformParameterPtr Program::resolveAutoParameterInt(GpuProgramParameters::AutoConstantType autoType, GpuConstantType type, - uint32 data, size_t size) -{ - UniformParameterPtr param; - - // Check if parameter already exists. - param = getParameterByAutoType(autoType); - if (param.get() != NULL) - { - if (param->isAutoConstantIntParameter() && - param->getAutoConstantIntData() == data) - { - param->setSize(std::max(size, param->getSize())); - return param; - } - } - - // Create new parameter. - param = std::make_shared(autoType, data, size, type); - addParameter(param); - - return param; -} - -//----------------------------------------------------------------------------- -UniformParameterPtr Program::resolveParameter(GpuConstantType type, - int index, uint16 variability, - const String& suggestedName, - size_t size) -{ - UniformParameterPtr param; - - if (index == -1) - { - index = 0; - - // Find the next available index of the target type. - UniformParameterIterator it; - - for (it = mParameters.begin(); it != mParameters.end(); ++it) - { - if ((*it)->getType() == type && - (*it)->isAutoConstantParameter() == false) - { - index++; - } - } - } - else - { - // Check if parameter already exists. - param = getParameterByType(type, index); - if (param.get() != NULL) - { - return param; - } - } - - // Create new parameter. - param = ParameterFactory::createUniform(type, index, variability, suggestedName, size); - addParameter(param); - - return param; -} - - - -//----------------------------------------------------------------------------- -UniformParameterPtr Program::getParameterByName(const String& name) -{ - UniformParameterIterator it; - - for (it = mParameters.begin(); it != mParameters.end(); ++it) - { - if ((*it)->getName() == name) - { - return *it; - } - } - - return UniformParameterPtr(); -} - -//----------------------------------------------------------------------------- -UniformParameterPtr Program::getParameterByType(GpuConstantType type, int index) -{ - UniformParameterIterator it; - - for (it = mParameters.begin(); it != mParameters.end(); ++it) - { - if ((*it)->getType() == type && - (*it)->getIndex() == index) - { - return *it; - } - } - - return UniformParameterPtr(); -} - -//----------------------------------------------------------------------------- -UniformParameterPtr Program::getParameterByAutoType(GpuProgramParameters::AutoConstantType autoType) -{ - for (const auto& p : mParameters) - { - if (p->isAutoConstantParameter() && p->getAutoConstantType() == autoType) - return p; - } - - return UniformParameterPtr(); -} - -//----------------------------------------------------------------------------- -void Program::addDependency(const String& libFileName) -{ - for (auto & dep : mDependencies) - { - if (dep == libFileName) - { - return; - } - } - mDependencies.push_back(libFileName); -} - -void Program::addPreprocessorDefines(const String& defines) -{ - mPreprocessorDefines += - mPreprocessorDefines.empty() ? defines : ("," + defines); -} - -//----------------------------------------------------------------------------- -size_t Program::getDependencyCount() const -{ - return mDependencies.size(); -} - -//----------------------------------------------------------------------------- -const String& Program::getDependency(unsigned int index) const -{ - return mDependencies[index]; -} - -} -} diff --git a/Components/RTShaderSystem/src/OgreShaderProgramManager.cpp b/Components/RTShaderSystem/src/OgreShaderProgramManager.cpp deleted file mode 100644 index 1a932725f05..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderProgramManager.cpp +++ /dev/null @@ -1,306 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderPrecompiledHeaders.h" - -namespace Ogre { - -//----------------------------------------------------------------------- -template<> -RTShader::ProgramManager* Singleton::msSingleton = 0; - -namespace RTShader { - - -//----------------------------------------------------------------------- -ProgramManager* ProgramManager::getSingletonPtr() -{ - return msSingleton; -} - -//----------------------------------------------------------------------- -ProgramManager& ProgramManager::getSingleton() -{ - assert( msSingleton ); - return ( *msSingleton ); -} - -//----------------------------------------------------------------------------- -ProgramManager::ProgramManager() -{ - createDefaultProgramProcessors(); -} - -//----------------------------------------------------------------------------- -ProgramManager::~ProgramManager() -{ - flushGpuProgramsCache(); - destroyDefaultProgramProcessors(); -} - -//----------------------------------------------------------------------------- -void ProgramManager::releasePrograms(const ProgramSet* programSet) -{ - for(auto t : {GPT_VERTEX_PROGRAM, GPT_FRAGMENT_PROGRAM}) - { - const auto& prg = programSet->getGpuProgram(t); - if(prg.use_count() > ResourceGroupManager::RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS + 2) - continue; - - const auto it = std::find(mShaderList.begin(), mShaderList.end(), prg); - // TODO: this check should not be necessary, but we observed strange prg.use_count() in the wild - if(it != mShaderList.end()) - mShaderList.erase(it); - GpuProgramManager::getSingleton().remove(prg); - } -} -size_t ProgramManager::getShaderCount(GpuProgramType type) const -{ - size_t count = 0; - - for(const auto& s : mShaderList) - { - count += size_t(s->getType() == type); - } - - return count; -} -//----------------------------------------------------------------------------- -void ProgramManager::flushGpuProgramsCache() -{ - for(auto& s : mShaderList) - { - GpuProgramManager::getSingleton().remove(s); - } - mShaderList.clear(); -} -//----------------------------------------------------------------------------- -void ProgramManager::createDefaultProgramProcessors() -{ - // Add standard shader processors - mDefaultProgramProcessors.push_back(OGRE_NEW ProgramProcessor); -} - -//----------------------------------------------------------------------------- -void ProgramManager::destroyDefaultProgramProcessors() -{ - for (auto processor : mDefaultProgramProcessors) { - OGRE_DELETE processor; - } - mDefaultProgramProcessors.clear(); -} - -//----------------------------------------------------------------------------- -void ProgramManager::createGpuPrograms(ProgramSet* programSet) -{ - // Before we start we need to make sure that the pixel shader input - // parameters are the same as the vertex output, this required by - // shader models 4 and 5. - matchVStoPSInterface(programSet); - - // Grab the matching writer. - const String& language = ShaderGenerator::getSingleton().getTargetLanguage(); - - auto programWriter = ProgramWriterManager::getSingleton().getProgramWriter(language); - - ProgramProcessor* programProcessor = mDefaultProgramProcessors.front(); - - // Call the pre creation of GPU programs method. - if (!programProcessor->preCreateGpuPrograms(programSet)) - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "preCreateGpuPrograms failed"); - - // Create the shader programs - for(auto type : {GPT_VERTEX_PROGRAM, GPT_FRAGMENT_PROGRAM}) - { - auto gpuProgram = createGpuProgram(programSet->getCpuProgram(type), programWriter, language, - ShaderGenerator::getSingleton().getShaderProfiles(type), - ShaderGenerator::getSingleton().getShaderCachePath()); - programSet->setGpuProgram(gpuProgram); - } - - // update VS flags - auto gpuVs = programSet->getGpuProgram(GPT_VERTEX_PROGRAM); - auto cpuVs = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - gpuVs->setSkeletalAnimationIncluded(cpuVs->getSkeletalAnimationIncluded()); - gpuVs->setInstancingIncluded(cpuVs->getInstancingIncluded()); - - // Call the post creation of GPU programs method. - if(!programProcessor->postCreateGpuPrograms(programSet)) - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "postCreateGpuPrograms failed"); -} - -//----------------------------------------------------------------------------- -GpuProgramPtr ProgramManager::createGpuProgram(Program* shaderProgram, - ProgramWriter* programWriter, - const String& language, - const String& profiles, - const String& cachePath) -{ - std::stringstream sourceCodeStringStream; - - // Generate source code. - programWriter->writeSourceCode(sourceCodeStringStream, shaderProgram); - String source = sourceCodeStringStream.str(); - - // Generate program name. - String programName = generateHash(source, shaderProgram->getPreprocessorDefines()); - - if (shaderProgram->getType() == GPT_VERTEX_PROGRAM) - { - programName += "_VS"; - } - else if (shaderProgram->getType() == GPT_FRAGMENT_PROGRAM) - { - programName += "_FS"; - } - - // Try to get program by name. - auto pGpuProgram = GpuProgramManager::getSingleton().getByName(programName, RGN_INTERNAL); - - if(pGpuProgram) { - return pGpuProgram; - } - - // Case the program doesn't exist yet. - // Create new GPU program. - pGpuProgram = - GpuProgramManager::getSingleton().createProgram(programName, RGN_INTERNAL, language, shaderProgram->getType()); - - // Case cache directory specified -> create program from file. - if (!cachePath.empty()) - { - const String programFullName = programName + "." + programWriter->getTargetLanguage(); - const String programFileName = cachePath + programFullName; - std::ifstream programFile; - - // Check if program file already exist. - programFile.open(programFileName.c_str()); - - // Case we have to write the program to a file. - if (!programFile) - { - std::ofstream outFile(programFileName.c_str()); - - if (!outFile) - return GpuProgramPtr(); - - outFile << source; - outFile.close(); - } - else - { - // use program file version - StringStream buffer; - programFile >> buffer.rdbuf(); - source = buffer.str(); - } - } - - pGpuProgram->setSource(source); - pGpuProgram->setParameter("preprocessor_defines", shaderProgram->getPreprocessorDefines()); - pGpuProgram->setParameter("entry_point", "main"); - - if (language == "hlsl") - { - pGpuProgram->setParameter("target", profiles); - pGpuProgram->setParameter("enable_backwards_compatibility", "true"); - pGpuProgram->setParameter("column_major_matrices", StringConverter::toString(shaderProgram->getUseColumnMajorMatrices())); - } - else if (language == "glsl") - { - auto* rs = Root::getSingleton().getRenderSystem(); - if( rs && rs->getNativeShadingLanguageVersion() >= 420) - pGpuProgram->setParameter("has_sampler_binding", "true"); - } - - pGpuProgram->load(); - - // Add the created GPU program to local index - mShaderList.push_back(pGpuProgram); - - return pGpuProgram; -} - - -//----------------------------------------------------------------------------- -String ProgramManager::generateHash(const String& programString, const String& defines) -{ - //Different programs must have unique hash values. - uint32_t hash[4]; - uint32_t seed = FastHash(defines.c_str(), defines.size()); - MurmurHash3_128(programString.c_str(), programString.size(), seed, hash); - - //Generate the string - return StringUtil::format("%08x%08x%08x%08x", hash[0], hash[1], hash[2], hash[3]); -} - -//----------------------------------------------------------------------- -void ProgramManager::matchVStoPSInterface( ProgramSet* programSet ) -{ - Function* vertexMain = programSet->getCpuProgram(GPT_VERTEX_PROGRAM)->getMain(); - Function* pixelMain = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM)->getMain(); - - // save the pixel program original input parameters - auto pixelOriginalInParams = pixelMain->getInputParameters(); - - // set the pixel Input to be the same as the vertex prog output - pixelMain->deleteAllInputParameters(); - - // Loop the vertex shader output parameters and make sure that - // all of them exist in the pixel shader input. - // If the parameter type exist in the original output - use it - // If the parameter doesn't exist - use the parameter from the - // vertex shader input. - // The order will be based on the vertex shader parameters order - // Write output parameters. - for (const auto& curOutParemter : vertexMain->getOutputParameters()) - { - ParameterPtr paramToAdd = Function::_getParameterBySemantic( - pixelOriginalInParams, curOutParemter->getSemantic(), curOutParemter->getIndex()); - - pixelOriginalInParams.erase( - std::remove(pixelOriginalInParams.begin(), pixelOriginalInParams.end(), paramToAdd), - pixelOriginalInParams.end()); - - if (!paramToAdd) - { - // param not found - we will add the one from the vertex shader - paramToAdd = curOutParemter; - } - - pixelMain->addInputParameter(paramToAdd); - } - - for(const auto& paramToAdd : pixelOriginalInParams) - { - pixelMain->addInputParameter(paramToAdd); - } -} - -/** @} */ -/** @} */ -} -} diff --git a/Components/RTShaderSystem/src/OgreShaderProgramProcessor.cpp b/Components/RTShaderSystem/src/OgreShaderProgramProcessor.cpp deleted file mode 100644 index 7931cb50804..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderProgramProcessor.cpp +++ /dev/null @@ -1,1012 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreShaderPrecompiledHeaders.h" - -namespace Ogre { -namespace RTShader { - -//----------------------------------------------------------------------------- -ProgramProcessor::ProgramProcessor() -{ - mMaxTexCoordSlots = 16; - mMaxTexCoordFloats = mMaxTexCoordSlots * 4; - -} - -//----------------------------------------------------------------------------- -ProgramProcessor::~ProgramProcessor() -{ - -} - -//----------------------------------------------------------------------------- -bool ProgramProcessor::preCreateGpuPrograms(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* fsProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Function* fsMain = fsProgram->getEntryPointFunction(); - - // Compact vertex shader outputs. - return compactVsOutputs(vsMain, fsMain); -} - - -bool ProgramProcessor::postCreateGpuPrograms(ProgramSet* programSet) -{ - // Bind vertex auto parameters. - for(auto type : {GPT_VERTEX_PROGRAM, GPT_FRAGMENT_PROGRAM}) - bindAutoParameters(programSet->getCpuProgram(type), programSet->getGpuProgram(type)); - - if(ShaderGenerator::getSingleton().getTargetLanguage().find("glsl") == String::npos) - return true; - - for(auto type : {GPT_VERTEX_PROGRAM, GPT_FRAGMENT_PROGRAM}) - bindTextureSamplers(programSet->getCpuProgram(type), programSet->getGpuProgram(type)); - - return true; -} - -//----------------------------------------------------------------------------- -void ProgramProcessor::bindAutoParameters(Program* pCpuProgram, GpuProgramPtr pGpuProgram) -{ - GpuProgramParametersSharedPtr pGpuParams = pGpuProgram->getDefaultParameters(); - - for (const auto& p : pCpuProgram->getParameters()) - { - const GpuConstantDefinition* gpuConstDef = pGpuParams->_findNamedConstantDefinition(p->getName()); - - if (gpuConstDef != NULL) - { - // Handle auto parameters. - if (p->isAutoConstantParameter()) - { - if (p->isAutoConstantRealParameter()) - { - pGpuParams->setNamedAutoConstantReal(p->getName(), - p->getAutoConstantType(), - p->getAutoConstantRealData()); - - } - else if (p->isAutoConstantIntParameter()) - { - pGpuParams->setNamedAutoConstant(p->getName(), - p->getAutoConstantType(), - p->getAutoConstantIntData()); - } - } - - // Case this is not auto constant - we have to update its variability ourself. - else - { - gpuConstDef->variability |= p->getVariability(); - - // Update variability in the float map. - if (gpuConstDef->isSampler() == false) - { - GpuLogicalBufferStructPtr floatLogical = pGpuParams->getLogicalBufferStruct(); - if (floatLogical.get()) - { - for (GpuLogicalIndexUseMap::const_iterator i = floatLogical->map.begin(); i != floatLogical->map.end(); ++i) - { - if (i->second.physicalIndex == gpuConstDef->physicalIndex) - { - i->second.variability |= gpuConstDef->variability; - break; - } - } - } - } - } - } - } -} - -void ProgramProcessor::bindTextureSamplers(Program* pCpuProgram, GpuProgramPtr pGpuProgram) -{ - if (StringConverter::parseBool(pGpuProgram->getParameter("has_sampler_binding"))) - return; - - GpuProgramParametersSharedPtr pGpuParams = pGpuProgram->getDefaultParameters(); - - // Bind the samplers. - for (const auto& pCurParam : pCpuProgram->getParameters()) - { - if (pCurParam->isSampler() && pCurParam->isUsed()) - { - // The optimizer may remove some unnecessary parameters, so we should ignore them - pGpuParams->setIgnoreMissingParams(true); - pGpuParams->setNamedConstant(pCurParam->getName(), pCurParam->getIndex()); - } - } -} - -//----------------------------------------------------------------------------- -bool ProgramProcessor::compactVsOutputs(Function* vsMain, Function* fsMain) -{ - - int outTexCoordSlots; - int outTexCoordFloats; - - // Count vertex shader texcoords outputs. - countVsTexcoordOutputs(vsMain, outTexCoordSlots, outTexCoordFloats); - - // Case the total number of used floats is bigger than maximum - nothing we can do. - if (outTexCoordFloats > mMaxTexCoordFloats) - return false; - - // Only one slot used -> nothing to compact. - if (outTexCoordSlots <= 1) - return true; - - // Case compact policy is low and output slots are enough -> quit compacting process. - if (ShaderGenerator::getSingleton().getVertexShaderOutputsCompactPolicy() == VSOCP_LOW && outTexCoordSlots <= mMaxTexCoordSlots) - return true; - - // Build output parameter tables - each row represents different parameter type (GCT_FLOAT1-4). - ShaderParameterList vsOutParamsTable[4]; - ShaderParameterList fsInParamsTable[4]; - - buildTexcoordTable(vsMain->getOutputParameters(), vsOutParamsTable); - buildTexcoordTable(fsMain->getInputParameters(), fsInParamsTable); - - - // Create merge parameters entries using the predefined merge combinations. - MergeParameterList vsMergedParamsList; - MergeParameterList fsMergedParamsList; - ShaderParameterList vsSplitParams; - ShaderParameterList fsSplitParams; - bool hasMergedParameters = false; - - mergeParameters(vsOutParamsTable, vsMergedParamsList, vsSplitParams); - - - // Check if any parameter has been merged - means at least two parameters takes the same slot. - for (auto & i : vsMergedParamsList) - { - if (i.getSourceParameterCount() > 1) - { - hasMergedParameters = true; - break; - } - } - - // Case no parameter has been merged -> quit compacting process. - if (hasMergedParameters == false) - return true; - - mergeParameters(fsInParamsTable, fsMergedParamsList, fsSplitParams); - - // Generate local params for split source parameters. - LocalParameterMap vsLocalParamsMap; - LocalParameterMap fsLocalParamsMap; - - generateLocalSplitParameters(vsMain, GPT_VERTEX_PROGRAM, vsMergedParamsList, vsSplitParams, vsLocalParamsMap); - generateLocalSplitParameters(fsMain, GPT_FRAGMENT_PROGRAM, fsMergedParamsList, fsSplitParams, fsLocalParamsMap); - - - // Rebuild functions parameter lists. - rebuildParameterList(vsMain, Operand::OPS_OUT, vsMergedParamsList); - rebuildParameterList(fsMain, Operand::OPS_IN, fsMergedParamsList); - - // Adjust function invocations operands to reference the new merged parameters. - rebuildFunctionInvocations(vsMain->getAtomInstances(), vsMergedParamsList, vsLocalParamsMap); - rebuildFunctionInvocations(fsMain->getAtomInstances(), fsMergedParamsList, fsLocalParamsMap); - - - return true; -} - -//----------------------------------------------------------------------------- -void ProgramProcessor::countVsTexcoordOutputs(Function* vsMain, - int& outTexCoordSlots, - int& outTexCoordFloats) -{ - outTexCoordSlots = 0; - outTexCoordFloats = 0; - - // Grab vertex shader output information. - for (const auto& p : vsMain->getOutputParameters()) - { - if (p->getSemantic() == Parameter::SPS_TEXTURE_COORDINATES) - { - outTexCoordSlots++; - outTexCoordFloats += getParameterFloatCount(p->getType()); - } - } -} - -//----------------------------------------------------------------------------- -void ProgramProcessor::buildTexcoordTable(const ShaderParameterList& paramList, ShaderParameterList outParamsTable[4]) -{ - for (const auto& p : paramList) - { - if (p->getSemantic() == Parameter::SPS_TEXTURE_COORDINATES) - { - - switch (p->getType()) - { - case GCT_FLOAT1: - outParamsTable[0].push_back(p); - break; - - case GCT_FLOAT2: - outParamsTable[1].push_back(p); - break; - - case GCT_FLOAT3: - outParamsTable[2].push_back(p); - break; - - case GCT_FLOAT4: - outParamsTable[3].push_back(p); - break; - case GCT_SAMPLER1D: - case GCT_SAMPLER2D: - case GCT_SAMPLER2DARRAY: - case GCT_SAMPLER3D: - case GCT_SAMPLERCUBE: - case GCT_SAMPLER1DSHADOW: - case GCT_SAMPLER2DSHADOW: - case GCT_MATRIX_2X2: - case GCT_MATRIX_2X3: - case GCT_MATRIX_2X4: - case GCT_MATRIX_3X2: - case GCT_MATRIX_3X3: - case GCT_MATRIX_3X4: - case GCT_MATRIX_4X2: - case GCT_MATRIX_4X3: - case GCT_MATRIX_4X4: - case GCT_INT1: - case GCT_INT2: - case GCT_INT3: - case GCT_INT4: - case GCT_UINT1: - case GCT_UINT2: - case GCT_UINT3: - case GCT_UINT4: - case GCT_UNKNOWN: - default: - break; - } - } - } -} - -//----------------------------------------------------------------------------- -void ProgramProcessor::mergeParameters(ShaderParameterList paramsTable[4], MergeParameterList& mergedParams, - ShaderParameterList& splitParams) -{ - // Merge using the predefined combinations. - mergeParametersByPredefinedCombinations(paramsTable, mergedParams); - - // Merge the reminders parameters if such left. - if (paramsTable[0].size() + paramsTable[1].size() + - paramsTable[2].size() + paramsTable[3].size() > 0) - { - mergeParametersReminders(paramsTable, mergedParams, splitParams); - } -} - -//----------------------------------------------------------------------------- -void ProgramProcessor::mergeParametersByPredefinedCombinations(ShaderParameterList paramsTable[4], - MergeParameterList& mergedParams) -{ - - // Make sure the merge combinations are ready. - if (mParamMergeCombinations.empty()) - { - buildMergeCombinations(); - } - - // Create the full used merged params - means FLOAT4 params that all of their components are used. - for (auto & curCombination : mParamMergeCombinations) - { - // Case all parameters have been merged. - if (paramsTable[0].empty() && paramsTable[1].empty() && - paramsTable[2].empty() && paramsTable[3].empty()) - return; - - MergeParameter curMergeParam; - - while (mergeParametersByCombination(curCombination, paramsTable, &curMergeParam)) - { - mergedParams.push_back(curMergeParam); - curMergeParam.clear(); - } - } - - // Case low/medium compacting policy -> use these simplified combinations in order to prevent splits. - if (ShaderGenerator::getSingleton().getVertexShaderOutputsCompactPolicy() == VSOCP_LOW || - ShaderGenerator::getSingleton().getVertexShaderOutputsCompactPolicy() == VSOCP_MEDIUM) - { - const int curUsedSlots = static_cast(mergedParams.size()); - const int float1ParamCount = static_cast(paramsTable[0].size()); - const int float2ParamCount = static_cast(paramsTable[1].size()); - const int float3ParamCount = static_cast(paramsTable[2].size()); - int reqSlots = 0; - - // Compute the required slots. - - // Add all float3 since each one of them require one slot for himself. - reqSlots += float3ParamCount; - - // Add the float2 count -> at max it will be 1 since all pairs have been merged previously. - if (float2ParamCount > 1) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Invalid float2 reminder count.", - "ProgramProcessor::mergeParametersByPredefinedCombinations"); - } - - reqSlots += float2ParamCount; - - // Compute how much space needed for the float1(s) that left -> at max it will be 3. - if (float1ParamCount > 0) - { - if (float2ParamCount > 3) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Invalid float1 reminder count.", - "ProgramProcessor::mergeParametersByPredefinedCombinations"); - } - - // No float2 -> we need one more slot for these float1(s). - if (float2ParamCount == 0) - { - reqSlots += 1; - } - else - { - // Float2 exists -> there must be at max 1 float1. - if (float1ParamCount > 1) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Invalid float1 reminder count.", - "ProgramProcessor::mergeParametersByPredefinedCombinations"); - } - } - } - - // Case maximum slot count will be exceeded -> fall back to full compaction. - if (curUsedSlots + reqSlots > mMaxTexCoordSlots) - return; - - MergeCombination simpleCombinations[6] = - { - // Deal with the float3 parameters. - MergeCombination( - 0, Operand::OPM_ALL, - 0, Operand::OPM_ALL, - 1, Operand::OPM_ALL, - 0, Operand::OPM_ALL), - - // Deal with float2 + float1 combination. - MergeCombination( - 1, Operand::OPM_ALL, - 1, Operand::OPM_ALL, - 0, Operand::OPM_ALL, - 0, Operand::OPM_ALL), - - // Deal with the float2 parameter. - MergeCombination( - 0, Operand::OPM_ALL, - 1, Operand::OPM_ALL, - 0, Operand::OPM_ALL, - 0, Operand::OPM_ALL), - - // Deal with the 3 float1 combination. - MergeCombination( - 3, Operand::OPM_ALL, - 0, Operand::OPM_ALL, - 0, Operand::OPM_ALL, - 0, Operand::OPM_ALL), - - // Deal with the 2 float1 combination. - MergeCombination( - 2, Operand::OPM_ALL, - 0, Operand::OPM_ALL, - 0, Operand::OPM_ALL, - 0, Operand::OPM_ALL), - - // Deal with the 1 float1 combination. - MergeCombination( - 1, Operand::OPM_ALL, - 0, Operand::OPM_ALL, - 0, Operand::OPM_ALL, - 0, Operand::OPM_ALL), - - }; - - for (const auto & curCombination : simpleCombinations) - { - // Case all parameters have been merged. - if (paramsTable[0].size() + paramsTable[1].size() + paramsTable[2].size() + paramsTable[3].empty()) - break; - - MergeParameter curMergeParam; - - while (mergeParametersByCombination(curCombination, paramsTable, &curMergeParam)) - { - mergedParams.push_back(curMergeParam); - curMergeParam.clear(); - } - } - } -} - -//----------------------------------------------------------------------------- -bool ProgramProcessor::mergeParametersByCombination(const MergeCombination& combination, - ShaderParameterList paramsTable[4], - MergeParameter* mergedParameter) -{ - // Make sure we have enough parameters to combine. - if (combination.srcParameterTypeCount[0] > paramsTable[0].size() || - combination.srcParameterTypeCount[1] > paramsTable[1].size() || - combination.srcParameterTypeCount[2] > paramsTable[2].size() || - combination.srcParameterTypeCount[3] > paramsTable[3].size()) - { - return false; - } - - // Create the new output parameter. - for (int i=0; i < 4; ++i) - { - ShaderParameterList& curParamList = paramsTable[i]; - int srcParameterTypeCount = static_cast(combination.srcParameterTypeCount[i]); - int srcParameterCount = 0; - - while (srcParameterTypeCount > 0) - { - mergedParameter->addSourceParameter(curParamList.back(), combination.srcParameterMask[srcParameterCount]); - curParamList.pop_back(); - srcParameterCount++; - --srcParameterTypeCount; - } - } - - - return true; -} - -//----------------------------------------------------------------------------- -void ProgramProcessor::mergeParametersReminders(ShaderParameterList paramsTable[4], MergeParameterList& mergedParams, ShaderParameterList& splitParams) -{ - - // Handle reminders parameters - All of the parameters that could not packed perfectly. - const size_t mergedParamsBaseIndex = mergedParams.size(); - const size_t remindersFloatCount = (1 * paramsTable[0].size()) + (2 * paramsTable[1].size()) + (3 * paramsTable[2].size()) + (4 * paramsTable[3].size()); - const size_t remindersFloatMod = remindersFloatCount % 4; - const size_t remindersFullSlotCount = remindersFloatCount / 4; - const size_t remindersPartialSlotCount = remindersFloatMod > 0 ? 1 : 0; - const size_t remindersTotalSlotCount = remindersFullSlotCount + remindersPartialSlotCount; - - // First pass -> fill the slots with the largest reminders parameters. - for (unsigned int slot=0; slot < remindersTotalSlotCount; ++slot) - { - MergeParameter curMergeParam; - - for (unsigned int row=0; row < 4; ++row) - { - ShaderParameterList& curParamList = paramsTable[3 - row]; - - // Case this list contains parameters -> pop it out and add to merged params. - if (curParamList.size() > 0) - { - curMergeParam.addSourceParameter(curParamList.back(), Operand::OPM_ALL); - curParamList.pop_back(); - mergedParams.push_back(curMergeParam); - break; - } - } - } - - // Second pass -> merge the reminders parameters. - for (unsigned int row=0; row < 4; ++row) - { - ShaderParameterList& curParamList = paramsTable[3 - row]; - - // Merge the all the parameters of the current list. - while (curParamList.size() > 0) - { - ParameterPtr srcParameter = curParamList.back(); - int splitCount = 0; // How many times the source parameter has been split. - int srcParameterComponents; - int srcParameterFloats; - int curSrcParameterFloats; - - srcParameterFloats = getParameterFloatCount(srcParameter->getType()); - curSrcParameterFloats = srcParameterFloats; - srcParameterComponents = getParameterMaskByType(srcParameter->getType()); - - - // While this parameter has remaining components -> split it. - while (curSrcParameterFloats > 0) - { - for (unsigned int slot=0; slot < remindersTotalSlotCount && curSrcParameterFloats > 0; ++slot) - { - MergeParameter& curMergeParam = mergedParams[mergedParamsBaseIndex + slot]; - const int freeFloatCount = 4 - curMergeParam.getUsedFloatCount(); - - // Case this slot has free space. - if (freeFloatCount > 0) - { - // Case current components of source parameter can go all into this slot without split. - if (srcParameterFloats < freeFloatCount && splitCount == 0) - { - curMergeParam.addSourceParameter(srcParameter, Operand::OPM_ALL); - } - - // Case we have to split the current source parameter. - else - { - int srcComponentsMask; - - // Create the mask that tell us which part of the source component is added to the merged parameter. - srcComponentsMask = getParameterMaskByFloatCount(freeFloatCount) << splitCount; - - // Add the partial source parameter to merged parameter. - curMergeParam.addSourceParameter(srcParameter, Operand::OpMask(srcComponentsMask & srcParameterComponents)); - } - splitCount++; - - // Update left floats count. - if (srcParameterFloats < freeFloatCount) - { - curSrcParameterFloats -= srcParameterFloats; - } - else - { - curSrcParameterFloats -= freeFloatCount; - } - } - } - } - - // Add to split params list. - if (splitCount > 1) - splitParams.push_back(srcParameter); - - - curParamList.pop_back(); - } - } -} - -//----------------------------------------------------------------------------- -void ProgramProcessor::rebuildParameterList(Function* func, int paramsUsage, MergeParameterList& mergedParams) -{ - // Delete the old merged parameters. - for (auto & curMergeParameter : mergedParams) - { - for (unsigned int j=0; j < curMergeParameter.getSourceParameterCount(); ++j) - { - ParameterPtr curSrcParam = curMergeParameter.getSourceParameter(j); - - if (paramsUsage == Operand::OPS_OUT) - { - func->deleteOutputParameter(curSrcParam); - } - else if (paramsUsage == Operand::OPS_IN) - { - func->deleteInputParameter(curSrcParam); - } - } - } - - // Add the new combined parameters. - for (unsigned int i=0; i < mergedParams.size(); ++i) - { - MergeParameter& curMergeParameter = mergedParams[i]; - - if (paramsUsage == Operand::OPS_OUT) - { - func->addOutputParameter(curMergeParameter.getDestinationParameter(i)); - } - else if (paramsUsage == Operand::OPS_IN) - { - func->addInputParameter(curMergeParameter.getDestinationParameter(i)); - } - } -} - -//----------------------------------------------------------------------------- -void ProgramProcessor::generateLocalSplitParameters(Function* func, GpuProgramType progType, - MergeParameterList& mergedParams, - ShaderParameterList& splitParams, LocalParameterMap& localParamsMap) -{ - // No split params created. - if (splitParams.empty()) - return; - - // Create the local parameters + map from source to local. - for (const auto& srcParameter : splitParams) - { - ParameterPtr localParameter = func->resolveLocalParameter(srcParameter->getType(), "lsplit_" + srcParameter->getName()); - - localParamsMap[srcParameter.get()] = localParameter; - } - - // Establish link between the local parameter to the merged parameter. - for (unsigned int i=0; i < mergedParams.size(); ++i) - { - MergeParameter& curMergeParameter = mergedParams[i]; - - for (unsigned int p=0; p < curMergeParameter.getSourceParameterCount(); ++p) - { - ParameterPtr srcMergedParameter = curMergeParameter.getSourceParameter(p); - LocalParameterMap::iterator itFind = localParamsMap.find(srcMergedParameter.get()); - - // Case the source parameter is split parameter. - if (itFind != localParamsMap.end()) - { - // Case it is the vertex shader -> assign the local parameter to the output merged parameter. - if (progType == GPT_VERTEX_PROGRAM) - { - FunctionAtom* curFuncInvocation = OGRE_NEW AssignmentAtom(FFP_VS_POST_PROCESS); - - curFuncInvocation->pushOperand(itFind->second, Operand::OPS_IN, curMergeParameter.getSourceParameterMask(p)); - curFuncInvocation->pushOperand(curMergeParameter.getDestinationParameter(i), Operand::OPS_OUT, curMergeParameter.getDestinationParameterMask(p)); - func->addAtomInstance(curFuncInvocation); - } - else if (progType == GPT_FRAGMENT_PROGRAM) - { - FunctionAtom* curFuncInvocation = OGRE_NEW AssignmentAtom(FFP_PS_PRE_PROCESS); - - curFuncInvocation->pushOperand(curMergeParameter.getDestinationParameter(i), Operand::OPS_IN, curMergeParameter.getDestinationParameterMask(p)); - curFuncInvocation->pushOperand(itFind->second, Operand::OPS_OUT, curMergeParameter.getSourceParameterMask(p)); - func->addAtomInstance(curFuncInvocation); - } - } - } - } -} - -//----------------------------------------------------------------------------- -void ProgramProcessor::rebuildFunctionInvocations(const FunctionAtomInstanceList& funcAtomList, - MergeParameterList& mergedParams, - LocalParameterMap& localParamsMap) -{ - ParameterOperandMap paramsRefMap; - - // Build reference map of source parameters. - buildParameterReferenceMap(funcAtomList, paramsRefMap); - - // Replace references to old parameters with references to new parameters. - replaceParametersReferences(mergedParams, paramsRefMap); - - - // Replace references to old parameters with references to new split parameters. - replaceSplitParametersReferences(localParamsMap, paramsRefMap); - -} - -//----------------------------------------------------------------------------- -void ProgramProcessor::buildParameterReferenceMap(const FunctionAtomInstanceList& funcAtomList, ParameterOperandMap& paramsRefMap) -{ - for (const auto& func : funcAtomList) - { - for (Operand& curOperand : func->getOperandList()) - { - paramsRefMap[curOperand.getParameter().get()].push_back(&curOperand); - } - } -} - -//----------------------------------------------------------------------------- -void ProgramProcessor::replaceParametersReferences(MergeParameterList& mergedParams, ParameterOperandMap& paramsRefMap) -{ - for (unsigned int i=0; i < mergedParams.size(); ++i) - { - MergeParameter& curMergeParameter = mergedParams[i]; - int paramBitMaskOffset = 0; - - for (unsigned int j=0; j < curMergeParameter.getSourceParameterCount(); ++j) - { - ParameterPtr curSrcParam = curMergeParameter.getSourceParameter(j); - ParameterOperandMap::iterator itParamRefs = paramsRefMap.find(curSrcParam.get()); - - // Case the source parameter has some references - if (itParamRefs != paramsRefMap.end()) - { - OperandPtrVector& srcParamRefs = itParamRefs->second; - ParameterPtr dstParameter; - - // Case the source parameter is fully contained within the destination merged parameter. - if (curMergeParameter.getSourceParameterMask(j) == Operand::OPM_ALL) - { - dstParameter = curMergeParameter.getDestinationParameter(i); - - for (auto srcOperandPtr : srcParamRefs) - { - int dstOpMask; - - if (srcOperandPtr->getMask() == Operand::OPM_ALL) - { - // Case the merged parameter contains only one source - no point in adding special mask. - if (curMergeParameter.getSourceParameterCount() == 1) - { - dstOpMask = Operand::OPM_ALL; - } - else - { - dstOpMask = getParameterMaskByType(curSrcParam->getType()) << paramBitMaskOffset; - } - } - else - { - dstOpMask = srcOperandPtr->getMask() << paramBitMaskOffset; - } - - // Replace the original source operand with a new operand the reference the new merged parameter. - *srcOperandPtr = Operand(dstParameter, srcOperandPtr->getSemantic(), Operand::OpMask(dstOpMask)); - } - } - } - - - // Update the bit mask offset. - paramBitMaskOffset += getParameterFloatCount(curSrcParam->getType()); - } - } -} - -//----------------------------------------------------------------------------- -void ProgramProcessor::replaceSplitParametersReferences(LocalParameterMap& localParamsMap, ParameterOperandMap& paramsRefMap) -{ - for (const auto& p : localParamsMap) - { - Parameter* curSrcParam = p.first; - ParameterOperandMap::iterator itParamRefs = paramsRefMap.find(curSrcParam); - - if (itParamRefs != paramsRefMap.end()) - { - ParameterPtr dstParameter = p.second; - OperandPtrVector& srcParamRefs = itParamRefs->second; - - for (auto srcOperandPtr : srcParamRefs) - { - Operand::OpMask dstOpMask; - - if (srcOperandPtr->getMask() == Operand::OPM_ALL) - { - dstOpMask = getParameterMaskByType(curSrcParam->getType()); - } - else - { - dstOpMask = srcOperandPtr->getMask(); - } - - // Replace the original source operand with a new operand the reference the new merged parameter. - *srcOperandPtr = Operand(dstParameter, srcOperandPtr->getSemantic(), dstOpMask); - } - } - } -} - -//----------------------------------------------------------------------------- -int ProgramProcessor::getParameterFloatCount(GpuConstantType type) -{ - int floatCount = 0; - - switch (type) - { - case GCT_FLOAT1: floatCount = 1; break; - case GCT_FLOAT2: floatCount = 2; break; - case GCT_FLOAT3: floatCount = 3; break; - case GCT_FLOAT4: floatCount = 4; break; - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Invalid parameter float type.", - "ProgramProcessor::getParameterFloatCount"); - } - - return floatCount; -} - -//----------------------------------------------------------------------------- -Operand::OpMask ProgramProcessor::getParameterMaskByType(GpuConstantType type) -{ - switch (type) - { - case GCT_FLOAT1: return Operand::OPM_X; - case GCT_FLOAT2: return Operand::OPM_XY; - case GCT_FLOAT3: return Operand::OPM_XYZ; - case GCT_FLOAT4: return Operand::OPM_XYZW; - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Invalid parameter type."); - } -} - -//----------------------------------------------------------------------------- -Operand::OpMask ProgramProcessor::getParameterMaskByFloatCount(int floatCount) -{ - switch (floatCount) - { - case 1: return Operand::OPM_X; - case 2: return Operand::OPM_XY; - case 3: return Operand::OPM_XYZ; - case 4: return Operand::OPM_XYZW; - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Invalid parameter float type"); - } -} - - - -//----------------------------------------------------------------------------- -void ProgramProcessor::buildMergeCombinations() -{ - mParamMergeCombinations.push_back( - MergeCombination( - 1, Operand::OPM_ALL, - 0, Operand::OPM_ALL, - 1, Operand::OPM_ALL, - 0, Operand::OPM_ALL)); - - mParamMergeCombinations.push_back( - MergeCombination( - 2, Operand::OPM_ALL, - 1, Operand::OPM_ALL, - 0, Operand::OPM_ALL, - 0, Operand::OPM_ALL)); - - mParamMergeCombinations.push_back( - MergeCombination( - 4, Operand::OPM_ALL, - 0, Operand::OPM_ALL, - 0, Operand::OPM_ALL, - 0, Operand::OPM_ALL)); - - mParamMergeCombinations.push_back( - MergeCombination( - 0, Operand::OPM_ALL, - 2, Operand::OPM_ALL, - 0, Operand::OPM_ALL, - 0, Operand::OPM_ALL)); - - mParamMergeCombinations.push_back( - MergeCombination( - 0, Operand::OPM_ALL, - 0, Operand::OPM_ALL, - 0, Operand::OPM_ALL, - 1, Operand::OPM_ALL)); -} - -//----------------------------------------------------------------------------- -ProgramProcessor::MergeParameter::MergeParameter() -{ - clear(); -} - -//----------------------------------------------------------------------------- -void ProgramProcessor::MergeParameter::addSourceParameter(ParameterPtr srcParam, Operand::OpMask mask) -{ - // Case source count exceeded maximum - if (mSrcParameterCount >= 4) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Merged parameter source parameters overflow", - "MergeParameter::addSourceParameter"); - } - - mSrcParameter[mSrcParameterCount] = srcParam; - mSrcParameterMask[mSrcParameterCount] = mask; - - if (mask == Operand::OPM_ALL) - { - mDstParameterMask[mSrcParameterCount] = mask; - - mUsedFloatCount += getParameterFloatCount(srcParam->getType()); - } - else - { - int srcParamFloatCount = Operand::getFloatCount(mask); - - mDstParameterMask[mSrcParameterCount] = Operand::OpMask(getParameterMaskByFloatCount(srcParamFloatCount) << mUsedFloatCount); - mUsedFloatCount += srcParamFloatCount; - } - - mSrcParameterCount++; - - - // Case float count exceeded maximum - if (mUsedFloatCount > 4) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Merged parameter floats overflow", - "MergeParameter::addSourceParameter"); - } - -} - -//----------------------------------------------------------------------------- -int ProgramProcessor::MergeParameter::getUsedFloatCount() -{ - return mUsedFloatCount; -} - -//----------------------------------------------------------------------------- -static ParameterPtr createTexcoordParam(GpuConstantType type, int index) -{ - return std::make_shared(type, StringUtil::format("vsTexcoord_%d", index), - Parameter::SPS_TEXTURE_COORDINATES, index, Parameter::SPC_UNKNOWN); -} - -void ProgramProcessor::MergeParameter::createDestinationParameter(int index) -{ - GpuConstantType dstParamType = GCT_UNKNOWN; - - switch (getUsedFloatCount()) - { - case 1: - dstParamType = GCT_FLOAT1; - break; - - case 2: - dstParamType = GCT_FLOAT2; - break; - - case 3: - dstParamType = GCT_FLOAT3; - break; - - case 4: - dstParamType = GCT_FLOAT4; - break; - - } - - mDstParameter = createTexcoordParam(dstParamType, index); -} - -//----------------------------------------------------------------------------- -Ogre::RTShader::ParameterPtr ProgramProcessor::MergeParameter::getDestinationParameter(int index) -{ - if (!mDstParameter) - createDestinationParameter(index); - - return mDstParameter; -} - -//----------------------------------------------------------------------------- -void ProgramProcessor::MergeParameter::clear() -{ - mDstParameter.reset(); - for (unsigned int i=0; i < 4; ++i) - { - mSrcParameter[i].reset(); - mSrcParameterMask[i] = Operand::OPM_NONE; - mDstParameterMask[i] = Operand::OPM_NONE; - } - mSrcParameterCount = 0; - mUsedFloatCount = 0; -} - -} -} diff --git a/Components/RTShaderSystem/src/OgreShaderProgramProcessor.h b/Components/RTShaderSystem/src/OgreShaderProgramProcessor.h deleted file mode 100644 index 01ffe8f928c..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderProgramProcessor.h +++ /dev/null @@ -1,273 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderProgramProcessor_ -#define _ShaderProgramProcessor_ - -#include "OgreShaderPrerequisites.h" -#include "OgreShaderFunctionAtom.h" -#include "OgreGpuProgram.h" - -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - -/** A class that provides extra processing services on CPU based programs. -The base class perform only the generic processing. In order to provide target language specific services and -optimization one should derive from this class and register its factory via the ProgramManager instance. -*/ -class ProgramProcessor : public RTShaderSystemAlloc -{ - -// Interface. -public: - - /** Class constructor. - */ - ProgramProcessor(); - - /** Class destructor */ - virtual ~ProgramProcessor(); - - /** Called before creation of the GPU programs. - Do several preparation operation such as validation, register compaction and specific target language optimizations. - @param programSet The program set container. - Return true on success. - */ - bool preCreateGpuPrograms(ProgramSet* programSet); - - /** Called after creation of the GPU programs. - @param programSet The program set container. - Return true on success. - */ - bool postCreateGpuPrograms(ProgramSet* programSet); - -// Protected types. -protected: - - //----------------------------------------------------------------------------- - // Class that holds merge parameter information. - class MergeParameter - { - // Interface. - public: - /** Class constructor. */ - MergeParameter(); - - - /** Clear the state of this merge parameter. */ - void clear(); - - /** Add source parameter to this merged */ - void addSourceParameter(ParameterPtr srcParam, Operand::OpMask mask); - - /** Return the source parameter count. */ - size_t getSourceParameterCount() const { return mSrcParameterCount; } - - /** Return source parameter by index. */ - ParameterPtr getSourceParameter(unsigned int index) { return mSrcParameter[index]; } - - /** Return source parameter mask by index. */ - Operand::OpMask getSourceParameterMask(unsigned int index) const { return mSrcParameterMask[index]; } - - /** Return destination parameter mask by index. */ - Operand::OpMask getDestinationParameterMask(unsigned int index) const { return mDstParameterMask[index]; } - - /** Return the number of used floats. */ - int getUsedFloatCount(); - - /** Return the destination parameter. */ - ParameterPtr getDestinationParameter(int index); - - protected: - - /** Creates the destination parameter by a given class and index. */ - void createDestinationParameter(int index); - - - protected: - // Destination merged parameter. - ParameterPtr mDstParameter; - // Source parameters - 4 source at max 1,1,1,1 -> 4. - ParameterPtr mSrcParameter[4]; - // Source parameters mask. OPM_ALL means all fields used, otherwise it is split source parameter. - Operand::OpMask mSrcParameterMask[4]; - // Destination parameters mask. OPM_ALL means all fields used, otherwise it is split source parameter. - Operand::OpMask mDstParameterMask[4]; - // The actual source parameters count. - size_t mSrcParameterCount; - // The number of used floats. - int mUsedFloatCount; - }; - typedef std::vector MergeParameterList; - - - //----------------------------------------------------------------------------- - // A struct that defines merge parameters combination. - struct MergeCombination - { - // The count of each source type. I.E (1 FLOAT1, 0 FLOAT2, 1 FLOAT3, 0 FLOAT4). - size_t srcParameterTypeCount[4]; - // Source parameters mask. OPM_ALL means all fields used, otherwise it is split source parameter. - Operand::OpMask srcParameterMask[4]; - - MergeCombination( - int float1Count, Operand::OpMask float1Mask, - int float2Count, Operand::OpMask float2Mask, - int float3Count, Operand::OpMask float3Mask, - int float4Count, Operand::OpMask float4Mask) - { - srcParameterTypeCount[0] = float1Count; - srcParameterTypeCount[1] = float2Count; - srcParameterTypeCount[2] = float3Count; - srcParameterTypeCount[3] = float4Count; - srcParameterMask[0] = float1Mask; - srcParameterMask[1] = float2Mask; - srcParameterMask[2] = float3Mask; - srcParameterMask[3] = float4Mask; - - } - }; - typedef std::vector MergeCombinationList; - - //----------------------------------------------------------------------------- - typedef std::vector OperandPtrVector; - typedef std::map ParameterOperandMap; - typedef std::map LocalParameterMap; - -protected: - - /** Build parameter merging combinations. */ - void buildMergeCombinations(); - - /** Compact the vertex shader output registers. - @param vsMain The vertex shader entry function. - @param fsMain The fragment shader entry function. - Return true on success. - */ - virtual bool compactVsOutputs(Function* vsMain, Function* fsMain); - - /** Internal method that counts vertex shader texcoord output slots and output floats. - @param vsMain The vertex shader entry function. - @param outTexCoordSlots Will hold the number of used output texcoord slots. - @param outTexCoordFloats Will hold the total number of floats used by output texcoord slots. - */ - void countVsTexcoordOutputs(Function* vsMain, int& outTexCoordSlots, int& outTexCoordFloats); - - /** Internal function that builds parameters table. - @param paramList The parameter list. - @param outParamsTable Will hold the texcoord params sorted by types in each row. - */ - void buildTexcoordTable(const ShaderParameterList& paramList, ShaderParameterList outParamsTable[4]); - - - /** Merge the parameters from the given table. - @param paramsTable Source parameters table. - @param mergedParams Will hold the merged parameters list. - */ - void mergeParameters(ShaderParameterList paramsTable[4], MergeParameterList& mergedParams, ShaderParameterList& splitParams); - - - /** Internal function that creates merged parameter using pre defined combinations. - @param paramsTable Source parameters table. - @param mergedParams The merged parameters list. - */ - void mergeParametersByPredefinedCombinations(ShaderParameterList paramsTable[4], MergeParameterList& mergedParams); - - /** Internal function that creates merged parameter from given combination. - @param combination The merge combination to try. - @param paramsTable The params table sorted by types in each row. - @param mergedParameter Will hold the merged parameter. - */ - bool mergeParametersByCombination(const MergeCombination& combination, ShaderParameterList paramsTable[4], - MergeParameter* mergedParameter); - - /** Merge reminders parameters that could not be merged into one slot using the predefined combinations. - @param paramsTable The params table sorted by types in each row. - @param mergedParams The merged parameters list. - @param splitParams The split parameters list. - */ - void mergeParametersReminders(ShaderParameterList paramsTable[4], MergeParameterList& mergedParams, ShaderParameterList& splitParams); - - - /** Generates local parameters for the split parameters and perform packing/unpacking operation using them. */ - void generateLocalSplitParameters(Function* func, GpuProgramType progType, MergeParameterList& mergedParams, ShaderParameterList& splitParams, LocalParameterMap& localParamsMap); - - /** Rebuild the given parameters list using the merged parameters. - */ - void rebuildParameterList(Function* func, int paramsUsage, MergeParameterList& mergedParams); - - /** Rebuild function invocations by replacing references to old source parameters with the matching merged parameters components. */ - void rebuildFunctionInvocations(const FunctionAtomInstanceList& funcAtomList, MergeParameterList& mergedParams, LocalParameterMap& localParamsMap); - - /** Builds a map between parameter and all the references to it. */ - void buildParameterReferenceMap(const FunctionAtomInstanceList& funcAtomList, ParameterOperandMap& paramsRefMap); - - /** Replace references to old parameters with the new merged parameters. */ - void replaceParametersReferences(MergeParameterList& mergedParams, ParameterOperandMap& paramsRefMap); - - /** Replace references to old parameters that have been split with the new local parameters that represents them. */ - void replaceSplitParametersReferences(LocalParameterMap& localParamsMap, ParameterOperandMap& paramsRefMap); - - /** Return number of floats needed by the given type. */ - static int getParameterFloatCount(GpuConstantType type); - - /** Return the parameter mask of by the given parameter type (I.E: X|Y for FLOAT2 etc..) */ - static Operand::OpMask getParameterMaskByType(GpuConstantType type); - - /** Return the parameter mask of by the float count type (I.E: X|Y for 2 etc..) */ - static Operand::OpMask getParameterMaskByFloatCount(int floatCount); - - /** Bind the auto parameters for a given CPU and GPU program set. */ - void bindAutoParameters(Program* pCpuProgram, GpuProgramPtr pGpuProgram); - - void bindTextureSamplers(Program* pCpuProgram, GpuProgramPtr pGpuProgram); -protected: - // Merging combinations defs. - MergeCombinationList mParamMergeCombinations; - // Maximum texcoord slots. - int mMaxTexCoordSlots; - // Maximum texcoord floats count. - int mMaxTexCoordFloats; - std::map mFunctionMap; // Map between function signatures and source code - -}; - - -/** @} */ -/** @} */ - -} -} - -#endif - diff --git a/Components/RTShaderSystem/src/OgreShaderProgramSet.cpp b/Components/RTShaderSystem/src/OgreShaderProgramSet.cpp deleted file mode 100644 index a5ac669d3bb..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderProgramSet.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreShaderPrecompiledHeaders.h" - -namespace Ogre { -namespace RTShader { - -//----------------------------------------------------------------------------- -ProgramSet::ProgramSet() {} - -//----------------------------------------------------------------------------- -ProgramSet::~ProgramSet() {} - -//----------------------------------------------------------------------------- -void ProgramSet::setCpuProgram(std::unique_ptr&& program) -{ - switch(program->getType()) - { - case GPT_VERTEX_PROGRAM: - mVSCpuProgram = std::move(program); - break; - case GPT_FRAGMENT_PROGRAM: - mPSCpuProgram = std::move(program); - break; - default: - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "", ""); - break; - } -} - -//----------------------------------------------------------------------------- -Program* ProgramSet::getCpuProgram(GpuProgramType type) const -{ - switch(type) - { - case GPT_VERTEX_PROGRAM: - return mVSCpuProgram.get(); - case GPT_FRAGMENT_PROGRAM: - return mPSCpuProgram.get(); - default: - return NULL; - } -} -//----------------------------------------------------------------------------- -void ProgramSet::setGpuProgram(const GpuProgramPtr& program) -{ - switch(program->getType()) - { - case GPT_VERTEX_PROGRAM: - mVSGpuProgram = program; - break; - case GPT_FRAGMENT_PROGRAM: - mPSGpuProgram = program; - break; - default: - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "", ""); - break; - } -} - -//----------------------------------------------------------------------------- -const GpuProgramPtr& ProgramSet::getGpuProgram(GpuProgramType type) const -{ - switch(type) - { - case GPT_VERTEX_PROGRAM: - return mVSGpuProgram; - break; - case GPT_FRAGMENT_PROGRAM: - return mPSGpuProgram; - break; - default: - break; - } - - static GpuProgramPtr nullPtr; - return nullPtr; -} - -} -} diff --git a/Components/RTShaderSystem/src/OgreShaderProgramWriter.cpp b/Components/RTShaderSystem/src/OgreShaderProgramWriter.cpp deleted file mode 100644 index 03e452df9d5..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderProgramWriter.cpp +++ /dev/null @@ -1,183 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderPrecompiledHeaders.h" - -namespace Ogre { -namespace RTShader { - -//----------------------------------------------------------------------- -void ProgramWriter::writeProgramTitle(std::ostream& os, Program* program) -{ - os << "//-----------------------------------------------------------------------------" << std::endl; - os << "// Program Type: " << to_string(program->getType()) << std::endl; - os << "// Language: " << getTargetLanguage() << std::endl; - os << "// Created by Ogre RT Shader Generator. All rights reserved." << std::endl; - os << "//-----------------------------------------------------------------------------" << std::endl; -} - -//----------------------------------------------------------------------- -void ProgramWriter::writeUniformParametersTitle(std::ostream& os, Program* program) -{ - os << "//-----------------------------------------------------------------------------" << std::endl; - os << "// GLOBAL PARAMETERS" << std::endl; - os << "//-----------------------------------------------------------------------------" << std::endl; -} -//----------------------------------------------------------------------- -void ProgramWriter::writeFunctionTitle(std::ostream& os, Function* function) -{ - os << "//-----------------------------------------------------------------------------" << std::endl; - os << "// MAIN" << std::endl; - os << "//-----------------------------------------------------------------------------" << std::endl; -} - -ProgramWriter::ProgramWriter() -{ - mParamSemanticMap[Parameter::SPS_POSITION] = "POSITION"; - mParamSemanticMap[Parameter::SPS_BLEND_WEIGHTS] = "BLENDWEIGHT"; - mParamSemanticMap[Parameter::SPS_BLEND_INDICES] = "BLENDINDICES"; - mParamSemanticMap[Parameter::SPS_NORMAL] = "NORMAL"; - mParamSemanticMap[Parameter::SPS_COLOR] = "COLOR"; - mParamSemanticMap[Parameter::SPS_TEXTURE_COORDINATES] = "TEXCOORD"; - mParamSemanticMap[Parameter::SPS_BINORMAL] = "BINORMAL"; - mParamSemanticMap[Parameter::SPS_TANGENT] = "TANGENT"; -} - -ProgramWriter::~ProgramWriter() {} - -void ProgramWriter::writeParameter(std::ostream& os, const ParameterPtr& parameter) -{ - if (!parameter->getStructType().empty()) - { - os << parameter->getStructType() << '\t' << parameter->getName(); - return; - } - - os << mGpuConstTypeMap[parameter->getType()] << '\t' << parameter->getName(); - if (parameter->isArray()) - os << '[' << parameter->getSize() << ']'; -} - -void ProgramWriter::writeSamplerParameter(std::ostream& os, const UniformParameterPtr& parameter) -{ - if (parameter->getType() == GCT_SAMPLER_EXTERNAL_OES) - { - os << "uniform\t"; - writeParameter(os, parameter); - return; - } - - switch(parameter->getType()) - { - case GCT_SAMPLER1D: - os << "SAMPLER1D("; - break; - case GCT_SAMPLER2D: - os << "SAMPLER2D("; - break; - case GCT_SAMPLER3D: - os << "SAMPLER3D("; - break; - case GCT_SAMPLERCUBE: - os << "SAMPLERCUBE("; - break; - case GCT_SAMPLER2DSHADOW: - os << "SAMPLER2DSHADOW("; - break; - case GCT_SAMPLER2DARRAY: - os << "SAMPLER2DARRAY("; - break; - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "unsupported sampler type"); - } - os << parameter->getName() << ", " << parameter->getIndex() << ")"; -} - -void ProgramWriter::writeParameterSemantic(std::ostream& os, const ParameterPtr& parameter) -{ - OgreAssertDbg(parameter->getSemantic() != Parameter::SPS_UNKNOWN, "invalid semantic"); - os << mParamSemanticMap[parameter->getSemantic()]; - - if (parameter->getSemantic() == Parameter::SPS_TEXTURE_COORDINATES || - (parameter->getSemantic() == Parameter::SPS_COLOR && parameter->getIndex() > 0)) - { - os << parameter->getIndex(); - } -} - -void ProgramWriter::redirectGlobalWrites(std::ostream& os, FunctionAtom* func, const ShaderParameterList& inputs, - const UniformParameterList& uniforms) -{ - for (auto& operand : func->getOperandList()) - { - auto opSemantic = operand.getSemantic(); - - if (opSemantic != Operand::OPS_OUT && opSemantic != Operand::OPS_INOUT) - continue; - - const ParameterPtr& param = operand.getParameter(); - - // Check if we write to an input variable because they are only readable - // Well, actually "attribute" were writable in GLSL < 120, but we dont care here - bool doLocalRename = std::find(inputs.begin(), inputs.end(), param) != inputs.end(); - - // If its not a varying param check if a uniform is written - if (!doLocalRename) - { - doLocalRename = std::find(uniforms.begin(), uniforms.end(), param) != uniforms.end(); - } - - // now we check if we already declared a redirector var - if (doLocalRename && mLocalRenames.find(param->getName()) == mLocalRenames.end()) - { - // Declare the copy variable and assign the original - String newVar = "local_" + param->getName(); - os << "\t" << mGpuConstTypeMap[param->getType()] << " " << newVar << " = " << param->getName() << ";" - << std::endl; - - // From now on we replace it automatic - param->_rename(newVar, true); - mLocalRenames.insert(newVar); - } - } -} - -//----------------------------------------------------------------------- -void ProgramWriter::writeProgramDependencies(std::ostream& os, Program* program) -{ - os << "//-----------------------------------------------------------------------------" << std::endl; - os << "// PROGRAM DEPENDENCIES" << std::endl; - os << "//-----------------------------------------------------------------------------" << std::endl; - os << "#include " << std::endl; - - for (unsigned int i=0; i < program->getDependencyCount(); ++i) - { - os << "#include \"" << program->getDependency(i) << ".glsl\"" << std::endl; - } -} - -} -} diff --git a/Components/RTShaderSystem/src/OgreShaderProgramWriterManager.cpp b/Components/RTShaderSystem/src/OgreShaderProgramWriterManager.cpp deleted file mode 100644 index 45d2c6e058d..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderProgramWriterManager.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreShaderPrecompiledHeaders.h" - -namespace Ogre { - -//----------------------------------------------------------------------- -template<> -RTShader::ProgramWriterManager* Singleton::msSingleton = 0; - -namespace RTShader { -//----------------------------------------------------------------------- -ProgramWriterManager* ProgramWriterManager::getSingletonPtr(void) -{ - return msSingleton; -} -//----------------------------------------------------------------------- -ProgramWriterManager& ProgramWriterManager::getSingleton(void) -{ - assert( msSingleton ); - return ( *msSingleton ); -} -//----------------------------------------------------------------------- -ProgramWriterManager::ProgramWriterManager() -{ - // Add standard shader writer factories -#if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID - addProgramWriter("glsl", new GLSLProgramWriter()); - addProgramWriter("hlsl", new CGProgramWriter()); -#endif - addProgramWriter("glslang", new GLSLProgramWriter()); - addProgramWriter("glsles", new GLSLESProgramWriter()); -} -//----------------------------------------------------------------------- -ProgramWriterManager::~ProgramWriterManager() -{ - for(auto& it : mProgramWriters) - { - delete it.second; - } -} -//----------------------------------------------------------------------- -void ProgramWriterManager::addProgramWriter(const String& lang, ProgramWriter* writer) -{ - mProgramWriters[lang] = writer; -} -//----------------------------------------------------------------------- -bool ProgramWriterManager::isLanguageSupported(const String& lang) -{ - return mProgramWriters.find(lang) != mProgramWriters.end(); -} -} -} diff --git a/Components/RTShaderSystem/src/OgreShaderRenderState.cpp b/Components/RTShaderSystem/src/OgreShaderRenderState.cpp deleted file mode 100644 index a280e6a52d0..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderRenderState.cpp +++ /dev/null @@ -1,359 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderPrecompiledHeaders.h" - -namespace Ogre { -namespace RTShader { - -const char* TargetRenderState::UserKey = "TargetRenderState"; - -//----------------------------------------------------------------------- -RenderState::RenderState() -{ - mLightCountAutoUpdate = true; - mHaveAreaLights = false; - mLightCount = 0; -} - -//----------------------------------------------------------------------- -RenderState::~RenderState() -{ - clear(); -} - -void RenderState::resetToBuiltinSubRenderStates() -{ -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS - clear(); - addTemplateSubRenderStates( - {SRS_TRANSFORM, SRS_VERTEX_COLOUR, SRS_PER_PIXEL_LIGHTING, SRS_TEXTURING, SRS_FOG, SRS_ALPHA_TEST}); -#endif -} - -//----------------------------------------------------------------------- -void RenderState::clear() -{ - for (auto & it : mSubRenderStateList) - { - ShaderGenerator::getSingleton().destroySubRenderState(it); - } - mSubRenderStateList.clear(); -} - -void RenderState::addTemplateSubRenderStates(const StringVector& srsTypes) -{ - for (auto& srsType : srsTypes) - { - addTemplateSubRenderState(ShaderGenerator::getSingleton().createSubRenderState(srsType)); - } -} - -//----------------------------------------------------------------------- -void RenderState::addTemplateSubRenderState(SubRenderState* subRenderState) -{ - bool addSubRenderState = true; - - // Go over the current sub render state. - for (auto & it : mSubRenderStateList) - { - // Case the same instance already exists -> do not add to list. - if (it == subRenderState) - { - addSubRenderState = false; - break; - } - - // Case it is different sub render state instance with the same type, use the new sub render state - // instead of the previous sub render state. This scenario is usually caused by material inheritance, so we use the derived material sub render state - // and destroy the base sub render state. - else if (it->getType() == subRenderState->getType()) - { - removeSubRenderState(it); - break; - } - } - - // Add only if this sub render state instance is not on the list. - if (addSubRenderState) - { - mSubRenderStateList.push_back(subRenderState); - } -} - -//----------------------------------------------------------------------- -void RenderState::removeSubRenderState(SubRenderState* subRenderState) -{ - auto it = std::find(mSubRenderStateList.begin(), mSubRenderStateList.end(), subRenderState); - if(it == mSubRenderStateList.end()) return; - - mSubRenderStateList.erase(it); - ShaderGenerator::getSingleton().destroySubRenderState(subRenderState); -} - -SubRenderState* RenderState::getSubRenderState(const String& type) const -{ - for (auto srs : mSubRenderStateList) - { - if (srs->getType() == type) - return srs; - } - - return nullptr; -} - -//----------------------------------------------------------------------- -TargetRenderState::TargetRenderState() : mSubRenderStateSortValid(false), mParent(nullptr) {} - -TargetRenderState::~TargetRenderState() -{ - if(mParent) - releasePrograms(mParent); -} - -//----------------------------------------------------------------------- -void TargetRenderState::addSubRenderStateInstance(SubRenderState* subRenderState) -{ - mSubRenderStateList.push_back(subRenderState); - mSubRenderStateSortValid = false; -} - -//----------------------------------------------------------------------------- -void TargetRenderState::bindUniformParameters(Program* pCpuProgram, const GpuProgramParametersSharedPtr& passParams) -{ - // samplers are bound via registers in HLSL & Cg - bool samplersBound = ShaderGenerator::getSingleton().getTargetLanguage()[0] != 'g'; - - // Bind each uniform parameter to its GPU parameter. - for (const auto& param : pCpuProgram->getParameters()) - { - if((samplersBound && param->isSampler()) || !param->isUsed()) continue; - - param->bind(passParams); - param->setUsed(false); // reset for shader regen - } -} - -void TargetRenderState::acquirePrograms(Pass* pass) -{ - createCpuPrograms(); - ProgramManager::getSingleton().createGpuPrograms(mProgramSet.get()); - - bool hasError = false; - bool logProgramNames = !ShaderGenerator::getSingleton().getShaderCachePath().empty(); - const char* matName = pass->getParent()->getParent()->getName().c_str(); - - for(auto type : {GPT_VERTEX_PROGRAM, GPT_FRAGMENT_PROGRAM}) - { - auto prog = mProgramSet->getGpuProgram(type); - hasError = hasError || prog->hasCompileError(); - if (logProgramNames) - { - LogManager::getSingleton().logMessage(StringUtil::format( - "RTSS: using %s for Pass %d of '%s'", prog->getName().c_str(), pass->getIndex(), matName)); - } - - // Bind the created GPU programs to the target pass. - pass->setGpuProgram(type, prog); - // Bind uniform parameters to pass parameters. - bindUniformParameters(mProgramSet->getCpuProgram(type), pass->getGpuProgramParameters(type)); - } - - if (hasError) - { - LogManager::getSingleton().logError( - StringUtil::format("RTSS: failed to create GpuPrograms for Pass %d of '%s'", pass->getIndex(), matName)); - } - - mParent = pass; -} - - -void TargetRenderState::releasePrograms(Pass* pass) -{ - if(!mProgramSet) - return; - - pass->setGpuProgram(GPT_VERTEX_PROGRAM, GpuProgramPtr()); - pass->setGpuProgram(GPT_FRAGMENT_PROGRAM, GpuProgramPtr()); - - ProgramManager::getSingleton().releasePrograms(mProgramSet.get()); - - mProgramSet.reset(); -} - -/// we cannot resolve this at preAddToRenderState time as addition order is arbitrary -static void fixupFFPLighting(TargetRenderState* renderState) -{ -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS - auto ffpLighting = static_cast(renderState->getSubRenderState(SRS_PER_VERTEX_LIGHTING)); - - if (!ffpLighting) - return; - - auto ffpColour = static_cast(renderState->getSubRenderState(SRS_VERTEX_COLOUR)); - OgreAssert(ffpColour, "SRS_VERTEX_COLOUR required"); - ffpColour->addResolveStageMask(FFPColour::SF_VS_OUTPUT_DIFFUSE); - - if(ffpLighting->getSpecularEnable()) - ffpColour->addResolveStageMask(FFPColour::SF_VS_OUTPUT_SPECULAR); -#endif -} - -//----------------------------------------------------------------------- -void TargetRenderState::createCpuPrograms() -{ - sortSubRenderStates(); - - fixupFFPLighting(this); - - ProgramSet* programSet = createProgramSet(); - programSet->setCpuProgram(std::unique_ptr(new Program(GPT_VERTEX_PROGRAM))); - programSet->setCpuProgram(std::unique_ptr(new Program(GPT_FRAGMENT_PROGRAM))); - - for (auto srcSubRenderState : mSubRenderStateList) - { - if (!srcSubRenderState->createCpuSubPrograms(programSet)) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Could not generate sub render program of type: " + srcSubRenderState->getType()); - } - } -} - -//----------------------------------------------------------------------- -ProgramSet* TargetRenderState::createProgramSet() -{ - mProgramSet.reset(new ProgramSet); - - return mProgramSet.get(); -} - -//----------------------------------------------------------------------- -void TargetRenderState::updateGpuProgramsParams(Renderable* rend, const Pass* pass, const AutoParamDataSource* source, - const LightList* pLightList) -{ - for (auto curSubRenderState : mSubRenderStateList) - { - curSubRenderState->updateGpuProgramsParams(rend, pass, source, pLightList); - } -} - -void TargetRenderState::link(const StringVector& srsTypes, Pass* srcPass, Pass* dstPass) -{ - for (const auto& srsType : srsTypes) - { - auto srs = ShaderGenerator::getSingleton().createSubRenderState(srsType); - - if (srs->preAddToRenderState(this, srcPass, dstPass)) - { - addSubRenderStateInstance(srs); - } - else - { - ShaderGenerator::getSingleton().destroySubRenderState(srs); - } - } -} - -//----------------------------------------------------------------------- -void TargetRenderState::link(const RenderState& templateRS, Pass* srcPass, Pass* dstPass) -{ - for (auto srcSubRenderState : templateRS.getSubRenderStates()) - { - auto it = mSubRenderStateList.end(); - switch (srcSubRenderState->getExecutionOrder()) - { - case FFP_TRANSFORM: - case FFP_COLOUR: - case FFP_LIGHTING: - case FFP_TEXTURING: - case FFP_FOG: - // Check if this FFP stage already exists. - it = std::find_if(mSubRenderStateList.begin(), mSubRenderStateList.end(), - [srcSubRenderState](const SubRenderState* e) { - return srcSubRenderState->getExecutionOrder() == e->getExecutionOrder(); - }); - default: - break; - } - - if(it != mSubRenderStateList.end()) - { - ShaderGenerator::getSingleton().destroySubRenderState(*it); - std::swap(*it, mSubRenderStateList.back()); - mSubRenderStateList.pop_back(); - } - - // Check if this type of sub render state already exists. - it = std::find_if(mSubRenderStateList.begin(), mSubRenderStateList.end(), - [srcSubRenderState](const SubRenderState* e) { - return srcSubRenderState->getType() == e->getType(); - }); - - if(it != mSubRenderStateList.end()) - { - ShaderGenerator::getSingleton().destroySubRenderState(*it); - std::swap(*it, mSubRenderStateList.back()); - mSubRenderStateList.pop_back(); - } - - // Case custom sub render state not exits -> add it to custom list. - auto newSubRenderState = ShaderGenerator::getSingleton().createSubRenderState(srcSubRenderState->getType()); - *newSubRenderState = *srcSubRenderState; - - if (newSubRenderState->preAddToRenderState(this, srcPass, dstPass)) - { - addSubRenderStateInstance(newSubRenderState); - } - else - { - ShaderGenerator::getSingleton().destroySubRenderState(newSubRenderState); - } - } -} - -namespace { - struct CmpSubRenderStates { - bool operator()(const SubRenderState* a, const SubRenderState* b) const - { - return a->getExecutionOrder() < b->getExecutionOrder(); - } - }; -} - -//----------------------------------------------------------------------- -void TargetRenderState::sortSubRenderStates() -{ - if (mSubRenderStateSortValid == false) - { - std::sort(mSubRenderStateList.begin(), mSubRenderStateList.end(), CmpSubRenderStates()); - mSubRenderStateSortValid = true; - } -} - -} -} diff --git a/Components/RTShaderSystem/src/OgreShaderScriptTranslator.cpp b/Components/RTShaderSystem/src/OgreShaderScriptTranslator.cpp deleted file mode 100644 index 0bbc39999d8..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderScriptTranslator.cpp +++ /dev/null @@ -1,238 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderPrecompiledHeaders.h" - -namespace Ogre { -namespace RTShader { - -//----------------------------------------------------------------------------- -SGScriptTranslator::SGScriptTranslator() : - mGeneratedRenderState(NULL) -{ -} - -//----------------------------------------------------------------------------- -void SGScriptTranslator::translate(ScriptCompiler* compiler, const AbstractNodePtr &node) -{ - ObjectAbstractNode* obj = static_cast(node.get()); - ObjectAbstractNode* parent = static_cast(obj->parent); - - // Translate section within a pass context. - if (parent->id == ID_PASS) - { - translatePass(compiler, node); - } - if (parent->id == ID_TEXTURE_UNIT) - { - translateTextureUnit(compiler, node); - } -} - -//----------------------------------------------------------------------------- -SubRenderState* SGScriptTranslator::getGeneratedSubRenderState(const String& typeName) -{ - //check if we are in the middle of parsing - if (mGeneratedRenderState) - return mGeneratedRenderState->getSubRenderState(typeName); - return NULL; -} - -//----------------------------------------------------------------------------- -/* -note: we can know the texture unit index by getting parent then finding it in the list of children -*/ -void SGScriptTranslator::translateTextureUnit(ScriptCompiler* compiler, const AbstractNodePtr &node) -{ - ObjectAbstractNode *obj = static_cast(node.get()); - TextureUnitState* texState = any_cast(obj->parent->context); - Pass* pass = texState->getParent(); - Technique* technique = pass->getParent(); - Material* material = technique->getParent(); - ShaderGenerator* shaderGenerator = ShaderGenerator::getSingletonPtr(); - String dstTechniqueSchemeName = obj->name; - bool techniqueCreated; - - // Make sure the scheme name is valid - use default if none exists. - if (dstTechniqueSchemeName.empty()) - dstTechniqueSchemeName = MSN_SHADERGEN; - - - //check if technique already created - techniqueCreated = shaderGenerator->hasShaderBasedTechnique(*material, - technique->getSchemeName(), - dstTechniqueSchemeName); - - if (techniqueCreated == false) - { - // Create the shader based technique. - techniqueCreated = shaderGenerator->createShaderBasedTechnique(technique, - dstTechniqueSchemeName, - shaderGenerator->getCreateShaderOverProgrammablePass()); - } - - - - // Case technique successfully created. - if (techniqueCreated) - { - //Attempt to get the render state which might have been created by the pass parsing - mGeneratedRenderState = - shaderGenerator->getRenderState(dstTechniqueSchemeName, *material, pass->getIndex()); - - // Go over all the render state properties. - for(auto & i : obj->children) - { - if(i->type == ANT_PROPERTY) - { - PropertyAbstractNode *prop = static_cast(i.get()); - SubRenderState* subRenderState = ShaderGenerator::getSingleton().createSubRenderState(compiler, prop, texState, this); - - if (subRenderState) - { - addSubRenderState(subRenderState, dstTechniqueSchemeName, material->getName(), - material->getGroup(), pass->getIndex()); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, prop->name); - } - } - else - { - processNode(compiler, i); - } - } - - mGeneratedRenderState = NULL; - } -} - - -//----------------------------------------------------------------------------- -void SGScriptTranslator::translatePass(ScriptCompiler* compiler, const AbstractNodePtr &node) -{ - ObjectAbstractNode *obj = static_cast(node.get()); - Pass* pass = any_cast(obj->parent->context); - Technique* technique = pass->getParent(); - Material* material = technique->getParent(); - ShaderGenerator* shaderGenerator = ShaderGenerator::getSingletonPtr(); - String dstTechniqueSchemeName = obj->name; - bool techniqueCreated; - - // Make sure the scheme name is valid - use default if none exists. - if (dstTechniqueSchemeName.empty()) - dstTechniqueSchemeName = MSN_SHADERGEN; - - - // Create the shader based technique. - techniqueCreated = shaderGenerator->createShaderBasedTechnique(technique, - dstTechniqueSchemeName, - shaderGenerator->getCreateShaderOverProgrammablePass()); - - - // Case technique successfully created. - if (techniqueCreated) - { - // Go over all the render state properties. - for(auto & i : obj->children) - { - if(i->type == ANT_PROPERTY) - { - PropertyAbstractNode *prop = static_cast(i.get()); - - // Handle light count property. - if (prop->name == "light_count") - { - if (prop->values.size() == 3 || prop->values.size() == 1) - { - std::vector lightCount; - getVector(prop->values.begin(), prop->values.end(), lightCount, prop->values.size()); - int total = 0; - for(auto & j : lightCount) - total += j; - shaderGenerator->createScheme(dstTechniqueSchemeName); - auto renderState = - shaderGenerator->getRenderState(dstTechniqueSchemeName, *material, pass->getIndex()); - - renderState->setLightCount(total); - renderState->setLightCountAutoUpdate(false); - - if(prop->values.size() == 3) - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, prop->file, prop->line, "light_count only takes 1 parameter now"); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - } - - // Handle the rest of the custom properties. - else - { - SubRenderState* subRenderState = ShaderGenerator::getSingleton().createSubRenderState(compiler, prop, pass, this); - if (subRenderState) - { - addSubRenderState(subRenderState, dstTechniqueSchemeName, material->getName(), material->getGroup(), pass->getIndex()); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, prop->name); - } - } - } - else - { - processNode(compiler, i); - } - } - - mGeneratedRenderState = NULL; - } - -} - -//----------------------------------------------------------------------------- -void SGScriptTranslator::addSubRenderState(SubRenderState* newSubRenderState, - const String& dstTechniqueSchemeName, const String& materialName, const String& groupName, unsigned short passIndex) -{ - assert(newSubRenderState); - - //check if a different sub render state of the same type already exists - ShaderGenerator* shaderGenerator = ShaderGenerator::getSingletonPtr(); - - //create a new scheme if needed - shaderGenerator->createScheme(dstTechniqueSchemeName); - - //update the active render state - mGeneratedRenderState = shaderGenerator->getRenderState(dstTechniqueSchemeName, materialName, groupName, passIndex); - - //add the new sub render state - mGeneratedRenderState->addTemplateSubRenderState(newSubRenderState); -} - -} -} diff --git a/Components/RTShaderSystem/src/OgreShaderSubRenderState.cpp b/Components/RTShaderSystem/src/OgreShaderSubRenderState.cpp deleted file mode 100644 index a1266a9a39e..00000000000 --- a/Components/RTShaderSystem/src/OgreShaderSubRenderState.cpp +++ /dev/null @@ -1,191 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreShaderPrecompiledHeaders.h" - -namespace Ogre { -namespace RTShader { - - - -//----------------------------------------------------------------------- -SubRenderState::SubRenderState() -{ - -} - -//----------------------------------------------------------------------- -SubRenderState::~SubRenderState() -{ - if (mOtherAccessor) - { - mOtherAccessor->removeSubRenderStateInstance(this); - } -} - -//----------------------------------------------------------------------- -SubRenderStateFactory::~SubRenderStateFactory() -{ - OgreAssert(mSubRenderStateList.empty(), "Sub render states still exists"); -} - -//----------------------------------------------------------------------- -SubRenderState* SubRenderStateFactory::createInstance() -{ - SubRenderState* subRenderState = createInstanceImpl(); - - mSubRenderStateList.insert(subRenderState); - - return subRenderState; -} - -//----------------------------------------------------------------------- -SubRenderState* SubRenderStateFactory::createOrRetrieveInstance(SGScriptTranslator* translator) -{ - //check if we already create a SRS - SubRenderState* subRenderState = translator->getGeneratedSubRenderState(getType()); - if (subRenderState == NULL) - { - //create a new sub render state - subRenderState = SubRenderStateFactory::createInstance(); - } - return subRenderState; -} - -//----------------------------------------------------------------------- -void SubRenderStateFactory::destroyInstance(SubRenderState* subRenderState) -{ - SubRenderStateSetIterator it = mSubRenderStateList.find(subRenderState); - - if (it != mSubRenderStateList.end()) - { - OGRE_DELETE *it; - mSubRenderStateList.erase(it); - } -} - -//----------------------------------------------------------------------- -void SubRenderStateFactory::destroyAllInstances() -{ - SubRenderStateSetIterator it; - - for (it = mSubRenderStateList.begin(); it != mSubRenderStateList.end(); ++it) - { - OGRE_DELETE *it; - } - mSubRenderStateList.clear(); - -} - -//----------------------------------------------------------------------- -SubRenderState& SubRenderState::operator=(const SubRenderState& rhs) -{ - if (getType() != rhs.getType()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Can not copy sub render states of different types !!", - "SubRenderState::operator="); - } - - copyFrom(rhs); - - SubRenderStateAccessorPtr rhsAccessor = rhs.getAccessor(); - - rhsAccessor->addSubRenderStateInstance(this); - mOtherAccessor = rhsAccessor; - - return *this; -} - -//----------------------------------------------------------------------- -bool SubRenderState::createCpuSubPrograms(ProgramSet* programSet) -{ - bool result; - - // Resolve parameters. - result = resolveParameters(programSet); - if (false == result) - return false; - - // Resolve dependencies. - result = resolveDependencies(programSet); - if (false == result) - return false; - - // Add function invocations. - result = addFunctionInvocations(programSet); - if (false == result) - return false; - - return true; -} - -//----------------------------------------------------------------------- -bool SubRenderState::resolveParameters(ProgramSet* programSet) -{ - return true; -} - -//----------------------------------------------------------------------- -bool SubRenderState::resolveDependencies(ProgramSet* programSet) -{ - return true; -} - -//----------------------------------------------------------------------- -bool SubRenderState::addFunctionInvocations( ProgramSet* programSet ) -{ - return true; -} - -//----------------------------------------------------------------------- -SubRenderStateAccessorPtr SubRenderState::getAccessor() -{ - if (!mThisAccessor) - { - mThisAccessor.reset(OGRE_NEW SubRenderStateAccessor(this)); - } - - return mThisAccessor; -} - -//----------------------------------------------------------------------- -SubRenderStateAccessorPtr SubRenderState::getAccessor() const -{ - if (!mThisAccessor) - { - mThisAccessor.reset(OGRE_NEW SubRenderStateAccessor(this)); - } - - return mThisAccessor; -} - - - -} -} - diff --git a/Components/Terrain/CMakeLists.txt b/Components/Terrain/CMakeLists.txt deleted file mode 100644 index b83ddf25e87..00000000000 --- a/Components/Terrain/CMakeLists.txt +++ /dev/null @@ -1,63 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -############################################################ -# Terrain optional component -############################################################ - -# define header and source files for the library -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") - -list(REMOVE_ITEM HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/OgreTerrainPagedWorldSection.h" - "${CMAKE_CURRENT_SOURCE_DIR}/include/OgreTerrainPaging.h" -) -list(REMOVE_ITEM SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreTerrainPagedWorldSection.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreTerrainPaging.cpp" -) - -# Add needed definitions -add_definitions(-DOGRE_TERRAIN_EXPORTS ${OGRE_VISIBILITY_FLAGS}) - -if (OGRE_BUILD_COMPONENT_PAGING) - list(APPEND HEADER_FILES - include/OgreTerrainPaging.h - include/OgreTerrainPagedWorldSection.h - ) - list(APPEND SOURCE_FILES - src/OgreTerrainPaging.cpp - src/OgreTerrainPagedWorldSection.cpp - ) -endif () - -# setup target -add_library(OgreTerrain ${OGRE_COMP_LIB_TYPE} ${HEADER_FILES} ${SOURCE_FILES} ${PLATFORM_HEADER_FILES} ${PLATFORM_SOURCE_FILES}) -set_target_properties(OgreTerrain PROPERTIES VERSION ${OGRE_SOVERSION} SOVERSION ${OGRE_SOVERSION}) -target_link_libraries(OgreTerrain PUBLIC OgreMain OgreRTShaderSystem) - -target_include_directories(OgreTerrain PUBLIC - "$" - $ - PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src") - -if (OGRE_BUILD_COMPONENT_PAGING) - target_link_libraries(OgreTerrain PUBLIC OgrePaging) -endif () - - -# install -ogre_config_framework(OgreTerrain) -ogre_config_component(OgreTerrain) - -install(FILES ${HEADER_FILES} - DESTINATION include/OGRE/Terrain -) -install(DIRECTORY "${PROJECT_SOURCE_DIR}/Media/Terrain" - DESTINATION "${OGRE_MEDIA_PATH}/" -) \ No newline at end of file diff --git a/Components/Terrain/include/OgreTerrain.h b/Components/Terrain/include/OgreTerrain.h deleted file mode 100644 index 5ae14098795..00000000000 --- a/Components/Terrain/include/OgreTerrain.h +++ /dev/null @@ -1,2056 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_Terrain_H__ -#define __Ogre_Terrain_H__ - -#include "OgreTerrainPrerequisites.h" -#include "OgreCommon.h" -#include "OgreVector.h" -#include "OgreAxisAlignedBox.h" -#include "OgreSceneManager.h" -#include "OgreTerrainMaterialGenerator.h" -#include "OgreTerrainLayerBlendMap.h" -#include "OgreWorkQueue.h" -#include "OgreTerrainLodManager.h" - -namespace Ogre -{ - /** \addtogroup Optional - * @{ - */ - /** \defgroup Terrain Terrain - * Editable %Terrain System with LOD @cite de2000fast, serialization and \ref Paging support - * @{ - */ - - /** The main containing class for a chunk of terrain. - @par - Terrain can be edited and stored. - The data format for this in a file is:
- TerrainData (Identifier 'TERR')\n - [Version 1] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
Terrain orientationuint8The orientation of the terrain; XZ = 0, XY = 1, YZ = 2
Terrain sizeuint16The number of vertices along one side of the terrain
Terrain world sizeRealThe world size of one side of the terrain
Max batch sizeuint16The maximum batch size in vertices along one side
Min batch sizeuint16The minimum batch size in vertices along one side
PositionVector3The location of the centre of the terrain
Height datafloat[size*size]List of floating point heights
LayerDeclarationLayerDeclaration*The layer declaration for this terrain (see below)
Layer countuint8The number of layers in this terrain
LayerInstance listLayerInstance*A number of LayerInstance definitions based on layer count (see below)
Layer blend map sizeuint16The size of the layer blend maps as stored in this file
Packed blend texture datauint8*layerCount-1 sets of blend texture data interleaved as RGBA
Optional derived map dataTerrainDerivedMap list0 or more sets of map data derived from the original terrain
Delta datafloat[size*size]At each vertex, delta information for the LOD at which this vertex disappears
Quadtree delta datafloat[quadtrees*lods]At each quadtree node, for each lod a record of the max delta value in the region
- TerrainLayerDeclaration (Identifier 'TDCL')\n - [Version 1] - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
TerrainLayerSampler Countuint8Number of samplers in this declaration
TerrainLayerSampler ListTerrainLayerSampler*List of TerrainLayerSampler structures
Sampler Element Countuint8Number of sampler elements in this declaration
TerrainLayerSamplerElement ListTerrainLayerSamplerElement*List of TerrainLayerSamplerElement structures
- TerrainLayerSampler (Identifier 'TSAM')\n - [Version 1] - - - - - - - - - - - - - - - - -
NameTypeDescription
AliasStringAlias name of this sampler
Formatuint8Desired pixel format
- TerrainLayerSamplerElement (Identifier 'TSEL')\n - [Version 1] - - - - - - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
Sourceuint8Sampler source index
Semanticuint8Semantic interpretation of this element
Element startuint8Start of this element in the sampler
Element countuint8Number of elements in the sampler used by this entry
- LayerInstance (Identifier 'TLIN')\n - [Version 1] - - - - - - - - - - - - - - - - -
NameTypeDescription
World sizeRealThe world size of this layer (determines UV scaling)
Texture listString*List of texture names corresponding to the number of samplers in the layer declaration
- TerrainDerivedData (Identifier 'TDDA')\n - [Version 1] - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
Derived data type nameStringName of the derived data type ('normalmap', 'lightmap', 'colourmap', 'compositemap')
Sizeuint16Size of the data along one edge
Datavaries based on typeThe data
- */ - class _OgreTerrainExport Terrain : public SceneManager::Listener - { - public: - friend class TerrainLodManager; - - /** Constructor. - @param sm The SceneManager to use. - */ - Terrain(SceneManager* sm); - virtual ~Terrain(); - - static const uint32 TERRAIN_CHUNK_ID; - static const uint16 TERRAIN_CHUNK_VERSION; - static const uint16 TERRAIN_MAX_BATCH_SIZE; - - static const uint32 TERRAINLAYERDECLARATION_CHUNK_ID; - static const uint16 TERRAINLAYERDECLARATION_CHUNK_VERSION; - static const uint32 TERRAINLAYERSAMPLER_CHUNK_ID; - static const uint16 TERRAINLAYERSAMPLER_CHUNK_VERSION; - static const uint32 TERRAINLAYERSAMPLERELEMENT_CHUNK_ID; - static const uint16 TERRAINLAYERSAMPLERELEMENT_CHUNK_VERSION; - static const uint32 TERRAINLAYERINSTANCE_CHUNK_ID; - static const uint16 TERRAINLAYERINSTANCE_CHUNK_VERSION; - static const uint32 TERRAINDERIVEDDATA_CHUNK_ID; - static const uint16 TERRAINDERIVEDDATA_CHUNK_VERSION; - static const uint32 TERRAINGENERALINFO_CHUNK_ID; - static const uint16 TERRAINGENERALINFO_CHUNK_VERSION; - - static const uint32 LOD_MORPH_CUSTOM_PARAM; - - typedef std::vector RealVector; - - /** An instance of a layer, with specific texture names - */ - struct _OgreTerrainExport LayerInstance - { - /// The world size of the texture to be applied in this layer - Real worldSize; - /// List of texture names to import; must match with TerrainLayerDeclaration - StringVector textureNames; - - LayerInstance() - : worldSize(100) {} - }; - typedef std::vector LayerInstanceList; - - /// The alignment of the terrain - enum Alignment - { - /// Terrain is in the X/Z plane - ALIGN_X_Z = 0, - /// Terrain is in the X/Y plane - ALIGN_X_Y = 1, - /// Terrain is in the Y/Z plane - ALIGN_Y_Z = 2 - }; - - /** Structure encapsulating import data that you may use to bootstrap - the terrain without loading from a native data stream. - */ - struct ImportData - { - /// The alignment of the terrain - Alignment terrainAlign; - /// Terrain size (along one edge) in vertices; must be 2^n+1 - uint16 terrainSize; - /** Maximum batch size (along one edge) in vertices; must be 2^n+1 and <= 65 - - The terrain will be divided into hierarchical tiles, and this is the maximum - size of one tile in vertices (at any LOD). - */ - uint16 maxBatchSize; - /** Minimum batch size (along one edge) in vertices; must be 2^n+1. - - The terrain will be divided into tiles, and this is the minimum - size of one tile in vertices (at any LOD). Adjacent tiles will be - collected together into one batch to drop LOD levels once they are individually at this minimum, - so setting this value higher means greater batching at the expense - of making adjacent tiles use a common LOD. - Once the entire terrain is collected together into one batch this - effectively sets the minimum LOD. - */ - uint16 minBatchSize; - - /** Position of the terrain. - - Represents the position of the centre of the terrain. - */ - Vector3 pos; - - /** The world size of the terrain. */ - Real worldSize; - - /** Optional heightmap providing the initial heights for the terrain. - - If supplied, should ideally be terrainSize * terrainSize, but if - it isn't it will be resized. - */ - Image* inputImage; - - /** Optional list of terrainSize * terrainSize floats defining the terrain. - The list of floats wil be interpreted such that the first row - in the array equates to the bottom row of vertices. - */ - float* inputFloat; - - /** If neither inputImage or inputFloat are supplied, the constant - height at which the initial terrain should be created (flat). - */ - float constantHeight; - - /** Whether this structure should 'own' the input data (inputImage and - inputFloat), and therefore delete it on destruction. - The default is false so you have to manage your own memory. If you - set it to true, then you must have allocated the memory through - OGRE_NEW (for Image) and OGRE_ALLOC_T (for inputFloat), the latter - with the category MEMCATEGORY_GEOMETRY. - */ - bool deleteInputData; - - /// How to scale the input values provided (if any) - Real inputScale; - /// How to bias the input values provided (if any) - Real inputBias; - - /** Definition of the contents of each layer (required). - Most likely, you will pull a declaration from a TerrainMaterialGenerator - of your choice. - */ - TerrainLayerDeclaration layerDeclaration; - /** List of layer structures, one for each layer required. - Can be empty or underfilled if required, list will be padded with - blank textures. - */ - LayerInstanceList layerList; - - ImportData() - : terrainAlign(ALIGN_X_Z) - , terrainSize(1025) - , maxBatchSize(65) - , minBatchSize(17) - , pos(Vector3::ZERO) - , worldSize(1000) - , inputImage(0) - , inputFloat(0) - , constantHeight(0) - , deleteInputData(false) - , inputScale(1.0) - , inputBias(0.0) - { - - } - - ImportData(const ImportData& rhs) - : terrainAlign(ALIGN_X_Z) - , terrainSize(1025) - , maxBatchSize(65) - , minBatchSize(17) - , pos(Vector3::ZERO) - , worldSize(1000) - , inputImage(0) - , inputFloat(0) - , constantHeight(0) - , deleteInputData(false) - , inputScale(1.0) - , inputBias(0.0) - { - *this = rhs; - } - - ImportData& operator=(const ImportData& rhs) - { - // basic copy - terrainAlign = rhs.terrainAlign; - terrainSize = rhs.terrainSize; - maxBatchSize = rhs.maxBatchSize; - minBatchSize = rhs.minBatchSize; - pos = rhs.pos; - worldSize = rhs.worldSize; - constantHeight = rhs.constantHeight; - deleteInputData = rhs.deleteInputData; - inputScale = rhs.inputScale; - inputBias = rhs.inputBias; - layerDeclaration = rhs.layerDeclaration; - layerList = rhs.layerList; - - // By-value copies in ownership cases - if (rhs.deleteInputData) - { - if (rhs.inputImage) - inputImage = OGRE_NEW Image(*rhs.inputImage); - else - inputImage = 0; - - if (rhs.inputFloat) - { - inputFloat = OGRE_ALLOC_T(float, terrainSize*terrainSize, MEMCATEGORY_GEOMETRY); - memcpy(inputFloat, rhs.inputFloat, sizeof(float) * terrainSize*terrainSize); - } - else - inputFloat = 0; - } - else - { - // re-use pointers - inputImage = rhs.inputImage; - inputFloat = rhs.inputFloat; - } - return *this; - } - - /// Delete any input data if this struct is set to do so - void destroy() - { - if (deleteInputData) - { - OGRE_DELETE inputImage; - OGRE_FREE(inputFloat, MEMCATEGORY_GEOMETRY); - inputImage = 0; - inputFloat = 0; - } - - } - - ~ImportData() - { - destroy(); - } - - }; - - /// Neighbour index enumeration - indexed anticlockwise from East like angles - enum NeighbourIndex - { - NEIGHBOUR_EAST = 0, - NEIGHBOUR_NORTHEAST = 1, - NEIGHBOUR_NORTH = 2, - NEIGHBOUR_NORTHWEST = 3, - NEIGHBOUR_WEST = 4, - NEIGHBOUR_SOUTHWEST = 5, - NEIGHBOUR_SOUTH = 6, - NEIGHBOUR_SOUTHEAST = 7, - - NEIGHBOUR_COUNT = 8 - }; - - SceneManager* getSceneManager() const { return mSceneMgr; } - - /// Enumeration of relative spaces that you might want to use to address the terrain - enum Space - { - /// Simple global world space, axes and positions are all in world space - WORLD_SPACE = 0, - /// As world space, but positions are relative to the terrain world position - LOCAL_SPACE = 1, - /** x & y are parametric values on the terrain from 0 to 1, with the - origin at the bottom left. z is the world space height at that point. - */ - TERRAIN_SPACE = 2, - /** x & y are integer points on the terrain from 0 to size-1, with the - origin at the bottom left. z is the world space height at that point. - */ - POINT_SPACE = 3 - }; - - /** Interface used to by the Terrain instance to allocate GPU buffers. - @remarks This class exists to make it easier to re-use buffers between - multiple instances of terrain. - */ - class _OgreTerrainExport GpuBufferAllocator : public TerrainAlloc - { - public: - GpuBufferAllocator() {} - virtual ~GpuBufferAllocator() {} - - /** Allocate (or reuse) vertex buffers for a terrain LOD. - @param forTerrain - @param numVertices The total number of vertices - @param destPos Pointer to a vertex buffer for positions, to be bound - @param destDelta Pointer to a vertex buffer for deltas, to be bound - */ - virtual void allocateVertexBuffers(Terrain* forTerrain, size_t numVertices, HardwareVertexBufferSharedPtr& destPos, HardwareVertexBufferSharedPtr& destDelta) = 0; - /** Free (or return to the pool) vertex buffers for terrain. - */ - virtual void freeVertexBuffers(const HardwareVertexBufferSharedPtr& posbuf, const HardwareVertexBufferSharedPtr& deltabuf) = 0; - - /** Get a shared index buffer for a given number of settings. - - Since all index structures are the same at the same LOD level and - relative position, we can share index buffers. Therefore the - buffer returned from this method does not need to be 'freed' like - the vertex buffers since it is never owned. - @param batchSize The batch size along one edge - @param vdatasize The size of the referenced vertex data along one edge - @param vertexIncrement The number of vertices to increment for each new indexed row / column - @param xoffset The x offset from the start of vdatasize, at that resolution - @param yoffset The y offset from the start of vdatasize, at that resolution - @param numSkirtRowsCols Number of rows and columns of skirts - @param skirtRowColSkip The number of rows / cols to skip in between skirts - */ - virtual HardwareIndexBufferSharedPtr getSharedIndexBuffer(uint16 batchSize, - uint16 vdatasize, size_t vertexIncrement, uint16 xoffset, uint16 yoffset, uint16 numSkirtRowsCols, - uint16 skirtRowColSkip) = 0; - - /// Free any buffers we're holding - virtual void freeAllBuffers() = 0; - - }; - /// Standard implementation of a buffer allocator which re-uses buffers - class _OgreTerrainExport DefaultGpuBufferAllocator : public GpuBufferAllocator - { - public: - DefaultGpuBufferAllocator(); - virtual ~DefaultGpuBufferAllocator(); - void allocateVertexBuffers(Terrain* forTerrain, size_t numVertices, HardwareVertexBufferSharedPtr& destPos, HardwareVertexBufferSharedPtr& destDelta) override; - void freeVertexBuffers(const HardwareVertexBufferSharedPtr& posbuf, const HardwareVertexBufferSharedPtr& deltabuf) override; - HardwareIndexBufferSharedPtr getSharedIndexBuffer(uint16 batchSize, - uint16 vdatasize, size_t vertexIncrement, uint16 xoffset, uint16 yoffset, uint16 numSkirtRowsCols, - uint16 skirtRowColSkip) override; - void freeAllBuffers() override; - - /** 'Warm start' the allocator based on needing x instances of - terrain with the given configuration. - */ - void warmStart(size_t numInstances, uint16 terrainSize, uint16 maxBatchSize, - uint16 minBatchSize); - - private: - typedef std::list VBufList; - VBufList mFreePosBufList; - VBufList mFreeDeltaBufList; - typedef std::map IBufMap; - IBufMap mSharedIBufMap; - - uint32 hashIndexBuffer(uint16 batchSize, - uint16 vdatasize, size_t vertexIncrement, uint16 xoffset, uint16 yoffset, uint16 numSkirtRowsCols, - uint16 skirtRowColSkip); - HardwareVertexBufferSharedPtr getVertexBuffer(VBufList& list, size_t vertexSize, size_t numVertices); - - }; - - /** Tell this instance to use the given GpuBufferAllocator. - - May only be called when the terrain is not loaded. - */ - void setGpuBufferAllocator(GpuBufferAllocator* alloc); - - /// Get the current buffer allocator - GpuBufferAllocator* getGpuBufferAllocator(); - - /// Utility method to get the number of indexes required to render a given batch - static size_t _getNumIndexesForBatchSize(uint16 batchSize); - /** Utility method to populate a (locked) index buffer. - @param pIndexes Pointer to an index buffer to populate - @param batchSize The number of vertices down one side of the batch - @param vdatasize The number of vertices down one side of the vertex data being referenced - @param vertexIncrement The number of vertices to increment for each new indexed row / column - @param xoffset The x offset from the start of the vertex data being referenced - @param yoffset The y offset from the start of the vertex data being referenced - @param numSkirtRowsCols Number of rows and columns of skirts - @param skirtRowColSkip The number of rows / cols to skip in between skirts - - */ - static void _populateIndexBuffer(uint16* pIndexes, uint16 batchSize, - uint16 vdatasize, uint16 vertexIncrement, uint16 xoffset, uint16 yoffset, uint16 numSkirtRowsCols, - uint16 skirtRowColSkip); - - /** Utility method to calculate the skirt index for a given original vertex index. */ - static uint16 _calcSkirtVertexIndex(uint16 mainIndex, uint16 vdatasize, bool isCol, - uint16 numSkirtRowsCols, uint16 skirtRowColSkip); - - /** Convert a position from one space to another with respect to this terrain. - @param inSpace The space that inPos is expressed as - @param inPos The incoming position - @param outSpace The space which outPos should be expressed as - @param outPos The output position to be populated - */ - void convertPosition(Space inSpace, const Vector3& inPos, Space outSpace, Vector3& outPos) const; - /** Convert a position from one space to another with respect to this terrain. - @param inSpace The space that inPos is expressed as - @param inPos The incoming position - @param outSpace The space which outPos should be expressed as - @return The output position - */ - Vector3 convertPosition(Space inSpace, const Vector3& inPos, Space outSpace) const; - /** Convert a direction from one space to another with respect to this terrain. - @param inSpace The space that inDir is expressed as - @param inDir The incoming direction - @param outSpace The space which outDir should be expressed as - @param outDir The output direction to be populated - */ - void convertDirection(Space inSpace, const Vector3& inDir, Space outSpace, Vector3& outDir) const; - /** Convert a direction from one space to another with respect to this terrain. - @param inSpace The space that inDir is expressed as - @param inDir The incoming direction - @param outSpace The space which outDir should be expressed as - @return The output direction - */ - Vector3 convertDirection(Space inSpace, const Vector3& inDir, Space outSpace) const; - - /** Set the resource group to use when loading / saving. - @param resGroup Resource group name - you can set this to blank to use - the default in TerrainGlobalOptions. - */ - void setResourceGroup(const String& resGroup) { mResourceGroup = resGroup; } - - /** Get the resource group to use when loading / saving. - If this is blank, the default in TerrainGlobalOptions will be used. - */ - const String& getResourceGroup() const { return mResourceGroup; } - - /** Get the final resource group to use when loading / saving. - */ - const String& _getDerivedResourceGroup() const; - - /** Save terrain data in native form to a standalone file - @param filename The name of the file to save to. If this is a filename with - no path elements, then it is saved in the first writeable location - available in the resource group you have chosen to use for this - terrain. If the filename includes path specifiers then it is saved - directly instead (but note that it may not be reloadable via the - resource system if the location is not on the path). - */ - void save(const String& filename); - /** Save terrain data in native form to a serializing stream. - - If you want complete control over where the terrain data goes, use - this form. - */ - void save(StreamSerialiser& stream); - - /** Prepare the terrain from a standalone file. - @note - This is safe to do in a background thread as it creates no GPU resources. - It reads data from a native terrain data chunk. For more advanced uses, - such as loading from a shared file, use the StreamSerialiser form. - */ - bool prepare(const String& filename); - /** Prepare terrain data from saved data. - - This is safe to do in a background thread as it creates no GPU resources. - It reads data from a native terrain data chunk. - @return true if the preparation was successful - */ - bool prepare(DataStreamPtr& stream); - /** Prepare terrain data from saved data. - - This is safe to do in a background thread as it creates no GPU resources. - It reads data from a native terrain data chunk. - @return true if the preparation was successful - */ - bool prepare(StreamSerialiser& stream); - - /** Prepare the terrain from some import data rather than loading from - native data. - - This method may be called in a background thread. - */ - bool prepare(const ImportData& importData); - - /** Prepare and load the terrain in one simple call from a standalone file. - @note - This method must be called from the primary render thread. To load data - in a background thread, use the prepare() method. - */ - void load(const String& filename); - - /** Prepare and load the terrain in one simple call from a stream. - @note - This method must be called from the primary render thread. To load data - in a background thread, use the prepare() method. - */ - void load(StreamSerialiser& stream); - - /** Load the terrain based on the data already populated via prepare methods. - - This method must be called in the main render thread. - @param lodLevel Load the specified LOD level - @param synchronous Load type - */ - void load(int lodLevel = 0, bool synchronous = true); - - /** Return whether the terrain is loaded. - - Should only be called from the render thread really, since this is - where the loaded state changes. - */ - bool isLoaded() const { return mIsLoaded; } - - /** Returns whether this terrain has been modified since it was first loaded / defined. - - This flag is reset on save(). - */ - bool isModified() const { return mModified; } - - - /** Returns whether terrain heights have been modified since the terrain was first loaded / defined. - - This flag is reset on save(). - */ - bool isHeightDataModified() const { return mHeightDataModified; } - - - /** Unload the terrain and free GPU resources. - - This method must be called in the main render thread. - */ - void unload(); - - /** Free CPU resources created during prepare methods. - - This is safe to do in a background thread after calling unload(). - */ - void unprepare(); - - - /** Get a pointer to all the height data for this terrain. - - The height data is in world coordinates, relative to the position - of the terrain. - @par - This pointer is not const, so you can update the height data if you - wish. However, changes will not be propagated until you call - Terrain::dirty or Terrain::dirtyRect. - */ - float* getHeightData() const; - - /** Get a pointer to the height data for a given point. - */ - float* getHeightData(uint32 x, uint32 y) const; - - /** Get the height data for a given terrain point. - @param x, y Discrete coordinates in terrain vertices, values from 0 to size-1, - left/right bottom/top - */ - float getHeightAtPoint(uint32 x, uint32 y) const; - - /** Set the height data for a given terrain point. - @note this doesn't take effect until you call update() - @param x, y Discrete coordinates in terrain vertices, values from 0 to size-1, - left/right bottom/top - @param h The new height - */ - void setHeightAtPoint(uint32 x, uint32 y, float h); - - /** Get the height data for a given terrain position. - @param x, y Position in terrain space, values from 0 to 1 left/right bottom/top - */ - float getHeightAtTerrainPosition(Real x, Real y) const; - - /** Get the height data for a given world position (projecting the point - down on to the terrain). - @param x, y,z Position in world space. Positions will be clamped to the edge - of the terrain - */ - float getHeightAtWorldPosition(Real x, Real y, Real z) const; - /// @overload - float getHeightAtWorldPosition(const Vector3& pos) const; - - /** Get a pointer to all the delta data for this terrain. - - The delta data is a measure at a given vertex of by how much vertically - a vertex will have to move to reach the point at which it will be - removed in the next lower LOD. - */ - const float* getDeltaData() const; - - /** Get a pointer to the delta data for a given point. - */ - const float* getDeltaData(uint32 x, uint32 y) const; - - /** Get a Vector3 of the world-space point on the terrain, aligned as per - options. - @note This point is relative to Terrain::getPosition - */ - void getPoint(uint32 x, uint32 y, Vector3* outpos) const; - - /** Get a Vector3 of the world-space point on the terrain, aligned as per - options. Cascades into neighbours if out of bounds. - @note This point is relative to Terrain::getPosition - neighbours are - adjusted to be relative to this tile - */ - void getPointFromSelfOrNeighbour(int32 x, int32 y, Vector3* outpos) const; - - /** Get a Vector3 of the world-space point on the terrain, supplying the - height data manually (can be more optimal). - @note This point is relative to Terrain::getPosition - */ - void getPoint(uint32 x, uint32 y, float height, Vector3* outpos) const; - /** Get a transform which converts Vector4(xindex, yindex, height, 1) into - an object-space position including scalings and alignment. - */ - Affine3 getPointTransform() const; - - /** Translate a vector from world space to local terrain space based on the alignment options. - @param inVec The vector in basis space, where x/y represents the - terrain plane and z represents the up vector - @param[out] outVec - */ - void getTerrainVector(const Vector3& inVec, Vector3* outVec) const; - /// @overload - void getTerrainVector(Real x, Real y, Real z, Vector3* outVec) const; - - /** Translate a vector from world space to local terrain space based on a specified alignment. - @param inVec The vector in basis space, where x/y represents the - terrain plane and z represents the up vector - @param[out] outVec - @param align The alignment of the terrain - */ - void getTerrainVectorAlign(const Vector3& inVec, Alignment align, Vector3* outVec) const; - /// @overload - void getTerrainVectorAlign(Real x, Real y, Real z, Alignment align, Vector3* outVec) const; - - /** Translate a vector into world space based on the alignment options. - @param inVec The vector in basis space, where x/y represents the - terrain plane and z represents the up vector - @param[out] outVec - */ - void getVector(const Vector3& inVec, Vector3* outVec) const; - /// @overload - void getVector(Real x, Real y, Real z, Vector3* outVec) const; - - /** Translate a vector into world space based on a specified alignment. - @param inVec The vector in basis space, where x/y represents the - terrain plane and z represents the up vector - @param[out] outVec - @param align The alignment of the terrain - */ - void getVectorAlign(const Vector3& inVec, Alignment align, Vector3* outVec) const; - /// @overload - void getVectorAlign(Real x, Real y, Real z, Alignment align, Vector3* outVec) const; - - - /** Convert a position from terrain basis space to world space. - @param TSpos Terrain space position, where (0,0) is the bottom-left of the - terrain, and (1,1) is the top-right. The Z coordinate is in absolute - height units. - @note This position is relative to Terrain::getPosition - @param outWSpos World space output position (setup according to current alignment). - */ - void getPosition(const Vector3& TSpos, Vector3* outWSpos) const; - /// @overload - void getPosition(Real x, Real y, Real z, Vector3* outWSpos) const; - - /** Convert a position from world space to terrain basis space. - @param WSpos World space position (setup according to current alignment). - @param outTSpos Terrain space output position, where (0,0) is the bottom-left of the - terrain, and (1,1) is the top-right. The Z coordinate is in absolute - height units. - */ - void getTerrainPosition(const Vector3& WSpos, Vector3* outTSpos) const; - /// @overload - void getTerrainPosition(Real x, Real y, Real z, Vector3* outTSpos) const; - /** Convert a position from terrain basis space to world space based on a specified alignment. - @param TSpos Terrain space position, where (0,0) is the bottom-left of the - terrain, and (1,1) is the top-right. The Z coordinate is in absolute - height units. - @param outWSpos World space output position (setup according to alignment). - @param align The alignment of the terrain - */ - void getPositionAlign(const Vector3& TSpos, Alignment align, Vector3* outWSpos) const; - /// @overload - void getPositionAlign(Real x, Real y, Real z, Alignment align, Vector3* outWSpos) const; - - /** Convert a position from world space to terrain basis space based on a specified alignment. - @param WSpos World space position (setup according to alignment). - @param outTSpos Terrain space output position, where (0,0) is the bottom-left of the - terrain, and (1,1) is the top-right. The Z coordinate is in absolute - height units. - @param align The alignment of the terrain - */ - void getTerrainPositionAlign(const Vector3& WSpos, Alignment align, Vector3* outTSpos) const; - /// @overload - void getTerrainPositionAlign(Real x, Real y, Real z, Alignment align, Vector3* outTSpos) const; - - - /// Get the alignment of the terrain - Alignment getAlignment() const; - /// Get the size of the terrain in vertices along one side - uint16 getSize() const; - /** Set the size of terrain in vertices along one side. - @note The existing height data will be bilinear filtered to fill the new size - @param newSize the new size of the terrain - */ - void setSize(uint16 newSize); - /// Get the maximum size in vertices along one side of a batch - uint16 getMaxBatchSize() const; - /// Get the minimum size in vertices along one side of a batch - uint16 getMinBatchSize() const; - /// Get the size of the terrain in world units - Real getWorldSize() const; - /** Set the world size of terrain. - @param newWorldSize the new world size of the terrain - */ - void setWorldSize(Real newWorldSize); - - /// @name Layers - /// @{ - /** Get the number of layers in this terrain. */ - uint8 getLayerCount() const { return static_cast(mLayers.size()); } - - /** Get the declaration which describes the layers in this terrain. */ - const TerrainLayerDeclaration& getLayerDeclaration() const { return mLayerDecl; } - - /** Add a new layer to this terrain. - @param worldSize The size of the texture in this layer in world units. Default - to zero to use the default - @param textureNames A list of textures to assign to the samplers in this - layer. Leave blank to provide these later. - */ - void addLayer(Real worldSize = 0, const StringVector* textureNames = 0); - - /** Add a new layer to this terrain at a specific index. - @param index The index at which to insert this layer (existing layers are shifted forwards) - @param worldSize The size of the texture in this layer in world units. Default - to zero to use the default - @param textureNames A list of textures to assign to the samplers in this - layer. Leave blank to provide these later. - */ - void addLayer(uint8 index, Real worldSize = 0, const StringVector* textureNames = 0); - - /** Remove a layer from the terrain. - */ - void removeLayer(uint8 index); - - /** Replace an existing terrain layer, optionally preserving all other layer blend maps - @param index The 0 based index of the terrain layer to replace - @param keepBlends True to keep using the existing blend maps. False to reset the blend map for the layer. - Irrelevant if index == 0 - @param worldSize The size of the texture in this layer in world units. Default - to zero to use the default - @param textureNames A list of textures to assign to the samplers in this - layer. Leave blank to provide these later. - */ - void replaceLayer(uint8 index, bool keepBlends, Real worldSize = 0, const StringVector* textureNames = 0); - - /** Get the maximum number of layers supported with the current options. - @note When you change the options requested, this value can change. - */ - uint8 getMaxLayers() const; - - /** How large an area in world space the texture in a terrain layer covers - before repeating. - @param index The layer index. - */ - Real getLayerWorldSize(uint8 index) const; - /** How large an area in world space the texture in a terrain layer covers - before repeating. - @param index The layer index. - @param size The world size of the texture before repeating - */ - void setLayerWorldSize(uint8 index, Real size); - - /** Get the layer UV multiplier. - - This is derived from the texture world size. The base UVs in the - terrain vary from 0 to 1 and this multiplier is used (in a fixed-function - texture coord scaling or a shader parameter) to translate it to the - final value. - @param index The layer index. - */ - Real getLayerUVMultiplier(uint8 index) const; - - /** Get the name of the texture bound to a given index within a given layer. - See the LayerDeclaration for a list of sampelrs within a layer. - @param layerIndex The layer index. - @param samplerIndex The sampler index within a layer - */ - const String& getLayerTextureName(uint8 layerIndex, uint8 samplerIndex) const; - /** Set the name of the texture bound to a given index within a given layer. - See the LayerDeclaration for a list of sampelrs within a layer. - @param layerIndex The layer index. - @param samplerIndex The sampler index within a layer - @param textureName The name of the texture to use - */ - void setLayerTextureName(uint8 layerIndex, uint8 samplerIndex, const String& textureName); - - /** Get the requested size of the blend maps used to blend between layers - for this terrain. - Note that where hardware limits this, the actual blend maps may be lower - resolution. This option is derived from TerrainGlobalOptions when the - terrain is created. - */ - uint16 getLayerBlendMapSize() const { return mLayerBlendMapSize; } - /// @} - - /** Get the requested size of lightmap for this terrain. - Note that where hardware limits this, the actual lightmap may be lower - resolution. This option is derived from TerrainGlobalOptions when the - terrain is created. - */ - uint16 getLightmapSize() const { return mLightmapSize; } - - /// Get access to the lightmap, if enabled (as requested by the material generator) - const TexturePtr& getLightmap() const { return mLightmap; } - - /** Get the requested size of composite map for this terrain. - Note that where hardware limits this, the actual texture may be lower - resolution. This option is derived from TerrainGlobalOptions when the - terrain is created. - */ - uint16 getCompositeMapSize() const { return mCompositeMapSize; } - - /// Get access to the composite map, if enabled (as requested by the material generator) - const TexturePtr& getCompositeMap() const { return mCompositeMap; } - - /// Get the world position of the terrain centre - const Vector3& getPosition() const { return mPos; } - /// Set the position of the terrain centre in world coordinates - void setPosition(const Vector3& pos); - /// Get the root scene node for the terrain (internal use only) - SceneNode* _getRootSceneNode() const; - /** Mark the entire terrain as dirty. - By marking a section of the terrain as dirty, you are stating that you have - changed the height data within this rectangle. This rectangle will be merged with - any existing outstanding changes. To finalise the changes, you must - call update(), updateGeometry(), or updateDerivedData(). - */ - void dirty(); - - /** Mark a region of the terrain as dirty. - By marking a section of the terrain as dirty, you are stating that you have - changed the height data within this rectangle. This rectangle will be merged with - any existing outstanding changes. To finalise the changes, you must - call update(), updateGeometry(), or updateDerivedData(). - @param rect A rectangle expressed in vertices describing the dirty region; - left < right, top < bottom, left & top are inclusive, right & bottom exclusive - */ - void dirtyRect(const Rect& rect); - - /** Mark a region of the terrain composite map as dirty. - - You don't usually need to call this directly, it is inferred from - changing the other data on the terrain. - */ - void _dirtyCompositeMapRect(const Rect& rect); - - /** Mark a region of the lightmap as dirty. - - You only need to call this if you need to tell the terrain to update - the lightmap data for some reason other than the terrain geometry - has changed. Changing terrain geometry automatically dirties the - correct lightmap areas. - @note - The lightmap won't actually be updated until update() or updateDerivedData() - is called. - */ - void dirtyLightmapRect(const Rect& rect); - - /** Mark a the entire lightmap as dirty. - - You only need to call this if you need to tell the terrain to update - the lightmap data for some reason other than the terrain geometry - has changed. Changing terrain geometry automatically dirties the - correct lightmap areas. - @note - The lightmap won't actually be updated until update() or updateDerivedData() - is called. - */ - void dirtyLightmap(); - - /** Trigger the update process for the terrain. - - Updating the terrain will process any dirty sections of the terrain. - This may affect many things: -
  1. The terrain geometry
  2. -
  3. The terrain error metrics which determine LOD transitions
  4. -
  5. The terrain normal map, if present
  6. -
  7. The terrain lighting map, if present
  8. -
  9. The terrain composite map, if present
  10. -
- If threading is enabled, only item 1 (the geometry) will be updated - synchronously, ie will be fully up to date when this method returns. - The other elements are more expensive to compute, and will be queued - for processing in a background thread, in the order shown above. As these - updates complete, the effects will be shown. - - You can also separate the timing of updating the geometry, LOD and the lighting - information if you want, by calling updateGeometry() and - updateDerivedData() separately. - @param synchronous If true, all updates will happen immediately and not - in a separate thread. - */ - void update(bool synchronous = false); - - /** Performs an update on the terrain geometry based on the dirty region. - - Terrain geometry will be updated when this method returns. - */ - void updateGeometry(); - /** Performs an update on the terrain geometry based on the dirty region. - - Terrain geometry will be updated when this method returns, and no - neighbours will be notified. - */ - void updateGeometryWithoutNotifyNeighbours(); - - // Used as a type mask for updateDerivedData - static const uint8 DERIVED_DATA_DELTAS; - static const uint8 DERIVED_DATA_NORMALS; - static const uint8 DERIVED_DATA_LIGHTMAP; - static const uint8 DERIVED_DATA_ALL; - - /** Updates derived data for the terrain (LOD, lighting) to reflect changed height data, in a separate - thread if threading is enabled (OGRE_THREAD_SUPPORT). - If threading is enabled, on return from this method the derived - data will not necessarily be updated immediately, the calculation - may be done in the background. Only one update will run in the background - at once. This derived data can typically survive being out of sync for a - few frames which is why it is not done synchronously - @param synchronous If true, the update will happen immediately and not - in a separate thread. - @param typeMask Mask indicating the types of data we should generate - */ - void updateDerivedData(bool synchronous = false, uint8 typeMask = 0xFF); - - /** Performs an update on the terrain composite map based on its dirty region. - - Rather than calling this directly, call updateDerivedData, which will - also call it after the other derived data has been updated (there is - no point updating the composite map until lighting has been updated). - However the blend maps may call this directly when only the blending - information has been updated. - */ - void updateCompositeMap(); - - /** Performs an update on the terrain composite map based on its dirty region, - but only at a maximum frequency. - - Rather than calling this directly, call updateDerivedData, which will - also call it after the other derived data has been updated (there is - no point updating the composite map until lighting has been updated). - However the blend maps may call this directly when only the blending - information has been updated. - @note - This method will log the request for an update, but won't do it just yet - unless there are no further requests in the next 'delay' seconds. This means - you can call it all the time but only pick up changes in quiet times. - */ - void updateCompositeMapWithDelay(Real delay = 2); - - - /** The default size of 'skirts' used to hide terrain cracks - (default 10, set for new Terrain using TerrainGlobalOptions) - */ - Real getSkirtSize() const { return mSkirtSize; } - - /// Get the total number of LOD levels in the terrain - uint16 getNumLodLevels() const { return mNumLodLevels; } - - /// Get the number of LOD levels in a leaf of the terrain quadtree - uint16 getNumLodLevelsPerLeaf() const { return mNumLodLevelsPerLeafNode; } - - /** Calculate (or recalculate) the delta values of heights between a vertex - in its recorded position, and the place it will end up in the LOD - in which it is removed. - @param rect Rectangle describing the area in which heights have altered - @return A Rectangle describing the area which was updated (may be wider - than the input rectangle) - */ - Rect calculateHeightDeltas(const Rect& rect); - - /** Finalise the height deltas. - Calculated height deltas are kept in a separate calculation field to make - them safe to perform in a background thread. This call promotes those - calculations to the runtime values, and must be called in the main thread. - @param rect Rectangle describing the area to finalise - @param cpuData When updating vertex data, update the CPU copy (background) - */ - void finaliseHeightDeltas(const Rect& rect, bool cpuData); - - /** Calculate (or recalculate) the normals on the terrain - @param rect Rectangle describing the area of heights that were changed - @param outFinalRect Output rectangle describing the area updated - @return Pointer to a PixelBox full of normals (caller responsible for deletion) - */ - PixelBox* calculateNormals(const Rect& rect, Rect& outFinalRect); - - /** Finalise the normals. - Calculated normals are kept in a separate calculation area to make - them safe to perform in a background thread. This call promotes those - calculations to the runtime values, and must be called in the main thread. - @param rect Rectangle describing the area to finalise - @param normalsBox Pointer to a PixelBox full of normals - */ - void finaliseNormals(const Rect& rect, PixelBox* normalsBox); - - /** Calculate (or recalculate) the terrain lightmap - @param rect Rectangle describing the area of heights that were changed - @param extraTargetRect Rectangle describing a target area of the terrain that - needs to be calculated additionally (e.g. from a neighbour) - @param outFinalRect Output rectangle describing the area updated in the lightmap - @return Pointer to a PixelBox full of lighting data (caller responsible for deletion) - */ - PixelBox* calculateLightmap(const Rect& rect, const Rect& extraTargetRect, Rect& outFinalRect); - - /** Finalise the lightmap. - Calculating lightmaps is kept in a separate calculation area to make - it safe to perform in a background thread. This call promotes those - calculations to the runtime values, and must be called in the main thread. - @param rect Rectangle describing the area to finalise - @param lightmapBox Pointer to a PixelBox full of normals - */ - void finaliseLightmap(const Rect& rect, PixelBox* lightmapBox); - - /** Gets the resolution of the entire terrain (down one edge) at a - given LOD level. - */ - uint16 getResolutionAtLod(uint16 lodLevel) const; - - /** Test for intersection of a given ray with the terrain. If the ray hits - the terrain, the point of intersection is returned. - @param ray The ray to test for intersection - @param cascadeToNeighbours Whether the ray will be projected onto neighbours if - no intersection is found - @param distanceLimit The distance from the ray origin at which we will stop looking, - 0 indicates no limit - @return A pair which contains whether the ray hit the terrain and, if so, where. - @remarks This can be called from any thread as long as no parallel write to - the heightmap data occurs. - */ - std::pair rayIntersects(const Ray& ray, - bool cascadeToNeighbours = false, Real distanceLimit = 0); //const; - - /// Get the AABB (local coords) of the entire terrain - const AxisAlignedBox& getAABB() const; - /// Get the AABB (world coords) of the entire terrain - AxisAlignedBox getWorldAABB() const; - /// Get the minimum height of the terrain - Real getMinHeight() const; - /// Get the maximum height of the terrain - Real getMaxHeight() const; - /// Get the bounding radius of the entire terrain - Real getBoundingRadius() const; - - /// Get the material being used for the terrain - const MaterialPtr& getMaterial() const; - /// Internal getting of material - const MaterialPtr& _getMaterial() const { return mMaterial; } - /// Get the material being used for the terrain composite map - const MaterialPtr& getCompositeMapMaterial() const; - /// Internal getting of material for the terrain composite map - const MaterialPtr& _getCompositeMapMaterial() const { return mCompositeMapMaterial; } - - /// Get the name of the material being used for the terrain - const String& getMaterialName() const { return mMaterialName; } - - /// Overridden from SceneManager::Listener - void preFindVisibleObjects(SceneManager* source, - SceneManager::IlluminationRenderStage irs, Viewport* v) override; - /// Overridden from SceneManager::Listener - void sceneManagerDestroyed(SceneManager* source) override; - - /// Get the render queue group that this terrain will be rendered into - uint8 getRenderQueueGroup(void) const { return mRenderQueueGroup; } - /** Set the render queue group that this terrain will be rendered into. - @remarks The default is specified in TerrainGlobalOptions - */ - void setRenderQueueGroup(uint8 grp) { mRenderQueueGroup = grp; } - - /// Get the visibility flags for this terrain. - uint32 getVisibilityFlags(void) const { return mVisibilityFlags; } - /** Set the visibility flags for this terrain. - @remarks The default is specified in TerrainGlobalOptions - */ - void setVisibilityFlags(uint32 flags) { mVisibilityFlags = flags; } - - /// Get the query flags for this terrain. - uint32 getQueryFlags(void) const { return mQueryFlags; } - /** Set the query flags for this terrain. - @remarks The default is specified in TerrainGlobalOptions - */ - void setQueryFlags(uint32 flags) { mQueryFlags = flags; } - - /** As setQueryFlags, except the flags passed as parameters are appended to the existing flags on this object. */ - void addQueryFlags(uint32 flags) { mQueryFlags |= flags; } - - /* As setQueryFlags, except the flags passed as parameters are removed from the existing flags on this object. */ - void removeQueryFlags(uint32 flags) { mQueryFlags &= ~flags; } - - - /** Retrieve the layer blending map for a given layer, which may - be used to edit the blending information for that layer. - @note - You can only do this after the terrain has been loaded. You may - edit the content of the blend layer in another thread, but you - may only upload it in the main render thread. - @param layerIndex The layer index, which should be 1 or higher (since - the bottom layer has no blending). - @return Pointer to the TerrainLayerBlendMap requested. The caller must - not delete this instance, use freeTemporaryResources if you want - to save the memory after completing your editing. - */ - TerrainLayerBlendMap* getLayerBlendMap(uint8 layerIndex); - - /** Get the index of the blend texture that a given layer uses. - @param layerIndex The layer index, must be >= 1 and less than the number - of layers - @return The index of the shared blend texture - */ - uint8 getBlendTextureIndex(uint8 layerIndex) const; - - /// @deprecated use getBlendTextures() - OGRE_DEPRECATED uint8 getBlendTextureCount() const; - /// Get the number of blend textures needed for a given number of layers - static uint8 getBlendTextureCount(uint8 numLayers) { return ((numLayers - 2) / 4) + 1; } - - - /** Get the packed blend textures. - @note These are indexed by the blend texture index, not the layer index - (multiple layers will share a blend texture) - */ - const std::vector& getBlendTextures() const { return mBlendTextureList; } - - /// @deprecated use getBlendTextures() - OGRE_DEPRECATED const String& getBlendTextureName(uint8 textureIndex) const; - - /** Set whether a global colour map is enabled. - - A global colour map can add variation to your terrain and reduce the - perceived tiling effect you might get in areas of continuous lighting - and the same texture. - The global colour map is only used when the material generator chooses - to use it. - @note You must only call this from the main render thread - @param enabled Whether the global colour map is enabled or not - @param size The resolution of the colour map. A value of zero means 'no change' - and the default is set in TerrainGlobalOptions. - */ - void setGlobalColourMapEnabled(bool enabled, uint16 size = 0); - /// Get whether a global colour map is enabled on this terrain - bool getGlobalColourMapEnabled() const { return mGlobalColourMapEnabled; } - /// Get the size of the global colour map (if used) - uint16 getGlobalColourMapSize() const { return mGlobalColourMapSize; } - /// Get access to the global colour map, if enabled - const TexturePtr& getGlobalColourMap() const { return mColourMap; } - - /** Widen a rectangular area of terrain to take into account an extrusion vector. - @param vec A vector in world space - @param inRect Input rectangle - @param outRect Output rectangle - */ - void widenRectByVector(const Vector3& vec, const Rect& inRect, Rect& outRect); - - /** Widen a rectangular area of terrain to take into account an extrusion vector, - but specify the min / max heights to extrude manually. - @param vec A vector in world space - @param inRect Input rectangle - @param minHeight, maxHeight The extents of the height to extrude - @param outRect Output rectangle - */ - void widenRectByVector(const Vector3& vec, const Rect& inRect, - Real minHeight, Real maxHeight, Rect& outRect); - - /** Free as many resources as possible for optimal run-time memory use. - - This class keeps some temporary storage around in order to make - certain actions (such as editing) possible more quickly. Calling this - method will cause as many of those resources as possible to be - freed. You might want to do this for example when you are finished - editing a particular terrain and want to have optimal runtime - efficiency. - */ - void freeTemporaryResources(); - - /** Get a blend texture with a given index. - @param index The blend texture index (note: not layer index; derive - the texture index from getLayerBlendTextureIndex) - */ - const TexturePtr& getLayerBlendTexture(uint8 index) const; - - /** Get the texture index and colour channel of the blend information for - a given layer. - @param layerIndex The index of the layer (1 or higher, layer 0 has no blend data) - @return A pair in which the first value is the texture index, and the - second value is the colour channel (RGBA) - */ - std::pair getLayerBlendTextureIndex(uint8 layerIndex) const; - - /** @name Internal implementation options for the terrain material - - The TerrainMaterialGenerator should call this methods to specify the - options it would like to use when creating a material. Not all the data - is guaranteed to be up to date on return from this method - for example some - maps may be generated in the background. However, on return from this method - all the features that are requested will be referenceable by materials, the - data may just take a few frames to be fully populated. - */ - /// @{ - /** Request vertex morphing information. - @param morph Whether LOD morphing information is required to be calculated - */ - void _setMorphRequired(bool morph) { mLodMorphRequired = morph; } - /// Get whether LOD morphing is needed - bool _getMorphRequired() const { return mLodMorphRequired; } - - /** Request a terrain-wide normal map. - @param normalMap Whether a terrain-wide normal map is requested. This is usually - mutually exclusive with the lightmap option. - */ - void _setNormalMapRequired(bool normalMap); - - /** Request a terrain-wide light map. - @param lightMap Whether a terrain-wide lightmap including precalculated - lighting is required (light direction in TerrainGlobalOptions) - @param shadowsOnly If true, the lightmap contains only shadows, - no directional lighting intensity - */ - void _setLightMapRequired(bool lightMap, bool shadowsOnly = false); - - /** Request a terrain-wide composite map. - - A composite map is a texture with all of the blending and lighting baked in, such that - at distance this texture can be used as an approximation of the multi-layer - blended material. It is actually up to the material generator to render this - composite map, because obviously precisely what it looks like depends on what - the main material looks like. For this reason, the composite map is one piece - of derived terrain data that is always calculated in the render thread, and - usually on the GPU. It is expected that if this option is requested, - the material generator will use it to construct distant LOD techniques. - @param compositeMap Whether a terrain-wide composite map is needed. - */ - void _setCompositeMapRequired(bool compositeMap); - /// @} - - /// Whether we're using vertex compression or not - bool _getUseVertexCompression() const; - - /// Utility method, get the first LOD Level at which this vertex is no longer included - uint16 getLODLevelWhenVertexEliminated(long x, long y) const; - /// Utility method, get the first LOD Level at which this vertex is no longer included - uint16 getLODLevelWhenVertexEliminated(long rowOrColulmn) const; - - - /// Get the top level of the quad tree which is used to divide up the terrain - TerrainQuadTreeNode* getQuadTree() { return mQuadTree; } - - /// Get the (global) normal map texture - TexturePtr getTerrainNormalMap() const { return mTerrainNormalMap; } - - /** Retrieve the terrain's neighbour, or null if not present. - - Terrains only know about their neighbours if they are notified via - setNeighbour. This information is not saved with the terrain since every - tile must be able to be independent. - @param index The index of the neighbour - */ - Terrain* getNeighbour(NeighbourIndex index) const; - - /** Set a terrain's neighbour, or null to detach one. - - This information is not saved with the terrain since every - tile must be able to be independent. However if modifications are - made to a tile which can affect its neighbours, while connected the - changes will be propagated. - @param index The index of the neighbour - @param neighbour The terrain instance to become the neighbour, or null to reset. - @param recalculate If true, this terrain instance will recalculate elements - that could be affected by the connection of this tile (e.g. matching - heights, calcaulting normals, calculating shadows crossing the boundary). - If false, this terrain's state is assumed to be up to date already - (e.g. was calculated with this tile present before and the state saved). - @param notifyOther Whether the neighbour should also be notified (recommended - to leave this at the default so relationships are up to date before - background updates are triggered) - */ - void setNeighbour(NeighbourIndex index, Terrain* neighbour, bool recalculate = false, bool notifyOther = true); - - /** Get the opposite neighbour relationship (useful for finding the - neighbour index from the perspective of the tile the other side of the - boundary). - */ - static NeighbourIndex getOppositeNeighbour(NeighbourIndex index); - - /** Get the neighbour enum for a given offset in a grid (signed). - */ - static NeighbourIndex getNeighbourIndex(long offsetx, long offsety); - - /** Tell this instance to notify all neighbours that will be affected - by a height change that has taken place. - - This method will determine which neighbours need notification and call - their neighbourModified method. It is called automatically by - updateGeometry(). - */ - void notifyNeighbours(); - - /** Notify that a neighbour has just finished updating and that this - change affects this tile. - @param index The neighbour index (from this tile's perspective) - @param edgerect The area at the edge of this tile that needs height / normal - recalculation (may be null) - @param shadowrect The area on this tile where shadows need recalculating (may be null) - */ - void neighbourModified(NeighbourIndex index, const Rect& edgerect, const Rect& shadowrect); - - /** Utility method to pick a neighbour based on a ray. - @param ray The ray in world space - @param distanceLimit Limit beyond which we want to ignore neighbours (0 for infinite) - @return The first neighbour along this ray, or null - */ - Terrain* raySelectNeighbour(const Ray& ray, Real distanceLimit = 0); - - /** Dump textures to files. - - This is a debugging method. - */ - void _dumpTextures(const String& prefix, const String& suffix); - - /** Query whether a derived data update is in progress or not. */ - bool isDerivedDataUpdateInProgress() const { return mDerivedDataUpdateInProgress; } - - - /// Utility method to convert axes from world space to terrain space (xy terrain, z up) - static void convertWorldToTerrainAxes(Alignment align, const Vector3& worldVec, Vector3* terrainVec); - /// Utility method to convert axes from terrain space (xy terrain, z up) tp world space - static void convertTerrainToWorldAxes(Alignment align, const Vector3& terrainVec, Vector3* worldVec); - - /// Utility method to write a layer declaration to a stream - static void writeLayerDeclaration(const TerrainLayerDeclaration& decl, StreamSerialiser& ser); - /// Utility method to read a layer declaration from a stream - static bool readLayerDeclaration(StreamSerialiser& ser, TerrainLayerDeclaration& targetdecl); - /// Utility method to write a layer instance list to a stream - static void writeLayerInstanceList(const Terrain::LayerInstanceList& lst, StreamSerialiser& ser); - /// Utility method to read a layer instance list from a stream - static bool readLayerInstanceList(StreamSerialiser& ser, size_t numSamplers, Terrain::LayerInstanceList& targetlst); - - // This mutex is write-locked by neighbours if they are in the process of deleting themselves. - // It should be read-locked whenever using neighbours in calculations which are possibly running in a - // background thread. - OGRE_RW_MUTEX(mNeighbourMutex); - - void waitForDerivedProcesses(); - private: - /// WorkQueue::RequestHandler override - WorkQueue::Response* handleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ); - /// WorkQueue::ResponseHandler override - void handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ); - - void generateMaterial(); - - /** Gets the data size at a given LOD level. - */ - uint getGeoDataSizeAtLod(uint16 lodLevel) const; - /** Get the real lod level - @param lodLevel LOD level which can be negative. - @note After mapping, [-mNumLodLevels, -1] equals to [0,mNumLodLevels-1] - So you can reference the lowest LOD with -1 - */ - inline int getPositiveLodLevel( int lodLevel ) const - { - return (lodLevel>=0) ? lodLevel : mNumLodLevels+lodLevel; - } - void freeLodData(); - - void freeCPUResources(); - void freeGPUResources(); - void determineLodLevels(); - void distributeVertexData(); - void updateBaseScale(); - void createGPUBlendTextures(); - void createLayerBlendMaps(); - void createOrDestroyGPUNormalMap(); - void createOrDestroyGPUColourMap(); - void createOrDestroyGPULightmap(); - void createOrDestroyGPUCompositeMap(); - - void convertSpace(Space inSpace, const Vector3& inVec, Space outSpace, Vector3& outVec, bool translation) const; - Vector3 convertWorldToTerrainAxes(const Vector3& inVec) const; - Vector3 convertTerrainToWorldAxes(const Vector3& inVec) const; - /** Get a Vector3 of the world-space point on the terrain, aligned Y-up always. - @note This point is relative to Terrain::getPosition - */ - void getPointAlign(uint32 x, uint32 y, Alignment align, Vector3* outpos) const; - /** Get a Vector3 of the world-space point on the terrain, supplying the - height data manually (can be more optimal). - @note This point is relative to Terrain::getPosition - */ - void getPointAlign(uint32 x, uint32 y, float height, Alignment align, Vector3* outpos) const; - void calculateCurrentLod(Viewport* vp); - - /// Delete blend maps for all layers >= lowIndex - void deleteBlendMaps(uint8 lowIndex); - /// Shift/slide all GPU blend texture channels > index up one slot. Blend data may shift into the next texture - void shiftUpGPUBlendChannels(uint8 index); - /// Shift/slide all GPU blend texture channels > index down one slot. Blend data may shift into the previous texture - void shiftDownGPUBlendChannels(uint8 index); - /// Copy a GPU blend channel from one source to another. Source and Dest are not required to be in the same texture - void copyBlendTextureChannel(uint8 srcIndex, uint8 srcChannel, uint8 destIndex, uint8 destChannel ); - /// Reset a blend channel back to full black - void clearGPUBlendChannel(uint8 index, uint channel); - - void copyGlobalOptions(); - void checkLayers(bool includeGPUResources); - void checkDeclaration(); - void deriveUVMultipliers(); - - void updateDerivedDataImpl(const Rect& rect, const Rect& lightmapExtraRect, bool synchronous, uint8 typeMask); - - void getEdgeRect(NeighbourIndex index, int32 range, Rect* outRect) const; - // get the equivalent of the passed in edge rectangle in neighbour - void getNeighbourEdgeRect(NeighbourIndex index, const Rect& inRect, Rect* outRect) const; - // get the equivalent of the passed in edge point in neighbour - void getNeighbourPoint(NeighbourIndex index, uint32 x, uint32 y, uint32 *outx, uint32 *outy) const; - // overflow a point into a neighbour index and point - void getNeighbourPointOverflow(int32 x, int32 y, NeighbourIndex *outindex, uint32 *outx, uint32 *outy) const; - - /// Removes this terrain instance from neighbouring terrain's list of neighbours. - void removeFromNeighbours(); - - SceneManager* mSceneMgr; - SceneNode* mRootNode; - String mResourceGroup; - bool mIsLoaded; - bool mModified; - bool mHeightDataModified; - - /// The height data (world coords relative to mPos) - float* mHeightData; - /// The delta information defining how a vertex moves before it is removed at a lower LOD - float* mDeltaData; - Alignment mAlign; - Real mWorldSize; - uint16 mSize; - uint16 mMaxBatchSize; - uint16 mMinBatchSize; - Vector3 mPos; - TerrainQuadTreeNode* mQuadTree; - uint16 mNumLodLevels; - uint16 mNumLodLevelsPerLeafNode; - uint16 mTreeDepth; - /// Base position in world space, relative to mPos - Real mBase; - /// Relationship between one point on the terrain and world size - Real mScale; - TerrainLayerDeclaration mLayerDecl; - LayerInstanceList mLayers; - RealVector mLayerUVMultiplier; - - Real mSkirtSize; - uint8 mRenderQueueGroup; - uint32 mVisibilityFlags; - uint32 mQueryFlags; - - Rect mDirtyGeometryRect; - Rect mDirtyDerivedDataRect; - Rect mDirtyGeometryRectForNeighbours; - Rect mDirtyLightmapFromNeighboursRect; - bool mDerivedDataUpdateInProgress; - /// If another update is requested while one is already running - uint8 mDerivedUpdatePendingMask; - - bool mGenerateMaterialInProgress; - /// Don't release Height/DeltaData when preparing - mutable bool mPrepareInProgress; - /// A data holder for communicating with the background derived data update - struct DerivedDataRequest - { - Terrain* terrain; - // types requested - uint8 typeMask; - Rect dirtyRect; - Rect lightmapExtraDirtyRect; - }; - - /// A data holder for communicating with the background derived data update - struct DerivedDataResponse - { - Terrain* terrain; - /// Remaining types not yet processed - uint8 remainingTypeMask; - /// The area of deltas that was updated - Rect deltaUpdateRect; - /// The area of normals that was updated - Rect normalUpdateRect; - /// The area of lightmap that was updated - Rect lightmapUpdateRect; - /// All CPU-side data, independent of textures; to be blitted in main thread - PixelBox* normalMapBox; - PixelBox* lightMapBox; - }; - - String mMaterialName; - MaterialPtr mMaterial; - TerrainMaterialGeneratorPtr mMaterialGenerator; - unsigned long long int mMaterialGenerationCount; - bool mMaterialDirty; - mutable bool mMaterialParamsDirty; - - uint16 mLayerBlendMapSize; - uint16 mLayerBlendMapSizeActual; - typedef std::vector TexturePtrList; - TexturePtrList mBlendTextureList; - TerrainLayerBlendMapList mLayerBlendMapList; - - uint16 mGlobalColourMapSize; - bool mGlobalColourMapEnabled; - TexturePtr mColourMap; - - uint16 mLightmapSize; - uint16 mLightmapSizeActual; - TexturePtr mLightmap; - - uint16 mCompositeMapSize; - uint16 mCompositeMapSizeActual; - TexturePtr mCompositeMap; - Rect mCompositeMapDirtyRect; - unsigned long mCompositeMapUpdateCountdown; - unsigned long mLastMillis; - /// True if the updates included lightmap changes (widen) - bool mCompositeMapDirtyRectLightmapUpdate; - mutable MaterialPtr mCompositeMapMaterial; - - /// staging images read in prepere - typedef std::vector ImageList; - ImageList mCpuBlendMapStorage; - Image mCpuColourMap; - Image mCpuLightmap; - Image mCpuCompositeMap; - Image mCpuTerrainNormalMap; - - static NameGenerator msBlendTextureGenerator; - static NameGenerator msNormalMapNameGenerator; - static NameGenerator msLightmapNameGenerator; - static NameGenerator msCompositeMapNameGenerator; - - bool mLodMorphRequired; - bool mNormalMapRequired; - bool mLightMapRequired; - bool mLightMapShadowsOnly; - bool mCompositeMapRequired; - /// Texture storing normals for the whole terrain - TexturePtr mTerrainNormalMap; - - const Camera* mLastLODCamera; - unsigned long mLastLODFrame; - int mLastViewportHeight; - - Terrain* mNeighbours[NEIGHBOUR_COUNT]; - - GpuBufferAllocator* mCustomGpuBufferAllocator; - DefaultGpuBufferAllocator mDefaultGpuBufferAllocator; - - size_t getPositionBufVertexSize() const; - size_t getDeltaBufVertexSize() const; - - TerrainLodManager* mLodManager; - - public: - /** Increase Terrain's LOD level by 1 - @param synchronous Run synchronously - */ - void increaseLodLevel(bool synchronous = false); - /** Removes highest LOD level loaded - @remarks If there is LOD level load in progress it's load is canceled instead of removal of already loaded one. - */ - void decreaseLodLevel(); - - int getHighestLodPrepared() const { return (mLodManager) ? mLodManager->getHighestLodPrepared() : -1; }; - int getHighestLodLoaded() const { return (mLodManager) ? mLodManager->getHighestLodLoaded() : -1; }; - int getTargetLodLevel() const { return (mLodManager) ? mLodManager->getTargetLodLevel() : -1; }; - private: - /// Test a single quad of the terrain for ray intersection. - OGRE_FORCE_INLINE std::pair checkQuadIntersection(int x, int y, const Ray& ray) const; - }; - - - /** Options class which just stores default options for the terrain. - - None of these options are stored with the terrain when saved. They are - options that you can use to modify the behaviour of the terrain when it - is loaded or created. - @note - You should construct a single instance of this class per application and - do so before you start working with any other terrain classes. - */ - class _OgreTerrainExport TerrainGlobalOptions : public TerrainAlloc, public Singleton - { - protected: - - Real mSkirtSize; - Vector3 mLightMapDir; - bool mCastsShadows; - Real mMaxPixelError; - uint8 mRenderQueueGroup; - uint32 mVisibilityFlags; - uint32 mQueryFlags; - bool mUseRayBoxDistanceCalculation; - TerrainMaterialGeneratorPtr mDefaultMaterialGenerator; - uint16 mLayerBlendMapSize; - Real mDefaultLayerTextureWorldSize; - uint16 mDefaultGlobalColourMapSize; - uint16 mLightmapSize; - uint16 mCompositeMapSize; - ColourValue mCompositeMapAmbient; - ColourValue mCompositeMapDiffuse; - Real mCompositeMapDistance; - String mResourceGroup; - bool mUseVertexCompressionWhenAvailable; - - public: - TerrainGlobalOptions(); - ~TerrainGlobalOptions(); - - - /** The default size of 'skirts' used to hide terrain cracks - (default 10) - */ - Real getSkirtSize() const { return mSkirtSize; } - /** method - the default size of 'skirts' used to hide terrain cracks - (default 10) - - Changing this value only applies to Terrain instances loaded / reloaded afterwards. - */ - void setSkirtSize(Real skirtSz) { mSkirtSize = skirtSz; } - /// Get the shadow map light direction to use (world space) - const Vector3& getLightMapDirection() const { return mLightMapDir; } - /** Set the shadow map light direction to use (world space). */ - void setLightMapDirection(const Vector3& v) { mLightMapDir = v; } - /// Get the composite map ambient light to use - const ColourValue& getCompositeMapAmbient() const { return mCompositeMapAmbient; } - /// Set the composite map ambient light to use - void setCompositeMapAmbient(const ColourValue& c) { mCompositeMapAmbient = c; } - /// Get the composite map iffuse light to use - const ColourValue& getCompositeMapDiffuse() const { return mCompositeMapDiffuse; } - /// Set the composite map diffuse light to use - void setCompositeMapDiffuse(const ColourValue& c) { mCompositeMapDiffuse = c; } - /// Get the distance at which to start using a composite map if present - Real getCompositeMapDistance() const { return mCompositeMapDistance; } - /// Set the distance at which to start using a composite map if present - void setCompositeMapDistance(Real c) { mCompositeMapDistance = c; } - - - /** Whether the terrain will be able to cast shadows (texture shadows - only are supported, and you must be using depth shadow maps). - */ - bool getCastsDynamicShadows() const { return mCastsShadows; } - - /** Whether the terrain will be able to cast shadows (texture shadows - only are supported, and you must be using depth shadow maps). - This value can be set dynamically, and affects all existing terrains. - It defaults to false. - */ - void setCastsDynamicShadows(bool s) { mCastsShadows = s; } - - /** Get the maximum screen pixel error that should be allowed when rendering. */ - Real getMaxPixelError() const { return mMaxPixelError; } - - /** Set the maximum screen pixel error that should be allowed when rendering. - @note - This value can be varied dynamically and affects all existing terrains. - It will be weighted by the LOD bias on viewports. - */ - void setMaxPixelError(Real pixerr) { mMaxPixelError = pixerr; } - - /// Get the render queue group that this terrain will be rendered into - uint8 getRenderQueueGroup(void) const { return mRenderQueueGroup; } - /** Set the render queue group that terrains will be rendered into. - @remarks This applies to newly created terrains, after which they will - maintain their own queue group settings - */ - void setRenderQueueGroup(uint8 grp) { mRenderQueueGroup = grp; } - - /// Get the visbility flags that terrains will be rendered with - uint32 getVisibilityFlags(void) const { return mVisibilityFlags; } - /** Set the visbility flags that terrains will be rendered with - @remarks This applies to newly created terrains, after which they will - maintain their own settings - */ - void setVisibilityFlags(uint32 flags) { mVisibilityFlags = flags; } - - /** Set the default query flags for terrains. - @remarks This applies to newly created terrains, after which they will - maintain their own settings - */ - void setQueryFlags(uint32 flags) { mQueryFlags = flags; } - /** Get the default query flags for terrains. - */ - uint32 getQueryFlags(void) const { return mQueryFlags; } - - /** As setQueryFlags, except the flags passed as parameters are appended to the existing flags on this object. */ - void addQueryFlags(uint32 flags) { mQueryFlags |= flags; } - - /* As setQueryFlags, except the flags passed as parameters are removed from the existing flags on this object. */ - void removeQueryFlags(uint32 flags) { mQueryFlags &= ~flags; } - - /** Returns whether or not to use an accurate calculation of camera distance - from a terrain tile (ray / AABB intersection) or whether to use the - simpler distance from the tile centre. - */ - bool getUseRayBoxDistanceCalculation() const { return mUseRayBoxDistanceCalculation; } - - /** Sets whether to use an accurate ray / box intersection to determine - distance from a terrain tile, or whether to use the simple distance - from the tile centre. - Using ray/box intersection will result in higher detail terrain because - the LOD calculation is more conservative, assuming the 'worst case scenario' - of a large height difference at the edge of a tile. This is guaranteed to give you at least - the max pixel error or better, but will often give you more detail than - you need. Not using the ray/box method is cheaper but will only use - the max pixel error as a guide, the actual error will vary above and - below that. The default is not to use the ray/box approach. - */ - void setUseRayBoxDistanceCalculation(bool rb) { mUseRayBoxDistanceCalculation = rb; } - - /** Get the default material generator. - */ - TerrainMaterialGeneratorPtr getDefaultMaterialGenerator(); - - /** Set the default material generator. - */ - void setDefaultMaterialGenerator(const TerrainMaterialGeneratorPtr& gen); - - /** Get the default size of the blend maps for a new terrain. - */ - uint16 getLayerBlendMapSize() const { return mLayerBlendMapSize; } - - /** Sets the default size of blend maps for a new terrain. - This is the resolution of each blending layer for a new terrain. - Once created, this information will be stored with the terrain. - */ - void setLayerBlendMapSize(uint16 sz) { mLayerBlendMapSize = sz;} - - /** Get the default world size for a layer 'splat' texture to cover. - */ - Real getDefaultLayerTextureWorldSize() const { return mDefaultLayerTextureWorldSize; } - - /** Set the default world size for a layer 'splat' texture to cover. - */ - void setDefaultLayerTextureWorldSize(Real sz) { mDefaultLayerTextureWorldSize = sz; } - - /** Get the default size of the terrain global colour map for a new terrain. - */ - uint16 getDefaultGlobalColourMapSize() const { return mDefaultGlobalColourMapSize; } - - /** Set the default size of the terrain global colour map for a new terrain. - Once created, this information will be stored with the terrain. - */ - void setDefaultGlobalColourMapSize(uint16 sz) { mDefaultGlobalColourMapSize = sz;} - - - /** Get the default size of the lightmaps for a new terrain. - */ - uint16 getLightMapSize() const { return mLightmapSize; } - - /** Sets the default size of lightmaps for a new terrain. - */ - void setLightMapSize(uint16 sz) { mLightmapSize = sz;} - - /** Get the default size of the composite maps for a new terrain. - */ - uint16 getCompositeMapSize() const { return mCompositeMapSize; } - - /** Sets the default size of composite maps for a new terrain. - */ - void setCompositeMapSize(uint16 sz) { mCompositeMapSize = sz;} - - /** Set the default resource group to use to load / save terrains. - */ - void setDefaultResourceGroup(const String& grp) { mResourceGroup = grp; } - - /** Get the default resource group to use to load / save terrains. - */ - const String& getDefaultResourceGroup() const { return mResourceGroup; } - - /** Get whether to allow vertex compression to be used when the material - generator states that it supports it. - */ - bool getUseVertexCompressionWhenAvailable() const { return mUseVertexCompressionWhenAvailable; } - - /** Set whether to allow vertex compression to be used when the material - generator states that it supports it. - @note You should only call this before creating any terrain instances. - The default is true, so if a material generator supports compressed vertices, - and so does the hardware (this basically means shader support), they will be used). - However you can disable this in an emergency if required. - */ - void setUseVertexCompressionWhenAvailable(bool enable) { mUseVertexCompressionWhenAvailable = enable; } - - /// @copydoc Singleton::getSingleton() - static TerrainGlobalOptions& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static TerrainGlobalOptions* getSingletonPtr(void); - - - }; - - - /** @} */ - /** @} */ -} - - - - -#endif diff --git a/Components/Terrain/include/OgreTerrain.i b/Components/Terrain/include/OgreTerrain.i deleted file mode 100644 index aa43378c632..00000000000 --- a/Components/Terrain/include/OgreTerrain.i +++ /dev/null @@ -1,43 +0,0 @@ -#ifdef SWIGPYTHON -%module(package="Ogre") Terrain -#else -%module OgreTerrain -#endif -%{ -/* Includes the header in the wrapper code */ -#include "Ogre.h" -#include "OgreDefaultDebugDrawer.h" -#include "OgreTerrainLayerBlendMap.h" -#include "OgreTerrainMaterialGeneratorA.h" -#include "OgreTerrain.h" -#include "OgreTerrainQuadTreeNode.h" -#include "OgreTerrainAutoUpdateLod.h" -#include "OgreTerrainGroup.h" -%} - -%include std_string.i -%include std_vector.i -%include exception.i -%import "Ogre.i" - -#define _OgreTerrainExport -#define __inline -#define __forceinline - -%ignore Ogre::TerrainMaterialGenerator::setActiveProfile; -%include "OgreTerrainMaterialGenerator.h" -%include "OgreTerrainMaterialGeneratorA.h" - -%include "OgreTerrainLayerBlendMap.h" -%include "OgreTerrainQuadTreeNode.h" - -%template(LayerInstanceList) std::vector; -%template(TerrainRayResult) std::pair; -%include "OgreTerrain.h" - -%ignore Ogre::TerrainGroup::rayIntersects; -%ignore Ogre::TerrainGroup::getTerrainIterator; // deprecated -%include "OgreTerrainGroup.h" - -%include "OgreTerrainLodManager.h" -%include "OgreTerrainPrerequisites.h" diff --git a/Components/Terrain/include/OgreTerrainAutoUpdateLod.h b/Components/Terrain/include/OgreTerrainAutoUpdateLod.h deleted file mode 100644 index 8f7d855ad38..00000000000 --- a/Components/Terrain/include/OgreTerrainAutoUpdateLod.h +++ /dev/null @@ -1,111 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_TerrainAutoUpdateLod_H__ -#define __Ogre_TerrainAutoUpdateLod_H__ - -#include "OgreTerrainPrerequisites.h" - -namespace Ogre -{ - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Terrain - * Some details on the terrain auto load - * @{ - */ - - /** Terrain automatic LOD loading - @par - This set of classes is used for automatic change of terrain LOD level. Base is TerrainAutoUpdateLod interface with just - one public method autoUpdateLod. This method gets called by terrain whenever user thinks something has - changed(typically in application's main loop) what could affect terrain's LOD level. It is designed in such a way - so user can use whatever algorithm he likes to change terrain's LOD level. For example see TerrainAutoUpdateLod - implementation TerrainAutoUpdateLodByDistance. - It is also used as a null object for auto-LOD-updating. - */ - class _OgreTerrainExport TerrainAutoUpdateLod : public TerrainAlloc - { - public: - virtual ~TerrainAutoUpdateLod() {} - /** Method to be called to change terrain's LOD level. - @param terrain Instance of Terrain which LOD level is going to be changed - @param synchronous Run this as part of main thread or in background - @param data Any user specific data. - */ - virtual void autoUpdateLod(Terrain *terrain, bool synchronous, const Any &data) = 0; - virtual uint32 getStrategyId() = 0; - }; - - // other Strategy's id start from 2 - enum TerrainAutoUpdateLodStrategy - { - NONE = 0, - BY_DISTANCE = 1 - }; - - /** Class implementing TerrainAutoUpdateLod interface. It does LOD level increase/decrease according to camera's - distance to Terrain. - */ - class _OgreTerrainExport TerrainAutoUpdateLodByDistance : public TerrainAutoUpdateLod - { - public: - void autoUpdateLod(Terrain *terrain, bool synchronous, const Any &data) override; - uint32 getStrategyId() override { return BY_DISTANCE; } - - private: - /** Modifies Terrain's LOD level according to it's distance from camera. - @param holdDistance How far ahead of terrain's LOD level change this LOD level should be loaded. - */ - void autoUpdateLodByDistance(Terrain *terrain, bool synchronous, const Real holdDistance); - /// Traverse Terrain's QuadTree and calculate what LOD level is needed. - int traverseTreeByDistance(TerrainQuadTreeNode *node, const Camera *cam, Real cFactor, const Real holdDistance); - }; - - class _OgreTerrainExport TerrainAutoUpdateLodFactory - { - public: - static TerrainAutoUpdateLod* getAutoUpdateLod( uint32 strategy ) - { - switch(strategy) - { - case BY_DISTANCE: - return OGRE_NEW TerrainAutoUpdateLodByDistance; - case NONE: - default: - return 0; - } - return 0; - } - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/Components/Terrain/include/OgreTerrainGroup.h b/Components/Terrain/include/OgreTerrainGroup.h deleted file mode 100644 index 34e5534aa52..00000000000 --- a/Components/Terrain/include/OgreTerrainGroup.h +++ /dev/null @@ -1,568 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_TerrainGroup_H__ -#define __Ogre_TerrainGroup_H__ - -#include "OgreTerrainPrerequisites.h" -#include "OgreTerrain.h" -#include "OgreWorkQueue.h" -#include "OgreIteratorWrapper.h" -#include "OgreConfigFile.h" - -namespace Ogre -{ - class TerrainAutoUpdateLod; - - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Terrain - * Some details on the terrain component - * @{ - */ - - /** Helper class to assist you in managing multiple terrain instances - that are connected to each other. - - This class makes it easy to specify the same options for a group of - terrain instances and have them positioned relative to each other and - associated via each other's neighbour connections. You can do all this - manually but this class just makes things easier, so that you only - have to specify most options once. - @par - Terrains are maintained in a grid of entries, and for simplicity - the grid cells are indexed from 0 as a 'centre' slot, supporting both - positive and negative values. so (0,0) is the centre slot, (1,0) is the - slot to the right of the centre, (1,0) is the slot above the centre, (-2,1) - is the slot two to the left of the centre and one up, etc. The maximum - extent of each axis is -32768 to +32767, so in other words enough for - over 4 billion entries. That should be enough for anyone! - @par - Note that this is not a 'paging' class as such. It's simply a way to make it easier to - perform common tasks with multiple terrain instances, which you choose when - to define, load and remove. Automatic paging is handled separately by the Paging - component. - */ - class _OgreTerrainExport TerrainGroup - { - public: - /** Constructor. - @param sm The SceneManager which will parent the terrain instances. - @param align The alignment that all terrain instances will use - @param terrainSize The size of each terrain down one edge in vertices (2^n+1) - @param terrainWorldSize The world size of each terrain instance - */ - TerrainGroup(SceneManager* sm, Terrain::Alignment align, uint16 terrainSize, - Real terrainWorldSize); - /** Alternate constructor. - - You can ONLY use this constructor if you subsequently call loadGroupDefinition - or loadLegacyTerrain to populate the rest. - */ - TerrainGroup(SceneManager* sm); - virtual ~TerrainGroup(); - - /** Retrieve a shared structure which will provide the base settings for - all terrains created via this group. - - All neighbouring terrains should have the same basic settings (particularly - the size parameters) - to avoid having to set the terrain import information - more than once, you can retrieve the standard settings for this group - here and modify them to your needs. Once you've done that you can - use the shortcut methods in this class to create new terrain instances - using these base settings (plus any per-instance settings you might - want to use). - @note - The structure returned from this method is intended for in-place modification, - that's why it is not const and there is no equivalent 'set' method. - You should not, however, change the alignment or any of the size parameters - after you start constructing instances, since neighbouring terrains - should have the same size & alignment. - */ - virtual Terrain::ImportData& getDefaultImportSettings() { return mDefaultImportData; } - - /** Define the centre position of the grid of terrain. - */ - virtual void setOrigin(const Vector3& pos); - - /** Retrieve the centre position of the grid of terrain. - */ - virtual const Vector3& getOrigin() const { return mOrigin; } - - /** Retrieve the alignment of the grid of terrain (cannot be modified after construction). - */ - virtual Terrain::Alignment getAlignment() const { return mAlignment; } - - /** Retrieve the world size of each terrain instance - */ - virtual Real getTerrainWorldSize() const { return mTerrainWorldSize; } - /** Set the world size of terrain. - @note This will cause the terrains to change position due to their size change - @param newWorldSize the new world size of each terrain instance - */ - virtual void setTerrainWorldSize(Real newWorldSize); - /** Retrieve the size of each terrain instance in number of vertices down one side - */ - virtual uint16 getTerrainSize() const { return mTerrainSize; } - /** Set the size of each terrain instance in number of vertices down one side. - @note This will cause the height data in each nested terrain to be bilinear - filtered to fit the new data size. - @param newTerrainSize the new map size of each terrain instance - */ - virtual void setTerrainSize(uint16 newTerrainSize); - /** Retrieve the SceneManager being used for this group. - */ - virtual SceneManager* getSceneManager() const { return mSceneManager; } - - /** Set the naming convention for file names in this terrain group. - - You can more easily generate file names for saved / loaded terrain slots - if you define a naming prefix. When you call saveAllTerrains(), all the - terrain instances currently loaded will be saved to a file named - <prefix>_<index>.<extension>, where <index> is - given by packing the x and y coordinates of the entry into a 32-bit - index (@see packIndex). - */ - void setFilenameConvention(const String& prefix, const String& extension); - /// @see setFilenameConvention - void setFilenamePrefix(const String& prefix); - /// @see setFilenameConvention - void setFilenameExtension(const String& extension); - /// @see setFilenameConvention - const String& getFilenamePrefix() const { return mFilenamePrefix; } - /// @see setFilenameConvention - const String& getFilenameExtension() const { return mFilenameExtension; } - - /** Set the resource group in which files will be located. */ - void setResourceGroup(const String& grp) { mResourceGroup = grp; } - /** Get the resource group in which files will be located. */ - const String& getResourceGroup() const { return mResourceGroup; } - /** Define a 'slot' in the terrain grid - in this case to be loaded from - a generated file name. - - At this stage the terrain instance isn't actually present in the grid, - you're merely expressing an intention for it to take its place there - once it's loaded. The reason we do it like this is to support - background preparation of this terrain instance. - @note This method assumes that you want a file name to be generated from - the naming convention that you have supplied (@see setFilenameConvention). - If a file of that name isn't found during loading, then a flat terrain is - created instead at height 0. - @param x, y The coordinates of the terrain slot relative to the centre slot (signed). - */ - virtual void defineTerrain(long x, long y); - - /** Define a 'slot' in the terrain grid - in this case a flat terrain. - - At this stage the terrain instance isn't actually present in the grid, - you're merely expressing an intention for it to take its place there - once it's loaded. The reason we do it like this is to support - background preparation of this terrain instance. - @param x, y The coordinates of the terrain slot relative to the centre slot (signed). - @param constantHeight The constant, uniform height that you want the terrain - to start at - */ - virtual void defineTerrain(long x, long y, float constantHeight); - - /** Define the content of a 'slot' in the terrain grid. - - At this stage the terrain instance isn't actually present in the grid, - you're merely expressing an intention for it to take its place there - once it's loaded. The reason we do it like this is to support - background preparation of this terrain instance. - @param x, y The coordinates of the terrain slot relative to the centre slot (signed). - @param importData Import data - this data is copied during the - call so you may destroy your copy afterwards. - */ - virtual void defineTerrain(long x, long y, const Terrain::ImportData* importData); - - /** Define the content of a 'slot' in the terrain grid. - - At this stage the terrain instance isn't actually present in the grid, - you're merely expressing an intention for it to take its place there - once it's loaded. The reason we do it like this is to support - background preparation of this terrain instance. - @param x, y The coordinates of the terrain slot relative to the centre slot (signed). - @param img Heightfield image - this data is copied during the call so you may destroy your copy afterwards. - @param layers Optional texture layers to use (if not supplied, default import - data layers will be used) - this data is copied during the - call so you may destroy your copy afterwards. - */ - virtual void defineTerrain(long x, long y, const Image* img, const Terrain::LayerInstanceList* layers = 0); - - /** Define the content of a 'slot' in the terrain grid. - - At this stage the terrain instance isn't actually present in the grid, - you're merely expressing an intention for it to take its place there - once it's loaded. The reason we do it like this is to support - background preparation of this terrain instance. - @param x, y The coordinates of the terrain slot relative to the centre slot (signed). - @param pFloat Heights array - @param layers Optional texture layers to use (if not supplied, default import - data layers will be used) - this data is copied during the - call so you may destroy your copy afterwards. - */ - virtual void defineTerrain(long x, long y, const float* pFloat, const Terrain::LayerInstanceList* layers = 0); - - /** Define the content of a 'slot' in the terrain grid. - - At this stage the terrain instance isn't actually present in the grid, - you're merely expressing an intention for it to take its place there - once it's loaded. The reason we do it like this is to support - background preparation of this terrain instance. - @param x, y The coordinates of the terrain slot relative to the centre slot (signed). - @param filename The name of a file which fully defines the terrain (as - written by Terrain::save). Size settings from all files must agree. - */ - virtual void defineTerrain(long x, long y, const String& filename); - - - /** Load any terrain instances that have been defined but not loaded yet. - @param synchronous Whether we should force this to happen entirely in the - primary thread - */ - virtual void loadAllTerrains(bool synchronous = false); - - /** Load a specific terrain slot based on the definition that has already - been supplied. - @param x, y The coordinates of the terrain slot relative to the centre slot (signed). - @copydetails loadAllTerrains - */ - virtual void loadTerrain(long x, long y, bool synchronous = false); - - /** Load a terrain.cfg as used by the terrain scene manager into a single terrain slot - * - * automatically configures the SM2Profile if it is used. - * @attention not all of the legacy parameters/ parameter combinations are supported - * @param cfgFilename .cfg file that specifices what textures/scale/mipmaps/etc to use. - * @param x, y The coordinates of the terrain slot relative to the centre slot (signed). - * @copydetails loadAllTerrains - */ - void loadLegacyTerrain(const String& cfgFilename, long x = 0, long y = 0, bool synchronous = true); - - /// @overload - void loadLegacyTerrain(const ConfigFile& cfg, long x = 0, long y = 0, bool synchronous = true); - - /** Unload a specific terrain slot. - - This destroys the Terrain instance but retains the slot definition (so - it would be reloaded next time you call loadAllTerrains() if you did not - remove it beforehand). - @note - While the definition of the terrain is kept, if you used import data - to populate it, this will have been lost so repeat loading cannot occur. - The only way to support repeat loading is via the 'filename' option of - defineTerrain instead. - @param x, y The coordinates of the terrain slot relative to the centre slot (signed). - */ - virtual void unloadTerrain(long x, long y); - - /** Remove a specific terrain slot. - - This destroys any Terrain instance at this position and also removes the - definition, so it essentially no longer exists. - @param x, y The coordinates of the terrain slot relative to the centre slot (signed). - */ - virtual void removeTerrain(long x, long y); - - /** Remove all terrain instances. - */ - void removeAllTerrains(); - - /** Save all terrain instances using the assigned file names, or - via the filename convention. - @see setFilenameConvention - @see setResourceGroup - @param onlyIfModified If true, only terrains that have been modified since load(), - or since the last save(), will be saved. You want to set this to true if - you loaded the terrain from these same files, but false if you - defined them using some other input data since the files wouldn't exist. - @param replaceManualFilenames If true, replaces any manually defined filenames - in the TerrainSlotDefinition with the generated names from the convention. - This is recommended since it makes everything more consistent, although - you might want to use manual filenames in the original definition to import - previously separate data. - */ - void saveAllTerrains(bool onlyIfModified, bool replaceManualFilenames = true); - - /** Definition of how to populate a 'slot' in the terrain group. - */ - struct _OgreTerrainExport TerrainSlotDefinition - { - /// Filename, if this is to be loaded from a file - String filename; - /// Import data, if this is to be defined based on importing - Terrain::ImportData* importData; - - TerrainSlotDefinition() :importData(0) {} - ~TerrainSlotDefinition(); - - /// Set to use import data - void useImportData(); - /// Set to use file name - void useFilename(); - /// Destroy temp import resources - void freeImportData(); - }; - - /** Slot for a terrain instance, together with its definition. */ - struct _OgreTerrainExport TerrainSlot : public TerrainAlloc - { - /// The coordinates of the terrain slot relative to the centre slot (signed). - long x, y; - /// Definition used to load the terrain - TerrainSlotDefinition def; - /// Actual terrain instance - Terrain* instance; - - TerrainSlot(long _x, long _y) : x(_x), y(_y), instance(0) {} - virtual ~TerrainSlot(); - void freeInstance(); - }; - - /** Get the definition of a slot in the terrain. - - Definitions exist before the actual instances to allow background loading. - @param x, y The coordinates of the terrain slot relative to the centre slot (signed). - @return The definition, or null if nothing is in this slot. While this return value is - not const, you should be careful about modifying it; it will have no effect unless you load - the terrain afterwards, and can cause a race condition if you modify it while a background - load is in progress. - */ - virtual TerrainSlotDefinition* getTerrainDefinition(long x, long y) const; - - /** Get the terrain instance at a given slot, if loaded. - @param x, y The coordinates of the terrain slot relative to the centre slot (signed). - @return The terrain, or null if no terrain is loaded in this slot (call getTerrainDefinition if - you want to access the definition before it is loaded). - */ - virtual Terrain* getTerrain(long x, long y) const; - - /** Free as many resources as possible for optimal run-time memory use for all - terrain tiles. - @see Terrain::freeTemporaryResources - */ - void freeTemporaryResources(); - - /** Trigger the update process for all terrain instances. - @see Terrain::update - */ - void update(bool synchronous = false); - - /** Performs an update on all terrain geometry. - @see Terrain::updateGeometry - */ - void updateGeometry(); - - /** Updates derived data for all terrains (LOD, lighting) to reflect changed height data. - @see Terrain::updateDerivedData - */ - void updateDerivedData(bool synchronous = false, uint8 typeMask = 0xFF); - - /** Result from a terrain ray intersection with the terrain group. - */ - struct _OgreTerrainExport RayResult - { - /// Whether an intersection occurred - bool hit; - /// Which terrain instance was hit, if any - Terrain* terrain; - /// Position at which the intersection occurred - Vector3 position; - - RayResult(bool _hit, Terrain* _terrain, const Vector3& _pos) - : hit(_hit), terrain(_terrain), position(_pos) {} - }; - - /** Get the height data for a given world position (projecting the point - down on to the terrain underneath). - @param x, y,z Position in world space. Positions will be clamped to the edge - of the terrain - @param ppTerrain Pointer to a pointer to a terrain which will be completed - with the terrain that was found to resolve this query, or null if none were - */ - float getHeightAtWorldPosition(Real x, Real y, Real z, Terrain** ppTerrain = 0); - - /** Get the height data for a given world position (projecting the point - down on to the terrain). - @param pos Position in world space. Positions will be clamped to the edge - of the terrain - @param ppTerrain Pointer to a pointer to a terrain which will be completed - with the terrain that was found to resolve this query, or null if none were - */ - float getHeightAtWorldPosition(const Vector3& pos, Terrain** ppTerrain = 0); - - /** Test for intersection of a given ray with any terrain in the group. If the ray hits - a terrain, the point of intersection and terrain instance is returned. - @param ray The ray to test for intersection - @param distanceLimit The distance from the ray origin at which we will stop looking, - 0 indicates no limit - @return A result structure which contains whether the ray hit a terrain and if so, where. - @remarks This can be called from any thread as long as no parallel write to - the terrain data occurs. - */ - RayResult rayIntersects(const Ray& ray, Real distanceLimit = 0) const; - - typedef std::vector TerrainList; - /** Test intersection of a box with the terrain. - - Tests an AABB for overlap with a terrain bounding box. Note that this does not mean that the box - touches the terrain itself, just the bounding box for the terrain. You can use this to get region - results for further testing or use (e.g. painting areas). - @param box The AABB you want to test in world units - @param resultList Pointer to a list of terrain pointers which will be updated to include just - the terrains that overlap - */ - void boxIntersects(const AxisAlignedBox& box, TerrainList* resultList) const; - /** Test intersection of a sphere with the terrain. - - Tests a sphere for overlap with a terrain bounding box. Note that this does not mean that the sphere - touches the terrain itself, just the bounding box for the terrain. You can use this to get region - results for further testing or use (e.g. painting areas). - @param sphere The sphere you want to test in world units - @param resultList Pointer to a list of terrain pointers which will be updated to include just - the terrains that overlap - */ - void sphereIntersects(const Sphere& sphere, TerrainList* resultList) const; - - /** Convert a world position to terrain slot coordinates. - @param pos The world position - @param x,y Pointers to the coordinates to be completed. - */ - void convertWorldPositionToTerrainSlot(const Vector3& pos, long *x, long *y) const; - - /** Convert a slot location to a world position at the centre - @param x,y The slot coordinates - @param pos Pointer to the world position to be completed - */ - void convertTerrainSlotToWorldPosition(long x, long y, Vector3* pos) const; - - /** Calls Terrain::isDerivedDataUpdateInProgress on each loaded instance and returns true - if any of them are undergoing a derived update. - */ - bool isDerivedDataUpdateInProgress() const; - - /// Packed map, signed 16 bits for each axis from -32767 to +32767 - typedef std::map TerrainSlotMap; - typedef MapIterator TerrainIterator; - typedef ConstMapIterator ConstTerrainIterator; - - /// @deprecated use getTerrainSlots() - OGRE_DEPRECATED TerrainIterator getTerrainIterator(); - /// @deprecated use getTerrainSlots() - OGRE_DEPRECATED ConstTerrainIterator getTerrainIterator() const; - - /// Get the defined terrains - const TerrainSlotMap& getTerrainSlots() const { return mTerrainSlots; } - - /// Convert coordinates to a packed integer index - uint32 packIndex(long x, long y) const; - - /// Convert a packed integer index to coordinates - void unpackIndex(uint32 key, long *x, long *y); - - /// Generate a file name based on the current naming convention - String generateFilename(long x, long y) const; - - /** Save the group data only in native form to a file. - */ - void saveGroupDefinition(const String& filename); - /** Save the group data only in native form to a serializing stream. - */ - void saveGroupDefinition(StreamSerialiser& stream); - /** Load the group definition only in native form from a file. - */ - void loadGroupDefinition(const String& filename); - /** Load the group definition only in native form from a serializing stream. - */ - void loadGroupDefinition(StreamSerialiser& stream); - - static const uint32 CHUNK_ID; - static const uint16 CHUNK_VERSION; - - /// Loads terrain's next LOD level. - void increaseLodLevel(long x, long y, bool synchronous = false); - /// Removes terrain's highest LOD level. - void decreaseLodLevel(long x, long y); - - void setAutoUpdateLod(TerrainAutoUpdateLod* updater); - /// Automatically checks if terrain's LOD level needs to be updated. - void autoUpdateLod(long x, long y, bool synchronous, const Any &data); - void autoUpdateLodAll(bool synchronous, const Any &data); - - /** Get the number of terrains that are still waiting for the Terrain::prepare() to be called. - * - * @note Terrain::prepare() happens in background thread so the actual call will be completed - * a bit before this returns the reduced number. - * - * @return Amount of terrain prepare requests pending. - */ - size_t getNumTerrainPrepareRequests() const; - - private: - typedef std::map TerrainPrepareRequestMap; - SceneManager *mSceneManager; - Terrain::Alignment mAlignment; - uint16 mTerrainSize; - Real mTerrainWorldSize; - Terrain::ImportData mDefaultImportData; - Vector3 mOrigin; - TerrainSlotMap mTerrainSlots; - TerrainPrepareRequestMap mTerrainPrepareRequests; - String mFilenamePrefix; - String mFilenameExtension; - String mResourceGroup; - TerrainAutoUpdateLod *mAutoUpdateLod; - Terrain::DefaultGpuBufferAllocator mBufferAllocator; - - /// Get the position of a terrain instance - Vector3 getTerrainSlotPosition(long x, long y); - /// Retrieve a slot, potentially allocate one - TerrainSlot* getTerrainSlot(long x, long y, bool createIfMissing); - TerrainSlot* getTerrainSlot(long x, long y) const; - void freeTerrainSlotInstance(TerrainSlot* slot); - void connectNeighbour(TerrainSlot* slot, long offsetx, long offsety); - - void loadTerrainImpl(TerrainSlot* slot, bool synchronous); - - /// WorkQueue::RequestHandler override - WorkQueue::Response* handleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ); - /// WorkQueue::ResponseHandler override - void handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ); - - }; - - - /** @} */ - /** @} */ - -} - -#endif - diff --git a/Components/Terrain/include/OgreTerrainLayerBlendMap.h b/Components/Terrain/include/OgreTerrainLayerBlendMap.h deleted file mode 100644 index dd6ff5553d6..00000000000 --- a/Components/Terrain/include/OgreTerrainLayerBlendMap.h +++ /dev/null @@ -1,197 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_TerrainLayerBlendMap_H__ -#define __Ogre_TerrainLayerBlendMap_H__ - -#include "OgreTerrainPrerequisites.h" -#include "OgreCommon.h" -#include "OgreDataStream.h" -#include "OgreImage.h" - -namespace Ogre -{ - class Image; - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Terrain - * Some details on the terrain component - * @{ - */ - - - /** Class exposing an interface to a blend map for a given layer. - Each layer after the first layer in a terrain has a blend map which - expresses how it is alpha blended with the layers beneath. Internally, this - blend map is packed into one channel of an RGBA texture in - order to use the smallest number of samplers, but this class allows - a caller to manipulate the data more easily without worrying about - this packing. Also, the values you use to interact with the blend map are - floating point, which gives you full precision for updating, but in fact the - values are packed into 8-bit integers in the actual blend map. - @par - You shouldn't construct this class directly, use Terrain::getLayerBlendMap(). - */ - class _OgreTerrainExport TerrainLayerBlendMap : public TerrainAlloc - { - Terrain* mParent; - uint8 mLayerIdx; - uint8 mChannel; // RGBA - uint8 mChannelOffset; // in pixel format - Box mDirtyBox; - bool mDirty; - HardwarePixelBuffer* mBuffer; - Image mData; - - void download(); - void upload(); - - public: - /** Constructor - @param parent The parent terrain - @param layerIndex The layer index (should be 1 or higher) - @param buf The buffer holding the data - */ - TerrainLayerBlendMap(Terrain* parent, uint8 layerIndex, HardwarePixelBuffer* buf); - virtual ~TerrainLayerBlendMap(); - /// Get the parent terrain - Terrain* getParent() const { return mParent; } - /// Get the index of the layer this is targeting - uint8 getLayerIndex() const { return mLayerIdx; } - - /** Helper method - convert a point in world space to UV space based on the - terrain settings. - @param worldPos World position - @param outX, outY Pointers to variables which will be filled in with the - local UV space value. Note they are deliberately signed Real values, because the - point you supply may be outside of image space and may be between texels. - The values will range from 0 to 1, top/bottom, left/right. - */ - void convertWorldToUVSpace(const Vector3& worldPos, Real *outX, Real* outY); - - /** Helper method - convert a point in local space to worldspace based on the - terrain settings. - @param x,y Local position, ranging from 0 to 1, top/bottom, left/right. - @param outWorldPos Pointer will be filled in with the world space value - */ - void convertUVToWorldSpace(Real x, Real y, Vector3* outWorldPos); - - /** Convert local space values (0,1) to image space (0, imageSize). - */ - void convertUVToImageSpace(Real x, Real y, size_t* outX, size_t* outY); - /** Convert image space (0, imageSize) to local space values (0,1). - */ - void convertImageToUVSpace(size_t x, size_t y, Real* outX, Real* outY); - /** Convert image space (0, imageSize) to terrain space values (0,1). - */ - void convertImageToTerrainSpace(size_t x, size_t y, Real* outX, Real* outY); - /** Convert terrain space values (0,1) to image space (0, imageSize). - */ - void convertTerrainToImageSpace(Real x, Real y, size_t* outX, size_t* outY); - - /** Get a single value of blend information, in image space. - @param x,y Coordinates of the point of data to get, in image space (top down) - @return The blend data - */ - float getBlendValue(uint32 x, uint32 y); - - /** Set a single value of blend information (0 = transparent, 255 = solid) - @param x,y Coordinates of the point of data to get, in image space (top down) - @param val The blend value to set (0..1) - */ - void setBlendValue(uint32 x, uint32 y, float val); - - /** Get a pointer to the whole blend data. - - This method allows you to get a raw pointer to all the blend data, to - update it as you like. However, you must then call dirtyRect manually - if you want those changes to be recognised. - */ - float* getBlendPointer(); - - /** Indicate that all of the blend data is dirty and needs updating. - */ - void dirty(); - - /** Indicate that a portion of the blend data is dirty and needs updating. - @param rect Rectangle in image space - */ - void dirtyRect(const Rect& rect); - - /** Blits a set of values into a region on the blend map. - @param src PixelBox containing the source pixels and format - @param dstBox Box describing the destination region in this map - @remarks The source and destination regions dimensions don't have to match, in which - case scaling is done. - @note You can call this method in a background thread if you want. - You still need to call update() to commit the changes to the GPU. - */ - void blit(const PixelBox &src, const Box &dstBox); - - /** Blits a set of values into the entire map. The source data is scaled if needed. - @param src PixelBox containing the source pixels and format - @note You can call this method in a background thread if you want. - You still need to call update() to commit the changes to the GPU. - - */ - void blit(const PixelBox &src); - - /** Load an image into this blend layer. - */ - void loadImage(const Image& img); - - /** Load an image into this blend layer. - @param stream Stream containing the image data - @param ext Extension identifying the image type, if the stream data doesn't identify - */ - void loadImage(DataStreamPtr& stream, const String& ext = BLANKSTRING); - - /** Load an image into this blend layer. - */ - void loadImage(const String& filename, const String& groupName); - - /** Publish any changes you made to the blend data back to the blend map. - @note - Can only be called in the main render thread. - */ - void update(); - - - }; - - typedef std::vector TerrainLayerBlendMapList; - - /** @} */ - /** @} */ - -} - - - -#endif diff --git a/Components/Terrain/include/OgreTerrainLodManager.h b/Components/Terrain/include/OgreTerrainLodManager.h deleted file mode 100644 index af2624ddd94..00000000000 --- a/Components/Terrain/include/OgreTerrainLodManager.h +++ /dev/null @@ -1,164 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_TerrainLodManager_H__ -#define __Ogre_TerrainLodManager_H__ - -#include "OgreTerrainPrerequisites.h" -#include "OgreWorkQueue.h" - - -namespace Ogre -{ - class Terrain; - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Terrain - * Some details on the terrain LOD manager - * @{ - */ - - /** Terrain LOD data manager - @par - This class is used for managing terrain LOD data's loading, unloading. - */ - - class _OgreTerrainExport TerrainLodManager - { - public: - static const uint32 TERRAINLODDATA_CHUNK_ID; - static const uint16 TERRAINLODDATA_CHUNK_VERSION; - typedef std::vector LodData; - typedef std::vector LodsData; - - struct LoadLodRequest - { - LoadLodRequest( TerrainLodManager* r, uint16 preparedLod, uint16 loadedLod, uint16 target ) - : requestee(r) - , currentPreparedLod(preparedLod) - , currentLoadedLod(loadedLod) - , requestedLod(target) - { - } - TerrainLodManager* requestee; - uint16 currentPreparedLod; - uint16 currentLoadedLod; - uint16 requestedLod; - }; - - struct LodInfo - { - uint treeStart; - uint treeEnd; - bool isLast; - uint16 resolution; - uint size; - }; - public: - TerrainLodManager(Terrain* t, DataStreamPtr& stream); - TerrainLodManager(Terrain* t, const String& filename = ""); - virtual ~TerrainLodManager(); - - void open(const String& filename); - void close(); - bool isOpen() const; - - void updateToLodLevel(int lodLevel, bool synchronous = false); - /// Save each LOD level separately compressed so seek is possible - static void saveLodData(StreamSerialiser& stream, Terrain* terrain); - - /** Copy geometry data from buffer to mHeightData/mDeltaData - @param lodLevel A LOD level to work with - @param data, dataSize Buffer which holds geometry data if separated form - @remarks Data in buffer has to be both height and delta data. First half is height data. - Seconds half is delta data. - */ - void fillBufferAtLod(uint lodLevel, const float* data, uint dataSize ); - /** Read separated geometry data from file into allocated memory - @param lowerLodBound Lower bound of LOD levels to load - @param higherLodBound Upper bound of LOD levels to load - @remarks Geometry data are uncompressed using inflate() and stored into - allocated buffer - */ - void readLodData(uint16 lowerLodBound, uint16 higherLodBound); - void waitForDerivedProcesses(); - - int getHighestLodPrepared(){ return mHighestLodPrepared; } - int getHighestLodLoaded(){ return mHighestLodLoaded; } - int getTargetLodLevel(){ return mTargetLodLevel; } - - LodInfo& getLodInfo(uint lodLevel) - { - if(!mLodInfoTable) - buildLodInfoTable(); - return mLodInfoTable[lodLevel]; - } - private: - WorkQueue::Response* handleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ); - void handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ); - - void init(); - void buildLodInfoTable(); - - /** Separate geometry data by LOD level - @param data A geometry data to separate i.e. mHeightData/mDeltaData - @param size Dimension of the input data - @param numLodLevels Number of LOD levels in the input data - @param lods The separated LOD data - @remarks Allocates new array and fills it with geometry data coupled by LOD level from lowest LOD level to highest. Example: - before separation: - 00 01 02 03 04 - 05 06 07 08 09 - 10 11 12 13 14 - 15 16 17 18 19 - 20 21 22 23 24 - after separation: - 2: 00 04 20 24 - 1: 02 10 12 14 22 - 0: 01 03 05 06 07 08 09 11 13 15 16 17 18 19 21 23 - */ - static void separateData(float* data, uint16 size, uint16 numLodLevels, LodsData& lods ); - private: - Terrain* mTerrain; - DataStreamPtr mDataStream; - size_t mStreamOffset; - - LodInfo* mLodInfoTable; - int mTargetLodLevel; /// Which LOD level is demanded - int mHighestLodPrepared; /// Highest LOD level stored in memory i.e. mHeightData/mDeltaData - int mHighestLodLoaded; /// Highest LOD level loaded in GPU - - bool mIncreaseLodLevelInProgress; /// Is increaseLodLevel() running? - bool mLastRequestSynchronous; - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/Components/Terrain/include/OgreTerrainMaterialGenerator.h b/Components/Terrain/include/OgreTerrainMaterialGenerator.h deleted file mode 100644 index ea2cbeb58b1..00000000000 --- a/Components/Terrain/include/OgreTerrainMaterialGenerator.h +++ /dev/null @@ -1,201 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_TerrainMaterialGenerator_H__ -#define __Ogre_TerrainMaterialGenerator_H__ - -#include "OgreTerrainPrerequisites.h" -#include "OgrePixelFormat.h" -#include "OgreSharedPtr.h" - -namespace Ogre -{ - class Rectangle2D; - class Terrain; - - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Terrain - * Some details on the terrain component - * @{ - */ - - /** Description of a sampler that will be used with each layer. - */ - struct _OgreTerrainExport TerrainLayerSampler - { - /// A descriptive name that is merely used to assist in recognition - String alias; - /// The format required of this texture - PixelFormat format; - - TerrainLayerSampler() - : alias(""), format(PF_UNKNOWN) - { - } - - TerrainLayerSampler(const String& aliasName, PixelFormat fmt) - : alias(aliasName), format(fmt) - { - } - }; - /** The definition of the information each layer will contain in this terrain. - All layers must contain the same structure of information, although the - input textures can be different per layer instance. - */ - typedef std::vector TerrainLayerDeclaration; - - /** Class that provides functionality to generate materials for use with a terrain. - - Terrains are composed of one or more layers of texture information, and - require that a material is generated to render them. There are various approaches - to rendering the terrain, which may vary due to: -
  • Hardware support (static)
  • -
  • Texture instances assigned to a particular terrain (dynamic in an editor)
  • -
  • User selection (e.g. changing to a cheaper option in order to increase performance, - or in order to test how the material might look on other hardware (dynamic)
  • -
- Subclasses of this class are responsible for responding to these factors and - to generate a terrain material. - */ - class _OgreTerrainExport TerrainMaterialGenerator : public TerrainAlloc - { - public: - struct Profile - { - virtual ~Profile() {} - }; - - TerrainMaterialGenerator(); - virtual ~TerrainMaterialGenerator(); - - /// Get the active profile - virtual Profile* getActiveProfile() const { return NULL; } - - /// Internal method - indicates that a change has been made that would require material regeneration - void _markChanged() { ++mChangeCounter; } - - /** Returns the number of times the generator has undergone a change which - would require materials to be regenerated. - */ - unsigned long long int getChangeCount() const { return mChangeCounter; } - - /** Get the layer declaration that this material generator operates with. - */ - const TerrainLayerDeclaration& getLayerDeclaration() const { return mLayerDecl; } - - /** Return whether this material generator supports using a compressed - vertex format. This is only possible when using shaders. - */ - virtual bool isVertexCompressionSupported() const { return false; } - - /** Triggers the generator to request the options that it needs. - */ - virtual void requestOptions(Terrain* terrain) {} - /** Generate a material for the given terrain using the active profile. - */ - virtual MaterialPtr generate(const Terrain* terrain) = 0; - /** Generate a material for the given composite map of the terrain using the active profile. - */ - virtual MaterialPtr generateForCompositeMap(const Terrain* terrain) = 0; - /** Whether to support a light map over the terrain in the shader, - if it's present (default true). - */ - virtual void setLightmapEnabled(bool enabled) {} - /** Get the maximum number of layers supported with the given terrain. - @note When you change the options on the terrain, this value can change. - */ - virtual uint8 getMaxLayers(const Terrain* terrain) const { return 0; } - - /** Update the composite map for a terrain. - The composite map for a terrain must match what the terrain should look like - at distance. This method will only be called in the render thread so the - generator is free to render into a texture to support this, so long as - the results are blitted into the Terrain's own composite map afterwards. - */ - void updateCompositeMap(const Terrain* terrain, const Rect& rect); - - /** Update parameters for the given terrain using the active profile. - */ - virtual void updateParams(const MaterialPtr& mat, const Terrain* terrain) {} - /** Update parameters for the given terrain composite map using the active profile. - */ - virtual void updateParamsForCompositeMap(const MaterialPtr& mat, const Terrain* terrain) {} - - /** Set the debug level of the material. - - Sets the level of debug display for this material. - What this debug level means is entirely depdendent on the generator, - the only constant is that 0 means 'no debug' and non-zero means - 'some level of debugging', with any graduations in non-zero values - being generator-specific. - */ - void setDebugLevel(unsigned int dbg) - { - if (mDebugLevel != dbg) - { - mDebugLevel = dbg; - _markChanged(); - } - } - /// Get the debug level of the material. - unsigned int getDebugLevel() const { return mDebugLevel; } - - /** Helper method to render a composite map. - @param size The requested composite map size - @param rect The region of the composite map to update, in image space - @param mat The material to use to render the map - @param destCompositeMap A TexturePtr for the composite map to be written into - */ - void _renderCompositeMap(size_t size, const Rect& rect, const MaterialPtr& mat, - const TexturePtr& destCompositeMap); - - Texture* _getCompositeMapRTT() { return mCompositeMapRTT; } - protected: - unsigned long long int mChangeCounter; - TerrainLayerDeclaration mLayerDecl; - unsigned int mDebugLevel; - SceneManager* mCompositeMapSM; - Camera* mCompositeMapCam; - Texture* mCompositeMapRTT; // deliberately holding this by raw pointer to avoid shutdown issues - Rectangle2D* mCompositeMapPlane; - Light* mCompositeMapLight; - SceneNode* mLightNode; - - - }; - - typedef SharedPtr TerrainMaterialGeneratorPtr; - - /** @} */ - /** @} */ - -} -#endif - diff --git a/Components/Terrain/include/OgreTerrainMaterialGeneratorA.h b/Components/Terrain/include/OgreTerrainMaterialGeneratorA.h deleted file mode 100644 index c43af1fe62e..00000000000 --- a/Components/Terrain/include/OgreTerrainMaterialGeneratorA.h +++ /dev/null @@ -1,186 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_TerrainMaterialGeneratorA_H__ -#define __Ogre_TerrainMaterialGeneratorA_H__ - -#include "OgreTerrainPrerequisites.h" -#include "OgreTerrainMaterialGenerator.h" - -namespace Ogre -{ - class PSSMShadowCameraSetup; - - namespace RTShader - { - class RenderState; - } - - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Terrain - * @{ - */ - - /** A TerrainMaterialGenerator which can cope with normal mapped, specular mapped - terrain. - */ - class _OgreTerrainExport TerrainMaterialGeneratorA : public TerrainMaterialGenerator - { - public: - class SM2Profile; - private: - std::unique_ptr mMainRenderState; - std::unique_ptr mActiveProfile; - bool mLightmapEnabled; - bool mCompositeMapEnabled; - bool mReceiveDynamicShadows; - bool mLowLodShadows; - public: - TerrainMaterialGeneratorA(); - virtual ~TerrainMaterialGeneratorA(); - - RTShader::RenderState* getMainRenderState() const { return mMainRenderState.get(); } - - /** Shader model 2 profile target. - */ - class _OgreTerrainExport SM2Profile : public Profile - { - public: - SM2Profile(TerrainMaterialGeneratorA* parent); - virtual ~SM2Profile(); - /// Generate / reuse a material for the terrain - MaterialPtr generate(const Terrain* terrain); - /// Get the number of layers supported - uint8 getMaxLayers(const Terrain* terrain) const; - /** Whether to support normal mapping per layer in the shader (default true). - */ - bool isLayerNormalMappingEnabled() const { return mLayerNormalMappingEnabled; } - /** Whether to support normal mapping per layer in the shader (default true). - */ - void setLayerNormalMappingEnabled(bool enabled); - /** Whether to support parallax mapping per layer in the shader (default true). - */ - bool isLayerParallaxMappingEnabled() const { return mLayerParallaxMappingEnabled; } - /** Whether to support parallax mapping per layer in the shader (default true). - */ - void setLayerParallaxMappingEnabled(bool enabled); - /** Whether to support steep parallax mapping per layer in the shader (default true). - */ - void setLayerParallaxOcclusionMappingEnabled(bool enabled); - /** Whether to support steep parallax mapping per layer in the shader (default true). - */ - bool isLayerOcclusionMappingEnabled() const { return mLayerParallaxOcclusionMappingEnabled; } - /** Whether to support specular mapping per layer in the shader (default true). - */ - bool isLayerSpecularMappingEnabled() const { return mLayerSpecularMappingEnabled; } - /** Whether to support specular mapping per layer in the shader (default true). - */ - void setLayerSpecularMappingEnabled(bool enabled); - - - /** Whether to use PSSM support dynamic texture shadows, and if so the - settings to use (default 0). - */ - void setReceiveDynamicShadowsPSSM(PSSMShadowCameraSetup* pssmSettings); - /** Whether to use PSSM support dynamic texture shadows, and if so the - settings to use (default 0). - */ - PSSMShadowCameraSetup* getReceiveDynamicShadowsPSSM() const { return mPSSM; } - - void setLightmapEnabled(bool enabled) { mParent->setLightmapEnabled(enabled); } - void setCompositeMapEnabled(bool enabled) { mParent->setCompositeMapEnabled(enabled); } - void setReceiveDynamicShadowsEnabled(bool enabled) { mParent->setReceiveDynamicShadowsEnabled(enabled); } - void setReceiveDynamicShadowsLowLod(bool enabled) { mParent->setReceiveDynamicShadowsLowLod(enabled); } - private: - enum TechniqueType - { - HIGH_LOD, - LOW_LOD, - RENDER_COMPOSITE_MAP - }; - bool isShadowingEnabled(TechniqueType tt, const Terrain* terrain) const; - TerrainMaterialGeneratorA* mParent; - bool mLayerNormalMappingEnabled; - bool mLayerParallaxMappingEnabled; - bool mLayerParallaxOcclusionMappingEnabled; - bool mLayerSpecularMappingEnabled; - PSSMShadowCameraSetup* mPSSM; - }; - - /** Whether to support normal mapping per layer in the shader (default true). - */ - void setLayerNormalMappingEnabled(bool enabled) { mActiveProfile->setLayerNormalMappingEnabled(enabled); } - - /** Whether to support specular mapping per layer in the shader (default true). - */ - void setLayerSpecularMappingEnabled(bool enabled) { mActiveProfile->setLayerSpecularMappingEnabled(enabled); } - - /** Whether to support dynamic texture shadows received from other - objects, on the terrain (default true). - */ - bool getReceiveDynamicShadowsEnabled() const { return mReceiveDynamicShadows; } - /** Whether to support dynamic texture shadows received from other - objects, on the terrain (default true). - */ - void setReceiveDynamicShadowsEnabled(bool enabled); - - /** Whether to use shadows on low LOD material rendering (when using composite map) (default false). - */ - void setReceiveDynamicShadowsLowLod(bool enabled); - - /** Whether to use shadows on low LOD material rendering (when using composite map) (default false). - */ - bool getReceiveDynamicShadowsLowLod() const { return mLowLodShadows; } - - bool isLightmapEnabled() const { return mLightmapEnabled; } - /** Whether to use the composite map to provide a lower LOD technique - in the distance (default true). - */ - void setCompositeMapEnabled(bool enabled); - bool isCompositeMapEnabled() const { return mCompositeMapEnabled; } - - /// Get the active profile - Profile* getActiveProfile() const override { return mActiveProfile.get(); } - - bool isVertexCompressionSupported() const override { return true; } - void requestOptions(Terrain* terrain) override; - MaterialPtr generate(const Terrain* terrain) override { return mActiveProfile->generate(terrain); } - MaterialPtr generateForCompositeMap(const Terrain* terrain) override; - void setLightmapEnabled(bool enabled) override; - uint8 getMaxLayers(const Terrain* terrain) const override { return mActiveProfile->getMaxLayers(terrain); } - void updateParams(const MaterialPtr& mat, const Terrain* terrain) override; - void updateParamsForCompositeMap(const MaterialPtr& mat, const Terrain* terrain) override; - }; - /** @} */ - /** @} */ -} - -#endif - diff --git a/Components/Terrain/include/OgreTerrainPagedWorldSection.h b/Components/Terrain/include/OgreTerrainPagedWorldSection.h deleted file mode 100644 index a87ecec5480..00000000000 --- a/Components/Terrain/include/OgreTerrainPagedWorldSection.h +++ /dev/null @@ -1,196 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_TerrainPagedWorldSection_H__ -#define __Ogre_TerrainPagedWorldSection_H__ - -#include "OgreTerrainPrerequisites.h" -#include "OgrePagedWorldSection.h" -#include "OgreWorkQueue.h" -#include "OgreTerrainGroup.h" - - -namespace Ogre -{ - class Grid2DPageStrategy; - class Grid2DPageStrategyData; - - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Terrain - * Some details on the terrain component - * @{ - */ - - /** A world section which includes paged terrain. - - Rather than implement terrain paging as a PageContent subclass, because terrain - benefits from direct knowledge of neighbour arrangements and the tight - coupling between that and the paging strategy, instead we use a PagedWorldSection - subclass. This automatically provides a PageStrategy subclass of the - correct type (Grid2DPageStrategy) and derives the correct settings for - it compared to the terrain being used. This frees the user from having to - try to match all these up through the generic interfaces. - @par - When creating this in code, the user should make use of the helper - functions on the TerrainPaging class. The basic sequence is that - you define your terrain settings in a TerrainGroup, and then create an - instance of TerrainPagedWorldSection via TerrainPaging::createWorldSection. - That's basically all there is to it - the normal rules of TerrainGroup - apply, it's just that instead of having to choose when to try to load / unload - pages from the TerrainGroup, that is automatically done by the paging system. - You can also create other types of content in this PagedWorldSection other - than terrain, it's just that this comes with terrain handling built-in. - @par - When this world data is saved, you basically get 3 sets of data - firstly - the top-level 'world data' which is where the definition of the world - sections are stored (and hence, the definition of this class, although none - of the terrain instance content is included). Secondly, you get a number - of .page files which include any other content that you might have inserted - into the pages. Lastly, you get the standard terrain data files which are - saved as per TerrainGroup. - */ - class _OgreTerrainExport TerrainPagedWorldSection : public PagedWorldSection - { - public: - /** Constructor. - @param name The name of the section - @param parent The parent world - @param sm The SceneManager to use (can be left as null if to be loaded) - */ - TerrainPagedWorldSection(const String& name, PagedWorld* parent, SceneManager* sm); - virtual ~TerrainPagedWorldSection(); - - /** Initialise this section from an existing TerrainGroup instance. - - This is the route you will take if you're defining this world section - from scratch in code. The other alternative is that you'll be loading - this section from a file, in which case all the settings will be - derived from that. - @param grp The TerrainGroup which will form the basis of this world section. - The instance will be owned by this class from now on and will be destroyed by it. - */ - virtual void init(TerrainGroup* grp); - - /** Get the TerrainGroup which this world section is using. - @remarks For information, you can use the returned TerrainGroup to - convert to/from x/y locations and the pageID, since the grid strategy - is the same. - */ - virtual TerrainGroup* getTerrainGroup() { return mTerrainGroup; } - - /// Set the loading radius - virtual void setLoadRadius(Real sz); - /// Get the loading radius - virtual Real getLoadRadius() const; - /// Set the Holding radius - virtual void setHoldRadius(Real sz); - /// Get the Holding radius - virtual Real getHoldRadius(); - /// Set the index range of all Pages (values outside this will be ignored) - virtual void setPageRange(int32 minX, int32 minY, int32 maxX, int32 maxY); - /// Set the index range of all Pages (values outside this will be ignored) - virtual void setPageRangeMinX(int32 minX); - /// Set the index range of all Pages (values outside this will be ignored) - virtual void setPageRangeMinY(int32 minY); - /// Set the index range of all Pages (values outside this will be ignored) - virtual void setPageRangeMaxX(int32 maxX); - /// Set the index range of all Pages (values outside this will be ignored) - virtual void setPageRangeMaxY(int32 maxY); - /// get the index range of all Pages (values outside this will be ignored) - virtual int32 getPageRangeMinX() const; - /// get the index range of all Pages (values outside this will be ignored) - virtual int32 getPageRangeMinY() const; - /// get the index range of all Pages (values outside this will be ignored) - virtual int32 getPageRangeMaxX() const; - /// get the index range of all Pages (values outside this will be ignored) - virtual int32 getPageRangeMaxY() const; - - /// Convenience method - this section always uses a grid strategy - virtual Grid2DPageStrategy* getGridStrategy() const; - /// Convenience method - this section always uses a grid strategy - virtual Grid2DPageStrategyData* getGridStrategyData() const; - - /// Set the interval between the loading of single pages in milliseconds (ms) - virtual void setLoadingIntervalMs(uint32 loadingIntervalMs); - /// Get the interval between the loading of single pages in milliseconds (ms) - virtual uint32 getLoadingIntervalMs() const; - - /// Overridden from PagedWorldSection - void loadPage(PageID pageID, bool forceSynchronous = false) override; - /// Overridden from PagedWorldSection - void unloadPage(PageID pageID, bool forceSynchronous = false) override; - - class TerrainDefiner : public TerrainAlloc - { - public: - virtual void define(TerrainGroup* terrainGroup, long x, long y) - { - terrainGroup->defineTerrain(x,y); - } - virtual ~TerrainDefiner() {} - }; - - void setDefiner(TerrainDefiner* terrainDefiner) - { - if(mTerrainDefiner) - OGRE_DELETE mTerrainDefiner; - mTerrainDefiner = terrainDefiner; - } - - private: - TerrainGroup* mTerrainGroup; - TerrainDefiner* mTerrainDefiner; - std::list mPagesInLoading; - bool mHasRunningTasks; - unsigned long mNextLoadingTime; - uint32 mLoadingIntervalMs; - - /// WorkQueue::RequestHandler override - WorkQueue::Response* handleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ); - /// WorkQueue::ResponseHandler override - void handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ); - - /// Overridden from PagedWorldSection - void loadSubtypeData(StreamSerialiser& ser) override; - void saveSubtypeData(StreamSerialiser& ser) override; - - virtual void syncSettings(); - - }; - - - - - - /** @} */ - /** @} */ -} - -#endif diff --git a/Components/Terrain/include/OgreTerrainPaging.h b/Components/Terrain/include/OgreTerrainPaging.h deleted file mode 100644 index 769d0d2cce1..00000000000 --- a/Components/Terrain/include/OgreTerrainPaging.h +++ /dev/null @@ -1,135 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_TerrainPaging_H__ -#define __Ogre_TerrainPaging_H__ - -#include "OgreTerrainPrerequisites.h" -#include "OgrePagedWorldSection.h" -#include "OgreCommon.h" - -namespace Ogre -{ - class PagedWorld; - class TerrainGroup; - class TerrainPagedWorldSection; - - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Terrain - * Some details on the terrain component - * @{ - */ - - /** This class is the 'core' class for paging terrain, that will integrate - with the larger paging system and provide the appropriate utility - classes required. - - You should construct this class after PageManager and before any PagedWorlds - that might use it are created / loaded. Once constructed, it will make - the "Terrain" PagedWorldSection type available, which uses a grid strategy for - paging and uses TerrainGroup for the content. Other content can - be embedded in the pages too but the terrain is done like this in order - to maintain connections between pages and other global data. - @par - Because PagedWorld and all attached classes have to be loadable from a stream, - most of the functionality is provided behind generalised interfaces. However, - for constructing a paged terrain in code you can use utility methods on - this class. This procedurally created data can then be saved in a generic - form which will reconstruct on loading. Alternatively you can use the - generic methods and simply cast based on your prior knowledge of the types - (or checking the type names exposed). - - */ - class _OgreTerrainExport TerrainPaging : public TerrainAlloc - { - public: - /** Constructor. - @param pageMgr The PageManager which this class should attach to. - */ - TerrainPaging(PageManager* pageMgr); - virtual ~TerrainPaging(); - - /** Create a TerrainPagedWorldSection. - - This is the simplest way to create a world section which is configured - to contain terrain (among other objects if you want). You can also do this - by calling PagedWorld::createSection with the type "Terrain" but there - are more steps to configuring it that way (note: this is how loading - works though so it remains generic). - @param world The PagedWorld that is to contain this section - @param terrainGroup A TerrainGroup which must have been pre-configured before - this call, to at least set the origin, the world size, and the file name - convention. - @param loadRadius The radius from the camera at which terrain pages will be loaded - @param holdRadius The radius from the camera at which terrain pages will be held in memory - but not loaded if they're not already. This must be larger than loadRadius and is used - to minimise thrashing if the camera goes backwards and forwards at the loading border. - @param minX,minY,maxX,maxY The min/max page indexes that the world will try to load pages for, - as measured from the origin page at (0,0) by a signed index. The default is -10 to 10 - in each direction or 20x20 pages. - @param sectionName An optional name to give the section (if none is - provided, one will be generated) - @param loadingIntervalMs An optional interval in milliseconds to wait between loading single - pages. The default is 900 ms. - @return The world section which is already attached to and owned by the world you passed in. - There is no 'destroy' method because you destroy via the PagedWorld, this is just a - helper function. - */ - TerrainPagedWorldSection* createWorldSection(PagedWorld* world, TerrainGroup* terrainGroup, - Real loadRadius, Real holdRadius, - int32 minX = -10, int32 minY = -10, int32 maxX = 10, int32 maxY = 10, - const String& sectionName = BLANKSTRING, uint32 loadingIntervalMs = 900); - - private: - PageManager* mManager; - - class _OgreTerrainExport SectionFactory : public PagedWorldSectionFactory - { - public: - static const String FACTORY_NAME; - const String& getName() const override; - PagedWorldSection* createInstance(const String& name, PagedWorld* parent, SceneManager* sm) override; - void destroyInstance(PagedWorldSection*) override; - - }; - - SectionFactory mSectionFactory; - - }; - - - - - - /** @} */ - /** @} */ -} - -#endif diff --git a/Components/Terrain/include/OgreTerrainPrerequisites.h b/Components/Terrain/include/OgreTerrainPrerequisites.h deleted file mode 100644 index 6d1288c5875..00000000000 --- a/Components/Terrain/include/OgreTerrainPrerequisites.h +++ /dev/null @@ -1,68 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_Terrain_Prereq_H__ -#define __Ogre_Terrain_Prereq_H__ - -#include "OgrePrerequisites.h" - -namespace Ogre -{ - // forward decls - class Terrain; - class TerrainPageContent; - class TerrainPageContentFactory; - class TerrainQuadTreeNode; - - - typedef GeneralAllocatedObject TerrainAlloc; - - -} - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT -# if defined( OGRE_STATIC_LIB ) -# define _OgreTerrainExport -# else -# if defined( OGRE_TERRAIN_EXPORTS ) -# define _OgreTerrainExport __declspec( dllexport ) -# else -# if defined( __MINGW32__ ) -# define _OgreTerrainExport -# else -# define _OgreTerrainExport __declspec( dllimport ) -# endif -# endif -# endif -#elif defined ( OGRE_GCC_VISIBILITY ) -# define _OgreTerrainExport __attribute__ ((visibility("default"))) -#else -# define _OgreTerrainExport -#endif - -#endif diff --git a/Components/Terrain/include/OgreTerrainQuadTreeNode.h b/Components/Terrain/include/OgreTerrainQuadTreeNode.h deleted file mode 100644 index e2e18a1558e..00000000000 --- a/Components/Terrain/include/OgreTerrainQuadTreeNode.h +++ /dev/null @@ -1,372 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Ogre_TerrainQuadTreeNode_H__ -#define __Ogre_TerrainQuadTreeNode_H__ - -#include "OgreTerrainPrerequisites.h" -#include "OgreCommon.h" -#include "OgreMovableObject.h" -#include "OgreRenderable.h" - -namespace Ogre -{ - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Terrain - * Some details on the terrain component - * @{ - */ - - - /** A node in a quad tree used to store a patch of terrain. - - Algorithm overview: - @par - Our goal is to perform traditional chunked LOD with geomorphing. But, - instead of just dividing the terrain into tiles, we will divide them into - a hierarchy of tiles, a quadtree, where any level of the quadtree can - be a rendered tile (to the exclusion of its children). The idea is to - collect together children into a larger batch with their siblings as LOD - decreases, to improve performance. - @par - The minBatchSize and maxBatchSize parameters on Terrain a key to - defining this behaviour. Both values are expressed in vertices down one axis. - maxBatchSize determines the number of tiles on one side of the terrain, - which is numTiles = (terrainSize-1) / (maxBatchSize-1). This in turn determines the depth - of the quad tree, which is sqrt(numTiles). The minBatchSize determines - the 'floor' of how low the number of vertices can go in a tile before it - has to be grouped together with its siblings to drop any lower. We also do not group - a tile with its siblings unless all of them are at this minimum batch size, - rather than trying to group them when they all end up on the same 'middle' LOD; - this is for several reasons; firstly, tiles hitting the same 'middle' LOD is - less likely and more transient if they have different levels of 'roughness', - and secondly since we're sharing a vertex / index pool between all tiles, - only grouping at the min level means that the number of combinations of - buffer sizes for any one tile is greatly simplified, making it easier to - pool data. To be more specific, any tile / quadtree node can only have - log2(maxBatchSize-1) - log2(minBatchSize-1) + 1 LOD levels (and if you set them - to the same value, LOD can only change by going up/down the quadtree). - The numbers of vertices / indices in each of these levels is constant for - the same (relative) LOD index no matter where you are in the tree, therefore - buffers can potentially be reused more easily. - */ - class _OgreTerrainExport TerrainQuadTreeNode : private Renderable, private MovableObject - { - public: - /** Constructor. - @param terrain The ultimate parent terrain - @param parent Optional parent node (in which case xoff, yoff are 0 and size must be entire terrain) - @param xoff, yoff Offsets from the start of the terrain data in 2D - @param size The size of the node in vertices at the highest LOD - @param lod The base LOD level - @param depth The depth that this node is at in the tree (or convenience) - */ - TerrainQuadTreeNode(Terrain* terrain, TerrainQuadTreeNode* parent, - uint16 xoff, uint16 yoff, uint16 size, uint16 lod, uint16 depth); - virtual ~TerrainQuadTreeNode(); - - /// Get the horizontal offset into the main terrain data of this node - uint16 getXOffset() const { return mOffsetX; } - /// Get the vertical offset into the main terrain data of this node - uint16 getYOffset() const { return mOffsetY; } - /// Is this a leaf node (no children) - bool isLeaf() const; - /// Get the base LOD level this node starts at (the highest LOD it handles) - uint16 getBaseLod() const { return mBaseLod; } - /// Get the number of LOD levels this node can represent itself (only > 1 for leaf nodes) - uint16 getLodCount() const; - /// Get child node - TerrainQuadTreeNode* getChild(unsigned short child) const; - /// Get parent node - TerrainQuadTreeNode* getParent() const; - /// Get ultimate parent terrain - Terrain* getTerrain() const; - - /// Prepare node and children (perform CPU tasks, may be background thread) - void prepare(); - /// Prepare node from a stream - void prepare(StreamSerialiser& stream); - /// Load node and children (perform GPU tasks, will be render thread) - void load(); - /// Load node and children in a depth range (perform GPU tasks, will be render thread) - void load(uint16 depthStart, uint16 depthEnd); - void loadSelf(); - /// Unload node and children (perform GPU tasks, will be render thread) - void unload(); - /// Unload node and children in a depth range (perform GPU tasks, will be render thread) - void unload(uint16 depthStart, uint16 depthEnd); - /// Unprepare node and children (perform CPU tasks, may be background thread) - void unprepare(); - /// Save node to a stream - void save(StreamSerialiser& stream); - - struct _OgreTerrainExport LodLevel : public TerrainAlloc - { - /// Number of vertices rendered down one side (not including skirts) - uint16 batchSize; - /// Index data on the gpu - IndexData* gpuIndexData; - /// Maximum delta height between this and the next lower lod - Real maxHeightDelta; - /// Temp calc area for max height delta - Real calcMaxHeightDelta; - /// The most recently calculated transition distance - Real lastTransitionDist; - /// The cFactor value used to calculate transitionDist - Real lastCFactor; - - LodLevel() : batchSize(0), gpuIndexData(0), maxHeightDelta(0), calcMaxHeightDelta(0), - lastTransitionDist(0), lastCFactor(0) {} - }; - typedef std::vector LodLevelList; - - /** Get the LodLevel information for a given lod. - @param lod The lod level index relative to this classes own list; if you - want to use a global lod level, subtract getBaseLod() first. Higher - LOD levels are lower detail. - */ - const LodLevel* getLodLevel(uint16 lod); - - /** Notify the node (and children) that deltas are going to be calculated for a given range. - - Based on this call, we can know whether or not to reset the max height. - */ - void preDeltaCalculation(const Rect& rect); - - /** Notify the node (and children) of a height delta value. */ - void notifyDelta(uint16 x, uint16 y, uint16 lod, Real delta); - - /** Notify the node (and children) that deltas have finished being calculated. - */ - void postDeltaCalculation(const Rect& rect); - - /** Promote the delta values calculated to the runtime ones (this must - be called in the main thread). - */ - void finaliseDeltaValues(const Rect& rect); - - /** Assign vertex data to the tree, from a depth and at a given resolution. - @param treeDepthStart The first depth of tree that should use this data, owns the data - @param treeDepthEnd The end of the depth that should use this data (exclusive) - @param resolution The resolution of the data to use (compared to full terrain) - @param sz The size of the data along one edge - */ - void assignVertexData(uint16 treeDepthStart, uint16 treeDepthEnd, uint16 resolution, uint sz); - - /** Tell a node that it should use an anscestor's vertex data. - @param owner - @param treeDepthEnd The end of the depth that should use this data (exclusive) - @param resolution The resolution of the data to use - */ - void useAncestorVertexData(TerrainQuadTreeNode* owner, uint16 treeDepthEnd, uint16 resolution); - - /** Tell the node to update its vertex data for a given region. - */ - void updateVertexData(bool positions, bool deltas, const Rect& rect, bool cpuData); - - - - /** Merge a point (relative to terrain node) into the local bounds, - and that of children if applicable. - @param x,y The point on the terrain to which this position corresponds - (affects which nodes update their bounds) - @param pos The position relative to the terrain centre - */ - void mergeIntoBounds(long x, long y, const Vector3& pos); - /** Reset the bounds of this node and all its children for the region given. - @param rect The region for which bounds should be reset, in top-level terrain coords - */ - void resetBounds(const Rect& rect); - - /** Returns true if the given rectangle overlaps the terrain area that - this node references. - @param rect The region in top-level terrain coords - */ - bool rectIntersectsNode(const Rect& rect); - /** Returns true if the given rectangle completely contains the terrain area that - this node references. - @param rect The region in top-level terrain coords - */ - bool rectContainsNode(const Rect& rect); - /** Returns true if the given point is in the terrain area that - this node references. - @param x,y The point in top-level terrain coords - */ - bool pointIntersectsNode(long x, long y); - - /// Get the AABB (local coords) of this node - const AxisAlignedBox& getBoundingBox(void) const override { return mAABB; } - - /// Get the bounding radius of this node - Real getBoundingRadius() const override; - /// Get the local centre of this node, relative to parent terrain centre - const Vector3& getLocalCentre() const { return mLocalCentre; } - /// Get the minimum height of the node - Real getMinHeight() const; - /// Get the maximum height of the node - Real getMaxHeight() const; - - /** Calculate appropriate LOD for this node and children - @param cam The camera to be used (this should already be the LOD camera) - @param cFactor The cFactor which incorporates the viewport size, max pixel error and lod bias - @return true if this node or any of its children were selected for rendering - */ - bool calculateCurrentLod(const Camera* cam, Real cFactor); - - /// Get the current LOD index (only valid after calculateCurrentLod) - int getCurrentLod() const { return mCurrentLod; } - /// Returns whether this node is rendering itself at the current LOD level - bool isRenderedAtCurrentLod() const; - /// Returns whether this node or its children are being rendered at the current LOD level - bool isSelfOrChildRenderedAtCurrentLod() const; - /// Manually set the current LOD, intended for internal use only - void setCurrentLod(int lod); - /// Get the transition state between the current LOD and the next lower one (only valid after calculateCurrentLod) - float getLodTransition() const { return mLodTransition; } - /// Manually set the current LOD transition state, intended for internal use only - void setLodTransition(float t); - - /// Buffer binding used for holding positions - static unsigned short POSITION_BUFFER; - /// Buffer binding used for holding delta values - static unsigned short DELTA_BUFFER; - - private: - Terrain* mTerrain; - TerrainQuadTreeNode* mParent; - TerrainQuadTreeNode* mChildren[4]; - LodLevelList mLodLevels; - - uint16 mOffsetX, mOffsetY; - uint16 mBoundaryX, mBoundaryY; - /// The number of vertices at the original terrain resolution this node encompasses - uint16 mSize; - uint16 mBaseLod; - uint16 mDepth; - Vector3 mLocalCentre; /// Relative to terrain centre - AxisAlignedBox mAABB; /// Relative to mLocalCentre - Real mBoundingRadius; /// Relative to mLocalCentre - int mCurrentLod; /// -1 = none (do not render) - float mLodTransition; /// 0-1 transition to lower LOD - /// The child with the largest height delta - TerrainQuadTreeNode* mChildWithMaxHeightDelta; - bool mSelfOrChildRendered; - - struct VertexDataRecord : public TerrainAlloc - { - VertexData* cpuVertexData; - VertexData* gpuVertexData; - /// Resolution of the data compared to the base terrain data (NOT number of vertices!) - uint16 resolution; - /// Size of the data along one edge - uint16 size; - /// Number of quadtree levels (including this one) this data applies to - uint16 treeLevels; - /// Number of rows and columns of skirts - uint16 numSkirtRowsCols; - /// The number of rows / cols to skip in between skirts - uint16 skirtRowColSkip; - /// Is the GPU vertex data out of date? - bool gpuVertexDataDirty; - - VertexDataRecord(uint16 res, uint16 sz, uint16 lvls) - : cpuVertexData(0), gpuVertexData(0), resolution(res), size(sz), - treeLevels(lvls), numSkirtRowsCols(0), - skirtRowColSkip(0), gpuVertexDataDirty(false) {} - }; - - TerrainQuadTreeNode* mNodeWithVertexData; - VertexDataRecord* mVertexDataRecord; - - /** MovableObject implementation to provide the hook to the scene. - - In one sense, it would be most convenient to have a single MovableObject - to represent the whole Terrain object, and then internally perform - some quadtree frustum culling to narrow down which specific tiles are rendered. - However, the one major flaw with that is that exposing the bounds to - the SceneManager at that level prevents it from doing anything smarter - in terms of culling - for example a portal or occlusion culling SceneManager - would have no opportunity to process the leaf nodes in those terms, and - a simple frustum cull may give significantly poorer results. - @par - Therefore, we in fact register a MovableObject at every node, and - use the LOD factor to determine which one is currently active. LODs - must be mutually exclusive and to deal with precision errors, we really - need to evaluate them all at once, rather than as part of the - _notifyCurrentCamera function. Therefore the root Terrain registers - a SceneManager::Listener to precalculate which nodes will be displayed - when it comes to purely a LOD basis. - */ - SceneNode* mLocalNode; - - // actual implementation of MovableObject methods - bool isVisible(void) const override; - const String& getMovableType(void) const override; - void _updateRenderQueue(RenderQueue* queue) override; - void visitRenderables(Renderable::Visitor* visitor, bool debugRenderables = false) override; - // actual implementations of Renderable methods - const MaterialPtr& getMaterial(void) const override; - Technique* getTechnique(void) const override; - void getRenderOperation(RenderOperation& op) override; - void getWorldTransforms(Matrix4* xform) const override; - Real getSquaredViewDepth(const Camera* cam) const override; - const LightList& getLights(void) const override; - bool getCastShadows(void) const override; - /// @deprecated will be private in 14 - bool getCastsShadows(void) const override { return getCastShadows(); } - - - const VertexDataRecord* getVertexDataRecord() const; - void createCpuVertexData(); - /* Update the vertex buffers - the rect in question is relative to the whole terrain, - not the local vertex data (which may use a subset) - */ - void updateVertexBuffer(const HardwareVertexBufferPtr& posbuf, const HardwareVertexBufferPtr& deltabuf, const Rect& rect); - void destroyCpuVertexData(); - - void createGpuVertexData(); - void destroyGpuVertexData(); - void updateGpuVertexData(); - void createGpuIndexData(); - void destroyGpuIndexData(); - - void populateIndexData(uint16 batchSize, IndexData* destData); - void writePosVertex(bool compress, uint16 x, uint16 y, float height, const Vector3& pos, float uvScale, float** ppPos); - void writeDeltaVertex(bool compress, uint16 x, uint16 y, float delta, float deltaThresh, float** ppDelta); - - uint16 calcSkirtVertexIndex(uint16 mainIndex, bool isCol); - - }; - - /** @} */ - /** @} */ -} - -#endif diff --git a/Components/Terrain/src/OgreTerrain.cpp b/Components/Terrain/src/OgreTerrain.cpp deleted file mode 100644 index e0d5d771685..00000000000 --- a/Components/Terrain/src/OgreTerrain.cpp +++ /dev/null @@ -1,4527 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreTerrain.h" -#include "OgreTerrainQuadTreeNode.h" -#include "OgreStreamSerialiser.h" -#include "OgreMath.h" -#include "OgreCamera.h" -#include "OgreImage.h" -#include "OgrePixelFormat.h" -#include "OgreSceneManager.h" -#include "OgreSceneNode.h" -#include "OgreException.h" -#include "OgreBitwise.h" -#include "OgreViewport.h" -#include "OgreLogManager.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreTextureManager.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" -#include "OgreRay.h" -#include "OgrePlane.h" -#include "OgreHardwareBufferManager.h" -#include "OgreMaterialManager.h" -#include "OgreTimer.h" -#include "OgreTerrainMaterialGeneratorA.h" -#include "OgreFileSystemLayer.h" - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -// we do lots of conversions here, casting them all is tedious & cluttered, we know what we're doing -# pragma warning (disable : 4244) -#endif -namespace Ogre -{ - //--------------------------------------------------------------------- - const uint32 Terrain::TERRAIN_CHUNK_ID = StreamSerialiser::makeIdentifier("TERR"); - const uint16 Terrain::TERRAIN_CHUNK_VERSION = 2; - const uint32 Terrain::TERRAINGENERALINFO_CHUNK_ID = StreamSerialiser::makeIdentifier("TGIN"); - const uint16 Terrain::TERRAINGENERALINFO_CHUNK_VERSION = 1; - const uint32 Terrain::TERRAINLAYERDECLARATION_CHUNK_ID = StreamSerialiser::makeIdentifier("TDCL"); - const uint16 Terrain::TERRAINLAYERDECLARATION_CHUNK_VERSION = 1; - const uint32 Terrain::TERRAINLAYERSAMPLER_CHUNK_ID = StreamSerialiser::makeIdentifier("TSAM"); - const uint16 Terrain::TERRAINLAYERSAMPLER_CHUNK_VERSION = 1; - const uint32 Terrain::TERRAINLAYERSAMPLERELEMENT_CHUNK_ID = StreamSerialiser::makeIdentifier("TSEL"); - const uint16 Terrain::TERRAINLAYERSAMPLERELEMENT_CHUNK_VERSION = 1; - const uint32 Terrain::TERRAINLAYERINSTANCE_CHUNK_ID = StreamSerialiser::makeIdentifier("TLIN"); - const uint16 Terrain::TERRAINLAYERINSTANCE_CHUNK_VERSION = 1; - const uint32 Terrain::TERRAINDERIVEDDATA_CHUNK_ID = StreamSerialiser::makeIdentifier("TDDA"); - const uint16 Terrain::TERRAINDERIVEDDATA_CHUNK_VERSION = 1; - // since 129^2 is the greatest power we can address in 16-bit index - const uint16 Terrain::TERRAIN_MAX_BATCH_SIZE = 129; - const uint32 Terrain::LOD_MORPH_CUSTOM_PARAM = 1001; - const uint8 Terrain::DERIVED_DATA_DELTAS = 1; - const uint8 Terrain::DERIVED_DATA_NORMALS = 2; - const uint8 Terrain::DERIVED_DATA_LIGHTMAP = 4; - // This MUST match the bitwise OR of all the types above with no extra bits! - const uint8 Terrain::DERIVED_DATA_ALL = 7; - //----------------------------------------------------------------------- - template<> TerrainGlobalOptions* Singleton::msSingleton = 0; - TerrainGlobalOptions* TerrainGlobalOptions::getSingletonPtr(void) - { - return msSingleton; - } - TerrainGlobalOptions& TerrainGlobalOptions::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - // need to implement in cpp due to how Ogre::Singleton works - TerrainGlobalOptions::~TerrainGlobalOptions() {} - //--------------------------------------------------------------------- - TerrainGlobalOptions::TerrainGlobalOptions() - : mSkirtSize(30) - , mLightMapDir(Vector3(1, -1, 0).normalisedCopy()) - , mCastsShadows(false) - , mMaxPixelError(3.0) - , mRenderQueueGroup(RENDER_QUEUE_MAIN) - , mVisibilityFlags(0xFFFFFFFF) - , mQueryFlags(0xFFFFFFFF) - , mUseRayBoxDistanceCalculation(false) - , mLayerBlendMapSize(1024) - , mDefaultLayerTextureWorldSize(10) - , mDefaultGlobalColourMapSize(1024) - , mLightmapSize(1024) - , mCompositeMapSize(1024) - , mCompositeMapAmbient(ColourValue::White) - , mCompositeMapDiffuse(ColourValue::White) - , mCompositeMapDistance(4000) - , mResourceGroup(ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME) - , mUseVertexCompressionWhenAvailable(true) - { - } - //--------------------------------------------------------------------- - void TerrainGlobalOptions::setDefaultMaterialGenerator(const TerrainMaterialGeneratorPtr& gen) - { - mDefaultMaterialGenerator = gen; - } - //--------------------------------------------------------------------- - TerrainMaterialGeneratorPtr TerrainGlobalOptions::getDefaultMaterialGenerator() - { - if (!mDefaultMaterialGenerator) - { - // default - mDefaultMaterialGenerator.reset(OGRE_NEW TerrainMaterialGeneratorA()); - } - - return mDefaultMaterialGenerator; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - NameGenerator Terrain::msBlendTextureGenerator = NameGenerator("TerrBlend"); - //--------------------------------------------------------------------- - Terrain::Terrain(SceneManager* sm) - : mSceneMgr(sm) - , mResourceGroup(BLANKSTRING) - , mIsLoaded(false) - , mModified(false) - , mHeightDataModified(false) - , mHeightData(0) - , mDeltaData(0) - , mAlign(ALIGN_X_Z) - , mWorldSize(0) - , mSize(0) - , mMaxBatchSize(0) - , mMinBatchSize(0) - , mPos(Vector3::ZERO) - , mQuadTree(0) - , mNumLodLevels(0) - , mNumLodLevelsPerLeafNode(0) - , mTreeDepth(0) - , mBase(0) - , mScale(0) - , mSkirtSize(0) - , mRenderQueueGroup(0) - , mVisibilityFlags(0) - , mQueryFlags(0) - , mDirtyGeometryRect(0, 0, 0, 0) - , mDirtyDerivedDataRect(0, 0, 0, 0) - , mDirtyGeometryRectForNeighbours(0, 0, 0, 0) - , mDirtyLightmapFromNeighboursRect(0, 0, 0, 0) - , mDerivedDataUpdateInProgress(false) - , mDerivedUpdatePendingMask(0) - , mGenerateMaterialInProgress(false) - , mPrepareInProgress(false) - , mMaterialGenerationCount(0) - , mMaterialDirty(false) - , mMaterialParamsDirty(false) - , mLayerBlendMapSize(0) - , mLayerBlendMapSizeActual(0) - , mGlobalColourMapSize(0) - , mGlobalColourMapEnabled(false) - , mLightmapSize(0) - , mLightmapSizeActual(0) - , mCompositeMapSize(0) - , mCompositeMapSizeActual(0) - , mCompositeMapDirtyRect(0, 0, 0, 0) - , mCompositeMapUpdateCountdown(0) - , mLastMillis(0) - , mCompositeMapDirtyRectLightmapUpdate(false) - , mLodMorphRequired(false) - , mNormalMapRequired(false) - , mLightMapRequired(false) - , mLightMapShadowsOnly(true) - , mCompositeMapRequired(false) - , mLastLODCamera(0) - , mLastLODFrame(0) - , mLastViewportHeight(0) - , mCustomGpuBufferAllocator(0) - , mLodManager(0) - - { - mRootNode = sm->getRootSceneNode()->createChildSceneNode(); - sm->addListener(this); - - // generate a material name, it's important for the terrain material - // name to be consistent & unique no matter what generator is being used - // so use our own pointer as identifier, use FashHash rather than just casting - // the pointer to a long so we support 64-bit pointers - Terrain* pTerrain = this; - mMaterialName = "OgreTerrain/" + StringConverter::toString(FastHash((const char*)&pTerrain, sizeof(Terrain*))); - - memset(mNeighbours, 0, sizeof(Terrain*) * NEIGHBOUR_COUNT); - } - //--------------------------------------------------------------------- - Terrain::~Terrain() - { - mDerivedUpdatePendingMask = 0; - waitForDerivedProcesses(); - removeFromNeighbours(); - - freeLodData(); - freeTemporaryResources(); - freeGPUResources(); - freeCPUResources(); - if (mSceneMgr) - { - mSceneMgr->destroySceneNode(mRootNode); - mSceneMgr->removeListener(this); - } - } - //--------------------------------------------------------------------- - const AxisAlignedBox& Terrain::getAABB() const - { - if (!mQuadTree) - return AxisAlignedBox::BOX_NULL; - else - return mQuadTree->getBoundingBox(); - } - //--------------------------------------------------------------------- - AxisAlignedBox Terrain::getWorldAABB() const - { - Affine3 m = Affine3::IDENTITY; - m.setTrans(getPosition()); - - AxisAlignedBox ret = getAABB(); - ret.transform(m); - return ret; - } - //--------------------------------------------------------------------- - Real Terrain::getMinHeight() const - { - if (!mQuadTree) - return 0; - else - return mQuadTree->getMinHeight(); - } - //--------------------------------------------------------------------- - Real Terrain::getMaxHeight() const - { - if (!mQuadTree) - return 0; - else - return mQuadTree->getMaxHeight(); - } - //--------------------------------------------------------------------- - Real Terrain::getBoundingRadius() const - { - if (!mQuadTree) - return 0; - else - return mQuadTree->getBoundingRadius(); - } - //--------------------------------------------------------------------- - void Terrain::save(const String& filename) - { - // force to load highest lod, or quadTree may contain hole - load(0,true); - - bool wasOpen = false; - - if (mLodManager) - { - wasOpen = mLodManager->isOpen(); - mLodManager->close(); - } - - { -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - static FileSystemLayer fs(""); -#endif - - DataStreamPtr stream = Root::createFileStream( -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - fs.getWritablePath(filename) -#else - filename -#endif - , - _getDerivedResourceGroup(), - true); - - StreamSerialiser ser(stream); - save(ser); - } - - if (mLodManager && wasOpen) - mLodManager->open(filename); - } - //--------------------------------------------------------------------- - void Terrain::save(StreamSerialiser& stream) - { - // wait for any queued processes to finish - waitForDerivedProcesses(); - - if (mHeightDataModified) - { - // When modifying, for efficiency we only increase the max deltas at each LOD, - // we never reduce them (since that would require re-examining more samples) - // Since we now save this data in the file though, we need to make sure we've - // calculated the optimal - Rect rect(0, 0, mSize, mSize); - calculateHeightDeltas(rect); - finaliseHeightDeltas(rect, false); - } - - stream.writeChunkBegin(TERRAIN_CHUNK_ID, TERRAIN_CHUNK_VERSION); - - stream.writeChunkBegin(TERRAINGENERALINFO_CHUNK_ID, TERRAINGENERALINFO_CHUNK_VERSION); - uint8 align = (uint8)mAlign; - stream.write(&align); - - stream.write(&mSize); - stream.write(&mWorldSize); - stream.write(&mMaxBatchSize); - stream.write(&mMinBatchSize); - stream.write(&mPos); - stream.writeChunkEnd(TERRAINGENERALINFO_CHUNK_ID); - - TerrainLodManager::saveLodData(stream,this); - - // start compressing - stream.startDeflate(); - - writeLayerDeclaration(mLayerDecl, stream); - - // Layers - checkLayers(false); - uint8 numLayers = (uint8)mLayers.size(); - writeLayerInstanceList(mLayers, stream); - - // Packed layer blend data - if(!mCpuBlendMapStorage.empty()) - { - // save from CPU data if it's there, it means GPU data was never created - stream.write(&mLayerBlendMapSize); - - // load packed CPU data - int numBlendTex = getBlendTextureCount(numLayers); - for (int i = 0; i < numBlendTex; ++i) - { - stream.write(mCpuBlendMapStorage[i].getData(), mCpuBlendMapStorage[i].getSize()); - } - } - else - { - if (mLayerBlendMapSize != mLayerBlendMapSizeActual) - { - LogManager::getSingleton().logWarning( - "blend maps were requested at a size larger than was supported " - "on this hardware, which means the quality has been degraded"); - } - stream.write(&mLayerBlendMapSizeActual); - Image tmp(PF_BYTE_RGBA, mLayerBlendMapSizeActual, mLayerBlendMapSizeActual); - for (const auto& tex : mBlendTextureList) - { - // Must blit back in CPU format! - tex->getBuffer()->blitToMemory(tmp.getPixelBox()); - stream.write(tmp.getData(), tmp.getSize()); - } - } - - // other data - // normals - if (mNormalMapRequired) - { - stream.writeChunkBegin(TERRAINDERIVEDDATA_CHUNK_ID, TERRAINDERIVEDDATA_CHUNK_VERSION); - String normalDataType("normalmap"); - stream.write(&normalDataType); - stream.write(&mSize); - if (mCpuTerrainNormalMap.getData()) - { - // save from CPU data if it's there, it means GPU data was never created - stream.write(mCpuTerrainNormalMap.getData(), mCpuTerrainNormalMap.getSize()); - } - else - { - Image tmp(PF_BYTE_RGB, mSize, mSize); - mTerrainNormalMap->getBuffer()->blitToMemory(tmp.getPixelBox()); - stream.write(tmp.getData(), tmp.getSize()); - } - stream.writeChunkEnd(TERRAINDERIVEDDATA_CHUNK_ID); - } - - // colourmap - if (mGlobalColourMapEnabled) - { - stream.writeChunkBegin(TERRAINDERIVEDDATA_CHUNK_ID, TERRAINDERIVEDDATA_CHUNK_VERSION); - String colourDataType("colourmap"); - stream.write(&colourDataType); - stream.write(&mGlobalColourMapSize); - if (mCpuColourMap.getData()) - { - // save from CPU data if it's there, it means GPU data was never created - stream.write(mCpuColourMap.getData(), mCpuColourMap.getSize()); - } - else - { - Image tmp(PF_BYTE_RGB, mGlobalColourMapSize, mGlobalColourMapSize); - mColourMap->getBuffer()->blitToMemory(tmp.getPixelBox()); - stream.write(tmp.getData(), tmp.getSize()); - } - stream.writeChunkEnd(TERRAINDERIVEDDATA_CHUNK_ID); - - } - - // lightmap - if (mLightMapRequired) - { - stream.writeChunkBegin(TERRAINDERIVEDDATA_CHUNK_ID, TERRAINDERIVEDDATA_CHUNK_VERSION); - String lightmapDataType("lightmap"); - stream.write(&lightmapDataType); - stream.write(&mLightmapSize); - if (mCpuLightmap.getData()) - { - // save from CPU data if it's there, it means GPU data was never created - stream.write(mCpuLightmap.getData(), mCpuLightmap.getSize()); - } - else - { - Image tmp(PF_L8, mLightmapSize, mLightmapSize); - mLightmap->getBuffer()->blitToMemory(tmp.getPixelBox()); - stream.write(tmp.getData(), tmp.getSize()); - } - stream.writeChunkEnd(TERRAINDERIVEDDATA_CHUNK_ID); - } - - // composite map - if (mCompositeMapRequired) - { - stream.writeChunkBegin(TERRAINDERIVEDDATA_CHUNK_ID, TERRAINDERIVEDDATA_CHUNK_VERSION); - String compositeMapDataType("compositemap"); - stream.write(&compositeMapDataType); - stream.write(&mCompositeMapSize); - if (mCpuCompositeMap.getData()) - { - // save from CPU data if it's there, it means GPU data was never created - stream.write(mCpuCompositeMap.getData(), mCpuCompositeMap.getSize()); - } - else - { - // composite map is 4 channel, 3x diffuse, 1x specular mask - Image tmp(PF_BYTE_RGBA, mCompositeMapSize, mCompositeMapSize); - mCompositeMap->getBuffer()->blitToMemory(tmp.getPixelBox()); - stream.write(tmp.getData(), tmp.getSize()); - } - stream.writeChunkEnd(TERRAINDERIVEDDATA_CHUNK_ID); - } - - // write the quadtree - mQuadTree->save(stream); - - // stop compressing - stream.stopDeflate(); - - stream.writeChunkEnd(TERRAIN_CHUNK_ID); - - mModified = false; - mHeightDataModified = false; - - } - //--------------------------------------------------------------------- - void Terrain::writeLayerDeclaration(const TerrainLayerDeclaration& decl, StreamSerialiser& stream) - { - // Layer declaration - stream.writeChunkBegin(TERRAINLAYERDECLARATION_CHUNK_ID, TERRAINLAYERDECLARATION_CHUNK_VERSION); - // samplers - uint8 numSamplers = (uint8)decl.size(); - stream.write(&numSamplers); - for (const auto & sampler : decl) - { - stream.writeChunkBegin(TERRAINLAYERSAMPLER_CHUNK_ID, TERRAINLAYERSAMPLER_CHUNK_VERSION); - stream.write(&sampler.alias); - uint8 pixFmt = (uint8)sampler.format; - stream.write(&pixFmt); - stream.writeChunkEnd(TERRAINLAYERSAMPLER_CHUNK_ID); - } - // elements - uint8 numElems = 0; - stream.write(&numElems); - stream.writeChunkEnd(TERRAINLAYERDECLARATION_CHUNK_ID); - } - //--------------------------------------------------------------------- - bool Terrain::readLayerDeclaration(StreamSerialiser& stream, TerrainLayerDeclaration& targetdecl) - { - if (!stream.readChunkBegin(TERRAINLAYERDECLARATION_CHUNK_ID, TERRAINLAYERDECLARATION_CHUNK_VERSION)) - return false; - // samplers - uint8 numSamplers; - stream.read(&numSamplers); - targetdecl.resize(numSamplers); - for (uint8 s = 0; s < numSamplers; ++s) - { - if (!stream.readChunkBegin(TERRAINLAYERSAMPLER_CHUNK_ID, TERRAINLAYERSAMPLER_CHUNK_VERSION)) - return false; - - stream.read(&(targetdecl[s].alias)); - uint8 pixFmt; - stream.read(&pixFmt); - targetdecl[s].format = (PixelFormat)pixFmt; - stream.readChunkEnd(TERRAINLAYERSAMPLER_CHUNK_ID); - } - // elements are gone, keeping for backward compatibility - uint8 numElems; - stream.read(&numElems); - for (uint8 e = 0; e < numElems; ++e) - { - if (!stream.readChunkBegin(TERRAINLAYERSAMPLERELEMENT_CHUNK_ID, TERRAINLAYERSAMPLERELEMENT_CHUNK_VERSION)) - return false; - - uint8 unused; - stream.read(&unused); // source - stream.read(&unused); // semantic - stream.read(&unused); // start - stream.read(&unused); // count - stream.readChunkEnd(TERRAINLAYERSAMPLERELEMENT_CHUNK_ID); - } - stream.readChunkEnd(TERRAINLAYERDECLARATION_CHUNK_ID); - - return true; - } - //--------------------------------------------------------------------- - void Terrain::writeLayerInstanceList(const Terrain::LayerInstanceList& layers, StreamSerialiser& stream) - { - uint8 numLayers = (uint8)layers.size(); - stream.write(&numLayers); - for (const auto & inst : layers) - { - stream.writeChunkBegin(TERRAINLAYERINSTANCE_CHUNK_ID, TERRAINLAYERINSTANCE_CHUNK_VERSION); - stream.write(&inst.worldSize); - for (const auto & textureName : inst.textureNames) - { - stream.write(&textureName); - } - stream.writeChunkEnd(TERRAINLAYERINSTANCE_CHUNK_ID); - } - - } - //--------------------------------------------------------------------- - bool Terrain::readLayerInstanceList(StreamSerialiser& stream, size_t numSamplers, Terrain::LayerInstanceList& targetlayers) - { - uint8 numLayers; - stream.read(&numLayers); - targetlayers.resize(numLayers); - for (uint8 l = 0; l < numLayers; ++l) - { - if (!stream.readChunkBegin(TERRAINLAYERINSTANCE_CHUNK_ID, TERRAINLAYERINSTANCE_CHUNK_VERSION)) - return false; - stream.read(&targetlayers[l].worldSize); - targetlayers[l].textureNames.resize(numSamplers); - for (size_t t = 0; t < numSamplers; ++t) - { - stream.read(&(targetlayers[l].textureNames[t])); - } - stream.readChunkEnd(TERRAINLAYERINSTANCE_CHUNK_ID); - } - - return true; - } - //--------------------------------------------------------------------- - const String& Terrain::_getDerivedResourceGroup() const - { - if (mResourceGroup.empty()) - return TerrainGlobalOptions::getSingleton().getDefaultResourceGroup(); - else - return mResourceGroup; - } - //--------------------------------------------------------------------- - bool Terrain::prepare(const String& filename) - { - DataStreamPtr stream = ResourceGroupManager::getSingleton().openResource(filename, _getDerivedResourceGroup()); - - return prepare(stream); - } - //--------------------------------------------------------------------- - bool Terrain::prepare(DataStreamPtr& stream) - { - freeLodData(); - mLodManager = OGRE_NEW TerrainLodManager( this, stream ); - StreamSerialiser ser(stream); - return prepare(ser); - } - //--------------------------------------------------------------------- - bool Terrain::prepare(StreamSerialiser& stream) - { - mPrepareInProgress = true; - - freeTemporaryResources(); - freeCPUResources(); - - if(mLodManager == NULL) - { - mLodManager = OGRE_NEW TerrainLodManager( this ); - } - - copyGlobalOptions(); - - const StreamSerialiser::Chunk *mainChunk = stream.readChunkBegin(TERRAIN_CHUNK_ID, TERRAIN_CHUNK_VERSION); - if (!mainChunk) - return false; - - if(mainChunk->version > 1) - stream.readChunkBegin(Terrain::TERRAINGENERALINFO_CHUNK_ID, Terrain::TERRAINGENERALINFO_CHUNK_VERSION); - uint8 align; - stream.read(&align); - mAlign = (Alignment)align; - stream.read(&mSize); - stream.read(&mWorldSize); - - stream.read(&mMaxBatchSize); - stream.read(&mMinBatchSize); - stream.read(&mPos); - mRootNode->setPosition(mPos); - updateBaseScale(); - determineLodLevels(); - - if(mainChunk->version > 1) - stream.readChunkEnd(Terrain::TERRAINGENERALINFO_CHUNK_ID); - - size_t numVertices = mSize * mSize; - mHeightData = OGRE_ALLOC_T(float, numVertices, MEMCATEGORY_GEOMETRY); - mDeltaData = OGRE_ALLOC_T(float, numVertices, MEMCATEGORY_GEOMETRY); - // As we may not load full data, so we should make it clean first - memset(mHeightData, 0.0f, sizeof(float)*numVertices); - memset(mDeltaData, 0.0f, sizeof(float)*numVertices); - - if(mainChunk->version > 1) - { - // skip height/delta data - for (int i = 0; i < mNumLodLevels; i++) - { - stream.readChunkBegin(TerrainLodManager::TERRAINLODDATA_CHUNK_ID, TerrainLodManager::TERRAINLODDATA_CHUNK_VERSION); - stream.readChunkEnd(TerrainLodManager::TERRAINLODDATA_CHUNK_ID); - } - - // start uncompressing - stream.startDeflate( mainChunk->length - stream.getOffsetFromChunkStart() ); - } - else - { - stream.read(mHeightData, numVertices); - } - - // Layer declaration - if (!readLayerDeclaration(stream, mLayerDecl)) - return false; - checkDeclaration(); - - - // Layers - if (!readLayerInstanceList(stream, mLayerDecl.size(), mLayers)) - return false; - deriveUVMultipliers(); - - // Packed layer blend data - uint8 numLayers = (uint8)mLayers.size(); - stream.read(&mLayerBlendMapSize); - mLayerBlendMapSizeActual = mLayerBlendMapSize; // for now, until we check - // load packed CPU data - int numBlendTex = getBlendTextureCount(numLayers); - for (int i = 0; i < numBlendTex; ++i) - { - mCpuBlendMapStorage.emplace_back(PF_BYTE_RGBA, mLayerBlendMapSize, mLayerBlendMapSize); - stream.read(mCpuBlendMapStorage.back().getData(), mCpuBlendMapStorage.back().getSize()); - } - - // derived data - while (!stream.isEndOfChunk(TERRAIN_CHUNK_ID) && - stream.peekNextChunkID() == TERRAINDERIVEDDATA_CHUNK_ID) - { - stream.readChunkBegin(TERRAINDERIVEDDATA_CHUNK_ID, TERRAINDERIVEDDATA_CHUNK_VERSION); - // name - String name; - stream.read(&name); - uint16 sz; - stream.read(&sz); - if (name == "normalmap") - { - mNormalMapRequired = true; - mCpuTerrainNormalMap.create(PF_BYTE_RGB, sz, sz); - stream.read(mCpuTerrainNormalMap.getData(), mCpuTerrainNormalMap.getSize()); - - } - else if (name == "colourmap") - { - mGlobalColourMapEnabled = true; - mGlobalColourMapSize = sz; - mCpuColourMap.create(PF_BYTE_RGB, sz, sz); - stream.read(mCpuColourMap.getData(), mCpuColourMap.getSize()); - } - else if (name == "lightmap") - { - mLightMapRequired = true; - mLightmapSize = sz; - mCpuLightmap.create(PF_L8, sz, sz); - stream.read(mCpuLightmap.getData(), mCpuLightmap.getSize()); - } - else if (name == "compositemap") - { - mCompositeMapRequired = true; - mCompositeMapSize = sz; - mCpuCompositeMap.create(PF_BYTE_RGBA, sz, sz); - stream.read(mCpuCompositeMap.getData(), mCpuCompositeMap.getSize()); - } - - stream.readChunkEnd(TERRAINDERIVEDDATA_CHUNK_ID); - - - } - - if(mainChunk->version == 1) - { - // Load delta data - mDeltaData = OGRE_ALLOC_T(float, numVertices, MEMCATEGORY_GEOMETRY); - stream.read(mDeltaData, numVertices); - } - - // Create & load quadtree - mQuadTree = OGRE_NEW TerrainQuadTreeNode(this, 0, 0, 0, mSize, mNumLodLevels - 1, 0); - mQuadTree->prepare(stream); - - // stop uncompressing - if(mainChunk->version > 1) - stream.stopDeflate(); - - stream.readChunkEnd(TERRAIN_CHUNK_ID); - - mModified = false; - mHeightDataModified = false; - - mPrepareInProgress = false; - - return true; - } - //--------------------------------------------------------------------- - bool Terrain::prepare(const ImportData& importData) - { - mPrepareInProgress = true; - freeTemporaryResources(); - freeLodData(); - freeCPUResources(); - mLodManager = OGRE_NEW TerrainLodManager( this ); - - copyGlobalOptions(); - - // validate - if (!(Bitwise::isPO2(importData.terrainSize - 1) && Bitwise::isPO2(importData.minBatchSize - 1) - && Bitwise::isPO2(importData.maxBatchSize - 1))) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "terrainSize, minBatchSize and maxBatchSize must all be 2^n + 1", - "Terrain::prepare"); - } - - if (importData.minBatchSize > importData.maxBatchSize) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "minBatchSize must be less than or equal to maxBatchSize", - "Terrain::prepare"); - } - - if (importData.maxBatchSize > TERRAIN_MAX_BATCH_SIZE) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "maxBatchSize must be no larger than " + - StringConverter::toString(TERRAIN_MAX_BATCH_SIZE), - "Terrain::prepare"); - } - - mAlign = importData.terrainAlign; - mSize = importData.terrainSize; - mWorldSize = importData.worldSize; - mLayerDecl = importData.layerDeclaration; - checkDeclaration(); - mLayers = importData.layerList; - checkLayers(false); - deriveUVMultipliers(); - mMaxBatchSize = importData.maxBatchSize; - mMinBatchSize = importData.minBatchSize; - setPosition(importData.pos); - - updateBaseScale(); - determineLodLevels(); - - size_t numVertices = mSize * mSize; - - mHeightData = OGRE_ALLOC_T(float, numVertices, MEMCATEGORY_GEOMETRY); - - if (importData.inputFloat) - { - if (Math::RealEqual(importData.inputBias, 0.0) && Math::RealEqual(importData.inputScale, 1.0)) - { - // straight copy - memcpy(mHeightData, importData.inputFloat, sizeof(float) * numVertices); - } - else - { - // scale & bias - float* src = importData.inputFloat; - float* dst = mHeightData; - for (size_t i = 0; i < numVertices; ++i) - *dst++ = (*src++ * importData.inputScale) + importData.inputBias; - } - } - else if (importData.inputImage) - { - Image* img = importData.inputImage; - - if (img->getWidth() != mSize || img->getHeight() != mSize) - img->resize(mSize, mSize); - - // convert image data to floats - // Do this on a row-by-row basis, because we describe the terrain in - // a bottom-up fashion (ie ascending world coords), while Image is top-down - for (uint16 i = 0; i < mSize; ++i) - { - uint32 srcy = mSize - i - 1; - float* pDst = mHeightData + i * mSize; - PixelUtil::bulkPixelConversion(img->getData(0, srcy), img->getFormat(), pDst, PF_FLOAT32_R, - mSize); - } - - if (!Math::RealEqual(importData.inputBias, 0.0) || !Math::RealEqual(importData.inputScale, 1.0)) - { - float* pAdj = mHeightData; - for (size_t i = 0; i < numVertices; ++i) - { - *pAdj = (*pAdj * importData.inputScale) + importData.inputBias; - ++pAdj; - } - } - - } - else - { - // start with flat terrain - if (importData.constantHeight == 0) - memset(mHeightData, 0, sizeof(float) * mSize * mSize); - else - { - float* pFloat = mHeightData; - for (long i = 0 ; i < mSize * mSize; ++i) - *pFloat++ = importData.constantHeight; - - } - } - - mDeltaData = OGRE_ALLOC_T(float, numVertices, MEMCATEGORY_GEOMETRY); - memset(mDeltaData, 0, sizeof(float) * numVertices); - - mQuadTree = OGRE_NEW TerrainQuadTreeNode(this, 0, 0, 0, mSize, mNumLodLevels - 1, 0); - mQuadTree->prepare(); - - // calculate entire terrain - Rect rect(0, 0, mSize, mSize); - calculateHeightDeltas(rect); - finaliseHeightDeltas(rect, true); - - distributeVertexData(); - - // Imported data is treated as modified because it's not saved - mModified = true; - mHeightDataModified = true; - - mPrepareInProgress = false; - - return true; - - } - //--------------------------------------------------------------------- - void Terrain::copyGlobalOptions() - { - TerrainGlobalOptions& opts = TerrainGlobalOptions::getSingleton(); - mSkirtSize = opts.getSkirtSize(); - mRenderQueueGroup = opts.getRenderQueueGroup(); - mVisibilityFlags = opts.getVisibilityFlags(); - mQueryFlags = opts.getQueryFlags(); - mLayerBlendMapSize = opts.getLayerBlendMapSize(); - mLayerBlendMapSizeActual = mLayerBlendMapSize; // for now, until we check - mLightmapSize = opts.getLightMapSize(); - mLightmapSizeActual = mLightmapSize; // for now, until we check - mCompositeMapSize = opts.getCompositeMapSize(); - mCompositeMapSizeActual = mCompositeMapSize; // for now, until we check - - } - //--------------------------------------------------------------------- - void Terrain::determineLodLevels() - { - /* On a leaf-node basis, LOD can vary from maxBatch to minBatch in - number of vertices. After that, nodes will be gathered into parent - nodes with the same number of vertices, but they are combined with - 3 of their siblings. In practice, the number of LOD levels overall - is: - LODlevels = log2(size - 1) - log2(minBatch - 1) + 1 - TreeDepth = log2((size - 1) / (maxBatch - 1)) + 1 - - .. it's just that at the max LOD, the terrain is divided into - (size - 1) / (maxBatch - 1) tiles each of maxBatch vertices, and - at the lowest LOD the terrain is made up of one single tile of - minBatch vertices. - - Example: size = 257, minBatch = 17, maxBatch = 33 - - LODlevels = log2(257 - 1) - log2(17 - 1) + 1 = 8 - 4 + 1 = 5 - TreeDepth = log2((size - 1) / (maxBatch - 1)) + 1 = 4 - - LOD list - this assumes everything changes at once, which rarely happens of course - in fact except where groupings must occur, tiles can change independently - LOD 0: 257 vertices, 8 x 33 vertex tiles (tree depth 3) - LOD 1: 129 vertices, 8 x 17 vertex tiles (tree depth 3) - LOD 2: 65 vertices, 4 x 17 vertex tiles (tree depth 2) - LOD 3: 33 vertices, 2 x 17 vertex tiles (tree depth 1) - LOD 4: 17 vertices, 1 x 17 vertex tiles (tree depth 0) - - Notice how we only have 2 sizes of index buffer to be concerned about, - 17 vertices (per side) or 33. This makes buffer re-use much easier while - still giving the full range of LODs. - */ - mNumLodLevelsPerLeafNode = (uint16) (Math::Log2(mMaxBatchSize - 1.0f) - Math::Log2(mMinBatchSize - 1.0f) + 1.0f); - mNumLodLevels = (uint16) (Math::Log2(mSize - 1.0f) - Math::Log2(mMinBatchSize - 1.0f) + 1.0f); - //mTreeDepth = Math::Log2(mMaxBatchSize - 1) - Math::Log2(mMinBatchSize - 1) + 2; - mTreeDepth = mNumLodLevels - mNumLodLevelsPerLeafNode + 1; - - LogManager::getSingleton().stream() << "Terrain created; size=" << mSize - << " minBatch=" << mMinBatchSize << " maxBatch=" << mMaxBatchSize - << " treeDepth=" << mTreeDepth << " lodLevels=" << mNumLodLevels - << " leafLods=" << mNumLodLevelsPerLeafNode; - } - //--------------------------------------------------------------------- - void Terrain::distributeVertexData() - { - /* Now we need to figure out how to distribute vertex data. We want to - use 16-bit indexes for compatibility, which means that the maximum patch - size that we can address (even sparsely for lower LODs) is 129x129 - (the next one up, 257x257 is too big). - - So we need to split the vertex data into chunks of 129. The number of - primary tiles this creates also indicates the point above which in - the node tree that we can no longer merge tiles at lower LODs without - using different vertex data. For example, using the 257x257 input example - above, the vertex data would have to be split in 2 (in each dimension) - in order to fit within the 129x129 range. This data could be shared by - all tree depths from 1 onwards, it's just that LODs 3-1 would sample - the 129x129 data sparsely. LOD 0 would sample all of the vertices. - - LOD 4 however, the lowest LOD, could not work with the same vertex data - because it needs to cover the entire terrain. There are 2 choices here: - create another set of vertex data at 17x17 which is only used by LOD 4, - or make LOD 4 occur at tree depth 1 instead (ie still split up, and - rendered as 2x9 along each edge instead. - - Since rendering very small batches is not desirable, and the vertex counts - are inherently not going to be large, creating a separate vertex set is - preferable. This will also be more efficient on the vertex cache with - distant terrains. - - We probably need a larger example, because in this case only 1 level (LOD 0) - needs to use this separate vertex data. Higher detail terrains will need - it for multiple levels, here's a 2049x2049 example with 65 / 33 batch settings: - - LODlevels = log2(2049 - 1) - log2(33 - 1) + 1 = 11 - 5 + 1 = 7 - TreeDepth = log2((2049 - 1) / (65 - 1)) + 1 = 6 - Number of vertex data splits at most detailed level: - (size - 1) / (TERRAIN_MAX_BATCH_SIZE - 1) = 2048 / 128 = 16 - - LOD 0: 2049 vertices, 32 x 65 vertex tiles (tree depth 5) vdata 0-15 [129x16] - LOD 1: 1025 vertices, 32 x 33 vertex tiles (tree depth 5) vdata 0-15 [129x16] - LOD 2: 513 vertices, 16 x 33 vertex tiles (tree depth 4) vdata 0-15 [129x16] - LOD 3: 257 vertices, 8 x 33 vertex tiles (tree depth 3) vdata 16-17 [129x2] - LOD 4: 129 vertices, 4 x 33 vertex tiles (tree depth 2) vdata 16-17 [129x2] - LOD 5: 65 vertices, 2 x 33 vertex tiles (tree depth 1) vdata 16-17 [129x2] - LOD 6: 33 vertices, 1 x 33 vertex tiles (tree depth 0) vdata 18 [33] - - All the vertex counts are to be squared, they are just along one edge. - So as you can see, we need to have 3 levels of vertex data to satisy this - (admittedly quite extreme) case, and a total of 19 sets of vertex data. - The full detail geometry, which is 16(x16) sets of 129(x129), used by - LODs 0-2. LOD 3 can't use this set because it needs to group across them, - because it has only 8 tiles, so we make another set which satisfies this - at a maximum of 129 vertices per vertex data section. In this case LOD - 3 needs 257(x257) total vertices so we still split into 2(x2) sets of 129. - This set is good up to and including LOD 5, but LOD 6 needs a single - contiguous set of vertices, so we make a 33x33 vertex set for it. - - In terms of vertex data stored, this means that while our primary data is: - 2049^2 = 4198401 vertices - our final stored vertex data is - (16 * 129)^2 + (2 * 129)^2 + 33^2 = 4327749 vertices - - That equals a 3% premium, but it's both necessary and worth it for the - reduction in batch count resulting from the grouping. In addition, at - LODs 3 and 6 (or rather tree depth 3 and 0) there is the opportunity - to free up the vertex data used by more detailed LODs, which is - important when dealing with large terrains. For example, if we - freed the (GPU) vertex data for LOD 0-2 in the medium distance, - we would save 98% of the memory overhead for this terrain. - - */ - - LogManager& logMgr = LogManager::getSingleton(); - logMgr.stream(LML_TRIVIAL) << "Terrain::distributeVertexData processing source " - "terrain size of " << mSize; - - uint16 depth = mTreeDepth; - uint16 prevdepth = depth; - uint16 currresolution = mSize; - uint16 bakedresolution = mSize; - uint16 targetSplits = (bakedresolution - 1) / (TERRAIN_MAX_BATCH_SIZE - 1); - while(depth-- && targetSplits) - { - uint splits = 1 << depth; - if (splits == targetSplits) - { - logMgr.stream(LML_TRIVIAL) << " Assigning vertex data, resolution=" - << bakedresolution << " startDepth=" << depth << " endDepth=" << prevdepth - << " splits=" << splits; - // vertex data goes at this level, at bakedresolution - // applies to all lower levels (except those with a closer vertex data) - // determine physical size (as opposed to resolution) - uint sz = ((bakedresolution-1) / splits) + 1; - mQuadTree->assignVertexData(depth, prevdepth, bakedresolution, sz); - - // next set to look for - bakedresolution = ((currresolution - 1) >> 1) + 1; - targetSplits = (bakedresolution - 1) / (TERRAIN_MAX_BATCH_SIZE - 1); - prevdepth = depth; - - } - - currresolution = ((currresolution - 1) >> 1) + 1; - - - } - - // Always assign vertex data to the top of the tree - if (prevdepth > 0) - { - mQuadTree->assignVertexData(0, 1, bakedresolution, bakedresolution); - logMgr.stream(LML_TRIVIAL) << " Assigning vertex data, resolution: " - << bakedresolution << " startDepth=0 endDepth=1 splits=1"; - - } - - logMgr.stream(LML_TRIVIAL) << "Terrain::distributeVertexData finished"; - - } - //--------------------------------------------------------------------- - void Terrain::load(const String& filename) - { - if (prepare(filename)) - load(); - else - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Error while preparing " + filename + ", see log for details"); - } - //--------------------------------------------------------------------- - void Terrain::load(StreamSerialiser& stream) - { - if (prepare(stream)) - load(); - else - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Error while preparing from stream, see log for details"); - } - //--------------------------------------------------------------------- - void Terrain::load(int lodLevel, bool synchronous) - { - if (mQuadTree) - mLodManager->updateToLodLevel(lodLevel,synchronous); - - if (mIsLoaded || mGenerateMaterialInProgress) - return; - - checkLayers(true); - createOrDestroyGPUColourMap(); - createOrDestroyGPUNormalMap(); - createOrDestroyGPULightmap(); - createOrDestroyGPUCompositeMap(); - - mMaterialGenerator->requestOptions(this); - - mGenerateMaterialInProgress = true; - - if(synchronous) - { - generateMaterial(); - return; - } - - Root::getSingleton().getWorkQueue()->addMainThreadTask([this]() { generateMaterial(); }); - } - //--------------------------------------------------------------------- - void Terrain::unload() - { - if (!mIsLoaded) - return; - - if (mQuadTree) - mQuadTree->unload(); - - // free own buffers if used, but not custom - mDefaultGpuBufferAllocator.freeAllBuffers(); - - mIsLoaded = false; - mModified = false; - mHeightDataModified = false; - - } - //--------------------------------------------------------------------- - void Terrain::unprepare() - { - if (mQuadTree) - mQuadTree->unprepare(); - } - //--------------------------------------------------------------------- - float* Terrain::getHeightData() const - { - return mHeightData; - } - //--------------------------------------------------------------------- - float* Terrain::getHeightData(uint32 x, uint32 y) const - { - assert (x < mSize && y < mSize); - return &mHeightData[y * mSize + x]; - } - //--------------------------------------------------------------------- - float Terrain::getHeightAtPoint(uint32 x, uint32 y) const - { - // clamp - x = std::min(x, mSize - 1u); - y = std::min(y, mSize - 1u); - - int highestLod = mLodManager->getHighestLodPrepared(); - uint32 skip = 1 << (highestLod != -1 ? highestLod : 0); - if (x % skip == 0 && y % skip == 0) - return *getHeightData(x, y); - - uint32 x1 = std::min( (x/skip) * skip , mSize - 1u ); - uint32 x2 = std::min( ((x+skip) / skip) * skip, mSize - 1u ); - uint32 y1 = std::min( (y/skip) * skip , mSize - 1u ); - uint32 y2 = std::min( ((y+skip) / skip) * skip, mSize - 1u ); - - float rx = (float(x % skip) / skip); - float ry = (float(y % skip) / skip); - - return *getHeightData(x1, y1) * (1.0f-rx) * (1.0f-ry) - + *getHeightData(x2, y1) * rx * (1.0f-ry) - + *getHeightData(x1, y2) * (1.0f-rx) * ry - + *getHeightData(x2, y2) * rx * ry; - } - //--------------------------------------------------------------------- - void Terrain::setHeightAtPoint(uint32 x, uint32 y, float h) - { - // force to load all data - load(0,true); - // clamp - x = std::min(x, mSize - 1u); - y = std::min(y, mSize - 1u); - - *getHeightData(x, y) = h; - Rect rect; - rect.left = x; - rect.right = x+1; - rect.top = y; - rect.bottom = y+1; - dirtyRect(rect); - } - //--------------------------------------------------------------------- - float Terrain::getHeightAtTerrainPosition(Real x, Real y) const - { - // get left / bottom points (rounded down) - Real factor = (Real)mSize - 1.0f; - Real invFactor = 1.0f / factor; - - uint32 startX = static_cast(x * factor); - uint32 startY = static_cast(y * factor); - uint32 endX = startX + 1; - uint32 endY = startY + 1; - - // now get points in terrain space (effectively rounding them to boundaries) - // note that we do not clamp! We need a valid plane - Real startXTS = startX * invFactor; - Real startYTS = startY * invFactor; - Real endXTS = endX * invFactor; - Real endYTS = endY * invFactor; - - // now clamp - endX = std::min(endX, mSize-1u); - endY = std::min(endY, mSize-1u); - - // get parametric from start coord to next point - Real xParam = (x - startXTS) / invFactor; - Real yParam = (y - startYTS) / invFactor; - - - /* For even / odd tri strip rows, triangles are this shape: - even odd - 3---2 3---2 - | / | | \ | - 0---1 0---1 - */ - - // Build all 4 positions in terrain space, using point-sampled height - Vector3 v0 (startXTS, startYTS, getHeightAtPoint(startX, startY)); - Vector3 v1 (endXTS, startYTS, getHeightAtPoint(endX, startY)); - Vector3 v2 (endXTS, endYTS, getHeightAtPoint(endX, endY)); - Vector3 v3 (startXTS, endYTS, getHeightAtPoint(startX, endY)); - // define a plane in terrain space - // do not normalise as the normalization factor cancels out in the final - // equation anyway - Vector4 plane; - if (startY % 2) - { - // odd row - bool secondTri = ((1.0 - yParam) > xParam); - if (secondTri) - plane = Math::calculateFaceNormalWithoutNormalize(v0, v1, v3); - else - plane = Math::calculateFaceNormalWithoutNormalize(v1, v2, v3); - } - else - { - // even row - bool secondTri = (yParam > xParam); - if (secondTri) - plane = Math::calculateFaceNormalWithoutNormalize(v0, v2, v3); - else - plane = Math::calculateFaceNormalWithoutNormalize(v0, v1, v2); - } - - // Solve plane equation for z - return (-plane.x * x - plane.y * y - plane.w) / plane.z; - } - //--------------------------------------------------------------------- - float Terrain::getHeightAtWorldPosition(Real x, Real y, Real z) const - { - Vector3 terrPos; - getTerrainPosition(x, y, z, &terrPos); - return getHeightAtTerrainPosition(terrPos.x, terrPos.y); - } - //--------------------------------------------------------------------- - float Terrain::getHeightAtWorldPosition(const Vector3& pos) const - { - return getHeightAtWorldPosition(pos.x, pos.y, pos.z); - } - //--------------------------------------------------------------------- - const float* Terrain::getDeltaData() const - { - return mDeltaData; - } - //--------------------------------------------------------------------- - const float* Terrain::getDeltaData(uint32 x, uint32 y) const - { - assert (x < mSize && y < mSize); - return &mDeltaData[y * mSize + x]; - } - //--------------------------------------------------------------------- - Vector3 Terrain::convertPosition(Space inSpace, const Vector3& inPos, Space outSpace) const - { - Vector3 ret; - convertPosition(inSpace, inPos, outSpace, ret); - return ret; - } - //--------------------------------------------------------------------- - Vector3 Terrain::convertDirection(Space inSpace, const Vector3& inDir, Space outSpace) const - { - Vector3 ret; - convertDirection(inSpace, inDir, outSpace, ret); - return ret; - } - //--------------------------------------------------------------------- - void Terrain::convertPosition(Space inSpace, const Vector3& inPos, Space outSpace, Vector3& outPos) const - { - convertSpace(inSpace, inPos, outSpace, outPos, true); - } - //--------------------------------------------------------------------- - void Terrain::convertDirection(Space inSpace, const Vector3& inDir, Space outSpace, Vector3& outDir) const - { - convertSpace(inSpace, inDir, outSpace, outDir, false); - } - //--------------------------------------------------------------------- - void Terrain::convertSpace(Space inSpace, const Vector3& inVec, Space outSpace, Vector3& outVec, bool translation) const - { - Space currSpace = inSpace; - outVec = inVec; - while (currSpace != outSpace) - { - switch(currSpace) - { - case WORLD_SPACE: - // In all cases, transition to local space - if (translation) - outVec -= mPos; - currSpace = LOCAL_SPACE; - break; - case LOCAL_SPACE: - switch(outSpace) - { - case WORLD_SPACE: - if (translation) - outVec += mPos; - currSpace = WORLD_SPACE; - break; - case POINT_SPACE: - case TERRAIN_SPACE: - // go via terrain space - outVec = convertWorldToTerrainAxes(outVec); - if (translation) - { - outVec.x -= mBase; outVec.y -= mBase; - outVec.x /= (mSize - 1) * mScale; outVec.y /= (mSize - 1) * mScale; - } - currSpace = TERRAIN_SPACE; - break; - case LOCAL_SPACE: - default: - break; - }; - break; - case TERRAIN_SPACE: - switch(outSpace) - { - case WORLD_SPACE: - case LOCAL_SPACE: - // go via local space - if (translation) - { - outVec.x *= (mSize - 1) * mScale; outVec.y *= (mSize - 1) * mScale; - outVec.x += mBase; outVec.y += mBase; - } - outVec = convertTerrainToWorldAxes(outVec); - currSpace = LOCAL_SPACE; - break; - case POINT_SPACE: - if (translation) - { - outVec.x *= (mSize - 1); outVec.y *= (mSize - 1); - // rounding up/down - // this is why POINT_SPACE is the last on the list, because it loses data - outVec.x = static_cast(static_cast(outVec.x + 0.5)); - outVec.y = static_cast(static_cast(outVec.y + 0.5)); - } - currSpace = POINT_SPACE; - break; - case TERRAIN_SPACE: - default: - break; - }; - break; - case POINT_SPACE: - // always go via terrain space - if (translation) - { - outVec.x /= (mSize - 1); - outVec.y /= (mSize - 1); - } - currSpace = TERRAIN_SPACE; - break; - - }; - } - - } - //--------------------------------------------------------------------- - void Terrain::convertWorldToTerrainAxes(Alignment align, const Vector3& worldVec, Vector3* terrainVec) - { - switch (align) - { - case ALIGN_X_Z: - terrainVec->z = worldVec.y; - terrainVec->x = worldVec.x; - terrainVec->y = -worldVec.z; - break; - case ALIGN_Y_Z: - terrainVec->z = worldVec.x; - terrainVec->x = -worldVec.z; - terrainVec->y = worldVec.y; - break; - case ALIGN_X_Y: - *terrainVec = worldVec; - break; - }; - - } - //--------------------------------------------------------------------- - void Terrain::convertTerrainToWorldAxes(Alignment align, const Vector3& terrainVec, Vector3* worldVec) - { - switch (align) - { - case ALIGN_X_Z: - worldVec->x = terrainVec.x; - worldVec->y = terrainVec.z; - worldVec->z = -terrainVec.y; - break; - case ALIGN_Y_Z: - worldVec->x = terrainVec.z; - worldVec->y = terrainVec.y; - worldVec->z = -terrainVec.x; - break; - case ALIGN_X_Y: - *worldVec = terrainVec; - break; - }; - - } - //--------------------------------------------------------------------- - Vector3 Terrain::convertWorldToTerrainAxes(const Vector3& inVec) const - { - Vector3 ret; - convertWorldToTerrainAxes(mAlign, inVec, &ret); - - return ret; - } - //--------------------------------------------------------------------- - Vector3 Terrain::convertTerrainToWorldAxes(const Vector3& inVec) const - { - Vector3 ret; - convertTerrainToWorldAxes(mAlign, inVec, &ret); - - return ret; - } - //--------------------------------------------------------------------- - void Terrain::getPoint(uint32 x, uint32 y, Vector3* outpos) const - { - getPointAlign(x, y, mAlign, outpos); - } - //--------------------------------------------------------------------- - void Terrain::getPoint(uint32 x, uint32 y, float height, Vector3* outpos) const - { - getPointAlign(x, y, height, mAlign, outpos); - } - //--------------------------------------------------------------------- - void Terrain::getPointAlign(uint32 x, uint32 y, Alignment align, Vector3* outpos) const - { - getPointAlign(x, y, *getHeightData(x, y), align, outpos); - } - //--------------------------------------------------------------------- - void Terrain::getPointAlign(uint32 x, uint32 y, float height, Alignment align, Vector3* outpos) const - { - switch(align) - { - case ALIGN_X_Z: - outpos->y = height; - outpos->x = x * mScale + mBase; - outpos->z = y * -mScale - mBase; - break; - case ALIGN_Y_Z: - outpos->x = height; - outpos->z = x * -mScale - mBase; - outpos->y = y * mScale + mBase; - break; - case ALIGN_X_Y: - outpos->z = height; - outpos->x = x * mScale + mBase; - outpos->y = y * mScale + mBase; - break; - }; - - } - //--------------------------------------------------------------------- - Affine3 Terrain::getPointTransform() const - { - auto outXform = Affine3::ZERO; - switch(mAlign) - { - case ALIGN_X_Z: - //outpos->y = height (z) - outXform[1][2] = 1.0f; - //outpos->x = x * mScale + mBase; - outXform[0][0] = mScale; - outXform[0][3] = mBase; - //outpos->z = y * -mScale - mBase; - outXform[2][1] = -mScale; - outXform[2][3] = -mBase; - break; - case ALIGN_Y_Z: - //outpos->x = height; - outXform[0][2] = 1.0f; - //outpos->z = x * -mScale - mBase; - outXform[2][0] = -mScale; - outXform[2][3] = -mBase; - //outpos->y = y * mScale + mBase; - outXform[1][1] = mScale; - outXform[1][3] = mBase; - break; - case ALIGN_X_Y: - //outpos->z = height; - outXform[2][2] = 1.0f; - //outpos->x = x * mScale + mBase; - outXform[0][0] = mScale; - outXform[0][3] = mBase; - //outpos->y = y * mScale + mBase; - outXform[1][1] = mScale; - outXform[1][3] = mBase; - break; - }; - return outXform; - } - //--------------------------------------------------------------------- - void Terrain::getVector(const Vector3& inVec, Vector3* outVec) const - { - getVectorAlign(inVec.x, inVec.y, inVec.z, mAlign, outVec); - } - //--------------------------------------------------------------------- - void Terrain::getVector(Real x, Real y, Real z, Vector3* outVec) const - { - getVectorAlign(x, y, z, mAlign, outVec); - } - //--------------------------------------------------------------------- - void Terrain::getVectorAlign(const Vector3& inVec, Alignment align, Vector3* outVec) const - { - getVectorAlign(inVec.x, inVec.y, inVec.z, align, outVec); - } - //--------------------------------------------------------------------- - void Terrain::getVectorAlign(Real x, Real y, Real z, Alignment align, Vector3* outVec) const - { - - switch(align) - { - case ALIGN_X_Z: - outVec->y = z; - outVec->x = x; - outVec->z = -y; - break; - case ALIGN_Y_Z: - outVec->x = z; - outVec->y = y; - outVec->z = -x; - break; - case ALIGN_X_Y: - outVec->x = x; - outVec->y = y; - outVec->z = z; - break; - }; - - } - //--------------------------------------------------------------------- - void Terrain::getPosition(const Vector3& TSpos, Vector3* outWSpos) const - { - getPositionAlign(TSpos, mAlign, outWSpos); - } - //--------------------------------------------------------------------- - void Terrain::getPosition(Real x, Real y, Real z, Vector3* outWSpos) const - { - getPositionAlign(x, y, z, mAlign, outWSpos); - } - //--------------------------------------------------------------------- - void Terrain::getTerrainPosition(const Vector3& WSpos, Vector3* outTSpos) const - { - getTerrainPositionAlign(WSpos, mAlign, outTSpos); - } - //--------------------------------------------------------------------- - void Terrain::getTerrainPosition(Real x, Real y, Real z, Vector3* outTSpos) const - { - getTerrainPositionAlign(x, y, z, mAlign, outTSpos); - } - //--------------------------------------------------------------------- - void Terrain::getPositionAlign(const Vector3& TSpos, Alignment align, Vector3* outWSpos) const - { - getPositionAlign(TSpos.x, TSpos.y, TSpos.z, align, outWSpos); - } - //--------------------------------------------------------------------- - void Terrain::getPositionAlign(Real x, Real y, Real z, Alignment align, Vector3* outWSpos) const - { - switch(align) - { - case ALIGN_X_Z: - outWSpos->y = z; - outWSpos->x = x * (mSize - 1) * mScale + mBase; - outWSpos->z = y * (mSize - 1) * -mScale - mBase; - break; - case ALIGN_Y_Z: - outWSpos->x = z; - outWSpos->y = y * (mSize - 1) * mScale + mBase; - outWSpos->z = x * (mSize - 1) * -mScale - mBase; - break; - case ALIGN_X_Y: - outWSpos->z = z; - outWSpos->x = x * (mSize - 1) * mScale + mBase; - outWSpos->y = y * (mSize - 1) * mScale + mBase; - break; - }; - - } - //--------------------------------------------------------------------- - void Terrain::getTerrainPositionAlign(const Vector3& WSpos, Alignment align, Vector3* outTSpos) const - { - getTerrainPositionAlign(WSpos.x, WSpos.y, WSpos.z, align, outTSpos); - } - //--------------------------------------------------------------------- - void Terrain::getTerrainPositionAlign(Real x, Real y, Real z, Alignment align, Vector3* outTSpos) const - { - switch(align) - { - case ALIGN_X_Z: - outTSpos->x = (x - mBase - mPos.x) / ((mSize - 1) * mScale); - outTSpos->y = (z + mBase - mPos.z) / ((mSize - 1) * -mScale); - outTSpos->z = y; - break; - case ALIGN_Y_Z: - outTSpos->x = (z - mBase - mPos.z) / ((mSize - 1) * -mScale); - outTSpos->y = (y + mBase - mPos.y) / ((mSize - 1) * mScale); - outTSpos->z = x; - break; - case ALIGN_X_Y: - outTSpos->x = (x - mBase - mPos.x) / ((mSize - 1) * mScale); - outTSpos->y = (y - mBase - mPos.y) / ((mSize - 1) * mScale); - outTSpos->z = z; - break; - }; - - } - //--------------------------------------------------------------------- - void Terrain::getTerrainVector(const Vector3& inVec, Vector3* outVec) const - { - getTerrainVectorAlign(inVec.x, inVec.y, inVec.z, mAlign, outVec); - } - //--------------------------------------------------------------------- - void Terrain::getTerrainVector(Real x, Real y, Real z, Vector3* outVec) const - { - getTerrainVectorAlign(x, y, z, mAlign, outVec); - } - //--------------------------------------------------------------------- - void Terrain::getTerrainVectorAlign(const Vector3& inVec, Alignment align, Vector3* outVec) const - { - getTerrainVectorAlign(inVec.x, inVec.y, inVec.z, align, outVec); - } - //--------------------------------------------------------------------- - void Terrain::getTerrainVectorAlign(Real x, Real y, Real z, Alignment align, Vector3* outVec) const - { - - switch(align) - { - case ALIGN_X_Z: - outVec->z = y; - outVec->x = x; - outVec->y = -z; - break; - case ALIGN_Y_Z: - outVec->z = x; - outVec->y = y; - outVec->x = -z; - break; - case ALIGN_X_Y: - outVec->x = x; - outVec->y = y; - outVec->z = z; - break; - }; - - } - //--------------------------------------------------------------------- - Terrain::Alignment Terrain::getAlignment() const - { - return mAlign; - } - //--------------------------------------------------------------------- - uint16 Terrain::getSize() const - { - return mSize; - } - //--------------------------------------------------------------------- - uint16 Terrain::getMaxBatchSize() const - { - return mMaxBatchSize; - } - //--------------------------------------------------------------------- - uint16 Terrain::getMinBatchSize() const - { - return mMinBatchSize; - } - //--------------------------------------------------------------------- - Real Terrain::getWorldSize() const - { - return mWorldSize; - } - //--------------------------------------------------------------------- - Real Terrain::getLayerWorldSize(uint8 index) const - { - if (index < mLayers.size()) - { - return mLayers[index].worldSize; - } - else if (!mLayers.empty()) - { - return mLayers[0].worldSize; - } - else - { - return TerrainGlobalOptions::getSingleton().getDefaultLayerTextureWorldSize(); - } - } - //--------------------------------------------------------------------- - void Terrain::setLayerWorldSize(uint8 index, Real size) - { - if (index < mLayers.size()) - { - - if (index >= mLayerUVMultiplier.size()) - mLayerUVMultiplier.resize(index + 1); - - mLayers[index].worldSize = size; - mLayerUVMultiplier[index] = mWorldSize / size; - mMaterialParamsDirty = true; - mModified = true; - } - } - //--------------------------------------------------------------------- - Real Terrain::getLayerUVMultiplier(uint8 index) const - { - if (index < mLayerUVMultiplier.size()) - { - return mLayerUVMultiplier[index]; - } - else if (!mLayerUVMultiplier.empty()) - { - return mLayerUVMultiplier[0]; - } - else - { - // default to tile 100 times - return 100; - } - } - //--------------------------------------------------------------------- - void Terrain::deriveUVMultipliers() - { - mLayerUVMultiplier.resize(mLayers.size()); - for (size_t i = 0; i < mLayers.size(); ++i) - { - const LayerInstance& inst = mLayers[i]; - - mLayerUVMultiplier[i] = mWorldSize / inst.worldSize; - - } - } - //--------------------------------------------------------------------- - const String& Terrain::getLayerTextureName(uint8 layerIndex, uint8 samplerIndex) const - { - if (layerIndex < mLayers.size() && samplerIndex < mLayerDecl.size()) - { - return mLayers[layerIndex].textureNames[samplerIndex]; - } - else - { - return BLANKSTRING; - } - - } - //--------------------------------------------------------------------- - void Terrain::setLayerTextureName(uint8 layerIndex, uint8 samplerIndex, const String& textureName) - { - if (layerIndex < mLayers.size() && samplerIndex < mLayerDecl.size()) - { - if (mLayers[layerIndex].textureNames[samplerIndex] != textureName) - { - mLayers[layerIndex].textureNames[samplerIndex] = textureName; - mMaterialDirty = true; - mMaterialParamsDirty = true; - mModified = true; - } - } - } - //--------------------------------------------------------------------- - void Terrain::setPosition(const Vector3& pos) - { - if (pos != mPos) - { - mPos = pos; - mRootNode->setPosition(pos); - updateBaseScale(); - mModified = true; - } - } - //--------------------------------------------------------------------- - SceneNode* Terrain::_getRootSceneNode() const - { - return mRootNode; - } - //--------------------------------------------------------------------- - void Terrain::updateBaseScale() - { - // centre the terrain on local origin - mBase = -mWorldSize * 0.5; - // scale determines what 1 unit on the grid becomes in world space - mScale = mWorldSize / (Real)(mSize-1); - } - //--------------------------------------------------------------------- - void Terrain::dirty() - { - dirtyRect(Rect(0, 0, mSize, mSize)); - } - //--------------------------------------------------------------------- - void Terrain::dirtyRect(const Rect& rect) - { - mDirtyGeometryRect.merge(rect); - mDirtyGeometryRectForNeighbours.merge(rect); - mDirtyDerivedDataRect.merge(rect); - mCompositeMapDirtyRect.merge(rect); - - mModified = true; - mHeightDataModified = true; - - } - //--------------------------------------------------------------------- - void Terrain::_dirtyCompositeMapRect(const Rect& rect) - { - mCompositeMapDirtyRect.merge(rect); - mModified = true; - } - //--------------------------------------------------------------------- - void Terrain::dirtyLightmapRect(const Rect& rect) - { - mDirtyDerivedDataRect.merge(rect); - - mModified = true; - - } - //--------------------------------------------------------------------- - void Terrain::dirtyLightmap() - { - dirtyLightmapRect(Rect(0, 0, mSize, mSize)); - } - //--------------------------------------------------------------------- - void Terrain::update(bool synchronous) - { - updateGeometry(); - updateDerivedData(synchronous); - } - //--------------------------------------------------------------------- - void Terrain::updateGeometry() - { - if (!mDirtyGeometryRect.isNull()) - { - mQuadTree->updateVertexData(true, false, mDirtyGeometryRect, false); - mDirtyGeometryRect.setNull(); - } - - // propagate changes - notifyNeighbours(); - } - //--------------------------------------------------------------------- - void Terrain::updateGeometryWithoutNotifyNeighbours() - { - if (!mDirtyGeometryRect.isNull()) - { - mQuadTree->updateVertexData(true, false, mDirtyGeometryRect, false); - mDirtyGeometryRect.setNull(); - } - } - //--------------------------------------------------------------------- - void Terrain::updateDerivedData(bool synchronous, uint8 typeMask) - { - if (!mDirtyDerivedDataRect.isNull() || !mDirtyLightmapFromNeighboursRect.isNull()) - { - mModified = true; - if (mDerivedDataUpdateInProgress) - { - // Don't launch many updates, instead wait for the other one - // to finish and issue another afterwards. - mDerivedUpdatePendingMask |= typeMask; - } - else - { - updateDerivedDataImpl(mDirtyDerivedDataRect, mDirtyLightmapFromNeighboursRect, - synchronous, typeMask); - mDirtyDerivedDataRect.setNull(); - mDirtyLightmapFromNeighboursRect.setNull(); - } - } - else - { - // Usually the composite map is updated after the other background - // data is updated (no point doing it beforehand), but if there's - // nothing to update, then we'll do it right now. - updateCompositeMap(); - } - - - } - //--------------------------------------------------------------------- - void Terrain::updateDerivedDataImpl(const Rect& rect, const Rect& lightmapExtraRect, - bool synchronous, uint8 typeMask) - { - mDerivedDataUpdateInProgress = true; - mDerivedUpdatePendingMask = 0; - - DerivedDataRequest req; - req.terrain = this; - req.dirtyRect = rect; - req.lightmapExtraDirtyRect = lightmapExtraRect; - req.typeMask = typeMask; - if (!mNormalMapRequired) - req.typeMask = req.typeMask & ~DERIVED_DATA_NORMALS; - if (!mLightMapRequired) - req.typeMask = req.typeMask & ~DERIVED_DATA_LIGHTMAP; - - if(synchronous) - { - auto r = new WorkQueue::Request(0, 0, req, 0, 0); - auto res = handleRequest(r, NULL); - handleResponse(res, NULL); - delete res; - return; - } - - Root::getSingleton().getWorkQueue()->addTask( - [this, req]() - { - auto r = new WorkQueue::Request(0, 0, req, 0, 0); - auto res = handleRequest(r, NULL); - Root::getSingleton().getWorkQueue()->addMainThreadTask([this, res](){ - handleResponse(res, NULL); - delete res; - }); - }); - } - //--------------------------------------------------------------------- - void Terrain::waitForDerivedProcesses() - { - while (mDerivedDataUpdateInProgress || mGenerateMaterialInProgress || mPrepareInProgress) - { - // we need to wait for this to finish - OGRE_THREAD_SLEEP(50); - Root::getSingleton().getWorkQueue()->processMainThreadTasks(); - } - - } - //--------------------------------------------------------------------- - void Terrain::freeCPUResources() - { - OGRE_FREE(mHeightData, MEMCATEGORY_GEOMETRY); - mHeightData = 0; - - OGRE_FREE(mDeltaData, MEMCATEGORY_GEOMETRY); - mDeltaData = 0; - - OGRE_DELETE mQuadTree; - mQuadTree = 0; - - mCpuTerrainNormalMap.freeMemory(); - mCpuColourMap.freeMemory(); - mCpuLightmap.freeMemory(); - mCpuCompositeMap.freeMemory(); - } - //--------------------------------------------------------------------- - void Terrain::freeGPUResources() - { - // remove textures - TextureManager* tmgr = TextureManager::getSingletonPtr(); - if (tmgr) - { - for (auto & i : mBlendTextureList) - { - tmgr->remove(i->getHandle()); - } - mBlendTextureList.clear(); - - if (mTerrainNormalMap) - { - tmgr->remove(mTerrainNormalMap->getHandle()); - mTerrainNormalMap.reset(); - } - - if (mColourMap) - { - tmgr->remove(mColourMap->getHandle()); - mColourMap.reset(); - } - - if (mLightmap) - { - tmgr->remove(mLightmap->getHandle()); - mLightmap.reset(); - } - - if (mCompositeMap) - { - tmgr->remove(mCompositeMap->getHandle()); - mCompositeMap.reset(); - } - } - - if (mMaterial) - { - MaterialManager::getSingleton().remove(mMaterial->getHandle()); - mMaterial.reset(); - } - if (mCompositeMapMaterial) - { - MaterialManager::getSingleton().remove(mCompositeMapMaterial->getHandle()); - mCompositeMapMaterial.reset(); - } - - - } - //--------------------------------------------------------------------- - void Terrain::freeLodData() - { - if(mLodManager) - { - OGRE_DELETE mLodManager; - mLodManager = 0; - } - } - //--------------------------------------------------------------------- - Rect Terrain::calculateHeightDeltas(const Rect& rect) - { - Rect clampedRect = rect.intersect(Rect(0, 0, mSize, mSize)); - Rect finalRect(clampedRect); - - mQuadTree->preDeltaCalculation(clampedRect); - - /// Iterate over target levels, - for (int targetLevel = 1; targetLevel < mNumLodLevels; ++targetLevel) - { - int sourceLevel = targetLevel - 1; - int step = 1 << targetLevel; - // The step of the next higher LOD -// int higherstep = step >> 1; - - // need to widen the dirty rectangle since change will affect surrounding - // vertices at lower LOD - Rect widenedRect(rect); - widenedRect.left = std::max(0, widenedRect.left - step); - widenedRect.top = std::max(0, widenedRect.top - step); - widenedRect.right = std::min((int)mSize, widenedRect.right + step); - widenedRect.bottom = std::min((int)mSize, widenedRect.bottom + step); - - // keep a merge of the widest - finalRect.merge(widenedRect); - - - // now round the rectangle at this level so that it starts & ends on - // the step boundaries - Rect lodRect(widenedRect); - lodRect.left -= lodRect.left % step; - lodRect.top -= lodRect.top % step; - if (lodRect.right % step) - lodRect.right += step - (lodRect.right % step); - if (lodRect.bottom % step) - lodRect.bottom += step - (lodRect.bottom % step); - - for (int j = lodRect.top; j < lodRect.bottom - step; j += step ) - { - for (int i = lodRect.left; i < lodRect.right - step; i += step ) - { - // Form planes relating to the lower detail tris to be produced - // For even tri strip rows, they are this shape: - // 2---3 - // | / | - // 0---1 - // For odd tri strip rows, they are this shape: - // 2---3 - // | \ | - // 0---1 - - Vector3 v0, v1, v2, v3; - getPointAlign(i, j, ALIGN_X_Y, &v0); - getPointAlign(i + step, j, ALIGN_X_Y, &v1); - getPointAlign(i, j + step, ALIGN_X_Y, &v2); - getPointAlign(i + step, j + step, ALIGN_X_Y, &v3); - - Vector4 t1, t2; - bool backwardTri = false; - // Odd or even in terms of target level - if ((j / step) % 2 == 0) - { - t1 = Math::calculateFaceNormalWithoutNormalize(v0, v1, v3); - t2 = Math::calculateFaceNormalWithoutNormalize(v0, v3, v2); - } - else - { - t1 = Math::calculateFaceNormalWithoutNormalize(v1, v3, v2); - t2 = Math::calculateFaceNormalWithoutNormalize(v0, v1, v2); - backwardTri = true; - } - - // include the bottommost row of vertices if this is the last row - int yubound = (j == (mSize - step)? step : step - 1); - for ( int y = 0; y <= yubound; y++ ) - { - // include the rightmost col of vertices if this is the last col - int xubound = (i == (mSize - step)? step : step - 1); - for ( int x = 0; x <= xubound; x++ ) - { - int fulldetailx = static_cast(i + x); - int fulldetaily = static_cast(j + y); - if ( fulldetailx % step == 0 && - fulldetaily % step == 0 ) - { - // Skip, this one is a vertex at this level - continue; - } - - Real ypct = (Real)y / (Real)step; - Real xpct = (Real)x / (Real)step; - - //interpolated height - Vector3 actualPos; - getPointAlign(fulldetailx, fulldetaily, ALIGN_X_Y, &actualPos); - Real interp_h; - // Determine which tri we're on - if ((xpct > ypct && !backwardTri) || - (xpct > (1-ypct) && backwardTri)) - { - // Solve for x/z - interp_h = - (-t1.x * actualPos.x - - t1.y * actualPos.y - - t1.w) / t1.z; - } - else - { - // Second tri - interp_h = - (-t2.x * actualPos.x - - t2.y * actualPos.y - - t2.w) / t2.z; - } - - Real actual_h = actualPos.z; - Real delta = interp_h - actual_h; - - // max(delta) is the worst case scenario at this LOD - // compared to the original heightmap - - // tell the quadtree about this - mQuadTree->notifyDelta(fulldetailx, fulldetaily, sourceLevel, delta); - - - // If this vertex is being removed at this LOD, - // then save the height difference since that's the move - // it will need to make. Vertices to be removed at this LOD - // are halfway between the steps, but exclude those that - // would have been eliminated at earlier levels - int halfStep = step / 2; - if ( - ((fulldetailx % step) == halfStep && (fulldetaily % halfStep) == 0) || - ((fulldetaily % step) == halfStep && (fulldetailx % halfStep) == 0)) - { - // Save height difference - mDeltaData[fulldetailx + (fulldetaily * mSize)] = delta; - } - - } - - } - } // i - } // j - - } // targetLevel - - mQuadTree->postDeltaCalculation(clampedRect); - - return finalRect; - - } - //--------------------------------------------------------------------- - void Terrain::finaliseHeightDeltas(const Rect& rect, bool cpuData) - { - - Rect clampedRect = rect.intersect(Rect(0, 0, mSize, mSize)); - // min/max information - mQuadTree->finaliseDeltaValues(clampedRect); - // delta vertex data - mQuadTree->updateVertexData(false, true, clampedRect, cpuData); - - } - - //--------------------------------------------------------------------- - uint16 Terrain::getResolutionAtLod(uint16 lodLevel) const - { - return ((mSize - 1) >> lodLevel) + 1; - } - //--------------------------------------------------------------------- - uint Terrain::getGeoDataSizeAtLod(uint16 lodLevel) const - { - uint size = getResolutionAtLod(lodLevel); - uint prevSize = (lodLevelgetMilliseconds(); - unsigned long elapsedMillis = currMillis - mLastMillis; - if (mCompositeMapUpdateCountdown > 0 && elapsedMillis) - { - if (elapsedMillis > mCompositeMapUpdateCountdown) - mCompositeMapUpdateCountdown = 0; - else - mCompositeMapUpdateCountdown -= elapsedMillis; - - if (!mCompositeMapUpdateCountdown) - updateCompositeMap(); - } - mLastMillis = currMillis; - // only calculate LOD once per LOD camera, per frame, per viewport height - const Camera* lodCamera = v->getCamera()->getLodCamera(); - unsigned long frameNum = Root::getSingleton().getNextFrameNumber(); - int vpHeight = v->getActualHeight(); - if (mLastLODCamera != lodCamera || frameNum != mLastLODFrame - || mLastViewportHeight != vpHeight) - { - mLastLODCamera = lodCamera; - mLastLODFrame = frameNum; - mLastViewportHeight = vpHeight; - calculateCurrentLod(v); - } - } - //--------------------------------------------------------------------- - void Terrain::sceneManagerDestroyed(SceneManager* source) - { - unload(); - unprepare(); - if (source == mSceneMgr) - mSceneMgr = 0; - } - //--------------------------------------------------------------------- - void Terrain::calculateCurrentLod(Viewport* vp) - { - if (mQuadTree) - { - // calculate error terms - const Camera* cam = vp->getCamera()->getLodCamera(); - - // W. de Boer 2000 calculation - // A = vp_near / abs(vp_top) - // A = 1 / tan(fovy*0.5) (== 1 for fovy=45*2) - Real A = 1.0f / Math::Tan(cam->getFOVy() * 0.5f); - // T = 2 * maxPixelError / vertRes - Real maxPixelError = TerrainGlobalOptions::getSingleton().getMaxPixelError() * cam->_getLodBiasInverse(); - Viewport* lodVp = cam->getViewport(); - Real T = 2.0f * maxPixelError / (Real)lodVp->getActualHeight(); - - // CFactor = A / T - Real cFactor = A / T; - - mQuadTree->calculateCurrentLod(cam, cFactor); - } - } - //--------------------------------------------------------------------- - std::pair Terrain::rayIntersects(const Ray& ray, - bool cascadeToNeighbours /* = false */, Real distanceLimit /* = 0 */) - { - typedef std::pair Result; - // first step: convert the ray to a local vertex space - // we assume terrain to be in the x-z plane, with the [0,0] vertex - // at origin and a plane distance of 1 between vertices. - // This makes calculations easier. - Vector3 rayOrigin = ray.getOrigin() - getPosition(); - Vector3 rayDirection = ray.getDirection(); - // change alignment - Vector3 tmp; - switch (getAlignment()) - { - case ALIGN_X_Y: - std::swap(rayOrigin.y, rayOrigin.z); - std::swap(rayDirection.y, rayDirection.z); - break; - case ALIGN_Y_Z: - // x = z, z = y, y = -x - tmp.x = rayOrigin.z; - tmp.z = rayOrigin.y; - tmp.y = -rayOrigin.x; - rayOrigin = tmp; - tmp.x = rayDirection.z; - tmp.z = rayDirection.y; - tmp.y = -rayDirection.x; - rayDirection = tmp; - break; - case ALIGN_X_Z: - // already in X/Z but values increase in -Z - rayOrigin.z = -rayOrigin.z; - rayDirection.z = -rayDirection.z; - break; - } - // readjust coordinate origin - rayOrigin.x += mWorldSize/2; - rayOrigin.z += mWorldSize/2; - // scale down to vertex level - rayOrigin.x /= mScale; - rayOrigin.z /= mScale; - rayDirection.x /= mScale; - rayDirection.z /= mScale; - rayDirection.normalise(); - Ray localRay (rayOrigin, rayDirection); - - // test if the ray actually hits the terrain's bounds - Real maxHeight = getMaxHeight(); - Real minHeight = getMinHeight(); - - AxisAlignedBox aabb (Vector3(0, minHeight, 0), Vector3(mSize, maxHeight, mSize)); - std::pair aabbTest = localRay.intersects(aabb); - if (!aabbTest.first) - { - if (cascadeToNeighbours) - { - OGRE_LOCK_RW_MUTEX_READ(mNeighbourMutex); - Terrain* neighbour = raySelectNeighbour(ray, distanceLimit); - if (neighbour) - return neighbour->rayIntersects(ray, cascadeToNeighbours, distanceLimit); - } - return Result(false, Vector3()); - } - // get intersection point and move inside - Vector3 cur = localRay.getPoint(aabbTest.second); - - // now check every quad the ray touches - int quadX = std::min(std::max(static_cast(cur.x), 0), (int)mSize-2); - int quadZ = std::min(std::max(static_cast(cur.z), 0), (int)mSize-2); - int flipX = (rayDirection.x < 0 ? 0 : 1); - int flipZ = (rayDirection.z < 0 ? 0 : 1); - int xDir = (rayDirection.x < 0 ? -1 : 1); - int zDir = (rayDirection.z < 0 ? -1 : 1); - - Result result(true, Vector3::ZERO); - Real dummyHighValue = (Real)mSize * 10000.0f; - - - while (cur.y >= (minHeight - 1e-3) && cur.y <= (maxHeight + 1e-3)) - { - if (quadX < 0 || quadX >= (int)mSize-1 || quadZ < 0 || quadZ >= (int)mSize-1) - break; - - result = checkQuadIntersection(quadX, quadZ, localRay); - if (result.first) - break; - - // determine next quad to test - Real xDist = Math::RealEqual(rayDirection.x, 0.0) ? dummyHighValue : - (quadX - cur.x + flipX) / rayDirection.x; - Real zDist = Math::RealEqual(rayDirection.z, 0.0) ? dummyHighValue : - (quadZ - cur.z + flipZ) / rayDirection.z; - if (xDist < zDist) - { - quadX += xDir; - cur += rayDirection * xDist; - } - else - { - quadZ += zDir; - cur += rayDirection * zDist; - } - - } - - if (result.first) - { - // transform the point of intersection back to world space - result.second.x *= mScale; - result.second.z *= mScale; - result.second.x -= mWorldSize/2; - result.second.z -= mWorldSize/2; - switch (getAlignment()) - { - case ALIGN_X_Y: - std::swap(result.second.y, result.second.z); - break; - case ALIGN_Y_Z: - // z = x, y = z, x = -y - tmp.x = -rayOrigin.y; - tmp.y = rayOrigin.z; - tmp.z = rayOrigin.x; - rayOrigin = tmp; - break; - case ALIGN_X_Z: - result.second.z = -result.second.z; - break; - } - result.second += getPosition(); - } - else if (cascadeToNeighbours) - { - Terrain* neighbour = raySelectNeighbour(ray, distanceLimit); - if (neighbour) - result = neighbour->rayIntersects(ray, cascadeToNeighbours, distanceLimit); - } - return result; - } - //--------------------------------------------------------------------- - std::pair Terrain::checkQuadIntersection(int x, int z, const Ray& ray) const - { - // build the two planes belonging to the quad's triangles - Vector3 v1 ((Real)x, *getHeightData(x,z), (Real)z); - Vector3 v2 ((Real)x+1, *getHeightData(x+1,z), (Real)z); - Vector3 v3 ((Real)x, *getHeightData(x,z+1), (Real)z+1); - Vector3 v4 ((Real)x+1, *getHeightData(x+1,z+1), (Real)z+1); - - Vector4 p1, p2; - bool oddRow = false; - if (z % 2) - { - /* odd - 3---4 - | \ | - 1---2 - */ - p1 = Math::calculateFaceNormalWithoutNormalize(v2, v4, v3); - p2 = Math::calculateFaceNormalWithoutNormalize(v1, v2, v3); - oddRow = true; - } - else - { - /* even - 3---4 - | / | - 1---2 - */ - p1 = Math::calculateFaceNormalWithoutNormalize(v1, v2, v4); - p2 = Math::calculateFaceNormalWithoutNormalize(v1, v4, v3); - } - - // Test for intersection with the two planes. - // Then test that the intersection points are actually - // still inside the triangle (with a small error margin) - // Also check which triangle it is in - RayTestResult planeInt = ray.intersects(Plane(p1)); - if (planeInt.first) - { - Vector3 where = ray.getPoint(planeInt.second); - Vector3 rel = where - v1; - if (rel.x >= -0.01 && rel.x <= 1.01 && rel.z >= -0.01 && rel.z <= 1.01 // quad bounds - && ((rel.x >= rel.z && !oddRow) || (rel.x >= (1 - rel.z) && oddRow))) // triangle bounds - return std::pair(true, where); - } - planeInt = ray.intersects(Plane(p2)); - if (planeInt.first) - { - Vector3 where = ray.getPoint(planeInt.second); - Vector3 rel = where - v1; - if (rel.x >= -0.01 && rel.x <= 1.01 && rel.z >= -0.01 && rel.z <= 1.01 // quad bounds - && ((rel.x <= rel.z && !oddRow) || (rel.x <= (1 - rel.z) && oddRow))) // triangle bounds - return std::pair(true, where); - } - - return std::pair(false, Vector3()); - } - //--------------------------------------------------------------------- - const MaterialPtr& Terrain::getMaterial() const - { - if (!mMaterial || - mMaterialGenerator->getChangeCount() != mMaterialGenerationCount || - mMaterialDirty) - { - const_cast(this)->generateMaterial(); - } - if (mMaterialParamsDirty) - { - mMaterialGenerator->updateParams(mMaterial, this); - if(mCompositeMapRequired) - mMaterialGenerator->updateParamsForCompositeMap(mCompositeMapMaterial, this); - mMaterialParamsDirty = false; - - } - - return mMaterial; - } - //--------------------------------------------------------------------- - const MaterialPtr& Terrain::getCompositeMapMaterial() const - { - // both materials updated together since they change at the same time - getMaterial(); - return mCompositeMapMaterial; - } - //--------------------------------------------------------------------- - void Terrain::checkLayers(bool includeGPUResources) - { - for (auto & layer : mLayers) - { - // adjust number of textureNames to number declared samplers - layer.textureNames.resize(mLayerDecl.size()); - } - - if (includeGPUResources) - { - createGPUBlendTextures(); - createLayerBlendMaps(); - } - - } - //--------------------------------------------------------------------- - void Terrain::checkDeclaration() - { - if (!mMaterialGenerator) - { - mMaterialGenerator = TerrainGlobalOptions::getSingleton().getDefaultMaterialGenerator(); - } - - if (mLayerDecl.empty()) - { - // default the declaration - mLayerDecl = mMaterialGenerator->getLayerDeclaration(); - } - - } - //--------------------------------------------------------------------- - void Terrain::replaceLayer(uint8 index, bool keepBlends, Real worldSize, const StringVector* textureNames) - { - if (getLayerCount() > 0) - { - if (index >= getLayerCount()) - index = getLayerCount() - 1; - - LayerInstanceList::iterator i = mLayers.begin(); - std::advance(i, index); - - if (textureNames) - { - (*i).textureNames = *textureNames; - } - - // use utility method to update UV scaling - setLayerWorldSize(index, worldSize); - - // Delete the blend map if its not the base - if ( !keepBlends && index > 0 ) - { - if (mLayerBlendMapList[index-1]) - { - delete mLayerBlendMapList[index-1]; - mLayerBlendMapList[index-1] = 0; - } - - // Reset the layer to black - std::pair layerPair = getLayerBlendTextureIndex(index); - clearGPUBlendChannel( layerPair.first, layerPair.second ); - } - - mMaterialDirty = true; - mMaterialParamsDirty = true; - mModified = true; - } - } - //--------------------------------------------------------------------- - void Terrain::addLayer(Real worldSize, const StringVector* textureNames) - { - addLayer(getLayerCount(), worldSize, textureNames); - } - //--------------------------------------------------------------------- - void Terrain::addLayer(uint8 index, Real worldSize, const StringVector* textureNames) - { - if (!worldSize) - worldSize = TerrainGlobalOptions::getSingleton().getDefaultLayerTextureWorldSize(); - - uint8 blendIndex = std::max(index-1,0); - if (index >= getLayerCount()) - { - mLayers.push_back(LayerInstance()); - index = getLayerCount() - 1; - } - else - { - LayerInstanceList::iterator i = mLayers.begin(); - std::advance(i, index); - mLayers.insert(i, LayerInstance()); - - RealVector::iterator uvi = mLayerUVMultiplier.begin(); - std::advance(uvi, index); - mLayerUVMultiplier.insert(uvi, 0.0f); - - TerrainLayerBlendMapList::iterator bi = mLayerBlendMapList.begin(); - std::advance(bi, blendIndex); - mLayerBlendMapList.insert(bi, static_cast(0)); - } - if (textureNames) - { - LayerInstance& inst = mLayers[index]; - inst.textureNames = *textureNames; - } - // use utility method to update UV scaling - setLayerWorldSize(index, worldSize); - checkLayers(true); - - // Is this an insert into the middle of the layer list? - if (index < getLayerCount() - 1) - { - // Shift all GPU texture channels up one - shiftUpGPUBlendChannels(blendIndex); - - // All blend maps above this layer index will need to be recreated since their buffers/channels have changed - deleteBlendMaps(index); - } - - mMaterialDirty = true; - mMaterialParamsDirty = true; - mModified = true; - - } - //--------------------------------------------------------------------- - void Terrain::removeLayer(uint8 index) - { - if (index < mLayers.size()) - { - uint8 blendIndex = std::max(index-1,0); - - // Shift all GPU texture channels down one - shiftDownGPUBlendChannels(blendIndex); - - LayerInstanceList::iterator i = mLayers.begin(); - std::advance(i, index); - mLayers.erase(i); - - RealVector::iterator uvi = mLayerUVMultiplier.begin(); - std::advance(uvi, index); - mLayerUVMultiplier.erase(uvi); - - if (mLayerBlendMapList.size() > 0) - { - // If they removed the base OR the first layer, we need to erase the first blend map - TerrainLayerBlendMapList::iterator bi = mLayerBlendMapList.begin(); - std::advance(bi, blendIndex); - OGRE_DELETE *bi; - mLayerBlendMapList.erase(bi); - - // Check to see if a GPU textures can be released - checkLayers(true); - - // All blend maps for layers above the erased will need to be recreated since their buffers/channels have changed - deleteBlendMaps(blendIndex); - } - - mMaterialDirty = true; - mMaterialParamsDirty = true; - mModified = true; - } - } - //--------------------------------------------------------------------- - uint8 Terrain::getMaxLayers() const - { - return mMaterialGenerator->getMaxLayers(this); - } - //--------------------------------------------------------------------- - TerrainLayerBlendMap* Terrain::getLayerBlendMap(uint8 layerIndex) - { - if (layerIndex == 0 || layerIndex-1 >= (uint8)mLayerBlendMapList.size()) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Invalid layer index", "Terrain::getLayerBlendMap"); - - uint8 idx = layerIndex - 1; - if (!mLayerBlendMapList[idx]) - { - if (mBlendTextureList.size() < static_cast(idx / 4)) - checkLayers(true); - - const TexturePtr& tex = mBlendTextureList[idx / 4]; - mLayerBlendMapList[idx] = OGRE_NEW TerrainLayerBlendMap(this, layerIndex, tex->getBuffer().get()); - } - - return mLayerBlendMapList[idx]; - - } - //--------------------------------------------------------------------- - uint8 Terrain::getBlendTextureCount() const - { - return (uint8)mBlendTextureList.size(); - } - //--------------------------------------------------------------------- - void Terrain::shiftUpGPUBlendChannels(uint8 index) - { - // checkLayers() has been called to make sure the blend textures have been created - assert( mBlendTextureList.size() == getBlendTextureCount(getLayerCount()) ); - - // Shift all blend channels > index UP one slot, possibly into the next texture - // Example: index = 2 - // Before: [1 2 3 4] [5] - // After: [1 2 0 3] [4 5] - - uint8 layerIndex = index + 1; - for (uint8 i=getLayerCount()-1; i > layerIndex; --i ) - { - std::pair destPair = getLayerBlendTextureIndex(i); - std::pair srcPair = getLayerBlendTextureIndex(i - 1); - - copyBlendTextureChannel( srcPair.first, srcPair.second, destPair.first, destPair.second ); - } - - // Reset the layer to black - std::pair layerPair = getLayerBlendTextureIndex(layerIndex); - clearGPUBlendChannel( layerPair.first, layerPair.second ); - } - //--------------------------------------------------------------------- - void Terrain::shiftDownGPUBlendChannels(uint8 index) - { - // checkLayers() has been called to make sure the blend textures have been created - assert( mBlendTextureList.size() == getBlendTextureCount(getLayerCount()) ); - - // Shift all blend channels above layerIndex DOWN one slot, possibly into the previous texture - // Example: index = 2 - // Before: [1 2 3 4] [5] - // After: [1 2 4 5] [0] - - uint8 layerIndex = index + 1; - for (uint8 i=layerIndex; i < getLayerCount() - 1; ++i ) - { - std::pair destPair = getLayerBlendTextureIndex(i); - std::pair srcPair = getLayerBlendTextureIndex(i + 1); - - copyBlendTextureChannel( srcPair.first, srcPair.second, destPair.first, destPair.second ); - } - - // Reset the layer to black - if ( getLayerCount() > 1 ) - { - std::pair layerPair = getLayerBlendTextureIndex(getLayerCount() - 1); - clearGPUBlendChannel( layerPair.first, layerPair.second ); - } - } - //--------------------------------------------------------------------- - void Terrain::copyBlendTextureChannel(uint8 srcIndex, uint8 srcChannel, uint8 destIndex, uint8 destChannel ) - { - HardwarePixelBufferSharedPtr srcBuffer = getLayerBlendTexture(srcIndex)->getBuffer(); - HardwarePixelBufferSharedPtr destBuffer = getLayerBlendTexture(destIndex)->getBuffer(); - - unsigned char rgbaShift[4]; - Box box(0, 0, destBuffer->getWidth(), destBuffer->getHeight()); - - uint8* pDestBase = destBuffer->lock(box, HardwareBuffer::HBL_NORMAL).data; - PixelUtil::getBitShifts(destBuffer->getFormat(), rgbaShift); - uint8* pDest = pDestBase + rgbaShift[destChannel] / 8; - size_t destInc = PixelUtil::getNumElemBytes(destBuffer->getFormat()); - - size_t srcInc; - uint8* pSrc; - - if ( destBuffer == srcBuffer ) - { - pSrc = pDestBase + rgbaShift[srcChannel] / 8; - srcInc = destInc; - } - else - { - pSrc = srcBuffer->lock(box, HardwareBuffer::HBL_READ_ONLY).data; - PixelUtil::getBitShifts(srcBuffer->getFormat(), rgbaShift); - pSrc += rgbaShift[srcChannel] / 8; - srcInc = PixelUtil::getNumElemBytes(srcBuffer->getFormat()); - } - - for (size_t y = box.top; y < box.bottom; ++y) - { - for (size_t x = box.left; x < box.right; ++x) - { - *pDest = *pSrc; - pSrc += srcInc; - pDest += destInc; - } - } - - destBuffer->unlock(); - if ( destBuffer != srcBuffer ) - srcBuffer->unlock(); - } - //--------------------------------------------------------------------- - void Terrain::clearGPUBlendChannel(uint8 index, uint channel) - { - HardwarePixelBufferSharedPtr buffer = getLayerBlendTexture(index)->getBuffer(); - - unsigned char rgbaShift[4]; - Box box(0, 0, buffer->getWidth(), buffer->getHeight()); - - uint8* pData = buffer->lock(box, HardwareBuffer::HBL_NORMAL).data; - PixelUtil::getBitShifts(buffer->getFormat(), rgbaShift); - pData += rgbaShift[channel] / 8; - size_t inc = PixelUtil::getNumElemBytes(buffer->getFormat()); - - for (size_t y = box.top; y < box.bottom; ++y) - { - for (size_t x = box.left; x < box.right; ++x) - { - *pData = 0; - pData += inc; - } - } - buffer->unlock(); - } - //--------------------------------------------------------------------- - void Terrain::createGPUBlendTextures() - { - // Create enough RGBA textures to cope with blend layers - uint8 numTex = getBlendTextureCount(getLayerCount()); - // delete extras - TextureManager* tmgr = TextureManager::getSingletonPtr(); - if (!tmgr) - return; - - while (mBlendTextureList.size() > numTex) - { - tmgr->remove(mBlendTextureList.back()->getHandle()); - mBlendTextureList.pop_back(); - } - - uint8 currentTex = (uint8)mBlendTextureList.size(); - mBlendTextureList.resize(numTex); - // create new textures - for (uint8 i = currentTex; i < numTex; ++i) - { - // Use TU_STATIC because although we will update this, we won't do it every frame - // in normal circumstances, so we don't want TU_DYNAMIC. Also we will - // read it (if we've cleared local temp areas) so no WRITE_ONLY - mBlendTextureList[i] = TextureManager::getSingleton().createManual( - msBlendTextureGenerator.generate(), _getDerivedResourceGroup(), - TEX_TYPE_2D, mLayerBlendMapSize, mLayerBlendMapSize, 1, 0, PF_BYTE_RGBA, TU_STATIC); - - mLayerBlendMapSizeActual = mBlendTextureList[i]->getWidth(); - - if (mCpuBlendMapStorage.size() > i) - { - // Load blend data - mBlendTextureList[i]->getBuffer()->blitFromMemory(mCpuBlendMapStorage[i].getPixelBox()); - // release CPU copy, don't need it anymore - mCpuBlendMapStorage[i].freeMemory(); - } - else - { - // initialise black - auto buf = mBlendTextureList[i]->getBuffer(); - uint8* pInit = buf->lock(Box(buf->getSize()), HardwarePixelBuffer::HBL_DISCARD).data; - memset(pInit, 0, buf->getSizeInBytes()); - buf->unlock(); - } - } - mCpuBlendMapStorage.clear(); - - - } - //--------------------------------------------------------------------- - void Terrain::createLayerBlendMaps() - { - // delete extra blend layers (affects GPU) - while (mLayerBlendMapList.size() > mLayers.size() - 1) - { - OGRE_DELETE mLayerBlendMapList.back(); - mLayerBlendMapList.pop_back(); - } - - // resize up (initialises to 0, populate as necessary) - if ( mLayers.size() > 1 ) - mLayerBlendMapList.resize(mLayers.size() - 1, 0); - - } - //--------------------------------------------------------------------- - void Terrain::createOrDestroyGPUNormalMap() - { - if (mNormalMapRequired && !mTerrainNormalMap) - { - // create - mTerrainNormalMap = TextureManager::getSingleton().createManual( - mMaterialName + "/nm", _getDerivedResourceGroup(), - TEX_TYPE_2D, mSize, mSize, 1, 0, PF_BYTE_RGB, TU_STATIC); - - // Upload loaded normal data if present - if (mCpuTerrainNormalMap.getData()) - { - mTerrainNormalMap->getBuffer()->blitFromMemory(mCpuTerrainNormalMap.getPixelBox()); - mCpuTerrainNormalMap.freeMemory(); - } - } - else if (!mNormalMapRequired && mTerrainNormalMap) - { - // destroy - TextureManager::getSingleton().remove(mTerrainNormalMap->getHandle()); - mTerrainNormalMap.reset(); - } - - } - //--------------------------------------------------------------------- - void Terrain::freeTemporaryResources() - { - // CPU blend maps - mCpuBlendMapStorage.clear(); - - // Editable structures for blend layers (not needed at runtime, only blend textures are) - deleteBlendMaps(0); - } - //--------------------------------------------------------------------- - void Terrain::deleteBlendMaps(uint8 lowIndex) - { - TerrainLayerBlendMapList::iterator i = mLayerBlendMapList.begin(); - std::advance(i, lowIndex); - for (; i != mLayerBlendMapList.end(); ++i ) - { - OGRE_DELETE *i; - *i = 0; - } - } - //--------------------------------------------------------------------- - const TexturePtr& Terrain::getLayerBlendTexture(uint8 index) const - { - assert(index < mBlendTextureList.size()); - - return mBlendTextureList[index]; - } - //--------------------------------------------------------------------- - std::pair Terrain::getLayerBlendTextureIndex(uint8 layerIndex) const - { - assert(layerIndex > 0 && layerIndex < mLayers.size()); - uint8 idx = layerIndex - 1; - return std::pair(idx / 4, idx % 4); - } - //--------------------------------------------------------------------- - void Terrain::_setNormalMapRequired(bool normalMap) - { - if (normalMap != mNormalMapRequired) - { - mNormalMapRequired = normalMap; - - // Check NPOT textures supported. We have to use NPOT textures to map - // texels to vertices directly! - if (!mNormalMapRequired && Root::getSingleton().getRenderSystem() - ->getCapabilities()->hasCapability(RSC_NON_POWER_OF_2_TEXTURES)) - { - mNormalMapRequired = false; - LogManager::getSingleton().stream(LML_CRITICAL) << - "Terrain: Ignoring request for normal map generation since " - "non-power-of-two texture support is required."; - } - - createOrDestroyGPUNormalMap(); - - // if we enabled, generate normal maps - if (mNormalMapRequired) - { - // update derived data for whole terrain, but just normals - mDirtyDerivedDataRect.left = mDirtyDerivedDataRect.top = 0; - mDirtyDerivedDataRect.right = mDirtyDerivedDataRect.bottom = mSize; - updateDerivedData(false, DERIVED_DATA_NORMALS); - } - - } - } - //--------------------------------------------------------------------- - void Terrain::_setLightMapRequired(bool lightMap, bool shadowsOnly) - { - if (lightMap != mLightMapRequired || shadowsOnly != mLightMapShadowsOnly) - { - mLightMapRequired = lightMap; - mLightMapShadowsOnly = shadowsOnly; - - createOrDestroyGPULightmap(); - - // if we enabled, generate light maps - if (mLightMapRequired) - { - // update derived data for whole terrain, but just lightmap - mDirtyDerivedDataRect.left = mDirtyDerivedDataRect.top = 0; - mDirtyDerivedDataRect.right = mDirtyDerivedDataRect.bottom = mSize; - updateDerivedData(false, DERIVED_DATA_LIGHTMAP); - } - } - - } - //--------------------------------------------------------------------- - void Terrain::_setCompositeMapRequired(bool compositeMap) - { - if (compositeMap != mCompositeMapRequired) - { - mCompositeMapRequired = compositeMap; - - createOrDestroyGPUCompositeMap(); - - // if we enabled, generate composite maps - if (mCompositeMapRequired) - { - mCompositeMapDirtyRect.left = mCompositeMapDirtyRect.top = 0; - mCompositeMapDirtyRect.right = mCompositeMapDirtyRect.bottom = mSize; - updateCompositeMap(); - } - - } - - } - //--------------------------------------------------------------------- - bool Terrain::_getUseVertexCompression() const - { - return mMaterialGenerator->isVertexCompressionSupported() && - TerrainGlobalOptions::getSingleton().getUseVertexCompressionWhenAvailable(); - } - //--------------------------------------------------------------------- - WorkQueue::Response* Terrain::handleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ) - { - // Background thread (maybe) - DerivedDataRequest ddr = any_cast(req->getData()); - DerivedDataResponse ddres; - ddres.remainingTypeMask = ddr.typeMask & DERIVED_DATA_ALL; - - // Do only ONE type of task per background iteration, in order of priority - // this means we return faster, can abort faster and we repeat less redundant calcs - // we don't do this as separate requests, because we only want one background - // task per Terrain instance in flight at once - if (ddr.typeMask & DERIVED_DATA_DELTAS) - { - ddres.deltaUpdateRect = calculateHeightDeltas(ddr.dirtyRect); - ddres.remainingTypeMask &= ~ DERIVED_DATA_DELTAS; - } - else if (ddr.typeMask & DERIVED_DATA_NORMALS) - { - ddres.normalMapBox = calculateNormals(ddr.dirtyRect, ddres.normalUpdateRect); - ddres.remainingTypeMask &= ~ DERIVED_DATA_NORMALS; - } - else if (ddr.typeMask & DERIVED_DATA_LIGHTMAP) - { - ddres.lightMapBox = calculateLightmap(ddr.dirtyRect, ddr.lightmapExtraDirtyRect, ddres.lightmapUpdateRect); - ddres.remainingTypeMask &= ~ DERIVED_DATA_LIGHTMAP; - } - - ddres.terrain = ddr.terrain; - WorkQueue::Response* response = OGRE_NEW WorkQueue::Response(req, true, ddres); - return response; - } - //--------------------------------------------------------------------- - void Terrain::handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ) - { - // Main thread - DerivedDataResponse ddres = any_cast(res->getData()); - DerivedDataRequest ddreq = any_cast(res->getRequest()->getData()); - - if ((ddreq.typeMask & DERIVED_DATA_DELTAS) && - !(ddres.remainingTypeMask & DERIVED_DATA_DELTAS)) - finaliseHeightDeltas(ddres.deltaUpdateRect, false); - if ((ddreq.typeMask & DERIVED_DATA_NORMALS) && - !(ddres.remainingTypeMask & DERIVED_DATA_NORMALS)) - { - finaliseNormals(ddres.normalUpdateRect, ddres.normalMapBox); - mCompositeMapDirtyRect.merge(ddreq.dirtyRect); - } - if ((ddreq.typeMask & DERIVED_DATA_LIGHTMAP) && - !(ddres.remainingTypeMask & DERIVED_DATA_LIGHTMAP)) - { - finaliseLightmap(ddres.lightmapUpdateRect, ddres.lightMapBox); - mCompositeMapDirtyRect.merge(ddreq.dirtyRect); - mCompositeMapDirtyRectLightmapUpdate = true; - } - - mDerivedDataUpdateInProgress = false; - - // Re-trigger another request if there are still things to do, or if - // we had a new request since this one - Rect newRect(0,0,0,0); - if (ddres.remainingTypeMask) - newRect.merge(ddreq.dirtyRect); - if (mDerivedUpdatePendingMask) - { - newRect.merge(mDirtyDerivedDataRect); - mDirtyDerivedDataRect.setNull(); - } - Rect newLightmapExtraRect(0,0,0,0); - if (ddres.remainingTypeMask) - newLightmapExtraRect.merge(ddreq.lightmapExtraDirtyRect); - if (mDerivedUpdatePendingMask) - { - newLightmapExtraRect.merge(mDirtyLightmapFromNeighboursRect); - mDirtyLightmapFromNeighboursRect.setNull(); - } - uint8 newMask = ddres.remainingTypeMask | mDerivedUpdatePendingMask; - if (newMask) - { - // trigger again - updateDerivedDataImpl(newRect, newLightmapExtraRect, false, newMask); - } - else - { - // we've finished all the background processes - // update the composite map if enabled - if (mCompositeMapRequired) - updateCompositeMap(); - } - - } - //--------------------------------------------------------------------- - void Terrain::generateMaterial() - { - mMaterial = mMaterialGenerator->generate(this); - mMaterial->load(); - - if (mCompositeMapRequired) - { - mCompositeMapMaterial = mMaterialGenerator->generateForCompositeMap(this); - mCompositeMapMaterial->load(); - } - - mMaterialGenerationCount = mMaterialGenerator->getChangeCount(); - mMaterialDirty = false; - - mGenerateMaterialInProgress = false; - mIsLoaded = true; - } - //--------------------------------------------------------------------- - uint16 Terrain::getLODLevelWhenVertexEliminated(long x, long y) const - { - // gets eliminated by either row or column first - return std::min(getLODLevelWhenVertexEliminated(x), getLODLevelWhenVertexEliminated(y)); - } - //--------------------------------------------------------------------- - uint16 Terrain::getLODLevelWhenVertexEliminated(long rowOrColulmn) const - { - // LOD levels bisect the domain. - // start at the lowest detail - uint16 currentElim = (mSize - 1) / (mMinBatchSize - 1); - // start at a non-exitant LOD index, this applies to the min batch vertices - // which are never eliminated - uint16 currentLod = mNumLodLevels; - - while (rowOrColulmn % currentElim) - { - // not on this boundary, look finer - currentElim = currentElim / 2; - --currentLod; - - // This will always terminate since (anything % 1 == 0) - } - - return currentLod; - } - //--------------------------------------------------------------------- - PixelBox* Terrain::calculateNormals(const Rect &rect, Rect& finalRect) - { - // Widen the rectangle by 1 element in all directions since height - // changes affect neighbours normals - Rect widenedRect( - std::max(0, rect.left - 1), - std::max(0, rect.top - 1), - std::min((int32)mSize, rect.right + 1), - std::min((int32)mSize, rect.bottom + 1) - ); - // allocate memory for RGB - uint8* pData = static_cast( - OGRE_MALLOC(widenedRect.width() * widenedRect.height() * 3, MEMCATEGORY_GENERAL)); - - PixelBox* pixbox = OGRE_NEW PixelBox(static_cast(widenedRect.width()), - static_cast(widenedRect.height()), 1, PF_BYTE_RGB, pData); - - // Evaluate normal like this - // 3---2---1 - // | \ | / | - // 4---P---0 - // | / | \ | - // 5---6---7 - - for (int y = widenedRect.top; y < widenedRect.bottom; ++y) - { - for (int x = widenedRect.left; x < widenedRect.right; ++x) - { - Vector3 cumulativeNormal = Vector3::ZERO; - - // Build points to sample - Vector3 centrePoint; - Vector3 adjacentPoints[8]; - getPointFromSelfOrNeighbour(x , y, ¢rePoint); - getPointFromSelfOrNeighbour(x+1, y, &adjacentPoints[0]); - getPointFromSelfOrNeighbour(x+1, y+1, &adjacentPoints[1]); - getPointFromSelfOrNeighbour(x, y+1, &adjacentPoints[2]); - getPointFromSelfOrNeighbour(x-1, y+1, &adjacentPoints[3]); - getPointFromSelfOrNeighbour(x-1, y, &adjacentPoints[4]); - getPointFromSelfOrNeighbour(x-1, y-1, &adjacentPoints[5]); - getPointFromSelfOrNeighbour(x, y-1, &adjacentPoints[6]); - getPointFromSelfOrNeighbour(x+1, y-1, &adjacentPoints[7]); - - for (int i = 0; i < 8; ++i) - { - cumulativeNormal += Math::calculateBasicFaceNormal(centrePoint, adjacentPoints[i], adjacentPoints[(i+1)%8]); - } - - // normalise & store normal - cumulativeNormal.normalise(); - - // encode as RGB, object space - // invert the Y to deal with image space - long storeX = x - widenedRect.left; - long storeY = widenedRect.bottom - y - 1; - - uint8* pStore = pData + ((storeY * widenedRect.width()) + storeX) * 3; - *pStore++ = static_cast((cumulativeNormal.x + 1.0f) * 0.5f * 255.0f); - *pStore++ = static_cast((cumulativeNormal.y + 1.0f) * 0.5f * 255.0f); - *pStore++ = static_cast((cumulativeNormal.z + 1.0f) * 0.5f * 255.0f); - - - } - } - - finalRect = widenedRect; - - return pixbox; - } - //--------------------------------------------------------------------- - void Terrain::finaliseNormals(const Ogre::Rect &rect, Ogre::PixelBox *normalsBox) - { - createOrDestroyGPUNormalMap(); - // deal with race condition where nm has been disabled while we were working! - if (mTerrainNormalMap) - { - // blit the normals into the texture - if (rect.left == 0 && rect.top == 0 && rect.bottom == mSize && rect.right == mSize) - { - mTerrainNormalMap->getBuffer()->blitFromMemory(*normalsBox); - } - else - { - // content of normalsBox is already inverted in Y, but rect is still - // in terrain space for dealing with sub-rect, so invert - Box dstBox; - dstBox.left = static_cast(rect.left); - dstBox.right = static_cast(rect.right); - dstBox.top = static_cast(mSize - rect.bottom); - dstBox.bottom = static_cast(mSize - rect.top); - mTerrainNormalMap->getBuffer()->blitFromMemory(*normalsBox, dstBox); - } - } - - - // delete memory - OGRE_FREE(normalsBox->data, MEMCATEGORY_GENERAL); - OGRE_DELETE(normalsBox); - - } - //--------------------------------------------------------------------- - void Terrain::widenRectByVector(const Vector3& vec, const Rect& inRect, Rect& outRect) - { - widenRectByVector(vec, inRect, getMinHeight(), getMaxHeight(), outRect); - } - //--------------------------------------------------------------------- - void Terrain::widenRectByVector(const Vector3& vec, const Rect& inRect, - Real minHeight, Real maxHeight, Rect& outRect) - { - - outRect = inRect; - - Plane p; - switch(getAlignment()) - { - case ALIGN_X_Y: - p.redefine(Vector3::UNIT_Z, Vector3(0, 0, vec.z < 0.0 ? minHeight : maxHeight)); - break; - case ALIGN_X_Z: - p.redefine(Vector3::UNIT_Y, Vector3(0, vec.y < 0.0 ? minHeight : maxHeight, 0)); - break; - case ALIGN_Y_Z: - p.redefine(Vector3::UNIT_X, Vector3(vec.x < 0.0 ? minHeight : maxHeight, 0, 0)); - break; - } - float verticalVal = vec.dotProduct(p.normal); - - if (Math::RealEqual(verticalVal, 0.0)) - return; - - Vector3 corners[4]; - Real startHeight = verticalVal < 0.0 ? maxHeight : minHeight; - getPoint(inRect.left, inRect.top, startHeight, &corners[0]); - getPoint(inRect.right-1, inRect.top, startHeight, &corners[1]); - getPoint(inRect.left, inRect.bottom-1, startHeight, &corners[2]); - getPoint(inRect.right-1, inRect.bottom-1, startHeight, &corners[3]); - - for (auto & corner : corners) - { - Ray ray(corner + mPos, vec); - std::pair rayHit = ray.intersects(p); - if(rayHit.first) - { - Vector3 pt = ray.getPoint(rayHit.second); - // convert back to terrain point - Vector3 terrainHitPos; - getTerrainPosition(pt, &terrainHitPos); - // build rectangle which has rounded down & rounded up values - // remember right & bottom are exclusive - Rect mergeRect( - (terrainHitPos.x * (mSize - 1)), - (terrainHitPos.y * (mSize - 1)), - (terrainHitPos.x * (float)(mSize - 1) + 0.5) + 1, - (terrainHitPos.y * (float)(mSize - 1) + 0.5) + 1 - ); - outRect.merge(mergeRect); - } - } - - } - //--------------------------------------------------------------------- - PixelBox* Terrain::calculateLightmap(const Rect& rect, const Rect& extraTargetRect, Rect& outFinalRect) - { - // as well as calculating the lighting changes for the area that is - // dirty, we also need to calculate the effect on casting shadow on - // other areas. To do this, we project the dirt rect by the light direction - // onto the minimum height - - - const Vector3& lightVec = TerrainGlobalOptions::getSingleton().getLightMapDirection(); - Ogre::Rect widenedRect; - widenRectByVector(lightVec, rect, widenedRect); - - // merge in the extra area (e.g. from neighbours) - widenedRect.merge(extraTargetRect); - - // widenedRect now contains terrain point space version of the area we - // need to calculate. However, we need to calculate in lightmap image space - float terrainToLightmapScale = (float)mLightmapSizeActual / (float)mSize; - widenedRect.left = (widenedRect.left * terrainToLightmapScale); - widenedRect.right = (widenedRect.right * terrainToLightmapScale); - widenedRect.top = (widenedRect.top * terrainToLightmapScale); - widenedRect.bottom = (widenedRect.bottom * terrainToLightmapScale); - - // clamp - widenedRect = widenedRect.intersect(Rect(0, 0, mLightmapSizeActual, mLightmapSizeActual)); - - outFinalRect = widenedRect; - - // allocate memory (L8) - uint8* pData = static_cast( - OGRE_MALLOC(widenedRect.width() * widenedRect.height(), MEMCATEGORY_GENERAL)); - - PixelBox* pixbox = OGRE_NEW PixelBox(static_cast(widenedRect.width()), - static_cast(widenedRect.height()), 1, PF_L8, pData); - - Real heightPad = (getMaxHeight() - getMinHeight()) * 1.0e-3f; - - for (long y = widenedRect.top; y < widenedRect.bottom; ++y) - { - for (long x = widenedRect.left; x < widenedRect.right; ++x) - { - float litVal = 1.0f; - - // convert to terrain space (not points, allow this to go between points) - float Tx = (float)x / (float)(mLightmapSizeActual-1); - float Ty = (float)y / (float)(mLightmapSizeActual-1); - - // get world space point - // add a little height padding to stop shadowing self - Vector3 wpos = Vector3::ZERO; - getPosition(Tx, Ty, getHeightAtTerrainPosition(Tx, Ty) + heightPad, &wpos); - wpos += getPosition(); - // build ray, cast backwards along light direction - Ray ray(wpos, -lightVec); - - // Cascade into neighbours when casting, but don't travel further - // than world size - std::pair rayHit = rayIntersects(ray, true, mWorldSize); - - if (rayHit.first) - litVal = 0.0f; - - // encode as L8 - // invert the Y to deal with image space - long storeX = x - widenedRect.left; - long storeY = widenedRect.bottom - y - 1; - - uint8* pStore = pData + ((storeY * widenedRect.width()) + storeX); - *pStore = (unsigned char)(litVal * 255.0); - - } - } - - return pixbox; - - - } - //--------------------------------------------------------------------- - void Terrain::finaliseLightmap(const Rect& rect, PixelBox* lightmapBox) - { - createOrDestroyGPULightmap(); - // deal with race condition where lm has been disabled while we were working! - if (mLightmap) - { - // blit the normals into the texture - if (rect.left == 0 && rect.top == 0 && rect.bottom == mLightmapSizeActual && rect.right == mLightmapSizeActual) - { - mLightmap->getBuffer()->blitFromMemory(*lightmapBox); - } - else - { - // content of PixelBox is already inverted in Y, but rect is still - // in terrain space for dealing with sub-rect, so invert - Box dstBox; - dstBox.left = static_cast(rect.left); - dstBox.right = static_cast(rect.right); - dstBox.top = static_cast(mLightmapSizeActual - rect.bottom); - dstBox.bottom = static_cast(mLightmapSizeActual - rect.top); - mLightmap->getBuffer()->blitFromMemory(*lightmapBox, dstBox); - } - } - - // delete memory - OGRE_FREE(lightmapBox->data, MEMCATEGORY_GENERAL); - OGRE_DELETE(lightmapBox); - - - } - //--------------------------------------------------------------------- - void Terrain::updateCompositeMap() - { - // All done in the render thread - if (mCompositeMapRequired && !mCompositeMapDirtyRect.isNull()) - { - mModified = true; - createOrDestroyGPUCompositeMap(); - if (mCompositeMapDirtyRectLightmapUpdate && - (mCompositeMapDirtyRect.width() < mSize || mCompositeMapDirtyRect.height() < mSize)) - { - // widen the dirty rectangle since lighting makes it wider - Rect widenedRect; - widenRectByVector(TerrainGlobalOptions::getSingleton().getLightMapDirection(), mCompositeMapDirtyRect, widenedRect); - // clamp - widenedRect = widenedRect.intersect(Rect(0, 0, mSize, mSize)); - mMaterialGenerator->updateCompositeMap(this, widenedRect); - } - else - mMaterialGenerator->updateCompositeMap(this, mCompositeMapDirtyRect); - - mCompositeMapDirtyRectLightmapUpdate = false; - mCompositeMapDirtyRect.setNull(); - - - } - } - //--------------------------------------------------------------------- - void Terrain::updateCompositeMapWithDelay(Real delay) - { - mCompositeMapUpdateCountdown = (long)(delay * 1000); - } - //--------------------------------------------------------------------- - uint8 Terrain::getBlendTextureIndex(uint8 layerIndex) const - { - if (layerIndex == 0 || layerIndex-1 >= (uint8)mLayerBlendMapList.size()) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Invalid layer index", "Terrain::getBlendTextureIndex"); - - return (layerIndex - 1) % 4; - - } - //--------------------------------------------------------------------- - const String& Terrain::getBlendTextureName(uint8 textureIndex) const - { - if (textureIndex >= (uint8)mBlendTextureList.size()) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Invalid texture index", "Terrain::getBlendTextureName"); - - return mBlendTextureList[textureIndex]->getName(); - } - //--------------------------------------------------------------------- - void Terrain::setGlobalColourMapEnabled(bool enabled, uint16 sz) - { - if (!sz) - sz = TerrainGlobalOptions::getSingleton().getDefaultGlobalColourMapSize(); - - if (enabled != mGlobalColourMapEnabled || - (enabled && mGlobalColourMapSize != sz)) - { - mGlobalColourMapEnabled = enabled; - mGlobalColourMapSize = sz; - - createOrDestroyGPUColourMap(); - - mMaterialDirty = true; - mMaterialParamsDirty = true; - mModified = true; - } - - } - //--------------------------------------------------------------------- - void Terrain::createOrDestroyGPUColourMap() - { - if (mGlobalColourMapEnabled && !mColourMap) - { - // create - mColourMap = TextureManager::getSingleton().createManual( - mMaterialName + "/cm", _getDerivedResourceGroup(), - TEX_TYPE_2D, mGlobalColourMapSize, mGlobalColourMapSize, MIP_DEFAULT, - PF_BYTE_RGB, TU_AUTOMIPMAP|TU_STATIC); - - if (mCpuColourMap.getData()) - { - // Load cached data - mColourMap->getBuffer()->blitFromMemory(mCpuColourMap.getPixelBox()); - // release CPU copy, don't need it anymore - mCpuColourMap.freeMemory(); - } - } - else if (!mGlobalColourMapEnabled && mColourMap) - { - // destroy - TextureManager::getSingleton().remove(mColourMap); - mColourMap.reset(); - } - - } - //--------------------------------------------------------------------- - void Terrain::createOrDestroyGPULightmap() - { - if (mLightMapRequired && !mLightmap) - { - // create - mLightmap = TextureManager::getSingleton().createManual( - mMaterialName + "/lm", _getDerivedResourceGroup(), - TEX_TYPE_2D, mLightmapSize, mLightmapSize, 0, PF_L8, TU_STATIC); - - mLightmapSizeActual = mLightmap->getWidth(); - - if (mCpuLightmap.getData()) - { - // Load cached data - mLightmap->getBuffer()->blitFromMemory(mCpuLightmap.getPixelBox()); - // release CPU copy, don't need it anymore - mCpuLightmap.freeMemory(); - } - else - { - // initialise to full-bright - Box box(0, 0, mLightmapSizeActual, mLightmapSizeActual); - HardwarePixelBufferSharedPtr buf = mLightmap->getBuffer(); - uint8* pInit = buf->lock(box, HardwarePixelBuffer::HBL_DISCARD).data; - memset(pInit, 255, mLightmapSizeActual * mLightmapSizeActual); - buf->unlock(); - - } - } - else if (!mLightMapRequired && mLightmap) - { - // destroy - TextureManager::getSingleton().remove(mLightmap); - mLightmap.reset(); - } - - } - //--------------------------------------------------------------------- - void Terrain::createOrDestroyGPUCompositeMap() - { - if (mCompositeMapRequired && !mCompositeMap) - { - // create - mCompositeMap = TextureManager::getSingleton().createManual( - mMaterialName + "/comp", _getDerivedResourceGroup(), - TEX_TYPE_2D, mCompositeMapSize, mCompositeMapSize, 0, PF_BYTE_RGBA, TU_STATIC); - - mCompositeMapSizeActual = mCompositeMap->getWidth(); - - if (mCpuCompositeMap.getData()) - { - // Load cached data - mCompositeMap->getBuffer()->blitFromMemory(mCpuCompositeMap.getPixelBox()); - // release CPU copy, don't need it anymore - mCpuCompositeMap.freeMemory(); - } - else - { - // initialise to black - Box box(0, 0, mCompositeMapSizeActual, mCompositeMapSizeActual); - HardwarePixelBufferSharedPtr buf = mCompositeMap->getBuffer(); - uint8* pInit = buf->lock(box, HardwarePixelBuffer::HBL_DISCARD).data; - memset(pInit, 0, mCompositeMapSizeActual * mCompositeMapSizeActual * 4); - buf->unlock(); - - } - } - else if (!mCompositeMapRequired && mCompositeMap) - { - // destroy - TextureManager::getSingleton().remove(mCompositeMap); - mCompositeMap.reset(); - } - - } - //--------------------------------------------------------------------- - Terrain* Terrain::getNeighbour(NeighbourIndex index) const - { - return mNeighbours[index]; - } - //--------------------------------------------------------------------- - void Terrain::setNeighbour(NeighbourIndex index, Terrain* neighbour, - bool recalculate /*= false*/, bool notifyOther /* = true */) - { - if (mNeighbours[index] != neighbour) - { - assert(neighbour != this && "Can't set self as own neighbour!"); - - // detach existing - if (mNeighbours[index] && notifyOther) - mNeighbours[index]->setNeighbour(getOppositeNeighbour(index), 0, false, false); - - mNeighbours[index] = neighbour; - if (neighbour && notifyOther) - mNeighbours[index]->setNeighbour(getOppositeNeighbour(index), this, recalculate, false); - - if (recalculate) - { - // Recalculate, pass OUR edge rect - Rect edgerect; - getEdgeRect(index, 2, &edgerect); - neighbourModified(index, edgerect, edgerect); - } - } - } - //--------------------------------------------------------------------- - Terrain::NeighbourIndex Terrain::getOppositeNeighbour(NeighbourIndex index) - { - int intindex = static_cast(index); - intindex += NEIGHBOUR_COUNT / 2; - intindex = intindex % NEIGHBOUR_COUNT; - return static_cast(intindex); - } - //--------------------------------------------------------------------- - Terrain::NeighbourIndex Terrain::getNeighbourIndex(long x, long y) - { - if (x < 0) - { - if (y < 0) - return NEIGHBOUR_SOUTHWEST; - else if (y > 0) - return NEIGHBOUR_NORTHWEST; - else - return NEIGHBOUR_WEST; - } - else if (x > 0) - { - if (y < 0) - return NEIGHBOUR_SOUTHEAST; - else if (y > 0) - return NEIGHBOUR_NORTHEAST; - else - return NEIGHBOUR_EAST; - } - - // x == 0, given the check above - if (y < 0) - return NEIGHBOUR_SOUTH; - else if (y > 0) - return NEIGHBOUR_NORTH; - return NEIGHBOUR_NORTH; - } - //--------------------------------------------------------------------- - void Terrain::notifyNeighbours() - { - // There are 3 things that can need updating: - // Height at edge - match to neighbour (first one to update 'loses' to other since read-only) - // Normal at edge - use heights from across boundary too - // Shadows across edge - // The extent to which these can affect the current tile vary: - // Height at edge - only affected by a change at the adjoining edge / corner - // Normal at edge - only affected by a change to the 2 rows adjoining the edge / corner - // Shadows across edge - possible effect extends based on the projection of the - // neighbour AABB along the light direction (worst case scenario) - - if (!mDirtyGeometryRectForNeighbours.isNull()) - { - Rect dirtyRectForNeighbours(mDirtyGeometryRectForNeighbours); - mDirtyGeometryRectForNeighbours.setNull(); - // calculate light update rectangle - const Vector3& lightVec = TerrainGlobalOptions::getSingleton().getLightMapDirection(); - Rect lightmapRect; - widenRectByVector(lightVec, dirtyRectForNeighbours, getMinHeight(), getMaxHeight(), lightmapRect); - - for (int i = 0; i < (int)NEIGHBOUR_COUNT; ++i) - { - NeighbourIndex ni = static_cast(i); - Terrain* neighbour = getNeighbour(ni); - if (!neighbour) - continue; - - // Intersect the incoming rectangles with the edge regions related to this neighbour - Rect edgeRect; - getEdgeRect(ni, 2, &edgeRect); - Rect heightEdgeRect = edgeRect.intersect(dirtyRectForNeighbours); - Rect lightmapEdgeRect = edgeRect.intersect(lightmapRect); - - if (!heightEdgeRect.isNull() || !lightmapRect.isNull()) - { - // ok, we have something valid to pass on - Rect neighbourHeightEdgeRect, neighbourLightmapEdgeRect; - if (!heightEdgeRect.isNull()) - getNeighbourEdgeRect(ni, heightEdgeRect, &neighbourHeightEdgeRect); - if (!lightmapRect.isNull()) - getNeighbourEdgeRect(ni, lightmapEdgeRect, &neighbourLightmapEdgeRect); - - neighbour->neighbourModified(getOppositeNeighbour(ni), - neighbourHeightEdgeRect, neighbourLightmapEdgeRect); - - } - - } - } - } - //--------------------------------------------------------------------- - void Terrain::neighbourModified(NeighbourIndex index, const Rect& edgerect, const Rect& shadowrect) - { - // We can safely assume that we would not have been contacted if it wasn't - // important - const Terrain* neighbour = getNeighbour(index); - if (!neighbour) - return; // bogus request - - bool updateGeom = false; - uint8 updateDerived = 0; - - - if (!edgerect.isNull()) - { - // update edges; match heights first, then recalculate normals - // reduce to just single line / corner - Rect heightMatchRect; - getEdgeRect(index, 1, &heightMatchRect); - heightMatchRect = heightMatchRect.intersect(edgerect); - - for (int y = heightMatchRect.top; y < heightMatchRect.bottom; ++y) - { - for (int x = heightMatchRect.left; x < heightMatchRect.right; ++x) - { - uint32 nx, ny; - getNeighbourPoint(index, x, y, &nx, &ny); - float neighbourHeight = neighbour->getHeightAtPoint(nx, ny); - if (!Math::RealEqual(neighbourHeight, getHeightAtPoint(x, y), 1e-3f)) - { - setHeightAtPoint(x, y, neighbourHeight); - if (!updateGeom) - { - updateGeom = true; - updateDerived |= DERIVED_DATA_ALL; - } - - } - } - } - // if we didn't need to update heights, we still need to update normals - // because this was called only if neighbor changed - if (!updateGeom) - { - // ideally we would deal with normal dirty rect separately (as we do with - // lightmaps) because a dirty geom rectangle will actually grow by one - // element in each direction for normals recalculation. However for - // the sake of one row/column it's really not worth it. - mDirtyDerivedDataRect.merge(edgerect); - updateDerived |= DERIVED_DATA_NORMALS; - } - } - - if (!shadowrect.isNull()) - { - // update shadows - // here we need to widen the rect passed in based on the min/max height - // of the *neighbour* - const Vector3& lightVec = TerrainGlobalOptions::getSingleton().getLightMapDirection(); - Rect widenedRect; - widenRectByVector(lightVec, shadowrect, neighbour->getMinHeight(), neighbour->getMaxHeight(), widenedRect); - - // set the special-case lightmap dirty rectangle - mDirtyLightmapFromNeighboursRect.merge(widenedRect); - updateDerived |= DERIVED_DATA_LIGHTMAP; - } - - if (updateGeom) - updateGeometry(); - if (updateDerived) - updateDerivedData(false, updateDerived); - - - - } - //--------------------------------------------------------------------- - void Terrain::getEdgeRect(NeighbourIndex index, int32 range, Rect* outRect) const - { - // We make the edge rectangle 2 rows / columns at the edge of the tile - // 2 because this copes with normal changes and potentially filtered - // shadows. - // all right / bottom values are exclusive - // terrain origin is bottom-left remember so north is highest value - - // set left/right - switch(index) - { - case NEIGHBOUR_EAST: - case NEIGHBOUR_NORTHEAST: - case NEIGHBOUR_SOUTHEAST: - outRect->left = mSize - range; - outRect->right = mSize; - break; - case NEIGHBOUR_WEST: - case NEIGHBOUR_NORTHWEST: - case NEIGHBOUR_SOUTHWEST: - outRect->left = 0; - outRect->right = range; - break; - case NEIGHBOUR_NORTH: - case NEIGHBOUR_SOUTH: - outRect->left = 0; - outRect->right = mSize; - break; - case NEIGHBOUR_COUNT: - default: - break; - }; - - // set top / bottom - switch(index) - { - case NEIGHBOUR_NORTH: - case NEIGHBOUR_NORTHEAST: - case NEIGHBOUR_NORTHWEST: - outRect->top = mSize - range; - outRect->bottom = mSize; - break; - case NEIGHBOUR_SOUTH: - case NEIGHBOUR_SOUTHWEST: - case NEIGHBOUR_SOUTHEAST: - outRect->top = 0; - outRect->bottom = range; - break; - case NEIGHBOUR_EAST: - case NEIGHBOUR_WEST: - outRect->top = 0; - outRect->bottom = mSize; - break; - case NEIGHBOUR_COUNT: - default: - break; - }; - } - //--------------------------------------------------------------------- - void Terrain::getNeighbourEdgeRect(NeighbourIndex index, const Rect& inRect, Rect* outRect) const - { - assert (mSize == getNeighbour(index)->getSize()); - - // Basically just reflect the rect - // remember index is neighbour relationship from OUR perspective so - // arrangement is backwards to getEdgeRect - - // left/right - switch(index) - { - case NEIGHBOUR_EAST: - case NEIGHBOUR_NORTHEAST: - case NEIGHBOUR_SOUTHEAST: - case NEIGHBOUR_WEST: - case NEIGHBOUR_NORTHWEST: - case NEIGHBOUR_SOUTHWEST: - outRect->left = mSize - inRect.right; - outRect->right = mSize - inRect.left; - break; - default: - outRect->left = inRect.left; - outRect->right = inRect.right; - break; - }; - - // top / bottom - switch(index) - { - case NEIGHBOUR_NORTH: - case NEIGHBOUR_NORTHEAST: - case NEIGHBOUR_NORTHWEST: - case NEIGHBOUR_SOUTH: - case NEIGHBOUR_SOUTHWEST: - case NEIGHBOUR_SOUTHEAST: - outRect->top = mSize - inRect.bottom; - outRect->bottom = mSize - inRect.top; - break; - default: - outRect->top = inRect.top; - outRect->bottom = inRect.bottom; - break; - }; - - } - //--------------------------------------------------------------------- - void Terrain::getNeighbourPoint(NeighbourIndex index, uint32 x, uint32 y, uint32 *outx, uint32 *outy) const - { - // Get the index of the point we should be looking at on a neighbour - // in order to match up points - assert (mSize == getNeighbour(index)->getSize()); - - // left/right - switch(index) - { - case NEIGHBOUR_EAST: - case NEIGHBOUR_NORTHEAST: - case NEIGHBOUR_SOUTHEAST: - case NEIGHBOUR_WEST: - case NEIGHBOUR_NORTHWEST: - case NEIGHBOUR_SOUTHWEST: - *outx = mSize - x - 1; - break; - default: - *outx = x; - break; - }; - - // top / bottom - switch(index) - { - case NEIGHBOUR_NORTH: - case NEIGHBOUR_NORTHEAST: - case NEIGHBOUR_NORTHWEST: - case NEIGHBOUR_SOUTH: - case NEIGHBOUR_SOUTHWEST: - case NEIGHBOUR_SOUTHEAST: - *outy = mSize - y - 1; - break; - default: - *outy = y; - break; - }; - } - //--------------------------------------------------------------------- - void Terrain::getPointFromSelfOrNeighbour(int32 x, int32 y, Vector3* outpos) const - { - if (x >= 0 && y >=0 && x < mSize && y < mSize) - getPoint(x, y, outpos); - else - { - uint32 nx, ny; - NeighbourIndex ni = NEIGHBOUR_EAST; - getNeighbourPointOverflow(x, y, &ni, &nx, &ny); - Terrain* neighbour = getNeighbour(ni); - if (neighbour) - { - Vector3 neighbourPos = Vector3::ZERO; - neighbour->getPoint(nx, ny, &neighbourPos); - // adjust to make it relative to our position - *outpos = neighbourPos + neighbour->getPosition() - getPosition(); - } - else - { - // use our getPoint() after all, just clamp - x = std::min(x, mSize - 1); - y = std::min(y, mSize - 1); - x = std::max(x, 0); - y = std::max(y, 0); - getPoint(x, y, outpos); - } - - } - } - //--------------------------------------------------------------------- - void Terrain::getNeighbourPointOverflow(int32 x, int32 y, NeighbourIndex *outindex, uint32 *outx, uint32 *outy) const - { - if (x < 0) - { - *outx = x + mSize - 1; - if (y < 0) - *outindex = NEIGHBOUR_SOUTHWEST; - else if (y >= mSize) - *outindex = NEIGHBOUR_NORTHWEST; - else - *outindex = NEIGHBOUR_WEST; - } - else if (x >= mSize) - { - *outx = x - mSize + 1; - if (y < 0) - *outindex = NEIGHBOUR_SOUTHEAST; - else if (y >= mSize) - *outindex = NEIGHBOUR_NORTHEAST; - else - *outindex = NEIGHBOUR_EAST; - } - else - *outx = x; - - if (y < 0) - { - *outy = y + mSize - 1; - if (x >= 0 && x < mSize) - *outindex = NEIGHBOUR_SOUTH; - } - else if (y >= mSize) - { - *outy = y - mSize + 1; - if (x >= 0 && x < mSize) - *outindex = NEIGHBOUR_NORTH; - } - else - *outy = y; - } - //--------------------------------------------------------------------- - Terrain* Terrain::raySelectNeighbour(const Ray& ray, Real distanceLimit /* = 0 */) - { - Ray modifiedRay(ray.getOrigin(), ray.getDirection()); - // Move back half a square - if we're on the edge of the AABB we might - // miss the intersection otherwise; it's ok for everywhere else since - // we want the far intersection anyway - modifiedRay.setOrigin(modifiedRay.getPoint(-mWorldSize/mSize * 0.5f)); - - // transform into terrain space - Vector3 tPos, tDir; - convertPosition(WORLD_SPACE, modifiedRay.getOrigin(), TERRAIN_SPACE, tPos); - convertDirection(WORLD_SPACE, modifiedRay.getDirection(), TERRAIN_SPACE, tDir); - // Discard rays with no lateral component - if (Math::RealEqual(tDir.x, 0.0f, 1e-4) && Math::RealEqual(tDir.y, 0.0f, 1e-4)) - return 0; - - Ray terrainRay(tPos, tDir); - // Intersect with boundary planes - // Only collide with the positive (exit) side of the plane, because we may be - // querying from a point outside ourselves if we've cascaded more than once - Real dist = std::numeric_limits::max(); - std::pair intersectResult; - if (tDir.x < 0.0f) - { - intersectResult = Math::intersects(terrainRay, Plane(Vector3::UNIT_X, Vector3::ZERO)); - if (intersectResult.first && intersectResult.second < dist) - dist = intersectResult.second; - } - else if (tDir.x > 0.0f) - { - intersectResult = Math::intersects(terrainRay, Plane(Vector3::NEGATIVE_UNIT_X, Vector3(1,0,0))); - if (intersectResult.first && intersectResult.second < dist) - dist = intersectResult.second; - } - if (tDir.y < 0.0f) - { - intersectResult = Math::intersects(terrainRay, Plane(Vector3::UNIT_Y, Vector3::ZERO)); - if (intersectResult.first && intersectResult.second < dist) - dist = intersectResult.second; - } - else if (tDir.y > 0.0f) - { - intersectResult = Math::intersects(terrainRay, Plane(Vector3::NEGATIVE_UNIT_Y, Vector3(0,1,0))); - if (intersectResult.first && intersectResult.second < dist) - dist = intersectResult.second; - } - - - // discard out of range - if (dist * mWorldSize > distanceLimit) - return 0; - - Vector3 terrainIntersectPos = terrainRay.getPoint(dist); - Real x = terrainIntersectPos.x; - Real y = terrainIntersectPos.y; - Real dx = tDir.x; - Real dy = tDir.y; - - // Never return diagonal directions, we will navigate those recursively anyway - if (Math::RealEqual(x, 1.0f, 1e-4f) && dx > 0) - return getNeighbour(NEIGHBOUR_EAST); - else if (Math::RealEqual(x, 0.0f, 1e-4f) && dx < 0) - return getNeighbour(NEIGHBOUR_WEST); - else if (Math::RealEqual(y, 1.0f, 1e-4f) && dy > 0) - return getNeighbour(NEIGHBOUR_NORTH); - else if (Math::RealEqual(y, 0.0f, 1e-4f) && dy < 0) - return getNeighbour(NEIGHBOUR_SOUTH); - - - - return 0; - } - //--------------------------------------------------------------------- - void Terrain::_dumpTextures(const String& prefix, const String& suffix) - { - if (mTerrainNormalMap) - { - Image img; - mTerrainNormalMap->convertToImage(img); - img.save(prefix + "_normalmap" + suffix); - } - - if (mColourMap) - { - Image img; - mColourMap->convertToImage(img); - img.save(prefix + "_colourmap" + suffix); - } - - if (mLightmap) - { - Image img; - mLightmap->convertToImage(img); - img.save(prefix + "_lightmap" + suffix); - } - - if (mCompositeMap) - { - Image img; - mCompositeMap->convertToImage(img); - img.save(prefix + "_compositemap" + suffix); - } - - int blendTexture = 0; - for (TexturePtrList::iterator i = mBlendTextureList.begin(); i != mBlendTextureList.end(); ++i, ++blendTexture) - { - if (*i) - { - Image img; - (*i)->convertToImage(img); - img.save(prefix + "_blendtexture" + StringConverter::toString(blendTexture) + suffix); - } - } - - } - //--------------------------------------------------------------------- - void Terrain::setGpuBufferAllocator(GpuBufferAllocator* alloc) - { - if (alloc != getGpuBufferAllocator()) - { - if (isLoaded()) - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, - "Cannot alter the allocator when loaded!"); - - mCustomGpuBufferAllocator = alloc; - } - } - //--------------------------------------------------------------------- - Terrain::GpuBufferAllocator* Terrain::getGpuBufferAllocator() - { - if (mCustomGpuBufferAllocator) - return mCustomGpuBufferAllocator; - else - return &mDefaultGpuBufferAllocator; - } - //--------------------------------------------------------------------- - size_t Terrain::getPositionBufVertexSize() const - { - size_t sz = 0; - if (_getUseVertexCompression()) - { - // short2 position - sz += sizeof(short) * 2; - // float1 height - sz += sizeof(float); - } - else - { - // float3 position - sz += sizeof(float) * 3; - // float2 uv - sz += sizeof(float) * 2; - } - - return sz; - - } - //--------------------------------------------------------------------- - size_t Terrain::getDeltaBufVertexSize() const - { - // float2(delta, deltaLODthreshold) - return sizeof(float) * 2; - } - //--------------------------------------------------------------------- - size_t Terrain::_getNumIndexesForBatchSize(uint16 batchSize) - { - size_t mainIndexesPerRow = batchSize * 2 + 1; - size_t numRows = batchSize - 1; - size_t mainIndexCount = mainIndexesPerRow * numRows; - // skirts share edges, so they take 1 less row per side than batchSize, - // but with 2 extra at the end (repeated) to finish the strip - // * 2 for the vertical line, * 4 for the sides, +2 to finish - size_t skirtIndexCount = (batchSize - 1) * 2 * 4 + 2; - return mainIndexCount + skirtIndexCount; - - } - //--------------------------------------------------------------------- - void Terrain::_populateIndexBuffer(uint16* pI, uint16 batchSize, - uint16 vdatasize, uint16 vertexIncrement, uint16 xoffset, uint16 yoffset, uint16 numSkirtRowsCols, - uint16 skirtRowColSkip) - { - /* For even / odd tri strip rows, triangles are this shape: - 6---7---8 - | \ | \ | - 3---4---5 - | / | / | - 0---1---2 - Note how vertex rows count upwards. In order to match up the anti-clockwise - winding and this upward transitioning list, we need to start from the - right hand side. So we get (2,5,1,4,0,3) etc on even lines (right-left) - and (3,6,4,7,5,8) etc on odd lines (left-right). At the turn, we emit the end index - twice, this forms a degenerate triangle, which lets us turn without any artefacts. - So the full list in this simple case is (2,5,1,4,0,3,3,6,4,7,5,8) - - Skirts are part of the same strip, so after finishing on 8, where sX is - the skirt vertex corresponding to main vertex X, we go - anticlockwise around the edge, (s8,7,s7,6,s6) to do the top skirt, - then (3,s3,0,s0),(1,s1,2,s2),(5,s5,8,s8) to finish the left, bottom, and - right skirts respectively. - */ - - // to issue a complete row, it takes issuing the upper and lower row - // and one extra index, which is the degenerate triangle and also turning - // around the winding - - uint16 rowSize = vdatasize * vertexIncrement; - uint16 numRows = batchSize - 1; - - // Start on the right - uint16 currentVertex = (batchSize - 1) * vertexIncrement; - // but, our quad area might not start at 0 in this vertex data - // offsets are at main terrain resolution, remember - uint16 columnStart = xoffset; - uint16 rowStart = yoffset; - currentVertex += rowStart * vdatasize + columnStart; - bool rightToLeft = true; - for (uint16 r = 0; r < numRows; ++r) - { - for (uint16 c = 0; c < batchSize; ++c) - { - - *pI++ = currentVertex; - *pI++ = currentVertex + rowSize; - - // don't increment / decrement at a border, keep this vertex for next - // row as we 'snake' across the tile - if (c+1 < batchSize) - { - currentVertex = rightToLeft ? - currentVertex - vertexIncrement : currentVertex + vertexIncrement; - } - } - rightToLeft = !rightToLeft; - currentVertex += rowSize; - // issue one extra index to turn winding around - *pI++ = currentVertex; - } - - // Skirts - for (uint16 s = 0; s < 4; ++s) - { - // edgeIncrement is the index offset from one original edge vertex to the next - // in this row or column. Columns skip based on a row size here - // skirtIncrement is the index offset from one skirt vertex to the next, - // because skirts are packed in rows/cols then there is no row multiplier for - // processing columns - int edgeIncrement = 0, skirtIncrement = 0; - switch(s) - { - case 0: // top - edgeIncrement = -static_cast(vertexIncrement); - skirtIncrement = -static_cast(vertexIncrement); - break; - case 1: // left - edgeIncrement = -static_cast(rowSize); - skirtIncrement = -static_cast(vertexIncrement); - break; - case 2: // bottom - edgeIncrement = static_cast(vertexIncrement); - skirtIncrement = static_cast(vertexIncrement); - break; - case 3: // right - edgeIncrement = static_cast(rowSize); - skirtIncrement = static_cast(vertexIncrement); - break; - } - // Skirts are stored in contiguous rows / columns (rows 0/2, cols 1/3) - uint16 skirtIndex = _calcSkirtVertexIndex(currentVertex, vdatasize, - (s % 2) != 0, numSkirtRowsCols, skirtRowColSkip); - for (uint16 c = 0; c < batchSize - 1; ++c) - { - *pI++ = currentVertex; - *pI++ = skirtIndex; - currentVertex += edgeIncrement; - skirtIndex += skirtIncrement; - } - if (s == 3) - { - // we issue an extra 2 indices to finish the skirt off - *pI++ = currentVertex; - *pI++ = skirtIndex; - currentVertex += edgeIncrement; - } - } - - } - //--------------------------------------------------------------------- - uint16 Terrain::_calcSkirtVertexIndex(uint16 mainIndex, uint16 vdatasize, bool isCol, - uint16 numSkirtRowsCols, uint16 skirtRowColSkip) - { - // row / col in main vertex resolution - uint16 row = mainIndex / vdatasize; - uint16 col = mainIndex % vdatasize; - - // skirts are after main vertices, so skip them - uint16 base = vdatasize * vdatasize; - - // The layout in vertex data is: - // 1. row skirts - // numSkirtRowsCols rows of resolution vertices each - // 2. column skirts - // numSkirtRowsCols cols of resolution vertices each - - // No offsets used here, this is an index into the current vertex data, - // which is already relative - if (isCol) - { - uint16 skirtNum = col / skirtRowColSkip; - uint16 colbase = numSkirtRowsCols * vdatasize; - return base + colbase + vdatasize * skirtNum + row; - } - else - { - uint16 skirtNum = row / skirtRowColSkip; - return base + vdatasize * skirtNum + col; - } - - } - //--------------------------------------------------------------------- - void Terrain::setWorldSize(Real newWorldSize) - { - if(mWorldSize != newWorldSize) - { - waitForDerivedProcesses(); - - mWorldSize = newWorldSize; - - updateBaseScale(); - - deriveUVMultipliers(); - - mMaterialParamsDirty = true; - - if(mIsLoaded) - { - Rect dRect(0, 0, mSize, mSize); - dirtyRect(dRect); - update(); - } - - mModified = true; - } - } - //--------------------------------------------------------------------- - void Terrain::setSize(uint16 newSize) - { - if(mSize != newSize) - { - waitForDerivedProcesses(); - // load full HeightData - load(0,true); - - size_t numVertices = newSize * newSize; - - PixelBox src(mSize, mSize, 1, Ogre::PF_FLOAT32_R, (void*)getHeightData()); - - float* tmpData = OGRE_ALLOC_T(float, numVertices, MEMCATEGORY_GENERAL); - - PixelBox dst(newSize, newSize, 1, Ogre::PF_FLOAT32_R, tmpData); - - Image::scale(src, dst, Image::FILTER_BILINEAR); - - if (mTerrainNormalMap) - { - TextureManager::getSingletonPtr()->remove(mTerrainNormalMap->getHandle()); - mTerrainNormalMap.reset(); - } - - freeLodData(); - freeCPUResources(); - mLodManager = OGRE_NEW TerrainLodManager( this ); - mSize = newSize; - - determineLodLevels(); - - updateBaseScale(); - - deriveUVMultipliers(); - - mMaterialParamsDirty = true; - - mHeightData = tmpData; - mDeltaData = OGRE_ALLOC_T(float, numVertices, MEMCATEGORY_GEOMETRY); - memset(mDeltaData, 0, sizeof(float) * numVertices); - - mQuadTree = OGRE_NEW TerrainQuadTreeNode(this, 0, 0, 0, mSize, mNumLodLevels - 1, 0); - mQuadTree->prepare(); - - // calculate entire terrain - Rect rect; - rect.top = 0; rect.bottom = mSize; - rect.left = 0; rect.right = mSize; - calculateHeightDeltas(rect); - finaliseHeightDeltas(rect, true); - - if(mIsLoaded) - { - load(0,true); - } - - mModified = true; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - Terrain::DefaultGpuBufferAllocator::DefaultGpuBufferAllocator() - { - - } - //--------------------------------------------------------------------- - Terrain::DefaultGpuBufferAllocator::~DefaultGpuBufferAllocator() - { - freeAllBuffers(); - } - //--------------------------------------------------------------------- - void Terrain::DefaultGpuBufferAllocator::allocateVertexBuffers(Terrain* forTerrain, - size_t numVertices, HardwareVertexBufferSharedPtr& destPos, HardwareVertexBufferSharedPtr& destDelta) - { - destPos = getVertexBuffer(mFreePosBufList, forTerrain->getPositionBufVertexSize(), numVertices); - destDelta = getVertexBuffer(mFreeDeltaBufList, forTerrain->getDeltaBufVertexSize(), numVertices); - - } - //--------------------------------------------------------------------- - HardwareVertexBufferSharedPtr Terrain::DefaultGpuBufferAllocator::getVertexBuffer( - VBufList& list, size_t vertexSize, size_t numVertices) - { - size_t sz = vertexSize * numVertices; - for (VBufList::iterator i = list.begin(); i != list.end(); ++i) - { - if ((*i)->getSizeInBytes() == sz) - { - HardwareVertexBufferSharedPtr ret = *i; - list.erase(i); - return ret; - } - } - // Didn't find one? - return HardwareBufferManager::getSingleton() - .createVertexBuffer(vertexSize, numVertices, HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - - } - //--------------------------------------------------------------------- - void Terrain::DefaultGpuBufferAllocator::freeVertexBuffers( - const HardwareVertexBufferSharedPtr& posbuf, const HardwareVertexBufferSharedPtr& deltabuf) - { - mFreePosBufList.push_back(posbuf); - mFreeDeltaBufList.push_back(deltabuf); - } - //--------------------------------------------------------------------- - HardwareIndexBufferSharedPtr Terrain::DefaultGpuBufferAllocator::getSharedIndexBuffer(uint16 batchSize, - uint16 vdatasize, size_t vertexIncrement, uint16 xoffset, uint16 yoffset, uint16 numSkirtRowsCols, - uint16 skirtRowColSkip) - { - uint32 hsh = hashIndexBuffer(batchSize, vdatasize, vertexIncrement, xoffset, yoffset, - numSkirtRowsCols, skirtRowColSkip); - - IBufMap::iterator i = mSharedIBufMap.find(hsh); - if (i == mSharedIBufMap.end()) - { - // create new - size_t indexCount = Terrain::_getNumIndexesForBatchSize(batchSize); - HardwareIndexBufferSharedPtr ret = HardwareBufferManager::getSingleton() - .createIndexBuffer(HardwareIndexBuffer::IT_16BIT, indexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - uint16* pI = static_cast(ret->lock(HardwareBuffer::HBL_DISCARD)); - Terrain::_populateIndexBuffer(pI, batchSize, vdatasize, uint16(vertexIncrement), xoffset, yoffset, numSkirtRowsCols, skirtRowColSkip); - ret->unlock(); - - mSharedIBufMap[hsh] = ret; - return ret; - } - else - return i->second; - - } - //--------------------------------------------------------------------- - void Terrain::DefaultGpuBufferAllocator::freeAllBuffers() - { - mFreePosBufList.clear(); - mFreeDeltaBufList.clear(); - mSharedIBufMap.clear(); - } - //--------------------------------------------------------------------- - void Terrain::DefaultGpuBufferAllocator::warmStart(size_t numInstances, uint16 terrainSize, uint16 maxBatchSize, - uint16 minBatchSize) - { - // TODO - - } - //--------------------------------------------------------------------- - uint32 Terrain::DefaultGpuBufferAllocator::hashIndexBuffer(uint16 batchSize, - uint16 vdatasize, size_t vertexIncrement, uint16 xoffset, uint16 yoffset, uint16 numSkirtRowsCols, - uint16 skirtRowColSkip) - { - uint32 ret = 0; - ret = HashCombine(ret, batchSize); - ret = HashCombine(ret, vdatasize); - ret = HashCombine(ret, vertexIncrement); - ret = HashCombine(ret, xoffset); - ret = HashCombine(ret, yoffset); - ret = HashCombine(ret, numSkirtRowsCols); - ret = HashCombine(ret, skirtRowColSkip); - return ret; - - } - //--------------------------------------------------------------------- - void Terrain::increaseLodLevel(bool synchronous /* = false */) - { - int lodLevel = mLodManager->getTargetLodLevel(); - if(lodLevel<0) - mLodManager->updateToLodLevel(-1, synchronous); - else if( --lodLevel >= 0 ) - mLodManager->updateToLodLevel(lodLevel, synchronous); - } - //--------------------------------------------------------------------- - void Terrain::decreaseLodLevel() - { - int lodLevel = mLodManager->getTargetLodLevel() + 1; - if( lodLevel>0 && lodLevelupdateToLodLevel(lodLevel); - } - - void Terrain::removeFromNeighbours() - { - // We are reading the list of neighbours here - OGRE_LOCK_RW_MUTEX_READ(mNeighbourMutex); - for (int i = 0; i < (int)NEIGHBOUR_COUNT; ++i) - { - NeighbourIndex ni = static_cast(i); - Terrain* neighbour = getNeighbour(ni); - if (!neighbour) - continue; - - OGRE_LOCK_RW_MUTEX_WRITE(neighbour->mNeighbourMutex); - // TODO: do we want to re-calculate? probably not, but not sure - neighbour->setNeighbour(getOppositeNeighbour(ni), 0, false, false); - } - } -} diff --git a/Components/Terrain/src/OgreTerrainAutoUpdateLod.cpp b/Components/Terrain/src/OgreTerrainAutoUpdateLod.cpp deleted file mode 100644 index 935e07763d4..00000000000 --- a/Components/Terrain/src/OgreTerrainAutoUpdateLod.cpp +++ /dev/null @@ -1,149 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreTerrain.h" -#include "OgreTerrainQuadTreeNode.h" -#include "OgreCamera.h" -#include "OgreSceneManager.h" -#include "OgreViewport.h" -#include "OgreLogManager.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" -#include "OgreRay.h" -#include "OgreTerrainAutoUpdateLod.h" - -/* -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -// we do lots of conversions here, casting them all is tedious & cluttered, we know what we're doing -# pragma warning (disable : 4244) -#endif -*/ - -namespace Ogre -{ - void TerrainAutoUpdateLodByDistance::autoUpdateLod(Terrain *terrain, bool synchronous, const Any &data) - { - if( terrain ) - autoUpdateLodByDistance(terrain, synchronous, any_cast(data)); - } - - void TerrainAutoUpdateLodByDistance::autoUpdateLodByDistance(Terrain *terrain, bool synchronous, const Real holdDistance) - { - if (!terrain->isLoaded()) - return; - - // calculate error terms - const Viewport* vp = terrain->getSceneManager()->getCurrentViewport(); - if(!vp) - return; - const Camera* cam = vp->getCamera()->getLodCamera(); - - // W. de Boer 2000 calculation - // A = vp_near / abs(vp_top) - // A = 1 / tan(fovy*0.5) (== 1 for fovy=45*2) - Real A = 1.0f / Math::Tan(cam->getFOVy() * 0.5f); - // T = 2 * maxPixelError / vertRes - Real maxPixelError = TerrainGlobalOptions::getSingleton().getMaxPixelError() * cam->_getLodBiasInverse(); - Real T = 2.0f * maxPixelError / (Real)vp->getActualHeight(); - - // CFactor = A / T - Real cFactor = A / T; - - int maxLod = traverseTreeByDistance(terrain->getQuadTree(), cam, cFactor, holdDistance); - if (maxLod >= 0) - terrain->load(maxLod,synchronous); - } - - int TerrainAutoUpdateLodByDistance::traverseTreeByDistance(TerrainQuadTreeNode *node, - const Camera *cam, Real cFactor, const Real holdDistance) - { - if (!node->isLeaf()) - { - int tmp = -1; - for (int i = 0; i < 4; ++i) - { - int ret = traverseTreeByDistance(node->getChild(i), cam, cFactor, holdDistance); - if (ret != -1) - { - if (tmp == -1 || ret < tmp) - tmp = ret; - } - } - - if (tmp != -1) - return tmp; - } - - Vector3 localPos = cam->getDerivedPosition() - node->getLocalCentre() - node->getTerrain()->getPosition(); - Real dist; - if (TerrainGlobalOptions::getSingleton().getUseRayBoxDistanceCalculation()) - { - // Get distance to this terrain node (to closest point of the box) - // head towards centre of the box (note, box may not cover mLocalCentre because of height) - Vector3 dir(node->getBoundingBox().getCenter() - localPos); - dir.normalise(); - Ray ray(localPos, dir); - std::pair intersectRes = Math::intersects(ray, node->getBoundingBox()); - - // ray will always intersect, we just want the distance - dist = intersectRes.second; - } - else - { - // distance to tile centre - dist = localPos.length(); - // deduct half the radius of the box, assume that on average the - // worst case is best approximated by this - dist -= (node->getBoundingRadius() * 0.5f); - } - - // For each LOD, the distance at which the LOD will transition *downwards* - // is given by - // distTransition = maxDelta * cFactor; - for (uint16 lodLevel = 0; lodLevel < node->getLodCount(); ++lodLevel) - { - // If we have no parent, and this is the lowest LOD, we always render - // this is the 'last resort' so to speak, we always enoucnter this last - if (lodLevel+1 == node->getLodCount() && !node->getParent()) - return lodLevel + node->getBaseLod(); - else - { - // Calculate or reuse transition distance - Real distTransition; - if (Math::RealEqual(cFactor, node->getLodLevel(lodLevel)->lastCFactor)) - distTransition = node->getLodLevel(lodLevel)->lastTransitionDist; - else - distTransition = node->getLodLevel(lodLevel)->maxHeightDelta * cFactor; - - if ((dist - holdDistance) < distTransition) - return lodLevel + node->getBaseLod(); - } - } - - return -1; - } -} diff --git a/Components/Terrain/src/OgreTerrainGroup.cpp b/Components/Terrain/src/OgreTerrainGroup.cpp deleted file mode 100644 index 23c374ce576..00000000000 --- a/Components/Terrain/src/OgreTerrainGroup.cpp +++ /dev/null @@ -1,1084 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreTerrainGroup.h" -#include "OgreRoot.h" -#include "OgreWorkQueue.h" -#include "OgreStreamSerialiser.h" -#include "OgreLogManager.h" -#include "OgreTerrainAutoUpdateLod.h" -#include "OgreTerrainMaterialGeneratorA.h" -#include -#include - -namespace Ogre -{ - const uint32 TerrainGroup::CHUNK_ID = StreamSerialiser::makeIdentifier("TERG"); - const uint16 TerrainGroup::CHUNK_VERSION = 1; - - //--------------------------------------------------------------------- - TerrainGroup::TerrainGroup(SceneManager* sm, Terrain::Alignment align, - uint16 terrainSize, Real terrainWorldSize) - : mSceneManager(sm) - , mAlignment(align) - , mTerrainSize(terrainSize) - , mTerrainWorldSize(terrainWorldSize) - , mOrigin(Vector3::ZERO) - , mFilenamePrefix("terrain") - , mFilenameExtension("dat") - , mResourceGroup(ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME) - , mAutoUpdateLod( TerrainAutoUpdateLodFactory::getAutoUpdateLod(NONE) ) - { - mDefaultImportData.terrainAlign = align; - mDefaultImportData.terrainSize = terrainSize; - mDefaultImportData.worldSize = terrainWorldSize; - // by default we delete input data because we copy it, unless user - // passes us an ImportData where they explicitly don't want it copied - mDefaultImportData.deleteInputData = true; - } - //--------------------------------------------------------------------- - TerrainGroup::TerrainGroup(SceneManager* sm) - : mSceneManager(sm) - , mAlignment(Terrain::ALIGN_X_Z) - , mTerrainSize(0) - , mTerrainWorldSize(0) - , mOrigin(Vector3::ZERO) - , mFilenamePrefix("terrain") - , mFilenameExtension("dat") - , mResourceGroup(ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME) - , mAutoUpdateLod(0) - { - mDefaultImportData.terrainAlign = mAlignment; - mDefaultImportData.terrainSize = 0; - mDefaultImportData.worldSize = 0; - // by default we delete input data because we copy it, unless user - // passes us an ImportData where they explicitly don't want it copied - mDefaultImportData.deleteInputData = true; - } - //--------------------------------------------------------------------- - TerrainGroup::~TerrainGroup() - { - if(mAutoUpdateLod) - { - OGRE_DELETE mAutoUpdateLod; - mAutoUpdateLod = 0; - } - - // waiting for terrain preparing finished - while (getNumTerrainPrepareRequests() > 0) - { - OGRE_THREAD_SLEEP(50); - Root::getSingleton().getWorkQueue()->processMainThreadTasks(); - } - - removeAllTerrains(); - } - //--------------------------------------------------------------------- - void TerrainGroup::setOrigin(const Vector3& pos) - { - if (pos != mOrigin) - { - mOrigin = pos; - for (const auto& t : mTerrainSlots) - { - TerrainSlot* slot = t.second; - if (slot->instance) { - slot->instance->setPosition(getTerrainSlotPosition(slot->x, slot->y)); - } - } - } - } - //--------------------------------------------------------------------- - void TerrainGroup::setFilenameConvention(const String& prefix, const String& extension) - { - mFilenamePrefix = prefix; - mFilenameExtension = extension; - } - //--------------------------------------------------------------------- - void TerrainGroup::setFilenamePrefix(const String& prefix) - { - mFilenamePrefix = prefix; - } - //--------------------------------------------------------------------- - void TerrainGroup::setFilenameExtension(const String& extension) - { - mFilenameExtension = extension; - } - //--------------------------------------------------------------------- - void TerrainGroup::defineTerrain(long x, long y) - { - defineTerrain(x, y, generateFilename(x, y)); - } - //--------------------------------------------------------------------- - void TerrainGroup::defineTerrain(long x, long y, float constantHeight) - { - TerrainSlot* slot = getTerrainSlot(x, y, true); - - slot->def.useImportData(); - - // Copy all settings, but make sure our primary settings are immutable - *slot->def.importData = mDefaultImportData; - slot->def.importData->constantHeight = constantHeight; - slot->def.importData->terrainAlign = mAlignment; - slot->def.importData->terrainSize = mTerrainSize; - slot->def.importData->worldSize = mTerrainWorldSize; - } - //--------------------------------------------------------------------- - void TerrainGroup::defineTerrain(long x, long y, const Terrain::ImportData* importData) - { - TerrainSlot* slot = getTerrainSlot(x, y, true); - - slot->def.useImportData(); - - // Copy all settings, but make sure our primary settings are immutable - *slot->def.importData = *importData; - slot->def.importData->terrainAlign = mAlignment; - slot->def.importData->terrainSize = mTerrainSize; - slot->def.importData->worldSize = mTerrainWorldSize; - - } - //--------------------------------------------------------------------- - void TerrainGroup::defineTerrain(long x, long y, const Image* img, - const Terrain::LayerInstanceList* layers /*= 0*/) - { - TerrainSlot* slot = getTerrainSlot(x, y, true); - - freeTerrainSlotInstance(slot); - slot->def.useImportData(); - - *slot->def.importData = mDefaultImportData; - - // Copy all settings, but make sure our primary settings are immutable - // copy image - this will get deleted by importData - slot->def.importData->inputImage = OGRE_NEW Image(*img); - if (layers) - { - // copy (held by value) - slot->def.importData->layerList = *layers; - } - slot->def.importData->terrainAlign = mAlignment; - slot->def.importData->terrainSize = mTerrainSize; - slot->def.importData->worldSize = mTerrainWorldSize; - - } - //--------------------------------------------------------------------- - void TerrainGroup::defineTerrain(long x, long y, const float* pFloat /*= 0*/, - const Terrain::LayerInstanceList* layers /*= 0*/) - { - TerrainSlot* slot = getTerrainSlot(x, y, true); - - freeTerrainSlotInstance(slot); - slot->def.useImportData(); - - *slot->def.importData = mDefaultImportData; - - // Copy all settings, but make sure our primary settings are immutable - if(pFloat) - { - // copy data - this will get deleted by importData - slot->def.importData->inputFloat = OGRE_ALLOC_T(float, mTerrainSize*mTerrainSize, MEMCATEGORY_GEOMETRY); - memcpy(slot->def.importData->inputFloat, pFloat, sizeof(float) * mTerrainSize*mTerrainSize); - } - if (layers) - { - // copy (held by value) - slot->def.importData->layerList = *layers; - } - slot->def.importData->terrainAlign = mAlignment; - slot->def.importData->terrainSize = mTerrainSize; - slot->def.importData->worldSize = mTerrainWorldSize; - - } - //--------------------------------------------------------------------- - void TerrainGroup::defineTerrain(long x, long y, const String& filename) - { - TerrainSlot* slot = getTerrainSlot(x, y, true); - - freeTerrainSlotInstance(slot); - - slot->def.useFilename(); - slot->def.filename = filename; - - } - //--------------------------------------------------------------------- - void TerrainGroup::loadAllTerrains(bool synchronous /*= false*/) - { - // Just a straight iteration - for the numbers involved not worth - // keeping a loaded / unloaded list - for (const auto& t : mTerrainSlots) - loadTerrainImpl(t.second, synchronous); - } - //--------------------------------------------------------------------- - void TerrainGroup::saveAllTerrains(bool onlyIfModified, bool replaceFilenames) - { - for (const auto& s : mTerrainSlots) - { - TerrainSlot* slot = s.second; - if (slot->instance) - { - Terrain* t = slot->instance; - if (t->isLoaded() && - (!onlyIfModified || t->isModified())) - { - // Overwrite the file names? - if (replaceFilenames) - slot->def.filename = generateFilename(slot->x, slot->y); - - String filename; - if (!slot->def.filename.empty()) - filename = slot->def.filename; - else - filename = generateFilename(slot->x, slot->y); - - t->save(filename); - } - } - } - - } - //--------------------------------------------------------------------- - void TerrainGroup::loadTerrain(long x, long y, bool synchronous /*= false*/) - { - TerrainSlot* slot = getTerrainSlot(x, y, false); - if (slot) - { - loadTerrainImpl(slot, synchronous); - } - - } - - void TerrainGroup::loadLegacyTerrain(const String& cfgFilename, long x, long y, bool synchronous) - { - ConfigFile cfg; - cfg.loadFromResourceSystem(cfgFilename, mResourceGroup); - loadLegacyTerrain(cfg, x, y, synchronous); - } - - void TerrainGroup::loadLegacyTerrain(const ConfigFile& cfg, long x, long y, bool synchronous) - { - OgreAssert(cfg.getSetting("PageSource") == "Heightmap", "only heightmap PageSource supported"); - OgreAssert(cfg.getSetting("PageWorldZ") == cfg.getSetting("PageWorldX"), "terrain must be square"); - - mTerrainWorldSize = StringConverter::parseReal(cfg.getSetting("PageWorldX")); - mTerrainSize = StringConverter::parseInt(cfg.getSetting("PageSize")); - - mAlignment = Terrain::ALIGN_X_Z; - mOrigin = Vector3(mTerrainWorldSize / 2, 0, mTerrainWorldSize / 2); - - mDefaultImportData.inputScale = StringConverter::parseReal(cfg.getSetting("MaxHeight")); - mDefaultImportData.maxBatchSize = StringConverter::parseInt(cfg.getSetting("TileSize")); - mDefaultImportData.minBatchSize = (mDefaultImportData.maxBatchSize - 1)/2 + 1; - - // copy data that would have normally happened on construction - mDefaultImportData.terrainAlign = mAlignment; - mDefaultImportData.terrainSize = mTerrainSize; - mDefaultImportData.worldSize = mTerrainWorldSize; - - const String& worldTexName = cfg.getSetting("WorldTexture"); - if (!worldTexName.empty()) - { - const String& detailTexName = cfg.getSetting("DetailTexture"); - OgreAssert(!detailTexName.empty(), "DetailTexture must be given"); - Real detailTile = StringConverter::parseReal(cfg.getSetting("DetailTile"), 1); - mDefaultImportData.layerList.resize(1); - mDefaultImportData.layerList[0].worldSize = - (mTerrainWorldSize / mTerrainSize) * (mDefaultImportData.maxBatchSize / detailTile); - mDefaultImportData.layerList[0].textureNames.push_back(detailTexName); - } - - // Load terrain from heightmap - Image img; - img.load(cfg.getSetting("Heightmap.image"), mResourceGroup); - defineTerrain(x, y, &img); - - auto profile = dynamic_cast( - TerrainGlobalOptions::getSingleton().getDefaultMaterialGenerator()->getActiveProfile()); - - if(profile) - { - profile->setLayerSpecularMappingEnabled(false); - profile->setLayerNormalMappingEnabled(false); - profile->setLightmapEnabled(false); // baked into diffusemap - } - - TerrainSlot* slot = getTerrainSlot(x, y, false); - loadTerrainImpl(slot, synchronous); - - if (!worldTexName.empty()) - { - img.load(worldTexName, mResourceGroup); - slot->instance->setGlobalColourMapEnabled(true, img.getWidth()); - slot->instance->getGlobalColourMap()->loadImage(img); - } - } - - //--------------------------------------------------------------------- - void TerrainGroup::loadTerrainImpl(TerrainSlot* slot, bool synchronous) - { - if (!slot->instance && - (!slot->def.filename.empty() || slot->def.importData)) - { - // Allocate in main thread so no race conditions - slot->instance = OGRE_NEW Terrain(mSceneManager); - slot->instance->setResourceGroup(mResourceGroup); - // Use shared pool of buffers - slot->instance->setGpuBufferAllocator(&mBufferAllocator); - - std::pair ret = mTerrainPrepareRequests.emplace(slot, 0); - assert(ret.second == true); - - if(synchronous) - { - auto r = new WorkQueue::Request(0, 0, slot, 0, 0); - auto res = handleRequest(r, NULL); - handleResponse(res, NULL); - delete res; - return; - } - - Root::getSingleton().getWorkQueue()->addTask( - [this, slot]() - { - auto r = new WorkQueue::Request(0, 0, slot, 0, 0); - auto res = handleRequest(r, NULL); - Root::getSingleton().getWorkQueue()->addMainThreadTask( - [this, res]() - { - handleResponse(res, NULL); - delete res; - }); - }); - ret.first->second = 0; - } - } - //--------------------------------------------------------------------- - void TerrainGroup::increaseLodLevel(long x, long y, bool synchronous /* = false */) - { - TerrainSlot* slot = getTerrainSlot(x, y, false); - if (slot && slot->instance) - { - slot->instance->increaseLodLevel(synchronous); - } - } - void TerrainGroup::decreaseLodLevel(long x, long y) - { - TerrainSlot* slot = getTerrainSlot(x, y, false); - if (slot && slot->instance) - { - slot->instance->decreaseLodLevel(); - } - } - //--------------------------------------------------------------------- - void TerrainGroup::setAutoUpdateLod(TerrainAutoUpdateLod* updater) - { - if(mAutoUpdateLod) - OGRE_DELETE mAutoUpdateLod; - mAutoUpdateLod = updater; - } - //--------------------------------------------------------------------- - void TerrainGroup::autoUpdateLod(long x, long y, bool synchronous, const Any &data) - { - if(mAutoUpdateLod) - { - TerrainSlot* slot = getTerrainSlot(x, y, synchronous); - if (slot) - { - mAutoUpdateLod->autoUpdateLod(slot->instance, synchronous, data); - } - } - } - //--------------------------------------------------------------------- - void TerrainGroup::autoUpdateLodAll(bool synchronous, const Any &data) - { - if(mAutoUpdateLod) - { - for (const auto& s : mTerrainSlots) - { - TerrainSlot* slot = s.second; - mAutoUpdateLod->autoUpdateLod(slot->instance, synchronous, data); - } - } - } - //--------------------------------------------------------------------- - size_t TerrainGroup::getNumTerrainPrepareRequests() const - { - return mTerrainPrepareRequests.size(); - } - //--------------------------------------------------------------------- - void TerrainGroup::unloadTerrain(long x, long y) - { - freeTerrainSlotInstance(getTerrainSlot(x, y, false)); - } - //--------------------------------------------------------------------- - void TerrainGroup::removeTerrain(long x, long y) - { - uint32 key = packIndex(x, y); - TerrainSlotMap::iterator i = mTerrainSlots.find(key); - if (i != mTerrainSlots.end()) - { - OGRE_DELETE i->second; - mTerrainSlots.erase(i); - } - - } - //--------------------------------------------------------------------- - void TerrainGroup::removeAllTerrains() - { - for (const auto& s : mTerrainSlots) { - OGRE_DELETE s.second; - } - mTerrainSlots.clear(); - // Also clear buffer pools, if we're clearing completely may not be representative - mBufferAllocator.freeAllBuffers(); - } - //--------------------------------------------------------------------- - TerrainGroup::TerrainSlotDefinition* TerrainGroup::getTerrainDefinition(long x, long y) const - { - TerrainSlot* slot = getTerrainSlot(x, y); - if (slot) - return &slot->def; - else - return 0; - - } - //--------------------------------------------------------------------- - Terrain* TerrainGroup::getTerrain(long x, long y) const - { - TerrainSlot* slot = getTerrainSlot(x, y); - if (slot) - return slot->instance; - else - return 0; - } - //--------------------------------------------------------------------- - float TerrainGroup::getHeightAtWorldPosition(Real x, Real y, Real z, Terrain** ppTerrain /* = 0*/) - { - return getHeightAtWorldPosition(Vector3(x, y, z), ppTerrain); - - } - //--------------------------------------------------------------------- - float TerrainGroup::getHeightAtWorldPosition(const Vector3& pos, Terrain** ppTerrain /*= 0*/) - { - long x, y; - convertWorldPositionToTerrainSlot(pos, &x, &y); - TerrainSlot* slot = getTerrainSlot(x, y); - if (slot && slot->instance && slot->instance->isLoaded()) - { - if (ppTerrain) - *ppTerrain = slot->instance; - return slot->instance->getHeightAtWorldPosition(pos); - } - else - { - if (ppTerrain) - *ppTerrain = 0; - return 0; - } - } - //--------------------------------------------------------------------- - TerrainGroup::RayResult TerrainGroup::rayIntersects(const Ray& ray, Real distanceLimit /* = 0*/) const - { - long curr_x, curr_z; - convertWorldPositionToTerrainSlot(ray.getOrigin(), &curr_x, &curr_z); - TerrainSlot* slot = getTerrainSlot(curr_x, curr_z); - RayResult result(false, 0, Vector3::ZERO); - - Vector3 tmp, localRayDir, centreOrigin, offset; - // get the middle of the current tile - convertTerrainSlotToWorldPosition(curr_x, curr_z, ¢reOrigin); - offset = ray.getOrigin() - centreOrigin; - localRayDir = ray.getDirection(); - switch (getAlignment()) - { - case Terrain::ALIGN_X_Y: - std::swap(localRayDir.y, localRayDir.z); - std::swap(offset.y, offset.z); - break; - case Terrain::ALIGN_Y_Z: - // x = z, z = y, y = -x - tmp.x = localRayDir.z; - tmp.z = localRayDir.y; - tmp.y = -localRayDir.x; - localRayDir = tmp; - tmp.x = offset.z; - tmp.z = offset.y; - tmp.y = -offset.x; - offset = tmp; - break; - case Terrain::ALIGN_X_Z: - // already in X/Z but values increase in -Z - localRayDir.z = -localRayDir.z; - offset.z = -offset.z; - break; - } - // Normalise the offset based on the world size of a square, and rebase to the bottom left - offset /= mTerrainWorldSize; - offset += 0.5f; - // this is our counter moving away from the 'current' square - Vector3 inc(Math::Abs(localRayDir.x), Math::Abs(localRayDir.y), Math::Abs(localRayDir.z)); - long xdir = localRayDir.x > 0.0f ? 1 : -1; - long zdir = localRayDir.z > 0.0f ? 1 : -1; - - // We're always counting from 0 to 1 regardless of what direction we're heading - if (xdir < 0) - offset.x = 1.0f - offset.x; - if (zdir < 0) - offset.z = 1.0f - offset.z; - - // find next slot - bool keepSearching = true; - int numGaps = 0; - while(keepSearching) - { - if (Math::RealEqual(inc.x, 0.0f) && Math::RealEqual(inc.z, 0.0f)) - keepSearching = false; - - while ( (!slot || !slot->instance) && keepSearching) - { - ++numGaps; - /// if we don't find any filled slot in 6 traversals, give up - if (numGaps > 6) - { - keepSearching = false; - break; - } - // find next slot - Vector3 oldoffset = offset; - while (offset.x < 1.0f && offset.z < 1.0f) - offset += inc; - if (offset.x >= 1.0f && offset.z >= 1.0f) - { - // We crossed a corner, need to figure out which we passed first - Real diffz = 1.0f - oldoffset.z; - Real diffx = 1.0f - oldoffset.x; - Real distz = diffz / inc.z; - Real distx = diffx / inc.x; - if (distx < distz) - { - curr_x += xdir; - offset.x -= 1.0f; - } - else - { - curr_z += zdir; - offset.z -= 1.0f; - } - - } - else if (offset.x >= 1.0f) - { - curr_x += xdir; - offset.x -= 1.0f; - } - else if (offset.z >= 1.0f) - { - curr_z += zdir; - offset.z -= 1.0f; - } - if (distanceLimit) - { - Vector3 worldPos; - convertTerrainSlotToWorldPosition(curr_x, curr_z, &worldPos); - if (ray.getOrigin().distance(worldPos) > distanceLimit) - { - keepSearching = false; - break; - } - } - slot = getTerrainSlot(curr_x, curr_z); - } - if (slot && slot->instance) - { - numGaps = 0; - // don't cascade into neighbours - std::pair raypair = slot->instance->rayIntersects(ray, false, distanceLimit); - if (raypair.first) - { - keepSearching = false; - result.hit = true; - result.terrain = slot->instance; - result.position = raypair.second; - } - else - { - // not this one, trigger search for another slot - slot = 0; - } - } - - } - - - return result; - - } - //--------------------------------------------------------------------- - void TerrainGroup::boxIntersects(const AxisAlignedBox& box, TerrainList* resultList) const - { - resultList->clear(); - // Much simpler test - for (auto const& s : mTerrainSlots) - { - if (s.second->instance && box.intersects(s.second->instance->getWorldAABB())) - resultList->push_back(s.second->instance); - } - - } - //--------------------------------------------------------------------- - void TerrainGroup::sphereIntersects(const Sphere& sphere, TerrainList* resultList) const - { - resultList->clear(); - // Much simpler test - for (auto const& s : mTerrainSlots) - { - if (s.second->instance && sphere.intersects(s.second->instance->getWorldAABB())) - resultList->push_back(s.second->instance); - } - } - //--------------------------------------------------------------------- - void TerrainGroup::convertWorldPositionToTerrainSlot(const Vector3& pos, long *x, long *y) const - { - // 0,0 terrain is centred at the origin - Vector3 terrainPos; - // convert to standard xy base (z up), make relative to origin - Terrain::convertWorldToTerrainAxes(mAlignment, pos - mOrigin, &terrainPos); - - Real offset = mTerrainWorldSize * 0.5f; - terrainPos.x += offset; - terrainPos.y += offset; - - *x = static_cast(std::floor(terrainPos.x / mTerrainWorldSize)); - *y = static_cast(std::floor(terrainPos.y / mTerrainWorldSize)); - - - } - //--------------------------------------------------------------------- - void TerrainGroup::convertTerrainSlotToWorldPosition(long x, long y, Vector3* pos) const - { - Vector3 terrainPos(x * mTerrainWorldSize, y * mTerrainWorldSize, 0); - - Terrain::convertTerrainToWorldAxes(mAlignment, terrainPos, pos); - *pos += mOrigin; - - - } - //--------------------------------------------------------------------- - bool TerrainGroup::isDerivedDataUpdateInProgress() const - { - for (TerrainSlotMap::const_iterator i = mTerrainSlots.begin(); i != mTerrainSlots.end(); ++i) - { - if (i->second->instance && i->second->instance->isDerivedDataUpdateInProgress()) - return true; - } - return false; - } - //--------------------------------------------------------------------- - WorkQueue::Response* TerrainGroup::handleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ) - { - auto slot = any_cast(req->getData()); - - TerrainSlotDefinition& def = slot->def; - Terrain* t = slot->instance; - assert(t && "Terrain instance should have been constructed in the main thread"); - WorkQueue::Response* response = 0; - try - { - if (!def.filename.empty()) - t->prepare(def.filename); - else - { - assert(def.importData && "No import data or file name"); - t->prepare(*def.importData); - // if this worked, we can destroy the input data to save space - def.freeImportData(); - } - response = OGRE_NEW WorkQueue::Response(req, true, Any()); - } - catch (Exception& e) - { - // oops - response = OGRE_NEW WorkQueue::Response(req, false, Any(), - e.getFullDescription()); - } - - return response; - - - } - //--------------------------------------------------------------------- - void TerrainGroup::handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ) - { - // No response data, just request - auto slot = any_cast(res->getRequest()->getData()); - - TerrainPrepareRequestMap::iterator it = mTerrainPrepareRequests.find(slot); - - // This slot was scheduled to be deleted. - if (it == mTerrainPrepareRequests.end()) - { - freeTerrainSlotInstance(slot); - return; - } - else - { - mTerrainPrepareRequests.erase(it); - } - - if (res->succeeded()) - { - Terrain* terrain = slot->instance; - if (terrain) - { - // do final load now we've prepared in the background - // we must set the position - terrain->setPosition(getTerrainSlotPosition(slot->x, slot->y)); - - // the LOD will be auto-updated, then load lowest LOD - if(mAutoUpdateLod) - terrain->load(-1,false); - else - terrain->load(0,true); - - // hook up with neighbours - for (int i = -1; i <= 1; ++i) - { - for (int j = -1; j <= 1; ++j) - { - if (i != 0 || j != 0) - connectNeighbour(slot, i, j); - } - - } - } - } - else - { - // oh dear - LogManager::getSingleton().stream(LML_CRITICAL) << - "We failed to prepare the terrain at (" << slot->x << ", " << - slot->y <<") with the error '" << res->getMessages() << "'"; - freeTerrainSlotInstance(slot); - } - } - //--------------------------------------------------------------------- - void TerrainGroup::connectNeighbour(TerrainSlot* slot, long offsetx, long offsety) - { - TerrainSlot* neighbourSlot = getTerrainSlot(slot->x + offsetx, slot->y + offsety); - if (neighbourSlot && neighbourSlot->instance && neighbourSlot->instance->isLoaded()) - { - // reclaculate if imported - slot->instance->setNeighbour(Terrain::getNeighbourIndex(offsetx, offsety), neighbourSlot->instance, slot->def.importData != 0); - } - } - //--------------------------------------------------------------------- - uint32 TerrainGroup::packIndex(long x, long y) const - { - // Convert to signed 16-bit so sign bit is in bit 15 - int16 xs16 = static_cast(x); - int16 ys16 = static_cast(y); - - // convert to unsigned because we do not want to propagate sign bit to 32-bits - uint16 x16 = static_cast(xs16); - uint16 y16 = static_cast(ys16); - - uint32 key = 0; - key = (x16 << 16) | y16; - - return key; - } - //--------------------------------------------------------------------- - void TerrainGroup::unpackIndex(uint32 key, long *x, long *y) - { - // inverse of packIndex - // unsigned versions - uint16 y16 = static_cast(key & 0xFFFF); - uint16 x16 = static_cast((key >> 16) & 0xFFFF); - - *x = static_cast(x16); - *y = static_cast(y16); - - } - - //--------------------------------------------------------------------- - String TerrainGroup::generateFilename(long x, long y) const - { - StringStream str; - str << mFilenamePrefix << "_" << - std::setw(8) << std::setfill('0') << std::hex << packIndex(x, y) << - "." << mFilenameExtension; - return str.str(); - } - //--------------------------------------------------------------------- - Vector3 TerrainGroup::getTerrainSlotPosition(long x, long y) - { - Vector3 pos; - convertTerrainSlotToWorldPosition(x, y, &pos); - return pos; - } - //--------------------------------------------------------------------- - TerrainGroup::TerrainSlot* TerrainGroup::getTerrainSlot(long x, long y, bool createIfMissing) - { - uint32 key = packIndex(x, y); - TerrainSlotMap::iterator i = mTerrainSlots.find(key); - if (i != mTerrainSlots.end()) - return i->second; - else if (createIfMissing) - { - TerrainSlot* slot = OGRE_NEW TerrainSlot(x, y); - mTerrainSlots[key] = slot; - return slot; - } - return 0; - } - //--------------------------------------------------------------------- - TerrainGroup::TerrainSlot* TerrainGroup::getTerrainSlot(long x, long y) const - { - uint32 key = packIndex(x, y); - TerrainSlotMap::const_iterator i = mTerrainSlots.find(key); - if (i != mTerrainSlots.end()) - return i->second; - else - return 0; - - } - //--------------------------------------------------------------------- - void TerrainGroup::freeTerrainSlotInstance(TerrainSlot* slot) - { - if (!slot) - return; - - TerrainPrepareRequestMap::iterator it = mTerrainPrepareRequests.find(slot); - - // Terrain was in load request so we need to schedule the deletion see handleResponse(). - if (it != mTerrainPrepareRequests.end()) - { - mTerrainPrepareRequests.erase(it); - } - else - { - slot->freeInstance(); - } - } - //--------------------------------------------------------------------- - void TerrainGroup::freeTemporaryResources() - { - for (const auto& s : mTerrainSlots) - { - if (s.second->instance) - s.second->instance->freeTemporaryResources(); - } - - } - //--------------------------------------------------------------------- - void TerrainGroup::update(bool synchronous) - { - for (const auto& s : mTerrainSlots) - { - if (s.second->instance) - s.second->instance->update(); - } - - } - //--------------------------------------------------------------------- - void TerrainGroup::updateGeometry() - { - for (const auto& s : mTerrainSlots) - { - if (s.second->instance) - s.second->instance->updateGeometry(); - } - } - //--------------------------------------------------------------------- - void TerrainGroup::updateDerivedData(bool synchronous, uint8 typeMask) - { - for (const auto& s : mTerrainSlots) - { - if (s.second->instance) - s.second->instance->updateDerivedData(); - } - } - //--------------------------------------------------------------------- - TerrainGroup::TerrainIterator TerrainGroup::getTerrainIterator() - { - return TerrainIterator(mTerrainSlots.begin(), mTerrainSlots.end()); - } - //--------------------------------------------------------------------- - TerrainGroup::ConstTerrainIterator TerrainGroup::getTerrainIterator() const - { - return ConstTerrainIterator(mTerrainSlots.begin(), mTerrainSlots.end()); - } - //--------------------------------------------------------------------- - void TerrainGroup::saveGroupDefinition(const String& filename) - { - DataStreamPtr stream = Root::getSingleton().createFileStream(filename, - getResourceGroup(), true); - StreamSerialiser ser(stream); - saveGroupDefinition(ser); - } - //--------------------------------------------------------------------- - void TerrainGroup::saveGroupDefinition(StreamSerialiser& ser) - { - ser.writeChunkBegin(CHUNK_ID, CHUNK_VERSION); - // Base details - ser.write(&mAlignment); - ser.write(&mTerrainSize); - ser.write(&mTerrainWorldSize); - ser.write(&mFilenamePrefix); - ser.write(&mFilenameExtension); - ser.write(&mResourceGroup); - ser.write(&mOrigin); - - uint32 autoUpdateLodStrategyId = (mAutoUpdateLod) ? mAutoUpdateLod->getStrategyId() : 0; - ser.write(&autoUpdateLodStrategyId); - - // Default import settings (those not duplicated by the above) - ser.write(&mDefaultImportData.constantHeight); - ser.write(&mDefaultImportData.inputBias); - ser.write(&mDefaultImportData.inputScale); - ser.write(&mDefaultImportData.maxBatchSize); - ser.write(&mDefaultImportData.minBatchSize); - Terrain::writeLayerDeclaration(mDefaultImportData.layerDeclaration, ser); - Terrain::writeLayerInstanceList(mDefaultImportData.layerList, ser); - - - ser.writeChunkEnd(CHUNK_ID); - } - //--------------------------------------------------------------------- - void TerrainGroup::loadGroupDefinition(const String& filename) - { - DataStreamPtr stream = Root::getSingleton().openFileStream(filename, - getResourceGroup()); - StreamSerialiser ser(stream); - loadGroupDefinition(ser); - } - //--------------------------------------------------------------------- - void TerrainGroup::loadGroupDefinition(StreamSerialiser& ser) - { - if (!ser.readChunkBegin(CHUNK_ID, CHUNK_VERSION)) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Stream does not contain TerrainGroup data"); - - // Base details - ser.read(&mAlignment); - ser.read(&mTerrainSize); - ser.read(&mTerrainWorldSize); - ser.read(&mFilenamePrefix); - ser.read(&mFilenameExtension); - ser.read(&mResourceGroup); - ser.read(&mOrigin); - uint32 autoUpdateLodStrategyId; - ser.read(&autoUpdateLodStrategyId); - mAutoUpdateLod = TerrainAutoUpdateLodFactory::getAutoUpdateLod( autoUpdateLodStrategyId ); - - // Default import settings (those not duplicated by the above) - ser.read(&mDefaultImportData.constantHeight); - ser.read(&mDefaultImportData.inputBias); - ser.read(&mDefaultImportData.inputScale); - ser.read(&mDefaultImportData.maxBatchSize); - ser.read(&mDefaultImportData.minBatchSize); - Terrain::readLayerDeclaration(ser, mDefaultImportData.layerDeclaration); - Terrain::readLayerInstanceList(ser, mDefaultImportData.layerDeclaration.size(), - mDefaultImportData.layerList); - - // copy data that would have normally happened on construction - mDefaultImportData.terrainAlign = mAlignment; - mDefaultImportData.terrainSize = mTerrainSize; - mDefaultImportData.worldSize = mTerrainWorldSize; - mDefaultImportData.deleteInputData = true; - - ser.readChunkEnd(CHUNK_ID); - - - } - //--------------------------------------------------------------------- - void TerrainGroup::setTerrainWorldSize(Real newWorldSize) - { - if (newWorldSize != mTerrainWorldSize) - { - mTerrainWorldSize = newWorldSize; - for (const auto& s : mTerrainSlots) - { - if (s.second->instance) - { - s.second->instance->setWorldSize(newWorldSize); - s.second->instance->setPosition(getTerrainSlotPosition(s.second->x, s.second->y)); - } - } - } - } - //--------------------------------------------------------------------- - void TerrainGroup::setTerrainSize(uint16 newTerrainSize) - { - if (newTerrainSize != mTerrainSize) - { - mTerrainSize = newTerrainSize; - for (const auto& s : mTerrainSlots) - { - if (s.second->instance) - s.second->instance->setSize(newTerrainSize); - } - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - TerrainGroup::TerrainSlotDefinition::~TerrainSlotDefinition() - { - freeImportData(); - } - //--------------------------------------------------------------------- - void TerrainGroup::TerrainSlotDefinition::freeImportData() - { - OGRE_DELETE_T(importData, ImportData, MEMCATEGORY_GEOMETRY); - importData = 0; - } - //--------------------------------------------------------------------- - void TerrainGroup::TerrainSlotDefinition::useImportData() - { - filename.clear(); - freeImportData(); - importData = OGRE_NEW_T(Terrain::ImportData, MEMCATEGORY_GEOMETRY); - // we're going to own all the data in the def - importData->deleteInputData = true; - - } - //--------------------------------------------------------------------- - void TerrainGroup::TerrainSlotDefinition::useFilename() - { - freeImportData(); - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - TerrainGroup::TerrainSlot::~TerrainSlot() - { - freeInstance(); - } - //--------------------------------------------------------------------- - void TerrainGroup::TerrainSlot::freeInstance() - { - OGRE_DELETE instance; - instance = 0; - } -} diff --git a/Components/Terrain/src/OgreTerrainLayerBlendMap.cpp b/Components/Terrain/src/OgreTerrainLayerBlendMap.cpp deleted file mode 100644 index 7121007a608..00000000000 --- a/Components/Terrain/src/OgreTerrainLayerBlendMap.cpp +++ /dev/null @@ -1,258 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreTerrainLayerBlendMap.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreTerrain.h" -#include "OgreImage.h" - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -// we do lots of conversions here, casting them all is tedious & cluttered, we know what we're doing -# pragma warning (disable : 4244) -#endif - -namespace Ogre -{ - //--------------------------------------------------------------------- - TerrainLayerBlendMap::TerrainLayerBlendMap(Terrain* parent, uint8 layerIndex, - HardwarePixelBuffer* buf) - : mParent(parent) - , mLayerIdx(layerIndex) - , mChannel((layerIndex-1) % 4) - , mDirty(false) - , mBuffer(buf) - { - mData.create(PF_FLOAT32_R, mBuffer->getWidth(), mBuffer->getHeight()); - - // we know which of RGBA we need to look at, now find it in the format - // because we can't guarantee what precise format the RS gives us - unsigned char rgbaShift[4]; - PixelFormat fmt = mBuffer->getFormat(); - PixelUtil::getBitShifts(fmt, rgbaShift); - mChannelOffset = rgbaShift[mChannel] / 8; // /8 to convert to bytes -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - // invert (dealing bytewise) - mChannelOffset = PixelUtil::getNumElemBytes(fmt) - mChannelOffset - 1; -#endif - download(); - - } - //--------------------------------------------------------------------- - TerrainLayerBlendMap::~TerrainLayerBlendMap() {} - //--------------------------------------------------------------------- - void TerrainLayerBlendMap::download() - { - float* pDst = mData.getData(); - // Download data - Box box(0, 0, mBuffer->getWidth(), mBuffer->getHeight()); - uint8* pSrc = mBuffer->lock(box, HardwareBuffer::HBL_READ_ONLY).data; - pSrc += mChannelOffset; - size_t srcInc = PixelUtil::getNumElemBytes(mBuffer->getFormat()); - for (size_t y = box.top; y < box.bottom; ++y) - { - for (size_t x = box.left; x < box.right; ++x) - { - *pDst++ = static_cast(*pSrc) / 255.0f; - pSrc += srcInc; - } - } - mBuffer->unlock(); - - } - //--------------------------------------------------------------------- - void TerrainLayerBlendMap::convertWorldToUVSpace(const Vector3& worldPos, Real *outX, Real* outY) - { - Vector3 terrainSpace; - mParent->getTerrainPosition(worldPos, &terrainSpace); - *outX = terrainSpace.x; - *outY = 1.0f - terrainSpace.y; - } - //--------------------------------------------------------------------- - void TerrainLayerBlendMap::convertUVToWorldSpace(Real x, Real y, Vector3* outWorldPos) - { - mParent->getPosition(x, 1.0f - y, 0, outWorldPos); - } - //--------------------------------------------------------------------- - void TerrainLayerBlendMap::convertUVToImageSpace(Real x, Real y, size_t* outX, size_t* outY) - { - *outX = (unsigned long)(x * (mBuffer->getWidth() - 1)); - *outY = (unsigned long)(y * (mBuffer->getHeight() - 1)); - } - //--------------------------------------------------------------------- - void TerrainLayerBlendMap::convertImageToUVSpace(size_t x, size_t y, Real* outX, Real* outY) - { - *outX = x / (Real)(mBuffer->getWidth() - 1); - *outY = y / (Real)(mBuffer->getHeight() - 1); - } - //--------------------------------------------------------------------- - void TerrainLayerBlendMap::convertImageToTerrainSpace(size_t x, size_t y, Real* outX, Real* outY) - { - convertImageToUVSpace(x, y, outX, outY); - *outY = 1.0f - *outY; - } - //--------------------------------------------------------------------- - void TerrainLayerBlendMap::convertTerrainToImageSpace(Real x, Real y, size_t* outX, size_t* outY) - { - convertUVToImageSpace(x, 1.0f - y, outX, outY); - } - //--------------------------------------------------------------------- - float TerrainLayerBlendMap::getBlendValue(uint32 x, uint32 y) - { - return *mData.getData(x, y); - } - //--------------------------------------------------------------------- - void TerrainLayerBlendMap::setBlendValue(uint32 x, uint32 y, float val) - { - *mData.getData(x, y) = val; - dirtyRect(Rect(x, y, x+1, y+1)); - - } - //--------------------------------------------------------------------- - float* TerrainLayerBlendMap::getBlendPointer() - { - return mData.getData(); - } - //--------------------------------------------------------------------- - void TerrainLayerBlendMap::dirty() - { - Rect rect; - rect.top = 0; rect.bottom = mBuffer->getHeight(); - rect.left = 0; rect.right = mBuffer->getWidth(); - dirtyRect(rect); - - } - //--------------------------------------------------------------------- - void TerrainLayerBlendMap::dirtyRect(const Rect& rect) - { - if (mDirty) - { - mDirtyBox.left = std::min(mDirtyBox.left, static_cast(rect.left)); - mDirtyBox.top = std::min(mDirtyBox.top, static_cast(rect.top)); - mDirtyBox.right = std::max(mDirtyBox.right, static_cast(rect.right)); - mDirtyBox.bottom = std::max(mDirtyBox.bottom, static_cast(rect.bottom)); - } - else - { - mDirtyBox = Box(rect); - mDirty = true; - } - } - //--------------------------------------------------------------------- - void TerrainLayerBlendMap::update() - { - if (mData.getData() && mDirty) - { - // Upload data - float* pSrcBase = mData.getData(mDirtyBox.left, mDirtyBox.top); - uint8* pDstBase = mBuffer->lock(mDirtyBox, HardwarePixelBuffer::HBL_NORMAL).data; - pDstBase += mChannelOffset; - size_t dstInc = PixelUtil::getNumElemBytes(mBuffer->getFormat()); - for (size_t y = 0; y < mDirtyBox.getHeight(); ++y) - { - float* pSrc = pSrcBase + y * mBuffer->getWidth(); - uint8* pDst = pDstBase + y * mBuffer->getWidth() * dstInc; - for (size_t x = 0; x < mDirtyBox.getWidth(); ++x) - { - *pDst = static_cast(*pSrc++ * 255); - pDst += dstInc; - } - } - mBuffer->unlock(); - - mDirty = false; - - // make sure composite map is updated - // mDirtyBox is in image space, convert to terrain units - Rect compositeMapRect; - float blendToTerrain = (float)mParent->getSize() / (float)mBuffer->getWidth(); - compositeMapRect.left = (mDirtyBox.left * blendToTerrain); - compositeMapRect.right = (mDirtyBox.right * blendToTerrain + 1); - compositeMapRect.top = ((mBuffer->getHeight() - mDirtyBox.bottom) * blendToTerrain); - compositeMapRect.bottom = ((mBuffer->getHeight() - mDirtyBox.top) * blendToTerrain + 1); - mParent->_dirtyCompositeMapRect(compositeMapRect); - mParent->updateCompositeMapWithDelay(); - - } - } - //--------------------------------------------------------------------- - void TerrainLayerBlendMap::blit(const PixelBox &src, const Box &dstBox) - { - const PixelBox* srcBox = &src; - - if (srcBox->getWidth() != dstBox.getWidth() || srcBox->getHeight() != dstBox.getHeight()) - { - // we need to rescale src to dst size first (also confvert format) - void* tmpData = OGRE_MALLOC(dstBox.getWidth() * dstBox.getHeight(), MEMCATEGORY_GENERAL); - srcBox = OGRE_NEW PixelBox(dstBox.getWidth(), dstBox.getHeight(), 1, PF_L8, tmpData); - - Image::scale(src, *srcBox); - } - - // pixel conversion - PixelBox dstMemBox = mData.getPixelBox().getSubVolume(dstBox); - PixelUtil::bulkPixelConversion(*srcBox, dstMemBox); - - if (srcBox != &src) - { - // free temp - OGRE_FREE(srcBox->data, MEMCATEGORY_GENERAL); - OGRE_DELETE srcBox; - srcBox = 0; - } - - Rect dRect(dstBox.left, dstBox.top, dstBox.right, dstBox.bottom); - dirtyRect(dRect); - - } - //--------------------------------------------------------------------- - void TerrainLayerBlendMap::blit(const PixelBox &src) - { - blit(src, mData.getPixelBox()); - } - //--------------------------------------------------------------------- - void TerrainLayerBlendMap::loadImage(const Image& img) - { - blit(img.getPixelBox()); - } - //--------------------------------------------------------------------- - void TerrainLayerBlendMap::loadImage(DataStreamPtr& stream, const String& ext) - { - Image img; - img.load(stream, ext); - loadImage(img); - } - //--------------------------------------------------------------------- - void TerrainLayerBlendMap::loadImage(const String& filename, const String& groupName) - { - Image img; - img.load(filename, groupName); - loadImage(img); - } - - -} - diff --git a/Components/Terrain/src/OgreTerrainLodManager.cpp b/Components/Terrain/src/OgreTerrainLodManager.cpp deleted file mode 100644 index ed9cfaf5950..00000000000 --- a/Components/Terrain/src/OgreTerrainLodManager.cpp +++ /dev/null @@ -1,401 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreRoot.h" -#include "OgreTerrainQuadTreeNode.h" -#include "OgreTerrainLodManager.h" -#include "OgreStreamSerialiser.h" -#include "OgreLogManager.h" -#include "OgreTerrain.h" - -namespace Ogre -{ - const uint32 TerrainLodManager::TERRAINLODDATA_CHUNK_ID = StreamSerialiser::makeIdentifier("TLDA"); - const uint16 TerrainLodManager::TERRAINLODDATA_CHUNK_VERSION = 1; - - TerrainLodManager::TerrainLodManager(Terrain* t, DataStreamPtr& stream) - : mTerrain(t) - { - init(); - mDataStream = stream; - mStreamOffset = !mDataStream ? 0 : mDataStream->tell(); - } - - TerrainLodManager::TerrainLodManager(Terrain* t, const String& filename) - : mTerrain(t), mStreamOffset(0) - { - init(); - open(filename); - } - - void TerrainLodManager::open(const String& filename) - { - if(!filename.empty()) - mDataStream = Root::getSingleton().openFileStream(filename, mTerrain->_getDerivedResourceGroup()); - } - - void TerrainLodManager::close() - { - mDataStream.reset(); - } - - bool TerrainLodManager::isOpen() const - { - return mDataStream.get() != 0; - } - - void TerrainLodManager::init() - { - mHighestLodPrepared = -1; - mHighestLodLoaded = -1; - mTargetLodLevel = -1; - mIncreaseLodLevelInProgress = false; - mLastRequestSynchronous = false; - mLodInfoTable = 0; - } - - TerrainLodManager::~TerrainLodManager() - { - waitForDerivedProcesses(); - - if(mLodInfoTable) - OGRE_FREE(mLodInfoTable,MEMCATEGORY_GENERAL); - } - - WorkQueue::Response* TerrainLodManager::handleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ) - { - LoadLodRequest lreq = any_cast(req->getData()); - // read data from file into temporary height & delta buffer - try { - if(lreq.currentPreparedLod>lreq.requestedLod) - readLodData(lreq.currentPreparedLod-1, lreq.requestedLod); - } catch (Exception& e) { - return OGRE_NEW WorkQueue::Response(req, false, Any(), e.getFullDescription()); - } - - int lastTreeStart = -1; - for( int level=lreq.currentLoadedLod-1; level>=lreq.requestedLod; --level ) - { - LodInfo& lodinfo = getLodInfo(level); - // skip re-assign - if(lastTreeStart != (int)lodinfo.treeStart) - { - mTerrain->getQuadTree()->assignVertexData(lodinfo.treeStart, lodinfo.treeEnd, - lodinfo.resolution, lodinfo.size); - lastTreeStart = lodinfo.treeStart; - } - } - return OGRE_NEW WorkQueue::Response(req, true, Any()); - } - - void TerrainLodManager::handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ) - { - const WorkQueue::Request* req = res->getRequest(); - // No response data, just request - LoadLodRequest lreq = any_cast(req->getData()); - - mIncreaseLodLevelInProgress = false; - - if (res->succeeded()) - { - // no others update LOD status - if(lreq.currentPreparedLod == mHighestLodPrepared && lreq.currentLoadedLod == mHighestLodLoaded ) - { - if( lreq.requestedLod < mHighestLodPrepared ) - mHighestLodPrepared = lreq.requestedLod; - - int lastTreeStart = -1; - for( int level = mHighestLodLoaded-1; level>=lreq.requestedLod && level>=mTargetLodLevel; --level ) - { - LodInfo& lodinfo = getLodInfo(level); - // skip re-load - if(lastTreeStart != (int)lodinfo.treeStart) - { - mTerrain->getQuadTree()->load(lodinfo.treeStart, lodinfo.treeEnd); - lastTreeStart = lodinfo.treeStart; - } - --mHighestLodLoaded; - } - } - - // has streamed in new data, should update terrain - if(lreq.currentPreparedLod>lreq.requestedLod) - { - mTerrain->dirty(); - mTerrain->updateGeometryWithoutNotifyNeighbours(); - } - - // there are new requests - if(mHighestLodLoaded != mTargetLodLevel) - updateToLodLevel(mTargetLodLevel,mLastRequestSynchronous); - } - else - { - LogManager::getSingleton().stream(LML_CRITICAL) << "Failed to prepare and load terrain LOD: " << res->getMessages(); - } - } - void TerrainLodManager::buildLodInfoTable() - { - uint16 numLodLevels = mTerrain->getNumLodLevels(); - mLodInfoTable = OGRE_ALLOC_T(LodInfo, numLodLevels, MEMCATEGORY_GENERAL); - - uint16 size = mTerrain->getSize(); - uint16 depth = mTerrain->mTreeDepth; - uint16 prevdepth = depth; - uint16 last = 0; - uint16 currresolution = size; - uint16 bakedresolution = size; - uint16 targetSplits = (bakedresolution - 1) / (Terrain::TERRAIN_MAX_BATCH_SIZE - 1); - - int *lodDepth = OGRE_ALLOC_T(int, numLodLevels, MEMCATEGORY_GENERAL); - for(int level=0; levelgetNumLodLevelsPerLeaf()) ? depth-1 : numLodLevels-level-1; - - while(depth-- && targetSplits) - { - uint splits = 1 << depth; - if (splits == targetSplits) - { - for(uint level=0; level= depth && lodDepth[level] < prevdepth) - { - mLodInfoTable[level].treeStart = depth; - mLodInfoTable[level].treeEnd = prevdepth; - mLodInfoTable[level].isLast = level == last+prevdepth-depth-static_cast(1); - mLodInfoTable[level].resolution = bakedresolution; - mLodInfoTable[level].size = ((bakedresolution-1) / splits) + 1; - // this lod info has been filled - lodDepth[level] = -1; - } - } - // next set to look for - bakedresolution = ((currresolution - 1) >> 1) + 1; - targetSplits = (bakedresolution - 1) / (Terrain::TERRAIN_MAX_BATCH_SIZE - 1); - prevdepth = depth; - } - currresolution = ((currresolution - 1) >> 1) + 1; - last++; - } - for(int level=0; level=0 && lodDepth[level]<=prevdepth) - { - mLodInfoTable[level].treeStart = 0; - mLodInfoTable[level].treeEnd = 1; - mLodInfoTable[level].isLast = level == last+prevdepth-depth-1; - mLodInfoTable[level].resolution = bakedresolution; - mLodInfoTable[level].size = bakedresolution; - } - } - OGRE_FREE(lodDepth,MEMCATEGORY_GENERAL); - } - - // data are reorganized from lowest lod level(mNumLodLevels-1) to highest(0) - void TerrainLodManager::separateData(float* data, uint16 size, uint16 numLodLevels, LodsData& lods) - { - lods.resize(numLodLevels); - for (int level = numLodLevels - 1; level >= 0; level--) - { - unsigned int inc = 1 << level; - unsigned int prev = 1 << (level + 1); - - for (uint16 y = 0; y < size; y += inc) - { - for (uint16 x = 0; x < size-1; x += inc) - if ((level == numLodLevels - 1) || ((x % prev != 0) || (y % prev != 0))) - lods[level].push_back( data[y*size + x] ); - if ((level == numLodLevels -1) || (y % prev) != 0) - lods[level].push_back( data[y*size + size-1] ); - if (y+inc > size) - break; - } - } - } - //--------------------------------------------------------------------- - void TerrainLodManager::updateToLodLevel(int lodLevel, bool synchronous /* = false */) - { - //init - if(mHighestLodPrepared==-1) - mHighestLodPrepared = mTerrain->getNumLodLevels(); - if(mHighestLodLoaded==-1) - mHighestLodLoaded = mTerrain->getNumLodLevels(); - - lodLevel = mTerrain->getPositiveLodLevel(lodLevel); - - mTargetLodLevel = lodLevel; - mLastRequestSynchronous = synchronous; - - // need loading - if(mTargetLodLeveladdTask([this, r]() { - auto res = handleRequest(r, NULL); - Root::getSingleton().getWorkQueue()->addMainThreadTask([this, res]() { - handleResponse(res, NULL); - delete res; - }); - }); - } - } - else if(synchronous) - waitForDerivedProcesses(); - } - // need unloading - else if(mTargetLodLevel>mHighestLodLoaded) - { - for( int level=mHighestLodLoaded; levelgetQuadTree()->unload(lod.treeStart, lod.treeEnd); - mHighestLodLoaded = level+1; - } - } - } - } - - // save each LOD level separately compressed so seek is possible - void TerrainLodManager::saveLodData(StreamSerialiser& stream, Terrain* terrain) - { - uint16 numLodLevels = terrain->getNumLodLevels(); - - LodsData lods; - separateData(terrain->mHeightData, terrain->getSize(), numLodLevels, lods); - separateData(terrain->mDeltaData, terrain->getSize(), numLodLevels, lods); - - for (int level = numLodLevels - 1; level >=0; level--) - { - stream.writeChunkBegin(TERRAINLODDATA_CHUNK_ID, TERRAINLODDATA_CHUNK_VERSION); - stream.startDeflate(); - stream.write(&(lods[level][0]), lods[level].size()); - stream.stopDeflate(); - stream.writeChunkEnd(TERRAINLODDATA_CHUNK_ID); - } - } - - void TerrainLodManager::readLodData(uint16 lowerLodBound, uint16 higherLodBound) - { - if(!mDataStream) // No file to read from - return; - - uint16 numLodLevels = mTerrain->getNumLodLevels(); - mDataStream->seek(mStreamOffset); - StreamSerialiser stream(mDataStream); - - const StreamSerialiser::Chunk *mainChunk = stream.readChunkBegin(Terrain::TERRAIN_CHUNK_ID, Terrain::TERRAIN_CHUNK_VERSION); - - if(mainChunk->version > 1) - { - // skip the general information - stream.readChunkBegin(Terrain::TERRAINGENERALINFO_CHUNK_ID, Terrain::TERRAINGENERALINFO_CHUNK_VERSION); - stream.readChunkEnd(Terrain::TERRAINGENERALINFO_CHUNK_ID); - - // skip the previous lod data - for(int skip=numLodLevels-1-lowerLodBound; skip>0; skip--) - { - stream.readChunkBegin(TERRAINLODDATA_CHUNK_ID, TERRAINLODDATA_CHUNK_VERSION); - stream.readChunkEnd(TERRAINLODDATA_CHUNK_ID); - } - - // uncompress - uint maxSize = 2 * mTerrain->getGeoDataSizeAtLod(higherLodBound); - float *lodData = OGRE_ALLOC_T(float, maxSize, MEMCATEGORY_GENERAL); - - for(int level=lowerLodBound; level>=higherLodBound; level-- ) - { - // both height data and delta data - uint dataSize = 2 * mTerrain->getGeoDataSizeAtLod(level); - - // reach and read the target lod data - const StreamSerialiser::Chunk *c = stream.readChunkBegin(TERRAINLODDATA_CHUNK_ID, - TERRAINLODDATA_CHUNK_VERSION); - stream.startDeflate(c->length); - stream.read(lodData, dataSize); - stream.stopDeflate(); - stream.readChunkEnd(TERRAINLODDATA_CHUNK_ID); - - fillBufferAtLod(level, lodData, dataSize); - } - stream.readChunkEnd(Terrain::TERRAIN_CHUNK_ID); - - OGRE_FREE(lodData, MEMCATEGORY_GENERAL); - } - } - void TerrainLodManager::fillBufferAtLod(uint lodLevel, const float* data, uint dataSize ) - { - unsigned int inc = 1 << lodLevel; - unsigned int prev = 1 << (lodLevel + 1); - uint16 numLodLevels = mTerrain->getNumLodLevels(); - uint16 size = mTerrain->getSize(); - - const float* heightDataPtr = data; - const float* deltaDataPtr = data+dataSize/2; - - for (uint16 y = 0; y < size; y += inc) - { - for (uint16 x = 0; x < size-1; x += inc) - if ((lodLevel == numLodLevels - static_cast(1)) || (x % prev) || (y % prev)) - { - mTerrain->mHeightData[y*size + x] = *(heightDataPtr++); - mTerrain->mDeltaData[y*size + x] = *(deltaDataPtr++); - } - if ((lodLevel == numLodLevels - static_cast(1)) || (y % prev)) - { - mTerrain->mHeightData[y*size + size-1] = *(heightDataPtr++); - mTerrain->mDeltaData[y*size + size-1] = *(deltaDataPtr++); - } - if (y+inc > size) - break; - } - } - void TerrainLodManager::waitForDerivedProcesses() - { - while (mIncreaseLodLevelInProgress) - { - // we need to wait for this to finish - OGRE_THREAD_SLEEP(50); - Root::getSingleton().getWorkQueue()->processMainThreadTasks(); - } - } -} diff --git a/Components/Terrain/src/OgreTerrainMaterialGenerator.cpp b/Components/Terrain/src/OgreTerrainMaterialGenerator.cpp deleted file mode 100644 index 1aad8b5ef00..00000000000 --- a/Components/Terrain/src/OgreTerrainMaterialGenerator.cpp +++ /dev/null @@ -1,192 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreTerrainMaterialGeneratorA.h" -#include "OgreRoot.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreTextureManager.h" -#include "OgreTexture.h" -#include "OgreTerrain.h" -#include "OgreManualObject.h" -#include "OgreCamera.h" -#include "OgreViewport.h" -#include "OgreRenderSystem.h" -#include "OgreRenderTarget.h" -#include "OgreRenderTexture.h" -#include "OgreSceneNode.h" -#include "OgreRectangle2D.h" - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -// we do lots of conversions here, casting them all is tedious & cluttered, we know what we're doing -# pragma warning (disable : 4244) -#endif - - -namespace Ogre -{ - //--------------------------------------------------------------------- - TerrainMaterialGenerator::TerrainMaterialGenerator() - : mChangeCounter(0) - , mDebugLevel(0) - , mCompositeMapSM(0) - , mCompositeMapCam(0) - , mCompositeMapRTT(0) - , mCompositeMapPlane(0) - , mCompositeMapLight(0) - { - - } - //--------------------------------------------------------------------- - TerrainMaterialGenerator::~TerrainMaterialGenerator() - { - if (mCompositeMapRTT && TextureManager::getSingletonPtr()) - { - TextureManager::getSingleton().remove(mCompositeMapRTT->getHandle()); - mCompositeMapRTT = 0; - } - if (mCompositeMapSM && Root::getSingletonPtr()) - { - // will also delete cam and objects etc - Root::getSingleton().destroySceneManager(mCompositeMapSM); - mCompositeMapSM = 0; - mCompositeMapCam = 0; - mCompositeMapLight = 0; - mLightNode = 0; - } - } - //--------------------------------------------------------------------- - void TerrainMaterialGenerator::_renderCompositeMap(size_t size, - const Rect& rect, const MaterialPtr& mat, const TexturePtr& destCompositeMap) - { - if (!mCompositeMapSM) - { - // dedicated SceneManager - mCompositeMapSM = Root::getSingleton().createSceneManager(); - mCompositeMapCam = mCompositeMapSM->createCamera("cam"); - mCompositeMapSM->getRootSceneNode()->attachObject(mCompositeMapCam); - mCompositeMapCam->setProjectionType(PT_ORTHOGRAPHIC); - mCompositeMapCam->setNearClipDistance(0.5); - mCompositeMapCam->setFarClipDistance(1.5); - mCompositeMapCam->setOrthoWindow(2, 2); - - // Just in case material relies on light auto params - mCompositeMapLight = mCompositeMapSM->createLight(); - mCompositeMapLight->setType(Light::LT_DIRECTIONAL); - mLightNode = mCompositeMapSM->getRootSceneNode()->createChildSceneNode(); - mLightNode->attachObject(mCompositeMapLight); - - RenderSystem* rSys = Root::getSingleton().getRenderSystem(); - Real hOffset = rSys->getHorizontalTexelOffset() / (Real)size; - Real vOffset = rSys->getVerticalTexelOffset() / (Real)size; - - - // set up scene - mCompositeMapPlane = mCompositeMapSM->createScreenSpaceRect(true); - mCompositeMapPlane->setUVs({0 - hOffset, 0 - vOffset}, {0 - hOffset, 1 - vOffset}, - {1 - hOffset, 0 - vOffset}, {1 - hOffset, 1 - vOffset}); - - mCompositeMapSM->getRootSceneNode()->attachObject(mCompositeMapPlane); - - } - - // update - mCompositeMapPlane->setMaterial(mat); - TerrainGlobalOptions& globalopts = TerrainGlobalOptions::getSingleton(); - mLightNode->setDirection(globalopts.getLightMapDirection(), Node::TS_WORLD); - mCompositeMapLight->setDiffuseColour(globalopts.getCompositeMapDiffuse()); - mCompositeMapSM->setAmbientLight(globalopts.getCompositeMapAmbient()); - - - // check for size change (allow smaller to be reused) - if (mCompositeMapRTT && size != mCompositeMapRTT->getWidth()) - { - TextureManager::getSingleton().remove(mCompositeMapRTT->getHandle()); - mCompositeMapRTT = 0; - } - - if (!mCompositeMapRTT) - { - mCompositeMapRTT = TextureManager::getSingleton().createManual( - mCompositeMapSM->getName() + "/compRTT", mat->getGroup(), - TEX_TYPE_2D, static_cast(size), static_cast(size), 0, - PF_BYTE_RGBA, TU_RENDERTARGET).get(); - RenderTarget* rtt = mCompositeMapRTT->getBuffer()->getRenderTarget(); - // don't render all the time, only on demand - rtt->setAutoUpdated(false); - Viewport* vp = rtt->addViewport(mCompositeMapCam); - // don't render overlays - vp->setOverlaysEnabled(false); - - } - - // calculate the area we need to update - Real vpleft = (Real)rect.left / (Real)size; - Real vptop = (Real)rect.top / (Real)size; - Real vpright = (Real)rect.right / (Real)size; - Real vpbottom = (Real)rect.bottom / (Real)size; - - RenderTarget* rtt = mCompositeMapRTT->getBuffer()->getRenderTarget(); - mCompositeMapCam->setWindow(vpleft, vptop, vpright, vpbottom); - - rtt->update(); - - // We have an RTT, we want to copy the results into a regular texture - // That's because in non-update scenarios we don't want to keep an RTT - // around. We use a single RTT to serve all terrain pages which is more - // efficient. - Box box(rect); - destCompositeMap->getBuffer()->blit(mCompositeMapRTT->getBuffer(), box, box); - - - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - void TerrainMaterialGenerator::updateCompositeMap(const Terrain* terrain, const Rect& rect) - { - // convert point-space rect into image space - int32 compSize = terrain->getCompositeMap()->getWidth(); - Rect imgRect; - Vector3 inVec, outVec; - inVec.x = rect.left; - inVec.y = rect.bottom - 1; // this is 'top' in image space, also make inclusive - terrain->convertPosition(Terrain::POINT_SPACE, inVec, Terrain::TERRAIN_SPACE, outVec); - imgRect.left = outVec.x * compSize; - imgRect.top = (1.0f - outVec.y) * compSize; - inVec.x = rect.right - 1; - inVec.y = rect.top; // this is 'bottom' in image space - terrain->convertPosition(Terrain::POINT_SPACE, inVec, Terrain::TERRAIN_SPACE, outVec); - imgRect.right = outVec.x * (Real)compSize + 1; - imgRect.bottom = (1.0 - outVec.y) * compSize + 1; - - imgRect = imgRect.intersect({0, 0, compSize, compSize}); - - _renderCompositeMap(compSize, imgRect, terrain->getCompositeMapMaterial(), terrain->getCompositeMap()); - } - - -} - diff --git a/Components/Terrain/src/OgreTerrainMaterialGeneratorA.cpp b/Components/Terrain/src/OgreTerrainMaterialGeneratorA.cpp deleted file mode 100644 index 3bbec6ae748..00000000000 --- a/Components/Terrain/src/OgreTerrainMaterialGeneratorA.cpp +++ /dev/null @@ -1,455 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreTerrainMaterialGeneratorA.h" -#include "OgreTerrain.h" -#include "OgreMaterialManager.h" -#include "OgreTechnique.h" -#include "OgrePass.h" -#include "OgreTextureUnitState.h" -#include "OgreGpuProgramManager.h" -#include "OgreShadowCameraSetupPSSM.h" -#include "OgreLogManager.h" -#include "OgreHighLevelGpuProgram.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" -#include "OgreTextureManager.h" - -#include "OgreShaderGenerator.h" -#include "OgreTerrainRTShaderSRS.h" - -#include -#include - -namespace Ogre -{ - //--------------------------------------------------------------------- - TerrainMaterialGeneratorA::TerrainMaterialGeneratorA() : - mLightmapEnabled(true), - mCompositeMapEnabled(true), - mReceiveDynamicShadows(true), - mLowLodShadows(false) - { - // define the layers - // We expect terrain textures to have no alpha, so we use the alpha channel - // in the albedo texture to store specular reflection - // similarly we double-up the normal and height (for parallax) - mLayerDecl = {{"albedo_specular", PF_BYTE_RGBA}, {"normal_height", PF_BYTE_RGBA}}; - - mActiveProfile.reset(new SM2Profile(this)); - - using namespace RTShader; - - if (!ShaderGenerator::getSingletonPtr()) - { - LogManager::getSingleton().logError( - "TerrainMaterialGeneratorA - Shader generation not possible: RTSS is not initialized."); - return; - } - - static SubRenderStateFactory* factory = nullptr; - if(!factory) - { - factory = new TerrainTransformFactory; - ShaderGenerator::getSingleton().addSubRenderStateFactory(factory); - factory = new TerrainSurfaceFactory; - ShaderGenerator::getSingleton().addSubRenderStateFactory(factory); - } - - mMainRenderState.reset(new RenderState()); - mMainRenderState->setLightCount(1); - mMainRenderState->addTemplateSubRenderStates( - {"TerrainTransform", "TerrainSurface", SRS_PER_PIXEL_LIGHTING, SRS_FOG}); - } - //--------------------------------------------------------------------- - TerrainMaterialGeneratorA::~TerrainMaterialGeneratorA() - { - - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - TerrainMaterialGeneratorA::SM2Profile::SM2Profile(TerrainMaterialGeneratorA* parent) - : mParent(parent) - , mLayerNormalMappingEnabled(true) - , mLayerParallaxMappingEnabled(true) - , mLayerParallaxOcclusionMappingEnabled(true) - , mLayerSpecularMappingEnabled(true) - , mPSSM(0) - { - } - //--------------------------------------------------------------------- - TerrainMaterialGeneratorA::SM2Profile::~SM2Profile() - { - } - //--------------------------------------------------------------------- - void TerrainMaterialGeneratorA::requestOptions(Terrain* terrain) - { - terrain->_setMorphRequired(true); - terrain->_setNormalMapRequired(true); - terrain->_setLightMapRequired(mLightmapEnabled, true); - terrain->_setCompositeMapRequired(mCompositeMapEnabled); - } - //--------------------------------------------------------------------- - void TerrainMaterialGeneratorA::SM2Profile::setLayerNormalMappingEnabled(bool enabled) - { - if (enabled != mLayerNormalMappingEnabled) - { - mLayerNormalMappingEnabled = enabled; - mParent->_markChanged(); - } - } - //--------------------------------------------------------------------- - void TerrainMaterialGeneratorA::SM2Profile::setLayerParallaxMappingEnabled(bool enabled) - { - if (enabled != mLayerParallaxMappingEnabled) - { - mLayerParallaxMappingEnabled = enabled; - mParent->_markChanged(); - } - } - //--------------------------------------------------------------------- - void TerrainMaterialGeneratorA::SM2Profile::setLayerParallaxOcclusionMappingEnabled(bool enabled) - { - if (enabled != mLayerParallaxOcclusionMappingEnabled) - { - mLayerParallaxOcclusionMappingEnabled = enabled; - mParent->_markChanged(); - } - } - //--------------------------------------------------------------------- - void TerrainMaterialGeneratorA::SM2Profile::setLayerSpecularMappingEnabled(bool enabled) - { - if (enabled != mLayerSpecularMappingEnabled) - { - mLayerSpecularMappingEnabled = enabled; - mParent->_markChanged(); - } - } - //--------------------------------------------------------------------- - void TerrainMaterialGeneratorA::setLightmapEnabled(bool enabled) - { - if (enabled != mLightmapEnabled) - { - mLightmapEnabled = enabled; - _markChanged(); - } - } - //--------------------------------------------------------------------- - void TerrainMaterialGeneratorA::setCompositeMapEnabled(bool enabled) - { - if (enabled != mCompositeMapEnabled) - { - mCompositeMapEnabled = enabled; - _markChanged(); - } - } - //--------------------------------------------------------------------- - void TerrainMaterialGeneratorA::setReceiveDynamicShadowsEnabled(bool enabled) - { - if (enabled != mReceiveDynamicShadows) - { - mReceiveDynamicShadows = enabled; - _markChanged(); - } - } - //--------------------------------------------------------------------- - void TerrainMaterialGeneratorA::SM2Profile::setReceiveDynamicShadowsPSSM(PSSMShadowCameraSetup* pssmSettings) - { - if (pssmSettings != mPSSM) - { - mPSSM = pssmSettings; - mParent->_markChanged(); - } - } - //--------------------------------------------------------------------- - void TerrainMaterialGeneratorA::setReceiveDynamicShadowsLowLod(bool enabled) - { - if (enabled != mLowLodShadows) - { - mLowLodShadows = enabled; - _markChanged(); - } - } - //--------------------------------------------------------------------- - uint8 TerrainMaterialGeneratorA::SM2Profile::getMaxLayers(const Terrain* terrain) const - { - // count the texture units free - uint8 freeTextureUnits = 16; - // lightmap - --freeTextureUnits; - // normalmap - --freeTextureUnits; - // colourmap - if (terrain->getGlobalColourMapEnabled()) - --freeTextureUnits; - if (isShadowingEnabled(HIGH_LOD, terrain)) - { - uint8 numShadowTextures = 1; - if (getReceiveDynamicShadowsPSSM()) - { - numShadowTextures = (uint8)getReceiveDynamicShadowsPSSM()->getSplitCount(); - } - freeTextureUnits -= numShadowTextures; - } - - // each layer needs 2.25 units (1xdiffusespec, 1xnormalheight, 0.25xblend) - return static_cast(freeTextureUnits / 2.25f); - - - } - //--------------------------------------------------------------------- - static int getRequiredLayers(const Terrain* terrain, bool pssm) - { - int layers = terrain->getLayerCount(); // layer diffusespec - if (!terrain->getLayerTextureName(0, 1).empty()) - layers *= 2; // per layer normalheight - layers += 1; // global normal - layers += bool(terrain->getGlobalColourMap()); - layers += bool(terrain->getLightmap()); - layers += terrain->getBlendTextures().size(); - - if(pssm) - layers += 3; // 3 shadow textures - - return layers; - } - MaterialPtr TerrainMaterialGeneratorA::SM2Profile::generate(const Terrain* terrain) - { - // re-use old material if exists - MaterialPtr mat = terrain->_getMaterial(); - if (!mat) - { - MaterialManager& matMgr = MaterialManager::getSingleton(); - const String& matName = terrain->getMaterialName(); - mat = matMgr.getByName(matName); - if (!mat) - { - mat = matMgr.create(matName, terrain->_getDerivedResourceGroup()); - } - } - // clear everything - mat->removeAllTechniques(); - - // Automatically disable normal & parallax mapping if card cannot handle it - // We do this rather than having a specific technique for it since it's simpler - auto rsc = Root::getSingletonPtr()->getRenderSystem()->getCapabilities(); - if (getRequiredLayers(terrain, mPSSM) > rsc->getNumTextureUnits()) - { - setLayerNormalMappingEnabled(false); - setLayerParallaxMappingEnabled(false); - LogManager::getSingleton().logWarning( - "TerrainMaterialGeneratorA: Normal mapping disabled due to lack of texture units"); - } - - Pass* pass; - pass = mat->createTechnique()->createPass(); - pass->getUserObjectBindings().setUserAny("Terrain", terrain); - pass->setSpecular(ColourValue::White); - pass->setShininess(32); // user param - - if(mLayerSpecularMappingEnabled) - { - // we use this to inject our specular map - pass->setVertexColourTracking(TVC_SPECULAR); - } - - using namespace RTShader; - auto mainRenderState = std::make_shared(); - auto tplRS = static_cast(mParent)->getMainRenderState(); - mainRenderState->setLightCount(tplRS->getLightCount()); - mainRenderState->setHaveAreaLights(tplRS->haveAreaLights()); - - if(auto surface = tplRS->getSubRenderState("TerrainSurface")) - surface->setParameter("use_normal_mapping", std::to_string(mLayerNormalMappingEnabled)); - - try - { - mainRenderState->link(*tplRS, pass, pass); - auto surface = mainRenderState->getSubRenderState("TerrainSurface"); - OgreAssert(surface, "TerrainSurface SubRenderState not found"); - surface->setParameter("use_parallax_mapping", std::to_string(mLayerParallaxMappingEnabled)); - surface->setParameter("use_parallax_occlusion_mapping", std::to_string(mLayerParallaxOcclusionMappingEnabled)); - surface->setParameter("use_specular_mapping", std::to_string(mLayerSpecularMappingEnabled)); - if(isShadowingEnabled(HIGH_LOD, terrain)) - { - auto pssm = ShaderGenerator::getSingleton().createSubRenderState(SRS_SHADOW_MAPPING); - if(mPSSM) - pssm->setParameter("split_points", mPSSM->getSplitPoints()); - pssm->preAddToRenderState(mainRenderState.get(), pass, pass); - mainRenderState->addSubRenderStateInstance(pssm); - } - mainRenderState->acquirePrograms(pass); - } - catch(const std::exception& e) - { - LogManager::getSingleton().logError(e.what()); - return nullptr; - } - - pass->getUserObjectBindings().setUserAny(TargetRenderState::UserKey, mainRenderState); - - // LOD - if(mParent->isCompositeMapEnabled()) - { - Technique* tech = mat->createTechnique(); - tech->setLodIndex(1); - - pass = tech->createPass(); - TextureUnitState* tu = pass->createTextureUnitState(); - tu->setTexture(terrain->getCompositeMap()); - tu->setTextureAddressingMode(TAM_CLAMP); - - pass->getUserObjectBindings().setUserAny("Terrain", terrain); - - auto lod1RenderState = std::make_shared(); - try - { - lod1RenderState->link({"TerrainTransform", SRS_VERTEX_COLOUR, SRS_TEXTURING, SRS_FOG}, pass, pass); - if (isShadowingEnabled(LOW_LOD, terrain)) - { - // light count needed to enable PSSM3 - lod1RenderState->setLightCount(1); - auto pssm = ShaderGenerator::getSingleton().createSubRenderState(SRS_SHADOW_MAPPING); - if(mPSSM) - pssm->setParameter("split_points", mPSSM->getSplitPoints()); - pssm->preAddToRenderState(lod1RenderState.get(), pass, pass); - lod1RenderState->addSubRenderStateInstance(pssm); - } - lod1RenderState->acquirePrograms(pass); - } - catch(const Exception& e) - { - LogManager::getSingleton().logError(e.what()); - return nullptr; - } - - pass->getUserObjectBindings().setUserAny(TargetRenderState::UserKey, lod1RenderState); - - mat->setLodLevels({TerrainGlobalOptions::getSingleton().getCompositeMapDistance()}); - } - - mParent->updateParams(mat, terrain); - - return mat; - } - //--------------------------------------------------------------------- - MaterialPtr TerrainMaterialGeneratorA::generateForCompositeMap(const Terrain* terrain) - { - // re-use old material if exists - MaterialPtr mat = terrain->_getCompositeMapMaterial(); - if (!mat) - { - MaterialManager& matMgr = MaterialManager::getSingleton(); - - // it's important that the names are deterministic for a given terrain, so - // use the terrain pointer as an ID - const String& matName = terrain->getMaterialName() + "/comp"; - mat = matMgr.getByName(matName); - if (!mat) - { - mat = matMgr.create(matName, terrain->_getDerivedResourceGroup()); - } - } - // clear everything - mat->removeAllTechniques(); - - using namespace RTShader; - auto pass = mat->createTechnique()->createPass(); - pass->getUserObjectBindings().setUserAny("Terrain", terrain); - - auto compRenderState = std::make_shared(); - compRenderState->setLightCount(1); - - try - { - compRenderState->link({SRS_TRANSFORM, "TerrainSurface", SRS_PER_PIXEL_LIGHTING}, pass, pass); - auto terrainSurface = compRenderState->getSubRenderState("TerrainSurface"); - terrainSurface->setParameter("for_composite_map", "true"); - compRenderState->acquirePrograms(pass); - terrainSurface->updateGpuProgramsParams(NULL, NULL, NULL, NULL); // composite map scene manager not registered - } - catch(const std::exception& e) - { - LogManager::getSingleton().logError(e.what()); - return nullptr; - } - - pass->getUserObjectBindings().setUserAny(TargetRenderState::UserKey, compRenderState); - updateParamsForCompositeMap(mat, terrain); - - return mat; - - } - //--------------------------------------------------------------------- - bool TerrainMaterialGeneratorA::SM2Profile::isShadowingEnabled(TechniqueType tt, const Terrain* terrain) const - { - return mParent->getReceiveDynamicShadowsEnabled() && tt != RENDER_COMPOSITE_MAP && - (tt != LOW_LOD || mParent->getReceiveDynamicShadowsLowLod()) && - terrain->getSceneManager()->isShadowTechniqueTextureBased(); - } - //--------------------------------------------------------------------- - void TerrainMaterialGeneratorA::updateParams(const MaterialPtr& mat, const Terrain* terrain) - { - using namespace RTShader; - auto mainRenderState = any_cast( - mat->getTechnique(0)->getPass(0)->getUserObjectBindings().getUserAny(TargetRenderState::UserKey)); - - for (auto srs : mainRenderState->getSubRenderStates()) - { - if (auto transform = dynamic_cast(srs)) - { - transform->updateParams(); - } - if (auto surface = dynamic_cast(srs)) - { - surface->updateParams(); - } - } - - if(!isCompositeMapEnabled()) - return; - - auto lod1RenderState = any_cast( - mat->getTechnique(1)->getPass(0)->getUserObjectBindings().getUserAny(TargetRenderState::UserKey)); - if (auto transform = lod1RenderState->getSubRenderState("TerrainTransform")) - { - static_cast(transform)->updateParams(); - } - } - //--------------------------------------------------------------------- - void TerrainMaterialGeneratorA::updateParamsForCompositeMap(const MaterialPtr& mat, const Terrain* terrain) - { - using namespace RTShader; - auto mainRenderState = any_cast( - mat->getTechnique(0)->getPass(0)->getUserObjectBindings().getUserAny(TargetRenderState::UserKey)); - - if (auto surface = mainRenderState->getSubRenderState("TerrainSurface")) - { - static_cast(surface)->updateParams(); - } - } -} diff --git a/Components/Terrain/src/OgreTerrainPagedWorldSection.cpp b/Components/Terrain/src/OgreTerrainPagedWorldSection.cpp deleted file mode 100644 index 5c2a042d284..00000000000 --- a/Components/Terrain/src/OgreTerrainPagedWorldSection.cpp +++ /dev/null @@ -1,337 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreTerrainPagedWorldSection.h" -#include "OgreTerrainGroup.h" -#include "OgreGrid2DPageStrategy.h" -#include "OgrePagedWorld.h" -#include "OgrePageManager.h" -#include "OgreRoot.h" -#include "OgreTimer.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - TerrainPagedWorldSection::TerrainPagedWorldSection(const String& name, PagedWorld* parent, SceneManager* sm) - : PagedWorldSection(name, parent, sm) - , mTerrainGroup(0) - , mTerrainDefiner(0) - , mHasRunningTasks(false) - , mLoadingIntervalMs(900) - { - // we always use a grid strategy - setStrategy(parent->getManager()->getStrategy("Grid2D")); - mNextLoadingTime = Root::getSingletonPtr()->getTimer()->getMilliseconds(); - } - //--------------------------------------------------------------------- - TerrainPagedWorldSection::~TerrainPagedWorldSection() - { - //remove the pending tasks, but keep the front one, as it may have been in running - if(!mPagesInLoading.empty()) - mPagesInLoading.erase( ++mPagesInLoading.begin(), mPagesInLoading.end() ); - - while(!mPagesInLoading.empty()) - { - OGRE_THREAD_SLEEP(50); - Root::getSingleton().getWorkQueue()->processMainThreadTasks(); - } - - OGRE_DELETE mTerrainGroup; - if(mTerrainDefiner) - OGRE_DELETE mTerrainDefiner; - } - //--------------------------------------------------------------------- - void TerrainPagedWorldSection::init(TerrainGroup* grp) - { - if (mTerrainGroup == grp) - return; - - if (mTerrainGroup) - OGRE_DELETE mTerrainGroup; - - mTerrainGroup = grp; - syncSettings(); - - // Unload all existing terrain pages, because we want the paging system - // to be in charge of this - mTerrainGroup->removeAllTerrains(); - } - //--------------------------------------------------------------------- - void TerrainPagedWorldSection::syncSettings() - { - - // Base grid on terrain settings - Grid2DPageStrategyData* gridData = getGridStrategyData(); - switch (mTerrainGroup->getAlignment()) - { - case Terrain::ALIGN_X_Y: - gridData->setMode(G2D_X_Y); - break; - case Terrain::ALIGN_X_Z: - gridData->setMode(G2D_X_Z); - break; - case Terrain::ALIGN_Y_Z: - gridData->setMode(G2D_Y_Z); - break; - } - gridData->setOrigin(mTerrainGroup->getOrigin()); - - gridData->setCellSize(mTerrainGroup->getTerrainWorldSize()); - - } - //--------------------------------------------------------------------- - void TerrainPagedWorldSection::setLoadRadius(Real sz) - { - getGridStrategyData()->setLoadRadius(sz); - } - //--------------------------------------------------------------------- - Real TerrainPagedWorldSection::getLoadRadius() const - { - return getGridStrategyData()->getLoadRadius(); - } - //--------------------------------------------------------------------- - void TerrainPagedWorldSection::setHoldRadius(Real sz) - { - getGridStrategyData()->setHoldRadius(sz); - } - //--------------------------------------------------------------------- - Real TerrainPagedWorldSection::getHoldRadius() - { - return getGridStrategyData()->getHoldRadius(); - } - //--------------------------------------------------------------------- - void TerrainPagedWorldSection::setPageRange(int32 minX, int32 minY, int32 maxX, int32 maxY) - { - getGridStrategyData()->setCellRange(minX, minY, maxX, maxY); - } - //--------------------------------------------------------------------- - void TerrainPagedWorldSection::setPageRangeMinX(int32 minX) - { - getGridStrategyData()->setCellRangeMinX(minX); - } - //--------------------------------------------------------------------- - void TerrainPagedWorldSection::setPageRangeMinY(int32 minY) - { - getGridStrategyData()->setCellRangeMinY(minY); - } - //--------------------------------------------------------------------- - void TerrainPagedWorldSection::setPageRangeMaxX(int32 maxX) - { - getGridStrategyData()->setCellRangeMaxX(maxX); - } - //--------------------------------------------------------------------- - void TerrainPagedWorldSection::setPageRangeMaxY(int32 maxY) - { - getGridStrategyData()->setCellRangeMaxY(maxY); - } - //--------------------------------------------------------------------- - int32 TerrainPagedWorldSection::getPageRangeMinX() const - { - return getGridStrategyData()->getCellRangeMinX(); - } - //--------------------------------------------------------------------- - int32 TerrainPagedWorldSection::getPageRangeMinY() const - { - return getGridStrategyData()->getCellRangeMinY(); - } - //--------------------------------------------------------------------- - int32 TerrainPagedWorldSection::getPageRangeMaxX() const - { - return getGridStrategyData()->getCellRangeMaxX(); - } - //--------------------------------------------------------------------- - int32 TerrainPagedWorldSection::getPageRangeMaxY() const - { - return getGridStrategyData()->getCellRangeMaxY(); - } - //--------------------------------------------------------------------- - Grid2DPageStrategy* TerrainPagedWorldSection::getGridStrategy() const - { - return static_cast(this->getStrategy()); - } - //--------------------------------------------------------------------- - Grid2DPageStrategyData* TerrainPagedWorldSection::getGridStrategyData() const - { - return static_cast(mStrategyData); - } - //--------------------------------------------------------------------- - void TerrainPagedWorldSection::setLoadingIntervalMs(uint32 loadingIntervalMs) - { - mLoadingIntervalMs = loadingIntervalMs; - } - //--------------------------------------------------------------------- - uint32 TerrainPagedWorldSection::getLoadingIntervalMs() const - { - return mLoadingIntervalMs; - } - - //--------------------------------------------------------------------- - void TerrainPagedWorldSection::loadSubtypeData(StreamSerialiser& ser) - { - // we load the TerrainGroup information from here - if (!mTerrainGroup) - mTerrainGroup = OGRE_NEW TerrainGroup(getSceneManager()); - - mTerrainGroup->loadGroupDefinition(ser); - - // params that are in the Grid2DStrategyData will have already been loaded - // as part of the main load() routine - - syncSettings(); - } - //--------------------------------------------------------------------- - void TerrainPagedWorldSection::saveSubtypeData(StreamSerialiser& ser) - { - mTerrainGroup->saveGroupDefinition(ser); - - // params that are in the Grid2DStrategyData will have already been saved - // as part of the main save() routine - - } - //--------------------------------------------------------------------- - void TerrainPagedWorldSection::loadPage(PageID pageID, bool forceSynchronous) - { - if (!mParent->getManager()->getPagingOperationsEnabled()) - return; - - PageMap::iterator i = mPages.find(pageID); - if (i == mPages.end()) - { - std::list::iterator it = find( mPagesInLoading.begin(), mPagesInLoading.end(), pageID); - if(it==mPagesInLoading.end()) - { - mPagesInLoading.push_back(pageID); - mHasRunningTasks = true; - } - - // no running tasks, start the new one - if(mPagesInLoading.size()==1) - { - if(forceSynchronous) - { - handleRequest(NULL, NULL); - handleResponse(NULL, NULL); - } - else - { - Root::getSingleton().getWorkQueue()->addTask([this]() { - handleRequest(NULL, NULL); - if(mPagesInLoading.empty()) - return; - // continue loading in main thread - Root::getSingleton().getWorkQueue()->addMainThreadTask([this]() { handleResponse(NULL, NULL); }); - }); - } - } - } - - PagedWorldSection::loadPage(pageID, forceSynchronous); - } - //--------------------------------------------------------------------- - void TerrainPagedWorldSection::unloadPage(PageID pageID, bool forceSynchronous) - { - if (!mParent->getManager()->getPagingOperationsEnabled()) - return; - - PagedWorldSection::unloadPage(pageID, forceSynchronous); - - std::list::iterator it = find( mPagesInLoading.begin(), mPagesInLoading.end(), pageID); - // hasn't been loaded, just remove from the queue - if(it!=mPagesInLoading.end()) - { - mPagesInLoading.erase(it); - } - else - { - // trigger terrain unload - long x, y; - // pageID is the same as a packed index - mTerrainGroup->unpackIndex(pageID, &x, &y); - mTerrainGroup->unloadTerrain(x, y); - } - } - //--------------------------------------------------------------------- - WorkQueue::Response* TerrainPagedWorldSection::handleRequest(const WorkQueue::Request* req, const WorkQueue* srcQ) - { - if(mPagesInLoading.empty()) - { - mHasRunningTasks = false; - return NULL; - } - - unsigned long currentTime = Root::getSingletonPtr()->getTimer()->getMilliseconds(); - if(currentTime < mNextLoadingTime) - { - // Wait until the next page is to be loaded -> we are in background thread here - OGRE_THREAD_SLEEP(mNextLoadingTime - currentTime); - } - - PageID pageID = mPagesInLoading.front(); - - // call the TerrainDefiner from the background thread - long x, y; - // pageID is the same as a packed index - mTerrainGroup->unpackIndex(pageID, &x, &y); - - if(!mTerrainDefiner) - mTerrainDefiner = OGRE_NEW TerrainDefiner(); - mTerrainDefiner->define(mTerrainGroup, x, y); - - return NULL; - } - - //--------------------------------------------------------------------- - void TerrainPagedWorldSection::handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ) - { - if(!mPagesInLoading.empty()) - { - PageID pageID = mPagesInLoading.front(); - - // trigger terrain load - long x, y; - // pageID is the same as a packed index - mTerrainGroup->unpackIndex(pageID, &x, &y); - mTerrainGroup->loadTerrain(x, y, false); - mPagesInLoading.pop_front(); - - unsigned long currentTime = Root::getSingletonPtr()->getTimer()->getMilliseconds(); - mNextLoadingTime = currentTime + mLoadingIntervalMs; - - // Continue loading other pages - Root::getSingleton().getWorkQueue()->addTask([this]() { - handleRequest(NULL, NULL); - if(mPagesInLoading.empty()) - return; - // continue loading in main thread - Root::getSingleton().getWorkQueue()->addMainThreadTask([this]() { handleResponse(NULL, NULL); }); - }); - } - else - mHasRunningTasks = false; - } -} - diff --git a/Components/Terrain/src/OgreTerrainPaging.cpp b/Components/Terrain/src/OgreTerrainPaging.cpp deleted file mode 100644 index aa0929af1e1..00000000000 --- a/Components/Terrain/src/OgreTerrainPaging.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreTerrainPaging.h" -#include "OgreTerrainPagedWorldSection.h" -#include "OgreTerrainGroup.h" -#include "OgrePagedWorld.h" -#include "OgrePageManager.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - TerrainPaging::TerrainPaging(PageManager* pageMgr) - : mManager(pageMgr) - { - mManager->addWorldSectionFactory(&mSectionFactory); - } - //--------------------------------------------------------------------- - TerrainPaging::~TerrainPaging() - { - mManager->removeWorldSectionFactory(&mSectionFactory); - } - //--------------------------------------------------------------------- - TerrainPagedWorldSection* TerrainPaging::createWorldSection( - PagedWorld* world, TerrainGroup* terrainGroup, - Real loadRadius, Real holdRadius, int32 minX, int32 minY, int32 maxX, int32 maxY, - const String& sectionName, uint32 loadingIntervalMs) - { - TerrainPagedWorldSection* ret = static_cast( - world->createSection(terrainGroup->getSceneManager(), SectionFactory::FACTORY_NAME, sectionName)); - - ret->init(terrainGroup); - ret->setLoadRadius(loadRadius); - ret->setHoldRadius(holdRadius); - ret->setPageRange(minX, minY, maxX, maxY); - ret->setLoadingIntervalMs(loadingIntervalMs); - - return ret; - - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - const String TerrainPaging::SectionFactory::FACTORY_NAME("Terrain"); - - const String& TerrainPaging::SectionFactory::getName() const - { - return FACTORY_NAME; - } - //--------------------------------------------------------------------- - PagedWorldSection* TerrainPaging::SectionFactory::createInstance(const String& name, PagedWorld* parent, SceneManager* sm) - { - return OGRE_NEW TerrainPagedWorldSection(name, parent, sm); - } - //--------------------------------------------------------------------- - void TerrainPaging::SectionFactory::destroyInstance(PagedWorldSection* s) - { - OGRE_DELETE s; - } - - -} - diff --git a/Components/Terrain/src/OgreTerrainQuadTreeNode.cpp b/Components/Terrain/src/OgreTerrainQuadTreeNode.cpp deleted file mode 100644 index 1093d6bc65d..00000000000 --- a/Components/Terrain/src/OgreTerrainQuadTreeNode.cpp +++ /dev/null @@ -1,1454 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreTerrainQuadTreeNode.h" -#include "OgreTerrain.h" -#include "OgreVertexIndexData.h" -#include "OgreDefaultHardwareBufferManager.h" -#include "OgreCamera.h" -#include "OgreStreamSerialiser.h" -#include "OgreSceneNode.h" -#include "OgreLodStrategy.h" - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -// we do lots of conversions here, casting them all is tedious & cluttered, we know what we're doing -# pragma warning (disable : 4244) -#endif - -namespace Ogre -{ - unsigned short TerrainQuadTreeNode::POSITION_BUFFER = 0; - unsigned short TerrainQuadTreeNode::DELTA_BUFFER = 1; - - //--------------------------------------------------------------------- - TerrainQuadTreeNode::TerrainQuadTreeNode(Terrain* terrain, - TerrainQuadTreeNode* parent, uint16 xoff, uint16 yoff, uint16 size, - uint16 lod, uint16 depth) - : mTerrain(terrain) - , mParent(parent) - , mOffsetX(xoff) - , mOffsetY(yoff) - , mBoundaryX(xoff + size) - , mBoundaryY(yoff + size) - , mSize(size) - , mBaseLod(lod) - , mDepth(depth) - , mBoundingRadius(0) - , mCurrentLod(-1) - , mLodTransition(0) - , mChildWithMaxHeightDelta(0) - , mSelfOrChildRendered(false) - , mNodeWithVertexData(0) - , mVertexDataRecord(0) - , mLocalNode(0) - { - if (terrain->getMaxBatchSize() < size) - { - uint16 childSize = (uint16)(((size - 1) * 0.5f) + 1); - uint16 childOff = childSize - 1; - uint16 childLod = lod - 1; // LOD levels decrease down the tree (higher detail) - uint16 childDepth = depth + 1; - // create children - mChildren[0] = OGRE_NEW TerrainQuadTreeNode(terrain, this, xoff, yoff, childSize, childLod, childDepth); - mChildren[1] = OGRE_NEW TerrainQuadTreeNode(terrain, this, xoff + childOff, yoff, childSize, childLod, childDepth); - mChildren[2] = OGRE_NEW TerrainQuadTreeNode(terrain, this, xoff, yoff + childOff, childSize, childLod, childDepth); - mChildren[3] = OGRE_NEW TerrainQuadTreeNode(terrain, this, xoff + childOff, yoff + childOff, childSize, childLod, childDepth); - - LodLevel* ll = OGRE_NEW LodLevel(); - // non-leaf nodes always render with minBatchSize vertices - ll->batchSize = terrain->getMinBatchSize(); - ll->maxHeightDelta = 0; - ll->calcMaxHeightDelta = 0; - mLodLevels.push_back(ll); - - } - else - { - // No children - memset(mChildren, 0, sizeof(TerrainQuadTreeNode*) * 4); - - // this is a leaf node and may have internal LODs of its own - uint16 ownLod = terrain->getNumLodLevelsPerLeaf(); - assert (lod == (ownLod - 1) && "The lod passed in should reflect the number of " - "lods in a leaf"); - // leaf nodes always have a base LOD of 0, because they're always handling - // the highest level of detail - mBaseLod = 0; - // leaf nodes render from max batch size to min batch size - uint16 sz = terrain->getMaxBatchSize(); - - while (ownLod--) - { - LodLevel* ll = OGRE_NEW LodLevel(); - ll->batchSize = sz; - ll->maxHeightDelta = 0; - ll->calcMaxHeightDelta = 0; - mLodLevels.push_back(ll); - if (ownLod) - sz = (uint16)(((sz - 1) * 0.5) + 1); - } - - assert(sz == terrain->getMinBatchSize()); - - } - - // Local centre calculation - // Because of pow2 + 1 there is always a middle point - uint16 midoffset = (size - 1) / 2; - uint16 midpointx = mOffsetX + midoffset; - uint16 midpointy = mOffsetY + midoffset; - // derive the local centre, but give it a height of 0 - // TODO - what if we actually centred this at the terrain height at this point? - // would this be better? - mTerrain->getPoint(midpointx, midpointy, 0, &mLocalCentre); - } - //--------------------------------------------------------------------- - TerrainQuadTreeNode::~TerrainQuadTreeNode() - { - if (mLocalNode) - { - mTerrain->_getRootSceneNode()->removeAndDestroyChild(mLocalNode); - mLocalNode = 0; - } - - for (int i = 0; i < 4; ++i) - OGRE_DELETE mChildren[i]; - - destroyCpuVertexData(); - destroyGpuVertexData(); - destroyGpuIndexData(); - - for (LodLevelList::iterator i = mLodLevels.begin(); i != mLodLevels.end(); ++i) - OGRE_DELETE *i; - - OGRE_DELETE mVertexDataRecord; - } - //--------------------------------------------------------------------- - bool TerrainQuadTreeNode::isLeaf() const - { - return mChildren[0] == 0; - } - //--------------------------------------------------------------------- - TerrainQuadTreeNode* TerrainQuadTreeNode::getChild(unsigned short child) const - { - if (isLeaf() || child >= 4) - return 0; - - return mChildren[child]; - } - //--------------------------------------------------------------------- - TerrainQuadTreeNode* TerrainQuadTreeNode::getParent() const - { - return mParent; - } - //--------------------------------------------------------------------- - Terrain* TerrainQuadTreeNode::getTerrain() const - { - return mTerrain; - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::prepare() - { - if (!isLeaf()) - { - for (int i = 0; i < 4; ++i) - mChildren[i]->prepare(); - } - - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::prepare(StreamSerialiser& stream) - { - // load LOD data we need - for (auto *l : mLodLevels) - { - // only read 'calc' and then copy to final (separation is only for - // real-time calculation - // Basically this is what finaliseHeightDeltas does in calc path - stream.read(&l->calcMaxHeightDelta); - l->maxHeightDelta = l->calcMaxHeightDelta; - l->lastCFactor = 0; - } - - if (!isLeaf()) - { - for (int i = 0; i < 4; ++i) - mChildren[i]->prepare(stream); - } - - // If this is the root, do the post delta calc to finish - if (!mParent) - { - Rect rect; - rect.top = mOffsetY; rect.bottom = mBoundaryY; - rect.left = mOffsetX; rect.right = mBoundaryX; - postDeltaCalculation(rect); - } - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::save(StreamSerialiser& stream) - { - // save LOD data we need - for (const auto *l : mLodLevels) - stream.write(&l->maxHeightDelta); - - if (!isLeaf()) - { - for (int i = 0; i < 4; ++i) - mChildren[i]->save(stream); - } - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::load() - { - loadSelf(); - - if (!isLeaf()) - for (int i = 0; i < 4; ++i) - mChildren[i]->load(); - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::load(uint16 treeDepthStart, uint16 treeDepthEnd) - { - if (mDepth >= treeDepthEnd) - return ; - - if (mDepth >= treeDepthStart && mDepth < treeDepthEnd && mNodeWithVertexData) - loadSelf(); - - if (!isLeaf()) - for (int i = 0; i < 4; ++i) - mChildren[i]->load(treeDepthStart, treeDepthEnd); - } - void TerrainQuadTreeNode::loadSelf() - { - createGpuVertexData(); - createGpuIndexData(); - if (!mLocalNode) - mLocalNode = mTerrain->_getRootSceneNode()->createChildSceneNode(mLocalCentre); - - if (!isAttached()) - mLocalNode->attachObject(this); - - mQueryFlags = mTerrain->getQueryFlags(); - mVisibilityFlags = mTerrain->getVisibilityFlags(); - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::unload() - { - if (!isLeaf()) - for (int i = 0; i < 4; ++i) - mChildren[i]->unload(); - - destroyGpuVertexData(); - detachFromParent(); - } - - void TerrainQuadTreeNode::unload(uint16 treeDepthStart, uint16 treeDepthEnd) - { - if (mDepth >= treeDepthEnd) - return ; - - if (!isLeaf()) - for (int i = 0; i < 4; ++i) - mChildren[i]->unload(treeDepthStart, treeDepthEnd); - - if (mDepth >= treeDepthStart && mDepth < treeDepthEnd) - { - destroyGpuVertexData(); - detachFromParent(); - } - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::unprepare() - { - if (!isLeaf()) - for (int i = 0; i < 4; ++i) - mChildren[i]->unprepare(); - - destroyCpuVertexData(); - } - //--------------------------------------------------------------------- - uint16 TerrainQuadTreeNode::getLodCount() const - { - return static_cast(mLodLevels.size()); - } - //--------------------------------------------------------------------- - const TerrainQuadTreeNode::LodLevel* TerrainQuadTreeNode::getLodLevel(uint16 lod) - { - assert(lod < mLodLevels.size()); - - return mLodLevels[lod]; - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::preDeltaCalculation(const Rect& rect) - { - if (rect.left <= mBoundaryX || rect.right > mOffsetX - || rect.top <= mBoundaryY || rect.bottom > mOffsetY) - { - // relevant to this node (overlaps) - - // if the rect covers the whole node, reset the max height - // this means that if you recalculate the deltas progressively, end up keeping - // a max height that's no longer the case (ie more conservative lod), - // but that's the price for not recaculating the whole node. If a - // complete recalculation is required, just dirty the entire node. (or terrain) - - // Note we use the 'calc' field here to avoid interfering with any - // ongoing LOD calculations (this can be in the background) - - if (rect.left <= mOffsetX && rect.right > mBoundaryX - && rect.top <= mOffsetY && rect.bottom > mBoundaryY) - { - for (LodLevelList::iterator i = mLodLevels.begin(); i != mLodLevels.end(); ++i) - (*i)->calcMaxHeightDelta = 0.0; - } - - // pass on to children - if (!isLeaf()) - { - for (int i = 0; i < 4; ++i) - mChildren[i]->preDeltaCalculation(rect); - - } - } - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::notifyDelta(uint16 x, uint16 y, uint16 lod, Real delta) - { - if (x >= mOffsetX && x < mBoundaryX - && y >= mOffsetY && y < mBoundaryY) - { - // within our bounds, check it's our LOD level - if (lod >= mBaseLod && lod < mBaseLod + mLodLevels.size()) - { - // Apply the delta to all LODs equal or lower detail to lod - LodLevelList::iterator i = mLodLevels.begin(); - std::advance(i, lod - mBaseLod); - (*i)->calcMaxHeightDelta = std::max((*i)->calcMaxHeightDelta, delta); - } - - // pass on to children - if (!isLeaf()) - { - for (int i = 0; i < 4; ++i) - { - mChildren[i]->notifyDelta(x, y, lod, delta); - } - } - - } - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::postDeltaCalculation(const Rect& rect) - { - if (rect.left <= mBoundaryX || rect.right > mOffsetX - || rect.top <= mBoundaryY || rect.bottom > mOffsetY) - { - // relevant to this node (overlaps) - - // each non-leaf node should know which of its children transitions - // to the lower LOD level last, because this is the one which controls - // when the parent takes over - if (!isLeaf()) - { - Real maxChildDelta = -1; - TerrainQuadTreeNode* childWithMaxHeightDelta = 0; - for (int i = 0; i < 4; ++i) - { - TerrainQuadTreeNode* child = mChildren[i]; - - child->postDeltaCalculation(rect); - - Real childDelta = child->getLodLevel(child->getLodCount()-1)->calcMaxHeightDelta; - if (childDelta > maxChildDelta) - { - childWithMaxHeightDelta = child; - maxChildDelta = childDelta; - } - - } - - // make sure that our highest delta value is greater than all children's - // otherwise we could have some crossover problems - // for a non-leaf, there is only one LOD level - mLodLevels[0]->calcMaxHeightDelta = std::max(mLodLevels[0]->calcMaxHeightDelta, maxChildDelta * (Real)1.05); - mChildWithMaxHeightDelta = childWithMaxHeightDelta; - - } - else - { - // make sure own LOD levels delta values ascend - for (size_t i = 0; i < mLodLevels.size() - 1; ++i) - { - // the next LOD after this one should have a higher delta - // otherwise it won't come into affect further back like it should! - mLodLevels[i+1]->calcMaxHeightDelta = - std::max(mLodLevels[i+1]->calcMaxHeightDelta, - mLodLevels[i]->calcMaxHeightDelta * (Real)1.05); - } - - } - } - - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::finaliseDeltaValues(const Rect& rect) - { - if (rect.left <= mBoundaryX || rect.right > mOffsetX - || rect.top <= mBoundaryY || rect.bottom > mOffsetY) - { - // relevant to this node (overlaps) - - // Children - if (!isLeaf()) - { - for (int i = 0; i < 4; ++i) - { - TerrainQuadTreeNode* child = mChildren[i]; - child->finaliseDeltaValues(rect); - } - - } - - // Self - for (auto *l : mLodLevels) - { - // copy from 'calc' area to runtime value - l->maxHeightDelta = l->calcMaxHeightDelta; - // also trash stored cfactor - l->lastCFactor = 0; - } - } - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::assignVertexData(uint16 treeDepthStart, - uint16 treeDepthEnd, uint16 resolution, uint sz) - { - assert(treeDepthStart >= mDepth && "Should not be calling this"); - - if (mDepth == treeDepthStart) - { - // we own this vertex data - mNodeWithVertexData = this; - if (!mVertexDataRecord) - mVertexDataRecord = OGRE_NEW VertexDataRecord(resolution, sz, treeDepthEnd - treeDepthStart); - - createCpuVertexData(); - - // pass on to children - if (!isLeaf() && treeDepthEnd > (mDepth + 1)) // treeDepthEnd is exclusive, and this is children - { - for (int i = 0; i < 4; ++i) - mChildren[i]->useAncestorVertexData(this, treeDepthEnd, resolution); - - } - } - else - { - assert(!isLeaf() && "No more levels below this!"); - - for (int i = 0; i < 4; ++i) - mChildren[i]->assignVertexData(treeDepthStart, treeDepthEnd, resolution, sz); - - } - - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::useAncestorVertexData(TerrainQuadTreeNode* owner, uint16 treeDepthEnd, uint16 resolution) - { - mNodeWithVertexData = owner; - mVertexDataRecord = 0; - - if (!isLeaf() && treeDepthEnd > (mDepth + 1)) // treeDepthEnd is exclusive, and this is children - { - for (int i = 0; i < 4; ++i) - mChildren[i]->useAncestorVertexData(owner, treeDepthEnd, resolution); - } - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::updateVertexData(bool positions, bool deltas, - const Rect& rect, bool cpuData) - { - //Check that we really intersect the dirty rect. This avoid assertion errors further down the line. - Rect updateRect = rect.intersect(Rect(mOffsetX, mOffsetY, mBoundaryX, mBoundaryY)); - if (!updateRect.isNull()) - { - // Do we have vertex data? - if (mVertexDataRecord) - { - // update the GPU buffer directly - // TODO: do we have no use for CPU vertex data after initial load? - // if so, destroy it to free RAM, this should be fast enough to - // to direct - HardwareVertexBufferSharedPtr posbuf, deltabuf; - VertexData* targetVertexData = mVertexDataRecord->cpuVertexData; - if(!cpuData) - { - if(mVertexDataRecord->gpuVertexData == NULL) - createGpuVertexData(); - assert(mVertexDataRecord->gpuVertexData); - targetVertexData = mVertexDataRecord->gpuVertexData; - } - - if (positions) - posbuf = targetVertexData->vertexBufferBinding->getBuffer(POSITION_BUFFER); - if (deltas) - deltabuf = targetVertexData->vertexBufferBinding->getBuffer(DELTA_BUFFER); - updateVertexBuffer(posbuf, deltabuf, updateRect); - } - - // pass on to children - if (!isLeaf()) - { - for (int i = 0; i < 4; ++i) - { - mChildren[i]->updateVertexData(positions, deltas, rect, cpuData); - - // merge bounds from children - AxisAlignedBox childBox = mChildren[i]->getBoundingBox(); - // this box is relative to child centre - Vector3 boxoffset = mChildren[i]->getLocalCentre() - getLocalCentre(); - childBox.setMinimum(childBox.getMinimum() + boxoffset); - childBox.setMaximum(childBox.getMaximum() + boxoffset); - mAABB.merge(childBox); - } - - } - // Make sure node knows to update - if (isAttached()) - mLocalNode->needUpdate(); - - - - } - - } - //--------------------------------------------------------------------- - const TerrainQuadTreeNode::VertexDataRecord* TerrainQuadTreeNode::getVertexDataRecord() const - { - return mNodeWithVertexData ? mNodeWithVertexData->mVertexDataRecord : 0; - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::createCpuVertexData() - { - if (mVertexDataRecord) - { - destroyCpuVertexData(); - - // create vertex structure, not using GPU for now (these are CPU structures) - VertexDeclaration* dcl = OGRE_NEW VertexDeclaration(); - VertexBufferBinding* bufbind = OGRE_NEW VertexBufferBinding(); - - mVertexDataRecord->cpuVertexData = OGRE_NEW VertexData(dcl, bufbind); - - // Vertex declaration - size_t offset = 0; - - if (mTerrain->_getUseVertexCompression()) - { - // 16 bytes per vertex, shaders only - // POSITION (encoded x/y as indexes from base) - // short2(x, y) - offset += dcl->addElement(POSITION_BUFFER, offset, VET_SHORT2, VES_POSITION).getSize(); - // UV0 - height - // float(height) - dcl->addElement(POSITION_BUFFER, offset, VET_FLOAT1, VES_TEXTURE_COORDINATES, 0).getSize(); - // UV1 delta information - // float2(delta, deltaLODthreshold) - dcl->addElement(DELTA_BUFFER, 0, VET_FLOAT2, VES_TEXTURE_COORDINATES, 1).getSize(); - } - else - { - // 28 bytes per vertex, compatibility - // POSITION - // float3(x, y, z) - offset += dcl->addElement(POSITION_BUFFER, offset, VET_FLOAT3, VES_POSITION).getSize(); - // UV0 - // float2(u, v) - dcl->addElement(POSITION_BUFFER, offset, VET_FLOAT2, VES_TEXTURE_COORDINATES, 0).getSize(); - // UV1 delta information - // float2(delta, deltaLODthreshold) - dcl->addElement(DELTA_BUFFER, 0, VET_FLOAT2, VES_TEXTURE_COORDINATES, 1).getSize(); - } - - // Calculate number of vertices - // Base geometry size * size - size_t baseNumVerts = (size_t)Math::Sqr(mVertexDataRecord->size); - size_t numVerts = baseNumVerts; - // Now add space for skirts - // Skirts will be rendered as copies of the edge vertices translated downwards - // Some people use one big fan with only 3 vertices at the bottom, - // but this requires creating them much bigger that necessary, meaning - // more unnecessary overdraw, so we'll use more vertices - // You need 2^levels + 1 rows of full resolution (max 129) vertex copies, plus - // the same number of columns. There are common vertices at intersections - uint16 levels = mVertexDataRecord->treeLevels; - mVertexDataRecord->numSkirtRowsCols = (uint16)(Math::Pow(2, levels) + 1); - mVertexDataRecord->skirtRowColSkip = (mVertexDataRecord->size - 1) / (mVertexDataRecord->numSkirtRowsCols - 1); - numVerts += mVertexDataRecord->size * mVertexDataRecord->numSkirtRowsCols; - numVerts += mVertexDataRecord->size * mVertexDataRecord->numSkirtRowsCols; - // manually create CPU-side buffer - auto pos_sz = dcl->getVertexSize(POSITION_BUFFER); - auto posbuf = std::make_shared(nullptr, pos_sz, numVerts, - new DefaultHardwareBuffer(pos_sz * numVerts)); - - auto delta_sz = dcl->getVertexSize(DELTA_BUFFER); - auto deltabuf = std::make_shared(nullptr, delta_sz, numVerts, - new DefaultHardwareBuffer(delta_sz * numVerts)); - - mVertexDataRecord->cpuVertexData->vertexStart = 0; - mVertexDataRecord->cpuVertexData->vertexCount = numVerts; - - Rect updateRect(mOffsetX, mOffsetY, mBoundaryX, mBoundaryY); - updateVertexBuffer(posbuf, deltabuf, updateRect); - bufbind->setBinding(POSITION_BUFFER, posbuf); - bufbind->setBinding(DELTA_BUFFER, deltabuf); - mVertexDataRecord->gpuVertexDataDirty = true; - } - } - //---------------------------------------------------------------------- - void TerrainQuadTreeNode::updateVertexBuffer(const HardwareVertexBufferPtr& posbuf, - const HardwareVertexBufferPtr& deltabuf, const Rect& rect) - { - assert (rect.left >= mOffsetX && rect.right <= mBoundaryX && - rect.top >= mOffsetY && rect.bottom <= mBoundaryY); - - // potentially reset our bounds depending on coverage of the update - resetBounds(rect); - - // Main data - uint16 inc = (mTerrain->getSize()-1) / (mVertexDataRecord->resolution-1); - long destOffsetX = rect.left <= mOffsetX ? 0 : (rect.left - mOffsetX) / inc; - long destOffsetY = rect.top <= mOffsetY ? 0 : (rect.top - mOffsetY) / inc; - // Fill the buffers - - HardwareBuffer::LockOptions lockMode; - if (destOffsetX || destOffsetY || rect.width() < mSize - || rect.height() < mSize) - { - lockMode = HardwareBuffer::HBL_NORMAL; - } - else - { - lockMode = HardwareBuffer::HBL_DISCARD; - } - - Real uvScale = 1.0f / (mTerrain->getSize() - 1); - const float* pBaseHeight = mTerrain->getHeightData(rect.left, rect.top); - const float* pBaseDelta = mTerrain->getDeltaData(rect.left, rect.top); - uint16 rowskip = mTerrain->getSize() * inc; - uint16 destPosRowSkip = 0, destDeltaRowSkip = 0; - unsigned char* pRootPosBuf = 0; - unsigned char* pRootDeltaBuf = 0; - unsigned char* pRowPosBuf = 0; - unsigned char* pRowDeltaBuf = 0; - - if (posbuf) - { - destPosRowSkip = mVertexDataRecord->size * uint16(posbuf->getVertexSize()); - pRootPosBuf = static_cast(posbuf->lock(lockMode)); - pRowPosBuf = pRootPosBuf; - // skip dest buffer in by left/top - pRowPosBuf += destOffsetY * destPosRowSkip + destOffsetX * posbuf->getVertexSize(); - } - if (deltabuf) - { - destDeltaRowSkip = mVertexDataRecord->size * uint16(deltabuf->getVertexSize()); - pRootDeltaBuf = static_cast(deltabuf->lock(lockMode)); - pRowDeltaBuf = pRootDeltaBuf; - // skip dest buffer in by left/top - pRowDeltaBuf += destOffsetY * destDeltaRowSkip + destOffsetX * deltabuf->getVertexSize(); - } - Vector3 pos; - - bool vcompress = mTerrain->_getUseVertexCompression(); - - for (uint16 y = rect.top; y < rect.bottom; y += inc) - { - const float* pHeight = pBaseHeight; - const float* pDelta = pBaseDelta; - float* pPosBuf = static_cast(static_cast(pRowPosBuf)); - float* pDeltaBuf = static_cast(static_cast(pRowDeltaBuf)); - for (uint16 x = rect.left; x < rect.right; x += inc) - { - if (pPosBuf) - { - mTerrain->getPoint(x, y, *pHeight, &pos); - - // Update bounds *before* making relative - mergeIntoBounds(x, y, pos); - // relative to local centre - pos -= mLocalCentre; - - writePosVertex(vcompress, x, y, *pHeight, pos, uvScale, &pPosBuf); - pHeight += inc; - - - } - - if (pDeltaBuf) - { - // delta, and delta LOD threshold - // we want delta to apply to LODs no higher than this value - // at runtime this will be combined with a per-renderable parameter - // to ensure we only apply morph to the correct LOD - writeDeltaVertex(vcompress, x, y, *pDelta, - (float)mTerrain->getLODLevelWhenVertexEliminated(x, y) - 1.0f, - &pDeltaBuf); - pDelta += inc; - - } - - - } - pBaseHeight += rowskip; - pBaseDelta += rowskip; - if (pRowPosBuf) - pRowPosBuf += destPosRowSkip; - if (pRowDeltaBuf) - pRowDeltaBuf += destDeltaRowSkip; - - } - - // Skirts now - // skirt spacing based on top-level resolution (* inc to cope with resolution which is not the max) - uint16 skirtSpacing = mVertexDataRecord->skirtRowColSkip * inc; - Vector3 skirtOffset; - mTerrain->getVector(0, 0, -mTerrain->getSkirtSize(), &skirtOffset); - - // skirt rows - // clamp rows to skirt spacing (round up) - int skirtStartX = rect.left; - int skirtStartY = rect.top; - // for rows, clamp Y to skirt frequency, X to inc (LOD resolution vs top) - if (skirtStartY % skirtSpacing) - skirtStartY += skirtSpacing - (skirtStartY % skirtSpacing); - if (skirtStartX % inc) - skirtStartX += inc - (skirtStartX % inc); - skirtStartY = std::max(skirtStartY, (int)mOffsetY); - pBaseHeight = mTerrain->getHeightData(skirtStartX, skirtStartY); - if (posbuf) - { - // position dest buffer just after the main vertex data - pRowPosBuf = pRootPosBuf + posbuf->getVertexSize() - * mVertexDataRecord->size * mVertexDataRecord->size; - // move it onwards to skip the skirts we don't need to update - pRowPosBuf += destPosRowSkip * ((skirtStartY - mOffsetY) / skirtSpacing); - pRowPosBuf += posbuf->getVertexSize() * (skirtStartX - mOffsetX) / inc; - } - if (deltabuf) - { - // position dest buffer just after the main vertex data - pRowDeltaBuf = pRootDeltaBuf + deltabuf->getVertexSize() - * mVertexDataRecord->size * mVertexDataRecord->size; - // move it onwards to skip the skirts we don't need to update - pRowDeltaBuf += destDeltaRowSkip * (skirtStartY - mOffsetY) / skirtSpacing; - pRowDeltaBuf += deltabuf->getVertexSize() * (skirtStartX - mOffsetX) / inc; - } - for (uint16 y = skirtStartY; y < rect.bottom; y += skirtSpacing) - { - const float* pHeight = pBaseHeight; - float* pPosBuf = static_cast(static_cast(pRowPosBuf)); - float* pDeltaBuf = static_cast(static_cast(pRowDeltaBuf)); - for (uint16 x = skirtStartX; x < rect.right; x += inc) - { - if (pPosBuf) - { - mTerrain->getPoint(x, y, *pHeight, &pos); - // relative to local centre - pos -= mLocalCentre; - pos += skirtOffset; - writePosVertex(vcompress, x, y, *pHeight - mTerrain->getSkirtSize(), pos, uvScale, &pPosBuf); - - pHeight += inc; - - - - } - - if (pDeltaBuf) - { - // delta (none) - // delta threshold (irrelevant) - writeDeltaVertex(vcompress, x, y, 0, 99, &pDeltaBuf); - } - } - pBaseHeight += mTerrain->getSize() * skirtSpacing; - if (pRowPosBuf) - pRowPosBuf += destPosRowSkip; - if (pRowDeltaBuf) - pRowDeltaBuf += destDeltaRowSkip; - } - // skirt cols - // clamp cols to skirt spacing (round up) - skirtStartX = rect.left; - if (skirtStartX % skirtSpacing) - skirtStartX += skirtSpacing - (skirtStartX % skirtSpacing); - // clamp Y to inc (LOD resolution vs top) - skirtStartY = rect.top; - if (skirtStartY % inc) - skirtStartY += inc - (skirtStartY % inc); - skirtStartX = std::max(skirtStartX, (int)mOffsetX); - if (posbuf) - { - // position dest buffer just after the main vertex data and skirt rows - pRowPosBuf = pRootPosBuf + posbuf->getVertexSize() - * mVertexDataRecord->size * mVertexDataRecord->size; - // skip the row skirts - pRowPosBuf += mVertexDataRecord->numSkirtRowsCols * mVertexDataRecord->size * posbuf->getVertexSize(); - // move it onwards to skip the skirts we don't need to update - pRowPosBuf += destPosRowSkip * (skirtStartX - mOffsetX) / skirtSpacing; - pRowPosBuf += posbuf->getVertexSize() * (skirtStartY - mOffsetY) / inc; - } - if (deltabuf) - { - // Delta dest buffer just after the main vertex data and skirt rows - pRowDeltaBuf = pRootDeltaBuf + deltabuf->getVertexSize() - * mVertexDataRecord->size * mVertexDataRecord->size; - // skip the row skirts - pRowDeltaBuf += mVertexDataRecord->numSkirtRowsCols * mVertexDataRecord->size * deltabuf->getVertexSize(); - // move it onwards to skip the skirts we don't need to update - pRowDeltaBuf += destDeltaRowSkip * (skirtStartX - mOffsetX) / skirtSpacing; - pRowDeltaBuf += deltabuf->getVertexSize() * (skirtStartY - mOffsetY) / inc; - } - - for (uint16 x = skirtStartX; x < rect.right; x += skirtSpacing) - { - float* pPosBuf = static_cast(static_cast(pRowPosBuf)); - float* pDeltaBuf = static_cast(static_cast(pRowDeltaBuf)); - for (uint16 y = skirtStartY; y < rect.bottom; y += inc) - { - if (pPosBuf) - { - float height = mTerrain->getHeightAtPoint(x, y); - mTerrain->getPoint(x, y, height, &pos); - // relative to local centre - pos -= mLocalCentre; - pos += skirtOffset; - - writePosVertex(vcompress, x, y, height - mTerrain->getSkirtSize(), pos, uvScale, &pPosBuf); - - } - if (pDeltaBuf) - { - // delta (none) - // delta threshold (irrelevant) - writeDeltaVertex(vcompress, x, y, 0, 99, &pDeltaBuf); - } - } - if (pRowPosBuf) - pRowPosBuf += destPosRowSkip; - if (pRowDeltaBuf) - pRowDeltaBuf += destDeltaRowSkip; - } - - if (posbuf) - posbuf->unlock(); - if (deltabuf) - deltabuf->unlock(); - - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::writePosVertex(bool compress, uint16 x, uint16 y, float height, - const Vector3& pos, float uvScale, float** ppPos) - { - float* pPosBuf = *ppPos; - - if (compress) - { - short* pPosShort = static_cast(static_cast(pPosBuf)); - *pPosShort++ = (short)x; - *pPosShort++ = (short)y; - pPosBuf = static_cast(static_cast(pPosShort)); - - *pPosBuf++ = height; - } - else - { - *pPosBuf++ = pos.x; - *pPosBuf++ = pos.y; - *pPosBuf++ = pos.z; - - // UVs - base UVs vary from 0 to 1, all other values - // will be derived using scalings - *pPosBuf++ = x * uvScale; - *pPosBuf++ = 1.0f - (y * uvScale); - } - - *ppPos = pPosBuf; - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::writeDeltaVertex(bool compress, uint16 x, uint16 y, - float delta, float deltaThresh, float** ppDelta) - { - *(*ppDelta)++ = delta; - *(*ppDelta)++ = deltaThresh; - } - //--------------------------------------------------------------------- - uint16 TerrainQuadTreeNode::calcSkirtVertexIndex(uint16 mainIndex, bool isCol) - { - const VertexDataRecord* vdr = getVertexDataRecord(); - // row / col in main vertex resolution - uint16 row = mainIndex / vdr->size; - uint16 col = mainIndex % vdr->size; - - // skrits are after main vertices, so skip them - uint16 base = vdr->size * vdr->size; - - // The layout in vertex data is: - // 1. row skirts - // numSkirtRowsCols rows of resolution vertices each - // 2. column skirts - // numSkirtRowsCols cols of resolution vertices each - - // No offsets used here, this is an index into the current vertex data, - // which is already relative - if (isCol) - { - uint16 skirtNum = col / vdr->skirtRowColSkip; - uint16 colbase = vdr->numSkirtRowsCols * vdr->size; - return base + colbase + vdr->size * skirtNum + row; - } - else - { - uint16 skirtNum = row / vdr->skirtRowColSkip; - return base + vdr->size * skirtNum + col; - } - - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::destroyCpuVertexData() - { - if (mVertexDataRecord && mVertexDataRecord->cpuVertexData) - { - // avoid copy empty buffer - mVertexDataRecord->gpuVertexDataDirty = false; - // delete the bindings and declaration manually since not from a buf mgr - OGRE_DELETE mVertexDataRecord->cpuVertexData->vertexDeclaration; - mVertexDataRecord->cpuVertexData->vertexDeclaration = 0; - - OGRE_DELETE mVertexDataRecord->cpuVertexData->vertexBufferBinding; - mVertexDataRecord->cpuVertexData->vertexBufferBinding = 0; - - OGRE_DELETE mVertexDataRecord->cpuVertexData; - mVertexDataRecord->cpuVertexData = 0; - } - - - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::populateIndexData(uint16 batchSize, IndexData* destData) - { - const VertexDataRecord* vdr = getVertexDataRecord(); - - // Ratio of the main terrain resolution in relation to this vertex data resolution - uint16 resolutionRatio = (mTerrain->getSize() - 1) / (vdr->resolution - 1); - // At what frequency do we sample the vertex data we're using? - // mSize is the coverage in terms of the original terrain data (not split to fit in 16-bit) - uint16 vertexIncrement = (mSize-1) / (batchSize-1); - // however, the vertex data we're referencing may not be at the full resolution anyway - vertexIncrement /= resolutionRatio; - uint16 vdatasizeOffsetX = (mOffsetX - mNodeWithVertexData->mOffsetX) / resolutionRatio; - uint16 vdatasizeOffsetY = (mOffsetY - mNodeWithVertexData->mOffsetY) / resolutionRatio; - - destData->indexBuffer = mTerrain->getGpuBufferAllocator()->getSharedIndexBuffer(batchSize, vdr->size, - vertexIncrement, vdatasizeOffsetX, vdatasizeOffsetY, - vdr->numSkirtRowsCols, vdr->skirtRowColSkip); - destData->indexStart = 0; - destData->indexCount = destData->indexBuffer->getNumIndexes(); - - // shared index buffer is pre-populated - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::createGpuVertexData() - { - // TODO - mutex cpu data - if (mVertexDataRecord && mVertexDataRecord->cpuVertexData && !mVertexDataRecord->gpuVertexData) - { - // copy data from CPU to GPU, but re-use vertex buffers (so don't use regular clone) - mVertexDataRecord->gpuVertexData = OGRE_NEW VertexData(); - VertexData* srcData = mVertexDataRecord->cpuVertexData; - VertexData* destData = mVertexDataRecord->gpuVertexData; - - // copy vertex buffers - // get new buffers - HardwareVertexBufferSharedPtr destPosBuf, destDeltaBuf; - mTerrain->getGpuBufferAllocator()->allocateVertexBuffers(mTerrain, srcData->vertexCount, - destPosBuf, destDeltaBuf); - - // copy data - destPosBuf->copyData(*srcData->vertexBufferBinding->getBuffer(POSITION_BUFFER)); - destDeltaBuf->copyData(*srcData->vertexBufferBinding->getBuffer(DELTA_BUFFER)); - - // set bindings - destData->vertexBufferBinding->setBinding(POSITION_BUFFER, destPosBuf); - destData->vertexBufferBinding->setBinding(DELTA_BUFFER, destDeltaBuf); - // Basic vertex info - destData->vertexStart = srcData->vertexStart; - destData->vertexCount = srcData->vertexCount; - // Copy elements - const VertexDeclaration::VertexElementList elems = - srcData->vertexDeclaration->getElements(); - for (auto& e : elems) { - destData->vertexDeclaration->addElement( - e.getSource(), - e.getOffset(), - e.getType(), - e.getSemantic(), - e.getIndex() - ); - } - // We don't need the CPU copy anymore - destroyCpuVertexData(); - } - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::updateGpuVertexData() - { - if (mVertexDataRecord && mVertexDataRecord->gpuVertexDataDirty) - { - mVertexDataRecord->gpuVertexData->vertexBufferBinding->getBuffer(POSITION_BUFFER)-> - copyData(*mVertexDataRecord->cpuVertexData->vertexBufferBinding->getBuffer(POSITION_BUFFER).get()); - mVertexDataRecord->gpuVertexData->vertexBufferBinding->getBuffer(DELTA_BUFFER)-> - copyData(*mVertexDataRecord->cpuVertexData->vertexBufferBinding->getBuffer(DELTA_BUFFER).get()); - mVertexDataRecord->gpuVertexDataDirty = false; - } - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::destroyGpuVertexData() - { - if (mVertexDataRecord && mVertexDataRecord->gpuVertexData) - { - // Before we delete, free up the vertex buffers for someone else - mTerrain->getGpuBufferAllocator()->freeVertexBuffers( - mVertexDataRecord->gpuVertexData->vertexBufferBinding->getBuffer(POSITION_BUFFER), - mVertexDataRecord->gpuVertexData->vertexBufferBinding->getBuffer(DELTA_BUFFER)); - OGRE_DELETE mVertexDataRecord->gpuVertexData; - mVertexDataRecord->gpuVertexData = 0; - } - - - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::createGpuIndexData() - { - for (size_t lod = 0; lod < mLodLevels.size(); ++lod) - { - LodLevel* ll = mLodLevels[lod]; - - if (!ll->gpuIndexData) - { - // clone, using default buffer manager ie hardware - ll->gpuIndexData = OGRE_NEW IndexData(); - populateIndexData(ll->batchSize, ll->gpuIndexData); - } - } - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::destroyGpuIndexData() - { - for (size_t lod = 0; lod < mLodLevels.size(); ++lod) - { - LodLevel* ll = mLodLevels[lod]; - - OGRE_DELETE ll->gpuIndexData; - ll->gpuIndexData = 0; - } - - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::mergeIntoBounds(long x, long y, const Vector3& pos) - { - if (pointIntersectsNode(x, y)) - { - Vector3 localPos = pos - mLocalCentre; - mAABB.merge(localPos); - mBoundingRadius = std::max(mBoundingRadius, localPos.length()); - - if (!isLeaf()) - { - for (int i = 0; i < 4; ++i) - mChildren[i]->mergeIntoBounds(x, y, pos); - } - } - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::resetBounds(const Rect& rect) - { - if (rectContainsNode(rect)) - { - mAABB.setNull(); - mBoundingRadius = 0; - - if (!isLeaf()) - { - for (int i = 0; i < 4; ++i) - mChildren[i]->resetBounds(rect); - } - - - } - } - //--------------------------------------------------------------------- - bool TerrainQuadTreeNode::rectContainsNode(const Rect& rect) - { - return (rect.left <= mOffsetX && rect.right > mBoundaryX && - rect.top <= mOffsetY && rect.bottom > mBoundaryY); - } - //--------------------------------------------------------------------- - bool TerrainQuadTreeNode::rectIntersectsNode(const Rect& rect) - { - return (rect.right >= mOffsetX && rect.left <= mBoundaryX && - rect.bottom >= mOffsetY && rect.top <= mBoundaryY); - } - //--------------------------------------------------------------------- - bool TerrainQuadTreeNode::pointIntersectsNode(long x, long y) - { - return x >= mOffsetX && x < mBoundaryX && - y >= mOffsetY && y < mBoundaryY; - } - //--------------------------------------------------------------------- - Real TerrainQuadTreeNode::getBoundingRadius() const - { - return mBoundingRadius; - } - //--------------------------------------------------------------------- - Real TerrainQuadTreeNode::getMinHeight() const - { - switch (mTerrain->getAlignment()) - { - case Terrain::ALIGN_X_Y: - default: - return mAABB.getMinimum().z; - case Terrain::ALIGN_X_Z: - return mAABB.getMinimum().y; - case Terrain::ALIGN_Y_Z: - return mAABB.getMinimum().x; - }; - } - //--------------------------------------------------------------------- - Real TerrainQuadTreeNode::getMaxHeight() const - { - switch (mTerrain->getAlignment()) - { - case Terrain::ALIGN_X_Y: - default: - return mAABB.getMaximum().z; - case Terrain::ALIGN_X_Z: - return mAABB.getMaximum().y; - case Terrain::ALIGN_Y_Z: - return mAABB.getMaximum().x; - }; - - } - //--------------------------------------------------------------------- - bool TerrainQuadTreeNode::calculateCurrentLod(const Camera* cam, Real cFactor) - { - mSelfOrChildRendered = false; - - // early-out - if (!cam->isVisible(getWorldBoundingBox(true))) - { - mCurrentLod = -1; - return mSelfOrChildRendered; - } - - // Check children first - int childRenderedCount = 0; - if (!isLeaf()) - { - for (int i = 0; i < 4; ++i) - { - if (mChildren[i]->calculateCurrentLod(cam, cFactor)) - ++childRenderedCount; - } - - } - - // this node not loaded yet so skip - if (!isAttached()) - { - mCurrentLod = -1; - return mSelfOrChildRendered; - } - - if (childRenderedCount == 0) - { - - // no children were within their LOD ranges, so we should consider our own - Vector3 localPos = cam->getDerivedPosition() - mLocalCentre - mTerrain->getPosition(); - Real dist; - if (TerrainGlobalOptions::getSingleton().getUseRayBoxDistanceCalculation()) - { - // Get distance to this terrain node (to closest point of the box) - // head towards centre of the box (note, box may not cover mLocalCentre because of height) - Vector3 dir(mAABB.getCenter() - localPos); - dir.normalise(); - Ray ray(localPos, dir); - std::pair intersectRes = Math::intersects(ray, mAABB); - - // ray will always intersect, we just want the distance - dist = intersectRes.second; - } - else - { - // distance to tile centre - dist = localPos.length(); - // deduct half the radius of the box, assume that on average the - // worst case is best approximated by this - dist -= (mBoundingRadius * 0.5f); - } - - // Do material LOD - MaterialPtr material = getMaterial(); - const LodStrategy *materialStrategy = material->getLodStrategy(); - Real lodValue = materialStrategy->getValue(this, cam); - // Get the index at this biased depth - mMaterialLodIndex = material->getLodIndex(lodValue); - - - // For each LOD, the distance at which the LOD will transition *downwards* - // is given by - // distTransition = maxDelta * cFactor; - uint lodLvl = 0; - mCurrentLod = -1; - for (LodLevelList::iterator i = mLodLevels.begin(); i != mLodLevels.end(); ++i, ++lodLvl) - { - // If we have no parent, and this is the lowest LOD, we always render - // this is the 'last resort' so to speak, we always enoucnter this last - if (lodLvl+1 == mLodLevels.size() && !mParent) - { - mCurrentLod = lodLvl; - mSelfOrChildRendered = true; - mLodTransition = 0; - } - else - { - // check the distance - LodLevel* ll = *i; - - // Calculate or reuse transition distance - Real distTransition; - if (Math::RealEqual(cFactor, ll->lastCFactor)) - distTransition = ll->lastTransitionDist; - else - { - distTransition = ll->maxHeightDelta * cFactor; - ll->lastCFactor = cFactor; - ll->lastTransitionDist = distTransition; - } - - if (dist < distTransition) - { - // we're within range of this LOD - mCurrentLod = lodLvl; - mSelfOrChildRendered = true; - - if (mTerrain->_getMorphRequired()) - { - // calculate the transition percentage - // we need a percentage of the total distance for just this LOD, - // which means taking off the distance for the next higher LOD - // which is either the previous entry in the LOD list, - // or the largest of any children. In both cases these will - // have been calculated before this point, since we process - // children first. Distances at lower LODs are guaranteed - // to be larger than those at higher LODs - - Real distTotal = distTransition; - if (isLeaf()) - { - // Any higher LODs? - if (i != mLodLevels.begin()) - { - LodLevelList::iterator prev = i - 1; - distTotal -= (*prev)->lastTransitionDist; - } - } - else - { - // Take the distance of the lowest LOD of child - const LodLevel* childLod = mChildWithMaxHeightDelta->getLodLevel( - mChildWithMaxHeightDelta->getLodCount()-1); - distTotal -= childLod->lastTransitionDist; - } - // fade from 0 to 1 in the last 25% of the distance - Real distMorphRegion = distTotal * 0.25f; - Real distRemain = distTransition - dist; - - mLodTransition = 1.0f - (distRemain / distMorphRegion); - mLodTransition = std::min(1.0f, mLodTransition); - mLodTransition = std::max(0.0f, mLodTransition); - - // Pass both the transition % and target LOD (GLOBAL current + 1) - // this selectively applies the morph just to the - // vertices which would drop out at this LOD, even - // while using the single shared vertex data - setCustomParameter(Terrain::LOD_MORPH_CUSTOM_PARAM, - Vector4f(mLodTransition, mCurrentLod + mBaseLod + 1, 0, 0)); - } - // since LODs are ordered from highest to lowest detail, - // we can stop looking now - break; - } - - } - } - - } - else - { - // we should not render ourself - mCurrentLod = -1; - mSelfOrChildRendered = true; - if (childRenderedCount < 4) - { - // only *some* children decided to render on their own, but either - // none or all need to render, so set the others manually to their lowest - for (int i = 0; i < 4; ++i) - { - TerrainQuadTreeNode* child = mChildren[i]; - if (!child->isSelfOrChildRenderedAtCurrentLod()) - { - child->setCurrentLod(child->getLodCount()-1); - child->setLodTransition(1.0); - } - } - } // (childRenderedCount < 4) - - } // (childRenderedCount == 0) - - - return mSelfOrChildRendered; - - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::setCurrentLod(int lod) - { - mCurrentLod = lod; - setCustomParameter(Terrain::LOD_MORPH_CUSTOM_PARAM, - Vector4f(mLodTransition, mCurrentLod + mBaseLod + 1, 0, 0)); - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::setLodTransition(float t) - { - mLodTransition = t; - setCustomParameter(Terrain::LOD_MORPH_CUSTOM_PARAM, Vector4f(mLodTransition, mCurrentLod + mBaseLod + 1, 0, 0)); - } - //--------------------------------------------------------------------- - bool TerrainQuadTreeNode::isRenderedAtCurrentLod() const - { - return mCurrentLod != -1; - } - //--------------------------------------------------------------------- - bool TerrainQuadTreeNode::isSelfOrChildRenderedAtCurrentLod() const - { - return mSelfOrChildRendered; - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::_updateRenderQueue(RenderQueue* queue) - { - if (isRenderedAtCurrentLod()) - { - mNodeWithVertexData->updateGpuVertexData(); - queue->addRenderable(this, mTerrain->getRenderQueueGroup()); - } - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::visitRenderables(Renderable::Visitor* visitor, bool debugRenderables) - { - visitor->visit(this, 0, false); - } - //--------------------------------------------------------------------- - const MaterialPtr& TerrainQuadTreeNode::getMaterial(void) const - { - return mTerrain->getMaterial(); - } - //--------------------------------------------------------------------- - Technique* TerrainQuadTreeNode::getTechnique(void) const - { - return getMaterial()->getBestTechnique(mMaterialLodIndex, this); - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::getRenderOperation(RenderOperation& op) - { - op.indexData = mLodLevels[mCurrentLod]->gpuIndexData; - op.operationType = RenderOperation::OT_TRIANGLE_STRIP; - op.useIndexes = true; - op.vertexData = getVertexDataRecord()->gpuVertexData; - } - //--------------------------------------------------------------------- - void TerrainQuadTreeNode::getWorldTransforms(Matrix4* xform) const - { - if (mTerrain->_getUseVertexCompression()) - { - // vertex data is generated in terrain space - *xform = Matrix4::IDENTITY; - xform->setTrans(mTerrain->getPosition()); - - } - else - { - // the vertex data is relative to the node that owns the vertex data - *xform = mNodeWithVertexData->_getParentNodeFullTransform(); - } - - } - //--------------------------------------------------------------------- - Real TerrainQuadTreeNode::getSquaredViewDepth(const Camera* cam) const - { - return mLocalNode->getSquaredViewDepth(cam); - } - //--------------------------------------------------------------------- - const LightList& TerrainQuadTreeNode::getLights(void) const - { - return queryLights(); - } - //--------------------------------------------------------------------- - bool TerrainQuadTreeNode::getCastShadows(void) const - { - return TerrainGlobalOptions::getSingleton().getCastsDynamicShadows(); - } - //--------------------------------------------------------------------- - const String& TerrainQuadTreeNode::getMovableType(void) const - { - static String stype("OgreTerrainNodeMovable"); - - return stype; - - } - //--------------------------------------------------------------------- - bool TerrainQuadTreeNode::isVisible(void) const - { - if (getCurrentLod() == -1) - return false; - else - return MovableObject::isVisible(); - } -} - diff --git a/Components/Terrain/src/OgreTerrainRTShaderSRS.cpp b/Components/Terrain/src/OgreTerrainRTShaderSRS.cpp deleted file mode 100644 index ce34c82f070..00000000000 --- a/Components/Terrain/src/OgreTerrainRTShaderSRS.cpp +++ /dev/null @@ -1,349 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT -#include "OgreTerrainRTShaderSRS.h" - -#include "OgrePass.h" -#include "OgreShaderProgramSet.h" -#include "OgreShaderParameter.h" -#include "OgreMaterialSerializer.h" -#include "OgreShaderGenerator.h" -#include "OgreShaderFunction.h" -#include "OgreShaderProgram.h" -#include "OgreTerrainQuadTreeNode.h" -#include "OgreTextureManager.h" - -namespace Ogre { -using namespace RTShader; - -/************************************************************************/ -/* */ -/************************************************************************/ -String TerrainTransform::Type = "TerrainTransform"; - -bool TerrainTransform::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) -{ - auto terrainAny = srcPass->getUserObjectBindings().getUserAny("Terrain"); - mTerrain = any_cast(terrainAny); - mCompressed = mTerrain->_getUseVertexCompression(); - mAlign = mTerrain->getAlignment(); - return true; -} - -void TerrainTransform::updateParams() -{ - if(!mCompressed) - return; - - mPointTrans->setGpuParameter(mTerrain->getPointTransform()); - - float baseUVScale = 1.0f / (mTerrain->getSize() - 1); - mBaseUVScale->setGpuParameter(baseUVScale); -} - -//----------------------------------------------------------------------- -bool TerrainTransform::createCpuSubPrograms(ProgramSet* programSet) -{ - static Operand::OpMask heightAxis[3] = {Operand::OPM_Y, Operand::OPM_Z, Operand::OPM_X}; - - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Function* vsEntry = vsProgram->getEntryPointFunction(); - - auto posType = mCompressed ? GCT_INT2 : GCT_FLOAT4; - - auto wvpMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLDVIEWPROJ_MATRIX); - - auto lodMorph = vsProgram->resolveAutoParameterInt(GpuProgramParameters::ACT_CUSTOM, GCT_FLOAT2, Terrain::LOD_MORPH_CUSTOM_PARAM); - - auto positionIn = vsEntry->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE, posType); - auto positionOut = vsEntry->resolveOutputParameter(Parameter::SPC_POSITION_PROJECTIVE_SPACE); - auto uv = vsEntry->resolveOutputParameter(Parameter::SPC_TEXTURE_COORDINATE0, GCT_FLOAT2); - auto delta = vsEntry->resolveInputParameter(Parameter::SPC_TEXTURE_COORDINATE1, GCT_FLOAT2); - - // Add dependency. - vsProgram->addDependency("FFPLib_Transform"); - vsProgram->addDependency("TerrainTransforms"); - - auto stage = vsEntry->getStage(FFP_VS_TRANSFORM); - - if(mCompressed) - { - mPointTrans = vsProgram->resolveParameter(GCT_MATRIX_4X4, "pointTrans"); - mBaseUVScale = vsProgram->resolveParameter(GCT_FLOAT1, "baseUVScale"); - auto height = vsEntry->resolveInputParameter(Parameter::SPC_TEXTURE_COORDINATE0, GCT_FLOAT1); - auto position = vsEntry->resolveLocalParameter(Parameter::SPC_POSITION_OBJECT_SPACE); - - stage.callFunction("expandVertex", - {In(mPointTrans), In(mBaseUVScale), In(positionIn), In(height), Out(position), Out(uv)}); - positionIn = position; - } - else - { - auto uvin = vsEntry->resolveInputParameter(Parameter::SPC_TEXTURE_COORDINATE0, GCT_FLOAT2); - stage.assign(In(uvin).xy(), uv); - } - - stage.callBuiltin("mul", wvpMatrix, positionIn, positionOut); - stage.callFunction("applyLODMorph", {In(delta), In(lodMorph), InOut(positionOut).mask(heightAxis[mAlign])}); - - return true; -} - -String TerrainSurface::Type = "TerrainSurface"; - -bool TerrainSurface::setParameter(const String& name, const String& value) -{ - if(name == "for_composite_map") - { - return StringConverter::parse(value, mForCompositeMap); - } - else if (name == "use_parallax_mapping") - { - return StringConverter::parse(value, mUseParallaxMapping); - } - else if (name == "use_parallax_occlusion_mapping") - { - return StringConverter::parse(value, mUseParallaxOcclusionMapping); - } - else if (name == "use_specular_mapping") - { - return StringConverter::parse(value, mUseSpecularMapping); - } - else if (name == "use_normal_mapping") - { - return StringConverter::parse(value, mUseNormalMapping); - } - - return false; -} - -bool TerrainSurface::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) -{ - mTerrain = any_cast(srcPass->getUserObjectBindings().getUserAny("Terrain")); - - SamplerPtr clampSampler = TextureManager::getSingleton().createSampler(); - clampSampler->setAddressingMode(TAM_CLAMP); - - auto tu = dstPass->createTextureUnitState(); - tu->setTexture(mTerrain->getTerrainNormalMap()); - tu->setSampler(clampSampler); - - if (auto cm = mTerrain->getGlobalColourMap()) - { - tu = dstPass->createTextureUnitState(); - tu->setTexture(cm); - tu->setSampler(clampSampler); - } - - if(auto lm = mTerrain->getLightmap()) - { - tu = dstPass->createTextureUnitState(); - tu->setTexture(lm); - tu->setSampler(clampSampler); - } - - for(auto bt : mTerrain->getBlendTextures()) - { - tu = srcPass->createTextureUnitState(); - tu->setTexture(bt); - tu->setSampler(clampSampler); - } - - mUVMul.resize((mTerrain->getLayerCount() + 3) / 4); // integer ceil - - mUseNormalMapping = mUseNormalMapping && !mTerrain->getLayerTextureName(0, 1).empty(); - for (int i = 0; i < mTerrain->getLayerCount(); ++i) - { - srcPass->createTextureUnitState(mTerrain->getLayerTextureName(i, 0)); - if (mUseNormalMapping) - srcPass->createTextureUnitState(mTerrain->getLayerTextureName(i, 1)); - } - - return true; -} - -void TerrainSurface::updateParams() -{ - for (size_t i = 0; i < mUVMul.size(); i++) - { - Vector4 uvMul(mTerrain->getLayerUVMultiplier(i + 0), mTerrain->getLayerUVMultiplier(i + 1), - mTerrain->getLayerUVMultiplier(i + 2), mTerrain->getLayerUVMultiplier(i + 3)); - mUVMul[i]->setGpuParameter(uvMul); - } -} - -static Operand::OpMask channel[4] = {Operand::OPM_X, Operand::OPM_Y, Operand::OPM_Z, Operand::OPM_W}; - -//----------------------------------------------------------------------- -bool TerrainSurface::createCpuSubPrograms(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* psMain = psProgram->getMain(); - Function* vsMain = vsProgram->getMain(); - - psProgram->addDependency("FFPLib_Transform"); - psProgram->addDependency("SGXLib_NormalMap"); - psProgram->addDependency("SGXLib_IntegratedPSSM"); - psProgram->addDependency("TerrainSurface"); - - if(mUseNormalMapping) - psProgram->addPreprocessorDefines("TERRAIN_NORMAL_MAPPING"); - - auto uvVS = vsMain->resolveOutputParameter(Parameter::SPC_TEXTURE_COORDINATE0, GCT_FLOAT2); - - if (mForCompositeMap) - { - auto uvIn = vsMain->resolveInputParameter(Parameter::SPC_TEXTURE_COORDINATE0, GCT_FLOAT2); - // forward texcoords in VS - vsMain->getStage(FFP_VS_TEXTURING).assign(uvIn, uvVS); - } - - ParameterPtr viewPos; - if (mUseNormalMapping && mUseParallaxMapping) - { - psProgram->addPreprocessorDefines("TERRAIN_PARALLAX_MAPPING"); - if (mUseParallaxOcclusionMapping) - { - psProgram->addPreprocessorDefines("POM_MAX_DISTANCE=400.0,POM_LAYER_COUNT=32"); - } - - // assuming: lighting stage computed this - auto vsOutViewPos = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_VIEW_SPACE); - viewPos = psMain->resolveInputParameter(vsOutViewPos); - } - - auto uvPS = psMain->resolveInputParameter(uvVS); - uvPS->setHighP(true); - - for(auto& uvMul : mUVMul) - { - uvMul = psProgram->resolveParameter(GCT_FLOAT4, "uvMul"); - } - - int texUnit = 0; - auto globalNormal = psProgram->resolveParameter(GCT_SAMPLER2D, "globalNormal", texUnit++); - - ParameterPtr globalColourMap; - if (mTerrain->getGlobalColourMap()) - globalColourMap = psProgram->resolveParameter(GCT_SAMPLER2D, "globalColour", texUnit++); - - ParameterPtr lightMap; - if(mTerrain->getLightmap()) - lightMap = psProgram->resolveParameter(GCT_SAMPLER2D, "lightMap", texUnit++); - - auto normal = psMain->resolveLocalParameter(Parameter::SPC_NORMAL_VIEW_SPACE); - auto ITMat = psProgram->resolveParameter(GpuProgramParameters::ACT_NORMAL_MATRIX); - - auto diffuse = psMain->resolveLocalParameter(Parameter::SPC_COLOR_DIFFUSE); - auto diffuseSpec = psMain->resolveLocalParameter(GCT_FLOAT4, "diffuseSpec"); - auto TSnormal = psMain->resolveLocalParameter(GCT_FLOAT3, "TSnormal"); - auto texTmp = psMain->resolveLocalParameter(GCT_FLOAT4, "texTmp"); - - auto outDiffuse = psMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE); - - auto stage = psMain->getStage(FFP_PS_COLOUR_BEGIN); - stage.assign(Vector4(1), outDiffuse); // FFPColour logic - stage.callFunction("SGX_FetchNormal", globalNormal, uvPS, normal); - stage.callBuiltin("mul", ITMat, normal, normal); - - auto psSpecular = psMain->resolveLocalParameter(Parameter::SPC_COLOR_SPECULAR); - stage.assign(Vector4::ZERO, psSpecular); - - std::vector blendWeights; - for(auto bt : mTerrain->getBlendTextures()) - { - auto weight = psMain->resolveLocalParameter(GCT_FLOAT4, StringUtil::format("blendWeight%d", texUnit)); - auto blendTex = psProgram->resolveParameter(GCT_SAMPLER2D, "blendTex", texUnit++); - stage.sampleTexture(blendTex, uvPS, weight); - blendWeights.push_back(weight); - } - - // Call TBN calculation - auto psOutTBN = psMain->resolveLocalParameter(GpuConstantType::GCT_MATRIX_3X3, "TBN"); - stage.callFunction("SGX_CalculateTerrainTBN", {In(normal), In(ITMat), Out(psOutTBN)}); - - stage.assign(Vector4::ZERO, diffuseSpec); - stage.assign(Vector3(0, 0, 1), TSnormal); - for (int l = 0; l < mTerrain->getLayerCount(); ++l) - { - auto blendWeight = l == 0 ? In(1.0f) : In(blendWeights[(l - 1) / 4]).mask(channel[(l - 1) % 4]); - auto difftex = psProgram->resolveParameter(GCT_SAMPLER2D, "difftex", texUnit++); - std::vector args = {blendWeight, In(uvPS), In(mUVMul[l/4]).mask(channel[l % 4])}; - if (mUseNormalMapping) - { - if (mUseParallaxMapping) - { - args.push_back(In(viewPos)); - args.push_back(In(0.04)); //Scale - args.push_back(In(psOutTBN)); - } - - auto normtex = psProgram->resolveParameter(GCT_SAMPLER2D, "normtex", texUnit++); - args.push_back(In(normtex)); - args.push_back(Out(TSnormal)); - } - args.push_back(In(difftex)); - args.push_back(Out(diffuseSpec)); - stage.callFunction("blendTerrainLayer", {args}); - } - - if(mUseNormalMapping) - stage.callFunction("transformToTS", {In(TSnormal), In(ITMat), InOut(normal)}); - - // fake vertexcolour input for TVC_SPECULAR - if(mUseSpecularMapping) - stage.mul(In(diffuseSpec).w(), Vector4(1), diffuse); - - if(lightMap) - { - auto shadowFactor = psMain->getLocalParameter("lShadowFactor"); - if(!shadowFactor) - { - shadowFactor = psMain->resolveLocalParameter(GCT_FLOAT1, "lShadowFactor", 1); - psProgram->addPreprocessorDefines("SHADOWLIGHT_COUNT=1"); - } - stage = psMain->getStage(FFP_PS_COLOUR_BEGIN - 1); // before the PSSM stage - stage.assign({In(1), Out(shadowFactor), At(0)}); - - stage = psMain->getStage(FFP_PS_COLOUR_BEGIN + 1); // after the PSSM stage - stage.callFunction("getShadowFactor", {In(lightMap), In(uvPS), InOut(shadowFactor), At(0)}); - } - - if(globalColourMap) - { - stage = psMain->getStage(FFP_PS_COLOUR_BEGIN + 2); // after lighting calculations - stage.sampleTexture(globalColourMap, uvPS, texTmp); - stage.mul(In(diffuseSpec).xyz(), In(texTmp).xyz(), Out(diffuseSpec).xyz()); - } - - stage = psMain->getStage(FFP_PS_TEXTURING); - stage.mul(diffuseSpec, outDiffuse, outDiffuse); - - // FFPColour logic - psMain->getStage(FFP_PS_COLOUR_END) - .add(In(outDiffuse).xyz(), In(psSpecular).xyz(), Out(outDiffuse).xyz()); - return true; -} - -//----------------------------------------------------------------------- -const String& TerrainTransformFactory::getType() const -{ - return TerrainTransform::Type; -} -SubRenderState* TerrainTransformFactory::createInstanceImpl() -{ - return OGRE_NEW TerrainTransform(); -} - -const String& TerrainSurfaceFactory::getType() const -{ - return TerrainSurface::Type; -} -SubRenderState* TerrainSurfaceFactory::createInstanceImpl() -{ - return OGRE_NEW TerrainSurface(); -} - -} \ No newline at end of file diff --git a/Components/Terrain/src/OgreTerrainRTShaderSRS.h b/Components/Terrain/src/OgreTerrainRTShaderSRS.h deleted file mode 100644 index 8a260522c2d..00000000000 --- a/Components/Terrain/src/OgreTerrainRTShaderSRS.h +++ /dev/null @@ -1,80 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT -#ifndef _ShaderTerrainTransform_ -#define _ShaderTerrainTransform_ - -#include "OgreTerrainPrerequisites.h" - -#include "OgreShaderSubRenderState.h" -#include "OgreShaderParameter.h" -#include "OgreShaderFFPRenderState.h" -#include "OgreTerrain.h" - -namespace Ogre { - -class TerrainTransform : public RTShader::SubRenderState -{ -public: - const String& getType() const override { return Type; } - int getExecutionOrder() const override { return RTShader::FFP_TRANSFORM; } - void copyFrom(const SubRenderState& rhs) override {} - bool createCpuSubPrograms(RTShader::ProgramSet* programSet) override; - bool preAddToRenderState(const RTShader::RenderState* renderState, Pass* srcPass, Pass* dstPass) override; - void updateParams(); - - static String Type; -private: - const Terrain* mTerrain; - bool mCompressed = false; - Terrain::Alignment mAlign = Terrain::ALIGN_X_Z; - RTShader::UniformParameterPtr mPointTrans; - RTShader::UniformParameterPtr mBaseUVScale; -}; - -class TerrainSurface : public RTShader::SubRenderState -{ -public: - const String& getType() const override { return Type; } - int getExecutionOrder() const override { return RTShader::FFP_LIGHTING - 1; } - void copyFrom(const SubRenderState& rhs) override - { - mUseNormalMapping = static_cast(rhs).mUseNormalMapping; - } - bool createCpuSubPrograms(RTShader::ProgramSet* programSet) override; - bool preAddToRenderState(const RTShader::RenderState* renderState, Pass* srcPass, Pass* dstPass) override; - void updateParams(); - bool setParameter(const String& name, const String& value) override; - - static String Type; -protected: - const Terrain* mTerrain; - std::vector mUVMul; - bool mUseNormalMapping = true; - bool mUseSpecularMapping = false; - bool mUseParallaxMapping = false; - bool mUseParallaxOcclusionMapping = false; - bool mForCompositeMap = false; - int mNumLayers = 0; -}; - -class TerrainSurfaceFactory : public RTShader::SubRenderStateFactory -{ -public: - const String& getType() const override; - -protected: - RTShader::SubRenderState* createInstanceImpl() override; -}; - -class TerrainTransformFactory : public RTShader::SubRenderStateFactory -{ -public: - const String& getType() const override; - -protected: - RTShader::SubRenderState* createInstanceImpl() override; -}; -} -#endif diff --git a/Components/Volume/CMakeLists.txt b/Components/Volume/CMakeLists.txt deleted file mode 100644 index a944276c322..00000000000 --- a/Components/Volume/CMakeLists.txt +++ /dev/null @@ -1,37 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -############################################################ -# Volume optional component -############################################################ - -# define header and source files for the library -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES ${PROJECT_BINARY_DIR}/include/OgreVolumePrerequisites.h) -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") - -# setup target -add_library(OgreVolume ${OGRE_COMP_LIB_TYPE} ${HEADER_FILES} ${SOURCE_FILES} ${PLATFORM_HEADER_FILES} ${PLATFORM_SOURCE_FILES}) -set_target_properties(OgreVolume PROPERTIES VERSION ${OGRE_SOVERSION} SOVERSION ${OGRE_SOVERSION}) -target_link_libraries(OgreVolume PUBLIC OgreMain) -target_include_directories(OgreVolume PUBLIC - "$" - $) - -generate_export_header(OgreVolume - EXPORT_MACRO_NAME _OgreVolumeExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreVolumePrerequisites.h) - -# install -ogre_config_framework(OgreVolume) -ogre_config_component(OgreVolume) - -install(FILES ${HEADER_FILES} - DESTINATION include/OGRE/Volume -) diff --git a/Components/Volume/include/OgreVolumeCSGSource.h b/Components/Volume/include/OgreVolumeCSGSource.h deleted file mode 100644 index b768f29e057..00000000000 --- a/Components/Volume/include/OgreVolumeCSGSource.h +++ /dev/null @@ -1,479 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Ogre_Volume_CSGSource_H__ -#define __Ogre_Volume_CSGSource_H__ - -#include "OgreVolumeSource.h" -#include "OgreVector.h" -#include "OgreAxisAlignedBox.h" -#include "OgreVolumePrerequisites.h" -#include "OgreVolumeSimplexNoise.h" - -namespace Ogre { -namespace Volume { - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Volume - * @{ - */ - /** A sphere. - */ - class _OgreVolumeExport CSGSphereSource : public Source - { - protected: - /** The radius. - */ - const Real mR; - - /** The center. - */ - const Vector3 mCenter; - public: - - /** Constructor. - @param r - The radius. - @param center - The center. - */ - CSGSphereSource(const Real r, const Vector3 ¢er); - - /** Overridden from Source. - */ - Vector4 getValueAndGradient(const Vector3 &position) const override; - - /** Overridden from Source. - */ - Real getValue(const Vector3 &position) const override; - }; - - /** A plane. - */ - class _OgreVolumeExport CSGPlaneSource : public Source - { - protected: - - /// The distance to zero of the plane. - const Real mD; - - /// The normal of the plane. - Vector3 mNormal; - - public: - - /** Constructor. - @param d - The distance to zero of the plane. - @param normal - The planes normal. - */ - CSGPlaneSource(const Real d, const Vector3 &normal); - - /** Overridden from Source. - */ - Vector4 getValueAndGradient(const Vector3 &position) const override; - - /** Overridden from Source. - */ - Real getValue(const Vector3 &position) const override; - }; - - /** A not rotated cube. - */ - class _OgreVolumeExport CSGCubeSource : public Source - { - protected: - - /// The six possible normals of the cube. - static Vector3 mBoxNormals[6]; - - /// The box. - AxisAlignedBox mBox; - - /** Gets the distance of a point to the nearest cube element. - @param position - The point to test. - @return - The distance. - */ - inline Real distanceTo(const Vector3 &position) const - { - Real distance; - const Vector3 dMin = position - mBox.getMinimum(); - const Vector3 dMax = mBox.getMaximum() - position; - - // Check if inside of the box - if (dMin.x >= (Real)0.0 && dMin.y >= (Real)0.0 && dMin.z >= (Real)0.0 && - dMax.x >= (Real)0.0 && dMax.y >= (Real)0.0 && dMax.z >= (Real)0.0) - { - const Real d[6] = {dMin.x, dMin.y, dMin.z, dMax.x, dMax.y, dMax.z}; - distance = Math::POS_INFINITY; - for (size_t i = 0; i < 6; ++i) - { - if (d[i] < distance) - { - distance = d[i]; - } - } - } - else - { - distance = -mBox.distance(position); - } - return distance; - } - - public: - - /** Constructor. - @param min - The lower back left corner. - @param max - The upper front right corner. - */ - CSGCubeSource(const Vector3 &min, const Vector3 &max); - - /** Overridden from Source. - */ - Vector4 getValueAndGradient(const Vector3 &position) const override; - - /** Overridden from Source. - */ - Real getValue(const Vector3 &position) const override; - }; - - /** Abstract operation volume source holding two sources as operants. - */ - class _OgreVolumeExport CSGOperationSource : public Source - { - protected: - - /// The first operant. - const Source *mA; - - /// The second operant. - const Source *mB; - - /** Constructor. Protected to be callable from child classes. - @param a - The first operator. - @param b - The second operator. - */ - CSGOperationSource(const Source *a, const Source *b); - - /** Constructor, sets the sources to null. - Protected to be callable from child classes. - */ - CSGOperationSource(void); - public: - - /** Gets the first operator source. - @return - The first operator source. - */ - virtual const Source* getSourceA() const; - - /** Sets the first operator source. - @param a - The first operator source. - */ - virtual void setSourceA(Source *a); - - /** Gets the second operator source. - @return - The second operator source. - */ - virtual const Source* getSourceB(void) const; - - /** Sets the second operator source. - @param b - The second operator source. - */ - virtual void setSourceB(Source *b); - }; - - /** Builds the intersection between two sources. - */ - class _OgreVolumeExport CSGIntersectionSource : public CSGOperationSource - { - public: - - /** Constructor. - @param a - The first operator. - @param b - The second operator. - */ - CSGIntersectionSource(const Source *a, const Source *b); - - /** Constructor, sets the sources to null. - */ - CSGIntersectionSource(void); - - /** Overridden from Source. - */ - Vector4 getValueAndGradient(const Vector3 &position) const override; - - /** Overridden from Source. - */ - Real getValue(const Vector3 &position) const override; - }; - - /** Builds the union between two sources. - */ - class _OgreVolumeExport CSGUnionSource : public CSGOperationSource - { - public: - - /** Constructor. - @param a - The first operator. - @param b - The second operator. - */ - CSGUnionSource(const Source *a, const Source *b); - - /** Constructor, sets the sources to null. - */ - CSGUnionSource(void); - - /** Overridden from Source. - */ - Vector4 getValueAndGradient(const Vector3 &position) const override; - - /** Overridden from Source. - */ - Real getValue(const Vector3 &position) const override; - }; - - /** Builds the difference between two sources. - */ - class _OgreVolumeExport CSGDifferenceSource : public CSGOperationSource - { - public: - - - /** Constructor. - @param a - The first operator. - @param b - The second operator. - */ - CSGDifferenceSource(const Source *a, const Source *b); - - /** Constructor, sets the sources to null. - */ - CSGDifferenceSource(void); - - /** Overridden from Source. - */ - Vector4 getValueAndGradient(const Vector3 &position) const override; - - /** Overridden from Source. - */ - Real getValue(const Vector3 &position) const override; - }; - - /** Source which does a unary operation to another one. - */ - class _OgreVolumeExport CSGUnarySource : public Source - { - protected: - - /// The first operant. - const Source *mSrc; - - /** Constructor. Protected to be callable from child classes. - @param src - The operator. - */ - CSGUnarySource(const Source *src); - - /** Constructor. Sets the source to null. - Protected to be callable from child classes. - */ - CSGUnarySource(void); - - public: - - /** Gets the source. - @return - The source. - */ - virtual const Source* getSource(void) const; - - /** Sets the source. - @param a - The source. - */ - virtual void setSource(Source *a); - }; - - /** Negates the given volume. - */ - class _OgreVolumeExport CSGNegateSource : public CSGUnarySource - { - public: - - /** Constructor. - @param src - The source to negate. - */ - explicit CSGNegateSource(const Source *src); - - /** Constructor. Sets the source to null. - */ - CSGNegateSource(void); - - /** Overridden from Source. - */ - Vector4 getValueAndGradient(const Vector3 &position) const override; - - /** Overridden from Source. - */ - Real getValue(const Vector3 &position) const override; - }; - - /** Scales the given volume source. - */ - class _OgreVolumeExport CSGScaleSource : public CSGUnarySource - { - protected: - - /// Holds the dimensions of the volume. - Real mScale; - public: - - /** Constructor. - @param src - The source to scale. - @param scale - The scale of the source. - */ - CSGScaleSource(const Source *src, const Real scale); - - /** Overridden from Source. - */ - Vector4 getValueAndGradient(const Vector3 &position) const override; - - /** Overridden from Source. - */ - Real getValue(const Vector3 &position) const override; - }; - - class _OgreVolumeExport CSGNoiseSource: public CSGUnarySource - { - protected: - - /// The frequencies of the octaves. - Real *mFrequencies; - - /// The amplitudes of the octaves. - Real *mAmplitudes; - - /// The amount of octaves. - size_t mNumOctaves; - - /// To make some noise. - SimplexNoise mNoise; - - /// To calculate the gradient. - Real mGradientOff; - - /// The initial seed. - long mSeed; - - /// Prepares the node members. - void setData(void); - - /* Gets the density value. - @param position - The position of the value. - @return - The value. - */ - inline Real getInternalValue(const Vector3 &position) const - { - Real toAdd = (Real)0.0; - for (size_t i = 0; i < mNumOctaves; ++i) - { - toAdd += mNoise.noise(position.x * mFrequencies[i], position.y * mFrequencies[i], position.z * mFrequencies[i]) * mAmplitudes[i]; - } - return mSrc->getValue(position) + toAdd; - } - - public: - - /** Constructor. - @param src - The source to add the noise to. - @param frequencies - The frequencies of the added noise octaves. - @param amplitudes - The amplitudes of the added noise octaves. - @param numOctaves - The amount of octaves. - @param seed - The seed to initialize the random number generator with. - */ - CSGNoiseSource(const Source *src, Real *frequencies, Real *amplitudes, size_t numOctaves, long seed); - - /** Constructor with current time as seed. - @param src - The source to add the noise to. - @param frequencies - The frequencies of the added noise octaves. - @param amplitudes - The amplitudes of the added noise octaves. - @param numOctaves - The amount of octaves. - */ - CSGNoiseSource(const Source *src, Real *frequencies, Real *amplitudes, size_t numOctaves); - - /** Overridden from Source. - */ - Vector4 getValueAndGradient(const Vector3 &position) const override; - - /** Overridden from Source. - */ - Real getValue(const Vector3 &position) const override; - - /** Gets the initial seed. - @return - The initial seed. - */ - long getSeed(void) const; - }; - /** @} */ - /** @} */ -} -} - -#endif diff --git a/Components/Volume/include/OgreVolumeCacheSource.h b/Components/Volume/include/OgreVolumeCacheSource.h deleted file mode 100644 index a357debbd9b..00000000000 --- a/Components/Volume/include/OgreVolumeCacheSource.h +++ /dev/null @@ -1,111 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Ogre_Volume_CacheSource_H__ -#define __Ogre_Volume_CacheSource_H__ - -#include "OgreVector.h" - -#include "OgreVolumeSource.h" -#include "OgreVolumePrerequisites.h" - -namespace Ogre { -namespace Volume { - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Volume - * @{ - */ - /** A less operator. - @note - This operator is needed so that Vertex can serve as the key in a map structrue - @param a - The first vector to test. - @param b - The second vector to test. - */ - bool _OgreVolumeExport operator<(const Vector3& a, const Vector3& b); - - /** A caching Source. - */ - class _OgreVolumeExport CacheSource : public Source - { - protected: - - /// Map for the cache - typedef std::map UMapPositionValue; - mutable UMapPositionValue mCache; - - /// The source to cache. - const Source *mSrc; - - /** Gets a density value and gradient from the cache. - @param position - The position of the density value and gradient. - @return - The density value (w-component) and the gradient (x, y and z component). - */ - inline Vector4 getFromCache(const Vector3 &position) const - { - Vector4 result; - std::map::iterator it = mCache.find(position); - if (it == mCache.end()) - { - result = mSrc->getValueAndGradient(position); - mCache[position] = result; - } - else - { - result = it->second; - } - return result; - } - - public: - - /** Constructor. - @param src - The source to cache. - */ - CacheSource(const Source *src); - - /** Overridden from Source. - */ - Vector4 getValueAndGradient(const Vector3 &position) const override; - - /** Overridden from Source. - */ - Real getValue(const Vector3 &position) const override; - - }; - /** @} */ - /** @} */ -} -} - -#endif diff --git a/Components/Volume/include/OgreVolumeChunk.h b/Components/Volume/include/OgreVolumeChunk.h deleted file mode 100644 index 374765ed71c..00000000000 --- a/Components/Volume/include/OgreVolumeChunk.h +++ /dev/null @@ -1,486 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Ogre_Volume_Chunk_H__ -#define __Ogre_Volume_Chunk_H__ - -#include "OgreSimpleRenderable.h" -#include "OgreResourceGroupManager.h" -#include "OgreFrameListener.h" -#include "OgreEntity.h" - -#include "OgreVolumePrerequisites.h" - -namespace Ogre { -namespace Volume { - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Volume - * @{ - */ - class Source; - class MeshBuilderCallback; - class ChunkHandler; - class MeshBuilder; - class DualGridGenerator; - class OctreeNode; - - /** Parameters for loading the volume. - */ - typedef struct ChunkParameters - { - /// The scenemanager to construct the entity with. - SceneManager *sceneManager; - - /// The volume source. - Source *src; - - /// The smallest allowed geometric error of the highest LOD. - Real baseError; - - /// The error multiplicator per LOD level with 1.0 as default. - Real errorMultiplicator; - - /// Whether to create the octree debug visualization entity with false as default. - bool createOctreeVisualization; - - /// Whether to create the dualgrid debug visualization entity with false as default. - bool createDualGridVisualization; - - /// Factor for the skirt length generation. - Real skirtFactor; - - /// Callback for a specific LOD level. - MeshBuilderCallback *lodCallback; - - /// The scale of the volume with 1.0 as default. - Real scale; - - /// The maximum accepted screen space error when choosing the LOD levels to render. - Real maxScreenSpaceError; - - /// The first LOD level to create geometry for. For scenarios where the lower levels won't be visible anyway. 0 is the default and switches this off. - size_t createGeometryFromLevel; - - /// If an existing chunktree is to be partially updated, set this to the back lower left point of the (sub-)cube to be reloaded. Else, set both update vectors to zero (initial load). 1.5 is the default. - Vector3 updateFrom; - - /// If an existing chunktree is to be partially updated, set this to the front upper right point of the (sub-)cube to be reloaded. Else, set both update vectors to zero (initial load). - Vector3 updateTo; - - /// Whether to load the chunks async. if set to false, the call to load waits for the whole chunk. false is the default. - bool async; - - /** Constructor. - */ - ChunkParameters(void) : - sceneManager(0), src(0), baseError((Real)0.0), errorMultiplicator((Real)1.0), createOctreeVisualization(false), - createDualGridVisualization(false), skirtFactor(0), lodCallback(0), scale((Real)1.0), maxScreenSpaceError(0), createGeometryFromLevel(0), - updateFrom(Vector3::ZERO), updateTo(Vector3::ZERO), async(false) - { - } - } ChunkParameters; - - /** Internal shared values of the chunks which are equal in the whole tree. - */ - typedef struct ChunkTreeSharedData - { - /// Flag whether the octree is visible or not. - bool octreeVisible; - - /// Flag whether the dualgrid is visible or not. - bool dualGridVisible; - - /// Another visibility flag to be user setable. - bool volumeVisible; - - /// The amount of chunks being processed (== loading). - int chunksBeingProcessed; - - /// The parameters with which the chunktree got loaded. - ChunkParameters *parameters; - - /** Constructor. - */ - ChunkTreeSharedData(const ChunkParameters *params) : octreeVisible(false), dualGridVisible(false), volumeVisible(true), chunksBeingProcessed(0) - { - this->parameters = new ChunkParameters(*params); - } - - /** Destructor. - */ - ~ChunkTreeSharedData(void) - { - delete parameters; - } - - } ChunkTreeSharedData; - - /** A single volume chunk mesh. - */ - class _OgreVolumeExport Chunk : public SimpleRenderable, public FrameListener - { - /** Data being passed around while loading. - */ - struct ChunkRequest - { - - /// The back lower left corner of the world. - Vector3 totalFrom; - - /// The front upper rightcorner of the world. - Vector3 totalTo; - - /// The current LOD level. - size_t level; - - /// The maximum amount of levels. - size_t maxLevels; - - /// The MeshBuilder to use. - MeshBuilder *meshBuilder; - - /// The DualGridGenerator to use. - DualGridGenerator *dualGridGenerator; - - /// The octree node to use. - OctreeNode *root; - - /// Whether this is an update of an existing tree - bool isUpdate; - }; - - protected: - /// To attach this node to. - SceneNode *mNode; - - /// Holds the error associated with this chunk. - Real mError; - - /// Holds the dualgrid debug visualization. - Entity *mDualGrid; - - /// The debug visualization of the octree. - Entity *mOctree; - - /// The more detailed children chunks. - Chunk **mChildren; - - /// Flag whether this node will never be shown. - bool mInvisible; - - /// Whether this chunk is the root of the tree. - bool isRoot; - - /// Holds some shared data among all chunks of the tree. - ChunkTreeSharedData *mShared; - - /** Loads a single chunk of the tree. - @param parent - The parent scene node for the volume - @param from - The back lower left corner of the cell. - @param to - The front upper right corner of the cell. - @param totalFrom - The back lower left corner of the world. - @param totalTo - The front upper rightcorner of the world. - @param level - The current LOD level. - @param maxLevels - The maximum amount of levels. - */ - virtual void loadChunk(SceneNode *parent, const Vector3 &from, const Vector3 &to, const Vector3 &totalFrom, const Vector3 &totalTo, const size_t level, const size_t maxLevels); - - /** Whether the center of the given cube (from -> to) will contribute something - to the total volume mesh. - @param from - The back lower left corner of the cell. - @param to - The front upper right corner of the cell. - @return - true if triangles might be generated - */ - virtual bool contributesToVolumeMesh(const Vector3 &from, const Vector3 &to) const; - - /** Loads the tree children of the current node. - @param parent - The parent scene node for the volume - @param from - The back lower left corner of the cell. - @param to - The front upper right corner of the cell. - @param totalFrom - The back lower left corner of the world. - @param totalTo - The front upper rightcorner of the world. - @param level - The current LOD level. - @param maxLevels - The maximum amount of levels. - */ - virtual void loadChildren(SceneNode *parent, const Vector3 &from, const Vector3 &to, const Vector3 &totalFrom, const Vector3 &totalTo, const size_t level, const size_t maxLevels); - - /** Actually loads the volume tree with all LODs. - @param parent - The parent scene node for the volume - @param from - The back lower left corner of the cell. - @param to - The front upper right corner of the cell. - @param totalFrom - The back lower left corner of the world. - @param totalTo - The front upper rightcorner of the world. - @param level - The current LOD level. - @param maxLevels - The maximum amount of levels. - */ - virtual void doLoad(SceneNode *parent, const Vector3 &from, const Vector3 &to, const Vector3 &totalFrom, const Vector3 &totalTo, const size_t level, const size_t maxLevels); - - /** Prepares the geometry of the chunk request. To be called in a different thread. - @param level - The current LOD level. - @param root - The root of the upcoming Octree (in here) of the chunk. - @param dualGridGenerator - The DualGrid. - @param meshBuilder - The MeshBuilder which will contain the geometry. - @param totalFrom - The back lower left corner of the world. - @param totalTo - The front upper rightcorner of the world. - */ - virtual void prepareGeometry(size_t level, OctreeNode *root, DualGridGenerator *dualGridGenerator, MeshBuilder *meshBuilder, const Vector3 &totalFrom, const Vector3 &totalTo); - - /** Loads the actual geometry when the processing is done. - @param meshBuilder - The MeshBuilder holding the geometry. - @param dualGridGenerator - The DualGridGenerator to build up the debug visualization of the DualGrid. - @param root - The root node of the Octree to build up the debug visualization of the Otree. - @param level - The current LOD level. - @param isUpdate - Whether this loading is updating an existing ChunkTree. - */ - virtual void loadGeometry(MeshBuilder *meshBuilder, DualGridGenerator *dualGridGenerator, OctreeNode *root, size_t level, bool isUpdate); - - /** Sets the visibility of this chunk. - @param visible - Whether this chunk is visible or not. - @param applyToChildren - Whether all children and subchildren should have their visibility changed, too. - */ - inline void setChunkVisible(const bool visible, const bool applyToChildren) - { - if (mInvisible) - { - return; - } - if (mShared->volumeVisible) - { - mVisible = visible; - } - if (mOctree) - { - mOctree->setVisible(mShared->octreeVisible && visible); - } - if (mDualGrid) - { - mDualGrid->setVisible(mShared->dualGridVisible && visible); - } - if (applyToChildren && mChildren) - { - mChildren[0]->setChunkVisible(visible, applyToChildren); - if (mChildren[1]) - { - mChildren[1]->setChunkVisible(visible, applyToChildren); - mChildren[2]->setChunkVisible(visible, applyToChildren); - mChildren[3]->setChunkVisible(visible, applyToChildren); - mChildren[4]->setChunkVisible(visible, applyToChildren); - mChildren[5]->setChunkVisible(visible, applyToChildren); - mChildren[6]->setChunkVisible(visible, applyToChildren); - mChildren[7]->setChunkVisible(visible, applyToChildren); - } - } - } - - public: - - /// The type name. - static const String MOVABLE_TYPE_NAME; - - /** Constructor. - */ - Chunk(void); - - /** Destructor. - */ - virtual ~Chunk(void); - - /** Overridden from MovableObject. - */ - const String& getMovableType(void) const override; - - /** Overridden from Renderable. - */ - Real getSquaredViewDepth(const Camera* camera) const override; - - /** Overridden from MovableObject. - */ - Real getBoundingRadius() const override; - - /** Loads the volume mesh with all LODs. - @param parent - The parent scene node for the volume - @param from - The back lower left corner of the cell. - @param to - The front upper right corner of the cell. - @param level - The amount of LOD level. - @param parameters - The parameters to use while loading. - */ - virtual void load(SceneNode *parent, const Vector3 &from, const Vector3 &to, size_t level, const ChunkParameters *parameters); - - /** Loads a TextureSource volume scene from a config file. - @param parent - The parent scene node for the volume. - @param sceneManager - The scenemanager to construct the entity with. - @param filename - The filename of the configuration file. - @param validSourceResult - If you want to use the loaded source afterwards of the parameters, set this to true. Beware, that you - will have to delete the pointer on your own then! On false here, it internally frees the - memory for you - @param lodCallback - Callback for a specific LOD level. - @param resourceGroup - The resource group where to search for the configuration file. - */ - virtual void load(SceneNode *parent, SceneManager *sceneManager, const String& filename, bool validSourceResult = false, MeshBuilderCallback *lodCallback = 0, const String& resourceGroup = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME); - - /** Shows the debug visualization entity of the dualgrid. - @param visible - Whether the grid should be visible. - */ - virtual void setDualGridVisible(const bool visible); - - /** Gets whether the debug visualization entity of the - dualgrid is visible. - @return - true if visible. - */ - virtual bool getDualGridVisible(void) const; - - /** Shows the debug visualization entity of the octree. - @param visible - Whether the octree should be visible. - */ - virtual void setOctreeVisible(const bool visible); - - /** Gets whether the debug visualization entity of the - octree is visible. - @return - true if visible. - */ - virtual bool getOctreeVisible(void) const; - - /** Sets whether the volume mesh is visible. - @param visible - true if visible - */ - virtual void setVolumeVisible(const bool visible); - - /** Gets whether the volume mesh is visible. - @return - true if visible - */ - virtual bool getVolumeVisible(void) const; - - /** Overridden from FrameListener. - */ - bool frameStarted(const FrameEvent& evt) override; - - /** Overridable factory method. - @return - The created chunk. - */ - virtual Chunk* createInstance(void); - - /** Overridden from SimpleRenderable. - Sets the material of this chunk and all of his children. - */ - void setMaterial(const MaterialPtr& mat) override; - - /// @overload - using Ogre::SimpleRenderable::setMaterial; - - /** Sets the material of all chunks of a specific level in the tree. - This allows LODs where the lower levels (== less detail and more far away) - have simpler materials. - @param level - The tree level getting the material, 0 based. 0 means the chunk with the lowest level of detail. - @param mat - The material name to set. - */ - void setMaterialOfLevel(size_t level, const MaterialPtr& mat); - - /** A list of Chunks. - */ - typedef std::vector VecChunk; - - /** Gathers all visible chunks (containing triangles) of a specific LOD level. - @param level - The desired chunk level, 0 based. 0 means the chunk with the lowest level of detail. If the chunks are loaded with - a level amount of 5, valid values here are 0-4. - @param result - Vector where the chunks will be added to. - */ - virtual void getChunksOfLevel(const size_t level, VecChunk &result) const; - - /** Gets the parameters with which the chunktree got loaded. - @return - The parameters. - */ - ChunkParameters* getChunkParameters(void); - - }; - /** @} */ - /** @} */ -} -} - -#endif diff --git a/Components/Volume/include/OgreVolumeDualGridGenerator.h b/Components/Volume/include/OgreVolumeDualGridGenerator.h deleted file mode 100644 index 844eecbc392..00000000000 --- a/Components/Volume/include/OgreVolumeDualGridGenerator.h +++ /dev/null @@ -1,358 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Ogre_Volume_DualGridGenerator_H__ -#define __Ogre_Volume_DualGridGenerator_H__ - -#include - -#include "OgreVolumeOctreeNode.h" -#include "OgreVolumePrerequisites.h" -#include "OgreVolumeIsoSurface.h" - -namespace Ogre { -namespace Volume { - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Volume - * @{ - */ - /** To store the generated dual cells in a vector. - */ - typedef struct _OgreVolumeExport DualCell - { - public: - Vector3 mC0; - Vector3 mC1; - Vector3 mC2; - Vector3 mC3; - Vector3 mC4; - Vector3 mC5; - Vector3 mC6; - Vector3 mC7; - DualCell(const Vector3 &c0, const Vector3 &c1, const Vector3 &c2, const Vector3 &c3, const Vector3 &c4, const Vector3 &c5, const Vector3 &c6, const Vector3 &c7) : - mC0(c0), mC1(c1), mC2(c2), mC3(c3), mC4(c4), mC5(c5), mC6(c6), mC7(c7) - { - } - } DualCell; - - /** To hold dual cells. - */ - typedef std::vector VecDualCell; - - /** Class for the generation of the DualGrid. - */ - class _OgreVolumeExport DualGridGenerator : public UtilityAlloc - { - protected: - - /// To give the debug manual object an unique name. - static size_t mDualGridI; - - /// The entity for the debug visualization of the grid. - Entity* mDualGrid; - - /// Starting node to generate the grid from. - OctreeNode const* mRoot; - - /// Holds the generated dual cells of the grid. - VecDualCell mDualCells; - - /// Whether to store the dualcells for later visualization. - bool mSaveDualCells; - - /// To contour the dualcells. - IsoSurface *mIs; - - /// To store the triangles of the contour. - MeshBuilder *mMb; - - /// The maximum distance where to generate the skirts. - Real mMaxMSDistance; - - /// The global from. - Vector3 mTotalFrom; - - /// The total to. - Vector3 mTotalTo; - - /** Adds a dualcell. - @param c0 - The first corner. - @param c1 - The second corner. - @param c2 - The third corner. - @param c3 - The fourth corner. - @param c4 - The fifth corner. - @param c5 - The sixth corner. - @param c6 - The seventh corner. - */ - inline void addDualCell(const Vector3 &c0, const Vector3 &c1, const Vector3 &c2, const Vector3 &c3, const Vector3 &c4, const Vector3 &c5, const Vector3 &c6, const Vector3 &c7) - { - addDualCell(c0, c1, c2, c3, c4, c5, c6, c7, 0); - } - - /** Adds a dualcell with precalculated values. - @param c0 - The first corner. - @param c1 - The second corner. - @param c2 - The third corner. - @param c3 - The fourth corner. - @param c4 - The fifth corner. - @param c5 - The sixth corner. - @param c6 - The seventh corner. - @param c7 - The eighth corner. - @param values - The (possible) values at the corners. - */ - inline void addDualCell(const Vector3 &c0, const Vector3 &c1, const Vector3 &c2, const Vector3 &c3, const Vector3 &c4, const Vector3 &c5, const Vector3 &c6, const Vector3 &c7, - Vector4 *values) - { - - if (mSaveDualCells) - { - mDualCells.push_back(DualCell(c0, c1, c2, c3, c4, c5, c6, c7)); - } - - Vector3 corners[8]; - corners[0] = c0; - corners[1] = c1; - corners[2] = c2; - corners[3] = c3; - corners[4] = c4; - corners[5] = c5; - corners[6] = c6; - corners[7] = c7; - mIs->addMarchingCubesTriangles(corners, values, mMb); - Vector3 from = mRoot->getFrom(); - Vector3 to = mRoot->getTo(); - if (corners[0].z == from.z && corners[0].z != mTotalFrom.z) - { - mIs->addMarchingSquaresTriangles(corners, values, IsoSurface::MS_CORNERS_BACK, mMaxMSDistance, mMb); - } - if (corners[2].z == to.z && corners[2].z != mTotalTo.z) - { - mIs->addMarchingSquaresTriangles(corners, values, IsoSurface::MS_CORNERS_FRONT, mMaxMSDistance, mMb); - } - if (corners[0].x == from.x && corners[0].x != mTotalFrom.x) - { - mIs->addMarchingSquaresTriangles(corners, values, IsoSurface::MS_CORNERS_LEFT, mMaxMSDistance, mMb); - } - if (corners[1].x == to.x && corners[1].x != mTotalTo.x) - { - mIs->addMarchingSquaresTriangles(corners, values, IsoSurface::MS_CORNERS_RIGHT, mMaxMSDistance, mMb); - } - if (corners[5].y == to.y && corners[5].y != mTotalTo.y) - { - mIs->addMarchingSquaresTriangles(corners, values, IsoSurface::MS_CORNERS_TOP, mMaxMSDistance, mMb); - } - if (corners[0].y == from.y && corners[0].y != mTotalFrom.y) - { - mIs->addMarchingSquaresTriangles(corners, values, IsoSurface::MS_CORNERS_BOTTOM, mMaxMSDistance, mMb); - } - } - - /* Startpoint for the creation recursion. - @param n - The node to start with. - */ - void nodeProc(const OctreeNode *n); - - /* faceProc with variing X and Y of the nodes, see the paper for faceProc(). - Direction of parameters: Z+ (n0 and n3 for example of parent cell) - @param n0 - The first node. - @param n1 - The second node. - */ - void faceProcXY(const OctreeNode *n0, const OctreeNode *n1); - - /* faceProc with variing Z and Y of the nodes, see the paper for faceProc(). - Direction of parameters: X+ (n0 and n1 for example of parent cell) - @param n0 - The first node. - @param n1 - The second node. - */ - void faceProcZY(const OctreeNode *n0, const OctreeNode *n1); - - /* faceProc with variing X and Z of the nodes, see the paper for faceProc(). - Direction of parameters: Y- (n4 and n0 for example of parent cell) - @param n0 - The first node. - @param n1 - The second node. - */ - void faceProcXZ(const OctreeNode *n0, const OctreeNode *n1); - - /** edgeProc with variing X of the nodes, see the paper for edgeProc(). - Direction of parameters: Z+, Y around the clock (n0, n3, n7, n4 for example of the parent cell) - @param n0 - The first node. - @param n1 - The second node. - @param n2 - The third node. - @param n3 - The fourth node. - */ - void edgeProcX(const OctreeNode *n0, const OctreeNode *n1, const OctreeNode *n2, const OctreeNode *n3); - - /** edgeProc with variing Y of the nodes, see the paper for edgeProc(). - Direction of parameters: X+, Z around the clock (n0, n1, n2, n3 for example of the parent cell) - @param n0 - The first node. - @param n1 - The second node. - @param n2 - The third node. - @param n3 - The fourth node. - */ - void edgeProcY(const OctreeNode *n0, const OctreeNode *n1, const OctreeNode *n2, const OctreeNode *n3); - - /** edgeProc with variing Z of the nodes, see the paper for edgeProc(). - Direction of parameters: X+, Y around the clock (n7, n6, n2, n3 for example of the parent cell) - @param n0 - The first node. - @param n1 - The second node. - @param n2 - The third node. - @param n3 - The fourth node. - */ - void edgeProcZ(const OctreeNode *n0, const OctreeNode *n1, const OctreeNode *n2, const OctreeNode *n3); - - /* vertProc of the nodes, see the paper for vertProc. Difference to the paper: The cells to the - octree border are already created here and not with another traversion. - @param n0 - The first node. - @param n1 - The second node. - @param n3 - The third node. - @param n4 - The fourth node. - @param n5 - The fifth node. - @param n6 - The sixth node. - @param n7 - The seventh node. - */ - void vertProc(const OctreeNode *n0, const OctreeNode *n1, const OctreeNode *n2, const OctreeNode *n3, const OctreeNode *n4, const OctreeNode *n5, const OctreeNode *n6, const OctreeNode *n7); - - /* Creates the bordercells. - @param n0 - The first node. - @param n1 - The second node. - @param n3 - The third node. - @param n4 - The fourth node. - @param n5 - The fifth node. - @param n6 - The sixth node. - @param n7 - The seventh node. - */ - void createBorderCells(const OctreeNode *n0, const OctreeNode *n1, const OctreeNode *n2, const OctreeNode *n3, const OctreeNode *n4, const OctreeNode *n5, const OctreeNode *n6, const OctreeNode *n7); - - public: - - /** Constructor. - */ - DualGridGenerator(void); - - /** Generates the dualgrid of the given octree root node. - @param root - The octree root node. - @param is - To contour the dualcells. - @param mb - To store the triangles of the contour. - @param maxMSDistance - The maximum distance to the isosurface where to generate skirts. - @param totalFrom - The global from. - @param totalTo - The global to. - @param saveDualCells - Whether to save the generated dualcells of the generated dual cells. - */ - void generateDualGrid(const OctreeNode *root, IsoSurface *is, MeshBuilder *mb, Real maxMSDistance, const Vector3 &totalFrom, const Vector3 &totalTo, bool saveDualCells); - - /** Gets the lazily created entity of the dualgrid debug visualization. - @param sceneManager - The scenemanager creating the entity. - @return - The entity. Might be null if no dualcells are available. - */ - Entity* getDualGrid(SceneManager *sceneManager); - - /** Gets the amount of generated dual cells. - @return - The amount of generated dual cells. - */ - inline size_t getDualCellCount(void) const - { - return mDualCells.size(); - } - - /** Gets a dual cell. - @param i - The index of the wanted dual cell. - @return - The dual cell. - */ - inline DualCell getDualCell(size_t i) const - { - return mDualCells[i]; - } - }; - /** @} */ - /** @} */ -} -} - -#endif diff --git a/Components/Volume/include/OgreVolumeGridSource.h b/Components/Volume/include/OgreVolumeGridSource.h deleted file mode 100644 index 7060dfba4ad..00000000000 --- a/Components/Volume/include/OgreVolumeGridSource.h +++ /dev/null @@ -1,206 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Ogre_Volume_GridSource_H__ -#define __Ogre_Volume_GridSource_H__ - -#include "OgreVector.h" - -#include "OgreVolumePrerequisites.h" -#include "OgreVolumeSource.h" - -namespace Ogre { -namespace Volume { - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Volume - * @{ - */ - class CSGOperationSource; - - /** A volume source from a discrete 3d grid. - */ - class _OgreVolumeExport GridSource : public Source - { - protected: - - /// The texture width. - size_t mWidth; - - /// The texture height. - size_t mHeight; - - /// The texture depth. - size_t mDepth; - - /// The scale of the position based on the world width. - Real mPosXScale; - - /// The scale of the position based on the world height. - Real mPosYScale; - - /// The scale of the position based on the world depth. - Real mPosZScale; - - /// Whether to use trilinear filtering or not for the value. - bool mTrilinearValue; - - /// Whether to use trilinear filtering or not for the gradient. - const bool mTrilinearGradient; - - /// Whether to blur the gradient a bit Sobel like. - const bool mSobelGradient; - - /// Factor to come from volume coordinate to world coordinate. - Real mVolumeSpaceToWorldSpaceFactor; - - /** Overridden from VolumeSource. - */ - Vector3 getIntersectionStart(const Ray &ray, Real maxDistance) const override; - - /** Overridden from VolumeSource. - */ - Vector3 getIntersectionEnd(const Ray &ray, Real maxDistance) const override; - - /** Gets the volume value of a position. - @param x - The x position. - @param y - The y position. - @param z - The z position. - @return - The density. - */ - virtual float getVolumeGridValue(size_t x, size_t y, size_t z) const = 0; - - /** Sets the volume value of a position. - @param x - The x position. - @param y - The y position. - @param z - The z position. - @param value - The density to be set. - */ - virtual void setVolumeGridValue(int x, int y, int z, float value) = 0; - - /** Gets a gradient of a point with optional sobel blurring. - @param x - The x coordinate of the point. - @param y - The x coordinate of the point. - @param z - The x coordinate of the point. - */ - inline const Vector3 getGradient(size_t x, size_t y, size_t z) const - { - if (mSobelGradient) - { - // Calculate gradient like in the original MC paper but mix a bit of Sobel in - return Vector3( - (getVolumeGridValue(x + 1, y - 1, z) - getVolumeGridValue(x - 1, y - 1, z)) - + (Real)2.0 * (getVolumeGridValue(x + 1, y, z) - getVolumeGridValue(x - 1, y, z)) - + (getVolumeGridValue(x + 1, y + 1, z) - getVolumeGridValue(x - 1, y + 1, z)), - (getVolumeGridValue(x, y + 1, z - 1) - getVolumeGridValue(x, y - 1, z - 1)) - + (Real)2.0 * (getVolumeGridValue(x, y + 1, z) - getVolumeGridValue(x, y - 1, z)) - + (getVolumeGridValue(x, y + 1, z + 1) - getVolumeGridValue(x, y - 1, z + 1)), - (getVolumeGridValue(x - 1, y, z + 1) - getVolumeGridValue(x - 1, y, z - 1)) - + (Real)2.0 * (getVolumeGridValue(x, y, z + 1) - getVolumeGridValue(x, y, z - 1)) - + (getVolumeGridValue(x + 1, y, z + 1) - getVolumeGridValue(x + 1, y, z - 1))) / (Real)4.0; - } - // Calculate gradient like in the original MC paper - return Vector3( - getVolumeGridValue(x + 1, y, z) - getVolumeGridValue(x - 1, y, z), - getVolumeGridValue(x, y + 1, z) - getVolumeGridValue(x, y - 1, z), - getVolumeGridValue(x, y, z + 1) - getVolumeGridValue(x, y, z - 1)); - } - - public: - - GridSource(bool trilinearValue, bool trilinearGradient, bool sobelGradient); - - /** Destructor. - */ - virtual ~GridSource(void); - - /** Overridden from VolumeSource. - */ - Vector4 getValueAndGradient(const Vector3 &position) const override; - - /** Overridden from VolumeSource. - */ - Real getValue(const Vector3 &position) const override; - - /** Gets the width of the texture. - @return - The width of the texture. - */ - size_t getWidth(void) const; - - /** Gets the height of the texture. - @return - The height of the texture. - */ - size_t getHeight(void) const; - - /** Gets the depth of the texture. - @return - The depth of the texture. - */ - size_t getDepth(void) const; - - /** Updates this grid with another source in a certain area. Use - it for example to add spheres as a brush. - @param operation - The operation to use, will use this source and the other given one as operands. Beware that - this function overrides the maybe existing sources in the operation. - @param source - The other source to combine this one with. - @param center - The rough center of the affected area by the operation. If the other source is a sphere, take - its center for example. - @param radius - The radius of the affected area. For the example sphere, you might use its radius times two - because the density outside of the sphere is needed, too. - */ - virtual void combineWithSource(CSGOperationSource *operation, Source *source, const Vector3 ¢er, Real radius); - - - /** Overridden from VolumeSource. - */ - Real getVolumeSpaceToWorldSpaceFactor(void) const; - - }; - /** @} */ - /** @} */ -} -} - -#endif diff --git a/Components/Volume/include/OgreVolumeHalfFloatGridSource.h b/Components/Volume/include/OgreVolumeHalfFloatGridSource.h deleted file mode 100644 index e2e7e50799f..00000000000 --- a/Components/Volume/include/OgreVolumeHalfFloatGridSource.h +++ /dev/null @@ -1,105 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Ogre_Volume_HalfFloatGridSource_H__ -#define __Ogre_Volume_HalfFloatGridSource_H__ - - -#include "OgreVolumeGridSource.h" - -namespace Ogre { -namespace Volume { - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Volume - * @{ - */ - /** A volume source from a 16 Bit float 3D grid capable of loading volume - serializations. - */ - class _OgreVolumeExport HalfFloatGridSource : public GridSource - { - protected: - - /// The raw volume data. - uint16 *mData; - - /// To have a little bit faster data access. - int mDepthTimesHeight; - - /// The maximum absolute density value to be written into the data when combining, - /// influencing the compression rate on serialization. - Real mMaxClampedAbsoluteDensity; - - /** Overridden from GridSource. - */ - float getVolumeGridValue(size_t x, size_t y, size_t z) const override; - - /** Overridden from GridSource. - */ - void setVolumeGridValue(int x, int y, int z, float value) override; - - public: - - /** Constructur. - @param serializedVolumeFile - Which volume serialization to get the data from. - @param trilinearValue - Whether to use trilinear filtering (true) or nearest neighbour (false) for the value. - @param trilinearGradient - Whether to use trilinear filtering (true) or nearest neighbour (false) for the gradient. - @param sobelGradient - Whether to add a bit of blur to the gradient like in a sobel filter. - */ - explicit HalfFloatGridSource(const String &serializedVolumeFile, const bool trilinearValue = true, const bool trilinearGradient = false, const bool sobelGradient = false); - - /** Sets the maximum absolute density value to be written into the data when combining, - influencing the compression rate on serialization. Set it to 0.0 to deactivate. - @param maxClampedAbsoluteDensity - The maximum absolute density value. - */ - void setMaxClampedAbsoluteDensity(Real maxClampedAbsoluteDensity); - - /** Gets the maximum absolute density value to be written into the data when combining, - influencing the compression rate on serialization. - @return - The maximum absolute density value, 0.0 when deactivated. - */ - Real getMaxClampedAbsoluteDensity(void) const; - - /** Destructor. - */ - ~HalfFloatGridSource(void); - - }; - /** @} */ - /** @} */ -} -} - -#endif diff --git a/Components/Volume/include/OgreVolumeIsoSurface.h b/Components/Volume/include/OgreVolumeIsoSurface.h deleted file mode 100644 index 968ae3ee61a..00000000000 --- a/Components/Volume/include/OgreVolumeIsoSurface.h +++ /dev/null @@ -1,114 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Ogre_Volume_IsoSurface_H__ -#define __Ogre_Volume_IsoSurface_H__ - -#include "OgreVolumePrerequisites.h" -#include "OgrePrerequisites.h" - -namespace Ogre { -namespace Volume { - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Volume - * @{ - */ - class Source; - class MeshBuilder; - - /** Abstract IsoSurface. - */ - class _OgreVolumeExport IsoSurface : public UtilityAlloc - { - protected: - - /// The value where our isosurface is. - static const Real ISO_LEVEL; - - /// To get the isovalue and normal. - const Source *mSrc; - - /** Constructor. - @param src - The source to use. - */ - explicit IsoSurface(const Source *src); - - public: - - /// To call Marching Squares with a cube on its front. - static const size_t MS_CORNERS_FRONT[4]; - - /// To call Marching Squares with a cube on its back. - static const size_t MS_CORNERS_BACK[4]; - - /// To call Marching Squares with a cube on its left. - static const size_t MS_CORNERS_LEFT[4]; - - /// To call Marching Squares with a cube on its right. - static const size_t MS_CORNERS_RIGHT[4]; - - /// To call Marching Squares with a cube on its top. - static const size_t MS_CORNERS_TOP[4]; - - /// To call Marching Squares with a cube on its bottom. - static const size_t MS_CORNERS_BOTTOM[4]; - - virtual ~IsoSurface(void); - - /** Adds triangles to a MeshBuilder via Marching Cubes. - @param corners - The corners of the cube to triangulate via Marching Cubes. - @param volumeValues - The cached volume values, one Vector4 consists of gradient (x, y, z) and density (w). If 0 is given, it will be calculated. - @param mb - The MeshBuilder to add the triangles to. - */ - virtual void addMarchingCubesTriangles(const Vector3 *corners, const Vector4 *volumeValues, MeshBuilder *mb) const = 0; - - /** Adds triangles to a MeshBuilder via Marching Squares. - @param corners - The corners of the cube where one side is to be triangulated. - @param volumeValues - The cached volume values, one Vector4 consists of gradient (x, y, z) and density (w). If 0 is given, it will be calculated. - @param indices - The four corners of the cube (== one side) to triangulate. - @param maxDistance - The maximum distance to the surface where triangles are generated. - @param mb - The MeshBuilder to add the triangles to. - */ - virtual void addMarchingSquaresTriangles(const Vector3 *corners, const Vector4 *volumeValues, const size_t *indices, const Real maxDistance, MeshBuilder *mb) const = 0; - }; - /** @} */ - /** @} */ -} -} - -#endif diff --git a/Components/Volume/include/OgreVolumeIsoSurfaceMC.h b/Components/Volume/include/OgreVolumeIsoSurfaceMC.h deleted file mode 100644 index c69731460cc..00000000000 --- a/Components/Volume/include/OgreVolumeIsoSurfaceMC.h +++ /dev/null @@ -1,122 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Ogre_Volume_IsoSurfaceMC_H__ -#define __Ogre_Volume_IsoSurfaceMC_H__ - -#include "OgreVolumeIsoSurface.h" -#include "OgreVector.h" -#include - -namespace Ogre { -namespace Volume { - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Volume - * @{ - */ - class Source; - class MeshBuilder; - - /** Marching Cubes implementation like at - http://local.wasp.uwa.edu.au/~pbourke/geometry/polygonise/ - */ - class _OgreVolumeExport IsoSurfaceMC : public IsoSurface - { - protected: - - - /** Linear interpolation between two vectors based on some values associated to them. - @param v0 - The first vector. - @param v1 - The second vector. - @param val0 - The value for the first vector. - @param val1 - The value for the second vector. - @param normal - Reference to a vector where the normal will be stored. - @return - The interpolated position. - */ - inline Vector3 interpolate(const Vector3 &v0, const Vector3 &v1, const Vector4 &val0, const Vector4 &val1, Vector3 &normal) const - { - // Don't use Math::RealEqual here as it isn't inlined and this function is performance critical. - if (fabs(val0.w - ISO_LEVEL) <= FLT_EPSILON) - { - normal.x = val0.x; - normal.y = val0.y; - normal.z = val0.z; - return v0; - } - if (fabs(val1.w - ISO_LEVEL) <= FLT_EPSILON) - { - normal.x = val1.x; - normal.y = val1.y; - normal.z = val1.z; - return v1; - } - if (fabs(val1.w - val0.w) <= FLT_EPSILON) - { - normal.x = val0.x; - normal.y = val0.y; - normal.z = val0.z; - return v0; - } - Real mu = (ISO_LEVEL - val0.w) / (val1.w - val0.w); - Vector4 normal4 = val0 + mu * (val1 - val0); - normal.x = normal4.x; - normal.y = normal4.y; - normal.z = normal4.z; - normal.normalise(); - return v0 + mu * (v1 - v0); - } - - public: - - /** Constructor. - @param src - The source for the isovalues and normals there. - */ - explicit IsoSurfaceMC(const Source *src); - - /** Overridden from IsoSurface. - */ - void addMarchingCubesTriangles(const Vector3 *corners, const Vector4 *volumeValues, MeshBuilder *mb) const override; - - /** Overridden from IsoSurface. - */ - void addMarchingSquaresTriangles(const Vector3 *corners, const Vector4 *volumeValues, const size_t *indices, const Real maxDistance, MeshBuilder *mb) const override; - }; - /** @} */ - /** @} */ -} -} - -#endif diff --git a/Components/Volume/include/OgreVolumeIsoSurfaceTablesMC.h b/Components/Volume/include/OgreVolumeIsoSurfaceTablesMC.h deleted file mode 100644 index 044eeb6fcff..00000000000 --- a/Components/Volume/include/OgreVolumeIsoSurfaceTablesMC.h +++ /dev/null @@ -1,387 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Ogre_Volume_IsoSurfaceTablesMC_H__ -#define __Ogre_Volume_IsoSurfaceTablesMC_H__ - -namespace Ogre { -namespace Volume { - - /** Marching Cubes tables from the public domain code found on - http://local.wasp.uwa.edu.au/~pbourke/geometry/polygonise/ - in - http://paulbourke.net/geometry/polygonise/marchingsource.cpp - Thanks! - */ - - /** Edges table. - */ - int mcEdges[256] = - { - 0x000, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, - 0x190, 0x099, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, - 0x230, 0x339, 0x033, 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, - 0x3a0, 0x2a9, 0x1a3, 0x0aa, 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, - 0x460, 0x569, 0x663, 0x76a, 0x066, 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, - 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0x0ff, 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, - 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x055, 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, - 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0x0cc, 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, - 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0x0cc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, - 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x055, 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, - 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0x0ff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, - 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x066, 0x76a, 0x663, 0x569, 0x460, - 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0x0aa, 0x1a3, 0x2a9, 0x3a0, - 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x033, 0x339, 0x230, - 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x099, 0x190, - 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x000 - }; - - /** Triangulation lookup table. - */ - int mcTriangles[256][16] = - { - {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1}, - {3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1}, - {3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1}, - {3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1}, - {9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1}, - {1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1}, - {9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, - {2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1}, - {8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1}, - {9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, - {4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1}, - {3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1}, - {1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1}, - {4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1}, - {4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1}, - {9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1}, - {1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, - {5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1}, - {2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1}, - {9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, - {0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, - {2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1}, - {10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1}, - {4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1}, - {5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1}, - {5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1}, - {9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1}, - {0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1}, - {1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1}, - {10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1}, - {8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1}, - {2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1}, - {7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1}, - {9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1}, - {2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1}, - {11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1}, - {9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1}, - {5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1}, - {11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1}, - {11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, - {1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1}, - {9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1}, - {5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1}, - {2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, - {0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, - {5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1}, - {6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1}, - {0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1}, - {3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1}, - {6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1}, - {5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1}, - {1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, - {10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1}, - {6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1}, - {1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1}, - {8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1}, - {7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1}, - {3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, - {5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1}, - {0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1}, - {9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1}, - {8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1}, - {5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1}, - {0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1}, - {6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1}, - {10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1}, - {10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1}, - {8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1}, - {1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1}, - {3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1}, - {0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1}, - {10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1}, - {0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1}, - {3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1}, - {6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1}, - {9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1}, - {8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1}, - {3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1}, - {6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1}, - {0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1}, - {10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1}, - {10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1}, - {1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1}, - {2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1}, - {7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1}, - {7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1}, - {2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1}, - {1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1}, - {11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1}, - {8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1}, - {0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1}, - {7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, - {10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, - {2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, - {6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1}, - {7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1}, - {2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1}, - {1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1}, - {10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1}, - {10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1}, - {0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1}, - {7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1}, - {6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1}, - {8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1}, - {9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1}, - {6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1}, - {1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1}, - {4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1}, - {10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1}, - {8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1}, - {0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1}, - {1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1}, - {8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1}, - {10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1}, - {4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1}, - {10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, - {5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, - {11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1}, - {9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, - {6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1}, - {7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1}, - {3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1}, - {7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1}, - {9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1}, - {3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1}, - {6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1}, - {9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1}, - {1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1}, - {4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1}, - {7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1}, - {6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1}, - {3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1}, - {0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1}, - {6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1}, - {1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1}, - {0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1}, - {11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1}, - {6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1}, - {5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1}, - {9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1}, - {1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1}, - {1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1}, - {10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1}, - {0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1}, - {5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1}, - {10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1}, - {11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1}, - {0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1}, - {9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1}, - {7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1}, - {2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1}, - {8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1}, - {9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1}, - {9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1}, - {1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1}, - {9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1}, - {9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1}, - {5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1}, - {0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1}, - {10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1}, - {2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1}, - {0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1}, - {0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1}, - {9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1}, - {5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1}, - {3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1}, - {5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1}, - {8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1}, - {0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1}, - {9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1}, - {0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1}, - {1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1}, - {3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1}, - {4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1}, - {9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1}, - {11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1}, - {11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1}, - {2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1}, - {9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1}, - {3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1}, - {1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1}, - {4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1}, - {4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1}, - {0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1}, - {3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1}, - {3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1}, - {0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1}, - {9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1}, - {1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, - {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1} - }; - - /* - Throw in the corners inside of the volume and get a 4 bit array which edges are cutting it. - Edge indices to check then (Edge between 0 and 4 cut == msEdges[x] & 4). - 0-1-1 - | | - 4 2 - | | - 3-3-2 - */ - int msEdges[16] = - { - 0x0, // 0000 Nothing intersects - 0x9, // 0001 0 - 0x3, // 0010 1 - 0xA, // 0011 0 1 - 0x6, // 0100 2 - 0xF, // 0101 0 2 - 0x5, // 0110 1 2 - 0xC, // 0111 0 1 2 - 0xC, // 1000 3 - 0x5, // 1001 0 3 - 0xF, // 1010 1 3 - 0x6, // 1011 0 1 3 - 0xA, // 1100 2 3 - 0x3, // 1101 0 2 3 - 0x9, // 1110 1 2 3 - 0x0 // 1111 0 1 2 3 - }; - - /* - To get a triangulation with up to 5 triangles based on the corners inside. Alternative - ambigous cases added at the end. Indices of the counterclockwise formed triangles: - 0-1-2 - | | - 7 3 - | | - 6-5-4 - */ - int msTriangles[18][13] = - { - {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, // Nothing intersects - {7, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, // 0 - {3, 2, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, // 1 - {7, 2, 0, 7, 3, 2, -1, -1, -1, -1, -1, -1, -1}, // 0 1 - {5, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, // 2 - {7, 1, 0, 3, 5, 4, -1, -1, -1, -1, -1, -1, -1}, // 0 2 - {1, 4, 2, 1, 5, 4, -1, -1, -1, -1, -1, -1, -1}, // 1 2 - {0, 7, 5, 0, 5, 4, 0, 4, 2, -1, -1, -1, -1}, // 0 1 2 - {7, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, // 3 - {0, 5, 1, 0, 6, 5, -1, -1, -1, -1, -1, -1, -1}, // 0 3 - {1, 3, 2, 7, 6, 5, -1, -1, -1, -1, -1, -1, -1}, // 1 3 - {3, 6, 5, 3, 0, 6, 3, 2, 0, -1, -1, -1, -1}, // 0 1 3 - {7, 6, 4, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1}, // 2 3 - {3, 1, 0, 3, 0, 6, 3, 6, 4, -1, -1, -1, -1}, // 0 2 3 - {2, 1, 7, 2, 7, 6, 2, 6, 4, -1, -1, -1, -1}, // 1 2 3 - {6, 2, 0, 6, 4, 2, -1, -1, -1, -1, -1, -1, -1}, // 0 1 2 3 - {1, 0, 7, 1, 7, 5, 1, 5, 4, 1, 4, 3, -1}, // 0 2 alternative - {1, 3, 2, 1, 5, 3, 1, 6, 5, 1, 7, 6, -1} // 1 3 alternative - }; -} -} - -#endif \ No newline at end of file diff --git a/Components/Volume/include/OgreVolumeMeshBuilder.h b/Components/Volume/include/OgreVolumeMeshBuilder.h deleted file mode 100644 index 7ab5bba8b58..00000000000 --- a/Components/Volume/include/OgreVolumeMeshBuilder.h +++ /dev/null @@ -1,349 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Ogre_Volume_MeshBuilder_H__ -#define __Ogre_Volume_MeshBuilder_H__ - -#include -#include "OgreManualObject.h" -#include "OgreVector.h" -#include "OgreAxisAlignedBox.h" -#include "OgreVolumePrerequisites.h" - -namespace Ogre { -namespace Volume { - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Volume - * @{ - */ - /** Lightweight struct to represent a mesh vertex. - */ - typedef struct _OgreVolumeExport Vertex - { - /// X coordinate of the position - Real x; - - /// Y coordinate of the position - Real y; - - /// Z coordinate of the position - Real z; - - /// X component of the normal - Real nX; - - /// Y component of the normal - Real nY; - - /// Z component of the normal - Real nZ; - - /** Convenience constructor. - @param v - The vertex position. - @param n - The vertex normal. - */ - Vertex(const Vector3 &v, const Vector3 &n) : - x(v.x), y(v.y), z(v.z), - nX(n.x), nY(n.y), nZ(n.z) - { - } - Vertex() - { - } - } Vertex; - - /** == operator for two vertices. - @param a - The first vertex to test. - @param b - The second vertex to test. - */ - bool _OgreVolumeExport operator==(Vertex const& a, Vertex const& b); - - /** A less operator. - @note - This operator is needed so that Vertex can serve as the key in a map structrue - @param a - The first vertex to test. - @param b - The second vertex to test. - */ - bool _OgreVolumeExport operator<(const Vertex& a, const Vertex& b); - - /** To hold vertices. - */ - typedef std::vector VecVertex; - - /** To hold indices. - */ - typedef std::vector VecIndices; - - /** Callback class when the user needs information about the triangles of - chunks of a LOD level. - */ - class _OgreVolumeExport MeshBuilderCallback - { - public: - virtual ~MeshBuilderCallback() {} - - /** To be called with the callback function of a MeshBuilder. - @param simpleRenderable - Contains the SimpleRenderable for which the triangles were built. - @param vertices - Contains the vertices of the triangles. - @param indices - Contains the indices of the triangles. - @param level - The LOD level of this mesh. - @param inProcess - The amount of other meshes/LOD-Chunks still to be loaded. - */ - virtual void ready(const SimpleRenderable *simpleRenderable, const VecVertex &vertices, const VecIndices &indices, size_t level, int inProcess) = 0; - }; - - /** Class to build up a mesh with vertices and indices. - */ - class _OgreVolumeExport MeshBuilder : public UtilityAlloc - { - protected: - - /// The buffer binding. - static const unsigned short MAIN_BINDING; - - /// Map to get a vertex index. - typedef std::map UMapVertexIndex; - UMapVertexIndex mIndexMap; - - /// Holds the vertices of the mesh. - VecVertex mVertices; - - /// Holds the indices of the mesh. - VecIndices mIndices; - - /// Holds the bounding box. - AxisAlignedBox mBox; - - /// Holds whether the initial bounding box has been set - bool mBoxInit; - - /** Adds a vertex to the data structure, reusing the index if it is already known. - @param v - The vertex. - */ - inline void addVertex(const Vertex &v) - { - size_t i = 0; - if (mIndexMap.find(v) == mIndexMap.end()) - { - i = mVertices.size(); - mIndexMap[v] = i; - mVertices.push_back(v); - - // Update bounding box - if (!mBoxInit) - { - mBox.setExtents(v.x, v.y, v.z, v.x, v.y, v.z); - mBoxInit = true; - } - else - { - if (v.x < mBox.getMinimum().x) - { - mBox.setMinimumX(v.x); - } - if (v.y < mBox.getMinimum().y) - { - mBox.setMinimumY(v.y); - } - if (v.z < mBox.getMinimum().z) - { - mBox.setMinimumZ(v.z); - } - if (v.x > mBox.getMaximum().x) - { - mBox.setMaximumX(v.x); - } - if (v.y > mBox.getMaximum().y) - { - mBox.setMaximumY(v.y); - } - if (v.z > mBox.getMaximum().z) - { - mBox.setMaximumZ(v.z); - } - } - } - else - { - i = mIndexMap[v]; - } - mIndices.push_back(i); - } - - public: - - /** Adds a cube to a manual object rendering lines. Corner numeration: - 4 5 - 7 6 - 0 1 - 3 2 - @param manual - The manual for the cube lines. - @param c0 - The corner 0. - @param c1 - The corner 1. - @param c2 - The corner 2. - @param c3 - The corner 3. - @param c4 - The corner 4. - @param c5 - The corner 5. - @param c6 - The corner 6. - @param c7 - The corner 7. - @param baseIndex - The next free index of this manual object. - Is incremented by 8 in this function. - */ - static inline void addCubeToManualObject( - ManualObject *manual, - const Vector3 &c0, - const Vector3 &c1, - const Vector3 &c2, - const Vector3 &c3, - const Vector3 &c4, - const Vector3 &c5, - const Vector3 &c6, - const Vector3 &c7, - uint32 &baseIndex - ) - { - manual->position(c0); - manual->position(c1); - manual->position(c2); - manual->position(c3); - manual->position(c4); - manual->position(c5); - manual->position(c6); - manual->position(c7); - - manual->index(baseIndex + 0); manual->index(baseIndex + 1); - manual->index(baseIndex + 1); manual->index(baseIndex + 2); - manual->index(baseIndex + 2); manual->index(baseIndex + 3); - manual->index(baseIndex + 3); manual->index(baseIndex + 0); - - manual->index(baseIndex + 4); manual->index(baseIndex + 5); - manual->index(baseIndex + 5); manual->index(baseIndex + 6); - manual->index(baseIndex + 6); manual->index(baseIndex + 7); - manual->index(baseIndex + 7); manual->index(baseIndex + 4); - - manual->index(baseIndex + 0); manual->index(baseIndex + 4); - manual->index(baseIndex + 1); manual->index(baseIndex + 5); - manual->index(baseIndex + 2); manual->index(baseIndex + 6); - manual->index(baseIndex + 3); manual->index(baseIndex + 7); - baseIndex += 8; - } - - /** Constructor. - */ - MeshBuilder(void); - - /** Adds a triangle to the mesh with reusing already existent vertices via their index. - @param v0 - The first vertex of the triangle. - @param n0 - The normal of the first vertex. - @param v1 - The second vertex of the triangle. - @param n1 - The normal of the second vertex. - @param v2 - The third vertex of the triangle. - @param n2 - The normal of the third vertex. - */ - inline void addTriangle(const Vector3 &v0, const Vector3 &n0, const Vector3 &v1, const Vector3 &n1, const Vector3 &v2, const Vector3 &n2) - { - addVertex(Vertex(v0, n0)); - addVertex(Vertex(v1, n1)); - addVertex(Vertex(v2, n2)); - } - - /** Generates the vertex- and indexbuffer of this mesh on the given - RenderOperation. - @param operation - The RenderOperation for the buffers. - @return - The amount of generated triangles. - */ - size_t generateBuffers(RenderOperation &operation); - - /** Generates an entity via a ManualObject. - @param sceneManager - The creating sceneManager. - @param name - The name for the entity. - @param material - The material to use. - @return - The created entity. - */ - Entity* generateWithManualObject(SceneManager *sceneManager, const String &name, const String &material); - - /** Gets the bounding box of the mesh. - @return - The bounding box. - */ - AxisAlignedBox getBoundingBox(void); - - /** Executes a MeshBuilderCallback on this instance. - @param callback - The callback to execute. - @param simpleRenderable - Contains the SimpleRenderable for which the triangles were built. - @param level - The LOD level of this mesh. - @param inProcess - The amount of other meshes/LOD-Chunks still to be loaded. - */ - void executeCallback(MeshBuilderCallback *callback, const SimpleRenderable *simpleRenderable, size_t level, int inProcess) const; - - }; - /** @} */ - /** @} */ -} -} - -#endif diff --git a/Components/Volume/include/OgreVolumeOctreeNode.h b/Components/Volume/include/OgreVolumeOctreeNode.h deleted file mode 100644 index f3d6cf770a8..00000000000 --- a/Components/Volume/include/OgreVolumeOctreeNode.h +++ /dev/null @@ -1,544 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Ogre_Volume_OctreeNode_H__ -#define __Ogre_Volume_OctreeNode_H__ - -#include "OgreVolumePrerequisites.h" -#include "OgreVector.h" - -namespace Ogre { - -namespace Volume { - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Volume - * @{ - */ - class OctreeNodeSplitPolicy; - class Source; - - /** A node in the volume octree. - */ - class _OgreVolumeExport OctreeNode : public UtilityAlloc - { - protected: - - /// Factor to the diagonal of the cell to decide whether this cell is near the isosurface or not. - static const Real NEAR_FACTOR; - - /// To count some indices while creating the debug view and recursing through the instances. - static uint32 mGridPositionCount; - - /// To give the debug manual object an unique name. - static size_t mNodeI; - - /// The back lower left corner of the cell. - Vector3 mFrom; - - /// The front upper right corner of the cell. - Vector3 mTo; - - /// The children of this node. - OctreeNode **mChildren; - - /// Holds the debug visualization of the octree. Just set in the root. - Entity* mOctreeGrid; - - /// Density and gradient of the center. - Vector4 mCenterValue; - - /** Method to actually add the lines of the octree cells to - the debug visualization. - @param manual - The manual object to add the lines to if this is a leaf in the octree. - */ - void buildOctreeGridLines(ManualObject *manual) const; - public: - - /// Even in an OCtree, the amount of children should not be hardcoded. - static const size_t OCTREE_CHILDREN_COUNT; - - /** Gets the center and width / height / depth vector of the children of a node. - @param from - The back lower left corner of the cell. - @param to - The front upper right corner of the cell. - @param center - Out parameter of the calculated center. - @param width - Out parameter of the width vector (width in x, rest zero). - @param height - Out parameter of the height vector (height in y, rest zero). - @param depth - Out parameter of the depth vector (depth in z, rest zero). - */ - static inline void getChildrenDimensions(const Vector3 &from, const Vector3 &to, Vector3 ¢er, Vector3 &width, Vector3 &height, Vector3 &depth) - { - center = (to - from) / (Real)2.0; - width.x = center.x; - width.y = (Real)0.0; - width.z = (Real)0.0; - height.x = (Real)0.0; - height.y = center.y; - height.z = (Real)0.0; - depth.x = (Real)0.0; - depth.y = (Real)0.0; - depth.z = center.z; - center += from; - } - - /** Constructor. - @param from - The back lower left corner of the cell. - @param to - The front upper right corner of the cell. - */ - OctreeNode(const Vector3 &from = Vector3::ZERO, const Vector3 &to = Vector3::ZERO); - - /** Destructor. - */ - virtual ~OctreeNode(void); - - /** Factory method to create octree nodes. - @param from - The back lower left corner of the cell. - @param to - The front upper right corner of the cell. - @return - The created entity. Make sure to destroy it when you don't need it anymore. - */ - virtual OctreeNode* createInstance(const Vector3& from, const Vector3& to); - - /** Splits this cell if the split policy says so. - @param splitPolicy - Defines the policy deciding whether to split this node or not. - @param src - The volume source. - @param geometricError - The accepted geometric error. - */ - void split(const OctreeNodeSplitPolicy *splitPolicy, const Source *src, const Real geometricError); - - /** Getter for the octree debug visualization of the octree starting with - this node. - @param sceneManager - The scenemanager creating the actual entity. - @return - The lazily created debug visualization. - */ - Entity* getOctreeGrid(SceneManager *sceneManager); - - /** Setter for the from-part of this cell. - @param from - The back lower left corner of the cell. - */ - inline void setFrom(Vector3 from) - { - mFrom = from; - } - - /** Setter for the to-part of this cell. - @param to - The front upper right corner of the cell. - */ - inline void setTo(Vector3 to) - { - mTo = to; - } - - /** Gets whether this cell has any children. - @return - True if so. - */ - inline bool isSubdivided(void) const - { - return mChildren != 0; - } - - /** Gets an octree child. Enumeration: - 4 5 - 7 6 - 0 1 - 3 2 - @param i - The child index. - @return - The child. - */ - inline const OctreeNode* getChild(const size_t i) const - { - return mChildren[i]; - } - - /** Gets the center of this cell. - @return - The center. - */ - inline const Vector3 getCenter(void) const - { - return (mFrom + mTo) / (Real)2.0; - } - - /** Gets the back lower left corner of the cell. - @return - The back lower left corner of the cell. - */ - inline const Vector3& getFrom(void) const - { - return mFrom; - } - - /** Gets the front upper right corner of the cell. - @return - The front upper right corner of the cell. - */ - inline const Vector3& getTo(void) const - { - return mTo; - } - - /** Gets whether this cell is at the left of the given root cell. - @param root - The octree root node to test against. - @return - true if so. - */ - inline bool isBorderLeft(const OctreeNode &root) const - { - return mFrom.x == root.mFrom.x; - } - - /** Gets whether this cell is at the right of the given root cell. - @param root - The octree root node to test against. - @return - true if so. - */ - inline bool isBorderRight(const OctreeNode &root) const - { - return mTo.x == root.mTo.x; - } - - /** Gets whether this cell is at the bottom of the given root cell. - @param root - The octree root node to test against. - @return - true if so. - */ - inline bool isBorderBottom(const OctreeNode &root) const - { - return mFrom.y == root.mFrom.y; - } - - /** Gets whether this cell is at the top of the given root cell. - @param root - The octree root node to test against. - @return - true if so. - */ - inline bool isBorderTop(const OctreeNode &root) const - { - return mTo.y == root.mTo.y; - } - - /** Gets whether this cell is at the back of the given root cell. - @param root - The octree root node to test against. - @return - true if so. - */ - inline bool isBorderBack(const OctreeNode &root) const - { - return mFrom.z == root.mFrom.z; - } - - /** Gets whether this cell is at the front of the given root cell. - @param root - The octree root node to test against. - @return - true if so. - */ - inline bool isBorderFront(const OctreeNode &root) const - { - return mTo.z == root.mTo.z; - } - - /** Gets the center of the corners 0, 1, 4, 5. - @return - The center. - */ - inline const Vector3 getCenterBack(void) const - { - return Vector3(mFrom.x + (mTo.x - mFrom.x) / (Real)2.0, mFrom.y + (mTo.y - mFrom.y) / (Real)2.0, mFrom.z); - } - - /** Gets the center of the corners 2, 3, 6, 7. - @return - The center. - */ - inline const Vector3 getCenterFront(void) const - { - return Vector3(mFrom.x + (mTo.x - mFrom.x) / (Real)2.0, mFrom.y + (mTo.y - mFrom.y) / (Real)2.0, mTo.z); - } - - /** Gets the center of the corners 0, 3, 4, 6. - @return - The center. - */ - inline const Vector3 getCenterLeft(void) const - { - return Vector3(mFrom.x, mFrom.y + (mTo.y - mFrom.y) / (Real)2.0, mFrom.z + (mTo.z - mFrom.z) / (Real)2.0); - } - - /** Gets the center of the corners 1, 2, 5, 6. - @return - The center. - */ - inline const Vector3 getCenterRight(void) const - { - return Vector3(mTo.x, mFrom.y + (mTo.y - mFrom.y) / (Real)2.0, mFrom.z + (mTo.z - mFrom.z) / (Real)2.0); - } - - /** Gets the center of the corners 4, 5, 6, 7. - @return - The center. - */ - inline const Vector3 getCenterTop(void) const - { - return Vector3(mFrom.x + (mTo.x - mFrom.x) / (Real)2.0, mTo.y, mFrom.z + (mTo.z - mFrom.z) / (Real)2.0); - } - - /** Gets the center of the corners 0, 1, 2, 3. - @return - The center. - */ - inline const Vector3 getCenterBottom(void) const - { - return Vector3(mFrom.x + (mTo.x - mFrom.x) / (Real)2.0, mFrom.y, mFrom.z + (mTo.z - mFrom.z) / (Real)2.0); - } - - /** Gets the center of the corners 4, 5. - @return - The center. - */ - inline const Vector3 getCenterBackTop(void) const - { - return Vector3(mFrom.x + (mTo.x - mFrom.x) / (Real)2.0, mTo.y, mFrom.z); - } - - /** Gets the center of the corners 0, 1. - @return - The center. - */ - inline const Vector3 getCenterBackBottom(void) const - { - return Vector3(mFrom.x + (mTo.x - mFrom.x) / (Real)2.0, mFrom.y, mFrom.z); - } - - /** Gets the center of the corners 6, 7. - @return - The center. - */ - inline const Vector3 getCenterFrontTop(void) const - { - return Vector3(mFrom.x + (mTo.x - mFrom.x) / (Real)2.0, mTo.y, mTo.z); - } - - /** Gets the center of the corners 2, 3. - @return - The center. - */ - inline const Vector3 getCenterFrontBottom(void) const - { - return Vector3(mFrom.x + (mTo.x - mFrom.x) / (Real)2.0, mFrom.y, mTo.z); - } - - /** Gets the center of the corners 4, 7. - @return - The center. - */ - inline const Vector3 getCenterLeftTop(void) const - { - return Vector3(mFrom.x, mTo.y, mFrom.z + (mTo.z - mFrom.z) / (Real)2.0); - } - - /** Gets the center of the corners 0, 3. - @return - The center. - */ - inline const Vector3 getCenterLeftBottom(void) const - { - return Vector3(mFrom.x, mFrom.y, mFrom.z + (mTo.z - mFrom.z) / (Real)2.0); - } - - /** Gets the center of the corners 5, 6. - @return - The center. - */ - inline const Vector3 getCenterRightTop(void) const - { - return Vector3(mTo.x, mTo.y, mFrom.z + (mTo.z - mFrom.z) / (Real)2.0); - } - - /** Gets the center of the corners 1, 2. - @return - The center. - */ - inline const Vector3 getCenterRightBottom(void) const - { - return Vector3(mTo.x, mFrom.y, mFrom.z + (mTo.z - mFrom.z) / (Real)2.0); - } - - /** Gets the center of the corners 0, 4. - @return - The center. - */ - inline const Vector3 getCenterBackLeft(void) const - { - return Vector3(mFrom.x, mFrom.y + (mTo.y - mFrom.y) / (Real)2.0, mFrom.z); - } - - /** Gets the center of the corners 3, 7. - @return - The center. - */ - inline const Vector3 getCenterFrontLeft(void) const - { - return Vector3(mFrom.x, mFrom.y + (mTo.y - mFrom.y) / (Real)2.0, mTo.z); - } - - /** Gets the center of the corners 1, 5. - @return - The center. - */ - inline const Vector3 getCenterBackRight(void) const - { - return Vector3(mTo.x, mFrom.y + (mTo.y - mFrom.y) / (Real)2.0, mFrom.z); - } - - /** Gets the center of the corners 2, 6. - @return - The center. - */ - inline const Vector3 getCenterFrontRight(void) const - { - return Vector3(mTo.x, mFrom.y + (mTo.y - mFrom.y) / (Real)2.0, mTo.z); - } - - /** Gets the coordinate of corner 1. - @return - The corner. - */ - inline const Vector3 getCorner1(void) const - { - return Vector3(mTo.x, mFrom.y, mFrom.z); - } - - /** Gets the coordinate of corner 2. - @return - The corner. - */ - inline const Vector3 getCorner2(void) const - { - return Vector3(mTo.x, mFrom.y, mTo.z); - } - - /** Gets the coordinate of corner 3. - @return - The corner. - */ - inline const Vector3 getCorner3(void) const - { - return Vector3(mFrom.x, mFrom.y, mTo.z); - } - - /** Gets the coordinate of corner 4. - @return - The corner. - */ - inline const Vector3 getCorner4(void) const - { - return Vector3(mFrom.x, mTo.y, mFrom.z); - } - - /** Gets the coordinate of corner 5. - @return - The corner. - */ - inline const Vector3 getCorner5(void) const - { - return Vector3(mTo.x, mTo.y, mFrom.z); - } - - /** Gets the coordinate of corner 7. - @return - The corner. - */ - inline const Vector3 getCorner7(void) const - { - return Vector3(mFrom.x, mTo.y, mTo.z); - } - - /** Raw setter for the center value. - @param value - The density value. - */ - inline void setCenterValue(Vector4 value) - { - mCenterValue = value; - } - - /** Gets the center value. - @return - The center value, one Vector4 consisting of gradient (x, y, z) and density (w). - */ - inline const Vector4 getCenterValue(void) const - { - return mCenterValue; - } - - /** Gets whether the isosurface is somewhat near to this node. - @return - true if somewhat near. - */ - inline bool isIsoSurfaceNear(void) const - { - if (mCenterValue.w == (Real)0.0) - { - return true; - } - return Math::Abs(mCenterValue.w) < (mFrom - mTo).length() * NEAR_FACTOR; - } - }; - /** @} */ - /** @} */ -} -} - -#endif diff --git a/Components/Volume/include/OgreVolumeOctreeNodeSplitPolicy.h b/Components/Volume/include/OgreVolumeOctreeNodeSplitPolicy.h deleted file mode 100644 index 4aa8e1005ba..00000000000 --- a/Components/Volume/include/OgreVolumeOctreeNodeSplitPolicy.h +++ /dev/null @@ -1,125 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Ogre_Volume_OctreeNodeSplitPolicy_H__ -#define __Ogre_Volume_OctreeNodeSplitPolicy_H__ - -#include "OgreVector.h" - -#include "OgreVolumePrerequisites.h" - -namespace Ogre { -namespace Volume { - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Volume - * @{ - */ - class OctreeNode; - class Source; - - /** The class deciding on whether to split an octree node or not - when building the octree. - Splitting like Zhang in http://www.andrew.cmu.edu/user/jessicaz/publication/meshing/. - */ - class _OgreVolumeExport OctreeNodeSplitPolicy - { - protected: - - /// Holds the volume source to decide something. - const Source *mSrc; - - /// The maximum cell size where the policy stops the splitting. - Real mMaxCellSize; - - /** Trilinear interpolation of a relative point. - @param f000 - Value of the lower back left corner. - @param f001 - Value of the lower front right corner. - @param f010 - Value of the upper back left corner. - @param f011 - Value of the upper front left corner. - @param f100 - Value of the lower back right corner. - @param f101 - Value of the lower back right corner. - @param f110 - Value of the upper front right corner. - @param f111 - Value of the upper front right corner. - @param position - The relative (0-1) position to interpolate. - @return - The interpolated value. - */ - inline Real interpolate(const Real f000, const Real f001, const Real f010, const Real f011, - const Real f100, const Real f101, const Real f110, const Real f111, const Vector3 &position) const - { - Real oneMinX = (Real)1.0 - position.x; - Real oneMinY = (Real)1.0 - position.y; - Real oneMinZ = (Real)1.0 - position.z; - Real oneMinXoneMinY = oneMinX * oneMinY; - Real xOneMinY = position.x * oneMinY; - return oneMinZ * (f000 * oneMinXoneMinY - + f100 * xOneMinY - + f010 * oneMinX * position.y) - + position.z * (f001 * oneMinXoneMinY - + f101 * xOneMinY - + f011 * oneMinX * position.y) - + position.x * position.y * (f110 * oneMinZ - + f111 * position.z); - } - - public: - - /** Constructur. Protected to have the initialization. - @param src - The volume source to decide something. - @param maxCellSize - The maximum size when the splitting will stop anyway. - */ - OctreeNodeSplitPolicy(const Source *src, const Real maxCellSize); - - /** Decider for the splitting. - @param node - The split candidate. - @param geometricError - The accepted geometric error. - @return - true if the node should be split. - */ - virtual bool doSplit(OctreeNode *node, const Real geometricError) const; - }; - /** @} */ - /** @} */ -} -} - -#endif diff --git a/Components/Volume/include/OgreVolumeSimplexNoise.h b/Components/Volume/include/OgreVolumeSimplexNoise.h deleted file mode 100644 index 85f3909c6c0..00000000000 --- a/Components/Volume/include/OgreVolumeSimplexNoise.h +++ /dev/null @@ -1,129 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Ogre_Simplex_Noise_H__ -#define __Ogre_Simplex_Noise_H__ - -#include "OgreVector.h" - -#include "OgreVolumePrerequisites.h" - -namespace Ogre { -namespace Volume { - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Volume - * @{ - */ - /** Simplex Noise ported from public domain Java Implementation - http://webstaff.itn.liu.se/~stegu/simplexnoise/SimplexNoise.java - Thanks Stefan Gustavson! - */ - class _OgreVolumeExport SimplexNoise - { - private: - - /// Skewing and unskewing factor for 3 dimensions. - static Real F3; - - /// Skewing and unskewing factor for 3 dimensions. - static Real G3; - - /// Random seed. - long mSeed; - - /// Permutation table. - short perm[512]; - - /// Permutation table modulo 12. - short permMod12[512]; - - /* Gets a random long. - @return - A random long. - */ - unsigned long random(void); - - /** Dot product of a gradient with the given values. - @param g - The gradient. - @param x - The first value. - @param y - The second value. - @param z - The third value. - @return - The dot product. - */ - inline Real dot(const Vector3 &g, Real x, Real y, Real z) const - { - return g.x * x + g.y * y + g.z * z; - } - - /** Initializes the SimplexNoise instance. - */ - void init(unsigned long definedSeed); - - public: - - /** Constructor with a random permutation table. - */ - SimplexNoise(void); - - /** Constructor with a by seed defined permutation table. - @param definedSeed - The seed to use. - */ - SimplexNoise(unsigned long definedSeed); - - /** 3D noise function. - @param xIn - The first dimension parameter. - @param yIn - The second dimension parameter. - @param zIn - The third dimension parameter. - @return - The noise value. - */ - Real noise(Real xIn, Real yIn, Real zIn) const; - - /** Gets the current seed. - @return - The current seed. - */ - long getSeed(void) const; - - }; - /** @} */ - /** @} */ -} -} - -#endif diff --git a/Components/Volume/include/OgreVolumeSource.h b/Components/Volume/include/OgreVolumeSource.h deleted file mode 100644 index ae3af0a9c4b..00000000000 --- a/Components/Volume/include/OgreVolumeSource.h +++ /dev/null @@ -1,167 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Ogre_Volume_Source_H__ -#define __Ogre_Volume_Source_H__ - -#include "OgreVector.h" -#include "OgreVolumePrerequisites.h" - -namespace Ogre { -namespace Volume { - - /** \addtogroup Optional - * @{ - */ - /** \defgroup Volume Volume - * %Volume Rendering with LOD aimed at terrain - * @{ - */ - - /** Abstract class defining the density function. - */ - class _OgreVolumeExport Source - { - protected: - - /** Gets the start vector of an intersection. This is needed for restricted volumes - like discreet grids. - @param ray - The ray of the intersection. - @param maxDistance - The maximum distance to query the ray for intersections. - @return - The start point of the intersection ray. - */ - virtual Vector3 getIntersectionStart(const Ray &ray, Real maxDistance) const; - - /** Gets the end vector of an intersection. This is needed for restricted volumes - like discreet grids. - @param ray - The ray of the intersection. - @param maxDistance - The maximum distance to query the ray for intersections. - @return - The end point of the intersection ray. - */ - virtual Vector3 getIntersectionEnd(const Ray &ray, Real maxDistance) const; - - public: - - /// The id of volume files. - static const uint32 VOLUME_CHUNK_ID; - - /// The version of volume files. - static const uint16 VOLUME_CHUNK_VERSION; - - /// The amount of items being written as one chunk during serialization. - static const size_t SERIALIZATION_CHUNK_SIZE; - - /** Destructor. - */ - virtual ~Source(void); - - /** Gets the density value and gradient at a specific position. - @param position - The position. - @return - A vector with x, y, z containing the gradient and w containing the density. - */ - virtual Vector4 getValueAndGradient(const Vector3 &position) const = 0; - - /** Gets the density value at a specific position. - @param position - The position. - @return - The density. - */ - virtual Real getValue(const Vector3 &position) const = 0; - - /** Serializes a volume source to a discrete grid file with deflated - compression. To achieve better compression, all density values are clamped - within a maximum absolute value of (to - from).length() / 16.0. The values - are scanned in this inner-loop-order: z, x, y. y last because there is usually - the least isosurface intersection to be expected in the use case of terrain and - so more often the maximum density value hit. The values are written as 16 Bit - floats to save space. Note that this process is not lossless, the tradeoff is - between accuracy of the source-reproduction (smaller voxelWidth) and smaller - filesize (bigger voxelWidth). - @param from - The start point to scan the volume. - @param to - The end point to scan the volume. - @param voxelWidth - The width of a single cube in the density grid. - @param file - The file to write the grid to. - */ - void serialize(const Vector3 &from, const Vector3 &to, float voxelWidth, const String &file); - - /** Same as the other serialize function but with a user definable maximum absolute density value. - @param from - The start point to scan the volume. - @param to - The end point to scan the volume. - @param voxelWidth - The width of a single cube in the density grid. - @param maxClampedAbsoluteDensity - The maximum absolute density value to be written into the file, influencing the compression rate. - @param file - The file to write the grid to. - */ - void serialize(const Vector3 &from, const Vector3 &to, float voxelWidth, Real maxClampedAbsoluteDensity, const String &file); - - /** Gets the first intersection of a ray with the volume. - If you are using this together with the VolumeChunk: - Beware of the possible scaling or other transformations you did on the Chunk! Do the inverse first - on the ray origin. Example of a scaling with the factor 10: ray.setOrigin(ray.getOrigin() / (Real)10.0); - @param ray - The ray. - @param result - Will hold the intersection point if there is an intersection. - @param scale - The scaling of the volume compared to the world. - @param maxIterations - The maximum amount of iterations on the ray before giving up. - @param maxDistance - The maximum distance of the intersection point. - */ - bool getFirstRayIntersection(const Ray &ray, Vector3 &result, Real scale = (Real)1.0, size_t maxIterations = 5000, Real maxDistance = (Real)10000.0) const; - - /** Gets a factor to come from volume coordinate to world coordinate. - @return - The factor, 1.0 in the default implementation. - */ - Real getVolumeSpaceToWorldSpaceFactor(void) const; - }; - - /** @} */ - /** @} */ -} -} - -#endif diff --git a/Components/Volume/include/OgreVolumeTextureSource.h b/Components/Volume/include/OgreVolumeTextureSource.h deleted file mode 100644 index 4816b576124..00000000000 --- a/Components/Volume/include/OgreVolumeTextureSource.h +++ /dev/null @@ -1,92 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Ogre_Volume_TextureSource_H__ -#define __Ogre_Volume_TextureSource_H__ - - -#include "OgreVolumeGridSource.h" - -namespace Ogre { -namespace Volume { - /** \addtogroup Optional - * @{ - */ - /** \addtogroup Volume - * @{ - */ - /** A volume source from a 3D texture. - */ - class _OgreVolumeExport TextureSource : public GridSource - { - protected: - - /// To have a little bit faster data access. - unsigned long mWidthTimesHeight; - - /// The raw volume data. - float *mData; - - /** Overridden from GridSource. - */ - float getVolumeGridValue(size_t x, size_t y, size_t z) const override; - - /** Overridden from GridSource. - */ - void setVolumeGridValue(int x, int y, int z, float value) override; - - public: - - /** Constructur. - @param volumeTextureName - Which volume texture to get the data from. - @param worldWidth - The world width. - @param worldHeight - The world height. - @param worldDepth - The world depth. - @param trilinearValue - Whether to use trilinear filtering (true) or nearest neighbour (false) for the value. - @param trilinearGradient - Whether to use trilinear filtering (true) or nearest neighbour (false) for the gradient. - @param sobelGradient - Whether to add a bit of blur to the gradient like in a sobel filter. - */ - explicit TextureSource(const String &volumeTextureName, const Real worldWidth, const Real worldHeight, const Real worldDepth, const bool trilinearValue = true, const bool trilinearGradient = false, const bool sobelGradient = false); - - /** Destructor. - */ - ~TextureSource(void); - - }; - /** @} */ - /** @} */ -} -} - -#endif diff --git a/Components/Volume/src/OgreVolumeCSGSource.cpp b/Components/Volume/src/OgreVolumeCSGSource.cpp deleted file mode 100644 index 7dc13013c61..00000000000 --- a/Components/Volume/src/OgreVolumeCSGSource.cpp +++ /dev/null @@ -1,411 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreVolumeCSGSource.h" -#include - -namespace Ogre { -namespace Volume { - - Vector3 CSGCubeSource::mBoxNormals[6] = { - Vector3::UNIT_X, - Vector3::UNIT_Y, - Vector3::UNIT_Z, - Vector3::NEGATIVE_UNIT_X, - Vector3::NEGATIVE_UNIT_Y, - Vector3::NEGATIVE_UNIT_Z - }; - - //----------------------------------------------------------------------- - - CSGSphereSource::CSGSphereSource(const Real r, const Vector3 ¢er) : mR(r), mCenter(center) - { - } - - //----------------------------------------------------------------------- - - Vector4 CSGSphereSource::getValueAndGradient(const Vector3 &position) const - { - Vector3 pMinCenter = position- mCenter; - Vector3 gradient = pMinCenter; - return Vector4( - gradient.x, - gradient.y, - gradient.z, - mR - gradient.normalise() - ); - } - - //----------------------------------------------------------------------- - - Real CSGSphereSource::getValue(const Vector3 &position) const - { - Vector3 pMinCenter = position - mCenter; - return mR - pMinCenter.length(); - } - - //----------------------------------------------------------------------- - - CSGPlaneSource::CSGPlaneSource(const Real d, const Vector3 &normal) : mD(d), mNormal(normal.normalisedCopy()) - { - } - - //----------------------------------------------------------------------- - - Vector4 CSGPlaneSource::getValueAndGradient(const Vector3 &position) const - { - // Lineare Algebra: Ein geometrischer Zugang, S.180-181 - return Vector4( - mNormal.x, - mNormal.y, - mNormal.z, - mD - mNormal.dotProduct(position) - ); - } - - //----------------------------------------------------------------------- - - Real CSGPlaneSource::getValue(const Vector3 &position) const - { - // Lineare Algebra: Ein geometrischer Zugang, S.180-181 - return mD - mNormal.dotProduct(position); - } - - //----------------------------------------------------------------------- - - CSGCubeSource::CSGCubeSource(const Vector3 &min, const Vector3 &max) - { - mBox.setExtents(min, max); - } - - //----------------------------------------------------------------------- - - Vector4 CSGCubeSource::getValueAndGradient(const Vector3 &position) const - { - // Just approximate the normal via a simple Prewitt. To get the real normal, 26 cases had to be evaluated... - Vector3 gradient(getValue(Vector3(position.x + (Real)1.0, position.y, position.z)) - getValue(Vector3(position.x - (Real)1.0, position.y, position.z)), - getValue(Vector3(position.x, position.y + (Real)1.0, position.z)) - getValue(Vector3(position.x, position.y - (Real)1.0, position.z)), - getValue(Vector3(position.x, position.y, position.z + (Real)1.0)) - getValue(Vector3(position.x, position.y, position.z - (Real)1.0))); - gradient.normalise(); - gradient *= (Real)-1.0; - return Vector4( - gradient.x, - gradient.y, - gradient.z, - distanceTo(position)); - } - - //----------------------------------------------------------------------- - - Real CSGCubeSource::getValue(const Vector3 &position) const - { - return distanceTo(position); - } - - //----------------------------------------------------------------------- - - CSGOperationSource::CSGOperationSource(const Source *a, const Source *b) : mA(a), mB(b) - { - } - - //----------------------------------------------------------------------- - - CSGOperationSource::CSGOperationSource(void) : mA(0), mB(0) - { - } - - //----------------------------------------------------------------------- - - const Source* CSGOperationSource::getSourceA(void) const - { - return mA; - } - - //----------------------------------------------------------------------- - - void CSGOperationSource::setSourceA(Source *a) - { - mA = a; - } - - //----------------------------------------------------------------------- - - const Source* CSGOperationSource::getSourceB(void) const - { - return mB; - } - - //----------------------------------------------------------------------- - - void CSGOperationSource::setSourceB(Source *b) - { - mB = b; - } - - //----------------------------------------------------------------------- - - CSGIntersectionSource::CSGIntersectionSource(const Source *a, const Source *b) : CSGOperationSource(a, b) - { - } - - //----------------------------------------------------------------------- - - CSGIntersectionSource::CSGIntersectionSource(void) : CSGOperationSource() - { - } - - //----------------------------------------------------------------------- - - Vector4 CSGIntersectionSource::getValueAndGradient(const Vector3 &position) const - { - Vector4 valueA = mA->getValueAndGradient(position); - Vector4 valueB = mB->getValueAndGradient(position); - if (valueA.w < valueB.w) - { - return valueA; - } - return valueB; - } - - //----------------------------------------------------------------------- - - Real CSGIntersectionSource::getValue(const Vector3 &position) const - { - Real valueA = mA->getValue(position); - Real valueB = mB->getValue(position); - if (valueA < valueB) - { - return valueA; - } - return valueB; - } - - //----------------------------------------------------------------------- - - CSGUnionSource::CSGUnionSource(const Source *a, const Source *b) : CSGOperationSource(a, b) - { - } - - //----------------------------------------------------------------------- - - CSGUnionSource::CSGUnionSource(void) : CSGOperationSource() - { - } - - //----------------------------------------------------------------------- - - Vector4 CSGUnionSource::getValueAndGradient(const Vector3 &position) const - { - Vector4 valueA = mA->getValueAndGradient(position); - Vector4 valueB = mB->getValueAndGradient(position); - if (valueA.w > valueB.w) - { - return valueA; - } - return valueB; - } - - //----------------------------------------------------------------------- - - Real CSGUnionSource::getValue(const Vector3 &position) const - { - Real valueA = mA->getValue(position); - Real valueB = mB->getValue(position); - if (valueA > valueB) - { - return valueA; - } - return valueB; - } - - //----------------------------------------------------------------------- - - CSGDifferenceSource::CSGDifferenceSource(const Source *a, const Source *b) : CSGOperationSource(a, b) - { - } - - //----------------------------------------------------------------------- - - CSGDifferenceSource::CSGDifferenceSource(void) : CSGOperationSource() - { - } - - //----------------------------------------------------------------------- - - Vector4 CSGDifferenceSource::getValueAndGradient(const Vector3 &position) const - { - Vector4 valueA = mA->getValueAndGradient(position); - Vector4 valueB = (Real)-1.0 * mB->getValueAndGradient(position); - if (valueA.w < valueB.w) - { - return valueA; - } - return valueB; - } - - //----------------------------------------------------------------------- - - Real CSGDifferenceSource::getValue(const Vector3 &position) const - { - Real valueA = mA->getValue(position); - Real valueB = (Real)-1.0 * mB->getValue(position); - if (valueA < valueB) - { - return valueA; - } - return valueB; - } - - //----------------------------------------------------------------------- - - CSGUnarySource::CSGUnarySource(const Source *src) : mSrc(src) - { - } - - //----------------------------------------------------------------------- - - CSGUnarySource::CSGUnarySource(void) : mSrc(0) - { - } - - //----------------------------------------------------------------------- - - const Source* CSGUnarySource::getSource(void) const - { - return mSrc; - } - - //----------------------------------------------------------------------- - - void CSGUnarySource::setSource(Source *a) - { - mSrc = a; - } - - //----------------------------------------------------------------------- - - CSGNegateSource::CSGNegateSource(const Source *src) : CSGUnarySource(src) - { - } - - //----------------------------------------------------------------------- - - CSGNegateSource::CSGNegateSource(void) : CSGUnarySource() - { - } - - //----------------------------------------------------------------------- - - Vector4 CSGNegateSource::getValueAndGradient(const Vector3 &position) const - { - return (Real)-1.0 * mSrc->getValueAndGradient(position); - } - - //----------------------------------------------------------------------- - - Real CSGNegateSource::getValue(const Vector3 &position) const - { - return (Real)-1.0 * mSrc->getValue(position); - } - - //----------------------------------------------------------------------- - - CSGScaleSource::CSGScaleSource(const Source *src, const Real scale) : CSGUnarySource(src), mScale(scale) - { - } - - //----------------------------------------------------------------------- - - Vector4 CSGScaleSource::getValueAndGradient(const Vector3 &position) const - { - return mSrc->getValueAndGradient(position / mScale) * mScale; - } - - //----------------------------------------------------------------------- - - Real CSGScaleSource::getValue(const Vector3 &position) const - { - return mSrc->getValue(position / mScale) * mScale; - } - - //----------------------------------------------------------------------- - - void CSGNoiseSource::setData(void) - { - mGradientOff = fabs(mFrequencies[0]); - for (size_t i = 1; i < mNumOctaves; ++i) - { - if (fabs(mFrequencies[i]) < mGradientOff) - { - mGradientOff = mFrequencies[i]; - } - } - mGradientOff /= (Real)4.0; - mSeed = mNoise.getSeed(); - } - - //----------------------------------------------------------------------- - - CSGNoiseSource::CSGNoiseSource(const Source *src, Real *frequencies, Real *amplitudes, size_t numOctaves, long seed) : - CSGUnarySource(src), mFrequencies(frequencies), mAmplitudes(amplitudes), mNumOctaves(numOctaves), mNoise(seed) - { - setData(); - } - - //----------------------------------------------------------------------- - - CSGNoiseSource::CSGNoiseSource(const Source *src, Real *frequencies, Real *amplitudes, size_t numOctaves) : - CSGUnarySource(src), mFrequencies(frequencies), mAmplitudes(amplitudes), mNumOctaves(numOctaves) - { - setData(); - } - - //----------------------------------------------------------------------- - - Vector4 CSGNoiseSource::getValueAndGradient(const Vector3 &position) const - { - return Vector4( - -(getInternalValue(Vector3(position.x + mGradientOff, position.y, position.z)) - getInternalValue(Vector3(position.x - mGradientOff, position.y, position.z))), - -(getInternalValue(Vector3(position.x, position.y + mGradientOff, position.z)) - getInternalValue(Vector3(position.x, position.y - mGradientOff, position.z))), - -(getInternalValue(Vector3(position.x, position.y, position.z + mGradientOff)) - getInternalValue(Vector3(position.x, position.y, position.z - mGradientOff))), - getInternalValue(position)); - } - - //----------------------------------------------------------------------- - - Real CSGNoiseSource::getValue(const Vector3 &position) const - { - return getInternalValue(position); - } - - //----------------------------------------------------------------------- - - long CSGNoiseSource::getSeed(void) const - { - return mSeed; - } -} -} \ No newline at end of file diff --git a/Components/Volume/src/OgreVolumeCacheSource.cpp b/Components/Volume/src/OgreVolumeCacheSource.cpp deleted file mode 100644 index 4142cab109b..00000000000 --- a/Components/Volume/src/OgreVolumeCacheSource.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreVolumeCacheSource.h" - -namespace Ogre { -namespace Volume { - - //----------------------------------------------------------------------- - - bool operator<(const Vector3& a, const Vector3& b) - { - return memcmp(&a, &b, sizeof(Vector3)) < 0; - } - - //----------------------------------------------------------------------- - - CacheSource::CacheSource(const Source *src) : mSrc(src) - { - } - - //----------------------------------------------------------------------- - - Vector4 CacheSource::getValueAndGradient(const Vector3 &position) const - { - return getFromCache(position); - } - - //----------------------------------------------------------------------- - - Real CacheSource::getValue(const Vector3 &position) const - { - return getFromCache(position).w; - } - -} -} \ No newline at end of file diff --git a/Components/Volume/src/OgreVolumeChunk.cpp b/Components/Volume/src/OgreVolumeChunk.cpp deleted file mode 100644 index e18157d11c6..00000000000 --- a/Components/Volume/src/OgreVolumeChunk.cpp +++ /dev/null @@ -1,684 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreVolumeChunk.h" - -#include "OgreCamera.h" -#include "OgreLogManager.h" -#include "OgreConfigFile.h" -#include "OgreVolumeIsoSurfaceMC.h" -#include "OgreVolumeOctreeNodeSplitPolicy.h" -#include "OgreVolumeTextureSource.h" -#include "OgreVolumeMeshBuilder.h" -#include "OgreVolumeDualGridGenerator.h" -#include "OgreSceneNode.h" -#include "OgreViewport.h" -#include "OgreRoot.h" -#include "OgreVolumeChunk.h" - -#include -#include "OgreVolumeMeshBuilder.h" -#include "OgreVolumeOctreeNode.h" -#include "OgreMaterialManager.h" -#include "OgreWorkQueue.h" - -namespace Ogre { -namespace Volume { - - const String Chunk::MOVABLE_TYPE_NAME = "VolumeChunk"; - - //----------------------------------------------------------------------- - - void Chunk::loadChunk(SceneNode *parent, const Vector3 &from, const Vector3 &to, const Vector3 &totalFrom, const Vector3 &totalTo, const size_t level, const size_t maxLevels) - { - // This might already exist on update - if (!mNode) - { - mNode = parent->createChildSceneNode(); - } - if (mShared->parameters->createGeometryFromLevel == 0 || level <= mShared->parameters->createGeometryFromLevel) - { - mShared->chunksBeingProcessed++; - - // Call worker - ChunkRequest req; - req.totalFrom = totalFrom; - req.totalTo = totalTo; - req.level = level; - req.maxLevels = maxLevels; - req.isUpdate = mShared->parameters->updateFrom != Vector3::ZERO || mShared->parameters->updateTo != Vector3::ZERO; - - req.root = OGRE_NEW OctreeNode(from, to); - req.meshBuilder = OGRE_NEW MeshBuilder(); - req.dualGridGenerator = OGRE_NEW DualGridGenerator(); - - Root::getSingleton().getWorkQueue()->addTask([this, req]() { - prepareGeometry(req.level, req.root, req.dualGridGenerator, req.meshBuilder, req.totalFrom, req.totalTo); - Root::getSingleton().getWorkQueue()->addMainThreadTask([this, req]() { - loadGeometry(req.meshBuilder, req.dualGridGenerator, req.root, req.level, req.isUpdate); - delete req.root; - delete req.meshBuilder; - delete req.dualGridGenerator; - }); - }); - } - else - { - mInvisible = false; - } - } - - //----------------------------------------------------------------------- - - bool Chunk::contributesToVolumeMesh(const Vector3 &from, const Vector3 &to) const - { - Real centralValue = mShared->parameters->src->getValue((to - from) / (Real)2.0 + from); - return Math::Abs(centralValue) <= (to - from).length() * mShared->parameters->src->getVolumeSpaceToWorldSpaceFactor(); - } - - //----------------------------------------------------------------------- - - void Chunk::loadChildren(SceneNode *parent, const Vector3 &from, const Vector3 &to, const Vector3 &totalFrom, const Vector3 &totalTo, const size_t level, const size_t maxLevels) - { - // Now recursively create the more detailed children - if (level > 2) - { - Vector3 newCenter, xWidth, yWidth, zWidth; - OctreeNode::getChildrenDimensions(from, to, newCenter, xWidth, yWidth, zWidth); - if (!mChildren) - { - mChildren = new Chunk*[OctreeNode::OCTREE_CHILDREN_COUNT]; - mChildren[0] = createInstance(); - mChildren[1] = createInstance(); - mChildren[2] = createInstance(); - mChildren[3] = createInstance(); - mChildren[4] = createInstance(); - mChildren[5] = createInstance(); - mChildren[6] = createInstance(); - mChildren[7] = createInstance(); - mChildren[0]->mShared = mShared; - mChildren[1]->mShared = mShared; - mChildren[2]->mShared = mShared; - mChildren[3]->mShared = mShared; - mChildren[4]->mShared = mShared; - mChildren[5]->mShared = mShared; - mChildren[6]->mShared = mShared; - mChildren[7]->mShared = mShared; - } - mChildren[0]->doLoad(mNode, from, newCenter, totalFrom, totalTo, level - 1, maxLevels); - mChildren[1]->doLoad(mNode, from + xWidth, newCenter + xWidth, totalFrom, totalTo, level - 1, maxLevels); - mChildren[2]->doLoad(mNode, from + xWidth + zWidth, newCenter + xWidth + zWidth, totalFrom, totalTo, level - 1, maxLevels); - mChildren[3]->doLoad(mNode, from + zWidth, newCenter + zWidth, totalFrom, totalTo, level - 1, maxLevels); - mChildren[4]->doLoad(mNode, from + yWidth, newCenter + yWidth, totalFrom, totalTo, level - 1, maxLevels); - mChildren[5]->doLoad(mNode, from + yWidth + xWidth, newCenter + yWidth + xWidth, totalFrom, totalTo, level - 1, maxLevels); - mChildren[6]->doLoad(mNode, from + yWidth + xWidth + zWidth, newCenter + yWidth + xWidth + zWidth, totalFrom, totalTo, level - 1, maxLevels); - mChildren[7]->doLoad(mNode, from + yWidth + zWidth, newCenter + yWidth + zWidth, totalFrom, totalTo, level - 1, maxLevels); - } - // Just load one child of the same size as the parent for the leafes because they actually don't need to be subdivided as they - // are all rendered anyway. - else if (level > 1) - { - if (!mChildren) - { - mChildren = new Chunk*[2]; - mChildren[0] = createInstance(); - mChildren[0]->mShared = mShared; - mChildren[1] = 0; // Indicator that there are no more children. - } - mChildren[0]->doLoad(mNode, from, to, totalFrom, totalTo, level - 1, maxLevels); - } - } - - //----------------------------------------------------------------------- - - void Chunk::doLoad(SceneNode *parent, const Vector3 &from, const Vector3 &to, const Vector3 &totalFrom, const Vector3 &totalTo, const size_t level, const size_t maxLevels) - { - - // Handle the situation where we update an existing tree - if (mShared->parameters->updateFrom != Vector3::ZERO || mShared->parameters->updateTo != Vector3::ZERO) - { - // Early out if an update of a part of the tree volume is going on and this chunk is outside of the area. - AxisAlignedBox chunkCube(from, to); - AxisAlignedBox updatedCube(mShared->parameters->updateFrom, mShared->parameters->updateTo); - if (!chunkCube.intersects(updatedCube)) - { - return; - } - // Free memory from old mesh version - if (mRenderOp.vertexData) - { - OGRE_DELETE mRenderOp.vertexData; - mRenderOp.vertexData = 0; - } - if (mRenderOp.indexData) - { - OGRE_DELETE mRenderOp.indexData; - mRenderOp.indexData = 0; - } - } - - // Set to invisible for now. - mVisible = false; - mInvisible = true; - - // Don't generate this chunk if it doesn't contribute to the whole volume. - if (!contributesToVolumeMesh(from, to)) - { - return; - } - - loadChunk(parent, from, to, totalFrom, totalTo, level, maxLevels); - - loadChildren(parent, from, to, totalFrom, totalTo, level, maxLevels); - } - - //----------------------------------------------------------------------- - - void Chunk::prepareGeometry(size_t level, OctreeNode *root, DualGridGenerator *dualGridGenerator, MeshBuilder *meshBuilder, const Vector3 &totalFrom, const Vector3 &totalTo) - { - OctreeNodeSplitPolicy policy(mShared->parameters->src, - mShared->parameters->errorMultiplicator * mShared->parameters->baseError); - mError = (Real)level * mShared->parameters->errorMultiplicator * mShared->parameters->baseError; - root->split(&policy, mShared->parameters->src, mError); - Real maxMSDistance = (Real)level * mShared->parameters->errorMultiplicator * mShared->parameters->baseError * mShared->parameters->skirtFactor; - IsoSurface *is = OGRE_NEW IsoSurfaceMC(mShared->parameters->src); - dualGridGenerator->generateDualGrid(root, is, meshBuilder, maxMSDistance, totalFrom, totalTo, - mShared->parameters->createDualGridVisualization); - OGRE_DELETE is; - } - - //----------------------------------------------------------------------- - - void Chunk::loadGeometry(MeshBuilder *meshBuilder, DualGridGenerator *dualGridGenerator, OctreeNode *root, size_t level, bool isUpdate) - { - size_t chunkTriangles = meshBuilder->generateBuffers(mRenderOp); - mInvisible = chunkTriangles == 0; - - if (mShared->parameters->lodCallback) - { - meshBuilder->executeCallback(mShared->parameters->lodCallback, this, level, mShared->chunksBeingProcessed); - } - - mBox = meshBuilder->getBoundingBox(); - - if (!mInvisible) - { - if (isUpdate) - { - mNode->detachObject(this); - } - mNode->attachObject(this); - } - - mVisible = false; - - if (mShared->parameters->createDualGridVisualization) - { - mDualGrid = dualGridGenerator->getDualGrid(mShared->parameters->sceneManager); - if (mDualGrid) - { - mNode->attachObject(mDualGrid); - mDualGrid->setVisible(false); - } - } - - if (mShared->parameters->createOctreeVisualization) - { - mOctree = root->getOctreeGrid(mShared->parameters->sceneManager); - mNode->attachObject(mOctree); - mOctree->setVisible(false); - } - mShared->chunksBeingProcessed--; - } - - //----------------------------------------------------------------------- - - Chunk::Chunk(void) : mNode(0), mError(false), mDualGrid(0), mOctree(0), mChildren(0), - mInvisible(false), isRoot(false), mShared(0) - { - } - - //----------------------------------------------------------------------- - - Chunk::~Chunk(void) - { - OGRE_DELETE mRenderOp.indexData; - OGRE_DELETE mRenderOp.vertexData; - - // Root might already be shutdown. - if (Root::getSingletonPtr()) - { - Root::getSingleton().removeFrameListener(this); - } - - if (mChildren) - { - OGRE_DELETE mChildren[0]; - if (mChildren[1]) - { - OGRE_DELETE mChildren[1]; - OGRE_DELETE mChildren[2]; - OGRE_DELETE mChildren[3]; - OGRE_DELETE mChildren[4]; - OGRE_DELETE mChildren[5]; - OGRE_DELETE mChildren[6]; - OGRE_DELETE mChildren[7]; - } - } - delete[] mChildren; - if (isRoot) - { - delete mShared; - } - } - - //----------------------------------------------------------------------- - - const String& Chunk::getMovableType(void) const - { - return MOVABLE_TYPE_NAME; - } - - //----------------------------------------------------------------------- - - Real Chunk::getSquaredViewDepth(const Camera* camera) const - { - return (mBox.getCenter() * mShared->parameters->scale).squaredDistance(camera->getDerivedPosition()); - } - - //----------------------------------------------------------------------- - - Real Chunk::getBoundingRadius() const - { - return mBox.getMinimum().distance(mBox.getCenter()) * mShared->parameters->scale; - } - - //----------------------------------------------------------------------- - - void Chunk::load(SceneNode *parent, const Vector3 &from, const Vector3 &to, size_t level, const ChunkParameters *parameters) - { - if (parameters->baseError == (Real)0.0 || parameters->errorMultiplicator == (Real)0.0 || - parameters->sceneManager == 0 || parameters->src == 0) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Invalid parameters given!"); - } - - isRoot = true; - - // Don't recreate the shared parameters on update. - if (parameters->updateFrom == Vector3::ZERO && parameters->updateTo == Vector3::ZERO) - { - mShared = new ChunkTreeSharedData(parameters); - parent->scale(Vector3(parameters->scale)); - } - - mShared->chunksBeingProcessed = 0; - - doLoad(parent, from, to, from, to, level, level); - - // Wait for the threads. - if (!parameters->async) - { - while(mShared->chunksBeingProcessed) - { - OGRE_THREAD_SLEEP(0); - Root::getSingleton().getWorkQueue()->processMainThreadTasks(); - } - } - - - // Just add the frame listener on initial load - if (parameters->updateFrom == Vector3::ZERO && parameters->updateTo == Vector3::ZERO) - { - Root::getSingleton().addFrameListener(this); - } - } - - //----------------------------------------------------------------------- - - void Chunk::load(SceneNode *parent, SceneManager *sceneManager, const String& filename, bool validSourceResult, MeshBuilderCallback *lodCallback, const String& resourceGroup) - { - ConfigFile config; - config.loadFromResourceSystem(filename, resourceGroup); - - String source = config.getSetting("source"); - Vector3 dimensions = StringConverter::parseVector3(config.getSetting("sourceDimensions")); - bool trilinearValue = StringConverter::parseBool(config.getSetting("trilinearValue")); - bool trilinearGradient = StringConverter::parseBool(config.getSetting("trilinearGradient")); - bool sobelGradient = StringConverter::parseBool(config.getSetting("sobelGradient")); - bool async = StringConverter::parseBool(config.getSetting("async")); - - TextureSource *textureSource = new TextureSource(source, dimensions.x, dimensions.y, dimensions.z, trilinearValue, trilinearGradient, sobelGradient); - - Vector3 from = StringConverter::parseVector3(config.getSetting("scanFrom")); - Vector3 to = StringConverter::parseVector3(config.getSetting("scanTo")); - size_t level = StringConverter::parseUnsignedInt(config.getSetting("level")); - Real scale = StringConverter::parseReal(config.getSetting("scale")); - Real maxScreenSpaceError = StringConverter::parseReal(config.getSetting("maxScreenSpaceError")); - - ChunkParameters parameters; - parameters.sceneManager = sceneManager; - parameters.lodCallback = lodCallback; - parameters.src = textureSource; - parameters.scale = scale; - parameters.maxScreenSpaceError = maxScreenSpaceError; - parameters.createGeometryFromLevel = StringConverter::parseInt(config.getSetting("createGeometryFromLevel")); - parameters.baseError = StringConverter::parseReal(config.getSetting("baseError")); - parameters.errorMultiplicator = StringConverter::parseReal(config.getSetting("errorMultiplicator")); - parameters.createOctreeVisualization = StringConverter::parseBool(config.getSetting("createOctreeVisualization")); - parameters.createDualGridVisualization = StringConverter::parseBool(config.getSetting("createDualGridVisualization")); - parameters.skirtFactor = StringConverter::parseReal(config.getSetting("skirtFactor")); - parameters.async = async; - - load(parent, from, to, level, ¶meters); - - if (!validSourceResult) - { - delete textureSource; - } - - MaterialPtr mat = MaterialManager::getSingleton().getByName(config.getSetting("material")); - setMaterial(mat); - - for (size_t i = 0; i < level; ++i) - { - StringStream stream; - stream << "materialOfLevel" << i; - - String materialOfLevel = config.getSetting(stream.str()); - if (!materialOfLevel.empty()) - { - mat = MaterialManager::getSingleton().getByName(config.getSetting(stream.str())); - setMaterialOfLevel(i, mat); - } - } - } - - //----------------------------------------------------------------------- - - void Chunk::setDualGridVisible(const bool visible) - { - mShared->dualGridVisible = visible; - if (mChildren) - { - mChildren[0]->setDualGridVisible(visible); - if (mChildren[1]) - { - mChildren[1]->setDualGridVisible(visible); - mChildren[2]->setDualGridVisible(visible); - mChildren[3]->setDualGridVisible(visible); - mChildren[4]->setDualGridVisible(visible); - mChildren[5]->setDualGridVisible(visible); - mChildren[6]->setDualGridVisible(visible); - mChildren[7]->setDualGridVisible(visible); - } - } - } - - //----------------------------------------------------------------------- - - bool Chunk::getDualGridVisible(void) const - { - return mShared->dualGridVisible; - } - - //----------------------------------------------------------------------- - - void Chunk::setOctreeVisible(const bool visible) - { - mShared->octreeVisible = visible; - if (mChildren) - { - mChildren[0]->setOctreeVisible(visible); - if (mChildren[1]) - { - mChildren[1]->setOctreeVisible(visible); - mChildren[2]->setOctreeVisible(visible); - mChildren[3]->setOctreeVisible(visible); - mChildren[4]->setOctreeVisible(visible); - mChildren[5]->setOctreeVisible(visible); - mChildren[6]->setOctreeVisible(visible); - mChildren[7]->setOctreeVisible(visible); - } - } - } - - //----------------------------------------------------------------------- - - bool Chunk::getOctreeVisible(void) const - { - return mShared->octreeVisible; - } - - //----------------------------------------------------------------------- - - bool Chunk::getVolumeVisible(void) const - { - return mShared->volumeVisible; - } - - //----------------------------------------------------------------------- - - bool Chunk::frameStarted(const FrameEvent& evt) - { - - if (mInvisible) - { - return true; - } - - // This might be a chunk on a lower LOD level without geometry, so lets just proceed here. - if (!mRenderOp.vertexData && mChildren) - { - mChildren[0]->frameStarted(evt); - if (mChildren[1]) - { - mChildren[1]->frameStarted(evt); - mChildren[2]->frameStarted(evt); - mChildren[3]->frameStarted(evt); - mChildren[4]->frameStarted(evt); - mChildren[5]->frameStarted(evt); - mChildren[6]->frameStarted(evt); - mChildren[7]->frameStarted(evt); - } - return true; - } - - if (!mCamera || !mCamera->getViewport()) - { - setChunkVisible(true, false); - return true; - } - - Real k = ((Real)mCamera->getViewport()->getActualHeight() / ((Real)2.0 * std::tan(mCamera->getFOVy().valueRadians() / (Real)2.0))); - - - // Get the distance to the center. - Vector3 camPos = mCamera->getRealPosition(); - Real d = (mBox.getCenter() * mShared->parameters->scale).distance(camPos); - if (d < 1.0) - { - d = 1.0; - } - - Real screenSpaceError = mError / d * k; - - if (screenSpaceError <= mShared->parameters->maxScreenSpaceError / mShared->parameters->scale) - { - setChunkVisible(true, false); - if (mChildren) - { - mChildren[0]->setChunkVisible(false, true); - if (mChildren[1]) - { - mChildren[1]->setChunkVisible(false, true); - mChildren[2]->setChunkVisible(false, true); - mChildren[3]->setChunkVisible(false, true); - mChildren[4]->setChunkVisible(false, true); - mChildren[5]->setChunkVisible(false, true); - mChildren[6]->setChunkVisible(false, true); - mChildren[7]->setChunkVisible(false, true); - } - } - } - else - { - setChunkVisible(false, false); - if (mChildren) - { - mChildren[0]->frameStarted(evt); - if (mChildren[1]) - { - mChildren[1]->frameStarted(evt); - mChildren[2]->frameStarted(evt); - mChildren[3]->frameStarted(evt); - mChildren[4]->frameStarted(evt); - mChildren[5]->frameStarted(evt); - mChildren[6]->frameStarted(evt); - mChildren[7]->frameStarted(evt); - } - } - else - { - setChunkVisible(true, false); - } - } - - return true; - } - - //----------------------------------------------------------------------- - - Chunk* Chunk::createInstance(void) - { - return OGRE_NEW Chunk(); - } - - //----------------------------------------------------------------------- - - void Chunk::setMaterial(const MaterialPtr& mat) - { - SimpleRenderable::setMaterial(mat); - - if (mChildren) - { - mChildren[0]->setMaterial(mat); - if (mChildren[1]) - { - mChildren[1]->setMaterial(mat); - mChildren[2]->setMaterial(mat); - mChildren[3]->setMaterial(mat); - mChildren[4]->setMaterial(mat); - mChildren[5]->setMaterial(mat); - mChildren[6]->setMaterial(mat); - mChildren[7]->setMaterial(mat); - } - } - } - - //----------------------------------------------------------------------- - void Chunk::setMaterialOfLevel(size_t level, const MaterialPtr& mat) - { - if (level == 0) - { - SimpleRenderable::setMaterial(mat); - } - - if (level > 0 && mChildren) - { - mChildren[0]->setMaterialOfLevel(level - 1, mat); - if (mChildren[1]) - { - mChildren[1]->setMaterialOfLevel(level - 1, mat); - mChildren[2]->setMaterialOfLevel(level - 1, mat); - mChildren[3]->setMaterialOfLevel(level - 1, mat); - mChildren[4]->setMaterialOfLevel(level - 1, mat); - mChildren[5]->setMaterialOfLevel(level - 1, mat); - mChildren[6]->setMaterialOfLevel(level - 1, mat); - mChildren[7]->setMaterialOfLevel(level - 1, mat); - } - } - } - - //----------------------------------------------------------------------- - - void Chunk::getChunksOfLevel(const size_t level, VecChunk &result) const - { - if (level == 0) - { - if (!mInvisible) - { - result.push_back(this); - } - return; - } - - if (mChildren) - { - mChildren[0]->getChunksOfLevel(level - 1, result); - if (mChildren[1]) - { - mChildren[1]->getChunksOfLevel(level - 1, result); - mChildren[2]->getChunksOfLevel(level - 1, result); - mChildren[3]->getChunksOfLevel(level - 1, result); - mChildren[4]->getChunksOfLevel(level - 1, result); - mChildren[5]->getChunksOfLevel(level - 1, result); - mChildren[6]->getChunksOfLevel(level - 1, result); - mChildren[7]->getChunksOfLevel(level - 1, result); - } - } - } - - //----------------------------------------------------------------------- - - void Chunk::setVolumeVisible(bool visible) - { - mShared->volumeVisible = visible; - mVisible = visible; - if (mChildren) - { - mChildren[0]->setVolumeVisible(visible); - if (mChildren[1]) - { - mChildren[1]->setVolumeVisible(visible); - mChildren[2]->setVolumeVisible(visible); - mChildren[3]->setVolumeVisible(visible); - mChildren[4]->setVolumeVisible(visible); - mChildren[5]->setVolumeVisible(visible); - mChildren[6]->setVolumeVisible(visible); - mChildren[7]->setVolumeVisible(visible); - } - } - } - - //----------------------------------------------------------------------- - - ChunkParameters* Chunk::getChunkParameters(void) - { - return mShared->parameters; - } -} -} diff --git a/Components/Volume/src/OgreVolumeDualGridGenerator.cpp b/Components/Volume/src/OgreVolumeDualGridGenerator.cpp deleted file mode 100644 index e9f93c781a5..00000000000 --- a/Components/Volume/src/OgreVolumeDualGridGenerator.cpp +++ /dev/null @@ -1,549 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreVolumeDualGridGenerator.h" -#include "OgreManualObject.h" -#include "OgreSceneManager.h" -#include "OgreVolumeMeshBuilder.h" - -namespace Ogre { -namespace Volume { - - size_t DualGridGenerator::mDualGridI = 0; - - //----------------------------------------------------------------------- - - void DualGridGenerator::nodeProc(const OctreeNode *n) - { - if (n->isSubdivided()) - { - - const OctreeNode *c0 = n->getChild(0); - const OctreeNode *c1 = n->getChild(1); - const OctreeNode *c2 = n->getChild(2); - const OctreeNode *c3 = n->getChild(3); - const OctreeNode *c4 = n->getChild(4); - const OctreeNode *c5 = n->getChild(5); - const OctreeNode *c6 = n->getChild(6); - const OctreeNode *c7 = n->getChild(7); - - nodeProc(c0); - nodeProc(c1); - nodeProc(c2); - nodeProc(c3); - nodeProc(c4); - nodeProc(c5); - nodeProc(c6); - nodeProc(c7); - - faceProcXY(c0, c3); - faceProcXY(c1, c2); - faceProcXY(c4, c7); - faceProcXY(c5, c6); - - faceProcZY(c0, c1); - faceProcZY(c3, c2); - faceProcZY(c4, c5); - faceProcZY(c7, c6); - - faceProcXZ(c4, c0); - faceProcXZ(c5, c1); - faceProcXZ(c7, c3); - faceProcXZ(c6, c2); - - edgeProcX(c0, c3, c7, c4); - edgeProcX(c1, c2, c6, c5); - - edgeProcY(c0, c1, c2, c3); - edgeProcY(c4, c5, c6, c7); - - edgeProcZ(c7, c6, c2, c3); - edgeProcZ(c4, c5, c1, c0); - - vertProc(c0, c1, c2, c3, c4, c5, c6, c7); - } - } - - //----------------------------------------------------------------------- - - void DualGridGenerator::faceProcXY(const OctreeNode *n0, const OctreeNode *n1) - { - const bool n0Subdivided = n0->isSubdivided(); - const bool n1Subdivided = n1->isSubdivided(); - - if (n0Subdivided || n1Subdivided) - { - const OctreeNode *c0 = n0Subdivided ? n0->getChild(3) : n0; - const OctreeNode *c1 = n0Subdivided ? n0->getChild(2) : n0; - const OctreeNode *c2 = n1Subdivided ? n1->getChild(1) : n1; - const OctreeNode *c3 = n1Subdivided ? n1->getChild(0) : n1; - - const OctreeNode *c4 = n0Subdivided ? n0->getChild(7) : n0; - const OctreeNode *c5 = n0Subdivided ? n0->getChild(6) : n0; - const OctreeNode *c6 = n1Subdivided ? n1->getChild(5) : n1; - const OctreeNode *c7 = n1Subdivided ? n1->getChild(4) : n1; - - faceProcXY(c0, c3); - faceProcXY(c1, c2); - faceProcXY(c4, c7); - faceProcXY(c5, c6); - - edgeProcX(c0, c3, c7, c4); - edgeProcX(c1, c2, c6, c5); - edgeProcY(c0, c1, c2, c3); - edgeProcY(c4, c5, c6, c7); - - vertProc(c0, c1, c2, c3, c4, c5, c6, c7); - } - } - - //----------------------------------------------------------------------- - - void DualGridGenerator::faceProcZY(const OctreeNode *n0, const OctreeNode *n1) - { - const bool n0Subdivided = n0->isSubdivided(); - const bool n1Subdivided = n1->isSubdivided(); - - if (n0Subdivided || n1Subdivided) - { - const OctreeNode *c0 = n0Subdivided ? n0->getChild(1) : n0; - const OctreeNode *c1 = n1Subdivided ? n1->getChild(0) : n1; - const OctreeNode *c2 = n1Subdivided ? n1->getChild(3) : n1; - const OctreeNode *c3 = n0Subdivided ? n0->getChild(2) : n0; - - const OctreeNode *c4 = n0Subdivided ? n0->getChild(5) : n0; - const OctreeNode *c5 = n1Subdivided ? n1->getChild(4) : n1; - const OctreeNode *c6 = n1Subdivided ? n1->getChild(7) : n1; - const OctreeNode *c7 = n0Subdivided ? n0->getChild(6) : n0; - - faceProcZY(c0, c1); - faceProcZY(c3, c2); - faceProcZY(c4, c5); - faceProcZY(c7, c6); - - edgeProcY(c0, c1, c2, c3); - edgeProcY(c4, c5, c6, c7); - edgeProcZ(c7, c6, c2, c3); - edgeProcZ(c4, c5, c1, c0); - - vertProc(c0, c1, c2, c3, c4, c5, c6, c7); - } - } - - //----------------------------------------------------------------------- - - void DualGridGenerator::faceProcXZ(const OctreeNode *n0, const OctreeNode *n1) - { - const bool n0Subdivided = n0->isSubdivided(); - const bool n1Subdivided = n1->isSubdivided(); - - if (n0Subdivided || n1Subdivided) - { - const OctreeNode *c0 = n1Subdivided ? n1->getChild(4) : n1; - const OctreeNode *c1 = n1Subdivided ? n1->getChild(5) : n1; - const OctreeNode *c2 = n1Subdivided ? n1->getChild(6) : n1; - const OctreeNode *c3 = n1Subdivided ? n1->getChild(7) : n1; - - const OctreeNode *c4 = n0Subdivided ? n0->getChild(0) : n0; - const OctreeNode *c5 = n0Subdivided ? n0->getChild(1) : n0; - const OctreeNode *c6 = n0Subdivided ? n0->getChild(2) : n0; - const OctreeNode *c7 = n0Subdivided ? n0->getChild(3) : n0; - - faceProcXZ(c4, c0); - faceProcXZ(c5, c1); - faceProcXZ(c7, c3); - faceProcXZ(c6, c2); - - edgeProcX(c0, c3, c7, c4); - edgeProcX(c1, c2, c6, c5); - edgeProcZ(c7, c6, c2, c3); - edgeProcZ(c4, c5, c1, c0); - - vertProc(c0, c1, c2, c3, c4, c5, c6, c7); - } - } - - //----------------------------------------------------------------------- - - void DualGridGenerator::edgeProcX(const OctreeNode *n0, const OctreeNode *n1, const OctreeNode *n2, const OctreeNode *n3) - { - const bool n0Subdivided = n0->isSubdivided(); - const bool n1Subdivided = n1->isSubdivided(); - const bool n2Subdivided = n2->isSubdivided(); - const bool n3Subdivided = n3->isSubdivided(); - - if (n0Subdivided || n1Subdivided || n2Subdivided || n3Subdivided) - { - const OctreeNode *c0 = n0Subdivided ? n0->getChild(7) : n0; - const OctreeNode *c1 = n0Subdivided ? n0->getChild(6) : n0; - const OctreeNode *c2 = n1Subdivided ? n1->getChild(5) : n1; - const OctreeNode *c3 = n1Subdivided ? n1->getChild(4) : n1; - const OctreeNode *c4 = n3Subdivided ? n3->getChild(3) : n3; - const OctreeNode *c5 = n3Subdivided ? n3->getChild(2) : n3; - const OctreeNode *c6 = n2Subdivided ? n2->getChild(1) : n2; - const OctreeNode *c7 = n2Subdivided ? n2->getChild(0) : n2; - - edgeProcX(c0, c3, c7, c4); - edgeProcX(c1, c2, c6, c5); - - vertProc(c0, c1, c2, c3, c4, c5, c6, c7); - } - } - - //----------------------------------------------------------------------- - - void DualGridGenerator::edgeProcY(const OctreeNode *n0, const OctreeNode *n1, const OctreeNode *n2, const OctreeNode *n3) - { - const bool n0Subdivided = n0->isSubdivided(); - const bool n1Subdivided = n1->isSubdivided(); - const bool n2Subdivided = n2->isSubdivided(); - const bool n3Subdivided = n3->isSubdivided(); - - if (n0Subdivided || n1Subdivided || n2Subdivided || n3Subdivided) - { - const OctreeNode *c0 = n0Subdivided ? n0->getChild(2) : n0; - const OctreeNode *c1 = n1Subdivided ? n1->getChild(3) : n1; - const OctreeNode *c2 = n2Subdivided ? n2->getChild(0) : n2; - const OctreeNode *c3 = n3Subdivided ? n3->getChild(1) : n3; - const OctreeNode *c4 = n0Subdivided ? n0->getChild(6) : n0; - const OctreeNode *c5 = n1Subdivided ? n1->getChild(7) : n1; - const OctreeNode *c6 = n2Subdivided ? n2->getChild(4) : n2; - const OctreeNode *c7 = n3Subdivided ? n3->getChild(5) : n3; - - edgeProcY(c0, c1, c2, c3); - edgeProcY(c4, c5, c6, c7); - - vertProc(c0, c1, c2, c3, c4, c5, c6, c7); - } - } - - //----------------------------------------------------------------------- - - void DualGridGenerator::edgeProcZ(const OctreeNode *n0, const OctreeNode *n1, const OctreeNode *n2, const OctreeNode *n3) - { - const bool n0Subdivided = n0->isSubdivided(); - const bool n1Subdivided = n1->isSubdivided(); - const bool n2Subdivided = n2->isSubdivided(); - const bool n3Subdivided = n3->isSubdivided(); - - if (n0Subdivided || n1Subdivided || n2Subdivided || n3Subdivided) - { - const OctreeNode *c0 = n3Subdivided ? n3->getChild(5) : n3; - const OctreeNode *c1 = n2Subdivided ? n2->getChild(4) : n2; - const OctreeNode *c2 = n2Subdivided ? n2->getChild(7) : n2; - const OctreeNode *c3 = n3Subdivided ? n3->getChild(6) : n3; - const OctreeNode *c4 = n0Subdivided ? n0->getChild(1) : n0; - const OctreeNode *c5 = n1Subdivided ? n1->getChild(0) : n1; - const OctreeNode *c6 = n1Subdivided ? n1->getChild(3) : n1; - const OctreeNode *c7 = n0Subdivided ? n0->getChild(2) : n0; - - edgeProcZ(c7, c6, c2, c3); - edgeProcZ(c4, c5, c1, c0); - - vertProc(c0, c1, c2, c3, c4, c5, c6, c7); - } - } - - //----------------------------------------------------------------------- - - void DualGridGenerator::vertProc(const OctreeNode *n0, const OctreeNode *n1, const OctreeNode *n2, const OctreeNode *n3, const OctreeNode *n4, const OctreeNode *n5, const OctreeNode *n6, const OctreeNode *n7) - { - const bool n0Subdivided = n0->isSubdivided(); - const bool n1Subdivided = n1->isSubdivided(); - const bool n2Subdivided = n2->isSubdivided(); - const bool n3Subdivided = n3->isSubdivided(); - const bool n4Subdivided = n4->isSubdivided(); - const bool n5Subdivided = n5->isSubdivided(); - const bool n6Subdivided = n6->isSubdivided(); - const bool n7Subdivided = n7->isSubdivided(); - - if (n0Subdivided || n1Subdivided || n2Subdivided || n3Subdivided || - n4Subdivided || n5Subdivided || n6Subdivided || n7Subdivided) - { - const OctreeNode *c0 = n0Subdivided ? n0->getChild(6) : n0; - const OctreeNode *c1 = n1Subdivided ? n1->getChild(7) : n1; - const OctreeNode *c2 = n2Subdivided ? n2->getChild(4) : n2; - const OctreeNode *c3 = n3Subdivided ? n3->getChild(5) : n3; - const OctreeNode *c4 = n4Subdivided ? n4->getChild(2) : n4; - const OctreeNode *c5 = n5Subdivided ? n5->getChild(3) : n5; - const OctreeNode *c6 = n6Subdivided ? n6->getChild(0) : n6; - const OctreeNode *c7 = n7Subdivided ? n7->getChild(1) : n7; - - vertProc(c0, c1, c2, c3, c4, c5, c6, c7); - } - else - { - - if (!n0->isIsoSurfaceNear() && !n1->isIsoSurfaceNear() && !n2->isIsoSurfaceNear() && !n3->isIsoSurfaceNear() && - !n4->isIsoSurfaceNear() && !n5->isIsoSurfaceNear() && !n6->isIsoSurfaceNear() && !n7->isIsoSurfaceNear()) - { - return; - } - - Vector4 values[8]; - values[0] = n0->getCenterValue(); - values[1] = n1->getCenterValue(); - values[2] = n2->getCenterValue(); - values[3] = n3->getCenterValue(); - values[4] = n4->getCenterValue(); - values[5] = n5->getCenterValue(); - values[6] = n6->getCenterValue(); - values[7] = n7->getCenterValue(); - addDualCell(n0->getCenter(), n1->getCenter(), n2->getCenter(), n3->getCenter(), - n4->getCenter(), n5->getCenter(), n6->getCenter(), n7->getCenter(), values); - createBorderCells(n0, n1, n2, n3, n4, n5, n6, n7); - } - } - - //----------------------------------------------------------------------- - - void DualGridGenerator::createBorderCells(const OctreeNode *n0, const OctreeNode *n1, const OctreeNode *n2, const OctreeNode *n3, const OctreeNode *n4, const OctreeNode *n5, const OctreeNode *n6, const OctreeNode *n7) - { - if (n0->isBorderBack(*mRoot) && n1->isBorderBack(*mRoot) && n4->isBorderBack(*mRoot) && n5->isBorderBack(*mRoot)) - { - addDualCell(n0->getCenterBack(), n1->getCenterBack(), n1->getCenter(), n0->getCenter(), - n4->getCenterBack(), n5->getCenterBack(), n5->getCenter(), n4->getCenter()); - // Generate back edge border cells - if (n4->isBorderTop(*mRoot) && n5->isBorderTop(*mRoot)) - { - addDualCell(n4->getCenterBack(), n5->getCenterBack(), n5->getCenter(), n4->getCenter(), - n4->getCenterBackTop(), n5->getCenterBackTop(), n5->getCenterTop(), n4->getCenterTop()); - // Generate back top corner cells - if (n4->isBorderLeft(*mRoot)) - { - addDualCell(n4->getCenterBackLeft(), n4->getCenterBack(), n4->getCenter(), n4->getCenterLeft(), - n4->getCorner4(), n4->getCenterBackTop(), n4->getCenterTop(), n4->getCenterLeftTop()); - } - if (n5->isBorderRight(*mRoot)) - { - addDualCell(n5->getCenterBack(), n5->getCenterBackRight(), n5->getCenterRight(), n5->getCenter(), - n5->getCenterBackTop(), n5->getCorner5(), n5->getCenterRightTop(), n5->getCenterTop()); - } - } - if (n0->isBorderBottom(*mRoot) && n1->isBorderBottom(*mRoot)) - { - addDualCell(n0->getCenterBackBottom(), n1->getCenterBackBottom(), n1->getCenterBottom(), n0->getCenterBottom(), - n0->getCenterBack(), n1->getCenterBack(), n1->getCenter(), n0->getCenter()); - // Generate back bottom corner cells - if (n0->isBorderLeft(*mRoot)) - { - addDualCell(n0->getFrom(), n0->getCenterBackBottom(), n0->getCenterBottom(), n0->getCenterLeftBottom(), - n0->getCenterBackLeft(), n0->getCenterBack(), n0->getCenter(), n0->getCenterLeft()); - } - if (n1->isBorderRight(*mRoot)) - { - addDualCell(n1->getCenterBackBottom(), n1->getCorner1(), n1->getCenterRightBottom(), n1->getCenterBottom(), - n1->getCenterBack(), n1->getCenterBackRight(), n1->getCenterRight(), n1->getCenter()); - } - } - } - if (n2->isBorderFront(*mRoot) && n3->isBorderFront(*mRoot) && n6->isBorderFront(*mRoot) && n7->isBorderFront(*mRoot)) - { - addDualCell(n3->getCenter(), n2->getCenter(), n2->getCenterFront(), n3->getCenterFront(), - n7->getCenter(), n6->getCenter(), n6->getCenterFront(), n7->getCenterFront()); - // Generate front edge border cells - if (n6->isBorderTop(*mRoot) && n7->isBorderTop(*mRoot)) - { - addDualCell(n7->getCenter(), n6->getCenter(), n6->getCenterFront(), n7->getCenterFront(), - n7->getCenterTop(), n6->getCenterTop(), n6->getCenterFrontTop(), n7->getCenterFrontTop()); - // Generate back bottom corner cells - if (n7->isBorderLeft(*mRoot)) - { - addDualCell(n7->getCenterLeft(), n7->getCenter(), n7->getCenterFront(), n7->getCenterFrontLeft(), - n7->getCenterLeftTop(), n7->getCenterTop(), n7->getCenterFrontTop(), n7->getCorner7()); - } - if (n6->isBorderRight(*mRoot)) - { - addDualCell(n6->getCenter(), n6->getCenterRight(), n6->getCenterFrontRight(), n6->getCenterFront(), - n6->getCenterTop(), n6->getCenterRightTop(), n6->getTo(), n6->getCenterFrontTop()); - } - } - if (n3->isBorderBottom(*mRoot) && n2->isBorderBottom(*mRoot)) - { - addDualCell(n3->getCenterBottom(), n2->getCenterBottom(), n2->getCenterFrontBottom(), n3->getCenterFrontBottom(), - n3->getCenter(), n2->getCenter(), n2->getCenterFront(), n3->getCenterFront()); - // Generate back bottom corner cells - if (n3->isBorderLeft(*mRoot)) - { - addDualCell(n3->getCenterLeftBottom(), n3->getCenterBottom(), n3->getCenterFrontBottom(), n3->getCorner3(), - n3->getCenterLeft(), n3->getCenter(), n3->getCenterFront(), n3->getCenterFrontLeft()); - } - if (n2->isBorderRight(*mRoot)) - { - addDualCell(n2->getCenterBottom(), n2->getCenterRightBottom(), n2->getCorner2(), n2->getCenterFrontBottom(), - n2->getCenter(), n2->getCenterRight(), n2->getCenterFrontRight(), n2->getCenterFront()); - } - } - } - if (n0->isBorderLeft(*mRoot) && n3->isBorderLeft(*mRoot) && n4->isBorderLeft(*mRoot) && n7->isBorderLeft(*mRoot)) - { - addDualCell(n0->getCenterLeft(), n0->getCenter(), n3->getCenter(), n3->getCenterLeft(), - n4->getCenterLeft(), n4->getCenter(), n7->getCenter(), n7->getCenterLeft()); - // Generate left edge border cells - if (n4->isBorderTop(*mRoot) && n7->isBorderTop(*mRoot)) - { - addDualCell(n4->getCenterLeft(), n4->getCenter(), n7->getCenter(), n7->getCenterLeft(), - n4->getCenterLeftTop(), n4->getCenterTop(), n7->getCenterTop(), n7->getCenterLeftTop()); - } - if (n0->isBorderBottom(*mRoot) && n3->isBorderBottom(*mRoot)) - { - addDualCell(n0->getCenterLeftBottom(), n0->getCenterBottom(), n3->getCenterBottom(), n3->getCenterLeftBottom(), - n0->getCenterLeft(), n0->getCenter(), n3->getCenter(), n3->getCenterLeft()); - } - if (n0->isBorderBack(*mRoot) && n4->isBorderBack(*mRoot)) - { - addDualCell(n0->getCenterBackLeft(), n0->getCenterBack(), n0->getCenter(), n0->getCenterLeft(), - n4->getCenterBackLeft(), n4->getCenterBack(), n4->getCenter(), n4->getCenterLeft()); - } - if (n3->isBorderFront(*mRoot) && n7->isBorderFront(*mRoot)) - { - addDualCell(n3->getCenterLeft(), n3->getCenter(), n3->getCenterFront(), n3->getCenterFrontLeft(), - n7->getCenterLeft(), n7->getCenter(), n7->getCenterFront(), n7->getCenterFrontLeft()); - } - } - if (n1->isBorderRight(*mRoot) && n2->isBorderRight(*mRoot) && n5->isBorderRight(*mRoot) && n6->isBorderRight(*mRoot)) - { - addDualCell(n1->getCenter(), n1->getCenterRight(), n2->getCenterRight(), n2->getCenter(), - n5->getCenter(), n5->getCenterRight(), n6->getCenterRight(), n6->getCenter()); - // Generate right edge border cells - if (n5->isBorderTop(*mRoot) && n6->isBorderTop(*mRoot)) - { - addDualCell(n5->getCenter(), n5->getCenterRight(), n6->getCenterRight(), n6->getCenter(), - n5->getCenterTop(), n5->getCenterRightTop(), n6->getCenterRightTop(), n6->getCenterTop()); - } - if (n1->isBorderBottom(*mRoot) && n2->isBorderBottom(*mRoot)) - { - addDualCell(n1->getCenterBottom(), n1->getCenterRightBottom(), n2->getCenterRightBottom(), n2->getCenterBottom(), - n1->getCenter(), n1->getCenterRight(), n2->getCenterRight(), n2->getCenter()); - } - if (n1->isBorderBack(*mRoot) && n5->isBorderBack(*mRoot)) - { - addDualCell(n1->getCenterBack(), n1->getCenterBackRight(), n1->getCenterRight(), n1->getCenter(), - n5->getCenterBack(), n5->getCenterBackRight(), n5->getCenterRight(), n5->getCenter()); - } - if (n2->isBorderFront(*mRoot) && n6->isBorderFront(*mRoot)) - { - addDualCell(n2->getCenter(), n2->getCenterRight(), n2->getCenterFrontRight(), n2->getCenterFront(), - n6->getCenter(), n6->getCenterRight(), n6->getCenterFrontRight(), n6->getCenterFront()); - } - } - if (n4->isBorderTop(*mRoot) && n5->isBorderTop(*mRoot) && n6->isBorderTop(*mRoot) && n7->isBorderTop(*mRoot)) - { - addDualCell(n4->getCenter(), n5->getCenter(), n6->getCenter(), n7->getCenter(), - n4->getCenterTop(), n5->getCenterTop(), n6->getCenterTop(), n7->getCenterTop()); - } - if (n0->isBorderBottom(*mRoot) && n1->isBorderBottom(*mRoot) && n2->isBorderBottom(*mRoot) && n3->isBorderBottom(*mRoot)) - { - addDualCell(n0->getCenterBottom(), n1->getCenterBottom(), n2->getCenterBottom(), n3->getCenterBottom(), - n0->getCenter(), n1->getCenter(), n2->getCenter(), n3->getCenter()); - } - } - - //----------------------------------------------------------------------- - - DualGridGenerator::DualGridGenerator(): mDualGrid(0), mRoot(0), mSaveDualCells(0), mIs(0), mMb(0), mMaxMSDistance(0) - { - } - - //----------------------------------------------------------------------- - - void DualGridGenerator::generateDualGrid(const OctreeNode *root, IsoSurface *is, MeshBuilder *mb, Real maxMSDistance, const Vector3 &totalFrom, const Vector3 &totalTo, bool saveDualCells) - { - mRoot = root; - mIs = is; - mMb = mb; - mMaxMSDistance = maxMSDistance; - mTotalFrom = totalFrom; - mTotalTo = totalTo; - mSaveDualCells = saveDualCells; - - nodeProc(root); - - // Build up a minimal dualgrid for octrees without children. - if (!root->isSubdivided()) - { - addDualCell(root->getFrom(), root->getCenterBackBottom(), root->getCenterBottom(), root->getCenterLeftBottom(), - root->getCenterBackLeft(), root->getCenterBack(), root->getCenter(), root->getCenterLeft()); - addDualCell(root->getCenterBackBottom(), root->getCorner1(), root->getCenterRightBottom(), root->getCenterBottom(), - root->getCenterBack(), root->getCenterBackRight(), root->getCenterRight(), root->getCenter()); - addDualCell(root->getCenterBottom(), root->getCenterRightBottom(), root->getCorner2(), root->getCenterFrontBottom(), - root->getCenter(), root->getCenterRight(), root->getCenterFrontRight(), root->getCenterFront()); - addDualCell(root->getCenterLeftBottom(), root->getCenterBottom(), root->getCenterFrontBottom(), root->getCorner3(), - root->getCenterLeft(), root->getCenter(), root->getCenterFront(), root->getCenterFrontLeft()); - - addDualCell(root->getCenterBackLeft(), root->getCenterBack(), root->getCenter(), root->getCenterLeft(), - root->getCorner4(), root->getCenterBackTop(), root->getCenterTop(), root->getCenterLeftTop()); - addDualCell(root->getCenterBack(), root->getCenterBackRight(), root->getCenterRight(), root->getCenter(), - root->getCenterBackTop(), root->getCorner5(), root->getCenterRightTop(), root->getCenterTop()); - addDualCell(root->getCenter(), root->getCenterRight(), root->getCenterFrontRight(), root->getCenterFront(), - root->getCenterTop(), root->getCenterRightTop(), root->getTo(), root->getCenterFrontTop()); - addDualCell(root->getCenterLeft(), root->getCenter(), root->getCenterFront(), root->getCenterFrontLeft(), - root->getCenterLeftTop(), root->getCenterTop(), root->getCenterFrontTop(), root->getCorner7()); - } - } - - //----------------------------------------------------------------------- - - Entity* DualGridGenerator::getDualGrid(SceneManager *sceneManager) - { - if (!mDualGrid && mDualCells.size() > 0) - { - ManualObject* manual = sceneManager->createManualObject(); - manual->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_LIST); - manual->colour((Real)0.0, (Real)1.0, (Real)0.0); - manual->estimateVertexCount(mDualCells.size() * 8); - manual->estimateIndexCount(mDualCells.size() * 24); - - uint32 baseIndex = 0; - for (VecDualCell::iterator it = mDualCells.begin(); it != mDualCells.end(); ++it) - { - MeshBuilder::addCubeToManualObject( - manual, - it->mC0, - it->mC1, - it->mC2, - it->mC3, - it->mC4, - it->mC5, - it->mC6, - it->mC7, - baseIndex); - } - - manual->end(); - mDualGridI++; - StringStream meshName; - meshName << "VolumeDualGridGridMesh" << mDualGridI; - manual->convertToMesh(meshName.str()); - StringStream entityName; - entityName << "VolumeDualGrid" << mDualGridI; - mDualGrid = sceneManager->createEntity(entityName.str(), meshName.str()); - } - return mDualGrid; - } - -} -} \ No newline at end of file diff --git a/Components/Volume/src/OgreVolumeGridSource.cpp b/Components/Volume/src/OgreVolumeGridSource.cpp deleted file mode 100644 index e99e2fd7e3e..00000000000 --- a/Components/Volume/src/OgreVolumeGridSource.cpp +++ /dev/null @@ -1,269 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreVolumeGridSource.h" -#include "OgreVector.h" -#include "OgreLogManager.h" -#include "OgreRay.h" -#include "OgreVolumeCSGSource.h" - -namespace Ogre { -namespace Volume { - - Vector3 GridSource::getIntersectionStart(const Ray &ray, Real maxDistance) const - { - AxisAlignedBox box((Real)0, (Real)0, (Real)0, (Real)mWidth / mPosXScale, (Real)mHeight / mPosYScale, (Real)mDepth / mPosZScale); - - // Inside the grid - if (box.intersects(ray.getOrigin())) - { - return ray.getOrigin(); - } - - // Outside the grid, ray intersects it - std::pair intersection = ray.intersects(box); - if (intersection.first) - { - Vector3 direction = ray.getDirection().normalisedCopy(); - return ray.getOrigin() + direction * intersection.second; - } - - // Outside the grid, ray doesn't intersect it - return ray.getOrigin(); - } - - //----------------------------------------------------------------------- - - Vector3 GridSource::getIntersectionEnd(const Ray &ray, Real maxDistance) const - { - AxisAlignedBox box((Real)0, (Real)0, (Real)0, (Real)mWidth / mPosXScale, (Real)mHeight / mPosYScale, (Real)mDepth / mPosZScale); - Vector3 direction = ray.getDirection().normalisedCopy(); - Vector3 invertedDirection = (Real)-1.0 * direction; - Vector3 origin = ray.getOrigin() + direction * box.getSize().length(); - - Ray inverted(origin, invertedDirection); - std::pair intersection = inverted.intersects(box); - if (intersection.first) - { - return origin + invertedDirection * intersection.second; - } - return ray.getOrigin() + direction * maxDistance; - } - - //----------------------------------------------------------------------- - - GridSource::GridSource(bool trilinearValue, bool trilinearGradient, bool sobelGradient) : - mWidth(0), mHeight(0), mDepth(0), mPosXScale(0), mPosYScale(0), mPosZScale(0), - mTrilinearValue(trilinearValue), mTrilinearGradient(trilinearGradient), mSobelGradient(sobelGradient), - mVolumeSpaceToWorldSpaceFactor(0) - { - } - - //----------------------------------------------------------------------- - - GridSource::~GridSource(void) - { - } - - //----------------------------------------------------------------------- - - Vector4 GridSource::getValueAndGradient(const Vector3 &position) const - { - Vector3 scaledPosition(position.x * mPosXScale, position.y * mPosYScale, position.z * mPosZScale); - Vector3 gradient; - if (mTrilinearGradient) - { - size_t x0 = (size_t)scaledPosition.x; - size_t x1 = (size_t)ceil(scaledPosition.x); - size_t y0 = (size_t)scaledPosition.y; - size_t y1 = (size_t)ceil(scaledPosition.y); - size_t z0 = (size_t)scaledPosition.z; - size_t z1 = (size_t)ceil(scaledPosition.z); - - Real dX = scaledPosition.x - (Real)x0; - Real dY = scaledPosition.y - (Real)y0; - Real dZ = scaledPosition.z - (Real)z0; - - Vector3 f000 = getGradient(x0, y0, z0); - Vector3 f100 = getGradient(x1, y0, z0); - Vector3 f010 = getGradient(x0, y1, z0); - Vector3 f001 = getGradient(x0, y0, z1); - Vector3 f101 = getGradient(x1, y0, z1); - Vector3 f011 = getGradient(x0, y1, z1); - Vector3 f110 = getGradient(x1, y1, z0); - Vector3 f111 = getGradient(x1, y1, z1); - - Real oneMinX = (Real)1.0 - dX; - Real oneMinY = (Real)1.0 - dY; - Real oneMinZ = (Real)1.0 - dZ; - Real oneMinXoneMinY = oneMinX * oneMinY; - Real dXOneMinY = dX * oneMinY; - - gradient = oneMinZ * (f000 * oneMinXoneMinY - + f100 * dXOneMinY - + f010 * oneMinX * dY) - + dZ * (f001 * oneMinXoneMinY - + f101 * dXOneMinY - + f011 * oneMinX * dY) - + dX * dY * (f110 * oneMinZ - + f111 * dZ); - - gradient *= (Real)-1.0; - } - else - { - gradient = getGradient((size_t)(scaledPosition.x + (Real)0.5), (size_t)(scaledPosition.y + (Real)0.5), (size_t)(scaledPosition.z + (Real)0.5)); - gradient *= (Real)-1.0; - } - return Vector4(gradient.x, gradient.y, gradient.z, getValue(position)); - } - - //----------------------------------------------------------------------- - - Real GridSource::getValue(const Vector3 &position) const - { - Vector3 scaledPosition(position.x * mPosXScale, position.y * mPosYScale, position.z * mPosZScale); - Real value; - if (mTrilinearValue) - { - size_t x0 = (size_t)scaledPosition.x; - size_t x1 = (size_t)ceil(scaledPosition.x); - size_t y0 = (size_t)scaledPosition.y; - size_t y1 = (size_t)ceil(scaledPosition.y); - size_t z0 = (size_t)scaledPosition.z; - size_t z1 = (size_t)ceil(scaledPosition.z); - - Real dX = scaledPosition.x - (Real)x0; - Real dY = scaledPosition.y - (Real)y0; - Real dZ = scaledPosition.z - (Real)z0; - - Real f000 = getVolumeGridValue(x0, y0, z0); - Real f100 = getVolumeGridValue(x1, y0, z0); - Real f010 = getVolumeGridValue(x0, y1, z0); - Real f001 = getVolumeGridValue(x0, y0, z1); - Real f101 = getVolumeGridValue(x1, y0, z1); - Real f011 = getVolumeGridValue(x0, y1, z1); - Real f110 = getVolumeGridValue(x1, y1, z0); - Real f111 = getVolumeGridValue(x1, y1, z1); - - Real oneMinX = (Real)1.0 - dX; - Real oneMinY = (Real)1.0 - dY; - Real oneMinZ = (Real)1.0 - dZ; - Real oneMinXoneMinY = oneMinX * oneMinY; - Real dXOneMinY = dX * oneMinY; - - value = oneMinZ * (f000 * oneMinXoneMinY - + f100 * dXOneMinY - + f010 * oneMinX * dY) - + dZ * (f001 * oneMinXoneMinY - + f101 * dXOneMinY - + f011 * oneMinX * dY) - + dX * dY * (f110 * oneMinZ - + f111 * dZ); - - } - else - { - // Nearest neighbour else - size_t x = (size_t)(scaledPosition.x + (Real)0.5); - size_t y = (size_t)(scaledPosition.y + (Real)0.5); - size_t z = (size_t)(scaledPosition.z + (Real)0.5); - value = (Real)getVolumeGridValue(x, y, z); - } - return value; - } - - //----------------------------------------------------------------------- - - size_t GridSource::getWidth(void) const - { - return mWidth; - } - - //----------------------------------------------------------------------- - - size_t GridSource::getHeight(void) const - { - return mHeight; - } - - //----------------------------------------------------------------------- - - size_t GridSource::getDepth(void) const - { - return mDepth; - } - - //----------------------------------------------------------------------- - - void GridSource::combineWithSource(CSGOperationSource *operation, Source *source, const Vector3 ¢er, Real radius) - { - Real worldWidthScale = (Real)1.0 / mPosXScale; - Real worldHeightScale = (Real)1.0 / mPosYScale; - Real worldDepthScale = (Real)1.0 / mPosZScale; - - operation->setSourceA(this); - operation->setSourceB(source); - // No need for trilineaer interpolation here as we iterate over the - // cells anyway. - bool oldTrilinearValue = mTrilinearValue; - mTrilinearValue = false; - float value; - int x, y; - Vector3 scaledCenter(center.x * mPosXScale, center.y * mPosYScale, center.z * mPosZScale); - int xStart = Math::Clamp(static_cast(scaledCenter.x - radius * mPosXScale), 0, static_cast(mWidth)); - int xEnd = Math::Clamp(static_cast(scaledCenter.x + radius * mPosXScale), 0, static_cast(mWidth)); - int yStart = Math::Clamp(static_cast(scaledCenter.y - radius * mPosYScale), 0, static_cast(mHeight)); - int yEnd = Math::Clamp(static_cast(scaledCenter.y + radius * mPosYScale), 0, static_cast(mHeight)); - int zStart = Math::Clamp(static_cast(scaledCenter.z - radius * mPosZScale), 0, static_cast(mDepth)); - int zEnd = Math::Clamp(static_cast(scaledCenter.z + radius * mPosZScale), 0, static_cast(mDepth)); - Vector3 pos; - for (int z = zStart; z < zEnd; ++z) - { - for (y = yStart; y < yEnd; ++y) - { - for (x = xStart; x < xEnd; ++x) - { - pos.x = x * worldWidthScale; - pos.y = y * worldHeightScale; - pos.z = z * worldDepthScale; - value = operation->getValue(pos); - setVolumeGridValue(x, y, z, value); - } - } - } - - mTrilinearValue = oldTrilinearValue; - } - - //----------------------------------------------------------------------- - - Real GridSource::getVolumeSpaceToWorldSpaceFactor(void) const - { - return mVolumeSpaceToWorldSpaceFactor; - } -} -} \ No newline at end of file diff --git a/Components/Volume/src/OgreVolumeHalfFloatGridSource.cpp b/Components/Volume/src/OgreVolumeHalfFloatGridSource.cpp deleted file mode 100644 index 03d52268d90..00000000000 --- a/Components/Volume/src/OgreVolumeHalfFloatGridSource.cpp +++ /dev/null @@ -1,135 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreVolumeHalfFloatGridSource.h" -#include "OgreRoot.h" -#include "OgreDeflate.h" -#include "OgreStreamSerialiser.h" -#include "OgreBitwise.h" -#include "OgreMemoryAllocatorConfig.h" -#include "OgreLogManager.h" -#include "OgreTimer.h" - -namespace Ogre { -namespace Volume { - - float HalfFloatGridSource::getVolumeGridValue(size_t x, size_t y, size_t z) const - { - x = x >= mWidth ? mWidth - 1 : x; - y = y >= mHeight ? mHeight - 1 : y; - z = z >= mDepth ? mDepth - 1 : z; - return Bitwise::halfToFloat(mData[(mDepth - z - 1) * mDepthTimesHeight + x * mHeight + y]); - } - - //----------------------------------------------------------------------- - - void HalfFloatGridSource::setVolumeGridValue(int x, int y, int z, float value) - { - - // Clamp if wanted. - if (mMaxClampedAbsoluteDensity != (Real)0.0 && Math::Abs(value) > mMaxClampedAbsoluteDensity) - { - value = mMaxClampedAbsoluteDensity; - } - - mData[(mDepth - z - 1) * mDepthTimesHeight + x * mHeight + y] = Bitwise::floatToHalf(value); - } - - //----------------------------------------------------------------------- - - HalfFloatGridSource::HalfFloatGridSource(const String &serializedVolumeFile, const bool trilinearValue, const bool trilinearGradient, const bool sobelGradient) : - GridSource(trilinearValue, trilinearGradient, sobelGradient) - { - - Timer t; - DataStreamPtr streamRead = Root::getSingleton().openFileStream(serializedVolumeFile); -#if OGRE_NO_ZIP_ARCHIVE == 0 - DataStreamPtr uncompressStream(OGRE_NEW DeflateStream(serializedVolumeFile, streamRead)); - StreamSerialiser ser(uncompressStream); -#else - StreamSerialiser ser(streamRead); -#endif - if (!ser.readChunkBegin(VOLUME_CHUNK_ID, VOLUME_CHUNK_VERSION)) - { - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Invalid volume file given!"); - } - - // Read header - Vector3 readFrom, readTo; - ser.read(&readFrom); - ser.read(&readTo); - float voxelWidth; - ser.read(&voxelWidth); - size_t width, height, depth; - ser.read(&width); - ser.read(&height); - ser.read(&depth); - mWidth = static_cast(width); - mHeight = static_cast(height); - mDepth = static_cast(depth); - mDepthTimesHeight = static_cast(mDepth * mHeight); - - Vector3 worldDimension = readTo - readFrom; - mPosXScale = (Real)1.0 / (Real)worldDimension.x * (Real)mWidth; - mPosYScale = (Real)1.0 / (Real)worldDimension.y * (Real)mHeight; - mPosZScale = (Real)1.0 / (Real)worldDimension.z * (Real)mDepth; - - mVolumeSpaceToWorldSpaceFactor = (Real)worldDimension.x * (Real)mWidth; - mMaxClampedAbsoluteDensity = 0; - - // Read data - size_t elementCount = mWidth * mHeight * mDepth; - mData = OGRE_ALLOC_T(uint16, elementCount, MEMCATEGORY_GENERAL); - ser.read(mData, elementCount); - - ser.readChunkEnd(VOLUME_CHUNK_ID); - - LogManager::getSingleton().stream() << "Processed serialization in " << t.getMilliseconds() << "ms."; - } - - //----------------------------------------------------------------------- - - void HalfFloatGridSource::setMaxClampedAbsoluteDensity(Real maxClampedAbsoluteDensity) - { - mMaxClampedAbsoluteDensity = maxClampedAbsoluteDensity; - } - - //----------------------------------------------------------------------- - - - Real HalfFloatGridSource::getMaxClampedAbsoluteDensity(void) const - { - return mMaxClampedAbsoluteDensity; - } - - //----------------------------------------------------------------------- - - HalfFloatGridSource::~HalfFloatGridSource(void) - { - OGRE_FREE(mData, MEMCATEGORY_GENERAL); - } -} -} \ No newline at end of file diff --git a/Components/Volume/src/OgreVolumeIsoSurface.cpp b/Components/Volume/src/OgreVolumeIsoSurface.cpp deleted file mode 100644 index 8e1a1ade82b..00000000000 --- a/Components/Volume/src/OgreVolumeIsoSurface.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreVolumeIsoSurface.h" - -namespace Ogre { -namespace Volume { - - const Real IsoSurface::ISO_LEVEL = (Real)0.0; - - const size_t IsoSurface::MS_CORNERS_FRONT[4] = {7, 6, 2, 3}; - const size_t IsoSurface::MS_CORNERS_BACK[4] = {5, 4, 0, 1}; - const size_t IsoSurface::MS_CORNERS_LEFT[4] = {4, 7, 3, 0}; - const size_t IsoSurface::MS_CORNERS_RIGHT[4] = {6, 5, 1, 2}; - const size_t IsoSurface::MS_CORNERS_TOP[4] = {4, 5, 6, 7}; - const size_t IsoSurface::MS_CORNERS_BOTTOM[4] = {3, 2, 1, 0}; - - //----------------------------------------------------------------------- - - IsoSurface::IsoSurface(const Source *src) : mSrc(src) - { - } - - //----------------------------------------------------------------------- - - IsoSurface::~IsoSurface(void) - { - } -} -} \ No newline at end of file diff --git a/Components/Volume/src/OgreVolumeIsoSurfaceMC.cpp b/Components/Volume/src/OgreVolumeIsoSurfaceMC.cpp deleted file mode 100644 index 1455a3f4bd9..00000000000 --- a/Components/Volume/src/OgreVolumeIsoSurfaceMC.cpp +++ /dev/null @@ -1,238 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreVolumeIsoSurfaceMC.h" - -#include "OgreVolumeIsoSurfaceTablesMC.h" -#include "OgreVolumeSource.h" -#include "OgreVolumeMeshBuilder.h" - -namespace Ogre { -namespace Volume { - - //----------------------------------------------------------------------- - - IsoSurfaceMC::IsoSurfaceMC(const Source *src) : IsoSurface(src) - { - } - - //----------------------------------------------------------------------- - - void IsoSurfaceMC::addMarchingCubesTriangles(const Vector3 *corners, const Vector4 *volumeValues, MeshBuilder *mb) const - { - unsigned char cubeIndex = 0; - Vector4 values[8]; - - // Find out the case. - for (size_t i = 0; i < 8; ++i) - { - if (volumeValues) - { - values[i] = volumeValues[i]; - } - else - { - values[i] = mSrc->getValueAndGradient(corners[i]); - } - if (values[i].w >= ISO_LEVEL) - { - cubeIndex |= 1 << i; - } - } - - int edge = mcEdges[cubeIndex]; - - // Nothing intersects. - if (!edge) - { - return; - } - - // Find the intersection vertices. - Vector3 intersectionPoints[12]; - Vector3 intersectionNormals[12]; - if (edge & 1) - { - intersectionPoints[0] = interpolate(corners[0], corners[1], values[0], values[1], intersectionNormals[0]); - } - if (edge & 2) - { - intersectionPoints[1] = interpolate(corners[1], corners[2], values[1], values[2], intersectionNormals[1]); - } - if (edge & 4) - { - intersectionPoints[2] = interpolate(corners[2], corners[3], values[2], values[3], intersectionNormals[2]); - } - if (edge & 8) - { - intersectionPoints[3] = interpolate(corners[3], corners[0], values[3], values[0], intersectionNormals[3]); - } - if (edge & 16) - { - intersectionPoints[4] = interpolate(corners[4], corners[5], values[4], values[5], intersectionNormals[4]); - } - if (edge & 32) - { - intersectionPoints[5] = interpolate(corners[5], corners[6], values[5], values[6], intersectionNormals[5]); - } - if (edge & 64) - { - intersectionPoints[6] = interpolate(corners[6], corners[7], values[6], values[7], intersectionNormals[6]); - } - if (edge & 128) - { - intersectionPoints[7] = interpolate(corners[7], corners[4], values[7], values[4], intersectionNormals[7]); - } - if (edge & 256) - { - intersectionPoints[8] = interpolate(corners[0], corners[4], values[0], values[4], intersectionNormals[8]); - } - if (edge & 512) - { - intersectionPoints[9] = interpolate(corners[1], corners[5], values[1], values[5], intersectionNormals[9]); - } - if (edge & 1024) - { - intersectionPoints[10] = interpolate(corners[2], corners[6], values[2], values[6], intersectionNormals[10]); - } - if (edge & 2048) - { - intersectionPoints[11] = interpolate(corners[3], corners[7], values[3], values[7], intersectionNormals[11]); - } - - // Create the triangles according to the table. - for (int i = 0; mcTriangles[cubeIndex][i] != -1; i += 3) - { - mb->addTriangle(intersectionPoints[mcTriangles[cubeIndex][i]], intersectionNormals[mcTriangles[cubeIndex][i]], - intersectionPoints[mcTriangles[cubeIndex][i + 1]], intersectionNormals[mcTriangles[cubeIndex][i + 1]], - intersectionPoints[mcTriangles[cubeIndex][i + 2]], intersectionNormals[mcTriangles[cubeIndex][i + 2]]); - } - } - - //----------------------------------------------------------------------- - - void IsoSurfaceMC::addMarchingSquaresTriangles(const Vector3 *corners, const Vector4 *volumeValues, const size_t *indices, const Real maxDistance, MeshBuilder *mb) const - { - unsigned char squareIndex = 0; - Vector4 values[4]; - - // Find out the case. - for (size_t i = 0; i < 4; ++i) - { - if (volumeValues) - { - values[i] = Vector4(volumeValues[indices[i]].w); - } - else - { - values[i] = mSrc->getValueAndGradient(corners[indices[i]]); - } - if (values[i].w >= ISO_LEVEL) - { - squareIndex |= 1 << i; - } - } - - // Don't generate triangles if we are completely inside and far enough away from the surface - if (squareIndex == 15 && values[0].w >= maxDistance && values[1].w >= maxDistance && values[2].w >= maxDistance && values[3].w >= maxDistance) - { - return; - } - - int edge = msEdges[squareIndex]; - - // Find the intersection vertices. - Vector3 intersectionPoints[8]; - Vector3 intersectionNormals[8]; - intersectionPoints[0] = corners[indices[0]]; - intersectionPoints[2] = corners[indices[1]]; - intersectionPoints[4] = corners[indices[2]]; - intersectionPoints[6] = corners[indices[3]]; - - Vector4 innerVal = mSrc->getValueAndGradient(intersectionPoints[0]); - intersectionNormals[0].x = innerVal.x; - intersectionNormals[0].y = innerVal.y; - intersectionNormals[0].z = innerVal.z; - intersectionNormals[0].normalise(); - intersectionNormals[0] *= innerVal.w + (Real)1.0; - innerVal = mSrc->getValueAndGradient(intersectionPoints[2]); - intersectionNormals[2].x = innerVal.x; - intersectionNormals[2].y = innerVal.y; - intersectionNormals[2].z = innerVal.z; - intersectionNormals[2].normalise(); - intersectionNormals[2] *= innerVal.w + (Real)1.0; - innerVal = mSrc->getValueAndGradient(intersectionPoints[4]); - intersectionNormals[4].x = innerVal.x; - intersectionNormals[4].y = innerVal.y; - intersectionNormals[4].z = innerVal.z; - intersectionNormals[4].normalise(); - intersectionNormals[4] *= innerVal.w + (Real)1.0; - innerVal = mSrc->getValueAndGradient(intersectionPoints[6]); - intersectionNormals[6].x = innerVal.x; - intersectionNormals[6].y = innerVal.y; - intersectionNormals[6].z = innerVal.z; - intersectionNormals[6].normalise(); - intersectionNormals[6] *= innerVal.w + (Real)1.0; - - if (edge & 1) - { - intersectionPoints[1] = interpolate(corners[indices[0]], corners[indices[1]], values[0], values[1], intersectionNormals[1]); - } - if (edge & 2) - { - intersectionPoints[3] = interpolate(corners[indices[1]], corners[indices[2]], values[1], values[2], intersectionNormals[3]); - } - if (edge & 4) - { - intersectionPoints[5] = interpolate(corners[indices[2]], corners[indices[3]], values[2], values[3], intersectionNormals[5]); - } - if (edge & 8) - { - intersectionPoints[7] = interpolate(corners[indices[3]], corners[indices[0]], values[3], values[0], intersectionNormals[7]); - } - - // Ambigous case handling, 5 = 0 2 and 10 = 1 3 - /*if (squareIndex == 5 || squareIndex == 10) - { - Vector3 avg = (corners[indices[0]] + corners[indices[1]] + corners[indices[2]] + corners[indices[3]]) / (Real)4.0; - // Lets take the alternative. - if (mSrc->getValue(avg) >= ISO_LEVEL) - { - squareIndex = squareIndex == 5 ? 16 : 17; - } - }*/ - - // Create the triangles according to the table. - for (int i = 0; mcTriangles[squareIndex][i] != -1; i += 3) - { - mb->addTriangle(intersectionPoints[msTriangles[squareIndex][i]], intersectionNormals[msTriangles[squareIndex][i]], - intersectionPoints[msTriangles[squareIndex][i + 1]], intersectionNormals[msTriangles[squareIndex][i + 1]], - intersectionPoints[msTriangles[squareIndex][i + 2]], intersectionNormals[msTriangles[squareIndex][i + 2]]); - } - } - -} -} diff --git a/Components/Volume/src/OgreVolumeMeshBuilder.cpp b/Components/Volume/src/OgreVolumeMeshBuilder.cpp deleted file mode 100644 index f85152484c2..00000000000 --- a/Components/Volume/src/OgreVolumeMeshBuilder.cpp +++ /dev/null @@ -1,201 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreVolumeMeshBuilder.h" - -#include - -#include "OgreHardwareBufferManager.h" -#include "OgreManualObject.h" -#include "OgreMeshManager.h" -#include "OgreSceneManager.h" - -namespace Ogre { -namespace Volume { - - bool operator==(Vertex const& a, Vertex const& b) - { - return a.x == b.x && - a.y == b.y && - a.z == b.z && - a.nX == b.nX && - a.nY == b.nY && - a.nZ == b.nZ; - } - - //----------------------------------------------------------------------- - - bool operator<(const Vertex& a, const Vertex& b) - { - return memcmp(&a, &b, sizeof(Vertex)) < 0; - } - - //----------------------------------------------------------------------- - - const unsigned short MeshBuilder::MAIN_BINDING = 0; - - //----------------------------------------------------------------------- - - MeshBuilder::MeshBuilder(void) : mBoxInit(false) - { - } - - //----------------------------------------------------------------------- - - size_t MeshBuilder::generateBuffers(RenderOperation &operation) - { - // Early out if nothing to do. - if (mIndices.empty()) - { - return 0; - } - - // Prepare vertex buffer - operation.operationType = RenderOperation::OT_TRIANGLE_LIST; - - operation.vertexData = OGRE_NEW VertexData(); - operation.vertexData->vertexCount = mVertices.size(); - operation.vertexData->vertexStart = 0; - - VertexDeclaration *decl = operation.vertexData->vertexDeclaration; - VertexBufferBinding *bind = operation.vertexData->vertexBufferBinding; - - size_t offset = 0; - - // Add vertex-positions to the buffer - offset += decl->addElement(0, offset, VET_FLOAT3, VES_POSITION).getSize(); - - // Add vertex-normals to the buffer - decl->addElement(0, offset, VET_FLOAT3, VES_NORMAL); - - HardwareVertexBufferSharedPtr vbuf = HardwareBufferManager::getSingleton().createVertexBuffer( - decl->getVertexSize(MAIN_BINDING), - operation.vertexData->vertexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - bind->setBinding(0, vbuf); - - float* vertices = static_cast(vbuf->lock(HardwareBuffer::HBL_DISCARD)); - - VecVertex::const_iterator endVertices = mVertices.end(); - for (VecVertex::const_iterator iter = mVertices.begin(); iter != endVertices; ++iter) - { - *vertices++ = (float)iter->x; - *vertices++ = (float)iter->y; - *vertices++ = (float)iter->z; - *vertices++ = (float)iter->nX; - *vertices++ = (float)iter->nY; - *vertices++ = (float)iter->nZ; - } - - vbuf->unlock(); - - // Get Indexarray - operation.indexData = OGRE_NEW IndexData(); - operation.indexData->indexCount = mIndices.size(); - operation.indexData->indexStart = 0; - - VecIndices::const_iterator endIndices = mIndices.end(); - if (operation.indexData->indexCount > USHRT_MAX) - { - operation.indexData->indexBuffer = - HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_32BIT, - operation.indexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - unsigned int* indices = static_cast( - operation.indexData->indexBuffer->lock(0, - operation.indexData->indexBuffer->getSizeInBytes(), - HardwareBuffer::HBL_DISCARD)); - - for (VecIndices::const_iterator iter = mIndices.begin(); iter != endIndices; ++iter) - { - *indices++ = static_cast(*iter); - } - } - else - { - operation.indexData->indexBuffer = - HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, - operation.indexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - unsigned short* indices = static_cast( - operation.indexData->indexBuffer->lock(0, - operation.indexData->indexBuffer->getSizeInBytes(), - HardwareBuffer::HBL_DISCARD)); - - for (VecIndices::const_iterator iter = mIndices.begin(); iter != endIndices; ++iter) - { - *indices++ = (unsigned short)*iter; - } - } - - operation.indexData->indexBuffer->unlock(); - return mIndices.size() / 3; - } - - //----------------------------------------------------------------------- - - AxisAlignedBox MeshBuilder::getBoundingBox(void) - { - return mBox; - } - - //----------------------------------------------------------------------- - - Entity* MeshBuilder::generateWithManualObject(SceneManager *sceneManager, const String &name, const String &material) - { - ManualObject* manual = sceneManager->createManualObject(); - manual->begin(material, RenderOperation::OT_TRIANGLE_LIST); - - for (VecVertex::const_iterator iter = mVertices.begin(); iter != mVertices.end(); ++iter) - { - manual->position(Vector3(iter->x, iter->y, iter->z)); - manual->normal(Vector3(iter->nX, iter->nY, iter->nZ)); - } - for (VecIndices::const_iterator iter = mIndices.begin(); iter != mIndices.end(); ++iter) - { - manual->index(static_cast(*iter)); - } - - manual->end(); - StringStream meshName; - meshName << name << "ManualObject"; - MeshManager::getSingleton().remove(meshName.str(), ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - manual->convertToMesh(meshName.str()); - return sceneManager->createEntity(name, meshName.str()); - } - - //----------------------------------------------------------------------- - - void MeshBuilder::executeCallback(MeshBuilderCallback *callback, const SimpleRenderable *simpleRenderable, size_t level, int inProcess) const - { - callback->ready(simpleRenderable, mVertices, mIndices, level, inProcess); - } - -} -} diff --git a/Components/Volume/src/OgreVolumeOctreeNode.cpp b/Components/Volume/src/OgreVolumeOctreeNode.cpp deleted file mode 100644 index ce8a9e5f852..00000000000 --- a/Components/Volume/src/OgreVolumeOctreeNode.cpp +++ /dev/null @@ -1,172 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreVolumeOctreeNode.h" - -#include "OgreVolumeMeshBuilder.h" -#include "OgreVolumeSource.h" -#include "OgreVolumeOctreeNodeSplitPolicy.h" -#include "OgreSceneManager.h" - -namespace Ogre { -namespace Volume { - - const Real OctreeNode::NEAR_FACTOR = (Real)2.0; - const size_t OctreeNode::OCTREE_CHILDREN_COUNT = 8; - uint32 OctreeNode::mGridPositionCount = 0; - size_t OctreeNode::mNodeI = 0; - - //----------------------------------------------------------------------- - - void OctreeNode::buildOctreeGridLines(ManualObject *manual) const - { - if (!mChildren) - { - Vector3 xWidth(mTo.x - mFrom.x, (Real)0.0, (Real)0.0); - Vector3 yWidth((Real)0.0, mTo.y - mFrom.y, (Real)0.0); - Vector3 zWidth((Real)0.0, (Real)0.0, mTo.z - mFrom.z); - MeshBuilder::addCubeToManualObject( - manual, - mFrom, - mFrom + xWidth, - mFrom + xWidth + zWidth, - mFrom + zWidth, - mFrom + yWidth, - mFrom + yWidth + xWidth, - mFrom + yWidth + xWidth + zWidth, - mFrom + yWidth + zWidth, - mGridPositionCount); - } - else - { - mChildren[0]->buildOctreeGridLines(manual); - mChildren[1]->buildOctreeGridLines(manual); - mChildren[2]->buildOctreeGridLines(manual); - mChildren[3]->buildOctreeGridLines(manual); - mChildren[4]->buildOctreeGridLines(manual); - mChildren[5]->buildOctreeGridLines(manual); - mChildren[6]->buildOctreeGridLines(manual); - mChildren[7]->buildOctreeGridLines(manual); - } - } - - //----------------------------------------------------------------------- - - OctreeNode::OctreeNode(const Vector3 &from, const Vector3 &to) : mFrom(from), mTo(to), - mChildren(0), mOctreeGrid(0), mCenterValue(0.0, 0.0, 0.0, 0.0) - { - } - - //----------------------------------------------------------------------- - - OctreeNode::~OctreeNode(void) - { - if (mChildren) - { - for (size_t i = 0; i < OCTREE_CHILDREN_COUNT; ++i) - { - OGRE_DELETE mChildren[i]; - } - delete[] mChildren; - } - } - - //----------------------------------------------------------------------- - - OctreeNode* OctreeNode::createInstance(const Vector3& from, const Vector3& to) - { - return OGRE_NEW OctreeNode(from, to); - } - - //----------------------------------------------------------------------- - - void OctreeNode::split(const OctreeNodeSplitPolicy *splitPolicy, const Source *src, const Real geometricError) - { - if (splitPolicy->doSplit(this, geometricError)) - { - Vector3 newCenter, xWidth, yWidth, zWidth; - OctreeNode::getChildrenDimensions(mFrom, mTo, newCenter, xWidth, yWidth, zWidth); - /* - 4 5 - 7 6 - 0 1 - 3 2 - 0 == from - 6 == to - */ - mChildren = new OctreeNode*[OCTREE_CHILDREN_COUNT]; - mChildren[0] = createInstance(mFrom, newCenter); - mChildren[0]->split(splitPolicy, src, geometricError); - mChildren[1] = createInstance(mFrom + xWidth, newCenter + xWidth); - mChildren[1]->split(splitPolicy, src, geometricError); - mChildren[2] = createInstance(mFrom + xWidth + zWidth, newCenter + xWidth + zWidth); - mChildren[2]->split(splitPolicy, src, geometricError); - mChildren[3] = createInstance(mFrom + zWidth, newCenter + zWidth); - mChildren[3]->split(splitPolicy, src, geometricError); - mChildren[4] = createInstance(mFrom + yWidth, newCenter + yWidth); - mChildren[4]->split(splitPolicy, src, geometricError); - mChildren[5] = createInstance(mFrom + yWidth + xWidth, newCenter + yWidth + xWidth); - mChildren[5]->split(splitPolicy, src, geometricError); - mChildren[6] = createInstance(mFrom + yWidth + xWidth + zWidth, newCenter + yWidth + xWidth + zWidth); - mChildren[6]->split(splitPolicy, src, geometricError); - mChildren[7] = createInstance(mFrom + yWidth + zWidth, newCenter + yWidth + zWidth); - mChildren[7]->split(splitPolicy, src, geometricError); - } - else - { - if (mCenterValue.x == (Real)0.0 && mCenterValue.y == (Real)0.0 && mCenterValue.z == (Real)0.0 && mCenterValue.w == (Real)0.0) - { - setCenterValue(src->getValueAndGradient(getCenter())); - } - } - } - - //----------------------------------------------------------------------- - - Entity* OctreeNode::getOctreeGrid(SceneManager *sceneManager) - { - if (!mOctreeGrid) - { - mGridPositionCount = 0; - mNodeI++; - ManualObject* manual = sceneManager->createManualObject(); - manual->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_LIST); - manual->colour((Real)1.0, (Real)0.0, (Real)0.0); - buildOctreeGridLines(manual); - manual->end(); - - StringStream meshName; - meshName << "VolumeOctreeGridMesh" << mNodeI; - manual->convertToMesh(meshName.str()); - StringStream entityName; - entityName << "VolumeOctreeGrid" << mNodeI; - mOctreeGrid = sceneManager->createEntity(entityName.str(), meshName.str()); - } - return mOctreeGrid; - } - -} -} \ No newline at end of file diff --git a/Components/Volume/src/OgreVolumeOctreeNodeSplitPolicy.cpp b/Components/Volume/src/OgreVolumeOctreeNodeSplitPolicy.cpp deleted file mode 100644 index 9afa0faceb8..00000000000 --- a/Components/Volume/src/OgreVolumeOctreeNodeSplitPolicy.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreVolumeOctreeNodeSplitPolicy.h" - -#include "OgreVolumeSource.h" -#include "OgreVolumeOctreeNode.h" -#include - -namespace Ogre { -namespace Volume { - - OctreeNodeSplitPolicy::OctreeNodeSplitPolicy(const Source *src, const Real maxCellSize) : - mSrc(src), mMaxCellSize(maxCellSize) - { - } - - //----------------------------------------------------------------------- - - bool OctreeNodeSplitPolicy::doSplit(OctreeNode *node, const Real geometricError) const - { - - // We have a highest resolution. - Vector3 from = node->getFrom(); - Vector3 to = node->getTo(); - if (to.x - from.x <= mMaxCellSize) - { - return false; - } - - // Don't split if nothing is inside. - Vector4 centerValue = mSrc->getValueAndGradient(node->getCenter()); - if (Math::Abs(centerValue.w) > (to - from).length() * mSrc->getVolumeSpaceToWorldSpaceFactor()) - { - node->setCenterValue(centerValue); - return false; - } - - // Error metric of http://www.andrew.cmu.edu/user/jessicaz/publication/meshing/ - Real f000 = mSrc->getValue(from); - Real f001 = mSrc->getValue(node->getCorner3()); - Real f010 = mSrc->getValue(node->getCorner4()); - Real f011 = mSrc->getValue(node->getCorner7()); - Real f100 = mSrc->getValue(node->getCorner1()); - Real f101 = mSrc->getValue(node->getCorner2()); - Real f110 = mSrc->getValue(node->getCorner5()); - Real f111 = mSrc->getValue(to); - - Vector3 positions[19][2] = { - {node->getCenterBackBottom(), Vector3((Real)0.5, (Real)0.0, (Real)0.0)}, - {node->getCenterLeftBottom(), Vector3((Real)0.0, (Real)0.0, (Real)0.5)}, - {node->getCenterBottom(), Vector3((Real)0.5, (Real)0.0, (Real)0.5)}, - {node->getCenterRightBottom(), Vector3((Real)1.0, (Real)0.0, (Real)0.5)}, - {node->getCenterFrontBottom(), Vector3((Real)0.5, (Real)0.0, (Real)1.0)}, - - {node->getCenterBackLeft(), Vector3((Real)0.0, (Real)0.5, (Real)0.0)}, - {node->getCenterBack(), Vector3((Real)0.5, (Real)0.5, (Real)0.0)}, - {node->getCenterBackRight(), Vector3((Real)1.0, (Real)0.5, (Real)0.0)}, - {node->getCenterLeft(), Vector3((Real)0.0, (Real)0.5, (Real)0.5)}, - {node->getCenter(), Vector3((Real)0.5, (Real)0.5, (Real)0.5)}, - {node->getCenterRight(), Vector3((Real)1.0, (Real)0.5, (Real)0.5)}, - {node->getCenterFrontLeft(), Vector3((Real)0.0, (Real)0.5, (Real)1.0)}, - {node->getCenterFront(), Vector3((Real)0.5, (Real)0.5, (Real)1.0)}, - {node->getCenterFrontRight(), Vector3((Real)1.0, (Real)0.5, (Real)1.0)}, - - {node->getCenterBackTop(), Vector3((Real)0.5, (Real)1.0, (Real)0.0)}, - {node->getCenterLeftTop(), Vector3((Real)0.0, (Real)1.0, (Real)0.5)}, - {node->getCenterTop(), Vector3((Real)0.5, (Real)1.0, (Real)0.5)}, - {node->getCenterRightTop(), Vector3((Real)1.0, (Real)1.0, (Real)0.5)}, - {node->getCenterFrontTop(), Vector3((Real)0.5, (Real)1.0, (Real)1.0)} - }; - - - Real error = (Real)0.0; - Vector4 value; - Vector3 gradient; - for (auto & position : positions) - { - value = mSrc->getValueAndGradient(position[0]); - gradient.x = value.x; - gradient.y = value.y; - gradient.z = value.z; - Real interpolated = interpolate(f000, f001, f010, f011, f100, f101, f110, f111, position[1]); - Real gradientMagnitude = gradient.length(); - if (gradientMagnitude < FLT_EPSILON) - { - gradientMagnitude = (Real)1.0; - } - error += Math::Abs(value.w - interpolated) / gradientMagnitude; - if (error >= geometricError) - { - return true; - } - } - node->setCenterValue(centerValue); - return false; - } - -} -} diff --git a/Components/Volume/src/OgreVolumeSimplexNoise.cpp b/Components/Volume/src/OgreVolumeSimplexNoise.cpp deleted file mode 100644 index e65e627e9cd..00000000000 --- a/Components/Volume/src/OgreVolumeSimplexNoise.cpp +++ /dev/null @@ -1,243 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreVolumeSimplexNoise.h" - -#include - -#include - -namespace Ogre { -namespace Volume { - - Real SimplexNoise::F3 = (Real)(1.0 / 3.0); - Real SimplexNoise::G3 = (Real)(1.0 / 6.0); - - Vector3 grad3[] = { - Vector3(1,1,0), Vector3(-1,1,0), Vector3(1,-1,0), Vector3(-1,-1,0), - Vector3(1,0,1), Vector3(-1,0,1), Vector3(1,0,-1), Vector3(-1,0,-1), - Vector3(0,1,1), Vector3(0,-1,1), Vector3(0,1,-1), Vector3(0,-1,-1) - }; - - //----------------------------------------------------------------------- - - unsigned long SimplexNoise::random(void) - { - // Simple XORShift random number generator like in http://www.jstatsoft.org/v08/i14/paper - mSeed ^= mSeed << 13; - mSeed = mSeed >> 17; - return mSeed ^= mSeed << 5; - } - - //----------------------------------------------------------------------- - - void SimplexNoise::init(unsigned long definedSeed) - { - mSeed = definedSeed; - short p[256]; - for (int i = 0; i < 256; ++i) - { - p[i] = (short)(random() % 256); - } - - for(int i=0; i<512; i++) - { - perm[i]= p[i & 255]; - permMod12[i] = (short)(perm[i] % 12); - } - } - - //----------------------------------------------------------------------- - - SimplexNoise::SimplexNoise(void) - { - init((unsigned long)time(0)); - } - - //----------------------------------------------------------------------- - - SimplexNoise::SimplexNoise(unsigned long definedSeed) - { - init(definedSeed); - } - - //----------------------------------------------------------------------- - - Real SimplexNoise::noise(Real xIn, Real yIn, Real zIn) const - { - Real n0, n1, n2, n3; // Noise contributions from the four corners - // Skew the input space to determine which simplex cell we're in - Real s = (xIn + yIn + zIn) * F3; // Very nice and simple skew factor for 3D - int i = (int)std::floor(xIn + s); - int j = (int)std::floor(yIn + s); - int k = (int)std::floor(zIn + s); - Real t = (i + j + k) * G3; - Real X0 = i - t; // Unskew the cell origin back to (x,y,z) space - Real Y0 = j - t; - Real Z0 = k - t; - Real x0 = xIn - X0; // The x,y,z distances from the cell origin - Real y0 = yIn - Y0; - Real z0 = zIn - Z0; - // For the 3D case, the simplex shape is a slightly irregular tetrahedron. - // Determine which simplex we are in. - int i1, j1, k1; // Offsets for second corner of simplex in (i,j,k) coords - int i2, j2, k2; // Offsets for third corner of simplex in (i,j,k) coords - if (x0 >= y0) - { - if (y0 >= z0) // X Y Z order - { - i1 = 1; - j1 = 0; - k1 = 0; - i2 = 1; - j2 = 1; - k2 = 0; - } - else if (x0 >= z0) // X Z Y order - { - i1 = 1; - j1 = 0; - k1 = 0; - i2 = 1; - j2 = 0; - k2 = 1; - } - else // Z X Y order - { - i1 = 0; - j1 = 0; - k1 = 1; - i2 = 1; - j2 = 0; - k2 = 1; - } - } - else // x0(&voxelWidth); - Vector3 diagonal = to - from; - size_t gridWidth = (size_t)(diagonal.x / voxelWidth); - size_t gridHeight = (size_t)(diagonal.y / voxelWidth); - size_t gridDepth = (size_t)(diagonal.z / voxelWidth); - ser.write(&gridWidth); - ser.write(&gridHeight); - ser.write(&gridDepth); - - // Go over the volume and write the density data. - Vector3 pos; - Real realVal; - size_t x; - size_t y; - uint16 buffer[SERIALIZATION_CHUNK_SIZE]; - size_t bufferI = 0; - for (size_t z = 0; z < gridDepth; ++z) - { - for (x = 0; x < gridWidth; ++x) - { - for (y = 0; y < gridHeight; ++y) - { - pos.x = x * voxelWidth + from.x; - pos.y = y * voxelWidth + from.y; - pos.z = z * voxelWidth + from.z; - realVal = Math::Clamp(getValue(pos), -maxClampedAbsoluteDensity, maxClampedAbsoluteDensity); - buffer[bufferI] = Bitwise::floatToHalf(realVal); - bufferI++; - if (bufferI == SERIALIZATION_CHUNK_SIZE) - { - ser.write(buffer, SERIALIZATION_CHUNK_SIZE); - bufferI = 0; - } - } - } - } - if (bufferI > 0) - { - ser.write(buffer, bufferI); - } - ser.writeChunkEnd(VOLUME_CHUNK_ID); - - } - - //----------------------------------------------------------------------- - - bool Source::getFirstRayIntersection(const Ray &ray, Vector3 &result, Real scale, size_t maxIterations, Real maxDistance) const - { - Ray scaledRay(ray.getOrigin() / scale, ray.getDirection()); - Vector3 start = getIntersectionStart(scaledRay, maxDistance); - Vector3 cur = start; - Vector3 end = getIntersectionEnd(scaledRay, maxDistance); - - Vector4 startVal = getValueAndGradient(start); - Vector3 scaleSampleGradient(startVal.x, startVal.y, startVal.z); - Vector3 scaleSampleEnd = start + scaleSampleGradient.normalisedCopy(); - Real scaleSample = getValue(scaleSampleEnd); - Real densityScale = (Real)1.0 / Math::Abs(scaleSample - startVal.w) * (Real)2.0; - - Real densityCur = getValue(cur); - Vector3 dir = scaledRay.getDirection().normalisedCopy(); - - size_t count = 0; - Vector3 prev = Vector3::ZERO, prevPrev = Vector3::ZERO; - bool atEnd = false; - Real totalLength = (start - end).length(); - while (Math::Abs(densityCur) > (Real)0.01 && !atEnd) - { - cur += dir * (Real)-1.0 * (densityCur / densityScale); - - // Increase the scaling a bit if we jump forth and back due to bad depth data. - if ((cur - prevPrev).length() < (Real)0.0001) - { - densityScale *= (Real)2.0; - } - prevPrev = prev; - prev = cur; - - densityCur = getValue(cur); - - // Check if we are out of range - if ((start - cur).length() >= totalLength) { - atEnd = true; - } - - // We have a limit here... - count++; - if (count > maxIterations) - { - break; - } - } - - if (Math::Abs(densityCur) <= (Real)0.01) - { - result = cur; - return true; - } - return false; - } - - //----------------------------------------------------------------------- - - Real Source::getVolumeSpaceToWorldSpaceFactor(void) const - { - return (Real)1.0; - } -} -} \ No newline at end of file diff --git a/Components/Volume/src/OgreVolumeTextureSource.cpp b/Components/Volume/src/OgreVolumeTextureSource.cpp deleted file mode 100644 index 2779f92261c..00000000000 --- a/Components/Volume/src/OgreVolumeTextureSource.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreVolumeTextureSource.h" -#include "OgreTextureManager.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreColourValue.h" -#include "OgreMemoryAllocatorConfig.h" -#include "OgreLogManager.h" -#include "OgreTimer.h" - -namespace Ogre { -namespace Volume { - - float TextureSource::getVolumeGridValue(size_t x, size_t y, size_t z) const - { - x = x >= mWidth ? mWidth - 1 : x; - y = y >= mHeight ? mHeight - 1 : y; - z = z >= mDepth ? mDepth - 1 : z; - return mData[(mDepth - z - 1) * mWidthTimesHeight + y * mWidth + x]; - } - - //----------------------------------------------------------------------- - - void TextureSource::setVolumeGridValue(int x, int y, int z, float value) - { - mData[(mDepth - z - 1) * mWidthTimesHeight + y * mWidth + x] = value; - } - - //----------------------------------------------------------------------- - - TextureSource::TextureSource(const String &volumeTextureName, const Real worldWidth, const Real worldHeight, const Real worldDepth, const bool trilinearValue, const bool trilinearGradient, const bool sobelGradient) : - GridSource(trilinearValue, trilinearGradient, sobelGradient) - { - - Timer t; - Image img; - img.load(volumeTextureName, ResourceGroupManager::getSingleton().getWorldResourceGroupName()); - - LogManager::getSingleton().stream() << "Loaded texture in " << t.getMilliseconds() << "ms."; - t.reset(); - - mWidth = img.getWidth(); - mHeight= img.getHeight(); - mWidthTimesHeight = mWidth * mHeight; - mDepth = img.getDepth(); - - mPosXScale = (Real)1.0 / (Real)worldWidth * (Real)mWidth; - mPosYScale = (Real)1.0 / (Real)worldHeight * (Real)mHeight; - mPosZScale = (Real)1.0 / (Real)worldDepth * (Real)mDepth; - - mVolumeSpaceToWorldSpaceFactor = (Real)worldWidth * (Real)mWidth; - - auto srcBox = img.getPixelBox(); - - mData = OGRE_ALLOC_T(float, mWidth * mHeight * mDepth, MEMCATEGORY_GENERAL); - auto dstBox = srcBox; - dstBox.data = (uchar*)mData; - dstBox.format = PF_FLOAT32_R; - PixelUtil::bulkPixelConversion(srcBox, dstBox); - - LogManager::getSingleton().stream() << "Processed texture in " << t.getMilliseconds() << "ms."; - } - - //----------------------------------------------------------------------- - - TextureSource::~TextureSource(void) - { - OGRE_FREE(mData, MEMCATEGORY_GENERAL); - } - -} -} diff --git a/Docs/1.10-Notes.md b/Docs/1.10-Notes.md deleted file mode 100644 index cc30dbaad9b..00000000000 --- a/Docs/1.10-Notes.md +++ /dev/null @@ -1,143 +0,0 @@ -# New and Noteworthy in OGRE 1.10 - -This is only a high level overview. For detailed changes, see the git changelog. - -## Core Improvements -* [Unified documentation](https://ogrecave.github.io/ogre/api/1.10/index.html) API reference, manual and some of the wiki tutorials are now all available through Doxygen and editable using Markdown. Now there is syntax highlighting in the snippets and automatic links to corresponding function documentation. To locally build the docs, just do `make OgreDoc`. The sources are in `Docs/src/`. -* by default Ogre will now automatically fetch and build its core dependencies. This way your deps have the same compile options like Ogre and you do not have to track the separate OgreDeps repository. -* Pass now uses a proper HashFunc and defaults to `MinGpuProgramChangeHashFunc`. This should give a performance boost when using the RTSS and with shader based materials. -* new `OgreAssertDbg` macro that only fires in Debug configuration. To be used in performance critical code. In turn the existing `OgreAssert` macro is now enabled in Release/ RelWithDebug configurations. -* FileSystemLayer: use `$XDG_CACHE_HOME` as base path on Linux -* FileSystemLayer: resolve paths inside snap packages on Linux -* allow using `std::thread` (with c++11) for background resource loading -* `Ogre::Any` and `Ogre::SharedPtr` now support the corresponding c++11/ c++17 API. (deprecating the previous API) -* using a duplicate resource name is an error now and throws an exception -* STBICodec using an embedded stb_image copy for image reading/ writing. No need using the bloated freetype. However you should not use this in a security critical environment. -* the nedmalloc allocator is now deprecated and disabled by default due to memory leaks. Use the default STL allocator. -* several functions were deprecated and will be dropped in the next major release. [See the deprecation list here.](https://ogrecave.github.io/ogre/api/1.10/deprecated.html) -* several SceneNode and Node functions were de-virtualised as they are internal API and were not overridden. If this breaks you code though, this will be considered a regression and be reverted/ fixed. -* performance improvements for `Ogre::ResourceGroupManager` -* upgraded embedded TinyXML from 2.5.2 to 2.6.2 - -### ResourceManager strict mode -By defining `OGRE_RESOURCEMANAGER_STRICT=ON` in CMake the Resource System is put into the a "strict" mode. In this mode resource managers default to *retrieving* resources rather than *searching* for them. -This means that you must specify not only the resource name, but also the resource group as resources are only uniquely identified by the `(name, group)` tuple. Furthermore lookup is case sensitive and all quirks are disabled. -This greatly improves performance as now usually only one group has to be searched - also this makes the lookup predictable. If you specify a group and the resource is not found, the managers will not fall back to some arbitrary other resource with the same name. -If you want OGRE to really search for a resource, you have to explicitly specify `AUTODETECT_RESOURCE_GROUP_NAME`. - -While enabling the strict mode is highly recommended, the default is the legacy mode to ensure compatibility with existing projects. - -### CMake Config-File support -A CMake config-file package is now installed making it easy to discover OGRE for third-party projects. This means that you no longer have to copy paste the `FindOGRE.cmake` script into your project. Instead you can specify `OGRE_DIR` to point to the installed `OGREConfig.cmake` and thats it. On Linux CMake will even automatically find OGRE if it is installed in one of the default system paths like `/usr/local/`. - -The config also provides the following variables for a better OGRE integration: - -* `OGRE_CONFIG_DIR` - the `resources.cfg` and `plugins.cfg` are located here -* `OGRE_MEDIA_DIR` - path to the sample media and RTShaderLib - -You are strongly advised to migrate away any custom/ local `FindOGRE.cmake` (i.e. just delete it). -In case you must support Ogre 1.10 and previous Ogre releases simultaneously, rename the local find script to e.g. `FindOldOGRE.cmake` and adapt your `CMakeLists.txt` as: -``` -find_package(OGRE) -if(NOT ${OGRE_FOUND}) - find_package(OldOGRE) -endif() -``` -this will give precedence to the upstream script and fall back to your local copy. - -### Plugins -* the EXRCodec can now be build again by setting `OGRE_BUILD_PLUGIN_EXRCODEC=TRUE` -* the BSPSceneManger now works when using the RTSS: i.e. it can be used with GLES2/ GL3Plus/ D3D11. - -### Testing / Continuous Integration -* PlayPen and Visual Tests are up and running again. They must pass if you want to get your code into Ogre now. -* Unit Tests ported from CppUnit to GTest. This allows to build them easily on all platforms and even run on Android. (see NDK docs how) -* similarly all warnings were eliminated from the code base and `-Werror` was turned on the GCC and MSVC builds. - -### Emscripten -In case you want to bring your existing code-base to the web or just continue using a familiar development environment, there is now Emscripten/ HTML5 support with Ogre. [You can see it live here](https://ogrecave.github.io/ogre/emscripten/). - -The sources are in `Samples/Emscripten` and build instructions in BuildingOgre.md. - -## RenderSystems - -### GLSupport -This module includes the platform specific parts that are needed to create a GL Context. (i.e. GLX, WGL, Cocoa, EGL) -They had been copy/ pasted but stayed largely the same across the different GL Rendersytems. - -The result is the GLNativeSupport API that can be plugged in the exiting GL*Support classes (e.g. GL3PlusSupport) to handle the context creation. - -Furthermore the API was extended to allow specifying a context profile. This way the GL3Plus RS creates a core profile, while the old GL RS uses the compatibility profile. Additionally you can create a GLES context using GLX/WGL on a desktop machine and use/ test the GLES2 RenderSystem there. -In case you are in the embedded world or on Wayland/ Mir already it can also use EGL to be compatible with those. - -### GLES2 -Due to the ubiquitous availability of GLES2 this RenderSystem got a large overhaul. -All legacy workarounds without justifications were removed from the code which makes it behave the same on all platforms and also fixing several VTests. -The extension handling was fixed, it is now possible running in GLES2 mode on GLES3 contexts which previously led to a crash on Android. - -Furthermore, - -* 3D textures are now also available in GLES2 mode -* Emscripten: GL_ANGLE_instanced_arrays is supported -* declare glsl300es/ glsl310es/ glsl320es shader profiles - -## Components - -### OgreBites -The reusable parts of the SampleBrowser were factored out forming the new OgreBites Component. -It handles Ogre startup/ tear down (including Overlay, RTShaderSystem) and also includes the SdkTrays and SdkCameraManager. - -This is useful if all you want is to get a Scene with a FPS counter up and running (i.e. rapid prototyping). -If available it also uses SDL2 for input - you now just have to implement the callbacks. - -By making the SampleBrowser code useful by third-party apps, both benefit. - -Furthermore the Android specific parts of SampleBrowser were merged into OgreBites. This eases porting your application to Android if it uses the ApplicationContext. - -### Python -After python bindings are now SWIG based with the corresponding siwg interfaces being part of ogre. This means that if you checkout the git version you can have up-to-date bindings for it. The work took some inspiration by the [ruby-ogre](https://github.com/abexsoft/ruby-ogre) project. -This means that it would be trivial to bring up an Ogre-Ruby component if needed by someone. -As there is some demand for it a [Ogre-C# (Mono) component was prototyped](https://github.com/OGRECave/ogre/pull/192). However some help is needed here. - -Currently the OgreMain, RTShaderSystem, Overlay and OgreBites Components are covered. However most iterator APIs are broken, as the way they are implemented in Ogre is rather exotic. - -For usage see the code in `Samples/Python`. - -### RTShaderSystem -The duplicated GLSL, GLSLES and GLSL150 shaders were merged into one common GLSL codebase. Furthermore the lighting equations were fixed such that they produce the equal light intensity as fixed function GL. This allows pixel perfect replication of the fixed function pipeline [in some cases](https://ogrecave.github.io/ogre/#opengl-rendersystem-status). - -In general the GLSL support was improved: - -- Environment Map (reflection) shaders no longer produce a flipped reflection -- The hardware skeletal animation support was finished. See the skeletal animation sample for how to enable it in your code. - -### High Level Material System (HLMS) -This component is a backport from the 2.1 branch and is a different take to shader management. Basically it solves the same problem like the RTShaderSystem, but instead of relying on C++ classes generating the final shader it rather uses a custom preprocessor language. -Currently the HLMS only implements a PBS material which is not compatible with the legacy Ogre materials that implement fog, diffuse_color etc. . - -If you want to implement your own materials and use custom shaders all the way, this is the way to go. If on the other hand you like the flexibility and convenience of the legacy Ogre materials, you should keep with the RTSS. - -### MeshLodGenerator -This code was factored out from OgreMain and is now a separate Component. - -## Tools -Some Tools that were dysfunctional and unmaintained were removed from the repository. Notably: - -* **MaterialEditor**: was relying on an no longer maintained wxWidgets component. Copy paste parts of [Ogitor](https://github.com/OGRECave/ogitor) if you need it. -* **Blender26Export**: dysfunctional. Use [blender2ogre](https://github.com/OGRECave/blender2ogre) instead. -* **BlenderExport**: same as above - -On the plus side **VRMLConverter** was brought back from the dead. - -## SampleBrowser -As the SampleBrowser is now based on the OgreBites component it also uses SDL2 for input, which finally means a modern input system instead of OIS. -The drawback is that the NaCL platform is currently broken due to missing bits in OgreBites. However porting should be straightforward. - -Furthermore the following Samples were updated/ added: - -* ComputeShader: shows how to use ComputeShaders with the GL3+ RS -* ShaderSystemMultiLight: ported to GLES3 -* VolumeTerrain: fixed the triplanar texturing part -* HLMS: resolve conflict with RTSS -* Shadows: fixed GLSL shaders for Stencil shadowing (now working on GL3+) -* DeferredShading: resolve conflict with RTSS (now working on GL3+ and GLES2) diff --git a/Docs/1.11-Notes.md b/Docs/1.11-Notes.md deleted file mode 100644 index 1983187a95b..00000000000 --- a/Docs/1.11-Notes.md +++ /dev/null @@ -1,232 +0,0 @@ -# New and Noteworthy in OGRE 1.11 - -This is only a high level overview. For detailed changes, see the git changelog. - -## Core changes - -Ogre now requires a C++11 conforming compiler (at least gcc 4.8 or VS2013). Furthermore internal headers were moved into the src/ directory and are not installed any more when creating the SDK. This prevents you from accidentally using private API, while giving us more flexibility to change the implementation. - -* Reduced Memory consumption of core classes - - by reducing padding and using bitfields for flags, the memory consumption of e.g. `Pass` could be reduced by 11%. - - see https://github.com/OGRECave/ogre/pull/665 for numbers of other classes - -* Added strong typed `Affine3` matrix class. - - overloads of `operator*`: no need to remember to call `transformAffine`, `concatenateAffine` etc. any more - everything is done and checked by the compiler automatically. - - affine only methods moved from `Matrix4` to `Affine3`. e.g. `decomposition`, `getTrans`. - - scale related functions moved from `Matrix4` to `Matrix3`: porting `.hasScale()` → `.linear().hasScale()` - - similarly `transformDirectionAffine` is now done by extracting the linear part via `linear()` and using `operator*` of `Matrix3`, that has now improved performance. - -* New `SceneLoaderManager` API - * you can now register classes derived from `SceneLoader` - * calling `SceneLoaderManager::load("filename.ext", "Group", rootNode)` will then dispatch to a Loader supporting ".ext" (if available) and populate the given SceneManager starting at `rootNode`. - -* `Image::flipAroundX/Y` now operate in-place instead of allocating temporary memory. - -* `PF_DEPTH` now correctly works with `TU_RENDERTARGET`. This will create a depth-only FBO and give you the raw depth values, without needing any special shaders. - -* Generic Image codecs (STB Image, FreeImage) are now plugins. For distribution you should use compressed textures (e.g. DDS) with precomputed mipmaps. Having the generic codecs as plugins allows you to easily disable them. Editing software on the other hand can now easily swap in a custom implementation (like QImage). - -* `InstancedGeometry` API removed. This was replaced with the more flexible `InstanceManager` API in OGRE 1.8. - -### Use plain STL where possible - -* C++11ifycation: replace core classes by C++11 equivalents - particularly - - SharedPtr -> `std::shared_ptr`. Note that due to its widespread usage, a SharedPtr wrapper class still exists for backwards compatibility. - - AtomicScalar -> `std::atomic` - - OGRE_HashMap -> `std::unordered_map` - - _StringHash -> `std::hash< string >` - - Timer: the platform specific implementations were replaced by wrapping - `std::chrono`. - -* Removed container indirections. `Ogre::vector::type`, is now just plain `std::vector`. The Ogre version is still there to ease porting, but will generate a deprecation warning. - -* drop Threading backport from 2.x, `std::thread` is now the preferred API. - -* Memory Allocation cleanup - * Drop MemoryTracker API. Nowadays [MSan](https://github.com/google/sanitizers/wiki/MemorySanitizer) is the better alternative. - * drop builtin support for custom memory allocators. Consequently drop nedmalloc. Was only needed on WinXP. Empty class definitions are still there for compatibility. If you still want a different allocator you have to [do so globally](http://en.cppreference.com/w/cpp/memory/new/operator_new#Global_replacements). - -### Platform independant OgreMain - -Linking against OgreMain will no longer pull in any platform UI libraries (e.g. Cocoa, X11). The respective code was moved to OgreBites. - -* `WindowEventUtilities` were moved to the Bites Component. They rely on low level platform code (like X11 on linux) and are mostly obsoleted by the ApplicationContext class. Generally you should be using SDL2/ Qt for windowing and just embed Ogre. - - Windows porting note: to continue using `WindowEventUtilities`, you now must explicitly register `_WndProc` for each window you create: - ``` - NameValuePairList miscParams; - miscParams["windowProc"] = - StringConverter::toString((size_t)WindowEventUtilities::_WndProc); - RenderWindow* renderWindow = - Root::getSingleton().createRenderWindow(name, width, height, isFullScreen, &miscParams); - WindowEventUtilities::_addRenderWindow(renderWindow); - ``` - i.e. `Ogre::Root::initialise(True, ...)` does no longer work. - -* similarly the `ConfigDialog` was moved to the Bites Component. - -* unused `ErrorDialog` API was dropped - -### Breaking non-API changes - -These changes require unit testing on your side as compilation will succeed, but the rendering result may vary compared to 1.10. - -* `TextureUnit` no longer caches any `Texture` state. All texture related calls now forward to the assigned Texture. If there is no Texture assigned, calls to e.g. `TextureUnitState::setNumMipmaps` have no effect. - -* Textures must not be declared in an Ogre Script *and* be manually created. Ogre now immediately creates all Textures declared in scripts (in unloaded state). Previously it was possible to declare a texture name in the Material and create a manual texture before the material was fully loaded. This is not possible any more. -If you were relying on the old behaviour, you now must explicitly set the texture via `pass->getTextureUnitState(..)->setTexture(manualTex)`. - -* default Light direction changed from `UNIT_Z` to `NEGATIVE_UNIT_Z` to be consistent with Cameras and SceneNodes. This will only cause issues if you were relying on the default direction. If you manually set it directly or via SceneNodes the results are the same. For legacy code with Lights attached to SceneNodes, just drop the `localDirectionVector` param. - -* Mesh: does not use CPU shadow buffers by default any more. If you were relying on fast read access, you will have to explicitly request shadow buffers. Everybody else just saves memory now. - -* AxisAlignedBox: do not cache corner positions to reduce memory usage - -### Other - -* drop RenderSystemCapabilities that were never set or that are supported everywhere - -* `Archive` specializations e.g. `FileSystemArchive`, `ZipArchive` are now fully hidden. You must now use the respective Factories to create them. - -* SceneManager: factored out SkyRenderer and ShadowRenderer helper classes. They enforce encapsulation and allow easier maintenance of the respective algorithms. In future this will be pluggable to allow for more sophisticated algorithms. - - -## CMake/ Build - -Precompiled headers (PCH) support was rewritten and now works on GCC too (not yet with clang). -* PCHs are the predecessors of the Module TS (C++20) -* on both MSVC and GCC they speed up the build by about 2x -* Consequently the "Unity build" (rather hack) option was dropped - -The `FindOGRE.cmake` script (deprecated in 1.10) was dropped in favour of the modern `OGREConfig.cmake` config-file package. -Additionally `OGREConfig.cmake` was upgraded to use export targets instead of variables. - -This means that you now can just write -```python -target_link_libraries(YourApp OgreMain) -``` -and all include path and additional libraries will be automatically handled. Using `${OGRE_INCLUDE_DIRS}` is not necessary any more. - -New `OGRE_RESOURCEMANAGER_STRICT` options: - -0. legacy mode that searches through all groups (slow) -1. pedantic mode that forces you to specify a resource group (cumbersome) -2. new strict mode that only searches the default group - -Mode 2 is the default now and the legacy mode 0 is deprecated. For a for a quick and dirty porting to mode 2, consider: -```cpp -// changing all instances in your code from -ResourceGroupManager::getSingleton().createResourceGroup(name); -MeshManager::getSingleton().getByName(name); -MeshManager::getSingleton().unload(name); - -// to -ResourceGroupManager::getSingleton().createResourceGroup(name, true); -MeshManager::getSingleton().getByName(name, RGN_AUTODETECT); -MeshManager::getSingleton().unload(name, RGN_AUTODETECT); -``` -which will explicitly enable the legacy behaviour (while still being case-sensitive). - -Note that you have to clear your CMake cache variable for the new values to work. Otherwise you will get compile errors due to the old values (ON/ OFF). - -## Platforms -All platform headers were hidden and are now only available for internal usage. You are forced to use the cross platform API now. Alongside support for some obsolete platforms was dropped. -* Android: Android specific classes are now declared in the respective Main headers. e.g. APKZipArchive is in `OgreZip.h` -* iOS/ OSX: `macUtils.h` is hidden. Use the cross-platform alternatives in `FileSystemLayer` e.g. - - `iOSDocumentsDirectory()` -> `getWritablePath` - - `macBundlePath()` -> `resolveBundlePath` -* Google NaCl platform support was removed. [See the official migration guide](https://developer.chrome.com/native-client/migration) -* MinGW (mingw-w64) is support again, including the D3D9 RenderSystem - -## RT Shader System - -Extend API for additional shader types (e.g. Geometry) and drop the separate HLSL4 handling. With D3D11 we now use the HLSL4 legacy mode which allows us to use the same shaders like for D3D9. This unifies the code and improves RTSS compatibility with D3D11. - -## Overlay -Overlay scripts now support the standard ogrescript syntax and the `template` keyword is now optional. -Furthermore the the `overlay_element` keyword unifies `container` and `element`, as there was little difference between those two. -So if you had a script like this - -```cpp -template container BorderPanel(MyTemplates/BasicBorderPanel) -{ - ... -} - -MyOverlays/AnotherOverlay -{ - zorder 490 - container BorderPanel(MyElements/BackPanel) : MyTemplates/BasicBorderPanel - { - ... - } -} -``` - -you can (and should) now write - -```cpp -overlay_element MyTemplates/BasicBorderPanel BorderPanel -{ - ... -} - -overlay MyOverlays/AnotherOverlay -{ - zorder 490 - overlay_element MyElements/BackPanel BorderPanel : MyTemplates/BasicBorderPanel - { - ... - } -} -``` - -in a later release the custom parser will be replaced by a standard ScriptTranslator. However to retain support for the old syntax it is kept for now. Consequently this means that script variables and abstract objects are not yet supported. - -### Fontdef - -The generic Ogre Script parser is now used for .fontdef scripts as well. Basically the same rule as for overlay scripts apply: - -Where you had -``` -MyFont -{ - type image - source atlas.png - glyph " 0.691406 0.343750 0.796875 0.515625 - ... -} -``` - -you should now write - -```cpp -font MyFont -{ - type image - source atlas.png - glyph "\"" 0.691406 0.343750 0.796875 0.515625 - ... -} -``` - -Here, the glyph property needs extra care, as it may contain ogre script separators like `", }, :`, which must be explicitly marked as strings now, by wrapping them in `""` (as done in the sample above). - -## BSP Plugin -* ported to the new `SceneLoader` API. Consequently `BspResourceManager` was replaced by `BspSceneLoader`. - -## RenderSystems -* GL: bump required OpenGL version to 1.5 (Hardware from 2003) -* GL: no longer depends on GLU (deprecated since 2009) -* D3D9: improved compatibility with MinGW-w64 -* GLES1: dropped GLES1 RenderSystem (deprecated since 1.8) - -## Bites -This component finalized which allows us to drop the BETA status -* SDL2 classes are no longer exported through headers. - * OgreBites SDLK_.. enum moved into the `OgreBites` namespace. Internal SDL2 fields no longer accessible. -* While the API still resembles SDL2, we can now swap the implementation to e.g. Qt without API breaks. - -## Samples -Build all included samples as on SamplePlugin "DefaultSamples". This greatly simplifies the build and reduces build time while external Plugins are still supported. - diff --git a/Docs/1.12-Notes.md b/Docs/1.12-Notes.md deleted file mode 100644 index bb383687209..00000000000 --- a/Docs/1.12-Notes.md +++ /dev/null @@ -1,204 +0,0 @@ -# New and Noteworthy in OGRE 1.12 - -This is only a high level overview. For detailed changes, see the git changelog. - -## Core changes - -### Component Media files - -Previously all of our bundled Media files lived in the `Samples/Media` subdirectory - including the `RTShaderLib`. -However the latter is not a sample, but required to use the RTSS component. -Therefore, we now put media files that are required by a component into `Media/*` and install them independent of the Sample Media. -This allows you to merely reference these locations instead of having to copy them into your project. - -Consequently, this allowed us to move various embedded resources to the filesystem for easier editing. - -**ACTION REQUIRED** you must add the `Media/ShadowVolume` resource location to use the build-in algorithms. - -### NEON intrinsics on all ARM platforms - -We converted our SSE based OptimisedMath using SSE2NEON. While the gains are not as substantial as on x86, you can expect an speedup of about 30% for e.g. CPU skeletal animation. - -### Automatic Plugin discovery for Windows Debug builds - -Ogre now automatically append the `_d` suffix to plugin library names on windows. -Consequently it does not need a `plugins_d.cfg` any more. Therefore you can now use the same config files for release and debug with the same content. - -### Separate UV skyboxes removed - -Ogre no longer supports `cubic_texture .. separateUV` textures. Previously it was possible to create a "fake" cubic texture unit which would actually contain 6 individual 2d textures. These could be used to render skyboxes. Only skyboxes that is. -For everything else you would need real hardware cubic textures. -Ogre will ignore the `separateUV` part now, and create a real cubic texture anyway. -The advantage is that ogre renders the skybox with only one draw call. - -**ACTION REQUIRED** If you use custom shaders on such materials, you will have to update them to cope with real cubic textures. - -### RenderSystem - unified API for fixed-function and shaders - -The `RenderSystem` API was modernized and streamlined for programmable pipeline usage. Consequently most of the legacy fixed function API calls were removed (e.g. `_setProjectionMatrix`, `_setSurfaceParams`). - -Instead these parameters are now passed through the `GpuProgramParameters` structure to the fixed function unifying the API between fixed and programmable pipeline. - -RenderSystems supporting `RSC_FIXED_FUNCTION`, now export the respective parameters through `getFixedFunctionParams`. -You can query and modify those and then apply them using `applyFixedFunctionParams`. - -If you bypass the SceneManager and use the RenderSystem directly, e.g. `_setProjectionMatrix` becomes - -```cpp - auto params = rs->getFixedFunctionParams(TVC_NONE, FOG_NONE); - params->setConstant(8, Matrix4()); // the "magic" 8 is defined in getFixedFunctionParams - rs->applyFixedFunctionParams(params, GPV_GLOBAL); -``` - -### Improved Profiling - -The instrumentation code inside Ogre was improved to be less costy compared to the measured code. At this we also improved the labels to be more readable (camera name vs. "_renderScene") - see [the updated Profiling tutorial](https://codedocs.xyz/OGRECave/ogre/profiler.html#profRead). - -Additionally the Profiler class can now use [Remotery](https://github.com/Celtoys/Remotery) as its backend. Again see the tutorial for more details. - -### Multi-language GPU Programs (since 1.12.9) - -Basic programs, are compatible with GLSL and GLSLES. To avoid duplicating the whole program declaration, you can simply specify all the language types the program is compatible with as: - -```cpp -fragment_program myFragmentShader glsl glsles -{ - source example.frag -} -``` - -### Cubemap support in compositors (since 1.12.12) - -Compositors render targets can now be cubemaps by adding the `cubic` keyword to the `texture` declaration - just like with `texture_units` in materials. - -To really take advantage of this, you can now also specify the camera to use when doing `render_scene` passes. This way any camera in your scene can be used as an environment-probe for cube mapping. - -Additionally, there is now the `align_to_face` keyword which automatically orients the given camera to point to the targeted cubemap face. - -### Breaking non-API changes - -These changes require unit testing on your side as compilation will succeed, but the rendering result may vary compared to 1.11. - -* `fog_override` semantics changed: previously it would only affect fixed function fog and shader autoparams would still get the global scene fog. Now both autparams and fixed function settings are affected. - -* `SubMesh::setMaterialName` now immediately queries the `MaterialManager` instead of merely storing the name. This means that if you do not load any `.material` files and do an import/ export cycle of a `.mesh`, the material names will be lost. This is a common use case for offline processing of mesh files. Register a `MeshSerializerListener` to create dummy materials in this case. - -* `Ogre::any_cast` now throws a `std::bad_cast` exception instead of a `Ogre::InvalidParametersException` for compatibility with `std::any_cast`. Both derive from `std::exception`, in case you want to preserve legacy compatibility. - -* The `OGRE_BUILD_*` defines moved to a separate `OgreComponents.h` header. As those were typically checked with `#ifdef`, these check will silently fail. Migrate to the `Ogre.h` header instead of including headers form OgreMain directly. - -* compute shaders are no longer automatically dispatched when the according material is used during rendering. You now have to explicitly reference the respective material in a [*compute* compisitor pass](https://ogrecave.github.io/ogre/api/latest/_compositor-_scripts.html#Compositor-Passes). - -## Samples - -As a side-effect of the stable media files effort, the Sample media files were refactored as well. -Now all GL rendersystems share a common GLSL shader codebase - likewise the D3D rendersystems and the Cg plugin use the same Cg shaders (which is just HLSL9 really). - -Additionally we took advantage of the RTSS improvements and replaced any custom depth shadow code by the unified RTSS solution. - -Since 1.12.7, the PBR sample additionally showcases the usage of [Filament PBR shaders](https://google.github.io/filament/Materials.html). - -## Bites - -The `ApplicationContext` class was split into `ApplicationContextBase` and `ApplicationContextSDL`. This allows additional implementations (like Qt) and eases consumption in projects that do not use SDL. - -### Qt Integration (since 1.12.6) - -There is now an glue code for Ogre-Qt interop, that builds upon the ApplicationContext abstraction. - -The API exposed through the `ApplicationContextQt` class is `QWindow` based making it lightweight - only the `QtGui` module is required. -Also, this should allow extending it for QtQuick in the future, which is also `QWindow` based. - -The implementation lives in a separate `OgreBitesQt` library which is only created when Qt is detected when building - so if you do not use it, you do not have to care about any Qt dependencies. - -### Relocatable Install (since 1.12.9) - -You can now control the lookup of Plugins and Resources with the following environment variables -- `OGRE_PLUGIN_DIR` override the `PluginFolder` setting in `plugins.cfg` at runtime -- `OGRE_CONFIG_DIR` sets a custom directory where ogre looks for `resources.cfg` and `plugins.cfg`. - -Furthermore, relative locations inside `resources.cfg` are now correctly resolved in respect to that cfg file. - -### Gamepad Support (since 1.12.11) - -When using `ApplicationContextSDL`, you will now also get Input events for any attached gamepads. - -## Real Time Shader System 3.0 - -The RTSS API was overhauled and is now more flexible and easy to use. You can now directly acquire shaders for an arbitrary Pass using `TargetRenderState` - without having to go through any Viewport Scheme juggling. This means that `TargetRenderState` can now replace any ad-hoc shader generator that you might have in place to leverage the Ogre maintained RTSS shader snippets. - -The RTSS now defaults to Per-Pixel lighting, consequently making it the default for GL3+/ GLES2 and D3D11. - -### Depth Shadowmap Support -The PSSM3 shadow stage now supports hardware PCF and automatically uses it if your shadow textures are compatible (i.e. of type `PF_DEPTH`). - -Furthermore you can now use it generally for depth based textures by not calling `setSplitPoints` - it will use only the first depth shadow texture then. - -### Merged Lighting calculations -The Fixed Function, Per-Pixel and Normal map sub-render states now all share the same shader code. - -**ACTION REQUIRED** you must update your `RTShaderLib` for the 1.12 shaders. - -## Terrain - -To allow usage `PF_DEPTH` shadow textures, the "linear" depth code was dropped from the `SM2Profile`. -Where previously you were expected to write an interpolated value of `(gl_Position.z - depthRange.x) * depthRange.w` in the fragment shader, it is now enough to just write `gl_FragCoord.z`. -This enables early-z optimizations by the hardware and generally eases the workflow. -Refer to the Terrain Sample for the updated depth shadow scene setup. - -Furthermore it is now possible to load legacy 1.7 style Terrains (aka "terrain.cfg") using `TerrainGroup::loadLegacyTerrain`. - -**ACTION REQUIRED** you have to add the `Media/Terrain` resource location to use the SM2Profile Shader Generator. - -## D3D9 RenderSystem - -Direct3D9 feature level 9.1 is now required. - -## GL/ GLES2/ GL3+ - -`#include` directives in GLSL shaders are now resolved by OGRE. The lookup is performed by filename using the Resource System. (based on the existing code of the Cg plugin) - -Monolithic shaders are used instead of separable shader objects (SSO) by default again due to better performance and better driver support. - -Since 1.12.2, the GL3+ RenderSystem supports loading SPIRV shaders. This requires SSO to be enabled though. - -Starting with 1.12.10, the GLES2 RenderSystem is usable on Windows with drivers providing the `WGL_EXT_create_context_es2_profile` extension (only NVidia and Intel at the time of writing). - -## DotScene Plugin (since 1.12.2) - -The DotScene (aka .scene) Plugin was merged into the main repository. This format stores the scene hierarchy and is supported by the `blender2ogre` and `EasyOgreExporter` (3DS Max) exporters. - -## Reversed Depth Support (since 1.12.3) - -On D3D11 & GL3+, Ogre allows you to use a reversed floating-point Z-Buffer, that results in an approximately linear depth value distribution. To use this, enable the "Reversed Z-Buffer" RenderSystem option. - -This will make Ogre use the `[1; 0]` range for depth values instead of the standard `[0; 1]` range. To handle this in your shaders, there is now a `OGRE_REVERSED_Z` define if revered depth is used. - -## Metal RenderSystem Preview (since 1.12.7) - -The implementation pretends to have Fixed Function capabilities leveraging the unified FFP API. This allows operating with a single shader, which only supports one 2D texture without lighting. - -Proper lighting and texturing support, would require a Metal Shader Language support in the RTSS, which is not there yet. Therefore, the RenderSystem is tagged as EXPERIMENTAL. -However, if you only want to custom shaders on OSX, you can start experimenting with Metal now. - -## Assimp Plugin (since 1.12.9) - -The separate `ogre-assimp` project was merged into the main repository as the `Codec_Assimp` Plugin, which allows loading arbitrary meshes and runtime and the `OgreAssimpConverter` Tool for converting meshes to the `.mesh` format offline (which improves loading time). - -Especially the introduction of `Codec_Assimp` is notable, as mesh loading now goes through the same Codec dispatching as image formats. - -On the application side, you can now simply -```cpp -sceneManager->createEntity("Bike.obj") -``` - -## Native MovableText (since 1.12.10) - -The Font class can be used to create 3D text billboards. No more snippets from the Wiki needed and everything integrates with the existing API as: - -```cpp -auto font = FontManager::getSingleton().getByName("SdkTrays/Caption"); -auto bbs = mSceneMgr->createBillboardSet(); - -font->putText(bbs, "OGRE\n ...", 10); -``` \ No newline at end of file diff --git a/Docs/13-Notes.md b/Docs/13-Notes.md deleted file mode 100644 index 6419e575ae6..00000000000 --- a/Docs/13-Notes.md +++ /dev/null @@ -1,227 +0,0 @@ -# New and Noteworthy in OGRE 13 - -This is only a high level overview. For detailed changes, see the git changelog. - -**The versioning scheme changed with this release. This is the successor to Ogre 1.12 and the porting efforts are comparable with porting from 1.11 to 1.12.** - -## Core changes -### Zero external dependencies -Ogre was put on a dependency diet and now you can get a fully functional build without any additional dependencies. We replaced zlib and libzzip in Main by miniz and use a bundled stb_truetype for Overlays if you dont provide Ogre with freetype. - -While miniz provides a seamless replacement, there are visual differences when using stb_truetype due to differences in glyph metrics. - -### Node-less positioning API disabled by default -Traditionally Ogre allowed you to place Cameras and Lights in the scene without attaching them to a SceneNode. This resulted in three different positioning APIs for Cameras, Lights and SceneNodes with slight inconsistencies (e.g. `Camera::move` vs. `SceneNode::translate`). -Furthermore, this complicated things when e.g. attaching a Camera to a SceneNode as you might have an additional transform "hidden" inside Camera. - -Therefore, the use of node-less positioning was deprecated since Ogre 1.10.8. With this release we disable the according API and no longer store any transforms inside Light and Camera so you have to port your code like: -```cpp -// Ogre 1.12 (warning: ‘setDirection’ is deprecated) -mLight->setDirection(...); - -// Ogre 13 (also 1.12 to get rid of warnings) -mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(mLight); -mLight->getParentSceneNode()->setDirection(...); -``` -Alternatively, you can set `OGRE_NODELESS_POSITIONING=ON` in CMake to get back the old behaviour. - -### Unified storage of GpuProgramParams -All constants are stored in a single byte-buffer instead of being split by -type. -This maps to how Uniform/ Constant buffers work and allows updating a backing hardware buffer with a single `memcpy` instead of having to explicitly collect the individual floats. -Consequently, `physicalIndex` is now a byte offset instead of a slot offset. -The high-level APIs based on `String` names and `logicalIndex` are not affected by this change. - -### Unified HighLevelGpuPrograms & GpuPrograms -`HighLevelGpuProgramPtr` is now an alias for `GpuProgramPtr`. While the class separation still exists, user code should use both interchangeably. -The only user-visible change is that calls `setPreprocessorDefines(...)` should be be changed to `setParameter("preprocessor_defines", ...)`. - -Furthermore, `HighLevelGpuProgramManager` is now merely an alias for `GpuProgramManager`. Internally, this saves us quite some shunting. Most users should not notice - unless you were creating low-level and high-level programs with the same name. This will trigger an error now, as both live in the same resource-namespace. - -### Private class visibility -Historically, Ogre only used only public and protected visibility. While this makes it easy to customise Ogre classes for a specific use, it is not so great when it comes to committing to a stable API. -Previously, you could (accidentally) use a inherited class member that we would later change during an internal refactor, causing your code to break. While we could exclude all protected members from our API guarantee, it would be even better if the compiler would check that you only use the stable API - thats exactly what private visibility does. -Consequently, most protected members are private now. - -### `shadow_*_program_ref` API removed -`shadow_caster_material` and `shadow_receiver_material` are better alternatives available since Ogre 1.6. These not only simplify code, but also allow for efficient caching of generated shaders. - -Nevertheless, there is fallback code so you still can use old `.material` files. Here, a caster/ receiver material will be generated on demand. However, you are highly encouraged to define those explicitly. - -### `texture_alias` API removed -Texture aliases were a restricted version of Script Variables, which you should instead. -I.e. replace - -```cpp -texture_alias DiffuseMap -// and -set_texture_alias DiffuseMap r2skin.jpg -``` - -by - -```cpp -texture $DiffuseMap -// and -set $DiffuseMap r2skin.jpg -``` - -There is limited backward compatibility for material scripts, where `texture_alias` will set the texture unit name and later `set_texture_alias` is applied based on that. - -### Automatic Instancing (since 13.5) - -Visible SubEntities can now be automatically batched up for Hardware Instancing. -While this is not as fast as using the respective InstanceManager class, it requires no code changes and still offers a nice speed-up. -The idea is that you specify that your vertex shader is capable of instancing - similar to how you would do for hardware skinning: - -```nginx -includes_instancing true -``` - -Ogre will then do the rest and provide the world matrices through an automatically created instance buffer to the shader. - -The RTSS will also set the respective flag, so enabling hardware instancing now merely takes only one line in the material script: - -```nginx -rtshader_system -{ - transform_stage instanced -} -``` - -### Object Space Bones (since 13.5) - -Ogre now offers the option to do the bone-to-world transformation on the GPU - aka "Object Space Bones". - -Traditionally Ogre passed bones to shaders (for HW skinning) via the `world_*_array` auto constant. Obviously this implied the bones to be in world space. To this end, Ogre did the transformation on the CPU. While this does not add much for a few bones, it becomes noticeable if you got multiple skeletons with 40+ bones. - -You can opt-in into the new behavior via `MeshManager::setBonesUseObjectSpace`. -Also see `Renderable::getWorldTransforms` for how to return the transformations for your custom renderables when doing so. - -When using the RTSS for HW Skinning, it will automatically generate improved shaders, when the option is on. - -Also, you can now use the `bone_*_array` alias instead of `world_*_array` for clarity. Note that `world_*_array` was exclusively used for bones by Ogre anyway. - -### Other -- Size of the Particle class was reduced by 12% which results in about 13% faster rendering -- Frustum is not a Renderable any more. Rendering Frusta is now done by the DebugDrawer. -- ShadowTextureListener was factored out of SceneManager::Listener -- RenderQueueInvocationSequence API was removed as it prevented effective batching. Use the current Viewport name instead of invocationName in your RenderQueueListener for porting. -- SWIG 4.0 is now fully supported -- Following SemVer, incrementing PATCH now guarantees ABI compatibility. Therefore SOVERSION on Unix system now only contains two digits e.g. `libOgreMain.so.13.0` instead of `libOgreMain.so.1.12.13`. -- since 13.3, `PF_DEPTH24_STENCIL8` is available -- since 13.6, shadow pancaking is applied for directional shadow lights - - -### Breaking non-API changes - -- `VET_COLOUR*` is now an alias for `VET_UBYTE4_NORM`. On most RenderSystems VET_COLOUR would be already mapped to VET_UBYTE4_NORM anyway. A notable exception is D3D9, where this changes the channel order from BGRA to RGBA. If you are using custom vertex shaders, you must update them accordingly. For all other cases Ogre will handle this for you. If a buffer conversion is performed on loading, Ogre will issue a warning in the log. -- The default transform space of `SceneNode::setDirection` changed from `TS_LOCAL` to `TS_PARENT` to aid with the node-less positiong transiton. -- The `parentWindowHandle` and `externalWindowHandle` Window creation parameters are now equivalent on all platforms. - - On Win32 the `parentWindowHandle` behaviour is gone and no child window is ever created. - - On Linux the `externalWindowHandle` behaviour is gone and an external `GLXDrawable` can be only set via an external context. - -## Overlay -`DisplayString` is now merely an alias for `String`. The `UTFString` class was replaced by a much smaller (and faster) implementation that is not exposed. For all practical purposes, you can just pass UTF8 encoded strings through `String`. - -Glyph placement has been improved. Previously Ogre only considered glyph width for typesetting. However, this did not take into account that glphs can overlap, as happens with italic fonts. Therefore, there is now an independent property `GlyphInfo::advance`. Ogre internal code was updated for this change. However, if you directly access the texture atlas, you have to update your code. - -An Exception is now thrown, when querying a `GlyphInfo` of a Font that is not loaded. Make sure to call `font->load()` before querying. - -## RTSS -There is now a RTSS stage for Weighted, blended Order Independent Transparency, which implements the according algorithm by Morgan McGuire. -See the transparency Sample for how to integrate it into your pipeline. - -The RTSS Normal Map stage, is no longer a lighting stage but only does normal mapping. -This allows using it with per-pixel lighting as before, but also enables combining it with the GBuffer stage to enable normal mapping in the GBuffer. - -**ACTION REQUIRED** Direct specification of sampler parameters via `lighting_stage normal_map ...` is no longer supported and the additional parameters will be interpreted as a sampler reference. - -The PSSM3 stage now also supports colour shadows in addition to depth shadows. Colour shadows are automatically used for `PCT_BYTE` texture formats. -Since 13.3, the PSSM3 stage supports the "Reversed Z-Buffer" RenderSystem option. -Since 13.5, the PSSM3 stage respects other, non shadow-casting, lights so you can add a spot-light to simulate a flashlight. - -### PBR Material support (since 13.3) - -The RTSS can now be used to create a PBR pipeline. To enable it via material scripts, specify - -```nginx -rtshader_system -{ - lighting_stage metal_roughness texture Default_metalRoughness.jpg -} -``` - -The parameters are expected to be in the green and blue channels (as per glTF2.0) and lighting will be done according to the [Filament equations](https://google.github.io/filament/Filament.md.html#materialsystem). - -Alternatively, you can use material-wide settings, by skipping the texture part like: - -```nginx -rtshader_system -{ - lighting_stage metal_roughness -} -``` - -Here, metalness is read from `specular[0]` and roughness from `specular[1]`. - -Since 13.6, additionally indirect, image based lighting (IBL) can be used. It can be enabled by also adding - -```nginx -image_based_lighting texture ibl_cubemap.ktx -``` - -Where `ibl_cubemap.ktx`, is a cubemap texture. -For best results, it should be generated with the [cmgen tool](https://github.com/google/filament/tree/main/tools/cmgen) from the filament project. - -## Terrain - -Since 13.6, `TerrainMaterialGeneratorA` internally uses the RTSS to generate shaders. This allows you to use the RTSS SRS to customize the terrain appearance. -The API to configure this is `TerrainMaterialGeneratorA::getMainRenderState()`. This way you can enable multiple light support for the terrain or switch to PBR lighting equations. - -## DotScene -The Plugin now supports exporting via a generic `SceneNode::saveChildren` API. This allows you to dump your dynamically generated Scene to file and later inspect it with ogre-meshviewer, which also got improved .scene support. - -## D3D11 -Shader interfaces/ subroutines are no longer available. They were cumbersome to use, while adding overhead to all rendersystems. - -Constant buffers are now fully supported, so if you write `cbuffer Foo` in HLSL, you get the data that you declared previously as `shared_params Foo` in your Ogre material script. - -## GL3Plus -Atomic buffers are no longer supported. They were only partially implemented, while being cumbersome to use and adding overhead to the core loop. SSBOs offer the same functionality, while proving a convenient API. - -Separate shader objects are now used by default, if available. This enables an improved shader parser using the GL introspection API and allows mixing GLSL and SPIRV shaders. - -## D3D9 - -The Option "Multi device memory hint" was renamed to "Auto hardware buffer management" as it is generally enables memory recovery on device loss. - -Since 13.2.1 there is support for `PF_DEPTH16` textures, which can be part of a MRT too. - -Since 13.3, the first 4 textures are shared between vertex and fragment programs. Explicitly stating BindingType for vertex textures fetch is no longer needed. - -## Vulkan (since 13.2) - -The RenderSystem does not yet support all of Ogre features, but many common use-cases are already covered. There are two caveats though: - -1. *Buffer updates*: Ogre does not try to hide the asynchronicity of Vulkan from the user and rather lets you run into rendering glitches. The solution here is to either implement triple-buffering yourself or discard the buffer contents on update (`HBL_DISCARD`), which will give you new memory on Vulkan. -2. *Rendering interruption*: Closely related to the above is rendering interruption. This means that after the first Renderable was submitted for the current frame, you decide to load another Texture or update a buffer. Typically, it is possible to schedule your buffer updates before rendering kicks off. Additionally, this improves performance on tile-based hardware (mobile). - -Since 13.5, the Vulkan Memory Allocator is used for improved memory management. - -## GLSLang Plugin - -This new Plugin enables Ogre to automatically compile GLSL shaders to SPIRV that in turn will be loaded by GL3+. -This means you can now easily use the Khronos reference compiler instead of what your driver would do - similar to how things work on D3D11. - -## Bullet Component (since 13.4) - -btOgre was moved into Ogre as the Bullet Component. This allows you to just build it as part of Ogre on one hand and on the other hand this ensures that it is integration tested by our CI. - -## RsImage Codec (since 13.6) - -This new Codec internally uses image-rs to load the various formats, which are all implemented in Rust and thus provide memory safety. -Unfortunately, currently the Rust implementation is slower than the highly optimized C libs that have been around for decades. - -## HLMS -The component was removed. The RTSS or just plain shaders in Ogre materials are a better way forward. \ No newline at end of file diff --git a/Docs/14-Notes.md b/Docs/14-Notes.md deleted file mode 100644 index cdad852bb98..00000000000 --- a/Docs/14-Notes.md +++ /dev/null @@ -1,157 +0,0 @@ -# New and Noteworthy in OGRE 14 -This is only a high level overview. For detailed changes, see the git changelog. - -## Core changes -Following the removal of `UTFString` in Ogre 13, the generic data structures `AnyNumeric` and `HashedVector` were removed in order to reduce code complexity. -If you were using them, consider copying the code from Ogre 13 into your project. - -The option to store tangents with `TEXCOORD` semantic was removed. The `TANGENT` semantic is now used unconditionally. - -On GL, D3D11 and Vulkan VertexWinding is set in terms of FrontFace, so `gl_FrontFacing` and `SV_IsFrontFace` now behave as expected. - -Object space bones are now enabled by default. Use `MeshManager::setBonesUseObjectSpace(false)` to go back to old behaviour. - -All builtin Factory classes were made private. Replace `DefaultSceneManagerFactory::FACTORY_TYPE_NAME` by `SMT_DEFAULT` and e.g. `ManualObjectFactory::FACTORY_TYPE_NAME` by `MOT_MANUAL_OBJECT`. - -Since 14.1, `ACT_MATERIAL_LOD_INDEX` is available to implement multiple material LOD levels in a single shader. - -### OgreUnifiedShader.h - -Sampler definitions now implicitly include the `uniform` keyword to support Vulkan; i.e. this will generate an error: - -```cpp -uniform SAMPLER2D(sampler, 0); -// with Ogre 14 use: -SAMPLER2D(sampler, 0); -``` - -You opt-in to this syntax with Ogre 13, by defining `USE_OGRE_FROM_FUTURE` before including `OgreUnifiedShader.h`. - -### Task-based WorkQueue - -The WorkQueue API was changed from request/ response style to a task-based style. -I.e. instead of sending messages between threads, the actual work is send as a callback. - -Or speaking with code, whereas before you would do: -```cpp -Root::getSingleton().getWorkQueue()->addRequest(mWorkQueueChannel, WORKQUEUE_DERIVED_DATA_REQUEST, data); -``` - -With the new API you do: -```cpp -Root::getSingleton().getWorkQueue()->addTask( - [this, req]() - { - auto req = new WorkQueue::Request(0, 0, data, 0, 0); - auto res = handleRequest(r, NULL); - Root::getSingleton().getWorkQueue()->addMainThreadTask([this, res]() { - handleResponse(res, NULL); - delete res; - }); - }); -``` - -the new version might seem more lengthy, but actually it requires less code, while being more explicit. -There is neither a request handler nor a response handler interface that you must implement. -Also the WorkQueue-channel concept is gone. -Ultimately, the Request and Response classes are not necessary either and are here for illustrative purposes. - -At this, the custom ticketing mechanism of `ResourceBackgroundQueue` was replaced by the more modern use of `std::future`. -So where you would previously do: -```cpp -Ogre::WorkQueue::RequestID ticket = rbq.prepare(tex->getCreator()->getType(), tex->getName(), tex->getGroup()); -... -rbq.isProcessComplete(ticket); -``` -you now do: -```cpp -auto future = rbq.prepare(tex); -... -future.wait_for(std::chrono::milliseconds(0)); -``` - -### Transparent objects are now on their own render queue - -Transparent objects are now put on the `RENDER_QUEUE_TRANSPARENTS` queue, which is rendered after `RENDER_QUEUE_SKIES_LATE`. -This fixes compatibility with late sky rendering, but more importantly makes transparent objects easily accessible from compositor scripts. - -This simplifies many advanced algorithms, such as deferred shading, where you want to render transparent objects after the opaque ones. - -### Breaking non-API changes - -The second argument of `RenderQueueListener::renderQueueStarted` now contains the current camera name and hence is always non-empty. - -## Rectangular Area Lights (since 14.1) - -A new spot light type `LT_RECTLIGHT` has been introduced along with the `setSourceSize` method, enabling the rendering of rectangular area lights. In order to process this light type in your shader, verify that the `spotlight_params.w` autoparam is equal to 2. Then, `spotlight_params.xyz` contains the light width in the view space, and `light_attenuation.xyz` contains the light height. - -## Python - -The double `ImGui` namespacing in `Ogre.ImGui` enums was removed; e.g. `ImGui.ImGuiWindowFlags_NoTitleBar` is now `ImGui.WindowFlags_NoTitleBar`. -Since 14.1, `Checkbox` and multidimensional input (e.g. `ColorEdit3` `InputFloat2`) are correctly wrapped. - -Since 14.1, primitive types like `Ogre.Vector3`, `Ogre.ColourValue` etc. behave like Python sequences and can be used with `len()` and expanded `myfun(*Ogre.Quaternion())`. -Additionally, `Ogre.Degree` can be transparently used where `Ogre.Radian` is required. - -## RTShader System - -The PSSM3, TriplanarTexturing and GBuffer sub-renderstates are now only configurable through the generic `setParameter()` method. - -Light types are now dynamically handled inside the shader. Shader recompilation is no longer required when changing the light type. -Consequently, the `light_count` property now only takes a single count instead of a count per light type. - -The default (FFP) sub-renderstates are now added to the scheme render state first instead of last. This means that you can inspect and modify them in the scheme render state. - -The normal maps should now be specified at the `texture_unit` level instead of the `pass` level - -```nginx -// with Ogre 13 -pass -{ - rtshader_system - { - lighting_stage normal_map Panels_Normal_Tangent.png tangent_space 0 RTSS/NormalMapSampler - } -} - -// with Ogre 14 -pass -{ - texture_unit - { - texture Panels_Normal_Tangent.png - sampler_ref RTSS/NormalMapSampler - rtshader_system - { - normal_map tangent_space - } - } -} -``` - -Additionally `parallax_occlusion` mapping is now supported by using the respective keyword. It is also available with the Terrain Component. - -## Terrain - -The TerrainMaterialGenerator API was simplified by making the use of a Profile optional. -Furthermore, the required TerrainLayer metadata was reduced to a minimum. -If you have a custom `TerrainMaterialGenerator`, you will need to update it. - -## Bullet - -A separate `CollisionWorld` wrapper was split off from `DynamicsWorld`, enabling the use of Bullet for collision detection only. - -## MeshLodGenerator - -The MeshLodGenerator now also support line primitives and correctly handles the boundaries between SubMeshes. The latter needs to be explicitly enabled, as it increases LOD generation time and is not required, if only a single submesh is used. - -## MeshUpgrader - -The interactive mode has been removed. Edge lists are no longer generated by default. Pass `-el` to generate them. - -## GL3Plus - -Transform feedback outputs are now consistently named `xfb_position`, `xfb_uv0` instead of `oPos`, `oUv0`. -Shader updates are required. - -On OSX, `texture2D` etc. functions are no longer implicitly upgraded to version 150 equivalents, explicitly `#include ` to get them. diff --git a/Docs/CMakeLists.txt b/Docs/CMakeLists.txt deleted file mode 100644 index c8a91dc66cd..00000000000 --- a/Docs/CMakeLists.txt +++ /dev/null @@ -1,71 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -############################################################### -# Install documentation -# Build API docs, if doxygen is available -############################################################### - -# Set docs target directory -if (NOT OGRE_DOCS_PATH) - if (WIN32 OR APPLE) - set(OGRE_DOCS_PATH "Docs") - elseif (UNIX) - set(OGRE_DOCS_PATH "share/doc/OGRE") - endif () -endif () - -# Build and install API documentation if doxygen is available -if(DOXYGEN_FOUND) - if (OGRE_INSTALL_DOCS) - install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ - DESTINATION ${OGRE_DOCS_PATH} - PATTERN ".hg" EXCLUDE - PATTERN "src" EXCLUDE - ) - endif () - - file(GLOB TUTORIALS ${PROJECT_SOURCE_DIR}/Docs/src/tutorials/*.md) - file(GLOB BASIC_TUTORIALS ${PROJECT_SOURCE_DIR}/Docs/src/tutorials/basictutorials/*.md) - file(GLOB COMPONENTS ${PROJECT_SOURCE_DIR}/Components/*/include) - file(GLOB PLUGINS ${PROJECT_SOURCE_DIR}/PlugIns/*/include) - - set(CMAKE_DOXYGEN_INPUT_LIST - ${PROJECT_SOURCE_DIR}/OgreMain/include - ${COMPONENTS} - ${PLUGINS} - ${PROJECT_SOURCE_DIR}/PlugIns/PCZSceneManager/docs/readme.md - ${PROJECT_SOURCE_DIR}/PlugIns/DotScene/README.md - ${PROJECT_SOURCE_DIR}/RenderSystems - ${BASIC_TUTORIALS} - ${PROJECT_SOURCE_DIR}/Docs/src/apimainpage.md - ${PROJECT_SOURCE_DIR}/Docs/src/manual.md - ${PROJECT_SOURCE_DIR}/Docs/src/ogre-shadows.md - ${PROJECT_SOURCE_DIR}/Docs/src/scripts.md - ${PROJECT_SOURCE_DIR}/Docs/src/material-scripts.md - ${PROJECT_SOURCE_DIR}/Docs/src/high-level-programs.md - ${PROJECT_SOURCE_DIR}/Docs/src/particle-scripts.md - ${PROJECT_SOURCE_DIR}/Docs/src/hardware-buffers.md - ${PROJECT_SOURCE_DIR}/Docs/src/rtss.md - ${PROJECT_SOURCE_DIR}/Docs/src/instancing.md - ${PROJECT_SOURCE_DIR}/Docs/src/resourcemanagement.md - ${PROJECT_SOURCE_DIR}/BuildingOgre.md - ${TUTORIALS}) - string(REPLACE ";" " \\\n" CMAKE_DOXYGEN_INPUT_LIST "${CMAKE_DOXYGEN_INPUT_LIST}") - configure_file(${OGRE_TEMPLATES_DIR}/html.cfg.in ${PROJECT_BINARY_DIR}/html.cfg) - add_custom_target(OgreDoc COMMAND - ${DOXYGEN_EXECUTABLE} ${PROJECT_BINARY_DIR}/html.cfg - DEPENDS ${PROJECT_BINARY_DIR}/html.cfg - WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/Docs/src/ - COMMENT "Building documentation" VERBATIM) - file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/api/) - if (OGRE_INSTALL_DOCS) - install(DIRECTORY ${PROJECT_BINARY_DIR}/api DESTINATION ${OGRE_DOCS_PATH}) - endif() -endif() diff --git a/Docs/ChangeLog.md b/Docs/ChangeLog.md deleted file mode 100644 index 72407519ece..00000000000 --- a/Docs/ChangeLog.md +++ /dev/null @@ -1,716 +0,0 @@ -# Change Log - -## v1.10 and newer -See "New and Noteworthy" for each release - e.g. [1.10-Notes.md](1.10-Notes.md) - -## v1.9.0 [Ghadamon] (22 November 2013) - MAJOR RELEASE -* [Change log in the Ogre3D wiki](https://wiki.ogre3d.org/tiki-index.php?page=GhadamonNotes) -* [Closed JIRA tickets for Ogre 1.9](https://ogre3d.atlassian.net/issues/?jql=fixVersion%20in%20%28%221.9.0%22%2C%20%221.9.0%20RC1%22%2C%20%221.9.0%20RC2%22%29%20AND%20status%20in%20%28Resolved%2C%20Closed%29%20ORDER%20BY%20key%20DESC) - -## v1.8.1 [Byatis] (02 September 2012) - MAINTENANCE RELEASE -
    -
  • [GLES2] Add missing shader for skeletal sample
  • -
  • Fix crashes in OS X template code.
  • -
  • [OS X] Resolve some issues with visibility of symbols preventing universal builds.
  • -
  • [GLES] Improvements to pixel format selection. Reduces conversions at runtime and enables more formats.
  • -
  • Fix a couple defines in GLEW headers that I mistakenly altered during a batch replace. Resolves issues with FSAA on Windows using OpenGL
  • -
  • Disabling X11 check for all Apple platforms. Because it may not always be available on the system.
  • -
  • Fix a bug with OctreeNodes that are not in the scene graph being updated improperly. As reported in viewtopic.php?f=4&t=70617&p=461051
  • -
  • Patch 3517455 - Rename the COPYING file due to CPack not allowing files without extensions.
  • -
  • Patch 3526568 - Fix for when a listener object unreferences itself from the listened object while in a callback
  • -
  • Patch 3525902 - SceneManager - Fix for when a listener object unreferences itself from the listened object while in a callback
  • -
  • Bug 521 - Copy the flag to control auto edge list building when cloning a mesh.
  • -
  • Bug 532 - Default values not being returned on invalid input to StringConverter::parse* functions
  • -
  • Patch 3519819 - Add missing setRenderQueueGroupAndPriority functions to ParticleSystem and BillboardParticleRenderer.
  • -
  • OS X - Fix the "invalid drawable" error that pops up in the log when a window is created.
  • -
  • Patch 3324815 - Fix incorrect zip archive behavior. This also fixes a few of our unit tests.
  • -
  • Add a missing capabilities mapping
  • -
  • Fix up the Xcode 4 template
  • -
  • iOS: Fix crash caused by missing GL function pointers with GLES 2 on iOS 4
  • -
  • Revert part of a change that I made several months ago that was causing problems with texture shadows without edge lists.
  • -
  • Bug 538 - Support for boost 1.50
  • -
  • Bug 536 - Freetype 2.4.10
  • -
  • Fix [3538257]: Listener was never actually removed in SceneManager::removeListener
  • -
  • added check for icon existance in bool GLXGLSupport -
  • -
  • Made SimpleRenderable::setMaterial virtual. -
  • -
  • [OS X] Use the path from the FindCg script to create the framework symlink instead of assuming the prebuilt dependencies are being used.
  • -
  • Add a missing semicolon that has been causing some compile errors when using boost for threading.
  • -
  • Moved call to wglShareLists before call to wglMakeCurrent to help Wine emulation
  • -
  • [D3D9] Catch texture load exception in D3D9Texture::notifyOnDeviceCreate to prevent Ogre from crashing when moved to a new display
  • -
  • [Papercut] Resolve ambiguity of get/setUserAny in InstanceBatch
  • -
  • Fix [3545669]: Submesh operation type is not passed to tangent calculator causing triangle strips and fans to have improper tangents
  • -
  • Fix [3542148] Properly set texture coordinate index in D3D9 if vertex program is used with projective texturing
  • -
  • Fix [3538259]: Use _tempnam on Windows to generate temporary file name in OgreDeflate.cpp
  • -
  • Fix [3535939]: In CompositorInstance::getTargetForTex search also for referenced texture name if referencing another compositor's texture
  • -
  • [3531905] Fix a bug in LOD generation of XSI exporter
  • -
  • [3531904] Update FindSoftimage.cmake to find Softimage 2013
  • -
  • Applied and enhanced masterfalcon's patch to prevent BillboardChains from - updating their vertex buffer except when they are actually being rendered.
  • -
  • Fixed ParticleSystem's emitted emitters 'sputtering' when emission rate per frame near 1/2.
  • -
  • Fix [522]: D3D9 / D3D11 destroyRenderTarget caused dangling pointer inside RS's
  • -
  • Fix [504]: D3D9 Prevent infinite loop when CheckDeviceMultiSampleType fails when - fsaa is 0
  • -
  • Fix [454]: D3D9 add more error details when we can not create a vertex shader
  • -
  • [3484580] Fix a potential crash when loading materials referencing non-existent shadow caster/receiver materials
  • -
  • Increased size of GLX config dialog to accomodate for additional GL RenderSystem option
  • -
  • TerrainGroup did not pass along parameters to underlying Terrain in update and updateDerivedData
  • -
  • Fix [541]: In Rev 3513 the warning texture is created with a invalid context so - the gl id was 0 - this broke materials without valid textures (if no texture is - bounded the warning texture is bound)
  • -
  • Fix for possible endless loop if requesting max number of mipmaps with 0 depth. Affects all GL render systems.
  • -
  • Fixed -msse flag when building with MinGW.
  • -
  • [OS X] Fix displaying garbage on first frame when using Cocoa windows. - Also fixing the "invalid drawable" error.
  • -
  • Fix incorrect header guard.
  • -
  • Replace an ugly hack for GCC that was trying to force 16-byte stack alignment in OgreOptimisedUtilSSE, but causes trouble with recent GCC versions
  • -
  • GLES/GLES2 move error checks into the right place
  • -
  • Fixed bug: D3D9 can now be compiled in static with MinGW.
  • -
  • Get PlayPen and VTests running with static builds like iOS. Also some minor code cleanup.
  • -
  • Patches 3506252 & 3535295 - Profiler enhancements and support for GPU profile events.
  • -
  • Fix [541]: viewportDestroyed were never called
  • -
  • Fix a crash when starting/stopping the terrain sample with shadowing enabled. House entities need to be freed.
  • -
  • Fix [549]: When ogre is compiled with profiler support link dx9 to dx11 so we can - use D3DPERF_BeginEvent/D3DPERF_EndEvent/D3DPERF_SetMarker - Fix some profiler crashes
  • -
  • Bugfix: Instancing LOD distance strategy was considering entities that were not in the scene. - Bugfix: Instancing LOD distance strategy was using very inaccurate distance formula.
  • -
  • Bug 545: ScriptLexer is counting \r\n as 2 newlines
  • -
  • Patch 3505652 - Fix for compositors recompiling every frame
  • -
  • Patch 3489471 - Entity LOD animation bugfix
  • -
  • Fixed a bug in the CMakeLists.txt that would cause an error when the user - influences CMAKE_CXX_FLAGS manually in CMake.
  • -
  • [GLES2] Attempt to resolve the isAttributeValid crash when shaders are either missing or have failed to compile/link. Also do a little more logging when reporting compile errors.
  • -
  • Calling removeInstancedEntity on the same InstancedEntity more than once will now raise an exception.
  • -
  • [iOS] Remove old GCC define to disable thumb and use a compiler flag instead. More reliable across gcc and clang.
  • -
  • Make it possible to call Viewport::removeListener during viewportDestroyed event
  • -
  • [OS X] Correctly compute Cocoa window origins and fix repositioning.
  • -
  • HW-Instancing: Add support for meshes which use a shared vertex buffer
  • -
  • Fixed the NaCl compile and link for the latest code changed in 1.8
  • -
  • Fixed texture loading issues in GLES2 RS for NaCl.
  • -
  • Changed RenderSystems on Windows to interpret externalWindowHandle and parentWindowHandle parameters as size_t instead of unsigned int, which has the wrong size on 64bit platforms
  • -
  • Fix Unity builds for OSX (SampleBrowser did not compile)
  • -
- - -## v1.8.0 [Byatis] (25 May 2012) - MAJOR RELEASE -There have been well over 1000 commits since the release of v1.7.0. The following list -shows only the highlights of new features. - -
    -
  • Platform support -
      -
    • iOS -
        -
      • Use the device's screen size to determine the default screen size on iPhone OS platforms.
      • -
      • Profiling showed that aligning loops on iPhone would be a good thing.
      • -
      • iOS: Changing OGRE_PLATFORM_IPHONE to OGRE_PLATFORM_APPLE_IOS
      • -
    • -
    • NaCl -
        -
      • Added NaCl platform support
      • -
    • -
  • - -
  • Render systems -
      -
    • GLES2 render system -
        -
      • Added GLES2 render system.
      • -
      • Uses the RT shader system for fixed-function emulation.
      • -
    • -
    • D3D9 render system -
        -
      • Hardware buffers system memory consumption reduced. Only write only access buffers allocates extra memory.
      • -
      • Fixed hardware buffer lock crashes when locked with read_only flag.
      • -
      • Fix hardware buffers crash when used create on active device policy.
      • -
      • Only default pool hardware buffers are re-created after device reset (Should fix resizing issues)
      • -
      • Added new config option related to system memory usage when multiple devices involved.
      • -
    • -
    • D3D11 render system -
        -
      • Removed the obsolete shader generator (Now that we have the RTSS – we don’t need it anymore).
      • -
      • A number of the Ogre samples now work with the D3D11 render system.
      • -
      • Added code to support copy of vertex buffers that where allocated in system memory. (The terrain sample does such a copy).
      • -
      • DX 11 Stream Out support (along the lines of the existing GL support).
      • -
      • texture2d-array support added
      • -
      • Various improvements.
      • -
    • -
  • - -
  • Components -
      -
    • Terrain component -
        -
      • Patch 2951501: allow changes in terrain size in vertices and world size on the fly
      • -
      • Support for Terrain vertex compression.
      • -
      • Terrain now defaults to saving compressed files (can still load uncompressed)
      • -
    • -
    • Real-Time Shader System (RTSS) -
        -
      • Added layered blending. Added an entity that shows the feature to the RTSS sample - a rock wall with the OGRE logo blended with the new "overlay" blend.
      • -
      • Blending modes for GLSL ES.
      • -
      • Added Hardware skeleton animation in RTSS - A patch by Mattan F.
      • -
      • Added instanced viewports.
      • -
    • -
  • - -
  • Additional updates (highlights only) -
      -
    • Fixed/silenced a number of compiler warnings on all platforms.
    • -
    • Patch 2942638: allow Mesh to have infinite and null AABBs.
    • -
    • D3D10 render system removed – the system is obsolete and all of its functionality exists in the D3D11 render system.
    • -
    • Remove TerrainSceneManager - no longer supported, use Components/Terrain instead.
    • -
    • Patch 2952444: support float1-4, short1-4, colour and ubyte4 in texture coordinates in XML converter
    • -
    • Patch 2955902: Add Grid3DPageStrategy for space scenes or similar
    • -
    • Patch 2963105: Add ability to set depth clear value on viewport
    • -
    • Added DeflateStream for compressing / decompressing regular streams
    • -
    • Support normals in vertex animation
    • -
    • MeshUpgrader can now also *downgrade* mesh files with the -V option
    • -
    • RenderWindows can now be hidden (useful for creating an invisible primary renderwindow).
    • -
    • Add vsync adjustment options to RenderWindow
    • -
    • Added new InstanceManager (see http://www.ogre3d.org/forums/viewtopic.php?f=4&t=59902)
    • -
    • Ogre can now run on Ubuntu in a VirtualBox.
    • -
    • Added optional shader cache feature: Compiled shaders can be saved to improve loading times.
    • -
    • Added EmbeddedZipArchiveFactory to OgreZip.
    • -
    • Fixed a number of papercuts.
    • -
    • Introduced Unity builds: Enabling OGRE_UNITY_BUILD in CMake will significantly speed up Ogre compile times. - Still considered experimental, but should be fine.
    • -
    • Add nograb command line parameter to SampleBrowser to allow debugging with gdb
    • -
    • Allow skeletal and pose animations to be relative to a keyframe of an animation instead of the binding pose
    • -
    • GSoC 2011 project: Added VisualTest infrastructure
    • -
    • GSoC 2011 project: Dual Quaternion skinning
    • -
  • -
- - -## v1.7.4 [Cthugha] (14 January 2012) - MAINTENANCE RELEASE -
    -
  • iOS: Fix the fix I did for libraries that are included in SDK builds. Use iOS 3.2 when building SDKs
  • -
  • OS X: Add visibility attributes to Cocoa classes so the symbols are exported. Apparently symbol visibility only has an effect for Objective-C on x86_64 targets.
  • -
  • OS X: Fix the OS X build
  • -
  • Bug 443: Small fix for Image::setColourAt
  • -
  • GL: Fix for a couple old bugs that could cause lots of GL errors. One is an assumption about 2 sided stencil support always being there. The other related to the wrong enumerations being used for the extension that we are checking. See relevant forum topic.
  • -
  • Missing D3D9 Software vertex processing fix
  • -
  • Xcode templates update
  • -
  • Adding RTShaderLib files to Xcode templates
  • -
  • OS X: Fix for input issues on Lion. NSTitledWindowMask is no longer implied when creating a NSWindow. To fix, we just add it to the style mask that we use.
  • -
  • iOS: The Dynamic Texture sample works. It should be enabled.
  • -
  • Add a forward slash to the beginning of paths in the Xcode 4 templates to workaround a weird bug in the template wizard that eats up any leading slashes in text fields
  • -
  • GLES: A little cleanup and fixed GL errors when using BGRA textures.
  • -
  • Fix the incorrect average and max FPS entries in SDK trays.
  • -
  • The Xcode 4 templates will need to link to the CoreGraphics framework now.
  • -
  • OS X: FSAA was not being applied to the both Carbon and Cocoa contexts at all.
  • -
  • Updated FindOGRE.cmake to properly set OGRE_${COMPONENT}_BINARY variables with paths to the corresponding DLLs
  • -
  • Updated FindTBB.cmake to correctly identify the version of Visual Studio used
  • -
  • Consider OGRE_LIB_DIRECTORY when setting RPATH for SampleBrowser and OctreeZone plugin
  • -
  • Fix D3D9 capabilities check for cubemaps
  • -
  • Fixed a memory leak in InstancedGeometry
  • -
  • Fix Boost license file location in CMake
  • -
  • Fix definition of element extremes in ogremeshxml.dtd
  • -
  • Have D3D9 rendersystem clean up properly when creating a renderwindow fails
  • -
- -## v1.7.3 [Cthugha] (08 May 2011) - MAINTENANCE RELEASE -
    -
  • iOS: Remove the animation timer. Since DisplayLink is used by default now, this only hurts performance of things like input.
  • -
  • Some small changes to ensure that the terrain and paging libs are added to linker flags for SDK sample builds.
  • -
  • Consider weight when scaling in AnimationTracks
  • -
  • Only allow to set custom render capabilities before RenderSystem is fully created
  • -
  • iOS: Fix to prevent absolute paths from being inserted into resources.cfg for iOS to fix running the sample browser on devices.
  • -
  • OS X: The Cocoa view has no use inside the main library. Moving into the GL Rendersystem where it is actually used.
  • -
  • OS X: Disabling CoreGraphics error checking by default
  • -
  • OS X: 64 bit Cocoa support. New dependencies are also available to download. Fixed a few uninitialized variables along the way. Also updated GLEW to the same version as in default, the older version had some Apple specific bugs that needed to be resolved.
  • -
  • Several fixes for the Xcode templates such as: file permissions for the installer, iOS device orientation.
  • -
  • Adding Cocoa window event handling. Plus several other fixes for parameter parsing and other things. Thanks to jdiogo for finding the bugs.
  • -
  • OS X: Build fix when targeting 10.5 or earlier.
  • -
  • OS X: A few fixes for Cocoa windowing. Now plays nicer with externally created windows.
  • -
  • Clean up several warnings(hidden local variables, unused functions)
  • -
  • iOS: Fix orientation change support. Use UISupportedInterfaceOrientations in your apps info property list to restrict which orientations are supported by your application.
  • -
  • Fix a couple comment typos
  • -
  • GLES: Disable ENABLE_GL_CHECK, again.
  • -
  • GLES: Fix for images with custom mipmaps. The dimensions were never being reduced for each mipmap level. As a side effect, memory usage is also reduced.
  • -
  • iOS: IOKit isn't needed at all and causes link errors with iOS 4.2.
  • -
  • Separate out all the OS X and iOS specific code from SampleBrowser.cpp. It was getting a bit unruly and difficult to maintain
  • -
  • iOS: Improve orientation support. Separate EAGLView into its own files.
  • -
  • iOS: Several fixes to the Xcode templates regarding viewport orientation and some cleanup for readability.
  • -
  • Patch 3116577: Plane equality operators. Also cleaned up some documentation.
  • -
  • Fix a catch-22 that prevented OGRE_BUILD_PLATFORM_IPHONE from showing up in CMake-Gui.
  • -
  • Fixed an incorrect error message in the Terrain component.
  • -
  • Do not offer the Carbon API option in 64-bit Mac builds and default to Cocoa
  • -
  • Allow the retrieval of NSOpenGLContext and NSOpenGLPixelFormat easily in OSXCocoaWindow
  • -
  • Specify the NSOpenGLFPAScreenMask to resolve ambiguity in the pixel format on multiple display systems
  • -
  • In OSXCocoaWindow::createWindowFromExternal, don't force the window to be made key and ordered in front. As an external window, the calling application should have full control over window behaviour.
  • -
  • When creating an external window in Cocoa, don't centre the window (app should be in charge of that) - Also don't mess with the first responder.
  • -
  • Fix using multiple Cocoa windows with Ogre. - Previously the window delegate was incorrectly listening in on the events of *every* window, not just the one containing Ogre. This meant if the application had more than one window (Ogre or otherwise), the Ogre windows would get confused with all the events from different windows. - Fix this by making sure each delegate only attaches to the NSNotifications of the specific window it's concerned with.
  • -
  • Support getCustomAttribute() on Texture, only GL extracts anything interesting so far but more can be added - This is pretty much essential if you want to get to internal API data for resource sharing without down-casting, which itself requires otherwise unnecessary linking to plugins. It's why we've offered this for RenderWindow etc in the past, I'm not sure why it's never been done for Texture. - Also support retrieving the FBO ids directly from render targets on GL (already allowed retrieval of FBO struct but again that requires linking)
  • -
  • Added support for spotlight_viewproj_matrix_array GPU parameter
  • -
  • Changed DataStream::getAsString and MemoryDataStream constructors to deal with streams of unknown size
  • -
  • [Papercut] Add destroyRenderTarget function to Ogre::Root
  • -
  • Fix a problem with using some of the lower-level renderable callbacks such as RenderObjectListener to alter shader parameter state - mGpuParamsDirty would not be updated to reflect this and as such things like manual param variances within light iteration loops would not be propagated. - Allow user to mark GPU params dirty themselves to resolve this.
  • -
  • iOS: Rework some of the sample browser code to shut down properly on iOS
  • -
  • GLES: Use the correct GL type for BGRA textures
  • -
  • OS X: Use correct pixel format attribute name for specifying FSAA in Carbon windows.
  • -
  • GL: Only bind up to the max supported number of render targets since not all implementations support 8. This prevents a few OpenGL errors.
  • -
  • iOS: Clean up the FSAA/framebuffer code in swapBuffers. This should resolve issues on iOS 4.1 that have been reported. Bug #384
  • -
  • iOS: Don't search for X11 if building for iOS. I'm surprised that this hasn't been found until now. Apparently most devs have the X11 package installed.
  • -
  • iOS: 2 fixes. The compiler should be g++ instead of gcc and switching the architecture to build for both armv6 and armv7.
  • -
  • OS X: A few CMake fixes to ease building for universal libraries. Upping the minimum OS to 10.5(it's required for x86_64). Also updating the list of Boost versions to be current.
  • -
  • Don't apply visibility settings to statically built samples. Fixes linking problems with Xcode 4 and iOS. (Backporting to 1.7)
  • -
  • Remove a GL ES 2 reference in the 1.7 branch
  • -
  • iOS: The meaning of ARCHS_UNIVERSAL_IPHONE_OS changed in Xcode at some point to just armv7. Changing it to Standard will compile for both armv6 and armv7.
  • -
  • OS X: A few small tweaks for Cocoa windows. Clearing the framebuffer right away, fixing multisampling for example
  • -
  • iOS: Let's pretend that the iOS simulator doesn't have SSE. (Works around a Xcode 4 bug)
  • -
  • OS X: Add support for 8 FSAA samples
  • -
  • Update the boost versions to look for.
  • -
  • Patch 3153910 - Fix a typo in MovableObject::setRenderQueueGroupAndPriority. Render queue priority should be set to the priority argument, not the queue ID.
  • -
  • Patch 3221772 - iOS: Fixed bug in setting up the viewport if the lower-left corner is not 0,0.
  • -
  • RTSS: Fix the "Disco" effect in the Shader Sample on OS X. Thanks to Wolfmanfx!
  • -
  • Fix a documentation spelling error in 2 places
  • -
  • Patch 3046729 - Improvements on previous ProgressiveMesh patch. "Sometimes it seems to be actually desired to list itself as neighbor, so instead of denying this, we rather make the loop in ProgressiveMesh::PMTriangle::notifyRemoved more robust to these edge conditions."
  • -
  • GLES: Fix using PVR textures
  • -
  • OS X: Fix a crash when switching between windowed and full screen when using the Cocoa interface.
  • -
  • Bug #397: Fix the build with some versions of GCC.
  • -
  • [Papercut] Image getColourAt parameters should be type size_t, not int
  • -
  • 373 - [Papercut] Image has getColourAt but not setColourAt
  • -
  • Bug 409 - System freezes in GLPixelUtil::getMaxMipmaps when width or height is 0. Bug was reported for GL but could affect GL ES as well.
  • -
  • Reformat a little text in an exception so that it follows the format used elsewhere.
  • -
  • Bug 374 - [Papercut] PixelBox should have getColourAt and setColourAt
  • -
  • Bug 365 - [Papercut] void BillBoardSet::setMaterial (const MaterialPtr &material) is missing
  • -
  • Bug 340 - Viewport::clear() saves and re-sets the previous Viewport, even if that Viewport has since been deleted
  • -
  • Bug 344 - Add utility functions to enable/disable skybox/dome/planes instead of destroying and recreating.
  • -
  • Bug 423 - Fix for looking up for texture definitions in very complex compositor setups in getSourceForTex and getTargetForTex
  • -
  • iOS: Explicitly specify the release lib paths so that libraries are always installed to the correct places. This fixes the problem of duplicate, single architecture libraries in SDK builds.
  • -
  • iOS: Remove -fno-regmove flag to keep Clang from complaining about it.
  • -
  • Update the SDK CMakeList template
  • -
  • Several updates and fixes for the OS X and iOS SDK build scripts
  • -
  • OS X: Fix a long standing issue that often prevented 3 situations: Building with Clang, 64 bit debug builds and linking with Xcode 4. -
  • OS X: Add macAPI option to the config dialog
  • -
  • Added Gentoo install location for Cg to the FindCg.cmake script
  • -
  • Fixed a comment in OgrePixelFormat.h
  • -
  • Modified FindTBB.cmake to cope with TBB 3 paths
  • -
  • Fixed a build error with GCC 4.6
  • -
  • Xcode 4 templates and installer files
  • -
  • iOS: Normalize the case of the word Media in scripts. Simplifies a little scripting.
  • -
- -## v1.7.2 [Cthugha] (03 November 2010) - MAINTENANCE RELEASE -
    -
  • Fix bug 240: TextAreaOverlayElement incorrectly loads Font in background thread (OGRE_THREAD_SUPPORT == 2)
  • -
  • Report errors if installable DLLs missing (e.g. cg.dll)
    - Make sure OGRE_INSTALL_DEPENDENCIES always true
  • -
  • Fix Cmake error with VS 2010
  • -
  • Fixed a compile bug - in visual studio 2010 - 64 bit we get this error: "LINK : fatal error LNK1210: exceeded internal ILK size limit; link with /INCREMENTAL:NO"
  • -
  • SDK build - added vcxproj ext to the batch file - for VC10 support
  • -
  • Fix a breakage from rev 2133 on systems other than 64-bit VS 2010 - - Cannot pass a blank string to LINK_FLAGS
  • -
  • Fix an infinite loop that could occur with StringUtil::replaceAll if replaceWhat is a substring of replaceWith. Solved by advancing the string position after each replacement.
  • -
  • Make sure the correct resource path is inserted into config files when building the OS X SDK.
  • -
  • Correct the iPhone SDK disc image to use the correct background image file.
  • -
  • Patch 2979571 by moagames : textures referenced with texture_ref can now be also used as render targets. http://www.ogre3d.org/forums/viewtopic.php?f=4&t=56671
  • -
  • Dispose of Carbon window handles when the window object is destroyed. Fixes a problem with old windows remaining visible after the resolution has been changed.
  • -
  • Removed redundant compositor creation call from deferred shading demo.
  • -
  • Allow overriding Rectangle2D's vertex buffer usage, and using this in the compositor's quads. As discussed in http://www.ogre3d.org/forums/viewtopic.php?f=4&t=57656
  • -
  • fixed parsing of matrix types from shared parameter definition
  • -
  • ProgressiveMesh::PMVertex can list itself as a neighbor after collapsing vertices. This leads to a crash in ProgressiveMesh::PMTriangle::notifyRemoved. - Changed ProgressiveMesh::PMVertex::removeIfNonNeighbor to always remove itself from the neighbor set.
  • -
  • fixed destroySubMesh corrupting the mesh if it contains an edge list
  • -
  • Add OgreOverlayElementFactory.cpp for methods which can't be inlined.
  • -
  • Install ressources according to OGRE_LIB_DIRECTORY .
  • -
  • Support LIB_SUFFIX. Which is the de-facto standard for cmake to support lib64|32 systems.
  • -
  • Removing a few unused variables to lower the number of compiler warnings.
  • -
  • GLES: Fixed a crash on texture creation. Added buffer mapping support(port from GL Rendersystem).
  • -
  • Adding a few missing header search paths to the Xcode templates.
  • -
  • Adding iPhone 4's native resolution.
  • -
  • Xcode Templates: Use devices' native resolution. Shutdown properly. Add CADisplayLink support.
  • -
  • iPhone: Adding CADisplayLink support to SampleBrowser. Shutdown the app properly on iPhone and disable the loading bar to speed up loading on iOS 4
  • -
  • GL ES: 16 bit texture support.
  • -
  • OS X: When targeting 10.6 only - Fixed an issue with old framebuffer contents being displayed when using non-native resolution full screen contexts. Also fixed a crash when switching resolutions. Added some error checking to the full screen context creation.
  • -
  • Disabling DisplayLink on iPhone by default, as it can cause input lag sometimes.
  • -
  • Fix a cross-endian bug in StreamSerialiser::calculateChecksum
    - Files written on one endian system would fail checksums on another (even though the data can be converted on the fly) because the checksums were calculated on the raw memory of the header data - Now always calculate checksums in little-endian
  • -
  • Endian fix for FastHash - casting to uint16 is non-portable
    - NOTE: this will break checksums if you're on a big-endian machine using files generated before this change.
  • -
  • Fix StreamSerialiser::REVERSE_HEADER_ID which was only reverse for uint16, not the declared uint32
  • -
  • OS X: Reworked windowing to fix setFullscreen and provide more robust GL context management
  • -
  • Adding additional directories to search for the Ogre framework when using a prebuilt SDK with your own projects under OS X
  • -
  • OS X & iOS: Simplify some post build commands by using wildcards. Updating pbxcp commands to exclude .hg directories.
  • -
  • Refreshed iOS SampleBrowser icons and launch images
  • -
  • Adding new iOS higher resolution icons and launch images
  • -
  • Uncomment the use of the HideOnFullScreen attribute for Carbon windows
  • -
  • Adding the using keyword to resolve a set of warnings. Also removed a switch for a simple if-else.
  • -
  • Very minor cleanup from a bad copy/paste in Xcode template installer code
  • -
  • iOS: Several additions to properly support newer iOS devices including: High resolution screen support, FSAA and Framebuffer discard. A config key has been added to allow you to manually configure the content scaling factor. For example, if you only want 720x480 on an iPhone 4, specify contentScalingFactor=1.5.
  • -
  • iOS: Fixed the camera frustum and viewport dimensions if the device is in landscape. With this fix, the FOV and aspect ratio will be correct in all device orientations
  • -
  • Patch 3034005: GLSL writers make wrong assumptions about the precedence of the || && operators (v1-7 applicable part)
  • -
  • Patch 3034009: navigation bug in sample browser
  • -
  • Build fixes for MinGW-w64
  • -
  • (CMake) Properly determine if we are on a 64bit platform
  • -
  • Allow embedding of Dependencies source build into the Ogre source tree
  • -
  • Due to a change made in CMake 2.8.1, Xcode based projects for iPhone would be corrupted. This fixes the problem. Also, up the default SDK version to 4.0 since Apple is no longer shipping a 3.0 SDK but still supports targeting it.
  • -
  • LLVM compile fix
  • -
  • Patch 3040518: Fix link warnings when compiling Ogre with -fvisibility-hidden
  • -
  • Updated sed script to work with the CMake 2.8.1+ fix for iOS
  • -
  • iOS: Cache the system version so we don't query it every time we call swapBuffers
  • -
  • Patch 3034010: Reduce a large number of compiler warnings, particularly shadowed local variables
  • -
  • Backing out use of _OgreExport on AllocatedObject members, causes major build problems on VS
  • -
  • SceneManager::renderVisibleObjectsCustomSequence was calling firePostRenderQueues at the start instead of firePreRenderQueues (thanks Lacero)
  • -
  • Fix a script compile error introduced with the warning reduction patch
  • -
  • Fixing iOS project generation. Running fix_linker_paths.sh may no longer be necessary, especially if using CMake 2.8.1 or later.
  • -
  • Use RenderSystem capabilities to only load samples that require shaders if we support a shading language when linking statically.
  • -
  • Bugfix : Scriptcompiler would crash when a specular attribute contained one number. - As reported in http://www.ogre3d.org/forums/viewtopic.php?f=1&t=59742
  • -
  • Fix a bug in Unix FileSystemLayerImpl if resolving a symlink fails
  • -
  • Fixed animation track exporting to avoid XMLConverter to crash.
  • -
  • Avoid sending tangent related params to XMLConverter when mesh does not have UV data.
  • -
  • Materials will now fallback to Rendering Material mode when custom material template is invalid
  • -
  • Added _tex[#] handlers to material template system allowing the use of indexed base texture binding.
  • -
  • Improved material warnings for better readability.
  • -
  • Updated help document on feature additions.
  • -
  • D3D9RenderSystem: Fixed crash when HLSL compilation failed and trying to log errors but D3DXCompileShader returned a NULL pointer
  • -
  • Fixed nasty memory corruption in OgreInstancedGeometry, when building the GeometryBucket. - Discussed in http://www.ogre3d.org/forums/viewtopic.php?f=4&t=60432
  • -
  • [3061946] Fix invalid fbConfig check in GL rendersystem
  • -
  • Fix errors generated from RenderSystemCapabilitiesTests due to missing or misnamed capability keywords.
  • -
  • GLES: Use _OgreGLESExport instead of _OgrePrivate to control symbol visibility for rendersystem classes.
  • -
  • pkg-config can be used to properly build a PCZSceneManager application
  • -
  • Installing OIS dependency didn't work on RelWithDebInfo with MingW
  • -
  • [3059963] Fix a slight copy&paste error in PCZSM
  • -
  • Change required CMake version to >=2.6.2
  • -
  • [3078774] Convert home path to OEM codepage in FileSystemLayerImpl_Win32
  • -
  • [3074121] Fix handling of lights for multiple displays in D3D9 rendersystem.
  • -
  • [3032954] Properly adjust window size in D3D9 RenderSystem to get the desired client size when switching from fullscreen to windowed.
  • -
  • [3067141] Generate user files with debug paths for Visual Studio 2010
  • -
  • Change Manual & API license to Creative Commons ShareAlike v3.0. - Apparently Debian will only accept the 3.0 license and not 2.x
  • -
  • [3002754] Add OGRE_UNICODE_SUPPORT guard to OgreUTFString.cpp
  • -
  • [3072166] Fixed a crash on exit when SdkSample is initialised before Ogre::Root
  • -
  • [3053689] Terrain sample: Add Numpad +/- as alternative key bindings
  • -
  • Add threading library's include directory to Ogre include directories in FindOGRE.cmake
  • -
  • Correctly check for PBuffer support even if FBO is supported in GL rendersystem
  • -
  • [3043021] Use CMake to make sure that GCC visibility settings are passed along to Xcode.
  • -
  • [3054042] Fix for two frustums attached to one scene node. Cameras and Frustums should use the name member that they inherit from MoveableObject instead of their own.
  • -
  • [3003231] Specify default values in StringConverter::parse*
  • -
  • D3D9: RenderWindow::adjustWindow needs to take the current window style into consideration, otherwise the produced values can be off.
  • -
  • D3D9: Fixed a bug where RenderWindow and Viewport sizes would not be in sync during a windowResized event.
  • -
  • OS X: Fix use of macAPI in config files to specify Carbon or Cocoa windowing APIs
  • -
  • A fix so ogre can run on Ubuntu that runs in "VirtualBox".
    - At the date of this commit - chooseFBConfig was not supported on VirtualBox - http://www.virtualbox.org/ticket/7195
    - Now glXGetFBConfigs is uses as an alternative if chooseFBConfig fails. -
  • -
  • iOS: Build script and CMake updates for iOS 4. Fixes several project creation bugs and includes a warning about CMake 2.8.2 which cannot create usable universal Xcode iOS projects.
  • -
  • Add some error checking to the Xcode template installer to help alleviate installation problems
  • -
  • Update documentation on Bone::setManuallyControlled to mention the option of using AnimationState::setBlendMask to prevent scripted animations applying to the bone.
  • -
  • Patch 3097617: initialise mManager correctly in default hardware buffers. - Modified slightly to maintain previous interfaces & not break build
  • -
  • Apply patch 3097617 to the GL ES rendersystem too.
  • -
  • [3057434] Fix RibbonTrail reset when attached to a SceneNode not positioned at the origin
  • -
  • iOS: Guard a media dir variable update since we want to preserve the relative paths on iOS
  • -
  • Remove a couple patterns from the Boost header exclude list. Some headers in these directories are needed indirectly.
  • -
  • Add missing CMake file to list of scripts to install
  • -
- -## v1.7.1 [Cthugha] (25 April 2010) - MAINTENANCE RELEASE - -
    -
  • Terrain: Fix memory leak after updating lightmaps
  • -
  • Terrain: Ensure that imported position is used when preparing from ImportData
  • -
  • Fix calcMorphKeyframeSize in serializer - there has never been an 'isOriginalGeometry' flag!
  • -
  • Safety checks - use !mSkeleton.isNull() instead of hasSkeleton() when accessing the pointer, since hasSkeleton() determines whether the skeleton name is provided, not whether the skeleton has loaded & the pointer is valid
  • -
  • Terrain: Fix a delete that should have been OGRE_DELETE as pointed out by harkon
  • -
  • Focussed shadow camera setup dealt with extrusion of directional light volume incorrectly: -- It clipped the extrusions against the scene AABB, which may exclude casters in sparse scenes where the main camera has stopped seeing them or their shadows for a frame or more -- It should actually have been extruding the receivers AABB clipped to the camera by the shadow far distance -- Focus regions would not be affected because extrusion along the light direction does not widen the focus; in fact the use of the whole scene BB instead of just the receivers BB may have led to worse focus
  • -
  • ArchiveManager's constructor should be in source, not header, to avoid link errors if constructed from outside OgreMain (this fixes tests build on OS X) -Fix some new/deletes in tests that should have been OGRE_NEW/OGRE_DELETE
  • -
  • Mark a few more options as 'Advanced' to de-clutter the main CMake page. -Disabling zip, freeimage, dds etc is definitely an advanced function.
  • -
  • Patch 2981322 - allow OGRE_LIB_DIRECTORY to be set to install in alternate named directories such as lib64 for 64-bit Linuxes that use that convention.
  • -
  • Fix for VC10
  • -
  • Patch 2986452: avoid potential resource group change deadlocks
  • -
  • Patch 2986446: For ACT_LIGHT_POSITION_OBJECT_SPACE for directional lights, we need to use the inverse of the inverse transpose as with ACT_LIGHT_DIRECTION_OBJECT_SPACE, to deal with non-uniform scalings
  • -
  • Patch 2986441: MovableObject's queryLights and _notifyCurrentCamera didn't take account of object scaling when dealing with bounding radius
  • -
  • Patch 2986437: auto-tracking update should be after the re-entrant call to update shadow textures, otherwise old tracking state may be used
  • -
  • Fixed BillboardChain::getNumChainElements when tail < head
  • -
  • Fix loading of mesh versions 1.30 and before -They were picking up LOD loading from latest version instead of fallback in MeshSerializerImpl_v1_4 because of inheritance error
  • -
  • In Mesh::destroySubMesh, fix up SubMesh name map for the removed item
  • -
  • If group name on manual LOD level is blank, use parent mesh
  • -
  • Make PlayPen plugin work on OS X
  • -
  • Fix bug 308 according to user report - don't include _mingw.h in more recent MinGW packages
  • -
  • Fix bug 313: doc build target doesn't handle spaces in directry names
  • -
  • Fix terrain rendering on ATI/GL - no support for fp30/fp40 in latest ATI drivers but arbfp1 works
  • -
  • Terrain morphing was missing from shader when alignment wasn't x/z
  • -
  • Deal with CMAKE_OSX_ARCHITECTURES a little better: -- Selectively remove 64-bit archs (Carbon requirement) instead of manually setting "i386 ppc", so that user can still customise archs for 10.6 -- Set the default arch if none is specified (Cmake 2.8.0)
  • -
  • Patch 2977286: Fix support for scene blending operations other than SBO_ADD on Dx9 because caps were not being set
  • -
  • Patch 2979431: Matrix4::makeInverseTransform bug with non-uniform scale
  • -
  • Patch 2978035: D3D9 should send a "DeviceLost" message to app-side listeners before a device is reset
  • -
  • Deferred Shading Demo : Fixed 'is camera inside light' test for spotlights.
  • -
  • Fix problem with picking the right shader generator in TerrainMaterialGeneratorA -- Would not fall back from Cg when Cg not available (bad nesting) -- Can only use ps_2_0 when not parallax mapping
  • -
  • Fix memory leak in SharedPtr when initialised with a null pointer
  • -
  • Ensure libdl exists before linking to it
  • -
  • Fix install of tools PDBs in debug mode
  • -
  • Add test for switching full screen modes without reinitialisation
  • -
  • (Fixed commit) Applied l3fthn4d's compositor (material_scheme & shadows settings) patch as discussed in http://www.ogre3d.org/forums/viewtopic.php?f=4&t=56031
  • -
  • Fix bug 305: Entity::setMaterialName(material, group) calls SubEntity::setMaterialName(material) without group.
  • -
  • Add the rtshader materials directory to resources.cfg
  • -
  • Correct case-sensitivity issue with samples media path
  • -
  • Remove nested parenthesis, not supported on CMake 2.6 (only 2.8)
  • -
  • Explicitly include errno.h. Otherwise build errors occur if not using boost and threading is turned off.
  • -
  • Patch 2971821: Fix consistency of inclusions of OctreeSceneManager plugin (important when referenced with relative paths)
  • -
  • Patch 2971818: deal with missing MinGW header & make inclusion specific to MinGW
  • -
  • Just make sure meshes are being reloaded in LOD test
  • -
  • Added tests for manual LOD, seems to work
  • -
  • Explicitly note in the manual some directives which are irrelevant when using shaders
  • -
  • Another bad svn:eol-style property
  • -
  • Fix some bad svn:eol-style properties
  • -
  • More Xcode template work. Cleaned up warnings. Changed iPhone template to use a NSTimer to make it more reliable at high framerates. Fixed the installer path.
  • -
  • GLES 1.x patch: fix opengl es 1.1 compilation under windows - ID: 2961527. Thanks Thomas. -http://sourceforge.net/tracker/?func=detail&atid=302997&aid=2961527&group_id=2997
  • -
  • GLES 1.x render system: Replaced a printf with a log entry.
  • -
  • RTSS: Extended the normal map texture unit settings script parsing caps. -Now it can read the filtering type, max anisotropy and mip map bias.
  • -
  • Patch 2965714: CMake Infinite Loop Fix for OS X using makefiles instead of XCode
  • -
  • Patch 2968889: fix ExampleApplication loading config files in debug mode
  • -
  • Fixed some iPhone remnants of the OGRE_CONFIG_DISABLE to OGRE_CONFIG_ENABLE change
  • -
  • Implement missing wireframe and points rendering in GL ES. Also fixed a typo in a comment.
  • -
  • Doc fix
  • -
  • Fix copy & paste error that could cause crashes when unloading & reinitialising terrain
  • -
  • Fix a couple bugs in the Xcode templates. Added an option to choose separate locations for OS X and iPhone SDK's. Cleaned up the installer package a little bit.
  • -
  • Patch 2963406: Deal with negative scale in Entity::getBoundingRadius
  • -
  • Patch 2963372: Matrix4::makeTransform/makeInverseTransform inefficiencies fixed -Reduces complexity of this from 39MUL+30ADD to 18MUL+15ADD
  • -
  • Must set the OGRE_MEDIA_DIR_* to an absolute path for build folder versions
  • -
  • Patch 2959565: fix XSI exporter build
  • -
  • Fix bug 264: problem with Camera::setDirection when using non-fixed yaw and a non-identity parent node.
  • -
  • Fix bug 299: Sequence of light changes can cause crash because of light hash==0
  • -
  • Make sure linking or copying media works in non-SDK builds for OS X and iPhone
  • -
  • Mention that the default material generator requires the Cg plugin
  • -
  • Fix water sample when exiting & reentering it by making sure mesh is removed from MeshManager
  • -
  • Update Xcode templates for 1.7 final release
  • -
  • Profiler: endProfile checks group id against mask.
  • -
  • GpuProgram: Added init in the contractor to mMorphAnimation and mPoseAnimation members.
  • -
  • Fix bug 297: Incorrect use of Boost_USE_STATIC_LIBS causes boost library search to fail when trying to switch to Boost dynamic libs
  • -
  • Changes for building SDK for iPhone
  • -
  • Should delete .exe not .7z when building SDK multiple times
  • -
  • D3D9 Render System: Device multi thread flag is used now only when OGRE_THREAD_SUPPORT == 1. This will save us a few cycles in the other threading modes..
  • -
  • FindOIS.cmake fixes: -- Respect OGRE_DEPENDENCIES_DIR (useful if used outside of OGRE) -- On Win32 define names of the OIS DLLs so they can be copied from wherever they are found
  • -
  • FindOGRE.cmake fixes: -- Use OGRE_DEPENDENCIES_DIR if defined (external dependencies) -- Find media in the OGRE_SOURCE folder correctly -- Use a zip file common to 1.6 and 1.7 to detect media (OgreCore.zip doesn't exist anymore in 1.7+)
  • -
  • Compile fix for people using ExampleFrameListener
  • -
  • RTSS: Fixed Normal map point and spotlight GPU parameters that weren't update correctly.
  • -
  • Minor tweaks to the demos installer -- Nicer defaults -- License display (forced to be RTF unfortunately)
  • -
  • Enable WiX installer interface and allow the user to specify the install directory for the demos -Fix media installing -Add missing samples.cfg
  • -
  • Fixed remaining bugs for MinGW SDK and finished mingwsdk.sh
  • -
  • Fix shortcut errors in WiX setup
  • -
  • Generate WiX config files and custom task for building a demo installer on MSVC -Remove space in OGRE_VERSION before suffix, more trouble than it's worth even for display strings -demomedia.wxi.in was generated using 'heat dir Media -gg -cg OgreMedia -out demomedia.wxi.in -sfrag' on a clean Media export, then replacing SourceDir with Cmake variable
  • -
  • Fixes and enhancements for MinGW SDK generation.
  • -
  • Merged v9841 into tag since urgent change
  • -
  • Merged v9841 into tag since urgent change
  • -
  • In future, use the Windows-mode 7zip self-extractor not the default console-mode one
  • -
  • Final changes for the OS X SDK. Fixes up all the absolute paths in CMake generated files.
  • -
  • OGRE_VERSION has a whitespace and version suffix appended; this breaks builds if used as the .so version for shared libraries. Use a dedicated OGRE_SOVERSION instead.
  • -
  • RTSS: Fixed Normal map and PSSM3 GPU parameters that weren't update on object switch scenario.
  • - -
- -## v1.7.0 [Cthugha] (28 February 2010) - MAJOR RELEASE -[View changes since RC1] - -
  • License changes - -
  • Compositor changes -
    • Allow 'pooled' compositor surfaces. -
      • Separate compositor instances using the same size & format surfaces can share them, saving memory -
      • System detects the compositor instance chaining to avoid problems with interdependence -
      • 'pooled' has to be explicitly enabled on texture definitions, it is not the default because once enabled you cannot necessarily rely on being able to see all the intermediate texture results (because they can be ping-ponging across shared textures); people may be relying on this -
      -
    • Manual switching between supported compositor techniques is now possible on the fly -
      • Compositor techniques can now have 'scheme' names, you can manually switch between supported techniques using the scheme name to drop to different approaches for reasons other than hardware compatibility (performance, alternative tweaks etc) -
      • You can keep & share the textures used by previously active techniques so switching back & forth is faster (must use 'pooled' option for this). -
      -
    • Compositors can now specify if they don't want to inherit the FSAA setting from the main target for texture definitions ('no_fsaa') -
    • Compositors can now turn on sRGB gamma conversion per texture definition instead of just inheriting from the main surface ('gamma') -
    • Cross-compositor communication (from SoC2009 Compositor) -
      • Define a texture as accessible from other locations by the chain_scope or global_scope directive in the texture definition -
      • Reference a texture from a different compositor in the chain (or in general) using the texture_ref directive -
      -
    • Compositor <-> code connection improvements (from SoC2009 Compositor) -
      • It is now possible to define a custom composition pass (instead of just quad/scene/clear) in code and trigger it using the render_custom composition pass type. -
      • You can now link between a compositor and related code (for example, a compositor listener) automatically using CompositorLogics. -
      -
    -
  • SceneManager changes (from SoC2009 Compositor) - -
    • It is now possible to pause a frame's rendering mid-way (for example, during a callback called in the middle of the process) to trigger a side render and then resume rendering. See SceneManager::_pauseFrame and SceneManager::_resumeFrame. -
    • Added an option to manually trigger the updating of shadow textures for specific lights. See SceneManager::prepareShadowTextures. The combination of the two new additions allow reusing a single texture for multiple shadowmaps. -
    -
  • New Sample Browser (from SoC2009_Samples) -
    • Instead of many separate demos, we now have one integrated sample browser -
    • Samples are pluggable libraries that can be reloaded at runtime without restarting the browser -
    • A simple 'tray' system is used to make sample GUI controls easy to create -
    -
  • Antialising changes -
    • Support for Coverage Sampled AA (CSAA) - Dx9 & Dx10 only for now -
    • Unified & simplified AA settings -
      • on Root's config options the setting is now called 'FSAA' in all cases, and consist of samples and a hint string (separated by spaces) -
      • on the miscParams to createRenderWindow you can supply 'FSAA' and 'FSAAHint'. The former is the number of samples, the latter any hinting (e.g. 'Quality') -
      -
    -
  • Light changes -
    • Near/far plane settings for shadow cameras can now be manually configured per light if required -
    • You can now mask lights out per object by calling MovableObject::setLightMask - a renderable object's mask is bitwise and'ed with the light's mask and the light is excluded if the result is 0. -
    -
  • LOD changes (from Soc2008_LOD) - -
    • LOD no longer has to use distance as a metric for changing LOD levels -
    • LodStrategy can now be set on both Material and Mesh, to either Distance or PixelCount (new strategies can also be added) -
    -
  • STL container changes -
    • All STL containers now use custom memory allocators -
    -
  • Profiler changes -
    • Allow milliseconds as well as percentage view - gives a better idea of absolute fluctuations. -
    • Define profiler masks so that profiling can be added to core OGRE but still filtered out by categories (added some simple profiling to test) -
    • Hierarchy of profiles is now inclusive instead of exclusive (children no longer subtract their time from parents). This is more useful in practice when doing breakdowns -
    • Added numerical indicators instead of a scale with 'ticks' since its more useful -
    -
  • Optimisations -
    • Fixed-function light state is now handled more intelligently, leading to better performance with large numbers of objects -
    • Shader parameters are now updated more selectively, reducing unnecessary updates -
    -
  • GpuProgramParameters changes - -
    • Support added for shared parameter sets which allow you to define / update shader variables for many programs and materials in one place. See GpuProgramManager::createSharedParamerers -
    • Use shared_params, shared_param_named and shared_params_ref in scripts to define and reference shared parameter sets. -
    • Parameters are now automatically migrated when the program they are based on is changed and reloaded; any parameters which still apply are merged into the new parameters -
    -
  • Archive changes -
    • Archive now supports create and remove of files (FileSystem only implemented for now) -
    -
  • DataStream changes - -
    • Writeable data streams are now supported (FileSystem only implemented for now) -
    -
  • File handling changes -
    • New class StreamSerialiser is the new way to read & write binary chunk-based formats -
    -
  • Build changes -
    • Cmake is now used to generate project files, separate explicitly maintained build systems are being removed. See Building With CMake -
    -
  • RenderWindow changes -
    • miscParams now supports 'vsyncInterval' option, allowing you to sync to a multiple of the refresh rate if you want (and the hardware supports it) -
    -
  • Viewport changes -
    • Added clear method to manually clear any combination of colour/depth/stencil to a specified value without performing an update. -
    -
  • Image changes -
    • Added loadTwoImagesAsRGBA and combineTwoImagesAsRGBA to make it easier to construct combined normal/height and diffuse/specular images etc -
    -
  • New Paging Component -
    • SceneManager-independent, separate optional component (OGRE_HOME/Components/Paging) -
    • Pluggable strategy components to control paging strategy for a section of the scene -
    • Pluggable content components to control paging of content -
    • Plugggable collection components so that paged elements can be composed or selected between in different ways (e.g. paging many LOD levels within a page) -
    -
  • New Terrain Component -
    • SceneManager-independent, separate optional component (OGRE_HOME/Components/Terrain) -
    • Inherently editable -
    • Hierarchical geometry batching; batch counts reduce at lower LODs as well as vertex count. At the lowest level of detail, the entire terrain page is a single batch. -
    • LOD now adapts in real-time to camera settings (viewport sizes & LOD bias) so you can use the same terrain with multiple views efficiently -
    • Skirts are used instead of stitching to avoid cracks in geometry; this means fewer indexing arrangements & lower overall index buffer usage -
    • Saving & loading of terrain built in, including loading / processing in a background thread -
    • In-built support for splatting layers, configurable sampler inputs and pluggable material generators -
    • Support for generating global normal maps and light maps, in a background thread -
    -
  • New 'Real Time Shader System' (RTSS) Component -
    • Automatically generate shaders to replace the fixed-function pipeline and to add features such as per-pixel lighting, normal mapping and shadows. -
    -
  • New Property Component -
    • Separate optional component (OGRE_HOME/Components/Property) -
    • boost::bind based property system to make it easier to expose reflected properties from your objects -
    -
  • Threading changes -
    • WorkQueue added to accept generalised work items to be executed in multiple background worker threads -
    • WorkQueue starts the number of workers based on hardware, or can be told to start a different number -
    • Main Ogre WorkQueue is in Root::getWorkQueue. You can also subclass WorkQueue and provide your own if you want -
    • ResourceBackgroundQueue now uses WorkQueue instead of using its own queue and can have multiple tasks running at once -
    • New focus on data-driven, task-based parallel execution with separation of GPU and CPU activities -
    • Boost, POCO and Thread Building Blocks supported as threading back-ends (Boost preferred) -
    -
  • Resource changes -
    • ResourcePool added as a place for other application components to shelve & re-use resources -
    -
  • Material changes - -
    • scene_blend_op and separate_scene_blend_op added to passes, to change the default '+' operator between source & dest blending params -
    • Material listeners can now register to listen to a specific scheme, to allow for none-competing scheme handlers for different schemes. -
    -
  • iPhone OS port -
    • Synced GLESRenderSystem with GLRenderSystem and added some more extension detection -
    • Added support for ARM architecture and CPU feature detection -
    • iPhone OGRE SDK disc image and sdk package script -
    - -
  • OS X improvements -
    • Moved code and resources from the Mac directory to OgreMain -
    • Eliminated deprecation warnings when targeting Mac OS X 10.5/10.6 -
    • General organisation and compatibility improvements -
    -
- -Changes since 1.7.0 RC1 (highlights only) -
    -
  • Fix GPU-extruded stencil shadows on Dx9
  • -
  • Allow Terrain to have layers inserted / removed at any point in the stack
  • -
  • Fix bug 254: DXTn volume texture size calculation crash
  • -
  • Samples tidied up, and some fixes to unloading behaviour in Compositor, Instancing and VolumeTex samples
  • -
  • Many fixes to FindOGRE.cmake, now much more reliable and compatible with 1.6 and 1.7. Reference SDKs with OGRE_SDK, or source builds via OGRE_SOURCE and OGRE_BUILD paths.
  • -
  • New SDKs for Windows and OS X created
  • -
  • Fill in some missed PVRTC rendersystem caps
  • -
  • Fix resolving some types in OS X 10.5 SDK
  • -
  • Added validateConfigOptions() call in Root::restoreConfig(). Solves a crash when moving cfg file from one machine to another.
  • -
  • RTSS: some refactoring and bug fixing
  • -
  • Terrain: fixed several bugs
  • -
  • GLES rendersystem bugfixes
  • -
  • Fix Codec compile when using OGRE_STRING_USE_CUSTOM_MEMORY_ALLOCATOR
  • -
  • HashedVector::mListHashDirty was not initialised correctly in a few cases
  • -
  • Null shadow textures should not be dynamic since that means after a device lost they lost their contents, and there is no handler to manage this.
  • -
  • Prevent excessive logging when texture load failed in ensureloaded/ensurePrepared
  • -
  • Windows 64-bit compatibility fixes
  • -
  • Fix problems when using logical GPU parameter indexes which end up needing more space than originally thought
  • -
  • Fix a problem with .hdr introduced by new FreeImage
  • -
  • Fix a bug in ResourceGroupManager::loadResourceGroup when a resource changes group
  • -
  • Added a Character sample featuring the Sinbad character model.
  • -
  • Add CMake option corresponding to OGRE_PROFILING
  • -
  • Fix a large number of problems on Windows with establishing the max size of a window and switching between fullscreen and windowed modes
  • -
  • WorkQueue::addRequestHandler and WorkQueue::removeRequestHandler no longer block until existing background requests are processed, leading to better parallelism
  • -
  • Fix no grass displayed on ATI cards on GL in grass demo
  • -
  • Static build now works including all sample browser plugins
  • -
  • Fix RGBA colours in custom GLSL attributes
  • -
  • Reduce compiler warnings
  • -
  • Lots & lots of other bugfixes and tweaks!
  • -
diff --git a/Docs/CodingStandards.md b/Docs/CodingStandards.md deleted file mode 100644 index 0556332bb0a..00000000000 --- a/Docs/CodingStandards.md +++ /dev/null @@ -1,93 +0,0 @@ -# OGRE Coding Standards - -This document describes the coding standards all developers are expected to adhere to when writing code for the OGRE project. - -## Top-level organisation issues - -
    -
  1. All source files must begin with the standard OGRE copyright statement:
    // This file is part of the OGRE project.
    -// It is subject to the license terms in the LICENSE file found in the top-level directory
    -// of this distribution and at https://www.ogre3d.org/licensing.
    -// SPDX-License-Identifier: MIT
    -
  2. -
  3. All publicly visible classes should be declared in their own header file using the .h extension, placed in the `include` folder of the sub-project in question, and named after the class but prefixed with `Ogre` e.g. `OgreMyClass.h`. Only very tightly related classes should be declared in the same header file.
  4. -
  5. Headers of private classes must be placed in the `src` folder of the sub-project in question
  6. -
  7. Implementations should be placed in a source file called the same name as the class but with an extension of .cpp.
  8. -
  9. Everything must be declared inside the namespace `Ogre`.
  10. -
- -## Portablity - -
    -
  1. All code must be cross platform, ANSI C++. No dependencies on platform-specific headers and / or types are allowed (the only exception is when dealing with platform-specific features like windowing, which must be implemented for each platform separately).
  2. -
  3. If you serialise / deserialise any data, subclass from Serializer and use its methods, it will insulate you from endianness issues. If you need to serialise any types it doesn't already handle, make sure you deal with endianness issues in the same way Serializer does (ie use native endianness by default but detect the inverse on reading and perform flipping if required).
  4. -
- -## C++ Standards compliance - -
    -
  1. Always prefer the STL over custom containers / algorithms.
  2. -
  3. Always prefer C++ techniques over C. -
    • Avoid C-strings (`char*` and functions like sprintf, strcpy, use `Ogre::String`)
    • -
    • Avoid old I/O routines (fopen et al, use ``)
    • -
    • Use abstract classes or templates not `void*`
    • -
    • Use overloaded methods not varargs.
    • -
  4. -
  5. Minimum C++ compiler level is MSVC 14 (VS2015) or gcc 5. Compilers which do not support C++14 properly are not supported.
  6. -
  7. Use the PImpl idiom to reduce dependencies between classes.
  8. -
  9. Always use const-correctness. Methods taking non-primitive types as parameters should generally take them as const references, methods returning non-primitive types should generally return them as const references. Declare all methods that do not modify internal state `const`. For lazy-update getter methods, declare the internal state which is lazy-updated `mutable`.
  10. -
  11. Prefer `private` over `protected` to encourage encapsulation. Use public interfaces internally too.
  12. -
  13. Always declare destructors `virtual` unless the class you are writing should not have any vtable (no other virtual methods).
  14. -
  15. Avoid non-const by-ref parameters unless you have no other option. We prefer not to have inout parameters since they are less intuitive.
  16. -
- - -## Naming conventions & Documentation - -
    -
  1. Classes, types and structures must be title case (MyNewClass).
  2. -
  3. Methods and local variables must be camel case (myNewMethod).
  4. -
  5. Member variables should be prefixed with `m` (mInstanceVar), static member variables should be prefixed `ms` (msStaticMemberVar). Do not use any other prefixing such as Hungarian notation.
  6. -
  7. Preprocessor macros must be all upper case and prefixed with OGRE_
  8. -
  9. Enums should be named in title case, enum values should be all upper case
  10. -
  11. All classes and methods must be fully documented in English using Doxygen-compatible comments. Use the `@param` and `@return` directives to define inputs and outputs clearly, and `@note` to indicate points of interest.
  12. -
  13. Use verbose, descriptive names for classes, methods, variables - everything except trival counters. Code should be self-describing, don't be obtuse.
  14. -
- -## Style issues - -
    -
  1. Insert a newline before an open brace (contentious I know!)
  2. -
  3. Use typedefs to declare template-based types that you use to avoid ugliness e.g. typedef std::list MyTypeList;
  4. -
  5. Always insert spaces in between operators and operands (x + y, not x+y)
  6. -
  7. Use parenthesis to make the operator precedence unambiguous, even when it is not required ((x * y) + 1, not x * y + 1)
  8. -
- - -## Error handling - -
    -
  1. Fatal errors should always be dealt with though exception handling. No return-value error reporting.
  2. -
  3. Whenever you make an assumption in your code, verify it with an assert. - -* By default use `OgreAssert`. This will generate an exception - even in release builds. -* For performance critical code resort to `OgreAssertDbg` that only fires in debug builds. -* In public header files use the C `assert` macro to follow user-defined compilation flags. -* Prefer `OGRE_EXCEPT` for runtime-conditions outside of developer control e.g. minimal required OpenGL Version. This allows building Ogre with no assertion for release. -
  4. -
- - -## Design issues - -
    -
  1. Use existing design patterns and identify them by their well known names. A good starting reference is the "Gang of Four" book.
  2. -
  3. Use strong encapsulation. Top-level interfaces should hide implementations and not require the user of the library to understand internals. Avoid public attributes except in structs.
  4. -
  5. Don't use `friend` if you can avoid it. Where classes need to collaborate on an internal implementation, prefix the methods they use to communicate with `_` (this is our demarcation for "recommended for internal use only"). This can also be used to expose advanced functionality only intended for very skilled users.
  6. - -
- - -## Final words - -If in doubt, do as the existing code does! diff --git a/Docs/License.md b/Docs/License.md deleted file mode 100644 index 5bbaa070bd1..00000000000 --- a/Docs/License.md +++ /dev/null @@ -1,277 +0,0 @@ - -# License Information - - -

OGRE is released under an open source license, specifically the MIT License. - -

Under the MIT License you may use Ogre for any purpose you wish, without warranty, and modify it if you require, subject to one condition:

-
    -
  1. "The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software."
  2. -
- -In practice this means that whenever you distribute your application, whether as binary or as source code, you must include somewhere in your distribution the text in this file. This might be in the printed documentation, as a file on delivered media, or even on the credits / acknowledgements of the runtime application itself; any of those would satisfy the requirement. - -The [OGRE Logo](ogre-logo.png) is licenced [CC-BY](https://creativecommons.org/licenses/by/2.0/) [Pierre Fontaine](http://codrer.com/). - -# Licenses for 3rd-party libraries used in OGRE - -Several 3rd-party libraries are used in OGRE for various purposes, and the licensing details of each are given here. - -## Core Dependencies - -These are the libraries which the core of OGRE depends on, and are -therefore prerequisites for any use of OGRE. None of these libraries -have been modified from their original distributions, and they are all -licensed under liberal terms. You should read the detail of the -licenses when distributing an application since most require you to -include the license in your documentation. All the license texts are -included in the Docs/licenses folder. - -### zip - - - - - - - - - - - - - - - - - - - - -
Original Authors:Rich Geldreich and Kuba Podgórski
Website:https://github.com/kuba--/zip
Licensed Under:Unlicense (Public Domain)
- -## Optional Dependencies -These dependencies are only needed if you use the plugins they relate to, or you enable them in the source build. - -### SDL2 - - - - - - - - - - - - - - - - - - - -
-Original Authors: -Many
-Website: -https://www.libsdl.org/
-Licensed Under: -Zlib License
-Needed By: -Bites Component
- -### NVidia Cg - - - - - - - - - - - - - - - - - - - - - - - - - -
Original Authors:NVidia
Website:http://developer.nvidia.com
Licensed Under:Custom free license (binary only)
Needed By:Plugin_CgProgramManager
- -### STB Image - - - - - - - - - - - - - - - - - - - - - - - - - -
Original Authors:Sean Barrett
-
Website:https://github.com/nothings/stb
-
Licensed Under:public domain
Needed By:Codec_STBI
- -### OpenEXR - - - - - - - - - - - - - - - - - - - - - - - - - -
Original Authors:Industrial Light and Magic
Website:http://www.openexr.com
Licensed Under:Modified BSD License
Needed By:Codec_EXR
- -### pugixml - - - - - - - - - - - - - - - - - - - - - - -
-Original Authors: -Arseny Kapoulkine
-Website: - https://pugixml.org/
-Licensed Under: -MIT License
Needed By:OgreXMLConverter, Plugin_DotScene
- -## Source code used in-place in OGRE - -
    -
  • -

    Many of the maths/spatial routines - were adapted from work by Geometric Tools, LLC, Copyright (c) 1998-2010 and licensed under the Boost software license.

    - -
  • - -
- -## Art credits for demos - -
    -
  • -

    Matt Anderson at - www.The3dStudio.com who - kindly gave permission for the use of some textures. These textures are used with permission of - www.The3dStudio.com and may - not be re-distributed, sold, or given away except in the form of - rendered images, animations, or real time 3D applications when credit - is given to www.The3dStudio.com.

    -
  • -
  • -

    Jonathan Clark at - http://www.jonathanclark.com - for some Golgotha textures thet were released to the public domain.

    -
  • -
  • -

    The 'Raptor Assault Gunboat' mesh - & texture are © 2002 by Adrian 'cearny' Cearnau.

    -
  • -
  • -

    The robot andn ninja mesh and - animation are by Psionic, - kindly made available from the CharacterFX - site

    -
  • -
  • -

    The 'Razor 2' mesh is by Dennis - Verbeek

    -
  • -
  • -

    Skyboxes in cubemapJS.zip are - ©Johannes Schlorb, used - with permission. -

    -
  • -
  • -

    Grass texture is courtesy of Mathias 'freezer' Walc

    -
  • -
  • -

    The 'Cuckoo' TrueType font is provided by http://www.downloadheaven.co.uk.

    -
  • -
  • SoftImage|XSI sample media files (facial.mesh, jaiqua.mesh and associated files) are provided courtesy of Avid Technology, Inc.
    - © 2004 Avid Technology, Inc. All rights - reserved. Avid is either a registered trademark or trademark of Avid - Technology, Inc. in the United States and/or other countries. -
  • -
  • -

    The Sibenik Cathedral model by Marko Dabrovic - marko@3lhd.com.

    -
  • -
  • -

    Battle Damaged Sci-fi Helmet - PBR by theblueturtle_, published under a Creative Commons Attribution-NonCommercial license

    -
  • -
  • -

    Smoke15Frames.png by Beast, published under CC-0 https://opengameart.org/content/smoke-aura

    -
  • -
  • -

    Earth-Color10x6.astc and Texture.pkm by ARM Limited, published under MIT https://github.com/ARM-software/opengl-es-sdk-for-android

    -
  • -
  • -

    studio_garden.jpg adapted from Sergej Majboroda, published under CC-0 https://polyhaven.com/a/studio_garden

    -
  • -
diff --git a/Docs/doxygen-awesome.css b/Docs/doxygen-awesome.css deleted file mode 100644 index 05ecbfe94c1..00000000000 --- a/Docs/doxygen-awesome.css +++ /dev/null @@ -1,2669 +0,0 @@ -/** - -Doxygen Awesome -https://github.com/jothepro/doxygen-awesome-css - -MIT License - -Copyright (c) 2021 - 2023 jothepro - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - -*/ - -html { - /* primary theme color. This will affect the entire websites color scheme: links, arrows, labels, ... */ - --primary-color: #1779c4; - --primary-dark-color: #335c80; - --primary-light-color: #70b1e9; - - /* page base colors */ - --page-background-color: #ffffff; - --page-foreground-color: #2f4153; - --page-secondary-foreground-color: #6f7e8e; - - /* color for all separators on the website: hr, borders, ... */ - --separator-color: #dedede; - - /* border radius for all rounded components. Will affect many components, like dropdowns, memitems, codeblocks, ... */ - --border-radius-large: 8px; - --border-radius-small: 4px; - --border-radius-medium: 6px; - - /* default spacings. Most components reference these values for spacing, to provide uniform spacing on the page. */ - --spacing-small: 5px; - --spacing-medium: 10px; - --spacing-large: 16px; - - /* default box shadow used for raising an element above the normal content. Used in dropdowns, search result, ... */ - --box-shadow: 0 2px 8px 0 rgba(0,0,0,.075); - - --odd-color: rgba(0,0,0,.028); - - /* font-families. will affect all text on the website - * font-family: the normal font for text, headlines, menus - * font-family-monospace: used for preformatted text in memtitle, code, fragments - */ - --font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif; - --font-family-monospace: ui-monospace,SFMono-Regular,SF Mono,Menlo,Consolas,Liberation Mono,monospace; - - /* font sizes */ - --page-font-size: 15.6px; - --navigation-font-size: 14.4px; - --toc-font-size: 13.4px; - --code-font-size: 14px; /* affects code, fragment */ - --title-font-size: 22px; - - /* content text properties. These only affect the page content, not the navigation or any other ui elements */ - --content-line-height: 27px; - /* The content is centered and constraint in it's width. To make the content fill the whole page, set the variable to auto.*/ - --content-maxwidth: 1050px; - --table-line-height: 24px; - --toc-sticky-top: var(--spacing-medium); - --toc-width: 200px; - --toc-max-height: calc(100vh - 2 * var(--spacing-medium) - 85px); - - /* colors for various content boxes: @warning, @note, @deprecated @bug */ - --warning-color: #faf3d8; - --warning-color-dark: #f3a600; - --warning-color-darker: #5f4204; - --note-color: #e4f3ff; - --note-color-dark: #1879C4; - --note-color-darker: #274a5c; - --todo-color: #e4dafd; - --todo-color-dark: #5b2bdd; - --todo-color-darker: #2a0d72; - --deprecated-color: #ecf0f3; - --deprecated-color-dark: #5b6269; - --deprecated-color-darker: #43454a; - --bug-color: #f8d1cc; - --bug-color-dark: #b61825; - --bug-color-darker: #75070f; - --invariant-color: #d8f1e3; - --invariant-color-dark: #44b86f; - --invariant-color-darker: #265532; - - /* blockquote colors */ - --blockquote-background: #f8f9fa; - --blockquote-foreground: #636568; - - /* table colors */ - --tablehead-background: #f1f1f1; - --tablehead-foreground: var(--page-foreground-color); - - /* menu-display: block | none - * Visibility of the top navigation on screens >= 768px. On smaller screen the menu is always visible. - * `GENERATE_TREEVIEW` MUST be enabled! - */ - --menu-display: block; - - --menu-focus-foreground: var(--page-background-color); - --menu-focus-background: var(--primary-color); - --menu-selected-background: rgba(0,0,0,.05); - - - --header-background: var(--page-background-color); - --header-foreground: var(--page-foreground-color); - - /* searchbar colors */ - --searchbar-background: var(--side-nav-background); - --searchbar-foreground: var(--page-foreground-color); - - /* searchbar size - * (`searchbar-width` is only applied on screens >= 768px. - * on smaller screens the searchbar will always fill the entire screen width) */ - --searchbar-height: 33px; - --searchbar-width: 210px; - --searchbar-border-radius: var(--searchbar-height); - - /* code block colors */ - --code-background: #f5f5f5; - --code-foreground: var(--page-foreground-color); - - /* fragment colors */ - --fragment-background: #F8F9FA; - --fragment-foreground: #37474F; - --fragment-keyword: #bb6bb2; - --fragment-keywordtype: #8258b3; - --fragment-keywordflow: #d67c3b; - --fragment-token: #438a59; - --fragment-comment: #969696; - --fragment-link: #5383d6; - --fragment-preprocessor: #46aaa5; - --fragment-linenumber-color: #797979; - --fragment-linenumber-background: #f4f4f5; - --fragment-linenumber-border: #e3e5e7; - --fragment-lineheight: 20px; - - /* sidebar navigation (treeview) colors */ - --side-nav-background: #fbfbfb; - --side-nav-foreground: var(--page-foreground-color); - --side-nav-arrow-opacity: 0; - --side-nav-arrow-hover-opacity: 0.9; - - --toc-background: var(--side-nav-background); - --toc-foreground: var(--side-nav-foreground); - - /* height of an item in any tree / collapsible table */ - --tree-item-height: 30px; - - --memname-font-size: var(--code-font-size); - --memtitle-font-size: 18px; - - --webkit-scrollbar-size: 7px; - --webkit-scrollbar-padding: 4px; - --webkit-scrollbar-color: var(--separator-color); - - --animation-duration: .12s -} - -@media screen and (max-width: 767px) { - html { - --page-font-size: 16px; - --navigation-font-size: 16px; - --toc-font-size: 15px; - --code-font-size: 15px; /* affects code, fragment */ - --title-font-size: 22px; - } -} - -@media (prefers-color-scheme: dark) { - html:not(.light-mode) { - color-scheme: dark; - - --primary-color: #1982d2; - --primary-dark-color: #86a9c4; - --primary-light-color: #4779ac; - - --box-shadow: 0 2px 8px 0 rgba(0,0,0,.35); - - --odd-color: rgba(100,100,100,.06); - - --menu-selected-background: rgba(0,0,0,.4); - - --page-background-color: #1C1D1F; - --page-foreground-color: #d2dbde; - --page-secondary-foreground-color: #859399; - --separator-color: #38393b; - --side-nav-background: #252628; - - --code-background: #2a2c2f; - - --tablehead-background: #2a2c2f; - - --blockquote-background: #222325; - --blockquote-foreground: #7e8c92; - - --warning-color: #3b2e04; - --warning-color-dark: #f1b602; - --warning-color-darker: #ceb670; - --note-color: #163750; - --note-color-dark: #1982D2; - --note-color-darker: #dcf0fa; - --todo-color: #2a2536; - --todo-color-dark: #7661b3; - --todo-color-darker: #ae9ed6; - --deprecated-color: #2e323b; - --deprecated-color-dark: #738396; - --deprecated-color-darker: #abb0bd; - --bug-color: #2e1917; - --bug-color-dark: #ad2617; - --bug-color-darker: #f5b1aa; - --invariant-color: #303a35; - --invariant-color-dark: #76ce96; - --invariant-color-darker: #cceed5; - - --fragment-background: #282c34; - --fragment-foreground: #dbe4eb; - --fragment-keyword: #cc99cd; - --fragment-keywordtype: #ab99cd; - --fragment-keywordflow: #e08000; - --fragment-token: #7ec699; - --fragment-comment: #999999; - --fragment-link: #98c0e3; - --fragment-preprocessor: #65cabe; - --fragment-linenumber-color: #cccccc; - --fragment-linenumber-background: #35393c; - --fragment-linenumber-border: #1f1f1f; - } -} - -/* dark mode variables are defined twice, to support both the dark-mode without and with doxygen-awesome-darkmode-toggle.js */ -html.dark-mode { - color-scheme: dark; - - --primary-color: #1982d2; - --primary-dark-color: #86a9c4; - --primary-light-color: #4779ac; - - --box-shadow: 0 2px 8px 0 rgba(0,0,0,.30); - - --odd-color: rgba(100,100,100,.06); - - --menu-selected-background: rgba(0,0,0,.4); - - --page-background-color: #1C1D1F; - --page-foreground-color: #d2dbde; - --page-secondary-foreground-color: #859399; - --separator-color: #38393b; - --side-nav-background: #252628; - - --code-background: #2a2c2f; - - --tablehead-background: #2a2c2f; - - --blockquote-background: #222325; - --blockquote-foreground: #7e8c92; - - --warning-color: #3b2e04; - --warning-color-dark: #f1b602; - --warning-color-darker: #ceb670; - --note-color: #163750; - --note-color-dark: #1982D2; - --note-color-darker: #dcf0fa; - --todo-color: #2a2536; - --todo-color-dark: #7661b3; - --todo-color-darker: #ae9ed6; - --deprecated-color: #2e323b; - --deprecated-color-dark: #738396; - --deprecated-color-darker: #abb0bd; - --bug-color: #2e1917; - --bug-color-dark: #ad2617; - --bug-color-darker: #f5b1aa; - --invariant-color: #303a35; - --invariant-color-dark: #76ce96; - --invariant-color-darker: #cceed5; - - --fragment-background: #282c34; - --fragment-foreground: #dbe4eb; - --fragment-keyword: #cc99cd; - --fragment-keywordtype: #ab99cd; - --fragment-keywordflow: #e08000; - --fragment-token: #7ec699; - --fragment-comment: #999999; - --fragment-link: #98c0e3; - --fragment-preprocessor: #65cabe; - --fragment-linenumber-color: #cccccc; - --fragment-linenumber-background: #35393c; - --fragment-linenumber-border: #1f1f1f; -} - -body { - color: var(--page-foreground-color); - background-color: var(--page-background-color); - font-size: var(--page-font-size); -} - -body, table, div, p, dl, #nav-tree .label, .title, -.sm-dox a, .sm-dox a:hover, .sm-dox a:focus, #projectname, -.SelectItem, #MSearchField, .navpath li.navelem a, -.navpath li.navelem a:hover, p.reference, p.definition { - font-family: var(--font-family); -} - -h1, h2, h3, h4, h5 { - margin-top: 1em; - font-weight: 600; - line-height: initial; -} - -p, div, table, dl, p.reference, p.definition { - font-size: var(--page-font-size); -} - -p.reference, p.definition { - color: var(--page-secondary-foreground-color); -} - -a:link, a:visited, a:hover, a:focus, a:active { - color: var(--primary-color) !important; - font-weight: 500; -} - -a.anchor { - scroll-margin-top: var(--spacing-large); - display: block; -} - -/* - Title and top navigation - */ - -#top { - background: var(--header-background); - border-bottom: 1px solid var(--separator-color); -} - -@media screen and (min-width: 768px) { - #top { - display: flex; - flex-wrap: wrap; - justify-content: space-between; - align-items: center; - } -} - -#main-nav { - flex-grow: 5; - padding: var(--spacing-small) var(--spacing-medium); -} - -#titlearea { - width: auto; - padding: var(--spacing-medium) var(--spacing-large); - background: none; - color: var(--header-foreground); - border-bottom: none; -} - -@media screen and (max-width: 767px) { - #titlearea { - padding-bottom: var(--spacing-small); - } -} - -#titlearea table tbody tr { - height: auto !important; -} - -#projectname { - font-size: var(--title-font-size); - font-weight: 600; -} - -#projectnumber { - font-family: inherit; - font-size: 60%; -} - -#projectbrief { - font-family: inherit; - font-size: 80%; -} - -#projectlogo { - vertical-align: middle; -} - -#projectlogo img { - max-height: calc(var(--title-font-size) * 2); - margin-right: var(--spacing-small); -} - -.sm-dox, .tabs, .tabs2, .tabs3 { - background: none; - padding: 0; -} - -.tabs, .tabs2, .tabs3 { - border-bottom: 1px solid var(--separator-color); - margin-bottom: -1px; -} - -.main-menu-btn-icon, .main-menu-btn-icon:before, .main-menu-btn-icon:after { - background: var(--page-secondary-foreground-color); -} - -@media screen and (max-width: 767px) { - .sm-dox a span.sub-arrow { - background: var(--code-background); - } - - #main-menu a.has-submenu span.sub-arrow { - color: var(--page-secondary-foreground-color); - border-radius: var(--border-radius-medium); - } - - #main-menu a.has-submenu:hover span.sub-arrow { - color: var(--page-foreground-color); - } -} - -@media screen and (min-width: 768px) { - .sm-dox li, .tablist li { - display: var(--menu-display); - } - - .sm-dox a span.sub-arrow { - border-color: var(--header-foreground) transparent transparent transparent; - } - - .sm-dox a:hover span.sub-arrow { - border-color: var(--menu-focus-foreground) transparent transparent transparent; - } - - .sm-dox ul a span.sub-arrow { - border-color: transparent transparent transparent var(--page-foreground-color); - } - - .sm-dox ul a:hover span.sub-arrow { - border-color: transparent transparent transparent var(--menu-focus-foreground); - } -} - -.sm-dox ul { - background: var(--page-background-color); - box-shadow: var(--box-shadow); - border: 1px solid var(--separator-color); - border-radius: var(--border-radius-medium) !important; - padding: var(--spacing-small); - animation: ease-out 150ms slideInMenu; -} - -@keyframes slideInMenu { - from { - opacity: 0; - transform: translate(0px, -2px); - } - - to { - opacity: 1; - transform: translate(0px, 0px); - } -} - -.sm-dox ul a { - color: var(--page-foreground-color) !important; - background: var(--page-background-color); - font-size: var(--navigation-font-size); -} - -.sm-dox>li>ul:after { - border-bottom-color: var(--page-background-color) !important; -} - -.sm-dox>li>ul:before { - border-bottom-color: var(--separator-color) !important; -} - -.sm-dox ul a:hover, .sm-dox ul a:active, .sm-dox ul a:focus { - font-size: var(--navigation-font-size) !important; - color: var(--menu-focus-foreground) !important; - text-shadow: none; - background-color: var(--menu-focus-background); - border-radius: var(--border-radius-small) !important; -} - -.sm-dox a, .sm-dox a:focus, .tablist li, .tablist li a, .tablist li.current a { - text-shadow: none; - background: transparent; - background-image: none !important; - color: var(--header-foreground) !important; - font-weight: normal; - font-size: var(--navigation-font-size); - border-radius: var(--border-radius-small) !important; -} - -.sm-dox a:focus { - outline: auto; -} - -.sm-dox a:hover, .sm-dox a:active, .tablist li a:hover { - text-shadow: none; - font-weight: normal; - background: var(--menu-focus-background); - color: var(--menu-focus-foreground) !important; - border-radius: var(--border-radius-small) !important; - font-size: var(--navigation-font-size); -} - -.tablist li.current { - border-radius: var(--border-radius-small); - background: var(--menu-selected-background); -} - -.tablist li { - margin: var(--spacing-small) 0 var(--spacing-small) var(--spacing-small); -} - -.tablist a { - padding: 0 var(--spacing-large); -} - - -/* - Search box - */ - -#MSearchBox { - height: var(--searchbar-height); - background: var(--searchbar-background); - border-radius: var(--searchbar-border-radius); - border: 1px solid var(--separator-color); - overflow: hidden; - width: var(--searchbar-width); - position: relative; - box-shadow: none; - display: block; - margin-top: 0; -} - -/* until Doxygen 1.9.4 */ -.left img#MSearchSelect { - left: 0; - user-select: none; - padding-left: 8px; -} - -/* Doxygen 1.9.5 */ -.left span#MSearchSelect { - left: 0; - user-select: none; - margin-left: 8px; - padding: 0; -} - -.left #MSearchSelect[src$=".png"] { - padding-left: 0 -} - -.SelectionMark { - user-select: none; -} - -.tabs .left #MSearchSelect { - padding-left: 0; -} - -.tabs #MSearchBox { - position: absolute; - right: var(--spacing-medium); -} - -@media screen and (max-width: 767px) { - .tabs #MSearchBox { - position: relative; - right: 0; - margin-left: var(--spacing-medium); - margin-top: 0; - } -} - -#MSearchSelectWindow, #MSearchResultsWindow { - z-index: 9999; -} - -#MSearchBox.MSearchBoxActive { - border-color: var(--primary-color); - box-shadow: inset 0 0 0 1px var(--primary-color); -} - -#main-menu > li:last-child { - margin-right: 0; -} - -@media screen and (max-width: 767px) { - #main-menu > li:last-child { - height: 50px; - } -} - -#MSearchField { - font-size: var(--navigation-font-size); - height: calc(var(--searchbar-height) - 2px); - background: transparent; - width: calc(var(--searchbar-width) - 64px); -} - -.MSearchBoxActive #MSearchField { - color: var(--searchbar-foreground); -} - -#MSearchSelect { - top: calc(calc(var(--searchbar-height) / 2) - 11px); -} - -#MSearchBox span.left, #MSearchBox span.right { - background: none; - background-image: none; -} - -#MSearchBox span.right { - padding-top: calc(calc(var(--searchbar-height) / 2) - 12px); - position: absolute; - right: var(--spacing-small); -} - -.tabs #MSearchBox span.right { - top: calc(calc(var(--searchbar-height) / 2) - 12px); -} - -@keyframes slideInSearchResults { - from { - opacity: 0; - transform: translate(0, 15px); - } - - to { - opacity: 1; - transform: translate(0, 20px); - } -} - -#MSearchResultsWindow { - left: auto !important; - right: var(--spacing-medium); - border-radius: var(--border-radius-large); - border: 1px solid var(--separator-color); - transform: translate(0, 20px); - box-shadow: var(--box-shadow); - animation: ease-out 280ms slideInSearchResults; - background: var(--page-background-color); -} - -iframe#MSearchResults { - margin: 4px; -} - -iframe { - color-scheme: normal; -} - -@media (prefers-color-scheme: dark) { - html:not(.light-mode) iframe#MSearchResults { - filter: invert() hue-rotate(180deg); - } -} - -html.dark-mode iframe#MSearchResults { - filter: invert() hue-rotate(180deg); -} - -#MSearchResults .SRPage { - background-color: transparent; -} - -#MSearchResults .SRPage .SREntry { - font-size: 10pt; - padding: var(--spacing-small) var(--spacing-medium); -} - -#MSearchSelectWindow { - border: 1px solid var(--separator-color); - border-radius: var(--border-radius-medium); - box-shadow: var(--box-shadow); - background: var(--page-background-color); - padding-top: var(--spacing-small); - padding-bottom: var(--spacing-small); -} - -#MSearchSelectWindow a.SelectItem { - font-size: var(--navigation-font-size); - line-height: var(--content-line-height); - margin: 0 var(--spacing-small); - border-radius: var(--border-radius-small); - color: var(--page-foreground-color) !important; - font-weight: normal; -} - -#MSearchSelectWindow a.SelectItem:hover { - background: var(--menu-focus-background); - color: var(--menu-focus-foreground) !important; -} - -@media screen and (max-width: 767px) { - #MSearchBox { - margin-top: var(--spacing-medium); - margin-bottom: var(--spacing-medium); - width: calc(100vw - 30px); - } - - #main-menu > li:last-child { - float: none !important; - } - - #MSearchField { - width: calc(100vw - 110px); - } - - @keyframes slideInSearchResultsMobile { - from { - opacity: 0; - transform: translate(0, 15px); - } - - to { - opacity: 1; - transform: translate(0, 20px); - } - } - - #MSearchResultsWindow { - left: var(--spacing-medium) !important; - right: var(--spacing-medium); - overflow: auto; - transform: translate(0, 20px); - animation: ease-out 280ms slideInSearchResultsMobile; - width: auto !important; - } - - /* - * Overwrites for fixing the searchbox on mobile in doxygen 1.9.2 - */ - label.main-menu-btn ~ #searchBoxPos1 { - top: 3px !important; - right: 6px !important; - left: 45px; - display: flex; - } - - label.main-menu-btn ~ #searchBoxPos1 > #MSearchBox { - margin-top: 0; - margin-bottom: 0; - flex-grow: 2; - float: left; - } -} - -/* - Tree view - */ - -#side-nav { - padding: 0 !important; - background: var(--side-nav-background); - min-width: 8px; - max-width: 50vw; -} - -@media screen and (max-width: 767px) { - #side-nav { - display: none; - } - - #doc-content { - margin-left: 0 !important; - } -} - -#nav-tree { - background: transparent; - margin-right: 1px; -} - -#nav-tree .label { - font-size: var(--navigation-font-size); -} - -#nav-tree .item { - height: var(--tree-item-height); - line-height: var(--tree-item-height); -} - -#nav-sync { - bottom: 12px; - right: 12px; - top: auto !important; - user-select: none; -} - -#nav-tree .selected { - text-shadow: none; - background-image: none; - background-color: transparent; - position: relative; -} - -#nav-tree .selected::after { - content: ""; - position: absolute; - top: 1px; - bottom: 1px; - left: 0; - width: 4px; - border-radius: 0 var(--border-radius-small) var(--border-radius-small) 0; - background: var(--primary-color); -} - - -#nav-tree a { - color: var(--side-nav-foreground) !important; - font-weight: normal; -} - -#nav-tree a:focus { - outline-style: auto; -} - -#nav-tree .arrow { - opacity: var(--side-nav-arrow-opacity); -} - -.arrow { - color: inherit; - cursor: pointer; - font-size: 45%; - vertical-align: middle; - margin-right: 2px; - font-family: serif; - height: auto; - text-align: right; -} - -#nav-tree div.item:hover .arrow, #nav-tree a:focus .arrow { - opacity: var(--side-nav-arrow-hover-opacity); -} - -#nav-tree .selected a { - color: var(--primary-color) !important; - font-weight: bolder; - font-weight: 600; -} - -.ui-resizable-e { - width: 4px; - background: transparent; - box-shadow: inset -1px 0 0 0 var(--separator-color); -} - -/* - Contents - */ - -div.header { - border-bottom: 1px solid var(--separator-color); - background-color: var(--page-background-color); - background-image: none; -} - -@media screen and (min-width: 1000px) { - #doc-content > div > div.contents, - .PageDoc > div.contents { - display: flex; - flex-direction: row-reverse; - flex-wrap: nowrap; - align-items: flex-start; - } - - div.contents .textblock { - min-width: 200px; - flex-grow: 1; - } -} - -div.contents, div.header .title, div.header .summary { - max-width: var(--content-maxwidth); -} - -div.contents, div.header .title { - line-height: initial; - margin: calc(var(--spacing-medium) + .2em) auto var(--spacing-medium) auto; -} - -div.header .summary { - margin: var(--spacing-medium) auto 0 auto; -} - -div.headertitle { - padding: 0; -} - -div.header .title { - font-weight: 600; - font-size: 225%; - padding: var(--spacing-medium) var(--spacing-large); - word-break: break-word; -} - -div.header .summary { - width: auto; - display: block; - float: none; - padding: 0 var(--spacing-large); -} - -td.memSeparator { - border-color: var(--separator-color); -} - -span.mlabel { - background: var(--primary-color); - border: none; - padding: 4px 9px; - border-radius: 12px; - margin-right: var(--spacing-medium); -} - -span.mlabel:last-of-type { - margin-right: 2px; -} - -div.contents { - padding: 0 var(--spacing-large); -} - -div.contents p, div.contents li { - line-height: var(--content-line-height); -} - -div.contents div.dyncontent { - margin: var(--spacing-medium) 0; -} - -@media (prefers-color-scheme: dark) { - html:not(.light-mode) div.contents div.dyncontent img, - html:not(.light-mode) div.contents center img, - html:not(.light-mode) div.contents > table img, - html:not(.light-mode) div.contents div.dyncontent iframe, - html:not(.light-mode) div.contents center iframe, - html:not(.light-mode) div.contents table iframe, - html:not(.light-mode) div.contents .dotgraph iframe { - filter: brightness(89%) hue-rotate(180deg) invert(); - } -} - -html.dark-mode div.contents div.dyncontent img, -html.dark-mode div.contents center img, -html.dark-mode div.contents > table img, -html.dark-mode div.contents div.dyncontent iframe, -html.dark-mode div.contents center iframe, -html.dark-mode div.contents table iframe, -html.dark-mode div.contents .dotgraph iframe - { - filter: brightness(89%) hue-rotate(180deg) invert(); -} - -h2.groupheader { - border-bottom: 0px; - color: var(--page-foreground-color); - box-shadow: - 100px 0 var(--page-background-color), - -100px 0 var(--page-background-color), - 100px 0.75px var(--separator-color), - -100px 0.75px var(--separator-color), - 500px 0 var(--page-background-color), - -500px 0 var(--page-background-color), - 500px 0.75px var(--separator-color), - -500px 0.75px var(--separator-color), - 900px 0 var(--page-background-color), - -900px 0 var(--page-background-color), - 900px 0.75px var(--separator-color), - -900px 0.75px var(--separator-color), - 1400px 0 var(--page-background-color), - -1400px 0 var(--page-background-color), - 1400px 0.75px var(--separator-color), - -1400px 0.75px var(--separator-color), - 1900px 0 var(--page-background-color), - -1900px 0 var(--page-background-color), - 1900px 0.75px var(--separator-color), - -1900px 0.75px var(--separator-color); -} - -blockquote { - margin: 0 var(--spacing-medium) 0 var(--spacing-medium); - padding: var(--spacing-small) var(--spacing-large); - background: var(--blockquote-background); - color: var(--blockquote-foreground); - border-left: 0; - overflow: visible; - border-radius: var(--border-radius-medium); - overflow: visible; - position: relative; -} - -blockquote::before, blockquote::after { - font-weight: bold; - font-family: serif; - font-size: 360%; - opacity: .15; - position: absolute; -} - -blockquote::before { - content: "“"; - left: -10px; - top: 4px; -} - -blockquote::after { - content: "â€"; - right: -8px; - bottom: -25px; -} - -blockquote p { - margin: var(--spacing-small) 0 var(--spacing-medium) 0; -} -.paramname { - font-weight: 600; - color: var(--primary-dark-color); -} - -.paramname > code { - border: 0; -} - -table.params .paramname { - font-weight: 600; - font-family: var(--font-family-monospace); - font-size: var(--code-font-size); - padding-right: var(--spacing-small); - line-height: var(--table-line-height); -} - -h1.glow, h2.glow, h3.glow, h4.glow, h5.glow, h6.glow { - text-shadow: 0 0 15px var(--primary-light-color); -} - -.alphachar a { - color: var(--page-foreground-color); -} - -.dotgraph { - max-width: 100%; - overflow-x: scroll; -} - -.dotgraph .caption { - position: sticky; - left: 0; -} - -/* Wrap Graphviz graphs with the `interactive_dotgraph` class if `INTERACTIVE_SVG = YES` */ -.interactive_dotgraph .dotgraph iframe { - max-width: 100%; -} - -/* - Table of Contents - */ - -div.contents .toc { - max-height: var(--toc-max-height); - min-width: var(--toc-width); - border: 0; - border-left: 1px solid var(--separator-color); - border-radius: 0; - background-color: transparent; - box-shadow: none; - position: sticky; - top: var(--toc-sticky-top); - padding: 0 var(--spacing-large); - margin: var(--spacing-small) 0 var(--spacing-large) var(--spacing-large); -} - -div.toc h3 { - color: var(--toc-foreground); - font-size: var(--navigation-font-size); - margin: var(--spacing-large) 0 var(--spacing-medium) 0; -} - -div.toc li { - padding: 0; - background: none; - line-height: var(--toc-font-size); - margin: var(--toc-font-size) 0 0 0; -} - -div.toc li::before { - display: none; -} - -div.toc ul { - margin-top: 0 -} - -div.toc li a { - font-size: var(--toc-font-size); - color: var(--page-foreground-color) !important; - text-decoration: none; -} - -div.toc li a:hover, div.toc li a.active { - color: var(--primary-color) !important; -} - -div.toc li a.aboveActive { - color: var(--page-secondary-foreground-color) !important; -} - - -@media screen and (max-width: 999px) { - div.contents .toc { - max-height: 45vh; - float: none; - width: auto; - margin: 0 0 var(--spacing-medium) 0; - position: relative; - top: 0; - position: relative; - border: 1px solid var(--separator-color); - border-radius: var(--border-radius-medium); - background-color: var(--toc-background); - box-shadow: var(--box-shadow); - } - - div.contents .toc.interactive { - max-height: calc(var(--navigation-font-size) + 2 * var(--spacing-large)); - overflow: hidden; - } - - div.contents .toc > h3 { - -webkit-tap-highlight-color: transparent; - cursor: pointer; - position: sticky; - top: 0; - background-color: var(--toc-background); - margin: 0; - padding: var(--spacing-large) 0; - display: block; - } - - div.contents .toc.interactive > h3::before { - content: ""; - width: 0; - height: 0; - border-left: 4px solid transparent; - border-right: 4px solid transparent; - border-top: 5px solid var(--primary-color); - display: inline-block; - margin-right: var(--spacing-small); - margin-bottom: calc(var(--navigation-font-size) / 4); - transform: rotate(-90deg); - transition: transform var(--animation-duration) ease-out; - } - - div.contents .toc.interactive.open > h3::before { - transform: rotate(0deg); - } - - div.contents .toc.interactive.open { - max-height: 45vh; - overflow: auto; - transition: max-height 0.2s ease-in-out; - } - - div.contents .toc a, div.contents .toc a.active { - color: var(--primary-color) !important; - } - - div.contents .toc a:hover { - text-decoration: underline; - } -} - -/* - Code & Fragments - */ - -code, div.fragment, pre.fragment { - border-radius: var(--border-radius-small); - border: 1px solid var(--separator-color); - overflow: hidden; -} - -code { - display: inline; - background: var(--code-background); - color: var(--code-foreground); - padding: 2px 6px; -} - -div.fragment, pre.fragment { - margin: var(--spacing-medium) 0; - padding: calc(var(--spacing-large) - (var(--spacing-large) / 6)) var(--spacing-large); - background: var(--fragment-background); - color: var(--fragment-foreground); - overflow-x: auto; -} - -@media screen and (max-width: 767px) { - div.fragment, pre.fragment { - border-top-right-radius: 0; - border-bottom-right-radius: 0; - border-right: 0; - } - - .contents > div.fragment, - .textblock > div.fragment, - .textblock > pre.fragment, - .textblock > .tabbed > ul > li > div.fragment, - .textblock > .tabbed > ul > li > pre.fragment, - .contents > .doxygen-awesome-fragment-wrapper > div.fragment, - .textblock > .doxygen-awesome-fragment-wrapper > div.fragment, - .textblock > .doxygen-awesome-fragment-wrapper > pre.fragment, - .textblock > .tabbed > ul > li > .doxygen-awesome-fragment-wrapper > div.fragment, - .textblock > .tabbed > ul > li > .doxygen-awesome-fragment-wrapper > pre.fragment { - margin: var(--spacing-medium) calc(0px - var(--spacing-large)); - border-radius: 0; - border-left: 0; - } - - .textblock li > .fragment, - .textblock li > .doxygen-awesome-fragment-wrapper > .fragment { - margin: var(--spacing-medium) calc(0px - var(--spacing-large)); - } - - .memdoc li > .fragment, - .memdoc li > .doxygen-awesome-fragment-wrapper > .fragment { - margin: var(--spacing-medium) calc(0px - var(--spacing-medium)); - } - - .textblock ul, .memdoc ul { - overflow: initial; - } - - .memdoc > div.fragment, - .memdoc > pre.fragment, - dl dd > div.fragment, - dl dd pre.fragment, - .memdoc > .doxygen-awesome-fragment-wrapper > div.fragment, - .memdoc > .doxygen-awesome-fragment-wrapper > pre.fragment, - dl dd > .doxygen-awesome-fragment-wrapper > div.fragment, - dl dd .doxygen-awesome-fragment-wrapper > pre.fragment { - margin: var(--spacing-medium) calc(0px - var(--spacing-medium)); - border-radius: 0; - border-left: 0; - } -} - -code, code a, pre.fragment, div.fragment, div.fragment .line, div.fragment span, div.fragment .line a, div.fragment .line span { - font-family: var(--font-family-monospace); - font-size: var(--code-font-size) !important; -} - -div.line:after { - margin-right: var(--spacing-medium); -} - -div.fragment .line, pre.fragment { - white-space: pre; - word-wrap: initial; - line-height: var(--fragment-lineheight); -} - -div.fragment span.keyword { - color: var(--fragment-keyword); -} - -div.fragment span.keywordtype { - color: var(--fragment-keywordtype); -} - -div.fragment span.keywordflow { - color: var(--fragment-keywordflow); -} - -div.fragment span.stringliteral { - color: var(--fragment-token) -} - -div.fragment span.comment { - color: var(--fragment-comment); -} - -div.fragment a.code { - color: var(--fragment-link) !important; -} - -div.fragment span.preprocessor { - color: var(--fragment-preprocessor); -} - -div.fragment span.lineno { - display: inline-block; - width: 27px; - border-right: none; - background: var(--fragment-linenumber-background); - color: var(--fragment-linenumber-color); -} - -div.fragment span.lineno a { - background: none; - color: var(--fragment-link) !important; -} - -div.fragment > .line:first-child .lineno { - box-shadow: -999999px 0px 0 999999px var(--fragment-linenumber-background), -999998px 0px 0 999999px var(--fragment-linenumber-border); - background-color: var(--fragment-linenumber-background) !important; -} - -div.line { - border-radius: var(--border-radius-small); -} - -div.line.glow { - background-color: var(--primary-light-color); - box-shadow: none; -} - -/* - dl warning, attention, note, deprecated, bug, ... - */ - -dl.bug dt a, dl.deprecated dt a, dl.todo dt a { - font-weight: bold !important; -} - -dl.warning, dl.attention, dl.note, dl.deprecated, dl.bug, dl.invariant, dl.pre, dl.post, dl.todo, dl.remark { - padding: var(--spacing-medium); - margin: var(--spacing-medium) 0; - color: var(--page-background-color); - overflow: hidden; - margin-left: 0; - border-radius: var(--border-radius-small); -} - -dl.section dd { - margin-bottom: 2px; -} - -dl.warning, dl.attention { - background: var(--warning-color); - border-left: 8px solid var(--warning-color-dark); - color: var(--warning-color-darker); -} - -dl.warning dt, dl.attention dt { - color: var(--warning-color-dark); -} - -dl.note, dl.remark { - background: var(--note-color); - border-left: 8px solid var(--note-color-dark); - color: var(--note-color-darker); -} - -dl.note dt, dl.remark dt { - color: var(--note-color-dark); -} - -dl.todo { - background: var(--todo-color); - border-left: 8px solid var(--todo-color-dark); - color: var(--todo-color-darker); -} - -dl.todo dt a { - color: var(--todo-color-dark) !important; -} - -dl.bug dt a { - color: var(--todo-color-dark) !important; -} - -dl.bug { - background: var(--bug-color); - border-left: 8px solid var(--bug-color-dark); - color: var(--bug-color-darker); -} - -dl.bug dt a { - color: var(--bug-color-dark) !important; -} - -dl.deprecated { - background: var(--deprecated-color); - border-left: 8px solid var(--deprecated-color-dark); - color: var(--deprecated-color-darker); -} - -dl.deprecated dt a { - color: var(--deprecated-color-dark) !important; -} - -dl.section dd, dl.bug dd, dl.deprecated dd, dl.todo dd { - margin-inline-start: 0px; -} - -dl.invariant, dl.pre, dl.post { - background: var(--invariant-color); - border-left: 8px solid var(--invariant-color-dark); - color: var(--invariant-color-darker); -} - -dl.invariant dt, dl.pre dt, dl.post dt { - color: var(--invariant-color-dark); -} - -/* - memitem - */ - -div.memdoc, div.memproto, h2.memtitle { - box-shadow: none; - background-image: none; - border: none; -} - -div.memdoc { - padding: 0 var(--spacing-medium); - background: var(--page-background-color); -} - -h2.memtitle, div.memitem { - border: 1px solid var(--separator-color); - box-shadow: var(--box-shadow); -} - -h2.memtitle { - box-shadow: 0px var(--spacing-medium) 0 -1px var(--fragment-background), var(--box-shadow); -} - -div.memitem { - transition: none; -} - -div.memproto, h2.memtitle { - background: var(--fragment-background); -} - -h2.memtitle { - font-weight: 500; - font-size: var(--memtitle-font-size); - font-family: var(--font-family-monospace); - border-bottom: none; - border-top-left-radius: var(--border-radius-medium); - border-top-right-radius: var(--border-radius-medium); - word-break: break-all; - position: relative; -} - -h2.memtitle:after { - content: ""; - display: block; - background: var(--fragment-background); - height: var(--spacing-medium); - bottom: calc(0px - var(--spacing-medium)); - left: 0; - right: -14px; - position: absolute; - border-top-right-radius: var(--border-radius-medium); -} - -h2.memtitle > span.permalink { - font-size: inherit; -} - -h2.memtitle > span.permalink > a { - text-decoration: none; - padding-left: 3px; - margin-right: -4px; - user-select: none; - display: inline-block; - margin-top: -6px; -} - -h2.memtitle > span.permalink > a:hover { - color: var(--primary-dark-color) !important; -} - -a:target + h2.memtitle, a:target + h2.memtitle + div.memitem { - border-color: var(--primary-light-color); -} - -div.memitem { - border-top-right-radius: var(--border-radius-medium); - border-bottom-right-radius: var(--border-radius-medium); - border-bottom-left-radius: var(--border-radius-medium); - overflow: hidden; - display: block !important; -} - -div.memdoc { - border-radius: 0; -} - -div.memproto { - border-radius: 0 var(--border-radius-small) 0 0; - overflow: auto; - border-bottom: 1px solid var(--separator-color); - padding: var(--spacing-medium); - margin-bottom: -1px; -} - -div.memtitle { - border-top-right-radius: var(--border-radius-medium); - border-top-left-radius: var(--border-radius-medium); -} - -div.memproto table.memname { - font-family: var(--font-family-monospace); - color: var(--page-foreground-color); - font-size: var(--memname-font-size); - text-shadow: none; -} - -div.memproto div.memtemplate { - font-family: var(--font-family-monospace); - color: var(--primary-dark-color); - font-size: var(--memname-font-size); - margin-left: 2px; - text-shadow: none; -} - -table.mlabels, table.mlabels > tbody { - display: block; -} - -td.mlabels-left { - width: auto; -} - -td.mlabels-right { - margin-top: 3px; - position: sticky; - left: 0; -} - -table.mlabels > tbody > tr:first-child { - display: flex; - justify-content: space-between; - flex-wrap: wrap; -} - -.memname, .memitem span.mlabels { - margin: 0 -} - -/* - reflist - */ - -dl.reflist { - box-shadow: var(--box-shadow); - border-radius: var(--border-radius-medium); - border: 1px solid var(--separator-color); - overflow: hidden; - padding: 0; -} - - -dl.reflist dt, dl.reflist dd { - box-shadow: none; - text-shadow: none; - background-image: none; - border: none; - padding: 12px; -} - - -dl.reflist dt { - font-weight: 500; - border-radius: 0; - background: var(--code-background); - border-bottom: 1px solid var(--separator-color); - color: var(--page-foreground-color) -} - - -dl.reflist dd { - background: none; -} - -/* - Table - */ - -.contents table:not(.memberdecls):not(.mlabels):not(.fieldtable):not(.memname), -.contents table:not(.memberdecls):not(.mlabels):not(.fieldtable):not(.memname) tbody { - display: inline-block; - max-width: 100%; -} - -.contents > table:not(.memberdecls):not(.mlabels):not(.fieldtable):not(.memname):not(.classindex) { - margin-left: calc(0px - var(--spacing-large)); - margin-right: calc(0px - var(--spacing-large)); - max-width: calc(100% + 2 * var(--spacing-large)); -} - -table.fieldtable, -table.markdownTable tbody, -table.doxtable tbody { - border: none; - margin: var(--spacing-medium) 0; - box-shadow: 0 0 0 1px var(--separator-color); - border-radius: var(--border-radius-small); -} - -table.markdownTable, table.doxtable, table.fieldtable { - padding: 1px; -} - -table.doxtable caption { - display: block; -} - -table.fieldtable { - border-collapse: collapse; - width: 100%; -} - -th.markdownTableHeadLeft, -th.markdownTableHeadRight, -th.markdownTableHeadCenter, -th.markdownTableHeadNone, -table.doxtable th { - background: var(--tablehead-background); - color: var(--tablehead-foreground); - font-weight: 600; - font-size: var(--page-font-size); -} - -th.markdownTableHeadLeft:first-child, -th.markdownTableHeadRight:first-child, -th.markdownTableHeadCenter:first-child, -th.markdownTableHeadNone:first-child, -table.doxtable tr th:first-child { - border-top-left-radius: var(--border-radius-small); -} - -th.markdownTableHeadLeft:last-child, -th.markdownTableHeadRight:last-child, -th.markdownTableHeadCenter:last-child, -th.markdownTableHeadNone:last-child, -table.doxtable tr th:last-child { - border-top-right-radius: var(--border-radius-small); -} - -table.markdownTable td, -table.markdownTable th, -table.fieldtable td, -table.fieldtable th, -table.doxtable td, -table.doxtable th { - border: 1px solid var(--separator-color); - padding: var(--spacing-small) var(--spacing-medium); -} - -table.markdownTable td:last-child, -table.markdownTable th:last-child, -table.fieldtable td:last-child, -table.fieldtable th:last-child, -table.doxtable td:last-child, -table.doxtable th:last-child { - border-right: none; -} - -table.markdownTable td:first-child, -table.markdownTable th:first-child, -table.fieldtable td:first-child, -table.fieldtable th:first-child, -table.doxtable td:first-child, -table.doxtable th:first-child { - border-left: none; -} - -table.markdownTable tr:first-child td, -table.markdownTable tr:first-child th, -table.fieldtable tr:first-child td, -table.fieldtable tr:first-child th, -table.doxtable tr:first-child td, -table.doxtable tr:first-child th { - border-top: none; -} - -table.markdownTable tr:last-child td, -table.markdownTable tr:last-child th, -table.fieldtable tr:last-child td, -table.fieldtable tr:last-child th, -table.doxtable tr:last-child td, -table.doxtable tr:last-child th { - border-bottom: none; -} - -table.markdownTable tr, table.doxtable tr { - border-bottom: 1px solid var(--separator-color); -} - -table.markdownTable tr:last-child, table.doxtable tr:last-child { - border-bottom: none; -} - -.full_width_table table:not(.memberdecls):not(.mlabels):not(.fieldtable):not(.memname) { - display: block; -} - -.full_width_table table:not(.memberdecls):not(.mlabels):not(.fieldtable):not(.memname) tbody { - display: table; - width: 100%; -} - -table.fieldtable th { - font-size: var(--page-font-size); - font-weight: 600; - background-image: none; - background-color: var(--tablehead-background); - color: var(--tablehead-foreground); -} - -table.fieldtable td.fieldtype, .fieldtable td.fieldname, .fieldtable td.fielddoc, .fieldtable th { - border-bottom: 1px solid var(--separator-color); - border-right: 1px solid var(--separator-color); -} - -table.fieldtable tr:last-child td:first-child { - border-bottom-left-radius: var(--border-radius-small); -} - -table.fieldtable tr:last-child td:last-child { - border-bottom-right-radius: var(--border-radius-small); -} - -.memberdecls td.glow, .fieldtable tr.glow { - background-color: var(--primary-light-color); - box-shadow: none; -} - -table.memberdecls { - display: block; - -webkit-tap-highlight-color: transparent; -} - -table.memberdecls tr[class^='memitem'] { - font-family: var(--font-family-monospace); - font-size: var(--code-font-size); -} - -table.memberdecls tr[class^='memitem'] .memTemplParams { - font-family: var(--font-family-monospace); - font-size: var(--code-font-size); - color: var(--primary-dark-color); - white-space: normal; -} - -table.memberdecls .memItemLeft, -table.memberdecls .memItemRight, -table.memberdecls .memTemplItemLeft, -table.memberdecls .memTemplItemRight, -table.memberdecls .memTemplParams { - transition: none; - padding-top: var(--spacing-small); - padding-bottom: var(--spacing-small); - border-top: 1px solid var(--separator-color); - border-bottom: 1px solid var(--separator-color); - background-color: var(--fragment-background); -} - -table.memberdecls .memTemplItemLeft, -table.memberdecls .memTemplItemRight { - padding-top: 2px; -} - -table.memberdecls .memTemplParams { - border-bottom: 0; - border-left: 1px solid var(--separator-color); - border-right: 1px solid var(--separator-color); - border-radius: var(--border-radius-small) var(--border-radius-small) 0 0; - padding-bottom: var(--spacing-small); -} - -table.memberdecls .memTemplItemLeft { - border-radius: 0 0 0 var(--border-radius-small); - border-left: 1px solid var(--separator-color); - border-top: 0; -} - -table.memberdecls .memTemplItemRight { - border-radius: 0 0 var(--border-radius-small) 0; - border-right: 1px solid var(--separator-color); - padding-left: 0; - border-top: 0; -} - -table.memberdecls .memItemLeft { - border-radius: var(--border-radius-small) 0 0 var(--border-radius-small); - border-left: 1px solid var(--separator-color); - padding-left: var(--spacing-medium); - padding-right: 0; -} - -table.memberdecls .memItemRight { - border-radius: 0 var(--border-radius-small) var(--border-radius-small) 0; - border-right: 1px solid var(--separator-color); - padding-right: var(--spacing-medium); - padding-left: 0; - -} - -table.memberdecls .mdescLeft, table.memberdecls .mdescRight { - background: none; - color: var(--page-foreground-color); - padding: var(--spacing-small) 0; -} - -table.memberdecls .memItemLeft, -table.memberdecls .memTemplItemLeft { - padding-right: var(--spacing-medium); -} - -table.memberdecls .memSeparator { - background: var(--page-background-color); - height: var(--spacing-large); - border: 0; - transition: none; -} - -table.memberdecls .groupheader { - margin-bottom: var(--spacing-large); -} - -table.memberdecls .inherit_header td { - padding: 0 0 var(--spacing-medium) 0; - text-indent: -12px; - color: var(--page-secondary-foreground-color); -} - -table.memberdecls img[src="closed.png"], -table.memberdecls img[src="open.png"], -div.dynheader img[src="open.png"], -div.dynheader img[src="closed.png"] { - width: 0; - height: 0; - border-left: 4px solid transparent; - border-right: 4px solid transparent; - border-top: 5px solid var(--primary-color); - margin-top: 8px; - display: block; - float: left; - margin-left: -10px; - transition: transform var(--animation-duration) ease-out; -} - -table.memberdecls img { - margin-right: 10px; -} - -table.memberdecls img[src="closed.png"], -div.dynheader img[src="closed.png"] { - transform: rotate(-90deg); - -} - -.compoundTemplParams { - font-family: var(--font-family-monospace); - color: var(--primary-dark-color); - font-size: var(--code-font-size); -} - -@media screen and (max-width: 767px) { - - table.memberdecls .memItemLeft, - table.memberdecls .memItemRight, - table.memberdecls .mdescLeft, - table.memberdecls .mdescRight, - table.memberdecls .memTemplItemLeft, - table.memberdecls .memTemplItemRight, - table.memberdecls .memTemplParams { - display: block; - text-align: left; - padding-left: var(--spacing-large); - margin: 0 calc(0px - var(--spacing-large)) 0 calc(0px - var(--spacing-large)); - border-right: none; - border-left: none; - border-radius: 0; - white-space: normal; - } - - table.memberdecls .memItemLeft, - table.memberdecls .mdescLeft, - table.memberdecls .memTemplItemLeft { - border-bottom: 0; - padding-bottom: 0; - } - - table.memberdecls .memTemplItemLeft { - padding-top: 0; - } - - table.memberdecls .mdescLeft { - margin-bottom: calc(0px - var(--page-font-size)); - } - - table.memberdecls .memItemRight, - table.memberdecls .mdescRight, - table.memberdecls .memTemplItemRight { - border-top: 0; - padding-top: 0; - padding-right: var(--spacing-large); - overflow-x: auto; - } - - table.memberdecls tr[class^='memitem']:not(.inherit) { - display: block; - width: calc(100vw - 2 * var(--spacing-large)); - } - - table.memberdecls .mdescRight { - color: var(--page-foreground-color); - } - - table.memberdecls tr.inherit { - visibility: hidden; - } - - table.memberdecls tr[style="display: table-row;"] { - display: block !important; - visibility: visible; - width: calc(100vw - 2 * var(--spacing-large)); - animation: fade .5s; - } - - @keyframes fade { - 0% { - opacity: 0; - max-height: 0; - } - - 100% { - opacity: 1; - max-height: 200px; - } - } -} - - -/* - Horizontal Rule - */ - -hr { - margin-top: var(--spacing-large); - margin-bottom: var(--spacing-large); - height: 1px; - background-color: var(--separator-color); - border: 0; -} - -.contents hr { - box-shadow: 100px 0 0 var(--separator-color), - -100px 0 0 var(--separator-color), - 500px 0 0 var(--separator-color), - -500px 0 0 var(--separator-color), - 1500px 0 0 var(--separator-color), - -1500px 0 0 var(--separator-color), - 2000px 0 0 var(--separator-color), - -2000px 0 0 var(--separator-color); -} - -.contents img, .contents .center, .contents center, .contents div.image object { - max-width: 100%; - overflow: auto; -} - -@media screen and (max-width: 767px) { - .contents .dyncontent > .center, .contents > center { - margin-left: calc(0px - var(--spacing-large)); - margin-right: calc(0px - var(--spacing-large)); - max-width: calc(100% + 2 * var(--spacing-large)); - } -} - -/* - Directories - */ -div.directory { - border-top: 1px solid var(--separator-color); - border-bottom: 1px solid var(--separator-color); - width: auto; -} - -table.directory { - font-family: var(--font-family); - font-size: var(--page-font-size); - font-weight: normal; - width: 100%; -} - -table.directory td.entry, table.directory td.desc { - padding: calc(var(--spacing-small) / 2) var(--spacing-small); - line-height: var(--table-line-height); -} - -table.directory tr.even td:last-child { - border-radius: 0 var(--border-radius-small) var(--border-radius-small) 0; -} - -table.directory tr.even td:first-child { - border-radius: var(--border-radius-small) 0 0 var(--border-radius-small); -} - -table.directory tr.even:last-child td:last-child { - border-radius: 0 var(--border-radius-small) 0 0; -} - -table.directory tr.even:last-child td:first-child { - border-radius: var(--border-radius-small) 0 0 0; -} - -table.directory td.desc { - min-width: 250px; -} - -table.directory tr.even { - background-color: var(--odd-color); -} - -table.directory tr.odd { - background-color: transparent; -} - -.icona { - width: auto; - height: auto; - margin: 0 var(--spacing-small); -} - -.icon { - background: var(--primary-color); - border-radius: var(--border-radius-small); - font-size: var(--page-font-size); - padding: calc(var(--page-font-size) / 5); - line-height: var(--page-font-size); - transform: scale(0.8); - height: auto; - width: var(--page-font-size); - user-select: none; -} - -.iconfopen, .icondoc, .iconfclosed { - background-position: center; - margin-bottom: 0; - height: var(--table-line-height); -} - -.icondoc { - filter: saturate(0.2); -} - -@media screen and (max-width: 767px) { - div.directory { - margin-left: calc(0px - var(--spacing-large)); - margin-right: calc(0px - var(--spacing-large)); - } -} - -@media (prefers-color-scheme: dark) { - html:not(.light-mode) .iconfopen, html:not(.light-mode) .iconfclosed { - filter: hue-rotate(180deg) invert(); - } -} - -html.dark-mode .iconfopen, html.dark-mode .iconfclosed { - filter: hue-rotate(180deg) invert(); -} - -/* - Class list - */ - -.classindex dl.odd { - background: var(--odd-color); - border-radius: var(--border-radius-small); -} - -.classindex dl.even { - background-color: transparent; -} - -/* - Class Index Doxygen 1.8 -*/ - -table.classindex { - margin-left: 0; - margin-right: 0; - width: 100%; -} - -table.classindex table div.ah { - background-image: none; - background-color: initial; - border-color: var(--separator-color); - color: var(--page-foreground-color); - box-shadow: var(--box-shadow); - border-radius: var(--border-radius-large); - padding: var(--spacing-small); -} - -div.qindex { - background-color: var(--odd-color); - border-radius: var(--border-radius-small); - border: 1px solid var(--separator-color); - padding: var(--spacing-small) 0; -} - -/* - Footer and nav-path - */ - -#nav-path { - width: 100%; -} - -#nav-path ul { - background-image: none; - background: var(--page-background-color); - border: none; - border-top: 1px solid var(--separator-color); - border-bottom: 1px solid var(--separator-color); - border-bottom: 0; - box-shadow: 0 0.75px 0 var(--separator-color); - font-size: var(--navigation-font-size); -} - -img.footer { - width: 60px; -} - -.navpath li.footer { - color: var(--page-secondary-foreground-color); -} - -address.footer { - color: var(--page-secondary-foreground-color); - margin-bottom: var(--spacing-large); -} - -#nav-path li.navelem { - background-image: none; - display: flex; - align-items: center; -} - -.navpath li.navelem a { - text-shadow: none; - display: inline-block; - color: var(--primary-color) !important; -} - -.navpath li.navelem b { - color: var(--primary-dark-color); - font-weight: 500; -} - -li.navelem { - padding: 0; - margin-left: -8px; -} - -li.navelem:first-child { - margin-left: var(--spacing-large); -} - -li.navelem:first-child:before { - display: none; -} - -#nav-path li.navelem:after { - content: ''; - border: 5px solid var(--page-background-color); - border-bottom-color: transparent; - border-right-color: transparent; - border-top-color: transparent; - transform: translateY(-1px) scaleY(4.2); - z-index: 10; - margin-left: 6px; -} - -#nav-path li.navelem:before { - content: ''; - border: 5px solid var(--separator-color); - border-bottom-color: transparent; - border-right-color: transparent; - border-top-color: transparent; - transform: translateY(-1px) scaleY(3.2); - margin-right: var(--spacing-small); -} - -.navpath li.navelem a:hover { - color: var(--primary-color); -} - -/* - Scrollbars for Webkit -*/ - -#nav-tree::-webkit-scrollbar, -div.fragment::-webkit-scrollbar, -pre.fragment::-webkit-scrollbar, -div.memproto::-webkit-scrollbar, -.contents center::-webkit-scrollbar, -.contents .center::-webkit-scrollbar, -.contents table:not(.memberdecls):not(.mlabels):not(.fieldtable):not(.memname) tbody::-webkit-scrollbar, -div.contents .toc::-webkit-scrollbar, -.contents .dotgraph::-webkit-scrollbar, -.contents .tabs-overview-container::-webkit-scrollbar { - background: transparent; - width: calc(var(--webkit-scrollbar-size) + var(--webkit-scrollbar-padding) + var(--webkit-scrollbar-padding)); - height: calc(var(--webkit-scrollbar-size) + var(--webkit-scrollbar-padding) + var(--webkit-scrollbar-padding)); -} - -#nav-tree::-webkit-scrollbar-thumb, -div.fragment::-webkit-scrollbar-thumb, -pre.fragment::-webkit-scrollbar-thumb, -div.memproto::-webkit-scrollbar-thumb, -.contents center::-webkit-scrollbar-thumb, -.contents .center::-webkit-scrollbar-thumb, -.contents table:not(.memberdecls):not(.mlabels):not(.fieldtable):not(.memname) tbody::-webkit-scrollbar-thumb, -div.contents .toc::-webkit-scrollbar-thumb, -.contents .dotgraph::-webkit-scrollbar-thumb, -.contents .tabs-overview-container::-webkit-scrollbar-thumb { - background-color: transparent; - border: var(--webkit-scrollbar-padding) solid transparent; - border-radius: calc(var(--webkit-scrollbar-padding) + var(--webkit-scrollbar-padding)); - background-clip: padding-box; -} - -#nav-tree:hover::-webkit-scrollbar-thumb, -div.fragment:hover::-webkit-scrollbar-thumb, -pre.fragment:hover::-webkit-scrollbar-thumb, -div.memproto:hover::-webkit-scrollbar-thumb, -.contents center:hover::-webkit-scrollbar-thumb, -.contents .center:hover::-webkit-scrollbar-thumb, -.contents table:not(.memberdecls):not(.mlabels):not(.fieldtable):not(.memname) tbody:hover::-webkit-scrollbar-thumb, -div.contents .toc:hover::-webkit-scrollbar-thumb, -.contents .dotgraph:hover::-webkit-scrollbar-thumb, -.contents .tabs-overview-container:hover::-webkit-scrollbar-thumb { - background-color: var(--webkit-scrollbar-color); -} - -#nav-tree::-webkit-scrollbar-track, -div.fragment::-webkit-scrollbar-track, -pre.fragment::-webkit-scrollbar-track, -div.memproto::-webkit-scrollbar-track, -.contents center::-webkit-scrollbar-track, -.contents .center::-webkit-scrollbar-track, -.contents table:not(.memberdecls):not(.mlabels):not(.fieldtable):not(.memname) tbody::-webkit-scrollbar-track, -div.contents .toc::-webkit-scrollbar-track, -.contents .dotgraph::-webkit-scrollbar-track, -.contents .tabs-overview-container::-webkit-scrollbar-track { - background: transparent; -} - -#nav-tree::-webkit-scrollbar-corner { - background-color: var(--side-nav-background); -} - -#nav-tree, -div.fragment, -pre.fragment, -div.memproto, -.contents center, -.contents .center, -.contents table:not(.memberdecls):not(.mlabels):not(.fieldtable):not(.memname) tbody, -div.contents .toc { - overflow-x: auto; - overflow-x: overlay; -} - -#nav-tree { - overflow-x: auto; - overflow-y: auto; - overflow-y: overlay; -} - -/* - Scrollbars for Firefox -*/ - -#nav-tree, -div.fragment, -pre.fragment, -div.memproto, -.contents center, -.contents .center, -.contents table:not(.memberdecls):not(.mlabels):not(.fieldtable):not(.memname) tbody, -div.contents .toc, -.contents .dotgraph, -.contents .tabs-overview-container { - scrollbar-width: thin; -} - -/* - Optional Dark mode toggle button -*/ - -doxygen-awesome-dark-mode-toggle { - display: inline-block; - margin: 0 0 0 var(--spacing-small); - padding: 0; - width: var(--searchbar-height); - height: var(--searchbar-height); - background: none; - border: none; - border-radius: var(--searchbar-height); - vertical-align: middle; - text-align: center; - line-height: var(--searchbar-height); - font-size: 22px; - display: flex; - align-items: center; - justify-content: center; - user-select: none; - cursor: pointer; -} - -doxygen-awesome-dark-mode-toggle > svg { - transition: transform var(--animation-duration) ease-in-out; -} - -doxygen-awesome-dark-mode-toggle:active > svg { - transform: scale(.5); -} - -doxygen-awesome-dark-mode-toggle:hover { - background-color: rgba(0,0,0,.03); -} - -html.dark-mode doxygen-awesome-dark-mode-toggle:hover { - background-color: rgba(0,0,0,.18); -} - -/* - Optional fragment copy button -*/ -.doxygen-awesome-fragment-wrapper { - position: relative; -} - -doxygen-awesome-fragment-copy-button { - opacity: 0; - background: var(--fragment-background); - width: 28px; - height: 28px; - position: absolute; - right: calc(var(--spacing-large) - (var(--spacing-large) / 2.5)); - top: calc(var(--spacing-large) - (var(--spacing-large) / 2.5)); - border: 1px solid var(--fragment-foreground); - cursor: pointer; - border-radius: var(--border-radius-small); - display: flex; - justify-content: center; - align-items: center; -} - -.doxygen-awesome-fragment-wrapper:hover doxygen-awesome-fragment-copy-button, doxygen-awesome-fragment-copy-button.success { - opacity: .28; -} - -doxygen-awesome-fragment-copy-button:hover, doxygen-awesome-fragment-copy-button.success { - opacity: 1 !important; -} - -doxygen-awesome-fragment-copy-button:active:not([class~=success]) svg { - transform: scale(.91); -} - -doxygen-awesome-fragment-copy-button svg { - fill: var(--fragment-foreground); - width: 18px; - height: 18px; -} - -doxygen-awesome-fragment-copy-button.success svg { - fill: rgb(14, 168, 14); -} - -doxygen-awesome-fragment-copy-button.success { - border-color: rgb(14, 168, 14); -} - -@media screen and (max-width: 767px) { - .textblock > .doxygen-awesome-fragment-wrapper > doxygen-awesome-fragment-copy-button, - .textblock li > .doxygen-awesome-fragment-wrapper > doxygen-awesome-fragment-copy-button, - .memdoc li > .doxygen-awesome-fragment-wrapper > doxygen-awesome-fragment-copy-button, - .memdoc > .doxygen-awesome-fragment-wrapper > doxygen-awesome-fragment-copy-button, - dl dd > .doxygen-awesome-fragment-wrapper > doxygen-awesome-fragment-copy-button { - right: 0; - } -} - -/* - Optional paragraph link button -*/ - -a.anchorlink { - font-size: 90%; - margin-left: var(--spacing-small); - color: var(--page-foreground-color) !important; - text-decoration: none; - opacity: .15; - display: none; - transition: opacity var(--animation-duration) ease-in-out, color var(--animation-duration) ease-in-out; -} - -a.anchorlink svg { - fill: var(--page-foreground-color); -} - -h3 a.anchorlink svg, h4 a.anchorlink svg { - margin-bottom: -3px; - margin-top: -4px; -} - -a.anchorlink:hover { - opacity: .45; -} - -h2:hover a.anchorlink, h1:hover a.anchorlink, h3:hover a.anchorlink, h4:hover a.anchorlink { - display: inline-block; -} - -/* - Optional tab feature -*/ - -.tabbed ul { - padding-inline-start: 0px; - margin: 0; - padding: var(--spacing-small) 0; -} - -.tabbed li { - display: none; -} - -.tabbed li.selected { - display: block; -} - -.tabs-overview-container { - overflow-x: auto; - display: block; - overflow-y: visible; -} - -.tabs-overview { - border-bottom: 1px solid var(--separator-color); - display: flex; - flex-direction: row; -} - -@media screen and (max-width: 767px) { - .tabs-overview-container { - margin: 0 calc(0px - var(--spacing-large)); - } - .tabs-overview { - padding: 0 var(--spacing-large) - } -} - -.tabs-overview button.tab-button { - color: var(--page-foreground-color); - margin: 0; - border: none; - background: transparent; - padding: calc(var(--spacing-large) / 2) 0; - display: inline-block; - font-size: var(--page-font-size); - cursor: pointer; - box-shadow: 0 1px 0 0 var(--separator-color); - position: relative; - - -webkit-tap-highlight-color: transparent; -} - -.tabs-overview button.tab-button .tab-title::before { - display: block; - content: attr(title); - font-weight: 600; - height: 0; - overflow: hidden; - visibility: hidden; -} - -.tabs-overview button.tab-button .tab-title { - float: left; - white-space: nowrap; - font-weight: normal; - padding: calc(var(--spacing-large) / 2) var(--spacing-large); - border-radius: var(--border-radius-medium); - transition: background-color var(--animation-duration) ease-in-out, font-weight var(--animation-duration) ease-in-out; -} - -.tabs-overview button.tab-button:not(:last-child) .tab-title { - box-shadow: 8px 0 0 -7px var(--separator-color); -} - -.tabs-overview button.tab-button:hover .tab-title { - background: var(--separator-color); - box-shadow: none; -} - -.tabs-overview button.tab-button.active .tab-title { - font-weight: 600; -} - -.tabs-overview button.tab-button::after { - content: ''; - display: block; - position: absolute; - left: 0; - bottom: 0; - right: 0; - height: 0; - width: 0%; - margin: 0 auto; - border-radius: var(--border-radius-small) var(--border-radius-small) 0 0; - background-color: var(--primary-color); - transition: width var(--animation-duration) ease-in-out, height var(--animation-duration) ease-in-out; -} - -.tabs-overview button.tab-button.active::after { - width: 100%; - box-sizing: border-box; - height: 3px; -} - - -/* - Navigation Buttons -*/ - -.section_buttons:not(:empty) { - margin-top: calc(var(--spacing-large) * 3); -} - -.section_buttons table.markdownTable { - display: block; - width: 100%; -} - -.section_buttons table.markdownTable tbody { - display: table !important; - width: 100%; - box-shadow: none; - border-spacing: 10px; -} - -.section_buttons table.markdownTable td { - padding: 0; -} - -.section_buttons table.markdownTable th { - display: none; -} - -.section_buttons table.markdownTable tr.markdownTableHead { - border: none; -} - -.section_buttons tr th, .section_buttons tr td { - background: none; - border: none; - padding: var(--spacing-large) 0 var(--spacing-small); -} - -.section_buttons a { - display: inline-block; - border: 1px solid var(--separator-color); - border-radius: var(--border-radius-medium); - color: var(--page-secondary-foreground-color) !important; - text-decoration: none; - transition: color var(--animation-duration) ease-in-out, background-color var(--animation-duration) ease-in-out; -} - -.section_buttons a:hover { - color: var(--page-foreground-color) !important; - background-color: var(--odd-color); -} - -.section_buttons tr td.markdownTableBodyLeft a { - padding: var(--spacing-medium) var(--spacing-large) var(--spacing-medium) calc(var(--spacing-large) / 2); -} - -.section_buttons tr td.markdownTableBodyRight a { - padding: var(--spacing-medium) calc(var(--spacing-large) / 2) var(--spacing-medium) var(--spacing-large); -} - -.section_buttons tr td.markdownTableBodyLeft a::before, -.section_buttons tr td.markdownTableBodyRight a::after { - color: var(--page-secondary-foreground-color) !important; - display: inline-block; - transition: color .08s ease-in-out, transform .09s ease-in-out; -} - -.section_buttons tr td.markdownTableBodyLeft a::before { - content: '〈'; - padding-right: var(--spacing-large); -} - - -.section_buttons tr td.markdownTableBodyRight a::after { - content: '〉'; - padding-left: var(--spacing-large); -} - - -.section_buttons tr td.markdownTableBodyLeft a:hover::before { - color: var(--page-foreground-color) !important; - transform: translateX(-3px); -} - -.section_buttons tr td.markdownTableBodyRight a:hover::after { - color: var(--page-foreground-color) !important; - transform: translateX(3px); -} - -@media screen and (max-width: 450px) { - .section_buttons a { - width: 100%; - box-sizing: border-box; - } - - .section_buttons tr td:nth-of-type(1).markdownTableBodyLeft a { - border-radius: var(--border-radius-medium) 0 0 var(--border-radius-medium); - border-right: none; - } - - .section_buttons tr td:nth-of-type(2).markdownTableBodyRight a { - border-radius: 0 var(--border-radius-medium) var(--border-radius-medium) 0; - } -} diff --git a/Docs/licenses/bsd.txt b/Docs/licenses/bsd.txt deleted file mode 100644 index fa6e928b8d2..00000000000 --- a/Docs/licenses/bsd.txt +++ /dev/null @@ -1,23 +0,0 @@ -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY -EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/Docs/licenses/freeimage.txt b/Docs/licenses/freeimage.txt deleted file mode 100644 index 479fb4d5119..00000000000 --- a/Docs/licenses/freeimage.txt +++ /dev/null @@ -1,142 +0,0 @@ -FreeImage Public License - Version 1.0 ---------------------------------------------- - -1. Definitions. - -1.1. "Contributor" means each entity that creates or contributes to the creation of Modifications. - -1.2. "Contributor Version" means the combination of the Original Code, prior Modifications used by a Contributor, and the Modifications made by that particular Contributor. - -1.3. "Covered Code" means the Original Code or Modifications or the combination of the Original Code and Modifications, in each case including portions thereof. - -1.4. "Electronic Distribution Mechanism" means a mechanism generally accepted in the software development community for the electronic transfer of data. - -1.5. "Executable" means Covered Code in any form other than Source Code. - -1.6. "Initial Developer" means the individual or entity identified as the Initial Developer in the Source Code notice required by Exhibit A. - -1.7. "Larger Work" means a work which combines Covered Code or portions thereof with code not governed by the terms of this License. - -1.8. "License" means this document. - -1.9. "Modifications" means any addition to or deletion from the substance or structure of either the Original Code or any previous Modifications. When Covered Code is released as a series of files, a -Modification is: - -A. Any addition to or deletion from the contents of a file containing Original Code or previous Modifications. - -B. Any new file that contains any part of the Original Code or previous Modifications. - -1.10. "Original Code" means Source Code of computer software code which is described in the Source Code notice required by Exhibit A as Original Code, and which, at the time of its release under this License is not already Covered Code governed by this License. - -1.11. "Source Code" means the preferred form of the Covered Code for making modifications to it, including all modules it contains, plus any associated interface definition files, scripts used to control -compilation and installation of an Executable, or a list of source code differential comparisons against either the Original Code or another well known, available Covered Code of the Contributor's choice. The Source Code can be in a compressed or archival form, provided the appropriate decompression or de-archiving software is widely available for no charge. - -1.12. "You" means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License or a future version of this License issued under Section 6.1. For legal entities, "You" includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the -direction or management of such entity, whether by contract or otherwise, or (b) ownership of fifty percent (50%) or more of the outstanding shares or beneficial ownership of such entity. - -2. Source Code License. - -2.1. The Initial Developer Grant. -The Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license, subject to third party intellectual property claims: - -(a) to use, reproduce, modify, display, perform, sublicense and distribute the Original Code (or portions thereof) with or without Modifications, or as part of a Larger Work; and - -(b) under patents now or hereafter owned or controlled by Initial Developer, to make, have made, use and sell ("Utilize") the Original Code (or portions thereof), but solely to the extent that -any such patent is reasonably necessary to enable You to Utilize the Original Code (or portions thereof) and not to any greater extent that may be necessary to Utilize further Modifications or -combinations. - -2.2. Contributor Grant. -Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license, subject to third party intellectual property claims: - -(a) to use, reproduce, modify, display, perform, sublicense and distribute the Modifications created by such Contributor (or portions thereof) either on an unmodified basis, with other Modifications, as Covered Code or as part of a Larger Work; and - -(b) under patents now or hereafter owned or controlled by Contributor, to Utilize the Contributor Version (or portions thereof), but solely to the extent that any such patent is reasonably necessary to enable You to Utilize the Contributor Version (or portions thereof), and not to any greater extent that -may be necessary to Utilize further Modifications or combinations. - -3. Distribution Obligations. - -3.1. Application of License. -The Modifications which You create or to which You contribute are governed by the terms of this License, including without limitation Section 2.2. The Source Code version of Covered Code may be distributed only under the terms of this License or a future version of this License released under Section 6.1, and You must include a copy of this License with every copy of the Source Code You distribute. You may not offer or impose any terms on any Source Code version that alters or -restricts the applicable version of this License or the recipients' rights hereunder. However, You may include an additional document offering the additional rights described in Section 3.5. - -3.2. Availability of Source Code. -Any Modification which You create or to which You contribute must be made available in Source Code form under the terms of this License either on the same media as an Executable version or via an accepted Electronic Distribution Mechanism to anyone to whom you made an Executable version available; and if made available via Electronic Distribution Mechanism, must remain available for at least twelve (12) months after the date it initially became available, or at least six (6) months after a subsequent version of that particular Modification has been made available to such recipients. You are responsible for ensuring that the Source Code version remains available even if the Electronic Distribution Mechanism is maintained by a third party. - -3.3. Description of Modifications. -You must cause all Covered Code to which you contribute to contain a file documenting the changes You made to create that Covered Code and the date of any change. You must include a prominent statement that the Modification is derived, directly or indirectly, from Original Code provided by the Initial Developer and including the name of the Initial Developer in (a) the Source Code, and (b) in any notice in an Executable version or related documentation in which You describe the origin or ownership of the Covered Code. - -3.4. Intellectual Property Matters - -(a) Third Party Claims. -If You have knowledge that a party claims an intellectual property right in particular functionality or code (or its utilization under this License), you must include a text file with the source code distribution titled "LEGAL" which describes the claim and the party making the claim in sufficient detail that a recipient will know whom to contact. If you obtain such knowledge after You make Your Modification available as described in Section 3.2, You shall promptly modify the LEGAL file in all copies You make -available thereafter and shall take other steps (such as notifying appropriate mailing lists or newsgroups) reasonably calculated to inform those who received the Covered Code that new knowledge has been obtained. - -(b) Contributor APIs. -If Your Modification is an application programming interface and You own or control patents which are reasonably necessary to implement that API, you must also include this information in the LEGAL file. - -3.5. Required Notices. -You must duplicate the notice in Exhibit A in each file of the Source Code, and this License in any documentation for the Source Code, where You describe recipients' rights relating to Covered Code. If You created one or more Modification(s), You may add your name as a Contributor to the notice described in Exhibit A. If it is not possible to put such notice in a particular Source Code file due to its -structure, then you must include such notice in a location (such as a relevant directory file) where a user would be likely to look for such a notice. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Code. However, You may do so only on Your own behalf, and not on behalf of the Initial Developer or any Contributor. You must make it absolutely clear than any such warranty, support, indemnity or -liability obligation is offered by You alone, and You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of -warranty, support, indemnity or liability terms You offer. - -3.6. Distribution of Executable Versions. -You may distribute Covered Code in Executable form only if the requirements of Section 3.1-3.5 have been met for that Covered Code, and if You include a notice stating that the Source Code version of the Covered Code is available under the terms of this License, including a description of how and where You have fulfilled the obligations of Section 3.2. The notice must be conspicuously included in any notice in an Executable version, related documentation or collateral in which You -describe recipients' rights relating to the Covered Code. You may distribute the Executable version of Covered Code under a license of Your choice, which may contain terms different from this License, -provided that You are in compliance with the terms of this License and that the license for the Executable version does not attempt to limit or alter the recipient's rights in the Source Code version from the rights set forth in this License. If You distribute the Executable version under a different license You must make it absolutely clear that any terms which differ from this License are offered by You alone, not by the Initial Developer or any Contributor. You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of any such terms You offer. - -3.7. Larger Works. -You may create a Larger Work by combining Covered Code with other code not governed by the terms of this License and distribute the Larger Work as a single product. In such a case, You must make sure the requirements of this License are fulfilled for the Covered Code. - -4. Inability to Comply Due to Statute or Regulation. - -If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Code due to statute or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be included in the LEGAL file described in Section 3.4 and must be included with all distributions of the Source Code. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. - -5. Application of this License. - -This License applies to code to which the Initial Developer has attached the notice in Exhibit A, and to related Covered Code. - -6. Versions of the License. - -6.1. New Versions. -Floris van den Berg may publish revised and/or new versions of the License from time to time. Each version will be given a distinguishing version number. - -6.2. Effect of New Versions. -Once Covered Code has been published under a particular version of the License, You may always continue to use it under the terms of that version. You may also choose to use such Covered Code under the terms of any subsequent version of the License published by Floris van den Berg -No one other than Floris van den Berg has the right to modify the terms applicable to Covered Code created under this License. - -6.3. Derivative Works. -If you create or use a modified version of this License (which you may only do in order to apply it to code which is not already Covered Code governed by this License), you must (a) rename Your license so that the phrases "FreeImage", `FreeImage Public License", "FIPL", or any confusingly similar phrase do not appear anywhere in your license and (b) otherwise make it clear that your version of the license contains terms which differ from the FreeImage Public License. (Filling in the name of the Initial Developer, Original Code or Contributor in the notice described in Exhibit A shall not of themselves be deemed to be modifications of this License.) - -7. DISCLAIMER OF WARRANTY. - -COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. - -8. TERMINATION. - -This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. All sublicenses to the Covered Code which are properly granted shall survive any termination of this License. Provisions which, by their nature, must remain in effect beyond the termination of this License shall survive. - -9. LIMITATION OF LIABILITY. - -UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO YOU OR ANY OTHER PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE -EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THAT EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU. - -10. U.S. GOVERNMENT END USERS. - -The Covered Code is a "commercial item," as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer software" and "commercial computer software documentation," as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered Code with only those rights set forth herein. - -11. MISCELLANEOUS. - -This License represents the complete agreement concerning subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. This License shall be governed by Dutch law provisions (except to the extent applicable law, if any, provides otherwise), excluding its conflict-of-law provisions. With respect to disputes in which at least one party is a citizen of, or an entity chartered or registered to do business in, the The Netherlands: (a) unless otherwise agreed in writing, all disputes relating to this License (excepting any dispute relating to intellectual property rights) shall be subject to final and binding arbitration, with the losing party paying all costs of arbitration; (b) any arbitration relating to this Agreement shall be held in Almelo, The Netherlands; and (c) any litigation relating to this Agreement shall be subject to the jurisdiction of the court of Almelo, The Netherlands with the losing party responsible for costs, including without limitation, court costs and reasonable attorneys fees and expenses. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not apply to this License. - -12. RESPONSIBILITY FOR CLAIMS. - -Except in cases where another Contributor has failed to comply with Section 3.4, You are responsible for damages arising, directly or indirectly, out of Your utilization of rights under this License, based -on the number of copies of Covered Code you made available, the revenues you received from utilizing such rights, and other relevant factors. You agree to work with affected parties to distribute -responsibility on an equitable basis. - -EXHIBIT A. - -"The contents of this file are subject to the FreeImage Public License Version 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://home.wxs.nl/~flvdberg/freeimage-license.txt - -Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. \ No newline at end of file diff --git a/Docs/licenses/freetype.txt b/Docs/licenses/freetype.txt deleted file mode 100644 index c3fb425343e..00000000000 --- a/Docs/licenses/freetype.txt +++ /dev/null @@ -1,170 +0,0 @@ - The FreeType Project LICENSE - ---------------------------- - - 2006-Jan-27 - - Copyright 1996-2002, 2006 by - David Turner, Robert Wilhelm, and Werner Lemberg - - - -Introduction -============ - - The FreeType Project is distributed in several archive packages; - some of them may contain, in addition to the FreeType font engine, - various tools and contributions which rely on, or relate to, the - FreeType Project. - - This license applies to all files found in such packages, and - which do not fall under their own explicit license. The license - affects thus the FreeType font engine, the test programs, - documentation and makefiles, at the very least. - - This license was inspired by the BSD, Artistic, and IJG - (Independent JPEG Group) licenses, which all encourage inclusion - and use of free software in commercial and freeware products - alike. As a consequence, its main points are that: - - o We don't promise that this software works. However, we will be - interested in any kind of bug reports. (`as is' distribution) - - o You can use this software for whatever you want, in parts or - full form, without having to pay us. (`royalty-free' usage) - - o You may not pretend that you wrote this software. If you use - it, or only parts of it, in a program, you must acknowledge - somewhere in your documentation that you have used the - FreeType code. (`credits') - - We specifically permit and encourage the inclusion of this - software, with or without modifications, in commercial products. - We disclaim all warranties covering The FreeType Project and - assume no liability related to The FreeType Project. - - - Finally, many people asked us for a preferred form for a - credit/disclaimer to use in compliance with this license. We thus - encourage you to use the following text: - - """ - Portions of this software are copyright © The FreeType - Project (www.freetype.org). All rights reserved. - """ - - Please replace with the value from the FreeType version you - actually use. - - -Legal Terms -=========== - -0. Definitions --------------- - - Throughout this license, the terms `package', `FreeType Project', - and `FreeType archive' refer to the set of files originally - distributed by the authors (David Turner, Robert Wilhelm, and - Werner Lemberg) as the `FreeType Project', be they named as alpha, - beta or final release. - - `You' refers to the licensee, or person using the project, where - `using' is a generic term including compiling the project's source - code as well as linking it to form a `program' or `executable'. - This program is referred to as `a program using the FreeType - engine'. - - This license applies to all files distributed in the original - FreeType Project, including all source code, binaries and - documentation, unless otherwise stated in the file in its - original, unmodified form as distributed in the original archive. - If you are unsure whether or not a particular file is covered by - this license, you must contact us to verify this. - - The FreeType Project is copyright (C) 1996-2000 by David Turner, - Robert Wilhelm, and Werner Lemberg. All rights reserved except as - specified below. - -1. No Warranty --------------- - - THE FREETYPE PROJECT IS PROVIDED `AS IS' WITHOUT WARRANTY OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE. IN NO EVENT WILL ANY OF THE AUTHORS OR COPYRIGHT HOLDERS - BE LIABLE FOR ANY DAMAGES CAUSED BY THE USE OR THE INABILITY TO - USE, OF THE FREETYPE PROJECT. - -2. Redistribution ------------------ - - This license grants a worldwide, royalty-free, perpetual and - irrevocable right and license to use, execute, perform, compile, - display, copy, create derivative works of, distribute and - sublicense the FreeType Project (in both source and object code - forms) and derivative works thereof for any purpose; and to - authorize others to exercise some or all of the rights granted - herein, subject to the following conditions: - - o Redistribution of source code must retain this license file - (`FTL.TXT') unaltered; any additions, deletions or changes to - the original files must be clearly indicated in accompanying - documentation. The copyright notices of the unaltered, - original files must be preserved in all copies of source - files. - - o Redistribution in binary form must provide a disclaimer that - states that the software is based in part of the work of the - FreeType Team, in the distribution documentation. We also - encourage you to put an URL to the FreeType web page in your - documentation, though this isn't mandatory. - - These conditions apply to any software derived from or based on - the FreeType Project, not just the unmodified files. If you use - our work, you must acknowledge us. However, no fee need be paid - to us. - -3. Advertising --------------- - - Neither the FreeType authors and contributors nor you shall use - the name of the other for commercial, advertising, or promotional - purposes without specific prior written permission. - - We suggest, but do not require, that you use one or more of the - following phrases to refer to this software in your documentation - or advertising materials: `FreeType Project', `FreeType Engine', - `FreeType library', or `FreeType Distribution'. - - As you have not signed this license, you are not required to - accept it. However, as the FreeType Project is copyrighted - material, only this license, or another one contracted with the - authors, grants you the right to use, distribute, and modify it. - Therefore, by using, distributing, or modifying the FreeType - Project, you indicate that you understand and accept all the terms - of this license. - -4. Contacts ------------ - - There are two mailing lists related to FreeType: - - o freetype@nongnu.org - - Discusses general use and applications of FreeType, as well as - future and wanted additions to the library and distribution. - If you are looking for support, start in this list if you - haven't found anything to help you in the documentation. - - o freetype-devel@nongnu.org - - Discusses bugs, as well as engine internals, design issues, - specific licenses, porting, etc. - - Our home page can be found at - - http://www.freetype.org - - ---- end of FTL.TXT --- - diff --git a/Docs/licenses/libjpeg.txt b/Docs/licenses/libjpeg.txt deleted file mode 100644 index bc48c0b968e..00000000000 --- a/Docs/licenses/libjpeg.txt +++ /dev/null @@ -1,34 +0,0 @@ -The authors make NO WARRANTY or representation, either express or implied, -with respect to this software, its quality, accuracy, merchantability, or -fitness for a particular purpose. This software is provided "AS IS", and you, -its user, assume the entire risk as to its quality and accuracy. - -This software is copyright (C) 1991-1998, Thomas G. Lane. -All Rights Reserved except as specified below. - -Permission is hereby granted to use, copy, modify, and distribute this -software (or portions thereof) for any purpose, without fee, subject to these -conditions: -(1) If any part of the source code for this software is distributed, then this -README file must be included, with this copyright and no-warranty notice -unaltered; and any additions, deletions, or changes to the original files -must be clearly indicated in accompanying documentation. -(2) If only executable code is distributed, then the accompanying -documentation must state that "this software is based in part on the work of -the Independent JPEG Group". -(3) Permission for use of this software is granted only if the user accepts -full responsibility for any undesirable consequences; the authors accept -NO LIABILITY for damages of any kind. - -These conditions apply to any software derived from or based on the IJG code, -not just to the unmodified library. If you use our work, you ought to -acknowledge us. - -Permission is NOT granted for the use of any IJG author's name or company name -in advertising or publicity relating to this software or products derived from -it. This software may be referred to only as "the Independent JPEG Group's -software". - -We specifically permit and encourage the use of this software as the basis of -commercial products, provided that all warranty or liability claims are -assumed by the product vendor. diff --git a/Docs/licenses/libmng.txt b/Docs/licenses/libmng.txt deleted file mode 100644 index 6f49acef69d..00000000000 --- a/Docs/licenses/libmng.txt +++ /dev/null @@ -1,26 +0,0 @@ - The MNG Library is supplied "AS IS". The Contributing Authors - disclaim all warranties, expressed or implied, including, without - limitation, the warranties of merchantability and of fitness for any - purpose. The Contributing Authors assume no liability for direct, - indirect, incidental, special, exemplary, or consequential damages, - which may result from the use of the MNG Library, even if advised of - the possibility of such damage. - - Permission is hereby granted to use, copy, modify, and distribute this - source code, or portions hereof, for any purpose, without fee, subject - to the following restrictions: - - 1. The origin of this source code must not be misrepresented; - you must not claim that you wrote the original software. - - 2. Altered versions must be plainly marked as such and must not be - misrepresented as being the original source. - - 3. This Copyright notice may not be removed or altered from any source - or altered source distribution. - - The Contributing Authors specifically permit, without fee, and - encourage the use of this source code as a component to supporting - the MNG and JNG file format in commercial products. If you use this - source code in a product, acknowledgment would be highly appreciated. - diff --git a/Docs/licenses/libpng.txt b/Docs/licenses/libpng.txt deleted file mode 100644 index 91cd1b8294c..00000000000 --- a/Docs/licenses/libpng.txt +++ /dev/null @@ -1,109 +0,0 @@ -This copy of the libpng notices is provided for your convenience. In case of -any discrepancy between this copy and the notices in the file png.h that is -included in the libpng distribution, the latter shall prevail. - -COPYRIGHT NOTICE, DISCLAIMER, and LICENSE: - -If you modify libpng you may insert additional notices immediately following -this sentence. - -libpng versions 1.2.6, August 15, 2004, through 1.2.15, January 5, 2007, are -Copyright (c) 2004, 2006 Glenn Randers-Pehrson, and are -distributed according to the same disclaimer and license as libpng-1.2.5 -with the following individual added to the list of Contributing Authors - - Cosmin Truta - -libpng versions 1.0.7, July 1, 2000, through 1.2.5 - October 3, 2002, are -Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are -distributed according to the same disclaimer and license as libpng-1.0.6 -with the following individuals added to the list of Contributing Authors - - Simon-Pierre Cadieux - Eric S. Raymond - Gilles Vollant - -and with the following additions to the disclaimer: - - There is no warranty against interference with your enjoyment of the - library or against infringement. There is no warranty that our - efforts or the library will fulfill any of your particular purposes - or needs. This library is provided with all faults, and the entire - risk of satisfactory quality, performance, accuracy, and effort is with - the user. - -libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are -Copyright (c) 1998, 1999 Glenn Randers-Pehrson, and are -distributed according to the same disclaimer and license as libpng-0.96, -with the following individuals added to the list of Contributing Authors: - - Tom Lane - Glenn Randers-Pehrson - Willem van Schaik - -libpng versions 0.89, June 1996, through 0.96, May 1997, are -Copyright (c) 1996, 1997 Andreas Dilger -Distributed according to the same disclaimer and license as libpng-0.88, -with the following individuals added to the list of Contributing Authors: - - John Bowler - Kevin Bracey - Sam Bushell - Magnus Holmgren - Greg Roelofs - Tom Tanner - -libpng versions 0.5, May 1995, through 0.88, January 1996, are -Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc. - -For the purposes of this copyright and license, "Contributing Authors" -is defined as the following set of individuals: - - Andreas Dilger - Dave Martindale - Guy Eric Schalnat - Paul Schmidt - Tim Wegner - -The PNG Reference Library is supplied "AS IS". The Contributing Authors -and Group 42, Inc. disclaim all warranties, expressed or implied, -including, without limitation, the warranties of merchantability and of -fitness for any purpose. The Contributing Authors and Group 42, Inc. -assume no liability for direct, indirect, incidental, special, exemplary, -or consequential damages, which may result from the use of the PNG -Reference Library, even if advised of the possibility of such damage. - -Permission is hereby granted to use, copy, modify, and distribute this -source code, or portions hereof, for any purpose, without fee, subject -to the following restrictions: - -1. The origin of this source code must not be misrepresented. - -2. Altered versions must be plainly marked as such and must not - be misrepresented as being the original source. - -3. This Copyright notice may not be removed or altered from any - source or altered source distribution. - -The Contributing Authors and Group 42, Inc. specifically permit, without -fee, and encourage the use of this source code as a component to -supporting the PNG file format in commercial products. If you use this -source code in a product, acknowledgment is not required but would be -appreciated. - - -A "png_get_copyright" function is available, for convenient use in "about" -boxes and the like: - - printf("%s",png_get_copyright(NULL)); - -Also, the PNG logo (in PNG format, of course) is supplied in the -files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31). - -Libpng is OSI Certified Open Source Software. OSI Certified Open Source is a -certification mark of the Open Source Initiative. - -Glenn Randers-Pehrson -glennrp at users.sourceforge.net -January 5, 2007 - diff --git a/Docs/licenses/libtiff.txt b/Docs/licenses/libtiff.txt deleted file mode 100644 index 5562b21794b..00000000000 --- a/Docs/licenses/libtiff.txt +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 1988-1997 Sam Leffler -Copyright (c) 1991-1997 Silicon Graphics, Inc. - -Permission to use, copy, modify, distribute, and sell this software and -its documentation for any purpose is hereby granted without fee, provided -that (i) the above copyright notices and this permission notice appear in -all copies of the software and related documentation, and (ii) the names of -Sam Leffler and Silicon Graphics may not be used in any advertising or -publicity relating to the software without the specific, prior written -permission of Sam Leffler and Silicon Graphics. - -THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, -EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY -WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. - -IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR -ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, -OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, -WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF -LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE -OF THIS SOFTWARE. - diff --git a/Docs/licenses/mit.txt b/Docs/licenses/mit.txt deleted file mode 100644 index 38c7bb36d17..00000000000 --- a/Docs/licenses/mit.txt +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License - -Copyright (c) 2004 - 2006 Paul D Turner & The CEGUI Development Team - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Docs/licenses/mpl.txt b/Docs/licenses/mpl.txt deleted file mode 100644 index 1bf2b1279dd..00000000000 --- a/Docs/licenses/mpl.txt +++ /dev/null @@ -1,471 +0,0 @@ - MOZILLA PUBLIC LICENSE - Version 1.1 - - --------------- - -1. Definitions. - - 1.0.1. "Commercial Use" means distribution or otherwise making the - Covered Code available to a third party. - - 1.1. "Contributor" means each entity that creates or contributes to - the creation of Modifications. - - 1.2. "Contributor Version" means the combination of the Original - Code, prior Modifications used by a Contributor, and the Modifications - made by that particular Contributor. - - 1.3. "Covered Code" means the Original Code or Modifications or the - combination of the Original Code and Modifications, in each case - including portions thereof. - - 1.4. "Electronic Distribution Mechanism" means a mechanism generally - accepted in the software development community for the electronic - transfer of data. - - 1.5. "Executable" means Covered Code in any form other than Source - Code. - - 1.6. "Initial Developer" means the individual or entity identified - as the Initial Developer in the Source Code notice required by Exhibit - A. - - 1.7. "Larger Work" means a work which combines Covered Code or - portions thereof with code not governed by the terms of this License. - - 1.8. "License" means this document. - - 1.8.1. "Licensable" means having the right to grant, to the maximum - extent possible, whether at the time of the initial grant or - subsequently acquired, any and all of the rights conveyed herein. - - 1.9. "Modifications" means any addition to or deletion from the - substance or structure of either the Original Code or any previous - Modifications. When Covered Code is released as a series of files, a - Modification is: - A. Any addition to or deletion from the contents of a file - containing Original Code or previous Modifications. - - B. Any new file that contains any part of the Original Code or - previous Modifications. - - 1.10. "Original Code" means Source Code of computer software code - which is described in the Source Code notice required by Exhibit A as - Original Code, and which, at the time of its release under this - License is not already Covered Code governed by this License. - - 1.10.1. "Patent Claims" means any patent claim(s), now owned or - hereafter acquired, including without limitation, method, process, - and apparatus claims, in any patent Licensable by grantor. - - 1.11. "Source Code" means the preferred form of the Covered Code for - making modifications to it, including all modules it contains, plus - any associated interface definition files, scripts used to control - compilation and installation of an Executable, or source code - differential comparisons against either the Original Code or another - well known, available Covered Code of the Contributor's choice. The - Source Code can be in a compressed or archival form, provided the - appropriate decompression or de-archiving software is widely available - for no charge. - - 1.12. "You" (or "Your") means an individual or a legal entity - exercising rights under, and complying with all of the terms of, this - License or a future version of this License issued under Section 6.1. - For legal entities, "You" includes any entity which controls, is - controlled by, or is under common control with You. For purposes of - this definition, "control" means (a) the power, direct or indirect, - to cause the direction or management of such entity, whether by - contract or otherwise, or (b) ownership of more than fifty percent - (50%) of the outstanding shares or beneficial ownership of such - entity. - -2. Source Code License. - - 2.1. The Initial Developer Grant. - The Initial Developer hereby grants You a world-wide, royalty-free, - non-exclusive license, subject to third party intellectual property - claims: - (a) under intellectual property rights (other than patent or - trademark) Licensable by Initial Developer to use, reproduce, - modify, display, perform, sublicense and distribute the Original - Code (or portions thereof) with or without Modifications, and/or - as part of a Larger Work; and - - (b) under Patents Claims infringed by the making, using or - selling of Original Code, to make, have made, use, practice, - sell, and offer for sale, and/or otherwise dispose of the - Original Code (or portions thereof). - - (c) the licenses granted in this Section 2.1(a) and (b) are - effective on the date Initial Developer first distributes - Original Code under the terms of this License. - - (d) Notwithstanding Section 2.1(b) above, no patent license is - granted: 1) for code that You delete from the Original Code; 2) - separate from the Original Code; or 3) for infringements caused - by: i) the modification of the Original Code or ii) the - combination of the Original Code with other software or devices. - - 2.2. Contributor Grant. - Subject to third party intellectual property claims, each Contributor - hereby grants You a world-wide, royalty-free, non-exclusive license - - (a) under intellectual property rights (other than patent or - trademark) Licensable by Contributor, to use, reproduce, modify, - display, perform, sublicense and distribute the Modifications - created by such Contributor (or portions thereof) either on an - unmodified basis, with other Modifications, as Covered Code - and/or as part of a Larger Work; and - - (b) under Patent Claims infringed by the making, using, or - selling of Modifications made by that Contributor either alone - and/or in combination with its Contributor Version (or portions - of such combination), to make, use, sell, offer for sale, have - made, and/or otherwise dispose of: 1) Modifications made by that - Contributor (or portions thereof); and 2) the combination of - Modifications made by that Contributor with its Contributor - Version (or portions of such combination). - - (c) the licenses granted in Sections 2.2(a) and 2.2(b) are - effective on the date Contributor first makes Commercial Use of - the Covered Code. - - (d) Notwithstanding Section 2.2(b) above, no patent license is - granted: 1) for any code that Contributor has deleted from the - Contributor Version; 2) separate from the Contributor Version; - 3) for infringements caused by: i) third party modifications of - Contributor Version or ii) the combination of Modifications made - by that Contributor with other software (except as part of the - Contributor Version) or other devices; or 4) under Patent Claims - infringed by Covered Code in the absence of Modifications made by - that Contributor. - -3. Distribution Obligations. - - 3.1. Application of License. - The Modifications which You create or to which You contribute are - governed by the terms of this License, including without limitation - Section 2.2. The Source Code version of Covered Code may be - distributed only under the terms of this License or a future version - of this License released under Section 6.1, and You must include a - copy of this License with every copy of the Source Code You - distribute. You may not offer or impose any terms on any Source Code - version that alters or restricts the applicable version of this - License or the recipients' rights hereunder. However, You may include - an additional document offering the additional rights described in - Section 3.5. - - 3.2. Availability of Source Code. - Any Modification which You create or to which You contribute must be - made available in Source Code form under the terms of this License - either on the same media as an Executable version or via an accepted - Electronic Distribution Mechanism to anyone to whom you made an - Executable version available; and if made available via Electronic - Distribution Mechanism, must remain available for at least twelve (12) - months after the date it initially became available, or at least six - (6) months after a subsequent version of that particular Modification - has been made available to such recipients. You are responsible for - ensuring that the Source Code version remains available even if the - Electronic Distribution Mechanism is maintained by a third party. - - 3.3. Description of Modifications. - You must cause all Covered Code to which You contribute to contain a - file documenting the changes You made to create that Covered Code and - the date of any change. You must include a prominent statement that - the Modification is derived, directly or indirectly, from Original - Code provided by the Initial Developer and including the name of the - Initial Developer in (a) the Source Code, and (b) in any notice in an - Executable version or related documentation in which You describe the - origin or ownership of the Covered Code. - - 3.4. Intellectual Property Matters - (a) Third Party Claims. - If Contributor has knowledge that a license under a third party's - intellectual property rights is required to exercise the rights - granted by such Contributor under Sections 2.1 or 2.2, - Contributor must include a text file with the Source Code - distribution titled "LEGAL" which describes the claim and the - party making the claim in sufficient detail that a recipient will - know whom to contact. If Contributor obtains such knowledge after - the Modification is made available as described in Section 3.2, - Contributor shall promptly modify the LEGAL file in all copies - Contributor makes available thereafter and shall take other steps - (such as notifying appropriate mailing lists or newsgroups) - reasonably calculated to inform those who received the Covered - Code that new knowledge has been obtained. - - (b) Contributor APIs. - If Contributor's Modifications include an application programming - interface and Contributor has knowledge of patent licenses which - are reasonably necessary to implement that API, Contributor must - also include this information in the LEGAL file. - - (c) Representations. - Contributor represents that, except as disclosed pursuant to - Section 3.4(a) above, Contributor believes that Contributor's - Modifications are Contributor's original creation(s) and/or - Contributor has sufficient rights to grant the rights conveyed by - this License. - - 3.5. Required Notices. - You must duplicate the notice in Exhibit A in each file of the Source - Code. If it is not possible to put such notice in a particular Source - Code file due to its structure, then You must include such notice in a - location (such as a relevant directory) where a user would be likely - to look for such a notice. If You created one or more Modification(s) - You may add your name as a Contributor to the notice described in - Exhibit A. You must also duplicate this License in any documentation - for the Source Code where You describe recipients' rights or ownership - rights relating to Covered Code. You may choose to offer, and to - charge a fee for, warranty, support, indemnity or liability - obligations to one or more recipients of Covered Code. However, You - may do so only on Your own behalf, and not on behalf of the Initial - Developer or any Contributor. You must make it absolutely clear than - any such warranty, support, indemnity or liability obligation is - offered by You alone, and You hereby agree to indemnify the Initial - Developer and every Contributor for any liability incurred by the - Initial Developer or such Contributor as a result of warranty, - support, indemnity or liability terms You offer. - - 3.6. Distribution of Executable Versions. - You may distribute Covered Code in Executable form only if the - requirements of Section 3.1-3.5 have been met for that Covered Code, - and if You include a notice stating that the Source Code version of - the Covered Code is available under the terms of this License, - including a description of how and where You have fulfilled the - obligations of Section 3.2. The notice must be conspicuously included - in any notice in an Executable version, related documentation or - collateral in which You describe recipients' rights relating to the - Covered Code. You may distribute the Executable version of Covered - Code or ownership rights under a license of Your choice, which may - contain terms different from this License, provided that You are in - compliance with the terms of this License and that the license for the - Executable version does not attempt to limit or alter the recipient's - rights in the Source Code version from the rights set forth in this - License. If You distribute the Executable version under a different - license You must make it absolutely clear that any terms which differ - from this License are offered by You alone, not by the Initial - Developer or any Contributor. You hereby agree to indemnify the - Initial Developer and every Contributor for any liability incurred by - the Initial Developer or such Contributor as a result of any such - terms You offer. - - 3.7. Larger Works. - You may create a Larger Work by combining Covered Code with other code - not governed by the terms of this License and distribute the Larger - Work as a single product. In such a case, You must make sure the - requirements of this License are fulfilled for the Covered Code. - -4. Inability to Comply Due to Statute or Regulation. - - If it is impossible for You to comply with any of the terms of this - License with respect to some or all of the Covered Code due to - statute, judicial order, or regulation then You must: (a) comply with - the terms of this License to the maximum extent possible; and (b) - describe the limitations and the code they affect. Such description - must be included in the LEGAL file described in Section 3.4 and must - be included with all distributions of the Source Code. Except to the - extent prohibited by statute or regulation, such description must be - sufficiently detailed for a recipient of ordinary skill to be able to - understand it. - -5. Application of this License. - - This License applies to code to which the Initial Developer has - attached the notice in Exhibit A and to related Covered Code. - -6. Versions of the License. - - 6.1. New Versions. - Netscape Communications Corporation ("Netscape") may publish revised - and/or new versions of the License from time to time. Each version - will be given a distinguishing version number. - - 6.2. Effect of New Versions. - Once Covered Code has been published under a particular version of the - License, You may always continue to use it under the terms of that - version. You may also choose to use such Covered Code under the terms - of any subsequent version of the License published by Netscape. No one - other than Netscape has the right to modify the terms applicable to - Covered Code created under this License. - - 6.3. Derivative Works. - If You create or use a modified version of this License (which you may - only do in order to apply it to code which is not already Covered Code - governed by this License), You must (a) rename Your license so that - the phrases "Mozilla", "MOZILLAPL", "MOZPL", "Netscape", - "MPL", "NPL" or any confusingly similar phrase do not appear in your - license (except to note that your license differs from this License) - and (b) otherwise make it clear that Your version of the license - contains terms which differ from the Mozilla Public License and - Netscape Public License. (Filling in the name of the Initial - Developer, Original Code or Contributor in the notice described in - Exhibit A shall not of themselves be deemed to be modifications of - this License.) - -7. DISCLAIMER OF WARRANTY. - - COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, - WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, - WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF - DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. - THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE - IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, - YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE - COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER - OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF - ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. - -8. TERMINATION. - - 8.1. This License and the rights granted hereunder will terminate - automatically if You fail to comply with terms herein and fail to cure - such breach within 30 days of becoming aware of the breach. All - sublicenses to the Covered Code which are properly granted shall - survive any termination of this License. Provisions which, by their - nature, must remain in effect beyond the termination of this License - shall survive. - - 8.2. If You initiate litigation by asserting a patent infringement - claim (excluding declatory judgment actions) against Initial Developer - or a Contributor (the Initial Developer or Contributor against whom - You file such action is referred to as "Participant") alleging that: - - (a) such Participant's Contributor Version directly or indirectly - infringes any patent, then any and all rights granted by such - Participant to You under Sections 2.1 and/or 2.2 of this License - shall, upon 60 days notice from Participant terminate prospectively, - unless if within 60 days after receipt of notice You either: (i) - agree in writing to pay Participant a mutually agreeable reasonable - royalty for Your past and future use of Modifications made by such - Participant, or (ii) withdraw Your litigation claim with respect to - the Contributor Version against such Participant. If within 60 days - of notice, a reasonable royalty and payment arrangement are not - mutually agreed upon in writing by the parties or the litigation claim - is not withdrawn, the rights granted by Participant to You under - Sections 2.1 and/or 2.2 automatically terminate at the expiration of - the 60 day notice period specified above. - - (b) any software, hardware, or device, other than such Participant's - Contributor Version, directly or indirectly infringes any patent, then - any rights granted to You by such Participant under Sections 2.1(b) - and 2.2(b) are revoked effective as of the date You first made, used, - sold, distributed, or had made, Modifications made by that - Participant. - - 8.3. If You assert a patent infringement claim against Participant - alleging that such Participant's Contributor Version directly or - indirectly infringes any patent where such claim is resolved (such as - by license or settlement) prior to the initiation of patent - infringement litigation, then the reasonable value of the licenses - granted by such Participant under Sections 2.1 or 2.2 shall be taken - into account in determining the amount or value of any payment or - license. - - 8.4. In the event of termination under Sections 8.1 or 8.2 above, - all end user license agreements (excluding distributors and resellers) - which have been validly granted by You or any distributor hereunder - prior to termination shall survive termination. - -9. LIMITATION OF LIABILITY. - - UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT - (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL - DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE, - OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR - ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY - CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, - WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER - COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN - INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF - LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY - RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW - PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE - EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO - THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU. - -10. U.S. GOVERNMENT END USERS. - - The Covered Code is a "commercial item," as that term is defined in - 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer - software" and "commercial computer software documentation," as such - terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 - C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), - all U.S. Government End Users acquire Covered Code with only those - rights set forth herein. - -11. MISCELLANEOUS. - - This License represents the complete agreement concerning subject - matter hereof. If any provision of this License is held to be - unenforceable, such provision shall be reformed only to the extent - necessary to make it enforceable. This License shall be governed by - California law provisions (except to the extent applicable law, if - any, provides otherwise), excluding its conflict-of-law provisions. - With respect to disputes in which at least one party is a citizen of, - or an entity chartered or registered to do business in the United - States of America, any litigation relating to this License shall be - subject to the jurisdiction of the Federal Courts of the Northern - District of California, with venue lying in Santa Clara County, - California, with the losing party responsible for costs, including - without limitation, court costs and reasonable attorneys' fees and - expenses. The application of the United Nations Convention on - Contracts for the International Sale of Goods is expressly excluded. - Any law or regulation which provides that the language of a contract - shall be construed against the drafter shall not apply to this - License. - -12. RESPONSIBILITY FOR CLAIMS. - - As between Initial Developer and the Contributors, each party is - responsible for claims and damages arising, directly or indirectly, - out of its utilization of rights under this License and You agree to - work with Initial Developer and Contributors to distribute such - responsibility on an equitable basis. Nothing herein is intended or - shall be deemed to constitute any admission of liability. - -13. MULTIPLE-LICENSED CODE. - - Initial Developer may designate portions of the Covered Code as - "Multiple-Licensed". "Multiple-Licensed" means that the Initial - Developer permits you to utilize portions of the Covered Code under - Your choice of the NPL or the alternative licenses, if any, specified - by the Initial Developer in the file described in Exhibit A. - -EXHIBIT A -Mozilla Public License. - - ``The contents of this file are subject to the Mozilla Public License - Version 1.1 (the "License"); you may not use this file except in - compliance with the License. You may obtain a copy of the License at - http://www.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" - basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the - License for the specific language governing rights and limitations - under the License. - - The Original Code is ______________________________________. - - The Initial Developer of the Original Code is ________________________. - Portions created by ______________________ are Copyright (C) ______ - _______________________. All Rights Reserved. - - Contributor(s): ______________________________________. - - Alternatively, the contents of this file may be used under the terms - of the _____ license (the "[___] License"), in which case the - provisions of [______] License are applicable instead of those - above. If you wish to allow use of your version of this file only - under the terms of the [____] License and not to allow others to use - your version of this file under the MPL, indicate your decision by - deleting the provisions above and replace them with the notice and - other provisions required by the [___] License. If you do not delete - the provisions above, a recipient may use your version of this file - under either the MPL or the [___] License." - - [NOTE: The text of this Exhibit A may differ slightly from the text of - the notices in the Source Code files of the Original Code. You should - use the text of this Exhibit A rather than the text found in the - Original Code Source Code for Your Modifications.] - - diff --git a/Docs/licenses/uiuc.txt b/Docs/licenses/uiuc.txt deleted file mode 100644 index b8d2c742096..00000000000 --- a/Docs/licenses/uiuc.txt +++ /dev/null @@ -1,69 +0,0 @@ -============================================================================== -LLVM Release License -============================================================================== -University of Illinois/NCSA -Open Source License - -Copyright (c) 2003-2010 University of Illinois at Urbana-Champaign. -All rights reserved. - -Developed by: - - LLVM Team - - University of Illinois at Urbana-Champaign - - http://llvm.org - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal with -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimers. - - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimers in the - documentation and/or other materials provided with the distribution. - - * Neither the names of the LLVM Team, University of Illinois at - Urbana-Champaign, nor the names of its contributors may be used to - endorse or promote products derived from this Software without specific - prior written permission. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE -SOFTWARE. - -============================================================================== -Copyrights and Licenses for Third Party Software Distributed with LLVM: -============================================================================== -The LLVM software contains code written by third parties. Such software will -have its own individual LICENSE.TXT file in the directory in which it appears. -This file will describe the copyrights, license, and restrictions which apply -to that code. - -The disclaimer of warranty in the University of Illinois Open Source License -applies to all code in the LLVM Distribution, and nothing in any of the -other licenses gives permission to use the names of the LLVM Team or the -University of Illinois to endorse or promote products derived from this -Software. - -The following pieces of software have additional or alternate copyrights, -licenses, and/or restrictions: - -Program Directory -------- --------- -Autoconf llvm/autoconf - llvm/projects/ModuleMaker/autoconf - llvm/projects/sample/autoconf -CellSPU backend llvm/lib/Target/CellSPU/README.txt -Google Test llvm/utils/unittest/googletest -OpenBSD regex llvm/lib/Support/{reg*, COPYRIGHT.regex} diff --git a/Docs/licenses/zlib.txt b/Docs/licenses/zlib.txt deleted file mode 100644 index c635a8436ee..00000000000 --- a/Docs/licenses/zlib.txt +++ /dev/null @@ -1,26 +0,0 @@ -/* zlib.h -- interface of the 'zlib' general purpose compression library - version 1.2.3, July 18th, 2005 - - Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler - - 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. - - Jean-loup Gailly jloup@gzip.org - Mark Adler madler@alumni.caltech.edu - -*/ - diff --git a/Docs/ogre-logo.png b/Docs/ogre-logo.png deleted file mode 100644 index b1f4efdc250..00000000000 Binary files a/Docs/ogre-logo.png and /dev/null differ diff --git a/Docs/ogre_style.css b/Docs/ogre_style.css deleted file mode 100644 index 83d5137dc7e..00000000000 --- a/Docs/ogre_style.css +++ /dev/null @@ -1,12 +0,0 @@ -html { - --primary-color: #628768; -} - -@media (prefers-color-scheme: dark) { - html:not(.light-mode) { - --primary-color: #628768; - } - img.inline { - background-color: #d2dbde; - } -} \ No newline at end of file diff --git a/Docs/src/apimainpage.md b/Docs/src/apimainpage.md deleted file mode 100644 index da711dc06df..00000000000 --- a/Docs/src/apimainpage.md +++ /dev/null @@ -1,40 +0,0 @@ -# API Reference Start Page {#mainpage} - -# What is this? - -This is the complete API reference for OGRE (Object-Oriented Graphics Rendering Engine). Contained within are the -specifications for each namespace/module/class and the methods from those which you can refer to when writing code which uses OGRE. - -The API reference for a specific OGRE version can be found under: -- https://ogrecave.github.io/ogre/api/13 -- https://ogrecave.github.io/ogre/api/1.12 - -i.e. replace the last part with the version number, for example 14, 1.11, etc. - -# It's so BIG! - -Yes it is (and thank you for noticing). OGRE is a large and complex -system so the API documentation, whilst fully inclusive and the most -complete reference to OGRE that you'll find, is not the recommended way to -start learning. You will certainly want -to refer to this documentation once you have found your feet, and pretty soon -referring to it will become second nature. Until then, you should begin with -more "discussive" documentation such as: - -* [The Manual](@ref manual): The OGRE manual is a -general introduction to the OGRE principles and core components, and a -reference to various important parts of the OGRE system, especially the -script syntax for materials, particle systems, and overlays. - -* [The OGRE Tutorials](@ref tutorials): This is a gold mine for new and experienced users alike. - -We make an effort to document our classes fully so we hope you can find what -you need here. However, if you can't find it, or you're not sure where to -start looking, visit the main OGRE website and dip into the community areas -like the wiki and the forums to get some assistance. - -# License - -The OGRE rendering engine itself is licensed under the MIT License. More details can be found here.
-This documentation work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
-![](cc_licensebutton.png) diff --git a/Docs/src/bibliography.bib b/Docs/src/bibliography.bib deleted file mode 100644 index 3a6d4f0cf72..00000000000 --- a/Docs/src/bibliography.bib +++ /dev/null @@ -1,164 +0,0 @@ - -@inproceedings{WIL78, - author = {Lance Williams}, - title = {Casting curved shadows on curved surfaces}, - booktitle = {SIGGRAPH '78: Proceedings of the 5th annual conference on Computer graphics and interactive techniques}, - year = {1978}, - pages = {270--274}, - doi = {http://doi.acm.org/10.1145/800248.807402}, - publisher = {ACM Press}, - address = {New York, NY, USA}, - } - - -@inproceedings{MT04, - author = {Tobias Martin and Tiow-Seng Tan}, - title = {Anti-aliasing and Continuity with Trapezoidal Shadow Maps}, - booktitle = {Proceedings of the Eurographics Symposium on Rendering}, - year = {2004}, - location = {Norrk\"oping, Sweden}, - pages = {153--160}, - publisher = {Eurographics Association}, -} - -@inproceedings{WSP04, - author = {Michael Wimmer and Daniel Scherzer and Werner Purgathofer}, - title = {Light Space Perspective Shadow Maps}, - booktitle = {Proceedings of the Eurographics Symposium on Rendering}, - year = {2004}, - location = {Norrk\"oping, Sweden}, - publisher = {Eurographics Association}, -} - -@inproceedings{Chong04, - author = {Hamilton Y. Chong and Steven J. Gortler}, - title = {A lixel for every pixel}, - booktitle = {Proceedings of the Eurographics Symposium on Rendering}, - year = {2004}, - location = {Norrk\"oping, Sweden}, - publisher = {Eurographics Association}, -} - -@inproceedings{Chong06, - author = {Hamilton Y. Chong and Steven J. Gortler}, - title = {Scene Optimized Shadow Maps}, - booktitle = {Harvard Technical Report TR-11-06}, - year = {2006}, -} - -@inproceedings{FFB01, - author = {Randima Fernando and Sebastian Fernandez and Kavita Bala and Donald P. Greenberg}, - title = {Adaptive shadow maps}, - booktitle = {SIGGRAPH '01: Proceedings of the 28th annual conference on Computer graphics and interactive techniques}, - year = {2001}, - isbn = {1-58113-374-X}, - pages = {387--390}, - doi = {http://doi.acm.org/10.1145/383259.383302}, - publisher = {ACM Press}, - address = {New York, NY, USA}, -} - -@inproceedings{SD02, - author = {Marc Stamminger and George Drettakis}, - title = {Perspective shadow maps}, - booktitle = {SIGGRAPH '02: Proceedings of the 29th annual conference on Computer graphics and interactive techniques}, - year = {2002}, - isbn = {1-58113-521-1}, - pages = {557--562}, - location = {San Antonio, Texas}, - doi = {http://doi.acm.org/10.1145/566570.566616}, - publisher = {ACM Press}, - address = {New York, NY, USA}, -} - -@inproceedings{RSC87, - author = {William T. Reeves and David H. Salesin and Robert L. Cook}, - title = {Rendering antialiased shadows with depth maps}, - booktitle = {SIGGRAPH '87: Proceedings of the 14th annual conference on Computer graphics and interactive techniques}, - year = {1987}, - isbn = {0-89791-227-6}, - pages = {283--291}, - doi = {http://doi.acm.org/10.1145/37401.37435}, - publisher = {ACM Press}, - address = {New York, NY, USA}, -} - -@inproceedings{LV00, - author = {Tom Lokovic and Eric Veach}, - title = {Deep Shadow Maps }, - booktitle = {SIGGRAPH '00: Proceedings of the 27th annual conference on Computer graphics and interactive techniques}, - year = {2000}, - publisher = {ACM Press}, - address = {New York, NY, USA}, -} - -@inproceedings{DL06, - author = {William Donnelly and Andrew Lauritzen}, - title = {Variance shadow maps}, - booktitle = {SI3D '06: Proceedings of the 2006 symposium on Interactive 3D graphics and games}, - year = {2006}, - isbn = {1-59593-295-X}, - pages = {161--165}, - location = {Redwood City, California}, - doi = {http://doi.acm.org/10.1145/1111411.1111440}, - publisher = {ACM Press}, - address = {New York, NY, USA}, - } - - @article{bilas2000automatic, - title={An Automatic Singleton Utility}, - author={Bilas, Scott}, - journal={Game Programming Gems. Charles River Media}, - pages={36--40}, - year={2000} -} - -@article{melax1998simple, - title={A simple, fast, and effective polygon reduction algorithm}, - author={Melax, Stan}, - journal={Game Developer}, - volume={11}, - pages={44--49}, - year={1998} -} - -@article{de2000fast, - title={Fast terrain rendering using geometrical mipmapping}, - author={De Boer, Willem H}, - journal={Unpublished paper, available at http://www.flipcode.com/articles/article_geomipmaps.pdf}, - year={2000} -} - -@article{moller1997fast, - title={Fast, minimum storage ray-triangle intersection}, - author={M{\"o}ller, Tomas and Trumbore, Ben}, - journal={Journal of graphics tools}, - volume={2}, - number={1}, - pages={21--28}, - year={1997}, - publisher={Taylor \& Francis} -} - -@article{mcguire2003fast, - title={Fast, practical and robust shadows}, - author={McGuire, Morgan and Hughes, John F and Egan, Kevin and Kilgard, Mark J and Everitt, Cass}, - journal={Brown University Computer Science Tech Report CS-03-19, November}, - year={2003} -} - -@inproceedings{lloyd2007practical, - title={Practical logarithmic rasterization for low-error shadow maps}, - author={Lloyd, Brandon and Govindaraju, Naga K and Molnar, Steven E and Manocha, Dinesh}, - booktitle={Graphics Hardware}, - volume={7}, - year={2007} -} - -@inproceedings{stamminger2002perspective, - title={Perspective shadow maps}, - author={Stamminger, Marc and Drettakis, George}, - booktitle={Proceedings of the 29th annual conference on Computer graphics and interactive techniques}, - pages={557--562}, - year={2002} -} diff --git a/Docs/src/hardware-buffers.md b/Docs/src/hardware-buffers.md deleted file mode 100644 index 9f6269aec99..00000000000 --- a/Docs/src/hardware-buffers.md +++ /dev/null @@ -1,500 +0,0 @@ -# Hardware Buffers {#Hardware-Buffers} - -The general premise with a hardware buffer is that it is an area of memory with which you can do whatever you like; there is no format (vertex or otherwise) associated with the buffer itself - that is entirely up to interpretation by the methods that use it - in that way, a Ogre::HardwareBuffer is just like an area of memory you might allocate using @c malloc - the difference being that this memory is accessible by the GPU driver. Vertex buffers, index buffers and pixel buffers inherit most of their features from the HardwareBuffer class. - -@tableofcontents - - - -# The Hardware Buffer Manager {#The-Hardware-Buffer-Manager} - -The HardwareBufferManager class is the factory hub of all the objects in the new geometry system. You create and destroy the majority of the objects you use to define geometry through this class. It’s a Singleton, so you access it by doing HardwareBufferManager::getSingleton() - however be aware that it is only guaranteed to exist after the RenderSystem has been initialised (after you call Root::initialise); this is because the objects created are invariably API-specific, although you will deal with them through one common interface. For example: - -```cpp -Ogre::VertexDeclaration* decl = HardwareBufferManager::getSingleton().createVertexDeclaration(); - -auto vbuf = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer( - 3 * sizeof(float), // size of one whole vertex - numVertices, // number of vertices - Ogre::HBU_GPU_ONLY, // usage - false); // no shadow buffer -``` - -Don’t worry about the details of the above, we’ll cover that in the later sections. The important thing to remember is to always create objects through the HardwareBufferManager, don’t use ’new’ (it won’t work anyway in most cases). - -# Buffer Usage {#Buffer-Usage} - -Because the memory in a hardware buffer is likely to be under significant contention during the rendering of a scene, the kind of access you need to the buffer over the time it is used is extremely important; whether you need to update the contents of the buffer regularly, whether you need to be able to read information back from it, these are all important factors to how the graphics card manages the buffer. The method and exact parameters used to create a buffer depends on whether you are creating an [index buffer](@ref Hardware-Index-Buffers) or [vertex buffer](@ref Hardware-Vertex-Buffers), however one creation parameter is common to them both - the @c usage. The most optimal type of hardware buffer is one which is not updated often, and is never read from. The usage parameter of @c createVertexBuffer or @c createIndexBuffer can be one of Ogre::HardwareBufferUsage. - -Choosing the usage of your buffers carefully is important to getting optimal performance out of your geometry. If you have a situation where you need to update a vertex buffer often, consider whether you actually need to update **all** the parts of it, or just some. If it’s the latter, consider using more than one buffer, with only the data you need to modify in the HBU_CPU_TO_GPU buffer. Always try to use the HBU_GPU_ONLY form. This just means that you cannot read *directly* from the hardware buffer, which is good practice because reading from hardware buffers is very slow. If you really need to read data back, use a shadow buffer, described in the next section. - -The following table shows how the descriptive usage names map to the legacy terminology used in older versions of %Ogre as well as rendering APIs like D3D11 and OpenGL. - -| Usage | Legacy name | -|----------------|-------------| -| HBU_GPU_ONLY | HBU_STATIC_WRITE_ONLY | -| HBU_CPU_TO_GPU | HBU_DYNAMIC_WRITE_ONLY | -| HBU_GPU_TO_CPU | HBU_STATIC | -| HBU_CPU_ONLY | HBU_DYNAMIC | - -# Shadow Buffers {#Shadow-Buffers} - -Reading data from a buffer in the GPU memory is very expensive. However, if you have a cast-iron need to read the contents of the buffer, you should set the @c shadowBuffer parameter of @c createVertexBuffer or @c createIndexBuffer to @c true. -This causes the hardware buffer to be shadowed with a *staging* system-memory copy, which will be synchronised with the GPU buffer at locking (@c HBL_READ_ONLY) or unlocking (@c HBL_WRITE_ONLY) time. -You can read from with no more penalty than reading ordinary memory. The catch is that you now have two copies of the buffer - one in system memory and one on the GPU. Therefore do not use it, unless you need it. - -# Data Transfer {#Data-Transfer} -In order to read or update a hardware buffer, you have to notify the card about it as it can have an effect on its rendering queue. %Ogre provides two ways of doing this as described below. - -## writeData and readData - -If your data is already somewhere in system memory, you can use the simple @c writeData and @c readData methods. These can be thought of as locking the buffer (as described below) and doing a @c memcpy. Some APIs, like OpenGL, implement this more efficiently though. - -```cpp -std::vector vec = ...; -Ogre::HardwareBufferPtr pBuffer = ...; -// the last parameter means we discard all previous content on writing -pBuffer->writeData(0, vec.size() * sizeof(float), vec.data(), true); -``` - -However, this approach has a noticeable overhead, if you update small portions of the buffer at different locations. Also, it obviously requires system memory to be allocated for the data. - -## Locking buffers {#Locking-buffers} - -Locking performs 2 functions - it tells the card that you want access to the buffer, and it returns a pointer which you can manipulate. Note that if you’ve asked to read the buffer (and remember, you really shouldn’t unless you’ve set the buffer up with a shadow buffer), the contents of the hardware buffer will have been copied into system memory somewhere in order for you to get access to it. For the same reason, when you’re finished with the buffer you must unlock it; if you locked the buffer for writing this will trigger the process of uploading the modified information to the graphics hardware. - -@note It is strongly recommended to use Ogre::HardwareBufferLockGuard instead of manually locking and unlocking buffers. This guarantees unlocking even in case of exception. - - - -### Lock parameters - -When you lock a buffer, you call one of the following methods: - -```cpp -HardwareBufferPtr pBuffer = ...; -// Lock the entire buffer -pBuffer->lock(lockType); -// Lock only part of the buffer -pBuffer->lock(start, length, lockType); -``` - -The first call locks the entire buffer, the second locks only the section from @c start (as a byte offset), for @c length bytes. This could be faster than locking the entire buffer since less is transferred, but not if you later update the rest of the buffer too, because doing it in small chunks like this means you cannot use Ogre::HardwareBuffer::HBL_DISCARD. The @c lockType parameter can have a large effect on the performance of your application, especially if you are not using a shadow buffer. See Ogre::HardwareBuffer::LockOptions. - -Once you have locked a buffer, you can use the pointer returned however you wish (just don’t bother trying to read the data that’s there if you’ve used @c HBL_DISCARD, or write the data if you’ve used @c HBL_READ_ONLY). Modifying the contents depends on the type of buffer. -@see @ref Updating-Vertex-Buffers -@see @ref Updating-Index-Buffers - -# Practical Buffer Tips {#Practical-Buffer-Tips} - -The interplay of usage mode on creation, and locking options when reading / updating is important for performance. Here’s some tips: - -1. Aim for the ’perfect’ buffer by creating with @c HBU_GPU_ONLY, with no shadow buffer, and locking all of it once only with @c HBL_DISCARD to populate it. Never touch it again. -2. If you need to update a buffer regularly, you will have to compromise. Use @c HBU_CPU_TO_GPU when creating (still no shadow buffer), and use @c HBL_DISCARD to lock the entire buffer, or if you can’t then use @c HBL_NO_OVERWRITE to lock parts of it. -3. If you really need to read data from the buffer, create it with a shadow buffer. Make sure you use @c HBL_READ_ONLY when locking for reading because it will avoid the upload normally associated with unlocking the buffer. You can also combine this with either of the 2 previous points, obviously try for @c HBU_GPU_ONLY if you can - remember that the usage refers to the hardware buffer so can be safely used with a shadow buffer you read from. -4. Split your vertex buffers up if you find that your usage patterns for different elements of the vertex are different. No point having one huge updatable buffer with all the vertex data in it, if all you need to update is the texture coordinates. Split that part out into it’s own buffer and make the rest @c HBU_GPU_ONLY. - -## Vulkan specific notes - -When it comes to Vulkan, the above tips become rules. %Ogre does not try to emulate the behaviour of older APIs and gets out of the way when you are about to shoot yourself in the foot. -- As the GPU might not yet be done processing the data, you should always use @c HBL_DISCARD or multiple buffers to avoid rendering glitches -- @c HBU_GPU_ONLY buffer updates must be done before rendering of the current frame starts (i.e. @c RenderSystem::_render has been called) - -# Hardware Vertex Buffers {#Hardware-Vertex-Buffers} - -This section covers specialised hardware buffers which contain vertex data. - -## The VertexData class {#The-VertexData-class} - -The Ogre::VertexData class @copybrief Ogre::VertexData -@copydetails Ogre::VertexData -The VertexData class has a number of important members: - -
-
vertexStart
-@copybrief Ogre::VertexData::vertexStart - -
vertexCount
-@copybrief Ogre::VertexData::vertexCount - -
vertexDeclaration
- -@copybrief Ogre::VertexData::vertexDeclaration -@copydetails Ogre::VertexData::vertexDeclaration -See @ref Vertex-Declarations - -
vertexBufferBinding
-@copybrief Ogre::VertexData::vertexBufferBinding -@copydetails Ogre::VertexData::vertexBufferBinding -See @ref Vertex-Buffer-Bindings - -
- -## Vertex Declarations {#Vertex-Declarations} - -Vertex declarations define the vertex inputs used to render the geometry you want to appear on the screen. Basically this means that for each vertex, you want to feed a certain set of data into the graphics pipeline, which (you hope) will affect how it all looks when the triangles are drawn. Vertex declarations let you pull items of data (which we call vertex elements, represented by the VertexElement class) from any number of buffers, both shared and dedicated to that particular element. It’s your job to ensure that the contents of the buffers make sense when interpreted in the way that your VertexDeclaration indicates that they should. To add an element to a VertexDeclaration, you call Ogre::VertexDeclaration::addElement method. The parameters to this method are: - -
-
source
- -This tells the declaration which buffer the element is to be pulled from. Note that this is just an index, which may range from 0 to one less than the number of buffers which are being bound as sources of vertex data. See [Vertex Buffer Bindings](#Vertex-Buffer-Bindings) for information on how a real buffer is bound to a source index. Storing the source of the vertex element this way (rather than using a buffer pointer) allows you to rebind the source of a vertex very easily, without changing the declaration of the vertex format itself. - -
offset
- -Tells the declaration how far in bytes the element is offset from the start of each whole vertex in this buffer. This will be 0 if this is the only element being sourced from this buffer, but if other elements are there then it may be higher. A good way of thinking of this is the size of all vertex elements which precede this element in the buffer. - -
type
- -This defines the data type of the vertex input, including it’s size. This is an important element because as GPUs become more advanced, we can no longer assume that position input will always require 3 floating point numbers, because programmable vertex pipelines allow full control over the inputs and outputs. This part of the element definition covers the basic type and size, e.g. VET\_FLOAT3 is 3 floating point numbers - the meaning of the data is dealt with in the next parameter. - -
semantic
- -This defines the meaning of the element - the GPU will use this to determine what to use this input for, and programmable vertex pipelines will use this to identify which semantic to map the input to. This can identify the element as positional data, normal data, texture coordinate data, etc. See the API reference for full details of all the options. - -
index
- -This parameter is only required when you supply more than one element of the same semantic in one vertex declaration. For example, if you supply more than one set of texture coordinates, you would set first sets index to 0, and the second set to 1. - -
- -You can repeat the call to addElement for as many elements as you have in your vertex input structures. There are also useful methods on VertexDeclaration for locating elements within a declaration - see the API reference for full details. - -## Vertex Buffer Bindings {#Vertex-Buffer-Bindings} - -Vertex buffer bindings are about associating a vertex buffer with a source index used in [Vertex Declarations](#Vertex-Declarations). - -## Creating the Vertex Buffer {#Creating-the-Vertex-Buffer} - -Firstly, lets look at how you create a vertex buffer: - -```cpp -HardwareVertexBufferPtr vbuf = - Ogre::HardwareBufferManager::getSingleton().createVertexBuffer( - 3 * sizeof(float), // size of one whole vertex - numVertices, // number of vertices - Ogre::HBU_GPU_ONLY, // usage - false); // no shadow buffer -``` - -Notice that we use @ref The-Hardware-Buffer-Manager to create our vertex buffer, and that a class called Ogre::HardwareVertexBufferPtr is returned from the method, rather than a raw pointer. This is because vertex buffers are reference counted - you are able to use a single vertex buffer as a source for multiple pieces of geometry therefore a standard pointer would not be good enough, because you would not know when all the different users of it had finished with it. The @c HardwareVertexBufferPtr class manages its own destruction by keeping a reference count of the number of times it is being used - when the last @c HardwareVertexBufferPtr is destroyed, the buffer itself automatically destroys itself. - -The parameters to the creation of a vertex buffer are as follows: - -
-
vertexSize
- -The size in bytes of a whole vertex in this buffer. A vertex may include multiple elements, and in fact the contents of the vertex data may be reinterpreted by different vertex declarations if you wish. Therefore you must tell the buffer manager how large a whole vertex is, but not the internal format of the vertex, since that is down to the declaration to interpret. In the above example, the size is set to the size of 3 floating point values - this would be enough to hold a standard 3D position or normal, or a 3D texture coordinate, per vertex. - -
numVertices
- -The number of vertices in this buffer. Remember, not all the vertices have to be used at once - it can be beneficial to create large buffers which are shared between many chunks of geometry because changing vertex buffer bindings is a render state switch, and those are best minimised. - -
usage
- -This tells the system how you intend to use the buffer. See @ref Buffer-Usage - -
useShadowBuffer
- -Tells the system whether you want this buffer backed by a system-memory copy. See @ref Shadow-Buffers - -
- -## Binding the Vertex Buffer {#Binding-the-Vertex-Buffer} - -The second part of the process is to bind this buffer which you have created to a source index. To do this, you call: - -```cpp -vertexBufferBinding->setBinding(0, vbuf); -``` - -This results in the vertex buffer you created earlier being bound to source index 0, so any vertex element which is pulling its data from source index 0 will retrieve data from this buffer. There are also methods for retrieving buffers from the binding data - see the API reference for full details. - -## Updating Vertex Buffers {#Updating-Vertex-Buffers} - -The complexity of updating a vertex buffer entirely depends on how its contents are laid out. You can [lock a buffer](@ref Locking-buffers), but how you write data into it vert much depends on what it contains. Lets start with a vert simple example. Lets say you have a buffer which only contains vertex positions, so it only contains sets of 3 floating point numbers per vertex. In this case, all you need to do to write data into it is: - -```cpp -auto pFloat = static_cast(vbuf->lock(HardwareBuffer::HBL_DISCARD)); -``` - -... then you just write positions in chunks of 3 reals. If you have other floating point data in there, it’s a little more complex but the principle is largely the same, you just need to write alternate elements. But what if you have elements of different types, or you need to derive how to write the vertex data from the elements themselves? Well, there are some useful methods on the VertexElement class to help you out. Firstly, you lock the buffer but assign the result to a unsigned char\* rather than a specific type. Then, for each element which is sourcing from this buffer (which you can find out by calling VertexDeclaration::findElementsBySource) you call VertexElement::baseVertexPointerToElement. This offsets a pointer which points at the base of a vertex in a buffer to the beginning of the element in question, and allows you to use a pointer of the right type to boot. Here’s a full example: - -```cpp -// will automatically release the lock -Ogre::HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_READ_ONLY); -// Get base pointer -auto pVert = static_cast(vbufLock.pData); -float* pFloat; -for (size_t v = 0; v < vertexCount; ++v) -{ - // Get elements - for (VertexElement& elem : decl->findElementsBySource(bufferIdx)) - { - if (elem.getSemantic() == VES_POSITION) - { - elem.baseVertexPointerToElement(pVert, &pFloat); - // write position using pFloat - - } - - ... - - - } - pVert += vbuf->getVertexSize(); -} -``` - -See the API docs for full details of all the helper methods on VertexDeclaration and VertexElement to assist you in manipulating vertex buffer data pointers. - -# Hardware Index Buffers {#Hardware-Index-Buffers} - -Index buffers are used to render geometry by building triangles out of vertices indirectly by reference to their position in the buffer, rather than just building triangles by sequentially reading vertices. Index buffers are simpler than vertex buffers, since they are just a list of indexes at the end of the day, however they can be held on the hardware and shared between multiple pieces of geometry in the same way vertex buffers can, so the rules on creation and locking are the same. - -## The IndexData class {#The-IndexData-class} - -This class summarises the information required to use a set of indexes to render geometry. It’s members are as follows: - -
-
indexStart
- -The first index used by this piece of geometry; this can be useful for sharing a single index buffer among several geometry pieces. - -
indexCount
- -The number of indexes used by this particular renderable. - -
indexBuffer
- -The index buffer which is used to source the indexes. - -
- -## Creating an Index Buffer - -Index buffers are created using See [The Hardware Buffer Manager](#The-Hardware-Buffer-Manager) just like vertex buffers, here’s how: - -```cpp -HardwareIndexBufferPtr ibuf = Ogre::HardwareBufferManager::getSingleton(). - createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, // type of index - numIndexes, // number of indexes - Ogre::HBU_GPU_ONLY, // usage - false); // no shadow buffer -``` - -Once again, notice that the return type is a class rather than a pointer; this is reference counted so that the buffer is automatically destroyed when no more references are made to it. The parameters to the index buffer creation are: - -
-
indexType
- -There are 2 types of index; 16-bit and 32-bit. They both perform the same way, except that the latter can address larger vertex buffers. If your buffer includes more than 65526 vertices, then you will need to use 32-bit indexes. Note that you should only use 32-bit indexes when you need to, since they incur more overhead than 16-bit vertices, and are not supported on some older hardware. - -
numIndexes
- -The number of indexes in the buffer. As with vertex buffers, you should consider whether you can use a shared index buffer which is used by multiple pieces of geometry, since there can be performance advantages to switching index buffers less often. - -
usage
- -This tells the system how you intend to use the buffer. See @ref Buffer-Usage - -
useShadowBuffer
- -Tells the system whether you want this buffer backed by a system-memory copy. See @ref Shadow-Buffers - -
- -## Updating Index Buffers {#Updating-Index-Buffers} - -Updating index buffers can only be done when you [lock the buffer](@ref Locking-buffers) for writing; Locking returns a void pointer, which must be cast to the appropriate type; with index buffers this is either an @c uint16 (for 16-bit indexes) or an @c uint32 (for 32-bit indexes). For example: - -```cpp -uint16* pIdx = static_cast(ibuf->lock(Ogre::HardwareBuffer::HBL_DISCARD)); -``` - -You can then write to the buffer using the usual pointer semantics, just remember to unlock the buffer when you’re finished! - -# Hardware Pixel Buffers {#Hardware-Pixel-Buffers} - -Hardware Pixel Buffers are a special kind of buffer that stores graphical data in graphics card memory, generally for use as textures. Pixel buffers can represent a one dimensional, two dimensional or three dimensional image. A texture can consist of a multiple of these buffers. - -In contrary to vertex and index buffers, pixel buffers are not constructed directly. When creating @ref Textures, the necessary pixel buffers to hold the data are constructed automatically. - -## Pixel boxes {#Pixel-boxes} - -All methods in Ogre that take or return raw image data return a Ogre::PixelBox object. - -A PixelBox is a primitive describing a volume (3D), image (2D) or line (1D) of pixels in CPU memory. It describes the location and data format of a region of memory used for image data, but does not do any memory management in itself. - -Inside the memory pointed to by the *data* member of a pixel box, pixels are stored as a succession of "depth" slices (in Z), each containing "height" rows (Y) of "width" pixels (X). - -Dimensions that are not used must be 1. For example, a one dimensional image will have extents (width,1,1). A two dimensional image has extents (width,height,1). - -## Updating Pixel Buffers {#Updating-Pixel-Buffers} - -Pixel Buffers can be updated in two different ways; a simple, convenient way and a more difficult (but in some cases faster) method. Both methods make use of Ogre::PixelBox objects to represent image data in memory. - -### Blit from memory {#blitFromMemory} - -The easy method to get an image into a PixelBuffer is by using Ogre::HardwarePixelBuffer::blitFromMemory. This takes a PixelBox object and does all necessary pixel format conversion and scaling for you. For example, to create a manual texture and load an image into it, all you have to do is - -```cpp -// Manually loads an image and puts the contents in a manually created texture -Ogre::Image img; -img.load("elephant.png", "General"); -// Create RGB texture with 5 mipmaps -TexturePtr tex = Ogre::TextureManager::getSingleton().createManual( - "elephant", - "General", - Ogre::TEX_TYPE_2D, - img.getWidth(), img.getHeight(), - 5, Ogre::PF_X8R8G8B8); -// Copy face 0 mipmap 0 of the image to face 0 mipmap 0 of the texture. -tex->getBuffer(0,0)->blitFromMemory(img.getPixelBox(0,0)); -``` - -### Direct memory locking {#Direct-memory-locking} - -A more advanced method to transfer image data from and to a PixelBuffer is to use locking. By locking a PixelBuffer you can directly access its contents in whatever the internal format of the buffer inside the GPU is. - -```cpp -/// Lock the buffer so we can write to it -buffer->lock(HardwareBuffer::HBL_DISCARD); -const Ogre::PixelBox &pb = buffer->getCurrentLock(); - -/// Update the contents of pb here -/// Image data starts at pb.data and has format pb.format -/// Here we assume data.format is PF_X8R8G8B8 so we can address pixels as uint32. -uint32 *data = static_cast(pb.data); -size_t height = pb.getHeight(); -size_t width = pb.getWidth(); -size_t pitch = pb.rowPitch; // Skip between rows of image -for(size_t y=0; y fill the buffer with yellow pixels - data[pitch*y + x] = 0x00FFFF00; - } -} - -/// Unlock the buffer again (frees it for use by the GPU) -buffer->unlock(); -``` - - -# Textures {#Textures} - -A texture is an image that can be applied onto the surface of a three dimensional model. In %Ogre, textures are represented by the Ogre::Texture resource class. - -## Creating a texture {#Creating-a-texture} - -Textures are created through the TextureManager. In most cases they are created from image files directly by the Ogre resource system. If you are reading this, you most probably want to create a texture manually so that you can provide it with image data yourself. This is done through Ogre::TextureManager::createManual: - -```cpp -tex = Ogre::TextureManager::getSingleton().createManual( - "MyManualTexture", // Name of texture - "General", // Name of resource group in which the texture should be created - TEX_TYPE_2D, // Texture type - 256, // Width - 256, // Height - 1, // Depth (Must be 1 for two dimensional textures) - 0, // No mipmaps - PF_A8R8G8B8, // internal Pixel format hint - HBU_GPU_ONLY | TU_AUTOMIPMAP // usage -); -``` - -This example creates a texture named *MyManualTexture* in resource group *General*. It is a square *two dimensional* texture, with width 256 and height 256. - -The available texture types are specified in Ogre::TextureType. Pixel formats are summarised in @ref Pixel-Formats. -@note The format specified here is only a hint. If the hardware does not support the requested format, you will get the closest supported alternative format as returned by Ogre::TextureManager::getNativeFormat. - -In addition to the hardware buffer usages as described in Ogre::HardwareBufferUsage there are some usage flags specific to textures defined in Ogre::TextureUsage. - -## Getting a PixelBuffer {#Getting-a-PixelBuffer} - -A Texture can consist of multiple @ref Hardware-Pixel-Buffers, one for each combo if mipmap level and face number. To get a PixelBuffer from a Texture object the method Ogre::Texture::getBuffer is used: - -@c face should be zero for non-cubemap textures. For @ref Cube-map-textures it identifies which one of the cube faces to use. - -@c mipmap is zero for the zeroth mipmap level, one for the first mipmap level, and so on. On textures that have automatic mipmap generation (@c TU_AUTOMIPMAP) only level 0 should be accessed, the rest will be taken care of by the rendering API. - -A simple example of using getBuffer is - -```cpp -// Get the PixelBuffer for face 0, mipmap 0. -HardwarePixelBufferSharedPtr ptr = tex->getBuffer(0,0); -``` - -## Cube map textures {#Cube-map-textures} - -The cube map texture type (Ogre::TEX_TYPE_CUBE_MAP) is a different beast from the others; a cube map texture represents a series of six two dimensional images addressed by 3D texture coordinates. - -@par +X (face 0) -Represents the positive x plane (right). - -@par -X (face 1) -Represents the negative x plane (left). - -@par +Y (face 2) -Represents the positive y plane (top). - -@par -Y (face 3) -Represents the negative y plane (bottom). - -@par +Z (face 4) -Represents the positive z plane (front). - -@par -Z (face 5) -Represents the negative z plane (back). - -## Pixel Formats {#Pixel-Formats} - -@copydetails Ogre::PixelFormat - -A pixel format described the storage format of pixel data. It defines the way pixels are encoded in memory. The following classes of pixel formats (PF\_\*) are defined: - -@par Native endian formats (PF\_A8R8G8B8 and other formats with bit counts) -These are native endian (16, 24 and 32 bit) integers in memory. The meaning of the letters is described below. - -@par Byte formats (PF\_BYTE\_\*) -These formats have one byte per channel, and their channels in memory are organized in the order they are specified in the format name. For example, PF\_BYTE\_RGBA consists of blocks of four bytes, one for red, one for green, one for blue, one for alpha. - -@par Short formats (PF\_SHORT\_\*) -These formats have one unsigned short (16 bit integer) per channel, and their channels in memory are organized in the order they are specified in the format name. For example, PF\_SHORT\_RGBA consists of blocks of four 16 bit integers, one for red, one for green, one for blue, one for alpha. - -@par Float16 formats (PF\_FLOAT16\_\*) -These formats have one 16 bit floating point number per channel, and their channels in memory are organized in the order they are specified in the format name. For example, PF\_FLOAT16\_RGBA consists of blocks of four 16 bit floats, one for red, one for green, one for blue, one for alpha. The 16 bit floats, also called half float) are very similar to the IEEE single-precision floating-point standard of the 32 bits floats, except that they have only 5 exponent bits and 10 mantissa. Note that there is no standard C++ data type or CPU support to work with these efficiently, but GPUs can calculate with these much more efficiently than with 32 bit floats. - -@par Float32 formats (PF\_FLOAT32\_\*) -These formats have one 32 bit floating point number per channel, and their channels in memory are organized in the order they are specified in the format name. For example, PF\_FLOAT32\_RGBA consists of blocks of four 32 bit floats, one for red, one for green, one for blue, one for alpha. The C++ data type for these 32 bits floats is just "float". - -@par Compressed formats (PF\_DXT\[1-5\]) -S3TC compressed texture formats, [a good description can be found at Wikipedia](http://en.wikipedia.org/wiki/S3TC) - -For a complete list see Ogre::PixelFormat. - -### Colour channels {#Colour-channels} - -The meaning of the channels R,G,B,A,L and X is defined as - -@par R -Red colour component, usually ranging from 0.0 (no red) to 1.0 (full red). - -@par G -Green colour component, usually ranging from 0.0 (no green) to 1.0 (full green). - -@par B -Blue colour component, usually ranging from 0.0 (no blue) to 1.0 (full blue). - -@par A -Alpha component, usually ranging from 0.0 (entire transparent) to 1.0 (opaque). - -@par L -Luminance component, usually ranging from 0.0 (black) to 1.0 (white). The luminance component is duplicated in the R, G, and B channels to achieve a greyscale image. - -@par X -This component is completely ignored. - -If none of red, green and blue components, or luminance is defined in a format, these default to 0. For the alpha channel this is different; if no alpha is defined, it defaults to 1. \ No newline at end of file diff --git a/Docs/src/high-level-programs.md b/Docs/src/high-level-programs.md deleted file mode 100644 index e76dd1e1230..00000000000 --- a/Docs/src/high-level-programs.md +++ /dev/null @@ -1,955 +0,0 @@ -# GPU Program Scripts {#High-level-Programs} - -@anchor Declaring-Vertex_002fGeometry_002fFragment-Programs - -@tableofcontents - -In order [to use a vertex, geometry or fragment program in your materials](@ref Using-Vertex_002fGeometry_002fFragment-Programs-in-a-Pass), you first have to define them. A single program definition can be used by any number of materials, the only prerequisite is that a program must be defined before being referenced in the pass section of a material. - -The definition of a program can either be embedded in the .material script itself (in which case it must precede any references to it in the script), or if you wish to use the same program across multiple .material files, you can define it in an external .program script. You define the program in exactly the same way whether you use a .program script or a .material script, the only difference is that all .program scripts are guaranteed to have been parsed before **all** .material scripts, so you can guarantee that your program has been defined before any .material script that might use it. Just like .material scripts, .program scripts will be read from any location which is on your resource path, and you can define many programs in a single script. - -Vertex, geometry and fragment programs can be low-level (i.e. assembler code written to the specification of a given low level syntax such as vs\_1\_1 or arbfp1) or high-level such as DirectX HLSL and OpenGL GLSL. High level languages give you a number of advantages, such as being able to write more intuitive code, and possibly being able to target multiple architectures in a single program (for example, the same Cg program might be able to be used in both D3D and GL, whilst the equivalent low-level programs would require separate techniques, each targeting a different API). High-level programs also allow you to use named parameters instead of simply indexed ones, although parameters are not defined here, they are used in the Pass. - -Here is an example of a definition of a low-level vertex program: - -```cpp -vertex_program myVertexProgram spirv -{ - source myVertexProgram.spv -} -``` - -As you can see, that’s very simple, and defining a fragment or geometry program is exactly the same, just with @c vertex_program replaced with @c fragment_program or @c geometry_program, respectively. Likewise, for tessellation and compute programs, use @c tessellation_hull_program, @c tessellation_domain_program, and @c compute_program. - -You give the program a name in the header, followed by the word @c spirv to indicate the syntax being used. Inside the braces, you specify where the source is going to come from (and this is loaded from any of the resource locations as with other media). The syntax specification is necessary for the engine to know what syntax the program is in before reading it. During the compilation of the material, it is important to quickly skip programs that use unsupported syntax to avoid loading the program first. - -# Default Program Parameters {#Default-Program-Parameters} - -While defining a vertex, geometry or fragment program, you can also specify the default parameters to be used for materials which use it, unless they specifically override them. You do this by including a nested ’default\_params’ section, like so: - -@snippet Samples/Media/materials/scripts/Examples-Advanced.material celshading_vp - -The syntax of the parameter definition is exactly the same as when you define parameters when using programs, See @ref Program-Parameter-Specification. Defining default parameters allows you to avoid rebinding common parameters repeatedly (clearly in the above example, all but ’shininess’ are unlikely to change between uses of the program) which makes your material declarations shorter. - -# High Level Programs - -Support for high level vertex and fragment programs is provided through plugins; this is to make sure that an application using OGRE can use as little or as much of the high-level program functionality as they like. OGRE supports multiple high-level program types. Notably DirectX [HLSL](#HLSL), and OpenGL [GLSL](#GLSL). HLSL can only be used with the DirectX rendersystem, and GLSL can only be used with the GL and Vulkan rendersystems. - -One way to support both HLSL and GLSL is to include separate techniques in the material script, each one referencing separate programs. However, if the programs are basically the same, with the same parameters, and the techniques are complex this can bloat your material scripts with duplication fairly quickly. Instead, if the only difference is the language of the vertex & fragment program you can use OGRE’s [Unified High-level Programs](#Unified-High_002dlevel-Programs) to automatically pick a program suitable for your rendersystem whilst using a single technique. - -There is also [Cg](#Cg) which is deprecated, but allows to use the same Shader code across different APIs - although experience has shown that more advanced programs, particularly fragment programs which perform a lot of texture fetches, can produce better code in the rendersystem-specific shader language. -The better alternative to Cg is to use @ref multi-language-programs with `OgreUnifiedShader.h`. This achieves the same goal as Cg, but uses only a few straightforward preprocessor macros. - -## Preprocessor definitions {#Preprocessor-definitions} - -Both GLSL and HLSL support using preprocessor definitions in your code - some are defined by the implementation, but you can also define your own, say in order to use the same source code for a few different variants of the same technique. In order to use this feature, include preprocessor conditions in your code, of the kind \#ifdef SYMBOL, \#if SYMBOL==2 etc. Then in your program definition, use the `preprocessor_defines` option, following it with a string of definitions. Definitions are separated by `;` or `,` and may optionally have a `=` operator within them to specify a definition value. Those without an `=` will implicitly have a definition of 1. - -@par -Format: preprocessor_defines <defines> -@par -Example: preprocessor_defines CLEVERTECHNIQUE,NUMTHINGS=2 - -```cpp -// in your shader - -#ifdef CLEVERTECHNIQUE - // some clever stuff here -#else - // normal technique -#endif - -#if NUM_THINGS==2 - // Some specific code -#else - // something else -#endif -``` - -This way you can use the same source code but still include small variations, each one defined as a different %Ogre program name but based on the same source code. - -@note on GLSL %Ogre pre-processes the source itself instead on relying on the driver implementation which is often buggy. This relaxes using @c \#ifdef directives compared to the standard - e.g. you can \#ifdef \#version. However this means that defines specified in GLSL extensions are not present. - -## Entry Point - -The parameter @c entry_point, specifies the name of a function which will be the first one called as part of the program. Unlike assembler programs, which just run top-to-bottom, high-level programs can include multiple functions and as such you must specify the one which start the ball rolling. -If you omit this line, %Ogre will default to looking for a function called `main`. - -@par -Format: entry_point <name> -@par -Example: entry_point main_vp - -@note on GLSL the @c entry_point is required to be `main` - -# GLSL programs {#GLSL} - -GLSL is the native shading language of the OpenGL API and requires no plugins there. Additionally, you can use it with Vulkan by loading the @c Plugin_GLSLangProgramManager. -Declaring a OpenGL GLSL program is similar to Cg but simpler. Here’s an example: - -```cpp -vertex_program myGLSLVertexProgram glsl -{ - source myGLSLVertexProgram.vert -} -``` - -The type `glsl` works with the GL and GL3+ RenderSystems, while with the GLES2 RenderSystem you must specify `glsles` instead. -For Vulkan, you must specify `glslang` so the GLSLang Plugin is used. This also works with GL3+, in case you prefer not to use the GLSL compiler of your driver. -If your shader is designed for this, you can also specify all of those at once. See @ref multi-language-programs. - -In GLSL, no entry point needs to be defined since it is always `main()` and there is no target definition since GLSL source is compiled into native GPU code and not intermediate assembly. - -For modularity %Ogre supports the non-standard \#include directive in GLSL. It also works with OpenGL ES and resembles what is available with HLSL and Cg. - -## Binding vertex attributes {#Binding-vertex-attributes} - -Vertex attributes must be declared in the shader, for the vertex data bound to it by Ogre. - -```cpp -// legacy GLSL syntax -attribute vec4 vertex; - -// modern GLSL syntax with explicit layout qualifier -layout(location = 0) in vec4 vertex; -``` - -refer to the following table for the location indices and names to use: - -| Semantic | Custom name | Binding location | Legacy OpenGL built-in | -|----------|------|------------------|-----------------------| -| Ogre::VES_POSITION | vertex | 0 | gl_Vertex | -| Ogre::VES_BLEND_WEIGHTS | blendWeights | 1 | n/a | -| Ogre::VES_NORMAL | normal | 2 | gl_Normal | -| Ogre::VES_COLOUR | colour | 3 | gl_Color | -| Ogre::VES_COLOUR2 | secondary_colour | 4 | gl_SecondaryColor | -| Ogre::VES_BLEND_INDICES | blendIndices | 7 | n/a | -| Ogre::VES_TEXTURE_COORDINATES | uv0 - uv7 | 8-15 | gl_MultiTexCoord0 - gl_MultiTexCoord7 | -| Ogre::VES_TANGENT | tangent | 14 | n/a | -| Ogre::VES_BINORMAL | binormal | 15 | n/a | - -@note uv6 and uv7 share attributes with tangent and binormal respectively so cannot both be present. - -## Binding Texture Samplers {#GLSL-Texture-Samplers} - -To bind samplers to texture unit indices from the material scripts, you can either use the explicit binding with GL4.2+ or -set the sampler via a `int` type named parameter. - -```cpp -// modern (GL4.2+) syntax with explicit binding -layout(binding = 0) uniform sampler2D diffuseMap; - -// legacy syntax -uniform sampler2D diffuseMap; -``` - -Binding the sampler in material script: - -```cpp -material exampleGLSLTexturing -{ - technique - { - pass - { - fragment_program_ref myFragmentShader - { - param_named diffuseMap int 0 - } - - texture_unit - { - texture myTexture.jpg 2d - } - } - } -} -``` - -An index value of 0 refers to the first texture unit in the pass, an index value of 1 refers to the second unit in the pass and so on. - -## Matrix parameters {#Matrix-parameters} - -Here are some examples of passing matrices to GLSL mat2, mat3, mat4 uniforms: - -```cpp -// mat4 uniform -param_named OcclusionMatrix matrix4x4 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 -// or -param_named ViewMatrix float16 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 - -// mat3 -param_named TextRotMatrix float9 1 0 0 0 1 0 0 0 1 - -// mat2 uniform -param_named skewMatrix float4 0.5 0 -0.5 1.0 -``` - -@note GLSL uses column-major storage by default, while %Ogre is using row-major storage. Furthermore, GLSL is using column-major addressing, while %Ogre and HLSL use row-major addressing. -This means that `mat[0]` is the first column in GLSL, but the first row in HLSL and %Ogre. %Ogre takes care of transposing square matrices before uploading them with GLSL, so matrix-vector multiplication `M*v` just works and `mat[0]` will return the same data. -However, with non-square matrices transposing would change their GLSL type from e.g. `mat2x4` (two columns, four rows) to `mat4x2` (two rows, four columns) and consequently what `mat[0]` would return. Therefore %Ogre just passes such matrices unchanged and you have to handle this case (notably in skinning) yourself by either transposing the matrix in the shader or column-wise access. - -## Transform Feedback Varyings {#Transform-Feedback-Varyings} - -Similarly to vertex attributes, the transform feedback varyings are bound by name. -Only interleaved output to a single buffer is supported. The offsets are given by the Ogre::VertexDeclaration. -The available varyings are: - -| Semantic | Varying name | -|----------|--------------| -| Ogre::VES_POSITION | xfb_position | -| Ogre::VES_NORMAL | xfb_normal | -| Ogre::VES_COLOUR | xfb_colour | -| Ogre::VES_COLOUR2 | xfb_colour2 | -| Ogre::VES_TEXTURE_COORDINATES | xfb_uv0 - xfb_uv7 | - -## Compatibility profile GLSL features {#Legacy-GLSL-features} - -The following features are only available when using the legacy OpenGL profile. Notably they are not available with GL3+ or GLES2. - -### Accessing OpenGL state -GLSL can access most of the GL states directly so you do not need to pass these states through [param\_named\_auto](#param_005fnamed_005fauto) in the material script. This includes lights, material state, and all the matrices used in the openGL state i.e. model view matrix, worldview projection matrix etc. - -### Access to built-in attributes -GLSL natively supports automatic binding of the most common incoming per-vertex attributes (e.g. `gl_Vertex`, `gl_Normal`, `gl_MultiTexCoord0` etc) -as described in section 7.3 of the GLSL manual. -There are some drivers that do not behave correctly when mixing built-in vertex attributes like `gl_Normal` and custom vertex attributes, so for maximum compatibility you should use all custom attributes - -### Geometry shader specification -GLSL allows the same shader to run on different types of geometry primitives. In order to properly link the shaders together, you have to specify which primitives it will receive as input, which primitives it will emit and how many vertices a single run of the shader can generate. The GLSL geometry\_program definition requires three additional parameters - -@param input\_operation\_type -The operation type of the geometry that the shader will receive. Can be ’point\_list’, ’line\_list’, ’line\_strip’, ’triangle\_list’, ’triangle\_strip’ or ’triangle\_fan’. - -@param output\_operation\_type -The operation type of the geometry that the shader will emit. Can be ’point\_list’, ’line\_strip’ or ’triangle\_strip’. - -@param max\_output\_vertices -The maximum number of vertices that the shader can emit. There is an upper limit for this value, it is exposed in the render system capabilities. - -@par Example -```cpp -geometry_program Ogre/GPTest/Swizzle_GP_GLSL glsl -{ - source SwizzleGP.glsl - input_operation_type triangle_list - output_operation_type line_strip - max_output_vertices 6 -} -``` - -With GL3+ these values are specified using the `layout` modifier. - -# Cg programs {#Cg} - -In order to define Cg programs, you have to have to load @c Plugin_CgProgramManager at startup, either through plugins.cfg or through your own plugin loading code. They are very easy to define: - -```cpp -fragment_program myCgFragmentProgram cg -{ - source myCgFragmentProgram.cg - entry_point main_fp - profiles ps_2_0 arbfp1 -} -``` - -There are a few differences between this and the assembler program - to begin with, we declare that the fragment program is of type `cg` rather than `spirv`, which indicates that it’s a high-level program using Cg. The `source` parameter is the same, except this time it’s referencing a Cg source file instead of a file of assembler. - -Here is where things start to change. Instead of a fixed `syntax` parameter, you specify one or more `profiles`; profiles are how Cg compiles a program down to the low-level assembler. The profiles have the same names as the assembler syntax codes mentioned above; the main difference is that you can list more than one, thus allowing the program to be compiled down to more low-level syntaxes so you can write a single high-level program which runs on both D3D and GL. You are advised to just enter the simplest profiles under which your programs can be compiled in order to give it the maximum compatibility. The ordering also matters; if a card supports more than one syntax then the one listed first will be used. - -@note Instead of `preprocessor_defines` Cg uses the `compile_arguments` option where you can specify arguments exactly as you would to the [cgc command-line compiler](http://developer.download.nvidia.com/cg/cgc.html). While this gives you more flexibility, it means that you must specify the defines as `-DSYMBOL` separated by spaces. Keep this in mind when copying program definitions across the supported languages. - -# DirectX HLSL {#HLSL} - -DirectX HLSL has an almost identical language syntax to Cg but is tied to the DirectX API. The benefit over Cg is that it only requires the DirectX render system plugin, not any additional plugins. Declaring a DirectX HLSL program is very similar to Cg. Here’s an example: - -```cpp -vertex_program myHLSLVertexProgram hlsl -{ - source myHLSLVertexProgram.hlsl - entry_point main_vp - target vs_2_0 -} -``` - -As you can see, the main syntax is almost identical, except that instead of `profiles` with a list of assembler formats, you have a `target` parameter which allows a single assembler target to be specified - obviously this has to be a DirectX assembler format syntax code. - -@note One thing to bear in mind is that HLSL allows you to use 2 different ways to multiply a vector by a matrix - mul(v,m) or mul(m,v). The only difference between them is that the matrix is effectively transposed. You should use mul(m,v) with the matrices passed in from Ogre - this agrees with the shaders produced from tools like RenderMonkey, and is consistent with Cg too, but disagrees with the Dx9 SDK and FX Composer which use mul(v,m) - you will have to switch the parameters to mul() in those shaders. -@note -If you use the @c float3x4 / @c matrix3x4 type in your shader, bound to an OGRE auto-definition (such as bone matrices) you should use the `column_major_matrices = false` option (discussed below) in your program definition. This is because OGRE passes @c float3x4 as row-major to save constant space (3 float4’s rather than 4 float4’s with only the top 3 values used) and this tells OGRE to pass all matrices like this, so that you can use mul(m,v) consistently for all calculations. OGRE will also to tell the shader to compile in row-major form (you don’t have to set the `/Zpr` compile option or \#pragma pack(row-major) option, OGRE does this for you). Note that passing bones in float4x3 form is not supported by OGRE, but you don’t need it given the above. - -**Advanced options**
- -
-
column\_major\_matrices <true|false>
- -The default for this option is ’true’ so that OGRE passes matrices auto-bound matrices in a form where mul(m,v) works. Setting this option to false does 2 things - it transpose auto-bound 4x4 matrices and also sets the /Zpr (row-major) option on the shader compilation. This means you can still use mul(m,v), but the matrix layout is row-major instead. This is only useful if you need to use bone matrices (float3x4) in a shader since it saves a float4 constant for every bone involved. - -
optimisation\_level <opt>
- -Set the optimisation level, which can be one of ’default’, ’none’, ’0’, ’1’, ’2’, or ’3’. This corresponds to the /O parameter of fxc.exe, except that in ’default’ mode, optimisation is disabled in debug mode and set to 1 in release mode (fxc.exe uses 1 all the time). Unsurprisingly the default value is ’default’. You may want to change this if you want to tweak the optimisation, for example if your shader gets so complex that it will not longer compile without some minimum level of optimisation. - -
- -### Multi module shaders - -The `attach` keyword allows creating GLSL shaders from multiple shader modules of the same type. The referencing shader has to forward-declare the functions it intends to use - -@deprecated The @c attach keyword for multi-module shaders is not supported on OpenGL ES and therefore deprecated in favor of the @c \#include directive - -```cpp -vertex_program myExternalGLSLFunction glsl -{ - source myExternalGLSLfunction.vert -} - -vertex_program myGLSLVertexProgram glsl -{ - source myGLSLfunction.vert - attach myExternalGLSLFunction -} -``` - -# Assembler Shaders - -The current supported syntaxes are: - -
-
spirv
- -The assembly language used by Vulkan - -
-
gl_spirv
- -SPIRV variant exposed by ARB_gl_spirv - -
-
vs_*
- -These is are the DirectX vertex shader assembler syntaxes. - -
arbvp1
- -This is the OpenGL standard assembler format for vertex programs. It’s roughly equivalent to DirectX vs\_1\_1. - -
vp*
- -These are nVidia-specific OpenGL vertex shader syntax which is a superset of vs_1_1_, that have otherwise no equivalent in OpenGL. - -
-
ps_*
- -DirectX pixel shader (i.e. fragment program) assembler syntax. -@note for ATI 8500, 9000, 9100, 9200 hardware, these profiles can also be used in OpenGL. The ATI 8500 to 9200 do not support arbfp1 but do support atifs extension in OpenGL which is very similar in function to ps\_1\_4 in DirectX. Ogre has a built in ps\_1\_x to atifs compiler that is automatically invoked when ps\_1\_x is used in OpenGL on ATI hardware. - -
-
arbfp1
- -This is the OpenGL standard assembler format for fragment programs. It’s roughly equivalent to ps\_2\_0, which means that not all cards that support basic pixel shaders under DirectX support arbfp1 (for example neither the GeForce3 or GeForce4 support arbfp1, but they do support ps\_1\_1). - -
fp20
- -This is an nVidia-specific OpenGL fragment syntax which is a superset of ps 1.3. It allows you to use the [nvparse format](https://www.nvidia.com/attach/6400) for basic fragment programs. It actually uses NV\_texture\_shader and NV\_register\_combiners to provide functionality equivalent to DirectX’s ps\_1\_1 under GL, but only for nVidia cards. However, since ATI cards adopted arbfp1 a little earlier than nVidia, it is mainly nVidia cards like the GeForce3 and GeForce4 that this will be useful for. - -
fp*
- -Another nVidia-specific OpenGL fragment shader syntax. - -
-
gpu\_gp, gp4\_gp
- -An nVidia-specific OpenGL geometry shader syntax.
Supported cards: nVidia GeForce FX8 series
- -
- -You can get a definitive list of the syntaxes supported by the current card by calling `Ogre::GpuProgramManager::getSupportedSyntax()`. - -## Specifying Named Constants {#Specifying-Named-Constants-for-Assembler-Shaders} - -Assembler shaders don’t have named constants (also called uniform parameters) because the language does not support them - however if you for example decided to precompile your shaders from a high-level language down to assembler for performance or obscurity, you might still want to use the named parameters. Well, you actually can - GpuNamedConstants which contains the named parameter mappings has a ’save’ method which you can use to write this data to disk, where you can reference it later using the manual\_named\_constants directive inside your assembler program declaration, e.g. - -```cpp -vertex_program myVertexProgram spirv -{ - source myVertexProgram.spv - manual_named_constants myVertexProgram.constants -} -``` - -In this case myVertexProgram.constants has been created by calling `Ogre::GpuNamedConstants::save("myVertexProgram.constants");` sometime earlier as preparation, from the original high-level program. Once you’ve used this directive, you can use named parameters here even though the assembler program itself has no knowledge of them. - -# Multi-language Programs {#multi-language-programs} - -Basic programs, like the `example.frag` stated above, are compatible with GLSL and GLSLES. To avoid duplicating the whole -program declaration, you can simply specify all the language types the program is compatible with as: - -```cpp -fragment_program myFragmentShader glsl glsles -{ - source example.frag -} -``` - -If you use the built-in defines like @c OGRE_HLSL, you can even write programs compatible with both HLSL and GLSL. In fact, you can use `#include ` in the shader which provides cross-language macros to help with this. - -# Unified High-level Programs {#Unified-High_002dlevel-Programs} - -As mentioned above, it can often be useful to write both HLSL and GLSL programs to specifically target each platform, but if you do this via multiple material techniques this can cause a bloated material definition when the only difference is the program language. Well, there is another option. You can ’wrap’ multiple programs in a ’unified’ program definition, which will automatically choose one of a series of ’delegate’ programs depending on the rendersystem and hardware support. - -```cpp -vertex_program myVertexProgram unified -{ - delegate realProgram1 - delegate realProgram2 - ... etc -} -``` - -This works for both vertex and fragment programs, and you can list as many delegates as you like - the first one to be supported by the current rendersystem & hardware will be used as the real program. This is almost like a mini-technique system, but for a single program and with a much tighter purpose. You can only use this where the programs take all the same inputs, particularly textures and other pass / sampler state. Where the only difference between the programs is the language (or possibly the target in HLSL - you can include multiple HLSL programs with different targets in a single unified program too if you want, or indeed any number of other high-level programs), this can become a very powerful feature. For example, without this feature here’s how you’d have to define a programmable material which supported HLSL and GLSL: - -```cpp -vertex_program myVertexProgramHLSL hlsl -{ - source prog.hlsl - entry_point main_vp - target vs_2_0 -} -fragment_program myFragmentProgramHLSL hlsl -{ - source prog.hlsl - entry_point main_fp - target ps_2_0 -} -vertex_program myVertexProgramGLSL glsl -{ - source prog.vert -} -fragment_program myFragmentProgramGLSL glsl -{ - source prog.frag - default_params - { - param_named tex int 0 - } -} -material SupportHLSLandGLSLwithoutUnified -{ - // HLSL technique - technique - { - pass - { - vertex_program_ref myVertexProgramHLSL - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto lightColour light_diffuse_colour 0 - param_named_auto lightSpecular light_specular_colour 0 - param_named_auto lightAtten light_attenuation 0 - } - fragment_program_ref myFragmentProgramHLSL - { - } - } - } - // GLSL technique - technique - { - pass - { - vertex_program_ref myVertexProgramGLSL - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto lightColour light_diffuse_colour 0 - param_named_auto lightSpecular light_specular_colour 0 - param_named_auto lightAtten light_attenuation 0 - } - fragment_program_ref myFragmentProgramGLSL - { - } - } - } -} -``` - -And that’s a really small example. Everything you added to the HLSL technique, you’d have to duplicate in the GLSL technique too. So instead, here’s how you’d do it with unified program definitions: - -```cpp -vertex_program myVertexProgramHLSL hlsl -{ - source prog.hlsl - entry_point main_vp - target vs_2_0 -} -fragment_program myFragmentProgramHLSL hlsl -{ - source prog.hlsl - entry_point main_fp - target ps_2_0 -} -vertex_program myVertexProgramGLSL glsl -{ - source prog.vert -} -fragment_program myFragmentProgramGLSL glsl -{ - source prog.frag - default_params - { - param_named tex int 0 - } -} -// Unified definition -vertex_program myVertexProgram unified -{ - delegate myVertexProgramGLSL - delegate myVertexProgramHLSL -} -fragment_program myFragmentProgram unified -{ - delegate myFragmentProgramGLSL - delegate myFragmentProgramHLSL -} -material SupportHLSLandGLSLwithUnified -{ - // HLSL technique - technique - { - pass - { - vertex_program_ref myVertexProgram - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto lightColour light_diffuse_colour 0 - param_named_auto lightSpecular light_specular_colour 0 - param_named_auto lightAtten light_attenuation 0 - } - fragment_program_ref myFragmentProgram - { - } - } - } -} -``` - -At runtime, when myVertexProgram or myFragmentProgram are used, OGRE automatically picks a real program to delegate to based on what’s supported on the current hardware / rendersystem. If none of the delegates are supported, the entire technique referencing the unified program is marked as unsupported and the next technique in the material is checked for fallback, just like normal. As your materials get larger, and you find you need to support HLSL and GLSL specifically (or need to write multiple interface-compatible versions of a program for whatever other reason), unified programs can really help reduce duplication. - -# Parameter specification {#Program-Parameter-Specification} - -Parameters can be specified using one of 4 commands as shown below. The same syntax is used whether you are defining a parameter just for this particular use of the program, or when specifying the @ref Default-Program-Parameters. Parameters set in the specific use of the program override the defaults. - -- [param\_indexed](#param_005findexed) -- [param\_indexed\_auto](#param_005findexed_005fauto) -- [param\_named](#param_005fnamed) -- [param\_named\_auto](#param_005fnamed_005fauto) -- [shared\_params\_ref](#shared_005fparams_005fref) - - - -## param\_indexed - -This command sets the value of an indexed parameter. - -@par -Format: param\_indexed <index> <type> <value> -@par -Example: param\_indexed 0 float4 10.0 0 0 0 - -@param index -simply a number representing the position in the parameter list which the value should be written, and you should derive this from your program definition. The index is relative to the way constants are stored on the card, which is in 4-element blocks. For example if you defined a float4 parameter at index 0, the next index would be 1. If you defined a matrix4x4 at index 0, the next usable index would be 4, since a 4x4 matrix takes up 4 indexes. - -@param type -can be float4, matrix4x4, float<n>, int4, int<n>. Note that ’int’ parameters are only available on some more advanced program syntaxes, check the D3D or GL vertex / fragment program documentation for full details. Typically the most useful ones will be float4 and matrix4x4. Note that if you use a type which is not a multiple of 4, then the remaining values up to the multiple of 4 will be filled with zeroes for you (since GPUs always use banks of 4 floats per constant even if only one is used). - -@param value -a space or tab-delimited list of values which can be converted into the type you have specified. - - - -## param\_indexed\_auto - -This command tells Ogre to automatically update a given parameter with a derived value. This frees you from writing code to update program parameters every frame when they are always changing. - -@par -Format: param\_indexed\_auto <index> <autoConstType> <extraInfo> -@par -Example: param\_indexed\_auto 0 worldviewproj\_matrix - -@param index -has the same meaning as [param\_indexed](#param_005findexed); note this time you do not have to specify the size of the parameter because the engine knows this already. In the example, the world/view/projection matrix is being used so this is implicitly a matrix4x4. - -@param autoConstType, extraInfo -is one of Ogre::GpuProgramParameters::AutoConstantType without the `ACT_` prefix. E.g. `ACT_WORLD_MATRIX` becomes `world_matrix`. - - - -## param\_named - -This is the same as param\_indexed, but uses a named parameter instead of an index. This can only be used with high-level programs which include parameter names; if you’re using an assembler program then you have no choice but to use indexes. Note that you can use indexed parameters for high-level programs too, but it is less portable since if you reorder your parameters in the high-level program the indexes will change. -@par -Format: param\_named <name> <type> <value> -@par -Example: param\_named shininess float4 10.0 0 0 0 - -The type is required because the program is not compiled and loaded when the material script is parsed, so at this stage we have no idea what types the parameters are. Programs are only loaded and compiled when they are used, to save memory. - - - -## param\_named\_auto - -This is the named equivalent of param\_indexed\_auto, for use with high-level programs. - -@par -Format: param\_named\_auto <name> <autoConstType> <extraInfo> -@par -Example: param\_named\_auto worldViewProj worldviewproj\_matrix - -The allowed @c autoConstType and the meaning of @c extraInfo are detailed in [param\_indexed\_auto](#param_005findexed_005fauto). - - - -## shared\_params\_ref - -This option allows you to reference shared parameter sets as defined in @ref Declaring-Shared-Parameters. -@par -Format: shared\_params\_ref <shared\_set\_name> -@par -Example: shared\_params\_ref mySharedParams - -The only required parameter is a name, which must be the name of an already defined shared parameter set. All named parameters which are present in both the program and the shared parameter set will be linked, and the shared parameters values will be used. - -# Declaring Shared Parameters {#Declaring-Shared-Parameters} - -Often, not every parameter you want to pass to a shader is unique to that program, and perhaps you want to give the same value to a number of different programs, and a number of different materials using that program. Shared parameter sets allow you to define a ’holding area’ for shared parameters that can then be referenced when you need them in particular shaders, while keeping the definition of that value in one place. To define a set of shared parameters, you do this: - -```cpp -shared_params YourSharedParamsName -{ - shared_param_named mySharedParam1 float4 0.1 0.2 0.3 0.4 - ... -} -``` - -As you can see, you need to use the keyword ’shared\_params’ and follow it with the name that you will use to identify these shared parameters. Inside the curly braces, you can define one parameter per line, in a way which is very similar to the [param\_named](#param_005fnamed) syntax. The definition of these lines is: -@par -Format: shared\_param\_named <param\_name> <param\_type> \[<\[array\_size\]>\] \[<initial\_values>\] - -@param param_name must be unique within the set -@param param_type can be any one of float, float2, float3, float4, int, int2, int3, int4, matrix2x2, matrix2x3, matrix2x4, matrix3x2, matrix3x3, matrix3x4, matrix4x2, matrix4x3 and matrix4x4. -@param array_size allows you to define arrays of param\_type should you wish, and if present must be a number enclosed in square brackets (and note, must be separated from the param\_type with whitespace). -@param initial_values If you wish, you can also initialise the parameters by providing a list of values. - -Once you have defined the shared parameters, you can reference them inside default\_params and params blocks using [shared\_params\_ref](#shared_005fparams_005fref). You can also obtain a reference to them in your code via Ogre::GpuProgramManager::getSharedParameters, and update the values for all instances using them. - -## Hardware Support - -Furthermore, shared_params can be mapped to hardware buffers, if supported by the RenderSystem. To enable this, you have to provide a matching declaration in your shader. - -For HLSL, that would be a constant buffer defined as -```cpp -cbuffer YourSharedParamsName -{ - float4 mySharedParam1; -} -``` - -and for GLSL a uniform block defined as -```cpp -layout(std140, row_major) uniform YourSharedParamsName -{ - vec4 mySharedParam1; -}; -``` - -# Shadows and Vertex Programs {#Shadows-and-Vertex-Programs} - -When using @ref Shadows, the use of vertex programs can add some additional complexities, because %Ogre can only automatically deal with everything when using the fixed-function pipeline. If you use vertex programs, and you are also using shadows, you may need to make some adjustments. - -- If you use **stencil shadows**, then any vertex programs which do vertex deformation can be a problem, because stencil shadows are calculated on the CPU, which does not have access to the modified vertices. If the vertex program is doing standard skeletal animation, this is ok (see section above) because %Ogre knows how to replicate the effect in software, but any other vertex deformation cannot be replicated, and you will either have to accept that the shadow will not reflect this deformation, or you should turn off shadows for that object. -- If you use **texture shadows**, then vertex deformation is acceptable; however, when rendering the object into the shadow texture (the shadow caster pass), the shadow has to be rendered in a solid colour (linked to the ambient colour). You must therefore provide an alternative vertex program, so %Ogre provides you with a way of specifying one to use when rendering the caster. - -Basically you specify an alternate material to use when rendering the object into the shadow texture: - -```cpp -technique myShaderBasedTechnique -{ - shadow_caster_material myShadowCasterMaterial - pass - { - ... - } -} -``` - -When rendering a shadow caster, Ogre will automatically use the alternate material. You can bind the same or different parameters to the program - the most important thing is that you bind @c *ambient_light_colour*, since this determines the colour of the shadow in modulative texture shadows. If you don’t supply an alternate material, Ogre will fall back on a fixed-function material which will not reflect any vertex deformation you do in your vertex or geometry programs. - -In addition, when rendering the shadow receivers with shadow textures, Ogre needs to project the shadow texture. It does this automatically in fixed function mode, but if the receivers use vertex programs, they need to have a shadow receiver material which does the usual vertex deformation, but also generates projective texture coordinates. - -@note At this point you can as well just extend your original program for @ref Integrated-Texture-Shadows. The only advantage of the technique below is that you can use the same material with and without shadow mapping. - -The alternative material is linked into the technique - similarly to the caster material - like: - -```cpp -technique myShaderBasedTechnique -{ - shadow_receiver_material myShadowReceiverMaterial - ... -} - -material myShadowReceiverMaterial -{ - ... - vertex_program_ref myShadowReceiverVertexProgram - { - param_indexed_auto 0 worldviewproj_matrix - param_indexed_auto 4 texture_worldviewproj_matrix - } - ... -} -``` - -For the purposes of writing the alternate program, there is an automatic parameter binding of @c texture_worldviewproj_matrix which provides the program with texture projection parameters. The vertex program should do it’s normal vertex processing, and generate texture coordinates using this matrix and place them in texture coord sets 0 and 1, since some shadow techniques use 2 texture units. The colour of the vertices output by this vertex program must always be white, so as not to affect the final colour of the rendered shadow. - -When using additive texture shadows, the @c shadow_receiver_material replaces the lighting render, so if you perform any fragment program lighting you also need to pull in a custom fragment program: - -```cpp -pass -{ - fragment_program_ref myShadowReceiverFragmentProgram - { - param_named_auto lightDiffuse light_diffuse_colour 0 - } - texture_unit - { - content_type shadow - } -} -``` - -You should pass the projected shadow coordinates from the custom vertex program. As for textures, define a @c texture_unit with @c content_type @c shadow to pull the shadow texture. Your shadow receiver fragment program is likely to be the same as the bare lighting pass of your normal material, except that you insert an extra texture sampler for the shadow texture, which you will use to adjust the result by (modulating diffuse and specular components). - -# Instancing in Vertex Programs {#Instancing-in-Vertex-Programs} - -You can implement hardware instancing by writing a vertex program which reads the world matrix of each instance from a `float3x4` vertex attribute. -However, you need to communicate this support to %Ogre so it batches the instances instead of rendering them individually. -You do this by adding the following attribute to your `vertex_program` definition: - -```cpp - includes_instancing true -``` - -When you do this, all SubEntities with the same material will be batched together. %Ogre will create and populate an instance buffer with the world matrices of the instances. This buffer is provided in the `TEXCOORD1` attribute (also consuming `TEXCOORD2` and `TEXCOORD3`) to the vertex shader. - -When batching, all instances are rendered in a single draw-call. All per-renderable operations are only performed with the first SubMesh of the batch. - -Therefore the following features are not supported: -- `start_light` and `iteration` (all instances share the same lights) -- flip culling on negative scale (all instances use the same face order) -- custom renderable parameters (not implemented) -- light scissoring & clipping (not implemented) -- manualLightList (not implemented) - -@note Instancing cannot be used together with skeletal animation (neither Hardware nor Software). - -# Skeletal Animation in Vertex Programs {#Skeletal-Animation-in-Vertex-Programs} - -You can implement skeletal animation in hardware by writing a vertex program which uses the per-vertex blending indices and blending weights, together with an array of world matrices (which will be provided for you by Ogre if you bind the automatic parameter ’world\_matrix\_array\_3x4’). However, you need to communicate this support to Ogre so it does not perform skeletal animation in software for you. You do this by adding the following attribute to your `vertex_program` definition: - -```cpp - includes_skeletal_animation true -``` - -When you do this, any skeletally animated entity which uses this material will forgo the usual animation blend and will expect the vertex program to do it, for both vertex positions and normals. Note that ALL submeshes must be assigned a material which implements this, and that if you combine skeletal animation with vertex animation (See [Animation](@ref Animation)) then all techniques must be hardware accelerated for any to be. - - -# Morph Animation in Vertex Programs {#Morph-Animation-in-Vertex-Programs} - -You can implement morph animation in hardware by writing a vertex program which linearly blends between the first and second position keyframes passed as positions and the first free texture coordinate set, and by binding the animation\_parametric value to a parameter (which tells you how far to interpolate between the two). However, you need to communicate this support to Ogre so it does not perform morph animation in software for you. You do this by adding the following attribute to your `vertex_program` definition: - -```cpp - includes_morph_animation true -``` - -When you do this, any skeletally animated entity which uses this material will forgo the usual software morph and will expect the vertex program to do it. Note that if your model includes both skeletal animation and morph animation, they must both be implemented in the vertex program if either is to be hardware acceleration. Note that ALL submeshes must be assigned a material which implements this, and that if you combine skeletal animation with vertex animation (See [Animation](#Animation)) then all techniques must be hardware accelerated for any to be. - -# Pose Animation in Vertex Programs {#Pose-Animation-in-Vertex-Programs} - -You can implement pose animation (blending between multiple poses based on weight) in a vertex program by pulling in the original vertex data (bound to position), and as many pose offset buffers as you’ve defined in your ’includes\_pose\_animation’ declaration, which will be in the first free texture unit upwards. You must also use the animation\_parametric parameter to define the starting point of the constants which will contain the pose weights; they will start at the parameter you define and fill ’n’ constants, where ’n’ is the max number of poses this shader can blend, i.e. the parameter to includes\_pose\_animation. - -```cpp - includes_pose_animation 4 -``` - -Note that ALL submeshes must be assigned a material which implements this, and that if you combine skeletal animation with vertex animation (See [Animation](#Animation)) then all techniques must be hardware accelerated for any to be. - -# Vertex Texture Fetch {#Vertex-Texture-Fetch} - -More recent generations of video card allow you to perform a read from a texture in the vertex program rather than just the fragment program, as is traditional. This allows you to, for example, read the contents of a texture and displace vertices based on the intensity of the colour contained within. - - - -## Declaring the use of vertex texture fetching - -If your vertex program makes use of Vertex Texture Fetch, you should declare that as - -```cpp - uses_vertex_texture_fetch true -``` - -Since hardware support for vertex texture fetching is not ubiquitous, you should use the directive when declaring your vertex programs which use vertex textures, so that if it is not supported, technique fallback can be enabled. This is not strictly necessary for DirectX-targeted shaders, since vertex texture fetching is only supported in vs\_3\_0, which can be stated as a required syntax in your shader definition, but for OpenGL (GLSL), there are cards which support GLSL but not vertex textures, so you should be explicit about your need for them. - - - -## DirectX9 binding limitations - -Shader Model 3.0 (SM3.0) hardware under DirectX9 includes 4 sampler bindings for the purposes of vertex textures. Ogre assigns the first 4 texture units to these bindings - therefore you should put fragment-only textures last. - - - -## Texture format limitations - -Again as at the time of writing, the types of texture you can use in a vertex program are limited to 1- or 4-component, full precision floating point formats. In code that equates to PF\_FLOAT32\_R or PF\_FLOAT32\_RGBA. No other formats are supported. In addition, the textures must be regular 2D textures (no cube or volume maps) and mipmapping and filtering is not supported, although you can perform filtering in your vertex program if you wish by sampling multiple times. - - - -## Hardware limitations - -As at the time of writing (early Q3 2006), ATI do not support texture fetch in their current crop of cards (Radeon X1n00). nVidia do support it in both their 6n00 and 7n00 range. ATI support an alternative called ’Render to Vertex Buffer’, but this is not standardised at this time and is very much different in its implementation, so cannot be considered to be a drop-in replacement. This is the case even though the Radeon X1n00 cards claim to support vs\_3\_0 (which requires vertex texture fetch). - -# Programmatic creation {#GpuProgram-API} - -In case you need to create GPU Programs programmatically, see the following example for how the script is mapped to the API. - -```cpp -vertex_program glTF2/PBR_vs glsl -{ - source pbr-vert.glsl - preprocessor_defines HAS_NORMALS,HAS_TANGENTS - default_params - { - param_named_auto u_MVPMatrix worldviewproj_matrix - } -} -``` -becomes -```cpp -using namespace Ogre; -GpuProgramManager& mgr = GpuProgramManager::getSingleton(); - -GpuProgramPtr vertex_program = mgr.createProgram("glTF2/PBR_vs", RGN_DEFAULT, "glsl", GPT_VERTEX_PROGRAM); -vertex_program->setSource("pbr-vert.glsl"); -vertex_program->setParameter("preprocessor_defines", "HAS_NORMALS,HAS_TANGENTS"); - -GpuProgramParametersPtr params = vertex_program->getDefaultParameters(); -params->setNamedAutoConstant("u_MVPMatrix", GpuProgramParameters::ACT_WORLDVIEWPROJ_MATRIX); -``` - -@page Cross-platform-Shaders Cross-platform Shaders - -When targeting multiple graphics APIs, one typically needs to provide separate shaders for each API. This results in lots of duplicated code gets out of hand quickly. - -@tableofcontents - -To support using the same shader code for multiple APIs, %Ogre provides the following mechanisms. -- @c \#include directives are universally supported - even with GLSL, so you can rely on them to organised your shaders. -- There are several built-in defines that can be used to conditionally compile different versions of the same shader. - -# Built-in defines -The following defines are available: -- The current shading language and native version: e.g. @c OGRE_GLSL=120, @c OGRE_HLSL=3 -- The current shader type: e.g. @c OGRE_VERTEX_SHADER, @c OGRE_FRAGMENT_SHADER -- Whether @ref reversed-depth is enabled: @c OGRE_REVERSED_Z - -# Cross-platform macros {#OgreUnifiedShader} - -Additionally, the `OgreUnifiedShader.h` provides macros to map GLSL to HLSL and (to some extent) Metal. - -As everything is handled by standard macros, the conversion can be performed by simply running the standard c preprocessor (`cpp`) on them - even without running %Ogre. - -In general, you have to do the following changes compared to regular GLSL: -- Add the `#include ` directive at the top of the file -- Use the `MAIN_PARAMETERS` and `MAIN_DECLARATION` directives instead of `void main()` -- Use the `IN`/ `OUT` macros to specify non-uniform parameters that are passed to the main function. -- Wrap the uniform paramters in the `OGRE_UNIFORMS` macro -- Declare Samplers with `SAMPLER2D/3D/CUBE/..` macros instead of `sampler2D/3D/Cube/..` -- Use `mtxFromRows` / `mtxFromCols` to construct matrices from vectors -- Use the HLSL style `mul` instead of `*` to multiply matrices -- Use `vec2_splat(1.0)` instead of the `vec2(1.0)` single component constructor. - -Lets take a look on how to use the `OgreUnifiedShader.h` macros by starting with a simple GLSL shader: - -```cpp -uniform mat4 worldMatrix; - -attribute vec4 vertex; -void main() -{ - gl_Position = worldMatrix * vertex; -} -``` - -to make it cross-platform, we need to modify it as: - -```cpp -#include - -OGRE_UNIFORMS( -uniform mat4 worldMatrix; -) - -MAIN_PARAMETERS -IN(vec4 vertex, POSITION) -MAIN_DECLARATION -{ - gl_Position = mul(worldMatrix, vertex); -} -``` - -@note If you only target different versions of the same API, there are reduced headers: -- `HLSL_SM4Support.hlsl` providing the `SAMPLER*` macros for mapping HLSL9/ Cg and HLSL SM4 (D3D11) -- `GLSL_GL3Support.glsl` providing the `IN`/ `OUT` macros and `texture` aliases for mapping GLSL <= 120 and GLSL >= 130 - -# Uber shader tips - -To toggle features on and off use a shader skeleton like this: - -```cpp -#ifdef USE_UV -#include "parameters_uv.glsl" -#endif -#ifdef USE_SKINNING -#include -#endif -... - -void main() -{ -#ifdef USE_UV - #include -#endif -#ifdef USE_SKINNING - #include -#endif -#ifdef USE_TANGENT - #include -#endif - ... - gl_Position = ...; -} -``` - -then in the material file, you can instantiate it as: - -```cpp -vertex_program TextureAndSkinning glsl -{ - source UberShader_vp.glsl - preprocessor_defines USE_UV,USE_SKINNING - default_params - { - ... - } -} -``` -and reference it with your materials. - -Incidentally, this is very similar to what the [RTSS](@ref rtss) is doing internally. Except, you do not need the @c preprocessor_defines part, as it can derive automatically from the material what needs to be done. diff --git a/Docs/src/images/ResourceManagement.svg b/Docs/src/images/ResourceManagement.svg deleted file mode 100644 index 267ab5dfaf7..00000000000 --- a/Docs/src/images/ResourceManagement.svg +++ /dev/null @@ -1,59 +0,0 @@ -ApplicationResourceGroupManagerResourceManagerResourcecreateResourceGroup(group)loop[resources.cfg]addResourceLocation(loc, type, group)addToIndex(file)initialiseResourceGroup(group)parseScript(file)loop[Examples.material]create(name, group)<< new >>load(name, group)<< new >>prepareopenResource(name, group)DataStreamPtrResourcePtrloadResourceGroup(group)loop[group]loadclearResourceGroup(group)loop[group]remove(name)<< delete >> \ No newline at end of file diff --git a/Docs/src/images/TextureSource.svg b/Docs/src/images/TextureSource.svg deleted file mode 100644 index 6742cde52a8..00000000000 --- a/Docs/src/images/TextureSource.svg +++ /dev/null @@ -1,10 +0,0 @@ -ExternalTextureSourcesetParameter()ExternalTextureSourceManagersetExternalTextureSource()setCurrentPlugin()createDefinedTexture()ScriptTranslatorSet "video" plugin activeParse & set parametersCreate TexturePlugin_TheoraVideoSysteminstall()Plugins.cfgPlugin=..Plugin=Plugin_TheoraVideoSystemPlugin=..Sample Material Scripttexture_source video{filename test.mpegplay_mode playsound_mode on} \ No newline at end of file diff --git a/Docs/src/images/cc_licensebutton.png b/Docs/src/images/cc_licensebutton.png deleted file mode 100644 index e76aeffd876..00000000000 Binary files a/Docs/src/images/cc_licensebutton.png and /dev/null differ diff --git a/Docs/src/images/depthbias.svg b/Docs/src/images/depthbias.svg deleted file mode 100644 index 9dc6b91f726..00000000000 --- a/Docs/src/images/depthbias.svg +++ /dev/null @@ -1,572 +0,0 @@ - - - -image/svg+xml \ No newline at end of file diff --git a/Docs/src/images/numpy_arr.png b/Docs/src/images/numpy_arr.png deleted file mode 100644 index f5223384b34..00000000000 Binary files a/Docs/src/images/numpy_arr.png and /dev/null differ diff --git a/Docs/src/images/numpy_final.png b/Docs/src/images/numpy_final.png deleted file mode 100644 index 0557f63beec..00000000000 Binary files a/Docs/src/images/numpy_final.png and /dev/null differ diff --git a/Docs/src/images/optfrust.svg b/Docs/src/images/optfrust.svg deleted file mode 100644 index 1d2dba6b658..00000000000 --- a/Docs/src/images/optfrust.svg +++ /dev/null @@ -1,777 +0,0 @@ - - - -image/svg+xml \ No newline at end of file diff --git a/Docs/src/images/renderOneFrame.svg b/Docs/src/images/renderOneFrame.svg deleted file mode 100644 index 0e9d420a0cf..00000000000 --- a/Docs/src/images/renderOneFrame.svg +++ /dev/null @@ -1,55 +0,0 @@ -ApplicationRootRenderSystemRenderTargetViewportCameraSceneManagerRenderablerenderOneFrame_updateAllRenderTargetsupdateupdate_renderScene_renderScene_renderVisibleObjects_renderQueueGroupObjectsloop_issueRenderOpgetRenderOperationRenderOperation_render \ No newline at end of file diff --git a/Docs/src/images/uml-overview.svg b/Docs/src/images/uml-overview.svg deleted file mode 100644 index 8a32677428c..00000000000 --- a/Docs/src/images/uml-overview.svg +++ /dev/null @@ -1,45 +0,0 @@ -SceneManagementPluginResource ManagementPluginRenderingPluginMovableObjectEntityCameraLightSceneNodeSceneManagerOctreeSceneManagerResourceGroupManagerResourceManagerImageCodecMeshMaterialGpuProgramTextureFreeImageCodecRenderWindowRenderableRenderSystemHardwareBufferManagerGLTextureGLRenderSystemRoot \ No newline at end of file diff --git a/Docs/src/instancing.md b/Docs/src/instancing.md deleted file mode 100644 index 396a1374b24..00000000000 --- a/Docs/src/instancing.md +++ /dev/null @@ -1,390 +0,0 @@ -# Instancing User-Guide {#WhatIsInstancing} - -@tableofcontents - -A common question is why should I use instancing. -The big reason is performance. -There can be 10x improvements or more when used correctly. -Here's a guide on when you should use instancing: - -1. You have *a lot* of Entities that are repeated and based on the same Mesh (i.e. a rock, a building, a tree, loose leaves, enemies, irrelevant crowds or NPCs) -2. These Entities that repeat a lot also share the same material (or just a few materials, i.e. 3 or 4) -3. The bottleneck in your game is the CPU. - -If these three requirements are all met in your game, chances are instancing is for you. -There will be minimal gains when using instancing on an Entity that repeats very little, or if each instance actually has a different material, or it could run even slower if the Entity never repeats. - -If the bottleneck in your game is not CPU (i.e. it's in the GPU) then instancing won't make a noticeable difference. - -## Instances per batch {#InstancesPerBatch} - -As explained in the previous section, instancing groups all instances into one draw call. -However this is half the truth. -Instancing actually groups a certain number of instances into a batch. -One batch = One draw call. - -If the technique is using 80 instances per batch; then rendering 160 instances is going to need 2 draw calls (two batches); -if there are 180 instances, 3 draw calls will be needed (3 batches). - -What is a good value for instances-per-batch setting? -That depends on a lot of factors, which you will have to profile. -Normally, increasing the number should improve performance because the system is most likely CPU bottleneck. -However, past certain number, certain trade offs begin to show up: - -- Culling is first performed at batch level, then for HW techniques culling is also done at per instance level. - If the batch contains too many instances, its AABB will grow too large; thus the hierarchy culling will always pass and Ogre won't be able skip entire batches. -- If the instance per batch is at 10.000 and the application created 10.001 instances; - a lot of RAM & VRAM will be wasted because it's set for 20.000 instances; - HW techniques will spent an excessive amount of CPU time parsing the 9.999 inactive instances; - and SW techniques will saturate the Bus bandwidth sending null matrices for the inactive instances to the GPU. - -The actual value will depend a lot on the application and whether all instances are often on screen or frustum culled and whether the total number of instances can be known at production time (i.e. environment props). -Normally numbers between 80 and 500 work best, but there have been cases where big values like 5.000 actually improved performance. - -# Techniques {#InstancingTechniques} - -Ogre supports 4 different instancing techniques. Unfortunately, each of them requires a different vertex shader, since their approaches are different. -Also their compatibility and performance varies. - -## ShaderBased {#InstancingTechniquesShaderBased} - -@copybrief Ogre::InstanceBatchShader -@copydetails Ogre::InstanceBatchShader - -Vertex Shader input example: -```cpp - ... - float4 blendIdx : BLENDINDICES, - uniform float3x4 worldMatrix3x4Array[80], - ... -``` - -Vertex position calculation example: -```cpp - int idx = int(blendIdx[0]); - float4 worldPos = float4( mul( worldMatrix3x4Array[idx], position ).xyz, 1.0f ); - oClipPos = mul( viewProjMatrix, worldPos ); - ... -``` - -See `Examples/Instancing/RTSS/Robot` for an example on how to use instancing with the [RTSS: Run Time Shader System](@ref rtss) - -See `material Examples/Instancing/ShaderBased` for an example on how to write the vertex shader. (You can find these files in OGRE sources from before v1.12) -Files: - - ShaderInstancing.material - - ShaderInstancing.vert (GLSL) - - ShaderInstancing.cg (Cg, works with HLSL) - -## VTF (Software) {#InstancingTechniquesVTFSoftware} - -@copybrief Ogre::BaseInstanceBatchVTF -@copydetails Ogre::BaseInstanceBatchVTF - -Texture unit example: -``` -texture_unit InstancingVTF -{ - filtering none -} -``` - -Vertex Shader input example: -``` - ... - float4 m01 : TEXCOORD1, - float4 m23 : TEXCOORD2, - uniform sampler2D matrixTexture : register(s0), // s0 if texture_unit InstancingVTF appears first - ... -``` - -Vertex position calculation example: - -@snippet Samples/Media/materials/programs/HLSL_Cg/VTFInstancing.cg world_pos - -See `material Examples/Instancing/VTF` for an example on how to write the vertex shader and setup the material. -Files: - - VTFInstancing.material - - VTFInstancing.vert (GLSL) - - VTFInstancing.cg (Cg, also works with HLSL) - -## HW VTF {#InstancingTechniquesHWVTF} - -This is the same technique as VTF; but implemented through hardware instancing. -It is probably one of the best and most flexible techniques. - -The vertex shader has to be slightly different from SW VTF version. - -Texture unit example: -``` -texture_unit InstancingVTF -{ - filtering none -} -``` - -Vertex Shader input example: -``` - float4 m03 : TEXCOORD1, - float2 mOffset : TEXCOORD2, - uniform sampler2D matrixTexture : register(s1), -``` - -Vertex position calculation example: - -@snippet Samples/Media/materials/programs/HLSL_Cg/HW_VTFInstancing.cg world_pos - -See `material Examples/Instancing/HW_VTF` for an example on how to write the vertex shader and setup the material. -Files: - - HW\_VTFInstancing.material - - HW\_VTFInstancing.vert (GLSL) - - HW\_VTFInstancing.cg (Cg, works with HLSL) - -### HW VTF LUT {#InstancingTechniquesHW} - -LUT is a special feature of HW VTF; which stands for Look Up Table. -It has been particularly designed for drawing large animated crowds. - -The technique is a trick that works by animating a limited number of instances (i.e. 16 animations) storing them in a look up table in the VTF, and then repeating these animations to all instances uniformly, giving the appearance that all instances are independently animated when seen in large crowds. - -To enable the use of LUT, `SceneManager::createInstanceManager`'s flags must include the flag `IM_VTFBONEMATRIXLOOKUP` and specify HW VTF as technique. - -```cpp -mSceneMgr->createInstanceManager("InstanceMgr","MyMesh.mesh", - ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME, - InstanceManager::HWInstancingVTF, - numInstancesPerBatch,IM_USEALL|IM_VTFBONEMATRIXLOOKUP ); -``` - -See `material Examples/Instancing/HW_VTF_LUT`. -Files: - - Same as HW VTF (different macros defined) - -## HW Basic {#InstancingTechniquesHWBasic} - -@copybrief Ogre::InstanceBatchHW -@copydetails Ogre::InstanceBatchHW - -Vertex Shader input example: -```cpp - ... - float3x4 worldMatrix : TEXCOORD1, - ... -``` - -Vertex position calculation example: -```cpp - ... - float4 worldPos = float4( mul( worldMatrix, position ).xyz, 1.0f ); - oClipPos = mul( viewProjMatrix, worldPos ); - ... -``` -See `Examples/Instancing/RTSS/Robot` for an example on how to use instancing with the [RTSS: Run Time Shader System](@ref rtss) - -See `material Examples/Instancing/HWBasic` for an example. (You can find these files in OGRE sources from before v1.12) -Files: - - HWInstancing.material - - HWBasicInstancing.vert (GLSL) - - HWBasicInstancing.cg (Cg, works with HLSL) - -# Custom parameters {#InstancingCustomParameters} - -Some instancing techniques allow passing custom parameters to vertex shaders. -For example a custom colour in an RTS game to identify player units; a single value for randomly colouring vegetation, light parameters for rendering deferred shading's light volumes (diffuse colour, specular colour, etc) - -At the time of writing only HW Basic supports passing the custom parameters. -All other techniques will ignore it.[^8] - -To use custom parameters, call `InstanceManager::setNumCustomParams` to tell the number of custom parameters the user will need. -**This number cannot be changed after creating the first batch** (call createInstancedEntity) - -Afterwards, it's just a matter of calling `InstancedEntity::setCustomParam` with the param you wish to send. - -For HW Basic techniques, the vertex shader will receive the custom param in an extra `TEXCOORD.` - -```cpp - InstanceManager *instanceMgr;//Assumed to be valid ptr -instanceMgr->setNumCustomParams(2); - -InstancedEntity *instancedEntity =instanceMgr->createInstancedEntity("myMaterial"); -instancedEntity->setCustomParam(0,Vector4(1.0f,1.0f,1.2f,0.0f)); -instancedEntity->setCustomParam(1,Vector4(0.2f,0.0f,0.7f,1.0f)); -``` - -# Supporting multiple submeshes {#InstancingMultipleSubmeshes} - -Multiple submeshes means different instance managers, because instancing can only be applied to the same submesh. - -Nevertheless, it is actually quite easy to support multiple submeshes. -The first step is to create the InstanceManager setting the `subMeshIdx` parameter to the number of submesh you want to use: - -```cpp -std::vectorinstanceManagers; -MeshPtr mesh =MeshManager::getSingleton().load("myMesh.mesh"); -for(uint16 i=0;igetNumSubMeshes();++i ) -{ - InstanceManager *mgr = - mSceneMgr->createInstanceManager("MyManager"+StringConverter::toString(i ), - "myMesh.mesh", - ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME, - InstanceManager::HWInstancingVTF,numInstancePerBatch, - flags,i ); - instanceManagers.push_back(mgr ); -} -``` - -The second step lies in sharing the transform with one of the submeshes (which will be named 'master'; i.e. the first submesh) to improve performance and reduce RAM consumption when creating the Instanced Entities: - -```cpp -SceneNode *sceneNode; //Assumed to be valid ptr -std::vectorinstancedEntities; -for(size_t i=0;icreateInstancedEntity("MyMaterial"); - - if(i !=0) - instancedEntities[0]->shareTransformWith(ent ); - - sceneNode->attachObject(ent ); - instancedEntities.push_back(ent ); -} -``` - -Note that it is perfectly possible that each `InstancedEntity` based on a different "submesh" uses a different material. -Selecting the same material won't cause the InstanceManagers to get batched together (though the RenderQueue will try to reduce state change reduction, like with any normal Entity). - -Because the transform is shared, animating the master InstancedEntity (in this example, `instancedEntity[0]`) will cause all other slave instances to follow the same animation. - -To destroy the instanced entities, use the normal procedure: - -```cpp -SceneNode *sceneNode; //Assumed to be valid ptr -std::vectorinstancedEntities; -for(size_t i=0;idestroyInstancedEntity(instancedEntities[i]); -} -mSceneMgr->getRootSceneNode()->removeAndDestroyChild(sceneNode ); -``` - -# Defragmenting batches {#InstancingDefragmentingBatches} - -## What is batch fragmentation? {#InstancingDefragmentingBatchesIntro} - -There are two kinds of fragmentation: - -1. "Deletion" Fragmentation is when many instances have been created, spanning multiple batches; *and many of them got later removed* but they were all from different batches. - If there were 10 instances per batch, 100 instances created, then later 90 removed; it is possible that now there are 10 batches with one instance each (which equals 10 drawcalls); instead of being just 1 batch with 10 instances (which equals 1 drawcall). -2. "Culling" Fragmentation is also when many instances of different batches are all sparsed across the whole scene. - If they were defragmented, they would've been put together in the same batch (all instances sorted by proximity to each other should be in the same batch) to take advantage of hierarchy culling optimizations. - -Defragmented batches can dramatically improve performance: - -Suppose there 50 instances per batch, and 100 batches total (which means 5000 instanced entities of the same mesh with same material), and they're all moving all the time. - -Normally, Ogre first updates all instances' position, then their AABBs; -and while at it, computes the AABB for each batch that encloses all of its instances. - -When frustum culling, we first cull the batches, then we cull their instances[^9] (that are inside those culled batches). -**This is the typical hierachial culling optimization**. -We then upload the instances transforms to the GPU. - -After moving many instances around the whole world, they will make the batch' enclosing AABB bigger and bigger. -Eventually, every batch' AABB will be so large, that wherever the camera looks, all 100 batches will end up passing the frustum culling test; thus having to resort to cull all 5000 instances individually. - -## Prevention: Avoiding fragmentation {#InstancingDefragmentingBatchesPrevention} - -If you're creating static objects that won't move (i.e. trees), create them sorted by proximity. -This helps both types of fragmentation: - -1. When unloading areas (i.e. open world games), these objects will be removed all together, thus whole batches will no longer have active instances. -2. Batches and instances are often assigned by order of creation. - Those instances will belong to the same batch and thus maximizing culling efficiency. - -## Cure: Defragmenting on the fly {#InstancingDefragmentingBatchesOnTheFly} - -There are cases where preventing fragmentation, for example units in an RTS game. -By design, all units may end up scattering and moving from one extreme of the scene to the other after hours of gameplay; additionally, lots of units may be in an endless loop of creation and destroying, but if the loop for a certain type of unit is broken; it is possible to end up with the kind of "Deletion" Fragmentation too. - -For this reason, the function `InstanceManager::defragmentBatches( bool optimizeCulling )` exists. - -Using it as simple as calling the function. -**The sample NewInstancing shows how to do this interactively**. -When `optimizeCulling` is true, both types of fragmentation will be attempted to be fixed. -When false, only the "deletion" kind of fragmentation will be fixed. - -Take in mind that when `optimizeCulling = true` it takes significantly more time depending on the level of fragmentation and could cause framerate spikes, even stalls. -Do it sparingly and profile the optimal frequency of calling. - -# Troubleshooting {#InstancingTroubleshooting} - -@par Q: My mesh doesn't show up. -A: Verify you're using the right material, the vertex shader is set correctly, and it matches the instancing technique being used. - -@par Q: My animation plays quite differently than when it is an Entity, or previewed in [Ogre Mesh Viewer](https://github.com/OGRECave/ogre-meshviewer). -A: Your rig animation must be using more than one weight per bone. -You need to add support for it in the vertex shader, and make sure you didn't create the instance manager with the flags Ogre::IM_USEONEWEIGHT or Ogre::IM_FORCEONEWEIGHT. - -For example, to modify the HW VTF vertex shader, you need to sample the additional matrices from the VTF: - -```cpp -float2uv0 : TEXCOORD0; -// Up to four weights per vertex. Don't use this shader on a model with 3 weights per vertex, or 2 or 1 -float4m03_0 : TEXCOORD1;//m03.w is always 0 -float4m03_1 : TEXCOORD2; -float4m03_2 : TEXCOORD3; -float4m03_3 : TEXCOORD4; -float4mWeights : TEXCOORD5; - -float2mOffset : TEXCOORD6; - -float3x4worldMatrix[4]; -worldMatrix[0][0] =tex2D(matrixTexture, m03_0.xw +mOffset ); -worldMatrix[0][1] =tex2D(matrixTexture, m03_0.yw +mOffset ); -worldMatrix[0][2] =tex2D(matrixTexture, m03_0.zw +mOffset ); - -worldMatrix[1][0] =tex2D(matrixTexture, m03_1.xw +mOffset ); -worldMatrix[1][1] =tex2D(matrixTexture, m03_1.yw +mOffset ); -worldMatrix[1][2] =tex2D(matrixTexture, m03_1.zw +mOffset ); - -worldMatrix[2][0] =tex2D(matrixTexture, m03_2.xw +mOffset ); -worldMatrix[2][1] =tex2D(matrixTexture, m03_2.yw +mOffset ); -worldMatrix[2][2] =tex2D(matrixTexture, m03_2.zw +mOffset ); - -worldMatrix[3][0] =tex2D(matrixTexture, m03_3.xw +mOffset ); -worldMatrix[3][1] =tex2D(matrixTexture, m03_3.yw +mOffset ); -worldMatrix[3][2] =tex2D(matrixTexture, m03_3.zw +mOffset ); - -float4 worldPos = float4(mul(worldMatrix[0], inPos ).xyz, 1.0f )* mWeights.x; -worldPos +=float4(mul(worldMatrix[1], inPos ).xyz, 1.0f )* mWeights.y; -worldPos +=float4(mul(worldMatrix[2], inPos ).xyz, 1.0f )* mWeights.z; -worldPos +=float4(mul(worldMatrix[3], inPos ).xyz, 1.0f )* mWeights.w; - -float4 worldNor = float4(mul(worldMatrix[0], inNor ).xyz, 1.0f )* mWeights.x; -worldNor +=float4(mul(worldMatrix[1], inNor ).xyz, 1.0f )* mWeights.y; -worldNor +=float4(mul(worldMatrix[2], inNor ).xyz, 1.0f )* mWeights.z; -worldNor +=float4(mul(worldMatrix[3], inNor ).xyz, 1.0f )* mWeights.w; -``` - -As you can witness, a HW VTF vertex shader with 4 weights per vertex needs a lot of texture fetches. -Fortunately they fit the texture cache very well; nonetheless it's something to keep watching out. - -Instancing is meant for rendering large number of objects in a scene. -If you plan on rendering thousands or tens of thousands of animated objects with 4 weights per vertex, don't expect it to be fast; no matter what technique you use to draw them. - -Try convincing the art department to lower the animation quality or just use Ogre::IM_FORCEONEWEIGHT for Ogre to do the downgrade for you. -There are many plugins for popular modeling packages (3DS Max, Maya, Blender) out there that help automatizing this task. - -@par Q: The instance doesn't show up, or when playing animations the mesh deforms very weirdly or other very visible artifacts occur - -A: Your rig uses more than one weight per vertex. -Either create the instance manager with the flag Ogre::IM_FORCEONEWEIGHT, or modify the vertex shader to support the *exact* amount of weights per vertex needed (see previous questions). - -@par Q: How do I find how many weights per vertices is using my model? - -A: The quickest way is by looking at the type of Ogre::VES_BLEND_WEIGHTS, where `VET_FLOAT` means N weights. - -[^8]: In theory all other techniques could implement custom parameters but for performance reasons only HW VTF is well suited to implement it. - Though it yet remains to be seen whether it should be passed to the shader through the VTF, or through additional TEXCOORDs. - -[^9]: Only HW instancing techniques cull per instance. - SW instancing techniques send all of their instances, zeroing matrices of those instances that are not in the scene. diff --git a/Docs/src/manual.md b/Docs/src/manual.md deleted file mode 100644 index f52e0b669b8..00000000000 --- a/Docs/src/manual.md +++ /dev/null @@ -1,948 +0,0 @@ -# Manual {#manual} - -- @subpage Introduction -- @subpage The-Core-Objects -- @subpage Resource-Management -- @subpage Scripts -- @subpage rtss -- @subpage Mesh-Tools -- @subpage Hardware-Buffers -- @subpage Shadows -- @subpage Animation -- @subpage Instancing -- @subpage Cross-platform-Shaders - -@page Introduction Introduction - -This chapter is intended to give you an overview of the main components of OGRE and why they have been put together that way. - -# Object Orientation - more than just a buzzword - -The name is a dead giveaway. It says Object-Oriented Graphics Rendering Engine, and that’s exactly what it is. Ok, but why? Why did I choose to make such a big deal about this? - -Well, nowadays graphics engines are like any other large software system. They start small, but soon they balloon into monstrously complex beasts which just can’t be all understood at once. It’s pretty hard to manage systems of this size, and even harder to make changes to them reliably, and that’s pretty important in a field where new techniques and approaches seem to appear every other week. Designing systems around huge files full of C function calls just doesn’t cut it anymore - even if the whole thing is written by one person (not likely) they will find it hard to locate that elusive bit of code after a few months and even harder to work out how it all fits together. - -Object orientation is a very popular approach to addressing the complexity problem. It’s a step up from decomposing your code into separate functions, it groups function and state data together in classes which are designed to represent real concepts. It allows you to hide complexity inside easily recognised packages with a conceptually simple interface so they are easy to recognise and have a feel of ’building blocks’ which you can plug together again later. You can also organise these blocks so that some of them look the same on the outside, but have very different ways of achieving their objectives on the inside, again reducing the complexity for the developers because they only have to learn one interface. - -I’m not going to teach you OO here, that’s a subject for many other books, but suffice to say I’d seen enough benefits of OO in business systems that I was surprised most graphics code seemed to be written in C function style. I was interested to see whether I could apply my design experience in other types of software to an area which has long held a place in my heart - 3D graphics engines. Some people I spoke to were of the opinion that using full C++ wouldn’t be fast enough for a real-time graphics engine, but others (including me) were of the opinion that, with care, and object-oriented framework can be performant. We were right. - -In summary, here’s the benefits an object-oriented approach brings to OGRE: - - -@par Abstraction -Common interfaces hide the nuances between different implementations of 3D API and operating systems - -@par Encapsulation -There is a lot of state management and context-specific actions to be done in a graphics engine - encapsulation allows me to put the code and data nearest to where it is used which makes the code cleaner and easier to understand, and more reliable because duplication is avoided - -@par Polymorphism -The behaviour of methods changes depending on the type of object you are using, even if you only learn one interface, e.g. a class specialised for managing indoor levels behaves completely differently from the standard scene manager, but looks identical to other classes in the system and has the same methods called on it - - - -# Multi-everything - -OGRE is more than a 3D engine that runs on one 3D API, on one platform, with one type of scene (indoor levels are most popular). OGRE is able to extend to any kind of scene (but yet still implements scene-specific optimisations under the surface), any platform and any 3D API. - -Therefore all the ’visible’ parts of OGRE are completely independent of platform, 3D API and scene type. There are no dependencies on Windows types, no assumptions about the type of scene you are creating, and the principles of the 3D aspects are based on core maths texts rather than one particular API implementation. - -Now of course somewhere OGRE has to get down to the nitty-gritty of the specifics of the platform, API and scene, but it does this in subclasses specially designed for the environment in question, but which still expose the same interface as the abstract versions. - -For example, there is a @c Win32Window class which handles all the details about rendering windows on a Win32 platform - however the application designer only has to manipulate it via the superclass interface Ogre::RenderWindow, which will be the same across all platforms. - -Similarly the Ogre::SceneManager class looks after the arrangement of objects in the scene and their rendering sequence. Applications only have to use this interface, but there is a Ogre::OctreeSceneManager class which optimises the scene management for outdoor levels, meaning you get both performance and an easy to learn interface. All applications have to do is hint about the kind of scene they will be creating and let OGRE choose the most appropriate implementation - this is covered in a later tutorial. - -OGRE’s object-oriented nature makes all this possible. Currently OGRE runs on different platforms using plugins to drive the underlying rendering API. Applications use OGRE at the abstract level, thus ensuring that they automatically operate on all platforms and rendering subsystems that OGRE provides without any need for platform or API specific code. - -@page The-Core-Objects The Core Objects - -@tableofcontents - -This tutorial gives you a quick summary of the core objects that you will use in OGRE and what they are used for. - - - -# Overview from 10,000 feet - -Shown below is a diagram of some of the core objects and where they ’sit’ in the grand scheme of things. This is not all the classes by a long shot, just a few examples of the more more significant ones to give you an idea of how it slots together. - -At the very top of the diagram is the Root object. This is your ’way in’ to the OGRE system, and it’s where you tend to create the top-level objects that you need to deal with, like scene managers, rendering systems and render windows, loading plugins, all the fundamental stuff. If you don’t know where to start, Root is it for almost everything, although often it will just give you another object which will actually do the detail work, since Root itself is more of an organiser and facilitator object. - -The majority of rest of OGRE’s classes fall into one of 3 roles: - -@par Scene Management -This is about the contents of your scene, how it’s structured, how it’s viewed from cameras, etc. Objects in this area are responsible for giving you a natural declarative interface to the world you’re building; i.e. you don’t tell OGRE "set these render states and then render 3 polygons", you tell it "I want an object here, here and here, with these materials on them, rendered from this view", and let it get on with it. - -@par Resource Management -All rendering needs resources, whether it’s geometry, textures, fonts, whatever. It’s important to manage the loading, re-use and unloading of these things carefully, so that’s what classes in this area do. - -@par Rendering -Finally, there’s getting the visuals on the screen - this is about the lower-level end of the rendering pipeline, the specific rendering system API objects like buffers, render states and the like and pushing it all down the pipeline. Classes in the Scene Management subsystem use this to get their higher-level scene information onto the screen. - -![](images/uml-overview.svg) - -You’ll notice that scattered around the edge are a number of plugins. OGRE is designed to be extended, and plugins are the usual way to go about it. Many of the classes in OGRE can be subclassed and extended, whether it’s changing the scene organisation through a custom SceneManager, adding a new render system implementation (e.g. Direct3D or OpenGL), or providing a way to load resources from another source (say from a web location or a database). Again this is just a small smattering of the kinds of things plugins can do, but as you can see they can plug in to almost any aspect of the system. This way, OGRE isn’t just a solution for one narrowly defined problem, it can extend to pretty much anything you need it to do. - - -# The Root object {#The-Root-Object} - -The Ogre::Root object is the entry point to the OGRE system. This object MUST be the first one to be created, and the last one to be destroyed. In the example applications I chose to make an instance of Root a member of my application object which ensured that it was created as soon as my application object was, and deleted when the application object was deleted. - -The root object lets you configure the system, for example through the Ogre::Root::showConfigDialog method which is an extremely handy method which performs all render system options detection and shows a dialog for the user to customise resolution, colour depth, full screen options etc. It also sets the options the user selects so that you can initialise the system directly afterwards. - -The root object is also your method for obtaining pointers to other objects in the system, such as the Ogre::SceneManager, Ogre::RenderSystem and various other resource managers. See below for details. - -Finally, if you run OGRE in continuous rendering mode, i.e. you want to always refresh all the rendering targets as fast as possible (the norm for games and demos, but not for windowed utilities), the root object has a method called Ogre::Root::startRendering, which when called will enter a continuous rendering loop which will only end when all rendering windows are closed, or any Ogre::FrameListener objects indicate that they want to stop the cycle (see below for details of Ogre::FrameListener objects). - -# The RenderSystem object {#The-RenderSystem-object} - -The Ogre::RenderSystem object is actually an abstract class which defines the interface to the underlying 3D API. It is responsible for sending rendering operations to the API and setting all the various rendering options. This class is abstract because all the implementation is rendering API specific - there are API-specific subclasses for each rendering API (e.g. D3DRenderSystem for Direct3D). After the system has been initialised through Ogre::Root::initialise, the Ogre::RenderSystem object for the selected rendering API is available via the Ogre::Root::getRenderSystem() method. - -However, a typical application should not normally need to manipulate the Ogre::RenderSystem object directly - everything you need for rendering objects and customising settings should be available on the Ogre::SceneManager, Material and other scene-oriented classes. It’s only if you want to create multiple rendering windows (completely separate windows in this case, not multiple viewports like a split-screen effect which is done via the RenderWindow class) or access other advanced features that you need access to the RenderSystem object. - -For this reason I will not discuss the Ogre::RenderSystem object further in these tutorials. You can assume the Ogre::SceneManager handles the calls to the Ogre::RenderSystem at the appropriate times. - - -# The SceneManager object {#The-SceneManager-object} - -Apart from the Ogre::Root object, this is probably the most critical part of the system from the application’s point of view. Certainly it will be the object which is most used by the application. The Ogre::SceneManager is in charge of the contents of the scene which is to be rendered by the engine. It is responsible for organising the contents using whatever technique it deems best, for creating and managing all the cameras, movable objects (entities), lights and materials (surface properties of objects), and for managing the ’world geometry’ which is the sprawling static geometry usually used to represent the immovable parts of a scene. - -It is to the SceneManager that you go when you want to create a camera for the scene. It’s also where you go to retrieve or to remove a light from the scene. There is no need for your application to keep lists of objects, the SceneManager keeps a named set of all of the scene objects for you to access, should you need them. Look in the main documentation under the getCamera, getLight, getEntity etc methods. - -The SceneManager also sends the scene to the RenderSystem object when it is time to render the scene. You never have to call the Ogre::SceneManager::_renderScene method directly though - it is called automatically whenever a rendering target is asked to update (see Ogre::Root::renderOneFrame for details). - -So most of your interaction with the SceneManager is during scene setup. You’re likely to call a great number of methods (perhaps driven by some input file containing the scene data) in order to set up your scene. You can also modify the contents of the scene dynamically during the rendering cycle if you create your own FrameListener object (see later). - -Because different scene types require very different algorithmic approaches to deciding which objects get sent to the RenderSystem in order to attain good rendering performance, the SceneManager class is designed to be subclassed for different scene types. The default SceneManager object will render a scene, but it does little or no scene organisation and you should not expect the results to be high performance in the case of large scenes. The intention is that specialisations will be created for each type of scene such that under the surface the subclass will optimise the scene organisation for best performance given assumptions which can be made for that scene type. An example is the @c OctreeSceneManager which optimises rendering for large levels based on the Octree partitioning scheme. - -You can specify the SceneManager type you want as the parameter of Ogre::Root::createSceneManager. If you do not specify any parameter, OGRE will use to the default SceneManager, which is well suited for small and moderate sized scenes. - -# The ResourceGroupManager Object {#The-ResourceGroupManager-Object} - -The Ogre::ResourceGroupManager class is actually a ’hub’ for loading of reusable resources like textures and meshes. It is the place that you define groups for your resources, so they may be unloaded and reloaded when you want. Servicing it are a number of ResourceManagers which manage the individual types of resource, like Ogre::TextureManager or Ogre::MeshManager. In this context, resources are sets of data which must be loaded from somewhere to provide OGRE with the data it needs. - -ResourceManagers ensure that resources are only loaded once and shared throughout the OGRE engine. They also manage the memory requirements of the resources they look after. They can also search in a number of locations for the resources they need, including multiple search paths and compressed archives (ZIP files). - -Most of the time you won’t interact with resource managers directly. Resource managers will be called by other parts of the OGRE system as required, for example when you request for a texture to be added to a Material, the Ogre::TextureManager will be called for you. If you like, you can call the appropriate resource manager directly to preload resources (if for example you want to prevent disk access later on) but most of the time it’s ok to let OGRE decide when to do it. - -One thing you will want to do is to tell the resource managers where to look for resources. You do this via Ogre::ResourceGroupManager::addResourceLocation. - -As its name already tells, the ResourceGroupManager keeps resources organized in Groups. These define a set of Resources that shall be loaded / unloaded as a unit. For example, it might be all the resources used for the level of a game. -By default the "General" group is used, which will only be unloaded on shutdown. To define your own groups use Ogre::ResourceGroupManager::createResourceGroup. - -Because there is only ever 1 instance of each resource manager in the engine, if you do want to get a reference to a resource manager use the following syntax: - -```cpp -Ogre::TextureManager::getSingleton().someMethod() -Ogre::MeshManager::getSingleton().someMethod() -``` -# The Mesh Object {#The-Mesh-Object} - -A Ogre::Mesh object represents a discrete model, a set of geometry which is self-contained and is typically fairly small on a world scale. Ogre::Mesh objects are assumed to represent movable objects and are not used for the sprawling level geometry typically used to create backgrounds. - -Ogre::Mesh objects are a type of resource, and are managed by the MeshManager resource manager. They are typically loaded from OGRE’s custom object format, the ’.mesh’ format. Mesh files are typically created by exporting from a modelling tool See [Exporters](@ref Exporters) and can be manipulated through various [Mesh Tools](@ref Mesh-Tools) - -You can also create Mesh objects manually by calling the Ogre::MeshManager::createManual method. This way you can define the geometry yourself, but this is outside the scope of this manual. - -Mesh objects are the basis for the individual movable objects in the world, which are called @ref Entities. - -Mesh objects can also be animated using See @ref Skeletal-Animation. - -# Entities {#Entities} - -An entity is an instance of a movable object in the scene. It could be a car, a person, a dog, a shuriken, whatever. The only assumption is that it does not necessarily have a fixed position in the world. - -Entities are based on discrete meshes, i.e. collections of geometry which are self-contained and typically fairly small on a world scale, which are represented by the Ogre::Mesh object. Multiple entities can be based on the same mesh, since often you want to create multiple copies of the same type of object in a scene. - -You create an entity by calling the Ogre::SceneManager::createEntity method, giving it a name and specifying the name of the mesh object which it will be based on (e.g. ’muscleboundhero.mesh’). The Ogre::SceneManager will ensure that the mesh is loaded by calling the Ogre::MeshManager resource manager for you. Only one copy of the Mesh will be loaded. - -Ogre::Entities are not deemed to be a part of the scene until you attach them to a Ogre::SceneNode (see the section below). By attaching entities to SceneNodes, you can create complex hierarchical relationships between the positions and orientations of entities. You then modify the positions of the nodes to indirectly affect the entity positions. - -When a Ogre::Mesh is loaded, it automatically comes with a number of materials defined. It is possible to have more than one material attached to a mesh - different parts of the mesh may use different materials. Any entity created from the mesh will automatically use the default materials. However, you can change this on a per-entity basis if you like so you can create a number of entities based on the same mesh but with different textures etc. - -To understand how this works, you have to know that all Mesh objects are actually composed of Ogre::SubMesh objects, each of which represents a part of the mesh using one Material. If a Ogre::Mesh uses only one Ogre::Material, it will only have one Ogre::SubMesh. - -When an Ogre::Entity is created based on this Mesh, it is composed of (possibly) multiple Ogre::SubEntity objects, each matching 1 for 1 with the Ogre::SubMesh objects from the original Mesh. You can access the Ogre::SubEntity objects using the Ogre::Entity::getSubEntity method. Once you have a reference to a Ogre::SubEntity, you can change the material it uses by calling it’s setMaterialName method. In this way you can make an Ogre::Entity deviate from the default materials and thus create an individual looking version of it. - -# Materials {#Materials} - -The Ogre::Material object controls how objects in the scene are rendered. It specifies what basic surface properties objects have such as reflectance of colours, shininess etc, how many texture layers are present, what images are on them and how they are blended together, what special effects are applied such as environment mapping, what culling mode is used, how the textures are filtered etc. - -Materials can either be set up programmatically, by calling Ogre::MaterialManager::create and tweaking the settings, or by specifying it in a ’script’ which is loaded at runtime. See [Material Scripts](@ref Material-Scripts) for more info. - -Basically everything about the appearance of an object apart from it’s shape is controlled by the Material class. - -The Ogre::MaterialManager class manages the master list of materials available to the scene. The list can be added to by the application by calling Ogre::MaterialManager::create, or by loading a Mesh (which will in turn load material properties). - -@copydetails Ogre::MaterialManager::getDefaultSettings() - -You can alter these settings by calling Ogre::MaterialManager::getDefaultSettings() and making the required changes to the Material which is returned. - -Entities automatically have Material’s associated with them if they use a Ogre::Mesh object, since the Ogre::Mesh object typically sets up it’s required materials on loading. You can also customise the material used by an entity as described in @ref Entities. Just create a new Material, set it up how you like (you can copy an existing material into it if you like using a standard assignment statement) and point the SubEntity entries at it using Ogre::SubEntity::setMaterialName(). - - - -# Overlays {#Overlays} - -Overlays allow you to render 2D and 3D elements on top of the normal scene contents to create effects like heads-up displays (HUDs), menu systems, status panels etc. The frame rate statistics panel which comes as standard with OGRE is an example of an overlay. Overlays can contain 2D or 3D elements. 2D elements are used for HUDs, and 3D elements can be used to create cockpits or any other 3D object which you wish to be rendered on top of the rest of the scene. - -You can create overlays either through the Ogre::OverlayManager::create method, or you can define them in an .overlay script. See [Overlay Scripts](@ref Overlay-Scripts) for more info. In reality the latter is likely to be the most practical because it is easier to tweak (without the need to recompile the code). Note that you can define as many overlays as you like: they all start off life hidden, and you display them by calling Ogre::Overlay::show. You can get pointers to them with Ogre::OverlayManager::getByName. You can also show multiple overlays at once, and their Z order is determined by the Ogre::Overlay::setZOrder() method. - - - - -## How to Enable Overlays - -The OverlaySystem is its own component, you need to manually initialize it, with the following two lines of code (mSceneMgr is a pointer to your current Ogre::SceneManager): - -```cpp -Ogre::OverlaySystem* pOverlaySystem = new Ogre::OverlaySystem(); -mSceneMgr->addRenderQueueListener(pOverlaySystem); -``` - -One Ogre::OverlaySystem per application is enough but you need to call addRenderQueueListener once per SceneManager. - -If you are using OgreBites, then you need to fetch the pre-existing OverlaySystem. -```cpp -Ogre::OverlaySystem* pOverlaySystem = myApplicationContext.getOverlaySystem(); -mSceneMgr->addRenderQueueListener(pOverlaySystem); -``` - -Where `myApplicationContext` is your OgreBites::ApplicationContext object. - - - -## Creating 2D Elements - -The Ogre::OverlayElement class abstracts the details of 2D elements which are added to overlays. All items which can be added to overlays are derived from this class. It is possible (and encouraged) for users of OGRE to define their own custom subclasses of OverlayElement in order to provide their own user controls. The key common features of all OverlayElements are things like size, position, basic material name etc. Subclasses extend this behaviour to include more complex properties and behaviour. - -An important built-in subclass of OverlayElement is Ogre::OverlayContainer. OverlayContainer is the same as a OverlayElement, except that it can contain other OverlayElements, grouping them together (allowing them to be moved together for example) and providing them with a local coordinate origin for easier lineup. - -The third important class is Ogre::OverlayManager. Whenever an application wishes to create a 2D element to add to an overlay (or a container), it should call Ogre::OverlayManager::createOverlayElement. The type of element you wish to create is identified by a string, the reason being that it allows plugins to register new types of OverlayElement for you to create without you having to link specifically to those libraries. For example, to create a panel (a plain rectangular area which can contain other OverlayElements) you would call `OverlayManager::getSingleton().createOverlayElement("Panel", "myNewPanel");`. - - - -## Adding 2D Elements to the Overlay - -Only OverlayContainers can be added direct to an overlay. The reason is that each level of container establishes the Zorder of the elements contained within it, so if you nest several containers, inner containers have a higher Z-order than outer ones to ensure they are displayed correctly. To add a container (such as a Panel) to the overlay, simply call Ogre::Overlay::add2D. - -If you wish to add child elements to that container, call Ogre::OverlayContainer::addChild. Child elements can be Ogre::OverlayElements or Ogre::OverlayContainer instances themselves. Remember that the position of a child element is relative to the top-left corner of it’s parent. - - - -## A word about 2D coordinates - -OGRE allows you to place and size elements based on 2 coordinate systems: **relative** and **pixel** based. - -
-
Pixel Mode
- -This mode is useful when you want to specify an exact size for your overlay items, and you don’t mind if those items get smaller on the screen if you increase the screen resolution (in fact you might want this). In this mode the only way to put something in the middle or at the right or bottom of the screen reliably in any resolution is to use the aligning options, whilst in relative mode you can do it just by using the right relative coordinates. This mode is very simple, the top-left of the screen is (0,0) and the bottom-right of the screen depends on the resolution. As mentioned above, you can use the aligning options to make the horizontal and vertical coordinate origins the right, bottom or center of the screen if you want to place pixel items in these locations without knowing the resolution. - -
Relative Mode
- -This mode is useful when you want items in the overlay to be the same size on the screen no matter what the resolution. In relative mode, the top-left of the screen is (0,0) and the bottom-right is (1,1). So if you place an element at (0.5, 0.5), it’s top-left corner is placed exactly in the center of the screen, no matter what resolution the application is running in. The same principle applies to sizes; if you set the width of an element to 0.5, it covers half the width of the screen. Note that because the aspect ratio of the screen is typically 1.3333 : 1 (width : height), an element with dimensions (0.25, 0.25) will not be square, but it will take up exactly 1/16th of the screen in area terms. If you want square-looking areas you will have to compensate using the typical aspect ratio e.g. use (0.1875, 0.25) instead. - -
- - -## Transforming Overlays - -Another nice feature of overlays is being able to rotate, scroll and scale them as a whole. You can use this for zooming in / out menu systems, dropping them in from off screen and other nice effects. See the Ogre::Overlay::scroll, Ogre::Overlay::rotate and Ogre::Overlay::setScale methods for more information. - - - -## GUI systems - -Overlays are only really designed for non-interactive screen elements, although you can create a simple GUI using the [Trays System](@ref trays). For a far more complete GUI solution, we recommend Ogre's integration with [Dear ImGui](), or third-party libraries like [CEGui]() or [MyGUI](). - -@page Mesh-Tools Mesh Tools - -There are a number of mesh tools available with OGRE to help you manipulate your meshes. - -@tableofcontents - -# XMLConverter {#XMLConverter} - -This tool can convert binary .mesh and .skeleton files to XML and back again - this is a very useful tool for debugging the contents of meshes, or for exchanging mesh data easily - many of the modeller mesh exporters export to XML because it is simpler to do, and @c OgreXMLConverter can then produce a binary from it. - -@par Usage -``` -OgreXMLConverter [options] sourcefile [destfile] -``` - -Run the tool with no arguments to see the available options. - -# MeshUpgrader {#MeshUpgrader} - -This tool is provided to allow you to upgrade your meshes when the binary format changes - sometimes we alter it to add new features and as such you need to keep your own assets up to date. -Furthermore, @c OgreMeshUpgrader can generate additional information for the mesh, like bounding regions and level-of-detail reduction. -See the @ref meshlod-generator Tutorial for details. - -@par Usage -``` -OgreMeshUpgrader [options] sourcefile [destfile] -``` - -Run the tool with no arguments to see the available options. - -@note -The OGRE release notes will notify you when meshes should be upgraded with a new release. - -# AssimpConverter {#AssimpConverter} - -This tool converts 3D-formats supported by [assimp](https://assimp-docs.readthedocs.io/en/stable/about/introduction.html) to native OGRE .mesh .skeleton and .material files. - -@par Usage -``` -OgreAssimpConverter [options] sourcefile [destination] -``` - -Run the tool with no arguments to see the available options. - -# Exporters {#Exporters} - -Exporters are plugins to 3D modelling tools which write meshes and skeletal animation to file formats which OGRE can use for realtime rendering. The files the exporters write end in .mesh and .skeleton respectively. - -Each exporter has to be written specifically for the modeller in question, although they all use a common set of facilities provided by Ogre::MeshSerializer and Ogre::SkeletonSerializer. They also normally require you to own the modelling tool. - -All the exporters here can be built from the source code, or you can download precompiled versions from the OGRE web site. - -## A Note About Modelling / Animation For OGRE - -There are a few rules when creating an animated model for OGRE: - -- You must have no more than 4 weighted bone assignments per vertex. If you have more, OGRE will eliminate the lowest weighted assignments and re-normalise the other weights. This limit is imposed by hardware blending limitations. -- All vertices must be assigned to at least one bone - assign static vertices to the root bone. -- At the very least each bone must have a keyframe at the beginning and end of the animation. - -If you’re creating non-animated meshes, then you do not need to be concerned with the above. - -Full documentation for each exporter is provided along with the exporter itself, and there is a [selection of the currently supported modelling tools at OGRECave](https://github.com/OGRECave). - -## A Note About empty Material Names - -All mesh files are required to have a material name set, otherwise most mesh tools will fail with an exception. -Even if they don't, the exception will happen deep inside the render-loop which is way harder to debug (unless you set the material programmatically). - -To set a material name for the mesh, you have these options: - - - Re-export the mesh from your preferred DCC (Digital Content Creator) exporter, making sure that a material has been assigned. - - Edit the mesh.xml file to set a material name and reprocess the xml with @c OgreXMLConverter. - - Edit the mesh file with [MeshMagick](https://github.com/OGRECave/meshmagick) to set a material name - -@page Shadows Shadows - -Shadows are clearly an important part of rendering a believable scene - they provide a more tangible feel to the objects in the scene, and aid the viewer in understanding the spatial relationship between objects. Unfortunately, shadows are also one of the most challenging aspects of 3D rendering, and they are still very much an active area of research. Whilst there are many techniques to render shadows, none is perfect and they all come with advantages and disadvantages. For this reason, %Ogre provides multiple shadow implementations, with plenty of configuration settings, so you can choose which technique is most appropriate for your scene. - -Shadow implementations fall into 2 basic categories: -- @ref Stencil-Shadows -- @ref Texture_002dbased-Shadows. - -This describes the method by which the shape of the shadow is generated. - -In addition, there is more than one way to render the shadow into the scene: -- @ref Modulative-Shadows, which darkens the scene in areas of shadow, and -- @ref Additive-Light-Masking, which by contrast builds up light contribution in areas which are not in shadow. - -You also have the option of @ref Integrated-Texture-Shadows which gives you complete control over texture shadow application, allowing for complex single-pass shadowing shaders. %Ogre supports all these combinations. - -@tableofcontents - -# Enabling shadows {#Enabling-shadows} - -Shadows are disabled by default, here’s how you turn them on and configure them in the general sense: - -1. Enable a shadow technique on the SceneManager as the **first** thing you doing your scene setup. It is important that this is done first because the shadow technique can alter the way meshes are loaded. Here’s an example: -```cpp -mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_ADDITIVE); -``` -2. Create one or more lights. Note that not all light types are necessarily supported by all shadow techniques, you should check the sections about each technique to check. Note that if certain lights should not cast shadows, you can turn that off by calling setCastShadows(false) on the light, the default is true. -3. Disable shadow casting on objects which should not cast shadows. Call setCastShadows(false) on objects you don’t want to cast shadows, the default for all objects is to cast shadows. -4. Configure shadow far distance. You can limit the distance at which shadows are considered for performance reasons, by calling Ogre::SceneManager::setShadowFarDistance. -5. Turn off the receipt of shadows on materials that should not receive them. You can turn off the receipt of shadows (note, not the casting of shadows - that is done per-object) by calling Material::setReceiveShadows or using the receive\_shadows material attribute. This is useful for materials which should be considered self-illuminated for example. Note that transparent materials are typically excluded from receiving and casting shadows, although see the [transparency\_casts\_shadows](#transparency_005fcasts_005fshadows) option for exceptions. - -# Opting out of shadows {#Opting-out-of-shadows} - -By default Ogre treats all non-transparent objects as shadow casters and receivers (depending on the shadow technique they may not be able to be both at once, check the docs for your chosen technique first). You can disable shadows in various ways: - -
-
Turning off shadow casting on the light
- -Calling `Light::setCastShadows(false)` will mean this light casts no shadows at all. - -
Turn off shadow receipt on a material
- -Calling `Material::setReceiveShadows(false)` will prevent any objects using this material from receiving shadows. - -
Turn off shadow casting on individual objects
- -Calling `MovableObject::setCastShadows(false)` will disable shadow casting for this object. - -
Turn off shadows on an entire rendering queue group
- -Calling `RenderQueueGroup::setShadowsEnabled(false)` will turn off both shadow casting and receiving on an entire rendering queue group. This is useful because Ogre has to do light setup tasks per group in order to preserve the inter-group ordering. Ogre automatically disables shadows on a number of groups automatically, such as `RENDER_QUEUE_BACKGROUND, RENDER_QUEUE_OVERLAY, RENDER_QUEUE_SKIES_EARLY` and `RENDER_QUEUE_SKIES_LATE`. If you choose to use more rendering queues (and by default, you won’t be using any more than this plus the ’standard’ queue, so ignore this if you don’t know what it means!), be aware that each one can incur a light setup cost, and you should disable shadows on the additional ones you use if you can. - -
- -# Stencil Shadows {#Stencil-Shadows} - -Stencil shadows are a method by which a ’mask’ is created for the screen using a feature called the stencil buffer. This mask can be used to exclude areas of the screen from subsequent renders, and thus it can be used to either include or exclude areas in shadow. They are enabled by calling Ogre::SceneManager::setShadowTechnique with a parameter of either `SHADOWTYPE_STENCIL_ADDITIVE` or `SHADOWTYPE_STENCIL_MODULATIVE`. Because the stencil can only mask areas to be either ’enabled’ or ’disabled’, stencil shadows have ’hard’ edges, that is to say clear dividing lines between light and shadow - it is not possible to soften these edges. - -In order to generate the stencil, ’shadow volumes’ are rendered by extruding the silhouette of the shadow caster away from the light. Where these shadow volumes intersect other objects (or the caster, since self-shadowing is supported using this technique), the stencil is updated, allowing subsequent operations to differentiate between light and shadow. How exactly this is used to render the shadows depends on whether @ref Modulative-Shadows or @ref Additive-Light-Masking is being used. Objects can both cast and receive stencil shadows, so self-shadowing is inbuilt. - -The advantage of stencil shadows is that they can do self-shadowing simply on low-end hardware, provided you keep your poly count under control. In contrast doing self-shadowing with @ref Texture_002dbased-Shadows requires a fairly modern machine. For this reason, you’re likely to pick stencil shadows if you need an accurate shadowing solution for an application aimed at older or lower-spec machines. - -The disadvantages of stencil shadows are numerous though, especially on more modern hardware. Because stencil shadows are a geometric technique, they are inherently more costly the higher the number of polygons you use, meaning you are penalized the more detailed you make your meshes. The fillrate cost, which comes from having to render shadow volumes, also escalates the same way. Since more modern applications are likely to use higher polygon counts, stencil shadows can start to become a bottleneck. In addition, the visual aspects of stencil shadows are pretty primitive - your shadows will always be hard-edged, and you have no possibility of doing clever things with shaders since the stencil is not available for manipulation there. Therefore, if your application is aimed at higher-end machines you should definitely consider switching to @ref Texture_002dbased-Shadows. - -There are a number of issues to consider which are specific to stencil shadows: - -- [CPU Overhead](#CPU-Overhead) -- [Extrusion distance](#Extrusion-distance) -- [Camera far plane positioning](#Camera-far-plane-positioning) -- [Mesh edge lists](#Mesh-edge-lists) -- [The Silhouette Edge](#The-Silhouette-Edge) -- [Be realistic](#Be-realistic) -- [Stencil Optimisations Performed By Ogre](#Stencil-Optimisations-Performed-By-Ogre) - - - -## CPU Overhead - -Calculating the shadow volume for a mesh can be expensive, and it has to be done on the CPU, it is not a hardware accelerated feature. Therefore, you can find that if you overuse this feature, you can create a CPU bottleneck for your application. Ogre quite aggressively eliminates objects which cannot be casting shadows on the frustum, but there are limits to how much it can do, and large, elongated shadows (e.g. representing a very low sun position) are very difficult to cull efficiently. Try to avoid having too many shadow casters around at once, and avoid long shadows if you can. Also, make use of the ’shadow far distance’ parameter on the SceneManager, this can eliminate distant shadow casters from the shadow volume construction and save you some time, at the expense of only having shadows for closer objects. Lastly, make use of Ogre’s Level-Of-Detail (LOD) features; you can generate automatically calculated LODs for your meshes in code (see the Mesh API docs) or when using the mesh tools such as @ref XMLConverter and @ref MeshUpgrader. Alternatively, you can assign your own manual LODs by providing alternative mesh files at lower detail levels. Both methods will cause the shadow volume complexity to decrease as the object gets further away, which saves you valuable volume calculation time. - - - -## Extrusion distance - -When vertex programs are not available, Ogre can only extrude shadow volumes a finite distance from the object. If an object gets too close to a light, any finite extrusion distance will be inadequate to guarantee all objects will be shadowed properly by this object. Therefore, you are advised not to let shadow casters pass too close to light sources if you can avoid it, unless you can guarantee that your target audience will have vertex program capable hardware (in this case, Ogre extrudes the volume to infinity using a vertex program so the problem does not occur). When infinite extrusion is not possible, Ogre uses finite extrusion, either derived from the attenuation range of a light (in the case of a point light or spotlight), or a fixed extrusion distance set in the application in the case of directional lights. To change the directional light extrusion distance, use SceneManager::setShadowDirectionalLightExtrusionDistance. - - - -## Camera far plane positioning - -Stencil shadow volumes rely very much on not being clipped by the far plane. When you enable stencil shadows, Ogre internally changes the far plane settings of your cameras such that there is no far plane - i.e. it is placed at infinity (Camera::setFarClipDistance(0)). This avoids artifacts caused by clipping the dark caps on shadow volumes, at the expense of a (very) small amount of depth precision. - - - -## Mesh edge lists - -Stencil shadows can only be calculated when an ’edge list’ has been built for all the geometry in a mesh. The official exporters and tools automatically build this for you (or have an option to do so), but if you create your own meshes, you must remember to build edge lists for them before using them with stencil shadows - you can do that by using @ref MeshUpgrader, or by calling Ogre::Mesh::buildEdgeList before you export or use the mesh. If a mesh doesn’t have edge lists, OGRE assumes that it is not supposed to cast stencil shadows. - - - -## The Silhouette Edge - -Stencil shadowing is about finding a silhouette of the mesh, and projecting it away to form a volume. What this means is that there is a definite boundary on the shadow caster between light and shadow; a set of edges where where the triangle on one side is facing toward the light, and one is facing away. This produces a sharp edge around the mesh as the transition occurs. Provided there is little or no other light in the scene, and the mesh has smooth normals to produce a gradual light change in its underlying shading, the silhouette edge can be hidden - this works better the higher the tessellation of the mesh. However, if the scene includes ambient light, then the difference is far more marked. This is especially true when using [Modulative Shadows](#Modulative-Shadows), because the light contribution of each shadowed area is not taken into account by this simplified approach, and so using 2 or more lights in a scene using modulative stencil shadows is not advisable; the silhouette edges will be very marked. Additive lights do not suffer from this as badly because each light is masked individually, meaning that it is only ambient light which can show up the silhouette edges. - - - -## Be realistic - -Don’t expect to be able to throw any scene using any hardware at the stencil shadow algorithm and expect to get perfect, optimum speed results. Shadows are a complex and expensive technique, so you should impose some reasonable limitations on your placing of lights and objects; they’re not really that restricting, but you should be aware that this is not a complete free-for-all. - -- Try to avoid letting objects pass very close (or even through) lights - it might look nice but it’s one of the cases where artifacts can occur on machines not capable of running vertex programs. -- Be aware that shadow volumes do not respect the ’solidity’ of the objects they pass through, and if those objects do not themselves cast shadows (which would hide the effect) then the result will be that you can see shadows on the other side of what should be an occluding object. -- Make use of SceneManager::setShadowFarDistance to limit the number of shadow volumes constructed -- Make use of LOD to reduce shadow volume complexity at distance -- Avoid very long (dusk and dawn) shadows - they exacerbate other issues such as volume clipping, fillrate, and cause many more objects at a greater distance to require volume construction. - - - -## Stencil optimisations performed by Ogre - -Despite all that, stencil shadows can look very nice (especially with @ref Additive-Light-Masking) and can be fast if you respect the rules above. In addition, %Ogre comes pre-packed with a lot of optimisations which help to make this as quick as possible. This section is more for developers or people interested in knowing something about the ’under the hood’ behaviour of %Ogre. - -
-
Vertex program extrusion
- -As previously mentioned, Ogre performs the extrusion of shadow volumes in hardware on vertex program-capable hardware. This has 2 major benefits; the obvious one being speed, but secondly that vertex programs can extrude points to infinity, which the fixed-function pipeline cannot, at least not without performing all calculations in software. This leads to more robust volumes, and also eliminates more than half the volume triangles on directional lights since all points are projected to a single point at infinity. - -
Scissor test optimisation
- -Ogre uses a scissor rectangle to limit the effect of point / spot lights when their range does not cover the entire viewport; that means we save fillrate when rendering stencil volumes, especially with distant lights - -
Z-Pass and Z-Fail algorithms
- -The Z-Fail algorithm, often attributed to John Carmack, is used in Ogre to make sure shadows are robust when the camera passes through the shadow volume. However, the Z-Fail algorithm is more expensive than the traditional Z-Pass; so Ogre detects when Z-Fail is required and only uses it then, Z-Pass is used at all other times. - -
2-Sided stenciling and stencil wrapping
- -Ogre supports the 2-Sided stenciling / stencil wrapping extensions, which when supported allow volumes to be rendered in a single pass instead of having to do one pass for back facing tris and another for front-facing tris. This doesn’t save fillrate, since the same number of stencil updates are done, but it does save primitive setup and the overhead incurred in the driver every time a render call is made. - -
Aggressive shadow volume culling
- -Ogre is pretty good at detecting which lights could be affecting the frustum, and from that, which objects could be casting a shadow on the frustum. This means we don’t waste time constructing shadow geometry we don’t need. Setting the shadow far distance is another important way you can reduce stencil shadow overhead since it culls far away shadow volumes even if they are visible, which is beneficial in practice since you’re most interested in shadows for close-up objects. - -
- -# Texture-based Shadows {#Texture_002dbased-Shadows} - -Texture shadows involve rendering shadow casters from the point of view of the light into a texture, which is then projected onto shadow receivers. The main advantage of texture shadows as opposed to @ref Stencil-Shadows is that the overhead of increasing the geometric detail is far lower, since there is no need to perform per-triangle calculations. Most of the work in rendering texture shadows is done by the graphics card, meaning the technique scales well when taking advantage of the latest cards, which are at present outpacing CPUs in terms of their speed of development. In addition, texture shadows are **much** more customisable - you can pull them into shaders to apply as you like (particularly with [Integrated Texture Shadows](#Integrated-Texture-Shadows), you can perform filtering to create softer shadows or perform other special effects on them. Basically, most modern engines use texture shadows as their primary shadow technique simply because they are more powerful, and the increasing speed of GPUs is rapidly amortizing the fillrate / texture access costs of using them. - -The main disadvantage to texture shadows is that, because they are simply a texture, they have a fixed resolution which means if stretched, the pixellation of the texture can become obvious. There are ways to combat this though: - -
-
Choosing a projection basis
- -The simplest projection is just to render the shadow casters from the lights perspective using a regular camera setup. This can look bad though, so there are many other projections which can help to improve the quality from the main camera’s perspective. OGRE supports pluggable projection bases via it’s ShadowCameraSetup class, and comes with several existing options -- **Uniform**, which is the simplest, -- **Uniform Focused**, which is still a normal camera projection, except that the camera is focused into the area that the main viewing camera is looking at -- **Light Space Perspective Shadow Mapping** (LiSPSM), which both focuses and distorts the shadow frustum based on the main view camera and -- **Plane Optimal**, which seeks to optimise the shadow fidelity for a single receiver plane. - -
Filtering
- -You can also sample the shadow texture multiple times rather than once to soften the shadow edges and improve the appearance. Percentage Closest Filtering (PCF) is the most popular approach, although there are multiple variants depending on the number and pattern of the samples you take. Our shadows demo includes a 5-tap PCF example combined with depth shadow mapping. - -
Using a larger texture
- -Again as GPUs get faster and gain more memory, you can scale up to take advantage of this. - -
- -If you combine all 3 of these techniques you can get a very high quality shadow solution. - -The other issue is with point lights. Because texture shadows require a render to texture in the direction of the light, omnidirectional lights (point lights) would require 6 renders to totally cover all the directions shadows might be cast. For this reason, Ogre primarily supports directional lights and spotlights for generating texture shadows; you can use point lights but they will only work if off-camera since they are essentially turned into a spotlight shining into your camera frustum for the purposes of texture shadows. - - - -## Directional Lights - -Directional lights in theory shadow the entire scene from an infinitely distant light. Now, since we only have a finite texture which will look very poor quality if stretched over the entire scene, clearly a simplification is required. Ogre places a shadow texture over the area immediately in front of the camera, and moves it as the camera moves (although it rounds this movement to multiples of texels so that the slight ’swimming shadow’ effect caused by moving the texture is minimised). The range to which this shadow extends, and the offset used to move it in front of the camera, are configurable (See @ref Configuring-Texture-Shadows). At the far edge of the shadow, Ogre fades out the shadow based on other configurable parameters so that the termination of the shadow is softened. - - - -## Spotlights - -Spotlights are much easier to represent as renderable shadow textures than directional lights, since they are naturally a frustum. Ogre represents spotlight directly by rendering the shadow from the light position, in the direction of the light cone; the field-of-view of the texture camera is adjusted based on the spotlight falloff angles. In addition, to hide the fact that the shadow texture is square and has definite edges which could show up outside the spotlight, Ogre uses a second texture unit when projecting the shadow onto the scene which fades out the shadow gradually in a projected circle around the spotlight. - - - -## Point Lights - -As mentioned above, to support point lights properly would require multiple renders (either 6 for a cubic render or perhaps 2 for a less precise parabolic mapping), so rather than do that we approximate point lights as spotlights, where the configuration is changed on the fly to make the light shine from its position over the whole of the viewing frustum. This is not an ideal setup since it means it can only really work if the point light’s position is out of view, and in addition the changing parameterisation can cause some ’swimming’ of the texture. Generally we recommend avoiding making point lights cast texture shadows. - - - -## Shadow Casters and Shadow Receivers - -To enable texture shadows, use the shadow technique SHADOWTYPE\_TEXTURE\_MODULATIVE or SHADOWTYPE\_TEXTURE\_ADDITIVE; as the name suggests this produces [Modulative Shadows](#Modulative-Shadows) or [Additive Light Masking](#Additive-Light-Masking) respectively. The cheapest and simplest texture shadow techniques do not use depth information, they merely render casters to a texture and render this onto receivers as plain colour - this means self-shadowing is not possible using these methods. This is the default behaviour if you use the automatic, fixed-function compatible (and thus usable on lower end hardware) texture shadow techniques. You can however use shaders-based techniques through custom shadow materials for casters and receivers to perform more complex shadow algorithms, such as depth shadow mapping which does allow self-shadowing. OGRE comes with an example of this in its shadows demo, although it’s only usable on Shader Model 2 cards or better. Whilst fixed-function depth shadow mapping is available in OpenGL, it was never standardised in Direct3D so using shaders in custom caster & receiver materials is the only portable way to do it. If you use this approach, call SceneManager::setShadowTextureSelfShadow with a parameter of ’true’ to allow texture shadow casters to also be receivers. If you’re not using depth shadow mapping, OGRE divides shadow casters and receivers into 2 disjoint groups. Simply by turning off shadow casting on an object, you automatically make it a shadow receiver (although this can be disabled by setting the ’receive\_shadows’ option to ’false’ in a material script. Similarly, if an object is set as a shadow caster, it cannot receive shadows. - -# Configuring Texture Shadows {#Configuring-Texture-Shadows} - -There are a number of settings which will help you configure your texture-based shadows so that they match your requirements. - -- [Maximum number of shadow textures](#Maximum-number-of-shadow-textures) -- [Shadow texture size](#Shadow-texture-size) -- [Shadow far distance](#Shadow-far-distance) -- [Shadow texture offset (Directional Lights)](#Shadow-texture-offset-Directional-Lights_0029) -- [Shadow fade settings](#Shadow-fade-settings) -- [Custom shadow camera setups](#Custom-shadow-camera-setups) -- [Shadow texture Depth Buffer sharing](#Shadow-texture-Depth-Buffer-sharing) -- [Integrated Texture Shadows](#Integrated-Texture-Shadows) - - - -## Maximum number of shadow textures - -Shadow textures take up texture memory, and to avoid stalling the rendering pipeline Ogre does not reuse the same shadow texture for multiple lights within the same frame. This means that each light which is to cast shadows must have its own shadow texture. In practice, if you have a lot of lights in your scene you would not wish to incur that sort of texture overhead. You can adjust this manually by simply turning off shadow casting for lights you do not wish to cast shadows. In addition, you can set a maximum limit on the number of shadow textures Ogre is allowed to use by calling Ogre::SceneManager::setShadowTextureCount. Each frame, Ogre determines the lights which could be affecting the frustum, and then allocates the number of shadow textures it is allowed to use to the lights on a first-come-first-served basis. Any additional lights will not cast shadows that frame. Note that you can set the number of shadow textures and their size at the same time by using the Ogre::SceneManager::setShadowTextureSettings method; this is useful because both the individual calls require the potential creation / destruction of texture resources. - - - -## Shadow texture size - -The size of the textures used for rendering the shadow casters into can be altered; clearly using larger textures will give you better quality shadows, but at the expense of greater memory usage. Changing the texture size is done by calling Ogre::SceneManager::setShadowTextureSize - textures are assumed to be square and you must specify a texture size that is a power of 2. Be aware that each modulative shadow texture will take \f$size*size*3\f$ bytes of texture memory. - -@note if you use the GL render system your shadow texture size can only be larger (in either dimension) than the size of your primary window surface if the hardware supports the Frame Buffer Object (FBO) or Pixel Buffer Object (PBO) extensions. Most modern cards support this now, but be careful of older cards - you can check the ability of the hardware to manage this through Ogre::RSC_HWRENDER_TO_TEXTURE. If this is absent, if you create a shadow texture larger in any dimension than the primary surface, the rest of the shadow texture will be blank. - - - -## Shadow far distance - -This determines the distance at which shadows are terminated; it also determines how far into the distance the texture shadows for directional lights are stretched - by reducing this value, or increasing the texture size, you can improve the quality of shadows from directional lights at the expense of closer shadow termination or increased memory usage, respectively. - - - -## Shadow texture offset (Directional Lights) - -@copydetails Ogre::SceneManager::setShadowDirLightTextureOffset - -You change this value by calling Ogre::SceneManager::setShadowDirLightTextureOffset. - - - -## Shadow fade settings - -Shadows fade out before the shadow far distance so that the termination of shadow is not abrupt. You can configure the start and end points of this fade by calling the Ogre::SceneManager::setShadowTextureFadeStart and Ogre::SceneManager::setShadowTextureFadeEnd methods, both take distances as a proportion of the shadow far distance. Because of the inaccuracies caused by using a square texture and a radial fade distance, you cannot use 1.0 as the fade end, if you do you’ll see artifacts at the extreme edges. The default values are 0.7 and 0.9, which serve most purposes but you can change them if you like. - -# Texture shadows and vertex / fragment programs {#texture_shadows_and_shaders} - -When rendering shadow casters into a modulative shadow texture, Ogre turns off all textures, and all lighting contributions except for ambient light, which it sets to the colour of the shadow ([Shadow Colour](#Shadow-Colour)). For additive shadows, it render the casters into a black & white texture instead. This is enough to render shadow casters for fixed-function material techniques, however where a vertex program is used Ogre doesn’t have so much control. If you use a vertex program in the **first pass** of your technique, then you must also tell ogre which vertex program you want it to use when rendering the shadow caster; see @ref Shadows-and-Vertex-Programs for full details. - - - -## Custom shadow camera setups - -As previously mentioned, one of the downsides of texture shadows is that the texture resolution is finite, and it’s possible to get aliasing when the size of the shadow texel is larger than a screen pixel, due to the projection of the texture. In order to address this, you can specify alternative projection bases by using or creating subclasses of the Ogre::ShadowCameraSetup class. The default version is called DefaultShadowCameraSetup and this sets up a simple regular frustum for point and spotlights, and an orthographic frustum for directional lights. There is also a Ogre::PlaneOptimalShadowCameraSetup class which specialises the projection to a plane, thus giving you much better definition provided your shadow receivers exist mostly in a single plane. Other setup classes (e.g. you might create a perspective or trapezoid shadow mapping version) can be created and plugged in at runtime, either on individual lights or on the SceneManager as a whole. - - - -## Shadow texture Depth Buffer sharing - -Shadow textures need a depth buffer like many other RTs (Render Textures). Prior to Ogre 1.8, the depth buffer behavior was left undefined leaving a very small possibility of causing inconsistencies across different window resolutions and render systems. Depending on the render window’s resolutions and/or rendersystem being used, the depth buffer might been shared with the render window or a new one could get created to suite the shadow textures. If the application was depending on the depth buffer contents from the previous scene render (that is, no clear was performed) where a shadow texture render pass was in the middle; then the depth buffer would’ve contained garbage (but not consistent on all machines) causing graphical glitches hard to spot. - -From Ogre 1.8 onwards the depth buffer usage & sharing can be flexible controlled through the use of depth pool IDs. These pool IDs are not specifically part of shadow textures, but rather anything involving RTs. All RTs with the same pool ID share the same depth buffers when possible (following RenderSystem API rules, check RenderSystemCapabilities flags to find out what the behavior will be). The default ID for shadow textures is 1; which is the same default value for render windows, and RTTs; thus maintaining the same behavior with older applications while achieving maximum memory saving and performance efficiency because the number of created depth buffers is as lowest as possible. - -However there are some reasons to put shadow textures in a separate pool. This holds specially true if the application depends on the previous contents from the depth buffer before the shadow pass, instead of doing a clear: - -- In Direct3D9, the shadow texture is more likely to share the depth buffer with the render window at high resolutions (when the window is bigger than the shadow texture resolution), but at low resolutions it won’t be shared, thus causing two different behaviors. Also probably the shadow texture will share the depth buffers with most other RTTs (i.e. compositors) -- In OpenGL 2.1, the shadow texture can’t be shared with the main render window; and most likely will **not** be shared with many other RTTs (i.e. compositors) since OGL 2.1 has a requirement that texture resolutions should exactly match, while D3D9 specifies depth buffers can be shared as long as the resolutions are equal or less. - -For example, the DeferredShading sample suffers from this problem. If this is a problem for a particular effect you’re trying to achieve, you can specify a custom pool ID so that shadow textures get their own depth buffer(s), ensuring they aren’t shared with other RTs. You can set the poolId parameter from either Ogre::SceneManager::setShadowTextureSettings or setShadowTextureConfig - -```cpp -mSceneMgr->setShadowTextureSettings( size, count, format, PoolId ); -mSceneMgr->setShadowTextureConfig( 0, 512, 512, PF_FLOAT16_R, 50 ); -``` - -Note a poolId of 0 will make the shadow textures not to use a depth buffer, which isn’t usually a desired behavior. - -## Integrated Texture Shadows {#Integrated-Texture-Shadows} - -Texture shadows have one major advantage over stencil shadows - the data used to represent them can be referenced in regular shaders. Whilst the default texture shadow modes (SHADOWTYPE\_TEXTURE\_MODULATIVE and SHADOWTYPE\_TEXTURE\_ADDITIVE) automatically render shadows for you, their disadvantage is that because they are generalised add-ons to your own materials, they tend to take more passes of the scene to use. In addition, you don’t have a lot of control over the composition of the shadows. - -Here is where ’integrated’ texture shadows step in. Both of the texture shadow types above have alternative versions called SHADOWTYPE\_TEXTURE\_MODULATIVE\_INTEGRATED and SHADOWTYPE\_TEXTURE\_ADDITIVE\_INTEGRATED, where instead of rendering the shadows for you, it just creates the texture shadow and then expects you to use that shadow texture as you see fit when rendering receiver objects in the scene. The downside is that you have to take into account shadow receipt in every one of your materials if you use this option - the upside is that you have total control over how the shadow textures are used. The big advantage here is that you can can perform more complex shading, taking into account shadowing, than is possible using the generalised bolt-on approaches, AND you can probably write them in a smaller number of passes, since you know precisely what you need and can combine passes where possible. When you use one of these shadowing approaches, the only difference between additive and modulative is the colour of the casters in the shadow texture (the shadow colour for modulative, black for additive) - the actual calculation of how the texture affects the receivers is of course up to you. No separate modulative pass will be performed, and no splitting of your materials into ambient / per-light / decal etc will occur - absolutely everything is determined by your original material (which may have modulative passes or per-light iteration if you want of course, but it’s not required). - -You reference a shadow texture in a material which implements this approach by using the `content_type shadow` directive in your @ref Texture-Units. It implicitly references a shadow texture based on the number of times you’ve used this directive in the same pass, and the light\_start option or light-based pass iteration, which might start the light index higher than 0. - -# Modulative Shadows {#Modulative-Shadows} - -Modulative shadows work by darkening an already rendered scene with a fixed colour. First, the scene is rendered normally containing all the objects which will be shadowed, then a modulative pass is done per light, which darkens areas in shadow. Finally, objects which do not receive shadows are rendered. - -There are 2 modulative shadow techniques: -1. @ref Stencil-Shadows, SHADOWTYPE\_STENCIL\_MODULATIVE and -2. @ref Texture_002dbased-Shadows, SHADOWTYPE\_TEXTURE\_MODULATIVE. - -Modulative shadows are an inaccurate lighting model, since they darken the areas of shadow uniformly, irrespective of the amount of light which would have fallen on the shadow area anyway. However, they can give fairly attractive results for a much lower overhead than more ’correct’ methods like @ref Additive-Light-Masking, and they also combine well with pre-baked static lighting (such as pre-calculated lightmaps), which additive lighting does not. The main thing to consider is that using multiple light sources can result in overly dark shadows (where shadows overlap, which intuitively looks right in fact, but it’s not physically correct) and artifacts when using stencil shadows (See [The Silhouette Edge](#The-Silhouette-Edge)). - - - -## Shadow Colour - -The colour which is used to darken the areas in shadow is set by Ogre::SceneManager::setShadowColour; it defaults to a dark grey (so that the underlying colour still shows through a bit). - -Note that if you’re using texture shadows you have the additional option of using @ref Integrated-Texture-Shadows rather than being forced to have a separate pass of the scene to render shadows. In this case the ’modulative’ aspect of the shadow technique just affects the colour of the shadow texture. - -# Additive Light Masking {#Additive-Light-Masking} - -Additive light masking is about rendering the scene many times, each time representing a single light contribution whose influence is masked out in areas of shadow. Each pass is combined with (added to) the previous one such that when all the passes are complete, all the light contribution has correctly accumulated in the scene, and each light has been prevented from affecting areas which it should not be able to because of shadow casters. This is an effective technique which results in very realistic looking lighting, but it comes at a price: more rendering passes. - -As many technical papers (and game marketing) will tell you, rendering realistic lighting like this requires multiple passes. Being a friendly sort of engine, Ogre frees you from most of the hard work though, and will let you use the exact same material definitions whether you use this lighting technique or not (for the most part, see @ref Pass-Classification-and-Vertex-Programs). In order to do this technique, Ogre automatically categorises the @ref Passes you define in your materials into 3 types: - -1. ambient Passes categorised as ’ambient’ include any base pass which is not lit by any particular light, i.e. it occurs even if there is no ambient light in the scene. The ambient pass always happens first, and sets up the initial depth value of the fragments, and the ambient colour if applicable. It also includes any emissive / self illumination contribution. Only textures which affect ambient light (e.g. ambient occlusion maps) should be rendered in this pass. -2. diffuse/specular Passes categorised as ’diffuse/specular’ (or ’per-light’) are rendered once per light, and each pass contributes the diffuse and specular colour from that single light as reflected by the diffuse / specular terms in the pass. Areas in shadow from that light are masked and are thus not updated. The resulting masked colour is added to the existing colour in the scene. Again, no textures are used in this pass (except for textures used for lighting calculations such as normal maps). -3. decal Passes categorised as ’decal’ add the final texture colour to the scene, which is modulated by the accumulated light built up from all the ambient and diffuse/specular passes. - -In practice, @ref Passes rarely fall nicely into just one of these categories. For each Technique, Ogre compiles a list of ’Illumination Passes’, which are derived from the user defined passes, but can be split, to ensure that the divisions between illumination pass categories can be maintained. For example, if we take a very simple material definition: - -```cpp -material TestIllumination -{ - technique - { - pass - { - ambient 0.5 0.2 0.2 - diffuse 1 0 0 - specular 1 0.8 0.8 15 - texture_unit - { - texture grass.png - } - } - } -} -``` - -Ogre will split this into 3 illumination passes, which will be the equivalent of this: - -```cpp -material TestIlluminationSplitIllumination -{ - technique - { - // Ambient pass - pass - { - ambient 0.5 0.2 0.2 - diffuse 0 0 0 - specular 0 0 0 - } - - // Diffuse / specular pass - pass - { - scene_blend add - iteration once_per_light - diffuse 1 0 0 - specular 1 0.8 0.8 15 - } - - // Decal pass - pass - { - scene_blend modulate - lighting off - texture_unit - { - texture grass.png - } - } - } -} -``` - -So as you can see, even a simple material requires a minimum of 3 passes when using this shadow technique, and in fact it requires (num\_lights + 2) passes in the general sense. You can use more passes in your original material and Ogre will cope with that too, but be aware that each pass may turn into multiple ones if it uses more than one type of light contribution (ambient vs diffuse/specular) and / or has texture units. The main nice thing is that you get the full multipass lighting behaviour even if you don’t define your materials in terms of it, meaning that your material definitions can remain the same no matter what lighting approach you decide to use. - -## Manually Categorising Illumination Passes {#Manually-Categorising-Illumination-Passes} - -Alternatively, if you want more direct control over the categorisation of your passes, you can use the @ref illumination_005fstage option in your pass to explicitly assign a pass unchanged to an illumination stage. This way you can make sure you know precisely how your material will be rendered under additive lighting conditions. - -## Pass Classification and Vertex Programs {#Pass-Classification-and-Vertex-Programs} - -Ogre is pretty good at classifying and splitting your passes to ensure that the multipass rendering approach required by additive lighting works correctly without you having to change your material definitions. However, there is one exception; when you use vertex programs, the normal lighting attributes ambient, diffuse, specular etc are not used, because all of that is determined by the vertex program. Ogre has no way of knowing what you’re doing inside that vertex program, so you have to tell it. - -In practice this is very easy. Even though your vertex program could be doing a lot of complex, highly customised processing, it can still be classified into one of the 3 types listed above. All you need to do to tell Ogre what you’re doing is to use the pass attributes ambient, diffuse, specular and self\_illumination, just as if you were not using a vertex program. Sure, these attributes do nothing (as far as rendering is concerned) when you’re using vertex programs, but it’s the easiest way to indicate to Ogre which light components you’re using in your vertex program. Ogre will then classify and potentially split your programmable pass based on this information - it will leave the vertex program as-is (so that any split passes will respect any vertex modification that is being done). - -Note that when classifying a diffuse/specular programmable pass, Ogre checks to see whether you have indicated the pass can be run once per light (iteration once\_per\_light). If so, the pass is left intact, including it’s vertex and fragment programs. However, if this attribute is not included in the pass, Ogre tries to split off the per-light part, and in doing so it will disable the fragment program, since in the absence of the ’iteration once\_per\_light’ attribute it can only assume that the fragment program is performing decal work and hence must not be used per light. - -So clearly, when you use additive light masking as a shadow technique, you need to make sure that programmable passes you use are properly set up so that they can be classified correctly. However, also note that the changes you have to make to ensure the classification is correct does not affect the way the material renders when you choose not to use additive lighting, so the principle that you should be able to use the same material definitions for all lighting scenarios still holds. Here is an example of a programmable material which will be classified correctly by the illumination pass classifier: - -@snippet Samples/Media/materials/scripts/Examples-Advanced.material normal_map_multipass - -Note that if you’re using texture shadows you have the additional option of using @ref Integrated-Texture-Shadows rather than being forced to use this explicit sequence - allowing you to compress the number of passes into a much smaller number at the expense of defining an upper number of shadow casting lights. In this case the ’additive’ aspect of the shadow technique just affects the colour of the shadow texture and it’s up to you to combine the shadow textures in your receivers however you like. - - - -## Static Lighting {#Static-Lighting} - -Despite their power, additive lighting techniques have an additional limitation; they do not combine well with pre-calculated static lighting in the scene. This is because they are based on the principle that shadow is an absence of light, but since static lighting in the scene already includes areas of light and shadow, additive lighting cannot remove light to create new shadows. Therefore, if you use the additive lighting technique you must either use it exclusively as your lighting solution (and you can combine it with per-pixel lighting to create a very impressive dynamic lighting solution), or you must use @ref Integrated-Texture-Shadows to combine the static lighting according to your chosen approach. - -@page Animation Animation - -OGRE supports a pretty flexible animation system that allows you to script animation for several different purposes: - -
-
@ref SceneNode-Animation
-Animating SceneNodes automatically to create effects like camera sweeps, objects following predefined paths, etc. -
-
@ref Skeletal-Animation
-Mesh animation using a skeletal structure to determine how the mesh deforms. -
@ref Vertex-Animation
-Mesh animation using snapshots of vertex data to determine how the shape of the mesh changes. -
@ref Numeric-Value-Animation
-Using OGRE’s extensible class structure to animate any value. -
- -@tableofcontents - -# Animation State {#Animation-State} - -When an entity containing animation of any type is created, it is given an ’animation state’ object per animation to allow you to specify the animation state of that single entity (you can animate multiple entities using the same animation definitions, OGRE sorts the reuse out internally). - -You can retrieve a pointer to the AnimationState object by calling Ogre::Entity::getAnimationState. You can then call methods on this returned object to update the animation, probably in the frameStarted event. Each AnimationState needs to be enabled using the setEnabled method before the animation it refers to will take effect, and you can set both the weight and the time position (where appropriate) to affect the application of the animation using correlating methods. AnimationState also has a very simple method ’addTime’ which allows you to alter the animation position incrementally, and it will automatically loop for you. addTime can take positive or negative values (so you can reverse the animation if you want). - - -# Skeletal Animation {#Skeletal-Animation} - -Skeletal animation is a process of animating a mesh by moving a set of hierarchical bones within the mesh, which in turn moves the vertices of the model according to the bone assignments stored in each vertex. An alternative term for this approach is ’skinning’. The usual way of creating these animations is with a modelling tool such as Softimage XSI, Milkshape 3D, Blender, 3D Studio or Maya among others. OGRE provides exporters to allow you to get the data out of these modellers and into the engine See [Exporters](@ref Exporters). - -There are many grades of skeletal animation, and not all engines (or modellers for that matter) support all of them. OGRE supports the following features: - -- Each mesh can be linked to a single skeleton -- Unlimited bones per skeleton -- Hierarchical forward-kinematics on bones -- Multiple named animations per skeleton (e.g. ’Walk’, ’Run’, ’Jump’, ’Shoot’ etc) -- Unlimited keyframes per animation -- Linear or spline-based interpolation between keyframes -- A vertex can be assigned to multiple bones and assigned weightings for smoother skinning -- Multiple animations can be applied to a mesh at the same time, again with a blend weighting - -Skeletons and the animations which go with them are held in .skeleton files, which are produced by the OGRE exporters. These files are loaded automatically when you create an Entity based on a Mesh which is linked to the skeleton in question. You then use @ref Animation-State to set the use of animation on the entity in question. - -Skeletal animation can be performed in software, or implemented in shaders (hardware skinning). Clearly the latter is preferable, since it takes some of the work away from the CPU and gives it to the graphics card, and also means that the vertex data does not need to be re-uploaded every frame. This is especially important for large, detailed models. You should try to use hardware skinning wherever possible; this basically means assigning a material which has a vertex program powered technique. See @ref Skeletal-Animation-in-Vertex-Programs for more details. Skeletal animation can be combined with vertex animation, See @ref Combining-Skeletal-and-Vertex-Animation. - -# SceneNode Animation {#SceneNode-Animation} - -SceneNode animation is created from the SceneManager in order to animate the movement of SceneNodes, to make any attached objects move around automatically. You can see this performing a camera swoop in the CameraTrack Sample, or controlling how the fish move around in the pond in the Fresnel Sample. - -At it’s heart, scene node animation is mostly the same code which animates the underlying skeleton in skeletal animation. After creating the main Animation using Ogre::SceneManager::createAnimation you can create a NodeAnimationTrack per SceneNode that you want to animate, and create keyframes which control its position, orientation and scale which can be interpolated linearly or via splines. You use @ref Animation-State in the same way as you do for skeletal/vertex animation, except you obtain the state from SceneManager instead of from an individual Entity. Animations are applied automatically every frame, or the state can be applied manually in advance using the \_applySceneAnimations() method on SceneManager. See the API reference for full details of the interface for configuring scene animations. - -# Vertex Animation {#Vertex-Animation} - -Vertex animation is about using information about the movement of vertices directly to animate the mesh. Each track in a vertex animation targets a single VertexData instance. Vertex animation is stored inside the .mesh file since it is tightly linked to the vertex structure of the mesh. - -There are actually two subtypes of vertex animation, for reasons which will be discussed in a moment. - -
-
@ref Morph-Animation
- -Morph animation is a very simple technique which interpolates mesh snapshots along a keyframe timeline. Morph animation has a direct correlation to old-school character animation techniques used before skeletal animation was widely used.
- -
@ref Pose-Animation
- -Pose animation is about blending multiple discrete poses, expressed as offsets to the base vertex data, with different weights to provide a final result. Pose animation’s most obvious use is facial animation. - -
- -## Why two subtypes? - -So, why two subtypes of vertex animation? Couldn’t both be implemented using the same system? The short answer is yes; in fact you can implement both types using pose animation. But for very good reasons we decided to allow morph animation to be specified separately since the subset of features that it uses is both easier to define and has lower requirements on hardware shaders, if animation is implemented through them. If you don’t care about the reasons why these are implemented differently, you can skip to the next part. - -Morph animation is a simple approach where we have a whole series of snapshots of vertex data which must be interpolated, e.g. a running animation implemented as morph targets. Because this is based on simple snapshots, it’s quite fast to use when animating an entire mesh because it’s a simple linear change between keyframes. However, this simplistic approach does not support blending between multiple morph animations. If you need animation blending, you are advised to use skeletal animation for full-mesh animation, and pose animation for animation of subsets of meshes or where skeletal animation doesn’t fit - for example facial animation. For animating in a vertex shader, morph animation is quite simple and just requires the 2 vertex buffers (one the original position buffer) of absolute position data, and an interpolation factor. Each track in a morph animation references a unique set of vertex data. - -Pose animation is more complex. Like morph animation each track references a single unique set of vertex data, but unlike morph animation, each keyframe references 1 or more ’poses’, each with an influence level. A pose is a series of offsets to the base vertex data, and may be sparse - i.e. it may not reference every vertex. Because they’re offsets, they can be blended - both within a track and between animations. This set of features is very well suited to facial animation. - -For example, let’s say you modelled a face (one set of vertex data), and defined a set of poses which represented the various phonetic positions of the face. You could then define an animation called ’SayHello’, containing a single track which referenced the face vertex data, and which included a series of keyframes, each of which referenced one or more of the facial positions at different influence levels - the combination of which over time made the face form the shapes required to say the word ’hello’. Since the poses are only stored once, but can be referenced may times in many animations, this is a very powerful way to build up a speech system. - -The downside of pose animation is that it can be more difficult to set up, requiring poses to be separately defined and then referenced in the keyframes. Also, since it uses more buffers (one for the base data, and one for each active pose), if you’re animating in hardware using vertex shaders you need to keep an eye on how many poses you’re blending at once. You define a maximum supported number in your vertex program definition, via the includes\_pose\_animation material script entry, See [Pose Animation in Vertex Programs](@ref Pose-Animation-in-Vertex-Programs). - -So, by partitioning the vertex animation approaches into 2, we keep the simple morph technique easy to use, whilst still allowing all the powerful techniques to be used. Note that morph animation cannot be blended with other types of vertex animation on the same vertex data (pose animation or other morph animation); pose animation can be blended with other pose animation though, and both types can be combined with skeletal animation. This combination limitation applies per set of vertex data though, not globally across the mesh (see below). Also note that all morph animation can be expressed (in a more complex fashion) as pose animation, but not vice versa. - - - -## Subtype applies per track - -It’s important to note that the subtype in question is held at a track level, not at the animation or mesh level. Since tracks map onto VertexData instances, this means that if your mesh is split into SubMeshes, each with their own dedicated geometry, you can have one SubMesh animated using pose animation, and others animated with morph animation (or not vertex animated at all). - -For example, a common set-up for a complex character which needs both skeletal and facial animation might be to split the head into a separate SubMesh with its own geometry, then apply skeletal animation to both submeshes, and pose animation to just the head. - -To see how to apply vertex animation, See @ref Animation-State. - - - -## Vertex buffer arrangements - -When using vertex animation in software, vertex buffers need to be arranged such that vertex positions reside in their own hardware buffer. This is to avoid having to upload all the other vertex data when updating, which would quickly saturate the GPU bus. When using the OGRE .mesh format and the tools / exporters that go with it, OGRE organises this for you automatically. But if you create buffers yourself, you need to be aware of the layout arrangements. - -To do this, you have a set of helper functions in Ogre::Mesh. See API Reference entries for Ogre::VertexData::reorganiseBuffers() and Ogre::VertexDeclaration::getAutoOrganisedDeclaration(). The latter will turn a vertex declaration into one which is recommended for the usage you’ve indicated, and the former will reorganise the contents of a set of buffers to conform to that layout. - - -## Morph Animation {#Morph-Animation} - -Morph animation works by storing snapshots of the absolute vertex positions in each keyframe, and interpolating between them. Morph animation is mainly useful for animating objects which could not be adequately handled using skeletal animation; this is mostly objects that have to radically change structure and shape as part of the animation such that a skeletal structure isn’t appropriate. - -Because absolute positions are used, it is not possible to blend more than one morph animation on the same vertex data; you should use skeletal animation if you want to include animation blending since it is much more efficient. If you activate more than one animation which includes morph tracks for the same vertex data, only the last one will actually take effect. This also means that the ’weight’ option on the animation state is not used for morph animation. - -Morph animation can be combined with skeletal animation if required See @ref Combining-Skeletal-and-Vertex-Animation. Morph animation can also be implemented in hardware using vertex shaders, See @ref Morph-Animation-in-Vertex-Programs. - -## Pose Animation {#Pose-Animation} - -Pose animation allows you to blend together potentially multiple vertex poses at different influence levels into final vertex state. A common use for this is facial animation, where each facial expression is placed in a separate animation, and influences used to either blend from one expression to another, or to combine full expressions if each pose only affects part of the face. - -In order to do this, pose animation uses a set of reference poses defined in the mesh, expressed as offsets to the original vertex data. It does not require that every vertex has an offset - those that don’t are left alone. When blending in software these vertices are completely skipped - when blending in hardware (which requires a vertex entry for every vertex), zero offsets for vertices which are not mentioned are automatically created for you. - -Once you’ve defined the poses, you can refer to them in animations. Each pose animation track refers to a single set of geometry (either the shared geometry of the mesh, or dedicated geometry on a submesh), and each keyframe in the track can refer to one or more poses, each with its own influence level. The weight applied to the entire animation scales these influence levels too. You can define many keyframes which cause the blend of poses to change over time. The absence of a pose reference in a keyframe when it is present in a neighbouring one causes it to be treated as an influence of 0 for interpolation. - -You should be careful how many poses you apply at once. When performing pose animation in hardware (See @ref Pose-Animation-in-Vertex-Programs), every active pose requires another vertex buffer to be added to the shader, and in when animating in software it will also take longer the more active poses you have. Bear in mind that if you have 2 poses in one keyframe, and a different 2 in the next, that actually means there are 4 active keyframes when interpolating between them. - -You can combine pose animation with skeletal animation, See @ref Combining-Skeletal-and-Vertex-Animation, and you can also hardware accelerate the application of the blend with a vertex shader, See @ref Pose-Animation-in-Vertex-Programs. - -## Combining Skeletal and Vertex Animation {#Combining-Skeletal-and-Vertex-Animation} - -Skeletal animation and vertex animation (of either subtype) can both be enabled on the same entity at the same time (See @ref Animation-State). The effect of this is that vertex animation is applied first to the base mesh, then skeletal animation is applied to the result. This allows you, for example, to facially animate a character using pose vertex animation, whilst performing the main movement animation using skeletal animation. - -Combining the two is, from a user perspective, as simple as just enabling both animations at the same time. When it comes to using this feature efficiently though, there are a few points to bear in mind: - -- [Combined Hardware Skinning](#Combined-Hardware-Skinning) -- [Submesh Splits](#Submesh-Splits) - - - -## Combined Hardware Skinning - -For complex characters it is a very good idea to implement hardware skinning by including a technique in your materials which has a vertex program which can perform the kinds of animation you are using in hardware. See [Skeletal Animation in Vertex Programs](@ref Skeletal-Animation-in-Vertex-Programs), [Morph Animation in Vertex Programs](@ref Morph-Animation-in-Vertex-Programs), [Pose Animation in Vertex Programs](@ref Pose-Animation-in-Vertex-Programs). - -When combining animation types, your vertex programs must support both types of animation that the combined mesh needs, otherwise hardware skinning will be disabled. You should implement the animation in the same way that OGRE does, i.e. perform vertex animation first, then apply skeletal animation to the result of that. Remember that the implementation of morph animation passes 2 absolute snapshot buffers of the from & to keyframes, along with a single parametric, which you have to linearly interpolate, whilst pose animation passes the base vertex data plus ’n’ pose offset buffers, and ’n’ parametric weight values. - - - -## Submesh Splits - -If you only need to combine vertex and skeletal animation for a small part of your mesh, e.g. the face, you could split your mesh into 2 parts, one which needs the combination and one which does not, to reduce the calculation overhead. Note that it will also reduce vertex buffer usage since vertex keyframe / pose buffers will also be smaller. Note that if you use hardware skinning you should then implement 2 separate vertex programs, one which does only skeletal animation, and the other which does skeletal and vertex animation. - -# Numeric Value Animation {#Numeric-Value-Animation} - -Apart from the specific animation types which may well comprise the most common uses of the animation framework, you can also use animations to alter any value which is exposed via the [AnimableObject](#AnimableObject) interface. - - - -## AnimableObject - -Ogre::AnimableObject is an abstract interface that any class can extend in order to provide access to a number of [AnimableValue](#AnimableValue)s. It holds a ’dictionary’ of the available animable properties which can be enumerated via the getAnimableValueNames method, and when its createAnimableValue method is called, it returns a reference to a value object which forms a bridge between the generic animation interfaces, and the underlying specific object property. - -One example of this is the Ogre::Light class. It extends AnimableObject and provides AnimableValues for properties such as "diffuseColour" and "attenuation". Animation tracks can be created for these values and thus properties of the light can be scripted to change. Other objects, including your custom objects, can extend this interface in the same way to provide animation support to their properties. - - - -## AnimableValue - -When implementing custom animable properties, you have to also implement a number of methods on the AnimableValue interface - basically anything which has been marked as unimplemented. These are not pure virtual methods simply because you only have to implement the methods required for the type of value you’re animating. Again, see the examples in Light to see how this is done. - - -@page Instancing Instancing - -Instancing significantly reduces the CPU overhead of submitting many separate draw calls and is a great technique for rendering trees, rocks, grass, RTS units and other groups of similar (but necessarily identical) objects. - -OGRE supports a variety of techniques to speed up the rendering of many objects in the Scene. - -
-
@ref Static-Geometry
-
Pre-transforms and batches up meshes for efficient use as static geometry in a scene.
-
@ref Instance-Manager
-
Instancing is a way of batching up geometry into a much more efficient form, but with some limitations, and still be able to move & animate it.
-
- -@tableofcontents - -# Static Geometry {#Static-Geometry} -Modern graphics cards (GPUs) prefer to receive geometry in large batches. -It is orders of magnitude faster to render 10 batches of 10,000 triangles than it is to render 10,000 batches of 10 triangles, even though both result in the same number of on-screen triangles. - -Therefore it is important when you are rendering a lot of geometry to batch things up into as few rendering calls as possible. -This class allows you to build a batched object from a series of entities in order to benefit from this behaviour. Batching has implications of it's own though: - - A geometry region cannot be subdivided; that means that the whole group will be displayed, or none of it will. This obivously has culling issues. - - A single world transform must apply to the entire batch. Therefore once you have batched things, you can't move them around relative to each other. - That's why this class is most useful when dealing with static geometry (hence the name). - In addition, geometry is effectively duplicated, so if you add 3 entities based on the same mesh in different positions, they will use 3 times the geometry space than the movable version (which re-uses the same geometry). - So you trade memory and flexibility of movement for pure speed when using this class. - - A single material must apply for each batch. In fact this class allows you to use multiple materials, but you should be aware that internally this means that there is one batch per material. - Therefore you won't gain as much benefit from the batching if you use many different materials; try to keep the number down. - -@see Ogre::StaticGeometry -@see [Tutorial - Static Geometry](@ref tut_StaticGeom) - -# Instance Manager {#Instance-Manager} -Instancing is a rendering technique to draw multiple instances of the same mesh using just one render call. There are two kinds of instancing: - -@par Software -Two larges vertex & index buffers are created and the mesh vertices/indices are duplicated N number of times. When rendering, invisible instances receive a transform matrix filled with 0s. This technique can take a lot of VRAM and has limited culling capabilities. -@par Hardware -The hardware supports an extra param which allows Ogre to tell the GPU to repeat the drawing of vertices N number of times; thus taking considerably less VRAM. Because N can be controlled at runtime, individual instances can be culled before sending the data to the GPU. -Hardware techniques are almost always superior to Software techniques, but Software are more compatible, where as Hardware techniques require D3D9 or GL3, and is not supported in GLES2 - -All instancing techniques require shaders. It is possible to have the [RTSS (Realtime Shader System)](@ref rtss) generate the shaders for you. - -@see Ogre::InstanceManager -@see @subpage WhatIsInstancing - -# Static Geometry vs Instancing {#Static-Geometry-vs-Instancing} - -| Static Geometry | Instancing | -| ----------------|------------| -| Any sort of mesh is grouped in a minimal number of meshes, and cannot be updated (each mesh cannot move independently, only all the static geometry would be able to do so.) | The same mesh used many times, so Instanced geometry can be updated (each mesh can move independently) | -| You have a scene with many unique meshes| Reuse the same mesh many times without the draw call cost. | -| Batches up small static detail fragments like grass without shaders. | One mesh is repeated many times without the performance hit of having them as individual meshes. | -| Geometry that doesn't move and has low in GPU requirements | Dynamic geometry (animated or moving) and better GPU (sm2.0+) | -| Batches separate sets of polygons together, as long as they have the same properties such as material. These batches are then automatically split into regions for better culling. You can control the region size. This is a good way to reduce batches for static elements. | Good for large numbers of the same exact object. You can have multiple instances of one object that can dynamically move but that are drawn in one draw call. | diff --git a/Docs/src/material-scripts.md b/Docs/src/material-scripts.md deleted file mode 100644 index f2ee6795521..00000000000 --- a/Docs/src/material-scripts.md +++ /dev/null @@ -1,1549 +0,0 @@ -# Material Scripts {#Material-Scripts} - -Material scripts offer you the ability to define complex materials in a script which can be reused easily. Whilst you could set up all materials for a scene in code using the methods of the Material and TextureLayer classes, in practice it's a bit unwieldy. Instead you can store material definitions in text files which can then be loaded whenever required. - -@tableofcontents - -It’s important to realise that materials are not loaded completely by the parsing process: only the definition is loaded, no textures or other resources are loaded. This is because it is common to have a large library of materials, but only use a relatively small subset of them in any one scene. To load every material completely in every script would therefore cause unnecessary memory overhead. You can access a ’deferred load’ Material in the normal way (Ogre::MaterialManager::getSingleton().getByName()), but you must call the ’load’ method before trying to use it. Ogre does this for you when using the normal material assignment methods of entities etc. - -To start with, we only consider fixed-function materials which don’t use vertex, geometry or fragment programs, these are covered later: - -```cpp -// This is a comment -material walls/funkywall1 -{ - // first, preferred technique - technique - { - // first pass - pass - { - ambient 0.5 0.5 0.5 - diffuse 1.0 1.0 1.0 - - // Texture unit 0 - texture_unit - { - texture wibbly.jpg - scroll_anim 0.1 0.0 - wave_xform scale sine 0.0 0.7 0.0 1.0 - } - // Texture unit 1 (this is a multitexture pass) - texture_unit - { - texture wobbly.png - rotate_anim 0.25 - colour_op add - } - - // Additional RT Shader system options - rtshader_system - { - // Do lighting calculations per-pixel - lighting_stage per_pixel - } - } - } - - // Second technique, can be used as a fallback or LOD level - technique - { - // .. and so on - } -} -``` - -A material can be made up of many @ref Techniques - a technique is one way of achieving the effect you are looking for. You can supply more than one technique in order to provide fallback approaches where a card does not have the ability to render the preferred technique, or where you wish to define lower level of detail versions of the material in order to conserve rendering power when objects are more distant. - -Each technique can be made up of many @ref Passes, that is a complete render of the object can be performed multiple times with different settings in order to produce composite effects. Ogre may also split the passes you have defined into many passes at runtime, if you define a pass which uses too many texture units for the card you are currently running on (note that it can only do this if you are not using a fragment program). Each pass has a number of top-level attributes such as ’ambient’ to set the amount & colour of the ambient light reflected by the material. Some of these options do not apply if you are using vertex programs, See @ref Passes for more details. - -Within each pass, there can be zero or many @ref Texture-Units in use. These define the texture to be used, and optionally some blending operations (which use multitexturing) and texture effects. - -You can also reference vertex and fragment programs (or vertex and pixel shaders, if you want to use that terminology) in a pass with a given set of parameters. Programs themselves are declared in separate .program scripts (See [GPU Program Scripts](@ref Declaring-Vertex_002fGeometry_002fFragment-Programs)) and are used as described in @ref Using-Vertex_002fGeometry_002fFragment-Programs-in-a-Pass. - - - -# Material {#Material} - -The outermost section of a material definition does not have a lot of attributes of its own (most of the configurable parameters are within the child sections. However, it does have some, and here they are: - - - - -## lod\_strategy - -Sets the name of the LOD strategy to be used. - -@par -Format: lod\_strategy <name> -@par -Default: lod\_strategy distance_sphere - -@par Valid values are: -- @c distance_sphere which means LOD changes based on distance from the camera (calculated via the bounding sphere radius). -- @c distance_box behaves the same as 'distance_sphere' except that it uses the object’s bounding box to approximate the distance. -- @c pixel_count changes LOD levels based on an absolute estimate of the screen-space pixels occupied (internally approximated via the bounding radius). -- @c screen_ratio_pixel_count sets that absolute screen space value in relation to the screen size (1.0 = object covering complete screen, 0.5 = half screen covered by object, etc.). - - - - -## lod\_values - -This attribute defines the values used to control the LOD transition for this material. By setting this attribute, you indicate that you want this material to alter the Technique that it uses based on some metric, such as the distance from the camera, or the approximate screen space coverage. The exact meaning of these values is determined by the option you select for [lod\_strategy](#lod_005fstrategy) - it is a list of distances for the @c distance_sphere strategy, and a list of pixel counts for the @c pixel_count strategy, for example. You must give it a list of values, in order from highest LOD value to lowest LOD value, each one indicating the point at which the material will switch to the next LOD. All materials automatically activate LOD index 0 for values less than the first entry, so you don't have to explicitly specify this. Additionally, if there is no technique that matches the active LOD index, a technique with a lower LOD index will be used instead. Therefore, it is important to always have at least one technique with LOD index 0. - -@par -Format: lod\_values <value0> <value1> <value2> ... -@par -Default: none -@par Example: -lod\_strategy distance_sphere -@par -lod\_values 300.0 600.5 1200 - -The above example would cause the material to use the best Technique at lod\_index 0 up to a distance of 300 world units, the best from lod\_index 1 from 300 up to 600, lod\_index 2 from 600 to 1200, and lod\_index 3 from 1200 upwards. - - -## lod\_distances - -@deprecated This option is deprecated in favour of [lod\_values](#lod_005fvalues) now. - - - -## receive\_shadows - -This attribute controls whether objects using this material can have shadows cast upon them. - -@par -Format: receive\_shadows <on|off>
Default: on - -Whether or not an object receives a shadow is the combination of a number of factors, See @ref Shadows for full details; however this allows you to make a material opt-out of receiving shadows if required. Note that transparent materials never receive shadows so this option only has an effect on solid materials. - - - -## transparency\_casts\_shadows - -This attribute controls whether transparent materials can cast certain kinds of shadow. - -@par -Format: transparency\_casts\_shadows <on|off>
-Default: off - -Whether or not an object casts a shadow is the combination of a number of factors, See @ref Shadows for full details; however this allows you to make a transparent material cast shadows, when it would otherwise not. For example, when using texture shadows, transparent materials are normally not rendered into the shadow texture because they should not block light. This flag overrides that. - - - -## set\_texture\_alias - -This attribute associates a texture alias with a texture name. - -@par -Format: set\_texture\_alias <alias name> <texture name> - -@deprecated texture aliases are a restricted version of @ref Script-Variables, which you should instead. - -# Techniques {#Techniques} - -A "technique" section in your material script encapsulates a single method of rendering an object. The simplest of material definitions only contains a single technique, however since PC hardware varies quite greatly in it’s capabilities, you can only do this if you are sure that every card for which you intend to target your application will support the capabilities which your technique requires. In addition, it can be useful to define simpler ways to render a material if you wish to use material LOD, such that more distant objects use a simpler, less performance-hungry technique. - -When a material is used for the first time, it is ’compiled’. That involves scanning the techniques which have been defined, and marking which of them are supportable using the current rendering API and graphics card. If no techniques are supportable, your material will render as blank white. The compilation examines a number of things, such as: - -- The number of texture\_unit entries in each pass
Note that if the number of texture\_unit entries exceeds the number of texture units in the current graphics card, the technique may still be supportable so long as a fragment program is not being used. In this case, Ogre will split the pass which has too many entries into multiple passes for the less capable card, and the multitexture blend will be turned into a multipass blend (See [colour\_op\_multipass\_fallback](#colour_005fop_005fmultipass_005ffallback)). -- Whether vertex, geometry or fragment programs are used, and if so which syntax they use (e.g. vs\_1\_1, ps\_2\_x, arbfp1 etc.) -- Other effects like cube mapping and dot3 blending -- Whether the vendor or device name of the current graphics card matches some user-specified rules - -
- -In a material script, techniques must be listed in order of preference, i.e. the earlier techniques are preferred over the later techniques. This normally means you will list your most advanced, most demanding techniques first in the script, and list fallbacks afterwards. - -To help clearly identify what each technique is used for, the technique can be named but its optional. Techniques not named within the script will take on a name that is the technique index number. For example: the first technique in a material is index 0, its name would be "0" if it was not given a name in the script. The technique name must be unique within the material or else the final technique is the resulting merge of all techniques with the same name in the material. A warning message is posted in the Ogre.log if this occurs. Named techniques can help when inheriting a material and modifying an existing technique: (See @ref Script-Inheritance) - -@par -Format: technique name - -Techniques have only a small number of attributes of their own: - -- [scheme](#scheme) -- [lod\_index](#lod_005findex) (and also see [lod\_distances](#lod_005fdistances) in the parent material) -- [shadow\_caster\_material](#shadow_005fcaster_005fmaterial) -- [shadow\_receiver\_material](#shadow_005freceiver_005fmaterial) -- [gpu\_vendor\_rule](#gpu_005fvendor_005frule) -- [gpu\_device\_rule](#gpu_005fdevice_005frule) - - - -## scheme - -Sets the ’scheme’ this Technique belongs to. Material schemes are used to control top-level switching from one set of techniques to another. For example, you might use this to define ’high’, ’medium’ and ’low’ complexity levels on materials to allow a user to pick a performance / quality ratio. Another possibility is that you have a fully HDR-enabled pipeline for top machines, rendering all objects using unclamped shaders, and a simpler pipeline for others; this can be implemented using schemes. The active scheme is typically controlled at a viewport level, and the active one defaults to ’Default’. - -@par -Format: scheme <name>
Example: scheme hdr
Default: scheme Default - - - -## lod\_index - -Sets the level-of-detail (LOD) index this Technique belongs to. - -@par -Format: lod\_index <number>
NB Valid values are 0 (highest level of detail) to 65535, although this is unlikely. You should not leave gaps in the LOD indexes between Techniques. - -@par -Example: lod\_index 1 - -All techniques are automatically assigned to a LOD index, with the default being index 0, which corresponds to the highest LOD. Increasing indexes denote lower levels of detail. You can (and often will) assign more than one technique to the same LOD index, what this means is that OGRE will pick the best technique of the ones listed at the same LOD index. For readability, it is advised that you list your techniques in order of LOD, then in order of preference, although the latter is the only prerequisite (OGRE determines which one is ’best’ by which one is listed first). You must always have at least one Technique at lod\_index 0. The distance at which a LOD level is applied is determined by the [lod_values](#lod_005fvalues) attribute of the containing material. - -@par -Default: lod\_index 0 - -Techniques also contain one or more @ref Passes (and there must be at least one). - - - -## shadow\_caster\_material - -When using @ref Texture_002dbased-Shadows you can specify an alternate material to use when rendering the object using this material into the shadow texture. This is like a more advanced version of using @c shadow_caster_vertex_program, however note that for the moment you are expected to render the shadow in one pass, i.e. only the first pass is respected. - - - -## shadow\_receiver\_material - -When using @ref Texture_002dbased-Shadows you can specify an alternate material to use when performing the receiver shadow pass. This is like a more advanced version of using @c shadow_receiver_vertex_program and @c shadow_receiver_fragment_program, however note that for the moment you are expected to render the shadow in one pass, i.e. only the first pass is respected. - -@note This explicit ’receiver’ pass is only done when you’re **not** using @ref Integrated-Texture-Shadows - i.e. the shadow rendering is done separately (either as a modulative pass, or a masked light pass). - - - -## gpu\_vendor\_rule and gpu\_device\_rule - -Although Ogre does a good job of detecting the capabilities of graphics cards and setting the supportability of techniques from that, occasionally card-specific behaviour exists which is not necessarily detectable and you may want to ensure that your materials go down a particular path to either use or avoid that behaviour. This is what these rules are for - you can specify matching rules so that a technique will be considered supportable only on cards from a particular vendor, or which match a device name pattern, or will be considered supported only if they **don’t** fulfil such matches. The format of the rules are as follows: - -@par -gpu\_vendor\_rule <include|exclude> <vendor\_name>
gpu\_device\_rule <include|exclude> <device\_pattern> \[case\_sensitive\] - -An ’include’ rule means that the technique will only be supported if one of the include rules is matched (if no include rules are provided, anything will pass). An ’exclude’ rules means that the technique is considered unsupported if any of the exclude rules are matched. You can provide as many rules as you like, although <vendor\_name> and <device\_pattern> must obviously be unique. The valid list of <vendor\_name> values is currently ’nvidia’, ’ati’, ’intel’, ’s3’, ’matrox’ and ’3dlabs’. <device\_pattern> can be any string, and you can use wildcards (’\*’) if you need to match variants. Here’s an example: - -@par -gpu\_vendor\_rule include nvidia
gpu\_vendor\_rule include intel
gpu\_device\_rule exclude \*950\* - -These rules, if all included in one technique, will mean that the technique will only be considered supported on graphics cards made by NVIDIA and Intel, and so long as the device name doesn’t have ’950’ in it. - -Note that these rules can only mark a technique ’unsupported’ when it would otherwise be considered ’supported’ judging by the hardware capabilities. Even if a technique passes these rules, it is still subject to the usual hardware support tests. - -# Passes {#Passes} - -A pass is a single render of the geometry in question; a single call to the rendering API with a certain set of rendering properties. A technique can have between one and 16 passes, although clearly the more passes you use, the more expensive the technique will be to render. - -To help clearly identify what each pass is used for, the pass can be named but its optional. Passes not named within the script will take on a name that is the pass index number. For example: the first pass in a technique is index 0 so its name would be "0" if it was not given a name in the script. The pass name must be unique within the technique or else the final pass is the resulting merge of all passes with the same name in the technique. A warning message is posted in the Ogre.log if this occurs. Named passes can help when inheriting a material and modifying an existing pass: (See @ref Script-Inheritance) - -Passes have a set of global attributes (described below) and optionally -- zero or more nested texture\_unit entries (See @ref Texture-Units) -- references to shader programs (See @ref Using-Vertex_002fGeometry_002fFragment-Programs-in-a-Pass) -- additional instructions for the RTSS (See @ref rtss_custom_mat) - - - -Here are the attributes you can use in a ’pass’ section of a .material script: - -- [ambient](#ambient) -- [diffuse](#diffuse) -- [specular](#specular) -- [emissive](#emissive) -- [scene\_blend](#scene_005fblend) -- [separate\_scene\_blend](#separate_005fscene_005fblend) -- [scene\_blend\_op](#scene_005fblend_005fop) -- [separate\_scene\_blend\_op](#separate_005fscene_005fblend_005fop) -- [depth\_check](#depth_005fcheck) -- [depth\_write](#depth_005fwrite) -- [depth\_func](#depth_005ffunc) -- [depth\_bias](#depth_005fbias) -- [iteration\_depth\_bias](#iteration_005fdepth_005fbias) -- [alpha\_rejection](#alpha_005frejection) -- [alpha\_to\_coverage](#alpha_005fto_005fcoverage) -- [light\_scissor](#light_005fscissor) -- [light\_clip\_planes](#light_005fclip_005fplanes) -- [illumination\_stage](#illumination_005fstage) -- [transparent\_sorting](#transparent_005fsorting) -- [cull\_hardware](#cull_005fhardware) -- [cull\_software](#cull_005fsoftware) -- [lighting](#lighting) -- [shading](#shading) -- [polygon\_mode](#polygon_005fmode) -- [polygon\_mode\_overrideable](#polygon_005fmode_005foverrideable) -- [fog\_override](#fog_005foverride) -- [colour\_write](#colour_005fwrite) -- [max\_lights](#max_005flights) -- [start\_light](#start_005flight) -- [iteration](#iteration) -- [point\_size](#point_005fsize) -- [point\_sprites](#point_005fsprites) -- [point\_size\_attenuation](#point_005fsize_005fattenuation) -- [point\_size\_min](#point_005fsize_005fmin) -- [point\_size\_max](#point_005fsize_005fmax) -- [line_width](#line_width) - - - -# Attribute Descriptions - - - -## ambient - -Sets the ambient colour reflectance properties of this pass. - -@par -Format: ambient (<red> <green> <blue> \[<alpha>\]| vertexcolour)
NB valid colour values are between 0.0 and 1.0. - -@copydetails Ogre::Pass::setAmbient -@shaderparam - -@par -Example: ambient 0.0 0.8 0.0 -@par -Default: ambient 1.0 1.0 1.0 1.0 - - - -## diffuse - -Sets the diffuse colour reflectance properties of this pass. -@par -Format: diffuse (<red> <green> <blue> \[<alpha>\]| vertexcolour)
NB valid colour values are between 0.0 and 1.0. - -@copydetails Ogre::Pass::setDiffuse -@shaderparam - -@par -Example: diffuse 1.0 0.5 0.5 -@par -Default: diffuse 1.0 1.0 1.0 1.0 - - - -## specular - -Sets the specular colour reflectance properties of this pass. -@par -Format: specular (<red> <green> <blue> \[<alpha>\]| vertexcolour) <shininess>
NB valid colour values are between 0.0 and 1.0. Shininess can be any value greater than 0. - - -This property determines how much specular light (highlights from instances of the Light class in the scene) is reflected. The default is to reflect no specular light. The colour of the specular highlights is determined by the colour parameters, and the size of the highlights by the separate shininess parameter. -It is also possible to make the specular reflectance track the vertex colour as defined in -the mesh instead of the colour values. - -@copydetails Ogre::Pass::setShininess -@shaderparam - -@par -Example: specular 1.0 1.0 1.0 12.5 - -@par -Default: specular 0.0 0.0 0.0 0.0 0.0 - - - -## emissive - -Sets the amount of self-illumination an object has. - -@par -Format: emissive (<red> <green> <blue> \[<alpha>\]| vertexcolour)
NB valid colour values are between 0.0 and 1.0. - -Unlike the name suggests, this object doesn’t act as a light source for other objects in the scene (if you want it to, you have to create a light which is centered on the object). -@copydetails Ogre::Pass::setSelfIllumination -@shaderparam - -@par -Example: emissive 1.0 0.0 0.0 -@par -Default: emissive 0.0 0.0 0.0 0.0 - - - -## scene\_blend - -Sets the kind of blending this pass has with the existing contents of the scene. - -Whereas the texture blending operations seen in the texture\_unit entries are concerned with blending between texture layers, this blending is about combining the output of this pass as a whole with the existing contents of the rendering target. This blending therefore allows object transparency and other special effects. - -There are 2 formats, one using predefined blend types, the other allowing a roll-your-own approach using source and destination factors. -@par -Format1: scene\_blend <blend\_type> -@par -Example: scene\_blend add - -This is the simpler form, where the most commonly used blending modes are enumerated using a single parameter. - -@param blend_type -
-
add
-
@copybrief Ogre::SBT_ADD - -Equivalent to ’scene_blend one one’.
-
modulate
-
@copybrief Ogre::SBT_MODULATE - -Equivalent to ’scene_blend dest_colour zero’.
-
colour_blend
-
@copybrief Ogre::SBT_TRANSPARENT_COLOUR - -Equivalent to ’scene_blend src_colour one_minus_src_colour’
-
alpha_blend
-
@copybrief Ogre::SBT_TRANSPARENT_ALPHA - -Equivalent to ’scene_blend src_alpha one_minus_src_alpha’
-
- -@par -Format2: scene\_blend <sourceFactor> <destFactor> - -@copydetails Ogre::Pass::setSceneBlending(const SceneBlendFactor, const SceneBlendFactor) - -Valid values for both parameters are one of Ogre::SceneBlendFactor without the `SBF_` prefix. E.g. `SBF_DEST_COLOUR` becomes `dest_colour`. - -@par -Example: scene\_blend one one\_minus\_dest\_alpha - -@par -Default: scene\_blend one zero (opaque) - -Also see [separate\_scene\_blend](#separate_005fscene_005fblend). - - - -## separate\_scene\_blend - -This option operates in exactly the same way as [scene\_blend](#scene_005fblend), except that it allows you to specify the operations to perform between the rendered pixel and the frame buffer separately for colour and alpha components. By nature this option is only useful when rendering to targets which have an alpha channel which you’ll use for later processing, such as a render texture. -@par -Format1: separate\_scene\_blend <simple\_colour\_blend> <simple\_alpha\_blend> -@par -Example: separate\_scene\_blend add modulate - -This example would add colour components but multiply alpha components. The blend modes available are as in [scene\_blend](#scene_005fblend). The more advanced form is also available: -@par -Format2: separate\_scene\_blend <colour\_src\_factor> <colour\_dest\_factor> <alpha\_src\_factor> <alpha\_dest\_factor> -@par -Example: separate\_scene\_blend one one\_minus\_dest\_alpha one one - -Again the options available in the second format are the same as those in the second format of [scene\_blend](#scene_005fblend). - - - -## scene\_blend\_op - -This directive changes the operation which is applied between the two components of the scene blending equation - -@par -Format: scene\_blend\_op <op> - -@copydetails Ogre::Pass::setSceneBlendingOperation -You may change this to ’add’, ’subtract’, ’reverse_subtract’, ’min’ or ’max’. - - - -## separate\_scene\_blend\_op - -This directive is as scene\_blend\_op, except that you can set the operation for colour and alpha separately. -@par -Format: separate\_scene\_blend\_op <colourOp> <alphaOp> Default: separate\_scene\_blend\_op add add - - - -## depth\_check - -Sets whether or not this pass renders with depth-buffer checking on or not. -@par -Format: depth\_check <on|off> - -@copydetails Ogre::Pass::setDepthCheckEnabled - -Default: depth\_check on - - - -## depth\_write - -Sets whether or not this pass renders with depth-buffer writing on or not. - -@par -Format: depth\_write <on|off> - -@copydetails Ogre::Pass::setDepthWriteEnabled - -@par -Default: depth\_write on
- - - -## depth\_func - -Sets the function used to compare depth values when depth checking is on. -@par -Format: depth\_func <func> - -@copydetails Ogre::Pass::setDepthFunction - -@param func one of Ogre::CompareFunction without the `CMPF_` prefix. E.g. `CMPF_LESS_EQUAL` becomes `less_equal`. - -@par -Default: depth\_func less\_equal - - - -## depth\_bias - -Sets the bias applied to the depth value of this pass. -@par -Format: depth\_bias <constantBias> \[<slopeScaleBias>\] - -@copydetails Ogre::Pass::setDepthBias - -Also see [iteration\_depth\_bias](#iteration_005fdepth_005fbias) - - - -## iteration\_depth\_bias - -Sets an additional bias derived from the number of times a given pass has been iterated. Operates just like [depth\_bias](#depth_005fbias) except that it applies an additional bias factor to the base depth\_bias value, multiplying the provided value by the number of times this pass has been iterated before, through one of the [iteration](#iteration) variants. So the first time the pass will get the depth\_bias value, the second time it will get depth\_bias + iteration\_depth\_bias, the third time it will get depth\_bias + iteration\_depth\_bias \* 2, and so on. The default is zero. -@par -Format: iteration\_depth\_bias <bias\_per\_iteration> - - - -## alpha\_rejection - -Sets the way the pass will have use alpha to totally reject pixels from the pipeline. -@par -Format: alpha\_rejection <function> <value> -@par -Example: alpha\_rejection greater\_equal 128 - -The function parameter can be any of the options listed in the material depth\_function attribute. The value parameter can theoretically be any value between 0 and 255, but is best limited to 0 or 128 for hardware compatibility. - -@ffp_rtss_only - -@par -Default: alpha\_rejection always\_pass - - - -## alpha\_to\_coverage - -Sets whether this pass will use ’alpha to coverage’, - -@par -Format: alpha\_to\_coverage <on|off> - -@copydetails Ogre::Pass::setAlphaToCoverageEnabled - -@par -Default: alpha\_to\_coverage off - - - -## light_scissor - -Sets whether when rendering this pass, rendering will be limited to a screen-space scissor rectangle representing the coverage of the light(s) being used in this pass. -@par -Format: light\_scissor <on|off> -@par -Default: light\_scissor off - -@copydetails Ogre::Pass::setLightScissoringEnabled - - - -## light\_clip\_planes - -Sets whether when rendering this pass, triangle setup will be limited to clipping volume covered by the light. -@par -Format: light\_clip\_planes <on|off> -@par -Default: light\_clip\_planes off - -@copydetails Ogre::Pass::setLightClipPlanesEnabled - -@see @ref Integrated-Texture-Shadows - -## illumination_stage {#illumination_005fstage} - -@copydetails Ogre::Pass::setIlluminationStage - -@par -Format: illumination\_stage <ambient|per\_light|decal> Default: none (autodetect) - - - -## transparent\_sorting - -Sets if transparent textures should be sorted by depth or not. -@par -Format: transparent\_sorting <on|off|force> - -By default all transparent materials are sorted such that renderables furthest away from the camera are rendered first. This is usually the desired behaviour but in certain cases this depth sorting may be unnecessary and undesirable. If for example it is necessary to ensure the rendering order does not change from one frame to the next. In this case you could set the value to ’off’ to prevent sorting. - -You can also use the keyword ’force’ to force transparent sorting on, regardless of other circumstances. Usually sorting is only used when the pass is also transparent, and has a depth write or read which indicates it cannot reliably render without sorting. By using ’force’, you tell OGRE to sort this pass no matter what other circumstances are present. -@par -Default: transparent\_sorting on - - - -## cull\_hardware - -Sets the hardware culling mode for this pass. -@par -Format: cull\_hardware <clockwise|anticlockwise|none> - -@copydetails Ogre::Pass::setCullingMode - -@par -Default: cull\_hardware clockwise
NB this is the same as OpenGL’s default but the opposite of Direct3D’s default (because Ogre uses a right-handed coordinate system like OpenGL). - - - -## cull\_software - -Sets the software culling mode for this pass. -@par -Format: cull\_software <back|front|none> - -@copydetails Ogre::Pass::setManualCullingMode - -@par -Default: cull\_software back - - - -## lighting - -Sets whether or not dynamic lighting is turned on for this pass or not. - -@par -Format: lighting <on|off> - -@copydetails Ogre::Pass::setLightingEnabled -@par -Default: lighting on - - - -## shading - -Sets the kind of shading which should be used for representing dynamic lighting for this pass. -@par -Format: shading <mode> - -@copydetails Ogre::Pass::setShadingMode - -@param mode one of Ogre::ShadeOptions without the `SO_` prefix. E.g. `SO_FLAT` becomes `flat`. - -@par -Default: shading gouraud - - - -## polygon\_mode - -@copydetails Ogre::Pass::setPolygonMode - -@par -Format: polygon_mode <solid|wireframe|points> - -@param mode one of Ogre::PolygonMode without the `PM_` prefix. E.g. `PM_SOLID` becomes `solid`. - -@par -Default: polygon\_mode solid - - - -## polygon\_mode\_overrideable - -Sets whether or not the [polygon\_mode](#polygon_005fmode) set on this pass can be downgraded by the camera - -@par -Format: polygon\_mode\_overrideable <override> - -@copydetails Ogre::Pass::setPolygonModeOverrideable - - - -## fog\_override - -Tells the pass whether it should override the scene fog settings, and enforce it’s own. Very useful for things that you don’t want to be affected by fog when the rest of the scene is fogged, or vice versa. -@par -Format: fog\_override <override?> \[<type> <colour> <density> <start> <end>\] -@par -Default: fog\_override false - -If you specify ’true’ for the first parameter and you supply the rest of the parameters, you are telling the pass to use these fog settings in preference to the scene settings, whatever they might be. If you specify ’true’ but provide no further parameters, you are telling this pass to never use fogging no matter what the scene says. - -@param type **none** = No fog, equivalent of just using ’fog\_override true’
**linear** = Linear fog from the <start> and <end> distances
**exp** = Fog increases exponentially from the camera (fog = 1/e^(distance \* density)), use <density> param to control it
**exp2** = Fog increases at the square of FOG\_EXP, i.e. even quicker (fog = 1/e^(distance \* density)^2), use <density> param to control it - -@param colour Sequence of 3 floating point values from 0 to 1 indicating the red, green and blue intensities - -@param density The density parameter used in the ’exp’ or ’exp2’ fog types. Not used in linear mode but param must still be there as a placeholder - -@param start The start distance from the camera of linear fog. Must still be present in other modes, even though it is not used. - -@param end The end distance from the camera of linear fog. Must still be present in other modes, even though it is not used. - -@par -Example: fog\_override true exp 1 1 1 0.002 100 10000 - - - -## colour\_write - -Sets whether this pass renders with colour writing on or not. Alternatively, it can also be used to enable/disable colour writing specific channels. -In the second format, the parameters are in the red, green, blue, alpha order. - -@par -Format 1: colour\_write <on|off> -@par -Format 2: colour\_write <on|off> <on|off> <on|off> <on|off> - -@copydetails Ogre::Pass::setColourWriteEnabled - -@par -Default: colour\_write on
- - - -## start\_light - -Sets the first light which will be considered for use with this pass. -@par -Format: start\_light <number> - -@copydetails Ogre::Pass::setStartLight - -@par -Default: start\_light 0
- - - -## max\_lights - -Sets the maximum number of lights which will be considered for use with this pass. -@par -Format: max\_lights <number> - -The maximum number of lights which can be used when rendering fixed-function materials is set by the rendering system, and is typically set at 8. When you are using the programmable pipeline (See [Using Vertex/Geometry/Fragment Programs in a Pass](@ref Using-Vertex_002fGeometry_002fFragment-Programs-in-a-Pass)) this limit is dependent on the program you are running, or, if you use ’iteration once\_per\_light’ or a variant (See @ref iteration), it effectively only bounded by the number of passes you are willing to use. If you are not using pass iteration, the light limit applies once for this pass. If you are using pass iteration, the light limit applies across all iterations of this pass - for example if you have 12 lights in range with an ’iteration once\_per\_light’ setup but your max\_lights is set to 4 for that pass, the pass will only iterate 4 times. -@par -Default: max\_lights 8
- -## iteration {#iteration} - -Sets whether or not this pass is iterated, i.e. issued more than once. -@par -Format 1: iteration <once | once\_per\_light> \[lightType\] - -@par -Format 2: iteration <number> \[<per\_light> \[lightType\] - -@par -Format 3: iteration <number> \[<per\_n\_lights> <num\_lights> \[lightType\] - -@par -Examples: - -
-
iteration once
- -The pass is only executed once which is the default behaviour. - -
iteration once\_per\_light point
- -The pass is executed once for each point light. - -
iteration 5
- -The render state for the pass will be setup and then the draw call will execute 5 times. - -
iteration 5 per\_light point
- -The render state for the pass will be setup and then the draw call will execute 5 times. This will be done for each point light. - -
iteration 1 per\_n\_lights 2 point
- -The render state for the pass will be setup and the draw call executed once for every 2 lights. - -

- -By default, passes are only issued once. However, if you use the programmable pipeline, or you wish to exceed the normal limits on the number of lights which are supported, you might want to use the once\_per\_light option. In this case, only light index 0 is ever used, and the pass is issued multiple times, each time with a different light in light index 0. Clearly this will make the pass more expensive, but it may be the only way to achieve certain effects such as per-pixel lighting effects which take into account 1..n lights. - -Using a number instead of "once" instructs the pass to iterate more than once after the render state is setup. The render state is not changed after the initial setup so repeated draw calls are very fast and ideal for passes using programmable shaders that must iterate more than once with the same render state i.e. shaders that do fur, motion blur, special filtering. - -If you use once\_per\_light, you should also add an ambient pass to the technique before this pass, otherwise when no lights are in range of this object it will not get rendered at all; this is important even when you have no ambient light in the scene, because you would still want the objects silhouette to appear. - -The lightType parameter to the attribute only applies if you use once\_per\_light, per\_light, or per\_n\_lights and restricts the pass to being run for lights of a single type (either ’point’, ’directional’ or ’spot’). In the example, the pass will be run once per point light. This can be useful because when you’re writing a vertex / fragment program it is a lot easier if you can assume the kind of lights you’ll be dealing with. However at least point and directional lights can be dealt with in one way. Default: iteration once - - - -Example: Simple Fur shader material script that uses a second pass with 10 iterations to grow the fur: - -```cpp -// GLSL simple Fur -vertex_program GLSLDemo/FurVS glsl -{ - source fur.vert - default_params - { - param_named_auto lightPosition light_position_object_space 0 - param_named_auto eyePosition camera_position_object_space - param_named_auto passNumber pass_number - param_named_auto multiPassNumber pass_iteration_number - param_named furLength float 0.15 - } -} - -fragment_program GLSLDemo/FurFS glsl -{ - source fur.frag - default_params - { - param_named Ka float 0.2 - param_named Kd float 0.5 - param_named Ks float 0.0 - param_named furTU int 0 - } -} - -material Fur -{ - technique GLSL - { - pass base_coat - { - ambient 0.7 0.7 0.7 - diffuse 0.5 0.8 0.5 - specular 1.0 1.0 1.0 1.5 - - vertex_program_ref GLSLDemo/FurVS - { - } - - fragment_program_ref GLSLDemo/FurFS - { - } - - texture_unit - { - texture Fur.tga - tex_coord_set 0 - filtering trilinear - } - } - - pass grow_fur - { - ambient 0.7 0.7 0.7 - diffuse 0.8 1.0 0.8 - specular 1.0 1.0 1.0 64 - depth_write off - - scene_blend src_alpha one - iteration 10 - - vertex_program_ref GLSLDemo/FurVS - { - } - - fragment_program_ref GLSLDemo/FurFS - { - } - - texture_unit - { - texture Fur.tga - tex_coord_set 0 - filtering trilinear - } - } - } -} -``` - -@note use gpu program auto parameters [pass\_number](#pass_005fnumber) and [pass\_iteration\_number](#pass_005fiteration_005fnumber) to tell the vertex, geometry or fragment program the pass number and iteration number. - - - -## point\_size - -@copydetails Ogre::Pass::setPointSize - -@par -Format: point\_size <size> Default: point\_size 1.0 - -@ffp_rtss_only - - - -## point\_sprites - -@copydetails Ogre::Pass::setPointSpritesEnabled - -@par -Format: point\_sprites <on|off> Default: point\_sprites off - - - -## point\_size\_attenuation - -Defines whether point size is attenuated with view space distance, and in what fashion. - -@par -Format: point\_size\_attenuation <enabled> \[constant linear quadratic\] Default: point\_size\_attenuation off - -@copydetails Ogre::Pass::setPointAttenuation - -@ffp_rtss_only - - - -## point\_size\_min - -Sets the minimum point size after attenuation ([point\_size\_attenuation](#point_005fsize_005fattenuation)). For details on the size metrics, See [point\_size](#point_005fsize). -@par -Format: point\_size\_min <size> Default: point\_size\_min 0 - - - -## point\_size\_max - -Sets the maximum point size after attenuation ([point\_size\_attenuation](#point_005fsize_005fattenuation)). For details on the size metrics, See [point\_size](#point_005fsize). A value of 0 means the maximum is set to the same as the max size reported by the current card. -@par -Format: point\_size\_max <size> Default: point\_size\_max 0 - - -## line_width -@copydetails Ogre::Pass::setLineWidth - -@par -Format: line_width <width> -@par -Default: line_width 1 - -# Texture Units {#Texture-Units} - -Here are the attributes you can use in a @c texture_unit section of a .material script: - - - -## Available Texture Unit Attributes - -- [texture\_alias](#texture_005falias) -- [texture](#texture) -- [anim\_texture](#anim_005ftexture) -- [cubic\_texture](#cubic_005ftexture) -- [tex\_coord\_set](#tex_005fcoord_005fset) -- [colour\_op](#colour_005fop) -- [colour\_op\_ex](#colour_005fop_005fex) -- [colour\_op\_multipass\_fallback](#colour_005fop_005fmultipass_005ffallback) -- [alpha\_op\_ex](#alpha_005fop_005fex) -- [env\_map](#env_005fmap) -- [scroll](#scroll) -- [scroll\_anim](#scroll_005fanim) -- [rotate](#rotate) -- [rotate\_anim](#rotate_005fanim) -- [scale](#scale) -- [wave\_xform](#wave_005fxform) -- [transform](#transform) -- [content\_type](#content_005ftype) -- [sampler_ref](#sampler_ref) -- [unordered_access_mip](#unordered_access_mip) - -@note Furthermore all attributes of @ref Samplers are available. Using any of them will create a new Ogre::Sampler local to the texture unit. -This means that any changes you made to the Default Sampler e.g. via Ogre::MaterialManager::setDefaultTextureFiltering have no effect anymore. -If several texture units share the same Sampler settings, you are encouraged to reference the same Sampler via [sampler_ref](#sampler_ref) for improved performance. - -You can also use nested section in order to use a special add-ins -- @c texture_source as a source of texture data, see @ref External-Texture-Sources for details -- @c rtshader_system for additional layer blending options, see @ref rtss for details. - - - -## Attribute Descriptions - - - -## texture\_alias - -Sets the alias name for this texture unit. -@par -Format: texture\_alias <name> -@par -Example: texture\_alias NormalMap - -@deprecated texture aliases are a restricted version of @ref Script-Variables, which you should instead. - - - -## texture - -Sets the name of the static texture image this layer will use. -@par -Format: texture <texturename> \[<type>\] \[unlimited | numMipMaps\] \[<PixelFormat>\] \[gamma\] -@par -Example: texture funkywall.jpg - -This setting is mutually exclusive with the anim\_texture attribute. Note that the texture file cannot include spaces. Those of you Windows users who like spaces in filenames, please get over it and use underscores instead. - -@param type -specify a the type of texture to create - the default is ’2d’, but you can override this; here’s the full list: -
-
1d
- -A 1-dimensional texture; that is, a texture which is only 1 pixel high. These kinds of textures can be useful when you need to encode a function in a texture and use it as a simple lookup, perhaps in a fragment program. It is important that you use this setting when you use a fragment program which uses 1-dimensional texture coordinates, since GL requires you to use a texture type that matches (D3D will let you get away with it, but you ought to plan for cross-compatibility). Your texture widths should still be a power of 2 for best compatibility and performance. - -
2d
- -The default type which is assumed if you omit it, your texture has a width and a height, both of which should preferably be powers of 2, and if you can, make them square because this will look best on the most hardware. These can be addressed with 2D texture coordinates. - -
3d
- -A 3 dimensional texture i.e. volume texture. Your texture has a width, a height, both of which should be powers of 2, and has depth. These can be addressed with 3d texture coordinates i.e. through a pixel shader. - -
cubic
- -This texture is made up of 6 2D textures which are pasted around the inside of a cube. -Can be addressed with 3D texture coordinates and are useful for cubic reflection maps. -If the @c texturename in this format is something like @c skybox.jpg, the system will expect `skybox_px.jpg, skybox_nx.jpg, skybox_py.jpg, skybox_ny.jpg, skybox_pz.jpg, skybox_nz.jpg` for the individual faces. For compatibility, the suffixes `_lf, _rt, _up, _dn, _fr, _bk` are also supported. -Alternatively a single file with all faces can be used, if supported by the texture format (e.g. DDS). -
- -@param numMipMaps -specify the number of mipmaps to generate for this texture. The default is ’unlimited’ which means mips down to 1x1 size are generated. You can specify a fixed number (even 0) if you like instead. Note that if you use the same texture in many material scripts, the number of mipmaps generated will conform to the number specified in the first texture\_unit used to load the texture - so be consistent with your usage. - -@param PixelFormat -specify the desired pixel format of the texture to create, which may be different to the pixel format of the texture file being loaded. Bear in mind that the final pixel format will be constrained by hardware capabilities so you may not get exactly what you ask for. -Names defined in Ogre::PixelFormat are valid values. - -@param gamma -informs the renderer that you want the graphics hardware to perform gamma correction on the texture values as they are sampled for rendering. This is only applicable for textures which have 8-bit colour channels (e.g.PF\_R8G8B8). Often, 8-bit per channel textures will be stored in [gamma space](http://en.wikipedia.org/wiki/Gamma_correction) in order to increase the precision of the darker colours but this can throw out blending and filtering calculations since they assume linear space colour values. For the best quality shading, you may want to enable gamma correction so that the hardware converts the texture values to linear space for you automatically when sampling the texture, then the calculations in the pipeline can be done in a reliable linear colour space. When rendering to a final 8-bit per channel display, you’ll also want to convert back to gamma space which can be done in your shader (by raising to the power 1/2.2) or you can enable gamma correction on the texture being rendered to or the render window. Note that the ’gamma’ option on textures is applied on loading the texture so must be specified consistently if you use this texture in multiple places. - - - -## anim\_texture - -Sets the images to be used in an animated texture layer. There are 2 formats, one for implicitly determined image names, one for explicitly named images. -@par -Format1 (short): anim\_texture <name> <numFrames> <duration> - -@copydetails Ogre::TextureUnitState::setAnimatedTextureName - -@par -Example: anim\_texture flame.jpg 5 2.5 - -@par -Format2 (long): anim\_texture <frame1> <frame2> ... <duration> -@par -Example: anim\_texture flamestart.jpg flamemore.png flameagain.jpg moreflame.jpg lastflame.tga 2.5 - -This sets up the same duration animation but from 5 separately named image files. The first format is more concise, but the second is provided if you cannot make your images conform to the naming standard required for it. -@par -Default: none - - - -## cubic\_texture - -Sets the images used in a cubic texture, i.e. one made up of 6 individual images making up the faces of a cube or 1 cube texture if supported by the texture format(DDS for example) and rendersystem.. These kinds of textures are used for reflection maps (if hardware supports cubic reflection maps) or skyboxes. There are 2 formats, a brief format expecting image names of a particular format and a more flexible but longer format for arbitrarily named textures. -@par -Format1 (short): cubic\_texture <base\_name> <combinedUVW|separateUV> - -@deprecated use the format '`texture cubic`' instead - -@par -Format2 (long): cubic\_texture <pz> <nz> <nx> <px> <py> <ny> <combinedUVW|separateUV> - -In this case each face is specified explicitly, in case you don’t want to conform to the image naming standards above. - -In both cases the final parameter means the following: - -
-
combinedUVW
-The 6 textures are combined into a single ’cubic’ texture map which is then addressed using 3D texture coordinates. -
-
separateUV
-This is no longer supported and behaves like combinedUVW. -
-

- - - -## content_type - -Tells this texture unit where it should get its content from. The default is to get texture content from a named texture, as defined with the [texture](#texture), [cubic\_texture](#cubic_005ftexture), [anim\_texture](#anim_005ftexture) attributes. However you can also pull texture information from other automated sources. - -@par -Format: content\_type <type> \[<compositorName>\] \[<textureName>\] \[<mrtIndex>\] - -@param type -
-
named
- -@copybrief Ogre::TextureUnitState::CONTENT_NAMED - -
shadow
- -This option allows you to pull in a shadow texture, and is only valid when you use texture shadows and one of the ’custom sequence’ shadowing types (See @ref Shadows). The shadow texture in question will be from the ’n’th closest light that casts shadows, unless you use light-based pass iteration or the light\_start option which may start the light index higher. When you use this option in multiple texture units within the same pass, each one references the next shadow texture. The shadow texture index is reset in the next pass, in case you want to take into account the same shadow textures again in another pass (e.g. a separate specular / gloss pass). By using this option, the correct light frustum projection is set up for you for use in fixed-function, if you use shaders just reference the texture\_viewproj\_matrix auto parameter in your shader. - -
compositor
- -@copybrief Ogre::TextureUnitState::CONTENT_COMPOSITOR This can be either in a render\_scene directive inside a compositor script, or in a general pass in a viewport that has a compositor attached. Note that this is a reference only, meaning that it does not change the render order. You must make sure that the order is reasonable for what you are trying to achieve (for example, texture pooling might cause the referenced texture to be overwritten by something else by the time it is referenced). - -
- -@copydetails Ogre::TextureUnitState::setCompositorReference - -@par -Example: content\_type compositor DepthCompositor OutputTexture - -@par -Default: content\_type named - - - - -## tex\_coord\_set - -@copybrief Ogre::TextureUnitState::setTextureCoordSet -@copydetails Ogre::TextureUnitState::setTextureCoordSet - -@par -Format: tex\_coord\_set <set\_num> - -@ffp_rtss_only - -@par -Example: tex\_coord\_set 2 -@par -Default: tex\_coord\_set 0 - - - -## colour\_op - -@ffp_rtss_only - -Determines how the colour of this texture layer is combined with the one below it (or the lighting effect on the geometry if this is the first layer). -@par -Format: colour\_op <op> - -@copydetails Ogre::TextureUnitState::setColourOperation Without the `LBO_` prefix. E.g. `LBO_REPLACE` becomes `replace`. - -@par -Default: colour\_op modulate - - - -## colour\_op\_ex - -@ffp_rtss_only -@par -Format: colour\_op\_ex <op> <source1> <source2> \[<manualBlend>\] \[<arg1>\] \[<arg2>\] -@par -Example colour\_op\_ex add\_signed src\_manual src\_current 0.5 - -@copydetails Ogre::TextureUnitState::setColourOperationEx - -Each parameter can be one of Ogre::LayerBlendOperationEx or Ogre::LayerBlendSource without the prefix. E.g. `LBX_MODULATE_X4` becomes `modulate_x4`. - -@par -Default: none (colour\_op modulate)
- - - -## colour\_op\_multipass\_fallback - -Sets the multipass fallback operation for this layer, if you used colour\_op\_ex and not enough multitexturing hardware is available. -@par -Format: colour\_op\_multipass\_fallback <src\_factor> <dest\_factor> -@par -Example: colour\_op\_multipass\_fallback one one\_minus\_dest\_alpha - -@copydetails Ogre::TextureUnitState::setColourOpMultipassFallback - - - -## alpha\_op\_ex - -@ffp_rtss_only - -@par -Format: alpha\_op\_ex <op> <source1> <source2> \[<manualBlend>\] \[<arg1>\] \[<arg2>\] - -@copydetails Ogre::TextureUnitState::setAlphaOperation - - - -## env\_map - -@ffp_rtss_only - -@copybrief Ogre::TextureUnitState::setEnvironmentMap - -@par -Format: env\_map <off|spherical|planar|cubic\_reflection|cubic\_normal> - -Environment maps make an object look reflective by using automatic texture coordinate generation depending on the relationship between the objects vertices or normals and the eye. - -
-
spherical
- -@copybrief Ogre::TextureUnitState::ENV_CURVED -Requires a single texture which is either a fish-eye lens view of the reflected scene, or some other texture which looks good as a spherical map (a texture of glossy highlights is popular especially in car sims). This effect is based on the relationship between the eye direction and the vertex normals of the object, so works best when there are a lot of gradually changing normals, i.e. curved objects. - -
planar
- -The effect is based on the position of the vertices in the viewport rather than vertex normals. This is useful for planar geometry (where a spherical env\_map would not look good because the normals are all the same) or objects without normals. - -@remarks This was never actually implemented. Same as @c spherical on all backends. - -
cubic\_reflection
- -@copybrief Ogre::TextureUnitState::ENV_REFLECTION -Uses a group of 6 textures making up the inside of a cube, each of which is a view if the scene down each axis. Works extremely well in all cases but has a higher technical requirement from the card than spherical mapping. Requires that you bind a [cubic texture](#texture) to this unit. - -
cubic\_normal
-@copybrief Ogre::TextureUnitState::ENV_NORMAL -Generates 3D texture coordinates containing the camera space normal vector from the normal information held in the vertex data. Again, use of this feature requires a [cubic texture](#texture). - -

-@par -Default: env\_map off
- - - -## scroll - -@copybrief Ogre::TextureUnitState::setTextureScroll -@par -Format: scroll <u> <v> - -@copydetails Ogre::TextureUnitState::setTextureScroll - -@shaderparam - - - -## scroll\_anim - -@copybrief Ogre::TextureUnitState::setScrollAnimation -@par -Format: scroll\_anim <uSpeed> <vSpeed>
- -@copydetails Ogre::TextureUnitState::setScrollAnimation - -@shaderparam - - -## rotate - -@copybrief Ogre::TextureUnitState::setTextureRotate - -@par -Format: rotate <angle_in_deg> - -@copydetails Ogre::TextureUnitState::setTextureRotate - -@shaderparam - - - -## rotate\_anim - -@copybrief Ogre::TextureUnitState::setRotateAnimation - -@par -Format: rotate\_anim <speed> - -@copydetails Ogre::TextureUnitState::setRotateAnimation - -@shaderparam - - - -## scale - -@copybrief Ogre::TextureUnitState::setTextureScale - -@par -Format: scale <uScale> <vScale> - -@copydetails Ogre::TextureUnitState::setTextureScale - - -@shaderparam - - - -## wave\_xform - -@copybrief Ogre::TextureUnitState::setTransformAnimation - -@par -Format: wave\_xform <ttype> <waveType> <base> <frequency> <phase> <amplitude> -@par -Example: wave\_xform scale\_x sine 1.0 0.2 0.0 5.0 - -@copydetails Ogre::TextureUnitState::setTransformAnimation - -ttype is one of -
-
scroll\_x
- -Animate the u scroll value - -
scroll\_y
- -Animate the v scroll value - -
rotate
- -Animate the rotate value - -
scale\_x
- -Animate the u scale value - -
scale\_y
- -Animate the v scale value - -
- -waveType is one of Ogre::WaveformType without the `WFT_` prefix. E.g. `WFT_SQUARE` becomes `square`. - -@shaderparam - - - -## transform - -This attribute allows you to specify a static 4x4 transformation matrix for the texture unit, thus replacing the individual scroll, rotate and scale attributes mentioned above. -@par -Format: transform m00 m01 m02 m03 m10 m11 m12 m13 m20 m21 m22 m23 m30 m31 m32 m33 - -The indexes of the 4x4 matrix value above are expressed as m<row><col>. - -@shaderparam - - -## sampler_ref - -By default all texture units use a shared default Sampler object. This parameter allows you to explicitly set a different one. - -@par -Format: sampler_ref <name> - -@par -Example: sampler_ref mySampler - - -## unordered_access_mip - -@copybrief Ogre::TextureUnitState::setUnorderedAccessMipLevel - -@par -Format: unordered_access_mip <mipLevel> - -@par -Example: unordered_access_mip 0 - -# Samplers {#Samplers} - -Samplers allow you to quickly change the settings for all associated Textures. Typically you have many Textures but only a few sampling states in your application. - -```cpp -sampler mySampler -{ - filtering bilinear - max_anisotropy 16 -} - -... - texture_unit - { - texture myTexture.dds - sampler_ref mySampler - } -... -``` - -## Available parameters - -- [filtering](#filtering) -- [max\_anisotropy](#max_005fanisotropy) -- [tex\_address\_mode](#tex_005faddress_005fmode) -- [tex\_border\_colour](#tex_005fborder_005fcolour) -- [mipmap\_bias](#mipmap_005fbias) -- [compare_test](#compare_test) -- [comp_func](#comp_func) - - - -## tex\_address\_mode - -Defines what happens when texture coordinates exceed 1.0 for this texture layer.You can use the simple format to specify the addressing mode for all 3 potential texture coordinates at once, or you can use the 2/3 parameter extended format to specify a different mode per texture coordinate. -@par -Simple Format: tex\_address\_mode <uvw\_mode>
Extended Format: tex\_address\_mode <u\_mode> <v\_mode> \[<w\_mode>\] - -Valid values for both are one of Ogre::TextureAddressingMode without the `TAM_` prefix. E.g. `TAM_WRAP` becomes `wrap`. - -@par -Default: tex\_address\_mode wrap - - - -## tex\_border\_colour - -Sets the border colour of border texture address mode (see [tex\_address\_mode](#tex_005faddress_005fmode)). -@par -Format: tex\_border\_colour <red> <green> <blue> \[<alpha>\]
NB valid colour values are between 0.0 and 1.0. -@par -Example: tex\_border\_colour 0.0 1.0 0.3 -@par -Default: tex\_border\_colour 0.0 0.0 0.0 1.0 - - - -## filtering - -Sets the type of texture filtering used when magnifying or minifying a texture. There are 2 formats to this attribute, the simple format where you simply specify the name of a predefined set of filtering options, and the complex format, where you individually set the minification, magnification, and mip filters yourself. - -### Simple Format -With this format, you only need to provide a single parameter - -@par -Format: filtering <none|bilinear|trilinear|anisotropic>
Default: filtering bilinear - -
-
none
-@copybrief Ogre::TFO_NONE - -@copydetails Ogre::TFO_NONE -
-
bilinear
-@copybrief Ogre::TFO_BILINEAR - -@copydetails Ogre::TFO_BILINEAR -
-
trilinear
-@copybrief Ogre::TFO_TRILINEAR - -@copydetails Ogre::TFO_TRILINEAR -
-
anisotropic
-@copybrief Ogre::TFO_ANISOTROPIC - -@copydetails Ogre::TFO_ANISOTROPIC -
- -### Complex Format -This format gives you complete control over the minification, magnification, and mip filters. - -@par -Format: filtering <minFilter> <magFilter> <mipFilter> -@par -Default: filtering linear linear point - -Each parameter can be one of Ogre::FilterOptions without the `FO_` prefix. E.g. `FO_LINEAR` becomes `linear`. - -@copydetails Ogre::Sampler::setFiltering(FilterOptions,FilterOptions,FilterOptions) - - - -## max\_anisotropy - -@copybrief Ogre::Sampler::setAnisotropy - -@par -Format: max\_anisotropy <maxAniso>
Default: max\_anisotropy 1 - -@copydetails Ogre::Sampler::setAnisotropy - - - -## mipmap\_bias - -@copydetails Ogre::Sampler::setMipmapBias - -@par -Format: mipmap\_bias <value>
Default: mipmap\_bias 0 - - -## compare_test - -@copybrief Ogre::Sampler::setCompareEnabled - -@copydetails Ogre::Sampler::setCompareEnabled - -@par -Format: compare_test on - -@par -Default: compare_test off - - - -## comp_func - -The comparison func to use when @c compare_test is enabled -@par -Format: comp_func <func> - -@param func one of Ogre::CompareFunction without the `CMPF_` prefix. E.g. `CMPF_LESS_EQUAL` becomes `less_equal`. - -# Using GPU Programs in a Pass {#Using-Vertex_002fGeometry_002fFragment-Programs-in-a-Pass} - -Within a pass section of a material script, you can reference a vertex, geometry, tessellation, compute, and / or a fragment program which has been defined in @ref High-level-Programs. The programs are defined separately from the usage of them in the pass, since the programs are very likely to be reused between many separate materials, probably across many different .material scripts, so this approach lets you define the program only once and use it many times. - -As well as naming the program in question, you can also provide parameters to it. Here’s a simple example: - -```cpp -vertex_program_ref myVertexProgram -{ - param_indexed_auto 0 worldviewproj_matrix - param_indexed 4 float4 10.0 0 0 0 -} -``` - -In this example, we bind a vertex program called ’myVertexProgram’ (which will be defined elsewhere) to the pass, and give it 2 parameters, one is an ’auto’ parameter, meaning we do not have to supply a value as such, just a recognised code (in this case it’s the world/view/projection matrix which is kept up to date automatically by Ogre). The second parameter is a manually specified parameter, a 4-element float. The indexes are described later. - -The syntax of the link to a vertex program and a fragment or geometry program are identical, the only difference is that `fragment_program_ref` and `geometry_program_ref` are used respectively instead of `vertex_program_ref`. For tessellation shaders, use `tessellation_hull_program_ref` and `tessellation_domain_program_ref` to link to the hull tessellation program and the domain tessellation program respectively. Compute shader programs can be linked with `compute_program_ref`. - -For many situations vertex, geometry and fragment programs are associated with each other in a pass but this is not cast in stone. You could have a vertex program that can be used by several different fragment programs. - -Moreover, older APIs permit the use of both fixed pipeline and programmable pipeline (shaders) simultaneously. Specifically, the OpenGL compatibility profile and Direct3D SM2.x allow this. -You can utilize the vertex fixed function pipeline and just provide a @c fragment_program_ref in a pass, with no vertex program reference included. The fragment program must comply with the specified requirements of the related API in order to access the outputs of the vertex fixed pipeline. Alternatively, you can employ a vertex program that directly feeds into the fragment fixed function pipeline. -Most of Ogre's render systems do not support the Fixed Function pipeline. In that case, if you supply vertex shader, you will need to supply a fragment shader as well. - -# Adding new Techniques, Passes, to copied materials {#Adding-new-Techniques_002c-Passes_002c-to-copied-materials_003a} - -If a new technique or pass needs to be added to a copied material then use a unique name for the technique or pass that does not exist in the parent material. Using an index for the name that is one greater than the last index in the parent will do the same thing. The new technique/pass will be added to the end of the techniques/passes copied from the parent material. - -@note if passes or techniques aren’t given a name, they will take on a default name based on their index. For example the first pass has index 0 so its name will be 0. - -# Identifying Texture Units to override values {#Identifying-Texture-Units-to-override-values} - -A specific texture unit state (TUS) can be given a unique name within a pass of a material so that it can be identified later in cloned materials that need to override specified texture unit states in the pass without declaring previous texture units. Using a unique name for a Texture unit in a pass of a cloned material adds a new texture unit at the end of the texture unit list for the pass. - -```cpp -material BumpMap2 : BumpMap1 -{ - technique ati8500 - { - pass 0 - { - texture_unit NormalMap - { - texture BumpyMetalNM.png - } - } - } -} -``` diff --git a/Docs/src/ogre-shadows.md b/Docs/src/ogre-shadows.md deleted file mode 100644 index e0b0bde12d9..00000000000 --- a/Docs/src/ogre-shadows.md +++ /dev/null @@ -1,676 +0,0 @@ -# Shadow Mapping in %Ogre {#ShadowMappingOgre} - -# Introduction to the Shadow Mapping Algorithm {#ShadowMappingIntro} - -@tableofcontents - -Shadow mapping, an algorithm introduced by Lance Williams  @cite WIL78 and -now prevalent in real-time and off-line rendering, is based on a simple -idea: First, a snapshot of the scene is taken from the viewpoint of the -light. Then, when creating an image from the perspective of the camera, -the light’s snapshot is used to determine visibility. Parts of the scene -seen by both the light and the camera must be lit (by the light in -question). Parts of the scene visible only to the camera must be -shadowed. We do not care about parts of the scene seen only by the -light. - -@note This tutorial is more explicit and in depth than required -to merely render shadows in OGRE as to teach you the theory behind the -rendering shadows as well. - -In practice, the snapshot from the viewpoint of the light is stored as a -floating point depth buffer. It is important to use a format that -supports enough precision to avoid shadow acne (z-fighting) on lit -surfaces. In Ogre, we can specify the depth format to use; in the -example code, we will choose the 16-bit format. - -Once shadow determination has occurred (whether a fragment is in shadow -or not), Ogre provides two different ways to render the shadows into the -final image. The modulative technique will uniformly darken regions of -the image determined to be in shadow. This is a cheaper and less -accurate lighting model. For instance, specular highlights in shadow -will appear as darkened specular highlights. The other technique is -additive light masking. This technique builds up contributions from each -light in non-shadowed areas and adds them together to create the final -image. The code in section @ref Implementation will use additive light -masking, but could just as easily be adapted for modulative shadows. - -## Formalism {#sm_formalism} - -Mathematically, the process can be represented as follows: Let \f$P_l\f$ and -\f$P_c\f$ be the projection matrices for the light and camera respectively. -Let \f$M_l\f$ and \f$M_c\f$ be the modelview matrices for the light and camera -coordinate systems. Let \f$\vec{x} = [x_1,x_2,x_3,1]^t\f$ be a point in -object space, \f$\vec{y} = [y_1,y_2,y_3,1]^t\f$ the screen space -coordinates, and \f$\vec{u} = [u_1,u_2,u_3,1]^t\f$ the shadow map -coordinates. - -\f[ - \begin{aligned} - \left[ \begin{array}{c} - u_1 w_l \\ - u_2 w_l \\ - u_3 w_l \\ - w_l \end{array} \right] = P_l M_l \left[ \begin{array}{c} - x_1 \\ - x_2 \\ - x_3 \\ - 1 \end{array} \right]\end{aligned} -\f] - -\f[\begin{aligned} - \left[ \begin{array}{c} - y_1 w_c \\ - y_2 w_c \\ - y_3 w_c \\ - w_c \end{array} \right] = P_c M_c \left[ \begin{array}{c} - x_1 \\ - x_2 \\ - x_3 \\ - 1 \end{array} \right]\end{aligned}\f] - -These equations can be written more concisely as: -\f$\vec{u}w_l = P_l M_l \vec{x}\f$ and \f$\vec{y} w_c = P_c M_c \vec{x}\f$. -Division of \f$\vec{u}w_l\f$ and \f$\vec{y}w_c\f$ by their respective -homogeneous coordinates yields the Euclidean representations \f$\vec{u}\f$ -and \f$\vec{y}\f$. - -Note that while \f$P_c\f$ and \f$M_c\f$ are completely determined by the camera -image we want to produce, we have some ambiguity in the \f$P_l\f$ and \f$M_l\f$ -chosen for shadow mapping. The degrees of freedom here are later -exploited to combat the aliasing issue. - -## Depth Biasing {#DepthBias} - -![](images/depthbias.svg) Shadow map sample must use one float to represent a range of possible depth values. -A depth sample is chosen in the middle. -Any camera image point in between the two camera rays will see the geometry, -and depending on distance from light will report differently on shadowed versus lit. -However, every such point should be lit. - -Due to the finite precision of floating point representations and -inherent inability of one number to represent a range of values, it is -often necessary to add a little bias to the depth values stored in a -shadow map. One does not simply store the \f$u_3\f$ value. Figure -\[fig:bias\] illustrates the issue. Here we have used blue dots on the -light’s image plane to represent boundaries between shadow “texels.†The -interval in between the dots then represents a shadow map sample for -which a single depth value (float) is stored. For the sample whose -boundary rays are shown, the red dot’s depth is saved. However, note -that from the camera’s perspective, any (camera) image point in between -the two drawn camera rays will hit the scene geometry within the shadow -map sample’s interval. Hence, the same shadow map sample depth will be -used to determine visibility for all such camera pixels. Camera pixels -whose rays fall to the right of the red dot will be marked as shadowed, -while pixels whose rays fall to the left of the red dot will be marked -as lit. This is not the right behavior because clearly all the pixels -should be marked as lit. As we can see, a depth bias is needed. By -pushing the shadow map sample’s depth farther (to the 2nd red dot), we -can achieve correct shadow determination. - -One could approach the depth bias issue in a completely *ad -hoc* manner, but it is possible to do better. One would ideally -compute a bias that depends on how depth (\f$u_3\f$) changes between shadow -map samples. The change in depth as one moves a unit step (to the next -shadow map sample) represents the ambiguity of the depth value. Such a -value may seem intractable to compute, but calculus and linear algebra -save the day. From calculus, we learn that the derivative provides the -best linear approximation to any function (\f$u_3 = u_3(u_1, u_2)\f$ in -particular). In multiple dimensions, this role is played by the Jacobian -(matrix of partial derivatives). In other words, we want to compute -\f$\frac{du_3}{du_1}\f$ and \f$\frac{du_3}{du_2}\f$, where we have treated \f$u_3\f$ -as a function of \f$u_1\f$ and \f$u_2\f$. Once these values are computed, it -makes sense to then add some weighted combination of these to the stored -depth value (e.g., some scale of the Jacobian’s Frobenius norm). - -But even if the light is staring at a plane straight on (view direciton -lines up with plane’s normal), making \f$\frac{du_3}{du_1}\f$ and -\f$\frac{du_3}{du_2}\f$ both zero, we would still need a slight offset -because rounding due to the float’s finite representation may still -cause shadow acne. In this case, we’d like to offset the depth by a -small value that pushes it beyond rounding ambiguity. While one could -use an arbitrary constant offset, this is unsatisfactory since the -constant in light image space corresponds to varying amounts of offset -in light space (pre-projection Euclidean space with light’s position at -origin). Let us instead choose a constant offset in the z direction of -*light space* and compute what the offset for a particular -sample should be in *light image space*. In Ogre’s example -code, the small constant offset in light space is chosen to be 1 unit. -If 1 is not a small amount in your engine’s chosen scale, you can easily -change this choice. At any rate, the relevant quantity is -\f$\frac{\partial u_3}{\partial X_3}\f$ where \f$\vec{X} = M_l \vec{x}\f$. - -The choices here closely mirror what OpenGL implements through -glPolygonOffset. The second adjustment is slightly different since -OpenGL chooses a vendor specific fudge factor. - -Equations for computing the stated quantities are provided below. One -need not wade through these to use the depth biasing code. Understanding -what the relevant parameters explained above are (in case adjustment is -needed) is sufficient. - -\f[\begin{aligned} -\label{eqn:dxqdu} - \frac{\partial (\vec{x} q_l)}{\partial u_i} = \mbox{i-th column of } M_l^{-1} P_l^{-1} V_l^{-1} \end{aligned}\f] - -where \f$V_l\f$ is the viewport matrix for the light and \f$i=1,2,3\f$. \f$q_l\f$ -turns out to be \f$1/w_l\f$. - -\f[\begin{aligned} -\label{eqn:dxdu} - \frac{\partial \vec{x}}{\partial u_i} = \frac{1}{q_l} \left( \frac{\partial (\vec{x} q_l)}{\partial u_i} - \vec{x}\frac{\partial q_l}{\partial u_i} \right) \\ -\label{eqn:du3du} - \frac{du_3}{du_j} = \left( \vec{n} \cdot \frac{\partial \vec{x}}{\partial u_3} \right)^{-1} \left( \vec{n} \cdot \frac{\partial \vec{x}}{\partial u_j} \right)\end{aligned}\f] - -where \f$\vec{n}\f$ is the normal at point \f$\vec{x}\f$ and \f$j=1,2\f$. Note that -(\[eqn:du3du\]) is exactly the set of values needed for the first part. - -\f[\begin{aligned} -\label{eqn:duwdX3} - \frac{\partial (\vec{u} w_l)}{\partial X_3} = \mbox{3rd column of } P_l \\ -\label{eqn:dudX3} - \frac{\partial \vec{u}}{\partial X_3} = \frac{1}{w_l} \left( \frac{\partial (\vec{u} w_l)}{\partial X_3} - \vec{u}\frac{\partial w_l}{\partial X_3} \right)\end{aligned}\f] - -Note that (\[eqn:dudX3\]) is the quantity needed for the second bias -term. This is also the term to scale for different choices of small -offset in light space. If 0.01 units is the small offset, scale this -value by 0.01. - -## Percentage Closest Filtering {#sm_pcm} - -As widely known, shadow mapping can exhibit significant aliasing. When -this happens during texture mapping we apply filtering. We’d like to -apply a similar principle with shadow maps, but filtering depth values -is categorically the wrong thing to do. As described in  @cite RSC87, one -should instead filter depth test results. This is termed percentage -closest filtering. Ideally this would be a filtering technique much like -anisotropic texture filtering, but for simplicity and efficiency, Ogre’s -example code implements the bilinear analogue. - -# Variants {#sm_variants} - - -There are many shadow mapping variants. Enumerating (much less -describing) all of them would take us too far afield in this article. We -instead defer to the provided references and google for such coverage. -The many variants can, however, be broken up into three broad -categories: -1. Those that store additional information beyond a single -float, -2. Those that divide up shadow frusta into multiple frusta to be -handled separately, and -3. Those that propose less naive \f$P_l\f$ and -\f$M_l\f$ to use and thereby affect the sampling distribution. - -Algorithms in each category usually work quite independently and so many hybrid -approaches are easily conceivable. - -## Storing Additional Info {#sm_additional_info} - -One example of this is Deep Shadow Maps  @cite LV00. In this work, instead of -storing a single depth value and treating visibility as a binary value, -a transfer function is stored and visibility is continuous. This -algorithm is important in offline movie rendering, but also relevant to -the Variance Shadow Mapping algorithm elucidated by the game developer -community  @cite DL06. - -While variance shadow maps are motivated by statistical considerations, -it is perhaps more properly understood in the Deep Shadow Maps -framework. Analyzing it in terms of distributions is flawed for two -reasons: -1. The inequality considered is valid only for unimodal -distributions whereas depth values are often discontinuous in regions -that matter; -2. The inequality is treated as equality. The equations -are justified with a very specific example in which two planes are -viewed straight on. In practice there are very noticeable halo effects -around objects, which makes more heuristic tweaks necessary. - -Recasting this into the framework of deep shadow maps, we see that the -proposed equality is simply a particular functional approximation to the -transfer function. Variance shadow maps proposes a two-parameter family -of approximation functions whose parameters are linearly interpolated in -the usual way. This viewpoint allows for analysis and also suggests the -possibility of getting improvements via other approximating functional -forms. - -## Breaking up Shadow Frusta {#sm_breaking_frusta} - -Adaptive Shadow Maps @cite FFB01 are an example of this. It is still largely -considered too expensive for real-time rendering, but continued research -and growing GPU power may make some variant worthwhile. - -## Playing with Projection Matrices {#sect_planeopt} - -There are various heuristic approaches for choosing \f$P_l\f$ and \f$M_l\f$, but -here we will focus on one method, the Plane Optimal algorithm  @cite Chong04, -that provides a particular guarantee. For this algorithm, we specify a -plane of interest (e.g., ground plane, wall, table top) for which we -want perfect shadowing no matter the configuration of light and camera -in the scene (even dueling frusta). The algorithm will then compute -\f$P_l\f$ and \f$M_l\f$ so that the mapping between camera image and light image -is the identity when restricted to the plane. If the shadow map matches -the resolution of the screen, then each pixel gets exactly one shadow -sample. Shadows off the plane of interest have no guarantees. One -limitation of the method is shown in Figure \[fig:planeopt\]. Only -region I will be shadowed and self-shadowed properly, with points on the -plane being shadowed perfectly (alias-free). This makes the method -perhaps most useful for games where the view is top-down or isometric -(like RTS games). It is also useful for cases like dueling frusta (where -just about all other methods fail). - -![](images/optfrust.svg) Region I is defined as the set of all points along rays between the light and a point on the plane of interest in the camera’s view. Everything in region I is shadowed and self-shadowed properly. Objects in region II are not self-shadowed properly. - -# Theory and Analysis {#sm_theory} - -A full discussion of shadow map analysis is beyond the scope of this -article. For those interested, the references  @cite Chong06 and  @cite Chong04 -are good (in my extremely biased opinion). Note that as research papers, -they are quite concise. Unfortunately there don’t seem to more -step-by-step expositions available at this moment. - -There has been a lot of academic and industry research on improving -shadow maps. However, analyses presented on shadow maps often do not say -what people claim they say. These faulty conclusions usually come from -considering very special cases and assuming the general case is very -similar. For clarification, we explore some of these misconceptions -here. - -## (Non) Optimality of Logarithmic Shadow Maps {#sm_nonopt} - -We start with one *heuristic* that has gained quite a bit -of traction: the idea of using some logarithmic mapping between light -space and light image space instead of a projective transform. A number -of algorithms based on this idea have been proposed, and even some -hardware changes. Much of this work seems to be motivated by the -incorrect assumption that logarithmic mappings are optimal. - -The very special motivating case is this: The camera looks down the z -axis. Directional light illuminates the scene perpendicular to the z -axis. An angled piece of a plane is viewed by the camera. As the angled -piece of plane is pulled along the camera ray direction, using a -logarithmic shadow map gives us constant shadow quality on this -geometric piece. But unless we’re rendering translucent dust particles -along a camera ray, this analysis is irrelevant. If the dust particles -are not translucent, we only care about shadow determination on the -first one, not a whole line of them. If we are rendering continuous -surfaces (resp. curves), we care about the quality as one moves in the -tangent plane (resp. tangent) direction because this is the best linear -approximation to the surface (resp. curve), not the camera ray -direction. - -In fact, in the case of a chosen plane of interest for example, we know -we can get completely alias free shadow mapping using a projective -transform (section @ref sect_planeopt). Logarithmic shadow maps may be an -interesting heuristic to try out, but certainly not worth changing -hardware over in my opinion. If you’re going to change hardware, might -as well aim for true optimality. - -## Sampling Aliasing versus Depth Precision Aliasing {#sm_aliasing} - -Sometimes people tend to conflate these two sources of aliasing. They -note that after applying some sort of custom projective transform, the -depth values are warped as well. This problem can be completely overcome -via the depth replacement method prescribed in Trapezoidal Shadow Maps - @cite MT04. So this is a completely orthogonal issue. Depth precision can be -just as good as “normal†shadow maps, no matter the perspective warp -used to affect sampling. - -## Projective versus Perspective Aliasing {#sm_proj_aliasing} - -The terms perspective and projective aliasing appeared in the -Perspective Shadow Maps  @cite SD02 paper and has since been used extensively -by those who work on improving shadow heuristics. Often it is claimed -that methods ameliorate perspective aliasing while projective aliasing -is either unavoidable or must be addressed via completely separate -means. However, the distinction between the two is somewhat artificial. -Both result from not allocating enough shadow map samples to regions -that matter to the viewer. As the Plane Optimal algorithm demonstrates, -it is possible to completely remove projective aliasing (as well as -perspective aliasing) in certain scenes. In general, there should be one -combined measure of aliasing and algorithms must minimize this quantity. -See  @cite Chong06 for a unified notion of aliasing. - -# Implementation {#Implementation} - -Ogre provides a powerful framework that allows us to do a lot of shadow -map customization. In Ogre, we turn on custom shadow mapping through the -scene manager. It is recommended that this happen early -as it may affect how certain resources are loaded. - -```cpp -// Use Ogre's custom shadow mapping ability -Ogre::SceneManager *mSceneMgr = ...; -Ogre::MaterialManager *materialMgr = Ogre::MaterialManager::getSingletonPtr(); -mSceneMgr->setShadowTexturePixelFormat(PF_DEPTH16); -mSceneMgr->setShadowTechnique( SHADOWTYPE_TEXTURE_ADDITIVE ); -mSceneMgr->setShadowTextureCasterMaterial(materialMgr->getByName("PSSM/shadow_caster")); -mSceneMgr->setShadowTextureReceiverMaterial(materialMgr->getByName("Ogre/DepthShadowmap/Receiver/RockWall")); -mSceneMgr->setShadowTextureSelfShadow(true); -mSceneMgr->setShadowTextureSize(1024); -``` - -The setShadowTechnique call is all that is required for Ogre’s default -shadow mapping. In the code above, we have told Ogre to use a 16-bit depth texture. -This tends to be a very portable method (over graphics cards and APIs). The sample -uses 1024x1024 shadow maps. Self-shadowing is -turned on, but be warned that this will only work properly if -appropriate depth biasing is also used. The example code will manually -account for depth biasing via the method described above in section -@ref DepthBias. The shadow caster and shadow receiver materials are -defined in a material script. They tell Ogre which shaders to use when -rendering shadow casters into the shadow map and rendering shadow -receivers during shadow determination. - -We’ll present the GLSL code below. Note that the variable names in the shaders presented below are slightly -different from those presented earlier in this document. This is due in -part to the awkwardness of expressing subscripts in variable names and -also in part because \f$u_3\f$ is less evocative of depth than \f$z\f$, etc. -With minimal effort one can match the shader equations with those -presented earlier. The code is presented here mostly to demonstrate how -things fit together. - -## Caster -```cpp -uniform mat4 worldViewProjMatrix; -attribute vec4 vertex; - -void main() -{ - gl_Position = worldViewProjMatrix * vertex; -} -``` - -This is a pretty standard vertex shader. - -@include Samples/Media/materials/programs/GLSL/pssmCasterFp.glsl - -Just write out the depth values here. The bias and derivatives are handled by the @c depth_bias set in the pass. - -## Receiver - -@include Samples/Media/materials/programs/GLSL/DepthShadowmapReceiverVp.glsl - -This is a pretty standard vertex shader as well. - -@include Samples/Media/materials/programs/GLSL/DepthShadowmapReceiverFp.glsl - -Additionally this file implements percentage closest filtering. To use unfiltered -shadow mapping, comment out the PCF define. - -## Debugging Shadows -Since shadows are a difficult subject, so it is a good idea to have the Shadow Map -projected on a Mini-Screen where it is possible to see how the Depth Caster is performing. - -Material definition: `shadow_debug.material` -``` -material ShadowDebug -{ - technique - { - pass - { - lighting off - - texture_unit ShadowMap - { - tex_address_mode clamp - filtering none - content_type shadow - } - } - } -} -``` - -With only this material definition the [RTSS (Realtime Shader System)](@ref rtss) -takes care of generating the proper shader to project the Shadow Map on the Mini Screen. - -Source code to create a Rectangle on the screen and project the Shadow Map texture: -```cpp -// Create rectangle for the Mini-Screen and attach to node -Ogre::Rectangle2D* miniScreen = mSceneMgr->createScreenSpaceRect(true); -miniScreen->setCorners(.5, 1.0, 1.0, .5); -miniScreen->setBoundingBox(Ogre::AxisAlignedBox::BOX_INFINITE); -miniScreen->setMaterial(Ogre::MaterialManager::getSingletonPtr()->getByName("ShadowDebug")); - -Ogre::SceneNode* miniScreenNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); -miniScreenNode->attachObject(miniScreen); -``` - -## Improving Shadow Quality - -The default projection used when rendering shadow textures is a uniform frustum. -This is pretty straight forward but doesn't make the best use of the space in the shadow map -since texels closer to the camera will be larger, resulting in 'jaggies'. -There are several ways to distribute the texels in the shadow texture differently. -Ogre is provided with several alternative shadow camera setups: - - Ogre::FocusedShadowCameraSetup: Implements the uniform shadow mapping algorithm in focused mode. - - Ogre::LiSPSMShadowCameraSetup: Implements the Light Space Perspective Shadow Mapping Algorithm. - - Ogre::PSSMShadowCameraSetup: Parallel Split Shadow Map (PSSM) shadow camera setup. - - Ogre::PlaneOptimalShadowCameraSetup: Implements the plane optimal shadow camera algorithm. - -These Shadow Camera Setups can be enabled for the whole Scene with Ogre::SceneManager::setShadowCameraSetup -or per light with Ogre::Light::setCustomShadowCameraSetup - -The following shows how to activate Plane Optimal Shadow Mapping given -some pointer to a MovablePlane and a pointer to a light. -```cpp -Ogre::MovablePlane *movablePlane = new Ogre::MovablePlane( Ogre::Vector3::UNIT_Y, 0 ); -Ogre::Entity *movablePlaneEntity = mSceneMgr->createEntity( "movablePlane", "Floor.mesh" ); -Ogre::SceneNode *movablePlaneNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("MovablePlaneNode"); -movablePlaneNode->attachObject(movablePlaneEntity); -light->setCustomShadowCameraSetup(Ogre::PlaneOptimalShadowCameraSetup::create(movablePlane)); -``` - -Another example, using LiSPSM Camera Setup: -```cpp -mSceneMgr->setShadowCameraSetup(Ogre::LiSPSMShadowCameraSetup::create()); -``` - -For big scenes with directional lights one of the better performing Shadow Camera Setups is PSSM. -A PSSM shadow system uses multiple shadow maps per light and maps each texture into a region of space, -progressing away from the camera. As such it is most appropriate for directional light setups. -A more in depth explanation can be found in the wiki: [Parallel Split Shadow Mapping](https://wiki.ogre3d.org/Parallel+Split+Shadow+Mapping) - -```cpp -// General scene setup -mSceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_TEXTURE_ADDITIVE_INTEGRATED); -mSceneMgr->setShadowTextureCasterMaterial(Ogre::MaterialManager::getSingletonPtr()->getByName("PSSMCaster")); -mSceneMgr->setShadowTextureSelfShadow(true); -mSceneMgr->setShadowFarDistance(3000); -// 3 textures per directional light (PSSM) -mSceneMgr->setShadowTextureCountPerLightType(Ogre::Light::LT_DIRECTIONAL, 3); -mSceneMgr->setShadowTextureCount(3); -mSceneMgr->setShadowTextureConfig(0, 2048, 2048, Ogre::PF_DEPTH16); -mSceneMgr->setShadowTextureConfig(1, 1024, 1024, Ogre::PF_DEPTH16); -mSceneMgr->setShadowTextureConfig(2, 512, 512, Ogre::PF_DEPTH16); - -Ogre::PSSMShadowCameraSetup* pssmSetup = new Ogre::PSSMShadowCameraSetup(); -pssmSetup->setSplitPadding(1); -pssmSetup->calculateSplitPoints(3, 1, mSceneMgr->getShadowFarDistance()); -pssmSetup->setOptimalAdjustFactor(0, 2); -pssmSetup->setOptimalAdjustFactor(1, 1); -pssmSetup->setOptimalAdjustFactor(2, 0.5); -mSceneMgr->setShadowCameraSetup(Ogre::ShadowCameraSetupPtr(pssmSetup)); -``` - -The Shadow Caster Vertex and Fragment programs are the same as the regular shadow mapping techniques. - -But some changes have to be made to the shaders of the Shadow Receiver as well as the program definition, because now we are sending three shadow map splits (in this example). - -Material definition: -``` -sampler DepthSampler -{ - filtering none - tex_address_mode clamp - tex_border_colour 1.0 1.0 1.0 1.0 -} - -material PSSMShadowReceiver -{ - technique default - { - pass - { - vertex_program_ref PSSMShadowReceiverVP {} - fragment_program_ref PSSMShadowReceiverFP {} - - texture_unit ShadowMap0 - { - content_type shadow - sampler_ref DepthSampler - } - - texture_unit ShadowMap1 - { - content_type shadow - sampler_ref DepthSampler - } - - texture_unit ShadowMap2 - { - content_type shadow - sampler_ref DepthSampler - } - } - } -} -``` - -Program definition: -``` -vertex_program PSSMShadowReceiverVP glsl -{ - source PSSMShadowReceiver.vert - - default_params - { - param_named_auto world world_matrix - param_named_auto worldIT inverse_transpose_world_matrix - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto lightPosition light_position 0 - param_named_auto lightColour light_diffuse_colour 0 - - param_named_auto texViewProj0 texture_viewproj_matrix 0 - param_named_auto texViewProj1 texture_viewproj_matrix 1 - param_named_auto texViewProj2 texture_viewproj_matrix 2 - } -} - -fragment_program PSSMShadowReceiverFP glsl -{ - source PSSMShadowReceiver.frag - - default_params - { - param_named shadowMap0 int 0 - param_named shadowMap1 int 1 - param_named shadowMap2 int 2 - - param_named pssmSplitPoints float4 0 0 0 0 - } -} -``` - -The vertex shader now includes three texture projection matrixes -```glsl -#version 330 core - -layout (location = 0) in vec4 vertex; -layout (location = 2) in vec3 normal; - -uniform mat4 world; -uniform mat4 worldIT; -uniform mat4 worldViewProj; -uniform vec4 lightPosition; -uniform vec4 lightColour; - -uniform mat4 texViewProj0; -uniform mat4 texViewProj1; -uniform mat4 texViewProj2; - -out vec4 outColor; - -out vec4 oUv0; -out vec4 oUv1; -out vec4 oUv2; - -out float depth; - -void main() -{ - gl_Position = worldViewProj * vertex; - depth = gl_Position.z; - - vec4 worldPos = world * vertex; - - vec3 worldNorm = (worldIT * vec4(normal, 1.0)).xyz; - - // calculate lighting (simple vertex lighting) - vec3 lightDir = normalize(lightPosition.xyz - (worldPos.xyz * lightPosition.w)); - - outColor = lightColour * max(dot(lightDir, worldNorm), 0.0); - - // calculate shadow map coords - oUv0 = texViewProj0 * worldPos; - oUv1 = texViewProj1 * worldPos; - oUv2 = texViewProj2 * worldPos; -} -``` - -And the fragment shader has to be accommodated to select the correct Shadow Map according to the camera distance -```glsl -#version 330 core - -in vec4 oUv0; -in vec4 oUv1; -in vec4 oUv2; - -in vec4 outColor; - -in float depth; - -uniform sampler2D shadowMap0; -uniform sampler2D shadowMap1; -uniform sampler2D shadowMap2; - -uniform vec4 pssmSplitPoints; - -void shadowFilter( sampler2D shadowMap, vec4 oUv, vec3 splitColour ) -{ - // Perform perspective divide - vec4 shadowUV = oUv; - shadowUV = shadowUV / shadowUV.w; - - // Transform [-1, 1] to [0, 1] range - shadowUV.z = shadowUV.z * 0.5 + 0.5; - - // Get closest depth value from light's perspective (using [0,1] range fragPosLight as coords) - float centerdepth = texture2D(shadowMap, shadowUV.xy).x; - - // Check whether current frag pos is in shadow - gl_FragColor = (finalCenterDepth > shadowUV.z) ? vec4(outColor.xyz * splitColour, 1.0) : vec4(0.0, 0.0, 0.0, 1.0); -} - -void main() -{ - if( depth <= pssmSplitPoints.y ) - { - shadowFilter( shadowMap0, oUv0, vec3( 1.0, 0.0, 0.0 ) ); - } - else if( depth <= pssmSplitPoints.z ) - { - shadowFilter( shadowMap1, oUv1, vec3( 0.0, 1.0, 0.0 ) ); - } - else if( depth <= pssmSplitPoints.w ) - { - shadowFilter( shadowMap2, oUv2, vec3( 0.0, 0.0, 1.0 ) ); - } - else - { - discard; - } -} -``` diff --git a/Docs/src/particle-scripts.md b/Docs/src/particle-scripts.md deleted file mode 100644 index f29c63eb5ba..00000000000 --- a/Docs/src/particle-scripts.md +++ /dev/null @@ -1,846 +0,0 @@ -# Particle Scripts {#Particle-Scripts} - -Particle scripts allow you to define particle systems to be instantiated in your code without having to hard-code the settings themselves in your source code, allowing a very quick turnaround on any changes you make. Particle systems which are defined in scripts are used as templates, and multiple actual systems can be created from them at runtime. - -@tableofcontents - -Once scripts have been parsed, your code is free to instantiate systems based on them using the Ogre::SceneManager::createParticleSystem() method which can take both a name for the new system, and the name of the template to base it on (this template name is in the script). - -@snippet Samples/Media/particle/Examples.particle manual_sample - -A system can have top-level attributes set using the scripting commands available, such as ’quota’ to set the maximum number of particles allowed in the system. Emitters (which create particles) and affectors (which modify particles) are added as nested definitions within the script. The parameters available in the emitter and affector sections are entirely dependent on the type of emitter / affector. - -For a detailed description of the core particle system attributes, see the list below: - -## Particle System Attributes {#Particle-System-Attributes} - -This section describes to attributes which you can set on every particle system using scripts. All attributes have default values so all settings are optional in your script. - -- [quota](#quota) -- [material](#particle_005fmaterial) -- [particle\_width](#particle_005fwidth) -- [particle\_height](#particle_005fheight) -- [cull\_each](#cull_005feach) -- [renderer](#particle_005frenderer) -- [sorted](#particle_005fsorted) -- [local\_space](#particle_005flocalspace) -- [iteration\_interval](#iteration_005finterval) -- [nonvisible\_update\_timeout](#nonvisible_005fupdate_005ftimeout) - -@par Billboard Renderer Attributes - -- [billboard\_type](#billboard_005ftype) -- [billboard\_origin](#billboard_005forigin) -- [billboard\_rotation\_type](#billboard_005frotation_005ftype) -- [common\_direction](#common_005fdirection) -- [common\_up\_vector](#common_005fup_005fvector) -- [point\_rendering](#particle_005fpoint_005frendering) -- [accurate\_facing](#particle_005faccurate_005ffacing) - -@see @ref Particle-Emitters -@see @ref Particle-Affectors - - - - -### quota - -Sets the maximum number of particles this system is allowed to contain at one time. When this limit is exhausted, the emitters will not be allowed to emit any more particles until some destroyed (e.g. through their time\_to\_live running out). Note that you will almost always want to change this, since it defaults to a very low value (particle pools are only ever increased in size, never decreased). - -format: quota <max\_particles>
example: quota 10000
default: 10
- - - -### material - -Sets the name of the material which all particles in this system will use. All particles in a system use the same material, although each particle can tint this material through the use of it’s colour property. - -format: material <material\_name>
example: material Examples/Flare
default: none (blank material)
- - - -### particle\_width - -Sets the width of particles in world coordinates. Note that this property is absolute when billboard\_type (see below) is set to ’point’ or ’perpendicular\_self’, but is scaled by the length of the direction vector when billboard\_type is ’oriented\_common’, ’oriented\_self’ or ’perpendicular\_common’.
- -format: particle\_width <width>
example: particle\_width 20
default: 100
- - - -### particle\_height - -Sets the height of particles in world coordinates. Note that this property is absolute when billboard\_type (see below) is set to ’point’ or ’perpendicular\_self’, but is scaled by the length of the direction vector when billboard\_type is ’oriented\_common’, ’oriented\_self’ or ’perpendicular\_common’.
- -format: particle\_height <height>
example: particle\_height 20
default: 100
- - - -### cull\_each - -All particle systems are culled by the bounding box which contains all the particles in the system. This is normally sufficient for fairly locally constrained particle systems where most particles are either visible or not visible together. However, for those that spread particles over a wider area (e.g. a rain system), you may want to actually cull each particle individually to save on time, since it is far more likely that only a subset of the particles will be visible. You do this by setting the cull\_each parameter to true. - -format: cull\_each <true|false>
example: cull\_each true
default: false
- - - -### renderer - -Particle systems do not render themselves, they do it through ParticleRenderer classes. Those classes are registered with a manager in order to provide particle systems with a particular ’look’. OGRE comes configured with a default billboard-based renderer, but more can be added through plugins. Particle renders are registered with a unique name, and you can use that name in this attribute to determine the renderer to use. The default is ’billboard’. - -Particle renderers can have attributes, which can be passed by setting them on the root particle system. - -format: renderer <renderer\_name>
default: billboard
- - - -### sorted - -By default, particles are not sorted. By setting this attribute to ’true’, the particles will be sorted with respect to the camera, furthest first. This can make certain rendering effects look better at a small sorting expense. - -format: sorted <true|false>
default: false
- - - -### local\_space - -By default, particles are emitted into world space, such that if you transform the node to which the system is attached, it will not affect the particles (only the emitters). This tends to give the normal expected behaviour, which is to model how real world particles travel independently from the objects they are emitted from. However, to create some effects you may want the particles to remain attached to the local space the emitter is in and to follow them directly. This option allows you to do that. - -format: local\_space <true|false>
default: false
- - - -### iteration\_interval - -Usually particle systems are updated based on the frame rate; however this can give variable results with more extreme frame rate ranges, particularly at lower frame rates. You can use this option to make the update frequency a fixed interval, whereby at lower frame rates, the particle update will be repeated at the fixed interval until the frame time is used up. A value of 0 means the default frame time iteration. - -format: iteration\_interval <secs>
example: iteration\_interval 0.01
default: iteration\_interval 0
- - - -### nonvisible\_update\_timeout - -Sets when the particle system should stop updating after it hasn’t been visible for a while. By default, visible particle systems update all the time, even when not in view. This means that they are guaranteed to be consistent when they do enter view. However, this comes at a cost, updating particle systems can be expensive, especially if they are perpetual. This option lets you set a ’timeout’ on the particle system, so that if it isn’t visible for this amount of time, it will stop updating until it is next visible. A value of 0 disables the timeout and always updates. - -format: nonvisible\_update\_timeout <secs>
example: nonvisible\_update\_timeout 10
default: nonvisible\_update\_timeout 0
- -## Billboard Renderer Attributes {#Billboard-Renderer-Attributes} - -These are actually attributes of the @c billboard particle renderer (the default), but can be passed to a particle renderer by declaring them directly within the system declaration. Particles using the default renderer are rendered using billboards, which are rectangles formed by 2 triangles which rotate to face the given direction. - - - -### billboard\_type - -There is more than 1 way to orient a billboard. The classic approach is for the billboard to directly face the camera: this is the default behaviour. However this arrangement only looks good for particles which are representing something vaguely spherical like a light flare. For more linear effects like laser fire, you actually want the particle to have an orientation of it’s own. - -format: billboard\_type <point|oriented\_common|oriented\_self|perpendicular\_common|perpendicular\_self>
example: billboard\_type oriented\_self
default: point
- -The options for this parameter are: - -
-
point
- -The default arrangement, this approximates spherical particles and the billboards always fully face the camera. - -
oriented\_common
- -Particles are oriented around a common, typically fixed direction vector (see [common\_direction](#common_005fdirection)), which acts as their local Y axis. The billboard rotates only around this axis, giving the particle some sense of direction. Good for rainstorms, starfields etc where the particles will traveling in one direction - this is slightly faster than oriented\_self (see below). - -
oriented\_self
- -Particles are oriented around their own direction vector, which acts as their local Y axis. As the particle changes direction, so the billboard reorients itself to face this way. Good for laser fire, fireworks and other ’streaky’ particles that should look like they are traveling in their own direction. - -
perpendicular\_common
- -Particles are perpendicular to a common, typically fixed direction vector (see [common\_direction](#common_005fdirection)), which acts as their local Z axis, and their local Y axis coplanar with common direction and the common up vector (see [common\_up\_vector](#common_005fup_005fvector)). The billboard never rotates to face the camera, you might use double-side material to ensure particles never culled by back-facing. Good for aureolas, rings etc where the particles will perpendicular to the ground - this is slightly faster than perpendicular\_self (see below). - -
perpendicular\_self
- -Particles are perpendicular to their own direction vector, which acts as their local Z axis, and their local Y axis coplanar with their own direction vector and the common up vector (see [common\_up\_vector](#common_005fup_005fvector)). The billboard never rotates to face the camera, you might use double-side material to ensure particles never culled by back-facing. Good for rings stack etc where the particles will perpendicular to their traveling direction. - -
- -### billboard\_origin - -@copydetails Ogre::BillboardOrigin - -format: billboard\_origin <top\_left|top\_center|top\_right|center\_left|center|center\_right|bottom\_left|bottom\_center|bottom\_right>
example: billboard\_origin top\_right
default: center
- - - -### billboard\_rotation\_type - -@copydetails Ogre::BillboardRotationType - -format: billboard\_rotation\_type <vertex|texcoord>
example: billboard\_rotation\_type vertex
default: texcoord
- -The options for this parameter are: - -
-
vertex
- -Billboard particles will rotate the vertices around their facing direction to according with particle rotation. Rotate vertices guarantee texture corners exactly match billboard corners, thus has advantage mentioned above, but should take more time to generate the vertices. - -
texcoord
- -Billboard particles will rotate the texture coordinates to according with particle rotation. Rotate texture coordinates is faster than rotate vertices, but has some disadvantage mentioned above. - -
- - - -### common\_direction - -Only required if [billboard\_type](#billboard_005ftype) is set to oriented\_common or perpendicular\_common, this vector is the common direction vector used to orient all particles in the system. - -format: common\_direction <x> <y> <z>
example: common\_direction 0 -1 0
default: 0 0 1
- - - -### common\_up\_vector - -Only required if [billboard\_type](#billboard_005ftype) is set to perpendicular\_self or perpendicular\_common, this vector is the common up vector used to orient all particles in the system. - -format: common\_up\_vector <x> <y> <z>
example: common\_up\_vector 0 1 0
default: 0 1 0
- - - -### point\_rendering - -This sets whether or not the BillboardSet will use point rendering rather than manually generated quads. - -@copydetails Ogre::BillboardSet::setPointRenderingEnabled - - - -### accurate\_facing - -This sets whether or not the BillboardSet will use a slower but more accurate calculation for facing the billboard to the camera. By default it uses the camera direction, which is faster but means the billboards don’t stay in the same orientation as you rotate the camera. The ’accurate\_facing on’ option makes the calculation based on a vector from each billboard to the camera, which means the orientation is constant even whilst the camera rotates. - -format: accurate\_facing on|off
default: accurate\_facing off
- -### texture_sheet_size - -format: texture_sheet_size <stacks> <slices> - -@copydetails Ogre::BillboardSet::setTextureStacksAndSlices - -# Particle Emitters {#Particle-Emitters} - -Particle emitters are classified by ’type’ e.g. ’Point’ emitters emit from a single point whilst ’Box’ emitters emit randomly from an area. New emitters can be added to Ogre by creating plugins. You add an emitter to a system by nesting another section within it, headed with the keyword ’emitter’ followed by the name of the type of emitter (case sensitive). Ogre currently supports ’Point’, ’Box’, ’Cylinder’, ’Ellipsoid’, ’HollowEllipsoid’ and ’Ring’ emitters. - -@see @ref Particle-Affectors - -## Emitting Emitters {#Emitting-Emitters} - -It is possible to ’emit emitters’ - that is, have new emitters spawned based on the position of particles,, for example to product ’firework’ style effects. - -This is controlled via the following directives: - -
-
emit\_emitter\_quota
- -This parameter is a system-level parameter telling the system how many emitted emitters may be in use at any one time. This is just to allow for the space allocation process. - -
name
- -This parameter is an emitter-level parameter, giving a name to an emitter. This can then be referred to in another emitter as the new emitter type to spawn. - -
emit\_emitter
- -This is an emitter-level parameter, and if specified, it means that the particles spawned by this emitter, are themselves emitters of the named type. - -
- - - -## Common Emitter Attributes - -This section describes the common attributes of all particle emitters. Specific emitter types may also support their own extra attributes. - -- [angle](#angle) -- [colour](#colour) -- [colour\_range\_start](#colour_005frange_005fstart) -- [colour\_range\_end](#colour_005frange_005fend) -- [direction](#direction) -- [direction\_position\_reference](#direction_005fposition_005freference) -- [emission\_rate](#emission_005frate) -- [position](#position) -- [velocity](#velocity) -- [velocity\_min](#velocity_005fmin) -- [velocity\_max](#velocity_005fmax) -- [time\_to\_live](#time_005fto_005flive) -- [time\_to\_live\_min](#time_005fto_005flive_005fmin) -- [time\_to\_live\_max](#time_005fto_005flive_005fmax) -- [duration](#duration) -- [duration\_min](#duration_005fmin) -- [duration\_max](#duration_005fmax) -- [repeat\_delay](#repeat_005fdelay) -- [repeat\_delay\_min](#repeat_005fdelay_005fmin) -- [repeat\_delay\_max](#repeat_005fdelay_005fmax) - - - -## angle - -Sets the maximum angle (in degrees) which emitted particles may deviate from the direction of the emitter (see direction). Setting this to 10 allows particles to deviate up to 10 degrees in any direction away from the emitter’s direction. A value of 180 means emit in any direction, whilst 0 means emit always exactly in the direction of the emitter. - -format: angle <degrees>
example: angle 30
default: 0
- - - -## colour - -Sets a static colour for all particle emitted. Also see the colour\_range\_start and colour\_range\_end attributes for setting a range of colours. The format of the colour parameter is "r g b a", where each component is a value from 0 to 1, and the alpha value is optional (assumes 1 if not specified). - -format: colour <r> <g> <b> \[<a>\]
example: colour 1 0 0 1
default: 1 1 1 1
- - - -## colour\_range\_start & colour\_range\_end - -As the ’colour’ attribute, except these 2 attributes must be specified together, and indicate the range of colours available to emitted particles. The actual colour will be randomly chosen between these 2 values. - -format: as colour
example (generates random colours between red and blue):
    colour\_range\_start 1 0 0
    colour\_range\_end 0 0 1
default: both 1 1 1 1
- - - -## direction - -Sets the direction of the emitter. This is relative to the SceneNode which the particle system is attached to, meaning that as with other movable objects changing the orientation of the node will also move the emitter. - -format: direction <x> <y> <z>
example: direction 0 1 0
default: 1 0 0
- - - -## direction\_position\_reference - -Sets the position reference of the emitter. This supersedes direction when present. The last parameter must be 1 to enable it, 0 to disable. You may still want to set the direction to setup orientation of the emitter’s dimensions. When present, particles direction is calculated at the time of emission by doing (particlePosition - referencePosition); therefore particles will travel in a particular direction or in every direction depending on where the particles are originated, and the location of the reference position. Note angle still works to apply some randomness after the direction vector is generated. This parameter is specially useful to create explosions and implosions (when velocity is negative) best paired with HollowEllipsoid and Ring emitters. This is relative to the SceneNode which the particle system is attached to, meaning that as with other movable objects changing the orientation of the node will also move the emitter. - -format: direction\_position\_reference <x> <y> <z> <enable>
example: direction\_position\_reference 0 -10 0 1
default: direction\_position\_reference 0 0 0 0
- - - -## emission\_rate - -Sets how many particles per second should be emitted. The specific emitter does not have to emit these in a continuous manner - this is a relative parameter and the emitter may choose to emit all of the second’s worth of particles every half-second for example, the behaviour depends on the emitter. The emission rate will also be limited by the particle system’s ’quota’ setting. - -format: emission\_rate <particles\_per\_second>
example: emission\_rate 50
default: 10
- - - -## position - -Sets the position of the emitter relative to the SceneNode the particle system is attached to. - -format: position <x> <y> <z>
example: position 10 0 40
default: 0 0 0
- - - -## velocity - -Sets a constant velocity for all particles at emission time. See also the velocity\_min and velocity\_max attributes which allow you to set a range of velocities instead of a fixed one. - -format: velocity <world\_units\_per\_second>
example: velocity 100
default: 1
- - - -## velocity\_min & velocity\_max - -As ’velocity’ except these attributes set a velocity range and each particle is emitted with a random velocity within this range. - -format: as velocity
example:
    velocity\_min 50
    velocity\_max 100
default: both 1
- - - -## time\_to\_live - -Sets the number of seconds each particle will ’live’ for before being destroyed. NB it is possible for particle affectors to alter this in flight, but this is the value given to particles on emission. See also the time\_to\_live\_min and time\_to\_live\_max attributes which let you set a lifetime range instead of a fixed one. - -format: time\_to\_live <seconds>
example: time\_to\_live 10
default: 5
- - - -## time\_to\_live\_min & time\_to\_live\_max - -As time\_to\_live, except this sets a range of lifetimes and each particle gets a random value in-between on emission. - -format: as time\_to\_live
example:
    time\_to\_live\_min 2
    time\_to\_live\_max 5
default: both 5

- - - -## duration - -Sets the number of seconds the emitter is active. The emitter can be started again, see [repeat\_delay](#repeat_005fdelay). -See also the duration\_min and duration\_max attributes which let you set a duration range instead of a fixed one. - -format: duration <seconds>
example:
    duration 2.5
default: 0

- -@note A value of 0 means infinite duration. A value < 0 means "burst" where @c emission_rate of particles are emitted once in the next frame. - - - -## duration\_min & duration\_max - -As duration, except these attributes set a variable time range between the min and max values each time the emitter is started. - -format: as duration
example:
    duration\_min 2
    duration\_max 5
default: both 0

- - - -## repeat\_delay - -Sets the number of seconds to wait before the emission is repeated when stopped by a limited [duration](#duration). See also the repeat\_delay\_min and repeat\_delay\_max attributes which allow you to set a range of repeat\_delays instead of a fixed one. - -format: repeat\_delay <seconds>
example:
    repeat\_delay 2.5
default: 0

- - - -## repeat\_delay\_min & repeat\_delay\_max - -As repeat\_delay, except this sets a range of repeat delays and each time the emitter is started it gets a random value in-between. - -format: as repeat\_delay
example:
    repeat\_delay 2
    repeat\_delay 5
default: both 0

- -# Standard Particle Emitters {#Standard-Particle-Emitters} - -Ogre comes preconfigured with a few particle emitters. New ones can be added by creating plugins: see the Plugin\_ParticleFX project as an example of how you would do this (this is where these emitters are implemented). - -- [Point Emitter](#Point-Emitter) -- [Box Emitter](#Box-Emitter) -- [Cylinder Emitter](#Cylinder-Emitter) -- [Ellipsoid Emitter](#Ellipsoid-Emitter) -- [Hollow Ellipsoid Emitter](#Hollow-Ellipsoid-Emitter) -- [Ring Emitter](#Ring-Emitter) - -## Point Emitter {#Point-Emitter} - -@copybrief Ogre::PointEmitter - -This emitter has no additional attributes over an above the standard emitter attributes. - -To create a point emitter, include a section like this within your particle system script: - -```cpp - -emitter Point -{ - // Settings go here -} -``` - -## Box Emitter {#Box-Emitter} - -@copybrief Ogre::BoxEmitter - -It’s extra attributes are: - -
-
width
- -Sets the width of the box (this is the size of the box along it’s local X axis, which is dependent on the ’direction’ attribute which forms the box’s local Z).
format: width <units>
example: width 250
default: 100
- -
height
- -Sets the height of the box (this is the size of the box along it’s local Y axis, which is dependent on the ’direction’ attribute which forms the box’s local Z).
format: height <units>
example: height 250
default: 100
- -
depth
- -Sets the depth of the box (this is the size of the box along it’s local Z axis, which is the same as the ’direction’ attribute).
format: depth <units>
example: depth 250
default: 100
- -

- -To create a box emitter, include a section like this within your particle system script: - -```cpp -emitter Box -{ - // Settings go here -} -``` - -## Cylinder Emitter {#Cylinder-Emitter} - -@copybrief Ogre::CylinderEmitter - -This emitter has exactly the same parameters as the [Box Emitter](#Box-Emitter) so there are no additional parameters to consider here - the width and height determine the shape of the cylinder along it’s axis (if they are different it is an ellipsoid cylinder), the depth determines the length of the cylinder. - -## Ellipsoid Emitter {#Ellipsoid-Emitter} - -This emitter emits particles from within an ellipsoid shaped area, i.e. a sphere or squashed-sphere area. The parameters are again identical to the [Box Emitter](#Box-Emitter), except that the dimensions describe the widest points along each of the axes. - -## Hollow Ellipsoid Emitter {#Hollow-Ellipsoid-Emitter} - -This emitter is just like [Ellipsoid Emitter](#Ellipsoid-Emitter) except that there is a hollow area in the center of the ellipsoid from which no particles are emitted. - -Therefore it has 3 extra parameters in order to define this area: - -
-
inner\_width
- -The width of the inner area which does not emit any particles. - -
inner\_height
- -The height of the inner area which does not emit any particles. - -
inner\_depth
- -The depth of the inner area which does not emit any particles. - -
- -## Ring Emitter {#Ring-Emitter} - -This emitter emits particles from a ring-shaped area, i.e. a little like [Hollow Ellipsoid Emitter](#Hollow-Ellipsoid-Emitter) except only in 2 dimensions. - -
-
inner\_width
- -The width of the inner area which does not emit any particles. - -
inner\_height
- -The height of the inner area which does not emit any particles. - -
- -# Particle Affectors {#Particle-Affectors} - -Particle affectors modify particles over their lifetime. They are classified by ’type’ e.g. ’LinearForce’ affectors apply a force to all particles, whilst ’ColourFader’ affectors alter the colour of particles in flight. New affectors can be added to Ogre by creating plugins. You add an affector to a system by nesting another section within it, headed with the keyword ’affector’ followed by the name of the type of affector (case sensitive). - -Particle affectors actually have no universal attributes; they are all specific to the type of affector. - -@see @ref Particle-Emitters - -# Standard Particle Affectors {#Standard-Particle-Affectors} - -Ogre comes preconfigured with a few particle affectors. New ones can be added by creating plugins: see the Plugin\_ParticleFX project as an example of how you would do this (this is where these affectors are implemented). - -- [Linear Force Affector](#Linear-Force-Affector) -- [ColourFader Affector](#ColourFader-Affector) -- [ColourFader2 Affector](#ColourFader2-Affector) -- [Scaler Affector](#Scaler-Affector) -- [Rotator Affector](#Rotator-Affector) -- [ColourInterpolator Affector](#ColourInterpolator-Affector) -- [ColourImage Affector](#ColourImage-Affector) -- [DeflectorPlane Affector](#DeflectorPlane-Affector) -- [DirectionRandomiser Affector](#DirectionRandomiser-Affector) -- [TextureAnimator Affector](#TextureAnimator-Affector) - -## Linear Force Affector {#Linear-Force-Affector} - -@copybrief Ogre::LinearForceAffector - -It’s extra attributes are: - -
-
force\_vector
- -Sets the vector for the force to be applied to every particle. The magnitude of this vector determines how strong the force is.
    format: force\_vector <x> <y> <z>
    example: force\_vector 50 0 -50
    default: 0 -100 0 (a fair gravity effect)
- -
force\_application
- -Sets the way in which the force vector is applied to particle momentum.
    format: force\_application <add|average>
    example: force\_application average
    default: add
The options are: - -
-
average
- -The resulting momentum is the average of the force vector and the particle’s current motion. Is self-stabilising but the speed at which the particle changes direction is non-linear. - -
add
- -The resulting momentum is the particle’s current motion plus the force vector. This is traditional force acceleration but can potentially result in unlimited velocity. - -

- -To create a linear force affector, include a section like this within your particle system script: - -```cpp -affector LinearForce -{ - // Settings go here -} -``` - -## ColourFader Affector {#ColourFader-Affector} - -@copybrief Ogre::ColourFaderAffector - -It’s extra attributes are: - -
-
red
- -Sets the adjustment to be made to the red component of the particle colour per second.
    format: red <delta\_value>
    example: red -0.1
    default: 0
- -
green
- -Sets the adjustment to be made to the green component of the particle colour per second.
    format: green <delta\_value>
    example: green -0.1
    default: 0
- -
blue
- -Sets the adjustment to be made to the blue component of the particle colour per second.
    format: blue <delta\_value>
    example: blue -0.1
    default: 0
- -
alpha
- -Sets the adjustment to be made to the alpha component of the particle colour per second.
    format: alpha <delta\_value>
example: alpha -0.1
default: 0
- -
- -To create a colour fader affector, include a section like this within your particle system script: - -```cpp -affector ColourFader -{ - // Settings go here -} -``` - -## ColourFader2 Affector {#ColourFader2-Affector} - -This affector is similar to the [ColourFader Affector](#ColourFader-Affector), except it introduces two states of colour changes as opposed to just one. The second colour change state is activated once a specified amount of time remains in the particles life. - -
-
red1
- -Sets the adjustment to be made to the red component of the particle colour per second for the first state.
    format: red <delta\_value>
    example: red -0.1
    default: 0
- -
green1
- -Sets the adjustment to be made to the green component of the particle colour per second for the first state.
    format: green <delta\_value>
    example: green -0.1
    default: 0
- -
blue1
- -Sets the adjustment to be made to the blue component of the particle colour per second for the first state.
    format: blue <delta\_value>
    example: blue -0.1
    default: 0
- -
alpha1
- -Sets the adjustment to be made to the alpha component of the particle colour per second for the first state.
    format: alpha <delta\_value>
example: alpha -0.1
default: 0
- -
red2
- -Sets the adjustment to be made to the red component of the particle colour per second for the second state.
    format: red <delta\_value>
    example: red -0.1
    default: 0
- -
green2
- -Sets the adjustment to be made to the green component of the particle colour per second for the second state.
    format: green <delta\_value>
    example: green -0.1
    default: 0
- -
blue2
- -Sets the adjustment to be made to the blue component of the particle colour per second for the second state.
    format: blue <delta\_value>
    example: blue -0.1
    default: 0
- -
alpha2
- -Sets the adjustment to be made to the alpha component of the particle colour per second for the second state.
    format: alpha <delta\_value>
example: alpha -0.1
default: 0
- -
state\_change
- -When a particle has this much time left to live, it will switch to state 2.
    format: state\_change <seconds>
example: state\_change 2
default: 1
- -
- -To create a ColourFader2 affector, include a section like this within your particle system script: - -```cpp -affector ColourFader2 -{ - // Settings go here -} -``` - -## Scaler Affector {#Scaler-Affector} - -@copybrief Ogre::ScaleAffector - -It’s extra attributes are: - - -@par rate -The amount by which to scale the particles in both the x and y direction per second. - -@par scale_range -The scale factor range to be applied to emitted particles. -@par -example: scale_range 0.5 1.5
-default: 1.0 1.0
- -To create a scale affector, include a section like this within your particle system script: - -```cpp -affector Scaler -{ - // Settings go here -} -``` - -## Rotator Affector {#Rotator-Affector} - -@copybrief Ogre::RotationAffector - -It’s extra attributes are: - -
-
rotation\_speed\_range\_start
- -The start of a range of rotation speeds to be assigned to emitted particles.
    format: rotation\_speed\_range\_start <degrees\_per\_second>
example: rotation\_speed\_range\_start 90
default: 0
- -
rotation\_speed\_range\_end
- -The end of a range of rotation speeds to be assigned to emitted particles.
    format: rotation\_speed\_range\_end <degrees\_per\_second>
example: rotation\_speed\_range\_end 180
default: 0
- -
rotation\_range\_start
- -The start of a range of rotation angles to be assigned to emitted particles.
    format: rotation\_range\_start <degrees>
example: rotation\_range\_start 0
default: 0
- -
rotation\_range\_end
- -The end of a range of rotation angles to be assigned to emitted particles.
    format: rotation\_range\_end <degrees>
example: rotation\_range\_end 360
default: 0
- -
- -To create a rotate affector, include a section like this within your particle system script: - -```cpp -affector Rotator -{ - // Settings go here -} -``` - -## ColourInterpolator Affector {#ColourInterpolator-Affector} - -Similar to the ColourFader and ColourFader2 Affectors, this affector modifies the colour of particles in flight, except it has a variable number of defined stages. It swaps the particle colour for several stages in the life of a particle and interpolates between them. - -It’s extra attributes are: - -
-
time0
- -The point in time of stage 0.
    format: time0 <0-1 based on lifetime>
example: time0 0
default: 1
- -
colour0
- -The colour at stage 0.
    format: colour0 <r> <g> <b> \[<a>\]
example: colour0 1 0 0 1
default: 0.5 0.5 0.5 0.0
- -
time1
- -The point in time of stage 1.
    format: time1 <0-1 based on lifetime>
example: time1 0.5
default: 1
- -
colour1
- -The colour at stage 1.
    format: colour1 <r> <g> <b> \[<a>\]
example: colour1 0 1 0 1
default: 0.5 0.5 0.5 0.0
- -
time2
- -The point in time of stage 2.
    format: time2 <0-1 based on lifetime>
example: time2 1
default: 1
- -
colour2
- -The colour at stage 2.
    format: colour2 <r> <g> <b> \[<a>\]
example: colour2 0 0 1 1
default: 0.5 0.5 0.5 0.0
- -
- -@note The number of stages is variable. The maximal number of stages is 6; where time5 and colour5 are the last possible parameters. - -To create a colour interpolation affector, include a section like this within your particle system script: - -```cpp -affector ColourInterpolator -{ - // Settings go here -} -``` - -## ColourImage Affector {#ColourImage-Affector} - -This is another affector that modifies the colour of particles in flight, but instead of programmatically defining colours, the colours are taken from a specified image file. The range of colour values begins from the left side of the image and move to the right over the lifetime of the particle, therefore only the horizontal dimension of the image is used. - -Its extra attributes are: - -
-
image
- -The start of a range of rotation speed to be assigned to emitted particles.
    format: image <image\_name>
example: image rainbow.png
default: none
- -
- -To create a ColourImage affector, include a section like this within your particle system script: - -```cpp -affector ColourImage -{ - // Settings go here -} -``` - -## DeflectorPlane Affector {#DeflectorPlane-Affector} - -@copybrief Ogre::DeflectorPlaneAffector - -The attributes are: - -
-
plane\_point
- -A point on the deflector plane. Together with the normal vector it defines the plane.
default: plane\_point 0 0 0
- -
plane\_normal
- -The normal vector of the deflector plane. Together with the point it defines the plane.
default: plane\_normal 0 1 0
- -
bounce
- -The amount of bouncing when a particle is deflected. 0 means no deflection and 1 stands for 100 percent reflection.
default: bounce 1.0 - -
- -## DirectionRandomiser Affector {#DirectionRandomiser-Affector} - -@copybrief Ogre::DirectionRandomiserAffector - -Its extra attributes are: - -@par randomness -@copybrief Ogre::DirectionRandomiserAffector::setRandomness -@par -Default: randomness 1 - -@par scope -@copybrief Ogre::DirectionRandomiserAffector::setScope -@par -Default: scope 1.0 - -@par keep_velocity -@copybrief Ogre::DirectionRandomiserAffector::setKeepVelocity -@par -Default: keep_velocity false - -## TextureAnimator Affector {#TextureAnimator-Affector} - -@copybrief Ogre::TextureAnimatorAffector - -Its extra attributes are: - -@par texcoord_start -@copybrief Ogre::TextureAnimatorAffector::setTexcoordStart -@par -Default: texcoord_start 0 - -@par texcoord_count -@copybrief Ogre::TextureAnimatorAffector::setTexcoordCount -@par -Default: texcoord_count 0 -@copydetails Ogre::TextureAnimatorAffector::setTexcoordCount - -@par duration -@copybrief Ogre::TextureAnimatorAffector::setDuration -@par -@copydetails Ogre::TextureAnimatorAffector::setDuration -@par -Default: duration 0 - -@par random_offset -@copybrief Ogre::TextureAnimatorAffector::useRandomStartOffset -@par -Default: random_offset false \ No newline at end of file diff --git a/Docs/src/resourcemanagement.md b/Docs/src/resourcemanagement.md deleted file mode 100644 index 295868f0bad..00000000000 --- a/Docs/src/resourcemanagement.md +++ /dev/null @@ -1,102 +0,0 @@ -# Resource Management {#Resource-Management} - -Resources are data objects that must be loaded and managed throughout an application. A Ogre::Resource might be a Ogre::Mesh, a Ogre::Texture, or any other piece of data - the key properties are -- they must be identified by a name which is unique -- must be loaded only once -- must be managed efficiently in terms of retrieval, and -- they may also be unloadable to free memory up when they have not been used for a while and the memory budget is under stress. - -@tableofcontents - -# Resource Life-cycle {#Resource-Life-cycle} - -![](images/ResourceManagement.svg) - -A Ogre::ResourceManager is responsible for managing a pool of resources of a particular type. It must index them, look them up, load and destroy them. It may also need to stay within a defined memory budget, and temporarily unload some resources if it needs to to stay within this budget. - -Resource managers use a priority system to determine what can be unloaded, and a Least Recently Used (LRU) policy within resources of the same priority. - -Resources can be loaded using the generalised load interface, and they can be unloaded and removed. In addition, each subclass of ResourceManager will likely define custom 'load' methods which take explicit parameters depending on the kind of resource being created. - -A resource is created in [LOADSTATE_UNLOADED](@ref Ogre::Resource::LOADSTATE_UNLOADED), it then progressed to [LOADSTATE_PREPARED](@ref Ogre::Resource::LOADSTATE_PREPARED), the meaning of which depends on the concrete Resource type, but usually means that data has been read from disk into memory. -[LOADSTATE_LOADED](@ref Ogre::Resource::LOADSTATE_LOADED) means all data has been uploaded to the GPU and is ready to use without further processing. - -Resources can be loaded and unloaded through the Ogre::Resource class, but they can only be removed (and thus eventually destroyed) using their parent Ogre::ResourceManager. - -@note specify a Ogre::ManualResourceLoader for procedurally generated Resources at creation time, so they can be unloaded/ reloaded too. - -# Locations {#Resource-Location} - -Resource files need to be loaded from specific locations. By calling Ogre::ResourceGroupManager::addResourceLocation, you add search locations to the list. Locations added first are preferred over locations added later. Furthermore locations are indexed at the time you add them, so make sure that all your assets are already there - or you will have to remove and re-add the location. - -Locations can be folders, compressed archives, even perhaps remote locations. Facilities for loading from different locations are provided by plugins which provide implementations of the Ogre::Archive class. All the application user has to do is specify a 'loctype' string in order to indicate the type of location, which should map onto one of the provided plugins. %Ogre comes configured with the @c FileSystem (folders) and @c Zip (archive compressed with the pkzip / WinZip etc utilities) types. - -# Groups {#Resource-Groups} - -Resource Locations are organized in Groups. A resource group allows you to define a set of resources that can be loaded / unloaded as a unit. For example, it might be all the resources used for the level of a game. -- There is always one predefined resource group called "General", which is typically used to hold all resources which do not need to be unloaded until shutdown. -- There is another predefined resource group called [INTERNAL_RESOURCE_GROUP_NAME](@ref Ogre::ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME) too, which should be used by OGRE internal only, the resources created in this group aren't supposed to be modified, unloaded or removed by user. -- There is one other predefined value, [AUTODETECT_RESOURCE_GROUP_NAME](@ref Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME). Using this causes to search for the resource in the resource locations of each group in turn. The results depends on the set of defined groups as the same resource name might exist in several groups. - -You can create additional groups so that you can control the life of your resources in whichever way you wish. - -Once you have defined a resource group, resources which will be loaded as part of it are defined in one of 2 ways: - -1. Through the use of @ref Scripts; some Ogre::ResourceManager subtypes have -script formats (e.g. .material, .overlay) which can be used to declare resources -2. By calling Ogre::ResourceManager::createResource to create a resource manually. -This resource will go on the list for it's group and will be loaded -and unloaded with that group - -After creating a resource group, adding some resource locations, and perhaps [pre-declaring](@ref Resource-Declaration) some resources, but before you need to use the resources in the group, you must call Ogre::ResourceGroupManager::initialiseResourceGroup to initialise the group. By calling this, you are triggering the following processes: - -- @ref Scripts for all resource types which support scripting are parsed from the resource locations, and resources within them are created (but not loaded yet). -- Creates all the resources which have just pre-declared using declareResource (again, these are not loaded yet) - -So what this essentially does is create a bunch of unloaded Ogre::Resource objects in the respective ResourceManagers based on scripts, and resources you've pre-declared. That means that code looking for these resources will find them, but they won't be taking up much memory yet, until they are either used, or they are loaded in bulk using Ogre::ResourceGroupManager::loadResourceGroup. Loading the resource group in bulk is entirely optional, but has the advantage of coming with progress reporting as resources are loaded. - -Failure to call Ogre::ResourceGroupManager::initialiseResourceGroup means that Ogre::ResourceGroupManager::loadResourceGroup will do nothing, and any resources you define in scripts will not be found. Similarly, once you have called this method you won't be able to pick up any new scripts or pre-declared resources, unless you call Ogre::ResourceGroupManager::clearResourceGroup, set up declared resources, and call this method again. - -@note Resource groups by default are treated as self-contained - i.e. they cannot reference resources from other groups. To circumvent this specify `inGlobalPool=true` at Ogre::ResourceGroupManager::createResourceGroup for all groups that should be able to cross-reference resources. - -## Resource-Declaration {#Resource-Declaration} - -Declaring the resources you intend to use in advance is optional, however it is a very useful feature. -By declaring resources before you attempt to use them, you can -more easily control the loading and unloading of those resources -by their group. Declaring them also allows them to be enumerated, -which means events can be raised to indicate the loading progress -(Ogre::ResourceGroupListener). - -To declare a resource use Ogre::ResourceGroupManager::declareResource. This is useful for scripted -declarations since it is entirely generalised, and does not create Resource instances right away. -This adds the following conceptual stages before a Resource is created as Unloaded: - -@par Undefined -Nobody knows about this resource yet. It might be -in the filesystem, but %Ogre is oblivious to it at the moment - there -is no Ogre::Resource instance. This might be because it's never been declared -(either in a script, or using Ogre::ResourceGroupManager::declareResource), or -it may have previously been a valid Resource instance but has been -removed, either individually through Ogre::ResourceManager::remove or as a group -through Ogre::ResourceGroupManager::clearResourceGroup. - -@par Declared -%Ogre has some forewarning of this resource, either -through calling Ogre::ResourceGroupManager::declareResource, or by declaring -the resource in a script file which is on one of the resource locations -which has been defined for a group. There is still no instance of Resource, -but Ogre will know to create this resource when -Ogre::ResourceGroupManager::initialiseResourceGroup is called -(which is automatic if you declare the resource group before Ogre::Root::initialise). - -@par Unloaded -There is now a Ogre::Resource instance for this resource, -although it is not loaded. This means that code which looks for this -named resource will find it, but the Resource is not using a lot of memory -because it is in an unloaded state. A Resource can get into this state -by having just been created by Ogre::ResourceGroupManager::initialiseResourceGroup -(either from a script, or from a call to Ogre::ResourceGroupManager::declareResource), by -being created directly from code (Ogre::ResourceManager::createResource), or it may -have previously been loaded and has been unloaded, either individually -through Resource::unload, or as a group through Ogre::ResourceGroupManager::unloadResourceGroup. \ No newline at end of file diff --git a/Docs/src/rtss.md b/Docs/src/rtss.md deleted file mode 100644 index 586ee52b686..00000000000 --- a/Docs/src/rtss.md +++ /dev/null @@ -1,548 +0,0 @@ -# Runtime Shader Generation {#rtss} - -With D3D11 and GL3, support for fixed pipeline functionality was removed. Meaning you can only render objects using shaders. - -While @ref High-level-Programs offer you maximal control and flexibility over how your objects are rendered, writing and maintaining them is also a very time consuming task. - -The Run Time Shader System or RTSS for short is the %Ogre way of managing Shaders and their variations. Initially it was created as a drop-in-replacement to the Fixed-Function Pipeline (FFP) for RenderSystems that lacked it. -However, since then it grew to a general way to express shader functionality in @ref Material-Scripts without having to manually write shaders. - -While the resulting shaders are less optimized, they offer the following advantages: - -* Save development time e.g. when your target scene has dynamic lights and the number changes, fog changes and the number of material attributes increases the total count of needed shaders dramatically. It can easily cross 100 and it becomes a time consuming development task. -* Reusable code - once you've written the shader extension you can use it anywhere due to its independent nature. -* Custom shaders extension library - enjoy the shared library of effects created by the community. Unlike hand written shader code, which may require many adjustments to be plugged into your own shader code, using the extensions library requires minimum changes. - -For fixed function function properties, the RTSS will read the standard `pass` and `texture_unit` definitions, so no changes are required. To enable features that go beyond the possibilities of the FFP, you have to define an additional `rtshader_system` block with the respective properties. - -For instance, the FFP only allows per-vertex lighting. To request per-pixel lighting, you would add the following block to a pass: - -@snippet Samples/Media/materials/scripts/RTShaderSystem.material rtss_per_pixel - -To modify the default lighting stage [see below](@ref rtss_custom_api). For more examples see `Media/RTShaderLib/materials/RTShaderSystem.material`. - -@tableofcontents - -# RTSS Pass properties {#rtss_custom_mat} - -Here are the attributes you can use in a `rtshader_system` block of a `pass {}`: - -- [transform_stage](#transform_stage) -- [lighting_stage](#lighting_stage) -- [image_based_lighting](#image_based_lighting) -- [gbuffer](#gbuffer) -- [normal_map](#normal_map_pass) -- [metal_roughness](#metal_roughness) -- [fog_stage](#fog_stage) -- [light_count](#light_count) -- [triplanarTexturing](#triplanarTexturing) -- [shadow_mapping](#shadow_mapping) -- [integrated_pssm4](#integrated_pssm4) -- [hardware_skinning](#hardware_skinning) -- [layered_blend](#layered_blend) -- [source_modifier](#source_modifier) - - - -## transform_stage -@copybrief Ogre::RTShader::SRS_TRANSFORM - -@par -Format: `transform_stage [attrIndex]` -@par -Example: `transform_stage instanced 1` - -@param type either `ffp` or `instanced` -@param attrIndex the start texcoord attribute index to read the instanced world matrix from. Must be greater than 0. - -@see @ref Instancing-in-Vertex-Programs -@see Ogre::InstanceBatchHW - - - - -## lighting_stage - -Force a specific lighting model. - -@par -Format: `lighting_stage [two_sided] [normalised]` -@par -Example: `lighting_stage ffp two_sided` - -@param two_sided compute lighting on both sides of the surface, when culling is disabled. -@param normalised normalise the blinn-phong reflection model to make it energy conserving - see [this for details](http://www.rorydriscoll.com/2009/01/25/energy-conservation-in-games/) - - - -## image_based_lighting - -@copybrief Ogre::RTShader::SRS_IMAGE_BASED_LIGHTING - -@par -Format: `image_based_lighting texture [luminance ]` -@par -Example: `image_based_lighting texture ibl_cubemap.ktx` - -@param luminance factor to scale the IBL influence by - -For best results, generate the cubemaps using [cmgen](https://github.com/google/filament/tree/main/tools/cmgen) from the filament project. - - - -## gbuffer - -@copybrief Ogre::RTShader::SRS_GBUFFER - -@par -Format: `lighting_stage gbuffer [target_layout]` -@par -Example: `lighting_stage gbuffer normal_viewdepth diffuse_specular` - -@param target_layout with @c gbuffer, this specifies the data to be written into one or two MRT targets. Possible values are @c depth, @c normal, @c viewpos, @c normal_viewdepth and @c diffuse_specular - - - -## normal_map - -@deprecated use @ref normal_map instead - -@copybrief Ogre::RTShader::SRS_NORMALMAP - -@par -Format: `lighting_stage normal_map [normalmap_space] [texcoord_index] [sampler]` -@par -Example: `lighting_stage normal_map Panels_Normal_Tangent.png tangent_space 0 SamplerToUse` - -@param texture normal map name to use -@param normalmap_space see @ref normal_map -@param texcoord_index the start texcoord attribute index to read the uv coordinates from -@param sampler the [Sampler](@ref Samplers) to use for the normal map - - - - -## metal_roughness - -@copybrief Ogre::RTShader::SRS_COOK_TORRANCE_LIGHTING - -By default, roughness is read from `specular[0]` and metalness from `specular[1]`. - -@par -Format: `lighting_stage metal_roughness [texture ]` -@par -Example: `lighting_stage metal_roughness texture Default_metalRoughness.jpg` - -@param texturename texture for spatially varying parametrization. -[In accordance to the glTF2.0 specification](https://www.khronos.org/registry/glTF/specs/2.0/glTF-2.0.html#_material_pbrmetallicroughness_metallicroughnesstexture), roughness is sampled from the G channel and metalness from the B channel. - -@note Using this option switches the lighting equations from Blinn-Phong to the Cook-Torrance PBR model [using the equations described by Filament](https://google.github.io/filament/Filament.html#materialsystem/standardmodelsummary). - - - -## fog_stage - -@copybrief Ogre::RTShader::SRS_FOG - -@par -Format: `fog_stage ffp ` -@par -Example: `fog_stage ffp per_pixel` - -@param calc_mode either `per_vertex` or `per_pixel` - - - -## light_count - -Override dynamic light count. Fix the number of lights to be used in the shader. Avoids shader recompilation when the number of lights changes. -@par -Format: `light_count ` - - - -## triplanarTexturing - -@copybrief Ogre::RTShader::SRS_TRIPLANAR_TEXTURING - -@par -Format: `triplanarTexturing ` -@par -Example: `triplanarTexturing 0.05 0.2 4.0 BumpyMetal.jpg egyptrockyfull.jpg MtlPlat2.jpg` - -@param textureScale texture coordinates are multiplied by this. -@param plateauSize plateau on which small components of the normal have no influence. -@param transitionSpeed transitions speed between the three textures -Valid values are [0; 0.57] not bigger to avoid division by zero -@param textureFromX Texture for the x-direction planar mapping -@param textureFromY Texture for the y-direction planar mapping -@param textureFromZ Texture for the z-direction planar mapping - - - -## integrated_pssm4 -@copybrief Ogre::RTShader::SRS_INTEGRATED_PSSM3 - -@par -Format: `integrated_pssm4 [debug] [filter]` -@param debug visualize the active shadow-splits in the scene -@param filter one of `pcf4, pcf16` (default: @c pcf4) - -## shadow_mapping {#shadow_mapping} -@copybrief Ogre::RTShader::SRS_SHADOW_MAPPING - -@par -Format: `shadow_mapping [light_count ] [filter ]` -@param filter one of `pcf4, pcf16` (default: @c pcf4) -@param light_count number of lights to support (default: 1) - - - -## hardware_skinning -@copybrief Ogre::RTShader::SRS_HARDWARE_SKINNING - -@par -Format: `hardware_skinning [type] [correct_antipodality scale_shearing]` -@par -Example: `hardware_skinning 24 2 dual_quaternion true false` - -@param type either `dual_quaternion` or `linear` (default: @c linear) -@param correct_antipodality Correctly handle rotations > 180° in dual quaternion computation -@param scale_shearing add scaling and shearing support to dual quaternion computation - -@note You can also use Ogre::RTShader::HardwareSkinningFactory::prepareEntityForSkinning to derive this information automatically. - -# RTSS Texture Unit properties {#rtss_tu_props} - -Here are the attributes you can use in a `rtshader_system` block of a `texture_unit {}`: - -- [normal_map](#normal_map) -- [layered_blend](#layered_blend) -- [source_modifier](#source_modifier) - -## normal_map {#normal_map} - -@copybrief Ogre::RTShader::SRS_NORMALMAP - -@par -Format: `normal_map [height_scale scale] [texcoord_index idx]` -@par -Example: `normal_map parallax_occlusion height_scale 0.1` - -@param normalmap_space
-
tangent_space
-
Normal map contains normal data in tangent space. -This is the default normal mapping behavior and it requires that the -target mesh will have valid tangents within its vertex data.
-
object_space
-
Normal map contains normal data in object local space. -This normal mapping technique has the advantages of better visualization results, -lack of artifacts that comes from texture mirroring usage, it doesn't requires tangent -and it also saves some instruction in the vertex shader stage. -The main drawback of using this kind of normal map is that the target object must be static -in terms of local space rotations and translations.
-
parallax
-
Normal map contains normal data in parallax corrected tangent space -The restrictions of @c tangent_space apply. Additionally the alpha -channel of the normal texture is expected to contain height displacement data. -This is used for parallax corrected rendering.
-
parallax_occlusion
-
An extension of @c parallax, which samples the texture multiple times to allow using -a larger displacement value without getting artifacts.
-
-@param height_scale displacement scale factor, when using @c parallax or @c parallax_occlusion -@param texcoord_index the texcoord attribute index to read the uv coordinates from - - - -## layered_blend - -@copybrief Ogre::RTShader::SRS_LAYERED_BLENDING -@par -Format: `layered_blend ` -@par -Example: layered_blend luminosity - -@param effect one of `default, normal, lighten, darken, multiply, average, add, subtract, difference, negation, exclusion, screen, overlay, hard_light, soft_light, color_dodge, color_burn, linear_dodge, linear_burn, linear_light, vivid_light, pin_light, hard_mix, reflect, glow, phoenix, saturation, color, luminosity` - - - - -## source_modifier - -Apply custom modulate effect to texture layer -@par -Format: `source_modifier custom ` -@par -Example: `source_modifier src1_inverse_modulate custom 2` - -@param operation one of `src1_modulate, src2_modulate, src1_inverse_modulate, src2_inverse_modulate` -@param parameterNum number of the custom shader parameter that controls the operation - -# Setting properties programmatically {#RTSS-Props-API} - -In case you need to set the properties programmatically, see the following example for how the script is mapped to the API. - -```cpp -rtshader_system -{ - normal_map height_scale 0.1 -} -``` -becomes -```cpp -using namespace Ogre::RTShader; -ShaderGenerator* shaderGen = ShaderGenerator::getSingletonPtr(); - -shaderGen->createShaderBasedTechnique(mat->getTechnique(0), MSN_SHADERGEN); -RenderState* rs = shaderGen->getRenderState(MSN_SHADERGEN, *mat, 0); -SubRenderState* srs = shaderGen->createSubRenderState(SRS_NORMALMAP); -rs->addTemplateSubRenderState(srs); - -srs->setParameter("height_scale", "0.1"); -``` - -# System overview {#rtss_overview} - -The RTSS manages a set of opaque isolated components (SubRenderStates) where each implements a specific effect. -These "effects" include Fixed Function transformation and lighting. At the core these components are plain shader files providing a set of functions; e.g. @c SGX_Light_Directional_Diffuse(), @c SGX_Light_Point_Diffuse(). - -Correctly ordering these functions, providing them with the right input values and interconnecting them is the main purpose of the RTSS. - -To this end the RTSS defines a set of stages; e.g Ogre::RTShader::FFP_VS_TRANSFORM, Ogre::RTShader::FFP_PS_TEXTURING. -It then queries each registered Ogre::RTShader::SubRenderState to attach its functions to these stages. Then it generates the entry function (e.g. `main()` for GLSL) by sequentially calling these functions. - -You can think of stages as a way to group shader "effects" inside a Ogre::Pass - similarly how a Ogre::RenderQueueGroup groups [renderables](@ref Ogre::Renderable) for rendering. - -Basically it performs the following (simplified) transformation, given -```cpp -// GLOBAL PARAMETERS -$global_parameters -// FUNCTION -$input_parameters -$output_parameters -void main() { - $local_parameters - $FFP_VS_TRANSFORM - (...) - $FFP_VS_TEXTURING -} -``` -and `$FFP_VS_TRANSFORM = [FFP_Transform()]`, `$FFP_VS_TEXTURING = [FFP_TransformTexCoord()]`, it generates - -```cpp -// PROGRAM DEPENDENCIES -#include -#include -// GLOBAL PARAMETERS -uniform mat4 worldviewproj_matrix; -uniform mat4 texture_matrix1; -// FUNCTION -in vec4 vertex; -in vec4 uv0; -out vec4 oTexcoord4_0; -void main() { - FFP_Transform(worldviewproj_matrix, vertex, gl_Position); - FFP_TransformTexCoord(texture_matrix1, uv0.xy, oTexcoord4_0.xy); -} -``` - -As you can see the RTSS also resolved the required parameters and routed them into the correct functions. See @ref creating-extensions for details about parameter resolution. - -Now that you know what the RTSS does, you are probably wondering how to change which functions are emitted per stage. Lets say, change the lighting from the FFP style per-vertex lighting to per-pixel lighting. - -The RTSS is flexible enough to "just" move the according calculations from the vertex shader to the pixel shader. - -## Core features of the system {#core-feats} -* Runtime shader generation synchronized with scene state. Each time scene settings change, a new set of shaders is generated. -* Full Fixed Function Pipeline (FFP) emulation. This feature is most useful combined with render system that doesn't provide any FFP functionality (OpenGL ES 2.0, D3D11 etc). -* Shader language independent interface: the logic representation of the shader programs is completely independent from the target shader language. You can generate code for different shader languages from the same program. -* Pluggable interface for different shader languages. -* Pluggable interface for shader based functions in a seamless way. Each function will be automatically combined with the rest of the shader code. -* Smart program caching: each shader program is created only once and may be used by multiple passes. -* Automatic vertex shader output register compacting: no more compacting variables by hand. In case the amount of used vertex shader outputs exceeds the maximum allowed (12 to 32, depending on [D3DPSHADERCAPS2_0.NumTemps](http://msdn.microsoft.com/en-us/library/bb172918%28v=VS.85%29.aspx)), a compacting algorithm packs the vertex shader outputs and adds unpack code in the fragment shader side. -* Material script support, for both export and import. - -## Controlling shader re-generation - -By default the RTSS synchronizes with the active SceneManager regarding the fog settings and the number of active lights. -This can result in frame-drops when new lights are added, as all managed Materials are updated for the new light-count. -On the other hand, the generated shaders might include too many lights for the targeted budget. - -To get more fine-grained control, you can use: -- Ogre::RTShader::RenderState::setLightCountAutoUpdate and -- Ogre::RTShader::RenderState::setLightCount - -to set a fixed number of lights the materials should consider. - -# The RTSS in Depth {#rtss_indepth} - -When the user asks the system to generate shaders for a given technique he has to provide a name for the target technique scheme. The system then creates a new technique based on the source technique but with a different scheme name. - -The idea behind this concept is to use Ogre's built in mechanism of material schemes, so all the user has to do in order to use the new technique is to call Ogre::Viewport::setMaterialScheme. - -Before each viewport update, the system performs a validation step of all associated shader based techniques it created. This step includes automatic synchronization with the scene lights and fog states. When the system detects that a scheme is out of date it generates the appropriate shaders for each technique new. - -The following steps are executed in order to generate shaders for a given technique: - -* For each pass in the technique the system builds a set of sub render states that describe the logic process of the rendering pipeline from the draw call submission until the final pixel color. -* Each render state is translated into a set of logic shader programs (currently only pixel and vertex shader). -The logic programs are then sent to specific shader language writers that produce source code for the respective shader language. The source code is used to create the GPU programs that are applied to the destination pass. -Before rendering of an object that uses generated shaders the system allows each sub render state to update the GPU constants associated with it. - -## Main components {#rtss__components} -The following is an partial list of components within the RTSS. These components are listed as they have great importance in understanding controlling and later extending the RTSS system. - -@par ShaderGenerator -The ShaderGenerator is the main interface to the RTSS system. Through it you can request to generate and destroy the shaders, influence from what parts to create the shaders, and control general system settings such as the shading language and shader caching. - -@par RenderState classes -The RenderState is the core component of the system. It aggregates the stages that the final shader will be created from. These stages are referred to as SubRenderStates. It is possible to bypass the rest of the RTSS and use RenderStates directly to manually generate shaders for arbitrary passes. -@par -RenderStates exist on two levels: -1. SGScheme RenderStates describe the SubRenderStates that will be used when creating a shader for a given material scheme. -2. SGPass TargetRenderState describe the SubRenderStates that will be used when creating a specific pass of a specific material. -@par -When a shader is generated for a given material the system combines the SubRenderStates from both RenderStates to create a shader specific for a material pass in a specific scheme. - -@par SubRenderState classes -Sub-render states (SRS) are components designed to generate the code of the RTSS shaders. Each SRS usually has a specific role to fill within the shader's construction. These components can be combined in different combinations to create shaders with different capabilities. -@par -By default, %Ogre adds the following 5 SRSs to every scheme RenderState to recreate the functionality provided by the fixed pipeline -1. @ref Ogre::RTShader::SRS_TRANSFORM - @copybrief Ogre::RTShader::SRS_TRANSFORM -2. @ref Ogre::RTShader::SRS_VERTEX_COLOUR - Calculate the base diffuse and specular color of the object regardless of lights or textures. The color is calculated based on the ambient, diffuse, specular and emissive properties of the object and scene and the specified color tracking. -3. @ref Ogre::RTShader::SRS_PER_PIXEL_LIGHTING - @copybrief Ogre::RTShader::SRS_PER_PIXEL_LIGHTING -4. @ref Ogre::RTShader::SRS_TEXTURING - @copybrief Ogre::RTShader::SRS_TEXTURING -5. @ref Ogre::RTShader::SRS_FOG - @copybrief Ogre::RTShader::SRS_FOG - -@par SubRenderStateFactory -As the name suggests, sub render state factories are factories that produce sub render states. Each factory generates a specific SRS. -@par -These type of components are note worthy for 2 reason. The first and obvious one is that they allow the system to generate new SRSs for the materials it is asked to generate. The second reason is that they perform as script readers and writers allowing the system to create specific or specialized SRSs per material. - -## Initializing the system - -@note If you are using the OgreBites::ApplicationContext, the following steps will be taken automatically for you. - -Initializing the system is composed of the following steps: -* Create the internal managers and structures via the Ogre::RTShader::ShaderGenerator::initialize() method. -* Assign the target scene manager to the shader generator. -* Listen for SchemeNotFound events via Ogre::MaterialManager::Listener and use the RTSS to handle them - -```cpp -if (Ogre::RTShader::ShaderGenerator::initialize()) -{ - // Register the scene manager. - Ogre::RTShader::ShaderGenerator::getSingleton().addSceneManager(sceneMgr); - - // forward scheme not found events to the RTSS - OgreBites::SGTechniqueResolverListener* schemeNotFoundHandler = ... - Ogre::MaterialManager::getSingleton().addListener(schemeNotFoundHandler); -} -``` - -## Customizing the default RenderState {#rtss_custom_api} - -Lets say, you wanted to globally change the default per-pixel lighting mode of the RTSS back to the FFP style per-vertex lighting. -For this you have to grab the global RenderState associated with the active material scheme, as - -@snippet Components/Bites/src/OgreAdvancedRenderControls.cpp rtss_per_pixel - -Next, you have to create the FFPLighting SRS that should be used for shader generation and *add* to the set. - -@note adding a SRS will automatically override the default SRS for the same stage. In the example we override the Ogre::RTShader::FFP_LIGHTING stage. - -## Creating the shader based technique {#rtssTech} -This step will create a new, shader-based, technique based on the given technique. Calling Ogre::RTShader::ShaderGenerator::createShaderBasedTechnique() will cause the system to generate SubRenderStates based on the source technique and add a new technique using the given scheme name to the material. -The passes of this new technique will receive shaders generated and updated by the system during as described in the @ref rtssGenerate section below. - -![](CreateShaderBasedTech.svg) - -To use the generated technique, change the material scheme of your viewport(s) to scheme name you passed as argument to this method. - -```cpp -// Create shader based technique from the default technique of the given material. -mShaderGenerator->createShaderBasedTechnique("Examples/BeachStones", Ogre::MSN_DEFAULT, Ogre::MSN_SHADERGEN); - -// Apply the shader generated based techniques. -mViewport->setMaterialScheme(Ogre::MSN_SHADERGEN); -``` - -@note you can automate the shader generation process for all materials. First set the viewport scheme to the destination scheme of the RTSS shaders. Second register to the `Ogre::MaterialManager::Listener` implementing `handleSchemeNotFound()` - e.g. OgreBites::SGTechniqueResolverListener - -## Shader generation at runtime {#rtssGenerate} -During the application runtime the @c ShaderGenerator instance receives notifications on per frame basis from its target @c SceneManager. -At this point it checks the material scheme in use. In case the current scheme has representations in the manager, it executes its validate method. -The @c SGScheme validation includes synchronization with scene light and fog settings. In case it is out of date it will rebuild all shader generated techniques. -1. The first step is to loop over every @c SGTechnique associated with this @c SGScheme and build its @c RenderStates - one for each pass. -2. The second step is to loop again on every @c SGTechnique and acquire a program set for each @c SGPass. - -@note The shaders are only automatically updated for lights and fog changes. If you change the source pass after initial shader creation, you must call Ogre::RTShader::ShaderGenerator::invalidateMaterial manually. - -The actual acquiring process is done by the @c TargetRenderState that generates CPU program representation, send them to a matching @c ProgramWriter that is chosen by the active target language, the writer generates source code that is the basis for the GPU programs. -The result of this entire process is that each technique associated with the @c SGScheme has vertex and pixel shaders applied to all its passes. These shaders are synchronized with scene lights and fog settings. - -![](RuntimeShaderGeneration.svg) - -## Creating custom shader extensions {#creating-extensions} -Although the system implements some common shader based effects such as per pixel lighting, normal map, etc., you may find it useful to write your own shader extensions. - -In order to extend the system with your own shader effects you'll have to follow these steps: -* Implement the SubRenderState interface - This is the main class that is responsible for the actual effect processing such as preparing the destination pass, updating the CPU shader programs, updating the GPU shader parameters etc. -* Implement the SubRenderStateFactory interface: This class will allow the RTSS to create instances of the previous class via code or script as well as export it to material script file. -* Register the factory to the RTSS using the Ogre::RTShader::ShaderGenerator::addSubRenderStateFactory method. -* Add shader files that will supply all the actual shader functions your SubRenderState needs. In order to support multiple shader languages, @ref OgreUnifiedShader are provided. These shaders should be placed in a resource location known to the resource manager. - -Implementing the SubRenderState requires overriding the pure methods of the base class. -* Ogre::RTShader::SubRenderState::getType() should return unique string that identify the sub class implementation. That value is shared among all instances and can be stored in a static string variable. It uses to system to match between SubRenderState instance and the factory to should destroy it. -* Ogre::RTShader::SubRenderState::getExecutionOrder() should return integer value that will use the system to sort all SubRenderState instances of the same render state before each one of them will create its part in the CPU shader programs. Note that: - * The execution order does not imply the order of the parameter definitions and function calls within the generated shader. - * If an execution number is set to be the same as one of the basic fixed pipeline SRSs. Than that SRS will be built __instead__ of the fixed pipeline SRS. -* Ogre::RTShader::SubRenderState::copyFrom() a simple copy method that uses the system when coping one instance to another. **Note:** Only configuration data attributes should be copy here. -* Ogre::RTShader::SubRenderState::createCpuSubPrograms - This is the heart of this interface. This method should update the CPU shader programs with the specific details of the overriding class. - -The SubRenderState supply default implementation for this method which break down this method into three stages: - -@par Resolving parameters -this stage should grab all the needed parameters for this SubRenderState. Typically there several SubRenderStates working on a common set of Parameters - either to cooperate or because they use the same inputs. -Therefore parameters are not resolved by name (except for local variables), but rather by symbolic constants. These can either be of Ogre::GpuProgramParameters::AutoConstantType, which should already be familiar to you or of Ogre::RTShader::Parameter::Content. -@par -You can think of the latter as an extension of the Cg/ HLSL Semantics to the actual content of the parameter. -@par -In case of the Ogre::RTShader::FFPTransform we need the world view projection matrix and vertex shader input and output position parameters. -@par -@snippet Components/RTShaderSystem/src/OgreShaderFFPTransform.cpp param_resolve - -@par Resolving dependencies -this stage should provide the name of the external shader library files that contains the actual shader code needed by this SubRenderState. -In case of the Ogre::RTShader::SRS_TEXTURING it will add the common and texturing library for both vertex and pixel shader program. -@par -@snippet Components/RTShaderSystem/src/OgreShaderFFPTexturing.cpp deps_resolve - -@par Adding function invocations -this stage creates the function calls within this SubRenderState requires. To add function invocations, you first need to obtain a Ogre::RTShader::FunctionStageRef for the respective stage. -In case of the Ogre::RTShader::SRS_FOG it will add vertex depth calculation to the vertex shader program. -@par -@snippet Components/RTShaderSystem/src/OgreShaderFFPFog.cpp func_invoc -@par -The arguments to the function are the ones you resolved in the first step and the function name must be available in one of the libraries you provided in the second step. -You can add call as many functions as you need. The calls will appear in the same order in the generates shader source code. -@note -* The ordering of the function invocation is crucial. Use the Ogre::RTShader::FFPVertexShaderStage and Ogre::RTShader::FFPFragmentShaderStage enumarations to place your invocations in the desired global order. -* Make sure the parameter semantic (in/out) in the SubRenderState code matches to your shader code implementation you supplied in the library file. GLSL will fail to link to library functions if it won't be able to find a perfect function declaration match. -* Ogre::RTShader::SubRenderState::updateGpuProgramsParams - As the name suggest this method should be overridden only in case your SubRenderState should update some parameter it created before. -* Ogre::RTShader::SubRenderState::preAddToRenderState(): this method called before adding this SubRenderState to a parent RenderState instances. It allows this SubRenderState to exclude itself from the list in case the source pass is not matching. I.E in case of SubRenderState that perform lighting calculations it can return false when the given source pass specifies that lighting calculations disabled for it. -@snippet Components/RTShaderSystem/src/OgreShaderFFPLighting.cpp disable -This method also let the SubRenderState to opportunity to modify the destination pass. I.E the Ogre::RTShader::NormalMapLighting instance adds the normal map texture unit in this context. - -Implementing the Ogre::RTShader::SubRenderStateFactory is much simpler and involves implementing the following methods -* Ogre::RTShader::SubRenderStateFactory::createInstanceImpl(): This method should return instance for the SubRenderState sub class. -* Ogre::RTShader::SubRenderStateFactory::createInstance(): This method should return instance for the SubRenderState sub class using the given script compiler parameters. Implement this method if you want to be able to create your custom shader extension from material script. -* Ogre::RTShader::SubRenderStateFactory::writeInstance(): This method should write down the parameters of a given SubRenderState instance to material script file. Implement this method if you want to be able to export a material that contains your custom shader extension. - -## Tips for debugging shaders {#debugging} -A couple of notes on debugging shaders coming from the RTSS: -* Call OgreBites::ApplicationContext::setRTSSWriteShadersToDisk. This will cache the generated shaders onto the disk under the directory [WRITABLE_PATH](@ref Ogre::FileSystemLayer::getWritablePath)`/RTShaderLib/cache`. This is important for 2 reasons: - * It will make compilation problems easier to detect. - * Once a shader is written to the disk, as long as you don't change the code behind it, the same shader will be picked up in the next application run even if its content has changed. If you have compilation or visual problems with the shader you can try to manually tinker with it without compiling the code again and again. -* Other common problems with creating shaders in RTSS usually occur from defining vertex shader parameters and using them in the pixel shader and vice versa. so watch out for those. diff --git a/Docs/src/scripts.md b/Docs/src/scripts.md deleted file mode 100644 index 6ad4cd25944..00000000000 --- a/Docs/src/scripts.md +++ /dev/null @@ -1,1296 +0,0 @@ -# Scripts {#Scripts} - -OGRE drives many of its features through scripts in order to make it easier to set up. The scripts are simply plain text files which can be edited in any standard text editor, and modifying them immediately takes effect on your OGRE-based applications, without any need to recompile. This makes prototyping a lot faster. Here are the items that OGRE lets you script: - -- @subpage Material-Scripts -- @subpage High-level-Programs -- @subpage Compositor-Scripts -- @subpage Particle-Scripts -- @subpage Overlay-Scripts -- @subpage Font-Definition-Scripts - -@tableofcontents - -# Loading scripts - -Scripts are loaded when resource groups are initialised: OGRE looks in all resource locations associated with the group (see Ogre::ResourceGroupManager::addResourceLocation) for files with the respective extension (e.g. ’.material’, ’.compositor’, ..) and parses them. If you want to parse files manually, use Ogre::ScriptCompilerManager::parseScript. - -The file extension does not actually restrict the items that can be specified inside the file; e.g. %Ogre is perfectly fine with loading a particle-system from a ’.compositor’ file - but it will lead you straight to maintenance-hell if you do that. -The extensions, however, do specify the order in which the scripts are parsed, which is as follows: - -1. "*.program" -2. "*.material" -3. "*.particle" -4. "*.compositor" -5. "*.os" -6. "*.overlay" - -# Format {#Format} - -Several script objects may be defined in a single file. The script format is pseudo-C++, with sections delimited by curly braces ({}), and comments indicated by starting a line with ’//’. The general format is shown below: - -```cpp -// This is a comment -object_keyword Example/ObjectName -{ - attribute_name "some value" - - object_keyword2 "Nested Object" - { - other_attribute 1 2 3 - // and so on.. - } -} -``` - -Every script object must be given a name, which is the line ’object_keyword <name>’ before the first opening ’{’. This name must be globally unique. It can include path characters (as in the example) to logically divide up the objects, and also to avoid duplicate names, but the engine does not treat the name as hierarchical, just as a string. Names can include spaces but must be surrounded by double quotes i.e. `compositor "My Name"`. - -@note ’:’ is the delimiter for specifying inheritance in the script so it can’t be used as part of the name. - -An script object can inherit from a previously defined object by using a *colon* ’:’ after the name followed by the name of the reference object to inherit from. You can in fact even inherit just *parts* of a script object from others; all this is covered in @ref Script-Inheritance). You can also use variables in your script which can be replaced in inheriting versions, see @ref Script-Variables. - -## Script Inheritance {#Script-Inheritance} - -When creating new script objects that are only slight variations of another object, it’s good to avoid copying and pasting between scripts. Script inheritance lets you do this; in this section we’ll use material scripts as an example, but this applies to all scripts parsed with the script compilers in %Ogre 1.6 onwards. - -For example, to make a new material that is based on one previously defined, add a *colon* ’:’ after the new material name followed by the name of the material that is to be copied. - -Example -```cpp -material : -``` - -The only caveat is that a parent material must have been defined/parsed prior to the child material script being parsed. The easiest way to achieve this is to either place parents at the beginning of the material script file, or to use the @ref Script-Import-Directive. Note that inheritance is actually a copy - after scripts are loaded into Ogre, objects no longer maintain their copy inheritance structure. If a parent material is modified through code at runtime, the changes have no effect on child materials that were copied from it in the script. - -Material copying within the script alleviates some drudgery from copy/paste but having the ability to identify specific techniques, passes, and texture units to modify makes material copying easier. Techniques, passes, texture units can be identified directly in the child material without having to layout previous techniques, passes, texture units by associating a name with them, Techniques and passes can take a name and texture units can be numbered within the material script. You can also use variables, See @ref Script-Variables. - -Names become very useful in materials that copy from other materials. In order to override values they must be in the correct technique, pass, texture unit etc. The script could be lain out using the sequence of techniques, passes, texture units in the child material but if only one parameter needs to change in say the 5th pass then the first four passes prior to the fifth would have to be placed in the script: - -Here is an example: - -```cpp -material test2 : test1 -{ - technique - { - pass - { - } - - pass - { - } - - pass - { - } - - pass - { - } - - pass - { - ambient 0.5 0.7 0.3 1.0 - } - } -} -``` - -This method is tedious for materials that only have slight variations to their parent. An easier way is to name the pass directly without listing the previous passes:
- -```cpp -material test2 : test1 -{ - technique - { - pass "Fifth Pass" - { - ambient 0.5 0.7 0.3 1.0 - } - } -} -``` - -The parent pass name must be known and the pass must be in the correct technique in order for this to work correctly. Specifying the technique name and the pass name is the best method. - -### Advanced Script Inheritance {#Advanced-Script-Inheritance} - -Script objects can also inherit from each other more generally. The previous concept of inheritance, material copying, was restricted only to the top-level material objects. Now, any level of object can take advantage of inheritance (for instance, techniques, passes, and compositor targets). - -```cpp -material Test -{ - technique - { - pass : ParentPass - { - } - } -} -``` - -Notice that the pass inherits from ParentPass. This allows for the creation of more fine-grained inheritance hierarchies. - -Along with the more generalized inheritance system comes an important new keyword: "abstract." This keyword is used at a top-level object declaration (not inside any other object) to denote that it is not something that the compiler should actually attempt to compile, but rather that it is only for the purpose of inheritance. For example, a material declared with the abstract keyword will never be turned into an actual usable material in the material framework. Objects which cannot be at a top-level in the document (like a pass) but that you would like to declare as such for inheriting purpose must be declared with the abstract keyword. - -```cpp -abstract pass ParentPass -{ - diffuse 1 0 0 1 -} -``` - -That declares the ParentPass object which was inherited from in the above example. Notice the abstract keyword which informs the compiler that it should not attempt to actually turn this object into any sort of Ogre resource. If it did attempt to do so, then it would obviously fail, since a pass all on its own like that is not valid. - -The final matching option is based on wildcards. Using the ’\*’ character, you can make a powerful matching scheme and override multiple objects at once, even if you don’t know exact names or positions of those objects in the inherited object. - -```cpp -abstract technique Overrider -{ - pass *colour* - { - diffuse 0 0 0 0 - } -} -``` - -This technique, when included in a material, will override all passes matching the wildcard "\*color\*" (color has to appear in the name somewhere) and turn their diffuse properties black. It does not matter their position or exact name in the inherited technique, this will match them. - -## Script Variables {#Script-Variables} - -A very powerful new feature in Ogre 1.6 is variables. Variables allow you to parameterize data in materials so that they can become more generalized. This enables greater reuse of scripts by targeting specific customization points. Using variables along with inheritance allows for huge amounts of overrides and easy object reuse. - -```cpp -abstract pass ParentPass -{ - diffuse $diffuse_colour -} - -material Test -{ - technique - { - pass : ParentPass - { - set $diffuse_colour "1 0 0 1" - } - } -} -``` - -The ParentPass object declares a variable called "diffuse\_colour" which is then overridden in the Test material’s pass. The "set" keyword is used to set the value of that variable. The variable assignment follows lexical scoping rules, which means that the value of "1 0 0 1" is only valid inside that pass definition. Variable assignment in outer scopes carry over into inner scopes. - -```cpp -material Test -{ - set $diffuse_colour "1 0 0 1" - technique - { - pass : ParentPass - { - } - } -} -``` - -The $diffuse\_colour assignment carries down through the technique and into the pass. - -## Script Import Directive {#Script-Import-Directive} - -Imports are a feature introduced to remove ambiguity from script dependencies. When using scripts that inherit from each other but which are defined in separate files sometimes errors occur because the scripts are loaded in incorrect order. Using imports removes this issue. The script which is inheriting another can explicitly import its parent’s definition which will ensure that no errors occur because the parent’s definition was not found. - -```cpp -import * from "parent.material" -material Child : Parent -{ -} -``` - -The material "Parent" is defined in parent.material and the import ensures that those definitions are found properly. You can also import specific targets from within a file. - -```cpp -import Parent from "parent.material" -``` - -If there were other definitions in the parent.material file, they would not be imported. - -@note Importing does not actually cause objects in the imported script to be fully parsed & created, it just makes the definitions available for inheritance. This has a specific ramification for vertex / fragment program definitions, which must be loaded before any parameters can be specified. You should continue to put common program definitions in .program files to ensure they are fully parsed before being referenced in multiple .material files. The ’import’ command just makes sure you can resolve dependencies between equivalent script definitions (e.g. material to material). - -# Custom Translators {#custom-translators} -Writing a custom translators allows you to extend Ogre's standard compilers with completely new functionality. The same scripting interfaces can be used to define application-specific functionality. Here's how you do it. - -The first step is creating a custom translator class which extends Ogre::ScriptTranslator. - -@snippet Components/Overlay/src/OgreOverlayTranslator.h font_translator - -This class defines the important function to override: translate. This is called when the TestTranslator needs to process a sub-set of the parsed script. The definition of this function might look something like this: - -@snippet Components/Overlay/src/OgreOverlayTranslator.cpp font_translate - -The translate function here expects all children to be atomic properties. Sub-objects can also be processed by checking if the child node type is Ogre::ANT_OBJECT. - -From here you need to register the translator to be invoked when the proper object is found in the scripts. To do this we need to create a Ogre::ScriptTranslatorManager object to create your custom translator. The relevant parts look like this: - -@snippet Components/Overlay/src/OgreOverlayTranslator.cpp font_register - -Note how we use Ogre::ScriptCompilerManager::registerCustomWordId to avoid string comparisons in our code. - -@snippet Components/Overlay/src/OgreOverlayTranslator.cpp font_get_translator - -No new translators are created here, just returned when requested. This is because our translator does not require separate instances to properly parse scripts, and so it is easier to only create one instance and reuse it. Often this strategy will work. - -The order that custom translator managers are registered will make a difference. When the system is attempting to find translators to handle pieces of a script, it will query the translator managers one-by-one until it finds one that handles that script object. It is a first-come-first-served basis. - -An important note is that this will recognize the above pattern no matter where in the script it is. That means that this may appear at the top-level of a script or inside several sub-objects. If this is not what you want then you can change the translator manager to do more advanced processing in the getTranslator function. - -@page Compositor-Scripts Compositor Scripts - -The compositor framework is a subsection of the OGRE API that allows you to easily define how to assemble the final image. A typical use-case are full screen post-processing effects - however Compositors are not limited to that. Compositor scripts offer you the ability to define rendering pipelines in a script which can be reused and modified easily, rather than having to use the API to define them. You still need to use code to instantiate a compositor against one of your visible viewports, but this is a much simpler process than actually defining the compositor itself. - -@tableofcontents - -# Compositor Fundamentals {#Compositor-Fundamentals} - -Compositing generally involves rendering the scene to a texture, either in addition to or instead of the main window. Once the scene is in a texture, you can then pull the scene image into a fragment program and perform operations on it by rendering it through full screen quad. The target of this post processing render can be the main result (e.g. a window), or it can be another render texture so that you can perform multi-stage convolutions on the image. You can even ’ping-pong’ the render back and forth between a couple of render textures to perform convolutions which require many iterations, without using a separate texture for each stage. Eventually you’ll want to render the result to the final output, which you do with a full screen quad. This might replace the whole window (thus the main window doesn’t need to render the scene itself), or it might be a combinational effect. - -So that we can discuss how to implement these techniques efficiently, a number of definitions are required: - -
-
Compositor
- -Definition of a rendering pipeline that can be applied to a user viewport. This is what you’re defining when writing compositor scripts as detailed in this section. - -
Compositor Instance
- -An instance of a compositor as applied to a single viewport. You create these based on compositor definitions, See @ref Applying-a-Compositor. - -
Compositor Chain
- -It is possible to enable more than one compositor instance on a viewport at the same time, with one compositor taking the results of the previous one as input. This is known as a compositor chain. Every viewport which has at least one compositor attached to it has a compositor chain. See @ref Applying-a-Compositor - -
Target
- -This is a Ogre::RenderTarget, i.e. the canvas where the result of a series of render operations is sent. A target may be the final output (e.g. your Ogre::RenderWindow), or it may be an intermediate render texture, which you declare in your script with the @ref compositor-texture line. A target which is not the output target has a size and pixel format which you can define inside the compositor script. - -
Output Target
- -As Target, but this is the single final result of all operations. The size and pixel format of this target cannot be controlled by the compositor since it is defined by the application using it, thus you don’t declare it in your script. However, you do declare a Target Section for it, see below. - -
Target Section
- -A Target may be rendered to many times in the course of a composition effect. In particular if you ’ping pong’ a convolution between a couple of textures, you will have more than one Target Sections per Target. Target Sections are declared in the script using a [target or target\_output line](#Compositor-Target-Passes), the latter being the final output of which there can be only one. -@note Internally this is referred to as Ogre::CompositionTargetPass - -
Pass
- -Within a Target Section, there are one or more individual @ref Compositor-Passes, which perform a very specific action, such as rendering the original scene (or pulling the result from the previous compositor in the chain), rendering a fullscreen quad, or clearing one or more buffers. Typically within a single target section you will use the either a `render_scene` pass or a `render_quad` pass, not both. Clear can be used with either type. - -
- -@snippet Samples/Media/materials/scripts/Examples.compositor manual_sample - -The major components of a compositor are the @ref Compositor-Techniques, the @ref Compositor-Target-Passes and the @ref Compositor-Passes, which are covered in detail in the following sections. - -# Techniques {#Compositor-Techniques} - -A compositor technique is much like a [material technique](@ref Techniques) in that it describes one approach to achieving the effect you’re looking for. A compositor definition can have more than one technique if you wish to provide some fallback should the hardware not support the technique you’d prefer to use. Techniques are evaluated for hardware support based on 2 things: - -
-
Material support
- -All @ref Compositor-Passes that render a fullscreen quad use a material; for the technique to be supported, all of the materials referenced must have at least one supported material technique. If they don’t, the compositor technique is marked as unsupported and won’t be used. - -
Texture format support
- -This one is slightly more complicated. When you request a @ref compositor-texture in your technique, you request a pixel format. Not all formats are natively supported by hardware, especially the floating point formats. However, in this case the hardware will typically downgrade the texture format requested to one that the hardware does support - with compositor effects though, you might want to use a different approach if this is the case. So, when evaluating techniques, the compositor will first look for native support for the exact pixel format you’ve asked for, and will skip onto the next technique if it is not supported, thus allowing you to define other techniques with simpler pixel formats which use a different approach. If it doesn’t find any techniques which are natively supported, it tries again, this time allowing the hardware to downgrade the texture format and thus should find at least some support for what you’ve asked for. - -
- -As with material techniques, compositor techniques are evaluated in the order you define them in the script, so techniques declared first are preferred over those declared later. - -@par -Format: technique { } - -Techniques can have the following nested elements: - -- [texture](#compositor-texture) -- [texture\_ref](#compositor_005ftexture_005fref) -- [scheme](#compositor_005fscheme) -- [compositor\_logic](#compositor_005flogic) -- [target](#Compositor-Target-Passes) -- [target\_output](#Compositor-Target-Passes) - - - -## texture {#compositor-texture} - -This declares a render texture for use in subsequent @ref Compositor-Target-Passes. -@par -Format: texture <name> <width> <height> <PixelFormat> \[<MRT Pixel_Format2>\] \[<MRT Pixel_FormatN>\] \[pooled\] \[gamma\] \[no\_fsaa\] \[depth\_pool <poolId>\] \[<scope>\] \[<cubic>\] - -@param name -A name to give the render texture, which must be unique within this compositor. This name is used to reference the texture in @ref Compositor-Target-Passes, when the texture is rendered to, and in @ref Compositor-Passes, when the texture is used as input to a material rendering a fullscreen quad. - -@param width -@param height -@parblock -The dimensions of the render texture. You can either specify a fixed width and height, or you can request that the texture is based on the physical dimensions of the viewport to which the compositor is attached. The options for the latter are either of -
    -
  • @c target_width and @c target_height -
  • @c target_width_scaled <factor> and @c target_height_scaled <factor> -
-where <factor> is the amount by which you wish to multiply the size of the main target to derive the dimensions. -@endparblock -@param PixelFormat -The Ogre::PixelFormat of the render texture. This affects how much memory it will take, what colour channels will be available, and what precision you will have within those channels. -You can in fact repeat this element if you wish. If you do so, that means that this render texture becomes a Multiple Render Target (MRT), when the GPU writes to multiple textures at once. -If you use a depth format here, the texture will be used as the depth attachment instead of the depth-buffer. Use the MRT format to specify both the depth and the colour attachments. - - -@param pooled -If present, this directive makes this texture ’pooled’ among compositor instances, which can save some memory. - -@param gamma -If present, this directive means that sRGB gamma correction will be enabled on writes to this texture. You should remember to include the opposite sRGB conversion when you read this texture back in another material, such as a quad. This option will automatically enabled if you use a render\_scene pass on this texture and the viewport on which the compositor is based has sRGB write support enabled. - -@param no\_fsaa -If present, this directive disables the use of anti-aliasing on this texture. FSAA is only used if this texture is subject to a render\_scene pass and FSAA was enabled on the original viewport on which this compositor is based; this option allows you to override it and disable the FSAA if you wish. - -@param depth\_pool -When present, this directive has to be followed by an integer. This directive is unrelated to the "pooled" directive. This one sets from which Depth buffer pool the depth buffer will be chosen from. All RTs from all compositors (including render windows if the render system API allows it) with the same pool ID share the same depth buffers (following the rules of the current render system APIs, (check RenderSystemCapabilities flags to find the rules). When the pool ID is 0, no depth buffer is used. This can be helpful for passes that don’t require a Depth buffer at all, potentially saving performance and memory. Default value is 1. -Ignored with depth pixel formats. - -@param scope -If present, this directive sets the scope for the texture for being accessed by other compositors using the [texture\_ref](#compositor_005ftexture_005fref) directive. There are three options : -1. @c local_scope (which is also the default) means that only the compositor defining the texture can access it. -2. @c chain_scope means that the compositors after this compositor in the chain can reference its textures, and -3. @c global_scope means that the entire application can access the texture. This directive also affects the creation of the textures (global textures are created once and thus can’t be used with the pooled directive, and can’t rely on viewport size). - -@param cubic -This texture is of type Ogre::TEX_TYPE_CUBE_MAP - i.e. made up of 6 2D textures which are pasted around the inside of a cube. - -@par -Example: texture rt0 512 512 PF\_R8G8B8A8 -@par -Example: texture rt1 target\_width target\_height PF\_FLOAT32\_RGB -@par -Example : texture mrt\_output target\_width target\_height PF\_FLOAT16\_RGBA PF\_FLOAT16\_RGBA chain\_scope - -@note -It is imperative that if you use MRT that the shaders that render to it render to ALL the targets. Not doing so can cause undefined results. It is also important to note that although you can use different pixel formats for each target in a MRT, each one should have the same total bit depth since most cards do not support independent bit depths. If you try to use this feature on cards that do not support the number of MRTs you’ve asked for, the technique will be skipped (so you ought to write a fallback technique). - - - - -## texture\_ref - -This declares a reference of a texture from another compositor to be used in this compositor. - -@par -Format: texture\_ref <Local_Name> <Reference_Compositor> <Reference_Texture_Name> - -@param Local_Name -A name to give the referenced texture, which must be unique within this compositor. This name is used to reference the texture in @ref Compositor-Target-Passes, when the texture is rendered to, and in @ref Compositor-Passes, when the texture is used as input to a material rendering a fullscreen quad. - -@param Reference_Compositor -The name of the compositor that we are referencing a texture from - -@param Reference_Texture_Name -The name of the texture in the compositor that we are referencing - -Make sure that the texture being referenced is scoped accordingly (either chain or global scope) and placed accordingly during chain creation (if referencing a chain-scoped texture, the compositor must be present in the chain and placed before the compositor referencing it). - -@par -Example : texture\_ref GBuffer GBufferCompositor mrt\_output - - - -## scheme - -This gives a compositor technique a scheme name, allowing you to manually switch between different techniques for this compositor when instantiated on a viewport by calling Ogre::CompositorInstance::setScheme. - -@par -Format: scheme <Name> - - - -## compositor\_logic - -This connects between a compositor and code that it requires in order to function correctly. When an instance of this compositor will be created, the compositor logic will be notified and will have the chance to prepare the compositor’s operation (for example, adding a listener). - -@par -Format: compositor\_logic <Name> - -Registration of compositor logics is done by name through Ogre::CompositorManager::registerCompositorLogic. - -# Target Sections {#Compositor-Target-Passes} - -A target section defines the rendering of either a render texture or the final output. You can update the same target multiple times by adding more than one target section to your compositor script - this is very useful for ’ping pong’ renders between a couple of render textures to perform complex convolutions that cannot be done in a single render, such as blurring. - -There are two types of target sections, the sort that updates a render texture - -@par -Format: target <Name> [<slice>] { } - -and the sort that defines the final output render - -@par -Format: target\_output { } - -The contents of both are identical, the only real difference is that you can only have a single target\_output entry, whilst you can have many target entries. - -Note, the target entry can refer to @ref Cube-map-textures. Therefore, it takes an optional _decimal_ slice parameter that specifies which face you want to render on. The default is 0, hence +X. - -Here are the attributes you can use in a ’target’ or ’target\_output’ section of a .compositor script: - -- [input](#compositor_005ftarget_005finput) -- [only\_initial](#only_005finitial) -- [visibility\_mask](#visibility_005fmask) -- [lod\_bias](#compositor_005flod_005fbias) -- [material_scheme](#material_005fscheme) -- [shadows](#compositor_005fshadows) - - - -## input - -Sets input mode of the target, which tells the target pass what is pulled in before any of its own passes are rendered. - -@par -Format: input (none | previous) -@par -Default: input none - -@param none -The target will have nothing as input, all the contents of the target must be generated using its own passes. Note this does not mean the target will be empty, just no data will be pulled in. For it to truly be blank you’d need a ’clear’ pass within this target. - -@param previous -The target will pull in the previous contents of the viewport. This will be either the original scene if this is the first compositor in the chain, or it will be the output from the previous compositor in the chain if the viewport has multiple compositors enabled. - - - -## only\_initial - -If set to on, this target pass will only execute once initially after the effect has been enabled. This could be useful to perform once-off renders, after which the static contents are used by the rest of the compositor. - -@par -Format: only\_initial (on | off) -@par -Default: only\_initial off - - - -## visibility\_mask - -Sets the visibility mask for any render\_scene passes performed in this target pass. This is a bitmask (specified as decimal or hex) and maps to Ogre::Viewport::setVisibilityMask. -@par -Format: visibility\_mask <mask> -@par -Default: visibility\_mask 0xFFFFFFFF - - - -## lod\_bias - -Set the scene LOD bias for any render\_scene passes performed in this target pass. The default is 1.0, everything below that means lower quality, higher means higher quality. -@par -Format: lod\_bias <lodbias> -@par -Default: lod\_bias 1.0 - - - -## shadows - -Sets whether shadows should be rendered during any render\_scene pass performed in this target pass. - -@par -Format: shadows (on | off) -@par -Default: shadows on - - - -## material\_scheme - -If set, indicates the material scheme to use for any render\_scene pass. Useful for performing special-case rendering effects. - -@par -Format: material\_scheme <scheme name> -@par -Default: None - -# Passes {#Compositor-Passes} - -A pass is a single rendering action to be performed in a target section. -@par -Format: pass <type> \[custom name\] { } - -There are the following types of a pass: - -
-
clear
- -This kind of pass sets the contents of one or more buffers in the target to a fixed value. So this could clear the colour buffer to a fixed colour, set the depth buffer to a certain set of contents, fill the stencil buffer with a value, or any combination of the above. - -
stencil
- -This kind of pass configures stencil operations for the subsequent passes. It can set the stencil compare function, operations and reference values for you to perform your own stencil effects. - -
render\_scene
- -This kind of pass performs a regular rendering of the scene. It will use the [visibility\_mask](#visibility_005fmask), [lod\_bias](#compositor_005flod_005fbias), and [material\_scheme](#material_005fscheme) from the parent target pass. - -
render\_quad
- -This kind of pass renders a quad over the entire render target, using a given material. You will undoubtedly want to pull in the results of other target passes into this operation to perform fullscreen effects. - -
compute
- -This kind of a pass dispatches a compute shader as attached to the given material. Compute shaders are independent from normal rendering pipeline as triggered by `render_scene` or `render_quad`. They do not have any predefined input/ outputs but rather read/ write to any buffers you attach to them. - -
render\_custom
- -This kind of pass is just a callback to user code for the composition pass specified in the custom name (and registered via Ogre::CompositorManager::registerCustomCompositionPass) and allows the user to create custom render operations for more advanced effects. This is the only pass type that requires the custom name parameter. - -
- -## render_quad & compute - -Here are the attributes you can use in the @c render_quad and @c compute sections of a .compositor script: - -- [material](#material) -- [input](#compositor_005fpass_005finput) -- [identifier](#compositor_005fpass_005fidentifier) -- [thread_groups](#thread_groups) -- [quad_normals](#quad_normals) - - - -### material - -Sets the material to be used. With `compute` passes only the compute shader is used and only global auto parameter can be accessed. -For `render_quad` you will want to use shaders in this material to perform fullscreen effects, and use the [input](#compositor_005fpass_005finput) attribute to map other texture targets into the texture bindings needed by this material. - -@par -Format: material <Name> - - - -### input - -This is how you map one or more local @ref compositor-texture into the material you’re using to render. To bind more than one texture, repeat this attribute with different texUnit indices. - -@par -Format: input <texUnit> <name> \[<mrtIndex>\] - -@param texUnit -The index of the target texture unit, must be a number in the range \[0, OGRE\_MAX\_TEXTURE\_LAYERS-1\]. -@param name -The name of the local render texture to bind, as declared by @ref compositor-texture and rendered to in one or more @ref Compositor-Target-Passes. -@param mrtIndex -If the local texture that you’re referencing is a Multiple Render Target (MRT), this identifies the surface from the MRT that you wish to reference (0 is the first surface, 1 the second etc). - -@par -Example: input 0 rt0 - - - -### identifier - -Associates a numeric identifier with a pass involving a material. This is useful for registering a listener with Ogre::CompositorInstance::addListener, and being able to identify which pass it is that’s being processed, so that material parameters can be varied. Numbers between 0 and 2^32 - 1 are allowed. - -@par -Format: identifier <number> -@par -Example: identifier 99945 -@par -Default: identifier 0 - - - -### quad_normals - -Pass the camera Frustum far corner vectors in the quad normals for passes of type `quad`. This is particularly useful for efficiently reconstructing position using only the depth and the corners. - -@par -Format: quad_normals <camera_far_corners_world_space|camera_far_corners_view_space> -@par -Default: None - - - -### thread_groups - -Passes of type `compute` operate on an abstract "compute space". This space is typically divided into threads and thread groups (work groups). The size of a thread group is defined inside the compute shader itself. This defines how many groups should be launched. - -@par -Example: if you want to process a 256x256px image and have a thread group size of 16x16x1, you want to specify `16 16 1` here as well. - -@par -Format: thread_groups <groups_x> <groups_y> <groups_z> - -## render_scene - -Here are the attributes you can use in a @c render_scene section of a .compositor script: - -- [first\_render\_queue](#first_005frender_005fqueue) -- [last\_render\_queue](#last_005frender_005fqueue) -- [material\_scheme](#compositor_005fpass_005fmaterial_005fscheme) -- [camera](#camera) - - - -### first\_render\_queue - -For passes of type ’render\_scene’, this sets the first render queue id that is included in the render. Defaults to the value of Ogre::RENDER_QUEUE_BACKGROUND. -@par -Format: first\_render\_queue <id> -@par -Default: first\_render\_queue 0 - - - -### last\_render\_queue - -For passes of type ’render\_scene’, this sets the last render queue id that is included in the render. Defaults to the value of Ogre::RENDER_QUEUE_SKIES_LATE. -@par -Format: last\_render\_queue <id> -@par -Default: last\_render\_queue 95 - - - -### material\_scheme - -If set, indicates the material scheme to use for this pass only. Useful for performing special-case rendering effects. This will overwrite any scheme set in the parent @ref Compositor-Target-Passes. -@par -Format: material\_scheme <scheme name> -@par -Default: None - - - -### camera - -Use a camera different from the output Viewport for rendering the scene into this target. Very useful for reflection effects like mirrors or water. The camera will be searched by name in the currently active scene and must be created prior to activating the compositor. - -The optional parameter @c align_to_face automatically rotates the camera towards the target cubemap face, when rendering to a cubic texture. - -@par -Format: camera <name> [<align_to_face>] -@par -Default: None - -## clear {#Clear-Section} - -For passes of type ’clear’, this section defines the buffer clearing parameters. - -@par -Format: pass clear { } - -Here are the attributes you can use in a ’clear’ section of a .compositor script: - -- [buffers](#compositor_005fclear_005fbuffers) -- [colour\_value](#compositor_005fclear_005fcolour_005fvalue) -- [depth\_value](#compositor_005fclear_005fdepth_005fvalue) -- [stencil\_value](#compositor_005fclear_005fstencil_005fvalue) - - ### buffers - - Sets the buffers cleared by this pass. - - @par - Format: buffers \[colour\] \[depth\] \[stencil\] - @par - Default: buffers colour depth - - - - ### colour\_value - - Set the colour used to fill the colour buffer by this pass, if the colour buffer is being cleared - @par - Format: colour\_value (<red> <green> <blue> <alpha> | auto) - @par - Default: colour\_value 0 0 0 0 - - If set to `auto` the background colour of the viewport is used, to which the parent compositor is attached to. - - - - ### depth\_value - - Set the depth value used to fill the depth buffer by this pass, if the depth buffer is being cleared - @par - Format: depth\_value <depth> - @par - Default: depth\_value 1.0 - - - - ### stencil\_value - - Set the stencil value used to fill the stencil buffer by this pass, if the stencil buffer is being cleared - @par - Format: stencil\_value <value> - @par - Default: stencil\_value 0.0 - -## stencil {#Stencil-Section} - -For passes of type ’stencil’, this section defines the stencil operation parameters. - -@par -Format: pass stencil { } - -@copydetails Ogre::StencilState - -Here are the attributes you can use in a ’stencil’ section of a .compositor script: - -- [check](#compositor_005fstencil_005fcheck) -- [comp\_func](#compositor_005fstencil_005fcomp_005ffunc) -- [ref\_value](#compositor_005fstencil_005fref_005fvalue) -- [mask](#compositor_005fstencil_005fmask) -- [fail\_op](#compositor_005fstencil_005ffail_005fop) -- [depth\_fail\_op](#compositor_005fstencil_005fdepth_005ffail_005fop) -- [pass\_op](#compositor_005fstencil_005fpass_005fop) -- [two\_sided](#compositor_005fstencil_005ftwo_005fsided) - - ### check - - Enables or disables the stencil check. The rest of the options in this section do nothing if the stencil check is off. - @par - Format: check (on | off) - - - - ### comp\_func - - @copybrief Ogre::StencilState::compareOp - - @par - Format: comp\_func <func> - @par - Default: comp\_func always\_pass - - @param func one of Ogre::CompareFunction without the `CMPF_` prefix. E.g. `CMPF_LESS_EQUAL` becomes `less_equal`. - - - - ### ref\_value - - @copybrief Ogre::StencilState::referenceValue - - @par - Format: ref\_value <value> - @par - Default: ref\_value 0.0 - - - - ### mask - - @copybrief Ogre::StencilState::compareMask - - @par - Format: mask <value> - @par - Default: mask 4294967295 - - - - ### fail\_op - - @copybrief Ogre::StencilState::stencilFailOp - - @par - Format: fail\_op <op> - @par - Default: fail\_op keep - - @param op one of Ogre::StencilOperation without the `SOP_` prefix. E.g. `SOP_INCREMENT_WRAP` becomes `increment_wrap`. - - - - ### depth\_fail\_op - - @copybrief Ogre::StencilState::depthFailOp - - @par - Format: depth\_fail\_op <op> - @par - Default: depth\_fail\_op keep - - @param op one of Ogre::StencilOperation without the `SOP_` prefix. E.g. `SOP_INCREMENT_WRAP` becomes `increment_wrap`. - - - - ### pass\_op - - @copybrief Ogre::StencilState::depthStencilPassOp - - @par - Format: pass\_op <op> - @par - Default: pass\_op keep - - @param op one of Ogre::StencilOperation without the `SOP_` prefix. E.g. `SOP_INCREMENT_WRAP` becomes `increment_wrap`. - - - - ### two\_sided - - @copybrief Ogre::StencilState::twoSidedOperation - - @par - Format: two\_sided (on | off) - @par - Default: two\_sided off - - -# Applying a Compositor {#Applying-a-Compositor} - -Adding a compositor instance to a viewport is very simple. All you need to do is: - -```cpp -Ogre::CompositorManager::getSingleton().addCompositor(viewport, compositorName); -``` - - - -Where viewport is a pointer to your viewport, and compositorName is the name of the compositor to create an instance of. By doing this, a new instance of a compositor will be added to a new compositor chain on that viewport. You can call the method multiple times to add further compositors to the chain on this viewport. By default, each compositor which is added is disabled, but you can change this state by calling: - -```cpp -Ogre::CompositorManager::getSingleton().setCompositorEnabled(viewport, compositorName, enabledOrDisabled); -``` - -For more information on defining and using compositors, see @c Sample_Compositor in the Samples area, together with the Examples.compositor script in the media area. - -# Programmatic creation {#Compositor-API} - -In case you need to create Compositors programmatically, see the following example for how the script is mapped to the API. - -@snippet Samples/Media/materials/scripts/Examples.compositor glass_script - -becomes -```cpp -using namespace Ogre; -CompositorPtr glass = CompositorManager::getSingleton().create("Glass", RGN_DEFAULT); - -CompositionTechnique *t = glass->createTechnique(); -auto td = t->createTextureDefinition("rt0"); -td->width = 0; -td->height = 0; -td->format = PF_BYTE_RGB; - -CompositionTargetPass *tp = t->createTargetPass(); -tp->setInputMode(CompositionTargetPass::IM_PREVIOUS); -tp->setOutputName("rt0"); - -CompositionTargetPass *tp = t->getOutputTargetPass(); -tp->setInputMode(CompositionTargetPass::IM_NONE); - -CompositionPass *pass = tp->createPass(CompositionPass::PT_RENDERQUAD) -pass->setMaterialName("Ogre/Compositor/GlassPass"); -pass->setInput(0, "rt0"); -``` - -@page Overlay-Scripts Overlay Scripts - -Overlay scripts offer you the ability to define overlays in a script which can be reused easily. Whilst you could set up all overlays for a scene in code using the methods of the SceneManager, Overlay and OverlayElement classes, in practice it’s a bit unwieldy. Instead you can store overlay definitions in text files which can then be loaded whenever required. - -To use overlays defined in `.overlay` scripts, see [Overlays](@ref Overlays). - -@tableofcontents - -```cpp -// The name of the overlay comes first -overlay MyOverlays/ANewOverlay -{ - zorder 200 - - overlay_element MyOverlayElements/TestPanel Panel - { - // Center it horizontally, put it at the top - left 0.25 - top 0 - width 0.5 - height 0.1 - material MyMaterials/APanelMaterial - - // Another panel nested in this one - overlay_element MyOverlayElements/AnotherPanel Panel - { - left 0 - top 0 - width 0.1 - height 0.1 - material MyMaterials/NestedPanel - } - } -} -``` - -The above example defines a single overlay called ’MyOverlays/ANewOverlay’, with 2 panels in it, one nested under the other. It uses relative metrics (the default if no metrics\_mode option is found). - -The overlay itself only has a single property ’zorder’ which determines how ’high’ it is in the stack of overlays if more than one is displayed at the same time. Overlays with higher zorder values are displayed on top. - -# Adding elements to the overlay {#Adding-elements-to-the-overlay} - -Within an overlay, you can include any number of 2D or 3D elements. You do this by defining nested ’overlay_element’ blocks. - -@note Top level overlay components must derive from Ogre::OverlayContainer - e.g. you must place @ref TextArea into a @ref Panel component to be able to add it to the overlay. - -## ’overlay_element’ blocks - -These are delimited by curly braces. The format for the header preceding the first brace is: - -@par -Format: overlay_element <instance\_name> <type\_name> \[: <template\_name>\] - -@param type_name -Must resolve to the name of a Ogre::OverlayElement type which has been registered with the Ogre::OverlayManager. Plugins register with the OverlayManager to advertise their ability to create elements, and at this time advertise the name of the type. OGRE comes preconfigured with types @ref Panel, @ref BorderPanel and @ref TextArea. - -@param instance_name -Must be a name unique among all other elements / containers by which to identify the element. Note that you can obtain a pointer to any named element by calling OverlayManager::getSingleton().getOverlayElement(name). - -@param template_name Optional template on which to base this item. See @ref Templates. - - -The properties which can be included within the braces depend on the custom type. However the following are always valid: - -- [metrics\_mode](#metrics_005fmode) -- [horz\_align](#horz_005falign) -- [vert\_align](#vert_005falign) -- [left](#left) -- [top](#overlaytopelement) -- [width](#width) -- [height](#height) -- [material](#overlay_005fmaterial) -- [caption](#caption) - -# Templates {#Templates} - -You can use templates to create numerous elements with the same properties. A template is an abstract element and it is not added to an overlay. It acts as a base class that elements can inherit and get its default properties. The template element is created in the topmost scope - it is NOT specified in an Overlay. It is recommended that you define templates in a separate overlay though this is not essential. Having templates defined in a separate file will allow different look & feels to be easily substituted. - -Elements can inherit a template in a similar way to C++ inheritance - by using the : operator on the element definition. The : operator is placed after the closing bracket of the name (separated by a space). The name of the template to inherit is then placed after the : operator (also separated by a space). - -A template can contain template children which are created when the template is subclassed and instantiated. - -```cpp -overlay_element MyTemplates/BasicBorderPanel BorderPanel -{ - left 0 - top 0 - width 1 - height 1 - -// setup the texture UVs for a borderpanel - -// do this in a template so it doesn't need to be redone everywhere - material Core/StatsBlockCenter - border_size 0.05 0.05 0.06665 0.06665 - border_material Core/StatsBlockBorder - border_topleft_uv 0.0000 1.0000 0.1914 0.7969 - border_top_uv 0.1914 1.0000 0.8086 0.7969 - border_topright_uv 0.8086 1.0000 1.0000 0.7969 - border_left_uv 0.0000 0.7969 0.1914 0.2148 - border_right_uv 0.8086 0.7969 1.0000 0.2148 - border_bottomleft_uv 0.0000 0.2148 0.1914 0.0000 - border_bottom_uv 0.1914 0.2148 0.8086 0.0000 - border_bottomright_uv 0.8086 0.2148 1.0000 0.0000 -} -overlay_element MyTemplates/BasicButton Button : MyTemplates/BasicBorderPanel -{ - left 0.82 - top 0.45 - width 0.16 - height 0.13 - material Core/StatsBlockCenter - border_up_material Core/StatsBlockBorder/Up - border_down_material Core/StatsBlockBorder/Down -} -overlay_element MyTemplates/BasicText TextArea -{ - font_name Ogre - char_height 0.08 - colour_top 1 1 0 - colour_bottom 1 0.2 0.2 - left 0.03 - top 0.02 - width 0.12 - height 0.09 -} - -overlay MyOverlays/AnotherOverlay -{ - zorder 490 - overlay_element MyElements/BackPanel BorderPanel : MyTemplates/BasicBorderPanel - { - left 0 - top 0 - width 1 - height 1 - - overlay_element MyElements/HostButton Button : MyTemplates/BasicButton - { - left 0.82 - top 0.45 - caption MyTemplates/BasicText HOST - } - - overlay_element MyElements/JoinButton Button : MyTemplates/BasicButton - { - left 0.82 - top 0.60 - caption MyTemplates/BasicText JOIN - } - } -} -``` - -The above example uses templates to define a button. Note that the button template inherits from the borderPanel template. This reduces the number of attributes needed to instantiate a button. - -Also note that the instantiate of a Button needs a template name for the caption attribute. So templates can also be used by elements that need dynamic creation of children elements (the button creates a TextAreaElement in this case for its caption). - -See [OverlayElement Attributes](#OverlayElement-Attributes), [Standard OverlayElements](#Standard-OverlayElements) - - - - - -## OverlayElement Attributes - -These attributes are valid within the braces of a ’container’ or ’element’ block in an overlay script. They must each be on their own line. Ordering is unimportant. - - - -## metrics\_mode - -Sets the units which will be used to size and position this element. - -@par -Format: metrics\_mode <pixels|relative>
Example: metrics\_mode pixels
- -This can be used to change the way that all measurement attributes in the rest of this element are interpreted. In relative mode, they are interpreted as being a parametric value from 0 to 1, as a proportion of the width / height of the screen. In pixels mode, they are simply pixel offsets. -@par -Default: metrics\_mode relative
- - - -## horz\_align - -Sets the horizontal alignment of this element, in terms of where the horizontal origin is. -@par -Format: horz\_align <left|center|right>
Example: horz\_align center - -This can be used to change where the origin is deemed to be for the purposes of any horizontal positioning attributes of this element. By default the origin is deemed to be the left edge of the screen, but if you change this you can center or right-align your elements. Note that setting the alignment to center or right does not automatically force your elements to appear in the center or the right edge, you just have to treat that point as the origin and adjust your coordinates appropriately. This is more flexible because you can choose to position your element anywhere relative to that origin. For example, if your element was 10 pixels wide, you would use a ’left’ property of -10 to align it exactly to the right edge, or -20 to leave a gap but still make it stick to the right edge. - -Note that you can use this property in both relative and pixel modes, but it is most useful in pixel mode. -@par -Default: horz\_align left
- - - -## vert\_align - -Sets the vertical alignment of this element, in terms of where the vertical origin is. -@par -Format: vert\_align <top|center|bottom>
Example: vert\_align center - -This can be used to change where the origin is deemed to be for the purposes of any vertical positioning attributes of this element. By default the origin is deemed to be the top edge of the screen, but if you change this you can center or bottom-align your elements. Note that setting the alignment to center or bottom does not automatically force your elements to appear in the center or the bottom edge, you just have to treat that point as the origin and adjust your coordinates appropriately. This is more flexible because you can choose to position your element anywhere relative to that origin. For example, if your element was 50 pixels high, you would use a ’top’ property of -50 to align it exactly to the bottom edge, or -70 to leave a gap but still make it stick to the bottom edge. - -Note that you can use this property in both relative and pixel modes, but it is most useful in pixel mode. -@par -Default: vert\_align top
- - - -## left - -Sets the horizontal position of the element relative to it’s parent. -@par -Format: left <value>
Example: left 0.5 - -Positions are relative to the parent (the top-left of the screen if the parent is an overlay, the top-left of the parent otherwise) and are expressed in terms of a proportion of screen size. Therefore 0.5 is half-way across the screen. -@par -Default: left 0
- - - -## top - -Sets the vertical position of the element relative to it’s parent. -@par -Format: top <value>
Example: top 0.5 - -Positions are relative to the parent (the top-left of the screen if the parent is an overlay, the top-left of the parent otherwise) and are expressed in terms of a proportion of screen size. Therefore 0.5 is half-way down the screen. -@par -Default: top 0
- - - -## width - -Sets the width of the element as a proportion of the size of the screen. -@par -Format: width <value>
Example: width 0.25 - -Sizes are relative to the size of the screen, so 0.25 is a quarter of the screen. Sizes are not relative to the parent; this is common in windowing systems where the top and left are relative but the size is absolute. -@par -Default: width 1
- - - -## height - -Sets the height of the element as a proportion of the size of the screen. -@par -Format: height <value>
Example: height 0.25 - -Sizes are relative to the size of the screen, so 0.25 is a quarter of the screen. Sizes are not relative to the parent; this is common in windowing systems where the top and left are relative but the size is absolute. -@par -Default: height 1
- - - -## material - -Sets the name of the material to use for this element. -@par -Format: material <name>
Example: material Examples/TestMaterial - -This sets the base material which this element will use. Each type of element may interpret this differently; for example the OGRE element ’Panel’ treats this as the background of the panel, whilst ’BorderPanel’ interprets this as the material for the center area only. Materials should be defined in .material scripts. Note that using a material in an overlay element automatically disables lighting and depth checking on this material. Therefore you should not use the same material as is used for real 3D objects for an overlay. -@par -Default: none
- - - -## caption - -Sets a text caption for the element. -@par -Format: caption <string>
Example: caption This is a caption - -Not all elements support captions, so each element is free to disregard this if it wants. However, a general text caption is so common to many elements that it is included in the generic interface to make it simpler to use. This is a common feature in GUI systems. -@par -Default: blank - - - -## rotation - -Sets the rotation of the element. -@par -Format: rotation <angle\_in\_degrees> <axis\_x> <axis\_y> <axis\_z> Example: rotation 30 0 0 1 -@par -Default: none - -# Standard OverlayElements {#Standard-OverlayElements} - -Although OGRE’s Ogre::OverlayElement and Ogre::OverlayContainer classes are designed to be extended by applications developers, there are a few elements which come as standard with Ogre. These include: - -- @ref Panel -- @ref BorderPanel -- @ref TextArea - -This section describes how you define their custom attributes in an .overlay script, but you can also change these custom properties in code if you wish. You do this by calling setParameter(param, value). You may wish to use the StringConverter class to convert your types to and from strings. - -## Panel (container) {#Panel} - -This is the most bog-standard container you can use. It is a rectangular area which can contain other elements (or containers) and may or may not have a background, which can be tiled however you like. The background material is determined by the material attribute, but is only displayed if transparency is off. - -@param transparent <true | false> If set to ’true’ the panel is transparent and is not rendered itself, it is just used as a grouping level for it’s children. - -@param tiling <layer> <x\_tile> <y\_tile> Sets the number of times the texture(s) of the material are tiled across the panel in the x and y direction. <layer> is the texture layer, from 0 to the number of texture layers in the material minus one. By setting tiling per layer you can create some nice multitextured backdrops for your panels, this works especially well when you animate one of the layers. - -@param uv\_coords <topleft\_u> <topleft\_v> <bottomright\_u> <bottomright\_v> Sets the texture coordinates to use for this panel. - -## BorderPanel (container) {#BorderPanel} - -This is a slightly more advanced version of Panel, where instead of just a single flat panel, the panel has a separate border which resizes with the panel. It does this by taking an approach very similar to the use of HTML tables for bordered content: the panel is rendered as 9 square areas, with the center area being rendered with the main material (as with Panel) and the outer 8 areas (the 4 corners and the 4 edges) rendered with a separate border material. The advantage of rendering the corners separately from the edges is that the edge textures can be designed so that they can be stretched without distorting them, meaning the single texture can serve any size panel. - -@param border\_size <left> <right> <top> <bottom> The size of the border at each edge, as a proportion of the size of the screen. This lets you have different size borders at each edge if you like, or you can use the same value 4 times to create a constant size border. - -@param border\_material <name> The name of the material to use for the border. This is normally a different material to the one used for the center area, because the center area is often tiled which means you can’t put border areas in there. You must put all the images you need for all the corners and the sides into a single texture. - -@param border\_topleft\_uv <u1> <v1> <u2> <v2> \[also border\_topright\_uv, border\_bottomleft\_uv, border\_bottomright\_uv\]; The texture coordinates to be used for the corner areas of the border. 4 coordinates are required, 2 for the top-left corner of the square, 2 for the bottom-right of the square. - -@param border\_left\_uv <u1> <v1> <u2> <v2> \[also border\_right\_uv, border\_top\_uv, border\_bottom\_uv\]; The texture coordinates to be used for the edge areas of the border. 4 coordinates are required, 2 for the top-left corner, 2 for the bottom-right. Note that you should design the texture so that the left & right edges can be stretched / squashed vertically and the top and bottom edges can be stretched / squashed horizontally without detrimental effects. - -## TextArea (element) {#TextArea} - -This is a generic element that you can use to render text. It uses fonts which can be defined in code using the FontManager and Font classes, or which have been predefined in .fontdef files. See the font definitions section for more information. - -@param font\_name <name> The name of the font to use. This font must be defined in a .fontdef file to ensure it is available at scripting time. - -@param char\_height <height> The height of the letters as a proportion of the screen height. Character widths may vary because OGRE supports proportional fonts, but will be based on this constant height. - -@param colour <red> <green> <blue> A solid colour to render the text in. Often fonts are defined in monochrome, so this allows you to colour them in nicely and use the same texture for multiple different coloured text areas. The colour elements should all be expressed as values between 0 and 1. If you use predrawn fonts which are already full colour then you don’t need this. - -@param colour\_bottom <red> <green> <blue> -@param colour\_top <red> <green> <blue> As an alternative to a solid colour, you can colour the text differently at the top and bottom to create a gradient colour effect which can be very effective. - -@param alignment <left | center | right> Sets the horizontal alignment of the text. This is different from the horz\_align parameter. - -@param space\_width <width> Sets the width of a space in relation to the screen. - -@page Font-Definition-Scripts Font Definition Scripts - -%Ogre uses texture-based fonts to render the Ogre::TextAreaOverlayElement. You can also use the Ogre::Font object for your own purpose if you wish. The final form of a font is a Ogre::Material object generated by the font, and a set of ’glyph’ (character) texture coordinate information. - -There are 2 ways you can get a font into OGRE: - -1. Design a font texture yourself using an art package or font generator tool -2. Ask OGRE to generate a font texture based on a truetype font - -The former gives you the most flexibility and the best performance (in terms of startup times), but the latter is convenient if you want to quickly use a font without having to generate the texture yourself. I suggest prototyping using the latter and change to the former for your final solution. - -All font definitions are held in `.fontdef` files, which are parsed by the system at startup time. Each `.fontdef` file can contain multiple font definitions. The basic format of an entry in the `.fontdef` file is: - -```cpp -font -{ - type - source - ... - ... custom attributes depending on type -} -``` - - - -# Using an existing font texture - -If you have one or more artists working with you, no doubt they can produce you a very nice font texture. OGRE supports full colour font textures, or alternatively you can keep them monochrome / greyscale and use TextArea’s colouring feature. Font textures should always have an alpha channel, preferably an 8-bit alpha channel such as that supported by TGA and PNG files, because it can result in much nicer edges. To use an existing texture, here are the settings you need: - -@param type image This just tells OGRE you want a pre-drawn font. - -@param source <filename> This is the name of the image file you want to load. This will be loaded from the standard resource locations and can be of any type OGRE supports, although JPEG is not recommended because of the lack of alpha and the lossy compression. I recommend PNG format which has both good lossless compression and an 8-bit alpha channel. - -@param glyph <character> <u1> <v1> <u2> <v2> This provides the texture coordinates for the specified character. You must repeat this for every character you have in the texture. The first 2 numbers are the x and y of the top-left corner, the second two are the x and y of the bottom-right corner. Note that you really should use a common height for all characters, but widths can vary because of proportional fonts. -’character’ is either an ASCII character for non-extended 7-bit ASCII, or for extended glyphs, a unicode decimal value, which is identified by preceding the number with a ’u’ - e.g. ’u0546’ denotes unicode value 546. - -A note for Windows users: I recommend using [BitmapFontBuilder](), a free tool which will generate a texture and export character widths for you, you can find a tool for converting the binary output from this into ’glyph’ lines in the Tools folder.
- - - -# Generating a font texture - -You can also generate font textures on the fly using truetype fonts. I don’t recommend heavy use of this in production work because rendering the texture can take a several seconds per font which adds to the loading times. However it is a very nice way of quickly getting text output in a font of your choice. - -Here are the attributes you need to supply: - -@param type truetype Tells OGRE to generate the texture from a font - -@param source <ttf file> The name of the ttf file to load. This will be searched for in the common resource locations. - -@param size <size\_in\_points> The size at which to generate the font in points. This is the value that you would select in e.g. Word. This only affects how big the characters are in the font texture, not how big they are on the screen. You should tailor this depending on how large you expect to render the fonts because generating a large texture will result in blurry characters when they are scaled very small, and conversely generating a small font will result in blocky characters if large text is rendered. - -@param resolution <dpi> The resolution in dots per inch, which is used in conjunction with the point size to determine the final texture size. Typical values are 72 / 96 dpi. This should match the dpi of the screen, given that the glyps occupy `size` points after projection (i.e. in screen-space). - -@param code\_points nn-nn \[nn-nn\] .. This directive allows you to specify which unicode code points should be generated as glyphs into the font texture. If you don’t specify this, code points 32-126 will be generated by default which covers the ASCII glyphs. If you use this flag, you should specify a space-separated list of inclusive code point ranges of the form ’start-end’. Numbers must be decimal. - -You can also create new fonts at runtime by using the FontManager if you wish. diff --git a/Docs/src/sm-redesign/WorldUpdate.odt b/Docs/src/sm-redesign/WorldUpdate.odt deleted file mode 100644 index 3575bedfd86..00000000000 Binary files a/Docs/src/sm-redesign/WorldUpdate.odt and /dev/null differ diff --git a/Docs/src/tutorials/CreateShaderBasedTech.svg b/Docs/src/tutorials/CreateShaderBasedTech.svg deleted file mode 100644 index 3d9bcdd2924..00000000000 --- a/Docs/src/tutorials/CreateShaderBasedTech.svg +++ /dev/null @@ -1 +0,0 @@ -ApplicationShaderGeneratorSGMaterialSGTechniqueSGSchemecreateShaderBasedTechnique<< new >><< new >>addTechnique(tech)<< new >>addTechniqueEntry(tech) \ No newline at end of file diff --git a/Docs/src/tutorials/DeferredCone.jpg b/Docs/src/tutorials/DeferredCone.jpg deleted file mode 100644 index 19d83cfc81a..00000000000 Binary files a/Docs/src/tutorials/DeferredCone.jpg and /dev/null differ diff --git a/Docs/src/tutorials/GBufferRenderdoc.jpg b/Docs/src/tutorials/GBufferRenderdoc.jpg deleted file mode 100644 index 73e1b69f774..00000000000 Binary files a/Docs/src/tutorials/GBufferRenderdoc.jpg and /dev/null differ diff --git a/Docs/src/tutorials/Gui2.jpg b/Docs/src/tutorials/Gui2.jpg deleted file mode 100644 index 2e0160fc691..00000000000 Binary files a/Docs/src/tutorials/Gui2.jpg and /dev/null differ diff --git a/Docs/src/tutorials/RuntimeShaderGeneration.svg b/Docs/src/tutorials/RuntimeShaderGeneration.svg deleted file mode 100644 index b50508ecc9f..00000000000 --- a/Docs/src/tutorials/RuntimeShaderGeneration.svg +++ /dev/null @@ -1,35 +0,0 @@ -ShaderGeneratorSGSchemeSGTechniqeSGPassTargetRenderStateProgramManagervalidatesyncWithScenebuildRenderStatebuildRenderState<< new >>loop[globalRenderState]addSubRenderStateacquirePrograms(Pass)createCpuProgramscreateGpuProgramshash(source)GpuProgramPtrbindUniformParameters \ No newline at end of file diff --git a/Docs/src/tutorials/background-resource.md b/Docs/src/tutorials/background-resource.md deleted file mode 100644 index da41d1248e2..00000000000 --- a/Docs/src/tutorials/background-resource.md +++ /dev/null @@ -1,36 +0,0 @@ -# Background Resource Loading {#background-resource} - -%Ogre uses thread pool based concurrency, where a fixed number of persistent worker threads are used to process incoming jobs. -The worker threads are organized in [WorkQueues](@ref Ogre::WorkQueue), which allows implementing load-balancing. - -By default %Ogre creates one Ogre::WorkQueue, implementing Ogre::DefaultWorkQueueBase with 1-2 workers attached. The workers are started after the first Ogre::RenderWindow is created. -You can customize the default work queue by calling Ogre::DefaultWorkQueueBase::setWorkerThreadCount and Ogre::DefaultWorkQueueBase::setWorkersCanAccessRenderSystem before the WorkQueue is started or later by manually restarting the WorkQueue. - -For resource loading, there is additionally the high-level Ogre::ResourceBackgroundQueue interface, that dispatches work to the default WorkQueue, but hides the internal Ogre::WorkQueue::Request/ Ogre::WorkQueue::Response handling. - -To prepare a Texture in the background you can do: -```cpp -Ogre::TexturePtr tex = ...; -Ogre::ResourceBackgroundQueue& rbq = Ogre::ResourceBackgroundQueue::getSingleton(); -std::future fut = rbq.prepare(tex); -``` - -the returned std::future can be used to poll whether it is finished via std::future::wait_for. -However, the preferred way to get notified about the operation being completed is to register a Ogre::Resource::Listener. - -In the default build config, background workers cannot access the Ogre::RenderSystem to avoid the overhead incurred by the underlying APIs. -Therefore, only Ogre::Resource::prepare can be called by a worker, while Ogre::Resource::load must be done on the main thread. - -@note This makes calls to Ogre::Resource::setBackgroundLoaded obsolete as they cause Resources to ignore load() calls from the main thread, enforcing that they are loaded from a Worker thread. - -The table below shows an overview what the prepared and loaded states mean for different resource types. - -| Type | Prepared | Loaded | -| -------- | ----------- | --------| -| Mesh | read file to memory | parsed and uploaded to GPU | -| Material | prepared and compiled supported techniques | supported techniques loaded | -| Texture | read and decoded images | uploaded to GPU | -| GpuProgram (HLSL) | read source and compiled microcode | uploaded to GPU and created buffers | -| GpuProgram (GLSL) | read and preprocessed source | compiled and uploaded to GPU | -| Compositor | - | compiled supported techniques and created textures | -| Skeleton | read and parsed animation | - | \ No newline at end of file diff --git a/Docs/src/tutorials/basictutorials/basictutorial1.md b/Docs/src/tutorials/basictutorials/basictutorial1.md deleted file mode 100644 index 633e1175ca6..00000000000 --- a/Docs/src/tutorials/basictutorials/basictutorial1.md +++ /dev/null @@ -1,205 +0,0 @@ -# Your First Scene {#tut_FirstScene} - -@tableofcontents - -This first tutorial will cover the basic elements of building a scene in Ogre. The primary focus will be the Ogre::SceneManager, Ogre::SceneNode, and Ogre::Entity. An Entity is anything represented by a mesh. A Ogre::SceneNode is what attaches an object to your scene. Finally, the SceneManager is the object that organizes everything. It keeps track of the entities and nodes in your scene and determines how to display them. - -We'll start with an explanation of some of the basic concepts in Ogre. Don't worry, this first tutorial has a little more explanation than the rest, but that changes very quickly once you get to the later tutorials. We will be building plenty of things. We just have to lay a little groundwork first, so you have somewhere to stand. - -The full source for this tutorial can be found in samples directory **Samples/Tutorials/BasicTutorial1.cpp**. - -@note Refer to @ref setup for instructions how set up an Ogre project and compile it successfully. - -# How Ogre Works {#howogreworks} -We are going to provide a quick introduction to the basic elements of an Ogre scene. - -## SceneManager {#scenemanager} - -Everything that appears on the screen is managed by the Ogre::SceneManager. The SceneManager keeps track of the locations and other attributes of the objects in your scene. The SceneManager also manages any cameras that you add to your scene. There are multiples types of SceneManagers. They differ in how they partition the scene for culling and searching nodes. There are managers implementing the [Octtree](https://en.wikipedia.org/wiki/Octree) scheme and others using portals. For now, you can use the default SceneManager, which is best suited for scenes where most of the objects are visible most of the time. - -[//]: <> (TODO: Move content of the link into manual pages as well) - -## SceneNode {#SceneNode} - -SceneNodes carry information that is used for all of the objects that are attached to it. An Entity is not rendered in your scene until it is attached to a SceneNode. In addition, a SceneNode is not a visible object in your scene. It only holds abstract information like location and orientation. Only when it is connected to something like an Entity is that information used to actually render something in the scene. - -SceneNodes can have more than one object attached to them. We may want to have a light that will follow a character around in a scene. To do this, we could attach both the character Entity and the light to the same SceneNode. This will cause them both to share the same location information. We can even attach SceneNodes to other SceneNodes. This is useful in many circumstances. Imagine you have a character and you want to attach a tool to their hand. You wouldn't want to attach the tool to SceneNode for the entire character. Instead, you could attach a SceneNode representing their hand to the character's main SceneNode, and then attach the tool Entity to that "child" SceneNode. more complicated uses of SceneNodes will be covered in later tutorials. - -One final thing to keep in mind about SceneNodes is that their position is relative to their parent SceneNode and each SceneManager creates a root Node to which all other SceneNodes are attached. - -## Entity {#Entity} - -An Entity is one type of object that you can render in your scene. It is anything that is represented by a 3D mesh. Even terrain objects are very large entities. Lights, Billboards, Particles, and Cameras are examples of scene elements that are not entities. Ogre uses a well-known design pattern that separates renderable objects from information like their location. This means that you don't directly place an Entity into your scene. Instead, you place a SceneNode into your scene, then attach your Entity to that SceneNode. The Entity is then rendered using information taken from the SceneNode. - -# Setting Up the Scene {#SettingUptheScene} - -It's finally time to start building something in our scene. All source addition will be in "tutorial section" in cpp file of the tutorial TutorialApplication::setup method. - -The first thing we want to do is turn on the lights. - -@snippet Samples/Tutorials/BasicTutorial1.cpp turnlights - -The setAmbientLight method takes an Ogre::ColourValue. The three values represent the red, green, and blue values of the colour, and they range between 0 and 1. - -scnMgr is a variable that is defined in OgreBites::ApplicationContext. There are a number of features available, like setting up resources and initialization of required routines for rendering. They will be introduced as we need them. - -Lights will be covered in detail in the next tutorial, but we will still add a simple one to this scene as a teaser. New Light objects can also be requested from the Ogre::SceneManager. We give the Light a unique name when it is created. - -@snippet Samples/Tutorials/BasicTutorial1.cpp newlight - -Once the Light is created and attached to its SceneNode, we set its position. The three parameters are the x, y, and z coordinates of the location we want to place the Light. - -@snippet Samples/Tutorials/BasicTutorial1.cpp lightpos - -Next step is to create a camera. - -@snippet Samples/Tutorials/BasicTutorial1.cpp camera - -Details about camera will be covered in the following tutorial. - -The next thing we do is ask the SceneManager to create an Entity. - -@snippet Samples/Tutorials/BasicTutorial1.cpp entity1 - -The parameter given to this function must be a mesh that was loaded by Ogre's resource manager. For now, resource loading is one of the many things that OgreBites::ApplicationContext is taking care of for us. It will be explained further in later tutorials. - -Now that we have an Entity, we need to create a SceneNode so the Entity can be displayed in our scene. Every SceneManager has a root node. That node has a method called createChildSceneNode that will return a new SceneNode attached to the root. In older versions of Ogre, you were required to provide a unique name for your Entities and SceneNodes. This is now optional. Ogre will generate names for them if you do not provide one. - -@snippet Samples/Tutorials/BasicTutorial1.cpp entity1node - -We save the SceneNode pointer that is returned by the method so that we can attach our Entity to it. - -@snippet Samples/Tutorials/BasicTutorial1.cpp entity1nodeattach - -We now have a basic scene set up. Compile and run your application. You should see an Ogre's head on your screen. This is only the beginning... - -![](bt1_first_run.png) - -# Coordinates Systems {#CoordinatesSystems} - -Before we go on, let's cover some basics of Ogre's coordinate system. Ogre, like many other graphics engines, uses the x-z plane as the "floor" in a scene. This means that the y-axis is the vertical axis to ensure Ogre is using a [right-handed coordinate system](https://en.wikipedia.org/wiki/Right-hand_rule) - -![](bt1_display1921.png) - -The x-axis starts with negative values to the left and increases to the right (passing through zero at the origin). The z-axis runs forwards and backwards. The positive direction of the z-axis points "out of the screen". So if a character walks towards the screen, then its z value will be increasing. Finally, the y-axis runs from the bottom to the top. Values that are "below ground" are negative. Don't take these terms in parenthesis literally. You can put the ground wherever you want. It is just to help you orient yourself in the scene. - -When you run your application, notice how your Ogre head is facing towards the camera down the positive z-axis. This is a property of the mesh itself and the orientation of the camera. Cameras are covered in a later tutorial. The Ogre head is sitting at the origin of our world, (0, 0, 0). The direction the head is facing by default is a result of which way it was facing when it was originally modeled. You can effectively change this from within Ogre as well, but it will require some knowledge of quaternions, which aren't really covered until the [Intermediate Tutorials](#). -[//]: <> (TODO: Replace link with manual page when time has come) - -Ogre uses a vector class to represent positions and directions. There are vectors defined for 2-4 dimensions. They are called Ogre::Vector2, Ogre::Vector3, and Ogre::Vector4 - Vector3 being the most commonly used by far. If you are not familiar with the concept of vectors it is highly recommended to learn a little before attempting these tutorials. Even though Ogre is an abstraction over many of the complications involved with OpenGL and DirectX, there is still no escaping some mathematical concepts. Vectors and basic linear algebra will be some of the most useful things you can learn if you intend to proceed with 3D rendering. This [site](https://paroj.github.io/gltut/Positioning/Tutorial%2006.html) has produced a nice primer on vectors focused on game programmers. - -# Adding Another Entity {#AddingAnotherEntity} - -It's time to get back to the coding. With our first Entity, we did not specify the location we wanted anywhere. Many of the functions in Ogre have default parameters. The SceneNode::createChildSceneNode(external link) method can take three parameters, but we called it with none. The parameters are the name, position, and rotation of the SceneNode being created. We've already mentioned that Ogre generates a unique name for us. It also uses (0, 0, 0) as a default position. - -First, let's move the camera so we can fit more Entities on screen. Place this call right after you set the ambient light in createScene: - -@snippet Samples/Tutorials/BasicTutorial1.cpp cameramove - -Now, let's create another Entity and SceneNode, but this time we'll give it a new position. - -@snippet Samples/Tutorials/BasicTutorial1.cpp entity2 - -This is the same thing we did the first time, except we are now providing a Vector3 to our createChildSceneNode method. This will override the default position. Remember, the SceneNode's position is always relative to its parent. In this case, the parent SceneNode is the root SceneNode, which is positioned at (0, 0, 0) by default. - -Compile and run your application. Your Ogre head should have a buddy. - -![](bt1_added_entity.png) - -# More About Entities {#MoreAboutEntities} - -The Ogre::Entity class is very extensive. We will now introduce just a few more of its methods that will be useful. The Entity class has setVisible and isVisible methods. If you want an Entity to be hidden, but you still need it later, then you can use this function instead of destroying the Entity and rebuilding it later. - -@note Entities do not need to be pooled like they are in some graphics engines. Only one copy of each mesh and texture is ever loaded into memory, so there is not a big savings from trying to minimize the number of Entities. - -The getName method returns the name of an Entity, and the getParentSceneNode method returns the SceneNode that the Entity is attached to. In our case, this would be the root SceneNode. - -# More About SceneNodes {#MoreAboutSceneNodes} - -The Ogre::SceneNode class is very complex. For now, we will only cover some of the most useful methods. - -You can set the position after creating the node with setPosition. This is still relative to its parent node. You can move an objective relative to its current position by using translate. - -SceneNodes are used to set a lot more than just position. They also manage the scale and rotation of objects. You can set the scale of an object with setScale. And you can use yaw, pitch, and roll to set the object's orientation. You can use resetRotation to return the object to its default orientation. Finally, you can use rotate to perform more complicated rotations. This will again involve the use of quaternions, which will not be covered until the [Intermediate Tutorials](#). - -[//]: <> (TODO: Replace link with manual page when time has come) - -We've already used the attachObject method of a SceneNode. There are few more methods that are useful for dealing with the objects that are attached to a SceneNode. You can use numAttachedObjects to return the number of children attached to your node. You can use one of the many versions of Ogre::SceneNode::getAttachedObject to retrieve one of the SceneNode's children. The method detachObject can be used to remove a specific child node, and detachAllObjects can be used to remove all. - -Since the position of a child node is relative to its parent, it makes it very easy to move large groups of nodes together. For example, if we changed this line: - -```cpp -Ogre::SceneNode* ogreNode2 = scnMgr->getRootSceneNode()->createChildSceneNode(Ogre::Vector3(84, 48, 0)); -``` - -To this: - -```cpp -Ogre::SceneNode* ogreNode2 = ogreNode->createChildSceneNode(Ogre::Vector3(84, 48, 0)); -``` - -Then our new node would be parented directly to the SceneNode for our first Entity. This would mean that moving ogreNode would also move ogreNode2. It would also mean that the position of ogreNode2 would be relative to ogreNode. - -If you're having trouble with the idea of a relative location, then maybe an example will help. Let's say we put our first node, ogreNode, at (10, 10, 10) and attach ogreNode2 directly to ogreNode. Then we set the position of ogreNode2 to be (-10, -10, -10). To figure out where ogreNode2 will be displayed we add its position to the position of its parent. - -``` -(10, 10, 10) + (-10, -10, -10) = (0, 0, 0) - ogreNode ogreNode2 - parent child -``` - -So this means that ogreNode2 would actually be placed at (0, 0, 0) in our world, even though we set its position to (-10, -10, -10). If we detached this node and reattached it to the root SceneNode, then it would really be displayed at (-10, -10, -10), because: - -``` -(0, 0, 0) + (-10, -10, -10) = (-10, -10, -10) - root ogreNode2 - parent child -``` - -Take a few seconds to soak this in. Relativity is hard. That's why it took an Einstein to really figure it out. - -Lastly, you can get a SceneNode or Entity by its name (if you gave it one), by calling getSceneNode or getEntity, which are Ogre::SceneManager methods. This way you don't have to keep a pointer to all of your SceneNodes. You should generally only define pointers for nodes you will use often. - -# Changing An Entity's Scale {#ChangingAnEntitysScale} - -We can set the scale of an Entity by calling setScale. This method allows us to provide a scale factor for each dimension. Let's add another Ogre head and give it a different scale for demonstration. We will also position it so it fits well on the screen. - -@snippet Samples/Tutorials/BasicTutorial1.cpp entity3 - -Compile and run your application. You should see a fat Ogre head up top. - -![](bt_1scaled_entity.png) - -# Rotating An Entity {#RotatingAnEntity} - -An Entity's rotation can be changed using the yaw, pitch, and roll methods. - -![](tiki-download_file_rotation_axis.png) - -These methods will take either an Ogre::Degree or Ogre::Radian. As the picture demonstrates, rotation around the y-axis is called yaw, around the x-axis is called pitch, and around the z-axis is called roll. These are terms often used in describing the movements of an aircraft. - -There is a well-known trick for remembering which direction is a positive rotation around an axis. It is called the [right-hand rule](http://en.wikipedia.org/wiki/Right-hand_rule). Point your thumb in the direction of the axis, and the direction your fingers curl towards is the positive direction. You can now see why these are often called "right-handed coordinate systems". There are about a million ways of doing the right-hand rule. This is why you might see a group of physics students throwing gang signs while doing their homework. They're trying to remember which direction the magnetic field is headed. - -Let's put this to use and place a rotated Entity into our scene. We will also position it nicely. - -@snippet Samples/Tutorials/BasicTutorial1.cpp entity4 - -Compile and run your application. We should now have a rotated Ogre head in our scene. - -![](bt1_rotated_entity.png) - -# Plugins {#TheOgreEnvironment} - -Third-party plugins make it easy to integrate external libraries to add things like physics, input, and GUI systems. These libraries are used together to form a full game development environment. You might find this piecemeal approach a little strange, but it is a very common design pattern in large software projects. It is harder to comprehend at first, but it is a much more flexible approach when you want to start building more complicated scenes. - -The SDK includes some of these third-party libraries. The [Simple DirectMedia Layer](https://www.libsdl.org/) is used to manage input events and distribute them to Ogre. You can also make use of [Assimp](https://www.assimp.org/) through the @ref AssimpCodec. This library allows you to load many popular geometry formats like .obj. There are other libraries (not included with the SDK) that offer functionality such as sound and physics. - -## Testing vs Release - -When you're building your application you can just leave every plugin activated. This will allow you to experiment with using them or not. But when you get ready to distribute a release build of your work, then you will want to deactivate any of the plugins you are not using. - -# Conclusion {#Conclusion1} - -You should now have a basic understanding of setting up an Ogre scene. This tutorial provided an introduction to three of the most important objects in Ogre: Ogre::Entity, Ogre::SceneNode, and Ogre::SceneManager. These objects allow us to render and manipulate a scene filled with 3D objects. - -An Ogre::Entity represents anything that has an Ogre mesh. A Ogre::SceneNode is used to hold properties like location, scale, and rotation. It is also the anchor that attaches your Entities to your scene and allows them to be rendered on screen. Finally, The Ogre::SceneManager is the object that orchestrates it all. It has methods that allow you to create Entities and SceneNodes and keep them organized within a complicated scene. diff --git a/Docs/src/tutorials/basictutorials/basictutorial2.md b/Docs/src/tutorials/basictutorials/basictutorial2.md deleted file mode 100644 index ed05e988eb4..00000000000 --- a/Docs/src/tutorials/basictutorials/basictutorial2.md +++ /dev/null @@ -1,176 +0,0 @@ -# Lights, Cameras, and Shadows {#tut_LightsCamerasShadows} - -@tableofcontents - -This tutorial will expand on the use of Lights in a scene and using them to cast shadows. - -The full source for this tutorial can be found in samples directory **Samples/Tutorials/BasicTutorial2.cpp**. - -@note Refer to @ref setup for instructions how set up an Ogre project and compile it successfully. - -# The Ogre Camera Class {#bt2TheOgreCameraClass} -A Camera is the object we use to view our scene. A Ogre::Camera is a special object that must be attached to a -Ogre::SceneNode. You can then use that for movement and rotation. For example, you might want to use a SceneNode that follows a path in the sky to create an impressive aerial cutscene - -# Creating a Camera {#bt2CreatingaCamera} -We will now cover camera creation part which we just applied in previous tutorial. We remember that now we need to have SceneNode for camera. The first step will be doing is creating that SceneNode and asking the SceneManager to create a new Camera. Add the following to create SceneNode and Camera: - -@snippet Samples/Tutorials/BasicTutorial2.cpp cameracreate -You can retrieve the Camera by name using the SceneManager's getCamera method. - -Next, we will position the Camera and use a method called lookAt to set its direction using camNode. -@snippet Samples/Tutorials/BasicTutorial2.cpp cameraposition -The Ogre::SceneNode::lookAt method is very useful. It does exactly what it says. It rotates the SceneNode so that its line of sight focuses on the vector you give it. It makes the Camera "look at" the point. - -[//]: <> (TODO: add explanation about second arguemnt of lookAt method) - -The last thing we'll do (apart of attachning camera to a SceneNode) is set the near clipping distance to 5 units. This is the distance at which the Camera will no longer render any mesh. If you get very close to a mesh, this will sometimes cut the mesh and allow you to see inside of it. The alternative is filling the entire screen with a tiny, highly magnified piece of the mesh's texture. It's up to you what you want in your scene. For demonstration, we'll set it here. - -@snippet Samples/Tutorials/BasicTutorial2.cpp cameralaststep - -# Viewports {#bt2Viewports} -When dealing with multiple Cameras in a scene, the concept of a Viewport becomes very useful. We will touch on it now, because it will help you understand more about how Ogre decides which Camera to use when rendering a scene. Ogre makes it possible to have multiple SceneManagers running at the same time. It also allows you to break up the screen and use separate Cameras to render different views of a scene. This would allow the creation of things like splitscreens and minimaps. These kinds of things will be covered in later tutorials. - -There are three constructs that are crucial to understanding how Ogre renders a scene: the Camera, the SceneManager, and the RenderWindow. We have not yet covered the RenderWindow. It basically represents the whole window we are rendering to. The SceneManager will create Cameras to view the scene, and then we tell the RenderWindow where to display each Camera's view. The way we tell the RenderWindow which area of the screen to use is by giving it a Ogre::Viewport. For many circumstances, we will simply create one Camera and create a Viewport which represents the whole screen. - -## Creating a Viewport {#bt2CreatingaViewport} -Let's create a Viewport for our scene. To do this, we will use the addViewport method of the RenderWindow. -@snippet Samples/Tutorials/BasicTutorial2.cpp addviewport -getRenderWindow() is a method defined for us in OgreBites::ApplicationContext which returns Ogre::RenderWindow. - -Now let's set the background color of the Viewport. -@snippet Samples/Tutorials/BasicTutorial2.cpp viewportback - -We've set it to black because we are going to add colored lighting later, and we don't want the background color affecting how we see the lighting. - -The last thing we are going to do is set the aspect ratio of our Camera. If you are using something other than a standard full-window viewport, then failing to set this can result in a distorted scene. We will set it here for demonstration even though we are using the default aspect ratio. - -@snippet Samples/Tutorials/BasicTutorial2.cpp cameraratio - -We have retrieved the width and height from the Viewport to set the aspect ratio. As we mentioned, the default is already set to use the full screen's dimensions. - -Compile and run your application. You should still only see a black screen, just make sure it runs. - -# Building the Scene {#bt2BuildingtheScene} -Before we get to shadows and lighting, let's add some elements to our scene. Let's put a ninja right in the middle of things. Add the following code right after we set the ambient light: -@snippet Samples/Tutorials/BasicTutorial2.cpp ninja - -This should look familiar, except we are asking the mesh to cast shadows this time. And notice that we have created a child scene node and attached the ninjaEntity all in one call this time. - -We will also create something for the ninja to be standing on. We can use the Ogre::MeshManager to create meshes from scratch. We will use it to generate a textured plane to use as the ground. - -The first thing we'll do is create an abstract Plane object. This is not the mesh, it is more of a blueprint. -@snippet Samples/Tutorials/BasicTutorial2.cpp plane - -We create a plane by supplying a vector that is normal to our plane and its distance from the origin. So we have created a plane that is perpendicular to the y-axis and zero units from the origin. Here's a picture: - -![](bt2_plane_normal.png) - -There are other overloads of the Plane constructor that let us pass a second vector instead of a distance from the origin. This allows us to build any plane in 3D space we want. - -Now we'll ask the MeshManager to create us a mesh using our Plane blueprint. The MeshManager is already keeping track of the resources we loaded when initializing our application. On top of this, it can create new meshes for us. - -@snippet Samples/Tutorials/BasicTutorial2.cpp planedefine -This is a complicated method, and we're not entirely equipped to understand all of it yet. You can read through the Ogre::MeshManager class specification if you want to learn more now. Basically, we've created a new mesh called "ground" with a size of 1500x1500. - -Now we will create a new Entity using this mesh. -@snippet Samples/Tutorials/BasicTutorial2.cpp planecreate - -Be careful that you don't confuse the parameter given to createEntity for the Entity's name. It is actually the name of the mesh we just created. We're used to seeing mesh names end with '.mesh'. - -We want to tell our SceneManager not to cast shadows from our ground Entity. It would just be a waste. Don't get confused, this means the ground won't cast a shadow, it doesn't mean we can't cast shadows on to the *ground*. -@snippet Samples/Tutorials/BasicTutorial2.cpp planenoshadow - -And finally we need to give our ground a material. For now, it will be easiest to use a material from the script that Ogre includes with its samples. You should have these resources in your SDK or the source directory you downloaded to build Ogre. -@snippet Samples/Tutorials/BasicTutorial2.cpp planesetmat - -Make sure you add the texture for the material and the Examples.material script to your resource loading path. In our case, the texture is called 'rockwall.tga'. You can find the name yourself by reading the entry in the material script. - -# Using Shadows in Ogre {#bt2UsingShadowsinOgre} -Enabling shadows in Ogre is easy. The SceneManager class has a Ogre::SceneManager::setShadowTechnique method we can use. Then whenever we create an Entity, we call Ogre::Entity::setCastShadows to choose which ones will cast shadows. setShadowTechinique method takes several of different techniques. Refer to Ogre::ShadowTechnique for more details. - -Let's turn off the ambient light so we can see the full effect of our lights. Add the following changes: - -@snippet Samples/Tutorials/BasicTutorial2.cpp lightingsset - -Now the SceneManager will use shadows. Let's add some lights to see this in action. - -# Lights {#bt2Lights} -%Ogre provides different types of lights as listed in Ogre::Light::LightTypes. - -The Ogre::Light class has a wide range of properties. Two of the most important are the [diffuse](https://learn.microsoft.com/en-us/windows/win32/direct3d9/diffuse-lighting#example) and [specular](https://learn.microsoft.com/en-us/windows/win32/direct3d9/specular-lighting#example) color. Each material script defines how much specular and diffuse lighting a material reflects. These properties will be covered in some of the later tutorials. - -## Creating a Light {#CreatingaLight} -Let's add a Light to our scene. We do this by calling the Ogre::SceneManager::createLight method. Add the following code right after we finish creating the groundEntity: -@snippet Samples/Tutorials/BasicTutorial2.cpp spotlight - -We'll set the diffuse and specular colors to pure blue. -@snippet Samples/Tutorials/BasicTutorial2.cpp spotlightcolor - -Next we will set the type of the light to spotlight. - -@snippet Samples/Tutorials/BasicTutorial2.cpp spotlighttype - -The spotlight requires both a position and a direction - remember it acts like a flashlight. We'll place the spotlight above the right shoulder of the ninja shining down on him at a 45 degree angle. - -@snippet Samples/Tutorials/BasicTutorial2.cpp spotlightposrot - -![](bt2_light_dir_1.png) - -Finally, we set what is called the spotlight range. These are the angles that determine where the light fades from bright in the middle to dimmer on the outside edges. - -@snippet Samples/Tutorials/BasicTutorial2.cpp spotlightrange -Compile and run the application. You should see the shadowy blue figure of a ninja. - -![](bt2_ninja1.jpg) - -## Creating More Lights {#CreatingMoreLights} -Next we'll add a directional light to our scene. This type of light essentially simulates daylight or moonlight. The light is cast at the same angle across the entire scene equally. As before, we'll start by creating the Light and setting its type. - -@snippet Samples/Tutorials/BasicTutorial2.cpp directlight - -Now we'll set the diffuse and specular colors to a dark red. -@snippet Samples/Tutorials/BasicTutorial2.cpp directlightcolor - -Finally, we need to set the Light's direction. A directional light does not have a position because it is modeled as a point light that is infinitely far away. - -@snippet Samples/Tutorials/BasicTutorial2.cpp directlightdir - -![](bt2_light_dir_2.png) - -The Light class also defines a Ogre::Light::setAttenuation function which allows you to control how the light dissipates as you get farther away from it. After you finish this tutorial, try using this method in your scene to see how it affects your lights. - -Compile and run the application. Your ninja should now have a shadow cast behind him, and the scene should be filled with red light. - -![](bt2_ninja2.jpg) - -To complete the set, we will now add a point light to our scene. -@snippet Samples/Tutorials/BasicTutorial2.cpp pointlight - -We'll set the the specular and diffuse colors to a dark gray. - -@snippet Samples/Tutorials/BasicTutorial2.cpp pointlightcolor - -A point light has no direction. It only has a position. We will place our last light above and behind the ninja. - -@snippet Samples/Tutorials/BasicTutorial2.cpp pointlightpos - -Compile and run the application. You should see a long shadow cast in front of the ninja now. And you should see the effects of the point light brightening up the area behind the ninja. Try to think about why the colors turn out the way they do. For instance, why does the shadow behind the ninja appear to have no red at all? - -![](bt2_ninja3.jpg) - -# Shadow Types {#ShadowTypes} -Ogre supports set of different shadow types. Please refer to Ogre::ShadowTechnique enumerator for more details. - -Try experimenting with the different shadow types. There are also other shadow-related methods in the Ogre::SceneManager class that you can play with. - -Ogre does not provide soft shadows as part of the engine. You can write your own vertex and fragment programs to implement soft shadows and many other things. The Ogre Manual has a full description of @ref Shadows. - -# Conclusion {#Conclusion2} - -This tutorial introduced the use of lights and shadows into the scene. To begin, we covered how to use the MeshManager to generate meshes from scratch. We then chose which shadow type Ogre should use. Finally, we begin adding an example of each type of Light to our scene. We created a spotlight, a directional light, and a point light. You can even extend Ogre's lighting and shadow systems by writing your own vertex and fragment programs. Refer to the Ogre Manual for more details. - -There are a lot of different settings we've covered that allow you to customize how Ogre renders light and shadow. After you've finished each tutorial, it is a good idea to play around with the new tools you have. This will greatly increase your comfort level working with the library, and it is an excellent way to learn how to navigate API documentation. - - - diff --git a/Docs/src/tutorials/basictutorials/basictutorial3.md b/Docs/src/tutorials/basictutorials/basictutorial3.md deleted file mode 100644 index ac50a14d6c3..00000000000 --- a/Docs/src/tutorials/basictutorials/basictutorial3.md +++ /dev/null @@ -1,246 +0,0 @@ -# Terrain, Sky and Fog {#tut_TerrainSkyFog} - -@tableofcontents - -This tutorial will focus on rendering terrain in a scene. We will cover the basic set up that needs to be done, and we will introduce the use of lighting with terrains. We will also give a brief introduction to simulating a sky using Skyboxes, Skydomes, and Skyplanes. Finally, we will explain how to add a fog effect to the scene. - -The full source for this tutorial can be found in samples directory **Samples/Simple/include/Terrain.h**. - -@note Refer to @ref setup for instructions how set up an Ogre project and compile it successfully. - -@image html bt3_fog_visual.png width=70% - -Ignore the FPS stats in the screenshots. They were rendered on an ancient computer. - -# An Introduction to Terrain {#tut_terrain} -With older versions of %Ogre, we had to use the "Terrain Scene Manager" to render terrain in a scene. This is a separate SceneManager that runs alongside your other managers. The new Ogre Terrain Component doesn't require using a separate manager. Since %Ogre 1.7, there are two terrain components: Terrain and Paging. The Paging component is used optimize large terrains. It will be covered in later tutorials. This tutorial will focus largely on the Terrain component. - -To set up the terrain we will focus on two main classes: -- Ogre::Terrain, representing one piece of terrain and -- Ogre::TerrainGroup, holding a series of Terrain pieces. - -This separation is used for LOD (Level of Detail) rendering. LOD rendering reduces the resolution for terrain that is farther away from the camera. An individual Terrain object consists of tiles with a material mapped on to them. We will use a single TerrainGroup without paging. Paging will be covered in later tutorials. - -## Setting Up the Camera -Let's first set up our Camera. Add the following to the beginning of `setup`: - -@snippet Samples/Simple/include/Terrain.h camera_setup - -This should look familiar from the previous tutorial. - -@snippet Samples/Simple/include/Terrain.h camera_inf - -The last thing we do is to set the far clip distance to zero (which means ''no'' far clipping). -## Setting Up a Light for Our Terrain -The Terrain component can use a directional light to compute a lightmap. Let's add a Light for this purpose and add some ambient light to the scene while we're at it. - -@snippet Samples/Simple/include/Terrain.h light - -This was also covered in the previous tutorial if you're confused by any of it. The `normalise` method will make the vector's length equal to one while maintaining its direction. This is something that you will see a lot of when working with vectors. It is done to avoid extra factors showing up in calculations. -## Terrain loading overview {#bt3Overview} -Now we'll get into the actual terrain setup. First, we create TerrainGlobalOptions. - -@snippet Samples/Simple/include/Terrain.h global_opts - -This is a class that holds information for all of the terrains we might create - that is why they are called ''global'' options. It also provides a few getters and setters. There are also local options for each TerrainGroup that we will see later in this tutorial. - -Next we construct our TerrainGroup object. This will manage a grid of Terrains. - -@snippet Samples/Simple/include/Terrain.h terrain_create - -The TerrainGroup constructor takes the SceneManager as its first parameter. It then takes an alignment option, terrain size, and terrain world size. You can read the Ogre::TerrainGroup for more information. The `setFilenameConvention` allows us to choose how our terrain will be saved. Finally, we set the origin to be used for our terrain. - -The next thing we will do is call our terrain configuration method, which we will fill in soon. Make sure to pass the Light we created as a parameter. -```cpp -configureTerrainDefaults(light); -``` -The next thing we do is define our terrains and ask the TerrainGroup to load them all. - -@snippet Samples/Simple/include/Terrain.h define_loop - -We are only using a single terrain, so the method will only be called once. The for loops are just for demonstration in our case. Again, we will fill in the `defineTerrain` method soon. - -We will now initialize the blend maps for our terrain. - -@snippet Samples/Simple/include/Terrain.h init_blend - -We get a TerrainIterator from our TerrainGroup and then loop through any Terrain elements and initialize their blend maps - `initBlendMaps` will also be written soon. The `mTerrainsImported` variable will be set during the `configureTerrainDefaults` function when we complete it. - -The last thing we will do is make sure to cleanup any temporary resources that were created while configuring our terrain. - -That completes our `setupContent` method. Now we just have to complete all of the methods we jumped over. -## Terrain appearance {#bt3Appearance} -The %Ogre Terrain component has a large number of options that can be set to change how the terrain is rendered. To start out, we configure the level of detail (LOD). There are two LOD approaches in the Terrain component, one controlling the geometry and the other controlling the texture. - -@snippet Samples/Simple/include/Terrain.h configure_lod - -The first call sets the largest allowed error for geometry. It controls the distance in pixels allowed between our ideal terrain and the mesh that is created to render it. A smaller number will mean a more accurate terrain, because it will require more vertices to reduce the error. - -The second call determines the distance at which %Ogre will reduce the texture resolution. For this, %Ogre automatically creates a composite map, where the terrain textures, the blending textures and lighting information are "baked" together at a lower resolution. This way only a single texture lookup is needed when using the low LOD setting. -If you increase the distance, then %Ogre will use the high LOD setting out to a farther distance, where it computes all lighting effects per-pixel. - -In order to generate composite map correctly, we have to pass our lighting information to the terrain. - -@snippet Samples/Simple/include/Terrain.h composite_lighting - -In the first call, `getDerivedDirection` will apply all transforms by the parent SceneNodes to our Light's direction. The next two calls should be pretty self-explanatory. We simply set the ambient light and diffuse color for our terrain to match our scene lighting. - -The next thing we do is get a reference to the import settings of our TerrainGroup and set some basic values. - -@snippet Samples/Simple/include/Terrain.h import_settings - -We are not going to cover the exact meaning of these options in this tutorial. The `inputScale` determines how the heightmap image will be scaled up for the scene. We are using a somewhat large scale because our heightmap image is a 8bit grayscale bitmap, that is normalised to the `[0; 1]` range on loading. You can use floating point raw heightmaps to avoid applying any input scaling and gain a higher precision, but such images require more storage and are not supported by common image viewers. - -The last step is adding the textures our terrain will use. First, we resize the list to hold three textures. -After that, we set each texture's `worldSize` and add them to the list. - -@snippet Samples/Simple/include/Terrain.h textures - -The texture's `worldSize` determines how big each splat of texture is going to be when applied to the terrain. A smaller value will increase the resolution of the rendered texture layer because each piece will be stretched less to fill in the terrain. - -The default material generator requires two textures maps per layer: -1. one containing diffuse + specular data and -2. another containing normal + displacement data. - -It is recommended that you pre-merge your textures accordingly e.g. using [ImageMagick](https://imagemagick.org/). This way you save storage space and speed up loading. -However if you want more flexibility, you can also make %Ogre combine the images at loading accordingly as shown below - -@snippet Samples/Simple/include/Terrain.h tex_from_src - -## Defining a terrain chunk {#bt3TerrainChunk} -Now we will tackle our `defineTerrain` method. The first thing we do is ask the TerrainGroup to define a unique filename for this Terrain. -If it has already been generated, then we can call `TerrainGroup::defineTerrain` method to set up this grid location with the previously generated filename automatically. If it has not been generated, then we generate an image with `getTerrainImage` and then call a different overload of `TerrainGroup::defineTerrain` that takes a reference to our generated image. Finally, we set the `mTerrainsImported` flag to true. - -@snippet Samples/Simple/include/Terrain.h define - -You might have to look at this method for a little while to fully understand it. Make sure you notice that there are ''three'' different `defineTerrain` methods in use. One of them from TutorialApplication and two of them from TerrainGroup. -## Loading a heightmap {#bt3Heightmap} -We need to write the helper function that was used by `defineTerrain` in the last step. This will load our `terrain.png` heightmap. Make sure it has been added to one of your resource loading paths. It is also included in the Ogre Samples directory. - -@snippet Samples/Simple/include/Terrain.h heightmap - -Flipping is used to create seamless terrain so that unlimited terrain can be created using a single heightmap. If your terrain's heightmap is already seamless, then you don't need to use this trick. In our case, the flipping code is also useless, because we are using a 1x1 TerrainGroup. Flipping a 1x1 tile doesn't change anything. It is just for demonstration. -## Height based blending {#bt3Blendmap} -Finally, we will finish up our configuration methods by completing the `initBlendMaps` method. This method sets up [texture-splatting](https://en.wikipedia.org/wiki/Texture_splatting) for the different layers we defined in `configureTerrainDefaults`. For now, you should pretty much view this method as a magic. The details will not be covered in this tutorial. Basically, the method blends the textures based on the height of the terrain at that point. This is not the only way of doing blending. It's a complicated topic and sits right at the verge between Ogre and the things it tries to abstract away. - -@snippet Samples/Simple/include/Terrain.h blendmap - -## Terrain Loading Label {#bt3LoadingLabel} - -There are a number of things we will improve. We will add a label to the overlay that allows us to see when the terrain generation has finished. We will also make sure to save our terrain so that it can be reloaded instead of rebuilding it every time. Finally, we will make sure to clean up after ourselves. - -First, we need to add a data member to private section of our Sample_Terrain header. - -@snippet Samples/Simple/include/Terrain.h infolabel - -Let's construct this label in the `createFrameListener` method. - -@snippet Samples/Simple/include/Terrain.h infolabel_create - -We use the TrayManager pointer that was defined in SdkSample to request the creation of a new label. This method takes a TrayLocation, a name for the label, a caption to display, and a width. - -Next we will add logic to `frameRenderingQueued` that tracks whether the terrain is still loading or not. We will also take care of saving our terrain after it has been loaded. Add the following to `frameRenderingQueued` right after the call to the parent method: - -@snippet Samples/Simple/include/Terrain.h loading_label - -The first thing we do is determine if our terrain is still being built. If it is, then we add our Label to the tray and ask for it to be shown. Then we check to see if any new terrains have been imported. If they have, then we display text saying that the terrain is still being built. Otherwise we assume the textures are being updated. - -If the terrain is no longer being updated, then we ask the OgreBites::TrayManager to remove the our Label widget and hide the Label. We also check to see if new terrains have been imported and save them for future use. In our case, the file will be named 'terrain_00000000.dat' and it will reside in your 'bin' directory alongside your application's executable. After saving any new terrains, we reset the `mTerrainsImported` flag. - -Compile and run your application again. You should now see a Label at the top of the screen while the terrain is being built. While the terrain is loading, you will not be able to press escape to exit and your movement controls will be choppy. This is what loading screens are for in games. But if you exit and run the application a second time, then it should load the terrain file that was saved the first time. This should be a much faster process. - -![](bt3_building_terrain_label_visual.png) - -# Simulating a sky {#bt3sky} -## SkyBoxes -A SkyBox is basically a huge textured cube that surrounds all of the objects in your scene. It is one of the methods for simulating a sky. We will need six textures to cover all of the interior faces of the SkyBox. - -It is very easy to include a SkyBox in your scene. Add the following to the end of `setupContent`: - -@snippet Samples/Simple/include/Terrain.h skybox - -Compile and run your application. That's all there is to it. The SkyBox will look really grainy because we are using a rather low resolution collection of textures. - -The first parameter of this method determines whether or not to immediately enable the SkyBox. If you want to later disable the SkyBox you can call `mSceneMgr->setSkyBox(false, "")`. This disables the SkyBox. - -The third and fourth parameters to `setSkyBox` are important to understand. We have allowed them to take their default values in our call. The third parameter is the distance between the Camera and the SkyBox. Make this change to your call: -```cpp -mSceneMgr->setSkyBox(true, "Examples/SpaceSkyBox", 300); -``` -Compile and run your application. Nothing has changed. This is because the fourth parameter sets whether or not to render the SkyBox before the rest of the scene. If the SkyBox is rendered first, then no matter how close it is the rest of your scene objects will be rendered on top of it. Now try this call: -```cpp -mSceneMgr->setSkyBox(true, "Examples/SpaceSkyBox", 300, false); -``` -Compile and run your application again. This time you should definitely see something different. Only a small patch of terrain should exist below the camera. Move around and notice what is happening. The SkyBox is being rendered only 300 units away from the Camera and it is no longer being rendered before everything else. This means the SkyBox is drawn over terrain that is farther than 300 units away from the Camera. - -You can get a modest performance boost by not rendering the SkyBox first, but as you can see, you'll need to make sure not to cause strange problems like this when doing it. For the most part, leaving these additional parameters at their defaults is good enough. Although you may want to purposely use this strange culling behavior in your application. Try not to get to locked into how things are "supposed to work". If something catches your eye, then play around with it. -## SkyDomes -Another method of simulating a sky is the SkyDome. The sky texture is still applied to a huge cube that surrounds the scene, but the textures is projected in such a way that it appears to create a dome over the scene. The best way to understand this is to see it in practice. Comment out our call to `setSkyBox` and add the following line: -```cpp -mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8); -``` -Compile and run your application. Make sure to move the Camera to the edge of the terrain so you can better idea of what is being done. The main drawback to this method is that the texture won't cover the bottom face of the cube. You would need to make sure a user could not accidentally see behind the curtain. - -The first two parameters of the `setSkyDome` method are the same as `setSkyBox`. You can disable the SkyDome in the same way as well. The third parameter is the curvature for the dome projection. It is suggested to use values between 2 and 65. Lower values will produce a better effect at far distances, but higher values will cause less distortion of the texture. The fourth parameter is the number of times the texture will be tiled. This parameter is a Ogre::Real value. You can tile your texture 3.14 times if you want. The last two parameters are the distance and whether or not to draw the SkyDome first. These are the same last two parameters we had with `setSkyBox`. - -## SkyPlanes -The third method for simulating sky is rather different from the first two. This method will use a single plane. The first thing we need to do is create a Plane object. Comment out our call to `setSkyDome` and add the following: -```cpp -Ogre::Plane plane; -plane.d = 1000; -plane.normal = Ogre::Vector3::NEGATIVE_UNIT_Y; -``` -We've defined a plane by providing a distance from the origin (d) and a vector that is normal to our plane (normal). By choosing the the ''negative'' unit vector along the y-axis we have a plane that is parallel to the ground and facing downwards. - -Now we can create the SkyPlane. -```cpp -mSceneMgr->setSkyPlane(true, plane, "Examples/SpaceSkyPlane", 1500, 75); -``` -The fourth parameter is the size of the SkyPlane (1500x1500 units), and the fifth parameter is number of times to tile the texture. - -Compile and run your application. Again, the texture we are using is rather low-resolution. A high definition texture would look much better. It also doesn't tile very well. These issuse can both be fixed by using higher quality resources. The real problem is that it is very likely a user will be able to see the end of the SkyPlane as soon as they move anywhere near the edge of the terrain. For this reason, a SkyPlane is often used most in scenes that have high walls. In these cases, a SkyPlane offers a decent increase in performance over the other techniques. - -The SkyPlane has some other attributes that can be used to produce a better effect. The sixth parameter of the `setSkyPlane` method is the "renderFirst" parameter we covered for the past two methods. The seventh parameter allows us to specify a curvature for the SkyPlane. This will pull down the corners of the SkyPlane turning it into a curved surface instead of a flat plane. If we set the curvature to something other flat, we also need to set the number of segments Ogre should use to render the SkyPlane. When the SkyPlane was a flat plane, everything was one large square, but if we add curvature, then it will require a more complicated geometry. The eighth and ninth parameters to the function are the number of segments for each dimension of the plane. - -Let's test this out. Make these changes to our call: -```cpp -mSceneMgr->setSkyPlane( - true, plane, "Examples/SpaceSkyPlane", 1500, 50, true, 1.5, 150, 150); -``` -Compile and run the application. This should help the look of our SkyPlane a bit. Go to the edge of the terrain to get a better look at what was done with the curvature. -# Fog {#tut_fog} -Like practically everything in graphics programming, the fog effect in Ogre is an illusion. Ogre does not render a fog object into our scene. Instead, it simply applies a filter to our scene. This filter allows the Viewport's background color to show through our scenery to varying degrees based on the object's distance from the Camera. What this means is that your fog will have the same color has your Viewport's background color. - -There are two basic types of fog in Ogre: linear and exponential. The difference is the rate at which the fog gets thicker as you move away from the Camera. - -![](bt3_linear_exp_visual.png) - -## Adding Fog to Our Scene -We will first add linear fog to our scene. We need to make sure to set our Viewport's background color to our desired fog color. Add the following to `setupContent` right before our code for setting up the terrain: -```cpp -Ogre::ColourValue fadeColour(0.9, 0.9, 0.9); -mWindow->getViewport(0)->setBackgroundColour(fadeColour); -``` -Make sure you add this before the terrain code otherwise it won't work. If you were using more than one Viewport, then you may have to iterate through them all by using Ogre::RenderTarget::getNumViewports. - -Now we can create the fog. - -@snippet Samples/Simple/include/Terrain.h linear_fog - -The first parameter is the fog type. The second parameter is the color we used to set our Viewport's background color. The third parameter is not used for linear fog. The fourth and fifth parameters specify the beginning and the end of the range for the fog. In our example, the fog will begin at 600 units out from the Camera, and it will end at 900 units. The reason this is called linear fog is because the thickness increases between these two values in a linear fashion. Compile and run your application. - -The next type of fog is exponential fog. Like the picture suggests, exponential fog grows slowly at first and then gets dense very quickly. We do not set a range for this fog, instead we simply supply a desired density. -```cpp -mSceneMgr->setFog(Ogre::FOG_EXP, fadeColour, 0.002); -``` -Compile and run the application. You can see this creates a different kind of fog effect. It is more like a haze that fills the area surrounding the Camera. There is a variation of the exponential fog that increases at a faster rate. -```cpp -mSceneMgr->setFog(Ogre::FOG_EXP2, fadeColour, 0.002); -``` -Compile and run your application to see the difference this makes. -# Conclusion {#conclusion3} -This tutorial covered the basics of using the Ogre Terrain Component. We gave a brief overview of the setup that needs to be done to allow the importing of a terrain heightmap into our scene. We mentioned the notion of a Ogre::TerrainGroup although we only used one Ogre::Terrain object in our "group" for this tutorial. We also made sure to initialize our terrain with a directional light so that we would get specular reflections and shadows cast across our terrain. - -We also covered the different methods Ogre offers to simulate a sky in your scene. These included: SkyBoxes, SkyDomes, and SkyPlanes. Finally, we introduced Ogre's fog effects. Fog is rendered by applying a filter to our scene that allows the Viewport's background color to bleed through our scene based on distance from our Camera. - -This is a tutorial that you should spend a lot of time experimenting with. All of these features can be configured a great deal, and you can create some very convincing scenes with just what we've covered so far. diff --git a/Docs/src/tutorials/basictutorials/images/bt1_added_entity.png b/Docs/src/tutorials/basictutorials/images/bt1_added_entity.png deleted file mode 100644 index 9bb64c20661..00000000000 Binary files a/Docs/src/tutorials/basictutorials/images/bt1_added_entity.png and /dev/null differ diff --git a/Docs/src/tutorials/basictutorials/images/bt1_display1921.png b/Docs/src/tutorials/basictutorials/images/bt1_display1921.png deleted file mode 100644 index 8b21bb4084a..00000000000 Binary files a/Docs/src/tutorials/basictutorials/images/bt1_display1921.png and /dev/null differ diff --git a/Docs/src/tutorials/basictutorials/images/bt1_first_run.png b/Docs/src/tutorials/basictutorials/images/bt1_first_run.png deleted file mode 100644 index c2075c952be..00000000000 Binary files a/Docs/src/tutorials/basictutorials/images/bt1_first_run.png and /dev/null differ diff --git a/Docs/src/tutorials/basictutorials/images/bt1_rotated_entity.png b/Docs/src/tutorials/basictutorials/images/bt1_rotated_entity.png deleted file mode 100644 index a67c1103ab6..00000000000 Binary files a/Docs/src/tutorials/basictutorials/images/bt1_rotated_entity.png and /dev/null differ diff --git a/Docs/src/tutorials/basictutorials/images/bt2_light_dir_1.png b/Docs/src/tutorials/basictutorials/images/bt2_light_dir_1.png deleted file mode 100644 index 8c03e54ca6c..00000000000 Binary files a/Docs/src/tutorials/basictutorials/images/bt2_light_dir_1.png and /dev/null differ diff --git a/Docs/src/tutorials/basictutorials/images/bt2_light_dir_2.png b/Docs/src/tutorials/basictutorials/images/bt2_light_dir_2.png deleted file mode 100644 index 8ee476a39c5..00000000000 Binary files a/Docs/src/tutorials/basictutorials/images/bt2_light_dir_2.png and /dev/null differ diff --git a/Docs/src/tutorials/basictutorials/images/bt2_ninja1.jpg b/Docs/src/tutorials/basictutorials/images/bt2_ninja1.jpg deleted file mode 100644 index a0f733f15f0..00000000000 Binary files a/Docs/src/tutorials/basictutorials/images/bt2_ninja1.jpg and /dev/null differ diff --git a/Docs/src/tutorials/basictutorials/images/bt2_ninja2.jpg b/Docs/src/tutorials/basictutorials/images/bt2_ninja2.jpg deleted file mode 100644 index 294ba7a12af..00000000000 Binary files a/Docs/src/tutorials/basictutorials/images/bt2_ninja2.jpg and /dev/null differ diff --git a/Docs/src/tutorials/basictutorials/images/bt2_ninja3.jpg b/Docs/src/tutorials/basictutorials/images/bt2_ninja3.jpg deleted file mode 100644 index 25e6da1cc6b..00000000000 Binary files a/Docs/src/tutorials/basictutorials/images/bt2_ninja3.jpg and /dev/null differ diff --git a/Docs/src/tutorials/basictutorials/images/bt2_plane_normal.png b/Docs/src/tutorials/basictutorials/images/bt2_plane_normal.png deleted file mode 100644 index e19bfdcd021..00000000000 Binary files a/Docs/src/tutorials/basictutorials/images/bt2_plane_normal.png and /dev/null differ diff --git a/Docs/src/tutorials/basictutorials/images/bt3_building_terrain_label_visual.png b/Docs/src/tutorials/basictutorials/images/bt3_building_terrain_label_visual.png deleted file mode 100644 index cf0034d2867..00000000000 Binary files a/Docs/src/tutorials/basictutorials/images/bt3_building_terrain_label_visual.png and /dev/null differ diff --git a/Docs/src/tutorials/basictutorials/images/bt3_fog_visual.png b/Docs/src/tutorials/basictutorials/images/bt3_fog_visual.png deleted file mode 100644 index 1b01af17cdf..00000000000 Binary files a/Docs/src/tutorials/basictutorials/images/bt3_fog_visual.png and /dev/null differ diff --git a/Docs/src/tutorials/basictutorials/images/bt3_linear_exp_visual.png b/Docs/src/tutorials/basictutorials/images/bt3_linear_exp_visual.png deleted file mode 100644 index 0a4bab8881a..00000000000 Binary files a/Docs/src/tutorials/basictutorials/images/bt3_linear_exp_visual.png and /dev/null differ diff --git a/Docs/src/tutorials/basictutorials/images/bt_1scaled_entity.png b/Docs/src/tutorials/basictutorials/images/bt_1scaled_entity.png deleted file mode 100644 index 43c899cacc3..00000000000 Binary files a/Docs/src/tutorials/basictutorials/images/bt_1scaled_entity.png and /dev/null differ diff --git a/Docs/src/tutorials/basictutorials/images/tiki-download_file_rotation_axis.png b/Docs/src/tutorials/basictutorials/images/tiki-download_file_rotation_axis.png deleted file mode 100644 index c42722be4cd..00000000000 Binary files a/Docs/src/tutorials/basictutorials/images/tiki-download_file_rotation_axis.png and /dev/null differ diff --git a/Docs/src/tutorials/deferred.md b/Docs/src/tutorials/deferred.md deleted file mode 100644 index 4212e121135..00000000000 --- a/Docs/src/tutorials/deferred.md +++ /dev/null @@ -1,258 +0,0 @@ -# Deferred Shading {#deferred} -This tutorial is complementary to the deferred shading sample that is part of Ogre. It will reference the code quite a bit and explain some of the decisions made when implementing the deferred shading framework for the demo. - -@tableofcontents - -# What is Deferred Shading? {#what} -Deferred shading is an alternative approach to rendering 3d scenes. The classic rendering approach involves rendering each object and applying lighting passes to it. So, if an ogre head is affected by 6 lights, it will be rendered 6 times, once for each light, in order to accumulate the affection of each light. -Deferred shading takes another approach : In the beginning, all of the objects render their "lighting related info" to a texture, often called the G-Buffer. This means their colours, normals, depths and any other info that might be relevant to calculating their final colour. Afterwards, the lights in the scene are rendered as geometry (sphere for point light, cone for spotlight and full screen quad for directional light), and they use the G-buffer to calculate the colour contribution of that light to that pixel. - -See the links in @ref further to read more about it. It is recommended to understand deferred shading before reading this article, as the article focuses on implementing it in ogre, and not explaining how it works. - -## Deferred Shading Advantages -The main reason for using deferred shading is performance related. Classing rendering (also called forward rendering) can, in the worst case, require num_objects * num_lights batches to render a scene. Deferred shading changes that to num_objects + num_lights, which can often be a lot less. -Another reason is that some new post-processing effects are easily achievable using the G-Buffer as input. If you wanted to perform these effects without deferred shading, you would've had to render the whole scene again. - -## Deferred Shading Disadvantages -There are several algorithmic drawbacks with deferred shading - transparent objects are hard to handle, anti aliasing can not be used in DX9 class hardware, additional memory consumption because of the G-Buffer. -In addition to that, deferred shading is harder to implement - it overrides the entire fixed function pipeline. Pretty much everything is rendered using manual shaders - which probably means a lot of shader code. - -# Creating the G-Buffer {#creating} -The first part of the deferred shading pipeline involves rendering all the (non-transparent) objects of the scene to the G-Buffer. This is done using a compositor : - -@snippet Samples/Media/DeferredShadingMedia/deferred.compositor gbuffer - -Things to note about this compositor : -* mrt_output (the GBuffer) is an MRT because there are two pixel formats defined. -* mrt_output will be accessible to the next compositors in the chain because it is marked as chain_scope, meaning it is visible to the next compositors in the chain. -* The material scheme tells ogre that objects shouldn't be rendered in normal fashion, but in some other way (we'll get to that soon) -* Not all the objects are rendered to the GBuffer. Skies and 'late objects' (which can be specified manually using render queues) will be forward rendered. -* This compositor does NOT have a target_output pass, because it does not contribute directly to the final image. - -## Deciding on the GBuffer format -This in an important decision in deferred shading, as it has performance and visual implications. - -Also, the entire pipeline has to be coordinated with this format - all the writing shaders have to write the same data to the same places, and all the reading shaders (for lighting later) have to be synchronized with it. - -We chose two PF_FLOAT16_RGBA textures. The first one will contain the colour in RGB, specular intensity in A. - -The second one will contain the view-space-normal in RGB (we keep all 3 coordinates) and the (linear) depth in A. - -See the references for other possibilities. - -## Preparing the objects for G-Buffer rendering -The only indicator that ogre has when rendering the scene is that the material scheme is different. Material schemes in ogre allow materials to specify different rendering techniques for different scenarios. In this case, we would like to output the lighting related information instead of the lighting calculation result. - -Materials that have a technique associated with the GBuffer scheme will render using that, but we don't want to modify the materials of all the objects in our art pipeline to use them in deferred shading. - -The solution is to use scheme listeners! The material manager has a method for registering listeners when objects don't have a technique defined for the current scheme: Ogre::MaterialManager::addListener(). - -The listener has a callback method that gets called whenever an object is about to be rendered without a matching technique: Ogre::MaterialManager::Listener::handleSchemeNotFound(). - -We will implement such a listener for the GBuffer scheme. It is GBufferSchemeHandler from the demo. -The GBufferSchemeHandlers works like this : - -### Inspect the classic technique -For each pass in the technique that would have been used normally, the GBufferSchemeHandler::inspectPass is called, inspects the pass, and returns the PassProperties - does this pass have a texture? a normal map? is it skinned? tranpsarent? Etc. The PassProperties (should) contain all the information required to build a GBuffer technique for an object. - -### Generate the G-Buffer technique -After a pass has been inspected and understood, the next stage is to generate the G-Buffer-writing technique. This is done using the RTSS GBuffer lighting stage. This greatly reduces the number of shaders that you need to manage when using deferred shading, as most of them are created on the fly. Here is an example of what they look like : - -```cpp -void ToGBufferVP( - float4 iPosition : POSITION, - float3 iNormal : NORMAL, - float2 iUV0 : TEXCOORD0, - - out float4 oPosition : POSITION, - out float3 oViewPos : TEXCOORD0, - out float3 oNormal : TEXCOORD1, - out float2 oUV0 : TEXCOORD2, - - uniform float4x4 cWorldViewProj, - uniform float4x4 cWorldView - ) - { - oPosition = mul(cWorldViewProj, iPosition); - oNormal = mul(cWorldView, float4(iNormal,0)).xyz; - oViewPos = mul(cWorldView, iPosition).xyz; - oUV0 = iUV0; - } - - void ToGBufferFP( - float3 iViewPos : TEXCOORD0, - float3 iNormal : TEXCOORD1, - float3 iTangent : TEXCOORD2, - float3 iBiNormal : TEXCOORD3, - float2 iUV0 : TEXCOORD4, - - out float4 oColor0 : COLOR0, - out float4 oColor1 : COLOR1, - - uniform sampler sNormalMap : register(s0), - uniform sampler sTex0 : register(s1), - uniform float4 cDiffuseColour, - uniform float cFarDistance, - uniform float cSpecularity - ) - { - oColor0.rgb = tex2D(sTex0, iUV0); - oColor0.rgb *= cDiffuseColour.rgb; - oColor0.a = cSpecularity; - float3 texNormal = (tex2D(sNormalMap, iUV0)-0.5)*2; - float3x3 normalRotation = float3x3(iTangent, iBiNormal, iNormal); - oColor1.rgb = normalize(mul(texNormal, normalRotation)); - oColor1.a = length(iViewPos) / cFarDistance; - } -``` -(This is for an object with a texture and a normal map) - -### Add the G-Buffer technique to the original material -We don't want to inspect the passes and generate the material each time an object is rendered, so we create a technique in the original material, and fill it with the auto-generated information. The next time the object will be rendered, it WILL have a technique for the GBuffer scheme, so -the listener won't get called. - -### Putting it all together -This is how `GBufferSchemeHandler::handleSchemeNotFound` works: - -@snippet Samples/DeferredShading/src/GBufferSchemeHandler.cpp schemenotfound - -## Overriding the automatic process - -In some cases the automatic material generation will not be good enough. We want to keep the option of manually writing GBuffer materials and shaders. - -How do we do this? Easily! Since GBufferSchemeHandler::handleSchemeNotFound only gets called when an object doesn't already have a GBuffer scheme, adding a 'GBuffer' technique to the material will cause it to not get passed to the listener even once. - -## Seeing it in action -Using tools like [RenderDoc](https://renderdoc.org/), we can see the texture being built during the frame: - -@image html GBufferRenderdoc.jpg width=90% - -Note that nothing has been written to the final output yet and that two output textures are being written to (see right hand side). - -# Lighting the scene {#lighting} -In the GBuffer compositor, we built the G-Buffer for the current frame. It is now the time to use it to calculate the final lighting of the scene. This is what the compositor looks like : - -@snippet Samples/Media/DeferredShadingMedia/deferred.compositor showlit - -Yes, it's a long one. Here is a breakdown of the compositor : -* The 'texture_ref' definition means that we are referencing a texture from another compositor. In the case of a chain-scoped texture (like the GBuffer), this means that we can only apply this compositor on chains that have the GBuffer creating compositor earlier in the chain than this one. Ogre will check that this is the case. - -There are four target passes in this compositor. -1. Render the skies and then the lights using the render_custom directive (more on this later) -2. Render the objects that are in the GBuffer render queues but didn't get rendered to the GBuffer -3. Render the post-GBuffer render queue objects -4. Output the result - -## Rendering the light geometry {#lightgeom} -The geometry that we want to render to calculate lighting information doesn't really fit in any classic category. It is not really a part of the scene, as the light geometry aren't objects in the world. But it is geometry (not always a quad) that needs to be rendered. - -For these kind of operations, the render_custom target pass was introduced into Ogre. It is possible to register custom (named) composition passes that will be performed in the compositor. In this case, it is 'DeferredLight'. The composition pass will receive a call each frame telling it 'it's your turn, do your thing'. The class in the demo is DeferredLightCP. - -The registration of the custom composition pass has to be done once, using Ogre::CompositorManager::registerCustomCompositionPass(). - -CustomCompositionPass is essentially just a factory for RenderSystemOperations, which are the operations that get executed during a compositor chain. This is the single API call: Ogre::CustomCompositionPass::createOperation(). - -So, now we get called exactly when we want, after the G-Buffer has been built and the (early) skies have been rendered. What will we do? - -### Prepare ambient colour and rebuild original depth buffer -Since we rendered the original scene to a different RTT, the depth buffer won't necessarily get reused for the output target, so we need to rebuild it so that future objects (lights and non-g-buffer objects) will be able to interact with the depth naturally. - -Also, we need to apply the ambient light to the scene. For the purpose of the demo, the ambient light is not a separate colour channel, just the object's original textures applied with the scene's global ambient light factor. In theory, you could set up a different G-Buffer to allow more flexibility, but we didn't do that. - -These two actions happen in a single full-screen quad render, that comes from the AmbientLight class. - -### Render the light geometries -The most important stage is the light geometry. The code scans the original scene's lights, builds a matching DLight (deferred light) instance for each light in the scene, and renders away using the G-Buffer. - - -These lights use pretty sophisticated shaders, since they perform the lighting calculations of the fixed function pipeline themselves, and have to account for many options (specularity, attenuation, different light types and shadows, which will get talked about soon). In contrast to the G-Buffer building stage, the shaders here do not get generated on the fly. There is one big shader (sometimes referred to as an Uber-Shader) with many preprocessor options that account for all the options. (See LightMaterial_ps.cg) Note that the shaders have to be synchronized with the G-Buffer layout. A change in the layout would need a parallel change in the deferred lighting shaders. - - -The material generator for this section (LightMaterialGenerator class) just scans the flags of input and generates the correct preprocessor defines for the uber-shader. Some people prefer to use this approach for the G-Buffer stage as well, but I wanted to show both options in the demo. - - -In order to dispatch render operations manually, the following call exists in SceneManager: Ogre::SceneManager::_injectRenderWithPass(). - -When rendering a light, we pass the light we are rendering as the manual light list in order to have the auto params for that light available in the shader. - -### Rendering shadow casting lights -The 'classic' approach to rendering texture shadows is to prepare all of them before the scene rendering starts, and then apply them to the rendered objects using shadow receiver passes or integrated shaders. The downside of this approach is that you need to allocate a texture per-light (5 shadow casting lights -> 5 shadow textures) and that if you don't integrate it in your shaders you also contribute even more passes to the scene. - -One of the advantages of deferred shading is that we render the lights completely, and one by one. So, we can generate the shadow texture for a light just before the light's geometry is rendered, allowing us to reuse the same texture for as many lights as we want. (We still have an overhead of rendering the scene from the light's perspective per-light). - -The API call that prepares shadow textures on demand is Ogre::SceneManager::prepareShadowTextures(). -The lightList parameter allows specification of which lights to prepare shadow textures for. - - -Important note - RenderSystemOperations get executed in the middle of scene rendering. This means that there is an active render target being rendered to. In order to render the shadow texture we need to be able to pause rendering mid frame, render the shadow texture, and resume rendering immediately afterwards. For this, SceneManager has two methods that do just that Ogre::SceneManager::_pauseRendering() and Ogre::SceneManager::_resumeRendering(), -so the prepareShadowTextures call has to be inside this. - -The demo currently supports just spotlight shadow casting (since it is the cheapest to implement) but the other options can be supported as well. - -### Putting it all together - -@snippet Samples/DeferredShading/src/DeferredLightCP.cpp execute - -### Seeing it in action - -Here is a screenshot from RenderDoc of the draw call that renders a spotlight that casts shadows. See the two G-Buffer textures and one shadow texture on the right: - -@image html DeferredCone.jpg width=90% - -After all the lights are rendered, the scene is fully lit! - -# Post Processing {#post} -The compositor framework used to be a post processing framework, but as this article shows - it is now a 'custom render pipeline' framework, allowing different rendering approaches. However, it can still be used to post process the scene, even under deferred rendering. - -## Screen Space Ambient Occlusion -'Screen Space Ambient Occlusion' is a global illumination technique that adds a bit of realism to the scene, where classic lighting often fails. However, it requires the normals and depths of the scene in order to calculate its contribution. Normally, the SSAO compositor would have a render_scene directive that does that. - -However, with deferred shading, we already have that information from the G-Buffer stage, so we just need to access it! - -This is what the compositor looks like : - -@include Samples/Media/DeferredShadingMedia/ssao.compositor - -Some notes : -* Again, texture_ref is used to access a chain_scoped texture from the GBuffer compositor -* compositor_logic is used to couple between the compositor and some code that it requires to run. A CompositorLogic class is created and registered with the CompositorManager with Ogre::CompositorManager::registerCompositorLogic(). -Which will cause the binding code to run whenever an instance of this compositor is created. -* 'Regular' compositors that don't use the GBuffer are also still possible of course, they can be used regularly, as long as they are placed after the DeferredShading/ShowLit compositor. - -# Integration in real projects {#realprojects} -The framework that this demo uses was designed to be pluggable into other projects. Some of the design considerations that contribute to that are : -1. The scene setup does not change in any way. You still set the scene up with normal lights and modify their parameters just like you would regularly. -2. The GBuffer scheme handler and shader generator allow existing materials to work in a deferred shading pipeline unmodified. It might not cover all the cases, but it can. -3. Easy to integrate - see next section - -## Integration steps -The framework created for a demo fits the plugin architecture pretty well. The GBufferSchemeHandler and DeferredLightCompositionPass classes could be instantiated once on plugin setup and registered with ogre's systems. This is not the case currently just to keep the SDK build simpler. - -So, the steps are : -1. Register GBufferSchemeHandler and DeferredLightCompositionPass with their respective managers. -2. Add the GBuffer and ShowLit compositors to the viewports you want deferred shaded. - - - -And that's it! In the demo, the DeferredShading class takes care of that. - -## Adapting the framework -The deferred shading framework in the demo was designed to be usable in real applications. Where would one want to modify it ? -1. GBufferSchemeHandler / MaterialGenerator - support more options out of the box. Skinning, specular maps, and whatever you have in your project that can be solved in a generic fashion. -2. LightMaterialGenerator - support more lighting options (fog, etc), more shadow types, different shadow techniques (currently using very basic depth shadow mapping) -3. Tweak the framework to your pipeline - The material inspection relies on naming (among other things) to decide what its looking at. Just modify it to fit your art pipeline's conventions! (For example, how does a texture get flagged as a normal map?) - -Indeed, it means that the framework is not 100% plug and play. But, if understood correctly, it can be adapted to real life scenarios with relative ease. - -## Adding features to the framework -Post processing compositors that rely on certain aspects of the scene (like SSAO does) are now much easier to create and integrate with the earlier processes. An example could be edge-based anti aliasing, to address the lack of anti aliasing in DX9-based deferred shading systems. - -In addition to that, the deferred shading implementation was focused on simplicity. There are many optimization options and most of them were not done, mainly to keep the demo as simple and understandable as possible. - -# Summary {#summary} -Deferred Shading is an advanced rendering technique, that brings a pretty big implementation challenge along with it. This article, along with the demo, shows that it is possible to implement without relying on hacks and bypassing ogre's systems. Yes, it involves more advanced usage of ogre's APIs and requires a bit of knowledge about what happens behind the scenes, but is in no way impossible. - -## Further reading {#further} -* [KillZone 2 Deferred Shading overview](https://d1z4o56rleaq4j.cloudfront.net/downloads/assets/Develop07_Valient_DeferredRenderingInKillzone2.pdf) - Great resource for understanding deferred shading in general before diving into implementing it in Ogre. -* [Improving Ogre's Compositor Framework GSoC project page](http://www.ogre3d.org/tikiwiki/tiki-index.php?page=SoC2009+Compositor) -* [Deferred Rendering Demystified](https://www.gamedev.net/articles/programming/graphics/deferred-rendering-demystified-r2746/) - An article written around this project that explains the design behind the deferred renderer. diff --git a/Docs/src/tutorials/external_texture.md b/Docs/src/tutorials/external_texture.md deleted file mode 100644 index 6d482cc644c..00000000000 --- a/Docs/src/tutorials/external_texture.md +++ /dev/null @@ -1,97 +0,0 @@ -# External Texture Sources {#External-Texture-Sources} - -This tutorial will provide a brief introduction of ExternalTextureSource and ExternalTextureSourceManager classes, their relationship, and how the PlugIns work. For those interested in developing a Texture Source Plugin or maybe just wanting to know more about this system, take a look the [TheoraVideoSystem Plugin](https://github.com/OGRECave/ogre-audiovideo), which you can find more about on the OGRE forums. - - - -# What Is An External Texture Source? - -What is a texture source? Well, a texture source could be anything - png, bmp, jpeg, etc. However, loading textures from traditional bitmap files is already handled by another part OGRE. There are, however, other types of sources to get texture data from - i.e. ogg/avi/etc movie files, run-time generated source, user defined, etc. - -How do external texture source plugins benefit OGRE? Well, the main answer is: adding support for any type of texture source does not require changing OGRE to support it... all that is involved is writing a new plugin. Additionally, because the manager uses the Ogre::StringInterface class to issue commands/params, no change to the material script reader is needs to be made. As a result, if a plugin needs a special parameter set, it just creates a new command in it’s Parameter Dictionary. - see TheoraVideoSystem plugin for an example. To make this work, two classes have been added to OGRE: -- Ogre::ExternalTextureSource -- Ogre::ExternalTextureSourceManager - - - -# ExternalTextureSource Class - -The @c ExternalTextureSource class is the base class that Texture Source PlugIns must be derived from. It provides a generic framework with a very limited amount of functionality. The most common of parameters can be set through the ExternalTextureSource class interface or via the StringInterface commands contained within this class. While this may seem like duplication of code, it is not. By using the string command interface, it becomes extremely easy for derived plugins to add any new types of parameters that it may need. - -Default Command Parameters defined in ExternalTextureSource base class are: - -@param filename Sets a filename plugin will read from -@param play_mode Sets initial play mode to be used by the plugin - "play", "loop", "pause" -@param set_T_P_S Used to set the technique, pass, and texture unit level to apply this texture to. As an example: To set a technique level of 1, a pass level of 2, and a texture unit level of 3, send this string "1 2 3". -@param frames_per_second Set a Frames per second update speed. (Integer Values only) - - - -# ExternalTextureSourceManager Class - -@c ExternalTextureSourceManager is responsible for keeping track of loaded Texture Source PlugIns. It also aids in the creation of texture source textures from scripts. It also is the interface you should use when dealing with texture source plugins. - -Steps needed to create a new texture via ExternalTextureSourceManager: - -@remark The function prototypes shown below are mockups - param names are simplified to better illustrate purpose here... - -- Obviously, the first step is to have the desired plugin included in @c plugin.cfg for it to be loaded. -- Set the desired PlugIn as Active via -```cpp -Ogre::ExternalTextureSourceManager::getSingleton().setCurrentPlugIn(type); -``` - type is whatever the plugin registers as handling (e.g. "video", "flash", "whatever", etc). -- Consult Desired PlugIn to see what params it needs/expects. Set params/value pairs via -```cpp -Ogre::ExternalTextureSourceManager::getCurrentPlugIn()->setParameter( Param, Value ); -``` -- After required params are set, a simple call to -```cpp -Ogre::ExternalTextureSourceManager::getCurrentPlugIn()->createDefinedTexture( MaterialName ); -``` - will create a texture to the material name given. - - -The manager also provides a method for deleting a texture source material -```cpp -Ogre::ExternalTextureSourceManager::destroyAdvancedTexture( MaterialName ) -``` -The destroy method works by broadcasting the material name to all loaded @c ExternalTextureSource instances, and the PlugIn who actually created the material is responsible for the deletion, while other PlugIns will just ignore the request. What this means is that you do not need to worry about which PlugIn created the material, or activating the PlugIn yourself. Just call the manager method to remove the material. Also, all texture plugins should handle cleanup when they are shutdown. - - - -# Texture Source Material Script - -As mentioned earlier, the process of defining/creating texture sources can be done within material script file. Here is an example of a material script definition - Note: This example is based off the @c TheoraVideoSystem Plugin parameters. - -```cpp -material Example/MyVideoExample -{ - technique - { - pass - { - texture_unit - { - texture_source ogg_video - { - filename mymovie.ogg - play_mode play - sound_mode on - } - } - } - } -} -``` - -Notice that the first two param/value pairs are defined in the ExternalTextureSource base class and that the third parameter/value pair is not defined in the base class... That parameter is added to the param dictionary by the @c TheoraVideoSystem... This shows that extending the functionality with the plugins is extremely easy. Also, pay particular attention to the line: `texture_source ogg_video`. -This line identifies that this texture unit will come from a texture source plugin. It requires one parameter that determines which texture plugin will be used. In the example shown, the plugin requested is one that registered with @c "ogg_video" name. - - - -# Simplified Diagram of Process - -This diagram uses @c TheoraVideoSystem as example, but all plug ins will work the same in how they are registered/used here. Also note that TextureSource Plugins are loaded/registered before scripts are parsed. This does not mean that they are initialized... Plugins are not initialized until they are set active! This is to ensure that a rendersystem is set up before the plugins might make a call the rendersystem. - -![](images/TextureSource.svg) diff --git a/Docs/src/tutorials/manualmesh.md b/Docs/src/tutorials/manualmesh.md deleted file mode 100644 index 887413ea62e..00000000000 --- a/Docs/src/tutorials/manualmesh.md +++ /dev/null @@ -1,77 +0,0 @@ -# Manual mesh creation {#manual-mesh-creation} - -There are two ways to create your own mesh. The first way is to create a Ogre::Mesh instance and provide it with the vertex and index buffers directly. - -The second way is the high level Ogre::ManualObject interface. Instead of filling position and color buffers, you simply call the "position" and "colour" functions. - -# Using Manual Object - -@copydetails Ogre::ManualObject - -## Example - -We will use the ManualObject to create a single textured plane. -After creating the object, we start a new geometry block that will use the given material - -@snippet Tests/VisualTests/PlayPen/src/PlayPenTests.cpp manual_plane_begin - -Next we specify the vertices of the plane - -@snippet Tests/VisualTests/PlayPen/src/PlayPenTests.cpp manual_plane_vertices - -Now we can define the face. %Ogre will split the quad into triangles for us. - -@snippet Tests/VisualTests/PlayPen/src/PlayPenTests.cpp manual_plane_faces - -Calling @c end() creates the actual Hardware Buffers to be used for rendering and we can attach the Object to a Ogre::SceneNode. - -@snippet Tests/VisualTests/PlayPen/src/PlayPenTests.cpp manual_plane_end - -In case you need multiple Ogre::Entities of the plane, you should call Ogre::ManualObject::convertToMesh first and then use Ogre::SceneManager::createEntity as usual. - -# Using vertex and index buffers directly - -This time we are going to create a plane using the lower level Ogre::HardwareBuffer primitives. - -We start by creating a Mesh object. As this is a manual Mesh, we have to set the bounds of it explicitly. -```cpp -using namespace Ogre; - - MeshPtr mesh = MeshManager::getSingleton().createManual(yourMeshName, RGN_DEFAULT); - mesh->_setBounds(AxisAlignedBox({-100,-100,0}, {100,100,0}); -``` - -Next we define what should end up in our vertex and index buffer. We will store all data interleaved in one buffer. This typically has some advantages due to cache coherency and also is what ManualObject does automatically for us. - -@snippet OgreMain/src/OgrePrefabFactory.cpp manual_plane_geometry - -However we could also split the data into multiple buffers with lower precision to save some bytes on texture coordinates and normals. - -To describe the vertex sources, we have to create a Ogre::VertexData object. Notably it stores how many vertices we have. - -@snippet OgreMain/src/OgrePrefabFactory.cpp vertex_data - -The actual description of our vertex buffer however is stored inside the Ogre::VertexDeclaration. - -@snippet OgreMain/src/OgrePrefabFactory.cpp vertex_decl - -Now we can continue to create the Hardware Buffers and upload our data. - -@snippet OgreMain/src/OgrePrefabFactory.cpp vertex_buffer - -Note how we used the symbolical constant @c 0 to link the Ogre::HardwareVertexBuffer to the Ogre::VertexDeclaration. -This allows the underlying RenderSystem to swap VertexBuffers without changing the VertexDeclaration. i.e. render different Meshes that share the same vertex layout, without changing the state. - -Finally we create the Ogre::SubMesh that will be ultimately rendered. - -@snippet OgreMain/src/OgrePrefabFactory.cpp sub_mesh - -Note that while our VertexBuffer is shared, the IndexBuffer is not. This allows rendering different faces of the same object using different Materials. Here, each SubMesh links the faces (IndexBuffer) to the according material. - -Finally, we have to update the loading state of the mesh as -```cpp - mesh->load(); -``` -If you have registered a Ogre::ManualResourceLoader, the resource loading would only happen now. - -@note Using the Ogre::ManualResourceLoader is highly recommended. It allows lazy-loading the data on demand as well as unloading and re-loading resources when running out of memory. \ No newline at end of file diff --git a/Docs/src/tutorials/meshlod.md b/Docs/src/tutorials/meshlod.md deleted file mode 100644 index 80406ba73d2..00000000000 --- a/Docs/src/tutorials/meshlod.md +++ /dev/null @@ -1,89 +0,0 @@ -# Automatic Mesh LOD Generator {#meshlod-generator} - -@tableofcontents - -Mesh LOD allows to swap the models to Low-poly models in far distance, which makes your game faster. -%Ogre will automatically use Mesh LOD when you load a mesh file, which has LOD information in it. So basically you don't need to do any coding to use this feature, but you need to prepare your meshes! - -The Mesh LOD generator can generate Low-poly models automatically from High-poly models. -It implements an improved version of "A simple, fast, and effective polygon reduction algorithm" by Stan Melax @cite melax1998simple. The improvements are described in detail [in the GSoC2012 report](http://sajty.elementfx.com/progressivemesh/GSoC2012.pdf). - -# How to use it for non-programmers {#meshlod-nonprog} -The __fastest way__ to generate mesh LOD is to use OgreMeshUpgrader on the console: -* Generate autoconfigured LOD: no questions asked, just get instant performance. - ``` - OgreMeshUpgrader -autogen athene.mesh athene_lod.mesh - ``` -* Interactive mode: It will ask you for every LOD level detail and much more! - ``` - OgreMeshUpgrader -i athene.mesh athene_lod.mesh - ``` -* If you don't use stencil shadows, I would recommend disabling Edge lists, because they increase the mesh file a lot! If you load the mesh, edge lists will also stay in memory and consuming resources. -* If you use older %Ogre version, but you want to use latest LOD generator algorithm for best quality, you can get it with -V option! - ``` - OgreMeshUpgrader -autogen -V 1.8 athene.mesh athene_lod.mesh - ``` - -The __best way__ to generate mesh LOD with visual feedback is to use the Mesh Lod sample in the Sample Browser. -* Put your meshes and materials into `Samples/Media/models` -* Start up SampleBrowser and load MeshLod sample. -* Select your mesh in the "model" combobox. -* Change the "Reduced vertices" slider to the reduction where you want to create a LOD level. -* Change the camera distance to the desired distance -* Click on Add level to add the reduction amount with given distance -* Repeat previous 3 steps to create all levels. -* You can check the final mesh by clicking on "Show all levels". If you made the LOD perfectly, you see the triangle count dropping, when zooming out, while not seeing graphical errors. -* If you are ready, click on "save mesh" to save the LOD into the mesh file. - -# How to use it for programmers {#meshlod-prog} -You can find lot of usage samples in Ogre. For example MeshLod sample, MeshLodTests, MeshSerializerTests, PlayPen. - -```cpp -#include - -... -new Ogre::MeshLodGenerator(); -``` - -@note You can create it on the stack if you don’t enable lodConfig.advanced.useBackgroundQueue. Otherwise, when you free up the stack it will abort the LOD generation and you will not get any LOD for your mesh! - -As a first step, I would recommend to read through OgreLodConfig.h to know all available options! -LodConfig inheritance (having a base/default LodConfig) can be done with copy constructor! -```cpp -Ogre::LodConfig config(mesh); -config.createGeneratedLodLevel(5, 0.5); // At 5 ogre worldspace units use 50% reduced mesh -config.createGeneratedLodLevel(10, 0.75); // By default, it is using DistanceLodStrategy and proportional reduction. -config.createManualLodLevel(15, "mesh_LOD3.mesh"); // Manual level created in blender, maya or 3ds max. -config.advanced.useBackgroundQueue = true; // Generate in background thread, later inject with framelistener. -Ogre::MeshLodGenerator::getSingleton().generateLodLevels(config); - -// Or you can use autoconfigured LOD: -Ogre::MeshLodGenerator::getSingleton().generateAutoconfiguredLodLevels(mesh); -``` - -```cpp -delete Ogre::MeshLodGenerator::getSingletonPtr(); -``` - -# Extending MeshLodGenerator {#meshlod-extend} -MeshLodGenerator is built up of 6 components: -- Ogre::LodData: The core of the algorithm, containing the Mesh network representation. -- Ogre::LodCollapseCost: Provides an interface for collapse cost calculation algorithms (like curvature, quadric error, profiling, outside weight, normals) -- Ogre::LodInputProvider: Initializes LodData based on a source (It can be mesh or buffered(for threading)). -- Ogre::LodOutputProvider: Bakes the Lod to a target (It can be mesh, buffered, mesh+compressed and buffered+compressed) -- Ogre::LodCollapser: This will reduce the smallest costing vertices to the requested amount of vertices. Creates/destroys faces. -- Ogre::MeshLodGenerator: Frontend, which can receive LodConfig. It will create/run the required internal components to generate the requested LodConfig. Only this class is using the LodConfig. - -## Replacing a component -You can replace or inherit from any component by passing it to Ogre::MeshLodGenerator::generateLodLevels() function as parameter. - -For example there is a hidden feature (which can't be enabled in LodConfig) to use Quadric Error Metrics instead of Curvature to calculate collapse cost: -```cpp -Ogre::MeshLodGenerator gen; -gen.generateLodLevels(config, std::make_shared()); -``` -In the above example MeshLodGenerator will use every option from LodConfig, which is not related to collapse cost. This means outsideWeight, outsideWalkAngle and profile options will be ignored. - -Internally MeshLodGenerator uses 2 steps: -* _resolveComponents(): Creates the components which are still nullptr and configures them based on LodConfig. -* _process(): Runs the components. This may be called on background thread depending on LodConfig. diff --git a/Docs/src/tutorials/numpy.md b/Docs/src/tutorials/numpy.md deleted file mode 100644 index 0d87e618992..00000000000 --- a/Docs/src/tutorials/numpy.md +++ /dev/null @@ -1,45 +0,0 @@ -# Working with NumPy {#working-with-numpy} - -Ogre includes a Python component which automatically generates Python bindings from the C++ headers. -However, with Python, you most likely do not only want to just use Ogre, but connect it to other components. -For this, the Component uses standard python protocols, that offer exposing the API in a pythonic way. -In this tutorial, we will look how %Ogre integrates with numpy. - -@note this tutorial can be [run live in Google Colab here](https://colab.research.google.com/github/OGRECave/ogre/blob/master/Samples/Python/numpy_sample.ipynb). - -We start with a simple 3 channel python array representing a green gradient: - -@snippet Samples/Python/numpy_sample.py numpy_image - -![](numpy_arr.png) - -To be able to load it into %Ogre we now have to convert it to `Ogre.Image`. -The underlying C++ API takes a raw `uchar*`. However, the python bindings accept any object -implementing the Buffer Protocol. This means we can pass the numpy array as is. - -@snippet Samples/Python/numpy_sample.py np_to_ogre - -Note that `Ogre.Image` is merely a view on the underlying array and no data is copied. -While this is efficient, it also means that you have to ensure that the array does not get out of scope manually. -Otherwise the application will crash due to accessing an invalid pointer. - -For completeness we also create a small scene where we map the texture on a screen-centred rectangle. -@snippet Samples/Python/numpy_sample.py apply_to_rect - -As the rectangle does not cover the full scene, we also set a background colour -@snippet Samples/Python/numpy_sample.py py_to_primitive -Here, the standard python sequence protocol is used. Therefore, the data is copied. - -Finally, we want read-back rendered image into an array. To avoid superficial copies of the data, we again allocate the memory with numpy: - -@snippet Samples/Python/numpy_sample.py ogre_to_np - -Note, that the convention of specifying width and height is swapped between %Ogre and numpy. - -Now we can store the image to disk using pyplot. - -@snippet Samples/Python/numpy_sample.py zero_copy_view - -@note There is also Ogre::RenderTarget::writeContentsToFile if you do not need the pixel data in Python. - -![](numpy_final.png) \ No newline at end of file diff --git a/Docs/src/tutorials/profiler.jpg b/Docs/src/tutorials/profiler.jpg deleted file mode 100644 index 1a29a3fb079..00000000000 Binary files a/Docs/src/tutorials/profiler.jpg and /dev/null differ diff --git a/Docs/src/tutorials/profiler.md b/Docs/src/tutorials/profiler.md deleted file mode 100644 index 834ea0d6106..00000000000 --- a/Docs/src/tutorials/profiler.md +++ /dev/null @@ -1,134 +0,0 @@ -# Using the Profiler {#profiler} - -@note If you are using the Ogre SDK and you want to use the Profiler, it is advisable to switch to the source code version of Ogre, because the SDK is shipped with `OGRE_PROFILING=OFF`, so instrumentation is disabled by default. - -@tableofcontents - -First you want to initialize the Profiler like this: -```cpp - Ogre::Profiler::getSingleton().setEnabled(true); -``` -This sets up the media that the profiler uses. The reason this is not in the constructor is because the profiler contains media dependencies that people who aren't using the profiler shouldn't have to worry about. The profiler will need you to specify the main program loop. To do this, you call the following at the very beginning of the frameStarted() function in your FrameListener class: -```cpp - OgreProfileBegin("Ogre Main Loop"); -``` -and add this at the very end of the frameEnded() function: -```cpp - OgreProfileEnd("Ogre Main Loop"); -``` -Make sure the names match exactly, otherwise the profiler will fail an assert. Next you want to profile some of your code. You do this by calling OgreProfile() and using braces ({}) to limit the scope. Note that OgreProfile cannot be called in the same scope as another OgreProfile(). Doing so will result in a compile-time error. Here is an example of using OgreProfile: -```cpp -{ - OgreProfile("Collision Detection"); - mISQR = mISQ->execute(); -} -{ - OgreProfile("Collision Response"); - SceneQueryMovableIntersectionList::iterator iter; - for (iter = mISQR.movables2movables.begin(); iter != mISQR.movables2movables.end(); iter++) { - // do stuff - OgreProfile("Explosions"); - createExplosion(); - } -} -``` -If you want a profile to last outside of its scope, use OgreProfileBegin() and OgreProfileEnd() like you did when creating the main loop profile. - -# Reading the Display {#profRead} - -![](profiler.jpg) - -On the left side are the profile names with a number in parentheses next to it. This number is the number of times this profile was called during this frame. If this number is 0, that means that the profile was called before, but is not being called currently. The bars on the left represent the frame time statistics. You can see indicators above which show that a profile can take anywhere from 0% to 100% of the frame time. The big yellow bars show the current frame percentage that the profile is taking. The green line shows the minimum frame time, the red line is the maximum frame time, and the blue line is the average frame time. Big discrepancies between the average and maximum can possibly be the sign of a performance bottleneck (however it could be the profiler acting strangely, see the ''Known Issues'' section). These results will be printed to the log when the application ends or you can manually do it by calling logResults(). - -# Features {#profFeatures} -## Disabling the Profiler -You can disable the profiler by calling: -```cpp - Ogre::Profiler::getSingleton().setEnabled(false); -``` -and enable it again by calling: -```cpp - Ogre::Profiler::getSingleton().setEnabled(true); -``` -Note that this is a temporary solution. If you want to completely disable the profiler for your release version, see the section ''Release Version Considerations''. - -## Disabling Individual Profiles -Disabling profiles can be useful if there are certain core functions that you want to profile on occasion. For example, you could profile certain rendering operations when you are checking general performance and then disable those profiles when you want to profile your AI code. You can disable a profile like this: -```cpp - Ogre::Profiler.getSingleton().disableProfile(""); -``` -and you can enable it again with this: -```cpp - Ogre::Profiler.getSingleton().enableProfile(""); -``` -Please note that trying to enable or disable a profile while that profile is running will have no effect. - -## Analyzing Application State -It is helpful to see the state of your application when a profile reaches a maximum level or some other condition. To check if a specific has reached a new maximum level, use: -```cpp - Ogre::Profiler.getSingleton().watchForMax(""); // return true if it reaches a new maximum -``` -or to see if a profile has reached a new minimum level, use: -```cpp - Ogre::Profiler.getSingleton().watchForMin(""); // returns true if it reaches a new minimum -``` -or to set an arbitrary level: -```cpp -//returns true when AI code takes over 60% of the frame time -Ogre::Profiler.getSingleton().watchForLimit("AI code", .6, true); - -//returns true when graphics code takes less than 10% of the frame time -Ogre::Profiler.getSingleton().watchForLimit("Graphics code", .1, false); -``` - -These functions should be used at the end of the main game loop for more accuracy. Otherwise, it will represent the results of the previous frame. - -## Logging Results -You can log the results of the current profiler statistics like this: -```cpp - Ogre::Profiler.getSingleton().logResults(); -``` -This is called automatically when you quit your Ogre application. - -## Changing the Frequency of Updating the Display -You can change how frequently the display is updated to suit your tastes like this: -```cpp - Ogre::Profiler.getSingleton().setUpdateDisplayFrequency(); -``` -Basically the tradeoff is between how accurate the display is and the amount of flicker. The default is that the display is updated every 10 frames. - -# Performance and Accuracy {#profAccuracy} -I've tried to minimize the performance hit from using the profiler. However, like anything else, it still takes some time to perform the necessary calculations. There are some steps you can take to increase the accuracy of the results. Firstly, although the profiler supports multiple calls of a profile during each frame, doing this more than a few times can cause the profiler to take significantly longer than the actual code you are trying to profile. Therefore it is recommended that you move the profile up one level (such as outside of a for loop) so that it is called fewer times. - -To maximize the accuracy of a profile, it is best to remove the child profiles of the profile you are analysing. Child profiles increases the frame time of the parent due to the overhead of using the profiler. - -Some tests I've conducted show that the profiling code will max out unexpectedly, so take the maximum frame time value with a grain of salt (See the *Known Issues* section). I think this only happens when a profile is first created, so you can possibly get around this issue by calling the reset() function after the first frame. - -# Remotery Backend {#profRemotery} - -If you need some more overview or want to profile a remote device, the profiler optionally supports using [Remotery](https://github.com/Celtoys/Remotery). - -To enable the Remotery backend set `OGRE_PROFILING_REMOTERY_PATH` in CMake to point to the `Remotery/lib` directory (containing `Remotery.c`). -Remotery will be compiled into OgreMain and can be accessed as usual. - -Note that no features besides Ogre::Profiler::setEnabled are available when using Remotery. - -# Release Version Considerations {#profRelmode} -For the release version of your app, you should set `OGRE_PROFILING=OFF` in CMake. If the build you are using has been compiled with the `OGRE_PROFILING=OFF` and you still want to use instrumentation, you can instantiate a dummy profiler like this: - -```cpp -// Create dummy profile to set singleton pointer -new Ogre::Profiler(); - -// Give it a timer and enable it -Ogre::Profiler::getSingleton().setTimer(Root::getSingleton().getTimer()); -Ogre::Profiler::getSingleton().setEnabled(true); -``` - -The profiler will now work but the 3 OgreProfile macro will not work. You will have to manually use the beginProfile() and endProfile() method. You can also instantiate scope-limited Profile objects or simply define your own macros somewhere in your code. - -```cpp -#define MyScopedProfile( a ) Ogre::Profile _OgreProfileInstance( (a) ) -#define MyProfileBegin( a ) Ogre::Profiler::getSingleton().beginProfile( (a) ) -#define MyProfileEnd( a ) Ogre::Profiler::getSingleton().endProfile( (a) ) -``` \ No newline at end of file diff --git a/Docs/src/tutorials/quad_visual.png b/Docs/src/tutorials/quad_visual.png deleted file mode 100644 index 5fcb6b97b45..00000000000 Binary files a/Docs/src/tutorials/quad_visual.png and /dev/null differ diff --git a/Docs/src/tutorials/reversed-depth.md b/Docs/src/tutorials/reversed-depth.md deleted file mode 100644 index 17c447dc460..00000000000 --- a/Docs/src/tutorials/reversed-depth.md +++ /dev/null @@ -1,76 +0,0 @@ -# Reversed Depth {#reversed-depth} - -By default %Ogre is using the standard depth setup, which results in a [hyperbolical depth value distribution](https://developer.nvidia.com/content/depth-precision-visualized). -This means that there is a high depth resolution close to the near plane, while objects far from the near-plane are likely to experience [z-fighting](https://en.wikipedia.org/wiki/Z-fighting). - -This typically occurs if you try to render large outdoor scenes, where you have objects very close to the camera, like grass-leaves, as well as objects very far away that all have their separate depth. - -To mitigate this problem, %Ogre allows you to use a reversed floating-point Z-Buffer, that results in an approximately linear depth value distribution. To use this, enable the `"Reversed Z-Buffer"` RenderSystem option. - -@note currently this is only supported by the D3D11 and GL3Plus RenderSystems - -This will make %Ogre use the `[1; 0]` range for depth values instead of the standard `[0; 1]` range. - -However, we also have to use a floating-point depth buffer to get any benefit from that. -This is a little bit tricky, as e.g. OpenGL is very restrictive on the main depth-buffer therefore unlikely to allow you to using a floating point buffer there. - -Therefore, we will use an off-screen texture for rendering, where we can easily use a floating-point depth buffer and only copy the results to the screen. - -For this you can use the following [Compositor script](@ref Compositor-Scripts): - -```cpp -// a simple material that only applies the texture -material copy -{ - technique - { - pass - { - lighting off - texture_unit - { - filtering none - } - } - } -} - -compositor OffscreenRender -{ - technique - { - // this intermediate texture allows OGRE to attach a float depth buffer - texture result target_width target_height PF_BYTE_RGBA - - target result - { - // this will just render the scene as-is - input previous - } - - target_output - { - // for the output we only have to copy the "result" texture to screen - pass render_quad - { - material copy - input 0 result - } - } - } -} -``` -If reversed depth is enabled, %Ogre will automatically assign a floating point buffer here. - -See @ref Applying-a-Compositor, for how to set that compositor on your main window. - -@note if you already use some compositor effects, make sure that `OffscreenRender` is the first compositor in the Ogre::CompositorChain. - -As we only render a full-screen quad to our main window, we should tell %Ogre that we do not need a depth buffer for it. -We do this as: -```cpp -Ogre::RenderWindow* rwin = getRenderWindow(); -rwin->setDepthBufferPool(Ogre::DepthBuffer::POOL_NO_DEPTH); -``` - -@note If you are reading depth values in your shader, you can test for the `OGRE_REVERSED_Z` define, to discover whether reversed depth is enabled. diff --git a/Docs/src/tutorials/setup.md b/Docs/src/tutorials/setup.md deleted file mode 100644 index dae59392400..00000000000 --- a/Docs/src/tutorials/setup.md +++ /dev/null @@ -1,129 +0,0 @@ -# Setting up an OGRE project {#setup} -@note see @ref building-ogre for instructions how to build OGRE itself - -@tableofcontents - -# CMake Configuration {#cmake} -Ogre uses CMake as its build system. It is strongly recommended that you use it in your project as well. -Then, all you need is to add the following lines to your project -@snippet Samples/Tutorials/CMakeLists.txt discover_ogre -These settings already include any third party libraries the Components depends on (e.g. SDL) - nothing more to do. -Alternatively use `${OGRE_LIBRARIES}` to link against all available OGRE components. - -@note If you built OGRE statically, you also need `find_package` the used third-party libraries. e.g. `find_package(ZLIB)` - -If you installed OGRE in a non-standard path, you will have to set `OGRE_DIR` to the location of `OGREConfig.cmake` so `find_package` can figure out the rest. - -For inspecting the detected OGRE installation, the following CMake variables are available -* `OGRE_STATIC` - whether ogre was build as static lib -* `OGRE_${COMPONENT}_FOUND` - ${COMPONENT} is available -* `OGRE_PLUGIN_DIR` - The directory where the OGRE plugins are located -* `OGRE_MEDIA_DIR` - The directory where the OGRE sample media is located -* `OGRE_CONFIG_DIR` - The directory where the OGRE config files are located - -# Application skeleton {#skeleton} -The easiest way to get started is the OgreBites Component. It handles Ogre startup/ tear down (including Ogre::Overlay, @ref rtss "RTSS"), input using SDL2 and even includes a @ref trays "Simple GUI System". - -This is useful if all you want is to get a Scene with a FPS counter up and running (rapid prototyping). -If available it also uses SDL2 for input - you now just have to implement the callbacks. - -The main class is OgreBites::ApplicationContext which manages the lifetime of everything else. -In the constructor we set our application name. The ogre configuration files will be stored in a system dependent location specific to our app. Then @c initApp will initialise all components and create a window for us. -@snippet Samples/Tutorials/Bootstrap.cpp constructor - -the interesting part however is creation of the actual scene -@note The code is explained in detail in the Tutorial @ref tut_FirstScene - -@snippet Samples/Tutorials/Bootstrap.cpp setup - -to handle input events, we then override the according method -@snippet Samples/Tutorials/Bootstrap.cpp key_handler - -finally we start everything as -@snippet Samples/Tutorials/Bootstrap.cpp main - -OgreBites itself is also a good starting point if you need more control over the Camera or the Window creation. -For instance to render into an externally created Window. Fore Qt interop, there is OgreBites::ApplicationContextQt. - -@note You can find the full code of the above example at -* `Samples/Tutorials/Bootstrap.cpp` for C++ -* `Samples/Python/sample.py` for Python -* `Samples/AndroidJNI/MainActivity.java` for Java (Android) -* `Samples/Csharp/example.cs` for C\# - -@see Ogre::FileSystemLayer::getConfigFilePath -@see Ogre::Root::renderOneFrame -@see Ogre::RenderSystem::_createRenderWindow -@see Ogre::RenderSystem::preExtraThreadsStarted - -# Running your App {#setupRunning} - -%Ogre is divided into two library groups: main libraries and plugins. - -@par Main libraries -The main library group contains the @c OgreMain library itself (named @c OgreMain.dll or @c libOgreMain.so depending on your platform) and the component libraries that rely on it. -@par -On Linux you will typically install these into `/usr/local/` which is automatically searched by the linker, so nothing more to do. -On Windows however, you will have to either add the `sdk/bin` folder to `PATH` or copy your executable into `sdk/bin`. - -@par Plugins -The second group of shared libraries are the plugins. %Ogre pushes a good portion of its functionality into plugins so that they may be turned on or off easily at runtime. The core plugins that are included with %Ogre have names that start with @c "Plugin_" and @c "Codec_". You can also write your own plugins. -@par -%Ogre also uses plugins for the different render systems (such as OpenGL, DirectX, etc). These plugins start with @c "RenderSystem_". - -On Windows, the library and configuration files for %Ogre can be found in the @c bin folder of the SDK. -On Unix they are split into @c share/OGRE for configuration files, @c lib/ for libraries and @c lib/OGRE for Plugins. - -## Configuration Files - -%Ogre uses several configuration files (\*.cfg) in the INI format. They control things like which plugins are loaded and where your application will search for resource files. We will briefly introduce you to each of these files. You'll slowly read more about them as you progress through the tutorials as well. - -These files are searched in [a set of predefined locations as described here](@ref Ogre::FileSystemLayer::getConfigFilePath). Alternatively, you can set the @c OGRE_CONFIG_DIR environment variable for a custom configuration file location. - -@attention The above sample code must find @c plugins.cfg and @c resources.cfg to function properly. - -### plugins.cfg - -This file tells %Ogre which plugins to load. You modify this file when you want to load a different set of plugins. It is often most useful to simply "comment out" lines instead of removing them, because you never know when a stroke of inspiration will mean you want to reload some unused plugins. Here is some sample content: - -```py -# Plugin=RenderSystem_Direct3D9 -# Plugin=RenderSystem_Direct3D11 -Plugin=RenderSystem_GL -``` - -We have the DirectX systems commented out, and an active line for OpenGL. On a windows system, you may have this reversed. You can see why it might be helpful not to delete unused lines, because then you have to try and remember whether it was @c RenderSystem_OpenGL or @c RenderSystem_GL. - -You can also decide where %Ogre looks for plugins by changing the @c PluginFolder variable. You can use both absolute and relative paths. Relative paths are resolved relative to the location of @c plugins.cfg. - -For example, if you have built %Ogre from source on a linux machine, then you will need a line like this at the beginning of your file: - -``` -PluginFolder=/usr/local/lib/OGRE -``` - -By default, %Ogre would have been looking in the same directory where the @c plugins.cfg is located, which is sufficient on Windows. - -Additionally, you can use the @c OGRE_PLUGIN_DIR environment variable to override the value of @c PluginFolder. - -@note %Ogre is aware whether your app is a bundle. Therefore a relative path like `Contents/Frameworks/` will be correctly resolved inside the app bundle on OSX. - -### resources.cfg - -This file contains a list of the directories %Ogre will use to search for resources. Resources include scripts, meshes, textures, GUI layouts, and others. You can also use both absolute and relative paths in this file, but you still cannot use environment variables. Relative paths are resolved relative to the location of @c resources.cfg. %Ogre will **not** search subdirectories, so you have to manually enter them. Here is an example: - -``` -[General] -FileSystem=../media -FileSystem=../media/materials/scripts -FileSystem=../media/materials/textures -FileSystem=../media/models -``` - -Here is an example of a relative path being used and the need to list subdirectories. Including the '../media' directory did not automatically include the '../media/models' directory. This is so that Ogre doesn't get greedy and waste time loading up unneeded resources. - -### ogre.cfg - -This file is generated by the Render Settings dialog that appears when you run your application. **Do not** distribute this file with your application. This file will be specific to your own setup. This file will contain your choices for things like screen resolution (see Ogre::RenderSystem::setConfigOption). Do not modify this file directly. Change the settings with the dialog and it will be automatically updated. - -Depending on the OS, %Ogre will place this config file in [the writable path described here](@ref Ogre::FileSystemLayer::getWritablePath). \ No newline at end of file diff --git a/Docs/src/tutorials/static-geometry.md b/Docs/src/tutorials/static-geometry.md deleted file mode 100644 index 2361898eb9e..00000000000 --- a/Docs/src/tutorials/static-geometry.md +++ /dev/null @@ -1,83 +0,0 @@ -# Static Geometry {#tut_StaticGeom} - -If we have a collection of entities in our scene that will not be moved, then %Ogre can perform an optimization by rendering them in "batches". Modern GPUs are designed to render an enormous amount of triangles at once. We are able to take advantage of this through the batching techniques used by a Ogre::StaticGeometry object. -Static geometry is a bit of a misnomer in this case, because we can use some tricks to accomplish things like grass waving in the wind, but the general idea is that this is an object that will not be manipulated a great deal. Good examples include rocks, trees, and buildings. - -The full source for this tutorial can be found in samples directory **Samples/Simple/include/Grass.h**. - -@tableofcontents - -# Blades of grass -The first thing we will do is create the grass mesh we will be rendering. We will use a pattern you've probably seen to create the illusion of grass. We will render three square quads that have a grass texture applied to them. We will create one, then place another rotated 60 degrees, and then place a third rotated 120 degrees. This will create a simple illusion of 3D grass. - -The first step will be to define some variables. We will define the width and height of our quad, then we will initialize a vector that will be used to define the four corners of our quad. We will again be using quaternions to handle rotations. Our plan is to use the vector to represent the orientation of the base of our quad. - -@snippet Samples/Simple/include/Grass.h grass_base - -This should look somewhat familiar. We have created a quaternion that rotates by multiples of 60 degree around the y-axis. - -The vector we are using starts out pointing down the x-axis with a length that is half the width of our quad. This may be a little hard to visualize. Here is a picture to help: - -![](quad_visual.png) - -Remember that x and z are in the plane of the floor. So our vector keeps track of where the foundation of our quad is, we build everything from that. - -We will now begin defining our manual object. We set the render operation to be OT_TRIANGLE_LIST. This means that after we define our vertices with the `position` method, we then have to let Ogre know how to set up the index buffer by giving it a list of triangles made from the vertices. - -@snippet Samples/Simple/include/Grass.h mo - -For each quad we are going to define four vertices representing the corners. We will also specify a texture coordinates. These are normalized coordinates that tell Ogre how to map the texture on to our mesh. In our case, these coordinates are very simple since we are creating a solid square. - -@snippet Samples/Simple/include/Grass.h mo_quad - -We've also labeled the four corners with the order they were created to help with creating the triangles. The count starts with the 0th corner. - -To ensure that both triangles face the same direction, we need to provide the points in counter-clockwise order. The `triangle` method does not directly take positions, instead it takes three numbers that represent the order in which the points were created. This is why we labeled the four corners in our image. - -@snippet Samples/Simple/include/Grass.h mo_index - -First, ignore the offset value and look at the numbers we are adding. They match the numbers we assigned in the image. The first triangle connects the 0th, 3rd, and 1st corners. The second triangle connects the 0th, 2nd, and 3rd corners. You can look at the image to see these are in counter-clockwise order. The purpose of the offset is because we are creating three different quads, but they are all going to be a part of one manual object. So the second quad's corners will be numbered 4, 5, 6, 7. Adding the offset accounts for this. - -After we've created all three quads, the loop finishes and we call `end` to finalize the object. - -@snippet Samples/Simple/include/Grass.h finish - -The last line converts our manual object into an actual mesh. Meshes require less storage compared to directly using the manual object for rendering. - -We are now finished creating the grass mesh. If you create a complex mesh, then you may save it to a file instead of rebuilding the mesh each time. To do this, you would save the mesh pointer that is returned by `convertToMesh`. Then you would use a mesh serializer to export the mesh to a file. - -Here is an example. Do __not__ add this code to our current project. -```cpp -auto mesh = obj.convertToMesh("GrassBladesMesh"); -Ogre::MeshSerializer ser; -ser.exportMesh(mesh, "my_grass.mesh"); - -Ogre::StaticGeometry* mField; -``` - -# A field of grass - -Now we get to the creation of our static geometry. The first thing we do is create an entity from the grass mesh we constructed, then we ask the scene manager to give us a pointer to a new StaticGeometry object. - -@snippet Samples/Simple/include/Grass.h static_geom - -Here, RegionDimensions refer to the physical size of one batch. All grass patches located within the region will be treated as one. Patches outside the region will be in a separate batch. This allows you to trade culling for batching effectiveness. - -Now we will prepare the actual build. We are going to loop through points on the floor of our region and place a grass patch with a random offset at each point. - -@snippet Samples/Simple/include/Grass.h grass_field - -We've partitioned the floor of our region into enough sections to fit all of our grass patches. The first thing we do is calculate an offset that will be used to randomly nudge each grass patch. This will help it look a little more natural. We use this offset to define a position vector for our object. To do this, we use the Ogre::Math::RangeRandom. We then use the same method to create a randomized scale vector to add some more variety to our grass. Our three quads were already rotated 60 degrees from each other, but now we are randomly rotating the entire grass patch as a whole. -Always remember to play around with numbers like these to create surprising effects in your scene. Some great game mechanics have been discovered by doing exactly this. - -The last thing we do is add a new grass entity to our scene using all of the information we've just set up. We then call the `build` method to construct our StaticGeometry object. - -@note When defining static geometry, you will either use Ogre::StaticGeometry::addEntity or Ogre::StaticGeometry::addSceneNode. The latter method adds all of the entities attached to that scene node to the static geometry. It uses the positions, orientations, and scales of the child nodes instead of requiring you to specify them manually. When using `addSceneNode`, be sure to remove the scene node from its previous parent. If you do not, Ogre will render them both. - -# Animating StaticGeometry -Once you have created a StaticGeometry object, you are not supposed to do much more with it. After all, that's the entire point behind static geometry - it's supposed to be static. As mentioned before, you can use certain tricks to do things like grass waving in the wind. If you are interested in how to do this, then take a look at the `Examples/GrassBladesWaver` material, which adds wave-like behavior to our grass meshes through a vertex-shader. - -# Advanced Object Batching -This is just the beginning of the batching technique. StaticGeometry objects are useful for grouping together many things that will not move. But if you're trying to create something more massive, like a forest or a large terrain covered in grass, then you should look into more advanced batching techniques. A good place to start is the [PagedGeometry Engine](https://ogrecave.github.io/ogre-pagedgeometry/). It works similar to StaticGeometry, but extends it with paging and automatic Impostor generation for LOD. - -If you actually need your Entities to move in space or if each entity consists of many vertices, rather take a look at Ogre::SceneManager::createInstanceManager. \ No newline at end of file diff --git a/Docs/src/tutorials/trays.md b/Docs/src/tutorials/trays.md deleted file mode 100644 index 2f4030fb222..00000000000 --- a/Docs/src/tutorials/trays.md +++ /dev/null @@ -1,183 +0,0 @@ -# Trays GUI System {#trays} - -Ever wanted really simple GUI controls for your sample? Don't want to write one from scratch, but CEGUI's just a little too much? The Trays system was created to address this issue. It's a simple GUI system based on the OGRE @ref Overlays system and designed just for samples. Because it's simple, you're not going to be able to skin it or build very unique interfaces, but you'll also find it much easier to use. - -@tableofcontents - -# Trays {#trays-1} -Why trays? The concept of trays is central to the system in that it removes the need for the GUI designer (you) to calculate or specify positional coordinates of any kind. Think about the widget locations in a typical GUI. They are almost always in any of the four corners, along any of the four edges or, on the rare occasion, in the center of the screen. In Trays, there are nine "trays", one in each of the locations previously mentioned. When you create a widget, you specify one of these nine locations, and the widget will be added to the tray at that location. Your widget will be added directly beneath the last widget in that tray. When you add a widget to a tray, the tray grows in size. Trays along the top of the screen grow downward, Trays along the bottom grow upward, and the trays in the middle row grow vertically in both directions. Visually, the trays are semi-transparent panels that fit the widgets they contain. Only non-empty trays are visible. If this is hard to visualise, don't worry, here's a picture to help you out. -![](Gui2.jpg) - -# TrayManager {#traymanager} -To use Trays, you have to create an TrayManager. This is the class through which you will create and manage all your widgets, manipulate the cursor, change the backdrop image, adjust tray properties, pop up dialogs, show/hide the loading bar, etc. You can have multiple tray managers in one application. For example, the OGRE Sample Browser uses its own tray manager and hides it when a sample is running, and the SDK samples also have their own tray managers, which are hidden when the samples are paused by the browser. - -@note The TrayManager requires `Trays.zip`, so you can only create it after loading that resource. Also, make sure you're correctly initialized the @ref Overlays Component as the Trays Framework depends on it. - -Create your tray manager like so: -```cpp -OgreBites::TrayManager* mTrayMgr = new OgreBites::TrayManager("InterfaceName", mWindow); -``` -You must pass in a name for your interface and a Ogre::RenderWindow. Optionally pass a `OgreBites::TrayListener` as a third argument if you want to be notified on e.g. button press. You can extend your sample or sample context to be a tray listener. Remember to destroy your tray manager like so: -```cpp -delete mTrayMgr; -``` -Once you have your tray manager, make sure you relay input events to it. -```cpp -addInputListener(mTrayMgr); -``` -@note In case you also want to handle the events yourself: -The listener methods on TrayManager return true if the event was relevant to the tray manager, and should not be processed again by you. For example, if you click a button that is over an interactive part of your scene, you want the button to be pressed, but you don't want the scene interaction to take place. So the listener methods double as filters for your mouse events. - -You're now free to create widgets! Try adding a button to the top-left tray: -```cpp -Button* b = mTrayMgr->createButton(TL_TOPLEFT, "MyButton", "Click Me!"); -``` -TrayManager is a huge class, and you can do tons of things with it. For some examples, see the Things to Try section below. - -## The Cursor -The cursor has three parts in the Trays system: The layer it moves around in Overlay, the container which positions the cursor (OverlayContainer), and the cursor image, which is a child of the container (OverlayElement). When hiding/showing the cursor, the entire cursor layer is hidden/shown. The top left corner of the cursor container is used as the hotspot of the cursor. By positioning the cursor image relative to the cursor container, you can basically decide which part of the cursor image is the "clicking part". For the default arrow cursor, the image is simply lined up with the container, meaning the top left is the hotspot. However, for something like a crosshair cursor, you could move the cursor image so that its center is over the top left corner of the cursor container. To show the cursor, use `OgreBites::TrayManager::showCursor`, which takes an optional material name for the cursor image. If unspecified, the cursor image is not changed. To hide the cursor, use `OgreBites::TrayManager::hideCursor`. You can get the cursor's different parts using getCursorLayer, getCursorContainer, and getCursorImage. Note that if the cursor is hidden, all interactions with widgets are disabled. - -## The Backdrop -If you want to show a backdrop, use `OgreBites::TrayManager::showBackdrop`, which takes an optional material name for the backdrop. If unspecified, the backdrop image is not changed. To hide it, use `OgreBites::TrayManager::hideBackdrop`. - -# Widgets {#widgets} -There are 10 basic widgets. Each widget is just an instance of an OverlayElement template, and all widgets use {LEX()}pixel{LEX} metrics. You can get access to any widget's underlying OverlayElement through `OgreBites::Widget::getOverlayElement`. Do not instantiate and delete widgets manually. Create and destroy them using the TrayManager. The first argument to any one of TrayManager's widget creation methods is the location of the tray you want the widget to be in. This is of the enumerated type TrayLocation. The second argument is the name of your widget (this is not your widget's caption, but a unique string identifier for your widget). The rest of the arguments are specific to the type of widget. - -## Button -This is the most basic widget of all. To create a button, use `OgreBites::TrayManager::createButton`. In addition to a tray location and a name, you must specify a caption for your button, and an optional width. If width is not specified, the button will automatically resize to fit its caption. There are no button states. You only get notified when a button is pushed. To see how to respond to button push events, see the TrayListener section below. - -## TextBox -This widget consists of a bold caption bar and a text area that can be scrolled vertically. In addition to a tray location and a name, `OgreBites::TrayManager::createTextBox` takes a caption, width, and height. You can set/get the caption, the text area contents, text padding, text alignment, manually change the scroll bar position, among other things. - -## SelectMenu -A basic drop-down menu. To create it, use `OgreBites::TrayManager::createLongSelectMenu` or `OgreBites::TrayManager::createThickSelectMenu`. Both these methods return a SelectMenu object, but they give one of two different visual styles to the widget. One is thicker, but shorter, because it places the caption over the item box. This style of menu is good for putting in the side trays. The other is longer, but thinner, because it places the item box next to the caption. This style of menu is good for putting in the top or bottom trays. createThickSelectMenu takes a tray location, a name, a caption, the width of the whole widget, the maximum number of visible items when expanded, and an optional string vector of items. The medthod `createLongSelectMenu` takes nearly the same arguments, except that it needs the width of the text box that shows the currently selected item. Also, for long menus, it is optional to specify the total width because it will automatically resize to fit the item box and the caption. You can set/get the caption, and set/get the items in many different ways. You can also manually change the selection, with the option of not firing an event. To see how to respond to menu item selection events, see the TrayListener section below. - -## Label -A big, semi-transparent, tabby-looking label. This widget uses a different font from the rest of the widgets, and is good for section headings and such. In addition to a tray location and a name, `OgreBites::TrayManager::createLabel` takes a caption, and an optional width. If the width is not specified, the label automatically adjusts its width to fill the tray it's currently in, so it matches the other contents of the tray. Labels can also be clicked. To see how to respond to label click events, see the TrayListener section below. - -## Separator -A horizontal line which looks like it was etched into the tray. Good for dividing up other widgets into sections without taking up as much space as a label. `TrayManager::createSeparator` takes a tray location, name, and an optional width. If the width is not specified, the behaviour is the same as a Label's. - -## Slider -A slider bar consists of a container box, a small text box to display the value, and a track + handle. Sliders are type-agnostic. Using three parameters - a minimum value, a maximum value, and the number of "snapping points", you can give your slider track of any kind of discrete scale - integer, floating point, or even nominal. Snapping points are basically the "steps" on your slider track. By specifying how many of them there are, you are in effect specifying an entire range of values all the way from your minimum value to your maximum value. Let's say you have minimum value 0, maximum value 1, and 6 snapping points. Underneath the surface, each slider stores a floating point value, so in this case you would be able to display 6 floating point values: {0, 0.2, 0.4, 0.6, 0.8, 1}. The slider will display your value in the cleanest way possible (using `Ogre::StringConverter::toString`). This means that if all your values happen to land on integers, then they will be displayed as integers without decimals. You can also exploit this by using your slider's integer values as indices into an array of string values, and manually set your slider's value to the new string value. Basically, you can make your slider display things like Low, Medium, High, 1/4, 3/4, $4.00, N/A, etc. This requires you to respond to slider move events. More on this in the TrayListener section below. Then your Like select menus, sliders also come in two flavours - thick and long. The thick style places the caption and the value box above the track, while the long style places the caption, track, and value box side by side in that order. `OgreBites::TrayManager::createThickSlider` takes a tray location, name, caption, total width, value box width, minimum value, maximum value, and the number of snapping points. `OgreBites::TrayManager::createLongSlider` takes a an optional total width, track width, value box width, minimum value, maximum value, and the number of snapping points. If the total width is not specified, the slider will automatically scale to fit the track, the value box, and the caption text. You can get/set the slider's caption, displayed value, actual value, and range of values. When you change the range, the value is reset to be the minimum value. When you change the value, you also have the option of not firing an event. To respond to slider move events, see the TrayListener section below. - -## ParamsPanel -This panel displays an arbitrary number of parameters and their values. This could be anything you want. For example, the stats panel in the SDK samples shows the average framerate, best framerate, batch count, etc. The details panel in the SDK samples shows the texture filtering technique, the polygon mode, and the camera position and orientation. To create a ParamsPanel, use `OgreBites::TrayManager::createParamsPanel`, which takes a tray location, a name, a width, and then either a string vector of parameter names or the number of parameters (lines) to leave room for. The parameter names will be left justified, and their values will be right justified on the same line. At any time, you can set/get the parameter names and values either one at a time, or all at once using a string vector. - -## CheckBox -Self-explanatory. `OgreBites::TrayManager::createCheckBox` takes a tray location, name, caption, and an optional width. Unspecified width means auto-fit to caption. You can set/get the state of the check box, with the option of not triggering an event. To respond to check box state change events, see the TrayListener section below. -## DecorWidget -This widget takes any OverlayElement template, and creates a widget out of it. If you want to put your own picture, icons, or other static objects into the trays, make an OverlayElement template out of it, and then turn it into a DecorWidget. `OgreBites::TrayManager::createDecorWidget` takes a tray location, a name, and an OverlayElement template name. These are basically the same things you would normally use to create an OverlayElement from a template. The OGRE logo in the SDK samples is a DecorWidget. -## ProgressBar -A progress bar with a caption, a comment/details box, and a meter that fills up. `OgreBites::TrayManager::createProgressBar` takes a tray location, a name, a caption, a total width, and comment box width. You can use progress bars to show any kind of progress you want, but for the most common kind (loading resources), there's a special instance of ProgressBar already created by TrayManager which you can use. See Loading Bar below. - -## The Null Tray -In addition to the nine trays you can place your widgets in, there is also a "null tray". This is an imaginary tray, whose location is specified by `TL_NONE`. This tray is virtual, invisible, and does not arrange widgets within it. Basically, if you place a widget in this tray, it becomes "free-floating", and you're allowed to manually position it anywhere on the screen. Widgets must always reside in a tray for as long as they exist, so when a widget is removed from a tray, it is automatically placed in the null tray. - -# Special Widgets {#special-widgets} -Some widgets are so common they deserve special treatment. - -## Frame Stats -This is not exactly one widget, but a combination of Label that displays the current FPS, and a ParamsPanel that displays advanced frame statistics (such as average FPS and batch count). Use `OgreBites::TrayManager::showFrameStats` and `OgreBites::TrayManager::hideFrameStats` to show/hide this special widget. You can choose where to put it. When the user clicks the FPS label, it toggles the visibility of the advanced frame stats, so they can be out of the way when they're unwanted. You can also manually toggle the visibility of the advanced frame stats using `OgreBites::TrayManager::toggleAdvancedFrameStats`. - -## Logo -This is just a decor widget of the OGRE logo. Use `OgreBites::TrayManager::showLogo` and `OgreBites::TrayManager::hideLogo` to show/hide the logo. You can choose where to put it. - -## Loading Bar -This is a progress bar that shows you the progress of your current resource loading job. The comment box will show the current resource being loaded. Use `OgreBites::TrayManager::showLoadingBar` before you begin your loading job. Specify the number of resource groups you will initialise, the number of groups you will load, and, if you want to, the proportion of time you think will go to initialisation (default estimate is 70%). You cannot decide where to place this loading bar. The screen will be darkened, and the loading bar will appear in the center. Any other dialog or loading bar will be closed. When you finish your loading job, call `OgreBites::TrayManager::hideLoadingBar`. - -## Information Dialog -This is a dialog which tells the user something and displays an OK button. It's a combination of a TextBox and a Button. Use `OgreBites::TrayManager::showOkDialog` to display an information dialog. Specify the caption of the TextBox, and the message you want to display in it. Any other dialog or loading bar will be closed. The screen will be darkened, and the dialog will appear in the center. All other widget interactions are disabled until the dialog is closed. You can manually close a dialog using `OgreBites::TrayManager::closeDialog`. To respond to information dialog closing events, see the TrayListenersection below. - -## Question Dialog -Same as the Information Dialog except it asks the user something and displays a Yes button and a No button. Use `OgreBites::TrayManager::showYesNoDialog` to display a question dialog. Specify the caption of the TextBox, and the question you want to display in it. To respond to question dialog closing events, see the TrayListener section below. - -# TrayListener {#tray-listener} -This class contains handlers for all the different events that your widgets can fire. The TrayManager class itself is an TrayListener, because it responds to events from its special widgets. You should extend your sample class from TrayListener as well as Sample if you want to handle widget events. If you're using SdkSample, you're all set because it's already an TrayListener. Some widgets give you an option of not firing an event when you change their state. This is helpful for initialising or resetting a widget, in which case there shouldn't be a response of any sort. For example, if you're initialising your slider bar before the scene is set up, and your slider bar is used to control some part of your scene, firing an event would cause an error. Below is a list of the different handlers. All handlers have return type void. -* __buttonHit__: Gives you a pointer to the Button which was hit. -* __itemSelected__: Gives you a pointer to the SelectMenu the item was chosen from. You can then use the SelectMenu to see which item was selected. -* __labelHit__: Gives you a pointer to the Label that was clicked. -* __sliderMoved__: Gives you a pointer to the Slider whose value was changed. You can then use the Slider to see what its new value is. Also, you can convert this value into a more suitable form and display it using Slider::setDisplayedValue. -* __checkBoxToggled__: Gives you a pointer to the CheckBox whose state was changed. You can then use the CheckBox to see if it's been checked or unchecked. -* __okDialogClosed__: Gives you the message of the OK dialog that was closed. -* __yesNoDialogClosed__: Gives you the question of the Yes-No dialog that was closed, and a boolean indicating whether or not the Yes button was pressed. - -# Things to Try {#things-to-try} -Getting access to widgets: -```cpp -Button* b; -b = (Button*)mTrayMgr->getWidget("MyButton"); // by name -b = (Button*)mTrayMgr->getWidget(TL_LEFT, 0); // by tray and position -b = (Button*)mTrayMgr->getWidget(TL_LEFT, "MyButton"); // by tray and name -b = (Button*)mTrayMgr->getWidgets(TL_LEFT).front(); // by tray -``` -Counting widgets: -```cpp -unsigned int n = mTrayMgr->getNumWidgets(); // total -unsigned int n = mTrayMgr->getNumWidgets(TL_LEFT); // by tray -``` -Moving widgets to other trays: -```cpp -mTrayMgr->moveWidgetToTray(b, TL_TOP); -mTrayMgr->moveWidgetToTray(b, TL_BOTTOM, 1); -mTrayMgr->moveWidgetToTray(TL_BOTTOM, 1, TL_RIGHT, 3); -mTrayMgr->moveWidgetToTray(TL_RIGHT, 3, TL_BOTTOM); -mTrayMgr->moveWidgetToTray("MyButton", TL_TOP); -mTrayMgr->moveWidgetToTray(TL_TOP, "MyButton", TL_LEFT); -``` -Removing widgets from trays: -```cpp -mTrayMgr->removeWidgetFromTray(b); -mTrayMgr->removeWidgetFromTray("MyButton"); -mTrayMgr->removeWidgetFromTray(TL_LEFT, 0); -mTrayMgr->moveWidgetToTray(b, TL_NONE); -mTrayMgr->clearTray(TL_LEFT); -mTrayMgr->clearAllTrays(); -``` -Destroying widgets: -```cpp -mTrayMgr->destroyWidget(b); -mTrayMgr->destroyWidget("MyButton"); -mTrayMgr->destroyWidget(TL_LEFT, 0); -mTrayMgr->destroyAllWidgetsInTray(TL_LEFT); -mTrayMgr->destroyAllWidgets(); -``` -Finding the position of a widget in a tray: -```cpp -unsigned int pos = mTrayMgr->locateWidgetInTray(b); -``` -Finding the tray a widget is in: -```cpp -TrayLocation trayLoc = b->getTrayLocation(); -``` -Changing the tray listener object: -```cpp -mTrayMgr->setListener(newListener); -``` -Toggling system visibility: -```cpp -mTrayMgr->showAll(); -mTrayMgr->hideAll(); -``` -Changing horizontal widget alignment in one tray: -```cpp -mTrayMgr->setTrayWidgetAlignment(TL_LEFT, GHA_RIGHT); -``` -Changing spacing and padding: -```cpp -mTrayMgr->setWidgetSpacing(5); -mTrayMgr->setWidgetPadding(3); -mTrayMgr->setTrayPadding(12); -``` -Casting 3D ray from under cursor into the scene: -```cpp -Ray r = mTrayMgr->getCursorRay(mCamera); -``` -Casting 3D ray from any 2D screen coordinate into the scene: -```cpp -Ray r = OgreBites::TrayManager::screenToScene(mCamera, Vector2(320, 240)); -``` -Converting a 3D scene coordinate to a 2D screen coordinate: -```cpp -Vector2 p = OgreBites::TrayManager::sceneToScreen(mCamera, Vector3::ZERO); -``` diff --git a/Docs/src/tutorials/tutorials.md b/Docs/src/tutorials/tutorials.md deleted file mode 100644 index 22dff00e247..00000000000 --- a/Docs/src/tutorials/tutorials.md +++ /dev/null @@ -1,24 +0,0 @@ -# Tutorials {#tutorials} - -- Getting Started - - @subpage building-ogre - - @subpage setup - - @subpage tut_FirstScene - - @subpage tut_LightsCamerasShadows - - @subpage tut_TerrainSkyFog - - @subpage working-with-numpy -- Components - - @subpage trays - - @subpage volume - - @subpage meshlod-generator - - @subpage dotscene_overview -- In Depth - - @subpage manual-mesh-creation - - @subpage tut_StaticGeom - - @subpage profiler - - @subpage reversed-depth - - @subpage External-Texture-Sources - - @subpage background-resource - - @subpage ShadowMappingOgre - - @subpage deferred - - @subpage pczscenemanager diff --git a/Docs/src/tutorials/volume.md b/Docs/src/tutorials/volume.md deleted file mode 100644 index c4fa41a0df8..00000000000 --- a/Docs/src/tutorials/volume.md +++ /dev/null @@ -1,135 +0,0 @@ -# Volume Component {#volume} - -Welcome to the Volume Component of OGRE. It is a component to render volumes. It can handle any volume data but featurewise has a tedency towards terrains. -The terrain aspect means, that it's all about huge meshes being displayed with high performance via a level of detail mechanism. Thanks to volume rendering, caves, cliffes, holes and similar geometry can be displayed. Also constructive solid geometry gets easy. - -@tableofcontents - -A dense list of the features: -* Volume Rendering via Dual Marching Cubes -* LOD mechanism via a chunk tree and marching squares skirts for crack patching -* Data-Sources: 3D Textures with density values and the ability to buildup a CSG-Tree with 3D Textures, Spheres, Cubes, Planes, Intersection, Union, Difference and Negation, SimplexNoise addition -* Loading a 3D Texture Scene from config files -* An own file format for discrete density values which compresses a lot better -* Realtime editing -* Serialization and Deserialization from and to an own file format for discrete density values which compresses a lot better than 3D textures -* A triplanar texturing example material -* A triplanar texturing SubRenderState for the RTSS - -This documentation is only intended for the usage of the Volume Component, not the algorithms which make it work. If you want to get to know the theory behind it, you can read the articles on this page: http://volume-gfx.com/ - -# How to use it {#howto} - -Here is an example loading the volume scene from a configuration file. The configuration file must be findable by the resource system of course. Only "OgreVolumeChunk.h" has to be included. -```cpp -Ogre::Volume::Chunk *volumeRoot = OGRE_NEW Ogre::Volume::Chunk(); -SceneNode *volumeRootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("VolumeParent"); -volumeRoot->load(volumeRootNode, mSceneMgr, "volumeTerrain.cfg"); -``` -The first line creates the volume chunk which is the MovableObject holding the Volume-Root. Next, a SceneNode is created where the volume(-tree) is attached to. And lastly, the volume is loaded from the configuration file "volumeTerrain.cfg". -mSceneMgr is the SceneManager who should show the volume. Later, when you don't need it anymore, you have to free the volumeRoot Chunk via OGRE_DELETE. - -# Manual creation of a CSG-Tree {#creation} - -This example skips the configuration file and loads a simple CSG-Scene: An union of a 3D Texture and a sphere with 5 LOD levels. It also setups a material LOD system. -First, create a sphere with the radius 5 at the coordinates 128, 150, 128: -```cpp -Ogre::Volume::CSGSphereSource sphere (5, Vector3(128, 150, 128)); -``` -Now a 3D texture from "volumeTerrainBig.dds" which has the world dimensions 256, 256, 256. The next flag indicates that the trilinear interpolation of the value-selection should be activated. We switch off the trilinear interpolation and the sobel filter of the normal for the sake of faster loading times: -```cpp -Ogre::Volume::TextureSource volumeTexture ("volumeTerrainBig.dds", 256, 256, 256, true, false, false); -``` -Now combine them: -```cpp -Ogre::Volume::CSGUnionSource unionSrc (&sphere, &volumeTexture); -``` -Set the general parameters, see the comments for their meaning: -```cpp -Ogre::Volume::ChunkParameters parameters; -parameters.sceneManager = mSceneMgr; // The SceneManager to use -parameters.src = &unionSrc; // The just created density source. -parameters.baseError = 1.8; // The error of the highest LOD-level -parameters.errorMultiplicator = 0.9; // The factor between each LOD-level (error = baseError * errorMultiplicator * level) -parameters.skirtFactor = 0.7; // Controls how long the skirts are. The lower the number, the shorter the skirts are. This saves geometry. But if they are too short, cracks might occur. -parameters.scale = 10; // The displayed volume will be scaled by this factor. -parameters.maxScreenSpaceError = 30; // The screen space error controlling when the LOD-levels change. -``` - -Create the root-chunk and load now. The two vectors define the area to be scanned in the volume-source. The following integer determines the amount of LOD-levels. -```cpp -Ogre::Volume::Chunk *volumeRoot = OGRE_NEW Chunk(); -volumeRoot->load(mVolumeRootNode, Vector3::ZERO, Vector3(256), 5, ¶meters); -``` -Now setup the global volume material: -```cpp -volumeRoot->setMaterial("triplanarReference"); -``` -# Getting the triangles of the chunks {#triangles} - -When you want to integrate the volume triangles in a physics engine for example, you need to hand over the exact triangles. For this scenario, the ChunkParameters hold a pointer to a ''MeshBuilderCallback'' and a number ''lodCallbackLod''. The first is an interface with a single function ''trianglesReady'' which is called, when the triangles of a chunk are ready. The chunks are chosen via the ''lodCallbackLod''. If you build a volume with 3 LOD levels and you want the triangles of the highest detail level, you set this parameter to 3. Example: - -```cpp -class MyMeshBuilderCallback : public MeshBuilderCallback -{ -public: - virtual ready(const SimpleRenderable *simpleRenderable, const VecVertex &vertices, const VecIndices &indices, size_t level, int inProcess) - { - size_t count = indices.size(); - for (size_t i = 0; i < count; i += 3) - { - Vertex v1 = vertices[indices[i]]; - Vertex v2 = vertices[indices[i + 1]]; - Vertex v3 = vertices[indices[i + 2]]; - // Do something with the Triangle... - } - } -}; -``` - -And using it like this: -```cpp -ChunkParameters parameters; -... -MyMeshBuilderCallback callback; -parameters.lodCallback = &callback; -parameters.lodCallbackLod = 3; -... -rootChunk->load(parent, from, to, 3, ¶meters); -``` -Or in case of loading from a configuration file: -```cpp -MyMeshBuilderCallback callback; -rootChunk->load(parent, sceneManager, "myVolume.cfg", 0, &callback, 3); -``` - -You might have seen, that a pointer to a SimpleRenderable is handed in, too. This is actually the Chunk whose triangles are loaded. It's parent class is used to not create a circular dependency. You might get the triangle data from it, too by getting the Renderoperation. - -# Intersecting a ray with a volume {#intersecting} - -When you want to do something exactly on the volume surface, you can cast rays and find their first intersection point. Behold that the triangle representation might be slightly different than the actual volume surface. And you have to scale the ray origin just like the volume. Here is an example which uses the negative z-axis of the camera as ray as it might be done like in an ego-shooter: -```cpp -Ray ray(mCamera->getPosition() / rootChunk->getScale(), -mCamera->getOrientation().zAxis()); -Vector3 intersection; -Real scale = mVolumeRoot->getChunkParameters()->scale; -bool intersects = mVolumeRoot->getChunkParameters()->src->getFirstRayIntersection(ray, intersection, scale); -if (intersects) -{ - intersection *= scale; // As it is in volume space. - // Do something with intersection. -} -``` - -# Editing a Volume made from a GridSource {#editing} - -A usecase is realtime editing of volume terrain as seen as in the sample. Let's union the terrain with a sphere of the radius 2.5 and the center 123/123/123. __volumeRoot__ is the Chunk instance with which the terrain was initially loaded. The factor 1.5 is just to have a save border around the sphere which also gets updated. The rest of the parameters are 5 LOD levels and a volume mesh covering an area of 384^3. -```cpp -Vector3 center(123); -Real radius = (Real)2.5; -CSGSphereSource sphere(radius, center); -CSGUnionSource operation; -static_cast(volumeRoot->getChunkParameters()->src)->combineWithSource(&operation, &sphere, center, radius * (Real)1.5); -volumeRoot->getChunkParameters()->updateFrom = center - radius * (Real)1.5; -volumeRoot->getChunkParameters()->updateTo = center + radius * (Real)1.5; -volumeRoot->load(volumeRootNode, Vector3::ZERO, Vector3(384), 5, volumeRoot->getChunkParameters()); -``` diff --git a/Docs/src/umldocs/CreateShaderBasedTech.puml b/Docs/src/umldocs/CreateShaderBasedTech.puml deleted file mode 100644 index e005cfc30ed..00000000000 --- a/Docs/src/umldocs/CreateShaderBasedTech.puml +++ /dev/null @@ -1,13 +0,0 @@ -@startuml -hide footbox - -Application -> ShaderGenerator: createShaderBasedTechnique -activate ShaderGenerator -ShaderGenerator -> SGMaterial: << new >> -ShaderGenerator -> SGTechnique: << new >> -ShaderGenerator -> SGMaterial: addTechnique(tech) - -ShaderGenerator -> SGScheme: << new >> -ShaderGenerator -> SGScheme: addTechniqueEntry(tech) -deactivate ShaderGenerator -@enduml diff --git a/Docs/src/umldocs/ResourceManagement.puml b/Docs/src/umldocs/ResourceManagement.puml deleted file mode 100644 index af06fc613d0..00000000000 --- a/Docs/src/umldocs/ResourceManagement.puml +++ /dev/null @@ -1,47 +0,0 @@ -@startuml -hide footbox - -Application -> ResourceGroupManager: createResourceGroup(group) -loop resources.cfg -Application -> ResourceGroupManager: addResourceLocation(loc, type, group) -ResourceGroupManager -> ResourceGroupManager: addToIndex(file) -end -Application -> ResourceGroupManager: initialiseResourceGroup(group) - -ResourceGroupManager -> ResourceManager: parseScript(file) -activate ResourceGroupManager -loop Examples.material -activate ResourceManager -ResourceManager -> ResourceManager: create(name, group) -ResourceManager -> Resource: << new >> -deactivate ResourceManager -end -deactivate ResourceGroupManager - -Application -> ResourceManager: load(name, group) -activate ResourceManager -ResourceManager -> Resource: << new >> -activate Resource -Resource -> Resource: prepare -Resource -> ResourceGroupManager: openResource(name, group) -activate ResourceGroupManager -ResourceGroupManager --> Resource: DataStreamPtr -deactivate ResourceGroupManager -deactivate Resource -ResourceManager --> Application: ResourcePtr -deactivate ResourceManager - -Application -> ResourceGroupManager: loadResourceGroup(group) -loop group -ResourceGroupManager -> Resource: load -end - -Application -> ResourceGroupManager: clearResourceGroup(group) -activate ResourceGroupManager -loop group -ResourceGroupManager -> ResourceManager: remove(name) -ResourceManager -> Resource: << delete >> -end -deactivate ResourceGroupManager -@enduml - diff --git a/Docs/src/umldocs/RuntimeShaderGeneration.puml b/Docs/src/umldocs/RuntimeShaderGeneration.puml deleted file mode 100644 index 2e93d32e070..00000000000 --- a/Docs/src/umldocs/RuntimeShaderGeneration.puml +++ /dev/null @@ -1,25 +0,0 @@ -@startuml -hide footbox - -ShaderGenerator -> SGScheme: validate -activate SGScheme -SGScheme -> SGScheme: syncWithScene -SGScheme -> SGTechniqe: buildRenderState -SGTechniqe -> SGPass: buildRenderState -deactivate SGScheme -activate SGPass -SGPass -> TargetRenderState: << new >> -loop globalRenderState -SGPass -> TargetRenderState: addSubRenderState -end -SGPass -> TargetRenderState: acquirePrograms(Pass) -deactivate SGPass -activate TargetRenderState -TargetRenderState -> TargetRenderState: createCpuPrograms -TargetRenderState -> ProgramManager: createGpuPrograms -activate ProgramManager -ProgramManager -> ProgramManager: hash(source) -ProgramManager --> TargetRenderState: GpuProgramPtr -deactivate ProgramManager -TargetRenderState -> TargetRenderState : bindUniformParameters -@enduml diff --git a/Docs/src/umldocs/TextureSource.puml b/Docs/src/umldocs/TextureSource.puml deleted file mode 100644 index 06b4cfe0a6d..00000000000 --- a/Docs/src/umldocs/TextureSource.puml +++ /dev/null @@ -1,42 +0,0 @@ -@startuml -skinparam backgroundcolor transparent -hide empty members -set namespaceSeparator none -class ExternalTextureSource { -+ setParameter() -} -class ExternalTextureSourceManager { -+ setExternalTextureSource() -+ setCurrentPlugin() -+ createDefinedTexture() -} -ExternalTextureSource -down-o ExternalTextureSourceManager -class ScriptTranslator { - * Set "video" plugin active - * Parse & set parameters - * Create Texture -} -class Plugin_TheoraVideoSystem { -+ install() -} -object Plugins.cfg { - Plugin=.. - Plugin=Plugin_TheoraVideoSystem - Plugin=.. -} -Plugins.cfg -- Plugin_TheoraVideoSystem -Plugin_TheoraVideoSystem -down-> ExternalTextureSourceManager -ScriptTranslator -down-> ExternalTextureSourceManager - -object "Sample Material Script" as material { -texture_source video -{ -\tfilename test.mpeg -\tplay_mode play -\tsound_mode on -} -} -material -- ScriptTranslator - -@enduml - diff --git a/Docs/src/umldocs/renderOneFrame.puml b/Docs/src/umldocs/renderOneFrame.puml deleted file mode 100644 index 2eaccffbb56..00000000000 --- a/Docs/src/umldocs/renderOneFrame.puml +++ /dev/null @@ -1,42 +0,0 @@ -@startuml -hide footbox - -Application -> Root: renderOneFrame -activate Root -Root -> RenderSystem: _updateAllRenderTargets -activate RenderSystem -RenderSystem -> RenderTarget: update -activate RenderTarget -'RenderTarget -> RenderTarget: _updateAutoUpdatedViewports -RenderTarget -> Viewport: update -activate Viewport -Viewport -> Camera: _renderScene -activate Camera -Camera -> SceneManager: _renderScene -activate SceneManager -SceneManager -> SceneManager: _renderVisibleObjects -SceneManager -> SceneManager: _renderQueueGroupObjects -loop -SceneManager -> SceneManager: _issueRenderOp -SceneManager -> Renderable: getRenderOperation -activate Renderable -Renderable --> SceneManager: RenderOperation -deactivate Renderable -SceneManager -> RenderSystem: _render -activate RenderSystem -RenderSystem --> SceneManager -deactivate RenderSystem -end -SceneManager --> Camera -deactivate SceneManager -Camera --> Viewport -deactivate Camera -Viewport --> RenderTarget -deactivate Viewport -RenderTarget --> RenderSystem -deactivate RenderTarget -RenderSystem --> Root -deactivate RenderSystem -Root --> Application -deactivate Root -@enduml diff --git a/Docs/src/umldocs/uml-overview.puml b/Docs/src/umldocs/uml-overview.puml deleted file mode 100644 index 62535d374ff..00000000000 --- a/Docs/src/umldocs/uml-overview.puml +++ /dev/null @@ -1,47 +0,0 @@ -@startuml -'left to right direction -hide members -hide methods -class Root -package SceneManagement { - MovableObject <|-- Entity - MovableObject <|-- Camera - MovableObject <|-- Light - class SceneNode - class SceneManager -} -package Plugin as Plugin1 #DDD { - SceneManager <|-- OctreeSceneManager -} -package "Resource Management" { - class ResourceGroupManager - class ResourceManager - class ImageCodec - class Mesh - class Material - class GpuProgram - class Texture -} -package Plugin as Plugin2 #DDD { - ImageCodec <|-down- FreeImageCodec -} -package Rendering { - class RenderWindow - class Renderable - class RenderSystem - class HardwareBufferManager -} -package Plugin as Plugin3 #DDD { - Texture <|-- GLTexture - RenderSystem <|-- GLRenderSystem -} - -'some dummy connection to get the desired layout -Root -right[hidden]- SceneManagement -Light -down[hidden]- Rendering -Light -down[hidden] "Resource Management" -ResourceGroupManager -down[hidden]- Texture -ResourceGroupManager -down[hidden]- ImageCodec -HardwareBufferManager -down[hidden]- RenderSystem -@enduml - diff --git a/Docs/src/vbo-update.texi b/Docs/src/vbo-update.texi deleted file mode 100644 index 47c93419542..00000000000 --- a/Docs/src/vbo-update.texi +++ /dev/null @@ -1,64 +0,0 @@ -\input texinfo @c -*-texinfo-*- -@c %**start of header -@setfilename vbo-update.info -@settitle Hardware Buffers In OGRE -@c %**end of header - -@titlepage -@title Geometry Changes In OGRE 0.12 -@author Steve Streeting -@page -@vskip 0pt plus 1fill -Copyright @copyright{} The OGRE Team@* - -Permission is granted to make and distribute verbatim -copies of this manual provided the copyright notice and -this permission notice are preserved on all copies. - -Permission is granted to copy and distribute modified -versions of this manual under the conditions for verbatim -copying, provided that the entire resulting derived work is -distributed under the terms of a permission notice -identical to this one. -@end titlepage - -@node Top -@top Geometry Changes In OGRE 0.12 -This manual covers the changes which have been made in the core geometry -and rendering operation classes in OGRE v0.12. - -@menu -* Introduction:: What's all this about anyway? -* Hardware Buffers:: All about hardware buffers -* Hardware Vertex Buffers:: The stuff that vertices are made of -* Hardware Index Buffers:: Indirect rendering through indexes -@detailmenu -@end detailmenu -@end menu - - -@node Introduction -@chapter Introduction - -Geometry handling, for obvious reasons, is at the centre of any 3D engine. OGRE inherited much of its core geometry structures from a previous engine I -designed for DirectX 6 / OpenGL, and it has worked quite well. It was based around the historical premise that applications wanted to construct a lot -of geometry in main memory, manipulate it on the CPU, and upload it in small chunks for the hardware to process every frame. This was fine because the card -couldn't handle enormous amounts of polys anyway, so it was up to the application to pick the most appropriate subset to upload. -@*@* -Times changed, however, with graphics processors beginning to have more and more of their own memory, and being able to process the transformation and lighting on the card itself, or in AGP memory, rather than main memory. This made it feasible to upload static geometry to the card and keep it there, avoiding the bandwidth requirements of the per-frame upload. The advent of vertex shaders has allowed programs to process the vertices in custom ways without having to shuffle them between main memory and the card. We'll call these GPU and AGP-based buffers 'Hardware Buffers'. We often refer to them as 'VBOs' (Vertex Buffer Objects) for speed, although the term is not exactly accurate since they can hold both vertex and index data. The use of hardware buffers can significantly improve the rendering speed of a scene, especially one with a large amount of repeating geometry or one which uses lots of multipass effects. - -@*@* -So why did we wait until now? After all, the APIs have supported hardware buffers in some shape or form for some time. Well, there were a few reasons. Firstly, it's a large and disruptive change (to do it properly and use it to it's full) so we had to find time in our schedule. We worked on a separate CVS branch to avoid disturbing regular developers for some time. Secondly, it's actually only in the past 6-12 months that both APIs have exposed these functions in such a way that makes them practical to implement in a generic engine like OGRE. Whilst DirectX has had VBOs since D3D7, version 7 was so simplistic as to be almost useless, and version 8 has a serious design flaw which tied a buffer to a single vertex format, a restriction which would have crippled our design. D3D9 is the first version to have a genuinely useful VBO design. As for OpenGL, nVidia and ATI has their own, very separate extensions to the GL API to manage VBOs - these have only recently been standardised (Feb 2003) into the ARB_vertex_buffer_object extension. So we saw this as the best possible time to bring this new feature into OGRE. - -@section More than just hardware buffers -Besides allowing buffers to be held on the GPU / AGP memory, we also took the opportunity to completely overhaul the way we represent geometry formats in the engine. Previously, the GeometryData and RenderOperation classes held explicit pointers to elements of the vertex, e.g. a pointer to the positions, a pointer to the normals etc. The type and format of the vertex elements was fixed (positions always had to be 3 floats for example), because that's how cards used too work. The latest generation of cards allow a lot more flexibility around what data you feed into them - for example if you like you can omit positions and generate them in the vertex shader, or use a 4D normal vector, among many other things. -@*@* -In addition, since hardware buffers can be very large, there is more incentive to try to reuse and share buffers between meshes, perhaps using subsets of the same buffer for different purposes, perhaps even changing vertex format half way through the buffer - this sharing can be beneficial to performance because changing the source of the 'streams' of vertex data coming into the card can be comparatively expensive. -@*@* -Finally, we also wanted to make it easier to switch the vertex sources used by a given piece of geometry, without changing the information held about the format of the vertex. Therefore we have the concept of buffer bindings - vertex elements (a position for example) are bound to a 'source index' which is not a pointer to a buffer, it's just an identifier. You then 'bind' this index to a real vertex buffer, and you can rebind it to another buffer if you wish later. -@* - -@include vbos.inc - - -@bye diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 9cb0f1e3c52..00000000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2000-2013 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/Media/Main/DefaultShaders.metal b/Media/Main/DefaultShaders.metal deleted file mode 100644 index 84defe9d4e0..00000000000 --- a/Media/Main/DefaultShaders.metal +++ /dev/null @@ -1,38 +0,0 @@ -#include "OgreUnifiedShader.h" - -struct RasterizerData -{ - vec4 pos [[position]]; - vec2 uv; -}; - -struct Vertex -{ - IN(vec3 pos, POSITION); - IN(vec2 uv, TEXCOORD0); -}; - -struct Uniform -{ - mat4 mvpMtx; - mat4 texMtx; -}; - -// first 15 slots are reserved for the vertex attributes -#define UNIFORM_INDEX_START 16 - -vertex RasterizerData default_vp(Vertex in [[stage_in]], - constant Uniform& u [[buffer(UNIFORM_INDEX_START)]]) -{ - RasterizerData out; - out.pos = u.mvpMtx * vec4(in.pos, 1); - out.uv = (u.texMtx * vec4(in.uv,1,1)).xy; - return out; -} - -fragment half4 default_fp(RasterizerData in [[stage_in]], - metal::texture2d tex [[texture(0)]], - metal::sampler s [[sampler(0)]]) -{ - return tex.sample(s, in.uv); -} \ No newline at end of file diff --git a/Media/Main/GLSL_GL3Support.glsl b/Media/Main/GLSL_GL3Support.glsl deleted file mode 100644 index a8bb9791792..00000000000 --- a/Media/Main/GLSL_GL3Support.glsl +++ /dev/null @@ -1,97 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. - -// @public-api - -#if defined(OGRE_FRAGMENT_SHADER) && defined(OGRE_GLSLES) -// define default precisions for ES fragement shaders -precision mediump float; - -#if __VERSION__ > 100 -precision lowp sampler2DArray; -precision lowp sampler2DShadow; -precision lowp sampler3D; -#endif -#endif - -#if __VERSION__ == 100 -mat2 transpose(mat2 m) -{ - return mat2(m[0][0], m[1][0], - m[0][1], m[1][1]); -} - -mat3 transpose(mat3 m) -{ - return mat3(m[0][0], m[1][0], m[2][0], - m[0][1], m[1][1], m[2][1], - m[0][2], m[1][2], m[2][2]); -} - -mat4 transpose(mat4 m) -{ - return mat4(m[0][0], m[1][0], m[2][0], m[3][0], - m[0][1], m[1][1], m[2][1], m[3][1], - m[0][2], m[1][2], m[2][2], m[3][2], - m[0][3], m[1][3], m[2][3], m[3][3]); -} -#endif - -#if __VERSION__ > 120 || defined(OGRE_GLSLANG) -#define texture1D texture -#define texture2D texture -#define texture3D texture -#define texture2DArray texture -#define textureCube texture -#define shadow2D texture -#define shadow2DProj textureProj -#define texture2DProj textureProj -#define texture2DLod textureLod -#define textureCubeLod textureLod - -#if defined(OGRE_GLSLANG) || (__VERSION__ > 150 && defined(OGRE_VERTEX_SHADER)) || __VERSION__ >= 410 -#define IN(decl, loc) layout(location = loc) in decl; -#else -#define IN(decl, loc) in decl; -#endif - -#if defined(OGRE_GLSLANG) || (__VERSION__ > 150 && defined(OGRE_FRAGMENT_SHADER)) || __VERSION__ >= 410 -#define OUT(decl, loc) layout(location = loc) out decl; -#else -#define OUT(decl, loc) out decl; -#endif - -#else - -#ifdef OGRE_VERTEX_SHADER -#define IN(decl, loc) attribute decl; -#define OUT(decl, loc) varying decl; -#else -#define IN(decl, loc) varying decl; -#define OUT(decl, loc) out decl; -#endif - -#endif - -#if defined(OGRE_FRAGMENT_SHADER) && (defined(OGRE_GLSLANG) || (__VERSION__ > 130)) -#define gl_FragColor FragColor -OUT(vec4 FragColor, 0) -#endif - -#ifdef VULKAN - -#ifdef OGRE_VERTEX_SHADER -#define OGRE_UNIFORMS_BEGIN layout(binding = 0, row_major) uniform OgreUniforms { -#else -#define OGRE_UNIFORMS_BEGIN layout(binding = 1, row_major) uniform OgreUniforms { -#endif - -#define OGRE_UNIFORMS_END }; - -#else - -#define OGRE_UNIFORMS_BEGIN -#define OGRE_UNIFORMS_END - -#endif \ No newline at end of file diff --git a/Media/Main/HLSL_SM4Support.hlsl b/Media/Main/HLSL_SM4Support.hlsl deleted file mode 100644 index 2d2e3eac1e9..00000000000 --- a/Media/Main/HLSL_SM4Support.hlsl +++ /dev/null @@ -1,98 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. - -// @public-api - -#if OGRE_HLSL >= 4 - -// SM4 separates sampler into Texture and SamplerState - -#define sampler1D Sampler1D -#define sampler2D Sampler2D -#define sampler3D Sampler3D -#define samplerCUBE SamplerCube - -struct Sampler1D -{ - Texture1D t; - SamplerState s; -}; -struct Sampler2D -{ - Texture2D t; - SamplerState s; -}; -struct Sampler3D -{ - Texture3D t; - SamplerState s; -}; -struct SamplerCube -{ - TextureCube t; - SamplerState s; -}; - -float4 tex1D(Sampler1D s, float v) { return s.t.Sample(s.s, v); } -float4 tex2D(Sampler2D s, float2 v) { return s.t.Sample(s.s, v); } -float4 tex3D(Sampler3D s, float3 v) { return s.t.Sample(s.s, v); } -float4 texCUBE(SamplerCube s, float3 v) { return s.t.Sample(s.s, v); } -float4 texCUBElod(SamplerCube s, float4 v) { return s.t.SampleLevel(s.s, v.xyz, v.w); } - -float4 tex2D(Sampler2D s, float2 v, float2 ddx, float2 ddy) { return s.t.SampleGrad(s.s, v, ddx, ddy); } -float4 tex2Dproj(Sampler2D s, float4 v) { return s.t.Sample(s.s, v.xy/v.w); } -float4 tex2Dlod(Sampler2D s, float4 v) { return s.t.SampleLevel(s.s, v.xy, v.w); } - -#define SAMPLER1D(name, reg) \ - Texture1D name ## Tex : register(t ## reg);\ - SamplerState name ## State : register(s ## reg);\ - static Sampler1D name = {name ## Tex, name ## State} - -#define SAMPLER2D(name, reg) \ - Texture2D name ## Tex : register(t ## reg);\ - SamplerState name ## State : register(s ## reg);\ - static Sampler2D name = {name ## Tex, name ## State} - -#define SAMPLER3D(name, reg) \ - Texture3D name ## Tex : register(t ## reg);\ - SamplerState name ## State : register(s ## reg);\ - static Sampler3D name = {name ## Tex, name ## State} - -#define SAMPLERCUBE(name, reg) \ - TextureCube name ## Tex : register(t ## reg);\ - SamplerState name ## State : register(s ## reg);\ - static SamplerCube name = {name ## Tex, name ## State} - -// the following are not available in D3D9, but provided for convenience -struct Sampler2DShadow -{ - Texture2D t; - SamplerComparisonState s; -}; -struct Sampler2DArray -{ - Texture2DArray t; - SamplerState s; -}; - -#define SAMPLER2DSHADOW(name, reg) \ - Texture2D name ## Tex : register(t ## reg);\ - SamplerComparisonState name ## State : register(s ## reg);\ - static Sampler2DShadow name = {name ## Tex, name ## State} - -#define SAMPLER2DARRAY(name, reg) \ - Texture2DArray name ## Tex : register(t ## reg);\ - SamplerState name ## State : register(s ## reg);\ - static Sampler2DArray name = {name ## Tex, name ## State} - -float tex2Dcmp(Sampler2DShadow s, float3 v) { return s.t.SampleCmpLevelZero(s.s, v.xy, v.z); } -float4 tex2DARRAY(Sampler2DArray s, float3 v) { return s.t.Sample(s.s, v); } -#else - -#define SAMPLER1D(name, reg) sampler1D name : register(s ## reg) -#define SAMPLER2D(name, reg) sampler2D name : register(s ## reg) -#define SAMPLER3D(name, reg) sampler3D name : register(s ## reg) -#define SAMPLERCUBE(name, reg) samplerCUBE name : register(s ## reg) - -#endif \ No newline at end of file diff --git a/Media/Main/OgreUnifiedShader.h b/Media/Main/OgreUnifiedShader.h deleted file mode 100644 index e6e59a97f98..00000000000 --- a/Media/Main/OgreUnifiedShader.h +++ /dev/null @@ -1,183 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. - -// greatly inspired by -// - shiny: https://ogrecave.github.io/shiny/defining-materials-shaders.html -// - bgfx: https://github.com/bkaradzic/bgfx/blob/master/src/bgfx_shader.sh - -/// general usage: -// MAIN_PARAMETERS -// IN(vec4 vertex, POSITION) -// MAIN_DECLARATION -// { -// GLSL code here -// } - -/// configuration -// use macros that will be default with Ogre 15 -// #define USE_OGRE_FROM_FUTURE - -// @public-api - -#if defined(OGRE_HLSL) || defined(OGRE_CG) -// HLSL -#include "HLSL_SM4Support.hlsl" -#define vec2 float2 -#define vec3 float3 -#define vec4 float4 -#define mat3 float3x3 -#define mat4 float4x4 - -#define ivec2 int2 -#define ivec3 int3 -#define ivec4 int4 - -#define texture1D tex1D -#define texture2D tex2D -#define texture3D tex3D -#define texture2DArray tex2DARRAY -#define textureCube texCUBE -#define shadow2D tex2Dcmp -#define texture2DProj tex2Dproj -vec4 texture2DLod(sampler2D s, vec2 v, float lod) { return tex2Dlod(s, vec4(v.x, v.y, 0, lod)); } - -#define samplerCube samplerCUBE -vec4 textureCubeLod(samplerCube s, vec3 v, float lod) { return texCUBElod(s, vec4(v.x, v.y, v.z, lod)); } - -#define sampler2DShadow Sampler2DShadow - -#define mix lerp -#define fract frac -#define inversesqrt rsqrt - -float mod(float _a, float _b) { return _a - _b * floor(_a / _b); } -vec2 mod(vec2 _a, vec2 _b) { return _a - _b * floor(_a / _b); } -vec3 mod(vec3 _a, vec3 _b) { return _a - _b * floor(_a / _b); } -vec4 mod(vec4 _a, vec4 _b) { return _a - _b * floor(_a / _b); } - -vec2 vec2_splat(float x) { return vec2(x, x); } -vec3 vec3_splat(float x) { return vec3(x, x, x); } -vec4 vec4_splat(float x) { return vec4(x, x, x, x); } - -mat4 mtxFromRows(vec4 a, vec4 b, vec4 c, vec4 d) -{ - return mat4(a, b, c, d); -} - -mat3 mtxFromRows(vec3 a, vec3 b, vec3 c) -{ - return mat3(a, b, c); -} - -mat3 mtxFromCols(vec3 a, vec3 b, vec3 c) -{ - return transpose(mat3(a, b, c)); -} - -#define STATIC static - -#define OGRE_UNIFORMS_BEGIN -#define OGRE_UNIFORMS_END - -#define MAIN_PARAMETERS void main( - -#ifdef OGRE_VERTEX_SHADER -#define MAIN_DECLARATION out float4 gl_Position : POSITION) -#else -#define MAIN_DECLARATION in float4 gl_FragCoord : POSITION, out float4 gl_FragColor : COLOR) -#endif - -#define IN(decl, sem) in decl : sem, -#define OUT(decl, sem) out decl : sem, -#elif defined(OGRE_METAL) -#define vec2 float2 -#define vec3 float3 -#define vec4 float4 -#define mat3 metal::float3x3 -#define mat4 metal::float4x4 - -#define IN(decl, sem) decl [[ attribute(sem) ]]; -#else -// GLSL -#include "GLSL_GL3Support.glsl" - -#ifdef VULKAN -#define _UNIFORM_BINDING(b) layout(binding = b + 2) uniform -#elif __VERSION__ >= 420 -#define _UNIFORM_BINDING(b) layout(binding = b) uniform -#else -#define _UNIFORM_BINDING(b) uniform -#endif - -#define SAMPLER1D(name, reg) _UNIFORM_BINDING(reg) sampler1D name -#define SAMPLER2D(name, reg) _UNIFORM_BINDING(reg) sampler2D name -#define SAMPLER3D(name, reg) _UNIFORM_BINDING(reg) sampler3D name -#define SAMPLER2DARRAY(name, reg) _UNIFORM_BINDING(reg) sampler2DArray name -#define SAMPLERCUBE(name, reg) _UNIFORM_BINDING(reg) samplerCube name -#define SAMPLER2DSHADOW(name, reg) _UNIFORM_BINDING(reg) sampler2DShadow name - -#define saturate(x) clamp(x, 0.0, 1.0) -#define mul(a, b) ((a) * (b)) - -#define vec2_splat vec2 -#define vec3_splat vec3 -#define vec4_splat vec4 - -mat4 mtxFromRows(vec4 a, vec4 b, vec4 c, vec4 d) -{ - return transpose(mat4(a, b, c, d)); -} - -mat3 mtxFromRows(vec3 a, vec3 b, vec3 c) -{ - return transpose(mat3(a, b, c)); -} - -mat3 mtxFromCols(vec3 a, vec3 b, vec3 c) -{ - return mat3(a, b, c); -} - -#define STATIC - -#define MAIN_PARAMETERS -#define MAIN_DECLARATION void main() - -#endif - -#if !defined(OGRE_HLSL) && !defined(OGRE_CG) -// semantics as aliases for attribute locations -#define POSITION 0 -#define BLENDWEIGHT 1 -#define NORMAL 2 -#define COLOR0 3 -#define COLOR1 4 -#define COLOR COLOR0 -#define FOG 5 -#define BLENDINDICES 7 -#define TEXCOORD0 8 -#define TEXCOORD1 9 -#define TEXCOORD2 10 -#define TEXCOORD3 11 -#define TEXCOORD4 12 -#define TEXCOORD5 13 -#define TEXCOORD6 14 -#define TEXCOORD7 15 -#define TANGENT 14 -#endif - -#define OGRE_UNIFORMS(params) OGRE_UNIFORMS_BEGIN params OGRE_UNIFORMS_END - -// GL_EXT_shader_explicit_arithmetic_types polyfill -#ifdef OGRE_GLSLES -#define float32_t highp float -#define f32vec2 highp vec2 -#define f32vec3 highp vec3 -#define f32vec4 highp vec4 -#else -#define float32_t float -#define f32vec2 vec2 -#define f32vec3 vec3 -#define f32vec4 vec4 -#endif diff --git a/Media/Main/Shadow.material b/Media/Main/Shadow.material deleted file mode 100644 index ef14b2d5d96..00000000000 --- a/Media/Main/Shadow.material +++ /dev/null @@ -1,85 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. - -material Ogre/TextureShadowCaster -{ - receive_shadows false - technique - { - pass - { - // Lighting has to be on, because we need shadow coloured objects - // Note that because we can't predict vertex programs, we'll have to - // bind light values to those, and so we bind White to ambient - // reflectance, and we'll set the ambient colour to the shadow colour - ambient 1 1 1 - diffuse 0 0 0 - specular 0 0 0 1 - emissive 0 0 0 - fog_override true none - // set depth bias in case this is used with PF_DEPTH - depth_bias -1 -1 - } - } -} - -material Ogre/StencilShadowModulationPass -{ - technique - { - pass - { - lighting off - scene_blend modulate - depth_write off - depth_check off - cull_hardware none - - vertex_program_ref Ogre/ShadowBlendVP {} - fragment_program_ref Ogre/ShadowBlendFP {} - texture_unit {} - } - } -} - -material Ogre/StencilShadowVolumes -{ - technique - { - pass - { - // program will be set dynamically to match light type - vertex_program_ref Ogre/ShadowExtrudeDirLightFinite - { - // however, the parameters here are shared between all programs - param_named_auto worldviewproj_matrix worldviewproj_matrix - param_named_auto light_position_object_space light_position_object_space 0 - param_named_auto shadow_extrusion_distance shadow_extrusion_distance 0 - } - fragment_program_ref Ogre/ShadowBlendFP {} - } - } -} - -material Ogre/Debug/ShadowVolumes -{ - technique - { - pass - { - depth_write off - scene_blend add - cull_hardware none - - // program will be set dynamically to match light type - vertex_program_ref Ogre/ShadowExtrudeDirLight - { - // however, the parameters here are shared between all programs - param_named_auto worldviewproj_matrix worldviewproj_matrix - param_named_auto light_position_object_space light_position_object_space 0 - } - fragment_program_ref Ogre/ShadowBlendFP {} - } - } -} \ No newline at end of file diff --git a/Media/Main/ShadowBlend.frag b/Media/Main/ShadowBlend.frag deleted file mode 100644 index 4b6556e6772..00000000000 --- a/Media/Main/ShadowBlend.frag +++ /dev/null @@ -1,11 +0,0 @@ -#include - -OGRE_UNIFORMS( - uniform vec4 shadowColor; -) - -MAIN_PARAMETERS -MAIN_DECLARATION -{ - gl_FragColor = shadowColor; -} diff --git a/Media/Main/ShadowBlend.vert b/Media/Main/ShadowBlend.vert deleted file mode 100644 index d052617cb15..00000000000 --- a/Media/Main/ShadowBlend.vert +++ /dev/null @@ -1,12 +0,0 @@ -#include - -OGRE_UNIFORMS( - uniform mat4 worldViewProj; -) - -MAIN_PARAMETERS -IN(vec4 vertex, POSITION) -MAIN_DECLARATION -{ - gl_Position = mul(worldViewProj, vertex); -} diff --git a/Media/Main/ShadowExtrudeDirLight.vert b/Media/Main/ShadowExtrudeDirLight.vert deleted file mode 100644 index 60809865c14..00000000000 --- a/Media/Main/ShadowExtrudeDirLight.vert +++ /dev/null @@ -1,18 +0,0 @@ -#include - -// Directional light extrude -uniform mat4 worldviewproj_matrix; -uniform vec4 light_position_object_space; // homogenous, object space - -MAIN_PARAMETERS -IN(vec4 uv0, TEXCOORD0) -IN(vec4 position, POSITION) -MAIN_DECLARATION -{ - // Extrusion in object space - // Vertex unmodified if w==1, extruded if w==0 - vec4 newpos = - (uv0.xxxx * (position + light_position_object_space)) - light_position_object_space; - - gl_Position = mul(worldviewproj_matrix, newpos); -} \ No newline at end of file diff --git a/Media/Main/ShadowExtrudeDirLightFinite.vert b/Media/Main/ShadowExtrudeDirLightFinite.vert deleted file mode 100644 index 16f758c74e6..00000000000 --- a/Media/Main/ShadowExtrudeDirLightFinite.vert +++ /dev/null @@ -1,22 +0,0 @@ -#include - -// Directional light extrude - FINITE -uniform mat4 worldviewproj_matrix; -uniform vec4 light_position_object_space; // homogenous, object space -uniform float shadow_extrusion_distance; // how far to extrude - -MAIN_PARAMETERS -IN(vec4 uv0, TEXCOORD0) -IN(vec4 position, POSITION) -MAIN_DECLARATION -{ - // Extrusion in object space - // Vertex unmodified if w==1, extruded if w==0 - vec3 extrusionDir = - light_position_object_space.xyz; - extrusionDir = normalize(extrusionDir); - - vec4 newpos = vec4(position.xyz + - ((1.0 - uv0.x) * shadow_extrusion_distance * extrusionDir), 1.0); - - gl_Position = mul(worldviewproj_matrix, newpos); -} \ No newline at end of file diff --git a/Media/Main/ShadowExtrudePointLight.vert b/Media/Main/ShadowExtrudePointLight.vert deleted file mode 100644 index 9f4ddf4d035..00000000000 --- a/Media/Main/ShadowExtrudePointLight.vert +++ /dev/null @@ -1,19 +0,0 @@ -#include - -// Point light shadow volume extrude -uniform mat4 worldviewproj_matrix; -uniform vec4 light_position_object_space; // homogenous, object space - -MAIN_PARAMETERS -IN(vec4 uv0, TEXCOORD0) -IN(vec4 position, POSITION) -MAIN_DECLARATION -{ - // Extrusion in object space - // Vertex unmodified if w==1, extruded if w==0 - vec4 newpos = - (uv0.xxxx * light_position_object_space) + - vec4(position.xyz - light_position_object_space.xyz, 0.0); - - gl_Position = mul(worldviewproj_matrix, newpos); -} \ No newline at end of file diff --git a/Media/Main/ShadowExtrudePointLightFinite.vert b/Media/Main/ShadowExtrudePointLightFinite.vert deleted file mode 100644 index 1e7134b49b8..00000000000 --- a/Media/Main/ShadowExtrudePointLightFinite.vert +++ /dev/null @@ -1,22 +0,0 @@ -#include - -// Point light shadow volume extrude - FINITE -uniform mat4 worldviewproj_matrix; -uniform vec4 light_position_object_space; // homogenous, object space -uniform float shadow_extrusion_distance; // how far to extrude - -MAIN_PARAMETERS -IN(vec4 uv0, TEXCOORD0) -IN(vec4 position, POSITION) -MAIN_DECLARATION -{ - // Extrusion in object space - // Vertex unmodified if w==1, extruded if w==0 - vec3 extrusionDir = position.xyz - light_position_object_space.xyz; - extrusionDir = normalize(extrusionDir); - - vec4 newpos = vec4(position.xyz + - ((1.0 - uv0.x) * shadow_extrusion_distance * extrusionDir), 1.0); - - gl_Position = mul(worldviewproj_matrix, newpos); -} \ No newline at end of file diff --git a/Media/Main/ShadowVolumeExtude.program b/Media/Main/ShadowVolumeExtude.program deleted file mode 100644 index 75c50e3d15f..00000000000 --- a/Media/Main/ShadowVolumeExtude.program +++ /dev/null @@ -1,41 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. - -vertex_program Ogre/ShadowBlendVP glsl glsles hlsl glslang -{ - source ShadowBlend.vert - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -fragment_program Ogre/ShadowBlendFP glsl glsles hlsl glslang -{ - source ShadowBlend.frag - default_params - { - param_named_auto shadowColor shadow_colour - } -} - -vertex_program Ogre/ShadowExtrudePointLight glsl glsles hlsl -{ - source ShadowExtrudePointLight.vert -} - -vertex_program Ogre/ShadowExtrudeDirLight glsl glsles hlsl -{ - source ShadowExtrudeDirLight.vert -} - -vertex_program Ogre/ShadowExtrudePointLightFinite glsl glsles hlsl -{ - source ShadowExtrudePointLightFinite.vert -} - -vertex_program Ogre/ShadowExtrudeDirLightFinite glsl glsles hlsl -{ - source ShadowExtrudeDirLightFinite.vert -} \ No newline at end of file diff --git a/Media/Main/spot_shadow_fade.dds b/Media/Main/spot_shadow_fade.dds deleted file mode 100644 index f672065cbcb..00000000000 Binary files a/Media/Main/spot_shadow_fade.dds and /dev/null differ diff --git a/Media/RTShaderLib/FFPLib_AlphaTest.glsl b/Media/RTShaderLib/FFPLib_AlphaTest.glsl deleted file mode 100644 index c28f0591ab3..00000000000 --- a/Media/RTShaderLib/FFPLib_AlphaTest.glsl +++ /dev/null @@ -1,45 +0,0 @@ -//----------------------------------------------------------------------------- -// Program Name: FFPLib_AlphaTest -// Program Desc: Alpha test function. -// Program Type: Vertex/Pixel shader -// Language: GLSL -//----------------------------------------------------------------------------- - -#define CMPF_ALWAYS_FAIL 0 -#define CMPF_ALWAYS_PASS 1 -#define CMPF_LESS 2 -#define CMPF_LESS_EQUAL 3 -#define CMPF_EQUAL 4 -#define CMPF_NOT_EQUAL 5 -#define CMPF_GREATER_EQUAL 6 -#define CMPF_GREATER 7 - -bool Alpha_Func(in int func, in float alphaRef, in float alphaValue) -{ - // ES2 does not have switch - if(func == CMPF_ALWAYS_PASS) - return true; - else if(func == CMPF_LESS) - return alphaValue < alphaRef; - else if(func == CMPF_LESS_EQUAL) - return alphaValue <= alphaRef; - else if(func == CMPF_EQUAL) - return alphaValue == alphaRef; - else if(func == CMPF_NOT_EQUAL) - return alphaValue != alphaRef; - else if(func == CMPF_GREATER_EQUAL) - return alphaValue >= alphaRef; - else if(func == CMPF_GREATER) - return alphaValue > alphaRef; - - // CMPF_ALWAYS_FAIL and default - return false; -} - - -void FFP_Alpha_Test(in float func, in float alphaRef, in vec4 texel) -{ - bool pass_ = Alpha_Func(int(func), alphaRef, texel.a); - if (!pass_) - discard; -} diff --git a/Media/RTShaderLib/FFPLib_Fog.glsl b/Media/RTShaderLib/FFPLib_Fog.glsl deleted file mode 100644 index b57c3241cbf..00000000000 --- a/Media/RTShaderLib/FFPLib_Fog.glsl +++ /dev/null @@ -1,92 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -//----------------------------------------------------------------------------- -// Program Name: FFPLib_Fog -// Program Desc: Fog functions of the FFP. -// Program Type: Vertex/Pixel shader -// Language: GLSL -// Notes: Implements core functions needed by FFPFog class. -// Based on fog engine. -// See http://msdn.microsoft.com/en-us/library/bb173398.aspx -// Vertex based fog: the w component of the out position is used -// as the distance parameter to fog formulas. This is basically the z coordinate -// in world space. See pixel fog under D3D docs. The fog factor is computed according -// to each formula, then clamped and output to the pixel shader. -// Pixel based fog: the w component of the out position is passed to pixel shader -// that computes the fog factor based on it. -// Both techniques use the fog factor in the end of the pixel shader to blend -// the output color with the fog color. -//----------------------------------------------------------------------------- - -#define FOG_EXP 1 -#define FOG_EXP2 2 -#define FOG_LINEAR 3 - -//----------------------------------------------------------------------------- -void FFP_FogFactor(in float depth, - in vec4 fogParams, - out float oFogFactor) -{ - float distance = abs(depth); - -#if FOG_TYPE == FOG_LINEAR - float fogFactor = (fogParams.z - distance) * fogParams.w; -#elif FOG_TYPE == FOG_EXP - float x = distance*fogParams.x; - float fogFactor = 1.0 / exp(x); -#elif FOG_TYPE == FOG_EXP2 - float x = (distance*fogParams.x*distance*fogParams.x); - float fogFactor = 1.0 / exp(x); -#endif - - oFogFactor = saturate(fogFactor); -} - -//----------------------------------------------------------------------------- -void FFP_PixelFog_PositionDepth(in mat4 mWorld, - in vec3 cameraPos, - in vec4 pos, - out vec3 oPosView, - out float oDepth) -{ - vec4 vOutPos = mul(mWorld, pos); - oPosView = vOutPos.xyz - cameraPos; - oDepth = length(oPosView); -} - -//----------------------------------------------------------------------------- -void FFP_PixelFog(in float depth, - in vec4 fogParams, - in vec4 fogColor, - in vec4 baseColor, - out vec4 oColor) -{ - float fogFactor = 0.0; - FFP_FogFactor(depth, fogParams, fogFactor); - oColor = mix(fogColor, baseColor, fogFactor); -} \ No newline at end of file diff --git a/Media/RTShaderLib/FFPLib_Texturing.glsl b/Media/RTShaderLib/FFPLib_Texturing.glsl deleted file mode 100644 index a77a2701695..00000000000 --- a/Media/RTShaderLib/FFPLib_Texturing.glsl +++ /dev/null @@ -1,144 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -//----------------------------------------------------------------------------- -// Program Name: FFPLib_Texturing -// Program Desc: Texture functions of the FFP. -// Program Type: Vertex/Pixel shader -// Language: GLSL -// Notes: Implements core functions for FFPTexturing class. -// based on texturing operations needed by render system. -// Implements texture coordinate processing: -// see http://msdn.microsoft.com/en-us/library/bb206247.aspx -// Implements texture blending operation: -// see http://msdn.microsoft.com/en-us/library/bb206241.aspx -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -void FFP_TransformTexCoord(in mat4 m, in vec2 v, out vec2 vOut) -{ - vOut = mul(m, vec4(v, 0.0, 1.0)).xy; -} -//----------------------------------------------------------------------------- -void FFP_TransformTexCoord(in mat4 m, in vec4 v, out vec2 vOut) -{ - vOut = mul(m, v).xy; -} - -//----------------------------------------------------------------------------- -void FFP_TransformTexCoord(in mat4 m, in vec3 v, out vec3 vOut) -{ - vOut = mul(m, vec4(v, 1.0)).xyz; -} - -//----------------------------------------------------------------------------- -void FFP_GenerateTexCoord_EnvMap_Normal(in mat3 mWorldIT, - in vec3 vNormal, - out vec3 vOut) -{ - vOut = normalize(mul(mWorldIT, vNormal)); -} - -//----------------------------------------------------------------------------- -void FFP_GenerateTexCoord_EnvMap_Sphere(in mat4 mWorldView, - in mat3 mWorldIT, - in vec4 vPos, - in vec3 vNormal, - out vec2 vOut) -{ - vec3 normal = normalize( mul(mWorldIT, vNormal)); - vec3 eyedir = normalize(mul(mWorldView, vPos)).xyz; - vec3 r = reflect(eyedir, normal); - r.z += 1.0; - float two_p = 2.0 * length(r); - vOut = vec2(0.5 + r.x / two_p, 0.5 - r.y / two_p); -} - -//----------------------------------------------------------------------------- -void FFP_GenerateTexCoord_EnvMap_Reflect(in mat4 mWorld, - in mat4 mWorldIT, - in vec3 vCamPos, - in vec3 vNormal, - in vec4 vPos, - out vec3 vOut) -{ - vec3 vWorldNormal = normalize(mul(mWorldIT, vec4(vNormal, 0.0)).xyz); - vec3 vWorldPos = mul(mWorld, vPos).xyz; - vec3 vEyeDir = normalize(vWorldPos - vCamPos); - - vec3 vReflect = reflect(vEyeDir, vWorldNormal); - vReflect.z *= -1.0; - - vOut = vReflect; -} - -//----------------------------------------------------------------------------- -void FFP_AddSmooth(in float vIn0, in float vIn1, out float vOut) -{ - vOut = vIn0 + vIn1 - (vIn0 * vIn1); -} - -//----------------------------------------------------------------------------- -void FFP_AddSmooth(in vec2 vIn0, in vec2 vIn1, out vec2 vOut) -{ - vOut = vIn0 + vIn1 - (vIn0 * vIn1); -} - -//----------------------------------------------------------------------------- -void FFP_AddSmooth(in vec3 vIn0, in vec3 vIn1, out vec3 vOut) -{ - vOut = vIn0 + vIn1 - (vIn0 * vIn1); -} - -//----------------------------------------------------------------------------- -void FFP_AddSmooth(in vec4 vIn0, in vec4 vIn1, out vec4 vOut) -{ - vOut = vIn0 + vIn1 - (vIn0 * vIn1); -} -//----------------------------------------------------------------------------- -void FFP_DotProduct(in float vIn0, in float vIn1, out float vOut) -{ - vOut = dot(vIn0, vIn1); -} - -//----------------------------------------------------------------------------- -void FFP_DotProduct(in vec2 vIn0, in vec2 vIn1, out vec2 vOut) -{ - vOut = vec2_splat(dot(vIn0, vIn1)); -} - -//----------------------------------------------------------------------------- -void FFP_DotProduct(in vec3 vIn0, in vec3 vIn1, out vec3 vOut) -{ - vOut = vec3_splat(dot(vIn0, vIn1)); -} - -//----------------------------------------------------------------------------- -void FFP_DotProduct(in vec4 vIn0, in vec4 vIn1, out vec4 vOut) -{ - vOut = vec4_splat(dot(vIn0, vIn1)); -} \ No newline at end of file diff --git a/Media/RTShaderLib/FFPLib_Transform.glsl b/Media/RTShaderLib/FFPLib_Transform.glsl deleted file mode 100644 index 936257cad72..00000000000 --- a/Media/RTShaderLib/FFPLib_Transform.glsl +++ /dev/null @@ -1,100 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -//----------------------------------------------------------------------------- -// Program Name: FFPLib_Transform -// Program Desc: Transform functions of the FFP. -// Program Type: Vertex shader -// Language: GLSL -// Notes: Implements core functions for FFPTransform class. -// based on transform engine. -// See http://msdn.microsoft.com/en-us/library/bb206269.aspx -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -void FFP_Transform(in mat4 m, - in vec4 v, - out vec3 vOut) -{ - vOut = mul(m, v).xyz; -} - -#ifdef OGRE_HLSL -void FFP_Transform(in float3x4 m, - in float4 v, - out float3 vOut) -{ - vOut = mul(m, v); -} - -//----------------------------------------------------------------------------- -void FFP_Transform(in float3x4 m, - in float3 v, - out float3 vOut) -{ - vOut = mul((float3x3)m, v); -} -#elif !defined(OGRE_GLSLES) || OGRE_GLSLES > 100 -//----------------------------------------------------------------------------- -void FFP_Transform(in mat3x4 m, - in vec4 v, - out vec3 vOut) -{ -/* transpose non-square uniform matrix for correct row-major > column-major mapping - * to keep the indexing inside the shader so mat[0] returns the same data in both GLSL and HLSL - * although it will be the first row in HLSL and the first column in GLSL - */ - vOut = v * m; -} - -void FFP_Transform(in mat3x4 m, - in vec3 v, - out vec3 vOut) -{ - vOut = v * mat3(m); -} -#endif - -//----------------------------------------------------------------------------- -void FFP_Transform(in mat4 m, - in vec3 v, - out vec3 vOut) -{ -#ifdef OGRE_HLSL - vOut = mul((float3x3)m, v); -#else - vOut = mat3(m) * v; -#endif -} - -//----------------------------------------------------------------------------- -void FFP_DerivePointSize(in vec4 params, - in float d, - out float sz) -{ - sz = params.x/sqrt(params.y + params.z*d + params.w*d*d); -} diff --git a/Media/RTShaderLib/RTSLib_IBL.glsl b/Media/RTShaderLib/RTSLib_IBL.glsl deleted file mode 100644 index f55372d581b..00000000000 --- a/Media/RTShaderLib/RTSLib_IBL.glsl +++ /dev/null @@ -1,88 +0,0 @@ -// This file is part of the OGRE project. -// code adapted from Google Filament -// SPDX-License-Identifier: Apache-2.0 - -vec3 specularDFG(const PixelParams pixel) { - return mix(pixel.dfg.xxx, pixel.dfg.yyy, pixel.f0); -} - -vec3 decodeDataForIBL(const vec4 data) { - return data.rgb; -} - -vec3 Irradiance_RoughnessOne(samplerCube light_iblSpecular, const vec3 n, float iblRoughnessOneLevel) { - // note: lod used is always integer, hopefully the hardware skips tri-linear filtering - return decodeDataForIBL(textureCubeLod(light_iblSpecular, n, iblRoughnessOneLevel)); -} - -vec3 PrefilteredDFG_LUT(sampler2D light_iblDFG, float lod, float NoV) { - // coord = sqrt(linear_roughness), which is the mapping used by cmgen. - // OGRE Specific: y is flipped compared to Filament code - return texture2DLod(light_iblDFG, vec2(NoV, 1.0 - lod), 0.0).rgb; -} - -float perceptualRoughnessToLod(float iblRoughnessOneLevel, float perceptualRoughness) { - // The mapping below is a quadratic fit for log2(perceptualRoughness)+iblRoughnessOneLevel when - // iblRoughnessOneLevel is 4. We found empirically that this mapping works very well for - // a 256 cubemap with 5 levels used. But also scales well for other iblRoughnessOneLevel values. - return iblRoughnessOneLevel * perceptualRoughness * (2.0 - perceptualRoughness); -} - -vec3 prefilteredRadiance(samplerCube light_iblSpecular, const vec3 r, float perceptualRoughness, float iblRoughnessOneLevel) { - float lod = perceptualRoughnessToLod(iblRoughnessOneLevel, perceptualRoughness); - return decodeDataForIBL(textureCubeLod(light_iblSpecular, r, lod)); -} - -vec3 getSpecularDominantDirection(const vec3 n, const vec3 r, float roughness) { - return mix(r, n, roughness * roughness); -} - -void evaluateIBL(inout PixelParams pixel, - in vec3 vNormal, - in vec3 viewPos, - in mat4 invViewMat, - in sampler2D dfgTex, - in samplerCube iblEnvTex, - in float iblRoughnessOneLevel, - in float iblLuminance, - inout vec3 color) -{ - vec3 shading_normal = normalize(vNormal); - vec3 shading_view = -normalize(viewPos); - float shading_NoV = clampNoV(abs(dot(shading_normal, shading_view))); - - // the above is currently duplicated with CookTorrance - - vec3 shading_reflected = reflect(-shading_view, shading_normal); - - // Pre-filtered DFG term used for image-based lighting - pixel.dfg = PrefilteredDFG_LUT(dfgTex, pixel.perceptualRoughness, shading_NoV); - - vec3 E = specularDFG(pixel); - vec3 r = getSpecularDominantDirection(shading_normal, shading_reflected, pixel.roughness); - - // OGRE specific: convert r and n back to world space for texture sampling - r = normalize(mul(invViewMat, vec4(r, 0.0)).xyz); - r.z *= -1.0; - shading_normal = normalize(mul(invViewMat, vec4(shading_normal, 0.0)).xyz); - - // specular layer - vec3 Fr = E * prefilteredRadiance(iblEnvTex, r, pixel.perceptualRoughness, iblRoughnessOneLevel); - - vec3 diffuseIrradiance = Irradiance_RoughnessOne(iblEnvTex, shading_normal, iblRoughnessOneLevel); - vec3 Fd = pixel.diffuseColor * diffuseIrradiance * (1.0 - E); - - Fr *= iblLuminance; - Fd *= iblLuminance; - - // Combine all terms - // Note: iblLuminance is already premultiplied by the exposure - - color = pow(color, vec3_splat(2.2)); // gamma to linear - - color += Fr + Fd; - - // linear to gamma - color = pow(color, vec3_splat(1.0/2.2)); - color = saturate(color); -} \ No newline at end of file diff --git a/Media/RTShaderLib/RTSLib_LTC.glsl b/Media/RTShaderLib/RTSLib_LTC.glsl deleted file mode 100644 index 90d5139c4fe..00000000000 --- a/Media/RTShaderLib/RTSLib_LTC.glsl +++ /dev/null @@ -1,114 +0,0 @@ -// Real-Time Polygonal-Light Shading with Linearly Transformed Cosines -// by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt -// code: https://github.com/selfshadow/ltc_code/ -// also: https://github.com/mrdoob/three.js/blob/master/src/renderers/shaders/ShaderChunk/lights_physical_pars_fragment.glsl.js -// adapted for Ogre by Pavel Rojtberg - -#define LUT_SIZE 64.0 -#define LUT_SCALE ((LUT_SIZE - 1.0)/LUT_SIZE) -#define LUT_BIAS (0.5/LUT_SIZE) - -vec3 IntegrateEdgeVec(vec3 v1, vec3 v2) -{ - float x = dot(v1, v2); - float y = abs(x); - - float a = 0.8543985 + (0.4965155 + 0.0145206*y)*y; - float b = 3.4175940 + (4.1616724 + y)*y; - float v = a / b; - - float theta_sintheta = (x > 0.0) ? v : 0.5*inversesqrt(max(1.0 - x*x, 1e-7)) - v; - - return cross(v1, v2)*theta_sintheta; -} - -float LTC_Evaluate(vec3 N, vec3 V, vec3 P, mat3 Minv, vec3 points[4], sampler2D ltc_2) -{ - vec3 dir = points[0] - P; - vec3 lightDir = cross(points[1] - points[0], points[3] - points[0]); - if(dot(dir, lightDir) < 0.0) - return 0.0; - - // construct orthonormal basis around N - vec3 T1, T2; - T1 = normalize(V - N*dot(V, N)); - T2 = cross(N, T1); - - // rotate area light in (T1, T2, N) basis - Minv = mul(Minv, mtxFromRows(T1, T2, N)); - - // polygon - vec3 L[4]; - L[0] = mul(Minv, points[0] - P); - L[1] = mul(Minv, points[1] - P); - L[2] = mul(Minv, points[2] - P); - L[3] = mul(Minv, points[3] - P); - - // project rect onto sphere - L[0] = normalize(L[0]); - L[1] = normalize(L[1]); - L[2] = normalize(L[2]); - L[3] = normalize(L[3]); - - vec3 vsum = vec3_splat(0.0); - - vsum += IntegrateEdgeVec(L[0], L[1]); - vsum += IntegrateEdgeVec(L[1], L[2]); - vsum += IntegrateEdgeVec(L[2], L[3]); - vsum += IntegrateEdgeVec(L[3], L[0]); - - float len = length(vsum); - float z = vsum.z/len; - - // clipless approximation: tabulated horizon-clipped sphere - // visually better than alternatives, but produces artifacts at low roughness values - vec2 uv = vec2(z*0.5 + 0.5, len); - uv = uv*LUT_SCALE + LUT_BIAS; - - float scale = texture2D(ltc_2, uv).w; - return len*scale; -} - -void InitRectPoints(vec3 center, vec3 ex, vec3 ey, out vec3 points[4]) -{ - points[0] = center - ex - ey; - points[1] = center + ex - ey; - points[2] = center + ex + ey; - points[3] = center - ex + ey; -} - -void evaluateRectLight(sampler2D ltc_1, sampler2D ltc_2, float roughness, vec3 N, vec3 pos, vec3 lpos, vec3 halfwidth, vec3 halfheight, - inout vec3 scol, inout vec3 dcol) -{ - vec3 points[4]; - InitRectPoints(lpos, halfwidth, halfheight, points); - - vec3 V = -normalize(pos); - - float ndotv = saturate(dot(N, V)); - vec2 uv = vec2(roughness, sqrt(1.0 - ndotv)); - uv = uv*LUT_SCALE + LUT_BIAS; - - vec4 t1 = texture2D(ltc_1, uv); - - mat3 Minv = mtxFromCols( - vec3(t1.x, 0.0, t1.y), - vec3( 0.0, 1.0, 0.0), - vec3(t1.z, 0.0, t1.w) - ); - - float spec = LTC_Evaluate(N, V, pos, Minv, points, ltc_2); - - // LTC Fresnel Approximation by Stephen Hill - // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf - vec4 t2 = texture2D(ltc_2, uv); - scol = (scol*t2.x + (1.0 - scol)*t2.y)*spec; - - mat3 Meye = mat3( - vec3(1.0, 0.0, 0.0), - vec3(0.0, 1.0, 0.0), - vec3(0.0, 0.0, 1.0) - ); - - dcol *= LTC_Evaluate(N, V, pos, Meye, points, ltc_2); -} \ No newline at end of file diff --git a/Media/RTShaderLib/RTSLib_Lighting.glsl b/Media/RTShaderLib/RTSLib_Lighting.glsl deleted file mode 100644 index ab5b9e3c5f0..00000000000 --- a/Media/RTShaderLib/RTSLib_Lighting.glsl +++ /dev/null @@ -1,18 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#define M_PI 3.14159265359 - -float getDistanceAttenuation(const vec3 params, float distance) -{ - return 1.0 / (params.x + params.y * distance + params.z * distance * distance); -} - -float getAngleAttenuation(const vec3 params, const vec3 lightDir, const vec3 toLight) -{ - float rho = dot(-lightDir, toLight); - float fSpotE = saturate((rho - params.y) / (params.x - params.y)); - return pow(fSpotE, params.z); -} \ No newline at end of file diff --git a/Media/RTShaderLib/RTSSamplers.material b/Media/RTShaderLib/RTSSamplers.material deleted file mode 100644 index fa4ef322784..00000000000 --- a/Media/RTShaderLib/RTSSamplers.material +++ /dev/null @@ -1,17 +0,0 @@ -sampler Ogre/ShadowSampler -{ - tex_address_mode border - tex_border_colour 1 1 1 1 -} - -sampler Ogre/DepthShadowSampler : Ogre/ShadowSampler -{ - compare_test on - comp_func less_equal -} - -sampler Ogre/LtcLUTSampler -{ - filtering point linear point - tex_address_mode clamp -} \ No newline at end of file diff --git a/Media/RTShaderLib/SGXLib_CookTorrance.glsl b/Media/RTShaderLib/SGXLib_CookTorrance.glsl deleted file mode 100644 index acbbe825af2..00000000000 --- a/Media/RTShaderLib/SGXLib_CookTorrance.glsl +++ /dev/null @@ -1,246 +0,0 @@ -// This file is part of the OGRE project. -// code adapted from Google Filament -// SPDX-License-Identifier: Apache-2.0 - -#include "RTSLib_Lighting.glsl" - -#ifdef HAVE_AREA_LIGHTS -#include "RTSLib_LTC.glsl" -#endif - -#ifdef OGRE_GLSLES - // min roughness such that (MIN_PERCEPTUAL_ROUGHNESS^4) > 0 in fp16 (i.e. 2^(-14/4), rounded up) - #define MIN_PERCEPTUAL_ROUGHNESS 0.089 -#else - #define MIN_PERCEPTUAL_ROUGHNESS 0.045 -#endif - -#define MEDIUMP_FLT_MAX 65504.0 -#define saturateMediump(x) min(x, MEDIUMP_FLT_MAX) - -#define MIN_N_DOT_V 1e-4 - -struct PixelParams -{ - vec3 baseColor; - vec3 diffuseColor; - float perceptualRoughness; - float roughness; - vec3 f0; - vec3 dfg; - vec3 energyCompensation; -}; - -float clampNoV(float NoV) { - // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886" - return max(NoV, MIN_N_DOT_V); -} - -// Computes x^5 using only multiply operations. -float pow5(float x) { - float x2 = x * x; - return x2 * x2 * x; -} - -// https://google.github.io/filament/Filament.md.html#materialsystem/diffusebrdf -float Fd_Lambert() { - return 1.0 / M_PI; -} - -// https://google.github.io/filament/Filament.md.html#materialsystem/specularbrdf/fresnel(specularf) -vec3 F_Schlick(const vec3 f0, float f90, float VoH) { - // Schlick 1994, "An Inexpensive BRDF Model for Physically-Based Rendering" - return f0 + (f90 - f0) * pow5(1.0 - VoH); -} - -vec3 computeDiffuseColor(const vec3 baseColor, float metallic) { - return baseColor.rgb * (1.0 - metallic); -} - -vec3 computeF0(const vec3 baseColor, float metallic, float reflectance) { - return baseColor.rgb * metallic + (reflectance * (1.0 - metallic)); -} - -float perceptualRoughnessToRoughness(float perceptualRoughness) { - return perceptualRoughness * perceptualRoughness; -} - -// https://google.github.io/filament/Filament.md.html#materialsystem/specularbrdf/geometricshadowing(specularg) -float V_SmithGGXCorrelated(float roughness, float NoV, float NoL) { - // Heitz 2014, "Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs" - float a2 = roughness * roughness; - // TODO: lambdaV can be pre-computed for all the lights, it should be moved out of this function - float lambdaV = NoL * sqrt((NoV - a2 * NoV) * NoV + a2); - float lambdaL = NoV * sqrt((NoL - a2 * NoL) * NoL + a2); - float v = 0.5 / (lambdaV + lambdaL); - // a2=0 => v = 1 / 4*NoL*NoV => min=1/4, max=+inf - // a2=1 => v = 1 / 2*(NoL+NoV) => min=1/4, max=+inf - // clamp to the maximum value representable in mediump - return saturateMediump(v); -} - -// https://google.github.io/filament/Filament.md.html#materialsystem/specularbrdf/normaldistributionfunction(speculard) -float D_GGX(float roughness, float NoH, const vec3 h, const vec3 n) { - // Walter et al. 2007, "Microfacet Models for Refraction through Rough Surfaces" - - // In mediump, there are two problems computing 1.0 - NoH^2 - // 1) 1.0 - NoH^2 suffers floating point cancellation when NoH^2 is close to 1 (highlights) - // 2) NoH doesn't have enough precision around 1.0 - // Both problem can be fixed by computing 1-NoH^2 in highp and providing NoH in highp as well - - // However, we can do better using Lagrange's identity: - // ||a x b||^2 = ||a||^2 ||b||^2 - (a . b)^2 - // since N and H are unit vectors: ||N x H||^2 = 1.0 - NoH^2 - // This computes 1.0 - NoH^2 directly (which is close to zero in the highlights and has - // enough precision). - // Overall this yields better performance, keeping all computations in mediump -#ifdef OGRE_GLSLES - vec3 NxH = cross(n, h); - float oneMinusNoHSquared = dot(NxH, NxH); -#else - float oneMinusNoHSquared = 1.0 - NoH * NoH; -#endif - - float a = NoH * roughness; - float k = roughness / (oneMinusNoHSquared + a * a); - float d = k * k * (1.0 / M_PI); - return saturateMediump(d); -} - -vec3 evaluateLight( - in vec3 vNormal, - in vec3 viewPos, - in vec4 lightPos, - in vec3 lightColor, - in vec4 pointParams, - in vec4 vLightDirView, - in vec4 spotParams, - in PixelParams pixel) -{ - vec3 vLightView = lightPos.xyz; - float fLightD = 0.0; - - if (lightPos.w != 0.0) - { - vLightView -= viewPos; // to light - fLightD = length(vLightView); - - if(fLightD > pointParams.x) - return vec3_splat(0.0); - } - - vLightView = normalize(vLightView); - - vec3 vNormalView = normalize(vNormal); - float NoL = saturate(dot(vNormalView, vLightView)); - - if(NoL <= 0.0) - return vec3_splat(0.0); // not lit by this light - - // https://google.github.io/filament/Filament.md.html#toc5.6.2 - float f90 = saturate(dot(pixel.f0, vec3_splat(50.0 * 0.33))); - - vec3 vView = -normalize(viewPos); - - // https://google.github.io/filament/Filament.md.html#materialsystem/standardmodelsummary - vec3 h = normalize(vView + vLightView); - float NoH = saturate(dot(vNormalView, h)); - float NoV = clampNoV(abs(dot(vNormalView, vView))); - - float V = V_SmithGGXCorrelated(pixel.roughness, NoV, NoL); - vec3 F = F_Schlick(pixel.f0, f90, NoH); - float D = D_GGX(pixel.roughness, NoH, h, vNormalView); - - vec3 Fr = (D * V) * F; - vec3 Fd = pixel.diffuseColor * Fd_Lambert(); - - // https://google.github.io/filament/Filament.md.html#materialsystem/improvingthebrdfs/energylossinspecularreflectance - vec3 color = NoL * lightColor * (Fr * pixel.energyCompensation + Fd); - - color *= getDistanceAttenuation(pointParams.yzw, fLightD); - - if(spotParams.w != 0.0) - { - color *= getAngleAttenuation(spotParams.xyz, vLightDirView.xyz, vLightView); - } - - return color; -} - -void PBR_MakeParams(in vec3 baseColor, in vec2 mrParam, inout PixelParams pixel) -{ - baseColor = pow(baseColor, vec3_splat(2.2)); - pixel.baseColor = baseColor; - - float perceptualRoughness = mrParam.x; - // Clamp the roughness to a minimum value to avoid divisions by 0 during lighting - pixel.perceptualRoughness = clamp(perceptualRoughness, MIN_PERCEPTUAL_ROUGHNESS, 1.0); - // Remaps the roughness to a perceptually linear roughness (roughness^2) - pixel.roughness = perceptualRoughnessToRoughness(pixel.perceptualRoughness); - - float metallic = saturate(mrParam.y); - pixel.f0 = computeF0(baseColor, metallic, 0.04); - pixel.diffuseColor = computeDiffuseColor(baseColor, metallic); - - pixel.dfg = vec3_splat(0.5); // use full f0 for energy compensation - pixel.energyCompensation = vec3_splat(0.0); // will be set later -} - -#if LIGHT_COUNT > 0 -void PBR_Lights( -#ifdef SHADOWLIGHT_COUNT - in float shadowFactor[SHADOWLIGHT_COUNT], -#endif -#ifdef HAVE_AREA_LIGHTS - in sampler2D ltcLUT1, - in sampler2D ltcLUT2, -#endif - in vec3 vNormal, - in vec3 viewPos, - in vec4 ambient, - in vec4 lightPos[LIGHT_COUNT], - in vec4 lightColor[LIGHT_COUNT], - in vec4 pointParams[LIGHT_COUNT], - in vec4 vLightDirView[LIGHT_COUNT], - in vec4 spotParams[LIGHT_COUNT], - in PixelParams pixel, - inout vec3 vOutColour) -{ - vOutColour = pow(vOutColour, vec3_splat(2.2)); // gamma to linear - - // Energy compensation for multiple scattering in a microfacet model - // See "Multiple-Scattering Microfacet BSDFs with the Smith Model" - pixel.energyCompensation = 1.0 + pixel.f0 * (1.0 / pixel.dfg.y - 1.0); - - for(int i = 0; i < LIGHT_COUNT; i++) - { -#ifdef HAVE_AREA_LIGHTS - if(spotParams[i].w == 2.0) - { - // rect area light - vec3 dcol = pixel.diffuseColor; - vec3 scol = pixel.f0; - evaluateRectLight(ltcLUT1, ltcLUT2, pixel.roughness, normalize(vNormal), viewPos, - lightPos[i].xyz, spotParams[i].xyz, pointParams[i].xyz, scol, dcol); - vOutColour += lightColor[i].xyz * (scol + dcol) * 4.0; - continue; - } -#endif - vec3 lightVal = evaluateLight(vNormal, viewPos, lightPos[i], lightColor[i].xyz, pointParams[i], vLightDirView[i], spotParams[i], - pixel); - -#ifdef SHADOWLIGHT_COUNT - if(i < SHADOWLIGHT_COUNT) - lightVal *= shadowFactor[i]; -#endif - vOutColour += lightVal; - } - - vOutColour += pixel.baseColor * pow(ambient.rgb, vec3_splat(2.2)); - - // linear to gamma - vOutColour = pow(vOutColour, vec3_splat(1.0/2.2)); - - vOutColour = saturate(vOutColour); -} -#endif \ No newline at end of file diff --git a/Media/RTShaderLib/SGXLib_DualQuaternion.glsl b/Media/RTShaderLib/SGXLib_DualQuaternion.glsl deleted file mode 100644 index e9a64a3f236..00000000000 --- a/Media/RTShaderLib/SGXLib_DualQuaternion.glsl +++ /dev/null @@ -1,172 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -//These functions are based on dqs.cg from http://isg.cs.tcd.ie/kavanl/dq/ -/* dqs.cg - - Dual quaternion skinning vertex shaders (no shading computations) - - Version 1.0.3, November 1st, 2007 - - Copyright (C) 2006-2007 University of Dublin, Trinity College, All Rights - Reserved - - This software is provided 'as-is', without any express or implied - warranty. In no event will the author(s) 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. - - Author: Ladislav Kavan, kavanl@cs.tcd.ie - -*/ - -//----------------------------------------------------------------------------- -// Program Name: SGXLib_DualQuaternion -// Program Desc: Dual quaternion skinning functions. -// Program Type: Vertex shader -// Language: GLSL -//----------------------------------------------------------------------------- - -#if defined(OGRE_HLSL) || defined(OGRE_CG) -// this is technically wrong, thats why we dont put it into OgreUnifiedShader.h -#define mat2x4 float2x4 -#define mat3x4 float3x4 -#endif - -//----------------------------------------------------------------------------- -void SGX_BlendWeight(in float blendWgt, in mat2x4 dualQuaternion, out mat2x4 vOut) -{ - vOut = blendWgt*dualQuaternion; -} - -//----------------------------------------------------------------------------- -void SGX_BlendWeight(in float blendWgt, in mat3x4 scaleShearMatrix, out mat3x4 vOut) -{ - vOut = blendWgt*scaleShearMatrix; -} - -//----------------------------------------------------------------------------- -// Adjusts the sign of a dual quaternion depending on its orientation to the root dual quaternion -void SGX_AntipodalityAdjustment(in mat2x4 dq0, in mat2x4 dq1,out mat2x4 dq2) -{ - //Accurate antipodality handling. For speed increase, remove the following line, - //though, the results will only be valid for rotations less than 180 degrees. - dq2 = (dot(dq0[0], dq1[0]) < 0.0) ? dq1 * -1.0 : dq1; -} - -//----------------------------------------------------------------------------- -void SGX_CalculateBlendPosition(in vec3 position, in mat2x4 blendDQ, out vec4 vOut) -{ - vec3 blendPosition = position + 2.0*cross(blendDQ[0].yzw, cross(blendDQ[0].yzw, position) + blendDQ[0].x*position); - vec3 trans = 2.0*(blendDQ[0].x*blendDQ[1].yzw - blendDQ[1].x*blendDQ[0].yzw + cross(blendDQ[0].yzw, blendDQ[1].yzw)); - blendPosition += trans; - - vOut = vec4(blendPosition, 1.0); -} - -//----------------------------------------------------------------------------- -void SGX_CalculateBlendNormal(in vec3 normal, in mat2x4 blendDQ, out vec3 vOut) -{ - vOut = normal + 2.0*cross(blendDQ[0].yzw, cross(blendDQ[0].yzw, normal) + blendDQ[0].x*normal); -} - -//----------------------------------------------------------------------------- -void SGX_AdjointTransposeMatrix(in mat3x4 M, out mat3 vOut) -{ - mat3 atM; - atM[0][0] = M[2][2] * M[1][1] - M[1][2] * M[2][1]; - atM[0][1] = M[1][2] * M[2][0] - M[1][0] * M[2][2]; - atM[0][2] = M[1][0] * M[2][1] - M[2][0] * M[1][1]; - - atM[1][0] = M[0][2] * M[2][1] - M[2][2] * M[0][1]; - atM[1][1] = M[2][2] * M[0][0] - M[0][2] * M[2][0]; - atM[1][2] = M[2][0] * M[0][1] - M[0][0] * M[2][1]; - - atM[2][0] = M[1][2] * M[0][1] - M[0][2] * M[1][1]; - atM[2][1] = M[1][0] * M[0][2] - M[1][2] * M[0][0]; - atM[2][2] = M[0][0] * M[1][1] - M[1][0] * M[0][1]; - - vOut = atM; -} - -//----------------------------------------------------------------------------- -void blendBonesDQ(mat2x4 bones_dq[BONE_COUNT], vec4 indices, vec4 weights, out mat2x4 blendDQ) -{ - blendDQ = bones_dq[int(indices.x)] * weights.x; - mat2x4 dqi; -#ifdef CORRECT_ANTIPODALITY - mat2x4 dq0 = blendDQ; -#endif -#if WEIGHT_COUNT > 1 - dqi = bones_dq[int(indices.y)] * weights.y; -# ifdef CORRECT_ANTIPODALITY - SGX_AntipodalityAdjustment(dq0, dqi, dqi); -# endif - blendDQ += dqi; -#endif -#if WEIGHT_COUNT > 2 - dqi = bones_dq[int(indices.z)] * weights.z; -# ifdef CORRECT_ANTIPODALITY - SGX_AntipodalityAdjustment(dq0, dqi, dqi); -# endif - blendDQ += dqi; -#endif -#if WEIGHT_COUNT > 3 - dqi = bones_dq[int(indices.w)] * weights.w; -# ifdef CORRECT_ANTIPODALITY - SGX_AntipodalityAdjustment(dq0, dqi, dqi); -# endif - blendDQ += dqi; -#endif - - blendDQ /= length(blendDQ[0]); // normalise dual quaternion -} - -void blendBonesMat3x4(mat3x4 bones_mat[BONE_COUNT], vec4 indices, vec4 weights, out mat3x4 blendMat) -{ - blendMat = bones_mat[int(indices.x)] * weights.x; -#if WEIGHT_COUNT > 1 - blendMat += bones_mat[int(indices.y)] * weights.y; -#endif -#if WEIGHT_COUNT > 2 - blendMat += bones_mat[int(indices.z)] * weights.z; -#endif -#if WEIGHT_COUNT > 3 - blendMat += bones_mat[int(indices.w)] * weights.w; -#endif -} \ No newline at end of file diff --git a/Media/RTShaderLib/SGXLib_IntegratedPSSM.glsl b/Media/RTShaderLib/SGXLib_IntegratedPSSM.glsl deleted file mode 100644 index ecd76120878..00000000000 --- a/Media/RTShaderLib/SGXLib_IntegratedPSSM.glsl +++ /dev/null @@ -1,183 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -//----------------------------------------------------------------------------- -// Program Name: SGXLib_IntegratedPSSM -// Program Desc: Integrated PSSM functions. -// Program Type: Vertex/Pixel shader -// Language: GLSL -//----------------------------------------------------------------------------- - -#ifdef PSSM_SAMPLE_CMP -#define SAMPLER_TYPE sampler2DShadow -#else -#define SAMPLER_TYPE sampler2D -#endif - -// default to 2x2 PCF -#ifndef PCF_XSAMPLES -#define PCF_XSAMPLES 2.0 -#endif - -//----------------------------------------------------------------------------- -#ifdef SHADOWLIGHT_COUNT -void SGX_ApplyShadowFactor_Modulative(in vec4 ambient, - in float fShadowFactor[SHADOWLIGHT_COUNT], - inout vec4 diffCol -#ifdef USE_SPECULAR - , inout vec4 specCol -#endif - ) -{ - float shadowFactor = fShadowFactor[0]; - for(int i = 1; i < SHADOWLIGHT_COUNT; ++i) - shadowFactor *= fShadowFactor[i]; - - diffCol.rgb = mix(ambient.rgb, diffCol.rgb, shadowFactor); - -#ifdef USE_SPECULAR - specCol.rgb *= shadowFactor; -#endif -} -#endif - -float sampleDepth(in SAMPLER_TYPE shadowMap, vec2 uv, float depth) -{ -#ifdef PSSM_SAMPLE_CMP -# if defined(OGRE_GLSL) && OGRE_GLSL < 130 - return shadow2D(shadowMap, vec3(uv, depth)).r; -# else - return shadow2D(shadowMap, vec3(uv, depth)); -# endif -#else - return (depth <= texture2D(shadowMap, uv).r) ? 1.0 : 0.0; -#endif -} - -//----------------------------------------------------------------------------- -#ifdef PSSM_SAMPLE_COLOUR -void SGX_ShadowPCF4(in sampler2D shadowMap, in vec4 shadowMapPos, in vec2 invTexSize, out float c) -{ - c = texture2DProj(shadowMap, shadowMapPos).x; -} -#else -void SGX_ShadowPCF4(in SAMPLER_TYPE shadowMap, in vec4 shadowMapPos, in vec2 invTexSize, out float c) -{ - shadowMapPos = shadowMapPos / shadowMapPos.w; -#if !defined(OGRE_REVERSED_Z) && !defined(OGRE_HLSL) && !defined(VULKAN) - shadowMapPos.z = shadowMapPos.z * 0.5 + 0.5; // convert -1..1 to 0..1 -#endif - vec2 uv = shadowMapPos.xy; - - // depth must be clamped to support floating-point depth formats. This is to avoid comparing a - // value from the depth texture (which is never greater than 1.0) with a greater-than-one - // comparison value (which is possible with floating-point formats). - float depth = clamp(shadowMapPos.z, 0.0, 1.0); - - c = 0.0; - float scale = 1.0; - float offset = (PCF_XSAMPLES / 2.0 - 0.5) * scale; - for (float y = -offset; y <= offset; y += scale) - for (float x = -offset; x <= offset; x += scale) - c += sampleDepth(shadowMap, uv + invTexSize * vec2(x, y), depth); - - c /= PCF_XSAMPLES * PCF_XSAMPLES; -} -#endif - -//----------------------------------------------------------------------------- -void SGX_ComputeShadowFactor_PSSM3(in float fDepth, - in vec4 vSplitPoints, - in vec4 lightPosition0, - in SAMPLER_TYPE shadowMap0, - in vec2 invShadowMapSize0, - #if PSSM_NUM_SPLITS > 2 - in vec4 lightPosition1, - in SAMPLER_TYPE shadowMap1, - in vec2 invShadowMapSize1, - #endif - #if PSSM_NUM_SPLITS > 3 - in vec4 lightPosition2, - in SAMPLER_TYPE shadowMap2, - in vec2 invShadowMapSize2, - #endif - in vec4 lightPosition3, - in SAMPLER_TYPE shadowMap3, - in vec2 invShadowMapSize3, - out float oShadowFactor - #ifdef DEBUG_PSSM - , out vec4 oDiffuse - #endif - ) -{ -#if !defined(OGRE_REVERSED_Z) && !defined(OGRE_HLSL) && !defined(VULKAN) - vSplitPoints = vSplitPoints * 0.5 + 0.5; // convert -1..1 to 0..1 -#endif - -#ifdef OGRE_REVERSED_Z - vSplitPoints = vec4_splat(1.0) - vSplitPoints; - fDepth = 1.0 - fDepth; -#endif - - if (fDepth <= vSplitPoints.x) - { - SGX_ShadowPCF4(shadowMap0, lightPosition0, invShadowMapSize0, oShadowFactor); -#ifdef DEBUG_PSSM - oDiffuse.r += 1.0; -#endif - } -#if PSSM_NUM_SPLITS > 2 - else if (fDepth <= vSplitPoints.y) - { - SGX_ShadowPCF4(shadowMap1, lightPosition1, invShadowMapSize1, oShadowFactor); -#ifdef DEBUG_PSSM - oDiffuse.g += 1.0; -#endif - } -#endif -#if PSSM_NUM_SPLITS > 3 - else if (fDepth <= vSplitPoints.z) - { - SGX_ShadowPCF4(shadowMap2, lightPosition2, invShadowMapSize2, oShadowFactor); -#ifdef DEBUG_PSSM - oDiffuse.r += 1.0; - oDiffuse.g += 1.0; -#endif - } -#endif - else if (fDepth <= vSplitPoints.w) - { - SGX_ShadowPCF4(shadowMap3, lightPosition3, invShadowMapSize3, oShadowFactor); -#ifdef DEBUG_PSSM - oDiffuse.b += 1.0; -#endif - } - else - { - // behind far distance - oShadowFactor = 1.0; - } -} diff --git a/Media/RTShaderLib/SGXLib_LayeredBlending.glsl b/Media/RTShaderLib/SGXLib_LayeredBlending.glsl deleted file mode 100644 index 8af709aa002..00000000000 --- a/Media/RTShaderLib/SGXLib_LayeredBlending.glsl +++ /dev/null @@ -1,825 +0,0 @@ -/* -** layered blending & misc math -** Blending modes, RGB/HSL/Contrast/Desaturate, levels control -** -** The shaders below are base on the shaders created by: -** Romain Dura | Romz -** Blog: http://blog.mouaif.org -** Post: http://blog.mouaif.org/?p=94 -*/ - - -/* -** Desaturation -*/ - -vec4 Desaturate(in vec3 color, in float Desaturation) -{ - vec3 grayXfer = vec3(0.3, 0.59, 0.11); - float grayf = dot(grayXfer, color); - vec3 gray = vec3(grayf, grayf, grayf); - return vec4(mix(color, gray, Desaturation), 1.0); -} - - -/* -** Hue, saturation, luminance -*/ - -vec3 RGBToHSL(in vec3 color) -{ - vec3 hsl; // init to 0 to avoid warnings ? (and reverse if + remove first part) - - float fmin = min(min(color.r, color.g), color.b); //Min. value of RGB - float fmax = max(max(color.r, color.g), color.b); //Max. value of RGB - float delta = fmax - fmin; //Delta RGB value - - hsl.z = (fmax + fmin) / 2.0; // Luminance - - if (delta == 0.0) //This is a gray, no chroma... - { - hsl.x = 0.0; // Hue - hsl.y = 0.0; // Saturation - } - else //Chromatic data... - { - if (hsl.z < 0.5) - hsl.y = delta / (fmax + fmin); // Saturation - else - hsl.y = delta / (2.0 - fmax - fmin); // Saturation - - float deltaR = (((fmax - color.r) / 6.0) + (delta / 2.0)) / delta; - float deltaG = (((fmax - color.g) / 6.0) + (delta / 2.0)) / delta; - float deltaB = (((fmax - color.b) / 6.0) + (delta / 2.0)) / delta; - - if (color.r == fmax ) - hsl.x = deltaB - deltaG; // Hue - else if (color.g == fmax) - hsl.x = (1.0 / 3.0) + deltaR - deltaB; // Hue - else if (color.b == fmax) - hsl.x = (2.0 / 3.0) + deltaG - deltaR; // Hue - - if (hsl.x < 0.0) - hsl.x += 1.0; // Hue - else if (hsl.x > 1.0) - hsl.x -= 1.0; // Hue - } - - return hsl; -} - -float HueToRGB(in float f1, in float f2, in float hue) -{ - if (hue < 0.0) - hue += 1.0; - else if (hue > 1.0) - hue -= 1.0; - float res; - if ((6.0 * hue) < 1.0) - res = f1 + (f2 - f1) * 6.0 * hue; - else if ((2.0 * hue) < 1.0) - res = f2; - else if ((3.0 * hue) < 2.0) - res = f1 + (f2 - f1) * ((2.0 / 3.0) - hue) * 6.0; - else - res = f1; - return res; -} - -vec3 HSLToRGB(in vec3 hsl) -{ - vec3 rgb; - - if (hsl.y == 0.0) - rgb = hsl.zzz; // Luminance - else - { - float f2; - - if (hsl.z < 0.5) - f2 = hsl.z * (1.0 + hsl.y); - else - f2 = (hsl.z + hsl.y) - (hsl.y * hsl.z); - - float f1 = 2.0 * hsl.z - f2; - - rgb.r = HueToRGB(f1, f2, hsl.x + (1.0/3.0)); - rgb.g = HueToRGB(f1, f2, hsl.x); - rgb.b = HueToRGB(f1, f2, hsl.x - (1.0/3.0)); - } - - return rgb; -} - - -/* -** Contrast, saturation, brightness -** Code of this function is from TGM's shader pack -** http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=21057 -*/ - -// For all settings: 1.0 = 100% 0.5=50% 1.5 = 150% -vec3 ContrastSaturationBrightness(in vec3 color, in float brt, in float sat, in float con) -{ - // Increase or decrease these values to adjust r, g and b color channels separately - const float AvgLumR = 0.5; - const float AvgLumG = 0.5; - const float AvgLumB = 0.5; - - const vec3 LumCoeff = vec3(0.2125, 0.7154, 0.0721); - - vec3 AvgLumin = vec3(AvgLumR, AvgLumG, AvgLumB); - vec3 brtColor = color * brt; - float intensityf = dot(brtColor, LumCoeff); - vec3 intensity = vec3(intensityf, intensityf, intensityf); - vec3 satColor = mix(intensity, brtColor, sat); - vec3 conColor = mix(AvgLumin, satColor, con); - return conColor; -} - -/* -** Float blending modes -** Adapted from here: http://www.nathanm.com/photoshop-blending-math/ -** But I modified the HardMix (wrong condition), Overlay, SoftLight, ColorDodge, ColorBurn, VividLight, PinLight (inverted layers) ones to have correct results -*/ - -#define BlendLinearDodgef BlendAddf -#define BlendLinearBurnf BlendSubtractf -#define BlendAddf(base, blend) min(base + blend, 1.0) -#define BlendSubtractf(base, blend) max(base + blend - 1.0, 0.0) -#define BlendLightenf(base, blend) max(blend, base) -#define BlendDarkenf(base, blend) min(blend, base) -#define BlendScreenf(base, blend) (1.0 - ((1.0 - base) * (1.0 - blend))) -#define BlendOverlayf(base, blend) (base < 0.5 ? (2.0 * base * blend) : (1.0 - 2.0 * (1.0 - base) * (1.0 - blend))) -#define BlendSoftLightf(base, blend) ((blend < 0.5) ? (2.0 * base * blend + base * base * (1.0 - 2.0 * blend)) : (sqrt(base) * (2.0 * blend - 1.0) + 2.0 * base * (1.0 - blend))) -#define BlendColorDodgef(base, blend) ((blend == 1.0) ? blend : min(base / (1.0 - blend), 1.0)) -#define BlendColorBurnf(base, blend) ((blend == 0.0) ? blend : max((1.0 - ((1.0 - base) / blend)), 0.0)) -#define BlendHardMixf(base, blend) ((BlendVividLightf(base, blend) < 0.5) ? 0.0 : 1.0) - - - -/* -** Vector3 blending modes -*/ - -// Component wise blending -#define Blend1(base, blend, funcf) funcf(base, blend) -#define Blend3(base, blend, funcf) vec3(funcf(base.r, blend.r), funcf(base.g, blend.g), funcf(base.b, blend.b)) -#define Blend4(base, blend, funcf) vec4(funcf(base.r, blend.r), funcf(base.g, blend.g), funcf(base.b, blend.b), funcf(base.a, blend.a)) - -#define BlendNormal(base, blend) (base) -#define BlendMultiply(base, blend) (base * blend) -#define BlendAverage(base, blend) ((base + blend) / 2.0) -#define BlendAdd(base, blend) min(base + blend, 1.0) -#define BlendSubtract(base, blend) max(base + blend - 1.0, 0.0) -#define BlendDifference(base, blend) abs(base - blend) -#define BlendNegation(base, blend) (1.0 - abs(1.0 - base - blend)) -#define BlendExclusion(base, blend) (base + blend - 2.0 * base * blend) -#define BlendPhoenix(base, blend) (min(base, blend) - max(base, blend) + 1.0) -#define BlendOpacity(base, blend, F, O) (F(base, blend) * O + blend * (1.0 - O)) - -// Hue Blend mode creates the result color by combining the luminance and saturation of the base color with the hue of the blend color. -float BlendHue1(in float base, in float blend) -{ - return base; -} - -vec3 BlendHue3(in vec3 base, in vec3 blend) -{ - vec3 baseHSL = RGBToHSL(base); - return HSLToRGB(vec3(RGBToHSL(blend).r, baseHSL.g, baseHSL.b)); -} - -vec4 BlendHue4(in vec4 base, in vec4 blend) -{ - vec3 hue = BlendHue3(base.xyz, blend.xyz); - return vec4(hue.x, hue.y, hue.z, BlendHue1(base.w, blend.w)); -} - -// Saturation Blend mode creates the result color by combining the luminance and hue of the base color with the saturation of the blend color. -float BlendSaturation1(in float base, in float blend) -{ - return base; -} - -vec3 BlendSaturation3(in vec3 base, in vec3 blend) -{ - vec3 baseHSL = RGBToHSL(base); - return HSLToRGB(vec3(baseHSL.r, RGBToHSL(blend).g, baseHSL.b)); -} - -vec4 BlendSaturation4(in vec4 base, in vec4 blend) -{ - vec3 hue = BlendSaturation3(base.xyz, blend.xyz); - return vec4(hue.x, hue.y, hue.z, BlendSaturation1(base.w, blend.w)); -} - -// Color Mode keeps the brightness of the base color and applies both the hue and saturation of the blend color. -float BlendColor1(in float base, in float blend) -{ - return base; -} - -vec3 BlendColor3(in vec3 base, in vec3 blend) -{ - vec3 blendHSL = RGBToHSL(blend); - return HSLToRGB(vec3(blendHSL.r, blendHSL.g, RGBToHSL(base).b)); -} - -vec4 BlendColor4(in vec4 base, in vec4 blend) -{ - vec3 hue = BlendColor3(base.xyz, blend.xyz); - return vec4(hue.x, hue.y, hue.z, BlendColor1(base.w, blend.w)); -} - - -// Luminosity Blend mode creates the result color by combining the hue and saturation of the base color with the luminance of the blend color. -float BlendLuminosity1(in float base, in float blend) -{ - return base; -} - -vec3 BlendLuminosity3(in vec3 base, in vec3 blend) -{ - vec3 baseHSL = RGBToHSL(base); - return HSLToRGB(vec3(baseHSL.r, baseHSL.g, RGBToHSL(blend).b)); -} - -vec4 BlendLuminosity4(in vec4 base, in vec4 blend) -{ - vec3 hue = BlendLuminosity3(base.xyz, blend.xyz); - return vec4(hue.x, hue.y, hue.z, BlendLuminosity1(base.w, blend.w)); -} - -float BlendLinearLightf(in float s1, in float s2) -{ - float oColor; - - if (s2 < 0.5) - { - float s2x = (2.0 * s2); - oColor = BlendSubtractf(s1, s2x); - } - else - { - float s2x = (2.0 * (s2 - 0.5)); - oColor = BlendAddf(s1, s2x); - } - - return oColor; -} - -float BlendVividLightf(in float s1, in float s2) -{ - float oColor; - - if (s2 < 0.5) - { - float s2x = (2.0 * s2); - oColor = BlendColorBurnf(s1, s2x); - } - else - { - float s2x = (2.0 * (s2 - 0.5)); - oColor = BlendColorDodgef(s1, s2x); - } - - return oColor; -} - -float BlendPinLightf(in float s1, in float s2) -{ - float oColor; - - if (s2 < 0.5) - { - float s2x = (2.0 * s2); - oColor = BlendDarkenf(s1, s2x); - } - else - { - float s2x = (2.0 * (s2 - 0.5)); - oColor = BlendLightenf(s1, s2x); - } - - return oColor; -} - -float BlendReflectf(in float s1, in float s2) -{ - float oColor; - - if (s2 == 1.0) - { - oColor = s2; - } - else - { - float s1x = (s1 * s1) / (1.0 - s2); - - oColor = min(s1x, 1.0); - } - - return oColor; -} - -//------------------------------------ -// Interface for RTShader -//------------------------------------ - - -void SGX_blend_normal(in vec4 basePixel, in vec4 blendPixel, out vec4 oColor) -{ - oColor = BlendNormal(basePixel, blendPixel); -} - -void SGX_blend_normal(in vec3 basePixel, in vec3 blendPixel, out vec3 oColor) -{ - oColor = BlendNormal(basePixel, blendPixel); -} - -void SGX_blend_normal(in float basePixel, in float blendPixel, out float oColor) -{ - oColor = BlendNormal(basePixel, blendPixel); -} - - -void SGX_blend_lighten(in vec4 basePixel, in vec4 blendPixel, out vec4 oColor) -{ - oColor = BlendLightenf(basePixel, blendPixel); -} - -void SGX_blend_lighten(in vec3 basePixel, in vec3 blendPixel, out vec3 oColor) -{ - oColor = BlendLightenf(basePixel, blendPixel); -} - -void SGX_blend_lighten(in float basePixel, in float blendPixel, out float oColor) -{ - oColor = BlendLightenf(basePixel, blendPixel); -} - - -void SGX_blend_darken(in vec4 basePixel, in vec4 blendPixel, out vec4 oColor) -{ - oColor = BlendDarkenf(basePixel, blendPixel); -} - -void SGX_blend_darken(in vec3 basePixel, in vec3 blendPixel, out vec3 oColor) -{ - oColor = BlendDarkenf(basePixel, blendPixel); -} - -void SGX_blend_darken(in float basePixel, in float blendPixel, out float oColor) -{ - oColor = BlendDarkenf(basePixel, blendPixel); -} - - -void SGX_blend_multiply(in vec4 basePixel, in vec4 blendPixel, out vec4 oColor) -{ - oColor = BlendMultiply(basePixel, blendPixel); -} - -void SGX_blend_multiply(in vec3 basePixel, in vec3 blendPixel, out vec3 oColor) -{ - oColor = BlendMultiply(basePixel, blendPixel); -} - -void SGX_blend_multiply(in float basePixel, in float blendPixel, out float oColor) -{ - oColor = BlendMultiply(basePixel, blendPixel); -} - - -void SGX_blend_average(in vec4 basePixel, in vec4 blendPixel, out vec4 oColor) -{ - oColor = BlendAverage(basePixel, blendPixel); -} - -void SGX_blend_average(in vec3 basePixel, in vec3 blendPixel, out vec3 oColor) -{ - oColor = BlendAverage(basePixel, blendPixel); -} - -void SGX_blend_average(in float basePixel, in float blendPixel, out float oColor) -{ - oColor = BlendAverage(basePixel, blendPixel); -} - - -void SGX_blend_add(in vec4 basePixel, in vec4 blendPixel, out vec4 oColor) -{ - oColor = BlendAdd(basePixel, blendPixel); -} - -void SGX_blend_add(in vec3 basePixel, in vec3 blendPixel, out vec3 oColor) -{ - oColor = BlendAdd(basePixel, blendPixel); -} - -void SGX_blend_add(in float basePixel, in float blendPixel, out float oColor) -{ - oColor = BlendAdd(basePixel, blendPixel); -} - - -void SGX_blend_subtract(in vec4 basePixel, in vec4 blendPixel, out vec4 oColor) -{ - oColor = BlendSubtract(basePixel, blendPixel); -} - -void SGX_blend_subtract(in vec3 basePixel, in vec3 blendPixel, out vec3 oColor) -{ - oColor = BlendSubtract(basePixel, blendPixel); -} - -void SGX_blend_subtract(in float basePixel, in float blendPixel, out float oColor) -{ - oColor = BlendSubtract(basePixel, blendPixel); -} - - -void SGX_blend_difference(in vec4 basePixel, in vec4 blendPixel, out vec4 oColor) -{ - oColor = BlendDifference(basePixel, blendPixel); -} -void SGX_blend_difference(in vec3 basePixel, in vec3 blendPixel, out vec3 oColor) -{ - oColor = BlendDifference(basePixel, blendPixel); -} -void SGX_blend_difference(in float basePixel, in float blendPixel, out float oColor) -{ - oColor = BlendDifference(basePixel, blendPixel); -} - - -void SGX_blend_negation(in vec4 basePixel, in vec4 blendPixel, out vec4 oColor) -{ - oColor = BlendNegation(basePixel, blendPixel); -} -void SGX_blend_negation(in vec3 basePixel, in vec3 blendPixel, out vec3 oColor) -{ - oColor = BlendNegation(basePixel, blendPixel); -} -void SGX_blend_negation(in float basePixel, in float blendPixel, out float oColor) -{ - oColor = BlendNegation(basePixel, blendPixel); -} - - -void SGX_blend_exclusion(in vec4 basePixel, in vec4 blendPixel, out vec4 oColor) -{ - oColor = BlendExclusion(basePixel, blendPixel); -} -void SGX_blend_exclusion(in vec3 basePixel, in vec3 blendPixel, out vec3 oColor) -{ - oColor = BlendExclusion(basePixel, blendPixel); -} -void SGX_blend_exclusion(in float basePixel, in float blendPixel, out float oColor) -{ - oColor = BlendExclusion(basePixel, blendPixel); -} - - -void SGX_blend_screen(in vec4 s1, in vec4 s2, out vec4 oColor) -{ - oColor = vec4(BlendScreenf(s1.r, s2.r), - BlendScreenf(s1.g, s2.g), - BlendScreenf(s1.b, s2.b), - BlendScreenf(s1.a, s2.a)); -} -void SGX_blend_screen(in vec3 s1, in vec3 s2, out vec3 oColor) -{ - oColor = vec3(BlendScreenf(s1.r, s2.r), - BlendScreenf(s1.g, s2.g), - BlendScreenf(s1.b, s2.b)); -} -void SGX_blend_screen(in float s1, in float s2, out float oColor) -{ - oColor = BlendScreenf(s1, s2); -} - - -void SGX_blend_overlay(in vec4 s1, in vec4 s2, out vec4 oColor) -{ - oColor = vec4(BlendOverlayf(s1.r, s2.r), - BlendOverlayf(s1.g, s2.g), - BlendOverlayf(s1.b, s2.b), - BlendOverlayf(s1.a, s2.a)); -} -void SGX_blend_overlay(in vec3 s1, in vec3 s2, out vec3 oColor) -{ - oColor = vec3(BlendOverlayf(s1.r, s2.r), - BlendOverlayf(s1.g, s2.g), - BlendOverlayf(s1.b, s2.b)); -} -void SGX_blend_overlay(in float s1, in float s2, out float oColor) -{ - oColor = BlendOverlayf(s1, s2); -} - - -void SGX_blend_softLight(in vec4 s1, in vec4 s2, out vec4 oColor) -{ - oColor = vec4(BlendSoftLightf(s1.r, s2.r), - BlendSoftLightf(s1.g, s2.g), - BlendSoftLightf(s1.b, s2.b), - BlendSoftLightf(s1.a, s2.a)); -} -void SGX_blend_softLight(in vec3 s1, in vec3 s2, out vec3 oColor) -{ - oColor = vec3(BlendSoftLightf(s1.r, s2.r), - BlendSoftLightf(s1.g, s2.g), - BlendSoftLightf(s1.b, s2.b)); -} -void SGX_blend_softLight(in float s1, in float s2, out float oColor) -{ - oColor = BlendSoftLightf(s1, s2); -} - - -void SGX_blend_hardLight(in vec4 s1, in vec4 s2, out vec4 oColor) -{ - oColor = vec4(BlendOverlayf(s1.r, s2.r), - BlendOverlayf(s1.g, s2.g), - BlendOverlayf(s1.b, s2.b), - BlendOverlayf(s1.a, s2.a)); -} -void SGX_blend_hardLight(in vec3 s1, in vec3 s2, out vec3 oColor) -{ - oColor = vec3(BlendOverlayf(s1.r, s2.r), - BlendOverlayf(s1.g, s2.g), - BlendOverlayf(s1.b, s2.b)); -} -void SGX_blend_hardLight(in float s1, in float s2, out float oColor) -{ - oColor = BlendOverlayf(s1, s2); -} - - -void SGX_blend_colorDodge(in vec4 s1, in vec4 s2, out vec4 oColor) -{ - oColor = vec4(BlendColorDodgef(s1.r, s2.r), - BlendColorDodgef(s1.g, s2.g), - BlendColorDodgef(s1.b, s2.b), - BlendColorDodgef(s1.a, s2.a)); -} -void SGX_blend_colorDodge(in vec3 s1, in vec3 s2, out vec3 oColor) -{ - oColor = vec3(BlendColorDodgef(s1.r, s2.r), - BlendColorDodgef(s1.g, s2.g), - BlendColorDodgef(s1.b, s2.b)); -} -void SGX_blend_colorDodge(in float s1, in float s2, out float oColor) -{ - oColor = BlendColorDodgef(s1, s2); -} - - -void SGX_blend_colorBurn(in vec4 s1, in vec4 s2, out vec4 oColor) -{ - oColor = vec4(BlendColorBurnf(s1.r, s2.r), - BlendColorBurnf(s1.g, s2.g), - BlendColorBurnf(s1.b, s2.b), - BlendColorBurnf(s1.a, s2.a)); -} -void SGX_blend_colorBurn(in vec3 s1, in vec3 s2, out vec3 oColor) -{ - oColor = vec3(BlendColorBurnf(s1.r, s2.r), - BlendColorBurnf(s1.g, s2.g), - BlendColorBurnf(s1.b, s2.b)); -} -void SGX_blend_colorBurn(in float s1, in float s2, out float oColor) -{ - oColor = BlendColorBurnf(s1, s2); -} - - -void SGX_blend_linearDodge(in vec4 basePixel, in vec4 blendPixel, out vec4 oColor) -{ - oColor = BlendAddf(basePixel, blendPixel); -} -void SGX_blend_linearDodge(in vec3 basePixel, in vec3 blendPixel, out vec3 oColor) -{ - oColor = BlendAddf(basePixel, blendPixel); -} -void SGX_blend_linearDodge(in float basePixel, in float blendPixel, out float oColor) -{ - oColor = BlendAddf(basePixel, blendPixel); -} - - -void SGX_blend_linearBurn(in vec4 basePixel, in vec4 blendPixel, out vec4 oColor) -{ - oColor = BlendSubtractf(basePixel, blendPixel); -} -void SGX_blend_linearBurn(in vec3 basePixel, in vec3 blendPixel, out vec3 oColor) -{ - oColor = BlendSubtractf(basePixel, blendPixel); -} -void SGX_blend_linearBurn(in float basePixel, in float blendPixel, out float oColor) -{ - oColor = BlendSubtractf(basePixel, blendPixel); -} - - -void SGX_blend_linearLight(in vec4 s1, in vec4 s2, out vec4 oColor) -{ - oColor = vec4(BlendLinearLightf(s1.r, s2.r), - BlendLinearLightf(s1.g, s2.g), - BlendLinearLightf(s1.b, s2.b), - BlendLinearLightf(s1.a, s2.a)); -} -void SGX_blend_linearLight(in vec3 s1, in vec3 s2, out vec3 oColor) -{ - oColor = vec3(BlendLinearLightf(s1.r, s2.r), - BlendLinearLightf(s1.g, s2.g), - BlendLinearLightf(s1.b, s2.b)); -} -void SGX_blend_linearLight(in float s1, in float s2, out float oColor) -{ - oColor = BlendLinearLightf(s1, s2); -} - - -void SGX_blend_vividLight(in vec4 s1, in vec4 s2, out vec4 oColor) -{ - oColor = vec4(BlendVividLightf(s1.r, s2.r), - BlendVividLightf(s1.g, s2.g), - BlendVividLightf(s1.b, s2.b), - BlendVividLightf(s1.a, s2.a)); -} -void SGX_blend_vividLight(in vec3 s1, in vec3 s2, out vec3 oColor) -{ - oColor = vec3(BlendVividLightf(s1.r, s2.r), - BlendVividLightf(s1.g, s2.g), - BlendVividLightf(s1.b, s2.b)); -} -void SGX_blend_vividLight(in float s1, in float s2, out float oColor) -{ - oColor = BlendVividLightf(s1, s2); -} - - -void SGX_blend_pinLight(in vec4 s1, in vec4 s2, out vec4 oColor) -{ - oColor = vec4(BlendPinLightf(s1.r, s2.r), - BlendPinLightf(s1.g, s2.g), - BlendPinLightf(s1.b, s2.b), - BlendPinLightf(s1.a, s2.a)); -} -void SGX_blend_pinLight(in vec3 s1, in vec3 s2, out vec3 oColor) -{ - oColor = vec3(BlendPinLightf(s1.r, s2.r), - BlendPinLightf(s1.g, s2.g), - BlendPinLightf(s1.b, s2.b)); -} -void SGX_blend_pinLight(in float s1, in float s2, out float oColor) -{ - oColor = BlendPinLightf(s1, s2); -} - - -void SGX_blend_hardMix(in vec4 s1, in vec4 s2, out vec4 oColor) -{ - oColor = vec4(BlendHardMixf(s1.r, s2.r), - BlendHardMixf(s1.g, s2.g), - BlendHardMixf(s1.b, s2.b), - BlendHardMixf(s1.a, s2.a)); -} -void SGX_blend_hardMix(in vec3 s1, in vec3 s2, out vec3 oColor) -{ - oColor = vec3(BlendHardMixf(s1.r, s2.r), - BlendHardMixf(s1.g, s2.g), - BlendHardMixf(s1.b, s2.b)); -} -void SGX_blend_hardMix(in float s1, in float s2, out float oColor) -{ - oColor = BlendHardMixf(s1, s2); -} - -void SGX_blend_reflect(in vec4 s1, in vec4 s2, out vec4 oColor) -{ - oColor = vec4(BlendReflectf(s1.r, s2.r), - BlendReflectf(s1.g, s2.g), - BlendReflectf(s1.b, s2.b), - BlendReflectf(s1.a, s2.a)); -} -void SGX_blend_reflect(in vec3 s1, in vec3 s2, out vec3 oColor) -{ - oColor = vec3(BlendReflectf(s1.r, s2.r), - BlendReflectf(s1.g, s2.g), - BlendReflectf(s1.b, s2.b)); -} -void SGX_blend_reflect(in float s1, in float s2, out float oColor) -{ - oColor = BlendReflectf(s1, s2); -} - - -void SGX_blend_glow(in vec4 s1, in vec4 s2, out vec4 oColor) -{ - oColor = vec4(BlendReflectf(s1.r, s2.r), - BlendReflectf(s1.g, s2.g), - BlendReflectf(s1.b, s2.b), - BlendReflectf(s1.a, s2.a)); -} -void SGX_blend_glow(in vec3 s1, in vec3 s2, out vec3 oColor) -{ - oColor = vec3(BlendReflectf(s1.r, s2.r), - BlendReflectf(s1.g, s2.g), - BlendReflectf(s1.b, s2.b)); -} -void SGX_blend_glow(in float s1, in float s2, out float oColor) -{ - oColor = BlendReflectf(s1, s2); -} - - -void SGX_blend_phoenix(in vec4 basePixel, in vec4 blendPixel, out vec4 oColor) -{ - oColor = BlendPhoenix(basePixel, blendPixel); -} -void SGX_blend_phoenix(in vec3 basePixel, in vec3 blendPixel, out vec3 oColor) -{ - oColor = BlendPhoenix(basePixel, blendPixel); -} -void SGX_blend_phoenix(in float basePixel, in float blendPixel, out float oColor) -{ - oColor = BlendPhoenix(basePixel, blendPixel); -} - - -void SGX_blend_saturation(in vec4 basePixel, in vec4 blendPixel, out vec4 oColor) -{ - oColor = BlendSaturation4(basePixel, blendPixel); -} -void SGX_blend_saturation(in vec3 basePixel, in vec3 blendPixel, out vec3 oColor) -{ - oColor = BlendSaturation3(basePixel, blendPixel); -} -void SGX_blend_saturation(in float basePixel, in float blendPixel, out float oColor) -{ - oColor = BlendSaturation1(basePixel, blendPixel); -} - - -void SGX_blend_color(in vec4 basePixel, in vec4 blendPixel, out vec4 oColor) -{ - oColor = BlendColor4(basePixel, blendPixel); -} -void SGX_blend_color(in vec3 basePixel, in vec3 blendPixel, out vec3 oColor) -{ - oColor = BlendColor3(basePixel, blendPixel); -} -void SGX_blend_color(in float basePixel, in float blendPixel, out float oColor) -{ - oColor = BlendColor1(basePixel, blendPixel); -} - - -void SGX_blend_luminosity(in vec4 basePixel, in vec4 blendPixel, out vec4 oColor) -{ - oColor = BlendLuminosity4(basePixel, blendPixel); -} -void SGX_blend_luminosity(in vec3 basePixel, in vec3 blendPixel, out vec3 oColor) -{ - oColor = BlendLuminosity3(basePixel, blendPixel); -} -void SGX_blend_luminosity(in float basePixel, in float blendPixel, out float oColor) -{ - oColor = BlendLuminosity1(basePixel, blendPixel); -} - - -//////////////////////////////////////////////////////////////////////////////////// -/// Source modification functions -//////////////////////////////////////////////////////////////////////////////////// - - -void SGX_src_mod_modulate(in vec4 iColor, in vec4 controlVal, out vec4 oColor) -{ - oColor = iColor * controlVal; -} -void SGX_src_mod_modulate(in vec3 iColor, in vec3 controlVal, out vec3 oColor) -{ - oColor = iColor * controlVal; -} -void SGX_src_mod_modulate(in float iColor, in float controlVal, out float oColor) -{ - oColor = iColor * controlVal; -} - -void SGX_src_mod_inv_modulate(in vec4 iColor, in vec4 controlVal, out vec4 oColor) -{ - oColor = mix(iColor, vec4(1.0,1.0,1.0,1.0), controlVal); -} -void SGX_src_mod_inv_modulate(in vec3 iColor, in vec3 controlVal, out vec3 oColor) -{ - oColor = mix(iColor, vec3(1.0,1.0,1.0), controlVal); -} -void SGX_src_mod_inv_modulate(in float iColor, in float controlVal, out float oColor) -{ - oColor = mix(iColor, 1.0, controlVal); -} diff --git a/Media/RTShaderLib/SGXLib_NormalMap.glsl b/Media/RTShaderLib/SGXLib_NormalMap.glsl deleted file mode 100644 index fb7555a0c3b..00000000000 --- a/Media/RTShaderLib/SGXLib_NormalMap.glsl +++ /dev/null @@ -1,125 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -//----------------------------------------------------------------------------- -// Program Name: SGXLib_NormalMapLighting -// Program Desc: Normal map lighting functions. -// Program Type: Vertex/Pixel shader -// Language: GLSL -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -void SGX_FetchNormal(in sampler2D s, - in vec2 uv, - out vec3 vOut) -{ - vOut = 2.0 * texture2D(s, uv).xyz - 1.0; -} - -//----------------------------------------------------------------------------- -void SGX_CalculateTBN(in vec3 vNormal, - in vec4 vTangent, - out mat3 TBN) -{ - vec3 vBinormal = cross(vNormal, vTangent.xyz) * vTangent.w; - - // direction: from tangent space to world - TBN = mtxFromCols(vTangent.xyz, vBinormal, vNormal); -} - -//----------------------------------------------------------------------------- -void SGX_Generate_Parallax_Texcoord(in sampler2D normalHeightMap, - in vec2 texCoord, - in vec3 viewPos, - in float heightScale, - in mat3 TBN, - out vec2 newTexCoord) -{ - //Calculate eye direction - vec3 eyeVec = mul(-viewPos, TBN); - eyeVec = normalize(eyeVec); -#ifndef TERRAIN_PARALLAX_MAPPING - eyeVec.y = -eyeVec.y; //Inverse y -#endif - - newTexCoord = texCoord; - -#ifndef POM_LAYER_COUNT - //Simple parallax mapping - float height = 1.0f - texture2D(normalHeightMap, newTexCoord).a; - - #ifndef TERRAIN_PARALLAX_MAPPING - vec2 p = eyeVec.xy / eyeVec.z * (height * heightScale); - #else - vec2 p = eyeVec.xy * (height * heightScale); - #endif - - newTexCoord = newTexCoord - p; -#else - // parallax occlusion mapping -#ifdef POM_MAX_DISTANCE - if (abs(viewPos.z) > POM_MAX_DISTANCE) - return; -#endif - - //Configure steep mapping layering. - float layerDepth = 1.0 / float(POM_LAYER_COUNT); - float currentLayerDepth = 0.0; - vec2 parallaxShift = (eyeVec.xy) * heightScale; - vec2 deltaTexCoords = parallaxShift / float(POM_LAYER_COUNT); - - float currentDepthMapValue = 1.0f - texture2D(normalHeightMap, newTexCoord).a; - - //Loop through layers and break early if match found. - for (int currentLayerId = 0; currentLayerId < POM_LAYER_COUNT; currentLayerId++) - { - // shift texture coordinates along direction of P - newTexCoord -= deltaTexCoords; - - // get depthmap value at current texture coordinates - currentDepthMapValue = 1.0f - texture2D(normalHeightMap, newTexCoord).a; - - //Break if layer height matched - if (currentLayerDepth > currentDepthMapValue) - break; - - // get depth of next layer - currentLayerDepth += layerDepth; - } - - // get texture coordinates before collision (reverse operations) - vec2 prevTexCoords = newTexCoord + deltaTexCoords; - - // get depth after and before collision for linear interpolation - float afterDepth = currentDepthMapValue - currentLayerDepth; - float beforeDepth = (1.0f - texture2D(normalHeightMap, prevTexCoords).a) - currentLayerDepth + layerDepth; - - // interpolation of texture coordinates - float weight = afterDepth / (afterDepth - beforeDepth); - newTexCoord = mix(newTexCoord, prevTexCoords, weight); -#endif -} \ No newline at end of file diff --git a/Media/RTShaderLib/SGXLib_PerPixelLighting.glsl b/Media/RTShaderLib/SGXLib_PerPixelLighting.glsl deleted file mode 100644 index d6fc0a45bf9..00000000000 --- a/Media/RTShaderLib/SGXLib_PerPixelLighting.glsl +++ /dev/null @@ -1,172 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -//----------------------------------------------------------------------------- -// Program Name: SGXLib_Lighting -// Program Desc: Per pixel lighting functions. -// Program Type: Vertex/Pixel shader -// Language: GLSL -// Notes: Implements core functions for FFPLighting class. -// based on lighting engine. -// See http://msdn.microsoft.com/en-us/library/bb147178.aspx -//----------------------------------------------------------------------------- - -#include "RTSLib_Lighting.glsl" -#ifdef HAVE_AREA_LIGHTS -#include "RTSLib_LTC.glsl" -#endif - -#ifdef OGRE_HLSL -void SGX_Flip_Backface_Normal(in float triArea, in float targetFlipped, inout vec3 normal) -{ -#if OGRE_HLSL == 3 - triArea *= -1.0; - triArea *= targetFlipped; -#endif - if(triArea < 0.0) - normal *= -1.0; -} -#else -void SGX_Flip_Backface_Normal(in bool frontFacing, in float targetFlipped, inout vec3 normal) -{ - if(!frontFacing) - normal *= -1.0; -} -#endif - -void evaluateLight( - in vec3 vNormal, - in vec3 vViewPos, - in vec4 vLightPos, - in vec4 vAttParams, - in vec4 vLightDirView, - in vec4 spotParams, - in vec4 vDiffuseColour, - inout vec3 vOutDiffuse -#if defined(TVC_DIFFUSE) || defined(TVC_SPECULAR) - , in vec4 vInVertexColour -#endif -#ifdef USE_SPECULAR - , in vec4 vSpecularColour, - in float fSpecularPower, - inout vec3 vOutSpecular -#endif -#ifdef SHADOWLIGHT_COUNT - , in float shadowFactor -#endif -#ifdef HAVE_AREA_LIGHTS - , in sampler2D ltcLUT1, - in sampler2D ltcLUT2 -#endif - ) -{ - - vec3 vLightView = vLightPos.xyz; - float fLightD = 0.0; - -#ifdef TVC_DIFFUSE - vDiffuseColour *= vInVertexColour; -#endif - -#ifdef HAVE_AREA_LIGHTS - if(spotParams.w == 2.0) - { - // rect area light - vec3 dcol = vDiffuseColour.rgb; -#ifdef USE_SPECULAR -#ifdef TVC_SPECULAR - vSpecularColour *= vInVertexColour; -#endif - vec3 scol = vSpecularColour.rgb; -#else - vec3 scol = vec3_splat(0.0); - float fSpecularPower = 0.0; -#endif - float roughness = saturate(1.0 - fSpecularPower/128.0); // convert specular to roughness - roughness *= roughness; // perceptual to physical roughness - evaluateRectLight(ltcLUT1, ltcLUT2, roughness, normalize(vNormal), vViewPos, vLightPos.xyz, spotParams.xyz, vAttParams.xyz, scol, dcol); - -#ifdef SHADOWLIGHT_COUNT - dcol *= shadowFactor; - scol *= shadowFactor; -#endif - - // linear to gamma - dcol = pow(dcol, vec3_splat(1.0/2.2)); - vOutDiffuse.rgb = saturate(vOutDiffuse.rgb + dcol); -#ifdef USE_SPECULAR - scol = pow(scol, vec3_splat(1.0/2.2)); - vOutSpecular.rgb = saturate(vOutSpecular.rgb + scol); -#endif - return; - } -#endif - - if (vLightPos.w != 0.0) - { - vLightView -= vViewPos; // to light - fLightD = length(vLightView); - - if(fLightD > vAttParams.x) - return; - } - - vLightView = normalize(vLightView); - vec3 vNormalView = normalize(vNormal); - float nDotL = saturate(dot(vNormalView, vLightView)); - - if (nDotL <= 0.0) - return; - - float fAtten = getDistanceAttenuation(vAttParams.yzw, fLightD); - -#ifdef SHADOWLIGHT_COUNT - fAtten *= shadowFactor; -#endif - - if(spotParams.w != 0.0) - { - fAtten *= getAngleAttenuation(spotParams.xyz, vLightDirView.xyz, vLightView); - } - - vOutDiffuse += vDiffuseColour.rgb * nDotL * fAtten; - vOutDiffuse = saturate(vOutDiffuse); - -#ifdef USE_SPECULAR - vec3 vView = -normalize(vViewPos); - vec3 vHalfWay = normalize(vView + vLightView); - float nDotH = saturate(dot(vNormalView, vHalfWay)); -#ifdef TVC_SPECULAR - vSpecularColour *= vInVertexColour; -#endif -#ifdef NORMALISED - vSpecularColour *= (fSpecularPower + 8.0)/(8.0 * M_PI); -#endif - vOutSpecular += vSpecularColour.rgb * pow(nDotH, fSpecularPower) * fAtten; - vOutSpecular = saturate(vOutSpecular); -#endif -} \ No newline at end of file diff --git a/Media/RTShaderLib/SGXLib_TriplanarTexturing.glsl b/Media/RTShaderLib/SGXLib_TriplanarTexturing.glsl deleted file mode 100644 index 179c4d71524..00000000000 --- a/Media/RTShaderLib/SGXLib_TriplanarTexturing.glsl +++ /dev/null @@ -1,47 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -void SGX_TriplanarTexturing(in vec4 diffuse, in vec3 normal, in vec4 position, in sampler2D texFromX, in sampler2D texFromY, in sampler2D texFromZ, in vec3 parameters, out vec4 cOut) -{ - vec3 blendWeights = abs(normalize(normal)); - blendWeights = blendWeights - parameters.y; - blendWeights = pow(max(blendWeights, vec3(0.0, 0.0, 0.0)), parameters.zzz); - float tot = (blendWeights.x + blendWeights.y + blendWeights.z); - blendWeights /= vec3(tot, tot, tot); - // Move the planar mapping a bit according to the normal length to avoid bad looking skirts. - float nLength = length(normal - 1.0); - vec2 coord1 = (position.yz + nLength) * parameters.x; - vec2 coord2 = (position.zx + nLength) * parameters.x; - vec2 coord3 = (position.xy + nLength) * parameters.x; - - vec4 col1 = texture2D(texFromX, coord1); - vec4 col2 = texture2D(texFromY, coord2); - vec4 col3 = texture2D(texFromZ, coord3); - cOut = diffuse * vec4(col1.xyz * blendWeights.x + - col2.xyz * blendWeights.y + - col3.xyz * blendWeights.z, 1); -} diff --git a/Media/RTShaderLib/SGXLib_WBOIT.glsl b/Media/RTShaderLib/SGXLib_WBOIT.glsl deleted file mode 100644 index 961cc3d858b..00000000000 --- a/Media/RTShaderLib/SGXLib_WBOIT.glsl +++ /dev/null @@ -1,19 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -float weight(float z, float a) -{ - // from https://casual-effects.blogspot.com/2015/03/implemented-weighted-blended-order.html - return clamp(pow(min(1.0, a * 10.0) + 0.01, 3.0) * 1e8 * pow(1.0 - z * 0.9, 3.0), 1e-2, 3e3); -} - -void SGX_WBOIT(float depth, inout vec4 accum, out vec4 revealage) -{ - vec4 colour = accum; - // Weighted Blended Order-Independent Transparency, Listing 4 - float w = weight(depth, colour.a); - accum = vec4(colour.rgb * w * colour.a, colour.a); - revealage = vec4_splat(colour.a * w); -} \ No newline at end of file diff --git a/Media/RTShaderLib/dfgLUTmultiscatter.dds b/Media/RTShaderLib/dfgLUTmultiscatter.dds deleted file mode 100644 index 51e397bdb34..00000000000 Binary files a/Media/RTShaderLib/dfgLUTmultiscatter.dds and /dev/null differ diff --git a/Media/RTShaderLib/ltc_1.dds b/Media/RTShaderLib/ltc_1.dds deleted file mode 100644 index e4465d22701..00000000000 Binary files a/Media/RTShaderLib/ltc_1.dds and /dev/null differ diff --git a/Media/RTShaderLib/ltc_2.dds b/Media/RTShaderLib/ltc_2.dds deleted file mode 100644 index 64e6b532e1d..00000000000 Binary files a/Media/RTShaderLib/ltc_2.dds and /dev/null differ diff --git a/Media/Terrain/TerrainSurface.glsl b/Media/Terrain/TerrainSurface.glsl deleted file mode 100644 index 02df32e76a5..00000000000 --- a/Media/Terrain/TerrainSurface.glsl +++ /dev/null @@ -1,83 +0,0 @@ -void transformToTS(in vec3 TSnormal, in mat3 normalMatrix, inout vec3 normal) -{ - // derive the tangent space basis - // we do this in the pixel shader because we don't have per-vertex normals - // because of the LOD, we use a normal map - // tangent is always +x or -z in object space depending on alignment -#ifdef TERRAIN_ALIGN_Y_Z - vec3 tangent = vec3(0, 0, -1); -#else - vec3 tangent = vec3(1, 0, 0); -#endif - normal = normalize(normal); - tangent = normalize(mul(normalMatrix, tangent)); - vec3 binormal = cross(tangent, normal); - // note, now we need to re-cross to derive tangent again because it wasn't orthonormal - tangent = cross(normal, binormal); - // derive final matrix - mat3 TBN = mtxFromCols(tangent, binormal, normal); - - normal = mul(TBN, TSnormal); -} - -void getShadowFactor(in sampler2D lightmap, in vec2 uv, inout float shadowFactor) -{ - float lmShadow = texture2D(lightmap, uv).x; - shadowFactor = min(shadowFactor, lmShadow); -} - -#define MIN_BLEND_WEIGHT 0.0039 // 1/255 - -void blendTerrainLayer(in float blendWeight, in f32vec2 uv0, in float uvMul, -#ifdef TERRAIN_PARALLAX_MAPPING - in vec3 viewPos, in float scaleBias, in mat3 TBN, -#endif -#ifdef TERRAIN_NORMAL_MAPPING - in sampler2D normtex, inout vec3 normal, -#endif - in sampler2D difftex, inout vec4 diffuseSpec) -{ - if(blendWeight < MIN_BLEND_WEIGHT) - return; - - // generate UV - vec2 uv = mod(uv0 * uvMul, 1.0); - -#ifdef TERRAIN_PARALLAX_MAPPING - SGX_Generate_Parallax_Texcoord(normtex, uv, viewPos, scaleBias, TBN, uv); -#endif - - // sample diffuse texture - vec4 diffuseSpecTex = texture2D(difftex, uv); - // apply to common - diffuseSpec = mix(diffuseSpec, diffuseSpecTex, blendWeight); - -#ifdef TERRAIN_NORMAL_MAPPING - vec3 TSnormal; - // access TS normal map - SGX_FetchNormal(normtex, uv, TSnormal); - // Partial Derivative Blending https://blog.selfshadow.com/publications/blending-in-detail/ - normal = normalize(vec3(mix(normal.xy*TSnormal.z, TSnormal.xy*normal.z, blendWeight), TSnormal.z*normal.z)); -#endif -} - -//----------------------------------------------------------------------------- -void SGX_CalculateTerrainTBN(in vec3 normal, in mat3 normalMatrix, out mat3 TBN) -{ - // derive the tangent space basis - // we do this in the pixel shader because we don't have per-vertex normals - // because of the LOD, we use a normal map - // tangent is always +x or -z in object space depending on alignment - #ifdef TERRAIN_ALIGN_Y_Z - vec3 tangent = vec3(0, 0, -1); - #else - vec3 tangent = vec3(1, 0, 0); - #endif - normal = normalize(normal); - tangent = normalize(mul(normalMatrix, tangent)); - vec3 binormal = cross(tangent, normal); - // note, now we need to re-cross to derive tangent again because it wasn't orthonormal - tangent = cross(normal, binormal); - // derive final matrix - TBN = mtxFromCols(tangent, binormal, normal); -} \ No newline at end of file diff --git a/Media/Terrain/TerrainTransforms.glsl b/Media/Terrain/TerrainTransforms.glsl deleted file mode 100644 index 1e59964398a..00000000000 --- a/Media/Terrain/TerrainTransforms.glsl +++ /dev/null @@ -1,36 +0,0 @@ -/** - * @param delta: lodDelta, lodThreshold (vertex attribute) - * @param lodMorph: morph amount, morph targetLOD (uniform) - */ -void applyLODMorph(vec2 delta, vec2 lodMorph, inout float height -#ifdef TERRAIN_DEBUG -, out vec2 lodInfo -#endif -) -{ - // determine whether to apply the LOD morph to this vertex - // we store the deltas against all vertices so we only want to apply - // the morph to the ones which would disappear. - // If we subtract - // the lodThreshold from the targetLOD, and arrange to only morph if the - // result is negative (it will only be -1 in fact, since after that - // the vertex will never be indexed), we will achieve our aim. - // sign(lodThreshold - targetLOD) == -1 is to morph - - // this will either be 1 (morph) or 0 (don't morph) - float toMorph = -min(0.0, sign(delta.y - lodMorph.y)); - height += delta.x * toMorph * lodMorph.x; - -#ifdef TERRAIN_DEBUG - // LOD level (-1 since value is target level, we want to display actual) - lodInfo.x = (lodMorph.y - 1) / NUM_LODS; - // LOD morph - lodInfo.y = toMorph * lodMorph.x; -#endif -} - -void expandVertex(mat4 idxToObjectSpace, float baseUVScale, vec2 idx, float height, out vec4 position, out vec2 uv) -{ - position = mul(idxToObjectSpace, vec4(idx, height, 1)); - uv = vec2(idx.x * baseUVScale, 1.0 - idx.y * baseUVScale); -} \ No newline at end of file diff --git a/Media/packs/SdkTrays.zip b/Media/packs/SdkTrays.zip deleted file mode 100644 index 1b55966baae..00000000000 Binary files a/Media/packs/SdkTrays.zip and /dev/null differ diff --git a/Media/packs/profiler.zip b/Media/packs/profiler.zip deleted file mode 100644 index c73abd3f82d..00000000000 Binary files a/Media/packs/profiler.zip and /dev/null differ diff --git a/OgreMain/CMakeLists.txt b/OgreMain/CMakeLists.txt deleted file mode 100644 index df19a5115e2..00000000000 --- a/OgreMain/CMakeLists.txt +++ /dev/null @@ -1,233 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -############################################################ -# OgreMain core library -############################################################ - -# define header and source files for the library -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES - ${PROJECT_BINARY_DIR}/include/OgreBuildSettings.h - ${PROJECT_BINARY_DIR}/include/OgreComponents.h - ${PROJECT_BINARY_DIR}/include/OgreExports.h - ${CMAKE_CURRENT_SOURCE_DIR}/include/Ogre.i) - -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") - -# Remove optional header files -list(REMOVE_ITEM HEADER_FILES - "${CMAKE_CURRENT_SOURCE_DIR}/include/OgreDDSCodec.h" - "${CMAKE_CURRENT_SOURCE_DIR}/include/OgrePVRTCCodec.h" - "${CMAKE_CURRENT_SOURCE_DIR}/include/OgreETCCodec.h" - "${CMAKE_CURRENT_SOURCE_DIR}/include/OgreZip.h" -) - -# Remove optional source files -list(REMOVE_ITEM SOURCE_FILES - "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreFileSystemLayerNoOp.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreDDSCodec.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/OgrePVRTCCodec.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreETCCodec.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreZip.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreSearchOps.cpp" -) - -# Add platform specific files -if (EMSCRIPTEN) - set(PLATFORM_SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreFileSystemLayerNoOp.cpp") -elseif (WIN32) - file(GLOB PLATFORM_SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/WIN32/*.cpp") -elseif (APPLE) - if (APPLE_IOS) - include_directories("${CMAKE_CURRENT_SOURCE_DIR}/src/iOS") - file(GLOB PLATFORM_SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/iOS/*.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/iOS/*.mm") - - set(PLATFORM_LIBS "") - else () - include_directories("${CMAKE_CURRENT_SOURCE_DIR}/src/OSX") - file(GLOB PLATFORM_SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/OSX/*.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/OSX/*.mm") - set(PLATFORM_LIBS "-framework CoreFoundation -framework Foundation") - endif () -elseif(ANDROID) - # required by OgrePlatformInformation.cpp - include_directories(${ANDROID_NDK}/sources/android/cpufeatures) - - file(GLOB PLATFORM_SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/Android/*.cpp") - # Remove optional platform source files - list(REMOVE_ITEM PLATFORM_SOURCE_FILES - "${CMAKE_CURRENT_SOURCE_DIR}/src/Android/OgreAPKZipArchive.cpp" - ) -elseif (UNIX) - file(GLOB PLATFORM_SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/GLX/*.cpp") - - set(PLATFORM_LIBS pthread) -endif() - -if(NOT WIN32) - list(APPEND PLATFORM_SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreSearchOps.cpp") -endif() - -# Configure threading files -file(GLOB THREAD_HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/Threading/*.h") -include_directories("include/Threading" "src/") - -if (OGRE_THREAD_PROVIDER EQUAL 0) - list(APPEND THREAD_HEADER_FILES - include/Threading/OgreThreadDefinesNone.h - ) -elseif (OGRE_THREAD_PROVIDER EQUAL 1) - include_directories(${Boost_INCLUDE_DIRS}) - link_directories(${Boost_LIBRARY_DIRS}) - - list(APPEND THREAD_HEADER_FILES - include/Threading/OgreThreadDefinesBoost.h - include/Threading/OgreThreadHeadersBoost.h - ) -elseif (OGRE_THREAD_PROVIDER EQUAL 2) - list(APPEND THREAD_HEADER_FILES - include/Threading/OgreThreadDefinesPoco.h - include/Threading/OgreThreadHeadersPoco.h - ) -elseif (OGRE_THREAD_PROVIDER EQUAL 4) - list(APPEND THREAD_HEADER_FILES - include/Threading/OgreThreadDefinesSTD.h - include/Threading/OgreThreadHeadersSTD.h - ) -endif () - -list(APPEND HEADER_FILES ${THREAD_HEADER_FILES}) - -set(LIBRARIES) - -if (OGRE_CONFIG_THREADS) - list(APPEND LIBRARIES ${OGRE_THREAD_LIBRARIES}) -endif () - -if (OGRE_CONFIG_ENABLE_DDS) - list(APPEND SOURCE_FILES src/OgreDDSCodec.cpp src/OgreDDSCodec.h) -endif () - -if (OGRE_CONFIG_ENABLE_PVRTC) - list(APPEND HEADER_FILES ) - list(APPEND SOURCE_FILES src/OgrePVRTCCodec.cpp src/OgrePVRTCCodec.h) -endif () - -if (OGRE_CONFIG_ENABLE_ETC) - list(APPEND SOURCE_FILES src/OgreETCCodec.cpp src/OgreETCCodec.h) -endif () - -if (OGRE_CONFIG_ENABLE_ASTC) - list(APPEND SOURCE_FILES src/OgreASTCCodec.cpp src/OgreASTCCodec.h) -endif () - -if (OGRE_CONFIG_ENABLE_ZIP) - include_directories(src/zip) - list(APPEND HEADER_FILES include/OgreZip.h) - list(APPEND SOURCE_FILES src/OgreZip.cpp src/zip/zip.c) - - if(ANDROID) - list(APPEND PLATFORM_SOURCE_FILES src/Android/OgreAPKZipArchive.cpp) - endif() -endif () - -if(OGRE_CONFIG_FILESYSTEM_UNICODE) - set_source_files_properties(src/OgreFileSystem.cpp - PROPERTIES COMPILE_DEFINITIONS _OGRE_FILESYSTEM_ARCHIVE_UNICODE) - set_source_files_properties(src/OgreZip.cpp - PROPERTIES COMPILE_DEFINITIONS _OGRE_FILESYSTEM_ARCHIVE_UNICODE) -endif() - -if(OGRE_PROFILING_REMOTERY_PATH) - list(APPEND SOURCE_FILES ${OGRE_PROFILING_REMOTERY_PATH}/Remotery.c) - set_source_files_properties(${OGRE_PROFILING_REMOTERY_PATH}/Remotery.c PROPERTIES LANGUAGE CXX) - set_source_files_properties(src/OgreProfiler.cpp PROPERTIES COMPILE_DEFINITIONS USE_REMOTERY) -endif() - -set (TARGET_LINK_FLAGS "") - -# setup OgreMain target - -get_native_precompiled_header(OgreMain) -add_library(OgreMain ${OGRE_LIB_TYPE} ${OgreMain_pch} ${HEADER_FILES} ${SOURCE_FILES} ${PLATFORM_HEADERS} ${PLATFORM_SOURCE_FILES} ${THREAD_HEADER_FILES}) - -if (WINDOWS_STORE OR WINDOWS_PHONE) - set_target_properties(OgreMain PROPERTIES VS_WINRT_COMPONENT "true") -endif () - -generate_export_header(OgreMain - EXPORT_MACRO_NAME _OgreExport - NO_EXPORT_MACRO_NAME _OgrePrivate - DEPRECATED_MACRO_NAME OGRE_DEPRECATED - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreExports.h) - -target_include_directories(OgreMain PUBLIC - "$" - "$" - $ - PRIVATE "${OGRE_PROFILING_REMOTERY_PATH}") - -# In visual studio 2010 - 64 bit we get this error: "LINK : fatal error LNK1210: exceeded internal ILK size limit; link with /INCREMENTAL:NO" -if(WIN32 AND MSVC10 AND CMAKE_SIZEOF_VOID_P EQUAL 8) - set_target_properties(OgreMain PROPERTIES - VERSION ${OGRE_SOVERSION} - LINK_FLAGS "/INCREMENTAL:NO" - ) -else() - set_target_properties(OgreMain PROPERTIES VERSION ${OGRE_SOVERSION} SOVERSION ${OGRE_SOVERSION}) -endif() - -if (APPLE) - if (APPLE_IOS) - set_target_properties(OgreMain PROPERTIES INSTALL_NAME_DIR "OGRE") - else() - if(OGRE_BUILD_LIBS_AS_FRAMEWORKS) - set(OGRE_OSX_BUILD_CONFIGURATION "${CMAKE_OSX_SYSROOT}/$(CONFIGURATION)") - add_custom_command(TARGET OgreMain POST_BUILD - COMMAND mkdir ARGS -p ${PROJECT_BINARY_DIR}/lib/${OGRE_OSX_BUILD_CONFIGURATION}/Ogre.framework/Headers/Threading - COMMAND ditto - ${PROJECT_SOURCE_DIR}/OgreMain/include/Threading/*.h ${PROJECT_BINARY_DIR}/lib/${OGRE_OSX_BUILD_CONFIGURATION}/Ogre.framework/Headers/Threading - COMMAND cd ${PROJECT_BINARY_DIR}/lib/${OGRE_OSX_BUILD_CONFIGURATION}/Ogre.framework/Headers - ) - - foreach(HEADER_PATH ${THREAD_HEADER_FILES}) - get_filename_component(HEADER_FILE ${HEADER_PATH} NAME) - set(FWK_HEADER_PATH ${PROJECT_BINARY_DIR}/lib/${OGRE_OSX_BUILD_CONFIGURATION}/Ogre.framework/Headers/${HEADER_FILE}) - add_custom_command(TARGET OgreMain POST_BUILD - COMMAND rm -f ${FWK_HEADER_PATH} - ) - endforeach() - endif() - - ogre_config_framework(OgreMain) - endif () - - if(OGRE_BUILD_LIBS_AS_FRAMEWORKS) - # Framework is called 'Ogre' - set_target_properties(OgreMain PROPERTIES OUTPUT_NAME Ogre) - endif() -endif () -target_link_libraries(OgreMain PUBLIC ${PLATFORM_LIBS} PRIVATE ${LIBRARIES} ${CMAKE_DL_LIBS}) - -# specify a precompiled header to use -add_native_precompiled_header(OgreMain "$<$:${CMAKE_CURRENT_SOURCE_DIR}/src/OgreStableHeaders.h>") - -# install OgreMain -ogre_config_lib(OgreMain TRUE) -install(FILES ${HEADER_FILES} - DESTINATION include/OGRE -) -install(FILES ${PLATFORM_HEADERS} - DESTINATION include/OGRE/${PLATFORM_HEADER_INSTALL} -) -install(FILES ${THREAD_HEADER_FILES} - DESTINATION include/OGRE/Threading -) diff --git a/OgreMain/include/Ogre.h b/OgreMain/include/Ogre.h deleted file mode 100644 index ca996cba72a..00000000000 --- a/OgreMain/include/Ogre.h +++ /dev/null @@ -1,133 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _Ogre_H__ -#define _Ogre_H__ -// This file includes all the other files which you will need to build a client application -#include "OgrePrerequisites.h" - -#include "OgreAnimation.h" -#include "OgreAnimationState.h" -#include "OgreAnimationTrack.h" -#include "OgreAny.h" -#include "OgreArchive.h" -#include "OgreArchiveManager.h" -#include "OgreAxisAlignedBox.h" -#include "OgreBillboard.h" -#include "OgreBillboardChain.h" -#include "OgreBillboardSet.h" -#include "OgreBone.h" -#include "OgreCamera.h" -#include "OgreCompositor.h" -#include "OgreCompositorManager.h" -#include "OgreCompositorChain.h" -#include "OgreCompositorInstance.h" -#include "OgreCompositionTechnique.h" -#include "OgreCompositionPass.h" -#include "OgreCompositionTargetPass.h" -#include "OgreConfigFile.h" -#include "OgreControllerManager.h" -#include "OgreDataStream.h" -#include "OgreEntity.h" -#include "OgreException.h" -#include "OgreFrameListener.h" -#include "OgreFrustum.h" -#include "OgreGpuProgram.h" -#include "OgreGpuProgramManager.h" -#include "OgreHardwareBufferManager.h" -#include "OgreDefaultHardwareBufferManager.h" -#include "OgreHardwareIndexBuffer.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreHardwareOcclusionQuery.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreHighLevelGpuProgram.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreInstanceBatch.h" -#include "OgreInstancedEntity.h" -#include "OgreInstanceManager.h" -#include "OgreKeyFrame.h" -#include "OgreLight.h" -#include "OgreLogManager.h" -#include "OgreManualObject.h" -#include "OgreMaterial.h" -#include "OgreMaterialManager.h" -#include "OgreMaterialSerializer.h" -#include "OgreMath.h" -#include "OgreMatrix3.h" -#include "OgreMatrix4.h" -#include "OgreMesh.h" -#include "OgreMeshManager.h" -#include "OgreMovablePlane.h" -#include "OgreMeshSerializer.h" -#include "OgreParticleAffector.h" -#include "OgreParticleEmitter.h" -#include "OgreParticleSystem.h" -#include "OgreParticleSystemManager.h" -#include "OgrePass.h" -#include "OgrePatchMesh.h" -#include "OgrePatchSurface.h" -#include "OgreProfiler.h" -#include "OgreRectangle2D.h" -#include "OgreRenderQueueListener.h" -#include "OgreRenderObjectListener.h" -#include "OgreRenderSystem.h" -#include "OgreRenderTargetListener.h" -#include "OgreRenderTexture.h" -#include "OgreRenderWindow.h" -#include "OgreResourceBackgroundQueue.h" -#include "OgreResourceGroupManager.h" -#include "OgreRibbonTrail.h" -#include "OgreRoot.h" -#include "OgreSceneManager.h" -#include "OgreSceneNode.h" -#include "OgreShadowCameraSetup.h" -#include "OgreShadowCameraSetupFocused.h" -#include "OgreShadowCameraSetupLiSPSM.h" -#include "OgreShadowCameraSetupPlaneOptimal.h" -#include "OgreShadowCameraSetupPSSM.h" -#include "OgreSimpleRenderable.h" -#include "OgreSkeleton.h" -#include "OgreSkeletonInstance.h" -#include "OgreSkeletonManager.h" -#include "OgreSkeletonSerializer.h" -#include "OgreStaticGeometry.h" -#include "OgreString.h" -#include "OgreStringConverter.h" -#include "OgreStringVector.h" -#include "OgreSubEntity.h" -#include "OgreSubMesh.h" -#include "OgreTechnique.h" -#include "OgreTextureManager.h" -#include "OgreTextureUnitState.h" -#include "OgreTimer.h" -#include "OgreVector.h" -#include "OgreViewport.h" -#include "OgreComponents.h" -// .... more to come - -#endif diff --git a/OgreMain/include/Ogre.i b/OgreMain/include/Ogre.i deleted file mode 100644 index 021129f07ee..00000000000 --- a/OgreMain/include/Ogre.i +++ /dev/null @@ -1,903 +0,0 @@ - %module(package="Ogre", directors="1") Ogre - %{ - /* Includes the header in the wrapper code */ -#include "Ogre.h" -#include "OgreArchiveFactory.h" -#include "OgreRectangle2D.h" -#include "OgreWireBoundingBox.h" -#include "OgreVertexBoneAssignment.h" -#include "OgreCodec.h" -#include "OgreZip.h" -#include "OgreParticleSystemRenderer.h" -#include "OgreParticleEmitterFactory.h" -#include "OgreParticleAffectorFactory.h" -#include "OgreScriptCompiler.h" -#include "OgreConfigDialog.h" -#include "OgreFileSystemLayer.h" -#include "OgrePredefinedControllers.h" -#include "OgrePixelCountLodStrategy.h" -#include "OgreDefaultDebugDrawer.h" -%} - -%include stdint.i -%include std_shared_ptr.i -%include std_string.i -%include std_pair.i -%include std_map.i -#ifdef SWIGPYTHON -%include std_multimap.i -%include std_list.i -#endif -%include std_vector.i -%include exception.i -%include typemaps.i - -// so swig correctly resolves "using std::*" declarations -%inline %{ -using namespace std; -%} - -/* Parse the header file to generate wrappers */ -#define _OgreExport -#define _OgrePrivate -#define OGRE_DEPRECATED -#define OGRE_NORETURN -#define OGRE_NODISCARD -#define OGRE_STATIC_MUTEX(arg) -#define OGRE_MUTEX(arg) - -%feature("autodoc", "1"); -%feature("director") *::Listener; -#ifdef SWIGPYTHON -// should be turned on globally if all renames are in place -%feature("flatnested") Ogre::MaterialManager::Listener; -%feature("flatnested") Ogre::SceneManager::Listener; -#endif - -%ignore *::operator=; // needs rename to wrap -%ignore *::setUserAny; // deprecated -%ignore *::getUserAny; // deprecated -%ignore *::getSingletonPtr; // only expose the non ptr variant -%ignore Ogre::Exception::getNumber; // deprecated -%ignore Ogre::ExceptionFactory::throwExceptionEx; // deprecated -%rename(OgreException) Ogre::Exception; // confilcts with Python Exception - -#ifdef __ANDROID__ -%{ -#include -static JavaVM *cached_jvm = 0; - -JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) { - cached_jvm = jvm; - return JNI_VERSION_1_2; -} - -JNIEnv* OgreJNIGetEnv() { - JNIEnv *env; - jint rc = cached_jvm->GetEnv((void **)&env, JNI_VERSION_1_2); - if (rc == JNI_EDETACHED) - throw std::runtime_error("current thread not attached"); - if (rc == JNI_EVERSION) - throw std::runtime_error("jni version not supported"); - return env; -} -%} -#endif - -#ifdef SWIG_DIRECTORS -%feature("director:except") { - if ($error != NULL) { - throw Swig::DirectorMethodException(); - } -} -#endif - -#ifdef SWIGCSHARP - %apply void *VOID_INT_PTR {void *} - - %typemap(csvarout) void * %{ - get { - global::System.IntPtr cPtr = $imcall; - if (OgrePINVOKE.SWIGPendingException.Pending) throw OgrePINVOKE.SWIGPendingException.Retrieve(); - return cPtr; - } - %} -#endif - -// convert c++ exceptions to language native exceptions -%exception { - try { - $action - } -#ifdef SWIGPYTHON - catch (Swig::DirectorException &e) { - SWIG_fail; - } - catch (std::length_error &e) { - SWIG_fail; - } -#endif - catch (const std::exception& e) { - SWIG_exception(SWIG_RuntimeError, e.what()); - } -} - -// connect operator<< to tp_repr -%ignore ::operator<<; -%feature("python:slot", "tp_repr", functype="reprfunc") *::__repr__; - -%ignore *::operator+; -%rename(__add__) *::operator+; - -%ignore *::operator-; -%rename(__sub__) *::operator-; - -%ignore *::operator*; -%rename(__mul__) *::operator*; - -%ignore *::operator/; -%rename(__div__) *::operator/; - -#ifdef SWIGJAVA -#define REPRFUNC toString -#elif defined(SWIGCSHARP) -#define REPRFUNC ToString -#else -#define REPRFUNC __repr__ -#endif - -%define ADD_REPR(classname) -%extend Ogre::classname { - const std::string REPRFUNC() { - std::ostringstream out; - out << *$self; - return out.str(); - } -} -%enddef - -%define SHARED_PTR(classname) -// %shared_ptr(type); -%template(classname ## Ptr) Ogre::SharedPtr; -%enddef - -%ignore *::operator[]; -%define SEQUENCE_METHODS -{ - void __setitem__(uint i, float v) { (*$self)[i] = v; } - size_t __len__() { return sizeof(*$self)/sizeof(float); } - float __getitem__(uint i) { - if(i >= sizeof(*$self)/sizeof(float)) - throw std::length_error("out of bounds"); - return (*$self)[i]; - } -} -%enddef - -#ifdef SWIGJAVA -// use proper (1.5+) enums -%include "enums.swg" -// conflicts with SWIG method -%ignore *::getType; -#endif - -#ifdef SWIGCSHARP -%ignore Ogre::HardwareBuffer::UsageEnum; -%ignore Ogre::TextureUsage; -%ignore Ogre::GpuConstantType; -%ignore Ogre::GpuProgramParameters::ElementType; -%ignore Ogre::Capabilities; -%typemap(csbase) Ogre::SceneManager::QueryTypeMask "uint"; -%csmethodmodifiers *::ToString "public override"; -// wrong "override" because of multiple inheritance -%csmethodmodifiers *::getMaterial "public"; -%csmethodmodifiers *::getSquaredViewDepth "public"; -%csmethodmodifiers *::getWorldTransforms "public"; -%csmethodmodifiers *::getRenderOperation "public"; -%csmethodmodifiers *::getLights "public"; -%csmethodmodifiers *::queryResult "public"; -%csmethodmodifiers *::createInstance "public"; -%csmethodmodifiers *::loadingComplete "public"; -%csmethodmodifiers *::getBoundingBox "public"; -%csmethodmodifiers *::getBoundingRadius "public"; -%csmethodmodifiers *::getMovableType "public"; -%csmethodmodifiers *::visitRenderables "public"; -%csmethodmodifiers *::loadResource "public"; -%csmethodmodifiers *::createAnimation "public"; -%csmethodmodifiers *::getAnimation "public"; -%csmethodmodifiers *::hasAnimation "public"; -%csmethodmodifiers *::removeAnimation "public"; -%csmethodmodifiers *::getNumAnimations "public"; -%csmethodmodifiers *::getAnimation "public"; -%csmethodmodifiers *::_notifyCurrentCamera "public"; -%csmethodmodifiers *::_updateRenderQueue "public"; -%csmethodmodifiers *::_notifyAttached "public"; -%csmethodmodifiers *::setRenderQueueGroup "public"; -%csmethodmodifiers *::setRenderQueueGroupAndPriority "public"; -%csmethodmodifiers *::getTypeFlags "public"; -%csmethodmodifiers *::viewportDestroyed "public"; -%csmethodmodifiers *::viewportDimensionsChanged "public"; -%csmethodmodifiers *::viewportCameraChanged "public"; -%csmethodmodifiers Ogre::BillboardChain::preRender "public"; -#endif - -// connect __getitem__ -%feature("python:slot", "sq_item", functype="ssizeargfunc") *::__getitem__; - -// connect __setitem__ -%feature("python:slot", "sq_ass_item", functype="ssizeobjargproc") *::__setitem__; - -// connect __len__ -%feature("python:slot", "sq_length", functype="lenfunc") *::__len__; - -// stringinterface internal -%rename("$ignore", regextarget=1) "^Cmd+"; - -/* these are ordered by dependancy */ -%include "OgreBuildSettings.h" - -#ifdef SWIGPYTHON - #define XSTR(x) #x - #define STR(x) XSTR(x) - #define __version__ STR(OGRE_VERSION_MAJOR) "." STR(OGRE_VERSION_MINOR) "." STR(OGRE_VERSION_PATCH) - #undef STR - #undef XSTR -#endif - -%include "OgrePrerequisites.h" -%include "OgrePlatform.h" -%include "OgreConfig.h" -%ignore Ogre::AllocPolicy; -%import "OgreMemoryAllocatorConfig.h" -%include "OgreCommon.h" -%template(NameValueMap) std::map; -ADD_REPR(TRect) -%template(Rect) Ogre::TRect; -%template(FloatRect) Ogre::TRect; -%ignore Ogre::findCommandLineOpts; // not needed in python - -// Basic Data Types -%include "OgreException.h" -%ignore Ogre::SharedPtr::useCount; -%ignore Ogre::SharedPtr::bind; -%ignore Ogre::SharedPtr::getPointer; -%ignore Ogre::SharedPtr::setNull; -%ignore Ogre::SharedPtr::isNull; -%ignore Ogre::SharedPtr::setUseCount; -%include "OgreSharedPtr.h" -%ignore Ogre::Any::getType; // deprecated -%ignore Ogre::Any::destroy; // deprecated -%ignore Ogre::Any::isEmpty; // deprecated -%include "OgreAny.h" -%include "OgreMath.h" -ADD_REPR(Degree) -ADD_REPR(Radian) -%template(RayTestResult) std::pair; -%include "OgreStringVector.h" -%template(StringList) std::vector; // actual vector -%template(StringListPtr) Ogre::SharedPtr >; -%include "OgreFileSystemLayer.h" -// Linear Algebra -%ignore Ogre::Vector<2, Ogre::Real>::Vector(float, float, float); -%ignore Ogre::Vector<2, Ogre::Real>::Vector(float, float, float, float); -%ignore Ogre::Vector<2, Ogre::Real>::xy; -%ignore Ogre::Vector<2, Ogre::Real>::xyz; -%ignore Ogre::Vector<3, Ogre::Real>::Vector(float, float); -%ignore Ogre::Vector<3, Ogre::Real>::Vector(float, float, float, float); -%ignore Ogre::Vector<3, Ogre::Real>::xyz; -%ignore Ogre::Vector<3, int>::Vector(int, int, int, int); -%ignore Ogre::Vector<3, int>::xyz; -%ignore Ogre::Vector<4, Ogre::Real>::Vector(float, float); -%ignore Ogre::Vector<4, Ogre::Real>::Vector(float, float, float); -%include "OgreVector.h" -ADD_REPR(Vector) - -%define TPL_VECTOR(N) -%ignore Ogre::VectorBase::VectorBase; -%ignore Ogre::VectorBase::ZERO; -%ignore Ogre::VectorBase::UNIT_SCALE; -%ignore Ogre::VectorBase::UNIT_X; -%ignore Ogre::VectorBase::UNIT_Y; -%ignore Ogre::VectorBase::UNIT_Z; -%ignore Ogre::VectorBase::NEGATIVE_UNIT_X; -%ignore Ogre::VectorBase::NEGATIVE_UNIT_Y; -%ignore Ogre::VectorBase::NEGATIVE_UNIT_Z; -%template(VectorBase ## N) Ogre::VectorBase; -%template(Vector ## N) Ogre::Vector; - -%extend Ogre::Vector SEQUENCE_METHODS -%enddef - -%ignore Ogre::VectorBase<3, int>::VectorBase; -%template(VectorBase3i) Ogre::VectorBase<3, int>; -%template(Vector3i) Ogre::Vector<3, int>; -%extend Ogre::Vector<3, int> SEQUENCE_METHODS - -TPL_VECTOR(2) -TPL_VECTOR(3) -TPL_VECTOR(4) - -%extend Ogre::ColourValue SEQUENCE_METHODS -%extend Ogre::Quaternion SEQUENCE_METHODS - -#ifdef SWIGCSHARP -%define CS_VECTOR_OPS(N) -%extend Ogre::Vector { - %proxycode %{ - public static Vector ## N operator+(Vector ## N lhs, Vector ## N rhs) { return lhs.__add__(rhs); } - public static Vector ## N operator-(Vector ## N lhs, Vector ## N rhs) { return lhs.__sub__(rhs); } - public static Vector ## N operator*(Vector ## N lhs, Vector ## N rhs) { return lhs.__mul__(rhs); } - public static Vector ## N operator/(Vector ## N lhs, Vector ## N rhs) { return lhs.__div__(rhs); } - public float this[uint i] { get { return __getitem__(i); } set { __setitem__(i, value); } } - %} -} -%enddef -CS_VECTOR_OPS(2); -CS_VECTOR_OPS(3); -CS_VECTOR_OPS(4); -#endif - -#ifdef SWIGPYTHON -// enable implicit conversion from float to Radian -%typemap(in) const Ogre::Radian& (Ogre::Radian tmp) { - void *argp = 0; - int res = SWIG_ConvertPtr($input, &argp, $descriptor, $disown); - if (SWIG_IsOK(res)) { - $1 = ($ltype)(argp); - } - else if(SWIG_IsOK(SWIG_ConvertPtr($input, &argp, $descriptor(Ogre::Degree*), $disown))) - { - tmp = *((Ogre::Degree*)argp); - $1 = &tmp; - } - else - { - res = SWIG_AsVal_float($input, (float*)&tmp); - $1 = &tmp; - - if (!SWIG_IsOK(res)) - SWIG_exception_fail(SWIG_TypeError, "Expected float (Ogre::Radian) or Ogre::Degree"); - } -} -// punch through overload resolution -%typecheck(SWIG_TYPECHECK_POINTER) const Ogre::Radian& { - $1 = true; // actual check in the typemap -} - -%typemap(in) void*, Ogre::uchar* { - void* argp; - // always allow uchar* as thats how pixel data is usually passed around - int res = SWIG_ConvertPtr($input, &argp, $descriptor(Ogre::uchar*), $disown); - if (SWIG_IsOK(res)) { - $1 = ($ltype)(argp); - } else { - Py_buffer view; - res = PyObject_GetBuffer($input, &view, PyBUF_CONTIG); - if (res < 0) { - SWIG_fail; - } - PyBuffer_Release(&view); - $1 = ($ltype)view.buf; - } -} -%typecheck(SWIG_TYPECHECK_POINTER) void*, Ogre::uchar* { - $1 = true; // actual check in the typemap -} - -%define TYPEMAP_SEQUENCE_FOR(TYPE, LEN_CHECK) -%typemap(in) const TYPE& (TYPE temp) { - void *argp = 0; - int res = SWIG_ConvertPtr($input, &argp, $descriptor, $disown); - if (SWIG_IsOK(res)) { - $1 = ($ltype)(argp); - } else { - int len = PySequence_Length($input); - for (int i = 0; i < len; i++) { - PyObject *o = PySequence_GetItem($input, i); - if (!PyNumber_Check(o)) { - Py_XDECREF(o); - SWIG_exception_fail(SWIG_TypeError, "Sequence elements must be numbers"); - } - temp.ptr()[i] = (float)PyFloat_AsDouble(o); - Py_DECREF(o); - } - $1 = &temp; - } -} -%typecheck(SWIG_TYPECHECK_STRING) const TYPE& { - if (PySequence_Check($input)) - { - int len = PySequence_Length($input); - $1 = (LEN_CHECK); - } - else { - $1 = false; - } -} -%enddef -TYPEMAP_SEQUENCE_FOR(Ogre::Vector2, len == 2) -TYPEMAP_SEQUENCE_FOR(Ogre::Vector3, len == 3) -TYPEMAP_SEQUENCE_FOR(Ogre::Vector4, len == 4) -TYPEMAP_SEQUENCE_FOR(Ogre::Quaternion, len == 4) -TYPEMAP_SEQUENCE_FOR(Ogre::ColourValue, len >= 3 && len <= 4) -#endif - -%include "OgreMatrix3.h" -ADD_REPR(Matrix3) -%extend Ogre::Matrix3 -{ - Ogre::Vector3 operator*(const Ogre::Vector3& v) { return *$self * v; } -} -%ignore Ogre::TransformBaseReal::extract3x3Matrix; // deprecated -%ignore Ogre::TransformBaseReal::extractQuaternion; // deprecated -%ignore Ogre::Matrix4::concatenate; // deprecated -%include "OgreMatrix4.h" -ADD_REPR(Matrix4) -%template(TransformBaseMatrix4) Ogre::TransformBase<4, Ogre::Real>; -%extend Ogre::Matrix4 -{ - Ogre::Vector4 operator*(const Ogre::Vector4& v) { return *$self * v; } - Ogre::Vector3 operator*(const Ogre::Vector3& v) { return *$self * v; } - Ogre::Matrix4 operator*(const Ogre::Matrix4& m) { return *$self * m; } - Ogre::Matrix4 operator+(const Ogre::Matrix4& m) { return *$self + m; } - Ogre::Matrix4 operator-(const Ogre::Matrix4& m) { return *$self - m; } - Ogre::Real __getitem__(int row, int column) { return (*$self)[row][column]; } -} -ADD_REPR(Affine3) -%extend Ogre::Affine3 -{ - Ogre::Vector4 operator*(const Ogre::Vector4& v) { return *$self * v; } - Ogre::Vector3 operator*(const Ogre::Vector3& v) { return *$self * v; } - Ogre::Affine3 operator*(const Ogre::Affine3& m) { return *$self * m; } -} -%include "OgreQuaternion.h" -ADD_REPR(Quaternion) -%include "OgreSimpleSpline.h" -%include "OgreRotationalSpline.h" -// Geometric Primitives -%include "OgreAxisAlignedBox.h" -ADD_REPR(AxisAlignedBox) -%include "OgreSphere.h" -%include "OgrePlane.h" -ADD_REPR(Plane) -%include "OgrePlaneBoundedVolume.h" -// I/O -%include "OgreConfigOptionMap.h" -%template(ConfigOptionMap) std::map; -%ignore Ogre::ConfigFile::load; // conflicting overloads -%ignore Ogre::ConfigFile::getSettingsIterator; // deprecated -%ignore Ogre::ConfigFile::getSectionIterator; -%template(SettingsBySectionMap) std::map >; -#ifdef SWIGPYTHON -%template(SettingsMultiMap) std::multimap; -#endif -%include "OgreConfigFile.h" -%ignore Ogre::Log::Stream; // not useful in bindings -%ignore Ogre::Log::stream; -%feature("director") Ogre::LogListener; -%ignore Ogre::Log::setLogDetail; -%include "OgreLog.h" -%ignore Ogre::LogManager::stream; // not useful in bindings -%ignore Ogre::LogManager::setLogDetail; -%include "OgreLogManager.h" -#ifdef SWIGJAVA -// conflicts with SWIG interal func -%ignore Ogre::MemoryDataStream::MemoryDataStream(size_t, bool); -%ignore Ogre::AtomAbstractNode::getValue; -#endif -SHARED_PTR(DataStream); -%ignore Ogre::MemoryDataStream::MemoryDataStream(DataStream&, bool = true, bool = false); -%ignore Ogre::MemoryDataStream::MemoryDataStream(const String&, DataStream&, bool = true, bool = false); -SHARED_PTR(MemoryDataStream); -SHARED_PTR(FileStreamDataStream); -SHARED_PTR(FileHandleDataStream); -%include "OgreDataStream.h" -%include "OgreArchive.h" -%include "OgreFactoryObj.h" -// %template(FactoryObjArchive) Ogre::FactoryObj; -%include "OgreArchiveFactory.h" -%ignore Ogre::ZipArchiveFactory; // private -%include "OgreZip.h" -%ignore Ogre::ArchiveManager::getArchiveIterator; -%include "OgreArchiveManager.h" -%include "OgreCodec.h" -%include "OgreSerializer.h" -%include "OgreScriptLoader.h" -// Listeners -%feature("director") Ogre::FrameListener; -%include "OgreFrameListener.h" -%feature("director") Ogre::LodListener; -%include "OgreLodListener.h" -%feature("director") Ogre::RenderObjectListener; -%include "OgreRenderObjectListener.h" -%feature("director") Ogre::RenderQueueListener; -%include "OgreRenderQueueListener.h" -%feature("director") Ogre::RenderTargetListener; -%include "OgreRenderTargetListener.h" -%feature("director") Ogre::MeshSerializerListener; -%feature("director") Ogre::ResourceLoadingListener; -// More Data Types -%include "OgreColourValue.h" -ADD_REPR(ColourValue) -%include "OgrePixelFormat.h" -#ifdef SWIGCSHARP -%extend Ogre::PixelBox -{ - void* getData() { return $self->data; } -} -#endif -%include "OgreBlendMode.h" -%include "OgreRay.h" -%include "OgreSceneQuery.h" -%template(RaySceneQueryResult) std::vector; -#ifdef SWIGPYTHON -%template(SceneQueryResultMovableList) std::list; -#endif - -%ignore *::convertColourValue; // deprecated - -%include "OgreNameGenerator.h" -%include "OgreController.h" -%ignore Ogre::GpuProgramParameters::hasPassIterationNumber; // deprecated -%ignore Ogre::GpuProgramParameters::getPassIterationNumberIndex; // deprecated -%ignore Ogre::GpuProgramParameters::setConstantFromTime; -%ignore Ogre::GpuProgramParameters::getConstantDefinitionIterator; -%ignore Ogre::GpuSharedParameters::getConstantDefinitionIterator; -SHARED_PTR(GpuProgramParameters); -%include "OgreGpuProgramParams.h" -%include "OgreImage.h" -%include "OgreBillboard.h" -%include "OgreParticle.h" -%include "OgreHardwareOcclusionQuery.h" -SHARED_PTR(HardwareBuffer); -%include "OgreHardwareBuffer.h" - -#ifdef SWIGPYTHON -%ignore std::vector::resize; // non default constructible -%ignore std::vector::vector; -%template(ParameterList) std::vector; -#endif -SHARED_PTR(StringInterface); -%include "OgreStringInterface.h" - SHARED_PTR(ParticleAffector); - %include "OgreParticleAffector.h" - %include "OgreParticleAffectorFactory.h" -// SHARED_PTR(ParticleEmitter); - %include "OgreParticleEmitter.h" - %include "OgreParticleEmitterFactory.h" - SHARED_PTR(Resource); - %include "OgreResource.h" - SHARED_PTR(Texture); - %ignore Ogre::Texture::setTreatLuminanceAsAlpha; - %include "OgreTexture.h" - SHARED_PTR(GpuProgram); - %ignore Ogre::GpuProgram::setAdjacencyInfoRequired; - %include "OgreGpuProgram.h" - SHARED_PTR(HighLevelGpuProgram); - %include "OgreHighLevelGpuProgram.h" -%include "OgreRenderSystemCapabilities.h" -%include "OgreScriptCompiler.h" -%ignore Ogre::TextureUnitState::setCubicTexture; -%ignore Ogre::TextureUnitState::setCubicTextureName; -%ignore Ogre::TextureUnitState::isCubic; -%ignore Ogre::TextureUnitState::is3D; -%ignore Ogre::TextureUnitState::setBindingType; -%ignore Ogre::TextureUnitState::getBindingType; -%ignore Ogre::TextureUnitState::setIsAlpha; -%ignore Ogre::TextureUnitState::setTextureNameAlias; -%ignore Ogre::TextureUnitState::getTextureNameAlias; -%include "OgreTextureUnitState.h" -%template(ControllerFloat) Ogre::Controller; -%template(ControllerValueFloatPtr) Ogre::SharedPtr >; -%template(ControllerFunctionPtr) Ogre::SharedPtr >; -%include "OgreControllerManager.h" -%include "OgrePredefinedControllers.h" -SHARED_PTR(Compositor); -%ignore Ogre::Compositor::getTechniqueIterator; -%ignore Ogre::Compositor::getSupportedTechniqueIterator; -%include "OgreCompositor.h" -%ignore Ogre::CompositionTechnique::getNumTextureDefinitions; -%ignore Ogre::CompositionTechnique::getTextureDefinitionIterator; -%ignore Ogre::CompositionTechnique::getTargetPass; -%ignore Ogre::CompositionTechnique::getNumTargetPasses; -%ignore Ogre::CompositionTechnique::getTargetPassIterator; -%include "OgreCompositionTechnique.h" -%ignore Ogre::CompositionTargetPass::getPass; -%ignore Ogre::CompositionTargetPass::getNumPasses; -%ignore Ogre::CompositionTargetPass::getPassIterator; -%include "OgreCompositionTargetPass.h" -SHARED_PTR(HardwareBuffer); -SHARED_PTR(HardwareVertexBuffer); -#ifdef SWIGPYTHON -%template(VertexElementList) std::list; -#endif -%include "OgreHardwareVertexBuffer.h" -SHARED_PTR(HardwareIndexBuffer); -%include "OgreHardwareIndexBuffer.h" -SHARED_PTR(HardwarePixelBuffer); -#ifdef SWIGJAVA -%ignore Ogre::HardwarePixelBuffer::lock; // duplicate definition -#endif -%include "OgreHardwarePixelBuffer.h" -%ignore Ogre::HardwareBufferManagerBase::_forceReleaseBufferCopies(HardwareVertexBuffer* sourceBuffer); -%include "OgreHardwareBufferManager.h" -%include "OgreDefaultHardwareBufferManager.h" -%include "OgreVertexIndexData.h" -// managers -%ignore Ogre::ResourceGroupManager::openResource(const String&, const String&, bool, Resource*) const; -%ignore Ogre::ResourceGroupManager::openResource(const String&, const String&, bool) const; -%ignore Ogre::ResourceGroupManager::getResourceManagerIterator; -%include "OgreResourceGroupManager.h" -#if SWIG_VERSION < 0x030012 || defined(SWIGJAVA) -// conflicts with overloaded versions (GpuProgram, Texture) -%ignore Ogre::ResourceManager::getResourceByName; -%ignore Ogre::ResourceManager::createOrRetrieve; -%ignore Ogre::ResourceManager::prepare; -%ignore Ogre::ResourceManager::load; -#endif -%ignore Ogre::ResourceManager::getResourceIterator; -%include "OgreResourceManager.h" - // ambiguity as enums are just ints - %ignore Ogre::TextureManager::createManual(const String&, const String&,TextureType,uint,uint,int,PixelFormat,int); - %ignore Ogre::TextureManager::createManual(const String&, const String&,TextureType,uint,uint,int,PixelFormat); - %include "OgreTextureManager.h" - %include "OgreGpuProgramManager.h" - %include "OgreHighLevelGpuProgramManager.h" -// animations -%ignore Ogre::VertexPoseKeyFrame::getPoseReferenceIterator; -%include "OgreKeyFrame.h" -%ignore Ogre::Pose::getNormalsIterator; -%ignore Ogre::Pose::getVertexOffsetIterator; -%include "OgrePose.h" -%include "OgreAnimationTrack.h" -%ignore Ogre::AnimationStateSet::getAnimationStateIterator; -%ignore Ogre::AnimationStateSet::getEnabledAnimationStateIterator; -%include "OgreAnimationState.h" - -#ifdef SWIGPYTHON -%{ - // this is a workaround for the following map with swig 3.0.12 - namespace swig { - template<> struct traits { - typedef pointer_category category; - static const char* type_name() { return "Ogre::AnimationState"; } - }; - template<> struct traits { - typedef pointer_category category; - static const char* type_name() { return "Ogre::Camera"; } - }; - } -%} -#endif -%template(AnimationStateMap) std::map; -%ignore Ogre::Animation::getVertexTrackIterator; -%ignore Ogre::Animation::getNodeTrackIterator; -%ignore Ogre::Animation::getNumericTrackIterator; -%include "OgreAnimation.h" -SHARED_PTR(Skeleton); -// deprecated -%ignore Ogre::Skeleton::getRootBone; -%ignore Ogre::Skeleton::getRootBoneIterator; -%ignore Ogre::Skeleton::getBoneIterator; -%ignore Ogre::Skeleton::getLinkedSkeletonAnimationSourceIterator; -%template(BoneList) std::vector; -%include "OgreSkeleton.h" - %ignore Ogre::SkeletonInstance::getLinkedSkeletonAnimationSourceIterator; - SHARED_PTR(SkeletonInstance); - %include "OgreSkeletonInstance.h" -%include "OgreSkeletonManager.h" -%include "OgreRenderQueue.h" -%include "OgreRenderOperation.h" -%ignore Ogre::Material::getLodValueIterator; -%ignore Ogre::Material::getUserLodValueIterator; -%ignore Ogre::Material::getSupportedTechniqueIterator; -%ignore Ogre::Material::getTechniqueIterator; -%ignore Ogre::Material::getSupportedTechnique; -%ignore Ogre::Material::getNumSupportedTechniques; -%ignore Ogre::Material::clone(const String&, bool) const; -%ignore Ogre::Material::clone(const String&, bool, const String&) const; -SHARED_PTR(Material); -%template(TechniqueList) std::vector; -%include "OgreMaterial.h" -%ignore Ogre::RenderSystem::_setSceneBlending; -%ignore Ogre::RenderSystem::_setSeparateSceneBlending; -%ignore Ogre::RenderSystem::_setColourBufferWriteEnabled; -%ignore Ogre::RenderSystem::_setFog; -%ignore Ogre::RenderSystem::_setWorldMatrix; -%ignore Ogre::RenderSystem::_setViewMatrix; -%ignore Ogre::RenderSystem::_setProjectionMatrix; -%ignore Ogre::RenderSystem::getRenderTargetIterator; -%ignore Ogre::RenderSystem::getColourVertexElementType; -%ignore Ogre::RenderSystem::setStencilCheckEnabled; -%ignore Ogre::RenderSystem::setStencilBufferParams; -%include "OgreRenderSystem.h" -%include "OgreCompositorManager.h" -#ifdef SWIGJAVA -%ignore Ogre::CompositorInstance::Listener; // issue with converting shared_ptr -#endif -%include "OgreCompositorInstance.h" -%include "OgreCompositionPass.h" -%include "OgreMaterialSerializer.h" -%include "OgreUserObjectBindings.h" -%rename(MaterialManager_Listener) Ogre::MaterialManager::Listener; -%include "OgreMaterialManager.h" -%include "OgreRenderable.h" -%ignore Ogre::ShadowCaster::getShadowVolumeRenderableIterator; -%include "OgreShadowCaster.h" -%extend Ogre::MovableObject { - Entity* castEntity() - { - return dynamic_cast($self); - } -} -%extend Ogre::Node { - SceneNode* castSceneNode() - { - return dynamic_cast($self); - } -} -%include "OgreMovableObject.h" - %feature("flatnested") Ogre::BillboardChain::Element; - %rename(BillboardChain_Element) Ogre::BillboardChain::Element; - %include "OgreBillboardChain.h" - %ignore Ogre::RibbonTrail::getNodeIterator; - %include "OgreRibbonTrail.h" - %ignore Ogre::BillboardSet::setTextureCoords(const FloatRect*, uint16); - %include "OgreBillboardSet.h" - %include "OgreMovablePlane.h" - %ignore Ogre::Light::setPosition; - %ignore Ogre::Light::getPosition; - %ignore Ogre::Light::getDirection; - %include "OgreLight.h" - %ignore Ogre::Node::getChildIterator; - %template(NodeList) std::vector; - %include "OgreNode.h" - %include "OgreBone.h" - %ignore Ogre::SceneNode::getAttachedObjectIterator; - %template(MovableObjectList) std::vector; - %include "OgreSceneNode.h" - SHARED_PTR(ShadowCameraSetup); - SHARED_PTR(DefaultShadowCameraSetup); - %include "OgreShadowCameraSetup.h" - SHARED_PTR(FocusedShadowCameraSetup); - %include "OgreShadowCameraSetupFocused.h" - SHARED_PTR(LiSPSMShadowCameraSetup); - %include "OgreShadowCameraSetupLiSPSM.h" - SHARED_PTR(PlaneOptimalShadowCameraSetup); - %include "OgreShadowCameraSetupPlaneOptimal.h" - SHARED_PTR(PSSMShadowCameraSetup); - %include "OgreShadowCameraSetupPSSM.h" - %template(SplitPointList) std::vector; - %ignore Ogre::Frustum::getFrustumExtents(Real&, Real& ,Real& ,Real&) const; - %include "OgreFrustum.h" - %ignore Ogre::Camera::setPosition; - %ignore Ogre::Camera::getPosition; - %ignore Ogre::Camera::setDirection; - %ignore Ogre::Camera::getDirection; - %ignore Ogre::Camera::setOrientation; - %ignore Ogre::Camera::getOrientation; - %ignore Ogre::Camera::rotate; - %ignore Ogre::Camera::getUp; - %ignore Ogre::Camera::getRight; - %ignore Ogre::Camera::lookAt; - %ignore Ogre::Camera::roll; - %ignore Ogre::Camera::yaw; - %ignore Ogre::Camera::pitch; - %ignore Ogre::Camera::setFixedYawAxis; - %ignore Ogre::Camera::setAutoTracking; - %ignore Ogre::Camera::move; - %ignore Ogre::Camera::moveRelative; - %ignore Ogre::Camera::_renderScene(Viewport*, bool); - %include "OgreCamera.h" - ADD_REPR(Camera) - %include "OgreManualObject.h" - %template(SubEntityList) std::vector; - %ignore Ogre::Entity::getAttachedObjectIterator; - %include "OgreEntity.h" - %include "OgreSubEntity.h" - %include "OgreParticleSystemRenderer.h" - SHARED_PTR(ParticleSystem); - %ignore Ogre::ParticleSystem::_getIterator; - %include "OgreParticleSystem.h" - %include "OgreInstancedEntity.h" - %include "OgreInstanceBatch.h" - %ignore Ogre::SimpleRenderable::setMaterial(const String&); - %include "OgreSimpleRenderable.h" - %include "OgreRectangle2D.h" - %include "OgreWireBoundingBox.h" -%ignore Ogre::ParticleSystemManager::getTemplateIterator; -%ignore Ogre::ParticleSystemManager::getEmitterFactoryIterator; -%ignore Ogre::ParticleSystemManager::getAffectorFactoryIterator; -%ignore Ogre::ParticleSystemManager::getRendererFactoryIterator; -%include "OgreParticleSystemManager.h" -%ignore Ogre::InstanceManager::getInstanceBatchIterator; -%ignore Ogre::InstanceManager::getInstanceBatchMapIterator; -%include "OgreInstanceManager.h" -%include "OgreVertexBoneAssignment.h" -// deprecated -%ignore Ogre::Mesh::getSubMeshIterator; -%ignore Ogre::Mesh::getPoseCount; -%ignore Ogre::Mesh::getPose; -%ignore Ogre::Mesh::getPoseIterator; -%ignore Ogre::Mesh::getBoneAssignmentIterator; -%template(PoseList) std::vector; -%template(SubMeshList) std::vector; -%apply unsigned short& OUTPUT { unsigned short& outSourceCoordSet, unsigned short& outIndex }; -SHARED_PTR(Mesh); -%include "OgreMesh.h" -%ignore Ogre::SubMesh::getBoneAssignmentIterator; -%include "OgreSubMesh.h" -%ignore Ogre::StaticGeometry::getRegionIterator; -%ignore Ogre::StaticGeometry::Region::getLODIterator; -%ignore Ogre::StaticGeometry::MaterialBucket::getGeometryIterator; -%ignore Ogre::StaticGeometry::LODBucket::getMaterialIterator; -%include "OgreStaticGeometry.h" -%include "OgrePatchSurface.h" - SHARED_PTR(PatchMesh); - %include "OgrePatchMesh.h" -%include "OgreMeshSerializer.h" -%include "OgreMeshManager.h" -%include "OgreLodStrategy.h" -%include "OgrePixelCountLodStrategy.h" -%ignore Ogre::Pass::getTextureUnitStateIterator; // deprecated -%template(TextureUnitStateList) std::vector; -%include "OgrePass.h" - %ignore Ogre::Technique::getGPUVendorRuleIterator; - %ignore Ogre::Technique::getGPUDeviceNameRuleIterator; - %ignore Ogre::Technique::getIlluminationPassIterator; - %ignore Ogre::Technique::getPassIterator(); - %template(PassList) std::vector; - %template(IlluminationPassList) std::vector; - %include "OgreTechnique.h" -%ignore Ogre::RenderTarget::copyContentsToMemory(const PixelBox&); -%ignore Ogre::RenderTarget::copyContentsToMemory(const PixelBox&, FrameBuffer); // deprecated -%feature("flatnested") Ogre::RenderTarget::FrameStats; -%include "OgreRenderTarget.h" -#ifdef __ANDROID__ - %ignore Ogre::RenderWindow::_notifySurfaceCreated(void*); - %ignore Ogre::RenderWindow::_notifySurfaceCreated(void*, void*); - %extend Ogre::RenderWindow { - void _notifySurfaceCreated(jobject surface) { - ANativeWindow* nativeWnd = ANativeWindow_fromSurface(OgreJNIGetEnv(), surface); - $self->_notifySurfaceCreated(nativeWnd, NULL); - } - } -#endif - %include "OgreRenderWindow.h" - %include "OgreRenderTexture.h" -%ignore Ogre::Viewport::getActualDimensions(int&, int& ,int& ,int&) const; -%include "OgreViewport.h" -%ignore Ogre::CompositorChain::getNumCompositors; -%ignore Ogre::CompositorChain::getCompositor(size_t) const; -%ignore Ogre::CompositorChain::getCompositors; -%template(CompositorInstanceList) std::vector; -%include "OgreCompositorChain.h" -%ignore Ogre::RenderQueueGroup::getIterator; -%include "OgreRenderQueueSortingGrouping.h" -%ignore Ogre::SceneManager::getCameraIterator; // deprecated -%ignore Ogre::SceneManager::getAnimationIterator; -%ignore Ogre::SceneManager::getAnimationStateIterator; -%ignore Ogre::SceneManager::getMovableObjectIterator; -%ignore Ogre::SceneManager::getShadowTextureCount; -%ignore Ogre::SceneManager::getShadowTextureConfigIterator; -%newobject Ogre::SceneManager::createRayQuery(const Ray&, uint32 mask); -%newobject Ogre::SceneManager::createRayQuery(const Ray&); -%rename(SceneManager_Listener) Ogre::SceneManager::Listener; -%template(MovableObjectMap) std::map; -%template(CameraMap) std::map; -%include "OgreSceneManager.h" -%include "OgreDefaultDebugDrawer.h" -%include "OgreConfigDialog.h" -%template(RenderSystemList) std::vector; -%ignore Ogre::Root::createSceneManager(uint16); -%ignore Ogre::Root::createSceneManager(uint16, const String&); -%ignore Ogre::Root::getMovableObjectFactoryIterator; -%include "OgreRoot.h" -// dont wrap: platform specific -// %include "OgreWindowEventUtilities.h" -// %include "OgreTimer.h" -// dont wrap: not useful in high level languages -// %include "OgreRadixSort.h" -// %include "OgreString.h" -// %include "OgreStringConverter.h" -// %include "OgreProfiler.h" diff --git a/OgreMain/include/OgreAlignedAllocator.h b/OgreMain/include/OgreAlignedAllocator.h deleted file mode 100644 index 728cfdf0876..00000000000 --- a/OgreMain/include/OgreAlignedAllocator.h +++ /dev/null @@ -1,129 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __AlignedAllocator_H__ -#define __AlignedAllocator_H__ - -#include -#include "OgrePlatform.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - - /** \addtogroup General - * @{ - */ - - /** Class to provide aligned memory allocate functionality. - - All SIMD processing are friendly with aligned memory, and some SIMD routines - are designed for working with aligned memory only. If the data are intended to - use SIMD processing, it's need to be aligned for better performance boost. - In additional, most time cache boundary aligned data also lead to better - performance even if didn't used SIMD processing. So this class provides a couple - of functions for allocate aligned memory. - @par - Anyways, in general, you don't need to use this class directly, Ogre internally - will take care with most SIMD and cache friendly optimisation if possible. - @par - This isn't a "one-step" optimisation, there are a lot of underlying work to - achieve performance boost. If you didn't know what are you doing or what there - are going, just ignore this class. - @note - This class intended to use by advanced user only. - */ - class _OgreExport AlignedMemory - { - public: - /** Allocate memory with given alignment. - @param - size The size of memory need to allocate. - @param - alignment The alignment of result pointer, must be power of two - and in range [1, 128]. - @return - The allocated memory pointer. - @par - On failure, exception will be throw. - */ - static DECL_MALLOC void* allocate(size_t size, size_t alignment); - - /** Allocate memory with default platform dependent alignment. - - The default alignment depend on target machine, this function - guarantee aligned memory according with SIMD processing and - cache boundary friendly. - @param - size The size of memory need to allocate. - @return - The allocated memory pointer. - @par - On failure, exception will be throw. - */ - static DECL_MALLOC void* allocate(size_t size); - - /** Deallocate memory that allocated by this class. - @param - p Pointer to the memory allocated by this class or NULL pointer. - @par - On NULL pointer, nothing happen. - */ - static void deallocate(void* p); - }; - - /// STL compatible wrapper for @ref AlignedMemory - template - struct AlignedAllocator : public std::allocator - { - AlignedAllocator() : std::allocator() {} - - template - AlignedAllocator(const AlignedAllocator& other) {}; - - template - struct rebind { using other = AlignedAllocator; }; - - T* allocate(size_t n) { - return static_cast(AlignedMemory::allocate(n * sizeof(T), Alignment)); - } - T* allocate(size_t n, const void* hint) { // deprecated in C++17 - return static_cast(AlignedMemory::allocate(n * sizeof(T), Alignment)); - } - - void deallocate(T* p, size_t /*n*/) { - AlignedMemory::deallocate(p); - } - }; - /** @} */ - /** @} */ - -} - -#endif // __AlignedAllocator_H__ diff --git a/OgreMain/include/OgreAnimable.h b/OgreMain/include/OgreAnimable.h deleted file mode 100644 index c171097a1da..00000000000 --- a/OgreMain/include/OgreAnimable.h +++ /dev/null @@ -1,263 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ANIMABLE_H__ -#define __ANIMABLE_H__ - -#include "OgrePrerequisites.h" -#include "OgreCommon.h" -#include "OgreVector.h" -#include "OgreColourValue.h" -#include "OgreStringVector.h" -#include "OgreException.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - class Any; - - /** \addtogroup Core - * @{ - */ - - /** \addtogroup Animation - * @{ - */ - - /** Defines an object property which is animable, i.e. may be keyframed. - - Animable properties are those which can be altered over time by a - predefined keyframe sequence. They may be set directly, or they may - be modified from their existing state (common if multiple animations - are expected to apply at once). Implementors of this interface are - expected to override the 'setValue', 'setCurrentStateAsBaseValue' and - 'applyDeltaValue' methods appropriate to the type in question, and to - initialise the type. - @par - AnimableValue instances are accessible through any class which extends - AnimableObject in order to expose it's animable properties. - @note - This class is an instance of the Adapter pattern, since it generalises - access to a particular property. Whilst it could have been templated - such that the type which was being referenced was compiled in, this would - make it more difficult to aggregated generically, and since animations - are often comprised of multiple properties it helps to be able to deal - with all values through a single class. - */ - class _OgreExport AnimableValue : public AnimableAlloc - { - public: - /// The type of the value being animated - enum ValueType - { - INT, - REAL, - VECTOR2, - VECTOR3, - VECTOR4, - QUATERNION, - COLOUR, - RADIAN - }; - protected: - /// Value type - ValueType mType; - - /// Base value data - union - { - int mBaseValueInt; - Real mBaseValueReal[4]; - }; - - /// Internal method to set a value as base - virtual void setAsBaseValue(int val) { mBaseValueInt = val; } - /// Internal method to set a value as base - virtual void setAsBaseValue(Real val) { mBaseValueReal[0] = val; } - /// Internal method to set a value as base - virtual void setAsBaseValue(const Vector2& val) - { memcpy(mBaseValueReal, val.ptr(), sizeof(Real)*2); } - /// Internal method to set a value as base - virtual void setAsBaseValue(const Vector3& val) - { memcpy(mBaseValueReal, val.ptr(), sizeof(Real)*3); } - /// Internal method to set a value as base - virtual void setAsBaseValue(const Vector4& val) - { memcpy(mBaseValueReal, val.ptr(), sizeof(Real)*4); } - /// Internal method to set a value as base - virtual void setAsBaseValue(const Quaternion& val) - { memcpy(mBaseValueReal, val.ptr(), sizeof(Real)*4); } - /// Internal method to set a value as base - virtual void setAsBaseValue(const Any& val); - /// Internal method to set a value as base - virtual void setAsBaseValue(const ColourValue& val) - { - mBaseValueReal[0] = val.r; - mBaseValueReal[1] = val.g; - mBaseValueReal[2] = val.b; - mBaseValueReal[3] = val.a; - } - /// Internal method to set a value as base - virtual void setAsBaseValue(const Radian& val) - { - mBaseValueReal[0] = val.valueRadians(); - } - /// Internal method to set a value as base - virtual void setAsBaseValue(const Degree& val) - { - mBaseValueReal[0] = val.valueRadians(); - } - - - public: - AnimableValue(ValueType t) : mType(t) {} - virtual ~AnimableValue() {} - - /// Gets the value type of this animable value - ValueType getType(void) const { return mType; } - - /// Sets the current state as the 'base' value; used for delta animation - virtual void setCurrentStateAsBaseValue(void) = 0; - - /// Set value - virtual void setValue(int) { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "", ""); - } - /// Set value - virtual void setValue(Real) { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "", ""); - } - /// Set value - virtual void setValue(const Vector2&) { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "", ""); - } - /// Set value - virtual void setValue(const Vector3&) { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "", ""); - } - /// Set value - virtual void setValue(const Vector4&) { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "", ""); - } - /// Set value - virtual void setValue(const Quaternion&) { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "", ""); - } - /// Set value - virtual void setValue(const ColourValue&) { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "", ""); - } - /// Set value - virtual void setValue(const Radian&) { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "", ""); - } - /// Set value - void setValue(const Degree& val) { setValue(Radian(val)); } - /// Set value - virtual void setValue(const Any& val); - - // reset to base value - virtual void resetToBaseValue(void); - - /// Apply delta value - virtual void applyDeltaValue(int) { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "", ""); - } - /// Set value - virtual void applyDeltaValue(Real) { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "", ""); - } - /// Apply delta value - virtual void applyDeltaValue(const Vector2&) { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "", ""); - } - /// Apply delta value - virtual void applyDeltaValue(const Vector3&) { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "", ""); - } - /// Apply delta value - virtual void applyDeltaValue(const Vector4&) { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "", ""); - } - /// Apply delta value - virtual void applyDeltaValue(const Quaternion&) { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "", ""); - } - /// Apply delta value - virtual void applyDeltaValue(const ColourValue&) { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "", ""); - } - /// Apply delta value - void applyDeltaValue(const Degree& val) { applyDeltaValue(Radian(val)); } - /// Apply delta value - virtual void applyDeltaValue(const Radian&) { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "", ""); - } - /// Apply delta value - virtual void applyDeltaValue(const Any& val); - - - }; - - /** Defines an interface to classes which have one or more AnimableValue - instances to expose. - */ - class _OgreExport AnimableObject - { - public: - AnimableObject() {} - virtual ~AnimableObject() {} - - /** Gets a list of animable value names for this object. */ - virtual const StringVector& getAnimableValueNames(void) const - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Animable value list not implemented"); - } - - /** Create a reference-counted AnimableValuePtr for the named value. - - You can use the returned object to animate a value on this object, - using AnimationTrack. Subclasses must override this if they wish - to support animation of their values. - */ - virtual AnimableValuePtr createAnimableValue(const String& valueName) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "No animable value named '" + valueName + "' present"); - } - - - - }; - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreAnimation.h b/OgreMain/include/OgreAnimation.h deleted file mode 100644 index 0a4fb45168c..00000000000 --- a/OgreMain/include/OgreAnimation.h +++ /dev/null @@ -1,544 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Animation_H__ -#define __Animation_H__ - -#include "OgrePrerequisites.h" -#include "OgreIteratorWrapper.h" -#include "OgreAnimationTrack.h" -#include "OgreAnimationState.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - - /** \addtogroup Animation - * @{ - */ - - class Animation; - - /** An animation container interface, which allows generic access to sibling animations. - - Because Animation instances can be held by different kinds of classes, and - there are sometimes instances when you need to reference other Animation - instances within the same container, this class allows generic access to - named animations within that container, whatever it may be. - */ - class _OgreExport AnimationContainer - { - public: - virtual ~AnimationContainer() {} - - /** Gets the number of animations in this container. */ - virtual unsigned short getNumAnimations(void) const = 0; - - /** Retrieve an animation by index. */ - virtual Animation* getAnimation(unsigned short index) const = 0; - - /** Retrieve an animation by name. */ - virtual Animation* getAnimation(const String& name) const = 0; - - /** Create a new animation with a given length owned by this container. */ - virtual Animation* createAnimation(const String& name, Real length) = 0; - - /** Returns whether this object contains the named animation. */ - virtual bool hasAnimation(const String& name) const = 0; - - /** Removes an Animation from this container. */ - virtual void removeAnimation(const String& name) = 0; - - }; - /** An animation sequence. - - This class defines the interface for a sequence of animation, whether that - be animation of a mesh, a path along a spline, or possibly more than one - type of animation in one. An animation is made up of many 'tracks', which are - the more specific types of animation. - @par - You should not create these animations directly. They will be created via a parent - object which owns the animation, e.g. Skeleton. - */ - class _OgreExport Animation : public AnimationAlloc - { - - public: - /** The types of animation interpolation available. */ - enum InterpolationMode : uint8 - { - /** Values are interpolated along straight lines. */ - IM_LINEAR, - /** Values are interpolated along a spline, resulting in smoother changes in direction. */ - IM_SPLINE - }; - - /** The types of rotational interpolation available. */ - enum RotationInterpolationMode : uint8 - { - /** Values are interpolated linearly. This is faster but does not - necessarily give a completely accurate result. - */ - RIM_LINEAR, - /** Values are interpolated spherically. This is more accurate but - has a higher cost. - */ - RIM_SPHERICAL - }; - /** You should not use this constructor directly, use the parent object such as Skeleton instead. - @param name The name of the animation, should be unique within it's parent (e.g. Skeleton) - @param length The length of the animation in seconds. - */ - Animation(const String& name, Real length); - virtual ~Animation(); - - /** Gets the name of this animation. */ - const String& getName(void) const; - - /** Gets the total length of the animation. */ - Real getLength(void) const; - - /** Sets the length of the animation. - @note Changing the length of an animation may invalidate existing AnimationState - instances which will need to be recreated. - */ - void setLength(Real len); - - /** Creates a NodeAnimationTrack for animating a Node. - @param handle Handle to give the track, used for accessing the track later. - Must be unique within this Animation. - */ - NodeAnimationTrack* createNodeTrack(unsigned short handle); - - /** Creates a VertexAnimationTrack for animating vertex position data. - @param handle Handle to give the track, used for accessing the track later. - Must be unique within this Animation, and is used to identify the target. For example - when applied to a Mesh, the handle must reference the index of the geometry being - modified; 0 for the shared geometry, and 1+ for SubMesh geometry with the same index-1. - @param animType Either morph or pose animation, - */ - VertexAnimationTrack* createVertexTrack(unsigned short handle, VertexAnimationType animType); - - /** Creates a new AnimationTrack automatically associated with a Node. - - This method creates a standard AnimationTrack, but also associates it with a - target Node which will receive all keyframe effects. - @param handle Numeric handle to give the track, used for accessing the track later. - Must be unique within this Animation. - @param node A pointer to the Node object which will be affected by this track - */ - NodeAnimationTrack* createNodeTrack(unsigned short handle, Node* node); - - /** Creates a NumericAnimationTrack and associates it with an animable. - @param handle Handle to give the track, used for accessing the track later. - @param anim Animable object link - Must be unique within this Animation. - */ - NumericAnimationTrack* createNumericTrack(unsigned short handle, - const AnimableValuePtr& anim); - - /** Creates a VertexAnimationTrack and associates it with VertexData. - @param handle Handle to give the track, used for accessing the track later. - @param data VertexData object link - @param animType The animation type - Must be unique within this Animation. - */ - VertexAnimationTrack* createVertexTrack(unsigned short handle, - VertexData* data, VertexAnimationType animType); - - /** Gets the number of NodeAnimationTrack objects contained in this animation. */ - unsigned short getNumNodeTracks(void) const; - - /** Gets a node track by it's handle. */ - NodeAnimationTrack* getNodeTrack(unsigned short handle) const; - - /** Does a track exist with the given handle? */ - bool hasNodeTrack(unsigned short handle) const; - - /** Gets the number of NumericAnimationTrack objects contained in this animation. */ - unsigned short getNumNumericTracks(void) const; - - /** Gets a numeric track by it's handle. */ - NumericAnimationTrack* getNumericTrack(unsigned short handle) const; - - /** Does a track exist with the given handle? */ - bool hasNumericTrack(unsigned short handle) const; - - /** Gets the number of VertexAnimationTrack objects contained in this animation. */ - unsigned short getNumVertexTracks(void) const; - - /** Gets a Vertex track by it's handle. */ - VertexAnimationTrack* getVertexTrack(unsigned short handle) const; - - /** Does a track exist with the given handle? */ - bool hasVertexTrack(unsigned short handle) const; - - /** Destroys the node track with the given handle. */ - void destroyNodeTrack(unsigned short handle); - - /** Destroys the numeric track with the given handle. */ - void destroyNumericTrack(unsigned short handle); - - /** Destroys the Vertex track with the given handle. */ - void destroyVertexTrack(unsigned short handle); - - /** Removes and destroys all tracks making up this animation. */ - void destroyAllTracks(void); - - /** Removes and destroys all tracks making up this animation. */ - void destroyAllNodeTracks(void); - /** Removes and destroys all tracks making up this animation. */ - void destroyAllNumericTracks(void); - /** Removes and destroys all tracks making up this animation. */ - void destroyAllVertexTracks(void); - - /** Applies an animation given a specific time point and weight. - - Where you have associated animation tracks with objects, you can easily apply - an animation to those objects by calling this method. - @param timePos The time position in the animation to apply. - @param weight The influence to give to this track, 1.0 for full influence, less to blend with - other animations. - @param scale The scale to apply to translations and scalings, useful for - adapting an animation to a different size target. - */ - void apply(Real timePos, Real weight = 1.0, Real scale = 1.0f); - - /** Applies all node tracks given a specific time point and weight to the specified node. - - It does not consider the actual node tracks are attached to. - As such, it resembles the apply method for a given skeleton (see below). - @param node - @param timePos The time position in the animation to apply. - @param weight The influence to give to this track, 1.0 for full influence, less to blend with - other animations. - @param scale The scale to apply to translations and scalings, useful for - adapting an animation to a different size target. - */ - void applyToNode(Node* node, Real timePos, Real weight = 1.0, Real scale = 1.0f); - - /** Applies all node tracks given a specific time point and weight to a given skeleton. - - Where you have associated animation tracks with Node objects, you can easily apply - an animation to those nodes by calling this method. - @param skeleton - @param timePos The time position in the animation to apply. - @param weight The influence to give to this track, 1.0 for full influence, less to blend with - other animations. - @param scale The scale to apply to translations and scalings, useful for - adapting an animation to a different size target. - */ - void apply(Skeleton* skeleton, Real timePos, Real weight = 1.0, Real scale = 1.0f); - - /** Applies all node tracks given a specific time point and weight to a given skeleton. - - Where you have associated animation tracks with Node objects, you can easily apply - an animation to those nodes by calling this method. - @param skeleton - @param timePos The time position in the animation to apply. - @param weight The influence to give to this track, 1.0 for full influence, less to blend with - other animations. - @param blendMask The influence array defining additional per bone weights. These will - be modulated with the weight factor. - @param scale The scale to apply to translations and scalings, useful for - adapting an animation to a different size target. - */ - void apply(Skeleton* skeleton, Real timePos, float weight, - const AnimationState::BoneBlendMask* blendMask, Real scale); - - /** Applies all vertex tracks given a specific time point and weight to a given entity. - @param entity The Entity to which this animation should be applied - @param timePos The time position in the animation to apply. - @param weight The weight at which the animation should be applied - (only affects pose animation) - @param software Whether to populate the software morph vertex data - @param hardware Whether to populate the hardware morph vertex data - */ - void apply(Entity* entity, Real timePos, Real weight, bool software, - bool hardware); - - /** Applies all numeric tracks given a specific time point and weight to the specified animable value. - - It does not applies to actual attached animable values but rather uses all tracks for a single animable value. - @param anim - @param timePos The time position in the animation to apply. - @param weight The influence to give to this track, 1.0 for full influence, less to blend with - other animations. - @param scale The scale to apply to translations and scalings, useful for - adapting an animation to a different size target. - */ - void applyToAnimable(const AnimableValuePtr& anim, Real timePos, Real weight = 1.0, Real scale = 1.0f); - - /** Applies all vertex tracks given a specific time point and weight to the specified vertex data. - - It does not apply to the actual attached vertex data but rather uses all tracks for a given vertex data. - @param data - @param timePos The time position in the animation to apply. - @param weight The influence to give to this track, 1.0 for full influence, less to blend with - other animations. - */ - void applyToVertexData(VertexData* data, Real timePos, float weight = 1.0); - - /** Tells the animation how to interpolate between keyframes. - - By default, animations normally interpolate linearly between keyframes. This is - fast, but when animations include quick changes in direction it can look a little - unnatural because directions change instantly at keyframes. An alternative is to - tell the animation to interpolate along a spline, which is more expensive in terms - of calculation time, but looks smoother because major changes in direction are - distributed around the keyframes rather than just at the keyframe. - @par - You can also change the default animation behaviour by calling - Animation::setDefaultInterpolationMode. - */ - void setInterpolationMode(InterpolationMode im); - - /** Gets the current interpolation mode of this animation. - - See setInterpolationMode for more info. - */ - InterpolationMode getInterpolationMode(void) const; - /** Tells the animation how to interpolate rotations. - - By default, animations interpolate linearly between rotations. This - is fast but not necessarily completely accurate. If you want more - accurate interpolation, use spherical interpolation, but be aware - that it will incur a higher cost. - @par - You can also change the default rotation behaviour by calling - Animation::setDefaultRotationInterpolationMode. - */ - void setRotationInterpolationMode(RotationInterpolationMode im); - - /** Gets the current rotation interpolation mode of this animation. - - See setRotationInterpolationMode for more info. - */ - RotationInterpolationMode getRotationInterpolationMode(void) const; - - // Methods for setting the defaults - /** Sets the default animation interpolation mode. - - Every animation created after this option is set will have the new interpolation - mode specified. You can also change the mode per animation by calling the - setInterpolationMode method on the instance in question. - */ - static void setDefaultInterpolationMode(InterpolationMode im); - - /** Gets the default interpolation mode for all animations. */ - static InterpolationMode getDefaultInterpolationMode(void); - - /** Sets the default rotation interpolation mode. - - Every animation created after this option is set will have the new interpolation - mode specified. You can also change the mode per animation by calling the - setInterpolationMode method on the instance in question. - */ - static void setDefaultRotationInterpolationMode(RotationInterpolationMode im); - - /** Gets the default rotation interpolation mode for all animations. */ - static RotationInterpolationMode getDefaultRotationInterpolationMode(void); - - typedef std::map NodeTrackList; - typedef ConstMapIterator NodeTrackIterator; - - typedef std::map NumericTrackList; - typedef ConstMapIterator NumericTrackIterator; - - typedef std::map VertexTrackList; - typedef ConstMapIterator VertexTrackIterator; - - /// Fast access to NON-UPDATEABLE node track list - const NodeTrackList& _getNodeTrackList(void) const; - - /// @deprecated use _getNodeTrackList - OGRE_DEPRECATED NodeTrackIterator getNodeTrackIterator(void) const - { return NodeTrackIterator(mNodeTrackList.begin(), mNodeTrackList.end()); } - - /// Fast access to NON-UPDATEABLE numeric track list - const NumericTrackList& _getNumericTrackList(void) const; - - /// @deprecated use _getNumericTrackList - OGRE_DEPRECATED NumericTrackIterator getNumericTrackIterator(void) const - { return NumericTrackIterator(mNumericTrackList.begin(), mNumericTrackList.end()); } - - /// Fast access to NON-UPDATEABLE Vertex track list - const VertexTrackList& _getVertexTrackList(void) const; - - /// @deprecated use _getVertexTrackList - OGRE_DEPRECATED VertexTrackIterator getVertexTrackIterator(void) const - { return VertexTrackIterator(mVertexTrackList.begin(), mVertexTrackList.end()); } - - /** Optimise an animation by removing unnecessary tracks and keyframes. - - When you export an animation, it is possible that certain tracks - have been keyframed but actually don't include anything useful - the - keyframes include no transformation. These tracks can be completely - eliminated from the animation and thus speed up the animation. - In addition, if several keyframes in a row have the same value, - then they are just adding overhead and can be removed. - @note - Since track-less and identity track has difference behavior for - accumulate animation blending if corresponding track presenting at - other animation that is non-identity, and in normally this method - didn't known about the situation of other animation, it can't deciding - whether or not discards identity tracks. So there have a parameter - allow you choose what you want, in case you aren't sure how to do that, - you should use Skeleton::optimiseAllAnimations instead. - @param - discardIdentityNodeTracks If true, discard identity node tracks. - */ - void optimise(bool discardIdentityNodeTracks = true); - - /// A list of track handles - typedef std::set TrackHandleList; - - /** Internal method for collecting identity node tracks. - - This method remove non-identity node tracks form the track handle list. - @param - tracks A list of track handle of non-identity node tracks, where this - method will remove non-identity node track handles. - */ - void _collectIdentityNodeTracks(TrackHandleList& tracks) const; - - /** Internal method for destroy given node tracks. - */ - void _destroyNodeTracks(const TrackHandleList& tracks); - - /** Clone this animation. - @note - The pointer returned from this method is the only one recorded, - thus it is up to the caller to arrange for the deletion of this - object. - */ - Animation* clone(const String& newName) const OGRE_NODISCARD; - - /** Internal method used to tell the animation that keyframe list has been - changed, which may cause it to rebuild some internal data */ - void _keyFrameListChanged(void) { mKeyFrameTimesDirty = true; } - - /** Internal method used to convert time position to time index object. - @note - The time index returns by this function are associated with state of - the animation object, if the animation object altered (e.g. create/remove - keyframe or track), all related time index will invalidated. - @param timePos The time position. - @return The time index object which contains wrapped time position (in - relation to the whole animation sequence) and lower bound index of - global keyframe time list. - */ - TimeIndex _getTimeIndex(Real timePos) const; - - /** Sets a base keyframe which for the skeletal / pose keyframes - in this animation. - - Skeletal and pose animation keyframes are expressed as deltas from a - given base state. By default, that is the binding setup of the skeleton, - or the object space mesh positions for pose animation. However, sometimes - it is useful for animators to create animations with a different starting - pose, because that's more convenient, and the animation is designed to - simply be added to the existing animation state and not globally averaged - with other animations (this is always the case with pose animations, but - is activated for skeletal animations via ANIMBLEND_CUMULATIVE). - @par - In order for this to work, the keyframes need to be 're-based' against - this new starting state, for example by treating the first keyframe as - the reference point (and therefore representing no change). This can - be achieved by applying the inverse of this reference keyframe against - all other keyframes. Since this fundamentally changes the animation, - this method just marks the animation as requiring this rebase, which - is performed at the next Animation 'apply' call. This is to allow the - Animation to be re-saved with this flag set, but without having altered - the keyframes yet, so no data is lost unintentionally. If you wish to - save the animation after the adjustment has taken place, you can - (@see _applyBaseKeyFrame) - @param useBaseKeyFrame Whether a base keyframe should be used - @param keyframeTime The time corresponding to the base keyframe, if any - @param baseAnimName Optionally a different base animation (must contain the same tracks) - */ - void setUseBaseKeyFrame(bool useBaseKeyFrame, Real keyframeTime = 0.0f, const String& baseAnimName = BLANKSTRING); - /** Whether a base keyframe is being used for this Animation. */ - bool getUseBaseKeyFrame() const; - /** If a base keyframe is being used, the time of that keyframe. */ - Real getBaseKeyFrameTime() const; - /** If a base keyframe is being used, the Animation that provides that keyframe. */ - const String& getBaseKeyFrameAnimationName() const; - - /// Internal method to adjust keyframes relative to a base keyframe (@see setUseBaseKeyFrame) */ - void _applyBaseKeyFrame(); - - void _notifyContainer(AnimationContainer* c); - /** Retrieve the container of this animation. */ - AnimationContainer* getContainer(); - - private: - /// Node tracks, indexed by handle - NodeTrackList mNodeTrackList; - /// Numeric tracks, indexed by handle - NumericTrackList mNumericTrackList; - /// Vertex tracks, indexed by handle - VertexTrackList mVertexTrackList; - String mName; - - Real mLength; - - InterpolationMode mInterpolationMode; - RotationInterpolationMode mRotationInterpolationMode; - - /// Dirty flag indicate that keyframe time list need to rebuild - mutable bool mKeyFrameTimesDirty; - bool mUseBaseKeyFrame; - - static InterpolationMode msDefaultInterpolationMode; - static RotationInterpolationMode msDefaultRotationInterpolationMode; - - /// Global keyframe time list used to search global keyframe index. - typedef std::vector KeyFrameTimeList; - mutable KeyFrameTimeList mKeyFrameTimes; - Real mBaseKeyFrameTime; - String mBaseKeyFrameAnimationName; - AnimationContainer* mContainer; - - void optimiseNodeTracks(bool discardIdentityTracks); - void optimiseVertexTracks(void); - - /// Internal method to build global keyframe time list - void buildKeyFrameTimeList(void) const; - }; - - /** @} */ - /** @} */ -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif // __Animation_H__ - diff --git a/OgreMain/include/OgreAnimationState.h b/OgreMain/include/OgreAnimationState.h deleted file mode 100644 index 898879d21b5..00000000000 --- a/OgreMain/include/OgreAnimationState.h +++ /dev/null @@ -1,330 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __AnimationState_H__ -#define __AnimationState_H__ - -#include "OgrePrerequisites.h" - -#include "OgreCommon.h" -#include "OgreController.h" -#include "OgreControllerManager.h" -#include "Threading/OgreThreadHeaders.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - template class MapIterator; - template class ConstMapIterator; - template class ConstVectorIterator; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Animation - * @{ - */ - - /** Represents the state of an animation and the weight of its influence. - - Other classes can hold instances of this class to store the state of any animations - they are using. - */ - class _OgreExport AnimationState : public AnimationAlloc - { - public: - - /// Typedef for an array of float values used as a bone blend mask - typedef std::vector BoneBlendMask; - - /** Normal constructor with all params supplied - @param - animName The name of this state. - @param - parent The parent AnimationStateSet that this state will belong to. - @param - timePos The position, in seconds, where this state will begin. - @param - length The length, in seconds, of this animation state. - @param - weight Weight to apply the animation state with. - @param - enabled Whether the animation state is enabled. - */ - AnimationState(const String& animName, AnimationStateSet *parent, - Real timePos, Real length, Real weight = 1.0, bool enabled = false); - /// Constructor to copy from an existing state with new parent - AnimationState(AnimationStateSet* parent, const AnimationState &rhs); - - /// Gets the name of the animation to which this state applies - const String& getAnimationName() const; - /// Gets the time position for this animation - Real getTimePosition(void) const; - /// Sets the time position for this animation - void setTimePosition(Real timePos); - /// Gets the total length of this animation (may be shorter than whole animation) - Real getLength() const; - /// Sets the total length of this animation (may be shorter than whole animation) - void setLength(Real len); - /// Gets the weight (influence) of this animation - Real getWeight(void) const; - /// Sets the weight (influence) of this animation - void setWeight(Real weight); - /** Modifies the time position, adjusting for animation length - @param offset The amount of time, in seconds, to extend the animation. - - This method loops at the edges if animation looping is enabled. - */ - void addTime(Real offset); - - /// Returns true if the animation has reached the end and is not looping - bool hasEnded(void) const; - - /// Returns true if this animation is currently enabled - bool getEnabled(void) const; - /// Sets whether this animation is enabled - void setEnabled(bool enabled); - - /// Equality operator - bool operator==(const AnimationState& rhs) const; - /// Inequality operator - bool operator!=(const AnimationState& rhs) const; - - /** Sets whether or not an animation loops at the start and end of - the animation if the time continues to be altered. - */ - void setLoop(bool loop) { mLoop = loop; } - /// Gets whether or not this animation loops - bool getLoop(void) const { return mLoop; } - - /** Copies the states from another animation state, preserving the animation name - (unlike operator=) but copying everything else. - @param animState Reference to animation state which will use as source. - */ - void copyStateFrom(const AnimationState& animState); - - /// Get the parent animation state set - AnimationStateSet* getParent(void) const { return mParent; } - - /** @brief Create a new blend mask with the given number of entries - * - * In addition to assigning a single weight value to a skeletal animation, - * it may be desirable to assign animation weights per bone using a 'blend mask'. - * - * @param blendMaskSizeHint - * The number of bones of the skeleton owning this AnimationState. - * @param initialWeight - * The value all the blend mask entries will be initialised with (negative to skip initialisation) - */ - void createBlendMask(size_t blendMaskSizeHint, float initialWeight = 1.0f); - /// Destroy the currently set blend mask - void destroyBlendMask(); - - /** @brief Set the blend mask - * - * @par The size of the array should match the number of entries the - * blend mask was created with. - * - * @par Stick to the setBlendMaskEntry method if you don't know exactly what you're doing. - */ - void _setBlendMask(const BoneBlendMask* blendMask); - /// Get the current blend mask - const BoneBlendMask* getBlendMask() const {return &mBlendMask;} - /// Return whether there is currently a valid blend mask set - bool hasBlendMask() const {return !mBlendMask.empty();} - /// Set the weight for the bone identified by the given handle - void setBlendMaskEntry(size_t boneHandle, float weight); - /// Get the weight for the bone identified by the given handle - inline float getBlendMaskEntry(size_t boneHandle) const - { - assert(mBlendMask.size() > boneHandle); - return mBlendMask[boneHandle]; - } - private: - /** @brief Set the blend mask data (might be dangerous) - * - * @par The size of the array should match the number of entries the - * blend mask was created with. - * - * @par Stick to the setBlendMaskEntry method if you don't know exactly what you're doing. - */ - void _setBlendMaskData(const float* blendMaskData); - /// The blend mask (containing per bone weights) - BoneBlendMask mBlendMask; - - String mAnimationName; - AnimationStateSet* mParent; - Real mTimePos; - Real mLength; - Real mWeight; - bool mEnabled; - bool mLoop; - - }; - - // A map of animation states - typedef std::map AnimationStateMap; - typedef MapIterator AnimationStateIterator; - typedef ConstMapIterator ConstAnimationStateIterator; - // A list of enabled animation states - typedef std::list EnabledAnimationStateList; - typedef ConstVectorIterator ConstEnabledAnimationStateIterator; - - /** Class encapsulating a set of AnimationState objects. - */ - class _OgreExport AnimationStateSet : public AnimationAlloc - { - public: - /// Mutex, public for external locking if needed - OGRE_AUTO_MUTEX; - /// Create a blank animation state set - AnimationStateSet(); - /// Create an animation set by copying the contents of another - AnimationStateSet(const AnimationStateSet& rhs); - - ~AnimationStateSet(); - - /** Create a new AnimationState instance. - @param animName The name of the animation - @param timePos Starting time position - @param length Length of the animation to play - @param weight Weight to apply the animation with - @param enabled Whether the animation is enabled - */ - AnimationState* createAnimationState(const String& animName, - Real timePos, Real length, Real weight = 1.0, bool enabled = false); - /// Get an animation state by the name of the animation - AnimationState* getAnimationState(const String& name) const; - /// Tests if state for the named animation is present - bool hasAnimationState(const String& name) const; - /// Remove animation state with the given name - void removeAnimationState(const String& name); - /// Remove all animation states - void removeAllAnimationStates(void); - - /** Get an iterator over all the animation states in this set. - @deprecated use getAnimationStates() - */ - AnimationStateIterator getAnimationStateIterator(void); - /** Get an iterator over all the animation states in this set. - @deprecated use getAnimationStates() - */ - OGRE_DEPRECATED ConstAnimationStateIterator getAnimationStateIterator(void) const; - - /** Get all the animation states in this set. - @note - This method is not threadsafe, - you will need to manually lock the public mutex on this - class to ensure thread safety if you need it. - */ - const AnimationStateMap& getAnimationStates() const { - return mAnimationStates; - } - - /// Copy the state of any matching animation states from this to another - void copyMatchingState(AnimationStateSet* target) const; - /// Set the dirty flag and dirty frame number on this state set - void _notifyDirty(void); - /// Get the latest animation state been altered frame number - unsigned long getDirtyFrameNumber(void) const { return mDirtyFrameNumber; } - - /// Internal method respond to enable/disable an animation state - void _notifyAnimationStateEnabled(AnimationState* target, bool enabled); - /// Tests if exists enabled animation state in this set - bool hasEnabledAnimationState(void) const { return !mEnabledAnimationStates.empty(); } - /** Get an iterator over all the enabled animation states in this set - @deprecated use getEnabledAnimationStates() - */ - OGRE_DEPRECATED ConstEnabledAnimationStateIterator getEnabledAnimationStateIterator(void) const; - - /** Get an iterator over all the enabled animation states in this set - @note - The iterator returned from this method is not threadsafe, - you will need to manually lock the public mutex on this - class to ensure thread safety if you need it. - */ - const EnabledAnimationStateList& getEnabledAnimationStates() const { - return mEnabledAnimationStates; - } - - private: - unsigned long mDirtyFrameNumber; - AnimationStateMap mAnimationStates; - EnabledAnimationStateList mEnabledAnimationStates; - - }; - - /** ControllerValue wrapper class for AnimationState. - - In Azathoth and earlier, AnimationState was a ControllerValue but this - actually causes memory problems since Controllers delete their values - automatically when there are no further references to them, but AnimationState - is deleted explicitly elsewhere so this causes double-free problems. - This wrapper acts as a bridge and it is this which is destroyed automatically. - */ - class _OgreExport AnimationStateControllerValue : public ControllerValue - { - private: - AnimationState* mTargetAnimationState; - bool mAddTime; - public: - /// @deprecated use create instead - AnimationStateControllerValue(AnimationState* targetAnimationState, bool addTime = false) - : mTargetAnimationState(targetAnimationState), mAddTime(addTime) {} - - /** - * create an instance of this class - * @param targetAnimationState - * @param addTime if true, increment time instead of setting to an absolute position - */ - static ControllerValueRealPtr create(AnimationState* targetAnimationState, bool addTime = false); - - /** ControllerValue implementation. */ - float getValue(void) const override - { - return mTargetAnimationState->getTimePosition() / mTargetAnimationState->getLength(); - } - - /** ControllerValue implementation. */ - void setValue(float value) override - { - if(mAddTime) - mTargetAnimationState->addTime(value); - else - mTargetAnimationState->setTimePosition(value * mTargetAnimationState->getLength()); - } - }; - - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreAnimationTrack.h b/OgreMain/include/OgreAnimationTrack.h deleted file mode 100644 index 65e92a24dfb..00000000000 --- a/OgreMain/include/OgreAnimationTrack.h +++ /dev/null @@ -1,559 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __AnimationTrack_H__ -#define __AnimationTrack_H__ - -#include "OgrePrerequisites.h" -#include "OgreHeaderPrefix.h" -#include "OgreSimpleSpline.h" -#include "OgreRotationalSpline.h" -#include "OgrePose.h" - -namespace Ogre -{ - class VertexPoseKeyFrame; - class KeyFrame; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Animation - * @{ - */ - /** Time index object used to search keyframe at the given position. - */ - class _OgreExport TimeIndex - { - private: - /** The time position (in relation to the whole animation sequence) - */ - Real mTimePos; - /** The global keyframe index (in relation to the whole animation sequence) - that used to convert to local keyframe index, or INVALID_KEY_INDEX which - means global keyframe index unavailable, and then slight slow method will - used to search local keyframe index. - */ - uint mKeyIndex; - - /** Indicate it's an invalid global keyframe index. - */ - static const uint INVALID_KEY_INDEX = (uint)-1; - - public: - /** Construct time index object by the given time position. - */ - TimeIndex(Real timePos) - : mTimePos(timePos) - , mKeyIndex(INVALID_KEY_INDEX) - { - } - - /** Construct time index object by the given time position and - global keyframe index. - @note In normally, you don't need to use this constructor directly, use - Animation::_getTimeIndex instead. - */ - TimeIndex(Real timePos, uint keyIndex) - : mTimePos(timePos) - , mKeyIndex(keyIndex) - { - } - - bool hasKeyIndex(void) const - { - return mKeyIndex != INVALID_KEY_INDEX; - } - - Real getTimePos(void) const - { - return mTimePos; - } - - uint getKeyIndex(void) const - { - return mKeyIndex; - } - }; - - /** A 'track' in an animation sequence, i.e. a sequence of keyframes which affect a - certain type of animable object. - - This class is intended as a base for more complete classes which will actually - animate specific types of object, e.g. a bone in a skeleton to affect - skeletal animation. An animation will likely include multiple tracks each of which - can be made up of many KeyFrame instances. Note that the use of tracks allows each animable - object to have it's own number of keyframes, i.e. you do not have to have the - maximum number of keyframes for all animable objects just to cope with the most - animated one. - - Since the most common animable object is a Node, there are options in this class for associating - the track with a Node which will receive keyframe updates automatically when the 'apply' method - is called. - - By default rotation is done using shortest-path algorithm. - It is possible to change this behaviour using - setUseShortestRotationPath() method. - */ - class _OgreExport AnimationTrack : public AnimationAlloc - { - public: - - /** Listener allowing you to override certain behaviour of a track, - for example to drive animation procedurally. - */ - class _OgreExport Listener - { - public: - virtual ~Listener() {} - - /** Get an interpolated keyframe for this track at the given time. - @return true if the KeyFrame was populated, false if not. - */ - virtual bool getInterpolatedKeyFrame(const AnimationTrack* t, const TimeIndex& timeIndex, KeyFrame* kf) = 0; - }; - - /// Constructor - AnimationTrack(Animation* parent, unsigned short handle); - - virtual ~AnimationTrack(); - - /** Get the handle associated with this track. */ - unsigned short getHandle(void) const { return mHandle; } - - /** Returns the number of keyframes in this animation. */ - size_t getNumKeyFrames(void) const { return mKeyFrames.size(); } - - /** Returns the KeyFrame at the specified index. */ - KeyFrame* getKeyFrame(size_t index) const { return mKeyFrames.at(index); } - - /** Gets the 2 KeyFrame objects which are active at the time given, and the blend value between them. - - At any point in time in an animation, there are either 1 or 2 keyframes which are 'active', - 1 if the time index is exactly on a keyframe, 2 at all other times i.e. the keyframe before - and the keyframe after. - @par - This method returns those keyframes given a time index, and also returns a parametric - value indicating the value of 't' representing where the time index falls between them. - E.g. if it returns 0, the time index is exactly on keyFrame1, if it returns 0.5 it is - half way between keyFrame1 and keyFrame2 etc. - @param timeIndex The time index. - @param keyFrame1 Pointer to a KeyFrame pointer which will receive the pointer to the - keyframe just before or at this time index. - @param keyFrame2 Pointer to a KeyFrame pointer which will receive the pointer to the - keyframe just after this time index. - @param firstKeyIndex Pointer to an unsigned short which, if supplied, will receive the - index of the 'from' keyframe in case the caller needs it. - @return Parametric value indicating how far along the gap between the 2 keyframes the timeIndex - value is, e.g. 0.0 for exactly at 1, 0.25 for a quarter etc. By definition the range of this - value is: 0.0 <= returnValue < 1.0 . - */ - float getKeyFramesAtTime(const TimeIndex& timeIndex, KeyFrame** keyFrame1, KeyFrame** keyFrame2, - unsigned short* firstKeyIndex = 0) const; - - /** Creates a new KeyFrame and adds it to this animation at the given time index. - - It is better to create KeyFrames in time order. - @param timePos The time from which this KeyFrame will apply. - */ - virtual KeyFrame* createKeyFrame(Real timePos); - - /** Removes a KeyFrame by it's index. */ - virtual void removeKeyFrame(unsigned short index); - - /** Removes all the KeyFrames from this track. */ - void removeAllKeyFrames(void); - - - /** Gets a KeyFrame object which contains the interpolated transforms at the time index specified. - - The KeyFrame objects held by this class are transformation snapshots at - discrete points in time. Normally however, you want to interpolate between these - keyframes to produce smooth movement, and this method allows you to do this easily. - In animation terminology this is called 'tweening'. - @param timeIndex The time (in relation to the whole animation sequence) - @param kf Keyframe object to store results - */ - virtual void getInterpolatedKeyFrame(const TimeIndex& timeIndex, KeyFrame* kf) const = 0; - - /** Applies an animation track to the designated target. - @param timeIndex The time position in the animation to apply. - @param weight The influence to give to this track, 1.0 for full influence, less to blend with - other animations. - @param scale The scale to apply to translations and scalings, useful for - adapting an animation to a different size target. - */ - virtual void apply(const TimeIndex& timeIndex, Real weight = 1.0, Real scale = 1.0f) = 0; - - /** Internal method used to tell the track that keyframe data has been - changed, which may cause it to rebuild some internal data. */ - virtual void _keyFrameDataChanged(void) const {} - - /** Method to determine if this track has any KeyFrames which are - doing anything useful - can be used to determine if this track - can be optimised out. - */ - virtual bool hasNonZeroKeyFrames(void) const { return true; } - - /** Optimise the current track by removing any duplicate keyframes. */ - virtual void optimise(void) {} - - /** Internal method to collect keyframe times, in unique, ordered format. */ - virtual void _collectKeyFrameTimes(std::vector& keyFrameTimes); - - /** Internal method to build keyframe time index map to translate global lower - bound index to local lower bound index. */ - virtual void _buildKeyFrameIndexMap(const std::vector& keyFrameTimes); - - /** Internal method to re-base the keyframes relative to a given keyframe. */ - virtual void _applyBaseKeyFrame(const KeyFrame* base); - - /** Set a listener for this track. */ - virtual void setListener(Listener* l) { mListener = l; } - - /** Returns the parent Animation object for this track. */ - Animation *getParent() const { return mParent; } - private: - /// Map used to translate global keyframe time lower bound index to local lower bound index - typedef std::vector KeyFrameIndexMap; - KeyFrameIndexMap mKeyFrameIndexMap; - - /// Create a keyframe implementation - must be overridden - virtual KeyFrame* createKeyFrameImpl(Real time) = 0; - protected: - typedef std::vector KeyFrameList; - KeyFrameList mKeyFrames; - Animation* mParent; - Listener* mListener; - unsigned short mHandle; - - /// Internal method for clone implementation - virtual void populateClone(AnimationTrack* clone) const; - }; - - /** Specialised AnimationTrack for dealing with generic animable values. - */ - class _OgreExport NumericAnimationTrack : public AnimationTrack - { - public: - /// Constructor, associates with an AnimableValue - NumericAnimationTrack(Animation* parent, unsigned short handle, - const AnimableValuePtr& target); - - /// @copydoc AnimationTrack::createKeyFrame - virtual NumericKeyFrame* createNumericKeyFrame(Real timePos); - - /// @copydoc AnimationTrack::getInterpolatedKeyFrame - void getInterpolatedKeyFrame(const TimeIndex& timeIndex, KeyFrame* kf) const override; - - /// @copydoc AnimationTrack::apply - void apply(const TimeIndex& timeIndex, Real weight = 1.0, Real scale = 1.0f) override; - - /** Applies an animation track to a given animable value. - @param anim The AnimableValue to which to apply the animation - @param timeIndex The time position in the animation to apply. - @param weight The influence to give to this track, 1.0 for full influence, less to blend with - other animations. - @param scale The scale to apply to translations and scalings, useful for - adapting an animation to a different size target. - */ - void applyToAnimable(const AnimableValuePtr& anim, const TimeIndex& timeIndex, - Real weight = 1.0, Real scale = 1.0f); - - /** Returns a pointer to the associated animable object (if any). */ - const AnimableValuePtr& getAssociatedAnimable(void) const { return mTargetAnim; } - - /** Sets the associated animable object which will be automatically - affected by calls to 'apply'. */ - void setAssociatedAnimable(const AnimableValuePtr& val) { mTargetAnim = val; } - - /** Returns the KeyFrame at the specified index. */ - NumericKeyFrame* getNumericKeyFrame(unsigned short index) const; - - /** Clone this track (internal use only) */ - NumericAnimationTrack* _clone(Animation* newParent) const; - - - private: - /// Target to animate - AnimableValuePtr mTargetAnim; - - /// @copydoc AnimationTrack::createKeyFrameImpl - KeyFrame* createKeyFrameImpl(Real time) override; - - - }; - - /** Specialised AnimationTrack for dealing with node transforms. - */ - class _OgreExport NodeAnimationTrack : public AnimationTrack - { - public: - /// Constructor - NodeAnimationTrack(Animation* parent, unsigned short handle); - /// Constructor, associates with a Node - NodeAnimationTrack(Animation* parent, unsigned short handle, - Node* targetNode); - /// Destructor - virtual ~NodeAnimationTrack(); - /// @copydoc AnimationTrack::createKeyFrame - virtual TransformKeyFrame* createNodeKeyFrame(Real timePos); - /** Returns a pointer to the associated Node object (if any). */ - virtual Node* getAssociatedNode(void) const; - - /** Sets the associated Node object which will be automatically affected by calls to 'apply'. */ - virtual void setAssociatedNode(Node* node); - - /** As the 'apply' method but applies to a specified Node instead of associated node. */ - virtual void applyToNode(Node* node, const TimeIndex& timeIndex, Real weight = 1.0, - Real scale = 1.0f); - - /** Sets the method of rotation calculation */ - virtual void setUseShortestRotationPath(bool useShortestPath); - - /** Gets the method of rotation calculation */ - virtual bool getUseShortestRotationPath() const; - - /// @copydoc AnimationTrack::getInterpolatedKeyFrame - void getInterpolatedKeyFrame(const TimeIndex& timeIndex, KeyFrame* kf) const override; - - /// @copydoc AnimationTrack::apply - void apply(const TimeIndex& timeIndex, Real weight = 1.0, Real scale = 1.0f) override; - - /// @copydoc AnimationTrack::_keyFrameDataChanged - void _keyFrameDataChanged(void) const override; - - /** Returns the KeyFrame at the specified index. */ - virtual TransformKeyFrame* getNodeKeyFrame(unsigned short index) const; - - - /** Method to determine if this track has any KeyFrames which are - doing anything useful - can be used to determine if this track - can be optimised out. - */ - bool hasNonZeroKeyFrames(void) const override; - - /** Optimise the current track by removing any duplicate keyframes. */ - void optimise(void) override; - - /** Clone this track (internal use only) */ - NodeAnimationTrack* _clone(Animation* newParent) const; - - void _applyBaseKeyFrame(const KeyFrame* base) override; - - private: - /// Specialised keyframe creation - KeyFrame* createKeyFrameImpl(Real time) override; - // Flag indicating we need to rebuild the splines next time - virtual void buildInterpolationSplines(void) const; - - // Struct for store splines, allocate on demand for better memory footprint - struct Splines - { - SimpleSpline positionSpline; - SimpleSpline scaleSpline; - RotationalSpline rotationSpline; - }; - - mutable bool mSplineBuildNeeded; - /// Defines if rotation is done using shortest path - mutable bool mUseShortestRotationPath; - Node* mTargetNode; - // Prebuilt splines, must be mutable since lazy-update in const method - mutable Splines* mSplines; - }; - - /** Type of vertex animation. - Vertex animation comes in 2 types, morph and pose. The reason - for the 2 types is that we have 2 different potential goals - to encapsulate - a complete, flowing morph animation with multiple keyframes (a typical animation, - but implemented by having snapshots of the vertex data at each keyframe), - or to represent a single pose change, for example a facial expression. - Whilst both could in fact be implemented using the same system, we choose - to separate them since the requirements and limitations of each are quite - different. - @par - Morph animation is a simple approach where we have a whole series of - snapshots of vertex data which must be interpolated, e.g. a running - animation implemented as morph targets. Because this is based on simple - snapshots, it's quite fast to use when animating an entire mesh because - it's a simple linear change between keyframes. However, this simplistic - approach does not support blending between multiple morph animations. - If you need animation blending, you are advised to use skeletal animation - for full-mesh animation, and pose animation for animation of subsets of - meshes or where skeletal animation doesn't fit - for example facial animation. - For animating in a vertex shader, morph animation is quite simple and - just requires the 2 vertex buffers (one the original position buffer) - of absolute position data, and an interpolation factor. Each track in - a morph animation references a unique set of vertex data. - @par - Pose animation is more complex. Like morph animation each track references - a single unique set of vertex data, but unlike morph animation, each - keyframe references 1 or more 'poses', each with an influence level. - A pose is a series of offsets to the base vertex data, and may be sparse - ie it - may not reference every vertex. Because they're offsets, they can be - blended - both within a track and between animations. This set of features - is very well suited to facial animation. - @par - For example, let's say you modelled a face (one set of vertex data), and - defined a set of poses which represented the various phonetic positions - of the face. You could then define an animation called 'SayHello', containing - a single track which referenced the face vertex data, and which included - a series of keyframes, each of which referenced one or more of the facial - positions at different influence levels - the combination of which over - time made the face form the shapes required to say the word 'hello'. Since - the poses are only stored once, but can be referenced may times in - many animations, this is a very powerful way to build up a speech system. - @par - The downside of pose animation is that it can be more difficult to set up. - Also, since it uses more buffers (one for the base data, and one for each - active pose), if you're animating in hardware using vertex shaders you need - to keep an eye on how many poses you're blending at once. You define a - maximum supported number in your vertex program definition, see the - includes_pose_animation material script entry. - @par - So, by partitioning the vertex animation approaches into 2, we keep the - simple morph technique easy to use, whilst still allowing all - the powerful techniques to be used. Note that morph animation cannot - be blended with other types of vertex animation (pose animation or other - morph animation); pose animation can be blended with other pose animation - though, and both types can be combined with skeletal animation. Also note - that all morph animation can be expressed as pose animation, but not vice - versa. - */ - enum VertexAnimationType : uint8 - { - /// No animation - VAT_NONE = 0, - /// Morph animation is made up of many interpolated snapshot keyframes - VAT_MORPH = 1, - /// Pose animation is made up of a single delta pose keyframe - VAT_POSE = 2 - }; - - /** Specialised AnimationTrack for dealing with changing vertex position information. - @see VertexAnimationType - */ - class _OgreExport VertexAnimationTrack : public AnimationTrack - { - public: - /** The target animation mode */ - enum TargetMode : uint8 - { - /// Interpolate vertex positions in software - TM_SOFTWARE, - /** Bind keyframe 1 to position, and keyframe 2 to a texture coordinate - for interpolation in hardware */ - TM_HARDWARE - }; - /// Constructor - VertexAnimationTrack(Animation* parent, unsigned short handle, VertexAnimationType animType); - /// Constructor, associates with target VertexData and temp buffer (for software) - VertexAnimationTrack(Animation* parent, unsigned short handle, VertexAnimationType animType, - VertexData* targetData, TargetMode target = TM_SOFTWARE); - - /** Get the type of vertex animation we're performing. */ - VertexAnimationType getAnimationType(void) const { return mAnimationType; } - - /** Whether the vertex animation (if present) includes normals */ - bool getVertexAnimationIncludesNormals() const; - - /// @copydoc AnimationTrack::createKeyFrame - virtual VertexMorphKeyFrame* createVertexMorphKeyFrame(Real timePos); - - /** Creates the single pose KeyFrame and adds it to this animation. - */ - virtual VertexPoseKeyFrame* createVertexPoseKeyFrame(Real timePos); - - /** @copydoc AnimationTrack::getInterpolatedKeyFrame - */ - void getInterpolatedKeyFrame(const TimeIndex& timeIndex, KeyFrame* kf) const override; - - /// @copydoc AnimationTrack::apply - void apply(const TimeIndex& timeIndex, Real weight = 1.0, Real scale = 1.0f) override; - - /** As the 'apply' method but applies to specified VertexData instead of - associated data. */ - virtual void applyToVertexData(VertexData* data, - const TimeIndex& timeIndex, float weight = 1.0, - const PoseList* poseList = 0); - - - /** Returns the morph KeyFrame at the specified index. */ - VertexMorphKeyFrame* getVertexMorphKeyFrame(unsigned short index) const; - - /** Returns the pose KeyFrame at the specified index. */ - VertexPoseKeyFrame* getVertexPoseKeyFrame(unsigned short index) const; - - /** Sets the associated VertexData which this track will update. */ - void setAssociatedVertexData(VertexData* data) { mTargetVertexData = data; } - /** Gets the associated VertexData which this track will update. */ - VertexData* getAssociatedVertexData(void) const { return mTargetVertexData; } - - /// Set the target mode - void setTargetMode(TargetMode m) { mTargetMode = m; } - /// Get the target mode - TargetMode getTargetMode(void) const { return mTargetMode; } - - /** Method to determine if this track has any KeyFrames which are - doing anything useful - can be used to determine if this track - can be optimised out. - */ - bool hasNonZeroKeyFrames(void) const override; - - /** Optimise the current track by removing any duplicate keyframes. */ - void optimise(void) override; - - /** Clone this track (internal use only) */ - VertexAnimationTrack* _clone(Animation* newParent) const; - - void _applyBaseKeyFrame(const KeyFrame* base) override; - - private: - /// Animation type - VertexAnimationType mAnimationType; - /// Mode to apply - TargetMode mTargetMode; - /// Target to animate - VertexData* mTargetVertexData; - - /// @copydoc AnimationTrack::createKeyFrameImpl - KeyFrame* createKeyFrameImpl(Real time) override; - - /// Utility method for applying pose animation - void applyPoseToVertexData(const Pose* pose, VertexData* data, float influence); - - - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreAny.h b/OgreMain/include/OgreAny.h deleted file mode 100644 index 9ba11e9e080..00000000000 --- a/OgreMain/include/OgreAny.h +++ /dev/null @@ -1,258 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -// -- Based on boost::any, original copyright information follows -- -// Copyright Kevlin Henney, 2000, 2001, 2002. All rights reserved. -// -// Distributed under the Boost Software License, Version 1.0. (See -// accompAnying file LICENSE_1_0.txt or copy at -// http://www.boost.org/LICENSE_1_0.txt) -// -- End original copyright -- - -#ifndef __OGRE_ANY_H__ -#define __OGRE_ANY_H__ - -#include "OgrePrerequisites.h" -#include -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - // resolve circular dependency - class Any; - template ValueType - any_cast(const Any & operand); - - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - /** Variant type that can hold Any other type. - */ - class Any - { - public: // constructors - - Any() - : mContent(0) - { - } - - template - Any(const ValueType & value) - : mContent(OGRE_NEW_T(holder, MEMCATEGORY_GENERAL)(value)) - { - } - - Any(const Any & other) - : mContent(other.mContent ? other.mContent->clone() : 0) - { - } - - virtual ~Any() - { - reset(); - } - - public: // modifiers - - Any& swap(Any & rhs) - { - std::swap(mContent, rhs.mContent); - return *this; - } - - template - Any& operator=(const ValueType & rhs) - { - Any(rhs).swap(*this); - return *this; - } - - Any & operator=(const Any & rhs) - { - Any(rhs).swap(*this); - return *this; - } - - public: // queries - - bool has_value() const - { - return mContent != NULL; - } - - /// @deprecated use has_value() instead - OGRE_DEPRECATED bool isEmpty() const { return !has_value(); } - - const std::type_info& type() const - { - return mContent ? mContent->getType() : typeid(void); - } - - /// @deprecated use type() instead - OGRE_DEPRECATED const std::type_info& getType() const { return type(); } - - /// @deprecated no longer supported - OGRE_DEPRECATED friend std::ostream& operator << - ( std::ostream& o, const Any& v ) - { - if (v.mContent) - v.mContent->writeToStream(o); - return o; - } - - void reset() - { - OGRE_DELETE_T(mContent, placeholder, MEMCATEGORY_GENERAL); - mContent = NULL; - } - - /// @deprecated use reset() instead - OGRE_DEPRECATED void destroy() { reset(); } - - protected: // types - - class placeholder - { - public: // structors - - virtual ~placeholder() - { - } - - public: // queries - - virtual const std::type_info& getType() const = 0; - - virtual placeholder * clone() const = 0; - - virtual void writeToStream(std::ostream& o) = 0; - - }; - - template - class holder : public placeholder - { - public: // structors - - holder(const ValueType & value) - : held(value) - { - } - - public: // queries - - const std::type_info & getType() const override - { - return typeid(ValueType); - } - - placeholder * clone() const override - { - return OGRE_NEW_T(holder, MEMCATEGORY_GENERAL)(held); - } - - void writeToStream(std::ostream& o) override - { - o << "Any::ValueType"; - } - - - public: // representation - - ValueType held; - - }; - - - - protected: // representation - placeholder * mContent; - - template - friend ValueType * any_cast(Any *); - - - public: - /// @deprecated use Ogre::any_cast instead - template - OGRE_DEPRECATED ValueType operator()() const - { - return any_cast(*this); - } - - /// @deprecated use Ogre::any_cast instead - template - OGRE_DEPRECATED ValueType get(void) const - { - return any_cast(*this); - } - - }; - - template - ValueType * any_cast(Any * operand) - { - return operand && -#if OGRE_COMPILER == OGRE_COMPILER_GNUC && OGRE_COMP_VER < 450 - (std::strcmp(operand->type().name(), typeid(ValueType).name()) == 0) -#else - (operand->type() == typeid(ValueType)) -#endif - ? &static_cast *>(operand->mContent)->held - : 0; - } - - template - const ValueType * any_cast(const Any * operand) - { - return any_cast(const_cast(operand)); - } - - template - ValueType any_cast(const Any & operand) - { - const ValueType * result = any_cast(&operand); - if(!result) - { - throw std::bad_cast(); - } - return *result; - } - /** @} */ - /** @} */ - - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreArchive.h b/OgreMain/include/OgreArchive.h deleted file mode 100644 index fddd33d5069..00000000000 --- a/OgreMain/include/OgreArchive.h +++ /dev/null @@ -1,228 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _Archive_H__ -#define _Archive_H__ - -#include "OgrePrerequisites.h" -#include "OgreDataStream.h" -#include "OgreStringVector.h" -#include -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - /** Information about a file/directory within the archive will be - returned using a FileInfo struct. - @see - Archive - */ - struct FileInfo { - /// The archive in which the file has been found (for info when performing - /// multi-Archive searches, note you should still open through ResourceGroupManager) - const Archive* archive; - /// The file's fully qualified name - String filename; - /// Path name; separated by '/' and ending with '/' - String path; - /// Base filename - String basename; - /// Compressed size - size_t compressedSize; - /// Uncompressed size - size_t uncompressedSize; - }; - - typedef std::vector FileInfoList; - typedef SharedPtr FileInfoListPtr; - - /** Archive-handling class. - - An archive is a generic term for a container of files. This may be a - filesystem folder, it may be a compressed archive, it may even be - a remote location shared on the web. This class is designed to be - subclassed to provide access to a range of file locations. - @par - Instances of this class are never constructed or even handled by end-user - applications. They are constructed by custom ArchiveFactory classes, - which plugins can register new instances of using ArchiveManager. - End-user applications will typically use ResourceManager or - ResourceGroupManager to manage resources at a higher level, rather than - reading files directly through this class. Doing it this way allows you - to benefit from OGRE's automatic searching of multiple file locations - for the resources you are looking for. - */ - class _OgreExport Archive : public ArchiveAlloc - { - protected: - /// Archive name - String mName; - /// Archive type code - String mType; - /// Read-only flag - bool mReadOnly; - public: - - - /** Constructor - don't call direct, used by ArchiveFactory. - */ - Archive( const String& name, const String& archType ) - : mName(name), mType(archType), mReadOnly(true) {} - - /** Default destructor. - */ - virtual ~Archive() {} - - /// Get the name of this archive - const String& getName(void) const { return mName; } - - /// Returns whether this archive is case sensitive in the way it matches files - virtual bool isCaseSensitive(void) const = 0; - - /** Loads the archive. - - This initializes all the internal data of the class. - @warning - Do not call this function directly, it is meant to be used - only by the ArchiveManager class. - */ - virtual void load() = 0; - - /** Unloads the archive. - @warning - Do not call this function directly, it is meant to be used - only by the ArchiveManager class. - */ - virtual void unload() = 0; - - /** Reports whether this Archive is read-only, or whether the contents - can be updated. - */ - virtual bool isReadOnly() const { return mReadOnly; } - - /** Open a stream on a given file. - @note - There is no equivalent 'close' method; the returned stream - controls the lifecycle of this file operation. - @param filename The fully qualified name of the file - @param readOnly Whether to open the file in read-only mode or not (note, - if the archive is read-only then this cannot be set to false) - @return A shared pointer to a DataStream which can be used to - read / write the file. If the file is not present, returns a null - shared pointer. - */ - virtual DataStreamPtr open(const String& filename, bool readOnly = true) const = 0; - - /** Create a new file (or overwrite one already there). - @note If the archive is read-only then this method will fail. - @param filename The fully qualified name of the file - @return A shared pointer to a DataStream which can be used to - read / write the file. - */ - virtual DataStreamPtr create(const String& filename); - - /** Delete a named file. - @remarks Not possible on read-only archives - @param filename The fully qualified name of the file - */ - virtual void remove(const String& filename); - - /** List all file names in the archive. - @note - This method only returns filenames, you can also retrieve other - information using listFileInfo. - @param recursive Whether all paths of the archive are searched (if the - archive has a concept of that) - @param dirs Set to true if you want the directories to be listed - instead of files - @return A list of filenames matching the criteria, all are fully qualified - */ - virtual StringVectorPtr list(bool recursive = true, bool dirs = false) const = 0; - - /** List all files in the archive with accompanying information. - @param recursive Whether all paths of the archive are searched (if the - archive has a concept of that) - @param dirs Set to true if you want the directories to be listed - instead of files - @return A list of structures detailing quite a lot of information about - all the files in the archive. - */ - virtual FileInfoListPtr listFileInfo(bool recursive = true, bool dirs = false) const = 0; - - /** Find all file or directory names matching a given pattern - in this archive. - @note - This method only returns filenames, you can also retrieve other - information using findFileInfo. - @param pattern The pattern to search for; wildcards (*) are allowed - @param recursive Whether all paths of the archive are searched (if the - archive has a concept of that) - @param dirs Set to true if you want the directories to be listed - instead of files - @return A list of filenames matching the criteria, all are fully qualified - */ - virtual StringVectorPtr find(const String& pattern, bool recursive = true, - bool dirs = false) const = 0; - - /** Find out if the named file exists (note: fully qualified filename required) */ - virtual bool exists(const String& filename) const = 0; - - /** Retrieve the modification time of a given file */ - virtual time_t getModifiedTime(const String& filename) const = 0; - - - /** Find all files or directories matching a given pattern in this - archive and get some detailed information about them. - @param pattern The pattern to search for; wildcards (*) are allowed - @param recursive Whether all paths of the archive are searched (if the - archive has a concept of that) - @param dirs Set to true if you want the directories to be listed - instead of files - @return A list of file information structures for all files matching - the criteria. - */ - virtual FileInfoListPtr findFileInfo(const String& pattern, - bool recursive = true, bool dirs = false) const = 0; - - /// Return the type code of this Archive - const String& getType(void) const { return mType; } - - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreArchiveFactory.h b/OgreMain/include/OgreArchiveFactory.h deleted file mode 100644 index 8172498e843..00000000000 --- a/OgreMain/include/OgreArchiveFactory.h +++ /dev/null @@ -1,81 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ArchiveFactory_H__ -#define _ArchiveFactory_H__ - -#include "OgrePrerequisites.h" -#include "OgreFactoryObj.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - /** Abstract factory class, archive codec plugins can register concrete - subclasses of this. - - All access to 'archives' (collections of files, compressed or - just folders, maybe even remote) is managed via the abstract - Archive class. Plugins are expected to provide the - implementation for the actual codec itself, but because a - subclass of Archive has to be created for every archive, a - factory class is required to create the appropriate subclass. - @par - So archive plugins create a subclass of Archive AND a subclass - of ArchiveFactory which creates instances of the Archive - subclass. See the 'Zip' and 'FileSystem' plugins for examples. - Each Archive and ArchiveFactory subclass pair deal with a - single archive type (identified by a string). - */ - class _OgreExport ArchiveFactory : public FactoryObj< Archive >, public ArchiveAlloc - { - public: - virtual ~ArchiveFactory() {} - /** Creates a new object. - @param name Name of the object to create - @param readOnly whether the Archive is read only - @return - An object created by the factory. The type of the object depends on - the factory. - */ - virtual Archive* createInstance(const String& name, bool readOnly) OGRE_NODISCARD = 0; - - Archive* createInstance(const String& name) override OGRE_NODISCARD { return createInstance(name, true); } - }; - /** @} */ - /** @} */ - -} // namespace - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreArchiveManager.h b/OgreMain/include/OgreArchiveManager.h deleted file mode 100644 index a63180fc3b4..00000000000 --- a/OgreMain/include/OgreArchiveManager.h +++ /dev/null @@ -1,116 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ArchiveManager_H__ -#define _ArchiveManager_H__ - -#include "OgrePrerequisites.h" - -#include "OgreSingleton.h" -#include "OgreIteratorWrapper.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - /** This class manages the available ArchiveFactory plugins. - */ - class _OgreExport ArchiveManager : public Singleton, public ArchiveAlloc - { - private: - typedef std::map ArchiveFactoryMap; - /// Factories available to create archives, indexed by archive type (String identifier e.g. 'Zip') - ArchiveFactoryMap mArchFactories; - /// Currently loaded archives - typedef std::map ArchiveMap; - ArchiveMap mArchives; - - public: - /** Default constructor - should never get called by a client app. - */ - ArchiveManager(); - /** Default destructor. - */ - virtual ~ArchiveManager(); - - /** Opens an archive for file reading. - - The archives are created using class factories within - extension libraries. - @param filename - The filename that will be opened - @param archiveType - The type of archive that this is. For example: "Zip". - @param readOnly - Whether the Archive is read only - @return - If the function succeeds, a valid pointer to an Archive - object is returned. - @par - If the function fails, an exception is thrown. - */ - Archive* load( const String& filename, const String& archiveType, bool readOnly); - - /** Unloads an archive. - - You must ensure that this archive is not being used before removing it. - */ - void unload(Archive* arch); - /** Unloads an archive by name. - - You must ensure that this archive is not being used before removing it. - */ - void unload(const String& filename); - typedef MapIterator ArchiveMapIterator; - /** Get an iterator over the Archives in this Manager. */ - ArchiveMapIterator getArchiveIterator(void); - - /** Adds a new ArchiveFactory to the list of available factories. - - Plugin developers who add new archive codecs need to call - this after defining their ArchiveFactory subclass and - Archive subclasses for their archive type. - */ - void addArchiveFactory(ArchiveFactory* factory); - /// @copydoc Singleton::getSingleton() - static ArchiveManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static ArchiveManager* getSingletonPtr(void); - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreAtomicScalar.h b/OgreMain/include/OgreAtomicScalar.h deleted file mode 100644 index 68168db9845..00000000000 --- a/OgreMain/include/OgreAtomicScalar.h +++ /dev/null @@ -1 +0,0 @@ -#pragma message( __FILE__ " is deprecated, migrate to Ogre.h") diff --git a/OgreMain/include/OgreAutoParamDataSource.h b/OgreMain/include/OgreAutoParamDataSource.h deleted file mode 100644 index 879ec2b5b18..00000000000 --- a/OgreMain/include/OgreAutoParamDataSource.h +++ /dev/null @@ -1,276 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __AutoParamDataSource_H_ -#define __AutoParamDataSource_H_ - -#include "OgrePrerequisites.h" -#include "OgreCommon.h" -#include "OgreLight.h" -#include "OgreSceneNode.h" - -namespace Ogre { - - // forward decls - struct VisibleObjectsBoundsInfo; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Materials - * @{ - */ - - - /** This utility class is used to hold the information used to generate the matrices - and other information required to automatically populate GpuProgramParameters. - - This class exercises a lazy-update scheme in order to avoid having to update all - the information a GpuProgramParameters class could possibly want all the time. - It relies on the SceneManager to update it when the base data has changed, and - will calculate concatenated matrices etc only when required, passing back precalculated - matrices when they are requested more than once when the underlying information has - not altered. - */ - class _OgreExport AutoParamDataSource : public SceneMgtAlloc - { - private: - const Light& getLight(size_t index) const; - mutable Affine3 mWorldMatrix[OGRE_MAX_NUM_BONES + 1]; - mutable size_t mWorldMatrixCount; - mutable const Affine3* mWorldMatrixArray; - mutable Affine3 mWorldViewMatrix; - mutable Matrix4 mViewProjMatrix; - mutable Matrix4 mWorldViewProjMatrix; - mutable Affine3 mInverseWorldMatrix; - mutable Affine3 mInverseWorldViewMatrix; - mutable Affine3 mInverseViewMatrix; - mutable Matrix4 mInverseTransposeWorldMatrix; - mutable Matrix4 mInverseTransposeWorldViewMatrix; - mutable Vector4 mCameraPosition; - mutable Vector4 mCameraPositionObjectSpace; - mutable Matrix4 mTextureViewProjMatrix[OGRE_MAX_SIMULTANEOUS_LIGHTS]; - mutable Matrix4 mTextureWorldViewProjMatrix[OGRE_MAX_SIMULTANEOUS_LIGHTS]; - mutable Matrix4 mSpotlightViewProjMatrix[OGRE_MAX_SIMULTANEOUS_LIGHTS]; - mutable Matrix4 mSpotlightWorldViewProjMatrix[OGRE_MAX_SIMULTANEOUS_LIGHTS]; - mutable Vector4 mShadowCamDepthRanges[OGRE_MAX_SIMULTANEOUS_LIGHTS]; - mutable Affine3 mViewMatrix; - mutable Matrix4 mProjectionMatrix; - mutable Real mDirLightExtrusionDistance; - mutable Real mPointLightExtrusionDistance; - mutable Vector4 mLodCameraPosition; - mutable Vector4 mLodCameraPositionObjectSpace; - - mutable bool mWorldMatrixDirty; - mutable bool mViewMatrixDirty; - mutable bool mProjMatrixDirty; - mutable bool mWorldViewMatrixDirty; - mutable bool mViewProjMatrixDirty; - mutable bool mWorldViewProjMatrixDirty; - mutable bool mInverseWorldMatrixDirty; - mutable bool mInverseWorldViewMatrixDirty; - mutable bool mInverseViewMatrixDirty; - mutable bool mInverseTransposeWorldMatrixDirty; - mutable bool mInverseTransposeWorldViewMatrixDirty; - mutable bool mCameraPositionDirty; - mutable bool mCameraPositionObjectSpaceDirty; - mutable bool mTextureViewProjMatrixDirty[OGRE_MAX_SIMULTANEOUS_LIGHTS]; - mutable bool mTextureWorldViewProjMatrixDirty[OGRE_MAX_SIMULTANEOUS_LIGHTS]; - mutable bool mSpotlightViewProjMatrixDirty[OGRE_MAX_SIMULTANEOUS_LIGHTS]; - mutable bool mSpotlightWorldViewProjMatrixDirty[OGRE_MAX_SIMULTANEOUS_LIGHTS]; - mutable bool mShadowCamDepthRangesDirty[OGRE_MAX_SIMULTANEOUS_LIGHTS]; - ColourValue mAmbientLight; - ColourValue mFogColour; - Vector4f mFogParams; - Vector4f mPointParams; - int mPassNumber; - mutable Vector4 mSceneDepthRange; - mutable bool mSceneDepthRangeDirty; - mutable bool mLodCameraPositionDirty; - mutable bool mLodCameraPositionObjectSpaceDirty; - - const Renderable* mCurrentRenderable; - const Camera* mCurrentCamera; - bool mCameraRelativeRendering; - Vector3 mCameraRelativePosition; - const LightList* mCurrentLightList; - const Frustum* mCurrentTextureProjector[OGRE_MAX_SIMULTANEOUS_LIGHTS]; - const RenderTarget* mCurrentRenderTarget; - const Viewport* mCurrentViewport; - const SceneManager* mCurrentSceneManager; - const VisibleObjectsBoundsInfo* mMainCamBoundsInfo; - const Pass* mCurrentPass; - - SceneNode mDummyNode; - Light mBlankLight; - public: - AutoParamDataSource(); - /** Updates the current renderable */ - void setCurrentRenderable(const Renderable* rend); - /** Sets the world matrices, avoid query from renderable again */ - void setWorldMatrices(const Affine3* m, size_t count); - /** Updates the current camera */ - void setCurrentCamera(const Camera* cam, bool useCameraRelative); - /** Sets the light list that should be used, and it's base index from the global list */ - void setCurrentLightList(const LightList* ll); - /** Sets the current texture projector for a index */ - void setTextureProjector(const Frustum* frust, size_t index); - /** Sets the current render target */ - void setCurrentRenderTarget(const RenderTarget* target); - /** Sets the current viewport */ - void setCurrentViewport(const Viewport* viewport); - /** Sets the shadow extrusion distance to be used for dir lights. */ - void setShadowDirLightExtrusionDistance(Real dist); - /** Sets the shadow extrusion distance to be used for point lights. */ - void setShadowPointLightExtrusionDistance(Real dist); - /** Sets the main camera's scene bounding information */ - void setMainCamBoundsInfo(VisibleObjectsBoundsInfo* info); - /** Set the current scene manager for enquiring on demand */ - void setCurrentSceneManager(const SceneManager* sm); - /** Sets the current pass */ - void setCurrentPass(const Pass* pass); - - /** Returns the current bounded camera */ - const Camera* getCurrentCamera() const; - - const Affine3& getWorldMatrix(void) const; - const Affine3* getBoneMatrixArray(void) const; - OGRE_DEPRECATED const Affine3* getWorldMatrixArray(void) const { return getBoneMatrixArray(); } - size_t getBoneMatrixCount(void) const; - OGRE_DEPRECATED size_t getWorldMatrixCount(void) const { return getBoneMatrixCount(); } - const Affine3& getViewMatrix(void) const; - const Matrix4& getViewProjectionMatrix(void) const; - const Matrix4& getProjectionMatrix(void) const; - const Matrix4& getWorldViewProjMatrix(void) const; - const Affine3& getWorldViewMatrix(void) const; - const Affine3& getInverseWorldMatrix(void) const; - const Affine3& getInverseWorldViewMatrix(void) const; - const Affine3& getInverseViewMatrix(void) const; - const Matrix4& getInverseTransposeWorldMatrix(void) const; - const Matrix4& getInverseTransposeWorldViewMatrix(void) const; - const Vector4& getCameraPosition(void) const; - const Vector4& getCameraPositionObjectSpace(void) const; - const Vector4 getCameraRelativePosition(void) const; - const Vector4& getLodCameraPosition(void) const; - const Vector4& getLodCameraPositionObjectSpace(void) const; - bool hasLightList() const { return mCurrentLightList != 0; } - /** Get the light which is 'index'th closest to the current object */ - float getLightNumber(size_t index) const; - float getLightCount() const; - float getLightCastsShadows(size_t index) const; - const ColourValue& getLightDiffuseColour(size_t index) const; - const ColourValue& getLightSpecularColour(size_t index) const; - const ColourValue getLightDiffuseColourWithPower(size_t index) const; - const ColourValue getLightSpecularColourWithPower(size_t index) const; - Vector3 getLightPosition(size_t index) const; - Vector4 getLightAs4DVector(size_t index) const; - Vector3 getLightDirection(size_t index) const; - Real getLightPowerScale(size_t index) const; - Vector4f getLightAttenuation(size_t index) const; - Vector4f getSpotlightParams(size_t index) const; - void setAmbientLightColour(const ColourValue& ambient); - const ColourValue& getAmbientLightColour(void) const; - const ColourValue& getSurfaceAmbientColour(void) const; - const ColourValue& getSurfaceDiffuseColour(void) const; - const ColourValue& getSurfaceSpecularColour(void) const; - const ColourValue& getSurfaceEmissiveColour(void) const; - Real getSurfaceShininess(void) const; - Real getSurfaceAlphaRejectionValue(void) const; - ColourValue getDerivedAmbientLightColour(void) const; - ColourValue getDerivedSceneColour(void) const; - void setFog(FogMode mode, const ColourValue& colour, Real expDensity, Real linearStart, Real linearEnd); - const ColourValue& getFogColour(void) const; - const Vector4f& getFogParams(void) const; - void setPointParameters(bool attenuation, const Vector4f& params); - const Vector4f& getPointParams() const; - const Matrix4& getTextureViewProjMatrix(size_t index) const; - const Matrix4& getTextureWorldViewProjMatrix(size_t index) const; - const Matrix4& getSpotlightViewProjMatrix(size_t index) const; - const Matrix4& getSpotlightWorldViewProjMatrix(size_t index) const; - const Matrix4& getTextureTransformMatrix(size_t index) const; - const RenderTarget* getCurrentRenderTarget(void) const; - const Renderable* getCurrentRenderable(void) const; - const Pass* getCurrentPass(void) const; - Vector4f getTextureSize(size_t index) const; - Vector4f getInverseTextureSize(size_t index) const; - Vector4f getPackedTextureSize(size_t index) const; - Real getShadowExtrusionDistance(void) const; - const Vector4& getSceneDepthRange() const; - const Vector4& getShadowSceneDepthRange(size_t index) const; - const ColourValue& getShadowColour() const; - Matrix4 getInverseViewProjMatrix(void) const; - Matrix4 getInverseTransposeViewProjMatrix() const; - Matrix4 getTransposeViewProjMatrix() const; - Matrix4 getTransposeViewMatrix() const; - Matrix4 getInverseTransposeViewMatrix() const; - Matrix4 getTransposeProjectionMatrix() const; - Matrix4 getInverseProjectionMatrix() const; - Matrix4 getInverseTransposeProjectionMatrix() const; - Matrix4 getTransposeWorldViewProjMatrix() const; - Matrix4 getInverseWorldViewProjMatrix() const; - Matrix4 getInverseTransposeWorldViewProjMatrix() const; - Matrix4 getTransposeWorldViewMatrix() const; - Matrix4 getTransposeWorldMatrix() const; - Real getTime(void) const; - Real getTime_0_X(Real x) const; - Real getCosTime_0_X(Real x) const; - Real getSinTime_0_X(Real x) const; - Real getTanTime_0_X(Real x) const; - Vector4f getTime_0_X_packed(Real x) const; - Real getTime_0_1(Real x) const; - Real getCosTime_0_1(Real x) const; - Real getSinTime_0_1(Real x) const; - Real getTanTime_0_1(Real x) const; - Vector4f getTime_0_1_packed(Real x) const; - Real getTime_0_2Pi(Real x) const; - Real getCosTime_0_2Pi(Real x) const; - Real getSinTime_0_2Pi(Real x) const; - Real getTanTime_0_2Pi(Real x) const; - Vector4f getTime_0_2Pi_packed(Real x) const; - Real getFrameTime(void) const; - Real getFPS() const; - Real getViewportWidth() const; - Real getViewportHeight() const; - Real getInverseViewportWidth() const; - Real getInverseViewportHeight() const; - Vector3 getViewDirection() const; - Vector3 getViewSideVector() const; - Vector3 getViewUpVector() const; - Real getFOV() const; - Real getNearClipDistance() const; - Real getFarClipDistance() const; - int getPassNumber(void) const; - int getMaterialLodIndex() const; - void setPassNumber(const int passNumber); - void incPassNumber(void); - void updateLightCustomGpuParameter(const GpuProgramParameters::AutoConstantEntry& constantEntry, GpuProgramParameters *params) const; - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/OgreMain/include/OgreAxisAlignedBox.h b/OgreMain/include/OgreAxisAlignedBox.h deleted file mode 100644 index 812d9668c48..00000000000 --- a/OgreMain/include/OgreAxisAlignedBox.h +++ /dev/null @@ -1,812 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __AxisAlignedBox_H_ -#define __AxisAlignedBox_H_ - -#include - -// Precompiler options -#include "OgrePrerequisites.h" - -#include "OgreMatrix4.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - - /** A 3D box aligned with the x/y/z axes. - - This class represents a simple box which is aligned with the - axes. Internally it only stores 2 points as the extremeties of - the box, one which is the minima of all 3 axes, and the other - which is the maxima of all 3 axes. This class is typically used - for an axis-aligned bounding box (AABB) for collision and - visibility determination. - */ - class _OgreExport AxisAlignedBox - { - public: - enum Extent - { - EXTENT_NULL, - EXTENT_FINITE, - EXTENT_INFINITE - }; - private: - - Vector3 mMinimum; - Vector3 mMaximum; - Extent mExtent; - - public: - /* - 1-------2 - /| /| - / | / | - 5-------4 | - | 0----|--3 - | / | / - |/ |/ - 6-------7 - */ - enum CornerEnum { - FAR_LEFT_BOTTOM = 0, - FAR_LEFT_TOP = 1, - FAR_RIGHT_TOP = 2, - FAR_RIGHT_BOTTOM = 3, - NEAR_RIGHT_BOTTOM = 7, - NEAR_LEFT_BOTTOM = 6, - NEAR_LEFT_TOP = 5, - NEAR_RIGHT_TOP = 4 - }; - typedef std::array Corners; - - AxisAlignedBox() - { - // Default to a null box - setMinimum( -0.5, -0.5, -0.5 ); - setMaximum( 0.5, 0.5, 0.5 ); - mExtent = EXTENT_NULL; - } - AxisAlignedBox(Extent e) - { - setMinimum( -0.5, -0.5, -0.5 ); - setMaximum( 0.5, 0.5, 0.5 ); - mExtent = e; - } - - AxisAlignedBox( const Vector3& min, const Vector3& max ) - { - setExtents( min, max ); - } - - AxisAlignedBox(Real mx, Real my, Real mz, Real Mx, Real My, Real Mz) - { - setExtents( mx, my, mz, Mx, My, Mz ); - } - - /** Gets the minimum corner of the box. - */ - inline const Vector3& getMinimum(void) const - { - return mMinimum; - } - - /** Gets a modifiable version of the minimum - corner of the box. - */ - inline Vector3& getMinimum(void) - { - return mMinimum; - } - - /** Gets the maximum corner of the box. - */ - inline const Vector3& getMaximum(void) const - { - return mMaximum; - } - - /** Gets a modifiable version of the maximum - corner of the box. - */ - inline Vector3& getMaximum(void) - { - return mMaximum; - } - - - /** Sets the minimum corner of the box. - */ - inline void setMinimum( const Vector3& vec ) - { - mExtent = EXTENT_FINITE; - mMinimum = vec; - } - - inline void setMinimum( Real x, Real y, Real z ) - { - mExtent = EXTENT_FINITE; - mMinimum.x = x; - mMinimum.y = y; - mMinimum.z = z; - } - - /** Changes one of the components of the minimum corner of the box - used to resize only one dimension of the box - */ - inline void setMinimumX(Real x) - { - mMinimum.x = x; - } - - inline void setMinimumY(Real y) - { - mMinimum.y = y; - } - - inline void setMinimumZ(Real z) - { - mMinimum.z = z; - } - - /** Sets the maximum corner of the box. - */ - inline void setMaximum( const Vector3& vec ) - { - mExtent = EXTENT_FINITE; - mMaximum = vec; - } - - inline void setMaximum( Real x, Real y, Real z ) - { - mExtent = EXTENT_FINITE; - mMaximum.x = x; - mMaximum.y = y; - mMaximum.z = z; - } - - /** Changes one of the components of the maximum corner of the box - used to resize only one dimension of the box - */ - inline void setMaximumX( Real x ) - { - mMaximum.x = x; - } - - inline void setMaximumY( Real y ) - { - mMaximum.y = y; - } - - inline void setMaximumZ( Real z ) - { - mMaximum.z = z; - } - - /** Sets both minimum and maximum extents at once. - */ - inline void setExtents( const Vector3& min, const Vector3& max ) - { - assert( (min.x <= max.x && min.y <= max.y && min.z <= max.z) && - "The minimum corner of the box must be less than or equal to maximum corner" ); - - mExtent = EXTENT_FINITE; - mMinimum = min; - mMaximum = max; - } - - inline void setExtents( - Real mx, Real my, Real mz, - Real Mx, Real My, Real Mz ) - { - assert( (mx <= Mx && my <= My && mz <= Mz) && - "The minimum corner of the box must be less than or equal to maximum corner" ); - - mExtent = EXTENT_FINITE; - - mMinimum.x = mx; - mMinimum.y = my; - mMinimum.z = mz; - - mMaximum.x = Mx; - mMaximum.y = My; - mMaximum.z = Mz; - - } - - /** Returns a pointer to an array of 8 corner points, useful for - collision vs. non-aligned objects. - - If the order of these corners is important, they are as - follows: The 4 points of the minimum Z face (note that - because Ogre uses right-handed coordinates, the minimum Z is - at the 'back' of the box) starting with the minimum point of - all, then anticlockwise around this face (if you are looking - onto the face from outside the box). Then the 4 points of the - maximum Z face, starting with maximum point of all, then - anticlockwise around this face (looking onto the face from - outside the box). Like this: -
-           1-------2
-          /|      /|
-         / |     / |
-        5-------4  |
-        |  0----|--3
-        | /     | /
-        |/      |/
-        6-------7
-        
- */ - inline Corners getAllCorners(void) const - { - assert( (mExtent == EXTENT_FINITE) && "Can't get corners of a null or infinite AAB" ); - - // The order of these items is, using right-handed coordinates: - // Minimum Z face, starting with Min(all), then anticlockwise - // around face (looking onto the face) - // Maximum Z face, starting with Max(all), then anticlockwise - // around face (looking onto the face) - // Only for optimization/compatibility. - Corners corners; - - corners[0] = getCorner(FAR_LEFT_BOTTOM); - corners[1] = getCorner(FAR_LEFT_TOP); - corners[2] = getCorner(FAR_RIGHT_TOP); - corners[3] = getCorner(FAR_RIGHT_BOTTOM); - - corners[4] = getCorner(NEAR_RIGHT_TOP); - corners[5] = getCorner(NEAR_LEFT_TOP); - corners[6] = getCorner(NEAR_LEFT_BOTTOM); - corners[7] = getCorner(NEAR_RIGHT_BOTTOM); - - return corners; - } - - /** Gets the position of one of the corners - */ - Vector3 getCorner(CornerEnum cornerToGet) const - { - switch(cornerToGet) - { - case FAR_LEFT_BOTTOM: - return mMinimum; - case FAR_LEFT_TOP: - return Vector3(mMinimum.x, mMaximum.y, mMinimum.z); - case FAR_RIGHT_TOP: - return Vector3(mMaximum.x, mMaximum.y, mMinimum.z); - case FAR_RIGHT_BOTTOM: - return Vector3(mMaximum.x, mMinimum.y, mMinimum.z); - case NEAR_RIGHT_BOTTOM: - return Vector3(mMaximum.x, mMinimum.y, mMaximum.z); - case NEAR_LEFT_BOTTOM: - return Vector3(mMinimum.x, mMinimum.y, mMaximum.z); - case NEAR_LEFT_TOP: - return Vector3(mMinimum.x, mMaximum.y, mMaximum.z); - case NEAR_RIGHT_TOP: - return mMaximum; - default: - return Vector3(); - } - } - - friend std::ostream& operator<<( std::ostream& o, const AxisAlignedBox &aab ) - { - switch (aab.mExtent) - { - case EXTENT_NULL: - o << "AxisAlignedBox(null)"; - return o; - - case EXTENT_FINITE: - o << "AxisAlignedBox(min=" << aab.mMinimum << ", max=" << aab.mMaximum << ")"; - return o; - - case EXTENT_INFINITE: - o << "AxisAlignedBox(infinite)"; - return o; - - default: // shut up compiler - assert( false && "Never reached" ); - return o; - } - } - - /** Merges the passed in box into the current box. The result is the - box which encompasses both. - */ - void merge( const AxisAlignedBox& rhs ) - { - // Do nothing if rhs null, or this is infinite - if ((rhs.mExtent == EXTENT_NULL) || (mExtent == EXTENT_INFINITE)) - { - return; - } - // Otherwise if rhs is infinite, make this infinite, too - else if (rhs.mExtent == EXTENT_INFINITE) - { - mExtent = EXTENT_INFINITE; - } - // Otherwise if current null, just take rhs - else if (mExtent == EXTENT_NULL) - { - setExtents(rhs.mMinimum, rhs.mMaximum); - } - // Otherwise merge - else - { - Vector3 min = mMinimum; - Vector3 max = mMaximum; - max.makeCeil(rhs.mMaximum); - min.makeFloor(rhs.mMinimum); - - setExtents(min, max); - } - - } - - /** Extends the box to encompass the specified point (if needed). - */ - inline void merge( const Vector3& point ) - { - switch (mExtent) - { - case EXTENT_NULL: // if null, use this point - setExtents(point, point); - return; - - case EXTENT_FINITE: - mMaximum.makeCeil(point); - mMinimum.makeFloor(point); - return; - - case EXTENT_INFINITE: // if infinite, makes no difference - return; - } - - assert( false && "Never reached" ); - } - - /** Transforms the box according to the matrix supplied. - - By calling this method you get the axis-aligned box which - surrounds the transformed version of this box. Therefore each - corner of the box is transformed by the matrix, then the - extents are mapped back onto the axes to produce another - AABB. Useful when you have a local AABB for an object which - is then transformed. - */ - inline void transform( const Matrix4& matrix ) - { - // Do nothing if current null or infinite - if( mExtent != EXTENT_FINITE ) - return; - - Vector3 oldMin, oldMax, currentCorner; - - // Getting the old values so that we can use the existing merge method. - oldMin = mMinimum; - oldMax = mMaximum; - - // reset - setNull(); - - // We sequentially compute the corners in the following order : - // 0, 6, 5, 1, 2, 4 ,7 , 3 - // This sequence allows us to only change one member at a time to get at all corners. - - // For each one, we transform it using the matrix - // Which gives the resulting point and merge the resulting point. - - // First corner - // min min min - currentCorner = oldMin; - merge( matrix * currentCorner ); - - // min,min,max - currentCorner.z = oldMax.z; - merge( matrix * currentCorner ); - - // min max max - currentCorner.y = oldMax.y; - merge( matrix * currentCorner ); - - // min max min - currentCorner.z = oldMin.z; - merge( matrix * currentCorner ); - - // max max min - currentCorner.x = oldMax.x; - merge( matrix * currentCorner ); - - // max max max - currentCorner.z = oldMax.z; - merge( matrix * currentCorner ); - - // max min max - currentCorner.y = oldMin.y; - merge( matrix * currentCorner ); - - // max min min - currentCorner.z = oldMin.z; - merge( matrix * currentCorner ); - } - - /** Transforms the box according to the affine matrix supplied. - - By calling this method you get the axis-aligned box which - surrounds the transformed version of this box. Therefore each - corner of the box is transformed by the matrix, then the - extents are mapped back onto the axes to produce another - AABB. Useful when you have a local AABB for an object which - is then transformed. - */ - void transform(const Affine3& m) - { - // Do nothing if current null or infinite - if ( mExtent != EXTENT_FINITE ) - return; - - Vector3 centre = getCenter(); - Vector3 halfSize = getHalfSize(); - - Vector3 newCentre = m * centre; - Vector3 newHalfSize( - Math::Abs(m[0][0]) * halfSize.x + Math::Abs(m[0][1]) * halfSize.y + Math::Abs(m[0][2]) * halfSize.z, - Math::Abs(m[1][0]) * halfSize.x + Math::Abs(m[1][1]) * halfSize.y + Math::Abs(m[1][2]) * halfSize.z, - Math::Abs(m[2][0]) * halfSize.x + Math::Abs(m[2][1]) * halfSize.y + Math::Abs(m[2][2]) * halfSize.z); - - setExtents(newCentre - newHalfSize, newCentre + newHalfSize); - } - - /** Sets the box to a 'null' value i.e. not a box. - */ - inline void setNull() - { - mExtent = EXTENT_NULL; - } - - /** Returns true if the box is null i.e. empty. - */ - inline bool isNull(void) const - { - return (mExtent == EXTENT_NULL); - } - - /** Returns true if the box is finite. - */ - bool isFinite(void) const - { - return (mExtent == EXTENT_FINITE); - } - - /** Sets the box to 'infinite' - */ - inline void setInfinite() - { - mExtent = EXTENT_INFINITE; - } - - /** Returns true if the box is infinite. - */ - bool isInfinite(void) const - { - return (mExtent == EXTENT_INFINITE); - } - - /** Returns whether or not this box intersects another. */ - inline bool intersects(const AxisAlignedBox& b2) const - { - // Early-fail for nulls - if (this->isNull() || b2.isNull()) - return false; - - // Early-success for infinites - if (this->isInfinite() || b2.isInfinite()) - return true; - - // Use up to 6 separating planes - if (mMaximum.x < b2.mMinimum.x) - return false; - if (mMaximum.y < b2.mMinimum.y) - return false; - if (mMaximum.z < b2.mMinimum.z) - return false; - - if (mMinimum.x > b2.mMaximum.x) - return false; - if (mMinimum.y > b2.mMaximum.y) - return false; - if (mMinimum.z > b2.mMaximum.z) - return false; - - // otherwise, must be intersecting - return true; - - } - - /// Calculate the area of intersection of this box and another - inline AxisAlignedBox intersection(const AxisAlignedBox& b2) const - { - if (this->isNull() || b2.isNull()) - { - return AxisAlignedBox(); - } - else if (this->isInfinite()) - { - return b2; - } - else if (b2.isInfinite()) - { - return *this; - } - - Vector3 intMin = mMinimum; - Vector3 intMax = mMaximum; - - intMin.makeCeil(b2.getMinimum()); - intMax.makeFloor(b2.getMaximum()); - - // Check intersection isn't null - if (intMin.x < intMax.x && - intMin.y < intMax.y && - intMin.z < intMax.z) - { - return AxisAlignedBox(intMin, intMax); - } - - return AxisAlignedBox(); - } - - /// Calculate the volume of this box - Real volume(void) const - { - switch (mExtent) - { - case EXTENT_NULL: - return 0.0f; - - case EXTENT_FINITE: - { - Vector3 diff = mMaximum - mMinimum; - return diff.x * diff.y * diff.z; - } - - case EXTENT_INFINITE: - return Math::POS_INFINITY; - - default: // shut up compiler - assert( false && "Never reached" ); - return 0.0f; - } - } - - /** Scales the AABB by the vector given. */ - inline void scale(const Vector3& s) - { - // Do nothing if current null or infinite - if (mExtent != EXTENT_FINITE) - return; - - // NB assumes centered on origin - Vector3 min = mMinimum * s; - Vector3 max = mMaximum * s; - setExtents(min, max); - } - - /** Tests whether this box intersects a sphere. */ - bool intersects(const Sphere& s) const - { - return Math::intersects(s, *this); - } - /** Tests whether this box intersects a plane. */ - bool intersects(const Plane& p) const - { - return Math::intersects(p, *this); - } - /** Tests whether the vector point is within this box. */ - bool intersects(const Vector3& v) const - { - switch (mExtent) - { - case EXTENT_NULL: - return false; - - case EXTENT_FINITE: - return(v.x >= mMinimum.x && v.x <= mMaximum.x && - v.y >= mMinimum.y && v.y <= mMaximum.y && - v.z >= mMinimum.z && v.z <= mMaximum.z); - - case EXTENT_INFINITE: - return true; - - default: // shut up compiler - assert( false && "Never reached" ); - return false; - } - } - /// Gets the centre of the box - Vector3 getCenter(void) const - { - assert( (mExtent == EXTENT_FINITE) && "Can't get center of a null or infinite AAB" ); - - return Vector3( - (mMaximum.x + mMinimum.x) * 0.5f, - (mMaximum.y + mMinimum.y) * 0.5f, - (mMaximum.z + mMinimum.z) * 0.5f); - } - /// Gets the size of the box - Vector3 getSize(void) const - { - switch (mExtent) - { - case EXTENT_NULL: - return Vector3::ZERO; - - case EXTENT_FINITE: - return mMaximum - mMinimum; - - case EXTENT_INFINITE: - return Vector3( - Math::POS_INFINITY, - Math::POS_INFINITY, - Math::POS_INFINITY); - - default: // shut up compiler - assert( false && "Never reached" ); - return Vector3::ZERO; - } - } - /// Gets the half-size of the box - Vector3 getHalfSize(void) const - { - switch (mExtent) - { - case EXTENT_NULL: - return Vector3::ZERO; - - case EXTENT_FINITE: - return (mMaximum - mMinimum) * 0.5; - - case EXTENT_INFINITE: - return Vector3( - Math::POS_INFINITY, - Math::POS_INFINITY, - Math::POS_INFINITY); - - default: // shut up compiler - assert( false && "Never reached" ); - return Vector3::ZERO; - } - } - - /** Tests whether the given point contained by this box. - */ - bool contains(const Vector3& v) const - { - if (isNull()) - return false; - if (isInfinite()) - return true; - - return mMinimum.x <= v.x && v.x <= mMaximum.x && - mMinimum.y <= v.y && v.y <= mMaximum.y && - mMinimum.z <= v.z && v.z <= mMaximum.z; - } - - /** Returns the squared minimum distance between a given point and any part of the box. - * This is faster than distance since avoiding a squareroot, so use if you can. */ - Real squaredDistance(const Vector3& v) const - { - - if (this->contains(v)) - return 0; - else - { - Vector3 maxDist(0,0,0); - - if (v.x < mMinimum.x) - maxDist.x = mMinimum.x - v.x; - else if (v.x > mMaximum.x) - maxDist.x = v.x - mMaximum.x; - - if (v.y < mMinimum.y) - maxDist.y = mMinimum.y - v.y; - else if (v.y > mMaximum.y) - maxDist.y = v.y - mMaximum.y; - - if (v.z < mMinimum.z) - maxDist.z = mMinimum.z - v.z; - else if (v.z > mMaximum.z) - maxDist.z = v.z - mMaximum.z; - - return maxDist.squaredLength(); - } - } - - /** Returns the minimum distance between a given point and any part of the box. */ - Real distance (const Vector3& v) const - { - return Ogre::Math::Sqrt(squaredDistance(v)); - } - - /** Tests whether another box contained by this box. - */ - bool contains(const AxisAlignedBox& other) const - { - if (other.isNull() || this->isInfinite()) - return true; - - if (this->isNull() || other.isInfinite()) - return false; - - return this->mMinimum.x <= other.mMinimum.x && - this->mMinimum.y <= other.mMinimum.y && - this->mMinimum.z <= other.mMinimum.z && - other.mMaximum.x <= this->mMaximum.x && - other.mMaximum.y <= this->mMaximum.y && - other.mMaximum.z <= this->mMaximum.z; - } - - /** Tests 2 boxes for equality. - */ - bool operator== (const AxisAlignedBox& rhs) const - { - if (this->mExtent != rhs.mExtent) - return false; - - if (!this->isFinite()) - return true; - - return this->mMinimum == rhs.mMinimum && - this->mMaximum == rhs.mMaximum; - } - - /** Tests 2 boxes for inequality. - */ - bool operator!= (const AxisAlignedBox& rhs) const - { - return !(*this == rhs); - } - - // special values - static const AxisAlignedBox BOX_NULL; - static const AxisAlignedBox BOX_INFINITE; - - - }; - - /** @} */ - /** @} */ -} // namespace Ogre - -#endif diff --git a/OgreMain/include/OgreBillboard.h b/OgreMain/include/OgreBillboard.h deleted file mode 100644 index 7d9d1ce8071..00000000000 --- a/OgreMain/include/OgreBillboard.h +++ /dev/null @@ -1,216 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Billboard_H__ -#define __Billboard_H__ - -#include "OgrePrerequisites.h" - -#include "OgreColourValue.h" -#include "OgreCommon.h" -#include "OgreHeaderPrefix.h" -#include "OgreMath.h" -#include "OgreVector.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - - /** A billboard is a primitive which always faces the camera in every frame. - - Billboards can be used for special effects or some other trickery which requires the - triangles to always facing the camera no matter where it is. Ogre groups billboards into - sets for efficiency, so you should never create a billboard on it's own (it's ok to have a - set of one if you need it). - @par - Billboards have their geometry generated every frame depending on where the camera is. It is most - beneficial for all billboards in a set to be identically sized since Ogre can take advantage of this and - save some calculations - useful when you have sets of hundreds of billboards as is possible with special - effects. You can deviate from this if you wish (example: a smoke effect would probably have smoke puffs - expanding as they rise, so each billboard will legitimately have it's own size) but be aware the extra - overhead this brings and try to avoid it if you can. - @par - Billboards are just the mechanism for rendering a range of effects such as particles. It is other classes - which use billboards to create their individual effects, so the methods here are quite generic. - @see - BillboardSet - */ - - class _OgreExport Billboard : public FXAlloc - { - friend class BillboardSet; - friend class BillboardParticleRenderer; - private: - bool mOwnDimensions; - bool mUseTexcoordRect; - uint16 mTexcoordIndex; /// Index into the BillboardSet array of texture coordinates - FloatRect mTexcoordRect; /// Individual texture coordinates - float mWidth; - float mHeight; - public: - // Note the intentional public access to main internal variables used at runtime - // Forcing access via get/set would be too costly for 000's of billboards - Vector3 mPosition; - /// Normalised direction vector - Vector3 mDirection; - RGBA mColour; - Radian mRotation; - - /** Default constructor. - */ - Billboard(); - - /** Default destructor. - */ - ~Billboard(); - - /** Normal constructor as called by BillboardSet. - */ - Billboard(const Vector3& position, BillboardSet* owner, const ColourValue& colour = ColourValue::White); - - /** Get the rotation of the billboard. - - This rotation is relative to the center of the billboard. - */ - const Radian& getRotation(void) const { return mRotation; } - - /** Set the rotation of the billboard. - - This rotation is relative to the center of the billboard. - */ - void setRotation(const Radian& rotation) { mRotation = rotation; } - - /** Set the position of the billboard. - - This position is relative to a point on the quad which is the billboard. Depending on the BillboardSet, - this may be the center of the quad, the top-left etc. See BillboardSet::setBillboardOrigin for more info. - */ - void setPosition(const Vector3& position) { mPosition = position; } - - /// @overload - void setPosition(Real x, Real y, Real z) { setPosition({x, y, z}); } - - /** Get the position of the billboard. - - This position is relative to a point on the quad which is the billboard. Depending on the BillboardSet, - this may be the center of the quad, the top-left etc. See BillboardSet::setBillboardOrigin for more info. - */ - const Vector3& getPosition(void) const { return mPosition; } - - /** Sets the width and height for this billboard. - - Note that it is most efficient for every billboard in a BillboardSet to have the same dimensions. If you - choose to alter the dimensions of an individual billboard the set will be less efficient. Do not call - this method unless you really need to have different billboard dimensions within the same set. Otherwise - just call the BillboardSet::setDefaultDimensions method instead. - */ - void setDimensions(float width, float height); - - /** Resets this Billboard to use the parent BillboardSet's dimensions instead of it's own. */ - void resetDimensions(void) { mOwnDimensions = false; } - /** Sets the colour of this billboard. - - Billboards can be tinted based on a base colour. This allows variations in colour irrespective of the - base colour of the material allowing more varied billboards. The default colour is white. - The tinting is effected using vertex colours. - */ - void setColour(const ColourValue& colour) { mColour = colour.getAsBYTE(); } - - /** Gets the colour of this billboard. - */ - ColourValue getColour(void) const { return ColourValue((const uchar*)&mColour); } - - /** Returns true if this billboard deviates from the BillboardSet's default dimensions (i.e. if the - Billboard::setDimensions method has been called for this instance). - @see - Billboard::setDimensions - */ - bool hasOwnDimensions(void) const { return mOwnDimensions; } - - /** Retrieves the billboard's personal width, if hasOwnDimensions is true. */ - float getOwnWidth(void) const { return mWidth; } - - /** Retrieves the billboard's personal height, if hasOwnDimensions is true. */ - float getOwnHeight(void) const { return mHeight; } - - /** Returns true if this billboard use individual texture coordinate rect (i.e. if the - Billboard::setTexcoordRect method has been called for this instance), or returns - false if use texture coordinates defined in the parent BillboardSet's texture - coordinates array (i.e. if the Billboard::setTexcoordIndex method has been called - for this instance). - @see - Billboard::setTexcoordIndex() - Billboard::setTexcoordRect() - */ - bool isUseTexcoordRect(void) const { return mUseTexcoordRect; } - - /** setTexcoordIndex() sets which texture coordinate rect this billboard will use - when rendering. The parent billboard set may contain more than one, in which - case a billboard can be textured with different pieces of a larger texture - sheet very efficiently. - @see - BillboardSet::setTextureCoords() - */ - void setTexcoordIndex(uint16 texcoordIndex); - - /** getTexcoordIndex() returns the previous value set by setTexcoordIndex(). - The default value is 0, which is always a valid texture coordinate set. - - This value is useful only when isUseTexcoordRect return false. - */ - uint16 getTexcoordIndex(void) const { return mTexcoordIndex; } - - /** sets the individual texture coordinate rect of this billboard will use when rendering. - The parent billboard set may contain more than one, in - which case a billboard can be textured with different pieces of a larger texture - sheet very efficiently. - */ - void setTexcoordRect(const FloatRect& texcoordRect); - - /// @overload - void setTexcoordRect(float u0, float v0, float u1, float v1) { setTexcoordRect({u0, v0, u1, v1}); } - - /** getTexcoordRect() returns the previous value set by setTexcoordRect(). - - This value is useful only when isUseTexcoordRect returns true. - */ - const FloatRect& getTexcoordRect(void) const { return mTexcoordRect; } - }; - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreBillboardChain.h b/OgreMain/include/OgreBillboardChain.h deleted file mode 100644 index 74ba2015aad..00000000000 --- a/OgreMain/include/OgreBillboardChain.h +++ /dev/null @@ -1,365 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -// Thanks to Vincent Cantin (karmaGfa) for the original implementation of this -// class, although it has now been mostly rewritten - -#ifndef _BillboardChain_H__ -#define _BillboardChain_H__ - -#include "OgrePrerequisites.h" - -#include "OgreMovableObject.h" -#include "OgreRenderable.h" -#include "OgreResourceGroupManager.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - - /** Allows the rendering of a chain of connected billboards. - - A billboard chain operates much like a traditional billboard, i.e. its - segments always face the camera; the difference being that instead of - a set of disconnected quads, the elements in this class are connected - together in a chain which must always stay in a continuous strip. This - kind of effect is useful for creating effects such as trails, beams, - lightning effects, etc. - @par - A single instance of this class can actually render multiple separate - chain segments in a single render operation, provided they all use the - same material. To clarify the terminology: a 'segment' is a separate - sub-part of the chain with its own start and end (called the 'head' - and the 'tail'). An 'element' is a single position / colour / texcoord - entry in a segment. You can add items to the head of a chain, and - remove them from the tail, very efficiently. Each segment has a max - size, and if adding an element to the segment would exceed this size, - the tail element is automatically removed and re-used as the new item - on the head. - @par - This class has no auto-updating features to do things like alter the - colour of the elements or to automatically add / remove elements over - time - you have to do all this yourself as a user of the class. - Subclasses can however be used to provide this kind of behaviour - automatically. @see RibbonTrail - */ - class _OgreExport BillboardChain : public MovableObject, public Renderable - { - bool getCastsShadows(void) const override { return getCastShadows(); } - public: - - /** Contains the data of an element of the BillboardChain. - */ - class _OgreExport Element - { - - public: - Element() {} - - Element(const Vector3& position, float width, float texCoord, const ColourValue& colour, - const Quaternion& orientation); - - Vector3 position; - float width; - /// U or V texture coord depending on options - float texCoord; - ColourValue colour; - /// Only used when mFaceCamera == false - Quaternion orientation; - }; - - /** Constructor (don't use directly, use factory) - @param name The name to give this object - @param maxElements The maximum number of elements per chain - @param numberOfChains The number of separate chain segments contained in this object - @param useTextureCoords If true, use texture coordinates from the chain elements - @param useColours If true, use vertex colours from the chain elements - @param dynamic If true, buffers are created with the intention of being updated - */ - BillboardChain(const String& name, size_t maxElements = 20, size_t numberOfChains = 1, - bool useTextureCoords = true, bool useColours = true, bool dynamic = true); - - ~BillboardChain(); - - /** Set the maximum number of chain elements per chain - */ - virtual void setMaxChainElements(size_t maxElements); - /** Get the maximum number of chain elements per chain - */ - virtual size_t getMaxChainElements(void) const { return mMaxElementsPerChain; } - /** Set the number of chain segments (this class can render multiple chains - at once using the same material). - */ - virtual void setNumberOfChains(size_t numChains); - /** Get the number of chain segments (this class can render multiple chains - at once using the same material). - */ - virtual size_t getNumberOfChains(void) const { return mChainCount; } - - /** Sets whether texture coordinate information should be included in the - final buffers generated. - @note You must use either texture coordinates or vertex colour since the - vertices have no normals and without one of these there is no source of - colour for the vertices. - */ - virtual void setUseTextureCoords(bool use); - /** Gets whether texture coordinate information should be included in the - final buffers generated. - */ - virtual bool getUseTextureCoords(void) const { return mUseTexCoords; } - - /** The direction in which texture coordinates from elements of the - chain are used. - */ - enum TexCoordDirection - { - /// Tex coord in elements is treated as the 'u' texture coordinate - TCD_U, - /// Tex coord in elements is treated as the 'v' texture coordinate - TCD_V - }; - /** Sets the direction in which texture coords specified on each element - are deemed to run along the length of the chain. - @param dir The direction, default is TCD_U. - */ - virtual void setTextureCoordDirection(TexCoordDirection dir); - /** Gets the direction in which texture coords specified on each element - are deemed to run. - */ - virtual TexCoordDirection getTextureCoordDirection(void) { return mTexCoordDir; } - - /** Set the range of the texture coordinates generated across the width of - the chain elements. - @param start Start coordinate, default 0.0 - @param end End coordinate, default 1.0 - */ - virtual void setOtherTextureCoordRange(Real start, Real end); - /** Get the range of the texture coordinates generated across the width of - the chain elements. - */ - virtual const Real* getOtherTextureCoordRange(void) const { return mOtherTexCoordRange; } - - /** Sets whether vertex colour information should be included in the - final buffers generated. - @note You must use either texture coordinates or vertex colour since the - vertices have no normals and without one of these there is no source of - colour for the vertices. - */ - virtual void setUseVertexColours(bool use); - /** Gets whether vertex colour information should be included in the - final buffers generated. - */ - virtual bool getUseVertexColours(void) const { return mUseVertexColour; } - - /** Set the auto update state - - @copydetails BillboardSet::setAutoUpdate - */ - void setAutoUpdate(bool autoUpdate); - - /** Return the auto update state */ - bool getAutoUpdate(void) const { return mAutoUpdate; } - - /** Add an element to the 'head' of a chain. - - If this causes the number of elements to exceed the maximum elements - per chain, the last element in the chain (the 'tail') will be removed - to allow the additional element to be added. - @param chainIndex The index of the chain - @param billboardChainElement The details to add - */ - virtual void addChainElement(size_t chainIndex, - const Element& billboardChainElement); - /** Remove an element from the 'tail' of a chain. - @param chainIndex The index of the chain - */ - virtual void removeChainElement(size_t chainIndex); - /** Update the details of an existing chain element. - @param chainIndex The index of the chain - @param elementIndex The element index within the chain, measured from - the 'head' of the chain - @param billboardChainElement The details to set - */ - virtual void updateChainElement(size_t chainIndex, size_t elementIndex, - const Element& billboardChainElement); - /** Get the detail of a chain element. - @param chainIndex The index of the chain - @param elementIndex The element index within the chain, measured from - the 'head' of the chain - */ - virtual const Element& getChainElement(size_t chainIndex, size_t elementIndex) const; - - /** Returns the number of chain elements. */ - virtual size_t getNumChainElements(size_t chainIndex) const; - - /** Remove all elements of a given chain (but leave the chain intact). */ - virtual void clearChain(size_t chainIndex); - /** Remove all elements from all chains (but leave the chains themselves intact). */ - virtual void clearAllChains(void); - - /** Sets whether the billboard should always be facing the camera or a custom direction - set by each point element. - - Billboards facing the camera are useful for smoke trails, light beams, etc by - simulating a cylinder. However, because of this property, wide trails can cause - several artefacts unless the head is properly covered. - Therefore, non-camera-facing billboards are much more convenient for leaving big - trails of movement from thin objects, for example a sword swing as seen in many - fighting games. - @param faceCamera True to be always facing the camera (Default value: True) - @param normalVector Only used when faceCamera == false. Must be a non-zero vector. - This vector is the "point of reference" for each point orientation. For example, - if normalVector is Vector3::UNIT_Z, and the point's orientation is an identity - matrix, the segment corresponding to that point will be facing towards UNIT_Z - This vector is internally normalized. - */ - void setFaceCamera( bool faceCamera, const Vector3 &normalVector=Vector3::UNIT_X ); - - /// Get the material name in use - virtual const String& getMaterialName(void) const { return mMaterial->getName(); } - /// Set the material name to use for rendering - virtual void setMaterialName( const String& name, const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME ); - - - // Overridden members follow - Real getSquaredViewDepth(const Camera* cam) const override; - Real getBoundingRadius(void) const override; - const AxisAlignedBox& getBoundingBox(void) const override; - const MaterialPtr& getMaterial(void) const override; - const String& getMovableType(void) const override; - void _updateRenderQueue(RenderQueue *) override; - void getRenderOperation(RenderOperation &) override; - bool preRender(SceneManager* sm, RenderSystem* rsys) override; - void getWorldTransforms(Matrix4 *) const override; - const LightList& getLights(void) const override; - /// @copydoc MovableObject::visitRenderables - void visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables = false) override; - - - - protected: - - /// Maximum length of each chain - uint32 mMaxElementsPerChain; - /// Number of chains - uint32 mChainCount; - /// Use texture coords? - bool mUseTexCoords; - /// Use vertex colour? - bool mUseVertexColour; - /// Tell if vertex buffer should be update automatically. - bool mAutoUpdate; - /// Is the vertex declaration dirty? - bool mVertexDeclDirty; - /// Do the buffers need recreating? - bool mBuffersNeedRecreating; - /// Do the bounds need redefining? - mutable bool mBoundsDirty; - /// Is the index buffer dirty? - bool mIndexContentDirty; - /// Is the vertex buffer dirty? - bool mVertexContentDirty; - /// AABB - mutable AxisAlignedBox mAABB; - /// Bounding radius - mutable Real mRadius; - /// Material - MaterialPtr mMaterial; - /// Texture coord direction - TexCoordDirection mTexCoordDir; - /// Other texture coord range - Real mOtherTexCoordRange[2]; - /// When true, the billboards always face the camera - bool mFaceCamera; - - typedef std::vector ElementList; - /// The list holding the chain elements - ElementList mChainElementList; - - /** Simple struct defining a chain segment by referencing a subset of - the preallocated buffer (which will be mMaxElementsPerChain * mChainCount - long), by it's chain index, and a head and tail value which describe - the current chain. The buffer subset wraps at mMaxElementsPerChain - so that head and tail can move freely. head and tail are inclusive, - when the chain is empty head and tail are filled with high-values. - */ - struct ChainSegment - { - /// The start of this chains subset of the buffer - size_t start; - /// The 'head' of the chain, relative to start - size_t head; - /// The 'tail' of the chain, relative to start - size_t tail; - }; - typedef std::vector ChainSegmentList; - ChainSegmentList mChainSegmentList; - - /// Chain segment has no elements - static const size_t SEGMENT_EMPTY; - private: - /// Used when mFaceCamera == false; determines the billboard's "normal". i.e. - /// when the orientation is identity, the billboard is perpendicular to this - /// vector - Vector3 mNormalBase; - /// Camera last used to build the vertex buffer - Camera *mVertexCameraUsed; - /// Vertex data - std::unique_ptr mVertexData; - /// Index data (to allow multiple unconnected chains) - std::unique_ptr mIndexData; - - /// Setup the STL collections - void setupChainContainers(void); - /// Setup vertex declaration - virtual void setupVertexDeclaration(void); - /// Setup buffers - virtual void setupBuffers(void); - /// Update the contents of the vertex buffer - virtual void updateVertexBuffer(Camera* cam); - /// Update the contents of the index buffer - virtual void updateIndexBuffer(void); - virtual void updateBoundingBox(void) const; - }; - /** @} */ - /** @} */ - -} // namespace - -#include "OgreHeaderSuffix.h" - -#endif - - diff --git a/OgreMain/include/OgreBillboardParticleRenderer.h b/OgreMain/include/OgreBillboardParticleRenderer.h deleted file mode 100644 index 877572bafa0..00000000000 --- a/OgreMain/include/OgreBillboardParticleRenderer.h +++ /dev/null @@ -1,170 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __BillboardParticleRenderer_H__ -#define __BillboardParticleRenderer_H__ - -#include "OgrePrerequisites.h" -#include "OgreParticleSystemRenderer.h" -#include "OgreBillboardSet.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - - /** Specialisation of ParticleSystemRenderer to render particles using - a BillboardSet. - - This renderer has a few more options than the standard particle system, - which will be passed to it automatically when the particle system itself - does not understand them. - */ - class _OgreExport BillboardParticleRenderer : public ParticleSystemRenderer - { - /// The billboard set that's doing the rendering - BillboardSet* mBillboardSet; - Vector2 mStacksSlices; - public: - BillboardParticleRenderer(); - ~BillboardParticleRenderer(); - - /// @copydoc BillboardSet::setTextureStacksAndSlices - void setTextureStacksAndSlices(uchar stacks, uchar slices) - { - mStacksSlices = Vector2(stacks, slices); // cache for get call - mBillboardSet->setTextureStacksAndSlices(stacks, slices); - } - - const Vector2& getTextureStacksAndSlices() const { return mStacksSlices; } - - /// @copydoc BillboardSet::setBillboardType - void setBillboardType(BillboardType bbt) { mBillboardSet->setBillboardType(bbt); } - /// @copydoc BillboardSet::getBillboardType - BillboardType getBillboardType(void) const { return mBillboardSet->getBillboardType(); } - /// @copydoc BillboardSet::setUseAccurateFacing - void setUseAccurateFacing(bool acc) { mBillboardSet->setUseAccurateFacing(acc); } - /// @copydoc BillboardSet::getUseAccurateFacing - bool getUseAccurateFacing(void) const { return mBillboardSet->getUseAccurateFacing(); } - /// @copydoc BillboardSet::setBillboardOrigin - void setBillboardOrigin(BillboardOrigin origin) { mBillboardSet->setBillboardOrigin(origin); } - /// @copydoc BillboardSet::getBillboardOrigin - BillboardOrigin getBillboardOrigin(void) const { return mBillboardSet->getBillboardOrigin(); } - /// @copydoc BillboardSet::setBillboardRotationType - void setBillboardRotationType(BillboardRotationType rotationType) - { - mBillboardSet->setBillboardRotationType(rotationType); - } - /// @copydoc BillboardSet::getBillboardRotationType - BillboardRotationType getBillboardRotationType() const - { - return mBillboardSet->getBillboardRotationType(); - } - /// @copydoc BillboardSet::setCommonDirection - void setCommonDirection(const Vector3& vec) { mBillboardSet->setCommonDirection(vec); } - /// @copydoc BillboardSet::getCommonDirection - const Vector3& getCommonDirection(void) const { return mBillboardSet->getCommonDirection(); } - /// @copydoc BillboardSet::setCommonUpVector - void setCommonUpVector(const Vector3& vec) { mBillboardSet->setCommonUpVector(vec); } - /// @copydoc BillboardSet::getCommonUpVector - const Vector3& getCommonUpVector(void) const { return mBillboardSet->getCommonUpVector(); } - /// @copydoc BillboardSet::setPointRenderingEnabled - void setPointRenderingEnabled(bool enabled) { mBillboardSet->setPointRenderingEnabled(enabled); } - /// @copydoc BillboardSet::isPointRenderingEnabled - bool isPointRenderingEnabled(void) const { return mBillboardSet->isPointRenderingEnabled(); } - - /// @copydoc ParticleSystemRenderer::getType - const String& getType(void) const override; - /// @copydoc ParticleSystemRenderer::_updateRenderQueue - void _updateRenderQueue(RenderQueue* queue, - std::vector& currentParticles, bool cullIndividually) override; - /// @copydoc ParticleSystemRenderer::visitRenderables - void visitRenderables(Renderable::Visitor* visitor, bool debugRenderables = false) override - { - mBillboardSet->visitRenderables(visitor, debugRenderables); - } - void _setMaterial(MaterialPtr& mat) override { mBillboardSet->setMaterial(mat); } - /// @copydoc ParticleSystemRenderer::_notifyCurrentCamera - void _notifyCurrentCamera(Camera* cam) override { mBillboardSet->_notifyCurrentCamera(cam); } - /// @copydoc ParticleSystemRenderer::_notifyParticleQuota - void _notifyParticleQuota(size_t quota) override { mBillboardSet->setPoolSize(quota); } - /// @copydoc ParticleSystemRenderer::_notifyAttached - void _notifyAttached(Node* parent, bool isTagPoint = false) override - { - mBillboardSet->_notifyAttached(parent, isTagPoint); - } - /// @copydoc ParticleSystemRenderer::_notifyDefaultDimensions - void _notifyDefaultDimensions(Real width, Real height) override - { - mBillboardSet->setDefaultDimensions(width, height); - } - /// @copydoc ParticleSystemRenderer::setRenderQueueGroup - void setRenderQueueGroup(uint8 queueID) override { mBillboardSet->setRenderQueueGroup(queueID); } - /// @copydoc MovableObject::setRenderQueueGroupAndPriority - void setRenderQueueGroupAndPriority(uint8 queueID, ushort priority) override - { - mBillboardSet->setRenderQueueGroupAndPriority(queueID, priority); - } - /// @copydoc ParticleSystemRenderer::setKeepParticlesInLocalSpace - void setKeepParticlesInLocalSpace(bool keepLocal) override - { - mBillboardSet->setBillboardsInWorldSpace(!keepLocal); - } - /// @copydoc ParticleSystemRenderer::_getSortMode - SortMode _getSortMode(void) const override { return mBillboardSet->_getSortMode(); } - - /// Access BillboardSet in use - BillboardSet* getBillboardSet(void) const { return mBillboardSet; } - - void _notifyBoundingBox(const AxisAlignedBox& aabb) override; - - void _notifyCastShadows(bool enabled) override { mBillboardSet->setCastShadows(enabled); } - }; - - /** Factory class for BillboardParticleRenderer */ - class _OgreExport BillboardParticleRendererFactory : public ParticleSystemRendererFactory - { - public: - /// @copydoc FactoryObj::getType - const String& getType() const override; - /// @copydoc FactoryObj::createInstance - ParticleSystemRenderer* createInstance( const String& name ) override; - }; - /** @} */ - /** @} */ - -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif // __BillboardParticleRenderer_H__ - diff --git a/OgreMain/include/OgreBillboardSet.h b/OgreMain/include/OgreBillboardSet.h deleted file mode 100644 index 5372da5c5b1..00000000000 --- a/OgreMain/include/OgreBillboardSet.h +++ /dev/null @@ -1,812 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __BillboardSet_H__ -#define __BillboardSet_H__ - -#include "OgrePrerequisites.h" - -#include "OgreMovableObject.h" -#include "OgreRenderable.h" -#include "OgreCommon.h" -#include "OgreResourceGroupManager.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - - /** Enum covering what exactly a billboard's position means (center, - top-left etc). - - This setting controls the fine tuning of where a billboard appears in relation to it's - position. It could be that a billboard's position represents it's center (e.g. for fireballs), - it could mean the center of the bottom edge (e.g. a tree which is positioned on the ground), - the top-left corner (e.g. a cursor). - */ - enum BillboardOrigin - { - BBO_TOP_LEFT, - BBO_TOP_CENTER, - BBO_TOP_RIGHT, - BBO_CENTER_LEFT, - BBO_CENTER, - BBO_CENTER_RIGHT, - BBO_BOTTOM_LEFT, - BBO_BOTTOM_CENTER, - BBO_BOTTOM_RIGHT - }; - /** The rotation type of billboard. - * - * By default, billboard particles will rotate the texture coordinates to according with particle - * rotation. But rotate texture coordinates has some disadvantage, e.g. the corners of the texture will - * lost after rotate, and the corners of the billboard will fill with unwanted texture area when using - * wrap address mode or sub-texture sampling. This settings allow you specifying other rotation type. - */ - enum BillboardRotationType - { - /// Rotate the billboard's vertices around their facing direction - BBR_VERTEX, - /// Rotate the billboard's texture coordinates - BBR_TEXCOORD - }; - /** The type of billboard to use. */ - enum BillboardType - { - /// Standard point billboard (default), always faces the camera completely and is always upright - BBT_POINT, - /// Billboards are oriented around a shared direction vector (used as Y axis) and only rotate around this to face the camera - BBT_ORIENTED_COMMON, - /// Billboards are oriented around their own direction vector (their own Y axis) and only rotate around this to face the camera - BBT_ORIENTED_SELF, - /// Billboards are perpendicular to a shared direction vector (used as Z axis, the facing direction) and X, Y axis are determined by a shared up-vertor - BBT_PERPENDICULAR_COMMON, - /// Billboards are perpendicular to their own direction vector (their own Z axis, the facing direction) and X, Y axis are determined by a shared up-vertor - BBT_PERPENDICULAR_SELF - }; - - /** A collection of billboards (faces which are always facing the given direction) with the same (default) dimensions, material - and which are fairly close proximity to each other. - - Billboards are rectangles made up of 2 tris which are always facing the given direction. They are typically used - for special effects like particles. This class collects together a set of billboards with the same (default) dimensions, - material and relative locality in order to process them more efficiently. The entire set of billboards will be - culled as a whole (by default, although this can be changed if you want a large set of billboards - which are spread out and you want them culled individually), individual Billboards have locations which are relative to the set (which itself derives it's - position from the SceneNode it is attached to since it is a MoveableObject), they will be rendered as a single rendering operation, - and some calculations will be sped up by the fact that they use the same dimensions so some workings can be reused. - @par - A BillboardSet can be created using the SceneManager::createBillboardSet method. They can also be used internally - by other classes to create effects. - @note - Billboard bounds are only automatically calculated when you create them. - If you modify the position of a billboard you may need to call - _updateBounds if the billboard moves outside the original bounds. - Similarly, the bounds do no shrink when you remove a billboard, - if you want them to call _updateBounds, but note this requires a - potentially expensive examination of every billboard in the set. - */ - class _OgreExport BillboardSet : public MovableObject, public Renderable - { - protected: - /** Private constructor (instances cannot be created directly). - */ - BillboardSet(); - - bool getCastsShadows(void) const override { return getCastShadows(); } - - /// Bounds of all billboards in this set - AxisAlignedBox mAABB; - /// Bounding radius - Real mBoundingRadius; - - /// Origin of each billboard - BillboardOrigin mOriginType; - /// Rotation type of each billboard - BillboardRotationType mRotationType; - - /// Default width of each billboard - Real mDefaultWidth; - /// Default height of each billboard - Real mDefaultHeight; - - /// Pointer to the material to use - MaterialPtr mMaterial; - - /// Flag indicating whether to autoextend pool - bool mAutoExtendPool; - - /// Flag indicating whether the billboards has to be sorted - bool mSortingEnabled; - - /// Use 'true' billboard to cam position facing, rather than camera direcion - bool mAccurateFacing; - - bool mWorldSpace; - - typedef std::vector BillboardPool; - - /** Active billboard count. - - This allows very fast activation / deactivation of billboards - (required for particle systems etc.) as well as reuse of Billboard instances in the pool - without construction & destruction which avoids memory thrashing. - */ - size_t mActiveBillboards; - - /** Pool of billboard instances for use and reuse. - - This vector will be preallocated with the estimated size of the set,and will extend as required. - */ - BillboardPool mBillboardPool; - - /// The vertex position data for all billboards in this set. - std::unique_ptr mVertexData; - /// Shortcut to main buffer (positions, colours, texture coords) - HardwareVertexBufferSharedPtr mMainBuf; - /// Locked pointer to buffer - float* mLockPtr; - /// Boundary offsets based on origin and camera orientation - /// Vector3 vLeftOff, vRightOff, vTopOff, vBottomOff; - /// Final vertex offsets, used where sizes all default to save calcs - Vector3 mVOffset[4]; - /// Current camera - Camera* mCurrentCamera; - /// Parametric offsets of origin - Real mLeftOff, mRightOff, mTopOff, mBottomOff; - /// Camera axes in billboard space - Vector3 mCamX, mCamY; - /// Camera direction in billboard space - Vector3 mCamDir; - /// Camera orientation in billboard space - Quaternion mCamQ; - /// Camera position in billboard space - Vector3 mCamPos; - - /// The vertex index data for all billboards in this set (1 set only) - std::unique_ptr mIndexData; - - /// Flag indicating whether each billboard should be culled separately (default: false) - bool mCullIndividual; - - typedef std::vector< Ogre::FloatRect > TextureCoordSets; - TextureCoordSets mTextureCoords; - - /// The type of billboard to render - BillboardType mBillboardType; - - /// Common direction for billboards of type BBT_ORIENTED_COMMON and BBT_PERPENDICULAR_COMMON - Vector3 mCommonDirection; - /// Common up-vector for billboards of type BBT_PERPENDICULAR_SELF and BBT_PERPENDICULAR_COMMON - Vector3 mCommonUpVector; - - /// Internal method for culling individual billboards - inline bool billboardVisible(Camera* cam, const Billboard& bill); - - /// Number of visible billboards (will be == getNumBillboards if mCullIndividual == false) - unsigned short mNumVisibleBillboards; - - /// Internal method for increasing pool size - void increasePool(size_t size); - - - //----------------------------------------------------------------------- - // The internal methods which follow are here to allow maximum flexibility as to - // when various components of the calculation are done. Depending on whether the - // billboards are of fixed size and whether they are point or oriented type will - // determine how much calculation has to be done per-billboard. NOT a one-size fits all approach. - //----------------------------------------------------------------------- - /** Internal method for generating billboard corners. - - Optional parameter pBill is only present for type BBT_ORIENTED_SELF and BBT_PERPENDICULAR_SELF - */ - void genBillboardAxes(Vector3* pX, Vector3 *pY, const Billboard* pBill = 0); - - /** Internal method, generates parametric offsets based on origin. - */ - void getParametricOffsets(Real& left, Real& right, Real& top, Real& bottom); - - /** Internal method for generating vertex data. - @param offsets Array of 4 Vector3 offsets - @param pBillboard Reference to billboard - */ - void genQuadVertices(const Vector3* const offsets, const Billboard& pBillboard); - - void genPointVertices(const Billboard& pBillboard); - - /** Internal method generates vertex offsets. - - Takes in parametric offsets as generated from getParametericOffsets, width and height values - and billboard x and y axes as generated from genBillboardAxes. - Fills output array of 4 vectors with vector offsets - from origin for left-top, right-top, left-bottom, right-bottom corners. - */ - static void genVertOffsets(Real inleft, Real inright, Real intop, Real inbottom, - Real width, Real height, - const Vector3& x, const Vector3& y, Vector3* pDestVec); - - - /** Sort by direction functor */ - struct SortByDirectionFunctor - { - /// Direction to sort in - Vector3 sortDir; - - SortByDirectionFunctor(const Vector3& dir); - float operator()(Billboard* bill) const; - }; - - /** Sort by distance functor */ - struct SortByDistanceFunctor - { - /// Position to sort in - Vector3 sortPos; - - SortByDistanceFunctor(const Vector3& pos); - float operator()(Billboard* bill) const; - }; - - /// Use point rendering? - bool mPointRendering; - - - - private: - /// Flag indicating whether the HW buffers have been created. - bool mBuffersCreated; - /// The number of billboard in the pool. - size_t mPoolSize; - /// Is external billboard data in use? - bool mExternalData; - /// Tell if vertex buffer should be update automatically. - bool mAutoUpdate; - /// True if the billboard data changed. Will cause vertex buffer update. - bool mBillboardDataChanged; - - /** Internal method creates vertex and index buffers. - */ - void _createBuffers(void); - /** Internal method destroys vertex and index buffers. - */ - void _destroyBuffers(void); - - public: - - /** Usual constructor - this is called by the SceneManager. - @param name - The name to give the billboard set (must be unique) - @param poolSize - The initial size of the billboard pool. Estimate of the number of billboards - which will be required, and pass it using this parameter. The set will - preallocate this number to avoid memory fragmentation. The default behaviour - once this pool has run out is to double it. - @param externalDataSource - If @c true, the source of data for drawing the - billboards will not be the internal billboard list, but external - data. When driving the billboard from external data, you must call - _notifyCurrentCamera to reorient the billboards, setPoolSize to set - the maximum billboards you want to use, beginBillboards to - start the update, and injectBillboard per billboard, - followed by endBillboards. - @see - BillboardSet::setAutoextend - */ - BillboardSet( const String& name, unsigned int poolSize = 20, - bool externalDataSource = false); - - virtual ~BillboardSet(); - - /** Creates a new billboard and adds it to this set. - - Behaviour once the billboard pool has been exhausted depends on the - BillboardSet::setAutoextend option. - @param position - The position of the new billboard relative to the center of the set - @param colour - Optional base colour of the billboard. - @return - On success, a pointer to a newly created Billboard is - returned. - @par - On failure (i.e. no more space and can't autoextend), - @c NULL is returned. - @see - BillboardSet::setAutoextend - */ - Billboard* createBillboard( - const Vector3& position, - const ColourValue& colour = ColourValue::White ); - - /// @overload - Billboard* createBillboard(Real x, Real y, Real z, const ColourValue& colour = ColourValue::White) - { - return createBillboard(Vector3(x, y, z), colour); - } - - /** Returns the number of active billboards which currently make up this set. - */ - int getNumBillboards(void) const { return static_cast(mActiveBillboards); } - - /** Tells the set whether to allow automatic extension of the pool of billboards. - - A BillboardSet stores a pool of pre-constructed billboards which are used as needed when - a new billboard is requested. This allows applications to create / remove billboards efficiently - without incurring construction / destruction costs (a must for sets with lots of billboards like - particle effects). This method allows you to configure the behaviour when a new billboard is requested - but the billboard pool has been exhausted. - @par - The default behaviour is to allow the pool to extend (typically this allocates double the current - pool of billboards when the pool is expended), equivalent to calling this method with - autoExtend = true. If you set the parameter to false however, any attempt to create a new billboard - when the pool has expired will simply fail silently, returning a null pointer. - @param autoextend - @c true to double the pool every time it runs out, @c false to fail silently. - */ - void setAutoextend(bool autoextend) { mAutoExtendPool = autoextend; } - - /** Returns true if the billboard pool automatically extends. - @see - BillboardSet::setAutoextend - */ - bool getAutoextend(void) const { return mAutoExtendPool; } - - /** Enables sorting for this BillboardSet. (default: off) - @param sortenable true to sort the billboards according to their distance to the camera - */ - void setSortingEnabled(bool sortenable) { mSortingEnabled = sortenable; } - - /** Returns true if sorting of billboards is enabled based on their distance from the camera - @see - BillboardSet::setSortingEnabled - */ - bool getSortingEnabled(void) const { return mSortingEnabled; } - - /** Adjusts the size of the pool of billboards available in this set. - - See the BillboardSet::setAutoextend method for full details of the billboard pool. This method adjusts - the preallocated size of the pool. If you try to reduce the size of the pool, the set has the option - of ignoring you if too many billboards are already in use. Bear in mind that calling this method will - incur significant construction / destruction calls so should be avoided in time-critical code. The same - goes for auto-extension, try to avoid it by estimating the pool size correctly up-front. - @param size - The new size for the pool. - */ - void setPoolSize(size_t size); - - /** Returns the current size of the billboard pool. - @return - The current size of the billboard pool. - @see - BillboardSet::setAutoextend - */ - unsigned int getPoolSize() const { return static_cast(mBillboardPool.size()); } - - /** Empties this set of all billboards. - */ - virtual void clear(); - - /** Returns a pointer to the billboard at the supplied index. - - @param index - The index of the billboard that is requested. - @return - On success, a valid pointer to the requested billboard is - returned. - @par - On failure, @c NULL is returned. - */ - virtual Billboard* getBillboard(unsigned int index) const; - - /** Removes the billboard at the supplied index. - */ - virtual void removeBillboard(unsigned int index); - - /** Removes a billboard from the set. - */ - virtual void removeBillboard(Billboard* pBill); - - /// @name Billboard positioning - /// @{ - /** Sets the point which acts as the origin point for all billboards in this set. - - This setting controls the fine tuning of where a billboard appears in relation to it's - position. It could be that a billboard's position represents it's center (e.g. for fireballs), - it could mean the center of the bottom edge (e.g. a tree which is positioned on the ground), - the top-left corner (e.g. a cursor). - - The default setting is #BBO_CENTER. - @param origin - A member of the BillboardOrigin enum specifying the origin for all the billboards in this set. - */ - void setBillboardOrigin(BillboardOrigin origin) { mOriginType = origin; } - - /** Gets the point which acts as the origin point for all billboards in this set. - @return - A member of the BillboardOrigin enum specifying the origin for all the billboards in this set. - */ - BillboardOrigin getBillboardOrigin(void) const { return mOriginType; } - - /** Sets billboard rotation type. - - This setting controls the billboard rotation type, you can deciding rotate the billboard's vertices - around their facing direction or rotate the billboard's texture coordinates. - - The default settings is #BBR_TEXCOORD. - @param rotationType - A member of the BillboardRotationType enum specifying the rotation type for all the billboards in this set. - */ - void setBillboardRotationType(BillboardRotationType rotationType) { mRotationType = rotationType; } - - /** Sets billboard rotation type. - @return - A member of the BillboardRotationType enum specifying the rotation type for all the billboards in this set. - */ - BillboardRotationType getBillboardRotationType(void) const { return mRotationType; } - - /** Sets the default dimensions of the billboards in this set. - - All billboards in a set are created with these default dimensions. The set will render most efficiently if - all the billboards in the set are the default size. It is possible to alter the size of individual - billboards at the expense of extra calculation. See the Billboard class for more info. - @param width - The new default width for the billboards in this set. - @param height - The new default height for the billboards in this set. - */ - void setDefaultDimensions(Real width, Real height) - { - mDefaultWidth = width; - mDefaultHeight = height; - } - - /** See setDefaultDimensions - this sets 1 component individually. */ - void setDefaultWidth(Real width) { mDefaultWidth = width; } - /** See setDefaultDimensions - this gets 1 component individually. */ - Real getDefaultWidth(void) const { return mDefaultWidth; } - /** See setDefaultDimensions - this sets 1 component individually. */ - void setDefaultHeight(Real height) { mDefaultHeight = height; } - /** See setDefaultDimensions - this gets 1 component individually. */ - Real getDefaultHeight(void) const { return mDefaultHeight; } - /// @} - - /** Sets the name of the material to be used for this billboard set. - */ - virtual void setMaterialName( const String& name, const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME ); - - /** Sets the name of the material to be used for this billboard set. - @return The name of the material that is used for this set. - */ - const String& getMaterialName(void) const { return mMaterial->getName(); } - - void _notifyCurrentCamera(Camera* cam) override; - - /** Begin injection of billboard data; applicable when - constructing the BillboardSet for external data use. - @param numBillboards If you know the number of billboards you will be - issuing, state it here to make the update more efficient. - */ - void beginBillboards(size_t numBillboards = 0); - /** Define a billboard. */ - void injectBillboard(const Billboard& bb); - /** Finish defining billboards. */ - void endBillboards(void); - /** Set the bounds of the BillboardSet. - - You may need to call this if you're injecting billboards manually, - and you're relying on the BillboardSet to determine culling. - */ - void setBounds(const AxisAlignedBox& box, Real radius); - - const AxisAlignedBox& getBoundingBox(void) const override { return mAABB; } - Real getBoundingRadius(void) const override { return mBoundingRadius; } - void _updateRenderQueue(RenderQueue* queue) override; - const MaterialPtr& getMaterial(void) const override { return mMaterial; } - - /** Sets the name of the material to be used for this billboard set. - @param material - The new material to use for this set. - */ - virtual void setMaterial( const MaterialPtr& material ); - - - void getRenderOperation(RenderOperation& op) override; - void getWorldTransforms(Matrix4* xform) const override; - - /** Returns whether or not billboards in this are tested individually for culling. */ - bool getCullIndividually(void) const { return mCullIndividual; } - /** Sets whether culling tests billboards in this individually as well as in a group. - - Billboard sets are always culled as a whole group, based on a bounding box which - encloses all billboards in the set. For fairly localised sets, this is enough. However, you - can optionally tell the set to also cull individual billboards in the set, i.e. to test - each individual billboard before rendering. The default is not to do this. - @par - This is useful when you have a large, fairly distributed set of billboards, like maybe - trees on a landscape. You probably still want to group them into more than one - set (maybe one set per section of landscape), which will be culled coarsely, but you also - want to cull the billboards individually because they are spread out. Whilst you could have - lots of single-tree sets which are culled separately, this would be inefficient to render - because each tree would be issued as it's own rendering operation. - @par - By calling this method with a parameter of true, you can have large billboard sets which - are spaced out and so get the benefit of batch rendering and coarse culling, but also have - fine-grained culling so unnecessary rendering is avoided. - @param cullIndividual If true, each billboard is tested before being sent to the pipeline as well - as the whole set having to pass the coarse group bounding test. - */ - void setCullIndividually(bool cullIndividual) { mCullIndividual = cullIndividual; } - - /// @name Billboard orientation - /// @{ - /** Sets the orientation behaviour of the billboards to render. - - The default sort of billboard (#BBT_POINT), always has both x and y axes parallel to - the camera's local axes. This is fine for 'point' style billboards (e.g. flares, - smoke, anything which is symmetrical about a central point) but does not look good for - billboards which have an orientation (e.g. an elongated raindrop). In this case, the - oriented billboards are more suitable (#BBT_ORIENTED_COMMON or #BBT_ORIENTED_SELF) since - they retain an independent Y axis and only the X axis is generated, perpendicular to both - the local Y and the camera Z. - - In some case you might want the billboard has fixed Z axis and doesn't need to face to - camera (e.g. an aureola around the player and parallel to the ground). You can use - #BBT_PERPENDICULAR_SELF which the billboard plane perpendicular to the billboard own - direction. Or #BBT_PERPENDICULAR_COMMON which the billboard plane perpendicular to the - common direction. - @note - #BBT_PERPENDICULAR_SELF and #BBT_PERPENDICULAR_COMMON can't guarantee counterclockwise, you might - use double-side material (#CULL_NONE) to ensure no billboard are culled. - @param bbt The type of billboard to render - */ - void setBillboardType(BillboardType bbt) { mBillboardType = bbt; } - - /** Returns the billboard type in use. */ - BillboardType getBillboardType(void) const { return mBillboardType; } - - /** Use this to specify the common direction given to billboards - - Use #BBT_ORIENTED_COMMON when you want oriented billboards but you know they are always going to - be oriented the same way (e.g. rain in calm weather). It is faster for the system to calculate - the billboard vertices if they have a common direction. - - The common direction also use in #BBT_PERPENDICULAR_COMMON, in this case the common direction - treat as Z axis, and an additional common up-vector was use to determine billboard X and Y - axis. - - @param vec The direction for all billboards. The vector is expected to be unit-length (normalised) - - @see setCommonUpVector - */ - void setCommonDirection(const Vector3& vec) { mCommonDirection = vec; } - - /** Gets the common direction for all billboards (BBT_ORIENTED_COMMON) */ - const Vector3& getCommonDirection(void) const { return mCommonDirection; } - - /** Use this to specify the common up-vector given to billboards - - Use #BBT_PERPENDICULAR_SELF or #BBT_PERPENDICULAR_COMMON when you want oriented billboards - perpendicular to specify direction vector (or, Z axis), and doesn't face to camera. - In this case, we need an additional up-vector to determine the billboard X and Y axis. - The generated billboard plane and X-axis guarantee perpendicular to specify direction. - - The specify direction is billboard own direction when billboard type is #BBT_PERPENDICULAR_SELF, - and it's shared common direction when billboard type is #BBT_PERPENDICULAR_COMMON. - - @param vec The up-vector for all billboards. The vector is expected to be unit-length (normalised) - - @see setCommonDirection - */ - void setCommonUpVector(const Vector3& vec) { mCommonUpVector = vec; } - - /** Gets the common up-vector for all billboards (BBT_PERPENDICULAR_SELF and BBT_PERPENDICULAR_COMMON) */ - const Vector3& getCommonUpVector(void) const { return mCommonUpVector; } - - /** Sets whether or not billboards should use an 'accurate' facing model - - By default, the axes for all billboards are calculated using the - camera's view direction, not the vector from the camera position to - the billboard. The former is faster, and most of the time the difference - is not noticeable. However for some purposes (e.g. very large, static - billboards) the changing billboard orientation when rotating the camera - can be off putting, therefore you can enable this option to use a - more expensive, but more accurate version. - @param acc True to use the slower but more accurate model. Default is false. - */ - void setUseAccurateFacing(bool acc) { mAccurateFacing = acc; } - /** Gets whether or not billboards use an 'accurate' facing model - - based on the vector from each billboard to the camera, rather than - an optimised version using just the camera direction. - */ - bool getUseAccurateFacing(void) const { return mAccurateFacing; } - /// @} - - const String& getMovableType(void) const override; - Real getSquaredViewDepth(const Camera* cam) const override; - - /** Update the bounds of the billboardset */ - virtual void _updateBounds(void); - /** @copydoc Renderable::getLights */ - const LightList& getLights(void) const override; - - /// @copydoc MovableObject::visitRenderables - void visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables = false) override; - - /** Sort the billboard set. Only called when enabled via setSortingEnabled */ - virtual void _sortBillboards( Camera* cam); - - /** Gets the sort mode of this billboard set */ - virtual SortMode _getSortMode(void) const; - - /** Sets whether billboards should be treated as being in world space. - - This is most useful when you are driving the billboard set from - an external data source. - */ - void setBillboardsInWorldSpace(bool ws) { mWorldSpace = ws; } - - /** Gets whether billboards are treated as being in world space. - */ - bool getBillboardsInWorldSpace() { return mWorldSpace; } - - /// @name Billboard UV computation - /// @{ - /** BillboardSet can use custom texture coordinates for various billboards. - This is useful for selecting one of many particle images out of a tiled - texture sheet, or doing flipbook animation within a single texture. - @par - The generic functionality is setTextureCoords(), which will copy the - texture coordinate rects you supply into internal storage for the - billboard set. If your texture sheet is a square grid, you can also - use setTextureStacksAndSlices() for more convenience, which will construct - the set of texture coordinates for you. - @par - When a Billboard is created, it can be assigned a texture coordinate - set from within the sets you specify (that set can also be re-specified - later). When drawn, the billboard will use those texture coordinates, - rather than the full 0-1 range. - - @param coords is a vector of texture coordinates (in UV space) to choose - from for each billboard created in the set. - - Set 'coords' to 0 and/or 'numCoords' to 0 to reset the texture coord - rects to the initial set of a single rectangle spanning 0 through 1 in - both U and V (i e, the entire texture). - @see - BillboardSet::setTextureStacksAndSlices() - Billboard::setTexcoordIndex() - */ - void setTextureCoords(const std::vector& coords); - - /// @deprecated - OGRE_DEPRECATED void setTextureCoords(FloatRect const* coords, uint16 numCoords) - { - setTextureCoords(std::vector(coords, coords + numCoords)); - } - - /** Generate texture coordinate rects for a tiled texture sheet - - A texture sheet is a grid of images that can be used to create simple animations. - This method will generate the uv coordinates for the individual sub-rectangles. - - These can then be addressed by Ogre::Billboard::setTexcoordIndex(). - - If the texture size is 512x512 and 'stacks' is 4 and 'slices' is 8, each sub-rectangle of the texture - would be 128 texels tall and 64 texels wide. - - The numbering counts first across, then down, so top-left is 0, the one to the right - of that is 1, and the lower-right is stacks*slices-1. - - If you need more flexibility, you can use Ogre::BillboardSet::setTextureCoords() instead. - - @param stacks number of vertical tiles (rows) - @param slices number of horizontal tiles (columns) - */ - void setTextureStacksAndSlices( uchar stacks, uchar slices ); - - /** getTextureCoords() returns the current texture coordinate rects in - effect. By default, there is only one texture coordinate rect in the - set, spanning the entire texture from 0 through 1 in each direction. - @see - BillboardSet::setTextureCoords() - */ - const std::vector& getTextureCoords() const { return mTextureCoords; } - /// @} - - /** Set whether or not the BillboardSet will use point rendering - rather than manually generated quads. - - By default a billboardset is rendered by generating geometry for a - textured quad in memory, taking into account the size and - orientation settings, and uploading it to the video card. - The alternative is to use hardware point rendering, which means that - only one position needs to be sent per billboard rather than 4 and - the hardware sorts out how this is rendered based on the render - state. - - Using point rendering is faster than generating quads manually, but - is more restrictive. The following restrictions apply: - - Only the Ogre::BBT_POINT type is supported - - Size and appearance of each billboard is controlled by the material - - Ogre::Pass::setPointSize - - Ogre::Pass::setPointAttenuation - - Ogre::Pass::setPointSpritesEnabled - - Per-billboard size is not supported (stems from the above) - - Per-billboard rotation is not supported, this can only be - controlled through texture unit rotation - - Only Ogre::BBO_CENTER origin is supported - - Per-billboard texture coordinates are not supported - - You will almost certainly want to enable in your material pass - both point attenuation and point sprites if you use this option. - */ - virtual void setPointRenderingEnabled(bool enabled); - - /** Returns whether point rendering is enabled. */ - bool isPointRenderingEnabled(void) const { return mPointRendering; } - - /// Override to return specific type flag - uint32 getTypeFlags(void) const override; - - /** Set the auto update state of this billboard set. - - This methods controls the updating policy of the vertex buffer. - By default auto update is true so the vertex buffer is being update every time this billboard set - is about to be rendered. This behavior best fit when the billboards of this set changes frequently. - When using static or semi-static billboards, it is recommended to set auto update to false. - In that case one should call notifyBillboardDataChanged method to reflect changes made to the - billboards data. - */ - void setAutoUpdate(bool autoUpdate); - - /** Return the auto update state of this billboard set.*/ - bool getAutoUpdate(void) const { return mAutoUpdate; } - - /** When billboard set is not auto updating its GPU buffer, the user is responsible to inform it - about any billboard changes in order to reflect them at the rendering stage. - Calling this method will cause GPU buffers update in the next render queue update. - */ - void notifyBillboardDataChanged(void) { mBillboardDataChanged = true; } - - /** @copydoc MovableObject::_releaseManualHardwareResources */ - void _releaseManualHardwareResources() override { _destroyBuffers(); } - - }; - /** @} */ - /** @} */ - -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif // __BillboardSet_H__ diff --git a/OgreMain/include/OgreBitwise.h b/OgreMain/include/OgreBitwise.h deleted file mode 100644 index 5062e4e04ba..00000000000 --- a/OgreMain/include/OgreBitwise.h +++ /dev/null @@ -1,417 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _Bitwise_H__ -#define _Bitwise_H__ - -#include "OgrePrerequisites.h" - -#ifdef bswap16 -#undef bswap16 -#undef bswap32 -#undef bswap64 -#endif - -#ifndef __has_builtin - // Compatibility with non-clang compilers - #define __has_builtin(x) 0 -#endif - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - - /** Class for manipulating bit patterns. - */ - class Bitwise { - public: - /** Returns value with reversed bytes order. - */ - static OGRE_FORCE_INLINE uint16 bswap16(uint16 arg) - { -#if OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_COMP_VER >= 1310 - return _byteswap_ushort(arg); -#elif (OGRE_COMPILER == OGRE_COMPILER_CLANG && __has_builtin(__builtin_bswap16)) || (OGRE_COMPILER == OGRE_COMPILER_GNUC && OGRE_COMP_VER >= 480) - return __builtin_bswap16(arg); -#else - return ((arg << 8) & 0xFF00) | ((arg >> 8) & 0x00FF); -#endif - } - /** Returns value with reversed bytes order. - */ - static OGRE_FORCE_INLINE uint32 bswap32(uint32 arg) - { -#if OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_COMP_VER >= 1310 - return _byteswap_ulong(arg); -#elif (OGRE_COMPILER == OGRE_COMPILER_CLANG && __has_builtin(__builtin_bswap32)) || (OGRE_COMPILER == OGRE_COMPILER_GNUC && OGRE_COMP_VER >= 430) - return __builtin_bswap32(arg); -#else - return ((arg & 0x000000FF) << 24) | ((arg & 0x0000FF00) << 8) | ((arg >> 8) & 0x0000FF00) | ((arg >> 24) & 0x000000FF); -#endif - } - /** Returns value with reversed bytes order. - */ - static OGRE_FORCE_INLINE uint64 bswap64(uint64 arg) - { -#if OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_COMP_VER >= 1310 - return _byteswap_uint64(arg); -#elif (OGRE_COMPILER == OGRE_COMPILER_CLANG && __has_builtin(__builtin_bswap64)) || (OGRE_COMPILER == OGRE_COMPILER_GNUC && OGRE_COMP_VER >= 430) - return __builtin_bswap64(arg); -#else - union { - uint64 sv; - uint32 ul[2]; - } tmp, result; - tmp.sv = arg; - result.ul[0] = bswap32(tmp.ul[1]); - result.ul[1] = bswap32(tmp.ul[0]); - return result.sv; -#endif - } - - /** Reverses byte order of buffer. Use bswap16/32/64 instead if possible. - */ - static inline void bswapBuffer(void * pData, size_t size) - { - char swapByte; - for(char *p0 = (char*)pData, *p1 = p0 + size - 1; p0 < p1; ++p0, --p1) - { - swapByte = *p0; - *p0 = *p1; - *p1 = swapByte; - } - } - /** Reverses byte order of chunks in buffer, where 'size' is size of one chunk. - */ - static inline void bswapChunks(void * pData, size_t size, size_t count) - { - for(size_t c = 0; c < count; ++c) - { - char swapByte; - for(char *p0 = (char*)pData + c * size, *p1 = p0 + size - 1; p0 < p1; ++p0, --p1) - { - swapByte = *p0; - *p0 = *p1; - *p1 = swapByte; - } - } - } - - /** Returns the most significant bit set in a value. - */ - static OGRE_FORCE_INLINE unsigned int mostSignificantBitSet(unsigned int value) - { - // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F - static const unsigned char msb[16] = { 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4 }; - - unsigned int result = 0; - if(value & 0xFFFF0000) { result += 16;value >>= 16; } - if(value & 0x0000FF00) { result += 8; value >>= 8; } - if(value & 0x000000F0) { result += 4; value >>= 4; } - result += msb[value]; - return result-1; - } - /** Returns the closest power-of-two number greater or equal to value. - @note 0 and 1 are powers of two, so - firstPO2From(0)==0 and firstPO2From(1)==1. - */ - static OGRE_FORCE_INLINE uint32 firstPO2From(uint32 n) - { - --n; - n |= n >> 16; - n |= n >> 8; - n |= n >> 4; - n |= n >> 2; - n |= n >> 1; - ++n; - return n; - } - /** Determines whether the number is power-of-two or not. - @note 0 and 1 are treat as power of two. - */ - template - static OGRE_FORCE_INLINE bool isPO2(T n) - { - return (n & (n-1)) == 0; - } - /** Returns the number of bits a pattern must be shifted right by to - remove right-hand zeros. - */ - template - static OGRE_FORCE_INLINE unsigned int getBitShift(T mask) - { - if (mask == 0) - return 0; - - unsigned int result = 0; - while ((mask & 1) == 0) { - ++result; - mask >>= 1; - } - return result; - } - - /** Takes a value with a given src bit mask, and produces another - value with a desired bit mask. - - This routine is useful for colour conversion. - */ - template - static inline DestT convertBitPattern(SrcT srcValue, SrcT srcBitMask, DestT destBitMask) - { - // Mask off irrelevant source value bits (if any) - srcValue = srcValue & srcBitMask; - - // Shift source down to bottom of DWORD - const unsigned int srcBitShift = getBitShift(srcBitMask); - srcValue >>= srcBitShift; - - // Get max value possible in source from srcMask - const SrcT srcMax = srcBitMask >> srcBitShift; - - // Get max available in dest - const unsigned int destBitShift = getBitShift(destBitMask); - const DestT destMax = destBitMask >> destBitShift; - - // Scale source value into destination, and shift back - DestT destValue = (srcValue * destMax) / srcMax; - return (destValue << destBitShift); - } - - /** - * Convert N bit colour channel value to P bits. It fills P bits with the - * bit pattern repeated. (this is /((1< p) - { - // Less bits required than available; this is easy - value >>= n-p; - } - else if(n < p) - { - // More bits required than are there, do the fill - // Use old fashioned division, probably better than a loop - if(value == 0) - value = 0; - else if(value == (static_cast(1)<= 1.0f) return (1<> 16) & 0xFF); - ((uint8*)dest)[1] = (uint8)((value >> 8) & 0xFF); - ((uint8*)dest)[2] = (uint8)(value & 0xFF); -#else - ((uint8*)dest)[2] = (uint8)((value >> 16) & 0xFF); - ((uint8*)dest)[1] = (uint8)((value >> 8) & 0xFF); - ((uint8*)dest)[0] = (uint8)(value & 0xFF); -#endif - break; - case 4: - ((uint32*)dest)[0] = (uint32)value; - break; - } - } - /** - * Read a n*8 bits integer value to memory in native endian. - */ - static inline unsigned int intRead(const void *src, int n) { - switch(n) { - case 1: - return ((const uint8*)src)[0]; - case 2: - return ((const uint16*)src)[0]; - case 3: -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - return ((uint32)((const uint8*)src)[0]<<16)| - ((uint32)((const uint8*)src)[1]<<8)| - ((uint32)((const uint8*)src)[2]); -#else - return ((uint32)((const uint8*)src)[0])| - ((uint32)((const uint8*)src)[1]<<8)| - ((uint32)((const uint8*)src)[2]<<16); -#endif - case 4: - return ((const uint32*)src)[0]; - } - return 0; // ? - } - - /** Convert a float32 to a float16 (NV_half_float) - Courtesy of OpenEXR - */ - static inline uint16 floatToHalf(float i) - { - union { float f; uint32 i; } v; - v.f = i; - return floatToHalfI(v.i); - } - /** Converts float in uint32 format to a a half in uint16 format - */ - static inline uint16 floatToHalfI(uint32 i) - { - int s = (i >> 16) & 0x00008000; - int e = ((i >> 23) & 0x000000ff) - (127 - 15); - int m = i & 0x007fffff; - - if (e <= 0) - { - if (e < -10) - { - return 0; - } - m = (m | 0x00800000) >> (1 - e); - - return static_cast(s | (m >> 13)); - } - else if (e == 0xff - (127 - 15)) - { - if (m == 0) // Inf - { - return static_cast(s | 0x7c00); - } - else // NAN - { - m >>= 13; - return static_cast(s | 0x7c00 | m | (m == 0)); - } - } - else - { - if (e > 30) // Overflow - { - return static_cast(s | 0x7c00); - } - - return static_cast(s | (e << 10) | (m >> 13)); - } - } - - /** - * Convert a float16 (NV_half_float) to a float32 - * Courtesy of OpenEXR - */ - static inline float halfToFloat(uint16 y) - { - union { float f; uint32 i; } v; - v.i = halfToFloatI(y); - return v.f; - } - /** Converts a half in uint16 format to a float - in uint32 format - */ - static inline uint32 halfToFloatI(uint16 y) - { - int s = (y >> 15) & 0x00000001; - int e = (y >> 10) & 0x0000001f; - int m = y & 0x000003ff; - - if (e == 0) - { - if (m == 0) // Plus or minus zero - { - return s << 31; - } - else // Denormalized number -- renormalize it - { - while (!(m & 0x00000400)) - { - m <<= 1; - e -= 1; - } - - e += 1; - m &= ~0x00000400; - } - } - else if (e == 31) - { - if (m == 0) // Inf - { - return (s << 31) | 0x7f800000; - } - else // NaN - { - return (s << 31) | 0x7f800000 | (m << 13); - } - } - - e = e + (127 - 15); - m = m << 13; - - return (s << 31) | (e << 23) | m; - } - - - }; - /** @} */ - /** @} */ - -} - -#endif diff --git a/OgreMain/include/OgreBlendMode.h b/OgreMain/include/OgreBlendMode.h deleted file mode 100644 index e6d3b166db5..00000000000 --- a/OgreMain/include/OgreBlendMode.h +++ /dev/null @@ -1,312 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __BLENDMODE_H__ -#define __BLENDMODE_H__ - -#include "OgrePrerequisites.h" -#include "OgreColourValue.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Materials - * @{ - */ - - /** Type of texture blend mode. - */ - enum LayerBlendType - { - LBT_COLOUR, - LBT_ALPHA - }; - - /** List of valid texture blending operations, for use with TextureUnitState::setColourOperation. - - This list is a more limited list than LayerBlendOperationEx because it only - includes operations that are supportable in both multipass and multitexture - rendering and thus provides automatic fallback if multitexture hardware - is lacking or insufficient. - */ - enum LayerBlendOperation { - /// Replace all colour with texture with no adjustment - LBO_REPLACE, - /// Add colour components together. - LBO_ADD, - /// Multiply colour components together. - LBO_MODULATE, - /// Blend based on texture alpha - LBO_ALPHA_BLEND - - }; - - /** Expert list of valid texture blending operations, for use with TextureUnitState::setColourOperationEx - and TextureUnitState::setAlphaOperation, and internally in the LayerBlendModeEx class. It's worth - noting that these operations are for blending between texture layers and not between rendered objects - and the existing scene. Because all of these modes are only supported in multitexture hardware it may be - required to set up a fallback operation where this hardware is not available. - */ - enum LayerBlendOperationEx { - /// use source1 without modification - LBX_SOURCE1, - /// use source2 without modification - LBX_SOURCE2, - /// multiply source1 and source2 together - LBX_MODULATE, - /// as LBX_MODULATE but brighten afterwards (x2) - LBX_MODULATE_X2, - /// as LBX_MODULATE but brighten more afterwards (x4) - LBX_MODULATE_X4, - /// add source1 and source2 together - LBX_ADD, - /// as LBX_ADD, but subtract 0.5 from the result - LBX_ADD_SIGNED, - /// as LBX_ADD, but subtract product from the sum - LBX_ADD_SMOOTH, - /// subtract source2 from source1 - LBX_SUBTRACT, - /// use interpolated alpha value from vertices to scale source1, then add source2 scaled by (1-alpha) - LBX_BLEND_DIFFUSE_ALPHA, - /// as LBX_BLEND_DIFFUSE_ALPHA, but use alpha from texture - LBX_BLEND_TEXTURE_ALPHA, - /// as LBX_BLEND_DIFFUSE_ALPHA, but use current alpha from previous stages - LBX_BLEND_CURRENT_ALPHA, - /// as LBX_BLEND_DIFFUSE_ALPHA but use a constant manual blend value (0.0-1.0) - LBX_BLEND_MANUAL, - /// dot product of color1 and color2 - LBX_DOTPRODUCT, - /// use interpolated color values from vertices to scale source1, then add source2 scaled by (1-color) - LBX_BLEND_DIFFUSE_COLOUR - }; - - /** List of valid sources of values for blending operations used - in TextureUnitState::setColourOperation and TextureUnitState::setAlphaOperation, - and internally in the LayerBlendModeEx class. - */ - enum LayerBlendSource - { - /// the colour as built up from previous stages - LBS_CURRENT, - /// the colour derived from the texture assigned to this layer - LBS_TEXTURE, - /// the interpolated diffuse colour from the vertices - LBS_DIFFUSE, - /// the interpolated specular colour from the vertices - LBS_SPECULAR, - /// a colour supplied manually as a separate argument - LBS_MANUAL - }; - /** Class which manages blending of both colour and alpha components. - - This class is a utility class used by both TextureUnitState and - RenderSystem to wrap up the details of a blending operation. This blending - operation could be used for blending colour or alpha in a texture layer. - This class is really only for use by OGRE, since apps can deal with - blending modes through the TextureUnitState class methods - setColourOperation and setAlphaOperation. - @par - It's worth noting that these operations are for blending between texture - layers and not between rendered objects and the existing scene. If - you wish to make an object blend with others in the scene, e.g. to make - transparent objects etc, use the Material::setSceneBlending method. - */ - class _OgreExport LayerBlendModeEx - { - public: - /// The type of blending (colour or alpha) - LayerBlendType blendType; - /// The operation to be applied - LayerBlendOperationEx operation; - /// The first source of colour/alpha - LayerBlendSource source1; - /// The second source of colour/alpha - LayerBlendSource source2; - - /// Manual colour value for manual source1 - ColourValue colourArg1; - /// Manual colour value for manual source2 - ColourValue colourArg2; - /// Manual alpha value for manual source1 - Real alphaArg1; - /// Manual alpha value for manual source2 - Real alphaArg2; - /// Manual blending factor - Real factor; - - bool operator==(const LayerBlendModeEx& rhs) const - { - if (blendType != rhs.blendType) return false; - - if (blendType == LBT_COLOUR) - { - - if (operation == rhs.operation && - source1 == rhs.source1 && - source2 == rhs.source2 && - colourArg1 == rhs.colourArg1 && - colourArg2 == rhs.colourArg2 && - factor == rhs.factor) - { - return true; - } - } - else // if (blendType == LBT_ALPHA) - { - if (operation == rhs.operation && - source1 == rhs.source1 && - source2 == rhs.source2 && - alphaArg1 == rhs.alphaArg1 && - alphaArg2 == rhs.alphaArg2 && - factor == rhs.factor) - { - return true; - } - } - return false; - } - - bool operator!=(const LayerBlendModeEx& rhs) const - { - return !(*this == rhs); - } - - - - }; - - /** Types of blending that you can specify between an object and the existing contents of the scene. - - As opposed to the LayerBlendType, which classifies blends between texture layers, these blending - types blend between the output of the texture units and the pixels already in the viewport, - allowing for object transparency, glows, etc. - - These types are provided to give quick and easy access to common effects. You can also use - the more manual method of supplying source and destination blending factors. - See Material::setSceneBlending for more details. - @see - Pass::setSceneBlending - */ - enum SceneBlendType - { - SBT_TRANSPARENT_ALPHA, //!< The alpha value of the rendering output is used as a mask. - SBT_TRANSPARENT_COLOUR, //!< Colour the scene based on the brightness of the input colours, but don’t darken. - SBT_ADD, //!< The colour of the rendering output is added to the scene. Good for explosions, flares, lights, ghosts etc. - SBT_MODULATE, //!< The colour of the rendering output is multiplied with the scene contents. Generally colours and darkens the scene, good for smoked glass, semi-transparent objects etc. - SBT_REPLACE //!< The default blend mode where source replaces destination - // TODO : more - }; - - /** Blending factors for manually blending objects with the scene. If there isn't a predefined - SceneBlendType that you like, then you can specify the blending factors directly to affect the - combination of object and the existing scene. See Material::setSceneBlending for more details. - */ - enum SceneBlendFactor - { - SBF_ONE, //!< Constant value of 1.0 - SBF_ZERO, //!< Constant value of 0.0 - SBF_DEST_COLOUR, //!< The existing pixel colour - SBF_SOURCE_COLOUR, //!< The texture pixel (texel) colour - SBF_ONE_MINUS_DEST_COLOUR, //!< 1 - SBF_DEST_COLOUR - SBF_ONE_MINUS_SOURCE_COLOUR, //!< 1 - SBF_SOURCE_COLOUR - SBF_DEST_ALPHA, //!< The existing pixel alpha value - SBF_SOURCE_ALPHA, //!< The texel alpha value - SBF_ONE_MINUS_DEST_ALPHA, //!< 1 - SBF_DEST_ALPHA - SBF_ONE_MINUS_SOURCE_ALPHA //!< 1 - SBF_SOURCE_ALPHA - }; - - /** Blending operations controls how objects are blended into the scene. The default operation - is add (+) but by changing this you can change how drawn objects are blended into the - existing scene. - */ - enum SceneBlendOperation - { - SBO_ADD, - SBO_SUBTRACT, - SBO_REVERSE_SUBTRACT, - SBO_MIN, - SBO_MAX - }; - - /** Describes the global blending factors for combining subsequent renders with the existing frame contents. - - By default the operation is Ogre::SBO_ADD, which creates this equation - - $$final = (passOutput * sourceFactor) + (frameBuffer * destFactor)$$ - - Each of the factors is specified as one of Ogre::SceneBlendFactor. - - By setting a different Ogre::SceneBlendOperation you can achieve a different effect. - */ - struct _OgreExport ColourBlendState - { - /** @name Write Mask - * Whether writing is enabled for each of the 4 colour channels */ - /// @{ - bool writeR : 1; - bool writeG : 1; - bool writeB : 1; - bool writeA : 1; - /// @} - - /** @name Blending factors - * used to weight the render colour components and the frame colour components */ - /// @{ - SceneBlendFactor sourceFactor; - SceneBlendFactor destFactor; - SceneBlendFactor sourceFactorAlpha; - SceneBlendFactor destFactorAlpha; - /// @} - - /** @name Blending operations - * The blend operation mode for combining colour values */ - /// @{ - SceneBlendOperation operation; - SceneBlendOperation alphaOperation; - /// @} - - ColourBlendState() - : writeR(true), writeG(true), writeB(true), writeA(true), sourceFactor(SBF_ONE), - destFactor(SBF_ZERO), sourceFactorAlpha(SBF_ONE), destFactorAlpha(SBF_ZERO), - operation(SBO_ADD), alphaOperation(SBO_ADD) - { - } - - /// can we simply overwrite the existing pixels or do we have to blend - bool blendingEnabled() const - { - return !(sourceFactor == SBF_ONE && destFactor == SBF_ZERO && - sourceFactorAlpha == SBF_ONE && destFactorAlpha == SBF_ZERO); - } - }; - /** @} */ - /** @} */ - -} - -#endif diff --git a/OgreMain/include/OgreBone.h b/OgreMain/include/OgreBone.h deleted file mode 100644 index 437b955d585..00000000000 --- a/OgreMain/include/OgreBone.h +++ /dev/null @@ -1,156 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Bone_H__ -#define __Bone_H__ - -#include "OgrePrerequisites.h" -#include "OgreNode.h" - - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Animation - * @{ - */ - - /** A bone in a skeleton. - - See Skeleton for more information about the principles behind skeletal animation. - This class is a node in the joint hierarchy. Mesh vertices also have assignments - to bones to define how they move in relation to the skeleton. - */ - class _OgreExport Bone : public Node - { - public: - /** Constructor, not to be used directly (use Bone::createChild or Skeleton::createBone) */ - Bone(unsigned short handle, Skeleton* creator); - /** Constructor, not to be used directly (use Bone::createChild or Skeleton::createBone) */ - Bone(const String& name, unsigned short handle, Skeleton* creator); - ~Bone(); - - private: - // Intentionally hide base implementations of createChild methods. This will also suppress - // warnings like 'Ogre::Bone::createChild' hides overloaded virtual functions - using Node::createChild; - public: - /** Creates a new Bone as a child of this bone. - - This method creates a new bone which will inherit the transforms of this - bone, with the handle specified. - @param - handle The numeric handle to give the new bone; must be unique within the Skeleton. - @param - translate Initial translation offset of child relative to parent - @param - rotate Initial rotation relative to parent - */ - Bone* createChild(unsigned short handle, - const Vector3& translate = Vector3::ZERO, const Quaternion& rotate = Quaternion::IDENTITY); - - /** Gets the numeric handle for this bone (unique within the skeleton). */ - unsigned short getHandle(void) const; - - /** Sets the current position / orientation to be the 'binding pose' ie the layout in which - bones were originally bound to a mesh. - */ - void setBindingPose(void); - - /** Resets the position and orientation of this Bone to the original binding position. - - Bones are bound to the mesh in a binding pose. They are then modified from this - position during animation. This method returns the bone to it's original position and - orientation. - */ - void reset(void); - - /** Sets whether or not this bone is manually controlled. - - Manually controlled bones can be altered by the application at runtime, - and their positions will not be reset by the animation routines. Note - that you should also make sure that there are no AnimationTrack objects - referencing this bone, or if there are, you should disable them using - pAnimation->destroyTrack(pBone->getHandle()); - @par - You can also use AnimationState::setBlendMask to mask out animation from - chosen tracks if you want to prevent application of a scripted animation - to a bone without altering the Animation definition. - */ - void setManuallyControlled(bool manuallyControlled); - - /** Getter for mManuallyControlled Flag */ - bool isManuallyControlled() const; - - - /** Gets the transform which takes bone space to current from the binding pose. - - Internal use only. - */ - void _getOffsetTransform(Affine3& m) const; - - /** Gets the inverted binding pose scale. */ - const Vector3& _getBindingPoseInverseScale(void) const { return mBindDerivedInverseScale; } - /** Gets the inverted binding pose position. */ - const Vector3& _getBindingPoseInversePosition(void) const { return mBindDerivedInversePosition; } - /** Gets the inverted binding pose orientation. */ - const Quaternion& _getBindingPoseInverseOrientation(void) const { return mBindDerivedInverseOrientation; } - - /// @see Node::needUpdate - void needUpdate(bool forceParentUpdate = false) override; - - - private: - /** See Node. */ - Node* createChildImpl(void) override; - /** See Node. */ - Node* createChildImpl(const String& name) override; - - /// Pointer back to creator, for child creation (not smart ptr so child does not preserve parent) - Skeleton* mCreator; - - /// The inversed derived scale of the bone in the binding pose - Vector3 mBindDerivedInverseScale; - /// The inversed derived orientation of the bone in the binding pose - Quaternion mBindDerivedInverseOrientation; - /// The inversed derived position of the bone in the binding pose - Vector3 mBindDerivedInversePosition; - /// The numeric handle of this bone - unsigned short mHandle; - /** Bones set as manuallyControlled are not reseted in Skeleton::reset() */ - bool mManuallyControlled; - }; - - /** @} */ - /** @} */ - -} - -#endif diff --git a/OgreMain/include/OgreCamera.h b/OgreMain/include/OgreCamera.h deleted file mode 100644 index 718678db766..00000000000 --- a/OgreMain/include/OgreCamera.h +++ /dev/null @@ -1,670 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Camera_H__ -#define __Camera_H__ - -// Default options -#include "OgrePrerequisites.h" - -// Matrices & Vectors -#include "OgreCommon.h" -#include "OgreFrustum.h" -#include "OgreHeaderPrefix.h" - - -namespace Ogre { - - class Matrix4; - class Ray; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - - /** A viewpoint from which the scene will be rendered. - - OGRE renders scenes from a camera viewpoint into a buffer of - some sort, normally a window or a texture (a subclass of - RenderTarget). OGRE cameras support both perspective projection (the default, - meaning objects get smaller the further away they are) and - orthographic projection (blueprint-style, no decrease in size - with distance). Each camera carries with it a style of rendering, - e.g. full textured, flat shaded, wireframe), field of view, - rendering distances etc, allowing you to use OGRE to create - complex multi-window views if required. In addition, more than - one camera can point at a single render target if required, - each rendering to a subset of the target, allowing split screen - and picture-in-picture views. - - At render time, all Scene Objects will be transformed in the camera space, - which is defined as: - - \f$+x\f$ is right - - \f$+y\f$ is up - - \f$-z\f$ is away - - Cameras maintain their own aspect ratios, field of view, and frustum, - and project coordinates into normalised device coordinates measured from -1 to 1 in x and y, - and 0 to 1 in z, where - - \f$+x\f$ is right - - \f$+y\f$ is up - - \f$+z\f$ is away - - At render time, the camera will be rendering to a - Viewport which will translate these parametric coordinates into real screen - coordinates. Obviously it is advisable that the viewport has the same - aspect ratio as the camera to avoid distortion (unless you want it!). - */ - class _OgreExport Camera : public Frustum - { - public: - /** Listener interface so you can be notified of Camera events. - */ - class _OgreExport Listener - { - public: - Listener() {} - virtual ~Listener() {} - - /// Called prior to the scene being rendered with this camera - virtual void cameraPreRenderScene(Camera* cam) - { (void)cam; } - - /// Called after the scene has been rendered with this camera - virtual void cameraPostRenderScene(Camera* cam) - { (void)cam; } - - /// Called when the camera is being destroyed - virtual void cameraDestroyed(Camera* cam) - { (void)cam; } - - }; - private: - /// Is viewing window used. - bool mWindowSet; - /// Was viewing window changed. - mutable bool mRecalcWindow; - - /** Whether aspect ratio will automatically be recalculated - when a viewport changes its size - */ - bool mAutoAspectRatio; - /// Whether or not the rendering distance of objects should take effect for this camera - bool mUseRenderingDistance; - /// Whether or not the minimum display size of objects should take effect for this camera - bool mUseMinPixelSize; - - /// Derived orientation/position of the camera, including reflection - mutable Quaternion mDerivedOrientation; - mutable Vector3 mDerivedPosition; - - /// Stored number of visible faces in the last render - unsigned int mVisFacesLastRender; - - /// Stored number of visible batches in the last render - unsigned int mVisBatchesLastRender; - -#ifdef OGRE_NODELESS_POSITIONING - /// Real world orientation/position of the camera - mutable Quaternion mRealOrientation; - mutable Vector3 mRealPosition; - - /// Whether to yaw around a fixed axis. - bool mYawFixed; - /// Fixed axis to yaw around - Vector3 mYawFixedAxis; - /// Camera orientation, quaternion style - Quaternion mOrientation; - /// Camera position - default (0,0,0) - Vector3 mPosition; - /// SceneNode which this Camera will automatically track - SceneNode* mAutoTrackTarget; - /// Tracking offset for fine tuning - Vector3 mAutoTrackOffset; -#endif - /// Scene LOD factor used to adjust overall LOD - Real mSceneLodFactor; - /// Inverted scene LOD factor, can be used by Renderables to adjust their LOD - Real mSceneLodFactorInv; - - - /** Viewing window. - - Generalize camera class for the case, when viewing frustum doesn't cover all viewport. - */ - Real mWLeft, mWTop, mWRight, mWBottom; - /// Windowed viewport clip planes - mutable std::vector mWindowClipPlanes; - /// The last viewport to be added using this camera - Viewport* mLastViewport; - /// Custom culling frustum - Frustum *mCullFrustum; - /// Camera to use for LOD calculation - const Camera* mLodCamera; - - typedef std::vector ListenerList; - ListenerList mListeners; - /// @see Camera::getPixelDisplayRatio - Real mPixelDisplayRatio; - - SortMode mSortMode; - /// Rendering type - PolygonMode mSceneDetail; - - // Internal functions for calcs - bool isViewOutOfDate(void) const override; - /// Signal to update frustum information. - void invalidateFrustum(void) const override; - /// Signal to update view information. - void invalidateView(void) const override; - - - /** Do actual window setting, using parameters set in SetWindow call - - The method will called on demand. - */ - virtual void setWindowImpl(void) const; - - /** Helper function for forwardIntersect that intersects rays with canonical plane */ - virtual std::vector getRayForwardIntersect(const Vector3& anchor, const Vector3 *dir, Real planeOffset) const; - - public: - /** Standard constructor. - */ - Camera( const String& name, SceneManager* sm); - - /** Standard destructor. - */ - virtual ~Camera(); - - /// Add a listener to this camera - virtual void addListener(Listener* l); - /// Remove a listener to this camera - virtual void removeListener(Listener* l); - - /** Returns a pointer to the SceneManager this camera is rendering through. - */ - SceneManager* getSceneManager(void) const; - - /** Sets the level of rendering detail required from this camera. - - Each camera is set to render at full detail by default, that is - with full texturing, lighting etc. This method lets you change - that behaviour, allowing you to make the camera just render a - wireframe view, for example. - */ - void setPolygonMode(PolygonMode sd); - - /** Retrieves the level of detail that the camera will render. - */ - PolygonMode getPolygonMode(void) const; - -#ifdef OGRE_NODELESS_POSITIONING - /** Sets the camera's position. - @deprecated attach to SceneNode and use SceneNode::setPosition - */ - OGRE_DEPRECATED void setPosition(Real x, Real y, Real z); - - /// @overload - /// @deprecated attach to SceneNode and use SceneNode::setPosition - OGRE_DEPRECATED void setPosition(const Vector3& vec); - - /** Retrieves the camera's position. - @deprecated attach to SceneNode and use SceneNode::getPosition - */ - OGRE_DEPRECATED const Vector3& getPosition(void) const; - - /** Moves the camera's position by the vector offset provided along world axes. - @deprecated attach to SceneNode and use SceneNode::translate - */ - OGRE_DEPRECATED void move(const Vector3& vec); - - /** Moves the camera's position by the vector offset provided along it's own axes (relative to orientation). - @deprecated attach to SceneNode and use SceneNode::translate(vec, Node::TS_LOCAL) - */ - OGRE_DEPRECATED void moveRelative(const Vector3& vec); - - /** Sets the camera's direction vector. - - Note that the 'up' vector for the camera will automatically be recalculated based on the - current 'up' vector (i.e. the roll will remain the same). - @deprecated attach to SceneNode and use SceneNode::setDirection - */ - OGRE_DEPRECATED void setDirection(Real x, Real y, Real z); - - /// @overload - /// @deprecated attach to SceneNode and use SceneNode::setDirection - OGRE_DEPRECATED void setDirection(const Vector3& vec); - - /** Gets the camera's direction. - @deprecated attach to SceneNode and use SceneNode::getOrientation().zAxis() * -1 - */ - OGRE_DEPRECATED Vector3 getDirection(void) const; - - /** Gets the camera's up vector. - @deprecated attach to SceneNode and use SceneNode::getOrientation().yAxis() - */ - OGRE_DEPRECATED Vector3 getUp(void) const; - - /** Gets the camera's right vector. - @deprecated attach to SceneNode and use SceneNode::getOrientation().xAxis() - */ - OGRE_DEPRECATED Vector3 getRight(void) const; - - /** Points the camera at a location in worldspace. - - This is a helper method to automatically generate the - direction vector for the camera, based on it's current position - and the supplied look-at point. - @param - targetPoint A vector specifying the look at point. - @deprecated attach to SceneNode and use SceneNode::lookAt - */ - OGRE_DEPRECATED void lookAt( const Vector3& targetPoint ); - /// @overload - /// @deprecated attach to SceneNode and use SceneNode::lookAt - OGRE_DEPRECATED void lookAt(Real x, Real y, Real z); - - /** Rolls the camera anticlockwise, around its local z axis. - @deprecated attach to SceneNode and use SceneNode::roll - */ - OGRE_DEPRECATED void roll(const Radian& angle); - - /** Rotates the camera anticlockwise around it's local y axis. - @deprecated attach to SceneNode and use SceneNode::yaw - */ - OGRE_DEPRECATED void yaw(const Radian& angle); - - /** Pitches the camera up/down anticlockwise around it's local z axis. - @deprecated attach to SceneNode and use SceneNode::pitch - */ - OGRE_DEPRECATED void pitch(const Radian& angle); - - /** Rotate the camera around an arbitrary axis. - @deprecated attach to SceneNode and use SceneNode::rotate - */ - OGRE_DEPRECATED void rotate(const Vector3& axis, const Radian& angle); - - /// @overload - /// @deprecated attach to SceneNode and use SceneNode::rotate - OGRE_DEPRECATED void rotate(const Quaternion& q); - - /** Tells the camera whether to yaw around it's own local Y axis or a - fixed axis of choice. - - This method allows you to change the yaw behaviour of the camera - - by default, the camera yaws around a fixed Y axis. This is - often what you want - for example if you're making a first-person - shooter, you really don't want the yaw axis to reflect the local - camera Y, because this would mean a different yaw axis if the - player is looking upwards rather than when they are looking - straight ahead. You can change this behaviour by calling this - method, which you will want to do if you are making a completely - free camera like the kind used in a flight simulator. - @param useFixed - If @c true, the axis passed in the second parameter will - always be the yaw axis no matter what the camera orientation. - If false, the camera yaws around the local Y. - @param fixedAxis - The axis to use if the first parameter is true. - @deprecated attach to SceneNode and use SceneNode::yaw(angle, Node::TS_PARENT) - */ - OGRE_DEPRECATED void setFixedYawAxis( bool useFixed, const Vector3& fixedAxis = Vector3::UNIT_Y ); - - - /** Returns the camera's current orientation. - @deprecated attach to SceneNode and use SceneNode::getOrientation - */ - OGRE_DEPRECATED const Quaternion& getOrientation(void) const; - - /** Sets the camera's orientation. - @deprecated attach to SceneNode and use SceneNode::setOrientation - */ - OGRE_DEPRECATED void setOrientation(const Quaternion& q); - - /** Internal method used by OGRE to update auto-tracking cameras. */ - OGRE_DEPRECATED void _autoTrack(void); - - /** Get the auto tracking target for this camera, if any. */ - OGRE_DEPRECATED SceneNode* getAutoTrackTarget(void) const { return mAutoTrackTarget; } - /** Get the auto tracking offset for this camera, if it is auto tracking. */ - OGRE_DEPRECATED const Vector3& getAutoTrackOffset(void) const { return mAutoTrackOffset; } - - /** Enables / disables automatic tracking of a SceneNode. - - If you enable auto-tracking, this Camera will automatically rotate to - look at the target SceneNode every frame, no matter how - it or SceneNode move. This is handy if you want a Camera to be focused on a - single object or group of objects. Note that by default the Camera looks at the - origin of the SceneNode, if you want to tweak this, e.g. if the object which is - attached to this target node is quite big and you want to point the camera at - a specific point on it, provide a vector in the 'offset' parameter and the - camera's target point will be adjusted. - @param enabled If true, the Camera will track the SceneNode supplied as the next - parameter (cannot be null). If false the camera will cease tracking and will - remain in it's current orientation. - @param target Pointer to the SceneNode which this Camera will track. Make sure you don't - delete this SceneNode before turning off tracking (e.g. SceneManager::clearScene will - delete it so be careful of this). Can be null if and only if the enabled param is false. - @param offset If supplied, the camera targets this point in local space of the target node - instead of the origin of the target node. Good for fine tuning the look at point. - @deprecated attach to SceneNode and use SceneNode::setAutoTracking - */ - OGRE_DEPRECATED void setAutoTracking(bool enabled, SceneNode* const target = 0, - const Vector3& offset = Vector3::ZERO); - - const Vector3& getPositionForViewUpdate(void) const override; - const Quaternion& getOrientationForViewUpdate(void) const override; -#endif - /** Tells the Camera to contact the SceneManager to render from it's viewpoint. - @param vp The viewport to render to - */ - void _renderScene(Viewport *vp); - - /// @deprecated do not use - OGRE_DEPRECATED void _renderScene(Viewport *vp, bool unused) { _renderScene(vp); } - - /** Function for outputting to a stream. - */ - _OgreExport friend std::ostream& operator<<(std::ostream& o, const Camera& c); - - /** Internal method to notify camera of the visible faces in the last render. - */ - void _notifyRenderedFaces(unsigned int numfaces); - - /** Internal method to notify camera of the visible batches in the last render. - */ - void _notifyRenderedBatches(unsigned int numbatches); - - /** Internal method to retrieve the number of visible faces in the last render. - */ - unsigned int _getNumRenderedFaces(void) const; - - /** Internal method to retrieve the number of visible batches in the last render. - */ - unsigned int _getNumRenderedBatches(void) const; - - /** Gets the derived orientation of the camera, including any - rotation inherited from a node attachment and reflection matrix. */ - const Quaternion& getDerivedOrientation(void) const; - /** Gets the derived position of the camera, including any - translation inherited from a node attachment and reflection matrix. */ - const Vector3& getDerivedPosition(void) const; - /** Gets the derived direction vector of the camera, including any - rotation inherited from a node attachment and reflection matrix. */ - Vector3 getDerivedDirection(void) const; - /** Gets the derived up vector of the camera, including any - rotation inherited from a node attachment and reflection matrix. */ - Vector3 getDerivedUp(void) const; - /** Gets the derived right vector of the camera, including any - rotation inherited from a node attachment and reflection matrix. */ - Vector3 getDerivedRight(void) const; - - /** Gets the real world orientation of the camera, including any - rotation inherited from a node attachment */ - const Quaternion& getRealOrientation(void) const; - /** Gets the real world position of the camera, including any - translation inherited from a node attachment. */ - const Vector3& getRealPosition(void) const; - /** Gets the real world direction vector of the camera, including any - rotation inherited from a node attachment. */ - Vector3 getRealDirection(void) const; - /** Gets the real world up vector of the camera, including any - rotation inherited from a node attachment. */ - Vector3 getRealUp(void) const; - /** Gets the real world right vector of the camera, including any - rotation inherited from a node attachment. */ - Vector3 getRealRight(void) const; - - const String& getMovableType(void) const override; - - /** Sets the level-of-detail factor for this Camera. - - This method can be used to influence the overall level of detail of the scenes - rendered using this camera. Various elements of the scene have level-of-detail - reductions to improve rendering speed at distance; this method allows you - to hint to those elements that you would like to adjust the level of detail that - they would normally use (up or down). - @par - The most common use for this method is to reduce the overall level of detail used - for a secondary camera used for sub viewports like rear-view mirrors etc. - Note that scene elements are at liberty to ignore this setting if they choose, - this is merely a hint. - @param factor The factor to apply to the usual level of detail calculation. Higher - values increase the detail, so 2.0 doubles the normal detail and 0.5 halves it. - */ - void setLodBias(Real factor = 1.0); - - /** Returns the level-of-detail bias factor currently applied to this camera. - - See Camera::setLodBias for more details. - */ - Real getLodBias(void) const; - - /** Set a pointer to the camera which should be used to determine - LOD settings. - - Sometimes you don't want the LOD of a render to be based on the camera - that's doing the rendering, you want it to be based on a different - camera. A good example is when rendering shadow maps, since they will - be viewed from the perspective of another camera. Therefore this method - lets you associate a different camera instance to use to determine the LOD. - @par - To revert the camera to determining LOD based on itself, call this method with - a pointer to itself. - */ - virtual void setLodCamera(const Camera* lodCam); - - /** Get a pointer to the camera which should be used to determine - LOD settings. - - If setLodCamera hasn't been called with a different camera, this - method will return 'this'. - */ - virtual const Camera* getLodCamera() const; - - - /** Gets a world space ray as cast from the camera through a viewport position. - @param screenx, screeny The x and y position at which the ray should intersect the viewport, - in normalised screen coordinates [0,1] - */ - Ray getCameraToViewportRay(Real screenx, Real screeny) const; - /** Gets a world space ray as cast from the camera through a viewport position. - @param screenx, screeny The x and y position at which the ray should intersect the viewport, - in normalised screen coordinates [0,1] - @param outRay Ray instance to populate with result - */ - void getCameraToViewportRay(Real screenx, Real screeny, Ray* outRay) const; - - /** Gets a world-space list of planes enclosing a volume based on a viewport - rectangle. - - Can be useful for populating a PlaneBoundedVolumeListSceneQuery, e.g. - for a rubber-band selection. - @param screenLeft, screenTop, screenRight, screenBottom The bounds of the - on-screen rectangle, expressed in normalised screen coordinates [0,1] - @param includeFarPlane If true, the volume is truncated by the camera far plane, - by default it is left open-ended - */ - PlaneBoundedVolume getCameraToViewportBoxVolume(Real screenLeft, - Real screenTop, Real screenRight, Real screenBottom, bool includeFarPlane = false); - - /// @overload - void getCameraToViewportBoxVolume(Real screenLeft, - Real screenTop, Real screenRight, Real screenBottom, - PlaneBoundedVolume* outVolume, bool includeFarPlane = false); - - /** Internal method for OGRE to use for LOD calculations. */ - Real _getLodBiasInverse(void) const; - - /** Sets the viewing window inside of viewport. - - This method can be used to set a subset of the viewport as the rendering - target. - @param left Relative to Viewport - 0 corresponds to left edge, 1 - to right edge (default - 0). - @param top Relative to Viewport - 0 corresponds to top edge, 1 - to bottom edge (default - 0). - @param right Relative to Viewport - 0 corresponds to left edge, 1 - to right edge (default - 1). - @param bottom Relative to Viewport - 0 corresponds to top edge, 1 - to bottom edge (default - 1). - */ - virtual void setWindow (Real left, Real top, Real right, Real bottom); - /// Cancel view window. - virtual void resetWindow (void); - /// Returns if a viewport window is being used - virtual bool isWindowSet(void) const { return mWindowSet; } - /// Gets the window clip planes, only applicable if isWindowSet == true - const std::vector& getWindowPlanes(void) const; - - Real getBoundingRadius(void) const override; - - /** Get the last viewport which was attached to this camera. - @note This is not guaranteed to be the only viewport which is - using this camera, just the last once which was created referring - to it. - */ - Viewport* getViewport(void) const {return mLastViewport;} - /** Notifies this camera that a viewport is using it.*/ - void _notifyViewport(Viewport* viewport) {mLastViewport = viewport;} - - /** If set to true a viewport that owns this frustum will be able to - recalculate the aspect ratio whenever the frustum is resized. - - You should set this to true only if the frustum / camera is used by - one viewport at the same time. Otherwise the aspect ratio for other - viewports may be wrong. - */ - void setAutoAspectRatio(bool autoratio); - - /** Retrieves if AutoAspectRatio is currently set or not - */ - bool getAutoAspectRatio(void) const; - - /** Tells the camera to use a separate Frustum instance to perform culling. - - By calling this method, you can tell the camera to perform culling - against a different frustum to it's own. This is mostly useful for - debug cameras that allow you to show the culling behaviour of another - camera, or a manual frustum instance. - @param frustum Pointer to a frustum to use; this can either be a manual - Frustum instance (which you can attach to scene nodes like any other - MovableObject), or another camera. If you pass 0 to this method it - reverts the camera to normal behaviour. - */ - void setCullingFrustum(Frustum* frustum) { mCullFrustum = frustum; } - /** Returns the custom culling frustum in use. */ - Frustum* getCullingFrustum(void) const { return mCullFrustum; } - - /** Forward projects frustum rays to find forward intersection with plane. - - Forward projection may lead to intersections at infinity. - */ - virtual void forwardIntersect(const Plane& worldPlane, std::vector* intersect3d) const; - - /// @copydoc Frustum::isVisible(const AxisAlignedBox&, FrustumPlane*) const - bool isVisible(const AxisAlignedBox& bound, FrustumPlane* culledBy = 0) const override; - /// @copydoc Frustum::isVisible(const Sphere&, FrustumPlane*) const - bool isVisible(const Sphere& bound, FrustumPlane* culledBy = 0) const override; - /// @copydoc Frustum::isVisible(const Vector3&, FrustumPlane*) const - bool isVisible(const Vector3& vert, FrustumPlane* culledBy = 0) const override; - /// @copydoc Frustum::getWorldSpaceCorners - const Corners& getWorldSpaceCorners(void) const override; - /// @copydoc Frustum::getFrustumPlane - const Plane& getFrustumPlane( unsigned short plane ) const override; - /// @copydoc Frustum::projectSphere - bool projectSphere(const Sphere& sphere, - Real* left, Real* top, Real* right, Real* bottom) const override; - /// @copydoc Frustum::getNearClipDistance - Real getNearClipDistance(void) const; - /// @copydoc Frustum::getFarClipDistance - Real getFarClipDistance(void) const; - /// @copydoc Frustum::getViewMatrix - const Affine3& getViewMatrix(void) const; - /** Specialised version of getViewMatrix allowing caller to differentiate - whether the custom culling frustum should be allowed or not. - - The default behaviour of the standard getViewMatrix is to delegate to - the alternate culling frustum, if it is set. This is expected when - performing CPU calculations, but the final rendering must be performed - using the real view matrix in order to display the correct debug view. - */ - const Affine3& getViewMatrix(bool ownFrustumOnly) const; - /** Set whether this camera should use the 'rendering distance' on - objects to exclude distant objects from the final image. The - default behaviour is to use it. - @param use True to use the rendering distance, false not to. - */ - virtual void setUseRenderingDistance(bool use) { mUseRenderingDistance = use; } - /** Get whether this camera should use the 'rendering distance' on - objects to exclude distant objects from the final image. - */ - virtual bool getUseRenderingDistance(void) const { return mUseRenderingDistance; } - - /** Synchronise core camera settings with another. - - Copies the position, orientation, clip distances, projection type, - FOV, focal length and aspect ratio from another camera. Other settings like query flags, - reflection etc are preserved. - */ - virtual void synchroniseBaseSettingsWith(const Camera* cam); - - /** @brief Sets whether to use min display size calculations. - When active, objects that derive from MovableObject whose size on the screen is less then a MovableObject::mMinPixelSize will not - be rendered. - */ - void setUseMinPixelSize(bool enable) { mUseMinPixelSize = enable; } - /** Returns whether to use min display size calculations - @see Camera::setUseMinDisplaySize - */ - bool getUseMinPixelSize() const { return mUseMinPixelSize; } - - /** Returns an estimated ratio between a pixel and the display area it represents. - For orthographic cameras this function returns the amount of meters covered by - a single pixel along the vertical axis. For perspective cameras the value - returned is the amount of meters covered by a single pixel per meter distance - from the camera. - @note - This parameter is calculated just before the camera is rendered - @note - This parameter is used in min display size calculations. - */ - Real getPixelDisplayRatio() const { return mPixelDisplayRatio; } - - /// Set the function used to compute the camera-distance for sorting Renderables - void setSortMode(SortMode sm) { mSortMode = sm; } - /// get the currently used @ref SortMode - SortMode getSortMode() const { return mSortMode; } - }; - /** @} */ - /** @} */ - -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif // __Camera_H__ diff --git a/OgreMain/include/OgreCodec.h b/OgreMain/include/OgreCodec.h deleted file mode 100644 index cffbf07fada..00000000000 --- a/OgreMain/include/OgreCodec.h +++ /dev/null @@ -1,145 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _Codec_H__ -#define _Codec_H__ - -#include "OgrePrerequisites.h" -#include "OgreIteratorWrapper.h" -#include "OgreStringVector.h" -#include "OgreException.h" -#include "OgreHeaderPrefix.h" -#include "OgreAny.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - - /** Abstract class that defines a 'codec'. - - A codec class works like a two-way filter for data - data entered on - one end (the decode end) gets processed and transformed into easily - usable data while data passed the other way around codes it back. - @par - The codec concept is a pretty generic one - you can easily understand - how it can be used for images, sounds, archives, even compressed data. - */ - class _OgreExport Codec : public CodecAlloc - { - private: - typedef std::map< String, Codec* > CodecList; - /** A map that contains all the registered codecs. - */ - static CodecList msMapCodecs; - - public: - virtual ~Codec(); - - /** Registers a new codec in the database. - */ - static void registerCodec( Codec *pCodec ); - - /** Return whether a codec is registered already. - */ - static bool isCodecRegistered( const String& codecType ) - { - return msMapCodecs.find(codecType) != msMapCodecs.end(); - } - - /** Unregisters a codec from the database. - */ - static void unregisterCodec( Codec *pCodec ) - { - msMapCodecs.erase(pCodec->getType()); - } - - /** Gets the file extension list for the registered codecs. */ - static StringVector getExtensions(void); - - /** Gets the codec registered for the passed in file extension. */ - static Codec* getCodec(const String& extension); - - /** Gets the codec that can handle the given 'magic' identifier. - @param magicNumberPtr Pointer to a stream of bytes which should identify the file. - Note that this may be more than needed - each codec may be looking for - a different size magic number. - @param maxbytes The number of bytes passed - */ - static Codec* getCodec(char *magicNumberPtr, size_t maxbytes); - - /** Codes the input and saves the result in the output - stream. - */ - virtual DataStreamPtr encode(const Any& input) const; - - /** Codes the data in the input chunk and saves the result in the output - filename provided. Provided for efficiency since coding to memory is - progressive therefore memory required is unknown leading to reallocations. - @param input The input data (codec type specific) - @param outFileName The filename to write to - */ - virtual void encodeToFile(const Any& input, const String& outFileName) const; - - /** Codes the data from the input chunk into the output chunk. - @param input Stream containing the encoded data - @param output codec type specific result - */ - virtual void decode(const DataStreamPtr& input, const Any& output) const = 0; - - /** Returns the type of the codec as a String - */ - virtual String getType() const = 0; - - /** Returns whether a magic number header matches this codec. - @param magicNumberPtr Pointer to a stream of bytes which should identify the file. - Note that this may be more than needed - each codec may be looking for - a different size magic number. - @param maxbytes The number of bytes passed - */ - bool magicNumberMatch(const char *magicNumberPtr, size_t maxbytes) const - { return !magicNumberToFileExt(magicNumberPtr, maxbytes).empty(); } - /** Maps a magic number header to a file extension, if this codec recognises it. - @param magicNumberPtr Pointer to a stream of bytes which should identify the file. - Note that this may be more than needed - each codec may be looking for - a different size magic number. - @param maxbytes The number of bytes passed - @return A blank string if the magic number was unknown, or a file extension. - */ - virtual String magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const = 0; - }; - /** @} */ - /** @} */ - -} // namespace - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreColourValue.h b/OgreMain/include/OgreColourValue.h deleted file mode 100644 index 811b73eb64f..00000000000 --- a/OgreMain/include/OgreColourValue.h +++ /dev/null @@ -1,353 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _COLOURVALUE_H__ -#define _COLOURVALUE_H__ - -#include "OgrePrerequisites.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - - typedef uint32 RGBA; - typedef uint32 ARGB; - typedef uint32 ABGR; - typedef uint32 BGRA; - - /** Class representing colour. - - Colour is represented as 4 components, each of which is a - floating-point value from 0.0 to 1.0. - @par - The 3 'normal' colour components are red, green and blue, a higher - number indicating greater amounts of that component in the colour. - The forth component is the 'alpha' value, which represents - transparency. In this case, 0.0 is completely transparent and 1.0 is - fully opaque. - */ - class _OgreExport ColourValue - { - public: - static const ColourValue ZERO; - static const ColourValue Black; - static const ColourValue White; - static const ColourValue Red; - static const ColourValue Green; - static const ColourValue Blue; - - explicit ColourValue( float red = 1.0f, - float green = 1.0f, - float blue = 1.0f, - float alpha = 1.0f ) : r(red), g(green), b(blue), a(alpha) - { } - - explicit ColourValue(const uchar* byte) : r(byte[0]), g(byte[1]), b(byte[2]), a(byte[3]) - { - *this /= 255; - } - - bool operator==(const ColourValue& rhs) const - { - return (r == rhs.r && g == rhs.g && b == rhs.b && a == rhs.a); - } - bool operator!=(const ColourValue& rhs) const { return !(*this == rhs); } - - float r,g,b,a; - - /// @name conversions from/ to native-endian packed formats - /// @{ - - /// value packed as #PF_R8G8B8A8 - RGBA getAsRGBA(void) const; - - /// value packed as #PF_A8R8G8B8 - ARGB getAsARGB(void) const; - - /// value packed as #PF_B8G8R8A8 - BGRA getAsBGRA(void) const; - - /// value packed as #PF_A8B8G8R8 - ABGR getAsABGR(void) const; - - /// value packed as #PF_BYTE_RGBA - RGBA getAsBYTE() const - { -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - return getAsRGBA(); -#else - return getAsABGR(); -#endif - } - - /// Set value from #PF_R8G8B8A8 - void setAsRGBA(RGBA val); - - /// Set value from #PF_A8R8G8B8 - void setAsARGB(ARGB val); - - /// Set value from #PF_B8G8R8A8 - void setAsBGRA(BGRA val); - - /// Set value from #PF_A8B8G8R8 - void setAsABGR(ABGR val); - /// @} - - /** Clamps colour value to the range [0, 1]. - */ - void saturate(void) - { - if (r < 0) - r = 0; - else if (r > 1) - r = 1; - - if (g < 0) - g = 0; - else if (g > 1) - g = 1; - - if (b < 0) - b = 0; - else if (b > 1) - b = 1; - - if (a < 0) - a = 0; - else if (a > 1) - a = 1; - } - - /** As saturate, except that this colour value is unaffected and - the saturated colour value is returned as a copy. */ - ColourValue saturateCopy(void) const - { - ColourValue ret = *this; - ret.saturate(); - return ret; - } - - /// Array accessor operator - float operator [] ( const size_t i ) const - { - assert( i < 4 ); - - return *(&r+i); - } - - /// Array accessor operator - float& operator [] ( const size_t i ) - { - assert( i < 4 ); - - return *(&r+i); - } - - /// Pointer accessor for direct copying - float* ptr() - { - return &r; - } - /// Pointer accessor for direct copying - const float* ptr() const - { - return &r; - } - - - // arithmetic operations - ColourValue operator + ( const ColourValue& rkVector ) const - { - ColourValue kSum; - - kSum.r = r + rkVector.r; - kSum.g = g + rkVector.g; - kSum.b = b + rkVector.b; - kSum.a = a + rkVector.a; - - return kSum; - } - - ColourValue operator - ( const ColourValue& rkVector ) const - { - ColourValue kDiff; - - kDiff.r = r - rkVector.r; - kDiff.g = g - rkVector.g; - kDiff.b = b - rkVector.b; - kDiff.a = a - rkVector.a; - - return kDiff; - } - - ColourValue operator * (const float fScalar ) const - { - ColourValue kProd; - - kProd.r = fScalar*r; - kProd.g = fScalar*g; - kProd.b = fScalar*b; - kProd.a = fScalar*a; - - return kProd; - } - - ColourValue operator * ( const ColourValue& rhs) const - { - ColourValue kProd; - - kProd.r = rhs.r * r; - kProd.g = rhs.g * g; - kProd.b = rhs.b * b; - kProd.a = rhs.a * a; - - return kProd; - } - - ColourValue operator / ( const ColourValue& rhs) const - { - ColourValue kProd; - - kProd.r = r / rhs.r; - kProd.g = g / rhs.g; - kProd.b = b / rhs.b; - kProd.a = a / rhs.a; - - return kProd; - } - - ColourValue operator / (const float fScalar ) const - { - assert( fScalar != 0.0 ); - - ColourValue kDiv; - - float fInv = 1.0f / fScalar; - kDiv.r = r * fInv; - kDiv.g = g * fInv; - kDiv.b = b * fInv; - kDiv.a = a * fInv; - - return kDiv; - } - - friend ColourValue operator * (const float fScalar, const ColourValue& rkVector ) - { - ColourValue kProd; - - kProd.r = fScalar * rkVector.r; - kProd.g = fScalar * rkVector.g; - kProd.b = fScalar * rkVector.b; - kProd.a = fScalar * rkVector.a; - - return kProd; - } - - // arithmetic updates - ColourValue& operator += ( const ColourValue& rkVector ) - { - r += rkVector.r; - g += rkVector.g; - b += rkVector.b; - a += rkVector.a; - - return *this; - } - - ColourValue& operator -= ( const ColourValue& rkVector ) - { - r -= rkVector.r; - g -= rkVector.g; - b -= rkVector.b; - a -= rkVector.a; - - return *this; - } - - ColourValue& operator *= (const float fScalar ) - { - r *= fScalar; - g *= fScalar; - b *= fScalar; - a *= fScalar; - return *this; - } - - ColourValue& operator /= (const float fScalar ) - { - assert( fScalar != 0.0 ); - - float fInv = 1.0f / fScalar; - - r *= fInv; - g *= fInv; - b *= fInv; - a *= fInv; - - return *this; - } - - /** Set a colour value from Hue, Saturation and Brightness. - @param hue Hue value, scaled to the [0,1] range as opposed to the 0-360 - @param saturation Saturation level, [0,1] - @param brightness Brightness level, [0,1] - */ - void setHSB(float hue, float saturation, float brightness); - - /** Convert the current colour to Hue, Saturation and Brightness values. - @param hue Output hue value, scaled to the [0,1] range as opposed to the 0-360 - @param saturation Output saturation level, [0,1] - @param brightness Output brightness level, [0,1] - */ - void getHSB(float& hue, float& saturation, float& brightness) const; - - /// @deprecated - OGRE_DEPRECATED void getHSB(float* hue, float* saturation, float* brightness) const - { - getHSB(*hue, *saturation, *brightness); - } - - /** Function for writing to a stream. - */ - inline friend std::ostream& operator << - ( std::ostream& o, const ColourValue& c ) - { - o << "ColourValue(" << c.r << ", " << c.g << ", " << c.b << ", " << c.a << ")"; - return o; - } - - }; - /** @} */ - /** @} */ - -} // namespace - -#endif diff --git a/OgreMain/include/OgreCommon.h b/OgreMain/include/OgreCommon.h deleted file mode 100644 index fa1ab9f2c8a..00000000000 --- a/OgreMain/include/OgreCommon.h +++ /dev/null @@ -1,628 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Common_H__ -#define __Common_H__ -// Common stuff - -#include "OgreVector.h" -#include "OgreHeaderPrefix.h" -#include "OgreMurmurHash3.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - - /// Fast general hashing algorithm - inline uint32 FastHash (const char * data, size_t len, uint32 hashSoFar = 0) { - uint32 ret; - MurmurHash3_x86_32(data, len, hashSoFar, &ret); - return ret; - } - /// Combine hashes with same style as boost::hash_combine - template - uint32 HashCombine (uint32 hashSoFar, const T& data) - { - return FastHash((const char*)&data, sizeof(T), hashSoFar); - } - - - /** Comparison functions used for the depth/stencil buffer operations and - others. */ - enum CompareFunction : uint8 - { - CMPF_ALWAYS_FAIL, //!< Never writes a pixel to the render target - CMPF_ALWAYS_PASS, //!< Always writes a pixel to the render target - CMPF_LESS, //!< Write if (new_Z < existing_Z) - CMPF_LESS_EQUAL, //!< Write if (new_Z <= existing_Z) - CMPF_EQUAL, //!< Write if (new_Z == existing_Z) - CMPF_NOT_EQUAL, //!< Write if (new_Z != existing_Z) - CMPF_GREATER_EQUAL,//!< Write if (new_Z >= existing_Z) - CMPF_GREATER //!< Write if (new_Z >= existing_Z) - }; - - /** High-level filtering options providing shortcuts to settings the - minification, magnification and mip filters. */ - enum TextureFilterOptions - { - /// No filtering or mipmapping is used. - /// Equal to: min=Ogre::FO_POINT, mag=Ogre::FO_POINT, mip=Ogre::FO_NONE - TFO_NONE, - /// 2x2 box filtering is performed when magnifying or reducing a texture, and a mipmap is picked from the list but no filtering is done between the levels of the mipmaps. - /// Equal to: min=Ogre::FO_LINEAR, mag=Ogre::FO_LINEAR, mip=Ogre::FO_POINT - TFO_BILINEAR, - /// 2x2 box filtering is performed when magnifying and reducing a texture, and the closest 2 mipmaps are filtered together. - /// Equal to: min=Ogre::FO_LINEAR, mag=Ogre::FO_LINEAR, mip=Ogre::FO_LINEAR - TFO_TRILINEAR, - /// This is the same as ’trilinear’, except the filtering algorithm takes account of the slope of the triangle in relation to the camera rather than simply doing a 2x2 pixel filter in all cases. - /// Equal to: min=Ogre::FO_ANISOTROPIC, max=Ogre::FO_ANISOTROPIC, mip=Ogre::FO_LINEAR - TFO_ANISOTROPIC - }; - - enum FilterType - { - /// The filter used when shrinking a texture - FT_MIN, - /// The filter used when magnifying a texture - FT_MAG, - /// The filter used when determining the mipmap - FT_MIP - }; - /** Filtering options for textures / mipmaps. */ - enum FilterOptions : uint8 - { - /// No filtering, used for FT_MIP to turn off mipmapping - FO_NONE, - /// Use the closest pixel - FO_POINT, - /// Average of a 2x2 pixel area, denotes bilinear for MIN and MAG, trilinear for MIP - FO_LINEAR, - /// Similar to FO_LINEAR, but compensates for the angle of the texture plane. Note that in - /// order for this to make any difference, you must also set the - /// TextureUnitState::setTextureAnisotropy attribute too. - FO_ANISOTROPIC - }; - - /** Texture addressing modes - default is TAM_WRAP. - */ - enum TextureAddressingMode : uint8 - { - /// %Any value beyond 1.0 wraps back to 0.0. %Texture is repeated. - TAM_WRAP, - /// %Texture flips every boundary, meaning texture is mirrored every 1.0 u or v - TAM_MIRROR, - /// Values beyond 1.0 are clamped to 1.0. %Texture ’streaks’ beyond 1.0 since last line - /// of pixels is used across the rest of the address space. Useful for textures which - /// need exact coverage from 0.0 to 1.0 without the ’fuzzy edge’ wrap gives when - /// combined with filtering. - TAM_CLAMP, - /// %Texture coordinates outside the range [0.0, 1.0] are set to the border colour. - TAM_BORDER - }; - - /** %Light shading modes. */ - enum ShadeOptions : uint8 - { - SO_FLAT, //!< No interpolation takes place. Each face is shaded with a single colour determined from the first vertex in the face. - SO_GOURAUD, //!< Colour at each vertex is linearly interpolated across the face. - SO_PHONG //!< Vertex normals are interpolated across the face, and these are used to determine colour at each pixel. Gives a more natural lighting effect but is more expensive and works better at high levels of tessellation. Not supported on all hardware. - }; - - /** Fog modes. */ - enum FogMode : uint8 - { - /// No fog. Duh. - FOG_NONE, - /// Fog density increases exponentially from the camera (fog = 1/e^(distance * density)) - FOG_EXP, - /// Fog density increases at the square of FOG_EXP, i.e. even quicker (fog = 1/e^(distance * density)^2) - FOG_EXP2, - /// Fog density increases linearly between the start and end distances - FOG_LINEAR - }; - - /** Hardware culling modes based on vertex winding. - This setting applies to how the hardware API culls triangles it is sent. */ - enum CullingMode : uint8 - { - /// Hardware never culls triangles and renders everything it receives. - CULL_NONE = 1, - /// Hardware culls triangles whose vertices are listed clockwise in the view (default). - CULL_CLOCKWISE = 2, - /// Hardware culls triangles whose vertices are listed anticlockwise in the view. - CULL_ANTICLOCKWISE = 3 - }; - - /** Manual culling modes based on vertex normals. - This setting applies to how the software culls triangles before sending them to the - hardware API. This culling mode is used by scene managers which choose to implement it - - normally those which deal with large amounts of fixed world geometry which is often - planar (software culling movable variable geometry is expensive). */ - enum ManualCullingMode : uint8 - { - /// No culling so everything is sent to the hardware. - MANUAL_CULL_NONE = 1, - /// Cull triangles whose normal is pointing away from the camera (default). - MANUAL_CULL_BACK = 2, - /// Cull triangles whose normal is pointing towards the camera. - MANUAL_CULL_FRONT = 3 - }; - - /** Enumerates the wave types usable with the Ogre engine. */ - enum WaveformType - { - /// Standard sine wave which smoothly changes from low to high and back again. - WFT_SINE, - /// An angular wave with a constant increase / decrease speed with pointed peaks. - WFT_TRIANGLE, - /// Half of the time is spent at the min, half at the max with instant transition between. - WFT_SQUARE, - /// Gradual steady increase from min to max over the period with an instant return to min at the end. - WFT_SAWTOOTH, - /// Gradual steady decrease from max to min over the period, with an instant return to max at the end. - WFT_INVERSE_SAWTOOTH, - /// Pulse Width Modulation. Works like WFT_SQUARE, except the high to low transition is controlled by duty cycle. - /// With a duty cycle of 50% (0.5) will give the same output as WFT_SQUARE. - WFT_PWM - }; - - /** The polygon mode to use when rasterising. */ - enum PolygonMode : uint8 - { - /// Only the points of each polygon are rendered. - PM_POINTS = 1, - /// Polygons are drawn in outline only. - PM_WIREFRAME = 2, - /// The normal situation - polygons are filled in. - PM_SOLID = 3 - }; - - /** An enumeration of broad shadow techniques */ - enum ShadowTechnique - { - /** No shadows */ - SHADOWTYPE_NONE = 0x00, - /** Mask for additive shadows (not for direct use, use SHADOWTYPE_ enum instead) - */ - SHADOWDETAILTYPE_ADDITIVE = 0x01, - /** Mask for modulative shadows (not for direct use, use SHADOWTYPE_ enum instead) - */ - SHADOWDETAILTYPE_MODULATIVE = 0x02, - /** Mask for integrated shadows (not for direct use, use SHADOWTYPE_ enum instead) - */ - SHADOWDETAILTYPE_INTEGRATED = 0x04, - /** Mask for stencil shadows (not for direct use, use SHADOWTYPE_ enum instead) - */ - SHADOWDETAILTYPE_STENCIL = 0x10, - /** Mask for texture shadows (not for direct use, use SHADOWTYPE_ enum instead) - */ - SHADOWDETAILTYPE_TEXTURE = 0x20, - - /** Stencil shadow technique which renders all shadow volumes as - a modulation after all the non-transparent areas have been - rendered. This technique is considerably less fillrate intensive - than the additive stencil shadow approach when there are multiple - lights, but is not an accurate model. - */ - SHADOWTYPE_STENCIL_MODULATIVE = SHADOWDETAILTYPE_STENCIL | SHADOWDETAILTYPE_MODULATIVE, - /** Stencil shadow technique which renders each light as a separate - additive pass to the scene. This technique can be very fillrate - intensive because it requires at least 2 passes of the entire - scene, more if there are multiple lights. However, it is a more - accurate model than the modulative stencil approach and this is - especially apparent when using coloured lights or bump mapping. - */ - SHADOWTYPE_STENCIL_ADDITIVE = SHADOWDETAILTYPE_STENCIL | SHADOWDETAILTYPE_ADDITIVE, - /** Texture-based shadow technique which involves a monochrome render-to-texture - of the shadow caster and a projection of that texture onto the - shadow receivers as a modulative pass. - */ - SHADOWTYPE_TEXTURE_MODULATIVE = SHADOWDETAILTYPE_TEXTURE | SHADOWDETAILTYPE_MODULATIVE, - - /** Texture-based shadow technique which involves a render-to-texture - of the shadow caster and a projection of that texture onto the - shadow receivers, built up per light as additive passes. - This technique can be very fillrate intensive because it requires numLights + 2 - passes of the entire scene. However, it is a more accurate model than the - modulative approach and this is especially apparent when using coloured lights - or bump mapping. - */ - SHADOWTYPE_TEXTURE_ADDITIVE = SHADOWDETAILTYPE_TEXTURE | SHADOWDETAILTYPE_ADDITIVE, - - /** Texture-based shadow technique which involves a render-to-texture - of the shadow caster and a projection of that texture on to the shadow - receivers, with the usage of those shadow textures completely controlled - by the materials of the receivers. - This technique is easily the most flexible of all techniques because - the material author is in complete control over how the shadows are - combined with regular rendering. It can perform shadows as accurately - as SHADOWTYPE_TEXTURE_ADDITIVE but more efficiently because it requires - less passes. However it also requires more expertise to use, and - in almost all cases, shader capable hardware to really use to the full. - @note The 'additive' part of this mode means that the colour of - the rendered shadow texture is by default plain black. It does - not mean it does the adding on your receivers automatically though, how you - use that result is up to you. - */ - SHADOWTYPE_TEXTURE_ADDITIVE_INTEGRATED = SHADOWTYPE_TEXTURE_ADDITIVE | SHADOWDETAILTYPE_INTEGRATED, - /** Texture-based shadow technique which involves a render-to-texture - of the shadow caster and a projection of that texture on to the shadow - receivers, with the usage of those shadow textures completely controlled - by the materials of the receivers. - This technique is easily the most flexible of all techniques because - the material author is in complete control over how the shadows are - combined with regular rendering. It can perform shadows as accurately - as SHADOWTYPE_TEXTURE_ADDITIVE but more efficiently because it requires - less passes. However it also requires more expertise to use, and - in almost all cases, shader capable hardware to really use to the full. - @note The 'modulative' part of this mode means that the colour of - the rendered shadow texture is by default the 'shadow colour'. It does - not mean it modulates on your receivers automatically though, how you - use that result is up to you. - */ - SHADOWTYPE_TEXTURE_MODULATIVE_INTEGRATED = SHADOWTYPE_TEXTURE_MODULATIVE | SHADOWDETAILTYPE_INTEGRATED - }; - - /** An enumeration describing which material properties should track the vertex colours */ - typedef int TrackVertexColourType; - enum TrackVertexColourEnum { - TVC_NONE = 0x0, - TVC_AMBIENT = 0x1, - TVC_DIFFUSE = 0x2, - TVC_SPECULAR = 0x4, - TVC_EMISSIVE = 0x8 - }; - - /** Function used compute the camera-distance for sorting objects */ - enum SortMode : uint8 - { - - /** Sort by direction of the camera - * - * The distance along the camera view as in `cam->getDerivedDirection().dotProduct(diff)` - * Best for @ref PT_ORTHOGRAPHIC - */ - SM_DIRECTION, - /** Sort by distance from the camera - * - * The euclidean distance as in `diff.squaredLength()` - * Best for @ref PT_PERSPECTIVE - */ - SM_DISTANCE - }; - - /** Defines the frame buffer types. */ - enum FrameBufferType { - FBT_COLOUR = 0x1, - FBT_DEPTH = 0x2, - FBT_STENCIL = 0x4 - }; - - /** Defines the colour buffer types. */ - enum ColourBufferType - { - CBT_BACK = 0x0, - CBT_BACK_LEFT, - CBT_BACK_RIGHT - }; - - /** Flags for the Instance Manager when calculating ideal number of instances per batch */ - enum InstanceManagerFlags - { - /** Forces an amount of instances per batch low enough so that vertices * numInst < 65535 - since usually improves performance. In HW instanced techniques, this flag is ignored - */ - IM_USE16BIT = 0x0001, - - /** The num. of instances is adjusted so that as few pixels as possible are wasted - in the vertex texture */ - IM_VTFBESTFIT = 0x0002, - - /** Use a limited number of skeleton animations shared among all instances. - Update only that limited amount of animations in the vertex texture.*/ - IM_VTFBONEMATRIXLOOKUP = 0x0004, - - IM_USEBONEDUALQUATERNIONS = 0x0008, - - /** Use one weight per vertex when recommended (i.e. VTF). */ - IM_USEONEWEIGHT = 0x0010, - - /** All techniques are forced to one weight per vertex. */ - IM_FORCEONEWEIGHT = 0x0020, - - IM_USEALL = IM_USE16BIT|IM_VTFBESTFIT|IM_USEONEWEIGHT - }; - - class Light; - typedef std::vector LightList; - - - /// Constant blank string, useful for returning by ref where local does not exist - const String BLANKSTRING; - - typedef std::map UnaryOptionList; - typedef std::map BinaryOptionList; - - /// Name / value parameter pair (first = name, second = value) - typedef std::map NameValuePairList; - - /// Alias / Texture name pair (first = alias, second = texture name) - typedef std::map AliasTextureNamePairList; - - template< typename T > struct TRect - { - T left, top, right, bottom; - TRect() : left(0), top(0), right(0), bottom(0) {} - TRect( T const & l, T const & t, T const & r, T const & b ) - : left( l ), top( t ), right( r ), bottom( b ) - { - } - TRect( TRect const & o ) - : left( o.left ), top( o.top ), right( o.right ), bottom( o.bottom ) - { - } - TRect & operator=( TRect const & o ) - { - left = o.left; - top = o.top; - right = o.right; - bottom = o.bottom; - return *this; - } - T width() const - { - return right - left; - } - T height() const - { - return bottom - top; - } - bool isNull() const - { - return width() == 0 || height() == 0; - } - void setNull() - { - left = right = top = bottom = 0; - } - TRect & merge(const TRect& rhs) - { - assert(right >= left && bottom >= top); - assert(rhs.right >= rhs.left && rhs.bottom >= rhs.top); - if (isNull()) - { - *this = rhs; - } - else if (!rhs.isNull()) - { - left = std::min(left, rhs.left); - right = std::max(right, rhs.right); - top = std::min(top, rhs.top); - bottom = std::max(bottom, rhs.bottom); - } - - return *this; - - } - - /** - * Returns the intersection of the two rectangles. - * - * Note that the rectangles extend downwards. I.e. a valid box will - * have "right > left" and "bottom > top". - * @param rhs Another rectangle. - * @return The intersection of the two rectangles. Zero size if they don't intersect. - */ - TRect intersect(const TRect& rhs) const - { - assert(right >= left && bottom >= top); - assert(rhs.right >= rhs.left && rhs.bottom >= rhs.top); - TRect ret; - if (isNull() || rhs.isNull()) - { - // empty - return ret; - } - else - { - ret.left = std::max(left, rhs.left); - ret.right = std::min(right, rhs.right); - ret.top = std::max(top, rhs.top); - ret.bottom = std::min(bottom, rhs.bottom); - } - - if (ret.left > ret.right || ret.top > ret.bottom) - { - // no intersection, return empty - ret.left = ret.top = ret.right = ret.bottom = 0; - } - - return ret; - - } - bool operator==(const TRect& rhs) const - { - return left == rhs.left && right == rhs.right && top == rhs.top && bottom == rhs.bottom; - } - bool operator!=(const TRect& rhs) const { return !(*this == rhs); } - }; - template - std::ostream& operator<<(std::ostream& o, const TRect& r) - { - o << "TRect<>(l:" << r.left << ", t:" << r.top << ", r:" << r.right << ", b:" << r.bottom << ")"; - return o; - } - - /** Structure used to define a rectangle in a 2-D floating point space. - */ - typedef TRect FloatRect; - - /** Structure used to define a rectangle in a 2-D floating point space, - subject to double / single floating point settings. - */ - typedef TRect RealRect; - - /** Structure used to define a rectangle in a 2-D integer space. - */ - typedef TRect< int32 > Rect; - - /** Structure used to define a box in a 3-D integer space. - Note that the left, top, and front edges are included but the right, - bottom and back ones are not. - */ - struct Box - { - uint32 left, top, right, bottom, front, back; - /// Parameterless constructor for setting the members manually - Box() - : left(0), top(0), right(1), bottom(1), front(0), back(1) - { - } - /** Define a box from left, top, right and bottom coordinates - This box will have depth one (front=0 and back=1). - @param l x value of left edge - @param t y value of top edge - @param r x value of right edge - @param b y value of bottom edge - @note @copydetails Ogre::Box - */ - Box( uint32 l, uint32 t, uint32 r, uint32 b ): - left(l), - top(t), - right(r), - bottom(b), - front(0), - back(1) - { - assert(right >= left && bottom >= top && back >= front); - } - - /// @overload - template explicit Box(const TRect& r) : Box(r.left, r.top, r.right, r.bottom) {} - - /** Define a box from left, top, front, right, bottom and back - coordinates. - @param l x value of left edge - @param t y value of top edge - @param ff z value of front edge - @param r x value of right edge - @param b y value of bottom edge - @param bb z value of back edge - @note @copydetails Ogre::Box - */ - Box( uint32 l, uint32 t, uint32 ff, uint32 r, uint32 b, uint32 bb ): - left(l), - top(t), - right(r), - bottom(b), - front(ff), - back(bb) - { - assert(right >= left && bottom >= top && back >= front); - } - - /// @overload - explicit Box(const Vector3i& size) - : left(0), top(0), right(size[0]), bottom(size[1]), front(0), back(size[2]) - { - } - - /// Return true if the other box is a part of this one - bool contains(const Box &def) const - { - return (def.left >= left && def.top >= top && def.front >= front && - def.right <= right && def.bottom <= bottom && def.back <= back); - } - - /// Get the width of this box - uint32 getWidth() const { return right-left; } - /// Get the height of this box - uint32 getHeight() const { return bottom-top; } - /// Get the depth of this box - uint32 getDepth() const { return back-front; } - - /// origin (top, left, front) of the box - Vector3i getOrigin() const { return Vector3i(left, top, front); } - /// size (width, height, depth) of the box - Vector3i getSize() const { return Vector3i(getWidth(), getHeight(), getDepth()); } - }; - - - - /** Locate command-line options of the unary form '-blah' and of the - binary form '-blah foo', passing back the index of the next non-option. - @param numargs, argv The standard parameters passed to the main method - @param unaryOptList Map of unary options (i.e. those that do not require a parameter). - Should be pre-populated with, for example '-e' in the key and false in the - value. Options which are found will be set to true on return. - @param binOptList Map of binary options (i.e. those that require a parameter - e.g. '-e afile.txt'). - Should be pre-populated with, for example '-e' and the default setting. - Options which are found will have the value updated. - */ - int _OgreExport findCommandLineOpts(int numargs, char** argv, UnaryOptionList& unaryOptList, - BinaryOptionList& binOptList); - - /// Generic result of clipping - enum ClipResult - { - /// Nothing was clipped - CLIPPED_NONE = 0, - /// Partially clipped - CLIPPED_SOME = 1, - /// Everything was clipped away - CLIPPED_ALL = 2 - }; - - /// Render window creation parameters. - struct RenderWindowDescription - { - String name; - unsigned int width; - unsigned int height; - bool useFullScreen; - NameValuePairList miscParams; - }; - - /// Render window creation parameters container. - typedef std::vector RenderWindowDescriptionList; - - /// Render window container. - typedef std::vector RenderWindowList; - - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreCompositionPass.h b/OgreMain/include/OgreCompositionPass.h deleted file mode 100644 index e165621959b..00000000000 --- a/OgreMain/include/OgreCompositionPass.h +++ /dev/null @@ -1,416 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __CompositionPass_H__ -#define __CompositionPass_H__ - -#include "OgrePrerequisites.h" -#include "OgreHeaderPrefix.h" -#include "OgreRenderSystem.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - /** Object representing one pass or operation in a composition sequence. This provides a - method to conveniently interleave RenderSystem commands between Render Queues. - */ - class _OgreExport CompositionPass : public CompositorInstAlloc - { - public: - CompositionPass(CompositionTargetPass *parent); - ~CompositionPass(); - - /** Enumeration that enumerates the various composition pass types. - */ - enum PassType - { - PT_CLEAR, //!< Clear target to one colour - PT_STENCIL, //!< Set stencil operation - PT_RENDERSCENE, //!< Render the scene or part of it - PT_RENDERQUAD, //!< Render a full screen quad - PT_RENDERCUSTOM, //!< Render a custom sequence - PT_COMPUTE //!< dispatch a compute shader - }; - - /** Set the type of composition pass */ - void setType(PassType type); - /** Get the type of composition pass */ - PassType getType() const; - - /** Set an identifier for this pass. This identifier can be used to - "listen in" on this pass with an CompositorInstance::Listener. - */ - void setIdentifier(uint32 id); - /** Get the identifier for this pass */ - uint32 getIdentifier() const; - - /** Set the material used by this pass - @note applies when PassType is RENDERQUAD - */ - void setMaterial(const MaterialPtr& mat); - /** Set the material used by this pass - @note applies when PassType is RENDERQUAD - */ - void setMaterialName(const String &name); - /** Get the material used by this pass - @note applies when PassType is RENDERQUAD - */ - const MaterialPtr& getMaterial() const; - /** Set the first render queue to be rendered in this pass (inclusive) - @note applies when PassType is RENDERSCENE - */ - void setFirstRenderQueue(uint8 id); - /** Get the first render queue to be rendered in this pass (inclusive) - @note applies when PassType is RENDERSCENE - */ - uint8 getFirstRenderQueue() const; - /** Set the last render queue to be rendered in this pass (inclusive) - @note applies when PassType is RENDERSCENE - */ - void setLastRenderQueue(uint8 id); - /** Get the last render queue to be rendered in this pass (inclusive) - @note applies when PassType is RENDERSCENE - */ - uint8 getLastRenderQueue() const; - - /** Set the material scheme used by this pass. - - Only applicable to passes that render the scene. - @see Technique::setScheme. - */ - void setMaterialScheme(const String& schemeName); - /** Get the material scheme used by this pass. - - Only applicable to passes that render the scene. - @see Technique::setScheme. - */ - const String& getMaterialScheme(void) const; - - /** Would be nice to have for RENDERSCENE: - flags to: - exclude transparents - override material (at least -- color) - */ - - /** Set the viewport clear buffers (defaults to FBT_COLOUR|FBT_DEPTH) - @param val is a combination of FBT_COLOUR, FBT_DEPTH, FBT_STENCIL. - @note applies when PassType is CLEAR - */ - void setClearBuffers(uint32 val); - /** Get the viewport clear buffers. - @note applies when PassType is CLEAR - */ - uint32 getClearBuffers() const; - /** Set the viewport clear colour (defaults to 0,0,0,0) - @note applies when PassType is CLEAR - */ - void setClearColour(const ColourValue &val); - /** Get the viewport clear colour (defaults to 0,0,0,0) - @note applies when PassType is CLEAR - */ - const ColourValue &getClearColour() const; - /** Set the clear colour to be the background colour of the original viewport - @note applies when PassType is CLEAR - */ - void setAutomaticColour(bool val); - /** Retrieves if the clear colour is automatically set to the background colour of the original viewport - @note applies when PassType is CLEAR - */ - bool getAutomaticColour() const; - /** Set the viewport clear depth (defaults to 1.0) - @note applies when PassType is CLEAR - */ - void setClearDepth(float depth); - /** Get the viewport clear depth (defaults to 1.0) - @note applies when PassType is CLEAR - */ - float getClearDepth() const; - /** Set the viewport clear stencil value (defaults to 0) - @note applies when PassType is CLEAR - */ - void setClearStencil(uint16 value); - /** Get the viewport clear stencil value (defaults to 0) - @note applies when PassType is CLEAR - */ - uint16 getClearStencil() const; - - /** Set stencil check on or off. - @note applies when PassType is STENCIL - */ - void setStencilCheck(bool value); - /** Get stencil check enable. - @note applies when PassType is STENCIL - */ - bool getStencilCheck() const; - /** Set stencil compare function. - @note applies when PassType is STENCIL - */ - void setStencilFunc(CompareFunction value); - /** Get stencil compare function. - @note applies when PassType is STENCIL - */ - CompareFunction getStencilFunc() const; - /** Set stencil reference value. - @note applies when PassType is STENCIL - */ - void setStencilRefValue(uint32 value); - /** Get stencil reference value. - @note applies when PassType is STENCIL - */ - uint32 getStencilRefValue() const; - /** Set stencil mask. - @note applies when PassType is STENCIL - */ - void setStencilMask(uint32 value); - /** Get stencil mask. - @note applies when PassType is STENCIL - */ - uint32 getStencilMask() const; - /** Set stencil fail operation. - @note applies when PassType is STENCIL - */ - void setStencilFailOp(StencilOperation value); - /** Get stencil fail operation. - @note applies when PassType is STENCIL - */ - StencilOperation getStencilFailOp() const; - /** Set stencil depth fail operation. - @note applies when PassType is STENCIL - */ - void setStencilDepthFailOp(StencilOperation value); - /** Get stencil depth fail operation. - @note applies when PassType is STENCIL - */ - StencilOperation getStencilDepthFailOp() const; - /** Set stencil pass operation. - @note applies when PassType is STENCIL - */ - void setStencilPassOp(StencilOperation value); - /** Get stencil pass operation. - @note applies when PassType is STENCIL - */ - StencilOperation getStencilPassOp() const; - /** Set two sided stencil operation. - @note applies when PassType is STENCIL - */ - void setStencilTwoSidedOperation(bool value); - /** Get two sided stencil operation. - @note applies when PassType is STENCIL - */ - bool getStencilTwoSidedOperation() const; - - const StencilState& getStencilState() const { return mStencilState; } - - /// Inputs (for material used for rendering the quad) - struct InputTex - { - /// Name (local) of the input texture (empty == no input) - String name; - /// MRT surface index if applicable - size_t mrtIndex; - InputTex() : mrtIndex(0) {} - InputTex(const String& _name, size_t _mrtIndex = 0) - : name(_name), mrtIndex(_mrtIndex) {} - }; - - /** Set an input local texture. An empty string clears the input. - @param id Input to set. Must be in 0..OGRE_MAX_TEXTURE_LAYERS-1 - @param input Which texture to bind to this input. An empty string clears the input. - @param mrtIndex Which surface of an MRT to retrieve - @note applies when PassType is RENDERQUAD - */ - void setInput(size_t id, const String &input=BLANKSTRING, size_t mrtIndex=0); - - /** Get the value of an input. - @param id Input to get. Must be in 0..OGRE_MAX_TEXTURE_LAYERS-1. - @note applies when PassType is RENDERQUAD - */ - const InputTex &getInput(size_t id) const; - - /** Get the number of inputs used. - @note applies when PassType is RENDERQUAD - */ - size_t getNumInputs() const; - - /** Clear all inputs. - @note applies when PassType is RENDERQUAD - */ - void clearAllInputs(); - - /** Get parent object - @note applies when PassType is RENDERQUAD - */ - CompositionTargetPass *getParent(); - - /** Determine if this target pass is supported on the current rendering device. - */ - bool _isSupported(void); - - /** Set quad normalised positions [-1;1]x[-1;1] - @note applies when PassType is RENDERQUAD - */ - void setQuadCorners(const FloatRect& quad) { mQuad.rect = quad; mQuad.cornerModified = true; } - - /** Get quad normalised positions [-1;1]x[-1;1] - @note applies when PassType is RENDERQUAD - */ - bool getQuadCorners(FloatRect& quad) const { quad = mQuad.rect; return mQuad.cornerModified; } - - /** Sets the use of camera frustum far corners provided in the quad's normals - @note applies when PassType is RENDERQUAD - */ - void setQuadFarCorners(bool farCorners, bool farCornersViewSpace); - - /** Returns true if camera frustum far corners are provided in the quad. - @note applies when PassType is RENDERQUAD - */ - bool getQuadFarCorners() const; - - /** Returns true if the far corners provided in the quad are in view space - @note applies when PassType is RENDERQUAD - */ - bool getQuadFarCornersViewSpace() const; - - /** Set the type name of this custom composition pass. - @note applies when PassType is RENDERCUSTOM - @see CompositorManager::registerCustomCompositionPass - */ - void setCustomType(const String& customType); - - /** Get the type name of this custom composition pass. - @note applies when PassType is RENDERCUSTOM - @see CompositorManager::registerCustomCompositionPass - */ - const String& getCustomType() const; - - void setThreadGroups(const Vector3i& g) { mThreadGroups = g; } - const Vector3i& getThreadGroups() const { return mThreadGroups; } - - void setCameraName(const String& name) { mRenderScene.cameraName = name; } - const String& getCameraName() const { return mRenderScene.cameraName; } - - void setAlignCameraToFace(bool val) { mRenderScene.alignCameraToFace = val; } - bool getAlignCameraToFace() const { return mRenderScene.alignCameraToFace; } - private: - /// Parent technique - CompositionTargetPass *mParent; - /// Type of composition pass - PassType mType; - - // in case of PT_RENDERQUAD, PT_COMPUTE, PT_CUSTOM - struct MaterialData - { - /// Identifier for this pass - uint32 identifier; - /// Material used for rendering - MaterialPtr material; - /** Inputs (for material used for rendering the quad). - An empty string signifies that no input is used */ - InputTex inputs[OGRE_MAX_TEXTURE_LAYERS]; - - MaterialData() : identifier(0) {} - } mMaterial; - - // in case of PT_RENDERSCENE - struct RenderSceneData - { - /// [first,last] render queue to render this pass (in case of PT_RENDERSCENE) - uint8 firstRenderQueue; - uint8 lastRenderQueue; - - /// Material scheme name - String materialScheme; - - /// name of camera to use instead of default - String cameraName; - bool alignCameraToFace; - - RenderSceneData() - : firstRenderQueue(RENDER_QUEUE_BACKGROUND), lastRenderQueue(RENDER_QUEUE_TRANSPARENTS), - alignCameraToFace(false) - { - } - } mRenderScene; - - // in case of PT_CLEAR - struct ClearData - { - /// Clear buffers - uint32 buffers; - /// Clear colour - ColourValue colour; - /// Clear colour with the colour of the original viewport. Overrides mClearColour - bool automaticColour; - /// Clear depth - float depth; - /// Clear stencil value - uint16 stencil; - - ClearData() - : buffers(FBT_COLOUR | FBT_DEPTH), colour(ColourValue::ZERO), automaticColour(false), - depth(1.0f), stencil(0) - { - } - } mClear; - - /// in case of PT_COMPUTE - Vector3i mThreadGroups; - - /// in case of PT_STENCIL - StencilState mStencilState; - - // in case of PT_RENDERQUAD - struct QuadData - { - /// True if quad should not cover whole screen - bool cornerModified; - /// quad positions in normalised coordinates [-1;1]x[-1;1] - FloatRect rect; - bool farCorners, farCornersViewSpace; - - QuadData() - : cornerModified(false), rect(-1, 1, 1, -1), farCorners(false), farCornersViewSpace(false) - { - } - } mQuad; - - /// in case of PT_RENDERCUSTOM - String mCustomType; - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreCompositionTargetPass.h b/OgreMain/include/OgreCompositionTargetPass.h deleted file mode 100644 index c7f2d49375c..00000000000 --- a/OgreMain/include/OgreCompositionTargetPass.h +++ /dev/null @@ -1,190 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __CompositionTargetPass_H__ -#define __CompositionTargetPass_H__ - -#include "OgrePrerequisites.h" -#include "OgreHeaderPrefix.h" -#include "OgreCompositionPass.h" - -namespace Ogre { - template class VectorIterator; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - /** Object representing one render to a RenderTarget or Viewport in the Ogre Composition - framework. - */ - class _OgreExport CompositionTargetPass : public CompositorInstAlloc - { - public: - CompositionTargetPass(CompositionTechnique *parent); - ~CompositionTargetPass(); - - /** Input mode of a TargetPass - */ - enum InputMode - { - IM_NONE, /// No input - IM_PREVIOUS /// Output of previous Composition in chain - }; - typedef std::vector Passes; - typedef VectorIterator PassIterator; - - /** Set input mode of this TargetPass - */ - void setInputMode(InputMode mode); - /** Get input mode */ - InputMode getInputMode() const; - - /** Set output local texture name */ - void setOutputName(const String &out); - /** Get output local texture name */ - const String &getOutputName() const; - - /// sets the slice of output texture - void setOutputSlice(int slice) { mOutputSlice = slice; } - int getOutputSlice() const { return mOutputSlice; } - - /** Set "only initial" flag. This makes that this target pass is only executed initially - after the effect has been enabled. - */ - void setOnlyInitial(bool value); - /** Get "only initial" flag. - */ - bool getOnlyInitial(); - - /** Set the scene visibility mask used by this pass - */ - void setVisibilityMask(uint32 mask); - /** Get the scene visibility mask used by this pass - */ - uint32 getVisibilityMask(); - - /** Set the material scheme used by this target pass. - - Only applicable to targets that render the scene as - one of their passes. - @see Technique::setScheme. - */ - void setMaterialScheme(const String& schemeName); - /** Get the material scheme used by this target pass. - - Only applicable to targets that render the scene as - one of their passes. - @see Technique::setScheme. - */ - const String& getMaterialScheme(void) const; - - /** Set whether shadows are enabled in this target pass. - - Only applicable to targets that render the scene as - one of their passes. - */ - void setShadowsEnabled(bool enabled); - /** Get whether shadows are enabled in this target pass. - - Only applicable to targets that render the scene as - one of their passes. - */ - bool getShadowsEnabled(void) const; - /** Set the scene LOD bias used by this pass. The default is 1.0, - everything below that means lower quality, higher means higher quality. - */ - void setLodBias(float bias); - /** Get the scene LOD bias used by this pass - */ - float getLodBias(); - - /** Create a new pass, and return a pointer to it. - */ - CompositionPass *createPass(CompositionPass::PassType type = CompositionPass::PT_RENDERQUAD); - /** Remove a pass. It will also be destroyed. - */ - void removePass(size_t idx); - /** Get a pass.*/ - CompositionPass *getPass(size_t idx) const { return mPasses.at(idx); } - /** Get the number of passes. - */ - size_t getNumPasses() const { return mPasses.size(); } - - /// Get the Passes in this TargetPass - const Passes& getPasses() const { - return mPasses; - } - - /** Remove all passes - */ - void removeAllPasses(); - - /** Get an iterator over the Passes in this TargetPass. - @deprecated use getPasses() */ - OGRE_DEPRECATED PassIterator getPassIterator(void); - - /** Get parent object */ - CompositionTechnique *getParent(); - - /** Determine if this target pass is supported on the current rendering device. - */ - bool _isSupported(void); - - private: - /// Parent technique - CompositionTechnique *mParent; - /// Input mode - InputMode mInputMode; - /// (local) output texture - String mOutputName; - /// Passes - Passes mPasses; - /// This target pass is only executed initially after the effect - /// has been enabled. - bool mOnlyInitial; - /// Visibility mask for this render - uint32 mVisibilityMask; - /// LOD bias of this render - float mLodBias; - /// Material scheme name - String mMaterialScheme; - /// Shadows option - bool mShadowsEnabled; - /// Output Slice - int mOutputSlice; - }; - - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreCompositionTechnique.h b/OgreMain/include/OgreCompositionTechnique.h deleted file mode 100644 index 59b16e0e09e..00000000000 --- a/OgreMain/include/OgreCompositionTechnique.h +++ /dev/null @@ -1,197 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __CompositionTechnique_H__ -#define __CompositionTechnique_H__ - -#include "OgrePrerequisites.h" -#include "OgrePixelFormat.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - template class VectorIterator; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - /** Base composition technique, can be subclassed in plugins. - */ - class _OgreExport CompositionTechnique : public CompositorInstAlloc - { - public: - CompositionTechnique(Compositor *parent); - virtual ~CompositionTechnique(); - - //The scope of a texture defined by the compositor - enum TextureScope { - //Local texture - only available to the compositor passes in this technique - TS_LOCAL, - //Chain texture - available to the other compositors in the chain - TS_CHAIN, - //Global texture - available to everyone in every scope - TS_GLOBAL - }; - - /// Local texture definition - class TextureDefinition : public CompositorInstAlloc - { - public: - String name; - //Texture definition being a reference is determined by these two fields not being empty. - String refCompName; //If a reference, the name of the compositor being referenced - String refTexName; //If a reference, the name of the texture in the compositor being referenced - uint32 width; // 0 means adapt to target width - uint32 height; // 0 means adapt to target height - TextureType type; // either 2d or cubic - float widthFactor; // multiple of target width to use (if width = 0) - float heightFactor; // multiple of target height to use (if height = 0) - PixelFormatList formatList; // more than one means MRT - bool fsaa; // FSAA enabled; true = determine from main target (if render_scene), false = disable - bool hwGammaWrite; // Do sRGB gamma correction on write (only 8-bit per channel formats) - uint16 depthBufferId;//Depth Buffer's pool ID. (unrelated to "pool" variable below) - bool pooled; // whether to use pooled textures for this one - TextureScope scope; // Which scope has access to this texture - - TextureDefinition() :width(0), height(0), type(TEX_TYPE_2D), widthFactor(1.0f), heightFactor(1.0f), - fsaa(true), hwGammaWrite(false), depthBufferId(1), pooled(false), scope(TS_LOCAL) {} - }; - /// Typedefs for several iterators - typedef std::vector TargetPasses; - typedef VectorIterator TargetPassIterator; - typedef std::vector TextureDefinitions; - typedef VectorIterator TextureDefinitionIterator; - - /** Create a new local texture definition, and return a pointer to it. - @param name Name of the local texture - */ - TextureDefinition *createTextureDefinition(const String &name); - - /** Remove and destroy a local texture definition. - */ - void removeTextureDefinition(size_t idx); - - /** Get a local texture definition. - */ - TextureDefinition *getTextureDefinition(size_t idx) const { return mTextureDefinitions.at(idx); } - - /** Get a local texture definition with a specific name. - */ - TextureDefinition *getTextureDefinition(const String& name) const; - - /** Get the number of local texture definitions.*/ - size_t getNumTextureDefinitions() const { return mTextureDefinitions.size(); } - - /** Remove all Texture Definitions - */ - void removeAllTextureDefinitions(); - - /** Get the TextureDefinitions in this Technique. */ - const TextureDefinitions& getTextureDefinitions() const { return mTextureDefinitions; } - - /// @deprecated use getTextureDefinitions() - OGRE_DEPRECATED TextureDefinitionIterator getTextureDefinitionIterator(void); - - /** Create a new target pass, and return a pointer to it. - */ - CompositionTargetPass *createTargetPass(); - - /** Remove a target pass. It will also be destroyed. - */ - void removeTargetPass(size_t idx); - - /** Get a target pass. - */ - CompositionTargetPass* getTargetPass(size_t idx) const { return mTargetPasses.at(idx); } - - /** Get the number of target passes. */ - size_t getNumTargetPasses() const { return mTargetPasses.size(); } - - /** Remove all target passes. - */ - void removeAllTargetPasses(); - - /** Get the TargetPasses in this Technique. */ - const TargetPasses& getTargetPasses() const { return mTargetPasses; } - - /// @deprecated use getTargetPasses() - OGRE_DEPRECATED TargetPassIterator getTargetPassIterator(void); - - /** Get output (final) target pass - */ - CompositionTargetPass *getOutputTargetPass() const { return mOutputTarget; } - - /** Determine if this technique is supported on the current rendering device. - @param allowTextureDegradation True to accept a reduction in texture depth - */ - virtual bool isSupported(bool allowTextureDegradation); - - /** Assign a scheme name to this technique, used to switch between - multiple techniques by choice rather than for hardware compatibility. - */ - virtual void setSchemeName(const String& schemeName); - /** Get the scheme name assigned to this technique. */ - const String& getSchemeName() const { return mSchemeName; } - - /** Set the name of the compositor logic assigned to this technique. - Instances of this technique will be auto-coupled with the matching logic. - */ - void setCompositorLogicName(const String& compositorLogicName) - { mCompositorLogicName = compositorLogicName; } - /** Get the compositor logic name assigned to this technique */ - const String& getCompositorLogicName() const { return mCompositorLogicName; } - - /** Get parent object */ - Compositor *getParent(); - private: - /// Parent compositor - Compositor *mParent; - /// Local texture definitions - TextureDefinitions mTextureDefinitions; - - /// Intermediate target passes - TargetPasses mTargetPasses; - /// Output target pass (can be only one) - CompositionTargetPass *mOutputTarget; - - /// Optional scheme name - String mSchemeName; - - /// Optional compositor logic name - String mCompositorLogicName; - - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreCompositor.h b/OgreMain/include/OgreCompositor.h deleted file mode 100644 index ebc3775404d..00000000000 --- a/OgreMain/include/OgreCompositor.h +++ /dev/null @@ -1,181 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Compositor_H__ -#define __Compositor_H__ - -#include "OgrePrerequisites.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - template class VectorIterator; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - /** Class representing a Compositor object. Compositors provide the means - to flexibly "composite" the final rendering result from multiple scene renders - and intermediate operations like rendering fullscreen quads. This makes - it possible to apply postfilter effects, HDRI postprocessing, and shadow - effects to a Viewport. - */ - class _OgreExport Compositor final : public Resource - { - public: - Compositor(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual = false, ManualResourceLoader* loader = 0); - ~Compositor(); - - /// Data types for internal lists - typedef std::vector Techniques; - typedef VectorIterator TechniqueIterator; - - /** Create a new technique, and return a pointer to it. - */ - CompositionTechnique *createTechnique(); - - /** Remove a technique. It will also be destroyed. - */ - void removeTechnique(size_t idx); - - /** Get a technique. - */ - CompositionTechnique *getTechnique(size_t idx) const { return mTechniques.at(idx); } - - /** Get the number of techniques. - */ - size_t getNumTechniques() const { return mTechniques.size(); } - - /** Remove all techniques - */ - void removeAllTechniques(); - - /** Get an iterator over the Techniques in this compositor. */ - TechniqueIterator getTechniqueIterator(void); - - /** Get a supported technique. - - The supported technique list is only available after this compositor has been compiled, - which typically happens on loading it. Therefore, if this method returns - an empty list, try calling Compositor::load. - */ - CompositionTechnique *getSupportedTechnique(size_t idx) const { return mSupportedTechniques.at(idx); } - - /** Get the number of supported techniques. - - The supported technique list is only available after this compositor has been compiled, - which typically happens on loading it. Therefore, if this method returns - an empty list, try calling Compositor::load. - */ - size_t getNumSupportedTechniques() const { return mSupportedTechniques.size(); } - - /** Gets an iterator over all the Techniques which are supported by the current card. - - The supported technique list is only available after this compositor has been compiled, - which typically happens on loading it. Therefore, if this method returns - an empty list, try calling Compositor::load. - */ - TechniqueIterator getSupportedTechniqueIterator(void); - - /** Get a pointer to a supported technique for a given scheme. - - If there is no specific supported technique with this scheme name, - then the first supported technique with no specific scheme will be returned. - @param schemeName The scheme name you are looking for. Blank means to - look for techniques with no scheme associated - */ - CompositionTechnique *getSupportedTechnique(const String& schemeName = BLANKSTRING); - - /** Get the instance name for a global texture. - @param name The name of the texture in the original compositor definition - @param mrtIndex If name identifies a MRT, which texture attachment to retrieve - @return The instance name for the texture, corresponds to a real texture - */ - const String& getTextureInstanceName(const String& name, size_t mrtIndex); - - /** Get the instance of a global texture. - @param name The name of the texture in the original compositor definition - @param mrtIndex If name identifies a MRT, which texture attachment to retrieve - @return The texture pointer, corresponds to a real texture - */ - const TexturePtr& getTextureInstance(const String& name, size_t mrtIndex); - - /** Get the render target for a given render texture name. - - You can use this to add listeners etc, but do not use it to update the - targets manually or any other modifications, the compositor instance - is in charge of this. - */ - RenderTarget* getRenderTarget(const String& name, int slice = 0); - - protected: - /// @copydoc Resource::loadImpl - void loadImpl(void) override; - - /// @copydoc Resource::unloadImpl - void unloadImpl(void) override; - /// @copydoc Resource::calculateSize - size_t calculateSize(void) const override; - - /** Check supportedness of techniques. - */ - void compile(); - private: - Techniques mTechniques; - Techniques mSupportedTechniques; - - /// Compilation required - /// This is set if the techniques change and the supportedness of techniques has to be - /// re-evaluated. - bool mCompilationRequired; - - /** Create global rendertextures. - */ - void createGlobalTextures(); - - /** Destroy global rendertextures. - */ - void freeGlobalTextures(); - - //TODO GSOC : These typedefs are duplicated from CompositorInstance. Solve? - /// Map from name->local texture - typedef std::map GlobalTextureMap; - GlobalTextureMap mGlobalTextures; - /// Store a list of MRTs we've created - typedef std::map GlobalMRTMap; - GlobalMRTMap mGlobalMRTs; - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreCompositorChain.h b/OgreMain/include/OgreCompositorChain.h deleted file mode 100644 index eb1cc02a378..00000000000 --- a/OgreMain/include/OgreCompositorChain.h +++ /dev/null @@ -1,251 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __CompositorChain_H__ -#define __CompositorChain_H__ - -#include "OgrePrerequisites.h" -#include "OgreRenderTargetListener.h" -#include "OgreRenderQueueListener.h" -#include "OgreCompositorInstance.h" -#include "OgreViewport.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - /** Chain of compositor effects applying to one viewport. - */ - class _OgreExport CompositorChain : public RenderTargetListener, public Viewport::Listener, public CompositorInstAlloc - { - public: - CompositorChain(Viewport *vp); - /** Another gcc warning here, which is no problem because RenderTargetListener is never used - to delete an object. - */ - virtual ~CompositorChain(); - - /// Data types - typedef std::vector Instances; - typedef VectorIterator InstanceIterator; - - enum { - /// Identifier for best technique. - BEST = 0, - /// Identifier for "last" compositor in chain. - LAST = (size_t)-1, - NPOS = LAST - }; - - /** Apply a compositor. Initially, the filter is enabled. - @param filter - Filter to apply. - @param addPosition - Position in filter chain to insert this filter at; defaults to the end (last applied filter). - @param scheme - Scheme to use (blank means default). - */ - CompositorInstance* addCompositor(const CompositorPtr& filter, size_t addPosition=LAST, const String& scheme = BLANKSTRING); - - /** Remove a compositor. - @param position - Position in filter chain of filter to remove; defaults to the end (last applied filter) - */ - void removeCompositor(size_t position=LAST); - - /// @deprecated use getCompositorInstances - OGRE_DEPRECATED size_t getNumCompositors(); - - /** Remove all compositors. - */ - void removeAllCompositors(); - - /** Get compositor instance by name. Returns null if not found. - */ - CompositorInstance* getCompositor(const String& name) const; - - /// @overload - CompositorInstance *getCompositor(size_t index) const { return mInstances.at(index); } - - /// Get compositor position by name. Returns #NPOS if not found. - size_t getCompositorPosition(const String& name) const; - - /** Get the original scene compositor instance for this chain (internal use). - */ - CompositorInstance* _getOriginalSceneCompositor(void) { return mOriginalScene; } - - /** The compositor instances. The first compositor in this list is applied first, the last one is applied last. - */ - const Instances& getCompositorInstances() const { return mInstances; } - - /// @deprecated use getCompositorInstances - OGRE_DEPRECATED InstanceIterator getCompositors(); - - /** Enable or disable a compositor, by position. Disabling a compositor stops it from rendering - but does not free any resources. This can be more efficient than using removeCompositor and - addCompositor in cases the filter is switched on and off a lot. - @param position - Position in filter chain of filter - @param state enabled flag - */ - void setCompositorEnabled(size_t position, bool state); - - void preRenderTargetUpdate(const RenderTargetEvent& evt) override; - void postRenderTargetUpdate(const RenderTargetEvent& evt) override; - void preViewportUpdate(const RenderTargetViewportEvent& evt) override; - void postViewportUpdate(const RenderTargetViewportEvent& evt) override; - void viewportCameraChanged(Viewport* viewport) override; - void viewportDimensionsChanged(Viewport* viewport) override; - void viewportDestroyed(Viewport* viewport) override; - - /** Mark state as dirty, and to be recompiled next frame. - */ - void _markDirty(); - - /** Get viewport that is the target of this chain - */ - Viewport *getViewport(); - /** Set viewport that is the target of this chain - */ - void _notifyViewport(Viewport* vp); - - /** Remove a compositor by pointer. This is internally used by CompositionTechnique to - "weak" remove any instanced of a deleted technique. - */ - void _removeInstance(CompositorInstance *i); - - /** Internal method for registering a queued operation for deletion later **/ - void _queuedOperation(CompositorInstance::RenderSystemOperation* op); - - /** Compile this Composition chain into a series of RenderTarget operations. - */ - void _compile(); - - /** Get the previous instance in this chain to the one specified. - */ - CompositorInstance* getPreviousInstance(CompositorInstance* curr, bool activeOnly = true); - /** Get the next instance in this chain to the one specified. - */ - CompositorInstance* getNextInstance(CompositorInstance* curr, bool activeOnly = true); - - private: - /// Viewport affected by this CompositorChain - Viewport *mViewport; - - /** Plainly renders the scene; implicit first compositor in the chain. - */ - CompositorInstance *mOriginalScene; - - /// Postfilter instances in this chain - Instances mInstances; - - /// State needs recompile - bool mDirty; - /// Any compositors enabled? - bool mAnyCompositorsEnabled; - - String mOriginalSceneScheme; - - /// Compiled state (updated with _compile) - CompositorInstance::CompiledState mCompiledState; - CompositorInstance::TargetOperation mOutputOperation; - /// Render System operations queued by last compile, these are created by this - /// instance thus managed and deleted by it. The list is cleared with - /// clearCompilationState() - typedef std::vector RenderSystemOperations; - RenderSystemOperations mRenderSystemOperations; - - /** Clear compiled state */ - void clearCompiledState(); - - /** Prepare a viewport, the camera and the scene for a rendering operation - */ - void preTargetOperation(CompositorInstance::TargetOperation &op, Viewport *vp, Camera *cam); - - /** Restore a viewport, the camera and the scene after a rendering operation - */ - void postTargetOperation(CompositorInstance::TargetOperation &op, Viewport *vp, Camera *cam); - - void createOriginalScene(); - void destroyOriginalScene(); - - /// destroy internal resources - void destroyResources(void); - - /** Internal method to get a unique name of a compositor - */ - const String getCompositorName() const; - - /** Render queue listener used to set up rendering events. */ - class _OgreExport RQListener: public RenderQueueListener - { - public: - RQListener() : mOperation(0), mSceneManager(0), mRenderSystem(0), mViewport(0) {} - - void renderQueueStarted(uint8 queueGroupId, const String& cameraName, bool& skipThisInvocation) override; - - /** Set current operation and target. */ - void setOperation(CompositorInstance::TargetOperation *op,SceneManager *sm,RenderSystem *rs); - - /** Notify current destination viewport. */ - void notifyViewport(Viewport* vp) { mViewport = vp; } - - /** Flush remaining render system operations. */ - void flushUpTo(uint8 id); - private: - CompositorInstance::TargetOperation *mOperation; - SceneManager *mSceneManager; - RenderSystem *mRenderSystem; - Viewport* mViewport; - CompositorInstance::RenderSystemOpPairs::iterator currentOp, lastOp; - }; - RQListener mOurListener; - /// Old viewport settings - unsigned int mOldClearEveryFrameBuffers; - /// Store old scene visibility mask - uint32 mOldVisibilityMask; - /// Store old find visible objects - bool mOldFindVisibleObjects; - /// Store old camera LOD bias - float mOldLodBias; - /// Store old viewport material scheme - String mOldMaterialScheme; - /// Store old shadows enabled flag - bool mOldShadowsEnabled; - - }; - /** @} */ - /** @} */ -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif // __CompositorChain_H__ diff --git a/OgreMain/include/OgreCompositorInstance.h b/OgreMain/include/OgreCompositorInstance.h deleted file mode 100644 index 364c3984990..00000000000 --- a/OgreMain/include/OgreCompositorInstance.h +++ /dev/null @@ -1,411 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __CompositorInstance_H__ -#define __CompositorInstance_H__ - -#include "OgrePrerequisites.h" -#include "OgreMaterialManager.h" -#include "OgreRenderQueue.h" -#include "OgreCompositionTechnique.h" -#include "OgreHeaderPrefix.h" - -#include - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - - /** An instance of a Compositor object for one Viewport. It is part of the CompositorChain - for a Viewport. - */ - class _OgreExport CompositorInstance : public CompositorInstAlloc - { - public: - CompositorInstance(CompositionTechnique *technique, CompositorChain *chain); - virtual ~CompositorInstance(); - /** Provides an interface to "listen in" to to render system operations executed by this - CompositorInstance. - */ - class _OgreExport Listener - { - public: - virtual ~Listener(); - - /** Notification of when a render target operation involving a material (like - rendering a quad) is compiled, so that miscellaneous parameters that are different - per Compositor instance can be set up. - @param pass_id - Pass identifier within Compositor instance, this is specified - by the user by CompositionPass::setIdentifier(). - @param mat - Material, this may be changed at will and will only affect - the current instance of the Compositor, not the global material - it was cloned from. - */ - virtual void notifyMaterialSetup(uint32 pass_id, MaterialPtr &mat); - - /** Notification before a render target operation involving a material (like - rendering a quad), so that material parameters can be varied. - @param pass_id - Pass identifier within Compositor instance, this is specified - by the user by CompositionPass::setIdentifier(). - @param mat - Material, this may be changed at will and will only affect - the current instance of the Compositor, not the global material - it was cloned from. - */ - virtual void notifyMaterialRender(uint32 pass_id, MaterialPtr &mat); - - /** Notification after resources have been created (or recreated). - @param forResizeOnly - Was the creation because the viewport was resized? - */ - virtual void notifyResourcesCreated(bool forResizeOnly); - - /** Notification before resources have been destructed. - @param forResizeOnly Was the creation because the viewport was resized? - */ - virtual void notifyResourcesReleased(bool forResizeOnly); - }; - /** Specific render system operation. A render target operation does special operations - between render queues like rendering a quad, clearing the frame buffer or - setting stencil state. - */ - class _OgreExport RenderSystemOperation : public CompositorInstAlloc - { - public: - virtual ~RenderSystemOperation(); - /// Set state to SceneManager and RenderSystem - virtual void execute(SceneManager *sm, RenderSystem *rs) = 0; - }; - typedef std::pair RenderSystemOpPair; - typedef std::vector RenderSystemOpPairs; - /** Operation setup for a RenderTarget (collected). - */ - class TargetOperation - { - public: - TargetOperation() - { - } - TargetOperation(RenderTarget* inTarget) - : target(inTarget), currentQueueGroupID(0), visibilityMask(0xFFFFFFFF), lodBias(1.0f), - onlyInitial(false), hasBeenRendered(false), findVisibleObjects(false), - materialScheme(MaterialManager::DEFAULT_SCHEME_NAME), shadowsEnabled(true), - alignCameraToFace(-1) - { - } - /// Target - RenderTarget *target; - - /// Current group ID - int currentQueueGroupID; - - /// RenderSystem operations to queue into the scene manager, by - /// uint8 - RenderSystemOpPairs renderSystemOperations; - - /// Scene visibility mask - /// If this is 0, the scene is not rendered at all - uint32 visibilityMask; - - /// LOD offset. This is multiplied with the camera LOD offset - /// 1.0 is default, lower means lower detail, higher means higher detail - float lodBias; - - /** A set of render queues to either include or exclude certain render queues. - */ - typedef std::bitset RenderQueueBitSet; - - /// Which renderqueues to render from scene - RenderQueueBitSet renderQueues; - - /** @see CompositionTargetPass::mOnlyInitial - */ - bool onlyInitial; - /** "Has been rendered" flag; used in combination with - onlyInitial to determine whether to skip this target operation. - */ - bool hasBeenRendered; - /** Whether this op needs to find visible scene objects or not - */ - bool findVisibleObjects; - /** Which material scheme this op will use */ - String materialScheme; - /** Whether shadows will be enabled */ - bool shadowsEnabled; - - String cameraOverride; - int alignCameraToFace; - }; - typedef std::vector CompiledState; - - /** Set enabled flag. The compositor instance will only render if it is - enabled, otherwise it is pass-through. Resources are only created if - they weren't alive when enabling. - */ - void setEnabled(bool value); - - /** Get enabled flag. - */ - bool getEnabled() const { return mEnabled; } - - /** Set alive/active flag. The compositor instance will create resources when alive, - and destroy them when inactive. - - Killing an instance means also disabling it: setAlive(false) implies - setEnabled(false) - */ - void setAlive(bool value); - - /** Get alive flag. - */ - bool getAlive() const { return mAlive; } - - /** Get the instance name for a local texture. - @note It is only valid to call this when local textures have been loaded, - which in practice means that the compositor instance is active. Calling - it at other times will cause an exception. Note that since textures - are cleaned up aggressively, this name is not guaranteed to stay the - same if you disable and re-enable the compositor instance. - @param name - The name of the texture in the original compositor definition. - @param mrtIndex - If name identifies a MRT, which texture attachment to retrieve. - @return - The instance name for the texture, corresponds to a real texture. - */ - const String& getTextureInstanceName(const String& name, size_t mrtIndex); - - /** Get the instance of a local texture. - @note Textures are only valid when local textures have been loaded, - which in practice means that the compositor instance is active. Calling - this method at other times will return null pointers. Note that since textures - are cleaned up aggressively, this pointer is not guaranteed to stay the - same if you disable and re-enable the compositor instance. - @param name - The name of the texture in the original compositor definition. - @param mrtIndex - If name identifies a MRT, which texture attachment to retrieve. - @return - The texture pointer, corresponds to a real texture. - */ - const TexturePtr& getTextureInstance(const String& name, size_t mrtIndex); - - /** Get the render target for a given render texture name. - - You can use this to add listeners etc, but do not use it to update the - targets manually or any other modifications, the compositor instance - is in charge of this. - */ - RenderTarget* getRenderTarget(const String& name, int slice = 0); - - - /** Recursively collect target states (except for final Pass). - @param compiledState - This vector will contain a list of TargetOperation objects. - */ - virtual void _compileTargetOperations(CompiledState &compiledState); - - /** Compile the final (output) operation. This is done separately because this - is combined with the input in chained filters. - */ - virtual void _compileOutputOperation(TargetOperation &finalState); - - /** Get Compositor of which this is an instance - */ - Compositor *getCompositor() const { return mCompositor; } - - /** Get CompositionTechnique used by this instance - */ - CompositionTechnique *getTechnique() const { return mTechnique; } - - /** Change the technique we're using to render this compositor. - @param tech - The technique to use (must be supported and from the same Compositor) - @param reuseTextures - If textures have already been created for the current - technique, whether to try to re-use them if sizes & formats match. - */ - void setTechnique(CompositionTechnique* tech, bool reuseTextures = true); - - /** Pick a technique to use to render this compositor based on a scheme. - - If there is no specific supported technique with this scheme name, - then the first supported technique with no specific scheme will be used. - @see CompositionTechnique::setSchemeName - @param schemeName - The scheme to use - @param reuseTextures - If textures have already been created for the current - technique, whether to try to re-use them if sizes & formats match. - Note that for this feature to be of benefit, the textures must have been created - with the 'pooled' option enabled. - */ - void setScheme(const String& schemeName, bool reuseTextures = true); - - /// Returns the name of the scheme this compositor is using. - const String& getScheme() const { return mTechnique ? mTechnique->getSchemeName() : BLANKSTRING; } - - /** Notify this instance that the primary surface has been resized. - - This will allow the instance to recreate its resources that - are dependent on the size. - */ - void notifyResized(); - - /** Get Chain that this instance is part of - */ - CompositorChain *getChain(); - - /** Add a listener. Listeners provide an interface to "listen in" to to render system - operations executed by this CompositorInstance so that materials can be - programmatically set up. - @see CompositorInstance::Listener - */ - void addListener(Listener *l); - - /** Remove a listener. - @see CompositorInstance::Listener - */ - void removeListener(Listener *l); - - /** Notify listeners of a material compilation. - */ - void _fireNotifyMaterialSetup(uint32 pass_id, MaterialPtr &mat); - - /** Notify listeners of a material render. - */ - void _fireNotifyMaterialRender(uint32 pass_id, MaterialPtr &mat); - - /** Notify listeners of a material render. - */ - void _fireNotifyResourcesCreated(bool forResizeOnly); - - /** Notify listeners resources - */ - void _fireNotifyResourcesReleased(bool forResizeOnly); - private: - /// Compositor of which this is an instance. - Compositor *mCompositor; - /// Composition technique used by this instance. - CompositionTechnique *mTechnique; - /// Composition chain of which this instance is part. - CompositorChain *mChain; - /// Is this instance enabled? - bool mEnabled; - /// Is this instance allocating resources? - bool mAlive; - /// Map from name->local texture. - typedef std::map LocalTextureMap; - LocalTextureMap mLocalTextures; - /// Store a list of MRTs we've created. - typedef std::map LocalMRTMap; - LocalMRTMap mLocalMRTs; - typedef std::map ReserveTextureMap; - /** Textures that are not currently in use, but that we want to keep for now, - for example if we switch techniques but want to keep all textures available - in case we switch back. - */ - ReserveTextureMap mReserveTextures; - - /// Vector of listeners. - typedef std::vector Listeners; - Listeners mListeners; - - /// Previous instance (set by chain). - CompositorInstance *mPreviousInstance; - - /** Collect rendering passes. Here, passes are converted into render target operations - and queued with queueRenderSystemOp. - */ - virtual void collectPasses(TargetOperation &finalState, const CompositionTargetPass *target); - - /** Create a local dummy material with one technique but no passes. - The material is detached from the Material Manager to make sure it is destroyed - when going out of scope. - */ - MaterialPtr createLocalMaterial(const String& srcName); - - /** Create local rendertextures and other resources. Builds mLocalTextures. - */ - void createResources(bool forResizeOnly); - - void setupRenderTarget(RenderTarget* target, uint16 depthBufferId); - - /** Destroy local rendertextures and other resources. - */ - void freeResources(bool forResizeOnly, bool clearReserveTextures); - - CompositionTechnique::TextureDefinition* - resolveTexReference(const CompositionTechnique::TextureDefinition* texDef); - - /** Get RenderTarget for a named local texture. - */ - RenderTarget *getTargetForTex(const String &name, int slice); - - /** Get source texture name for a named local texture. - @param name - The local name of the texture as given to it in the compositor. - @param mrtIndex - For MRTs, which attached surface to retrieve. - */ - const TexturePtr &getSourceForTex(const String &name, size_t mrtIndex = 0); - - /** Queue a render system operation. - */ - void queueRenderSystemOp(TargetOperation &finalState, RenderSystemOperation *op); - - /// Util method for assigning a local texture name to a MRT attachment - static String getMRTTexLocalName(const String& baseName, size_t attachment); - - /** Search for options like AA and hardware gamma which we may want to - inherit from the main render target to which we're attached. - */ - void deriveTextureRenderTargetOptions(const String& texname, - bool *hwGammaWrite, uint *fsaa, String* fsaaHint); - - /// Notify this instance that the primary viewport's camera has changed. - void notifyCameraChanged(Camera* camera); - - friend class CompositorChain; - friend class Compositor; - }; - /** @} */ - /** @} */ - -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif // __CompositorInstance_H__ diff --git a/OgreMain/include/OgreCompositorLogic.h b/OgreMain/include/OgreCompositorLogic.h deleted file mode 100644 index 611956e28f1..00000000000 --- a/OgreMain/include/OgreCompositorLogic.h +++ /dev/null @@ -1,68 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __CompositorLogic_H__ -#define __CompositorLogic_H__ - -#include "OgrePrerequisites.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - /** Interface for compositor logics, which can be automatically binded to compositors, - * allowing per-compositor logic (such as attaching a relevant listener) to happen - * automatically. - * @remarks All methods have empty implementations to not force an implementer into - * extending all of them. - */ - class _OgreExport CompositorLogic - { - public: - /** Called when a compositor instance has been created. - - This happens after its setup was finished, so the chain is also accessible. - This is an ideal method to automatically attach a compositor listener. - */ - virtual void compositorInstanceCreated(CompositorInstance* newInstance) {} - - /** Called when a compositor instance has been destroyed - - The chain that contained the compositor is still alive during this call. - */ - virtual void compositorInstanceDestroyed(CompositorInstance* destroyedInstance) {} - - virtual ~CompositorLogic() {} - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/OgreMain/include/OgreCompositorManager.h b/OgreMain/include/OgreCompositorManager.h deleted file mode 100644 index 9e5cf10a347..00000000000 --- a/OgreMain/include/OgreCompositorManager.h +++ /dev/null @@ -1,258 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __CompositorManager_H__ -#define __CompositorManager_H__ - -#include "OgrePrerequisites.h" -#include "OgreResourceManager.h" -#include "OgreRenderSystem.h" -#include "OgreCompositionTechnique.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - class Rectangle2D; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - /** Class for managing Compositor settings for Ogre. Compositors provide the means - to flexibly "composite" the final rendering result from multiple scene renders - and intermediate operations like rendering fullscreen quads. This makes - it possible to apply postfilter effects, HDRI postprocessing, and shadow - effects to a Viewport. - @par - When loaded from a script, a Compositor is in an 'unloaded' state and only stores the settings - required. It does not at that stage load any textures. This is because the material settings may be - loaded 'en masse' from bulk material script files, but only a subset will actually be required. - @par - Because this is a subclass of ResourceManager, any files loaded will be searched for in any path or - archive added to the resource paths/archives. See ResourceManager for details. - */ - class _OgreExport CompositorManager : public ResourceManager, public Singleton - { - public: - CompositorManager(); - virtual ~CompositorManager(); - - /** - * Create a new compositor - * @see ResourceManager::createResource - */ - CompositorPtr create (const String& name, const String& group, - bool isManual = false, ManualResourceLoader* loader = 0, - const NameValuePairList* createParams = 0); - - /// Get a resource by name. For example, a compositor defined in some .compositor script. - /// @see ResourceManager::getResourceByName - CompositorPtr getByName(const String& name, const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME) const; - - /** Get the compositor chain for a Viewport. If there is none yet, a new - compositor chain is registered. - XXX We need a _notifyViewportRemoved to find out when this viewport disappears, - so we can destroy its chain as well. - */ - CompositorChain *getCompositorChain(Viewport *vp); - - /** Returns whether exists compositor chain for a viewport. - */ - bool hasCompositorChain(const Viewport *vp) const; - - /** Remove the compositor chain from a viewport if exists. - */ - void removeCompositorChain(const Viewport *vp); - - /** Add a compositor to a viewport. By default, it is added to end of the chain, - after the other compositors. - @param vp Viewport to modify - @param compositor The name of the compositor to apply - @param addPosition At which position to add, defaults to the end (-1). - @return pointer to instance, or 0 if it failed. - */ - CompositorInstance *addCompositor(Viewport *vp, const String &compositor, int addPosition=-1); - - /** Remove a compositor from a viewport - */ - void removeCompositor(Viewport *vp, const String &compositor); - - /** Set the state of a compositor on a viewport to enabled or disabled. - Disabling a compositor stops it from rendering but does not free any resources. - This can be more efficient than using removeCompositor and addCompositor in cases - the filter is switched on and off a lot. - */ - void setCompositorEnabled(Viewport *vp, const String &compositor, bool value); - - /** Get a textured fullscreen 2D rectangle, for internal use. - */ - Renderable *_getTexturedRectangle2D(); - - /** Overridden from ResourceManager since we have to clean up chains too. */ - void removeAll(void) override; - - /** Internal method for forcing all active compositors to recreate their resources. */ - void _reconstructAllCompositorResources(); - - typedef std::set UniqueTextureSet; - - /** Utility function to get an existing pooled texture matching a given - definition, or creating one if one doesn't exist. It also takes into - account whether a pooled texture has already been supplied to this - same requester already, in which case it won't give the same texture - twice (this is important for example if you request 2 ping-pong textures, - you don't want to get the same texture for both requests! - */ - TexturePtr getPooledTexture(const String& name, const String& localName, - uint32 w, uint32 h, - PixelFormat f, uint aa, const String& aaHint, bool srgb, UniqueTextureSet& texturesAlreadyAssigned, - CompositorInstance* inst, CompositionTechnique::TextureScope scope, TextureType type = TEX_TYPE_2D); - - /** Free pooled textures from the shared pool (compositor instances still - using them will keep them in memory though). - */ - void freePooledTextures(bool onlyIfUnreferenced = true); - - /** Register a compositor logic for listening in to expecting composition - techniques. - */ - void registerCompositorLogic(const String& name, CompositorLogic* logic); - - /** Removes a listener for compositor logic registered with registerCompositorLogic - */ - void unregisterCompositorLogic(const String& name); - - /** Get a compositor logic by its name - */ - CompositorLogic* getCompositorLogic(const String& name); - - /** Check if a compositor logic exists - */ - bool hasCompositorLogic(const String& name); - - /** Register a custom composition pass. - */ - void registerCustomCompositionPass(const String& name, CustomCompositionPass* customPass); - - void unregisterCustomCompositionPass(const String& name); - - /** Get a custom composition pass by its name - */ - CustomCompositionPass* getCustomCompositionPass(const String& name); - - /** Check if a compositor pass exists - */ - bool hasCustomCompositionPass(const String& name); - - /** - Relocates a compositor chain from one viewport to another - @param sourceVP The viewport to take the chain from - @param destVP The viewport to connect the chain to - */ - void _relocateChain(Viewport* sourceVP, Viewport* destVP); - - /// @copydoc Singleton::getSingleton() - static CompositorManager& getSingleton(void); - - /// @copydoc Singleton::getSingleton() - static CompositorManager* getSingletonPtr(void); - - private: - Resource* createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* params) override; - - typedef std::map Chains; - Chains mChains; - - /** Clear composition chains for all viewports - */ - void freeChains(); - - Rectangle2D *mRectangle; - - /// List of instances - typedef std::vector Instances; - Instances mInstances; - - /// Map of registered compositor logics - typedef std::map CompositorLogicMap; - CompositorLogicMap mCompositorLogics; - - /// Map of registered custom composition passes - typedef std::map CustomCompositionPassMap; - CustomCompositionPassMap mCustomCompositionPasses; - - typedef std::vector TextureList; - typedef VectorIterator TextureIterator; - - struct TextureDef - { - size_t width, height; - TextureType type; - PixelFormat format; - uint fsaa; - String fsaaHint; - bool sRGBwrite; - - TextureDef(size_t w, size_t h, TextureType t, PixelFormat f, uint aa, const String& aaHint, - bool srgb) - : width(w), height(h), type(t), format(f), fsaa(aa), fsaaHint(aaHint), sRGBwrite(srgb) - { - } - - bool operator<(const TextureDef& y) const - { - return std::tie(width, height, type, format, fsaa, fsaaHint, sRGBwrite) < - std::tie(y.width, y.height, y.type, y.format, y.fsaa, y.fsaaHint, y.sRGBwrite); - } - }; - typedef std::map TexturesByDef; - TexturesByDef mTexturesByDef; - - typedef std::pair StringPair; - typedef std::map TextureDefMap; - typedef std::map ChainTexturesByDef; - - ChainTexturesByDef mChainTexturesByDef; - - bool isInputPreviousTarget(CompositorInstance* inst, const Ogre::String& localName); - bool isInputPreviousTarget(CompositorInstance* inst, const TexturePtr& tex); - bool isInputToOutputTarget(CompositorInstance* inst, const Ogre::String& localName); - bool isInputToOutputTarget(CompositorInstance* inst, const TexturePtr& tex); - - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreConfig.h b/OgreMain/include/OgreConfig.h deleted file mode 100644 index 00c9e6fb8bb..00000000000 --- a/OgreMain/include/OgreConfig.h +++ /dev/null @@ -1,65 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Config_H_ -#define __Config_H_ - -// Include the CMake-generated build settings. -// If you get complaints that this file is missing, then you're probably -// trying to link directly against your source dir. You must then add -// %BUILD_DIR%/include to your include search path to find OgreBuildSettings.h. -#include "OgreBuildSettings.h" - -/** If set to >0, OGRE will always 'think' that the graphics card only has the - number of texture units specified. Very useful for testing multipass fallback. -*/ -#define OGRE_PRETEND_TEXTURE_UNITS 0 - -/** Define number of texture coordinate sets allowed per vertex. -*/ -#define OGRE_MAX_TEXTURE_COORD_SETS 8 - -/** Define max number of texture layers allowed per pass on any card. -*/ -#define OGRE_MAX_TEXTURE_LAYERS 16 - -/** Define max number of lights allowed per pass. -*/ -#define OGRE_MAX_SIMULTANEOUS_LIGHTS 8 - -/** Define max number of blending weights allowed per vertex. -*/ -#define OGRE_MAX_BLEND_WEIGHTS 4 - -/// blend indices are stored as ubyte, so we can't address more than 256 bones -#define OGRE_MAX_NUM_BONES 256 - -/** Define max number of multiple render targets (MRTs) to render to at once. -*/ -#define OGRE_MAX_MULTIPLE_RENDER_TARGETS 8 - -#endif diff --git a/OgreMain/include/OgreConfigDialog.h b/OgreMain/include/OgreConfigDialog.h deleted file mode 100644 index 5cd43addff9..00000000000 --- a/OgreMain/include/OgreConfigDialog.h +++ /dev/null @@ -1,70 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __CommonConfigDialog_H__ -#define __CommonConfigDialog_H__ - -#include "OgrePrerequisites.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - - /** Defines the behaviour of an automatic renderer configuration dialog. - */ - class _OgreExport ConfigDialog : public UtilityAlloc - { - public: - virtual ~ConfigDialog() {} - - /** Displays the dialog. - - This method displays the dialog and from then on the dialog - interacts with the user independently. The dialog will be - calling the relevant OGRE rendering systems to query them for - options and to set the options the user selects. The method - returns when the user closes the dialog. - @returns - If the user accepted the dialog, true is returned. - @par - If the user cancelled the dialog (indicating the application - should probably terminate), false is returned. - @see - RenderSystem - */ - virtual bool display() = 0; - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/OgreMain/include/OgreConfigFile.h b/OgreMain/include/OgreConfigFile.h deleted file mode 100644 index 4dd08e1e128..00000000000 --- a/OgreMain/include/OgreConfigFile.h +++ /dev/null @@ -1,120 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ConfigFile_H__ -#define __ConfigFile_H__ - -#include "OgrePrerequisites.h" - -#include "OgreCommon.h" -#include "OgreStringVector.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - template class MapIterator; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - /** Class for quickly loading settings from a text file. - - This class is designed to quickly parse a simple file containing - key/value pairs, mainly for use in configuration settings. - @par - This is a very simplified approach, no multiple values per key - are allowed, no grouping or context is being kept etc. - @par - By default the key/values pairs are tokenised based on a - separator of Tab, the colon (:) or equals (=) character. Each - key - value pair must end in a carriage return. - @par - Settings can be optionally grouped in sections, using a header - beforehand of the form [SectionName]. - */ - class _OgreExport ConfigFile : public ConfigAlloc - { - public: - - ConfigFile(); - /// load from a filename (not using resource group locations) - void load(const String& filename, const String& separators = "\t:=", bool trimWhitespace = true); - /// load from a filename (using resource group locations) - void load(const String& filename, const String& resourceGroup, const String& separators = "\t:=", bool trimWhitespace = true); - /// load from a data stream - void load(const DataStreamPtr& stream, const String& separators = "\t:=", bool trimWhitespace = true); - /// load from a filename (not using resource group locations) - void loadDirect(const String& filename, const String& separators = "\t:=", bool trimWhitespace = true); - /// load from a filename (using resource group locations) - void loadFromResourceSystem(const String& filename, const String& resourceGroup, const String& separators = "\t:=", bool trimWhitespace = true); - - /** Gets the first setting from the file with the named key. - @param key The name of the setting - @param section The name of the section it must be in (if any) - @param defaultValue The value to return if the setting is not found - */ - String getSetting(const String& key, const String& section = BLANKSTRING, const String& defaultValue = BLANKSTRING) const; - /** Gets all settings from the file with the named key. */ - StringVector getMultiSetting(const String& key, const String& section = BLANKSTRING) const; - - typedef std::multimap SettingsMultiMap; - typedef MapIterator SettingsIterator; - /** Gets an iterator for stepping through all the keys / values in the file. */ - typedef std::map SettingsBySection; - typedef std::map SettingsBySection_; - typedef MapIterator SectionIterator; - - /// @deprecated use getSettingsBySection() - OGRE_DEPRECATED SectionIterator getSectionIterator(void); - - /** Get all the available settings grouped by sections */ - const SettingsBySection_& getSettingsBySection() const { - return mSettings; - } - - /// @deprecated use getSettings() - OGRE_DEPRECATED SettingsIterator getSettingsIterator(const String& section = BLANKSTRING); - - /** Get all the available settings in a section */ - const SettingsMultiMap& getSettings(const String& section = BLANKSTRING) const; - - /** Clear the settings */ - void clear(void); - protected: - SettingsBySection_ mSettings; - SettingsBySection mSettingsPtr; // for backwards compatibility - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreConfigOptionMap.h b/OgreMain/include/OgreConfigOptionMap.h deleted file mode 100644 index 87a31b30cce..00000000000 --- a/OgreMain/include/OgreConfigOptionMap.h +++ /dev/null @@ -1,62 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef _ConfigOptionMap_H__ -#define _ConfigOptionMap_H__ - -#include "OgrePrerequisites.h" - -#include "OgreStringVector.h" - - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - /** Packages the details of a configuration option. - - Used for RenderSystem::getConfigOptions. If immutable is true, this - option must be disabled for modifying. - */ - struct ConfigOption - { - String name; - String currentValue; - StringVector possibleValues; - bool immutable; - }; - - typedef std::map< String, ConfigOption > ConfigOptionMap; - /** @} */ - /** @} */ -} - -#endif diff --git a/OgreMain/include/OgreController.h b/OgreMain/include/OgreController.h deleted file mode 100644 index bb652e9e643..00000000000 --- a/OgreMain/include/OgreController.h +++ /dev/null @@ -1,227 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Controller_H__ -#define __Controller_H__ - -#include "OgrePrerequisites.h" - -#include "OgreSharedPtr.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Animation - * @{ - */ - - - /** Subclasses of this class are responsible for performing a function on an input value for a Controller. - - This abstract class provides the interface that needs to be supported for a custom function which - can be 'plugged in' to a Controller instance, which controls some object value based on an input value. - For example, the WaveControllerFunction class provided by Ogre allows you to use various waveforms to - translate an input value to an output value. - @par - You are free to create your own subclasses in order to define any function you wish. - */ - template - class ControllerFunction : public ControllerAlloc - { - protected: - /// If true, function will add input values together and wrap at 1.0 before evaluating - bool mDeltaInput; - T mDeltaCount; - - /** Gets the input value as adjusted by any delta. - */ - T getAdjustedInput(T input) - { - if (mDeltaInput) - { - // Wrap - mDeltaCount = std::fmod(mDeltaCount + input, 1.0f); - return mDeltaCount; - } - else - { - return input; - } - } - - public: - /** Constructor. - @param - deltaInput If true, function will add input values together and wrap at 1.0 before evaluating - */ - ControllerFunction(bool deltaInput) - { - mDeltaInput = deltaInput; - mDeltaCount = 0; - } - - virtual ~ControllerFunction() {} - - virtual T calculate(T sourceValue) = 0; - }; - - - /** Can either be used as an input or output value. - */ - template - class ControllerValue : public ControllerAlloc - { - - public: - virtual ~ControllerValue() { } - virtual T getValue(void) const = 0; - virtual void setValue(T value) = 0; - - }; - - /** Instances of this class 'control' the value of another object in the system. - - Controller classes are used to manage the values of object automatically based - on the value of some input. For example, a Controller could animate a texture - by controlling the current frame of the texture based on time, or a different Controller - could change the colour of a material used for a spaceship shield mesh based on the remaining - shield power level of the ship. - @par - The Controller is an intentionally abstract concept - it can generate values - based on input and a function, which can either be one of the standard ones - supplied, or a function can be 'plugged in' for custom behaviour - see the ControllerFunction class for details. - Both the input and output values are via ControllerValue objects, meaning that any value can be both - input and output of the controller. - @par - Whilst this is very flexible, it can be a little bit confusing so to make it simpler the most often used - controller setups are available by calling methods on the ControllerManager object. - @see - ControllerFunction - - */ - template - class Controller : public ControllerAlloc - { - protected: - /// Source value - SharedPtr< ControllerValue > mSource; - /// Destination value - SharedPtr< ControllerValue > mDest; - /// Function - SharedPtr< ControllerFunction > mFunc; - /// Controller is enabled or not - bool mEnabled; - - - public: - - /** Usual constructor. - - Requires source and destination values, and a function object. None of these are destroyed - with the Controller when it is deleted (they can be shared) so you must delete these as appropriate. - */ - Controller(const SharedPtr< ControllerValue >& src, - const SharedPtr< ControllerValue >& dest, const SharedPtr< ControllerFunction >& func) - : mSource(src), mDest(dest), mFunc(func) - { - mEnabled = true; - } - - /** Default d-tor. - */ - virtual ~Controller() {} - - - /// Sets the input controller value - void setSource(const SharedPtr< ControllerValue >& src) - { - mSource = src; - } - /// Gets the input controller value - const SharedPtr< ControllerValue >& getSource(void) const - { - return mSource; - } - /// Sets the output controller value - void setDestination(const SharedPtr< ControllerValue >& dest) - { - mDest = dest; - } - - /// Gets the output controller value - const SharedPtr< ControllerValue >& getDestination(void) const - { - return mDest; - } - - /// Returns true if this controller is currently enabled - bool getEnabled(void) const - { - return mEnabled; - } - - /// Sets whether this controller is enabled - void setEnabled(bool enabled) - { - mEnabled = enabled; - } - - /** Sets the function object to be used by this controller. - */ - void setFunction(const SharedPtr< ControllerFunction >& func) - { - mFunc = func; - } - - /** Returns a pointer to the function object used by this controller. - */ - const SharedPtr< ControllerFunction >& getFunction(void) const - { - return mFunc; - } - - /** Tells this controller to map it's input controller value - to it's output controller value, via the controller function. - - This method is called automatically every frame by ControllerManager. - */ - void update(void) - { - if(mEnabled) - mDest->setValue(mFunc->calculate(mSource->getValue())); - } - - }; - - /** @} */ - /** @} */ - -} - -#endif diff --git a/OgreMain/include/OgreControllerManager.h b/OgreMain/include/OgreControllerManager.h deleted file mode 100644 index cf5a4581517..00000000000 --- a/OgreMain/include/OgreControllerManager.h +++ /dev/null @@ -1,273 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ControllerManager_H__ -#define __ControllerManager_H__ - -#include "OgrePrerequisites.h" - -#include "OgreCommon.h" -#include "OgreSingleton.h" -#include "OgreTextureUnitState.h" -#include "OgreSharedPtr.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Animation - * @{ - */ - - typedef SharedPtr< ControllerValue > ControllerValueRealPtr; - typedef SharedPtr< ControllerFunction > ControllerFunctionRealPtr; - - /** Class for managing Controller instances. - - This class is responsible to keeping tabs on all the Controller instances registered - and updating them when requested. It also provides a number of convenience methods - for creating commonly used controllers (such as texture animators). - */ - class _OgreExport ControllerManager : public Singleton, public ControllerAlloc - { - private: - typedef std::vector ControllerList; - ControllerList mControllers; - - /// Global predefined controller - ControllerValueRealPtr mFrameTimeController; - - /// Global predefined controller - ControllerFunctionRealPtr mPassthroughFunction; - - /// Last frame number updated - unsigned long mLastFrameNumber; - - public: - ControllerManager(); - ~ControllerManager(); - - /** Creates a new controller and registers it with the manager. - */ - ControllerFloat* createController(const ControllerValueRealPtr& src, - const ControllerValueRealPtr& dest, const ControllerFunctionRealPtr& func); - - /** Creates a new controller use frame time source and passthrough controller function. - */ - ControllerFloat* createFrameTimePassthroughController(const ControllerValueRealPtr& dest); - - /** Destroys all the controllers in existence. - */ - void clearControllers(void); - - /** Updates all the registered controllers. - */ - void updateAllControllers(void); - - - /** Returns a ControllerValue which provides the time since the last frame as a control value source. - - A common source value to use to feed into a controller is the time since the last frame. This method - returns a pointer to a common source value which provides this information. - @par - Remember the value will only be up to date after the RenderSystem::beginFrame method is called. - @see - RenderSystem::beginFrame - */ - const ControllerValueRealPtr& getFrameTimeSource(void) const; - - /** Retrieve a simple passthrough controller function. */ - const ControllerFunctionRealPtr& getPassthroughControllerFunction(void) const; - - /** Creates a texture layer animator controller. - - This helper method creates the Controller, ControllerValue and ControllerFunction classes required - to animate a texture. - @param layer - TextureUnitState object to animate - @param sequenceTime - The amount of time in seconds it will take to loop through all the frames. - */ - ControllerFloat* createTextureAnimator(TextureUnitState* layer, Real sequenceTime); - - /** Creates a basic time-based texture uv coordinate modifier designed for creating scrolling textures. - - This simple method allows you to easily create constant-speed uv scrolling textures. If you want to - specify different speed values for horizontal and vertical scroll, use the specific methods - ControllerManager::createTextureUScroller and ControllerManager::createTextureVScroller. - If you want more control, look up the ControllerManager::createTextureWaveTransformer - for more complex wave-based scrollers / stretchers / rotators. - @param layer - The texture layer to animate. - @param speed - Speed of horizontal (u-coord) and vertical (v-coord) scroll, in complete wraps per second. - */ - ControllerFloat* createTextureUVScroller(TextureUnitState* layer, Real speed); - - /** Creates a basic time-based texture u coordinate modifier designed for creating scrolling textures. - - This simple method allows you to easily create constant-speed u scrolling textures. If you want more - control, look up the ControllerManager::createTextureWaveTransformer for more complex wave-based - scrollers / stretchers / rotators. - @param layer - The texture layer to animate. - @param uSpeed - Speed of horizontal (u-coord) scroll, in complete wraps per second. - */ - ControllerFloat* createTextureUScroller(TextureUnitState* layer, Real uSpeed); - - /** Creates a basic time-based texture v coordinate modifier designed for creating scrolling textures. - - This simple method allows you to easily create constant-speed v scrolling textures. If you want more - control, look up the ControllerManager::createTextureWaveTransformer for more complex wave-based - scrollers / stretchers / rotators. - @param layer - The texture layer to animate. - @param vSpeed - Speed of vertical (v-coord) scroll, in complete wraps per second. - */ - ControllerFloat* createTextureVScroller(TextureUnitState* layer, Real vSpeed); - - /** Creates a basic time-based texture coordinate modifier designed for creating rotating textures. - - This simple method allows you to easily create constant-speed rotating textures. If you want more - control, look up the ControllerManager::createTextureWaveTransformer for more complex wave-based - scrollers / stretchers / rotators. - @param layer - The texture layer to rotate. - @param speed - Speed of rotation, in complete anticlockwise revolutions per second. - */ - ControllerFloat* createTextureRotater(TextureUnitState* layer, Real speed); - - /** Creates a very flexible time-based texture transformation which can alter the scale, position or - rotation of a texture based on a wave function. - @param layer - The texture layer to affect. - @param ttype - The type of transform, either translate (scroll), scale (stretch) or rotate (spin). - @param waveType - The shape of the wave, see WaveformType enum for details. - @param base - The base value of the output. - @param frequency - The speed of the wave in cycles per second. - @param phase - The offset of the start of the wave, e.g. 0.5 to start half-way through the wave. - @param amplitude - Scales the output so that instead of lying within 0..1 it lies within 0..1*amplitude for exaggerated effects. - */ - ControllerFloat* createTextureWaveTransformer(TextureUnitState* layer, TextureUnitState::TextureTransformType ttype, - WaveformType waveType, Real base = 0, Real frequency = 1, Real phase = 0, Real amplitude = 1); - - /** Creates a controller for passing a frame time value through to a vertex / fragment program parameter. - - The destination parameter is expected to be a float, and the '.x' attribute will be populated - with the appropriately scaled time value. - @param params - The parameters to update. - @param paramIndex - The index of the parameter to update; if you want a named parameter, then - retrieve the index beforehand using GpuProgramParameters::getParamIndex. - @param timeFactor - The factor by which to adjust the time elapsed by before passing it to the program. - */ - ControllerFloat* createGpuProgramTimerParam(GpuProgramParametersPtr params, size_t paramIndex, - Real timeFactor = 1.0f); - - /** Removes & destroys the controller passed in as a pointer. - */ - void destroyController(ControllerFloat* controller); - - /** Return relative speed of time as perceived by time based controllers. - - See setTimeFactor for full information on the meaning of this value. - */ - Real getTimeFactor(void) const; - - /** Set the relative speed to update frame time based controllers. - - Normally any controllers which use time as an input (FrameTimeController) are updated - automatically in line with the real passage of time. This method allows you to change - that, so that controllers are told that the time is passing slower or faster than it - actually is. Use this to globally speed up / slow down the effect of time-based controllers. - @param tf - The virtual speed of time (1.0 is real time). - */ - void setTimeFactor(Real tf); - - /** Gets the constant that is added to time lapsed between each frame. - - See setFrameDelay for full information on the meaning of this value. - */ - Real getFrameDelay(void) const; - - /** Sets a constant frame rate. - - This function is useful when rendering a sequence to - files that should create a film clip with constant frame - rate. - It will ensure that scrolling textures and animations - move at a constant frame rate. - @param fd - The delay in seconds wanted between each frame - (1.0f / 25.0f means a seconds worth of animation is done - in 25 frames). - */ - void setFrameDelay(Real fd); - - /** Return the elapsed time. - - See setElapsedTime for full information on the meaning of this value. - */ - Real getElapsedTime(void) const; - - /** Set the elapsed time. - - Normally elapsed time accumulated all frames time (which speed relative to time - factor) since the rendering loop started. This method allows your to change that to - special time, so some elapsed-time-based globally effect is repeatable. - @param elapsedTime - The new elapsed time. - */ - void setElapsedTime(Real elapsedTime); - - /// @copydoc Singleton::getSingleton() - static ControllerManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static ControllerManager* getSingletonPtr(void); - }; - - /** @} */ - /** @} */ - -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif // __ControllerManager_H__ diff --git a/OgreMain/include/OgreConvexBody.h b/OgreMain/include/OgreConvexBody.h deleted file mode 100644 index 50497230eed..00000000000 --- a/OgreMain/include/OgreConvexBody.h +++ /dev/null @@ -1,258 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Copyright (c) 2006 Matthias Fink, netAllied GmbH - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ConvexBody_H__ -#define __ConvexBody_H__ - -#include "OgrePrerequisites.h" -#include "OgrePolygon.h" -#include "OgreHeaderPrefix.h" -#include "Threading/OgreThreadHeaders.h" - -namespace Ogre -{ - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - /** Holds a solid representation of a convex body. - - Administers a convex body. All polygons of the body are convex and - planar. Several operations may be applied, ranging from intersection - to join where each result it itself a convex body. - */ - class _OgreExport ConvexBody - { - public: - typedef std::vector< Polygon* > PolygonList; - - private: - PolygonList mPolygons; - - // Static 'free list' of polygons to save reallocation, shared between all bodies - static PolygonList msFreePolygons; - OGRE_STATIC_MUTEX(msFreePolygonsMutex); - - public: - ConvexBody(); - ~ConvexBody(); - ConvexBody( const ConvexBody& cpy ); - - /** Build a new polygon representation from a frustum. - */ - void define(const Frustum& frustum); - - /** Build a new polygon representation from an AAB. - */ - void define(const AxisAlignedBox& aab); - - /** Clips the body with a frustum. The resulting holes - are filled with new polygons. - */ - void clip( const Frustum& frustum ); - - /** Clips the body with an AAB. The resulting holes - are filled with new polygons. - */ - void clip( const AxisAlignedBox& aab ); - - /** Clips the body with another body. - */ - void clip(const ConvexBody& body); - - /** Clips the object by the positive half space of a plane - */ - void clip(const Plane& pl, bool keepNegative = true); - - /** Extends the existing body to incorporate the passed in point as a - convex hull. - - You must already have constructed a basic body using a 'construct' - method. - */ - void extend(const Vector3& pt); - - /** Resets the object. - */ - void reset( void ); - - /** Returns the current number of polygons. - */ - size_t getPolygonCount( void ) const; - - /** Returns the number of vertices for a polygon - */ - size_t getVertexCount( size_t poly ) const; - - /** Returns a polygon. - */ - const Polygon& getPolygon( size_t poly ) const; - - /** Returns a specific vertex of a polygon. - */ - const Vector3& getVertex( size_t poly, size_t vertex ) const; - - /** Returns the normal of a specified polygon. - */ - const Vector3& getNormal( size_t poly ); - - /** Returns an AABB representation. - */ - AxisAlignedBox getAABB( void ) const; - - /** Checks if the body has a closed hull. - */ - bool hasClosedHull( void ) const; - - /** Merges all neighboring polygons into one single polygon if they are - lay in the same plane. - */ - void mergePolygons( void ); - - /** Determines if the current object is equal to the compared one. - */ - bool operator == ( const ConvexBody& rhs ) const; - - /** Determines if the current object is not equal to the compared one. - */ - bool operator != ( const ConvexBody& rhs ) const - { return !( *this == rhs ); } - - /** Prints out the body with all its polygons. - */ - _OgreExport friend std::ostream& operator<< ( std::ostream& strm, const ConvexBody& body ); - - /// Initialise the internal polygon pool used to minimise allocations - static void _initialisePool(); - /// Tear down the internal polygon pool used to minimise allocations - static void _destroyPool(); - - - private: - /** Get a new polygon from the pool. - */ - static Polygon* allocatePolygon(); - /** Release a polygon back tot he pool. */ - static void freePolygon(Polygon* poly); - /** Inserts a polygon at a particular point in the body. - @note - After this method is called, the ConvexBody 'owns' this Polygon - and will be responsible for deleting it. - */ - void insertPolygon(Polygon* pdata, size_t poly); - /** Inserts a polygon at the end. - @note - After this method is called, the ConvexBody 'owns' this Polygon - and will be responsible for deleting it. - */ - void insertPolygon(Polygon* pdata); - - /** Inserts a vertex for a polygon at a particular point. - @note - No checks are done whether the assembled polygon is (still) planar, - the caller must ensure that this is the case. - */ - void insertVertex(size_t poly, const Vector3& vdata, size_t vertex); - /** Inserts a vertex for a polygon at the end. - @note - No checks are done whether the assembled polygon is (still) planar, - the caller must ensure that this is the case. - */ - void insertVertex(size_t poly, const Vector3& vdata); - /** Deletes a specific polygon. - */ - void deletePolygon(size_t poly); - - /** Removes a specific polygon from the body without deleting it. - @note - The retrieved polygon needs to be deleted later by the caller. - */ - Polygon* unlinkPolygon(size_t poly); - - /** Moves all polygons from the parameter body to this instance. - @note Both the passed in object and this instance are modified - */ - void moveDataFromBody(ConvexBody& body); - - /** Deletes a specific vertex of a specific polygon. - */ - void deleteVertex(size_t poly, size_t vertex); - - /** Replace a polygon at a particular index. - @note Again, the passed in polygon is owned by this object after this - call returns, and this object is resonsible for deleting it. - */ - void setPolygon(Polygon* pdata, size_t poly ); - - /** Replace a specific vertex of a polygon. - @note - No checks are done whether the assembled polygon is (still) planar, - the caller must ensure that this is the case. - */ - void setVertex( size_t poly, const Vector3& vdata, size_t vertex ); - - /** Returns the single edges in an EdgeMap (= edges where one side is a vertex and the - other is empty space (a hole in the body)). - */ - Polygon::EdgeMap getSingleEdges() const; - - /** Stores the edges of a specific polygon in a passed in structure. - */ - void storeEdgesOfPolygon(size_t poly, Polygon::EdgeMap *edgeMap) const; - - /** Allocates space for an specified amount of polygons with - each of them having a specified number of vertices. - @note - Old data (if available) will be erased. - */ - void allocateSpace(size_t numPolygons, size_t numVertices); - - /** Searches for a pair (an edge) in the intersectionList with an entry - that equals vec, and removes it from the passed in list. - @param vec The vertex to search for in intersectionEdges - @param intersectionEdges A list of edges, which is updated if a match is found - @param vNext A reference to a vector which will be filled with the other - vertex at the matching edge, if found. - @return True if a match was found - */ - bool findAndEraseEdgePair(const Vector3& vec, - Polygon::EdgeMap& intersectionEdges, Vector3& vNext ) const; - - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreCustomCompositionPass.h b/OgreMain/include/OgreCustomCompositionPass.h deleted file mode 100644 index 4b094185aa6..00000000000 --- a/OgreMain/include/OgreCustomCompositionPass.h +++ /dev/null @@ -1,64 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __CustomCompositionPass_H__ -#define __CustomCompositionPass_H__ - -#include "OgrePrerequisites.h" -#include "OgreCompositionPass.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - /** Interface for custom composition passes, allowing custom operations (in addition to - * the quad, scene and clear operations) in composition passes. - * @see CompositorManager::registerCustomCompositionPass - */ - class _OgreExport CustomCompositionPass - { - public: - /** Create a custom composition operation. - @param pass The CompositionPass that triggered the request - @param instance The compositor instance that this operation will be performed in - This call only happens once during creation. The RenderSystemOperation will - get called each render. - */ - virtual CompositorInstance::RenderSystemOperation* createOperation( - CompositorInstance* instance, const CompositionPass* pass) = 0; - - protected: - virtual ~CustomCompositionPass() {} - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/OgreMain/include/OgreDataStream.h b/OgreMain/include/OgreDataStream.h deleted file mode 100644 index 7130cd8f984..00000000000 --- a/OgreMain/include/OgreDataStream.h +++ /dev/null @@ -1,545 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __DataStream_H__ -#define __DataStream_H__ - -#include "OgrePrerequisites.h" -#include "OgreSharedPtr.h" -#include -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - - /** General purpose class used for encapsulating the reading and writing of data. - - This class performs basically the same tasks as std::basic_istream, - except that it does not have any formatting capabilities, and is - designed to be subclassed to receive data from multiple sources, - including libraries which have no compatibility with the STL's - stream interfaces. As such, this is an abstraction of a set of - wrapper classes which pretend to be standard stream classes but - can actually be implemented quite differently. - @par - Generally, if a plugin or application provides an ArchiveFactory, - it should also provide a DataStream subclass which will be used - to stream data out of that Archive implementation, unless it can - use one of the common implementations included. - @note - Ogre makes no guarantees about thread safety, for performance reasons. - If you wish to access stream data asynchronously then you should - organise your own mutexes to avoid race conditions. - */ - class _OgreExport DataStream : public StreamAlloc - { - public: - enum AccessMode - { - READ = 1, - WRITE = 2 - }; - protected: - /// The name (e.g. resource name) that can be used to identify the source for this data (optional) - String mName; - /// Size of the data in the stream (may be 0 if size cannot be determined) - size_t mSize; - /// What type of access is allowed (AccessMode) - uint16 mAccess; - - #define OGRE_STREAM_TEMP_SIZE 128 - public: - /// Constructor for creating unnamed streams - DataStream(uint16 accessMode = READ) : mSize(0), mAccess(accessMode) {} - /// Constructor for creating named streams - DataStream(const String& name, uint16 accessMode = READ) - : mName(name), mSize(0), mAccess(accessMode) {} - /// Returns the name of the stream, if it has one. - const String& getName(void) { return mName; } - /// Gets the access mode of the stream - uint16 getAccessMode() const { return mAccess; } - /** Reports whether this stream is readable. */ - virtual bool isReadable() const { return (mAccess & READ) != 0; } - /** Reports whether this stream is writeable. */ - virtual bool isWriteable() const { return (mAccess & WRITE) != 0; } - virtual ~DataStream() {} - // Streaming operators - template DataStream& operator>>(T& val); - /** Read the requisite number of bytes from the stream, - stopping at the end of the file. - @param buf Reference to a buffer pointer - @param count Number of bytes to read - @return The number of bytes read - */ - virtual size_t read(void* buf, size_t count) = 0; - /** Write the requisite number of bytes from the stream (only applicable to - streams that are not read-only) - @param buf Pointer to a buffer containing the bytes to write - @param count Number of bytes to write - @return The number of bytes written - */ - virtual size_t write(const void* buf, size_t count) - { - (void)buf; - (void)count; - // default to not supported - return 0; - } - - /** Get a single line from the stream. - - The delimiter character is not included in the data - returned, and it is skipped over so the next read will occur - after it. The buffer contents will include a - terminating character. - @note - If you used this function, you must open the stream in binary mode, - otherwise, it'll produce unexpected results. - @param buf Reference to a buffer pointer - @param maxCount The maximum length of data to be read, excluding the terminating character - @param delim The delimiter to stop at - @return The number of bytes read, excluding the terminating character - */ - virtual size_t readLine(char* buf, size_t maxCount, const String& delim = "\n"); - - /** Returns a String containing the next line of data, optionally - trimmed for whitespace. - - This is a convenience method for text streams only, allowing you to - retrieve a String object containing the next line of data. The data - is read up to the next newline character and the result trimmed if - required. - @note - If you used this function, you must open the stream in binary mode, - otherwise, it'll produce unexpected results. - @param - trimAfter If true, the line is trimmed for whitespace (as in - String.trim(true,true)) - */ - virtual String getLine( bool trimAfter = true ); - - /** Returns a String containing the entire stream. - - This is a convenience method for text streams only, allowing you to - retrieve a String object containing all the data in the stream. - */ - virtual String getAsString(void); - - /** Skip a single line from the stream. - @note - If you used this function, you must open the stream in binary mode, - otherwise, it'll produce unexpected results. - @par - delim The delimiter(s) to stop at - @return The number of bytes skipped - */ - virtual size_t skipLine(const String& delim = "\n"); - - /** Skip a defined number of bytes. This can also be a negative value, in which case - the file pointer rewinds a defined number of bytes. */ - virtual void skip(long count) = 0; - - /** Repositions the read point to a specified byte. - */ - virtual void seek( size_t pos ) = 0; - - /** Returns the current byte offset from beginning */ - virtual size_t tell(void) const = 0; - - /** Returns true if the stream has reached the end. - */ - virtual bool eof(void) const = 0; - - /** Returns the total size of the data to be read from the stream, - or 0 if this is indeterminate for this stream. - */ - size_t size(void) const { return mSize; } - - /** Close the stream; this makes further operations invalid. */ - virtual void close(void) = 0; - - - }; - - /// List of DataStream items - typedef std::list DataStreamList; - - /** Common subclass of DataStream for handling data from chunks of memory. - */ - class _OgreExport MemoryDataStream : public DataStream - { - private: - /// Pointer to the start of the data area - uchar* mData; - /// Pointer to the current position in the memory - uchar* mPos; - /// Pointer to the end of the memory - uchar* mEnd; - /// Do we delete the memory on close - bool mFreeOnClose; - public: - - /** Wrap an existing memory chunk in a stream. - @param pMem Pointer to the existing memory - @param size The size of the memory chunk in bytes - @param freeOnClose If true, the memory associated will be destroyed - when the stream is closed. Note: it's important that if you set - this option to true, that you allocated the memory using OGRE_ALLOC_T - with a category of MEMCATEGORY_GENERAL to ensure the freeing of memory - matches up. - @param readOnly Whether to make the stream on this memory read-only once created - */ - MemoryDataStream(void* pMem, size_t size, bool freeOnClose = false, bool readOnly = false); - - /** Wrap an existing memory chunk in a named stream. - @param name The name to give the stream - @param pMem Pointer to the existing memory - @param size The size of the memory chunk in bytes - @param freeOnClose If true, the memory associated will be destroyed - when the stream is destroyed. Note: it's important that if you set - this option to true, that you allocated the memory using OGRE_ALLOC_T - with a category of MEMCATEGORY_GENERAL ensure the freeing of memory - matches up. - @param readOnly Whether to make the stream on this memory read-only once created - */ - MemoryDataStream(const String& name, void* pMem, size_t size, - bool freeOnClose = false, bool readOnly = false); - - /** Create a stream which pre-buffers the contents of another stream. - - This constructor can be used to intentionally read in the entire - contents of another stream, copying them to the internal buffer - and thus making them available in memory as a single unit. - @param sourceStream Another DataStream which will provide the source - of data - @param freeOnClose If true, the memory associated will be destroyed - when the stream is destroyed. - @param readOnly Whether to make the stream on this memory read-only once created - */ - MemoryDataStream(DataStream& sourceStream, - bool freeOnClose = true, bool readOnly = false); - - /** Create a stream which pre-buffers the contents of another stream. - - This constructor can be used to intentionally read in the entire - contents of another stream, copying them to the internal buffer - and thus making them available in memory as a single unit. - @param sourceStream Another DataStream which will provide the source - of data - @param freeOnClose If true, the memory associated will be destroyed - when the stream is destroyed. - @param readOnly Whether to make the stream on this memory read-only once created - */ - MemoryDataStream(const DataStreamPtr& sourceStream, - bool freeOnClose = true, bool readOnly = false); - - /** Create a named stream which pre-buffers the contents of - another stream. - - This constructor can be used to intentionally read in the entire - contents of another stream, copying them to the internal buffer - and thus making them available in memory as a single unit. - @param name The name to give the stream - @param sourceStream Another DataStream which will provide the source - of data - @param freeOnClose If true, the memory associated will be destroyed - when the stream is destroyed. - @param readOnly Whether to make the stream on this memory read-only once created - */ - MemoryDataStream(const String& name, DataStream& sourceStream, - bool freeOnClose = true, bool readOnly = false); - - /** Create a named stream which pre-buffers the contents of - another stream. - - This constructor can be used to intentionally read in the entire - contents of another stream, copying them to the internal buffer - and thus making them available in memory as a single unit. - @param name The name to give the stream - @param sourceStream Another DataStream which will provide the source - of data - @param freeOnClose If true, the memory associated will be destroyed - when the stream is destroyed. - @param readOnly Whether to make the stream on this memory read-only once created - */ - MemoryDataStream(const String& name, const DataStreamPtr& sourceStream, - bool freeOnClose = true, bool readOnly = false); - - /** Create a stream with a brand new empty memory chunk. - @param size The size of the memory chunk to create in bytes - @param freeOnClose If true, the memory associated will be destroyed - when the stream is destroyed. - @param readOnly Whether to make the stream on this memory read-only once created - */ - MemoryDataStream(size_t size, bool freeOnClose = true, bool readOnly = false); - /** Create a named stream with a brand new empty memory chunk. - @param name The name to give the stream - @param size The size of the memory chunk to create in bytes - @param freeOnClose If true, the memory associated will be destroyed - when the stream is destroyed. - @param readOnly Whether to make the stream on this memory read-only once created - */ - MemoryDataStream(const String& name, size_t size, - bool freeOnClose = true, bool readOnly = false); - - ~MemoryDataStream(); - - /** Get a pointer to the start of the memory block this stream holds. */ - uchar* getPtr(void) { return mData; } - - /** Get a pointer to the current position in the memory block this stream holds. */ - uchar* getCurrentPtr(void) { return mPos; } - - /** @copydoc DataStream::read - */ - size_t read(void* buf, size_t count) override; - - /** @copydoc DataStream::write - */ - size_t write(const void* buf, size_t count) override; - - /** @copydoc DataStream::readLine - */ - size_t readLine(char* buf, size_t maxCount, const String& delim = "\n") override; - - /** @copydoc DataStream::skipLine - */ - size_t skipLine(const String& delim = "\n") override; - - /** @copydoc DataStream::skip - */ - void skip(long count) override; - - /** @copydoc DataStream::seek - */ - void seek( size_t pos ) override; - - /** @copydoc DataStream::tell - */ - size_t tell(void) const override; - - /** @copydoc DataStream::eof - */ - bool eof(void) const override; - - /** @copydoc DataStream::close - */ - void close(void) override; - - /** Sets whether or not to free the encapsulated memory on close. */ - void setFreeOnClose(bool free) { mFreeOnClose = free; } - }; - - /** Common subclass of DataStream for handling data from - std::basic_istream. - */ - class _OgreExport FileStreamDataStream : public DataStream - { - private: - /// Reference to source stream (read) - std::istream* mInStream; - /// Reference to source file stream (read-only) - std::ifstream* mFStreamRO; - /// Reference to source file stream (read-write) - std::fstream* mFStream; - bool mFreeOnClose; - - void determineAccess(); - public: - /** Construct a read-only stream from an STL stream - @param s Pointer to source stream - @param freeOnClose Whether to delete the underlying stream on - destruction of this class - */ - FileStreamDataStream(std::ifstream* s, - bool freeOnClose = true); - /** Construct a read-write stream from an STL stream - @param s Pointer to source stream - @param freeOnClose Whether to delete the underlying stream on - destruction of this class - */ - FileStreamDataStream(std::fstream* s, - bool freeOnClose = true); - - /** Construct named read-only stream from an STL stream - @param name The name to give this stream - @param s Pointer to source stream - @param freeOnClose Whether to delete the underlying stream on - destruction of this class - */ - FileStreamDataStream(const String& name, - std::ifstream* s, - bool freeOnClose = true); - - /** Construct named read-write stream from an STL stream - @param name The name to give this stream - @param s Pointer to source stream - @param freeOnClose Whether to delete the underlying stream on - destruction of this class - */ - FileStreamDataStream(const String& name, - std::fstream* s, - bool freeOnClose = true); - - /** Construct named read-only stream from an STL stream, and tell it the size - - This variant tells the class the size of the stream too, which - means this class does not need to seek to the end of the stream - to determine the size up-front. This can be beneficial if you have - metadata about the contents of the stream already. - @param name The name to give this stream - @param s Pointer to source stream - @param size Size of the stream contents in bytes - @param freeOnClose Whether to delete the underlying stream on - destruction of this class. If you specify 'true' for this you - must ensure that the stream was allocated using OGRE_NEW_T with - MEMCATEGRORY_GENERAL. - */ - FileStreamDataStream(const String& name, - std::ifstream* s, - size_t size, - bool freeOnClose = true); - - /** Construct named read-write stream from an STL stream, and tell it the size - - This variant tells the class the size of the stream too, which - means this class does not need to seek to the end of the stream - to determine the size up-front. This can be beneficial if you have - metadata about the contents of the stream already. - @param name The name to give this stream - @param s Pointer to source stream - @param size Size of the stream contents in bytes - @param freeOnClose Whether to delete the underlying stream on - destruction of this class. If you specify 'true' for this you - must ensure that the stream was allocated using OGRE_NEW_T with - MEMCATEGRORY_GENERAL. - */ - FileStreamDataStream(const String& name, - std::fstream* s, - size_t size, - bool freeOnClose = true); - - ~FileStreamDataStream(); - - /** @copydoc DataStream::read - */ - size_t read(void* buf, size_t count) override; - - /** @copydoc DataStream::write - */ - size_t write(const void* buf, size_t count) override; - - /** @copydoc DataStream::readLine - */ - size_t readLine(char* buf, size_t maxCount, const String& delim = "\n") override; - - /** @copydoc DataStream::skip - */ - void skip(long count) override; - - /** @copydoc DataStream::seek - */ - void seek( size_t pos ) override; - - /** @copydoc DataStream::tell - */ - size_t tell(void) const override; - - /** @copydoc DataStream::eof - */ - bool eof(void) const override; - - /** @copydoc DataStream::close - */ - void close(void) override; - - - }; - - /** Common subclass of DataStream for handling data from C-style file - handles. - - Use of this class is generally discouraged; if you want to wrap file - access in a DataStream, you should definitely be using the C++ friendly - FileStreamDataStream. However, since there are quite a few applications - and libraries still wedded to the old FILE handle access, this stream - wrapper provides some backwards compatibility. - */ - class _OgreExport FileHandleDataStream : public DataStream - { - private: - FILE* mFileHandle; - public: - /// Create stream from a C file handle - FileHandleDataStream(FILE* handle, uint16 accessMode = READ); - /// Create named stream from a C file handle - FileHandleDataStream(const String& name, FILE* handle, uint16 accessMode = READ); - ~FileHandleDataStream(); - - /** @copydoc DataStream::read - */ - size_t read(void* buf, size_t count) override; - - /** @copydoc DataStream::write - */ - size_t write(const void* buf, size_t count) override; - - /** @copydoc DataStream::skip - */ - void skip(long count) override; - - /** @copydoc DataStream::seek - */ - void seek( size_t pos ) override; - - /** @copydoc DataStream::tell - */ - size_t tell(void) const override; - - /** @copydoc DataStream::eof - */ - bool eof(void) const override; - - /** @copydoc DataStream::close - */ - void close(void) override; - - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreDefaultDebugDrawer.h b/OgreMain/include/OgreDefaultDebugDrawer.h deleted file mode 100644 index a6b3db5cb7f..00000000000 --- a/OgreMain/include/OgreDefaultDebugDrawer.h +++ /dev/null @@ -1,48 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. - -#ifndef OGREMAIN_INCLUDE_OGREDEFAULTDEBUGDRAWER_H_ -#define OGREMAIN_INCLUDE_OGREDEFAULTDEBUGDRAWER_H_ - -#include "OgreSceneManager.h" - -namespace Ogre -{ - -class _OgreExport DefaultDebugDrawer : public DebugDrawer -{ - ManualObject mLines; - ManualObject mAxes; - int mDrawType; - bool mStatic; - float mBoneAxesSize; - void preFindVisibleObjects(SceneManager* source, SceneManager::IlluminationRenderStage irs, Viewport* v) override; - void postFindVisibleObjects(SceneManager* source, SceneManager::IlluminationRenderStage irs, Viewport* v) override; - void beginLines(); -public: - enum DrawType - { - DT_AXES = 1 << 0, - DT_WIREBOX = 1 << 1 - }; - - DefaultDebugDrawer(); - - /// if static, the drawer contents are preserved across frames. They are cleared otherwise. - void setStatic(bool enable) { mStatic = enable; } - - void drawBone(const Node* node, const Affine3 & transform = Affine3::IDENTITY) override; - void drawSceneNode(const SceneNode* node) override; - void drawFrustum(const Frustum* frust) override; - /// Allows the rendering of a wireframe bounding box. - void drawWireBox(const AxisAlignedBox& aabb, const ColourValue& colour = ColourValue::White); - /// draw coordinate axes - void drawAxes(const Affine3& pose, float size = 1.0f); - /// Specifes the size of the axes drawn by drawBone() - void setBoneAxesSize(float size); -}; - -} /* namespace Ogre */ - -#endif /* OGREMAIN_INCLUDE_OGREDEFAULTDEBUGDRAWER_H_ */ diff --git a/OgreMain/include/OgreDefaultHardwareBufferManager.h b/OgreMain/include/OgreDefaultHardwareBufferManager.h deleted file mode 100644 index 397866cb817..00000000000 --- a/OgreMain/include/OgreDefaultHardwareBufferManager.h +++ /dev/null @@ -1,127 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __DefaultHardwareBufferManager_H__ -#define __DefaultHardwareBufferManager_H__ - -#include "OgrePrerequisites.h" -#include "OgreHardwareBufferManager.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - - /// Specialisation of HardwareBuffer for emulation - class _OgreExport DefaultHardwareBuffer : public HardwareBuffer - { - private: - unsigned char* mData; - void* lockImpl(size_t offset, size_t length, LockOptions options) override; - void unlockImpl(void) override; - public: - DefaultHardwareBuffer(size_t sizeInBytes); - ~DefaultHardwareBuffer(); - void readData(size_t offset, size_t length, void* pDest) override; - void writeData(size_t offset, size_t length, const void* pSource, bool discardWholeBuffer = false) override; - bool isSystemMemory(void) const override { return true; } - }; - - typedef DefaultHardwareBuffer DefaultHardwareUniformBuffer; - - /** Specialisation of HardwareBufferManagerBase to emulate hardware buffers. - - You might want to instantiate this class if you want to utilise - classes like MeshSerializer without having initialised the - rendering system (which is required to create a 'real' hardware - buffer manager). - */ - class _OgreExport DefaultHardwareBufferManagerBase : public HardwareBufferManagerBase - { - public: - DefaultHardwareBufferManagerBase(); - ~DefaultHardwareBufferManagerBase(); - HardwareVertexBufferPtr createVertexBuffer(size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, - bool useShadowBuffer = false) override; - HardwareIndexBufferPtr createIndexBuffer(HardwareIndexBuffer::IndexType itype, size_t numIndexes, - HardwareBuffer::Usage usage, bool useShadowBuffer = false) override; - HardwareBufferPtr createUniformBuffer(size_t sizeBytes, HardwareBufferUsage = HBU_CPU_ONLY, - bool = false) override - { - return std::make_shared(sizeBytes); - } - }; - - /// DefaultHardwareBufferManager as a Singleton - class _OgreExport DefaultHardwareBufferManager : public HardwareBufferManager - { - std::unique_ptr mImpl; - public: - DefaultHardwareBufferManager() : mImpl(new DefaultHardwareBufferManagerBase()) {} - ~DefaultHardwareBufferManager() - { - // have to do this before mImpl is gone - destroyAllDeclarations(); - destroyAllBindings(); - } - - HardwareVertexBufferSharedPtr - createVertexBuffer(size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, - bool useShadowBuffer = false) override - { - return mImpl->createVertexBuffer(vertexSize, numVerts, usage, useShadowBuffer); - } - - HardwareIndexBufferSharedPtr - createIndexBuffer(HardwareIndexBuffer::IndexType itype, size_t numIndexes, - HardwareBuffer::Usage usage, bool useShadowBuffer = false) override - { - return mImpl->createIndexBuffer(itype, numIndexes, usage, useShadowBuffer); - } - - RenderToVertexBufferSharedPtr createRenderToVertexBuffer() override - { - return mImpl->createRenderToVertexBuffer(); - } - - HardwareBufferPtr createUniformBuffer(size_t sizeBytes, HardwareBufferUsage usage, - bool useShadowBuffer) override - { - return mImpl->createUniformBuffer(sizeBytes, usage, useShadowBuffer); - } - }; - - /** @} */ - /** @} */ - -} - -#endif diff --git a/OgreMain/include/OgreDefaultWorkQueue.h b/OgreMain/include/OgreDefaultWorkQueue.h deleted file mode 100644 index 45c0e9674f6..00000000000 --- a/OgreMain/include/OgreDefaultWorkQueue.h +++ /dev/null @@ -1,82 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ -#ifndef __OgreDefaultWorkQueue_H__ -#define __OgreDefaultWorkQueue_H__ - -#include "OgreWorkQueue.h" - -namespace Ogre -{ - /** Implementation of a general purpose request / response style background work queue. - - This default implementation of a work queue starts a thread pool and - provides queues to process requests. - */ - class _OgreExport DefaultWorkQueue : public DefaultWorkQueueBase - { - public: - - DefaultWorkQueue(const String& name = BLANKSTRING); - virtual ~DefaultWorkQueue(); - - /// Main function for each thread spawned. - void _threadMain() override; - - /// @copydoc WorkQueue::shutdown - void shutdown() override; - - /// @copydoc WorkQueue::startup - void startup(bool forceRestart = true) override; - - protected: - /** To be called by a separate thread; will return immediately if there - are items in the queue, or suspend the thread until new items are added - otherwise. - */ - virtual void waitForNextRequest(); - - /// Notify that a thread has registered itself with the render system - virtual void notifyThreadRegistered(); - - void notifyWorkers() override; - - size_t mNumThreadsRegisteredWithRS; - /// Init notification mutex (must lock before waiting on initCondition) - OGRE_WQ_MUTEX(mInitMutex); - /// Synchroniser token to wait / notify on thread init - OGRE_WQ_THREAD_SYNCHRONISER(mInitSync); - - OGRE_WQ_THREAD_SYNCHRONISER(mRequestCondition); -#if OGRE_THREAD_SUPPORT - typedef std::vector WorkerThreadList; - WorkerThreadList mWorkers; -#endif - - }; - -} - -#endif diff --git a/OgreMain/include/OgreDeflate.h b/OgreMain/include/OgreDeflate.h deleted file mode 100644 index afb1ca97cee..00000000000 --- a/OgreMain/include/OgreDeflate.h +++ /dev/null @@ -1,280 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#ifndef __OGRE_DEFLATE_H__ -#define __OGRE_DEFLATE_H__ - -#if OGRE_NO_ZIP_ARCHIVE == 0 - -#include "OgrePrerequisites.h" -#include "OgreDataStream.h" -#include "OgreHeaderPrefix.h" - -/// forward decls -struct mz_stream_s; -typedef struct mz_stream_s z_stream; - -namespace Ogre -{ - /** Template version of cache based on static array. - 'cacheSize' defines size of cache in bytes. */ - template - class StaticCache - { - private: - /// Static buffer - char mBuffer[cacheSize]; - - /// Number of bytes valid in cache (written from the beginning of static buffer) - size_t mValidBytes; - /// Current read position - size_t mPos; - public: - /// Constructor - StaticCache() - { - mValidBytes = 0; - mPos = 0; - memset(mBuffer, 0, cacheSize); - } - - /** Cache data pointed by 'buf'. If 'count' is greater than cache size, we cache only last bytes. - Returns number of bytes written to cache. */ - size_t cacheData(const void* buf, size_t count) - { - assert(avail() == 0 && "It is assumed that you cache data only after you have read everything."); - - if (count < cacheSize) - { - // number of bytes written is less than total size of cache - if (count + mValidBytes <= cacheSize) - { - // just append - memcpy(mBuffer + mValidBytes, buf, count); - mValidBytes += count; - } - else - { - size_t begOff = count - (cacheSize - mValidBytes); - // override old cache content in the beginning - memmove(mBuffer, mBuffer + begOff, mValidBytes - begOff); - // append new data - memcpy(mBuffer + cacheSize - count, buf, count); - mValidBytes = cacheSize; - } - mPos = mValidBytes; - return count; - } - else - { - // discard all - memcpy(mBuffer, (const char*)buf + count - cacheSize, cacheSize); - mValidBytes = mPos = cacheSize; - return cacheSize; - } - } - /** Read data from cache to 'buf' (maximum 'count' bytes). Returns number of bytes read from cache. */ - size_t read(void* buf, size_t count) - { - size_t rb = avail(); - rb = (rb < count) ? rb : count; - memcpy(buf, mBuffer + mPos, rb); - mPos += rb; - return rb; - } - - /** Step back in cached stream by 'count' bytes. Returns 'true' if cache contains resulting position. */ - bool rewind(size_t count) - { - if (mPos < count) - { - clear(); - return false; - } - else - { - mPos -= count; - return true; - } - } - /** Step forward in cached stream by 'count' bytes. Returns 'true' if cache contains resulting position. */ - bool ff(size_t count) - { - if (avail() < count) - { - clear(); - return false; - } - else - { - mPos += count; - return true; - } - } - - /** Returns number of bytes available for reading in cache after rewinding. */ - size_t avail() const - { - return mValidBytes - mPos; - } - - /** Clear the cache */ - void clear() - { - mValidBytes = 0; - mPos = 0; - } - }; - - /** Stream which compresses / uncompresses data using the 'deflate' compression - algorithm. - - This stream is designed to wrap another stream for the actual source / destination - of the compressed data, it has no concrete source / data itself. The idea is - that you pass uncompressed data through this stream, and the underlying - stream reads/writes compressed data to the final source. - @note - This is an alternative to using a compressed archive since it is able to - compress & decompress regardless of the actual source of the stream. - You should avoid using this with already compressed archives. - Also note that this cannot be used as a read / write stream, only a read-only - or write-only stream. - */ - class _OgreExport DeflateStream : public DataStream - { - public: - /** Requested stream type. All are essentially the same deflate stream with varying wrapping. - ZLib is used by default. - */ - enum StreamType - { - Invalid = -1, /// Unexpected stream type or uncompressed data - Deflate = 0, /// no header, no checksum, rfc1951 - ZLib = 1, /// 2 byte header, 4 byte footer with adler32 checksum, rfc1950 - GZip = 2, /// 10 byte header, 8 byte footer with crc32 checksum and unpacked size, rfc1952 - }; - private: - DataStreamPtr mCompressedStream; - DataStreamPtr mTmpWriteStream; - String mTempFileName; - z_stream* mZStream; - int mStatus; - size_t mCurrentPos; - size_t mAvailIn; - - /// Cache for read data in case skipping around - StaticCache<16 * OGRE_STREAM_TEMP_SIZE> mReadCache; - - /// Intermediate buffer for read / write - unsigned char *mTmp; - - /// Whether the underlying stream is valid compressed data - StreamType mStreamType; - - void init(); - void destroy(); - void compressFinal(); - - size_t getAvailInForSinglePass(); - public: - /** Constructor for creating unnamed stream wrapping another stream. - @param compressedStream The stream that this stream will use when reading / - writing compressed data. The access mode from this stream will be matched. - @param tmpFileName Path/Filename to be used for temporary storage of incoming data - @param avail_in Available data length to be uncompressed. With it we can uncompress - DataStream partly. - */ - DeflateStream(const DataStreamPtr& compressedStream, const String& tmpFileName = "", - size_t avail_in = 0); - /** Constructor for creating named stream wrapping another stream. - @param name The name to give this stream - @param compressedStream The stream that this stream will use when reading / - writing compressed data. The access mode from this stream will be matched. - @param tmpFileName Path/Filename to be used for temporary storage of incoming data - @param avail_in Available data length to be uncompressed. With it we can uncompress - DataStream partly. - */ - DeflateStream(const String& name, const DataStreamPtr& compressedStream, const String& tmpFileName="", - size_t avail_in = 0); - /** Constructor for creating named stream wrapping another stream. - @param name The name to give this stream - @param compressedStream The stream that this stream will use when reading / - writing compressed data. The access mode from this stream will be matched. - @param streamType The type of compressed stream - @param tmpFileName Path/Filename to be used for temporary storage of incoming data - @param avail_in Available data length to be uncompressed. With it we can uncompress - DataStream partly. - */ - DeflateStream(const String& name, const DataStreamPtr& compressedStream, StreamType streamType, const String& tmpFileName="", - size_t avail_in = 0); - - ~DeflateStream(); - - /** Returns whether the compressed stream is valid deflated data. - - If you pass this class a READ stream which is not compressed with the - deflate algorithm, this method returns false and all read commands - will actually be executed as passthroughs as a fallback. - */ - bool isCompressedStreamValid() const { return mStreamType != Invalid; } - - /** @copydoc DataStream::read - */ - size_t read(void* buf, size_t count) override; - - /** @copydoc DataStream::write - */ - size_t write(const void* buf, size_t count) override; - - /** @copydoc DataStream::skip - */ - void skip(long count) override; - - /** @copydoc DataStream::seek - */ - void seek( size_t pos ) override; - - /** @copydoc DataStream::tell - */ - size_t tell(void) const override; - - /** @copydoc DataStream::eof - */ - bool eof(void) const override; - - /** @copydoc DataStream::close - */ - void close(void) override; - - }; -} - -#include "OgreHeaderSuffix.h" - -#endif - -#endif diff --git a/OgreMain/include/OgreDeprecated.h b/OgreMain/include/OgreDeprecated.h deleted file mode 100644 index 6fe07c4e33a..00000000000 --- a/OgreMain/include/OgreDeprecated.h +++ /dev/null @@ -1,106 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. - -#ifndef OGREMAIN_INCLUDE_OGREDEPRECATED_H_ -#define OGREMAIN_INCLUDE_OGREDEPRECATED_H_ - -#include "OgreStdHeaders.h" -#include "OgreMemoryAllocatorConfig.h" - -#include - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \defgroup deprecated deprecated - * deprecated std:: wrappers for backwards-compatibility only - * @{ - */ - template using AtomicScalar = std::atomic; - - struct SPFMNone { - void operator()(void*) {} - }; - const SPFMNone SPFM_NONE; - - struct SPFMDeleteT { - template - void operator()(T* p) { - OGRE_DELETE_T(p, T, MEMCATEGORY_GENERAL); - } - }; - const SPFMDeleteT SPFM_DELETE_T; - - typedef std::map QuadMaterialMap; - -#define OGRE_HashMap ::std::unordered_map -#define OGRE_HashMultiMap ::std::unordered_multimap -#define OGRE_HashSet ::std::unordered_set -#define OGRE_HashMultiSet ::std::unordered_multiset - - template - struct deque - { - typedef typename std::deque type; - typedef typename std::deque::iterator iterator; - typedef typename std::deque::const_iterator const_iterator; - }; - - template - struct vector - { - typedef typename std::vector type; - typedef typename std::vector::iterator iterator; - typedef typename std::vector::const_iterator const_iterator; - }; - - template - struct list - { - typedef typename std::list type; - typedef typename std::list::iterator iterator; - typedef typename std::list::const_iterator const_iterator; - }; - - template > - struct set - { - typedef typename std::set type; - typedef typename std::set::iterator iterator; - typedef typename std::set::const_iterator const_iterator; - }; - - template > - struct map - { - typedef typename std::map type; - typedef typename std::map::iterator iterator; - typedef typename std::map::const_iterator const_iterator; - }; - - template > - struct multimap - { - typedef typename std::multimap type; - typedef typename std::multimap::iterator iterator; - typedef typename std::multimap::const_iterator const_iterator; - }; - - /// Bitmask containing scene types - typedef uint16 SceneTypeMask; - enum SceneType - { - ST_GENERIC = 1, - ST_EXTERIOR_CLOSE = 2, - ST_EXTERIOR_FAR = 4, - ST_EXTERIOR_REAL_FAR = 8, - ST_INTERIOR = 16 - }; - /** @} */ - /** @} */ -} // Ogre - -#endif /* OGREMAIN_INCLUDE_OGREDEPRECATED_H_ */ diff --git a/OgreMain/include/OgreDepthBuffer.h b/OgreMain/include/OgreDepthBuffer.h deleted file mode 100644 index b4dfac62f2e..00000000000 --- a/OgreMain/include/OgreDepthBuffer.h +++ /dev/null @@ -1,146 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __DepthBuffer_H__ -#define __DepthBuffer_H__ - -#include "OgrePrerequisites.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - - /** An abstract class that contains a depth/stencil buffer. - Depth Buffers can be attached to render targets. Note we handle Depth & Stencil together. - DepthBuffer sharing is handled automatically for you. However, there are times where you want - to specifically control depth buffers to achieve certain effects or increase performance. - You can control this by hinting Ogre with POOL IDs. Created depth buffers can live in different - pools, or all together in the same one. - Usually, a depth buffer can only be attached to a RenderTarget if it's dimensions are bigger - and have the same bit depth and same multisample settings. Depth Buffers are created automatically - for new RTs when needed, and stored in the pool where the RenderTarget should have drawn from. - By default, all RTs have the Id POOL_DEFAULT, which means all depth buffers are stored by default - in that pool. By choosing a different Pool Id for a specific RenderTarget, that RT will only - retrieve depth buffers from _that_ pool, therefore not conflicting with sharing depth buffers - with other RTs (such as shadows maps). - Setting an RT to POOL_MANUAL_USAGE means Ogre won't manage the DepthBuffer for you (not recommended) - RTs with POOL_NO_DEPTH are very useful when you don't want to create a DepthBuffer for it. You can - still manually attach a depth buffer though as internally POOL_NO_DEPTH & POOL_MANUAL_USAGE are - handled in the same way. - - Behavior is consistent across all render systems, if, and only if, the same RSC flags are set - RSC flags that affect this class are: - * RSC_RTT_MAIN_DEPTHBUFFER_ATTACHABLE: - some APIs (ie. OpenGL w/ FBO) don't allow using - the main depth buffer for offscreen RTTs. When this flag is set, the depth buffer can be - shared between the main window and an RTT. - * RSC_RTT_DEPTHBUFFER_RESOLUTION_LESSEQUAL: - When this flag isn't set, the depth buffer can only be shared across RTTs who have the EXACT - same resolution. When it's set, it can be shared with RTTs as long as they have a - resolution less or equal than the depth buffer's. - - - Design discussion http://www.ogre3d.org/forums/viewtopic.php?f=4&t=53534&p=365582 - */ - class _OgreExport DepthBuffer : public RenderSysAlloc - { - public: - enum PoolId - { - POOL_NO_DEPTH = 0, - POOL_MANUAL_USAGE = 0, - POOL_DEFAULT = 1 - }; - - DepthBuffer(uint16 poolId, uint32 width, uint32 height, uint32 fsaa, bool manual); - virtual ~DepthBuffer(); - - /** Sets the pool id in which this DepthBuffer lives. - Note this will detach any render target from this depth buffer */ - void _setPoolId( uint16 poolId ); - - /// Gets the pool id in which this DepthBuffer lives - virtual uint16 getPoolId() const; - virtual uint32 getWidth() const; - virtual uint32 getHeight() const; - uint32 getFSAA() const { return mFsaa; } - - /** Manual DepthBuffers are cleared in RenderSystem's destructor. Non-manual ones are released - with it's render target (aka, a backbuffer or similar) */ - bool isManual() const; - - /** Returns whether the specified RenderTarget is compatible with this DepthBuffer - That is, this DepthBuffer can be attached to that RenderTarget - - Most APIs impose the following restrictions: - Width & height must be equal or higher than the render target's - They must be of the same bit depth. - They need to have the same FSAA setting - @param renderTarget The render target to test against - */ - virtual bool isCompatible( RenderTarget *renderTarget ) const; - - /** Called when a RenderTarget is attaches this DepthBuffer - - This function doesn't actually attach. It merely informs the DepthBuffer - which RenderTarget did attach. The real attachment happens in - RenderTarget::attachDepthBuffer() - @param renderTarget The RenderTarget that has just been attached - */ - virtual void _notifyRenderTargetAttached( RenderTarget *renderTarget ); - - /** Called when a RenderTarget is detaches from this DepthBuffer - - Same as DepthBuffer::_notifyRenderTargetAttached() - @param renderTarget The RenderTarget that has just been detached - */ - virtual void _notifyRenderTargetDetached( RenderTarget *renderTarget ); - - protected: - typedef std::set RenderTargetSet; - - uint16 mPoolId; - uint32 mWidth; - uint32 mHeight; - uint32 mFsaa; - - bool mManual; //We don't Release manual surfaces on destruction - RenderTargetSet mAttachedRenderTargets; - - void detachFromAllRenderTargets(); - }; -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreDistanceLodStrategy.h b/OgreMain/include/OgreDistanceLodStrategy.h deleted file mode 100644 index b4d6aff207f..00000000000 --- a/OgreMain/include/OgreDistanceLodStrategy.h +++ /dev/null @@ -1,182 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Distance_Lod_Strategy_H__ -#define __Distance_Lod_Strategy_H__ - -#include "OgrePrerequisites.h" - -#include "OgreLodStrategy.h" -#include "OgreSingleton.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup LOD - * @{ - */ - - /** Level of detail strategy based on distance from camera. This is an abstract base class for DistanceLodBoxStrategy and DistanceLodSphereStrategy. - - The purpose of the reference view is to ensure a consistent experience for all users. Monitors of different resolutions and aspect ratios will each have different results for the distance queries. - @par - It depends on gameplay testing. If all testers had 16:9 monitors and 110° FOV, then that's the value you should enter (to ensure as much as possible the experience stays consistent for all other users who don't have a 16:9 monitor and/or use a different FOV). - @par - If all your testers had 4:3 monitors, then enter a 4:3 resolution. - @par - If all your testers had varying resolutions or you just didn't care, then this feature is useless for you and should be disabled (default: disabled). - */ - class _OgreExport DistanceLodStrategyBase : public LodStrategy - { - protected: - /// @copydoc LodStrategy::getValueImpl - Real getValueImpl(const MovableObject *movableObject, const Camera *camera) const override; - - public: - /** Default constructor. */ - DistanceLodStrategyBase(const String& name); - - /// @copydoc LodStrategy::getBaseValue - Real getBaseValue() const override; - - /// @copydoc LodStrategy::transformBias - Real transformBias(Real factor) const override; - - /// @copydoc LodStrategy::transformUserValue - Real transformUserValue(Real userValue) const override; - - /// @copydoc LodStrategy::getIndex - ushort getIndex(Real value, const Mesh::MeshLodUsageList& meshLodUsageList) const override; - - /// @copydoc LodStrategy::getIndex - ushort getIndex(Real value, const Material::LodValueList& materialLodValueList) const override; - - /// @copydoc LodStrategy::sort - void sort(Mesh::MeshLodUsageList& meshLodUsageList) const override; - - /// @copydoc LodStrategy::isSorted - bool isSorted(const Mesh::LodValueList& values) const override; - - /** Get the squared distance between the camera and the LOD object */ - virtual Real getSquaredDepth(const MovableObject *movableObject, const Ogre::Camera *camera) const = 0; - - /** Sets the reference view upon which the distances were based. - @note - This automatically enables use of the reference view. - @note - There is no corresponding get method for these values as - they are not saved, but used to compute a reference value. - */ - void setReferenceView(Real viewportWidth, Real viewportHeight, Radian fovY); - - /** Enables to disables use of the reference view. - @note Do not enable use of the reference view before setting it. - */ - void setReferenceViewEnabled(bool value); - - /** Determine if use of the reference view is enabled */ - bool isReferenceViewEnabled() const; - - private: - bool mReferenceViewEnabled; - Real mReferenceViewValue; - - }; - /** @} */ - /** @} */ - - /** \addtogroup Core - * @{ - */ - /** \addtogroup LOD - * @{ - */ - - /** Level of detail strategy based on distance from camera to an object's bounding sphere. - - The purpose of the reference view is to ensure a consistent experience for all users. Monitors of different resolutions and aspect ratios will each have different results for the distance queries. - @par - It depends on gameplay testing. If all testers had 16:9 monitors and 110° FOV, then that's the value you should enter (to ensure as much as possible the experience stays consistent for all other users who don't have a 16:9 monitor and/or use a different FOV). - @par - If all your testers had 4:3 monitors, then enter a 4:3 resolution. - @par - If all your testers had varying resolutions or you just didn't care, then this feature is useless for you and should be disabled (default: disabled). - */ - class _OgreExport DistanceLodSphereStrategy : public DistanceLodStrategyBase, public Singleton - { - public: - /** Default constructor. */ - DistanceLodSphereStrategy(); - - Real getSquaredDepth(const MovableObject *movableObject, const Ogre::Camera *camera) const override; - - /// @copydoc Singleton::getSingleton() - static DistanceLodSphereStrategy& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static DistanceLodSphereStrategy* getSingletonPtr(void); - }; - /** @} */ - /** @} */ - - /** \addtogroup Core - * @{ - */ - /** \addtogroup LOD - * @{ - */ - - /** Level of detail strategy based on distance from camera to an object's bounding box. - - The purpose of the reference view is to ensure a consistent experience for all users. Monitors of different resolutions and aspect ratios will each have different results for the distance queries. - @par - It depends on gameplay testing. If all testers had 16:9 monitors and 110° FOV, then that's the value you should enter (to ensure as much as possible the experience stays consistent for all other users who don't have a 16:9 monitor and/or use a different FOV). - @par - If all your testers had 4:3 monitors, then enter a 4:3 resolution. - @par - If all your testers had varying resolutions or you just didn't care, then this feature is useless for you and should be disabled (default: disabled). - */ - class _OgreExport DistanceLodBoxStrategy : public DistanceLodStrategyBase, public Singleton - { - public: - /** Default constructor. */ - DistanceLodBoxStrategy(); - - Real getSquaredDepth(const MovableObject *movableObject, const Ogre::Camera *camera) const override; - - /// @copydoc Singleton::getSingleton() - static DistanceLodBoxStrategy& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static DistanceLodBoxStrategy* getSingletonPtr(void); - }; - - /** @} */ - /** @} */ - -} // namespace - -#endif diff --git a/OgreMain/include/OgreDualQuaternion.h b/OgreMain/include/OgreDualQuaternion.h deleted file mode 100644 index a48bf0efebc..00000000000 --- a/OgreMain/include/OgreDualQuaternion.h +++ /dev/null @@ -1,186 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __DualQuaternion_H__ -#define __DualQuaternion_H__ - -#include "OgrePrerequisites.h" -#include "OgreMath.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - /** Implementation of a dual quaternion, i.e. a rotation around an axis and a translation. - This implementation may note be appropriate as a general implementation, but is intended for use with - dual quaternion skinning. - */ - class _OgreExport DualQuaternion - { - public: - /// Default constructor, initializes to identity rotation (aka 0°), and zero translation (0,0,0) - inline DualQuaternion () - : w(1), x(0), y(0), z(0), dw(1), dx(0), dy(0), dz(0) - { - } - - /// Construct from an explicit list of values - inline DualQuaternion (Real fW, Real fX, Real fY, Real fZ, - Real fdW, Real fdX, Real fdY, Real fdZ) - : w(fW), x(fX), y(fY), z(fZ), dw(fdW), dx(fdX), dy(fdY), dz(fdZ) - { - } - - /// Construct a dual quaternion from a transformation matrix - inline DualQuaternion(const Affine3& rot) - { - this->fromTransformationMatrix(rot); - } - - /// Construct a dual quaternion from a unit quaternion and a translation vector - inline DualQuaternion(const Quaternion& q, const Vector3& trans) - { - this->fromRotationTranslation(q, trans); - } - - /// Construct a dual quaternion from 8 manual w/x/y/z/dw/dx/dy/dz values - inline DualQuaternion(Real* valptr) - { - memcpy(&w, valptr, sizeof(Real)*8); - } - - /// Array accessor operator - inline Real operator [] ( const size_t i ) const - { - assert( i < 8 ); - - return *(&w+i); - } - - /// Array accessor operator - inline Real& operator [] ( const size_t i ) - { - assert( i < 8 ); - - return *(&w+i); - } - - inline DualQuaternion& operator= (const DualQuaternion& rkQ) - { - w = rkQ.w; - x = rkQ.x; - y = rkQ.y; - z = rkQ.z; - dw = rkQ.dw; - dx = rkQ.dx; - dy = rkQ.dy; - dz = rkQ.dz; - - return *this; - } - - inline bool operator== (const DualQuaternion& rhs) const - { - return (rhs.w == w) && (rhs.x == x) && (rhs.y == y) && (rhs.z == z) && - (rhs.dw == dw) && (rhs.dx == dx) && (rhs.dy == dy) && (rhs.dz == dz); - } - - inline bool operator!= (const DualQuaternion& rhs) const - { - return !operator==(rhs); - } - - /// Pointer accessor for direct copying - inline Real* ptr() - { - return &w; - } - - /// Pointer accessor for direct copying - inline const Real* ptr() const - { - return &w; - } - - /// Exchange the contents of this dual quaternion with another. - inline void swap(DualQuaternion& other) - { - std::swap(w, other.w); - std::swap(x, other.x); - std::swap(y, other.y); - std::swap(z, other.z); - std::swap(dw, other.dw); - std::swap(dx, other.dx); - std::swap(dy, other.dy); - std::swap(dz, other.dz); - } - -#ifndef OGRE_FAST_MATH - /// Check whether this dual quaternion contains valid values - inline bool isNaN() const - { - return Math::isNaN(w) || Math::isNaN(x) || Math::isNaN(y) || Math::isNaN(z) || - Math::isNaN(dw) || Math::isNaN(dx) || Math::isNaN(dy) || Math::isNaN(dz); - } -#endif - - /// Construct a dual quaternion from a rotation described by a Quaternion and a translation described by a Vector3 - void fromRotationTranslation (const Quaternion& q, const Vector3& trans); - - /// Convert a dual quaternion into its two components, a Quaternion representing the rotation and a Vector3 representing the translation - void toRotationTranslation (Quaternion& q, Vector3& translation) const; - - /// Construct a dual quaternion from a 4x4 transformation matrix - void fromTransformationMatrix (const Affine3& kTrans); - - /// Convert a dual quaternion to a 4x4 transformation matrix - void toTransformationMatrix (Affine3& kTrans) const; - - Real w, x, y, z, dw, dx, dy, dz; - - /** - Function for writing to a stream. Outputs "DualQuaternion(w, x, y, z, dw, dx, dy, dz)" with w, x, y, z, dw, dx, dy, dz - being the member values of the dual quaternion. - */ - inline _OgreExport friend std::ostream& operator << - ( std::ostream& o, const DualQuaternion& q ) - { - o << "DualQuaternion(" << q.w << ", " << q.x << ", " << q.y << ", " << q.z << ", " << q.dw << ", " << q.dx << ", " << q.dy << ", " << q.dz << ")"; - return o; - } - }; - /** @} */ - /** @} */ - -} - -#endif diff --git a/OgreMain/include/OgreDynLib.h b/OgreMain/include/OgreDynLib.h deleted file mode 100644 index ebf23874be9..00000000000 --- a/OgreMain/include/OgreDynLib.h +++ /dev/null @@ -1,112 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _DynLib_H__ -#define _DynLib_H__ - -#include "OgrePrerequisites.h" -#include "OgreHeaderPrefix.h" - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT -struct HINSTANCE__; -#endif - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT - typedef struct HINSTANCE__* DYNLIB_HANDLE; -#else - typedef void* DYNLIB_HANDLE; -#endif - - /** Resource holding data about a dynamic library. - - This class holds the data required to get symbols from - libraries loaded at run-time (i.e. from DLL's for so's) - @author - Adrian Cearn„u (cearny@cearny.ro) - @since - 27 January 2002 - */ - class _OgreExport DynLib : public DynLibAlloc - { - private: - String mName; - /// Gets the last loading error - String dynlibError(void); - public: - /** Default constructor - used by DynLibManager. - @warning - Do not call directly - */ - DynLib( const String& name ); - - /** Default destructor. - */ - ~DynLib(); - - /** Load the library - */ - void load(); - /** Unload the library - */ - void unload(); - /// Get the name of the library - const String& getName(void) const { return mName; } - - /** - Returns the address of the given symbol from the loaded library. - @param - strName The name of the symbol to search for - @return - If the function succeeds, the returned value is a handle to - the symbol. - @par - If the function fails, the returned value is NULL. - - */ - void* getSymbol( const String& strName ) const throw(); - - private: - - /// Handle to the loaded library. - DYNLIB_HANDLE mInst; - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreDynLibManager.h b/OgreMain/include/OgreDynLibManager.h deleted file mode 100644 index 848ec066a49..00000000000 --- a/OgreMain/include/OgreDynLibManager.h +++ /dev/null @@ -1,92 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __DynLibManager_H__ -#define __DynLibManager_H__ - -#include "OgrePrerequisites.h" -#include "OgreSingleton.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - /** Manager for Dynamic-loading Libraries. - - This manager keeps a track of all the open dynamic-loading - libraries, opens them and returns references to already-open - libraries. - */ - class _OgreExport DynLibManager: public Singleton, public DynLibAlloc - { - private: - typedef std::map DynLibList; - DynLibList mLibList; - public: - /** Default constructor. - @note -
Should never be called as the singleton is automatically - created during the creation of the Root object. - @see - Root::Root - */ - DynLibManager(); - - /** Default destructor. - @see - Root::~Root - */ - ~DynLibManager(); - - /** Loads the passed library. - @param filename - The name of the library. The extension can be omitted. - */ - DynLib* load(const String& filename); - - /** Unloads the passed library. - @param lib - The library. - */ - void unload(DynLib* lib); - - /// @copydoc Singleton::getSingleton() - static DynLibManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static DynLibManager* getSingletonPtr(void); - }; - /** @} */ - /** @} */ -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif // __DynLibManager_H__ diff --git a/OgreMain/include/OgreEdgeListBuilder.h b/OgreMain/include/OgreEdgeListBuilder.h deleted file mode 100644 index aa3fff9031c..00000000000 --- a/OgreMain/include/OgreEdgeListBuilder.h +++ /dev/null @@ -1,278 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __EdgeListBuilder_H__ -#define __EdgeListBuilder_H__ - -#include "OgrePrerequisites.h" -#include "OgreRenderOperation.h" -#include "OgreVector.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - - - /** This class contains the information required to describe the edge connectivity of a - given set of vertices and indexes. - - This information is built using the EdgeListBuilder class. Note that for a given mesh, - which can be made up of multiple submeshes, there are separate edge lists for when - */ - class _OgreExport EdgeData : public EdgeDataAlloc - { - public: - - EdgeData(); - - /** Basic triangle structure. */ - struct Triangle { - /** The set of indexes this triangle came from (NB it is possible that the triangles on - one side of an edge are using a different vertex buffer from those on the other side.) */ - size_t indexSet; - /** The vertex set these vertices came from. */ - size_t vertexSet; - /// Vertex indexes, relative to the original buffer - size_t vertIndex[3]; - /** Vertex indexes, relative to a shared vertex buffer with - duplicates eliminated (this buffer is not exposed) */ - size_t sharedVertIndex[3]; - - Triangle() :indexSet(0), vertexSet(0) {} - }; - /** Edge data. */ - struct Edge { - /** The indexes of the 2 tris attached, note that tri 0 is the one where the - indexes run _anti_ clockwise along the edge. Indexes must be - reversed for tri 1. */ - size_t triIndex[2]; - /** The vertex indices for this edge. Note that both vertices will be in the vertex - set as specified in 'vertexSet', which will also be the same as tri 0 */ - size_t vertIndex[2]; - /** Vertex indices as used in the shared vertex list, not exposed. */ - size_t sharedVertIndex[2]; - /** Indicates if this is a degenerate edge, ie it does not have 2 triangles */ - bool degenerate; - }; - - /** Array of 4D vector of triangle face normal, which is unit vector orthogonal - to the triangles, plus distance from origin. - Use aligned policy here because we are intended to use in SIMD optimised routines. */ - typedef aligned_vector TriangleFaceNormalList; - - /** Working vector used when calculating the silhouette. - Use std::vector instead of std::vector which might implemented - similar bit-fields causing loss performance. */ - typedef std::vector TriangleLightFacingList; - - typedef std::vector TriangleList; - typedef std::vector EdgeList; - - /** A group of edges sharing the same vertex data. */ - struct EdgeGroup - { - /** The vertex set index that contains the vertices for this edge group. */ - size_t vertexSet; - /** Pointer to vertex data used by this edge group. */ - const VertexData* vertexData; - /** Index to main triangles array, indicate the first triangle of this edge - group, and all triangles of this edge group are stored continuous in - main triangles array. - */ - size_t triStart; - /** Number triangles of this edge group. */ - size_t triCount; - /** The edges themselves. */ - EdgeList edges; - - }; - - typedef std::vector EdgeGroupList; - - /** Main triangles array, stores all triangles of this edge list. Note that - triangles are grouping against edge group. - */ - TriangleList triangles; - /** All triangle face normals. It should be 1:1 with triangles. */ - TriangleFaceNormalList triangleFaceNormals; - /** Triangle light facing states. It should be 1:1 with triangles. */ - TriangleLightFacingList triangleLightFacings; - /** All edge groups of this edge list. */ - EdgeGroupList edgeGroups; - /** Flag indicate the mesh is manifold. */ - bool isClosed; - - - /** Calculate the light facing state of the triangles in this edge list - - This is normally the first stage of calculating a silhouette, i.e. - establishing which tris are facing the light and which are facing - away. This state is stored in the 'triangleLightFacings'. - @param lightPos 4D position of the light in object space, note that - for directional lights (which have no position), the w component - is 0 and the x/y/z position are the direction. - */ - void updateTriangleLightFacing(const Vector4& lightPos); - /** Updates the face normals for this edge list based on (changed) - position information, useful for animated objects. - @param vertexSet The vertex set we are updating - @param positionBuffer The updated position buffer, must contain ONLY xyz - */ - void updateFaceNormals(size_t vertexSet, const HardwareVertexBufferSharedPtr& positionBuffer); - - EdgeData* clone() OGRE_NODISCARD; - - - /// Debugging method - void log(Log* log); - - }; - - /** General utility class for building edge lists for geometry. - - You can add multiple sets of vertex and index data to build and edge list. - Edges will be built between the various sets as well as within sets; this allows - you to use a model which is built from multiple SubMeshes each using - separate index and (optionally) vertex data and still get the same connectivity - information. It's important to note that the indexes for the edge will be constrained - to a single vertex buffer though (this is required in order to render the edge). - */ - class _OgreExport EdgeListBuilder - { - public: - - EdgeListBuilder(); - /** Add a set of vertex geometry data to the edge builder. - - You must add at least one set of vertex data to the builder before invoking the - build method. - */ - void addVertexData(const VertexData* vertexData); - /** Add a set of index geometry data to the edge builder. - - You must add at least one set of index data to the builder before invoking the - build method. - @param indexData The index information which describes the triangles. - @param vertexSet The vertex data set this index data refers to; you only need to alter this - if you have added multiple sets of vertices - @param opType The operation type used to render these indexes. Only triangle types - are supported (no point or line types) - */ - void addIndexData(const IndexData* indexData, size_t vertexSet = 0, - RenderOperation::OperationType opType = RenderOperation::OT_TRIANGLE_LIST); - - /** Builds the edge information based on the information built up so far. - - The caller takes responsibility for deleting the returned structure. - */ - EdgeData* build(void); - - /// Debugging method - void log(Log* l); - private: - - /** A vertex can actually represent several vertices in the final model, because - vertices along texture seams etc will have been duplicated. In order to properly - evaluate the surface properties, a single common vertex is used for these duplicates, - and the faces hold the detail of the duplicated vertices. - */ - struct CommonVertex { - Vector3 position; /// Location of point in euclidean space - size_t index; /// Place of vertex in common vertex list - size_t vertexSet; /// The vertex set this came from - size_t indexSet; /// The index set this was referenced (first) from - size_t originalIndex; /// Place of vertex in original vertex set - }; - /** A set of indexed geometry data */ - struct Geometry { - size_t vertexSet; /// The vertex data set this geometry data refers to - size_t indexSet; /// The index data set this geometry data refers to - const IndexData* indexData; /// The index information which describes the triangles. - RenderOperation::OperationType opType; /// The operation type used to render this geometry - }; - /** Comparator for sorting geometries by vertex set */ - struct geometryLess { - bool operator()(const Geometry& a, const Geometry& b) const - { - if (a.vertexSet < b.vertexSet) return true; - if (a.vertexSet > b.vertexSet) return false; - return a.indexSet < b.indexSet; - } - }; - /** Comparator for unique vertex list */ - struct vectorLess { - bool operator()(const Vector3& a, const Vector3& b) const - { - if (a.x < b.x) return true; - if (a.x > b.x) return false; - if (a.y < b.y) return true; - if (a.y > b.y) return false; - return a.z < b.z; - } - }; - - typedef std::vector VertexDataList; - typedef std::vector GeometryList; - typedef std::vector CommonVertexList; - - GeometryList mGeometryList; - VertexDataList mVertexDataList; - CommonVertexList mVertices; - EdgeData* mEdgeData; - /// Map for identifying common vertices - typedef std::map CommonVertexMap; - CommonVertexMap mCommonVertexMap; - /** Edge map, used to connect edges. Note we allow many triangles on an edge, - after connected an existing edge, we will remove it and never used again. - */ - typedef std::multimap< std::pair, std::pair > EdgeMap; - EdgeMap mEdgeMap; - - void buildTrianglesEdges(const Geometry &geometry); - - /// Finds an existing common vertex, or inserts a new one - size_t findOrCreateCommonVertex(const Vector3& vec, size_t vertexSet, - size_t indexSet, size_t originalIndex); - /// Connect existing edge or create a new edge - utility method during building - void connectOrCreateEdge(size_t vertexSet, size_t triangleIndex, size_t vertIndex0, size_t vertIndex1, - size_t sharedVertIndex0, size_t sharedVertIndex1); - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreEntity.h b/OgreMain/include/OgreEntity.h deleted file mode 100644 index 1205256b3ca..00000000000 --- a/OgreMain/include/OgreEntity.h +++ /dev/null @@ -1,876 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Entity_H__ -#define __Entity_H__ - -#include "OgrePrerequisites.h" -#include "OgreCommon.h" - -#include "OgreMovableObject.h" -#include "OgreQuaternion.h" -#include "OgreVector.h" -#include "OgreHardwareBufferManager.h" -#include "OgreRenderable.h" -#include "OgreResourceGroupManager.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** Defines an instance of a discrete, movable object based on a Mesh. - - %Ogre generally divides renderable objects into 2 groups, discrete - (separate) and relatively small objects which move around the world, - and large, sprawling geometry which makes up generally immovable - scenery, aka 'level geometry'. - - The Mesh and SubMesh classes deal with the definition of the geometry - used by discrete movable objects. Entities are actual instances of - objects based on this geometry in the world. Therefore there is - usually a single set Mesh for a car, but there may be multiple - entities based on it in the world. Entities are able to override - aspects of the Mesh it is defined by, such as changing material - properties per instance (so you can have many cars using the same - geometry but different textures for example). Because a Mesh is split - into SubMeshes for this purpose, the Entity class is a grouping class - (much like the Mesh class) and much of the detail regarding - individual changes is kept in the SubEntity class. There is a 1:1 - relationship between SubEntity instances and the SubMesh instances - associated with the Mesh the Entity is based on. - - Entity and SubEntity classes are never created directly. Use the - createEntity method of the SceneManager (passing a model name) to - create one. - - Entities are included in the scene by associating them with a - SceneNode, using the @ref SceneNode::attachObject method. - @note - No functions were declared virtual to improve performance. - */ - class _OgreExport Entity: public MovableObject, public Resource::Listener - { - // Allow EntityFactory full access - friend class EntityFactory; - friend class SubEntity; - public: - - typedef std::set EntitySet; - typedef std::vector> SchemeHardwareAnimMap; - typedef std::vector SubEntityList; - private: - - /** Private constructor (instances cannot be created directly). - */ - Entity(); - /** Private constructor - specify name (the usual constructor used). - */ - Entity( const String& name, const MeshPtr& mesh); - - /** The Mesh that this Entity is based on. - */ - MeshPtr mMesh; - - /** List of SubEntities (point to SubMeshes). - */ - SubEntityList mSubEntityList; - - - /// State of animation for animable meshes - AnimationStateSet* mAnimationState; - - /** Structure for recording the use of temporary blend buffers. */ - class TempBlendedBufferInfo : public HardwareBufferLicensee - { - private: - // Pre-blended - HardwareVertexBufferPtr srcPositionBuffer; - HardwareVertexBufferPtr srcNormalBuffer; - // Post-blended - HardwareVertexBufferPtr destPositionBuffer; - HardwareVertexBufferPtr destNormalBuffer; - unsigned short posBindIndex; - unsigned short normBindIndex; - /// Both positions and normals are contained in the same buffer. - bool posNormalShareBuffer; - bool posNormalExtraData; - bool bindPositions; - bool bindNormals; - - public: - ~TempBlendedBufferInfo(void); - /// Utility method, extract info from the given VertexData. - void extractFrom(const VertexData* sourceData); - /// Utility method, checks out temporary copies of src into dest. - void checkoutTempCopies(bool positions = true, bool normals = true); - /// Utility method, binds dest copies into a given VertexData struct. - void bindTempCopies(VertexData* targetData, bool suppressHardwareUpload); - /** Overridden member from HardwareBufferLicensee. */ - void licenseExpired(HardwareBuffer* buffer) override; - /** Detect currently have buffer copies checked out and touch it. */ - bool buffersCheckedOut(bool positions = true, bool normals = true) const; - }; - - - /// Temp buffer details for software skeletal anim of shared geometry - TempBlendedBufferInfo mTempSkelAnimInfo; - /// Vertex data details for software skeletal anim of shared geometry - std::unique_ptr mSkelAnimVertexData; - /// Temp buffer details for software vertex anim of shared geometry - TempBlendedBufferInfo mTempVertexAnimInfo; - /// Vertex data details for software vertex anim of shared geometry - std::unique_ptr mSoftwareVertexAnimVertexData; - /// Vertex data details for hardware vertex anim of shared geometry - /// - separate since we need to s/w anim for shadows whilst still altering - /// the vertex data for hardware morphing (pos2 binding) - std::unique_ptr mHardwareVertexAnimVertexData; - - /// Have we applied any vertex animation to shared geometry? - bool mVertexAnimationAppliedThisFrame : 1; - /// Have the temp buffers already had their geometry prepared for use in rendering shadow volumes? - bool mPreparedForShadowVolumes : 1; - /// Flag determines whether or not to display skeleton. - bool mDisplaySkeleton : 1; - /// Current state of the hardware animation as represented by the entities parameters. - bool mCurrentHWAnimationState : 1; - /// Flag indicating whether to skip automatic updating of the Skeleton's AnimationState. - bool mSkipAnimStateUpdates : 1; - /// Flag indicating whether to update the main entity skeleton even when an LOD is displayed. - bool mAlwaysUpdateMainSkeleton : 1; - /// Flag indicating whether to update the bounding box from the bones of the skeleton. - bool mUpdateBoundingBoxFromSkeleton : 1; - /// Flag indicating whether we have a vertex program in use on any of our subentities. - bool mVertexProgramInUse : 1; - /// Has this entity been initialised yet? - bool mInitialised : 1; - - /** Internal method - given vertex data which could be from the Mesh or - any submesh, finds the temporary blend copy. - */ - const VertexData* findBlendedVertexData(const VertexData* orig); - /** Internal method - given vertex data which could be from the Mesh or - any SubMesh, finds the corresponding SubEntity. - */ - SubEntity* findSubEntityForVertexData(const VertexData* orig); - - /** Internal method for preparing this Entity for use in animation. */ - void prepareTempBlendBuffers(void); - /** Mark all vertex data as so far unanimated. - */ - void markBuffersUnusedForAnimation(void); - /** Internal method to restore original vertex data where we didn't - perform any vertex animation this frame. - */ - void restoreBuffersForUnusedAnimation(bool hardwareAnimation); - - /** Ensure that any unbound pose animation buffers are bound to a safe - default. - @param srcData - Original vertex data containing original positions. - @param destData - Hardware animation vertex data to be checked. - */ - void bindMissingHardwarePoseBuffers(const VertexData* srcData, - VertexData* destData); - - /** When performing software pose animation, initialise software copy - of vertex data. - */ - void initialisePoseVertexData(const VertexData* srcData, VertexData* destData, - bool animateNormals); - - /** When animating normals for pose animation, finalise normals by filling in - with the reference mesh normal where applied normal weights < 1. - */ - void finalisePoseNormals(const VertexData* srcData, VertexData* destData); - - /// Number of hardware poses supported by materials. - ushort mHardwarePoseCount; - ushort mNumBoneMatrices; - /// Cached bone matrices, including any world transform. - Affine3 *mBoneWorldMatrices; - /// Cached bone matrices in skeleton local space, might shares with other entity instances. - Affine3 *mBoneMatrices; - /// Records the last frame in which animation was updated. - unsigned long mFrameAnimationLastUpdated; - - /// Perform all the updates required for an animated entity. - void updateAnimation(void); - - /// Records the last frame in which the bones was updated. - /// It's a pointer because it can be shared between different entities with - /// a shared skeleton. - unsigned long *mFrameBonesLastUpdated; - - /** A set of all the entities which shares a single SkeletonInstance. - This is only created if the entity is in fact sharing it's SkeletonInstance with - other Entities. - */ - EntitySet* mSharedSkeletonEntities; - - /** Private method to cache bone matrices from skeleton. - @return - True if the bone matrices cache has been updated. False if note. - */ - bool cacheBoneMatrices(void); - - /** Flag indicating whether hardware animation is supported by this entities materials - data is saved per scehme number. - */ - SchemeHardwareAnimMap mSchemeHardwareAnim; - - /// Counter indicating number of requests for software animation. - int mSoftwareAnimationRequests; - /// Counter indicating number of requests for software blended normals. - int mSoftwareAnimationNormalsRequests; - - -#if !OGRE_NO_MESHLOD - /// The LOD number of the mesh to use, calculated by _notifyCurrentCamera. - ushort mMeshLodIndex; - - /// LOD bias factor, transformed for optimisation when calculating adjusted LOD value. - Real mMeshLodFactorTransformed; - /// Index of minimum detail LOD (NB higher index is lower detail). - ushort mMinMeshLodIndex; - /// Index of maximum detail LOD (NB lower index is higher detail). - ushort mMaxMeshLodIndex; - - /** List of LOD Entity instances (for manual LODs). - We don't know when the mesh is using manual LODs whether one LOD to the next will have the - same number of SubMeshes, therefore we have to allow a separate Entity list - with each alternate one. - */ - typedef std::vector LODEntityList; - LODEntityList mLodEntityList; -#else - const ushort mMeshLodIndex; - const Real mMeshLodFactorTransformed; - const ushort mMinMeshLodIndex; - const ushort mMaxMeshLodIndex; -#endif - /// LOD bias factor, not transformed. - Real mMaterialLodFactor; - /// Index of minimum detail LOD (NB higher index is lower detail). - ushort mMinMaterialLodIndex; - /// Index of maximum detail LOD (NB lower index is higher detail). - ushort mMaxMaterialLodIndex; - /** This Entity's personal copy of the skeleton, if skeletally animated. - */ - SkeletonInstance* mSkeletonInstance; - - /// Last parent transform. - Affine3 mLastParentXform; - - /// Mesh state count, used to detect differences. - size_t mMeshStateCount; - - /** Builds a list of SubEntities based on the SubMeshes contained in the Mesh. */ - void buildSubEntityList(MeshPtr& mesh, SubEntityList* sublist); - - /// Internal implementation of attaching a 'child' object to this entity and assign the parent node to the child entity. - void attachObjectImpl(MovableObject *pMovable, TagPoint *pAttachingPoint); - - /// Internal implementation of detaching a 'child' object of this entity and clear the parent node of the child entity. - void detachObjectImpl(MovableObject* pObject); - - /// Internal implementation of detaching all 'child' objects of this entity. - void detachAllObjectsImpl(void); - - /// Ensures reevaluation of the vertex processing usage. - void reevaluateVertexProcessing(void); - - /** Calculates the kind of vertex processing in use. - - This function's return value is calculated according to the current - active scheme. This is due to the fact that RTSS schemes may be different - in their handling of hardware animation. - */ - bool calcVertexProcessing(void); - - /// Apply vertex animation. - void applyVertexAnimation(bool hardwareAnimation, bool stencilShadows); - /// Initialise the hardware animation elements for given vertex data. - ushort initHardwareAnimationElements(VertexData* vdata, ushort numberOfElements, bool animateNormals); - /// Are software vertex animation temp buffers bound? - bool tempVertexAnimBuffersBound(void) const; - /// Are software skeleton animation temp buffers bound? - bool tempSkelAnimBuffersBound(bool requestNormals) const; - - public: - /// Contains the child objects (attached to bones) indexed by name. - typedef std::vector ChildObjectList; - private: - ChildObjectList mChildObjectList; - - - /// Bounding box that 'contains' all the mesh of each child entity. - mutable AxisAlignedBox mFullBoundingBox; // note: this exists only so that getBoundingBox() can return an AAB by reference - - ShadowRenderableList mShadowRenderables; - - /** Nested class to allow entity shadows. */ - class EntityShadowRenderable : public ShadowRenderable - { - /// Link to current vertex data used to bind (maybe changes). - const VertexData* mCurrentVertexData; - /// Link to SubEntity, only present if SubEntity has it's own geometry. - SubEntity* mSubEntity; - /// Original position buffer source binding. - ushort mOriginalPosBufferBinding; - - public: - EntityShadowRenderable(MovableObject* parent, - const HardwareIndexBufferSharedPtr& indexBuffer, const VertexData* vertexData, - bool createSeparateLightCap, SubEntity* subent, bool isLightCap = false); - - /// Create the separate light cap if it doesn't already exists. - void _createSeparateLightCap(); - /// Rebind the source positions (for temp buffer users). - void rebindPositionBuffer(const VertexData* vertexData, bool force); - bool isVisible(void) const override; - }; - public: - /** Default destructor. - */ - ~Entity(); - - /** Gets the Mesh that this Entity is based on. - */ - const MeshPtr& getMesh(void) const; - - /** Gets a pointer to a SubEntity, ie a part of an Entity. - */ - SubEntity* getSubEntity(size_t index) const { return mSubEntityList.at(index); } - - /** Gets a pointer to a SubEntity by name - - Names should be initialized during a Mesh creation. - */ - SubEntity* getSubEntity( const String& name ) const; - - /** Retrieves the number of SubEntity objects making up this entity. - */ - size_t getNumSubEntities(void) const { return mSubEntityList.size(); } - - /** Retrieves SubEntity objects making up this entity. - */ - const SubEntityList& getSubEntities() const { - return mSubEntityList; - } - - /** Clones this entity and returns a pointer to the clone. - - Useful method for duplicating an entity. The new entity must be - given a unique name, and is not attached to the scene in any way - so must be attached to a SceneNode to be visible (exactly as - entities returned from SceneManager::createEntity). - @param newName - Name for the new entity. - */ - Entity* clone( const String& newName ) const; - - /** Sets the material to use for the whole of this entity. - - This is a shortcut method to set all the materials for all - subentities of this entity. Only use this method is you want to - set the same material for all subentities or if you know there - is only one. Otherwise call getSubEntity() and call the same - method on the individual SubEntity. - */ - void setMaterialName( const String& name, const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME ); - - - /** Sets the material to use for the whole of this entity. - - This is a shortcut method to set all the materials for all - subentities of this entity. Only use this method is you want to - set the same material for all subentities or if you know there - is only one. Otherwise call getSubEntity() and call the same - method on the individual SubEntity. - */ - void setMaterial(const MaterialPtr& material); - - void _releaseManualHardwareResources() override; - void _restoreManualHardwareResources() override; - - void _notifyCurrentCamera(Camera* cam) override; - - void setRenderQueueGroup(uint8 queueID) override; - - void setRenderQueueGroupAndPriority(uint8 queueID, ushort priority) override; - - const AxisAlignedBox& getBoundingBox(void) const override; - - /// Merge all the child object Bounds a return it. - AxisAlignedBox getChildObjectsBoundingBox(void) const; - - void _updateRenderQueue(RenderQueue* queue) override; - const String& getMovableType(void) const override; - - /** For entities based on animated meshes, gets the AnimationState object for a single animation. - - You animate an entity by updating the animation state objects. Each of these represents the - current state of each animation available to the entity. The AnimationState objects are - initialised from the Mesh object. - */ - AnimationState* getAnimationState(const String& name) const; - /** Returns whether the AnimationState with the given name exists. */ - bool hasAnimationState(const String& name) const; - /** For entities based on animated meshes, gets the AnimationState objects for all animations. - @return - In case the entity is animated, this functions returns the pointer to a AnimationStateSet - containing all animations of the entries. If the entity is not animated, it returns 0. - - You animate an entity by updating the animation state objects. Each of these represents the - current state of each animation available to the entity. The AnimationState objects are - initialised from the Mesh object. - */ - AnimationStateSet* getAllAnimationStates(void) const; - - /** Tells the Entity whether or not it should display it's skeleton, if it has one. - */ - void setDisplaySkeleton(bool display); - - /** Returns whether or not the entity is currently displaying its skeleton. - */ - bool getDisplaySkeleton(void) const; - - /** Returns the number of manual levels of detail that this entity supports. - - This number never includes the original entity, it is difference - with Mesh::getNumLodLevels. - */ - size_t getNumManualLodLevels(void) const; - - /** Returns the current LOD used to render - */ - ushort getCurrentLodIndex() { return mMeshLodIndex; } - - /** Gets a pointer to the entity representing the numbered manual level of detail. - - The zero-based index never includes the original entity, unlike - Mesh::getLodLevel. - */ - Entity* getManualLodLevel(size_t index) const; - -#if !OGRE_NO_MESHLOD - /** Sets a level-of-detail bias for the mesh detail of this entity. - - Level of detail reduction is normally applied automatically based on the Mesh - settings. However, it is possible to influence this behaviour for this entity - by adjusting the LOD bias. This 'nudges' the mesh level of detail used for this - entity up or down depending on your requirements. You might want to use this - if there was a particularly important entity in your scene which you wanted to - detail better than the others, such as a player model. - @par - There are three parameters to this method; the first is a factor to apply; it - defaults to 1.0 (no change), by increasing this to say 2.0, this model would - take twice as long to reduce in detail, whilst at 0.5 this entity would use lower - detail versions twice as quickly. The other 2 parameters are hard limits which - let you set the maximum and minimum level-of-detail version to use, after all - other calculations have been made. This lets you say that this entity should - never be simplified, or that it can only use LODs below a certain level even - when right next to the camera. - @param factor - Proportional factor to apply to the distance at which LOD is changed. - Higher values increase the distance at which higher LODs are displayed (2.0 is - twice the normal distance, 0.5 is half). - @param maxDetailIndex - The index of the maximum LOD this entity is allowed to use (lower - indexes are higher detail: index 0 is the original full detail model). - @param minDetailIndex - The index of the minimum LOD this entity is allowed to use (higher - indexes are lower detail). Use something like 99 if you want unlimited LODs (the actual - LOD will be limited by the number in the Mesh). - */ - void setMeshLodBias(Real factor, ushort maxDetailIndex = 0, ushort minDetailIndex = 99); -#endif - /** Sets a level-of-detail bias for the material detail of this entity. - - Level of detail reduction is normally applied automatically based on the Material - settings. However, it is possible to influence this behaviour for this entity - by adjusting the LOD bias. This 'nudges' the material level of detail used for this - entity up or down depending on your requirements. You might want to use this - if there was a particularly important entity in your scene which you wanted to - detail better than the others, such as a player model. - @par - There are three parameters to this method; the first is a factor to apply; it - defaults to 1.0 (no change), by increasing this to say 2.0, this entity would - take twice as long to use a lower detail material, whilst at 0.5 this entity - would use lower detail versions twice as quickly. The other 2 parameters are - hard limits which let you set the maximum and minimum level-of-detail index - to use, after all other calculations have been made. This lets you say that - this entity should never be simplified, or that it can only use LODs below - a certain level even when right next to the camera. - @param factor - Proportional factor to apply to the distance at which LOD is changed. - Higher values increase the distance at which higher LODs are displayed (2.0 is - twice the normal distance, 0.5 is half). - @param maxDetailIndex - The index of the maximum LOD this entity is allowed to use (lower - indexes are higher detail: index 0 is the original full detail model). - @param minDetailIndex - The index of the minimum LOD this entity is allowed to use (higher - indexes are lower detail. Use something like 99 if you want unlimited LODs (the actual - LOD will be limited by the number of LOD indexes used in the Material). - */ - void setMaterialLodBias(Real factor, ushort maxDetailIndex = 0, ushort minDetailIndex = 99); - - /** Sets whether the polygon mode of this entire entity may be - overridden by the camera detail settings. - */ - void setPolygonModeOverrideable(bool PolygonModeOverrideable); - /** Attaches another object to a certain bone of the skeleton which this entity uses. - - This method can be used to attach another object to an animated part of this entity, - by attaching it to a bone in the skeleton (with an offset if required). As this entity - is animated, the attached object will move relative to the bone to which it is attached. - @par - An exception is thrown if the movable object is already attached to the bone, another bone or scenenode. - If the entity has no skeleton or the bone name cannot be found then an exception is thrown. - @param boneName - The name of the bone (in the skeleton) to attach this object - @param pMovable - Pointer to the object to attach - @param offsetOrientation - An adjustment to the orientation of the attached object, relative to the bone. - @param offsetPosition - An adjustment to the position of the attached object, relative to the bone. - @return - The TagPoint to which the object has been attached - */ - TagPoint* attachObjectToBone(const String &boneName, - MovableObject *pMovable, - const Quaternion &offsetOrientation = Quaternion::IDENTITY, - const Vector3 &offsetPosition = Vector3::ZERO); - - /** Detach a MovableObject previously attached using attachObjectToBone. - If the movable object name is not found then an exception is raised. - @param movableName - The name of the movable object to be detached. - */ - MovableObject* detachObjectFromBone(const String &movableName); - - /** Detaches an object by pointer. - - Use this method to destroy a MovableObject which is attached to a bone of belonging this entity. - But sometimes the object may be not in the child object list because it is a LOD entity, - this method can safely detect and ignore in this case and won't raise an exception. - */ - void detachObjectFromBone(MovableObject* obj); - - /// Detach all MovableObjects previously attached using attachObjectToBone - void detachAllObjectsFromBone(void); - - typedef VectorIterator ChildObjectListIterator; - /// @deprecated use getAttachedObjects() - OGRE_DEPRECATED ChildObjectListIterator getAttachedObjectIterator(void); - /** Gets an iterator to the list of objects attached to bones on this entity. */ - const ChildObjectList& getAttachedObjects() const { return mChildObjectList; } - - Real getBoundingRadius(void) const override; - const AxisAlignedBox& getWorldBoundingBox(bool derive = false) const override; - const Sphere& getWorldBoundingSphere(bool derive = false) const override; - - EdgeData* getEdgeList(void) override; - const ShadowRenderableList& getShadowVolumeRenderableList( - const Light* light, const HardwareIndexBufferPtr& indexBuffer, - size_t& indexBufferUsedSize, float extrusionDistance, int flags = 0) override; - - /** Internal method for retrieving bone matrix information. */ - const Affine3* _getBoneMatrices(void) const { return mBoneMatrices;} - /** Internal method for retrieving bone matrix information. */ - unsigned short _getNumBoneMatrices(void) const { return mNumBoneMatrices; } - /** Returns whether or not this entity is skeletally animated. */ - bool hasSkeleton(void) const { return mSkeletonInstance != 0; } - /** Get this Entity's personal skeleton instance. */ - SkeletonInstance* getSkeleton(void) const { return mSkeletonInstance; } - /** Returns whether or not hardware animation is enabled. - - Because fixed-function indexed vertex blending is rarely supported - by existing graphics cards, hardware animation can only be done if - the vertex programs in the materials used to render an entity support - it. Therefore, this method will only return true if all the materials - assigned to this entity have vertex programs assigned, and all those - vertex programs must support 'includes_morph_animation true' if using - morph animation, 'includes_pose_animation true' if using pose animation - and 'includes_skeletal_animation true' if using skeletal animation. - - Also note the the function returns value according to the current active - scheme. This is due to the fact that RTSS schemes may be different in their - handling of hardware animation. - */ - bool isHardwareAnimationEnabled(void); - - void _notifyAttached(Node* parent, bool isTagPoint = false) override; - /** Returns the number of requests that have been made for software animation - - If non-zero then software animation will be performed in updateAnimation - regardless of the current setting of isHardwareAnimationEnabled or any - internal optimise for eliminate software animation. Requests for software - animation are made by calling the addSoftwareAnimationRequest() method. - */ - int getSoftwareAnimationRequests(void) const { return mSoftwareAnimationRequests; } - /** Returns the number of requests that have been made for software animation of normals - - If non-zero, and getSoftwareAnimationRequests() also returns non-zero, - then software animation of normals will be performed in updateAnimation - regardless of the current setting of isHardwareAnimationEnabled or any - internal optimise for eliminate software animation. Currently it is not - possible to force software animation of only normals. Consequently this - value is always less than or equal to that returned by getSoftwareAnimationRequests(). - Requests for software animation of normals are made by calling the - addSoftwareAnimationRequest() method with 'true' as the parameter. - */ - int getSoftwareAnimationNormalsRequests(void) const { return mSoftwareAnimationNormalsRequests; } - /** Add a request for software animation - - Tells the entity to perform animation calculations for skeletal/vertex - animations in software, regardless of the current setting of - isHardwareAnimationEnabled(). Software animation will be performed - any time one or more requests have been made. If 'normalsAlso' is - 'true', then the entity will also do software blending on normal - vectors, in addition to positions. This advanced method useful for - situations in which access to actual mesh vertices is required, - such as accurate collision detection or certain advanced shading - techniques. When software animation is no longer needed, - the caller of this method should always remove the request by calling - removeSoftwareAnimationRequest(), passing the same value for - 'normalsAlso'. - */ - void addSoftwareAnimationRequest(bool normalsAlso); - /** Removes a request for software animation - - Calling this decrements the entity's internal counter of the number - of requests for software animation. If the counter is already zero - then calling this method throws an exception. The 'normalsAlso' - flag if set to 'true' will also decrement the internal counter of - number of requests for software animation of normals. - */ - void removeSoftwareAnimationRequest(bool normalsAlso); - - /** Shares the SkeletonInstance with the supplied entity. - Note that in order for this to work, both entities must have the same - Skeleton. - */ - void shareSkeletonInstanceWith(Entity* entity); - - /** Returns whether or not this entity is either morph or pose animated. - */ - bool hasVertexAnimation(void) const; - - - /** Stops sharing the SkeletonInstance with other entities. - */ - void stopSharingSkeletonInstance(); - - - /** Returns whether this entity shares it's SkeltonInstance with other entity instances. - */ - inline bool sharesSkeletonInstance() const { return mSharedSkeletonEntities != NULL; } - - /** Returns a pointer to the set of entities which share a SkeletonInstance. - If this instance does not share it's SkeletonInstance with other instances @c NULL will be returned - */ - inline const EntitySet* getSkeletonInstanceSharingSet() const { return mSharedSkeletonEntities; } - - /** Updates the internal animation state set to include the latest - available animations from the attached skeleton. - - Use this method if you manually add animations to a skeleton, or have - linked the skeleton to another for animation purposes since creating - this entity. - @note - If you have called getAnimationState prior to calling this method, - the pointers will still remain valid. - */ - void refreshAvailableAnimationState(void); - - /** Advanced method to perform all the updates required for an animated entity. - - You don't normally need to call this, but it's here in case you wish - to manually update the animation of an Entity at a specific point in - time. Animation will not be updated more than once a frame no matter - how many times you call this method. - */ - void _updateAnimation(void); - - /** Tests if any animation applied to this entity. - - An entity is animated if any animation state is enabled, or any manual bone - applied to the skeleton. - */ - bool _isAnimated(void) const; - - /** Tests if skeleton was animated. - */ - bool _isSkeletonAnimated(void) const; - - /** Advanced method to get the temporarily blended skeletal vertex information - for entities which are software skinned. - - Internal engine will eliminate software animation if possible, this - information is unreliable unless added request for software animation - via addSoftwareAnimationRequest. - @note - The positions/normals of the returned vertex data is in object space. - */ - VertexData* _getSkelAnimVertexData(void) const; - /** Advanced method to get the temporarily blended software vertex animation information - - Internal engine will eliminate software animation if possible, this - information is unreliable unless added request for software animation - via addSoftwareAnimationRequest. - @note - The positions/normals of the returned vertex data is in object space. - */ - VertexData* _getSoftwareVertexAnimVertexData(void) const; - /** Advanced method to get the hardware morph vertex information - @note - The positions/normals of the returned vertex data is in object space. - */ - VertexData* _getHardwareVertexAnimVertexData(void) const; - /// Override to return specific type flag. - uint32 getTypeFlags(void) const override; - /// Retrieve the VertexData which should be used for GPU binding. - VertexData* getVertexDataForBinding(void); - - /// Identify which vertex data we should be sending to the renderer. - enum VertexDataBindChoice - { - BIND_ORIGINAL, - BIND_SOFTWARE_SKELETAL, - BIND_SOFTWARE_MORPH, - BIND_HARDWARE_MORPH - }; - /// Choose which vertex data to bind to the renderer. - VertexDataBindChoice chooseVertexDataForBinding(bool hasVertexAnim); - - /** Are buffers already marked as vertex animated? */ - bool _getBuffersMarkedForAnimation(void) const { return mVertexAnimationAppliedThisFrame; } - /** Mark just this vertex data as animated. - */ - void _markBuffersUsedForAnimation(void); - - /** Has this Entity been initialised yet? - - If this returns false, it means this Entity hasn't been completely - constructed yet from the underlying resources (Mesh, Skeleton), which - probably means they were delay-loaded and aren't available yet. This - Entity won't render until it has been successfully initialised, nor - will many of the manipulation methods function. - */ - bool isInitialised(void) const { return mInitialised; } - - /** Try to initialise the Entity from the underlying resources. - - This method builds the internal structures of the Entity based on it - resources (Mesh, Skeleton). This may or may not succeed if the - resources it references have been earmarked for background loading, - so you should check isInitialised afterwards to see if it was successful. - @param forceReinitialise - If @c true, this forces the Entity to tear down it's - internal structures and try to rebuild them. Useful if you changed the - content of a Mesh or Skeleton at runtime. - */ - void _initialise(bool forceReinitialise = false); - /** Tear down the internal structures of this Entity, rendering it uninitialised. */ - void _deinitialise(void); - - /** Resource::Listener hook to notify Entity that a delay-loaded Mesh is - complete. - */ - void loadingComplete(Resource* res) override; - - void visitRenderables(Renderable::Visitor* visitor, bool debugRenderables = false) override; - - /** Get the LOD strategy transformation of the mesh LOD factor. */ - Real _getMeshLodFactorTransformed() const; - - /** Entity's skeleton's AnimationState will not be automatically updated when set to true. - Useful if you wish to handle AnimationState updates manually. - */ - void setSkipAnimationStateUpdate(bool skip) { - mSkipAnimStateUpdates = skip; - } - - /** Entity's skeleton's AnimationState will not be automatically updated when set to true. - Useful if you wish to handle AnimationState updates manually. - */ - bool getSkipAnimationStateUpdate() const { - return mSkipAnimStateUpdates; - } - - /** The skeleton of the main entity will be updated even if the an LOD entity is being displayed. - useful if you have entities attached to the main entity. Otherwise position of attached - entities will not be updated. - */ - void setAlwaysUpdateMainSkeleton(bool update) { - mAlwaysUpdateMainSkeleton = update; - } - - /** The skeleton of the main entity will be updated even if the an LOD entity is being displayed. - useful if you have entities attached to the main entity. Otherwise position of attached - entities will not be updated. - */ - bool getAlwaysUpdateMainSkeleton() const { - return mAlwaysUpdateMainSkeleton; - } - - /** If true, the skeleton of the entity will be used to update the bounding box for culling. - Useful if you have skeletal animations that move the bones away from the root. Otherwise, the - bounding box of the mesh in the binding pose will be used. - - When true, the bounding box will be generated to only enclose the bones that are used for skinning. - Also the resulting bounding box will be expanded by the amount of GetMesh()->getBoneBoundingRadius(). - The expansion amount can be changed on the mesh to achieve a better fitting bounding box. - */ - void setUpdateBoundingBoxFromSkeleton(bool update); - - /** If true, the skeleton of the entity will be used to update the bounding box for culling. - Useful if you have skeletal animations that move the bones away from the root. Otherwise, the - bounding box of the mesh in the binding pose will be used. - */ - bool getUpdateBoundingBoxFromSkeleton() const { - return mUpdateBoundingBoxFromSkeleton; - } - - - }; - /** @} */ - /** @} */ - -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif // __Entity_H__ \ No newline at end of file diff --git a/OgreMain/include/OgreException.h b/OgreMain/include/OgreException.h deleted file mode 100644 index 5e06c194525..00000000000 --- a/OgreMain/include/OgreException.h +++ /dev/null @@ -1,300 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Exception_H_ -#define __Exception_H_ - -// Precompiler options -#include "OgrePrerequisites.h" -#include "OgreString.h" -#include -#include "OgreHeaderPrefix.h" - -// Check for OGRE assert mode - -// RELEASE_EXCEPTIONS mode -#if OGRE_ASSERT_MODE == 1 -# if OGRE_DEBUG_MODE -# define OgreAssert( a, b ) assert( (a) && (b) ) -# else -# define OgreAssert( a, b ) if( !(a) ) OGRE_EXCEPT_2( Ogre::Exception::ERR_RT_ASSERTION_FAILED, (#a " failed. " b) ) -# endif - -// EXCEPTIONS mode -#elif OGRE_ASSERT_MODE == 2 -# define OgreAssert( a, b ) if( !(a) ) OGRE_EXCEPT_2( Ogre::Exception::ERR_RT_ASSERTION_FAILED, (#a " failed. " b) ) -// STANDARD mode -#else -/** Checks a condition at runtime and throws exception/ aborts if it fails. - * - * The macros OgreAssert (and OgreAssertDbg) evaluate the specified expression. - * If it is 0, OgreAssert raises an error (see Ogre::RuntimeAssertionException) in Release configuration - * and aborts in Debug configuration. - * The macro OgreAssert checks the condition in both Debug and Release configurations - * while OgreAssertDbg is only retained in the Debug configuration. - * - * To always abort instead of throwing an exception or disabling OgreAssert in Release configuration altogether, - * set OGRE_ASSERT_MODE in CMake accordingly. - */ -# define OgreAssert( expr, mesg ) assert( (expr) && (mesg) ) -#endif - -#if OGRE_DEBUG_MODE -# define OgreAssertDbg( a, b ) OgreAssert( a, b ) -#else -/// replaced with OgreAssert(expr, mesg) in Debug configuration -# define OgreAssertDbg( expr, mesg ) -#endif - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - /** When thrown, provides information about an error that has occurred inside the engine. - - OGRE never uses return values to indicate errors. Instead, if an - error occurs, an exception is thrown, and this is the object that - encapsulates the detail of the problem. The application using - OGRE should always ensure that the exceptions are caught, so all - OGRE engine functions should occur within a - try{} catch(Ogre::Exception& e) {} block. - @par - The user application should never create any instances of this - object unless it wishes to unify its error handling using the - same object. - */ - class _OgreExport Exception : public std::exception - { - protected: - long line; - const char* typeName; - String description; - String source; - const char* file; - String fullDesc; // storage for char* returned by what() - public: - /** Static definitions of error codes. - @todo - Add many more exception codes, since we want the user to be able - to catch most of them. - */ - enum ExceptionCodes { - ERR_CANNOT_WRITE_TO_FILE, - ERR_INVALID_STATE, - ERR_INVALIDPARAMS, - ERR_RENDERINGAPI_ERROR, - ERR_DUPLICATE_ITEM, - ERR_ITEM_NOT_FOUND = ERR_DUPLICATE_ITEM, - ERR_FILE_NOT_FOUND, - ERR_INTERNAL_ERROR, - ERR_RT_ASSERTION_FAILED, - ERR_NOT_IMPLEMENTED, - ERR_INVALID_CALL - }; - - /** Default constructor. - */ - Exception( int number, const String& description, const String& source ); - - /** Advanced constructor. - */ - Exception( int number, const String& description, const String& source, const char* type, const char* file, long line ); - - /** Copy constructor. - */ - Exception(const Exception& rhs); - - /// Needed for compatibility with std::exception - ~Exception() throw() {} - - /** Returns a string with the full description of this error. - - The description contains the error number, the description - supplied by the thrower, what routine threw the exception, - and will also supply extra platform-specific information - where applicable. For example - in the case of a rendering - library error, the description of the error will include both - the place in which OGRE found the problem, and a text - description from the 3D rendering library, if available. - */ - const String& getFullDescription(void) const { return fullDesc; } - - /** Gets the source function. - */ - const String &getSource() const { return source; } - - /** Gets source file name. - */ - const char* getFile() const { return file; } - - /** Gets line number. - */ - long getLine() const { return line; } - - /** Returns a string with only the 'description' field of this exception. Use - getFullDescriptionto get a full description of the error including line number, - error number and what function threw the exception. - */ - const String &getDescription(void) const { return description; } - - const char* what() const throw() override { return fullDesc.c_str(); } - - }; - - - /** Template struct which creates a distinct type for each exception code. - @note - This is useful because it allows us to create an overloaded method - for returning different exception types by value without ambiguity. - From 'Modern C++ Design' (Alexandrescu 2001). - */ - class _OgreExport UnimplementedException : public Exception - { - public: - UnimplementedException(int inNumber, const String& inDescription, const String& inSource, const char* inFile, long inLine) - : Exception(inNumber, inDescription, inSource, __FUNCTION__, inFile, inLine) {} - }; - class _OgreExport FileNotFoundException : public Exception - { - public: - FileNotFoundException(int inNumber, const String& inDescription, const String& inSource, const char* inFile, long inLine) - : Exception(inNumber, inDescription, inSource, __FUNCTION__, inFile, inLine) {} - }; - class _OgreExport IOException : public Exception - { - public: - IOException(int inNumber, const String& inDescription, const String& inSource, const char* inFile, long inLine) - : Exception(inNumber, inDescription, inSource, __FUNCTION__, inFile, inLine) {} - }; - class _OgreExport InvalidStateException : public Exception - { - public: - InvalidStateException(int inNumber, const String& inDescription, const String& inSource, const char* inFile, long inLine) - : Exception(inNumber, inDescription, inSource, __FUNCTION__, inFile, inLine) {} - }; - class _OgreExport InvalidParametersException : public Exception - { - public: - InvalidParametersException(int inNumber, const String& inDescription, const String& inSource, const char* inFile, long inLine) - : Exception(inNumber, inDescription, inSource, __FUNCTION__, inFile, inLine) {} - }; - class _OgreExport ItemIdentityException : public Exception - { - public: - ItemIdentityException(int inNumber, const String& inDescription, const String& inSource, const char* inFile, long inLine) - : Exception(inNumber, inDescription, inSource, __FUNCTION__, inFile, inLine) {} - }; - class _OgreExport InternalErrorException : public Exception - { - public: - InternalErrorException(int inNumber, const String& inDescription, const String& inSource, const char* inFile, long inLine) - : Exception(inNumber, inDescription, inSource, __FUNCTION__, inFile, inLine) {} - }; - class _OgreExport RenderingAPIException : public Exception - { - public: - RenderingAPIException(int inNumber, const String& inDescription, const String& inSource, const char* inFile, long inLine) - : Exception(inNumber, inDescription, inSource, __FUNCTION__, inFile, inLine) {} - }; - class _OgreExport RuntimeAssertionException : public Exception - { - public: - RuntimeAssertionException(int inNumber, const String& inDescription, const String& inSource, const char* inFile, long inLine) - : Exception(inNumber, inDescription, inSource, __FUNCTION__, inFile, inLine) {} - }; - class _OgreExport InvalidCallException : public Exception - { - public: - InvalidCallException(int inNumber, const String& inDescription, const String& inSource, const char* inFile, long inLine) - : Exception(inNumber, inDescription, inSource, __FUNCTION__, inFile, inLine) {} - }; - - /** Class implementing dispatch methods in order to construct by-value - exceptions of a derived type based just on an exception code. - - This nicely handles construction of derived Exceptions by value (needed - for throwing) without suffering from ambiguity - each code is turned into - a distinct type so that methods can be overloaded. This allows OGRE_EXCEPT - to stay small in implementation (desirable since it is embedded) whilst - still performing rich code-to-type mapping. - */ - class ExceptionFactory - { - private: - /// Private constructor, no construction - ExceptionFactory() {} - static OGRE_NORETURN void _throwException( - Exception::ExceptionCodes code, int number, - const String& desc, - const String& src, const char* file, long line) - { - switch (code) - { - case Exception::ERR_CANNOT_WRITE_TO_FILE: throw IOException(number, desc, src, file, line); - case Exception::ERR_INVALID_STATE: throw InvalidStateException(number, desc, src, file, line); - case Exception::ERR_INVALIDPARAMS: throw InvalidParametersException(number, desc, src, file, line); - case Exception::ERR_RENDERINGAPI_ERROR: throw RenderingAPIException(number, desc, src, file, line); - case Exception::ERR_DUPLICATE_ITEM: throw ItemIdentityException(number, desc, src, file, line); - case Exception::ERR_FILE_NOT_FOUND: throw FileNotFoundException(number, desc, src, file, line); - case Exception::ERR_INTERNAL_ERROR: throw InternalErrorException(number, desc, src, file, line); - case Exception::ERR_RT_ASSERTION_FAILED: throw RuntimeAssertionException(number, desc, src, file, line); - case Exception::ERR_NOT_IMPLEMENTED: throw UnimplementedException(number, desc, src, file, line); - case Exception::ERR_INVALID_CALL: throw InvalidCallException(number, desc, src, file, line); - default: throw Exception(number, desc, src, "Exception", file, line); - } - } - public: - static OGRE_NORETURN void throwException( - Exception::ExceptionCodes code, - const String& desc, - const String& src, const char* file, long line) - { - _throwException(code, code, desc, src, file, line); - } - }; - - - -#ifndef OGRE_EXCEPT -#define OGRE_EXCEPT_3(code, desc, src) Ogre::ExceptionFactory::throwException(code, desc, src, __FILE__, __LINE__) -#define OGRE_EXCEPT_2(code, desc) Ogre::ExceptionFactory::throwException(code, desc, __FUNCTION__, __FILE__, __LINE__) -#define OGRE_EXCEPT_CHOOSER(arg1, arg2, arg3, arg4, ...) arg4 -#define OGRE_EXPAND(x) x // MSVC workaround -#define OGRE_EXCEPT(...) OGRE_EXPAND(OGRE_EXCEPT_CHOOSER(__VA_ARGS__, OGRE_EXCEPT_3, OGRE_EXCEPT_2)(__VA_ARGS__)) -#endif - /** @} */ - /** @} */ - -} // Namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreExternalTextureSource.h b/OgreMain/include/OgreExternalTextureSource.h deleted file mode 100644 index 37f2c732d66..00000000000 --- a/OgreMain/include/OgreExternalTextureSource.h +++ /dev/null @@ -1,160 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _OgreExternalTextureSource_H -#define _OgreExternalTextureSource_H - -/*************************************************************************** -OgreExternalTextureSource.h - - Base class that texture plugins need to derive from. This provides the hooks - necessary for a plugin developer to easily extend the functionality of dynamic textures. - It makes creation/destruction of dynamic textures more streamlined. While the plugin - will need to talk with Ogre for the actual modification of textures, this class allows - easy integration with Ogre apps. Material script files can be used to aid in the - creation of dynamic textures. Functionality can be added that is not defined here - through the use of the base dictionary. For an example of how to use this class and the - string interface see ffmpegVideoPlugIn. - -------------------- -date : Jan 1 2004 -email : pjcast@yahoo.com -***************************************************************************/ - -#include "OgreStringInterface.h" -#include "OgreResourceGroupManager.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Materials - * @{ - */ - /** Enum for type of texture play mode */ - enum eTexturePlayMode - { - TextureEffectPause = 0, /// Video starts out paused - TextureEffectPlay_ASAP = 1, /// Video starts playing as soon as possible - TextureEffectPlay_Looping = 2 /// Video Plays Instantly && Loops - }; - - /** IMPORTANT: **Plugins must override default dictionary name!** - Base class that texture plugins derive from. Any specific - requirements that the plugin needs to have defined before - texture/material creation must be define using the stringinterface - before calling create defined texture... or it will fail, though, it - is up to the plugin to report errors to the log file, or raise an - exception if need be. */ - class _OgreExport ExternalTextureSource : public StringInterface - { - public: - /** Constructor */ - ExternalTextureSource(); - /** Virtual destructor */ - virtual ~ExternalTextureSource() {} - - //--------------------------------------------------------// - //Base Functions that work with Command String Interface... Or can be called - //manually to create video through code - - /// Sets an input file name - if needed by plugin - void setInputName( const String &sIN ) { mInputFileName = sIN; } - /// Gets currently set input file name - const String& getInputName( ) const { return mInputFileName; } - /// Sets the frames per second - plugin may or may not use this - void setFPS( int iFPS ) { mFramesPerSecond = iFPS; } - /// Gets currently set frames per second - int getFPS( ) const { return mFramesPerSecond; } - /// Sets a play mode - void setPlayMode( eTexturePlayMode eMode ) { mMode = eMode; } - /// Gets currently set play mode - eTexturePlayMode getPlayMode() const { return mMode; } - - /// Used for attaching texture to Technique, State, and texture unit layer - void setTextureTecPassStateLevel( int t, int p, int s ) - { mTechniqueLevel = t;mPassLevel = p;mStateLevel = s; } - /// Get currently selected Texture attribs. - void getTextureTecPassStateLevel( int& t, int& p, int& s ) const - {t = mTechniqueLevel; p = mPassLevel; s = mStateLevel;} - - /** Call from derived classes to ensure the dictionary is setup */ - void addBaseParams(); - - /** Returns the string name of this Plugin (as set by the Plugin)*/ - const String& getPluginStringName( void ) const { return mPluginName; } - /** Returns dictionary name */ - const String& getDictionaryStringName( void ) const { return mDictionaryName; } - - //Pure virtual functions that plugins must Override - /** Call this function from manager to init system */ - virtual bool initialise() = 0; - /** Shuts down Plugin */ - virtual void shutDown() = 0; - - /** Creates a texture into an already defined material or one that is created new - (it's up to plugin to use a material or create one) - Before calling, ensure that needed params have been defined via the stringInterface - or regular methods */ - virtual void createDefinedTexture( const String& sMaterialName, - const String& groupName = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME) = 0; - /** What this destroys is dependent on the plugin... See specific plugin - doc to know what is all destroyed (normally, plugins will destroy only - what they created, or used directly - ie. just texture unit) */ - virtual void destroyAdvancedTexture( const String& sTextureName, - const String& groupName = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME) = 0; - - protected: - /// String Name of this Plugin - String mPluginName; - - //------ Vars used for setting/getting dictionary stuff -----------// - eTexturePlayMode mMode; - - String mInputFileName; - - bool mUpdateEveryFrame; - - int mFramesPerSecond, - mTechniqueLevel, - mPassLevel, - mStateLevel; - //------------------------------------------------------------------// - - protected: - /** The string name of the dictionary name - each plugin - must override default name */ - String mDictionaryName; - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreExternalTextureSourceManager.h b/OgreMain/include/OgreExternalTextureSourceManager.h deleted file mode 100644 index 5ae9c13a1f8..00000000000 --- a/OgreMain/include/OgreExternalTextureSourceManager.h +++ /dev/null @@ -1,99 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _OgreExternalTextureSourceManager_H -#define _OgreExternalTextureSourceManager_H - -/*************************************************************************** -OgreExternalTextureSourceManager.h - - Handles the registering / unregistering of texture modifier plugins - -------------------- -date : Jan 1 2004 -email : pjcast@yahoo.com -***************************************************************************/ -#include "OgreSingleton.h" -#include "OgreResourceGroupManager.h" -#include "OgreExternalTextureSource.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Materials - * @{ - */ - /** - Singleton Class which handles the registering and control of texture plugins. The plugins - will be mostly controlled via a string interface. */ - class _OgreExport ExternalTextureSourceManager : public Singleton, public ResourceAlloc - { - public: - /** Constructor */ - ExternalTextureSourceManager(); - /** Destructor */ - ~ExternalTextureSourceManager(); - - /** Sets active plugin (ie. "video", "effect", "generic", etc..) */ - void setCurrentPlugIn( const String& sTexturePlugInType ); - - /** Returns currently selected plugin, may be null if none selected */ - ExternalTextureSource* getCurrentPlugIn( void ) const { return mCurrExternalTextureSource; } - - /** Calls the destroy method of all registered plugins... - Only the owner plugin should perform the destroy action. */ - void destroyAdvancedTexture( const String& sTextureName, - const String& groupName = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - /** Returns the plugin which registered itself with a specific name - (eg. "video"), or null if specified plugin not found */ - ExternalTextureSource* getExternalTextureSource( const String& sTexturePlugInType ); - - /** Called from plugin to register itself */ - void setExternalTextureSource( const String& sTexturePlugInType, ExternalTextureSource* pTextureSystem ); - - /// @copydoc Singleton::getSingleton() - static ExternalTextureSourceManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static ExternalTextureSourceManager* getSingletonPtr(void); - private: - /// The current texture controller selected - ExternalTextureSource* mCurrExternalTextureSource; - - // Collection of loaded texture System PlugIns, keyed by registered type - typedef std::map< String, ExternalTextureSource*> TextureSystemList; - TextureSystemList mTextureSystems; - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreFactoryObj.h b/OgreMain/include/OgreFactoryObj.h deleted file mode 100644 index f1d122667ee..00000000000 --- a/OgreMain/include/OgreFactoryObj.h +++ /dev/null @@ -1,72 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _FactoryObj_H__ -#define _FactoryObj_H__ - -#include "OgrePrerequisites.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - /** Abstract factory class. Does nothing by itself, but derived classes can add - functionality. - */ - template< typename T > class FactoryObj - { - public: - virtual ~FactoryObj() {} - - /** Returns the factory type. - @return - The factory type. - */ - virtual const String& getType() const = 0; - - /** Creates a new object. - @param name Name of the object to create - @return - An object created by the factory. The type of the object depends on - the factory. - */ - virtual T* createInstance(const String& name) = 0; - /** Destroys an object which was created by this factory. - @param ptr Pointer to the object to destroy - */ - virtual void destroyInstance(T* ptr) { delete ptr; } - }; - - /** @} */ - /** @} */ -} // namespace Ogre - -#endif // _FactoryObj_H__ diff --git a/OgreMain/include/OgreFileSystem.h b/OgreMain/include/OgreFileSystem.h deleted file mode 100644 index 0b08e714fde..00000000000 --- a/OgreMain/include/OgreFileSystem.h +++ /dev/null @@ -1,93 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __FileSystem_H__ -#define __FileSystem_H__ - -#include "OgrePrerequisites.h" - -#include "OgreArchive.h" -#include "OgreArchiveFactory.h" -#include "OgreHeaderPrefix.h" - -struct AAssetManager; - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - - /// internal method to open a FileStreamDataStream - DataStreamPtr _openFileStream(const String& path, std::ios::openmode mode, const String& name = ""); - - /** Specialisation of the ArchiveFactory to allow reading of files from - filesystem folders / directories. - */ - class _OgreExport FileSystemArchiveFactory : public ArchiveFactory - { - public: - /// @copydoc FactoryObj::getType - const String& getType(void) const override; - - using ArchiveFactory::createInstance; - - Archive *createInstance( const String& name, bool readOnly ) override; - - /// Set whether filesystem enumeration will include hidden files or not. - /// This should be called prior to declaring and/or initializing filesystem - /// resource locations. The default is true (ignore hidden files). - static void setIgnoreHidden(bool ignore); - - /// Get whether hidden files are ignored during filesystem enumeration. - static bool getIgnoreHidden(); - }; - - class APKFileSystemArchiveFactory : public ArchiveFactory - { - public: - APKFileSystemArchiveFactory(AAssetManager* assetMgr) : mAssetMgr(assetMgr) {} - virtual ~APKFileSystemArchiveFactory() {} - /// @copydoc FactoryObj::getType - const String& getType(void) const override; - /// @copydoc ArchiveFactory::createInstance - Archive *createInstance( const String& name, bool readOnly ) override; - private: - AAssetManager* mAssetMgr; - }; - - /** @} */ - /** @} */ - -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif // __FileSystem_H__ diff --git a/OgreMain/include/OgreFileSystemLayer.h b/OgreMain/include/OgreFileSystemLayer.h deleted file mode 100644 index 911e0e7ad83..00000000000 --- a/OgreMain/include/OgreFileSystemLayer.h +++ /dev/null @@ -1,155 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#ifndef __FileSystemLayer_H__ -#define __FileSystemLayer_H__ - -#include "OgrePrerequisites.h" -#include "OgreStringVector.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - /** Provides methods to find out where the Ogre config files are stored - and where logs and settings files should be written to. - - In modern multi-user OS, a standard user account will often not - have write access to the path where the application is stored. - In order to still be able to store graphics settings and log - output and for the user to overwrite the default Ogre config files, - this class tries to create a folder inside the user's home directory. - */ - class _OgreExport FileSystemLayer : public FileSystemLayerAlloc - { - public: - /** Creates a concrete platform-dependent implementation of FileSystemLayer. - @param subdir - A subdirectory inside the user's path to distinguish between - different Ogre applications. - */ - FileSystemLayer(const Ogre::String& subdir) - { - // determine directories to search for config files - getConfigPaths(); - // prepare write location in user directory - prepareUserHome(subdir); - } - - /** Search for the given config file in a set of predefined locations - - The search order is - 1. Subdirectory in user Home (see @ref getWritablePath) - 2. OS dependent config-paths - 3. Current working directory - - @param filename The config file name (without path) - @return The full path to the config file - */ - Ogre::String getConfigFilePath(Ogre::String filename) const - { - // look for the requested file in several locations: - - // 1. in the writable path (so user can provide custom files) - Ogre::String path = getWritablePath(filename); - if (fileExists(path)) - return path; - - // 2. in the config file search paths - for (const String& cpath : mConfigPaths) - { - path = cpath + filename; - if (fileExists(path)) - return path; - } - - // 3. fallback to current working dir - return filename; - } - - /** Find a path where the given filename can be written to. This path - will usually be a subdirectory in the user's home directory. - This function should be used for any output like logs and graphics settings. - - | Platform | Location | - |------------------|----------| - | Windows | Documents/$subdir/ | - | Linux | ~/.cache/$subdir/ | - | OSX | ~/Library/Application Support/$subdir/ | - | iOS | NSDocumentDirectory | - | Android / Emscripten | n/a | - - @param filename Name of the file. - @return The full path to a writable location for the given filename. - */ - Ogre::String getWritablePath(const Ogre::String& filename) const - { - return mHomePath + filename; - } - - void setConfigPaths(const Ogre::StringVector &paths){ - mConfigPaths = paths; - } - - void setHomePath(const Ogre::String &path){ - mHomePath = path; - } - - /** Resolve path inside the application bundle - * on some platforms Ogre is delivered as an application bundle - * this function resolves the given path such that it points inside that bundle - * @param path - * @return path inside the bundle - */ - static String resolveBundlePath(String path); - - /** Create a directory. */ - static bool createDirectory(const Ogre::String& name); - /** Delete a directory. Should be empty */ - static bool removeDirectory(const Ogre::String& name); - /** Test if the given file exists. */ - static bool fileExists(const Ogre::String& path); - /** Delete a file. */ - static bool removeFile(const Ogre::String& path); - /** Rename a file. */ - static bool renameFile(const Ogre::String& oldpath, const Ogre::String& newpath); - - private: - Ogre::StringVector mConfigPaths; - Ogre::String mHomePath; - - /** Determine config search paths. */ - void getConfigPaths(); - - /** Create an Ogre directory and the given subdir in the user's home. */ - void prepareUserHome(const Ogre::String& subdir); - }; - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreFrameListener.h b/OgreMain/include/OgreFrameListener.h deleted file mode 100644 index 2fcdfbed30d..00000000000 --- a/OgreMain/include/OgreFrameListener.h +++ /dev/null @@ -1,137 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __FrameListener_H__ -#define __FrameListener_H__ - - -#include "OgrePrerequisites.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - /** Struct containing information about a frame event. - */ - struct FrameEvent - { - /** Elapsed time in seconds since the last event. - This gives you time between frame start & frame end, - and between frame end and next frame start. - - This may not be the elapsed time but the average - elapsed time between recently fired events. - */ - Real timeSinceLastEvent; - /** Elapsed time in seconds since the last event of the same type, - i.e. time for a complete frame. - - This may not be the elapsed time but the average - elapsed time between recently fired events of the same type. - */ - Real timeSinceLastFrame; - }; - - - /** A interface class defining a listener which can be used to receive - notifications of frame events. - - A 'listener' is an interface designed to be called back when - particular events are called. This class defines the - interface relating to frame events. In order to receive - notifications of frame events, you should create a subclass of - FrameListener and override the methods for which you would like - to customise the resulting processing. You should then call - Root::addFrameListener passing an instance of this class. - There is no limit to the number of frame listeners you can register, - allowing you to register multiple listeners for different purposes. - Note that a frame event occurs once for all rendering targets, - not once per target. - */ - class _OgreExport FrameListener - { - /* - Note that this could have been an abstract class, but I made - the explicit choice not to do this, because I wanted to give - people the option of only implementing the methods they wanted, - rather than having to create 'do nothing' implementations for - those they weren't interested in. As such this class follows - the 'Adapter' classes in Java rather than pure interfaces. - */ - public: - /** Called when a frame is about to begin rendering. - - This event happens before any render targets have begun updating. - @return - True to go ahead, false to abort rendering and drop - out of the rendering loop. - */ - virtual bool frameStarted(const FrameEvent& evt) - { (void)evt; return true; } - - /** Called after all render targets have had their rendering commands - issued, but before render windows have been asked to flip their - buffers over. - - The usefulness of this event comes from the fact that rendering - commands are queued for the GPU to process. These can take a little - while to finish, and so while that is happening the CPU can be doing - useful things. Once the request to 'flip buffers' happens, the thread - requesting it will block until the GPU is ready, which can waste CPU - cycles. Therefore, it is often a good idea to use this callback to - perform per-frame processing. Of course because the frame's rendering - commands have already been issued, any changes you make will only - take effect from the next frame, but in most cases that's not noticeable. - @return - True to continue rendering, false to drop out of the rendering loop. - */ - virtual bool frameRenderingQueued(const FrameEvent& evt) - { (void)evt; return true; } - - /** Called just after a frame has been rendered. - - This event happens after all render targets have been fully updated - and the buffers switched. - @return - True to continue with the next frame, false to drop - out of the rendering loop. - */ - virtual bool frameEnded(const FrameEvent& evt) - { (void)evt; return true; } - - virtual ~FrameListener() {} - - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/OgreMain/include/OgreFrustum.h b/OgreMain/include/OgreFrustum.h deleted file mode 100644 index b3e966010cc..00000000000 --- a/OgreMain/include/OgreFrustum.h +++ /dev/null @@ -1,609 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Frustum_H__ -#define __Frustum_H__ - -#include "OgrePrerequisites.h" -#include "OgreMovableObject.h" -#include "OgreAxisAlignedBox.h" -#include "OgreVertexIndexData.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** Specifies perspective (realistic) or orthographic (architectural) projection. - */ - enum ProjectionType : uint8 - { - PT_ORTHOGRAPHIC, - PT_PERSPECTIVE - }; - - /** Worldspace clipping planes. - */ - enum FrustumPlane : uint8 - { - FRUSTUM_PLANE_NEAR = 0, - FRUSTUM_PLANE_FAR = 1, - FRUSTUM_PLANE_LEFT = 2, - FRUSTUM_PLANE_RIGHT = 3, - FRUSTUM_PLANE_TOP = 4, - FRUSTUM_PLANE_BOTTOM = 5 - }; - - /** A frustum represents a pyramid, capped at the near and far end which is - used to represent either a visible area or a projection area. Can be used - for a number of applications. - */ - class _OgreExport Frustum : public MovableObject - { - protected: - /// y-direction field-of-view (default 45) - Radian mFOVy; - /// Far clip distance - default 10000 - Real mFarDist; - /// Near clip distance - default 100 - Real mNearDist; - /// x/y viewport ratio - default 1.3333 - Real mAspect; - /// Ortho height size (world units) - Real mOrthoHeight; - /// Off-axis frustum center offset - default (0.0, 0.0) - Vector2 mFrustumOffset; - /// Focal length of frustum (for stereo rendering, defaults to 1.0) - Real mFocalLength; - - /// The 6 main clipping planes - mutable Plane mFrustumPlanes[6]; - - /// Stored versions of parent orientation / position - mutable Quaternion mLastParentOrientation; - mutable Vector3 mLastParentPosition; - - /// Pre-calced standard projection matrix but with render system depth range - mutable Matrix4 mProjMatrixRSDepth; - /// Pre-calced standard projection matrix - mutable Matrix4 mProjMatrix; - /// Pre-calced view matrix - mutable Affine3 mViewMatrix; - /// Something's changed in the frustum shape? - mutable bool mRecalcFrustum; - /// Something re the view pos has changed - mutable bool mRecalcView; - /// Something re the frustum planes has changed - mutable bool mRecalcFrustumPlanes; - /// Something re the world space corners has changed - mutable bool mRecalcWorldSpaceCorners; - /// Are we using a custom view matrix? - bool mCustomViewMatrix; - /// Are we using a custom projection matrix? - bool mCustomProjMatrix; - /// Have the frustum extents been manually set? - bool mFrustumExtentsManuallySet; - /// Orthographic or perspective? - ProjectionType mProjType; - /// Frustum extents - mutable RealRect mExtents; - - // Internal functions for calcs - RealRect calcProjectionParameters() const; - /// Update frustum if out of date - void updateFrustum(void) const; - /// Update view if out of date - void updateView(void) const; - /// Implementation of updateFrustum (called if out of date) - virtual void updateFrustumImpl(void) const; - /// Implementation of updateView (called if out of date) - virtual void updateViewImpl(void) const; - void updateFrustumPlanes(void) const; - /// Implementation of updateFrustumPlanes (called if out of date) - virtual void updateFrustumPlanesImpl(void) const; - void updateWorldSpaceCorners(void) const; - /// Implementation of updateWorldSpaceCorners (called if out of date) - virtual void updateWorldSpaceCornersImpl(void) const; - virtual bool isViewOutOfDate(void) const; - bool isFrustumOutOfDate(void) const; - /// Signal to update frustum information. - virtual void invalidateFrustum(void) const; - /// Signal to update view information. - virtual void invalidateView(void) const; - - ColourValue mDebugColour; - /// Pointer to a reflection plane (automatically updated) - const MovablePlane* mLinkedReflectPlane; - /// Pointer to oblique projection plane (automatically updated) - const MovablePlane* mLinkedObliqueProjPlane; - - mutable AxisAlignedBox mBoundingBox; - mutable Vector3 mWorldSpaceCorners[8]; - - /// Derived reflection matrix - mutable Affine3 mReflectMatrix; - /// Fixed reflection plane - mutable Plane mReflectPlane; - /// Record of the last world-space reflection plane info used - mutable Plane mLastLinkedReflectionPlane; - /// Fixed oblique projection plane - mutable Plane mObliqueProjPlane; - /// Record of the last world-space oblique depth projection plane info used - mutable Plane mLastLinkedObliqueProjPlane; - - /// Is this frustum to act as a reflection of itself? - bool mReflect; - /// Is this frustum using an oblique depth projection? - bool mObliqueDepthProjection; - - public: - - /// Named constructor - Frustum(const String& name = BLANKSTRING); - - virtual ~Frustum(); - /** Sets the Y-dimension Field Of View (FOV) of the frustum. - - Field Of View (FOV) is the angle made between the frustum's position, and the edges - of the 'screen' onto which the scene is projected. High values (90+ degrees) result in a wide-angle, - fish-eye kind of view, low values (30- degrees) in a stretched, telescopic kind of view. Typical values - are between 45 and 60 degrees. - @par - This value represents the VERTICAL field-of-view. The horizontal field of view is calculated from - this depending on the dimensions of the viewport (they will only be the same if the viewport is square). - */ - void setFOVy(const Radian& fovy); - - /** Retrieves the frustums Y-dimension Field Of View (FOV). - */ - const Radian& getFOVy(void) const; - - /** Sets the position of the near clipping plane. - - The position of the near clipping plane is the distance from the frustums position to the screen - on which the world is projected. The near plane distance, combined with the field-of-view and the - aspect ratio, determines the size of the viewport through which the world is viewed (in world - coordinates). Note that this world viewport is different to a screen viewport, which has it's - dimensions expressed in pixels. The frustums viewport should have the same aspect ratio as the - screen viewport it renders into to avoid distortion. - @param nearDist - The distance to the near clipping plane from the frustum in world coordinates. - */ - void setNearClipDistance(Real nearDist); - - /** Retrieves the distance from the frustum to the near clipping plane. - */ - Real getNearClipDistance(void) const; - - /** Sets the distance to the far clipping plane. - - The view frustum is a pyramid created from the frustum position and the edges of the viewport. - This method sets the distance for the far end of that pyramid. - Different applications need different values: e.g. a flight sim - needs a much further far clipping plane than a first-person - shooter. An important point here is that the larger the ratio - between near and far clipping planes, the lower the accuracy of - the Z-buffer used to depth-cue pixels. This is because the - Z-range is limited to the size of the Z buffer (16 or 32-bit) - and the max values must be spread over the gap between near and - far clip planes. As it happens, you can affect the accuracy far - more by altering the near distance rather than the far distance, - but keep this in mind. - @param farDist - The distance to the far clipping plane from the frustum in - world coordinates.If you specify 0, this means an infinite view - distance which is useful especially when projecting shadows; but - be careful not to use a near distance too close. - */ - void setFarClipDistance(Real farDist); - - /** Retrieves the distance from the frustum to the far clipping plane. - */ - Real getFarClipDistance(void) const; - - /** Sets the aspect ratio for the frustum viewport. - - The ratio between the x and y dimensions of the rectangular area visible through the frustum - is known as aspect ratio: aspect = width / height . - @par - The default for most fullscreen windows is 1.3333 - this is also assumed by Ogre unless you - use this method to state otherwise. - */ - void setAspectRatio(Real ratio); - - /** Retrieves the current aspect ratio. - */ - Real getAspectRatio(void) const; - - /** Sets frustum offsets, used in stereo rendering. - - You can set both horizontal and vertical plane offsets of "eye"; in - stereo rendering frustum is moved in horizontal plane. To be able to - render from two "eyes" you'll need two cameras rendering on two - RenderTargets. - @par - The frustum offsets is in world coordinates, and default to (0, 0) - no offsets. - @param offset - The horizontal and vertical plane offsets. - */ - void setFrustumOffset(const Vector2& offset); - - /** Sets frustum offsets, used in stereo rendering. - - You can set both horizontal and vertical plane offsets of "eye"; in - stereo rendering frustum is moved in horizontal plane. To be able to - render from two "eyes" you'll need two cameras rendering on two - RenderTargets. - @par - The frustum offsets is in world coordinates, and default to (0, 0) - no offsets. - @param horizontal - The horizontal plane offset. - @param vertical - The vertical plane offset. - */ - void setFrustumOffset(Real horizontal = 0.0, Real vertical = 0.0); - - /** Retrieves the frustum offsets. - */ - const Vector2& getFrustumOffset() const; - - /** Sets frustum focal length (used in stereo rendering). - @param focalLength - The distance to the focal plane from the frustum in world coordinates. - */ - void setFocalLength(Real focalLength = 1.0); - - /** Returns focal length of frustum. - */ - Real getFocalLength() const; - - /** Manually set the extents of the frustum. - @param left, right, top, bottom The position where the side clip planes intersect - the near clip plane, in eye space - */ - void setFrustumExtents(Real left, Real right, Real top, Real bottom); - /** Reset the frustum extents to be automatically derived from other params. */ - void resetFrustumExtents(); - /** Get the extents of the frustum in view space. */ - RealRect getFrustumExtents() const; - - /** Gets the depth-adjusted projection matrix for the current rendersystem - - This differs from the rendering-API independent @ref getProjectionMatrix - in that it the resulting depth range may vary between render systems since D3D uses [0,1] and - GL uses [-1,1]. This is required for vertex and fragment programs. - */ - const Matrix4& getProjectionMatrixWithRSDepth(void) const; - /** Gets the normal projection matrix for this frustum - - i.e. the projection matrix which conforms to standard right-handed rules and - uses depth range [-1,+1]. This is required for some uniform algebra. - */ - const Matrix4& getProjectionMatrix(void) const; - - /** Gets the view matrix for this frustum. Mainly for use by OGRE internally. - */ - const Affine3& getViewMatrix(void) const; - - /** Calculate a view matrix for this frustum, relative to a potentially dynamic point. - Mainly for use by OGRE internally when using camera-relative rendering - for frustums that are not the centre (e.g. texture projection) - */ - void calcViewMatrixRelative(const Vector3& relPos, Matrix4& matToUpdate) const; - - /** Set whether to use a custom view matrix on this frustum. - - This is an advanced method which allows you to manually set - the view matrix on this frustum, rather than having it calculate - itself based on it's position and orientation. - @note - After enabling a custom view matrix, the frustum will no longer - update on its own based on position / orientation changes. You - are completely responsible for keeping the view matrix up to date. - The custom matrix will be returned from getViewMatrix. - @param enable If @c true, the custom view matrix passed as the second - parameter will be used in preference to an auto calculated one. If - false, the frustum will revert to auto calculating the view matrix. - @param viewMatrix The custom view matrix to use - @see Frustum::setCustomProjectionMatrix - */ - void setCustomViewMatrix(bool enable, const Affine3& viewMatrix = Affine3::IDENTITY); - - /// Returns whether a custom view matrix is in use - bool isCustomViewMatrixEnabled(void) const { return mCustomViewMatrix; } - - /** Set whether to use a custom projection matrix on this frustum. - - This is an advanced method which allows you to manually set - the projection matrix on this frustum, rather than having it - calculate itself based on it's position and orientation. - @note - After enabling a custom projection matrix, the frustum will no - longer update on its own based on field of view and near / far - distance changes. You are completely responsible for keeping the - projection matrix up to date if those values change. The custom - matrix will be returned from getProjectionMatrix and derivative - functions. - @param enable - If @c true, the custom projection matrix passed as the - second parameter will be used in preference to an auto calculated - one. If @c false, the frustum will revert to auto calculating the - projection matrix. - @param projectionMatrix - The custom view matrix to use. - @see Frustum::setCustomViewMatrix - */ - void setCustomProjectionMatrix(bool enable, - const Matrix4& projectionMatrix = Matrix4::IDENTITY); - /// Returns whether a custom projection matrix is in use - bool isCustomProjectionMatrixEnabled(void) const { return mCustomProjMatrix; } - - /** Retrieves the clipping planes of the frustum (world space). - - The clipping planes are ordered as declared in enumerate constants FrustumPlane. - */ - virtual const Plane* getFrustumPlanes(void) const; - - /** Retrieves a specified plane of the frustum (world space). - - Gets a reference to one of the planes which make up the frustum frustum, e.g. for clipping purposes. - */ - virtual const Plane& getFrustumPlane( unsigned short plane ) const; - - /// @copydoc MovableObject::isVisible - using Ogre::MovableObject::isVisible; - - /** Tests whether the given container is visible in the Frustum. - @param bound - Bounding box to be checked (world space). - @param culledBy - Optional pointer to an int which will be filled by the plane number which culled - the box if the result was @c false; - @return - If the box was visible, @c true is returned. - @par - Otherwise, @c false is returned. - */ - virtual bool isVisible(const AxisAlignedBox& bound, FrustumPlane* culledBy = 0) const; - - /** Tests whether the given container is visible in the Frustum. - @param bound - Bounding sphere to be checked (world space). - @param culledBy - Optional pointer to an int which will be filled by the plane number which culled - the box if the result was @c false; - @return - If the sphere was visible, @c true is returned. - @par - Otherwise, @c false is returned. - */ - virtual bool isVisible(const Sphere& bound, FrustumPlane* culledBy = 0) const; - - /** Tests whether the given vertex is visible in the Frustum. - @param vert - Vertex to be checked (world space). - @param culledBy - Optional pointer to an int which will be filled by the plane number which culled - the box if the result was @c false; - @return - If the sphere was visible, @c true is returned. - @par - Otherwise, @c false is returned. - */ - virtual bool isVisible(const Vector3& vert, FrustumPlane* culledBy = 0) const; - - uint32 getTypeFlags(void) const override; - const AxisAlignedBox& getBoundingBox(void) const override; - Real getBoundingRadius(void) const override; - void _updateRenderQueue(RenderQueue* queue) override; - const String& getMovableType(void) const override; - void _notifyCurrentCamera(Camera* cam) override; - - void setDebugColour(const ColourValue& col) { mDebugColour = col; } - const ColourValue& getDebugColour() const { return mDebugColour; } - - typedef Vector3 Corners[8]; - - /** Gets the world space corners of the frustum. - - The corners are ordered as follows: top-right near, - top-left near, bottom-left near, bottom-right near, - top-right far, top-left far, bottom-left far, bottom-right far. - */ - virtual const Corners& getWorldSpaceCorners(void) const; - - /** Sets the type of projection to use (orthographic or perspective). Default is perspective. - */ - virtual void setProjectionType(ProjectionType pt); - - /** Retrieves info on the type of projection used (orthographic or perspective). - */ - ProjectionType getProjectionType(void) const; - - /** Sets the orthographic window settings, for use with orthographic rendering only. - @note Calling this method will recalculate the aspect ratio, use - setOrthoWindowHeight or setOrthoWindowWidth alone if you wish to - preserve the aspect ratio but just fit one or other dimension to a - particular size. - @param w - The width of the view window in world units. - @param h - The height of the view window in world units. - */ - void setOrthoWindow(Real w, Real h); - /** Sets the orthographic window height, for use with orthographic rendering only. - @note The width of the window will be calculated from the aspect ratio. - @param h - The height of the view window in world units. - */ - void setOrthoWindowHeight(Real h); - /** Sets the orthographic window width, for use with orthographic rendering only. - @note The height of the window will be calculated from the aspect ratio. - @param w - The width of the view window in world units. - */ - void setOrthoWindowWidth(Real w); - /** Gets the orthographic window height, for use with orthographic rendering only. - */ - Real getOrthoWindowHeight() const; - /** Gets the orthographic window width, for use with orthographic rendering only. - @note This is calculated from the orthographic height and the aspect ratio - */ - Real getOrthoWindowWidth() const; - - /** Modifies this frustum so it always renders from the reflection of itself through the - plane specified. - - This is obviously useful for performing planar reflections. - */ - void enableReflection(const Plane& p); - /** Modifies this frustum so it always renders from the reflection of itself through the - plane specified. Note that this version of the method links to a plane - so that changes to it are picked up automatically. It is important that - this plane continues to exist whilst this object does; do not destroy - the plane before the frustum. - - This is obviously useful for performing planar reflections. - */ - void enableReflection(const MovablePlane* p); - - /** Disables reflection modification previously turned on with enableReflection */ - void disableReflection(void); - - /// Returns whether this frustum is being reflected - bool isReflected(void) const { return mReflect; } - /// Returns the reflection matrix of the frustum if appropriate - const Affine3& getReflectionMatrix(void) const { return mReflectMatrix; } - /// Returns the reflection plane of the frustum if appropriate - const Plane& getReflectionPlane(void) const { return mReflectPlane; } - - /** Project a sphere onto the near plane and get the bounding rectangle. - @param sphere The world-space sphere to project. - @param left - Pointers to destination values, these will be completed with - the normalised device coordinates (in the range {-1,1}). - @param top - Pointers to destination values, these will be completed with - the normalised device coordinates (in the range {-1,1}). - @param right - Pointers to destination values, these will be completed with - the normalised device coordinates (in the range {-1,1}). - @param bottom - Pointers to destination values, these will be completed with - the normalised device coordinates (in the range {-1,1}). - @return @c true if the sphere was projected to a subset of the near plane, - @c false if the entire near plane was contained. - */ - virtual bool projectSphere(const Sphere& sphere, - Real* left, Real* top, Real* right, Real* bottom) const; - - - /** Links the frustum to a custom near clip plane, which can be used - to clip geometry in a custom manner without using user clip planes. - - There are several applications for clipping a scene arbitrarily by - a single plane; the most common is when rendering a reflection to - a texture, and you only want to render geometry that is above the - water plane (to do otherwise results in artefacts). Whilst it is - possible to use user clip planes, they are not supported on all - cards, and sometimes are not hardware accelerated when they are - available. Instead, where a single clip plane is involved, this - technique uses a 'fudging' of the near clip plane, which is - available and fast on all hardware, to perform as the arbitrary - clip plane. This does change the shape of the frustum, leading - to some depth buffer loss of precision, but for many of the uses of - this technique that is not an issue. - @par - This version of the method links to a plane, rather than requiring - a by-value plane definition, and therefore you can - make changes to the plane (e.g. by moving / rotating the node it is - attached to) and they will automatically affect this object. - @note This technique only works for perspective projection. - @param plane - The plane to link to to perform the clipping. This plane - must continue to exist while the camera is linked to it; do not - destroy it before the frustum. - */ - void enableCustomNearClipPlane(const MovablePlane* plane); - /** Links the frustum to a custom near clip plane, which can be used - to clip geometry in a custom manner without using user clip planes. - - There are several applications for clipping a scene arbitrarily by - a single plane; the most common is when rendering a reflection to - a texture, and you only want to render geometry that is above the - water plane (to do otherwise results in artefacts). Whilst it is - possible to use user clip planes, they are not supported on all - cards, and sometimes are not hardware accelerated when they are - available. Instead, where a single clip plane is involved, this - technique uses a 'fudging' of the near clip plane, which is - available and fast on all hardware, to perform as the arbitrary - clip plane. This does change the shape of the frustum, leading - to some depth buffer loss of precision, but for many of the uses of - this technique that is not an issue. - @note This technique only works for perspective projection. - @param plane - The plane to link to to perform the clipping. This plane - must continue to exist while the camera is linked to it; do not - destroy it before the frustum. - */ - void enableCustomNearClipPlane(const Plane& plane); - /** Disables any custom near clip plane. */ - void disableCustomNearClipPlane(void); - /** Is a custom near clip plane in use? */ - bool isCustomNearClipPlaneEnabled(void) const - { return mObliqueDepthProjection; } - - /// @copydoc MovableObject::visitRenderables - void visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables = false) override; - - /// Small constant used to reduce far plane projection to avoid inaccuracies - static const Real INFINITE_FAR_PLANE_ADJUST; - - /** Get the derived position of this frustum. */ - virtual const Vector3& getPositionForViewUpdate(void) const; - /** Get the derived orientation of this frustum. */ - virtual const Quaternion& getOrientationForViewUpdate(void) const; - - /** Gets a world-space list of planes enclosing the frustum. - */ - PlaneBoundedVolume getPlaneBoundedVolume(); - - }; - - /** @} */ - /** @} */ - -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif // __Frustum_H__ diff --git a/OgreMain/include/OgreGpuProgram.h b/OgreMain/include/OgreGpuProgram.h deleted file mode 100644 index 6a7c23b0b9d..00000000000 --- a/OgreMain/include/OgreGpuProgram.h +++ /dev/null @@ -1,376 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GpuProgram_H_ -#define __GpuProgram_H_ - -// Precompiler options -#include "OgrePrerequisites.h" -#include "OgreResource.h" -#include "OgreGpuProgramParams.h" -#include "OgreHeaderPrefix.h" -#include "OgreVector.h" -#include "OgreSharedPtr.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - /** Enumerates the types of programs which can run on the GPU. */ - enum GpuProgramType : uint8 - { - GPT_VERTEX_PROGRAM = 0, - GPT_FRAGMENT_PROGRAM, - GPT_GEOMETRY_PROGRAM, - GPT_DOMAIN_PROGRAM, - GPT_HULL_PROGRAM, - GPT_COMPUTE_PROGRAM - }; - enum { - GPT_COUNT = GPT_COMPUTE_PROGRAM + 1 - }; - - /** Defines a program which runs on the GPU such as a vertex or fragment program. - - This class defines the low-level program in assembler code, the sort used to - directly assemble into machine instructions for the GPU to execute. By nature, - this means that the assembler source is rendersystem specific, which is why this - is an abstract class - real instances are created through the RenderSystem. - If you wish to use higher level shading languages like HLSL and Cg, you need to - use the HighLevelGpuProgram class instead. - */ - class _OgreExport GpuProgram : public Resource - { - protected: - /// The name of the file to load source from (may be blank) - String mFilename; - /// The assembler source of the program (may be blank until file loaded) - String mSource; - /// Syntax code e.g. arbvp1, vs_2_0 etc - String mSyntaxCode; - /// The type of the program - GpuProgramType mType; - /// Whether we need to load source from file or not - bool mLoadFromFile; - /// Does this (vertex) program include Instancing? - bool mInstancing; - /// Does this (vertex) program include skeletal animation? - bool mSkeletalAnimation; - /// Does this (vertex) program include morph animation? - bool mMorphAnimation; - /// Does this (vertex) program require support for vertex texture fetch? - bool mVertexTextureFetch; - /// Does this (geometry) program require adjacency information? - bool mNeedsAdjacencyInfo; - /// Did we encounter a compilation error? - bool mCompileError; - bool mLoadedManualNamedConstants; - /// The default parameters for use with this object - GpuProgramParametersSharedPtr mDefaultParams; - /** Record of logical to physical buffer maps. Mandatory for low-level - programs or high-level programs which set their params the same way. - This is a shared pointer because if the program is recompiled and the parameters - change, this definition will alter, but previous params may reference the old def. */ - GpuLogicalBufferStructPtr mLogicalToPhysical; - /** Parameter name -> ConstantDefinition map, shared instance used by all parameter objects. - This is a shared pointer because if the program is recompiled and the parameters - change, this definition will alter, but previous params may reference the old def. - */ - GpuNamedConstantsPtr mConstantDefs; - /// File from which to load named constants manually - String mManualNamedConstantsFile; - /// Does this (vertex) program include pose animation (count of number of poses supported) - ushort mPoseAnimation; - - /** Internal method for setting up the basic parameter definitions for a subclass. - - Because StringInterface holds a dictionary of parameters per class, subclasses need to - call this to ask the base class to add it's parameters to their dictionary as well. - Can't do this in the constructor because that runs in a non-virtual context. - @par - The subclass must have called it's own createParamDictionary before calling this method. - */ - virtual void setupBaseParamDictionary(void); - - /** Internal method returns whether required capabilities for this program is supported. - */ - bool isRequiredCapabilitiesSupported(void) const; - - // catches errors during prepare - void safePrepare(); - - void prepareImpl() override; - - void loadImpl(void) override; - - void postLoadImpl() override; - - /// Create the internal params logical & named mapping structures - void createParameterMappingStructures(bool recreateIfExists = true); - /// Create the internal params logical mapping structures - void createLogicalParameterMappingStructures(bool recreateIfExists = true); - /// Create the internal params named mapping structures - void createNamedParameterMappingStructures(bool recreateIfExists = true); - - public: - - GpuProgram(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual = false, ManualResourceLoader* loader = 0); - - static const String getProgramTypeName(GpuProgramType programType); - - virtual ~GpuProgram() {} - - /** Sets the filename of the source assembly for this program. - - Setting this will have no effect until you (re)load the program. - */ - void setSourceFile(const String& filename); - - /** Sets the source assembly for this program from an in-memory string. - - Setting this will have no effect until you (re)load the program. - */ - void setSource(const String& source); - - /** Gets the syntax code for this program e.g. arbvp1, fp20, vs_1_1 etc */ - const String& getSyntaxCode(void) const { return mSyntaxCode; } - - /** Sets the syntax code for this program e.g. arbvp1, fp20, vs_1_1 etc */ - void setSyntaxCode(const String& syntax); - - /** Gets the name of the file used as source for this program. */ - const String& getSourceFile(void) const { return mFilename; } - /** Gets the assembler source for this program. */ - virtual const String& getSource(void) const { return mSource; } - /// Set the program type (only valid before load) - void setType(GpuProgramType t); - /// Get the program type - GpuProgramType getType(void) const { return mType; } - - /** Returns the GpuProgram which should be bound to the pipeline. - - This method is simply to allow some subclasses of GpuProgram to delegate - the program which is bound to the pipeline to a delegate, if required. */ - virtual GpuProgram* _getBindingDelegate(void) { return this; } - - /** Returns whether this program can be supported on the current renderer and hardware. */ - virtual bool isSupported(void) const; - - /** Creates a new parameters object compatible with this program definition. - - It is recommended that you use this method of creating parameters objects - rather than going direct to GpuProgramManager, because this method will - populate any implementation-specific extras (like named parameters) where - they are appropriate. - */ - virtual GpuProgramParametersSharedPtr createParameters(void); - - /// @name GPU offloading features - /// @{ - /** Sets whether a vertex program can do instancing. - - If this is set to true, OGRE will provide an instance buffer holding the - World Matrix of each instance to the vertex program. - */ - void setInstancingIncluded(bool included) { mInstancing = included; } - - /** Returns whether a vertex program can do instancing. - */ - bool isInstancingIncluded(void) const { return mInstancing; } - - /** Sets whether a vertex program can do skeletal animation. - - If this is set to true, OGRE will not blend the geometry according to - skeletal animation, it will expect the vertex program to do it. - */ - virtual void setSkeletalAnimationIncluded(bool included) { mSkeletalAnimation = included; } - - /** Returns whether a vertex program can do skeletal animation. - - If this returns true, OGRE will not blend the geometry according to - skeletal animation, it will expect the vertex program to do it. - */ - virtual bool isSkeletalAnimationIncluded(void) const { return mSkeletalAnimation; } - - /** Sets whether a vertex program can do morph animation. - - If this is set to true, OGRE will not blend the geometry according to - morph animation, it will expect the vertex program to do it. - */ - virtual void setMorphAnimationIncluded(bool included) - { mMorphAnimation = included; } - - /** Sets whether a vertex program can do pose animation. - - If this is set to true, OGRE will not blend the geometry according to - pose animation, it will expect the vertex program to do it. - @param poseCount The number of simultaneous poses the program can blend - */ - virtual void setPoseAnimationIncluded(ushort poseCount) - { mPoseAnimation = poseCount; } - - /** Returns whether a vertex program can do morph animation. - - If this returns true, OGRE will not blend the geometry according to - morph animation, it will expect the vertex program to do it. - */ - virtual bool isMorphAnimationIncluded(void) const { return mMorphAnimation; } - - /** Returns whether a vertex program can do pose animation. - - If this returns true, OGRE will not blend the geometry according to - pose animation, it will expect the vertex program to do it. - */ - virtual bool isPoseAnimationIncluded(void) const { return mPoseAnimation > 0; } - /** Returns the number of simultaneous poses the vertex program can - blend, for use in pose animation. - */ - virtual ushort getNumberOfPosesIncluded(void) const { return mPoseAnimation; } - /// @} - - /** Sets whether this vertex program requires support for vertex - texture fetch from the hardware. - */ - virtual void setVertexTextureFetchRequired(bool r) { mVertexTextureFetch = r; } - /** Returns whether this vertex program requires support for vertex - texture fetch from the hardware. - */ - virtual bool isVertexTextureFetchRequired(void) const { return mVertexTextureFetch; } - - /** Get a reference to the default parameters which are to be used for all - uses of this program. - - A program can be set up with a list of default parameters, which can save time when - using a program many times in a material with roughly the same settings. By - retrieving the default parameters and populating it with the most used options, - any new parameter objects created from this program afterwards will automatically include - the default parameters; thus users of the program need only change the parameters - which are unique to their own usage of the program. - */ - virtual const GpuProgramParametersPtr& getDefaultParameters(void); - - /** Returns true if default parameters have been set up. - */ - virtual bool hasDefaultParameters(void) const { return mDefaultParams.get() != 0; } - - /** Returns whether a vertex program wants light and material states to be passed - through fixed pipeline low level API rendering calls (default false, subclasses can override) - - Most vertex programs do not need this material information, however GLSL - shaders can refer to this material and lighting state so enable this option - */ - virtual bool getPassSurfaceAndLightStates(void) const { return false; } - - /** Returns whether a fragment program wants fog state to be passed - through fixed pipeline low level API rendering calls (default true, subclasses can override) - - On DirectX, shader model 2 and earlier continues to have fixed-function fog - applied to it, so fog state is still passed (you should disable fog on the - pass if you want to perform fog in the shader). In OpenGL it is also - common to be able to access the fixed-function fog state inside the shader. - */ - virtual bool getPassFogStates(void) const { return true; } - - /** Returns whether a vertex program wants transform state to be passed - through fixed pipeline low level API rendering calls - - Most vertex programs do not need fixed-function transform information, however GLSL - shaders can refer to this state so enable this option - */ - virtual bool getPassTransformStates(void) const { return false; } - - /** Returns a string that specifies the language of the gpu programs as specified - in a material script. ie: asm, cg, hlsl, glsl - */ - virtual const String& getLanguage(void) const; - - /** Did this program encounter a compile error when loading? - */ - virtual bool hasCompileError(void) const { return mCompileError; } - - /** Reset a compile error if it occurred, allowing the load to be retried - */ - virtual void resetCompileError(void) { mCompileError = false; } - - /** Allows you to manually provide a set of named parameter mappings - to a program which would not be able to derive named parameters itself. - - You may wish to use this if you have assembler programs that were compiled - from a high-level source, and want the convenience of still being able - to use the named parameters from the original high-level source. - @see setManualNamedConstantsFile - */ - void setManualNamedConstants(const GpuNamedConstants& namedConstants); - - /** Specifies the name of a file from which to load named parameters mapping - for a program which would not be able to derive named parameters itself. - - You may wish to use this if you have assembler programs that were compiled - from a high-level source, and want the convenience of still being able - to use the named parameters from the original high-level source. This - method will make a low-level program search in the resource group of the - program for the named file from which to load parameter names from. - The file must be in the format produced by GpuNamedConstants::save. - */ - void setManualNamedConstantsFile(const String& paramDefFile); - - /** Gets the name of a file from which to load named parameters mapping - for a program which would not be able to derive named parameters itself. - */ - const String& getManualNamedConstantsFile() const { return mManualNamedConstantsFile; } - /** Get the full list of named constants. - @note - Only available if this parameters object has named parameters, which means either - a high-level program which loads them, or a low-level program which has them - specified manually. - */ - virtual const GpuNamedConstants& getConstantDefinitions() { return *mConstantDefs.get(); } - - size_t calculateSize(void) const override; - - /// internal method to get the microcode cache id - uint32 _getHash(uint32 seed = 0) const; - - protected: - /// Virtual method which must be implemented by subclasses, load from mSource - virtual void loadFromSource(void) = 0; - - }; - - inline String to_string(const GpuProgramType& v) { return GpuProgram::getProgramTypeName(v); } - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreGpuProgramManager.h b/OgreMain/include/OgreGpuProgramManager.h deleted file mode 100644 index 18e7cae98b8..00000000000 --- a/OgreMain/include/OgreGpuProgramManager.h +++ /dev/null @@ -1,308 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GpuProgramManager_H_ -#define __GpuProgramManager_H_ - -// Precompiler options -#include "OgrePrerequisites.h" -#include "OgreResourceManager.h" -#include "OgreGpuProgram.h" -#include "OgreSingleton.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - - /** Interface definition for factories of GpuProgram. */ - class _OgreExport GpuProgramFactory : public FactoryAlloc - { - public: - virtual ~GpuProgramFactory() {} - /// Get the name of the language this factory creates programs for - virtual const String& getLanguage(void) const = 0; - virtual GpuProgram* create(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) = 0; - virtual void destroy(GpuProgram* prog) { delete prog; } - }; - - - /** This ResourceManager manages GPU shader programs - - This class not only manages the programs themselves, it also manages the factory - classes which allow the creation of programs using a variety of - syntaxes. Plugins can be created which register themselves as program - factories and as such the engine can be extended to accept virtually any kind of - program provided a plugin is written. - */ - class _OgreExport GpuProgramManager : public ResourceManager, public Singleton - { - // silence warnings - using ResourceManager::load; - - /// Factories capable of creating GpuProgram instances - typedef std::map FactoryMap; - FactoryMap mFactories; - - /// Factory for dealing with programs for languages we can't create - std::unique_ptr mNullFactory; - /// Factory for unified high-level programs - std::unique_ptr mUnifiedFactory; - - GpuProgramFactory* getFactory(const String& language); - - public: - - typedef std::set SyntaxCodes; - typedef std::map SharedParametersMap; - - typedef MemoryDataStreamPtr Microcode; - - protected: - - SharedParametersMap mSharedParametersMap; - std::map mMicrocodeCache; - bool mSaveMicrocodesToCache; - bool mCacheDirty; // When this is true the cache is 'dirty' and should be resaved to disk. - - static String addRenderSystemToName( const String & name ); - - /// Generic create method - Resource* createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams) override; - public: - GpuProgramManager(); - virtual ~GpuProgramManager(); - - /// Get a GPU Program by name. For example, a GPU Program defined in some .program file. - /// @see GpuProgramManager::getResourceByName - GpuProgramPtr getByName(const String& name, const String& group OGRE_RESOURCE_GROUP_INIT) const; - - /// @deprecated preferHighLevelPrograms has no effect - OGRE_DEPRECATED GpuProgramPtr getByName(const String& name, const String& group, - bool preferHighLevelPrograms) const - { - return getByName(name, group); - } - - /** Loads a GPU program from a file - - This method creates a new program of the type specified as the second parameter. - As with all types of ResourceManager, this class will search for the file in - all resource locations it has been configured to look in. - @param name The name of the GpuProgram - @param groupName The name of the resource group - @param filename The file to load - @param gptype The type of program to create - @param syntaxCode The name of the syntax to be used for this program e.g. arbvp1, vs_1_1 - */ - virtual GpuProgramPtr load(const String& name, const String& groupName, - const String& filename, GpuProgramType gptype, - const String& syntaxCode); - - /** Loads a GPU program from a string - - The assembly code must be compatible with this manager - call the - getSupportedSyntax method for details of the supported syntaxes - @param name The identifying name to give this program, which can be used to - retrieve this program later with getByName. - @param groupName The name of the resource group - @param code A string of assembly code which will form the program to run - @param gptype The type of program to create. - @param syntaxCode The name of the syntax to be used for this program e.g. arbvp1, vs_1_1 - */ - virtual GpuProgramPtr loadFromString(const String& name, const String& groupName, - const String& code, GpuProgramType gptype, - const String& syntaxCode); - - /** Returns the syntaxes that the RenderSystem supports. */ - static const SyntaxCodes& getSupportedSyntax(void); - - /** Returns whether a given syntax code (e.g. "glsl330", "vs_4_0", "arbvp1") is supported. */ - static bool isSyntaxSupported(const String& syntaxCode); - - /** Returns whether a given high-level language (e.g. "glsl", "hlsl") is supported. */ - bool isLanguageSupported(const String& lang) const; - - /** Creates a new GpuProgramParameters instance which can be used to bind - parameters to your programs. - - Program parameters can be shared between multiple programs if you wish. - */ - static GpuProgramParametersPtr createParameters(void) { return std::make_shared(); } - - /** Create a new, unloaded GpuProgram from a file of assembly. - - Use this method in preference to the 'load' methods if you wish to define - a GpuProgram, but not load it yet; useful for saving memory. - @par - This method creates a new program of the type specified as the second parameter. - As with all types of ResourceManager, this class will search for the file in - all resource locations it has been configured to look in. - @param name The name of the program - @param groupName The name of the resource group - @param filename The file to load - @param syntaxCode The name of the syntax to be used for this program e.g. arbvp1, vs_1_1 - @param gptype The type of program to create - */ - virtual GpuProgramPtr createProgram(const String& name, - const String& groupName, const String& filename, - GpuProgramType gptype, const String& syntaxCode); - - /** Create a GPU program from a string of assembly code. - - Use this method in preference to the 'load' methods if you wish to define - a GpuProgram, but not load it yet; useful for saving memory. - @par - The assembly code must be compatible with this manager - call the - getSupportedSyntax method for details of the supported syntaxes - @param name The identifying name to give this program, which can be used to - retrieve this program later with getByName. - @param groupName The name of the resource group - @param code A string of assembly code which will form the program to run - @param gptype The type of program to create. - @param syntaxCode The name of the syntax to be used for this program e.g. arbvp1, vs_1_1 - */ - virtual GpuProgramPtr createProgramFromString(const String& name, - const String& groupName, const String& code, - GpuProgramType gptype, const String& syntaxCode); - - /** General create method, using specific create parameters - instead of name / value pairs. - */ - GpuProgramPtr create(const String& name, const String& group, - GpuProgramType gptype, const String& language, bool isManual = false, - ManualResourceLoader* loader = 0); - - /** Create a new, unloaded GpuProgram. - @par - This method creates a new program of the type specified as the second and third parameters. - You will have to call further methods on the returned program in order to - define the program fully before you can load it. - @param name The identifying name of the program - @param groupName The name of the resource group which this program is - to be a member of - @param language Code of the language to use (e.g. "cg") - @param gptype The type of program to create - */ - GpuProgramPtr createProgram(const String& name, const String& groupName, const String& language, - GpuProgramType gptype) - { - return create(name, groupName, gptype, language); - } - - /** Create a new set of shared parameters, which can be used across many - GpuProgramParameters objects of different structures. - @param name The name to give the shared parameters so you can refer to them - later. - */ - virtual GpuSharedParametersPtr createSharedParameters(const String& name); - - /** Retrieve a set of shared parameters, which can be used across many - GpuProgramParameters objects of different structures. - */ - virtual GpuSharedParametersPtr getSharedParameters(const String& name) const; - - /** Get (const) access to the available shared parameter sets. - */ - virtual const SharedParametersMap& getAvailableSharedParameters() const; - - /** Get if the microcode of a shader should be saved to a cache - */ - bool getSaveMicrocodesToCache() const; - /** Set if the microcode of a shader should be saved to a cache - */ - void setSaveMicrocodesToCache( bool val ); - - /** Returns true if the microcodecache changed during the run. - */ - bool isCacheDirty(void) const; - - static bool canGetCompiledShaderBuffer(); - /** Check if a microcode is available for a program in the microcode cache. - @param id The id of the program. - */ - bool isMicrocodeAvailableInCache(uint32 id) const; - - /** Returns a microcode for a program from the microcode cache. - @param id The name of the program. - */ - const Microcode& getMicrocodeFromCache(uint32 id) const; - - /** Creates a microcode to be later added to the cache. - @param size The size of the microcode in bytes - */ - static Microcode createMicrocode(size_t size) { return std::make_shared(size); } - - /** Adds a microcode for a program to the microcode cache. - @param id The id of the program - @param microcode the program binary - */ - void addMicrocodeToCache(uint32 id, const Microcode& microcode); - - /** Removes a microcode for a program from the microcode cache. - @param id The name of the program. - */ - void removeMicrocodeFromCache(uint32 id); - - /** Saves the microcode cache to disk. - @param stream The destination stream - */ - void saveMicrocodeCache( const DataStreamPtr& stream ) const; - /** Loads the microcode cache from disk. - @param stream The source stream - */ - void loadMicrocodeCache( const DataStreamPtr& stream ); - - /** Add a new factory object for programs of a given language. */ - void addFactory(GpuProgramFactory* factory); - /** Remove a factory object for programs of a given language. */ - void removeFactory(GpuProgramFactory* factory); - - /// @copydoc Singleton::getSingleton() - static GpuProgramManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static GpuProgramManager* getSingletonPtr(void); - - - - }; - - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreGpuProgramParams.h b/OgreMain/include/OgreGpuProgramParams.h deleted file mode 100644 index dbcc126b108..00000000000 --- a/OgreMain/include/OgreGpuProgramParams.h +++ /dev/null @@ -1,1841 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#ifndef __GpuProgramParams_H_ -#define __GpuProgramParams_H_ - -#include - -// Precompiler options -#include "OgrePrerequisites.h" -#include "OgreSharedPtr.h" -#include "OgreSerializer.h" -#include "OgreAny.h" -#include "Threading/OgreThreadHeaders.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - struct TransformBaseReal; - template class ConstMapIterator; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Materials - * @{ - */ - - enum BaseConstantType - { - BCT_FLOAT = 0, - BCT_INT = 0x10, - BCT_DOUBLE = 0x20, - BCT_UINT = 0x30, - BCT_BOOL = 0x40, - BCT_SAMPLER = 0x50, - BCT_SPECIALIZATION = 0x60, //!< shader specialisation constant - BCT_UNKNOWN = 0x70 - }; - - /** Enumeration of the types of constant we may encounter in programs. - @note Low-level programs, by definition, will always use either - float4 or int4 constant types since that is the fundamental underlying - type in assembler. - */ - enum GpuConstantType - { - GCT_FLOAT1 = BCT_FLOAT + 1, - GCT_FLOAT2 = BCT_FLOAT + 2, - GCT_FLOAT3 = BCT_FLOAT + 3, - GCT_FLOAT4 = BCT_FLOAT + 4, - GCT_SAMPLER1D = BCT_SAMPLER + 1, - GCT_SAMPLER2D = BCT_SAMPLER + 2, - GCT_SAMPLER3D = BCT_SAMPLER + 3, - GCT_SAMPLERCUBE = BCT_SAMPLER + 4, - GCT_SAMPLER1DSHADOW = BCT_SAMPLER + 6, - GCT_SAMPLER2DSHADOW = BCT_SAMPLER + 7, - GCT_SAMPLER2DARRAY = BCT_SAMPLER + 8, - GCT_SAMPLER_EXTERNAL_OES = BCT_SAMPLER + 9, - GCT_MATRIX_2X2 = BCT_FLOAT + 5, - GCT_MATRIX_2X3 = BCT_FLOAT + 6, - GCT_MATRIX_2X4 = BCT_FLOAT + 7, - GCT_MATRIX_3X2 = BCT_FLOAT + 8, - GCT_MATRIX_3X3 = BCT_FLOAT + 9, - GCT_MATRIX_3X4 = BCT_FLOAT + 10, - GCT_MATRIX_4X2 = BCT_FLOAT + 11, - GCT_MATRIX_4X3 = BCT_FLOAT + 12, - GCT_MATRIX_4X4 = BCT_FLOAT + 13, - GCT_INT1 = BCT_INT + 1, - GCT_INT2 = BCT_INT + 2, - GCT_INT3 = BCT_INT + 3, - GCT_INT4 = BCT_INT + 4, - GCT_SPECIALIZATION = BCT_SPECIALIZATION, - GCT_DOUBLE1 = BCT_DOUBLE + 1, - GCT_DOUBLE2 = BCT_DOUBLE + 2, - GCT_DOUBLE3 = BCT_DOUBLE + 3, - GCT_DOUBLE4 = BCT_DOUBLE + 4, - GCT_MATRIX_DOUBLE_2X2 = BCT_DOUBLE + 5, - GCT_MATRIX_DOUBLE_2X3 = BCT_DOUBLE + 6, - GCT_MATRIX_DOUBLE_2X4 = BCT_DOUBLE + 7, - GCT_MATRIX_DOUBLE_3X2 = BCT_DOUBLE + 8, - GCT_MATRIX_DOUBLE_3X3 = BCT_DOUBLE + 9, - GCT_MATRIX_DOUBLE_3X4 = BCT_DOUBLE + 10, - GCT_MATRIX_DOUBLE_4X2 = BCT_DOUBLE + 11, - GCT_MATRIX_DOUBLE_4X3 = BCT_DOUBLE + 12, - GCT_MATRIX_DOUBLE_4X4 = BCT_DOUBLE + 13, - GCT_UINT1 = BCT_UINT + 1, - GCT_UINT2 = BCT_UINT + 2, - GCT_UINT3 = BCT_UINT + 3, - GCT_UINT4 = BCT_UINT + 4, - GCT_BOOL1 = BCT_BOOL + 1, - GCT_BOOL2 = BCT_BOOL + 2, - GCT_BOOL3 = BCT_BOOL + 3, - GCT_BOOL4 = BCT_BOOL + 4, - GCT_UNKNOWN = BCT_UNKNOWN - }; - - /** The variability of a GPU parameter, as derived from auto-params targeting it. - These values must be powers of two since they are used in masks. - */ - enum GpuParamVariability : uint16 - { - /// No variation except by manual setting - the default - GPV_GLOBAL = 1, - /// Varies per object (based on an auto param usually), but not per light setup - GPV_PER_OBJECT = 2, - /// Varies with light setup - GPV_LIGHTS = 4, - /// Varies with pass iteration number - GPV_PASS_ITERATION_NUMBER = 8, - - - /// Full mask (16-bit) - GPV_ALL = 0xFFFF - }; - - /** Information about predefined program constants. - @note Only available for high-level programs but is referenced generically - by GpuProgramParameters. - */ - struct _OgreExport GpuConstantDefinition - { - /// Physical byte offset in buffer - size_t physicalIndex; - /// Logical index - used to communicate this constant to the rendersystem - size_t logicalIndex; - /** Number of typed slots per element - (some programs pack each array element to float4, some do not) */ - uint32 elementSize; - /// Length of array - uint32 arraySize; - /// Data type - GpuConstantType constType; - /// How this parameter varies (bitwise combination of GpuProgramVariability) - mutable uint16 variability; - - //TODO Should offset be added to list? - // For instance, for GLSL atomic counters: - // layout(binding = 1, offset = 10) atomic_uint atom_counter; - // Binding goes in logicalIndex, but where does offset go? - //size_t offset; - - bool isFloat() const { return isFloat(constType); } - static bool isFloat(GpuConstantType c) { return getBaseType(c) == BCT_FLOAT; } - - bool isDouble() const { return isDouble(constType); } - static bool isDouble(GpuConstantType c) { return getBaseType(c) == BCT_DOUBLE; } - - bool isInt() const { return isInt(constType); } - static bool isInt(GpuConstantType c) { return getBaseType(c) == BCT_INT; } - - bool isUnsignedInt() const { return isUnsignedInt(constType); } - static bool isUnsignedInt(GpuConstantType c) { return getBaseType(c) == BCT_UINT; } - - bool isBool() const { return isBool(constType); } - static bool isBool(GpuConstantType c) { return getBaseType(c) == BCT_BOOL; } - - bool isSampler() const { return isSampler(constType); } - static bool isSampler(GpuConstantType c) { return getBaseType(c) == BCT_SAMPLER; } - - bool isSpecialization() const { return isSpecialization(constType); } - static bool isSpecialization(GpuConstantType c) { return getBaseType(c) == BCT_SPECIALIZATION; } - - static BaseConstantType getBaseType(GpuConstantType ctype) - { - return BaseConstantType(ctype / 0x10 * 0x10); - } - - /** Get the number of elements of a given type, including whether to pad the - elements into multiples of 4 (e.g. SM1 and D3D does, GLSL doesn't) - */ - static uint32 getElementSize(GpuConstantType ctype, bool padToMultiplesOf4) - { - if (padToMultiplesOf4) - { - switch(ctype) - { - case GCT_FLOAT1: - case GCT_INT1: - case GCT_UINT1: - case GCT_BOOL1: - case GCT_SAMPLER1D: - case GCT_SAMPLER2D: - case GCT_SAMPLER2DARRAY: - case GCT_SAMPLER3D: - case GCT_SAMPLERCUBE: - case GCT_SAMPLER1DSHADOW: - case GCT_SAMPLER2DSHADOW: - case GCT_FLOAT2: - case GCT_INT2: - case GCT_UINT2: - case GCT_BOOL2: - case GCT_FLOAT3: - case GCT_INT3: - case GCT_UINT3: - case GCT_BOOL3: - case GCT_FLOAT4: - case GCT_INT4: - case GCT_UINT4: - case GCT_BOOL4: - return 4; - case GCT_MATRIX_2X2: - case GCT_MATRIX_2X3: - case GCT_MATRIX_2X4: - case GCT_DOUBLE1: - case GCT_DOUBLE2: - case GCT_DOUBLE3: - case GCT_DOUBLE4: - return 8; // 2 float4s - case GCT_MATRIX_3X2: - case GCT_MATRIX_3X3: - case GCT_MATRIX_3X4: - return 12; // 3 float4s - case GCT_MATRIX_4X2: - case GCT_MATRIX_4X3: - case GCT_MATRIX_4X4: - case GCT_MATRIX_DOUBLE_2X2: - case GCT_MATRIX_DOUBLE_2X3: - case GCT_MATRIX_DOUBLE_2X4: - return 16; // 4 float4s - case GCT_MATRIX_DOUBLE_3X2: - case GCT_MATRIX_DOUBLE_3X3: - case GCT_MATRIX_DOUBLE_3X4: - return 24; - case GCT_MATRIX_DOUBLE_4X2: - case GCT_MATRIX_DOUBLE_4X3: - case GCT_MATRIX_DOUBLE_4X4: - return 32; - default: - return 4; - }; - } - else - { - switch(ctype) - { - case GCT_SAMPLER1D: - case GCT_SAMPLER2D: - case GCT_SAMPLER2DARRAY: - case GCT_SAMPLER3D: - case GCT_SAMPLERCUBE: - case GCT_SAMPLER1DSHADOW: - case GCT_SAMPLER2DSHADOW: - return 1; - case GCT_MATRIX_2X2: - case GCT_MATRIX_DOUBLE_2X2: - return 4; - case GCT_MATRIX_2X3: - case GCT_MATRIX_3X2: - case GCT_MATRIX_DOUBLE_2X3: - case GCT_MATRIX_DOUBLE_3X2: - return 6; - case GCT_MATRIX_2X4: - case GCT_MATRIX_4X2: - case GCT_MATRIX_DOUBLE_2X4: - case GCT_MATRIX_DOUBLE_4X2: - return 8; - case GCT_MATRIX_3X3: - case GCT_MATRIX_DOUBLE_3X3: - return 9; - case GCT_MATRIX_3X4: - case GCT_MATRIX_4X3: - case GCT_MATRIX_DOUBLE_3X4: - case GCT_MATRIX_DOUBLE_4X3: - return 12; - case GCT_MATRIX_4X4: - case GCT_MATRIX_DOUBLE_4X4: - return 16; - default: - return ctype % 0x10; - }; - - } - } - - GpuConstantDefinition() - : physicalIndex((std::numeric_limits::max)()) - , logicalIndex(0) - , elementSize(0) - , arraySize(1) - , constType(GCT_UNKNOWN) - , variability(GPV_GLOBAL) {} - }; - typedef std::map GpuConstantDefinitionMap; - typedef ConstMapIterator GpuConstantDefinitionIterator; - - /// Struct collecting together the information for named constants. - struct _OgreExport GpuNamedConstants : public GpuParamsAlloc - { - /// Total size of the buffer required - size_t bufferSize; - /// Number of register type params (samplers) - size_t registerCount; - /// Map of parameter names to GpuConstantDefinition - GpuConstantDefinitionMap map; - - GpuNamedConstants(); - ~GpuNamedConstants(); - - /** Saves constant definitions to a file - * compatible with @ref GpuProgram::setManualNamedConstantsFile. - */ - void save(const String& filename) const; - /** Loads constant definitions from a stream - * compatible with @ref GpuProgram::setManualNamedConstantsFile. - */ - void load(DataStreamPtr& stream); - - size_t calculateSize(void) const; - }; - - /// Simple class for loading / saving GpuNamedConstants - class _OgreExport GpuNamedConstantsSerializer : public Serializer - { - public: - GpuNamedConstantsSerializer(); - virtual ~GpuNamedConstantsSerializer(); - void exportNamedConstants(const GpuNamedConstants* pConsts, const String& filename, - Endian endianMode = ENDIAN_NATIVE); - void exportNamedConstants(const GpuNamedConstants* pConsts, DataStreamPtr stream, - Endian endianMode = ENDIAN_NATIVE); - void importNamedConstants(DataStreamPtr& stream, GpuNamedConstants* pDest); - }; - - /** Structure recording the use of a physical buffer by a logical parameter - index. Only used for low-level programs. - */ - struct _OgreExport GpuLogicalIndexUse - { - /// Physical buffer index - size_t physicalIndex; - /// Current physical size allocation - size_t currentSize; - /// How the contents of this slot vary - mutable uint16 variability; - /// Data type - BaseConstantType baseType; - - GpuLogicalIndexUse() - : physicalIndex(99999), currentSize(0), variability(GPV_GLOBAL), baseType(BCT_UNKNOWN) {} - GpuLogicalIndexUse(size_t bufIdx, size_t curSz, uint16 v, BaseConstantType t) - : physicalIndex(bufIdx), currentSize(curSz), variability(v), baseType(t) {} - }; - typedef std::map GpuLogicalIndexUseMap; - /// Container struct to allow params to safely & update shared list of logical buffer assignments - struct _OgreExport GpuLogicalBufferStruct : public GpuParamsAlloc - { - OGRE_MUTEX(mutex); - - /// Map from logical index to physical buffer location - GpuLogicalIndexUseMap map; - /// Shortcut to know the buffer size needs - size_t bufferSize; - GpuLogicalBufferStruct(); - ~GpuLogicalBufferStruct(); - }; - - /** Definition of container that holds the current constants. - @note Not necessarily in direct index order to constant indexes, logical - to physical index map is derived from GpuProgram - */ - typedef std::vector ConstantList; - - /** A group of manually updated parameters that are shared between many parameter sets. - - Sometimes you want to set some common parameters across many otherwise - different parameter sets, and keep them all in sync together. This class - allows you to define a set of parameters that you can share across many - parameter sets and have the parameters that match automatically be pulled - from the shared set, rather than you having to set them on all the parameter - sets individually. - @par - Parameters in a shared set are matched up with instances in a GpuProgramParameters - structure by matching names. It is up to you to define the named parameters - that a shared set contains, and ensuring the definition matches. - @note - Shared parameter sets can be named, and looked up using the GpuProgramManager. - */ - class _OgreExport GpuSharedParameters : public GpuParamsAlloc - { - /// Name of the shared parameter set. - String mName; - - /// Shared parameter definitions and related data. - GpuNamedConstants mNamedConstants; - - /// List of constant values. - ConstantList mConstants; - - /// Optional rendersystem backed storage - HardwareBufferPtr mHardwareBuffer; - - /// Version number of the definitions in this buffer. - uint32 mVersion; - - /// Accumulated offset used to calculate uniform location. - size_t mOffset; - - bool mDirty; - - template void _setNamedConstant(const String& name, const T* val, uint32 count); - public: - GpuSharedParameters(const String& name); - - /// Get the name of this shared parameter set. - const String& getName() { return mName; } - - /** Add a new constant definition to this shared set of parameters. - - Unlike GpuProgramParameters, where the parameter list is defined by the - program being compiled, this shared parameter set is defined by the - user. Only parameters which have been predefined here may be later - updated. - */ - void addConstantDefinition(const String& name, GpuConstantType constType, uint32 arraySize = 1); - - /// @deprecated removing a constant requires a full rebuild due to changed alignments - OGRE_DEPRECATED void removeConstantDefinition(const String& name); - - /** Remove a constant definition from this shared set of parameters. - */ - void removeAllConstantDefinitions(); - - /** Get the version number of this shared parameter set, can be used to identify when - changes have occurred. - */ - uint32 getVersion() const { return mVersion; } - - /** Calculate the expected size of the shared parameter buffer based - on constant definition data types. - */ - size_t calculateSize(void) const; - - /** True if this parameter set is dirty (values have been modified, - but the render system has not updated them yet). - */ - bool isDirty() const { return mDirty; } - - /** Mark the shared set as being clean (values successfully updated - by the render system). - - You do not need to call this yourself. The set is marked as clean - whenever the render system updates dirty shared parameters. - */ - void _markClean(); - - /** Mark the shared set as being dirty (values modified and not yet - updated in render system). - - You do not need to call this yourself. The set is marked as - dirty whenever setNamedConstant or (non const) getFloatPointer - et al are called. - */ - void _markDirty(); - - /// @deprecated use getConstantDefinitions() - OGRE_DEPRECATED GpuConstantDefinitionIterator getConstantDefinitionIterator(void) const; - - /** Get a specific GpuConstantDefinition for a named parameter. - */ - const GpuConstantDefinition& getConstantDefinition(const String& name) const; - - /** Get the full list of GpuConstantDefinition instances. - */ - const GpuNamedConstants& getConstantDefinitions() const; - - /** @copydoc GpuProgramParameters::setNamedConstant(const String&, Real) */ - template void setNamedConstant(const String& name, T val) - { - setNamedConstant(name, &val, 1); - } - /// @overload - template - void setNamedConstant(const String& name, const Vector& vec) - { - setNamedConstant(name, vec.ptr(), dims); - } - /** @copydoc GpuProgramParameters::setNamedConstant(const String& name, const Matrix4& m) */ - void setNamedConstant(const String& name, const Matrix4& m); - /** @copydoc GpuProgramParameters::setNamedConstant(const String& name, const Matrix4* m, size_t numEntries) */ - void setNamedConstant(const String& name, const Matrix4* m, uint32 numEntries); - void setNamedConstant(const String& name, const float *val, uint32 count); - void setNamedConstant(const String& name, const double *val, uint32 count); - /** @copydoc GpuProgramParameters::setNamedConstant(const String& name, const ColourValue& colour) */ - void setNamedConstant(const String& name, const ColourValue& colour); - void setNamedConstant(const String& name, const int *val, uint32 count); - void setNamedConstant(const String& name, const uint *val, uint32 count); - /// Get a pointer to the 'nth' item in the float buffer - float* getFloatPointer(size_t pos) { _markDirty(); return (float*)&mConstants[pos]; } - /// Get a pointer to the 'nth' item in the float buffer - const float* getFloatPointer(size_t pos) const { return (const float*)&mConstants[pos]; } - /// Get a pointer to the 'nth' item in the double buffer - double* getDoublePointer(size_t pos) { _markDirty(); return (double*)&mConstants[pos]; } - /// Get a pointer to the 'nth' item in the double buffer - const double* getDoublePointer(size_t pos) const { return (const double*)&mConstants[pos]; } - /// Get a pointer to the 'nth' item in the int buffer - int* getIntPointer(size_t pos) { _markDirty(); return (int*)&mConstants[pos]; } - /// Get a pointer to the 'nth' item in the int buffer - const int* getIntPointer(size_t pos) const { return (const int*)&mConstants[pos]; } - /// Get a pointer to the 'nth' item in the uint buffer - uint* getUnsignedIntPointer(size_t pos) { _markDirty(); return (uint*)&mConstants[pos]; } - /// Get a pointer to the 'nth' item in the uint buffer - const uint* getUnsignedIntPointer(size_t pos) const { return (const uint*)&mConstants[pos]; } - /// Get a reference to the list of constants - const ConstantList& getConstantList() const { return mConstants; } - /** Internal method that the RenderSystem might use to store optional data. */ - void _setHardwareBuffer(const HardwareBufferPtr& data) { mHardwareBuffer = data; } - /** Internal method that the RenderSystem might use to store optional data. */ - const HardwareBufferPtr& _getHardwareBuffer() const { return mHardwareBuffer; } - /// upload parameter data to GPU memory. Must have a HardwareBuffer - void _upload() const; - /// download data from GPU memory. Must have a writable HardwareBuffer - void download(); - }; - - class GpuProgramParameters; - - /** This class records the usage of a set of shared parameters in a concrete - set of GpuProgramParameters. - */ - class _OgreExport GpuSharedParametersUsage : public GpuParamsAlloc - { - private: - GpuSharedParametersPtr mSharedParams; - // Not a shared pointer since this is also parent - GpuProgramParameters* mParams; - // list of physical mappings that we are going to bring in - struct CopyDataEntry - { - const GpuConstantDefinition* srcDefinition; - const GpuConstantDefinition* dstDefinition; - }; - typedef std::vector CopyDataList; - - CopyDataList mCopyDataList; - - /// Version of shared params we based the copydata on - uint32 mCopyDataVersion; - - void initCopyData(); - - - public: - /// Construct usage - GpuSharedParametersUsage(GpuSharedParametersPtr sharedParams, - GpuProgramParameters* params); - - /** Update the target parameters by copying the data from the shared - parameters. - @note This method may not actually be called if the RenderSystem - supports using shared parameters directly in their own shared buffer; in - which case the values should not be copied out of the shared area - into the individual parameter set, but bound separately. - */ - void _copySharedParamsToTargetParams() const; - - /// Get the name of the shared parameter set - const String& getName() const { return mSharedParams->getName(); } - - GpuSharedParametersPtr getSharedParams() const { return mSharedParams; } - GpuProgramParameters* getTargetParams() const { return mParams; } - }; - - /** Collects together the program parameters used for a GpuProgram. - - Gpu program state includes constant parameters used by the program, and - bindings to render system state which is propagated into the constants - by the engine automatically if requested. - @par - GpuProgramParameters objects should be created through the GpuProgram and - may be shared between multiple Pass instances. For this reason they - are managed using a shared pointer, which will ensure they are automatically - deleted when no Pass is using them anymore. - @par - High-level programs use named parameters (uniforms), low-level programs - use indexed constants. This class supports both, but you can tell whether - named constants are supported by calling hasNamedParameters(). There are - references in the documentation below to 'logical' and 'physical' indexes; - logical indexes are the indexes used by low-level programs and represent - indexes into an array of float4's, some of which may be settable, some of - which may be predefined constants in the program. We only store those - constants which have actually been set, therefore our buffer could have - gaps if we used the logical indexes in our own buffers. So instead we map - these logical indexes to physical indexes in our buffer. When using - high-level programs, logical indexes don't necessarily exist, although they - might if the high-level program has a direct, exposed mapping from parameter - names to logical indexes. In addition, high-level languages may or may not pack - arrays of elements that are smaller than float4 (e.g. float2/vec2) contiguously. - This kind of information is held in the ConstantDefinition structure which - is only populated for high-level programs. You don't have to worry about - any of this unless you intend to read parameters back from this structure - rather than just setting them. - */ - class _OgreExport GpuProgramParameters : public GpuParamsAlloc - { - public: - /** Defines the types of automatically updated values that may be bound to GpuProgram - parameters, or used to modify parameters on a per-object basis. - - For use in @ref Program-Parameter-Specification, drop the `ACT_` prefix. - E.g. `ACT_WORLD_MATRIX` becomes `world_matrix`. - */ - enum AutoConstantType - { - /// The current world matrix - ACT_WORLD_MATRIX, - /// The current world matrix, inverted - ACT_INVERSE_WORLD_MATRIX, - /** Provides transpose of world matrix. - */ - ACT_TRANSPOSE_WORLD_MATRIX, - /// The current world matrix, inverted & transposed - ACT_INVERSE_TRANSPOSE_WORLD_MATRIX, - - /// An array of bone matrices, each represented as only a 3x4 matrix (3 rows of - /// 4columns) usually for doing hardware skinning. - /// You should make enough entries available in your vertex program for the number of - /// bones in use, i.e. an array of numBones*3 float4’s. - ACT_BONE_MATRIX_ARRAY_3x4, - ACT_WORLD_MATRIX_ARRAY_3x4 = ACT_BONE_MATRIX_ARRAY_3x4, - /// The current array of bone matrices, used for blending - ACT_BONE_MATRIX_ARRAY, - ACT_WORLD_MATRIX_ARRAY = ACT_BONE_MATRIX_ARRAY, - /// The current array of bone matrices transformed to an array of dual quaternions, - /// represented as a 2x4 matrix - ACT_BONE_DUALQUATERNION_ARRAY_2x4, - ACT_WORLD_DUALQUATERNION_ARRAY_2x4 = ACT_BONE_DUALQUATERNION_ARRAY_2x4, - /// The scale and shear components of the current array of bone matrices - ACT_BONE_SCALE_SHEAR_MATRIX_ARRAY_3x4, - ACT_WORLD_SCALE_SHEAR_MATRIX_ARRAY_3x4 = ACT_BONE_SCALE_SHEAR_MATRIX_ARRAY_3x4, - - /// The current view matrix - ACT_VIEW_MATRIX, - /// The current view matrix, inverted - ACT_INVERSE_VIEW_MATRIX, - /** Provides transpose of view matrix. - */ - ACT_TRANSPOSE_VIEW_MATRIX, - /** Provides inverse transpose of view matrix. - */ - ACT_INVERSE_TRANSPOSE_VIEW_MATRIX, - - /// The current projection matrix - ACT_PROJECTION_MATRIX, - /** Provides inverse of projection matrix. - */ - ACT_INVERSE_PROJECTION_MATRIX, - /** Provides transpose of projection matrix. - */ - ACT_TRANSPOSE_PROJECTION_MATRIX, - /** Provides inverse transpose of projection matrix. - */ - ACT_INVERSE_TRANSPOSE_PROJECTION_MATRIX, - - /// The current view & projection matrices concatenated - ACT_VIEWPROJ_MATRIX, - /** Provides inverse of concatenated view and projection matrices. - */ - ACT_INVERSE_VIEWPROJ_MATRIX, - /** Provides transpose of concatenated view and projection matrices. - */ - ACT_TRANSPOSE_VIEWPROJ_MATRIX, - /** Provides inverse transpose of concatenated view and projection matrices. - */ - ACT_INVERSE_TRANSPOSE_VIEWPROJ_MATRIX, - - /// The current world & view matrices concatenated - ACT_WORLDVIEW_MATRIX, - /// The current world & view matrices concatenated, then inverted - ACT_INVERSE_WORLDVIEW_MATRIX, - /** Provides transpose of concatenated world and view matrices. - */ - ACT_TRANSPOSE_WORLDVIEW_MATRIX, - /// The current world & view matrices concatenated, then inverted & transposed - ACT_INVERSE_TRANSPOSE_WORLDVIEW_MATRIX, - /** Provides inverse transpose of the upper 3x3 of the worldview matrix. - Equivalent to @c gl_NormalMatrix. - */ - ACT_NORMAL_MATRIX, - - /// The current world, view & projection matrices concatenated - ACT_WORLDVIEWPROJ_MATRIX, - /** Provides inverse of concatenated world, view and projection matrices. - */ - ACT_INVERSE_WORLDVIEWPROJ_MATRIX, - /** Provides transpose of concatenated world, view and projection matrices. - */ - ACT_TRANSPOSE_WORLDVIEWPROJ_MATRIX, - /** Provides inverse transpose of concatenated world, view and projection - matrices. - */ - ACT_INVERSE_TRANSPOSE_WORLDVIEWPROJ_MATRIX, - - // render target related values - /** -1 if requires texture flipping, +1 otherwise. It's useful when you bypassed - projection matrix transform, still able use this value to adjust transformed y - position. - */ - ACT_RENDER_TARGET_FLIPPING, - - /** -1 if the winding has been inverted, +1 otherwise. - * e.g. for reflections - */ - ACT_VERTEX_WINDING, - - /// Fog colour - ACT_FOG_COLOUR, - /// Fog params: `(density, linear start, linear end, 1/(end-start))` - ACT_FOG_PARAMS, - - /// Surface ambient colour, as set in Pass::setAmbient - ACT_SURFACE_AMBIENT_COLOUR, - /// Surface diffuse colour, as set in Pass::setDiffuse - ACT_SURFACE_DIFFUSE_COLOUR, - /// Surface specular colour, as set in Pass::setSpecular - ACT_SURFACE_SPECULAR_COLOUR, - /// Surface emissive colour, as set in Pass::setSelfIllumination - ACT_SURFACE_EMISSIVE_COLOUR, - /// Surface shininess, as set in Pass::setShininess - ACT_SURFACE_SHININESS, - /// Surface alpha rejection value, not as set in @ref Pass::setAlphaRejectValue, but a - /// floating number between 0.0f and 1.0f instead (255.0f / - /// @ref Pass::getAlphaRejectValue()) - ACT_SURFACE_ALPHA_REJECTION_VALUE, - - /// The number of active light sources - ACT_LIGHT_COUNT, - - /// The ambient light colour set in the scene - ACT_AMBIENT_LIGHT_COLOUR, - - /// Light diffuse colour (index determined by setAutoConstant call). - /// this requires an index in the ’extra_params’ field, and relates to the ’nth’ closest - /// light which could affect this object - /// (i.e. 0 refers to the closest light - note that directional lights are always first - /// in the list and always present). - /// NB if there are no lights this close, then the parameter will be set to black. - ACT_LIGHT_DIFFUSE_COLOUR, - /// Light specular colour (index determined by setAutoConstant call) - ACT_LIGHT_SPECULAR_COLOUR, - /** Light attenuation parameters. - * Packed as `(range, constant, linear, quadric)`. - * For area lights this contains the height half-vector `(x, y, z, 0)` of the light in viewspace. - */ - ACT_LIGHT_ATTENUATION, - /** Spotlight parameters. - Packed as `(innerFactor, outerFactor, falloff, spotType)` - innerFactor and outerFactor are cos(angle/2) - The spotType parameter is 0.0f for non-spotlights, 1.0f for spotlights and 2.0f for - area spotlights. - For area lights this contains the width half-vector `(x, y, z, 2)` of the light in viewspace. - Also for non-spotlights the inner and outer factors are 1 and 0 respectively - */ - ACT_SPOTLIGHT_PARAMS, - /** A light position in world space (index determined by setAutoConstant call). - This requires an index in the ’extra_params’ field, and relates to the ’nth’ closest - light which could affect this object (i.e. 0 refers to the closest light). - NB if there are no lights this close, then the parameter will be set to all zeroes. - Note that this property will work with all kinds of lights, even directional lights, - since the parameter is set as a 4D vector. - Point lights will be `(pos.x, pos.y, pos.z, 1.0f)` whilst directional lights will be - `(-dir.x, -dir.y, -dir.z, 0.0f)`. - Operations like dot products will work consistently on both. - */ - ACT_LIGHT_POSITION, - /// A light position in object space (index determined by setAutoConstant call) - ACT_LIGHT_POSITION_OBJECT_SPACE, - /// A light position in view space (index determined by setAutoConstant call) - ACT_LIGHT_POSITION_VIEW_SPACE, - /// A light direction in world space (index determined by setAutoConstant call) - /// @deprecated this property only works on directional lights, and we recommend that - /// you use light_position instead since that returns a generic 4D vector. - ACT_LIGHT_DIRECTION, - /// A light direction in object space (index determined by setAutoConstant call) - ACT_LIGHT_DIRECTION_OBJECT_SPACE, - /// A light direction in view space (index determined by setAutoConstant call) - ACT_LIGHT_DIRECTION_VIEW_SPACE, - /** The distance of the light from the center of the object - a useful approximation as an alternative to per-vertex distance - calculations. - */ - ACT_LIGHT_DISTANCE_OBJECT_SPACE, - /** Light power level, a single scalar as set in Light::setPowerScale (index determined - by setAutoConstant call) */ - ACT_LIGHT_POWER_SCALE, - /// Light diffuse colour pre-scaled by Light::setPowerScale (index determined by - /// setAutoConstant call) - ACT_LIGHT_DIFFUSE_COLOUR_POWER_SCALED, - /// Light specular colour pre-scaled by Light::setPowerScale (index determined by - /// setAutoConstant call) - ACT_LIGHT_SPECULAR_COLOUR_POWER_SCALED, - /// Array of light diffuse colours (count set by extra param) - ACT_LIGHT_DIFFUSE_COLOUR_ARRAY, - /// Array of light specular colours (count set by extra param) - ACT_LIGHT_SPECULAR_COLOUR_ARRAY, - /// Array of light diffuse colours scaled by light power (count set by extra param) - ACT_LIGHT_DIFFUSE_COLOUR_POWER_SCALED_ARRAY, - /// Array of light specular colours scaled by light power (count set by extra param) - ACT_LIGHT_SPECULAR_COLOUR_POWER_SCALED_ARRAY, - /// Array of light attenuation parameters. - /// @copydetails #ACT_LIGHT_ATTENUATION (count set by extra param) - ACT_LIGHT_ATTENUATION_ARRAY, - /// Array of light positions in world space (count set by extra param) - ACT_LIGHT_POSITION_ARRAY, - /// Array of light positions in object space (count set by extra param) - ACT_LIGHT_POSITION_OBJECT_SPACE_ARRAY, - /// Array of light positions in view space (count set by extra param) - ACT_LIGHT_POSITION_VIEW_SPACE_ARRAY, - /// Array of light directions in world space (count set by extra param) - ACT_LIGHT_DIRECTION_ARRAY, - /// Array of light directions in object space (count set by extra param) - ACT_LIGHT_DIRECTION_OBJECT_SPACE_ARRAY, - /// Array of light directions in view space (count set by extra param) - ACT_LIGHT_DIRECTION_VIEW_SPACE_ARRAY, - /** Array of distances of the lights from the center of the object - a useful approximation as an alternative to per-vertex distance - calculations. (count set by extra param) - */ - ACT_LIGHT_DISTANCE_OBJECT_SPACE_ARRAY, - /** Array of light power levels, a single scalar as set in Light::setPowerScale - (count set by extra param) - */ - ACT_LIGHT_POWER_SCALE_ARRAY, - /** Spotlight parameters array - * @copydetails #ACT_SPOTLIGHT_PARAMS - * (count set by extra param) - */ - ACT_SPOTLIGHT_PARAMS_ARRAY, - - /** The derived ambient light colour, with 'r', 'g', 'b' components filled with - product of surface ambient colour and ambient light colour, respectively, - and 'a' component filled with surface diffuse alpha component. - */ - ACT_DERIVED_AMBIENT_LIGHT_COLOUR, - /** The derived scene colour, with 'r', 'g' and 'b' components filled with sum - of derived ambient light colour and surface emissive colour, respectively, - and 'a' component filled with surface diffuse alpha component. - */ - ACT_DERIVED_SCENE_COLOUR, - - /** The derived light diffuse colour (index determined by setAutoConstant call), - with 'r', 'g' and 'b' components filled with product of surface diffuse colour, - light power scale and light diffuse colour, respectively, and 'a' component filled - with surface - diffuse alpha component. - */ - ACT_DERIVED_LIGHT_DIFFUSE_COLOUR, - /** The derived light specular colour (index determined by setAutoConstant call), - with 'r', 'g' and 'b' components filled with product of surface specular colour - and light specular colour, respectively, and 'a' component filled with surface - specular alpha component. - */ - ACT_DERIVED_LIGHT_SPECULAR_COLOUR, - - /// Array of derived light diffuse colours (count set by extra param) - ACT_DERIVED_LIGHT_DIFFUSE_COLOUR_ARRAY, - /// Array of derived light specular colours (count set by extra param) - ACT_DERIVED_LIGHT_SPECULAR_COLOUR_ARRAY, - /** The absolute light number of a local light index. Each pass may have - a number of lights passed to it, and each of these lights will have - an index in the overall light list, which will differ from the local - light index due to factors like setStartLight and setIteratePerLight. - This binding provides the global light index for a local index. - */ - ACT_LIGHT_NUMBER, - /// Returns (int) 1 if the given light casts shadows, 0 otherwise (index set in extra - /// param) - ACT_LIGHT_CASTS_SHADOWS, - /// Returns (int) 1 if the given light casts shadows, 0 otherwise (index set in extra - /// param) - ACT_LIGHT_CASTS_SHADOWS_ARRAY, - - /** The distance a shadow volume should be extruded when using - finite extrusion programs. - */ - ACT_SHADOW_EXTRUSION_DISTANCE, - /// The current camera's position in world space - ACT_CAMERA_POSITION, - /// The current camera's position in object space - ACT_CAMERA_POSITION_OBJECT_SPACE, - /// The current camera's position in world space even when camera relative rendering is enabled - ACT_CAMERA_RELATIVE_POSITION, - - /** The view/projection matrix of the assigned texture projection frustum. - Applicable to vertex programs which have been specified as the ’shadow receiver’ vertex - program alternative, or where a texture unit is marked as content_type shadow; this - provides details of the view/projection matrix for the current shadow projector. The - optional ’extra_params’ entry specifies which light the projector refers to (for the - case of content_type shadow where more than one shadow texture may be present in a - single pass), where 0 is the default and refers to the first light referenced in this - pass. - */ - ACT_TEXTURE_VIEWPROJ_MATRIX, - /// Array of view/projection matrices of the first n texture projection frustums - ACT_TEXTURE_VIEWPROJ_MATRIX_ARRAY, - /** The view/projection matrix of the assigned texture projection frustum, - combined with the current world matrix - */ - ACT_TEXTURE_WORLDVIEWPROJ_MATRIX, - /// Array of world/view/projection matrices of the first n texture projection frustums - ACT_TEXTURE_WORLDVIEWPROJ_MATRIX_ARRAY, - /// The view/projection matrix of a given spotlight - ACT_SPOTLIGHT_VIEWPROJ_MATRIX, - /// Array of view/projection matrix of a given spotlight - ACT_SPOTLIGHT_VIEWPROJ_MATRIX_ARRAY, - /** The view/projection matrix of a given spotlight projection frustum, - combined with the current world matrix - */ - ACT_SPOTLIGHT_WORLDVIEWPROJ_MATRIX, - /** An array of the view/projection matrix of a given spotlight projection frustum, - combined with the current world matrix - */ - ACT_SPOTLIGHT_WORLDVIEWPROJ_MATRIX_ARRAY, - /** A custom parameter which will come from the renderable, using 'data' as the - identifier - - This allows you to map a custom parameter on an individual Renderable (see - Renderable::setCustomParameter) to a parameter on a GPU program. It requires that you - complete the ’extra_params’ field with the index that was used in the - Renderable::setCustomParameter call, and this will ensure that whenever this Renderable - is used, it will have it’s custom parameter mapped in. It’s very important that this - parameter has been defined on all Renderables that are assigned the material that - contains this automatic mapping, otherwise the process will fail. - */ - ACT_CUSTOM, - /** provides current elapsed time - */ - ACT_TIME, - /** Single float value, which repeats itself based on given as - parameter "cycle time". - */ - ACT_TIME_0_X, - /// Cosine of "Time0_X". - ACT_COSTIME_0_X, - /// Sine of "Time0_X". - ACT_SINTIME_0_X, - /// Tangent of "Time0_X". - ACT_TANTIME_0_X, - /** Vector of "Time0_X", "SinTime0_X", "CosTime0_X", - "TanTime0_X". - */ - ACT_TIME_0_X_PACKED, - /** Single float value, which represents scaled time value [0..1], - which repeats itself based on given as parameter "cycle time". - */ - ACT_TIME_0_1, - /// Cosine of "Time0_1". - ACT_COSTIME_0_1, - /// Sine of "Time0_1". - ACT_SINTIME_0_1, - /// Tangent of "Time0_1". - ACT_TANTIME_0_1, - /** Vector of "Time0_1", "SinTime0_1", "CosTime0_1", - "TanTime0_1". - */ - ACT_TIME_0_1_PACKED, - /** Single float value, which represents scaled time value [0..2*Pi], - which repeats itself based on given as parameter "cycle time". - */ - ACT_TIME_0_2PI, - /// Cosine of "Time0_2PI". - ACT_COSTIME_0_2PI, - /// Sine of "Time0_2PI". - ACT_SINTIME_0_2PI, - /// Tangent of "Time0_2PI". - ACT_TANTIME_0_2PI, - /** Vector of "Time0_2PI", "SinTime0_2PI", "CosTime0_2PI", - "TanTime0_2PI". - */ - ACT_TIME_0_2PI_PACKED, - /// provides the scaled frame time, returned as a floating point value. - ACT_FRAME_TIME, - /// provides the calculated frames per second, returned as a floating point value. - ACT_FPS, - // viewport-related values - /** Current viewport width (in pixels) as floating point value. - */ - ACT_VIEWPORT_WIDTH, - /** Current viewport height (in pixels) as floating point value. - */ - ACT_VIEWPORT_HEIGHT, - /** This variable represents `1/ViewportWidth`. - */ - ACT_INVERSE_VIEWPORT_WIDTH, - /** This variable represents `1/ViewportHeight`. - */ - ACT_INVERSE_VIEWPORT_HEIGHT, - /** Viewport dimensions. - Packed as `(ViewportWidth, ViewportHeight, 1/ViewportWidth, 1/ViewportHeight)` - */ - ACT_VIEWPORT_SIZE, - - // view parameters - /** This variable provides the view direction vector (world space). - */ - ACT_VIEW_DIRECTION, - /** This variable provides the view side vector (world space). - */ - ACT_VIEW_SIDE_VECTOR, - /** This variable provides the view up vector (world space). - */ - ACT_VIEW_UP_VECTOR, - /** This variable provides the field of view as a floating point value. - */ - ACT_FOV, - /** This variable provides the near clip distance as a floating point value. - */ - ACT_NEAR_CLIP_DISTANCE, - /** This variable provides the far clip distance as a floating point value. - */ - ACT_FAR_CLIP_DISTANCE, - - /** provides the pass index number within the technique - of the active material. - */ - ACT_PASS_NUMBER, - - /** provides the current iteration number of the pass. The iteration - number is the number of times the current render operation has - been drawn for the active pass. - */ - ACT_PASS_ITERATION_NUMBER, - - /** Provides a parametric animation value [0..1], only available - where the renderable specifically implements it. - - For morph animation, sets the parametric value - (0..1) representing the distance between the first position keyframe (bound to - positions) and the second position keyframe (bound to the first free texture - coordinate) so that the vertex program can interpolate between them. For pose - animation, indicates a group of up to 4 parametric weight values applying to a - sequence of up to 4 poses (each one bound to x, y, z and w of the constant), one for - each pose. The original positions are held in the usual position buffer, and the - offsets to take those positions to the pose where weight == 1.0 are in the first ’n’ - free texture coordinates; ’n’ being determined by the value passed to - includes_pose_animation. If more than 4 simultaneous poses are required, then you’ll - need more than 1 shader constant to hold the parametric values, in which case you - should use this binding more than once, referencing a different constant entry; the - second one will contain the parametrics for poses 5-8, the third for poses 9-12, and - so on. - */ - ACT_ANIMATION_PARAMETRIC, - - /** Provides the texel offsets required by this rendersystem to map - texels to pixels. Packed as - `(absoluteHorizontalOffset, absoluteVerticalOffset, horizontalOffset / viewportWidth, verticalOffset / viewportHeight)` - */ - ACT_TEXEL_OFFSETS, - - /** Provides information about the depth range of the scene as viewed - from the current camera. - Passed as `(minDepth, maxDepth, depthRange, 1 / depthRange)` - */ - ACT_SCENE_DEPTH_RANGE, - - /** Provides information about the depth range of the scene as viewed - from a given shadow camera. Requires an index parameter which maps - to a light index relative to the current light list. - Passed as `(minDepth, maxDepth, depthRange, 1 / depthRange)` - */ - ACT_SHADOW_SCENE_DEPTH_RANGE, - - /** Provides an array of information about the depth range of the scene as viewed - from a given shadow camera. Requires an index parameter which maps - to a light index relative to the current light list. - Passed as `(minDepth, maxDepth, depthRange, 1 / depthRange)` - */ - ACT_SHADOW_SCENE_DEPTH_RANGE_ARRAY, - - /** Provides the fixed shadow colour as configured via SceneManager::setShadowColour; - useful for integrated modulative shadows. - */ - ACT_SHADOW_COLOUR, - /** Provides texture size of the texture unit (index determined by setAutoConstant - call). Packed as `(width, height, depth, numMipMaps)` - */ - ACT_TEXTURE_SIZE, - /** Provides inverse texture size of the texture unit (index determined by - setAutoConstant - call). Packed as `(1 / width, 1 / height, 1 / depth, 1 / numMipMaps)` - */ - ACT_INVERSE_TEXTURE_SIZE, - /** Provides packed texture size of the texture unit (index determined by - setAutoConstant - call). Packed as `(width, height, 1 / width, 1 / height)` - */ - ACT_PACKED_TEXTURE_SIZE, - - /** Provides the current transform matrix of the texture unit (index determined by - setAutoConstant - call), as seen by the fixed-function pipeline. - - This requires an index in the ’extra_params’ field, and relates to the ’nth’ texture - unit of the pass in question. - NB if the given index exceeds the number of texture units available for this pass, - then the parameter will be set to Matrix4::IDENTITY. - */ - ACT_TEXTURE_MATRIX, - - /** Provides the position of the LOD camera in world space, allowing you - to perform separate LOD calculations in shaders independent of the rendering - camera. If there is no separate LOD camera then this is the real camera - position. See Camera::setLodCamera. - */ - ACT_LOD_CAMERA_POSITION, - /** Provides the position of the LOD camera in object space, allowing you - to perform separate LOD calculations in shaders independent of the rendering - camera. If there is no separate LOD camera then this is the real camera - position. See Camera::setLodCamera. - */ - ACT_LOD_CAMERA_POSITION_OBJECT_SPACE, - /** Binds custom per-light constants to the shaders. */ - ACT_LIGHT_CUSTOM, - /// Point attenuation params. - /// Packed as `(size, constant, linear, quadratic)` - ACT_POINT_PARAMS, - /// the LOD index as selected by the active LodStrategy - ACT_MATERIAL_LOD_INDEX, - }; - - /** Defines the type of the extra data item used by the auto constant. - - */ - enum ACDataType { - /// no data is required - ACDT_NONE, - /// the auto constant requires data of type int - ACDT_INT, - /// the auto constant requires data of type float - ACDT_REAL - }; - - /** Defines the base element type of the auto constant - */ - enum ElementType { - ET_INT = BCT_INT, - // float - ET_REAL = BCT_FLOAT - }; - - /** Structure defining an auto constant that's available for use in - a parameters object. - */ - struct AutoConstantDefinition - { - AutoConstantType acType; - String name; - size_t elementCount; - /// The type of the constant in the program - ElementType elementType; - /// The type of any extra data - ACDataType dataType; - - AutoConstantDefinition(AutoConstantType _acType, const String& _name, - size_t _elementCount, ElementType _elementType, - ACDataType _dataType) - :acType(_acType), name(_name), elementCount(_elementCount), - elementType(_elementType), dataType(_dataType) - { - - } - }; - - /** Structure recording the use of an automatic parameter. */ - class AutoConstantEntry - { - public: - /// The target (physical) constant index - size_t physicalIndex; - /// The type of parameter - AutoConstantType paramType; - /// Additional information to go with the parameter - union{ - uint32 data; - float fData; - }; - /// The variability of this parameter (see GpuParamVariability) - uint16 variability; - /** The number of elements per individual entry in this constant - Used in case people used packed elements smaller than 4 (e.g. GLSL) - and bind an auto which is 4-element packed to it */ - uint8 elementCount; - - AutoConstantEntry(AutoConstantType theType, size_t theIndex, uint32 theData, - uint16 theVariability, uint8 theElemCount = 4) - : physicalIndex(theIndex), paramType(theType), - data(theData), variability(theVariability), elementCount(theElemCount) {} - - AutoConstantEntry(AutoConstantType theType, size_t theIndex, float theData, - uint16 theVariability, uint8 theElemCount = 4) - : physicalIndex(theIndex), paramType(theType), - fData(theData), variability(theVariability), elementCount(theElemCount) {} - - }; - // Auto parameter storage - typedef std::vector AutoConstantList; - - typedef std::vector GpuSharedParamUsageList; - private: - static AutoConstantDefinition AutoConstantDictionary[]; - - /// Packed list of constants (physical indexing) - ConstantList mConstants; - - /// Sampler handles (logical indexing) - std::vector mRegisters; - - /** Logical index to physical index map - for low-level programs - or high-level programs which pass params this way. */ - GpuLogicalBufferStructPtr mLogicalToPhysical; - - /** Gets the physical buffer index associated with a logical int constant index. - */ - GpuLogicalIndexUse* getConstantLogicalIndexUse(size_t logicalIndex, size_t requestedSize, - uint16 variability, BaseConstantType type); - - /// Mapping from parameter names to def - high-level programs are expected to populate this - GpuNamedConstantsPtr mNamedConstants; - /// List of automatically updated parameters - AutoConstantList mAutoConstants; - /// The combined variability masks of all parameters - uint16 mCombinedVariability; - /// Do we need to transpose matrices? - bool mTransposeMatrices; - /// flag to indicate if names not found will be ignored - bool mIgnoreMissingParams; - /// physical index for active pass iteration parameter real constant entry; - size_t mActivePassIterationIndex; - - /// Return the variability for an auto constant - static uint16 deriveVariability(AutoConstantType act); - - void copySharedParamSetUsage(const GpuSharedParamUsageList& srcList); - - GpuSharedParamUsageList mSharedParamSets; - - template void _setNamedConstant(const String& name, const T* val, size_t count); - - public: - GpuProgramParameters(); - ~GpuProgramParameters(); - - /// Copy constructor - GpuProgramParameters(const GpuProgramParameters& oth); - /// Operator = overload - GpuProgramParameters& operator=(const GpuProgramParameters& oth); - - /** Internal method for providing a link to a name->definition map for parameters. */ - void _setNamedConstants(const GpuNamedConstantsPtr& constantmap); - - /** Internal method for providing a link to a logical index->physical index map for - * parameters. */ - void _setLogicalIndexes(const GpuLogicalBufferStructPtr& indexMap); - - /// Does this parameter set include named parameters? - bool hasNamedParameters() const { return mNamedConstants.get() != 0; } - /** Does this parameter set include logically indexed parameters? - @note Not mutually exclusive with hasNamedParameters since some high-level - programs still use logical indexes to set the parameters on the - rendersystem. - */ - bool hasLogicalIndexedParameters() const { return mLogicalToPhysical.get() != 0; } - - /// @name Set constant by logical index - /// @{ - /** Sets a 4-element floating-point parameter to the program. - @param index The logical constant index at which to place the parameter - (each constant is a 4D float) - @param vec The value to set - */ - void setConstant(size_t index, const Vector4& vec); - /** Sets a single floating-point parameter to the program. - @note This is actually equivalent to calling - setConstant(index Vector4(val, 0, 0, 0)) since all constants are 4D. - @param index The logical constant index at which to place the parameter (each constant is - a 4D float) - @param val The value to set - */ - void setConstant(size_t index, Real val); - /** Sets a 4-element floating-point parameter to the program via Vector3. - @param index The logical constant index at which to place the parameter (each constant is - a 4D float). - Note that since you're passing a Vector3, the last element of the 4-element - value will be set to 1 (a homogeneous vector) - @param vec The value to set - */ - void setConstant(size_t index, const Vector3& vec); - /** Sets a 4-element floating-point parameter to the program via Vector2. - @param index The logical constant index at which to place the parameter (each constant is - a 4D float). - Note that since you're passing a Vector2, the last 2 elements of the 4-element - value will be set to 1 (a homogeneous vector) - @param vec The value to set - */ - void setConstant(size_t index, const Vector2& vec); - /** Sets a Matrix4 parameter to the program. - @param index The logical constant index at which to place the parameter (each constant is - a 4D float). - NB since a Matrix4 is 16 floats long, this parameter will take up 4 indexes. - @param m The value to set - */ - void setConstant(size_t index, const Matrix4& m); - /** Sets a list of Matrix4 parameters to the program. - @param index The logical constant index at which to start placing the parameter (each constant is - a 4D float). - NB since a Matrix4 is 16 floats long, so each entry will take up 4 indexes. - @param m Pointer to an array of matrices to set - @param numEntries Number of Matrix4 entries - */ - void setConstant(size_t index, const Matrix4* m, size_t numEntries); - /** Sets a ColourValue parameter to the program. - @param index The logical constant index at which to place the parameter (each constant is - a 4D float) - @param colour The value to set - */ - void setConstant(size_t index, const ColourValue& colour); - /** Sets a multiple value constant floating-point parameter to the program. - @param index The logical constant index at which to start placing parameters (each constant is - a 4D float) - @param val Pointer to the values to write, must contain 4*count floats - @param count The number of groups of 4 floats to write - */ - void setConstant(size_t index, const float *val, size_t count); - /** Sets a multiple value constant floating-point parameter to the program. - @param index The logical constant index at which to start placing parameters (each constant is - a 4D float) - @param val Pointer to the values to write, must contain 4*count floats - @param count The number of groups of 4 floats to write - */ - void setConstant(size_t index, const double *val, size_t count); - /** Sets a multiple value constant integer parameter to the program. - - Different types of GPU programs support different types of constant parameters. - For example, it's relatively common to find that vertex programs only support - floating point constants, and that fragment programs only support integer (fixed point) - parameters. This can vary depending on the program version supported by the - graphics card being used. You should consult the documentation for the type of - low level program you are using, or alternatively use the methods - provided on RenderSystemCapabilities to determine the options. - @param index The logical constant index at which to place the parameter (each constant is - a 4D integer) - @param val Pointer to the values to write, must contain 4*count ints - @param count The number of groups of 4 ints to write - */ - void setConstant(size_t index, const int *val, size_t count); - /** Sets a multiple value constant unsigned integer parameter to the program. - - Different types of GPU programs support different types of constant parameters. - For example, it's relatively common to find that vertex programs only support - floating point constants, and that fragment programs only support integer (fixed point) - parameters. This can vary depending on the program version supported by the - graphics card being used. You should consult the documentation for the type of - low level program you are using, or alternatively use the methods - provided on RenderSystemCapabilities to determine the options. - @param index The logical constant index at which to place the parameter (each constant is - a 4D integer) - @param val Pointer to the values to write, must contain 4*count ints - @param count The number of groups of 4 ints to write - */ - void setConstant(size_t index, const uint *val, size_t count); - /// @} - - /** @name Set constant by physical index - You can use these methods if you have already derived the physical - constant buffer location, for a slight speed improvement over using - the named / logical index versions. - */ - /// @{ - /** Write a series of values into the underlying - constant buffer at the given physical index. - @param physicalIndex The buffer position to start writing - @param val Pointer to a list of values to write - @param count The number of floats to write - */ - template - void _writeRawConstants(size_t physicalIndex, const T* val, size_t count) - { - assert(physicalIndex + sizeof(T) * count <= mConstants.size()); - memcpy(&mConstants[physicalIndex], val, sizeof(T) * count); - } - /// @overload - void _writeRawConstants(size_t physicalIndex, const double* val, size_t count); - /// write values into register storage - void _writeRegisters(size_t index, const int* val, size_t count); - /** Write a Vector parameter to the program directly to - the underlying constants buffer. - @param physicalIndex The physical buffer index at which to place the parameter - @param vec The value to set - @param count The number of floats to write; if for example - the uniform constant 'slot' is smaller than a Vector4 - */ - template - void _writeRawConstant(size_t physicalIndex, const Vector& vec, size_t count = dims) - { - _writeRawConstants(physicalIndex, vec.ptr(), std::min(count, (size_t)dims)); - } - /** Write a single parameter to the program. - @param physicalIndex The physical buffer index at which to place the parameter - @param val The value to set - */ - template - void _writeRawConstant(size_t physicalIndex, T val) - { - _writeRawConstants(physicalIndex, &val, 1); - } - /** Write a Matrix4 parameter to the program. - @param physicalIndex The physical buffer index at which to place the parameter - @param m The value to set - @param elementCount actual element count used with shader - */ - void _writeRawConstant(size_t physicalIndex, const Matrix4& m, size_t elementCount); - /// @overload - void _writeRawConstant(size_t physicalIndex, const Matrix3& m, size_t elementCount); - /** Write a list of Matrix4 parameters to the program. - @param physicalIndex The physical buffer index at which to place the parameter - @param m The value to set - @param numEntries Number of Matrix4 entries - */ - void _writeRawConstant(size_t physicalIndex, const TransformBaseReal* m, size_t numEntries); - /** Write a ColourValue parameter to the program. - @param physicalIndex The physical buffer index at which to place the parameter - @param colour The value to set - @param count The number of floats to write; if for example - the uniform constant 'slot' is smaller than a Vector4 - */ - void _writeRawConstant(size_t physicalIndex, const ColourValue& colour, - size_t count = 4); - /// @} - - /** Read a series of floating point values from the underlying float - constant buffer at the given physical index. - @param physicalIndex The buffer position to start reading - @param count The number of floats to read - @param dest Pointer to a buffer to receive the values - */ - void _readRawConstants(size_t physicalIndex, size_t count, float* dest); - /** Read a series of integer values from the underlying integer - constant buffer at the given physical index. - @param physicalIndex The buffer position to start reading - @param count The number of ints to read - @param dest Pointer to a buffer to receive the values - */ - void _readRawConstants(size_t physicalIndex, size_t count, int* dest); - - /// @deprecated use getConstantDefinitions() - OGRE_DEPRECATED GpuConstantDefinitionIterator getConstantDefinitionIterator(void) const; - - /** Get a specific GpuConstantDefinition for a named parameter. - @note - Only available if this parameters object has named parameters. - */ - const GpuConstantDefinition& getConstantDefinition(const String& name) const; - - /** Get the full list of GpuConstantDefinition instances. - @note - Only available if this parameters object has named parameters. - */ - const GpuNamedConstants& getConstantDefinitions() const; - - /** Get the current list of mappings from low-level logical param indexes - to physical buffer locations in the float buffer. - @note - Only applicable to low-level programs. - */ - const GpuLogicalBufferStructPtr& getLogicalBufferStruct() const { return mLogicalToPhysical; } - - /** Retrieves the logical index relating to a physical index in the - buffer, for programs which support that (low-level programs and - high-level programs which use logical parameter indexes). - @return std::numeric_limits::max() if not found - */ - size_t getLogicalIndexForPhysicalIndex(size_t physicalIndex); - /// Get a reference to the list of constants - const ConstantList& getConstantList() const { return mConstants; } - /// Get a pointer to the 'nth' item in the float buffer - float* getFloatPointer(size_t pos) { return (float*)&mConstants[pos]; } - /// Get a pointer to the 'nth' item in the float buffer - const float* getFloatPointer(size_t pos) const { return (const float*)&mConstants[pos]; } - /// Get a pointer to the 'nth' item in the double buffer - double* getDoublePointer(size_t pos) { return (double*)&mConstants[pos]; } - /// Get a pointer to the 'nth' item in the double buffer - const double* getDoublePointer(size_t pos) const { return (const double*)&mConstants[pos]; } - /// Get a pointer to the 'nth' item in the int buffer - int* getIntPointer(size_t pos) { return (int*)&mConstants[pos]; } - /// Get a pointer to the 'nth' item in the int buffer - const int* getIntPointer(size_t pos) const { return (const int*)&mConstants[pos]; } - /// Get a pointer to the 'nth' item in the uint buffer - uint* getUnsignedIntPointer(size_t pos) { return (uint*)&mConstants[pos]; } - /// Get a pointer to the 'nth' item in the uint buffer - const uint* getUnsignedIntPointer(size_t pos) const { return (const uint*)&mConstants[pos]; } - - /// get a pointer to register storage - int* getRegPointer(size_t pos) { return &mRegisters[pos]; } - /// @overload - const int* getRegPointer(size_t pos) const { return &mRegisters[pos]; } - - /// @name Automatically derived constants - /// @{ - - /// Get a reference to the list of auto constant bindings - const AutoConstantList& getAutoConstantList() const { return mAutoConstants; } - - /** Sets up a constant which will automatically be updated by the system. - - Vertex and fragment programs often need parameters which are to do with the - current render state, or particular values which may very well change over time, - and often between objects which are being rendered. This feature allows you - to set up a certain number of predefined parameter mappings that are kept up to - date for you. - @param index The location in the constant list to place this updated constant every time - it is changed. Note that because of the nature of the types, we know how big the - parameter details will be so you don't need to set that like you do for manual constants. - @param acType The type of automatic constant to set - @param extraInfo If the constant type needs more information (like a light index or array size) put it here. - */ - void setAutoConstant(size_t index, AutoConstantType acType, uint32 extraInfo = 0); - /// @overload - void setAutoConstantReal(size_t index, AutoConstantType acType, float rData); - /// @overload - void setAutoConstant(size_t index, AutoConstantType acType, uint16 extraInfo1, uint16 extraInfo2) - { - setAutoConstant(index, acType, (uint32)extraInfo1 | ((uint32)extraInfo2) << 16); - } - - /** As setAutoConstant, but sets up the auto constant directly against a - physical buffer index. - */ - void _setRawAutoConstant(size_t physicalIndex, AutoConstantType acType, uint32 extraInfo, - uint16 variability, uint8 elementSize = 4); - /** As setAutoConstantReal, but sets up the auto constant directly against a - physical buffer index. - */ - void _setRawAutoConstantReal(size_t physicalIndex, AutoConstantType acType, float rData, - uint16 variability, uint8 elementSize = 4); - - - /** Unbind an auto constant so that the constant is manually controlled again. */ - void clearAutoConstant(size_t index); - - /// @deprecated use ACT_TIME directly - OGRE_DEPRECATED void setConstantFromTime(size_t index, Real factor) - { - setAutoConstantReal(index, ACT_TIME, factor); - } - - /** Clears all the existing automatic constants. */ - void clearAutoConstants(void); - - /** Gets the automatic constant bindings currently in place. */ - const AutoConstantList& getAutoConstants() const { - return mAutoConstants; - } - - /// Gets the number of int constants that have been set - size_t getAutoConstantCount(void) const { return mAutoConstants.size(); } - /** Gets a specific Auto Constant entry if index is in valid range - otherwise returns a NULL - @param index which entry is to be retrieved - */ - AutoConstantEntry* getAutoConstantEntry(const size_t index); - /** Returns true if this instance has any automatic constants. */ - bool hasAutoConstants(void) const { return !(mAutoConstants.empty()); } - /** Finds an auto constant that's affecting a given logical parameter - index for floating-point values. - @note Only applicable for low-level programs. - */ - const AutoConstantEntry* findFloatAutoConstantEntry(size_t logicalIndex); - /** Finds an auto constant that's affecting a given named parameter index. - @note Only applicable to high-level programs. - */ - const AutoConstantEntry* findAutoConstantEntry(const String& paramName) const; - /** Finds an auto constant that's affecting a given physical position in - the floating-point buffer - */ - const AutoConstantEntry* _findRawAutoConstantEntryFloat(size_t physicalIndex) const; - /** Sets up a constant which will automatically be updated by the system. - - Vertex and fragment programs often need parameters which are to do with the - current render state, or particular values which may very well change over time, - and often between objects which are being rendered. This feature allows you - to set up a certain number of predefined parameter mappings that are kept up to - date for you. - @note - This named option will only work if you are using a parameters object created - from a high-level program (HighLevelGpuProgram). - @param name The name of the parameter - @param acType The type of automatic constant to set - @param extraInfo If the constant type needs more information (like a light index) put it here. - */ - void setNamedAutoConstant(const String& name, AutoConstantType acType, uint32 extraInfo = 0); - /// @overload - void setNamedAutoConstantReal(const String& name, AutoConstantType acType, Real rData); - /// @overload - void setNamedAutoConstant(const String& name, AutoConstantType acType, uint16 extraInfo1, uint16 extraInfo2) - { - setNamedAutoConstant(name, acType, (uint32)extraInfo1 | ((uint32)extraInfo2) << 16); - } - - /// @deprecated use ACT_TIME directly - void setNamedConstantFromTime(const String& name, Real factor) - { - setNamedAutoConstantReal(name, ACT_TIME, factor); - } - - /** Unbind an auto constant so that the constant is manually controlled again. */ - void clearNamedAutoConstant(const String& name); - /// @} - - /** Update automatic parameters. - @param source The source of the parameters - @param variabilityMask A mask of GpuParamVariability which identifies which autos will need updating - */ - void _updateAutoParams(const AutoParamDataSource* source, uint16 variabilityMask); - - /** Tells the program whether to ignore missing parameters or not. - */ - void setIgnoreMissingParams(bool state) { mIgnoreMissingParams = state; } - - /// @name Set constant by name - /// @{ - /** Sets a single value constant parameter to the program. - - Different types of GPU programs support different types of constant parameters. - For example, it's relatively common to find that vertex programs only support - floating point constants, and that fragment programs only support integer (fixed point) - parameters. This can vary depending on the program version supported by the - graphics card being used. You should consult the documentation for the type of - low level program you are using, or alternatively use the methods - provided on RenderSystemCapabilities to determine the options. - - Another possible limitation is that some systems only allow constants to be set - on certain boundaries, e.g. in sets of 4 values for example. Again, see - RenderSystemCapabilities for full details. - @note - This named option will only work if you are using a parameters object created - from a high-level program (HighLevelGpuProgram). - @param name The name of the parameter - @param val The value to set - */ - void setNamedConstant(const String& name, Real val); - /// @overload - void setNamedConstant(const String& name, int val); - /// @overload - void setNamedConstant(const String& name, uint val); - /// @overload - void setNamedConstant(const String& name, const Vector4& val); - /// @overload - void setNamedConstant(const String& name, const Vector3& val); - /// @overload - void setNamedConstant(const String& name, const Vector2& val); - /// @overload - void setNamedConstant(const String& name, const Matrix4& val); - /// @overload - void setNamedConstant(const String& name, const ColourValue& colour); - /** Sets a list of Matrix4 parameters to the program. - @param name The name of the parameter; this must be the first index of an array, - for examples 'matrices[0]' - NB since a Matrix4 is 16 floats long, so each entry will take up 4 indexes. - @param m Pointer to an array of matrices to set - @param numEntries Number of Matrix4 entries - */ - void setNamedConstant(const String& name, const Matrix4* m, size_t numEntries); - /** Sets a multiple value constant parameter to the program. - - Some systems only allow constants to be set on certain boundaries, - e.g. in sets of 4 values for example. The 'multiple' parameter allows - you to control that although you should only change it if you know - your chosen language supports that (at the time of writing, only - GLSL allows constants which are not a multiple of 4). - @note - This named option will only work if you are using a parameters object created - from a high-level program (HighLevelGpuProgram). - @param name The name of the parameter - @param val Pointer to the values to write - @param count The number of 'multiples' of floats to write - @param multiple The number of raw entries in each element to write, - the default is 4 so count = 1 would write 4 floats. - */ - void setNamedConstant(const String& name, const float *val, size_t count, - size_t multiple = 4); - /// @overload - void setNamedConstant(const String& name, const double *val, size_t count, - size_t multiple = 4); - /// @overload - void setNamedConstant(const String& name, const int *val, size_t count, - size_t multiple = 4); - /// @overload - void setNamedConstant(const String& name, const uint *val, size_t count, - size_t multiple = 4); - /// @} - /** Find a constant definition for a named parameter. - - This method returns null if the named parameter did not exist, unlike - getConstantDefinition which is more strict; unless you set the - last parameter to true. - @param name The name to look up - @param throwExceptionIfMissing If set to true, failure to find an entry - will throw an exception. - */ - const GpuConstantDefinition* _findNamedConstantDefinition( - const String& name, bool throwExceptionIfMissing = false) const; - /** Gets the physical buffer index associated with a logical float constant index. - @note Only applicable to low-level programs. - @param logicalIndex The logical parameter index - @param requestedSize The requested size - pass 0 to ignore missing entries - and return std::numeric_limits::max() - @param variability - @param type - */ - size_t _getConstantPhysicalIndex(size_t logicalIndex, size_t requestedSize, uint16 variability, BaseConstantType type); - /** Sets whether or not we need to transpose the matrices passed in from the rest of OGRE. - - D3D uses transposed matrices compared to GL and OGRE; this is not important when you - use programs which are written to process row-major matrices, such as those generated - by Cg, but if you use a program written to D3D's matrix layout you will need to enable - this flag. - */ - void setTransposeMatrices(bool val) { mTransposeMatrices = val; } - /// Gets whether or not matrices are to be transposed when set - bool getTransposeMatrices(void) const { return mTransposeMatrices; } - - /** Copies the values of all constants (including auto constants) from another - GpuProgramParameters object. - @note This copes the internal storage of the paarameters object and therefore - can only be used for parameters objects created from the same GpuProgram. - To merge parameters that match from different programs, use copyMatchingNamedConstantsFrom. - */ - void copyConstantsFrom(const GpuProgramParameters& source); - - /** Copies the values of all matching named constants (including auto constants) from - another GpuProgramParameters object. - - This method iterates over the named constants in another parameters object - and copies across the values where they match. This method is safe to - use when the 2 parameters objects came from different programs, but only - works for named parameters. - */ - void copyMatchingNamedConstantsFrom(const GpuProgramParameters& source); - - /** gets the auto constant definition associated with name if found else returns NULL - @param name The name of the auto constant - */ - static const AutoConstantDefinition* getAutoConstantDefinition(const String& name); - /** gets the auto constant definition by auto constant type. - @param type The auto constant type - */ - static const AutoConstantDefinition* getAutoConstantDefinition(AutoConstantType type); - /** Returns the number of auto constant definitions - */ - static size_t getNumAutoConstantDefinitions(void); - - - /** increments the multipass number entry by 1 if it exists - */ - void incPassIterationNumber(void); - /// @deprecated query by GPV_PASS_ITERATION_NUMBER instead - OGRE_DEPRECATED bool hasPassIterationNumber() const - { return mActivePassIterationIndex != (std::numeric_limits::max)(); } - /// @deprecated query by GPV_PASS_ITERATION_NUMBER instead - OGRE_DEPRECATED size_t getPassIterationNumberIndex() const - { return mActivePassIterationIndex; } - - /// @name Shared Parameters - /// @{ - /** Use a set of shared parameters in this parameters object. - - Allows you to use a set of shared parameters to automatically update - this parameter set. - */ - void addSharedParameters(GpuSharedParametersPtr sharedParams); - - /** Use a set of shared parameters in this parameters object. - - Allows you to use a set of shared parameters to automatically update - this parameter set. - @param sharedParamsName The name of a shared parameter set as defined in - GpuProgramManager - */ - void addSharedParameters(const String& sharedParamsName); - - /** Returns whether this parameter set is using the named shared parameter set. */ - bool isUsingSharedParameters(const String& sharedParamsName) const; - - /** Stop using the named shared parameter set. */ - void removeSharedParameters(const String& sharedParamsName); - - /** Stop using all shared parameter sets. */ - void removeAllSharedParameters(); - - /** Get the list of shared parameter sets. */ - const GpuSharedParamUsageList& getSharedParameters() const; - - /** Update the parameters by copying the data from the shared - parameters. - @note This method may not actually be called if the RenderSystem - supports using shared parameters directly in their own shared buffer; in - which case the values should not be copied out of the shared area - into the individual parameter set, but bound separately. - */ - void _copySharedParams(); - - /** Update the HardwareBuffer based backing of referenced shared parameters - * - * falls back to _copySharedParams() if a shared parameter is not hardware backed - */ - void _updateSharedParams(); - /// @} - - size_t calculateSize(void) const; - }; - - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreGpuProgramUsage.h b/OgreMain/include/OgreGpuProgramUsage.h deleted file mode 100644 index ae64cb862da..00000000000 --- a/OgreMain/include/OgreGpuProgramUsage.h +++ /dev/null @@ -1,157 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GpuProgramUsage_H__ -#define __GpuProgramUsage_H__ - -#include "OgrePrerequisites.h" -#include "OgreGpuProgram.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - class Pass; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Materials - * @{ - */ - /** This class makes the usage of a vertex and fragment programs (low-level or high-level), - with a given set of parameters, explicit. - - Using a vertex or fragment program can get fairly complex; besides the fairly rudimentary - process of binding a program to the GPU for rendering, managing usage has few - complications, such as: -
    -
  • Programs can be high level (e.g. Cg, RenderMonkey) or low level (assembler). Using - either should be relatively seamless, although high-level programs give you the advantage - of being able to use named parameters, instead of just indexed registers
  • -
  • Programs and parameters can be shared between multiple usages, in order to save - memory
  • -
  • When you define a user of a program, such as a material, you often want to be able to - set up the definition but not load / compile / assemble the program at that stage, because - it is not needed just yet. The program should be loaded when it is first needed, or - earlier if specifically requested. The program may not be defined at this time, you - may want to have scripts that can set up the definitions independent of the order in which - those scripts are loaded.
  • -
- This class packages up those details so you don't have to worry about them. For example, - this class lets you define a high-level program and set up the parameters for it, without - having loaded the program (which you normally could not do). When the program is loaded and - compiled, this class will then validate the parameters you supplied earlier and turn them - into runtime parameters. - @par - Just in case it wasn't clear from the above, this class provides linkage to both - GpuProgram and HighLevelGpuProgram, despite its name. - */ - class _OgreExport GpuProgramUsage : public Resource::Listener, public PassAlloc - { - private: - Pass* mParent; - /// The program link - GpuProgramPtr mProgram; - - /// Program parameters - GpuProgramParametersSharedPtr mParameters; - - /// Whether to recreate parameters next load - bool mRecreateParams; - GpuProgramType mType; - - void recreateParameters(); - - public: - /** Default constructor. - @param gptype The type of program to link to - @param parent - */ - GpuProgramUsage(GpuProgramType gptype, Pass* parent); - - /** Copy constructor */ - GpuProgramUsage(const GpuProgramUsage& rhs, Pass* newparent); - - ~GpuProgramUsage(); - - /** Gets the type of program we're trying to link to. */ - GpuProgramType getType(void) const { return mType; } - - /** Sets the name of the program to use. - @param name The name of the program to use - @param resetParams - If true, this will create a fresh set of parameters from the - new program being linked, so if you had previously set parameters - you will have to set them again. If you set this to false, you must - be absolutely sure that the parameters match perfectly, and in the - case of named parameters refers to the indexes underlying them, - not just the names. - */ - void setProgramName(const String& name, bool resetParams = true); - /** Sets the program to use. - - Note that this will create a fresh set of parameters from the - new program being linked, so if you had previously set parameters - you will have to set them again. - */ - void setProgram(const GpuProgramPtr& prog, bool resetParams = true); - /** Gets the program being used. */ - const GpuProgramPtr& getProgram() const { return mProgram; } - /** Gets the program being used. */ - const String& getProgramName(void) const { return mProgram->getName(); } - - /** Sets the program parameters that should be used; because parameters can be - shared between multiple usages for efficiency, this method is here for you - to register externally created parameter objects. Otherwise, the parameters - will be created for you when a program is linked. - */ - void setParameters(const GpuProgramParametersSharedPtr& params); - /** Gets the parameters being used here. - */ - const GpuProgramParametersSharedPtr& getParameters(void) const; - - /// Load this usage (and ensure program is loaded) - void _load(void); - /// Unload this usage - void _unload(void); - - size_t calculateSize(void) const; - - // Resource Listener - void unloadingComplete(Resource* prog) override; - void loadingComplete(Resource* prog) override; - - static GpuProgramPtr _getProgramByName(const String& name, const String& group, - GpuProgramType type); - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreHardwareBuffer.h b/OgreMain/include/OgreHardwareBuffer.h deleted file mode 100644 index 26ebd76ce39..00000000000 --- a/OgreMain/include/OgreHardwareBuffer.h +++ /dev/null @@ -1,457 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __HardwareBuffer__ -#define __HardwareBuffer__ - -// Precompiler options -#include "OgrePrerequisites.h" -#include "OgreException.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - /// Enums describing buffer usage - enum HardwareBufferUsage : uint8 - { - /** Memory mappable on host and cached - * @par Usage - * results of some computations, e.g. screen capture - */ - HBU_GPU_TO_CPU = 1, - /** CPU (system) memory - * This is the least optimal buffer setting. - * @par Usage - * Staging copy of resources used as transfer source. - */ - HBU_CPU_ONLY = 2, - /** Indicates the application will never read the contents of the buffer back, - it will only ever write data. Locking a buffer with this flag will ALWAYS - return a pointer to new, blank memory rather than the memory associated - with the contents of the buffer; this avoids DMA stalls because you can - write to a new memory area while the previous one is being used. - - However, you may read from it’s shadow buffer if you set one up - */ - HBU_DETAIL_WRITE_ONLY = 4, - /** Device-local GPU (video) memory. No need to be mappable on host. - * This is the optimal buffer usage setting. - * @par Usage - * Resources transferred from host once (immutable) - e.g. most textures, vertex buffers - */ - HBU_GPU_ONLY = HBU_GPU_TO_CPU | HBU_DETAIL_WRITE_ONLY, - /** Mappable on host and preferably fast to access by GPU. - * @par Usage - * Resources written frequently by host (dynamic) - e.g. uniform buffers updated every frame - */ - HBU_CPU_TO_GPU = HBU_CPU_ONLY | HBU_DETAIL_WRITE_ONLY, - }; - /** Abstract class defining common features of hardware buffers. - - A 'hardware buffer' is any area of memory held outside of core system ram, - and in our case refers mostly to video ram, although in theory this class - could be used with other memory areas such as sound card memory, custom - coprocessor memory etc. - @par - This reflects the fact that memory held outside of main system RAM must - be interacted with in a more formal fashion in order to promote - cooperative and optimal usage of the buffers between the various - processing units which manipulate them. - @par - This abstract class defines the core interface which is common to all - buffers, whether it be vertex buffers, index buffers, texture memory - or framebuffer memory etc. - @par - Buffers have the ability to be 'shadowed' in system memory, this is because - the kinds of access allowed on hardware buffers is not always as flexible as - that allowed for areas of system memory - for example it is often either - impossible, or extremely undesirable from a performance standpoint to read from - a hardware buffer; when writing to hardware buffers, you should also write every - byte and do it sequentially. In situations where this is too restrictive, - it is possible to create a hardware, write-only buffer (the most efficient kind) - and to back it with a system memory 'shadow' copy which can be read and updated arbitrarily. - Ogre handles synchronising this buffer with the real hardware buffer (which should still be - created with the HBU_DYNAMIC flag if you intend to update it very frequently). Whilst this - approach does have its own costs, such as increased memory overhead, these costs can - often be outweighed by the performance benefits of using a more hardware efficient buffer. - You should look for the 'useShadowBuffer' parameter on the creation methods used to create - the buffer of the type you require (see HardwareBufferManager) to enable this feature. - */ - class _OgreExport HardwareBuffer : public BufferAlloc - { - - public: - typedef uint8 Usage; - /// Rather use HardwareBufferUsage - enum UsageEnum - { - /// same as #HBU_GPU_TO_CPU - HBU_STATIC = HBU_GPU_TO_CPU, - /// same as #HBU_CPU_ONLY - HBU_DYNAMIC = HBU_CPU_ONLY, - /// @deprecated use #HBU_DETAIL_WRITE_ONLY - HBU_WRITE_ONLY = HBU_DETAIL_WRITE_ONLY, - /// @deprecated do not use - HBU_DISCARDABLE = 8, - /// same as #HBU_GPU_ONLY - HBU_STATIC_WRITE_ONLY = HBU_GPU_ONLY, - /// same as #HBU_CPU_TO_GPU - HBU_DYNAMIC_WRITE_ONLY = HBU_CPU_TO_GPU, - /// @deprecated do not use - HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE = HBU_CPU_TO_GPU, - }; - /// Locking options - enum LockOptions : uint8 - { - /** Normal mode, ie allows read/write and contents are preserved. - This kind of lock allows reading and writing from the buffer - it’s also the least - optimal because basically you’re telling the card you could be doing anything at - all. If you’re not using a shadow buffer, it requires the buffer to be transferred - from the card and back again. If you’re using a shadow buffer the effect is - minimal. - */ - HBL_NORMAL, - /** Discards the entire buffer while locking. - This means you are happy for the card to discard the entire current contents of the - buffer. Implicitly this means you are not going to read the data - it also means - that the card can avoid any stalls if the buffer is currently being rendered from, - because it will actually give you an entirely different one. Use this wherever - possible when you are locking a buffer which was not created with a shadow buffer. - If you are using a shadow buffer it matters less, although with a shadow buffer it’s - preferable to lock the entire buffer at once, because that allows the shadow buffer - to use HBL_DISCARD when it uploads the updated contents to the real buffer. - @note Only useful on buffers created with the HBU_CPU_TO_GPU flag. - */ - HBL_DISCARD, - /** Lock the buffer for reading only. Not allowed in buffers which are created with - HBU_GPU_ONLY. - Mandatory on static buffers, i.e. those created without the HBU_DYNAMIC flag. - */ - HBL_READ_ONLY, - /** As HBL_WRITE_ONLY, except the application guarantees not to overwrite any - region of the buffer which has already been used in this frame, can allow - some optimisation on some APIs. - @note Only useful on buffers with no shadow buffer.*/ - HBL_NO_OVERWRITE, - /** Lock the buffer for writing only.*/ - HBL_WRITE_ONLY - - }; - protected: - size_t mSizeInBytes; - size_t mLockStart; - size_t mLockSize; - std::unique_ptr mDelegate; - std::unique_ptr mShadowBuffer; - bool mShadowUpdated; - bool mSuppressHardwareUpdate; - bool mIsLocked; - Usage mUsage; - - /// Internal implementation of lock() - virtual void* lockImpl(size_t offset, size_t length, LockOptions options) - { - return mDelegate->lock(offset, length, options); - } - /// Internal implementation of unlock() - virtual void unlockImpl(void) { mDelegate->unlock(); } - - public: - /// Constructor, to be called by HardwareBufferManager only - HardwareBuffer(Usage usage, bool useShadowBuffer) - : mSizeInBytes(0), mLockStart(0), mLockSize(0), mShadowUpdated(false), mSuppressHardwareUpdate(false), - mIsLocked(false), mUsage(usage) - { - // If use shadow buffer, upgrade to WRITE_ONLY on hardware side - if (useShadowBuffer && usage == HBU_CPU_ONLY) - { - mUsage = HBU_CPU_TO_GPU; - } - else if (useShadowBuffer && usage == HBU_GPU_TO_CPU) - { - mUsage = HBU_GPU_ONLY; - } - } - virtual ~HardwareBuffer() {} - /** Lock the buffer for (potentially) reading / writing. - @param offset The byte offset from the start of the buffer to lock - @param length The size of the area to lock, in bytes - @param options Locking options - @return Pointer to the locked memory - */ - virtual void* lock(size_t offset, size_t length, LockOptions options) - { - OgreAssert(!isLocked(), "Cannot lock this buffer: it is already locked"); - OgreAssert((length + offset) <= mSizeInBytes, "Lock request out of bounds"); - - void* ret = NULL; - if (mShadowBuffer) - { - // we have to assume a read / write lock so we use the shadow buffer - // and tag for sync on unlock() - mShadowUpdated = (options != HBL_READ_ONLY); - - ret = mShadowBuffer->lock(offset, length, options); - } - else - { - mIsLocked = true; - // Lock the real buffer if there is no shadow buffer - ret = lockImpl(offset, length, options); - } - mLockStart = offset; - mLockSize = length; - return ret; - } - - /// @overload - void* lock(LockOptions options) - { - return this->lock(0, mSizeInBytes, options); - } - /** Releases the lock on this buffer. - - Locking and unlocking a buffer can, in some rare circumstances such as - switching video modes whilst the buffer is locked, corrupt the - contents of a buffer. This is pretty rare, but if it occurs, - this method will throw an exception, meaning you - must re-upload the data. - @par - Note that using the 'read' and 'write' forms of updating the buffer does not - suffer from this problem, so if you want to be 100% sure your - data will not be lost, use the 'read' and 'write' forms instead. - */ - void unlock(void) - { - OgreAssert(isLocked(), "Cannot unlock this buffer: it is not locked"); - - // If we used the shadow buffer this time... - if (mShadowBuffer && mShadowBuffer->isLocked()) - { - mShadowBuffer->unlock(); - // Potentially update the 'real' buffer from the shadow buffer - _updateFromShadow(); - } - else - { - // Otherwise, unlock the real one - unlockImpl(); - mIsLocked = false; - } - - } - - /** Reads data from the buffer and places it in the memory pointed to by pDest. - @param offset The byte offset from the start of the buffer to read - @param length The size of the area to read, in bytes - @param pDest The area of memory in which to place the data, must be large enough to - accommodate the data! - */ - virtual void readData(size_t offset, size_t length, void* pDest) - { - if (mShadowBuffer) - { - mShadowBuffer->readData(offset, length, pDest); - return; - } - - mDelegate->readData(offset, length, pDest); - } - /** Writes data to the buffer from an area of system memory; note that you must - ensure that your buffer is big enough. - @param offset The byte offset from the start of the buffer to start writing - @param length The size of the data to write to, in bytes - @param pSource The source of the data to be written - @param discardWholeBuffer If true, this allows the driver to discard the entire buffer when writing, - such that DMA stalls can be avoided; use if you can. - */ - virtual void writeData(size_t offset, size_t length, const void* pSource, - bool discardWholeBuffer = false) - { - // Update the shadow buffer - if (mShadowBuffer) - { - mShadowBuffer->writeData(offset, length, pSource, discardWholeBuffer); - } - - mDelegate->writeData(offset, length, pSource, discardWholeBuffer); - } - - /** Copy data from another buffer into this one. - - Note that the source buffer must not be created with the - usage HBU_WRITE_ONLY otherwise this will fail. - @param srcBuffer The buffer from which to read the copied data - @param srcOffset Offset in the source buffer at which to start reading - @param dstOffset Offset in the destination buffer to start writing - @param length Length of the data to copy, in bytes. - @param discardWholeBuffer If true, will discard the entire contents of this buffer before copying - */ - virtual void copyData(HardwareBuffer& srcBuffer, size_t srcOffset, - size_t dstOffset, size_t length, bool discardWholeBuffer = false) - { - if(mDelegate && !srcBuffer.isSystemMemory()) - { - mDelegate->copyData(*srcBuffer.mDelegate, srcOffset, dstOffset, length, discardWholeBuffer); - return; - } - const void* srcData = srcBuffer.lock(srcOffset, length, HBL_READ_ONLY); - this->writeData(dstOffset, length, srcData, discardWholeBuffer); - srcBuffer.unlock(); - } - - /** Copy all data from another buffer into this one. - - Normally these buffers should be of identical size, but if they're - not, the routine will use the smallest of the two sizes. - */ - void copyData(HardwareBuffer& srcBuffer) - { - size_t sz = std::min(getSizeInBytes(), srcBuffer.getSizeInBytes()); - copyData(srcBuffer, 0, 0, sz, true); - } - - /// Updates the real buffer from the shadow buffer, if required - virtual void _updateFromShadow(void) - { - if (mShadowBuffer && mShadowUpdated && !mSuppressHardwareUpdate) - { - // Do this manually to avoid locking problems - const void* srcData = mShadowBuffer->lockImpl(mLockStart, mLockSize, HBL_READ_ONLY); - // Lock with discard if the whole buffer was locked, otherwise w/o - bool discardWholeBuffer = mLockStart == 0 && mLockSize == mSizeInBytes; - LockOptions lockOpt = discardWholeBuffer ? HBL_DISCARD : HBL_WRITE_ONLY; - void* destData = this->lockImpl(mLockStart, mLockSize, lockOpt); - // Copy shadow to real - memcpy(destData, srcData, mLockSize); - this->unlockImpl(); - mShadowBuffer->unlockImpl(); - mShadowUpdated = false; - } - } - - /// Returns the size of this buffer in bytes - size_t getSizeInBytes(void) const { return mSizeInBytes; } - /// Returns the Usage flags with which this buffer was created - Usage getUsage(void) const { return mUsage; } - /// Returns whether this buffer is held in system memory - virtual bool isSystemMemory(void) const { return mDelegate && mDelegate->isSystemMemory(); } - /// Returns whether this buffer has a system memory shadow for quicker reading - bool hasShadowBuffer(void) const { return mShadowBuffer || (mDelegate && mDelegate->hasShadowBuffer()); } - /// Returns whether or not this buffer is currently locked. - bool isLocked(void) const { - return mIsLocked || (mShadowBuffer && mShadowBuffer->isLocked()); - } - /// Pass true to suppress hardware upload of shadow buffer changes - void suppressHardwareUpdate(bool suppress) { - mSuppressHardwareUpdate = suppress; - if (!suppress) - _updateFromShadow(); - - if(mDelegate) - mDelegate->suppressHardwareUpdate(suppress); - } - - template T* _getImpl() - { - return static_cast(mDelegate.get()); - } - }; - - typedef HardwareBuffer HardwareCounterBuffer; - typedef HardwareBuffer HardwareUniformBuffer; - - /** Locking helper. Guaranteed unlocking even in case of exception. */ - struct HardwareBufferLockGuard - { - HardwareBufferLockGuard() : pBuf(0), pData(0) {} - - HardwareBufferLockGuard(HardwareBuffer* p, HardwareBuffer::LockOptions options) - : pBuf(0), pData(0) { lock(p, options); } - - HardwareBufferLockGuard(HardwareBuffer* p, size_t offset, size_t length, HardwareBuffer::LockOptions options) - : pBuf(0), pData(0) { lock(p, offset, length, options); } - - template - HardwareBufferLockGuard(const SharedPtr& p, HardwareBuffer::LockOptions options) - : pBuf(0), pData(0) { lock(p.get(), options); } - - template - HardwareBufferLockGuard(const SharedPtr& p, size_t offset, size_t length, HardwareBuffer::LockOptions options) - : pBuf(0), pData(0) { lock(p.get(), offset, length, options); } - - ~HardwareBufferLockGuard() { unlock(); } - - void unlock() - { - if(pBuf) - { - pBuf->unlock(); - pBuf = 0; - pData = 0; - } - } - - void lock(HardwareBuffer* p, HardwareBuffer::LockOptions options) - { - assert(p); - unlock(); - pBuf = p; - pData = pBuf->lock(options); - } - - void lock(HardwareBuffer* p, size_t offset, size_t length, HardwareBuffer::LockOptions options) - { - assert(p); - unlock(); - pBuf = p; - pData = pBuf->lock(offset, length, options); - } - - template - void lock(const SharedPtr& p, HardwareBuffer::LockOptions options) - { lock(p.get(), options); } - - template - void lock(const SharedPtr& p, size_t offset, size_t length, HardwareBuffer::LockOptions options) - { lock(p.get(), offset, length, options); } - - HardwareBuffer* pBuf; - void* pData; - }; - - /** @} */ - /** @} */ -} -#endif - - diff --git a/OgreMain/include/OgreHardwareBufferManager.h b/OgreMain/include/OgreHardwareBufferManager.h deleted file mode 100644 index 5d3e522a35b..00000000000 --- a/OgreMain/include/OgreHardwareBufferManager.h +++ /dev/null @@ -1,328 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __HardwareBufferManager__ -#define __HardwareBufferManager__ - -// Precompiler options -#include "OgrePrerequisites.h" - -#include "OgreSingleton.h" -#include "OgreHardwareIndexBuffer.h" -#include "OgreHardwareVertexBuffer.h" -#include "Threading/OgreThreadHeaders.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - - /** Abstract interface representing a 'licensee' of a hardware buffer copy. - - Often it's useful to have temporary buffers which are used for working - but are not necessarily needed permanently. However, creating and - destroying buffers is expensive, so we need a way to share these - working areas, especially those based on existing fixed buffers. - This class represents a licensee of one of those temporary buffers, - and must be implemented by any user of a temporary buffer if they - wish to be notified when the license is expired. - */ - class _OgreExport HardwareBufferLicensee - { - public: - virtual ~HardwareBufferLicensee() { } - /** This method is called when the buffer license is expired and is about - to be returned to the shared pool. - */ - virtual void licenseExpired(HardwareBuffer* buffer) = 0; - }; - - /** Base definition of a hardware buffer manager. - - This class is deliberately not a Singleton, so that multiple types can - exist at once (notably DefaultHardwareBufferManagerBase). - The Singleton is add via the inheritance in HardwareBufferManager below. - */ - class _OgreExport HardwareBufferManagerBase : public BufferAlloc - { - protected: - /** WARNING: The following member should place before all other members. - Members destruct order is very important here, because destructing other - members will cause notify back to this class, and then will access to this - two members. - */ - typedef std::set VertexBufferList; - typedef std::set IndexBufferList; - VertexBufferList mVertexBuffers; - - - typedef std::set VertexDeclarationList; - typedef std::set VertexBufferBindingList; - VertexDeclarationList mVertexDeclarations; - VertexBufferBindingList mVertexBufferBindings; - - // Mutexes - OGRE_MUTEX(mVertexBuffersMutex); - OGRE_MUTEX(mVertexDeclarationsMutex); - OGRE_MUTEX(mVertexBufferBindingsMutex); - - /// Internal method for destroys all vertex declarations. - void destroyAllDeclarations(void); - /// Internal method for destroys all vertex buffer bindings. - void destroyAllBindings(void); - - private: - /// Internal method for creates a new vertex declaration, may be overridden by certain rendering APIs. - virtual VertexDeclaration* createVertexDeclarationImpl(void); - /// Internal method for destroys a vertex declaration, may be overridden by certain rendering APIs. - void destroyVertexDeclarationImpl(VertexDeclaration* decl); - - /// Internal method for creates a new VertexBufferBinding, may be overridden by certain rendering APIs. - virtual VertexBufferBinding* createVertexBufferBindingImpl(void); - /// Internal method for destroys a VertexBufferBinding, may be overridden by certain rendering APIs. - void destroyVertexBufferBindingImpl(VertexBufferBinding* binding); - - /** Struct holding details of a license to use a temporary shared buffer. */ - class _OgrePrivate VertexBufferLicense - { - public: - HardwareVertexBuffer* originalBufferPtr; - size_t expiredDelay; - HardwareVertexBufferSharedPtr buffer; - HardwareBufferLicensee* licensee; - VertexBufferLicense( - HardwareVertexBuffer* orig, - size_t delay, - const HardwareVertexBufferSharedPtr& buf, - HardwareBufferLicensee* lic) - : originalBufferPtr(orig) - , expiredDelay(delay) - , buffer(buf) - , licensee(lic) - {} - - }; - - /// Map from original buffer to temporary buffers. - typedef std::multimap FreeTemporaryVertexBufferMap; - /// Map of current available temp buffers. - FreeTemporaryVertexBufferMap mFreeTempVertexBufferMap; - /// Map from temporary buffer to details of a license. - typedef std::map TemporaryVertexBufferLicenseMap; - /// Map of currently licensed temporary buffers. - TemporaryVertexBufferLicenseMap mTempVertexBufferLicenses; - /// Number of frames elapsed since temporary buffers utilization was above half the available. - size_t mUnderUsedFrameCount; - /// Number of frames to wait before free unused temporary buffers. - static const size_t UNDER_USED_FRAME_THRESHOLD; - /// Frame delay for temporary buffers. - static const size_t EXPIRED_DELAY_FRAME_THRESHOLD; - // Mutexes - OGRE_MUTEX(mTempBuffersMutex); - - void _forceReleaseBufferCopies(HardwareVertexBuffer* sourceBuffer); - public: - HardwareBufferManagerBase(); - virtual ~HardwareBufferManagerBase(); - /** Create a hardware vertex buffer. - - This method creates a new vertex buffer; this will act as a source of geometry - data for rendering objects. Note that because the meaning of the contents of - the vertex buffer depends on the usage, this method does not specify a - vertex format; the user of this buffer can actually insert whatever data - they wish, in any format. However, in order to use this with a RenderOperation, - the data in this vertex buffer will have to be associated with a semantic element - of the rendering pipeline, e.g. a position, or texture coordinates. This is done - using the VertexDeclaration class, which itself contains VertexElement structures - referring to the source data. - Note that because vertex buffers can be shared, they are reference - counted so you do not need to worry about destroying them this will be done - automatically. - @param vertexSize - The size in bytes of each vertex in this buffer; you must calculate - this based on the kind of data you expect to populate this buffer with. - @param numVerts - The number of vertices in this buffer. - @param usage - One or more members of the #HardwareBufferUsage enumeration; you are - strongly advised to use #HBU_GPU_ONLY wherever possible, if you need to - update regularly, consider #HBU_CPU_TO_GPU or useShadowBuffer=true. - @param useShadowBuffer - If set to @c true, this buffer will be 'shadowed' by one stored in - system memory rather than GPU memory. See @ref Shadow-Buffers. - */ - virtual HardwareVertexBufferSharedPtr - createVertexBuffer(size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, - bool useShadowBuffer = false) = 0; - /** Create a hardware index buffer. - @remarks Note that because buffers can be shared, they are reference - counted so you do not need to worry about destroying them this will be done - automatically. - @param itype - The type in index, either 16- or 32-bit, depending on how many vertices - you need to be able to address - @param numIndexes - The number of indexes in the buffer - @param usage - One or more members of the #HardwareBufferUsage enumeration. - @param useShadowBuffer - If set to @c true, this buffer will be 'shadowed' by one stored in - system memory rather than GPU memory. See @ref Shadow-Buffers. - */ - virtual HardwareIndexBufferSharedPtr - createIndexBuffer(HardwareIndexBuffer::IndexType itype, size_t numIndexes, - HardwareBuffer::Usage usage, bool useShadowBuffer = false) = 0; - - /** Create a render to vertex buffer. - @remarks The parameters (such as vertex size etc) are determined later - and are allocated when needed. - */ - virtual RenderToVertexBufferSharedPtr createRenderToVertexBuffer(); - - /** - * Create uniform buffer. This type of buffer allows the upload of shader constants once, - * and sharing between shader stages or even shaders from another materials. - * The update shall be triggered by GpuProgramParameters, if is dirty - */ - virtual HardwareBufferPtr createUniformBuffer(size_t sizeBytes, - HardwareBufferUsage usage = HBU_CPU_TO_GPU, - bool useShadowBuffer = false); - - /** Creates a new vertex declaration. */ - VertexDeclaration* createVertexDeclaration(void); - /** Destroys a vertex declaration. */ - void destroyVertexDeclaration(VertexDeclaration* decl); - - /** Creates a new VertexBufferBinding. */ - VertexBufferBinding* createVertexBufferBinding(void); - /** Destroys a VertexBufferBinding. */ - void destroyVertexBufferBinding(VertexBufferBinding* binding); - - /** Allocates a copy of a given vertex buffer. - - This method allocates a temporary copy of an existing vertex buffer. - This buffer is subsequently stored and can be made available for - other purposes later without incurring the cost of construction / - destruction. - @param sourceBuffer - The source buffer to use as a copy. - @param licensee - Pointer back to the class requesting the copy, which must - implement HardwareBufferLicense in order to be notified when the license - expires. - @param copyData - If @c true, the current data is copied as well as the - structure of the buffer/ - */ - HardwareVertexBufferSharedPtr allocateVertexBufferCopy( - const HardwareVertexBufferSharedPtr& sourceBuffer, - HardwareBufferLicensee* licensee, - bool copyData = false); - - /** Manually release a vertex buffer copy for others to subsequently use. - - @param bufferCopy - The buffer copy. The caller is expected to delete - or at least no longer use this reference, since another user may - well begin to modify the contents of the buffer. - */ - void releaseVertexBufferCopy(const HardwareVertexBufferSharedPtr& bufferCopy); - - /** Tell engine that the vertex buffer copy intent to reuse. - - Ogre internal keep an expired delay counter. - When the counter count down to zero, it'll release for other - purposes later. But you can use this function to reset the counter to - the internal configured value, keep the buffer not get released for - some frames. - @param bufferCopy - The buffer copy. The caller is expected to keep this - buffer copy for use. - */ - void touchVertexBufferCopy(const HardwareVertexBufferSharedPtr& bufferCopy); - - /** Free all unused vertex buffer copies. - - This method free all temporary vertex buffers that not in used. - In normally, temporary vertex buffers are subsequently stored and can - be made available for other purposes later without incurring the cost - of construction / destruction. But in some cases you want to free them - to save hardware memory (e.g. application was runs in a long time, you - might free temporary buffers periodically to avoid memory overload). - */ - void _freeUnusedBufferCopies(void); - - /** Internal method for releasing all temporary buffers; is called by OGRE. - @param forceFreeUnused - If @c true, free all unused temporary buffers. - If @c false, auto detect and free all unused temporary buffers based on - temporary buffers utilization. - */ - void _releaseBufferCopies(bool forceFreeUnused = false); - - /** Internal method that forces the release of copies of a given buffer. - - This usually means that the buffer which the copies are based on has - been changed in some fundamental way, and the owner of the original - wishes to make that known so that new copies will reflect the - changes. - @param sourceBuffer - The source buffer as a shared pointer. Any buffer copies created - from the source buffer are deleted. - */ - void _forceReleaseBufferCopies(const HardwareVertexBufferSharedPtr& sourceBuffer); - - /// Notification that a hardware vertex buffer has been destroyed. - void _notifyVertexBufferDestroyed(HardwareVertexBuffer* buf); - }; - - /** Singleton wrapper for hardware buffer manager. */ - class _OgreExport HardwareBufferManager : public HardwareBufferManagerBase, public Singleton - { - public: - HardwareBufferManager(); - ~HardwareBufferManager(); - - /// @copydoc Singleton::getSingleton() - static HardwareBufferManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static HardwareBufferManager* getSingletonPtr(void); - - }; - - /** @} */ - /** @} */ -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif // __HardwareBufferManager__ - diff --git a/OgreMain/include/OgreHardwareCounterBuffer.h b/OgreMain/include/OgreHardwareCounterBuffer.h deleted file mode 100644 index acf6173a2b6..00000000000 --- a/OgreMain/include/OgreHardwareCounterBuffer.h +++ /dev/null @@ -1,2 +0,0 @@ -#include "OgreHardwareBuffer.h" -#pragma message( __FILE__ " is deprecated, migrate to Ogre.h") diff --git a/OgreMain/include/OgreHardwareIndexBuffer.h b/OgreMain/include/OgreHardwareIndexBuffer.h deleted file mode 100644 index 5dbb5bedf8e..00000000000 --- a/OgreMain/include/OgreHardwareIndexBuffer.h +++ /dev/null @@ -1,87 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __HardwareIndexBuffer__ -#define __HardwareIndexBuffer__ - -// Precompiler options -#include "OgrePrerequisites.h" -#include "OgreHardwareBuffer.h" -#include "OgreSharedPtr.h" - -namespace Ogre { - class HardwareBufferManagerBase; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - /** Specialisation of HardwareBuffer for vertex index buffers, still abstract. */ - class _OgreExport HardwareIndexBuffer final : public HardwareBuffer - { - public: - enum IndexType : uint8 { - IT_16BIT, - IT_32BIT - }; - - private: - IndexType mIndexType; - uint8 mIndexSize; - HardwareBufferManagerBase* mMgr; - uint32 mNumIndexes; - public: - /// Should be called by HardwareBufferManager - HardwareIndexBuffer(HardwareBufferManagerBase* mgr, IndexType idxType, size_t numIndexes, - Usage usage, bool useShadowBuffer); - HardwareIndexBuffer(HardwareBufferManagerBase* mgr, IndexType idxType, size_t numIndexes, - HardwareBuffer* delegate); - ~HardwareIndexBuffer(); - /// Return the manager of this buffer, if any - HardwareBufferManagerBase* getManager() const { return mMgr; } - /// Get the type of indexes used in this buffer - IndexType getType(void) const { return mIndexType; } - /// Get the number of indexes in this buffer - uint32 getNumIndexes(void) const { return mNumIndexes; } - /// Get the size in bytes of each index - uint8 getIndexSize(void) const { return mIndexSize; } - - static size_t indexSize(IndexType type) { return type == IT_16BIT ? sizeof(uint16) : sizeof(uint32); } - - // NB subclasses should override lock, unlock, readData, writeData - }; - - /// @deprecated use HardwareBufferLockGuard directly - OGRE_DEPRECATED typedef HardwareBufferLockGuard HardwareIndexBufferLockGuard; - - /** @} */ - /** @} */ -} -#endif - diff --git a/OgreMain/include/OgreHardwareOcclusionQuery.h b/OgreMain/include/OgreHardwareOcclusionQuery.h deleted file mode 100644 index 927883d1069..00000000000 --- a/OgreMain/include/OgreHardwareOcclusionQuery.h +++ /dev/null @@ -1,132 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _HardwareOcclusionQuery__ -#define _HardwareOcclusionQuery__ - -// Precompiler options -#include "OgrePrerequisites.h" - -namespace Ogre { - - - - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ -/** - * This is a abstract class that that provides the interface for the query class for - * hardware occlusion. - * - * @author Lee Sandberg - * Updated on 13/8/2005 by Tuan Kuranes email: tuan.kuranes@free.fr - */ - class _OgreExport HardwareOcclusionQuery : public RenderSysAlloc -{ -//---------------------------------------------------------------------- -// Public methods -//-- -public: - /** - * Object public member functions - */ - - /** - * Default object constructor - * - */ - HardwareOcclusionQuery(); - - /** - * Object destructor - */ - virtual ~HardwareOcclusionQuery(); - - /** - * Starts the hardware occlusion query - * @remarks Simple usage: Create one or more OcclusionQuery object one per outstanding query or one per tested object - * OcclusionQuery* mOcclusionQuery; - * createOcclusionQuery( &mOcclusionQuery ); - * In the rendering loop: - * Draw all occluders - * mOcclusionQuery->startOcclusionQuery(); - * Draw the polygons to be tested - * mOcclusionQuery->endOcclusionQuery(); - * - * Results must be pulled using: - * UINT mNumberOfPixelsVisable; - * pullOcclusionQuery( &mNumberOfPixelsVisable ); - * - */ - virtual void beginOcclusionQuery() = 0; - - /** - * Ends the hardware occlusion test - */ - virtual void endOcclusionQuery() = 0; - - /** - * Pulls the hardware occlusion query. - * @note Waits until the query result is available; use isStillOutstanding - * if just want to test if the result is available. - * @retval NumOfFragments will get the resulting number of fragments. - * @return True if success or false if not. - */ - virtual bool pullOcclusionQuery(unsigned int* NumOfFragments) = 0; - - /** - * Let's you get the last pixel count with out doing the hardware occlusion test - * @return The last fragment count from the last test. - * Remarks This function won't give you new values, just the old value. - */ - unsigned int getLastQuerysPixelcount() const { return mPixelCount; } - - /** - * Lets you know when query is done, or still be processed by the Hardware - * @return true if query isn't finished. - */ - virtual bool isStillOutstanding(void) = 0; - - - //---------------------------------------------------------------------- - // protected members - //-- - protected : - /// Number of visible pixels determined by last query - unsigned int mPixelCount; - /// Has the query returned a result yet? - bool mIsQueryResultStillOutstanding; -}; - - /** @} */ - /** @} */ -} -#endif - diff --git a/OgreMain/include/OgreHardwarePixelBuffer.h b/OgreMain/include/OgreHardwarePixelBuffer.h deleted file mode 100644 index 8da5ecb0a42..00000000000 --- a/OgreMain/include/OgreHardwarePixelBuffer.h +++ /dev/null @@ -1,202 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __HardwarePixelBuffer__ -#define __HardwarePixelBuffer__ - -// Precompiler options -#include "OgrePrerequisites.h" -#include "OgreHardwareBuffer.h" -#include "OgreImage.h" -#include "OgreSharedPtr.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - /** Specialisation of HardwareBuffer for a pixel buffer. The - HardwarePixelbuffer abstracts an 1D, 2D or 3D quantity of pixels - stored by the rendering API. The buffer can be located on the card - or in main memory depending on its usage. One mipmap level of a - texture is an example of a HardwarePixelBuffer. - */ - class _OgreExport HardwarePixelBuffer : public HardwareBuffer - { - protected: - LockOptions mCurrentLockOptions; - /// Extents - uint32 mWidth, mHeight, mDepth; - /// Internal format - PixelFormat mFormat; - /// Pitches (offsets between rows and slices) - size_t mRowPitch, mSlicePitch; - /// Currently locked region (local coords) - PixelBox mCurrentLock; - /// The current locked box of this surface (entire surface coords) - Box mLockedBox; - - typedef std::vector SliceTRT; - SliceTRT mSliceTRT; - - /// Internal implementation of lock(), must be overridden in subclasses - virtual PixelBox lockImpl(const Box &lockBox, LockOptions options) = 0; - - /** Internal implementation of lock(), do not OVERRIDE or CALL this - for HardwarePixelBuffer implementations, but override the previous method */ - void* lockImpl(size_t offset, size_t length, LockOptions options) override; - - /** Notify TextureBuffer of destruction of render target. - Called by RenderTexture when destroyed. - */ - void _clearSliceRTT(size_t zoffset); - friend class RenderTexture; - public: - /// Should be called by HardwareBufferManager - HardwarePixelBuffer(uint32 mWidth, uint32 mHeight, uint32 mDepth, - PixelFormat mFormat, - HardwareBuffer::Usage usage, bool useShadowBuffer); - ~HardwarePixelBuffer(); - - /** Make every lock method from HardwareBuffer available. - See http://www.research.att.com/~bs/bs_faq2.html#overloadderived - */ - using HardwareBuffer::lock; - - /** Lock the buffer for (potentially) reading / writing. - @param lockBox Region of the buffer to lock - @param options Locking options - @return PixelBox containing the locked region, the pitches and - the pixel format - */ - const PixelBox& lock(const Box& lockBox, LockOptions options); - /** @copydoc HardwareBuffer::lock - @attention this method returns a pointer to the raw buffer storage, which is likely not what you - want. The RenderSystem is free to add padding, which you have to query from @ref getCurrentLock() - and apply during copying. Prefer @ref blitFromMemory, which correctly - handles copying in this case - @see @ref Updating-Pixel-Buffers - */ - void* lock(size_t offset, size_t length, LockOptions options) override; - - /** Get the current locked region. This is the same value as returned - by lock(const Box, LockOptions) - @return PixelBox containing the locked region - */ - const PixelBox& getCurrentLock(); - - /// @copydoc HardwareBuffer::readData - void readData(size_t offset, size_t length, void* pDest) override; - /// @copydoc HardwareBuffer::writeData - void writeData(size_t offset, size_t length, const void* pSource, - bool discardWholeBuffer = false) override; - - /** Copies a box from another PixelBuffer to a region of the - this PixelBuffer. - @param src Source pixel buffer - @param srcBox Box describing the source region in src - @param dstBox Box describing the destination region in this buffer - @remarks The source and destination regions dimensions don't have to match, in which - case scaling is done. This scaling is generally done using a bilinear filter in hardware, - but it is faster to pass the source image in the right dimensions. - @note Only call this function when both buffers are unlocked. - */ - virtual void blit(const HardwarePixelBufferSharedPtr &src, const Box &srcBox, const Box &dstBox); - - /** Convenience function that blits the entire source pixel buffer to this buffer. - If source and destination dimensions don't match, scaling is done. - @param src PixelBox containing the source pixels and format in memory - @note Only call this function when the buffer is unlocked. - */ - void blit(const HardwarePixelBufferSharedPtr &src); - - /** Copies a region from normal memory to a region of this pixelbuffer. The source - image can be in any pixel format supported by OGRE, and in any size. - @param src PixelBox containing the source pixels and format in memory - @param dstBox Box describing the destination region in this buffer - @remarks The source and destination regions dimensions don't have to match, in which - case scaling is done. This scaling is generally done using a bilinear filter in hardware, - but it is faster to pass the source image in the right dimensions. - @note Only call this function when the buffer is unlocked. - */ - virtual void blitFromMemory(const PixelBox &src, const Box &dstBox) = 0; - - /** Convenience function that blits a pixelbox from memory to the entire - buffer. The source image is scaled as needed. - @param src PixelBox containing the source pixels and format in memory - @note Only call this function when the buffer is unlocked. - */ - void blitFromMemory(const PixelBox& src) { blitFromMemory(src, Box(getSize())); } - - /** Copies a region of this pixelbuffer to normal memory. - @param srcBox Box describing the source region of this buffer - @param dst PixelBox describing the destination pixels and format in memory - @remarks The source and destination regions don't have to match, in which - case scaling is done. - @note Only call this function when the buffer is unlocked. - */ - virtual void blitToMemory(const Box &srcBox, const PixelBox &dst) = 0; - - /** Convenience function that blits this entire buffer to a pixelbox. - The image is scaled as needed. - @param dst PixelBox describing the destination pixels and format in memory - @note Only call this function when the buffer is unlocked. - */ - void blitToMemory(const PixelBox& dst) { blitToMemory(Box(getSize()), dst); } - - /** Get a render target for this PixelBuffer, or a slice of it. The texture this - was acquired from must have TU_RENDERTARGET set - @param slice Which slice - @return A pointer to the render target. This pointer has the lifespan of this - PixelBuffer. - */ - RenderTexture *getRenderTarget(size_t slice=0); - - /// Gets the width of this buffer - uint32 getWidth() const { return mWidth; } - /// Gets the height of this buffer - uint32 getHeight() const { return mHeight; } - /// Gets the depth of this buffer - uint32 getDepth() const { return mDepth; } - /// size (width, height, depth) of the pixel buffer - Vector3i getSize() const { return Vector3i(getWidth(), getHeight(), getDepth()); } - /// Gets the native pixel format of this buffer - PixelFormat getFormat() const { return mFormat; } - }; - - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreHardwareUniformBuffer.h b/OgreMain/include/OgreHardwareUniformBuffer.h deleted file mode 100644 index e870f65a8dc..00000000000 --- a/OgreMain/include/OgreHardwareUniformBuffer.h +++ /dev/null @@ -1,2 +0,0 @@ -#include "OgreHardwareBuffer.h" -#pragma message( __FILE__ " is deprecated, migrate to Ogre.h") \ No newline at end of file diff --git a/OgreMain/include/OgreHardwareVertexBuffer.h b/OgreMain/include/OgreHardwareVertexBuffer.h deleted file mode 100644 index ffef26d6a8c..00000000000 --- a/OgreMain/include/OgreHardwareVertexBuffer.h +++ /dev/null @@ -1,562 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __HardwareVertexBuffer__ -#define __HardwareVertexBuffer__ - -// Precompiler options -#include "OgrePrerequisites.h" -#include "OgreHardwareBuffer.h" -#include "OgreSharedPtr.h" -#include "OgreColourValue.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - class HardwareBufferManagerBase; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - /** Specialisation of HardwareBuffer for a vertex buffer. */ - class _OgreExport HardwareVertexBuffer final : public HardwareBuffer - { - bool mIsInstanceData; - HardwareBufferManagerBase* mMgr; - uint32 mNumVertices; - uint32 mVertexSize; - uint32 mInstanceDataStepRate; - - public: - /// Should be called by HardwareBufferManager - HardwareVertexBuffer(HardwareBufferManagerBase* mgr, size_t vertexSize, size_t numVertices, - Usage usage, bool useShadowBuffer); - HardwareVertexBuffer(HardwareBufferManagerBase* mgr, size_t vertexSize, size_t numVertices, - HardwareBuffer* delegate); - ~HardwareVertexBuffer(); - /// Return the manager of this buffer, if any - HardwareBufferManagerBase* getManager() const { return mMgr; } - /// Gets the size in bytes of a single vertex in this buffer - uint32 getVertexSize(void) const { return mVertexSize; } - /// Get the number of vertices in this buffer - uint32 getNumVertices(void) const { return mNumVertices; } - /// Get if this vertex buffer is an "instance data" buffer (per instance) - bool isInstanceData() const { return mIsInstanceData; } - /// Set if this vertex buffer is an "instance data" buffer (per instance) - void setIsInstanceData(const bool val); - /// Get the number of instances to draw using the same per-instance data before advancing in the buffer by one element. - uint32 getInstanceDataStepRate() const; - /// Set the number of instances to draw using the same per-instance data before advancing in the buffer by one element. - void setInstanceDataStepRate(const size_t val); - - - // NB subclasses should override lock, unlock, readData, writeData - - }; - - /// @deprecated use HardwareBufferLockGuard directly - OGRE_DEPRECATED typedef HardwareBufferLockGuard HardwareVertexBufferLockGuard; - - /// Vertex element semantics, used to identify the meaning of vertex buffer contents - enum VertexElementSemantic : uint8 - { - /// Position, typically VET_FLOAT3 - VES_POSITION = 1, - /// Blending weights - VES_BLEND_WEIGHTS = 2, - /// Blending indices - VES_BLEND_INDICES = 3, - /// Normal, typically VET_FLOAT3 - VES_NORMAL = 4, - /// Colour, typically VET_UBYTE4 - VES_COLOUR = 5, - /// Secondary colour. Generally free for custom data. Means specular with OpenGL FFP. - VES_COLOUR2 = 6, - /// Texture coordinates, typically VET_FLOAT2 - VES_TEXTURE_COORDINATES = 7, - /// Binormal (Y axis if normal is Z) - VES_BINORMAL = 8, - /// Tangent (X axis if normal is Z) - VES_TANGENT = 9, - /// The number of VertexElementSemantic elements (note - the first value VES_POSITION is 1) - VES_COUNT = 9, - /// @deprecated use VES_COLOUR - VES_DIFFUSE = VES_COLOUR, - /// @deprecated use VES_COLOUR2 - VES_SPECULAR = VES_COLOUR2 - }; - - /** - * Vertex element type, used to identify the base types of the vertex contents - * - * @note VET_SHORT1, VET_SHORT3, VET_USHORT1 and VET_USHORT3 should never be used - * because they aren't supported on any known hardware - they are unaligned as their size - * is not a multiple of 4 bytes. Therefore drivers usually must add padding on upload. - */ - enum VertexElementType : uint8 - { - VET_FLOAT1 = 0, - VET_FLOAT2 = 1, - VET_FLOAT3 = 2, - VET_FLOAT4 = 3, - - VET_SHORT1 = 5, ///< @deprecated (see #VertexElementType note) - VET_SHORT2 = 6, - VET_SHORT3 = 7, ///< @deprecated (see #VertexElementType note) - VET_SHORT4 = 8, - VET_UBYTE4 = 9, - _DETAIL_SWAP_RB = 10, - - // the following are not universally supported on all hardware: - VET_DOUBLE1 = 12, - VET_DOUBLE2 = 13, - VET_DOUBLE3 = 14, - VET_DOUBLE4 = 15, - VET_USHORT1 = 16, ///< @deprecated (see #VertexElementType note) - VET_USHORT2 = 17, - VET_USHORT3 = 18, ///< @deprecated (see #VertexElementType note) - VET_USHORT4 = 19, - VET_INT1 = 20, - VET_INT2 = 21, - VET_INT3 = 22, - VET_INT4 = 23, - VET_UINT1 = 24, - VET_UINT2 = 25, - VET_UINT3 = 26, - VET_UINT4 = 27, - VET_BYTE4 = 28, ///< signed bytes - VET_BYTE4_NORM = 29, ///< signed bytes (normalized to -1..1) - VET_UBYTE4_NORM = 30, ///< unsigned bytes (normalized to 0..1) - VET_SHORT2_NORM = 31, ///< signed shorts (normalized to -1..1) - VET_SHORT4_NORM = 32, - VET_USHORT2_NORM = 33, ///< unsigned shorts (normalized to 0..1) - VET_USHORT4_NORM = 34, - VET_INT_10_10_10_2_NORM = 35, ///< signed int (normalized to 0..1) - VET_COLOUR = VET_UBYTE4_NORM, ///< @deprecated use VET_UBYTE4_NORM - VET_COLOUR_ARGB = VET_UBYTE4_NORM, ///< @deprecated use VET_UBYTE4_NORM - VET_COLOUR_ABGR = VET_UBYTE4_NORM, ///< @deprecated use VET_UBYTE4_NORM - }; - - /** This class declares the usage of a single vertex buffer as a component - of a complete VertexDeclaration. - - Several vertex buffers can be used to supply the input geometry for a - rendering operation, and in each case a vertex buffer can be used in - different ways for different operations; the buffer itself does not - define the semantics (position, normal etc), the VertexElement - class does. - */ - class _OgreExport VertexElement : public VertexDataAlloc - { - private: - /// The offset in the buffer that this element starts at - size_t mOffset; - /// The source vertex buffer, as bound to an index using VertexBufferBinding - unsigned short mSource; - /// Index of the item, only applicable for some elements like texture coords - unsigned short mIndex; - /// The type of element - VertexElementType mType; - /// The meaning of the element - VertexElementSemantic mSemantic; - public: - /// Constructor, should not be called directly, only needed because of list - VertexElement() {} - /// Constructor, should not be called directly, call VertexDeclaration::addElement - VertexElement(unsigned short source, size_t offset, VertexElementType theType, - VertexElementSemantic semantic, unsigned short index = 0); - /// Gets the vertex buffer index from where this element draws it's values - unsigned short getSource(void) const { return mSource; } - /// Gets the offset into the buffer where this element starts - size_t getOffset(void) const { return mOffset; } - /// Gets the data format of this element - VertexElementType getType(void) const { return mType; } - /// Gets the meaning of this element - VertexElementSemantic getSemantic(void) const { return mSemantic; } - /// Gets the index of this element, only applicable for repeating elements - unsigned short getIndex(void) const { return mIndex; } - /// Gets the size of this element in bytes - size_t getSize(void) const; - /// Utility method for helping to calculate offsets - static size_t getTypeSize(VertexElementType etype); - /// Utility method which returns the count of values in a given type (result for colors may be counter-intuitive) - static unsigned short getTypeCount(VertexElementType etype); - /** Simple converter function which will return a type large enough to hold 'count' values - of the same type as the values in 'baseType'. The 'baseType' parameter should have the - smallest count available. The return type may have the count rounded up to the next multiple - of 4 bytes. Byte types will always return a 4-count type, while short types will return either - a 2-count or 4-count type. - */ - static VertexElementType multiplyTypeCount(VertexElementType baseType, unsigned short count); - /** Simple converter function which will turn a type into it's single-value (or lowest multiple-value) - equivalent - makes switches on type easier. May give counter-intuitive results with bytes or shorts. - */ - static VertexElementType getBaseType(VertexElementType multiType); - - /// @deprecated do not use - OGRE_DEPRECATED static void convertColourValue(VertexElementType srcType, VertexElementType dstType, uint32* ptr); - - /// @deprecated use ColourValue::getAsABGR() - OGRE_DEPRECATED static uint32 convertColourValue(const ColourValue& src, VertexElementType) - { - return src.getAsABGR(); - } - - /// @deprecated use VET_UBYTE4_NORM - OGRE_DEPRECATED static VertexElementType getBestColourVertexElementType() { return VET_UBYTE4_NORM; } - - inline bool operator== (const VertexElement& rhs) const - { - if (mType != rhs.mType || - mIndex != rhs.mIndex || - mOffset != rhs.mOffset || - mSemantic != rhs.mSemantic || - mSource != rhs.mSource) - return false; - else - return true; - - } - /** Adjusts a pointer to the base of a vertex to point at this element. - - Pointers are passed as a parameter because we can't - rely on covariant return types. - @param pBase Pointer to the start of a vertex in this buffer. - @param pElem Pointer to a pointer which will be set to the start of this element. - */ - template - void baseVertexPointerToElement(void* pBase, T** pElem) const - { - // The only way we can do this is to cast to char* in order to use byte offset - // then cast back to T*. - *pElem = reinterpret_cast(static_cast(pBase) + mOffset); - } - }; - /** This class declares the format of a set of vertex inputs, which - can be issued to the rendering API through a RenderOperation. - - The ordering is important on Direct3D9 with Direct3D 7 grade cards. - Calling closeGapsInSource() will format this VertexDeclaration accordingly. - - Whilst GL and more modern graphics cards in D3D will allow you to defy these rules, - sticking to them will reduce state changes and improve performance on modern APIs as well. - - Like the other classes in this functional area, these declarations should be created and - destroyed using the HardwareBufferManager. - */ - class _OgreExport VertexDeclaration : public VertexDataAlloc - { - public: - /// Defines the list of vertex elements that makes up this declaration - typedef std::list VertexElementList; - protected: - VertexElementList mElementList; - - /** Notify derived class that it is time to invalidate cached state, such as VAO or ID3D11InputLayout */ - virtual void notifyChanged() {} - public: - /// Standard constructor, not you should use HardwareBufferManager::createVertexDeclaration - VertexDeclaration(); - virtual ~VertexDeclaration(); - - /** Get the number of elements in the declaration. */ - size_t getElementCount(void) const { return mElementList.size(); } - /** Gets read-only access to the list of vertex elements. */ - const VertexElementList& getElements(void) const; - /** Get a single element. */ - const VertexElement* getElement(unsigned short index) const; - - /** Sorts the elements in this list to be compatible with D3D7 graphics cards - - the order is as follows: position, blending weights, normals, diffuse colours, specular colours, - texture coordinates - */ - void sort(void); - - /** Remove any gaps in the source buffer list used by this declaration. - - This is useful if you've modified a declaration and want to remove - any gaps in the list of buffers being used. Note, however, that if this - declaration is already being used with a VertexBufferBinding, you will - need to alter that too. This method is mainly useful when reorganising - buffers based on an altered declaration. - - Whilst in theory you have completely full reign over the format of you vertices, in reality - there are some restrictions. D3D7 grade hardware imposes a fixed ordering on the elements which are - pulled from each buffer: - - - VertexElements should be added in the following order, and the order of the elements within any shared - buffer should be as follows: - 1. Positions - 2. Blending weights - 3. Normals - 4. Diffuse colours - 5. Specular colours - 6. Texture coordinates (starting at 0, listed in order, with no gaps) - - You must not have unused gaps in your buffers which are not referenced by any VertexElement - - You must not cause the buffer & offset settings of 2 VertexElements to overlap - - OpenGL and D3D9 compatible hardware are not required to follow these strict limitations, so you might - find, for example that if you broke these rules your application would run under OpenGL and under DirectX on - recent cards, but it is not guaranteed to run on older hardware under DirectX unless you stick to the above - rules. - @note - This will also call sort() - */ - void closeGapsInSource(void); - - /** Generates a new VertexDeclaration for optimal usage based on the current - vertex declaration, which can be used with VertexData::reorganiseBuffers later - if you wish, or simply used as a template. - - Different buffer organisations and buffer usages will be returned - depending on the parameters passed to this method. - @param skeletalAnimation Whether this vertex data is going to be - skeletally animated - @param vertexAnimation Whether this vertex data is going to be vertex animated - @param vertexAnimationNormals Whether vertex data animation is going to include normals animation - */ - VertexDeclaration* getAutoOrganisedDeclaration(bool skeletalAnimation, - bool vertexAnimation, bool vertexAnimationNormals) const; - - /** Gets the index of the highest source value referenced by this declaration. */ - unsigned short getMaxSource(void) const; - - - - /** Adds a new VertexElement to this declaration. - - This method adds a single element (positions, normals etc) to the end of the - vertex declaration. Please read the information in VertexDeclaration about - the importance of ordering and structure for compatibility with older D3D drivers. - @param source The binding index of HardwareVertexBuffer which will provide the source for this element. - See VertexBufferBinding for full information. - @param offset The offset in bytes where this element is located in the buffer - @param theType The data format of the element (3 floats, a colour etc) - @param semantic The meaning of the data (position, normal, diffuse colour etc) - @param index Optional index for multi-input elements like texture coordinates - @return A reference to the VertexElement added. - */ - const VertexElement& addElement(unsigned short source, size_t offset, VertexElementType theType, - VertexElementSemantic semantic, unsigned short index = 0); - /** Inserts a new VertexElement at a given position in this declaration. - - This method adds a single element (positions, normals etc) at a given position in this - vertex declaration. Please read the information in VertexDeclaration about - the importance of ordering and structure for compatibility with older D3D drivers. - @param atPosition Position where the new element is inserted - @param source The binding index of HardwareVertexBuffer which will provide the source for this element. - See VertexBufferBinding for full information. - @param offset The offset in bytes where this element is located in the buffer - @param theType The data format of the element (3 floats, a colour etc) - @param semantic The meaning of the data (position, normal, diffuse colour etc) - @param index Optional index for multi-input elements like texture coordinates - @return A reference to the VertexElement added. - */ - const VertexElement& insertElement(unsigned short atPosition, - unsigned short source, size_t offset, VertexElementType theType, - VertexElementSemantic semantic, unsigned short index = 0); - - /** Remove the element at the given index from this declaration. */ - void removeElement(unsigned short elem_index); - - /** Remove the element with the given semantic and usage index. - - In this case 'index' means the usage index for repeating elements such - as texture coordinates. For other elements this will always be 0 and does - not refer to the index in the vector. - */ - void removeElement(VertexElementSemantic semantic, unsigned short index = 0); - - /** Remove all elements. */ - void removeAllElements(void); - - /** Modify an element in-place, params as addElement. - - Please read the information in VertexDeclaration about - the importance of ordering and structure for compatibility with older D3D drivers. - */ - void modifyElement(unsigned short elem_index, unsigned short source, size_t offset, VertexElementType theType, - VertexElementSemantic semantic, unsigned short index = 0); - - /** Finds a VertexElement with the given semantic and index - - @return The VertexElement or null, if the element is not found - */ - const VertexElement* findElementBySemantic(VertexElementSemantic sem, unsigned short index = 0) const; - /** Based on the current elements, gets the size of the vertex for a given buffer source. - @param source The buffer binding index for which to get the vertex size. - */ - - /** Gets a list of elements which use a given source. - - Note that the list of elements is returned by value therefore is separate from - the declaration as soon as this method returns. - */ - VertexElementList findElementsBySource(unsigned short source) const; - - /** Gets the vertex size defined by this declaration for a given source. */ - size_t getVertexSize(unsigned short source) const; - - /** Return the index of the next free texture coordinate set which may be added - to this declaration. - */ - unsigned short getNextFreeTextureCoordinate() const; - - /** Clones this declaration. - @param mgr Optional HardwareBufferManager to use for creating the clone - (if null, use the current default). - */ - VertexDeclaration* clone(HardwareBufferManagerBase* mgr = 0) const OGRE_NODISCARD; - - inline bool operator== (const VertexDeclaration& rhs) const - { - if (mElementList.size() != rhs.mElementList.size()) - return false; - - VertexElementList::const_iterator i, iend, rhsi, rhsiend; - iend = mElementList.end(); - rhsiend = rhs.mElementList.end(); - rhsi = rhs.mElementList.begin(); - for (i = mElementList.begin(); i != iend && rhsi != rhsiend; ++i, ++rhsi) - { - if ( !(*i == *rhsi) ) - return false; - } - - return true; - } - inline bool operator!= (const VertexDeclaration& rhs) const - { - return !(*this == rhs); - } - - }; - - /** Records the state of all the vertex buffer bindings required to provide a vertex declaration - with the input data it needs for the vertex elements. - - Why do we have this binding list rather than just have VertexElement referring to the - vertex buffers direct? Well, in the underlying APIs, binding the vertex buffers to an - index (or 'stream') is the way that vertex data is linked, so this structure better - reflects the realities of that. In addition, by separating the vertex declaration from - the list of vertex buffer bindings, it becomes possible to reuse bindings between declarations - and vice versa, giving opportunities to reduce the state changes required to perform rendering. - @par - Like the other classes in this functional area, these binding maps should be created and - destroyed using the HardwareBufferManager. - */ - class _OgreExport VertexBufferBinding : public VertexDataAlloc - { - public: - /// Defines the vertex buffer bindings used as source for vertex declarations - typedef std::map VertexBufferBindingMap; - private: - VertexBufferBindingMap mBindingMap; - mutable unsigned short mHighIndex; - public: - /// Constructor, should not be called direct, use HardwareBufferManager::createVertexBufferBinding - VertexBufferBinding(); - ~VertexBufferBinding(); - /** Set a binding, associating a vertex buffer with a given index. - - If the index is already associated with a vertex buffer, - the association will be replaced. This may cause the old buffer - to be destroyed if nothing else is referring to it. - You should assign bindings from 0 and not leave gaps, although you can - bind them in any order. - */ - void setBinding(unsigned short index, const HardwareVertexBufferSharedPtr& buffer); - /** Removes an existing binding. */ - void unsetBinding(unsigned short index); - - /** Removes all the bindings. */ - void unsetAllBindings(void); - - /// Gets a read-only version of the buffer bindings - const VertexBufferBindingMap& getBindings(void) const; - - /// Gets the buffer bound to the given source index - const HardwareVertexBufferSharedPtr& getBuffer(unsigned short index) const; - /// Gets whether a buffer is bound to the given source index - bool isBufferBound(unsigned short index) const; - - size_t getBufferCount(void) const { return mBindingMap.size(); } - - /** Gets the highest index which has already been set, plus 1. - - This is to assist in binding the vertex buffers such that there are - not gaps in the list. - */ - unsigned short getNextIndex(void) const { return mHighIndex++; } - - /** Gets the last bound index. - */ - unsigned short getLastBoundIndex(void) const; - - typedef std::map BindingIndexMap; - - /** Check whether any gaps in the bindings. - */ - bool hasGaps(void) const; - - /** Remove any gaps in the bindings. - - This is useful if you've removed vertex buffer from this vertex buffer - bindings and want to remove any gaps in the bindings. Note, however, - that if this bindings is already being used with a VertexDeclaration, - you will need to alter that too. This method is mainly useful when - reorganising buffers manually. - @param - bindingIndexMap To be retrieve the binding index map that used to - translation old index to new index; will be cleared by this method - before fill-in. - */ - void closeGaps(BindingIndexMap& bindingIndexMap); - - /// Returns true if this binding has an element that contains instance data - bool hasInstanceData() const - { - for (const auto& b : mBindingMap) - if (b.second->isInstanceData()) - return true; - return false; - } - }; - /** @} */ - /** @} */ - - - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreHeaderPrefix.h b/OgreMain/include/OgreHeaderPrefix.h deleted file mode 100644 index 56b17d0bf15..00000000000 --- a/OgreMain/include/OgreHeaderPrefix.h +++ /dev/null @@ -1,49 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ -// ATTENTION: No header guard as this header is meant to be included -// multiple times. -//#ifndef __OgreHeaderPrefix_H__ -//#define __OgreHeaderPrefix_H__ - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC - -// Save warnings state -# pragma warning (push) - -// disable: " needs to have dll-interface to be used by clients' -// Happens on STL member variables which are not public therefore is ok -# pragma warning (disable : 4251) - -// disable: "non dll-interface class used as base for dll-interface class" -// Happens when deriving from std::exception -# pragma warning (disable : 4275) - -#endif - - -//#endif - - diff --git a/OgreMain/include/OgreHeaderSuffix.h b/OgreMain/include/OgreHeaderSuffix.h deleted file mode 100644 index 9ce71fbfe60..00000000000 --- a/OgreMain/include/OgreHeaderSuffix.h +++ /dev/null @@ -1,40 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ -// ATTENTION: No header guard as this header is meant to be included -// multiple times. -//#ifndef __OgreHeaderSuffix_H__ -//#define __OgreHeaderSuffix_H__ - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC - -// restore previous warnings settings -# pragma warning (pop) - - -#endif - - -//#endif diff --git a/OgreMain/include/OgreHighLevelGpuProgram.h b/OgreMain/include/OgreHighLevelGpuProgram.h deleted file mode 100644 index 4a91603e076..00000000000 --- a/OgreMain/include/OgreHighLevelGpuProgram.h +++ /dev/null @@ -1,154 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __HighLevelGpuProgram_H__ -#define __HighLevelGpuProgram_H__ - -#include "OgrePrerequisites.h" -#include "OgreGpuProgram.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - /** Abstract base class representing a high-level program (a vertex or - fragment program). - - High-level programs are vertex and fragment programs written in a high-level - language such as Cg or HLSL, and as such do not require you to write assembler code - like GpuProgram does. However, the high-level program does eventually - get converted (compiled) into assembler and then eventually microcode which is - what runs on the GPU. As well as the convenience, some high-level languages like Cg allow - you to write a program which will operate under both Direct3D and OpenGL, something - which you cannot do with just GpuProgram (which requires you to write 2 programs and - use each in a Technique to provide cross-API compatibility). Ogre will be creating - a GpuProgram for you based on the high-level program, which is compiled specifically - for the API being used at the time, but this process is transparent. - @par - You cannot create high-level programs direct - use HighLevelGpuProgramManager instead. - Plugins can register new implementations of HighLevelGpuProgramFactory in order to add - support for new languages without requiring changes to the core Ogre API. To allow - custom parameters to be set, this class extends StringInterface - the application - can query on the available custom parameters and get/set them without having to - link specifically with it. - */ - class _OgreExport HighLevelGpuProgram : public GpuProgram - { - protected: - /// Whether the high-level program (and it's parameter defs) is loaded - bool mHighLevelLoaded; - /// Have we built the name->index parameter map yet? - bool mConstantDefsBuilt; - /// The underlying assembler program - GpuProgramPtr mAssemblerProgram; - /// Preprocessor options - String mPreprocessorDefines; - /// Entry point for this program - String mEntryPoint; - - /// in-situ parsing of defines - static std::vector> parseDefines(String& defines); - - String appendBuiltinDefines(String defines); - - /// Internal load high-level portion if not loaded - virtual void loadHighLevel(void); - /// Internal unload high-level portion if loaded - virtual void unloadHighLevel(void); - /** Internal method for creating an appropriate low-level program from this - high-level program, must be implemented by subclasses. */ - virtual void createLowLevelImpl(void) = 0; - /// Internal unload implementation, must be implemented by subclasses - virtual void unloadHighLevelImpl(void) = 0; - /// Populate the passed parameters with name->index map - void populateParameterNames(const GpuProgramParametersSharedPtr& params); - /** Build the constant definition map, must be overridden. - @note The implementation must fill in the (inherited) mConstantDefs field at a minimum, - and if the program requires that parameters are bound using logical - parameter indexes then the mLogicalToPhysical and mIntLogicalToPhysical - maps must also be populated. - */ - virtual void buildConstantDefinitions() = 0; - - /** @copydoc Resource::loadImpl */ - void loadImpl() override; - /** @copydoc Resource::unloadImpl */ - void unloadImpl() override; - - void setupBaseParamDictionary() override; - public: - /** Constructor, should be used only by factory classes. */ - HighLevelGpuProgram(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual = false, ManualResourceLoader* loader = 0); - ~HighLevelGpuProgram(); - - - /** Creates a new parameters object compatible with this program definition. - - Unlike low-level assembly programs, parameters objects are specific to the - program and therefore must be created from it rather than by the - HighLevelGpuProgramManager. This method creates a new instance of a parameters - object containing the definition of the parameters this program understands. - */ - GpuProgramParametersSharedPtr createParameters(void) override; - /** @copydoc GpuProgram::_getBindingDelegate */ - GpuProgram* _getBindingDelegate(void) override { return mAssemblerProgram.get(); } - - /** Get the full list of GpuConstantDefinition instances. - @note - Only available if this parameters object has named parameters. - */ - const GpuNamedConstants& getConstantDefinitions() override; - - size_t calculateSize(void) const override; - - /** Sets the preprocessor defines used to compile the program. */ - void setPreprocessorDefines(const String& defines) { mPreprocessorDefines = defines; } - /** Gets the preprocessor defines used to compile the program. */ - const String& getPreprocessorDefines(void) const { return mPreprocessorDefines; } - - /** Sets the entry point for this program i.e, the first method called. */ - void setEntryPoint(const String& entryPoint) { mEntryPoint = entryPoint; } - /** Gets the entry point defined for this program. */ - const String& getEntryPoint(void) const { return mEntryPoint; } - - /// Scan the source for \#include and replace with contents from OGRE resources - static String _resolveIncludes(const String& source, Resource* resourceBeingLoaded, const String& fileName, bool supportsFilename = false); - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreHighLevelGpuProgramManager.h b/OgreMain/include/OgreHighLevelGpuProgramManager.h deleted file mode 100644 index c462072069a..00000000000 --- a/OgreMain/include/OgreHighLevelGpuProgramManager.h +++ /dev/null @@ -1 +0,0 @@ -#include "OgreGpuProgramManager.h" \ No newline at end of file diff --git a/OgreMain/include/OgreImage.h b/OgreMain/include/OgreImage.h deleted file mode 100644 index 7464e53cde9..00000000000 --- a/OgreMain/include/OgreImage.h +++ /dev/null @@ -1,481 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _Image_H__ -#define _Image_H__ - -#include "OgrePrerequisites.h" -#include "OgreCommon.h" -#include "OgrePixelFormat.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Image - * @{ - */ - - enum ImageFlags - { - IF_COMPRESSED = 0x00000001, - IF_CUBEMAP = 0x00000002, - IF_3D_TEXTURE = 0x00000004 - }; - /** Class representing an image file. - - The Image class usually holds uncompressed image data and is the - only object that can be loaded in a texture. Image objects handle - image data decoding themselves by the means of locating the correct - Codec object for each data type. - @par - Typically, you would want to use an Image object to load a texture - when extra processing needs to be done on an image before it is - loaded or when you want to blit to an existing texture. - */ - class _OgreExport Image : public ImageAlloc - { - friend class ImageCodec; - public: - /** Standard constructor. - * - * allocates a buffer of given size if buffer pointer is NULL. - */ - Image(PixelFormat format = PF_UNKNOWN, uint32 width = 0, uint32 height = 0, uint32 depth = 1, - uchar* buffer = NULL, bool autoDelete = true); - /** Copy-constructor - copies all the data from the target image. - */ - Image( const Image &img ); - - /** - * allocates a buffer of given size if needed - * - * - If the current allocation is equal to the requested size, this does nothing - * - Otherwise any current allocation is freed, and memory of specified size is allocated - * - * @see loadDynamicImage - */ - void create(PixelFormat format, uint32 width, uint32 height, uint32 depth = 1, uint32 numFaces = 1, - uint32 numMipMaps = 0); - - /** Standard destructor. - */ - ~Image(); - - /** Assignment operator - copies all the data from the target image. - */ - Image & operator = ( const Image & img ); - - /** - * sets all pixels to the specified colour - * - * format conversion is performed as needed - */ - void setTo(const ColourValue& col); - - /** Flips (mirrors) the image around the Y-axis. - - An example of an original and flipped image: -
                
-                originalimg
-                00000000000
-                00000000000
-                00000000000
-                00000000000
-                00000000000
-                ------------> flip axis
-                00000000000
-                00000000000
-                00000000000
-                00000000000
-                00000000000
-                originalimg
-                
- */ - Image & flipAroundY(); - - /** Flips (mirrors) the image around the X-axis. - - An example of an original and flipped image: -
-                        flip axis
-                            |
-                originalimg|gmilanigiro
-                00000000000|00000000000
-                00000000000|00000000000
-                00000000000|00000000000
-                00000000000|00000000000
-                00000000000|00000000000
-                
- */ - Image & flipAroundX(); - - /** Stores a pointer to raw data in memory. The pixel format has to be specified. - - This method loads an image into memory held in the object. The - pixel format will be either greyscale or RGB with an optional - Alpha component. - The type can be determined by calling getFormat(). - @note - Whilst typically your image is likely to be a simple 2D image, - you can define complex images including cube maps, volume maps, - and images including custom mip levels. The layout of the - internal memory should be: -
  • face 0, mip 0 (top), width x height (x depth)
  • -
  • face 0, mip 1, width/2 x height/2 (x depth/2)
  • -
  • face 0, mip 2, width/4 x height/4 (x depth/4)
  • -
  • .. remaining mips for face 0 ..
  • -
  • face 1, mip 0 (top), width x height (x depth)
  • .. and so on. -
- Of course, you will never have multiple faces (cube map) and - depth too. - @param data - The data pointer - @param width - Width of image - @param height - Height of image - @param depth - Image Depth (in 3d images, numbers of layers, otherwise 1) - @param format - Pixel Format - @param autoDelete - If memory associated with this buffer is to be destroyed - with the Image object. Note: it's important that if you set - this option to true, that you allocated the memory using OGRE_ALLOC_T - with a category of MEMCATEGORY_GENERAL to ensure the freeing of memory - matches up. - @param numFaces - The number of faces the image data has inside (6 for cubemaps, 1 otherwise) - @param numMipMaps - The number of mipmaps the image data has inside - @note - The memory associated with this buffer is NOT destroyed with the - Image object, unless autoDelete is set to true. - - The size of the buffer must be numFaces * PixelUtil::getMemorySize(width, height, depth, format) - */ - Image& loadDynamicImage(uchar* data, uint32 width, uint32 height, uint32 depth, PixelFormat format, - bool autoDelete = false, uint32 numFaces = 1, uint32 numMipMaps = 0); - - /// @overload - Image& loadDynamicImage(uchar* data, uint32 width, uint32 height, PixelFormat format) - { - return loadDynamicImage(data, width, height, 1, format); - } - /** Loads raw data from a stream. See the function - loadDynamicImage for a description of the parameters. - - The size of the buffer must be numFaces * PixelUtil::getMemorySize(width, height, depth, format) - @note - Whilst typically your image is likely to be a simple 2D image, - you can define complex images including cube maps - and images including custom mip levels. The layout of the - internal memory should be: -
  • face 0, mip 0 (top), width x height (x depth)
  • -
  • face 0, mip 1, width/2 x height/2 (x depth/2)
  • -
  • face 0, mip 2, width/4 x height/4 (x depth/4)
  • -
  • .. remaining mips for face 0 ..
  • -
  • face 1, mip 0 (top), width x height (x depth)
  • .. and so on. -
- Of course, you will never have multiple faces (cube map) and - depth too. - */ - Image& loadRawData(const DataStreamPtr& stream, uint32 width, uint32 height, uint32 depth, - PixelFormat format, uint32 numFaces = 1, uint32 numMipMaps = 0); - /// @overload - Image& loadRawData(const DataStreamPtr& stream, uint32 width, uint32 height, PixelFormat format) - { - return loadRawData(stream, width, height, 1, format); - } - - /** Loads an image file. - - This method loads an image into memory. Any format for which - an associated ImageCodec is registered can be loaded. - This can include complex formats like DDS with embedded custom - mipmaps, cube faces and volume textures. - The type can be determined by calling getFormat(). - @param - filename Name of an image file to load. - @param - groupName Name of the resource group to search for the image - @note - The memory associated with this buffer is destroyed with the - Image object. - */ - Image & load( const String& filename, const String& groupName ); - - /** Loads an image file from a stream. - - This method works in the same way as the filename-based load - method except it loads the image from a DataStream object. - This DataStream is expected to contain the - encoded data as it would be held in a file. - Any format for which an associated ImageCodec is registered - can be loaded. - This can include complex formats like DDS with embedded custom - mipmaps, cube faces and volume textures. - The type can be determined by calling getFormat(). - @param - stream The source data. - @param - type The type of the image. Used to decide what decompression - codec to use. Can be left blank if the stream data includes - a header to identify the data. - @see - Image::load( const String& filename ) - */ - Image & load(const DataStreamPtr& stream, const String& type = BLANKSTRING ); - - /** Utility method to combine 2 separate images into this one, with the first - image source supplying the RGB channels, and the second image supplying the - alpha channel (as luminance or separate alpha). - @param rgbFilename Filename of image supplying the RGB channels (any alpha is ignored) - @param alphaFilename Filename of image supplying the alpha channel. If a luminance image the - single channel is used directly, if an RGB image then the values are - converted to greyscale. - @param groupName The resource group from which to load the images - @param format The destination format - */ - Image & loadTwoImagesAsRGBA(const String& rgbFilename, const String& alphaFilename, - const String& groupName, PixelFormat format = PF_BYTE_RGBA); - - /** Utility method to combine 2 separate images into this one, with the first - image source supplying the RGB channels, and the second image supplying the - alpha channel (as luminance or separate alpha). - @param rgbStream Stream of image supplying the RGB channels (any alpha is ignored) - @param alphaStream Stream of image supplying the alpha channel. If a luminance image the - single channel is used directly, if an RGB image then the values are - converted to greyscale. - @param format The destination format - @param rgbType The type of the RGB image. Used to decide what decompression - codec to use. Can be left blank if the stream data includes - a header to identify the data. - @param alphaType The type of the alpha image. Used to decide what decompression - codec to use. Can be left blank if the stream data includes - a header to identify the data. - */ - Image& loadTwoImagesAsRGBA(const DataStreamPtr& rgbStream, const DataStreamPtr& alphaStream, - PixelFormat format = PF_BYTE_RGBA, - const String& rgbType = BLANKSTRING, - const String& alphaType = BLANKSTRING); - - /** Utility method to combine 2 separate images into this one, with the first - image source supplying the RGB channels, and the second image supplying the - alpha channel (as luminance or separate alpha). - @param rgb Image supplying the RGB channels (any alpha is ignored) - @param alpha Image supplying the alpha channel. If a luminance image the - single channel is used directly, if an RGB image then the values are - converted to greyscale. - @param format The destination format - */ - Image & combineTwoImagesAsRGBA(const Image& rgb, const Image& alpha, PixelFormat format = PF_BYTE_RGBA); - - - /** Save the image as a file. - - Saving and loading are implemented by back end (sometimes third - party) codecs. Implemented saving functionality is more limited - than loading in some cases. Particularly DDS file format support - is currently limited to true colour or single channel float32, - square, power of two textures with no mipmaps. Volumetric support - is currently limited to DDS files. - */ - void save(const String& filename); - - /** Encode the image and return a stream to the data. - @param formatextension An extension to identify the image format - to encode into, e.g. "jpg" or "png" - */ - DataStreamPtr encode(const String& formatextension); - - /** Returns a pointer to the internal image buffer at the specified pixel location. - - Be careful with this method. You will almost certainly - prefer to use getPixelBox, especially with complex images - which include many faces or custom mipmaps. - */ - uchar* getData(uint32 x = 0, uint32 y = 0, uint32 z = 0) - { - assert((!mBuffer && (x + y + z) == 0) || (x < mWidth && y < mHeight && z < mDepth)); - return mBuffer + mPixelSize * (z * mWidth * mHeight + mWidth * y + x); - } - - /// @overload - const uchar* getData(uint32 x = 0, uint32 y = 0, uint32 z = 0) const - { - assert(mBuffer); - assert(x < mWidth && y < mHeight && z < mDepth); - return mBuffer + mPixelSize * (z * mWidth * mHeight + mWidth * y + x); - } - - /// @overload - template T* getData(uint32 x = 0, uint32 y = 0, uint32 z = 0) - { - return reinterpret_cast(getData(x, y, z)); - } - - /// @overload - template const T* getData(uint32 x = 0, uint32 y = 0, uint32 z = 0) const - { - return reinterpret_cast(getData(x, y, z)); - } - - /** Returns the size of the data buffer in bytes - */ - size_t getSize() const { return mBufSize; } - - /** Returns the number of mipmaps contained in the image. - */ - uint32 getNumMipmaps() const { return mNumMipmaps; } - - /** Returns true if the image has the appropriate flag set. - */ - bool hasFlag(const ImageFlags imgFlag) const { return (mFlags & imgFlag) != 0; } - - /** Gets the width of the image in pixels. - */ - uint32 getWidth(void) const { return mWidth; } - - /** Gets the height of the image in pixels. - */ - uint32 getHeight(void) const { return mHeight; } - - /** Gets the depth of the image. - */ - uint32 getDepth(void) const { return mDepth; } - - /** Get the number of faces of the image. This is usually 6 for a cubemap, and - 1 for a normal image. - */ - uint32 getNumFaces(void) const { return hasFlag(IF_CUBEMAP) ? 6 : 1; } - - /** Gets the physical width in bytes of each row of pixels. - */ - size_t getRowSpan(void) const { return mWidth * mPixelSize; } - - /** Returns the image format. - */ - PixelFormat getFormat() const { return mFormat; } - - /** Returns the number of bits per pixel. - */ - uchar getBPP() const { return mPixelSize * 8;} - - /** Returns true if the image has an alpha component. - */ - bool getHasAlpha() const; - - /** Does gamma adjustment. - @note - Basic algo taken from Titan Engine, copyright (c) 2000 Ignacio - Castano Iguado - */ - static void applyGamma( uchar *buffer, Real gamma, size_t size, uchar bpp ); - - /** - * Get colour value from a certain location in the image. The z coordinate - * is only valid for cubemaps and volume textures. This uses the first (largest) - * mipmap. - */ - ColourValue getColourAt(uint32 x, uint32 y, uint32 z) const; - - /** - * Set colour value at a certain location in the image. The z coordinate - * is only valid for cubemaps and volume textures. This uses the first (largest) - * mipmap. - */ - void setColourAt(ColourValue const &cv, uint32 x, uint32 y, uint32 z); - - /** - * Get a PixelBox encapsulating the image data of a mipmap - */ - PixelBox getPixelBox(uint32 face = 0, uint32 mipmap = 0) const; - - /// Delete all the memory held by this image, if owned by this image (not dynamic) - void freeMemory(); - - enum Filter - { - FILTER_NEAREST, - FILTER_LINEAR, - FILTER_BILINEAR = FILTER_LINEAR - }; - /** Scale a 1D, 2D or 3D image volume. - @param src PixelBox containing the source pointer, dimensions and format - @param dst PixelBox containing the destination pointer, dimensions and format - @param filter Which filter to use - @remarks This function can do pixel format conversion in the process. - @note dst and src can point to the same PixelBox object without any problem - */ - static void scale(const PixelBox &src, const PixelBox &dst, Filter filter = FILTER_BILINEAR); - - /** Resize a 2D image, applying the appropriate filter. */ - void resize(ushort width, ushort height, Filter filter = FILTER_BILINEAR); - - /// Static function to calculate size in bytes from the number of mipmaps, faces and the dimensions - static size_t calculateSize(uint32 mipmaps, uint32 faces, uint32 width, uint32 height, uint32 depth, PixelFormat format); - - /// Static function to get an image type string from a stream via magic numbers - OGRE_DEPRECATED static String getFileExtFromMagic(DataStreamPtr stream); - - private: - /// The width of the image in pixels - uint32 mWidth; - /// The height of the image in pixels - uint32 mHeight; - /// The depth of the image - uint32 mDepth; - /// The number of mipmaps the image contains - uint32 mNumMipmaps; - /// The size of the image buffer - size_t mBufSize; - /// Image specific flags. - int mFlags; - - /// The pixel format of the image - PixelFormat mFormat; - - uchar* mBuffer; - /// The number of bytes per pixel - uchar mPixelSize; - /// A bool to determine if we delete the buffer or the calling app does - bool mAutoDelete; - }; - - typedef std::vector ImagePtrList; - typedef std::vector ConstImagePtrList; - - /** @} */ - /** @} */ - -} // namespace - -#endif diff --git a/OgreMain/include/OgreImageCodec.h b/OgreMain/include/OgreImageCodec.h deleted file mode 100644 index 88fca12c7b6..00000000000 --- a/OgreMain/include/OgreImageCodec.h +++ /dev/null @@ -1,65 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ImageCodec_H__ -#define _ImageCodec_H__ - -#include "OgreCodec.h" -#include "OgrePixelFormat.h" -#include "OgreBitwise.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Image - * @{ - */ - /** Codec specialized in images. - */ - class _OgreExport ImageCodec : public Codec - { - protected: - static void flipEndian(void* pData, size_t size, size_t count) - { -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - Bitwise::bswapChunks(pData, size, count); -#endif - } - static void flipEndian(void* pData, size_t size) - { -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - Bitwise::bswapBuffer(pData, size); -#endif - } - }; - /** @} */ - /** @} */ -} // namespace - -#endif diff --git a/OgreMain/include/OgreInstanceBatch.h b/OgreMain/include/OgreInstanceBatch.h deleted file mode 100644 index 8c6fb705fe5..00000000000 --- a/OgreMain/include/OgreInstanceBatch.h +++ /dev/null @@ -1,364 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __InstanceBatch_H__ -#define __InstanceBatch_H__ - -#include "OgrePrerequisites.h" -#include "OgreRenderOperation.h" -#include "OgreRenderable.h" -#include "OgreMovableObject.h" -#include "OgreMesh.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - - /** InstanceBatch forms part of the new Instancing system - This is an abstract class that must be derived to implement different instancing techniques - (@see InstanceManager::InstancingTechnique) - OGRE wasn't truly thought for instancing. OGRE assumes that either: - a. One MovableObject -> No Renderable - b. One MovableObject -> One Renderable - c. One MovableObject -> Many Renderable. - However, instances work on reverse: Many MovableObject have the same Renderable. - Instancing is already difficult to cull by a CPU, but the main drawback from this assumption - is that it makes it even harder to take advantage from OGRE's culling capabilities - (i.e. @see OctreeSceneManager) - @par - To workaround this problem, InstanceBatch updates on almost every frame, - growing the bounding box to fit all instances that are not being culled individually. - This helps by avoiding a huge bbox that may cover the whole scene, which decreases shadow - quality considerably (as it is seen as large shadow receiver) - Furthermore, if no individual instance is visible, the InstanceBatch switches it's visibility - (@see MovableObject::setVisible) to avoid sending this Renderable to the GPU. This happens because - even when no individual instance is visible, their merged bounding box may cause OGRE to think - the batch is visible (i.e. the camera is looking between object A & B, but A & B aren't visible) - @par - As it happens with instancing in general, all instanced entities from the same batch will share - the same textures and materials - @par - Each InstanceBatch preallocates a fixed amount of mInstancesPerBatch instances once it's been - built (@see build, @see buildFrom). - @see createInstancedEntity and @see removeInstancedEntity on how to retrieve those instances - remove them from scene. - Note that, on GPU side, removing an instance from scene doesn't save GPU cycles on what - respects vertex shaders, but saves a little fillrate and pixel shaders; unless all instances - are removed, which saves GPU. - For more information, @see InstancedEntity - For information on how Ogre manages multiple Instance batches, @see InstanceManager - - - Design discussion webpage - @author - Matias N. Goldberg ("dark_sylinc") - @version - 1.0 - */ - class _OgreExport InstanceBatch : public Renderable, public MovableObject - { - public: - typedef std::vector InstancedEntityVec; - typedef std::vector CustomParamsVec; - protected: - typedef TransformBase<3, float> Matrix3x4f; - RenderOperation mRenderOperation; - size_t mInstancesPerBatch; - - InstanceManager *mCreator; - - MaterialPtr mMaterial; - - MeshPtr mMeshReference; - Mesh::IndexMap const *mIndexToBoneMap; - - //InstancedEntities are all allocated at build time and kept as "unused" - //when they're requested, they're removed from there when requested, - //and put back again when they're no longer needed - //Note each InstancedEntity has a unique ID ranging from [0; mInstancesPerBatch) - InstancedEntityVec mInstancedEntities; - InstancedEntityVec mUnusedEntities; - - ///@see InstanceManager::setNumCustomParams(). Because this may not even be used, - ///our implementations keep the params separate from the InstancedEntity to lower - ///the memory overhead. They default to Vector4::ZERO - CustomParamsVec mCustomParams; - - /// This bbox contains all (visible) instanced entities - AxisAlignedBox mFullBoundingBox; - Real mBoundingRadius; - bool mBoundsDirty; - bool mBoundsUpdated; //Set to false by derived classes that need it - Camera *mCurrentCamera; - - bool mDirtyAnimation; //Set to false at start of each _updateRenderQueue - - /// False if a technique doesn't support skeletal animation - bool mTechnSupportsSkeletal; - - /// Last update camera distance frame number - mutable unsigned long mCameraDistLastUpdateFrameNumber; - /// Cached distance to last camera for getSquaredViewDepth - mutable Real mCachedCameraDist; - /// The camera for which the cached distance is valid - mutable const Camera *mCachedCamera; - - /// Tells that the list of entity instances with shared transforms has changed - bool mTransformSharingDirty; - - /// When true remove the memory of the VertexData we've created because no one else will - bool mRemoveOwnVertexData; - /// When true remove the memory of the IndexData we've created because no one else will - bool mRemoveOwnIndexData; - - virtual void setupVertices( const SubMesh* baseSubMesh ) = 0; - virtual void setupIndices( const SubMesh* baseSubMesh ) = 0; - virtual void createAllInstancedEntities(void); - void deleteAllInstancedEntities(void); - virtual void deleteUnusedInstancedEntities(void); - /// Creates a new InstancedEntity instance - virtual InstancedEntity* generateInstancedEntity(size_t num); - - /** Takes an array of 3x4 matrices and makes it camera relative. Note the second argument - takes number of floats in the array, not number of matrices. Assumes mCachedCamera - contains the camera which is about to be rendered to. - */ - void makeMatrixCameraRelative3x4( Matrix3x4f *mat3x4, size_t count ); - - /// Returns false on errors that would prevent building this batch from the given submesh - virtual bool checkSubMeshCompatibility( const SubMesh* baseSubMesh ); - - void updateVisibility(void); - - /** @see _defragmentBatch */ - void defragmentBatchNoCull( InstancedEntityVec &usedEntities, CustomParamsVec &usedParams ); - - /** @see _defragmentBatch - This one takes the entity closest to the minimum corner of the bbox, then starts - gathering entities closest to this entity. There might be much better algorithms (i.e. - involving space partition), but this one is simple and works well enough - */ - void defragmentBatchDoCull( InstancedEntityVec &usedEntities, CustomParamsVec &usedParams ); - - public: - InstanceBatch( InstanceManager *creator, MeshPtr &meshReference, const MaterialPtr &material, - size_t instancesPerBatch, const Mesh::IndexMap *indexToBoneMap, - const String &batchName ); - virtual ~InstanceBatch(); - - MeshPtr& _getMeshRef() { return mMeshReference; } - - /** Raises an exception if trying to change it after being built - */ - void _setInstancesPerBatch( size_t instancesPerBatch ); - - const Mesh::IndexMap* _getIndexToBoneMap() const { return mIndexToBoneMap; } - - /** Returns true if this technique supports skeletal animation - - A virtual function could have been used, but using a simple variable overridden - by the derived class is faster than virtual call overhead. And both are clean - ways of implementing it. - */ - bool _supportsSkeletalAnimation() const { return mTechnSupportsSkeletal; } - - /** @see InstanceManager::updateDirtyBatches */ - void _updateBounds(void); - - /** Some techniques have a limit on how many instances can be done. - Sometimes even depends on the material being used. - @par - Note this is a helper function, as such it takes a submesh base to compute - the parameters, instead of using the object's own. This allows - querying for a technique without requiring to actually build it. - @param baseSubMesh The base submesh that will be using to build it. - @param flags Flags to pass to the InstanceManager. @see InstanceManagerFlags - @return The max instances limit - */ - virtual size_t calculateMaxNumInstances( const SubMesh *baseSubMesh, uint16 flags ) const = 0; - - /** Constructs all the data needed to use this batch, as well as the - InstanceEntities. Placed here because in the constructor virtual - tables may not have been yet filled. - @param baseSubMesh A sub mesh which the instances will be based upon from - - Call this only ONCE. This is done automatically by Ogre::InstanceManager - Caller is responsible for freeing buffers in this RenderOperation - Buffers inside the RenderOp may be null if the built failed. - @return - A render operation which is very useful to pass to other InstanceBatches - (@see buildFrom) so that they share the same vertex buffers and indices, - when possible - */ - virtual RenderOperation build( const SubMesh* baseSubMesh ); - - /** Instancing consumes significantly more GPU memory than regular rendering - methods. However, multiple batches can share most, if not all, of the - vertex & index buffers to save memory. - Derived classes are free to overload this method to manipulate what to - reference from Render Op. - For example, Hardware based instancing uses it's own vertex buffer for the - last source binding, but shares the other sources. - @param baseSubMesh A sub mesh which the instances will be based upon from - @param renderOperation The RenderOp to reference. - - Caller is responsible for freeing buffers passed as input arguments - This function replaces the need to call build() - */ - virtual void buildFrom( const SubMesh *baseSubMesh, const RenderOperation &renderOperation ); - - const Ogre::MeshPtr& _getMeshReference(void) const { return mMeshReference; } - - /** @return true if it can not create more InstancedEntities - (Num InstancedEntities == mInstancesPerBatch) - */ - bool isBatchFull(void) const { return mUnusedEntities.empty(); } - - /** Returns true if it no instanced entity has been requested or all of them have been removed - */ - bool isBatchUnused(void) const { return mUnusedEntities.size() == mInstancedEntities.size(); } - - /** Fills the input vector with the instances that are currently being used or were requested. - Used for defragmentation, @see InstanceManager::defragmentBatches - */ - void getInstancedEntitiesInUse( InstancedEntityVec &outEntities, CustomParamsVec &outParams ); - - /** @see InstanceManager::defragmentBatches - This function takes InstancedEntities and pushes back all entities it can fit here - Extra entities in mUnusedEntities are destroyed - (so that used + unused = mInstancedEntities.size()) - @param optimizeCulling true will call the DoCull version, false the NoCull - @param usedEntities Array of InstancedEntities to parent with this batch. Those reparented - are removed from this input vector - @param usedParams Array of Custom parameters correlated with the InstancedEntities in usedEntities. - They follow the fate of the entities in that vector. - @remarks: - This function assumes caller holds data to mInstancedEntities! Otherwise - you can get memory leaks. Don't call this directly if you don't know what you're doing! - */ - void _defragmentBatch( bool optimizeCulling, InstancedEntityVec &usedEntities, - CustomParamsVec &usedParams ); - - /** @see InstanceManager::_defragmentBatchDiscard - Destroys unused entities and clears the mInstancedEntity container which avoids leaving - dangling pointers from reparented InstancedEntities - Usually called before deleting this pointer. Don't call directly! - */ - void _defragmentBatchDiscard(void); - - /** Called by InstancedEntity(s) to tell us we need to update the bounds - (we touch the SceneNode so the SceneManager aknowledges such change) - */ - virtual void _boundsDirty(void); - - /** Tells this batch to stop updating animations, positions, rotations, and display - all it's active instances. Currently only InstanceBatchHW & InstanceBatchHW_VTF support it. - This option makes the batch behave pretty much like Static Geometry, but with the GPU RAM - memory advantages (less VRAM, less bandwidth) and not LOD support. Very useful for - billboards of trees, repeating vegetation, etc. - - This function moves a lot of processing time from the CPU to the GPU. If the GPU - is already a bottleneck, you may see a decrease in performance instead! - Call this function again (with bStatic=true) if you've made a change to an - InstancedEntity and wish this change to take effect. - Be sure to call this after you've set all your instances - @see InstanceBatchHW::setStaticAndUpdate - */ - virtual void setStaticAndUpdate( bool bStatic ) {} - - /** Returns true if this batch was set as static. @see setStaticAndUpdate - */ - virtual bool isStatic() const { return false; } - - /** Returns a pointer to a new InstancedEntity ready to use - Note it's actually preallocated, so no memory allocation happens at - this point. - - Returns NULL if all instances are being used - */ - InstancedEntity* createInstancedEntity(); - - /** Removes an InstancedEntity from the scene retrieved with - getNewInstancedEntity, putting back into a queue - - Throws an exception if the instanced entity wasn't created by this batch - Removed instanced entities save little CPU time, but _not_ GPU - */ - void removeInstancedEntity( InstancedEntity *instancedEntity ); - - /** Tells whether world bone matrices need to be calculated. - This does not include bone matrices which are calculated regardless - */ - virtual bool useBoneWorldMatrices() const { return true; } - - /** Tells that the list of entity instances with shared transforms has changed */ - void _markTransformSharingDirty() { mTransformSharingDirty = true; } - - /** @see InstancedEntity::setCustomParam */ - void _setCustomParam( InstancedEntity *instancedEntity, unsigned char idx, const Vector4f &newParam ); - - /** @see InstancedEntity::getCustomParam */ - const Vector4f& _getCustomParam( InstancedEntity *instancedEntity, unsigned char idx ); - - //Renderable overloads - /** @copydoc Renderable::getMaterial */ - const MaterialPtr& getMaterial(void) const override { return mMaterial; } - /** @copydoc Renderable::getRenderOperation */ - void getRenderOperation( RenderOperation& op ) override { op = mRenderOperation; } - - /** @copydoc Renderable::getSquaredViewDepth */ - Real getSquaredViewDepth( const Camera* cam ) const override; - /** @copydoc Renderable::getLights */ - const LightList& getLights( void ) const override; - - /** @copydoc MovableObject::getMovableType */ - const String& getMovableType(void) const override; - /** @copydoc MovableObject::_notifyCurrentCamera */ - void _notifyCurrentCamera( Camera* cam ) override; - /** @copydoc MovableObject::getBoundingBox */ - const AxisAlignedBox& getBoundingBox(void) const override; - /** @copydoc MovableObject::getBoundingRadius */ - Real getBoundingRadius(void) const override; - - void _updateRenderQueue(RenderQueue* queue) override; - void visitRenderables( Renderable::Visitor* visitor, bool debugRenderables = false ) override; - - // resolve ambiguity of get/setUserAny due to inheriting from Renderable and MovableObject - using Renderable::getUserAny; - using Renderable::setUserAny; - }; -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif // __InstanceBatch_H__ diff --git a/OgreMain/include/OgreInstanceBatchHW.h b/OgreMain/include/OgreInstanceBatchHW.h deleted file mode 100644 index 3f76d90024a..00000000000 --- a/OgreMain/include/OgreInstanceBatchHW.h +++ /dev/null @@ -1,102 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __InstanceBatchHW_H__ -#define __InstanceBatchHW_H__ - -#include "OgreInstanceBatch.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - - /** This is technique requires true instancing hardware support. - - Basically it creates a cloned vertex buffer from the original, with an extra buffer containing - 3 additional @c TEXCOORDS (12 bytes) repeated as much as the instance count. - That will be used for each instance data. - - The main advantage of this technique is that it's VERY fast; but it doesn't support - skeletal animation at all. Very reduced memory consumption and bandwidth. Great for particles, - debris, bricks, trees, sprites. - This batch is one of the few (if not the only) techniques that allows culling on an individual - basis. This means we can save vertex shader performance for instances that aren't in scene or - just not focused by the camera. - */ - class _OgreExport InstanceBatchHW : public InstanceBatch - { - bool mKeepStatic; - - void setupVertices( const SubMesh* baseSubMesh ) override; - void setupIndices( const SubMesh* baseSubMesh ) override; - - bool checkSubMeshCompatibility( const SubMesh* baseSubMesh ) override; - - size_t updateVertexBuffer( Camera *currentCamera ); - - public: - InstanceBatchHW( InstanceManager *creator, MeshPtr &meshReference, const MaterialPtr &material, - size_t instancesPerBatch, const Mesh::IndexMap *indexToBoneMap, - const String &batchName ); - virtual ~InstanceBatchHW(); - - /** @see InstanceBatch::calculateMaxNumInstances */ - size_t calculateMaxNumInstances( const SubMesh *baseSubMesh, uint16 flags ) const override; - - /** @see InstanceBatch::buildFrom */ - void buildFrom( const SubMesh *baseSubMesh, const RenderOperation &renderOperation ) override; - - /** Overloaded so that we don't perform needless updates when in static mode. Also doing that - could cause glitches with shadow mapping (since Ogre thinks we're small/bigger than we - really are when displaying, or that we're somewhere else) - */ - void _boundsDirty(void) override; - - /** @see InstanceBatch::setStaticAndUpdate. While this flag is true, no individual per-entity - cull check is made. This means if the camera is looking at only one instance, all instances - are sent to the vertex shader (unlike when this flag is false). This saves a lot of CPU - power and a bit of bus bandwidth. - */ - void setStaticAndUpdate( bool bStatic ) override; - - bool isStatic() const override { return mKeepStatic; } - - //Renderable overloads - void getWorldTransforms( Matrix4* xform ) const override; - - /** Overloaded to avoid updating skeletons (which we don't support), check visibility on a - per unit basis and finally updated the vertex buffer */ - void _updateRenderQueue( RenderQueue* queue ) override; - }; -} - -#endif diff --git a/OgreMain/include/OgreInstanceBatchHW_VTF.h b/OgreMain/include/OgreInstanceBatchHW_VTF.h deleted file mode 100644 index a5af8092e1a..00000000000 --- a/OgreMain/include/OgreInstanceBatchHW_VTF.h +++ /dev/null @@ -1,112 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __InstanceBatchHW_VTF_H__ -#define __InstanceBatchHW_VTF_H__ - -#include "OgreInstanceBatchVTF.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - - /** Instancing implementation using vertex texture through Vertex Texture Fetch (VTF) and - hardware instancing. - @see BaseInstanceBatchVTF and @see InstanceBatchHW - - The advantage over TextureVTF technique, is that this implements a basic culling algorithm - to avoid useless processing in vertex shader and uses a lot less VRAM and memory bandwidth - - Basically it has the benefits of both TextureVTF (skeleton animations) and HWInstancingBasic - (lower memory consumption and basic culling) techniques - - - Design discussion webpage: http://www.ogre3d.org/forums/viewtopic.php?f=4&t=59902 - @author - Matias N. Goldberg ("dark_sylinc") - @version - 1.2 - */ - class _OgreExport InstanceBatchHW_VTF : public BaseInstanceBatchVTF - { - protected: - bool mKeepStatic; - - //Pointer to the buffer containing the per instance vertex data - HardwareVertexBufferSharedPtr mInstanceVertexBuffer; - - void setupVertices( const SubMesh* baseSubMesh ) override; - void setupIndices( const SubMesh* baseSubMesh ) override; - - /** Creates 2 TEXCOORD semantics that will be used to sample the vertex texture */ - void createVertexSemantics( VertexData *thisVertexData, VertexData *baseVertexData, - const HWBoneIdxVec &hwBoneIdx, const HWBoneWgtVec& hwBoneWgt ) override; - - /** updates the vertex buffer containing the per instance data - @param[in] isFirstTime Tells if this is the first time the buffer is being updated - @param[in] currentCamera The camera being used for render (valid when using bone matrix lookup) - @return The number of instances to be rendered - */ - virtual size_t updateInstanceDataBuffer(bool isFirstTime, Camera* currentCamera); - - - bool checkSubMeshCompatibility( const SubMesh* baseSubMesh ) override; - - /** Keeps filling the VTF with world matrix data. Overloaded to avoid culled objects - and update visible instances' animation - */ - size_t updateVertexTexture( Camera *currentCamera ); - - bool matricesTogetherPerRow() const override { return true; } - public: - InstanceBatchHW_VTF( InstanceManager *creator, MeshPtr &meshReference, const MaterialPtr &material, - size_t instancesPerBatch, const Mesh::IndexMap *indexToBoneMap, - const String &batchName ); - virtual ~InstanceBatchHW_VTF(); - /** @see InstanceBatch::calculateMaxNumInstances */ - size_t calculateMaxNumInstances( const SubMesh *baseSubMesh, uint16 flags ) const override; - - /** @copydoc InstanceBatchHW::_boundsDirty */ - void _boundsDirty(void) override; - - /** @copydoc InstanceBatchHW::setStaticAndUpdate */ - void setStaticAndUpdate( bool bStatic ) override; - - bool isStatic() const override { return mKeepStatic; } - - /** Overloaded to visibility on a per unit basis and finally updated the vertex texture */ - void _updateRenderQueue( RenderQueue* queue ) override; - }; - -} - -#endif diff --git a/OgreMain/include/OgreInstanceBatchShader.h b/OgreMain/include/OgreInstanceBatchShader.h deleted file mode 100644 index 21c8ad2d472..00000000000 --- a/OgreMain/include/OgreInstanceBatchShader.h +++ /dev/null @@ -1,91 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __InstanceBatchShader_H__ -#define __InstanceBatchShader_H__ - -#include "OgreInstanceBatch.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - - /** This is the same technique the old InstancedGeometry implementation used (with improvements). - Basically it creates a large vertex buffer with many repeating entities, and sends per instance - data through shader constants. Because SM 2.0 & 3.0 have up to 256 shader constant registers, - this means there can be approx up to 84 instances per batch, assuming they're not skinned - But using shader constants for other stuff (i.e. lighting) also affects negatively this number - A mesh with skeletally animated 2 bones reduces the number 84 to 42 instances per batch. - - The main advantage of this technique is that it's supported on a high variety of hardware - (SM 2.0 cards are required) and the same shader can be used for both skeletally animated - normal entities and instanced entities without a single change required. - - Unlike the old @c InstancedGeometry implementation, the developer doesn't need to worry about - reaching the 84 instances limit, the InstanceManager automatically takes care of splitting - and creating new batches. But beware internally, this means less performance improvement. - Another improvement is that vertex buffers are shared between batches, which significantly - reduces GPU VRAM usage. - */ - class _OgreExport InstanceBatchShader : public InstanceBatch - { - size_t mNumWorldMatrices; - - void setupVertices( const SubMesh* baseSubMesh ) override; - void setupIndices( const SubMesh* baseSubMesh ) override; - - /** When the mesh is (hardware) skinned, a different code path is called so that - we reuse the index buffers and modify them in place. For example Instance #2 - with reference to bone #5 would have BlendIndex = 2 + 5 = 7 - Everything is copied identically except the VES_BLEND_INDICES semantic - */ - void setupHardwareSkinned( const SubMesh* baseSubMesh, VertexData *thisVertexData, - VertexData *baseVertexData ); - - public: - InstanceBatchShader( InstanceManager *creator, MeshPtr &meshReference, const MaterialPtr &material, - size_t instancesPerBatch, const Mesh::IndexMap *indexToBoneMap, - const String &batchName ); - - /** @see InstanceBatch::calculateMaxNumInstances */ - size_t calculateMaxNumInstances( const SubMesh *baseSubMesh, uint16 flags ) const override; - - /** @see InstanceBatch::buildFrom */ - void buildFrom( const SubMesh *baseSubMesh, const RenderOperation &renderOperation ) override; - - //Renderable overloads - void getWorldTransforms( Matrix4* xform ) const override; - unsigned short getNumWorldTransforms(void) const override; - }; -} - -#endif diff --git a/OgreMain/include/OgreInstanceBatchVTF.h b/OgreMain/include/OgreInstanceBatchVTF.h deleted file mode 100644 index 3a907ff38c2..00000000000 --- a/OgreMain/include/OgreInstanceBatchVTF.h +++ /dev/null @@ -1,222 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __BaseInstanceBatchVTF_H__ -#define __BaseInstanceBatchVTF_H__ - -#include "OgreInstanceBatch.h" -#include "OgreTexture.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - - /** Instancing implementation using vertex texture through Vertex Texture Fetch (VTF) - This implementation has the following advantages: - - Supports huge amount of instances per batch - - Supports skinning even with huge ammounts of instances per batch - - Doesn't need shader constants registers. - - Best suited for skinned entities - - But beware the disadvantages: - - VTF is only fast on modern GPUs (ATI Radeon HD 2000+, GeForce 8+ series onwards) - - On GeForce 6/7 series VTF is too slow - - VTF isn't (controversely) supported on old ATI X1800 hardware - - Only one bone weight per vertex is supported - - GPUs with low memory bandwidth (i.e. laptops and integrated GPUs) - may perform even worse than no instancing - - Whether this performs great or bad depends on the hardware. It improved up to 4x performance on - a Intel Core 2 Quad Core X9650 GeForce 8600 GTS, and in an Intel Core 2 Duo P7350 ATI - Mobility Radeon HD 4650, but went 0.75x slower on an AthlonX2 5000+ integrated nForce 6150 SE - Each BaseInstanceBatchVTF has it's own texture, which occupies memory in VRAM. - Approx VRAM usage can be computed by doing 12 bytes * 3 * numInstances * numBones - Use flag IM_VTFBESTFIT to avoid wasting VRAM (but may reduce amount of instances per batch). - - The material requires at least a texture unit stage named @c InstancingVTF - - */ - class _OgreExport BaseInstanceBatchVTF : public InstanceBatch - { - protected: - typedef std::vector HWBoneIdxVec; - typedef std::vector HWBoneWgtVec; - typedef std::vector Matrix4Vec; - - size_t mMatricesPerInstance; //number of bone matrices per instance - size_t mNumWorldMatrices; //Num bones * num instances - TexturePtr mMatrixTexture; //The VTF - - //Used when all matrices from each instance must be in the same row (i.e. HW Instancing). - //A few pixels are wasted, but resizing the texture puts the danger of not sampling the - //right pixel... (in theory it should work, but in practice doesn't) - size_t mWidthFloatsPadding; - size_t mMaxFloatsPerLine; - - size_t mRowLength; - size_t mWeightCount; - //Temporary array used to store 3x4 matrices before they are converted to dual quaternions - Matrix3x4f* mTempTransformsArray3x4; - - // The state of the usage of bone matrix lookup - bool mUseBoneMatrixLookup; - size_t mMaxLookupTableInstances; - - bool mUseBoneDualQuaternions; - bool mForceOneWeight; - bool mUseOneWeight; - - /** Clones the base material so it can have it's own vertex texture, and also - clones it's shadow caster materials, if it has any - */ - void cloneMaterial( const MaterialPtr &material ); - - /** Retrieves bone data from the original sub mesh and puts it into an appropriate buffer, - later to be read when creating the vertex semantics. - Assumes outBoneIdx has enough space (base submesh vertex count) - */ - void retrieveBoneIdx( VertexData *baseVertexData, HWBoneIdxVec &outBoneIdx ); - - /** @see retrieveBoneIdx() - Assumes outBoneIdx has enough space (twice the base submesh vertex count, one for each weight) - Assumes outBoneWgt has enough space (twice the base submesh vertex count, one for each weight) - */ - void retrieveBoneIdxWithWeights(VertexData *baseVertexData, HWBoneIdxVec &outBoneIdx, HWBoneWgtVec &outBoneWgt); - - /** Setups the material to use a vertex texture */ - void setupMaterialToUseVTF( TextureType textureType, MaterialPtr &material ) const; - - /** Creates the vertex texture */ - void createVertexTexture( const SubMesh* baseSubMesh ); - - /** Creates 2 TEXCOORD semantics that will be used to sample the vertex texture */ - virtual void createVertexSemantics( VertexData *thisVertexData, VertexData *baseVertexData, - const HWBoneIdxVec &hwBoneIdx, const HWBoneWgtVec &hwBoneWgt) = 0; - - size_t convert3x4MatricesToDualQuaternions(Matrix3x4f* matrices, size_t numOfMatrices, float* outDualQuaternions); - - /** Keeps filling the VTF with world matrix data */ - void updateVertexTexture(void); - - /** Affects VTF texture's width dimension */ - virtual bool matricesTogetherPerRow() const = 0; - - /** update the lookup numbers for entities with shared transforms */ - virtual void updateSharedLookupIndexes(); - - /** @see InstanceBatch::generateInstancedEntity() */ - InstancedEntity* generateInstancedEntity(size_t num) override; - - public: - BaseInstanceBatchVTF( InstanceManager *creator, MeshPtr &meshReference, const MaterialPtr &material, - size_t instancesPerBatch, const Mesh::IndexMap *indexToBoneMap, - const String &batchName); - virtual ~BaseInstanceBatchVTF(); - - /** @see InstanceBatch::buildFrom */ - void buildFrom( const SubMesh *baseSubMesh, const RenderOperation &renderOperation ) override; - - //Renderable overloads - void getWorldTransforms( Matrix4* xform ) const override; - - /** Overloaded to be able to updated the vertex texture */ - void _updateRenderQueue(RenderQueue* queue) override; - - /** Sets the state of the usage of bone matrix lookup - - Under default condition each instance entity is assigned a specific area in the vertex - texture for bone matrix data. When turned on the amount of area in the vertex texture - assigned for bone matrix data will be relative to the amount of unique animation states. - Instanced entities sharing the same animation state will share the same area in the matrix. - The specific position of each entity is placed in the vertex data and added in a second phase - in the shader. - - Note this feature only works in VTF_HW for now. - This value needs to be set before adding any instanced entities - */ - void setBoneMatrixLookup(bool enable, size_t maxLookupTableInstances) { assert(mInstancedEntities.empty()); - mUseBoneMatrixLookup = enable; mMaxLookupTableInstances = maxLookupTableInstances; } - - /** Tells whether to use bone matrix lookup - @see setBoneMatrixLookup() - */ - bool useBoneMatrixLookup() const { return mUseBoneMatrixLookup; } - - void setBoneDualQuaternions(bool enable) { assert(mInstancedEntities.empty()); - mUseBoneDualQuaternions = enable; mRowLength = (mUseBoneDualQuaternions ? 2 : 3); } - - bool useBoneDualQuaternions() const { return mUseBoneDualQuaternions; } - - void setForceOneWeight(bool enable) { assert(mInstancedEntities.empty()); - mForceOneWeight = enable; } - - bool forceOneWeight() const { return mForceOneWeight; } - - void setUseOneWeight(bool enable) { assert(mInstancedEntities.empty()); - mUseOneWeight = enable; } - - bool useOneWeight() const { return mUseOneWeight; } - - /** @see InstanceBatch::useBoneWorldMatrices() */ - bool useBoneWorldMatrices() const override { return !mUseBoneMatrixLookup; } - - /** @return the maximum amount of shared transform entities when using lookup table*/ - virtual size_t getMaxLookupTableInstances() const { return mMaxLookupTableInstances; } - - }; - - class _OgreExport InstanceBatchVTF : public BaseInstanceBatchVTF - { - - void setupVertices( const SubMesh* baseSubMesh ) override; - void setupIndices( const SubMesh* baseSubMesh ) override; - - /** Creates 2 TEXCOORD semantics that will be used to sample the vertex texture */ - void createVertexSemantics( VertexData *thisVertexData, VertexData *baseVertexData, - const HWBoneIdxVec &hwBoneIdx, const HWBoneWgtVec &hwBoneWgt ) override; - - bool matricesTogetherPerRow() const override { return false; } - public: - InstanceBatchVTF( InstanceManager *creator, MeshPtr &meshReference, const MaterialPtr &material, - size_t instancesPerBatch, const Mesh::IndexMap *indexToBoneMap, - const String &batchName); - virtual ~InstanceBatchVTF(); - - /** @see InstanceBatch::calculateMaxNumInstances */ - size_t calculateMaxNumInstances( const SubMesh *baseSubMesh, uint16 flags ) const override; - }; -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreInstanceManager.h b/OgreMain/include/OgreInstanceManager.h deleted file mode 100644 index 6e797bc9a8c..00000000000 --- a/OgreMain/include/OgreInstanceManager.h +++ /dev/null @@ -1,310 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __InstanceManager_H__ -#define __InstanceManager_H__ - -#include "OgrePrerequisites.h" -#include "OgreRenderOperation.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - - /** This is the main starting point for the new instancing system. - Each InstanceManager can control one technique and one mesh, but it can manage - multiple materials at the same time. - @ref SceneManager::createInstanceManager, which creates this InstanceManager. Each one - must have a unique name. It's wasteless to create two InstanceManagers with the same - mesh reference, instancing technique and instances per batch count. - This class takes care of managing batches automatically, so that more are created when - needed, and reuse existing ones as much as possible; thus the user doesn't have to worry - of managing all those low level issues. - - @see @ref InstanceBatch - @see @ref InstancedEntity - @see Design discussion thread: http://www.ogre3d.org/forums/viewtopic.php?f=4&t=59902 - */ - class _OgreExport InstanceManager : public FactoryAlloc - { - public: - enum InstancingTechnique - { - ShaderBased, ///< %Any SM 2.0+ @ref InstanceBatchShader - TextureVTF, ///< Needs Vertex Texture Fetch & SM 3.0+ @ref InstanceBatchVTF - HWInstancingBasic, ///< Needs SM 3.0+ and HW instancing support @ref InstanceBatchHW - HWInstancingVTF, ///< Needs SM 3.0+, HW instancing support & VTF @ref InstanceBatchHW_VTF - InstancingTechniquesCount - }; - - /** Values to be used in setSetting() & BatchSettings::setting */ - enum BatchSettingId - { - /// Makes all batches from same material cast shadows - CAST_SHADOWS = 0, - /// Makes each batch to display it's bounding box. Useful for debugging or profiling - SHOW_BOUNDINGBOX, - - NUM_SETTINGS - }; - - private: - struct BatchSettings - { - //These are all per material - bool setting[NUM_SETTINGS]; - - BatchSettings() - { - setting[CAST_SHADOWS] = true; - setting[SHOW_BOUNDINGBOX] = false; - } - }; - - typedef std::vector InstanceBatchVec; //vec[batchN] = Batch - typedef std::map InstanceBatchMap; //map[materialName] = Vec - - typedef std::map BatchSettingsMap; - - const String mName; //Not the name of the mesh - MeshPtr mMeshReference; - InstanceBatchMap mInstanceBatches; - size_t mIdCount; - - InstanceBatchVec mDirtyBatches; - - RenderOperation mSharedRenderOperation; - - size_t mInstancesPerBatch; - InstancingTechnique mInstancingTechnique; - uint16 mInstancingFlags; ///< @see InstanceManagerFlags - unsigned short mSubMeshIdx; - - BatchSettingsMap mBatchSettings; - SceneManager* mSceneManager; - - size_t mMaxLookupTableInstances; - unsigned char mNumCustomParams; //Number of custom params per instance. - - /** Finds a batch with at least one free instanced entity we can use. - If none found, creates one. - */ - inline InstanceBatch* getFreeBatch( const String &materialName ); - - /** Called when batches are fully exhausted (can't return more instances) so a new batch - is created. - For the first time use, it can take big build time. - It takes care of getting the render operation which will be shared by further batches, - which decreases their build time, and prevents GPU RAM from skyrocketing. - @param materialName The material name, to know where to put this batch in the map - @param firstTime True if this is the first time it is called - @return The created InstancedManager for convenience - */ - InstanceBatch* buildNewBatch( const String &materialName, bool firstTime ); - - /** @see defragmentBatches overload, this takes care of an array of batches - for a specific material */ - void defragmentBatches( bool optimizeCull, std::vector &entities, - std::vector &usedParams, - InstanceBatchVec &fragmentedBatches ); - - /** @see setSetting. This function helps it by setting the given parameter to all batches - in container. - */ - void applySettingToBatches( BatchSettingId id, bool value, const InstanceBatchVec &container ); - - /** Called when we you use a mesh which has shared vertices, the function creates separate - vertex/index buffers and also recreates the bone assignments. - */ - static void unshareVertices(const Ogre::MeshPtr &mesh); - - public: - InstanceManager( const String &customName, SceneManager *sceneManager, - const String &meshName, const String &groupName, - InstancingTechnique instancingTechnique, uint16 instancingFlags, - size_t instancesPerBatch, unsigned short subMeshIdx, bool useBoneMatrixLookup = false); - ~InstanceManager(); - - const String& getName() const { return mName; } - - SceneManager* getSceneManager() const { return mSceneManager; } - - /** Raises an exception if trying to change it after creating the first InstancedEntity - The actual value may be less if the technique doesn't support having so much. - See @ref getMaxOrBestNumInstancesPerBatch for the usefulness of this function - @param instancesPerBatch New instances per batch number - */ - void setInstancesPerBatch( size_t instancesPerBatch ); - - /** Sets the size of the lookup table for techniques supporting bone lookup table. - Raises an exception if trying to change it after creating the first InstancedEntity. - Setting this value below the number of unique (non-sharing) entity instance animations - will produce a crash during runtime. Setting this value above will increase memory - consumption and reduce framerate. - @remarks The value should be as close but not below the actual value. - @param maxLookupTableInstances New size of the lookup table - */ - void setMaxLookupTableInstances( size_t maxLookupTableInstances ); - - /** Sets the number of custom parameters per instance. Some techniques (i.e. HWInstancingBasic) - support this, but not all of them. They also may have limitations to the max number. All - instancing implementations assume each instance param is a Vector4 (4 floats). - - This function cannot be called after the first batch has been created. Otherwise - it will raise an exception. If the technique doesn't support custom params, it will - raise an exception at the time of building the first InstanceBatch. - - HWInstancingBasic: - * Each custom params adds an additional float4 TEXCOORD. - HWInstancingVTF: - * Not implemented. (Recommendation: Implement this as an additional float4 VTF fetch) - TextureVTF: - * Not implemented. (see HWInstancingVTF's recommendation) - ShaderBased: - * Not supported. - @param numCustomParams Number of custom parameters each instance will have. Default: 0 - */ - void setNumCustomParams( unsigned char numCustomParams ); - - unsigned char getNumCustomParams() const - { return mNumCustomParams; } - - /** @return Instancing technique this manager was created for. Can't be changed after creation */ - InstancingTechnique getInstancingTechnique() const - { return mInstancingTechnique; } - - /** Calculates the maximum (or the best amount, depending on flags) of instances - per batch given the suggested size for the technique this manager was created for. - - This is done automatically when creating an instanced entity, but this function in conjunction - with @ref setInstancesPerBatch allows more flexible control over the amount of instances - per batch - @param materialName Name of the material to base on - @param suggestedSize Suggested amount of instances per batch - @param flags @ref InstanceManagerFlags to pass to the InstanceManager - @return The max/best amount of instances per batch given the suggested size and flags - */ - size_t getMaxOrBestNumInstancesPerBatch( const String &materialName, size_t suggestedSize, uint16 flags ); - - /// Creates an InstancedEntity - InstancedEntity* createInstancedEntity( const String &materialName ); - - /** This function can be useful to improve CPU speed after having too many instances - created, which where now removed, thus freeing many batches with zero used Instanced Entities - However the batches aren't automatically removed from memory until the InstanceManager is - destroyed, or this function is called. This function removes those batches which are completely - unused (only wasting memory). - */ - void cleanupEmptyBatches(void); - - /** After creating many entities (which turns in many batches) and then removing entities that - are in the middle of these batches, there might be many batches with many free entities. - Worst case scenario, there could be left one batch per entity. Imagine there can be - 80 entities per batch, there are 80 batches, making a total of 6400 entities. Then - 6320 of those entities are removed in a very specific way, which leads to having - 80 batches, 80 entities, and GPU vertex shader still needs to process 6400! - This is called fragmentation. This function reparents the InstancedEntities - to fewer batches, in this case leaving only one batch with 80 entities - - - This function takes time. Make sure to call this only when you're sure there's - too much of fragmentation and you won't be creating more InstancedEntities soon - Also in many cases cleanupEmptyBatches() ought to be enough - Defragmentation is done per material - Static batches won't be defragmented. If you want to degragment them, set them - to dynamic again, and switch back to static after calling this function. - - @param optimizeCulling When true, entities close together will be reorganized - in the same batch for more efficient CPU culling. This can take more CPU - time. You want this to be false if you now you're entities are moving very - randomly which tends them to get separated and spread all over the scene - (which nullifies any CPU culling) - */ - void defragmentBatches( bool optimizeCulling ); - - /** Applies a setting for all batches using the same material - - If the material name hasn't been used, the settings are still stored - This allows setting up batches before they get even created. - @par Examples - `setSetting(InstanceManager::CAST_SHADOWS, false, "")` disables shadow - casting for all instanced entities (see @ref MovableObject::setCastShadows) - @par - `setSetting(InstanceManager::SHOW_BOUNDINGBOX, true, "MyMat")` - will display the bounding box of the batch (not individual InstancedEntities) - from all batches using material "MyMat" - @param id @ref BatchSettingId to setup - @param enabled Boolean value. It's meaning depends on the id. - @param materialName When Blank, the setting is applied to all existing materials - */ - void setSetting( BatchSettingId id, bool enabled, const String &materialName = BLANKSTRING ); - - /// If settings for the given material didn't exist, default value is returned - bool getSetting( BatchSettingId id, const String &materialName ) const; - - /** Returns true if settings were already created for the given material name. - If false is returned, it means getSetting will return default settings. - */ - bool hasSettings( const String &materialName ) const; - - /** @copydoc InstanceBatch::setStaticAndUpdate */ - void setBatchesAsStaticAndUpdate( bool bStatic ); - - /** Called by an InstanceBatch when it requests their bounds to be updated for proper culling - @param dirtyBatch The batch which is dirty, usually same as caller. - */ - void _addDirtyBatch( InstanceBatch *dirtyBatch ); - - /** Called by SceneManager when we told it we have at least one dirty batch */ - void _updateDirtyBatches(void); - - typedef ConstMapIterator InstanceBatchMapIterator; - typedef ConstVectorIterator InstanceBatchIterator; - - /// Get non-updateable iterator over instance batches per material - InstanceBatchMapIterator getInstanceBatchMapIterator(void) const - { return InstanceBatchMapIterator( mInstanceBatches.begin(), mInstanceBatches.end() ); } - - /** Get non-updateable iterator over instance batches for given material - - Each InstanceBatch pointer may be modified for low level usage (i.e. - setCustomParameter), but there's no synchronization mechanism when - multithreading or creating more instances, that's up to the user. - */ - InstanceBatchIterator getInstanceBatchIterator( const String &materialName ) const; - }; -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif // __InstanceManager_H__ diff --git a/OgreMain/include/OgreInstancedEntity.h b/OgreMain/include/OgreInstancedEntity.h deleted file mode 100644 index 3d5b8239211..00000000000 --- a/OgreMain/include/OgreInstancedEntity.h +++ /dev/null @@ -1,298 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __InstancedEntity_H__ -#define __InstancedEntity_H__ - -#include "OgreMovableObject.h" -#include "OgreNode.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - class NameGenerator; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - - /** @see InstanceBatch to understand how instancing works. - - Instanced entities work in a very similar way as how an Entity works, as this interface - tries to mimic it as most as possible to make the transition between Entity and InstancedEntity - as straightforward and simple as possible. - There are a couple inherent limitations, for example setRenderQueueGroup only works on - the InstanceBatch level, not the individual instance. This limits Z sorting for alpha blending - quite significantly - An InstancedEntity won't appear in scene until a SceneNode is attached to them. Once the - InstancedEntity is no longer needed, call InstanceBatch::removeInstancedEntity to put them - back into a queue so the batch can return it back again when a new instance is requested. - @par - Internally, instanced entities that are not visible (i.e. by setting setVisible(false) or - when they don't have a SceneNode attached to them) a Zero world matrix is sent to the vertex shader - which in turn causes a zero area triangle. - This obviously means no Vertex shader benefit, but saves a bit of pixel shader processing power. - Also this means this object won't be considered when sizing the InstanceBatch's bounding box. - @par - Each instance has an instance ID unique within the batch, which matches the ID sent to the vertex - shader by some techniques (like InstanceBatchShader). - @par - Differences between Entity and InstancedEntity: - * Setting RenderQueueGroup and other Renderable stuff works at InstanceBatch level, not - InstancedEntity. This is obviously a limitation from instancing in general, not this particular - implementation - - - Design discussion webpage - @author - Matias N. Goldberg ("dark_sylinc") - @version - 1.0 - */ - class _OgreExport InstancedEntity : public MovableObject - { - friend class InstanceBatch; - friend class InstanceBatchShader; - friend class InstanceBatchHW; - friend class InstanceBatchHW_VTF; - friend class BaseInstanceBatchVTF; - private: - typedef TransformBase<3, float> Matrix3x4f; - uint16 mInstanceId; //Note it may change after defragmenting! - bool mInUse; - InstanceBatch *mBatchOwner; - - AnimationStateSet *mAnimationState; - SkeletonInstance *mSkeletonInstance; - Affine3 *mBoneMatrices; //Local space - Affine3 *mBoneWorldMatrices; //World space - unsigned long mFrameAnimationLastUpdated; - - InstancedEntity* mSharedTransformEntity; //When not null, another InstancedEntity controls the skeleton - - /** Used in conjunction with bone matrix lookup. Tells the number of the transform for - as arranged in the vertex texture */ - uint16 mTransformLookupNumber; - - /// Stores the master when we're the slave, store our slaves when we're the master - typedef std::vector InstancedEntityVec; - InstancedEntityVec mSharingPartners; - - ////////////////////////////////////////////////////////////////////////// - // Parameters used for local transformation offset information - // The - ////////////////////////////////////////////////////////////////////////// - - /// Object position - Vector3 mPosition; - Vector3 mDerivedLocalPosition; - /// Object orientation - Quaternion mOrientation; - /// Object scale - Vector3 mScale; - /// The maximum absolute scale for all dimension - Real mMaxScaleLocal; - /// Full world transform - Affine3 mFullLocalTransform; - /// Tells if mFullTransform needs an updated - bool mNeedTransformUpdate; - /// Tells if the animation world transform needs an update - bool mNeedAnimTransformUpdate; - /// Tells whether to use the local transform parameters - bool mUseLocalTransform; - - - /// Returns number of matrices written to transform, assumes transform has enough space - size_t getTransforms( Matrix4 *xform ) const; - /// Returns number of 32-bit values written - size_t getTransforms3x4( Matrix3x4f *xform ) const; - - /// Returns true if this InstancedObject is visible to the current camera - bool findVisible( Camera *camera ) const; - - /// Creates/destroys our own skeleton, also tells slaves to unlink if we're destroying - void createSkeletonInstance(); - void destroySkeletonInstance(); - - /// When this entity is a slave, stopSharingTransform delegates to this function. - /// nofityMaster = false is used to prevent iterator invalidation in specific cases. - void stopSharingTransformAsSlave( bool notifyMaster ); - - /// Just unlinks, and tells our master we're no longer sharing - void unlinkTransform( bool notifyMaster=true ); - - /// Called when a slave has unlinked from us - void notifyUnlink( const InstancedEntity *slave ); - - /// Mark the transformation matrixes as dirty - inline void markTransformDirty(); - - /// Incremented count for next name extension - static NameGenerator msNameGenerator; - - public: - InstancedEntity( InstanceBatch *batchOwner, uint32 instanceID, InstancedEntity* sharedTransformEntity = NULL); - virtual ~InstancedEntity(); - - /** Shares the entire transformation with another InstancedEntity. This is useful when a mesh - has more than one submeshes, therefore creating multiple InstanceManagers (one for each - submesh). With this function, sharing makes the skeleton to be shared (less memory) and - updated once (performance optimization). - Note that one InstancedEntity (i.e. submesh 0) must be chosen as "master" which will share - with the other instanced entities (i.e. submeshes 1-N) which are called "slaves" - @par - Requirements to share trasnformations: - * Both InstancedEntities must have use the same skeleton - * An InstancedEntity can't be both "master" and "slave" at the same time - - Sharing does nothing if the original mesh doesn't have a skeleton - When an InstancedEntity is removed (@see InstanceBatch::removeInstancedEntity), it stops - sharing the transform. If the instanced entity was the master one, all it's slaves stop - sharing and start having their own transform too. - @param slave The InstancedEntity that should share with us and become our slave - @return true if successfully shared (may fail if they aren't skeletally animated) - */ - bool shareTransformWith( InstancedEntity *slave ); - - /** @see shareTransformWith - Stops sharing the transform if this is a slave, and notifies the master we're no longer - a slave. - If this is a master, tells all it's slave to stop sharing - - This function is automatically called in InstanceBatch::removeInstancedEntity - */ - void stopSharingTransform(); - - InstanceBatch* _getOwner() const { return mBatchOwner; } - - const String& getMovableType(void) const override; - - const AxisAlignedBox& getBoundingBox(void) const override; - Real getBoundingRadius(void) const override; - - /** This is used by our batch owner to get the closest entity's depth, returns infinity - when not attached to a scene node */ - Real getSquaredViewDepth( const Camera* cam ) const; - - /// Overridden so we can tell the InstanceBatch it needs to update it's bounds - void _notifyMoved(void) override; - void _notifyAttached( Node* parent, bool isTagPoint = false ) override; - - /// Do nothing, InstanceBatch takes care of this. - void _updateRenderQueue( RenderQueue* queue ) override {} - void visitRenderables( Renderable::Visitor* visitor, bool debugRenderables = false ) override {} - - /** @see Entity::hasSkeleton */ - bool hasSkeleton(void) const { return mSkeletonInstance != 0; } - /** @see Entity::getSkeleton */ - SkeletonInstance* getSkeleton(void) const { return mSkeletonInstance; } - - /** @see Entity::getAnimationState */ - AnimationState* getAnimationState(const String& name) const; - /** @see Entity::getAllAnimationStates */ - AnimationStateSet* getAllAnimationStates(void) const; - - /** Called by InstanceBatch in his _updateRenderQueue to tell us we need - to calculate our bone matrices. - @remarks Assumes it has a skeleton (mSkeletonInstance != 0) - @return true if something was actually updated - */ - virtual bool _updateAnimation(void); - - /** Sets the transformation look up number */ - void setTransformLookupNumber(uint16 num) { mTransformLookupNumber = num;} - - /** Retrieve the position */ - const Vector3& getPosition() const { return mPosition; } - /** Set the position or the offset from the parent node if a parent node exists */ - void setPosition(const Vector3& position, bool doUpdate = true); - - /** Retrieve the orientation */ - const Quaternion& getOrientation() const { return mOrientation; } - /** Set the orientation or the offset from the parent node if a parent node exists */ - void setOrientation(const Quaternion& orientation, bool doUpdate = true); - - /** Retrieve the local scale */ - const Vector3& getScale() const { return mScale; } - /** Set the scale or the offset from the parent node if a parent node exists */ - void setScale(const Vector3& scale, bool doUpdate = true); - - /** Returns the maximum derived scale coefficient among the xyz values */ - Real getMaxScaleCoef() const; - - /** Update the world transform and derived values */ - void updateTransforms(); - - /** Tells if the entity is in use. */ - bool isInUse() const { return mInUse; } - /** Sets whether the entity is in use. */ - void setInUse(bool used); - - /** Returns the world transform of the instanced entity including local transform */ - const Affine3& _getParentNodeFullTransform(void) const override { - assert((!mNeedTransformUpdate || !mUseLocalTransform) && "Transform data should be updated at this point"); - return mUseLocalTransform ? mFullLocalTransform : - mParentNode ? mParentNode->_getFullTransform() : Affine3::IDENTITY; - } - - /** Returns the derived position of the instanced entity including local transform */ - const Vector3& _getDerivedPosition() const { - assert((!mNeedTransformUpdate || !mUseLocalTransform) && "Transform data should be updated at this point"); - return mUseLocalTransform ? mDerivedLocalPosition : - mParentNode ? mParentNode->_getDerivedPosition() : Vector3::ZERO; - } - - /** @copydoc MovableObject::isInScene */ - bool isInScene(void) const override - { - //We assume that the instanced entity is in the scene if it is in use - //It is in the scene whether it has a parent node or not - return mInUse; - } - - /** Sets the custom parameter for this instance @see InstanceManager::setNumCustomParams - Because not all techniques support custom params, and some users may not need it while - using millions of InstancedEntities, the params have been detached from InstancedEntity - and stored in it's InstanceBatch instead, to reduce memory overhead. - - If this function is never called, all instances default to Vector4::ZERO. Watch out! - If you destroy an instanced entity and then create it again (remember! Instanced entities - are pre-allocated) it's custom param will contain the old value when it was destroyed. - @param idx of the param. In the range [0; InstanceManager::getNumCustomParams()) - @param newParam New parameter - */ - void setCustomParam( unsigned char idx, const Vector4f &newParam ); - const Vector4f& getCustomParam( unsigned char idx ); - }; -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreIteratorWrapper.h b/OgreMain/include/OgreIteratorWrapper.h deleted file mode 100644 index 28488a135fd..00000000000 --- a/OgreMain/include/OgreIteratorWrapper.h +++ /dev/null @@ -1,381 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Ogre_Iterator_Wrapper_H__ -#define __Ogre_Iterator_Wrapper_H__ - -#include "OgreHeaderPrefix.h" - -namespace Ogre{ - -/** - * - * @brief Basefunctionality for IteratorWrappers - * - * - * @tparam T a Container like vector list map ... - * @tparam IteratorType T::iterator or T::const_iterator - * @tparam ValType T::mapped_type in case of a map, T::value_type for vector, list,... - * - * Have a look at VectorIteratorWrapper and MapIteratorWrapper for a concrete usage -*/ -template -class IteratorWrapper -{ - - private: - /// Private constructor since only the parameterised constructor should be used - IteratorWrapper(); - - protected: - IteratorType mBegin; - IteratorType mCurrent; - IteratorType mEnd; - - - public: - - /// Type you expect to get by funktions like peekNext(Value) - typedef ValType ValueType; - /// Type you expect to get by funktions like peekNext(Value)Ptr - typedef ValType* PointerType; - - /** - @brief Typedef to fulfill container interface - - Useful if you want to use BOOST_FOREACH - @note there is no distinction between const_iterator and iterator. - \n keep this in mind if you want to derivate from this class. - */ - typedef IteratorType iterator; - - /** - @brief Typedef to fulfill container interface - - Useful if you want to use BOOST_FOREACH - @note there is no distinction between const_iterator and iterator. - \n keep this in mind if you want to derivate from this class. - */ - typedef IteratorType const_iterator; - - - /** Constructor. - - Provide a start and end iterator to initialise. - */ - IteratorWrapper ( IteratorType start, IteratorType last ) - : mBegin( start ), mCurrent ( start ), mEnd ( last ) - { - } - - - /** Returns true if there are more items in the collection. */ - bool hasMoreElements ( ) const - { - return mCurrent != mEnd; - } - - - /** Moves the iterator on one element. */ - void moveNext ( ) - { - ++mCurrent; - } - - /** Bookmark to the begin of the underlying collection */ - const IteratorType& begin() {return mBegin;} - - - /** Full access to the current iterator */ - IteratorType& current(){return mCurrent;} - - /** Bookmark to the end (one behind the last element) of the underlying collection */ - const IteratorType& end() {return mEnd;} - - -}; - - - -/** - * - * @brief Prepared IteratorWrapper for container like std::vector - * - * - * @tparam T = Container eg vector - * @tparam IteratorType T::iterator or T::const_iterator - * - * Have a look at VectorIterator and ConstVectorIterator for a more concrete usage -*/ -template -class VectorIteratorWrapper : public IteratorWrapper -{ - - public: - typedef typename IteratorWrapper::ValueType ValueType ; - typedef typename IteratorWrapper::PointerType PointerType ; - - - /** - * @brief c'tor - * - * Constructor that provide a start and end iterator to initialise. - * - * @param start Start iterator - * @param last End iterator - */ - VectorIteratorWrapper ( IteratorType start, IteratorType last ) - : IteratorWrapper( start, last ) - { - } - - - /** Returns the next(=current) element in the collection, without advancing to the next. */ - ValueType peekNext ( ) const - { - return *(this->mCurrent); - } - - /** Returns a pointer to the next(=current) element in the collection, without advancing to the next afterwards. */ - PointerType peekNextPtr ( ) const - { - return &(*(this->mCurrent) ); - } - - /** Returns the next(=current) value element in the collection, and advances to the next. */ - ValueType getNext ( ) - { - return *(this->mCurrent++); - } - -}; - - -/** - * - * @brief Concrete IteratorWrapper for nonconst access to the underlying container - * - * @tparam T Container - * -*/ -template -class VectorIterator : public VectorIteratorWrapper{ - public: - /** Constructor. - - Provide a start and end iterator to initialise. - */ - VectorIterator( typename T::iterator start, typename T::iterator last ) - : VectorIteratorWrapper(start , last ) - { - } - - /** Constructor. - - Provide a container to initialise. - */ - explicit VectorIterator( T& c ) - : VectorIteratorWrapper ( c.begin(), c.end() ) - { - } - -}; - -/** - * - * @brief Concrete IteratorWrapper for const access to the underlying container - * - * - * @tparam T = Container - * -*/ -template -class ConstVectorIterator : public VectorIteratorWrapper{ - public: - /** Constructor. - - Provide a start and end iterator to initialise. - */ - ConstVectorIterator( typename T::const_iterator start, typename T::const_iterator last ) - : VectorIteratorWrapper (start , last ) - { - } - - /** Constructor. - - Provide a container to initialise. - */ - explicit ConstVectorIterator ( const T& c ) - : VectorIteratorWrapper (c.begin() , c.end() ) - { - } -}; - - - - - -/** - * - * @brief Prepared IteratorWrapper for key-value container - * - * - * @tparam T Container (map - or also set ) - * @tparam IteratorType T::iterator or T::const_iterator - * - * Have a look at MapIterator and ConstMapIterator for a concrete usage -*/ -template -class MapIteratorWrapper : public IteratorWrapper -{ - - public: - /// Redefined ValueType for a map/set - typedef typename IteratorWrapper::ValueType ValueType ; - /// Redefined PointerType for a map/set - typedef typename IteratorWrapper::PointerType PointerType ; - - /// Unused, just to make it clear that map/set\::value_type is not a ValueType - typedef typename T::value_type PairType ; - /// Type you expect to get by funktions like peekNextKey - typedef typename T::key_type KeyType; - - /** Constructor. - - Provide a start and end iterator to initialise. - */ - MapIteratorWrapper ( IteratorType start, IteratorType last ) - : IteratorWrapper( start, last ) - { - } - - /** Returns the next(=current) key element in the collection, without advancing to the next. */ - KeyType peekNextKey(void) const - { - return this->mCurrent->first; - } - - - /** Returns the next(=current) value element in the collection, without advancing to the next. */ - ValueType peekNextValue ( ) const - { - return this->mCurrent->second; - } - - - /** Returns a pointer to the next/current value element in the collection, without - advancing to the next afterwards. */ - const PointerType peekNextValuePtr ( ) const - { - return &(this->mCurrent->second); - } - - - /** Returns the next(=current) value element in the collection, and advances to the next. */ - ValueType getNext() - { - return ((this->mCurrent++)->second) ; - } - - -}; - - - - -/** - * - * @brief Concrete IteratorWrapper for nonconst access to the underlying key-value container - * - * - * @remarks Template key-value container - * -*/ -template -class MapIterator : public MapIteratorWrapper{ - public: - - /** Constructor. - - Provide a start and end iterator to initialise. - */ - MapIterator( typename T::iterator start, typename T::iterator last ) - : MapIteratorWrapper(start , last ) - { - } - - /** Constructor. - - Provide a container to initialise. - */ - explicit MapIterator( T& c ) - : MapIteratorWrapper ( c.begin(), c.end() ) - { - } - -}; - - -/** - * - * @brief Concrete IteratorWrapper for const access to the underlying key-value container - * - * - * @tparam T key-value container - * -*/ -template -class ConstMapIterator : public MapIteratorWrapper{ - public: - - /** Constructor. - - Provide a start and end iterator to initialise. - */ - ConstMapIterator( typename T::const_iterator start, typename T::const_iterator last ) - : MapIteratorWrapper (start , last ) - { - } - - /** Constructor. - - Provide a container to initialise. - */ - explicit ConstMapIterator ( const T& c ) - : MapIteratorWrapper (c.begin() , c.end() ) - { - } -}; - - - - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreIteratorWrappers.h b/OgreMain/include/OgreIteratorWrappers.h deleted file mode 100644 index ba967732df2..00000000000 --- a/OgreMain/include/OgreIteratorWrappers.h +++ /dev/null @@ -1,3 +0,0 @@ -#include "OgrePrerequisites.h" -#include "OgreIteratorWrapper.h" -#pragma message( __FILE__ " is deprecated, migrate to OgreIteratorWrapper.h") diff --git a/OgreMain/include/OgreKeyFrame.h b/OgreMain/include/OgreKeyFrame.h deleted file mode 100644 index 0599b8e6e82..00000000000 --- a/OgreMain/include/OgreKeyFrame.h +++ /dev/null @@ -1,259 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __KeyFrame_H__ -#define __KeyFrame_H__ - -#include "OgrePrerequisites.h" -#include "OgreVector.h" -#include "OgreQuaternion.h" -#include "OgreAny.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Animation - * @{ - */ - /** A key frame in an animation sequence defined by an AnimationTrack. - - This class can be used as a basis for all kinds of key frames. - The unifying principle is that multiple KeyFrames define an - animation sequence, with the exact state of the animation being an - interpolation between these key frames. - */ - class _OgreExport KeyFrame : public AnimationAlloc - { - public: - - /** Default constructor, you should not call this but use AnimationTrack::createKeyFrame instead. */ - KeyFrame(const AnimationTrack* parent, Real time); - - virtual ~KeyFrame() {} - - /** Gets the time of this keyframe in the animation sequence. */ - Real getTime(void) const { return mTime; } - - /** Clone a keyframe (internal use only) */ - virtual KeyFrame* _clone(AnimationTrack* newParent) const OGRE_NODISCARD; - - - protected: - Real mTime; - const AnimationTrack* mParentTrack; - }; - - - /** Specialised KeyFrame which stores any numeric value. - */ - class _OgreExport NumericKeyFrame : public KeyFrame - { - public: - /** Default constructor, you should not call this but use AnimationTrack::createKeyFrame instead. */ - NumericKeyFrame(const AnimationTrack* parent, Real time); - ~NumericKeyFrame() {} - - /** Get the value at this keyframe. */ - const Any& getValue(void) const { return mValue; } - /** Set the value at this keyframe. - - All keyframe values must have a consistent type. - */ - void setValue(const Any& val) { mValue = val; } - - /** Clone a keyframe (internal use only) */ - KeyFrame* _clone(AnimationTrack* newParent) const override; - private: - Any mValue; - }; - - - /** Specialised KeyFrame which stores a full transform. */ - class _OgreExport TransformKeyFrame : public KeyFrame - { - public: - /** Default constructor, you should not call this but use AnimationTrack::createKeyFrame instead. */ - TransformKeyFrame(const AnimationTrack* parent, Real time); - ~TransformKeyFrame() {} - /** Sets the translation associated with this keyframe. - - The translation factor affects how much the keyframe translates (moves) it's animable - object at it's time index. - @param trans The vector to translate by - */ - virtual void setTranslate(const Vector3& trans); - - /** Gets the translation applied by this keyframe. */ - const Vector3& getTranslate(void) const; - - /** Sets the scaling factor applied by this keyframe to the animable - object at it's time index. - @param scale The vector to scale by (beware of supplying zero values for any component of this - vector, it will scale the object to zero dimensions) - */ - virtual void setScale(const Vector3& scale); - - /** Gets the scaling factor applied by this keyframe. */ - virtual const Vector3& getScale(void) const; - - /** Sets the rotation applied by this keyframe. - @param rot The rotation applied; use Quaternion methods to convert from angle/axis or Matrix3 if - you don't like using Quaternions directly. - */ - virtual void setRotation(const Quaternion& rot); - - /** Gets the rotation applied by this keyframe. */ - virtual const Quaternion& getRotation(void) const; - - /** Clone a keyframe (internal use only) */ - KeyFrame* _clone(AnimationTrack* newParent) const override; - private: - Vector3 mTranslate; - Vector3 mScale; - Quaternion mRotate; - - - }; - - - - /** Specialised KeyFrame which stores absolute vertex positions for a complete - buffer, designed to be interpolated with other keys in the same track. - */ - class _OgreExport VertexMorphKeyFrame : public KeyFrame - { - public: - /** Default constructor, you should not call this but use AnimationTrack::createKeyFrame instead. */ - VertexMorphKeyFrame(const AnimationTrack* parent, Real time); - ~VertexMorphKeyFrame() {} - /** Sets the vertex buffer containing the source positions for this keyframe. - - We assume that positions are the first 3 float elements in this buffer, - although we don't necessarily assume they're the only ones in there. - @param buf Vertex buffer link; will not be modified so can be shared - read-only data - */ - void setVertexBuffer(const HardwareVertexBufferSharedPtr& buf); - - /** Gets the vertex buffer containing positions for this keyframe. */ - const HardwareVertexBufferSharedPtr& getVertexBuffer(void) const; - - KeyFrame* _clone(AnimationTrack* newParent) const override; - - private: - HardwareVertexBufferSharedPtr mBuffer; - - }; - - /** Specialised KeyFrame which references a Mesh::Pose at a certain influence - level, which stores offsets for a subset of the vertices - in a buffer to provide a blendable pose. - */ - class _OgreExport VertexPoseKeyFrame : public KeyFrame - { - public: - /** Default constructor, you should not call this but use AnimationTrack::createKeyFrame instead. */ - VertexPoseKeyFrame(const AnimationTrack* parent, Real time); - ~VertexPoseKeyFrame() {} - - /** Reference to a pose at a given influence level - - Each keyframe can refer to many poses each at a given influence level. - **/ - struct PoseRef - { - /** The linked pose index. - - The Mesh contains all poses for all vertex data in one list, both - for the shared vertex data and the dedicated vertex data on submeshes. - The 'target' on the parent track must match the 'target' on the - linked pose. - */ - ushort poseIndex; - /** Influence level of the linked pose. - 1.0 for full influence (full offset), 0.0 for no influence. - */ - float influence; - - PoseRef(ushort p, float i) : poseIndex(p), influence(i) {} - }; - typedef std::vector PoseRefList; - - /** Add a new pose reference. - @see PoseRef - */ - void addPoseReference(ushort poseIndex, float influence); - /** Update the influence of a pose reference. - @see PoseRef - */ - void updatePoseReference(ushort poseIndex, float influence); - /** Remove reference to a given pose. - @param poseIndex The pose index (not the index of the reference) - */ - void removePoseReference(ushort poseIndex); - /** Remove all pose references. */ - void removeAllPoseReferences(void); - - - /** Get a const reference to the list of pose references. */ - const PoseRefList& getPoseReferences(void) const; - - typedef VectorIterator PoseRefIterator; - typedef ConstVectorIterator ConstPoseRefIterator; - - /** Get an iterator over the pose references. - @deprecated use getPoseReferences() */ - OGRE_DEPRECATED PoseRefIterator getPoseReferenceIterator(void); - - /** Get a const iterator over the pose references. - @deprecated use getPoseReferences() */ - OGRE_DEPRECATED ConstPoseRefIterator getPoseReferenceIterator(void) const; - - /** Clone a keyframe (internal use only) */ - KeyFrame* _clone(AnimationTrack* newParent) const override; - - void _applyBaseKeyFrame(const VertexPoseKeyFrame* base); - - private: - PoseRefList mPoseRefs; - - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreLight.h b/OgreMain/include/OgreLight.h deleted file mode 100644 index 7bfc212cafe..00000000000 --- a/OgreMain/include/OgreLight.h +++ /dev/null @@ -1,628 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _LIGHT_H__ -#define _LIGHT_H__ - -#include "OgrePrerequisites.h" - -#include "OgreColourValue.h" -#include "OgreVector.h" -#include "OgreMovableObject.h" -#include "OgrePlaneBoundedVolume.h" -#include "OgreNode.h" -#include "OgreCamera.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** Representation of a dynamic light source in the scene. - - Lights are added to the scene like any other object. They contain various - parameters like type, attenuation (how light intensity fades with - distance), colour etc. - - The light colour is computed based on the - [Direct3D Light Model](https://docs.microsoft.com/en-us/windows/win32/direct3d9/mathematics-of-lighting) as: - - \f[ L_d = C_d \cdot p \cdot ( N \cdot L_{dir}) \cdot A \cdot S \f] - \f[ L_s = C_s \cdot p \cdot ( N \cdot H)^s \cdot A \cdot S \f] - - where - \f[ A = \frac{1}{c + l \cdot d + q \cdot d^2} \f] - and only computed when attenuation is enabled, - - \f[ S = \left[ \frac{\rho - cos(0.5 \cdot \phi)}{cos(0.5 \cdot \theta) - cos(0.5 \cdot \phi)} \right]^f \f] - and only computed with spotlights - - - \f$C_d\f$ is the light diffuse colour - - \f$C_s\f$ is the light specular colour - - \f$p\f$ is the light power scale factor - - \f$s\f$ is the surface shininess - - \f$N\f$ is the current surface normal - - \f$L_{dir}\f$ is vector from the vertex position to the light (constant for directional lights) - - \f$H = normalised(L_{dir} + V)\f$, where V is the vector from the vertex position to the camera - - \f$c, l, q\f$ are the constant, linear and quadratic attenuation factors - - \f$d = |L_{dir}|\f$ - - \f$\theta, \phi, f\f$ are the spotlight inner angle, outer angle and falloff - - \f$\rho = \langle L_{dir} , L_{dcs} \rangle \f$ where \f$L_{dcs}\f$ is the light direction in camera space - - The defaults when a light is created is pure white diffuse light, with no - attenuation (does not decrease with distance) and a range of 1000 world units. - - Lights are created by using the SceneManager::createLight method. They subsequently must be - added to a SceneNode to orient them in the scene and to allow moving them. - - Remember also that dynamic lights rely on modifying the colour of vertices based on the position of - the light compared to an object's vertex normals. Dynamic lighting will only look good if the - object being lit has a fair level of tessellation and the normals are properly set. This is particularly - true for the spotlight which will only look right on highly tessellated models. In the future OGRE may be - extended for certain scene types so an alternative to the standard dynamic lighting may be used, such - as dynamic lightmaps. - */ - class _OgreExport Light : public MovableObject - { - public: - /// Temp tag used for sorting - Real tempSquareDist; - /// internal method for calculating current squared distance from some world position - void _calcTempSquareDist(const Vector3& worldPos); - - /// Defines the type of light - enum LightTypes : uint8 - { - /// Point light sources give off light equally in all directions, so require only position not direction - LT_POINT = 0, - /// Directional lights simulate parallel light beams from a distant source, hence have direction but no position - LT_DIRECTIONAL = 1, - /// Spotlights simulate a cone of light from a source so require position and direction, plus extra values for falloff - LT_SPOTLIGHT = 2, - /// A rectangular area light, requires position, direction, width and height - LT_RECTLIGHT = 3 - }; - - /** Default constructor (for Python mainly). - */ - Light(); - - /** Normal constructor. Should not be called directly, but rather the SceneManager::createLight method should be used. - */ - Light(const String& name); - - /** Standard destructor. - */ - ~Light(); - - /** Sets the type of light - see LightTypes for more info. - */ - void setType(LightTypes type); - - /** Returns the light type. - */ - LightTypes getType(void) const; - - /** Sets the colour of the diffuse light given off by this source. - - Material objects have ambient, diffuse and specular values which indicate how much of each type of - light an object reflects. This value denotes the amount and colour of this type of light the light - exudes into the scene. The actual appearance of objects is a combination of the two. - @par - Diffuse light simulates the typical light emanating from light sources and affects the base colour - of objects together with ambient light. - */ - void setDiffuseColour(float red, float green, float blue); - - /// @overload - void setDiffuseColour(const ColourValue& colour); - - /** Returns the colour of the diffuse light given off by this light source (see setDiffuseColour for more info). - */ - const ColourValue& getDiffuseColour(void) const; - - /** Sets the colour of the specular light given off by this source. - - Material objects have ambient, diffuse and specular values which indicate how much of each type of - light an object reflects. This value denotes the amount and colour of this type of light the light - exudes into the scene. The actual appearance of objects is a combination of the two. - @par - Specular light affects the appearance of shiny highlights on objects, and is also dependent on the - 'shininess' Material value. - */ - void setSpecularColour(float red, float green, float blue); - - /// @overload - void setSpecularColour(const ColourValue& colour); - - /** Returns the colour of specular light given off by this light source. - */ - const ColourValue& getSpecularColour(void) const; - - /** Sets the attenuation parameters of the light source i.e. how it diminishes with distance. - - Lights normally get fainter the further they are away. Also, each light is given a maximum range - beyond which it cannot affect any objects. - @par - Light attenuation is not applicable to directional lights since they have an infinite range and - constant intensity. - @par - This follows a standard attenuation approach - see any good 3D text for the details of what they mean - since i don't have room here! - @param range - The absolute upper range of the light in world units. - @param constant - The constant factor in the attenuation formula: 1.0 means never attenuate, 0.0 is complete attenuation. - @param linear - The linear factor in the attenuation formula: 1 means attenuate evenly over the distance. - @param quadratic - The quadratic factor in the attenuation formula: adds a curvature to the attenuation formula. - */ - void setAttenuation(float range, float constant, float linear, float quadratic) - { - mAttenuation = {range, constant, linear, quadratic}; - } - - /** Returns the absolute upper range of the light. - */ - float getAttenuationRange(void) const { return mAttenuation[0]; } - - /** Returns the constant factor in the attenuation formula. - */ - float getAttenuationConstant(void) const { return mAttenuation[1]; } - - /** Returns the linear factor in the attenuation formula. - */ - float getAttenuationLinear(void) const { return mAttenuation[2]; } - - /** Returns the quadric factor in the attenuation formula. - */ - float getAttenuationQuadric(void) const { return mAttenuation[3]; } - - /// Returns all the attenuation params as (range, constant, linear, quadratic) - const Vector4f& getAttenuation() const { return mAttenuation; } - -#ifdef OGRE_NODELESS_POSITIONING - /** Sets the position of the light. - - Applicable to point lights and spotlights only. - @note - This will be overridden if the light is attached to a SceneNode. - @deprecated attach to SceneNode and use SceneNode::setPosition - */ - OGRE_DEPRECATED void setPosition(Real x, Real y, Real z); - - /// @overload - /// @deprecated attach to SceneNode and use SceneNode::setPosition - OGRE_DEPRECATED void setPosition(const Vector3& vec); - - /** Returns the position of the light. - @note - Applicable to point lights and spotlights only. - @deprecated attach to SceneNode and use SceneNode::getPosition - */ - OGRE_DEPRECATED const Vector3& getPosition(void) const; - - /// @deprecated attach to SceneNode and use SceneNode::setDirection - OGRE_DEPRECATED void setDirection(Real x, Real y, Real z); - - /// @overload - /// @deprecated attach to SceneNode and use SceneNode::setDirection - OGRE_DEPRECATED void setDirection(const Vector3& vec); - - /** - @deprecated attach to SceneNode and use SceneNode::getLocalAxes - */ - OGRE_DEPRECATED const Vector3& getDirection(void) const; - - void _notifyAttached(Node* parent, bool isTagPoint = false) override; - void _notifyMoved(void) override; -#endif - /** Sets the range of a spotlight, i.e. the angle of the inner and outer cones - and the rate of falloff between them. - @param innerAngle - Angle covered by the bright inner cone - @note - The inner cone applicable only to Direct3D, it'll always treat as zero in OpenGL. - @param outerAngle - Angle covered by the outer cone - @param falloff - The rate of falloff between the inner and outer cones. 1.0 means a linear falloff, - less means slower falloff, higher means faster falloff. - */ - void setSpotlightRange(const Radian& innerAngle, const Radian& outerAngle, Real falloff = 1.0); - - /** Returns the angle covered by the spotlights inner cone. - */ - const Radian& getSpotlightInnerAngle(void) const; - - /** Returns the angle covered by the spotlights outer cone. - */ - const Radian& getSpotlightOuterAngle(void) const; - - /** Returns the falloff between the inner and outer cones of the spotlight. - */ - Real getSpotlightFalloff(void) const; - - /** Sets the angle covered by the spotlights inner cone. - */ - void setSpotlightInnerAngle(const Radian& val); - - /** Sets the angle covered by the spotlights outer cone. - */ - void setSpotlightOuterAngle(const Radian& val); - - /** Sets the falloff between the inner and outer cones of the spotlight. - */ - void setSpotlightFalloff(Real val); - - /** Set the near clip plane distance to be used by spotlights that use light - clipping, allowing you to render spots as if they start from further - down their frustum. - @param nearClip - The near distance. - */ - void setSpotlightNearClipDistance(Real nearClip) { mSpotNearClip = nearClip; } - - /** Returns the near clip plane distance to be used by spotlights that use light - clipping. - */ - Real getSpotlightNearClipDistance() const { return mSpotNearClip; } - - /** Sets the size of the area covered by a area light. */ - void setSourceSize(float width, float height) { mSourceSize = {width, height}; } - Vector2f getSourceSize() const { return mSourceSize; } - - /// The width half vector of the source in world space - Vector3f getDerivedSourceHalfWidth() const; - - /// The height half vector of the source in world space - Vector3f getDerivedSourceHalfHeight() const; - - /** Set a scaling factor to indicate the relative power of a light. - - This factor is only useful in High Dynamic Range (HDR) rendering. - You can bind it to a shader variable to take it into account, - @see GpuProgramParameters - @param power - The power rating of this light, default is 1.0. - */ - void setPowerScale(Real power); - - /** Returns the scaling factor which indicates the relative power of a - light. - */ - Real getPowerScale(void) const; - - Real getBoundingRadius(void) const override { return 0; } - const AxisAlignedBox& getBoundingBox(void) const override; - - void _updateRenderQueue(RenderQueue* queue) override {} // No rendering - - /** @copydoc MovableObject::getMovableType */ - const String& getMovableType(void) const override; - - /** Retrieves the position of the light including any transform from nodes it is attached to. - @param cameraRelativeIfSet If set to true, returns data in camera-relative units if that's been set up (render use) - */ -#ifdef OGRE_NODELESS_POSITIONING - const Vector3& getDerivedPosition(bool cameraRelativeIfSet = false) const; -#else - Vector3 getDerivedPosition(bool cameraRelativeIfSet = false) const - { - assert(mParentNode && "Light must be attached to a SceneNode"); - auto ret = mParentNode->_getDerivedPosition(); - if (cameraRelativeIfSet && mCameraToBeRelativeTo) - ret -= mCameraToBeRelativeTo->getDerivedPosition(); - return ret; - } -#endif - - /** Retrieves the direction of the light including any transform from nodes it is attached to. */ -#ifdef OGRE_NODELESS_POSITIONING - const Vector3& getDerivedDirection(void) const; -#else - Vector3 getDerivedDirection(void) const - { - assert(mParentNode && "Light must be attached to a SceneNode"); - return -mParentNode->_getDerivedOrientation().zAxis(); - } -#endif - - /** @copydoc MovableObject::setVisible - - Although lights themselves are not 'visible', setting a light to invisible - means it no longer affects the scene. - */ - void setVisible(bool visible) { MovableObject::setVisible(visible); } - - /** Returns the details of this light as a 4D vector. - - Getting details of a light as a 4D vector can be useful for - doing general calculations between different light types; for - example the vector can represent both position lights (w=1.0f) - and directional lights (w=0.0f) and be used in the same - calculations. - @param cameraRelativeIfSet - If set to @c true, returns data in camera-relative units if that's been set up (render use). - */ - Vector4 getAs4DVector(bool cameraRelativeIfSet = false) const; - - /** Internal method for calculating the 'near clip volume', which is - the volume formed between the near clip rectangle of the - camera and the light. - - This volume is a pyramid for a point/spot light and - a cuboid for a directional light. It can used to detect whether - an object could be casting a shadow on the viewport. Note that - the reference returned is to a shared volume which will be - reused across calls to this method. - */ - virtual const PlaneBoundedVolume& _getNearClipVolume(const Camera* const cam) const; - - /** Internal method for calculating the clip volumes outside of the - frustum which can be used to determine which objects are casting - shadow on the frustum as a whole. - - Each of the volumes is a pyramid for a point/spot light and - a cuboid for a directional light. - */ - virtual const PlaneBoundedVolumeList& _getFrustumClipVolumes(const Camera* const cam) const; - - /// Override to return specific type flag - uint32 getTypeFlags(void) const override; - - /// @copydoc AnimableObject::createAnimableValue - AnimableValuePtr createAnimableValue(const String& valueName) override; - - /** Set this light to use a custom shadow camera when rendering texture shadows. - - This changes the shadow camera setup for just this light, you can set - the shadow camera setup globally using SceneManager::setShadowCameraSetup - @see ShadowCameraSetup - */ - void setCustomShadowCameraSetup(const ShadowCameraSetupPtr& customShadowSetup); - - /** Reset the shadow camera setup to the default. - @see ShadowCameraSetup - */ - void resetCustomShadowCameraSetup(void); - - /** Return a pointer to the custom shadow camera setup (null means use SceneManager global version). */ - const ShadowCameraSetupPtr& getCustomShadowCameraSetup(void) const; - - void visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables = false) override; - - /** Returns the index at which this light is in the current render. - - Lights will be present in the in a list for every renderable, - detected and sorted appropriately, and sometimes it's useful to know - what position in that list a given light occupies. This can vary - from frame to frame (and object to object) so you should not use this - value unless you're sure the context is correct. - */ - size_t _getIndexInFrame() const { return mIndexInFrame; } - void _notifyIndexInFrame(size_t i) { mIndexInFrame = i; } - - /** Sets the maximum distance away from the camera that shadows - by this light will be visible. - - Shadow techniques can be expensive, therefore it is a good idea - to limit them to being rendered close to the camera if possible, - and to skip the expense of rendering shadows for distance objects. - This method allows you to set the distance at which shadows casters - will be culled. - */ - void setShadowFarDistance(Real distance); - /** Tells the light to use the shadow far distance of the SceneManager - */ - void resetShadowFarDistance(void); - /** Returns the maximum distance away from the camera that shadows - by this light will be visible. - */ - Real getShadowFarDistance(void) const; - Real getShadowFarDistanceSquared(void) const; - - /** Set the near clip plane distance to be used by the shadow camera, if - this light casts texture shadows. - @param nearClip - The distance, or -1 to use the main camera setting. - */ - void setShadowNearClipDistance(Real nearClip) { mShadowNearClipDist = nearClip; } - - /** Returns the near clip plane distance to be used by the shadow camera, if - this light casts texture shadows. - - May be zero if the light doesn't have it's own near distance set; - use _deriveShadowNearDistance for a version guaranteed to give a result. - */ - Real getShadowNearClipDistance() const { return mShadowNearClipDist; } - - /** Derive a shadow camera near distance from either the light, or - from the main camera if the light doesn't have its own setting. - */ - Real _deriveShadowNearClipDistance(const Camera* maincam) const; - - /** Set the far clip plane distance to be used by the shadow camera, if - this light casts texture shadows. - - This is different from the 'shadow far distance', which is - always measured from the main camera. This distance is the far clip plane - of the light camera. - @param farClip - The distance, or -1 to use the main camera setting. - */ - void setShadowFarClipDistance(Real farClip) { mShadowFarClipDist = farClip; } - - /** Returns the far clip plane distance to be used by the shadow camera, if - this light casts texture shadows. - - May be zero if the light doesn't have it's own far distance set; - use _deriveShadowfarDistance for a version guaranteed to give a result. - */ - Real getShadowFarClipDistance() const { return mShadowFarClipDist; } - - /** Derive a shadow camera far distance - */ - Real _deriveShadowFarClipDistance() const; - /// @deprecated use _deriveShadowFarClipDistance() - OGRE_DEPRECATED Real _deriveShadowFarClipDistance(const Camera*) const - { - return _deriveShadowFarClipDistance(); - } - - /// Set the camera which this light should be relative to, for camera-relative rendering - void _setCameraRelative(Camera* cam); - - /** Sets a custom parameter for this Light, which may be used to - drive calculations for this specific Renderable, like GPU program parameters. - - Calling this method simply associates a numeric index with a 4-dimensional - value for this specific Light. This is most useful if the material - which this Renderable uses a vertex or fragment program, and has an - ACT_LIGHT_CUSTOM parameter entry. This parameter entry can refer to the - index you specify as part of this call, thereby mapping a custom - parameter for this renderable to a program parameter. - @param index - The index with which to associate the value. Note that this - does not have to start at 0, and can include gaps. It also has no direct - correlation with a GPU program parameter index - the mapping between the - two is performed by the ACT_LIGHT_CUSTOM entry, if that is used. - @param value - The value to associate. - */ - void setCustomParameter(uint16 index, const Vector4f& value); - - /** Returns the custom value associated with this Light at the given index. - @param index Index of the parameter to retrieve - @see setCustomParameter for full details. - */ - const Vector4f& getCustomParameter(uint16 index) const; - - /** Update a custom GpuProgramParameters constant which is derived from - information only this Light knows. - - This method allows a Light to map in a custom GPU program parameter - based on it's own data. This is represented by a GPU auto parameter - of ACT_LIGHT_CUSTOM, and to allow there to be more than one of these per - Light, the 'data' field on the auto parameter will identify - which parameter is being updated and on which light. The implementation - of this method must identify the parameter being updated, and call a 'setConstant' - method on the passed in GpuProgramParameters object. - @par - You do not need to override this method if you're using the standard - sets of data associated with the Renderable as provided by setCustomParameter - and getCustomParameter. By default, the implementation will map from the - value indexed by the 'constantEntry.data' parameter to a value previously - set by setCustomParameter. But custom Renderables are free to override - this if they want, in any case. - @param paramIndex - The index of the constant being updated - @param constantEntry - The auto constant entry from the program parameters - @param params - The parameters object which this method should call to - set the updated parameters. - */ - virtual void _updateCustomGpuParameter(uint16 paramIndex, - const GpuProgramParameters::AutoConstantEntry& constantEntry, - GpuProgramParameters* params) const; - - /** Check whether a sphere is included in the lighted area of the light - @note - The function trades accuracy for efficiency. As a result you may get - false-positives (The function should not return any false-negatives). - */ - bool isInLightRange(const Ogre::Sphere& sphere) const; - - /** Check whether a bounding box is included in the lighted area of the light - @note - The function trades accuracy for efficiency. As a result you may get - false-positives (The function should not return any false-negatives). - */ - bool isInLightRange(const Ogre::AxisAlignedBox& container) const; - - private: -#ifdef OGRE_NODELESS_POSITIONING - Vector3 mPosition; - Vector3 mDirection; - mutable Vector3 mDerivedPosition; - mutable Vector3 mDerivedDirection; - // Slightly hacky but unless we separate observed light render state from main Light... - mutable Vector3 mDerivedCamRelativePosition; - mutable bool mDerivedCamRelativeDirty; - /// Is the derived transform dirty? - mutable bool mDerivedTransformDirty; - - /// Internal method for synchronising with parent node (if any) - virtual void update(void) const; -#endif - ColourValue mDiffuse; - ColourValue mSpecular; - - Radian mSpotOuter; - Radian mSpotInner; - Real mSpotFalloff; - Real mSpotNearClip; - // range, const, linear, quad coeffs - Vector4f mAttenuation; - Real mShadowFarDist; - Real mShadowFarDistSquared; - size_t mIndexInFrame; - - Real mShadowNearClipDist; - Real mShadowFarClipDist; - - Camera* mCameraToBeRelativeTo; - - mutable PlaneBoundedVolume mNearClipVolume; - mutable PlaneBoundedVolumeList mFrustumClipVolumes; - - /// Pointer to a custom shadow camera setup. - mutable ShadowCameraSetupPtr mCustomShadowCameraSetup; - - typedef std::map CustomParameterMap; - /// Stores the custom parameters for the light. - CustomParameterMap mCustomParameters; - Real mPowerScale; - Vector2f mSourceSize; - LightTypes mLightType; - bool mOwnShadowFarDist; - }; - /** @} */ - /** @} */ - -#include "OgreHeaderSuffix.h" - -} // namespace Ogre -#endif // _LIGHT_H__ diff --git a/OgreMain/include/OgreLodListener.h b/OgreMain/include/OgreLodListener.h deleted file mode 100644 index fdb4dbc028b..00000000000 --- a/OgreMain/include/OgreLodListener.h +++ /dev/null @@ -1,207 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __LodListener_H__ -#define __LodListener_H__ - - -#include "OgrePrerequisites.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup LOD - * @{ - */ - /// Struct containing information about a LOD change event for movable objects. - struct MovableObjectLodChangedEvent - { - /// The movable object whose level of detail has changed. - MovableObject *movableObject; - - /// The camera with respect to which the level of detail has changed. - Camera *camera; - }; - - /// Struct containing information about a mesh LOD change event for entities. - struct EntityMeshLodChangedEvent - { - /// The entity whose level of detail has changed. - Entity *entity; - - /// The camera with respect to which the level of detail has changed. - Camera *camera; - - /// LOD value as determined by LOD strategy. - Real lodValue; - - /// Previous level of detail index. - ushort previousLodIndex; - - /// New level of detail index. - ushort newLodIndex; - }; - - /// Struct containing information about a material LOD change event for entities. - struct EntityMaterialLodChangedEvent - { - /// The sub-entity whose material's level of detail has changed. - SubEntity *subEntity; - - /// The camera with respect to which the level of detail has changed. - Camera *camera; - - /// LOD value as determined by LOD strategy. - Real lodValue; - - /// Previous level of detail index. - ushort previousLodIndex; - - /// New level of detail index. - ushort newLodIndex; - }; - - - /** A interface class defining a listener which can be used to receive - notifications of LOD events. - - A 'listener' is an interface designed to be called back when - particular events are called. This class defines the - interface relating to LOD events. In order to receive - notifications of LOD events, you should create a subclass of - LodListener and override the methods for which you would like - to customise the resulting processing. You should then call - SceneManager::addLodListener passing an instance of this class. - There is no limit to the number of LOD listeners you can register, - allowing you to register multiple listeners for different purposes. - - For some uses, it may be advantageous to also subclass - RenderQueueListener as this interface makes available information - regarding render queue invocations. - - It is important not to modify the scene graph during rendering, so, - for each event, there are two methods, a prequeue method and a - postqueue method. The prequeue method is invoked during rendering, - and as such should not perform any changes, but if the event is - relevant, it may return true indicating the postqueue method should - also be called. The postqueue method is invoked at an appropriate - time after rendering and scene changes may be safely made there. - */ - class _OgreExport LodListener - { - public: - - virtual ~LodListener() {} - - /** - Called before a movable object's LOD has changed. - - Do not change the Ogre state from this method, - instead return true and perform changes in - postqueueMovableObjectLodChanged. - @return - True to indicate the event should be queued and - postqueueMovableObjectLodChanged called after - rendering is complete. - */ - virtual bool prequeueMovableObjectLodChanged(const MovableObjectLodChangedEvent& evt) - { (void)evt; return false; } - - /** - Called after a movable object's LOD has changed. - - May be called even if not requested from prequeueMovableObjectLodChanged - as only one event queue is maintained per SceneManger instance. - */ - virtual void postqueueMovableObjectLodChanged(const MovableObjectLodChangedEvent& evt) - { (void)evt; } - - /** - Called before an entity's mesh LOD has changed. - - Do not change the Ogre state from this method, - instead return true and perform changes in - postqueueEntityMeshLodChanged. - - It is possible to change the event notification - and even alter the newLodIndex field (possibly to - prevent the LOD from changing, or to skip an - index). - @return - True to indicate the event should be queued and - postqueueEntityMeshLodChanged called after - rendering is complete. - */ - virtual bool prequeueEntityMeshLodChanged(EntityMeshLodChangedEvent& evt) - { (void)evt; return false; } - - /** - Called after an entity's mesh LOD has changed. - - May be called even if not requested from prequeueEntityMeshLodChanged - as only one event queue is maintained per SceneManger instance. - */ - virtual void postqueueEntityMeshLodChanged(const EntityMeshLodChangedEvent& evt) - { (void)evt; } - - /** - Called before an entity's material LOD has changed. - - Do not change the Ogre state from this method, - instead return true and perform changes in - postqueueMaterialLodChanged. - - It is possible to change the event notification - and even alter the newLodIndex field (possibly to - prevent the LOD from changing, or to skip an - index). - @return - True to indicate the event should be queued and - postqueueMaterialLodChanged called after - rendering is complete. - */ - virtual bool prequeueEntityMaterialLodChanged(EntityMaterialLodChangedEvent& evt) - { (void)evt; return false; } - - /** - Called after an entity's material LOD has changed. - - May be called even if not requested from prequeueEntityMaterialLodChanged - as only one event queue is maintained per SceneManger instance. - */ - virtual void postqueueEntityMaterialLodChanged(const EntityMaterialLodChangedEvent& evt) - { (void)evt; } - - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/OgreMain/include/OgreLodStrategy.h b/OgreMain/include/OgreLodStrategy.h deleted file mode 100755 index 426afc75fea..00000000000 --- a/OgreMain/include/OgreLodStrategy.h +++ /dev/null @@ -1,134 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Lod_Strategy_H__ -#define __Lod_Strategy_H__ - -#include "OgrePrerequisites.h" - -#include "OgreMesh.h" -#include "OgreMaterial.h" - -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \defgroup LOD Level of Detail - * @{ - */ - /** Strategy for determining level of detail. - - Generally, to create a new LOD strategy, all of the following will - need to be implemented: getValueImpl, getBaseValue, transformBias, - getIndex, sort, and isSorted. - In addition, transformUserValue may be overridden. - */ - class _OgreExport LodStrategy : public LodAlloc - { - private: - /** Name of this strategy. */ - String mName; - - /** Compute the LOD value for a given movable object relative to a given camera. */ - virtual Real getValueImpl(const MovableObject *movableObject, const Camera *camera) const = 0; - - public: - /** Constructor accepting name. */ - LodStrategy(const String& name); - - /** Virtual destructor. */ - virtual ~LodStrategy(); - - /** Get the value of the first (highest) level of detail. */ - virtual Real getBaseValue() const = 0; - - /** Transform LOD bias so it only needs to be multiplied by the LOD value. */ - virtual Real transformBias(Real factor) const = 0; - - /** Transform user supplied value to internal value. - - By default, performs no transformation. - - Do not throw exceptions for invalid values here, as the LOD strategy - may be changed such that the values become valid. - */ - virtual Real transformUserValue(Real userValue) const; - - /** Compute the LOD value for a given movable object relative to a given camera. */ - Real getValue(const MovableObject *movableObject, const Camera *camera) const; - - /** Get the index of the LOD usage which applies to a given value. */ - virtual ushort getIndex(Real value, const Mesh::MeshLodUsageList& meshLodUsageList) const = 0; - - /** Get the index of the LOD usage which applies to a given value. */ - virtual ushort getIndex(Real value, const Material::LodValueList& materialLodValueList) const = 0; - - /** Sort mesh LOD usage list from greatest to least detail */ - virtual void sort(Mesh::MeshLodUsageList& meshLodUsageList) const = 0; - - /** Determine if the LOD values are sorted from greatest detail to least detail. */ - virtual bool isSorted(const Mesh::LodValueList& values) const = 0; - - /** Assert that the LOD values are sorted from greatest detail to least detail. */ - void assertSorted(const Mesh::LodValueList& values) const; - - /** Get the name of this strategy. */ - const String& getName() const { return mName; } - - protected: - /** Implementation of isSorted suitable for ascending values. */ - static bool isSortedAscending(const Mesh::LodValueList& values); - /** Implementation of isSorted suitable for descending values. */ - static bool isSortedDescending(const Mesh::LodValueList& values); - - /** Implementation of sort suitable for ascending values. */ - static void sortAscending(Mesh::MeshLodUsageList& meshLodUsageList); - /** Implementation of sort suitable for descending values. */ - static void sortDescending(Mesh::MeshLodUsageList& meshLodUsageList); - - /** Implementation of getIndex suitable for ascending values. */ - static ushort getIndexAscending(Real value, const Mesh::MeshLodUsageList& meshLodUsageList); - /** Implementation of getIndex suitable for descending values. */ - static ushort getIndexDescending(Real value, const Mesh::MeshLodUsageList& meshLodUsageList); - - /** Implementation of getIndex suitable for ascending values. */ - static ushort getIndexAscending(Real value, const Material::LodValueList& materialLodValueList); - /** Implementation of getIndex suitable for descending values. */ - static ushort getIndexDescending(Real value, const Material::LodValueList& materialLodValueList); - - }; - /** @} */ - /** @} */ - -} // namespace - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreLodStrategyManager.h b/OgreMain/include/OgreLodStrategyManager.h deleted file mode 100644 index ece707c5c51..00000000000 --- a/OgreMain/include/OgreLodStrategyManager.h +++ /dev/null @@ -1,107 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Lod_Strategy_Manager_H__ -#define __Lod_Strategy_Manager_H__ - -#include "OgrePrerequisites.h" - -#include "OgreSingleton.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - template class MapIterator; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup LOD - * @{ - */ - /** Manager for LOD strategies. */ - class _OgreExport LodStrategyManager : public Singleton, public LodAlloc - { - /** Map of strategies. */ - typedef std::map StrategyMap; - - /** Internal map of strategies. */ - StrategyMap mStrategies; - - /** Default strategy. */ - LodStrategy *mDefaultStrategy; - - public: - /** Default constructor. */ - LodStrategyManager(); - - /** Destructor. */ - ~LodStrategyManager(); - - /** Add a strategy to the manager. */ - void addStrategy(LodStrategy *strategy); - - /** Remove a strategy from the manager with a specified name. - - The removed strategy is returned so the user can control - how it is destroyed. - */ - LodStrategy *removeStrategy(const String& name); - - /** Remove and delete all strategies from the manager. - - All strategies are deleted. If finer control is required - over strategy destruction, use removeStrategy. - */ - void removeAllStrategies(); - - /** Get the strategy with the specified name. */ - LodStrategy *getStrategy(const String& name); - - /** Set the default strategy. */ - void setDefaultStrategy(LodStrategy *strategy); - - /** Set the default strategy by name. */ - void setDefaultStrategy(const String& name); - - /** Get the current default strategy. */ - LodStrategy *getDefaultStrategy(); - - /** Get an iterator for all contained strategies. */ - MapIterator getIterator(); - - /// @copydoc Singleton::getSingleton() - static LodStrategyManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static LodStrategyManager* getSingletonPtr(void); - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreLog.h b/OgreMain/include/OgreLog.h deleted file mode 100644 index dfc87255865..00000000000 --- a/OgreMain/include/OgreLog.h +++ /dev/null @@ -1,252 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Log_H__ -#define __Log_H__ - -#include "OgrePrerequisites.h" -#include "OgreCommon.h" -#include "Threading/OgreThreadHeaders.h" -#include "OgreHeaderPrefix.h" - -#include -#include - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - - /// @deprecated use LogMessageLevel instead - enum LoggingLevel - { - LL_LOW = 1, - LL_NORMAL = 2, - LL_BOREME = 3 - }; - - /** The importance of a logged message. - */ - enum LogMessageLevel - { - LML_TRIVIAL = 1, - LML_NORMAL = 2, - LML_WARNING = 3, - LML_CRITICAL = 4 - }; - - /** @remarks Pure Abstract class, derive this class and register to the Log to listen to log messages */ - class LogListener - { - public: - virtual ~LogListener() {} - - /** - - This is called whenever the log receives a message and is about to write it out - @param message - The message to be logged - @param lml - The message level the log is using - @param maskDebug - If we are printing to the console or not - @param logName - The name of this log (so you can have several listeners for different logs, and identify them) - @param skipThisMessage - If set to true by the messageLogged() implementation message will not be logged - */ - virtual void messageLogged( const String& message, LogMessageLevel lml, bool maskDebug, const String &logName, bool& skipThisMessage ) = 0; - }; - - - /** - Log class for writing debug/log data to files. - - You can control the default log level through the `OGRE_MIN_LOGLEVEL` environment variable. - Here, the value 1 corresponds to #LML_TRIVIAL etc. - @note Should not be used directly, but through the LogManager class. - */ - class _OgreExport Log : public LogAlloc - { - private: - std::ofstream mLog; - LogMessageLevel mLogLevel; - bool mDebugOut; - bool mSuppressFile; - bool mTimeStamp; - String mLogName; - bool mTermHasColours; - - typedef std::vector mtLogListener; - mtLogListener mListeners; - public: - - class Stream; - - OGRE_AUTO_MUTEX; // public to allow external locking - /** - - Usual constructor - called by LogManager. - */ - Log( const String& name, bool debugOutput = true, bool suppressFileOutput = false); - - /** - - Default destructor. - */ - ~Log(); - - /// Return the name of the log - const String& getName() const { return mLogName; } - /// Get whether debug output is enabled for this log - bool isDebugOutputEnabled() const { return mDebugOut; } - /// Get whether file output is suppressed for this log - bool isFileOutputSuppressed() const { return mSuppressFile; } - /// Get whether time stamps are printed for this log - bool isTimeStampEnabled() const { return mTimeStamp; } - - /** Log a message to the debugger and to log file (the default is - "OGRE.log"), - */ - void logMessage( const String& message, LogMessageLevel lml = LML_NORMAL, bool maskDebug = false ); - - /** Get a stream object targeting this log. */ - Stream stream(LogMessageLevel lml = LML_NORMAL, bool maskDebug = false); - - /** - - Enable or disable outputting log messages to the debugger. - */ - void setDebugOutputEnabled(bool debugOutput); - /// @deprecated use setMinLogLevel() - OGRE_DEPRECATED void setLogDetail(LoggingLevel ll); - /// set the minimal #LogMessageLevel for a message to be logged - void setMinLogLevel(LogMessageLevel lml); - /** - - Enable or disable time stamps. - */ - void setTimeStampEnabled(bool timeStamp); - /** Gets the level of the log detail. - */ - LogMessageLevel getMinLogLevel() const { return mLogLevel; } - /** - - Register a listener to this log - @param listener - A valid listener derived class - */ - void addListener(LogListener* listener); - - /** - - Unregister a listener from this log - @param listener - A valid listener derived class - */ - void removeListener(LogListener* listener); - - /** Stream object which targets a log. - - A stream logger object makes it simpler to send various things to - a log. You can just use the operator<< implementation to stream - anything to the log, which is cached until a Stream::Flush is - encountered, or the stream itself is destroyed, at which point the - cached contents are sent to the underlying log. You can use Log::stream() - directly without assigning it to a local variable and as soon as the - streaming is finished, the object will be destroyed and the message - logged. - @par - You can stream control operations to this object too, such as - std::setw() and std::setfill() to control formatting. - @note - Each Stream object is not thread safe, so do not pass it between - threads. Multiple threads can hold their own Stream instances pointing - at the same Log though and that is threadsafe. - */ - class _OgrePrivate Stream - { - private: - Log* mTarget; - LogMessageLevel mLevel; - bool mMaskDebug; - typedef StringStream BaseStream; - BaseStream mCache; - - public: - - /// Simple type to indicate a flush of the stream to the log - struct Flush {}; - - Stream(Log* target, LogMessageLevel lml, bool maskDebug) - :mTarget(target), mLevel(lml), mMaskDebug(maskDebug) - { - - } - // move constructor - Stream(Stream&& rhs) = default; - - ~Stream() - { - // flush on destroy - if (mCache.tellp() > 0) - { - mTarget->logMessage(mCache.str(), mLevel, mMaskDebug); - } - } - - template - Stream& operator<< (const T& v) - { - mCache << v; - return *this; - } - - Stream& operator<< (const Flush& v) - { - (void)v; - mTarget->logMessage(mCache.str(), mLevel, mMaskDebug); - mCache.str(BLANKSTRING); - return *this; - } - - - }; - - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreLogManager.h b/OgreMain/include/OgreLogManager.h deleted file mode 100644 index 6ea78412cbc..00000000000 --- a/OgreMain/include/OgreLogManager.h +++ /dev/null @@ -1,155 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __LogManager_H__ -#define __LogManager_H__ - -#include "OgrePrerequisites.h" - -#include "OgreLog.h" -#include "OgreSingleton.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - /** The log manager handles the creation and retrieval of logs for the - application. - - This class will create new log files and will retrieve instances - of existing ones. Other classes wishing to log output can either - create a fresh log or retrieve an existing one to output to. - One log is the default log, and is the one written to when the - logging methods of this class are called. - @par - By default, Root will instantiate a LogManager (which becomes the - Singleton instance) on construction, and will create a default log - based on the Root construction parameters. If you want more control, - for example redirecting log output right from the start or suppressing - debug output, you need to create a LogManager yourself before creating - a Root instance, then create a default log. Root will detect that - you've created one yourself and won't create one of its own, thus - using all your logging preferences from the first instance. - */ - class _OgreExport LogManager : public Singleton, public LogAlloc - { - private: - typedef std::map LogList; - - /// A list of all the logs the manager can access - LogList mLogs; - - /// The default log to which output is done - Log* mDefaultLog; - - public: - OGRE_AUTO_MUTEX; // public to allow external locking - - LogManager(); - ~LogManager(); - - /** Creates a new log with the given name. - @param - name The name to give the log e.g. 'Ogre.log' - @param - defaultLog If true, this is the default log output will be - sent to if the generic logging methods on this class are - used. The first log created is always the default log unless - this parameter is set. - @param - debuggerOutput If true, output to this log will also be - routed to the debugger's output window. - @param - suppressFileOutput If true, this is a logical rather than a physical - log and no file output will be written. If you do this you should - register a LogListener so log output is not lost. - */ - Log* createLog( const String& name, bool defaultLog = false, bool debuggerOutput = true, - bool suppressFileOutput = false); - - /** Retrieves a log managed by this class. - */ - Log* getLog( const String& name); - - /** Returns a pointer to the default log. - */ - Log* getDefaultLog(); - - /** Closes and removes a named log. */ - void destroyLog(const String& name); - /** Closes and removes a log. */ - void destroyLog(Log* log); - - /** Sets the passed in log as the default log. - @return The previous default log. - */ - Log* setDefaultLog(Log* newLog); - - /** Log a message to the default log. - */ - void logMessage( const String& message, LogMessageLevel lml = LML_NORMAL, - bool maskDebug = false); - - /// @overload - void logError(const String& message, bool maskDebug = false ); - /// @overload - void logWarning(const String& message, bool maskDebug = false ); - - /** Log a message to the default log (signature for backward compatibility). - */ - void logMessage( LogMessageLevel lml, const String& message, - bool maskDebug = false) { logMessage(message, lml, maskDebug); } - - /** Get a stream on the default log. */ - Log::Stream stream(LogMessageLevel lml = LML_NORMAL, - bool maskDebug = false); - - /// @deprecated use setMinLogLevel() - OGRE_DEPRECATED void setLogDetail(LoggingLevel ll); - /// sets the minimal #LogMessageLevel for the default log - void setMinLogLevel(LogMessageLevel lml); - /// @copydoc Singleton::getSingleton() - static LogManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static LogManager* getSingletonPtr(void); - - }; - - - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreManualObject.h b/OgreMain/include/OgreManualObject.h deleted file mode 100644 index 45c8bdaf23e..00000000000 --- a/OgreMain/include/OgreManualObject.h +++ /dev/null @@ -1,696 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __OgreManualObject_H__ -#define __OgreManualObject_H__ - -#include "OgrePrerequisites.h" -#include "OgreMovableObject.h" -#include "OgreRenderable.h" -#include "OgreResourceGroupManager.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** Class providing a much simplified interface to generating manual - objects with custom geometry. - - Building one-off geometry objects manually usually requires getting - down and dirty with the vertex buffer and vertex declaration API, - which some people find a steep learning curve. This class gives you - a simpler interface specifically for the purpose of building a - 3D object simply and quickly. Note that if you intend to instance your - object you will still need to become familiar with the Mesh class. - - This class draws heavily on the interface for OpenGL - immediate-mode (@c glBegin, @c glVertex, @c glNormal etc), since this - is generally well-liked by people. There are a couple of differences - in the results though - internally this class still builds hardware - buffers which can be re-used, so you can render the resulting object - multiple times without re-issuing all the same commands again. - Secondly, the rendering is not immediate, it is still queued just like - all OGRE objects. This makes this object more efficient than the - equivalent GL immediate-mode commands, so it's feasible to use it for - large objects if you really want to. - - To construct some geometry with this object: - -# If you know roughly how many vertices (and indices, if you use them) - you're going to submit, call estimateVertexCount() and estimateIndexCount(). - This is not essential but will make the process more efficient by saving - memory reallocations. - -# Call begin() to begin entering data - -# For each vertex, call position(), normal(), textureCoord(), colour() - to define your vertex data. Note that each time you call position() - you start a new vertex. Note that the first vertex defines the - components of the vertex - you can't add more after that. For example - if you didn't call normal() in the first vertex, you cannot call it - in any others. You ought to call the same combination of methods per - vertex. - -# If you want to define triangles (or lines/points) by indexing into the vertex list, - you can call index() as many times as you need to define them. - If you don't do this, the class will assume you want triangles drawn - directly as defined by the vertex list, i.e. non-indexed geometry. Note - that stencil shadows are only supported on indexed geometry, and that - indexed geometry is a little faster; so you should try to use it. - -# Call end() to finish entering data. - -# Optionally repeat the begin-end cycle if you want more geometry - using different rendering operation types, or different materials - After calling end(), the class will organise the data for that section - internally and make it ready to render with. Like any other - MovableObject you should attach the object to a SceneNode to make it - visible. Other aspects like the relative render order can be controlled - using standard MovableObject methods like setRenderQueueGroup. - - You can also use beginUpdate() to alter the geometry later on if you wish. - If you do this, you should call setDynamic(true) before your first call - to begin(), and also consider using estimateVertexCount() / estimateIndexCount() - if your geometry is going to be growing, to avoid buffer recreation during - growth. - - @note like all OGRE geometry, triangles should be specified in - anti-clockwise winding order (whether you're doing it with just - vertices, or using indexes too). That is to say that the front of the - face is the one where the vertices are listed in anti-clockwise order. - */ - class _OgreExport ManualObject : public MovableObject - { - public: - ManualObject(const String& name); - virtual ~ManualObject(); - - /** @copydoc MovableObject::_releaseManualHardwareResources */ - void _releaseManualHardwareResources() override { clear(); } - - //pre-declare ManualObjectSection - class ManualObjectSection; - - /** Completely clear the contents of the object. - - Clearing the contents of this object and rebuilding from scratch - is not the optimal way to manage dynamic vertex data, since the - buffers are recreated. If you want to keep the same structure but - update the content within that structure, use beginUpdate() instead - of clear() begin(). However if you do want to modify the structure - from time to time you can do so by clearing and re-specifying the data. - */ - void clear(void); - - /** Estimate the number of vertices ahead of time. - - Calling this helps to avoid memory reallocation when you define - vertices. Also very handy when using beginUpdate() to manage dynamic - data - you can make the vertex buffers a little larger than their - initial needs to allow for growth later with this method. - */ - virtual void estimateVertexCount(uint32 vcount); - - /** Estimate the number of indices ahead of time. - - Calling this helps to avoid memory reallocation when you define - indices. Also very handy when using beginUpdate() to manage dynamic - data - you can make the index buffer a little larger than the - initial need to allow for growth later with this method. - */ - virtual void estimateIndexCount(uint32 icount); - - /** Start defining a part of the object. - - Each time you call this method, you start a new section of the - object with its own material and potentially its own type of - rendering operation (triangles, points or lines for example). - @param materialName The name of the material to render this part of the - object with. - @param opType The type of operation to use to render. - @param groupName The resource group of the material to render this part - of the object with. - */ - virtual void begin(const String& materialName, - RenderOperation::OperationType opType = RenderOperation::OT_TRIANGLE_LIST, - const String& groupName = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - /** @overload - @param mat The material to render this part of the object with. - @param opType The type of operation to use to render. - */ - virtual void begin(const MaterialPtr& mat, - RenderOperation::OperationType opType = RenderOperation::OT_TRIANGLE_LIST); - - /** Use before defining geometry to indicate how you intend to update the - geometry. - */ - void setBufferUsage(HardwareBuffer::Usage usage) { mBufferUsage = (HardwareBufferUsage)usage; } - - /// @overload - void setDynamic(bool dyn) { mBufferUsage = dyn ? HBU_CPU_TO_GPU : HBU_GPU_ONLY; } - - /** Gets whether this object is marked as dynamic */ - bool getDynamic() const { return mBufferUsage & HBU_CPU_ONLY; } - - /** Start the definition of an update to a part of the object. - - Using this method, you can update an existing section of the object - efficiently. You do not have the option of changing the operation type - obviously, since it must match the one that was used before. - @note If your sections are changing size, particularly growing, use - estimateVertexCount and estimateIndexCount to pre-size the buffers a little - larger than the initial needs to avoid buffer reconstruction. - @param sectionIndex The index of the section you want to update. The first - call to begin() would have created section 0, the second section 1, etc. - */ - virtual void beginUpdate(size_t sectionIndex); - /** Add a vertex position, starting a new vertex at the same time. - @remarks A vertex position is slightly special among the other vertex data - methods like normal() and textureCoord(), since calling it indicates - the start of a new vertex. All other vertex data methods you call - after this are assumed to be adding more information (like normals or - texture coordinates) to the last vertex started with position(). - */ - void position(const Vector3& pos) - { - OgreAssert(mCurrentSection, "You must call begin() before this method"); - if (mTempVertexPending) - { - // bake current vertex - copyTempVertexToBuffer(); - mFirstVertex = false; - } - - if (mFirstVertex && !mCurrentUpdating) - { - declareElement(VET_FLOAT3, VES_POSITION); - } - - mTempVertex.position = Vector3f(pos); - - // update bounds - mAABB.merge(pos); - mRadius = std::max(mRadius, mTempVertex.position.length()); - - // reset current texture coord - mTexCoordIndex = 0; - - mTempVertexPending = true; - } - /// @overload - void position(float x, float y, float z) { position({x, y, z}); } - - /** Add a vertex normal to the current vertex. - - Vertex normals are most often used for dynamic lighting, and - their components should be normalised. - */ - void normal(const Vector3& norm) - { - OgreAssert(mCurrentSection, "You must call begin() before this method"); - if (mFirstVertex && !mCurrentUpdating) - { - declareElement(VET_FLOAT3, VES_NORMAL); - } - mTempVertex.normal = Vector3f(norm); - } - /// @overload - void normal(float x, float y, float z) { normal({x, y, z}); } - - /** Add a vertex tangent to the current vertex. - - Vertex tangents are most often used for dynamic lighting, and - their components should be normalised. - Also, using tangent() you enable VES_TANGENT vertex semantic, which is not - supported on old non-SM2 cards. - */ - void tangent(const Vector3& tan) - { - OgreAssert(mCurrentSection, "You must call begin() before this method"); - if (mFirstVertex && !mCurrentUpdating) - { - declareElement(VET_FLOAT3, VES_TANGENT); - } - mTempVertex.tangent = Vector3f(tan); - } - - /// @overload - void tangent(float x, float y, float z) { tangent({x, y, z}); } - - /** Add a texture coordinate to the current vertex. - - You can call this method multiple times between position() calls - to add multiple texture coordinates to a vertex. Each one can have - between 1 and 3 dimensions, depending on your needs, although 2 is - most common. There are several versions of this method for the - variations in number of dimensions. - */ - void textureCoord(float u) - { - OgreAssert(mCurrentSection, "You must call begin() before this method"); - if (mFirstVertex && !mCurrentUpdating) - { - declareElement(VET_FLOAT1, VES_TEXTURE_COORDINATES); - } - mTempVertex.texCoord[mTexCoordIndex][0] = u; - - ++mTexCoordIndex; - } - /// @overload - void textureCoord(float u, float v) - { - OgreAssert(mCurrentSection, "You must call begin() before this method"); - if (mFirstVertex && !mCurrentUpdating) - { - declareElement(VET_FLOAT2, VES_TEXTURE_COORDINATES); - } - mTempVertex.texCoord[mTexCoordIndex][0] = u; - mTempVertex.texCoord[mTexCoordIndex][1] = v; - - ++mTexCoordIndex; - } - /// @overload - void textureCoord(float u, float v, float w) - { - OgreAssert(mCurrentSection, "You must call begin() before this method"); - if (mFirstVertex && !mCurrentUpdating) - { - declareElement(VET_FLOAT3, VES_TEXTURE_COORDINATES); - } - mTempVertex.texCoord[mTexCoordIndex][0] = u; - mTempVertex.texCoord[mTexCoordIndex][1] = v; - mTempVertex.texCoord[mTexCoordIndex][2] = w; - - ++mTexCoordIndex; - } - /// @overload - void textureCoord(float x, float y, float z, float w) { textureCoord(Vector4(x, y, z, w)); } - /// @overload - void textureCoord(const Vector2& uv) { textureCoord(uv.x, uv.y); } - /// @overload - void textureCoord(const Vector3& uvw) { textureCoord(uvw.x, uvw.y, uvw.z); } - /// @@overload - void textureCoord(const Vector4& xyzw) - { - OgreAssert(mCurrentSection, "You must call begin() before this method"); - if (mFirstVertex && !mCurrentUpdating) - { - declareElement(VET_FLOAT4, VES_TEXTURE_COORDINATES); - } - mTempVertex.texCoord[mTexCoordIndex] = Vector4f(xyzw); - - ++mTexCoordIndex; - } - - /** Add a vertex colour to a vertex. - */ - void colour(const ColourValue& col) - { - OgreAssert(mCurrentSection, "You must call begin() before this method"); - if (mFirstVertex && !mCurrentUpdating) - { - declareElement(VET_COLOUR, VES_DIFFUSE); - } - mTempVertex.colour = col; - } - /// @overload - void colour(float r, float g, float b, float a = 1.0f) { colour(ColourValue(r, g, b, a)); }; - - /** Add a vertex index to construct faces / lines / points via indexing - rather than just by a simple list of vertices. - - You will have to call this 3 times for each face for a triangle list, - or use the alternative 3-parameter version. Other operation types - require different numbers of indexes, @see RenderOperation::OperationType. - @note - 32-bit indexes are not supported on all cards and will only be used - when required, if an index is > 65535. - @param idx A vertex index from 0 to 4294967295. - */ - void index(uint32 idx) - { - OgreAssert(mCurrentSection, "You must call begin() before this method"); - mAnyIndexed = true; - if (idx >= 65536) - mCurrentSection->set32BitIndices(true); - - // make sure we have index data - RenderOperation* rop = mCurrentSection->getRenderOperation(); - if (!rop->indexData) - { - rop->indexData = OGRE_NEW IndexData(); - rop->indexData->indexCount = 0; - } - rop->useIndexes = true; - resizeTempIndexBufferIfNeeded(++rop->indexData->indexCount); - - mTempIndexBuffer[rop->indexData->indexCount - 1] = idx; - } - /** Add a set of 3 vertex indices to construct a triangle; this is a - shortcut to calling index() 3 times. It is only valid for triangle - lists. - @note - 32-bit indexes are not supported on all cards and will only be used - when required, if an index is > 65535. - @param i1, i2, i3 3 vertex indices from 0 to 4294967295 defining a face. - */ - void triangle(uint32 i1, uint32 i2, uint32 i3) - { - OgreAssert(mCurrentSection, "You must call begin() before this method"); - OgreAssert(mCurrentSection->getRenderOperation()->operationType == - RenderOperation::OT_TRIANGLE_LIST, - "This method is only valid on triangle lists"); - index(i1); - index(i2); - index(i3); - } - /** Add a set of 4 vertex indices to construct a quad (out of 2 - triangles); this is a shortcut to calling index() 6 times, - or triangle() twice. It's only valid for triangle list operations. - @note - 32-bit indexes are not supported on all cards and will only be used - when required, if an index is > 65535. - @param i1, i2, i3, i4 4 vertex indices from 0 to 4294967295 defining a quad. - */ - void quad(uint32 i1, uint32 i2, uint32 i3, uint32 i4) - { - // first tri - triangle(i1, i2, i3); - // second tri - triangle(i3, i4, i1); - } - - /// Get the number of vertices in the section currently being defined (returns 0 if no section is in progress). - virtual size_t getCurrentVertexCount() const; - - /// Get the number of indices in the section currently being defined (returns 0 if no section is in progress). - virtual size_t getCurrentIndexCount() const; - - /** Finish defining the object and compile the final renderable version. - @note - Will return a pointer to the finished section or NULL if the section was discarded (i.e. has zero vertices/indices). - */ - virtual ManualObjectSection* end(void); - - /** Alter the material for a subsection of this object after it has been - specified. - - You specify the material to use on a section of this object during the - call to begin(), however if you want to change the material afterwards - you can do so by calling this method. - @param subIndex The index of the subsection to alter - @param name The name of the new material to use - @param group The resource group of the new material to use - */ - void setMaterialName(size_t subIndex, const String& name, - const String & group = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME) - { - mSectionList.at(subIndex)->setMaterialName(name, group); - } - - /** @overload - @param subIndex The index of the subsection to alter - @param mat The new material to use - */ - void setMaterial(size_t subIndex, const MaterialPtr& mat) - { - mSectionList.at(subIndex)->setMaterial(mat); - } - - /** Convert this object to a Mesh. - - After you've finished building this object, you may convert it to - a Mesh if you want in order to be able to create many instances of - it in the world (via Entity). This is optional, since this instance - can be directly attached to a SceneNode itself, but of course only - one instance of it can exist that way. - @note Only objects which use indexed geometry may be converted to a mesh. - @param meshName The name to give the mesh - @param groupName The resource group to create the mesh in - */ - virtual MeshPtr convertToMesh(const String& meshName, - const String& groupName = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - /** Sets whether or not to use an 'identity' projection. - - Usually ManualObjects will use a projection matrix as determined - by the active camera. However, if they want they can cancel this out - and use an identity projection, which effectively projects in 2D using - a {-1, 1} view space. Useful for overlay rendering. Normally you don't - need to change this. The default is false. - @see ManualObject::getUseIdentityProjection - */ - void setUseIdentityProjection(bool useIdentityProjection); - - /** Returns whether or not to use an 'identity' projection. - - Usually ManualObjects will use a projection matrix as determined - by the active camera. However, if they want they can cancel this out - and use an identity projection, which effectively projects in 2D using - a {-1, 1} view space. Useful for overlay rendering. Normally you don't - need to change this. - @see ManualObject::setUseIdentityProjection - */ - bool getUseIdentityProjection(void) const { return mUseIdentityProjection; } - - /** Sets whether or not to use an 'identity' view. - - Usually ManualObjects will use a view matrix as determined - by the active camera. However, if they want they can cancel this out - and use an identity matrix, which means all geometry is assumed - to be relative to camera space already. Useful for overlay rendering. - Normally you don't need to change this. The default is false. - @see ManualObject::getUseIdentityView - */ - void setUseIdentityView(bool useIdentityView); - - /** Returns whether or not to use an 'identity' view. - - Usually ManualObjects will use a view matrix as determined - by the active camera. However, if they want they can cancel this out - and use an identity matrix, which means all geometry is assumed - to be relative to camera space already. Useful for overlay rendering. - Normally you don't need to change this. - @see ManualObject::setUseIdentityView - */ - bool getUseIdentityView(void) const { return mUseIdentityView; } - - /** Sets the bounding box. - @remarks Call this after having finished creating sections to modify the - bounding box. E.g. if you're using ManualObject to create 2D overlays - you can call things function to set an infinite bounding box so that - the object always stays visible when attached. - @see ManualObject::setUseIdentityProjection, ManualObject::setUseIdentityView, - AxisAlignedBox::setInfinite */ - void setBoundingBox(const AxisAlignedBox& box) { mAABB = box; } - - /** Gets the list of ManualObjectSection, i.e. a part of a ManualObject. - */ - const std::vector& getSections() const { return mSectionList; } - - ManualObjectSection* getSection(size_t index) const { return mSectionList.at(index); } - - size_t getNumSections(void) const { return mSectionList.size(); } - - - /** Sets whether or not to keep the original declaration order when - queuing the renderables. - - This overrides the default behavior of the rendering queue, - specifically stating the desired order of rendering. Might result in a - performance loss, but lets the user to have more direct control when - creating geometry through this class. - @param keepOrder Whether to keep the declaration order or not. - */ - void setKeepDeclarationOrder(bool keepOrder) { mKeepDeclarationOrder = keepOrder; } - - /** Gets whether or not the declaration order is to be kept or not. - @return A flag indication if the declaration order will be kept when - queuing the renderables. - */ - bool getKeepDeclarationOrder() const { return mKeepDeclarationOrder; } - // MovableObject overrides - - /** @copydoc MovableObject::getMovableType */ - const String& getMovableType(void) const override; - /** @copydoc MovableObject::getBoundingBox */ - const AxisAlignedBox& getBoundingBox(void) const override { return mAABB; } - /** @copydoc MovableObject::getBoundingRadius */ - Real getBoundingRadius(void) const override { return mRadius; } - /** @copydoc MovableObject::_updateRenderQueue */ - void _updateRenderQueue(RenderQueue* queue) override; - /** Implement this method to enable stencil shadows */ - EdgeData* getEdgeList(void) override; - /** Implement this method to enable stencil shadows. */ - const ShadowRenderableList& getShadowVolumeRenderableList( - const Light* light, const HardwareIndexBufferPtr& indexBuffer, - size_t& indexBufferUsedSize, float extrusionDist, int flags = 0) override; - - /// Built, renderable section of geometry - class _OgreExport ManualObjectSection : public Renderable, public MovableAlloc - { - protected: - ManualObject* mParent; - String mMaterialName; - String mGroupName; - mutable MaterialPtr mMaterial; - RenderOperation mRenderOperation; - bool m32BitIndices; - - - public: - ManualObjectSection(ManualObject* parent, const String& materialName, - RenderOperation::OperationType opType, - const String & groupName = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - /// @remark mat should not be null. - ManualObjectSection(ManualObject* parent, const MaterialPtr& mat, - RenderOperation::OperationType opType); - virtual ~ManualObjectSection(); - - /// Retrieve render operation for manipulation - RenderOperation* getRenderOperation(void); - /// Retrieve the material name in use - const String& getMaterialName(void) const { return mMaterialName; } - /// Retrieve the material group in use - const String& getMaterialGroup(void) const { return mGroupName; } - /// update the material name in use - void setMaterialName(const String& name, - const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME); - /// Update the material in use - /// @remark mat should not be null. - void setMaterial(const MaterialPtr& mat); - - /// Set whether we need 32-bit indices - void set32BitIndices(bool n32) { m32BitIndices = n32; } - /// Get whether we need 32-bit indices - bool get32BitIndices() const { return m32BitIndices; } - - // Renderable overrides - /** @copydoc Renderable::getMaterial */ - const MaterialPtr& getMaterial(void) const override; - /** @copydoc Renderable::getRenderOperation */ - void getRenderOperation(RenderOperation& op) override; - /** @copydoc Renderable::getWorldTransforms */ - void getWorldTransforms(Matrix4* xform) const override; - /** @copydoc Renderable::getSquaredViewDepth */ - Real getSquaredViewDepth(const Ogre::Camera *) const override; - /** @copydoc Renderable::getLights */ - const LightList &getLights(void) const override; - - /// convert this section to a SubMesh - void convertToSubMesh(SubMesh* sm) const; - - }; - - typedef std::vector SectionList; - - /// @copydoc MovableObject::visitRenderables - void visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables = false) override; - - - private: - /// Dynamic? - HardwareBufferUsage mBufferUsage; - /// List of subsections - SectionList mSectionList; - /// Current section - ManualObjectSection* mCurrentSection; - /// Are we updating? - bool mCurrentUpdating; - /// Temporary vertex structure - struct TempVertex - { - Vector3f position; - Vector3f normal; - Vector3f tangent; - Vector4f texCoord[OGRE_MAX_TEXTURE_COORD_SETS]; - ColourValue colour; - }; - /// Temp storage - TempVertex mTempVertex; - /// First vertex indicator - bool mFirstVertex; - /// Temp vertex data to copy? - bool mTempVertexPending; - /// System-memory buffer whilst we establish the size required - char* mTempVertexBuffer; - /// System memory allocation size, in bytes - size_t mTempVertexSize; - /// System-memory buffer whilst we establish the size required - uint32* mTempIndexBuffer; - /// System memory allocation size, in bytes - size_t mTempIndexSize; - /// Current declaration vertex size - size_t mDeclSize; - /// Estimated vertex count - uint32 mEstVertexCount; - /// Estimated index count - uint32 mEstIndexCount; - /// Current texture coordinate - ushort mTexCoordIndex; - /// Bounding box - AxisAlignedBox mAABB; - /// Bounding sphere - Real mRadius; - /// Any indexed geometry on any sections? - bool mAnyIndexed; - /// Edge list, used if stencil shadow casting is enabled - EdgeData* mEdgeList; - /// List of shadow renderables - ShadowRenderableList mShadowRenderables; - /// Whether to use identity projection for sections - bool mUseIdentityProjection; - /// Whether to use identity view for sections - bool mUseIdentityView; - /// Keep declaration order or let the queue optimize it - bool mKeepDeclarationOrder; - - - /// Delete temp buffers and reset init counts - void resetTempAreas(void); - /// Resize the temp vertex buffer? - void resizeTempVertexBufferIfNeeded(size_t numVerts); - /// Resize the temp index buffer? - void resizeTempIndexBufferIfNeeded(size_t numInds); - - /// Copy current temp vertex into buffer - void copyTempVertexToBuffer(void); - - private: - void declareElement(VertexElementType t, VertexElementSemantic s); - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif - - diff --git a/OgreMain/include/OgreMaterial.h b/OgreMain/include/OgreMaterial.h deleted file mode 100644 index ef234d94b0f..00000000000 --- a/OgreMain/include/OgreMaterial.h +++ /dev/null @@ -1,680 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _Material_H__ -#define _Material_H__ - -#include "OgrePrerequisites.h" - -#include "OgreResource.h" -#include "OgreCommon.h" -#include "OgreColourValue.h" -#include "OgreBlendMode.h" -#include "OgreHeaderPrefix.h" -#include "OgreSharedPtr.h" - -namespace Ogre { - - // Forward declaration - class LodStrategy; - template class ConstVectorIterator; - template class VectorIterator; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Materials - * @{ - */ - /** Class encapsulates rendering properties of an object. - - %Ogre's material class encapsulates *all* aspects of the visual appearance, - of an object. It also includes other flags which - might not be traditionally thought of as material properties such as - culling modes and depth buffer settings, but these affect the - appearance of the rendered object and are convenient to attach to the - material since it keeps all the settings in one place. This is - different to Direct3D which treats a material as just the colour - components (diffuse, specular) and not texture maps etc. An Ogre - Material can be thought of as equivalent to a 'Shader'. - - A Material can be rendered in multiple different ways depending on the - hardware available. You may configure a Material to use high-complexity - fragment shaders, but these won't work on every card; therefore a Technique - is an approach to creating the visual effect you are looking for. You are advised - to create fallback techniques with lower hardware requirements if you decide to - use advanced features. In addition, you also might want lower-detail techniques - for distant geometry. - - Each Technique can be made up of multiple passes. A fixed-function Pass - may combine multiple texture layers using multitexturing, but Ogre can - break that into multiple passes automatically if the active card cannot - handle that many simultaneous textures. Programmable passes, however, cannot - be split down automatically, so if the active graphics card cannot handle the - technique which contains these passes, OGRE will try to find another technique - which the card can do. If, at the end of the day, the card cannot handle any of the - techniques which are listed for the material, the engine will render the - geometry plain white, which should alert you to the problem. - - %Ogre comes configured with a number of default settings for a newly - created material. These can be changed if you wish by retrieving the - default material settings through - MaterialManager::getDefaultSettings. Any changes you make to the - Material returned from this method will apply to any materials created - from this point onward. - */ - class _OgreExport Material final : public Resource - { - friend class SceneManager; - friend class MaterialManager; - - public: - /// distance list used to specify LOD - typedef std::vector LodValueList; - typedef ConstVectorIterator LodValueIterator; - typedef std::vector Techniques; - private: - - - /** Internal method which sets the material up from the default settings. - */ - void applyDefaults(void); - - /// All techniques, supported and unsupported - Techniques mTechniques; - /// Supported techniques of any sort - Techniques mSupportedTechniques; - typedef std::map LodTechniques; - typedef std::map BestTechniquesBySchemeList; - /** Map of scheme -> list of LOD techniques. - Current scheme is set on MaterialManager, - and can be set per Viewport for auto activation. - */ - BestTechniquesBySchemeList mBestTechniquesBySchemeList; - - LodValueList mUserLodValues; - LodValueList mLodValues; - const LodStrategy *mLodStrategy; - /// Text description of why any techniques are not supported - String mUnsupportedReasons; - bool mReceiveShadows; - bool mTransparencyCastsShadows; - /// Does this material require compilation? - bool mCompilationRequired; - - /** Insert a supported technique into the local collections. */ - void insertSupportedTechnique(Technique* t); - - /** Clear the best technique list. - */ - void clearBestTechniqueList(void); - - void prepareImpl(void) override; - void unprepareImpl(void) override; - void loadImpl(void) override; - - /** Unloads the material, frees resources etc. - @see - Resource - */ - void unloadImpl(void) override; - /// @copydoc Resource::calculateSize - size_t calculateSize(void) const override; - public: - - /** Constructor - use resource manager's create method rather than this. - */ - Material(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual = false, ManualResourceLoader* loader = 0); - - ~Material(); - /** Assignment operator to allow easy copying between materials. - */ - Material& operator=( const Material& rhs ); - - /** Determines if the material has any transparency with the rest of the scene (derived from - whether any Techniques say they involve transparency). - */ - bool isTransparent(void) const; - - /** Sets whether objects using this material will receive shadows. - - This method allows a material to opt out of receiving shadows, if - it would otherwise do so. Shadows will not be cast on any objects - unless the scene is set up to support shadows - (@see SceneManager::setShadowTechnique), and not all techniques cast - shadows on all objects. In any case, if you have a need to prevent - shadows being received by material, this is the method you call to - do it. - @note - Transparent materials never receive shadows despite this setting. - The default is to receive shadows. - */ - void setReceiveShadows(bool enabled) { mReceiveShadows = enabled; } - /** Returns whether or not objects using this material will receive shadows. */ - bool getReceiveShadows(void) const { return mReceiveShadows; } - - /** Sets whether objects using this material be classified as opaque to the shadow caster system. - - This method allows a material to cast a shadow, even if it is transparent. - By default, transparent materials neither cast nor receive shadows. Shadows - will not be cast on any objects unless the scene is set up to support shadows - (@see SceneManager::setShadowTechnique), and not all techniques cast - shadows on all objects. - */ - void setTransparencyCastsShadows(bool enabled) { mTransparencyCastsShadows = enabled; } - /** Returns whether or not objects using this material be classified as opaque to the shadow caster system. */ - bool getTransparencyCastsShadows(void) const { return mTransparencyCastsShadows; } - - typedef VectorIterator TechniqueIterator; - /// @name Techniques - /// @{ - /** Creates a new Technique for this Material. - - A Technique is a single way of rendering geometry in order to achieve the effect - you are intending in a material. There are many reason why you would want more than - one - the main one being to handle variable graphics card abilities; you might have - one technique which is impressive but only runs on 4th-generation graphics cards, - for example. In this case you will want to create at least one fallback Technique. - OGRE will work out which Techniques a card can support and pick the best one. - @par - If multiple Techniques are available, the order in which they are created is - important - the engine will consider lower-indexed Techniques to be preferable - to higher-indexed Techniques, ie when asked for the 'best' technique it will - return the first one in the technique list which is supported by the hardware. - */ - Technique* createTechnique(void); - /** Gets the indexed technique. */ - Technique* getTechnique(size_t index) const { return mTechniques.at(index); } - /** searches for the named technique. - Return 0 if technique with name is not found - */ - Technique* getTechnique(const String& name) const; - /** Retrieves the number of techniques. */ - size_t getNumTechniques(void) const { return mTechniques.size(); } - /** Removes the technique at the given index. */ - void removeTechnique(unsigned short index); - /** Removes all the techniques in this Material. */ - void removeAllTechniques(void); - /** Get an iterator over the Techniques in this Material. - * @deprecated use getTechniques() */ - OGRE_DEPRECATED TechniqueIterator getTechniqueIterator(void); - - /** Get the Techniques in this Material. */ - const Techniques& getTechniques(void) const { - return mTechniques; - } - - /** Gets all the Techniques which are supported by the current card. - - The supported technique list is only available after this material has been compiled, - which typically happens on loading the material. Therefore, if this method returns - an empty list, try calling Material::load. - */ - const Techniques& getSupportedTechniques(void) const { - return mSupportedTechniques; - } - - /// @deprecated use getSupportedTechniques() - OGRE_DEPRECATED TechniqueIterator getSupportedTechniqueIterator(void); - - /** Gets the indexed supported technique. */ - Technique* getSupportedTechnique(size_t index) const { return mSupportedTechniques.at(index); } - /** Retrieves the number of supported techniques. */ - size_t getNumSupportedTechniques(void) const { return mSupportedTechniques.size(); } - /** Gets a string explaining why any techniques are not supported. */ - const String& getUnsupportedTechniquesExplanation() const { return mUnsupportedReasons; } - - /** Gets the best supported technique. - - This method returns the lowest-index supported Technique in this material - (since lower-indexed Techniques are considered to be better than higher-indexed - ones). - @par - The best supported technique is only available after this material has been compiled, - which typically happens on loading the material. Therefore, if this method returns - NULL, try calling Material::load. - @param lodIndex The material LOD index to use - @param rend Optional parameter specifying the Renderable that is requesting - this technique. Only used if no valid technique for the active material - scheme is found, at which point it is passed to - MaterialManager::Listener::handleSchemeNotFound as information. - */ - Technique* getBestTechnique(unsigned short lodIndex = 0, const Renderable* rend = 0); - /// @} - - /** Creates a new copy of this material with the same settings but a new name. - @param newName The name for the cloned material - @param newGroup - Optional name of the new group to assign the clone to; - if you leave this blank, the clone will be assigned to the same - group as this Material. - */ - MaterialPtr clone(const String& newName, const String& newGroup = BLANKSTRING) const; - - // needed because of deprecated variant below - MaterialPtr clone(const String& newName, const char* newGroup) const { return clone(newName, String(newGroup)); } - - /// @deprecated use clone(const String&, const String&) - OGRE_DEPRECATED MaterialPtr clone(const String& newName, bool changeGroup, - const String& newGroup = BLANKSTRING) const - { - return clone(newName, newGroup); - } - - /** Copies the details of this material into another, preserving the target's handle and name - (unlike operator=) but copying everything else. - @param mat Weak reference to material which will receive this material's settings. - */ - void copyDetailsTo(MaterialPtr& mat) const; - - /** 'Compiles' this Material. - - Compiling a material involves determining which Techniques are supported on the - card on which OGRE is currently running, and for fixed-function Passes within those - Techniques, splitting the passes down where they contain more TextureUnitState - instances than the current card has texture units. - @par - This process is automatically done when the Material is loaded, but may be - repeated if you make some procedural changes. - @param - autoManageTextureUnits If true, when a fixed function pass has too many TextureUnitState - entries than the card has texture units, the Pass in question will be split into - more than one Pass in order to emulate the Pass. If you set this to false and - this situation arises, an Exception will be thrown. - */ - void compile(bool autoManageTextureUnits = true); - - /** @name Forwarded Pass Properties - - The following methods are to make migration from previous versions simpler - and to make code easier to write when dealing with simple materials - They set the properties which have been moved to Pass for all Techniques and all Passes - */ - - /// @{ - /** Sets the point size properties for every Pass in every Technique. - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setPointSize - */ - void setPointSize(Real ps); - - /** Sets the ambient colour reflectance properties for every Pass in every Technique. - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setAmbient - */ - void setAmbient(float red, float green, float blue); - - /// @overload - void setAmbient(const ColourValue& ambient); - - /** Sets the diffuse colour reflectance properties of every Pass in every Technique. - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setDiffuse - */ - void setDiffuse(float red, float green, float blue, float alpha); - - /// @overload - void setDiffuse(const ColourValue& diffuse); - - /** Sets the specular colour reflectance properties of every Pass in every Technique. - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setSpecular - */ - void setSpecular(float red, float green, float blue, float alpha); - - /// @overload - void setSpecular(const ColourValue& specular); - - /** Sets the shininess properties of every Pass in every Technique. - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setShininess - */ - void setShininess(Real val); - - /** Sets the amount of self-illumination of every Pass in every Technique. - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setSelfIllumination - */ - void setSelfIllumination(float red, float green, float blue); - - /// @overload - void setSelfIllumination(const ColourValue& selfIllum); - - /** Sets whether or not each Pass renders with depth-buffer checking on or not. - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setDepthCheckEnabled - */ - void setDepthCheckEnabled(bool enabled); - - /** Sets whether or not each Pass renders with depth-buffer writing on or not. - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setDepthWriteEnabled - */ - void setDepthWriteEnabled(bool enabled); - - /** Sets the function used to compare depth values when depth checking is on. - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setDepthFunction - */ - void setDepthFunction( CompareFunction func ); - - /** Sets whether or not colour buffer writing is enabled for each Pass. - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setColourWriteEnabled - */ - void setColourWriteEnabled(bool enabled); - - /** Sets which colour buffer channels are enabled for writing for each Pass. - @see Pass::setColourWriteEnabled - */ - void setColourWriteEnabled(bool red, bool green, bool blue, bool alpha); - - /** Sets the culling mode for each pass based on the 'vertex winding'. - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setCullingMode - */ - void setCullingMode( CullingMode mode ); - - /** Sets the manual culling mode, performed by CPU rather than hardware. - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setManualCullingMode - */ - void setManualCullingMode( ManualCullingMode mode ); - - /** Sets whether or not dynamic lighting is enabled for every Pass. - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setLightingEnabled - */ - void setLightingEnabled(bool enabled); - - /** Sets the type of light shading required - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setShadingMode - */ - void setShadingMode( ShadeOptions mode ); - - /** Sets the fogging mode applied to each pass. - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setFog - */ - void setFog( - bool overrideScene, - FogMode mode = FOG_NONE, - const ColourValue& colour = ColourValue::White, - Real expDensity = 0.001f, Real linearStart = 0.0f, Real linearEnd = 1.0f ); - - /** Sets the depth bias to be used for each Pass. - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setDepthBias - */ - void setDepthBias(float constantBias, float slopeScaleBias); - - /** Set texture filtering for every texture unit in every Technique and Pass - @note - This property has been moved to the TextureUnitState class, which is accessible via the - Technique and Pass. For simplicity, this method allows you to set these properties for - every current TeextureUnitState, If you need more precision, retrieve the Technique, - Pass and TextureUnitState instances and set the property there. - @see TextureUnitState::setTextureFiltering - */ - void setTextureFiltering(TextureFilterOptions filterType); - /** Sets the anisotropy level to be used for all textures. - @note - This property has been moved to the TextureUnitState class, which is accessible via the - Technique and Pass. For simplicity, this method allows you to set these properties for - every current TeextureUnitState, If you need more precision, retrieve the Technique, - Pass and TextureUnitState instances and set the property there. - @see TextureUnitState::setTextureAnisotropy - */ - void setTextureAnisotropy(int maxAniso); - - /** Sets the kind of blending every pass has with the existing contents of the scene. - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setSceneBlending - */ - void setSceneBlending( const SceneBlendType sbt ); - - /** Sets the kind of blending every pass has with the existing contents of the scene, using individual factors for color and alpha channels - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setSeparateSceneBlending - */ - void setSeparateSceneBlending( const SceneBlendType sbt, const SceneBlendType sbta ); - - /** Allows very fine control of blending every Pass with the existing contents of the scene. - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setSceneBlending - */ - void setSceneBlending( const SceneBlendFactor sourceFactor, const SceneBlendFactor destFactor); - - /** Allows very fine control of blending every Pass with the existing contents of the scene, using individual factors for color and alpha channels - @note - This property has been moved to the Pass class, which is accessible via the - Technique. For simplicity, this method allows you to set these properties for - every current Technique, and for every current Pass within those Techniques. If - you need more precision, retrieve the Technique and Pass instances and set the - property there. - @see Pass::setSeparateSceneBlending - */ - void setSeparateSceneBlending( const SceneBlendFactor sourceFactor, const SceneBlendFactor destFactor, const SceneBlendFactor sourceFactorAlpha, const SceneBlendFactor destFactorAlpha); - /// @} - - /** Tells the material that it needs recompilation. */ - void _notifyNeedsRecompile(void); - - /// @name Level of Detail - /// @{ - /** Gets the number of levels-of-detail this material has in the - given scheme, based on Technique::setLodIndex. - - Note that this will not be up to date until the material has been compiled. - */ - unsigned short getNumLodLevels(unsigned short schemeIndex) const; - /** Gets the number of levels-of-detail this material has in the - given scheme, based on Technique::setLodIndex. - - Note that this will not be up to date until the material has been compiled. - */ - unsigned short getNumLodLevels(const String& schemeName) const; - /** Sets the distance at which level-of-detail (LOD) levels come into effect. - - You should only use this if you have assigned LOD indexes to the Technique - instances attached to this Material. If you have done so, you should call this - method to determine the distance at which the lowe levels of detail kick in. - The decision about what distance is actually used is a combination of this - and the LOD bias applied to both the current Camera and the current Entity. - @param lodValues A vector of Reals which indicate the LOD value at which to - switch to lower details. They are listed in LOD index order, starting at index - 1 (ie the first level down from the highest level 0, which automatically applies - from a value of 0). These are 'user values', before being potentially - transformed by the strategy, so for the distance strategy this is an - unsquared distance for example. - */ - void setLodLevels(const LodValueList& lodValues); - - /** Gets the list of values transformed by the LodStrategy at which each LOD comes into effect. - - Note that the iterator returned from this method is not totally analogous to - the one passed in by calling setLodLevels - the list includes a zero - entry at the start (since the highest LOD starts at value 0). Also, the - values returned are after being transformed by LodStrategy::transformUserValue. - */ - const LodValueList& getLodValues(void) const { - return mLodValues; - } - - /// @deprecated use getLodValues() - OGRE_DEPRECATED LodValueIterator getLodValueIterator(void) const; - - /** Gets the user-defined list of values which are internally transformed by the LodStrategy. - - Note that the iterator returned from this method is not totally analogous to - the one passed in by calling setLodLevels - the list includes a zero - entry at the start (since the highest LOD starts at value 0). Also, the - values returned are after being transformed by LodStrategy::transformUserValue. - */ - const LodValueList& getUserLodValues(void) const { - return mUserLodValues; - } - - /// @deprecated use getUserLodValues() - OGRE_DEPRECATED LodValueIterator getUserLodValueIterator(void) const; - - /** Gets the LOD index to use at the given value. - @note The value passed in is the 'transformed' value. If you are dealing with - an original source value (e.g. distance), use LodStrategy::transformUserValue - to turn this into a lookup value. - */ - ushort getLodIndex(Real value) const; - - /** Get LOD strategy used by this material. */ - const LodStrategy *getLodStrategy() const; - /** Set the LOD strategy used by this material. */ - void setLodStrategy(LodStrategy *lodStrategy); - /// @} - - void touch(void) override - { - if (mCompilationRequired) - compile(); - // call superclass - Resource::touch(); - } - - /** Gets the compilation status of the material. - @return True if the material needs recompilation. - */ - bool getCompilationRequired() const - { - return mCompilationRequired; - } - - - }; - /** @} */ - /** @} */ - -} //namespace - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreMaterialManager.h b/OgreMain/include/OgreMaterialManager.h deleted file mode 100644 index 452fa2019f6..00000000000 --- a/OgreMain/include/OgreMaterialManager.h +++ /dev/null @@ -1,299 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __MATERIALMANAGER_H__ -#define __MATERIALMANAGER_H__ - -#include "OgrePrerequisites.h" - -#include "OgreSingleton.h" -#include "OgreResourceManager.h" -#include "OgreHeaderPrefix.h" -#include "OgreTextureUnitState.h" - -namespace Ogre { - - class MaterialSerializer; - - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Materials - * @{ - */ - - /// Default material scheme name - _OgreExport extern const String MSN_DEFAULT; - /// Material scheme of the shader generator - _OgreExport extern const String MSN_SHADERGEN; - - /** Class for managing Material settings for %Ogre. - - Materials control the eventual surface rendering properties of geometry. This class - manages the library of materials, dealing with programmatic registrations and lookups, - as well as loading predefined Material settings from scripts. - - When loaded from a script, a Material is in an 'unloaded' state and only stores the settings - required. It does not at that stage load any textures. This is because the material settings may be - loaded 'en masse' from bulk material script files, but only a subset will actually be required. - - Because this is a subclass of ResourceManager, any files loaded will be searched for in any path or - archive added to the resource paths/archives. See ResourceManager for details. - - For a definition of the material script format, see @ref Material-Scripts. - - Ogre comes configured with a set of defaults for newly created - materials. If you wish to have a different set of defaults, - simply call getDefaultSettings() and change the returned Material's - settings. All materials created from then on will be configured - with the new defaults you have specified. - */ - class _OgreExport MaterialManager : public ResourceManager, public Singleton - { - public: - /** Listener on any general material events. - @see MaterialManager::addListener - */ - class Listener - { - public: - /** Virtual destructor needed as class has virtual methods. */ - virtual ~Listener() { } - /** Called if a technique for a given scheme is not found within a material, - allows the application to specify a Technique instance manually. - - Material schemes allow you to switch wholesale between families of - techniques on a material. However they require you to define those - schemes on the materials up-front, which might not be possible or - desirable for all materials, particular if, for example, you wanted - a simple way to replace all materials with another using a scheme. - @par - This callback allows you to handle the case where a scheme is requested - but the material doesn't have an entry for it. You can return a - Technique pointer from this method to specify the material technique - you'd like to be applied instead, which can be from another material - entirely (and probably will be). Note that it is critical that you - only return a Technique that is supported on this hardware; there are - utility methods like Material::getBestTechnique to help you with this. - @param schemeIndex The index of the scheme that was requested - all - schemes have a unique index when created that does not alter. - @param schemeName The friendly name of the scheme being requested - @param originalMaterial The material that is being processed, that - didn't have a specific technique for this scheme - @param lodIndex The material level-of-detail that was being asked for, - in case you need to use it to determine a technique. - @param rend Pointer to the Renderable that is requesting this technique - to be used, so this may influence your choice of Technique. May be - null if the technique isn't being requested in that context. - @return A pointer to the technique to be used, or NULL if you wish to - use the default technique for this material - */ - virtual Technique* handleSchemeNotFound(unsigned short schemeIndex, - const String& schemeName, Material* originalMaterial, unsigned short lodIndex, - const Renderable* rend) = 0; - - /** Called right after illuminated passes were created, - so that owner of runtime generated technique can handle this. - @return True if notification is handled and should not be propagated further. - */ - virtual bool afterIlluminationPassesCreated(Technique* technique) { return false; } - - /** Called right before illuminated passes would be removed, - so that owner of runtime generated technique can handle this. - @return True if notification is handled and should not be propagated further. - */ - virtual bool beforeIlluminationPassesCleared(Technique* technique) { return false; } - }; - - private: - /// Default settings - MaterialPtr mDefaultSettings; - - Resource* createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* params) override; - - /// Scheme name -> index. Never shrinks! Should be pretty static anyway - typedef std::map SchemeMap; - /// List of material schemes - SchemeMap mSchemes; - /// Current material scheme - String mActiveSchemeName; - /// Current material scheme - unsigned short mActiveSchemeIndex; - - /// The list of per-scheme (and general) material listeners - typedef std::list ListenerList; - typedef std::map ListenerMap; - ListenerMap mListenerMap; - - public: - /// same as @ref MSN_DEFAULT - static String DEFAULT_SCHEME_NAME; - - /// Create a new material - /// @see ResourceManager::createResource - MaterialPtr create (const String& name, const String& group, - bool isManual = false, ManualResourceLoader* loader = 0, - const NameValuePairList* createParams = 0); - - /// Get a material by name. For example, to get a MaterialPtr to a material defined in .material script. - /// @see ResourceManager::getResourceByName - MaterialPtr getByName(const String& name, const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME) const; - - /// Get a default material that is always available even when no resources were loaded - /// @param useLighting whether the material should be lit - MaterialPtr getDefaultMaterial(bool useLighting = true); - - /** Default constructor. - */ - MaterialManager(); - - /** Default destructor. - */ - virtual ~MaterialManager(); - - /** Initialises the material manager, which also triggers it to - * parse all available .program and .material scripts. */ - void initialise(void); - - /** Sets the default texture filtering to be used for loaded textures, for when textures are - loaded automatically (e.g. by Material class) or when 'load' is called with the default - parameters by the application. - @note - The default value is TFO_BILINEAR. - */ - virtual void setDefaultTextureFiltering(TextureFilterOptions fo); - /** Sets the default texture filtering to be used for loaded textures, for when textures are - loaded automatically (e.g. by Material class) or when 'load' is called with the default - parameters by the application. - */ - virtual void setDefaultTextureFiltering(FilterType ftype, FilterOptions opts); - /** Sets the default texture filtering to be used for loaded textures, for when textures are - loaded automatically (e.g. by Material class) or when 'load' is called with the default - parameters by the application. - */ - virtual void setDefaultTextureFiltering(FilterOptions minFilter, FilterOptions magFilter, FilterOptions mipFilter); - - /// Get the default texture filtering - virtual FilterOptions getDefaultTextureFiltering(FilterType ftype) const; - - /** Sets the default anisotropy level to be used for loaded textures, for when textures are - loaded automatically (e.g. by Material class) or when 'load' is called with the default - parameters by the application. - @note - The default value is 1 (no anisotropy). - */ - void setDefaultAnisotropy(unsigned int maxAniso); - /// Get the default maxAnisotropy - unsigned int getDefaultAnisotropy() const; - - /** Returns a pointer to the default Material settings. - - The default settings begin as a single Technique with a single, non-programmable Pass: - - - ambient = ColourValue::White - - diffuse = ColourValue::White - - specular = ColourValue::Black - - emissive = ColourValue::Black - - shininess = 0 (not shiny) - - No texture unit settings (& hence no textures) - - SourceBlendFactor = Ogre::SBF_ONE - - DestBlendFactor = Ogre::SBF_ZERO (no blend, replace with new colour) - - Depth buffer checking on - - Depth buffer writing on - - Depth buffer comparison function = Ogre::CMPF_LESS_EQUAL - - Colour buffer writing on for all channels - - Culling mode = Ogre::CULL_CLOCKWISE - - Ambient lighting = ColourValue(0.5, 0.5, 0.5) (mid-grey) - - Dynamic lighting enabled - - Gourad shading mode - - Bilinear texture filtering - */ - virtual MaterialPtr getDefaultSettings(void) const { return mDefaultSettings; } - - /** Internal method - returns index for a given material scheme name. - @see Technique::setSchemeName - */ - virtual unsigned short _getSchemeIndex(const String& name); - /** Internal method - returns name for a given material scheme index. - @see Technique::setSchemeName - */ - virtual const String& _getSchemeName(unsigned short index); - /** Internal method - returns the active scheme index. - @see Technique::setSchemeName - */ - unsigned short _getActiveSchemeIndex(void) const { return mActiveSchemeIndex; } - - /** Returns the name of the active material scheme. - @see Technique::setSchemeName - */ - const String& getActiveScheme(void) const { return mActiveSchemeName; } - - /** Sets the name of the active material scheme. - @see Technique::setSchemeName - */ - virtual void setActiveScheme(const String& schemeName); - - /** - Add a listener to handle material events. - If schemeName is supplied, the listener will only receive events for that certain scheme. - */ - virtual void addListener(Listener* l, const Ogre::String& schemeName = BLANKSTRING); - - /** - Remove a listener handling material events. - If the listener was added with a custom scheme name, it needs to be supplied here as well. - */ - virtual void removeListener(Listener* l, const Ogre::String& schemeName = BLANKSTRING); - - /// Internal method for sorting out missing technique for a scheme - virtual Technique* _arbitrateMissingTechniqueForActiveScheme( - Material* mat, unsigned short lodIndex, const Renderable* rend); - - /// Internal method for sorting out illumination passes for a scheme - virtual void _notifyAfterIlluminationPassesCreated(Technique* mat); - - /// Internal method for sorting out illumination passes for a scheme - virtual void _notifyBeforeIlluminationPassesCleared(Technique* mat); - - - /// @copydoc Singleton::getSingleton() - static MaterialManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static MaterialManager* getSingletonPtr(void); - - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreMaterialSerializer.h b/OgreMain/include/OgreMaterialSerializer.h deleted file mode 100644 index 45f9b783ccd..00000000000 --- a/OgreMain/include/OgreMaterialSerializer.h +++ /dev/null @@ -1,362 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __MaterialSerializer_H__ -#define __MaterialSerializer_H__ - -#include "OgrePrerequisites.h" -#include "OgreTextureUnitState.h" -#include "OgreGpuProgram.h" -#include "OgreStringVector.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Materials - * @{ - */ - /** Class for serializing Materials to a .material script.*/ - class _OgreExport MaterialSerializer : public SerializerAlloc - { - public: - - // Material serialize event. - enum SerializeEvent - { - MSE_PRE_WRITE, - MSE_WRITE_BEGIN, - MSE_WRITE_END, - MSE_POST_WRITE - }; - - /** Class that allows listening in on the various stages of material serialization process. - Sub-classing it enable extending the attribute set of any part in the material. - */ - class Listener - { - public: - virtual ~Listener() {} - - /** Called when material section event raised. - @param ser The MaterialSerializer instance that writes the given material. - @param event The current section writing stage. - @param skip May set to true by sub-class instances in order to skip the following section write. - This parameter relevant only when stage equals MSE_PRE_WRITE. - @param mat The material that is being written. - */ - virtual void materialEventRaised(MaterialSerializer* ser, - SerializeEvent event, bool& skip, const Material* mat) - { (void)ser; (void)event; (void)skip; (void)mat; } - - /** Called when technique section event raised. - @param ser The MaterialSerializer instance that writes the given material. - @param event The current section writing stage. - @param skip May set to true by sub-class instances in order to skip the following section write. - This parameter relevant only when stage equals MSE_PRE_WRITE. - @param tech The technique that is being written. - */ - virtual void techniqueEventRaised(MaterialSerializer* ser, - SerializeEvent event, bool& skip, const Technique* tech) - { (void)ser; (void)event; (void)skip; (void)tech; } - - /** Called when pass section event raised. - @param ser The MaterialSerializer instance that writes the given material. - @param event The current section writing stage. - @param skip May set to true by sub-class instances in order to skip the following section write. - This parameter relevant only when stage equals MSE_PRE_WRITE. - @param pass The pass that is being written. - */ - virtual void passEventRaised(MaterialSerializer* ser, - SerializeEvent event, bool& skip, const Pass* pass) - { (void)ser; (void)event; (void)skip; (void)pass; } - - /** Called when GPU program reference section event raised. - @param ser The MaterialSerializer instance that writes the given material. - @param event The current section writing stage. - @param skip May set to true by sub-class instances in order to skip the following section write. - This parameter relevant only when stage equals MSE_PRE_WRITE. - @param attrib The GPU program reference description (vertex_program_ref, fragment_program_ref, etc). - @param program The program being written. - @param params The program parameters. - @param defaultParams The default program parameters. - */ - void gpuProgramRefEventRaised(MaterialSerializer* ser, - SerializeEvent event, bool& skip, - const String& attrib, - const GpuProgramPtr& program, - const GpuProgramParametersSharedPtr& params, - GpuProgramParameters* defaultParams) - { - (void)ser; - (void)event; - (void)skip; - (void)attrib; - (void)program; - (void)params; - (void)defaultParams; - } - - /** Called when texture unit state section event raised. - @param ser The MaterialSerializer instance that writes the given material. - @param event The current section writing stage. - @param skip May set to true by sub-class instances in order to skip the following section write. - This parameter relevant only when stage equals MSE_PRE_WRITE. - @param textureUnit The texture unit state that is being written. - */ - virtual void textureUnitStateEventRaised(MaterialSerializer* ser, - SerializeEvent event, bool& skip, const TextureUnitState* textureUnit) - { - (void)ser; - (void)event; - (void)skip; - (void)textureUnit; - } - }; - - private: - /** Internal method for saving a program definition which has been - built up. - */ - void finishProgramDefinition(void); - - /// Listeners list of this Serializer. - typedef std::vector ListenerList; - typedef ListenerList::iterator ListenerListIterator; - typedef ListenerList::const_iterator ListenerListConstIterator; - ListenerList mListeners; - - - void writeMaterial(const MaterialPtr& pMat, const String& materialName = ""); - void writeTechnique(const Technique* pTech); - void writePass(const Pass* pPass); - void writeVertexProgramRef(const Pass* pPass); - void writeTesselationHullProgramRef(const Pass* pPass); - void writeTesselationDomainProgramRef(const Pass* pPass); - void writeGeometryProgramRef(const Pass* pPass); - void writeFragmentProgramRef(const Pass* pPass); - void writeGpuProgramRef(const String& attrib, const GpuProgramPtr& program, const GpuProgramParametersSharedPtr& params); - void writeGpuPrograms(void); - void writeGPUProgramParameters(const GpuProgramParametersSharedPtr& params, GpuProgramParameters* defaultParams, - const unsigned short level = 4, const bool useMainBuffer = true); - void writeNamedGpuProgramParameters(const GpuProgramParametersSharedPtr& params, GpuProgramParameters* defaultParams, - const unsigned short level = 4, const bool useMainBuffer = true); - void writeLowLevelGpuProgramParameters(const GpuProgramParametersSharedPtr& params, GpuProgramParameters* defaultParams, - const unsigned short level = 4, const bool useMainBuffer = true); - void writeGpuProgramParameter( - const String& commandName, const String& identifier, - const GpuProgramParameters::AutoConstantEntry* autoEntry, - const GpuProgramParameters::AutoConstantEntry* defaultAutoEntry, - bool isFloat, bool isDouble, bool isInt, bool isUnsignedInt, bool isRegister, - size_t physicalIndex, size_t physicalSize, - const GpuProgramParametersSharedPtr& params, GpuProgramParameters* defaultParams, - const unsigned short level, const bool useMainBuffer); - void writeTextureUnit(const TextureUnitState *pTex); - void writeSceneBlendFactor(const SceneBlendFactor c_src, const SceneBlendFactor c_dest, - const SceneBlendFactor a_src, const SceneBlendFactor a_dest); - void writeSceneBlendFactor(const SceneBlendFactor sbf_src, const SceneBlendFactor sbf_dest); - void writeSceneBlendFactor(const SceneBlendFactor sbf); - void writeCompareFunction(const CompareFunction cf); - void writeColourValue(const ColourValue &colour, bool writeAlpha = false); - void writeLayerBlendOperationEx(const LayerBlendOperationEx op); - void writeLayerBlendSource(const LayerBlendSource lbs); - - typedef std::multimap EffectMap; - - void writeRotationEffect(const TextureUnitState::TextureEffect& effect, const TextureUnitState *pTex); - void writeTransformEffect(const TextureUnitState::TextureEffect& effect, const TextureUnitState *pTex); - void writeScrollEffect(const TextureUnitState::TextureEffect& effect, const TextureUnitState *pTex); - void writeEnvironmentMapEffect(const TextureUnitState::TextureEffect& effect, const TextureUnitState *pTex); - - String convertFiltering(FilterOptions fo); - - - /** Internal methods that invokes registered listeners callback. - @see Listener::materialEventRaised. - */ - void fireMaterialEvent(SerializeEvent event, bool& skip, const Material* mat); - - /** Internal methods that invokes registered listeners callback. - @see Listener::techniqueEventRaised. - */ - void fireTechniqueEvent(SerializeEvent event, bool& skip, const Technique* tech); - - /** Internal methods that invokes registered listeners callback. - @see Listener::passEventRaised. - */ - void firePassEvent(SerializeEvent event, bool& skip, const Pass* pass); - - /** Internal methods that invokes registered listeners callback. - @see Listener::gpuProgramRefEventRaised. - */ - void fireGpuProgramRefEvent(SerializeEvent event, bool& skip, - const String& attrib, - const GpuProgramPtr& program, - const GpuProgramParametersSharedPtr& params, - GpuProgramParameters* defaultParams); - - - /** Internal methods that invokes registered listeners callback. - @see Listener::textureUnitStateEventRaised. - */ - void fireTextureUnitStateEvent(SerializeEvent event, bool& skip, const TextureUnitState* textureUnit); - - public: - /** default constructor*/ - MaterialSerializer(); - /** default destructor*/ - virtual ~MaterialSerializer() {} - - /** Queue an in-memory Material to the internal buffer for export. - @param pMat Material pointer - @param clearQueued If true, any materials already queued will be removed - @param exportDefaults If true, attributes which are defaulted will be - included in the script exported, otherwise they will be omitted - @param materialName Allow exporting the given material under a different name. - In case of empty string the original material name will be used. - */ - void queueForExport(const MaterialPtr& pMat, bool clearQueued = false, - bool exportDefaults = false, const String& materialName = ""); - /** Exports queued material(s) to a named material script file. - @param filename the file name of the material script to be exported - @param includeProgDef If true, vertex program and fragment program - definitions will be written at the top of the material script - @param programFilename the file name of the vertex / fragment program - script to be exported. This is only used if there are program definitions - to be exported and includeProgDef is false - when calling queueForExport. - */ - void exportQueued(const String& filename, const bool includeProgDef = false, const String& programFilename = ""); - /** Exports a single in-memory Material to the named material script file. - @param pMat Material pointer - @param filename the file name of the material script to be exported - @param exportDefaults if true then exports all values including defaults - @param includeProgDef if true includes Gpu shader program definitions in the - export material script otherwise if false then program definitions will - be exported to a separate file with name programFilename if - programFilename is not empty - @param programFilename the file name of the vertex / fragment program - script to be exported. This is only used if includeProgDef is false. - @param materialName Allow exporting the given material under a different name. - In case of empty string the original material name will be used. - */ - void exportMaterial(const MaterialPtr& pMat, const String& filename, bool exportDefaults = false, - const bool includeProgDef = false, const String& programFilename = "", - const String& materialName = ""); - /** Returns a string representing the parsed material(s) */ - const String &getQueuedAsString() const; - /** Clears the internal buffer */ - void clearQueue(); - - /** Register a listener to this Serializer. - @see MaterialSerializer::Listener - */ - void addListener(Listener* listener); - - /** Remove a listener from this Serializer. - @see MaterialSerializer::Listener - */ - void removeListener(Listener* listener); - - private: - String mBuffer; - String mGpuProgramBuffer; - typedef std::set GpuProgramDefinitionContainer; - typedef GpuProgramDefinitionContainer::iterator GpuProgramDefIterator; - GpuProgramDefinitionContainer mGpuProgramDefinitionContainer; - bool mDefaults; - - public: - void beginSection(unsigned short level, const bool useMainBuffer = true) - { - String& buffer = (useMainBuffer ? mBuffer : mGpuProgramBuffer); - buffer += "\n"; - for (unsigned short i = 0; i < level; ++i) - { - buffer += "\t"; - } - buffer += "{"; - } - void endSection(unsigned short level, const bool useMainBuffer = true) - { - String& buffer = (useMainBuffer ? mBuffer : mGpuProgramBuffer); - buffer += "\n"; - for (unsigned short i = 0; i < level; ++i) - { - buffer += "\t"; - } - buffer += "}"; - } - - void writeAttribute(unsigned short level, const String& att, const bool useMainBuffer = true) - { - String& buffer = (useMainBuffer ? mBuffer : mGpuProgramBuffer); - buffer += "\n"; - for (unsigned short i = 0; i < level; ++i) - { - buffer += "\t"; - } - buffer += att; - } - - void writeValue(const String& val, const bool useMainBuffer = true) - { - String& buffer = (useMainBuffer ? mBuffer : mGpuProgramBuffer); - buffer += (" " + val); - } - - String quoteWord(const String& val) - { - if (val.find_first_of("{}$: \t") != String::npos) - return ("\"" + val + "\""); - else return val; - } - - - void writeComment(unsigned short level, const String& comment, const bool useMainBuffer = true) - { - String& buffer = (useMainBuffer ? mBuffer : mGpuProgramBuffer); - buffer += "\n"; - for (unsigned short i = 0; i < level; ++i) - { - buffer += "\t"; - } - buffer += "// " + comment; - } - - - - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreMath.h b/OgreMain/include/OgreMath.h deleted file mode 100644 index 36c7347f0b1..00000000000 --- a/OgreMain/include/OgreMath.h +++ /dev/null @@ -1,810 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Math_H__ -#define __Math_H__ - -#include -#include "OgrePrerequisites.h" -#include "OgreHeaderPrefix.h" - -#if defined(__FAST_MATH__) || defined(_M_FP_FAST) -#define OGRE_FAST_MATH -#endif - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - - /** A pair structure where the first element indicates whether - an intersection occurs - - if true, the second element will - indicate the distance along the ray at which it intersects. - This can be converted to a point in space by calling Ray::getPoint(). - */ - typedef std::pair RayTestResult; - - /** Wrapper class which indicates a given angle value is in Radians. - - Radian values are interchangeable with Degree values, and conversions - will be done automatically between them. - */ - class Radian - { - float mRad; - - public: - explicit Radian ( float r=0 ) : mRad(r) {} - Radian ( const Degree& d ); - Radian (const Ogre::Radian& rhs) : mRad(rhs.mRad) {} - Radian& operator = ( const float& f ) { mRad = f; return *this; } - Radian& operator = ( const Radian& r ) { mRad = r.mRad; return *this; } - Radian& operator = ( const Degree& d ); - - float valueDegrees() const; // see bottom of this file - float valueRadians() const { return mRad; } - float valueAngleUnits() const; - - const Radian& operator + () const { return *this; } - Radian operator + ( const Radian& r ) const { return Radian ( mRad + r.mRad ); } - Radian operator + ( const Degree& d ) const; - Radian& operator += ( const Radian& r ) { mRad += r.mRad; return *this; } - Radian& operator += ( const Degree& d ); - Radian operator - () const { return Radian(-mRad); } - Radian operator - ( const Radian& r ) const { return Radian ( mRad - r.mRad ); } - Radian operator - ( const Degree& d ) const; - Radian& operator -= ( const Radian& r ) { mRad -= r.mRad; return *this; } - Radian& operator -= ( const Degree& d ); - Radian operator * ( float f ) const { return Radian ( mRad * f ); } - Radian operator * ( const Radian& f ) const { return Radian ( mRad * f.mRad ); } - Radian& operator *= ( float f ) { mRad *= f; return *this; } - Radian operator / ( float f ) const { return Radian ( mRad / f ); } - Radian& operator /= ( float f ) { mRad /= f; return *this; } - - bool operator < ( const Radian& r ) const { return mRad < r.mRad; } - bool operator <= ( const Radian& r ) const { return mRad <= r.mRad; } - bool operator == ( const Radian& r ) const { return mRad == r.mRad; } - bool operator != ( const Radian& r ) const { return mRad != r.mRad; } - bool operator >= ( const Radian& r ) const { return mRad >= r.mRad; } - bool operator > ( const Radian& r ) const { return mRad > r.mRad; } - - inline friend std::ostream& operator << - ( std::ostream& o, const Radian& v ) - { - o << "Radian(" << v.valueRadians() << ")"; - return o; - } - }; - - /** Wrapper class which indicates a given angle value is in Degrees. - - Degree values are interchangeable with Radian values, and conversions - will be done automatically between them. - */ - class Degree - { - float mDeg; // if you get an error here - make sure to define/typedef 'Real' first - - public: - explicit Degree ( float d=0 ) : mDeg(d) {} - Degree ( const Radian& r ) : mDeg(r.valueDegrees()) {} - Degree (const Ogre::Degree& rhs) : mDeg(rhs.mDeg) {} - Degree& operator = ( const float& f ) { mDeg = f; return *this; } - Degree& operator = ( const Degree& d ) { mDeg = d.mDeg; return *this; } - Degree& operator = ( const Radian& r ) { mDeg = r.valueDegrees(); return *this; } - - float valueDegrees() const { return mDeg; } - float valueRadians() const; // see bottom of this file - float valueAngleUnits() const; - - const Degree& operator + () const { return *this; } - Degree operator + ( const Degree& d ) const { return Degree ( mDeg + d.mDeg ); } - Degree operator + ( const Radian& r ) const { return Degree ( mDeg + r.valueDegrees() ); } - Degree& operator += ( const Degree& d ) { mDeg += d.mDeg; return *this; } - Degree& operator += ( const Radian& r ) { mDeg += r.valueDegrees(); return *this; } - Degree operator - () const { return Degree(-mDeg); } - Degree operator - ( const Degree& d ) const { return Degree ( mDeg - d.mDeg ); } - Degree operator - ( const Radian& r ) const { return Degree ( mDeg - r.valueDegrees() ); } - Degree& operator -= ( const Degree& d ) { mDeg -= d.mDeg; return *this; } - Degree& operator -= ( const Radian& r ) { mDeg -= r.valueDegrees(); return *this; } - Degree operator * ( float f ) const { return Degree ( mDeg * f ); } - Degree operator * ( const Degree& f ) const { return Degree ( mDeg * f.mDeg ); } - Degree& operator *= ( float f ) { mDeg *= f; return *this; } - Degree operator / ( float f ) const { return Degree ( mDeg / f ); } - Degree& operator /= ( float f ) { mDeg /= f; return *this; } - - bool operator < ( const Degree& d ) const { return mDeg < d.mDeg; } - bool operator <= ( const Degree& d ) const { return mDeg <= d.mDeg; } - bool operator == ( const Degree& d ) const { return mDeg == d.mDeg; } - bool operator != ( const Degree& d ) const { return mDeg != d.mDeg; } - bool operator >= ( const Degree& d ) const { return mDeg >= d.mDeg; } - bool operator > ( const Degree& d ) const { return mDeg > d.mDeg; } - - inline friend std::ostream& operator << - ( std::ostream& o, const Degree& v ) - { - o << "Degree(" << v.valueDegrees() << ")"; - return o; - } - }; - - /** Wrapper class which identifies a value as the currently default angle - type, as defined by Math::setAngleUnit. - - Angle values will be automatically converted between radians and degrees, - as appropriate. - */ - class Angle - { - float mAngle; - public: - explicit Angle ( float angle ) : mAngle(angle) {} - operator Radian() const; - operator Degree() const; - }; - - // these functions could not be defined within the class definition of class - // Radian because they required class Degree to be defined - inline Radian::Radian ( const Degree& d ) : mRad(d.valueRadians()) { - } - inline Radian& Radian::operator = ( const Degree& d ) { - mRad = d.valueRadians(); return *this; - } - inline Radian Radian::operator + ( const Degree& d ) const { - return Radian ( mRad + d.valueRadians() ); - } - inline Radian& Radian::operator += ( const Degree& d ) { - mRad += d.valueRadians(); - return *this; - } - inline Radian Radian::operator - ( const Degree& d ) const { - return Radian ( mRad - d.valueRadians() ); - } - inline Radian& Radian::operator -= ( const Degree& d ) { - mRad -= d.valueRadians(); - return *this; - } - - /** Class to provide access to common mathematical functions. - - Most of the maths functions are aliased versions of the C runtime - library functions. They are aliased here to provide future - optimisation opportunities, either from faster RTLs or custom - math approximations. - @note -
This is based on MgcMath.h from - Wild Magic. - */ - class _OgreExport Math - { - public: - /** The angular units used by the API. This functionality is now deprecated in favor - of discreet angular unit types ( see Degree and Radian above ). The only place - this functionality is actually still used is when parsing files. Search for - usage of the Angle class for those instances - */ - enum AngleUnit - { - AU_DEGREE, - AU_RADIAN - }; - - - /** This class is used to provide an external random value provider. - */ - class RandomValueProvider - { - public: - virtual ~RandomValueProvider() {} - /** When called should return a random values in the range of [0,1] */ - virtual Real getRandomUnit() = 0; - }; - - private: - /// Angle units used by the api - static AngleUnit msAngleUnit; - - /// Size of the trig tables as determined by constructor. - static int mTrigTableSize; - - /// Radian -> index factor value ( mTrigTableSize / 2 * PI ) - static float mTrigTableFactor; - static float* mSinTable; - static float* mTanTable; - - /// A random value provider. overriding the default random number generator. - static RandomValueProvider* mRandProvider; - - /** Private function to build trig tables. - */ - void buildTrigTables(); - - static float SinTable (float fValue); - static float TanTable (float fValue); - public: - /** Default constructor. - @param - trigTableSize Optional parameter to set the size of the - tables used to implement Sin, Cos, Tan - */ - Math(unsigned int trigTableSize = 4096); - - /** Default destructor. - */ - ~Math(); - - static inline int IAbs (int iValue) { return ( iValue >= 0 ? iValue : -iValue ); } - static inline int ICeil (float fValue) { return int(std::ceil(fValue)); } - static inline int IFloor (float fValue) { return int(std::floor(fValue)); } - static int ISign (int iValue) { - return ( iValue > 0 ? +1 : ( iValue < 0 ? -1 : 0 ) ); - } - - /** Absolute value function - @param - fValue The value whose absolute value will be returned. - */ - static inline Real Abs (Real fValue) { return std::abs(fValue); } - - /** Absolute value function - @param dValue - The value, in degrees, whose absolute value will be returned. - */ - static inline Degree Abs (const Degree& dValue) { return Degree(std::abs(dValue.valueDegrees())); } - - /** Absolute value function - @param rValue - The value, in radians, whose absolute value will be returned. - */ - static inline Radian Abs (const Radian& rValue) { return Radian(std::abs(rValue.valueRadians())); } - - /** Arc cosine function - @param fValue - The value whose arc cosine will be returned. - */ - static Radian ACos (Real fValue); - - /** Arc sine function - @param fValue - The value whose arc sine will be returned. - */ - static Radian ASin (Real fValue); - - /** Arc tangent function - @param fValue - The value whose arc tangent will be returned. - */ - static inline Radian ATan (float fValue) { return Radian(std::atan(fValue)); } - - /** Arc tangent between two values function - @param fY - The first value to calculate the arc tangent with. - @param fX - The second value to calculate the arc tangent with. - */ - static inline Radian ATan2 (float fY, float fX) { return Radian(std::atan2(fY,fX)); } - - /** Ceiling function - Returns the smallest following integer. (example: Ceil(1.1) = 2) - - @param fValue - The value to round up to the nearest integer. - */ - static inline Real Ceil (Real fValue) { return std::ceil(fValue); } - -#ifndef OGRE_FAST_MATH - static inline bool isNaN(Real f) - { - // std::isnan() has non-portable behaviour on MSVC - // However NaN always fails this next test, no other number does. - return f != f; - } -#endif - - /** Cosine function. - @param fValue - Angle in radians - @param useTables - If true, uses lookup tables rather than - calculation - faster but less accurate. - */ - static inline float Cos (const Radian& fValue, bool useTables = false) { - return (!useTables) ? std::cos(fValue.valueRadians()) : SinTable(fValue.valueRadians() + HALF_PI); - } - /** Cosine function. - @param fValue - Angle in radians - @param useTables - If true, uses lookup tables rather than - calculation - faster but less accurate. - */ - static inline float Cos (float fValue, bool useTables = false) { - return (!useTables) ? std::cos(fValue) : SinTable(fValue + HALF_PI); - } - - static inline Real Exp (Real fValue) { return std::exp(fValue); } - - /** Floor function - Returns the largest previous integer. (example: Floor(1.9) = 1) - - @param fValue - The value to round down to the nearest integer. - */ - static inline Real Floor (Real fValue) { return std::floor(fValue); } - - static inline Real Log (Real fValue) { return std::log(fValue); } - - /// Stored value of log(2) for frequent use - static constexpr Real LOG2 = static_cast (0.69314718055994530942); - - static inline Real Log2 (Real fValue) { return std::log2(fValue); } - - static inline Real LogN (Real base, Real fValue) { return std::log(fValue)/std::log(base); } - - static inline Real Pow (Real fBase, Real fExponent) { return std::pow(fBase,fExponent); } - - static Real Sign(Real fValue) - { - if (fValue > 0.0) - return 1.0; - if (fValue < 0.0) - return -1.0; - return 0.0; - } - - static inline Radian Sign ( const Radian& rValue ) - { - return Radian(Sign(rValue.valueRadians())); - } - static inline Degree Sign ( const Degree& dValue ) - { - return Degree(Sign(dValue.valueDegrees())); - } - - /// Simulate the shader function saturate that clamps a parameter value between 0 and 1 - static inline float saturate(float t) { return (t < 0) ? 0 : ((t > 1) ? 1 : t); } - static inline double saturate(double t) { return (t < 0) ? 0 : ((t > 1) ? 1 : t); } - - /// saturated cast of size_t to uint16 - static inline uint16 uint16Cast(size_t t) { return t < UINT16_MAX ? uint16(t) : UINT16_MAX; } - - /** Simulate the shader function lerp which performers linear interpolation - - given 3 parameters v0, v1 and t the function returns the value of (1 - t)* v0 + t * v1. - where v0 and v1 are matching vector or scalar types and t can be either a scalar or a - vector of the same type as a and b. - */ - template static V lerp(const V& v0, const V& v1, const T& t) - { - return v0 * (1 - t) + v1 * t; - } - - /** Sine function. - @param fValue - Angle in radians - @param useTables - If true, uses lookup tables rather than - calculation - faster but less accurate. - */ - static inline float Sin (const Radian& fValue, bool useTables = false) { - return (!useTables) ? std::sin(fValue.valueRadians()) : SinTable(fValue.valueRadians()); - } - /** Sine function. - @param fValue - Angle in radians - @param useTables - If true, uses lookup tables rather than - calculation - faster but less accurate. - */ - static inline float Sin (Real fValue, bool useTables = false) { - return (!useTables) ? std::sin(fValue) : SinTable(fValue); - } - - /** Squared function. - @param fValue - The value to be squared (fValue^2) - */ - static inline Real Sqr (Real fValue) { return fValue*fValue; } - - /** Square root function. - @param fValue - The value whose square root will be calculated. - */ - static inline Real Sqrt (Real fValue) { return std::sqrt(fValue); } - - /** Square root function. - @param fValue - The value, in radians, whose square root will be calculated. - @return - The square root of the angle in radians. - */ - static inline Radian Sqrt (const Radian& fValue) { return Radian(std::sqrt(fValue.valueRadians())); } - - /** Square root function. - @param fValue - The value, in degrees, whose square root will be calculated. - @return - The square root of the angle in degrees. - */ - static inline Degree Sqrt (const Degree& fValue) { return Degree(std::sqrt(fValue.valueDegrees())); } - - /** Inverse square root i.e. 1 / Sqrt(x), good for vector - normalisation. - @param fValue - The value whose inverse square root will be calculated. - */ - static Real InvSqrt (Real fValue) { - return Real(1.) / std::sqrt(fValue); - } - - /** Generate a random number of unit length. - @return - A random number in the range from [0,1]. - */ - static float UnitRandom(); - - /** Generate a random number within the range provided. - @param fLow - The lower bound of the range. - @param fHigh - The upper bound of the range. - @return - A random number in the range from [fLow,fHigh]. - */ - static float RangeRandom(float fLow, float fHigh) { return (fHigh - fLow) * UnitRandom() + fLow; } - - /** Generate a random number in the range [-1,1]. - @return - A random number in the range from [-1,1]. - */ - static float SymmetricRandom() { return 2.0f * UnitRandom() - 1.0f; } - - static void SetRandomValueProvider(RandomValueProvider* provider); - - /** Tangent function. - @param fValue - Angle in radians - @param useTables - If true, uses lookup tables rather than - calculation - faster but less accurate. - */ - static inline float Tan (const Radian& fValue, bool useTables = false) { - return (!useTables) ? std::tan(fValue.valueRadians()) : TanTable(fValue.valueRadians()); - } - /** Tangent function. - @param fValue - Angle in radians - @param useTables - If true, uses lookup tables rather than - calculation - faster but less accurate. - */ - static inline float Tan (Real fValue, bool useTables = false) { - return (!useTables) ? std::tan(fValue) : TanTable(fValue); - } - - static inline float DegreesToRadians(float degrees) { return degrees * fDeg2Rad; } - static inline float RadiansToDegrees(float radians) { return radians * fRad2Deg; } - - /** These functions used to set the assumed angle units (radians or degrees) - expected when using the Angle type. - @par - You can set this directly after creating a new Root, and also before/after resource creation, - depending on whether you want the change to affect resource files. - */ - static void setAngleUnit(AngleUnit unit); - /** Get the unit being used for angles. */ - static AngleUnit getAngleUnit(void); - - /** Convert from the current AngleUnit to radians. */ - static float AngleUnitsToRadians(float units); - /** Convert from radians to the current AngleUnit . */ - static float RadiansToAngleUnits(float radians); - /** Convert from the current AngleUnit to degrees. */ - static float AngleUnitsToDegrees(float units); - /** Convert from degrees to the current AngleUnit. */ - static float DegreesToAngleUnits(float degrees); - - /** Checks whether a given point is inside a triangle, in a - 2-dimensional (Cartesian) space. - - The vertices of the triangle must be given in either - trigonometrical (anticlockwise) or inverse trigonometrical - (clockwise) order. - @param p - The point. - @param a - The triangle's first vertex. - @param b - The triangle's second vertex. - @param c - The triangle's third vertex. - @return - If the point resides in the triangle, true is - returned. - @par - If the point is outside the triangle, false is - returned. - */ - static bool pointInTri2D(const Vector2& p, const Vector2& a, - const Vector2& b, const Vector2& c); - - /** Checks whether a given 3D point is inside a triangle. - - The vertices of the triangle must be given in either - trigonometrical (anticlockwise) or inverse trigonometrical - (clockwise) order, and the point must be guaranteed to be in the - same plane as the triangle - @param p - p The point. - @param a - The triangle's first vertex. - @param b - The triangle's second vertex. - @param c - The triangle's third vertex. - @param normal - The triangle plane's normal (passed in rather than calculated - on demand since the caller may already have it) - @return - If the point resides in the triangle, true is - returned. - @par - If the point is outside the triangle, false is - returned. - */ - static bool pointInTri3D(const Vector3& p, const Vector3& a, - const Vector3& b, const Vector3& c, const Vector3& normal); - /** Ray / plane intersection */ - static inline RayTestResult intersects(const Ray& ray, const Plane& plane); - /** Ray / sphere intersection */ - static RayTestResult intersects(const Ray& ray, const Sphere& sphere, bool discardInside = true); - /** Ray / box intersection */ - static RayTestResult intersects(const Ray& ray, const AxisAlignedBox& box); - - /** Ray / box intersection, returns boolean result and two intersection distance. - @param ray - The ray. - @param box - The box. - @param d1 - A real pointer to retrieve the near intersection distance - from the ray origin, maybe null which means don't care - about the near intersection distance. - @param d2 - A real pointer to retrieve the far intersection distance - from the ray origin, maybe null which means don't care - about the far intersection distance. - @return - If the ray is intersects the box, true is returned, and - the near intersection distance is return by d1, the - far intersection distance is return by d2. Guarantee - 0 <= d1 <= d2. - @par - If the ray isn't intersects the box, false is returned, and - d1 and d2 is unmodified. - */ - static bool intersects(const Ray& ray, const AxisAlignedBox& box, - Real* d1, Real* d2); - - /** Ray / triangle intersection @cite moller1997fast, returns boolean result and distance. - @param ray - The ray. - @param a - The triangle's first vertex. - @param b - The triangle's second vertex. - @param c - The triangle's third vertex. - @param positiveSide - Intersect with "positive side" of the triangle (as determined by vertex winding) - @param negativeSide - Intersect with "negative side" of the triangle (as determined by vertex winding) - */ - static RayTestResult intersects(const Ray& ray, const Vector3& a, - const Vector3& b, const Vector3& c, - bool positiveSide = true, bool negativeSide = true); - - /// @deprecated normal parameter is not used any more - OGRE_DEPRECATED static RayTestResult intersects(const Ray& ray, const Vector3& a, const Vector3& b, - const Vector3& c, const Vector3& normal, - bool positiveSide = true, bool negativeSide = true) - { - return intersects(ray, a, b, c, positiveSide, negativeSide); - } - - /** Sphere / box intersection test. */ - static bool intersects(const Sphere& sphere, const AxisAlignedBox& box); - - /** Plane / box intersection test. */ - static bool intersects(const Plane& plane, const AxisAlignedBox& box); - - /** Ray / convex plane list intersection test. - @param ray The ray to test with - @param planeList List of planes which form a convex volume - @param normalIsOutside Does the normal point outside the volume - */ - static RayTestResult intersects(const Ray& ray, const std::vector& planeList, bool normalIsOutside); - - /** Sphere / plane intersection test. - @remarks NB just do a plane.getDistance(sphere.getCenter()) for more detail! - */ - static bool intersects(const Sphere& sphere, const Plane& plane); - - /** Compare 2 reals, using tolerance for inaccuracies. - */ - static bool RealEqual(Real a, Real b, - Real tolerance = std::numeric_limits::epsilon()) { - return std::abs(b-a) <= tolerance; - } - - /// @deprecated use @ref TangentSpaceCalc - OGRE_DEPRECATED static Vector3 calculateTangentSpaceVector( - const Vector3& position1, const Vector3& position2, const Vector3& position3, - Real u1, Real v1, Real u2, Real v2, Real u3, Real v3); - - /** Build a reflection matrix for the passed in plane. */ - static Affine3 buildReflectionMatrix(const Plane& p); - /** Calculate a face normal, including the w component which is the offset from the origin. */ - static Vector4 calculateFaceNormal(const Vector3& v1, const Vector3& v2, const Vector3& v3); - /** Calculate a face normal, no w-information. */ - static Vector3 calculateBasicFaceNormal(const Vector3& v1, const Vector3& v2, const Vector3& v3); - /** Calculate a face normal without normalize, including the w component which is the offset from the origin. */ - static Vector4 calculateFaceNormalWithoutNormalize(const Vector3& v1, const Vector3& v2, const Vector3& v3); - /** Calculate a face normal without normalize, no w-information. */ - static Vector3 calculateBasicFaceNormalWithoutNormalize(const Vector3& v1, const Vector3& v2, const Vector3& v3); - - /** Generates a value based on the Gaussian (normal) distribution function - with the given offset and scale parameters. - */ - static Real gaussianDistribution(Real x, Real offset = 0.0f, Real scale = 1.0f); - - /** Clamp a value within an inclusive range. */ - template - static T Clamp(T val, T minval, T maxval) - { - assert (minval <= maxval && "Invalid clamp range"); - return std::max(std::min(val, maxval), minval); - } - - /** This creates a view matrix - - [ Lx Uy Dz Tx ] - [ Lx Uy Dz Ty ] - [ Lx Uy Dz Tz ] - [ 0 0 0 1 ] - - Where T = -(Transposed(Rot) * Pos) - */ - static Affine3 makeViewMatrix(const Vector3& position, const Quaternion& orientation, - const Affine3* reflectMatrix = 0); - - /** Create a rotation matrix from direction and yaw - @param direction the direction to look in. Must be normalised. - @param yaw the yaw axis to use - */ - static Matrix3 lookRotation(const Vector3& direction, const Vector3& yaw); - - /** This creates 'uniform' perspective projection matrix, - which depth range [-1,1], right-handed rules - - [ A 0 C 0 ] - [ 0 B D 0 ] - [ 0 0 q qn ] - [ 0 0 -1 0 ] - - A = 2 * near / (right - left) - B = 2 * near / (top - bottom) - C = (right + left) / (right - left) - D = (top + bottom) / (top - bottom) - q = - (far + near) / (far - near) - qn = - 2 * (far * near) / (far - near) - */ - static Matrix4 makePerspectiveMatrix(Real left, Real right, Real bottom, Real top, Real zNear, Real zFar); - - /** Get the radius of the origin-centered bounding sphere from the bounding box. */ - static Real boundingRadiusFromAABB(const AxisAlignedBox& aabb); - - /** Get the radius of the bbox-centered bounding sphere from the bounding box. */ - static Real boundingRadiusFromAABBCentered(const AxisAlignedBox &aabb); - - - static constexpr Real POS_INFINITY = std::numeric_limits::infinity(); - static constexpr Real NEG_INFINITY = -std::numeric_limits::infinity(); - static constexpr Real PI = static_cast (3.14159265358979323846); - static constexpr Real TWO_PI = Real( 2.0 * PI ); - static constexpr Real HALF_PI = Real( 0.5 * PI ); - static constexpr float fDeg2Rad = PI / Real(180.0); - static constexpr float fRad2Deg = Real(180.0) / PI; - - }; - - // these functions must be defined down here, because they rely on the - // angle unit conversion functions in class Math: - - inline float Radian::valueDegrees() const - { - return Math::RadiansToDegrees ( mRad ); - } - - inline float Radian::valueAngleUnits() const - { - return Math::RadiansToAngleUnits ( mRad ); - } - - inline float Degree::valueRadians() const - { - return Math::DegreesToRadians ( mDeg ); - } - - inline float Degree::valueAngleUnits() const - { - return Math::DegreesToAngleUnits ( mDeg ); - } - - inline Angle::operator Radian() const - { - return Radian(Math::AngleUnitsToRadians(mAngle)); - } - - inline Angle::operator Degree() const - { - return Degree(Math::AngleUnitsToDegrees(mAngle)); - } - - inline Radian operator * ( float a, const Radian& b ) - { - return Radian ( a * b.valueRadians() ); - } - - inline Radian operator / ( float a, const Radian& b ) - { - return Radian ( a / b.valueRadians() ); - } - - inline Degree operator * ( float a, const Degree& b ) - { - return Degree ( a * b.valueDegrees() ); - } - - inline Degree operator / ( float a, const Degree& b ) - { - return Degree ( a / b.valueDegrees() ); - } - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreMatrix3.h b/OgreMain/include/OgreMatrix3.h deleted file mode 100644 index 56df5db6baa..00000000000 --- a/OgreMain/include/OgreMatrix3.h +++ /dev/null @@ -1,341 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Matrix3_H__ -#define __Matrix3_H__ - -#include "OgrePrerequisites.h" - -#include "OgreVector.h" - -// NB All code adapted from Wild Magic 0.2 Matrix math (free source code) -// http://www.geometrictools.com/ - -// NOTE. The (x,y,z) coordinate system is assumed to be right-handed. -// Coordinate axis rotation matrices are of the form -// RX = 1 0 0 -// 0 cos(t) -sin(t) -// 0 sin(t) cos(t) -// where t > 0 indicates a counterclockwise rotation in the yz-plane -// RY = cos(t) 0 sin(t) -// 0 1 0 -// -sin(t) 0 cos(t) -// where t > 0 indicates a counterclockwise rotation in the zx-plane -// RZ = cos(t) -sin(t) 0 -// sin(t) cos(t) 0 -// 0 0 1 -// where t > 0 indicates a counterclockwise rotation in the xy-plane. - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - /** A 3x3 matrix which can represent rotations around axes. - @note - All the code is adapted from the Wild Magic 0.2 Matrix - library (http://www.geometrictools.com/). - @par - The coordinate system is assumed to be right-handed. - */ - class _OgreExport Matrix3 - { - public: - /** Default constructor. - @note - It does NOT initialize the matrix for efficiency. - */ - Matrix3 () {} - explicit Matrix3 (const Real arr[3][3]) - { - memcpy(m,arr,9*sizeof(Real)); - } - - Matrix3 (Real fEntry00, Real fEntry01, Real fEntry02, - Real fEntry10, Real fEntry11, Real fEntry12, - Real fEntry20, Real fEntry21, Real fEntry22) - { - m[0][0] = fEntry00; - m[0][1] = fEntry01; - m[0][2] = fEntry02; - m[1][0] = fEntry10; - m[1][1] = fEntry11; - m[1][2] = fEntry12; - m[2][0] = fEntry20; - m[2][1] = fEntry21; - m[2][2] = fEntry22; - } - - /// Member access, allows use of construct mat[r][c] - const Real* operator[] (size_t iRow) const - { - return m[iRow]; - } - - Real* operator[] (size_t iRow) - { - return m[iRow]; - } - - Vector3 GetColumn(size_t iCol) const - { - assert(iCol < 3); - return Vector3(m[0][iCol], m[1][iCol], m[2][iCol]); - } - void SetColumn(size_t iCol, const Vector3& vec) - { - assert(iCol < 3); - m[0][iCol] = vec.x; - m[1][iCol] = vec.y; - m[2][iCol] = vec.z; - } - void FromAxes(const Vector3& xAxis, const Vector3& yAxis, const Vector3& zAxis) - { - SetColumn(0, xAxis); - SetColumn(1, yAxis); - SetColumn(2, zAxis); - } - - /** Tests 2 matrices for equality. - */ - bool operator== (const Matrix3& rkMatrix) const; - - /** Tests 2 matrices for inequality. - */ - bool operator!= (const Matrix3& rkMatrix) const - { - return !operator==(rkMatrix); - } - - // arithmetic operations - /** Matrix addition. - */ - Matrix3 operator+ (const Matrix3& rkMatrix) const; - - /** Matrix subtraction. - */ - Matrix3 operator- (const Matrix3& rkMatrix) const; - - /** Matrix concatenation using '*'. - */ - Matrix3 operator* (const Matrix3& rkMatrix) const; - Matrix3 operator- () const; - - /// Vector * matrix [1x3 * 3x3 = 1x3] - _OgreExport friend Vector3 operator* (const Vector3& rkVector, - const Matrix3& rkMatrix); - - /// Matrix * scalar - Matrix3 operator* (Real fScalar) const; - - /// Scalar * matrix - _OgreExport friend Matrix3 operator* (Real fScalar, const Matrix3& rkMatrix); - - // utilities - Matrix3 Transpose () const; - bool Inverse (Matrix3& rkInverse, Real fTolerance = 1e-06f) const; - Matrix3 Inverse (Real fTolerance = 1e-06f) const; - Real Determinant() const { return determinant(); } - - Matrix3 transpose() const { return Transpose(); } - Matrix3 inverse() const { return Inverse(); } - Real determinant() const - { - Real fCofactor00 = m[1][1] * m[2][2] - m[1][2] * m[2][1]; - Real fCofactor10 = m[1][2] * m[2][0] - m[1][0] * m[2][2]; - Real fCofactor20 = m[1][0] * m[2][1] - m[1][1] * m[2][0]; - - return m[0][0] * fCofactor00 + m[0][1] * fCofactor10 + m[0][2] * fCofactor20; - } - - /** Determines if this matrix involves a negative scaling. */ - bool hasNegativeScale() const { return determinant() < 0; } - - /// Singular value decomposition - void SingularValueDecomposition (Matrix3& rkL, Vector3& rkS, - Matrix3& rkR) const; - void SingularValueComposition (const Matrix3& rkL, - const Vector3& rkS, const Matrix3& rkR); - - /// Gram-Schmidt orthogonalisation (applied to columns of rotation matrix) - Matrix3 orthonormalised() const - { - // Algorithm uses Gram-Schmidt orthogonalisation. If 'this' matrix is - // M = [m0|m1|m2], then orthonormal output matrix is Q = [q0|q1|q2], - // - // q0 = m0/|m0| - // q1 = (m1-(q0*m1)q0)/|m1-(q0*m1)q0| - // q2 = (m2-(q0*m2)q0-(q1*m2)q1)/|m2-(q0*m2)q0-(q1*m2)q1| - // - // where |V| indicates length of vector V and A*B indicates dot - // product of vectors A and B. - - Matrix3 Q; - // compute q0 - Q.SetColumn(0, GetColumn(0) / GetColumn(0).length()); - - // compute q1 - Real dot0 = Q.GetColumn(0).dotProduct(GetColumn(1)); - Q.SetColumn(1, (GetColumn(1) - dot0 * Q.GetColumn(0)).normalisedCopy()); - - // compute q2 - Real dot1 = Q.GetColumn(1).dotProduct(GetColumn(2)); - dot0 = Q.GetColumn(0).dotProduct(GetColumn(2)); - Q.SetColumn(2, (GetColumn(2) - dot0 * Q.GetColumn(0) + dot1 * Q.GetColumn(1)).normalisedCopy()); - - return Q; - } - - /// @deprecated - OGRE_DEPRECATED void Orthonormalize() { *this = orthonormalised(); } - - /// Orthogonal Q, diagonal D, upper triangular U stored as (u01,u02,u12) - void QDUDecomposition (Matrix3& rkQ, Vector3& rkD, - Vector3& rkU) const; - - Real SpectralNorm () const; - - /// Note: Matrix must be orthonormal - void ToAngleAxis (Vector3& rkAxis, Radian& rfAngle) const; - inline void ToAngleAxis (Vector3& rkAxis, Degree& rfAngle) const { - Radian r; - ToAngleAxis ( rkAxis, r ); - rfAngle = r; - } - void FromAngleAxis (const Vector3& rkAxis, const Radian& fRadians); - - /** - @name Euler angle conversions - (De-)composes the matrix in/ from yaw, pitch and roll angles, - where yaw is rotation about the Y vector, pitch is rotation about the - X axis, and roll is rotation about the Z axis. - - The function suffix indicates the (de-)composition order; - e.g. with the YXZ variants the matrix will be (de-)composed as yaw*pitch*roll - - For ToEulerAngles*, the return value denotes whether the solution is unique. - @note The matrix to be decomposed must be orthonormal. - @{ - */ - bool ToEulerAnglesXYZ(Radian& rfYAngle, Radian& rfPAngle, Radian& rfRAngle) const; - bool ToEulerAnglesXZY(Radian& rfYAngle, Radian& rfPAngle, Radian& rfRAngle) const; - bool ToEulerAnglesYXZ(Radian& rfYAngle, Radian& rfPAngle, Radian& rfRAngle) const; - bool ToEulerAnglesYZX(Radian& rfYAngle, Radian& rfPAngle, Radian& rfRAngle) const; - bool ToEulerAnglesZXY(Radian& rfYAngle, Radian& rfPAngle, Radian& rfRAngle) const; - bool ToEulerAnglesZYX(Radian& rfYAngle, Radian& rfPAngle, Radian& rfRAngle) const; - void FromEulerAnglesXYZ (const Radian& fYAngle, const Radian& fPAngle, const Radian& fRAngle); - void FromEulerAnglesXZY (const Radian& fYAngle, const Radian& fPAngle, const Radian& fRAngle); - void FromEulerAnglesYXZ (const Radian& fYAngle, const Radian& fPAngle, const Radian& fRAngle); - void FromEulerAnglesYZX (const Radian& fYAngle, const Radian& fPAngle, const Radian& fRAngle); - void FromEulerAnglesZXY (const Radian& fYAngle, const Radian& fPAngle, const Radian& fRAngle); - void FromEulerAnglesZYX (const Radian& fYAngle, const Radian& fPAngle, const Radian& fRAngle); - /// @} - /// Eigensolver, matrix must be symmetric - void EigenSolveSymmetric (Real afEigenvalue[3], - Vector3 akEigenvector[3]) const; - - static void TensorProduct (const Vector3& rkU, const Vector3& rkV, - Matrix3& rkProduct); - - /** Determines if this matrix involves a scaling. */ - bool hasScale() const - { - // check magnitude of column vectors (==local axes) - Real t = m[0][0] * m[0][0] + m[1][0] * m[1][0] + m[2][0] * m[2][0]; - if (!Math::RealEqual(t, 1.0, (Real)1e-04)) - return true; - t = m[0][1] * m[0][1] + m[1][1] * m[1][1] + m[2][1] * m[2][1]; - if (!Math::RealEqual(t, 1.0, (Real)1e-04)) - return true; - t = m[0][2] * m[0][2] + m[1][2] * m[1][2] + m[2][2] * m[2][2]; - if (!Math::RealEqual(t, 1.0, (Real)1e-04)) - return true; - - return false; - } - - /** Function for writing to a stream. - */ - inline friend std::ostream& operator << - ( std::ostream& o, const Matrix3& mat ) - { - o << "Matrix3(" << mat[0][0] << ", " << mat[0][1] << ", " << mat[0][2] << "; " - << mat[1][0] << ", " << mat[1][1] << ", " << mat[1][2] << "; " - << mat[2][0] << ", " << mat[2][1] << ", " << mat[2][2] << ")"; - return o; - } - - static const Real EPSILON; - static const Matrix3 ZERO; - static const Matrix3 IDENTITY; - - private: - // support for eigensolver - void Tridiagonal (Real afDiag[3], Real afSubDiag[3]); - bool QLAlgorithm (Real afDiag[3], Real afSubDiag[3]); - - // support for singular value decomposition - static const unsigned int msSvdMaxIterations; - static void Bidiagonalize (Matrix3& kA, Matrix3& kL, - Matrix3& kR); - static void GolubKahanStep (Matrix3& kA, Matrix3& kL, - Matrix3& kR); - - // support for spectral norm - static Real MaxCubicRoot (Real afCoeff[3]); - - Real m[3][3]; - - // for faster access - friend class Matrix4; - }; - - /// Matrix * vector [3x3 * 3x1 = 3x1] - inline Vector3 operator*(const Matrix3& m, const Vector3& v) - { - return Vector3( - m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z, - m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z, - m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z); - } - - inline Matrix3 Math::lookRotation(const Vector3& direction, const Vector3& yaw) - { - Matrix3 ret; - // cross twice to rederive, only direction is unaltered - const Vector3& xAxis = yaw.crossProduct(direction).normalisedCopy(); - const Vector3& yAxis = direction.crossProduct(xAxis); - ret.FromAxes(xAxis, yAxis, direction); - return ret; - } - /** @} */ - /** @} */ -} -#endif diff --git a/OgreMain/include/OgreMatrix4.h b/OgreMain/include/OgreMatrix4.h deleted file mode 100644 index 21f7995c815..00000000000 --- a/OgreMain/include/OgreMatrix4.h +++ /dev/null @@ -1,601 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Matrix4__ -#define __Matrix4__ - -// Precompiler options -#include "OgrePrerequisites.h" - -#include "OgreMatrix3.h" -#include "OgreVector.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - class Matrix4; - class Affine3; - Matrix4 operator*(const Matrix4 &m, const Matrix4 &m2); - /** Class encapsulating a standard 4x4 homogeneous matrix. - - OGRE uses column vectors when applying matrix multiplications, - This means a vector is represented as a single column, 4-row - matrix. This has the effect that the transformations implemented - by the matrices happens right-to-left e.g. if vector V is to be - transformed by M1 then M2 then M3, the calculation would be - M3 * M2 * M1 * V. The order that matrices are concatenated is - vital since matrix multiplication is not commutative, i.e. you - can get a different result if you concatenate in the wrong order. - @par - The use of column vectors and right-to-left ordering is the - standard in most mathematical texts, and is the same as used in - OpenGL. It is, however, the opposite of Direct3D, which has - inexplicably chosen to differ from the accepted standard and uses - row vectors and left-to-right matrix multiplication. - @par - OGRE deals with the differences between D3D and OpenGL etc. - internally when operating through different render systems. OGRE - users only need to conform to standard maths conventions, i.e. - right-to-left matrix multiplication, (OGRE transposes matrices it - passes to D3D to compensate). - @par - The generic form M * V which shows the layout of the matrix - entries is shown below: -
-                [ m[0][0]  m[0][1]  m[0][2]  m[0][3] ]   {x}
-                | m[1][0]  m[1][1]  m[1][2]  m[1][3] | * {y}
-                | m[2][0]  m[2][1]  m[2][2]  m[2][3] |   {z}
-                [ m[3][0]  m[3][1]  m[3][2]  m[3][3] ]   {1}
-            
- */ - template class TransformBase - { - protected: - /// The matrix entries, indexed by [row][col]. - T m[rows][4]; - // do not reduce storage for affine for compatibility with SSE, shader mat4 types - public: - /// Do NOT initialize for efficiency. - TransformBase() {} - - template - explicit TransformBase(const U* ptr) { - for (int i = 0; i < rows; i++) - for (int j = 0; j < 4; j++) - m[i][j] = T(ptr[i*4 + j]); - } - - template - explicit TransformBase(const TransformBase& o) : TransformBase(o[0]) {} - - T* operator[](size_t iRow) - { - assert(iRow < rows); - return m[iRow]; - } - - const T* operator[](size_t iRow) const - { - assert(iRow < rows); - return m[iRow]; - } - - /// Sets the translation transformation part of the matrix. - void setTrans( const Vector<3, T>& v ) - { - assert(rows > 2); - m[0][3] = v[0]; - m[1][3] = v[1]; - m[2][3] = v[2]; - } - /// Extracts the translation transformation part of the matrix. - Vector<3, T> getTrans() const - { - assert(rows > 2); - return Vector<3, T>(m[0][3], m[1][3], m[2][3]); - } - /// Sets the scale part of the matrix. - void setScale( const Vector<3, T>& v ) - { - assert(rows > 2); - m[0][0] = v[0]; - m[1][1] = v[1]; - m[2][2] = v[2]; - } - - /** Function for writing to a stream. - */ - inline friend std::ostream& operator<<(std::ostream& o, const TransformBase& mat) - { - o << "Matrix" << rows << "x4("; - for (size_t i = 0; i < rows; ++i) - { - for (size_t j = 0; j < 4; ++j) - { - o << mat[i][j]; - if(j != 3) - o << ", "; - } - - if(i != (rows - 1)) - o << "; "; - } - o << ")"; - return o; - } - }; - - struct _OgreExport TransformBaseReal : public TransformBase<4, Real> - { - /// Do NOT initialize for efficiency. - TransformBaseReal() {} - template - explicit TransformBaseReal(const U* ptr) : TransformBase(ptr) {} - /** Builds a translation matrix - */ - void makeTrans( const Vector3& v ) - { - makeTrans(v.x, v.y, v.z); - } - - void makeTrans( Real tx, Real ty, Real tz ) - { - m[0][0] = 1.0; m[0][1] = 0.0; m[0][2] = 0.0; m[0][3] = tx; - m[1][0] = 0.0; m[1][1] = 1.0; m[1][2] = 0.0; m[1][3] = ty; - m[2][0] = 0.0; m[2][1] = 0.0; m[2][2] = 1.0; m[2][3] = tz; - m[3][0] = 0.0; m[3][1] = 0.0; m[3][2] = 0.0; m[3][3] = 1.0; - } - - /** Assignment from 3x3 matrix. - */ - void set3x3Matrix(const Matrix3& mat3) - { - m[0][0] = mat3[0][0]; m[0][1] = mat3[0][1]; m[0][2] = mat3[0][2]; - m[1][0] = mat3[1][0]; m[1][1] = mat3[1][1]; m[1][2] = mat3[1][2]; - m[2][0] = mat3[2][0]; m[2][1] = mat3[2][1]; m[2][2] = mat3[2][2]; - } - - /** Extracts the rotation / scaling part of the Matrix as a 3x3 matrix. - */ - Matrix3 linear() const - { - return Matrix3(m[0][0], m[0][1], m[0][2], - m[1][0], m[1][1], m[1][2], - m[2][0], m[2][1], m[2][2]); - } - - OGRE_DEPRECATED void extract3x3Matrix(Matrix3& m3x3) const { m3x3 = linear(); } - OGRE_DEPRECATED Quaternion extractQuaternion() const { return Quaternion(linear()); } - - Real determinant() const; - - Matrix4 transpose() const; - - /** Building a Affine3 from orientation / scale / position. - - Transform is performed in the order scale, rotate, translation, i.e. translation is independent - of orientation axes, scale does not affect size of translation, rotation and scaling are always - centered on the origin. - */ - void makeTransform(const Vector3& position, const Vector3& scale, const Quaternion& orientation); - - /** Building an inverse Affine3 from orientation / scale / position. - - As makeTransform except it build the inverse given the same data as makeTransform, so - performing -translation, -rotate, 1/scale in that order. - */ - void makeInverseTransform(const Vector3& position, const Vector3& scale, const Quaternion& orientation); - }; - - /// Transform specialization for projective - encapsulating a 4x4 Matrix - class _OgreExport Matrix4 : public TransformBaseReal - { - public: - /// Do NOT initialize the matrix for efficiency. - Matrix4() {} - - Matrix4( - Real m00, Real m01, Real m02, Real m03, - Real m10, Real m11, Real m12, Real m13, - Real m20, Real m21, Real m22, Real m23, - Real m30, Real m31, Real m32, Real m33 ) - { - m[0][0] = m00; m[0][1] = m01; m[0][2] = m02; m[0][3] = m03; - m[1][0] = m10; m[1][1] = m11; m[1][2] = m12; m[1][3] = m13; - m[2][0] = m20; m[2][1] = m21; m[2][2] = m22; m[2][3] = m23; - m[3][0] = m30; m[3][1] = m31; m[3][2] = m32; m[3][3] = m33; - } - - template - explicit Matrix4(const U* ptr) : TransformBaseReal(ptr) {} - explicit Matrix4 (const Real* arr) - { - memcpy(m,arr,16*sizeof(Real)); - } - - /** Creates a standard 4x4 transformation matrix with a zero translation part from a rotation/scaling 3x3 matrix. - */ - - explicit Matrix4(const Matrix3& m3x3) - { - operator=(IDENTITY); - operator=(m3x3); - } - - /** Creates a standard 4x4 transformation matrix with a zero translation part from a rotation/scaling Quaternion. - */ - - explicit Matrix4(const Quaternion& rot) - { - Matrix3 m3x3; - rot.ToRotationMatrix(m3x3); - *this = IDENTITY; - *this = m3x3; - } - - Matrix4& operator=(const Matrix3& mat3) { - set3x3Matrix(mat3); - return *this; - } - - OGRE_DEPRECATED Matrix4 concatenate(const Matrix4& m2) const { return *this * m2; } - - /** Tests 2 matrices for equality. - */ - inline bool operator == ( const Matrix4& m2 ) const - { - if( - m[0][0] != m2.m[0][0] || m[0][1] != m2.m[0][1] || m[0][2] != m2.m[0][2] || m[0][3] != m2.m[0][3] || - m[1][0] != m2.m[1][0] || m[1][1] != m2.m[1][1] || m[1][2] != m2.m[1][2] || m[1][3] != m2.m[1][3] || - m[2][0] != m2.m[2][0] || m[2][1] != m2.m[2][1] || m[2][2] != m2.m[2][2] || m[2][3] != m2.m[2][3] || - m[3][0] != m2.m[3][0] || m[3][1] != m2.m[3][1] || m[3][2] != m2.m[3][2] || m[3][3] != m2.m[3][3] ) - return false; - return true; - } - - /** Tests 2 matrices for inequality. - */ - inline bool operator != ( const Matrix4& m2 ) const - { - if( - m[0][0] != m2.m[0][0] || m[0][1] != m2.m[0][1] || m[0][2] != m2.m[0][2] || m[0][3] != m2.m[0][3] || - m[1][0] != m2.m[1][0] || m[1][1] != m2.m[1][1] || m[1][2] != m2.m[1][2] || m[1][3] != m2.m[1][3] || - m[2][0] != m2.m[2][0] || m[2][1] != m2.m[2][1] || m[2][2] != m2.m[2][2] || m[2][3] != m2.m[2][3] || - m[3][0] != m2.m[3][0] || m[3][1] != m2.m[3][1] || m[3][2] != m2.m[3][2] || m[3][3] != m2.m[3][3] ) - return true; - return false; - } - - static const Matrix4 ZERO; - static const Matrix4 IDENTITY; - /** Useful little matrix which takes 2D clipspace {-1, 1} to {0,1} - and inverts the Y. */ - static const Matrix4 CLIPSPACE2DTOIMAGESPACE; - - inline Matrix4 operator*(Real scalar) const - { - return Matrix4( - scalar*m[0][0], scalar*m[0][1], scalar*m[0][2], scalar*m[0][3], - scalar*m[1][0], scalar*m[1][1], scalar*m[1][2], scalar*m[1][3], - scalar*m[2][0], scalar*m[2][1], scalar*m[2][2], scalar*m[2][3], - scalar*m[3][0], scalar*m[3][1], scalar*m[3][2], scalar*m[3][3]); - } - - Matrix4 adjoint() const; - Matrix4 inverse() const; - }; - - /// Transform specialization for 3D Affine - encapsulating a 3x4 Matrix - class _OgreExport Affine3 : public TransformBaseReal - { - public: - /// Do NOT initialize the matrix for efficiency. - Affine3() {} - - /// @copydoc TransformBaseReal::makeTransform - Affine3(const Vector3& position, const Quaternion& orientation, const Vector3& scale = Vector3::UNIT_SCALE) - { - makeTransform(position, scale, orientation); - } - - template - explicit Affine3(const U* ptr) - { - for (int i = 0; i < 3; i++) - for (int j = 0; j < 4; j++) - m[i][j] = Real(ptr[i*4 + j]); - m[3][0] = 0, m[3][1] = 0, m[3][2] = 0, m[3][3] = 1; - } - - explicit Affine3(const Real* arr) - { - memcpy(m, arr, 12 * sizeof(Real)); - m[3][0] = 0, m[3][1] = 0, m[3][2] = 0, m[3][3] = 1; - } - - Affine3( - Real m00, Real m01, Real m02, Real m03, - Real m10, Real m11, Real m12, Real m13, - Real m20, Real m21, Real m22, Real m23) - { - m[0][0] = m00; m[0][1] = m01; m[0][2] = m02; m[0][3] = m03; - m[1][0] = m10; m[1][1] = m11; m[1][2] = m12; m[1][3] = m13; - m[2][0] = m20; m[2][1] = m21; m[2][2] = m22; m[2][3] = m23; - m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1; - } - - /// extract the Affine part of a Matrix4 - explicit Affine3(const Matrix4& mat) - { - m[0][0] = mat[0][0]; m[0][1] = mat[0][1]; m[0][2] = mat[0][2]; m[0][3] = mat[0][3]; - m[1][0] = mat[1][0]; m[1][1] = mat[1][1]; m[1][2] = mat[1][2]; m[1][3] = mat[1][3]; - m[2][0] = mat[2][0]; m[2][1] = mat[2][1]; m[2][2] = mat[2][2]; m[2][3] = mat[2][3]; - m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1; - } - - Affine3& operator=(const Matrix3& mat3) { - set3x3Matrix(mat3); - return *this; - } - - /** Tests 2 matrices for equality. - */ - bool operator==(const Affine3& m2) const - { - if( - m[0][0] != m2.m[0][0] || m[0][1] != m2.m[0][1] || m[0][2] != m2.m[0][2] || m[0][3] != m2.m[0][3] || - m[1][0] != m2.m[1][0] || m[1][1] != m2.m[1][1] || m[1][2] != m2.m[1][2] || m[1][3] != m2.m[1][3] || - m[2][0] != m2.m[2][0] || m[2][1] != m2.m[2][1] || m[2][2] != m2.m[2][2] || m[2][3] != m2.m[2][3] ) - return false; - return true; - } - - bool operator!=(const Affine3& m2) const { return !(*this == m2); } - - Affine3 inverse() const; - - /** Decompose to orientation / scale / position. - */ - void decomposition(Vector3& position, Vector3& scale, Quaternion& orientation) const; - - /// every Affine3 transform is also a _const_ Matrix4 - operator const Matrix4&() const { return reinterpret_cast(*this); } - - using TransformBaseReal::getTrans; - - /** Gets a translation matrix. - */ - static Affine3 getTrans( const Vector3& v ) - { - return getTrans(v.x, v.y, v.z); - } - - /** Gets a translation matrix - variation for not using a vector. - */ - static Affine3 getTrans( Real t_x, Real t_y, Real t_z ) - { - return Affine3(1, 0, 0, t_x, - 0, 1, 0, t_y, - 0, 0, 1, t_z); - } - - /** Gets a scale matrix. - */ - static Affine3 getScale( const Vector3& v ) - { - return getScale(v.x, v.y, v.z); - } - - /** Gets a scale matrix - variation for not using a vector. - */ - static Affine3 getScale( Real s_x, Real s_y, Real s_z ) - { - return Affine3(s_x, 0, 0, 0, - 0, s_y, 0, 0, - 0, 0, s_z, 0); - } - - - static const Affine3 ZERO; - static const Affine3 IDENTITY; - }; - - inline Matrix4 TransformBaseReal::transpose() const - { - return Matrix4(m[0][0], m[1][0], m[2][0], m[3][0], - m[0][1], m[1][1], m[2][1], m[3][1], - m[0][2], m[1][2], m[2][2], m[3][2], - m[0][3], m[1][3], m[2][3], m[3][3]); - } - - /** Matrix addition. - */ - inline Matrix4 operator+(const Matrix4& m, const Matrix4& m2) - { - Matrix4 r; - - r[0][0] = m[0][0] + m2[0][0]; - r[0][1] = m[0][1] + m2[0][1]; - r[0][2] = m[0][2] + m2[0][2]; - r[0][3] = m[0][3] + m2[0][3]; - - r[1][0] = m[1][0] + m2[1][0]; - r[1][1] = m[1][1] + m2[1][1]; - r[1][2] = m[1][2] + m2[1][2]; - r[1][3] = m[1][3] + m2[1][3]; - - r[2][0] = m[2][0] + m2[2][0]; - r[2][1] = m[2][1] + m2[2][1]; - r[2][2] = m[2][2] + m2[2][2]; - r[2][3] = m[2][3] + m2[2][3]; - - r[3][0] = m[3][0] + m2[3][0]; - r[3][1] = m[3][1] + m2[3][1]; - r[3][2] = m[3][2] + m2[3][2]; - r[3][3] = m[3][3] + m2[3][3]; - - return r; - } - - /** Matrix subtraction. - */ - inline Matrix4 operator-(const Matrix4& m, const Matrix4& m2) - { - Matrix4 r; - r[0][0] = m[0][0] - m2[0][0]; - r[0][1] = m[0][1] - m2[0][1]; - r[0][2] = m[0][2] - m2[0][2]; - r[0][3] = m[0][3] - m2[0][3]; - - r[1][0] = m[1][0] - m2[1][0]; - r[1][1] = m[1][1] - m2[1][1]; - r[1][2] = m[1][2] - m2[1][2]; - r[1][3] = m[1][3] - m2[1][3]; - - r[2][0] = m[2][0] - m2[2][0]; - r[2][1] = m[2][1] - m2[2][1]; - r[2][2] = m[2][2] - m2[2][2]; - r[2][3] = m[2][3] - m2[2][3]; - - r[3][0] = m[3][0] - m2[3][0]; - r[3][1] = m[3][1] - m2[3][1]; - r[3][2] = m[3][2] - m2[3][2]; - r[3][3] = m[3][3] - m2[3][3]; - - return r; - } - - inline Matrix4 operator*(const Matrix4 &m, const Matrix4 &m2) - { - Matrix4 r; - r[0][0] = m[0][0] * m2[0][0] + m[0][1] * m2[1][0] + m[0][2] * m2[2][0] + m[0][3] * m2[3][0]; - r[0][1] = m[0][0] * m2[0][1] + m[0][1] * m2[1][1] + m[0][2] * m2[2][1] + m[0][3] * m2[3][1]; - r[0][2] = m[0][0] * m2[0][2] + m[0][1] * m2[1][2] + m[0][2] * m2[2][2] + m[0][3] * m2[3][2]; - r[0][3] = m[0][0] * m2[0][3] + m[0][1] * m2[1][3] + m[0][2] * m2[2][3] + m[0][3] * m2[3][3]; - - r[1][0] = m[1][0] * m2[0][0] + m[1][1] * m2[1][0] + m[1][2] * m2[2][0] + m[1][3] * m2[3][0]; - r[1][1] = m[1][0] * m2[0][1] + m[1][1] * m2[1][1] + m[1][2] * m2[2][1] + m[1][3] * m2[3][1]; - r[1][2] = m[1][0] * m2[0][2] + m[1][1] * m2[1][2] + m[1][2] * m2[2][2] + m[1][3] * m2[3][2]; - r[1][3] = m[1][0] * m2[0][3] + m[1][1] * m2[1][3] + m[1][2] * m2[2][3] + m[1][3] * m2[3][3]; - - r[2][0] = m[2][0] * m2[0][0] + m[2][1] * m2[1][0] + m[2][2] * m2[2][0] + m[2][3] * m2[3][0]; - r[2][1] = m[2][0] * m2[0][1] + m[2][1] * m2[1][1] + m[2][2] * m2[2][1] + m[2][3] * m2[3][1]; - r[2][2] = m[2][0] * m2[0][2] + m[2][1] * m2[1][2] + m[2][2] * m2[2][2] + m[2][3] * m2[3][2]; - r[2][3] = m[2][0] * m2[0][3] + m[2][1] * m2[1][3] + m[2][2] * m2[2][3] + m[2][3] * m2[3][3]; - - r[3][0] = m[3][0] * m2[0][0] + m[3][1] * m2[1][0] + m[3][2] * m2[2][0] + m[3][3] * m2[3][0]; - r[3][1] = m[3][0] * m2[0][1] + m[3][1] * m2[1][1] + m[3][2] * m2[2][1] + m[3][3] * m2[3][1]; - r[3][2] = m[3][0] * m2[0][2] + m[3][1] * m2[1][2] + m[3][2] * m2[2][2] + m[3][3] * m2[3][2]; - r[3][3] = m[3][0] * m2[0][3] + m[3][1] * m2[1][3] + m[3][2] * m2[2][3] + m[3][3] * m2[3][3]; - - return r; - } - inline Affine3 operator*(const Affine3 &m, const Affine3 &m2) - { - return Affine3( - m[0][0] * m2[0][0] + m[0][1] * m2[1][0] + m[0][2] * m2[2][0], - m[0][0] * m2[0][1] + m[0][1] * m2[1][1] + m[0][2] * m2[2][1], - m[0][0] * m2[0][2] + m[0][1] * m2[1][2] + m[0][2] * m2[2][2], - m[0][0] * m2[0][3] + m[0][1] * m2[1][3] + m[0][2] * m2[2][3] + m[0][3], - - m[1][0] * m2[0][0] + m[1][1] * m2[1][0] + m[1][2] * m2[2][0], - m[1][0] * m2[0][1] + m[1][1] * m2[1][1] + m[1][2] * m2[2][1], - m[1][0] * m2[0][2] + m[1][1] * m2[1][2] + m[1][2] * m2[2][2], - m[1][0] * m2[0][3] + m[1][1] * m2[1][3] + m[1][2] * m2[2][3] + m[1][3], - - m[2][0] * m2[0][0] + m[2][1] * m2[1][0] + m[2][2] * m2[2][0], - m[2][0] * m2[0][1] + m[2][1] * m2[1][1] + m[2][2] * m2[2][1], - m[2][0] * m2[0][2] + m[2][1] * m2[1][2] + m[2][2] * m2[2][2], - m[2][0] * m2[0][3] + m[2][1] * m2[1][3] + m[2][2] * m2[2][3] + m[2][3]); - } - - /** Vector transformation using '*'. - - Transforms the given 3-D vector by the matrix, projecting the - result back into w = 1. - @note - This means that the initial w is considered to be 1.0, - and then all the tree elements of the resulting 3-D vector are - divided by the resulting w. - */ - inline Vector3 operator*(const Matrix4& m, const Vector3& v) - { - Vector3 r; - - Real fInvW = 1.0f / ( m[3][0] * v.x + m[3][1] * v.y + m[3][2] * v.z + m[3][3] ); - - r.x = ( m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3] ) * fInvW; - r.y = ( m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3] ) * fInvW; - r.z = ( m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3] ) * fInvW; - - return r; - } - /// @overload - inline Vector3 operator*(const Affine3& m,const Vector3& v) - { - return Vector3( - m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3], - m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3], - m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3]); - } - - inline Vector4 operator*(const Matrix4& m, const Vector4& v) - { - return Vector4( - m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3] * v.w, - m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3] * v.w, - m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3] * v.w, - m[3][0] * v.x + m[3][1] * v.y + m[3][2] * v.z + m[3][3] * v.w); - } - inline Vector4 operator*(const Affine3& m, const Vector4& v) - { - return Vector4( - m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3] * v.w, - m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3] * v.w, - m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3] * v.w, - v.w); - } - - inline Vector4 operator * (const Vector4& v, const Matrix4& mat) - { - return Vector4( - v.x*mat[0][0] + v.y*mat[1][0] + v.z*mat[2][0] + v.w*mat[3][0], - v.x*mat[0][1] + v.y*mat[1][1] + v.z*mat[2][1] + v.w*mat[3][1], - v.x*mat[0][2] + v.y*mat[1][2] + v.z*mat[2][2] + v.w*mat[3][2], - v.x*mat[0][3] + v.y*mat[1][3] + v.z*mat[2][3] + v.w*mat[3][3] - ); - } - /** @} */ - /** @} */ - -} -#endif diff --git a/OgreMain/include/OgreMemoryAllocatorConfig.h b/OgreMain/include/OgreMemoryAllocatorConfig.h deleted file mode 100644 index 18b5d6e626f..00000000000 --- a/OgreMain/include/OgreMemoryAllocatorConfig.h +++ /dev/null @@ -1,207 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __MemoryAllocatorConfig_H__ -#define __MemoryAllocatorConfig_H__ - -#include "OgreAlignedAllocator.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - - /** A set of categories that indicate the purpose of a chunk of memory - being allocated. - These categories will be provided at allocation time in order to allow - the allocation policy to vary its behaviour if it wishes. This allows you - to use a single policy but still have variant behaviour. The level of - control it gives you is at a higher level than assigning different - policies to different classes, but is the only control you have over - general allocations that are primitive types. - */ - enum MemoryCategory - { - /// General purpose - MEMCATEGORY_GENERAL = 0, - /// Geometry held in main memory - MEMCATEGORY_GEOMETRY = 1, - /// Animation data like tracks, bone matrices - MEMCATEGORY_ANIMATION = 2, - /// Nodes, control data - MEMCATEGORY_SCENE_CONTROL = 3, - /// Scene object instances - MEMCATEGORY_SCENE_OBJECTS = 4, - /// Other resources - MEMCATEGORY_RESOURCE = 5, - /// Scripting - MEMCATEGORY_SCRIPTING = 6, - /// Rendersystem structures - MEMCATEGORY_RENDERSYS = 7, - - - // sentinel value, do not use - MEMCATEGORY_COUNT = 8 - }; - /** @} */ - /** @} */ - -} - -namespace Ogre -{ - class AllocPolicy {}; - // this is a template, mainly so swig does not pick it up - template class AllocatedObject {}; - - // Useful shortcuts - typedef AllocPolicy GeneralAllocPolicy; - typedef AllocPolicy GeometryAllocPolicy; - typedef AllocPolicy AnimationAllocPolicy; - typedef AllocPolicy SceneCtlAllocPolicy; - typedef AllocPolicy SceneObjAllocPolicy; - typedef AllocPolicy ResourceAllocPolicy; - typedef AllocPolicy ScriptingAllocPolicy; - typedef AllocPolicy RenderSysAllocPolicy; - - // Now define all the base classes for each allocation - typedef AllocatedObject<> GeneralAllocatedObject; - typedef AllocatedObject<> GeometryAllocatedObject; - typedef AllocatedObject<> AnimationAllocatedObject; - typedef AllocatedObject<> SceneCtlAllocatedObject; - typedef AllocatedObject<> SceneObjAllocatedObject; - typedef AllocatedObject<> ResourceAllocatedObject; - typedef AllocatedObject<> ScriptingAllocatedObject; - typedef AllocatedObject<> RenderSysAllocatedObject; - - - // Per-class allocators defined here - // NOTE: small, non-virtual classes should not subclass an allocator - // the virtual function table could double their size and make them less efficient - // use primitive or STL allocators / deallocators for those - typedef ScriptingAllocatedObject AbstractNodeAlloc; - typedef AnimationAllocatedObject AnimableAlloc; - typedef AnimationAllocatedObject AnimationAlloc; - typedef GeneralAllocatedObject ArchiveAlloc; - typedef GeometryAllocatedObject BatchedGeometryAlloc; - typedef RenderSysAllocatedObject BufferAlloc; - typedef GeneralAllocatedObject CodecAlloc; - typedef ResourceAllocatedObject CompositorInstAlloc; - typedef GeneralAllocatedObject ConfigAlloc; - typedef GeneralAllocatedObject ControllerAlloc; - typedef GeometryAllocatedObject DebugGeomAlloc; - typedef GeneralAllocatedObject DynLibAlloc; - typedef GeometryAllocatedObject EdgeDataAlloc; - typedef GeneralAllocatedObject FactoryAlloc; - typedef SceneObjAllocatedObject FXAlloc; - typedef GeneralAllocatedObject ImageAlloc; - typedef GeometryAllocatedObject IndexDataAlloc; - typedef GeneralAllocatedObject LogAlloc; - typedef SceneObjAllocatedObject MovableAlloc; - typedef SceneCtlAllocatedObject NodeAlloc; - typedef SceneObjAllocatedObject OverlayAlloc; - typedef RenderSysAllocatedObject GpuParamsAlloc; - typedef ResourceAllocatedObject PassAlloc; - typedef GeometryAllocatedObject PatchAlloc; - typedef GeneralAllocatedObject PluginAlloc; - typedef GeneralAllocatedObject ProfilerAlloc; - typedef GeometryAllocatedObject ProgMeshAlloc; - typedef SceneCtlAllocatedObject RenderQueueAlloc; - typedef RenderSysAllocatedObject RenderSysAlloc; - typedef GeneralAllocatedObject RootAlloc; - typedef ResourceAllocatedObject ResourceAlloc; - typedef GeneralAllocatedObject SerializerAlloc; - typedef SceneCtlAllocatedObject SceneMgtAlloc; - typedef ScriptingAllocatedObject ScriptCompilerAlloc; - typedef ScriptingAllocatedObject ScriptTranslatorAlloc; - typedef SceneCtlAllocatedObject ShadowDataAlloc; - typedef GeneralAllocatedObject StreamAlloc; - typedef SceneObjAllocatedObject SubEntityAlloc; - typedef ResourceAllocatedObject SubMeshAlloc; - typedef ResourceAllocatedObject TechniqueAlloc; - typedef GeneralAllocatedObject TimerAlloc; - typedef ResourceAllocatedObject TextureUnitStateAlloc; - typedef GeneralAllocatedObject UtilityAlloc; - typedef GeometryAllocatedObject VertexDataAlloc; - typedef RenderSysAllocatedObject ViewportAlloc; - typedef SceneCtlAllocatedObject LodAlloc; - typedef GeneralAllocatedObject FileSystemLayerAlloc; - typedef GeneralAllocatedObject StereoDriverAlloc; - - // Containers (by-value only) - // Will be of the form: - // typedef STLAllocator TAlloc; - // for use in std::vector - - - -} - -// define macros - -/** \addtogroup Core -* @{ -*/ -/** \addtogroup General -* @{ -*/ - -/// Allocate a block of raw memory, and indicate the category of usage -# define OGRE_MALLOC(bytes, category) (void*)new char[bytes] -/// Allocate a block of memory for a primitive type, and indicate the category of usage -# define OGRE_ALLOC_T(T, count, category) (T*)new char[(count) * sizeof(T)] -/// Free the memory allocated with OGRE_MALLOC or OGRE_ALLOC_T. Category is required to be restated to ensure the matching policy is used -# define OGRE_FREE(ptr, category) delete[] (char*)ptr - -/// Allocate space for one primitive type, external type or non-virtual type with constructor parameters -# define OGRE_NEW_T(T, category) new T -/// Allocate a block of memory for 'count' primitive types - do not use for classes that inherit from AllocatedObject -# define OGRE_NEW_ARRAY_T(T, count, category) new T[count] -/// Free the memory allocated with OGRE_NEW_T. Category is required to be restated to ensure the matching policy is used -# define OGRE_DELETE_T(ptr, T, category) delete ptr -/// Free the memory allocated with OGRE_NEW_ARRAY_T. Category is required to be restated to ensure the matching policy is used, count and type to call destructor -# define OGRE_DELETE_ARRAY_T(ptr, T, count, category) delete[] ptr - -// aligned allocation -/// Allocate a block of raw memory aligned to SIMD boundaries, and indicate the category of usage -# define OGRE_MALLOC_SIMD(bytes, category) ::Ogre::AlignedMemory::allocate(bytes) -/// Free the memory allocated with either OGRE_MALLOC_SIMD or OGRE_ALLOC_T_SIMD. Category is required to be restated to ensure the matching policy is used -# define OGRE_FREE_SIMD(ptr, category) ::Ogre::AlignedMemory::deallocate((void*)ptr) - -// new / delete for classes deriving from AllocatedObject (alignment determined by per-class policy) -# define OGRE_NEW new -# define OGRE_DELETE delete - -/** @} */ -/** @} */ - -#endif diff --git a/OgreMain/include/OgreMesh.h b/OgreMain/include/OgreMesh.h deleted file mode 100644 index 28f18e80630..00000000000 --- a/OgreMain/include/OgreMesh.h +++ /dev/null @@ -1,996 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Mesh_H__ -#define __Mesh_H__ - -#include "OgrePrerequisites.h" - -#include "OgreResource.h" -#include "OgreAxisAlignedBox.h" -#include "OgreVertexBoneAssignment.h" -#include "OgreAnimation.h" -#include "OgreAnimationTrack.h" -#include "OgreHeaderPrefix.h" -#include "OgreSharedPtr.h" -#include "OgreUserObjectBindings.h" -#include "OgreVertexIndexData.h" - - -namespace Ogre { - - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - - struct MeshLodUsage; - class LodStrategy; - - /** Resource holding data about 3D mesh. - - This class holds the data used to represent a discrete - 3-dimensional object. Mesh data usually contains more - than just vertices and triangle information; it also - includes references to materials (and the faces which use them), - level-of-detail reduction information, convex hull definition, - skeleton/bones information, keyframe animation etc. - However, it is important to note the emphasis on the word - 'discrete' here. This class does not cover the large-scale - sprawling geometry found in level / landscape data. - @par - Multiple world objects can (indeed should) be created from a - single mesh object - see the Entity class for more info. - The mesh object will have it's own default - material properties, but potentially each world instance may - wish to customise the materials from the original. When the object - is instantiated into a scene node, the mesh material properties - will be taken by default but may be changed. These properties - are actually held at the SubMesh level since a single mesh may - have parts with different materials. - @par - As described above, because the mesh may have sections of differing - material properties, a mesh is inherently a compound construct, - consisting of one or more SubMesh objects. - However, it strongly 'owns' it's SubMeshes such that they - are loaded / unloaded at the same time. This is contrary to - the approach taken to hierarchically related (but loosely owned) - scene nodes, where data is loaded / unloaded separately. Note - also that mesh sub-sections (when used in an instantiated object) - share the same scene node as the parent. - */ - class _OgreExport Mesh: public Resource, public AnimationContainer - { - friend class SubMesh; - friend class MeshSerializerImpl; - friend class MeshSerializerImpl_v1_8; - friend class MeshSerializerImpl_v1_4; - friend class MeshSerializerImpl_v1_3; - friend class MeshSerializerImpl_v1_2; - friend class MeshSerializerImpl_v1_1; - - public: - typedef std::vector LodValueList; - typedef std::vector MeshLodUsageList; - /// Multimap of vertex bone assignments (orders by vertex index). - typedef std::multimap VertexBoneAssignmentList; - typedef MapIterator BoneAssignmentIterator; - typedef std::vector SubMeshList; - typedef std::vector IndexMap; - - private: - /** A list of submeshes which make up this mesh. - Each mesh is made up of 1 or more submeshes, which - are each based on a single material and can have their - own vertex data (they may not - they can share vertex data - from the Mesh, depending on preference). - */ - SubMeshList mSubMeshList; - - /** Internal method for making the space for a vertex element to hold tangents. */ - void organiseTangentsBuffer(VertexData *vertexData, - VertexElementSemantic targetSemantic, unsigned short index, - unsigned short sourceTexCoordSet); - - public: - /** A hashmap used to store optional SubMesh names. - Translates a name into SubMesh index. - */ - typedef std::unordered_map SubMeshNameMap ; - - - private: - - DataStreamPtr mFreshFromDisk; - - SubMeshNameMap mSubMeshNameMap ; - - UserObjectBindings mUserObjectBindings; - - /// Local bounding box volume. - AxisAlignedBox mAABB; - /// Local bounding sphere radius (centered on object). - Real mBoundRadius; - /// Largest bounding radius of any bone in the skeleton (centered on each bone, only considering verts weighted to the bone) - Real mBoneBoundingRadius; - - /// Optional linked skeleton. - SkeletonPtr mSkeleton; - - VertexBoneAssignmentList mBoneAssignments; - - /// Flag indicating that bone assignments need to be recompiled. - bool mBoneAssignmentsOutOfDate; - - /** Build the index map between bone index and blend index. */ - void buildIndexMap(const VertexBoneAssignmentList& boneAssignments, - IndexMap& boneIndexToBlendIndexMap, IndexMap& blendIndexToBoneIndexMap); - /** Compile bone assignments into blend index and weight buffers. */ - void compileBoneAssignments(const VertexBoneAssignmentList& boneAssignments, - unsigned short numBlendWeightsPerVertex, - IndexMap& blendIndexToBoneIndexMap, - VertexData* targetVertexData); -#if !OGRE_NO_MESHLOD - const LodStrategy *mLodStrategy; - bool mHasManualLodLevel; - ushort mNumLods; - MeshLodUsageList mMeshLodUsageList; -#else - const LodStrategy *mLodStrategy; - const bool mHasManualLodLevel; - const ushort mNumLods; - MeshLodUsageList mMeshLodUsageList; -#endif - HardwareBufferManagerBase* mBufferManager; - HardwareBufferUsage mVertexBufferUsage; - HardwareBufferUsage mIndexBufferUsage; - bool mVertexBufferShadowBuffer; - bool mIndexBufferShadowBuffer; - - - bool mPreparedForShadowVolumes; - bool mEdgeListsBuilt; - bool mAutoBuildEdgeLists; - - /// Storage of morph animations, lookup by name - typedef std::map AnimationList; - AnimationList mAnimationsList; - /// The vertex animation type associated with the shared vertex data - mutable VertexAnimationType mSharedVertexDataAnimationType; - /// Whether vertex animation includes normals - mutable bool mSharedVertexDataAnimationIncludesNormals; - /// Do we need to scan animations for animation types? - mutable bool mAnimationTypesDirty; - - /// List of available poses for shared and dedicated geometryPoseList - PoseList mPoseList; - mutable bool mPosesIncludeNormals; - - - /** Loads the mesh from disk. This call only performs IO, it - does not parse the bytestream or check for any errors therein. - It also does not set up submeshes, etc. You have to call load() - to do that. - */ - void prepareImpl(void) override; - /** Destroys data cached by prepareImpl. - */ - void unprepareImpl(void) override; - /// @copydoc Resource::loadImpl - void loadImpl(void) override; - /// @copydoc Resource::postLoadImpl - void postLoadImpl(void) override; - /// @copydoc Resource::unloadImpl - void unloadImpl(void) override; - /// @copydoc Resource::calculateSize - size_t calculateSize(void) const override; - - void mergeAdjacentTexcoords( unsigned short finalTexCoordSet, - unsigned short texCoordSetToDestroy, VertexData *vertexData ); - - - public: - /** Default constructor - used by MeshManager - @warning - Do not call this method directly. - */ - Mesh(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual = false, ManualResourceLoader* loader = 0); - ~Mesh(); - - // NB All methods below are non-virtual since they will be - // called in the rendering loop - speed is of the essence. - - /** Creates a new SubMesh. - - Method for manually creating geometry for the mesh. - Note - use with extreme caution - you must be sure that - you have set up the geometry properly. - */ - SubMesh* createSubMesh(void); - - /** Creates a new SubMesh and gives it a name - */ - SubMesh* createSubMesh(const String& name); - - /** Gives a name to a SubMesh - */ - void nameSubMesh(const String& name, ushort index); - - /** Removes a name from a SubMesh - */ - void unnameSubMesh(const String& name); - - /** Gets the index of a submesh with a given name. - - Useful if you identify the SubMeshes by name (using nameSubMesh) - but wish to have faster repeat access. - */ - ushort _getSubMeshIndex(const String& name) const; - - /** Gets the number of sub meshes which comprise this mesh. - * @deprecated use getSubMeshes() instead - */ - size_t getNumSubMeshes(void) const { - return mSubMeshList.size(); - } - - /** Gets a pointer to the submesh indicated by the index. - * @deprecated use getSubMeshes() instead - */ - SubMesh* getSubMesh(size_t index) const { - return mSubMeshList[index]; - } - - /** Gets a SubMesh by name - */ - SubMesh* getSubMesh(const String& name) const ; - - /** Destroy a SubMesh with the given index. - @note - This will invalidate the contents of any existing Entity, or - any other object that is referring to the SubMesh list. Entity will - detect this and reinitialise, but it is still a disruptive action. - */ - void destroySubMesh(unsigned short index); - - /** Destroy a SubMesh with the given name. - @note - This will invalidate the contents of any existing Entity, or - any other object that is referring to the SubMesh list. Entity will - detect this and reinitialise, but it is still a disruptive action. - */ - void destroySubMesh(const String& name); - - typedef VectorIterator SubMeshIterator; - /// Gets an iterator over the available submeshes - /// @deprecated use getSubMeshes() instead - OGRE_DEPRECATED SubMeshIterator getSubMeshIterator(void) - { return SubMeshIterator(mSubMeshList.begin(), mSubMeshList.end()); } - - /// Gets the available submeshes - const SubMeshList& getSubMeshes() const { - return mSubMeshList; - } - - /** Shared vertex data. - - This vertex data can be shared among multiple submeshes. SubMeshes may not have - their own VertexData, they may share this one. - @par - The use of shared or non-shared buffers is determined when - model data is converted to the OGRE .mesh format. - */ - VertexData *sharedVertexData; - - /// replace the shared vertex data with a new one - void resetVertexData(VertexData* data = nullptr) - { - delete sharedVertexData; - sharedVertexData = data; - } - - /// Creates a new shared vertex data object - void createVertexData(HardwareBufferManagerBase* mgr = nullptr) { resetVertexData(new VertexData(mgr)); } - - /** Shared index map for translating blend index to bone index. - - This index map can be shared among multiple submeshes. SubMeshes might not have - their own IndexMap, they might share this one. - @par - We collect actually used bones of all bone assignments, and build the - blend index in 'packed' form, then the range of the blend index in vertex - data VES_BLEND_INDICES element is continuous, with no gaps. Thus, by - minimising the world matrix array constants passing to GPU, we can support - more bones for a mesh when hardware skinning is used. The hardware skinning - support limit is applied to each set of vertex data in the mesh, in other words, the - hardware skinning support limit is applied only to the actually used bones of each - SubMeshes, not all bones across the entire Mesh. - @par - Because the blend index is different to the bone index, therefore, we use - the index map to translate the blend index to bone index. - @par - The use of shared or non-shared index map is determined when - model data is converted to the OGRE .mesh format. - */ - IndexMap sharedBlendIndexToBoneIndexMap; - - /** Makes a copy of this mesh object and gives it a new name. - - This is useful if you want to tweak an existing mesh without affecting the original one. The - newly cloned mesh is registered with the MeshManager under the new name. - @param newName - The name to give the clone. - @param newGroup - Optional name of the new group to assign the clone to; - if you leave this blank, the clone will be assigned to the same - group as this Mesh. - */ - MeshPtr clone(const String& newName, const String& newGroup = BLANKSTRING); - - /** @copydoc Resource::reload */ - void reload(LoadingFlags flags = LF_DEFAULT) override; - - /** Get the axis-aligned bounding box for this mesh. - */ - const AxisAlignedBox& getBounds(void) const; - - /** Gets the radius of the bounding sphere surrounding this mesh. */ - Real getBoundingSphereRadius(void) const; - - /** Gets the radius used to inflate the bounding box around the bones. */ - Real getBoneBoundingRadius() const; - - /** Manually set the bounding box for this Mesh. - - Calling this method is required when building manual meshes now, because OGRE can no longer - update the bounds for you, because it cannot necessarily read vertex data back from - the vertex buffers which this mesh uses (they very well might be write-only, and even - if they are not, reading data from a hardware buffer is a bottleneck). - @param bounds The axis-aligned bounding box for this mesh - @param pad If true, a certain padding will be added to the bounding box to separate it from the mesh - */ - void _setBounds(const AxisAlignedBox& bounds, bool pad = true); - - /** Manually set the bounding radius. - - Calling this method is required when building manual meshes now, because OGRE can no longer - update the bounds for you, because it cannot necessarily read vertex data back from - the vertex buffers which this mesh uses (they very well might be write-only, and even - if they are not, reading data from a hardware buffer is a bottleneck). - */ - void _setBoundingSphereRadius(Real radius); - - /** Manually set the bone bounding radius. - - This value is normally computed automatically, however it can be overridden with this method. - */ - void _setBoneBoundingRadius(Real radius); - - /** Compute the bone bounding radius by looking at the vertices, vertex-bone-assignments, and skeleton bind pose. - - This is automatically called by Entity if necessary. Only does something if the boneBoundingRadius is zero to - begin with. Only works if vertex data is readable (i.e. not WRITE_ONLY). - */ - void _computeBoneBoundingRadius(); - - /** Automatically update the bounding radius and bounding box for this Mesh. - - Calling this method is required when building manual meshes. However it is recommended to - use _setBounds and _setBoundingSphereRadius instead, because the vertex buffer may not have - a shadow copy in the memory. Reading back the buffer from video memory is very slow! - @param pad If true, a certain padding will be added to the bounding box to separate it from the mesh - */ - void _updateBoundsFromVertexBuffers(bool pad = false); - - /** Calculates - - Calling this method is required when building manual meshes. However it is recommended to - use _setBounds and _setBoundingSphereRadius instead, because the vertex buffer may not have - a shadow copy in the memory. Reading back the buffer from video memory is very slow! - */ - void _calcBoundsFromVertexBuffer(VertexData* vertexData, AxisAlignedBox& outAABB, Real& outRadius, bool updateOnly = false); - /** Sets the name of the skeleton this Mesh uses for animation. - - Meshes can optionally be assigned a skeleton which can be used to animate - the mesh through bone assignments. The default is for the Mesh to use no - skeleton. Calling this method with a valid skeleton filename will cause the - skeleton to be loaded if it is not already (a single skeleton can be shared - by many Mesh objects). - @param skelName - The name of the .skeleton file to use, or an empty string to use - no skeleton - */ - void setSkeletonName(const String& skelName); - - /** Returns true if this Mesh has a linked Skeleton. */ - bool hasSkeleton(void) const { return mSkeleton != 0; } - - /** Returns whether or not this mesh has some kind of vertex animation. - */ - bool hasVertexAnimation(void) const; - - /** Gets a pointer to any linked Skeleton. - @return - Weak reference to the skeleton - copy this if you want to hold a strong pointer. - */ - const SkeletonPtr& getSkeleton(void) const { return mSkeleton; } - - /** Gets the name of any linked Skeleton */ - const String& getSkeletonName(void) const; - /** Initialise an animation set suitable for use with this mesh. - - Only recommended for use inside the engine, not by applications. - */ - void _initAnimationState(AnimationStateSet* animSet); - - /** Refresh an animation set suitable for use with this mesh. - - Only recommended for use inside the engine, not by applications. - */ - void _refreshAnimationState(AnimationStateSet* animSet); - /** Assigns a vertex to a bone with a given weight, for skeletal animation. - - This method is only valid after calling setSkeletonName. - Since this is a one-off process there exists only 'addBoneAssignment' and - 'clearBoneAssignments' methods, no 'editBoneAssignment'. You should not need - to modify bone assignments during rendering (only the positions of bones) and OGRE - reserves the right to do some internal data reformatting of this information, depending - on render system requirements. - @par - This method is for assigning weights to the shared geometry of the Mesh. To assign - weights to the per-SubMesh geometry, see the equivalent methods on SubMesh. - */ - void addBoneAssignment(const VertexBoneAssignment& vertBoneAssign); - - /** Removes all bone assignments for this mesh. - - This method is for modifying weights to the shared geometry of the Mesh. To assign - weights to the per-SubMesh geometry, see the equivalent methods on SubMesh. - */ - void clearBoneAssignments(void); - - /** Internal notification, used to tell the Mesh which Skeleton to use without loading it. - - This is only here for unusual situation where you want to manually set up a - Skeleton. Best to let OGRE deal with this, don't call it yourself unless you - really know what you're doing. - */ - void _notifySkeleton(const SkeletonPtr& pSkel); - - - /// @deprecated use getBoneAssignments - OGRE_DEPRECATED BoneAssignmentIterator getBoneAssignmentIterator(void); - - /** Gets a const reference to the list of bone assignments - */ - const VertexBoneAssignmentList& getBoneAssignments() const { return mBoneAssignments; } - - /** Returns the number of levels of detail that this mesh supports. - - This number includes the original model. - */ - ushort getNumLodLevels(void) const { return mNumLods; } - /** Gets details of the numbered level of detail entry. */ - const MeshLodUsage& getLodLevel(ushort index) const; - - /** Retrieves the level of detail index for the given LOD value. - @note - The value passed in is the 'transformed' value. If you are dealing with - an original source value (e.g. distance), use LodStrategy::transformUserValue - to turn this into a lookup value. - */ - ushort getLodIndex(Real value) const; - - /** Returns true if this mesh has a manual LOD level. - - A mesh can either use automatically generated LOD, or it can use alternative - meshes as provided by an artist. - */ - bool hasManualLodLevel(void) const { return mHasManualLodLevel; } -#if !OGRE_NO_MESHLOD - /** Changes the alternate mesh to use as a manual LOD at the given index. - - Note that the index of a LOD may change if you insert other LODs. If in doubt, - use getLodIndex(). - @param index - The index of the level to be changed. - @param meshName - The name of the mesh which will be the lower level detail version. - */ - void updateManualLodLevel(ushort index, const String& meshName); - - /** Internal methods for loading LOD, do not use. */ - void _setLodInfo(unsigned short numLevels); - /** Internal methods for loading LOD, do not use. */ - void _setLodUsage(unsigned short level, const MeshLodUsage& usage); - /** Internal methods for loading LOD, do not use. */ - void _setSubMeshLodFaceList(unsigned short subIdx, unsigned short level, IndexData* facedata); -#endif - /** Internal methods for loading LOD, do not use. */ - bool _isManualLodLevel(unsigned short level) const; - - - /** Removes all LOD data from this Mesh. */ - void removeLodLevels(void); - - /** Sets the manager for the vertex and index buffers to be used when loading - this Mesh. - - @param bufferManager - If set to @ref DefaultHardwareBufferManager, the buffers will be created in system memory - only, without hardware counterparts. Such mesh could not be rendered, but LODs could be - generated for such mesh, it could be cloned, transformed and serialized. - */ - void setHardwareBufferManager(HardwareBufferManagerBase* bufferManager) { mBufferManager = bufferManager; } - HardwareBufferManagerBase* getHardwareBufferManager(); - /** Sets the policy for the vertex buffers to be used when loading - this Mesh. - - By default, when loading the %Mesh, static, write-only vertex and index buffers - will be used where possible in order to improve rendering performance. - However, such buffers - cannot be manipulated on the fly by CPU code (although shader code can). If you - wish to use the CPU to modify these buffers, you should call this method. - - @note This only takes effect after the Mesh has been reloaded. Also, you - still have the option of manually replacing the buffers in this mesh with your - own if you see fit too, in which case you don't need to call this method since it - only affects buffers created by the mesh itself. - - You can define the approach to a %Mesh by changing the default parameters to - MeshManager::load if you wish; this means the Mesh is loaded with those options - the first time instead of you having to reload the mesh after changing these options. - @param usage - The usage flag, which by default is #HBU_GPU_ONLY - @param shadowBuffer - If set to @c true, the vertex buffers will be created with a - system memory shadow buffer. You should set this if you want to be able to - read from the buffer - */ - void setVertexBufferPolicy(HardwareBuffer::Usage usage, bool shadowBuffer = false); - /** Sets the policy for the index buffers to be used when loading - this Mesh. - - @copydetails setVertexBufferPolicy - */ - void setIndexBufferPolicy(HardwareBuffer::Usage usage, bool shadowBuffer = false); - /** Gets the usage setting for this meshes vertex buffers. */ - HardwareBufferUsage getVertexBufferUsage(void) const { return mVertexBufferUsage; } - /** Gets the usage setting for this meshes index buffers. */ - HardwareBufferUsage getIndexBufferUsage(void) const { return mIndexBufferUsage; } - /** Gets whether or not this meshes vertex buffers are shadowed. */ - bool isVertexBufferShadowed(void) const { return mVertexBufferShadowBuffer; } - /** Gets whether or not this meshes index buffers are shadowed. */ - bool isIndexBufferShadowed(void) const { return mIndexBufferShadowBuffer; } - - - /** Rationalises the passed in bone assignment list. - - OGRE supports up to 4 bone assignments per vertex. The reason for this limit - is that this is the maximum number of assignments that can be passed into - a hardware-assisted blending algorithm. This method identifies where there are - more than 4 bone assignments for a given vertex, and eliminates the bone - assignments with the lowest weights to reduce to this limit. The remaining - weights are then re-balanced to ensure that they sum to 1.0. - @param vertexCount - The number of vertices. - @param assignments - The bone assignment list to rationalise. This list will be modified and - entries will be removed where the limits are exceeded. - @return - The maximum number of bone assignments per vertex found, clamped to [1-4] - */ - unsigned short _rationaliseBoneAssignments(size_t vertexCount, VertexBoneAssignmentList& assignments); - - /** Internal method, be called once to compile bone assignments into geometry buffer. - - The OGRE engine calls this method automatically. It compiles the information - submitted as bone assignments into a format usable in realtime. It also - eliminates excessive bone assignments (max is OGRE_MAX_BLEND_WEIGHTS) - and re-normalises the remaining assignments. - */ - void _compileBoneAssignments(void); - - /** Internal method, be called once to update the compiled bone assignments. - - The OGRE engine calls this method automatically. It updates the compiled bone - assignments if requested. - */ - void _updateCompiledBoneAssignments(void); - - /** This method collapses two texcoords into one for all submeshes where this is possible. - - Often a submesh can have two tex. coords. (i.e. TEXCOORD0 & TEXCOORD1), being both - composed of two floats. There are many practical reasons why it would be more convenient - to merge both of them into one TEXCOORD0 of 4 floats. This function does exactly that - The finalTexCoordSet must have enough space for the merge, or else the submesh will be - skipped. (i.e. you can't merge a tex. coord with 3 floats with one having 2 floats) - - finalTexCoordSet & texCoordSetToDestroy must be in the same buffer source, and must - be adjacent. - @param finalTexCoordSet The tex. coord index to merge to. Should have enough space to - actually work. - @param texCoordSetToDestroy The texture coordinate index that will disappear on - successful merges. - */ - void mergeAdjacentTexcoords( unsigned short finalTexCoordSet, unsigned short texCoordSetToDestroy ); - - /** This method builds a set of tangent vectors for a given mesh into a 3D texture coordinate buffer. - - Tangent vectors are vectors representing the local 'X' axis for a given vertex based - on the orientation of the 2D texture on the geometry. They are built from a combination - of existing normals, and from the 2D texture coordinates already baked into the model. - They can be used for a number of things, but most of all they are useful for - vertex and fragment programs, when you wish to arrive at a common space for doing - per-pixel calculations. - @par - The prerequisites for calling this method include that the vertex data used by every - SubMesh has both vertex normals and 2D texture coordinates. - @param sourceTexCoordSet - The texture coordinate index which should be used as the source - of 2D texture coordinates, with which to calculate the tangents. - @param splitMirrored - Sets whether or not to split vertices when a mirrored tangent space - transition is detected (matrix parity differs). @ref TangentSpaceCalc::setSplitMirrored - @param splitRotated - Sets whether or not to split vertices when a rotated tangent space - is detected. @ref TangentSpaceCalc::setSplitRotated - @param storeParityInW - If @c true, store tangents as a 4-vector and include parity in w. - */ - void buildTangentVectors(unsigned short sourceTexCoordSet = 0, bool splitMirrored = false, - bool splitRotated = false, bool storeParityInW = false); - - /// @deprecated - OGRE_DEPRECATED void buildTangentVectors(VertexElementSemantic targetSemantic, - unsigned short sourceTexCoordSet = 0, unsigned short index = 0, - bool splitMirrored = false, bool splitRotated = false, - bool storeParityInW = false) - { - OgreAssert(targetSemantic == VES_TANGENT && index == 0, "Invalid Parameters"); - buildTangentVectors(sourceTexCoordSet, splitMirrored, splitRotated, storeParityInW); - } - - /** Ask the mesh to suggest a source texture coordinate set to a future buildTangentVectors call - - It will detect when there are inappropriate - conditions (such as multiple geometry sets which don't agree). - @param outSourceCoordSet - Reference to a source texture coordinate set which - will be used. - @return @c true if it detects that tangents may have been prepared already. - */ - bool suggestTangentVectorBuildParams(unsigned short& outSourceCoordSet); - - /// @deprecated - OGRE_DEPRECATED bool suggestTangentVectorBuildParams(VertexElementSemantic targetSemantic, - unsigned short& outSourceCoordSet, - unsigned short& outIndex) - { - OgreAssert(targetSemantic == VES_TANGENT, "Invalid targetSemantic"); - outIndex = 0; - return suggestTangentVectorBuildParams(outSourceCoordSet); - } - - /** Builds an edge list for this mesh, which can be used for generating a shadow volume - among other things. - */ - void buildEdgeList(void); - /** Destroys and frees the edge lists this mesh has built. */ - void freeEdgeList(void); - - /// @copydoc VertexData::prepareForShadowVolume - void prepareForShadowVolume(void); - - /** Return the edge list for this mesh, building it if required. - - You must ensure that the Mesh as been prepared for shadow volume - rendering if you intend to use this information for that purpose. - @param lodIndex - The LOD at which to get the edge list, 0 being the highest. - */ - EdgeData* getEdgeList(unsigned short lodIndex = 0); - - /** Return the edge list for this mesh, building it if required. - - You must ensure that the Mesh as been prepared for shadow volume - rendering if you intend to use this information for that purpose. - @param lodIndex - The LOD at which to get the edge list, 0 being the highest. - */ - const EdgeData* getEdgeList(unsigned short lodIndex = 0) const; - - /** Returns whether this mesh has already had it's geometry prepared for use in - rendering shadow volumes. */ - bool isPreparedForShadowVolumes(void) const { return mPreparedForShadowVolumes; } - - /** Returns whether this mesh has an attached edge list. */ - bool isEdgeListBuilt(void) const { return mEdgeListsBuilt; } - - /** Prepare matrices for software indexed vertex blend. - - This function organise bone indexed matrices to blend indexed matrices, - so software vertex blending can access to the matrix via blend index - directly. - @param blendMatrices - Pointer to an array of matrix pointers to store - prepared results, which indexed by blend index. - @param boneMatrices - Pointer to an array of matrices to be used to blend, - which indexed by bone index. - @param indexMap - The index map used to translate blend index to bone index. - */ - static void prepareMatricesForVertexBlend(const Affine3** blendMatrices, - const Affine3* boneMatrices, const IndexMap& indexMap); - - /** Performs a software indexed vertex blend, of the kind used for - skeletal animation although it can be used for other purposes. - - This function is supplied to update vertex data with blends - done in software, either because no hardware support is available, - or that you need the results of the blend for some other CPU operations. - @param sourceVertexData - VertexData class containing positions, normals, - blend indices and blend weights. - @param targetVertexData - VertexData class containing target position - and normal buffers which will be updated with the blended versions. - Note that the layout of the source and target position / normal - buffers must be identical, ie they must use the same buffer indexes - @param blendMatrices - Pointer to an array of matrix pointers to be used to blend, - indexed by blend indices in the sourceVertexData - @param numMatrices - Number of matrices in the blendMatrices, it might be used - as a hint for optimisation. - @param blendNormals - If @c true, normals are blended as well as positions. - */ - static void softwareVertexBlend(const VertexData* sourceVertexData, - const VertexData* targetVertexData, - const Affine3* const* blendMatrices, size_t numMatrices, - bool blendNormals); - - /** Performs a software vertex morph, of the kind used for - morph animation although it can be used for other purposes. - - This function will linearly interpolate positions between two - source buffers, into a third buffer. - @param t - Parametric distance between the start and end buffer positions. - @param b1 - Vertex buffer containing VET_FLOAT3 entries for the start positions. - @param b2 - Vertex buffer containing VET_FLOAT3 entries for the end positions. - @param targetVertexData - VertexData destination; assumed to have a separate position - buffer already bound, and the number of vertices must agree with the - number in start and end - */ - static void softwareVertexMorph(float t, - const HardwareVertexBufferSharedPtr& b1, - const HardwareVertexBufferSharedPtr& b2, - VertexData* targetVertexData); - - /** Performs a software vertex pose blend, of the kind used for - morph animation although it can be used for other purposes. - - This function will apply a weighted offset to the positions in the - incoming vertex data (therefore this is a read/write operation, and - if you expect to call it more than once with the same data, then - you would be best to suppress hardware uploads of the position buffer - for the duration). - @param weight - Parametric weight to scale the offsets by. - @param vertexOffsetMap - Potentially sparse map of vertex index -> offset. - @param normalsMap - Potentially sparse map of vertex index -> normal. - @param targetVertexData - VertexData destination; assumed to have a separate position - buffer already bound, and the number of vertices must agree with the - number in start and end. - */ - static void softwareVertexPoseBlend(float weight, - const std::map& vertexOffsetMap, - const std::map& normalsMap, - VertexData* targetVertexData); - /** Gets a reference to the optional name assignments of the SubMeshes. */ - const SubMeshNameMap& getSubMeshNameMap(void) const { return mSubMeshNameMap; } - - /** Sets whether or not this Mesh should automatically build edge lists - when asked for them, or whether it should never build them if - they are not already provided. - - This allows you to create meshes which do not have edge lists calculated, - because you never want to use them. This value defaults to 'true' - for mesh formats which did not include edge data, and 'false' for - newer formats, where edge lists are expected to have been generated - in advance. - */ - void setAutoBuildEdgeLists(bool autobuild) { mAutoBuildEdgeLists = autobuild; } - /** Sets whether or not this Mesh should automatically build edge lists - when asked for them, or whether it should never build them if - they are not already provided. - */ - bool getAutoBuildEdgeLists(void) const { return mAutoBuildEdgeLists; } - - /** Gets the type of vertex animation the shared vertex data of this mesh supports. - */ - virtual VertexAnimationType getSharedVertexDataAnimationType(void) const; - - /// Returns whether animation on shared vertex data includes normals. - bool getSharedVertexDataAnimationIncludesNormals() const { return mSharedVertexDataAnimationIncludesNormals; } - - /** Creates a new Animation object for vertex animating this mesh. - @param name - The name of this animation. - @param length - The length of the animation in seconds. - */ - Animation* createAnimation(const String& name, Real length) override; - - /** Returns the named vertex Animation object. - @param name - The name of the animation. - */ - Animation* getAnimation(const String& name) const override; - - /** Internal access to the named vertex Animation object - returns null - if it does not exist. - @param name - The name of the animation. - */ - virtual Animation* _getAnimationImpl(const String& name) const; - - /** Returns whether this mesh contains the named vertex animation. */ - bool hasAnimation(const String& name) const override; - - /** Removes vertex Animation from this mesh. */ - void removeAnimation(const String& name) override; - - /** Gets the number of morph animations in this mesh. */ - unsigned short getNumAnimations(void) const override; - - /** Gets a single morph animation by index. - */ - Animation* getAnimation(unsigned short index) const override; - - /** Removes all morph Animations from this mesh. */ - virtual void removeAllAnimations(void); - /** Gets a pointer to a vertex data element based on a morph animation - track handle. - - 0 means the shared vertex data, 1+ means a submesh vertex data (index+1) - */ - VertexData* getVertexDataByTrackHandle(unsigned short handle); - - /** Internal method which, if animation types have not been determined, - scans any vertex animations and determines the type for each set of - vertex data (cannot have 2 different types). - */ - void _determineAnimationTypes(void) const; - /** Are the derived animation types out of date? */ - bool _getAnimationTypesDirty(void) const { return mAnimationTypesDirty; } - - /** Create a new Pose for this mesh or one of its submeshes. - @param target - The target geometry index; 0 is the shared Mesh geometry, 1+ is the - dedicated SubMesh geometry belonging to submesh index + 1. - @param name - Name to give the pose, which is optional. - @return - A new Pose ready for population. - */ - Pose* createPose(ushort target, const String& name = BLANKSTRING); - /** Get the number of poses */ - size_t getPoseCount(void) const { return mPoseList.size(); } - /** Retrieve an existing Pose by index */ - Pose* getPose(size_t index) const { return mPoseList.at(index); } - /** Retrieve an existing Pose by name.*/ - Pose* getPose(const String& name) const; - /** Destroy a pose by index. - @note - This will invalidate any animation tracks referring to this pose or those after it. - */ - void removePose(ushort index); - /** Destroy a pose by name. - @note - This will invalidate any animation tracks referring to this pose or those after it. - */ - void removePose(const String& name); - /** Destroy all poses. */ - void removeAllPoses(void); - - typedef VectorIterator PoseIterator; - typedef ConstVectorIterator ConstPoseIterator; - - /** Get an iterator over all the poses defined. - * @deprecated use getPoseList() */ - OGRE_DEPRECATED PoseIterator getPoseIterator(void); - /** Get an iterator over all the poses defined. - * @deprecated use getPoseList() */ - OGRE_DEPRECATED ConstPoseIterator getPoseIterator(void) const; - /** Get pose list. */ - const PoseList& getPoseList(void) const; - - /** Get LOD strategy used by this mesh. */ - const LodStrategy *getLodStrategy() const; -#if !OGRE_NO_MESHLOD - /** Set the lod strategy used by this mesh. */ - void setLodStrategy(LodStrategy *lodStrategy); -#endif - - void _convertVertexElement(VertexElementSemantic semantic, VertexElementType dstType); - - /// @copydoc UserObjectBindings - UserObjectBindings& getUserObjectBindings() { return mUserObjectBindings; } - /// @overload - const UserObjectBindings& getUserObjectBindings() const { return mUserObjectBindings; } - }; - - /** A way of recording the way each LODs is recorded this Mesh. */ - struct MeshLodUsage - { - /** User-supplied values used to determine on which distance the lod is applies. - - This is required in case the LOD strategy changes. - */ - Real userValue; - - /** Value used by to determine when this LOD applies. - - May be interpreted differently by different strategies. - Transformed from user-supplied values with LodStrategy::transformUserValue. - */ - Real value; - - - /// Only relevant if mIsLodManual is true, the name of the alternative mesh to use. - String manualName; - /// Hard link to mesh to avoid looking up each time. - mutable MeshPtr manualMesh; - /// Edge list for this LOD level (may be derived from manual mesh). - mutable EdgeData* edgeData; - - MeshLodUsage() : userValue(0.0), value(0.0), edgeData(0) {} - }; - - /** @} */ - /** @} */ - - -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif // __Mesh_H__ diff --git a/OgreMain/include/OgreMeshManager.h b/OgreMain/include/OgreMeshManager.h deleted file mode 100644 index 38a780d8058..00000000000 --- a/OgreMain/include/OgreMeshManager.h +++ /dev/null @@ -1,446 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __MeshManager_H__ -#define __MeshManager_H__ - -#include "OgrePrerequisites.h" - -#include "OgreResourceManager.h" -#include "OgreSingleton.h" -#include "OgreVector.h" -#include "OgreHardwareBuffer.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgrePatchSurface.h" -#include "OgreHeaderPrefix.h" -#include "OgrePlane.h" - -namespace Ogre { - - class MeshSerializerListener; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - /** Handles the management of mesh resources. - - This class deals with the runtime management of - mesh data; like other resource managers it handles - the creation of resources (in this case mesh data), - working within a fixed memory budget. - - Ogre loads model files from it's own proprietary - format called .mesh. This is because having a single file - format is better for runtime performance, and we also have - control over pre-processed data (such as - collision boxes, LOD reductions etc). - */ - class _OgreExport MeshManager: public ResourceManager, public Singleton - { - public: - MeshManager(); - ~MeshManager(); - - /** Initialises the manager, only to be called by OGRE internally. */ - void _initialise(void); - - /// @copydoc ResourceManager::getResourceByName - MeshPtr getByName(const String& name, const String& groupName OGRE_RESOURCE_GROUP_INIT) const; - - /// Create a new mesh - /// @copydetails ResourceManager::createResource - MeshPtr create (const String& name, const String& group, - bool isManual = false, ManualResourceLoader* loader = 0, - const NameValuePairList* createParams = 0); - - using ResourceManager::createOrRetrieve; - - /** Create a new mesh, or retrieve an existing one with the same - name if it already exists. - @copydetails ResourceManager::createResource - @param vertexBufferUsage The usage flags with which the vertex buffer(s) - will be created - @param indexBufferUsage The usage flags with which the index buffer(s) created for - this mesh will be created with. - @param vertexBufferShadowed If true, the vertex buffers will be shadowed by system memory - copies for faster read access - @param indexBufferShadowed If true, the index buffers will be shadowed by system memory - copies for faster read access - */ - ResourceCreateOrRetrieveResult createOrRetrieve( - const String& name, - const String& group, - bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams, - HardwareBuffer::Usage vertexBufferUsage, - HardwareBuffer::Usage indexBufferUsage = HBU_GPU_ONLY, - bool vertexBufferShadowed = false, bool indexBufferShadowed = false); - - /** Prepares a mesh for loading from a file. This does the IO in advance of the call to load(). - @note - If the model has already been created (prepared or loaded), the existing instance - will be returned. - @param filename The name of the .mesh file - @param groupName The name of the resource group to assign the mesh to - @param vertexBufferUsage The usage flags with which the vertex buffer(s) - will be created - @param indexBufferUsage The usage flags with which the index buffer(s) created for - this mesh will be created with. - @param vertexBufferShadowed If true, the vertex buffers will be shadowed by system memory - copies for faster read access - @param indexBufferShadowed If true, the index buffers will be shadowed by system memory - copies for faster read access - */ - MeshPtr prepare( const String& filename, const String& groupName, - HardwareBuffer::Usage vertexBufferUsage = HBU_GPU_ONLY, - HardwareBuffer::Usage indexBufferUsage = HBU_GPU_ONLY, - bool vertexBufferShadowed = false, bool indexBufferShadowed = false); - - /** Loads a mesh from a file, making it immediately available for use. - @copydetails MeshManager::prepare - */ - MeshPtr load( const String& filename, const String& groupName, - HardwareBuffer::Usage vertexBufferUsage = HBU_GPU_ONLY, - HardwareBuffer::Usage indexBufferUsage = HBU_GPU_ONLY, - bool vertexBufferShadowed = false, bool indexBufferShadowed = false); - - - /** Creates a new Mesh specifically for manual definition rather - than loading from an object file. - - Note that once you've defined your mesh, you must call Mesh::_setBounds - in order to define the bounds of your mesh. In previous - versions of OGRE could auto-compute that, but OGRE's support of - write-only vertex buffers makes this no longer appropriate. - @param name The name to give the new mesh - @param groupName The name of the resource group to assign the mesh to - @param loader ManualResourceLoader which will be called to load this mesh - when the time comes. It is recommended that you populate this field - in order that the mesh can be rebuilt should the need arise - */ - MeshPtr createManual( const String& name, const String& groupName, - ManualResourceLoader* loader = 0); - - /** Creates a basic plane, by default majoring on the x/y axes facing positive Z. - @param - name The name to give the resulting mesh - @param - groupName The name of the resource group to assign the mesh to - @param - plane The orientation of the plane and distance from the origin - @param - width The width of the plane in world coordinates - @param - height The height of the plane in world coordinates - @param - xsegments The number of segments to the plane in the x direction - @param - ysegments The number of segments to the plane in the y direction - @param - normals If true, normals are created perpendicular to the plane - @param - numTexCoordSets The number of 2D texture coordinate sets created - by default the corners - are created to be the corner of the texture. - @param - uTile The number of times the texture should be repeated in the u direction - @param - vTile The number of times the texture should be repeated in the v direction - @param - upVector The 'Up' direction of the plane texture coordinates. - @param - vertexBufferUsage The usage flag with which the vertex buffer for this plane will be created - @param - indexBufferUsage The usage flag with which the index buffer for this plane will be created - @param - vertexShadowBuffer If this flag is set to true, the vertex buffer will be created - with a system memory shadow buffer, - allowing you to read it back more efficiently than if it is in hardware - @param - indexShadowBuffer If this flag is set to true, the index buffer will be - created with a system memory shadow buffer, - allowing you to read it back more efficiently than if it is in hardware - */ - MeshPtr createPlane( - const String& name, const String& groupName, const Plane& plane, - Real width, Real height, - int xsegments = 1, int ysegments = 1, - bool normals = true, unsigned short numTexCoordSets = 1, - Real uTile = 1.0f, Real vTile = 1.0f, const Vector3& upVector = Vector3::UNIT_Y, - HardwareBuffer::Usage vertexBufferUsage = HBU_GPU_ONLY, - HardwareBuffer::Usage indexBufferUsage = HBU_GPU_ONLY, - bool vertexShadowBuffer = false, bool indexShadowBuffer = false); - - - /** Creates a plane, which because of it's texture coordinates looks like a curved - surface, useful for skies in a skybox. - @param name - The name to give the resulting mesh - @param groupName - The name of the resource group to assign the mesh to - @param plane - The orientation of the plane and distance from the origin - @param width - The width of the plane in world coordinates - @param height - The height of the plane in world coordinates - @param curvature - The curvature of the plane. Good values are - between 2 and 65. Higher values are more curved leading to - a smoother effect, lower values are less curved meaning - more distortion at the horizons but a better distance effect. - @param xsegments - The number of segments to the plane in the x direction - @param ysegments - The number of segments to the plane in the y direction - @param normals - If true, normals are created perpendicular to the plane - @param numTexCoordSets - The number of 2D texture coordinate sets created - by default the corners - are created to be the corner of the texture. - @param uTile - The number of times the texture should be repeated in the u direction - @param vTile - The number of times the texture should be repeated in the v direction - @param upVector - The 'Up' direction of the plane. - @param orientation - The orientation of the overall sphere that's used to create the illusion - @param vertexBufferUsage - The usage flag with which the vertex buffer for this plane will be created - @param indexBufferUsage - The usage flag with which the index buffer for this plane will be created - @param vertexShadowBuffer - If this flag is set to true, the vertex buffer will be created - with a system memory shadow buffer, - allowing you to read it back more efficiently than if it is in hardware - @param indexShadowBuffer - If this flag is set to true, the index buffer will be - created with a system memory shadow buffer, - allowing you to read it back more efficiently than if it is in hardware - @param ySegmentsToKeep The number of segments from the top of the dome - downwards to keep. -1 keeps all of them. This can save fillrate if - you cannot see much of the sky lower down. - */ - MeshPtr createCurvedIllusionPlane( - const String& name, const String& groupName, const Plane& plane, - Real width, Real height, Real curvature, - int xsegments = 1, int ysegments = 1, - bool normals = true, unsigned short numTexCoordSets = 1, - Real uTile = 1.0f, Real vTile = 1.0f, const Vector3& upVector = Vector3::UNIT_Y, - const Quaternion& orientation = Quaternion::IDENTITY, - HardwareBuffer::Usage vertexBufferUsage = HBU_GPU_ONLY, - HardwareBuffer::Usage indexBufferUsage = HBU_GPU_ONLY, - bool vertexShadowBuffer = false, bool indexShadowBuffer = false, - int ySegmentsToKeep = -1); - - /** Creates a genuinely curved plane, by default majoring on the x/y axes facing positive Z. - @param name - The name to give the resulting mesh - @param groupName - The name of the resource group to assign the mesh to - @param plane - The orientation of the plane and distance from the origin - @param width - The width of the plane in world coordinates - @param height - The height of the plane in world coordinates - @param bow - The amount of 'bow' in the curved plane. (Could also be considered the depth.) - @param xsegments - The number of segments to the plane in the x direction - @param ysegments - The number of segments to the plane in the y direction - @param normals - If true, normals are created perpendicular to the plane - @param numTexCoordSets - The number of 2D texture coordinate sets created - by default the corners - are created to be the corner of the texture. - @param uTile - The number of times the texture should be repeated in the u direction - @param vTile - The number of times the texture should be repeated in the v direction - @param upVector - The 'Up' direction of the plane. - @param vertexBufferUsage - The usage flag with which the vertex buffer for this plane will be created - @param indexBufferUsage - The usage flag with which the index buffer for this plane will be created - @param vertexShadowBuffer - If this flag is set to true, the vertex buffer will be created - with a system memory shadow buffer, - allowing you to read it back more efficiently than if it is in hardware - @param indexShadowBuffer - If this flag is set to true, the index buffer will be - created with a system memory shadow buffer, - allowing you to read it back more efficiently than if it is in hardware - */ - MeshPtr createCurvedPlane( - const String& name, const String& groupName, const Plane& plane, - Real width, Real height, Real bow = 0.5f, - int xsegments = 1, int ysegments = 1, - bool normals = false, unsigned short numTexCoordSets = 1, - Real uTile = 1.0f, Real vTile = 1.0f, const Vector3& upVector = Vector3::UNIT_Y, - HardwareBuffer::Usage vertexBufferUsage = HBU_GPU_ONLY, - HardwareBuffer::Usage indexBufferUsage = HBU_GPU_ONLY, - bool vertexShadowBuffer = false, bool indexShadowBuffer = false); - - /** Creates a Bezier patch based on an array of control vertices. - @param name - The name to give the newly created mesh. - @param groupName - The name of the resource group to assign the mesh to - @param controlPointBuffer - A pointer to a buffer containing the vertex data which defines control points - of the curves rather than actual vertices. Note that you are expected to provide not - just position information, but potentially normals and texture coordinates too. The - format of the buffer is defined in the VertexDeclaration parameter - @param declaration - VertexDeclaration describing the contents of the buffer. - Note this declaration must _only_ draw on buffer source 0! - @param width - Specifies the width of the patch in control points. - Note this parameter must greater than or equal to 3. - @param height - Specifies the height of the patch in control points. - Note this parameter must greater than or equal to 3. - @param uMaxSubdivisionLevel, vMaxSubdivisionLevel - If you want to manually set the top level of subdivision, - do it here, otherwise let the system decide. - @param visibleSide - Determines which side of the patch (or both) triangles are generated for. - @param vbUsage - Vertex buffer usage flags. Recommend the default since vertex buffer should be static. - @param ibUsage - Index buffer usage flags. Recommend the default since index buffer should - be dynamic to change levels but not readable. - @param vbUseShadow - Flag to determine if a shadow buffer is generated for the vertex buffer. See - HardwareBuffer for full details. - @param ibUseShadow - Flag to determine if a shadow buffer is generated for the index buffer. See - HardwareBuffer for full details. - */ - PatchMeshPtr createBezierPatch( - const String& name, const String& groupName, void* controlPointBuffer, - VertexDeclaration *declaration, size_t width, size_t height, - size_t uMaxSubdivisionLevel = PatchSurface::AUTO_LEVEL, - size_t vMaxSubdivisionLevel = PatchSurface::AUTO_LEVEL, - PatchSurface::VisibleSide visibleSide = PatchSurface::VS_FRONT, - HardwareBuffer::Usage vbUsage = HBU_GPU_ONLY, - HardwareBuffer::Usage ibUsage = HBU_CPU_TO_GPU, - bool vbUseShadow = true, bool ibUseShadow = true); - - /** Tells the mesh manager that all future meshes should prepare themselves for - shadow volumes on loading. - */ - void setPrepareAllMeshesForShadowVolumes(bool enable); - /** Retrieves whether all Meshes should prepare themselves for shadow volumes. */ - bool getPrepareAllMeshesForShadowVolumes(void); - - /// @copydoc Singleton::getSingleton() - static MeshManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static MeshManager* getSingletonPtr(void); - - /** Gets the base element type used for blend weights in vertex buffers. - - See the remarks below for SetBlendWeightsBaseElementType(). - */ - VertexElementType getBlendWeightsBaseElementType() const; - - /** sets the base element type used for blend weights in vertex buffers. - - This takes effect when meshes are loaded. Default is VET_FLOAT1. - Valid values are: - VET_UBYTE4_NORM: 8-bit blend weights. Lowest memory cost but may have precision issues. Requires SM2.0+ vertex shader. No software skinning. - VET_USHORT2_NORM: 16-bit blend weights. Requires SM2.0+ vertex shader. No software skinning. - VET_FLOAT1: 32-bit blend weights. Highest memory cost. Supports hardware and software skinning. - */ - void setBlendWeightsBaseElementType( VertexElementType vet ); - - /** Set whether to keep the bone matrices in object space or transform them to world space. - * - * Transforming to world space happens on the CPU and is the legacy behavior. Using object space bones - * is more efficient as it allows to do the transformation in the vertex shader. - */ - static void setBonesUseObjectSpace(bool enable) { mBonesUseObjectSpace = enable; } - /// whether the bone matrices are in object space or world space - static bool getBonesUseObjectSpace() { return mBonesUseObjectSpace; } - - /** Gets the factor by which the bounding box of an entity is padded. - Default is 0.01 - */ - Real getBoundsPaddingFactor(void); - - /** Sets the factor by which the bounding box of an entity is padded - */ - void setBoundsPaddingFactor(Real paddingFactor); - - /** Sets the listener used to control mesh loading through the serializer. - */ - void setListener(MeshSerializerListener *listener); - - /** Gets the listener used to control mesh loading through the serializer. - */ - MeshSerializerListener *getListener(); - - private: - - /// @copydoc ResourceManager::createImpl - Resource* createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams) override; - - std::unique_ptr mPrefabLoader; - - // element type for blend weights in vertex buffer (VET_UBYTE4, VET_USHORT1, or VET_FLOAT1) - VertexElementType mBlendWeightsBaseElementType; - - bool mPrepAllMeshesForShadowVolumes; - static bool mBonesUseObjectSpace; - - //the factor by which the bounding box of an entity is padded - Real mBoundsPaddingFactor; - - // The listener to pass to serializers - MeshSerializerListener *mListener; - - private: - std::unique_ptr mMeshCodec; - }; - - /** @} */ - /** @} */ - -} //namespace - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreMeshSerializer.h b/OgreMain/include/OgreMeshSerializer.h deleted file mode 100644 index 1d305b406e7..00000000000 --- a/OgreMain/include/OgreMeshSerializer.h +++ /dev/null @@ -1,179 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __MeshSerializer_H__ -#define __MeshSerializer_H__ - -#include "OgrePrerequisites.h" -#include "OgreSerializer.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - class MeshSerializerListener; - class MeshVersionData; - - /// Mesh compatibility versions - enum MeshVersion - { - /// Latest version available - MESH_VERSION_LATEST, - - /// OGRE version v1.10+ - MESH_VERSION_1_10, - /// OGRE version v1.8+ - MESH_VERSION_1_8, - /// OGRE version v1.7+ - MESH_VERSION_1_7, - /// OGRE version v1.4+ - MESH_VERSION_1_4, - /// OGRE version v1.0+ - MESH_VERSION_1_0, - - /// Legacy versions, DO NOT USE for writing - MESH_VERSION_LEGACY - }; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - /** Class for serialising mesh data to/from an OGRE .mesh file. - - This class allows exporters to write OGRE .mesh files easily, and allows the - OGRE engine to import .mesh files into instantiated OGRE Meshes. - Note that a .mesh file can include not only the Mesh, but also definitions of - any Materials it uses (although this is optional, the .mesh can rely on the - Material being loaded from another source, especially useful if you want to - take advantage of OGRE's advanced Material properties which may not be available - in your modeller). - @par - To export a Mesh:
    -
  1. Use the MaterialManager methods to create any dependent Material objects, if you want - to export them with the Mesh.
  2. -
  3. Create a Mesh object and populate it using it's methods.
  4. -
  5. Call the exportMesh method
  6. -
- @par - It's important to realise that this exporter uses OGRE terminology. In this context, - 'Mesh' means a top-level mesh structure which can actually contain many SubMeshes, each - of which has only one Material. Modelling packages may refer to these differently, for - example in Milkshape, it says 'Model' instead of 'Mesh' and 'Mesh' instead of 'SubMesh', - but the theory is the same. - */ - class _OgreExport MeshSerializer : public Serializer - { - public: - MeshSerializer(); - virtual ~MeshSerializer(); - - /** Exports a mesh to the file specified, in a specific version format. - - This method takes an externally created Mesh object, and exports it - to a .mesh file in the specified format version. Note that picking a - format version other that the latest will cause some information to be - lost. - @param pMesh Pointer to the Mesh to export - @param filename The destination filename - @param version Mesh version to write - @param endianMode The endian mode of the written file - */ - void exportMesh(const Mesh* pMesh, const String& filename, MeshVersion version, - Endian endianMode = ENDIAN_NATIVE); - - /// @overload - void exportMesh(const Mesh* pMesh, const String& filename, Endian endianMode = ENDIAN_NATIVE) - { - exportMesh(pMesh, filename, MESH_VERSION_LATEST, endianMode); - } - - /// @overload - void exportMesh(const MeshPtr& pMesh, const String& filename, Endian endianMode = ENDIAN_NATIVE) - { - exportMesh(pMesh.get(), filename, MESH_VERSION_LATEST, endianMode); - } - - /// @overload - void exportMesh(const Mesh* pMesh, const DataStreamPtr& stream, Endian endianMode = ENDIAN_NATIVE) - { - exportMesh(pMesh, stream, MESH_VERSION_LATEST, endianMode); - } - - /// @overload - void exportMesh(const Mesh* pMesh, DataStreamPtr stream, MeshVersion version, - Endian endianMode = ENDIAN_NATIVE); - - /** Imports Mesh and (optionally) Material data from a .mesh file DataStream. - - This method imports data from a DataStream opened from a .mesh file and places it's - contents into the Mesh object which is passed in. - @param stream The DataStream holding the .mesh data. Must be initialised (pos at the start of the buffer). - @param pDest Pointer to the Mesh object which will receive the data. Should be blank already. - */ - void importMesh(const DataStreamPtr& stream, Mesh* pDest); - - /// Sets the listener for this serializer - void setListener(MeshSerializerListener *listener); - /// Returns the current listener - MeshSerializerListener *getListener(); - - private: - typedef std::vector MeshVersionDataList; - MeshVersionDataList mVersionData; - - MeshSerializerListener *mListener; - - }; - - /** - - This class allows users to hook into the mesh loading process and - modify references within the mesh as they are loading. Material and - skeletal references can be processed using this interface which allows - finer control over resources. - */ - class MeshSerializerListener - { - public: - virtual ~MeshSerializerListener() {} - /// Called to override the loading of the given named material - virtual void processMaterialName(Mesh *mesh, String *name) = 0; - /// Called to override the reference to a skeleton - virtual void processSkeletonName(Mesh *mesh, String *name) = 0; - /// Allows to do changes on mesh after it's completely loaded. For example you can generate LOD levels here. - virtual void processMeshCompleted(Mesh *mesh) = 0; - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreMovableObject.h b/OgreMain/include/OgreMovableObject.h deleted file mode 100644 index 9030ebc6afb..00000000000 --- a/OgreMain/include/OgreMovableObject.h +++ /dev/null @@ -1,642 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __MovableObject_H__ -#define __MovableObject_H__ - -// Precompiler options -#include "OgrePrerequisites.h" -#include "OgreAxisAlignedBox.h" -#include "OgreSphere.h" -#include "OgreShadowCaster.h" -#include "OgreAnimable.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - // Forward declaration - class MovableObjectFactory; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** Abstract class defining a movable object in a scene. - - Instances of this class are discrete, relatively small, movable objects - which are attached to SceneNode objects to define their position. - */ - class _OgreExport MovableObject : public ShadowCaster, public AnimableObject, public MovableAlloc - { - public: - /** Listener which gets called back on MovableObject events. - */ - class _OgreExport Listener - { - public: - Listener(void) {} - virtual ~Listener() {} - /** MovableObject is being destroyed */ - virtual void objectDestroyed(MovableObject*) {} - /** MovableObject has been attached to a node */ - virtual void objectAttached(MovableObject*) {} - /** MovableObject has been detached from a node */ - virtual void objectDetached(MovableObject*) {} - /** MovableObject has been moved */ - virtual void objectMoved(MovableObject*) {} - /** Called when the movable object of the camera to be used for rendering. - @return - true if allows queue for rendering, false otherwise. - */ - virtual bool objectRendering(const MovableObject*, const Camera*) { return true; } - /** Called when the movable object needs to query a light list. - - If you want to customize light finding for this object, you should override - this method and hook into MovableObject via MovableObject::setListener. - Be aware that the default method caches results within a frame to - prevent unnecessary recalculation, so if you override this you - should provide your own caching to maintain performance. - @note - If you use texture shadows, there is an additional restriction - - since the lights which should have shadow textures rendered for - them are determined based on the entire frustum, and not per-object, - it is important that the lights returned at the start of this - list (up to the number of shadow textures available) are the same - lights that were used to generate the shadow textures, - and they are in the same order (particularly for additive effects). - @note - This method will not be called for additive stencil shadows since the - light list cannot be varied per object with this technique. - @return - A pointer to a light list if you populated the light list yourself, or - NULL to fall back on the default finding process. - */ - virtual const LightList* objectQueryLights(const MovableObject*) { return 0; } - }; - - protected: - /// Name of this object - String mName; - /// Creator of this object (if created by a factory) - MovableObjectFactory* mCreator; - /// SceneManager holding this object (if applicable) - SceneManager* mManager; - /// node to which this object is attached - Node* mParentNode; - /// MovableObject listener - only one allowed (no list) for size & performance reasons. */ - Listener* mListener; - bool mParentIsTagPoint : 1; - /// Is this object visible? - bool mVisible : 1; - /// Is debug display enabled? - bool mDebugDisplay : 1; - /// Hidden because of distance? - bool mBeyondFarDistance : 1; - /// Does this object cast shadows? - bool mCastShadows : 1; - /// Flags whether the RenderQueue's default should be used. - bool mRenderQueueIDSet : 1; - /// Flags whether the RenderQueue's default should be used. - bool mRenderQueuePrioritySet : 1; - /// Does rendering this object disabled by listener? - bool mRenderingDisabled : 1; - /// The render queue to use when rendering this object - uint8 mRenderQueueID; - /// The render queue group to use when rendering this object - ushort mRenderQueuePriority; - /// Upper distance to still render - Real mUpperDistance; - Real mSquaredUpperDistance; - /// Minimum pixel size to still render - Real mMinPixelSize; - /// User objects binding. - UserObjectBindings mUserObjectBindings; - /// Flags determining whether this object is included / excluded from scene queries - uint32 mQueryFlags; - /// Flags determining whether this object is visible (compared to SceneManager mask) - uint32 mVisibilityFlags; - /// Cached world AABB of this object - mutable AxisAlignedBox mWorldAABB; - // Cached world bounding sphere - mutable Sphere mWorldBoundingSphere; - /// World space AABB of this object's dark cap - mutable AxisAlignedBox mWorldDarkCapBounds; - /// List of lights for this object - mutable LightList mLightList; - /// The last frame that this light list was updated in - mutable ulong mLightListUpdated; - /// the light mask defined for this movable. This will be taken into consideration when deciding which light should affect this movable - uint32 mLightMask; - - // Static members - /// Default query flags - static uint32 msDefaultQueryFlags; - /// Default visibility flags - static uint32 msDefaultVisibilityFlags; - - - - public: - /// Constructor - MovableObject(); - - /// Named constructor - MovableObject(const String& name); - /** Virtual destructor - read Scott Meyers if you don't know why this is needed. - */ - virtual ~MovableObject(); - - /** Notify the object of it's creator (internal use only) */ - virtual void _notifyCreator(MovableObjectFactory* fact) { mCreator = fact; } - /** Get the creator of this object, if any (internal use only) */ - MovableObjectFactory* _getCreator(void) const { return mCreator; } - /** Notify the object of it's manager (internal use only) */ - virtual void _notifyManager(SceneManager* man) { mManager = man; } - /** Get the manager of this object, if any (internal use only) */ - SceneManager* _getManager(void) const { return mManager; } - - /** Notifies the movable object that hardware resources were lost - - Called automatically by RenderSystem if hardware resources - were lost and can not be restored using some internal mechanism. - Among affected resources are nested shadow renderables, ManualObjects, etc. - */ - virtual void _releaseManualHardwareResources() {} - - /** Notifies the movable object that hardware resources should be restored - - Called automatically by RenderSystem if hardware resources - were lost and can not be restored using some internal mechanism. - Among affected resources are nested shadow renderables, ManualObjects, etc. - */ - virtual void _restoreManualHardwareResources() {} - - /** Returns the name of this object. */ - const String& getName(void) const { return mName; } - - /** Returns the type name of this object. */ - virtual const String& getMovableType(void) const = 0; - - /** Returns the node to which this object is attached. - - A MovableObject may be attached to either a SceneNode or to a TagPoint, - the latter case if it's attached to a bone on an animated entity. - Both are Node subclasses so this method will return either. - */ - Node* getParentNode(void) const { return mParentNode; } - - /** Returns the scene node to which this object is attached. - - A MovableObject may be attached to either a SceneNode or to a TagPoint, - the latter case if it's attached to a bone on an animated entity. - This method will return the scene node of the parent entity - if the latter is true. - */ - SceneNode* getParentSceneNode(void) const; - - /// Gets whether the parent node is a TagPoint (or a SceneNode) - bool isParentTagPoint() const { return mParentIsTagPoint; } - - /** Internal method called to notify the object that it has been attached to a node. - */ - virtual void _notifyAttached(Node* parent, bool isTagPoint = false); - - /** Returns true if this object is attached to a SceneNode or TagPoint. */ - bool isAttached(void) const { return (mParentNode != NULL); } - - /** Detaches an object from a parent SceneNode or TagPoint, if attached. */ - void detachFromParent(void); - - /** Returns true if this object is attached to a SceneNode or TagPoint, - and this SceneNode / TagPoint is currently in an active part of the - scene graph. */ - virtual bool isInScene(void) const; - - /** Internal method called to notify the object that it has been moved. - */ - virtual void _notifyMoved(void); - - /** Internal method to notify the object of the camera to be used for the next rendering operation. - - Certain objects may want to do specific processing based on the camera position. This method notifies - them in case they wish to do this. - */ - virtual void _notifyCurrentCamera(Camera* cam); - - /** Retrieves the local axis-aligned bounding box for this object. - - This bounding box is in local coordinates. - */ - virtual const AxisAlignedBox& getBoundingBox(void) const = 0; - - /** Retrieves the radius of the origin-centered bounding sphere - for this object. - */ - virtual Real getBoundingRadius(void) const = 0; - - /// as getBoundingRadius, but with scaling applied - Real getBoundingRadiusScaled() const; - - /** Retrieves the axis-aligned bounding box for this object in world coordinates. */ - const AxisAlignedBox& getWorldBoundingBox(bool derive = false) const override; - /** Retrieves the worldspace bounding sphere for this object. */ - virtual const Sphere& getWorldBoundingSphere(bool derive = false) const; - /** Internal method by which the movable object must add Renderable subclass instances to the rendering queue. - - The engine will call this method when this object is to be rendered. The object must then create one or more - Renderable subclass instances which it places on the passed in Queue for rendering. - */ - virtual void _updateRenderQueue(RenderQueue* queue) = 0; - - /** Tells this object whether to be visible or not, if it has a renderable component. - @note An alternative approach of making an object invisible is to detach it - from it's SceneNode, or to remove the SceneNode entirely. - Detaching a node means that structurally the scene graph changes. - Once this change has taken place, the objects / nodes that have been - removed have less overhead to the visibility detection pass than simply - making the object invisible, so if you do this and leave the objects - out of the tree for a long time, it's faster. However, the act of - detaching / reattaching nodes is in itself more expensive than - setting an object visibility flag, since in the latter case - structural changes are not made. Therefore, small or frequent visibility - changes are best done using this method; large or more longer term - changes are best done by detaching. - */ - void setVisible(bool visible) { mVisible = visible; } - - /** Gets this object whether to be visible or not, if it has a renderable component. - - Returns the value set by MovableObject::setVisible only. - */ - bool getVisible(void) const { return mVisible; } - - /** Returns whether or not this object is supposed to be visible or not. - - Takes into account both upper rendering distance and visible flag. - */ - virtual bool isVisible(void) const; - - /** Sets the distance at which the object is no longer rendered. - @note Camera::setUseRenderingDistance() needs to be called for this parameter to be used. - @param dist Distance beyond which the object will not be rendered - (the default is 0, which means objects are always rendered). - */ - void setRenderingDistance(Real dist) { - mUpperDistance = dist; - mSquaredUpperDistance = mUpperDistance * mUpperDistance; - } - - /** Gets the distance at which batches are no longer rendered. */ - Real getRenderingDistance(void) const { return mUpperDistance; } - - /** Sets the minimum pixel size an object needs to be in both screen axes in order to be rendered - @note Camera::setUseMinPixelSize() needs to be called for this parameter to be used. - @param pixelSize Number of minimum pixels - (the default is 0, which means objects are always rendered). - */ - void setRenderingMinPixelSize(Real pixelSize) { - mMinPixelSize = pixelSize; - } - - /** Returns the minimum pixel size an object needs to be in both screen axes in order to be rendered - */ - Real getRenderingMinPixelSize() const { - return mMinPixelSize; - } - - /** @deprecated use UserObjectBindings::setUserAny via getUserObjectBindings() instead. - */ - OGRE_DEPRECATED void setUserAny(const Any& anything) { getUserObjectBindings().setUserAny(anything); } - - /** @deprecated use UserObjectBindings::getUserAny via getUserObjectBindings() instead. - */ - OGRE_DEPRECATED const Any& getUserAny(void) const { return getUserObjectBindings().getUserAny(); } - - /// @copydoc UserObjectBindings - UserObjectBindings& getUserObjectBindings() { return mUserObjectBindings; } - - /// @overload - const UserObjectBindings& getUserObjectBindings() const { return mUserObjectBindings; } - - /** Sets the render queue group this entity will be rendered through. - - Render queues are grouped to allow you to more tightly control the ordering - of rendered objects. If you do not call this method, all Entity objects default - to the default queue (RenderQueue::getDefaultQueueGroup), which is fine for most objects. You may want to alter this - if you want this entity to always appear in front of other objects, e.g. for - a 3D menu system or such. - @par - See RenderQueue for more details. - @param queueID Enumerated value of the queue group to use. See the - enum RenderQueueGroupID for what kind of values can be used here. - */ - virtual void setRenderQueueGroup(uint8 queueID); - - /** Sets the render queue group and group priority this entity will be rendered through. - - Render queues are grouped to allow you to more tightly control the ordering - of rendered objects. Within a single render group there another type of grouping - called priority which allows further control. If you do not call this method, - all Entity objects default to the default queue and priority - (RenderQueue::getDefaultQueueGroup, RenderQueue::getDefaultRenderablePriority), - which is fine for most objects. You may want to alter this if you want this entity - to always appear in front of other objects, e.g. for a 3D menu system or such. - @par - See RenderQueue for more details. - @param queueID Enumerated value of the queue group to use. See the - enum RenderQueueGroupID for what kind of values can be used here. - @param priority The priority within a group to use. - */ - virtual void setRenderQueueGroupAndPriority(uint8 queueID, ushort priority); - - /** Gets the queue group for this entity - @see setRenderQueueGroup - */ - uint8 getRenderQueueGroup(void) const { return mRenderQueueID; } - - /// Return the full transformation of the parent sceneNode or the attachingPoint node - virtual const Affine3& _getParentNodeFullTransform(void) const; - - /** Sets the query flags for this object. - - When performing a scene query, this object will be included or excluded according - to flags on the object and flags on the query. This is a bitwise value, so only when - a bit on these flags is set, will it be included in a query asking for that flag. The - meaning of the bits is application-specific. - */ - void setQueryFlags(uint32 flags) { mQueryFlags = flags; } - - /** As setQueryFlags, except the flags passed as parameters are appended to the - existing flags on this object. */ - void addQueryFlags(uint32 flags) { mQueryFlags |= flags; } - - /** As setQueryFlags, except the flags passed as parameters are removed from the - existing flags on this object. */ - void removeQueryFlags(uint32 flags) { mQueryFlags &= ~flags; } - - /// Returns the query flags relevant for this object - virtual uint32 getQueryFlags(void) const { return mQueryFlags; } - - /** Set the default query flags for all future MovableObject instances. - */ - static void setDefaultQueryFlags(uint32 flags) { msDefaultQueryFlags = flags; } - - /** Get the default query flags for all future MovableObject instances. - */ - static uint32 getDefaultQueryFlags() { return msDefaultQueryFlags; } - - - /** Sets the visibility flags for this object. - - As well as a simple true/false value for visibility (as seen in setVisible), - you can also set visibility flags which when 'and'ed with the SceneManager's - visibility mask can also make an object invisible. - */ - void setVisibilityFlags(uint32 flags) { mVisibilityFlags = flags; } - - /** As setVisibilityFlags, except the flags passed as parameters are appended to the - existing flags on this object. */ - void addVisibilityFlags(uint32 flags) { mVisibilityFlags |= flags; } - - /** As setVisibilityFlags, except the flags passed as parameters are removed from the - existing flags on this object. */ - void removeVisibilityFlags(uint32 flags) { mVisibilityFlags &= ~flags; } - - /// Returns the visibility flags relevant for this object - virtual uint32 getVisibilityFlags(void) const { return mVisibilityFlags; } - - /** Set the default visibility flags for all future MovableObject instances. - */ - static void setDefaultVisibilityFlags(uint32 flags) { msDefaultVisibilityFlags = flags; } - - /** Get the default visibility flags for all future MovableObject instances. - */ - static uint32 getDefaultVisibilityFlags() { return msDefaultVisibilityFlags; } - - /** Sets a listener for this object. - - Note for size and performance reasons only one listener per object - is allowed. - */ - void setListener(Listener* listener) { mListener = listener; } - - /** Gets the current listener for this object. - */ - Listener* getListener(void) const { return mListener; } - - /** Gets a list of lights, ordered relative to how close they are to this movable object. - - By default, this method gives the listener a chance to populate light list first, - if there is no listener or Listener::objectQueryLights returns NULL, it'll - query the light list from parent entity if it is present, or returns - SceneNode::findLights if it has parent scene node, otherwise it just returns - an empty list. - @par - The object internally caches the light list, so it will recalculate - it only when object is moved, or lights that affect the frustum have - been changed (@see SceneManager::_getLightsDirtyCounter), - but if listener exists, it will be called each time, so the listener - should implement their own cache mechanism to optimise performance. - @par - This method can be useful when implementing Renderable::getLights in case - the renderable is a part of the movable. - @return The list of lights use to lighting this object. - */ - const LightList& queryLights(void) const; - - /** Get a bitwise mask which will filter the lights affecting this object - - By default, this mask is fully set meaning all lights will affect this object - */ - uint32 getLightMask()const { return mLightMask; } - /** Set a bitwise mask which will filter the lights affecting this object - - This mask will be compared against the mask held against Light to determine - if a light should affect a given object. - By default, this mask is fully set meaning all lights will affect this object - */ - void setLightMask(uint32 lightMask); - - /** Returns a pointer to the current list of lights for this object. - - You should not modify this list outside of MovableObject::Listener::objectQueryLights - (say if you want to use it to implement this method, and use the pointer - as a return value) and for reading it's only accurate as at the last frame. - */ - LightList* _getLightList() { return &mLightList; } - - /// Returns details of the edges which might be used to determine a silhouette - EdgeData* getEdgeList(void) override { return NULL; } - /// Define a default implementation of method from ShadowCaster which implements no shadows - const ShadowRenderableList& getShadowVolumeRenderableList( - const Light* light, const HardwareIndexBufferPtr& indexBuffer, - size_t& indexBufferUsedSize, float extrusionDist, int flags = 0) override; - - const AxisAlignedBox& getLightCapBounds(void) const override; - const AxisAlignedBox& getDarkCapBounds(const Light& light, Real dirLightExtrusionDist) const override; - /** Sets whether or not this object will cast shadows. - - This setting simply allows you to turn on/off shadows for a given object. - An object will not cast shadows unless the scene supports it in any case - (see SceneManager::setShadowTechnique), and also the material which is - in use must also have shadow casting enabled. By default all entities cast - shadows. If, however, for some reason you wish to disable this for a single - object then you can do so using this method. - @note This method normally refers to objects which block the light, but - since Light is also a subclass of MovableObject, in that context it means - whether the light causes shadows itself. - */ - void setCastShadows(bool enabled) { mCastShadows = enabled; } - /** Returns whether shadow casting is enabled for this object. */ - bool getCastShadows(void) const override { return mCastShadows; } - /** Returns whether the Material of any Renderable that this MovableObject will add to - the render queue will receive shadows. - */ - bool getReceivesShadows(); - - /** Get the distance to extrude for a point/spot light */ - Real getPointExtrusionDistance(const Light* l) const override; - /** Get the 'type flags' for this MovableObject. - - A type flag identifies the type of the MovableObject as a bitpattern. - This is used for categorical inclusion / exclusion in SceneQuery - objects. By default, this method returns all ones for objects not - created by a MovableObjectFactory (hence always including them); - otherwise it returns the value assigned to the MovableObjectFactory. - Custom objects which don't use MovableObjectFactory will need to - override this if they want to be included in queries. - */ - virtual uint32 getTypeFlags(void) const; - - /** Method to allow a caller to abstractly iterate over the Renderable - instances that this MovableObject will add to the render queue when - asked, if any. - @param visitor Pointer to a class implementing the Renderable::Visitor - interface which will be called back for each Renderable which will - be queued. Bear in mind that the state of the Renderable instances - may not be finalised depending on when you call this. - @param debugRenderables If false, only regular renderables will be visited - (those for normal display). If true, debug renderables will be - included too. - */ - virtual void visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables = false) = 0; - - /** Sets whether or not the debug display of this object is enabled. - - Some objects aren't visible themselves but it can be useful to display - a debug representation of them. Or, objects may have an additional - debug display on top of their regular display. This option enables / - disables that debug display. Objects that are not visible never display - debug geometry regardless of this setting. - */ - void setDebugDisplayEnabled(bool enabled) { mDebugDisplay = enabled; } - /// Gets whether debug display of this object is enabled. - bool isDebugDisplayEnabled(void) const { return mDebugDisplay; } - - - - - - }; - - /** Interface definition for a factory class which produces a certain - kind of MovableObject, and can be registered with Root in order - to allow all clients to produce new instances of this object, integrated - with the standard Ogre processing. - */ - class _OgreExport MovableObjectFactory : public MovableAlloc - { - private: - /// Type flag, allocated if requested - uint32 mTypeFlag; - - /// Internal implementation of create method - must be overridden - virtual MovableObject* createInstanceImpl( - const String& name, const NameValuePairList* params = 0) = 0; - public: - MovableObjectFactory() : mTypeFlag(0xFFFFFFFF) {} - virtual ~MovableObjectFactory() {} - /// Get the type of the object to be created - virtual const String& getType(void) const = 0; - - /** Create a new instance of the object. - @param name The name of the new object - @param manager The SceneManager instance that will be holding the - instance once created. - @param params Name/value pair list of additional parameters required to - construct the object (defined per subtype). Optional. - */ - MovableObject* createInstance( - const String& name, SceneManager* manager, - const NameValuePairList* params = 0); - /** Destroy an instance of the object */ - virtual void destroyInstance(MovableObject* obj) { delete obj; } - - /** Does this factory require the allocation of a 'type flag', used to - selectively include / exclude this type from scene queries? - - The default implementation here is to return 'false', ie not to - request a unique type mask from Root. For objects that - never need to be excluded in SceneQuery results, that's fine, since - the default implementation of MovableObject::getTypeFlags is to return - all ones, hence matching any query type mask. However, if you want the - objects created by this factory to be filterable by queries using a - broad type, you have to give them a (preferably unique) type mask - - and given that you don't know what other MovableObject types are - registered, Root will allocate you one. - */ - virtual bool requestTypeFlags(void) const { return false; } - /** Notify this factory of the type mask to apply. - - This should normally only be called by Root in response to - a 'true' result from requestTypeMask. However, you can actually use - it yourself if you're careful; for example to assign the same mask - to a number of different types of object, should you always wish them - to be treated the same in queries. - */ - void _notifyTypeFlags(uint32 flag) { mTypeFlag = flag; } - - /** Gets the type flag for this factory. - - A type flag is like a query flag, except that it applies to all instances - of a certain type of object. - */ - uint32 getTypeFlags(void) const { return mTypeFlag; } - - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreMovablePlane.h b/OgreMain/include/OgreMovablePlane.h deleted file mode 100644 index 01c970a57b4..00000000000 --- a/OgreMain/include/OgreMovablePlane.h +++ /dev/null @@ -1,99 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __MovablePlane_H__ -#define __MovablePlane_H__ - -#include "OgrePrerequisites.h" - -#include "OgrePlane.h" -#include "OgreMovableObject.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** Definition of a Plane that may be attached to a node, and the derived - details of it retrieved simply. - - This plane is not here for rendering purposes, it's to allow you to attach - planes to the scene in order to have them move and follow nodes on their - own, which is useful if you're using the plane for some kind of calculation, - e.g. reflection. - */ - class _OgreExport MovablePlane : public Plane, public MovableObject - { - private: - mutable Plane mDerivedPlane; - mutable Vector3 mLastTranslate; - mutable Quaternion mLastRotate; - mutable bool mDirty; - public: - - MovablePlane(const String& name); - MovablePlane (const Plane& rhs); - /** Construct a plane through a normal, and a distance to move the plane along the normal.*/ - MovablePlane (const Vector3& rkNormal, Real fConstant); - MovablePlane (const Vector3& rkNormal, const Vector3& rkPoint); - MovablePlane (const Vector3& rkPoint0, const Vector3& rkPoint1, - const Vector3& rkPoint2); - ~MovablePlane() {} - /// Overridden from MovableObject - void _notifyCurrentCamera(Camera*) override { /* don't care */ } - /// Overridden from MovableObject - const AxisAlignedBox& getBoundingBox(void) const override { return AxisAlignedBox::BOX_NULL; } - /// Overridden from MovableObject - Real getBoundingRadius(void) const override { return 0.0f; } - /// Overridden from MovableObject - void _updateRenderQueue(RenderQueue*) override { /* do nothing */} - /// Overridden from MovableObject - const String& getMovableType(void) const override; - /// Get the derived plane as transformed by its parent node. - const Plane& _getDerivedPlane(void) const; - /// @copydoc MovableObject::visitRenderables - void visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables = false) override - { - /* do nothing */ - (void)visitor; - (void)debugRenderables; - } - - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreMurmurHash3.h b/OgreMain/include/OgreMurmurHash3.h deleted file mode 100644 index b86e7444ee7..00000000000 --- a/OgreMain/include/OgreMurmurHash3.h +++ /dev/null @@ -1,36 +0,0 @@ -//----------------------------------------------------------------------------- -// MurmurHash3 was written by Austin Appleby, and is placed in the public -// domain. The author hereby disclaims copyright to this source code. - -#ifndef _MURMURHASH3_H_ -#define _MURMURHASH3_H_ - -//----------------------------------------------------------------------------- -// Platform-specific functions and macros -#include "OgrePlatform.h" - -#include -#include - -//----------------------------------------------------------------------------- - -namespace Ogre -{ - void _OgreExport MurmurHash3_x86_32 ( const void * key, size_t len, uint32_t seed, void * out ); - - void _OgreExport MurmurHash3_x86_128 ( const void * key, size_t len, uint32_t seed, void * out ); - - void _OgreExport MurmurHash3_x64_128 ( const void * key, size_t len, uint32_t seed, void * out ); - - inline void MurmurHash3_128( const void * key, size_t len, uint32_t seed, void * out ) { -#if OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_64 - MurmurHash3_x64_128(key, len, seed, out); -#else - MurmurHash3_x86_128(key, len, seed, out); -#endif - } -} - -//----------------------------------------------------------------------------- - -#endif // _MURMURHASH3_H_ diff --git a/OgreMain/include/OgreNameGenerator.h b/OgreMain/include/OgreNameGenerator.h deleted file mode 100644 index 9bb784f251a..00000000000 --- a/OgreMain/include/OgreNameGenerator.h +++ /dev/null @@ -1,96 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __NameGenerator_H__ -#define __NameGenerator_H__ - -#include "OgreString.h" -#include -#include "OgreHeaderPrefix.h" - -#include "Threading/OgreThreadHeaders.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - - /// Utility class to generate a sequentially numbered series of names - class _OgreExport NameGenerator - { - private: - String mPrefix; - unsigned long long int mNext; - OGRE_AUTO_MUTEX; - public: - NameGenerator(const NameGenerator& rhs) - : mPrefix(rhs.mPrefix), mNext(rhs.mNext) {} - - NameGenerator(const String& prefix) : mPrefix(prefix), mNext(1) {} - - /// Generate a new name - String generate() - { - OGRE_LOCK_AUTO_MUTEX; - StringStream s; - s << mPrefix << mNext++; - return s.str(); - } - - /// Reset the internal counter - void reset() - { - OGRE_LOCK_AUTO_MUTEX; - mNext = 1ULL; - } - - /// Manually set the internal counter (use caution) - void setNext(unsigned long long int val) - { - OGRE_LOCK_AUTO_MUTEX; - mNext = val; - } - - /// Get the internal counter - unsigned long long int getNext() const - { - // lock even on get because 64-bit may not be atomic read - OGRE_LOCK_AUTO_MUTEX; - return mNext; - } - }; - - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreNode.h b/OgreMain/include/OgreNode.h deleted file mode 100644 index fd9e39c3dc1..00000000000 --- a/OgreMain/include/OgreNode.h +++ /dev/null @@ -1,671 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _Node_H__ -#define _Node_H__ - -#include "OgrePrerequisites.h" - -#include "OgreMatrix4.h" -#include "OgreUserObjectBindings.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - template class VectorIterator; - template class ConstVectorIterator; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** Class representing a general-purpose node an articulated scene graph. - - A node in the scene graph is a node in a structured tree. A node contains - information about the transformation which will apply to - it and all of it's children. Child nodes can have transforms of their own, which - are combined with their parent's transformations. - @par - This is an abstract class - concrete classes are based on this for specific purposes, - e.g. SceneNode, Bone - */ - class _OgreExport Node : public NodeAlloc - { - public: - /** Enumeration denoting the spaces which a transform can be relative to. - */ - enum TransformSpace - { - /// Transform is relative to the local space - TS_LOCAL, - /// Transform is relative to the space of the parent node - TS_PARENT, - /// Transform is relative to world space - TS_WORLD - }; - typedef std::vector ChildNodeMap; - typedef VectorIterator ChildNodeIterator; - typedef ConstVectorIterator ConstChildNodeIterator; - - /** Listener which gets called back on Node events. - */ - class _OgreExport Listener - { - public: - Listener() {} - virtual ~Listener() {} - /** Called when a node gets updated. - - Note that this happens when the node's derived update happens, - not every time a method altering it's state occurs. There may - be several state-changing calls but only one of these calls, - when the node graph is fully updated. - */ - virtual void nodeUpdated(const Node*) {} - /** Node is being destroyed */ - virtual void nodeDestroyed(const Node*) {} - /** Node has been attached to a parent */ - virtual void nodeAttached(const Node*) {} - /** Node has been detached from a parent */ - virtual void nodeDetached(const Node*) {} - }; - - protected: - /// Pointer to parent node - Node* mParent; - /// Collection of pointers to direct children - ChildNodeMap mChildren; - - typedef std::set ChildUpdateSet; - /// List of children which need updating, used if self is not out of date but children are - ChildUpdateSet mChildrenToUpdate; - /// Friendly name of this node - String mName; - - /// Flag to indicate own transform from parent is out of date - mutable bool mNeedParentUpdate : 1; - /// Flag indicating that all children need to be updated - bool mNeedChildUpdate : 1; - /// Flag indicating that parent has been notified about update request - bool mParentNotified : 1; - /// Flag indicating that the node has been queued for update - bool mQueuedForUpdate : 1; - /// Stores whether this node inherits orientation from it's parent - bool mInheritOrientation : 1; - /// Stores whether this node inherits scale from it's parent - bool mInheritScale : 1; - mutable bool mCachedTransformOutOfDate : 1; - - /// Stores the orientation of the node relative to it's parent. - Quaternion mOrientation; - /// Stores the position/translation of the node relative to its parent. - Vector3 mPosition; - /// Stores the scaling factor applied to this node - Vector3 mScale; - - /// Cached derived transform as a 4x4 matrix - mutable Affine3 mCachedTransform; - - /// Only available internally - notification of parent. - virtual void setParent(Node* parent); - - /** Cached combined orientation. - @par - This member is the orientation derived by combining the - local transformations and those of it's parents. - This is updated when _updateFromParent is called by the - SceneManager or the nodes parent. - */ - mutable Quaternion mDerivedOrientation; - - /** Cached combined position. - @par - This member is the position derived by combining the - local transformations and those of it's parents. - This is updated when _updateFromParent is called by the - SceneManager or the nodes parent. - */ - mutable Vector3 mDerivedPosition; - - /** Cached combined scale. - @par - This member is the position derived by combining the - local transformations and those of it's parents. - This is updated when _updateFromParent is called by the - SceneManager or the nodes parent. - */ - mutable Vector3 mDerivedScale; - - /** Triggers the node to update it's combined transforms. - @par - This method is called internally by Ogre to ask the node - to update it's complete transformation based on it's parents - derived transform. - */ - void _updateFromParent(void) const; - - /** Class-specific implementation of _updateFromParent. - - Splitting the implementation of the update away from the update call - itself allows the detail to be overridden without disrupting the - general sequence of updateFromParent (e.g. raising events) - */ - virtual void updateFromParentImpl(void) const; - private: - /// The position to use as a base for keyframe animation - Vector3 mInitialPosition; - /// The orientation to use as a base for keyframe animation - Quaternion mInitialOrientation; - /// The scale to use as a base for keyframe animation - Vector3 mInitialScale; - - /** Node listener - only one allowed (no list) for size & performance reasons. */ - Listener* mListener; - - /// User objects binding. - UserObjectBindings mUserObjectBindings; - - typedef std::vector QueuedUpdates; - static QueuedUpdates msQueuedUpdates; - - /** Internal method for creating a new child node - must be overridden per subclass. */ - virtual Node* createChildImpl(void) = 0; - - /** Internal method for creating a new child node - must be overridden per subclass. */ - virtual Node* createChildImpl(const String& name) = 0; - public: - /// Constructor, should only be called by parent, not directly. - Node(); - /** Constructor, should only be called by parent, not directly. - - Assigned a name. - */ - Node(const String& name); - - virtual ~Node(); - - /** Returns the name of the node. */ - const String& getName(void) const { return mName; } - - /** Gets this node's parent (NULL if this is the root). - */ - Node* getParent(void) const { return mParent; } - - /** Returns a quaternion representing the nodes orientation. - */ - const Quaternion & getOrientation() const { return mOrientation; } - - /** Sets the orientation of this node via a quaternion. - - Orientations, unlike other transforms, are not always inherited by child nodes. - Whether or not orientations affect the orientation of the child nodes depends on - the setInheritOrientation option of the child. In some cases you want a orientating - of a parent node to apply to a child node (e.g. where the child node is a part of - the same object, so you want it to be the same relative orientation based on the - parent's orientation), but not in other cases (e.g. where the child node is just - for positioning another object, you want it to maintain it's own orientation). - The default is to inherit as with other transforms. - @par - Note that rotations are oriented around the node's origin. - */ - void setOrientation( const Quaternion& q ); - - /// @overload - void setOrientation( Real w, Real x, Real y, Real z); - - /** Resets the nodes orientation (local axes as world axes, no rotation). - - Orientations, unlike other transforms, are not always inherited by child nodes. - Whether or not orientations affect the orientation of the child nodes depends on - the setInheritOrientation option of the child. In some cases you want a orientating - of a parent node to apply to a child node (e.g. where the child node is a part of - the same object, so you want it to be the same relative orientation based on the - parent's orientation), but not in other cases (e.g. where the child node is just - for positioning another object, you want it to maintain it's own orientation). - The default is to inherit as with other transforms. - @par - Note that rotations are oriented around the node's origin. - */ - void resetOrientation(void); - - /** Sets the position of the node relative to it's parent. - */ - void setPosition(const Vector3& pos); - - /// @overload - void setPosition(Real x, Real y, Real z) { setPosition(Vector3(x, y, z)); } - - /** Gets the position of the node relative to it's parent. - */ - const Vector3 & getPosition(void) const { return mPosition; } - - /** Sets the scaling factor applied to this node. - - Scaling factors, unlike other transforms, are not always inherited by child nodes. - Whether or not scalings affect the size of the child nodes depends on the setInheritScale - option of the child. In some cases you want a scaling factor of a parent node to apply to - a child node (e.g. where the child node is a part of the same object, so you want it to be - the same relative size based on the parent's size), but not in other cases (e.g. where the - child node is just for positioning another object, you want it to maintain it's own size). - The default is to inherit as with other transforms. - @par - Note that like rotations, scalings are oriented around the node's origin. - */ - void setScale(const Vector3& scale); - - /// @overload - void setScale(Real x, Real y, Real z) { setScale(Vector3(x, y, z)); } - - /** Gets the scaling factor of this node. - */ - const Vector3& getScale(void) const { return mScale; } - - /** Tells the node whether it should inherit orientation from it's parent node. - - Orientations, unlike other transforms, are not always inherited by child nodes. - Whether or not orientations affect the orientation of the child nodes depends on - the setInheritOrientation option of the child. In some cases you want a orientating - of a parent node to apply to a child node (e.g. where the child node is a part of - the same object, so you want it to be the same relative orientation based on the - parent's orientation), but not in other cases (e.g. where the child node is just - for positioning another object, you want it to maintain it's own orientation). - The default is to inherit as with other transforms. - @param inherit If true, this node's orientation will be affected by its parent's orientation. - If false, it will not be affected. - */ - void setInheritOrientation(bool inherit); - - /** Returns true if this node is affected by orientation applied to the parent node. - - Orientations, unlike other transforms, are not always inherited by child nodes. - Whether or not orientations affect the orientation of the child nodes depends on - the setInheritOrientation option of the child. In some cases you want a orientating - of a parent node to apply to a child node (e.g. where the child node is a part of - the same object, so you want it to be the same relative orientation based on the - parent's orientation), but not in other cases (e.g. where the child node is just - for positioning another object, you want it to maintain it's own orientation). - The default is to inherit as with other transforms. - - See setInheritOrientation for more info. - */ - bool getInheritOrientation(void) const { return mInheritOrientation; } - - /** Tells the node whether it should inherit scaling factors from it's parent node. - - Scaling factors, unlike other transforms, are not always inherited by child nodes. - Whether or not scalings affect the size of the child nodes depends on the setInheritScale - option of the child. In some cases you want a scaling factor of a parent node to apply to - a child node (e.g. where the child node is a part of the same object, so you want it to be - the same relative size based on the parent's size), but not in other cases (e.g. where the - child node is just for positioning another object, you want it to maintain it's own size). - The default is to inherit as with other transforms. - @param inherit If true, this node's scale will be affected by its parent's scale. If false, - it will not be affected. - */ - void setInheritScale(bool inherit); - - /** Returns true if this node is affected by scaling factors applied to the parent node. - - See setInheritScale for more info. - */ - bool getInheritScale(void) const { return mInheritScale; } - - /** Scales the node, combining it's current scale with the passed in scaling factor. - - This method applies an extra scaling factor to the node's existing scale, (unlike setScale - which overwrites it) combining it's current scale with the new one. E.g. calling this - method twice with Vector3(2,2,2) would have the same effect as setScale(Vector3(4,4,4)) if - the existing scale was 1. - @par - Note that like rotations, scalings are oriented around the node's origin. - */ - void scale(const Vector3& scale); - - /// @overload - void scale(Real x, Real y, Real z); - - /** Moves the node along the Cartesian axes. - @par - This method moves the node by the supplied vector along the - world Cartesian axes, i.e. along world x,y,z - @param d - Vector with x,y,z values representing the translation. - @param relativeTo - The space which this transform is relative to. - */ - void translate(const Vector3& d, TransformSpace relativeTo = TS_PARENT); - /// @overload - void translate(Real x, Real y, Real z, TransformSpace relativeTo = TS_PARENT) - { - translate(Vector3(x, y, z), relativeTo); - } - /** Moves the node along arbitrary axes. - - This method translates the node by a vector which is relative to - a custom set of axes. - @param axes - A 3x3 Matrix containing 3 column vectors each representing the - axes X, Y and Z respectively. In this format the standard cartesian - axes would be expressed as: -
-            1 0 0
-            0 1 0
-            0 0 1
-            
- i.e. the identity matrix. - @param move - Vector relative to the axes above. - @param relativeTo - The space which this transform is relative to. - */ - void translate(const Matrix3& axes, const Vector3& move, TransformSpace relativeTo = TS_PARENT) - { - translate(axes * move, relativeTo); - } - /// @overload - void translate(const Matrix3& axes, Real x, Real y, Real z, TransformSpace relativeTo = TS_PARENT) - { - translate(axes, Vector3(x, y, z), relativeTo); - } - - /** Rotate the node around the Z-axis. - */ - virtual void roll(const Radian& angle, TransformSpace relativeTo = TS_LOCAL) - { - rotate(Quaternion(angle, Vector3::UNIT_Z), relativeTo); - } - - /** Rotate the node around the X-axis. - */ - virtual void pitch(const Radian& angle, TransformSpace relativeTo = TS_LOCAL) - { - rotate(Quaternion(angle, Vector3::UNIT_X), relativeTo); - } - - /** Rotate the node around the Y-axis. - */ - virtual void yaw(const Radian& angle, TransformSpace relativeTo = TS_LOCAL) - { - rotate(Quaternion(angle, Vector3::UNIT_Y), relativeTo); - } - - /** Rotate the node around an arbitrary axis. - */ - void rotate(const Vector3& axis, const Radian& angle, TransformSpace relativeTo = TS_LOCAL) - { - rotate(Quaternion(angle, axis), relativeTo); - } - - /** Rotate the node around an arbitrary axis using a Quarternion. - */ - void rotate(const Quaternion& q, TransformSpace relativeTo = TS_LOCAL); - - /** Gets a matrix whose columns are the local axes based on - the nodes orientation relative to it's parent. */ - Matrix3 getLocalAxes(void) const; - - /** Creates an unnamed new Node as a child of this node. - @param translate - Initial translation offset of child relative to parent - @param rotate - Initial rotation relative to parent - */ - virtual Node* createChild( - const Vector3& translate = Vector3::ZERO, - const Quaternion& rotate = Quaternion::IDENTITY ); - - /** Creates a new named Node as a child of this node. - - This creates a child node with a given name, which allows you to look the node up from - the parent which holds this collection of nodes. - @param name Name of the Node to create - @param translate - Initial translation offset of child relative to parent - @param rotate - Initial rotation relative to parent - */ - virtual Node* createChild(const String& name, const Vector3& translate = Vector3::ZERO, const Quaternion& rotate = Quaternion::IDENTITY); - - /** Adds a (precreated) child scene node to this node. If it is attached to another node, - it must be detached first. - @param child The Node which is to become a child node of this one - */ - void addChild(Node* child); - - /** Reports the number of child nodes under this one. - @deprecated use getChildren() - */ - uint16 numChildren(void) const { return static_cast< uint16 >( mChildren.size() ); } - - /** Gets a pointer to a child node. - - There is an alternate getChild method which returns a named child. - @deprecated use getChildren() - */ - Node* getChild(unsigned short index) const; - - /** Gets a pointer to a named child node. - */ - Node* getChild(const String& name) const; - - /// @deprecated use getChildren() - OGRE_DEPRECATED ChildNodeIterator getChildIterator(void); - - /// @deprecated use getChildren() - OGRE_DEPRECATED ConstChildNodeIterator getChildIterator(void) const; - - /// List of sub-nodes of this Node - const ChildNodeMap& getChildren() const { return mChildren; } - - /** Drops the specified child from this node. - - Does not delete the node, just detaches it from - this parent, potentially to be reattached elsewhere. - There is also an alternate version which drops a named - child from this node. - */ - virtual Node* removeChild(unsigned short index); - /// @overload - virtual Node* removeChild(Node* child); - - /** Drops the named child from this node. - - Does not delete the node, just detaches it from - this parent, potentially to be reattached elsewhere. - */ - virtual Node* removeChild(const String& name); - /** Removes all child Nodes attached to this node. Does not delete the nodes, just detaches them from - this parent, potentially to be reattached elsewhere. - */ - virtual void removeAllChildren(void); - - /** Sets the final world position of the node directly. - - It's advisable to use the local setPosition if possible - */ - void _setDerivedPosition(const Vector3& pos); - - /** Sets the final world orientation of the node directly. - - It's advisable to use the local setOrientation if possible, this simply does - the conversion for you. - */ - void _setDerivedOrientation(const Quaternion& q); - - /** Gets the orientation of the node as derived from all parents. - */ - const Quaternion & _getDerivedOrientation(void) const; - - /** Gets the position of the node as derived from all parents. - */ - const Vector3 & _getDerivedPosition(void) const; - - /** Gets the scaling factor of the node as derived from all parents. - */ - const Vector3 & _getDerivedScale(void) const; - - /** Gets the full transformation matrix for this node. - - This method returns the full transformation matrix - for this node, including the effect of any parent node - transformations, provided they have been updated using the Node::_update method. - This should only be called by a SceneManager which knows the - derived transforms have been updated before calling this method. - Applications using Ogre should just use the relative transforms. - */ - const Affine3& _getFullTransform(void) const; - - /** Internal method to update the Node. - @note - Updates this node and any relevant children to incorporate transforms etc. - Don't call this yourself unless you are writing a SceneManager implementation. - @param updateChildren - If @c true, the update cascades down to all children. Specify false if you wish to - update children separately, e.g. because of a more selective SceneManager implementation. - @param parentHasChanged - This flag indicates that the parent transform has changed, - so the child should retrieve the parent's transform and combine - it with its own even if it hasn't changed itself. - */ - virtual void _update(bool updateChildren, bool parentHasChanged); - - /** Sets a listener for this Node. - - Note for size and performance reasons only one listener per node is - allowed. - */ - void setListener(Listener* listener) { mListener = listener; } - - /** Gets the current listener for this Node. - */ - Listener* getListener(void) const { return mListener; } - - - /** Sets the current transform of this node to be the 'initial state' ie that - position / orientation / scale to be used as a basis for delta values used - in keyframe animation. - - You never need to call this method unless you plan to animate this node. If you do - plan to animate it, call this method once you've loaded the node with it's base state, - ie the state on which all keyframes are based. - @par - If you never call this method, the initial state is the identity transform, ie do nothing. - */ - void setInitialState(void); - - /** Resets the position / orientation / scale of this node to it's initial state, see setInitialState for more info. */ - void resetToInitialState(void); - - /** Gets the initial position of this node, see setInitialState for more info. - - Also resets the cumulative animation weight used for blending. - */ - const Vector3& getInitialPosition(void) const { return mInitialPosition; } - - /** Gets the local position, relative to this node, of the given world-space position */ - Vector3 convertWorldToLocalPosition( const Vector3 &worldPos ); - - /** Gets the world position of a point in the node local space - useful for simple transforms that don't require a child node.*/ - Vector3 convertLocalToWorldPosition( const Vector3 &localPos ); - - /** Gets the local direction, relative to this node, of the given world-space direction */ - Vector3 convertWorldToLocalDirection( const Vector3 &worldDir, bool useScale ); - - /** Gets the world direction of a point in the node local space - useful for simple transforms that don't require a child node.*/ - Vector3 convertLocalToWorldDirection( const Vector3 &localDir, bool useScale ); - - /** Gets the local orientation, relative to this node, of the given world-space orientation */ - Quaternion convertWorldToLocalOrientation( const Quaternion &worldOrientation ); - - /** Gets the world orientation of an orientation in the node local space - useful for simple transforms that don't require a child node.*/ - Quaternion convertLocalToWorldOrientation( const Quaternion &localOrientation ); - - /** Gets the initial orientation of this node, see setInitialState for more info. */ - const Quaternion& getInitialOrientation(void) const { return mInitialOrientation; } - - /** Gets the initial position of this node, see setInitialState for more info. */ - const Vector3& getInitialScale(void) const { return mInitialScale; } - - /** Helper function, get the squared view depth. */ - Real getSquaredViewDepth(const Camera* cam) const; - - /** To be called in the event of transform changes to this node that require it's recalculation. - - This not only tags the node state as being 'dirty', it also requests it's parent to - know about it's dirtiness so it will get an update next time. - @param forceParentUpdate Even if the node thinks it has already told it's - parent, tell it anyway - */ - virtual void needUpdate(bool forceParentUpdate = false); - /** Called by children to notify their parent that they need an update. - @param child The child Node to be updated - @param forceParentUpdate Even if the node thinks it has already told it's - parent, tell it anyway - */ - void requestUpdate(Node* child, bool forceParentUpdate = false); - /** Called by children to notify their parent that they no longer need an update. */ - void cancelUpdate(Node* child); - - /** Queue a 'needUpdate' call to a node safely. - - You can't call needUpdate() during the scene graph update, e.g. in - response to a Node::Listener hook, because the graph is already being - updated, and update flag changes cannot be made reliably in that context. - Call this method if you need to queue a needUpdate call in this case. - */ - static void queueNeedUpdate(Node* n); - /** Process queued 'needUpdate' calls. */ - static void processQueuedUpdates(void); - - - /** @deprecated use UserObjectBindings::setUserAny via getUserObjectBindings() instead. - */ - OGRE_DEPRECATED void setUserAny(const Any& anything) { getUserObjectBindings().setUserAny(anything); } - - /** @deprecated use UserObjectBindings::getUserAny via getUserObjectBindings() instead. - */ - OGRE_DEPRECATED const Any& getUserAny(void) const { return getUserObjectBindings().getUserAny(); } - - /// @copydoc UserObjectBindings - UserObjectBindings& getUserObjectBindings() { return mUserObjectBindings; } - - /// @overload - const UserObjectBindings& getUserObjectBindings() const { return mUserObjectBindings; } - - }; - /** @} */ - /** @} */ - -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif // _Node_H__ diff --git a/OgreMain/include/OgreOptimisedUtil.h b/OgreMain/include/OgreOptimisedUtil.h deleted file mode 100644 index bb26a01742e..00000000000 --- a/OgreMain/include/OgreOptimisedUtil.h +++ /dev/null @@ -1,245 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OptimisedUtil_H__ -#define __OptimisedUtil_H__ - -#include "OgrePrerequisites.h" -#include "OgreEdgeListBuilder.h" -#include - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - /** Utility class for provides optimised functions. - @note - This class are supposed used by internal engine only. - */ - class _OgreExport OptimisedUtil - { - private: - /// Privated copy constructor, to prevent misuse - OptimisedUtil(const OptimisedUtil& rhs); /* do nothing, should not use */ - /// Privated operator=, to prevent misuse - OptimisedUtil& operator=(const OptimisedUtil& rhs); /* do not use */ - - protected: - /// Store a pointer to the implementation - static OptimisedUtil* msImplementation; - - /// Detect best implementation based on run-time environment - static OptimisedUtil* _detectImplementation(void); - - public: - // Default constructor - OptimisedUtil(void) {} - // Destructor - virtual ~OptimisedUtil() {} - - /** Gets the implementation of this class. - @note - Don't cache the pointer returned by this function, it'll change due - run-time environment detection to pick up the best implementation. - */ - static OptimisedUtil* getImplementation(void) { return msImplementation; } - - /** Performs software vertex skinning. - @param srcPosPtr Pointer to source position buffer. - @param destPosPtr Pointer to destination position buffer. - @param srcNormPtr Pointer to source normal buffer, if NULL, - means blend position only. - @param destNormPtr Pointer to destination normal buffer, it's - ignored if srcNormPtr is NULL. - @param blendWeightPtr Pointer to blend weight buffer. - @param blendIndexPtr Pointer to blend index buffer. - @param blendMatrices An array of pointer of blend matrix, the matrix - must be aligned to SIMD alignment, but not necessary for the array - itself. - @param srcPosStride The stride of source position in bytes. - @param destPosStride The stride of destination position in bytes. - @param srcNormStride The stride of source normal in bytes, - it's ignored if srcNormPtr is NULL. - @param destNormStride The stride of destination normal in bytes, - it's ignored if srcNormPtr is NULL. - @param blendWeightStride The stride of blend weight buffer in bytes. - @param blendIndexStride The stride of blend index buffer in bytes. - @param numWeightsPerVertex Number of blend weights per-vertex, as well - as for blend indices. - @param numVertices Number of vertices to blend. - */ - virtual void softwareVertexSkinning( - const float *srcPosPtr, float *destPosPtr, - const float *srcNormPtr, float *destNormPtr, - const float *blendWeightPtr, const unsigned char* blendIndexPtr, - const Affine3* const* blendMatrices, - size_t srcPosStride, size_t destPosStride, - size_t srcNormStride, size_t destNormStride, - size_t blendWeightStride, size_t blendIndexStride, - size_t numWeightsPerVertex, - size_t numVertices) = 0; - - /** Performs a software vertex morph, of the kind used for - morph animation although it can be used for other purposes. - - This function will linearly interpolate positions between two - source buffers, into a third buffer. - @param t Parametric distance between the start and end positions - @param srcPos1 Pointer to buffer for the start positions - @param srcPos2 Pointer to buffer for the end positions - @param dstPos Pointer to buffer for the destination positions - @param pos1VSize, pos2VSize, dstVSize Vertex sizes in bytes of each of the 3 buffers referenced - @param numVertices Number of vertices to morph, which agree with - the number in start, end and destination buffer. Bear in mind - three floating-point values per vertex - @param morphNormals - */ - virtual void softwareVertexMorph( - float t, - const float *srcPos1, const float *srcPos2, - float *dstPos, - size_t pos1VSize, size_t pos2VSize, size_t dstVSize, - size_t numVertices, - bool morphNormals) = 0; - - /** Concatenate an affine matrix to an array of affine matrices. - @note - An affine matrix is a 4x4 matrix with row 3 equal to (0, 0, 0, 1), - e.g. no projective coefficients. - @param baseMatrix The matrix used as first operand. - @param srcMatrices An array of matrix used as second operand. - @param dstMatrices An array of matrix to store matrix concatenate results. - @param numMatrices Number of matrices in the array. - */ - virtual void concatenateAffineMatrices( - const Affine3& baseMatrix, - const Affine3* srcMatrices, - Affine3* dstMatrices, - size_t numMatrices) = 0; - - /** Calculate the face normals for the triangles based on position - information. - @param positions Pointer to position information, which packed in - (x, y, z) format, indexing by vertex index in the triangle. No - alignment requests. - @param triangles The triangles need to calculate face normal, the vertex - positions is indexed by vertex index to position information. - @param faceNormals The array of Vector4 used to store triangles face normal, - Must be aligned to SIMD alignment. - @param numTriangles Number of triangles to calculate face normal. - */ - virtual void calculateFaceNormals( - const float *positions, - const EdgeData::Triangle *triangles, - Vector4 *faceNormals, - size_t numTriangles) = 0; - - /** Calculate the light facing state of the triangle's face normals - - This is normally the first stage of calculating a silhouette, i.e. - establishing which tris are facing the light and which are facing - away. - @param lightPos 4D position of the light in object space, note that - for directional lights (which have no position), the w component - is 0 and the x/y/z position are the direction. - @param faceNormals An array of face normals for the triangles, the face - normal are unit vector orthogonal to the triangles, plus distance - from origin. This array must be aligned to SIMD alignment. - @param lightFacings An array of flags for store light facing state - results, the result flag is true if corresponding face normal facing - the light, false otherwise. This array no alignment requires. - @param numFaces Number of face normals to calculate. - */ - virtual void calculateLightFacing( - const Vector4& lightPos, - const Vector4* faceNormals, - char* lightFacings, - size_t numFaces) = 0; - - /** Extruding vertices by a fixed distance based on light position. - @param lightPos 4D light position, when w=0.0f this represents a - directional light, otherwise, w must be equal to 1.0f, which - represents a point light. - @param extrudeDist The distance to extrude. - @param srcPositions Pointer to source vertex's position buffer, which - the position is a 3D vector packed in xyz format. No SIMD alignment - requirement but loss performance for unaligned data. - @param destPositions Pointer to destination vertex's position buffer, - which the position is a 3D vector packed in xyz format. No SIMD - alignment requirement but loss performance for unaligned data. - @param numVertices Number of vertices need to extruding, which agree - with source and destination buffers. - */ - virtual void extrudeVertices( - const Vector4& lightPos, - Real extrudeDist, - const float* srcPositions, - float* destPositions, - size_t numVertices) = 0; - }; - - /** Returns raw offsetted of the given pointer. - @note - The offset are in bytes, no matter what type of the pointer. - */ - template - static OGRE_FORCE_INLINE const T* rawOffsetPointer(const T* ptr, ptrdiff_t offset) - { - return (const T*)((const char*)(ptr) + offset); - } - - template - static OGRE_FORCE_INLINE T* rawOffsetPointer(T* ptr, ptrdiff_t offset) - { - return (T*)((char*)(ptr) + offset); - } - - /** Advance the pointer with raw offset. - @note - The offset are in bytes, no matter what type of the pointer. - */ - template - static OGRE_FORCE_INLINE void advanceRawPointer(const T*& ptr, ptrdiff_t offset) - { - ptr = rawOffsetPointer(ptr, offset); - } - - template - static OGRE_FORCE_INLINE void advanceRawPointer(T*& ptr, ptrdiff_t offset) - { - ptr = rawOffsetPointer(ptr, offset); - } - /** @} */ - /** @} */ - -} - -#endif // __OptimisedUtil_H__ diff --git a/OgreMain/include/OgreParticle.h b/OgreMain/include/OgreParticle.h deleted file mode 100644 index 2489801ce78..00000000000 --- a/OgreMain/include/OgreParticle.h +++ /dev/null @@ -1,116 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Particle_H__ -#define __Particle_H__ - -#include "OgrePrerequisites.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - /** Class representing a single particle instance. */ - class _OgreExport Particle : public FXAlloc - { - public: - /// Type of particle - enum ParticleType : uint8 - { - Visual, - Emitter - }; - - /// Particle width - float mWidth; - /// Particle height - float mHeight; - /// Current rotation value - Radian mRotation; - // Note the intentional public access to internal variables - // Accessing via get/set would be too costly for 000's of particles - /// World position - Vector3 mPosition; - /// Direction (and speed) - Vector3 mDirection; - /// Current colour - RGBA mColour; - /// Time to live, number of seconds left of particles natural life - float mTimeToLive; - /// Total Time to live, number of seconds of particles natural life - float mTotalTimeToLive; - /// Speed of rotation in radians/sec - Radian mRotationSpeed; - /// Determines the type of particle. - ParticleType mParticleType; - /// Index into the array of texture coordinates @see BillboardSet::setTextureStacksAndSlices() - uint8 mTexcoordIndex; - uint8 mRandomTexcoordOffset; - - Particle() - : mWidth(0), mHeight(0), - mRotation(0), mPosition(Vector3::ZERO), mDirection(Vector3::ZERO), - mColour(0xFFFFFFFF), mTimeToLive(10), mTotalTimeToLive(10), - mRotationSpeed(0), mParticleType(Visual), mTexcoordIndex(0), mRandomTexcoordOffset(0) - { - } - - /** Sets the width and height for this particle. - */ - void setDimensions(float width, float height) - { - mWidth = width; - mHeight = height; - } - - /// @deprecated do not use - OGRE_DEPRECATED bool hasOwnDimensions(void) const { return true; } - - /** Retrieves the particle's personal width, if hasOwnDimensions is true. */ - float getOwnWidth(void) const { return mWidth; } - - /** Retrieves the particle's personal width, if hasOwnDimensions is true. */ - float getOwnHeight(void) const { return mHeight; } - - /** Sets the current rotation */ - void setRotation(const Radian& rad) { mRotation = rad; } - - const Radian& getRotation(void) const { return mRotation; } - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreParticleAffector.h b/OgreMain/include/OgreParticleAffector.h deleted file mode 100644 index a3e205438cf..00000000000 --- a/OgreMain/include/OgreParticleAffector.h +++ /dev/null @@ -1,129 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ParticleAffector_H__ -#define __ParticleAffector_H__ - -#include "OgrePrerequisites.h" -#include "OgreString.h" -#include "OgreStringInterface.h" -#include "OgreHeaderPrefix.h" - - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ -/** Abstract class defining the interface to be implemented by particle affectors. - - Particle affectors modify particles in a particle system over their lifetime. They can be - grouped into types, e.g. 'vector force' affectors, 'fader' affectors etc; each type will - modify particles in a different way, using different parameters. - @par - Because there are so many types of affectors you could use, OGRE chooses not to dictate - the available types. It comes with some in-built, but allows plugins or applications to extend the affector types available. - This is done by subclassing ParticleAffector to have the appropriate emission behaviour you want, - and also creating a subclass of ParticleAffectorFactory which is responsible for creating instances - of your new affector type. You register this factory with the ParticleSystemManager using - addAffectorFactory, and from then on affectors of this type can be created either from code or through - text particle scripts by naming the type. - @par - This same approach is used for ParticleEmitters (which are the source of particles in a system). - This means that OGRE is particularly flexible when it comes to creating particle system effects, - with literally infinite combinations of affector and affector types, and parameters within those - types. - */ - class _OgreExport ParticleAffector : public StringInterface, public FXAlloc - { - protected: - /// Name of the type of affector, MUST be initialised by subclasses - String mType; - - /** Internal method for setting up the basic parameter definitions for a subclass. - - Because StringInterface holds a dictionary of parameters per class, subclasses need to - call this to ask the base class to add it's parameters to their dictionary as well. - Can't do this in the constructor because that runs in a non-virtual context. - @par - The subclass must have called it's own createParamDictionary before calling this method. - */ - void addBaseParameters(void) { /* actually do nothing - for future possible use */ } - - ParticleSystem* mParent; - public: - ParticleAffector(ParticleSystem* parent): mParent(parent) {} - - /** Virtual destructor essential. */ - virtual ~ParticleAffector(); - - /** Method called to allow the affector to initialize all newly created particles in the system. - - This is where the affector gets the chance to initialize it's effects to the particles of a system. - The affector is expected to initialize some or all of the particles in the system - passed to it, depending on the affector's approach. - @param - pParticle Pointer to a Particle to initialize. - */ - virtual void _initParticle(Particle* pParticle) - { - /* by default do nothing */ - (void)pParticle; - } - - /** Method called to allow the affector to 'do it's stuff' on all active particles in the system. - - This is where the affector gets the chance to apply it's effects to the particles of a system. - The affector is expected to apply it's effect to some or all of the particles in the system - passed to it, depending on the affector's approach. - @param - pSystem Pointer to a ParticleSystem to affect. - @param - timeElapsed The number of seconds which have elapsed since the last call. - */ - virtual void _affectParticles(ParticleSystem* pSystem, Real timeElapsed) = 0; - - /** Returns the name of the type of affector. - - This property is useful for determining the type of affector procedurally so another - can be created. - */ - const String &getType(void) const { return mType; } - - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreParticleAffectorFactory.h b/OgreMain/include/OgreParticleAffectorFactory.h deleted file mode 100644 index ea4d866484d..00000000000 --- a/OgreMain/include/OgreParticleAffectorFactory.h +++ /dev/null @@ -1,83 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ParticleAffectorFactory_H__ -#define __ParticleAffectorFactory_H__ - - -#include "OgrePrerequisites.h" -#include "OgreParticleAffector.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - /** Abstract class defining the interface to be implemented by creators of ParticleAffector subclasses. - - Plugins or 3rd party applications can add new types of particle affectors to Ogre by creating - subclasses of the ParticleAffector class. Because multiple instances of these affectors may be - required, a factory class to manage the instances is also required. - @par - ParticleAffectorFactory subclasses must allow the creation and destruction of ParticleAffector - subclasses. They must also be registered with the ParticleSystemManager. All factories have - a name which identifies them, examples might be 'force_vector', 'attractor', or 'fader', and these can be - also be used from particle system scripts. - */ - class _OgreExport ParticleAffectorFactory : public FXAlloc - { - protected: - std::vector mAffectors; //!< @deprecated do not use - public: - ParticleAffectorFactory() {} - virtual ~ParticleAffectorFactory(); - /** Returns the name of the factory, the name which identifies the particle affector type this factory creates. */ - virtual String getName() const = 0; - - /** Creates a new affector instance. - - The subclass MUST add a pointer to the created instance to mAffectors. - */ - virtual ParticleAffector* createAffector(ParticleSystem* psys) = 0; - - /** Destroys the affector pointed to by the parameter (for early clean up if required). */ - virtual void destroyAffector(ParticleAffector* e); - }; - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreParticleEmitter.h b/OgreMain/include/OgreParticleEmitter.h deleted file mode 100644 index f4bb52591e5..00000000000 --- a/OgreMain/include/OgreParticleEmitter.h +++ /dev/null @@ -1,532 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ParticleEmitter_H__ -#define __ParticleEmitter_H__ - -#include "OgrePrerequisites.h" -#include "OgreVector.h" -#include "OgreColourValue.h" -#include "OgreStringInterface.h" -#include "OgreParticle.h" -#include "OgreParticleSystem.h" -#include "OgreHeaderPrefix.h" - - -namespace Ogre { - - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - /** Abstract class defining the interface to be implemented by particle emitters. - - Particle emitters are the sources of particles in a particle system. - This class defines the ParticleEmitter interface, and provides a basic implementation - for tasks which most emitters will do (these are of course overridable). - Particle emitters can be grouped into types, e.g. 'point' emitters, 'box' emitters etc; each type will - create particles with a different starting point, direction and velocity (although - within the types you can configure the ranges of these parameters). - @par - Because there are so many types of emitters you could use, OGRE chooses not to dictate - the available types. It comes with some in-built, but allows plugins or applications to extend the emitter types available. - This is done by subclassing ParticleEmitter to have the appropriate emission behaviour you want, - and also creating a subclass of ParticleEmitterFactory which is responsible for creating instances - of your new emitter type. You register this factory with the ParticleSystemManager using - addEmitterFactory, and from then on emitters of this type can be created either from code or through - text particle scripts by naming the type. - @par - This same approach is used for ParticleAffectors (which modify existing particles per frame). - This means that OGRE is particularly flexible when it comes to creating particle system effects, - with literally infinite combinations of emitter and affector types, and parameters within those - types. - */ - class _OgreExport ParticleEmitter : public StringInterface, public Particle - { - protected: - /// Parent particle system - ParticleSystem* mParent; - - /// Position relative to the center of the ParticleSystem - // inherited: Vector3 mPosition; - // Note, that position of the emitter becomes a position in worldspace if mLocalSpace is set - // to false (will this become a problem?) - - /// Rate in particles per second at which this emitter wishes to emit particles - Real mEmissionRate; - /// Name of the type of emitter, MUST be initialised by subclasses - String mType; - /// Base direction of the emitter, may not be used by some emitters - Vector3 mDirection; - /// Notional up vector, used to speed up generation of variant directions, and also to orient some emitters. - Vector3 mUp; - /// When true, mDirPositionRef is used instead of mDirection to generate particles - bool mUseDirPositionRef; - /* Center position to tell in which direction will particles be emitted according to their position, - useful for explosions & implosions, some emitters (i.e. point emitter) may not need it. */ - Vector3 mDirPositionRef; - /// Angle around direction which particles may be emitted, internally radians but angleunits for interface - Radian mAngle; - /// Min speed of particles - Real mMinSpeed; - /// Max speed of particles - Real mMaxSpeed; - /// Initial time-to-live of particles (min) - Real mMinTTL; - /// Initial time-to-live of particles (max) - Real mMaxTTL; - /// Initial colour of particles (range start) - ColourValue mColourRangeStart; - /// Initial colour of particles (range end) - ColourValue mColourRangeEnd; - - /// Whether this emitter is currently enabled (defaults to true) - bool mEnabled; - - /// Start time (in seconds from start of first call to ParticleSystem to update) - Real mStartTime; - /// Minimum length of time emitter will run for (0 = forever) - Real mDurationMin; - /// Maximum length of time the emitter will run for (0 = forever) - Real mDurationMax; - /// Current duration remainder - Real mDurationRemain; - - /// Time between each repeat - Real mRepeatDelayMin; - Real mRepeatDelayMax; - /// Repeat delay left - Real mRepeatDelayRemain; - - // Fractions of particles wanted to be emitted last time - float mRemainder; - - /// The name of the emitter. The name is optional unless it is used as an emitter that is emitted itself. - String mName; - - /// The name of the emitter to be emitted (optional) - String mEmittedEmitter; - - // If 'true', this emitter is emitted by another emitter. - // NB. That doesn't imply that the emitter itself emits other emitters (that could or could not be the case) - bool mEmitted; - - // NB Method below here are to help out people implementing emitters by providing the - // most commonly used approaches as piecemeal methods - - /** Internal utility method for generating particle exit direction - @param destVector Reference to vector to complete with new direction (normalised) - */ - virtual void genEmissionDirection( const Vector3 &particlePos, Vector3& destVector ); - - /** Internal utility method to apply velocity to a particle direction. - @param destVector The vector to scale by a randomly generated scale between min and max speed. - Assumed normalised already, and likely already oriented in the right direction. - */ - virtual void genEmissionVelocity(Vector3& destVector); - - /** Internal utility method for generating a time-to-live for a particle. */ - virtual Real genEmissionTTL(void); - - /** Internal utility method for generating a colour for a particle. */ - virtual void genEmissionColour(RGBA& destColour); - - /** Internal utility method for generating an emission count based on a constant emission rate. */ - unsigned short genConstantEmissionCount(Real timeElapsed); - - /** Internal method for setting up the basic parameter definitions for a subclass. - - Because StringInterface holds a dictionary of parameters per class, subclasses need to - call this to ask the base class to add it's parameters to their dictionary as well. - Can't do this in the constructor because that runs in a non-virtual context. - @par - The subclass must have called it's own createParamDictionary before calling this method. - */ - void addBaseParameters(void); - - /** Internal method for initialising the duration & repeat of an emitter. */ - void initDurationRepeat(void); - - - public: - ParticleEmitter(ParticleSystem* psys); - /** Virtual destructor essential. */ - virtual ~ParticleEmitter(); - - /** Sets the position of this emitter relative to the particle system center. */ - virtual void setPosition(const Vector3& pos); - - /** Returns the position of this emitter relative to the center of the particle system. */ - virtual const Vector3& getPosition(void) const; - - /** Sets the direction of the emitter. - - Most emitters will have a base direction in which they emit particles (those which - emit in all directions will ignore this parameter). They may not emit exactly along this - vector for every particle, many will introduce a random scatter around this vector using - the angle property. - @note - This resets the up vector. - @param direction - The base direction for particles emitted. - */ - virtual void setDirection(const Vector3& direction); - - /** Returns the base direction of the emitter. */ - virtual const Vector3& getDirection(void) const; - - /** Sets the notional up vector of the emitter - - Many emitters emit particles from within a region, and for some that region is not - circularly symmetric about the emitter direction. The up vector allows such emitters - to be orientated about the direction vector. - @param up - The base direction for particles emitted. It must be perpendicular to the direction vector. - */ - virtual void setUp(const Vector3& up); - - /** Returns the up vector of the emitter. */ - virtual const Vector3& getUp(void) const; - - /** Sets the direction of the emitter. - Some particle effects need to emit particles in many random directions, but still - following some rules; like not having them collide against each other. Very useful - for explosions and implosions (when velocity is negative) - @note - Although once enabled mDirPositionRef will supersede mDirection; calling setDirection() - may still be needed to setup a custom up vector. - @param position - The reference position in which the direction of the particles will be calculated from, - also taking into account the particle's position at the time of emission. - @param enable - True to use mDirPositionRef, false to use the default behaviour with mDirection - */ - virtual void setDirPositionReference( const Vector3& position, bool enable ); - - /** Returns the position reference to generate direction of emitted particles */ - virtual const Vector3& getDirPositionReference() const; - - /** Returns whether direction or position reference is used */ - virtual bool getDirPositionReferenceEnabled() const; - - /** Sets the maximum angle away from the emitter direction which particle will be emitted. - - Whilst the direction property defines the general direction of emission for particles, - this property defines how far the emission angle can deviate away from this base direction. - This allows you to create a scatter effect - if set to 0, all particles will be emitted - exactly along the emitters direction vector, whereas if you set it to 180 degrees or more, - particles will be emitted in a sphere, i.e. in all directions. - @param angle - Maximum angle which initial particle direction can deviate from the emitter base direction vector. - */ - virtual void setAngle(const Radian& angle); - - /** Returns the maximum angle which the initial particle direction can deviate from the emitters base direction. */ - virtual const Radian& getAngle(void) const; - - /** Sets the initial velocity of particles emitted. - - This method sets a constant speed for emitted particles. See the alternate version - of this method which takes 2 parameters if you want a variable speed. - @param - speed The initial speed in world units per second which every particle emitted starts with. - */ - virtual void setParticleVelocity(Real speed); - - - /** Sets the initial velocity range of particles emitted. - - This method sets the range of starting speeds for emitted particles. - See the alternate version of this method which takes 1 parameter if you want a - constant speed. This emitter will randomly choose a speed between the minimum and - maximum for each particle. - @param max The maximum speed in world units per second for the initial particle speed on emission. - @param min The minimum speed in world units per second for the initial particle speed on emission. - */ - virtual void setParticleVelocity(Real min, Real max); - /** Returns the minimum particle velocity. */ - virtual void setMinParticleVelocity(Real min); - /** Returns the maximum particle velocity. */ - virtual void setMaxParticleVelocity(Real max); - - /** Returns the initial velocity of particles emitted. */ - virtual Real getParticleVelocity(void) const; - - /** Returns the minimum particle velocity. */ - virtual Real getMinParticleVelocity(void) const; - - /** Returns the maximum particle velocity. */ - virtual Real getMaxParticleVelocity(void) const; - - /** Sets the emission rate for this emitter. - - This method tells the emitter how many particles per second should be emitted. The emitter - subclass does not have to emit these in a continuous burst - this is a relative parameter - and the emitter may choose to emit all of the second's worth of particles every half-second - for example. This is controlled by the emitter's getEmissionCount method. - @par - Also, if the ParticleSystem's particle quota is exceeded, not all the particles requested - may be actually emitted. - @param - particlesPerSecond The number of particles to be emitted every second. - */ - virtual void setEmissionRate(Real particlesPerSecond); - - /** Returns the emission rate set for this emitter. */ - virtual Real getEmissionRate(void) const; - - /** Sets the lifetime of all particles emitted. - - The emitter initialises particles with a time-to-live (TTL), the number of seconds a particle - will exist before being destroyed. This method sets a constant TTL for all particles emitted. - Note that affectors are able to modify the TTL of particles later. - @par - Also see the alternate version of this method which takes a min and max TTL in order to - have the TTL vary per particle. - @param ttl The number of seconds each particle will live for. - */ - virtual void setTimeToLive(Real ttl); - /** Sets the range of lifetime for particles emitted. - - The emitter initialises particles with a time-to-live (TTL), the number of seconds a particle - will exist before being destroyed. This method sets a range for the TTL for all particles emitted; - the ttl may be randomised between these 2 extremes or will vary some other way depending on the - emitter. - Note that affectors are able to modify the TTL of particles later. - @par - Also see the alternate version of this method which takes a single TTL in order to - set a constant TTL for all particles. - @param minTtl The minimum number of seconds each particle will live for. Must be non-negative! - @param maxTtl The maximum number of seconds each particle will live for. Must be non-negative! - */ - virtual void setTimeToLive(Real minTtl, Real maxTtl); - - /** Sets the minimum time each particle will live for. Must be non-negative! */ - virtual void setMinTimeToLive(Real min); - /** Sets the maximum time each particle will live for. Must be non-negative! */ - virtual void setMaxTimeToLive(Real max); - - /** Gets the time each particle will live for. */ - virtual Real getTimeToLive(void) const; - - /** Gets the minimum time each particle will live for. */ - virtual Real getMinTimeToLive(void) const; - /** Gets the maximum time each particle will live for. */ - virtual Real getMaxTimeToLive(void) const; - - /** Sets the initial colour of particles emitted. - - Particles have an initial colour on emission which the emitter sets. This method sets - this colour. See the alternate version of this method which takes 2 colours in order to establish - a range of colours to be assigned to particles. - @param colour The colour which all particles will be given on emission. - */ - virtual void setColour(const ColourValue& colour); - /** Sets the range of colours for emitted particles. - - Particles have an initial colour on emission which the emitter sets. This method sets - the range of this colour. See the alternate version of this method which takes a single colour - in order to set a constant colour for all particles. Emitters may choose to randomly assign - a colour in this range, or may use some other method to vary the colour. - @param colourStart The start of the colour range - @param colourEnd The end of the colour range - */ - virtual void setColour(const ColourValue& colourStart, const ColourValue& colourEnd); - /** Sets the minimum colour of particles to be emitted. */ - virtual void setColourRangeStart(const ColourValue& colour); - /** Sets the maximum colour of particles to be emitted. */ - virtual void setColourRangeEnd(const ColourValue& colour); - /** Gets the colour of particles to be emitted. */ - virtual const ColourValue& getColour(void) const; - /** Gets the minimum colour of particles to be emitted. */ - virtual const ColourValue& getColourRangeStart(void) const; - /** Gets the maximum colour of particles to be emitted. */ - virtual const ColourValue& getColourRangeEnd(void) const; - - /** Gets the number of particles which this emitter would like to emit based on the time elapsed. - - For efficiency the emitter does not actually create new Particle instances (these are reused - by the ParticleSystem as existing particles 'die'). The implementation for this method must - return the number of particles the emitter would like to emit given the number of seconds which - have elapsed (passed in as a parameter). - @par - Based on the return value from this method, the ParticleSystem class will call - _initParticle once for each particle it chooses to allow to be emitted by this emitter. - The emitter should not track these _initParticle calls, it should assume all emissions - requested were made (even if they could not be because of particle quotas). - */ - virtual unsigned short _getEmissionCount(Real timeElapsed) - { - return genConstantEmissionCount(timeElapsed); - } - - /** Initialises a particle based on the emitter's approach and parameters. - - See the _getEmissionCount method for details of why there is a separation between - 'requested' emissions and actual initialised particles. - @param - pParticle Pointer to a particle which must be initialised based on how this emitter - starts particles. This is passed as a pointer rather than being created by the emitter so the - ParticleSystem can reuse Particle instances, and can also set defaults itself. - */ - virtual void _initParticle(Particle* pParticle) { - // Initialise size in case it's been altered - pParticle->setDimensions(mParent->getDefaultWidth(), mParent->getDefaultHeight()); - } - - - /** Returns the name of the type of emitter. - - This property is useful for determining the type of emitter procedurally so another - can be created. - */ - const String &getType(void) const { return mType; } - - /** Sets whether or not the emitter is enabled. - - You can turn an emitter off completely by setting this parameter to false. - */ - virtual void setEnabled(bool enabled); - - /** Gets the flag indicating if this emitter is enabled or not. */ - virtual bool getEnabled(void) const; - - /** Sets the 'start time' of this emitter. - - By default an emitter starts straight away as soon as a ParticleSystem is first created, - or also just after it is re-enabled. This parameter allows you to set a time delay so - that the emitter does not 'kick in' until later. - @param startTime The time in seconds from the creation or enabling of the emitter. - */ - virtual void setStartTime(Real startTime); - /** Gets the start time of the emitter. */ - virtual Real getStartTime(void) const; - - /** Sets the duration of the emitter. - - By default emitters run indefinitely (unless you manually disable them). By setting this - parameter, you can make an emitter turn off on it's own after a set number of seconds. It - will then remain disabled until either setEnabled(true) is called, or if the 'repeatAfter' parameter - has been set it will also repeat after a number of seconds. - @par - Also see the alternative version of this method which allows you to set a min and max duration for - a random variable duration. - @param duration The duration in seconds. - */ - virtual void setDuration(Real duration); - - /** Gets the duration of the emitter from when it is created or re-enabled. */ - virtual Real getDuration(void) const; - - /** Sets the range of random duration for this emitter. - - By default emitters run indefinitely (unless you manually disable them). By setting this - parameter, you can make an emitter turn off on it's own after a random number of seconds. It - will then remain disabled until either setEnabled(true) is called, or if the 'repeatAfter' parameter - has been set it will also repeat after a number of seconds. - @par - Also see the alternative version of this method which allows you to set a constant duration. - @param min The minimum duration in seconds. - @param max The minimum duration in seconds. - */ - virtual void setDuration(Real min, Real max); - /** Sets the minimum duration of this emitter in seconds (see setDuration for more details) */ - virtual void setMinDuration(Real min); - /** Sets the maximum duration of this emitter in seconds (see setDuration for more details) */ - virtual void setMaxDuration(Real max); - /** Gets the minimum duration of this emitter in seconds (see setDuration for more details) */ - virtual Real getMinDuration(void) const; - /** Gets the maximum duration of this emitter in seconds (see setDuration for more details) */ - virtual Real getMaxDuration(void) const; - - /** Sets the time between repeats of the emitter. - - By default emitters run indefinitely (unless you manually disable them). However, if you manually - disable the emitter (by calling setEnabled(false), or it's duration runs out, it will cease to emit - @par - Also see the alternative version of this method which allows you to set a min and max duration for - a random variable duration. - @param duration The duration in seconds. - */ - virtual void setRepeatDelay(Real duration); - - /** Gets the duration of the emitter from when it is created or re-enabled. */ - virtual Real getRepeatDelay(void) const; - - /** Sets the range of random duration for this emitter. - - By default emitters run indefinitely (unless you manually disable them). By setting this - parameter, you can make an emitter turn off on it's own after a random number of seconds. It - will then remain disabled until either setEnabled(true) is called, or if the 'repeatAfter' parameter - has been set it will also repeat after a number of seconds. - @par - Also see the alternative version of this method which allows you to set a constant duration. - @param min The minimum duration in seconds. - @param max The minimum duration in seconds. - */ - virtual void setRepeatDelay(Real min, Real max); - /** Sets the minimum duration of this emitter in seconds (see setRepeatDelay for more details) */ - virtual void setMinRepeatDelay(Real min); - /** Sets the maximum duration of this emitter in seconds (see setRepeatDelay for more details) */ - virtual void setMaxRepeatDelay(Real max); - /** Gets the minimum duration of this emitter in seconds (see setRepeatDelay for more details) */ - virtual Real getMinRepeatDelay(void) const; - /** Gets the maximum duration of this emitter in seconds (see setRepeatDelay for more details) */ - virtual Real getMaxRepeatDelay(void) const; - - /** Returns the name of the emitter */ - const String &getName(void) const; - - /** Sets the name of the emitter */ - virtual void setName(const String& newName); - - /** Returns the name of the emitter to be emitted */ - const String &getEmittedEmitter(void) const; - - /** Sets the name of the emitter to be emitted*/ - virtual void setEmittedEmitter(const String& emittedEmitter); - - /** Return true if the emitter is emitted by another emitter */ - virtual bool isEmitted(void) const; - - /** Set the indication (true/false) to indicate that the emitter is emitted by another emitter */ - virtual void setEmitted(bool emitted); - - - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreParticleEmitterFactory.h b/OgreMain/include/OgreParticleEmitterFactory.h deleted file mode 100644 index 12b677f3b44..00000000000 --- a/OgreMain/include/OgreParticleEmitterFactory.h +++ /dev/null @@ -1,86 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ParticleEmitterFactory_H__ -#define __ParticleEmitterFactory_H__ - - -#include "OgrePrerequisites.h" -#include "OgreParticleEmitter.h" -#include "OgreString.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - /** Abstract class defining the interface to be implemented by creators of ParticleEmitter subclasses. - - Plugins or 3rd party applications can add new types of particle emitters to Ogre by creating - subclasses of the ParticleEmitter class. Because multiple instances of these emitters may be - required, a factory class to manage the instances is also required. - @par - ParticleEmitterFactory subclasses must allow the creation and destruction of ParticleEmitter - subclasses. They must also be registered with the ParticleSystemManager. All factories have - a name which identifies them, examples might be 'point', 'cone', or 'box', and these can be - also be used from particle system scripts. - */ - class _OgreExport ParticleEmitterFactory : public FXAlloc - { - protected: - std::vector mEmitters; //!< @deprecated do not use - public: - ParticleEmitterFactory() {} - virtual ~ParticleEmitterFactory(); - - /** Returns the name of the factory, the name which identifies the particle emitter type this factory creates. */ - virtual String getName() const = 0; - - /** Creates a new emitter instance. - - The subclass MUST add a pointer to the created instance to mEmitters. - */ - virtual ParticleEmitter* createEmitter(ParticleSystem* psys) = 0; - - /** Destroys the emitter pointed to by the parameter (for early clean up if required). */ - virtual void destroyEmitter(ParticleEmitter* e); - - }; - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreParticleSystem.h b/OgreMain/include/OgreParticleSystem.h deleted file mode 100644 index df2f1e52957..00000000000 --- a/OgreMain/include/OgreParticleSystem.h +++ /dev/null @@ -1,776 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ParticleSystem_H__ -#define __ParticleSystem_H__ - -#include "OgrePrerequisites.h" - -#include "OgreVector.h" -#include "OgreStringInterface.h" -#include "OgreMovableObject.h" -#include "OgreResourceGroupManager.h" -#include "OgreHeaderPrefix.h" - - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - /** Class defining particle system based special effects. - - Particle systems are special effects generators which are based on a - number of moving points to create the impression of things like like - sparkles, smoke, blood spurts, dust etc. - @par - This class simply manages a single collection of particles in world space - with a shared local origin for emission. The visual aspect of the - particles is handled by a ParticleSystemRenderer instance. - @par - Particle systems are created using the SceneManager, never directly. - In addition, like all subclasses of MovableObject, the ParticleSystem - will only be considered for rendering once it has been attached to a - SceneNode. - */ - class _OgreExport ParticleSystem : public StringInterface, public MovableObject - { - public: - /// Default constructor required for STL creation in manager - ParticleSystem(); - /** Creates a particle system with no emitters or affectors. - - You should use the ParticleSystemManager to create particle systems rather than creating - them directly. - */ - ParticleSystem(const String& name, const String& resourceGroupName); - - virtual ~ParticleSystem(); - - /** Sets the ParticleRenderer to be used to render this particle system. - - The main ParticleSystem just manages the creation and movement of - particles; they are rendered using functions in ParticleRenderer - and the ParticleVisual instances they create. - @param typeName String identifying the type of renderer to use; a new - instance of this type will be created; a factory must have been registered - with ParticleSystemManager. - */ - void setRenderer(const String& typeName); - - /** Gets the ParticleRenderer to be used to render this particle system. */ - ParticleSystemRenderer* getRenderer(void) const; - /** Gets the name of the ParticleRenderer to be used to render this particle system. */ - const String& getRendererName(void) const; - - /** Adds an emitter to this particle system. - - Particles are created in a particle system by emitters - see the ParticleEmitter - class for more details. - @param - emitterType String identifying the emitter type to create. Emitter types are defined - by registering new factories with the manager - see ParticleEmitterFactory for more details. - Emitter types can be extended by OGRE, plugin authors or application developers. - */ - ParticleEmitter* addEmitter(const String& emitterType); - - /** Retrieves an emitter by it's index (zero-based). - - Used to retrieve a pointer to an emitter for a particle system to procedurally change - emission parameters etc. - You should check how many emitters are registered against this system before calling - this method with an arbitrary index using getNumEmitters. - @param - index Zero-based index of the emitter to retrieve. - */ - ParticleEmitter* getEmitter(unsigned short index) const; - - /** Returns the number of emitters for this particle system. */ - unsigned short getNumEmitters(void) const; - - /** Removes an emitter from the system. - - Drops the emitter with the index specified from this system. - You should check how many emitters are registered against this system before calling - this method with an arbitrary index using getNumEmitters. - @param - index Zero-based index of the emitter to retrieve. - */ - void removeEmitter(unsigned short index); - - /** Removes all the emitters from this system. */ - void removeAllEmitters(void); - - /** Removes an emitter from the system. - - Drops the emitter from this system. - @param - emitter Pointer to a particle emitter. - */ - void removeEmitter(ParticleEmitter *emitter); - - /** Adds an affector to this particle system. - - Particles are modified over time in a particle system by affectors - see the ParticleAffector - class for more details. - @param - affectorType String identifying the affector type to create. Affector types are defined - by registering new factories with the manager - see ParticleAffectorFactory for more details. - Affector types can be extended by OGRE, plugin authors or application developers. - */ - ParticleAffector* addAffector(const String& affectorType); - - /** Retrieves an affector by it's index (zero-based). - - Used to retrieve a pointer to an affector for a particle system to procedurally change - affector parameters etc. - You should check how many affectors are registered against this system before calling - this method with an arbitrary index using getNumAffectors. - @param - index Zero-based index of the affector to retrieve. - */ - ParticleAffector* getAffector(unsigned short index) const; - - /** Returns the number of affectors for this particle system. */ - unsigned short getNumAffectors(void) const; - - /** Removes an affector from the system. - - Drops the affector with the index specified from this system. - You should check how many affectors are registered against this system before calling - this method with an arbitrary index using getNumAffectors. - @param - index Zero-based index of the affector to retrieve. - */ - void removeAffector(unsigned short index); - - /** Removes all the affectors from this system. */ - void removeAllAffectors(void); - - /** Empties this set of all particles. - */ - void clear(); - - /** Gets the number of individual particles in the system right now. - - The number of particles active in a system at a point in time depends on - the number of emitters, their emission rates, the time-to-live (TTL) each particle is - given on emission (and whether any affectors modify that TTL) and the maximum - number of particles allowed in this system at once (particle quota). - */ - size_t getNumParticles(void) const; - - /** Manually add a particle to the system. - - Instead of using an emitter, you can manually add a particle to the system. - You must initialise the returned particle instance immediately with the - 'emission' state. - @note - There is no corresponding 'destroyParticle' method - if you want to dispose of a - particle manually (say, if you've used setSpeedFactor(0) to make particles live forever) - you should use getParticle() and modify it's timeToLive to zero, meaning that it will - get cleaned up in the next update. - */ - Particle* createParticle(void); - - /** Manually add an emitter particle to the system. - - The purpose of a particle emitter is to emit particles. Besides visual particles, also other other - particle types can be emitted, other emitters for example. The emitted emitters have a double role; - they behave as particles and can be influenced by affectors, but they are still emitters and capable - to emit other particles (or emitters). It is possible to create a chain of emitters - emitters - emitting other emitters, which also emit emitters. - @param emitterName The name of a particle emitter that must be emitted. - */ - Particle* createEmitterParticle(const String& emitterName); - - /** Retrieve a particle from the system for manual tweaking. - - Normally you use an affector to alter particles in flight, but - for small manually controlled particle systems you might want to use - this method. - */ - Particle* getParticle(size_t index); - - /** Returns the maximum number of particles this system is allowed to have active at once. - - See ParticleSystem::setParticleQuota for more info. - */ - size_t getParticleQuota(void) const; - - /** Sets the maximum number of particles this system is allowed to have active at once. - - Particle systems all have a particle quota, i.e. a maximum number of particles they are - allowed to have active at a time. This allows the application to set a keep particle systems - under control should they be affected by complex parameters which alter their emission rates - etc. If a particle system reaches it's particle quota, none of the emitters will be able to - emit any more particles. As existing particles die, the spare capacity will be allocated - equally across all emitters to be as consistent to the original particle system style as possible. - The quota can be increased but not decreased after the system has been created. - @param quota The maximum number of particles this system is allowed to have. - */ - void setParticleQuota(size_t quota); - - /** Returns the maximum number of emitted emitters this system is allowed to have active at once. - - See ParticleSystem::setEmittedEmitterQuota for more info. - */ - size_t getEmittedEmitterQuota(void) const; - - /** Sets the maximum number of emitted emitters this system is allowed to have active at once. - - Particle systems can have - besides a particle quota - also an emitted emitter quota. - @param quota The maximum number of emitted emitters this system is allowed to have. - */ - void setEmittedEmitterQuota(size_t quota); - - /** Assignment operator for copying. - - This operator deep copies all particle emitters and effectors, but not particles. The - system's name is also not copied. - */ - ParticleSystem& operator=(const ParticleSystem& rhs); - - /** Updates the particles in the system based on time elapsed. - - This is called automatically every frame by OGRE. - @param - timeElapsed The amount of time, in seconds, since the last frame. - */ - void _update(Real timeElapsed); - - /** Returns all active particles in this system. - - This method is designed to be used by people providing new ParticleAffector subclasses, - this is the easiest way to step through all the particles in a system and apply the - changes the affector wants to make. - */ - const std::vector& _getActiveParticles() { return mActiveParticles; } - - /** Sets the name of the material to be used for this billboard set. - */ - virtual void setMaterialName( const String& name, const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME ); - - /** Sets the name of the material to be used for this billboard set. - @return The name of the material that is used for this set. - */ - virtual const String& getMaterialName(void) const; - - void _notifyCurrentCamera(Camera* cam) override; - void _notifyAttached(Node* parent, bool isTagPoint = false) override; - const AxisAlignedBox& getBoundingBox(void) const override { return mAABB; } - Real getBoundingRadius(void) const override { return mBoundingRadius; } - void _updateRenderQueue(RenderQueue* queue) override; - - /// @copydoc MovableObject::visitRenderables - void visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables = false) override; - - /** Fast-forwards this system by the required number of seconds. - - This method allows you to fast-forward a system so that it effectively looks like - it has already been running for the time you specify. This is useful to avoid the - 'startup sequence' of a system, when you want the system to be fully populated right - from the start. - @param - time The number of seconds to fast-forward by. - @param - interval The sampling interval used to generate particles, apply affectors etc. The lower this - is the more realistic the fast-forward, but it takes more iterations to do it. - */ - void fastForward(Real time, Real interval = 0.1f); - - /** Sets a 'speed factor' on this particle system, which means it scales the elapsed - real time which has passed by this factor before passing it to the emitters, affectors, - and the particle life calculation. - - An interesting side effect - if you want to create a completely manual particle system - where you control the emission and life of particles yourself, you can set the speed - factor to 0.0f, thus disabling normal particle emission, alteration, and death. - */ - void setSpeedFactor(Real speedFactor) { mSpeedFactor = speedFactor; } - - /** Gets the 'speed factor' on this particle system. - */ - Real getSpeedFactor(void) const { return mSpeedFactor; } - - /** Sets a 'iteration interval' on this particle system. - - The default Particle system update interval, based on elapsed frame time, - will cause different behavior between low frame-rate and high frame-rate. - By using this option, you can make the particle system update at - a fixed interval, keeping the behavior the same no matter what frame-rate - is. - @par - When iteration interval is set to zero, it means the update occurs based - on an elapsed frame time, otherwise each iteration will take place - at the given interval, repeating until it has used up all the elapsed - frame time. - @param - iterationInterval The iteration interval, default to zero. - */ - void setIterationInterval(Real iterationInterval); - - /** Gets a 'iteration interval' on this particle system. - */ - Real getIterationInterval(void) const { return mIterationInterval; } - - /** Set the default iteration interval for all ParticleSystem instances. - */ - static void setDefaultIterationInterval(Real iterationInterval) { msDefaultIterationInterval = iterationInterval; } - - /** Get the default iteration interval for all ParticleSystem instances. - */ - static Real getDefaultIterationInterval(void) { return msDefaultIterationInterval; } - - /** Sets when the particle system should stop updating after it hasn't been - visible for a while. - - By default, visible particle systems update all the time, even when - not in view. This means that they are guaranteed to be consistent when - they do enter view. However, this comes at a cost, updating particle - systems can be expensive, especially if they are perpetual. - @par - This option lets you set a 'timeout' on the particle system, so that - if it isn't visible for this amount of time, it will stop updating - until it is next visible. - @param timeout The time after which the particle system will be disabled - if it is no longer visible. 0 to disable the timeout and always update. - */ - void setNonVisibleUpdateTimeout(Real timeout); - /** Gets when the particle system should stop updating after it hasn't been - visible for a while. - */ - Real getNonVisibleUpdateTimeout(void) const { return mNonvisibleTimeout; } - - /** Set the default nonvisible timeout for all ParticleSystem instances. - */ - static void setDefaultNonVisibleUpdateTimeout(Real timeout) - { msDefaultNonvisibleTimeout = timeout; } - - /** Get the default nonvisible timeout for all ParticleSystem instances. - */ - static Real getDefaultNonVisibleUpdateTimeout(void) { return msDefaultNonvisibleTimeout; } - - const String& getMovableType(void) const override; - - /** Sets the default dimensions of the particles in this set. - - All particles in a set are created with these default dimensions. The set will render most efficiently if - all the particles in the set are the default size. It is possible to alter the size of individual - particles at the expense of extra calculation. See the Particle class for more info. - @param width - The new default width for the particles in this set. Must be non-negative! - @param height - The new default height for the particles in this set. Must be non-negative! - */ - void setDefaultDimensions(Real width, Real height); - - /** See setDefaultDimensions - this sets 1 component individually. */ - virtual void setDefaultWidth(Real width); - /** See setDefaultDimensions - this gets 1 component individually. */ - virtual Real getDefaultWidth(void) const; - /** See setDefaultDimensions - this sets 1 component individually. */ - virtual void setDefaultHeight(Real height); - /** See setDefaultDimensions - this gets 1 component individually. */ - virtual Real getDefaultHeight(void) const; - /** Returns whether or not particles in this are tested individually for culling. */ - virtual bool getCullIndividually(void) const; - /** Sets whether culling tests particles in this individually as well as in a group. - - Particle sets are always culled as a whole group, based on a bounding box which - encloses all particles in the set. For fairly localised sets, this is enough. However, you - can optionally tell the set to also cull individual particles in the set, i.e. to test - each individual particle before rendering. The default is not to do this. - @par - This is useful when you have a large, fairly distributed set of particles, like maybe - trees on a landscape. You probably still want to group them into more than one - set (maybe one set per section of landscape), which will be culled coarsely, but you also - want to cull the particles individually because they are spread out. Whilst you could have - lots of single-tree sets which are culled separately, this would be inefficient to render - because each tree would be issued as it's own rendering operation. - @par - By calling this method with a parameter of true, you can have large particle sets which - are spaced out and so get the benefit of batch rendering and coarse culling, but also have - fine-grained culling so unnecessary rendering is avoided. - @param cullIndividual If true, each particle is tested before being sent to the pipeline as well - as the whole set having to pass the coarse group bounding test. - */ - virtual void setCullIndividually(bool cullIndividual); - /// Return the resource group to be used to load dependent resources - virtual const String& getResourceGroupName(void) const { return mResourceGroupName; } - /** Get the origin of this particle system, e.g. a script file name. - - This property will only contain something if the creator of - this particle system chose to populate it. Script loaders are advised - to populate it. - */ - const String& getOrigin(void) const { return mOrigin; } - /// Notify this particle system of it's origin - void _notifyOrigin(const String& origin) { mOrigin = origin; } - - /** @copydoc MovableObject::setRenderQueueGroup */ - void setRenderQueueGroup(uint8 queueID) override; - /** @copydoc MovableObject::setRenderQueueGroupAndPriority */ - void setRenderQueueGroupAndPriority(uint8 queueID, ushort priority) override; - - /** Set whether or not particles are sorted according to the camera. - - Enabling sorting alters the order particles are sent to the renderer. - When enabled, particles are sent to the renderer in order of - furthest distance from the camera. - */ - void setSortingEnabled(bool enabled) { mSorted = enabled; } - /// Gets whether particles are sorted relative to the camera. - bool getSortingEnabled(void) const { return mSorted; } - - /** Set the (initial) bounds of the particle system manually. - - If you can, set the bounds of a particle system up-front and - call setBoundsAutoUpdated(false); this is the most efficient way to - organise it. Otherwise, set an initial bounds and let the bounds increase - for a little while (the default is 5 seconds), after which time the - AABB is fixed to save time. - @param aabb Bounds in local space. - */ - void setBounds(const AxisAlignedBox& aabb); - - /** Sets whether the bounds will be automatically updated - for the life of the particle system - - If you have a stationary particle system, it would be a good idea to - call this method and set the value to 'false', since the maximum - bounds of the particle system will eventually be static. If you do - this, you can either set the bounds manually using the setBounds() - method, or set the second parameter of this method to a positive - number of seconds, so that the bounds are calculated for a few - seconds and then frozen. - @param autoUpdate If true (the default), the particle system will - update it's bounds every frame. If false, the bounds update will - cease after the 'stopIn' number of seconds have passed. - @param stopIn Only applicable if the first parameter is true, this is the - number of seconds after which the automatic update will cease. - */ - void setBoundsAutoUpdated(bool autoUpdate, Real stopIn = 0.0f); - - /** Sets whether particles (and any affector effects) remain relative - to the node the particle system is attached to. - - By default particles are in world space once emitted, so they are not - affected by movement in the parent node of the particle system. This - makes the most sense when dealing with completely independent particles, - but if you want to constrain them to follow local motion too, you - can set this to true. - */ - void setKeepParticlesInLocalSpace(bool keepLocal); - - /** Gets whether particles (and any affector effects) remain relative - to the node the particle system is attached to. - */ - bool getKeepParticlesInLocalSpace(void) const { return mLocalSpace; } - - /** Internal method for updating the bounds of the particle system. - - This is called automatically for a period of time after the system's - creation (10 seconds by default, settable by setBoundsAutoUpdated) - to increase (and only increase) the bounds of the system according - to the emitted and affected particles. After this period, the - system is assumed to achieved its maximum size, and the bounds are - no longer computed for efficiency. You can tweak the behaviour by - either setting the bounds manually (setBounds, preferred), or - changing the time over which the bounds are updated (performance cost). - You can also call this method manually if you need to update the - bounds on an ad-hoc basis. - */ - void _updateBounds(void); - - /** This is used to turn on or off particle emission for this system. - - By default particle system is always emitting particles (if a emitters exists) - and this can be used to stop the emission for all emitters. To turn it on again, - call it passing true. - - Note that this does not detach the particle system from the scene node, it will - still use some CPU. - */ - void setEmitting(bool v); - - /** Returns true if the particle system emitting flag is turned on. - - This function will not actually return whether the particles are being emitted. - It only returns the value of emitting flag. - */ - bool getEmitting() const; - - /// Override to return specific type flag - uint32 getTypeFlags(void) const override; - private: - AxisAlignedBox mAABB; - Real mBoundingRadius; - bool mBoundsAutoUpdate; - Real mBoundsUpdateTime; - Real mUpdateRemainTime; - - /// Name of the resource group to use to load materials - String mResourceGroupName; - /// Have we set the material etc on the renderer? - bool mIsRendererConfigured; - /// Pointer to the material to use - MaterialPtr mMaterial; - /// Default width of each particle - Real mDefaultWidth; - /// Default height of each particle - Real mDefaultHeight; - /// Speed factor - Real mSpeedFactor; - /// Iteration interval - Real mIterationInterval; - /// Iteration interval set? Otherwise track default - bool mIterationIntervalSet; - /// Particles sorted according to camera? - bool mSorted; - /// Particles in local space? - bool mLocalSpace; - /// Update timeout when nonvisible (0 for no timeout) - Real mNonvisibleTimeout; - /// Update timeout when nonvisible set? Otherwise track default - bool mNonvisibleTimeoutSet; - /// Amount of time non-visible so far - Real mTimeSinceLastVisible; - /// Last frame in which known to be visible - unsigned long mLastVisibleFrame; - /// Controller for time update - ControllerFloat* mTimeController; - /// Indication whether the emitted emitter pool (= pool with particle emitters that are emitted) is initialised - bool mEmittedEmitterPoolInitialised; - /// Used to control if the particle system should emit particles or not. - bool mIsEmitting; - - typedef std::vector ParticlePool; - - /** Sort by direction functor */ - struct SortByDirectionFunctor - { - /// Direction to sort in - Vector3 sortDir; - - SortByDirectionFunctor(const Vector3& dir); - float operator()(Particle* p) const; - }; - - /** Sort by distance functor */ - struct SortByDistanceFunctor - { - /// Position to sort in - Vector3 sortPos; - - SortByDistanceFunctor(const Vector3& pos); - float operator()(Particle* p) const; - }; - - /** Active particle list. - - This is a linked list of pointers to particles in the particle pool. - @par - This allows very fast insertions and deletions from anywhere in - the list to activate / deactivate particles as well as reuse of - Particle instances in the pool without construction & destruction - which avoids memory thrashing. - */ - ParticlePool mActiveParticles; - - /** Free particle queue. - - This contains a list of the particles free for use as new instances - as required by the set. Particle instances are preconstructed up - to the estimated size in the mParticlePool vector and are - referenced on this deque at startup. As they get used this list - reduces, as they get released back to to the set they get added - back to the list. - */ - ParticlePool mFreeParticles; - - /** Pool of particle instances for use and reuse in the active particle list. - - This vector will be preallocated with the estimated size of the set,and will extend as required. - */ - ParticlePool mParticlePool; - - typedef std::list FreeEmittedEmitterList; - typedef std::list ActiveEmittedEmitterList; - typedef std::vector EmittedEmitterList; - typedef std::map FreeEmittedEmitterMap; - typedef std::map EmittedEmitterPool; - - /** Pool of emitted emitters for use and reuse in the active emitted emitter list. - - The emitters in this pool act as particles and as emitters. The pool is a map containing lists - of emitters, identified by their name. - @par - The emitters in this pool are cloned using emitters that are kept in the main emitter list - of the ParticleSystem. - */ - EmittedEmitterPool mEmittedEmitterPool; - - /** Free emitted emitter list. - - This contains a list of the emitters free for use as new instances as required by the set. - */ - FreeEmittedEmitterMap mFreeEmittedEmitters; - - /** Active emitted emitter list. - - This is a linked list of pointers to emitters in the emitted emitter pool. - Emitters that are used are stored (their pointers) in both the list with active particles and in - the list with active emitted emitters. */ - ActiveEmittedEmitterList mActiveEmittedEmitters; - - typedef std::vector ParticleEmitterList; - typedef std::vector ParticleAffectorList; - - /// List of particle emitters, ie sources of particles - ParticleEmitterList mEmitters; - /// List of particle affectors, ie modifiers of particles - ParticleAffectorList mAffectors; - - /// The renderer used to render this particle system - ParticleSystemRenderer* mRenderer; - - /// Do we cull each particle individually? - bool mCullIndividual; - - /// The name of the type of renderer used to render this system - String mRendererType; - - /// The number of particles in the pool. - size_t mPoolSize; - - /// The number of emitted emitters in the pool. - size_t mEmittedEmitterPoolSize; - - /// Optional origin of this particle system (eg script name) - String mOrigin; - - /// Default iteration interval - static Real msDefaultIterationInterval; - /// Default nonvisible update timeout - static Real msDefaultNonvisibleTimeout; - - /** Internal method used to expire dead particles. */ - void _expire(Real timeElapsed); - - /** Spawn new particles based on free quota and emitter requirements. */ - void _triggerEmitters(Real timeElapsed); - - /** Helper function that actually performs the emission of particles - */ - void _executeTriggerEmitters(ParticleEmitter* emitter, unsigned requested, Real timeElapsed); - - /** Updates existing particle based on their momentum. */ - void _applyMotion(Real timeElapsed); - - /** Applies the effects of affectors. */ - void _triggerAffectors(Real timeElapsed); - - /** Sort the particles in the system **/ - void _sortParticles(Camera* cam); - - /** Resize the internal pool of particles. */ - void increasePool(size_t size); - - /** Resize the internal pool of emitted emitters. - - The pool consists of multiple vectors containing pointers to particle emitters. Increasing the - pool with size implies that the vectors are equally increased. The quota of emitted emitters is - defined on a particle system level and not on a particle emitter level. This is to prevent that - the number of created emitters becomes too high; the quota is shared amongst the emitted emitters. - */ - void increaseEmittedEmitterPool(size_t size); - - /** Internal method for initialising string interface. */ - void initParameters(void); - - /** Internal method to configure the renderer. */ - void configureRenderer(void); - - /** Create a pool of emitted emitters and assign them to the free emitter list. - - The emitters in the pool are grouped by name. This name is the name of the base emitter in the - main list with particle emitters, which forms the template of the created emitted emitters. - */ - void initialiseEmittedEmitters(void); - - /** Determine which emitters in the Particle Systems main emitter become a template for creating an - pool of emitters that can be emitted. - */ - void initialiseEmittedEmitterPool(void); - - /** Add emitters from the pool to the free emitted emitter queue. */ - void addFreeEmittedEmitters(void); - - /** Removes all emitted emitters from this system. */ - void removeAllEmittedEmitters(void); - - /** Find the list with free emitted emitters. - @param name The name that identifies the list with free emitted emitters. - */ - FreeEmittedEmitterList* findFreeEmittedEmitter (const String& name); - - /** Removes an emitter from the active emitted emitter list. - - The emitter will not be destroyed! - @param emitter Pointer to a particle emitter. - */ - void removeFromActiveEmittedEmitters (ParticleEmitter* emitter); - - /** Moves all emitted emitters from the active list to the free list - - The active emitted emitter list will not be cleared and still keeps references to the emitters! - */ - void addActiveEmittedEmittersToFreeList (void); - - /** This function clears all data structures that are used in combination with emitted emitters and - sets the flag to indicate that the emitted emitter pool must be initialised again. - - This function should be called if new emitters are added to a ParticleSystem or deleted from a - ParticleSystem. The emitted emitter data structures become out of sync and need to be build up - again. The data structures are not reorganised in this function, but by setting a flag, - they are rebuild in the regular process flow. - */ - void _notifyReorganiseEmittedEmitterData (void); - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreParticleSystemManager.h b/OgreMain/include/OgreParticleSystemManager.h deleted file mode 100644 index 5bee95ca3cc..00000000000 --- a/OgreMain/include/OgreParticleSystemManager.h +++ /dev/null @@ -1,333 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ParticleSystemManager_H__ -#define __ParticleSystemManager_H__ - - -#include "OgrePrerequisites.h" -#include "OgreSingleton.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - // Forward decl - class ParticleSystemFactory; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - /** Manages particle systems, particle system scripts (templates) and the - available emitter & affector factories. - - This singleton class is responsible for managing particle - systems. Although, the user interface to creating them is via - SceneManager. Remember that like all other MovableObject - subclasses, ParticleSystems do not get rendered until they are - attached to a SceneNode object. - - This class also manages factories for ParticleEmitter and - ParticleAffector classes. To enable easy extensions to the types of - emitters (particle sources) and affectors (particle modifiers), the - ParticleSystemManager lets plugins or applications register factory - classes which submit new subclasses to ParticleEmitter and - ParticleAffector. The actual implementations, - such as cone, sphere and box-shaped emitters, and simple affectors such - as constant directional force and colour faders are provided by the @ref ParticleFX Plugin shipped with %Ogre. - However using this registration process, a custom plugin can create any behaviour required. - - This class also manages the loading and parsing of particle system - scripts, which are text files describing named particle system - templates. Instances of particle systems using these templates can - then be created easily through the SceneManager::createParticleSystem method. - */ - class _OgreExport ParticleSystemManager : public Singleton - { - friend class ParticleSystemFactory; - public: - typedef std::map ParticleTemplateMap; - typedef std::map ParticleAffectorFactoryMap; - typedef std::map ParticleEmitterFactoryMap; - typedef std::map ParticleSystemRendererFactoryMap; - private: - OGRE_AUTO_MUTEX; - - /// Templates based on scripts - ParticleTemplateMap mSystemTemplates; - - /// Factories for named emitter types (can be extended using plugins) - ParticleEmitterFactoryMap mEmitterFactories; - - /// Factories for named affector types (can be extended using plugins) - ParticleAffectorFactoryMap mAffectorFactories; - - /// Map of renderer types to factories - ParticleSystemRendererFactoryMap mRendererFactories; - - StringVector mScriptPatterns; - - // Factory instance - ParticleSystemFactory* mFactory; - - /// Internal implementation of createSystem - ParticleSystem* createSystemImpl(const String& name, size_t quota, - const String& resourceGroup); - /// Internal implementation of createSystem - ParticleSystem* createSystemImpl(const String& name, const String& templateName); - - public: - - ParticleSystemManager(); - virtual ~ParticleSystemManager(); - - /** Adds a new 'factory' object for emitters to the list of available emitter types. - - This method allows plugins etc to add new particle emitter types to Ogre. Particle emitters - are sources of particles, and generate new particles with their start positions, colours and - momentums appropriately. Plugins would create new subclasses of ParticleEmitter which - emit particles a certain way, and register a subclass of ParticleEmitterFactory to create them (since multiple - emitters can be created for different particle systems). - @par - All particle emitter factories have an assigned name which is used to identify the emitter - type. This must be unique. - @par - Note that the object passed to this function will not be destroyed by the ParticleSystemManager, - since it may have been allocated on a different heap in the case of plugins. The caller must - destroy the object later on, probably on plugin shutdown. - @param factory - Pointer to a ParticleEmitterFactory subclass created by the plugin or application code. - */ - void addEmitterFactory(ParticleEmitterFactory* factory); - - /** Adds a new 'factory' object for affectors to the list of available affector types. - - This method allows plugins etc to add new particle affector types to Ogre. Particle - affectors modify the particles in a system a certain way such as affecting their direction - or changing their colour, lifespan etc. Plugins would - create new subclasses of ParticleAffector which affect particles a certain way, and register - a subclass of ParticleAffectorFactory to create them. - @par - All particle affector factories have an assigned name which is used to identify the affector - type. This must be unique. - @par - Note that the object passed to this function will not be destroyed by the ParticleSystemManager, - since it may have been allocated on a different heap in the case of plugins. The caller must - destroy the object later on, probably on plugin shutdown. - @param factory - Pointer to a ParticleAffectorFactory subclass created by the plugin or application code. - */ - void addAffectorFactory(ParticleAffectorFactory* factory); - - /** Registers a factory class for creating ParticleSystemRenderer instances. - @par - Note that the object passed to this function will not be destroyed by the ParticleSystemManager, - since it may have been allocated on a different heap in the case of plugins. The caller must - destroy the object later on, probably on plugin shutdown. - @param factory - Pointer to a ParticleSystemRendererFactory subclass created by the plugin or application code. - */ - void addRendererFactory(ParticleSystemRendererFactory* factory); - - /** Adds a new particle system template to the list of available templates. - - Instances of particle systems in a scene are not normally unique - often you want to place the - same effect in many places. This method allows you to register a ParticleSystem as a named template, - which can subsequently be used to create instances using the createSystem method. - @par - Note that particle system templates can either be created programmatically by an application - and registered using this method, or they can be defined in a script file (*.particle) which is - loaded by the engine at startup, very much like Material scripts. - @param name - The name of the template. Must be unique across all templates. - @param sysTemplate - A pointer to a particle system to be used as a template. The manager - will take over ownership of this pointer. - - */ - void addTemplate(const String& name, ParticleSystem* sysTemplate); - - /** Removes a specified template from the ParticleSystemManager. - - This method removes a given template from the particle system manager, optionally deleting - the template if the deleteTemplate method is called. Throws an exception if the template - could not be found. - @param name - The name of the template to remove. - @param deleteTemplate - Whether or not to delete the template before removing it. - */ - void removeTemplate(const String& name, bool deleteTemplate = true); - - /** Removes a specified template from the ParticleSystemManager. - - This method removes all templates from the ParticleSystemManager. - @param deleteTemplate - Whether or not to delete the templates before removing them. - */ - void removeAllTemplates(bool deleteTemplate = true); - - - /** Removes all templates that belong to a specific Resource Group from the ParticleSystemManager. - - This method removes all templates that belong in a particular resource group from the ParticleSystemManager. - @param resourceGroup - Resource group to delete templates for - */ - void removeTemplatesByResourceGroup(const String& resourceGroup); - - /** Create a new particle system template. - - This method is similar to the addTemplate method, except this just creates a new template - and returns a pointer to it to be populated. Use this when you don't already have a system - to add as a template and just want to create a new template which you will build up in-place. - @param name - The name of the template. Must be unique across all templates. - @param resourceGroup - The name of the resource group which will be used to - load any dependent resources. - - */ - ParticleSystem* createTemplate(const String& name, const String& resourceGroup); - - /** Retrieves a particle system template for possible modification. - - Modifying a template does not affect the settings on any ParticleSystems already created - from this template. - */ - ParticleSystem* getTemplate(const String& name); - - /** Internal method for creating a new emitter from a factory. - - Used internally by the engine to create new ParticleEmitter instances from named - factories. Applications should use the ParticleSystem::addEmitter method instead, - which calls this method to create an instance. - @param emitterType - String name of the emitter type to be created. A factory of this type must have been registered. - @param psys - The particle system this is being created for - */ - ParticleEmitter* _createEmitter(const String& emitterType, ParticleSystem* psys); - - /** Internal method for destroying an emitter. - - Because emitters are created by factories which may allocate memory from separate heaps, - the memory allocated must be freed from the same place. This method is used to ask the factory - to destroy the instance passed in as a pointer. - @param emitter - Pointer to emitter to be destroyed. On return this pointer will point to invalid (freed) memory. - */ - void _destroyEmitter(ParticleEmitter* emitter); - - /** Internal method for creating a new affector from a factory. - - Used internally by the engine to create new ParticleAffector instances from named - factories. Applications should use the ParticleSystem::addAffector method instead, - which calls this method to create an instance. - @param affectorType - String name of the affector type to be created. A factory of this type must have been registered. - @param psys - The particle system it is being created for - */ - ParticleAffector* _createAffector(const String& affectorType, ParticleSystem* psys); - - /** Internal method for destroying an affector. - - Because affectors are created by factories which may allocate memory from separate heaps, - the memory allocated must be freed from the same place. This method is used to ask the factory - to destroy the instance passed in as a pointer. - @param affector - Pointer to affector to be destroyed. On return this pointer will point to invalid (freed) memory. - */ - void _destroyAffector(ParticleAffector* affector); - - /** Internal method for creating a new renderer from a factory. - - Used internally by the engine to create new ParticleSystemRenderer instances from named - factories. Applications should use the ParticleSystem::setRenderer method instead, - which calls this method to create an instance. - @param rendererType - String name of the renderer type to be created. A factory of this type must have been registered. - */ - ParticleSystemRenderer* _createRenderer(const String& rendererType); - - /** Internal method for destroying a renderer. - - Because renderer are created by factories which may allocate memory from separate heaps, - the memory allocated must be freed from the same place. This method is used to ask the factory - to destroy the instance passed in as a pointer. - @param renderer - Pointer to renderer to be destroyed. On return this pointer will point to invalid (freed) memory. - */ - void _destroyRenderer(ParticleSystemRenderer* renderer); - - /** Init method to be called by OGRE system. - - Due to dependencies between various objects certain initialisation tasks cannot be done - on construction. OGRE will call this method when the rendering subsystem is initialised. - */ - void _initialise(void); - - typedef MapIterator ParticleAffectorFactoryIterator; - typedef MapIterator ParticleEmitterFactoryIterator; - typedef MapIterator ParticleRendererFactoryIterator; - /** Return an iterator over the affector factories currently registered */ - ParticleAffectorFactoryIterator getAffectorFactoryIterator(void); - /** Return an iterator over the emitter factories currently registered */ - ParticleEmitterFactoryIterator getEmitterFactoryIterator(void); - /** Return an iterator over the renderer factories currently registered */ - ParticleRendererFactoryIterator getRendererFactoryIterator(void); - - - typedef MapIterator ParticleSystemTemplateIterator; - /** Gets an iterator over the list of particle system templates. */ - ParticleSystemTemplateIterator getTemplateIterator(void) - { - return ParticleSystemTemplateIterator( - mSystemTemplates.begin(), mSystemTemplates.end()); - } - - /** Get an instance of ParticleSystemFactory (internal use). */ - ParticleSystemFactory* _getFactory(void) { return mFactory; } - - /// @copydoc Singleton::getSingleton() - static ParticleSystemManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static ParticleSystemManager* getSingletonPtr(void); - - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreParticleSystemRenderer.h b/OgreMain/include/OgreParticleSystemRenderer.h deleted file mode 100644 index 9622a4f22a3..00000000000 --- a/OgreMain/include/OgreParticleSystemRenderer.h +++ /dev/null @@ -1,126 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ParticleSystemRenderer_H__ -#define __ParticleSystemRenderer_H__ - -#include "OgrePrerequisites.h" -#include "OgreStringInterface.h" -#include "OgreFactoryObj.h" -#include "OgreRenderQueue.h" -#include "OgreCommon.h" -#include "OgreRenderable.h" - -namespace Ogre { - class ParticleVisualData; - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - /** Abstract class defining the interface required to be implemented - by classes which provide rendering capability to ParticleSystem instances. - */ - class _OgreExport ParticleSystemRenderer : public StringInterface, public FXAlloc - { - public: - /// Constructor - ParticleSystemRenderer() {} - /// Destructor - virtual ~ParticleSystemRenderer() {} - - /** Gets the type of this renderer - must be implemented by subclasses */ - virtual const String& getType(void) const = 0; - - /** Delegated to by ParticleSystem::_updateRenderQueue - - The subclass must update the render queue using whichever Renderable - instance(s) it wishes. - */ - virtual void _updateRenderQueue(RenderQueue* queue, - std::vector& currentParticles, bool cullIndividually) = 0; - - /** Sets the material this renderer must use; called by ParticleSystem. */ - virtual void _setMaterial(MaterialPtr& mat) = 0; - /** Delegated to by ParticleSystem::_notifyCurrentCamera */ - virtual void _notifyCurrentCamera(Camera* cam) = 0; - /** Delegated to by ParticleSystem::_notifyAttached */ - virtual void _notifyAttached(Node* parent, bool isTagPoint = false) = 0; - /** Tells the renderer that the particle quota has changed */ - virtual void _notifyParticleQuota(size_t quota) = 0; - /** Tells the renderer that the particle default size has changed */ - virtual void _notifyDefaultDimensions(Real width, Real height) = 0; - /** Optional callback notified when particle emitted */ - virtual void _notifyParticleEmitted(Particle* particle) {} - /** Optional callback notified when particle expired */ - virtual void _notifyParticleExpired(Particle* particle) {} - /** Optional callback notified when particles moved */ - virtual void _notifyParticleMoved(std::vector& currentParticles) {} - /** Optional callback notified when particles cleared */ - virtual void _notifyParticleCleared(std::vector& currentParticles) {} - /// @deprecated do not use - OGRE_DEPRECATED ParticleVisualData* _createVisualData(void) { return 0; } - /// @deprecated do not use - OGRE_DEPRECATED void _destroyVisualData(ParticleVisualData*) {} - - /** Sets which render queue group this renderer should target with it's - output. - */ - virtual void setRenderQueueGroup(uint8 queueID) = 0; - /** Sets which render queue group and priority this renderer should target with it's - output. - */ - virtual void setRenderQueueGroupAndPriority(uint8 queueID, ushort priority) = 0; - - /** Setting carried over from ParticleSystem. - */ - virtual void setKeepParticlesInLocalSpace(bool keepLocal) = 0; - - /** Gets the desired particles sort mode of this renderer */ - virtual SortMode _getSortMode(void) const = 0; - - /** Required method to allow the renderer to communicate the Renderables - it will be using to render the system to a visitor. - @see MovableObject::visitRenderables - */ - virtual void visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables = false) = 0; - - /// Tells the Renderer about the ParticleSystem bounds - virtual void _notifyBoundingBox(const AxisAlignedBox& aabb) {} - - /// Tells the Renderer whether to cast shadows - virtual void _notifyCastShadows(bool enabled) {} - }; - - /** @} */ - /** @} */ - -} - -#endif diff --git a/OgreMain/include/OgrePass.h b/OgreMain/include/OgrePass.h deleted file mode 100644 index d9a2d48aaf5..00000000000 --- a/OgreMain/include/OgrePass.h +++ /dev/null @@ -1,1562 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Pass_H__ -#define __Pass_H__ - -#include "OgrePrerequisites.h" -#include "OgreColourValue.h" -#include "OgreCommon.h" -#include "OgreLight.h" -#include "OgreTextureUnitState.h" -#include "OgreUserObjectBindings.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Materials - * @{ - */ - /// Categorisation of passes for the purpose of additive lighting - enum IlluminationStage : uint8 - { - /// Part of the rendering which occurs without any kind of direct lighting - IS_AMBIENT, - /// Part of the rendering which occurs per light - IS_PER_LIGHT, - /// Post-lighting rendering - IS_DECAL, - /// Not determined - IS_UNKNOWN - }; - - /** Class defining a single pass of a Technique (of a Material): a single rendering call. - - If a pass does not explicitly use a vertex or fragment shader, %Ogre will calculate - lighting based on the [Direct3D Light Model](https://docs.microsoft.com/en-us/windows/win32/direct3d9/mathematics-of-lighting) as: - - If at least one shader is used, the pass is considered *programmable* and the lighting is - up to the shader. - - Rendering can be repeated with many passes for more complex effects. - - @copydetails setLightingEnabled - - @par Lighting disabled - - $$ passBase = C $$ - - where \f$C = (1, 1, 1)\f$ or a tracked vertex attribute if #TVC_DIFFUSE is set. - - @par Lighting enabled - - \f[ passBase = G_a \cdot C_a + \sum^N_i ( C_d \cdot L^{(i)}_d + C_s \cdot L^{(i)}_s ) + C_e \f] - - where - - \f$G_a\f$ is the ambient colour defined by the SceneManager - - \f$C_a\f$ is the pass ambient colour - - \f$C_e\f$ is the pass self-illumination colour or a tracked vertex attribute - - \f$N\f$ is the number of lights considered during light iteration - - \f$C_d\f$ is the pass diffuse colour or a tracked vertex attribute - - \f$C_s\f$ is the pass specular colour or a tracked vertex attribute - - \f$L_d^{(i)}\f$ is the (attenuated) diffuse colour of the i-th Light - - \f$L_s^{(i)}\f$ is the (attenuated) specular colour of the i-th Light - - @par Programmable passes - - Programmable passes are complex to define, because they require custom - programs and you have to set all constant inputs to the programs (like - the position of lights, any base material colours you wish to use etc), but - they do give you much total flexibility over the algorithms used to render your - pass, and you can create some effects which are impossible with a fixed-function pass. - On the other hand, you can define a fixed-function pass in very little time, and - you can use a range of fixed-function effects like environment mapping very - easily, plus your pass will be more likely to be compatible with older hardware. - There are pros and cons to both, just remember that if you use a programmable - pass to create some great effects, allow more time for definition and testing. - */ - class _OgreExport Pass : public PassAlloc - { - public: - /** Definition of a functor for calculating the hashcode of a Pass. - - The hashcode of a Pass is used to sort Passes for rendering, in order - to reduce the number of render state changes. Each Pass represents a - single unique set of states, but by ordering them, state changes can - be minimised between passes. An implementation of this functor should - order passes so that the elements that you want to keep constant are - sorted next to each other. - - Hash format is 32-bit, divided as follows (high to low bits) - bits purpose - 4 Pass index (i.e. max 16 passes!). - 28 Pass contents - - @note the high bits returned by this function will get overwritten - - @see Pass::setHashFunc - */ - struct HashFunc - { - virtual uint32 operator()(const Pass* p) const = 0; - /// Need virtual destructor in case subclasses use it - virtual ~HashFunc() {} - }; - - typedef std::vector TextureUnitStates; - private: - Technique* mParent; - String mName; /// Optional name for the pass - uint32 mHash; /// Pass hash - //------------------------------------------------------------------------- - // Colour properties, only applicable in fixed-function passes - ColourValue mAmbient; - ColourValue mDiffuse; - ColourValue mSpecular; - ColourValue mEmissive; - float mShininess; - TrackVertexColourType mTracking; - //------------------------------------------------------------------------- - ColourBlendState mBlendState; - - /// Needs to be dirtied when next loaded - bool mHashDirtyQueued : 1; - // Depth buffer settings - bool mDepthCheck : 1; - bool mDepthWrite : 1; - bool mAlphaToCoverageEnabled : 1; - /// Transparent depth sorting - bool mTransparentSorting : 1; - /// Transparent depth sorting forced - bool mTransparentSortingForced : 1; - /// Lighting enabled? - bool mLightingEnabled : 1; - /// Run this pass once per light? - bool mIteratePerLight : 1; - /// Should it only be run for a certain light type? - bool mRunOnlyForOneLightType : 1; - bool mPolygonModeOverrideable : 1; - bool mFogOverride : 1; - /// Is this pass queued for deletion? - bool mQueuedForDeletion : 1; - /// Scissoring for the light? - bool mLightScissoring : 1; - /// User clip planes for light? - bool mLightClipPlanes : 1; - bool mPointSpritesEnabled : 1; - bool mPointAttenuationEnabled : 1; - mutable bool mContentTypeLookupBuilt : 1; - - uchar mAlphaRejectVal; - - float mDepthBiasConstant; - float mDepthBiasSlopeScale; - float mDepthBiasPerIteration; - - CompareFunction mDepthFunc; - // Alpha reject settings - CompareFunction mAlphaRejectFunc; - - //------------------------------------------------------------------------- - - //------------------------------------------------------------------------- - // Culling mode - CullingMode mCullMode; - ManualCullingMode mManualCullMode; - //------------------------------------------------------------------------- - - /// Max simultaneous lights - unsigned short mMaxSimultaneousLights; - /// Starting light index - unsigned short mStartLight; - /// Iterate per how many lights? - unsigned short mLightsPerIteration; - - ushort mIndex; /// Pass index - - /// With a specific light mask? - uint32 mLightMask; - - //------------------------------------------------------------------------- - // Fog - ColourValue mFogColour; - float mFogStart; - float mFogEnd; - float mFogDensity; - //------------------------------------------------------------------------- - /// line width - float mLineWidth; - /// Storage of texture unit states - TextureUnitStates mTextureUnitStates; - - // TU Content type lookups - typedef std::vector ContentTypeLookup; - mutable ContentTypeLookup mShadowContentTypeLookup; - - /// Vertex program details - std::unique_ptr mProgramUsage[GPT_COUNT]; - /// Number of pass iterations to perform - size_t mPassIterationCount; - /// Point size, applies when not using per-vertex point size - float mPointMinSize; - float mPointMaxSize; - /// Size, Constant, linear, quadratic coeffs - Vector4f mPointAttenution; - - /// User objects binding. - UserObjectBindings mUserObjectBindings; - - /// Shading options - ShadeOptions mShadeOptions; - /// Polygon mode - PolygonMode mPolygonMode; - /// Illumination stage? - IlluminationStage mIlluminationStage; - - Light::LightTypes mOnlyLightType; - FogMode mFogMode; - - public: - typedef std::set PassSet; - private: - /// List of Passes whose hashes need recalculating - static PassSet msDirtyHashList; - /// The place where passes go to die - static PassSet msPassGraveyard; - /// The Pass hash functor - static HashFunc* msHashFunc; - public: - OGRE_STATIC_MUTEX(msDirtyHashListMutex); - OGRE_STATIC_MUTEX(msPassGraveyardMutex); - OGRE_MUTEX(mTexUnitChangeMutex); - OGRE_MUTEX(mGpuProgramChangeMutex); - /// Default constructor - Pass(Technique* parent, unsigned short index); - /// Copy constructor - Pass(Technique* parent, unsigned short index, const Pass& oth ); - - ~Pass(); - - /// Operator = overload - Pass& operator=(const Pass& oth); - - size_t calculateSize(void) const; - - /// Gets the index of this Pass in the parent Technique - unsigned short getIndex(void) const { return mIndex; } - /** Set the name of the pass - - The name of the pass is optional. Its useful in material scripts where a material could inherit - from another material and only want to modify a particular pass. - */ - void setName(const String& name) { mName = name; } - /// Get the name of the pass - const String& getName(void) const { return mName; } - - /// @name Surface properties - /// @{ - /** Sets the ambient colour reflectance properties of this pass. - - This property determines how much ambient light (directionless global light) is - reflected. The default is full white, meaning objects are completely globally - illuminated. Reduce this if you want to see diffuse or specular light effects, or change - the blend of colours to make the object have a base colour other than white. - - It is also possible to make the ambient reflectance track the vertex colour as defined in - the mesh instead of the colour values. - @note - This setting has no effect if dynamic lighting is disabled (see - Ogre::Pass::setLightingEnabled), or, if any texture layer has a Ogre::LBO_REPLACE - attribute. - */ - void setAmbient(float red, float green, float blue); - - /// @overload - void setAmbient(const ColourValue& ambient) { mAmbient = ambient; } - - /** Sets the diffuse colour reflectance properties of this pass. - - This property determines how much diffuse light (light from instances - of the Light class in the scene) is reflected. The default is full white, meaning objects - reflect the maximum white light they can from Light objects. - - It is also possible to make the diffuse reflectance track the vertex colour as defined in - the mesh instead of the colour values. - @note - This setting has no effect if dynamic lighting is disabled (see - Ogre::Pass::setLightingEnabled), or, if any texture layer has a Ogre::LBO_REPLACE - attribute. - */ - void setDiffuse(float red, float green, float blue, float alpha); - - /// @overload - void setDiffuse(const ColourValue& diffuse) { mDiffuse = diffuse; } - - /** Sets the specular colour reflectance properties of this pass. - - This property determines how much specular light (highlights from instances of the Light - class in the scene) is reflected. The default is to reflect no specular light. - - It is also possible to make the specular reflectance track the vertex colour as defined in - the mesh instead of the colour values. - @note - The size of the specular highlights is determined by the separate 'shininess' property. - @note - This setting has no effect if dynamic lighting is disabled (see - Ogre::Pass::setLightingEnabled), or, if any texture layer has a Ogre::LBO_REPLACE - attribute. - */ - void setSpecular(float red, float green, float blue, float alpha); - - /// @overload - void setSpecular(const ColourValue& specular) { mSpecular = specular; } - - /** Sets the shininess of the pass, affecting the size of specular highlights. - - The higher the value of the shininess parameter, the sharper the highlight i.e. the radius - is smaller. Beware of using shininess values in the range of 0 to 1 since this causes the - the specular colour to be applied to the whole surface that has the material applied to it. - When the viewing angle to the surface changes, ugly flickering will also occur when - shininess is in the range of 0 to 1. Shininess values between 1 and 128 work best in both - DirectX and OpenGL renderers. - @note - This setting has no effect if dynamic lighting is disabled (see - Ogre::Pass::setLightingEnabled), or, if any texture layer has a Ogre::LBO_REPLACE - attribute. - */ - void setShininess(float val) { mShininess = val; } - - /** Sets the amount of self-illumination an object has. - - If an object is self-illuminating, it does not need external sources to light it, ambient or - otherwise. It's like the object has it's own personal ambient light. This property is rarely useful since - you can already specify per-pass ambient light, but is here for completeness. - - It is also possible to make the emissive reflectance track the vertex colour as defined in - the mesh instead of the colour values. - @note - This setting has no effect if dynamic lighting is disabled (see - Ogre::Pass::setLightingEnabled), or, if any texture layer has a Ogre::LBO_REPLACE - attribute. - */ - void setSelfIllumination(float red, float green, float blue); - - /// @overload - void setSelfIllumination(const ColourValue& selfIllum) { mEmissive = selfIllum; } - - /// @copydoc setSelfIllumination - void setEmissive(float red, float green, float blue) { setSelfIllumination(red, green, blue); } - /// @overload - void setEmissive(const ColourValue& emissive) { setSelfIllumination(emissive); } - - /** Sets which material properties follow the vertex colour - */ - void setVertexColourTracking(TrackVertexColourType tracking) { mTracking = tracking; } - - /** Gets the ambient colour reflectance of the pass. - */ - const ColourValue& getAmbient(void) const { return mAmbient; } - - /** Gets the diffuse colour reflectance of the pass. - */ - const ColourValue& getDiffuse(void) const { return mDiffuse; } - - /** Gets the specular colour reflectance of the pass. - */ - const ColourValue& getSpecular(void) const { return mSpecular; } - - /** Gets the self illumination colour of the pass. - */ - const ColourValue& getSelfIllumination(void) const { return mEmissive; } - - /** Gets the self illumination colour of the pass. - @see - getSelfIllumination - */ - const ColourValue& getEmissive(void) const { return getSelfIllumination(); } - - /** Gets the 'shininess' property of the pass (affects specular highlights). - */ - float getShininess(void) const { return mShininess; } - - /** Gets which material properties follow the vertex colour - */ - TrackVertexColourType getVertexColourTracking(void) const { return mTracking; } - - /** Sets whether or not dynamic lighting is enabled. - - Turning dynamic lighting off makes any ambient, diffuse, specular, emissive and shading - properties for this pass redundant. - If lighting is turned off, all objects rendered using the pass will be fully lit. - When lighting is turned on, objects are lit according - to their vertex normals for diffuse and specular light, and globally for ambient and - emissive. - */ - void setLightingEnabled(bool enabled) { mLightingEnabled = enabled; } - - /** Returns whether or not dynamic lighting is enabled. - */ - bool getLightingEnabled(void) const { return mLightingEnabled; } - /// @} - - /** - * set the line width for this pass - * - * This property determines what width is used to render lines. - * @note some drivers only support a value of 1.0 here - */ - void setLineWidth(float width) { mLineWidth = width; } - float getLineWidth() const { return mLineWidth; } - - /// @name Point Sprites - /// @{ - /** Gets the point size of the pass. - - This property determines what point size is used to render a point - list. - */ - float getPointSize(void) const { return mPointAttenution[0]; } - - /** Sets the point size of this pass. - - This setting allows you to change the size of points when rendering - a point list, or a list of point sprites. The interpretation of this - command depends on the Ogre::Pass::setPointAttenuation option - if it - is off (the default), the point size is in screen pixels, if it is on, - it expressed as normalised screen coordinates (1.0 is the height of - the screen) when the point is at the origin. - @note - Some drivers have an upper limit on the size of points they support - this can even vary - between APIs on the same card! Don't rely on point sizes that cause the point sprites to - get very large on screen, since they may get clamped on some cards. Upper sizes can range - from 64 to 256 pixels. - */ - void setPointSize(float ps) { mPointAttenution[0] = ps; } - - /** Sets whether points will be rendered as textured quads or plain dots - - This setting specifies whether or not hardware point sprite rendering is enabled for - this pass. Enabling it means that a point list is rendered as a list of quads rather than - a list of dots. It is very useful to use this option if you are using a BillboardSet and - only need to use point oriented billboards which are all of the same size. You can also - use it for any other point list render. - */ - void setPointSpritesEnabled(bool enabled) { mPointSpritesEnabled = enabled; } - - /** Returns whether point sprites are enabled when rendering a - point list. - */ - bool getPointSpritesEnabled(void) const { return mPointSpritesEnabled; } - - /** Sets how points are attenuated with distance. - - When performing point rendering or point sprite rendering, - point size can be attenuated with distance. The equation for - doing this is - - $$attenuation = 1 / (constant + linear * dist + quadratic * d^2)$$ - - For example, to disable distance attenuation (constant screensize) - you would set constant to 1, and linear and quadratic to 0. A - standard perspective attenuation would be 0, 1, 0 respectively. - - The resulting size is clamped to the minimum and maximum point - size. - @param enabled Whether point attenuation is enabled - @param constant, linear, quadratic Parameters to the attenuation - function defined above - */ - void setPointAttenuation(bool enabled, float constant = 0.0f, float linear = 1.0f, float quadratic = 0.0f); - - /** Returns whether points are attenuated with distance. */ - bool isPointAttenuationEnabled(void) const { return mPointAttenuationEnabled; } - - /** Returns the constant coefficient of point attenuation. */ - float getPointAttenuationConstant(void) const { return mPointAttenution[1]; } - /** Returns the linear coefficient of point attenuation. */ - float getPointAttenuationLinear(void) const { return mPointAttenution[2]; } - /** Returns the quadratic coefficient of point attenuation. */ - float getPointAttenuationQuadratic(void) const { return mPointAttenution[3]; } - - /// get all point attenuation params as (size, constant, linear, quadratic) - const Vector4f& getPointAttenuation() const { return mPointAttenution; } - - /** Set the minimum point size, when point attenuation is in use. */ - void setPointMinSize(Real min); - /** Get the minimum point size, when point attenuation is in use. */ - Real getPointMinSize(void) const; - /** Set the maximum point size, when point attenuation is in use. - @remarks Setting this to 0 indicates the max size supported by the card. - */ - void setPointMaxSize(Real max); - /** Get the maximum point size, when point attenuation is in use. - @remarks 0 indicates the max size supported by the card. - */ - Real getPointMaxSize(void) const; - /// @} - - typedef VectorIterator TextureUnitStateIterator; - typedef ConstVectorIterator ConstTextureUnitStateIterator; - /// @name Texture Units - /// @{ - /** Inserts a new TextureUnitState object into the Pass. - - This unit is is added on top of all previous units. - @param textureName - The basic name of the texture e.g. brickwall.jpg, stonefloor.png - @param texCoordSet - The index of the texture coordinate set to use. - @note - Applies to both fixed-function and programmable passes. - */ - TextureUnitState* createTextureUnitState( const String& textureName, unsigned short texCoordSet = 0); - /// @overload - TextureUnitState* createTextureUnitState(void); - - /** Adds the passed in TextureUnitState, to the existing Pass. - @param - state The Texture Unit State to be attached to this pass. It must not be attached to another pass. - @note - Throws an exception if the TextureUnitState is attached to another Pass.*/ - void addTextureUnitState(TextureUnitState* state); - /** Retrieves a const pointer to a texture unit state. - */ - TextureUnitState* getTextureUnitState(size_t index) const { return mTextureUnitStates.at(index); } - /** Retrieves the Texture Unit State matching name. - Returns 0 if name match is not found. - */ - TextureUnitState* getTextureUnitState(const String& name) const; - - - /** Retrieve the index of the Texture Unit State in the pass. - @param - state The Texture Unit State this is attached to this pass. - @note - Throws an exception if the state is not attached to the pass. - @deprecated use getTextureUnitStates() - */ - unsigned short getTextureUnitStateIndex(const TextureUnitState* state) const; - - /** Get an iterator over the TextureUnitStates contained in this Pass. - * @deprecated use getTextureUnitStates() */ - OGRE_DEPRECATED TextureUnitStateIterator getTextureUnitStateIterator(void); - - /** Get an iterator over the TextureUnitStates contained in this Pass. - * @deprecated use getTextureUnitStates() */ - OGRE_DEPRECATED ConstTextureUnitStateIterator getTextureUnitStateIterator(void) const; - - /** Get the TextureUnitStates contained in this Pass. */ - const TextureUnitStates& getTextureUnitStates() const { return mTextureUnitStates; } - - /** Removes the indexed texture unit state from this pass. - - Note that removing a texture which is not the topmost will have a larger performance impact. - */ - void removeTextureUnitState(unsigned short index); - - /** Removes all texture unit settings. - */ - void removeAllTextureUnitStates(void); - - /** Returns the number of texture unit settings */ - size_t getNumTextureUnitStates(void) const { return mTextureUnitStates.size(); } - - /** Gets the 'nth' texture which references the given content type. - - If the 'nth' texture unit which references the content type doesn't - exist, then this method returns an arbitrary high-value outside the - valid range to index texture units. - */ - unsigned short _getTextureUnitWithContentTypeIndex( - TextureUnitState::ContentType contentType, unsigned short index) const; - - /** Set texture filtering for every texture unit - @note - This property actually exists on the TextureUnitState class - For simplicity, this method allows you to set these properties for - every current TeextureUnitState, If you need more precision, retrieve the - TextureUnitState instance and set the property there. - @see TextureUnitState::setTextureFiltering - */ - void setTextureFiltering(TextureFilterOptions filterType); - /** Sets the anisotropy level to be used for all textures. - @note - This property has been moved to the TextureUnitState class, which is accessible via the - Technique and Pass. For simplicity, this method allows you to set these properties for - every current TeextureUnitState, If you need more precision, retrieve the Technique, - Pass and TextureUnitState instances and set the property there. - @see TextureUnitState::setTextureAnisotropy - */ - void setTextureAnisotropy(unsigned int maxAniso); - /// @} - - /// @name Scene Blending - /// @{ - /** Sets the kind of blending this pass has with the existing contents of the scene. - - Whereas the texture blending operations seen in the TextureUnitState class are concerned with - blending between texture layers, this blending is about combining the output of the Pass - as a whole with the existing contents of the rendering target. This blending therefore allows - object transparency and other special effects. If all passes in a technique have a scene - blend, then the whole technique is considered to be transparent. - - This method allows you to select one of a number of predefined blending types. If you require more - control than this, use the alternative version of this method which allows you to specify source and - destination blend factors. - @note - This method is applicable for both the fixed-function and programmable pipelines. - @param - sbt One of the predefined SceneBlendType blending types - */ - void setSceneBlending( const SceneBlendType sbt ); - - /** Sets the kind of blending this pass has with the existing contents of the scene, separately for color and alpha channels - - This method allows you to select one of a number of predefined blending types. If you require more - control than this, use the alternative version of this method which allows you to specify source and - destination blend factors. - - @param - sbt One of the predefined SceneBlendType blending types for the color channel - @param - sbta One of the predefined SceneBlendType blending types for the alpha channel - */ - void setSeparateSceneBlending( const SceneBlendType sbt, const SceneBlendType sbta ); - - /** Allows very fine control of blending this Pass with the existing contents of the scene. - - This version of the method allows complete control over the blending operation, by specifying the - source and destination blending factors. - - @copydetails Ogre::ColourBlendState - - @param - sourceFactor The source factor in the above calculation, i.e. multiplied by the output of the %Pass. - @param - destFactor The destination factor in the above calculation, i.e. multiplied by the Frame Buffer contents. - */ - void setSceneBlending( const SceneBlendFactor sourceFactor, const SceneBlendFactor destFactor); - - /** Allows very fine control of blending this Pass with the existing contents of the scene. - @copydetails Ogre::Pass::setSceneBlending( const SceneBlendFactor, const SceneBlendFactor) - @param - sourceFactorAlpha The alpha source factor in the above calculation, i.e. multiplied by the output of the %Pass. - @param - destFactorAlpha The alpha destination factor in the above calculation, i.e. multiplied by the Frame Buffer alpha. - */ - void setSeparateSceneBlending( const SceneBlendFactor sourceFactor, const SceneBlendFactor destFactor, const SceneBlendFactor sourceFactorAlpha, const SceneBlendFactor destFactorAlpha ); - - /// Retrieves the complete blend state of this pass - const ColourBlendState& getBlendState() const { return mBlendState; } - - /** Retrieves the source blending factor for the material - */ - SceneBlendFactor getSourceBlendFactor() const { return mBlendState.sourceFactor; } - - /** Retrieves the destination blending factor for the material - */ - SceneBlendFactor getDestBlendFactor() const { return mBlendState.destFactor; } - - /** Retrieves the alpha source blending factor for the material - */ - SceneBlendFactor getSourceBlendFactorAlpha() const { return mBlendState.sourceFactorAlpha; } - - /** Retrieves the alpha destination blending factor for the material - */ - SceneBlendFactor getDestBlendFactorAlpha() const { return mBlendState.destFactorAlpha; } - - /** Sets the specific operation used to blend source and destination pixels together. - - @see Ogre::ColourBlendState - @param op The blending operation mode to use for this pass - */ - void setSceneBlendingOperation(SceneBlendOperation op); - - /** Sets the specific operation used to blend source and destination pixels together. - - This function allows more control over blending since it allows you to select different blending - modes for the color and alpha channels - - @copydetails Pass::setSceneBlendingOperation - @param alphaOp The blending operation mode to use for alpha channels in this pass - */ - void setSeparateSceneBlendingOperation(SceneBlendOperation op, SceneBlendOperation alphaOp); - - /** Returns the current blending operation */ - SceneBlendOperation getSceneBlendingOperation() const { return mBlendState.operation; } - - /** Returns the current alpha blending operation */ - SceneBlendOperation getSceneBlendingOperationAlpha() const { return mBlendState.alphaOperation; } - - /** Sets whether or not colour buffer writing is enabled for this %Pass. - - If colour writing is off no visible pixels are written to the screen during this pass. - You might think this is useless, but if you render with colour writing off, and with very - minimal other settings, you can use this pass to initialise the depth buffer before - subsequently rendering other passes which fill in the colour data. This can give you - significant performance boosts on some newer cards, especially when using complex - fragment programs, because if the depth check fails then the fragment program is never - run. - */ - void setColourWriteEnabled(bool enabled); - /** Determines if colour buffer writing is enabled for this pass i.e. when at least one - colour channel is enabled for writing. - */ - bool getColourWriteEnabled(void) const; - - /// Sets which colour buffer channels are enabled for writing for this Pass - void setColourWriteEnabled(bool red, bool green, bool blue, bool alpha); - /// Determines which colour buffer channels are enabled for writing for this pass. - void getColourWriteEnabled(bool& red, bool& green, bool& blue, bool& alpha) const; - /// @} - - /** Returns true if this pass has some element of transparency. */ - bool isTransparent(void) const; - - /// @name Depth Testing - /// @{ - /** Sets whether or not this pass renders with depth-buffer checking on or not. - - If depth-buffer checking is on, whenever a pixel is about to be written to the frame buffer - the depth buffer is checked to see if the pixel is in front of all other pixels written at that - point. If not, the pixel is not written. - - If depth checking is off, pixels are written no matter what has been rendered before. - Also see setDepthFunction for more advanced depth check configuration. - @see Ogre::CompareFunction - */ - void setDepthCheckEnabled(bool enabled) { mDepthCheck = enabled; } - - /** Returns whether or not this pass renders with depth-buffer checking on or not. - */ - bool getDepthCheckEnabled(void) const { return mDepthCheck; } - - /** Sets whether or not this pass renders with depth-buffer writing on or not. - - If depth-buffer writing is on, whenever a pixel is written to the frame buffer - the depth buffer is updated with the depth value of that new pixel, thus affecting future - rendering operations if future pixels are behind this one. - - If depth writing is off, pixels are written without updating the depth buffer Depth writing should - normally be on but can be turned off when rendering static backgrounds or when rendering a collection - of transparent objects at the end of a scene so that they overlap each other correctly. - */ - void setDepthWriteEnabled(bool enabled) { mDepthWrite = enabled; } - - /** Returns whether or not this pass renders with depth-buffer writing on or not. - */ - bool getDepthWriteEnabled(void) const { return mDepthWrite; } - - /** Sets the function used to compare depth values when depth checking is on. - - If depth checking is enabled (see setDepthCheckEnabled) a comparison occurs between the depth - value of the pixel to be written and the current contents of the buffer. This comparison is - normally Ogre::CMPF_LESS_EQUAL. - */ - void setDepthFunction( CompareFunction func ) { mDepthFunc = func; } - /** Returns the function used to compare depth values when depth checking is on. - @see - setDepthFunction - */ - CompareFunction getDepthFunction(void) const { return mDepthFunc; } - - /** Sets the depth bias to be used for this material. - - When polygons are coplanar, you can get problems with 'depth fighting' where - the pixels from the two polys compete for the same screen pixel. This is particularly - a problem for decals (polys attached to another surface to represent details such as - bulletholes etc.). - - A way to combat this problem is to use a depth bias to adjust the depth buffer value - used for the decal such that it is slightly higher than the true value, ensuring that - the decal appears on top. There are two aspects to the biasing, a constant - bias value and a slope-relative biasing value, which varies according to the - maximum depth slope relative to the camera, ie: - - $$finalBias = maxSlope * slopeScaleBias + constantBias$$ - - Slope scale biasing is relative to the angle of the polygon to the camera, which makes - for a more appropriate bias value, but this is ignored on some older hardware. Constant - biasing is expressed as a factor of the minimum depth value, so a value of 1 will nudge - the depth by one ’notch’ if you will. - @param constantBias The constant bias value - @param slopeScaleBias The slope-relative bias value - */ - void setDepthBias(float constantBias, float slopeScaleBias = 0.0f); - - /** Retrieves the const depth bias value as set by setDepthBias. */ - float getDepthBiasConstant(void) const { return mDepthBiasConstant; } - /** Retrieves the slope-scale depth bias value as set by setDepthBias. */ - float getDepthBiasSlopeScale(void) const { return mDepthBiasSlopeScale; } - /** Sets a factor which derives an additional depth bias from the number - of times a pass is iterated. - - The Final depth bias will be the constant depth bias as set through - setDepthBias, plus this value times the iteration number. - */ - void setIterationDepthBias(float biasPerIteration) { mDepthBiasPerIteration = biasPerIteration; } - /** Gets a factor which derives an additional depth bias from the number - of times a pass is iterated. - */ - float getIterationDepthBias() const { return mDepthBiasPerIteration; } - /// @} - - /** Sets the culling mode for this pass based on the 'vertex winding'. - A typical way for the rendering engine to cull triangles is based on the 'vertex winding' of - triangles. Vertex winding refers to the direction in which the vertices are passed or indexed - to in the rendering operation as viewed from the camera, and will either be clockwise or - anticlockwise (that's 'counterclockwise' for you Americans out there ;) The default is - Ogre::CULL_CLOCKWISE i.e. that only triangles whose vertices are passed/indexed in anticlockwise order - are rendered - this is a common approach and is used in 3D studio models for example. You can - alter this culling mode if you wish but it is not advised unless you know what you are doing. - - You may wish to use the Ogre::CULL_NONE option for mesh data that you cull yourself where the vertex - winding is uncertain or for creating 2-sided passes. - */ - void setCullingMode( CullingMode mode ) { mCullMode = mode; } - - /** Returns the culling mode for geometry rendered with this pass. See setCullingMode for more information. - */ - CullingMode getCullingMode(void) const { return mCullMode; } - - /** Sets the manual culling mode, performed by CPU rather than hardware. - - In some situations you want to use manual culling of triangles rather than sending the - triangles to the hardware and letting it cull them. This setting only takes effect on - SceneManager's that use it (since it is best used on large groups of planar world geometry rather - than on movable geometry since this would be expensive), but if used can cull geometry before it is - sent to the hardware. - - In this case the culling is based on whether the ’back’ or ’front’ of the triangle is facing the - camera - this definition is based on the face normal (a vector which sticks out of the front side of - the polygon perpendicular to the face). Since %Ogre expects face normals to be on anticlockwise side - of the face, Ogre::MANUAL_CULL_BACK is the software equivalent of Ogre::CULL_CLOCKWISE setting, - which is why they are both the default. The naming is different to reflect the way the culling is - done though, since most of the time face normals are pre-calculated and they don’t have to be the - way %Ogre expects - you could set Ogre::CULL_NONE and completely cull in software based on your - own face normals, if you have the right SceneManager which uses them. - */ - void setManualCullingMode( ManualCullingMode mode ); - - /** Retrieves the manual culling mode for this pass - @see - setManualCullingMode - */ - ManualCullingMode getManualCullingMode(void) const; - - /** Sets the type of light shading required - - When dynamic lighting is turned on, the effect is to generate colour values at each - vertex. Whether these values are interpolated across the face (and how) depends on this - setting. The default shading method is Ogre::SO_GOURAUD. - */ - void setShadingMode( ShadeOptions mode ) { mShadeOptions = mode; } - - /** Returns the type of light shading to be used. - */ - ShadeOptions getShadingMode(void) const { return mShadeOptions; } - - /** Sets the type of polygon rendering required - - Sets how polygons should be rasterised, i.e. whether they should be filled in, or just drawn as lines or points. - The default shading method is Ogre::PM_SOLID. - */ - void setPolygonMode( PolygonMode mode ) { mPolygonMode = mode; } - - /** Returns the type of light shading to be used. - */ - PolygonMode getPolygonMode(void) const { return mPolygonMode; } - - /** Sets whether the PolygonMode set on this pass can be downgraded by the camera - - @param override If set to false, this pass will always be rendered at its own chosen polygon mode no matter what the - camera says. The default is true. - */ - void setPolygonModeOverrideable(bool override) { mPolygonModeOverrideable = override; } - - /** Gets whether this renderable's chosen detail level can be - overridden (downgraded) by the camera setting. - */ - bool getPolygonModeOverrideable(void) const { return mPolygonModeOverrideable; } - - /// @name Fogging - /// @{ - /** Sets the fogging mode applied to this pass. - - Fogging is an effect that is applied as polys are rendered. Sometimes, you want - fog to be applied to an entire scene. Other times, you want it to be applied to a few - polygons only. This pass-level specification of fog parameters lets you easily manage - both. - @par - The SceneManager class also has a setFog method which applies scene-level fog. This method - lets you change the fog behaviour for this pass compared to the standard scene-level fog. - @param - overrideScene If true, you authorise this pass to override the scene's fog params with it's own settings. - If you specify false, so other parameters are necessary, and this is the default behaviour for passes. - @param - mode Only applicable if overrideScene is true. You can disable fog which is turned on for the - rest of the scene by specifying FOG_NONE. Otherwise, set a pass-specific fog mode as - defined in the enum FogMode. - @param - colour The colour of the fog. Either set this to the same as your viewport background colour, - or to blend in with a skydome or skybox. - @param - expDensity The density of the fog in FOG_EXP or FOG_EXP2 mode, as a value between 0 and 1. - The default is 0.001. - @param - linearStart Distance in world units at which linear fog starts to encroach. - Only applicable if mode is FOG_LINEAR. - @param - linearEnd Distance in world units at which linear fog becomes completely opaque. - Only applicable if mode is FOG_LINEAR. - */ - void setFog( - bool overrideScene, - FogMode mode = FOG_NONE, - const ColourValue& colour = ColourValue::White, - float expDensity = 0.001f, float linearStart = 0.0f, float linearEnd = 1.0f ); - - /** Returns true if this pass is to override the scene fog settings. - */ - bool getFogOverride(void) const { return mFogOverride; } - - /** Returns the fog mode for this pass. - @note - Only valid if getFogOverride is true. - */ - FogMode getFogMode(void) const { return mFogMode; } - - /** Returns the fog colour for the scene. - */ - const ColourValue& getFogColour(void) const { return mFogColour; } - - /** Returns the fog start distance for this pass. - @note - Only valid if getFogOverride is true. - */ - float getFogStart(void) const { return mFogStart; } - - /** Returns the fog end distance for this pass. - @note - Only valid if getFogOverride is true. - */ - float getFogEnd(void) const { return mFogEnd; } - - /** Returns the fog density for this pass. - @note - Only valid if getFogOverride is true. - */ - float getFogDensity(void) const { return mFogDensity; } - /// @} - - /// @name Alpha Rejection - /// @{ - /** Sets the way the pass will have use alpha to totally reject pixels from the pipeline. - - The default is CMPF_ALWAYS_PASS i.e. alpha is not used to reject pixels. - @param func The comparison which must pass for the pixel to be written. - @param value 1 byte value against which alpha values will be tested(0-255) - @param alphaToCoverageEnabled Whether to use alpha to coverage with MSAA. - This option applies in both the fixed function and the programmable pipeline. - */ - void setAlphaRejectSettings(CompareFunction func, unsigned char value, bool alphaToCoverageEnabled = false); - - /** Sets the alpha reject function. @see setAlphaRejectSettings for more information. - */ - void setAlphaRejectFunction(CompareFunction func) { mAlphaRejectFunc = func; } - - /** Gets the alpha reject value. @see setAlphaRejectSettings for more information. - */ - void setAlphaRejectValue(unsigned char val) { mAlphaRejectVal = val; } - - /** Gets the alpha reject function. @see setAlphaRejectSettings for more information. - */ - CompareFunction getAlphaRejectFunction(void) const { return mAlphaRejectFunc; } - - /** Gets the alpha reject value. @see setAlphaRejectSettings for more information. - */ - unsigned char getAlphaRejectValue(void) const { return mAlphaRejectVal; } - - /** Sets whether to use alpha to coverage (A2C) when blending alpha rejected values. - - Alpha to coverage performs multisampling on the edges of alpha-rejected - textures to produce a smoother result. It is only supported when multisampling - is already enabled on the render target, and when the hardware supports - alpha to coverage (see RenderSystemCapabilities). - The common use for alpha to coverage is foliage rendering and chain-link fence style - textures. - */ - void setAlphaToCoverageEnabled(bool enabled) { mAlphaToCoverageEnabled = enabled; } - - /** Gets whether to use alpha to coverage (A2C) when blending alpha rejected values. - */ - bool isAlphaToCoverageEnabled() const { return mAlphaToCoverageEnabled; } - /// @} - - /** Sets whether or not transparent sorting is enabled. - @param enabled - If false depth sorting of this material will be disabled. - - By default all transparent materials are sorted such that renderables furthest - away from the camera are rendered first. This is usually the desired behaviour - but in certain cases this depth sorting may be unnecessary and undesirable. If - for example it is necessary to ensure the rendering order does not change from - one frame to the next. - @note - This will have no effect on non-transparent materials. - */ - void setTransparentSortingEnabled(bool enabled) { mTransparentSorting = enabled; } - - /** Returns whether or not transparent sorting is enabled. - */ - bool getTransparentSortingEnabled(void) const { return mTransparentSorting; } - - /** Sets whether or not transparent sorting is forced. - @param enabled - If true depth sorting of this material will be depend only on the value of - getTransparentSortingEnabled(). - - By default even if transparent sorting is enabled, depth sorting will only be - performed when the material is transparent and depth write/check are disabled. - This function disables these extra conditions. - */ - void setTransparentSortingForced(bool enabled) { mTransparentSortingForced = enabled; } - - /** Returns whether or not transparent sorting is forced. - */ - bool getTransparentSortingForced(void) const { return mTransparentSortingForced; } - - /// @name Light Iteration - /// @{ - /** Sets the maximum number of lights to be used by this pass. - - During rendering, if lighting is enabled (or if the pass uses an automatic - program parameter based on a light) the engine will request the nearest lights - to the object being rendered in order to work out which ones to use. This - parameter sets the limit on the number of lights which should apply to objects - rendered with this pass. - */ - void setMaxSimultaneousLights(unsigned short maxLights) { mMaxSimultaneousLights = maxLights; } - /** Gets the maximum number of lights to be used by this pass. */ - unsigned short getMaxSimultaneousLights(void) const { return mMaxSimultaneousLights; } - - /** Sets the light index that this pass will start at in the light list. - - Normally the lights passed to a pass will start from the beginning - of the light list for this object. This option allows you to make this - pass start from a higher light index, for example if one of your earlier - passes could deal with lights 0-3, and this pass dealt with lights 4+. - This option also has an interaction with pass iteration, in that - if you choose to iterate this pass per light too, the iteration will - only begin from light 4. - */ - void setStartLight(unsigned short startLight) { mStartLight = startLight; } - /** Gets the light index that this pass will start at in the light list. */ - unsigned short getStartLight(void) const { return mStartLight; } - - /** Sets the light mask which can be matched to specific light flags to be handled by this pass */ - void setLightMask(uint32 mask) { mLightMask = mask; } - /** Gets the light mask controlling which lights are used for this pass */ - uint32 getLightMask() const { return mLightMask; } - - /** Sets whether or not this pass should iterate per light or number of - lights which can affect the object being rendered. - - The default behaviour for a pass (when this option is 'false'), is - for a pass to be rendered only once (or the number of times set in - setPassIterationCount), with all the lights which could - affect this object set at the same time (up to the maximum lights - allowed in the render system, which is typically 8). - @par - Setting this option to 'true' changes this behaviour, such that - instead of trying to issue render this pass once per object, it - is run per light, or for a group of 'n' lights each time - which can affect this object, the number of - times set in setPassIterationCount (default is once). In - this case, only light index 0 is ever used, and is a different light - every time the pass is issued, up to the total number of lights - which is affecting this object. This has 2 advantages: -
  • There is no limit on the number of lights which can be - supported
  • -
  • It's easier to write vertex / fragment programs for this because - a single program can be used for any number of lights
  • -
- However, this technique is more expensive, and typically you - will want an additional ambient pass, because if no lights are - affecting the object it will not be rendered at all, which will look - odd even if ambient light is zero (imagine if there are lit objects - behind it - the objects silhouette would not show up). Therefore, - use this option with care, and you would be well advised to provide - a less expensive fallback technique for use in the distance. - @note - The number of times this pass runs is still limited by the maximum - number of lights allowed as set in setMaxSimultaneousLights, so - you will never get more passes than this. Also, the iteration is - started from the 'start light' as set in Pass::setStartLight, and - the number of passes is the number of lights to iterate over divided - by the number of lights per iteration (default 1, set by - setLightCountPerIteration). - @param enabled Whether this feature is enabled - @param onlyForOneLightType If true, the pass will only be run for a single type - of light, other light types will be ignored. - @param lightType The single light type which will be considered for this pass - */ - void setIteratePerLight(bool enabled, - bool onlyForOneLightType = true, Light::LightTypes lightType = Light::LT_POINT); - - /** Does this pass run once for every light in range? */ - bool getIteratePerLight(void) const { return mIteratePerLight; } - /** Does this pass run only for a single light type (if getIteratePerLight is true). */ - bool getRunOnlyForOneLightType(void) const { return mRunOnlyForOneLightType; } - /** Gets the single light type this pass runs for if getIteratePerLight and - getRunOnlyForOneLightType are both true. */ - Light::LightTypes getOnlyLightType() const { return mOnlyLightType; } - - /** If light iteration is enabled, determine the number of lights per - iteration. - - The default for this setting is 1, so if you enable light iteration - (Pass::setIteratePerLight), the pass is rendered once per light. If - you set this value higher, the passes will occur once per 'n' lights. - The start of the iteration is set by Pass::setStartLight and the end - by Pass::setMaxSimultaneousLights. - */ - void setLightCountPerIteration(unsigned short c) { mLightsPerIteration = c; } - /** If light iteration is enabled, determine the number of lights per - iteration. - */ - unsigned short getLightCountPerIteration(void) const { return mLightsPerIteration; } - /// @} - - /// Gets the parent Technique - Technique* getParent(void) const { return mParent; } - - /// Gets the resource group of the ultimate parent Material - const String& getResourceGroup(void) const; - - /// @name Gpu Programs - /// @{ - - /// Returns true if this pass is programmable i.e. includes either a vertex or fragment program. - bool isProgrammable(void) const - { - for (const auto& u : mProgramUsage) - if (u) return true; - return false; - } - /// Returns true if this pass uses a programmable vertex pipeline - bool hasVertexProgram(void) const { return hasGpuProgram(GPT_VERTEX_PROGRAM); } - /// Returns true if this pass uses a programmable fragment pipeline - bool hasFragmentProgram(void) const { return hasGpuProgram(GPT_FRAGMENT_PROGRAM); } - /// Returns true if this pass uses a programmable geometry pipeline - bool hasGeometryProgram(void) const { return hasGpuProgram(GPT_GEOMETRY_PROGRAM); } - /// Returns true if this pass uses a programmable tessellation control pipeline - bool hasTessellationHullProgram(void) const { return hasGpuProgram(GPT_HULL_PROGRAM); } - /// Returns true if this pass uses a programmable tessellation control pipeline - bool hasTessellationDomainProgram(void) const { return hasGpuProgram(GPT_DOMAIN_PROGRAM); } - /// Returns true if this pass uses a programmable compute pipeline - bool hasComputeProgram(void) const { return hasGpuProgram(GPT_COMPUTE_PROGRAM); } - /// Gets the Gpu program used by this pass, only available after _load() - const GpuProgramPtr& getGpuProgram(GpuProgramType programType) const; - /// @overload - const GpuProgramPtr& getVertexProgram(void) const { return getGpuProgram(GPT_VERTEX_PROGRAM); } - /// @overload - const GpuProgramPtr& getFragmentProgram(void) const { return getGpuProgram(GPT_FRAGMENT_PROGRAM); } - /// @overload - const GpuProgramPtr& getGeometryProgram(void) const { return getGpuProgram(GPT_GEOMETRY_PROGRAM); } - /// @overload - const GpuProgramPtr& getTessellationHullProgram(void) const { return getGpuProgram(GPT_HULL_PROGRAM); } - /// @overload - const GpuProgramPtr& getTessellationDomainProgram(void) const { return getGpuProgram(GPT_DOMAIN_PROGRAM); } - /// @overload - const GpuProgramPtr& getComputeProgram(void) const { return getGpuProgram(GPT_COMPUTE_PROGRAM); } - - bool hasGpuProgram(GpuProgramType programType) const; - - /** Sets the details of the program to use. - - Only applicable to programmable passes, this sets the details of - the program to use in this pass. The program will not be - loaded until the parent Material is loaded. - @param prog The program. If this parameter is @c NULL, any program of the type in this pass is disabled. - @param type The type of program - @param resetParams - If true, this will create a fresh set of parameters from the - new program being linked, so if you had previously set parameters - you will have to set them again. If you set this to false, you must - be absolutely sure that the parameters match perfectly, and in the - case of named parameters refers to the indexes underlying them, - not just the names. - */ - void setGpuProgram(GpuProgramType type, const GpuProgramPtr& prog, bool resetParams = true); - /// @overload - void setGpuProgram(GpuProgramType type, const String& name, bool resetParams = true); - /// @overload - void setFragmentProgram(const String& name, bool resetParams = true); - /// @overload - void setGeometryProgram(const String& name, bool resetParams = true); - /// @overload - void setTessellationDomainProgram(const String& name, bool resetParams = true); - /// @overload - void setTessellationHullProgram(const String& name, bool resetParams = true); - /// @overload - void setVertexProgram(const String& name, bool resetParams = true); - /// @overload - void setComputeProgram(const String& name, bool resetParams = true); - - /** Gets the name of the program used by this pass. */ - const String& getGpuProgramName(GpuProgramType type) const; - /// @overload - const String& getFragmentProgramName(void) const { return getGpuProgramName(GPT_FRAGMENT_PROGRAM); } - /// @overload - const String& getGeometryProgramName(void) const { return getGpuProgramName(GPT_GEOMETRY_PROGRAM); } - /// @overload - const String& getTessellationDomainProgramName(void) const { return getGpuProgramName(GPT_DOMAIN_PROGRAM); } - /// @overload - const String& getTessellationHullProgramName(void) const { return getGpuProgramName(GPT_HULL_PROGRAM); } - /// @overload - const String& getVertexProgramName(void) const { return getGpuProgramName(GPT_VERTEX_PROGRAM); } - /// @overload - const String& getComputeProgramName(void) const { return getGpuProgramName(GPT_COMPUTE_PROGRAM); } - - /** Sets the Gpu program parameters. - - Only applicable to programmable passes, and this particular call is - designed for low-level programs; use the named parameter methods - for setting high-level program parameters. - */ - void setGpuProgramParameters(GpuProgramType type, const GpuProgramParametersSharedPtr& params); - /// @overload - void setVertexProgramParameters(GpuProgramParametersSharedPtr params); - /// @overload - void setFragmentProgramParameters(GpuProgramParametersSharedPtr params); - /// @overload - void setGeometryProgramParameters(GpuProgramParametersSharedPtr params); - /// @overload - void setTessellationHullProgramParameters(GpuProgramParametersSharedPtr params); - /// @overload - void setTessellationDomainProgramParameters(GpuProgramParametersSharedPtr params); - /// @overload - void setComputeProgramParameters(GpuProgramParametersSharedPtr params); - - /** Gets the Gpu program parameters used by this pass. */ - const GpuProgramParametersSharedPtr& getGpuProgramParameters(GpuProgramType type) const; - /// @overload - GpuProgramParametersSharedPtr getVertexProgramParameters(void) const; - /// @overload - GpuProgramParametersSharedPtr getFragmentProgramParameters(void) const; - /// @overload - GpuProgramParametersSharedPtr getGeometryProgramParameters(void) const; - /// @overload - GpuProgramParametersSharedPtr getTessellationHullProgramParameters(void) const; - /// @overload - GpuProgramParametersSharedPtr getTessellationDomainProgramParameters(void) const; - /// @overload - GpuProgramParametersSharedPtr getComputeProgramParameters(void) const; - /// @} - - /** Splits this Pass to one which can be handled in the number of - texture units specified. - - Only works on non-programmable passes, programmable passes cannot be - split, it's up to the author to ensure that there is a fallback Technique - for less capable cards. - @param numUnits The target number of texture units - @return A new Pass which contains the remaining units, and a scene_blend - setting appropriate to approximate the multitexture. This Pass will be - attached to the parent Technique of this Pass. - */ - Pass* _split(unsigned short numUnits); - - /** Internal method to adjust pass index. */ - void _notifyIndex(unsigned short index); - - /** Internal method for preparing to load this pass. */ - void _prepare(void); - /** Internal method for undoing the load preparartion for this pass. */ - void _unprepare(void); - /** Internal method for loading this pass. */ - void _load(void); - /** Internal method for unloading this pass. */ - void _unload(void); - /// Is this loaded? - bool isLoaded(void) const; - - /** Gets the 'hash' of this pass, ie a precomputed number to use for sorting - - This hash is used to sort passes, and for this reason the pass is hashed - using firstly its index (so that all passes are rendered in order), then - by the textures which it's TextureUnitState instances are using. - */ - uint32 getHash(void) const { return mHash; } - /// Mark the hash as dirty - void _dirtyHash(void); - /** Internal method for recalculating the hash. - - Do not call this unless you are sure the old hash is not still being - used by anything. If in doubt, call _dirtyHash if you want to force - recalculation of the has next time. - */ - void _recalculateHash(void); - /** Tells the pass that it needs recompilation. */ - void _notifyNeedsRecompile(void); - - /** Update automatic parameters. - @param source The source of the parameters - @param variabilityMask A mask of GpuParamVariability which identifies which autos will need updating - */ - void _updateAutoParams(const AutoParamDataSource* source, uint16 variabilityMask) const; - - /** Static method to retrieve all the Passes which need their - hash values recalculated. - */ - static const PassSet& getDirtyHashList(void) - { return msDirtyHashList; } - /** Static method to retrieve all the Passes which are pending deletion. - */ - static const PassSet& getPassGraveyard(void) - { return msPassGraveyard; } - /** Static method to reset the list of passes which need their hash - values recalculated. - - For performance, the dirty list is not updated progressively as - the hashes are recalculated, instead we expect the processor of the - dirty hash list to clear the list when they are done. - */ - static void clearDirtyHashList(void); - - /** Process all dirty and pending deletion passes. */ - static void processPendingPassUpdates(void); - - /** Queue this pass for deletion when appropriate. */ - void queueForDeletion(void); - - /** Returns whether this pass is ambient only. - */ - bool isAmbientOnly(void) const; - - /** set the number of iterations that this pass - should perform when doing fast multi pass operation. - - Only applicable for programmable passes. - @param count number of iterations to perform fast multi pass operations. - A value greater than 1 will cause the pass to be executed count number of - times without changing the render state. This is very useful for passes - that use programmable shaders that have to iterate more than once but don't - need a render state change. Using multi pass can dramatically speed up rendering - for materials that do things like fur, blur. - A value of 1 turns off multi pass operation and the pass does - the normal pass operation. - */ - void setPassIterationCount(const size_t count) { mPassIterationCount = count; } - - /** Gets the pass iteration count value. - */ - size_t getPassIterationCount(void) const { return mPassIterationCount; } - - /** Sets whether or not this pass will be clipped by a scissor rectangle - encompassing the lights that are being used in it. - - In order to cut down on fillrate when you have a number of fixed-range - lights in the scene, you can enable this option to request that - during rendering, only the region of the screen which is covered by - the lights is rendered. This region is the screen-space rectangle - covering the union of the spheres making up the light ranges. Directional - lights are ignored for this. - - This is only likely to be useful for multipass additive lighting - algorithms, where the scene has already been 'seeded' with an ambient - pass and this pass is just adding light in affected areas. - - When using Ogre::SHADOWTYPE_STENCIL_ADDITIVE or Ogre::SHADOWTYPE_TEXTURE_ADDITIVE, - this option is implicitly used for all per-light passes and does - not need to be specified. If you are not using shadows or are using - a modulative or @ref Integrated-Texture-Shadows then this could be useful. - - */ - void setLightScissoringEnabled(bool enabled) { mLightScissoring = enabled; } - /** Gets whether or not this pass will be clipped by a scissor rectangle - encompassing the lights that are being used in it. - */ - bool getLightScissoringEnabled() const { return mLightScissoring; } - - /** Sets whether or not this pass will be clipped by user clips planes - bounding the area covered by the light. - - This option will only function if there is a single non-directional light being used in - this pass. If there is more than one light, or only directional lights, then no clipping - will occur. If there are no lights at all then the objects won’t be rendered at all. - - In order to cut down on the geometry set up to render this pass - when you have a single fixed-range light being rendered through it, - you can enable this option to request that during triangle setup, - clip planes are defined to bound the range of the light. In the case - of a point light these planes form a cube, and in the case of - a spotlight they form a pyramid. Directional lights are never clipped. - - This option is only likely to be useful for multipass additive lighting - algorithms, where the scene has already been 'seeded' with an ambient - pass and this pass is just adding light in affected areas. In addition, - it will only be honoured if there is exactly one non-directional light - being used in this pass. Also, these clip planes override any user clip - planes set on Camera. - - When using Ogre::SHADOWTYPE_STENCIL_ADDITIVE or Ogre::SHADOWTYPE_TEXTURE_ADDITIVE, - this option is automatically used for all per-light passes if you - enable Ogre::SceneManager::setShadowUseLightClipPlanes and does - not need to be specified. It is disabled by default since clip planes have - a cost of their own which may not always exceed the benefits they give you. - Generally the smaller your lights are the more chance you’ll see a benefit rather than - a penalty from clipping. - - @note Only has an effect with the fixed-function pipeline. Exceptions: - - with D3D9, clip planes are even available when shaders are used - - with GL1, shaders must write to gl_ClipVertex - */ - void setLightClipPlanesEnabled(bool enabled) { mLightClipPlanes = enabled; } - /** Gets whether or not this pass will be clipped by user clips planes - bounding the area covered by the light. - */ - bool getLightClipPlanesEnabled() const { return mLightClipPlanes; } - - /** Manually set which illumination stage this pass is a member of. - - When using an additive lighting mode (Ogre::SHADOWTYPE_STENCIL_ADDITIVE or - Ogre::SHADOWTYPE_TEXTURE_ADDITIVE), the scene is rendered in 3 discrete - stages, ambient (or pre-lighting), per-light (once per light, with - shadowing) and decal (or post-lighting). Usually OGRE figures out how - to categorise your passes automatically, but there are some effects you - cannot achieve without manually controlling the illumination. For example - specular effects are muted by the typical sequence because all textures - are saved until the Ogre::IS_DECAL stage which mutes the specular effect. - Instead, you could do texturing within the per-light stage if it's - possible for your material and thus add the specular on after the - decal texturing, and have no post-light rendering. - - If you assign an illumination stage to a pass you have to assign it - to all passes in the technique otherwise it will be ignored. Also note - that whilst you can have more than one pass in each group, they cannot - alternate, ie all ambient passes will be before all per-light passes, - which will also be before all decal passes. Within their categories - the passes will retain their ordering though. - */ - void setIlluminationStage(IlluminationStage is) { mIlluminationStage = is; } - /// Get the manually assigned illumination stage, if any - IlluminationStage getIlluminationStage() const { return mIlluminationStage; } - /** There are some default hash functions used to order passes so that - render state changes are minimised, this enumerates them. - */ - enum BuiltinHashFunction - { - /** Try to minimise the number of texture changes. */ - MIN_TEXTURE_CHANGE, - /** Try to minimise the number of GPU program changes. - @note Only really useful if you use GPU programs for all of your - materials. - */ - MIN_GPU_PROGRAM_CHANGE - }; - /** Sets one of the default hash functions to be used. - - You absolutely must not change the hash function whilst any Pass instances - exist in the render queue. The only time you can do this is either - before you render anything, or directly after you manuall call - RenderQueue::clear(true) to completely destroy the queue structures. - The default is MIN_GPU_PROGRAM_CHANGE. - @note - You can also implement your own hash function, see the alternate version - of this method. - @see HashFunc - */ - static void setHashFunction(BuiltinHashFunction builtin); - - /** Set the hash function used for all passes. - - You absolutely must not change the hash function whilst any Pass instances - exist in the render queue. The only time you can do this is either - before you render anything, or directly after you manuall call - RenderQueue::clear(true) to completely destroy the queue structures. - @note - You can also use one of the built-in hash functions, see the alternate version - of this method. The default is MIN_GPU_PROGRAM_CHANGE. - @see HashFunc - */ - static void setHashFunction(HashFunc* hashFunc) { msHashFunc = hashFunc; } - - /** Get the hash function used for all passes. - */ - static HashFunc* getHashFunction(void) { return msHashFunc; } - - /** Get the builtin hash function. - */ - static HashFunc* getBuiltinHashFunction(BuiltinHashFunction builtin); - - /// @copydoc UserObjectBindings - UserObjectBindings& getUserObjectBindings() { return mUserObjectBindings; } - - /// @overload - const UserObjectBindings& getUserObjectBindings() const { return mUserObjectBindings; } - private: - std::unique_ptr& getProgramUsage(GpuProgramType programType); - const std::unique_ptr& getProgramUsage(GpuProgramType programType) const; - }; - - /** Struct recording a pass which can be used for a specific illumination stage. - - This structure is used to record categorised passes which fit into a - number of distinct illumination phases - ambient, diffuse / specular - (per-light) and decal (post-lighting texturing). - An original pass may fit into one of these categories already, or it - may require splitting into its component parts in order to be categorised - properly. - */ - struct IlluminationPass : public PassAlloc - { - IlluminationStage stage; - /// The pass to use in this stage - Pass* pass; - /// Whether this pass is one which should be deleted itself - bool destroyOnShutdown; - /// The original pass which spawned this one - Pass* originalPass; - - IlluminationPass() {} - }; - - typedef std::vector IlluminationPassList; - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgrePatchMesh.h b/OgreMain/include/OgrePatchMesh.h deleted file mode 100644 index 35289edb817..00000000000 --- a/OgreMain/include/OgrePatchMesh.h +++ /dev/null @@ -1,87 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __PatchMesh_H__ -#define __PatchMesh_H__ - -#include "OgrePrerequisites.h" -#include "OgreMesh.h" -#include "OgrePatchSurface.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup LOD - * @{ - */ - /** Patch specialisation of Mesh. - - Instances of this class should be created by calling MeshManager::createBezierPatch. - */ - class _OgreExport PatchMesh : public Mesh - { - private: - /// Internal surface definition - PatchSurface mSurface; - /// Vertex declaration, cloned from the input - VertexDeclaration* mDeclaration; - public: - /// Constructor - PatchMesh(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group); - /// Update the mesh with new control points positions. - void update(void* controlPointBuffer, size_t width, size_t height, - size_t uMaxSubdivisionLevel, size_t vMaxSubdivisionLevel, - PatchSurface::VisibleSide visibleSide); - /// Define the patch, as defined in MeshManager::createBezierPatch - void define(void* controlPointBuffer, - VertexDeclaration *declaration, size_t width, size_t height, - size_t uMaxSubdivisionLevel = PatchSurface::AUTO_LEVEL, - size_t vMaxSubdivisionLevel = PatchSurface::AUTO_LEVEL, - PatchSurface::VisibleSide visibleSide = PatchSurface::VS_FRONT, - HardwareBuffer::Usage vbUsage = HBU_GPU_ONLY, - HardwareBuffer::Usage ibUsage = HBU_CPU_TO_GPU, - bool vbUseShadow = false, bool ibUseShadow = false); - - /* Sets the current subdivision level as a proportion of full detail. - @param factor Subdivision factor as a value from 0 (control points only) to 1 (maximum - subdivision). */ - void setSubdivision(Real factor); - private: - void loadImpl(void) override; - /// Overridden from Resource - do nothing (no disk caching) - void prepareImpl(void) override {} - - }; - /** @} */ - /** @} */ - -} - -#endif diff --git a/OgreMain/include/OgrePatchSurface.h b/OgreMain/include/OgrePatchSurface.h deleted file mode 100644 index 90de6331d2a..00000000000 --- a/OgreMain/include/OgrePatchSurface.h +++ /dev/null @@ -1,242 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __PatchSurface_H__ -#define __PatchSurface_H__ - -#include "OgrePrerequisites.h" - -#include "OgreHardwareIndexBuffer.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreAxisAlignedBox.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup LOD - * @{ - */ - /** A surface which is defined by curves of some kind to form a patch, e.g. a Bezier patch. - - This object will take a list of control points with various assorted data, and will - subdivide it into a patch mesh. Currently only Bezier curves are supported for defining - the surface, but other techniques such as NURBS would follow the same basic approach. - */ - class _OgreExport PatchSurface : public PatchAlloc - { - public: - PatchSurface(); - ~PatchSurface(); - - enum PatchSurfaceType - { - /// A patch defined by a set of bezier curves - PST_BEZIER - }; - - /// Constant for indicating automatic determination of subdivision level for patches - enum - { - AUTO_LEVEL = -1 - }; - - enum VisibleSide { - /// The side from which u goes right and v goes up (as in texture coords) - VS_FRONT, - /// The side from which u goes right and v goes down (reverse of texture coords) - VS_BACK, - /// Both sides are visible - warning this creates 2x the number of triangles and adds extra overhead for calculating normals - VS_BOTH - }; - /** Sets up the surface by defining it's control points, type and initial subdivision level. - - This method initialises the surface by passing it a set of control points. The type of curves to be used - are also defined here, although the only supported option currently is a bezier patch. You can also - specify a global subdivision level here if you like, although it is recommended that the parameter - is left as AUTO_LEVEL, which means the system decides how much subdivision is required (based on the - curvature of the surface) - @param - controlPointBuffer A pointer to a buffer containing the vertex data which defines control points - of the curves rather than actual vertices. Note that you are expected to provide not - just position information, but potentially normals and texture coordinates too. The - format of the buffer is defined in the VertexDeclaration parameter - @param - declaration VertexDeclaration describing the contents of the buffer. - Note this declaration must _only_ draw on buffer source 0! - @param - width Specifies the width of the patch in control points. - @param - height Specifies the height of the patch in control points. - @param - pType The type of surface - currently only PST_BEZIER is supported - @param - uMaxSubdivisionLevel,vMaxSubdivisionLevel If you want to manually set the top level of subdivision, - do it here, otherwise let the system decide. - @param - visibleSide Determines which side of the patch (or both) triangles are generated for. - */ - void defineSurface(void* controlPointBuffer, - VertexDeclaration *declaration, size_t width, size_t height, - PatchSurfaceType pType = PST_BEZIER, - size_t uMaxSubdivisionLevel = AUTO_LEVEL, size_t vMaxSubdivisionLevel = AUTO_LEVEL, - VisibleSide visibleSide = VS_FRONT); - - /** Based on a previous call to defineSurface, establishes the number of vertices required - to hold this patch at the maximum detail level. - @remarks This is useful when you wish to build the patch into external vertex / index buffers. - - */ - size_t getRequiredVertexCount(void) const; - /** Based on a previous call to defineSurface, establishes the number of indexes required - to hold this patch at the maximum detail level. - @remarks This is useful when you wish to build the patch into external vertex / index buffers. - - */ - size_t getRequiredIndexCount(void) const; - - /** Gets the current index count based on the current subdivision level. */ - size_t getCurrentIndexCount(void) const; - /// Returns the index offset used by this buffer to write data into the buffer - size_t getIndexOffset(void) const { return mIndexOffset; } - /// Returns the vertex offset used by this buffer to write data into the buffer - size_t getVertexOffset(void) const { return mVertexOffset; } - - - /** Gets the bounds of this patch, only valid after calling defineSurface. */ - const AxisAlignedBox& getBounds(void) const; - /** Gets the radius of the bounding sphere for this patch, only valid after defineSurface - has been called. */ - Real getBoundingSphereRadius(void) const; - /** Tells the system to build the mesh relating to the surface into externally created - buffers. - - The VertexDeclaration of the vertex buffer must be identical to the one passed into - defineSurface. In addition, there must be enough space in the buffer to - accommodate the patch at full detail level; you should call getRequiredVertexCount - and getRequiredIndexCount to determine this. This method does not create an internal - mesh for this patch and so getMesh will return null if you call it after building the - patch this way. - @param destVertexBuffer The destination vertex buffer in which to build the patch. - @param vertexStart The offset at which to start writing vertices for this patch - @param destIndexBuffer The destination index buffer in which to build the patch. - @param indexStart The offset at which to start writing indexes for this patch - - */ - void build(HardwareVertexBufferSharedPtr destVertexBuffer, size_t vertexStart, - HardwareIndexBufferSharedPtr destIndexBuffer, size_t indexStart); - - /** Alters the level of subdivision for this surface. - - This method changes the proportionate detail level of the patch; since - the U and V directions can have different subdivision levels, this method - takes a single Real value where 0 is the minimum detail (the control points) - and 1 is the maximum detail level as supplied to the original call to - defineSurface. - */ - void setSubdivisionFactor(Real factor); - - /** Gets the current level of subdivision. */ - Real getSubdivisionFactor(void) const; - - void* getControlPointBuffer(void) const - { - return mControlPointBuffer; - } - /** Convenience method for telling the patch that the control points have been - deleted, since once the patch has been built they are not required. */ - void notifyControlPointBufferDeallocated(void) { - mControlPointBuffer = 0; - } - private: - /// Vertex declaration describing the control point buffer - VertexDeclaration* mDeclaration; - /// Buffer containing the system-memory control points - void* mControlPointBuffer; - /// Type of surface - PatchSurfaceType mType; - /// Width in control points - size_t mCtlWidth; - /// Height in control points - size_t mCtlHeight; - /// TotalNumber of control points - size_t mCtlCount; - /// U-direction subdivision level - size_t mULevel; - /// V-direction subdivision level - size_t mVLevel; - /// Max subdivision level - size_t mMaxULevel; - size_t mMaxVLevel; - /// Width of the subdivided mesh (big enough for max level) - size_t mMeshWidth; - /// Height of the subdivided mesh (big enough for max level) - size_t mMeshHeight; - /// Which side is visible - VisibleSide mVSide; - - Real mSubdivisionFactor; - - std::vector mVecCtlPoints; - - /** Internal method for finding the subdivision level given 3 control points. - */ - size_t findLevel( Vector3& a, Vector3& b, Vector3& c); - - void distributeControlPoints(void* lockedBuffer); - void subdivideCurve(void* lockedBuffer, size_t startIdx, size_t stepSize, size_t numSteps, size_t iterations); - void interpolateVertexData(void* lockedBuffer, size_t leftIndex, size_t rightIndex, size_t destIndex); - void makeTriangles(void); - - size_t getAutoULevel(bool forMax = false); - size_t getAutoVLevel(bool forMax = false); - - HardwareVertexBufferSharedPtr mVertexBuffer; - HardwareIndexBufferSharedPtr mIndexBuffer; - size_t mVertexOffset; - size_t mIndexOffset; - size_t mRequiredVertexCount; - size_t mRequiredIndexCount; - size_t mCurrIndexCount; - - AxisAlignedBox mAABB; - Real mBoundingSphere; - - - - }; - - /** @} */ - /** @} */ - -} // namespace - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgrePixelCountLodStrategy.h b/OgreMain/include/OgrePixelCountLodStrategy.h deleted file mode 100644 index 91dac4f9753..00000000000 --- a/OgreMain/include/OgrePixelCountLodStrategy.h +++ /dev/null @@ -1,110 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Pixel_Count_Lod_Strategy_H__ -#define __Pixel_Count_Lod_Strategy_H__ - -#include "OgrePrerequisites.h" - -#include "OgreLodStrategy.h" -#include "OgreSingleton.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup LOD - * @{ - */ - - class AbsolutePixelCountLodStrategy; - /// Backward compatible name for Distance_Box strategy. - typedef AbsolutePixelCountLodStrategy PixelCountLodStrategy; - - /** Abstract base class for level of detail strategy based on pixel count approximations from bounding sphere projection. */ - class _OgreExport PixelCountLodStrategyBase : public LodStrategy - { - protected: - Real getValueImpl(const MovableObject *movableObject, const Camera *camera) const override; - - public: - /** Default constructor. */ - PixelCountLodStrategyBase(const String& name); - - /// @copydoc LodStrategy::getBaseValue - Real getBaseValue() const override; - - /// @copydoc LodStrategy::transformBias - Real transformBias(Real factor) const override; - - /// @copydoc LodStrategy::getIndex - ushort getIndex(Real value, const Mesh::MeshLodUsageList& meshLodUsageList) const override; - - /// @copydoc LodStrategy::getIndex - ushort getIndex(Real value, const Material::LodValueList& materialLodValueList) const override; - - /// @copydoc LodStrategy::sort - void sort(Mesh::MeshLodUsageList& meshLodUsageList) const override; - - /// @copydoc LodStrategy::isSorted - bool isSorted(const Mesh::LodValueList& values) const override; - }; - - class _OgreExport AbsolutePixelCountLodStrategy : public PixelCountLodStrategyBase, public Singleton - { - public: - /** Default constructor. */ - AbsolutePixelCountLodStrategy(); - ~AbsolutePixelCountLodStrategy(); - - Real getValueImpl(const MovableObject *movableObject, const Camera *camera) const override; - - /// @copydoc Singleton::getSingleton() - static AbsolutePixelCountLodStrategy& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static AbsolutePixelCountLodStrategy* getSingletonPtr(void); - }; - - class _OgreExport ScreenRatioPixelCountLodStrategy : public PixelCountLodStrategyBase, public Singleton - { - public: - /** Default constructor. */ - ScreenRatioPixelCountLodStrategy(); - ~ScreenRatioPixelCountLodStrategy(); - - /// @copydoc Singleton::getSingleton() - static ScreenRatioPixelCountLodStrategy& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static ScreenRatioPixelCountLodStrategy* getSingletonPtr(void); - }; - /** @} */ - /** @} */ - -} // namespace - -#endif diff --git a/OgreMain/include/OgrePixelFormat.h b/OgreMain/include/OgrePixelFormat.h deleted file mode 100644 index b1b07b00ec7..00000000000 --- a/OgreMain/include/OgrePixelFormat.h +++ /dev/null @@ -1,667 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _PixelFormat_H__ -#define _PixelFormat_H__ - -#include "OgrePrerequisites.h" -#include "OgreCommon.h" -#include "OgreColourValue.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Image - * @{ - */ - /** The pixel format used for images, textures, and render surfaces - * - * A pixel format described the storage format of pixel data. It defines the way pixels are encoded in memory. - * The components are specified in "packed" native byte order for native endian (16, 24 and 32 bit) integers. - * This means that a pixel with format Ogre::PF_A8R8G8B8 can be seen as a 32 bit integer, written as @c 0xAARRGGBB in hexadecimal - * on a little-endian (x86) machine or as @c 0xBBGGRRAA on a big-endian machine. - * The example above would be expressed with an array of bytes as `{0xBB, 0xGG, 0xRR, 0xAA}` on both machines. - * Therefore, one would use the Ogre::PF_BYTE_BGRA format when reading pixel data expressed in bytes. - * This format aliases to either Ogre::PF_A8B8G8R8 or Ogre::PF_R8G8B8A8 - * depending on the machine endianness. - */ - enum PixelFormat - { - /// Unknown pixel format. - PF_UNKNOWN = 0, - /// 8-bit pixel format, all bits luminance. - PF_L8, - PF_BYTE_L = PF_L8, - /// 16-bit pixel format, all bits luminance. - PF_L16, - PF_SHORT_L = PF_L16, - /// 8-bit pixel format, all bits alpha. - PF_A8, - PF_BYTE_A = PF_A8, - /// 2 byte pixel format, 1 byte luminance, 1 byte alpha - PF_BYTE_LA, - /// 16-bit pixel format, 5 bits red, 6 bits green, 5 bits blue. - PF_R5G6B5, - /// 16-bit pixel format, 5 bits red, 6 bits green, 5 bits blue. - PF_B5G6R5, - /// 16-bit pixel format, 4 bits for alpha, red, green and blue. - PF_A4R4G4B4, - /// 16-bit pixel format, 5 bits for blue, green, red and 1 for alpha. - PF_A1R5G5B5, - /// 24-bit pixel format, 8 bits for red, green and blue. - PF_R8G8B8, - /// 24-bit pixel format, 8 bits for blue, green and red. - PF_B8G8R8, - /// 32-bit pixel format, 8 bits for alpha, red, green and blue. - PF_A8R8G8B8, - /// 32-bit pixel format, 8 bits for blue, green, red and alpha. - PF_A8B8G8R8, - /// 32-bit pixel format, 8 bits for blue, green, red and alpha. - PF_B8G8R8A8, - /// 32-bit pixel format, 2 bits for alpha, 10 bits for red, green and blue. - PF_A2R10G10B10, - /// 32-bit pixel format, 10 bits for blue, green and red, 2 bits for alpha. - PF_A2B10G10R10, - /// DDS (DirectDraw Surface) DXT1 format - PF_DXT1, - /// DDS (DirectDraw Surface) DXT2 format - PF_DXT2, - /// DDS (DirectDraw Surface) DXT3 format - PF_DXT3, - /// DDS (DirectDraw Surface) DXT4 format - PF_DXT4, - /// DDS (DirectDraw Surface) DXT5 format - PF_DXT5, - /// 48-bit pixel format, 16 bits (float) for red, 16 bits (float) for green, 16 bits (float) for blue - PF_FLOAT16_RGB, - /// 64-bit pixel format, 16 bits (float) for red, 16 bits (float) for green, 16 bits (float) for blue, 16 bits (float) for alpha - PF_FLOAT16_RGBA, - /// 96-bit pixel format, 32 bits (float) for red, 32 bits (float) for green, 32 bits (float) for blue - PF_FLOAT32_RGB, - /// 128-bit pixel format, 32 bits (float) for red, 32 bits (float) for green, 32 bits (float) for blue, 32 bits (float) for alpha - PF_FLOAT32_RGBA, - /// 32-bit pixel format, 8 bits for red, 8 bits for green, 8 bits for blue - /// like Ogre::PF_A8R8G8B8, but alpha will get discarded - PF_X8R8G8B8, - /// 32-bit pixel format, 8 bits for blue, 8 bits for green, 8 bits for red - /// like Ogre::PF_A8B8G8R8, but alpha will get discarded - PF_X8B8G8R8, - /// 32-bit pixel format, 8 bits for red, green, blue and alpha. - PF_R8G8B8A8, - /// Depth texture format, with 16-bit unsigned integer - PF_DEPTH16, - PF_DEPTH = PF_DEPTH16, - /// 64-bit pixel format, 16 bits for red, green, blue and alpha - PF_SHORT_RGBA, - /// 8-bit pixel format, 2 bits blue, 3 bits green, 3 bits red. - PF_R3G3B2, - /// 16-bit pixel format, 16 bits (float) for red - PF_FLOAT16_R, - /// 32-bit pixel format, 32 bits (float) for red - PF_FLOAT32_R, - /// 32-bit pixel format, 16-bit green, 16-bit red - PF_SHORT_GR, - /// 32-bit, 2-channel s10e5 floating point pixel format, 16-bit green, 16-bit red - PF_FLOAT16_GR, - /// 64-bit, 2-channel floating point pixel format, 32-bit green, 32-bit red - PF_FLOAT32_GR, - /// 48-bit pixel format, 16 bits for red, green and blue - PF_SHORT_RGB, - /// PVRTC (PowerVR) RGB 2 bpp - PF_PVRTC_RGB2, - /// PVRTC (PowerVR) RGBA 2 bpp - PF_PVRTC_RGBA2, - /// PVRTC (PowerVR) RGB 4 bpp - PF_PVRTC_RGB4, - /// PVRTC (PowerVR) RGBA 4 bpp - PF_PVRTC_RGBA4, - /// PVRTC (PowerVR) Version 2, 2 bpp - PF_PVRTC2_2BPP, - /// PVRTC (PowerVR) Version 2, 4 bpp - PF_PVRTC2_4BPP, - /// 32-bit pixel format, 11 bits (float) for red, 11 bits (float) for green, 10 bits (float) for blue - PF_R11G11B10_FLOAT, - /// 8-bit pixel format, 8 bits red (unsigned int). - PF_R8_UINT, - /// 16-bit pixel format, 8 bits red (unsigned int), 8 bits blue (unsigned int). - PF_R8G8_UINT, - /// 24-bit pixel format, 8 bits red (unsigned int), 8 bits blue (unsigned int), 8 bits green (unsigned int). - PF_R8G8B8_UINT, - /// 32-bit pixel format, 8 bits red (unsigned int), 8 bits blue (unsigned int), 8 bits green (unsigned int), 8 bits alpha (unsigned int). - PF_R8G8B8A8_UINT, - /// 16-bit pixel format, 16 bits red (unsigned int). - PF_R16_UINT, - /// 32-bit pixel format, 16 bits red (unsigned int), 16 bits blue (unsigned int). - PF_R16G16_UINT, - /// 48-bit pixel format, 16 bits red (unsigned int), 16 bits blue (unsigned int), 16 bits green (unsigned int). - PF_R16G16B16_UINT, - /// 64-bit pixel format, 16 bits red (unsigned int), 16 bits blue (unsigned int), 16 bits green (unsigned int), 16 bits alpha (unsigned int). - PF_R16G16B16A16_UINT, - /// 32-bit pixel format, 32 bits red (unsigned int). - PF_R32_UINT, - /// 64-bit pixel format, 32 bits red (unsigned int), 32 bits blue (unsigned int). - PF_R32G32_UINT, - /// 96-bit pixel format, 32 bits red (unsigned int), 32 bits blue (unsigned int), 32 bits green (unsigned int). - PF_R32G32B32_UINT, - /// 128-bit pixel format, 32 bits red (unsigned int), 32 bits blue (unsigned int), 32 bits green (unsigned int), 32 bits alpha (unsigned int). - PF_R32G32B32A32_UINT, - /// 8-bit pixel format, 8 bits red (signed int). - PF_R8_SINT, - /// 16-bit pixel format, 8 bits red (signed int), 8 bits blue (signed int). - PF_R8G8_SINT, - /// 24-bit pixel format, 8 bits red (signed int), 8 bits blue (signed int), 8 bits green (signed int). - PF_R8G8B8_SINT, - /// 32-bit pixel format, 8 bits red (signed int), 8 bits blue (signed int), 8 bits green (signed int), 8 bits alpha (signed int). - PF_R8G8B8A8_SINT, - /// 16-bit pixel format, 16 bits red (signed int). - PF_R16_SINT, - /// 32-bit pixel format, 16 bits red (signed int), 16 bits blue (signed int). - PF_R16G16_SINT, - /// 48-bit pixel format, 16 bits red (signed int), 16 bits blue (signed int), 16 bits green (signed int). - PF_R16G16B16_SINT, - /// 64-bit pixel format, 16 bits red (signed int), 16 bits blue (signed int), 16 bits green (signed int), 16 bits alpha (signed int). - PF_R16G16B16A16_SINT, - /// 32-bit pixel format, 32 bits red (signed int). - PF_R32_SINT, - /// 64-bit pixel format, 32 bits red (signed int), 32 bits blue (signed int). - PF_R32G32_SINT, - /// 96-bit pixel format, 32 bits red (signed int), 32 bits blue (signed int), 32 bits green (signed int). - PF_R32G32B32_SINT, - /// 128-bit pixel format, 32 bits red (signed int), 32 bits blue (signed int), 32 bits green (signed int), 32 bits alpha (signed int). - PF_R32G32B32A32_SINT, - /// 32-bit pixel format, 9 bits for blue, green, red plus a 5 bit exponent. - PF_R9G9B9E5_SHAREDEXP, - /// DDS (DirectDraw Surface) BC4 format (unsigned normalised) - PF_BC4_UNORM, - /// DDS (DirectDraw Surface) BC4 format (signed normalised) - PF_BC4_SNORM, - /// DDS (DirectDraw Surface) BC5 format (unsigned normalised) - PF_BC5_UNORM, - /// DDS (DirectDraw Surface) BC5 format (signed normalised) - PF_BC5_SNORM, - /// DDS (DirectDraw Surface) BC6H format (unsigned 16 bit float) - PF_BC6H_UF16, - /// DDS (DirectDraw Surface) BC6H format (signed 16 bit float) - PF_BC6H_SF16, - /// DDS (DirectDraw Surface) BC7 format (unsigned normalised) - PF_BC7_UNORM, - /// 8-bit pixel format, all bits red. - PF_R8, - /// 16-bit pixel format, 8 bits red, 8 bits green. - PF_R8G8, - PF_RG8 = PF_R8G8, - /// 8-bit pixel format, 8 bits red (signed normalised int). - PF_R8_SNORM, - /// 16-bit pixel format, 8 bits red (signed normalised int), 8 bits blue (signed normalised int). - PF_R8G8_SNORM, - /// 24-bit pixel format, 8 bits red (signed normalised int), 8 bits blue (signed normalised int), 8 bits green (signed normalised int). - PF_R8G8B8_SNORM, - /// 32-bit pixel format, 8 bits red (signed normalised int), 8 bits blue (signed normalised int), 8 bits green (signed normalised int), 8 bits alpha (signed normalised int). - PF_R8G8B8A8_SNORM, - /// 16-bit pixel format, 16 bits red (signed normalised int). - PF_R16_SNORM, - /// 32-bit pixel format, 16 bits red (signed normalised int), 16 bits blue (signed normalised int). - PF_R16G16_SNORM, - /// 48-bit pixel format, 16 bits red (signed normalised int), 16 bits blue (signed normalised int), 16 bits green (signed normalised int). - PF_R16G16B16_SNORM, - /// 64-bit pixel format, 16 bits red (signed normalised int), 16 bits blue (signed normalised int), 16 bits green (signed normalised int), 16 bits alpha (signed normalised int). - PF_R16G16B16A16_SNORM, - /// ETC1 (Ericsson Texture Compression) - PF_ETC1_RGB8, - /// ETC2 (Ericsson Texture Compression) - PF_ETC2_RGB8, - /// ETC2 (Ericsson Texture Compression) - PF_ETC2_RGBA8, - /// ETC2 (Ericsson Texture Compression) - PF_ETC2_RGB8A1, - /// ATC (AMD_compressed_ATC_texture) - PF_ATC_RGB, - /// ATC (AMD_compressed_ATC_texture) - PF_ATC_RGBA_EXPLICIT_ALPHA, - /// ATC (AMD_compressed_ATC_texture) - PF_ATC_RGBA_INTERPOLATED_ALPHA, - /// ASTC (ARM Adaptive Scalable Texture Compression RGBA, block size 4x4) - PF_ASTC_RGBA_4X4_LDR, - /// ASTC (ARM Adaptive Scalable Texture Compression RGBA, block size 5x4) - PF_ASTC_RGBA_5X4_LDR, - /// ASTC (ARM Adaptive Scalable Texture Compression RGBA, block size 5x5) - PF_ASTC_RGBA_5X5_LDR, - /// ASTC (ARM Adaptive Scalable Texture Compression RGBA, block size 6x5) - PF_ASTC_RGBA_6X5_LDR, - /// ASTC (ARM Adaptive Scalable Texture Compression RGBA, block size 6x6) - PF_ASTC_RGBA_6X6_LDR, - /// ASTC (ARM Adaptive Scalable Texture Compression RGBA, block size 8x5) - PF_ASTC_RGBA_8X5_LDR, - /// ASTC (ARM Adaptive Scalable Texture Compression RGBA, block size 8x6) - PF_ASTC_RGBA_8X6_LDR, - /// ASTC (ARM Adaptive Scalable Texture Compression RGBA, block size 8x8) - PF_ASTC_RGBA_8X8_LDR, - /// ASTC (ARM Adaptive Scalable Texture Compression RGBA, block size 10x5) - PF_ASTC_RGBA_10X5_LDR, - /// ASTC (ARM Adaptive Scalable Texture Compression RGBA, block size 10x6) - PF_ASTC_RGBA_10X6_LDR, - /// ASTC (ARM Adaptive Scalable Texture Compression RGBA, block size 10x8) - PF_ASTC_RGBA_10X8_LDR, - /// ASTC (ARM Adaptive Scalable Texture Compression RGBA, block size 10x10) - PF_ASTC_RGBA_10X10_LDR, - /// ASTC (ARM Adaptive Scalable Texture Compression RGBA, block size 12x10) - PF_ASTC_RGBA_12X10_LDR, - /// ASTC (ARM Adaptive Scalable Texture Compression RGBA, block size 12x12) - PF_ASTC_RGBA_12X12_LDR, - PF_DEPTH32, - /// Depth texture format with 32-bit floating point - PF_DEPTH32F, - /// Depth texture format with 24-bit unsigned integer and 8-bit stencil - PF_DEPTH24_STENCIL8, - /// Number of pixel formats currently defined - PF_COUNT, - // endianness aware aliases -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - /// @copydoc PF_R8G8B8 - PF_BYTE_RGB = PF_R8G8B8, - /// @copydoc PF_B8G8R8 - PF_BYTE_BGR = PF_B8G8R8, - /// @copydoc PF_B8G8R8A8 - PF_BYTE_BGRA = PF_B8G8R8A8, - /// @copydoc PF_R8G8B8A8 - PF_BYTE_RGBA = PF_R8G8B8A8, -#else - /// @copydoc PF_B8G8R8 - PF_BYTE_RGB = PF_B8G8R8, - /// @copydoc PF_R8G8B8 - PF_BYTE_BGR = PF_R8G8B8, - /// @copydoc PF_A8R8G8B8 - PF_BYTE_BGRA = PF_A8R8G8B8, - /// @copydoc PF_A8B8G8R8 - PF_BYTE_RGBA = PF_A8B8G8R8, -#endif - }; - typedef std::vector PixelFormatList; - - /** - * Flags defining some on/off properties of pixel formats - */ - enum PixelFormatFlags { - /// This format has an alpha channel - PFF_HASALPHA = 0x00000001, - /** This format is compressed. This invalidates the values in elemBytes, - elemBits and the bit counts as these might not be fixed in a compressed format. */ - PFF_COMPRESSED = 0x00000002, - /// This is a floating point format - PFF_FLOAT = 0x00000004, - /// This is a depth format (for depth textures) - PFF_DEPTH = 0x00000008, - /** Format is in native endian. Generally true for the 16, 24 and 32 bits - formats which can be represented as machine integers. */ - PFF_NATIVEENDIAN = 0x00000010, - /** This is an intensity format instead of a RGB one. The luminance - replaces R,G and B. (but not A) */ - PFF_LUMINANCE = 0x00000020, - /// This is an integer format - PFF_INTEGER = 0x00000040 - }; - - /** Pixel component format */ - enum PixelComponentType - { - PCT_BYTE = 0, /// Byte per component (8 bit fixed 0.0..1.0) - PCT_SHORT = 1, /// Short per component (16 bit fixed 0.0..1.0)) - PCT_FLOAT16 = 2, /// 16 bit float per component - PCT_FLOAT32 = 3, /// 32 bit float per component - PCT_SINT = 4, /// Signed integer per component - PCT_UINT = 5, /// Unsigned integer per component - PCT_COUNT = 6 /// Number of pixel types - }; - - /** A primitive describing a volume (3D), image (2D) or line (1D) of pixels in memory. - In case of a rectangle, depth must be 1. - Pixels are stored as a succession of "depth" slices, each containing "height" rows of - "width" pixels. - - @copydetails Ogre::Box - */ - class _OgreExport PixelBox: public Box, public ImageAlloc { - public: - /// Parameter constructor for setting the members manually - PixelBox() : data(NULL), rowPitch(0), slicePitch(0), format(PF_UNKNOWN) {} - ~PixelBox() {} - /** Constructor providing extents in the form of a Box object. This constructor - assumes the pixel data is laid out consecutively in memory. (this - means row after row, slice after slice, with no space in between) - @param extents Extents of the region defined by data - @param pixelFormat Format of this buffer - @param pixelData Pointer to the actual data - */ - PixelBox(const Box &extents, PixelFormat pixelFormat, void *pixelData=0): - Box(extents), data((uchar*)pixelData), format(pixelFormat) - { - setConsecutive(); - } - /** Constructor providing width, height and depth. This constructor - assumes the pixel data is laid out consecutively in memory. (this - means row after row, slice after slice, with no space in between) - @param width Width of the region - @param height Height of the region - @param depth Depth of the region - @param pixelFormat Format of this buffer - @param pixelData Pointer to the actual data - */ - PixelBox(uint32 width, uint32 height, uint32 depth, PixelFormat pixelFormat, void *pixelData=0): - Box(0, 0, 0, width, height, depth), - data((uchar*)pixelData), format(pixelFormat) - { - setConsecutive(); - } - - /// The data pointer - uchar* data; - /** Number of elements between the leftmost pixel of one row and the left - pixel of the next. This value must always be equal to getWidth() (consecutive) - for compressed formats. - */ - size_t rowPitch; - /** Number of elements between the top left pixel of one (depth) slice and - the top left pixel of the next. This can be a negative value. Must be a multiple of - rowPitch. This value must always be equal to getWidth()*getHeight() (consecutive) - for compressed formats. - */ - size_t slicePitch; - /// The pixel format - PixelFormat format; - /** Set the rowPitch and slicePitch so that the buffer is laid out consecutive - in memory. - */ - void setConsecutive() - { - rowPitch = getWidth(); - slicePitch = getWidth()*getHeight(); - } - /** Get the number of elements between one past the rightmost pixel of - one row and the leftmost pixel of the next row. (IE this is zero if rows - are consecutive). - */ - size_t getRowSkip() const { return rowPitch - getWidth(); } - /** Get the number of elements between one past the right bottom pixel of - one slice and the left top pixel of the next slice. (IE this is zero if slices - are consecutive). - */ - size_t getSliceSkip() const { return slicePitch - (getHeight() * rowPitch); } - - /** Return whether this buffer is laid out consecutive in memory (ie the pitches - are equal to the dimensions) - */ - bool isConsecutive() const - { - return rowPitch == getWidth() && slicePitch == getWidth()*getHeight(); - } - /** Return the size (in bytes) this image would take if it was - laid out consecutive in memory - */ - size_t getConsecutiveSize() const; - /** Return a subvolume of this PixelBox. - @param def Defines the bounds of the subregion to return - @param resetOrigin Whether to reset left/top/front of returned PixelBox to zero - together with adjusting data pointer to compensate this, or do nothing - so that returned PixelBox will have left/top/front of requested Box - @return A pixel box describing the region and the data in it - @remarks This function does not copy any data, it just returns - a PixelBox object with a data pointer pointing somewhere inside - the data of object. - @throws Exception(ERR_INVALIDPARAMS) if def is not fully contained - */ - PixelBox getSubVolume(const Box &def, bool resetOrigin = true) const; - - /** Return a data pointer pointing to top left front pixel of the pixel box. - @remarks Non consecutive pixel boxes are supported. - */ - uchar* getTopLeftFrontPixelPtr() const; - - /** - * Get colour value from a certain location in the PixelBox. The z coordinate - * is only valid for cubemaps and volume textures. This uses the first (largest) - * mipmap. - */ - ColourValue getColourAt(size_t x, size_t y, size_t z) const; - - /** - * Set colour value at a certain location in the PixelBox. The z coordinate - * is only valid for cubemaps and volume textures. This uses the first (largest) - * mipmap. - */ - void setColourAt(ColourValue const &cv, size_t x, size_t y, size_t z); - }; - - - /** - * Some utility functions for packing and unpacking pixel data - */ - class _OgreExport PixelUtil { - public: - /** Returns the size in bytes of an element of the given pixel format. - @return - The size in bytes of an element. See Remarks. - - Passing PF_UNKNOWN will result in returning a size of 0 bytes. - */ - static uint8 getNumElemBytes( PixelFormat format ); - - /** Returns the size in bits of an element of the given pixel format. - @return - The size in bits of an element. See Remarks. - - Passing PF_UNKNOWN will result in returning a size of 0 bits. - */ - static uint8 getNumElemBits( PixelFormat format ); - - /** Returns the size in memory of a region with the given extents and pixel - format with consecutive memory layout. - @param width - The width of the area - @param height - The height of the area - @param depth - The depth of the area - @param format - The format of the area - @return - The size in bytes - - In case that the format is non-compressed, this simply returns - width * height * depth * PixelUtil::getNumElemBytes(format). In the compressed - case, this does serious magic. - */ - static size_t getMemorySize(uint32 width, uint32 height, uint32 depth, PixelFormat format); - - /** Returns the property flags for this pixel format - @return - A bitfield combination of PFF_HASALPHA, PFF_ISCOMPRESSED, - PFF_FLOAT, PFF_DEPTH, PFF_NATIVEENDIAN, PFF_LUMINANCE - - This replaces the separate functions for formatHasAlpha, formatIsFloat, ... - */ - static unsigned int getFlags( PixelFormat format ); - - /** Shortcut method to determine if the format has an alpha component */ - static bool hasAlpha(PixelFormat format); - /** Shortcut method to determine if the format is floating point */ - static bool isFloatingPoint(PixelFormat format); - /** Shortcut method to determine if the format is integer */ - static bool isInteger(PixelFormat format); - /** Shortcut method to determine if the format is compressed */ - static bool isCompressed(PixelFormat format); - /** Shortcut method to determine if the format is a depth format. */ - static bool isDepth(PixelFormat format); - /** Shortcut method to determine if the format is in native endian format. */ - static bool isNativeEndian(PixelFormat format); - /** Shortcut method to determine if the format is a luminance format. */ - static bool isLuminance(PixelFormat format); - - /** Gives the number of bits (RGBA) for a format. See remarks. - @remarks For non-colour formats (dxt, depth) this returns [0,0,0,0]. - */ - static void getBitDepths(PixelFormat format, int rgba[4]); - - /** Gives the masks for the R, G, B and A component - @note Only valid for native endian formats - */ - static void getBitMasks(PixelFormat format, uint64 rgba[4]); - - /** Gives the bit shifts for R, G, B and A component - @note Only valid for native endian formats - */ - static void getBitShifts(PixelFormat format, unsigned char rgba[4]); - - /** Gets the name of an image format - */ - static const String& getFormatName(PixelFormat srcformat); - - /** Returns whether the format can be packed or unpacked with the packColour() - and unpackColour() functions. This is generally not true for compressed - formats as they are special. It can only be true for formats with a - fixed element size. - */ - static bool isAccessible(PixelFormat srcformat); - - /** Returns the component type for a certain pixel format. Returns PCT_BYTE - in case there is no clear component type like with compressed formats. - This is one of PCT_BYTE, PCT_SHORT, PCT_FLOAT16, PCT_FLOAT32. - */ - static PixelComponentType getComponentType(PixelFormat fmt); - - /** Returns the component count for a certain pixel format. Returns 3(no alpha) or - 4 (has alpha) in case there is no clear component type like with compressed formats. - */ - static uint8 getComponentCount(PixelFormat fmt); - - /** Gets the format from given name. - @param name The string of format name - @param accessibleOnly If true, non-accessible format will treat as invalid format, - otherwise, all supported format are valid. - @param caseSensitive Should be set true if string match should use case sensitivity. - @return The format match the format name, or PF_UNKNOWN if is invalid name. - */ - static PixelFormat getFormatFromName(const String& name, bool accessibleOnly = false, bool caseSensitive = false); - - /** Returns the similar format but according with given bit depths. - @param fmt The original format. - @param integerBits Preferred bit depth (pixel bits) for integer pixel format. - Available values: 0, 16 and 32, where 0 (the default) means as it is. - @param floatBits Preferred bit depth (channel bits) for float pixel format. - Available values: 0, 16 and 32, where 0 (the default) means as it is. - @return The format that similar original format with bit depth according - with preferred bit depth, or original format if no conversion occurring. - */ - static PixelFormat getFormatForBitDepths(PixelFormat fmt, ushort integerBits, ushort floatBits); - - /** Pack a colour value to memory - @param colour The colour - @param pf Pixelformat in which to write the colour - @param dest Destination memory location - */ - static void packColour(const ColourValue& colour, const PixelFormat pf, void* dest) - { - packColour(colour.r, colour.g, colour.b, colour.a, pf, dest); - } - /** Pack a colour value to memory - @param r,g,b,a The four colour components, range 0.0f to 1.0f - (an exception to this case exists for floating point pixel - formats, which don't clamp to 0.0f..1.0f) - @param pf Pixelformat in which to write the colour - @param dest Destination memory location - */ - static void packColour(const uint8 r, const uint8 g, const uint8 b, const uint8 a, const PixelFormat pf, void* dest); - /// @overload - static void packColour(const float r, const float g, const float b, const float a, const PixelFormat pf, void* dest); - - /** Unpack a colour value from memory - @param colour The colour is returned here - @param pf Pixelformat in which to read the colour - @param src Source memory location - */ - static void unpackColour(ColourValue& colour, PixelFormat pf, const void* src) - { - unpackColour(&colour.r, &colour.g, &colour.b, &colour.a, pf, src); - } - /// @overload - static void unpackColour(ColourValue* colour, PixelFormat pf, const void* src) - { - unpackColour(&colour->r, &colour->g, &colour->b, &colour->a, pf, src); - } - /** Unpack a colour value from memory - @param r,g,b,a The four colour channels are returned here - @param pf Pixelformat in which to read the colour - @param src Source memory location - */ - static void unpackColour(float *r, float *g, float *b, float *a, PixelFormat pf, const void* src); - /** @overload - @note This function returns the colour components in 8 bit precision, - this will lose precision when coming from #PF_A2R10G10B10 or floating - point formats. - */ - static void unpackColour(uint8 *r, uint8 *g, uint8 *b, uint8 *a, PixelFormat pf, const void* src); - - /** Convert consecutive pixels from one format to another. No dithering or filtering is being done. - Converting from RGB to luminance takes the R channel. In case the source and destination format match, - just a copy is done. - @param src Pointer to source region - @param srcFormat Pixel format of source region - @param dst Pointer to destination region - @param dstFormat Pixel format of destination region - @param count The number of pixels to convert - */ - static void bulkPixelConversion(void *src, PixelFormat srcFormat, void *dst, PixelFormat dstFormat, unsigned int count) - { - bulkPixelConversion(PixelBox(count, 1, 1, srcFormat, src), PixelBox(count, 1, 1, dstFormat, dst)); - } - - /** Convert pixels from one format to another. No dithering or filtering is being done. Converting - from RGB to luminance takes the R channel. - @param src PixelBox containing the source pixels, pitches and format - @param dst PixelBox containing the destination pixels, pitches and format - @remarks The source and destination boxes must have the same - dimensions. In case the source and destination format match, a plain copy is done. - */ - static void bulkPixelConversion(const PixelBox &src, const PixelBox &dst); - - /** Flips pixels inplace in vertical direction. - @param box PixelBox containing pixels, pitches and format - @remarks Non consecutive pixel boxes are supported. - */ - static void bulkPixelVerticalFlip(const PixelBox &box); - }; - - inline const String& to_string(PixelFormat v) { return PixelUtil::getFormatName(v); } - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgrePlane.h b/OgreMain/include/OgrePlane.h deleted file mode 100644 index e2b34422b8a..00000000000 --- a/OgreMain/include/OgrePlane.h +++ /dev/null @@ -1,281 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -// This file is based on material originally from: -// Geometric Tools, LLC -// Copyright (c) 1998-2010 -// Distributed under the Boost Software License, Version 1.0. -// http://www.boost.org/LICENSE_1_0.txt -// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt - - -#ifndef __Plane_H__ -#define __Plane_H__ - -#include "OgrePrerequisites.h" - -#include "OgreVector.h" -#include "OgreAxisAlignedBox.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - /** Defines a plane in 3D space. - - A plane is defined in 3D space by the equation - Ax + By + Cz + D = 0 - @par - This equates to a vector (the normal of the plane, whose x, y - and z components equate to the coefficients A, B and C - respectively), and a constant (D) which is the distance along - the normal you have to go to move the plane back to the origin. - */ - class _OgreExport Plane - { - public: - Vector3 normal; - Real d; - - public: - /** Default constructor - sets everything to 0. - */ - Plane() : normal(Vector3::ZERO), d(0.0f) {} - /** Construct a plane through a normal, and a distance to move the plane along the normal.*/ - Plane(const Vector3& rkNormal, Real fConstant) - { - normal = rkNormal; - d = -fConstant; - } - /** Construct a plane using the 4 constants directly **/ - Plane(Real a, Real b, Real c, Real _d) : normal(a, b, c), d(_d) {} - /// @overload - explicit Plane(const Vector4& v) : normal(v.xyz()), d(v.w) {} - Plane(const Vector3& rkNormal, const Vector3& rkPoint) - { - redefine(rkNormal, rkPoint); - } - Plane(const Vector3& p0, const Vector3& p1, const Vector3& p2) - { - redefine(p0, p1, p2); - } - - /** The "positive side" of the plane is the half space to which the - plane normal points. The "negative side" is the other half - space. The flag "no side" indicates the plane itself. - */ - enum Side - { - NO_SIDE, - POSITIVE_SIDE, - NEGATIVE_SIDE, - BOTH_SIDE - }; - - Side getSide(const Vector3& rkPoint) const - { - Real fDistance = getDistance(rkPoint); - - if (fDistance < 0.0) - return Plane::NEGATIVE_SIDE; - - if (fDistance > 0.0) - return Plane::POSITIVE_SIDE; - - return Plane::NO_SIDE; - } - - /** - Returns the side where the alignedBox is. The flag BOTH_SIDE indicates an intersecting box. - One corner ON the plane is sufficient to consider the box and the plane intersecting. - */ - Side getSide(const AxisAlignedBox& box) const - { - if (box.isNull()) - return NO_SIDE; - if (box.isInfinite()) - return BOTH_SIDE; - - return getSide(box.getCenter(), box.getHalfSize()); - } - - /** Returns which side of the plane that the given box lies on. - The box is defined as centre/half-size pairs for effectively. - @param centre The centre of the box. - @param halfSize The half-size of the box. - @return - POSITIVE_SIDE if the box complete lies on the "positive side" of the plane, - NEGATIVE_SIDE if the box complete lies on the "negative side" of the plane, - and BOTH_SIDE if the box intersects the plane. - */ - Side getSide(const Vector3& centre, const Vector3& halfSize) const - { - // Calculate the distance between box centre and the plane - Real dist = getDistance(centre); - - // Calculate the maximise allows absolute distance for - // the distance between box centre and plane - Real maxAbsDist = normal.absDotProduct(halfSize); - - if (dist < -maxAbsDist) - return NEGATIVE_SIDE; - - if (dist > +maxAbsDist) - return POSITIVE_SIDE; - - return BOTH_SIDE; - } - - /** This is a pseudodistance. The sign of the return value is - positive if the point is on the positive side of the plane, - negative if the point is on the negative side, and zero if the - point is on the plane. - @par - The absolute value of the return value is the true distance only - when the plane normal is a unit length vector. - */ - Real getDistance(const Vector3& rkPoint) const - { - return normal.dotProduct(rkPoint) + d; - } - - /** Redefine this plane based on 3 points. */ - void redefine(const Vector3& p0, const Vector3& p1, const Vector3& p2) - { - normal = Math::calculateBasicFaceNormal(p0, p1, p2); - d = -normal.dotProduct(p0); - } - - /** Redefine this plane based on a normal and a point. */ - void redefine(const Vector3& rkNormal, const Vector3& rkPoint) - { - normal = rkNormal; - d = -rkNormal.dotProduct(rkPoint); - } - - /** Project a vector onto the plane. - @remarks This gives you the element of the input vector that is perpendicular - to the normal of the plane. You can get the element which is parallel - to the normal of the plane by subtracting the result of this method - from the original vector, since parallel + perpendicular = original. - @param v The input vector - */ - Vector3 projectVector(const Vector3& v) const - { - // We know plane normal is unit length, so use simple method - Matrix3 xform; - xform[0][0] = 1.0f - normal.x * normal.x; - xform[0][1] = -normal.x * normal.y; - xform[0][2] = -normal.x * normal.z; - xform[1][0] = -normal.y * normal.x; - xform[1][1] = 1.0f - normal.y * normal.y; - xform[1][2] = -normal.y * normal.z; - xform[2][0] = -normal.z * normal.x; - xform[2][1] = -normal.z * normal.y; - xform[2][2] = 1.0f - normal.z * normal.z; - return xform * v; - } - - /** Normalises the plane. - - This method normalises the plane's normal and the length scale of d - is as well. - @note - This function will not crash for zero-sized vectors, but there - will be no changes made to their components. - @return The previous length of the plane's normal. - */ - Real normalise(void) - { - Real fLength = normal.length(); - - // Will also work for zero-sized vectors, but will change nothing - // We're not using epsilons because we don't need to. - // Read http://www.ogre3d.org/forums/viewtopic.php?f=4&t=61259 - if (fLength > Real(0.0f)) - { - Real fInvLength = 1.0f / fLength; - normal *= fInvLength; - d *= fInvLength; - } - - return fLength; - } - - /// Get flipped plane, with same location but reverted orientation - Plane operator - () const - { - return Plane(-(normal.x), -(normal.y), -(normal.z), -d); // not equal to Plane(-normal, -d) - } - - /// Comparison operator - bool operator==(const Plane& rhs) const - { - return (rhs.d == d && rhs.normal == normal); - } - bool operator!=(const Plane& rhs) const - { - return (rhs.d != d || rhs.normal != normal); - } - - friend std::ostream& operator<<(std::ostream& o, const Plane& p) - { - o << "Plane(normal=" << p.normal << ", d=" << p.d << ")"; - return o; - } - }; - - inline Plane operator * (const Matrix4& mat, const Plane& p) - { - Plane ret; - Matrix4 invTrans = mat.inverse().transpose(); - Vector4 v4( p.normal.x, p.normal.y, p.normal.z, p.d ); - v4 = invTrans * v4; - ret.normal.x = v4.x; - ret.normal.y = v4.y; - ret.normal.z = v4.z; - ret.d = v4.w / ret.normal.normalise(); - - return ret; - } - - inline bool Math::intersects(const Plane& plane, const AxisAlignedBox& box) - { - return plane.getSide(box) == Plane::BOTH_SIDE; - } - - typedef std::vector PlaneList; - /** @} */ - /** @} */ - -} // namespace Ogre - -#endif diff --git a/OgreMain/include/OgrePlaneBoundedVolume.h b/OgreMain/include/OgrePlaneBoundedVolume.h deleted file mode 100644 index 3d4c08e349e..00000000000 --- a/OgreMain/include/OgrePlaneBoundedVolume.h +++ /dev/null @@ -1,138 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __PlaneBoundedVolume_H_ -#define __PlaneBoundedVolume_H_ - -// Precompiler options -#include "OgrePrerequisites.h" -#include "OgreAxisAlignedBox.h" -#include "OgreSphere.h" -#include "OgreMath.h" -#include "OgrePlane.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - /** Represents a convex volume bounded by planes. - */ - class _OgreExport PlaneBoundedVolume - { - public: - typedef std::vector PlaneList; - /// Publicly accessible plane list, you can modify this direct - PlaneList planes; - Plane::Side outside; - - PlaneBoundedVolume() :outside(Plane::NEGATIVE_SIDE) {} - /** Constructor, determines which side is deemed to be 'outside' */ - PlaneBoundedVolume(Plane::Side theOutside) - : outside(theOutside) {} - - /** Intersection test with AABB - @remarks May return false positives but will never miss an intersection. - */ - inline bool intersects(const AxisAlignedBox& box) const - { - if (box.isNull()) return false; - if (box.isInfinite()) return true; - - // Get centre of the box - Vector3 centre = box.getCenter(); - // Get the half-size of the box - Vector3 halfSize = box.getHalfSize(); - - PlaneList::const_iterator i, iend; - iend = planes.end(); - for (i = planes.begin(); i != iend; ++i) - { - const Plane& plane = *i; - - Plane::Side side = plane.getSide(centre, halfSize); - if (side == outside) - { - // Found a splitting plane therefore return not intersecting - return false; - } - } - - // couldn't find a splitting plane, assume intersecting - return true; - - } - /** Intersection test with Sphere - @remarks May return false positives but will never miss an intersection. - */ - inline bool intersects(const Sphere& sphere) const - { - PlaneList::const_iterator i, iend; - iend = planes.end(); - for (i = planes.begin(); i != iend; ++i) - { - const Plane& plane = *i; - - // Test which side of the plane the sphere is - Real d = plane.getDistance(sphere.getCenter()); - // Negate d if planes point inwards - if (outside == Plane::NEGATIVE_SIDE) d = -d; - - if ( (d - sphere.getRadius()) > 0) - return false; - } - - return true; - - } - - /** Intersection test with a Ray - @return std::pair of hit (bool) and distance - @remarks May return false positives but will never miss an intersection. - */ - inline std::pair intersects(const Ray& ray) - { - return Math::intersects(ray, planes, outside == Plane::POSITIVE_SIDE); - } - - }; - - typedef std::vector PlaneBoundedVolumeList; - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgrePlatform.h b/OgreMain/include/OgrePlatform.h deleted file mode 100644 index 1c19e765c9a..00000000000 --- a/OgreMain/include/OgrePlatform.h +++ /dev/null @@ -1,280 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Platform_H_ -#define __Platform_H_ - -#include "OgreConfig.h" -#include "OgreExports.h" - -/* Initial platform/compiler-related stuff to set. -*/ -#define OGRE_PLATFORM_WIN32 1 -#define OGRE_PLATFORM_LINUX 2 -#define OGRE_PLATFORM_APPLE 3 -#define OGRE_PLATFORM_APPLE_IOS 4 -#define OGRE_PLATFORM_ANDROID 5 -#define OGRE_PLATFORM_WINRT 7 -#define OGRE_PLATFORM_EMSCRIPTEN 8 - -#define OGRE_COMPILER_MSVC 1 -#define OGRE_COMPILER_GNUC 2 -#define OGRE_COMPILER_CLANG 3 - -#define OGRE_ENDIAN_LITTLE 1 -#define OGRE_ENDIAN_BIG 2 - -#define OGRE_ARCHITECTURE_32 1 -#define OGRE_ARCHITECTURE_64 2 - -#define OGRE_CPU_UNKNOWN 0 -#define OGRE_CPU_X86 1 -#define OGRE_CPU_PPC 2 -#define OGRE_CPU_ARM 3 -#define OGRE_CPU_MIPS 4 - -/* Find CPU type */ -#if defined(__i386__) || defined(__x86_64__) || defined(_M_IX86) || defined(_M_X64) || defined(_M_AMD64) -# define OGRE_CPU OGRE_CPU_X86 -#elif defined(__ppc__) || defined(__ppc64__) || defined(_M_PPC) -# define OGRE_CPU OGRE_CPU_PPC -#elif defined(__arm__) || defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM) || defined(_M_ARM64) -# define OGRE_CPU OGRE_CPU_ARM -#elif defined(__mips__) || defined(__mips64) || defined(__mips64_) || defined(_M_MIPS) -# define OGRE_CPU OGRE_CPU_MIPS -#else -# define OGRE_CPU OGRE_CPU_UNKNOWN -#endif - -/* Determine CPU endian. - We were once in situation when XCode could produce mixed endian fat binary with x86 and ppc archs inside, so it's safer to sniff compiler macros too - */ -#if defined(OGRE_CONFIG_BIG_ENDIAN) || (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) -# define OGRE_ENDIAN OGRE_ENDIAN_BIG -#else -# define OGRE_ENDIAN OGRE_ENDIAN_LITTLE -#endif - - -/* Finds the compiler type and version. -*/ -#if (defined( __WIN32__ ) || defined( _WIN32 )) && defined(__ANDROID__) // We are using NVTegra -# define OGRE_COMPILER OGRE_COMPILER_GNUC -# define OGRE_COMP_VER 470 -#elif defined( _MSC_VER ) -# define OGRE_COMPILER OGRE_COMPILER_MSVC -# define OGRE_COMP_VER _MSC_VER -#elif defined( __clang__ ) -# define OGRE_COMPILER OGRE_COMPILER_CLANG -# define OGRE_COMP_VER (((__clang_major__)*100) + \ - (__clang_minor__*10) + \ - __clang_patchlevel__) -#elif defined( __GNUC__ ) -# define OGRE_COMPILER OGRE_COMPILER_GNUC -# define OGRE_COMP_VER (((__GNUC__)*100) + \ - (__GNUC_MINOR__*10) + \ - __GNUC_PATCHLEVEL__) -#else -# pragma error "No known compiler. Abort! Abort!" - -#endif - -#define OGRE_COMPILER_MIN_VERSION(COMPILER, VERSION) (OGRE_COMPILER == (COMPILER) && OGRE_COMP_VER >= (VERSION)) - -/* See if we can use __forceinline or if we need to use __inline instead */ -#if OGRE_COMPILER_MIN_VERSION(OGRE_COMPILER_MSVC, 1200) - #define OGRE_FORCE_INLINE __forceinline -#elif OGRE_COMPILER_MIN_VERSION(OGRE_COMPILER_GNUC, 340) - #define OGRE_FORCE_INLINE inline __attribute__((always_inline)) -#else - #define OGRE_FORCE_INLINE __inline -#endif - -/* fallthrough attribute */ -#if OGRE_COMPILER_MIN_VERSION(OGRE_COMPILER_GNUC, 700) -#define OGRE_FALLTHROUGH __attribute__((fallthrough)) -#else -#define OGRE_FALLTHROUGH -#endif - -#if OGRE_COMPILER == OGRE_COMPILER_GNUC || OGRE_COMPILER == OGRE_COMPILER_CLANG -#define OGRE_NODISCARD __attribute__((__warn_unused_result__)) -#else -#define OGRE_NODISCARD -#endif - -/* define OGRE_NORETURN macro */ -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -# define OGRE_NORETURN __declspec(noreturn) -#elif OGRE_COMPILER == OGRE_COMPILER_GNUC || OGRE_COMPILER == OGRE_COMPILER_CLANG -# define OGRE_NORETURN __attribute__((noreturn)) -#else -# define OGRE_NORETURN -#endif - -/* Finds the current platform */ -#if (defined( __WIN32__ ) || defined( _WIN32 )) && !defined(__ANDROID__) -# include -# if defined(WINAPI_FAMILY) -# include -# if WINAPI_FAMILY == WINAPI_FAMILY_APP|| WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP -# define OGRE_PLATFORM OGRE_PLATFORM_WINRT -# else -# define OGRE_PLATFORM OGRE_PLATFORM_WIN32 -# endif -# else -# define OGRE_PLATFORM OGRE_PLATFORM_WIN32 -# endif -# define __OGRE_WINRT_STORE (OGRE_PLATFORM == OGRE_PLATFORM_WINRT && WINAPI_FAMILY == WINAPI_FAMILY_APP) // WindowsStore 8.0 and 8.1 -# define __OGRE_WINRT_PHONE (OGRE_PLATFORM == OGRE_PLATFORM_WINRT && WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) // WindowsPhone 8.0 and 8.1 -# define __OGRE_WINRT_PHONE_80 (OGRE_PLATFORM == OGRE_PLATFORM_WINRT && WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP && _WIN32_WINNT <= _WIN32_WINNT_WIN8) // Windows Phone 8.0 often need special handling, while 8.1 is OK -# ifndef _CRT_SECURE_NO_WARNINGS -# define _CRT_SECURE_NO_WARNINGS -# endif -# ifndef _SCL_SECURE_NO_WARNINGS -# define _SCL_SECURE_NO_WARNINGS -# endif -#elif defined(__EMSCRIPTEN__) -# define OGRE_PLATFORM OGRE_PLATFORM_EMSCRIPTEN -#elif defined( __APPLE_CC__) -# include "Availability.h" -# ifdef __IPHONE_OS_VERSION_MIN_REQUIRED -# define OGRE_PLATFORM OGRE_PLATFORM_APPLE_IOS -# else -# define OGRE_PLATFORM OGRE_PLATFORM_APPLE -# endif -#elif defined(__ANDROID__) -# define OGRE_PLATFORM OGRE_PLATFORM_ANDROID -#else -# define OGRE_PLATFORM OGRE_PLATFORM_LINUX -#endif - -/* Find the arch type */ -#if defined(__LP64__) || defined(_WIN64) -# define OGRE_ARCH_TYPE OGRE_ARCHITECTURE_64 -#else -# define OGRE_ARCH_TYPE OGRE_ARCHITECTURE_32 -#endif - -/* Find how to declare aligned variable. */ -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -# define OGRE_ALIGNED_DECL(type, var, alignment) __declspec(align(alignment)) type var -#elif (OGRE_COMPILER == OGRE_COMPILER_GNUC) || (OGRE_COMPILER == OGRE_COMPILER_CLANG) -# define OGRE_ALIGNED_DECL(type, var, alignment) type var __attribute__((__aligned__(alignment))) -#else -# define OGRE_ALIGNED_DECL(type, var, alignment) type var -#endif - -/** Find perfect alignment (should supports SIMD alignment if SIMD available) */ -#define OGRE_SIMD_ALIGNMENT 16 - -/* Declare variable aligned to SIMD alignment. */ -#define OGRE_SIMD_ALIGNED_DECL(type, var) OGRE_ALIGNED_DECL(type, var, OGRE_SIMD_ALIGNMENT) - - -// For generating compiler warnings - should work on any compiler -// As a side note, if you start your message with 'Warning: ', the MSVC -// IDE actually does catch a warning :) -#define OGRE_QUOTE_INPLACE(x) # x -#define OGRE_QUOTE(x) OGRE_QUOTE_INPLACE(x) -#define OGRE_WARN( x ) message( __FILE__ "(" QUOTE( __LINE__ ) ") : " x "\n" ) - -//---------------------------------------------------------------------------- -// Windows Settings -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT - -// on windows we override OgreBuildSettings.h for convenience -// see https://bitbucket.org/sinbad/ogre/pull-requests/728 -#ifdef OGRE_DEBUG_MODE -#undef OGRE_DEBUG_MODE -#endif - -// Win32 compilers use _DEBUG for specifying debug builds. -// for MinGW, we use NDEBUG -# if defined(_DEBUG) || (defined(__MINGW32__) && !defined(NDEBUG)) -# define OGRE_DEBUG_MODE 1 -# else -# define OGRE_DEBUG_MODE 0 -# endif - -#endif // OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT - -//---------------------------------------------------------------------------- -// Android Settings -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID -# ifndef CLOCKS_PER_SEC -# define CLOCKS_PER_SEC 1000 -# endif -#endif - -//---------------------------------------------------------------------------- -// Endian Settings -// check for BIG_ENDIAN config flag, set OGRE_ENDIAN correctly -#ifdef OGRE_CONFIG_BIG_ENDIAN -# define OGRE_ENDIAN OGRE_ENDIAN_BIG -#else -# define OGRE_ENDIAN OGRE_ENDIAN_LITTLE -#endif - -//---------------------------------------------------------------------------- -// Set the default locale for strings -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID -// Locales are not supported by the C lib you have to go through JNI. -# define OGRE_DEFAULT_LOCALE "" -#else -# define OGRE_DEFAULT_LOCALE "C" -#endif - -//---------------------------------------------------------------------------- -// Library suffixes -// "_d" for debug builds, nothing otherwise -#if OGRE_DEBUG_MODE && OGRE_PLATFORM == OGRE_PLATFORM_WIN32 -# define OGRE_BUILD_SUFFIX "_d" -#else -# define OGRE_BUILD_SUFFIX "" -#endif - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -#define DECL_MALLOC __declspec(restrict) __declspec(noalias) -#else -#define DECL_MALLOC __attribute__ ((malloc)) -#endif - -#include - -namespace Ogre { -typedef uint32_t uint32; -typedef uint16_t uint16; -typedef uint8_t uint8; -typedef uint64_t uint64; -typedef int32_t int32; -typedef int16_t int16; -typedef int8_t int8; -typedef int64_t int64; -} - -#endif diff --git a/OgreMain/include/OgrePlatformInformation.h b/OgreMain/include/OgrePlatformInformation.h deleted file mode 100644 index 0f2023cea53..00000000000 --- a/OgreMain/include/OgrePlatformInformation.h +++ /dev/null @@ -1,162 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __PlatformInformation_H__ -#define __PlatformInformation_H__ - -#include "OgrePrerequisites.h" - -namespace Ogre { -/* Define whether or not Ogre compiled with SSE support. -*/ -#if OGRE_DOUBLE_PRECISION == 0 && OGRE_CPU == OGRE_CPU_X86 && OGRE_COMPILER == OGRE_COMPILER_MSVC -# define __OGRE_HAVE_SSE 1 -#elif OGRE_DOUBLE_PRECISION == 0 && OGRE_CPU == OGRE_CPU_X86 && (OGRE_COMPILER == OGRE_COMPILER_GNUC || OGRE_COMPILER == OGRE_COMPILER_CLANG) && \ - OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS -# define __OGRE_HAVE_SSE 1 -#endif - -/* Define whether or not Ogre compiled with VFP support. - */ -#if OGRE_DOUBLE_PRECISION == 0 && OGRE_CPU == OGRE_CPU_ARM && (OGRE_COMPILER == OGRE_COMPILER_GNUC || OGRE_COMPILER == OGRE_COMPILER_CLANG) && defined(__VFP_FP__) -# define __OGRE_HAVE_VFP 1 -#endif - -/* Define whether or not Ogre compiled with NEON support. - */ -#if OGRE_DOUBLE_PRECISION == 0 && OGRE_CPU == OGRE_CPU_ARM && (OGRE_COMPILER == OGRE_COMPILER_GNUC || OGRE_COMPILER == OGRE_COMPILER_CLANG) && defined(__ARM_NEON__) -# define __OGRE_HAVE_NEON 1 -#endif - -/* Define whether or not Ogre compiled with MSA support. - */ -#if OGRE_DOUBLE_PRECISION == 0 && OGRE_CPU == OGRE_CPU_MIPS && (OGRE_COMPILER == OGRE_COMPILER_GNUC || OGRE_COMPILER == OGRE_COMPILER_CLANG) && defined(__mips_msa) -# define __OGRE_HAVE_MSA 1 -#endif - -#ifndef __OGRE_HAVE_SSE -# define __OGRE_HAVE_SSE 0 -#endif - -#ifndef __OGRE_HAVE_VFP -# define __OGRE_HAVE_VFP 0 -#endif - -#ifndef __OGRE_HAVE_NEON -# define __OGRE_HAVE_NEON 0 -#endif - -#ifndef __OGRE_HAVE_MSA -# define __OGRE_HAVE_MSA 0 -#endif - - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - - - /** Class which provides the run-time platform information Ogre runs on. - - Ogre is designed to be platform-independent, but some platform - and run-time environment specific optimised functions are built-in - to maximise performance, and those special optimised routines are - need to determine run-time environment for select variant executing - path. - @par - This class manages that provides a couple of functions to determine - platform information of the run-time environment. - @note - This class is supposed to use by advanced user only. - */ - class _OgreExport PlatformInformation - { - public: - - /// Enum describing the different CPU features we want to check for, platform-dependent - enum CpuFeatures - { -#if OGRE_CPU == OGRE_CPU_X86 - CPU_FEATURE_SSE = 1 << 0, - CPU_FEATURE_SSE2 = 1 << 1, - CPU_FEATURE_SSE3 = 1 << 2, - CPU_FEATURE_SSE41 = 1 << 3, - CPU_FEATURE_SSE42 = 1 << 4, - CPU_FEATURE_MMX = 1 << 5, - CPU_FEATURE_MMXEXT = 1 << 6, - CPU_FEATURE_3DNOW = 1 << 7, - CPU_FEATURE_3DNOWEXT = 1 << 8, - CPU_FEATURE_CMOV = 1 << 9, - CPU_FEATURE_TSC = 1 << 10, - CPU_FEATURE_INVARIANT_TSC = 1 << 11, - CPU_FEATURE_FPU = 1 << 12, - CPU_FEATURE_PRO = 1 << 13, - CPU_FEATURE_HTT = 1 << 14, -#elif OGRE_CPU == OGRE_CPU_ARM - CPU_FEATURE_VFP = 1 << 15, - CPU_FEATURE_NEON = 1 << 16, -#elif OGRE_CPU == OGRE_CPU_MIPS - CPU_FEATURE_MSA = 1 << 17, -#endif - - CPU_FEATURE_NONE = 0 - }; - - /** Gets a string of the CPU identifier. - @note - Actual detecting are performs in the first time call to this function, - and then all future calls with return internal cached value. - */ - static const String& getCpuIdentifier(void); - - /** Gets a or-masked of enum CpuFeatures that are supported by the CPU. - @note - Actual detecting are performs in the first time call to this function, - and then all future calls with return internal cached value. - */ - static uint getCpuFeatures(void); - - /** Gets whether a specific feature is supported by the CPU. - @note - Actual detecting are performs in the first time call to this function, - and then all future calls with return internal cached value. - */ - static bool hasCpuFeature(CpuFeatures feature); - - - /** Write the CPU information to the passed in Log */ - static void log(Log* pLog); - - }; - /** @} */ - /** @} */ - -} - -#endif // __PlatformInformation_H__ diff --git a/OgreMain/include/OgrePlugin.h b/OgreMain/include/OgrePlugin.h deleted file mode 100644 index 73bfcf3a0bc..00000000000 --- a/OgreMain/include/OgrePlugin.h +++ /dev/null @@ -1,139 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OGREPLUGIN_H__ -#define __OGREPLUGIN_H__ - -#include "OgrePrerequisites.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - /** Class defining a generic OGRE plugin. - - OGRE is very plugin-oriented and you can customise much of its behaviour - by registering new plugins, dynamically if you are using dynamic linking. - This class abstracts the generic interface that all plugins must support. - Within the implementations of this interface, the plugin must call other - OGRE classes in order to register the detailed customisations it is - providing, e.g. registering a new SceneManagerFactory, a new - MovableObjectFactory, or a new RenderSystem. - @par - Plugins can be linked statically or dynamically. If they are linked - dynamically (ie the plugin is in a DLL or Shared Object file), then you - load the plugin by calling the Root::loadPlugin method (or some other - mechanism which leads to that call, e.g. plugins.cfg), passing the name of - the DLL. OGRE will then call a global init function on that DLL, and it - will be expected to register one or more Plugin implementations using - Root::installPlugin. The procedure is very similar if you use a static - linked plugin, except that you simply instantiate the Plugin implementation - yourself and pass it to Root::installPlugin. - @note - Lifecycle of a Plugin instance is very important. The Plugin instance must - remain valid until the Plugin is uninstalled. Here are the things you - must bear in mind: -
  • If your plugin is in a DLL: -
    • Create the Plugin instance and call Root::installPlugin in dllStartPlugin
    • -
    • Call Root::uninstallPlugin, then delete it in dllStopPlugin
    -
  • If your plugin is statically linked in your app: -
    • Create the Plugin anytime you like
    • -
    • Call Root::installPlugin any time whilst Root is valid
    • -
    • Call Root::uninstallPlugin if you like so long as Root is valid. However, - it will be done for you when Root is destroyed, so the Plugin instance must - still be valid at that point if you haven't manually uninstalled it.
    -
- The install and uninstall methods will be called when the plugin is - installed or uninstalled. The initialise and shutdown will be called when - there is a system initialisation or shutdown, e.g. when Root::initialise - or Root::shutdown are called. - */ - class _OgreExport Plugin : public PluginAlloc - { - public: - Plugin() {} - virtual ~Plugin() {} - - /** Get the name of the plugin. - @remarks An implementation must be supplied for this method to uniquely - identify the plugin. - */ - virtual const String& getName() const = 0; - - /** Perform the plugin initial installation sequence. - @remarks An implementation must be supplied for this method. It must perform - the startup tasks necessary to install any rendersystem customisations - or anything else that is not dependent on system initialisation, ie - only dependent on the core of Ogre. It must not perform any - operations that would create rendersystem-specific objects at this stage, - that should be done in initialise(). - */ - virtual void install() = 0; - - /** Perform any tasks the plugin needs to perform on full system - initialisation. - @remarks An implementation must be supplied for this method. It is called - just after the system is fully initialised (either after Root::initialise - if a window is created then, or after the first window is created) - and therefore all rendersystem functionality is available at this - time. You can use this hook to create any resources which are - dependent on a rendersystem or have rendersystem-specific implementations. - */ - virtual void initialise() = 0; - - /** Perform any tasks the plugin needs to perform when the system is shut down. - @remarks An implementation must be supplied for this method. - This method is called just before key parts of the system are unloaded, - such as rendersystems being shut down. You should use this hook to free up - resources and decouple custom objects from the OGRE system, whilst all the - instances of other plugins (e.g. rendersystems) still exist. - */ - virtual void shutdown() = 0; - - /** Perform the final plugin uninstallation sequence. - @remarks An implementation must be supplied for this method. It must perform - the cleanup tasks which haven't already been performed in shutdown() - (e.g. final deletion of custom instances, if you kept them around in case - the system was reinitialised). At this stage you cannot be sure what other - plugins are still loaded or active. It must therefore not perform any - operations that would reference any rendersystem-specific objects - those - should have been sorted out in the 'shutdown' method. - */ - virtual void uninstall() = 0; - }; - /** @} */ - /** @} */ - -} - -#endif - - diff --git a/OgreMain/include/OgrePolygon.h b/OgreMain/include/OgrePolygon.h deleted file mode 100644 index e2ceb4be282..00000000000 --- a/OgreMain/include/OgrePolygon.h +++ /dev/null @@ -1,150 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Copyright (c) 2006 Matthias Fink, netAllied GmbH - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Polygon_H__ -#define __Polygon_H__ - -#include "OgrePrerequisites.h" -#include "OgreVector.h" -#include "OgreHeaderPrefix.h" - - -namespace Ogre -{ - - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - /** The class represents a polygon in 3D space. - - It is made up of 3 or more vertices in a single plane, listed in - counter-clockwise order. - */ - class _OgreExport Polygon - { - - public: - typedef std::vector VertexList; - - typedef std::multimap EdgeMap; - typedef std::pair< Vector3, Vector3> Edge; - - private: - VertexList mVertexList; - mutable Vector3 mNormal; - mutable bool mIsNormalSet; - /** Updates the normal. - */ - void updateNormal(void) const; - - - public: - Polygon(); - ~Polygon(); - Polygon( const Polygon& cpy ); - - /** Inserts a vertex at a specific position. - @note Vertices must be coplanar. - */ - void insertVertex(const Vector3& vdata, size_t vertexIndex); - /** Inserts a vertex at the end of the polygon. - @note Vertices must be coplanar. - */ - void insertVertex(const Vector3& vdata); - - /** Returns a vertex. - */ - const Vector3& getVertex(size_t vertex) const; - - /** Sets a specific vertex of a polygon. - @note Vertices must be coplanar. - */ - void setVertex(const Vector3& vdata, size_t vertexIndex); - - /** Removes duplicate vertices from a polygon. - */ - void removeDuplicates(void); - - /** Vertex count. - */ - size_t getVertexCount(void) const; - - /** Returns the polygon normal. - */ - const Vector3& getNormal(void) const; - - /** Deletes a specific vertex. - */ - void deleteVertex(size_t vertex); - - /** Determines if a point is inside the polygon. - - A point is inside a polygon if it is both on the polygon's plane, - and within the polygon's bounds. Polygons are assumed to be convex - and planar. - */ - bool isPointInside(const Vector3& point) const; - - /** Stores the edges of the polygon in ccw order. - The vertices are copied so the user has to take the - deletion into account. - */ - void storeEdges(EdgeMap *edgeMap) const; - - /** Resets the object. - */ - void reset(void); - - /** Determines if the current object is equal to the compared one. - */ - bool operator == (const Polygon& rhs) const; - - /** Determines if the current object is not equal to the compared one. - */ - bool operator != (const Polygon& rhs) const - { return !( *this == rhs ); } - - Polygon& operator=(const Ogre::Polygon&) ; - - /** Prints out the polygon data. - */ - _OgreExport friend std::ostream& operator<< ( std::ostream& strm, const Polygon& poly ); - - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgrePose.h b/OgreMain/include/OgrePose.h deleted file mode 100644 index 124fcfd5068..00000000000 --- a/OgreMain/include/OgrePose.h +++ /dev/null @@ -1,157 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OGRE_POSE_H -#define __OGRE_POSE_H - -#include "OgrePrerequisites.h" -#include "OgreCommon.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - template class MapIterator; - template class ConstMapIterator; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Animation - * @{ - */ - /** A pose is a linked set of vertex offsets applying to one set of vertex - data. - - The target index referred to by the pose has a meaning set by the user - of this class; but for example when used by Mesh it refers to either the - Mesh shared geometry (0) or a SubMesh dedicated geometry (1+). - Pose instances can be referred to by keyframes in VertexAnimationTrack in - order to animate based on blending poses together. - */ - class _OgreExport Pose : public AnimationAlloc - { - public: - /** Constructor - @param target The target vertexdata index (0 for shared, 1+ for - dedicated at the submesh index + 1) - @param name Optional name - */ - Pose(ushort target, const String& name = BLANKSTRING); - /// Return the name of the pose (may be blank) - const String& getName(void) const { return mName; } - /// Return the target geometry index of the pose - ushort getTarget(void) const { return mTarget; } - /// A collection of vertex offsets based on the vertex index - typedef std::map VertexOffsetMap; - /// An iterator over the vertex offsets - typedef MapIterator VertexOffsetIterator; - /// An iterator over the vertex offsets - typedef ConstMapIterator ConstVertexOffsetIterator; - /// A collection of normals based on the vertex index - typedef std::map NormalsMap; - /// An iterator over the vertex offsets - typedef MapIterator NormalsIterator; - /// An iterator over the vertex offsets - typedef ConstMapIterator ConstNormalsIterator; - /// Return whether the pose vertices include normals - bool getIncludesNormals() const { return !mNormalsMap.empty(); } - - /** Adds an offset to a vertex for this pose. - @param index The vertex index - @param offset The position offset for this pose - */ - void addVertex(uint32 index, const Vector3f& offset); - - /** Adds an offset to a vertex and a new normal for this pose. - @param index The vertex index - @param offset The position offset for this pose - @param normal The new vertex normal - */ - void addVertex(uint32 index, const Vector3f& offset, const Vector3f& normal); - - /** Remove a vertex offset. */ - void removeVertex(uint32 index); - - /** Clear all vertices. */ - void clearVertices(void); - - /// @deprecated use getVertexOffsets - OGRE_DEPRECATED ConstVertexOffsetIterator getVertexOffsetIterator(void) const; - /// @deprecated use getVertexOffsets - OGRE_DEPRECATED VertexOffsetIterator getVertexOffsetIterator(void); - /** Gets a const reference to the vertex offsets. */ - const VertexOffsetMap& getVertexOffsets(void) const { return mVertexOffsetMap; } - - /// @deprecated use getNormals - OGRE_DEPRECATED ConstNormalsIterator getNormalsIterator(void) const; - /// @deprecated use getNormals - OGRE_DEPRECATED NormalsIterator getNormalsIterator(void); - /** Gets a const reference to the vertex normals */ - const NormalsMap& getNormals(void) const { return mNormalsMap; } - - /** writable access to the vertex offsets for offline processing - * - * @attention does not invalidate the vertexbuffer - */ - VertexOffsetMap& _getVertexOffsets() { return mVertexOffsetMap; } - - /** writable access to the vertex normals for offline processing - * - * @attention does not invalidate the vertexbuffer - */ - NormalsMap& _getNormals() { return mNormalsMap; } - - /** Get a hardware vertex buffer version of the vertex offsets. */ - const HardwareVertexBufferSharedPtr& _getHardwareVertexBuffer(const VertexData* origData) const; - - /** Clone this pose and create another one configured exactly the same - way (only really useful for cloning holders of this class). - */ - Pose* clone(void) const OGRE_NODISCARD; - private: - /// Target geometry index - ushort mTarget; - /// Optional name - String mName; - /// Primary storage, sparse vertex use - VertexOffsetMap mVertexOffsetMap; - /// Primary storage, sparse vertex use - NormalsMap mNormalsMap; - /// Derived hardware buffer, covers all vertices - mutable HardwareVertexBufferSharedPtr mBuffer; - }; - typedef std::vector PoseList; - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgrePredefinedControllers.h b/OgreMain/include/OgrePredefinedControllers.h deleted file mode 100644 index 571f39260c8..00000000000 --- a/OgreMain/include/OgrePredefinedControllers.h +++ /dev/null @@ -1,356 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __PredefinedControllers_H__ -#define __PredefinedControllers_H__ - -#include "OgrePrerequisites.h" - -#include "OgreCommon.h" -#include "OgreController.h" -#include "OgreFrameListener.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Animation - * @{ - */ - //----------------------------------------------------------------------- - // Controller Values - //----------------------------------------------------------------------- - /** Predefined controller value for getting the latest frame time. - */ - class _OgreExport FrameTimeControllerValue : public ControllerValue, private FrameListener - { - private: - Real mFrameTime; - Real mTimeFactor; - Real mElapsedTime; - Real mFrameDelay; - - bool frameStarted(const FrameEvent &evt) override; - public: - /// @deprecated use create() - FrameTimeControllerValue(); - - static ControllerValueRealPtr create() { return std::make_shared(); } - - float getValue(void) const override { return mFrameTime; } - void setValue(float value) override { /* Do nothing - value is set from frame listener */ } - Real getTimeFactor(void) const { return mTimeFactor; } - /// @copydoc ControllerManager::setTimeFactor - void setTimeFactor(Real tf); - Real getFrameDelay(void) const { return mFrameDelay; } - /// @copydoc ControllerManager::setFrameDelay - void setFrameDelay(Real fd); - Real getElapsedTime(void) const { return mElapsedTime; } - void setElapsedTime(Real elapsedTime) { mElapsedTime = elapsedTime; } - }; - - //----------------------------------------------------------------------- - /** Predefined controller value for getting / setting the frame number of a texture layer - */ - class _OgreExport TextureFrameControllerValue : public ControllerValue - { - private: - TextureUnitState* mTextureLayer; - public: - /// @deprecated use create() - TextureFrameControllerValue(TextureUnitState* t); - - static ControllerValueRealPtr create(TextureUnitState* t) - { - return std::make_shared(t); - } - - /** Gets the frame number as a parametric value in the range [0,1] - */ - float getValue(void) const override; - /** Sets the frame number as a parametric value in the range [0,1]; the actual frame number is (value * numFrames) % numFrames). - */ - void setValue(float value) override; - - }; - //----------------------------------------------------------------------- - /** Predefined controller value for getting / setting a texture coordinate modifications (scales and translates). - - Effects can be applied to the scale or the offset of the u or v coordinates, or both. If separate - modifications are required to u and v then 2 instances are required to control both independently, or 4 - if you want separate u and v scales as well as separate u and v offsets. - @par - Because of the nature of this value, it can accept values outside the 0..1 parametric range. - */ - class _OgreExport TexCoordModifierControllerValue : public ControllerValue - { - private: - bool mTransU, mTransV; - bool mScaleU, mScaleV; - bool mRotate; - TextureUnitState* mTextureLayer; - public: - /// @deprecated use create - TexCoordModifierControllerValue(TextureUnitState* t, bool translateU = false, bool translateV = false, - bool scaleU = false, bool scaleV = false, bool rotate = false ); - - /** Constructor. - @param - t TextureUnitState to apply the modification to. - @param - translateU If true, the u coordinates will be translated by the modification. - @param - translateV If true, the v coordinates will be translated by the modification. - @param - scaleU If true, the u coordinates will be scaled by the modification. - @param - scaleV If true, the v coordinates will be scaled by the modification. - @param - rotate If true, the texture will be rotated by the modification. - */ - static ControllerValueRealPtr create(TextureUnitState* t, bool translateU = false, bool translateV = false, - bool scaleU = false, bool scaleV = false, bool rotate = false) - { - return std::make_shared(t, translateU, translateV, scaleU, scaleV, rotate); - } - - float getValue(void) const override; - void setValue(float value) override; - - }; - - //----------------------------------------------------------------------- - /** Predefined controller value for setting a single floating- - point value in a constant parameter of a vertex or fragment program. - - Any value is accepted, it is propagated into the 'x' - component of the constant register identified by the index. If you - need to use named parameters, retrieve the index from the param - object before setting this controller up. - @note - Retrieving a value from the program parameters is not currently - supported, therefore do not use this controller value as a source, - only as a target. - */ - class _OgreExport FloatGpuParameterControllerValue : public ControllerValue - { - private: - /// The parameters to access - GpuProgramParametersSharedPtr mParams; - /// The index of the parameter to be read or set - size_t mParamIndex; - public: - /// @deprecated use create() - FloatGpuParameterControllerValue(const GpuProgramParametersSharedPtr& params, size_t index); - - /** Constructor. - @param - params The parameters object to access - @param - index The index of the parameter to be set - */ - static ControllerValueRealPtr create(const GpuProgramParametersSharedPtr& params, size_t index) - { - return std::make_shared(params, index); - } - - float getValue(void) const override; - void setValue(float value) override; - - }; - //----------------------------------------------------------------------- - // Controller functions - //----------------------------------------------------------------------- - - /** Predefined controller function which just passes through the original source - directly to dest. - */ - class _OgreExport PassthroughControllerFunction : public ControllerFunction - { - public: - /// @deprecated use create() - PassthroughControllerFunction(bool deltaInput = false); - - /// @copydoc ControllerFunction::ControllerFunction - static ControllerFunctionRealPtr create(bool deltaInput = false) - { - return std::make_shared(deltaInput); - } - - float calculate(float source) override; - }; - - /** Predefined controller function for dealing with animation. - */ - class _OgreExport AnimationControllerFunction : public ControllerFunction - { - private: - Real mSeqTime; - Real mTime; - public: - /// @deprecated use create() - AnimationControllerFunction(Real sequenceTime, Real timeOffset = 0.0f); - - /** Constructor. - @param - sequenceTime The amount of time in seconds it takes to loop through the whole animation sequence. - @param - timeOffset The offset in seconds at which to start (default is start at 0) - */ - static ControllerFunctionRealPtr create(Real sequenceTime, Real timeOffset = 0.0f) - { - return std::make_shared(sequenceTime, timeOffset); - } - - float calculate(float source) override; - - /** Set the time value manually. */ - void setTime(Real timeVal); - /** Set the sequence duration value manually. */ - void setSequenceTime(Real seqVal); - }; - - //----------------------------------------------------------------------- - /** Predefined controller function which simply scales an input to an output value. - */ - class _OgreExport ScaleControllerFunction : public ControllerFunction - { - private: - Real mScale; - public: - /// @deprecated use create() - ScaleControllerFunction(Real scalefactor, bool deltaInput); - - /** Constructor, requires a scale factor. - @param - scalefactor The multiplier applied to the input to produce the output. - @param - deltaInput If true, signifies that the input will be a delta value such that the function should - add it to an internal counter before calculating the output. - */ - static ControllerFunctionRealPtr create(Real scalefactor, bool deltaInput = false) - { - return std::make_shared(scalefactor, deltaInput); - } - - float calculate(float source) override; - }; - - //----------------------------------------------------------------------- - /** Predefined controller function based on a waveform. - - A waveform function translates parametric input to parametric output based on a wave. - @par - Note that for simplicity of integration with the rest of the controller insfrastructure, the output of - the wave is parametric i.e. 0..1, rather than the typical wave output of [-1,1]. To compensate for this, the - traditional output of the wave is scaled by the following function before output: - @par - output = (waveoutput + 1) * 0.5 - @par - Hence a wave output of -1 becomes 0, a wave output of 1 becomes 1, and a wave output of 0 becomes 0.5. - */ - class _OgreExport WaveformControllerFunction : public ControllerFunction - { - private: - WaveformType mWaveType; - Real mBase; - Real mFrequency; - Real mPhase; - Real mAmplitude; - Real mDutyCycle; - - /** Overridden from ControllerFunction. */ - Real getAdjustedInput(Real input); - - public: - /// @deprecated use create() - WaveformControllerFunction(WaveformType wType, Real base = 0, Real frequency = 1, Real phase = 0, Real amplitude = 1, bool deltaInput = true, Real dutyCycle = 0.5); - - /** Default constructor, requires at least a wave type, other parameters can be defaulted unless required. - @param wType the shape of the wave - @param base the base value of the output from the wave - @param frequency the speed of the wave in cycles per second - @param phase the offset of the start of the wave, e.g. 0.5 to start half-way through the wave - @param amplitude scales the output so that instead of lying within [0,1] it lies within [0,1] * amplitude - @param - deltaInput If true, signifies that the input will be a delta value such that the function should - add it to an internal counter before calculating the output. - @param - dutyCycle Used in PWM mode to specify the pulse width. - */ - static ControllerFunctionRealPtr create(WaveformType wType, Real base = 0, Real frequency = 1, Real phase = 0, Real amplitude = 1, bool deltaInput = true, Real dutyCycle = 0.5) - { - return std::make_shared(wType, base, frequency, phase, amplitude, deltaInput, dutyCycle); - } - - float calculate(float source) override; - }; - - //----------------------------------------------------------------------- - /** Predefined controller function based on linear function interpolation. - */ - class _OgreExport LinearControllerFunction : public ControllerFunction { - Real mFrequency; - std::vector mKeys; - std::vector mValues; - public: - /// @deprecated use create() - LinearControllerFunction(const std::vector& keys, const std::vector& values, Real frequency = 1, bool deltaInput = true); - - /** Constructor, requires keys and values of the function to interpolate - - For simplicity and compatibility with the predefined ControllerValue classes the function domain must be [0,1]. - However, you can use the frequency parameter to rescale the domain to a different range. - @param - keys the x-values of the function sampling points. Value range is [0,1]. Must include at least the keys 0 and 1. - @param - values the function values f(x) of the function. order must match keys - @param frequency the speed of the evaluation in cycles per second - @param - deltaInput If true, signifies that the input will be a delta value such that the function should - add it to an internal counter before calculating the output. - @note - there must be the same amount of keys and values - */ - static ControllerFunctionRealPtr create(const std::vector& keys, const std::vector& values, Real frequency = 1, bool deltaInput = true) - { - return std::make_shared(keys, values, frequency, deltaInput); - } - - float calculate(float source) override; - }; - //----------------------------------------------------------------------- - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgrePrerequisites.h b/OgreMain/include/OgrePrerequisites.h deleted file mode 100644 index 24e583f25be..00000000000 --- a/OgreMain/include/OgrePrerequisites.h +++ /dev/null @@ -1,347 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ -#ifndef __OgrePrerequisites_H__ -#define __OgrePrerequisites_H__ - -// Platform-specific stuff -#include "OgrePlatform.h" - -#include -#include - -namespace Ogre { - #define OGRE_TOKEN_PASTE_INNER(x, y) x ## y - #define OGRE_TOKEN_PASTE(x, y) OGRE_TOKEN_PASTE_INNER(x, y) - - #define OGRE_VERSION ((OGRE_VERSION_MAJOR << 16) | (OGRE_VERSION_MINOR << 8) | OGRE_VERSION_PATCH) - - #define OGRE_MIN_VERSION(MAJOR, MINOR, PATCH) OGRE_VERSION >= ((MAJOR << 16) | (MINOR << 8) | PATCH) - -// OSX needs this correctly export typeinfo, however on MSVC there is huge fallout with it. Linux is fine either way. -#if OGRE_COMPILER == OGRE_COMPILER_MSVC - #define _OgreMaybeExport -#else - #define _OgreMaybeExport _OgreExport -#endif - - // define the real number values to be used - // default to use 'float' unless precompiler option set - #if OGRE_DOUBLE_PRECISION == 1 - /** Software floating point type. - @note Not valid as a pointer to GPU buffers / parameters - */ - typedef double Real; - #else - /** Software floating point type. - @note Not valid as a pointer to GPU buffers / parameters - */ - typedef float Real; - #endif - - /** In order to avoid finger-aches :) - */ - typedef unsigned char uchar; - typedef unsigned short ushort; - typedef unsigned int uint; - typedef unsigned long ulong; - -// Pre-declare classes -// Allows use of pointers in header files without including individual .h -// so decreases dependencies between files - class Affine3; - class Angle; - class AnimableValue; - class Animation; - class AnimationState; - class AnimationStateSet; - class AnimationTrack; - class Archive; - class ArchiveFactory; - class ArchiveManager; - class AutoParamDataSource; - class AxisAlignedBox; - class AxisAlignedBoxSceneQuery; - class Billboard; - class BillboardChain; - class BillboardSet; - class Bone; - class Camera; - class Codec; - class ColourValue; - class ConfigDialog; - template class Controller; - typedef Controller ControllerFloat; - typedef Controller ControllerReal; - template class ControllerFunction; - class ControllerManager; - template class ControllerValue; - class DataStream; - class DebugDrawer; - class DefaultWorkQueue; - class Degree; - class DepthBuffer; - class DynLib; - class DynLibManager; - class EdgeData; - class EdgeListBuilder; - class Entity; - class ExternalTextureSourceManager; - class Factory; - struct FrameEvent; - class FrameListener; - class Frustum; - struct GpuLogicalBufferStruct; - struct GpuNamedConstants; - class GpuProgramParameters; - class GpuSharedParameters; - class GpuProgram; - class GpuProgramFactory; - typedef GpuProgramFactory HighLevelGpuProgramFactory; //!< @deprecated - class GpuProgramManager; - typedef GpuProgramManager HighLevelGpuProgramManager; //!< @deprecated - class GpuProgramUsage; - class HardwareBuffer; - class HardwareIndexBuffer; - class HardwareOcclusionQuery; - class HardwareVertexBuffer; - class HardwarePixelBuffer; - class HighLevelGpuProgram; - class IndexData; - class InstanceBatch; - class InstanceBatchHW; - class InstanceBatchHW_VTF; - class InstanceBatchShader; - class InstanceBatchVTF; - class InstanceManager; - class InstancedEntity; - class IntersectionSceneQuery; - class IntersectionSceneQueryListener; - class Image; - class KeyFrame; - class Light; - class Log; - class LogManager; - class LodStrategy; - class LodStrategyManager; - class ManualResourceLoader; - class ManualObject; - class Material; - class MaterialManager; - class Math; - class Matrix3; - class Matrix4; - class MemoryDataStream; - class MemoryManager; - class Mesh; - class MeshSerializer; - class MeshManager; - class MovableObject; - class MovablePlane; - class Node; - class NodeAnimationTrack; - class NodeKeyFrame; - class NumericAnimationTrack; - class NumericKeyFrame; - class Particle; - class ParticleAffector; - class ParticleAffectorFactory; - class ParticleEmitter; - class ParticleEmitterFactory; - class ParticleSystem; - class ParticleSystemManager; - class ParticleSystemRenderer; - template class FactoryObj; - typedef FactoryObj ParticleSystemRendererFactory; - class Pass; - class PatchMesh; - class PixelBox; - class Plane; - class PlaneBoundedVolume; - class Plugin; - class Pose; - class Profile; - class Profiler; - class Quaternion; - class Radian; - class Ray; - class RaySceneQuery; - class RaySceneQueryListener; - class Renderable; - class RenderPriorityGroup; - class RenderQueue; - class RenderQueueGroup; - class RenderQueueListener; - class RenderObjectListener; - class RenderSystem; - class RenderSystemCapabilities; - class RenderSystemCapabilitiesManager; - class RenderSystemCapabilitiesSerializer; - class RenderTarget; - class RenderTargetListener; - class RenderTexture; - class RenderToVertexBuffer; - class MultiRenderTarget; - class RenderWindow; - class RenderOperation; - class Resource; - class ResourceBackgroundQueue; - class ResourceGroupManager; - class ResourceManager; - class RibbonTrail; - class Root; - class SceneManager; - class SceneNode; - class SceneQuery; - class SceneQueryListener; - class ScriptCompiler; - class ScriptCompilerManager; - class ScriptLoader; - class Serializer; - class ShadowCameraSetup; - class ShadowCaster; - class ShadowRenderable; - class SimpleRenderable; - class SimpleSpline; - class Skeleton; - class SkeletonInstance; - class SkeletonManager; - class Sphere; - class SphereSceneQuery; - class StaticGeometry; - class StreamSerialiser; - class StringConverter; - class StringInterface; - class SubEntity; - class SubMesh; - class TagPoint; - class Technique; - class ExternalTextureSource; - class TextureUnitState; - class Texture; - class TextureManager; - class TransformKeyFrame; - class Timer; - class UserObjectBindings; - template class _OgreMaybeExport Vector; - typedef Vector<2, Real> Vector2; - typedef Vector<2, float> Vector2f; - typedef Vector<2, int> Vector2i; - typedef Vector<3, Real> Vector3; - typedef Vector<3, float> Vector3f; - typedef Vector<3, int> Vector3i; - typedef Vector<4, Real> Vector4; - typedef Vector<4, float> Vector4f; - class Viewport; - class VertexAnimationTrack; - class VertexBufferBinding; - class VertexData; - class VertexDeclaration; - class VertexMorphKeyFrame; - class WireBoundingBox; - class WorkQueue; - class Compositor; - class CompositorManager; - class CompositorChain; - class CompositorInstance; - class CompositorLogic; - class CompositionTechnique; - class CompositionPass; - class CompositionTargetPass; - class CustomCompositionPass; - - using std::shared_ptr; - using std::unique_ptr; - template class SharedPtr; - - typedef SharedPtr AnimableValuePtr; - typedef SharedPtr CompositorPtr; - typedef SharedPtr DataStreamPtr; - typedef SharedPtr GpuProgramPtr; - typedef SharedPtr GpuNamedConstantsPtr; - typedef SharedPtr GpuLogicalBufferStructPtr; - typedef SharedPtr GpuSharedParametersPtr; - typedef SharedPtr GpuProgramParametersPtr; - typedef SharedPtr HardwareBufferPtr; - typedef SharedPtr HardwareIndexBufferPtr; - typedef SharedPtr HardwarePixelBufferPtr; - typedef SharedPtr HardwareVertexBufferPtr; - typedef SharedPtr MaterialPtr; - typedef SharedPtr MemoryDataStreamPtr; - typedef SharedPtr MeshPtr; - typedef SharedPtr PatchMeshPtr; - typedef SharedPtr RenderToVertexBufferPtr; - typedef SharedPtr ResourcePtr; - typedef SharedPtr ShadowCameraSetupPtr; - typedef SharedPtr SkeletonPtr; - typedef SharedPtr TexturePtr; - - typedef RenderToVertexBufferPtr RenderToVertexBufferSharedPtr; //!< @deprecated - typedef HardwareIndexBufferPtr HardwareIndexBufferSharedPtr; //!< @deprecated - typedef HardwarePixelBufferPtr HardwarePixelBufferSharedPtr; //!< @deprecated - typedef HardwareVertexBufferPtr HardwareVertexBufferSharedPtr; //!< @deprecated - typedef GpuProgramPtr HighLevelGpuProgramPtr; //!< @deprecated - typedef HardwareBufferPtr HardwareUniformBufferSharedPtr; //!< @deprecated - typedef HardwareBufferPtr HardwareCounterBufferSharedPtr; //!< @deprecated - typedef GpuProgramParametersPtr GpuProgramParametersSharedPtr; //!< @deprecated -} - -/* Include all the standard header *after* all the configuration -settings have been made. -*/ -#include "OgreStdHeaders.h" -#include "OgreMemoryAllocatorConfig.h" - - -namespace Ogre -{ - typedef std::string String; - typedef std::stringstream StringStream; - - template - using aligned_vector = std::vector>; - - _OgreExport extern const String MOT_ENTITY; - _OgreExport extern const String MOT_LIGHT; - _OgreExport extern const String MOT_MANUAL_OBJECT; - _OgreExport extern const String MOT_PARTICLE_SYSTEM; - _OgreExport extern const String MOT_BILLBOARD_SET; - _OgreExport extern const String MOT_BILLBOARD_CHAIN; - _OgreExport extern const String MOT_RIBBON_TRAIL; - _OgreExport extern const String MOT_RECTANGLE2D; - _OgreExport extern const String MOT_STATIC_GEOMETRY; - _OgreExport extern const String MOT_CAMERA; - /// @deprecated use #MOT_FRUSTUM - _OgreExport extern const String MOT_FRUSTRUM; - _OgreExport extern const String MOT_FRUSTUM; - _OgreExport extern const String MOT_MOVABLE_PLANE; - _OgreExport extern const String MOT_INSTANCE_BATCH; - _OgreExport extern const String MOT_INSTANCED_ENTITY; - _OgreExport extern const String MOT_SIMPLE_RENDERABLE; -} - -#endif // __OgrePrerequisites_H__ - - diff --git a/OgreMain/include/OgreProfiler.h b/OgreMain/include/OgreProfiler.h deleted file mode 100644 index 831dd205629..00000000000 --- a/OgreMain/include/OgreProfiler.h +++ /dev/null @@ -1,464 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -/* - - Although the code is original, many of the ideas for the profiler were borrowed from -"Real-Time In-Game Profiling" by Steve Rabin which can be found in Game Programming -Gems 1. - - This code can easily be adapted to your own non-Ogre project. The only code that is -Ogre-dependent is in the visualization/logging routines and the use of the Timer class. - - Enjoy! - -*/ - -#ifndef __Profiler_H__ -#define __Profiler_H__ - -#include "OgrePrerequisites.h" -#include "OgreSingleton.h" -#include "OgreHeaderPrefix.h" - -#if OGRE_PROFILING == 1 -# define OgreProfile( a ) Ogre::Profile _OgreProfileInstance( (a) ) -# define OgreProfileBegin( a ) Ogre::Profiler::getSingleton().beginProfile( (a) ) -# define OgreProfileEnd( a ) Ogre::Profiler::getSingleton().endProfile( (a) ) -# define OgreProfileGroup( a, g ) Ogre::Profile OGRE_TOKEN_PASTE(_OgreProfileInstance, __LINE__) ( (a), (g) ) -# define OgreProfileBeginGroup( a, g ) Ogre::Profiler::getSingleton().beginProfile( (a), (g) ) -# define OgreProfileEndGroup( a, g ) Ogre::Profiler::getSingleton().endProfile( (a), (g) ) -# define OgreProfileBeginGPUEvent( g ) Ogre::Root::getSingleton().getRenderSystem()->beginProfileEvent(g) -# define OgreProfileEndGPUEvent( g ) Ogre::Root::getSingleton().getRenderSystem()->endProfileEvent() -# define OgreProfileMarkGPUEvent( e ) Ogre::Root::getSingleton().getRenderSystem()->markProfileEvent(e) -#else -# define OgreProfile( a ) -# define OgreProfileBegin( a ) -# define OgreProfileEnd( a ) -# define OgreProfileGroup( a, g ) -# define OgreProfileBeginGroup( a, g ) -# define OgreProfileEndGroup( a, g ) -# define OgreProfileBeginGPUEvent( e ) -# define OgreProfileEndGPUEvent( e ) -# define OgreProfileMarkGPUEvent( e ) -#endif - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - /** List of reserved profiling masks - */ - enum ProfileGroupMask - { - /// User default profile - OGREPROF_USER_DEFAULT = 0x00000001, - /// All in-built Ogre profiling will match this mask - OGREPROF_ALL = 0xFF000000, - /// General processing - OGREPROF_GENERAL = 0x80000000, - /// Culling - OGREPROF_CULLING = 0x40000000, - /// Rendering - OGREPROF_RENDERING = 0x20000000 - }; - - /** Represents the total timing information of a profile - since profiles can be called more than once each frame - */ - struct ProfileFrame - { - - /// The total time this profile has taken this frame - ulong frameTime; - - /// The number of times this profile was called this frame - uint calls; - - /// The hierarchical level of this profile, 0 being the main loop - uint hierarchicalLvl; - - }; - - /// Represents a history of each profile during the duration of the app - struct ProfileHistory - { - /// The current percentage of frame time this profile has taken - Real currentTimePercent; - /// The current frame time this profile has taken in milliseconds - Real currentTimeMillisecs; - - /// The maximum percentage of frame time this profile has taken - Real maxTimePercent; - /// The maximum frame time this profile has taken in milliseconds - Real maxTimeMillisecs; - - /// The minimum percentage of frame time this profile has taken - Real minTimePercent; - /// The minimum frame time this profile has taken in milliseconds - Real minTimeMillisecs; - - /// The number of times this profile has been called each frame - uint numCallsThisFrame; - - /// The total percentage of frame time this profile has taken - Real totalTimePercent; - /// The total frame time this profile has taken in milliseconds - Real totalTimeMillisecs; - - /// The total number of times this profile was called - /// (used to calculate average) - ulong totalCalls; - - /// The hierarchical level of this profile, 0 being the root profile - uint hierarchicalLvl; - - }; - - /// Represents an individual profile call - class _OgreExport ProfileInstance : public ProfilerAlloc - { - friend class Profiler; - public: - ProfileInstance(void); - virtual ~ProfileInstance(void); - - typedef std::map ProfileChildren; - - void logResults(); - void reset(); - - inline bool watchForMax(void) { return history.currentTimePercent == history.maxTimePercent; } - inline bool watchForMin(void) { return history.currentTimePercent == history.minTimePercent; } - inline bool watchForLimit(Real limit, bool greaterThan = true) - { - if (greaterThan) - return history.currentTimePercent > limit; - else - return history.currentTimePercent < limit; - } - - bool watchForMax(const String& profileName); - bool watchForMin(const String& profileName); - bool watchForLimit(const String& profileName, Real limit, bool greaterThan = true); - - /// The name of the profile - String name; - - /// The name of the parent, null if root - ProfileInstance* parent; - - ProfileChildren children; - - ProfileFrame frame; - ulong frameNumber; - - ProfileHistory history; - - /// The time this profile was started - ulong currTime; - - /// Represents the total time of all child profiles to subtract - /// from this profile - ulong accum; - - /// The hierarchical level of this profile, 0 being the root profile - uint hierarchicalLvl; - }; - - /** ProfileSessionListener should be used to visualize profile results. - Concrete impl. could be done using Overlay's but its not limited to - them you can also create a custom listener which sends the profile - informtaion over a network. - */ - class _OgreExport ProfileSessionListener - { - public: - virtual ~ProfileSessionListener() {} - - /// Create the internal resources - virtual void initializeSession() = 0; - - /// All internal resources should be deleted here - virtual void finializeSession() = 0; - - /** If the profiler disables this listener then it - should hide its panels (if any exists) or stop - sending data over the network - */ - virtual void changeEnableState(bool enabled) {}; - - /// Here we get the real profiling information which we can use - virtual void displayResults(const ProfileInstance& instance, ulong maxTotalFrameTime) {}; - }; - - /** The profiler allows you to measure the performance of your code - - Do not create profiles directly from this unless you want a profile to last - outside of its scope (i.e. the main game loop). For most cases, use the macro - OgreProfile(name) and braces to limit the scope. You must enable the Profile - before you can used it with setEnabled(true). If you want to disable profiling - in Ogre, simply set the macro OGRE_PROFILING to 0. - @author Amit Mathew (amitmathew (at) yahoo (dot) com) - @todo resolve artificial cap on number of profiles displayed - @todo fix display ordering of profiles not called every frame - */ - class _OgreExport Profiler : - public Singleton, - public ProfilerAlloc - { - public: - Profiler(); - ~Profiler(); - - /** Sets the timer for the profiler */ - void setTimer(Timer* t); - - /** Retrieves the timer for the profiler */ - Timer* getTimer(); - - /** Begins a profile - - Use the macro OgreProfileBegin(name) instead of calling this directly - so that profiling can be ignored in the release version of your app. - - You only use the macro (or this) if you want a profile to last outside - of its scope (i.e. the main game loop). If you use this function, make sure you - use a corresponding OgreProfileEnd(name). Usually you would use the macro - OgreProfile(name). This function will be ignored for a profile that has been - disabled or if the profiler is disabled. - @param profileName Must be unique and must not be an empty string - @param groupID A profile group identifier, which can allow you to mask profiles - */ - void beginProfile(const String& profileName, uint32 groupID = (uint32)OGREPROF_USER_DEFAULT); - - /** Ends a profile - - Use the macro OgreProfileEnd(name) instead of calling this directly so that - profiling can be ignored in the release version of your app. - - This function is usually not called directly unless you want a profile to - last outside of its scope. In most cases, using the macro OgreProfile(name) - which will call this function automatically when it goes out of scope. Make - sure the name of this profile matches its corresponding beginProfile name. - This function will be ignored for a profile that has been disabled or if the - profiler is disabled. - @param profileName Must be unique and must not be an empty string - @param groupID A profile group identifier, which can allow you to mask profiles - */ - void endProfile(const String& profileName, uint32 groupID = (uint32)OGREPROF_USER_DEFAULT); - - /** Sets whether this profiler is enabled. Only takes effect after the - the frame has ended. - @remarks When this is called the first time with the parameter true, - it initializes the GUI for the Profiler - */ - void setEnabled(bool enabled); - - /** Gets whether this profiler is enabled */ - bool getEnabled() const; - - /** Enables a previously disabled profile - @remarks Can be safely called in the middle of the profile. - */ - void enableProfile(const String& profileName); - - /** Disables a profile - @remarks Can be safely called in the middle of the profile. - */ - void disableProfile(const String& profileName); - - /** Set the mask which all profiles must pass to be enabled. - */ - void setProfileGroupMask(uint32 mask) { mProfileMask = mask; } - /** Get the mask which all profiles must pass to be enabled. - */ - uint32 getProfileGroupMask() const { return mProfileMask; } - - /** Returns true if the specified profile reaches a new frame time maximum - @remarks If this is called during a frame, it will be reading the results - from the previous frame. Therefore, it is best to use this after the frame - has ended. - */ - bool watchForMax(const String& profileName); - - /** Returns true if the specified profile reaches a new frame time minimum - @remarks If this is called during a frame, it will be reading the results - from the previous frame. Therefore, it is best to use this after the frame - has ended. - */ - bool watchForMin(const String& profileName); - - /** Returns true if the specified profile goes over or under the given limit - frame time - @remarks If this is called during a frame, it will be reading the results - from the previous frame. Therefore, it is best to use this after the frame - has ended. - @param profileName Must be unique and must not be an empty string - @param limit A number between 0 and 1 representing the percentage of frame time - @param greaterThan If true, this will return whether the limit is exceeded. Otherwise, - it will return if the frame time has gone under this limit. - */ - bool watchForLimit(const String& profileName, Real limit, bool greaterThan = true); - - /** Outputs current profile statistics to the log */ - void logResults(); - - /** Clears the profiler statistics */ - void reset(); - - /** Sets the Profiler so the display of results are updated every n frames*/ - void setUpdateDisplayFrequency(uint freq); - - /** Gets the frequency that the Profiler display is updated */ - uint getUpdateDisplayFrequency() const; - - /** - - Register a ProfileSessionListener from the Profiler - @param listener - A valid listener derived class - */ - void addListener(ProfileSessionListener* listener); - - /** - - Unregister a ProfileSessionListener from the Profiler - @param listener - A valid listener derived class - */ - void removeListener(ProfileSessionListener* listener); - - /// @copydoc Singleton::getSingleton() - static Profiler& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static Profiler* getSingletonPtr(void); - - private: - friend class ProfileInstance; - - typedef std::vector TProfileSessionListener; - TProfileSessionListener mListeners; - - /** Initializes the profiler's GUI elements */ - void initialize(); - - void displayResults(); - - /** Processes frame stats for all of the mRoot's children */ - void processFrameStats(void); - /** Processes specific ProfileInstance and it's children recursively.*/ - void processFrameStats(ProfileInstance* instance, Real& maxFrameTime); - - /** Handles a change of the profiler's enabled state*/ - void changeEnableState(); - - // lol. Uses typedef; put's original container type in name. - typedef std::set DisabledProfileMap; - typedef ProfileInstance::ProfileChildren ProfileChildren; - - ProfileInstance* mCurrent; - ProfileInstance* mLast; - ProfileInstance mRoot; - - /// Holds the names of disabled profiles - DisabledProfileMap mDisabledProfiles; - - /// Whether the GUI elements have been initialized - bool mInitialized; - - /// The number of frames that must elapse before the current - /// frame display is updated - uint mUpdateDisplayFrequency; - - /// The number of elapsed frame, used with mUpdateDisplayFrequency - uint mCurrentFrame; - - /// The timer used for profiling - Timer* mTimer; - - /// The total time each frame takes - ulong mTotalFrameTime; - - /// Whether this profiler is enabled - bool mEnabled; - - /// Keeps track of the new enabled/disabled state that the user has requested - /// which will be applied after the frame ends - bool mNewEnableState; - - /// Mask to decide whether a type of profile is enabled or not - uint32 mProfileMask; - - /// The max frame time recorded - ulong mMaxTotalFrameTime; - - /// Rolling average of millisecs - Real mAverageFrameTime; - bool mResetExtents; - - - }; // end class - - /** An individual profile that will be processed by the Profiler - - Use the macro OgreProfile(name) instead of instantiating this profile directly - - We use this Profile to allow scoping rules to signify the beginning and end of - the profile. Use the Profiler singleton (through the macro OgreProfileBegin(name) - and OgreProfileEnd(name)) directly if you want a profile to last - outside of a scope (i.e. the main game loop). - @author Amit Mathew (amitmathew (at) yahoo (dot) com) - */ - class Profile : public ProfilerAlloc - { - - public: - Profile(const String& profileName, uint32 groupID = (uint32)OGREPROF_USER_DEFAULT) - : mName(profileName), mGroupID(groupID) - { - Profiler::getSingleton().beginProfile(profileName, groupID); - } - ~Profile() { Profiler::getSingleton().endProfile(mName, mGroupID); } - - private: - /// The name of this profile - String mName; - /// The group ID - uint32 mGroupID; - }; - /** @} */ - /** @} */ - -} // end namespace - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreQuaternion.h b/OgreMain/include/OgreQuaternion.h deleted file mode 100644 index b921798ff04..00000000000 --- a/OgreMain/include/OgreQuaternion.h +++ /dev/null @@ -1,373 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -// This file is based on material originally from: -// Geometric Tools, LLC -// Copyright (c) 1998-2010 -// Distributed under the Boost Software License, Version 1.0. -// http://www.boost.org/LICENSE_1_0.txt -// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt - - -#ifndef __Quaternion_H__ -#define __Quaternion_H__ - -#include "OgrePrerequisites.h" -#include "OgreMath.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - /** Implementation of a Quaternion, i.e. a rotation around an axis. - For more information about Quaternions and the theory behind it, we recommend reading: - http://www.ogre3d.org/tikiwiki/Quaternion+and+Rotation+Primer and - http://www.cprogramming.com/tutorial/3d/quaternions.html and - http://www.gamedev.net/page/resources/_/reference/programming/math-and-physics/quaternions/quaternion-powers-r1095 - */ - class _OgreExport Quaternion - { - public: - /// Default constructor, initializes to identity rotation (aka 0°) - inline Quaternion () - : w(1), x(0), y(0), z(0) - { - } - /// Copy constructor - inline Quaternion(const Ogre::Quaternion& rhs) - : w(rhs.w), x(rhs.x), y(rhs.y), z(rhs.z) - {} - /// Construct from an explicit list of values - inline Quaternion ( - Real fW, - Real fX, Real fY, Real fZ) - : w(fW), x(fX), y(fY), z(fZ) - { - } - /// Construct a quaternion from a rotation matrix - inline Quaternion(const Matrix3& rot) - { - this->FromRotationMatrix(rot); - } - /// Construct a quaternion from an angle/axis - inline Quaternion(const Radian& rfAngle, const Vector3& rkAxis) - { - this->FromAngleAxis(rfAngle, rkAxis); - } - /// Construct a quaternion from 3 orthonormal local axes - inline Quaternion(const Vector3& xaxis, const Vector3& yaxis, const Vector3& zaxis) - { - this->FromAxes(xaxis, yaxis, zaxis); - } - /// Construct a quaternion from 3 orthonormal local axes - inline Quaternion(const Vector3* akAxis) - { - this->FromAxes(akAxis); - } - /// Construct a quaternion from 4 manual w/x/y/z values - inline Quaternion(Real* valptr) - { - memcpy(&w, valptr, sizeof(Real)*4); - } - - /** Exchange the contents of this quaternion with another. - */ - inline void swap(Quaternion& other) - { - std::swap(w, other.w); - std::swap(x, other.x); - std::swap(y, other.y); - std::swap(z, other.z); - } - - /// Array accessor operator - inline Real operator [] ( const size_t i ) const - { - assert( i < 4 ); - - return *(&w+i); - } - - /// Array accessor operator - inline Real& operator [] ( const size_t i ) - { - assert( i < 4 ); - - return *(&w+i); - } - - /// Pointer accessor for direct copying - inline Real* ptr() - { - return &w; - } - - /// Pointer accessor for direct copying - inline const Real* ptr() const - { - return &w; - } - - void FromRotationMatrix (const Matrix3& kRot); - void ToRotationMatrix (Matrix3& kRot) const; - /** Setups the quaternion using the supplied vector, and "roll" around - that vector by the specified radians. - */ - void FromAngleAxis (const Radian& rfAngle, const Vector3& rkAxis); - void ToAngleAxis (Radian& rfAngle, Vector3& rkAxis) const; - inline void ToAngleAxis (Degree& dAngle, Vector3& rkAxis) const { - Radian rAngle; - ToAngleAxis ( rAngle, rkAxis ); - dAngle = rAngle; - } - /** Constructs the quaternion using 3 axes, the axes are assumed to be orthonormal - @see FromAxes - */ - void FromAxes (const Vector3* akAxis); - void FromAxes (const Vector3& xAxis, const Vector3& yAxis, const Vector3& zAxis); - /** Gets the 3 orthonormal axes defining the quaternion. @see FromAxes */ - void ToAxes (Vector3* akAxis) const; - void ToAxes (Vector3& xAxis, Vector3& yAxis, Vector3& zAxis) const; - - /** Returns the X orthonormal axis defining the quaternion. Same as doing - xAxis = Vector3::UNIT_X * this. Also called the local X-axis - */ - Vector3 xAxis(void) const; - - /** Returns the Y orthonormal axis defining the quaternion. Same as doing - yAxis = Vector3::UNIT_Y * this. Also called the local Y-axis - */ - Vector3 yAxis(void) const; - - /** Returns the Z orthonormal axis defining the quaternion. Same as doing - zAxis = Vector3::UNIT_Z * this. Also called the local Z-axis - */ - Vector3 zAxis(void) const; - - inline Quaternion& operator= (const Quaternion& rkQ) - { - w = rkQ.w; - x = rkQ.x; - y = rkQ.y; - z = rkQ.z; - return *this; - } - Quaternion operator+ (const Quaternion& rkQ) const; - Quaternion operator- (const Quaternion& rkQ) const; - Quaternion operator*(const Quaternion& rkQ) const; - Quaternion operator*(Real s) const - { - return Quaternion(s * w, s * x, s * y, s * z); - } - friend Quaternion operator*(Real s, const Quaternion& q) - { - return q * s; - } - Quaternion operator-() const { return Quaternion(-w, -x, -y, -z); } - inline bool operator== (const Quaternion& rhs) const - { - return (rhs.x == x) && (rhs.y == y) && - (rhs.z == z) && (rhs.w == w); - } - inline bool operator!= (const Quaternion& rhs) const - { - return !operator==(rhs); - } - // functions of a quaternion - /// Returns the dot product of the quaternion - Real Dot(const Quaternion& rkQ) const - { - return w * rkQ.w + x * rkQ.x + y * rkQ.y + z * rkQ.z; - } - /// Returns the normal length of this quaternion. - Real Norm() const { return Math::Sqrt(w * w + x * x + y * y + z * z); } - /// Normalises this quaternion, and returns the previous length - Real normalise(void) - { - Real len = Norm(); - *this = 1.0f / len * *this; - return len; - } - Quaternion Inverse () const; /// Apply to non-zero quaternion - Quaternion UnitInverse () const; /// Apply to unit-length quaternion - Quaternion Exp () const; - Quaternion Log () const; - - /// Rotation of a vector by a quaternion - Vector3 operator* (const Vector3& rkVector) const; - - /** Calculate the local roll element of this quaternion. - @param reprojectAxis By default the method returns the 'intuitive' result - that is, if you projected the local X of the quaternion onto the XY plane, - the angle between it and global X is returned. The co-domain of the returned - value is from -180 to 180 degrees. If set to false though, the result is - the rotation around Z axis that could be used to implement the quaternion - using some non-intuitive order of rotations. This behavior is preserved for - backward compatibility, to decompose quaternion into yaw, pitch and roll use - q.ToRotationMatrix().ToEulerAnglesYXZ(yaw, pitch, roll) instead. - */ - Radian getRoll(bool reprojectAxis = true) const; - /** Calculate the local pitch element of this quaternion - @param reprojectAxis By default the method returns the 'intuitive' result - that is, if you projected the local Y of the quaternion onto the YZ plane, - the angle between it and global Y is returned. The co-domain of the returned - value is from -180 to 180 degrees. If set to false though, the result is - the rotation around X axis that could be used to implement the quaternion - using some non-intuitive order of rotations. This behavior is preserved for - backward compatibility, to decompose quaternion into yaw, pitch and roll use - q.ToRotationMatrix().ToEulerAnglesYXZ(yaw, pitch, roll) instead. - */ - Radian getPitch(bool reprojectAxis = true) const; - /** Calculate the local yaw element of this quaternion - @param reprojectAxis By default the method returns the 'intuitive' result - that is, if you projected the local Z of the quaternion onto the ZX plane, - the angle between it and global Z is returned. The co-domain of the returned - value is from -180 to 180 degrees. If set to false though, the result is - the rotation around Y axis that could be used to implement the quaternion - using some non-intuitive order of rotations. This behavior is preserved for - backward compatibility, to decompose quaternion into yaw, pitch and roll use - q.ToRotationMatrix().ToEulerAnglesYXZ(yaw, pitch, roll) instead. - */ - Radian getYaw(bool reprojectAxis = true) const; - - /** Equality with tolerance (tolerance is max angle difference) - @remark Both equals() and orientationEquals() measure the exact same thing. - One measures the difference by angle, the other by a different, non-linear metric. - */ - bool equals(const Quaternion& rhs, const Radian& tolerance) const - { - Real d = Dot(rhs); - Radian angle = Math::ACos(2.0f * d*d - 1.0f); - - return Math::Abs(angle.valueRadians()) <= tolerance.valueRadians(); - } - - /** Compare two quaternions which are assumed to be used as orientations. - @remark Both equals() and orientationEquals() measure the exact same thing. - One measures the difference by angle, the other by a different, non-linear metric. - @return true if the two orientations are the same or very close, relative to the given tolerance. - Slerp ( 0.75f, A, B ) != Slerp ( 0.25f, B, A ); - therefore be careful if your code relies in the order of the operands. - This is specially important in IK animation. - */ - inline bool orientationEquals( const Quaternion& other, Real tolerance = 1e-3f ) const - { - Real d = this->Dot(other); - return 1 - d*d < tolerance; - } - - /** Performs Spherical linear interpolation between two quaternions, and returns the result. - Slerp ( 0.0f, A, B ) = A - Slerp ( 1.0f, A, B ) = B - @return Interpolated quaternion - - Slerp has the proprieties of performing the interpolation at constant - velocity, and being torque-minimal (unless shortestPath=false). - However, it's NOT commutative, which means - Slerp ( 0.75f, A, B ) != Slerp ( 0.25f, B, A ); - therefore be careful if your code relies in the order of the operands. - This is specially important in IK animation. - */ - static Quaternion Slerp (Real fT, const Quaternion& rkP, - const Quaternion& rkQ, bool shortestPath = false); - - /** @see Slerp. It adds extra "spins" (i.e. rotates several times) specified - by parameter 'iExtraSpins' while interpolating before arriving to the - final values - */ - static Quaternion SlerpExtraSpins (Real fT, - const Quaternion& rkP, const Quaternion& rkQ, - int iExtraSpins); - - /// Setup for spherical quadratic interpolation - static void Intermediate (const Quaternion& rkQ0, - const Quaternion& rkQ1, const Quaternion& rkQ2, - Quaternion& rka, Quaternion& rkB); - - /// Spherical quadratic interpolation - static Quaternion Squad (Real fT, const Quaternion& rkP, - const Quaternion& rkA, const Quaternion& rkB, - const Quaternion& rkQ, bool shortestPath = false); - - /** Performs Normalised linear interpolation between two quaternions, and returns the result. - nlerp ( 0.0f, A, B ) = A - nlerp ( 1.0f, A, B ) = B - - Nlerp is faster than Slerp. - Nlerp has the proprieties of being commutative (@see Slerp; - commutativity is desired in certain places, like IK animation), and - being torque-minimal (unless shortestPath=false). However, it's performing - the interpolation at non-constant velocity; sometimes this is desired, - sometimes it is not. Having a non-constant velocity can produce a more - natural rotation feeling without the need of tweaking the weights; however - if your scene relies on the timing of the rotation or assumes it will point - at a specific angle at a specific weight value, Slerp is a better choice. - */ - static Quaternion nlerp(Real fT, const Quaternion& rkP, - const Quaternion& rkQ, bool shortestPath = false); - - /// Cutoff for sine near zero - static const Real msEpsilon; - - // special values - static const Quaternion ZERO; - static const Quaternion IDENTITY; - - Real w, x, y, z; - -#ifndef OGRE_FAST_MATH - /// Check whether this quaternion contains valid values - inline bool isNaN() const - { - return Math::isNaN(x) || Math::isNaN(y) || Math::isNaN(z) || Math::isNaN(w); - } -#endif - - /** Function for writing to a stream. Outputs "Quaternion(w, x, y, z)" with w,x,y,z - being the member values of the quaternion. - */ - inline friend std::ostream& operator << - ( std::ostream& o, const Quaternion& q ) - { - o << "Quaternion(" << q.w << ", " << q.x << ", " << q.y << ", " << q.z << ")"; - return o; - } - - }; - /** @} */ - /** @} */ - -} - - - - -#endif diff --git a/OgreMain/include/OgreRay.h b/OgreMain/include/OgreRay.h deleted file mode 100644 index ccc9e09d5a3..00000000000 --- a/OgreMain/include/OgreRay.h +++ /dev/null @@ -1,155 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Ray_H_ -#define __Ray_H_ - -// Precompiler options -#include "OgrePrerequisites.h" - -#include "OgrePlaneBoundedVolume.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - /** Representation of a ray in space, i.e. a line with an origin and direction. */ - class _OgreExport Ray - { - private: - Vector3 mOrigin; - Vector3 mDirection; - public: - Ray():mOrigin(Vector3::ZERO), mDirection(Vector3::UNIT_Z) {} - Ray(const Vector3& origin, const Vector3& direction) - :mOrigin(origin), mDirection(direction) {} - - /** Sets the origin of the ray. */ - void setOrigin(const Vector3& origin) {mOrigin = origin;} - /** Gets the origin of the ray. */ - const Vector3& getOrigin(void) const {return mOrigin;} - - /** Sets the direction of the ray. */ - void setDirection(const Vector3& dir) {mDirection = dir;} - /** Gets the direction of the ray. */ - const Vector3& getDirection(void) const {return mDirection;} - - /** Gets the position of a point t units along the ray. */ - Vector3 getPoint(Real t) const { - return Vector3(mOrigin + (mDirection * t)); - } - - /** Gets the position of a point t units along the ray. */ - Vector3 operator*(Real t) const { - return getPoint(t); - } - - /** Tests whether this ray intersects the given plane. */ - RayTestResult intersects(const Plane& p) const - { - Real denom = p.normal.dotProduct(mDirection); - if (Math::Abs(denom) < std::numeric_limits::epsilon()) - { - // Parallel - return RayTestResult(false, (Real)0); - } - else - { - Real nom = p.normal.dotProduct(mOrigin) + p.d; - Real t = -(nom / denom); - return RayTestResult(t >= 0, (Real)t); - } - } - /** Tests whether this ray intersects the given plane bounded volume. */ - RayTestResult intersects(const PlaneBoundedVolume& p) const - { - return Math::intersects(*this, p.planes, p.outside == Plane::POSITIVE_SIDE); - } - /** Tests whether this ray intersects the given sphere. */ - RayTestResult intersects(const Sphere& s, bool discardInside = true) const - { - // Adjust ray origin relative to sphere center - Vector3 rayorig = mOrigin - s.getCenter(); - Real radius = s.getRadius(); - - // Check origin inside first - if (rayorig.squaredLength() <= radius*radius && discardInside) - { - return RayTestResult(true, (Real)0); - } - - // Mmm, quadratics - // Build coeffs which can be used with std quadratic solver - // ie t = (-b +/- sqrt(b*b + 4ac)) / 2a - Real a = mDirection.dotProduct(mDirection); - Real b = 2 * rayorig.dotProduct(mDirection); - Real c = rayorig.dotProduct(rayorig) - radius*radius; - - // Calc determinant - Real d = (b*b) - (4 * a * c); - if (d < 0) - { - // No intersection - return RayTestResult(false, (Real)0); - } - else - { - // BTW, if d=0 there is one intersection, if d > 0 there are 2 - // But we only want the closest one, so that's ok, just use the - // '-' version of the solver - Real t = ( -b - Math::Sqrt(d) ) / (2 * a); - if (t < 0) - t = ( -b + Math::Sqrt(d) ) / (2 * a); - return RayTestResult(true, t); - } - } - /** Tests whether this ray intersects the given box. */ - RayTestResult intersects(const AxisAlignedBox& box) const - { - return Math::intersects(*this, box); - } - - }; - - inline RayTestResult Math::intersects(const Ray& ray, const Plane& plane) - { - return ray.intersects(plane); - } - - inline RayTestResult Math::intersects(const Ray& ray, const Sphere& sphere, bool discardInside) - { - return ray.intersects(sphere, discardInside); - } - /** @} */ - /** @} */ - -} -#endif diff --git a/OgreMain/include/OgreRectangle2D.h b/OgreMain/include/OgreRectangle2D.h deleted file mode 100644 index 77ff64f9019..00000000000 --- a/OgreMain/include/OgreRectangle2D.h +++ /dev/null @@ -1,103 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _Rectangle2D_H__ -#define _Rectangle2D_H__ - -#include "OgrePrerequisites.h" - -#include "OgreSimpleRenderable.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** Allows the rendering of a simple 2D rectangle - This class renders a simple 2D rectangle; this rectangle has no depth and - therefore is best used with specific render queue and depth settings, - like RENDER_QUEUE_BACKGROUND and 'depth_write off' for backdrops, and - RENDER_QUEUE_OVERLAY and 'depth_check off' for fullscreen quads. - */ - class _OgreExport Rectangle2D : public SimpleRenderable - { - protected: - /** Override this method to prevent parent transforms (rotation,translation,scale) - */ - void getWorldTransforms( Matrix4* xform ) const override; - - void _initRectangle2D(bool includeTextureCoords, HardwareBuffer::Usage vBufUsage); - - public: - - Rectangle2D(bool includeTextureCoordinates = false, HardwareBuffer::Usage vBufUsage = HBU_GPU_ONLY); - Rectangle2D(const String& name, bool includeTextureCoordinates = false, HardwareBuffer::Usage vBufUsage = HBU_GPU_ONLY); - ~Rectangle2D(); - - /** Sets the corners of the rectangle, in relative coordinates. - @param - left Left position in screen relative coordinates, -1 = left edge, 1.0 = right edge - @param top Top position in screen relative coordinates, 1 = top edge, -1 = bottom edge - @param right Right position in screen relative coordinates - @param bottom Bottom position in screen relative coordinates - @param updateAABB Tells if you want to recalculate the AABB according to - the new corners. If false, the axis aligned bounding box will remain identical. - */ - void setCorners(float left, float top, float right, float bottom, bool updateAABB = false); - - /** Sets the normals of the rectangle - */ - void setNormals(const Vector3& topLeft, const Vector3& bottomLeft, const Vector3& topRight, - const Vector3& bottomRight); - - /** Sets the UVs of the rectangle - - Doesn't do anything if the rectangle wasn't built with texture coordinates - */ - void setUVs(const Vector2& topLeft, const Vector2& bottomLeft, const Vector2& topRight, - const Vector2& bottomRight); - - void setDefaultUVs(); - - Real getSquaredViewDepth(const Camera* cam) const override - { (void)cam; return 0; } - - Real getBoundingRadius(void) const override { return 0; } - - const String& getMovableType() const override; - }; - /** @} */ - /** @} */ - -}// namespace - -#endif - - diff --git a/OgreMain/include/OgreRenderObjectListener.h b/OgreMain/include/OgreRenderObjectListener.h deleted file mode 100644 index 36f7334095a..00000000000 --- a/OgreMain/include/OgreRenderObjectListener.h +++ /dev/null @@ -1,68 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __RenderObjectListener_H__ -#define __RenderObjectListener_H__ - -#include "OgrePrerequisites.h" -#include "OgreRenderable.h" -#include "OgrePass.h" - -namespace Ogre { - - class Pass; - class Renderable; - - /** Abstract interface which classes must implement if they wish to receive - events from the scene manager when single object is about to be rendered. - */ - class _OgreExport RenderObjectListener - { - public: - virtual ~RenderObjectListener() {} - /** Event raised when render single object started. - - This method is called by the SceneManager. - @param rend - The renderable that is going to be rendered. - @param pass - The pass which was set. - @param source - The auto parameter source used within this render call. - @param pLightList - The light list in use. - @param suppressRenderStateChanges - True if render state changes should be suppressed. - */ - virtual void notifyRenderSingleObject(Renderable* rend, const Pass* pass, const AutoParamDataSource* source, - const LightList* pLightList, bool suppressRenderStateChanges) = 0; - }; - -} // namespace Ogre - -#endif // __RenderObjectListener_H__ - diff --git a/OgreMain/include/OgreRenderOperation.h b/OgreMain/include/OgreRenderOperation.h deleted file mode 100644 index c33fa8fb9cf..00000000000 --- a/OgreMain/include/OgreRenderOperation.h +++ /dev/null @@ -1,145 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#ifndef _RenderOperation_H__ -#define _RenderOperation_H__ - -#include "OgrePrerequisites.h" -#include "OgreVertexIndexData.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - /** 'New' rendering operation using vertex buffers. */ - class _OgreExport RenderOperation { - public: - /// The rendering operation type to perform - enum OperationType : uint8 { - /// A list of points, 1 vertex per point - OT_POINT_LIST = 1, - /// A list of lines, 2 vertices per line - OT_LINE_LIST = 2, - /// A strip of connected lines, 1 vertex per line plus 1 start vertex - OT_LINE_STRIP = 3, - /// A list of triangles, 3 vertices per triangle - OT_TRIANGLE_LIST = 4, - /// A strip of triangles, 3 vertices for the first triangle, and 1 per triangle after that - OT_TRIANGLE_STRIP = 5, - /// A fan of triangles, 3 vertices for the first triangle, and 1 per triangle after that - OT_TRIANGLE_FAN = 6, - /// Patch control point operations, used with tessellation stages - OT_PATCH_1_CONTROL_POINT = 7, - OT_PATCH_2_CONTROL_POINT = 8, - OT_PATCH_3_CONTROL_POINT = 9, - OT_PATCH_4_CONTROL_POINT = 10, - OT_PATCH_5_CONTROL_POINT = 11, - OT_PATCH_6_CONTROL_POINT = 12, - OT_PATCH_7_CONTROL_POINT = 13, - OT_PATCH_8_CONTROL_POINT = 14, - OT_PATCH_9_CONTROL_POINT = 15, - OT_PATCH_10_CONTROL_POINT = 16, - OT_PATCH_11_CONTROL_POINT = 17, - OT_PATCH_12_CONTROL_POINT = 18, - OT_PATCH_13_CONTROL_POINT = 19, - OT_PATCH_14_CONTROL_POINT = 20, - OT_PATCH_15_CONTROL_POINT = 21, - OT_PATCH_16_CONTROL_POINT = 22, - OT_PATCH_17_CONTROL_POINT = 23, - OT_PATCH_18_CONTROL_POINT = 24, - OT_PATCH_19_CONTROL_POINT = 25, - OT_PATCH_20_CONTROL_POINT = 26, - OT_PATCH_21_CONTROL_POINT = 27, - OT_PATCH_22_CONTROL_POINT = 28, - OT_PATCH_23_CONTROL_POINT = 29, - OT_PATCH_24_CONTROL_POINT = 30, - OT_PATCH_25_CONTROL_POINT = 31, - OT_PATCH_26_CONTROL_POINT = 32, - OT_PATCH_27_CONTROL_POINT = 33, - OT_PATCH_28_CONTROL_POINT = 34, - OT_PATCH_29_CONTROL_POINT = 35, - OT_PATCH_30_CONTROL_POINT = 36, - OT_PATCH_31_CONTROL_POINT = 37, - OT_PATCH_32_CONTROL_POINT = 38, - // max valid base OT_ = (1 << 6) - 1 - /// Mark that the index buffer contains adjacency information - OT_DETAIL_ADJACENCY_BIT = 1 << 6, - /// like OT_POINT_LIST but with adjacency information for the geometry shader - OT_LINE_LIST_ADJ = OT_LINE_LIST | OT_DETAIL_ADJACENCY_BIT, - /// like OT_LINE_STRIP but with adjacency information for the geometry shader - OT_LINE_STRIP_ADJ = OT_LINE_STRIP | OT_DETAIL_ADJACENCY_BIT, - /// like OT_TRIANGLE_LIST but with adjacency information for the geometry shader - OT_TRIANGLE_LIST_ADJ = OT_TRIANGLE_LIST | OT_DETAIL_ADJACENCY_BIT, - /// like OT_TRIANGLE_STRIP but with adjacency information for the geometry shader - OT_TRIANGLE_STRIP_ADJ = OT_TRIANGLE_STRIP | OT_DETAIL_ADJACENCY_BIT, - }; - - /// Vertex source data - VertexData *vertexData; - - /// Index data - only valid if useIndexes is true - IndexData *indexData; - /// Debug pointer back to renderable which created this - const Renderable* srcRenderable; - - /// The number of instances for the render operation - this option is supported - /// in only a part of the render systems. - uint32 numberOfInstances; - - /// The type of operation to perform - OperationType operationType; - - /** Specifies whether to use indexes to determine the vertices to use as input. If false, the vertices are - simply read in sequence to define the primitives. If true, indexes are used instead to identify vertices - anywhere in the buffer, and allowing vertices to be used more than once. - If true, then the indexBuffer, indexStart and numIndexes properties must be valid. */ - bool useIndexes; - - /** A flag to indicate that it is possible for this operation to use a global - vertex instance buffer if available.*/ - bool useGlobalInstancing; - - RenderOperation() - : vertexData(0), indexData(0), srcRenderable(0), numberOfInstances(1), - operationType(OT_TRIANGLE_LIST), useIndexes(true), - useGlobalInstancing(true) - { - } - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreRenderQueue.h b/OgreMain/include/OgreRenderQueue.h deleted file mode 100644 index 26bdde0bec9..00000000000 --- a/OgreMain/include/OgreRenderQueue.h +++ /dev/null @@ -1,311 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __RenderQueue_H__ -#define __RenderQueue_H__ - -#include "OgrePrerequisites.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - class Camera; - class MovableObject; - struct VisibleObjectsBoundsInfo; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - /** Enumeration of queue groups, by which the application may group queued renderables - so that they are rendered together with events in between - - When passed into methods these are actually passed as a uint8 to allow you - to use values in between if you want to. - */ - enum RenderQueueGroupID - { - /// Use this queue for objects which must be rendered first e.g. backgrounds - RENDER_QUEUE_BACKGROUND = 0, - /// First queue (after backgrounds), used for skyboxes if rendered first - RENDER_QUEUE_SKIES_EARLY = 5, - RENDER_QUEUE_1 = 10, - RENDER_QUEUE_2 = 20, - RENDER_QUEUE_WORLD_GEOMETRY_1 = 25, - RENDER_QUEUE_3 = 30, - RENDER_QUEUE_4 = 40, - /// The default render queue - RENDER_QUEUE_MAIN = 50, - RENDER_QUEUE_6 = 60, - RENDER_QUEUE_7 = 70, - RENDER_QUEUE_WORLD_GEOMETRY_2 = 75, - RENDER_QUEUE_8 = 80, - /// Used for skyboxes if rendered last - RENDER_QUEUE_SKIES_LATE = 90, - /// Penultimate queue(before overlays) - RENDER_QUEUE_TRANSPARENTS = 95, - /// Use this queue for objects which must be rendered last e.g. overlays - RENDER_QUEUE_OVERLAY = 100, - /// Final possible render queue, don't exceed this - RENDER_QUEUE_MAX = 105, - RENDER_QUEUE_COUNT - }; - - /// @deprecated - #define OGRE_RENDERABLE_DEFAULT_PRIORITY Ogre::Renderable::DEFAULT_PRIORITY - - /** Class to manage the scene object rendering queue. - - Objects are grouped by material to minimise rendering state changes. The map from - material to renderable object is wrapped in a class for ease of use. - @par - This class now includes the concept of 'queue groups' which allows the application - adding the renderable to specifically schedule it so that it is included in - a discrete group. Good for separating renderables into the main scene, - backgrounds and overlays, and also could be used in the future for more - complex multipass routines like stenciling. - */ - class _OgreExport RenderQueue : public RenderQueueAlloc - { - public: - - typedef std::unique_ptr RenderQueueGroupMap[RENDER_QUEUE_COUNT]; - - /** Class to listen in on items being added to the render queue. - - Use RenderQueue::setRenderableListener to get callbacks when an item - is added to the render queue. - */ - class _OgreExport RenderableListener - { - public: - RenderableListener() {} - virtual ~RenderableListener() {} - - /** Method called when a Renderable is added to the queue. - - You can use this event hook to alter the Technique used to - render a Renderable as the item is added to the queue. This is - a low-level way to override the material settings for a given - Renderable on the fly. - @param rend The Renderable being added to the queue - @param groupID The render queue group this Renderable is being added to - @param priority The priority the Renderable has been given - @param ppTech A pointer to the pointer to the Technique that is - intended to be used; you can alter this to an alternate Technique - if you so wish (the Technique doesn't have to be from the same - Material either). - @param pQueue Pointer to the render queue that this object is being - added to. You can for example call this back to duplicate the - object with a different technique - @return true to allow the Renderable to be added to the queue, - false if you want to prevent it being added - */ - virtual bool renderableQueued(Renderable* rend, uint8 groupID, - ushort priority, Technique** ppTech, RenderQueue* pQueue) = 0; - }; - private: - RenderQueueGroupMap mGroups; - /// The current default queue group - uint8 mDefaultQueueGroup; - /// The default priority - ushort mDefaultRenderablePriority; - - bool mSplitPassesByLightingType; - bool mSplitNoShadowPasses; - bool mShadowCastersCannotBeReceivers; - - RenderableListener* mRenderableListener; - public: - RenderQueue(); - virtual ~RenderQueue(); - - /** Empty the queue - should only be called by SceneManagers. - @param destroyPassMaps Set to true to destroy all pass maps so that - the queue is completely clean (useful when switching scene managers) - */ - void clear(bool destroyPassMaps = false); - - /** Get a render queue group. - - OGRE registers new queue groups as they are requested, - therefore this method will always return a valid group. - */ - RenderQueueGroup* getQueueGroup(uint8 qid); - - /** Add a renderable object to the queue. - - This methods adds a Renderable to the queue, which will be rendered later by - the SceneManager. This is the advanced version of the call which allows the renderable - to be added to any queue. - @note - Called by implementation of MovableObject::_updateRenderQueue. - @param - pRend Pointer to the Renderable to be added to the queue - @param - groupID The group the renderable is to be added to. This - can be used to schedule renderable objects in separate groups such that the SceneManager - respects the divisions between the groupings and does not reorder them outside these - boundaries. This can be handy for overlays where no matter what you want the overlay to - be rendered last. - @param - priority Controls the priority of the renderable within the queue group. If this number - is raised, the renderable will be rendered later in the group compared to it's peers. - Don't use this unless you really need to, manually ordering renderables prevents OGRE - from sorting them for best efficiency. However this could be useful for ordering 2D - elements manually for example. - */ - void addRenderable(Renderable* pRend, uint8 groupID, ushort priority); - - /** Add a renderable object to the queue. - - This methods adds a Renderable to the queue, which will be rendered later by - the SceneManager. This is the simplified version of the call which does not - require a priority to be specified. The queue priority is take from the - current default (see setDefaultRenderablePriority). - @note - Called by implementation of MovableObject::_updateRenderQueue. - @param pRend - Pointer to the Renderable to be added to the queue - @param groupId - The group the renderable is to be added to. This - can be used to schedule renderable objects in separate groups such that the SceneManager - respects the divisions between the groupings and does not reorder them outside these - boundaries. This can be handy for overlays where no matter what you want the overlay to - be rendered last. - */ - void addRenderable(Renderable* pRend, uint8 groupId); - - /** Add a renderable object to the queue. - - This methods adds a Renderable to the queue, which will be rendered later by - the SceneManager. This is the simplified version of the call which does not - require a queue or priority to be specified. The queue group is taken from the - current default (see setDefaultQueueGroup). The queue priority is take from the - current default (see setDefaultRenderablePriority). - @note - Called by implementation of MovableObject::_updateRenderQueue. - @param - pRend Pointer to the Renderable to be added to the queue - */ - void addRenderable(Renderable* pRend); - - /** Gets the current default queue group, which will be used for all renderable which do not - specify which group they wish to be on. - */ - uint8 getDefaultQueueGroup(void) const; - - /** Sets the current default renderable priority, - which will be used for all renderables which do not - specify which priority they wish to use. - */ - void setDefaultRenderablePriority(ushort priority); - - /** Gets the current default renderable priority, which will be used for all renderables which do not - specify which priority they wish to use. - */ - ushort getDefaultRenderablePriority(void) const; - - /** Sets the current default queue group, which will be used for all renderable which do not - specify which group they wish to be on. See the enum RenderQueueGroupID for what kind of - values can be used here. - */ - void setDefaultQueueGroup(uint8 grp); - - /** Internal method, returns the queue groups. */ - const RenderQueueGroupMap& _getQueueGroups() const { - return mGroups; - } - - /** Sets whether or not the queue will split passes by their lighting type, - ie ambient, per-light and decal. - */ - void setSplitPassesByLightingType(bool split); - - /** Gets whether or not the queue will split passes by their lighting type, - ie ambient, per-light and decal. - */ - bool getSplitPassesByLightingType(void) const; - - /** Sets whether or not the queue will split passes which have shadow receive - turned off (in their parent material), which is needed when certain shadow - techniques are used. - */ - void setSplitNoShadowPasses(bool split); - - /** Gets whether or not the queue will split passes which have shadow receive - turned off (in their parent material), which is needed when certain shadow - techniques are used. - */ - bool getSplitNoShadowPasses(void) const; - - /** Sets whether or not objects which cast shadows should be treated as - never receiving shadows. - */ - void setShadowCastersCannotBeReceivers(bool ind); - - /** Gets whether or not objects which cast shadows should be treated as - never receiving shadows. - */ - bool getShadowCastersCannotBeReceivers(void) const; - - /** Set a renderable listener on the queue. - - There can only be a single renderable listener on the queue, since - that listener has complete control over the techniques in use. - */ - void setRenderableListener(RenderableListener* listener) - { mRenderableListener = listener; } - - RenderableListener* getRenderableListener(void) const - { return mRenderableListener; } - - /** Merge render queue. - */ - void merge( const RenderQueue* rhs ); - /** Utility method to perform the standard actions associated with - getting a visible object to add itself to the queue. This is - a replacement for SceneManager implementations of the associated - tasks related to calling MovableObject::_updateRenderQueue. - */ - void processVisibleObject(MovableObject* mo, - Camera* cam, - bool onlyShadowCasters, - VisibleObjectsBoundsInfo* visibleBounds); - - }; - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreRenderQueueListener.h b/OgreMain/include/OgreRenderQueueListener.h deleted file mode 100644 index f91f47c127b..00000000000 --- a/OgreMain/include/OgreRenderQueueListener.h +++ /dev/null @@ -1,102 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __RenderQueueListener_H__ -#define __RenderQueueListener_H__ - -#include "OgrePrerequisites.h" -#include "OgreRenderQueue.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - /** Abstract interface which classes must implement if they wish to receive - events from the render queue. - - The OGRE render queue is divided into several queue groups, as defined by - uint8. A class may implement this interface, and register itself - as a listener by calling SceneManager::addRenderQueueListener. After doing so, - the class will receive an event before and after each queue group is sent to - the rendering system. - @par - The event listeners have an option to make a queue either be skipped, or to repeat. - Note that if multiple listeners are registered, the one registered last has the final - say, although options set by previous listeners will not be changed if the latest - does not express a preference. - */ - class _OgreExport RenderQueueListener - { - public: - virtual ~RenderQueueListener() {} - - /** Event raised before all render queues are processed. - */ - virtual void preRenderQueues() {} - /** Event raised after all render queues are processed. - */ - virtual void postRenderQueues() {} - - /** Event raised before a queue group is rendered. - - This method is called by the SceneManager before each queue group is - rendered. - @param queueGroupId The id of the queue group which is about to be rendered - @param cameraName Name of the camera which is triggering this to be - called - @param skipThisInvocation A boolean passed by reference which is by default set to - false. If the event sets this to true, the queue will be skipped and not - rendered. Note that in this case the renderQueueEnded event will not be raised - for this queue group. - */ - virtual void renderQueueStarted(uint8 queueGroupId, const String& cameraName, bool& skipThisInvocation) {} - - /** Event raised after a queue group is rendered. - - This method is called by the SceneManager after each queue group is - rendered. - @param queueGroupId The id of the queue group which has just been rendered - @param cameraName Name of the camera which is triggering this to be - called - @param repeatThisInvocation A boolean passed by reference which is by default set to - false. If the event sets this to true, the queue which has just been - rendered will be repeated, and the renderQueueStarted and renderQueueEnded - events will also be fired for it again. - */ - virtual void renderQueueEnded(uint8 queueGroupId, const String& cameraName, bool& repeatThisInvocation) {} - }; - /** @} */ - /** @} */ - -} - -#endif - diff --git a/OgreMain/include/OgreRenderQueueSortingGrouping.h b/OgreMain/include/OgreRenderQueueSortingGrouping.h deleted file mode 100644 index 73aa8d5b489..00000000000 --- a/OgreMain/include/OgreRenderQueueSortingGrouping.h +++ /dev/null @@ -1,629 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __RenderQueueSortingGrouping_H__ -#define __RenderQueueSortingGrouping_H__ - -// Precompiler options -#include "OgrePrerequisites.h" -#include "OgrePass.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - - typedef std::vector RenderableList; - - /** Struct associating a single Pass with a single Renderable. - This is used to for objects sorted by depth and thus not - grouped by pass. - */ - struct RenderablePass - { - /// Pointer to the Renderable details - Renderable* renderable; - /// Pointer to the Pass - Pass* pass; - - RenderablePass(Renderable* rend, Pass* p) :renderable(rend), pass(p) {} - }; - - - /** Visitor interface for items in a QueuedRenderableCollection. - - Those wishing to iterate over the items in a - QueuedRenderableCollection should implement this visitor pattern, - since internal organisation of the collection depends on the - sorting method in use. - */ - class _OgreExport QueuedRenderableVisitor - { - public: - QueuedRenderableVisitor() {} - virtual ~QueuedRenderableVisitor() {} - - /** Called when visiting a RenderablePass, i.e. items in a - sorted collection where items are not grouped by pass. - - If this is called, the other visit method - will not be called. - */ - virtual void visit(RenderablePass* rp) = 0; - - /** When visiting a collection grouped by pass, this is - called. - - If this method is called, the RenderablePass visit - method will not be called for this collection. - */ - virtual void visit(const Pass* p, RenderableList& rs) = 0; - }; - - /** Lowest level collection of renderables. - - To iterate over items in this collection, you must call - the accept method and supply a QueuedRenderableVisitor. - The order of the iteration, and whether that iteration is - over a RenderablePass list or a 2-level grouped list which - causes a visit call at the Pass level, and a call for each - Renderable underneath. - */ - class _OgreExport QueuedRenderableCollection : public RenderQueueAlloc - { - public: - /** Organisation modes required for this collection. - - This affects the internal placement of the items added to this collection; - if only one type of sorting / grouping is to be required, then renderables - can be stored only once, whilst if multiple types are going to be needed - then internally there will be multiple organisations. Changing the organisation - needs to be done when the collection is empty. - */ - enum OrganisationMode - { - /// Group by pass - OM_PASS_GROUP = 1, - /// Sort descending camera distance - OM_SORT_DESCENDING = 2, - /** Sort ascending camera distance - Note value overlaps with descending since both use same sort - */ - OM_SORT_ASCENDING = 6 - }; - - private: - /// Comparator to order pass groups - struct PassGroupLess - { - bool operator()(const Pass* a, const Pass* b) const - { - // Sort by passHash, which is pass, then texture unit changes - uint32 hasha = a->getHash(); - uint32 hashb = b->getHash(); - if (hasha == hashb) - { - // Must differentTransparentQueueItemLessiate by pointer in case 2 passes end up with the same hash - return a < b; - } - else - { - return hasha < hashb; - } - } - }; - /** Vector of RenderablePass objects, this is built on the assumption that - vectors only ever increase in size, so even if we do clear() the memory stays - allocated, ie fast */ - typedef std::vector RenderablePassList; - /** Map of pass to renderable lists, this is a grouping by pass. */ - typedef std::map PassGroupRenderableMap; - - /// Bitmask of the organisation modes requested - uint8 mOrganisationMode; - - /// Grouped - PassGroupRenderableMap mGrouped; - /// Sorted descending (can iterate backwards to get ascending) - RenderablePassList mSortedDescending; - - /// Internal visitor implementation - void acceptVisitorGrouped(QueuedRenderableVisitor* visitor) const; - /// Internal visitor implementation - void acceptVisitorDescending(QueuedRenderableVisitor* visitor) const; - /// Internal visitor implementation - void acceptVisitorAscending(QueuedRenderableVisitor* visitor) const; - - public: - QueuedRenderableCollection(); - - /// Empty the collection - void clear(void); - - /** Remove the group entry (if any) for a given Pass. - - To be used when a pass is destroyed, such that any - grouping level for it becomes useless. - */ - void removePassGroup(Pass* p); - - /** Reset the organisation modes required for this collection. - - You can only do this when the collection is empty. - @see OrganisationMode - */ - void resetOrganisationModes(void) - { - mOrganisationMode = 0; - } - - /** Add a required sorting / grouping mode to this collection when next used. - - You can only do this when the collection is empty. - @see OrganisationMode - */ - void addOrganisationMode(OrganisationMode om) - { - mOrganisationMode |= uint8(om); - } - - /// Add a renderable to the collection using a given pass - void addRenderable(Pass* pass, Renderable* rend); - - /** Perform any sorting that is required on this collection. - @param cam The camera - */ - void sort(const Camera* cam); - - /** Accept a visitor over the collection contents. - @param visitor Visitor class which should be called back - @param om The organisation mode which you want to iterate over. - Note that this must have been included in an addOrganisationMode - call before any renderables were added. - */ - void acceptVisitor(QueuedRenderableVisitor* visitor, OrganisationMode om) const; - - /** Merge renderable collection. - */ - void merge( const QueuedRenderableCollection& rhs ); - }; - - /** Collection of renderables by priority. - - This class simply groups renderables for rendering. All the - renderables contained in this class are destined for the same - RenderQueueGroup (coarse groupings like those between the main - scene and overlays) and have the same priority (fine groupings - for detailed overlap control). - @par - This class can order solid renderables by a number of criteria; - it can optimise them into groups based on pass to reduce render - state changes, or can sort them by ascending or descending view - depth. Transparent objects are always ordered by descending depth. - @par - To iterate over items in the collections held by this object - you should retrieve the collection in use (e.g. solids, solids with - no shadows, transparents) and use the accept() method, providing - a class implementing QueuedRenderableVisitor. - - */ - class _OgreExport RenderPriorityGroup : public RenderQueueAlloc - { - private: - - /// Parent queue group - RenderQueueGroup* mParent; - bool mSplitPassesByLightingType; - bool mSplitNoShadowPasses; - bool mShadowCastersNotReceivers; - /// Solid pass list, used when no shadows, modulative shadows, or ambient passes for additive - QueuedRenderableCollection mSolidsBasic; - /// Solid per-light pass list, used with additive shadows - QueuedRenderableCollection mSolidsDiffuseSpecular; - /// Solid decal (texture) pass list, used with additive shadows - QueuedRenderableCollection mSolidsDecal; - /// Solid pass list, used when shadows are enabled but shadow receive is turned off for these passes - QueuedRenderableCollection mSolidsNoShadowReceive; - /// Unsorted transparent list - QueuedRenderableCollection mTransparentsUnsorted; - /// Transparent list - QueuedRenderableCollection mTransparents; - - /// remove a pass entry from all collections - void removePassEntry(Pass* p); - /// Internal method for adding a solid renderable - void addSolidRenderableSplitByLightType(Technique* pTech, Renderable* rend); - - public: - RenderPriorityGroup(RenderQueueGroup* parent, - bool splitPassesByLightingType, - bool splitNoShadowPasses, - bool shadowCastersNotReceivers); - - ~RenderPriorityGroup() { } - - /** Get the collection of basic solids currently queued, this includes - all solids when there are no shadows, or all solids which have shadow - receiving enabled when using modulative shadows, or all ambient passes - of solids which have shadow receive enabled for additive shadows. */ - const QueuedRenderableCollection& getSolidsBasic(void) const - { return mSolidsBasic; } - /** Get the collection of solids currently queued per light (only applicable in - additive shadow modes). */ - const QueuedRenderableCollection& getSolidsDiffuseSpecular(void) const - { return mSolidsDiffuseSpecular; } - /** Get the collection of solids currently queued for decal passes (only - applicable in additive shadow modes). */ - const QueuedRenderableCollection& getSolidsDecal(void) const - { return mSolidsDecal; } - /** Get the collection of solids for which shadow receipt is disabled (only - applicable when shadows are enabled). */ - const QueuedRenderableCollection& getSolidsNoShadowReceive(void) const - { return mSolidsNoShadowReceive; } - /** Get the collection of transparent objects currently queued */ - const QueuedRenderableCollection& getTransparentsUnsorted(void) const - { return mTransparentsUnsorted; } - /** Get the collection of transparent objects currently queued */ - const QueuedRenderableCollection& getTransparents(void) const - { return mTransparents; } - - - /** Reset the organisation modes required for the solids in this group. - - You can only do this when the group is empty, i.e. after clearing the - queue. - @see QueuedRenderableCollection::OrganisationMode - */ - void resetOrganisationModes(void); - - /** Add a required sorting / grouping mode for the solids in this group. - - You can only do this when the group is empty, i.e. after clearing the - queue. - @see QueuedRenderableCollection::OrganisationMode - */ - void addOrganisationMode(QueuedRenderableCollection::OrganisationMode om); - - /** Set the sorting / grouping mode for the solids in this group to the default. - - You can only do this when the group is empty, i.e. after clearing the - queue. - @see QueuedRenderableCollection::OrganisationMode - */ - void defaultOrganisationMode(void); - - /** Add a renderable to this group. */ - void addRenderable(Renderable* pRend, Technique* pTech); - - /** Sorts the objects which have been added to the queue; transparent objects by their - depth in relation to the passed in Camera. */ - void sort(const Camera* cam); - - /** Clears this group of renderables. - */ - void clear(void); - - /** Sets whether or not the queue will split passes by their lighting type, - ie ambient, per-light and decal. - */ - void setSplitPassesByLightingType(bool split) - { - mSplitPassesByLightingType = split; - } - - /** Sets whether or not passes which have shadow receive disabled should - be separated. - */ - void setSplitNoShadowPasses(bool split) - { - mSplitNoShadowPasses = split; - } - - /** Sets whether or not objects which cast shadows should be treated as - never receiving shadows. - */ - void setShadowCastersCannotBeReceivers(bool ind) - { - mShadowCastersNotReceivers = ind; - } - - /** Merge group of renderables. - */ - void merge( const RenderPriorityGroup* rhs ); - - - }; - - - /** A grouping level underneath RenderQueue which groups renderables - to be issued at coarsely the same time to the renderer. - - Each instance of this class itself hold RenderPriorityGroup instances, - which are the groupings of renderables by priority for fine control - of ordering (not required for most instances). - */ - class _OgreExport RenderQueueGroup : public RenderQueueAlloc - { - public: - typedef std::map > PriorityMap; - typedef MapIterator PriorityMapIterator; - typedef ConstMapIterator ConstPriorityMapIterator; - private: - bool mSplitPassesByLightingType; - bool mSplitNoShadowPasses; - bool mShadowCastersNotReceivers; - /// Map of RenderPriorityGroup objects - PriorityMap mPriorityGroups; - /// Whether shadows are enabled for this queue - bool mShadowsEnabled; - /// Bitmask of the organisation modes requested (for new priority groups) - uint8 mOrganisationMode; - - - public: - RenderQueueGroup(bool splitPassesByLightingType, - bool splitNoShadowPasses, - bool shadowCastersNotReceivers) - : mSplitPassesByLightingType(splitPassesByLightingType) - , mSplitNoShadowPasses(splitNoShadowPasses) - , mShadowCastersNotReceivers(shadowCastersNotReceivers) - , mShadowsEnabled(true) - , mOrganisationMode(0) - { - } - - ~RenderQueueGroup() { - // destroy contents now - PriorityMap::iterator i; - for (i = mPriorityGroups.begin(); i != mPriorityGroups.end(); ++i) - { - OGRE_DELETE i->second; - } - } - - const PriorityMap& getPriorityGroups() const { return mPriorityGroups; } - - /** Add a renderable to this group, with the given priority. */ - void addRenderable(Renderable* pRend, Technique* pTech, ushort priority) - { - // Check if priority group is there - PriorityMap::iterator i = mPriorityGroups.find(priority); - RenderPriorityGroup* pPriorityGrp; - if (i == mPriorityGroups.end()) - { - // Missing, create - pPriorityGrp = OGRE_NEW RenderPriorityGroup(this, - mSplitPassesByLightingType, - mSplitNoShadowPasses, - mShadowCastersNotReceivers); - if (mOrganisationMode) - { - pPriorityGrp->resetOrganisationModes(); - pPriorityGrp->addOrganisationMode((QueuedRenderableCollection::OrganisationMode)mOrganisationMode); - } - - mPriorityGroups.emplace(priority, pPriorityGrp); - } - else - { - pPriorityGrp = i->second; - } - - // Add - pPriorityGrp->addRenderable(pRend, pTech); - - } - - /** Clears this group of renderables. - @param destroy - If false, doesn't delete any priority groups, just empties them. Saves on - memory deallocations since the chances are roughly the same kinds of - renderables are going to be sent to the queue again next time. If - true, completely destroys. - */ - void clear(bool destroy = false) - { - PriorityMap::iterator i, iend; - iend = mPriorityGroups.end(); - for (i = mPriorityGroups.begin(); i != iend; ++i) - { - if (destroy) - OGRE_DELETE i->second; - else - i->second->clear(); - } - - if (destroy) - mPriorityGroups.clear(); - - } - - /** Indicate whether a given queue group will be doing any - shadow setup. - - This method allows you to inform the queue about a queue group, and to - indicate whether this group will require shadow processing of any sort. - In order to preserve rendering order, OGRE has to treat queue groups - as very separate elements of the scene, and this can result in it - having to duplicate shadow setup for each group. Therefore, if you - know that a group which you are using will never need shadows, you - should preregister the group using this method in order to improve - the performance. - */ - void setShadowsEnabled(bool enabled) { mShadowsEnabled = enabled; } - - /** Are shadows enabled for this queue? */ - bool getShadowsEnabled(void) const { return mShadowsEnabled; } - - /** Sets whether or not the queue will split passes by their lighting type, - ie ambient, per-light and decal. - */ - void setSplitPassesByLightingType(bool split) - { - mSplitPassesByLightingType = split; - PriorityMap::iterator i, iend; - iend = mPriorityGroups.end(); - for (i = mPriorityGroups.begin(); i != iend; ++i) - { - i->second->setSplitPassesByLightingType(split); - } - } - /** Sets whether or not the queue will split passes which have shadow receive - turned off (in their parent material), which is needed when certain shadow - techniques are used. - */ - void setSplitNoShadowPasses(bool split) - { - mSplitNoShadowPasses = split; - PriorityMap::iterator i, iend; - iend = mPriorityGroups.end(); - for (i = mPriorityGroups.begin(); i != iend; ++i) - { - i->second->setSplitNoShadowPasses(split); - } - } - /** Sets whether or not objects which cast shadows should be treated as - never receiving shadows. - */ - void setShadowCastersCannotBeReceivers(bool ind) - { - mShadowCastersNotReceivers = ind; - PriorityMap::iterator i, iend; - iend = mPriorityGroups.end(); - for (i = mPriorityGroups.begin(); i != iend; ++i) - { - i->second->setShadowCastersCannotBeReceivers(ind); - } - } - /** Reset the organisation modes required for the solids in this group. - - You can only do this when the group is empty, ie after clearing the - queue. - @see QueuedRenderableCollection::OrganisationMode - */ - void resetOrganisationModes(void) - { - mOrganisationMode = 0; - - PriorityMap::iterator i, iend; - iend = mPriorityGroups.end(); - for (i = mPriorityGroups.begin(); i != iend; ++i) - { - i->second->resetOrganisationModes(); - } - } - - /** Add a required sorting / grouping mode for the solids in this group. - - You can only do this when the group is empty, ie after clearing the - queue. - @see QueuedRenderableCollection::OrganisationMode - */ - void addOrganisationMode(QueuedRenderableCollection::OrganisationMode om) - { - mOrganisationMode |= uint8(om); - - PriorityMap::iterator i, iend; - iend = mPriorityGroups.end(); - for (i = mPriorityGroups.begin(); i != iend; ++i) - { - i->second->addOrganisationMode(om); - } - } - - /** Setthe sorting / grouping mode for the solids in this group to the default. - - You can only do this when the group is empty, ie after clearing the - queue. - @see QueuedRenderableCollection::OrganisationMode - */ - void defaultOrganisationMode(void) - { - mOrganisationMode = 0; - - PriorityMap::iterator i, iend; - iend = mPriorityGroups.end(); - for (i = mPriorityGroups.begin(); i != iend; ++i) - { - i->second->defaultOrganisationMode(); - } - } - - /** Merge group of renderables. - */ - void merge( const RenderQueueGroup* rhs ) - { - for ( const auto& pg : rhs->getPriorityGroups() ) - { - ushort priority = pg.first; - RenderPriorityGroup* pSrcPriorityGrp = pg.second; - RenderPriorityGroup* pDstPriorityGrp; - - // Check if priority group is there - PriorityMap::iterator i = mPriorityGroups.find(priority); - if (i == mPriorityGroups.end()) - { - // Missing, create - pDstPriorityGrp = OGRE_NEW RenderPriorityGroup(this, - mSplitPassesByLightingType, - mSplitNoShadowPasses, - mShadowCastersNotReceivers); - if (mOrganisationMode) - { - pDstPriorityGrp->resetOrganisationModes(); - pDstPriorityGrp->addOrganisationMode((QueuedRenderableCollection::OrganisationMode)mOrganisationMode); - } - - mPriorityGroups.emplace(priority, pDstPriorityGrp); - } - else - { - pDstPriorityGrp = i->second; - } - - // merge - pDstPriorityGrp->merge( pSrcPriorityGrp ); - } - } - }; - - /** @} */ - /** @} */ - - -} - -#include "OgreHeaderSuffix.h" - -#endif - - diff --git a/OgreMain/include/OgreRenderSystem.h b/OgreMain/include/OgreRenderSystem.h deleted file mode 100644 index ff170814b90..00000000000 --- a/OgreMain/include/OgreRenderSystem.h +++ /dev/null @@ -1,1215 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __RenderSystem_H_ -#define __RenderSystem_H_ - -// Precompiler options -#include "OgrePrerequisites.h" - -#include "OgreTextureUnitState.h" -#include "OgreCommon.h" - -#include "OgreRenderSystemCapabilities.h" -#include "OgreConfigOptionMap.h" -#include "OgreGpuProgram.h" -#include "OgrePlane.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - - typedef std::vector DepthBufferVec; - typedef std::map< uint16, DepthBufferVec > DepthBufferMap; - typedef std::map< String, RenderTarget * > RenderTargetMap; - typedef std::multimap RenderTargetPriorityMap; - - class TextureManager; - /// Enum describing the ways to generate texture coordinates - enum TexCoordCalcMethod : uint8 - { - /// No calculated texture coordinates - TEXCALC_NONE, - /// Environment map based on vertex normals - TEXCALC_ENVIRONMENT_MAP, - /// Environment map based on vertex positions - TEXCALC_ENVIRONMENT_MAP_PLANAR, - TEXCALC_ENVIRONMENT_MAP_REFLECTION, - TEXCALC_ENVIRONMENT_MAP_NORMAL, - /// Projective texture - TEXCALC_PROJECTIVE_TEXTURE - }; - /// Enum describing the various actions which can be taken on the stencil buffer - enum StencilOperation - { - /// Leave the stencil buffer unchanged - SOP_KEEP, - /// Set the stencil value to zero - SOP_ZERO, - /// Set the stencil value to the reference value - SOP_REPLACE, - /// Increase the stencil value by 1, clamping at the maximum value - SOP_INCREMENT, - /// Decrease the stencil value by 1, clamping at 0 - SOP_DECREMENT, - /// Increase the stencil value by 1, wrapping back to 0 when incrementing the maximum value - SOP_INCREMENT_WRAP, - /// Decrease the stencil value by 1, wrapping when decrementing 0 - SOP_DECREMENT_WRAP, - /// Invert the bits of the stencil buffer - SOP_INVERT - }; - - /** Describes the stencil buffer operation - - The stencil buffer is used to mask out pixels in the render target, allowing - you to do effects like mirrors, cut-outs, stencil shadows and more. Each of - your batches of rendering is likely to ignore the stencil buffer, - update it with new values, or apply it to mask the output of the render. - - The stencil test is: - $$(referenceValue\\,\\&\\,compareMask)\\;compareOp\\;(stencilBuffer\\,\\&\\,compareMask)$$ - - The result of this will cause one of 3 actions depending on whether - 1. the stencil test fails - 2. the stencil test succeeds but the depth buffer check fails - 3. both depth buffer check and stencil test pass - */ - struct _OgreExport StencilState - { - /// Comparison operator for the stencil test - CompareFunction compareOp; - /// The action to perform when the stencil check fails - StencilOperation stencilFailOp; - /// The action to perform when the stencil check passes, but the depth buffer check fails - StencilOperation depthFailOp; - /// The action to take when both the stencil and depth check pass - StencilOperation depthStencilPassOp; - - /// The reference value used in the stencil comparison - uint32 referenceValue; - /// The bitmask applied to both the stencil value and the reference value before comparison - uint32 compareMask; - /** The bitmask the controls which bits from stencilRefValue will be written to stencil buffer - (valid for operations such as #SOP_REPLACE) */ - uint32 writeMask; - - /// Turns stencil buffer checking on or off - bool enabled : 1; - /// Toggles two-sided stencil operation, which swaps increment and decrement for back-facing polygons. - bool twoSidedOperation : 1; - - StencilState() - : compareOp(CMPF_LESS_EQUAL), stencilFailOp(SOP_KEEP), depthFailOp(SOP_KEEP), - depthStencilPassOp(SOP_KEEP), referenceValue(0), compareMask(0xFFFFFFFF), - writeMask(0xFFFFFFFF), enabled(false), twoSidedOperation(false) - { - } - }; - - /** Defines the functionality of a 3D API - - The RenderSystem class provides a base interface - which abstracts the general functionality of the 3D API - e.g. Direct3D or OpenGL. Whilst a few of the general - methods have implementations, most of this class is - abstract, requiring a subclass based on a specific API - to be constructed to provide the full functionality. - Note there are 2 levels to the interface - one which - will be used often by the caller of the Ogre library, - and one which is at a lower level and will be used by the - other classes provided by Ogre. These lower level - methods are prefixed with '_' to differentiate them. - The advanced user of the library may use these lower - level methods to access the 3D API at a more fundamental - level (dealing direct with render states and rendering - primitives), but still benefiting from Ogre's abstraction - of exactly which 3D API is in use. - @author - Steven Streeting - @version - 1.0 - */ - class _OgreExport RenderSystem : public RenderSysAlloc - { - public: - /** Default Constructor. - */ - RenderSystem(); - - /** Destructor. - */ - virtual ~RenderSystem(); - - /** Returns the name of the rendering system. - */ - virtual const String& getName(void) const = 0; - - /** Returns the details of this API's configuration options - - Each render system must be able to inform the world - of what options must/can be specified for it's - operation. - @par - These are passed as strings for portability, but - grouped into a structure (ConfigOption) which includes - both options and current value. - @par - Note that the settings returned from this call are - affected by the options that have been set so far, - since some options are interdependent. - @par - This routine is called automatically by the default - configuration dialogue produced by Root::showConfigDialog - or may be used by the caller for custom settings dialogs - @return - A 'map' of options, i.e. a list of options which is also - indexed by option name. - */ - const ConfigOptionMap& getConfigOptions() const { return mOptions; } - - /** Sets an option for this API - - Used to confirm the settings (normally chosen by the user) in - order to make the renderer able to initialise with the settings as required. - This may initialise the @ref RenderWindowDescription or set some RenderSystem - specific parameters. - Called automatically by the default configuration - dialog, and by the restoration of saved settings. - These settings are stored and only activated when - @ref RenderSystem::_initialise or @ref RenderSystem::reinitialise - are called. - - If using a custom configuration dialog, it is advised that the - caller calls RenderSystem::getConfigOptions - again, since some options can alter resulting from a selection. - - Common options: - - | Key | Default | Description | - |-----|---------------|---------| - | Full Screen | false | Window full-screen flag | - | VSync | true | "vsync" in @ref _createRenderWindow | - | VSync Interval | 1 | "vsyncInterval" in @ref _createRenderWindow | - | sRGB Gamma Conversion | false | "gamma" in @ref _createRenderWindow | - | FSAA | 0 | concatenation of "FSAA" and "FSAAHint" as in @ref _createRenderWindow | - | Video Mode | - | Window resolution | - | Display Frequency | - | "displayFrequency" in @ref _createRenderWindow | - | Content Scaling Factor | 1.0 | "contentScalingFactor" in @ref _createRenderWindow | - @param - name The name of the option to alter. - @param - value The value to set the option to. - */ - virtual void setConfigOption(const String &name, const String &value) = 0; - - /** get a RenderWindowDescription from the current ConfigOptionMap - */ - RenderWindowDescription getRenderWindowDescription() const; - - /** Create an object for performing hardware occlusion queries. - */ - virtual HardwareOcclusionQuery* createHardwareOcclusionQuery(void) = 0; - - /** Destroy a hardware occlusion query object. - */ - virtual void destroyHardwareOcclusionQuery(HardwareOcclusionQuery *hq); - - /** Validates the options set for the rendering system, returning a message if there are problems. - @note - If the returned string is empty, there are no problems. - */ - virtual String validateConfigOptions(void) { return BLANKSTRING; } - - /** Start up the renderer using the settings selected (Or the defaults if none have been selected). - - Called by Root::setRenderSystem. Shouldn't really be called - directly, although this can be done if the app wants to. - */ - virtual void _initialise(); - - /** Get a pointer to the current capabilities being used by the RenderSystem. - - The capabilities may be modified using this pointer, this will only have an effect - before the RenderSystem has been initialised. It's intended use is to allow a - listener of the RenderSystemCapabilitiesCreated event to customise the capabilities - on the fly before the RenderSystem is initialised. - */ - RenderSystemCapabilities* getMutableCapabilities(){ return mCurrentCapabilities; } - - /** Force the render system to use the special capabilities. Can only be called - * before the render system has been fully initializer (before createWindow is called) - * @param - * capabilities has to be a subset of the real capabilities and the caller is - * responsible for deallocating capabilities. - */ - void useCustomRenderSystemCapabilities(RenderSystemCapabilities* capabilities); - - /** Restart the renderer (normally following a change in settings). - */ - void reinitialise(void); - - /** Shutdown the renderer and cleanup resources. - */ - virtual void shutdown(void); - - virtual const GpuProgramParametersPtr& getFixedFunctionParams(TrackVertexColourType tracking, - FogMode fog) - { - return mFixedFunctionParams; - } - - /// @deprecated migrate to getFixedFunctionParams ASAP. this is very slow now. - OGRE_DEPRECATED void _setProjectionMatrix(Matrix4 m); - - /// @deprecated migrate to getFixedFunctionParams ASAP. this is very slow now. - OGRE_DEPRECATED void _setViewMatrix(const Matrix4& m) - { - if (!mFixedFunctionParams) return; - mFixedFunctionParams->setConstant(4, m); - applyFixedFunctionParams(mFixedFunctionParams, GPV_GLOBAL); - } - - /// @deprecated migrate to getFixedFunctionParams ASAP. this is very slow now. - OGRE_DEPRECATED void _setWorldMatrix(const Matrix4& m) - { - if (!mFixedFunctionParams) return; - mFixedFunctionParams->setConstant(0, m); - applyFixedFunctionParams(mFixedFunctionParams, GPV_PER_OBJECT); - } - - /// @deprecated migrate to getFixedFunctionParams ASAP. this is very slow now. - OGRE_DEPRECATED void _setFog(FogMode f) - { - if (mFixedFunctionParams) - getFixedFunctionParams(TVC_NONE, f); - } - - /// @deprecated use setColourBlendState - OGRE_DEPRECATED void _setSceneBlending(SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, - SceneBlendOperation op = SBO_ADD) - { - mCurrentBlend.sourceFactor = sourceFactor; - mCurrentBlend.destFactor = destFactor; - mCurrentBlend.sourceFactorAlpha = sourceFactor; - mCurrentBlend.destFactorAlpha = destFactor; - mCurrentBlend.operation = op; - mCurrentBlend.alphaOperation = op; - setColourBlendState(mCurrentBlend); - } - - virtual void applyFixedFunctionParams(const GpuProgramParametersPtr& params, uint16 variabilityMask) {} - - /** Sets the type of light shading required (default = Gouraud). - @deprecated only needed for fixed function APIs - */ - virtual void setShadingType(ShadeOptions so) {} - - /** Sets whether or not dynamic lighting is enabled. - @param - enabled If true, dynamic lighting is performed on geometry with normals supplied, geometry without - normals will not be displayed. If false, no lighting is applied and all geometry will be full brightness. - @deprecated only needed for fixed function APIs - */ - virtual void setLightingEnabled(bool enabled) {} - - /** Creates a new rendering window. - - This method creates a new rendering window as specified - by the paramteters. The rendering system could be - responible for only a single window (e.g. in the case - of a game), or could be in charge of multiple ones (in the - case of a level editor). The option to create the window - as a child of another is therefore given. - This method will create an appropriate subclass of - RenderWindow depending on the API and platform implementation. - @par - After creation, this window can be retrieved using getRenderTarget(). - @param - name The name of the window. Used in other methods - later like setRenderTarget and getRenderTarget. - @param - width The width of the new window. - @param - height The height of the new window. - @param - fullScreen Specify true to make the window full screen - without borders, title bar or menu bar. - @param - miscParams A NameValuePairList describing the other parameters for the new rendering window. - Options are case sensitive. Unrecognised parameters will be ignored silently. - These values might be platform dependent, but these are present for all platforms unless - indicated otherwise: - - | Key | Type / Values | Default | Description | Platform | - |-----|---------------|---------|-------------|-------| - | title | String | RenderTarget name | The title of the window that will appear in the title bar | | - | left | Positive integers | Centred | Screen x coordinate from left | | - | top | Positive integers | Centred | Screen y coordinate from left | | - | hidden | true, false | false | hide the created window | | - | FSAA | Positive integer (usually 0, 2, 4, 8, 16) | 0 | Full screen antialiasing factor | | - | gamma | true, false | false | Enable hardware conversion from linear colour space to gamma colour space on rendering to the window. | | - | vsync | true, false | false | Synchronize buffer swaps to monitor vsync, eliminating tearing at the expense of a fixed frame rate | | - | vsyncInterval | 1, 2, 3, 4 | 1 | If vsync is enabled, the minimum number of vertical blanks that should occur between renders. For example if vsync is enabled, the refresh rate is 60 and this is set to 2, then the frame rate will be locked at 30. | | - | Full Screen | true, false | false | Specify whether to create the window in full screen mode | | - | border | none, fixed, resize | resize | The type of window border (in windowed mode) | Windows, OSX | - | displayFrequency | Refresh rate in Hertz (e.g. 60, 75, 100) | Desktop vsync rate | Display frequency rate, for fullscreen mode | | - | externalWindowHandle |
  • Win32: HWND as int
  • Linux: X11 Window as ulong
  • OSX: OgreGLView address as an integer. You can pass NSView or NSWindow too, but should perform OgreGLView callbacks into the Ogre manually
  • iOS: UIWindow address as an integer
  • Emscripten: canvas selector String ("#canvas")
| 0 (none) | External window handle, for embedding the OGRE render in an existing window | | - | externalGLControl | true, false | false | Let the external window control OpenGL i.e. don't select a pixel format for the window, do not change v-sync and do not swap buffer. When set to true, the calling application is responsible of OpenGL initialization and buffer swapping. It should also create an OpenGL context for its own rendering, Ogre will create one for its use. Then the calling application must also enable Ogre OpenGL context before calling any Ogre function and restore its OpenGL context after these calls. | OpenGL | - | currentGLContext | true, false | false | Use an externally created GL context. (Must be current) | OpenGL | - | minColourBufferSize | Positive integer (usually 16, 32) | 16 | Min total colour buffer size. See EGL_BUFFER_SIZE | OpenGL | - | windowProc | WNDPROC | DefWindowProc | function that processes window messages | Win 32 | - | colourDepth | 16, 32 | Desktop depth | Colour depth of the resulting rendering window; only applies if fullScreen | Win32 | - | FSAAHint | %RenderSystem specific. Currently enables EQAA/ CSAA mode on D3D: if you want 4f8x (8x CSAA), set FSAA=4 and this to "f8" | Blank | FSAA mode hint | D3D | - | outerDimensions | true, false | false | Whether the width/height is expressed as the size of the outer window, rather than the content area | Win32 | - | monitorIndex | | -1 | | Win 32 | - | monitorHandle | | 0 (none) | | Win 32 (OpenGL) | - | enableDoubleClick | true, false | false | Enable the window to keep track and transmit double click messages. | Win32 | - | useNVPerfHUD | true, false | false | Enable the use of nVidia NVPerfHUD | D3D | - | depthBuffer | true, false | true | Use depth buffer | D3D | - | NSOpenGLCPSurfaceOrder | -1 or 1 | 1 | [NSOpenGLCPSurfaceOrder](https://developer.apple.com/documentation/appkit/nsopenglcpsurfaceorder) | OSX | - | contentScalingFactor | Positive Float | The default content scaling factor of the screen | On IOS specifies the CAEAGLLayer content scaling factor. This can be useful to limit the resolution of the OpenGL ES backing store. For example, the iPhone 4's native resolution is 960 x 640\. Windows are always 320 x 480, if you would like to limit the display to 720 x 480, specify 1.5 as the scaling factor. | OSX, iOS, Android | - | externalViewHandle | UIView pointer as an integer | 0 | External view handle, for rendering OGRE render in an existing view | iOS | - | externalViewControllerHandle | UIViewController pointer as an integer | 0 | External view controller handle, for embedding OGRE in an existing view controller | iOS | - | externalSharegroup | EAGLSharegroup pointer as an integer | 0 | External sharegroup, used to shared GL resources between contexts | iOS | - | CSAA | Positive integer (usually 0, 2, 4, 8, 16) | 0 | [Coverage sampling factor](https://www.khronos.org/registry/egl/extensions/NV/EGL_NV_coverage_sample.txt) | Android | - | maxColourBufferSize | Positive integer (usually 16, 32) | 32 | Max EGL_BUFFER_SIZE | Android | - | maxStencilBufferSize | Positive integer (usually 0, 8) | 0 | EGL_STENCIL_SIZE | Android | - | maxDepthBufferSize | Positive integer (usually 0, 16, 24) | 16 | EGL_DEPTH_SIZE | Android | - */ - virtual RenderWindow* _createRenderWindow(const String &name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams = 0); - - /** Create a MultiRenderTarget, which is a render target that renders to multiple RenderTextures - at once. Surfaces can be bound and unbound at will. - This fails if mCapabilities->getNumMultiRenderTargets() is smaller than 2. - */ - virtual MultiRenderTarget * createMultiRenderTarget(const String & name) = 0; - - /** Destroys a render window */ - virtual void destroyRenderWindow(const String& name); - /** Destroys a render texture */ - virtual void destroyRenderTexture(const String& name); - /** Destroys a render target of any sort */ - virtual void destroyRenderTarget(const String& name); - - /** Attaches the passed render target to the render system. - */ - void attachRenderTarget( RenderTarget &target ); - /** Returns a pointer to the render target with the passed name, or NULL if that - render target cannot be found. - */ - RenderTarget * getRenderTarget( const String &name ); - /** Detaches the render target with the passed name from the render system and - returns a pointer to it. - @note - If the render target cannot be found, NULL is returned. - */ - virtual RenderTarget * detachRenderTarget( const String &name ); - - /** Returns the global instance vertex buffer. - */ - HardwareVertexBufferPtr getGlobalInstanceVertexBuffer() const { return mGlobalInstanceVertexBuffer; } - /** Sets the global instance vertex buffer. - */ - void setGlobalInstanceVertexBuffer(const HardwareVertexBufferPtr &val); - /** Gets vertex declaration for the global vertex buffer for the global instancing - */ - VertexDeclaration* getGlobalInstanceVertexDeclaration() const { return mGlobalInstanceVertexDeclaration; } - /** Sets vertex declaration for the global vertex buffer for the global instancing - */ - void setGlobalInstanceVertexDeclaration( VertexDeclaration* val) { mGlobalInstanceVertexDeclaration = val; } - /** Gets the global number of instances. - */ - uint32 getGlobalInstanceCount() const { return mGlobalNumberOfInstances; } - /** Sets the global number of instances. - */ - void setGlobalInstanceCount(uint32 val) { mGlobalNumberOfInstances = val; } - - /** Retrieves an existing DepthBuffer or creates a new one suited for the given RenderTarget - and sets it. - - RenderTarget's pool ID is respected. @see RenderTarget::setDepthBufferPool() - */ - void setDepthBufferFor( RenderTarget *renderTarget ); - - /** - Returns if reverse Z-buffer is enabled. - - If you have large scenes and need big far clip distance but still want - to draw objects closer (for example cockpit of a plane) you can enable - reverse depth buffer so that the depth buffer precision is greater further away. - This enables the OGRE_REVERSED_Z preprocessor define for shaders. - - @retval true If reverse Z-buffer is enabled. - @retval false If reverse Z-buffer is disabled (default). - - @see setReverseDepthBuffer - */ - bool isReverseDepthBufferEnabled() const; - - // ------------------------------------------------------------------------ - // Internal Rendering Access - // All methods below here are normally only called by other OGRE classes - // They can be called by library user if required - // ------------------------------------------------------------------------ - - /** Tells the rendersystem to use the attached set of lights (and no others) - up to the number specified (this allows the same list to be used with different - count limits) - @deprecated only needed for fixed function APIs - */ - virtual void _useLights(unsigned short limit) {} - /** Utility function for setting all the properties of a texture unit at once. - This method is also worth using over the individual texture unit settings because it - only sets those settings which are different from the current settings for this - unit, thus minimising render state changes. - */ - virtual void _setTextureUnitSettings(size_t texUnit, TextureUnitState& tl); - /// set the sampler settings for the given texture unit - virtual void _setSampler(size_t texUnit, Sampler& s) = 0; - /** Turns off a texture unit. */ - virtual void _disableTextureUnit(size_t texUnit); - /** Disables all texture units from the given unit upwards */ - virtual void _disableTextureUnitsFrom(size_t texUnit); - - /** Sets whether or not rendering points using OT_POINT_LIST will - render point sprites (textured quads) or plain points. - @param enabled True enables point sprites, false returns to normal - point rendering. - @deprecated only needed for fixed function APIs - */ - virtual void _setPointSpritesEnabled(bool enabled) {}; - - /** - @deprecated only needed for fixed function APIs - */ - virtual void _setPointParameters(bool attenuationEnabled, Real minSize, Real maxSize) {} - - /** - * Set the line width when drawing as RenderOperation::OT_LINE_LIST/ RenderOperation::OT_LINE_STRIP - * @param width only value of 1.0 might be supported. Check for RSC_WIDE_LINES. - */ - virtual void _setLineWidth(float width) {}; - - /** - Sets the texture to bind to a given texture unit. - - User processes would not normally call this direct unless rendering - primitives themselves. - - @param unit The index of the texture unit to modify. Multitexturing - hardware can support multiple units (see - RenderSystemCapabilites::getNumTextureUnits) - @param enabled Boolean to turn the unit on/off - @param texPtr Pointer to the texture to use. - */ - virtual void _setTexture(size_t unit, bool enabled, - const TexturePtr &texPtr) = 0; - - /** - Sets the texture coordinate set to use for a texture unit. - - Meant for use internally - not generally used directly by apps - the Material and TextureUnitState - classes let you manage textures far more easily. - - @param unit Texture unit as above - @param index The index of the texture coordinate set to use. - @deprecated only needed for fixed function APIs - */ - virtual void _setTextureCoordSet(size_t unit, size_t index) {} - - /** - Sets a method for automatically calculating texture coordinates for a stage. - Should not be used by apps - for use by Ogre only. - @param unit Texture unit as above - @param m Calculation method to use - @param frustum Optional Frustum param, only used for projective effects - @deprecated only needed for fixed function APIs - */ - virtual void _setTextureCoordCalculation(size_t unit, TexCoordCalcMethod m, - const Frustum* frustum = 0) {} - - /** Sets the texture blend modes from a TextureUnitState record. - Meant for use internally only - apps should use the Material - and TextureUnitState classes. - @param unit Texture unit as above - @param bm Details of the blending mode - @deprecated only needed for fixed function APIs - */ - virtual void _setTextureBlendMode(size_t unit, const LayerBlendModeEx& bm) {} - - /** Sets the texture coordinate transformation matrix for a texture unit. - @param unit Texture unit to affect - @param xform The 4x4 matrix - @deprecated only needed for fixed function APIs - */ - virtual void _setTextureMatrix(size_t unit, const Matrix4& xform) {} - - /// Sets the global blending factors for combining subsequent renders with the existing frame contents. - virtual void setColourBlendState(const ColourBlendState& state) = 0; - - /// @deprecated use setColourBlendState - OGRE_DEPRECATED void - _setSeparateSceneBlending(SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, - SceneBlendFactor sourceFactorAlpha, SceneBlendFactor destFactorAlpha, - SceneBlendOperation op = SBO_ADD, SceneBlendOperation alphaOp = SBO_ADD) - { - mCurrentBlend.sourceFactor = sourceFactor; - mCurrentBlend.destFactor = destFactor; - mCurrentBlend.sourceFactorAlpha = sourceFactorAlpha; - mCurrentBlend.destFactorAlpha = destFactorAlpha; - mCurrentBlend.operation = op; - mCurrentBlend.alphaOperation = alphaOp; - setColourBlendState(mCurrentBlend); - } - - /** Sets the global alpha rejection approach for future renders. - By default images are rendered regardless of texture alpha. This method lets you change that. - @param func The comparison function which must pass for a pixel to be written. - @param value The value to compare each pixels alpha value to (0-255) - @param alphaToCoverage Whether to enable alpha to coverage, if supported - */ - virtual void _setAlphaRejectSettings(CompareFunction func, unsigned char value, bool alphaToCoverage) = 0; - - /** Notify the rendersystem that it should adjust texture projection to be - relative to a different origin. - */ - virtual void _setTextureProjectionRelativeTo(bool enabled, const Vector3& pos); - - /** Creates a DepthBuffer that can be attached to the specified RenderTarget - - It doesn't attach anything, it just returns a pointer to a new DepthBuffer - Caller is responsible for putting this buffer into the right pool, for - attaching, and deleting it. Here's where API-specific magic happens. - Don't call this directly unless you know what you're doing. - */ - virtual DepthBuffer* _createDepthBufferFor( RenderTarget *renderTarget ) = 0; - - /** Removes all depth buffers. Should be called on device lost and shutdown - - Advanced users can call this directly with bCleanManualBuffers=false to - remove all depth buffers created for RTTs; when they think the pool has - grown too big or they've used lots of depth buffers they don't need anymore, - freeing GPU RAM. - */ - void _cleanupDepthBuffers( bool bCleanManualBuffers=true ); - - /** - * Signifies the beginning of a frame, i.e. the start of rendering on a single viewport. Will occur - * several times per complete frame if multiple viewports exist. - */ - virtual void _beginFrame(); - - /** - * Ends rendering of a frame to the current viewport. - */ - virtual void _endFrame(void) = 0; - /** - Sets the provided viewport as the active one for future - rendering operations. This viewport is aware of it's own - camera and render target. Must be implemented by subclass. - - @param vp Pointer to the appropriate viewport. - */ - virtual void _setViewport(Viewport *vp) = 0; - /** Get the current active viewport for rendering. */ - virtual Viewport* _getViewport(void); - - /** Sets the culling mode for the render system based on the 'vertex winding'. - @copydetails Pass::setCullingMode - */ - virtual void _setCullingMode(CullingMode mode) = 0; - - virtual CullingMode _getCullingMode(void) const; - - /** Sets the mode of operation for depth buffer tests from this point onwards. - Sometimes you may wish to alter the behaviour of the depth buffer to achieve - special effects. Because it's unlikely that you'll set these options for an entire frame, - but rather use them to tweak settings between rendering objects, this is an internal - method (indicated by the '_' prefix) which will be used by a SceneManager implementation - rather than directly from the client application. - If this method is never called the settings are automatically the same as the default parameters. - @param depthTest If true, the depth buffer is tested for each pixel and the frame buffer is only updated - if the depth function test succeeds. If false, no test is performed and pixels are always written. - @param depthWrite If true, the depth buffer is updated with the depth of the new pixel if the depth test succeeds. - If false, the depth buffer is left unchanged even if a new pixel is written. - @param depthFunction Sets the function required for the depth test. - */ - virtual void _setDepthBufferParams(bool depthTest = true, bool depthWrite = true, CompareFunction depthFunction = CMPF_LESS_EQUAL) = 0; - - /// @deprecated use setColourBlendState - OGRE_DEPRECATED void _setColourBufferWriteEnabled(bool red, bool green, bool blue, bool alpha) - { - mCurrentBlend.writeR = red; - mCurrentBlend.writeG = green; - mCurrentBlend.writeB = blue; - mCurrentBlend.writeA = alpha; - setColourBlendState(mCurrentBlend); - } - /** Sets the depth bias, NB you should use the Material version of this. - - When polygons are coplanar, you can get problems with 'depth fighting' where - the pixels from the two polys compete for the same screen pixel. This is particularly - a problem for decals (polys attached to another surface to represent details such as - bulletholes etc.). - @par - A way to combat this problem is to use a depth bias to adjust the depth buffer value - used for the decal such that it is slightly higher than the true value, ensuring that - the decal appears on top. - @note - The final bias value is a combination of a constant bias and a bias proportional - to the maximum depth slope of the polygon being rendered. The final bias - is constantBias + slopeScaleBias * maxslope. Slope scale biasing is - generally preferable but is not available on older hardware. - @param constantBias The constant bias value, expressed as a value in - homogeneous depth coordinates. - @param slopeScaleBias The bias value which is factored by the maximum slope - of the polygon, see the description above. This is not supported by all - cards. - - */ - virtual void _setDepthBias(float constantBias, float slopeScaleBias = 0.0f) = 0; - - /** - * Clamp depth values to near and far plane rather than discarding - * - * Useful for "shadow caster pancaking" or with shadow volumes - */ - virtual void _setDepthClamp(bool enable) {} - - /** The RenderSystem will keep a count of tris rendered, this resets the count. */ - virtual void _beginGeometryCount(void); - /** Reports the number of tris rendered since the last _beginGeometryCount call. */ - virtual unsigned int _getFaceCount(void) const; - /** Reports the number of batches rendered since the last _beginGeometryCount call. */ - virtual unsigned int _getBatchCount(void) const; - /** Reports the number of vertices passed to the renderer since the last _beginGeometryCount call. */ - virtual unsigned int _getVertexCount(void) const; - - /// @deprecated use ColourValue::getAsBYTE() - OGRE_DEPRECATED static void convertColourValue(const ColourValue& colour, uint32* pDest) - { - *pDest = colour.getAsBYTE(); - } - /// @deprecated assume VET_UBYTE4_NORM - OGRE_DEPRECATED static VertexElementType getColourVertexElementType(void) { return VET_UBYTE4_NORM; } - - /** Converts a uniform projection matrix to suitable for this render system. - - Because different APIs have different requirements (some incompatible) for the - projection matrix, this method allows each to implement their own correctly and pass - back a generic OGRE matrix for storage in the engine. - */ - virtual void _convertProjectionMatrix(const Matrix4& matrix, - Matrix4& dest, bool forGpuProgram = false) = 0; - - /** Sets how to rasterise triangles, as points, wireframe or solid polys. */ - virtual void _setPolygonMode(PolygonMode level) = 0; - - /** This method allows you to set all the stencil buffer parameters in one call. - - Unlike other render states, stencilling is left for the application to turn - on and off when it requires. This is because you are likely to want to change - parameters between batches of arbitrary objects and control the ordering yourself. - In order to batch things this way, you'll want to use OGRE's Compositor stencil pass - or separate render queue groups and register a RenderQueueListener to get notifications - between batches. - - @see RenderQueue - */ - virtual void setStencilState(const StencilState& state) = 0; - - /// @deprecated use setStencilState - OGRE_DEPRECATED void setStencilCheckEnabled(bool enabled); - /// @deprecated use setStencilState - OGRE_DEPRECATED void setStencilBufferParams(CompareFunction func = CMPF_ALWAYS_PASS, uint32 refValue = 0, - uint32 compareMask = 0xFFFFFFFF, uint32 writeMask = 0xFFFFFFFF, - StencilOperation stencilFailOp = SOP_KEEP, - StencilOperation depthFailOp = SOP_KEEP, - StencilOperation passOp = SOP_KEEP, bool twoSidedOperation = false); - - /** Sets whether or not normals are to be automatically normalised. - - This is useful when, for example, you are scaling SceneNodes such that - normals may not be unit-length anymore. Note though that this has an - overhead so should not be turn on unless you really need it. - @par - You should not normally call this direct unless you are rendering - world geometry; set it on the Renderable because otherwise it will be - overridden by material settings. - @deprecated only needed for fixed function APIs - */ - virtual void setNormaliseNormals(bool normalise) {} - - /** - Render something to the active viewport. - - Low-level rendering interface to perform rendering - operations. Unlikely to be used directly by client - applications, since the SceneManager and various support - classes will be responsible for calling this method. - Can only be called between _beginScene and _endScene - - @param op A rendering operation instance, which contains - details of the operation to be performed. - */ - virtual void _render(const RenderOperation& op); - - virtual void _dispatchCompute(const Vector3i& workgroupDim) {} - - /** Gets the capabilities of the render system. */ - const RenderSystemCapabilities* getCapabilities(void) const { return mCurrentCapabilities; } - - - /** Returns the driver version. - */ - const DriverVersion& getDriverVersion(void) const { return mDriverVersion; } - - /** Returns the default material scheme used by the render system. - Systems that use the RTSS to emulate a fixed function pipeline - (e.g. OpenGL ES 2, GL3+, DX11) need to return - the default material scheme of the RTSS ShaderGenerator. - - This is currently only used to set the default material scheme for - viewports. It is a necessary step on these render systems for - render textures to be rendered into properly. - */ - const String& _getDefaultViewportMaterialScheme(void) const; - - /** Binds a given GpuProgram (but not the parameters). - @remarks Only one GpuProgram of each type can be bound at once, binding another - one will simply replace the existing one. - */ - virtual void bindGpuProgram(GpuProgram* prg); - - /** Bind Gpu program parameters. - @param gptype The type of program to bind the parameters to - @param params The parameters to bind - @param variabilityMask A mask of GpuParamVariability identifying which params need binding - */ - virtual void bindGpuProgramParameters(GpuProgramType gptype, - const GpuProgramParametersPtr& params, uint16 variabilityMask) = 0; - - /** Unbinds GpuPrograms of a given GpuProgramType. - - This returns the pipeline to fixed-function processing for this type. - */ - virtual void unbindGpuProgram(GpuProgramType gptype); - - /** Returns whether or not a Gpu program of the given type is currently bound. */ - bool isGpuProgramBound(GpuProgramType gptype); - - /** - * Gets the native shading language version for this render system. - * Formatted so that it can be used within a shading program. - * For example, OpenGL 3.2 would return 150, while 3.3 would return 330 - */ - uint16 getNativeShadingLanguageVersion() const { return mNativeShadingLanguageVersion; } - - /** Sets the user clipping region. - @deprecated only needed for fixed function APIs - */ - virtual void setClipPlanes(const PlaneList& clipPlanes); - - /** Utility method for initialising all render targets attached to this rendering system. */ - void _initRenderTargets(void); - - /** Utility method to notify all render targets that a camera has been removed, - in case they were referring to it as their viewer. - */ - void _notifyCameraRemoved(const Camera* cam); - - /** Internal method for updating all render targets attached to this rendering system. */ - virtual void _updateAllRenderTargets(bool swapBuffers = true); - /** Internal method for swapping all the buffers on all render targets, - if _updateAllRenderTargets was called with a 'false' parameter. */ - virtual void _swapAllRenderTargetBuffers(); - - /** Sets whether or not vertex windings set should be inverted; this can be important - for rendering reflections. */ - void setInvertVertexWinding(bool invert); - - /** Indicates whether or not the vertex windings set will be inverted for the current render (e.g. reflections) - @see RenderSystem::setInvertVertexWinding - */ - bool getInvertVertexWinding(void) const; - - /** Sets the 'scissor region' i.e. the region of the target in which rendering can take place. - - This method allows you to 'mask off' rendering in all but a given rectangular area - as identified by the parameters to this method. - @param enabled True to enable the scissor test, false to disable it. - @param rect The location of the corners of the rectangle, expressed in - pixels. - */ - virtual void setScissorTest(bool enabled, const Rect& rect = Rect()) = 0; - /// @deprecated - OGRE_DEPRECATED void setScissorTest(bool enabled, uint32 left, uint32 top = 0, - uint32 right = 800, uint32 bottom = 600) - { - setScissorTest(enabled, Rect(left, top, right, bottom)); - } - - /** Clears one or more frame buffers on the active render target. - @param buffers Combination of one or more elements of FrameBufferType - denoting which buffers are to be cleared - @param colour The colour to clear the colour buffer with, if enabled - @param depth The value to initialise the depth buffer with, if enabled - @param stencil The value to initialise the stencil buffer with, if enabled. - */ - virtual void clearFrameBuffer(uint32 buffers, const ColourValue& colour = ColourValue::Black, - float depth = 1.0f, uint16 stencil = 0) = 0; - /** Returns the horizontal texel offset value required for mapping - texel origins to pixel origins in this rendersystem. - - Since rendersystems sometimes disagree on the origin of a texel, - mapping from texels to pixels can sometimes be problematic to - implement generically. This method allows you to retrieve the offset - required to map the origin of a texel to the origin of a pixel in - the horizontal direction. - @note only non-zero with D3D9 - */ - virtual Real getHorizontalTexelOffset(void) { return 0.0f; } - /** Returns the vertical texel offset value required for mapping - texel origins to pixel origins in this rendersystem. - - Since rendersystems sometimes disagree on the origin of a texel, - mapping from texels to pixels can sometimes be problematic to - implement generically. This method allows you to retrieve the offset - required to map the origin of a texel to the origin of a pixel in - the vertical direction. - @note only non-zero with D3D9 - */ - virtual Real getVerticalTexelOffset(void) { return 0.0f; } - - /** Gets the minimum (closest) depth value to be used when rendering - using identity transforms. - - When using identity transforms you can manually set the depth - of a vertex; however the input values required differ per - rendersystem. This method lets you retrieve the correct value. - @see Renderable::getUseIdentityView, Renderable::getUseIdentityProjection - */ - virtual Real getMinimumDepthInputValue(void) = 0; - /** Gets the maximum (farthest) depth value to be used when rendering - using identity transforms. - - When using identity transforms you can manually set the depth - of a vertex; however the input values required differ per - rendersystem. This method lets you retrieve the correct value. - @see Renderable::getUseIdentityView, Renderable::getUseIdentityProjection - */ - virtual Real getMaximumDepthInputValue(void) = 0; - /** set the current multi pass count value. This must be set prior to - calling _render() if multiple renderings of the same pass state are - required. - @param count Number of times to render the current state. - */ - virtual void setCurrentPassIterationCount(const size_t count) { mCurrentPassIterationCount = count; } - - /** Tell the render system whether to derive a depth bias on its own based on - the values passed to it in setCurrentPassIterationCount. - The depth bias set will be baseValue + iteration * multiplier - @param derive True to tell the RS to derive this automatically - @param baseValue The base value to which the multiplier should be - added - @param multiplier The amount of depth bias to apply per iteration - @param slopeScale The constant slope scale bias for completeness - */ - void setDeriveDepthBias(bool derive, float baseValue = 0.0f, - float multiplier = 0.0f, float slopeScale = 0.0f) - { - mDerivedDepthBias = derive; - mDerivedDepthBiasBase = baseValue; - mDerivedDepthBiasMultiplier = multiplier; - mDerivedDepthBiasSlopeScale = slopeScale; - } - - /** - * Set current render target to target, enabling its device context if needed - */ - virtual void _setRenderTarget(RenderTarget *target) = 0; - - /** Defines a listener on the custom events that this render system - can raise. - @see RenderSystem::addListener - */ - class _OgreExport Listener - { - public: - Listener() {} - virtual ~Listener() {} - - /** A rendersystem-specific event occurred. - @param eventName The name of the event which has occurred - @param parameters A list of parameters that may belong to this event, - may be null if there are no parameters - */ - virtual void eventOccurred(const String& eventName, - const NameValuePairList* parameters = 0) = 0; - }; - - /** Sets shared listener. - - Shared listener could be set even if no render system is selected yet. - This listener will receive "RenderSystemChanged" event on each Root::setRenderSystem call. - */ - static void setSharedListener(Listener* listener); - /** Retrieve a pointer to the current shared render system listener. */ - static Listener* getSharedListener(void); - - /** Adds a listener to the custom events that this render system can raise. - - Some render systems have quite specific, internally generated events - that the application may wish to be notified of. Many applications - don't have to worry about these events, and can just trust OGRE to - handle them, but if you want to know, you can add a listener here. - @par - Events are raised very generically by string name. Perhaps the most - common example of a render system specific event is the loss and - restoration of a device in DirectX; which OGRE deals with, but you - may wish to know when it happens. - @see RenderSystem::getRenderSystemEvents - */ - void addListener(Listener* l); - /** Remove a listener to the custom events that this render system can raise. - */ - void removeListener(Listener* l); - - /** Gets a list of the rendersystem specific events that this rendersystem - can raise. - @see RenderSystem::addListener - */ - const StringVector& getRenderSystemEvents(void) const { return mEventNames; } - - /** Tell the rendersystem to perform any prep tasks it needs to directly - before other threads which might access the rendering API are registered. - - Call this from your main thread before starting your other threads. - @note - If you start your own threads, there is a specific startup sequence which - must be respected and requires synchronisation between the threads: - - @note - 1. [Main thread] Call preExtraThreadsStarted() - 2. [Main thread] Start other thread, wait - 3. [Other thread] Call registerThread(), notify main thread & continue - 4. [Main thread] Wake up & call postExtraThreadsStarted() - - @note - Once this init sequence is completed the threads are independent but - this startup sequence must be respected. - */ - virtual void preExtraThreadsStarted() {} - - /** Tell the rendersystem to perform any tasks it needs to directly - after other threads which might access the rendering API are registered. - @see RenderSystem::preExtraThreadsStarted - */ - virtual void postExtraThreadsStarted() {} - - /** Register the an additional thread which may make calls to rendersystem-related - objects. - - This method should only be called by additional threads during their - initialisation. If they intend to use hardware rendering system resources - they should call this method before doing anything related to the render system. - Some rendering APIs require a per-thread setup and this method will sort that - out. It is also necessary to call unregisterThread before the thread shuts down. - @note - This method takes no parameters - it must be called from the thread being - registered and that context is enough. - */ - virtual void registerThread() {} - - /** Unregister an additional thread which may make calls to rendersystem-related objects. - @see RenderSystem::registerThread - */ - virtual void unregisterThread() {} - - /** - * This marks the beginning of an event for GPU profiling. - */ - virtual void beginProfileEvent( const String &eventName ) = 0; - - /** - * Ends the currently active GPU profiling event. - */ - virtual void endProfileEvent( void ) = 0; - - /** - * Marks an instantaneous event for graphics profilers. - * This is equivalent to calling @see beginProfileEvent and @see endProfileEvent back to back. - */ - virtual void markProfileEvent( const String &event ) = 0; - - /** Gets a custom (maybe platform-specific) attribute. - @remarks This is a nasty way of satisfying any API's need to see platform-specific details. - @param name The name of the attribute. - @param pData Pointer to memory of the right kind of structure to receive the info. - */ - virtual void getCustomAttribute(const String& name, void* pData); - - /** - * Sets the colour buffer that the render system will to draw. If the render system - * implementation or configuration does not support a particular value, then false will be - * returned and the current colour buffer value will not be modified. - * - * @param - * colourBuffer Specifies the colour buffer that will be drawn into. - */ - virtual bool setDrawBuffer(ColourBufferType colourBuffer) { return false; }; - - protected: - - /** DepthBuffers to be attached to render targets */ - DepthBufferMap mDepthBufferPool; - - /** The render targets. */ - RenderTargetMap mRenderTargets; - /** The render targets, ordered by priority. */ - RenderTargetPriorityMap mPrioritisedRenderTargets; - /** The Active render target. */ - RenderTarget * mActiveRenderTarget; - - /** The Active GPU programs and gpu program parameters*/ - GpuProgramParametersPtr mActiveParameters[GPT_COUNT]; - - // Texture manager - // A concrete class of this will be created and - // made available under the TextureManager singleton, - // managed by the RenderSystem - TextureManager* mTextureManager; - - // Active viewport (dest for future rendering operations) - Viewport* mActiveViewport; - - CullingMode mCullingMode; - - size_t mBatchCount; - size_t mFaceCount; - size_t mVertexCount; - - bool mInvertVertexWinding; - bool mIsReverseDepthBufferEnabled; - - /// Texture units from this upwards are disabled - size_t mDisabledTexUnitsFrom; - - /// number of times to render the current state - size_t mCurrentPassIterationCount; - size_t mCurrentPassIterationNum; - /// Whether to update the depth bias per render call - bool mDerivedDepthBias; - float mDerivedDepthBiasBase; - float mDerivedDepthBiasMultiplier; - float mDerivedDepthBiasSlopeScale; - - /** updates pass iteration rendering state including bound gpu program parameter - pass iteration auto constant entry - @return True if more iterations are required - */ - bool updatePassIterationRenderState(void); - - /// List of names of events this rendersystem may raise - StringVector mEventNames; - - /// Internal method for firing a rendersystem event - void fireEvent(const String& name, const NameValuePairList* params = 0); - - typedef std::list ListenerList; - ListenerList mEventListeners; - static Listener* msSharedEventListener; - - typedef std::list HardwareOcclusionQueryList; - HardwareOcclusionQueryList mHwOcclusionQueries; - - std::array mProgramBound; - - // Recording user clip planes - PlaneList mClipPlanes; - // Indicator that we need to re-set the clip planes on next render call - bool mClipPlanesDirty; - - /// Used to store the capabilities of the graphics card - RenderSystemCapabilities* mRealCapabilities; - RenderSystemCapabilities* mCurrentCapabilities; - bool mUseCustomCapabilities; - - /// @deprecated only needed for fixed function APIs - virtual void setClipPlanesImpl(const PlaneList& clipPlanes) {} - - /** Query the real capabilities of the GPU and driver in the RenderSystem*/ - virtual RenderSystemCapabilities* createRenderSystemCapabilities() const = 0; - - /** Initialize the render system from the capabilities*/ - virtual void initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary) = 0; - - - DriverVersion mDriverVersion; - uint16 mNativeShadingLanguageVersion; - - bool mTexProjRelative; - Vector3 mTexProjRelativeOrigin; - - // Stored options - ConfigOptionMap mOptions; - - virtual void initConfigOptions(); - - ColourBlendState mCurrentBlend; - GpuProgramParametersSharedPtr mFixedFunctionParams; - - void initFixedFunctionParams(); - void setFFPLightParams(uint32 index, bool enabled); - bool flipFrontFace() const; - static CompareFunction reverseCompareFunction(CompareFunction func); - private: - StencilState mStencilState; - - /// a global vertex buffer for global instancing - HardwareVertexBufferSharedPtr mGlobalInstanceVertexBuffer; - /// a vertex declaration for the global vertex buffer for the global instancing - VertexDeclaration* mGlobalInstanceVertexDeclaration; - /// the number of global instances (this number will be multiply by the render op instance number) - uint32 mGlobalNumberOfInstances; - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreRenderSystemCapabilities.h b/OgreMain/include/OgreRenderSystemCapabilities.h deleted file mode 100644 index 7f6b5415df4..00000000000 --- a/OgreMain/include/OgreRenderSystemCapabilities.h +++ /dev/null @@ -1,637 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __RenderSystemCapabilities__ -#define __RenderSystemCapabilities__ - -// Precompiler options -#include "OgrePrerequisites.h" -#include "OgreStringVector.h" -#include "OgreStringConverter.h" -#include "OgreHeaderPrefix.h" -#include "OgreGpuProgram.h" - -// Because there are more than 32 possible Capabilities, more than 1 int is needed to store them all. -// In fact, an array of integers is used to store capabilities. However all the capabilities are defined in the single -// enum. The only way to know which capabilities should be stored where in the array is to use some of the 32 bits -// to record the category of the capability. These top few bits are used as an index into mCapabilities array -// The lower bits are used to identify each capability individually by setting 1 bit for each - -// Identifies how many bits are reserved for categories -// NOTE: Although 4 bits (currently) are enough -#define CAPS_CATEGORY_SIZE 4 -#define OGRE_CAPS_BITSHIFT (32 - CAPS_CATEGORY_SIZE) -#define CAPS_CATEGORY_MASK (((1 << CAPS_CATEGORY_SIZE) - 1) << OGRE_CAPS_BITSHIFT) -#define OGRE_CAPS_VALUE(cat, val) ((cat << OGRE_CAPS_BITSHIFT) | (1 << val)) - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - - /// Enumerates the categories of capabilities - enum CapabilitiesCategory - { - CAPS_CATEGORY_COMMON = 0, - CAPS_CATEGORY_COMMON_2 = 1, - CAPS_CATEGORY_D3D9 = 2, - CAPS_CATEGORY_GL = 3, - CAPS_CATEGORY_COMMON_3 = 4, - /// Placeholder for max value - CAPS_CATEGORY_COUNT = 5 - }; - - /// Enum describing the different hardware capabilities we want to check for - /// OGRE_CAPS_VALUE(a, b) defines each capability - /// a is the category (which can be from 0 to 15) - /// b is the value (from 0 to 27) - enum Capabilities - { - /// specifying a "-1" in the index buffer starts a new draw command. - RSC_PRIMITIVE_RESTART = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 0), - /// GL ES2/ES3 does not support generating mipmaps for compressed formats in hardware - RSC_AUTOMIPMAP_COMPRESSED = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 1), - /// Supports anisotropic texture filtering - RSC_ANISOTROPY = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 2), - /// Supports depth clamping - RSC_DEPTH_CLAMP = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 3), - /// Supports linewidth != 1.0 - RSC_WIDE_LINES = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 4), - /// Supports hardware stencil buffer - RSC_HWSTENCIL = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 5), - /// Supports read/write buffers with atomic counters (e.g. RWStructuredBuffer or SSBO) - RSC_READ_WRITE_BUFFERS = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 6), - /// Supports compressed textures in the ASTC format - RSC_TEXTURE_COMPRESSION_ASTC = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 7), - /// Supports 32bit hardware index buffers - RSC_32BIT_INDEX = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 8), - /// Supports vertex programs (vertex shaders) - /// @deprecated All targeted APIs by Ogre support this feature - RSC_VERTEX_PROGRAM = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 9), - /// Supports hardware tessellation domain programs - RSC_TESSELLATION_DOMAIN_PROGRAM = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 10), - /// Supports 2D Texture Arrays - RSC_TEXTURE_2D_ARRAY = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 11), - /// Supports separate stencil updates for both front and back faces - RSC_TWO_SIDED_STENCIL = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 12), - /// Supports wrapping the stencil value at the range extremeties - RSC_STENCIL_WRAP = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 13), - /// Supports hardware occlusion queries - RSC_HWOCCLUSION = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 14), - /// Supports user clipping planes - RSC_USER_CLIP_PLANES = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 15), - /// Supports hardware compute programs - RSC_COMPUTE_PROGRAM = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 16), - /// Supports 1d textures - RSC_TEXTURE_1D = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 17), - /// Supports hardware render-to-texture (bigger than framebuffer) - RSC_HWRENDER_TO_TEXTURE = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 18), - /// Supports float textures and render targets - RSC_TEXTURE_FLOAT = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 19), - /// Supports non-power of two textures - RSC_NON_POWER_OF_2_TEXTURES = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 20), - /// Supports 3d (volume) textures - RSC_TEXTURE_3D = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 21), - /// Supports basic point sprite rendering - RSC_POINT_SPRITES = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 22), - /// @deprecated same as RSC_POINT_SPRITES - RSC_POINT_EXTENDED_PARAMETERS = RSC_POINT_SPRITES, - /// Supports rendering to vertex buffers - RSC_HWRENDER_TO_VERTEX_BUFFER = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 23), - /// Supports vertex texture fetch - RSC_VERTEX_TEXTURE_FETCH = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 24), - /// Supports mipmap LOD biasing - RSC_MIPMAP_LOD_BIAS = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 25), - /// Supports hardware geometry programs - RSC_GEOMETRY_PROGRAM = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON, 26), - - /// Supports compressed textures - RSC_TEXTURE_COMPRESSION = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON_2, 0), - /// Supports compressed textures in the DXT/ST3C formats - RSC_TEXTURE_COMPRESSION_DXT = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON_2, 1), - /// Supports compressed textures in the VTC format - RSC_TEXTURE_COMPRESSION_VTC = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON_2, 2), - /// Supports compressed textures in the PVRTC format - RSC_TEXTURE_COMPRESSION_PVRTC = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON_2, 3), - /// Supports compressed textures in the ATC format - RSC_TEXTURE_COMPRESSION_ATC = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON_2, 4), - /// Supports compressed textures in the ETC1 format - RSC_TEXTURE_COMPRESSION_ETC1 = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON_2, 5), - /// Supports compressed textures in the ETC2 format - RSC_TEXTURE_COMPRESSION_ETC2 = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON_2, 6), - /// Supports compressed textures in BC4 and BC5 format (DirectX feature level 10_0) - RSC_TEXTURE_COMPRESSION_BC4_BC5 = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON_2, 7), - /// Supports compressed textures in BC6H and BC7 format (DirectX feature level 11_0) - RSC_TEXTURE_COMPRESSION_BC6H_BC7 = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON_2, 8), - /// Supports fixed-function pipeline - RSC_FIXED_FUNCTION = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON_2, 9), - /// Supports #VET_INT_10_10_10_2_NORM - RSC_VERTEX_FORMAT_INT_10_10_10_2 = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON_2, 10), - /// Supports Alpha to Coverage (A2C) - RSC_ALPHA_TO_COVERAGE = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON_2, 11), - /// Supports reading back compiled shaders - RSC_CAN_GET_COMPILED_SHADER_BUFFER = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON_2, 12), - /// Supports HW gamma, both in the framebuffer and as texture. - RSC_HW_GAMMA = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON_2, 13), - /// Supports using the MAIN depth buffer for RTTs. D3D 9&10, OGL w/FBO support unknown - /// (undefined behavior?), OGL w/ copy supports it - RSC_RTT_MAIN_DEPTHBUFFER_ATTACHABLE = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON_2, 14), - /// Supports attaching a depth buffer to an RTT that has width & height less or equal than RTT's. - /// Otherwise must be of _exact_ same resolution. D3D 9, OGL 3.0 (not 2.0, not D3D10) - RSC_RTT_DEPTHBUFFER_RESOLUTION_LESSEQUAL = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON_2, 15), - /// Supports using vertex buffers for instance data - RSC_VERTEX_BUFFER_INSTANCE_DATA = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON_2, 16), - /// Supports hardware tessellation hull programs - RSC_TESSELLATION_HULL_PROGRAM = OGRE_CAPS_VALUE(CAPS_CATEGORY_COMMON_2, 17), - - // ***** DirectX specific caps ***** - /// Is DirectX feature "per stage constants" supported - RSC_PERSTAGECONSTANT = OGRE_CAPS_VALUE(CAPS_CATEGORY_D3D9, 0), - /// D3D11: supports reading back the inactive depth-stencil buffer as texture - RSC_READ_BACK_AS_TEXTURE = OGRE_CAPS_VALUE(CAPS_CATEGORY_D3D9, 1), - /// the renderer will try to use W-buffers when available - /// W-buffers are enabled by default for 16bit depth buffers and disabled for all other - /// depths. - RSC_WBUFFER = OGRE_CAPS_VALUE(CAPS_CATEGORY_D3D9, 2), - /// D3D11: Supports asynchronous hardware occlusion queries - RSC_HWOCCLUSION_ASYNCHRONOUS = OGRE_CAPS_VALUE(CAPS_CATEGORY_D3D9, 3), - RSC_HWRENDER_TO_TEXTURE_3D = OGRE_CAPS_VALUE(CAPS_CATEGORY_D3D9, 4), - /// All MRTs must have same bit depths - RSC_MRT_SAME_BIT_DEPTHS = OGRE_CAPS_VALUE(CAPS_CATEGORY_D3D9, 5), - - // ***** GL Specific Caps ***** - /// Support for PBuffer - RSC_PBUFFER = OGRE_CAPS_VALUE(CAPS_CATEGORY_GL, 0), - /// Support for Separate Shader Objects - RSC_SEPARATE_SHADER_OBJECTS = OGRE_CAPS_VALUE(CAPS_CATEGORY_GL, 1), - /// Support for Vertex Array Objects (VAOs) - RSC_VAO = OGRE_CAPS_VALUE(CAPS_CATEGORY_GL, 2), - /// with Separate Shader Objects the gl_PerVertex interface block must be redeclared - /// but some drivers misbehave and do not compile if we do so - RSC_GLSL_SSO_REDECLARE = OGRE_CAPS_VALUE(CAPS_CATEGORY_GL, 3), - /// Supports debugging/ profiling events - RSC_DEBUG = OGRE_CAPS_VALUE(CAPS_CATEGORY_GL, 4), - /// RS can map driver buffer storage directly instead of using a shadow buffer - RSC_MAPBUFFER = OGRE_CAPS_VALUE(CAPS_CATEGORY_GL, 5), - - // deprecated caps, all aliasing to RSC_VERTEX_PROGRAM - /// @deprecated assume present - RSC_INFINITE_FAR_PLANE = RSC_VERTEX_PROGRAM, - /// @deprecated assume present - RSC_FRAGMENT_PROGRAM = RSC_VERTEX_PROGRAM - }; - - /// DriverVersion is used by RenderSystemCapabilities and both GL and D3D9 - /// to store the version of the current GPU driver - struct _OgreExport DriverVersion - { - int major; - int minor; - int release; - int build; - - DriverVersion() - { - major = minor = release = build = 0; - } - - String toString() const; - void fromString(const String& versionString); - }; - - /** Enumeration of GPU vendors. */ - enum GPUVendor - { - GPU_UNKNOWN = 0, - GPU_NVIDIA, - GPU_AMD, - GPU_INTEL, - GPU_IMAGINATION_TECHNOLOGIES, - GPU_APPLE, //!< Apple Software Renderer - GPU_NOKIA, - GPU_MS_SOFTWARE, //!< Microsoft software device - GPU_MS_WARP, //!< Microsoft WARP (Windows Advanced Rasterization Platform) software device - http://msdn.microsoft.com/en-us/library/dd285359.aspx - GPU_ARM, //!< For the Mali chipsets - GPU_QUALCOMM, - GPU_MOZILLA, //!< WebGL on Mozilla/Firefox based browser - GPU_WEBKIT, //!< WebGL on WebKit/Chrome base browser - /// placeholder - GPU_VENDOR_COUNT - }; - - /** This class stores the capabilities of the graphics card. - - This information is set by the individual render systems. - */ - class _OgreExport RenderSystemCapabilities : public RenderSysAlloc - { - - public: - - typedef std::set ShaderProfiles; - private: - /// This is used to build a database of RSC's - /// if a RSC with same name, but newer version is introduced, the older one - /// will be removed - DriverVersion mDriverVersion; - /// GPU Vendor - GPUVendor mVendor; - - static String msGPUVendorStrings[GPU_VENDOR_COUNT]; - static void initVendorStrings(); - - /// The number of texture units available - ushort mNumTextureUnits; - /// The stencil buffer bit depth - ushort mStencilBufferBitDepth; - /// Stores the capabilities flags. - int mCapabilities[CAPS_CATEGORY_COUNT]; - /// Which categories are relevant - bool mCategoryRelevant[CAPS_CATEGORY_COUNT]; - /// The name of the device as reported by the render system - String mDeviceName; - /// The identifier associated with the render system for which these capabilities are valid - String mRenderSystemName; - - /// The number of floating-point 4-vector constants - ushort mConstantFloatCount[GPT_COUNT]; - /// The number of simultaneous render targets supported - ushort mNumMultiRenderTargets; - /// The maximum point size - Real mMaxPointSize; - /// Are non-POW2 textures feature-limited? - bool mNonPOW2TexturesLimited; - /// The maximum supported anisotropy - Real mMaxSupportedAnisotropy; - /// The number of vertex texture units supported - ushort mNumVertexTextureUnits; - /// The number of vertices a geometry program can emit in a single run - int mGeometryProgramNumOutputVertices; - - /// The list of supported shader profiles - ShaderProfiles mSupportedShaderProfiles; - - /// The number of vertex attributes available - ushort mNumVertexAttributes; - public: - RenderSystemCapabilities (); - - /** Set the driver version. */ - void setDriverVersion(const DriverVersion& version) - { - mDriverVersion = version; - } - - void parseDriverVersionFromString(const String& versionString) - { - DriverVersion version; - version.fromString(versionString); - setDriverVersion(version); - } - - - DriverVersion getDriverVersion() const - { - return mDriverVersion; - } - - GPUVendor getVendor() const - { - return mVendor; - } - - void setVendor(GPUVendor v) - { - mVendor = v; - } - - /// Parse and set vendor - void parseVendorFromString(const String& vendorString) - { - setVendor(vendorFromString(vendorString)); - } - - /// Convert a vendor string to an enum - static GPUVendor vendorFromString(const String& vendorString); - /// Convert a vendor enum to a string - static const String& vendorToString(GPUVendor v); - - bool isDriverOlderThanVersion(const DriverVersion &v) const - { - if (mDriverVersion.major < v.major) - return true; - else if (mDriverVersion.major == v.major && - mDriverVersion.minor < v.minor) - return true; - else if (mDriverVersion.major == v.major && - mDriverVersion.minor == v.minor && - mDriverVersion.release < v.release) - return true; - else if (mDriverVersion.major == v.major && - mDriverVersion.minor == v.minor && - mDriverVersion.release == v.release && - mDriverVersion.build < v.build) - return true; - return false; - } - - void setNumTextureUnits(ushort num) - { - mNumTextureUnits = num; - } - - /// @deprecated do not use - void setStencilBufferBitDepth(ushort num) - { - mStencilBufferBitDepth = num; - } - - /// The number of simultaneous render targets supported - void setNumMultiRenderTargets(ushort num) - { - mNumMultiRenderTargets = num; - } - - void setNumVertexAttributes(ushort num) - { - mNumVertexAttributes = num; - } - - ushort getNumVertexAttributes(void) const - { - return mNumVertexAttributes; - } - - /** Returns the number of texture units the current output hardware - supports. - - For use in rendering, this determines how many texture units the - are available for multitexturing (i.e. rendering multiple - textures in a single pass). Where a Material has multiple - texture layers, it will try to use multitexturing where - available, and where it is not available, will perform multipass - rendering to achieve the same effect. This property only applies - to the fixed-function pipeline, the number available to the - programmable pipeline depends on the shader model in use. - */ - ushort getNumTextureUnits(void) const - { - return mNumTextureUnits; - } - - /// @deprecated assume 8-bit stencil buffer - ushort getStencilBufferBitDepth(void) const - { - return mStencilBufferBitDepth; - } - - /// The number of simultaneous render targets supported - ushort getNumMultiRenderTargets(void) const - { - return mNumMultiRenderTargets; - } - - /** Returns true if capability is render system specific - */ - bool isCapabilityRenderSystemSpecific(const Capabilities c) const - { - int cat = c >> OGRE_CAPS_BITSHIFT; - if(cat == CAPS_CATEGORY_GL || cat == CAPS_CATEGORY_D3D9) - return true; - return false; - } - - /** Adds a capability flag - */ - void setCapability(const Capabilities c) - { - int index = (CAPS_CATEGORY_MASK & c) >> OGRE_CAPS_BITSHIFT; - // zero out the index from the stored capability - mCapabilities[index] |= (c & ~CAPS_CATEGORY_MASK); - } - - /** Remove a capability flag - */ - void unsetCapability(const Capabilities c) - { - int index = (CAPS_CATEGORY_MASK & c) >> OGRE_CAPS_BITSHIFT; - // zero out the index from the stored capability - mCapabilities[index] &= (~c | CAPS_CATEGORY_MASK); - } - - /** Checks for a capability - */ - bool hasCapability(const Capabilities c) const - { - int index = (CAPS_CATEGORY_MASK & c) >> OGRE_CAPS_BITSHIFT; - // test against - if(mCapabilities[index] & (c & ~CAPS_CATEGORY_MASK)) - { - return true; - } - else - { - return false; - } - } - - /** Adds the profile to the list of supported profiles - */ - void addShaderProfile(const String& profile); - - /** Remove a given shader profile, if present. - */ - void removeShaderProfile(const String& profile); - - /** Returns true if profile is in the list of supported profiles - */ - bool isShaderProfileSupported(const String& profile) const; - - /** Returns a set of all supported shader profiles - * */ - const ShaderProfiles& getSupportedShaderProfiles() const - { - return mSupportedShaderProfiles; - } - - - /// The number of floating-point 4-vector constants vertex programs support - ushort getConstantFloatCount(GpuProgramType programType) const - { - return mConstantFloatCount[programType]; - } - - /// sets the device name for Render system - void setDeviceName(const String& name) - { - mDeviceName = name; - } - - /// gets the device name for render system - String getDeviceName() const - { - return mDeviceName; - } - - /// The number of floating-point 4-vector constants vertex programs support - void setVertexProgramConstantFloatCount(ushort c) - { - mConstantFloatCount[GPT_VERTEX_PROGRAM] = c; - } - /// The number of floating-point 4-vector constants geometry programs support - void setGeometryProgramConstantFloatCount(ushort c) - { - mConstantFloatCount[GPT_GEOMETRY_PROGRAM] = c; - } - /// The number of floating-point 4-vector constants fragment programs support - void setFragmentProgramConstantFloatCount(ushort c) - { - mConstantFloatCount[GPT_FRAGMENT_PROGRAM] = c; - } - - /// Maximum point screen size in pixels - void setMaxPointSize(Real s) - { - mMaxPointSize = s; - } - /// Maximum point screen size in pixels - Real getMaxPointSize(void) const - { - return mMaxPointSize; - } - /// Non-POW2 textures limited - void setNonPOW2TexturesLimited(bool l) - { - mNonPOW2TexturesLimited = l; - } - /** Are non-power of two textures limited in features? - - If the RSC_NON_POWER_OF_2_TEXTURES capability is set, but this - method returns true, you can use non power of 2 textures only if: -
  • You load them explicitly with no mip maps
  • -
  • You don't use DXT texture compression
  • -
  • You use clamp texture addressing
- */ - bool getNonPOW2TexturesLimited(void) const - { - return mNonPOW2TexturesLimited; - } - /// Set the maximum supported anisotropic filtering - void setMaxSupportedAnisotropy(Real s) - { - mMaxSupportedAnisotropy = s; - } - /// Get the maximum supported anisotropic filtering - Real getMaxSupportedAnisotropy() const - { - return mMaxSupportedAnisotropy; - } - - /// Set the number of vertex texture units supported - void setNumVertexTextureUnits(ushort n) - { - mNumVertexTextureUnits = n; - } - /// Get the number of vertex texture units supported - ushort getNumVertexTextureUnits(void) const - { - return mNumVertexTextureUnits; - } - - /// Set the number of vertices a single geometry program run can emit - void setGeometryProgramNumOutputVertices(int numOutputVertices) - { - mGeometryProgramNumOutputVertices = numOutputVertices; - } - /// Get the number of vertices a single geometry program run can emit - int getGeometryProgramNumOutputVertices(void) const - { - return mGeometryProgramNumOutputVertices; - } - - /// Get the identifier of the rendersystem from which these capabilities were generated - const String& getRenderSystemName(void) const - { - return mRenderSystemName; - } - /// Set the identifier of the rendersystem from which these capabilities were generated - void setRenderSystemName(const String& rs) - { - mRenderSystemName = rs; - } - - /// Mark a category as 'relevant' or not, ie will it be reported - void setCategoryRelevant(CapabilitiesCategory cat, bool relevant) - { - mCategoryRelevant[cat] = relevant; - } - - /// Return whether a category is 'relevant' or not, ie will it be reported - bool isCategoryRelevant(CapabilitiesCategory cat) - { - return mCategoryRelevant[cat]; - } - - - - /** Write the capabilities to the pass in Log */ - void log(Log* pLog) const; - - /// The number of floating-point 4-vector constants compute programs support - void setComputeProgramConstantFloatCount(ushort c) - { - mConstantFloatCount[GPT_COMPUTE_PROGRAM] = c; - } - /// The number of floating-point 4-vector constants tessellation Domain programs support - void setTessellationDomainProgramConstantFloatCount(ushort c) - { - mConstantFloatCount[GPT_DOMAIN_PROGRAM] = c; - } - /// The number of floating-point 4-vector constants tessellation Hull programs support - void setTessellationHullProgramConstantFloatCount(ushort c) - { - mConstantFloatCount[GPT_HULL_PROGRAM] = c; - } - - }; - - inline String to_string(GPUVendor v) { return RenderSystemCapabilities::vendorToString(v); } - inline String to_string(const DriverVersion& v) { return v.toString(); } - - /** @} */ - /** @} */ -} // namespace - - -#include "OgreHeaderSuffix.h" - -#endif // __RenderSystemCapabilities__ - diff --git a/OgreMain/include/OgreRenderSystemCapabilitiesManager.h b/OgreMain/include/OgreRenderSystemCapabilitiesManager.h deleted file mode 100644 index c0f03be5a4d..00000000000 --- a/OgreMain/include/OgreRenderSystemCapabilitiesManager.h +++ /dev/null @@ -1,106 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __RENDERSYSTEMCAPABILITIESMANAGER_H__ -#define __RENDERSYSTEMCAPABILITIESMANAGER_H__ - -#include "OgrePrerequisites.h" -#include "OgreSingleton.h" -#include "OgreHeaderPrefix.h" - - -namespace Ogre { - - - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - /** Class for managing RenderSystemCapabilities database for Ogre. - @remarks This class behaves similarly to other ResourceManager, although .rendercaps are not resources. - It contains and abstract a .rendercaps Serializer - */ - class _OgreExport RenderSystemCapabilitiesManager : public Singleton, public RenderSysAlloc - { - - public: - - /** Default constructor. - */ - RenderSystemCapabilitiesManager(); - - /** Default destructor. - */ - ~RenderSystemCapabilitiesManager(); - - /** loads a custom capabilites config file - * - * use with @ref Root::useCustomRenderSystemCapabilities - * @return the configured RenderSystemCapabilities - */ - RenderSystemCapabilities* loadCapabilitiesConfig(const String& filename); - - /** @see ScriptLoader::parseScript - */ - void parseCapabilitiesFromArchive(const String& filename, const String& archiveType, bool recursive = true); - - /** Returns a capability loaded with RenderSystemCapabilitiesManager::parseCapabilitiesFromArchive method - * @return NULL if the name is invalid, a parsed RenderSystemCapabilities otherwise. - */ - RenderSystemCapabilities* loadParsedCapabilities(const String& name); - - /** Access to the internal map of loaded capabilities */ - const std::map &getCapabilities() const; - - /** Method used by RenderSystemCapabilitiesSerializer::parseScript */ - void _addRenderSystemCapabilities(const String& name, RenderSystemCapabilities* caps); - - /// @copydoc Singleton::getSingleton() - static RenderSystemCapabilitiesManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static RenderSystemCapabilitiesManager* getSingletonPtr(void); - - private: - - RenderSystemCapabilitiesSerializer* mSerializer; - - typedef std::map CapabilitiesMap; - CapabilitiesMap mCapabilitiesMap; - - const String mScriptPattern; - - }; - - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreRenderSystemCapabilitiesSerializer.h b/OgreMain/include/OgreRenderSystemCapabilitiesSerializer.h deleted file mode 100644 index fba958312ed..00000000000 --- a/OgreMain/include/OgreRenderSystemCapabilitiesSerializer.h +++ /dev/null @@ -1,245 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __RenderSystemCapabilitiesSerializer_H__ -#define __RenderSystemCapabilitiesSerializer_H__ - -#include "OgrePrerequisites.h" -#include "OgreRenderSystemCapabilities.h" -#include "OgreHeaderPrefix.h" - - -namespace Ogre { - - - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - /** Class for serializing RenderSystemCapabilities to / from a .rendercaps script.*/ - class _OgreExport RenderSystemCapabilitiesSerializer : public RenderSysAlloc - { - - public: - /** default constructor*/ - RenderSystemCapabilitiesSerializer(); - - /** Writes a RenderSystemCapabilities object to a data stream */ - void writeScript(const RenderSystemCapabilities* caps, const String &name, const String& filename); - - /** Writes a RenderSystemCapabilities object to a string */ - String writeString(const RenderSystemCapabilities* caps, const String &name); - - /** Parses a RenderSystemCapabilities script file passed as a stream. - Adds it to RenderSystemCapabilitiesManager::_addRenderSystemCapabilities - */ - void parseScript(DataStreamPtr& stream); - - private: - void write(const RenderSystemCapabilities* caps, const String &name, std::ostream &file); - - enum CapabilityKeywordType {UNDEFINED_CAPABILITY_TYPE = 0, SET_STRING_METHOD, SET_INT_METHOD, SET_BOOL_METHOD, SET_REAL_METHOD, - SET_CAPABILITY_ENUM_BOOL, ADD_SHADER_PROFILE_STRING}; - // determines what keyword is what type of capability. For example: - // "automipmap" and "pbuffer" are both activated with setCapability (passing RSC_AUTOMIPMAP and RSC_PBUFFER respectivelly) - // while "max_num_multi_render_targets" is an integer and has it's own method: setMaxMultiNumRenderTargets - // we need to know these types to automatically parse each capability - typedef std::map KeywordTypeMap; - KeywordTypeMap mKeywordTypeMap; - - typedef void (RenderSystemCapabilities::*SetStringMethod)(const String&); - // maps capability keywords to setCapability(String& cap) style methods - typedef std::map SetStringMethodDispatchTable; - SetStringMethodDispatchTable mSetStringMethodDispatchTable; - - // SET_INT_METHOD parsing tables - typedef void (RenderSystemCapabilities::*SetIntMethod)(ushort); - typedef std::map SetIntMethodDispatchTable; - SetIntMethodDispatchTable mSetIntMethodDispatchTable; - - // SET_BOOL_METHOD parsing tables - typedef void (RenderSystemCapabilities::*SetBoolMethod)(bool); - typedef std::map SetBoolMethodDispatchTable; - SetBoolMethodDispatchTable mSetBoolMethodDispatchTable; - - // SET_REAL_METHOD parsing tables - typedef void (RenderSystemCapabilities::*SetRealMethod)(Real); - typedef std::map SetRealMethodDispatchTable; - SetRealMethodDispatchTable mSetRealMethodDispatchTable; - - typedef std::map CapabilitiesMap; - CapabilitiesMap mCapabilitiesMap; - - inline void addCapabilitiesMapping(const String& name, Capabilities cap) - { - mCapabilitiesMap.emplace(name, cap); - } - - - // capabilities lines for parsing are collected along with their line numbers for debugging - typedef std::vector > CapabilitiesLinesList; - // the set of states that the parser can be in - enum ParseAction {PARSE_HEADER, FIND_OPEN_BRACE, COLLECT_LINES}; - - int mCurrentLineNumber; - String* mCurrentLine; - DataStreamPtr mCurrentStream; - - RenderSystemCapabilities* mCurrentCapabilities; - - inline void addKeywordType(const String& keyword, CapabilityKeywordType type) - { - mKeywordTypeMap.emplace(keyword, type); - } - - CapabilityKeywordType getKeywordType(const String& keyword) const - { - KeywordTypeMap::const_iterator it = mKeywordTypeMap.find(keyword); - if (it != mKeywordTypeMap.end()) - return (*it).second; - - // default - return SET_CAPABILITY_ENUM_BOOL; - } - - inline void addSetStringMethod(const String& keyword, SetStringMethod method) - { - mSetStringMethodDispatchTable.emplace(keyword, method); - } - - inline void callSetStringMethod(String& keyword, String& val) - { - SetStringMethodDispatchTable::iterator methodIter = mSetStringMethodDispatchTable.find(keyword); - if (methodIter != mSetStringMethodDispatchTable.end()) - { - SetStringMethod m = (*methodIter).second; - (mCurrentCapabilities->*m)(val); - } - else - { - logParseError("undefined keyword: " + keyword); - } - } - - - inline void addSetIntMethod(const String& keyword, SetIntMethod method) - { - mSetIntMethodDispatchTable.emplace(keyword, method); - } - - inline void callSetIntMethod(String& keyword, ushort val) - { - SetIntMethodDispatchTable::iterator methodIter = mSetIntMethodDispatchTable.find(keyword); - if (methodIter != mSetIntMethodDispatchTable.end()) - { - SetIntMethod m = (*methodIter).second; - (mCurrentCapabilities->*m)(val); - } - else - { - logParseError("undefined keyword: " + keyword); - } - } - - - inline void addSetBoolMethod(const String& keyword, SetBoolMethod method) - { - mSetBoolMethodDispatchTable.emplace(keyword, method); - } - - inline void callSetBoolMethod(String& keyword, bool val) - { - SetBoolMethodDispatchTable::iterator methodIter = mSetBoolMethodDispatchTable.find(keyword); - if (methodIter != mSetBoolMethodDispatchTable.end()) - { - SetBoolMethod m = (*methodIter).second; - (mCurrentCapabilities->*m)(val); - } - else - { - logParseError("undefined keyword: " + keyword); - } - } - - - inline void addSetRealMethod(const String& keyword, SetRealMethod method) - { - mSetRealMethodDispatchTable.emplace(keyword, method); - } - - inline void callSetRealMethod(String& keyword, Real val) - { - SetRealMethodDispatchTable::iterator methodIter = mSetRealMethodDispatchTable.find(keyword); - if (methodIter != mSetRealMethodDispatchTable.end()) - { - SetRealMethod m = (*methodIter).second; - (mCurrentCapabilities->*m)(val); - } - else - { - logParseError("undefined keyword: " + keyword); - } - } - - inline void addShaderProfile(String& val) - { - mCurrentCapabilities->addShaderProfile(val); - } - - inline void setCapabilityEnumBool(String& name, bool val) - { - // check for errors - if(mCapabilitiesMap.find(name) == mCapabilitiesMap.end()) - { - logParseError("Undefined capability: " + name); - return; - } - // only set true capabilities, we can't unset false - if(val) - { - Capabilities cap = mCapabilitiesMap[name]; - mCurrentCapabilities->setCapability(cap); - } - } - - void initialiaseDispatchTables(); - - void parseCapabilitiesLines(CapabilitiesLinesList& linesList); - - void logParseError(const String& error) const; - - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreRenderTarget.h b/OgreMain/include/OgreRenderTarget.h deleted file mode 100644 index c3ccbd81763..00000000000 --- a/OgreMain/include/OgreRenderTarget.h +++ /dev/null @@ -1,500 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __RenderTarget_H__ -#define __RenderTarget_H__ - -#include "OgrePrerequisites.h" - -#include "OgrePixelFormat.h" -#include "OgreHeaderPrefix.h" - -/* Define the number of priority groups for the render system's render targets. */ -#ifndef OGRE_NUM_RENDERTARGET_GROUPS - #define OGRE_NUM_RENDERTARGET_GROUPS 10 - #define OGRE_DEFAULT_RT_GROUP 4 - #define OGRE_REND_TO_TEX_RT_GROUP 2 -#endif - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - /** A 'canvas' which can receive the results of a rendering - operation. - - This abstract class defines a common root to all targets of rendering operations. A - render target could be a window on a screen, or another - offscreen surface like a texture or bump map etc. - @author - Steven Streeting - @version - 1.0 - */ - class _OgreExport RenderTarget : public RenderSysAlloc - { - public: - struct FrameStats - { - /// frames per second (FPS) based on the frames rendered in the last second - float lastFPS; - /// average frames per second (FPS) since call to Root::startRendering - float avgFPS; - /// best frames per second (FPS) since call to Root::startRendering - float bestFPS; - /// worst frames per second (FPS) since call to Root::startRendering - float worstFPS; - unsigned long bestFrameTime; - unsigned long worstFrameTime; - /// number of triangles rendered in the last update() call. - size_t triangleCount; - /// number of batches rendered in the last update() call. - size_t batchCount; - int vBlankMissCount; // -1 means that the value is not applicable - }; - - enum FrameBuffer - { - FB_FRONT, - FB_BACK, - FB_AUTO - }; - - RenderTarget(); - virtual ~RenderTarget(); - - /// Retrieve target's name. - virtual const String& getName(void) const; - - /// Retrieve information about the render target. - void getMetrics(unsigned int& width, unsigned int& height); - - virtual uint32 getWidth(void) const; - virtual uint32 getHeight(void) const; - - /** - * Sets the pool ID this RenderTarget should query from. Default value is POOL_DEFAULT. - * Set to POOL_NO_DEPTH to avoid using a DepthBuffer (or manually controlling it) @see DepthBuffer - * Changing the pool Id will cause the current depth buffer to be detached unless the old - * id and the new one are the same - */ - void setDepthBufferPool( uint16 poolId ); - - //Returns the pool ID this RenderTarget should query from. @see DepthBuffer - uint16 getDepthBufferPool() const; - - DepthBuffer* getDepthBuffer() const; - - //Returns false if couldn't attach - virtual bool attachDepthBuffer( DepthBuffer *depthBuffer ); - - virtual void detachDepthBuffer(); - - /** Detaches DepthBuffer without notifying it from the detach. - Useful when called from the DepthBuffer while it iterates through attached - RenderTargets (@see DepthBuffer::_setPoolId()) - */ - virtual void _detachDepthBuffer(); - - /** Tells the target to update it's contents. - - If OGRE is not running in an automatic rendering loop - (started using Root::startRendering), - the user of the library is responsible for asking each render - target to refresh. This is the method used to do this. It automatically - re-renders the contents of the target using whatever cameras have been - pointed at it (using Camera::setRenderTarget). - @par - This allows OGRE to be used in multi-windowed utilities - and for contents to be refreshed only when required, rather than - constantly as with the automatic rendering loop. - @param swapBuffers For targets that support double-buffering, if set - to true, the target will immediately - swap it's buffers after update. Otherwise, the buffers are - not swapped, and you have to call swapBuffers yourself sometime - later. You might want to do this on some rendersystems which - pause for queued rendering commands to complete before accepting - swap buffers calls - so you could do other CPU tasks whilst the - queued commands complete. Or, you might do this if you want custom - control over your windows, such as for externally created windows. - */ - virtual void update(bool swapBuffers = true); - /** Swaps the frame buffers to display the next frame. - - For targets that are double-buffered so that no - 'in-progress' versions of the scene are displayed - during rendering. Once rendering has completed (to - an off-screen version of the window) the buffers - are swapped to display the new frame. - */ - virtual void swapBuffers() {} - - /** Adds a viewport to the rendering target. - - A viewport is the rectangle into which rendering output is sent. This method adds - a viewport to the render target, rendering from the supplied camera. The - rest of the parameters are only required if you wish to add more than one viewport - to a single rendering target. Note that size information passed to this method is - passed as a parametric, i.e. it is relative rather than absolute. This is to allow - viewports to automatically resize along with the target. - @param - cam The camera from which the viewport contents will be rendered (mandatory) - @param - ZOrder The relative order of the viewport with others on the target (allows overlapping - viewports i.e. picture-in-picture). Higher Z-orders are on top of lower ones. The actual number - is irrelevant, only the relative Z-order matters (you can leave gaps in the numbering) - @param - left The relative position of the left of the viewport on the target, as a value between 0 and 1. - @param - top The relative position of the top of the viewport on the target, as a value between 0 and 1. - @param - width The relative width of the viewport on the target, as a value between 0 and 1. - @param - height The relative height of the viewport on the target, as a value between 0 and 1. - */ - virtual Viewport* addViewport(Camera* cam, int ZOrder = 0, float left = 0.0f, float top = 0.0f , - float width = 1.0f, float height = 1.0f); - - /** Returns the number of viewports attached to this target.*/ - virtual unsigned short getNumViewports(void) const; - - /** Retrieves a pointer to the viewport with the given index. */ - virtual Viewport* getViewport(unsigned short index); - - /** Retrieves a pointer to the viewport with the given Z-order. - @remarks throws if not found. - */ - virtual Viewport* getViewportByZOrder(int ZOrder); - - /** Returns true if and only if a viewport exists at the given Z-order. */ - virtual bool hasViewportWithZOrder(int ZOrder); - - /** Removes a viewport at a given Z-order. - */ - virtual void removeViewport(int ZOrder); - - /** Removes all viewports on this target. - */ - virtual void removeAllViewports(void); - - /** Retrieves details of current rendering performance. */ - const FrameStats& getStatistics(void) const { - return mStats; - } - - /** Resets saved frame-rate statistices. - */ - void resetStatistics(void); - - /** Retrieve a platform or API-specific piece of information - - This method of retrieving information should only be used if you know what you're doing. - - | Name | Description | - |-------------|------------------------------------| - | WINDOW | The native window handle. (X11 Window XID/ HWND / NSWindow*) | - | HWND | deprecated (same as WINDOW) | - | GL_FBOID | the id of the OpenGL framebuffer object | - | GL_MULTISAMPLEFBOID | the id of the OpenGL framebuffer object used for multisampling | - | GLFBO | id of the screen OpenGL framebuffer object on iOS | - | GLCONTEXT | deprecated, do not use | - | FBO | deprecated, do not use | - | TARGET | deprecated, do not use | - | XDISPLAY | The X Display connection behind that context. | - | ATOM | The X Atom used in client delete events. | - | VIEW | Cocoa NSView* | - | NSOPENGLCONTEXT | Cocoa NSOpenGLContext* | - | NSOPENGLPIXELFORMAT | Cocoa NSOpenGLPixelFormat* | - - @param name The name of the attribute. - @param pData Pointer to memory of the right kind of structure to receive the info. - */ - virtual void getCustomAttribute(const String& name, void* pData); - - /** simplified API for bindings - * - * @overload - */ - uint getCustomAttribute(const String& name) - { - uint ret = 0; - getCustomAttribute(name, &ret); - return ret; - } - - /** Add a listener to this RenderTarget which will be called back before & after rendering. - - If you want notifications before and after a target is updated by the system, use - this method to register your own custom RenderTargetListener class. This is useful - for potentially adding your own manual rendering commands before and after the - 'normal' system rendering. - @par NB this should not be used for frame-based scene updates, use Root::addFrameListener for that. - */ - virtual void addListener(RenderTargetListener* listener); - /** same as addListener, but force the position in the vector, so we can control the call order */ - virtual void insertListener(RenderTargetListener* listener, const unsigned int pos = 0); - /** Removes a RenderTargetListener previously registered using addListener. */ - virtual void removeListener(RenderTargetListener* listener); - /** Removes all listeners from this instance. */ - virtual void removeAllListeners(void); - - /** Sets the priority of this render target in relation to the others. - - This can be used in order to schedule render target updates. Lower - priorities will be rendered first. Note that the priority must be set - at the time the render target is attached to the render system, changes - afterwards will not affect the ordering. - */ - virtual void setPriority( uchar priority ) { mPriority = priority; } - /** Gets the priority of a render target. */ - virtual uchar getPriority() const { return mPriority; } - - /** Used to retrieve or set the active state of the render target. - */ - virtual bool isActive() const; - - /** Used to set the active state of the render target. - */ - virtual void setActive( bool state ); - - /** Sets whether this target should be automatically updated if Ogre's rendering - loop or Root::_updateAllRenderTargets is being used. - - By default, if you use Ogre's own rendering loop (Root::startRendering) - or call Root::_updateAllRenderTargets, all render targets are updated - automatically. This method allows you to control that behaviour, if - for example you have a render target which you only want to update periodically. - @param autoupdate If true, the render target is updated during the automatic render - loop or when Root::_updateAllRenderTargets is called. If false, the - target is only updated when its update() method is called explicitly. - */ - virtual void setAutoUpdated(bool autoupdate); - /** Gets whether this target is automatically updated if Ogre's rendering - loop or Root::_updateAllRenderTargets is being used. - */ - virtual bool isAutoUpdated(void) const; - - /** Copies the current contents of the render target to a pixelbox. - @remarks See suggestPixelFormat for a tip as to the best pixel format to - extract into, although you can use whatever format you like and the - results will be converted. - */ - virtual void copyContentsToMemory(const Box& src, const PixelBox &dst, FrameBuffer buffer = FB_AUTO) = 0; - - /** @overload - @deprecated This function is deprecated as behavior for dst.size < RenderTarget.size - was inconsistent in previous versions of Ogre. Sometimes the whole rect was used as a source, - sometimes the rect with the size equal to the size of destination rect but located - in the top left corner of the render target, sometimes the destination rect itself. - Use the overload with explicitly specified source and destination boxes instead. - */ - OGRE_DEPRECATED void copyContentsToMemory(const PixelBox &dst, FrameBuffer buffer = FB_AUTO) { copyContentsToMemory(Box(0, 0, mWidth, mHeight), dst, buffer); } - - /** Suggests a pixel format to use for extracting the data in this target, - when calling copyContentsToMemory. - */ - virtual PixelFormat suggestPixelFormat() const { return PF_BYTE_RGBA; } - - /** Writes the current contents of the render target to the named file. */ - void writeContentsToFile(const String& filename); - - /** Writes the current contents of the render target to the (PREFIX)(time-stamp)(SUFFIX) file. - @return the name of the file used.*/ - virtual String writeContentsToTimestampedFile(const String& filenamePrefix, const String& filenameSuffix); - - virtual bool requiresTextureFlipping() const = 0; - - /** Utility method to notify a render target that a camera has been removed, - in case it was referring to it as a viewer. - */ - virtual void _notifyCameraRemoved(const Camera* cam); - - /** Indicates whether this target is the primary window. The - primary window is special in that it is destroyed when - ogre is shut down, and cannot be destroyed directly. - This is the case because it holds the context for vertex, - index buffers and textures. - */ - virtual bool isPrimary(void) const; - - /** Indicates whether stereo is currently enabled for this target. Default is false. */ - virtual bool isStereoEnabled(void) const; - - /** Indicates whether on rendering, linear colour space is converted to - sRGB gamma colour space. This is the exact opposite conversion of - what is indicated by Texture::isHardwareGammaEnabled, and can only - be enabled on creation of the render target. For render windows, it's - enabled through the 'gamma' creation misc parameter. For textures, - it is enabled through the hwGamma parameter to the create call. - */ - virtual bool isHardwareGammaEnabled() const { return mHwGamma; } - - /** Indicates whether multisampling is performed on rendering and at what level. - */ - virtual uint getFSAA() const { return mFSAA; } - - /// RenderSystem specific FSAA option. See @ref RenderSystem::_createRenderWindow for details. - virtual const String& getFSAAHint() const { return mFSAAHint; } - - /** Set the level of multisample AA to be used if hardware support it. - This option will be ignored if the hardware does not support it - or setting can not be changed on the fly on per-target level. - @param fsaa The number of samples - @param fsaaHint @copybrief getFSAAHint - */ - virtual void setFSAA(uint fsaa, const String& fsaaHint) { } - - /** Method for manual management of rendering : fires 'preRenderTargetUpdate' - and initialises statistics etc. - -
    -
  • _beginUpdate resets statistics and fires 'preRenderTargetUpdate'.
  • -
  • _updateViewport renders the given viewport (even if it is not autoupdated), - fires preViewportUpdate and postViewportUpdate and manages statistics.
  • -
  • _updateAutoUpdatedViewports renders only viewports that are auto updated, - fires preViewportUpdate and postViewportUpdate and manages statistics.
  • -
  • _endUpdate() ends statistics calculation and fires postRenderTargetUpdate.
  • -
- you can use it like this for example : -
-            renderTarget->_beginUpdate();
-            renderTarget->_updateViewport(1); // which is not auto updated
-            renderTarget->_updateViewport(2); // which is not auto updated
-            renderTarget->_updateAutoUpdatedViewports();
-            renderTarget->_endUpdate();
-            renderTarget->swapBuffers();
-        
- Please note that in that case, the zorder may not work as you expect, - since you are responsible for calling _updateViewport in the correct order. - */ - virtual void _beginUpdate(); - - /** Method for manual management of rendering - renders the given - viewport (even if it is not autoupdated) - - This also fires preViewportUpdate and postViewportUpdate, and manages statistics. - You should call it between _beginUpdate() and _endUpdate(). - @see _beginUpdate for more details. - @param zorder The zorder of the viewport to update. - @param updateStatistics Whether you want to update statistics or not. - */ - virtual void _updateViewport(int zorder, bool updateStatistics = true); - - /** Method for manual management of rendering - renders the given viewport (even if it is not autoupdated) - - This also fires preViewportUpdate and postViewportUpdate, and manages statistics - if needed. You should call it between _beginUpdate() and _endUpdate(). - @see _beginUpdate for more details. - @param viewport The viewport you want to update, it must be bound to the rendertarget. - @param updateStatistics Whether you want to update statistics or not. - */ - virtual void _updateViewport(Viewport* viewport, bool updateStatistics = true); - - /** Method for manual management of rendering - renders only viewports that are auto updated - - This also fires preViewportUpdate and postViewportUpdate, and manages statistics. - You should call it between _beginUpdate() and _endUpdate(). - See _beginUpdate for more details. - @param updateStatistics Whether you want to update statistics or not. - @see _beginUpdate() - */ - virtual void _updateAutoUpdatedViewports(bool updateStatistics = true); - - /** Method for manual management of rendering - finishes statistics calculation - and fires 'postRenderTargetUpdate'. - - You should call it after a _beginUpdate - @see _beginUpdate for more details. - */ - virtual void _endUpdate(); - - protected: - /// The name of this target. - String mName; - /// The priority of the render target. - uchar mPriority; - - uint32 mWidth; - uint32 mHeight; - uint16 mDepthBufferPoolId; - DepthBuffer *mDepthBuffer; - - // Stats - FrameStats mStats; - - Timer* mTimer ; - unsigned long mLastSecond; - unsigned long mLastTime; - size_t mFrameCount; - - bool mActive; - bool mAutoUpdate; - // Hardware sRGB gamma conversion done on write? - bool mHwGamma; - // FSAA performed? - uint mFSAA; - String mFSAAHint; - bool mStereoEnabled; - - virtual void updateStats(void); - - typedef std::map ViewportList; - /// List of viewports, map on Z-order - ViewportList mViewportList; - - typedef std::vector RenderTargetListenerList; - RenderTargetListenerList mListeners; - - - /// internal method for firing events - virtual void firePreUpdate(void); - /// internal method for firing events - virtual void firePostUpdate(void); - /// internal method for firing events - virtual void fireViewportPreUpdate(Viewport* vp); - /// internal method for firing events - virtual void fireViewportPostUpdate(Viewport* vp); - /// internal method for firing events - virtual void fireViewportAdded(Viewport* vp); - /// internal method for firing events - void fireViewportRemoved(Viewport* vp); - - /// Internal implementation of update() - virtual void updateImpl(); - }; - /** @} */ - /** @} */ - -} // Namespace - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreRenderTargetListener.h b/OgreMain/include/OgreRenderTargetListener.h deleted file mode 100644 index 73bc19e2f3c..00000000000 --- a/OgreMain/include/OgreRenderTargetListener.h +++ /dev/null @@ -1,146 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __RenderTargetListener_H__ -#define __RenderTargetListener_H__ - - -#include "OgrePrerequisites.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - /** Struct containing information about a RenderTarget event. - */ - struct RenderTargetEvent - { - /// The source of the event being raised - RenderTarget* source; - }; - - /** Struct containing information about a RenderTarget Viewport-specific event. - */ - struct RenderTargetViewportEvent - { - /// The source of the event being raised - Viewport* source; - }; - - /** A interface class defining a listener which can be used to receive - notifications of RenderTarget events. - - A 'listener' is an interface designed to be called back when - particular events are called. This class defines the - interface relating to RenderTarget events. In order to receive - notifications of RenderTarget events, you should create a subclass of - RenderTargetListener and override the methods for which you would like - to customise the resulting processing. You should then call - RenderTarget::addListener passing an instance of this class. - There is no limit to the number of RenderTarget listeners you can register, - allowing you to register multiple listeners for different purposes. - - RenderTarget events occur before and after the target is updated as a whole, - and before and after each viewport on that target is updated. Each RenderTarget - holds it's own set of listeners, but you can register the same listener on - multiple render targets if you like since the event contains details of the - originating RenderTarget. - */ - class _OgreExport RenderTargetListener - { - /* - Note that this could have been an abstract class, but I made - the explicit choice not to do this, because I wanted to give - people the option of only implementing the methods they wanted, - rather than having to create 'do nothing' implementations for - those they weren't interested in. As such this class follows - the 'Adapter' classes in Java rather than pure interfaces. - */ - public: - virtual ~RenderTargetListener() {} - /** Called just before a RenderTarget is about to be rendered into. - - This event is raised just before any of the viewports on the target - are rendered to. You can perform manual rendering operations here if - you want, but please note that if the Viewport objects attached to this - target are set up to clear the background, you will lose whatever you - render. If you want some kind of backdrop in this event - you should turn off background clearing off on the viewports, and either - clear the viewports yourself in this event handler before doing your rendering - or just render over the top if you don't need to. - */ - virtual void preRenderTargetUpdate(const RenderTargetEvent& evt) - { (void)evt; } - - /** Called just after a RenderTarget has been rendered to. - - This event is called just after all the viewports attached to the target - in question have been rendered to. You can perform your own manual rendering - commands in this event handler if you like, these will be composited with - the contents of the target already there (depending on the material settings - you use etc). - */ - virtual void postRenderTargetUpdate(const RenderTargetEvent& evt) - { (void)evt; } - - /** Called just before a Viewport on a RenderTarget is to be updated. - - This method is called before each viewport on the RenderTarget is - rendered to. You can use this to perform per-viewport settings changes, - such as showing / hiding particular overlays. - */ - virtual void preViewportUpdate(const RenderTargetViewportEvent& evt) - { (void)evt; } - - /** Called just after a Viewport on a RenderTarget is to be updated. - - This method is called after each viewport on the RenderTarget is - rendered to. - */ - virtual void postViewportUpdate(const RenderTargetViewportEvent& evt) - { (void)evt; } - - /** Called to notify listener that a Viewport has been added to the - target in question. - */ - virtual void viewportAdded(const RenderTargetViewportEvent& evt) - { (void)evt; } - /** Called to notify listener that a Viewport has been removed from the - target in question. - */ - virtual void viewportRemoved(const RenderTargetViewportEvent& evt) - { (void)evt; } - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/OgreMain/include/OgreRenderTexture.h b/OgreMain/include/OgreRenderTexture.h deleted file mode 100644 index 0aa0fe89174..00000000000 --- a/OgreMain/include/OgreRenderTexture.h +++ /dev/null @@ -1,128 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __RenderTexture_H__ -#define __RenderTexture_H__ - -#include "OgrePrerequisites.h" -#include "OgreRenderTarget.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - /** This class represents a RenderTarget that renders to a Texture. There is no 1 on 1 - relation between Textures and RenderTextures, as there can be multiple - RenderTargets rendering to different mipmaps, faces (for cubemaps) or slices (for 3D textures) - of the same Texture. - */ - class _OgreExport RenderTexture: public RenderTarget - { - public: - RenderTexture(HardwarePixelBuffer *buffer, uint32 zoffset); - virtual ~RenderTexture(); - - using RenderTarget::copyContentsToMemory; - void copyContentsToMemory(const Box& src, const PixelBox &dst, FrameBuffer buffer = FB_AUTO) override; - PixelFormat suggestPixelFormat() const override; - - protected: - HardwarePixelBuffer *mBuffer; - uint32 mZOffset; - }; - - /** This class represents a render target that renders to multiple RenderTextures - at once. Surfaces can be bound and unbound at will, as long as the following constraints - are met: - - All bound surfaces have the same size - - All bound surfaces have the same bit depth - - Target 0 is bound - */ - class _OgreExport MultiRenderTarget: public RenderTarget - { - public: - MultiRenderTarget(const String &name); - - /** Bind a surface to a certain attachment point. - @param attachment 0 .. mCapabilities->getNumMultiRenderTargets()-1 - @param target RenderTexture to bind. - - It does not bind the surface and fails with an exception (ERR_INVALIDPARAMS) if: - - Not all bound surfaces have the same size - - Not all bound surfaces have the same internal format - */ - - virtual void bindSurface(size_t attachment, RenderTexture *target); - - /** Unbind attachment. - */ - virtual void unbindSurface(size_t attachment) - { - if (attachment < mBoundSurfaces.size()) - mBoundSurfaces[attachment] = 0; - unbindSurfaceImpl(attachment); - } - - using RenderTarget::copyContentsToMemory; - - /** Error throwing implementation, it's not possible to write a MultiRenderTarget - to disk. - */ - void copyContentsToMemory(const Box& src, const PixelBox &dst, FrameBuffer buffer = FB_AUTO) override; - - /// Irrelevant implementation since cannot copy - PixelFormat suggestPixelFormat() const override { return PF_UNKNOWN; } - - typedef std::vector BoundSufaceList; - /// Get a list of the surfaces which have been bound - const BoundSufaceList& getBoundSurfaceList() const { return mBoundSurfaces; } - - /** Get a pointer to a bound surface */ - RenderTexture* getBoundSurface(size_t index) { return mBoundSurfaces.at(index); } - - protected: - BoundSufaceList mBoundSurfaces; - - /// Implementation of bindSurface, must be provided - virtual void bindSurfaceImpl(size_t attachment, RenderTexture *target) = 0; - /// Implementation of unbindSurface, must be provided - virtual void unbindSurfaceImpl(size_t attachment) = 0; - - - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreRenderToVertexBuffer.h b/OgreMain/include/OgreRenderToVertexBuffer.h deleted file mode 100644 index e0a51876b9d..00000000000 --- a/OgreMain/include/OgreRenderToVertexBuffer.h +++ /dev/null @@ -1,156 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#ifndef __RenderToVertexBuffer_H__ -#define __RenderToVertexBuffer_H__ - -#include "OgrePrerequisites.h" -#include "OgreRenderOperation.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - /** - An object which renders geometry to a vertex. - - This is especially useful together with geometry shaders, as you can - render procedural geometry which will get saved to a vertex buffer for - reuse later, without regenerating it again. You can also create shaders - that run on previous results of those shaders, creating stateful - shaders. - */ - class _OgreExport RenderToVertexBuffer - { - public: - RenderToVertexBuffer(); - virtual ~RenderToVertexBuffer(); - - /** - Get the vertex declaration that the pass will output. - - Use this object to set the elements of the buffer. Object will calculate - buffers on its own. Only one source allowed! - */ - VertexDeclaration* getVertexDeclaration(); - - /** - Get the maximum number of vertices that the buffer will hold - */ - unsigned int getMaxVertexCount() const { return mMaxVertexCount; } - - /** - Set the maximum number of vertices that the buffer will hold - */ - void setMaxVertexCount(unsigned int maxVertexCount) { mMaxVertexCount = maxVertexCount; } - - /** - What type of primitives does this object generate? - */ - RenderOperation::OperationType getOperationType() const { return mOperationType; } - - /** - Set the type of primitives that this object generates - */ - void setOperationType(RenderOperation::OperationType operationType) { mOperationType = operationType; } - - /** - Set whether this object resets its buffers each time it updates. - */ - void setResetsEveryUpdate(bool resetsEveryUpdate) { mResetsEveryUpdate = resetsEveryUpdate; } - - /** - Does this object reset its buffer each time it updates? - */ - bool getResetsEveryUpdate() const { return mResetsEveryUpdate; } - - /** - Get the render operation for this buffer - */ - void getRenderOperation(RenderOperation& op); - - /** - Update the contents of this vertex buffer by rendering - */ - virtual void update(SceneManager* sceneMgr) = 0; - - /** - Reset the vertex buffer to the initial state. In the next update, - the source renderable will be used as input. - */ - virtual void reset() { mResetRequested = true; } - - /** - Set the source renderable of this object. During the first (and - perhaps later) update of this object, this object's data will be - used as input) - */ - void setSourceRenderable(Renderable* source) { mSourceRenderable = source; } - - /** - Get the source renderable of this object - */ - const Renderable* getSourceRenderable() const { return mSourceRenderable; } - - /** - Get the material which is used to render the geometry into the - vertex buffer. - */ - const MaterialPtr& getRenderToBufferMaterial() { return mMaterial; } - - /** - Set the material name which is used to render the geometry into - the vertex buffer - */ - void setRenderToBufferMaterialName(const String& materialName); - - protected: - Pass* derivePass(SceneManager* sceneMgr); - - RenderOperation::OperationType mOperationType; - bool mResetsEveryUpdate; - bool mResetRequested; - Renderable* mSourceRenderable; - std::unique_ptr mVertexData; - unsigned int mMaxVertexCount; - HardwareVertexBufferPtr mVertexBuffers[2]; - uint8 mTargetBufferIndex; - private: - MaterialPtr mMaterial; - }; - - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreRenderWindow.h b/OgreMain/include/OgreRenderWindow.h deleted file mode 100644 index 1ded65272fc..00000000000 --- a/OgreMain/include/OgreRenderWindow.h +++ /dev/null @@ -1,246 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ -#ifndef __RenderWindow_H__ -#define __RenderWindow_H__ - -#include "OgrePrerequisites.h" - -#include "OgreRenderTarget.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - /** Manages the target rendering window. - - This class handles a window into which the contents - of a scene are rendered. There is a many-to-1 relationship - between instances of this class an instance of RenderSystem - which controls the rendering of the scene. There may be - more than one window in the case of level editor tools etc. - This class is abstract since there may be - different implementations for different windowing systems. - - Instances are created and communicated with by the render system - although client programs can get a reference to it from - the render system if required for resizing or moving. - Note that you can have multiple viewpoints - in the window for effects like rear-view mirrors and - picture-in-picture views (see Viewport and Camera). - @author - Steven Streeting - @version - 1.0 - */ - class _OgreExport RenderWindow : public RenderTarget - { - - public: - /** Default constructor. - */ - RenderWindow(); - - /** Many windowing systems that support HiDPI displays use special points to specify - size of the windows and controls, so that windows and controls with hardcoded - sizes does not become too small on HiDPI displays. Such points have constant density - ~ 100 points per inch (probably 96 on Windows and 72 on Mac), that is independent - of pixel density of real display, and are used through the all windowing system. - - Sometimes, such view points are chosen bigger for output devices that are viewed - from larger distances, like 30" TV comparing to 30" monitor, therefore maintaining - constant points angular density rather than constant linear density. - - In any case, all such windowing system provides the way to convert such view points - to pixels, be it DisplayProperties::LogicalDpi on WinRT or backingScaleFactor on MacOSX. - We use pixels consistently through the Ogre, but window/view management functions - takes view points for convenience, as does the rest of windowing system. Such parameters - are named using xxxxPt pattern, and should not be mixed with pixels without being - converted using getViewPointToPixelScale() function. - - Sometimes such scale factor can change on-the-fly, for example if window is dragged - to monitor with different DPI. In such situation, window size in view points is usually - preserved by windowing system, and Ogre should adjust pixel size of RenderWindow. - */ - virtual float getViewPointToPixelScale() { return 1.0f; } - - /** Creates & displays the new window. - @param name the internal window name. Not necessarily the title. - @param - widthPt The width of the window in view points. - @param - heightPt The height of the window in view points. - @param - fullScreen If true, the window fills the screen, - with no title bar or border. - @param - miscParams A variable number of pointers to platform-specific arguments. The - actual requirements must be defined by the implementing subclasses. - */ - virtual void create(const String& name, unsigned int widthPt, unsigned int heightPt, - bool fullScreen, const NameValuePairList *miscParams) = 0; - - /** Alter fullscreen mode options. - Nothing will happen unless the settings here are different from the - current settings. - @note Only implemented by few RenderSystems. Prefer native windowing API. - @param fullScreen Whether to use fullscreen mode or not. - @param widthPt The new width to use - @param heightPt The new height to use - */ - virtual void setFullscreen(bool fullScreen, unsigned int widthPt, unsigned int heightPt) - { (void)fullScreen; (void)widthPt; (void)heightPt; } - - /** Destroys the window. - */ - virtual void destroy(void) = 0; - - /** Alter the size of the window. - */ - virtual void resize(unsigned int widthPt, unsigned int heightPt) = 0; - - /** Query the current size and position from an external window handle. - @note most of the time you already know the size and should call @ref resize instead. - */ - virtual void windowMovedOrResized() {} - - /** Reposition the window. - - @note Only implemented by few RenderSystems. Prefer native windowing API. - */ - virtual void reposition(int leftPt, int topPt) {} - - /** Indicates whether the window is visible (not minimized or obscured) - */ - virtual bool isVisible(void) const { return true; } - - /** Set the visibility state - */ - virtual void setVisible(bool visible) - { (void)visible; } - - /** Indicates whether the window was set to hidden (not displayed) - */ - virtual bool isHidden(void) const { return false; } - - /** Hide (or show) the window. If called with hidden=true, this - will make the window completely invisible to the user. - - Setting a window to hidden is useful to create a dummy primary - RenderWindow hidden from the user so that you can create and - recreate your actual RenderWindows without having to recreate - all your resources. - */ - virtual void setHidden(bool hidden) - { (void)hidden; } - - /** Enable or disable vertical sync for the RenderWindow. - */ - virtual void setVSyncEnabled(bool vsync) - { (void)vsync; } - - /** Indicates whether vertical sync is activated for the window. - */ - virtual bool isVSyncEnabled() const { return false; } - - /** Set the vertical sync interval. This indicates the number of vertical retraces to wait for - before swapping buffers. A value of 1 is the default. - */ - virtual void setVSyncInterval(unsigned int interval) - { (void)interval; } - - /** Returns the vertical sync interval. - */ - unsigned int getVSyncInterval() const { return mVSyncInterval; } - - - /** Overridden from RenderTarget, flags invisible windows as inactive - */ - bool isActive(void) const override { return mActive && isVisible(); } - - /** Indicates whether the window has been closed by the user. - */ - virtual bool isClosed(void) const { return mClosed; } - - /** Indicates whether the window is the primary window. The - primary window is special in that it is destroyed when - ogre is shut down, and cannot be destroyed directly. - This is the case because it holds the context for vertex, - index buffers and textures. - */ - bool isPrimary(void) const override; - - /** Returns true if window is running in fullscreen mode. - */ - virtual bool isFullScreen(void) const; - - /** Overloaded version of getMetrics from RenderTarget, including extra details - specific to windowing systems. Result is in pixels. - */ - void getMetrics(unsigned int& width, unsigned int& height, int& left, int& top) const; - - /// Override since windows don't usually have alpha - PixelFormat suggestPixelFormat() const override { return PF_BYTE_RGB; } - - /** Returns true if the window will automatically de-activate itself when it loses focus. - */ - bool isDeactivatedOnFocusChange() const; - - /** Indicates whether the window will automatically deactivate itself when it loses focus. - * @param deactivate a value of 'true' will cause the window to deactivate itself when it loses focus. 'false' will allow it to continue to render even when window focus is lost. - * @note 'true' is the default behavior. - */ - void setDeactivateOnFocusChange(bool deactivate); - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - virtual void _notifySurfaceDestroyed() = 0; - virtual void _notifySurfaceCreated(void* nativeWindow, void* config = NULL) = 0; -#endif - - protected: - bool mIsFullScreen; - bool mIsPrimary; - bool mAutoDeactivatedOnFocusChange; - bool mClosed; - int mLeft; - int mTop; - unsigned int mVSyncInterval; - - /** Indicates that this is the primary window. Only to be called by - Ogre::Root - */ - void _setPrimary() { mIsPrimary = true; } - - friend class Root; - }; - /** @} */ - /** @} */ - -} // Namespace -#endif diff --git a/OgreMain/include/OgreRenderable.h b/OgreMain/include/OgreRenderable.h deleted file mode 100644 index ec3c8a5681b..00000000000 --- a/OgreMain/include/OgreRenderable.h +++ /dev/null @@ -1,371 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Renderable_H__ -#define __Renderable_H__ - -#include "OgrePrerequisites.h" -#include "OgreCommon.h" - -#include "OgreGpuProgram.h" -#include "OgreGpuProgramParams.h" -#include "OgreMatrix4.h" -#include "OgreMaterial.h" -#include "OgrePlane.h" -#include "OgreVector.h" -#include "OgreException.h" -#include "OgreUserObjectBindings.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** Abstract class defining the interface all renderable objects must implement. - - This interface abstracts renderable discrete objects which will be queued in the render pipeline, - grouped by material. Classes implementing this interface must be based on a single material, a single - world matrix (or a collection of world matrices which are blended by weights), and must be - renderable via a single render operation. - @par - Note that deciding whether to put these objects in the rendering pipeline is done from the more specific - classes e.g. entities. Only once it is decided that the specific class is to be rendered is the abstract version - created (could be more than one per visible object) and pushed onto the rendering queue. - */ - class _OgreExport Renderable - { - public: - enum - { - DEFAULT_PRIORITY = 100 - }; - - Renderable() - : mMaterialLodIndex(0), mPolygonModeOverrideable(true), mUseIdentityProjection(false), - mUseIdentityView(false) - { - } - /** Virtual destructor needed as class has virtual methods. */ - virtual ~Renderable() {} - /** Retrieves a weak reference to the material this renderable object uses. - - Note that the Renderable also has the option to override the getTechnique method - to specify a particular Technique to use instead of the best one available. - */ - virtual const MaterialPtr& getMaterial(void) const = 0; - /** Retrieves a pointer to the Material Technique this renderable object uses. - - This is to allow Renderables to use a chosen Technique if they wish, otherwise - they will use the best Technique available for the Material they are using. - */ - virtual Technique* getTechnique(void) const { return getMaterial()->getBestTechnique(mMaterialLodIndex, this); } - /** Gets the render operation required to send this object to the frame buffer. - */ - virtual void getRenderOperation(RenderOperation& op) = 0; - - uint16 _getMaterialLodIndex() const { return mMaterialLodIndex; } - - /** Called just prior to the Renderable being rendered. - - OGRE is a queued renderer, so the actual render commands are executed - at a later time than the point at which an object is discovered to be - visible. This allows ordering & grouping of renders without the discovery - process having to be aware of it. It also means OGRE uses declarative - render information rather than immediate mode rendering - this is very useful - in that certain effects and processes can automatically be applied to - a wide range of scenes, but the downside is that special cases are - more difficult to handle, because there is not the declared state to - cope with it. - @par - This method allows a Renderable to do something special at the actual - point of rendering if it wishes to. When this method is called, all the - material render state as declared by this Renderable has already been set, - all that is left to do is to bind the buffers and perform the render. - The Renderable may modify render state itself if it wants to (and restore it in the - postRender call) before the automated render happens, or by returning - 'false' from this method can actually suppress the automatic render - and perform one of its own. - @return - true if the automatic render should proceed, false to skip it on - the assumption that the Renderable has done it manually. - */ - virtual bool preRender(SceneManager* sm, RenderSystem* rsys) - { (void)sm; (void)rsys; return true; } - - /** Called immediately after the Renderable has been rendered. - */ - virtual void postRender(SceneManager* sm, RenderSystem* rsys) - { (void)sm; (void)rsys; } - - /** Gets the world transform matrix / matrices for this renderable object. - - If the object has any derived transforms, these are expected to be up to date as long as - all the SceneNode structures have been updated before this is called. - - @note - Internal Ogre never supports non-affine matrix for world transform matrix/matrices, - the behavior is undefined if returns non-affine matrix here. - - This method will populate transform with 1 matrix if it does not use GPU vertex blending. If it - does use GPU vertex blending it will fill the passed in pointer with an array of matrices, - the length being the value returned from @ref getNumWorldTransforms. - - @note If @ref MeshManager::getBonesUseObjectSpace() is true, the first matrix must contain the world - transform of the object, and the rest of the matrices must contain the bone transforms in object space. - */ - virtual void getWorldTransforms(Matrix4* xform) const = 0; - - /** Returns the number of world transform matrices this renderable requires. - - When a renderable uses GPU vertex blending, it uses multiple world matrices instead of a single - one. Each vertex sent to the pipeline can reference one or more matrices in this list - with given weights. - If a renderable does not use vertex blending this method returns 1, which is the default for - simplicity. - @note If @ref MeshManager::getBonesUseObjectSpace() is true, this method must return - numBones + 1 - */ - virtual uint16 getNumWorldTransforms(void) const { return 1; } - - /** Sets whether or not to use an 'identity' projection. - - Usually Renderable objects will use a projection matrix as determined - by the active camera. However, if they want they can cancel this out - and use an identity projection, which effectively projects in 2D using - a {-1, 1} view space. Useful for overlay rendering. Normal renderables - need not change this. The default is false. - @see Renderable::getUseIdentityProjection - */ - void setUseIdentityProjection(bool useIdentityProjection) - { - mUseIdentityProjection = useIdentityProjection; - } - - /** Returns whether or not to use an 'identity' projection. - - Usually Renderable objects will use a projection matrix as determined - by the active camera. However, if they want they can cancel this out - and use an identity projection, which effectively projects in 2D using - a {-1, 1} view space. Useful for overlay rendering. Normal renderables - need not change this. - @see Renderable::setUseIdentityProjection - */ - bool getUseIdentityProjection(void) const { return mUseIdentityProjection; } - - /** Sets whether or not to use an 'identity' view. - - Usually Renderable objects will use a view matrix as determined - by the active camera. However, if they want they can cancel this out - and use an identity matrix, which means all geometry is assumed - to be relative to camera space already. Useful for overlay rendering. - Normal renderables need not change this. The default is false. - @see Renderable::getUseIdentityView - */ - void setUseIdentityView(bool useIdentityView) - { - mUseIdentityView = useIdentityView; - } - - /** Returns whether or not to use an 'identity' view. - - Usually Renderable objects will use a view matrix as determined - by the active camera. However, if they want they can cancel this out - and use an identity matrix, which means all geometry is assumed - to be relative to camera space already. Useful for overlay rendering. - Normal renderables need not change this. - @see Renderable::setUseIdentityView - */ - bool getUseIdentityView(void) const { return mUseIdentityView; } - - /** Returns the squared distance between the camera and this renderable. - - Used to sort transparent objects. Squared distance is used - to avoid having to perform a square root on the result. - */ - virtual Real getSquaredViewDepth(const Camera* cam) const = 0; - - /** Gets a list of lights, ordered relative to how close they are to this renderable. - - Directional lights, which have no position, will always be first on this list. - */ - virtual const LightList& getLights(void) const = 0; - - /** Method which reports whether this renderable would normally cast a - shadow. - - Subclasses should override this if they could have been used to - generate a shadow. - */ - virtual bool getCastsShadows(void) const { return false; } - - /** Sets a custom parameter for this Renderable, which may be used to - drive calculations for this specific Renderable, like GPU program parameters. - - Calling this method simply associates a numeric index with a 4-dimensional - value for this specific Renderable. This is most useful if the material - which this Renderable uses a vertex or fragment program, and has an - ACT_CUSTOM parameter entry. This parameter entry can refer to the - index you specify as part of this call, thereby mapping a custom - parameter for this renderable to a program parameter. - @param index The index with which to associate the value. Note that this - does not have to start at 0, and can include gaps. It also has no direct - correlation with a GPU program parameter index - the mapping between the - two is performed by the ACT_CUSTOM entry, if that is used. - @param value The value to associate. - */ - void setCustomParameter(size_t index, const Vector4f& value); - - /** Removes a custom value which is associated with this Renderable at the given index. - @param index Index of the parameter to remove. - @see setCustomParameter for full details. - */ - void removeCustomParameter(size_t index); - - /** Checks whether a custom value is associated with this Renderable at the given index. - @param index Index of the parameter to check for existence. - @see setCustomParameter for full details. - */ - bool hasCustomParameter(size_t index) const; - - /** Gets the custom value associated with this Renderable at the given index. - @param index Index of the parameter to retrieve. - @see setCustomParameter for full details. - */ - const Vector4f& getCustomParameter(size_t index) const; - - /** Update a custom GpuProgramParameters constant which is derived from - information only this Renderable knows. - - This method allows a Renderable to map in a custom GPU program parameter - based on it's own data. This is represented by a GPU auto parameter - of ACT_CUSTOM, and to allow there to be more than one of these per - Renderable, the 'data' field on the auto parameter will identify - which parameter is being updated. The implementation of this method - must identify the parameter being updated, and call a 'setConstant' - method on the passed in GpuProgramParameters object, using the details - provided in the incoming auto constant setting to identify the index - at which to set the parameter. - @par - You do not need to override this method if you're using the standard - sets of data associated with the Renderable as provided by setCustomParameter - and getCustomParameter. By default, the implementation will map from the - value indexed by the 'constantEntry.data' parameter to a value previously - set by setCustomParameter. But custom Renderables are free to override - this if they want, in any case. - @param constantEntry The auto constant entry referring to the parameter - being updated - @param params The parameters object which this method should call to - set the updated parameters. - */ - virtual void _updateCustomGpuParameter(const GpuProgramParameters::AutoConstantEntry& constantEntry, - GpuProgramParameters* params) const; - - /** Sets whether this renderable's chosen detail level can be - overridden (downgraded) by the camera setting. - @param override true means that a lower camera detail will override this - renderables detail level, false means it won't. - */ - void setPolygonModeOverrideable(bool override) - { - mPolygonModeOverrideable = override; - } - - /** Gets whether this renderable's chosen detail level can be - overridden (downgraded) by the camera setting. - */ - bool getPolygonModeOverrideable(void) const - { - return mPolygonModeOverrideable; - } - - /** @deprecated use UserObjectBindings::setUserAny via getUserObjectBindings() instead. - */ - OGRE_DEPRECATED void setUserAny(const Any& anything) { getUserObjectBindings().setUserAny(anything); } - - /** @deprecated use UserObjectBindings::getUserAny via getUserObjectBindings() instead. - */ - OGRE_DEPRECATED const Any& getUserAny(void) const { return getUserObjectBindings().getUserAny(); } - - /// @copydoc UserObjectBindings - UserObjectBindings& getUserObjectBindings() { return mUserObjectBindings; } - - /// @overload - const UserObjectBindings& getUserObjectBindings() const { return mUserObjectBindings; } - - - /** Visitor object that can be used to iterate over a collection of Renderable - instances abstractly. - - Different scene objects use Renderable differently; some will have a - single Renderable, others will have many. This visitor interface allows - classes using Renderable to expose a clean way for external code to - get access to the contained Renderable instance(s) that it will - eventually add to the render queue. - @par - To actually have this method called, you have to call a method on the - class containing the Renderable instances. One example is - MovableObject::visitRenderables. - */ - class Visitor - { - public: - /** Virtual destructor needed as class has virtual methods. */ - virtual ~Visitor() { } - /** Generic visitor method. - @param rend The Renderable instance being visited - @param lodIndex The LOD index to which this Renderable belongs. Some - objects support LOD and this will tell you whether the Renderable - you're looking at is from the top LOD (0) or otherwise - @param isDebug Whether this is a debug renderable or not. - @param pAny Optional pointer to some additional data that the class - calling the visitor may populate if it chooses to. - */ - virtual void visit(Renderable* rend, ushort lodIndex, bool isDebug, - Any* pAny = 0) = 0; - }; - - protected: - typedef std::map CustomParameterMap; - CustomParameterMap mCustomParameters; - UserObjectBindings mUserObjectBindings; /// User objects binding. - uint16 mMaterialLodIndex; - bool mPolygonModeOverrideable; - bool mUseIdentityProjection; - bool mUseIdentityView; - }; - - /** @} */ - /** @} */ - -} // namespace Ogre - -#include "OgreHeaderSuffix.h" -#endif //__Renderable_H__ diff --git a/OgreMain/include/OgreResource.h b/OgreMain/include/OgreResource.h deleted file mode 100644 index 9460a049ad7..00000000000 --- a/OgreMain/include/OgreResource.h +++ /dev/null @@ -1,501 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _Resource_H__ -#define _Resource_H__ - -#include "OgrePrerequisites.h" -#include "OgreStringInterface.h" -#include "OgreHeaderPrefix.h" -#include "Threading/OgreThreadHeaders.h" - -namespace Ogre { - - typedef size_t ResourceHandle; - - - // Forward declaration - class ManualResourceLoader; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - /** Abstract class representing a loadable resource - - @see @ref Resource-Management - - Subclasses must implement: -
    -
  1. A constructor, overriding the same parameters as the constructor - defined by this class. Subclasses are not allowed to define - constructors with other parameters; other settings must be - settable through accessor methods before loading.
  2. -
  3. The loadImpl() and unloadImpl() methods - mSize must be set - after loadImpl()
  4. -
  5. StringInterface ParamCommand and ParamDictionary setups - in order to allow setting of core parameters (prior to load) - through a generic interface.
  6. -
- */ - class _OgreExport Resource : public StringInterface, public ResourceAlloc - { - public: - OGRE_AUTO_MUTEX; // public to allow external locking - class Listener - { - public: - virtual ~Listener() {} - - /** Called whenever the resource finishes loading. - - If a Resource has been marked as background loaded (@see Resource::setBackgroundLoaded), - the call does not itself occur in the thread which is doing the loading; - when loading is complete a response indicator is placed with the - ResourceGroupManager, which will then be sent back to the - listener as part of the application's primary frame loop thread. - */ - virtual void loadingComplete(Resource*) {} - - - /** Called whenever the resource finishes preparing (paging into memory). - - If a Resource has been marked as background loaded (@see Resource::setBackgroundLoaded) - the call does not itself occur in the thread which is doing the preparing; - when preparing is complete a response indicator is placed with the - ResourceGroupManager, which will then be sent back to the - listener as part of the application's primary frame loop thread. - */ - virtual void preparingComplete(Resource*) {} - - /** Called whenever the resource has been unloaded. */ - virtual void unloadingComplete(Resource*) {} - }; - - /// Enum identifying the loading state of the resource - enum LoadingState - { - /// Not loaded - LOADSTATE_UNLOADED, - /// Loading is in progress - LOADSTATE_LOADING, - /// Fully loaded - LOADSTATE_LOADED, - /// Currently unloading - LOADSTATE_UNLOADING, - /// Fully prepared - LOADSTATE_PREPARED, - /// Preparing is in progress - LOADSTATE_PREPARING - }; - - /// Enum that allow to choose subset of unloaded/reloaded resources and to adjust reloading behavior - enum LoadingFlags - { - /// Only reloadable resources are processed, reload restores initial state. - LF_DEFAULT = 0, - /// Process non-reloadable resources too. - LF_INCLUDE_NON_RELOADABLE = 1, - /// Process only resources which are not referenced by any other object. Useful to reduce resource consumption. - LF_ONLY_UNREFERENCED = 2, - /// Combination of LF_ONLY_UNREFERENCED and LF_INCLUDE_NON_RELOADABLE - LF_ONLY_UNREFERENCED_INCLUDE_NON_RELOADABLE = 3, - /// Preserve some states during reloading, for example stencil shadows prepareness for Meshes - LF_PRESERVE_STATE = 4, - }; - - protected: - /// Creator - ResourceManager* mCreator; - /// Unique name of the resource - String mName; - /// The name of the resource group - String mGroup; - /// Numeric handle for more efficient look up than name - ResourceHandle mHandle; - /// Is the resource currently loaded? - std::atomic mLoadingState; - /// Is this resource going to be background loaded? Only applicable for multithreaded - volatile bool mIsBackgroundLoaded; - /// Is this file manually loaded? - bool mIsManual; - /// The size of the resource in bytes - size_t mSize; - /// Origin of this resource (e.g. script name) - optional - String mOrigin; - /// Optional manual loader; if provided, data is loaded from here instead of a file - ManualResourceLoader* mLoader; - private: - /// State count, the number of times this resource has changed state - size_t mStateCount; - - typedef std::set ListenerList; - ListenerList mListenerList; - OGRE_MUTEX(mListenerListMutex); - protected: - /** Protected unnamed constructor to prevent default construction. - */ - Resource() - : mCreator(0), mHandle(0), mLoadingState(LOADSTATE_UNLOADED), - mIsBackgroundLoaded(0), mIsManual(0), mSize(0), mLoader(0), mStateCount(0) - { - } - - /// protected assignment as this is merely abstract - Resource& operator=(const Resource& rhs); - - /** Internal hook to perform actions before the load process, but - after the resource has been marked as 'loading'. - @note Mutex will have already been acquired by the loading thread. - Also, this call will occur even when using a ManualResourceLoader - (when loadImpl is not actually called) - */ - virtual void preLoadImpl(void) {} - /** Internal hook to perform actions after the load process, but - before the resource has been marked as fully loaded. - @note Mutex will have already been acquired by the loading thread. - Also, this call will occur even when using a ManualResourceLoader - (when loadImpl is not actually called) - */ - virtual void postLoadImpl(void) {} - - /** Internal hook to perform actions before the unload process. - @note Mutex will have already been acquired by the unloading thread. - */ - virtual void preUnloadImpl(void) {} - /** Internal hook to perform actions after the unload process, but - before the resource has been marked as fully unloaded. - @note Mutex will have already been acquired by the unloading thread. - */ - virtual void postUnloadImpl(void) {} - - /** Internal implementation of the meat of the 'prepare' action, only called if this - resource is not being loaded from a ManualResourceLoader. - */ - virtual void prepareImpl(void) {} - /** Internal function for undoing the 'prepare' action. Only called during - unload if this resource is prepared but not yet loaded. - */ - virtual void unprepareImpl(void) {} - /** Internal implementation of the meat of the 'load' action, only called if this - resource is not being loaded from a ManualResourceLoader. - */ - virtual void loadImpl(void) = 0; - /** Internal implementation of the 'unload' action; called regardless of - whether this resource is being loaded from a ManualResourceLoader. - */ - virtual void unloadImpl(void) = 0; - - /** Calculate the size of a resource; this will only be called after 'load' */ - virtual size_t calculateSize(void) const; - public: - /** Standard constructor. - @param creator Pointer to the ResourceManager that is creating this resource - @param name The unique name of the resource - @param handle Handle to the resource - @param group The name of the resource group to which this resource belongs - @param isManual Is this resource manually loaded? If so, you should really - populate the loader parameter in order that the load process - can call the loader back when loading is required. - @param loader Pointer to a ManualResourceLoader implementation which will be called - when the Resource wishes to load (should be supplied if you set - isManual to true). You can in fact leave this parameter null - if you wish, but the Resource will never be able to reload if - anything ever causes it to unload. Therefore provision of a proper - ManualResourceLoader instance is strongly recommended. - */ - Resource(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual = false, ManualResourceLoader* loader = 0); - - /** Virtual destructor. Shouldn't need to be overloaded, as the resource - deallocation code should reside in unload() - @see - Resource::unload() - */ - virtual ~Resource(); - - /** Prepares the resource for load, if it is not already. One can call prepare() - before load(), but this is not required as load() will call prepare() - itself, if needed. When OGRE_THREAD_SUPPORT==1 both load() and prepare() - are thread-safe. When OGRE_THREAD_SUPPORT==2 however, only prepare() - is thread-safe. The reason for this function is to allow a background - thread to do some of the loading work, without requiring the whole render - system to be thread-safe. The background thread would call - prepare() while the main render loop would later call load(). So long as - prepare() remains thread-safe, subclasses can arbitrarily split the work of - loading a resource between load() and prepare(). It is best to try and - do as much work in prepare(), however, since this will leave less work for - the main render thread to do and thus increase FPS. - @param backgroundThread Whether this is occurring in a background thread - */ - virtual void prepare(bool backgroundThread = false); - - /** Loads the resource, if it is not already. - - If the resource is loaded from a file, loading is automatic. If not, - if for example this resource gained it's data from procedural calls - rather than loading from a file, then this resource will not reload - on it's own. - @param backgroundThread Indicates whether the caller of this method is - the background resource loading thread. - - */ - virtual void load(bool backgroundThread = false); - - /** Reloads the resource, if it is already loaded. - - Calls unload() and then load() again, if the resource is already - loaded. If it is not loaded already, then nothing happens. - */ - virtual void reload(LoadingFlags flags = LF_DEFAULT); - - /** Returns true if the Resource is reloadable, false otherwise. - */ - bool isReloadable(void) const - { - return !mIsManual || mLoader; - } - - /** Is this resource manually loaded? - */ - bool isManuallyLoaded(void) const - { - return mIsManual; - } - - /** Unloads the resource; this is not permanent, the resource can be - reloaded later if required. - */ - virtual void unload(void); - - /** Retrieves info about the size of the resource. - */ - size_t getSize(void) const - { - return mSize; - } - - /** 'Touches' the resource to indicate it has been used. - */ - virtual void touch(void); - - /** Gets resource name. - */ - const String& getName(void) const { return mName; } - - ResourceHandle getHandle(void) const { return mHandle; } - - /** Returns true if the Resource has been prepared, false otherwise. - */ - bool isPrepared(void) const - { - // No lock required to read this state since no modify - return (mLoadingState.load() == LOADSTATE_PREPARED); - } - - /** Returns true if the Resource has been loaded, false otherwise. - */ - bool isLoaded(void) const - { - // No lock required to read this state since no modify - return (mLoadingState.load() == LOADSTATE_LOADED); - } - - /** Returns whether the resource is currently in the process of - background loading. - */ - bool isLoading() const - { - return (mLoadingState.load() == LOADSTATE_LOADING); - } - - /** Returns the current loading state. - */ - LoadingState getLoadingState() const - { - return mLoadingState.load(); - } - - - - /** Returns whether this Resource has been earmarked for background loading. - - This option only makes sense when you have built Ogre with - thread support (OGRE_THREAD_SUPPORT). If a resource has been marked - for background loading, then it won't load on demand like normal - when load() is called. Instead, it will ignore request to load() - except if the caller indicates it is the background loader. Any - other users of this resource should check isLoaded(), and if that - returns false, don't use the resource and come back later. - */ - bool isBackgroundLoaded(void) const { return mIsBackgroundLoaded; } - - /** Tells the resource whether it is background loaded or not. - - @see Resource::isBackgroundLoaded. Note that calling this only - defers the normal on-demand loading behaviour of a resource, it - does not actually set up a thread to make sure the resource gets - loaded in the background. You should use ResourceBackgroundLoadingQueue - to manage the actual loading (which will call this method itself). - */ - void setBackgroundLoaded(bool bl) { mIsBackgroundLoaded = bl; } - - /** Escalates the loading of a background loaded resource. - - If a resource is set to load in the background, but something needs - it before it's been loaded, there could be a problem. If the user - of this resource really can't wait, they can escalate the loading - which basically pulls the loading into the current thread immediately. - If the resource is already being loaded but just hasn't quite finished - then this method will simply wait until the background load is complete. - */ - virtual void escalateLoading(); - - /** Register a listener on this resource. - @see Resource::Listener - */ - virtual void addListener(Listener* lis); - - /** Remove a listener on this resource. - @see Resource::Listener - */ - virtual void removeListener(Listener* lis); - - /// Gets the group which this resource is a member of - const String& getGroup(void) const { return mGroup; } - - /** Change the resource group ownership of a Resource. - - This method is generally reserved for internal use, although - if you really know what you're doing you can use it to move - this resource from one group to another. - @param newGroup Name of the new group - */ - virtual void changeGroupOwnership(const String& newGroup); - - /// Gets the manager which created this resource - ResourceManager* getCreator(void) { return mCreator; } - /** Get the origin of this resource, e.g. a script file name. - - This property will only contain something if the creator of - this resource chose to populate it. Script loaders are advised - to populate it. - */ - const String& getOrigin(void) const { return mOrigin; } - /// Notify this resource of it's origin - void _notifyOrigin(const String& origin) { mOrigin = origin; } - - /** Returns the number of times this resource has changed state, which - generally means the number of times it has been loaded. Objects that - build derived data based on the resource can check this value against - a copy they kept last time they built this derived data, in order to - know whether it needs rebuilding. This is a nice way of monitoring - changes without having a tightly-bound callback. - */ - virtual size_t getStateCount() const { return mStateCount; } - - /** Manually mark the state of this resource as having been changed. - - You only need to call this from outside if you explicitly want derived - objects to think this object has changed. @see getStateCount. - */ - virtual void _dirtyState(); - - - /** Firing of loading complete event - - You should call this from the thread that runs the main frame loop - to avoid having to make the receivers of this event thread-safe. - If you use %Ogre's built in frame loop you don't need to call this - yourself. - */ - void _fireLoadingComplete(bool unused = false); - - /** Firing of preparing complete event - - @copydetails _fireLoadingComplete - */ - void _firePreparingComplete(bool unused = false); - - /** Firing of unloading complete event - - @copydetails _fireLoadingComplete - */ - void _fireUnloadingComplete(void); - }; - - /** Interface describing a manual resource loader. - - Resources are usually loaded from files; however in some cases you - want to be able to set the data up manually instead. This provides - some problems, such as how to reload a Resource if it becomes - unloaded for some reason, either because of memory constraints, or - because a device fails and some or all of the data is lost. - - This interface should be implemented by all classes which wish to - provide manual data to a resource. They provide a pointer to themselves - when defining the resource (via the appropriate ResourceManager), - and will be called when the Resource tries to load. - They should implement the loadResource method such that the Resource - is in the end set up exactly as if it had loaded from a file, - although the implementations will likely differ between subclasses - of Resource, which is why no generic algorithm can be stated here. - @note - The loader must remain valid for the entire life of the resource, - so that if need be it can be called upon to re-load the resource - at any time. - */ - class _OgreExport ManualResourceLoader - { - public: - ManualResourceLoader() {} - virtual ~ManualResourceLoader() {} - - /** Called when a resource wishes to prepare instead of Resource::prepareImpl - * @note this could get - * called in a background thread even in just a semithreaded ogre - * (OGRE_THREAD_SUPPORT==2). Thus, you must not access the RenderSystem from - * this callback. Do that stuff in #loadResource. - @param resource The resource which wishes to prepare - */ - virtual void prepareResource(Resource* resource) - { (void)resource; } - - /** Called when a resource wishes to load instead of Resource::loadImpl - @param resource The resource which wishes to load - */ - virtual void loadResource(Resource* resource) = 0; - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreResourceBackgroundQueue.h b/OgreMain/include/OgreResourceBackgroundQueue.h deleted file mode 100644 index f5897d9377c..00000000000 --- a/OgreMain/include/OgreResourceBackgroundQueue.h +++ /dev/null @@ -1,131 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ResourceBackgroundQueue_H__ -#define __ResourceBackgroundQueue_H__ - - -#include "OgrePrerequisites.h" -#include "OgreCommon.h" -#include "OgreSingleton.h" -#include "OgreResource.h" -#include "OgreWorkQueue.h" -#include "OgreHeaderPrefix.h" - -#include - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - - /** This class is used to perform Resource operations in a - background thread. - - All these requests are now queued via Root::getWorkQueue in order - to share the thread pool amongst all background tasks. You should therefore - refer to that class for configuring the behaviour of the threads - themselves, this class merely provides an interface that is specific - to resource loading around this common functionality. - @par - The general approach here is that on requesting a background resource - process, your request is placed on a queue ready for the background - thread to be picked up, and you will get a 'ticket' back, identifying - the request. Your call will then return and your thread can - proceed, knowing that at some point in the background the operation will - be performed. In it's own thread, the resource operation will be - performed, and once finished the ticket will be marked as complete. - */ - class _OgreExport ResourceBackgroundQueue : public Singleton - { - public: - ResourceBackgroundQueue(); - virtual ~ResourceBackgroundQueue(); - - /** Initialise a resource group in the background. - @see ResourceGroupManager::initialiseResourceGroup - @param name The name of the resource group to initialise - */ - std::future initialiseResourceGroup(const String& name); - - /** Initialise all resource groups which are yet to be initialised in - the background. - @see ResourceGroupManager::intialiseResourceGroup - */ - std::future initialiseAllResourceGroups(); - /** Prepares a resource group in the background. - @see ResourceGroupManager::prepareResourceGroup - @param name The name of the resource group to prepare - */ - std::future prepareResourceGroup(const String& name); - - /** Loads a resource group in the background. - @see ResourceGroupManager::loadResourceGroup - @param name The name of the resource group to load - */ - std::future loadResourceGroup(const String& name); - - /** Unload a single resource in the background. - @see ResourceManager::unload - */ - std::future unload(const ResourcePtr& res); - - /** Unloads a resource group in the background. - @see ResourceGroupManager::unloadResourceGroup - @param name The name of the resource group to load - */ - std::future unloadResourceGroup(const String& name); - - /** Prepare a single resource in the background. - @see ResourceManager::prepare - */ - std::future prepare(const ResourcePtr& res); - - /** Load a single resource in the background. - @see ResourceManager::load - */ - std::future load(const ResourcePtr& res); - - /// @copydoc Singleton::getSingleton() - static ResourceBackgroundQueue& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static ResourceBackgroundQueue* getSingletonPtr(void); - - }; - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreResourceGroupManager.h b/OgreMain/include/OgreResourceGroupManager.h deleted file mode 100644 index 69542ebc4a8..00000000000 --- a/OgreMain/include/OgreResourceGroupManager.h +++ /dev/null @@ -1,957 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ResourceGroupManager_H__ -#define _ResourceGroupManager_H__ - -#include "OgrePrerequisites.h" -#include "OgreSingleton.h" -#include "OgreDataStream.h" -#include "OgreArchive.h" -#include "OgreIteratorWrapper.h" -#include "OgreCommon.h" -#include "Threading/OgreThreadHeaders.h" -#include -#include "OgreHeaderPrefix.h" - -// If X11/Xlib.h gets included before this header (for example it happens when -// including wxWidgets and FLTK), Status is defined as an int which we don't -// want as we have an enum named Status. -#ifdef Status -#undef Status -#endif - -#if OGRE_RESOURCEMANAGER_STRICT == 0 -# define OGRE_RESOURCE_GROUP_INIT = RGN_AUTODETECT -#elif OGRE_RESOURCEMANAGER_STRICT == 1 -# define OGRE_RESOURCE_GROUP_INIT -#else -# define OGRE_RESOURCE_GROUP_INIT = RGN_DEFAULT -#endif - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - - /// Default resource group name - _OgreExport extern const char* const RGN_DEFAULT; - /// Internal resource group name (should be used by OGRE internal only) - _OgreExport extern const char* const RGN_INTERNAL; - /// Special resource group name which causes resource group to be automatically determined based on searching for the resource in all groups. - _OgreExport extern const char* const RGN_AUTODETECT; - - /** This class defines an interface which is called back during - resource group loading to indicate the progress of the load. - - Resource group loading is in 2 phases - creating resources from - declarations (which includes parsing scripts), and loading - resources. Note that you don't necessarily have to have both; it - is quite possible to just parse all the scripts for a group (see - ResourceGroupManager::initialiseResourceGroup, but not to - load the resource group. - The sequence of events is (* signifies a repeating item): -
    -
  • resourceGroupScriptingStarted
  • -
  • scriptParseStarted (*)
  • -
  • scriptParseEnded (*)
  • -
  • resourceGroupScriptingEnded
  • -
  • resourceGroupLoadStarted
  • -
  • resourceLoadStarted (*)
  • -
  • resourceLoadEnded (*)
  • -
  • customStageStarted (*)
  • -
  • customStageEnded (*)
  • -
  • resourceGroupLoadEnded
  • -
  • resourceGroupPrepareStarted
  • -
  • resourcePrepareStarted (*)
  • -
  • resourcePrepareEnded (*)
  • -
  • resourceGroupPrepareEnded
  • -
- @note - If OGRE_THREAD_SUPPORT is 1, this class is thread-safe. - - */ - class _OgreExport ResourceGroupListener - { - public: - virtual ~ResourceGroupListener() {} - - /** This event is fired when a resource group begins parsing scripts. - @note - Remember that if you are loading resources through ResourceBackgroundQueue, - these callbacks will occur in the background thread, so you should - not perform any thread-unsafe actions in this callback if that's the - case (check the group name / script name). - @param groupName The name of the group - @param scriptCount The number of scripts which will be parsed - */ - virtual void resourceGroupScriptingStarted(const String& groupName, size_t scriptCount) {} - /** This event is fired when a script is about to be parsed. - @param scriptName Name of the to be parsed - @param skipThisScript A boolean passed by reference which is by default set to - false. If the event sets this to true, the script will be skipped and not - parsed. Note that in this case the scriptParseEnded event will not be raised - for this script. - */ - virtual void scriptParseStarted(const String& scriptName, bool& skipThisScript) {} - - /** This event is fired when the script has been fully parsed. - */ - virtual void scriptParseEnded(const String& scriptName, bool skipped) {} - /** This event is fired when a resource group finished parsing scripts. */ - virtual void resourceGroupScriptingEnded(const String& groupName) {} - - /** This event is fired when a resource group begins preparing. - @param groupName The name of the group being prepared - @param resourceCount The number of resources which will be prepared, including - a number of stages required to prepare any linked world geometry - */ - virtual void resourceGroupPrepareStarted(const String& groupName, size_t resourceCount) - { (void)groupName; (void)resourceCount; } - - /** This event is fired when a declared resource is about to be prepared. - @param resource Weak reference to the resource prepared. - */ - virtual void resourcePrepareStarted(const ResourcePtr& resource) - { (void)resource; } - - /** This event is fired when the resource has been prepared. - */ - virtual void resourcePrepareEnded(void) {} - /** This event is fired when a resource group finished preparing. */ - virtual void resourceGroupPrepareEnded(const String& groupName) - { (void)groupName; } - - /** This event is fired when a resource group begins loading. - @param groupName The name of the group being loaded - @param resourceCount The number of resources which will be loaded, including - a number of custom stages required to load anything else - */ - virtual void resourceGroupLoadStarted(const String& groupName, size_t resourceCount) {} - /** This event is fired when a declared resource is about to be loaded. - @param resource Weak reference to the resource loaded. - */ - virtual void resourceLoadStarted(const ResourcePtr& resource) {} - /** This event is fired when the resource has been loaded. - */ - virtual void resourceLoadEnded(void) {} - /** This event is fired when a custom loading stage - is about to start. The number of stages required will have been - included in the resourceCount passed in resourceGroupLoadStarted. - @param description Text description of what is about to be done - */ - virtual void customStageStarted(const String& description){} - /** This event is fired when a custom loading stage - has been completed. The number of stages required will have been - included in the resourceCount passed in resourceGroupLoadStarted. - */ - virtual void customStageEnded(void) {} - /** This event is fired when a resource group finished loading. */ - virtual void resourceGroupLoadEnded(const String& groupName) {} - /** This event is fired when a resource was just created. - @param resource Weak reference to the resource created. - */ - virtual void resourceCreated(const ResourcePtr& resource) - { (void)resource; } - /** This event is fired when a resource is about to be removed. - @param resource Weak reference to the resource removed. - */ - virtual void resourceRemove(const ResourcePtr& resource) - { (void)resource; } - }; - - /** - This class allows users to override resource loading behavior. - - By overriding this class' methods, you can change how resources - are loaded and the behavior for resource name collisions. - */ - class ResourceLoadingListener - { - public: - virtual ~ResourceLoadingListener() {} - - /** This event is called when a resource beings loading. */ - virtual DataStreamPtr resourceLoading(const String &name, const String &group, Resource *resource) { return NULL; } - - /** This event is called when a resource stream has been opened, but not processed yet. - - You may alter the stream if you wish or alter the incoming pointer to point at - another stream if you wish. - */ - virtual void resourceStreamOpened(const String &name, const String &group, Resource *resource, DataStreamPtr& dataStream) {} - - /** This event is called when a resource collides with another existing one in a resource manager - - @param resource the new resource that conflicts with an existing one - @param resourceManager the according resource manager - @return false to skip registration of the conflicting resource and continue using the previous instance. - */ - virtual bool resourceCollision(Resource *resource, ResourceManager *resourceManager) { return true; } - }; - - /** This singleton class manages the list of resource groups, and notifying - the various resource managers of their obligations to load / unload - resources in a group. It also provides facilities to monitor resource - loading per group (to do progress bars etc), provided the resources - that are required are pre-registered. - - Defining new resource groups, and declaring the resources you intend to - use in advance is optional, however it is a very useful feature. In addition, - if a ResourceManager supports the definition of resources through scripts, - then this is the class which drives the locating of the scripts and telling - the ResourceManager to parse them. - - @see @ref Resource-Management - */ - class _OgreExport ResourceGroupManager : public Singleton, public ResourceAlloc - { - public: - OGRE_AUTO_MUTEX; // public to allow external locking - /// same as @ref RGN_DEFAULT - static const String DEFAULT_RESOURCE_GROUP_NAME; - /// same as @ref RGN_INTERNAL - static const String INTERNAL_RESOURCE_GROUP_NAME; - /// same as @ref RGN_AUTODETECT - static const String AUTODETECT_RESOURCE_GROUP_NAME; - /// The number of reference counts held per resource by the resource system - static const long RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS; - /// Nested struct defining a resource declaration - struct ResourceDeclaration - { - String resourceName; - String resourceType; - ManualResourceLoader* loader; - NameValuePairList parameters; - }; - /// List of resource declarations - typedef std::list ResourceDeclarationList; - typedef std::map ResourceManagerMap; - typedef MapIterator ResourceManagerIterator; - /// Resource location entry - struct ResourceLocation - { - /// Pointer to the archive which is the destination - Archive* archive; - /// Whether this location was added recursively - bool recursive; - }; - /// List of possible file locations - typedef std::vector LocationList; - - private: - /// Map of resource types (strings) to ResourceManagers, used to notify them to load / unload group contents - ResourceManagerMap mResourceManagerMap; - - /// Map of loading order (Real) to ScriptLoader, used to order script parsing - typedef std::multimap ScriptLoaderOrderMap; - ScriptLoaderOrderMap mScriptLoaderOrderMap; - - typedef std::vector ResourceGroupListenerList; - ResourceGroupListenerList mResourceGroupListenerList; - - ResourceLoadingListener *mLoadingListener; - - /// Resource index entry, resourcename->location - typedef std::map ResourceLocationIndex; - - /// List of resources which can be loaded / unloaded - typedef std::list LoadUnloadResourceList; - /// Resource group entry - struct ResourceGroup - { - enum Status - { - UNINITIALSED = 0, - INITIALISING = 1, - INITIALISED = 2, - LOADING = 3, - LOADED = 4 - }; - /// General mutex for dealing with group content - OGRE_AUTO_MUTEX; - /// Status-specific mutex, separate from content-changing mutex - OGRE_MUTEX(statusMutex); - /// Group name - String name; - /// Group status - Status groupStatus; - /// List of possible locations to search - LocationList locationList; - /// Index of resource names to locations, built for speedy access (case sensitive archives) - ResourceLocationIndex resourceIndexCaseSensitive; -#if !OGRE_RESOURCEMANAGER_STRICT - /// Index of resource names to locations, built for speedy access (case insensitive archives) - ResourceLocationIndex resourceIndexCaseInsensitive; -#endif - /// Pre-declared resources, ready to be created - ResourceDeclarationList resourceDeclarations; - /// Created resources which are ready to be loaded / unloaded - // Group by loading order of the type (defined by ResourceManager) - // (e.g. skeletons and materials before meshes) - typedef std::map LoadResourceOrderMap; - LoadResourceOrderMap loadResourceOrderMap; - uint32 customStageCount; - // in global pool flag - if true the resource will be loaded even a different group was requested in the load method as a parameter. - bool inGlobalPool; - - void addToIndex(const String& filename, Archive* arch); - void removeFromIndex(const String& filename, Archive* arch); - void removeFromIndex(Archive* arch); - - }; - /// Map from resource group names to groups - typedef std::map ResourceGroupMap; - ResourceGroupMap mResourceGroupMap; - - /// Group name for world resources - String mWorldGroupName; - - /** Parses all the available scripts found in the resource locations - for the given group, for all ResourceManagers. - - Called as part of initialiseResourceGroup - */ - void parseResourceGroupScripts(ResourceGroup* grp) const; - /** Create all the pre-declared resources. - - Called as part of initialiseResourceGroup - */ - void createDeclaredResources(ResourceGroup* grp); - /** Adds a created resource to a group. */ - void addCreatedResource(ResourcePtr& res, ResourceGroup& group) const; - /** Get resource group */ - ResourceGroup* getResourceGroup(const String& name, bool throwOnFailure = false) const; - /** Drops contents of a group, leave group there, notify ResourceManagers. */ - void dropGroupContents(ResourceGroup* grp); - /** Delete a group for shutdown - don't notify ResourceManagers. */ - void deleteGroup(ResourceGroup* grp); - /// Internal find method for auto groups - std::pair - resourceExistsInAnyGroupImpl(const String& filename) const; - /// Internal event firing method - void fireResourceGroupScriptingStarted(const String& groupName, size_t scriptCount) const; - /// Internal event firing method - void fireScriptStarted(const String& scriptName, bool &skipScript) const; - /// Internal event firing method - void fireScriptEnded(const String& scriptName, bool skipped) const; - /// Internal event firing method - void fireResourceGroupScriptingEnded(const String& groupName) const; - /// Internal event firing method - void fireResourceGroupLoadStarted(const String& groupName, size_t resourceCount) const; - /// Internal event firing method - void fireResourceLoadStarted(const ResourcePtr& resource) const; - /// Internal event firing method - void fireResourceLoadEnded(void) const; - /// Internal event firing method - void fireResourceGroupLoadEnded(const String& groupName) const; - /// Internal event firing method - void fireResourceGroupPrepareStarted(const String& groupName, size_t resourceCount) const; - /// Internal event firing method - void fireResourcePrepareStarted(const ResourcePtr& resource) const; - /// Internal event firing method - void fireResourcePrepareEnded(void) const; - /// Internal event firing method - void fireResourceGroupPrepareEnded(const String& groupName) const; - /// Internal event firing method - void fireResourceCreated(const ResourcePtr& resource) const; - /// Internal event firing method - void fireResourceRemove(const ResourcePtr& resource) const; - /** Internal modification time retrieval */ - time_t resourceModifiedTime(ResourceGroup* group, const String& filename) const; - - /** Find out if the named file exists in a group. Internal use only - @param group Pointer to the resource group - @param filename Fully qualified name of the file to test for - */ - Archive* resourceExists(ResourceGroup* group, const String& filename) const; - - /** Open resource with optional searching in other groups if it is not found. Internal use only */ - DataStreamPtr openResourceImpl(const String& resourceName, - const String& groupName, - bool searchGroupsIfNotFound, - Resource* resourceBeingLoaded, - bool throwOnFailure = true) const; - - /// Stored current group - optimisation for when bulk loading a group - ResourceGroup* mCurrentGroup; - public: - ResourceGroupManager(); - virtual ~ResourceGroupManager(); - - /** Create a resource group. - - @param name The name to give the resource group. - @param inGlobalPool if true the resource will be loaded even a different - group was requested in the load method as a parameter. - @see @ref Resource-Management - */ - void createResourceGroup(const String& name, bool inGlobalPool = !OGRE_RESOURCEMANAGER_STRICT); - - - /** Initialises a resource group. - @note - When you call Root::initialise, all resource groups that have already been - created are automatically initialised too. Therefore you do not need to - call this method for groups you define and set up before you call - Root::initialise. However, since one of the most useful features of - resource groups is to set them up after the main system initialisation - has occurred (e.g. a group per game level), you must remember to call this - method for the groups you create after this. - - @param name The name of the resource group to initialise - @see @ref Resource-Management - */ - void initialiseResourceGroup(const String& name); - - /** Initialise all resource groups which are yet to be initialised. - @see #initialiseResourceGroup - */ - void initialiseAllResourceGroups(void); - - /** Prepares a resource group. - - Prepares any created resources which are part of the named group. - Note that resources must have already been created by calling - ResourceManager::createResource, or declared using declareResource() or - in a script (such as .material and .overlay). The latter requires - that initialiseResourceGroup() has been called. - - When this method is called, this class will callback any ResourceGroupListener - which have been registered to update them on progress. - @param name The name of the resource group to prepare. - */ - void prepareResourceGroup(const String& name); - - /** Loads a resource group. - - Loads any created resources which are part of the named group. - Note that resources must have already been created by calling - ResourceManager::createResource, or declared using declareResource() or - in a script (such as .material and .overlay). The latter requires - that initialiseResourceGroup() has been called. - - When this method is called, this class will callback any ResourceGroupListeners - which have been registered to update them on progress. - @param name The name of the resource group to load. - */ - void loadResourceGroup(const String& name); - - /** Unloads a resource group. - - This method unloads all the resources that have been declared as - being part of the named resource group. Note that these resources - will still exist in their respective ResourceManager classes, but - will be in an unloaded state. If you want to remove them entirely, - you should use clearResourceGroup() or destroyResourceGroup(). - @param name The name to of the resource group to unload. - @param reloadableOnly If set to true, only unload the resource that is - reloadable. Because some resources isn't reloadable, they will be - unloaded but can't load them later. Thus, you might not want to them - unloaded. Or, you might unload all of them, and then populate them - manually later. - @see Resource::isReloadable for resource is reloadable. - */ - void unloadResourceGroup(const String& name, bool reloadableOnly = true); - - /** Unload all resources which are not referenced by any other object. - - This method behaves like unloadResourceGroup(), except that it only - unloads resources in the group which are not in use, ie not referenced - by other objects. This allows you to free up some memory selectively - whilst still keeping the group around (and the resources present, - just not using much memory). - @param name The name of the group to check for unreferenced resources - @param reloadableOnly If true (the default), only unloads resources - which can be subsequently automatically reloaded - */ - void unloadUnreferencedResourcesInGroup(const String& name, - bool reloadableOnly = true); - - /** Clears a resource group. - - This method unloads all resources in the group, but in addition it - removes all those resources from their ResourceManagers, and then - clears all the members from the list. That means after calling this - method, there are no resources declared as part of the named group - any more. Resource locations still persist though. - @param name The name to of the resource group to clear. - */ - void clearResourceGroup(const String& name); - - /** Destroys a resource group, clearing it first, destroying the resources - which are part of it, and then removing it from - the list of resource groups. - @param name The name of the resource group to destroy. - */ - void destroyResourceGroup(const String& name); - - /** Checks the status of a resource group. - - Looks at the state of a resource group. - If initialiseResourceGroup has been called for the resource - group return true, otherwise return false. - @param name The name to of the resource group to access. - */ - bool isResourceGroupInitialised(const String& name) const; - - /** Checks the status of a resource group. - - Looks at the state of a resource group. - If loadResourceGroup has been called for the resource - group return true, otherwise return false. - @param name The name to of the resource group to access. - */ - bool isResourceGroupLoaded(const String& name) const; - - /*** Verify if a resource group exists - @param name The name of the resource group to look for - */ - bool resourceGroupExists(const String& name) const; - - /** Adds a location to the list of searchable locations for a - Resource type. - - @param - name The name of the location, e.g. './data' or - '/compressed/gamedata.zip' - @param - locType A string identifying the location type, e.g. - 'FileSystem' (for folders), 'Zip' etc. Must map to a - registered plugin which deals with this type (FileSystem and - Zip should always be available) - @param - resGroup the resource group which this location - should apply to; defaults to the General group which applies to - all non-specific resources. - @param - recursive If the resource location has a concept of recursive - directory traversal, enabling this option will mean you can load - resources in subdirectories using only their unqualified name. - The default is to disable this so that resources in subdirectories - with the same name are still unique. - @param readOnly whether the Archive is read only - @see @ref Resource-Management - */ - void addResourceLocation(const String& name, const String& locType, - const String& resGroup = DEFAULT_RESOURCE_GROUP_NAME, bool recursive = false, bool readOnly = true); - /** Removes a resource location from the search path. */ - void removeResourceLocation(const String& name, - const String& resGroup = DEFAULT_RESOURCE_GROUP_NAME); - /** Verify if a resource location exists for the given group. */ - bool resourceLocationExists(const String& name, - const String& resGroup = DEFAULT_RESOURCE_GROUP_NAME) const; - - /** Declares a resource to be a part of a resource group, allowing you - to load and unload it as part of the group. - - @param name The resource name. - @param resourceType The type of the resource. Ogre comes preconfigured with - a number of resource types: -
    -
  • Font
  • -
  • GpuProgram
  • -
  • HighLevelGpuProgram
  • -
  • Material
  • -
  • Mesh
  • -
  • Skeleton
  • -
  • Texture
  • -
- .. but more can be added by plugin ResourceManager classes. - @param groupName The name of the group to which it will belong. - @param loadParameters A list of name / value pairs which supply custom - parameters to the resource which will be required before it can - be loaded. These are specific to the resource type. - @see @ref Resource-Management - */ - void declareResource(const String& name, const String& resourceType, - const String& groupName = DEFAULT_RESOURCE_GROUP_NAME, - const NameValuePairList& loadParameters = NameValuePairList()); - /** @copydoc declareResource - @param loader Pointer to a ManualResourceLoader implementation which will - be called when the Resource wishes to load. If supplied, the resource - is manually loaded, otherwise it'll loading from file automatic. - @note We don't support declare manually loaded resource without loader - here, since it's meaningless. - */ - void declareResource(const String& name, const String& resourceType, - const String& groupName, ManualResourceLoader* loader, - const NameValuePairList& loadParameters = NameValuePairList()); - /** Undeclare a resource. - - Note that this will not cause it to be unloaded - if it is already loaded, nor will it destroy a resource which has - already been created if initialiseResourceGroup has been called already. - Only unloadResourceGroup / clearResourceGroup / destroyResourceGroup - will do that. - @param name The name of the resource. - @param groupName The name of the group this resource was declared in. - */ - void undeclareResource(const String& name, const String& groupName); - - /** Open a single resource by name and return a DataStream - pointing at the source of the data. - @param resourceName The name of the resource to locate. - Even if resource locations are added recursively, you - must provide a fully qualified name to this method. You - can find out the matching fully qualified names by using the - find() method if you need to. - @param groupName The name of the resource group; this determines which - locations are searched. - If you're loading a @ref Resource using #RGN_AUTODETECT, you **must** - also provide the resourceBeingLoaded parameter to enable the - group membership to be changed - @param resourceBeingLoaded Optional pointer to the resource being - loaded, which you should supply if you want - @param throwOnFailure throw an exception. Returns nullptr otherwise - @return Shared pointer to data stream containing the data, will be - destroyed automatically when no longer referenced - */ - DataStreamPtr openResource(const String& resourceName, - const String& groupName = DEFAULT_RESOURCE_GROUP_NAME, - Resource* resourceBeingLoaded = NULL, - bool throwOnFailure = true) const - { - return openResourceImpl(resourceName, groupName, false, - resourceBeingLoaded, throwOnFailure); - } - - /** - @overload - if the resource is not found in the group specified, other groups will be searched. - @deprecated use AUTODETECT_RESOURCE_GROUP_NAME instead of searchGroupsIfNotFound - */ - OGRE_DEPRECATED DataStreamPtr openResource(const String& resourceName, - const String& groupName, - bool searchGroupsIfNotFound, - Resource* resourceBeingLoaded = 0) const - { - return openResourceImpl(resourceName, groupName, searchGroupsIfNotFound, resourceBeingLoaded); - } - - /** Open all resources matching a given pattern (which can contain - the character '*' as a wildcard), and return a collection of - DataStream objects on them. - @param pattern The pattern to look for. If resource locations have been - added recursively, subdirectories will be searched too so this - does not need to be fully qualified. - @param groupName The resource group; this determines which locations - are searched. - @return Shared pointer to a data stream list , will be - destroyed automatically when no longer referenced - */ - DataStreamList openResources(const String& pattern, - const String& groupName = DEFAULT_RESOURCE_GROUP_NAME) const; - - /** List all file or directory names in a resource group. - @note - This method only returns filenames, you can also retrieve other - information using listFileInfo. - @param groupName The name of the group - @param dirs If true, directory names will be returned instead of file names - @return A list of filenames matching the criteria, all are fully qualified - */ - StringVectorPtr listResourceNames(const String& groupName, bool dirs = false) const; - - /** List all files in a resource group with accompanying information. - @param groupName The name of the group - @param dirs If true, directory names will be returned instead of file names - @return A list of structures detailing quite a lot of information about - all the files in the archive. - */ - FileInfoListPtr listResourceFileInfo(const String& groupName, bool dirs = false) const; - - /** Find all file or directory names matching a given pattern in a - resource group. - @note - This method only returns filenames, you can also retrieve other - information using findFileInfo. - @param groupName The name of the group - @param pattern The pattern to search for; wildcards (*) are allowed - @param dirs Set to true if you want the directories to be listed - instead of files - @return A list of filenames matching the criteria, all are fully qualified - */ - StringVectorPtr findResourceNames(const String& groupName, const String& pattern, - bool dirs = false) const; - - /** Find out if the named file exists in a group. - @param group The name of the resource group - @param filename Fully qualified name of the file to test for - */ - bool resourceExists(const String& group, const String& filename) const; - - /** Find out if the named file exists in any group. - @param filename Fully qualified name of the file to test for - */ - bool resourceExistsInAnyGroup(const String& filename) const; - - /** Find the group in which a resource exists. - @param filename Fully qualified name of the file the resource should be - found as - @return Name of the resource group the resource was found in. An - exception is thrown if the group could not be determined. - */ - const String& findGroupContainingResource(const String& filename) const; - - /** Find all files or directories matching a given pattern in a group - and get some detailed information about them. - @param group The name of the resource group - @param pattern The pattern to search for; wildcards (*) are allowed - @param dirs Set to true if you want the directories to be listed - instead of files - @return A list of file information structures for all files matching - the criteria. - */ - FileInfoListPtr findResourceFileInfo(const String& group, const String& pattern, - bool dirs = false) const; - - /** Retrieve the modification time of a given file */ - time_t resourceModifiedTime(const String& group, const String& filename) const; - /** List all resource locations in a resource group. - @param groupName The name of the group - @return A list of resource locations matching the criteria - */ - StringVectorPtr listResourceLocations(const String& groupName) const; - - /** Find all resource location names matching a given pattern in a - resource group. - @param groupName The name of the group - @param pattern The pattern to search for; wildcards (*) are allowed - @return A list of resource locations matching the criteria - */ - StringVectorPtr findResourceLocation(const String& groupName, const String& pattern) const; - - /** Create a new resource file in a given group. - - This method creates a new file in a resource group and passes you back a - writeable stream. - @param filename The name of the file to create - @param groupName The name of the group in which to create the file - @param overwrite If true, an existing file will be overwritten, if false - an error will occur if the file already exists - @param locationPattern If the resource group contains multiple locations, - then usually the file will be created in the first writable location. If you - want to be more specific, you can include a location pattern here and - only locations which match that pattern (as determined by StringUtil::match) - will be considered candidates for creation. - */ - DataStreamPtr createResource(const String& filename, const String& groupName = DEFAULT_RESOURCE_GROUP_NAME, - bool overwrite = false, const String& locationPattern = BLANKSTRING); - - /** Delete a single resource file. - @param filename The name of the file to delete. - @param groupName The name of the group in which to search - @param locationPattern If the resource group contains multiple locations, - then usually first matching file found in any location will be deleted. If you - want to be more specific, you can include a location pattern here and - only locations which match that pattern (as determined by StringUtil::match) - will be considered candidates for deletion. - */ - void deleteResource(const String& filename, const String& groupName = DEFAULT_RESOURCE_GROUP_NAME, - const String& locationPattern = BLANKSTRING); - - /** Delete all matching resource files. - @param filePattern The pattern (see StringUtil::match) of the files to delete. - @param groupName The name of the group in which to search - @param locationPattern If the resource group contains multiple locations, - then usually all matching files in any location will be deleted. If you - want to be more specific, you can include a location pattern here and - only locations which match that pattern (as determined by StringUtil::match) - will be considered candidates for deletion. - */ - void deleteMatchingResources(const String& filePattern, const String& groupName = DEFAULT_RESOURCE_GROUP_NAME, - const String& locationPattern = BLANKSTRING); - - /** Adds a ResourceGroupListener which will be called back during - resource loading events. - */ - void addResourceGroupListener(ResourceGroupListener* l); - /** Removes a ResourceGroupListener */ - void removeResourceGroupListener(ResourceGroupListener* l); - - /** Sets the resource group that 'world' resources will use. - - This is the group which should be used by SceneManagers implementing - world geometry when looking for their resources. Defaults to the - DEFAULT_RESOURCE_GROUP_NAME but this can be altered. - */ - void setWorldResourceGroupName(const String& groupName) {mWorldGroupName = groupName;} - - /// Gets the resource group that 'world' resources will use. - const String& getWorldResourceGroupName(void) const { return mWorldGroupName; } - - /** Declare the number custom loading stages for a resource group - - This allows you to include them in a loading progress report. - @param group The name of the resource group - @param stageCount The number of extra stages - @see #addResourceGroupListener - @see #_notifyCustomStageStarted - @see #_notifyCustomStageEnded - */ - void setCustomStagesForResourceGroup(const String& group, uint32 stageCount); - - uint32 getCustomStagesForResourceGroup(const String& group); - - /** Checks the status of a resource group. - - Looks at the state of a resource group. - If loadResourceGroup has been called for the resource - group return true, otherwise return false. - @param name The name to of the resource group to access. - */ - bool isResourceGroupInGlobalPool(const String& name) const; - - /** Shutdown all ResourceManagers, performed as part of clean-up. */ - void shutdownAll(void); - - - /** Internal method for registering a ResourceManager (which should be - a singleton). Creators of plugins can register new ResourceManagers - this way if they wish. - - ResourceManagers that wish to parse scripts must also call - _registerScriptLoader. - @param resourceType String identifying the resource type, must be unique. - @param rm Pointer to the ResourceManager instance. - */ - void _registerResourceManager(const String& resourceType, ResourceManager* rm); - - /** Internal method for unregistering a ResourceManager. - - ResourceManagers that wish to parse scripts must also call - _unregisterScriptLoader. - @param resourceType String identifying the resource type. - */ - void _unregisterResourceManager(const String& resourceType); - - /** Get the registered resource managers. - */ - const ResourceManagerMap& getResourceManagers() const { return mResourceManagerMap; } - - /// @deprecated use getResourceManagers() - OGRE_DEPRECATED ResourceManagerIterator getResourceManagerIterator() - { return ResourceManagerIterator( - mResourceManagerMap.begin(), mResourceManagerMap.end()); } - - /** Internal method for registering a ScriptLoader. - @remarks ScriptLoaders parse scripts when resource groups are initialised. - @param su Pointer to the ScriptLoader instance. - */ - void _registerScriptLoader(ScriptLoader* su); - - /** Internal method for unregistering a ScriptLoader. - @param su Pointer to the ScriptLoader instance. - */ - void _unregisterScriptLoader(ScriptLoader* su); - - /** Method used to directly query for registered script loaders. - @param pattern The specific script pattern (e.g. *.material) the script loader handles - */ - ScriptLoader *_findScriptLoader(const String &pattern) const; - - /** Internal method for getting a registered ResourceManager. - @param resourceType String identifying the resource type. - */ - ResourceManager* _getResourceManager(const String& resourceType) const; - - /** Internal method called by ResourceManager when a resource is created. - @param res Weak reference to resource - */ - void _notifyResourceCreated(ResourcePtr& res) const; - - /** Internal method called by ResourceManager when a resource is removed. - @param res Weak reference to resource - */ - void _notifyResourceRemoved(const ResourcePtr& res) const; - - /** Internal method to notify the group manager that a resource has - changed group (only applicable for autodetect group) */ - void _notifyResourceGroupChanged(const String& oldGroup, Resource* res) const; - - /** Internal method called by ResourceManager when all resources - for that manager are removed. - @param manager Pointer to the manager for which all resources are being removed - */ - void _notifyAllResourcesRemoved(ResourceManager* manager) const; - - /** Notify this manager that one custom loading stage has been started - - User code should call this method the number of times equal to the value declared - in #setCustomStagesForResourceGroup. - */ - void _notifyCustomStageStarted(const String& description) const; - /** Notify this manager that one custom loading stage has been completed - - User code should call this method the number of times equal to the value declared - #setCustomStagesForResourceGroup. - */ - void _notifyCustomStageEnded(void) const; - - /** Get a list of the currently defined resource groups. - @note This method intentionally returns a copy rather than a reference in - order to avoid any contention issues in multithreaded applications. - @return A copy of list of currently defined groups. - */ - StringVector getResourceGroups(void) const; - /** Get the list of resource declarations for the specified group name. - @note This method intentionally returns a copy rather than a reference in - order to avoid any contention issues in multithreaded applications. - @param groupName The name of the group - @return A copy of list of currently defined resources. - */ - ResourceDeclarationList getResourceDeclarationList(const String& groupName) const; - - /** Get the list of resource locations for the specified group name. - @param groupName The name of the group - @return The list of resource locations associated with the given group. - */ - const LocationList& getResourceLocationList(const String& groupName) const; - - /// Sets a new loading listener - void setLoadingListener(ResourceLoadingListener *listener); - /// Returns the current loading listener - ResourceLoadingListener *getLoadingListener() const; - - /// @copydoc Singleton::getSingleton() - static ResourceGroupManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static ResourceGroupManager* getSingletonPtr(void); - - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreResourceManager.h b/OgreMain/include/OgreResourceManager.h deleted file mode 100644 index d3764819abf..00000000000 --- a/OgreMain/include/OgreResourceManager.h +++ /dev/null @@ -1,508 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ResourceManager_H__ -#define _ResourceManager_H__ - -#include "OgrePrerequisites.h" - -#include "OgreResource.h" -#include "OgreResourceGroupManager.h" -#include "OgreCommon.h" -#include "OgreStringVector.h" -#include "OgreScriptLoader.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** Template class describing a simple pool of items. - */ - template - class Pool - { - protected: - typedef typename std::list ItemList; - ItemList mItems; - OGRE_AUTO_MUTEX; - public: - Pool() {} - virtual ~Pool() {} - - /** Get the next item from the pool. - @return pair indicating whether there was a free item, and the item if so - */ - virtual std::pair removeItem() - { - OGRE_LOCK_AUTO_MUTEX; - std::pair ret; - if (mItems.empty()) - { - ret.first = false; - } - else - { - ret.first = true; - ret.second = mItems.front(); - mItems.pop_front(); - } - return ret; - } - - /** Add a new item to the pool. - */ - virtual void addItem(const T& i) - { - OGRE_LOCK_AUTO_MUTEX; - mItems.push_front(i); - } - /// Clear the pool - virtual void clear() - { - OGRE_LOCK_AUTO_MUTEX; - mItems.clear(); - } - }; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - /** Defines a generic resource handler. - @see @ref Resource-Management - @note - If OGRE_THREAD_SUPPORT is 1, this class is thread-safe. - */ - class _OgreExport ResourceManager : public ScriptLoader, public ResourceAlloc - { - public: - OGRE_AUTO_MUTEX; // public to allow external locking - ResourceManager(); - virtual ~ResourceManager(); - - /** Creates a new blank resource, but does not immediately load it. - @param name The unique name of the %Resource - @param group The name of the resource group to attach this new resource to - @param isManual Is this resource manually loaded? If so, you should really - populate the loader parameter in order that the load process - can call the loader back when loading is required. - @param loader Pointer to a ManualLoader implementation which will be called - when the Resource wishes to load (should be supplied if you set - isManual to true). You can in fact leave this parameter null - if you wish, but the Resource will never be able to reload if - anything ever causes it to unload. Therefore provision of a proper - ManualLoader instance is strongly recommended. - @param createParams If any parameters are required to create an instance, - they should be supplied here as name / value pairs - */ - ResourcePtr createResource(const String& name, const String& group, - bool isManual = false, ManualResourceLoader* loader = 0, - const NameValuePairList* createParams = 0); - - typedef std::pair ResourceCreateOrRetrieveResult; - /** Create a new resource, or retrieve an existing one with the same - name if it already exists. - - This method performs the same task as calling getByName() followed - by create() if that returns null. The advantage is that it does it - in one call so there are no race conditions if using multiple - threads that could cause getByName() to return null, but create() to - fail because another thread created a resource in between. - @copydetails ResourceManager::createResource - @return A pair, the first element being the pointer, and the second being - an indicator specifying whether the resource was newly created. - */ - ResourceCreateOrRetrieveResult createOrRetrieve(const String& name, - const String& group, bool isManual = false, - ManualResourceLoader* loader = 0, - const NameValuePairList* createParams = 0); - - /** Set a limit on the amount of memory this resource handler may use. - - If, when asked to load a new resource, the manager believes it will exceed this memory - budget, it will temporarily unload a resource to make room for the new one. This unloading - is not permanent and the Resource is not destroyed; it simply needs to be reloaded when - next used. - */ - void setMemoryBudget(size_t bytes); - - /** Get the limit on the amount of memory this resource handler may use. - */ - size_t getMemoryBudget(void) const; - - /** Gets the current memory usage, in bytes. */ - size_t getMemoryUsage(void) const { return mMemoryUsage.load(); } - - /** Unloads a single resource by name. - - Unloaded resources are not removed, they simply free up their memory - as much as they can and wait to be reloaded. - @see ResourceGroupManager for unloading of resource groups. - */ - void unload(const String& name, const String& group OGRE_RESOURCE_GROUP_INIT); - - /** Unloads a single resource by handle. - - Unloaded resources are not removed, they simply free up their memory - as much as they can and wait to be reloaded. - @see ResourceGroupManager for unloading of resource groups. - */ - void unload(ResourceHandle handle); - - /** Unloads all resources. - - Unloaded resources are not removed, they simply free up their memory - as much as they can and wait to be reloaded. - @see ResourceGroupManager for unloading of resource groups. - @param reloadableOnly If true (the default), only unload the resource that - is reloadable. Because some resources isn't reloadable, they will be - unloaded but can't load them later. Thus, you might not want to them - unloaded. Or, you might unload all of them, and then populate them - manually later. - @see Resource::isReloadable for resource is reloadable. - */ - void unloadAll(bool reloadableOnly = true) - { unloadAll(reloadableOnly ? Resource::LF_DEFAULT : Resource::LF_INCLUDE_NON_RELOADABLE); } - - /** Caused all currently loaded resources to be reloaded. - - All resources currently being held in this manager which are also - marked as currently loaded will be unloaded, then loaded again. - @param reloadableOnly If true (the default), only reload the resource that - is reloadable. Because some resources isn't reloadable, they will be - unloaded but can't loaded again. Thus, you might not want to them - unloaded. Or, you might unload all of them, and then populate them - manually later. - @see Resource::isReloadable for resource is reloadable. - */ - void reloadAll(bool reloadableOnly = true) - { reloadAll(reloadableOnly ? Resource::LF_DEFAULT : Resource::LF_INCLUDE_NON_RELOADABLE); } - - /** Unload all resources which are not referenced by any other object. - - This method behaves like unloadAll, except that it only unloads resources - which are not in use, ie not referenced by other objects. This allows you - to free up some memory selectively whilst still keeping the group around - (and the resources present, just not using much memory). - @par - Some referenced resource may exists 'weak' pointer to their sub-components - (e.g. Entity held pointer to SubMesh), in this case, unload or reload that - resource will cause dangerous pointer access. Use this function instead of - unloadAll allows you avoid fail in those situations. - @param reloadableOnly If true (the default), only unloads resources - which can be subsequently automatically reloaded. - */ - void unloadUnreferencedResources(bool reloadableOnly = true) - { unloadAll(reloadableOnly ? Resource::LF_ONLY_UNREFERENCED : Resource::LF_ONLY_UNREFERENCED_INCLUDE_NON_RELOADABLE); } - - /** Caused all currently loaded but not referenced by any other object - resources to be reloaded. - - This method behaves like reloadAll, except that it only reloads resources - which are not in use, i.e. not referenced by other objects. - @par - Some referenced resource may exists 'weak' pointer to their sub-components - (e.g. Entity held pointer to SubMesh), in this case, unload or reload that - resource will cause dangerous pointer access. Use this function instead of - reloadAll allows you avoid fail in those situations. - @param reloadableOnly If true (the default), only reloads resources - which can be subsequently automatically reloaded. - */ - void reloadUnreferencedResources(bool reloadableOnly = true) - { reloadAll(reloadableOnly ? Resource::LF_ONLY_UNREFERENCED : Resource::LF_ONLY_UNREFERENCED_INCLUDE_NON_RELOADABLE); } - - /** Unloads all resources. - - Unloaded resources are not removed, they simply free up their memory - as much as they can and wait to be reloaded. - @see ResourceGroupManager for unloading of resource groups. - @param flags Allow to restrict processing to only reloadable and/or - unreferenced resources. - @see Resource::LoadingFlags for additional information. - */ - virtual void unloadAll(Resource::LoadingFlags flags); - - /** Caused all currently loaded resources to be reloaded. - - All resources currently being held in this manager which are also - marked as currently loaded will be unloaded, then loaded again. - @param flags Allow to restrict processing to only reloadable and/or - unreferenced resources. Additionally, reloading could be done with - preserving some selected resource states that could be used elsewhere. - @see Resource::LoadingFlags for additional information. - */ - virtual void reloadAll(Resource::LoadingFlags flags); - - /** Remove a single resource. - - Removes a single resource, meaning it will be removed from the list - of valid resources in this manager, also causing it to be unloaded. - @note - The word 'Destroy' is not used here, since - if any other pointers are referring to this resource, it will persist - until they have finished with it; however to all intents and purposes - it no longer exists and will likely get destroyed imminently. - @note - If you do have shared pointers to resources hanging around after the - ResourceManager is destroyed, you may get problems on destruction of - these resources if they were relying on the manager (especially if - it is a plugin). If you find you get problems on shutdown in the - destruction of resources, try making sure you release all your - shared pointers before you shutdown OGRE. - */ - void remove(const ResourcePtr& r); - - /// @overload - void remove(const String& name, const String& group OGRE_RESOURCE_GROUP_INIT); - - /// @overload - void remove(ResourceHandle handle); - /** Removes all resources. - @note - The word 'Destroy' is not used here, since - if any other pointers are referring to these resources, they will persist - until they have been finished with; however to all intents and purposes - the resources no longer exist and will get destroyed imminently. - @note - If you do have shared pointers to resources hanging around after the - ResourceManager is destroyed, you may get problems on destruction of - these resources if they were relying on the manager (especially if - it is a plugin). If you find you get problems on shutdown in the - destruction of resources, try making sure you release all your - shared pointers before you shutdown OGRE. - */ - virtual void removeAll(void); - - /** Remove all resources which are not referenced by any other object. - - This method behaves like removeAll, except that it only removes resources - which are not in use, ie not referenced by other objects. This allows you - to free up some memory selectively whilst still keeping the group around - (and the resources present, just not using much memory). - @par - Some referenced resource may exists 'weak' pointer to their sub-components - (e.g. Entity held pointer to SubMesh), in this case, remove or reload that - resource will cause dangerous pointer access. Use this function instead of - removeAll allows you avoid fail in those situations. - @param reloadableOnly If true (the default), only removes resources - which can be subsequently automatically reloaded. - */ - virtual void removeUnreferencedResources(bool reloadableOnly = true); - - /** Retrieves a pointer to a resource by name, or null if the resource does not exist. - */ - virtual ResourcePtr getResourceByName(const String& name, const String& groupName OGRE_RESOURCE_GROUP_INIT) const; - - /** Retrieves a pointer to a resource by handle, or null if the resource does not exist. - */ - virtual ResourcePtr getByHandle(ResourceHandle handle) const; - - /// Returns whether the named resource exists in this manager - bool resourceExists(const String& name, const String& group OGRE_RESOURCE_GROUP_INIT) const - { - return getResourceByName(name, group).get() != 0; - } - /// Returns whether a resource with the given handle exists in this manager - bool resourceExists(ResourceHandle handle) const - { - return getByHandle(handle).get() != 0; - } - - /** Notify this manager that a resource which it manages has been - 'touched', i.e. used. - */ - virtual void _notifyResourceTouched(Resource* res); - - /** Notify this manager that a resource which it manages has been - loaded. - */ - virtual void _notifyResourceLoaded(Resource* res); - - /** Notify this manager that a resource which it manages has been - unloaded. - */ - virtual void _notifyResourceUnloaded(Resource* res); - - /** Generic prepare method, used to create a Resource specific to this - ResourceManager without using one of the specialised 'prepare' methods - (containing per-Resource-type parameters). - @param name The name of the %Resource - @param group The resource group to which this resource will belong - @param isManual Is the resource to be manually loaded? If so, you should - provide a value for the loader parameter - @param loader The manual loader which is to perform the required actions - when this resource is loaded; only applicable when you specify true - for the previous parameter - @param loadParams Optional pointer to a list of name/value pairs - containing loading parameters for this type of resource. - @param backgroundThread Optional boolean which lets the load routine know if it - is being run on the background resource loading thread - */ - ResourcePtr prepare(const String& name, - const String& group, bool isManual = false, - ManualResourceLoader* loader = 0, const NameValuePairList* loadParams = 0, - bool backgroundThread = false); - - /** Generic load method, used to create a Resource specific to this - ResourceManager without using one of the specialised 'load' methods - (containing per-Resource-type parameters). - @copydetails ResourceManager::prepare() - */ - ResourcePtr load(const String& name, - const String& group, bool isManual = false, - ManualResourceLoader* loader = 0, const NameValuePairList* loadParams = 0, - bool backgroundThread = false); - - const StringVector& getScriptPatterns(void) const override { return mScriptPatterns; } - void parseScript(DataStreamPtr& stream, const String& groupName) override; - Real getLoadingOrder(void) const override { return mLoadOrder; } - - /** Gets a string identifying the type of resource this manager handles. */ - const String& getResourceType(void) const { return mResourceType; } - - /** Sets whether this manager and its resources habitually produce log output */ - void setVerbose(bool v) { mVerbose = v; } - - /** Gets whether this manager and its resources habitually produce log output */ - bool getVerbose(void) { return mVerbose; } - - /** Definition of a pool of resources, which users can use to reuse similar - resources many times without destroying and recreating them. - - This is a simple utility class which allows the reuse of resources - between code which has a changing need for them. For example, - */ - class _OgreExport ResourcePool : public Pool, public ResourceAlloc - { - String mName; - public: - ResourcePool(const String& name); - ~ResourcePool(); - /// Get the name of the pool - const String& getName() const; - void clear() override; - }; - - /// Create a resource pool, or reuse one that already exists - ResourcePool* getResourcePool(const String& name); - /// Destroy a resource pool - void destroyResourcePool(ResourcePool* pool); - /// Destroy a resource pool - void destroyResourcePool(const String& name); - /// destroy all pools - void destroyAllResourcePools(); - - - - - protected: - - /** Allocates the next handle. */ - ResourceHandle getNextHandle(void); - - /** Create a new resource instance compatible with this manager (no custom - parameters are populated at this point). - - Subclasses must override this method and create a subclass of Resource. - @param name The unique name of the resource - @param handle The unique handle of the resource - @param group The name of the resource group to attach this new resource to - @param isManual Is this resource manually loaded? If so, you should really - populate the loader parameter in order that the load process - can call the loader back when loading is required. - @param loader Pointer to a ManualLoader implementation which will be called - when the Resource wishes to load (should be supplied if you set - isManual to true). You can in fact leave this parameter null - if you wish, but the Resource will never be able to reload if - anything ever causes it to unload. Therefore provision of a proper - ManualLoader instance is strongly recommended. - @param createParams If any parameters are required to create an instance, - they should be supplied here as name / value pairs. These do not need - to be set on the instance (handled elsewhere), just used if required - to differentiate which concrete class is created. - - */ - virtual Resource* createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams) = 0; - /** Add a newly created resource to the manager (note weak reference) */ - virtual void addImpl( ResourcePtr& res ); - /** Remove a resource from this manager; remove it from the lists. */ - virtual void removeImpl(const ResourcePtr& res ); - /** Checks memory usage and pages out if required. This is automatically done after a new resource is loaded. - */ - void checkUsage(void); - - - public: - typedef std::unordered_map< String, ResourcePtr > ResourceMap; - typedef std::unordered_map< String, ResourceMap > ResourceWithGroupMap; - typedef std::map ResourceHandleMap; - protected: - ResourceHandleMap mResourcesByHandle; - ResourceMap mResources; - ResourceWithGroupMap mResourcesWithGroup; - size_t mMemoryBudget; /// In bytes - std::atomic mNextHandle; - std::atomic mMemoryUsage; /// In bytes - - bool mVerbose; - - // IMPORTANT - all subclasses must populate the fields below - - /// Patterns to use to look for scripts if supported (e.g. *.overlay) - StringVector mScriptPatterns; - /// Loading order relative to other managers, higher is later - Real mLoadOrder; - /// String identifying the resource type this manager handles - String mResourceType; - - public: - typedef MapIterator ResourceMapIterator; - /** Returns an iterator over all resources in this manager. - @note - Use of this iterator is NOT thread safe! - */ - ResourceMapIterator getResourceIterator(void) - { - return ResourceMapIterator(mResourcesByHandle.begin(), mResourcesByHandle.end()); - } - - protected: - typedef std::map ResourcePoolMap; - ResourcePoolMap mResourcePoolMap; - }; - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreRibbonTrail.h b/OgreMain/include/OgreRibbonTrail.h deleted file mode 100644 index f5cebdab437..00000000000 --- a/OgreMain/include/OgreRibbonTrail.h +++ /dev/null @@ -1,228 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __RibbonTrail_H__ -#define __RibbonTrail_H__ - -#include "OgrePrerequisites.h" - -#include "OgreBillboardChain.h" -#include "OgreNode.h" -#include "OgreControllerManager.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - /** Subclass of BillboardChain which automatically leaves a trail behind - one or more Node instances. - - An instance of this class will watch one or more Node instances, and - automatically generate a trail behind them as they move. Because this - class can monitor multiple modes, it generates its own geometry in - world space and thus, even though it has to be attached to a SceneNode - to be visible, changing the position of the scene node it is attached to - makes no difference to the geometry rendered. - @par - The 'head' element grows smoothly in size until it reaches the required size, - then a new element is added. If the segment is full, the tail element - shrinks by the same proportion as the head grows before disappearing. - @par - Elements can be faded out on a time basis, either by altering their colour - or altering their alpha. The width can also alter over time. - @par - 'v' texture coordinates are fixed at 0.0 if used, meaning that you can - use a 1D texture to 'smear' a colour pattern along the ribbon if you wish. - The 'u' coordinates are by default (0.0, 1.0), but you can alter this - using setOtherTexCoordRange if you wish. - */ - class _OgreExport RibbonTrail : public BillboardChain, public Node::Listener - { - public: - /** Constructor (don't use directly, use factory) - @param name The name to give this object - @param maxElements The maximum number of elements per chain - @param numberOfChains The number of separate chain segments contained in this object, - ie the maximum number of nodes that can have trails attached - @param useTextureCoords If true, use texture coordinates from the chain elements - @param useVertexColours If true, use vertex colours from the chain elements (must - be true if you intend to use fading) - */ - RibbonTrail(const String& name, size_t maxElements = 20, size_t numberOfChains = 1, - bool useTextureCoords = true, bool useVertexColours = true); - /// destructor - virtual ~RibbonTrail(); - - typedef std::vector NodeList; - typedef ConstVectorIterator NodeIterator; - - /** Add a node to be tracked. - @param n The node that will be tracked. - */ - virtual void addNode(Node* n); - /** Remove tracking on a given node. */ - virtual void removeNode(const Node* n); - /** Get an iterator over the nodes which are being tracked. */ - virtual NodeIterator getNodeIterator(void) const; - /** Get the chain index for a given Node being tracked. */ - virtual size_t getChainIndexForNode(const Node* n); - - /** Set the length of the trail. - - This sets the length of the trail, in world units. It also sets how - far apart each segment will be, ie length / max_elements. - @param len The length of the trail in world units - */ - void setTrailLength(Real len); - /** Get the length of the trail. */ - Real getTrailLength(void) const { return mTrailLength; } - - /** @copydoc BillboardChain::setMaxChainElements */ - void setMaxChainElements(size_t maxElements) override; - /** @copydoc BillboardChain::setNumberOfChains */ - void setNumberOfChains(size_t numChains) override; - /** @copydoc BillboardChain::clearChain */ - void clearChain(size_t chainIndex) override; - - /** Set the starting ribbon colour for a given segment. - @param chainIndex The index of the chain - @param col The initial colour - @note - Only used if this instance is using vertex colours. - */ - virtual void setInitialColour(size_t chainIndex, const ColourValue& col); - /** Set the starting ribbon colour. - @param chainIndex The index of the chain - @param r,b,g,a The initial colour - @note - Only used if this instance is using vertex colours. - */ - virtual void setInitialColour(size_t chainIndex, float r, float g, float b, float a = 1.0); - /** Get the starting ribbon colour. */ - const ColourValue& getInitialColour(size_t chainIndex) const { return mInitialColour.at(chainIndex); } - - /** Enables / disables fading the trail using colour. - @param chainIndex The index of the chain - @param valuePerSecond The amount to subtract from colour each second - */ - virtual void setColourChange(size_t chainIndex, const ColourValue& valuePerSecond); - - /** Set the starting ribbon width in world units. - @param chainIndex The index of the chain - @param width The initial width of the ribbon - */ - virtual void setInitialWidth(size_t chainIndex, Real width); - /** Get the starting ribbon width in world units. */ - Real getInitialWidth(size_t chainIndex) const { return mInitialWidth.at(chainIndex); } - - /** Set the change in ribbon width per second. - @param chainIndex The index of the chain - @param widthDeltaPerSecond The amount the width will reduce by per second - */ - virtual void setWidthChange(size_t chainIndex, Real widthDeltaPerSecond); - /** Get the change in ribbon width per second. */ - Real getWidthChange(size_t chainIndex) const { return mDeltaWidth.at(chainIndex); } - - /** Enables / disables fading the trail using colour. - @param chainIndex The index of the chain - @param r,g,b,a The amount to subtract from each colour channel per second - */ - virtual void setColourChange(size_t chainIndex, float r, float g, float b, float a); - - /** Get the per-second fading amount */ - const ColourValue& getColourChange(size_t chainIndex) const { return mDeltaColour.at(chainIndex); } - - /// @see Node::Listener::nodeUpdated - void nodeUpdated(const Node* node) override; - /// @see Node::Listener::nodeDestroyed - void nodeDestroyed(const Node* node) override; - - /// Perform any fading / width delta required; internal method - virtual void _timeUpdate(Real time); - - const String& getMovableType(void) const override; - - private: - /// List of nodes being trailed - NodeList mNodeList; - /// Mapping of nodes to chain segments - typedef std::vector IndexVector; - /// Ordered like mNodeList, contains chain index - IndexVector mNodeToChainSegment; - // chains not in use - IndexVector mFreeChains; - - // fast lookup node->chain index - // we use positional map too because that can be useful - typedef std::map NodeToChainSegmentMap; - NodeToChainSegmentMap mNodeToSegMap; - - /// Total length of trail in world units - Real mTrailLength; - /// length of each element - Real mElemLength; - /// Squared length of each element - Real mSquaredElemLength; - typedef std::vector ColourValueList; - typedef std::vector RealList; - /// Initial colour of the ribbon - ColourValueList mInitialColour; - /// fade amount per second - ColourValueList mDeltaColour; - /// Initial width of the ribbon - RealList mInitialWidth; - /// Delta width of the ribbon - RealList mDeltaWidth; - /// controller used to hook up frame time to fader - ControllerFloat* mFadeController; - /// controller value for hooking up frame time to fader - ControllerValueRealPtr mTimeControllerValue; - - /// Manage updates to the time controller - void manageController(void); - /// Node has changed position, update - void updateTrail(size_t index, const Node* node); - /// Reset the tracked chain to initial state - void resetTrail(size_t index, const Node* node); - /// Reset all tracked chains to initial state - void resetAllTrails(void); - - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreRoot.h b/OgreMain/include/OgreRoot.h deleted file mode 100644 index 6c1028c4be8..00000000000 --- a/OgreMain/include/OgreRoot.h +++ /dev/null @@ -1,942 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ROOT__ -#define __ROOT__ - -// Precompiler options -#include "OgrePrerequisites.h" - -#include -#include -#include "OgreSingleton.h" -#include "OgreSceneManager.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - - class AndroidLogListener; - class ShadowTextureManager; - class SceneManagerEnumerator; - - typedef std::vector RenderSystemList; - - /// Scene manager instances, indexed by instance name - typedef std::map SceneManagerInstanceMap; - - /** The root class of the Ogre system. - - The Ogre::Root class represents a starting point for the client - application. From here, the application can gain access to the - fundamentals of the system, namely the rendering systems - available, management of saved configurations, logging, and - access to other classes in the system. Acts as a hub from which - all other objects may be reached. An instance of Root must be - created before any other Ogre operations are called. Once an - instance has been created, the same instance is accessible - throughout the life of that object by using Root::getSingleton - (as a reference) or Root::getSingletonPtr (as a pointer). - */ - class _OgreExport Root : public Singleton, public RootAlloc - { - // To allow update of active renderer if - // RenderSystem::initialise is used directly - friend class RenderSystem; - public: - typedef std::map MovableObjectFactoryMap; - typedef std::vector PluginLibList; - typedef std::vector PluginInstanceList; - private: - RenderSystemList mRenderers; - RenderSystem* mActiveRenderer; - String mVersion; - String mConfigFileName; - bool mQueuedEnd; - // In case multiple render windows are created, only once are the resources loaded. - bool mFirstTimePostWindowInit; - - // ordered in reverse destruction sequence - std::unique_ptr mLogManager; -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - std::unique_ptr mAndroidLogger; -#endif - std::unique_ptr mCompilerManager; - std::unique_ptr mDynLibManager; - std::unique_ptr mTimer; - std::unique_ptr mWorkQueue; - std::unique_ptr mResourceGroupManager; - std::unique_ptr mResourceBackgroundQueue; - std::unique_ptr mMaterialManager; - std::unique_ptr mGpuProgramManager; - std::unique_ptr mControllerManager; - std::unique_ptr mMeshManager; - std::unique_ptr mSkeletonManager; - - std::unique_ptr mFileSystemArchiveFactory; - std::unique_ptr mEmbeddedZipArchiveFactory; - std::unique_ptr mZipArchiveFactory; - std::unique_ptr mArchiveManager; - - MovableObjectFactoryMap mMovableObjectFactoryMap; - std::unique_ptr mRibbonTrailFactory; - std::unique_ptr mBillboardChainFactory; - std::unique_ptr mManualObjectFactory; - std::unique_ptr mBillboardSetFactory; - std::unique_ptr mLightFactory; - std::unique_ptr mEntityFactory; - std::unique_ptr mStaticGeometryFactory; - std::unique_ptr mRectangle2DFactory; - - std::unique_ptr mParticleManager; - std::unique_ptr mLodStrategyManager; - std::unique_ptr mProfiler; - - std::unique_ptr mExternalTextureSourceManager; - std::unique_ptr mCompositorManager; - std::unique_ptr mRenderSystemCapabilitiesManager; - - std::unique_ptr mSceneManagerEnum; - SceneManager* mCurrentSceneManager; - - std::unique_ptr mShadowTextureManager; - - RenderWindow* mAutoWindow; - - unsigned long mNextFrame; - Real mFrameSmoothingTime; - bool mRemoveQueueStructuresOnClear; - Real mDefaultMinPixelSize; - - private: - /// List of plugin DLLs loaded - PluginLibList mPluginLibs; - /// List of Plugin instances registered - PluginInstanceList mPlugins; - - uint32 mNextMovableObjectTypeFlag; - - /// Are we initialised yet? - bool mIsInitialised; - ///Tells whether blend indices information needs to be passed to the GPU - bool mIsBlendIndicesGpuRedundant; - ///Tells whether blend weights information needs to be passed to the GPU - bool mIsBlendWeightsGpuRedundant; - - /** Method reads a plugins configuration file and instantiates all - plugins. - @param - pluginsfile The file that contains plugins information. - */ - void loadPlugins(const String& pluginsfile = "plugins.cfg"); - /** Initialise all loaded plugins - allows plugins to perform actions - once the renderer is initialised. - */ - void initialisePlugins(); - /** Shuts down all loaded plugins - allows things to be tidied up whilst - all plugins are still loaded. - */ - void shutdownPlugins(); - - /** Unloads all loaded plugins. - */ - void unloadPlugins(); - - /// Internal method for one-time tasks after first window creation - void oneTimePostWindowInit(void); - - /** Set of registered frame listeners */ - std::set mFrameListeners; - - /** Set of frame listeners marked for removal and addition*/ - std::set mRemovedFrameListeners; - std::set mAddedFrameListeners; - void _syncAddedRemovedFrameListeners(); - - /** Indicates the type of event to be considered by calculateEventTime(). */ - enum FrameEventTimeType { - FETT_ANY = 0, - FETT_STARTED = 1, - FETT_QUEUED = 2, - FETT_ENDED = 3, - FETT_COUNT = 4 - }; - - /// Contains the times of recently fired events - typedef std::deque EventTimesQueue; - EventTimesQueue mEventTimes[FETT_COUNT]; - - /** Internal method for calculating the average time between recently fired events. - @param now The current time in ms. - @param type The type of event to be considered. - */ - Real calculateEventTime(unsigned long now, FrameEventTimeType type); - - /** Update a set of event times (note, progressive, only call once for each type per frame) */ - void populateFrameEvent(FrameEventTimeType type, FrameEvent& evtToUpdate); - - public: - - /** Constructor - @param pluginFileName The file that contains plugins information. - May be left blank to ignore. - @param configFileName The file that contains the configuration to be loaded. - Defaults to "ogre.cfg", may be left blank to load nothing. - @param logFileName The logfile to create, defaults to Ogre.log, may be - left blank if you've already set up LogManager & Log yourself - */ - Root(const String& pluginFileName = "plugins.cfg", - const String& configFileName = "ogre.cfg", - const String& logFileName = "Ogre.log"); - ~Root(); - - /** Saves the details of the current configuration - - Stores details of the current configuration so it may be - restored later on. - */ - void saveConfig(void); - - /** Checks for saved video/sound/etc settings - - This method checks to see if there is a valid saved configuration - from a previous run. If there is, the state of the system will - be restored to that configuration. - - @return - If a valid configuration was found, true is returned. - @par - If there is no saved configuration, or if the system failed - with the last config settings, false is returned. - */ - bool restoreConfig(void); - - /** Displays a dialog asking the user to choose system settings. - - This method displays the default dialog allowing the user to - choose the rendering system, video mode etc. If there is are - any settings saved already, they will be restored automatically - before displaying the dialogue. When the user accepts a group of - settings, this will automatically call Root::setRenderSystem, - RenderSystem::setConfigOption and Root::saveConfig with the - user's choices. This is the easiest way to get the system - configured. - @param dialog ConfigDialog implementation to use. - If NULL, the first available render system with the default options - will be selected. - @return - If the user clicked 'Ok', true is returned. - @par - If they clicked 'Cancel' (in which case the app should - strongly consider terminating), false is returned. - */ - bool showConfigDialog(ConfigDialog* dialog); - - /** Adds a new rendering subsystem to the list of available renderers. - - Intended for use by advanced users and plugin writers only! - Calling this method with a pointer to a valid RenderSystem - (subclass) adds a rendering API implementation to the list of - available ones. Typical examples would be an OpenGL - implementation and a Direct3D implementation. - @note -
This should usually be called from the dllStartPlugin() - function of an extension plug-in. - */ - void addRenderSystem(RenderSystem* newRend); - - /** Retrieve a list of the available render systems. - - Retrieves a pointer to the list of available renderers as a - list of RenderSystem subclasses. Can be used to build a - custom settings dialog. - */ - const RenderSystemList& getAvailableRenderers(void); - - /** Retrieve a pointer to the render system by the given name - @param - name Name of the render system intend to retrieve. - @return - A pointer to the render system, NULL if no found. - */ - RenderSystem* getRenderSystemByName(const String& name); - - /** Sets the rendering subsystem to be used. - - This method indicates to OGRE which rendering system is to be - used (e.g. Direct3D, OpenGL etc). This is called - automatically by the default config dialog, and when settings - are restored from a previous configuration. If used manually - it could be used to set the renderer from a custom settings - dialog. Once this has been done, the renderer can be - initialised using Root::initialise. - @par - This method is also called by render systems if they are - initialised directly. - @param - system Pointer to the render system to use. - @see - RenderSystem - */ - void setRenderSystem(RenderSystem* system); - - /** Retrieve a pointer to the currently selected render system. - */ - RenderSystem* getRenderSystem(void); - - /** Initialises the renderer. - - This method can only be called after a renderer has been - selected with Root::setRenderSystem, and it will initialise - the selected rendering system ready for use. - @param - autoCreateWindow If true, a rendering window will - automatically be created (saving a call to - Root::createRenderWindow). The window will be - created based on the options currently set on the render - system. - @param windowTitle - @return - A pointer to the automatically created window, if - requested, otherwise NULL. - */ - RenderWindow* initialise(bool autoCreateWindow, const String& windowTitle = "OGRE Render Window"); - - /** Returns whether the system is initialised or not. */ - bool isInitialised(void) const { return mIsInitialised; } - - /** Requests active RenderSystem to use custom RenderSystemCapabilities - - This is useful for testing how the RenderSystem would behave on a machine with - less advanced GPUs. This method MUST be called before creating the first RenderWindow - */ - void useCustomRenderSystemCapabilities(RenderSystemCapabilities* capabilities); - - /** Get whether the entire render queue structure should be emptied on clearing, - or whether just the objects themselves should be cleared. - */ - bool getRemoveRenderQueueStructuresOnClear() const { return mRemoveQueueStructuresOnClear; } - - /** Set whether the entire render queue structure should be emptied on clearing, - or whether just the objects themselves should be cleared. - */ - void setRemoveRenderQueueStructuresOnClear(bool r) { mRemoveQueueStructuresOnClear = r; } - - /** Register a new SceneManagerFactory, a factory object for creating instances - of specific SceneManagers. - - Plugins should call this to register as new SceneManager providers. - */ - void addSceneManagerFactory(SceneManagerFactory* fact); - - /** Remove a SceneManagerFactory. - */ - void removeSceneManagerFactory(SceneManagerFactory* fact); - - /// get all types of SceneManager available for construction - const StringVector& getSceneManagerTypes() const; - - /// create a default scene manager - SceneManager* createSceneManager() { return createSceneManager(SMT_DEFAULT); } - - /** Create a SceneManager instance of a given type. - - You can use this method to create a SceneManager instance of a - given specific type. You may know this type already, or you may - have discovered it by looking at the results from getMetaDataIterator. - @note - This method throws an exception if the named type is not found. - @param typeName String identifying a unique SceneManager type - @param instanceName Optional name to given the new instance that is - created. If you leave this blank, an auto name will be assigned. - */ - SceneManager* createSceneManager(const String& typeName, const String& instanceName = BLANKSTRING); - - /// @deprecated do not use - OGRE_DEPRECATED SceneManager* createSceneManager(uint16 typeMask, const String& instanceName = BLANKSTRING) - { - return createSceneManager(SMT_DEFAULT, instanceName); - } - - /** Destroy an instance of a SceneManager. */ - void destroySceneManager(SceneManager* sm); - - /** Get an existing SceneManager instance that has already been created, - identified by the instance name. - @param instanceName The name of the instance to retrieve. - */ - SceneManager* getSceneManager(const String& instanceName) const; - - /** Identify if a SceneManager instance already exists. - @param instanceName The name of the instance to retrieve. - */ - bool hasSceneManager(const String& instanceName) const; - - /// Get all the existing SceneManager instances. - const SceneManagerInstanceMap& getSceneManagers(void) const; - - /** Retrieves a reference to the current TextureManager. - - This performs the same function as - TextureManager::getSingleton, but is provided for convenience - particularly to scripting engines. - @par - Note that a TextureManager will NOT be available until the - Ogre system has been initialised by selecting a RenderSystem, - calling Root::initialise and a window having been created - (this may have been done by initialise if required). This is - because the exact runtime subclass which will be implementing - the calls will differ depending on the rendering engine - selected, and these typically require a window upon which to - base texture format decisions. - */ - TextureManager* getTextureManager(void); - - /** Retrieves a reference to the current MeshManager. - - This performs the same function as MeshManager::getSingleton - and is provided for convenience to scripting engines. - */ - MeshManager* getMeshManager(void); - - /** Registers a FrameListener which will be called back every frame. - - A FrameListener is a class which implements methods which - will be called every frame. - @par - See the FrameListener class for more details on the specifics - It is imperative that the instance passed to this method is - not destroyed before either the rendering loop ends, or the - class is removed from the listening list using - removeFrameListener. - @note -
This method can only be called after Root::initialise has - been called. - @see - FrameListener, Root::removeFrameListener - */ - void addFrameListener(FrameListener* newListener); - - /** Removes a FrameListener from the list of listening classes. - @see - FrameListener, Root::addFrameListener - */ - void removeFrameListener(FrameListener* oldListener); - - /** Queues the end of rendering. - - This method will do nothing unless startRendering() has - been called, in which case before the next frame is rendered - the rendering loop will bail out. - @see - Root, Root::startRendering - */ - void queueEndRendering(bool state = true); - - /** Check for planned end of rendering. - - This method return true if queueEndRendering() was called before. - @see - Root, Root::queueEndRendering, Root::startRendering - */ - bool endRenderingQueued(void); - - /** Starts / restarts the automatic rendering cycle. - - This method begins the automatic rendering of the scene. It - will NOT return until the rendering cycle is halted. - @par - During rendering, any FrameListener classes registered using - addFrameListener will be called back for each frame that is - to be rendered, These classes can tell OGRE to halt the - rendering if required, which will cause this method to - return. - @note -
Users of the OGRE library do not have to use this - automatic rendering loop. It is there as a convenience and is - most useful for high frame rate applications e.g. games. For - applications that don't need to constantly refresh the - rendering targets (e.g. an editor utility), it is better to - manually refresh each render target only when required by - calling RenderTarget::update, or if you want to run your own - render loop you can update all targets on demand using - Root::renderOneFrame. - @note - This frees up the CPU to do other things in between - refreshes, since in this case frame rate is less important. - @note - This method can only be called after Root::initialise has - been called. - */ - void startRendering(void); - - /** Updates all the render targets automatically - - Raises frame events before and after. - - Overview of the render cycle - ![](renderOneFrame.svg) - */ - bool renderOneFrame(void); - - /** Updates all the render targets with custom frame time information - - Updates all the render targets automatically and then returns, - raising frame events before and after - all per-frame times are based on - the time value you pass in. - */ - bool renderOneFrame(Real timeSinceLastFrame); - - /** Shuts down the system manually. - - This is normally done by Ogre automatically so don't think - you have to call this yourself. However this is here for - convenience, especially for dealing with unexpected errors or - for systems which need to shut down Ogre on demand. - */ - void shutdown(void); - - /** Helper method to assist you in creating writeable file streams. - - This is a high-level utility method which you can use to find a place to - save a file more easily. If the filename you specify is either an - absolute or relative filename (ie it includes path separators), then - the file will be created in the normal filesystem using that specification. - If it doesn't, then the method will look for a writeable resource location - via ResourceGroupManager::createResource using the other params provided. - @param filename The name of the file to create. If it includes path separators, - the filesystem will be accessed direct. If no path separators are - present the resource system is used, falling back on the raw filesystem after. - @param groupName The name of the group in which to create the file, if the - resource system is used - @param overwrite If true, an existing file will be overwritten, if false - an error will occur if the file already exists - @param locationPattern If the resource group contains multiple locations, - then usually the file will be created in the first writable location. If you - want to be more specific, you can include a location pattern here and - only locations which match that pattern (as determined by StringUtil::match) - will be considered candidates for creation. - */ - static DataStreamPtr createFileStream(const String& filename, - const String& groupName = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - bool overwrite = false, const String& locationPattern = BLANKSTRING); - - /** Helper method to assist you in accessing readable file streams. - - This is a high-level utility method which you can use to find a place to - open a file more easily. It checks the resource system first, and if - that fails falls back on accessing the file system directly. - @param filename The name of the file to open. - @param groupName The name of the group in which to create the file, if the - resource system is used - */ - static DataStreamPtr openFileStream(const String& filename, - const String& groupName = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - /// @deprecated use ColourValue::getAsBYTE() - OGRE_DEPRECATED static void convertColourValue(const ColourValue& colour, uint32* pDest) { *pDest = colour.getAsBYTE(); } - - /** Retrieves a pointer to the window that was created automatically - - When Root is initialised an optional window is created. This - method retrieves a pointer to that window. - @note - returns a null pointer when Root has not been initialised with - the option of creating a window. - */ - RenderWindow* getAutoCreatedWindow(void); - - /** @copydoc RenderSystem::_createRenderWindow - */ - RenderWindow* createRenderWindow(const String &name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams = 0) ; - - /// @overload - RenderWindow* createRenderWindow(const RenderWindowDescription& desc) - { - return createRenderWindow(desc.name, desc.width, desc.height, - desc.useFullScreen, &desc.miscParams); - } - - /** Detaches a RenderTarget from the active render system - and returns a pointer to it. - @note - If the render target cannot be found, NULL is returned. - */ - RenderTarget* detachRenderTarget( RenderTarget* pWin ); - - /** Detaches a named RenderTarget from the active render system - and returns a pointer to it. - @note - If the render target cannot be found, NULL is returned. - */ - RenderTarget* detachRenderTarget( const String & name ); - - /** Destroys the given RenderTarget. - */ - void destroyRenderTarget(RenderTarget* target); - - /** Destroys the given named RenderTarget. - */ - void destroyRenderTarget(const String &name); - - /** Retrieves a pointer to a named render target. - */ - RenderTarget * getRenderTarget(const String &name); - - /** Manually load a Plugin contained in a DLL / DSO. - - Plugins embedded in DLLs can be loaded at startup using the plugin - configuration file specified when you create Root. - This method allows you to load plugin DLLs directly in code. - The DLL in question is expected to implement a dllStartPlugin - method which instantiates a Plugin subclass and calls Root::installPlugin. - It should also implement dllStopPlugin (see Root::unloadPlugin) - @param pluginName Name of the plugin library to load - */ - void loadPlugin(const String& pluginName); - - /** Manually unloads a Plugin contained in a DLL / DSO. - - Plugin DLLs are unloaded at shutdown automatically. This method - allows you to unload plugins in code, but make sure their - dependencies are decoupled first. This method will call the - dllStopPlugin method defined in the DLL, which in turn should call - Root::uninstallPlugin. - @param pluginName Name of the plugin library to unload - */ - void unloadPlugin(const String& pluginName); - - /** Install a new plugin. - - This installs a new extension to OGRE. The plugin itself may be loaded - from a DLL / DSO, or it might be statically linked into your own - application. Either way, something has to call this method to get - it registered and functioning. You should only call this method directly - if your plugin is not in a DLL that could otherwise be loaded with - loadPlugin, since the DLL function dllStartPlugin should call this - method when the DLL is loaded. - */ - void installPlugin(Plugin* plugin); - - /** Uninstall an existing plugin. - - This uninstalls an extension to OGRE. Plugins are automatically - uninstalled at shutdown but this lets you remove them early. - If the plugin was loaded from a DLL / DSO you should call unloadPlugin - which should result in this method getting called anyway (if the DLL - is well behaved). - */ - void uninstallPlugin(Plugin* plugin); - - /** Gets a read-only list of the currently installed plugins. */ - const PluginInstanceList& getInstalledPlugins() const { return mPlugins; } - - /** Gets a pointer to the central timer used for all OGRE timings */ - Timer* getTimer(void); - - /** Method for raising frame started events. - - This method is only for internal use when you use OGRE's inbuilt rendering - loop (Root::startRendering). However, if you run your own rendering loop then - you should call this method to ensure that FrameListener objects are notified - of frame events; processes like texture animation and particle systems rely on - this. - @par - Calling this method also increments the frame number, which is - important for keeping some elements of the engine up to date. - @note - This method takes an event object as a parameter, so you can specify the times - yourself. If you are happy for OGRE to automatically calculate the frame time - for you, then call the other version of this method with no parameters. - @param evt Event object which includes all the timing information which you have - calculated for yourself - @return False if one or more frame listeners elected that the rendering loop should - be terminated, true otherwise. - */ - bool _fireFrameStarted(FrameEvent& evt); - /** Method for raising frame rendering queued events. - - This method is only for internal use when you use OGRE's inbuilt rendering - loop (Root::startRendering). However, if you run your own rendering loop then - you should call this method too, to ensure that all state is updated - correctly. You should call it after the windows have been updated - but before the buffers are swapped, or if you are not separating the - update and buffer swap, then after the update just before _fireFrameEnded. - */ - bool _fireFrameRenderingQueued(FrameEvent& evt); - - /** Method for raising frame ended events. - - This method is only for internal use when you use OGRE's inbuilt rendering - loop (Root::startRendering). However, if you run your own rendering loop then - you should call this method to ensure that FrameListener objects are notified - of frame events; processes like texture animation and particle systems rely on - this. - @note - This method takes an event object as a parameter, so you can specify the times - yourself. If you are happy for OGRE to automatically calculate the frame time - for you, then call the other version of this method with no parameters. - @param evt Event object which includes all the timing information which you have - calculated for yourself - @return False if one or more frame listeners elected that the rendering loop should - be terminated, true otherwise. - */ - bool _fireFrameEnded(FrameEvent& evt); - /** Method for raising frame started events. - - This method is only for internal use when you use OGRE's inbuilt rendering - loop (Root::startRendering). However, if you run your own rendering loop then - you should call this method to ensure that FrameListener objects are notified - of frame events; processes like texture animation and particle systems rely on - this. - @par - Calling this method also increments the frame number, which is - important for keeping some elements of the engine up to date. - @note - This method calculates the frame timing information for you based on the elapsed - time. If you want to specify elapsed times yourself you should call the other - version of this method which takes event details as a parameter. - @return False if one or more frame listeners elected that the rendering loop should - be terminated, true otherwise. - */ - bool _fireFrameStarted(); - /** Method for raising frame rendering queued events. - - This method is only for internal use when you use OGRE's inbuilt rendering - loop (Root::startRendering). However, if you run your own rendering loop then - you you may want to call this method too, although nothing in OGRE relies on this - particular event. Really if you're running your own rendering loop at - this level of detail then you can get the same effect as doing your - updates in a frameRenderingQueued callback by just calling - RenderWindow::update with the 'swapBuffers' option set to false. - */ - bool _fireFrameRenderingQueued(); - /** Method for raising frame ended events. - - This method is only for internal use when you use OGRE's inbuilt rendering - loop (Root::startRendering). However, if you run your own rendering loop then - you should call this method to ensure that FrameListener objects are notified - of frame events; processes like texture animation and particle systems rely on - this. - @note - This method calculates the frame timing information for you based on the elapsed - time. If you want to specify elapsed times yourself you should call the other - version of this method which takes event details as a parameter. - @return False if one or more frame listeners elected that the rendering loop should - be terminated, true otherwise. - */ - bool _fireFrameEnded(); - - /** Gets the number of the next frame to be rendered. - - Note that this is 'next frame' rather than 'current frame' because - it indicates the frame number that current changes made to the scene - will take effect. It is incremented after all rendering commands for - the current frame have been queued, thus reflecting that if you - start performing changes then, you will actually see them in the - next frame. */ - unsigned long getNextFrameNumber(void) const { return mNextFrame; } - - /** Returns the scene manager currently being used to render a frame. - - This is only intended for internal use; it is only valid during the - rendering of a frame. - */ - SceneManager* _getCurrentSceneManager(void) const { return mCurrentSceneManager; } - /** Sets the scene manager currently being used to render. - - This is only intended for internal use. - */ - void _setCurrentSceneManager(SceneManager* sm) { mCurrentSceneManager = sm; } - - /** Internal method used for updating all RenderTarget objects (windows, - renderable textures etc) which are set to auto-update. - - You don't need to use this method if you're using Ogre's own internal - rendering loop (Root::startRendering). If you're running your own loop - you may wish to call it to update all the render targets which are - set to auto update (RenderTarget::setAutoUpdated). You can also update - individual RenderTarget instances using their own update() method. - @return false if a FrameListener indicated it wishes to exit the render loop - */ - bool _updateAllRenderTargets(void); - - /** Internal method used for updating all RenderTarget objects (windows, - renderable textures etc) which are set to auto-update, with a custom time - passed to the frameRenderingQueued events. - - You don't need to use this method if you're using Ogre's own internal - rendering loop (Root::startRendering). If you're running your own loop - you may wish to call it to update all the render targets which are - set to auto update (RenderTarget::setAutoUpdated). You can also update - individual RenderTarget instances using their own update() method. - @return false if a FrameListener indicated it wishes to exit the render loop - */ - bool _updateAllRenderTargets(FrameEvent& evt); - - /// @copydoc Singleton::getSingleton() - static Root& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static Root* getSingletonPtr(void); - - /** Clears the history of all event times. - - OGRE stores a history of the last few event times in order to smooth - out any inaccuracies and temporary fluctuations. However, if you - pause or don't render for a little while this can cause a lurch, so - if you're resuming rendering after a break, call this method to reset - the stored times - */ - void clearEventTimes(void); - - /** Sets the period over which OGRE smooths out fluctuations in frame times. - - OGRE by default gives you the raw frame time, but can optionally - smooths it out over several frames, in order to reduce the - noticeable effect of occasional hiccups in framerate. - These smoothed values are passed back as parameters to FrameListener - calls. - @par - This method allow you to tweak the smoothing period, and is expressed - in seconds. Setting it to 0 will result in completely unsmoothed - frame times (the default). - */ - void setFrameSmoothingPeriod(Real period) { mFrameSmoothingTime = period; } - /** Gets the period over which OGRE smooths out fluctuations in frame times. */ - Real getFrameSmoothingPeriod(void) const { return mFrameSmoothingTime; } - - /** Register a new MovableObjectFactory which will create new MovableObject - instances of a particular type, as identified by the getType() method. - - Plugin creators can create subclasses of MovableObjectFactory which - construct custom subclasses of MovableObject for insertion in the - scene. This is the primary way that plugins can make custom objects - available. - @param fact Pointer to the factory instance - @param overrideExisting Set this to true to override any existing - factories which are registered for the same type. You should only - change this if you are very sure you know what you're doing. - */ - void addMovableObjectFactory(MovableObjectFactory* fact, - bool overrideExisting = false); - /** Removes a previously registered MovableObjectFactory. - - All instances of objects created by this factory will be destroyed - before removing the factory (by calling back the factories - 'destroyInstance' method). The plugin writer is responsible for actually - destroying the factory. - */ - void removeMovableObjectFactory(MovableObjectFactory* fact); - /// Checks whether a factory is registered for a given MovableObject type - bool hasMovableObjectFactory(const String& typeName) const; - /// Get a MovableObjectFactory for the given type - MovableObjectFactory* getMovableObjectFactory(const String& typeName); - /** Allocate the next MovableObject type flag. - - This is done automatically if MovableObjectFactory::requestTypeFlags - returns true; don't call this manually unless you're sure you need to. - */ - uint32 _allocateNextMovableObjectTypeFlag(void); - - typedef ConstMapIterator MovableObjectFactoryIterator; - /** Return an iterator over all the MovableObjectFactory instances currently - registered. - */ - const MovableObjectFactoryMap& getMovableObjectFactories() const - { - return mMovableObjectFactoryMap; - } - - /// @deprecated use getMovableObjectFactories - OGRE_DEPRECATED MovableObjectFactoryIterator getMovableObjectFactoryIterator(void) const; - - /** Get the WorkQueue for processing background tasks. - You are free to add new requests and handlers to this queue to - process your custom background tasks using the shared thread pool. - However, you must remember to assign yourself a new channel through - which to process your tasks. - */ - WorkQueue* getWorkQueue() const { return mWorkQueue.get(); } - - /** Replace the current work queue with an alternative. - You can use this method to replace the internal implementation of - WorkQueue with your own, e.g. to externalise the processing of - background events. Doing so will delete the existing queue and - replace it with this one. - @param queue The new WorkQueue instance. Root will delete this work queue - at shutdown, so do not destroy it yourself. - */ - void setWorkQueue(WorkQueue* queue); - - /** Sets whether blend indices information needs to be passed to the GPU. - When entities use software animation they remove blend information such as - indices and weights from the vertex buffers sent to the graphic card. This function - can be used to limit which information is removed. - @param redundant Set to true to remove blend indices information. - */ - void setBlendIndicesGpuRedundant(bool redundant) { mIsBlendIndicesGpuRedundant = redundant; } - /** Returns whether blend indices information needs to be passed to the GPU - see setBlendIndicesGpuRedundant() for more information - */ - bool isBlendIndicesGpuRedundant() const { return mIsBlendIndicesGpuRedundant; } - - /** Sets whether blend weights information needs to be passed to the GPU. - When entities use software animation they remove blend information such as - indices and weights from the vertex buffers sent to the graphic card. This function - can be used to limit which information is removed. - @param redundant Set to true to remove blend weights information. - */ - void setBlendWeightsGpuRedundant(bool redundant) { mIsBlendWeightsGpuRedundant = redundant; } - /** Returns whether blend weights information needs to be passed to the GPU - see setBlendWeightsGpuRedundant() for more information - */ - bool isBlendWeightsGpuRedundant() const { return mIsBlendWeightsGpuRedundant; } - - /** Set the default minimum pixel size for object to be rendered by - @note - To use this feature see Camera::setUseMinPixelSize() - */ - void setDefaultMinPixelSize(Real pixelSize) { mDefaultMinPixelSize = pixelSize; } - - /** Get the default minimum pixel size for object to be rendered by - */ - Real getDefaultMinPixelSize() { return mDefaultMinPixelSize; } - }; - /** @} */ - /** @} */ -} // Namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreRotationalSpline.h b/OgreMain/include/OgreRotationalSpline.h deleted file mode 100644 index c46ae5a3072..00000000000 --- a/OgreMain/include/OgreRotationalSpline.h +++ /dev/null @@ -1,138 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __RotationalSpline_H__ -#define __RotationalSpline_H__ - -#include "OgrePrerequisites.h" -#include "OgreQuaternion.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - /** This class interpolates orientations (rotations) along a spline using - derivatives of quaternions. - - Like the SimpleSpline class, this class is about interpolating values - smoothly over a spline. Whilst SimpleSpline deals with positions (the normal - sense we think about splines), this class interpolates orientations. The - theory is identical, except we're now in 4-dimensional space instead of 3. - @par - In positional splines, we use the points and tangents on those points to generate - control points for the spline. In this case, we use quaternions and derivatives - of the quaternions (i.e. the rate and direction of change at each point). This is the - same as SimpleSpline since a tangent is a derivative of a position. We effectively - generate an extra quaternion in between each actual quaternion which when take with - the original quaternion forms the 'tangent' of that quaternion. - */ - class _OgreExport RotationalSpline - { - public: - RotationalSpline(); - ~RotationalSpline(); - - /** Adds a control point to the end of the spline. */ - void addPoint(const Quaternion& p); - - /** Gets the detail of one of the control points of the spline. */ - const Quaternion& getPoint(unsigned short index) const; - - /** Gets the number of control points in the spline. */ - unsigned short getNumPoints(void) const; - - /** Clears all the points in the spline. */ - void clear(void); - - /** Updates a single point in the spline. - - This point must already exist in the spline. - */ - void updatePoint(unsigned short index, const Quaternion& value); - - /** Returns an interpolated point based on a parametric value over the whole series. - - Given a t value between 0 and 1 representing the parametric distance along the - whole length of the spline, this method returns an interpolated point. - @param t Parametric value. - @param useShortestPath Defines if rotation should take the shortest possible path - */ - Quaternion interpolate(Real t, bool useShortestPath=true); - - /** Interpolates a single segment of the spline given a parametric value. - @param fromIndex The point index to treat as t=0. fromIndex + 1 is deemed to be t=1 - @param t Parametric value - @param useShortestPath Defines if rotation should take the shortest possible path - */ - Quaternion interpolate(unsigned int fromIndex, Real t, bool useShortestPath=true); - - /** Tells the spline whether it should automatically calculate tangents on demand - as points are added. - - The spline calculates tangents at each point automatically based on the input points. - Normally it does this every time a point changes. However, if you have a lot of points - to add in one go, you probably don't want to incur this overhead and would prefer to - defer the calculation until you are finished setting all the points. You can do this - by calling this method with a parameter of 'false'. Just remember to manually call - the recalcTangents method when you are done. - @param autoCalc If true, tangents are calculated for you whenever a point changes. If false, - you must call reclacTangents to recalculate them when it best suits. - */ - void setAutoCalculate(bool autoCalc); - - /** Recalculates the tangents associated with this spline. - - If you tell the spline not to update on demand by calling setAutoCalculate(false) - then you must call this after completing your updates to the spline points. - */ - void recalcTangents(void); - - private: - - bool mAutoCalc; - - - - std::vector mPoints; - std::vector mTangents; - - }; - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreSceneManager.h b/OgreMain/include/OgreSceneManager.h deleted file mode 100644 index 6c1d6f06c62..00000000000 --- a/OgreMain/include/OgreSceneManager.h +++ /dev/null @@ -1,3395 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE - -You may alternatively use this source under the terms of a specific version of -the OGRE Unrestricted License provided you have obtained such a license from -Torus Knot Software Ltd. --------------------------------------------------------------------------*/ -#ifndef __SceneManager_H__ -#define __SceneManager_H__ - -// Precompiler options -#include "OgrePrerequisites.h" - -#include "OgrePlane.h" -#include "OgreQuaternion.h" -#include "OgreColourValue.h" -#include "OgreCommon.h" -#include "OgreSceneQuery.h" -#include "OgreAutoParamDataSource.h" -#include "OgreAnimationState.h" -#include "OgreRenderQueue.h" -#include "OgreRenderQueueSortingGrouping.h" -#include "OgreResourceGroupManager.h" -#include "OgreInstanceManager.h" -#include "OgreManualObject.h" -#include "OgreRenderSystem.h" -#include "OgreLodListener.h" -#include "OgreHeaderPrefix.h" -#include "OgreNameGenerator.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - - typedef std::vector ShadowTextureList; - - /** Structure containing the configuration for one shadow texture. */ - struct ShadowTextureConfig - { - unsigned int width; - unsigned int height; - PixelFormat format; - unsigned int fsaa; - uint16 depthBufferPoolId; - - ShadowTextureConfig() : width(512), height(512), format(PF_BYTE_RGBA), fsaa(0), depthBufferPoolId(1) {} - }; - - typedef std::vector ShadowTextureConfigList; - typedef ConstVectorIterator ConstShadowTextureConfigIterator; - - _OgreExport bool operator== ( const ShadowTextureConfig& lhs, const ShadowTextureConfig& rhs ); - _OgreExport bool operator!= ( const ShadowTextureConfig& lhs, const ShadowTextureConfig& rhs ); - - /** Structure for holding a position & orientation pair. */ - struct ViewPoint - { - Vector3 position; - Quaternion orientation; - }; - - // Forward declarations - class CompositorChain; - class Rectangle2D; - class LodListener; - struct MovableObjectLodChangedEvent; - struct EntityMeshLodChangedEvent; - struct EntityMaterialLodChangedEvent; - class ShadowCasterSceneQueryListener; - - /** Structure collecting together information about the visible objects - that have been discovered in a scene. - */ - struct _OgreExport VisibleObjectsBoundsInfo - { - /// The axis-aligned bounds of the visible objects - AxisAlignedBox aabb; - /// The axis-aligned bounds of the visible shadow receiver objects - AxisAlignedBox receiverAabb; - /// The closest a visible object is to the camera - Real minDistance; - /// The farthest a visible objects is from the camera - Real maxDistance; - /// The closest a object in the frustum regardless of visibility / shadow caster flags - Real minDistanceInFrustum; - /// The farthest object in the frustum regardless of visibility / shadow caster flags - Real maxDistanceInFrustum; - - VisibleObjectsBoundsInfo(); - void reset(); - void merge(const AxisAlignedBox& boxBounds, const Sphere& sphereBounds, - const Camera* cam, bool receiver=true); - /** Merge an object that is not being rendered because it's not a shadow caster, - but is a shadow receiver so should be included in the range. - */ - void mergeNonRenderedButInFrustum(const AxisAlignedBox& boxBounds, - const Sphere& sphereBounds, const Camera* cam); - - - }; - - struct ShadowTextureListener - { - ShadowTextureListener() {} - virtual ~ShadowTextureListener() {} - /** Event raised after all shadow textures have been rendered into for - all queues / targets but before any other geometry has been rendered - (including main scene geometry and any additional shadow receiver - passes). - - This callback is useful for those that wish to perform some - additional processing on shadow textures before they are used to - render shadows. For example you could perform some filtering by - rendering the existing shadow textures into another alternative - shadow texture with a shader. - @note - This event will only be fired when texture shadows are in use. - @param numberOfShadowTextures The number of shadow textures in use - */ - virtual void shadowTexturesUpdated(size_t numberOfShadowTextures) - { (void)numberOfShadowTextures; } - - /** This event occurs just before the view & projection matrices are - set for rendering into a shadow texture. - - You can use this event hook to perform some custom processing, - such as altering the camera being used for rendering the light's - view, including setting custom view & projection matrices if you - want to perform an advanced shadow technique. - @note - This event will only be fired when texture shadows are in use. - @param light Pointer to the light for which shadows are being rendered - @param camera Pointer to the camera being used to render - @param iteration For lights that use multiple shadow textures, the iteration number - */ - virtual void shadowTextureCasterPreViewProj(Light* light, - Camera* camera, size_t iteration) - { (void)light; (void)camera; (void)iteration; } - - /** This event occurs just before the view & projection matrices are - set for re-rendering a shadow receiver. - - You can use this event hook to perform some custom processing, - such as altering the projection frustum being used for rendering - the shadow onto the receiver to perform an advanced shadow - technique. - @note - This event will only be fired when texture shadows are in use. - @param light Pointer to the light for which shadows are being rendered - @param frustum Pointer to the projection frustum being used to project - the shadow texture - */ - virtual void shadowTextureReceiverPreViewProj(Light* light, - Frustum* frustum) - { (void)light; (void)frustum; } - - /** Hook to allow the listener to override the ordering of lights for - the entire frustum. - - Whilst ordinarily lights are sorted per rendered object - (@ref MovableObject::queryLights), texture shadows adds another issue - in that, given there is a finite number of shadow textures, we must - choose which lights to render texture shadows from based on the entire - frustum. These lights should always be listed first in every objects - own list, followed by any other lights which will not cast texture - shadows (either because they have shadow casting off, or there aren't - enough shadow textures to service them). - - This hook allows you to override the detailed ordering of the lights - per frustum. The default ordering is shadow casters first (which you - must also respect if you override this method), and ordered - by distance from the camera within those 2 groups. Obviously the closest - lights with shadow casting enabled will be listed first. Only lights - within the range of the frustum will be in the list. - @param lightList The list of lights within range of the frustum which you - may sort. - @return true if you sorted the list, false otherwise. - */ - virtual bool sortLightsAffectingFrustum(LightList& lightList) - { (void)lightList; return false; } - }; - - /** Manages the organisation and rendering of a 'scene': a collection of objects and potentially world geometry. - - This class defines the interface and the basic behaviour of a - 'Scene Manager'. A SceneManager organises the culling and rendering of - the scene, in conjunction with the RenderQueue. This class is designed - to be extended through subclassing in order to provide more specialised - scene organisation structures for particular needs. The default - SceneManager culls based on a hierarchy of node bounding boxes, other - implementations can use an octree (see OctreeSceneManager), a BSP - tree (see BspSceneManager), and many other options. New SceneManager - implementations can be added at runtime by plugins, see - SceneManagerEnumerator for the interfaces for adding new SceneManager - types. - - There is a distinction between 'objects' (which subclass MovableObject, - and are movable, discrete objects in the world), and 'world geometry', - which is large, generally static geometry. World geometry tends to - influence the SceneManager organisational structure (e.g. lots of indoor - static geometry might result in a spatial tree structure) and as such - world geometry is generally tied to a given SceneManager implementation, - whilst MovableObject instances can be used with any SceneManager. - Subclasses are free to define world geometry however they please. - - Multiple SceneManager instances can exist at one time, each one with - a distinct scene. Which SceneManager is used to render a scene is - dependent on the Camera, which will always call back the SceneManager - which created it to render the scene. - */ - class _OgreExport SceneManager : public SceneMgtAlloc - { - public: - enum QueryTypeMask : uint32 - { - /// Query type mask which will be used for world geometry @see SceneQuery - WORLD_GEOMETRY_TYPE_MASK = 0x80000000, - /// Query type mask which will be used for entities @see SceneQuery - ENTITY_TYPE_MASK = 0x40000000, - /// Query type mask which will be used for effects like billboardsets / particle systems @see SceneQuery - FX_TYPE_MASK = 0x20000000, - /// Query type mask which will be used for StaticGeometry @see SceneQuery - STATICGEOMETRY_TYPE_MASK = 0x10000000, - /// Query type mask which will be used for lights @see SceneQuery - LIGHT_TYPE_MASK = 0x08000000, - /// Query type mask which will be used for frusta and cameras @see SceneQuery - FRUSTUM_TYPE_MASK = 0x04000000, - /// User type mask limit - USER_TYPE_MASK_LIMIT = FRUSTUM_TYPE_MASK - }; - - /// Describes the stage of rendering when performing complex illumination - enum IlluminationRenderStage - { - /// No special illumination stage - IRS_NONE, - /// Render to texture stage, used for texture based shadows - IRS_RENDER_TO_TEXTURE, - /// Render from shadow texture to receivers stage - IRS_RENDER_RECEIVER_PASS - }; - - /** Enumeration of the possible modes allowed for processing the special case - render queue list. - @see SceneManager::setSpecialCaseRenderQueueMode - */ - enum SpecialCaseRenderQueueMode - { - /// Render only the queues in the special case list - SCRQM_INCLUDE, - /// Render all except the queues in the special case list - SCRQM_EXCLUDE - }; - - struct SkyDomeGenParameters - { - Real skyDomeCurvature; - Real skyDomeTiling; - Real skyDomeDistance; - int skyDomeXSegments; - int skyDomeYSegments; - int skyDomeYSegments_keep; - }; - - struct SkyPlaneGenParameters - { - Real skyPlaneScale; - Real skyPlaneTiling; - Real skyPlaneBow; - int skyPlaneXSegments; - int skyPlaneYSegments; - }; - - struct SkyBoxGenParameters - { - Real skyBoxDistance; - }; - - /** Class that allows listening in on the various stages of SceneManager - processing, so that custom behaviour can be implemented from outside. - */ - class Listener - { - public: - Listener() {} - virtual ~Listener() {} - - /** Called prior to updating the scene graph in this SceneManager. - - This is called before updating the scene graph for a camera. - @param source The SceneManager instance raising this event. - @param camera The camera being updated. - */ - virtual void preUpdateSceneGraph(SceneManager* source, Camera* camera) - { (void)source; (void)camera; } - - /** Called after updating the scene graph in this SceneManager. - - This is called after updating the scene graph for a camera. - @param source The SceneManager instance raising this event. - @param camera The camera being updated. - */ - virtual void postUpdateSceneGraph(SceneManager* source, Camera* camera) - { (void)source; (void)camera; } - - /** Called prior to searching for visible objects in this SceneManager. - - Note that the render queue at this stage will be full of the last - render's contents and will be cleared after this method is called. - @param source The SceneManager instance raising this event. - @param irs The stage of illumination being dealt with. IRS_NONE for - a regular render, IRS_RENDER_TO_TEXTURE for a shadow caster render. - @param v The viewport being updated. You can get the camera from here. - */ - virtual void preFindVisibleObjects(SceneManager* source, - IlluminationRenderStage irs, Viewport* v) - { (void)source; (void)irs; (void)v; } - - /** Called after searching for visible objects in this SceneManager. - - Note that the render queue at this stage will be full of the current - scenes contents, ready for rendering. You may manually add renderables - to this queue if you wish. - @param source The SceneManager instance raising this event. - @param irs The stage of illumination being dealt with. IRS_NONE for - a regular render, IRS_RENDER_TO_TEXTURE for a shadow caster render. - @param v The viewport being updated. You can get the camera from here. - */ - virtual void postFindVisibleObjects(SceneManager* source, - IlluminationRenderStage irs, Viewport* v) - { (void)source; (void)irs; (void)v; } - - /** Event notifying the listener of the SceneManager's destruction. */ - virtual void sceneManagerDestroyed(SceneManager* source) - { (void)source; } - }; - - /** Inner helper class to implement the visitor pattern for rendering objects - in a queue. - */ - class _OgreExport SceneMgrQueuedRenderableVisitor : public QueuedRenderableVisitor - { - private: - /// Pass that was actually used at the grouping level - const Pass* mUsedPass; - public: - SceneMgrQueuedRenderableVisitor() - :transparentShadowCastersMode(false) {} - ~SceneMgrQueuedRenderableVisitor() {} - void visit(const Pass* p, RenderableList& rs) override; - void visit(RenderablePass* rp) override; - - /// Target SM to send renderables to - SceneManager* targetSceneMgr; - /// Are we in transparent shadow caster mode? - bool transparentShadowCastersMode; - /// Automatic light handling? - bool autoLights; - /// Manual light list - const LightList* manualLightList; - /// Scissoring if requested? - bool scissoring; - - /** Render a set of objects - - transparentShadowCastersMode is intended to be used to render the shadows of transparent objects which have - transparency_casts_shadows set to 'on' in their material - @see SceneManager::_injectRenderWithPass - */ - void renderObjects(const QueuedRenderableCollection& objs, QueuedRenderableCollection::OrganisationMode om, - bool lightScissoringClipping, bool doLightIteration, - const LightList* manualLightList = 0, bool transparentShadowCastersMode = false); - - void renderTransparents(const RenderPriorityGroup* priorityGrp, QueuedRenderableCollection::OrganisationMode om); - }; - /// Allow visitor helper to access protected methods - friend class SceneMgrQueuedRenderableVisitor; - - typedef std::map CameraList; - typedef std::map AnimationList; - typedef std::map MovableObjectMap; - private: - HardwareVertexBufferPtr mInstanceBuffer; - - void renderInstancedObject(const RenderableList& rend, const Pass* pass, - bool lightScissoringClipping, bool doLightIteration, const LightList* manualLightList = 0); - - /// Subclasses can override this to ensure their specialised SceneNode is used. - virtual SceneNode* createSceneNodeImpl(void); - /// Subclasses can override this to ensure their specialised SceneNode is used. - virtual SceneNode* createSceneNodeImpl(const String& name); - - /// Instance name - String mName; - /// Queue of objects for rendering - std::unique_ptr mRenderQueue; - - typedef std::map StaticGeometryList; - StaticGeometryList mStaticGeometryList; - - typedef std::map InstanceManagerMap; - InstanceManagerMap mInstanceManagerMap; - - /// The rendering system to send the scene to - RenderSystem *mDestRenderSystem; - protected: - /** Central list of cameras - for easy memory management and lookup. - */ - CameraList mCameras; - - typedef std::vector SceneNodeList; - - /** Central list of SceneNodes - for easy memory management. - @note - Note that this list is used only for memory management; the structure of the scene - is held using the hierarchy of SceneNodes starting with the root node. However you - can look up nodes this way. - */ - SceneNodeList mSceneNodes; - - /// Camera in progress - Camera* mCameraInProgress; - - private: - /// additional map to speed up lookup by name - std::map mNamedNodes; - - /// Current Viewport - Viewport* mCurrentViewport; - - /// Root scene node - std::unique_ptr mSceneRoot; - - /// Autotracking scene nodes - typedef std::set AutoTrackingSceneNodes; - AutoTrackingSceneNodes mAutoTrackingSceneNodes; - - // Sky params - class _OgreExport SkyRenderer : public Listener, public Node::Listener - { - protected: - SceneManager* mSceneManager; - virtual void _updateRenderQueue(RenderQueue* queue) = 0; - void nodeDestroyed(const Node*) override; - public: - enum BoxPlane - { - BP_FRONT = 0, - BP_BACK = 1, - BP_LEFT = 2, - BP_RIGHT = 3, - BP_UP = 4, - BP_DOWN = 5 - }; - - SkyRenderer(SceneManager* owner); - - SceneNode* mSceneNode; - bool mEnabled; - - void setEnabled(bool enable); - void postFindVisibleObjects(SceneManager* source, IlluminationRenderStage irs, Viewport* vp) override; - }; - - class SkyPlaneRenderer : public SkyRenderer - { - Entity* mSkyPlaneEntity; - Plane mSkyPlane; - void _updateRenderQueue(RenderQueue* queue) override; - public: - SkyPlaneRenderer(SceneManager* owner) : SkyRenderer(owner), mSkyPlaneEntity(0) {} - SkyPlaneGenParameters mSkyPlaneGenParameters; - void setSkyPlane(bool enable, const Plane& plane, const String& materialName, - Real scale, Real tiling, uint8 renderQueue, Real bow, int xsegments, - int ysegments, const String& groupName); - } mSkyPlane; - - class SkyBoxRenderer : public SkyRenderer - { - std::unique_ptr mSkyBoxObj; - - Quaternion mSkyBoxOrientation; - void _updateRenderQueue(RenderQueue* queue) override; - public: - SkyBoxRenderer(SceneManager* owner) : SkyRenderer(owner) {} - SkyBoxGenParameters mSkyBoxGenParameters; - void setSkyBox(bool enable, const String& materialName, Real distance, - uint8 renderQueue, const Quaternion& orientation, - const String& groupName); - } mSkyBox; - - class SkyDomeRenderer : public SkyRenderer - { - std::array mSkyDomeEntity; - Quaternion mSkyDomeOrientation; - - MeshPtr createSkydomePlane( - BoxPlane bp, - Real curvature, Real tiling, Real distance, - const Quaternion& orientation, - int xsegments, int ysegments, int ySegmentsToKeep, - const String& groupName); - void _updateRenderQueue(RenderQueue* queue) override; - public: - SkyDomeRenderer(SceneManager* owner) : SkyRenderer(owner) {} - SkyDomeGenParameters mSkyDomeGenParameters; - void setSkyDome(bool enable, const String& materialName, Real curvature, Real tiling, - Real distance, uint8 renderQueue, const Quaternion& orientation, - int xsegments, int ysegments, int ysegments_keep, - const String& groupName); - } mSkyDome; - - // Fog - FogMode mFogMode; - ColourValue mFogColour; - Real mFogStart; - Real mFogEnd; - Real mFogDensity; - - typedef std::set SpecialCaseRenderQueueList; - SpecialCaseRenderQueueList mSpecialCaseQueueList; - SpecialCaseRenderQueueMode mSpecialCaseQueueMode; - uint8 mWorldGeometryRenderQueue; - - unsigned long mLastFrameNumber; - bool mResetIdentityView; - bool mResetIdentityProj; - - bool mFlipCullingOnNegativeScale; - CullingMode mPassCullingMode; - - protected: - - /** Visible objects bounding box list. - - Holds an ABB for each camera that contains the physical extends of the visible - scene elements by each camera. The map is crucial for shadow algorithms which - have a focus step to limit the shadow sample distribution to only valid visible - scene elements. - */ - typedef std::map< const Camera*, VisibleObjectsBoundsInfo> CamVisibleObjectsMap; - CamVisibleObjectsMap mCamVisibleObjectsMap; - - /// Cached light information, used to tracking light's changes - struct _OgreExport LightInfo - { - Light* light; /// Just a pointer for comparison, the light might destroyed for some reason - int type; /// Use int instead of Light::LightTypes to avoid header file dependence - Real range; /// Sets to zero if directional light - Vector3 position; /// Sets to zero if directional light - uint32 lightMask; /// Light mask - - bool operator== (const LightInfo& rhs) const - { - return light == rhs.light && type == rhs.type && - range == rhs.range && position == rhs.position && lightMask == rhs.lightMask; - } - - bool operator!= (const LightInfo& rhs) const - { - return !(*this == rhs); - } - }; - - typedef std::vector LightInfoList; - - LightList mLightsAffectingFrustum; - LightInfoList mCachedLightInfos; - LightInfoList mTestLightInfos; // potentially new list - ulong mLightsDirtyCounter; - - /// Simple structure to hold MovableObject map and a mutex to go with it. - struct MovableObjectCollection - { - MovableObjectMap map; - OGRE_MUTEX(mutex); - }; - /** Gets the movable object collection for the given type name. - - This method create new collection if the collection does not exist. - */ - MovableObjectCollection* getMovableObjectCollection(const String& typeName); - /** Gets the movable object collection for the given type name. - - This method throw exception if the collection does not exist. - */ - const MovableObjectCollection* getMovableObjectCollection(const String& typeName) const; - /// Mutex over the collection of MovableObject types - OGRE_MUTEX(mMovableObjectCollectionMapMutex); - - /** Internal method for initialising the render queue. - - Subclasses can use this to install their own RenderQueue implementation. - */ - virtual void initRenderQueue(void); - - /** Internal method to validate whether a Pass should be allowed to render. - - Called just before a pass is about to be used for rendering a group to - allow the SceneManager to omit it if required. A return value of false - skips this pass. - */ - bool validatePassForRendering(const Pass* pass); - - /** Internal method to validate whether a Renderable should be allowed to render. - - Called just before a pass is about to be used for rendering a Renderable to - allow the SceneManager to omit it if required. A return value of false - skips it. - */ - bool validateRenderableForRendering(const Pass* pass, const Renderable* rend); - - /** Internal utility method for rendering a single object. - - Assumes that the pass has already been set up. - @copydetail _injectRenderWithPass - @param lightScissoringClipping If true, passes that have the getLightScissorEnabled - and/or getLightClipPlanesEnabled flags will cause calculation and setting of - scissor rectangle and user clip planes. - */ - void renderSingleObject(Renderable* rend, const Pass* pass, - bool lightScissoringClipping, bool doLightIteration, const LightList* manualLightList = 0); - - void updateCachedLightInfos(const Camera* camera); - - /** Internal method for locating a list of lights which could be affecting the frustum. - - Custom scene managers are encouraged to override this method to make use of their - scene partitioning scheme to more efficiently locate lights, and to eliminate lights - which may be occluded by world geometry. - If the list of lights is different to the list returned by - SceneManager::_getLightsAffectingFrustum before this method was called, then this - method should update that cached list and call SceneManager::_notifyLightsDirty to - mark that the internal light cache has changed. - */ - virtual void findLightsAffectingFrustum(const Camera* camera); - /// Internal method for creating shadow textures (texture-based shadows) - virtual void ensureShadowTexturesCreated(); - - const std::vector& getShadowTextureCameras(); - bool isShadowTextureConfigDirty() const; - - /// Internal method for firing the queue start event, returns true if queue is to be skipped - virtual bool fireRenderQueueStarted(uint8 id, const String& cameraName); - /// Internal method for firing the queue end event, returns true if queue is to be repeated - virtual bool fireRenderQueueEnded(uint8 id, const String& cameraName); - - private: - /** Internal method for creating the AutoParamDataSource instance. */ - AutoParamDataSource* createAutoParamDataSource(void) const - { - return OGRE_NEW AutoParamDataSource(); - } - - /// Internal method for setting up materials for shadows - void initShadowVolumeMaterials(void); - /// Internal method for destroying shadow textures (texture-based shadows) - void destroyShadowTextures(void); - - /** Internal method for rendering all objects using the default queue sequence. */ - void renderVisibleObjectsDefaultSequence(void); - /** Internal method for preparing the render queue for use with each render. */ - void prepareRenderQueue(void); - - /** Internal method for setting the destination viewport for the next render. */ - void setViewport(Viewport *vp); - - /// Internal method for firing the queue start event - void firePreRenderQueues(); - /// Internal method for firing the queue end event - void firePostRenderQueues(); - /// Internal method for firing when rendering a single object. - void fireRenderSingleObject(Renderable* rend, const Pass* pass, const AutoParamDataSource* source, - const LightList* pLightList, bool suppressRenderStateChanges); - /// Internal method for firing pre update scene graph event - void firePreUpdateSceneGraph(Camera* camera); - /// Internal method for firing post update scene graph event - void firePostUpdateSceneGraph(Camera* camera); - /// Internal method for firing find visible objects event - void firePreFindVisibleObjects(Viewport* v); - /// Internal method for firing find visible objects event - void firePostFindVisibleObjects(Viewport* v); - /// Internal method for firing destruction event - void fireSceneManagerDestroyed(); - - /** Internal method used by _renderSingleObject to set the world transform */ - void setWorldTransform(Renderable* rend); - - /** Internal method used by _renderSingleObject to render a single light pass */ - void issueRenderWithLights(Renderable* rend, const Pass* pass, - const LightList* pLightListToUse, - bool lightScissoringClipping); - - /** Internal method used by _renderSingleObject to deal with renderables - which override the camera's own view / projection matrices. */ - void resetViewProjMode(); - - typedef std::map MovableObjectCollectionMap; - MovableObjectCollectionMap mMovableObjectCollectionMap; - NameGenerator mMovableNameGenerator; - - /// Flag indicating whether SceneNodes will be rendered as a set of 3 axes - bool mDisplayNodes; - std::unique_ptr mDebugDrawer; - - /// Storage of animations, lookup by name - AnimationList mAnimationsList; - OGRE_MUTEX(mAnimationsListMutex); - AnimationStateSet mAnimationStates; - - typedef std::vector RenderQueueListenerList; - RenderQueueListenerList mRenderQueueListeners; - - typedef std::vector RenderObjectListenerList; - RenderObjectListenerList mRenderObjectListeners; - typedef std::vector ListenerList; - ListenerList mListeners; - - /** Flag that indicates if all of the scene node's bounding boxes should be shown as a wireframe. */ - bool mShowBoundingBoxes; - - /// Utility class for calculating automatic parameters for gpu programs - std::unique_ptr mAutoParamDataSource; - - GpuProgramParametersPtr mFixedFunctionParams; - - CompositorChain* mActiveCompositorChain; - bool mLateMaterialResolving; - - IlluminationRenderStage mIlluminationStage; - - typedef std::vector InstanceManagerVec; - InstanceManagerVec mDirtyInstanceManagers; - InstanceManagerVec mDirtyInstanceMgrsTmp; - - /** Updates all instance managaers with dirty instance batches. @see _addDirtyInstanceManager */ - void updateDirtyInstanceManagers(void); - - void _destroySceneNode(SceneNodeList::iterator it); - - struct _OgreExport ShadowRenderer - { - typedef std::vector CameraList; - typedef std::map< const Camera*, const Light* > ShadowCamLightMapping; - - ShadowRenderer(SceneManager* owner); - ~ShadowRenderer(); - - SceneManager* mSceneManager; - RenderSystem* mDestRenderSystem; - - ShadowTechnique mShadowTechnique; - ColourValue mShadowColour; - - /// A pass designed to let us render shadow colour on white for texture shadows - Pass* mShadowCasterPlainBlackPass; - /// A pass designed to let us render shadow receivers for texture shadows - Pass* mShadowReceiverPass; - - Pass* mShadowModulativePass; - - Pass* mShadowDebugPass; - Pass* mShadowStencilPass; - HardwareIndexBufferSharedPtr mShadowIndexBuffer; - size_t mShadowIndexBufferSize; - size_t mShadowIndexBufferUsedSize; - static GpuProgramParametersSharedPtr msInfiniteExtrusionParams; - static GpuProgramParametersSharedPtr msFiniteExtrusionParams; - - Pass* mShadowTextureCustomCasterPass; - Pass* mShadowTextureCustomReceiverPass; - - SamplerPtr mBorderSampler; - - TexturePtr mSpotFadeTexture; - TexturePtr mNullShadowTexture; - CameraList mShadowTextureCameras; - LightList mShadowTextureCurrentCasterLightList; // remove for 13.4: unused - // ShadowCamera to light mapping - ShadowCamLightMapping mShadowCamLightMapping; - // Array defining shadow texture index in light list. - std::vector mShadowTextureIndexLightList; - - Rectangle2D* mFullScreenQuad; - - ShadowTextureList mShadowTextures; - - bool mShadowAdditiveLightClip; - bool mDebugShadows; - bool mShadowMaterialInitDone; - bool mShadowUseInfiniteFarPlane; - Real mShadowDirLightExtrudeDist; - - Real mDefaultShadowFarDist; - Real mDefaultShadowFarDistSquared; - Real mShadowTextureOffset; /// Proportion of texture offset in view direction e.g. 0.4 - Real mShadowTextureFadeStart; /// As a proportion e.g. 0.6 - Real mShadowTextureFadeEnd; /// As a proportion e.g. 0.9 - bool mShadowTextureSelfShadow; - bool mShadowTextureConfigDirty; - bool mShadowCasterRenderBackFaces; - - ShadowTextureConfigList mShadowTextureConfigList; - - /// Array defining shadow count per light type. - size_t mShadowTextureCountPerType[3]; - - /// default shadow camera setup - ShadowCameraSetupPtr mDefaultShadowCameraSetup; - - ShadowCameraSetupPtr mCullCameraSetup; - - void setShadowTechnique(ShadowTechnique technique); - - /// Internal method for creating shadow textures (texture-based shadows) - void ensureShadowTexturesCreated(); - void prepareShadowTextures(Camera* cam, Viewport* vp, const LightList* lightList); - /// Internal method for destroying shadow textures (texture-based shadows) - void destroyShadowTextures(void); - - /** Internal method for turning a regular pass into a shadow caster pass. - - This is only used for texture shadows, basically we're trying to - ensure that objects are rendered solid black. - This method will usually return the standard solid black pass for - all fixed function passes, but will merge in a vertex program - and fudge the AutoParamDataSource to set black lighting for - passes with vertex programs. - */ - const Pass* deriveShadowCasterPass(const Pass* pass); - /** Internal method for turning a regular pass into a shadow receiver pass. - - This is only used for texture shadows, basically we're trying to - ensure that objects are rendered with a projective texture. - This method will usually return a standard single-texture pass for - all fixed function passes, but will merge in a vertex program - for passes with vertex programs. - */ - const Pass* deriveShadowReceiverPass(const Pass* pass); - - const Pass* deriveTextureShadowPass(const Pass* pass); - - void initShadowVolumeMaterials(); - void setShadowTextureCasterMaterial(const MaterialPtr& mat); - void setShadowTextureReceiverMaterial(const MaterialPtr& mat); - void setShadowColour(const ColourValue& colour); - void updateSplitOptions(RenderQueue* queue); - void render(RenderQueueGroup* group, QueuedRenderableCollection::OrganisationMode om); - - /** Render a group with the added complexity of additive stencil shadows. */ - void renderAdditiveStencilShadowedQueueGroupObjects(RenderQueueGroup* group, - QueuedRenderableCollection::OrganisationMode om); - /** Render a group with the added complexity of modulative stencil shadows. */ - void renderModulativeStencilShadowedQueueGroupObjects(RenderQueueGroup* group, - QueuedRenderableCollection::OrganisationMode om); - /** Render a group rendering only shadow casters. */ - void renderTextureShadowCasterQueueGroupObjects(RenderQueueGroup* group, - QueuedRenderableCollection::OrganisationMode om); - /** Render a group rendering only shadow receivers. */ - void renderTextureShadowReceiverQueueGroupObjects(RenderQueueGroup* group, - QueuedRenderableCollection::OrganisationMode om); - /** Render a group with the added complexity of modulative texture shadows. */ - void renderModulativeTextureShadowedQueueGroupObjects(RenderQueueGroup* group, - QueuedRenderableCollection::OrganisationMode om); - - /** Render a group with additive texture shadows. */ - void renderAdditiveTextureShadowedQueueGroupObjects(RenderQueueGroup* group, - QueuedRenderableCollection::OrganisationMode om); - - /** Returns the shadow caster AAB for a specific light-camera combination */ - const VisibleObjectsBoundsInfo& getShadowCasterBoundsInfo(const Light* light, size_t iteration) const; - - /** Internal method for rendering all the objects for a given light into the - stencil buffer. - @param light The light source - @param cam The camera being viewed from - @param calcScissor Whether the method should set up any scissor state, or - false if that's already been done - */ - void renderShadowVolumesToStencil(const Light* light, const Camera* cam, - bool calcScissor); - - /** Internal utility method for setting stencil state for rendering shadow volumes. - @param secondpass Is this the second pass? - @param zfail Should we be using the zfail method? - @param twosided Should we use a 2-sided stencil? - */ - void setShadowVolumeStencilState(bool secondpass, bool zfail, bool twosided); - /** Render a set of shadow renderables. */ - void renderShadowVolumeObjects(const ShadowCaster::ShadowRenderableList& shadowRenderables, - Pass* pass, const LightList *manualLightList, unsigned long flags, - bool secondpass, bool zfail, bool twosided); - - size_t getShadowTexIndex(size_t lightIndex); - - void setShadowIndexBufferSize(size_t size); - - const TexturePtr& getShadowTexture(size_t shadowIndex); - - void resolveShadowTexture(TextureUnitState* tu, size_t shadowIndex, size_t shadowTexUnitIndex) const; - - void setShadowTextureSettings(uint16 size, uint16 count, PixelFormat fmt, uint16 fsaa, - uint16 depthBufferPoolId); - void setShadowTextureSize(unsigned short size); - void setShadowTextureCount(size_t count); - void setShadowTexturePixelFormat(PixelFormat fmt); - void setShadowTextureFSAA(unsigned short fsaa); - void setShadowTextureConfig(size_t shadowIndex, const ShadowTextureConfig& config); - void setShadowTextureConfig(size_t shadowIndex, uint16 width, uint16 height, PixelFormat format, - uint16 fsaa, uint16 depthBufferPoolId); - - typedef std::vector ShadowCasterList; - ShadowCasterList mShadowCasterList; - std::unique_ptr mShadowCasterSphereQuery; - std::unique_ptr mShadowCasterAABBQuery; - - typedef std::vector ListenerList; - ListenerList mListeners; - std::unique_ptr mShadowCasterQueryListener; - - /** Internal method for locating a list of shadow casters which - could be affecting the frustum for a given light. - */ - const ShadowCasterList& findShadowCastersForLight(const Light* light, const Camera* camera); - /// Internal method for firing the texture shadows updated event - void fireShadowTexturesUpdated(size_t numberOfShadowTextures); - /// Internal method for firing the pre caster texture shadows event - void fireShadowTexturesPreCaster(Light* light, Camera* camera, size_t iteration); - /// Internal method for firing the pre receiver texture shadows event - void fireShadowTexturesPreReceiver(Light* light, Frustum* f); - void sortLightsAffectingFrustum(LightList& lightList) const; - } mShadowRenderer; - - /// Struct for caching light clipping information for re-use in a frame - struct LightClippingInfo - { - RealRect scissorRect; - PlaneList clipPlanes; - bool scissorValid; - bool clipPlanesValid; - LightClippingInfo() : scissorValid(false), clipPlanesValid(false) {} - - }; - typedef std::map LightClippingInfoMap; - LightClippingInfoMap mLightClippingInfoMap; - unsigned long mLightClippingInfoMapFrameNumber; - - /// Set up a scissor rectangle from a group of lights - ClipResult buildAndSetScissor(const LightList& ll, const Camera* cam); - void resetScissor(); - /// Build a set of user clip planes from a single non-directional light - ClipResult buildAndSetLightClip(const LightList& ll); - void buildLightClip(const Light* l, PlaneList& planes); - void resetLightClip(); - void checkCachedLightClippingInfo(bool forceScissorRectsInvalidation = false); - - /// Visibility mask used to show / hide objects - uint32 mVisibilityMask; - bool mFindVisibleObjects; - - /// The active renderable visitor class - subclasses could override this - SceneMgrQueuedRenderableVisitor* mActiveQueuedRenderableVisitor; - /// Storage for default renderable visitor - SceneMgrQueuedRenderableVisitor mDefaultQueuedRenderableVisitor; - - /// Whether to use camera-relative rendering - bool mCameraRelativeRendering; - - /// Last light sets - uint32 mLastLightHash; - /// Gpu params that need rebinding (mask of GpuParamVariability) - uint16 mGpuParamsDirty; - - /** Render a group in the ordinary way */ - void renderBasicQueueGroupObjects(RenderQueueGroup* pGroup, - QueuedRenderableCollection::OrganisationMode om); - - void useLights(const LightList* lights, ushort limit); - void bindGpuProgram(GpuProgram* prog); - void updateGpuProgramParameters(const Pass* p); - - /// Set of registered LOD listeners - typedef std::set LodListenerSet; - LodListenerSet mLodListeners; - - /// List of movable object LOD changed events - typedef std::vector MovableObjectLodChangedEventList; - MovableObjectLodChangedEventList mMovableObjectLodChangedEvents; - - /// List of entity mesh LOD changed events - typedef std::vector EntityMeshLodChangedEventList; - EntityMeshLodChangedEventList mEntityMeshLodChangedEvents; - - /// List of entity material LOD changed events - typedef std::vector EntityMaterialLodChangedEventList; - EntityMaterialLodChangedEventList mEntityMaterialLodChangedEvents; - - public: - //A render context, used to store internal data for pausing/resuming rendering - struct RenderContext - { - RenderQueue* renderQueue; - Viewport* viewport; - Camera* camera; - CompositorChain* activeChain; - }; - - /** Pause rendering of the frame. This has to be called when inside a renderScene call - (Usually using a listener of some sort) - */ - RenderContext* _pauseRendering(); - /** Resume rendering of the frame. This has to be called after a _pauseRendering call - @param context The rendring context, as returned by the _pauseRendering call - */ - void _resumeRendering(RenderContext* context); - - /** Constructor. - */ - SceneManager(const String& instanceName); - - /** Default destructor. - */ - virtual ~SceneManager(); - - - /** Mutex to protect the scene graph from simultaneous access from - multiple threads. - - If you are updating the scene in a separate thread from the rendering - thread, then you should lock this mutex before making any changes to - the scene graph - that means creating, modifying or deleting a - scene node, or attaching / detaching objects. It is your - responsibility to take out this lock, the detail methods on the nodes - will not do it for you (for the reasons discussed below). - @par - Note that locking this mutex will prevent the scene being rendered until - it is unlocked again. Therefore you should do this sparingly. Try - to create any objects you need separately and fully prepare them - before doing all your scene graph work in one go, thus keeping this - lock for the shortest time possible. - @note - A single global lock is used rather than a per-node lock since - it keeps the number of locks required during rendering down to a - minimum. Obtaining a lock, even if there is no contention, is not free - so for performance it is good to do it as little as possible. - Since modifying the scene in a separate thread is a fairly - rare occurrence (relative to rendering), it is better to keep the - locking required during rendering lower than to make update locks - more granular. - */ - OGRE_MUTEX(sceneGraphMutex); - - /** Return the instance name of this SceneManager. */ - const String& getName(void) const { return mName; } - - /** Retrieve the type name of this scene manager. - - This method has to be implemented by subclasses. It should - return the type name of this SceneManager which agrees with - the type name of the SceneManagerFactory which created it. - */ - virtual const String& getTypeName(void) const = 0; - - typedef MapIterator CameraIterator; - /// @name Cameras - /// @{ - /** Creates a camera to be managed by this scene manager. - - This camera must be added to the scene at a later time using - the attachObject method of the SceneNode class. - @param - name Name to give the new camera. - */ - virtual Camera* createCamera(const String& name); - - /** Retrieves a pointer to the named camera. - @note Throws an exception if the named instance does not exist - */ - Camera* getCamera(const String& name) const; - - /** Returns whether a camera with the given name exists. - */ - bool hasCamera(const String& name) const; - - /** Removes a camera from the scene. - - This method removes a previously added camera from the scene. - The camera is deleted so the caller must ensure no references - to it's previous instance (e.g. in a SceneNode) are used. - @param - cam Pointer to the camera to remove - */ - void destroyCamera(Camera *cam); - - /** Removes a camera from the scene. - - This method removes an camera from the scene based on the - camera's name rather than a pointer. - */ - void destroyCamera(const String& name); - - /** Removes (and destroys) all cameras from the scene. - - Some cameras are internal created to dealing with texture shadow, - their aren't supposed to destroy outside. So, while you are using - texture shadow, don't call this method, or you can set the shadow - technique other than texture-based, which will destroy all internal - created shadow cameras and textures. - */ - void destroyAllCameras(void); - - /** Set whether to use camera-relative coordinates when rendering, ie - to always place the camera at the origin and move the world around it. - - This is a technique to alleviate some of the precision issues associated with - rendering far from the origin, where single-precision floats as used in most - GPUs begin to lose their precision. Instead of including the camera - translation in the view matrix, it only includes the rotation, and - the world matrices of objects must be expressed relative to this. - @note - If you need this option, you will probably also need to enable double-precision - mode in Ogre (OGRE_DOUBLE_PRECISION), since even though this will - alleviate the rendering precision, the source camera and object positions will still - suffer from precision issues leading to jerky movement. - */ - void setCameraRelativeRendering(bool rel) { mCameraRelativeRendering = rel; } - - /** Get whether to use camera-relative coordinates when rendering, ie - to always place the camera at the origin and move the world around it. - */ - bool getCameraRelativeRendering() const { return mCameraRelativeRendering; } - - /** Returns a specialised MapIterator over all cameras in the scene. - @deprecated use getCameras() - */ - OGRE_DEPRECATED CameraIterator getCameraIterator(void) { - return CameraIterator(mCameras.begin(), mCameras.end()); - } - /** Returns a const version of the camera list. - */ - const CameraList& getCameras() const { return mCameras; } - /// @} - - /// @name Lights - /// @{ - /** Creates a light for use in the scene. - - Lights can either be in a fixed position and independent of the - scene graph, or they can be attached to SceneNodes so they derive - their position from the parent node. Either way, they are created - using this method so that the SceneManager manages their - existence. - @param - name The name of the new light, to identify it later. - */ - virtual Light* createLight(const String& name); - - /// @overload - Light* createLight(const String& name, Light::LightTypes type) - { - auto l = createLight(name); - l->setType(type); - return l; - } - - /** Creates a light with a generated name. */ - virtual Light* createLight(); - - /// @overload - Light* createLight(Light::LightTypes type) - { - auto l = createLight(); - l->setType(type); - return l; - } - - /// @copydoc getMovableObject() - virtual Light* getLight(const String& name) const; - - /// @copydoc hasMovableObject() - virtual bool hasLight(const String& name) const { return hasMovableObject(name, MOT_LIGHT); } - - /** Retrieve a set of clipping planes for a given light. - */ - const PlaneList& getLightClippingPlanes(Light* l); - - /** Retrieve a scissor rectangle for a given light and camera. - */ - const RealRect& getLightScissorRect(Light* l, const Camera* cam); - - /** Scissor rects are cached during frame, and this cache should be explicitly invalidated - if several renders are done during one frame using different projections matrices, - for example for tiled, stereo or multiview orthographic projection rendering. - */ - virtual void invalidatePerFrameScissorRectCache(); - - /** Removes the light from the scene and destroys it. - - Any pointers held to this light after calling this method will be invalid. - */ - virtual void destroyLight(const String& name) { destroyMovableObject(name, MOT_LIGHT); } - - /// @overload - void destroyLight(Light* light) { destroyMovableObject(light); } - /** Removes and destroys all lights in the scene. - */ - virtual void destroyAllLights(void) { destroyAllMovableObjectsByType(MOT_LIGHT); } - - /** Advanced method to increase the lights dirty counter due to lights having changed. - - The SceneManager tracks the list of lights affecting the current frustum, and if - changes are detected (including changes to the light list itself or to a light's - position or attenuation range) then it increases the lights dirty counter. - @par - You could call this method to force all the objects in the scene to re-populate - their light list, but doing so may harm performance so should be avoided if possible. - */ - void _notifyLightsDirty(void); - - /** Advanced method to gets the lights dirty counter. - - The SceneManager tracks the list of lights affecting the current frustum, and if - changes are detected (including changes to the light list itself or to a light's - position or attenuation range) then it increases the lights dirty counter. - */ - ulong _getLightsDirtyCounter(void) const { return mLightsDirtyCounter; } - - /** Get the list of lights which could be affecting the frustum. - - This returns a cached light list which is populated when rendering the scene. - */ - const LightList& _getLightsAffectingFrustum(void) const; - - /** Populate a light list with an ordered set of the lights which are closest - to the position specified. - - Note that since directional lights have no position, they are always considered - closer than any point lights and as such will always take precedence. - The returned lights are those in the cached list of lights (i.e. those - returned by SceneManager::_getLightsAffectingFrustum) sorted by distance. - @par - The number of items in the list may exceed the maximum number of lights supported - by the renderer, but the extraneous ones will never be used. In fact the limit will - be imposed by Pass::getMaxSimultaneousLights. - @param position The position at which to evaluate the list of lights - @param radius The bounding radius to test - @param destList List to be populated with ordered set of lights; will be cleared by - this method before population. - @param lightMask The mask with which to include / exclude lights - */ - void _populateLightList(const Vector3& position, Real radius, LightList& destList, uint32 lightMask = 0xFFFFFFFF); - - /// @overload - void _populateLightList(const SceneNode* sn, Real radius, LightList& destList, uint32 lightMask = 0xFFFFFFFF) - { - _populateLightList(sn->_getDerivedPosition(), radius, destList, lightMask); - } - /// @} - - /// @name Scene Nodes - /// @{ - /** Creates an instance of a SceneNode. - - Note that this does not add the SceneNode to the scene hierarchy. - This method is for convenience, since it allows an instance to - be created for which the SceneManager is responsible for - allocating and releasing memory, which is convenient in complex - scenes. - @par - To include the returned SceneNode in the scene, use the addChild - method of the SceneNode which is to be it's parent. - @par - Note that this method takes no parameters, and the node created is unnamed (it is - actually given a generated name, which you can retrieve if you want). - If you wish to create a node with a specific name, call the alternative method - which takes a name parameter. - */ - SceneNode* createSceneNode(void); - - /// @overload - SceneNode* createSceneNode(const String& name); - - /** Destroys a SceneNode. - - This allows you to physically delete an individual SceneNode if you want to. - Note that this is not normally recommended, it's better to allow SceneManager - to delete the nodes when the scene is cleared. - */ - virtual void destroySceneNode(SceneNode* sn); - - /// @overload - virtual void destroySceneNode(const String& name); - - /** Gets the SceneNode at the root of the scene hierarchy. - - The entire scene is held as a hierarchy of nodes, which - allows things like relative transforms, general changes in - rendering state etc (See the SceneNode class for more info). - In this basic SceneManager class, the application using - Ogre is free to structure this hierarchy however it likes, - since it has no real significance apart from making transforms - relative to each node (more specialised subclasses will - provide utility methods for building specific node structures - e.g. loading a BSP tree). - @par - However, in all cases there is only ever one root node of - the hierarchy, and this method returns a pointer to it. - */ - SceneNode* getRootSceneNode(void); - - /** Retrieves a named SceneNode from the scene graph. - - If you chose to name a SceneNode as you created it, you can look it - up wherever it is in the scene graph using this method. - @param name - @param throwExceptionIfNotFound Throws an exception if the named instance does not exist - */ - SceneNode* getSceneNode(const String& name, bool throwExceptionIfNotFound = true) const; - - /** Returns whether a scene node with the given name exists. - */ - bool hasSceneNode(const String& name) const { return getSceneNode(name, false) != NULL; } - - /** Tells the SceneManager whether it should render the SceneNodes which - make up the scene as well as the objects in the scene. - - This method is mainly for debugging purposes. If you set this to 'true', - each node will be rendered as a set of 3 axes to allow you to easily see - the orientation of the nodes. - */ - void setDisplaySceneNodes(bool display); - /** Returns true if all scene nodes axis are to be displayed */ - bool getDisplaySceneNodes(void) const {return mDisplayNodes;} - - /** Allows all bounding boxes of scene nodes to be displayed. */ - void showBoundingBoxes(bool bShow); - - /** Returns if all bounding boxes of scene nodes are to be displayed */ - bool getShowBoundingBoxes() const; - - DebugDrawer* getDebugDrawer() const { return mDebugDrawer.get(); } - /// @} - - static constexpr const char* PT_PLANE = "Prefab_Plane"; //!< XY plane with -100..100 extent, +Z normal and UVs - static constexpr const char* PT_CUBE = "Prefab_Cube"; //!< 100x100x100 cube centred at origin with normals and UVs - static constexpr const char* PT_SPHERE = "Prefab_Sphere"; //!< %Sphere with radius 50, around origin with normals UVs - /// @name Entities - /// @{ - /** Create an Entity (instance of a discrete mesh). - @param - entityName The name to be given to the entity (must be unique). - @param - meshName The name of the Mesh it is to be based on (e.g. 'knot.oof'). The - mesh will be loaded if it is not already. - @param groupName The resource name where the mesh lives - */ - Entity* createEntity(const String& entityName, const String& meshName, const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME ); - - /** Create an Entity (instance of a discrete mesh). - @param - entityName The name to be given to the entity (must be unique). - @param - pMesh The pointer to the Mesh it is to be based on. - */ - Entity* createEntity(const String& entityName, const MeshPtr& pMesh ); - - /** Create an Entity (instance of a discrete mesh) with an autogenerated name. - @param - meshName The name of the Mesh it is to be based on (e.g. 'knot.oof'). The - mesh will be loaded if it is not already. - */ - Entity* createEntity(const String& meshName); - - /** Create an Entity (instance of a discrete mesh) with an autogenerated name. - @param - pMesh The pointer to the Mesh it is to be based on. - */ - Entity* createEntity(const MeshPtr& pMesh); - - /// @copydoc getMovableObject() - Entity* getEntity(const String& name) const; - /// @copydoc hasMovableObject() - bool hasEntity(const String& name) const { return hasMovableObject(name, MOT_ENTITY); } - - /** Removes & destroys an Entity from the SceneManager. - */ - void destroyEntity(MovableObject* ent) { destroyMovableObject(ent); } - - /// @overload - void destroyEntity(const String& name) { destroyMovableObject(name, MOT_ENTITY); } - - /** Removes & destroys all Entities. - */ - void destroyAllEntities(void) { destroyAllMovableObjectsByType(MOT_ENTITY); } - /// @} - - /// @name Manual Objects - /// @{ - /** Create a ManualObject, an object which you populate with geometry - manually through a GL immediate-mode style interface. - @param - name The name to be given to the object (must be unique). - */ - ManualObject* createManualObject(const String& name); - /** Create a ManualObject, an object which you populate with geometry - manually through a GL immediate-mode style interface, generating the name. - */ - ManualObject* createManualObject(); - /// @copydoc getMovableObject() - ManualObject* getManualObject(const String& name) const; - /// @copydoc hasMovableObject() - bool hasManualObject(const String& name) const { return hasMovableObject(name, MOT_MANUAL_OBJECT); } - - /** Removes & destroys a ManualObject from the SceneManager. - */ - void destroyManualObject(MovableObject* obj) { destroyMovableObject(obj); } - /// @overload - void destroyManualObject(const String& name) { return destroyMovableObject(name, MOT_MANUAL_OBJECT); } - /** Removes & destroys all ManualObjects from the SceneManager. - */ - void destroyAllManualObjects(void) { destroyAllMovableObjectsByType(MOT_MANUAL_OBJECT); } - /// @} - - /// @name Screenspace Rectangles - /// @{ - /** Creates a Rectangle2D that can be displayed for screen space effects or - showing a basic GUI. - @param name The name to be given to the object (must be unique). - @param includeTextureCoords whether to create texture coordinates - */ - Rectangle2D* createScreenSpaceRect(const String& name, bool includeTextureCoords = false); - /// @overload - Rectangle2D* createScreenSpaceRect(bool includeTextureCoords = false); - /// @copydoc hasMovableObject() - bool hasScreenSpaceRect(const String& name) const { return hasMovableObject(name, MOT_RECTANGLE2D); } - /// @copydoc getMovableObject() - Rectangle2D* getScreenSpaceRect(const String& name) const; - /// @} - - /// @name Billboard Chains - /// @{ - /** Create a BillboardChain, an object which you can use to render - a linked chain of billboards. - @param - name The name to be given to the object (must be unique). - */ - BillboardChain* createBillboardChain(const String& name); - /** Create a BillboardChain, an object which you can use to render - a linked chain of billboards, with a generated name. - */ - BillboardChain* createBillboardChain(); - /// @copydoc getMovableObject() - BillboardChain* getBillboardChain(const String& name) const; - /// @copydoc hasMovableObject() - bool hasBillboardChain(const String& name) const { return hasMovableObject(name, MOT_BILLBOARD_CHAIN); } - - /** Removes & destroys a BillboardChain from the SceneManager. - */ - void destroyBillboardChain(MovableObject* obj) { destroyMovableObject(obj); } - /// @overload - void destroyBillboardChain(const String& name) { destroyMovableObject(name, MOT_BILLBOARD_CHAIN); } - /** Removes & destroys all BillboardChains from the SceneManager. - */ - void destroyAllBillboardChains(void) { destroyAllMovableObjectsByType(MOT_BILLBOARD_CHAIN); } - /** Create a RibbonTrail, an object which you can use to render - a linked chain of billboards which follows one or more nodes. - @param - name The name to be given to the object (must be unique). - */ - RibbonTrail* createRibbonTrail(const String& name); - /** Create a RibbonTrail, an object which you can use to render - a linked chain of billboards which follows one or more nodes, generating the name. - */ - RibbonTrail* createRibbonTrail(); - /// @copydoc getMovableObject() - RibbonTrail* getRibbonTrail(const String& name) const; - /// @copydoc hasMovableObject() - bool hasRibbonTrail(const String& name) const { return hasMovableObject(name, MOT_RIBBON_TRAIL); } - - /** Removes & destroys a RibbonTrail from the SceneManager. - */ - void destroyRibbonTrail(MovableObject* obj) { destroyMovableObject(obj); } - /// @overload - void destroyRibbonTrail(const String& name) { destroyMovableObject(name, MOT_RIBBON_TRAIL); } - /** Removes & destroys all RibbonTrails from the SceneManager. - */ - void destroyAllRibbonTrails(void) { destroyAllMovableObjectsByType(MOT_RIBBON_TRAIL); } - /// @} - - /// @name Particle System - /// @{ - /** Creates a particle system based on a template. - - This method creates a new ParticleSystem instance based on the named template - (defined through ParticleSystemManager::createTemplate) and returns a - pointer to the caller. The caller should not delete this object, it will be freed at system shutdown, - or can be released earlier using the destroyParticleSystem method. - @par - Each system created from a template takes the template's settings at the time of creation, - but is completely separate from the template from there on. - @par - Creating a particle system does not make it a part of the scene. As with other MovableObject - subclasses, a ParticleSystem is not rendered until it is attached to a SceneNode. - @par - This is probably the more useful particle system creation method since it does not require manual - setup of the system. Note that the initial quota is based on the template but may be changed later. - @param - name The name to give the new particle system instance. - @param - templateName The name of the template to base the new instance on. - */ - ParticleSystem* createParticleSystem(const String& name, - const String& templateName); - /** Create a blank particle system. - - This method creates a new, blank ParticleSystem instance and returns a pointer to it. - The caller should not delete this object, it will be freed at system shutdown, or can - be released earlier using the destroyParticleSystem method. - @par - The instance returned from this method won't actually do anything because on creation a - particle system has no emitters. The caller should manipulate the instance through it's - ParticleSystem methods to actually create a real particle effect. - @par - Creating a particle system does not make it a part of the scene. As with other MovableObject - subclasses, a ParticleSystem is not rendered until it is attached to a SceneNode. - @param - name The name to give the ParticleSystem. - @param - quota The maximum number of particles to allow in this system. - @param - resourceGroup The resource group which will be used to load dependent resources - */ - ParticleSystem* createParticleSystem(const String& name, - size_t quota = 500, - const String& resourceGroup = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - /// @overload - ParticleSystem* createParticleSystem(size_t quota = 500, - const String& resourceGroup = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - /// @copydoc getMovableObject() - ParticleSystem* getParticleSystem(const String& name) const; - /// @copydoc hasMovableObject() - bool hasParticleSystem(const String& name) const { return hasMovableObject(name, MOT_PARTICLE_SYSTEM); } - - /** Removes & destroys a ParticleSystem from the SceneManager. - */ - void destroyParticleSystem(MovableObject* obj) { destroyMovableObject(obj); } - /// @overload - void destroyParticleSystem(const String& name) { destroyMovableObject(name, MOT_PARTICLE_SYSTEM); } - /** Removes & destroys all ParticleSystems from the SceneManager. - */ - void destroyAllParticleSystems(void) { destroyAllMovableObjectsByType(MOT_PARTICLE_SYSTEM); } - /// @} - - /** Empties the entire scene, including all SceneNodes, Entities, Lights, - BillboardSets etc. Cameras are not deleted at this stage since - they are still referenced by viewports, which are not destroyed during - this process. - */ - virtual void clearScene(void); - - /** Sets the ambient light level to be used for the scene. - - This sets the colour and intensity of the ambient light in the scene, i.e. the - light which is 'sourceless' and illuminates all objects equally. - The colour of an object is affected by a combination of the light in the scene, - and the amount of light that object reflects (in this case based on the Material::ambient - property). - - By default the ambient light in the scene is ColourValue::Black, i.e. no ambient light. This - means that any objects rendered with a Material which has lighting enabled (see Material::setLightingEnabled) - will not be visible unless you have some dynamic lights in your scene. - */ - void setAmbientLight(const ColourValue& colour); - - /** Returns the ambient light level to be used for the scene. - */ - const ColourValue& getAmbientLight(void) const; - - /// @name World Geometry - /// @{ - /** Sets the source of the 'world' geometry, i.e. the large, mainly static geometry - making up the world e.g. rooms, landscape etc. - - Depending on the type of SceneManager (subclasses will be specialised - for particular world geometry types) you have requested via the Root or - SceneManagerEnumerator classes, you can pass a filename to this method and it - will attempt to load the world-level geometry for use. If you try to load - an inappropriate type of world data an exception will be thrown. The default - SceneManager cannot handle any sort of world geometry and so will always - throw an exception. However subclasses like BspSceneManager can load - particular types of world geometry e.g. "q3dm1.bsp". - */ - virtual void setWorldGeometry(const String& filename); - - /** @overload - @param stream Data stream containing data to load - @param typeName String identifying the type of world geometry - contained in the stream - not required if this manager only - supports one type of world geometry. - */ - virtual void setWorldGeometry(DataStreamPtr& stream, - const String& typeName = BLANKSTRING); - - /** Estimate the number of loading stages required to load the named - world geometry. - - This method should be overridden by SceneManagers that provide - custom world geometry that can take some time to load. They should - return from this method a count of the number of stages of progress - they can report on whilst loading. During real loading (setWorldGeometry), - they should call ResourceGroupManager::_notifyCustomStage* exactly - that number of times when loading the geometry for real. - @note - The default is to return 0, ie to not report progress. - */ - virtual size_t estimateWorldGeometry(const String& filename) - { (void)filename; return 0; } - - /** @overload - @param stream Data stream containing data to load - @param typeName String identifying the type of world geometry - contained in the stream - not required if this manager only - supports one type of world geometry. - */ - virtual size_t estimateWorldGeometry(DataStreamPtr& stream, - const String& typeName = BLANKSTRING) - { (void)stream; (void)typeName; return 0; } - /// @} - - /** Asks the SceneManager to provide a suggested viewpoint from which the scene should be viewed. - - Typically this method returns the origin unless a) world geometry has been loaded using - SceneManager::setWorldGeometry and b) that world geometry has suggested 'start' points. - If there is more than one viewpoint which the scene manager can suggest, it will always suggest - the first one unless the random parameter is true. - @param - random If true, and there is more than one possible suggestion, a random one will be used. If false - the same one will always be suggested. - @return - On success, true is returned. - @par - On failure, false is returned. - */ - virtual ViewPoint getSuggestedViewpoint(bool random = false); - - /** Method for setting a specific option of the Scene Manager. These options are usually - specific for a certain implementation of the Scene Manager class, and may (and probably - will) not exist across different implementations. - @param - strKey The name of the option to set - @param - pValue A pointer to the value - the size should be calculated by the scene manager - based on the key - @return - On success, true is returned. - @par - On failure, false is returned. - */ - virtual bool setOption( const String& strKey, const void* pValue ) - { (void)strKey; (void)pValue; return false; } - - /** Method for getting the value of an implementation-specific Scene Manager option. - @param - strKey The name of the option - @param - pDestValue A pointer to a memory location where the value will - be copied. Currently, the memory will be allocated by the - scene manager, but this may change - @return - On success, true is returned and pDestValue points to the value of the given - option. - @par - On failure, false is returned and pDestValue is set to NULL. - */ - virtual bool getOption( const String& strKey, void* pDestValue ) - { (void)strKey; (void)pDestValue; return false; } - - /** Method for verifying whether the scene manager has an implementation-specific - option. - @param - strKey The name of the option to check for. - @return - If the scene manager contains the given option, true is returned. - - If it does not, false is returned. - */ - virtual bool hasOption( const String& strKey ) const - { (void)strKey; return false; } - - /** Method for getting all possible values for a specific option. When this list is too large - (i.e. the option expects, for example, a float), the return value will be true, but the - list will contain just one element whose size will be set to 0. - Otherwise, the list will be filled with all the possible values the option can - accept. - @param - strKey The name of the option to get the values for. - @param - refValueList A reference to a list that will be filled with the available values. - @return - On success (the option exists), true is returned. - @par - On failure, false is returned. - */ - virtual bool getOptionValues( const String& strKey, StringVector& refValueList ) - { (void)strKey; (void)refValueList; return false; } - - /** Method for getting all the implementation-specific options of the scene manager. - @param - refKeys A reference to a list that will be filled with all the available options. - @return - On success, true is returned. On failure, false is returned. - */ - virtual bool getOptionKeys( StringVector& refKeys ) - { (void)refKeys; return false; } - - /** Internal method for updating the scene graph ie the tree of SceneNode instances managed by this class. - - This must be done before issuing objects to the rendering pipeline, since derived transformations from - parent nodes are not updated until required. This SceneManager is a basic implementation which simply - updates all nodes from the root. This ensures the scene is up to date but requires all the nodes - to be updated even if they are not visible. Subclasses could trim this such that only potentially visible - nodes are updated. - */ - virtual void _updateSceneGraph(Camera* cam); - - /** Internal method which parses the scene to find visible objects to render. - - If you're implementing a custom scene manager, this is the most important method to - override since it's here you can apply your custom world partitioning scheme. Once you - have added the appropriate objects to the render queue, you can let the default - SceneManager objects _renderVisibleObjects handle the actual rendering of the objects - you pick. - @par - Any visible objects will be added to a rendering queue, which is indexed by material in order - to ensure objects with the same material are rendered together to minimise render state changes. - */ - virtual void _findVisibleObjects(Camera* cam, VisibleObjectsBoundsInfo* visibleBounds, bool onlyShadowCasters); - - /** Internal method for issuing the render operation.*/ - void _issueRenderOp(Renderable* rend, const Pass* pass); - - /** Sends visible objects found in _findVisibleObjects to the rendering engine. - */ - void _renderVisibleObjects(void) { renderVisibleObjectsDefaultSequence(); } - - /** Prompts the class to send its contents to the renderer. - - This method prompts the scene manager to send the - contents of the scene it manages to the rendering - pipeline, possibly preceded by some sorting, culling - or other scene management tasks. Note that this method is not normally called - directly by the user application; it is called automatically - by the Ogre rendering loop. - @param camera Pointer to a camera from whose viewpoint the scene is to - be rendered. - @param vp The target viewport - @param includeOverlays unused - */ - virtual void _renderScene(Camera* camera, Viewport* vp, bool includeOverlays = true); - - /** Notifies the scene manager of its destination render system - - Called automatically by RenderSystem::addSceneManager - this method simply notifies the manager of the render - system to which its output must be directed. - @param - sys Pointer to the RenderSystem subclass to be used as a render target. - */ - void _setDestinationRenderSystem(RenderSystem* sys); - - /** Notifies the scene manager that hardware resources were lost - - Called automatically by RenderSystem if hardware resources - were lost and can not be restored using some internal mechanism. - Among affected resources are manual meshes without loaders, - manual textures without loaders, ManualObjects, etc. - */ - void _releaseManualHardwareResources(); - - /** Notifies the scene manager that hardware resources should be restored - - Called automatically by RenderSystem if hardware resources - were lost and can not be restored using some internal mechanism. - Among affected resources are manual meshes without loaders, - manual textures without loaders, ManualObjects, etc. - */ - void _restoreManualHardwareResources(); - - /// @name Sky Rendering - /// @{ - /** Enables / disables a 'sky plane' i.e. a plane at constant - distance from the camera representing the sky. - - You can create sky planes yourself using the standard mesh and - entity methods, but this creates a plane which the camera can - never get closer or further away from - it moves with the camera. - (NB you could create this effect by creating a world plane which - was attached to the same SceneNode as the Camera too, but this - would only apply to a single camera whereas this plane applies to - any camera using this scene manager). - @note - To apply scaling, scrolls etc to the sky texture(s) you - should use the TextureUnitState class methods. - @param - enable True to enable the plane, false to disable it - @param - plane Details of the plane, i.e. it's normal and it's - distance from the camera. - @param - materialName The name of the material the plane will use - @param - scale The scaling applied to the sky plane - higher values - mean a bigger sky plane - you may want to tweak this - depending on the size of plane.d and the other - characteristics of your scene - @param - tiling How many times to tile the texture across the sky. - Applies to all texture layers. If you need finer control use - the TextureUnitState texture coordinate transformation methods. - @param - drawFirst If true, the plane is drawn before all other - geometry in the scene, without updating the depth buffer. - This is the safest rendering method since all other objects - will always appear in front of the sky. However this is not - the most efficient way if most of the sky is often occluded - by other objects. If this is the case, you can set this - parameter to false meaning it draws after all other - geometry which can be an optimisation - however you must - ensure that the plane.d value is large enough that no objects - will 'poke through' the sky plane when it is rendered. - @param - bow If zero, the plane will be completely flat (like previous - versions. If above zero, the plane will be curved, allowing - the sky to appear below camera level. Curved sky planes are - simular to skydomes, but are more compatible with fog. - @param xsegments, ysegments - Determines the number of segments the plane will have to it. This - is most important when you are bowing the plane, but may also be useful - if you need tessellation on the plane to perform per-vertex effects. - @param groupName - The name of the resource group to which to assign the plane mesh. - */ - - void setSkyPlane( - bool enable, - const Plane& plane, const String& materialName, Real scale = 1000, - Real tiling = 10, bool drawFirst = true, Real bow = 0, - int xsegments = 1, int ysegments = 1, - const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME); - /// @overload - void _setSkyPlane( - bool enable, - const Plane& plane, const String& materialName, Real scale = 1000, - Real tiling = 10, uint8 renderQueue = RENDER_QUEUE_SKIES_EARLY, Real bow = 0, - int xsegments = 1, int ysegments = 1, - const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME); - - /** Enables / disables a 'sky plane' */ - void setSkyPlaneEnabled(bool enable) { mSkyPlane.setEnabled(enable); } - - /** Return whether a key plane is enabled */ - bool isSkyPlaneEnabled(void) const { return mSkyPlane.mEnabled; } - - /** Get the sky plane node, if enabled. */ - SceneNode* getSkyPlaneNode(void) const { return mSkyPlane.mSceneNode; } - - /** Get the parameters used to construct the SkyPlane, if any **/ - const SkyPlaneGenParameters& getSkyPlaneGenParameters(void) const { return mSkyPlane.mSkyPlaneGenParameters; } - - /** Enables / disables a 'sky box' i.e. a 6-sided box at constant - distance from the camera representing the sky. - - You could create a sky box yourself using the standard mesh and - entity methods, but this creates a plane which the camera can - never get closer or further away from - it moves with the camera. - (NB you could create this effect by creating a world box which - was attached to the same SceneNode as the Camera too, but this - would only apply to a single camera whereas this skybox applies - to any camera using this scene manager). - @par - The material you use for the skybox can either contain layers - which are single textures, or they can be cubic textures, i.e. - made up of 6 images, one for each plane of the cube. See the - TextureUnitState class for more information. - @param - enable True to enable the skybox, false to disable it - @param - materialName The name of the material the box will use - @param - distance Distance in world coordinates from the camera to - each plane of the box. The default is normally OK. - @param - drawFirst If true, the box is drawn before all other - geometry in the scene, without updating the depth buffer. - This is the safest rendering method since all other objects - will always appear in front of the sky. However this is not - the most efficient way if most of the sky is often occluded - by other objects. If this is the case, you can set this - parameter to false meaning it draws after all other - geometry which can be an optimisation - however you must - ensure that the distance value is large enough that no - objects will 'poke through' the sky box when it is rendered. - @param - orientation Optional parameter to specify the orientation - of the box. By default the 'top' of the box is deemed to be - in the +y direction, and the 'front' at the -z direction. - You can use this parameter to rotate the sky if you want. - @param groupName - The name of the resource group to which to assign the plane mesh. - */ - void setSkyBox( - bool enable, const String& materialName, Real distance = 5000, - bool drawFirst = true, const Quaternion& orientation = Quaternion::IDENTITY, - const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME); - - /// @overload - void _setSkyBox( - bool enable, const String& materialName, Real distance = 5000, - uint8 renderQueue = RENDER_QUEUE_SKIES_EARLY, const Quaternion& orientation = Quaternion::IDENTITY, - const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME); - - /** Enables / disables a 'sky box' */ - void setSkyBoxEnabled(bool enable) { mSkyBox.setEnabled(enable); } - - /** Return whether a skybox is enabled */ - bool isSkyBoxEnabled(void) const { return mSkyBox.mEnabled; } - - /** Get the skybox node, if enabled. */ - SceneNode* getSkyBoxNode(void) const { return mSkyBox.mSceneNode; } - - /** Get the parameters used to generate the current SkyBox, if any */ - const SkyBoxGenParameters& getSkyBoxGenParameters(void) const { return mSkyBox.mSkyBoxGenParameters; } - - /** Enables / disables a 'sky dome' i.e. an illusion of a curved sky. - - A sky dome is actually formed by 5 sides of a cube, but with - texture coordinates generated such that the surface appears - curved like a dome. Sky domes are appropriate where you need a - realistic looking sky where the scene is not going to be - 'fogged', and there is always a 'floor' of some sort to prevent - the viewer looking below the horizon (the distortion effect below - the horizon can be pretty horrible, and there is never anything - directly below the viewer). If you need a complete wrap-around - background, use the setSkyBox method instead. You can actually - combine a sky box and a sky dome if you want, to give a positional - backdrop with an overlaid curved cloud layer. - @par - Sky domes work well with 2D repeating textures like clouds. You - can change the apparent 'curvature' of the sky depending on how - your scene is viewed - lower curvatures are better for 'open' - scenes like landscapes, whilst higher curvatures are better for - say FPS levels where you don't see a lot of the sky at once and - the exaggerated curve looks good. - @param - enable True to enable the skydome, false to disable it - @param - materialName The name of the material the dome will use - @param - curvature The curvature of the dome. Good values are - between 2 and 65. Higher values are more curved leading to - a smoother effect, lower values are less curved meaning - more distortion at the horizons but a better distance effect. - @param - tiling How many times to tile the texture(s) across the - dome. - @param - distance Distance in world coordinates from the camera to - each plane of the box the dome is rendered on. The default - is normally OK. - @param - drawFirst If true, the dome is drawn before all other - geometry in the scene, without updating the depth buffer. - This is the safest rendering method since all other objects - will always appear in front of the sky. However this is not - the most efficient way if most of the sky is often occluded - by other objects. If this is the case, you can set this - parameter to false meaning it draws after all other - geometry which can be an optimisation - however you must - ensure that the distance value is large enough that no - objects will 'poke through' the sky when it is rendered. - @param - orientation Optional parameter to specify the orientation - of the dome. By default the 'top' of the dome is deemed to - be in the +y direction, and the 'front' at the -z direction. - You can use this parameter to rotate the sky if you want. - @param groupName - The name of the resource group to which to assign the plane mesh. - @param xsegments, ysegments, ysegments_keep see @ref MeshManager::createCurvedIllusionPlane - */ - void setSkyDome( - bool enable, const String& materialName, Real curvature = 10, - Real tiling = 8, Real distance = 4000, bool drawFirst = true, - const Quaternion& orientation = Quaternion::IDENTITY, - int xsegments = 16, int ysegments = 16, int ysegments_keep = -1, - const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME); - - /// @overload - void _setSkyDome( - bool enable, const String& materialName, Real curvature = 10, - Real tiling = 8, Real distance = 4000, uint8 renderQueue = RENDER_QUEUE_SKIES_EARLY, - const Quaternion& orientation = Quaternion::IDENTITY, - int xsegments = 16, int ysegments = 16, int ysegments_keep = -1, - const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME); - - /** Enables / disables a 'sky dome' */ - void setSkyDomeEnabled(bool enable) { mSkyDome.setEnabled(enable); } - - /** Return whether a skydome is enabled */ - bool isSkyDomeEnabled(void) const { return mSkyDome.mEnabled; } - - /** Get the sky dome node, if enabled. */ - SceneNode* getSkyDomeNode(void) const { return mSkyDome.mSceneNode; } - - /** Get the parameters used to generate the current SkyDome, if any */ - const SkyDomeGenParameters& getSkyDomeGenParameters(void) const { return mSkyDome.mSkyDomeGenParameters; } - /// @} - - /// @name Fogging - /// @{ - /** Sets the fogging mode applied to the scene. - - This method sets up the scene-wide fogging effect. These settings - apply to all geometry rendered, UNLESS the material with which it - is rendered has it's own fog settings (see Material::setFog). - @param - mode Set up the mode of fog as described in the FogMode - enum, or set to FOG_NONE to turn off. - @param - colour The colour of the fog. Either set this to the same - as your viewport background colour, or to blend in with a - skydome or skybox. - @param - expDensity The density of the fog in FOG_EXP or FOG_EXP2 - mode, as a value between 0 and 1. The default is 0.001. - @param - linearStart Distance in world units at which linear fog starts to - encroach. Only applicable if mode is - FOG_LINEAR. - @param - linearEnd Distance in world units at which linear fog becomes completely - opaque. Only applicable if mode is - FOG_LINEAR. - */ - void setFog( - FogMode mode = FOG_NONE, const ColourValue& colour = ColourValue::White, - Real expDensity = 0.001f, Real linearStart = 0.0f, Real linearEnd = 1.0f); - - /** Returns the fog mode for the scene. - */ - FogMode getFogMode(void) const; - - /** Returns the fog colour for the scene. - */ - const ColourValue& getFogColour(void) const; - - /** Returns the fog start distance for the scene. - */ - Real getFogStart(void) const; - - /** Returns the fog end distance for the scene. - */ - Real getFogEnd(void) const; - - /** Returns the fog density for the scene. - */ - Real getFogDensity(void) const; - /// @} - - /// @name Billboard Sets - /// @{ - /** Creates a new BillboardSet for use with this scene manager. - - This method creates a new BillboardSet which is registered with - the SceneManager. The SceneManager will destroy this object when - it shuts down or when the SceneManager::clearScene method is - called, so the caller does not have to worry about destroying - this object (in fact, it definitely should not do this). - @par - See the BillboardSet documentations for full details of the - returned class. - @param - poolSize The initial size of the pool of billboards (see BillboardSet for more information) - @see - BillboardSet - */ - BillboardSet* createBillboardSet(unsigned int poolSize = 20); - - /** @overload - @copydoc createBillboardSet(unsigned int) - @param - name The name to give to this billboard set. Must be unique. - */ - BillboardSet* createBillboardSet(const String& name, unsigned int poolSize = 20); - - /** Retrieves a pointer to the named BillboardSet. - @note Throws an exception if the named instance does not exist - */ - BillboardSet* getBillboardSet(const String& name) const; - /** Returns whether a billboardset with the given name exists. - */ - bool hasBillboardSet(const String& name) const { return hasMovableObject(name, MOT_BILLBOARD_SET); } - - /** Removes & destroys an BillboardSet from the SceneManager. - */ - void destroyBillboardSet(MovableObject* set) { destroyMovableObject(set); } - - /// @overload - void destroyBillboardSet(const String& name) { destroyMovableObject(name, MOT_BILLBOARD_SET); } - - /** Removes & destroys all BillboardSets. - */ - void destroyAllBillboardSets(void) { destroyAllMovableObjectsByType(MOT_BILLBOARD_SET); } - /// @} - - typedef MapIterator AnimationIterator; - /// @name Scene Node Animation - /// @{ - /** Internal method for applying animations to scene nodes. - - Uses the internally stored AnimationState objects to apply animation to SceneNodes. - */ - void _applySceneAnimations(void); - - /** Creates an animation which can be used to animate scene nodes. - - An animation is a collection of 'tracks' which over time change the position / orientation - of Node objects. In this case, the animation will likely have tracks to modify the position - / orientation of SceneNode objects, e.g. to make objects move along a path. - @par - You don't need to use an Animation object to move objects around - you can do it yourself - using the methods of the Node in your FrameListener class. However, when you need relatively - complex scripted animation, this is the class to use since it will interpolate between - keyframes for you and generally make the whole process easier to manage. - @par - A single animation can affect multiple Node objects (each AnimationTrack affects a single Node). - In addition, through animation blending a single Node can be affected by multiple animations, - although this is more useful when performing skeletal animation (see Skeleton::createAnimation). - @par - Note that whilst it uses the same classes, the animations created here are kept separate from the - skeletal animations of meshes (each Skeleton owns those animations). - @param name The name of the animation, must be unique within this SceneManager. - @param length The total length of the animation. - */ - Animation* createAnimation(const String& name, Real length); - - /** Looks up an Animation object previously created with createAnimation. - @note Throws an exception if the named instance does not exist - */ - Animation* getAnimation(const String& name) const; - /** Returns whether an animation with the given name exists. - */ - bool hasAnimation(const String& name) const; - - /** Destroys an Animation. - - You should ensure that none of your code is referencing this animation objects since the - memory will be freed. - */ - void destroyAnimation(const String& name); - - /** Removes all animations created using this SceneManager. */ - void destroyAllAnimations(void); - - /** Create an AnimationState object for managing application of animations. - - You can create Animation objects for animating SceneNode obejcts using the - createAnimation method. However, in order to actually apply those animations - you have to call methods on Node and Animation in a particular order (namely - Node::resetToInitialState and Animation::apply). To make this easier and to - help track the current time position of animations, the AnimationState object - is provided. - So if you don't want to control animation application manually, call this method, - update the returned object as you like every frame and let SceneManager apply - the animation state for you. - @par - Remember, AnimationState objects are disabled by default at creation time. - Turn them on when you want them using their setEnabled method. - @par - Note that any SceneNode affected by this automatic animation will have it's state - reset to it's initial position before application of the animation. Unless specifically - modified using Node::setInitialState the Node assumes it's initial state is at the - origin. If you want the base state of the SceneNode to be elsewhere, make your changes - to the node using the standard transform methods, then call setInitialState to - 'bake' this reference position into the node. - @par - If the target of your animation is to be a generic AnimableValue, you - should ensure that it has a base value set (unlike nodes this has no - default). @see AnimableValue::setAsBaseValue. - @param animName The name of an animation created already with createAnimation. - */ - AnimationState* createAnimationState(const String& animName); - - /** Retrieves animation state as previously created using createAnimationState. - @note Throws an exception if the named instance does not exist - */ - AnimationState* getAnimationState(const String& animName) const; - /** Returns whether an animation state with the given name exists. - */ - bool hasAnimationState(const String& name) const; - - /** Destroys an AnimationState. - - You should ensure that none of your code is referencing this animation - state object since the memory will be freed. - */ - void destroyAnimationState(const String& name); - - /** Removes all animation states created using this SceneManager. */ - void destroyAllAnimationStates(void); - - /** Returns a specialised MapIterator over all animations in the scene. - * @deprecated use getAnimations() */ - OGRE_DEPRECATED AnimationIterator getAnimationIterator(void) { - return AnimationIterator(mAnimationsList.begin(), mAnimationsList.end()); - } - /** Returns a const version of the animation list. - */ - const AnimationList& getAnimations() const { return mAnimationsList; } - /** Returns a specialised MapIterator over all animation states in the scene. - * @deprecated use getAnimationStates() */ - OGRE_DEPRECATED AnimationStateIterator getAnimationStateIterator(void) - { - return mAnimationStates.getAnimationStateIterator(); - } - - /** Returns a specialised Map over all animation states in the scene. */ - const AnimationStateMap& getAnimationStates() { - return mAnimationStates.getAnimationStates(); - } - /// @} - - /** Manual rendering method, for advanced users only. - - This method allows you to send rendering commands through the pipeline on - demand, bypassing OGRE's normal world processing. You should only use this if you - really know what you're doing; OGRE does lots of things for you that you really should - let it do. However, there are times where it may be useful to have this manual interface, - for example overlaying something on top of the scene rendered by OGRE. - @par - Because this is an instant rendering method, timing is important. The best - time to call it is from a RenderTargetListener event handler. - @par - Don't call this method a lot, it's designed for rare (1 or 2 times per frame) use. - Calling it regularly per frame will cause frame rate drops! - @param rend A RenderOperation object describing the rendering op - @param pass The Pass to use for this render - @param vp Pointer to the viewport to render to, or 0 to use the current viewport - @param worldMatrix The transform to apply from object to world space - @param viewMatrix The transform to apply from world to view space - @param projMatrix The transform to apply from view to screen space - @param doBeginEndFrame If true, beginFrame() and endFrame() are called, - otherwise not. You should leave this as false if you are calling - this within the main render loop. - */ - void manualRender(RenderOperation* rend, Pass* pass, Viewport* vp, - const Affine3& worldMatrix, const Affine3& viewMatrix, const Matrix4& projMatrix, - bool doBeginEndFrame = false) ; - - /** Manual rendering method for rendering a single object. - @param rend The renderable to issue to the pipeline - @param pass The pass to use - @param vp Pointer to the viewport to render to, or 0 to use the existing viewport - @param doBeginEndFrame If true, beginFrame() and endFrame() are called, - otherwise not. You should leave this as false if you are calling - this within the main render loop. - @param viewMatrix The transform to apply from world to view space - @param projMatrix The transform to apply from view to screen space - @param lightScissoringClipping If true, passes that have the getLightScissorEnabled - and/or getLightClipPlanesEnabled flags will cause calculation and setting of - scissor rectangle and user clip planes. - @param doLightIteration If true, this method will issue the renderable to - the pipeline possibly multiple times, if the pass indicates it should be - done once per light - @param manualLightList Only applicable if doLightIteration is false, this - method allows you to pass in a previously determined set of lights - which will be used for a single render of this object. - */ - void manualRender(Renderable* rend, const Pass* pass, Viewport* vp, - const Affine3& viewMatrix, const Matrix4& projMatrix, bool doBeginEndFrame = false, bool lightScissoringClipping = true, - bool doLightIteration = true, const LightList* manualLightList = 0); - - /** Retrieves the internal render queue, for advanced users only. - - The render queue is mainly used internally to manage the scene object - rendering queue, it also exports some methods to allow advanced users - to configure the behavior of rendering process. - Most methods provided by RenderQueue are supposed to be used - internally only, you should reference to the RenderQueue API for - more information. Do not access this directly unless you know what - you are doing. - */ - RenderQueue* getRenderQueue(void); - - /** Registers a new RenderQueueListener which will be notified when render queues - are processed. - */ - void addRenderQueueListener(RenderQueueListener* newListener); - - /** Removes a listener previously added with addRenderQueueListener. */ - void removeRenderQueueListener(RenderQueueListener* delListener); - - /** Registers a new Render Object Listener which will be notified when rendering an object. - */ - void addRenderObjectListener(RenderObjectListener* newListener); - /** Removes a listener previously added with addRenderObjectListener. */ - void removeRenderObjectListener(RenderObjectListener* delListener); - - /** Adds an item to the 'special case' render queue list. - - Normally all render queues are rendered, in their usual sequence, - only varying if a RenderQueueListener nominates for the queue to be - repeated or skipped. This method allows you to add a render queue to - a 'special case' list, which varies the behaviour. The effect of this - list depends on the 'mode' in which this list is in, which might be - to exclude these render queues, or to include them alone (excluding - all other queues). This allows you to perform broad selective - rendering without requiring a RenderQueueListener. - @param qid The identifier of the queue which should be added to the - special case list. Nothing happens if the queue is already in the list. - */ - void addSpecialCaseRenderQueue(uint8 qid); - /** Removes an item to the 'special case' render queue list. - @see SceneManager::addSpecialCaseRenderQueue - @param qid The identifier of the queue which should be removed from the - special case list. Nothing happens if the queue is not in the list. - */ - void removeSpecialCaseRenderQueue(uint8 qid); - /** Clears the 'special case' render queue list. - @see SceneManager::addSpecialCaseRenderQueue - */ - void clearSpecialCaseRenderQueues(void); - /** Sets the way the special case render queue list is processed. - @see SceneManager::addSpecialCaseRenderQueue - @param mode The mode of processing - */ - void setSpecialCaseRenderQueueMode(SpecialCaseRenderQueueMode mode); - /** Gets the way the special case render queue list is processed. */ - SpecialCaseRenderQueueMode getSpecialCaseRenderQueueMode(void); - /** Returns whether or not the named queue will be rendered based on the - current 'special case' render queue list and mode. - @see SceneManager::addSpecialCaseRenderQueue - @param qid The identifier of the queue which should be tested - @return true if the queue will be rendered, false otherwise - */ - bool isRenderQueueToBeProcessed(uint8 qid); - - /** Sets the render queue that the world geometry (if any) this SceneManager - renders will be associated with. - - SceneManagers which provide 'world geometry' should place it in a - specialised render queue in order to make it possible to enable / - disable it easily using the addSpecialCaseRenderQueue method. Even - if the SceneManager does not use the render queues to render the - world geometry, it should still pick a queue to represent it's manual - rendering, and check isRenderQueueToBeProcessed before rendering. - @note - Setting this may not affect the actual ordering of rendering the - world geometry, if the world geometry is being rendered manually - by the SceneManager. If the SceneManager feeds world geometry into - the queues, however, the ordering will be affected. - */ - void setWorldGeometryRenderQueue(uint8 qid) { mWorldGeometryRenderQueue = qid; } - /** Gets the render queue that the world geometry (if any) this SceneManager - renders will be associated with. - - SceneManagers which provide 'world geometry' should place it in a - specialised render queue in order to make it possible to enable / - disable it easily using the addSpecialCaseRenderQueue method. Even - if the SceneManager does not use the render queues to render the - world geometry, it should still pick a queue to represent it's manual - rendering, and check isRenderQueueToBeProcessed before rendering. - */ - uint8 getWorldGeometryRenderQueue() { return mWorldGeometryRenderQueue; } - - /** Internal method for notifying the manager that a SceneNode is autotracking. */ - void _notifyAutotrackingSceneNode(SceneNode* node, bool autoTrack); - - /// @name Scene Queries - /// @{ - /** Creates an AxisAlignedBoxSceneQuery for this scene manager. - - This method creates a new instance of a query object for this scene manager, - for an axis aligned box region. See SceneQuery and AxisAlignedBoxSceneQuery - for full details. - @par - The instance returned from this method must be destroyed by calling - SceneManager::destroyQuery when it is no longer required. - @param box Details of the box which describes the region for this query. - @param mask The query mask to apply to this query; can be used to filter out - certain objects; see SceneQuery for details. - */ - virtual AxisAlignedBoxSceneQuery* - createAABBQuery(const AxisAlignedBox& box, uint32 mask = 0xFFFFFFFF); - /** Creates a SphereSceneQuery for this scene manager. - - This method creates a new instance of a query object for this scene manager, - for a spherical region. See SceneQuery and SphereSceneQuery - for full details. - @par - The instance returned from this method must be destroyed by calling - SceneManager::destroyQuery when it is no longer required. - @param sphere Details of the sphere which describes the region for this query. - @param mask The query mask to apply to this query; can be used to filter out - certain objects; see SceneQuery for details. - */ - virtual SphereSceneQuery* - createSphereQuery(const Sphere& sphere, uint32 mask = 0xFFFFFFFF); - /** Creates a PlaneBoundedVolumeListSceneQuery for this scene manager. - - This method creates a new instance of a query object for this scene manager, - for a region enclosed by a set of planes (normals pointing inwards). - See SceneQuery and PlaneBoundedVolumeListSceneQuery for full details. - @par - The instance returned from this method must be destroyed by calling - SceneManager::destroyQuery when it is no longer required. - @param volumes Details of the volumes which describe the region for this query. - @param mask The query mask to apply to this query; can be used to filter out - certain objects; see SceneQuery for details. - */ - virtual PlaneBoundedVolumeListSceneQuery* - createPlaneBoundedVolumeQuery(const PlaneBoundedVolumeList& volumes, uint32 mask = 0xFFFFFFFF); - - - /** Creates a RaySceneQuery for this scene manager. - - This method creates a new instance of a query object for this scene manager, - looking for objects which fall along a ray. See SceneQuery and RaySceneQuery - for full details. - @par - The instance returned from this method must be destroyed by calling - SceneManager::destroyQuery when it is no longer required. - @param ray Details of the ray which describes the region for this query. - @param mask The query mask to apply to this query; can be used to filter out - certain objects; see SceneQuery for details. - */ - virtual RaySceneQuery* - createRayQuery(const Ray& ray, uint32 mask = 0xFFFFFFFF); - - /** Creates an IntersectionSceneQuery for this scene manager. - - This method creates a new instance of a query object for locating - intersecting objects. See SceneQuery and IntersectionSceneQuery - for full details. - @par - The instance returned from this method must be destroyed by calling - SceneManager::destroyQuery when it is no longer required. - @param mask The query mask to apply to this query; can be used to filter out - certain objects; see SceneQuery for details. - */ - virtual IntersectionSceneQuery* - createIntersectionQuery(uint32 mask = 0xFFFFFFFF); - - /** Destroys a scene query of any type. */ - void destroyQuery(SceneQuery* query); - /// @} - - /// @name Shadow Setup - /// @{ - /** Sets the general shadow technique to be used in this scene. - - There are multiple ways to generate shadows in a scene, and each has - strengths and weaknesses. -
  • Stencil-based approaches can be used to - draw very long, extreme shadows without loss of precision and the 'additive' - version can correctly show the shadowing of complex effects like bump mapping - because they physically exclude the light from those areas. However, the edges - are very sharp and stencils cannot handle transparency, and they involve a - fair amount of CPU work in order to calculate the shadow volumes, especially - when animated objects are involved.
  • -
  • Texture-based approaches are good for handling transparency (they can, for - example, correctly shadow a mesh which uses alpha to represent holes), and they - require little CPU overhead, and can happily shadow geometry which is deformed - by a vertex program, unlike stencil shadows. However, they have a fixed precision - which can introduce 'jaggies' at long range and have fillrate issues of their own.
  • -
- @par - We support 2 kinds of stencil shadows, and 2 kinds of texture-based shadows, and one - simple decal approach. The 2 stencil approaches differ in the amount of multipass work - that is required - the modulative approach simply 'darkens' areas in shadow after the - main render, which is the least expensive, whilst the additive approach has to perform - a render per light and adds the cumulative effect, which is more expensive but more - accurate. The texture based shadows both work in roughly the same way, the only difference is - that the shadowmap approach is slightly more accurate, but requires a more recent - graphics card. - @par - Note that because mixing many shadow techniques can cause problems, only one technique - is supported at once. Also, you should call this method at the start of the - scene setup. - @param technique The shadowing technique to use for the scene. - */ - void setShadowTechnique(ShadowTechnique technique); - - /** Gets the current shadow technique. */ - ShadowTechnique getShadowTechnique(void) const { return mShadowRenderer.mShadowTechnique; } - - /** Enables / disables the rendering of debug information for shadows. */ - void setShowDebugShadows(bool debug) { mShadowRenderer.mDebugShadows = debug; } - /** Are debug shadows shown? */ - bool getShowDebugShadows(void ) const { return mShadowRenderer.mDebugShadows; } - - /** Set the colour used to modulate areas in shadow. - @remarks This is only applicable for shadow techniques which involve - darkening the area in shadow, as opposed to masking out the light. - This colour provided is used as a modulative value to darken the - areas. - */ - void setShadowColour(const ColourValue& colour) { mShadowRenderer.setShadowColour(colour); } - /** Get the colour used to modulate areas in shadow. - @remarks This is only applicable for shadow techniques which involve - darkening the area in shadow, as opposed to masking out the light. - This colour provided is used as a modulative value to darken the - areas. - */ - const ColourValue& getShadowColour(void) const; - /** Sets the distance a shadow volume is extruded for a directional light. - - Although directional lights are essentially infinite, there are many - reasons to limit the shadow extrusion distance to a finite number, - not least of which is compatibility with older cards (which do not - support infinite positions), and shadow caster elimination. - @par - The default value is 10,000 world units. This does not apply to - point lights or spotlights, since they extrude up to their - attenuation range. - */ - void setShadowDirectionalLightExtrusionDistance(Real dist); - /** Gets the distance a shadow volume is extruded for a directional light. - */ - Real getShadowDirectionalLightExtrusionDistance(void) const; - /** Sets the default maximum distance away from the camera that shadows - will be visible. You have to call this function before you create lights - or the default distance of zero will be used. - - Shadow techniques can be expensive, therefore it is a good idea - to limit them to being rendered close to the camera if possible, - and to skip the expense of rendering shadows for distance objects. - This method allows you to set the distance at which shadows will no - longer be rendered. - @note - Each shadow technique can interpret this subtely differently. - For example, one technique may use this to eliminate casters, - another might use it to attenuate the shadows themselves. - You should tweak this value to suit your chosen shadow technique - and scene setup. - */ - void setShadowFarDistance(Real distance); - /** Gets the default maximum distance away from the camera that shadows - will be visible. - */ - Real getShadowFarDistance(void) const - { return mShadowRenderer.mDefaultShadowFarDist; } - Real getShadowFarDistanceSquared(void) const - { return mShadowRenderer.mDefaultShadowFarDistSquared; } - - /** Sets the maximum size of the index buffer used to render shadow - primitives. - - This method allows you to tweak the size of the index buffer used - to render shadow primitives (including stencil shadow volumes). The - default size is 51,200 entries, which is 100k of GPU memory, or - enough to render approximately 17,000 triangles. You can reduce this - as long as you do not have any models / world geometry chunks which - could require more than the amount you set. - @par - The maximum number of triangles required to render a single shadow - volume (including light and dark caps when needed) will be 3x the - number of edges on the light silhouette, plus the number of - light-facing triangles. On average, half the - triangles will be facing toward the light, but the number of - triangles in the silhouette entirely depends on the mesh - - angular meshes will have a higher silhouette tris/mesh tris - ratio than a smooth mesh. You can estimate the requirements for - your particular mesh by rendering it alone in a scene with shadows - enabled and a single light - rotate it or the light and make a note - of how high the triangle count goes (remembering to subtract the - mesh triangle count) - @param size The number of indexes; divide this by 3 to determine the - number of triangles. - */ - void setShadowIndexBufferSize(size_t size); - /// Get the size of the shadow index buffer - size_t getShadowIndexBufferSize(void) const { return mShadowRenderer.mShadowIndexBufferSize; } - /** Get the shadow camera setup in use for all lights which don't have - their own shadow camera setup. - @see ShadowCameraSetup - */ - const ShadowCameraSetupPtr& getShadowCameraSetup() const; - - /** Sets whether we should use an infinite camera far plane - when rendering stencil shadows. - - Stencil shadow coherency is very reliant on the shadow volume - not being clipped by the far plane. If this clipping happens, you - get a kind of 'negative' shadow effect. The best way to achieve - coherency is to move the far plane of the camera out to infinity, - thus preventing the far plane from clipping the shadow volumes. - When combined with vertex program extrusion of the volume to - infinity, which Ogre does when available, this results in very - robust shadow volumes. For this reason, when you enable stencil - shadows, Ogre automatically changes your camera settings to - project to infinity if the card supports it. You can disable this - behaviour if you like by calling this method; although you can - never enable infinite projection if the card does not support it. - @par - If you disable infinite projection, or it is not available, - you need to be far more careful with your light attenuation / - directional light extrusion distances to avoid clipping artefacts - at the far plane. - @note - Recent cards will generally support infinite far plane projection. - However, we have found some cases where they do not, especially - on Direct3D. There is no standard capability we can check to - validate this, so we use some heuristics based on experience: -
    -
  • OpenGL always seems to support it no matter what the card
  • -
  • Direct3D on non-vertex program capable systems (including - vertex program capable cards on Direct3D7) does not - support it
  • -
  • Direct3D on GeForce3 and GeForce4 Ti does not seem to support - infinite projection
  • -
- Therefore in the RenderSystem implementation, we may veto the use - of an infinite far plane based on these heuristics. - */ - void setShadowUseInfiniteFarPlane(bool enable) { - mShadowRenderer.mShadowUseInfiniteFarPlane = enable; } - - /** Is there a stencil shadow based shadowing technique in use? */ - bool isShadowTechniqueStencilBased(void) const - { return (mShadowRenderer.mShadowTechnique & SHADOWDETAILTYPE_STENCIL) != 0; } - /** Is there a texture shadow based shadowing technique in use? */ - bool isShadowTechniqueTextureBased(void) const - { return (mShadowRenderer.mShadowTechnique & SHADOWDETAILTYPE_TEXTURE) != 0; } - /** Is there a modulative shadowing technique in use? */ - bool isShadowTechniqueModulative(void) const - { return (mShadowRenderer.mShadowTechnique & SHADOWDETAILTYPE_MODULATIVE) != 0; } - /** Is there an additive shadowing technique in use? */ - bool isShadowTechniqueAdditive(void) const - { return (mShadowRenderer.mShadowTechnique & SHADOWDETAILTYPE_ADDITIVE) != 0; } - /** Is the shadow technique integrated into primary materials? */ - bool isShadowTechniqueIntegrated(void) const - { return (mShadowRenderer.mShadowTechnique & SHADOWDETAILTYPE_INTEGRATED) != 0; } - /** Is there any shadowing technique in use? */ - bool isShadowTechniqueInUse(void) const - { return mShadowRenderer.mShadowTechnique != SHADOWTYPE_NONE; } - /** Sets whether when using a built-in additive shadow mode, user clip - planes should be used to restrict light rendering. - */ - void setShadowUseLightClipPlanes(bool enabled) { mShadowRenderer.mShadowAdditiveLightClip = enabled; } - /** Gets whether when using a built-in additive shadow mode, user clip - planes should be used to restrict light rendering. - */ - bool getShadowUseLightClipPlanes() const { return mShadowRenderer.mShadowAdditiveLightClip; } - /// @} - - /// @name Shadow Texture Config - /// @{ - - /// Method for preparing shadow textures ready for use in a regular render - /// Do not call manually unless before frame start or rendering is paused - /// If lightList is not supplied, will render all lights in frustum - virtual void prepareShadowTextures(Camera* cam, Viewport* vp, const LightList* lightList = 0); - - /** Set the size of the texture used for all texture-based shadows. - - The larger the shadow texture, the better the detail on - texture based shadows, but obviously this takes more memory. - The default size is 512. Sizes must be a power of 2. - @note This is the simple form, see setShadowTextureConfig for the more - complex form. - */ - void setShadowTextureSize(unsigned short size) { mShadowRenderer.setShadowTextureSize(size); } - - /** Set the detailed configuration for a shadow texture. - @param shadowIndex The index of the texture to configure, must be < the - number of shadow textures setting - @param width The width of the texture - @param height The height of the texture - @param format The pixel format of the texture - @param fsaa The level of multisampling to use. Ignored if the device does not support it. - @param depthBufferPoolId The pool # it should query the depth buffers from - */ - void setShadowTextureConfig(size_t shadowIndex, uint16 width, uint16 height, PixelFormat format, - uint16 fsaa = 0, uint16 depthBufferPoolId = 1) - { - mShadowRenderer.setShadowTextureConfig(shadowIndex, width, height, format, fsaa, depthBufferPoolId); - } - /** Set the detailed configuration for a shadow texture. - @param shadowIndex The index of the texture to configure, must be < the - number of shadow textures setting - @param config Configuration structure - */ - void setShadowTextureConfig(size_t shadowIndex, const ShadowTextureConfig& config) - { - mShadowRenderer.setShadowTextureConfig(shadowIndex, config); - } - - /** Get the current shadow texture settings. */ - const ShadowTextureConfigList& getShadowTextureConfigList() const { return mShadowRenderer.mShadowTextureConfigList; } - - /// @deprecated use getShadowTextureConfigList - OGRE_DEPRECATED ConstShadowTextureConfigIterator getShadowTextureConfigIterator() const; - - /** Set the pixel format of the textures used for texture-based shadows. - - By default, a colour texture is used (PF_X8R8G8B8) for texture shadows, - but if you want to use more advanced texture shadow types you can - alter this. If you do, you will have to also call - setShadowTextureCasterMaterial and setShadowTextureReceiverMaterial - to provide shader-based materials to use these customised shadow - texture formats. - @note This is the simple form, see setShadowTextureConfig for the more - complex form. - */ - void setShadowTexturePixelFormat(PixelFormat fmt) - { - mShadowRenderer.setShadowTexturePixelFormat(fmt); - } - /** Set the level of multisample AA of the textures used for texture-based shadows. - - By default, the level of multisample AA is zero. - @note This is the simple form, see setShadowTextureConfig for the more - complex form. - */ - void setShadowTextureFSAA(unsigned short fsaa) { mShadowRenderer.setShadowTextureFSAA(fsaa); } - - /** Set the number of textures allocated for texture-based shadows. - - The default number of textures assigned to deal with texture based - shadows is 1; however this means you can only have one light casting - shadows at the same time. You can increase this number in order to - make this more flexible, but be aware of the texture memory it will use. - */ - void setShadowTextureCount(size_t count) { mShadowRenderer.setShadowTextureCount(count); } - - /// @deprecated use getShadowTextureConfigList - OGRE_DEPRECATED size_t getShadowTextureCount(void) const {return mShadowRenderer.mShadowTextureConfigList.size(); } - - /** Set the number of shadow textures a light type uses. - - The default for all light types is 1. This means that each light uses only 1 shadow - texture. Call this if you need more than 1 shadow texture per light, E.G. PSSM. - @note - This feature only works with the Integrated shadow technique. - Also remember to increase the total number of shadow textures you request - appropriately (e.g. via setShadowTextureCount)!! - */ - void setShadowTextureCountPerLightType(Light::LightTypes type, size_t count) - { mShadowRenderer.mShadowTextureCountPerType[type] = count; } - /// Get the number of shadow textures is assigned for the given light type. - size_t getShadowTextureCountPerLightType(Light::LightTypes type) const - {return mShadowRenderer.mShadowTextureCountPerType[type]; } - - /** Sets the size and count of textures used in texture-based shadows. - @see setShadowTextureSize and setShadowTextureCount for details, this - method just allows you to change both at once, which can save on - reallocation if the textures have already been created. - @note This is the simple form, see setShadowTextureConfig for the more - complex form. - */ - void setShadowTextureSettings(uint16 size, uint16 count, PixelFormat fmt = PF_BYTE_RGBA, - uint16 fsaa = 0, uint16 depthBufferPoolId = 1) - { - mShadowRenderer.setShadowTextureSettings(size, count, fmt, fsaa, depthBufferPoolId); - } - - /** Get a reference to the shadow texture currently in use at the given index. - @note - If you change shadow settings, this reference may no longer - be correct, so be sure not to hold the returned reference over - texture shadow configuration changes. - */ - const TexturePtr& getShadowTexture(size_t shadowIndex) - { - return mShadowRenderer.getShadowTexture(shadowIndex); - } - - /** Sets the proportional distance which a texture shadow which is generated from a - directional light will be offset into the camera view to make best use of texture space. - - When generating a shadow texture from a directional light, an approximation is used - since it is not possible to render the entire scene to one texture. - The texture is projected onto an area centred on the camera, and is - the shadow far distance * 2 in length (it is square). This wastes - a lot of texture space outside the frustum though, so this offset allows - you to move the texture in front of the camera more. However, be aware - that this can cause a little shadow 'jittering' during rotation, and - that if you move it too far then you'll start to get artefacts close - to the camera. The value is represented as a proportion of the shadow - far distance, and the default is 0.6. - */ - void setShadowDirLightTextureOffset(Real offset) { mShadowRenderer.mShadowTextureOffset = offset;} - /** Gets the proportional distance which a texture shadow which is generated from a - directional light will be offset into the camera view to make best use of texture space. - */ - Real getShadowDirLightTextureOffset(void) const { return mShadowRenderer.mShadowTextureOffset; } - /** Sets the proportional distance at which texture shadows begin to fade out. - - To hide the edges where texture shadows end (in directional lights) - Ogre will fade out the shadow in the distance. This value is a proportional - distance of the entire shadow visibility distance at which the shadow - begins to fade out. The default is 0.7 - */ - void setShadowTextureFadeStart(Real fadeStart) - { mShadowRenderer.mShadowTextureFadeStart = fadeStart; } - /** Sets the proportional distance at which texture shadows finish to fading out. - - To hide the edges where texture shadows end (in directional lights) - Ogre will fade out the shadow in the distance. This value is a proportional - distance of the entire shadow visibility distance at which the shadow - is completely invisible. The default is 0.9. - */ - void setShadowTextureFadeEnd(Real fadeEnd) - { mShadowRenderer.mShadowTextureFadeEnd = fadeEnd; } - - /** Sets whether or not texture shadows should attempt to self-shadow. - - The default implementation of texture shadows uses a fixed-function - colour texture projection approach for maximum compatibility, and - as such cannot support self-shadowing. However, if you decide to - implement a more complex shadowing technique using the - setShadowTextureCasterMaterial and setShadowTextureReceiverMaterial - there is a possibility you may be able to support - self-shadowing (e.g by implementing a shader-based shadow map). In - this case you might want to enable this option. - @param selfShadow Whether to attempt self-shadowing with texture shadows - */ - void setShadowTextureSelfShadow(bool selfShadow); - - /// Gets whether or not texture shadows attempt to self-shadow. - bool getShadowTextureSelfShadow(void) const - { return mShadowRenderer.mShadowTextureSelfShadow; } - /** Sets the default material to use for rendering shadow casters. - - By default shadow casters are rendered into the shadow texture using - an automatically generated fixed-function pass. This allows basic - projective texture shadows, but it's possible to use more advanced - shadow techniques by overriding the caster and receiver materials, for - example providing vertex and fragment programs to implement shadow - maps. - @par - You can rely on the ambient light in the scene being set to the - requested texture shadow colour, if that's useful. - @note - Individual objects may also override the vertex program in - your default material if their materials include - shadow_caster_vertex_program_ref, shadow_receiver_vertex_program_ref - shadow_caster_material entries, so if you use both make sure they are compatible. - @note - Only a single pass is allowed in your material, although multiple - techniques may be used for hardware fallback. - */ - void setShadowTextureCasterMaterial(const MaterialPtr& mat) - { mShadowRenderer.setShadowTextureCasterMaterial(mat); } - - /** Sets the default material to use for rendering shadow receivers. - - By default shadow receivers are rendered as a post-pass using basic - modulation. This allows basic projective texture shadows, but it's - possible to use more advanced shadow techniques by overriding the - caster and receiver materials, for example providing vertex and - fragment programs to implement shadow maps. - @par - You can rely on texture unit 0 containing the shadow texture, and - for the unit to be set to use projective texturing from the light - (only useful if you're using fixed-function, which is unlikely; - otherwise you should rely on the texture_viewproj_matrix auto binding) - @note - Individual objects may also override the vertex program in - your default material if their materials include - shadow_caster_vertex_program_ref shadow_receiver_vertex_program_ref - shadow_receiver_material entries, so if you use both make sure they are compatible. - @note - Only a single pass is allowed in your material, although multiple - techniques may be used for hardware fallback. - */ - void setShadowTextureReceiverMaterial(const MaterialPtr& mat) - { mShadowRenderer.setShadowTextureReceiverMaterial(mat); } - - /** Sets whether or not shadow casters should be rendered into shadow - textures using their back faces rather than their front faces. - - Rendering back faces rather than front faces into a shadow texture - can help minimise depth comparison issues, if you're using depth - shadowmapping. You will probably still need some biasing but you - won't need as much. For solid objects the result is the same anyway, - if you have objects with holes you may want to turn this option off. - The default is to enable this option. - */ - void setShadowCasterRenderBackFaces(bool bf) { mShadowRenderer.mShadowCasterRenderBackFaces = bf; } - - /** Gets whether or not shadow casters should be rendered into shadow - textures using their back faces rather than their front faces. - */ - bool getShadowCasterRenderBackFaces() const { return mShadowRenderer.mShadowCasterRenderBackFaces; } - - /** Set the shadow camera setup to use for all lights which don't have - their own shadow camera setup. - @see ShadowCameraSetup - */ - void setShadowCameraSetup(const ShadowCameraSetupPtr& shadowSetup); - /// @} - - /** Sets the active compositor chain of the current scene being rendered. - @note CompositorChain does this automatically, no need to call manually. - */ - void _setActiveCompositorChain(CompositorChain* chain) { mActiveCompositorChain = chain; } - - /** Sets whether to use late material resolving or not. If set, materials will be resolved - from the materials at the pass-setting stage and not at the render queue building stage. - This is useful when the active material scheme during the render queue building stage - is different from the one during the rendering stage. - */ - void setLateMaterialResolving(bool isLate) { mLateMaterialResolving = isLate; } - - /** Gets whether using late material resolving or not. - @see setLateMaterialResolving */ - bool isLateMaterialResolving() const { return mLateMaterialResolving; } - - /** Gets the active compositor chain of the current scene being rendered */ - CompositorChain* _getActiveCompositorChain() const { return mActiveCompositorChain; } - - /** Add a listener which will get called back on scene manager events. - */ - void addListener(Listener* s); - /** Remove a listener - */ - void removeListener(Listener* s); - - /** Add a listener which will get called back on shadow texture events. - */ - void addShadowTextureListener(ShadowTextureListener* s); - /** Remove a listener - */ - void removeShadowTextureListener(ShadowTextureListener* s); - - /// @name Static Geometry - /// @{ - /** Creates a StaticGeometry instance suitable for use with this - SceneManager. - - StaticGeometry is a way of batching up geometry into a more - efficient form at the expense of being able to move it. Please - read the StaticGeometry class documentation for full information. - @param name The name to give the new object - @return The new StaticGeometry instance - */ - StaticGeometry* createStaticGeometry(const String& name); - /** Retrieve a previously created StaticGeometry instance. - @note Throws an exception if the named instance does not exist - */ - StaticGeometry* getStaticGeometry(const String& name) const; - /** Returns whether a static geometry instance with the given name exists. */ - bool hasStaticGeometry(const String& name) const; - /** Remove & destroy a StaticGeometry instance. */ - void destroyStaticGeometry(StaticGeometry* geom); - /** Remove & destroy a StaticGeometry instance. */ - void destroyStaticGeometry(const String& name); - /** Remove & destroy all StaticGeometry instances. */ - void destroyAllStaticGeometry(void); - /// @} - - /// @name Instancing - /// @{ - /** Creates an InstanceManager interface to create & manipulate instanced entities - You need to call this function at least once before start calling createInstancedEntity - to build up an instance based on the given mesh. - - Instancing is a way of batching up geometry into a much more - efficient form, but with some limitations, and still be able to move & animate it. - Please see @ref InstanceManager class documentation for full information. - @param customName Custom name for referencing. Must be unique - @param meshName The mesh name the instances will be based upon - @param groupName The resource name where the mesh lives - @param technique Technique to use, which may be shader based, or hardware based. - @param numInstancesPerBatch Suggested number of instances per batch. The actual number - may end up being lower if the technique doesn't support having so many. It can't be zero - @param flags Flags to pass to the InstanceManager see #InstanceManagerFlags - @param subMeshIdx InstanceManager only supports using one submesh from the base mesh. This parameter - says which submesh to pick (must be <= Mesh::getNumSubMeshes()) - @return The new InstanceManager instance - */ - InstanceManager* createInstanceManager( const String &customName, const String &meshName, - const String &groupName, - InstanceManager::InstancingTechnique technique, - size_t numInstancesPerBatch, uint16 flags=0, - unsigned short subMeshIdx=0 ); - - /** Retrieves an existing InstanceManager by it's name. - @note Throws an exception if the named InstanceManager does not exist - */ - InstanceManager* getInstanceManager( const String &managerName ) const; - - /** Returns whether an InstanceManager with the given name exists. */ - bool hasInstanceManager( const String &managerName ) const; - - /** Destroys an InstanceManager if it was created with createInstanceManager() - - Be sure you don't have any InstancedEntity referenced somewhere which was created with - this manager, since it will become a dangling pointer. - @param name Name of the manager to remove - */ - void destroyInstanceManager( const String &name ); - void destroyInstanceManager( InstanceManager *instanceManager ); - - void destroyAllInstanceManagers(void); - - /** @see InstanceManager::getMaxOrBestNumInstancesPerBatch - - If you've already created an InstanceManager, you can call it's - getMaxOrBestNumInstancesPerBatch() function directly. - Another (not recommended) way to know if the technique is unsupported is by creating - an InstanceManager and use createInstancedEntity, which will return null pointer. - The input parameter "numInstancesPerBatch" is a suggested value when using IM_VTFBESTFIT - flag (in that case it should be non-zero) - @return - The ideal (or maximum, depending on flags) number of instances per batch for - the given technique. Zero if technique is unsupported or errors were spotted - */ - size_t getNumInstancesPerBatch( const String &meshName, const String &groupName, - const String &materialName, - InstanceManager::InstancingTechnique technique, - size_t numInstancesPerBatch, uint16 flags=0, - unsigned short subMeshIdx=0 ); - - /** Creates an InstancedEntity based on an existing InstanceManager - - - Return value may be null if the InstanceManger technique isn't supported - - Try to keep the number of entities with different materials to a minimum - - Alternatively you can call @ref InstanceManager::createInstancedEntity using the returned - pointer from createInstanceManager() - @see InstanceBatch - @param materialName Material name - @param managerName Name of the instance manager - @return An InstancedEntity ready to be attached to a SceneNode - */ - InstancedEntity* createInstancedEntity( const String &materialName, - const String &managerName ); - - /** Removes an InstancedEntity, @see SceneManager::createInstancedEntity & - @see InstanceBatch::removeInstancedEntity - @param instancedEntity Instance to remove - */ - void destroyInstancedEntity( InstancedEntity *instancedEntity ); - - /** Called by an InstanceManager when it has at least one InstanceBatch that needs their bounds - to be updated for proper culling - @param dirtyManager The manager with dirty batches to update - */ - void _addDirtyInstanceManager( InstanceManager *dirtyManager ); - /// @} - - typedef MapIterator MovableObjectIterator; - /// @name Movable Objects - /// @{ - /** Create a movable object of the type specified. - - This is the generalised form of MovableObject creation where you can - create a MovableObject of any specialised type generically, including - any new types registered using plugins. - @param name The name to give the object. Must be unique within type. - @param typeName The type of object to create - @param params Optional name/value pair list to give extra parameters to - the created object. - */ - MovableObject* createMovableObject(const String& name, - const String& typeName, const NameValuePairList* params = 0); - /// @overload - MovableObject* createMovableObject(const String& typeName, const NameValuePairList* params = 0); - /** Destroys a MovableObject with the name specified, of the type specified. - - The MovableObject will automatically detach itself from any nodes - on destruction. - */ - void destroyMovableObject(const String& name, const String& typeName); - /** Destroys a MovableObject. - - The MovableObject will automatically detach itself from any nodes - on destruction. - */ - void destroyMovableObject(MovableObject* m); - /** Destroy all MovableObjects of a given type. */ - void destroyAllMovableObjectsByType(const String& typeName); - /** Destroy all MovableObjects. */ - void destroyAllMovableObjects(void); - /** Get a reference to a previously created object instance - @note Throws an exception if the named instance does not exist - */ - MovableObject* getMovableObject(const String& name, const String& typeName) const; - /** Returns whether a object instance with the given name exists. */ - bool hasMovableObject(const String& name, const String& typeName) const; - /** Get all MovableObect instances of a given type. - @note - The iterator returned from this method is not thread safe, do not use this - if you are creating or deleting objects of this type in another thread. - */ - const MovableObjectMap& getMovableObjects(const String& typeName); - - /// @deprecated use getMovableObjects - OGRE_DEPRECATED MovableObjectIterator getMovableObjectIterator(const String& typeName); - /** Inject a MovableObject instance created externally. - - This method 'injects' a MovableObject instance created externally into - the MovableObject instance registry held in the SceneManager. You - might want to use this if you have a MovableObject which you don't - want to register a factory for; for example a MovableObject which - cannot be generally constructed by clients. - @note - It is important that the MovableObject has a unique name for the type, - and that its getMovableType() method returns a proper type name. - */ - void injectMovableObject(MovableObject* m); - /** Extract a previously injected MovableObject. - - Essentially this does the same as destroyMovableObject, but only - removes the instance from the internal lists, it does not attempt - to destroy it. - */ - void extractMovableObject(const String& name, const String& typeName); - /// @overload - void extractMovableObject(MovableObject* m); - /** Extract all injected MovableObjects of a given type. - - Essentially this does the same as destroyAllMovableObjectsByType, - but only removes the instances from the internal lists, it does not - attempt to destroy them. - */ - void extractAllMovableObjectsByType(const String& typeName); - /// @} - - /** Sets a mask which is bitwise 'and'ed with objects own visibility masks - to determine if the object is visible. - - Note that this is combined with any per-viewport visibility mask - through an 'and' operation. @see Viewport::setVisibilityMask - */ - void setVisibilityMask(uint32 vmask) { mVisibilityMask = vmask; } - - /** Gets a mask which is bitwise 'and'ed with objects own visibility masks - to determine if the object is visible. - */ - uint32 getVisibilityMask(void) { return mVisibilityMask; } - - /** Internal method for getting the combination between the global visibility - mask and the per-viewport visibility mask. - */ - uint32 _getCombinedVisibilityMask(void) const; - - /** Sets whether the SceneManager should search for visible objects, or - whether they are being manually handled. - - This is an advanced function, you should not use this unless you know - what you are doing. - */ - void setFindVisibleObjects(bool find) { mFindVisibleObjects = find; } - - /** Gets whether the SceneManager should search for visible objects, or - whether they are being manually handled. - */ - bool getFindVisibleObjects(void) { return mFindVisibleObjects; } - - /** Set whether to automatically flip the culling mode on objects whenever they - are negatively scaled. - - Negativelyl scaling an object has the effect of flipping the triangles, - so the culling mode should probably be inverted to deal with this. - If you would prefer to manually manage this, set this option to 'false' - and use different materials with Pass::setCullingMode set manually as needed. - */ - void setFlipCullingOnNegativeScale(bool n) { mFlipCullingOnNegativeScale = n; } - - /** Get whether to automatically flip the culling mode on objects whenever they - are negatively scaled. - */ - bool getFlipCullingOnNegativeScale() const { return mFlipCullingOnNegativeScale; } - - /** Render something as if it came from the current queue. - @param rend The renderable to issue to the pipeline - @param pass The pass which is being used - @param doLightIteration If true, this method will issue the renderable to - the pipeline possibly multiple times, if the pass indicates it should be - done once per light - @param manualLightList Only applicable if doLightIteration is false, this - method allows you to pass in a previously determined set of lights - which will be used for a single render of this object. - @param shadowDerivation If false, disables the derivation of shadow - passes from original passes - */ - void _injectRenderWithPass(Pass *pass, Renderable *rend, bool shadowDerivation = true, - bool doLightIteration = false, const LightList* manualLightList = 0); - - /** Internal method for setting up the renderstate for a rendering pass. - @param pass The Pass details to set. - @param shadowDerivation If false, disables the derivation of shadow - passes from original passes - @return - A Pass object that was used instead of the one passed in, can - happen when rendering shadow passes - */ - const Pass* _setPass(const Pass* pass, bool shadowDerivation = true); - - /** Method to allow you to mark gpu parameters as dirty, causing them to - be updated according to the mask that you set when updateGpuProgramParameters is - next called. Only really useful if you're controlling parameter state in - inner rendering loop callbacks. - @param mask Some combination of GpuParamVariability which is bitwise OR'ed with the - current dirty state. - */ - void _markGpuParamsDirty(uint16 mask); - - /** Render the objects in a given queue group - */ - void _renderQueueGroupObjects(RenderQueueGroup* group, - QueuedRenderableCollection::OrganisationMode om); - - /** Advanced method for supplying an alternative visitor, used for parsing the - render queues and sending the results to the renderer. - - You can use this method to insert your own implementation of the - QueuedRenderableVisitor interface, which receives calls as the queued - renderables are parsed in a given order - and are sent to the renderer. If you provide your own implementation of - this visitor, you are responsible for either calling the rendersystem, - or passing the calls on to the base class implementation. - @note - Ownership is not taken of this pointer, you are still required to - delete it yourself once you're finished. - @param visitor Your implementation of SceneMgrQueuedRenderableVisitor. - If you pass 0, the default implementation will be used. - */ - void setQueuedRenderableVisitor(SceneMgrQueuedRenderableVisitor* visitor); - - /** Gets the current visitor object which processes queued renderables. */ - SceneMgrQueuedRenderableVisitor* getQueuedRenderableVisitor(void) const - { - return mActiveQueuedRenderableVisitor; - } - - /** Get the rendersystem subclass to which the output of this Scene Manager - gets sent - */ - RenderSystem *getDestinationRenderSystem(); - - /** Gets the current viewport being rendered (advanced use only, only - valid during viewport update. */ - Viewport* getCurrentViewport(void) const { return mCurrentViewport; } - - /** Returns a visibility boundary box for a specific camera. */ - const VisibleObjectsBoundsInfo& getVisibleObjectsBoundsInfo(const Camera* cam) const; - - /** Returns the shadow caster AAB for a specific light-camera combination */ - const VisibleObjectsBoundsInfo& getShadowCasterBoundsInfo(const Light* light, size_t iteration = 0) const; - - /** Add a level of detail listener. */ - void addLodListener(LodListener *listener); - - /** - Remove a level of detail listener. - - Do not call from inside an LodListener callback method. - */ - void removeLodListener(LodListener *listener); - - /** Notify that a movable object LOD change event has occurred. */ - void _notifyMovableObjectLodChanged(MovableObjectLodChangedEvent& evt); - - /** Notify that an entity mesh LOD change event has occurred. */ - void _notifyEntityMeshLodChanged(EntityMeshLodChangedEvent& evt); - - /** Notify that an entity material LOD change event has occurred. */ - void _notifyEntityMaterialLodChanged(EntityMaterialLodChangedEvent& evt); - - /** Handle LOD events. */ - void _handleLodEvents(); - - IlluminationRenderStage _getCurrentRenderStage() {return mIlluminationStage;} - - const AutoParamDataSource* _getAutoParamDataSource() { return mAutoParamDataSource.get(); } - }; - - /// Interface for visualising debugging the SceneManager state - class _OgreExport DebugDrawer : public SceneManager::Listener - { - public: - virtual ~DebugDrawer() {} - virtual void drawSceneNode(const SceneNode* node) = 0; - virtual void drawBone(const Node* node, const Affine3 & transform = Affine3::IDENTITY) = 0; - virtual void drawFrustum(const Frustum* frust) = 0; - }; - - /** Default implementation of IntersectionSceneQuery. */ - class _OgreExport DefaultIntersectionSceneQuery : - public IntersectionSceneQuery - { - public: - DefaultIntersectionSceneQuery(SceneManager* creator); - ~DefaultIntersectionSceneQuery(); - - void execute(IntersectionSceneQueryListener* listener) override; - }; - - /** Default implementation of RaySceneQuery. */ - class _OgreExport DefaultRaySceneQuery : public RaySceneQuery - { - public: - DefaultRaySceneQuery(SceneManager* creator); - ~DefaultRaySceneQuery(); - - void execute(RaySceneQueryListener* listener) override; - }; - /** Default implementation of SphereSceneQuery. */ - class _OgreExport DefaultSphereSceneQuery : public SphereSceneQuery - { - public: - DefaultSphereSceneQuery(SceneManager* creator); - ~DefaultSphereSceneQuery(); - - void execute(SceneQueryListener* listener) override; - }; - /** Default implementation of PlaneBoundedVolumeListSceneQuery. */ - class _OgreExport DefaultPlaneBoundedVolumeListSceneQuery : public PlaneBoundedVolumeListSceneQuery - { - public: - DefaultPlaneBoundedVolumeListSceneQuery(SceneManager* creator); - ~DefaultPlaneBoundedVolumeListSceneQuery(); - - void execute(SceneQueryListener* listener) override; - }; - /** Default implementation of AxisAlignedBoxSceneQuery. */ - class _OgreExport DefaultAxisAlignedBoxSceneQuery : public AxisAlignedBoxSceneQuery - { - public: - DefaultAxisAlignedBoxSceneQuery(SceneManager* creator); - ~DefaultAxisAlignedBoxSceneQuery(); - - void execute(SceneQueryListener* listener) override; - }; - - /** Class which will create instances of a given SceneManager. */ - class _OgreExport SceneManagerFactory - { - public: - virtual ~SceneManagerFactory() {} - /** Get the SceneManager type created by this factory. */ - virtual const String& getTypeName(void) const = 0; - /** Create a new instance of a SceneManager. - - Don't call directly, use SceneManagerEnumerator::createSceneManager. - */ - virtual SceneManager* createInstance(const String& instanceName) = 0; - /** Destroy an instance of a SceneManager. */ - virtual void destroyInstance(SceneManager* instance) { delete instance; } - - }; - - /// Default scene manager type name - _OgreExport extern const String SMT_DEFAULT; - - /** @} */ - /** @} */ - - -} // Namespace - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreSceneNode.h b/OgreMain/include/OgreSceneNode.h deleted file mode 100644 index cc51b38ccdf..00000000000 --- a/OgreMain/include/OgreSceneNode.h +++ /dev/null @@ -1,487 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _SceneNode_H__ -#define _SceneNode_H__ - -#include "OgrePrerequisites.h" -#include "OgreCommon.h" - -#include "OgreNode.h" -#include "OgreAxisAlignedBox.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - // forward decl - struct VisibleObjectsBoundsInfo; - template class ConstVectorIterator; - template class VectorIterator; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** Class representing a node in the scene graph. - - A SceneNode is a type of Node which is used to organise objects in a scene. - It has the same hierarchical transformation properties of the generic Node class, - but also adds the ability to attach world objects to the node, and stores hierarchical - bounding volumes of the nodes in the tree. - Child nodes are contained within the bounds of the parent, and so on down the - tree, allowing for fast culling. - */ - class _OgreExport SceneNode : public Node - { - friend class SceneManager; - public: - typedef std::vector ObjectMap; - typedef VectorIterator ObjectIterator; - typedef ConstVectorIterator ConstObjectIterator; - - protected: - ObjectMap mObjectsByName; - - /// SceneManager which created this node - SceneManager* mCreator; - - /// Auto tracking target - SceneNode* mAutoTrackTarget; - - /** Index in the vector holding this node reference. Used for O(1) removals. - - It is the parent (or our creator) the one that sets this value, not ourselves. Do NOT modify - it manually. - */ - size_t mGlobalIndex; - - /// World-Axis aligned bounding box, updated only through _update - AxisAlignedBox mWorldAABB; - - void updateFromParentImpl(void) const override; - - /** See Node */ - void setParent(Node* parent) override; - - /// Tracking offset for fine tuning - Vector3 mAutoTrackOffset; - /// Local 'normal' direction vector - Vector3 mAutoTrackLocalDirection; - /// Fixed axis to yaw around - Vector3 mYawFixedAxis; - - /// Whether to yaw around a fixed axis. - bool mYawFixed : 1; - /// Is this node a current part of the scene graph? - bool mIsInSceneGraph : 1; - private: // private in 1.13 - /// Flag that determines if the bounding box of the node should be displayed - bool mShowBoundingBox : 1; - - /** Internal method for setting whether the node is in the scene - graph. - */ - virtual void setInSceneGraph(bool inGraph); - /** See Node. */ - Node* createChildImpl(void) override; - - /** See Node. */ - Node* createChildImpl(const String& name) override; - public: - /** Constructor, only to be called by the creator SceneManager. - - Creates a node with a generated name. - */ - SceneNode(SceneManager* creator); - /** Constructor, only to be called by the creator SceneManager. - - Creates a node with a specified name. - */ - SceneNode(SceneManager* creator, const String& name); - ~SceneNode(); - - /** Adds an instance of a scene object to this node. - - Scene objects can include Entity objects, Camera objects, Light objects, - ParticleSystem objects etc. Anything that subclasses from MovableObject. - */ - virtual void attachObject(MovableObject* obj); - - /** Reports the number of objects attached to this node. - */ - size_t numAttachedObjects(void) const { return mObjectsByName.size(); } - - /** Retrieves a pointer to an attached object by index - @note The index of an object may change as other objects are added / removed. - */ - MovableObject* getAttachedObject(size_t index) const { return mObjectsByName.at(index); } - - /** Retrieves a pointer to an attached object by name - */ - MovableObject* getAttachedObject(const String& name) const; - - /** Detaches the indexed object from this scene node. - - Detaches by index, see the alternate version to detach by name. Object indexes - may change as other objects are added / removed. - */ - virtual MovableObject* detachObject(unsigned short index); - /** Detaches an object by pointer. */ - virtual void detachObject(MovableObject* obj); - - /** Detaches the named object from this node and returns a pointer to it. */ - virtual MovableObject* detachObject(const String& name); - - /** Detaches all objects attached to this node. - */ - virtual void detachAllObjects(void); - - /** Detaches and destroys all objects attached to this node. - * - * Does not destroy objects attached to children of this node - */ - void destroyAllObjects(void); - - /** Determines whether this node is in the scene graph, i.e. - whether it's ultimate ancestor is the root scene node. - */ - bool isInSceneGraph(void) const { return mIsInSceneGraph; } - - /** Notifies this SceneNode that it is the root scene node. - - Only SceneManager should call this! - */ - void _notifyRootNode(void) { mIsInSceneGraph = true; } - - - /** Internal method to update the Node. - @note - Updates this scene node and any relevant children to incorporate transforms etc. - Don't call this yourself unless you are writing a SceneManager implementation. - @param - updateChildren If true, the update cascades down to all children. Specify false if you wish to - update children separately, e.g. because of a more selective SceneManager implementation. - @param - parentHasChanged This flag indicates that the parent transform has changed, - so the child should retrieve the parent's transform and combine it with its own - even if it hasn't changed itself. - */ - void _update(bool updateChildren, bool parentHasChanged) override; - - /** Tells the SceneNode to update the world bound info it stores. - */ - virtual void _updateBounds(void); - - /** Internal method which locates any visible objects attached to this node and adds them to the passed in queue. - - Should only be called by a SceneManager implementation, and only after the _updat method has been called to - ensure transforms and world bounds are up to date. - SceneManager implementations can choose to let the search cascade automatically, or choose to prevent this - and select nodes themselves based on some other criteria. - @param - cam The active camera - @param - queue The SceneManager's rendering queue - @param - visibleBounds bounding information created on the fly containing all visible objects by the camera - @param - includeChildren If true, the call is cascaded down to all child nodes automatically. - @param - displayNodes If true, the nodes themselves are rendered as a set of 3 axes as well - as the objects being rendered. For debugging purposes. - @param onlyShadowCasters - */ - void _findVisibleObjects(Camera* cam, RenderQueue* queue, - VisibleObjectsBoundsInfo* visibleBounds, - bool includeChildren = true, bool displayNodes = false, bool onlyShadowCasters = false); - - /** Gets the axis-aligned bounding box of this node (and hence all subnodes). - - Recommended only if you are extending a SceneManager, because the bounding box returned - from this method is only up to date after the SceneManager has called _update. - */ - const AxisAlignedBox& _getWorldAABB(void) const { return mWorldAABB; } - - /// @deprecated use getAttachedObjects() - OGRE_DEPRECATED ObjectIterator getAttachedObjectIterator(void); - /// @deprecated use getAttachedObjects() - OGRE_DEPRECATED ConstObjectIterator getAttachedObjectIterator(void) const; - - /** The MovableObjects attached to this node - * - * This is a much faster way to go through all the objects attached to the node than - * using getAttachedObject. - */ - const ObjectMap& getAttachedObjects() const { - return mObjectsByName; - } - - /** Gets the creator of this scene node. - - This method returns the SceneManager which created this node. - This can be useful for destroying this node. - */ - SceneManager* getCreator(void) const { return mCreator; } - - /** This method removes and destroys the named child and all of its children. - - Unlike removeChild, which removes a single named child from this - node but does not destroy it, this method destroys the child - and all of it's children. - @par - Use this if you wish to recursively destroy a node as well as - detaching it from it's parent. Note that any objects attached to - the nodes will be detached but will not themselves be destroyed. - */ - void removeAndDestroyChild(const String& name); - - /// @overload - void removeAndDestroyChild(unsigned short index); - - /// @overload - void removeAndDestroyChild(SceneNode* child); - - - /** Removes and destroys all children of this node. - - Use this to destroy all child nodes of this node and remove - them from the scene graph. Note that all objects attached to this - node will be detached but will not be destroyed. - */ - void removeAndDestroyAllChildren(void); - - /** Removes and destroys the child and all movable objects attached to the child, - * and does the same to any children of that child node. - * - * Does **not** destroy animation, textures, meshes associated with those movable objects - * */ - void destroyChildAndObjects(const String& name); - ///@overload - void destroyChildAndObjects(unsigned short index); - ///@overload - void destroyChildAndObjects(SceneNode * child); - - /** Destroys everything attatched to or decended from this node - * @par - * Detaches and destroys all objects attached to this node or - * its children. - * Removes and destroys all the children of this node - * @par - * Use this method to complete destroy a node, for example, - * if you want to recreate its render tree from scratch. - * @par - * Does **not** destroy animations, textures, meshes associated with those movable objects - * Does not destroy the node itself - * */ - void destroyAllChildrenAndObjects(); - - /** - * Load a scene from a file as children of this node - * - * The file and any referenced resources will be searched in @ref ResourceGroupManager::getWorldResourceGroupName - * Depending on the type of SceneManager you can load different scene file-formats. - * @param filename source file containing the scene structure - */ - void loadChildren(const String& filename); - - /** - * Save the scene hierarchy starting at this node to file - * - * @param filename destination file - */ - void saveChildren(const String& filename); - - /** Allows the showing of the node's bounding box. - - Use this to show or hide the bounding box of the node. - */ - void showBoundingBox(bool bShow) { mShowBoundingBox = bShow; } - - /** This allows scene managers to determine if the node's bounding box - should be added to the rendering queue. - - Scene Managers that implement their own _findVisibleObjects will have to - check this flag and then use _addBoundingBoxToQueue to add the bounding box - wireframe. - */ - bool getShowBoundingBox() const { return mShowBoundingBox; } - - /** Creates an unnamed new SceneNode as a child of this node. - @param - translate Initial translation offset of child relative to parent - @param - rotate Initial rotation relative to parent - */ - virtual SceneNode* createChildSceneNode( - const Vector3& translate = Vector3::ZERO, - const Quaternion& rotate = Quaternion::IDENTITY ); - - /** Creates a new named SceneNode as a child of this node. - - This creates a child node with a given name, which allows you to look the node up from - the parent which holds this collection of nodes. - @param name name of the node - @param - translate Initial translation offset of child relative to parent - @param - rotate Initial rotation relative to parent - */ - virtual SceneNode* createChildSceneNode(const String& name, const Vector3& translate = Vector3::ZERO, const Quaternion& rotate = Quaternion::IDENTITY); - - /** Allows retrieval of the nearest lights to the centre of this SceneNode. - - This method allows a list of lights, ordered by proximity to the centre - of this SceneNode, to be retrieved. Can be useful when implementing - MovableObject::queryLights and Renderable::getLights. - @par - Note that only lights could be affecting the frustum will take into - account, which cached in scene manager. - @see SceneManager::_getLightsAffectingFrustum - @see SceneManager::_populateLightList - @param destList List to be populated with ordered set of lights; will be - cleared by this method before population. - @param radius Parameter to specify lights intersecting a given radius of - this SceneNode's centre. - @param lightMask The mask with which to include / exclude lights - */ - void findLights(LightList& destList, Real radius, uint32 lightMask = 0xFFFFFFFF) const; - - /** Tells the node whether to yaw around it's own local Y axis or a fixed axis of choice. - - This method allows you to change the yaw behaviour of the node - by default, it - yaws around it's own local Y axis when told to yaw with TS_LOCAL, this makes it - yaw around a fixed axis. - You only really need this when you're using auto tracking (see setAutoTracking, - because when you're manually rotating a node you can specify the TransformSpace - in which you wish to work anyway. - @param - useFixed If true, the axis passed in the second parameter will always be the yaw axis no - matter what the node orientation. If false, the node returns to it's default behaviour. - @param - fixedAxis The axis to use if the first parameter is true. - */ - void setFixedYawAxis( bool useFixed, const Vector3& fixedAxis = Vector3::UNIT_Y ); - - /** Rotate the node around the Y-axis. - */ - void yaw(const Radian& angle, TransformSpace relativeTo = TS_LOCAL) override; - /** Sets the node's direction vector ie it's local -z. - - Note that the 'up' vector for the orientation will automatically be - recalculated based on the current 'up' vector (i.e. the roll will - remain the same). If you need more control, use setOrientation. - @param x,y,z The components of the direction vector - @param relativeTo The space in which this direction vector is expressed - @param localDirectionVector The vector which normally describes the natural - direction of the node, usually -Z - */ - void setDirection(Real x, Real y, Real z, - TransformSpace relativeTo = TS_PARENT, - const Vector3& localDirectionVector = Vector3::NEGATIVE_UNIT_Z); - - /// @overload - void setDirection(const Vector3& vec, TransformSpace relativeTo = TS_PARENT, - const Vector3& localDirectionVector = Vector3::NEGATIVE_UNIT_Z); - /** Points the local -Z direction of this node at a point in space. - @param targetPoint A vector specifying the look at point. - @param relativeTo The space in which the point resides - @param localDirectionVector The vector which normally describes the natural - direction of the node, usually -Z - */ - void lookAt( const Vector3& targetPoint, TransformSpace relativeTo, - const Vector3& localDirectionVector = Vector3::NEGATIVE_UNIT_Z); - /** Enables / disables automatic tracking of another SceneNode. - - If you enable auto-tracking, this SceneNode will automatically rotate to - point it's -Z at the target SceneNode every frame, no matter how - it or the other SceneNode move. Note that by default the -Z points at the - origin of the target SceneNode, if you want to tweak this, provide a - vector in the 'offset' parameter and the target point will be adjusted. - @param enabled If true, tracking will be enabled and the next - parameter cannot be null. If false tracking will be disabled and the - current orientation will be maintained. - @param target Pointer to the SceneNode to track. Make sure you don't - delete this SceneNode before turning off tracking (e.g. SceneManager::clearScene will - delete it so be careful of this). Can be null if and only if the enabled param is false. - @param localDirectionVector The local vector considered to be the usual 'direction' - of the node; normally the local -Z but can be another direction. - @param offset If supplied, this is the target point in local space of the target node - instead of the origin of the target node. Good for fine tuning the look at point. - */ - void setAutoTracking(bool enabled, SceneNode* const target = 0, - const Vector3& localDirectionVector = Vector3::NEGATIVE_UNIT_Z, - const Vector3& offset = Vector3::ZERO); - /** Get the auto tracking target for this node, if any. */ - SceneNode* getAutoTrackTarget(void) const { return mAutoTrackTarget; } - /** Get the auto tracking offset for this node, if the node is auto tracking. */ - const Vector3& getAutoTrackOffset(void) const { return mAutoTrackOffset; } - /** Get the auto tracking local direction for this node, if it is auto tracking. */ - const Vector3& getAutoTrackLocalDirection(void) const { return mAutoTrackLocalDirection; } - /** Internal method used by OGRE to update auto-tracking cameras. */ - void _autoTrack(void); - /** Gets the parent of this SceneNode. */ - SceneNode* getParentSceneNode(void) const; - /** Makes all objects attached to this node become visible / invisible. - - This is a shortcut to calling setVisible() on the objects attached - to this node, and optionally to all objects attached to child - nodes. - @param visible Whether the objects are to be made visible or invisible - @param cascade If true, this setting cascades into child nodes too. - */ - void setVisible(bool visible, bool cascade = true) const; - /** Inverts the visibility of all objects attached to this node. - - This is a shortcut to calling setVisible(!isVisible()) on the objects attached - to this node, and optionally to all objects attached to child - nodes. - @param cascade If true, this setting cascades into child nodes too. - */ - void flipVisibility(bool cascade = true) const; - - /** Tells all objects attached to this node whether to display their - debug information or not. - - This is a shortcut to calling setDebugDisplayEnabled() on the objects attached - to this node, and optionally to all objects attached to child - nodes. - @param enabled Whether the objects are to display debug info or not - @param cascade If true, this setting cascades into child nodes too. - */ - void setDebugDisplayEnabled(bool enabled, bool cascade = true) const; - }; - /** @} */ - /** @} */ - - -}// namespace - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreSceneQuery.h b/OgreMain/include/OgreSceneQuery.h deleted file mode 100644 index 20bb3520a81..00000000000 --- a/OgreMain/include/OgreSceneQuery.h +++ /dev/null @@ -1,482 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __SceneQuery_H__ -#define __SceneQuery_H__ - -#include "OgrePrerequisites.h" -#include "OgreSphere.h" -#include "OgreRay.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - struct WorldFragment; - - /** A class for performing queries on a scene. - - This is an abstract class for performing a query on a scene, i.e. to retrieve - a list of objects and/or world geometry sections which are potentially intersecting a - given region. Note the use of the word 'potentially': the results of a scene query - are generated based on bounding volumes, and as such are not correct at a triangle - level; the user of the SceneQuery is expected to filter the results further if - greater accuracy is required. - - Different SceneManagers will implement these queries in different ways to - exploit their particular scene organisation, and thus will provide their own - concrete subclasses. In fact, these subclasses will be derived from subclasses - of this class rather than directly because there will be region-type classes - in between. - - These queries could have just been implemented as methods on the SceneManager, - however, they are wrapped up as objects to allow 'compilation' of queries - if deemed appropriate by the implementation; i.e. each concrete subclass may - precalculate information (such as fixed scene partitions involved in the query) - to speed up the repeated use of the query. - - You should never try to create a SceneQuery object yourself, they should be created - using the SceneManager interfaces for the type of query required, e.g. - @ref SceneManager::createSphereQuery. - */ - class _OgreExport SceneQuery : public SceneMgtAlloc - { - protected: - SceneManager* mParentSceneMgr; - uint32 mQueryMask; - uint32 mQueryTypeMask; - - public: - /** Standard constructor, should be called by SceneManager. */ - SceneQuery(SceneManager* mgr); - virtual ~SceneQuery(); - - /** Sets the mask for results of this query. - - This method allows you to set a 'mask' to limit the results of this - query to certain types of result. The actual meaning of this value is - up to the application; basically MovableObject instances will only be returned - from this query if a bitwise AND operation between this mask value and the - MovableObject::getQueryFlags value is non-zero. The application will - have to decide what each of the bits means. - */ - virtual void setQueryMask(uint32 mask); - /** Returns the current mask for this query. */ - virtual uint32 getQueryMask(void) const; - - /** Sets the type mask for results of this query. - - This method allows you to set a 'type mask' to limit the results of this - query to certain types of objects. Whilst setQueryMask deals with flags - set per instance of object, this method deals with setting a mask on - flags set per type of object. Both may exclude an object from query - results. - */ - virtual void setQueryTypeMask(uint32 mask); - /** Returns the current mask for this query. */ - virtual uint32 getQueryTypeMask(void) const; - - typedef Ogre::WorldFragment WorldFragment; - }; - - /** This optional class allows you to receive per-result callbacks from - SceneQuery executions instead of a single set of consolidated results. - - You should override this with your own subclass. Note that certain query - classes may refine this listener interface. - */ - class _OgreExport SceneQueryListener - { - public: - virtual ~SceneQueryListener() { } - /** Called when a MovableObject is returned by a query. - - The implementor should return 'true' to continue returning objects, - or 'false' to abandon any further results from this query. - */ - virtual bool queryResult(MovableObject* object) = 0; - /** Called when a WorldFragment is returned by a query. - - The implementor should return 'true' to continue returning objects, - or 'false' to abandon any further results from this query. - */ - virtual bool queryResult(SceneQuery::WorldFragment* fragment) { return false; } - - }; - - typedef std::list SceneQueryResultMovableList; - typedef std::list SceneQueryResultWorldFragmentList; - /** Holds the results of a scene query. */ - struct _OgreExport SceneQueryResult : public SceneMgtAlloc - { - /// List of movable objects in the query (entities, particle systems etc) - SceneQueryResultMovableList movables; - /// Only relevant for the BSP Scene Manager. List of world fragments - SceneQueryResultWorldFragmentList worldFragments; - }; - - /** Abstract class defining a query which returns single results from a region. - - This class is simply a generalisation of the subtypes of query that return - a set of individual results in a region. See the SceneQuery class for abstract - information, and subclasses for the detail of each query type. - */ - class _OgreExport RegionSceneQuery - : public SceneQuery, public SceneQueryListener - { - SceneQueryResult mLastResult; - public: - /** Standard constructor, should be called by SceneManager. */ - RegionSceneQuery(SceneManager* mgr); - virtual ~RegionSceneQuery(); - /** Executes the query, returning the results back in one list. - - This method executes the scene query as configured, gathers the results - into one structure and returns a reference to that structure. These - results will also persist in this query object until the next query is - executed, or clearResults() is called. An more lightweight version of - this method that returns results through a listener is also available. - */ - virtual SceneQueryResult& execute(void); - - /** Executes the query and returns each match through a listener interface. - - Note that this method does not store the results of the query internally - so does not update the 'last result' value. This means that this version of - execute is more lightweight and therefore more efficient than the version - which returns the results as a collection. - */ - virtual void execute(SceneQueryListener* listener) = 0; - - /** Gets the results of the last query that was run using this object, provided - the query was executed using the collection-returning version of execute. - */ - const SceneQueryResult& getLastResults(void) const; - /** Clears the results of the last query execution. - - You only need to call this if you specifically want to free up the memory - used by this object to hold the last query results. This object clears the - results itself when executing and when destroying itself. - */ - void clearResults(void); - - /** Self-callback in order to deal with execute which returns collection. */ - bool queryResult(MovableObject* first) override; - /** Self-callback in order to deal with execute which returns collection. */ - bool queryResult(SceneQuery::WorldFragment* fragment) override; - }; - - /** Specialises the SceneQuery class for querying within an axis aligned box. */ - class _OgreExport AxisAlignedBoxSceneQuery : public RegionSceneQuery - { - protected: - AxisAlignedBox mAABB; - public: - AxisAlignedBoxSceneQuery(SceneManager* mgr); - virtual ~AxisAlignedBoxSceneQuery(); - - /** Sets the size of the box you wish to query. */ - void setBox(const AxisAlignedBox& box); - - /** Gets the box which is being used for this query. */ - const AxisAlignedBox& getBox(void) const; - - }; - - /** Specialises the SceneQuery class for querying within a sphere. */ - class _OgreExport SphereSceneQuery : public RegionSceneQuery - { - protected: - Sphere mSphere; - public: - SphereSceneQuery(SceneManager* mgr); - virtual ~SphereSceneQuery(); - /** Sets the sphere which is to be used for this query. */ - void setSphere(const Sphere& sphere); - - /** Gets the sphere which is being used for this query. */ - const Sphere& getSphere() const; - - }; - - /** Specialises the SceneQuery class for querying within a plane-bounded volume. - */ - class _OgreExport PlaneBoundedVolumeListSceneQuery : public RegionSceneQuery - { - protected: - PlaneBoundedVolumeList mVolumes; - public: - PlaneBoundedVolumeListSceneQuery(SceneManager* mgr); - virtual ~PlaneBoundedVolumeListSceneQuery(); - /** Sets the volume which is to be used for this query. */ - void setVolumes(const PlaneBoundedVolumeList& volumes); - - /** Gets the volume which is being used for this query. */ - const PlaneBoundedVolumeList& getVolumes() const; - - }; - - /** Alternative listener class for dealing with RaySceneQuery. - - Because the RaySceneQuery returns results in an extra bit of information, namely - distance, the listener interface must be customised from the standard SceneQueryListener. - */ - class _OgreExport RaySceneQueryListener - { - public: - virtual ~RaySceneQueryListener() { } - /** Called when a movable objects intersects the ray. - - As with SceneQueryListener, the implementor of this method should return 'true' - if further results are required, or 'false' to abandon any further results from - the current query. - */ - virtual bool queryResult(MovableObject* obj, Real distance) = 0; - - /** Called when a world fragment is intersected by the ray. - - As with SceneQueryListener, the implementor of this method should return 'true' - if further results are required, or 'false' to abandon any further results from - the current query. - */ - virtual bool queryResult(SceneQuery::WorldFragment* fragment, Real distance) = 0; - - }; - - /** This struct allows a single comparison of result data no matter what the type */ - struct _OgreExport RaySceneQueryResultEntry - { - /// Distance along the ray - Real distance; - /// The movable, or NULL if this is not a movable result - MovableObject* movable; - /// Only relevant for the BSP Scene Manager. The world fragment, or NULL if this is not a fragment result - SceneQuery::WorldFragment* worldFragment; - /// Comparison operator for sorting - bool operator < (const RaySceneQueryResultEntry& rhs) const - { - return this->distance < rhs.distance; - } - - }; - typedef std::vector RaySceneQueryResult; - - /** Specialises the SceneQuery class for querying along a ray. */ - class _OgreExport RaySceneQuery : public SceneQuery, public RaySceneQueryListener - { - protected: - Ray mRay; - private: - bool mSortByDistance; - ushort mMaxResults; - RaySceneQueryResult mResult; - - public: - RaySceneQuery(SceneManager* mgr); - virtual ~RaySceneQuery(); - /** Sets the ray which is to be used for this query. */ - virtual void setRay(const Ray& ray); - /** Gets the ray which is to be used for this query. */ - virtual const Ray& getRay(void) const; - /** Sets whether the results of this query will be sorted by distance along the ray. - - Often you want to know what was the first object a ray intersected with, and this - method allows you to ask the query to sort the results so that the nearest results - are listed first. - @par - Note that because the query returns results based on bounding volumes, the ray may not - actually intersect the detail of the objects returned from the query, just their - bounding volumes. For this reason the caller is advised to use more detailed - intersection tests on the results if a more accurate result is required; OGRE uses - bounds checking in order to give the most speedy results since not all applications - need extreme accuracy. - @param sort If true, results will be sorted. - @param maxresults If sorting is enabled, this value can be used to constrain the maximum number - of results that are returned. Please note (as above) that the use of bounding volumes mean that - accuracy is not guaranteed; if in doubt, allow more results and filter them in more detail. - 0 means unlimited results. - */ - virtual void setSortByDistance(bool sort, ushort maxresults = 0); - /** Gets whether the results are sorted by distance. */ - virtual bool getSortByDistance(void) const; - /** Gets the maximum number of results returned from the query (only relevant if - results are being sorted) */ - virtual ushort getMaxResults(void) const; - /** Executes the query, returning the results back in one list. - - This method executes the scene query as configured, gathers the results - into one structure and returns a reference to that structure. These - results will also persist in this query object until the next query is - executed, or clearResults() is called. An more lightweight version of - this method that returns results through a listener is also available. - */ - virtual RaySceneQueryResult& execute(void); - - /** Executes the query and returns each match through a listener interface. - - Note that this method does not store the results of the query internally - so does not update the 'last result' value. This means that this version of - execute is more lightweight and therefore more efficient than the version - which returns the results as a collection. - */ - virtual void execute(RaySceneQueryListener* listener) = 0; - - /** Gets the results of the last query that was run using this object, provided - the query was executed using the collection-returning version of execute. - */ - const RaySceneQueryResult& getLastResults(void) const; - /** Clears the results of the last query execution. - - You only need to call this if you specifically want to free up the memory - used by this object to hold the last query results. This object clears the - results itself when executing and when destroying itself. - */ - void clearResults(void); - - /** Self-callback in order to deal with execute which returns collection. */ - bool queryResult(MovableObject* obj, Real distance) override; - /** Self-callback in order to deal with execute which returns collection. */ - bool queryResult(SceneQuery::WorldFragment* fragment, Real distance) override; - - - - - }; - - /** Alternative listener class for dealing with IntersectionSceneQuery. - - Because the IntersectionSceneQuery returns results in pairs, rather than singularly, - the listener interface must be customised from the standard SceneQueryListener. - */ - class _OgreExport IntersectionSceneQueryListener - { - public: - virtual ~IntersectionSceneQueryListener() { } - /** Called when 2 movable objects intersect one another. - - As with SceneQueryListener, the implementor of this method should return 'true' - if further results are required, or 'false' to abandon any further results from - the current query. - */ - virtual bool queryResult(MovableObject* first, MovableObject* second) = 0; - - /** Called when a movable intersects a world fragment. - - As with SceneQueryListener, the implementor of this method should return 'true' - if further results are required, or 'false' to abandon any further results from - the current query. - */ - virtual bool queryResult(MovableObject* movable, SceneQuery::WorldFragment* fragment) = 0; - - /* NB there are no results for world fragments intersecting other world fragments; - it is assumed that world geometry is either static or at least that self-intersections - are irrelevant or dealt with elsewhere (such as the custom scene manager) */ - - - }; - - typedef std::pair SceneQueryMovableObjectPair; - typedef std::pair SceneQueryMovableObjectWorldFragmentPair; - typedef std::list SceneQueryMovableIntersectionList; - typedef std::list SceneQueryMovableWorldFragmentIntersectionList; - /** Holds the results of an intersection scene query (pair values). */ - struct _OgreExport IntersectionSceneQueryResult : public SceneMgtAlloc - { - /// List of movable / movable intersections (entities, particle systems etc) - SceneQueryMovableIntersectionList movables2movables; - /// List of movable / world intersections - SceneQueryMovableWorldFragmentIntersectionList movables2world; - - - - }; - - /** Separate SceneQuery class to query for pairs of objects which are - possibly intersecting one another. - - This SceneQuery subclass considers the whole world and returns pairs of objects - which are close enough to each other that they may be intersecting. Because of - this slightly different focus, the return types and listener interface are - different for this class. - */ - class _OgreExport IntersectionSceneQuery - : public SceneQuery, public IntersectionSceneQueryListener - { - IntersectionSceneQueryResult* mLastResult; - public: - IntersectionSceneQuery(SceneManager* mgr); - virtual ~IntersectionSceneQuery(); - - /** Executes the query, returning the results back in one list. - - This method executes the scene query as configured, gathers the results - into one structure and returns a reference to that structure. These - results will also persist in this query object until the next query is - executed, or clearResults() is called. An more lightweight version of - this method that returns results through a listener is also available. - */ - virtual IntersectionSceneQueryResult& execute(void); - - /** Executes the query and returns each match through a listener interface. - - Note that this method does not store the results of the query internally - so does not update the 'last result' value. This means that this version of - execute is more lightweight and therefore more efficient than the version - which returns the results as a collection. - */ - virtual void execute(IntersectionSceneQueryListener* listener) = 0; - - /** Gets the results of the last query that was run using this object, provided - the query was executed using the collection-returning version of execute. - */ - virtual IntersectionSceneQueryResult& getLastResults(void) const; - /** Clears the results of the last query execution. - - You only need to call this if you specifically want to free up the memory - used by this object to hold the last query results. This object clears the - results itself when executing and when destroying itself. - */ - void clearResults(void); - - /** Self-callback in order to deal with execute which returns collection. */ - bool queryResult(MovableObject* first, MovableObject* second) override; - /** Self-callback in order to deal with execute which returns collection. */ - bool queryResult(MovableObject* movable, SceneQuery::WorldFragment* fragment) override; - }; - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreScriptCompiler.h b/OgreMain/include/OgreScriptCompiler.h deleted file mode 100644 index 129d29097d2..00000000000 --- a/OgreMain/include/OgreScriptCompiler.h +++ /dev/null @@ -1,845 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __SCRIPTCOMPILER_H_ -#define __SCRIPTCOMPILER_H_ - -#include "OgreSharedPtr.h" -#include "OgreSingleton.h" -#include "OgreScriptLoader.h" -#include "OgreGpuProgram.h" -#include "OgreAny.h" -#include "Threading/OgreThreadHeaders.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Script - * @{ - */ - /** These enums hold the types of the concrete parsed nodes */ - enum ConcreteNodeType - { - CNT_VARIABLE, - CNT_VARIABLE_ASSIGN, - CNT_WORD, - CNT_IMPORT, - CNT_QUOTE, - CNT_LBRACE, - CNT_RBRACE, - CNT_COLON - }; - - /** The ConcreteNode is the struct that holds an un-conditioned sub-tree of parsed input */ - struct ConcreteNode; - typedef SharedPtr ConcreteNodePtr; - typedef std::list ConcreteNodeList; - typedef SharedPtr ConcreteNodeListPtr; - struct ConcreteNode : public ScriptCompilerAlloc - { - String token, file; - unsigned int line; - ConcreteNodeType type; - ConcreteNodeList children; - ConcreteNode *parent; - }; - - /** This enum holds the types of the possible abstract nodes */ - enum AbstractNodeType - { - ANT_UNKNOWN, - ANT_ATOM, - ANT_OBJECT, - ANT_PROPERTY, - ANT_IMPORT, - ANT_VARIABLE_SET, - ANT_VARIABLE_ACCESS - }; - class AbstractNode; - typedef SharedPtr AbstractNodePtr; - typedef std::list AbstractNodeList; - typedef SharedPtr AbstractNodeListPtr; - - class _OgreExport AbstractNode : public AbstractNodeAlloc - { - public: - String file; - unsigned int line; - AbstractNodeType type; - AbstractNode *parent; - Any context; // A holder for translation context data - public: - AbstractNode(AbstractNode *ptr); - virtual ~AbstractNode(){} - /// Returns a new AbstractNode which is a replica of this one. - virtual AbstractNode *clone() const = 0; - /// Returns a string value depending on the type of the AbstractNode. - virtual const String& getValue() const = 0; - /// Returns the string content of the node for ANT_ATOM. Empty string otherwise. - const String& getString() const; - }; - - /** This is an abstract node which cannot be broken down further */ - class _OgreExport AtomAbstractNode : public AbstractNode - { - public: - String value; - uint32 id; - public: - AtomAbstractNode(AbstractNode *ptr); - AbstractNode *clone() const override; - const String& getValue() const override { return value; } - }; - - inline const String& AbstractNode::getString() const - { - return type == ANT_ATOM ? static_cast(this)->value : BLANKSTRING; - } - - /** This specific abstract node represents a script object */ - class _OgreExport ObjectAbstractNode : public AbstractNode - { - private: - std::map mEnv; - public: - String name, cls; - std::vector bases; - uint32 id; - bool abstract; - AbstractNodeList children; - AbstractNodeList values; - AbstractNodeList overrides; // For use when processing object inheritance and overriding - public: - ObjectAbstractNode(AbstractNode *ptr); - AbstractNode *clone() const override; - const String& getValue() const override { return cls; } - - void addVariable(const String &name); - void setVariable(const String &name, const String &value); - std::pair getVariable(const String &name) const; - const std::map &getVariables() const; - }; - - /** This abstract node represents a script property */ - class _OgreExport PropertyAbstractNode : public AbstractNode - { - public: - String name; - uint32 id; - AbstractNodeList values; - public: - PropertyAbstractNode(AbstractNode *ptr); - AbstractNode *clone() const override; - const String& getValue() const override { return name; } - }; - - /** This abstract node represents an import statement */ - class _OgreExport ImportAbstractNode : public AbstractNode - { - public: - String target, source; - public: - ImportAbstractNode(); - AbstractNode *clone() const override; - const String& getValue() const override { return target; } - }; - - /** This abstract node represents a variable assignment */ - class _OgreExport VariableAccessAbstractNode : public AbstractNode - { - public: - String name; - public: - VariableAccessAbstractNode(AbstractNode *ptr); - AbstractNode *clone() const override; - const String& getValue() const override { return name; } - }; - - class ScriptCompilerEvent; - class ScriptCompilerListener; - - /** This is the main class for the compiler. It calls the parser - and processes the CST into an AST and then uses translators - to translate the AST into the final resources. - */ - class _OgreExport ScriptCompiler : public ScriptCompilerAlloc - { - public: // Externally accessible types - //typedef std::map IdMap; - typedef std::unordered_map IdMap; - - // These are the built-in error codes - enum{ - CE_STRINGEXPECTED, - CE_NUMBEREXPECTED, - CE_FEWERPARAMETERSEXPECTED, - CE_VARIABLEEXPECTED, - CE_UNDEFINEDVARIABLE, - CE_OBJECTNAMEEXPECTED, - CE_OBJECTALLOCATIONERROR, - CE_INVALIDPARAMETERS, - CE_DUPLICATEOVERRIDE, - CE_UNEXPECTEDTOKEN, - CE_OBJECTBASENOTFOUND, - CE_REFERENCETOANONEXISTINGOBJECT, - CE_DEPRECATEDSYMBOL - }; - static String formatErrorCode(uint32 code); - public: - ScriptCompiler(); - virtual ~ScriptCompiler() {} - - /// Takes in a string of script code and compiles it into resources - /** - * @param str The script code - * @param source The source of the script code (e.g. a script file) - * @param group The resource group to place the compiled resources into - */ - bool compile(const String &str, const String &source, const String &group); - /// Compiles resources from the given concrete node list - bool compile(const ConcreteNodeListPtr &nodes, const String &group); - /// Adds the given error to the compiler's list of errors - void addError(uint32 code, const String &file, int line, const String &msg = ""); - /// Sets the listener used by the compiler - void setListener(ScriptCompilerListener *listener); - /// Returns the currently set listener - ScriptCompilerListener *getListener(); - /// Returns the resource group currently set for this compiler - const String &getResourceGroup() const; - /// Internal method for firing the handleEvent method - bool _fireEvent(ScriptCompilerEvent *evt, void *retval); - - /// Adds a custom word id which can be used for custom script translators - /** - @param - word The word to be registered. - - @return - The word id for the registered word. - - @note - If the word is already registered, the already registered id is returned. - */ - uint32 registerCustomWordId(const String &word); - - private: // Tree processing - AbstractNodeListPtr convertToAST(const ConcreteNodeList &nodes); - /// This built-in function processes import nodes - void processImports(AbstractNodeList &nodes); - /// Loads the requested script and converts it to an AST - AbstractNodeListPtr loadImportPath(const String &name); - /// Returns the abstract nodes from the given tree which represent the target - AbstractNodeList locateTarget(const AbstractNodeList& nodes, const String &target); - /// Handles object inheritance and variable expansion - void processObjects(AbstractNodeList& nodes, const AbstractNodeList &top); - /// Handles processing the variables - void processVariables(AbstractNodeList& nodes); - /// This function overlays the given object on the destination object following inheritance rules - void overlayObject(const ObjectAbstractNode &source, ObjectAbstractNode& dest); - /// Returns true if the given class is name excluded - bool isNameExcluded(const ObjectAbstractNode& node, AbstractNode *parent); - /// This function sets up the initial values in word id map - void initWordMap(); - private: - friend String getPropertyName(const ScriptCompiler *compiler, uint32 id); - // Resource group - String mGroup; - // The word -> id conversion table - IdMap mIds; - - // The largest registered id - uint32 mLargestRegisteredWordId; - - // This is an environment map - typedef std::map Environment; - Environment mEnv; - - typedef std::map ImportCacheMap; - ImportCacheMap mImports; // The set of imported scripts to avoid circular dependencies - typedef std::multimap ImportRequestMap; - ImportRequestMap mImportRequests; // This holds the target objects for each script to be imported - - // This stores the imports of the scripts, so they are separated and can be treated specially - AbstractNodeList mImportTable; - - // Error list - // The container for errors - struct Error - { - String file, message; - int line; - uint32 code; - }; - typedef std::list ErrorList; - ErrorList mErrors; - - // The listener - ScriptCompilerListener *mListener; - private: // Internal helper classes and processors - class AbstractTreeBuilder - { - private: - AbstractNodeListPtr mNodes; - AbstractNode *mCurrent; - ScriptCompiler *mCompiler; - public: - AbstractTreeBuilder(ScriptCompiler *compiler); - const AbstractNodeListPtr &getResult() const; - void visit(ConcreteNode *node); - static void visit(AbstractTreeBuilder *visitor, const ConcreteNodeList &nodes); - }; - friend class AbstractTreeBuilder; - public: // Public translator definitions - // This enum are built-in word id values - enum - { - ID_ON = 1, - ID_OFF = 2, - ID_TRUE = 1, - ID_FALSE = 2, - ID_YES = 1, - ID_NO = 2 - }; - }; - - /** - * This struct is a base class for events which can be thrown by the compilers and caught by - * subscribers. There are a set number of standard events which are used by Ogre's core. - * New event types may be derived for more custom compiler processing. - */ - class ScriptCompilerEvent - { - public: - String mType; - - ScriptCompilerEvent(const String &type):mType(type){} - virtual ~ScriptCompilerEvent(){} - private: // Non-copyable - ScriptCompilerEvent(const ScriptCompilerEvent&); - ScriptCompilerEvent &operator = (const ScriptCompilerEvent&); - }; - - /** This is a listener for the compiler. The compiler can be customized with - this listener. It lets you listen in on events occurring during compilation, - hook them, and change the behavior. - */ - class _OgreExport ScriptCompilerListener - { - public: - ScriptCompilerListener(); - virtual ~ScriptCompilerListener() {} - - /// Returns the concrete node list from the given file - virtual ConcreteNodeListPtr importFile(ScriptCompiler *compiler, const String &name); - /// Allows for responding to and overriding behavior before a CST is translated into an AST - virtual void preConversion(ScriptCompiler *compiler, ConcreteNodeListPtr nodes); - /// Allows vetoing of continued compilation after the entire AST conversion process finishes - /** - @remarks Once the script is turned completely into an AST, including import - and override handling, this function allows a listener to exit - the compilation process. - @return True continues compilation, false aborts - */ - virtual bool postConversion(ScriptCompiler *compiler, const AbstractNodeListPtr&); - /// Called when an error occurred - virtual void handleError(ScriptCompiler *compiler, uint32 code, const String &file, int line, const String &msg); - /// Called when an event occurs during translation, return true if handled - /** - @remarks This function is called from the translators when an event occurs that - that can be responded to. Often this is overriding names, or it can be a request for - custom resource creation. - @arg compiler A reference to the compiler - @arg evt The event object holding information about the event to be processed - @arg retval A possible return value from handlers - @return True if the handler processed the event - */ - virtual bool handleEvent(ScriptCompiler *compiler, ScriptCompilerEvent *evt, void *retval); - }; - - class ScriptTranslator; - class ScriptTranslatorManager; - - /** Manages threaded compilation of scripts. This script loader forwards - scripts compilations to a specific compiler instance. - */ - class _OgreExport ScriptCompilerManager : public Singleton, public ScriptLoader, public ScriptCompilerAlloc - { - private: - OGRE_AUTO_MUTEX; - - // A list of patterns loaded by this compiler manager - StringVector mScriptPatterns; - - // Stores a map from object types to the translators that handle them - std::vector mManagers; - - // A pointer to the built-in ScriptTranslatorManager - ScriptTranslatorManager *mBuiltinTranslatorManager; - - // the specific compiler instance used - ScriptCompiler mScriptCompiler; - public: - ScriptCompilerManager(); - virtual ~ScriptCompilerManager(); - - /// Sets the listener used for compiler instances - void setListener(ScriptCompilerListener *listener); - /// Returns the currently set listener used for compiler instances - ScriptCompilerListener *getListener(); - - /// Adds the given translator manager to the list of managers - void addTranslatorManager(ScriptTranslatorManager *man); - /// Removes the given translator manager from the list of managers - void removeTranslatorManager(ScriptTranslatorManager *man); - /// Clears all translator managers - void clearTranslatorManagers(); - /// Retrieves a ScriptTranslator from the supported managers - ScriptTranslator *getTranslator(const AbstractNodePtr &node); - - /// Adds a custom word id which can be used for custom script translators - /** - @param - word The word to be registered. - - @return - The word id for the registered word. - - @note - If the word is already registered, the already registered id is returned. - */ - uint32 registerCustomWordId(const String &word); - - /// Adds a script extension that can be handled (e.g. *.material, *.pu, etc.) - void addScriptPattern(const String &pattern); - /// @copydoc ScriptLoader::getScriptPatterns - const StringVector& getScriptPatterns(void) const override; - /// @copydoc ScriptLoader::parseScript - void parseScript(DataStreamPtr& stream, const String& groupName) override; - /// @copydoc ScriptLoader::getLoadingOrder - Real getLoadingOrder(void) const override; - - /// @copydoc Singleton::getSingleton() - static ScriptCompilerManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static ScriptCompilerManager* getSingletonPtr(void); - }; - - class _OgreExport ProcessResourceNameScriptCompilerEvent : public ScriptCompilerEvent - { - public: - enum ResourceType - { - TEXTURE, - MATERIAL, - GPU_PROGRAM, - COMPOSITOR - }; - ResourceType mResourceType; - String mName; - static String eventType; - - ProcessResourceNameScriptCompilerEvent(ResourceType resourceType, const String &name) - :ScriptCompilerEvent(eventType), mResourceType(resourceType), mName(name){} - }; - - class _OgreExport ProcessNameExclusionScriptCompilerEvent : public ScriptCompilerEvent - { - public: - String mClass; - AbstractNode *mParent; - static String eventType; - - ProcessNameExclusionScriptCompilerEvent(const String &cls, AbstractNode *parent) - :ScriptCompilerEvent(eventType), mClass(cls), mParent(parent){} - }; - - class _OgreExport CreateMaterialScriptCompilerEvent : public ScriptCompilerEvent - { - public: - String mFile, mName, mResourceGroup; - static String eventType; - - CreateMaterialScriptCompilerEvent(const String &file, const String &name, const String &resourceGroup) - :ScriptCompilerEvent(eventType), mFile(file), mName(name), mResourceGroup(resourceGroup){} - }; - - class _OgreExport CreateGpuProgramScriptCompilerEvent : public ScriptCompilerEvent - { - public: - String mFile, mName, mResourceGroup, mSource, mSyntax; - GpuProgramType mProgramType; - static String eventType; - - CreateGpuProgramScriptCompilerEvent(const String &file, const String &name, const String &resourceGroup, const String &source, - const String &syntax, GpuProgramType programType) - :ScriptCompilerEvent(eventType), mFile(file), mName(name), mResourceGroup(resourceGroup), mSource(source), - mSyntax(syntax), mProgramType(programType) - {} - }; - - /// @deprecated use CreateGpuProgramScriptCompilerEvent - typedef OGRE_DEPRECATED CreateGpuProgramScriptCompilerEvent CreateHighLevelGpuProgramScriptCompilerEvent; - - class _OgreExport CreateGpuSharedParametersScriptCompilerEvent : public ScriptCompilerEvent - { - public: - String mFile, mName, mResourceGroup; - static String eventType; - - CreateGpuSharedParametersScriptCompilerEvent(const String &file, const String &name, const String &resourceGroup) - :ScriptCompilerEvent(eventType), mFile(file), mName(name), mResourceGroup(resourceGroup){} - }; - - class _OgreExport CreateParticleSystemScriptCompilerEvent : public ScriptCompilerEvent - { - public: - String mFile, mName, mResourceGroup; - static String eventType; - - CreateParticleSystemScriptCompilerEvent(const String &file, const String &name, const String &resourceGroup) - :ScriptCompilerEvent(eventType), mFile(file), mName(name), mResourceGroup(resourceGroup){} - }; - - class _OgreExport CreateCompositorScriptCompilerEvent : public ScriptCompilerEvent - { - public: - String mFile, mName, mResourceGroup; - static String eventType; - - CreateCompositorScriptCompilerEvent(const String &file, const String &name, const String &resourceGroup) - :ScriptCompilerEvent(eventType), mFile(file), mName(name), mResourceGroup(resourceGroup){} - }; - - /// This enum defines the integer ids for keywords this compiler handles - enum - { - ID_MATERIAL = 3, - ID_VERTEX_PROGRAM, - ID_GEOMETRY_PROGRAM, - ID_FRAGMENT_PROGRAM, - ID_TECHNIQUE, - ID_PASS, - ID_TEXTURE_UNIT, - ID_VERTEX_PROGRAM_REF, - ID_GEOMETRY_PROGRAM_REF, - ID_FRAGMENT_PROGRAM_REF, - ID_SHADOW_CASTER_VERTEX_PROGRAM_REF, - ID_SHADOW_CASTER_FRAGMENT_PROGRAM_REF, - ID_SHADOW_RECEIVER_VERTEX_PROGRAM_REF, - ID_SHADOW_RECEIVER_FRAGMENT_PROGRAM_REF, - ID_SHADOW_CASTER_MATERIAL, - ID_SHADOW_RECEIVER_MATERIAL, - - ID_LOD_VALUES, - ID_LOD_STRATEGY, - ID_LOD_DISTANCES, - ID_RECEIVE_SHADOWS, - ID_TRANSPARENCY_CASTS_SHADOWS, - ID_SET_TEXTURE_ALIAS, - - ID_SOURCE, - ID_SYNTAX, - ID_DEFAULT_PARAMS, - ID_PARAM_INDEXED, - ID_PARAM_NAMED, - ID_PARAM_INDEXED_AUTO, - ID_PARAM_NAMED_AUTO, - - ID_SCHEME, - ID_LOD_INDEX, - ID_GPU_VENDOR_RULE, - ID_GPU_DEVICE_RULE, - ID_INCLUDE, - ID_EXCLUDE, - - ID_AMBIENT, - ID_DIFFUSE, - ID_SPECULAR, - ID_EMISSIVE, - ID_VERTEXCOLOUR, - ID_SCENE_BLEND, - ID_COLOUR_BLEND, - ID_ONE, - ID_ZERO, - ID_DEST_COLOUR, - ID_SRC_COLOUR, - ID_ONE_MINUS_DEST_COLOUR, - ID_ONE_MINUS_SRC_COLOUR, - ID_DEST_ALPHA, - ID_SRC_ALPHA, - ID_ONE_MINUS_DEST_ALPHA, - ID_ONE_MINUS_SRC_ALPHA, - ID_SEPARATE_SCENE_BLEND, - ID_SCENE_BLEND_OP, - ID_REVERSE_SUBTRACT, - ID_MIN, - ID_MAX, - ID_SEPARATE_SCENE_BLEND_OP, - ID_DEPTH_CHECK, - ID_DEPTH_WRITE, - ID_DEPTH_FUNC, - ID_DEPTH_BIAS, - ID_ITERATION_DEPTH_BIAS, - ID_ALWAYS_FAIL, - ID_ALWAYS_PASS, - ID_LESS_EQUAL, - ID_LESS, - ID_EQUAL, - ID_NOT_EQUAL, - ID_GREATER_EQUAL, - ID_GREATER, - ID_ALPHA_REJECTION, - ID_ALPHA_TO_COVERAGE, - ID_LIGHT_SCISSOR, - ID_LIGHT_CLIP_PLANES, - ID_TRANSPARENT_SORTING, - ID_ILLUMINATION_STAGE, - ID_DECAL, - ID_CULL_HARDWARE, - ID_CLOCKWISE, - ID_ANTICLOCKWISE, - ID_CULL_SOFTWARE, - ID_BACK, - ID_FRONT, - ID_LIGHTING, - ID_SHADING, - ID_FLAT, - ID_GOURAUD, - ID_PHONG, - ID_POLYGON_MODE, - ID_SOLID, - ID_WIREFRAME, - ID_POINTS, - ID_POLYGON_MODE_OVERRIDEABLE, - ID_FOG_OVERRIDE, - ID_NONE, - ID_LINEAR, - ID_EXP, - ID_EXP2, - ID_COLOUR_WRITE, - ID_MAX_LIGHTS, - ID_START_LIGHT, - ID_ITERATION, - ID_ONCE, - ID_ONCE_PER_LIGHT, - ID_PER_LIGHT, - ID_PER_N_LIGHTS, - ID_POINT, - ID_SPOT, - ID_DIRECTIONAL, - ID_LIGHT_MASK, - ID_POINT_SIZE, - ID_POINT_SPRITES, - ID_POINT_SIZE_ATTENUATION, - ID_POINT_SIZE_MIN, - ID_POINT_SIZE_MAX, - - ID_TEXTURE_ALIAS, - ID_TEXTURE, - ID_1D, - ID_2D, - ID_3D, - ID_CUBIC, - ID_2DARRAY, - ID_UNLIMITED, - ID_ALPHA, - ID_GAMMA, - ID_ANIM_TEXTURE, - ID_CUBIC_TEXTURE, - ID_SEPARATE_UV, - ID_COMBINED_UVW, - ID_TEX_COORD_SET, - ID_TEX_ADDRESS_MODE, - ID_WRAP, - ID_CLAMP, - ID_BORDER, - ID_MIRROR, - ID_TEX_BORDER_COLOUR, - ID_FILTERING, - ID_BILINEAR, - ID_TRILINEAR, - ID_ANISOTROPIC, - ID_CMPTEST, - ID_ON, - ID_OFF, - ID_CMPFUNC, - ID_MAX_ANISOTROPY, - ID_MIPMAP_BIAS, - ID_COLOUR_OP, - ID_REPLACE, - ID_ADD, - ID_MODULATE, - ID_ALPHA_BLEND, - ID_COLOUR_OP_EX, - ID_SOURCE1, - ID_SOURCE2, - ID_MODULATE_X2, - ID_MODULATE_X4, - ID_ADD_SIGNED, - ID_ADD_SMOOTH, - ID_SUBTRACT, - ID_BLEND_DIFFUSE_COLOUR, - ID_BLEND_DIFFUSE_ALPHA, - ID_BLEND_TEXTURE_ALPHA, - ID_BLEND_CURRENT_ALPHA, - ID_BLEND_MANUAL, - ID_DOT_PRODUCT, - ID_SRC_CURRENT, - ID_SRC_TEXTURE, - ID_SRC_DIFFUSE, - ID_SRC_SPECULAR, - ID_SRC_MANUAL, - ID_COLOUR_OP_MULTIPASS_FALLBACK, - ID_ALPHA_OP_EX, - ID_ENV_MAP, - ID_SPHERICAL, - ID_PLANAR, - ID_CUBIC_REFLECTION, - ID_CUBIC_NORMAL, - ID_SCROLL, - ID_SCROLL_ANIM, - ID_ROTATE, - ID_ROTATE_ANIM, - ID_SCALE, - ID_WAVE_XFORM, - ID_SCROLL_X, - ID_SCROLL_Y, - ID_SCALE_X, - ID_SCALE_Y, - ID_SINE, - ID_TRIANGLE, - ID_SQUARE, - ID_SAWTOOTH, - ID_INVERSE_SAWTOOTH, - ID_TRANSFORM, - ID_CONTENT_TYPE, - ID_NAMED, - ID_SHADOW, - ID_TEXTURE_SOURCE, - ID_SHARED_PARAMS, - ID_SHARED_PARAM_NAMED, - ID_SHARED_PARAMS_REF, - - ID_PARTICLE_SYSTEM, - ID_EMITTER, - ID_AFFECTOR, - - ID_COMPOSITOR, - ID_TARGET, - ID_TARGET_OUTPUT, - - ID_INPUT, - ID_PREVIOUS, - ID_TARGET_WIDTH, - ID_TARGET_HEIGHT, - ID_TARGET_WIDTH_SCALED, - ID_TARGET_HEIGHT_SCALED, - ID_COMPOSITOR_LOGIC, - ID_TEXTURE_REF, - ID_SCOPE_LOCAL, - ID_SCOPE_CHAIN, - ID_SCOPE_GLOBAL, - ID_POOLED, - //ID_GAMMA, - already registered for material - ID_NO_FSAA, - ID_DEPTH_POOL, - ID_ONLY_INITIAL, - ID_VISIBILITY_MASK, - ID_LOD_BIAS, - ID_MATERIAL_SCHEME, - ID_SHADOWS_ENABLED, - - ID_CLEAR, - ID_STENCIL, - ID_RENDER_SCENE, - ID_RENDER_QUAD, - ID_IDENTIFIER, - ID_FIRST_RENDER_QUEUE, - ID_LAST_RENDER_QUEUE, - ID_QUAD_NORMALS, - ID_CAMERA_FAR_CORNERS_VIEW_SPACE, - ID_CAMERA_FAR_CORNERS_WORLD_SPACE, - - ID_BUFFERS, - ID_COLOUR, - ID_DEPTH, - ID_COLOUR_VALUE, - ID_DEPTH_VALUE, - ID_STENCIL_VALUE, - - ID_CHECK, - ID_COMP_FUNC, - ID_REF_VALUE, - ID_MASK, - ID_FAIL_OP, - ID_KEEP, - ID_INCREMENT, - ID_DECREMENT, - ID_INCREMENT_WRAP, - ID_DECREMENT_WRAP, - ID_INVERT, - ID_DEPTH_FAIL_OP, - ID_PASS_OP, - ID_TWO_SIDED, - // Support for shader model 5.0 - // More program IDs - ID_TESSELLATION_HULL_PROGRAM, - ID_TESSELLATION_DOMAIN_PROGRAM, - ID_COMPUTE_PROGRAM, - ID_TESSELLATION_HULL_PROGRAM_REF, - ID_TESSELLATION_DOMAIN_PROGRAM_REF, - ID_COMPUTE_PROGRAM_REF, - // More binding IDs - ID_GEOMETRY, - ID_TESSELLATION_HULL, - ID_TESSELLATION_DOMAIN, - ID_COMPUTE, - - // added during 1.11. re-sort for 1.12 - ID_LINE_WIDTH, - ID_SAMPLER, - ID_SAMPLER_REF, - ID_THREAD_GROUPS, - ID_RENDER_CUSTOM, - ID_AUTO, - ID_CAMERA, - ID_ALIGN_TO_FACE, - ID_UNORDERED_ACCESS_MIP, - - ID_END_BUILTIN_IDS - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreScriptLoader.h b/OgreMain/include/OgreScriptLoader.h deleted file mode 100644 index e3e7a944435..00000000000 --- a/OgreMain/include/OgreScriptLoader.h +++ /dev/null @@ -1,97 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ScriptLoader_H__ -#define __ScriptLoader_H__ - -#include "OgrePrerequisites.h" -#include "OgreDataStream.h" -#include "OgreStringVector.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \defgroup Script Script - * @{ - */ - /** Abstract class defining the interface used by classes which wish - to perform script loading to define instances of whatever they manage. - - Typically classes of this type wish to either parse individual script files - on demand, or be called with a group of files matching a certain pattern - at the appropriate time. Normally this will coincide with resource loading, - although the script use does not necessarily have to be a ResourceManager - (which subclasses from this class), it may be simply a script loader which - manages non-resources but needs to be synchronised at the same loading points. - @par - Subclasses should add themselves to the ResourceGroupManager as a script loader - if they wish to be called at the point a resource group is loaded, at which - point the parseScript method will be called with each file which matches a - the pattern returned from getScriptPatterns. - */ - class _OgreExport ScriptLoader - { - public: - virtual ~ScriptLoader() {} - /** Gets the file patterns which should be used to find scripts for this - class. - - This method is called when a resource group is loaded if you use - ResourceGroupManager::_registerScriptLoader. - @return - A list of file patterns, in the order they should be searched in. - */ - virtual const StringVector& getScriptPatterns(void) const = 0; - - /** Parse a script file. - @param stream Weak reference to a data stream which is the source of the script - @param groupName The name of a resource group which should be used if any resources - are created during the parse of this script. - */ - virtual void parseScript(DataStreamPtr& stream, const String& groupName) = 0; - - /** Gets the loading order for scripts of this type. - - There are dependencies between some kinds of scripts, and this value enumerates that. - Higher values load later during bulk loading tasks. - @return The loading order - */ - virtual Real getLoadingOrder(void) const = 0; - - }; - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreScriptTranslator.h b/OgreMain/include/OgreScriptTranslator.h deleted file mode 100644 index 094dc95ff21..00000000000 --- a/OgreMain/include/OgreScriptTranslator.h +++ /dev/null @@ -1,139 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __SCRIPTTRANSLATOR_H_ -#define __SCRIPTTRANSLATOR_H_ - -#include "OgrePrerequisites.h" -#include "OgreScriptCompiler.h" -#include "OgreRenderSystem.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Script - * @{ - */ - /** This class translates script AST (abstract syntax tree) into - * Ogre resources. It defines a common interface for subclasses - * which perform the actual translation. - */ - - class _OgreExport ScriptTranslator : public ScriptTranslatorAlloc - { - public: - /** - * This function translates the given node into Ogre resource(s). - * @param compiler The compiler invoking this translator - * @param node The current AST node to be translated - */ - virtual void translate(ScriptCompiler *compiler, const AbstractNodePtr &node) = 0; - protected: - // needs virtual destructor - virtual ~ScriptTranslator() {} - /// Retrieves a new translator from the factories and uses it to process the give node - static void processNode(ScriptCompiler *compiler, const AbstractNodePtr &node); - - /// Retrieves the node iterator at the given index - static AbstractNodeList::const_iterator getNodeAt(const AbstractNodeList &nodes, size_t index); - /// Converts the node to a boolean and returns true if successful - static bool getBoolean(const AbstractNodePtr &node, bool *result); - /// Converts the node to a string and returns true if successful - static bool getString(const AbstractNodePtr &node, String *result); - /// Converts the node to a Real and returns true if successful - static bool getReal(const AbstractNodePtr& node, Real* result) - { -#if OGRE_DOUBLE_PRECISION == 0 - return getFloat(node, result); -#else - return getDouble(node, result); -#endif - } - /// Converts the node to a float and returns true if successful - static bool getFloat(const AbstractNodePtr &node, float *result); - /// Converts the node to a float and returns true if successful - static bool getDouble(const AbstractNodePtr &node, double *result); - /// Converts the node to an integer and returns true if successful - static bool getInt(const AbstractNodePtr &node, int *result); - /// Converts the node to an unsigned integer and returns true if successful - static bool getUInt(const AbstractNodePtr &node, uint32 *result); - /// Converts the range of nodes to a ColourValue and returns true if successful - static bool getColour(AbstractNodeList::const_iterator i, AbstractNodeList::const_iterator end, ColourValue *result, int maxEntries = 4); - /// Converts the node to a SceneBlendFactor enum and returns true if successful - static bool getSceneBlendFactor(const AbstractNodePtr &node, SceneBlendFactor *sbf); - /// Converts the node to a CompareFunction enum and returns true if successful - static bool getCompareFunction(const AbstractNodePtr &node, CompareFunction *func); - /// Converts the range of nodes to a Matrix4 and returns true if successful - static bool getMatrix4(AbstractNodeList::const_iterator i, AbstractNodeList::const_iterator end, Matrix4 *m); - /// @deprecated use getVector - OGRE_DEPRECATED static bool getInts(AbstractNodeList::const_iterator i, AbstractNodeList::const_iterator end, int *vals, int count); - /// @deprecated use getVector - OGRE_DEPRECATED static bool getFloats(AbstractNodeList::const_iterator i, AbstractNodeList::const_iterator end, float *vals, int count); - /// @deprecated - OGRE_DEPRECATED static bool getDoubles(AbstractNodeList::const_iterator i, AbstractNodeList::const_iterator end, double *vals, int count); - /// @deprecated - OGRE_DEPRECATED static bool getUInts(AbstractNodeList::const_iterator i, AbstractNodeList::const_iterator end, uint *vals, int count); - /// @deprecated - OGRE_DEPRECATED static bool getBooleans(AbstractNodeList::const_iterator i, AbstractNodeList::const_iterator end, uint *vals, int count); - /// read count values from the AbstractNodeList into vals. Fill with default value if AbstractNodeList is shorter then count - static bool getVector(AbstractNodeList::const_iterator i, AbstractNodeList::const_iterator end, std::vector& vals, size_t count); - /// @overload - static bool getVector(AbstractNodeList::const_iterator i, AbstractNodeList::const_iterator end, std::vector& vals, size_t count); - /// Converts the node to a StencilOperation enum and returns true if successful - static bool getStencilOp(const AbstractNodePtr &node, StencilOperation *op); - /// Converts the node to a GpuConstantType enum and returns true if successful - static bool getConstantType(AbstractNodeList::const_iterator i, GpuConstantType *op); - - template - friend bool getValue(const AbstractNodePtr &node, T& result); - }; - - /** The ScriptTranslatorManager manages the lifetime and access to - * script translators. You register these managers with the - * ScriptCompilerManager tied to specific object types. - * Each manager may manage multiple types. - */ - class _OgreExport ScriptTranslatorManager : public ScriptTranslatorAlloc - { - public: - // required - virtual destructor - virtual ~ScriptTranslatorManager() {} - - /// Returns a manager for the given object abstract node, or null if it is not supported - virtual ScriptTranslator *getTranslator(const AbstractNodePtr&) = 0; - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreSerializer.h b/OgreMain/include/OgreSerializer.h deleted file mode 100644 index 2896c5ec4c2..00000000000 --- a/OgreMain/include/OgreSerializer.h +++ /dev/null @@ -1,128 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Serializer_H__ -#define __Serializer_H__ - -#include "OgrePrerequisites.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - /** Generic class for serialising data to / from binary stream-based files. - - This class provides a number of useful methods for exporting / importing data - from stream-oriented binary files (e.g. .mesh and .skeleton). - */ - class _OgreExport Serializer : public SerializerAlloc - { - public: - Serializer(); - ~Serializer(); - - /// The endianness of written files - enum Endian - { - /// Use the platform native endian - ENDIAN_NATIVE, - /// Use big endian (0x1000 is serialised as 0x10 0x00) - ENDIAN_BIG, - /// Use little endian (0x1000 is serialised as 0x00 0x10) - ENDIAN_LITTLE - }; - - - protected: - - uint32 mCurrentstreamLen; - DataStreamPtr mStream; - String mVersion; - bool mFlipEndian; /// Default to native endian, derive from header - - // Internal methods - void writeFileHeader(void); - void writeChunkHeader(uint16 id, size_t size); - static size_t calcChunkHeaderSize() { return sizeof(uint16) + sizeof(uint32); } - /// string + terminating \n character - static size_t calcStringSize(const String& string) { return string.length() + 1; } - - void writeFloats(const float* const pfloat, size_t count); - void writeFloats(const double* const pfloat, size_t count); - void writeShorts(const uint16* const pShort, size_t count); - void writeInts(const uint32* const pInt, size_t count); - void writeBools(const bool* const pLong, size_t count); - void writeObject(const Vector3& vec); - void writeObject(const Quaternion& q); - - void writeString(const String& string); - void writeData(const void* const buf, size_t size, size_t count); - - void readFileHeader(const DataStreamPtr& stream); - unsigned short readChunk(const DataStreamPtr& stream); - - void readBools(const DataStreamPtr& stream, bool* pDest, size_t count); - void readFloats(const DataStreamPtr& stream, float* pDest, size_t count); - void readFloats(const DataStreamPtr& stream, double* pDest, size_t count); - void readShorts(const DataStreamPtr& stream, uint16* pDest, size_t count); - void readInts(const DataStreamPtr& stream, uint32* pDest, size_t count); - void readObject(const DataStreamPtr& stream, Vector3& pDest); - void readObject(const DataStreamPtr& stream, Quaternion& pDest); - - static String readString(const DataStreamPtr& stream); - - void flipToLittleEndian(void* pData, size_t size, size_t count = 1); - void flipFromLittleEndian(void* pData, size_t size, size_t count = 1); - - /// Determine the endianness of the incoming stream compared to native - void determineEndianness(const DataStreamPtr& stream); - /// Determine the endianness to write with based on option - void determineEndianness(Endian requestedEndian); - - // OGRE_SERIALIZER_VALIDATE_CHUNKSIZE - typedef std::vector ChunkSizeStack; - ChunkSizeStack mChunkSizeStack; - bool mReportChunkErrors; - - void pushInnerChunk(const DataStreamPtr& stream); - void popInnerChunk(const DataStreamPtr& stream); - void backpedalChunkHeader(const DataStreamPtr& stream); - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreShadowCameraSetup.h b/OgreMain/include/OgreShadowCameraSetup.h deleted file mode 100644 index 0ae798cd6fb..00000000000 --- a/OgreMain/include/OgreShadowCameraSetup.h +++ /dev/null @@ -1,107 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ShadowCameraSetup_H__ -#define __ShadowCameraSetup_H__ - -#include "OgrePrerequisites.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** This class allows you to plug in new ways to define the camera setup when - rendering and projecting shadow textures. - - The default projection used when rendering shadow textures is a uniform - frustum. This is pretty straight forward but doesn't make the best use of - the space in the shadow map since texels closer to the camera will be larger, - resulting in 'jaggies'. There are several ways to distribute the texels - in the shadow texture differently, and this class allows you to override - that. - @par - Ogre is provided with several alternative shadow camera setups, including - LiSPSM (LiSPSMShadowCameraSetup) and Plane Optimal (PlaneOptimalShadowCameraSetup). - Others can of course be written to incorporate other algorithms. All you - have to do is instantiate one of these classes and enable it using - SceneManager::setShadowCameraSetup (global) or Light::setCustomShadowCameraSetup - (per light). In both cases the instance is wrapped in a SharedPtr which means - it will be deleted automatically when no more references to it exist. - @note - Shadow map matrices, being projective matrices, have 15 degrees of freedom. - 3 of these degrees of freedom are fixed by the light's position. 4 are used to - affinely affect z values. 6 affinely affect u,v sampling. 2 are projective - degrees of freedom. This class is meant to allow custom methods for - handling optimization. - */ - class _OgreExport ShadowCameraSetup : public ShadowDataAlloc - { - public: - /// Function to implement -- must set the shadow camera properties - virtual void getShadowCamera (const SceneManager *sm, const Camera *cam, - const Viewport *vp, const Light *light, Camera *texCam, size_t iteration) const = 0; - /// Need virtual destructor in case subclasses use it - virtual ~ShadowCameraSetup() {} - - }; - - - - /** Implements default shadow camera setup - - This implements the default shadow camera setup algorithm. This is what might - be referred to as "normal" shadow mapping. - */ - class _OgreExport DefaultShadowCameraSetup : public ShadowCameraSetup - { - public: - DefaultShadowCameraSetup(); - virtual ~DefaultShadowCameraSetup(); - - static ShadowCameraSetupPtr create() - { - return std::make_shared(); - } - - /// Default shadow camera setup - void getShadowCamera (const SceneManager *sm, const Camera *cam, - const Viewport *vp, const Light *light, Camera *texCam, size_t iteration) const override; - }; - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreShadowCameraSetupFocused.h b/OgreMain/include/OgreShadowCameraSetupFocused.h deleted file mode 100644 index 6c9279942a8..00000000000 --- a/OgreMain/include/OgreShadowCameraSetupFocused.h +++ /dev/null @@ -1,277 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Copyright (c) 2006 Matthias Fink, netAllied GmbH - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ShadowCameraSetupFocused_H__ -#define __ShadowCameraSetupFocused_H__ - -#include "OgrePrerequisites.h" -#include "OgreShadowCameraSetup.h" -#include "OgrePolygon.h" -#include "OgreConvexBody.h" -#include "OgreHeaderPrefix.h" -#include "OgreAxisAlignedBox.h" -#include "OgreSceneNode.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** Implements the uniform shadow mapping algorithm in focused mode. - - Differs from the default shadow mapping projection in that it focuses the - shadow map on the visible areas of the scene. This results in better - shadow map texel usage, at the expense of some 'swimming' of the shadow - texture on receivers as the basis is constantly being reevaluated. - - Original implementation by Matthias Fink , 2006. - */ - class _OgreExport FocusedShadowCameraSetup : public DefaultShadowCameraSetup - { - // Persistent calculations to prevent reallocation - mutable ConvexBody mBodyB; - /// Use tighter focus region? - bool mUseAggressiveRegion; - protected: - /** Transform to or from light space as defined by Wimmer et al. - - Point and spot lights need to be converted to directional lights to enable a 1:1 - light mapping. Otherwise a directional light may become a point light or a point - sink (opposite of a light source) or point/spot lights may become directional lights - or light sinks. The light direction is always -y. - */ - static const Matrix4 msNormalToLightSpace; - static const Matrix4 msLightSpaceToNormal; - - mutable const Camera* mLightFrustumCamera; - mutable bool mLightFrustumCameraCalculated; - - /** Internal class holding a point list representation of a convex body. - */ - class _OgreExport PointListBody - { - Polygon::VertexList mBodyPoints; - AxisAlignedBox mAAB; - - public: - PointListBody(); - PointListBody(const ConvexBody& body); - ~PointListBody(); - - /** Merges a second PointListBody into this one. - */ - void merge(const PointListBody& plb); - - /** Builds a point list body from a 'real' body. - - Inserts all vertices from a body into the point list with or without adding duplicate vertices. - */ - void build(const ConvexBody& body, bool filterDuplicates = true); - - /** Builds a PointListBody from a Body and includes all the space in a given direction. - - Intersects the bounding box with a ray from each available point of the body with the given - direction. Base and intersection points are stored in a PointListBody structure. - @note - Duplicate vertices are not filtered. - @note - Body is not checked for correctness. - */ - void buildAndIncludeDirection(const ConvexBody& body, - Real extrudeDist, const Vector3& dir); - - /** Returns the bounding box representation. - */ - const AxisAlignedBox& getAAB(void) const; - - /** Adds a specific point to the body list. - */ - void addPoint(const Vector3& point); - - /** Adds all points of an AAB. - */ - void addAAB(const AxisAlignedBox& aab); - - /** Returns a point. - */ - const Vector3& getPoint(size_t cnt) const; - - /** Returns the point count. - */ - size_t getPointCount(void) const; - - /** Resets the body. - */ - void reset(void); - - }; - - // Persistent calculations to prevent reallocation - mutable PointListBody mPointListBodyB; - mutable PointListBody mPointListBodyLVS; - - protected: - /** Calculates the intersection bodyB. - - The intersection bodyB consists of the concatenation the cam frustum clipped - by the scene bounding box followed by a convex hullification with the light's - position and the clipping with the scene bounding box and the light frustum: - ((V \cap S) + l) \cap S \cap L (\cap: convex intersection, +: convex hull - operation). - For directional lights the bodyB is assembled out of the camera frustum - clipped by the scene bounding box followed by the extrusion of all available - bodyB points towards the negative light direction. The rays are intersected - by a maximum bounding box and added to the bodyB points to form the final - intersection bodyB point list. - @param sm - Scene manager. - @param cam - Currently active camera. - @param light - Currently active light. - @param sceneBB - Scene bounding box for clipping operations. - @param receiverBB - Bounding information for just the receivers. - @param out_bodyB - Final intersection bodyB point list. - */ - void calculateB(const SceneManager& sm, const Camera& cam, const Light& light, - const AxisAlignedBox& sceneBB, const AxisAlignedBox& receiverBB, PointListBody *out_bodyB) const; - - /** Calculates the bodyLVS. - - Calculates the bodyLVS which consists of the convex intersection operation - affecting the light frustum, the view frustum, and the current scene bounding - box is used to find suitable positions in the viewer's frustum to build the - rotation matrix L_r. This matrix is applied after the projection matrix L_p to - avoid an accidental flip of the frustum orientation for views tilted with - respect to the shadow map. - @param cam - Current viewer camera. - @param light - Current light. - @param sceneBB - Holds all potential occluders / receivers as one single bounding box - of the currently active scene node. - @param out_LVS - Intersection body LVS (world coordinates). - */ - void calculateLVS(const SceneManager& sm, const Camera& cam, const Light& light, - const AxisAlignedBox& sceneBB, PointListBody *out_LVS) const; - - /** Returns the projection view direction. - - After the matrix L_p is applied the orientation of the light space may tilt for - non-identity projections. To prevent a false shadow cast the real view direction - is evaluated and applied to the light matrix L. - @param lightSpace - Matrix of the light space transformation. - @param cam - Current viewer camera. - @param bodyLVS - Intersection body LVS (relevant space in front of the camera). - */ - Vector3 getLSProjViewDir(const Matrix4& lightSpace, const Camera& cam, - const PointListBody& bodyLVS) const; - - /** Returns a valid near-point seen by the camera. - - Returns a point that is situated near the camera by analyzing the bodyLVS that - contains all the relevant scene space in front of the light and the camera in - a point list array. The view matrix is relevant because the nearest point in - front of the camera should be determined. - @param viewMatrix - View matrix of the current camera. - @param bodyLVS - Intersection body LVS (relevant space in front of the camera). - */ - Vector3 getNearCameraPoint_ws(const Affine3& viewMatrix, - const PointListBody& bodyLVS) const; - - /** Transforms a given body to the unit cube (-1,-1,-1) / (+1,+1,+1) with a specific - shadow matrix enabled. - - Transforms a given point list body object with the matrix m and then maps its - extends to a (-1,-1,-1) / (+1,+1,+1) unit cube. - @param m - Transformation matrix applied on the point list body. - @param body - Contains the points of the extends of all valid scene elements which - are mapped to the unit cube. - */ - Matrix4 transformToUnitCube(const Matrix4& m, const PointListBody& body) const; - public: - /// @deprecated use create() - FocusedShadowCameraSetup(bool useAggressiveRegion = true); - - ~FocusedShadowCameraSetup(); - - /** Create an instance - - There are 2 approaches that can be used to define the focus region, - the more aggressive way introduced by Wimmer et al, or the original - way as described in Stamminger et al. Wimmer et al's way tends to - come up with a tighter focus region but in rare cases (mostly highly - glancing angles) can cause some shadow casters to be clipped - incorrectly. By default the more aggressive approach is used since it - leads to significantly better results in most cases, but if you experience - clipping issues, you can use the less aggressive version. - @param useAggressiveRegion - True to use the more aggressive approach, false otherwise. - */ - static ShadowCameraSetupPtr create(bool useAggressiveRegion = true) - { - return std::make_shared(useAggressiveRegion); - } - - /** Returns a uniform shadow camera with a focused view. - */ - void getShadowCamera(const SceneManager *sm, const Camera *cam, - const Viewport *vp, const Light *light, Camera *texCam, size_t iteration) const override; - - /** Sets whether or not to use the more aggressive approach to deciding on - the focus region or not. - */ - void setUseAggressiveFocusRegion(bool aggressive) { mUseAggressiveRegion = aggressive; } - - bool getUseAggressiveFocusRegion() const { return mUseAggressiveRegion; } - - }; - - /** @} */ - /** @} */ - -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif // __ShadowCameraSetupFocused_H__ diff --git a/OgreMain/include/OgreShadowCameraSetupLiSPSM.h b/OgreMain/include/OgreShadowCameraSetupLiSPSM.h deleted file mode 100644 index fef830943ea..00000000000 --- a/OgreMain/include/OgreShadowCameraSetupLiSPSM.h +++ /dev/null @@ -1,242 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Copyright (c) 2006 Matthias Fink, netAllied GmbH - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ShadowCameraSetupLiSPSM_H__ -#define __ShadowCameraSetupLiSPSM_H__ - -#include "OgrePrerequisites.h" -#include "OgreShadowCameraSetupFocused.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** Implements the %Light Space Perspective Shadow Mapping Algorithm @cite WSP04 - - Shadow mapping was introduced by Williams in 1978. First a depth image is rendered - from the light's view and compared in a second pass with depth values of the normal - camera view. In case the depth camera's depth value is greater than the depth seen - by the light the fragment lies in the shadow. - The concept has a major draw back named perspective aliasing. The shadow map distri- - butes the samples uniformly meaning the position of the viewer is ignored. For the - viewer however the perspective projection affects near objects to be displayed - bigger than further away objects. The same thing happens with the shadow map texels: - Near shadows appear very coarse and far away shadows are perfectly sampled. - PSM @cite stamminger2002perspective battles the perspective aliasing by distributing 50% of the shadow map - texels for objects in the range of < near clipping plane > to < near clipping plane * 2 > - which inverts the problem: The shadows near the viewer are perfectly sampled, - however far away shadow may contain aliasing artefacts. A near clipping plane may be - a problem. But this is not the only one. In the post-perspective space the light - sources are non-intuitively mapped: Directional lights may become point light and - point lights may become directional lights. Also light sinks (opposite of a light - source) may appear. Another problem are shadow casters located behind the viewer. - In post-projective space objects behind the viewer are mapped in front of him with - a flipped up-vector. - LiSPSM battles the light source problem of the post-projective space by rearranging - the light space before transformation in such a way that no special cases appear. - This is done by converting point/spot lights into directional lights. The light - space is arranged in such a way that the light direction equals the inverse UNIT_Y. - In this combination the directional light will neither change its type nor its - direction. Furthermore all visible objects and shadow casters affecting the user's - visible area lie in front of the shadow camera: After building the intersection body - that contains all these objects (body intersection building was introduced with PSM; - have a look at the description for the method "calculateB" for further info) a - frustum around the body's light space bounding box is created. A parameter (called - 'n') automatically adjusts the shadow map sample distribution by specifying the - frustum's view point - near plane which affects the perspective warp. In case the - distance is small the perspecive warp will be strong. As a consequence near objects - will gain quality. - However there are still problems. PSM as well as LiSPSM only devote to minimize - perspective aliasing. Projection aliasing is still a problem, also 'swimming - artefacts' still occur. The LiSPSM quality distribution is very good but not the - best available: Some sources say logarithmic shadow mapping @cite lloyd2007practical - is the non plus ultra, however others reject this thought. - - More information can be found on the webpage of the TU Wien: - http://www.cg.tuwien.ac.at/research/vr/lispsm/ - - Original implementation by Matthias Fink , 2006. - */ - class _OgreExport LiSPSMShadowCameraSetup : public FocusedShadowCameraSetup - { - /// Warp factor adjustment - Real mOptAdjustFactor; - /// Use simple nopt derivation? - bool mUseSimpleNOpt; - /// Extra calculated warp factor - mutable Real mOptAdjustFactorTweak; - /// Threshold (cos angle) within which to start increasing the opt adjust as camera direction approaches light direction - Real mCosCamLightDirThreshold; - - /** Calculates the LiSPSM projection matrix P. - - The LiSPSM projection matrix will be built around the axis aligned bounding box - of the intersection body B in light space. The distance between the near plane - and the projection center is chosen in such a way (distance is set by the para- - meter n) that the perspective error is the same on the near and far plane. In - case P equals the identity matrix the algorithm falls back to a uniform shadow - mapping matrix. - @param lightSpace Matrix of the light space transformation - @param bodyB Intersection body B - @param bodyLVS Intersection body LVS (relevant space in front of the camera) - @param sm Scene manager - @param cam Currently active camera - @param light Currently active light - */ - Matrix4 calculateLiSPSM(const Matrix4& lightSpace, const PointListBody& bodyB, - const PointListBody& bodyLVS, const SceneManager& sm, - const Camera& cam, const Light& light) const; - - /** Calculates the distance between camera position and near clipping plane. - - n_opt determines the distance between light space origin (shadow camera position) - and the near clipping plane to achieve an optimal perspective foreshortening effect. - In this way the texel distribution over the shadow map is controlled. - - Formula: - d - n_opt = --------------- - sqrt(z1/z0) - 1 - - Parameters: - d: distance between the near and the far clipping plane - z0: located on the near clipping plane of the intersection body b - z1: located on the far clipping plane with the same x/y values as z0 - @note - A positive value is applied as the distance between viewer and near clipping plane. - In case null is returned uniform shadow mapping will be applied. - @param lightSpace Matrix of the light space transformation - @param bodyBABB_ls Bounding box of the transformed (light space) bodyB - @param bodyLVS Point list of the bodyLVS which describes the scene space which is in - front of the light and the camera - @param cam Currently active camera - */ - Real calculateNOpt(const Matrix4& lightSpace, const AxisAlignedBox& bodyBABB_ls, - const PointListBody& bodyLVS, const Camera& cam) const; - - /** Calculates a simpler version than the one above. - */ - Real calculateNOptSimple(const PointListBody& bodyLVS, - const Camera& cam) const; - - /** Calculates the visible point on the near plane for the n_opt calculation - - z0 lies on the parallel plane to the near plane through e and on the near plane of - the frustum C (plane z = bodyB_zMax_ls) and on the line x = e.x. - @param lightSpace Matrix of the light space transformation - @param e The LiSPSM parameter e is located near or on the near clipping plane of the - LiSPSM frustum C - @param bodyB_zMax_ls Maximum z-value of the light space bodyB bounding box - @param cam Currently active camera - */ - Vector3 calculateZ0_ls(const Matrix4& lightSpace, const Vector3& e, Real bodyB_zMax_ls, - const Camera& cam) const; - public: - /// @deprecated use create() - LiSPSMShadowCameraSetup(Real n = 0.1f, bool useSimpleNOpt = true, Degree angle = Radian(0.451f)); - - virtual ~LiSPSMShadowCameraSetup(); - - /** - * @param n The adjustment factor - * @param useSimpleNOpt - * @param angle camera Light Direction Threshold - */ - static ShadowCameraSetupPtr create(Real n = 0.1f, bool useSimpleNOpt = true, Degree angle = Radian(0.451f)) - { - return std::make_shared(n, useSimpleNOpt, angle); - } - - /** Returns a LiSPSM shadow camera. - - Builds and returns a LiSPSM shadow camera. - More information can be found on the webpage of the TU Wien: - http://www.cg.tuwien.ac.at/research/vr/lispsm/ - */ - void getShadowCamera(const SceneManager *sm, const Camera *cam, - const Viewport *vp, const Light *light, Camera *texCam, size_t iteration) const override; - - /** Adjusts the parameter n to produce optimal shadows. - - The smaller the parameter n, the stronger the perspective warping effect. - The consequence of a stronger warping is that the near shadows will gain - quality while the far ones will lose it. Depending on your scene and light - types you may want to tweak this value - for example directional lights - tend to benefit from higher values of n than other types of light, - especially if you expect to see more distant shadows (say if the viewpoint is - higher above the ground plane). Remember that you can supply separate - ShadowCameraSetup instances configured differently per light if you wish. - @param n The adjustment factor - default is 0.1f. - */ - virtual void setOptimalAdjustFactor(Real n) { mOptAdjustFactor = n; } - /** Get the parameter n used to produce optimal shadows. - @see setOptimalAdjustFactor - */ - virtual Real getOptimalAdjustFactor() const { return mOptAdjustFactor; } - /** Sets whether or not to use a slightly simpler version of the - camera near point derivation (default is true) - */ - virtual void setUseSimpleOptimalAdjust(bool s) { mUseSimpleNOpt = s; } - /** Gets whether or not to use a slightly simpler version of the - camera near point derivation (default is true) - */ - virtual bool getUseSimpleOptimalAdjust() const { return mUseSimpleNOpt; } - - /** Sets the threshold between the camera and the light direction below - which the LiSPSM projection is 'flattened', since coincident light - and camera projections cause problems with the perspective skew. - - For example, setting this to 20 degrees will mean that as the difference - between the light and camera direction reduces from 20 degrees to 0 - degrees, the perspective skew will be proportionately removed. - */ - void setCameraLightDirectionThreshold(Degree angle); - - /** Sets the threshold between the camera and the light direction below - which the LiSPSM projection is 'flattened', since coincident light - and camera projections cause problems with the perspective skew. - */ - virtual Degree getCameraLightDirectionThreshold() const; - - - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreShadowCameraSetupPSSM.h b/OgreMain/include/OgreShadowCameraSetupPSSM.h deleted file mode 100644 index 4ca9c4cc7d2..00000000000 --- a/OgreMain/include/OgreShadowCameraSetupPSSM.h +++ /dev/null @@ -1,137 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Copyright (c) 2006 Matthias Fink, netAllied GmbH - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ShadowCameraSetupPSSM_H__ -#define __ShadowCameraSetupPSSM_H__ - -#include "OgrePrerequisites.h" -#include "OgreShadowCameraSetupLiSPSM.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** Parallel Split Shadow Map (PSSM) shadow camera setup. - - A PSSM shadow system uses multiple shadow maps per light and maps each - texture into a region of space, progressing away from the camera. As such - it is most appropriate for directional light setups. This particular version - also uses LiSPSM projection for each split to maximise the quality. - @note - Because PSSM uses multiple shadow maps per light, you will need to increase - the number of shadow textures available (via SceneManager) to match the - number of shadow maps required (default is 3 per light). - */ - class _OgreExport PSSMShadowCameraSetup : public LiSPSMShadowCameraSetup - { - using LiSPSMShadowCameraSetup::setOptimalAdjustFactor; - public: - typedef std::vector SplitPointList; - typedef std::vector OptimalAdjustFactorList; - - private: - uint mSplitCount; - SplitPointList mSplitPoints; - OptimalAdjustFactorList mOptimalAdjustFactors; - Real mSplitPadding; - - mutable size_t mCurrentIteration; - - public: - /// @deprecated use create() - PSSMShadowCameraSetup(); - virtual ~PSSMShadowCameraSetup(); - - /// Constructor, defaults to 3 splits - static ShadowCameraSetupPtr create() - { - return std::make_shared(); - } - - /** Calculate a new splitting scheme. - @param splitCount The number of splits to use - @param nearDist The near plane to use for the first split - @param farDist The far plane to use for the last split - @param lambda Factor to use to reduce the split size - */ - void calculateSplitPoints(uint splitCount, Real nearDist, Real farDist, Real lambda = 0.95f); - - /** Manually configure a new splitting scheme. - @param newSplitPoints A list which is splitCount + 1 entries long, containing the - split points. The first value is the near point, the last value is the - far point, and each value in between is both a far point of the previous - split, and a near point for the next one. - */ - void setSplitPoints(const SplitPointList& newSplitPoints); - - /** Set the LiSPSM optimal adjust factor for a given split (call after - configuring splits). - */ - void setOptimalAdjustFactor(size_t splitIndex, Real factor); - - /** Set the padding factor to apply to the near & far distances when matching up - splits to one another, to avoid 'cracks'. - */ - void setSplitPadding(Real pad) { mSplitPadding = pad; } - - /** Get the padding factor to apply to the near & far distances when matching up - splits to one another, to avoid 'cracks'. - */ - Real getSplitPadding() const { return mSplitPadding; } - /// Get the number of splits. - uint getSplitCount() const { return mSplitCount; } - - /// Returns a LiSPSM shadow camera with PSSM splits base on iteration. - void getShadowCamera(const Ogre::SceneManager *sm, const Ogre::Camera *cam, - const Ogre::Viewport *vp, const Ogre::Light *light, Ogre::Camera *texCam, size_t iteration) const override; - - /// Returns the calculated split points. - inline const SplitPointList& getSplitPoints() const - { return mSplitPoints; } - - /// Returns the optimal adjust factor for a given split. - inline Real getOptimalAdjustFactor(size_t splitIndex) const - { return mOptimalAdjustFactors[splitIndex]; } - - /// Overridden, recommended internal use only since depends on current iteration - Real getOptimalAdjustFactor() const override; - - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreShadowCameraSetupPlaneOptimal.h b/OgreMain/include/OgreShadowCameraSetupPlaneOptimal.h deleted file mode 100644 index d913d14c44b..00000000000 --- a/OgreMain/include/OgreShadowCameraSetupPlaneOptimal.h +++ /dev/null @@ -1,95 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ShadowCameraSetupPlaneOptimal_H__ -#define __ShadowCameraSetupPlaneOptimal_H__ - -#include "OgrePrerequisites.h" -#include "OgreShadowCameraSetup.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** Implements the plane optimal shadow camera algorithm. - - Given a plane of interest, it is possible to set up the shadow camera - matrix such that the mapping between screen and shadow map is the identity - (when restricted to pixels that view the plane of interest). Therefore, - if the shadow map resolution matches the screen space resolution (of the - seen planar receiver), we can get pixel perfect shadowing on the plane. - Off the plane, the shadowing is not guaranteed to be perfect and will - likely exhibit the usual sampling artifacts associated with shadow mapping. - @note Important: this routine requires double-precision calculations. When you - are running under Direct3D, you must ensure that you set the floating - point mode to 'Consistent' rather than 'Fastest' to ensure this precision. - This does allegedly come with some performance cost but when measuring - it appears to be negligible in modern systems for normal usage. - @note Second important note: this projection also only works for lights with - a finite position. Therefore you cannot use it for directional lights - at this time. - */ - class _OgreExport PlaneOptimalShadowCameraSetup : public ShadowCameraSetup - { - private: - const MovablePlane* mPlane; ///< pointer to plane of interest - private: - /// helper function computing projection matrix given constraints - Matrix4 computeConstrainedProjection( const Vector4& pinhole, - const std::vector& fpoint, - const std::vector& constraint) const; - - public: - /// @deprecated use create() - PlaneOptimalShadowCameraSetup(const MovablePlane *plane); - - virtual ~PlaneOptimalShadowCameraSetup(); - - /// Constructor -- requires a plane of interest - static ShadowCameraSetupPtr create(const MovablePlane *plane) - { - return std::make_shared(plane); - } - - /// Returns shadow camera configured to get 1-1 homography between screen and shadow map when restricted to plane - void getShadowCamera (const SceneManager *sm, const Camera *cam, - const Viewport *vp, const Light *light, Camera *texCam, size_t iteration) const override; - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreShadowCaster.h b/OgreMain/include/OgreShadowCaster.h deleted file mode 100644 index 0066b0f1179..00000000000 --- a/OgreMain/include/OgreShadowCaster.h +++ /dev/null @@ -1,258 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ShadowCaster_H__ -#define __ShadowCaster_H__ - -#include "OgrePrerequisites.h" -#include "OgreRenderable.h" -#include "OgreRenderOperation.h" -#include "OgreHeaderPrefix.h" - - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** Class which represents the renderable aspects of a set of shadow volume faces. - - Note that for casters comprised of more than one set of vertex buffers (e.g. SubMeshes each - using their own geometry), it will take more than one ShadowRenderable to render the - shadow volume. Therefore for shadow caster geometry, it is best to stick to one set of - vertex buffers (not necessarily one buffer, but the positions for the entire geometry - should come from one buffer if possible) - */ - class _OgreExport ShadowRenderable : public Renderable, public ShadowDataAlloc - { - protected: - RenderOperation mRenderOp; - MaterialPtr mMaterial; - ShadowRenderable* mLightCap; /// Used only if isLightCapSeparate == true - MovableObject* mParent; - /// Shared link to position buffer. - HardwareVertexBufferSharedPtr mPositionBuffer; - /// Shared link to w-coord buffer (optional). - HardwareVertexBufferSharedPtr mWBuffer; - public: - ShadowRenderable() : mLightCap(0) {} - ShadowRenderable(MovableObject* parent, const HardwareIndexBufferSharedPtr& indexBuffer, - const VertexData* vertexData, bool createSeparateLightCap, - bool isLightCap = false); - virtual ~ShadowRenderable(); - /** Set the material to be used by the shadow, should be set by the caller - before adding to a render queue - */ - void setMaterial(const MaterialPtr& mat) { mMaterial = mat; } - const MaterialPtr& getMaterial(void) const override { return mMaterial; } - void getRenderOperation(RenderOperation& op) override { op = mRenderOp; } - /// Get the internal render operation for set up. - RenderOperation* getRenderOperationForUpdate(void) {return &mRenderOp;} - void getWorldTransforms(Matrix4* xform) const override; - Real getSquaredViewDepth(const Camera*) const override { return 0; /* not used */} - const LightList& getLights(void) const override; - /** Does this renderable require a separate light cap? - - If possible, the light cap (when required) should be contained in the - usual geometry of the shadow renderable. However, if for some reason - the normal depth function (less than) could cause artefacts, then a - separate light cap with a depth function of 'always fail' can be used - instead. The primary example of this is when there are floating point - inaccuracies caused by calculating the shadow geometry separately from - the real geometry. - */ - bool isLightCapSeparate(void) const { return mLightCap != 0; } - - /// Get the light cap version of this renderable. - ShadowRenderable* getLightCapRenderable(void) { return mLightCap; } - /// Should this ShadowRenderable be treated as visible? - virtual bool isVisible(void) const { return true; } - - /** This function informs the shadow renderable that the global index buffer - from the SceneManager has been updated. As all shadow use this buffer their pointer - must be updated as well. - @param indexBuffer - Pointer to the new index buffer. - */ - void rebindIndexBuffer(const HardwareIndexBufferSharedPtr& indexBuffer); - - const HardwareVertexBufferSharedPtr& getPositionBuffer(void) const { return mPositionBuffer; } - }; - - /** A set of flags that can be used to influence ShadowRenderable creation. */ - enum ShadowRenderableFlags - { - /// For shadow volume techniques only, generate a light cap on the volume. - SRF_INCLUDE_LIGHT_CAP = 0x00000001, - /// For shadow volume techniques only, generate a dark cap on the volume. - SRF_INCLUDE_DARK_CAP = 0x00000002, - /// For shadow volume techniques only, indicates volume is extruded to infinity. - SRF_EXTRUDE_TO_INFINITY = 0x00000004, - /// For shadow volume techniques only, indicates hardware extrusion is not supported. - SRF_EXTRUDE_IN_SOFTWARE = 0x00000008, - }; - - typedef std::vector ShadowRenderableList; - - /** This class defines the interface that must be implemented by shadow casters. - */ - class _OgreExport ShadowCaster - { - public: - virtual ~ShadowCaster() { } - /** Returns whether or not this object currently casts a shadow. */ - virtual bool getCastShadows(void) const = 0; - - /** Returns details of the edges which might be used to determine a silhouette. */ - virtual EdgeData* getEdgeList(void) = 0; - /** Returns whether the object has a valid edge list. */ - bool hasEdgeList() { return getEdgeList() != NULL; } - - /** Get the world bounding box of the caster. */ - virtual const AxisAlignedBox& getWorldBoundingBox(bool derive = false) const = 0; - /** Gets the world space bounding box of the light cap. */ - virtual const AxisAlignedBox& getLightCapBounds(void) const = 0; - /** Gets the world space bounding box of the dark cap, as extruded using the light provided. */ - virtual const AxisAlignedBox& getDarkCapBounds(const Light& light, Real dirLightExtrusionDist) const = 0; - - typedef Ogre::ShadowRenderableList ShadowRenderableList; - typedef VectorIterator ShadowRenderableListIterator; - - /** Gets an list of the renderables required to render the shadow volume. - - Shadowable geometry should ideally be designed such that there is only one - ShadowRenderable required to render the the shadow; however this is not a necessary - limitation and it can be exceeded if required. - @param light - The light to generate the shadow from. - @param indexBuffer - The index buffer to build the renderables into, - the current contents are assumed to be disposable. - @param indexBufferUsedSize - If the rest of buffer is enough than it would be locked with - HBL_NO_OVERWRITE semantic and indexBufferUsedSize would be increased, - otherwise HBL_DISCARD would be used and indexBufferUsedSize would be reset. - @param extrusionDistance - The distance to extrude the shadow volume. - @param flags - Technique-specific flags, see ShadowRenderableFlags. - */ - virtual const ShadowRenderableList& - getShadowVolumeRenderableList(const Light* light, const HardwareIndexBufferPtr& indexBuffer, - size_t& indexBufferUsedSize, float extrusionDistance, - int flags = 0) = 0; - - /** Common implementation of releasing shadow renderables.*/ - static void clearShadowRenderableList(ShadowRenderableList& shadowRenderables); - - /** Utility method for extruding vertices based on a light. - - Unfortunately, because D3D cannot handle homogeneous (4D) position - coordinates in the fixed-function pipeline (GL can, but we have to - be cross-API), when we extrude in software we cannot extrude to - infinity the way we do in the vertex program (by setting w to - 0.0f). Therefore we extrude by a fixed distance, which may cause - some problems with larger scenes. Luckily better hardware (ie - vertex programs) can fix this. - @param vertexBuffer - The vertex buffer containing ONLY xyz position - values, which must be originalVertexCount * 2 * 3 floats long. - @param originalVertexCount - The count of the original number of - vertices, i.e. the number in the mesh, not counting the doubling - which has already been done (by VertexData::prepareForShadowVolume) - to provide the extruded area of the buffer. - @param lightPos - 4D light position in object space, when w=0.0f this - represents a directional light. - @param extrudeDist - The distance to extrude. - */ - static void extrudeVertices(const HardwareVertexBufferSharedPtr& vertexBuffer, - size_t originalVertexCount, const Vector4& lightPos, Real extrudeDist); - /** Get the distance to extrude for a point/spot light. */ - virtual Real getPointExtrusionDistance(const Light* l) const = 0; - protected: - /** Tells the caster to perform the tasks necessary to update the - edge data's light listing. Can be overridden if the subclass needs - to do additional things. - @param edgeData - The edge information to update. - @param lightPos - 4D vector representing the light, a directional light has w=0.0. - */ - virtual void updateEdgeListLightFacing(EdgeData* edgeData, - const Vector4& lightPos); - - /** Generates the indexes required to render a shadow volume into the - index buffer which is passed in, and updates shadow renderables - to use it. - @param edgeData - The edge information to use. - @param indexBuffer - The buffer into which to write data into; current - contents are assumed to be discardable. - @param indexBufferUsedSize - If the rest of buffer is enough than it would be locked with - HBL_NO_OVERWRITE semantic and indexBufferUsedSize would be increased, - otherwise HBL_DISCARD would be used and indexBufferUsedSize would be reset. - @param light - The light, mainly for type info as silhouette calculations - should already have been done in updateEdgeListLightFacing - @param shadowRenderables - A list of shadow renderables which has - already been constructed but will need populating with details of - the index ranges to be used. - @param flags - Additional controller flags, see ShadowRenderableFlags. - */ - virtual void generateShadowVolume(EdgeData* edgeData, - const HardwareIndexBufferSharedPtr& indexBuffer, size_t& indexBufferUsedSize, - const Light* light, ShadowRenderableList& shadowRenderables, unsigned long flags); - /** Utility method for extruding a bounding box. - @param box - Original bounding box, will be updated in-place. - @param lightPos - 4D light position in object space, when w=0.0f this - represents a directional light. - @param extrudeDist - The distance to extrude. - */ - virtual void extrudeBounds(AxisAlignedBox& box, const Vector4& lightPos, - Real extrudeDist) const; - - - }; - /** @} */ - /** @} */ -} // namespace Ogre -#include "OgreHeaderSuffix.h" - -#endif // __ShadowCaster_H__ diff --git a/OgreMain/include/OgreSharedPtr.h b/OgreMain/include/OgreSharedPtr.h deleted file mode 100644 index 830d3be667e..00000000000 --- a/OgreMain/include/OgreSharedPtr.h +++ /dev/null @@ -1,88 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __SharedPtr_H__ -#define __SharedPtr_H__ - -#include "OgrePrerequisites.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - using std::static_pointer_cast; - using std::dynamic_pointer_cast; - - /// @deprecated for backwards compatibility only, rather use shared_ptr directly - template class SharedPtr : public shared_ptr - { - public: - SharedPtr(std::nullptr_t) {} - SharedPtr() {} - template< class Y> - explicit SharedPtr(Y* ptr) : shared_ptr(ptr) {} - template< class Y, class Deleter > - SharedPtr( Y* ptr, Deleter d ) : shared_ptr(ptr, d) {} - SharedPtr(const SharedPtr& r) : shared_ptr(r) {} - template - SharedPtr(const SharedPtr& r) : shared_ptr(r) {} - - // implicit conversion from and to shared_ptr - template - SharedPtr(const shared_ptr& r) : shared_ptr(r) {} - operator const shared_ptr&() { return static_cast&>(*this); } - SharedPtr& operator=(const Ogre::SharedPtr& rhs) {shared_ptr::operator=(rhs); return *this;} - // so swig recognizes it should forward the operators - T* operator->() const { return shared_ptr::operator->(); } - - /// @deprecated use Ogre::static_pointer_cast instead - template - OGRE_DEPRECATED SharedPtr staticCast() const { return static_pointer_cast(*this); } - /// @deprecated use Ogre::dynamic_pointer_cast instead - template - OGRE_DEPRECATED SharedPtr dynamicCast() const { return dynamic_pointer_cast(*this); } - /// @deprecated this api will be dropped. use reset(T*) instead - OGRE_DEPRECATED void bind(T* rep) { shared_ptr::reset(rep); } - /// @deprecated use use_count() instead - OGRE_DEPRECATED unsigned int useCount() const { return shared_ptr::use_count(); } - /// @deprecated use get() instead - OGRE_DEPRECATED T* getPointer() const { return shared_ptr::get(); } - /// @deprecated use SharedPtr::operator bool instead - OGRE_DEPRECATED bool isNull(void) const { return !shared_ptr::operator bool(); } - /// @deprecated use reset() instead - OGRE_DEPRECATED void setNull() { shared_ptr::reset(); } - }; - /** @} */ - /** @} */ -} - - - -#endif diff --git a/OgreMain/include/OgreSimpleRenderable.h b/OgreMain/include/OgreSimpleRenderable.h deleted file mode 100644 index 0f6214d3bb1..00000000000 --- a/OgreMain/include/OgreSimpleRenderable.h +++ /dev/null @@ -1,104 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __SimpleRenderable_H__ -#define __SimpleRenderable_H__ - -#include "OgrePrerequisites.h" - -#include "OgreMovableObject.h" -#include "OgreRenderable.h" -#include "OgreAxisAlignedBox.h" -#include "OgreRenderOperation.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** Simple implementation of MovableObject and Renderable for single-part custom objects. - @see ManualObject for a simpler interface with more flexibility - */ - class _OgreExport SimpleRenderable : public MovableObject, public Renderable - { - bool getCastsShadows(void) const override { return getCastShadows(); } - protected: - RenderOperation mRenderOp; - - Affine3 mTransform; - AxisAlignedBox mBox; - - MaterialPtr mMaterial; - - /// The camera for the current frame. - Camera *mCamera; - - /// Static member used to automatically generate names for SimpleRendaerable objects. - static uint msGenNameCount; - - public: - /// Constructor - SimpleRenderable(); - - /// Named constructor - SimpleRenderable(const String& name); - - virtual void setMaterial(const MaterialPtr& mat); - const MaterialPtr& getMaterial(void) const override; - - virtual void setRenderOperation( const RenderOperation& rend ); - void getRenderOperation(RenderOperation& op) override; - - void setTransform( const Affine3& xform ); - void getWorldTransforms( Matrix4* xform ) const override; - - - void _notifyCurrentCamera(Camera* cam) override; - - void setBoundingBox( const AxisAlignedBox& box ); - const AxisAlignedBox& getBoundingBox(void) const override; - - void _updateRenderQueue(RenderQueue* queue) override; - - void visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables = false) override; - const String& getMovableType(void) const override; - const LightList& getLights(void) const override; - - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreSimpleSpline.h b/OgreMain/include/OgreSimpleSpline.h deleted file mode 100644 index 394327017d1..00000000000 --- a/OgreMain/include/OgreSimpleSpline.h +++ /dev/null @@ -1,139 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __SimpleSpline_H__ -#define __SimpleSpline_H__ - -#include "OgrePrerequisites.h" -#include "OgreMatrix4.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - /** A very simple spline class which implements the Catmull-Rom class of splines. - - Splines are bendy lines. You define a series of points, and the spline forms - a smoother line between the points to eliminate the sharp angles. - @par - Catmull-Rom splines are a specialisation of the general Hermite spline. With - a Hermite spline, you define the start and end point of the line, and 2 tangents, - one at the start of the line and one at the end. The Catmull-Rom spline simplifies - this by just asking you to define a series of points, and the tangents are - created for you. - */ - class _OgreExport SimpleSpline - { - public: - SimpleSpline(); - ~SimpleSpline(); - - /** Adds a control point to the end of the spline. */ - void addPoint(const Vector3& p); - - /** Gets the detail of one of the control points of the spline. */ - const Vector3& getPoint(unsigned short index) const; - - /** Gets the number of control points in the spline. */ - unsigned short getNumPoints(void) const; - - /** Clears all the points in the spline. */ - void clear(void); - - /** Updates a single point in the spline. - - This point must already exist in the spline. - */ - void updatePoint(unsigned short index, const Vector3& value); - - /** Returns an interpolated point based on a parametric value over the whole series. - - Given a t value between 0 and 1 representing the parametric distance along the - whole length of the spline, this method returns an interpolated point. - @param t Parametric value. - */ - Vector3 interpolate(Real t) const; - - /** Interpolates a single segment of the spline given a parametric value. - @param fromIndex The point index to treat as t=0. fromIndex + 1 is deemed to be t=1 - @param t Parametric value - */ - Vector3 interpolate(unsigned int fromIndex, Real t) const; - - - /** Tells the spline whether it should automatically calculate tangents on demand - as points are added. - - The spline calculates tangents at each point automatically based on the input points. - Normally it does this every time a point changes. However, if you have a lot of points - to add in one go, you probably don't want to incur this overhead and would prefer to - defer the calculation until you are finished setting all the points. You can do this - by calling this method with a parameter of 'false'. Just remember to manually call - the recalcTangents method when you are done. - @param autoCalc If true, tangents are calculated for you whenever a point changes. If false, - you must call reclacTangents to recalculate them when it best suits. - */ - void setAutoCalculate(bool autoCalc); - - /** Recalculates the tangents associated with this spline. - - If you tell the spline not to update on demand by calling setAutoCalculate(false) - then you must call this after completing your updates to the spline points. - */ - void recalcTangents(void); - - private: - - bool mAutoCalc; - - std::vector mPoints; - std::vector mTangents; - - /// Matrix of coefficients - Matrix4 mCoeffs; - - - - }; - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - - -#endif - diff --git a/OgreMain/include/OgreSingleton.h b/OgreMain/include/OgreSingleton.h deleted file mode 100644 index 20702b38cbe..00000000000 --- a/OgreMain/include/OgreSingleton.h +++ /dev/null @@ -1,118 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -/* Original version Copyright (C) Scott Bilas, 2000. - * All rights reserved worldwide. - * - * This software is provided "as is" without express or implied - * warranties. You may freely copy and compile this source into - * applications you distribute provided that the copyright text - * below is included in the resulting source code, for example: - * "Portions Copyright (C) Scott Bilas, 2000" - */ -#ifndef _SINGLETON_H__ -#define _SINGLETON_H__ - -// Added by Steve Streeting for Ogre -#include "OgrePrerequisites.h" -#include "OgreException.h" - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -# pragma warning (push) -# pragma warning ( disable: 4661) -#endif - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - -// End SJS additions -/** Template class for creating single-instance global classes. - * - * This implementation @cite bilas2000automatic slightly derives from the textbook pattern, by requiring - * manual instantiation, instead of implicitly doing it in #getSingleton. This is useful for classes that - * want to do some involved initialization, which should be done at a well defined time-point or need some - * additional parameters in their constructor. - * - * It also allows you to manage the singleton lifetime through RAII. - * - * @note Be aware that #getSingleton will fail before the global instance is created. (check via - * #getSingletonPtr) - */ -template class Singleton -{ -private: - /** @brief Explicit private copy constructor. This is a forbidden operation.*/ - Singleton(const Singleton&); - - /** @brief Private operator= . This is a forbidden operation. */ - Singleton& operator=(const Singleton&); - -protected: - static T* msSingleton; - -public: -#if defined(__has_attribute) -# if __has_attribute(no_sanitize) - // The `static_cast` happens so early in the construction of the inheriting - // classes that the `this` pointer is still detected as the super class - // pointer. Therefore, disabling vptr checks. - __attribute__((no_sanitize("vptr"))) -# endif -#endif - Singleton(void) - { - OgreAssert(!msSingleton, "There can be only one singleton"); - msSingleton = static_cast(this); - } - ~Singleton(void) - { - assert(msSingleton); - msSingleton = 0; - } - /// Get the singleton instance - static T& getSingleton(void) - { - assert(msSingleton); - return (*msSingleton); - } - /// @copydoc getSingleton - static T* getSingletonPtr(void) { return msSingleton; } - }; - /** @} */ - /** @} */ - -} -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -# pragma warning (pop) -#endif - -#endif diff --git a/OgreMain/include/OgreSkeleton.h b/OgreMain/include/OgreSkeleton.h deleted file mode 100644 index 688e04d5408..00000000000 --- a/OgreMain/include/OgreSkeleton.h +++ /dev/null @@ -1,489 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Skeleton_H__ -#define __Skeleton_H__ - -#include "OgrePrerequisites.h" -#include "OgreResource.h" -#include "OgreStringVector.h" -#include "OgreAnimation.h" -#include "OgreHeaderPrefix.h" -#include "OgreSharedPtr.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Animation - * @{ - */ - - /** */ - enum SkeletonAnimationBlendMode : uint8 { - /// Animations are applied by calculating a weighted average of all animations - ANIMBLEND_AVERAGE = 0, - /// Animations are applied by calculating a weighted cumulative total - ANIMBLEND_CUMULATIVE = 1 - }; - - struct LinkedSkeletonAnimationSource; - - /** A collection of Bone objects used to animate a skinned mesh. - - Skeletal animation works by having a collection of 'bones' which are - actually just joints with a position and orientation, arranged in a tree structure. - For example, the wrist joint is a child of the elbow joint, which in turn is a - child of the shoulder joint. Rotating the shoulder automatically moves the elbow - and wrist as well due to this hierarchy. - @par - So how does this animate a mesh? Well every vertex in a mesh is assigned to one or more - bones which affects it's position when the bone is moved. If a vertex is assigned to - more than one bone, then weights must be assigned to determine how much each bone affects - the vertex (actually a weight of 1.0 is used for single bone assignments). - Weighted vertex assignments are especially useful around the joints themselves - to avoid 'pinching' of the mesh in this region. - @par - Therefore by moving the skeleton using preset animations, we can animate the mesh. The - advantage of using skeletal animation is that you store less animation data, especially - as vertex counts increase. In addition, you are able to blend multiple animations together - (e.g. walking and looking around, running and shooting) and provide smooth transitions - between animations without incurring as much of an overhead as would be involved if you - did this on the core vertex data. - @par - Skeleton definitions are loaded from datafiles, namely the .skeleton file format. They - are loaded on demand, especially when referenced by a Mesh. - */ - class _OgreExport Skeleton : public Resource, public AnimationContainer - { - friend class SkeletonInstance; - private: - /// Internal constructor for use by SkeletonInstance only - Skeleton(); - - public: - /** Constructor, don't call directly, use SkeletonManager. - - On creation, a Skeleton has a no bones, you should create them and link - them together appropriately. - */ - Skeleton(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual = false, ManualResourceLoader* loader = 0); - virtual ~Skeleton(); - - - /** Creates a brand new Bone owned by this Skeleton. - - This method creates an unattached new Bone for this skeleton. - Unless this is to be a root bone (there may be more than one of - these), you must attach it to another Bone in the skeleton using addChild for it to be any use. - For this reason you will likely be better off creating child bones using the - Bone::createChild method instead, once you have created the root bone. - @par - Note that this method automatically generates a handle for the bone, which you - can retrieve using Bone::getHandle. If you wish the new Bone to have a specific - handle, use the alternate form of this method which takes a handle as a parameter, - although you should note the restrictions. - */ - virtual Bone* createBone(void); - - /** Creates a brand new Bone owned by this Skeleton. - - This method creates an unattached new Bone for this skeleton and assigns it a - specific handle. Unless this is to be a root bone (there may be more than one of - these), you must attach it to another Bone in the skeleton using addChild for it to be any use. - For this reason you will likely be better off creating child bones using the - Bone::createChild method instead, once you have created a root bone. - @param handle The handle to give to this new bone - must be unique within this skeleton. - You should also ensure that all bone handles are eventually contiguous (this is to simplify - their compilation into an indexed array of transformation matrices). For this reason - it is advised that you use the simpler createBone method which automatically assigns a - sequential handle starting from 0. - */ - virtual Bone* createBone(unsigned short handle); - - /** Creates a brand new Bone owned by this Skeleton. - - This method creates an unattached new Bone for this skeleton and assigns it a - specific name.Unless this is to be a root bone (there may be more than one of - these), you must attach it to another Bone in the skeleton using addChild for it to be any use. - For this reason you will likely be better off creating child bones using the - Bone::createChild method instead, once you have created the root bone. - @param name The name to give to this new bone - must be unique within this skeleton. - Note that the way OGRE looks up bones is via a numeric handle, so if you name a - Bone this way it will be given an automatic sequential handle. The name is just - for your convenience, although it is recommended that you only use the handle to - retrieve the bone in performance-critical code. - */ - virtual Bone* createBone(const String& name); - - /** Creates a brand new Bone owned by this Skeleton. - - This method creates an unattached new Bone for this skeleton and assigns it a - specific name and handle. Unless this is to be a root bone (there may be more than one of - these), you must attach it to another Bone in the skeleton using addChild for it to be any use. - For this reason you will likely be better off creating child bones using the - Bone::createChild method instead, once you have created the root bone. - @param name The name to give to this new bone - must be unique within this skeleton. - @param handle The handle to give to this new bone - must be unique within this skeleton. - */ - virtual Bone* createBone(const String& name, unsigned short handle); - - /** Returns the number of bones in this skeleton. */ - virtual unsigned short getNumBones(void) const; - - typedef std::vector BoneList; - typedef VectorIterator BoneIterator; - /// Get an iterator over the root bones in the skeleton, ie those with no parents - /// @deprecated use Skeleton::getRootBones - OGRE_DEPRECATED virtual BoneIterator getRootBoneIterator(void); - - /** Get the root bones in the skeleton, ie those with no parents - - The system derives the root bone the first time you ask for it. The root bone is the - only bone in the skeleton which has no parent. The system locates it by taking the - first bone in the list and going up the bone tree until there are no more parents, - and saves this top bone as the root. If you are building the skeleton manually using - createBone then you must ensure there is only one bone which is not a child of - another bone, otherwise your skeleton will not work properly. If you use createBone - only once, and then use Bone::createChild from then on, then inherently the first - bone you create will by default be the root. - */ - const BoneList& getRootBones() const; - - /// Get an iterator over all the bones in the skeleton - /// @deprecated use getBones() - OGRE_DEPRECATED virtual BoneIterator getBoneIterator(void); - /// Get all the bones in the skeleton - const BoneList& getBones() const { - return mBoneList; - } - - /** Gets a bone by it's handle. */ - virtual Bone* getBone(unsigned short handle) const; - - /** Gets a bone by it's name. */ - virtual Bone* getBone(const String& name) const; - - /** Returns whether this skeleton contains the named bone. */ - virtual bool hasBone(const String& name) const; - - /** Sets the current position / orientation to be the 'binding pose' i.e. the layout in which - bones were originally bound to a mesh. - */ - virtual void setBindingPose(void); - - /** Resets the position and orientation of all bones in this skeleton to their original binding position. - - A skeleton is bound to a mesh in a binding pose. Bone positions are then modified from this - position during animation. This method returns all the bones to their original position and - orientation. - @param resetManualBones If set to true, causes the state of manual bones to be reset - too, which is normally not done to allow the manual state to persist even - when keyframe animation is applied. - */ - virtual void reset(bool resetManualBones = false); - - /** Creates a new Animation object for animating this skeleton. - @param name The name of this animation - @param length The length of the animation in seconds - */ - Animation* createAnimation(const String& name, Real length) override; - - /** Returns the named Animation object. - - Will pick up animations in linked skeletons - (@see addLinkedSkeletonAnimationSource). - @param name The name of the animation - @param linker Optional pointer to a pointer to the linked skeleton animation - where this is coming from. - */ - virtual Animation* getAnimation(const String& name, - const LinkedSkeletonAnimationSource** linker) const; - - /** Returns the named Animation object. - - Will pick up animations in linked skeletons - (@see addLinkedSkeletonAnimationSource). - @param name The name of the animation - */ - Animation* getAnimation(const String& name) const override; - - /// Internal accessor for animations (returns null if animation does not exist) - virtual Animation* _getAnimationImpl(const String& name, - const LinkedSkeletonAnimationSource** linker = 0) const; - - - /** Returns whether this skeleton contains the named animation. */ - bool hasAnimation(const String& name) const override; - - /** Removes an Animation from this skeleton. */ - void removeAnimation(const String& name) override; - - /** Changes the state of the skeleton to reflect the application of the passed in collection of animations. - - Animating a skeleton involves both interpolating between keyframes of a specific animation, - and blending between the animations themselves. Calling this method sets the state of - the skeleton so that it reflects the combination of all the passed in animations, at the - time index specified for each, using the weights specified. Note that the weights between - animations do not have to sum to 1.0, because some animations may affect only subsets - of the skeleton. If the weights exceed 1.0 for the same area of the skeleton, the - movement will just be exaggerated. - */ - virtual void setAnimationState(const AnimationStateSet& animSet); - - - /** Initialise an animation set suitable for use with this skeleton. - - Only recommended for use inside the engine, not by applications. - */ - virtual void _initAnimationState(AnimationStateSet* animSet); - - /** Refresh an animation set suitable for use with this skeleton. - - Only recommended for use inside the engine, not by applications. - */ - virtual void _refreshAnimationState(AnimationStateSet* animSet); - - /** Populates the passed in array with the bone matrices based on the current position. - - Internal use only. The array pointed to by the passed in pointer must - be at least as large as the number of bones. - Assumes animation has already been updated. - */ - virtual void _getBoneMatrices(Affine3* pMatrices); - - /** Gets the number of animations on this skeleton. */ - unsigned short getNumAnimations(void) const override; - - /** Gets a single animation by index. - - Will NOT pick up animations in linked skeletons - (@see addLinkedSkeletonAnimationSource). - */ - Animation* getAnimation(unsigned short index) const override; - - - /** Gets the animation blending mode which this skeleton will use. */ - virtual SkeletonAnimationBlendMode getBlendMode() const; - /** Sets the animation blending mode this skeleton will use. */ - virtual void setBlendMode(SkeletonAnimationBlendMode state); - - /// Updates all the derived transforms in the skeleton - virtual void _updateTransforms(void); - - /** Optimise all of this skeleton's animations. - @see Animation::optimise - @param - preservingIdentityNodeTracks If true, don't destroy identity node tracks. - */ - virtual void optimiseAllAnimations(bool preservingIdentityNodeTracks = false); - - /** Allows you to use the animations from another Skeleton object to animate - this skeleton. - - If you have skeletons of identical structure (that means identically - named bones with identical handles, and with the same hierarchy), but - slightly different proportions or binding poses, you can re-use animations - from one in the other. Because animations are actually stored as - changes to bones from their bind positions, it's possible to use the - same animation data for different skeletons, provided the skeletal - structure matches and the 'deltas' stored in the keyframes apply - equally well to the other skeletons bind position (so they must be - roughly similar, but don't have to be identical). You can use the - 'scale' option to adjust the translation and scale keyframes where - there are large differences in size between the skeletons. - @note - This method takes a skeleton name, rather than a more specific - animation name, for two reasons; firstly it allows some validation - of compatibility of skeletal structure, and secondly skeletons are - the unit of loading. Linking a skeleton to another in this way means - that the linkee will be prevented from being destroyed until the - linker is destroyed. - - You cannot set up cyclic relationships, e.g. SkeletonA uses SkeletonB's - animations, and SkeletonB uses SkeletonA's animations. This is because - it would set up a circular dependency which would prevent proper - unloading - make one of the skeletons the 'master' in this case. - @param skelName Name of the skeleton to link animations from. This - skeleton will be loaded immediately if this skeleton is already - loaded, otherwise it will be loaded when this skeleton is. - @param scale A scale factor to apply to translation and scaling elements - of the keyframes in the other skeleton when applying the animations - to this one. Compensates for skeleton size differences. - */ - virtual void addLinkedSkeletonAnimationSource(const String& skelName, - Real scale = 1.0f); - /// Remove all links to other skeletons for the purposes of sharing animation - virtual void removeAllLinkedSkeletonAnimationSources(void); - - typedef std::vector - LinkedSkeletonAnimSourceList; - typedef ConstVectorIterator - LinkedSkeletonAnimSourceIterator; - /// Get the linked skeletons used as animation sources - virtual const LinkedSkeletonAnimSourceList& getLinkedSkeletonAnimationSources() const - { - return mLinkedSkeletonAnimSourceList; - } - - /// @deprecated use getLinkedSkeletonAnimationSources - OGRE_DEPRECATED virtual LinkedSkeletonAnimSourceIterator - getLinkedSkeletonAnimationSourceIterator(void) const; - - /// Internal method for marking the manual bones as dirty - virtual void _notifyManualBonesDirty(void); - /// Internal method for notifying that a bone is manual - virtual void _notifyManualBoneStateChange(Bone* bone); - - /// Have manual bones been modified since the skeleton was last updated? - virtual bool getManualBonesDirty(void) const { return mManualBonesDirty; } - /// Are there any manually controlled bones? - virtual bool hasManualBones(void) const { return !mManualBones.empty(); } - - /// Map to translate bone handle from one skeleton to another skeleton. - typedef std::vector BoneHandleMap; - - /** Merge animations from another Skeleton object into this skeleton. - - This function allow merge two structures compatible skeletons. The - 'compatible' here means identically bones will have same hierarchy, - but skeletons are not necessary to have same number of bones (if - number bones of source skeleton's more than this skeleton, they will - copied as is, except that duplicate names are disallowed; and in the - case of bones missing in source skeleton, nothing happen for those - bones). - @par - There are also unnecessary to have same binding poses, this function - will adjust keyframes of the source skeleton to match this skeleton - automatically. - @par - It's useful for exporting skeleton animations separately. i.e. export - mesh and 'master' skeleton at the same time, and then other animations - will export separately (even if used completely difference binding - pose), finally, merge separately exported animations into 'master' - skeleton. - @param - source Pointer to source skeleton. It'll keep unmodified. - @param - boneHandleMap A map to translate identically bone's handle from source - skeleton to this skeleton. If mapped bone handle doesn't exists in this - skeleton, it'll created. You can populate bone handle map manually, or - use predefined functions build bone handle map for you. (@see - _buildMapBoneByHandle, _buildMapBoneByName) - @param - animations A list name of animations to merge, if empty, all animations - of source skeleton are used to merge. Note that the animation names - must not presented in this skeleton, and will NOT pick up animations - in linked skeletons (@see addLinkedSkeletonAnimationSource). - */ - virtual void _mergeSkeletonAnimations(const Skeleton* source, - const BoneHandleMap& boneHandleMap, - const StringVector& animations = StringVector()); - - /** Build the bone handle map to use with Skeleton::_mergeSkeletonAnimations. - - Identically bones are determine by handle. - */ - virtual void _buildMapBoneByHandle(const Skeleton* source, - BoneHandleMap& boneHandleMap) const; - - /** Build the bone handle map to use with Skeleton::_mergeSkeletonAnimations. - - Identically bones are determine by name. - */ - virtual void _buildMapBoneByName(const Skeleton* source, - BoneHandleMap& boneHandleMap) const; - - protected: - /// Storage of animations, lookup by name - typedef std::map AnimationList; - AnimationList mAnimationsList; - private: - /// Lookup by bone name - typedef std::map BoneListByName; - BoneListByName mBoneListByName; - - /// Pointer to root bones (can now have multiple roots) - mutable BoneList mRootBones; - typedef std::set BoneSet; - /// Manual bones - BoneSet mManualBones; - - /// List of references to other skeletons to use animations from - mutable LinkedSkeletonAnimSourceList mLinkedSkeletonAnimSourceList; - - /// Bone automatic handles - unsigned short mNextAutoHandle; - SkeletonAnimationBlendMode mBlendState; - /// Manual bones dirty? - bool mManualBonesDirty; - /// Storage of bones, indexed by bone handle - BoneList mBoneList; - - /** Internal method which parses the bones to derive the root bone. - - Must be const because called in getRootBone but mRootBone is mutable - since lazy-updated. - */ - void deriveRootBone(void) const; - - /// Debugging method - _OgreExport friend std::ostream& operator<<(std::ostream& o, const Skeleton& s); - - void loadImpl() override {} - void unloadImpl() override { unprepareImpl(); } - - void prepareImpl(void) override; - void unprepareImpl(void) override; - /// @copydoc Resource::calculateSize - size_t calculateSize(void) const override; - - }; - - /// Link to another skeleton to share animations - struct LinkedSkeletonAnimationSource - { - String skeletonName; - SkeletonPtr pSkeleton; - Real scale; - LinkedSkeletonAnimationSource(const String& skelName, Real scl) - : skeletonName(skelName), scale(scl) {} - LinkedSkeletonAnimationSource(const String& skelName, Real scl, - const SkeletonPtr& skelPtr) - : skeletonName(skelName), pSkeleton(skelPtr), scale(scl) {} - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreSkeletonFileFormat.h b/OgreMain/include/OgreSkeletonFileFormat.h deleted file mode 100644 index bf5bcd70e15..00000000000 --- a/OgreMain/include/OgreSkeletonFileFormat.h +++ /dev/null @@ -1,117 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __SkeletonFileFormat_H__ -#define __SkeletonFileFormat_H__ - -#include "OgrePrerequisites.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Animation - * @{ - */ -/** Definition of the OGRE .skeleton file format - - .skeleton files are binary files (for read efficiency at runtime) and are arranged into chunks - of data, very like 3D Studio's format. - A chunk always consists of: - unsigned short CHUNK_ID : one of the following chunk ids identifying the chunk - unsigned long LENGTH : length of the chunk in bytes, including this header - void* DATA : the data, which may contain other sub-chunks (various data types) - - A .skeleton file contains both the definition of the Skeleton object and the animations it contains. It - contains only a single skeleton but can contain multiple animations. - - -*/ - enum SkeletonChunkID { - SKELETON_HEADER = 0x1000, - // char* version : Version number check - SKELETON_BLENDMODE = 0x1010, // optional - // unsigned short blendmode : SkeletonAnimationBlendMode - - SKELETON_BONE = 0x2000, - // Repeating section defining each bone in the system. - // Bones are assigned indexes automatically based on their order of declaration - // starting with 0. - - // char* name : name of the bone - // unsigned short handle : handle of the bone, should be contiguous & start at 0 - // Vector3 position : position of this bone relative to parent - // Quaternion orientation : orientation of this bone relative to parent - // Vector3 scale : scale of this bone relative to parent - - SKELETON_BONE_PARENT = 0x3000, - // Record of the parent of a single bone, used to build the node tree - // Repeating section, listed in Bone Index order, one per Bone - - // unsigned short handle : child bone - // unsigned short parentHandle : parent bone - - SKELETON_ANIMATION = 0x4000, - // A single animation for this skeleton - - // char* name : Name of the animation - // float length : Length of the animation in seconds - - SKELETON_ANIMATION_BASEINFO = 0x4010, - // [Optional] base keyframe information - // char* baseAnimationName (blank for self) - // float baseKeyFrameTime - - SKELETON_ANIMATION_TRACK = 0x4100, - // A single animation track (relates to a single bone) - // Repeating section (within SKELETON_ANIMATION) - - // unsigned short boneIndex : Index of bone to apply to - - SKELETON_ANIMATION_TRACK_KEYFRAME = 0x4110, - // A single keyframe within the track - // Repeating section - - // float time : The time position (seconds) - // Quaternion rotate : Rotation to apply at this keyframe - // Vector3 translate : Translation to apply at this keyframe - // Vector3 scale : Scale to apply at this keyframe - SKELETON_ANIMATION_LINK = 0x5000 - // Link to another skeleton, to re-use its animations - - // char* skeletonName : name of skeleton to get animations from - // float scale : scale to apply to trans/scale keys - - }; - /** @} */ - /** @} */ - -} // namespace - - -#endif diff --git a/OgreMain/include/OgreSkeletonInstance.h b/OgreMain/include/OgreSkeletonInstance.h deleted file mode 100644 index 0a90372af5b..00000000000 --- a/OgreMain/include/OgreSkeletonInstance.h +++ /dev/null @@ -1,162 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __SkeletonInstance_H__ -#define __SkeletonInstance_H__ - -#include "OgrePrerequisites.h" -#include "OgreSkeleton.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** A SkeletonInstance is a single instance of a Skeleton used by a world object. - - The difference between a Skeleton and a SkeletonInstance is that the - Skeleton is the 'master' version much like Mesh is a 'master' version of - Entity. Many SkeletonInstance objects can be based on a single Skeleton, - and are copies of it when created. Any changes made to this are not - reflected in the master copy. The exception is animations; these are - shared on the Skeleton itself and may not be modified here. - */ - class _OgreExport SkeletonInstance : public Skeleton - { - public: - /** Constructor, don't call directly, this will be created automatically - when you create an Entity based on a skeletally animated Mesh. - */ - SkeletonInstance(const SkeletonPtr& masterCopy); - ~SkeletonInstance(); - - /** Gets the number of animations on this skeleton. */ - unsigned short getNumAnimations(void) const override; - - /** Gets a single animation by index. */ - Animation* getAnimation(unsigned short index) const override; - /// Internal accessor for animations (returns null if animation does not exist) - Animation* _getAnimationImpl(const String& name, - const LinkedSkeletonAnimationSource** linker = 0) const override; - - /** Creates a new Animation object for animating this skeleton. - - This method updates the reference skeleton, not just this instance! - @param name The name of this animation - @param length The length of the animation in seconds - */ - Animation* createAnimation(const String& name, Real length) override; - - /** Returns the named Animation object. */ - Animation* getAnimation(const String& name, - const LinkedSkeletonAnimationSource** linker = 0) const override; - - /** Removes an Animation from this skeleton. - - This method updates the reference skeleton, not just this instance! - */ - void removeAnimation(const String& name) override; - - - /** Creates a TagPoint ready to be attached to a bone */ - TagPoint* createTagPointOnBone(Bone* bone, - const Quaternion &offsetOrientation = Quaternion::IDENTITY, - const Vector3 &offsetPosition = Vector3::ZERO); - - /** Frees a TagPoint that already attached to a bone */ - void freeTagPoint(TagPoint* tagPoint); - - /// @copydoc Skeleton::addLinkedSkeletonAnimationSource - void addLinkedSkeletonAnimationSource(const String& skelName, - Real scale = 1.0f) override; - /// @copydoc Skeleton::removeAllLinkedSkeletonAnimationSources - void removeAllLinkedSkeletonAnimationSources(void) override; - const LinkedSkeletonAnimSourceList& - getLinkedSkeletonAnimationSources() const override; - OGRE_DEPRECATED LinkedSkeletonAnimSourceIterator - getLinkedSkeletonAnimationSourceIterator(void) const override; - - /// @copydoc Skeleton::_initAnimationState - void _initAnimationState(AnimationStateSet* animSet) override; - - /// @copydoc Skeleton::_refreshAnimationState - void _refreshAnimationState(AnimationStateSet* animSet) override; - - /// @copydoc Resource::getName - const String& getName(void) const; - /// @copydoc Resource::getHandle - ResourceHandle getHandle(void) const; - /// @copydoc Resource::getGroup - const String& getGroup(void) const; - - private: - /// Pointer back to master Skeleton - SkeletonPtr mSkeleton; - - typedef std::list TagPointList; - - /** Active tag point list. - - This is a linked list of pointers to active tag points - @par - This allows very fast insertions and deletions from anywhere in the list to activate / deactivate - tag points (required for weapon / equip systems etc) as well as reuse of TagPoint instances - without construction & destruction which avoids memory thrashing. - */ - TagPointList mActiveTagPoints; - - /** Free tag point list. - - This contains a list of the tag points free for use as new instances - as required by the set. When a TagPoint instance is deactivated, there will be a reference on this - list. As they get used this list reduces, as they get released back to to the set they get added - back to the list. - */ - TagPointList mFreeTagPoints; - - /// TagPoint automatic handles - unsigned short mNextTagPointAutoHandle; - - void cloneBoneAndChildren(Bone* source, Bone* parent); - void prepareImpl(void) override; - void unprepareImpl(void) override; - - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreSkeletonManager.h b/OgreMain/include/OgreSkeletonManager.h deleted file mode 100644 index 46428eb9d82..00000000000 --- a/OgreMain/include/OgreSkeletonManager.h +++ /dev/null @@ -1,87 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __SkeletonManager_H__ -#define __SkeletonManager_H__ - -#include "OgrePrerequisites.h" - -#include "OgreResourceManager.h" -#include "OgreSingleton.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Animation - * @{ - */ - /** Handles the management of skeleton resources. - - This class deals with the runtime management of - skeleton data; like other resource managers it handles - the creation of resources (in this case skeleton data), - working within a fixed memory budget. - */ - class _OgreExport SkeletonManager: public ResourceManager, public Singleton - { - public: - /// Constructor - SkeletonManager(); - ~SkeletonManager(); - - /// Create a new skeleton - /// @see ResourceManager::createResource - SkeletonPtr create (const String& name, const String& group, - bool isManual = false, ManualResourceLoader* loader = 0, - const NameValuePairList* createParams = 0); - - /// Get a resource by name - /// @see ResourceManager::getResourceByName - SkeletonPtr getByName(const String& name, const String& groupName OGRE_RESOURCE_GROUP_INIT) const; - - /// @copydoc Singleton::getSingleton() - static SkeletonManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static SkeletonManager* getSingletonPtr(void); - private: - - /// @copydoc ResourceManager::createImpl - Resource* createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams) override; - - }; - - /** @} */ - /** @} */ - -} - - -#endif diff --git a/OgreMain/include/OgreSkeletonSerializer.h b/OgreMain/include/OgreSkeletonSerializer.h deleted file mode 100644 index ba5180b2a61..00000000000 --- a/OgreMain/include/OgreSkeletonSerializer.h +++ /dev/null @@ -1,152 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __SkeletonSerializer_H__ -#define __SkeletonSerializer_H__ - -#include "OgrePrerequisites.h" -#include "OgreSerializer.h" - -namespace Ogre { - - struct LinkedSkeletonAnimationSource; - - /// Skeleton compatibility versions - enum SkeletonVersion - { - /// OGRE version v1.0+ - SKELETON_VERSION_1_0, - /// OGRE version v1.8+ - SKELETON_VERSION_1_8, - - /// Latest version available - SKELETON_VERSION_LATEST = 100 - }; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Animation - * @{ - */ - /** Class for serialising skeleton data to/from an OGRE .skeleton file. - - This class allows exporters to write OGRE .skeleton files easily, and allows the - OGRE engine to import .skeleton files into instantiated OGRE Skeleton objects. - Note that a .skeleton file includes not only the Skeleton, but also definitions of - any Animations it uses. - @par - To export a Skeleton:
    -
  1. Create a Skeleton object and populate it using it's methods.
  2. -
  3. Call the exportSkeleton method
  4. -
- */ - class _OgreExport SkeletonSerializer : public Serializer - { - - public: - SkeletonSerializer(); - - /** Exports a skeleton to the file specified. - - This method takes an externally created Skeleton object, and exports both it - and animations it uses to a .skeleton file. - @param pSkeleton Weak reference to the Skeleton to export - @param filename The destination filename - @param ver @copydoc SkeletonVersion - @param endianMode The endian mode to write in - */ - void exportSkeleton(const Skeleton* pSkeleton, const String& filename, - SkeletonVersion ver = SKELETON_VERSION_LATEST, Endian endianMode = ENDIAN_NATIVE); - - /** Exports a skeleton to the stream specified. - - This method takes an externally created Skeleton object, and exports both it - and animations it uses to a .skeleton file. - @param pSkeleton Weak reference to the Skeleton to export - @param stream The destination stream - @param ver @copydoc SkeletonVersion - @param endianMode The endian mode to write in - */ - void exportSkeleton(const Skeleton* pSkeleton, const DataStreamPtr& stream, - SkeletonVersion ver = SKELETON_VERSION_LATEST, Endian endianMode = ENDIAN_NATIVE); - /** Imports Skeleton and animation data from a .skeleton file DataStream. - - This method imports data from a DataStream opened from a .skeleton file and places it's - contents into the Skeleton object which is passed in. - @param stream The DataStream holding the .skeleton data. Must be initialised (pos at the start of the buffer). - @param pDest Weak reference to the Skeleton object which will receive the data. Should be blank already. - */ - void importSkeleton(DataStreamPtr& stream, Skeleton* pDest); - - // TODO: provide Cal3D importer? - - private: - - void setWorkingVersion(SkeletonVersion ver); - - // Internal export methods - void writeSkeleton(const Skeleton* pSkel, SkeletonVersion ver); - void writeBone(const Skeleton* pSkel, const Bone* pBone); - void writeBoneParent(const Skeleton* pSkel, unsigned short boneId, unsigned short parentId); - void writeAnimation(const Skeleton* pSkel, const Animation* anim, SkeletonVersion ver); - void writeAnimationTrack(const Skeleton* pSkel, const NodeAnimationTrack* track); - void writeKeyFrame(const Skeleton* pSkel, const TransformKeyFrame* key); - void writeSkeletonAnimationLink(const Skeleton* pSkel, - const LinkedSkeletonAnimationSource& link); - - // Internal import methods - void readFileHeader(DataStreamPtr& stream); - void readBone(DataStreamPtr& stream, Skeleton* pSkel); - void readBoneParent(DataStreamPtr& stream, Skeleton* pSkel); - void readAnimation(DataStreamPtr& stream, Skeleton* pSkel); - void readAnimationTrack(DataStreamPtr& stream, Animation* anim, Skeleton* pSkel); - void readKeyFrame(DataStreamPtr& stream, NodeAnimationTrack* track, Skeleton* pSkel); - void readSkeletonAnimationLink(DataStreamPtr& stream, Skeleton* pSkel); - - size_t calcBoneSize(const Skeleton* pSkel, const Bone* pBone); - size_t calcBoneSizeWithoutScale(const Skeleton* pSkel, const Bone* pBone); - size_t calcBoneParentSize(const Skeleton* pSkel); - size_t calcAnimationSize(const Skeleton* pSkel, const Animation* pAnim, SkeletonVersion ver); - size_t calcAnimationTrackSize(const Skeleton* pSkel, const NodeAnimationTrack* pTrack); - size_t calcKeyFrameSize(const Skeleton* pSkel, const TransformKeyFrame* pKey); - size_t calcKeyFrameSizeWithoutScale(const Skeleton* pSkel, const TransformKeyFrame* pKey); - size_t calcSkeletonAnimationLinkSize(const Skeleton* pSkel, - const LinkedSkeletonAnimationSource& link); - - - - - }; - /** @} */ - /** @} */ - -} - - -#endif diff --git a/OgreMain/include/OgreSphere.h b/OgreMain/include/OgreSphere.h deleted file mode 100644 index 01ed6592941..00000000000 --- a/OgreMain/include/OgreSphere.h +++ /dev/null @@ -1,138 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Sphere_H_ -#define __Sphere_H_ - -// Precompiler options -#include "OgrePrerequisites.h" - -#include "OgreVector.h" -#include "OgrePlane.h" - -namespace Ogre { - - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - /** A sphere primitive, mostly used for bounds checking. - - A sphere in math texts is normally represented by the function - x^2 + y^2 + z^2 = r^2 (for sphere's centered on the origin). Ogre stores spheres - simply as a center point and a radius. - */ - class _OgreExport Sphere - { - private: - Real mRadius; - Vector3 mCenter; - public: - /** Standard constructor - creates a unit sphere around the origin.*/ - Sphere() : mRadius(1.0), mCenter(Vector3::ZERO) {} - /** Constructor allowing arbitrary spheres. - @param center The center point of the sphere. - @param radius The radius of the sphere. - */ - Sphere(const Vector3& center, Real radius) - : mRadius(radius), mCenter(center) {} - - /** Returns the radius of the sphere. */ - Real getRadius(void) const { return mRadius; } - - /** Sets the radius of the sphere. */ - void setRadius(Real radius) { mRadius = radius; } - - /** Returns the center point of the sphere. */ - const Vector3& getCenter(void) const { return mCenter; } - - /** Sets the center point of the sphere. */ - void setCenter(const Vector3& center) { mCenter = center; } - - /** Returns whether or not this sphere intersects another sphere. */ - bool intersects(const Sphere& s) const - { - return (s.mCenter - mCenter).squaredLength() <= - Math::Sqr(s.mRadius + mRadius); - } - /** Returns whether or not this sphere intersects a box. */ - bool intersects(const AxisAlignedBox& box) const - { - return Math::intersects(*this, box); - } - /** Returns whether or not this sphere intersects a plane. */ - bool intersects(const Plane& plane) const - { - return Math::Abs(plane.getDistance(getCenter())) <= getRadius(); - } - /** Returns whether or not this sphere intersects a point. */ - bool intersects(const Vector3& v) const - { - return ((v - mCenter).squaredLength() <= Math::Sqr(mRadius)); - } - /** Merges another Sphere into the current sphere */ - void merge(const Sphere& oth) - { - Vector3 diff = oth.getCenter() - mCenter; - Real lengthSq = diff.squaredLength(); - Real radiusDiff = oth.getRadius() - mRadius; - - // Early-out - if (Math::Sqr(radiusDiff) >= lengthSq) - { - // One fully contains the other - if (radiusDiff <= 0.0f) - return; // no change - else - { - mCenter = oth.getCenter(); - mRadius = oth.getRadius(); - return; - } - } - - Real length = Math::Sqrt(lengthSq); - Real t = (length + radiusDiff) / (2.0f * length); - mCenter = mCenter + diff * t; - mRadius = 0.5f * (length + mRadius + oth.getRadius()); - } - }; - - inline bool Math::intersects(const Sphere& sphere, const Plane& plane) - { - return sphere.intersects(plane); - } - /** @} */ - /** @} */ - -} - -#endif - diff --git a/OgreMain/include/OgreStaticGeometry.h b/OgreMain/include/OgreStaticGeometry.h deleted file mode 100644 index 6ee69a95d96..00000000000 --- a/OgreMain/include/OgreStaticGeometry.h +++ /dev/null @@ -1,731 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __StaticGeometry_H__ -#define __StaticGeometry_H__ - -#include "OgrePrerequisites.h" -#include "OgreMovableObject.h" -#include "OgreRenderable.h" -#include "OgreMesh.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** Pre-transforms and batches up meshes for efficient use as static - geometry in a scene. - - Modern graphics cards (GPUs) prefer to receive geometry in large - batches. It is orders of magnitude faster to render 10 batches - of 10,000 triangles than it is to render 10,000 batches of 10 - triangles, even though both result in the same number of on-screen - triangles. - @par - Therefore it is important when you are rendering a lot of geometry to - batch things up into as few rendering calls as possible. This - class allows you to build a batched object from a series of entities - in order to benefit from this behaviour. - Batching has implications of it's own though: - @li Batched geometry cannot be subdivided; that means that the whole - group will be displayed, or none of it will. This obivously has - culling issues. - @li A single world transform must apply to the entire batch. Therefore - once you have batched things, you can't move them around relative to - each other. That's why this class is most useful when dealing with - static geometry (hence the name). In addition, geometry is - effectively duplicated, so if you add 3 entities based on the same - mesh in different positions, they will use 3 times the geometry - space than the movable version (which re-uses the same geometry). - So you trade memory and flexibility of movement for pure speed when - using this class. - @li A single material must apply for each batch. In fact this class - allows you to use multiple materials, but you should be aware that - internally this means that there is one batch per material. - Therefore you won't gain as much benefit from the batching if you - use many different materials; try to keep the number down. - @par - In order to retain some sort of culling, this class will batch up - meshes in localised regions. The size and shape of these blocks is - controlled by the SceneManager which constructs this object, since it - makes sense to batch things up in the most appropriate way given the - existing partitioning of the scene. - @par - The LOD settings of both the Mesh and the Materials used in - constructing this static geometry will be respected. This means that - if you use meshes/materials which have LOD, batches in the distance - will have a lower polygon count or material detail to those in the - foreground. Since each mesh might have different LOD distances, during - build the furthest distance at each LOD level from all meshes - in that region is used. This means all the LOD levels change at the - same time, but at the furthest distance of any of them (so quality is - not degraded). Be aware that using Mesh LOD in this class will - further increase the memory required. Only generated LOD - is supported for meshes. - @par - There are 2 ways you can add geometry to this class; you can add - Entity objects directly with predetermined positions, scales and - orientations, or you can add an entire SceneNode and it's subtree, - including all the objects attached to it. Once you've added everything - you need to, you have to call build() the fix the geometry in place. - @note - This class is not a replacement for world geometry (@see - SceneManager::setWorldGeometry). The single most efficient way to - render large amounts of static geometry is to use a SceneManager which - is specialised for dealing with that particular world structure. - However, this class does provide you with a good 'halfway house' - between generalised movable geometry (Entity) which works with all - SceneManagers but isn't efficient when using very large numbers, and - highly specialised world geometry which is extremely fast but not - generic and typically requires custom world editors. - @par - You should not construct instances of this class directly; instead, cal - SceneManager::createStaticGeometry, which gives the SceneManager the - option of providing you with a specialised version of this class if it - wishes, and also handles the memory management for you like other - classes. - @note - Warning: this class only works with indexed triangle lists at the moment, - do not pass it triangle strips, fans or lines / points, or unindexed geometry. - */ - class _OgreExport StaticGeometry : public BatchedGeometryAlloc - { - public: - /** Struct holding geometry optimised per SubMesh / LOD level, ready - for copying to instances. - - Since we're going to be duplicating geometry lots of times, it's - far more important that we don't have redundant vertex data. If a - SubMesh uses shared geometry, or we're looking at a lower LOD, not - all the vertices are being referenced by faces on that submesh. - Therefore to duplicate them, potentially hundreds or even thousands - of times, would be extremely wasteful. Therefore, if a SubMesh at - a given LOD has wastage, we create an optimised version of it's - geometry which is ready for copying with no wastage. - */ - class _OgrePrivate OptimisedSubMeshGeometry : public BatchedGeometryAlloc - { - public: - OptimisedSubMeshGeometry() :vertexData(0), indexData(0) {} - ~OptimisedSubMeshGeometry() - { - OGRE_DELETE vertexData; - OGRE_DELETE indexData; - } - VertexData *vertexData; - IndexData *indexData; - }; - typedef std::list OptimisedSubMeshGeometryList; - /// Saved link between SubMesh at a LOD and vertex/index data - /// May point to original or optimised geometry - struct SubMeshLodGeometryLink - { - VertexData* vertexData; - IndexData* indexData; - }; - typedef std::vector SubMeshLodGeometryLinkList; - typedef std::map SubMeshGeometryLookup; - /// Structure recording a queued submesh for the build - struct QueuedSubMesh : public BatchedGeometryAlloc - { - SubMesh* submesh; - MaterialPtr material; - /// Link to LOD list of geometry, potentially optimised - SubMeshLodGeometryLinkList* geometryLodList; - Vector3 position; - Quaternion orientation; - Vector3 scale; - /// Pre-transformed world AABB - AxisAlignedBox worldBounds; - }; - typedef std::vector QueuedSubMeshList; - /// Structure recording a queued geometry for low level builds - struct QueuedGeometry : public BatchedGeometryAlloc - { - SubMeshLodGeometryLink* geometry; - Vector3 position; - Quaternion orientation; - Vector3 scale; - }; - typedef std::vector QueuedGeometryList; - - // forward declarations - class LODBucket; - class MaterialBucket; - class Region; - - /** A GeometryBucket is a the lowest level bucket where geometry with - the same vertex & index format is stored. It also acts as the - renderable. - */ - class _OgreExport GeometryBucket : public Renderable, public BatchedGeometryAlloc - { - /// Geometry which has been queued up pre-build (not for deallocation) - QueuedGeometryList mQueuedGeometry; - /// Pointer to parent bucket - MaterialBucket* mParent; - /// Vertex information, includes current number of vertices - /// committed to be a part of this bucket - VertexData* mVertexData; - /// Index information, includes index type which limits the max - /// number of vertices which are allowed in one bucket - IndexData* mIndexData; - /// Maximum vertex indexable - size_t mMaxVertexIndex; - public: - GeometryBucket(MaterialBucket* parent, const VertexData* vData, const IndexData* iData); - virtual ~GeometryBucket(); - MaterialBucket* getParent(void) { return mParent; } - /// Get the vertex data for this geometry - const VertexData* getVertexData(void) const { return mVertexData; } - /// Get the index data for this geometry - const IndexData* getIndexData(void) const { return mIndexData; } - /// @copydoc Renderable::getMaterial - const MaterialPtr& getMaterial(void) const override; - Technique* getTechnique(void) const override; - void getRenderOperation(RenderOperation& op) override; - void getWorldTransforms(Matrix4* xform) const override; - Real getSquaredViewDepth(const Camera* cam) const override; - const LightList& getLights(void) const override; - bool getCastsShadows(void) const override; - - /** Try to assign geometry to this bucket. - @return false if there is no room left in this bucket - */ - bool assign(QueuedGeometry* qsm); - /// Build - void build(bool stencilShadows); - /// Dump contents for diagnostics - _OgreExport friend std::ostream& operator<<(std::ostream& o, const GeometryBucket& b); - }; - /** A MaterialBucket is a collection of smaller buckets with the same - Material (and implicitly the same LOD). */ - class _OgreExport MaterialBucket : public BatchedGeometryAlloc - { - public: - /// list of Geometry Buckets in this region - typedef std::vector GeometryBucketList; - private: - /// Pointer to parent LODBucket - LODBucket* mParent; - /// Pointer to material being used - MaterialPtr mMaterial; - /// Active technique - Technique* mTechnique; - - /// list of Geometry Buckets in this region - GeometryBucketList mGeometryBucketList; - // index to current Geometry Buckets for a given geometry format - typedef std::map CurrentGeometryMap; - CurrentGeometryMap mCurrentGeometryMap; - - public: - MaterialBucket(LODBucket* parent, const MaterialPtr& material); - virtual ~MaterialBucket(); - LODBucket* getParent(void) { return mParent; } - /// Get the material name - const String& getMaterialName(void) const { return mMaterial->getName(); } - /// Assign geometry to this bucket - void assign(QueuedGeometry* qsm); - /// Build - void build(bool stencilShadows); - /// Add children to the render queue - void addRenderables(RenderQueue* queue, uint8 group, - Real lodValue); - /// Get the material for this bucket - const MaterialPtr& getMaterial(void) const { return mMaterial; } - /// Override Material without changing the partitioning. For advanced use only. - void _setMaterial(const MaterialPtr& material); - /// Iterator over geometry - typedef VectorIterator GeometryIterator; - /// Get a list of the contained geometry - const GeometryBucketList& getGeometryList() const { return mGeometryBucketList; } - /// @deprecated use getGeometryList() - OGRE_DEPRECATED GeometryIterator getGeometryIterator(void); - /// Get the current Technique - Technique* getCurrentTechnique(void) const { return mTechnique; } - /// Dump contents for diagnostics - _OgreExport friend std::ostream& operator<<(std::ostream& o, const MaterialBucket& b); - void visitRenderables(Renderable::Visitor* visitor, bool debugRenderables); - }; - /** A LODBucket is a collection of smaller buckets with the same LOD. - - LOD refers to Mesh LOD here. Material LOD can change separately - at the next bucket down from this. - */ - class _OgreExport LODBucket : public BatchedGeometryAlloc - { - public: - /// Lookup of Material Buckets in this region - typedef std::map MaterialBucketMap; - private: - /// Pointer to parent region - Region* mParent; - /// LOD level (0 == full LOD) - unsigned short mLod; - /// LOD value at which this LOD starts to apply (squared) - Real mLodValue; - /// Lookup of Material Buckets in this region - MaterialBucketMap mMaterialBucketMap; - /// Geometry queued for a single LOD (deallocated here) - QueuedGeometryList mQueuedGeometryList; - /// Edge list, used if stencil shadow casting is enabled - EdgeData* mEdgeList; - /// Is a vertex program in use somewhere in this group? - bool mVertexProgramInUse; - /// List of shadow renderables - ShadowCaster::ShadowRenderableList mShadowRenderables; - public: - LODBucket(Region* parent, unsigned short lod, Real lodValue); - virtual ~LODBucket(); - Region* getParent(void) { return mParent; } - /// Get the LOD index - ushort getLod(void) const { return mLod; } - /// Get the LOD value - Real getLodValue(void) const { return mLodValue; } - /// Assign a queued submesh to this bucket, using specified mesh LOD - void assign(QueuedSubMesh* qsm, ushort atLod); - /// Build - void build(bool stencilShadows); - /// Add children to the render queue - void addRenderables(RenderQueue* queue, uint8 group, - Real lodValue); - /// Iterator over the materials in this LOD - typedef MapIterator MaterialIterator; - /// Get an iterator over the materials in this LOD - const MaterialBucketMap& getMaterialBuckets() const { return mMaterialBucketMap; } - /// @deprecated use getMaterialBuckets() - OGRE_DEPRECATED MaterialIterator getMaterialIterator(void); - /// Dump contents for diagnostics - _OgreExport friend std::ostream& operator<<(std::ostream& o, const LODBucket& b); - void visitRenderables(Renderable::Visitor* visitor, bool debugRenderables); - EdgeData* getEdgeList() const { return mEdgeList; } - ShadowCaster::ShadowRenderableList& getShadowRenderableList() { return mShadowRenderables; } - bool isVertexProgramInUse() const { return mVertexProgramInUse; } - void updateShadowRenderables(const Vector4& lightPos, const HardwareIndexBufferPtr& indexBuffer, - Real extrusionDistance, int flags = 0); - }; - /** The details of a topological region which is the highest level of - partitioning for this class. - - The size & shape of regions entirely depends on the SceneManager - specific implementation. It is a MovableObject since it will be - attached to a node based on the local centre - in practice it - won't actually move (although in theory it could). - */ - class _OgreExport Region : public MovableObject - { - friend class MaterialBucket; - friend class GeometryBucket; - public: - /// list of LOD Buckets in this region - typedef std::vector LODBucketList; - private: - /// Parent static geometry - StaticGeometry* mParent; - /// Local list of queued meshes (not used for deallocation) - QueuedSubMeshList mQueuedSubMeshes; - /// Unique identifier for the region - uint32 mRegionID; - /// Center of the region - Vector3 mCentre; - /// LOD values as built up - use the max at each level - Mesh::LodValueList mLodValues; - /// Local AABB relative to region centre - AxisAlignedBox mAABB; - /// Local bounding radius - Real mBoundingRadius; - /// The current LOD level, as determined from the last camera - ushort mCurrentLod; - /// Current LOD value, passed on to do material LOD later - Real mLodValue; - /// List of LOD buckets - LODBucketList mLodBucketList; - /// List of lights for this region - mutable LightList mLightList; - /// LOD strategy reference - const LodStrategy *mLodStrategy; - /// Current camera - Camera *mCamera; - /// Cached squared view depth value to avoid recalculation by GeometryBucket - Real mSquaredViewDepth; - - public: - Region(StaticGeometry* parent, const String& name, SceneManager* mgr, - uint32 regionID, const Vector3& centre); - virtual ~Region(); - // more fields can be added in subclasses - StaticGeometry* getParent(void) const { return mParent;} - /// Assign a queued mesh to this region, read for final build - void assign(QueuedSubMesh* qmesh); - /// Build this region - void build(bool stencilShadows); - /// Get the region ID of this region - uint32 getID(void) const { return mRegionID; } - /// Get the centre point of the region - const Vector3& getCentre(void) const { return mCentre; } - const String& getMovableType(void) const override; - void _notifyCurrentCamera(Camera* cam) override; - const AxisAlignedBox& getBoundingBox(void) const override; - Real getBoundingRadius(void) const override; - void _updateRenderQueue(RenderQueue* queue) override; - /// @copydoc MovableObject::visitRenderables - void visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables = false) override; - bool isVisible(void) const override; - uint32 getTypeFlags(void) const override; - - typedef VectorIterator LODIterator; - /// @deprecated use getLODBuckets() - OGRE_DEPRECATED LODIterator getLODIterator(void); - /// Get an list of the LODs in this region - const LODBucketList& getLODBuckets() const { return mLodBucketList; } - const ShadowRenderableList& - getShadowVolumeRenderableList(const Light* light, const HardwareIndexBufferPtr& indexBuffer, - size_t& indexBufferUsedSize, float extrusionDistance, - int flags = 0) override; - EdgeData* getEdgeList(void) override; - - void _releaseManualHardwareResources() override; - void _restoreManualHardwareResources() override; - - /// Dump contents for diagnostics - _OgreExport friend std::ostream& operator<<(std::ostream& o, const Region& r); - - }; - /** Indexed region map based on packed x/y/z region index, 10 bits for - each axis. - - Regions are indexed 0-1023 in all axes, where for example region - 0 in the x axis begins at mOrigin.x + (mRegionDimensions.x * -512), - and region 1023 ends at mOrigin + (mRegionDimensions.x * 512). - */ - typedef std::map RegionMap; - private: - // General state & settings - SceneManager* mOwner; - String mName; - Real mUpperDistance; - Real mSquaredUpperDistance; - bool mCastShadows; - Vector3 mRegionDimensions; - Vector3 mHalfRegionDimensions; - Vector3 mOrigin; - bool mVisible; - /// The render queue to use when rendering this object - uint8 mRenderQueueID; - /// Flags whether the RenderQueue's default should be used. - bool mRenderQueueIDSet; - /// Stores the visibility flags for the regions - uint32 mVisibilityFlags; - - QueuedSubMeshList mQueuedSubMeshes; - - /// List of geometry which has been optimised for SubMesh use - /// This is the primary storage used for cleaning up later - OptimisedSubMeshGeometryList mOptimisedSubMeshGeometryList; - - /** Cached links from SubMeshes to (potentially optimised) geometry - This is not used for deletion since the lookup may reference - original vertex data - */ - SubMeshGeometryLookup mSubMeshGeometryLookup; - - /// Map of regions - RegionMap mRegionMap; - - /** Virtual method for getting a region most suitable for the - passed in bounds. Can be overridden by subclasses. - */ - virtual Region* getRegion(const AxisAlignedBox& bounds, bool autoCreate); - /** Get the region within which a point lies */ - virtual Region* getRegion(const Vector3& point, bool autoCreate); - /** Get the region using indexes */ - virtual Region* getRegion(ushort x, ushort y, ushort z, bool autoCreate); - /** Get the region using a packed index, returns null if it doesn't exist. */ - virtual Region* getRegion(uint32 index); - /** Get the region indexes for a point. - */ - virtual void getRegionIndexes(const Vector3& point, - ushort& x, ushort& y, ushort& z); - /** Pack 3 indexes into a single index value - */ - virtual uint32 packIndex(ushort x, ushort y, ushort z); - /** Get the volume intersection for an indexed region with some bounds. - */ - virtual Real getVolumeIntersection(const AxisAlignedBox& box, - ushort x, ushort y, ushort z); - /** Get the bounds of an indexed region. - */ - virtual AxisAlignedBox getRegionBounds(ushort x, ushort y, ushort z); - /** Get the centre of an indexed region. - */ - virtual Vector3 getRegionCentre(ushort x, ushort y, ushort z); - /** Calculate world bounds from a set of vertex data. */ - virtual AxisAlignedBox calculateBounds(VertexData* vertexData, - const Vector3& position, const Quaternion& orientation, - const Vector3& scale); - /** Look up or calculate the geometry data to use for this SubMesh */ - SubMeshLodGeometryLinkList* determineGeometry(SubMesh* sm); - /** Split some shared geometry into dedicated geometry. */ - void splitGeometry(VertexData* vd, IndexData* id, - SubMeshLodGeometryLink* targetGeomLink); - - typedef std::map IndexRemap; - /** Method for figuring out which vertices are used by an index buffer - and calculating a remap lookup for a vertex buffer just containing - those vertices. - */ - template - void buildIndexRemap(T* pBuffer, size_t numIndexes, IndexRemap& remap) - { - remap.clear(); - for (size_t i = 0; i < numIndexes; ++i) - { - // use insert since duplicates are silently discarded - remap.emplace(*pBuffer++, remap.size()); - // this will have mapped oldindex -> new index IF oldindex - // wasn't already there - } - } - /** Method for altering indexes based on a remap. */ - template - void remapIndexes(T* src, T* dst, const IndexRemap& remap, - size_t numIndexes) - { - for (size_t i = 0; i < numIndexes; ++i) - { - // look up original and map to target - IndexRemap::const_iterator ix = remap.find(*src++); - assert(ix != remap.end()); - *dst++ = static_cast(ix->second); - } - } - - public: - /// Constructor; do not use directly (@see SceneManager::createStaticGeometry) - StaticGeometry(SceneManager* owner, const String& name); - /// Destructor - virtual ~StaticGeometry(); - - /// Get the name of this object - const String& getName(void) const { return mName; } - /** Adds an Entity to the static geometry. - - This method takes an existing Entity and adds its details to the - list of elements to include when building. Note that the Entity - itself is not copied or referenced in this method; an Entity is - passed simply so that you can change the materials of attached - SubEntity objects if you want. You can add the same Entity - instance multiple times with different material settings - completely safely, and destroy the Entity before destroying - this StaticGeometry if you like. The Entity passed in is simply - used as a definition. - @note Must be called before 'build'. - @param ent The Entity to use as a definition (the Mesh and Materials - referenced will be recorded for the build call). - @param position The world position at which to add this Entity - @param orientation The world orientation at which to add this Entity - @param scale The scale at which to add this entity - */ - virtual void addEntity(Entity* ent, const Vector3& position, - const Quaternion& orientation = Quaternion::IDENTITY, - const Vector3& scale = Vector3::UNIT_SCALE); - - /** Adds all the Entity objects attached to a SceneNode and all it's - children to the static geometry. - - This method performs just like addEntity, except it adds all the - entities attached to an entire sub-tree to the geometry. - The position / orientation / scale parameters are taken from the - node structure instead of being specified manually. - @note - The SceneNode you pass in will not be automatically detached from - it's parent, so if you have this node already attached to the scene - graph, you will need to remove it if you wish to avoid the overhead - of rendering both the original objects and their new static - versions! We don't do this for you in case you are preparing this - in advance and so don't want the originals detached yet. - @note Must be called before 'build'. - @param node Pointer to the node to use to provide a set of Entity - templates - */ - virtual void addSceneNode(const SceneNode* node); - - /** Build the geometry. - - Based on all the entities which have been added, and the batching - options which have been set, this method constructs the batched - geometry structures required. The batches are added to the scene - and will be rendered unless you specifically hide them. - @note - Once you have called this method, you can no longer add any more - entities. - */ - virtual void build(void); - - /** Destroys all the built geometry state (reverse of build). - - You can call build() again after this and it will pick up all the - same entities / nodes you queued last time. - */ - void destroy(void); - - /** Clears any of the entities / nodes added to this geometry and - destroys anything which has already been built. - */ - void reset(void); - - /** Sets the distance at which batches are no longer rendered. - - This lets you turn off batches at a given distance. This can be - useful for things like detail meshes (grass, foliage etc) and could - be combined with a shader which fades the geometry out beforehand - to lessen the effect. - @param dist Distance beyond which the batches will not be rendered - (the default is 0, which means batches are always rendered). - */ - virtual void setRenderingDistance(Real dist) { - mUpperDistance = dist; - mSquaredUpperDistance = mUpperDistance * mUpperDistance; - } - - /** Gets the distance at which batches are no longer rendered. */ - virtual Real getRenderingDistance(void) const { return mUpperDistance; } - - /** Gets the squared distance at which batches are no longer rendered. */ - virtual Real getSquaredRenderingDistance(void) const - { return mSquaredUpperDistance; } - - /** Hides or shows all the batches. */ - virtual void setVisible(bool visible); - - /** Are the batches visible? */ - virtual bool isVisible(void) const { return mVisible; } - - /** Sets whether this geometry should cast shadows. - - No matter what the settings on the original entities, - the StaticGeometry class defaults to not casting shadows. - This is because, being static, unless you have moving lights - you'd be better to use precalculated shadows of some sort. - However, if you need them, you can enable them using this - method. If the SceneManager is set up to use stencil shadows, - edge lists will be copied from the underlying meshes on build. - It is essential that all meshes support stencil shadows in this - case. - @note If you intend to use stencil shadows, you must set this to - true before calling 'build' as well as making sure you set the - scene's shadow type (that should always be the first thing you do - anyway). You can turn shadows off temporarily but they can never - be turned on if they were not at the time of the build. - */ - virtual void setCastShadows(bool castShadows); - /// Will the geometry from this object cast shadows? - virtual bool getCastShadows(void) { return mCastShadows; } - - /** Sets the size of a single region of geometry. - - This method allows you to configure the physical world size of - each region, so you can balance culling against batch size. Entities - will be fitted within the batch they most closely fit, and the - eventual bounds of each batch may well be slightly larger than this - if they overlap a little. The default is Vector3(1000, 1000, 1000). - @note Must be called before 'build'. - @param size Vector3 expressing the 3D size of each region. - */ - virtual void setRegionDimensions(const Vector3& size) { - mRegionDimensions = size; - mHalfRegionDimensions = size * 0.5; - } - /** Gets the size of a single batch of geometry. */ - virtual const Vector3& getRegionDimensions(void) const { return mRegionDimensions; } - /** Sets the origin of the geometry. - - This method allows you to configure the world centre of the geometry, - thus the place which all regions surround. You probably don't need - to mess with this unless you have a seriously large world, since the - default set up can handle an area 1024 * mRegionDimensions, and - the sparseness of population is no issue when it comes to rendering. - The default is Vector3(0,0,0). - @note Must be called before 'build'. - @param origin Vector3 expressing the 3D origin of the geometry. - */ - virtual void setOrigin(const Vector3& origin) { mOrigin = origin; } - /** Gets the origin of this geometry. */ - virtual const Vector3& getOrigin(void) const { return mOrigin; } - - /// Sets the visibility flags of all the regions at once - void setVisibilityFlags(uint32 flags); - /// Returns the visibility flags of the regions - uint32 getVisibilityFlags() const; - - /** Sets the render queue group this object will be rendered through. - - Render queues are grouped to allow you to more tightly control the ordering - of rendered objects. If you do not call this method, all objects default - to the default queue (RenderQueue::getDefaultQueueGroup), which is fine for - most objects. You may want to alter this if you want to perform more complex - rendering. - @par - See RenderQueue for more details. - @param queueID Enumerated value of the queue group to use. - */ - virtual void setRenderQueueGroup(uint8 queueID); - - /** Gets the queue group for this entity, see setRenderQueueGroup for full details. */ - virtual uint8 getRenderQueueGroup(void) const; - /// @copydoc MovableObject::visitRenderables - void visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables = false); - - /// Iterator for iterating over contained regions - typedef MapIterator RegionIterator; - /// Get an list of the regions in this geometry - const RegionMap& getRegions() const { return mRegionMap; } - /// @deprecated use getRegions() - OGRE_DEPRECATED RegionIterator getRegionIterator(void); - - /** Dump the contents of this StaticGeometry for diagnostic - purposes. - */ - _OgreExport friend std::ostream& operator<<(std::ostream& o, const StaticGeometry& g); - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreStdHeaders.h b/OgreMain/include/OgreStdHeaders.h deleted file mode 100644 index 94ede558557..00000000000 --- a/OgreMain/include/OgreStdHeaders.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef __StdHeaders_H__ -#define __StdHeaders_H__ - -#include -#include -#include -#include -#include -#include -#include - -// STL containers -#include -#include -#include -#include -#include -#include - -// STL algorithms & functions -#include - -// C++ Stream stuff -#include -#include - -#include - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT -# undef min -# undef max -#endif - -#if OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN -# include -#endif - -#endif diff --git a/OgreMain/include/OgreStreamSerialiser.h b/OgreMain/include/OgreStreamSerialiser.h deleted file mode 100644 index 695ed576351..00000000000 --- a/OgreMain/include/OgreStreamSerialiser.h +++ /dev/null @@ -1,398 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __StreamSerialiser_H__ -#define __StreamSerialiser_H__ - -#include "OgrePrerequisites.h" -#include "OgreCommon.h" -#include "OgreDataStream.h" -#include "OgreHeaderPrefix.h" - -#include - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - - /** Utility class providing helper methods for reading / writing - structured data held in a DataStream. - - The structure of a file read / written by this class is a series of - 'chunks'. A chunk-based format has the advantage of being extensible later, - and it's robust, in that a reader can skip chunks that they are not - able (or willing) to process. - @par - Chunks are contained serially in the file, but they can also be - nested in order both to provide context, and to group chunks together for - potential skipping. - @par - The data format of a chunk is as follows: - -# Chunk ID (32-bit uint). This can be any number unique in a context, except the numbers 0x0000, 0x0001 and 0x1000, which are reserved for Ogre's use - -# Chunk version (16-bit uint). Chunks can change over time so this version number reflects that - -# Length (32-bit uint). The length of the chunk data section, including nested chunks. Note that - this length excludes this header, but includes the header of any nested chunks. - -# Checksum (32-bit uint). Checksum value generated from the above - basically lets us check this is a valid chunk. - -# Chunk data - The 'Chunk data' section will contain chunk-specific data, which may include - other nested chunks. - */ - class _OgreExport StreamSerialiser : public StreamAlloc - { - public: - /// The endianness of files - enum Endian - { - /// Automatically determine endianness - ENDIAN_AUTO, - /// Use big endian (0x1000 is serialised as 0x10 0x00) - ENDIAN_BIG, - /// Use little endian (0x1000 is serialised as 0x00 0x10) - ENDIAN_LITTLE - }; - - /// The storage format of Real values - enum RealStorageFormat - { - /// Real is stored as float, reducing precision if you're using OGRE_DOUBLE_PRECISION - REAL_FLOAT, - /// Real as stored as double, not useful unless you're using OGRE_DOUBLE_PRECISION - REAL_DOUBLE - }; - - - /// Definition of a chunk of data in a file - struct Chunk : public StreamAlloc - { - /// Identifier of the chunk (for example from makeIdentifier) (stored) - uint32 id; - /// Version of the chunk (stored) - uint16 version; - /// Length of the chunk data in bytes, excluding the header of this chunk (stored) - uint32 length; - /// Location of the chunk (header) in bytes from the start of a stream (derived) - uint32 offset; - - Chunk() : id(0), version(1), length(0), offset(0) {} - }; - - /** Constructor. - @param stream The stream on which you will read / write data. - @param endianMode The endian mode in which to read / writedata. If left at - the default, when writing the endian mode will be the native platform mode, - and when reading it's expected that the first chunk encountered will be - the header chunk, which will determine the endian mode. - @param autoHeader If true, the first write or read to this stream will - automatically read / write the header too. This is required if you - set endianMode to ENDIAN_AUTO, but if you manually set the endian mode, - then you can skip writing / reading the header if you wish, if for example - this stream is midway through a file which has already included header - information. - @param realFormat Set the format you want to write reals in. Only useful for files that - you're writing (since when reading this is picked up from the file), - and can only be changed if autoHeader is true, since real format is stored in the header. - Defaults to float unless you're using OGRE_DOUBLE_PRECISION. - */ - StreamSerialiser(const DataStreamPtr& stream, Endian endianMode = ENDIAN_AUTO, - bool autoHeader = true, -#if OGRE_DOUBLE_PRECISION - RealStorageFormat realFormat = REAL_DOUBLE -#else - RealStorageFormat realFormat = REAL_FLOAT -#endif - ); - virtual ~StreamSerialiser(); - - /** Get the endian mode. - - If the result is ENDIAN_AUTO, this mode will change when the first piece of - data is read / written. - */ - virtual Endian getEndian() const { return mEndian; } - - /** Pack a 4-character code into a 32-bit identifier. - - You can use this to generate id's for your chunks based on friendlier - 4-character codes rather than assigning numerical IDs, if you like. - @param code String to pack - must be 4 characters and '\0' - */ - static uint32 makeIdentifier(const char (&code)[5]); - - /** Report the current depth of the chunk nesting, whether reading or writing. - - Returns how many levels of nested chunks are currently being processed, - either writing or reading. In order to tidily finish, you must call - read/writeChunkEnd this many times. - */ - size_t getCurrentChunkDepth() const { return mChunkStack.size(); } - - /** Get the ID of the chunk that's currently being read/written, if any. - @return The id of the current chunk being read / written (at the tightest - level of nesting), or zero if no chunk is being processed. - */ - uint32 getCurrentChunkID() const; - - /** Get the current byte position relative to the start of the data section - of the last chunk that was read or written. - @return the offset. Note that a return value of 0 means that either the - position is at the start of the chunk data section (ie right after the - header), or that no chunk is currently active. Use getCurrentChunkID - or getCurrentChunkDepth to determine if a chunk is active. - */ - size_t getOffsetFromChunkStart() const; - - /** Reads the start of the next chunk in the file. - - Files are serialised in a chunk-based manner, meaning that each section - of data is prepended by a chunk header. After reading this chunk header, - the next set of data is available directly afterwards. - @note - When you have finished with this chunk, you should call readChunkEnd. - This will perform a bit of validation and clear the chunk from - the stack. - @return The Chunk that comes next - */ - virtual const Chunk* readChunkBegin(); - - /** Reads the start of the next chunk so long as it's of a given ID and version. - - This method operates like readChunkBegin, except it checks the ID and - version. - @param id The ID you're expecting. If the next chunk isn't of this ID, then - the chunk read is undone and the method returns null. - @param maxVersion The maximum version you're able to process. If the ID is correct - but the version exceeds what is passed in here, the chunk is skipped over, - the problem logged and null is returned. - @param msg Descriptive text added to the log if versions are not compatible - @return The chunk if it passes the validation. - */ - virtual const Chunk* readChunkBegin(uint32 id, uint16 maxVersion, const String& msg = BLANKSTRING); - - /** Call this to 'rewind' the stream to just before the start of the current - chunk. - - The most common case of wanting to use this is if you'd calledReadChunkBegin(), - but the chunk you read wasn't one you wanted to process, and rather than - skipping over it (which readChunkEnd() would do), you want to backtrack - and give something else an opportunity to read it. - @param id The id of the chunk that you were reading (for validation purposes) - */ - virtual void undoReadChunk(uint32 id); - - /** Call this to 'peek' at the next chunk ID without permanently moving the stream pointer. */ - virtual uint32 peekNextChunkID(); - - /** Finish the reading of a chunk. - - You can call this method at any point after calling readChunkBegin, even - if you didn't read all the rest of the data in the chunk. If you did - not read to the end of a chunk, this method will automatically skip - over the remainder of the chunk and position the stream just after it. - @param id The id of the chunk that you were reading (for validation purposes) - */ - virtual void readChunkEnd(uint32 id); - - /** Return whether the current data pointer is at the end of the current chunk. - @param id The id of the chunk that you were reading (for validation purposes) - */ - virtual bool isEndOfChunk(uint32 id); - - /// Reports whether the stream is at the end of file - virtual bool eof() const; - - /** Get the definition of the current chunk being read (if any). */ - virtual const Chunk* getCurrentChunk() const; - - /** Begin writing a new chunk. - - This starts the process of writing a new chunk to the stream. This will - write the chunk header for you, and store a pointer so that the - class can automatically go back and fill in the size for you later - should you need it to. If you have already begun a chunk without ending - it, then this method will start a nested chunk within it. Once written, - you can then start writing chunk-specific data into your stream. - @note If this is the first chunk in the file - @param id The identifier of the new chunk. Any value that's unique in the - file context is valid, except for the numbers 0x0001 and 0x1000 which are reserved - for internal header identification use. - @param version The version of the chunk you're writing - */ - virtual void writeChunkBegin(uint32 id, uint16 version = 1); - /** End writing a chunk. - @param id The identifier of the chunk - this is really just a safety check, - since you can only end the chunk you most recently started. - */ - virtual void writeChunkEnd(uint32 id); - - /** Write arbitrary data to a stream. - @param buf Pointer to bytes - @param size The size of each element to write; each will be endian-flipped if - necessary - @param count The number of elements to write - */ - virtual void writeData(const void* buf, size_t size, size_t count); - - /** Catch-all method to write primitive types. */ - template - void write(const T* pT, size_t count = 1) - { - writeData(pT, sizeof(T), count); - } - - // Special-case Real since we need to deal with single/double precision - virtual void write(const Real* val, size_t count = 1); - - virtual void write(const Vector2* vec, size_t count = 1); - virtual void write(const Vector3* vec, size_t count = 1); - virtual void write(const Vector4* vec, size_t count = 1); - virtual void write(const Quaternion* q, size_t count = 1); - virtual void write(const Matrix3* m, size_t count = 1); - virtual void write(const Matrix4* m, size_t count = 1); - virtual void write(const String* string); - virtual void write(const AxisAlignedBox* aabb, size_t count = 1); - virtual void write(const Sphere* sphere, size_t count = 1); - virtual void write(const Plane* plane, size_t count = 1); - virtual void write(const Ray* ray, size_t count = 1); - virtual void write(const Radian* angle, size_t count = 1); - virtual void write(const Node* node, size_t count = 1); - virtual void write(const bool* boolean, size_t count = 1); - - - /** Read arbitrary data from a stream. - @param buf Pointer to bytes - @param size The size of each element to read; each will be endian-flipped if - necessary - @param count The number of elements to read - */ - virtual void readData(void* buf, size_t size, size_t count); - - /** Catch-all method to read primitive types. */ - template - void read(T* pT, size_t count = 1) - { - readData(pT, sizeof(T), count); - } - - // Special case Real, single/double-precision issues - virtual void read(Real* val, size_t count = 1); - - /// read a Vector3 - virtual void read(Vector2* vec, size_t count = 1); - virtual void read(Vector3* vec, size_t count = 1); - virtual void read(Vector4* vec, size_t count = 1); - virtual void read(Quaternion* q, size_t count = 1); - virtual void read(Matrix3* m, size_t count = 1); - virtual void read(Matrix4* m, size_t count = 1); - virtual void read(String* string); - virtual void read(AxisAlignedBox* aabb, size_t count = 1); - virtual void read(Sphere* sphere, size_t count = 1); - virtual void read(Plane* plane, size_t count = 1); - virtual void read(Ray* ray, size_t count = 1); - virtual void read(Radian* angle, size_t count = 1); - virtual void read(Node* node, size_t count = 1); - virtual void read(bool* val, size_t count = 1); - - /** Start (un)compressing data - @param avail_in Available bytes for uncompressing - */ - virtual void startDeflate(size_t avail_in = 0); - /** Stop (un)compressing data - */ - virtual void stopDeflate(); - protected: - DataStreamPtr mStream; - DataStreamPtr mOriginalStream; - Endian mEndian; - bool mFlipEndian; - bool mReadWriteHeader; - RealStorageFormat mRealFormat; - typedef std::deque ChunkStack; - /// Current list of open chunks - ChunkStack mChunkStack; - - static uint32 HEADER_ID; - static uint32 REVERSE_HEADER_ID; - static uint32 CHUNK_HEADER_SIZE; - - virtual Chunk* readChunkImpl(); - virtual void writeChunkImpl(uint32 id, uint16 version); - virtual void readHeader(); - virtual void writeHeader(); - virtual uint32 calculateChecksum(Chunk* c); - virtual void checkStream(bool failOnEof = false, - bool validateReadable = false, bool validateWriteable = false) const; - - - virtual void determineEndianness(); - virtual Chunk* popChunk(uint id); - - virtual void writeFloatsAsDoubles(const float* val, size_t count); - virtual void writeDoublesAsFloats(const double* val, size_t count); - virtual void readFloatsAsDoubles(double* val, size_t count); - virtual void readDoublesAsFloats(float* val, size_t count); - template - void writeConverted(const T* src, U typeToWrite, size_t count) - { - U* tmp = OGRE_ALLOC_T(U, count, MEMCATEGORY_GENERAL); - U* pDst = tmp; - const T* pSrc = src; - for (size_t i = 0; i < count; ++i) - *pDst++ = static_cast(*pSrc++); - - writeData(tmp, sizeof(U), count); - - OGRE_FREE(tmp, MEMCATEGORY_GENERAL); - } - template - void readConverted(T* dst, U typeToRead, size_t count) - { - U* tmp = OGRE_ALLOC_T(U, count, MEMCATEGORY_GENERAL); - readData(tmp, sizeof(U), count); - - T* pDst = dst; - const U* pSrc = tmp; - for (size_t i = 0; i < count; ++i) - *pDst++ = static_cast(*pSrc++); - - - OGRE_FREE(tmp, MEMCATEGORY_GENERAL); - } - - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreString.h b/OgreMain/include/OgreString.h deleted file mode 100644 index 0dcd65733a2..00000000000 --- a/OgreMain/include/OgreString.h +++ /dev/null @@ -1,193 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _String_H__ -#define _String_H__ - -#include "OgrePrerequisites.h" -#include "OgreHeaderPrefix.h" - -#if OGRE_COMPILER == OGRE_COMPILER_GNUC || OGRE_COMPILER == OGRE_COMPILER_CLANG -#define OGRE_FORMAT_PRINTF(string_idx, first_to_check) __attribute__ ((format (printf, string_idx, first_to_check))) -#else -#define OGRE_FORMAT_PRINTF(A, B) -#endif - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - - /** Utility class for manipulating Strings. */ - class _OgreExport StringUtil - { - public: - OGRE_DEPRECATED static const String& BLANK; //!< @deprecated use Ogre::BLANKSTRING instead - OGRE_DEPRECATED typedef StringStream StrStreamType; //!< @deprecated use Ogre::StringStream instead - - /** Removes any whitespace characters, be it standard space or - TABs and so on. - - The user may specify whether they want to trim only the - beginning or the end of the String ( the default action is - to trim both). - */ - static void trim( String& str, bool left = true, bool right = true ); - - /** Returns a StringVector that contains all the substrings delimited - by the characters in the passed delims argument. - @param str - @param - delims A list of delimiter characters to split by - @param - maxSplits The maximum number of splits to perform (0 for unlimited splits). If this - parameters is > 0, the splitting process will stop after this many splits, left to right. - @param - preserveDelims Flag to determine if delimiters should be saved as substrings - */ - static std::vector split( const String& str, const String& delims = "\t\n ", unsigned int maxSplits = 0, bool preserveDelims = false); - - /** Returns a StringVector that contains all the substrings delimited - by the characters in the passed delims argument, - or in the doubleDelims argument, which is used to include (normal) - delimiters in the tokenised string. For example, "strings like this". - @param str - @param - delims A list of delimiter characters to split by - @param - doubleDelims A list of double delimiters characters to tokenise by - @param - maxSplits The maximum number of splits to perform (0 for unlimited splits). If this - parameters is > 0, the splitting process will stop after this many splits, left to right. - */ - static std::vector tokenise( const String& str, const String& delims = "\t\n ", const String& doubleDelims = "\"", unsigned int maxSplits = 0); - - /** Lower-cases all the characters in the string. - */ - static void toLowerCase( String& str ); - - /** Upper-cases all the characters in the string. - */ - static void toUpperCase( String& str ); - - /** Upper-cases the first letter of each word. - */ - static void toTitleCase( String& str ); - - - /** Returns whether the string begins with the pattern passed in. - @param str - @param pattern The pattern to compare with. - @param lowerCase If true, the start of the string will be lower cased before - comparison, pattern should also be in lower case. - */ - static bool startsWith(const String& str, const String& pattern, bool lowerCase = true); - - /** Returns whether the string ends with the pattern passed in. - @param str - @param pattern The pattern to compare with. - @param lowerCase If true, the end of the string will be lower cased before - comparison, pattern should also be in lower case. - */ - static bool endsWith(const String& str, const String& pattern, bool lowerCase = true); - - /** Method for standardising paths - use forward slashes only, end with slash. - */ - static String standardisePath( const String &init); - /** Returns a normalized version of a file path - This method can be used to make file path strings which point to the same directory - but have different texts to be normalized to the same text. The function: - - Transforms all backward slashes to forward slashes. - - Removes repeating slashes. - - Removes initial slashes from the beginning of the path. - - Removes ".\" and "..\" meta directories. - - Sets all characters to lowercase (if requested) - @param init The file path to normalize. - @param makeLowerCase If true, transforms all characters in the string to lowercase. - */ - static String normalizeFilePath(const String& init, bool makeLowerCase = false); - - - /** Method for splitting a fully qualified filename into the base name - and path. - - Path is standardised as in standardisePath - */ - static void splitFilename(const String& qualifiedName, - String& outBasename, String& outPath); - - /** Method for splitting a fully qualified filename into the base name, - extension and path. - - Path is standardised as in standardisePath - */ - static void splitFullFilename(const Ogre::String& qualifiedName, - Ogre::String& outBasename, Ogre::String& outExtention, - Ogre::String& outPath); - - /** Method for splitting a filename into the base name - and extension. - */ - static void splitBaseFilename(const Ogre::String& fullName, - Ogre::String& outBasename, Ogre::String& outExtention); - - - /** Simple pattern-matching routine allowing a wildcard pattern. - @param str String to test - @param pattern Pattern to match against; can include simple '*' wildcards - @param caseSensitive Whether the match is case sensitive or not - */ - static bool match(const String& str, const String& pattern, bool caseSensitive = true); - - - /** Replace all instances of a sub-string with a another sub-string. - @param source Source string - @param replaceWhat Sub-string to find and replace - @param replaceWithWhat Sub-string to replace with (the new sub-string) - @return An updated string with the sub-string replaced - */ - static const String replaceAll(const String& source, const String& replaceWhat, const String& replaceWithWhat); - - /** create a string from a printf expression - * - * @note this function - like printf - uses a locale dependent decimal point - */ - static String format(const char* fmt, ...) OGRE_FORMAT_PRINTF(1, 2); - }; - - typedef ::std::hash< String > _StringHash; - /** @} */ - /** @} */ - -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif // _String_H__ diff --git a/OgreMain/include/OgreStringConverter.h b/OgreMain/include/OgreStringConverter.h deleted file mode 100644 index 4a5e402d6c9..00000000000 --- a/OgreMain/include/OgreStringConverter.h +++ /dev/null @@ -1,362 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __StringConverter_H__ -#define __StringConverter_H__ - -#include "OgreCommon.h" -#include "OgrePrerequisites.h" -#include "OgreStringVector.h" -#include "OgreColourValue.h" -#include "OgreMatrix4.h" -#include "OgreVector.h" - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT -# define locale_t _locale_t -#elif OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN -# define locale_t int -#endif - -// If compiling with make on macOS, these headers need to be included to get -// definitions of locale_t, strtod_l, etc... -// See: http://www.unix.com/man-page/osx/3/strtod_l/ -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE -# include -# include -#endif - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - /** Class for converting the core Ogre data types to/from Strings. - - The code for converting values to and from strings is here as a separate - class to avoid coupling String to other datatypes (and vice-versa) which reduces - compilation dependency: important given how often the core types are used. - @par - This class is mainly used for parsing settings in text files. External applications - can also use it to interface with classes which use the StringInterface template - class. - @par - The String formats of each of the major types is listed with the methods. The basic types - like int and Real just use the underlying C runtime library atof and atoi family methods, - however custom types like Vector3, ColourValue and Matrix4 are also supported by this class - using custom formats. - */ - class _OgreExport StringConverter - { - public: - static String toString(int32 val) { return std::to_string(val); }; - static String toString(uint32 val) { return std::to_string(val); }; - static String toString(unsigned long val) { return std::to_string(val); }; - static String toString(unsigned long long val) { return std::to_string(val); }; - static String toString(long val) { return std::to_string(val); }; - - /** Converts a float to a String. */ - static String toString(float val, unsigned short precision = 6, - unsigned short width = 0, char fill = ' ', - std::ios::fmtflags flags = std::ios::fmtflags(0)); - - /** Converts a double to a String. */ - static String toString(double val, unsigned short precision = 6, - unsigned short width = 0, char fill = ' ', - std::ios::fmtflags flags = std::ios::fmtflags(0)); - - /** Converts a Radian to a String. */ - static String toString(Radian val, unsigned short precision = 6, - unsigned short width = 0, char fill = ' ', - std::ios::fmtflags flags = std::ios::fmtflags(0)) - { - return toString(val.valueAngleUnits(), precision, width, fill, flags); - } - /** Converts a Degree to a String. */ - static String toString(Degree val, unsigned short precision = 6, - unsigned short width = 0, char fill = ' ', - std::ios::fmtflags flags = std::ios::fmtflags(0)) - { - return toString(val.valueAngleUnits(), precision, width, fill, flags); - } - /// @deprecated use StringUtil::format - OGRE_DEPRECATED static String toString(int32 val, unsigned short width, - char fill = ' ', - std::ios::fmtflags flags = std::ios::fmtflags(0)); - /// @deprecated use StringUtil::format - OGRE_DEPRECATED static String toString(uint32 val, unsigned short width, - char fill = ' ', - std::ios::fmtflags flags = std::ios::fmtflags(0)); - // provide both long long and long to catch size_t on all platforms - /// @deprecated use StringUtil::format - OGRE_DEPRECATED static String toString(unsigned long val, - unsigned short width, char fill = ' ', - std::ios::fmtflags flags = std::ios::fmtflags(0)); - /// @deprecated use StringUtil::format - OGRE_DEPRECATED static String toString(unsigned long long val, - unsigned short width, char fill = ' ', - std::ios::fmtflags flags = std::ios::fmtflags(0)); - - /// @deprecated use StringUtil::format - OGRE_DEPRECATED static String toString(long val, - unsigned short width, char fill = ' ', - std::ios::fmtflags flags = std::ios::fmtflags(0)); - - /** Converts a boolean to a String. - @param val - @param yesNo If set to true, result is 'yes' or 'no' instead of 'true' or 'false' - */ - static String toString(bool val, bool yesNo = false); - /** Converts a Vector2 to a String. - - Format is "x y" (i.e. 2x Real values, space delimited) - */ - static String toString(const Vector2& val); - /** Converts a Vector3 to a String. - - Format is "x y z" (i.e. 3x Real values, space delimited) - */ - static String toString(const Vector3& val); - /** Converts a Vector4 to a String. - - Format is "x y z w" (i.e. 4x Real values, space delimited) - */ - static String toString(const Vector4& val); - /** Converts a Matrix3 to a String. - - Format is "00 01 02 10 11 12 20 21 22" where '01' means row 0 column 1 etc. - */ - static String toString(const Matrix3& val); - /** Converts a Matrix4 to a String. - - Format is "00 01 02 03 10 11 12 13 20 21 22 23 30 31 32 33" where - '01' means row 0 column 1 etc. - */ - static String toString(const Matrix4& val); - /** Converts a Quaternion to a String. - - Format is "w x y z" (i.e. 4x Real values, space delimited) - */ - static String toString(const Quaternion& val); - /** Converts a ColourValue to a String. - - Format is "r g b a" (i.e. 4x Real values, space delimited). - */ - static String toString(const ColourValue& val); - /** Converts a StringVector to a string. - - Strings must not contain spaces since space is used as a delimiter in - the output. - */ - static String toString(const StringVector& val); - - /** Converts a String to a basic value type - @return whether the conversion was successful - */ - static bool parse(const String& str, ColourValue& v); - static bool parse(const String& str, Quaternion& v); - static bool parse(const String& str, Matrix4& v); - static bool parse(const String& str, Matrix3& v); - static bool parse(const String& str, Vector4& v); - static bool parse(const String& str, Vector3& v); - static bool parse(const String& str, Vector2& v); - static bool parse(const String& str, int32& v); - static bool parse(const String& str, uint32& v); - static bool parse(const String& str, int64& v); - // provide both long long and long to catch size_t on all platforms - static bool parse(const String& str, unsigned long& v); - static bool parse(const String& str, unsigned long long& v); - static bool parse(const String& str, bool& v); - static bool parse(const String& str, double& v); - static bool parse(const String& str, float& v); - - /** Converts a String to a Real. - @return - 0.0 if the value could not be parsed, otherwise the Real version of the String. - */ - static Real parseReal(const String& val, Real defaultValue = 0) - { - Real ret; - return parse(val, ret) ? ret : defaultValue; - } - /** Converts a String to a Angle. - @return - 0.0 if the value could not be parsed, otherwise the Angle version of the String. - */ - static Radian parseAngle(const String& val, Radian defaultValue = Radian(0)) { - return Angle(parseReal(val, defaultValue.valueRadians())); - } - /** Converts a String to a whole number. - @return - 0.0 if the value could not be parsed, otherwise the numeric version of the String. - */ - static int32 parseInt(const String& val, int32 defaultValue = 0) - { - int32 ret; - return parse(val, ret) ? ret : defaultValue; - } - /** Converts a String to a whole number. - @return - 0.0 if the value could not be parsed, otherwise the numeric version of the String. - */ - static uint32 parseUnsignedInt(const String& val, uint32 defaultValue = 0) - { - uint32 ret; - return parse(val, ret) ? ret : defaultValue; - } - /// @deprecated - OGRE_DEPRECATED static int64 parseLong(const String& val, int64 defaultValue = 0) - { - int64 ret; - return parse(val, ret) ? ret : defaultValue; - } - /// @deprecated - OGRE_DEPRECATED static uint64 parseUnsignedLong(const String& val, uint64 defaultValue = 0) - { - uint64 ret; - return parse(val, ret) ? ret : defaultValue; - } - /** Converts a String to size_t. - @return - defaultValue if the value could not be parsed, otherwise the numeric version of the String. - */ - static size_t parseSizeT(const String& val, size_t defaultValue = 0) - { - size_t ret; - return parse(val, ret) ? ret : defaultValue; - } - /** Converts a String to a boolean. - - Returns true if case-insensitive match of the start of the string - matches "true", "yes", "1", or "on", false if "false", "no", "0" - or "off". - */ - static bool parseBool(const String& val, bool defaultValue = 0) - { - bool ret; - return parse(val, ret) ? ret : defaultValue; - } - /** Parses a Vector2 out of a String. - - Format is "x y" ie. 2 Real components, space delimited. Failure to parse returns - Vector2::ZERO. - */ - static Vector2 parseVector2(const String& val, const Vector2& defaultValue = Vector2::ZERO) - { - Vector2 ret; - return parse(val, ret) ? ret : defaultValue; - } - /** Parses a Vector3 out of a String. - - Format is "x y z" ie. 3 Real components, space delimited. Failure to parse returns - Vector3::ZERO. - */ - static Vector3 parseVector3(const String& val, const Vector3& defaultValue = Vector3::ZERO) - { - Vector3 ret; - return parse(val, ret) ? ret : defaultValue; - } - /** Parses a Vector4 out of a String. - - Format is "x y z w" ie. 4 Real components, space delimited. Failure to parse returns - Vector4::ZERO. - */ - static Vector4 parseVector4(const String& val, const Vector4& defaultValue = Vector4::ZERO) - { - Vector4 ret; - return parse(val, ret) ? ret : defaultValue; - } - /** Parses a Matrix3 out of a String. - - Format is "00 01 02 10 11 12 20 21 22" where '01' means row 0 column 1 etc. - Failure to parse returns Matrix3::IDENTITY. - */ - static Matrix3 parseMatrix3(const String& val, const Matrix3& defaultValue = Matrix3::IDENTITY) - { - Matrix3 ret; - return parse(val, ret) ? ret : defaultValue; - } - /** Parses a Matrix4 out of a String. - - Format is "00 01 02 03 10 11 12 13 20 21 22 23 30 31 32 33" where - '01' means row 0 column 1 etc. Failure to parse returns Matrix4::IDENTITY. - */ - static Matrix4 parseMatrix4(const String& val, const Matrix4& defaultValue = Matrix4::IDENTITY) - { - Matrix4 ret; - return parse(val, ret) ? ret : defaultValue; - } - /** Parses a Quaternion out of a String. - - Format is "w x y z" (i.e. 4x Real values, space delimited). - Failure to parse returns Quaternion::IDENTITY. - */ - static Quaternion parseQuaternion(const String& val, const Quaternion& defaultValue = Quaternion::IDENTITY) - { - Quaternion ret; - return parse(val, ret) ? ret : defaultValue; - } - /** Parses a ColourValue out of a String. - - Format is "r g b a" (i.e. 4x Real values, space delimited), or "r g b" which implies - an alpha value of 1.0 (opaque). Failure to parse returns ColourValue::Black. - */ - static ColourValue parseColourValue(const String& val, const ColourValue& defaultValue = ColourValue::Black) - { - ColourValue ret; - return parse(val, ret) ? ret : defaultValue; - } - - /// @deprecated use StringUtil::split - OGRE_DEPRECATED static StringVector parseStringVector(const String& val) { return StringUtil::split(val); } - /** Checks the String is a valid number value. */ - static bool isNumber(const String& val); - - static locale_t _numLocale; - private: - template - static String _toString(T val, uint16 width, char fill, std::ios::fmtflags flags); - }; - - inline String to_string(const Quaternion& v) { return StringConverter::toString(v); } - inline String to_string(const ColourValue& v) { return StringConverter::toString(v); } - inline String to_string(const Vector2& v) { return StringConverter::toString(v); } - inline String to_string(const Vector3& v) { return StringConverter::toString(v); } - inline String to_string(const Vector4& v) { return StringConverter::toString(v); } - inline String to_string(const Matrix3& v) { return StringConverter::toString(v); } - inline String to_string(const Matrix4& v) { return StringConverter::toString(v); } - /** @} */ - /** @} */ -} - - - -#endif - diff --git a/OgreMain/include/OgreStringInterface.h b/OgreMain/include/OgreStringInterface.h deleted file mode 100644 index 5484fcec85e..00000000000 --- a/OgreMain/include/OgreStringInterface.h +++ /dev/null @@ -1,283 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __StringInterface_H__ -#define __StringInterface_H__ - -#include "OgrePrerequisites.h" -#include "OgreCommon.h" -#include "OgreHeaderPrefix.h" -#include "OgreStringConverter.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - - /// @deprecated do not use - enum ParameterType - { - PT_BOOL, - PT_REAL, - PT_INT, - PT_UNSIGNED_INT, - PT_SHORT, - PT_UNSIGNED_SHORT, - PT_LONG, - PT_UNSIGNED_LONG, - PT_STRING, - PT_VECTOR3, - PT_MATRIX3, - PT_MATRIX4, - PT_QUATERNION, - PT_COLOURVALUE - }; - - /// @deprecated directly pass parameter name - class _OgreExport ParameterDef - { - public: - String name; - ParameterDef(const String& newName, const String& = "", ParameterType = PT_INT) - : name(newName) {} - }; - typedef std::vector ParameterList; - - /** Abstract class which is command object which gets/sets parameters.*/ - class _OgreExport ParamCommand - { - public: - virtual String doGet(const void* target) const = 0; - virtual void doSet(void* target, const String& val) = 0; - - virtual ~ParamCommand() { } - }; - typedef std::map ParamCommandMap; - -#ifndef SWIG - /** Generic ParamCommand implementation - stores pointers to the class getter and setter functions */ - template - class SimpleParamCommand : public ParamCommand { - public: - String doGet(const void* target) const override { - return StringConverter::toString((static_cast(target)->*getter)()); - } - - void doSet(void* target, const String& val) override { - typename std::decay::type tmp; - StringConverter::parse(val, tmp); - (static_cast<_Class*>(target)->*setter)(tmp); - } - }; - - /// specialization for strings - template - class SimpleParamCommand<_Class, const String&, getter, setter> : public ParamCommand { - public: - String doGet(const void* target) const override { - return (static_cast(target)->*getter)(); - } - - void doSet(void* target, const String& val) override { - (static_cast<_Class*>(target)->*setter)(val); - } - }; -#endif - - /** Class to hold a dictionary of parameters for a single class. */ - class _OgreExport ParamDictionary - { - friend class StringInterface; - /// Definitions of parameters - ParameterList mParamDefs; - - /// Command objects to get/set - ParamCommandMap mParamCommands; - - /** Retrieves the parameter command object for a named parameter. */ - ParamCommand* getParamCommand(const String& name); - const ParamCommand* getParamCommand(const String& name) const; - public: - ParamDictionary(); - ~ParamDictionary(); - /** Method for adding a parameter definition for this class. - @param name The name of the parameter - @param paramCmd Pointer to a ParamCommand subclass to handle the getting / setting of this parameter. - NB this class will not destroy this on shutdown, please ensure you do - - */ - void addParameter(const String& name, ParamCommand* paramCmd); - - /// @deprecated do not use - void addParameter(const ParameterDef& def, ParamCommand* paramCmd) - { - addParameter(def.name, paramCmd); - } - /** Retrieves a list of parameters valid for this object. - @return - A reference to a static list of ParameterDef objects. - - */ - const ParameterList& getParameters(void) const - { - return mParamDefs; - } - }; - typedef std::map ParamDictionaryMap; - - /** Class defining the common interface which classes can use to - present a reflection-style, self-defining parameter set to callers. - - This class also holds a static map of class name to parameter dictionaries - for each subclass to use. See ParamDictionary for details. - - In order to use this class, each subclass must call createParamDictionary in their constructors - which will create a parameter dictionary for the class if it does not exist yet. - */ - class _OgreExport StringInterface - { - private: - /// Class name for this instance to be used as a lookup (must be initialised by subclasses) - String mParamDictName; - ParamDictionary* mParamDict; - - protected: - /** Internal method for creating a parameter dictionary for the class, if it does not already exist. - - This method will check to see if a parameter dictionary exist for this class yet, - and if not will create one. NB you must supply the name of the class (RTTI is not - used or performance). - @param - className the name of the class using the dictionary - @return - true if a new dictionary was created, false if it was already there - */ - bool createParamDictionary(const String& className); - - public: - StringInterface() : mParamDict(NULL) { } - - /** Virtual destructor, see Effective C++ */ - virtual ~StringInterface() {} - - /** Retrieves the parameter dictionary for this class. - - Only valid to call this after createParamDictionary. - @return - Pointer to ParamDictionary shared by all instances of this class - which you can add parameters to, retrieve parameters etc. - */ - ParamDictionary* getParamDictionary(void) - { - return mParamDict; - } - - const ParamDictionary* getParamDictionary(void) const - { - return mParamDict; - } - - /** Retrieves a list of parameters valid for this object. - @return - A reference to a static list of ParameterDef objects. - - */ - const ParameterList& getParameters(void) const; - - /** Generic parameter setting method. - - Call this method with the name of a parameter and a string version of the value - to set. The implementor will convert the string to a native type internally. - If in doubt, check the parameter definition in the list returned from - StringInterface::getParameters. - @param - name The name of the parameter to set - @param - value String value. Must be in the right format for the type specified in the parameter definition. - See the StringConverter class for more information. - @return - true if set was successful, false otherwise (NB no exceptions thrown - tolerant method) - */ - bool setParameter(const String& name, const String& value); - /** Generic multiple parameter setting method. - - Call this method with a list of name / value pairs - to set. The implementor will convert the string to a native type internally. - If in doubt, check the parameter definition in the list returned from - StringInterface::getParameters. - @param - paramList Name/value pair list - */ - void setParameterList(const NameValuePairList& paramList); - /** Generic parameter retrieval method. - - Call this method with the name of a parameter to retrieve a string-format value of - the parameter in question. If in doubt, check the parameter definition in the - list returned from getParameters for the type of this parameter. If you - like you can use StringConverter to convert this string back into a native type. - @param - name The name of the parameter to get - @return - String value of parameter, blank if not found - */ - String getParameter(const String& name) const; - /** Method for copying this object's parameters to another object. - - This method takes the values of all the object's parameters and tries to set the - same values on the destination object. This provides a completely type independent - way to copy parameters to other objects. Note that because of the String manipulation - involved, this should not be regarded as an efficient process and should be saved for - times outside of the rendering loop. - @par - Any unrecognised parameters will be ignored as with setParameter method. - @param dest Pointer to object to have it's parameters set the same as this object. - - */ - void copyParametersTo(StringInterface* dest) const; - /** Cleans up the static 'msDictionary' required to reset Ogre, - otherwise the containers are left with invalid pointers, which will lead to a crash - as soon as one of the ResourceManager implementers (e.g. MaterialManager) initializes.*/ - static void cleanupDictionary () ; - - }; - - /** @} */ - /** @} */ - - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreStringVector.h b/OgreMain/include/OgreStringVector.h deleted file mode 100644 index 5b37ebe6e1d..00000000000 --- a/OgreMain/include/OgreStringVector.h +++ /dev/null @@ -1,51 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _StringVector_H__ -#define _StringVector_H__ - -#include "OgrePrerequisites.h" -#include "OgreSharedPtr.h" -#include "OgreString.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - - typedef std::vector StringVector; - typedef SharedPtr StringVectorPtr; - - /** @} */ - /** @} */ - -} - -#endif diff --git a/OgreMain/include/OgreSubEntity.h b/OgreMain/include/OgreSubEntity.h deleted file mode 100644 index 30923aaa1cc..00000000000 --- a/OgreMain/include/OgreSubEntity.h +++ /dev/null @@ -1,282 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __SubEntity_H__ -#define __SubEntity_H__ - -#include "OgrePrerequisites.h" - -#include "OgreRenderable.h" -#include "OgreHardwareBufferManager.h" -#include "OgreResourceGroupManager.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** Utility class which defines the sub-parts of an Entity. - - Just as meshes are split into submeshes, an Entity is made up of - potentially multiple SubMeshes. These are mainly here to provide the - link between the Material which the SubEntity uses (which may be the - default Material for the SubMesh or may have been changed for this - object) and the SubMesh data. - @par - The SubEntity also allows the application some flexibility in the - material properties for this section of a particular instance of this - Mesh, e.g. tinting the windows on a car model. - @par - SubEntity instances are never created manually. They are created at - the same time as their parent Entity by the SceneManager method - createEntity. - */ - class _OgreExport SubEntity: public Renderable, public SubEntityAlloc - { - // Note no virtual functions for efficiency - friend class Entity; - friend class SceneManager; - private: - /** Private constructor - don't allow creation by anybody else. - */ - SubEntity(Entity* parent, SubMesh* subMeshBasis); - ~SubEntity(); - - /// Pointer to parent. - Entity* mParentEntity; - - /// Cached pointer to material. - MaterialPtr mMaterialPtr; - - /// Pointer to the SubMesh defining geometry. - SubMesh* mSubMesh; - - /// override the start index for the RenderOperation - size_t mIndexStart; - - /// override the end index for the RenderOperation - size_t mIndexEnd; - - /// Is this SubEntity visible? - bool mVisible; - - /// The render queue to use when rendering this renderable - uint8 mRenderQueueID; - /// Flags whether the RenderQueue's default should be used. - bool mRenderQueueIDSet; - /// Flags whether the RenderQueue's default should be used. - bool mRenderQueuePrioritySet; - /// The render queue priority to use when rendering this renderable - ushort mRenderQueuePriority; - /// Blend buffer details for dedicated geometry - std::unique_ptr mSkelAnimVertexData; - /// Quick lookup of buffers - Entity::TempBlendedBufferInfo mTempSkelAnimInfo; - /// Temp buffer details for software Vertex anim geometry - Entity::TempBlendedBufferInfo mTempVertexAnimInfo; - /// Vertex data details for software Vertex anim of shared geometry - std::unique_ptr mSoftwareVertexAnimVertexData; - /// Vertex data details for hardware Vertex anim of shared geometry - /// - separate since we need to s/w anim for shadows whilst still altering - /// the vertex data for hardware morphing (pos2 binding) - std::unique_ptr mHardwareVertexAnimVertexData; - /// Cached distance to last camera for getSquaredViewDepth - mutable Real mCachedCameraDist; - /// Number of hardware blended poses supported by material - ushort mHardwarePoseCount; - /// Have we applied any vertex animation to geometry? - bool mVertexAnimationAppliedThisFrame; - /// The camera for which the cached distance is valid - mutable const Camera *mCachedCamera; - - /** Internal method for preparing this Entity for use in animation. */ - void prepareTempBlendBuffers(void); - - public: - /** Gets the name of the Material in use by this instance. - */ - const String& getMaterialName() const; - - /** Sets the name of the Material to be used. - - By default a SubEntity uses the default Material that the SubMesh - uses. This call can alter that so that the Material is different - for this instance. - */ - void setMaterialName( const String& name, const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME ); - - /// @copydoc setMaterialName - void setMaterial( const MaterialPtr& material ); - - /** Tells this SubEntity whether to be visible or not. */ - void setVisible(bool visible); - - /** Returns whether or not this SubEntity is supposed to be visible. */ - bool isVisible(void) const { return mVisible; } - - /** Sets the render queue group this SubEntity will be rendered through. - - Render queues are grouped to allow you to more tightly control the ordering - of rendered objects. If you do not call this method, the SubEntity will use - either the Entity's queue or it will use the default - (RenderQueue::getDefaultQueueGroup). - @par - See Entity::setRenderQueueGroup for more details. - @param queueID Enumerated value of the queue group to use. See the - enum RenderQueueGroupID for what kind of values can be used here. - */ - void setRenderQueueGroup(uint8 queueID); - - /** Sets the render queue group and group priority this SubEntity will be rendered through. - - Render queues are grouped to allow you to more tightly control the ordering - of rendered objects. Within a single render group there another type of grouping - called priority which allows further control. If you do not call this method, - all Entity objects default to the default queue and priority - (RenderQueue::getDefaultQueueGroup, RenderQueue::getDefaultRenderablePriority). - @par - See Entity::setRenderQueueGroupAndPriority for more details. - @param queueID Enumerated value of the queue group to use. See the - enum RenderQueueGroupID for what kind of values can be used here. - @param priority The priority within a group to use. - */ - void setRenderQueueGroupAndPriority(uint8 queueID, ushort priority); - - /** Gets the queue group for this entity, see setRenderQueueGroup for full details. */ - uint8 getRenderQueueGroup(void) const { return mRenderQueueID; } - - /** Gets the queue group for this entity, see setRenderQueueGroup for full details. */ - ushort getRenderQueuePriority(void) const { return mRenderQueuePriority; } - - /** Gets the queue group for this entity, see setRenderQueueGroup for full details. */ - bool isRenderQueueGroupSet(void) const { return mRenderQueueIDSet; } - - /** Gets the queue group for this entity, see setRenderQueueGroup for full details. */ - bool isRenderQueuePrioritySet(void) const { return mRenderQueuePrioritySet; } - - /** Accessor method to read mesh data. - */ - SubMesh* getSubMesh(void); - - /** Accessor to get parent Entity */ - Entity* getParent(void) const { return mParentEntity; } - - - const MaterialPtr& getMaterial(void) const override { return mMaterialPtr; } - void getRenderOperation(RenderOperation& op) override; - - /** Tells this SubEntity to draw a subset of the SubMesh by adjusting the index buffer extents. - * Default value is zero so that the entire index buffer is used when drawing. - * Valid values are zero to getIndexDataEndIndex() - */ - void setIndexDataStartIndex(size_t start_index); - - /** Returns the current value of the start index used for drawing. - * \see setIndexDataStartIndex - */ - size_t getIndexDataStartIndex() const; - - /** Tells this SubEntity to draw a subset of the SubMesh by adjusting the index buffer extents. - * Default value is SubMesh::indexData::indexCount so that the entire index buffer is used when drawing. - * Valid values are mStartIndex to SubMesh::indexData::indexCount - */ - void setIndexDataEndIndex(size_t end_index); - - /** Returns the current value of the start index used for drawing. - */ - size_t getIndexDataEndIndex() const; - - /** Reset the custom start/end index to the default values. - */ - void resetIndexDataStartEndIndex(); - - void getWorldTransforms(Matrix4* xform) const override; - unsigned short getNumWorldTransforms(void) const override; - Real getSquaredViewDepth(const Camera* cam) const override; - const LightList& getLights(void) const override; - bool getCastsShadows(void) const override; - /** Advanced method to get the temporarily blended vertex information - for entities which are software skinned. - - Internal engine will eliminate software animation if possible, this - information is unreliable unless added request for software animation - via Entity::addSoftwareAnimationRequest. - @note - The positions/normals of the returned vertex data is in object space. - */ - VertexData* _getSkelAnimVertexData(void); - /** Advanced method to get the temporarily blended software morph vertex information - - Internal engine will eliminate software animation if possible, this - information is unreliable unless added request for software animation - via Entity::addSoftwareAnimationRequest. - @note - The positions/normals of the returned vertex data is in object space. - */ - VertexData* _getSoftwareVertexAnimVertexData(void); - /** Advanced method to get the hardware morph vertex information - @note - The positions/normals of the returned vertex data is in object space. - */ - VertexData* _getHardwareVertexAnimVertexData(void); - /// Retrieve the VertexData which should be used for GPU binding - VertexData* getVertexDataForBinding(void); - - /** Mark all vertex data as so far unanimated. - */ - void _markBuffersUnusedForAnimation(void); - /** Mark all vertex data as animated. - */ - void _markBuffersUsedForAnimation(void); - /** Are buffers already marked as vertex animated? */ - bool _getBuffersMarkedForAnimation(void) const { return mVertexAnimationAppliedThisFrame; } - /** Internal method to copy original vertex data to the morph structures - should there be no active animation in use. - */ - void _restoreBuffersForUnusedAnimation(bool hardwareAnimation); - - /** Overridden from Renderable to provide some custom behaviour. */ - void _updateCustomGpuParameter( - const GpuProgramParameters::AutoConstantEntry& constantEntry, - GpuProgramParameters* params) const override; - - /** Invalidate the camera distance cache */ - void _invalidateCameraCache () - { mCachedCamera = 0; } - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreSubMesh.h b/OgreMain/include/OgreSubMesh.h deleted file mode 100644 index 688b9ff63f2..00000000000 --- a/OgreMain/include/OgreSubMesh.h +++ /dev/null @@ -1,259 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __SubMesh_H_ -#define __SubMesh_H_ - -#include "OgrePrerequisites.h" - -#include "OgreRenderOperation.h" -#include "OgreVertexBoneAssignment.h" -#include "OgreAnimationTrack.h" -#include "OgreResourceGroupManager.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - /** Defines a part of a complete mesh. - - Meshes which make up the definition of a discrete 3D object - are made up of potentially multiple parts. This is because - different parts of the mesh may use different materials or - use different vertex formats, such that a rendering state - change is required between them. - @par - Like the Mesh class, instantiations of 3D objects in the scene - share the SubMesh instances, and have the option of overriding - their material differences on a per-object basis if required. - See the SubEntity class for more information. - */ - class _OgreExport SubMesh : public SubMeshAlloc - { - friend class Mesh; - friend class MeshSerializerImpl; - friend class MeshSerializerImpl_v1_2; - friend class MeshSerializerImpl_v1_1; - public: - SubMesh(); - ~SubMesh(); - - /** Dedicated vertex data (only valid if useSharedVertices = false). - - This data is completely owned by this submesh. - @par - The use of shared or non-shared buffers is determined when - model data is converted to the OGRE .mesh format. - */ - VertexData *vertexData; - - /// replace the vertex data with a new one - void resetVertexData(VertexData* data = nullptr) - { - delete vertexData; - vertexData = data; - useSharedVertices = data == nullptr; - } - - /// Creates a new local vertex data object - void createVertexData(HardwareBufferManagerBase* mgr = nullptr) { resetVertexData(new VertexData(mgr)); } - - /// Face index data - IndexData *indexData; - - /** Dedicated index map for translate blend index to bone index (only valid if useSharedVertices = false). - - This data is completely owned by this submesh. - @par - We collect actually used bones of all bone assignments, and build the - blend index in 'packed' form, then the range of the blend index in vertex - data VES_BLEND_INDICES element is continuous, with no gaps. Thus, by - minimising the world matrix array constants passing to GPU, we can support - more bones for a mesh when hardware skinning is used. The hardware skinning - support limit is applied to each set of vertex data in the mesh, in other words, the - hardware skinning support limit is applied only to the actually used bones of each - SubMeshes, not all bones across the entire Mesh. - @par - Because the blend index is different to the bone index, therefore, we use - the index map to translate the blend index to bone index. - @par - The use of shared or non-shared index map is determined when - model data is converted to the OGRE .mesh format. - */ - typedef std::vector IndexMap; - IndexMap blendIndexToBoneIndexMap; - - typedef std::vector LODFaceList; - LODFaceList mLodFaceList; - - /** A list of extreme points on the submesh (optional). - - These points are some arbitrary points on the mesh that are used - by engine to better sort submeshes by depth. This doesn't matter - much for non-transparent submeshes, as Z-buffer takes care of invisible - surface culling anyway, but is pretty useful for semi-transparent - submeshes because the order in which transparent submeshes must be - rendered cannot be always correctly deduced from entity position. - @par - These points are intelligently chosen from the points that make up - the submesh, the criteria for choosing them should be that these points - somewhat characterize the submesh outline, e.g. they should not be - close to each other, and they should be on the outer hull of the submesh. - They can be stored in the .mesh file, or generated at runtime - (see generateExtremes ()). - @par - If this array is empty, submesh sorting is done like in older versions - - by comparing the positions of the owning entity. - */ - std::vector extremityPoints; - - /// Reference to parent Mesh (not a smart pointer so child does not keep parent alive). - Mesh* parent; - - /// Indicates if this submesh shares vertex data with other meshes or whether it has it's own vertices. - bool useSharedVertices; - - /// The render operation type used to render this submesh - RenderOperation::OperationType operationType; - - /// Sets the name of the Material which this SubMesh will use - void setMaterialName(const String& matName, const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME ); - const String& getMaterialName(void) const; - - void setMaterial(const MaterialPtr& mat) { mMaterial = mat; } - const MaterialPtr& getMaterial() const { return mMaterial; } - - /** Returns a RenderOperation structure required to render this mesh. - @param - rend Reference to a RenderOperation structure to populate. - @param - lodIndex The index of the LOD to use. - */ - void _getRenderOperation(RenderOperation& rend, ushort lodIndex = 0); - - /** Assigns a vertex to a bone with a given weight, for skeletal animation. - - This method is only valid after calling setSkeletonName. - Since this is a one-off process there exists only 'addBoneAssignment' and - 'clearBoneAssignments' methods, no 'editBoneAssignment'. You should not need - to modify bone assignments during rendering (only the positions of bones) and OGRE - reserves the right to do some internal data reformatting of this information, depending - on render system requirements. - @par - This method is for assigning weights to the dedicated geometry of the SubMesh. To assign - weights to the shared Mesh geometry, see the equivalent methods on Mesh. - */ - void addBoneAssignment(const VertexBoneAssignment& vertBoneAssign); - - /** Removes all bone assignments for this mesh. - @par - This method is for assigning weights to the dedicated geometry of the SubMesh. To assign - weights to the shared Mesh geometry, see the equivalent methods on Mesh. - */ - void clearBoneAssignments(void); - - /// Multimap of verex bone assignments (orders by vertex index) - typedef std::multimap VertexBoneAssignmentList; - typedef MapIterator BoneAssignmentIterator; - - /// @deprecated use getBoneAssignments - OGRE_DEPRECATED BoneAssignmentIterator getBoneAssignmentIterator(void); - - /** Gets a const reference to the list of bone assignments - */ - const VertexBoneAssignmentList& getBoneAssignments() const { return mBoneAssignments; } - - - /** Must be called once to compile bone assignments into geometry buffer. */ - void _compileBoneAssignments(void); - - /** Get the type of any vertex animation used by dedicated geometry. - */ - VertexAnimationType getVertexAnimationType(void) const; - - /// Returns whether animation on dedicated vertex data includes normals - bool getVertexAnimationIncludesNormals() const { return mVertexAnimationIncludesNormals; } - - - /** Generate the submesh extremes (@see extremityPoints). - @param count - Number of extreme points to compute for the submesh. - */ - void generateExtremes(size_t count); - - /** Returns true(by default) if the submesh should be included in the mesh EdgeList, otherwise returns false. - */ - bool isBuildEdgesEnabled(void) const { return mBuildEdgesEnabled; } - void setBuildEdgesEnabled(bool b); - /** Makes a copy of this submesh object and gives it a new name. - @param newName - The name to give the clone. - @param parentMesh - Optional mesh to make the parent of the newly created clone. - If you leave this blank, the clone will be parented to the same Mesh as the original. - */ - SubMesh * clone(const String& newName, Mesh *parentMesh = 0); - - private: - - /// Flag indicating that bone assignments need to be recompiled - bool mBoneAssignmentsOutOfDate; - - /// Type of vertex animation for dedicated vertex data (populated by Mesh) - mutable VertexAnimationType mVertexAnimationType; - - /// Whether normals are included in vertex animation keyframes - mutable bool mVertexAnimationIncludesNormals; - - /// Is Build Edges Enabled - bool mBuildEdgesEnabled; - - /// the material this SubMesh uses. - MaterialPtr mMaterial; - - VertexBoneAssignmentList mBoneAssignments; - - /// Internal method for removing LOD data - void removeLodLevels(void); - - - }; - /** @} */ - /** @} */ - -} // namespace - -#include "OgreHeaderSuffix.h" - -#endif - - diff --git a/OgreMain/include/OgreTagPoint.h b/OgreMain/include/OgreTagPoint.h deleted file mode 100644 index 5bc634d1471..00000000000 --- a/OgreMain/include/OgreTagPoint.h +++ /dev/null @@ -1,117 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __TagPoint_H_ -#define __TagPoint_H_ - -#include "OgrePrerequisites.h" - -#include "OgreBone.h" -#include "OgreMatrix4.h" - -namespace Ogre { - - - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Animation - * @{ - */ - /** A tagged point on a skeleton, which can be used to attach entities to on specific - other entities. - - A Skeleton, like a Mesh, is shared between Entity objects and simply updated as required - when it comes to rendering. However there are times when you want to attach another object - to an animated entity, and make sure that attachment follows the parent entity's animation - (for example, a character holding a gun in his / her hand). This class simply identifies - attachment points on a skeleton which can be used to attach child objects. - @par - The child objects themselves are not physically attached to this class; as it's name suggests - this class just 'tags' the area. The actual child objects are attached to the Entity using the - skeleton which has this tag point. Use the Entity::attachMovableObjectToBone method to attach - the objects, which creates a new TagPoint on demand. - */ - class _OgreExport TagPoint : public Bone - { - - public: - TagPoint(unsigned short handle, Skeleton* creator); - - Entity *getParentEntity(void) const; - MovableObject* getChildObject(void) const; - - void setParentEntity(Entity *pEntity); - void setChildObject(MovableObject *pObject); - - /** Tells the TagPoint whether it should inherit orientation from it's parent entity. - @param inherit If true, this TagPoint's orientation will be affected by - its parent entity's orientation. If false, it will not be affected. - */ - void setInheritParentEntityOrientation(bool inherit); - - /** Returns true if this TagPoint is affected by orientation applied to the parent entity. - */ - bool getInheritParentEntityOrientation(void) const; - - /** Tells the TagPoint whether it should inherit scaling factors from it's parent entity. - @param inherit If true, this TagPoint's scaling factors will be affected by - its parent entity's scaling factors. If false, it will not be affected. - */ - void setInheritParentEntityScale(bool inherit); - - /** Returns true if this TagPoint is affected by scaling factors applied to the parent entity. - */ - bool getInheritParentEntityScale(void) const; - - /** Gets the transform of parent entity. */ - const Affine3& getParentEntityTransform(void) const; - - /** Gets the transform of this node just for the skeleton (not entity) */ - const Affine3& _getFullLocalTransform(void) const; - - - void needUpdate(bool forceParentUpdate = false) override; - /** Overridden from Node in order to include parent Entity transform. */ - void updateFromParentImpl(void) const override; - - private: - bool mInheritParentEntityOrientation; - bool mInheritParentEntityScale; - Entity *mParentEntity; - MovableObject *mChildObject; - mutable Affine3 mFullLocalTransform; - }; - - /** @} */ - /** @} */ - -} //namespace - - -#endif//__TagPoint_H_ diff --git a/OgreMain/include/OgreTangentSpaceCalc.h b/OgreMain/include/OgreTangentSpaceCalc.h deleted file mode 100644 index cd1a0ccfc2c..00000000000 --- a/OgreMain/include/OgreTangentSpaceCalc.h +++ /dev/null @@ -1,262 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _OgreTangentSpaceCalc_H_ -#define _OgreTangentSpaceCalc_H_ - -#include "OgrePrerequisites.h" -#include "OgreRenderOperation.h" -#include "OgreVector.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - /** Class for calculating a tangent space basis. - */ - class _OgreExport TangentSpaceCalc - { - public: - TangentSpaceCalc(); - - typedef std::pair VertexSplit; - - /// Information about a remapped index - struct IndexRemap - { - /// Index data set (can be >0 if more than one index data was added) - size_t indexSet; - /// The position in the index buffer that's affected - size_t faceIndex; - /// The old and new vertex index - VertexSplit splitVertex; - - IndexRemap() {} // to keep container happy - IndexRemap(size_t i, size_t f, const VertexSplit& s) : indexSet(i), faceIndex(f), splitVertex(s) {} - }; - /** List of indexes that were remapped (split vertices). - */ - typedef std::list IndexRemapList; - - typedef std::list VertexSplits; - - /// The result of having built a tangent space basis - struct Result - { - /** A list of vertex indices which were split off into new vertices - because of mirroring. First item in each pair is the source vertex - index, the second value is the split vertex index. - */ - VertexSplits vertexSplits; - /** A list of indexes which were affected by splits. You can use this if you have other - triangle-based data which you will need to alter to match. */ - IndexRemapList indexesRemapped; - }; - - /// Reset the calculation object - void clear(); - - /** Set the incoming vertex data (which will be modified) */ - void setVertexData(VertexData* v_in); - - /** Add a set of index data that references the vertex data. - This might be modified if there are vertex splits. - */ - void addIndexData(IndexData* i_in, RenderOperation::OperationType opType = RenderOperation::OT_TRIANGLE_LIST); - - /** Sets whether to store tangent space parity in the W of a 4-component tangent or not. - - The default element format to use is VET_FLOAT3 which is enough to accurately - deal with tangents that do not involve any texture coordinate mirroring. - If you wish to allow UV mirroring in your model, you must enable 4-component - tangents using this method, and the 'w' coordinate will be populated - with the parity of the triangle (+1 or -1), which will allow you to generate - the bitangent properly. - @param enabled true to enable 4-component tangents (default false). If you enable - this, you will probably also want to enable mirror splitting (see setSplitMirrored), - and your shader must understand how to deal with the parity. - */ - void setStoreParityInW(bool enabled) { mStoreParityInW = enabled; } - - /** Gets whether to store tangent space parity in the W of a 4-component tangent or not. */ - bool getStoreParityInW() const { return mStoreParityInW; } - - /** Sets whether or not to split vertices when a mirrored tangent space - transition is detected (matrix parity differs). - - This defaults to 'off' because it's the safest option; tangents will be - interpolated in all cases even if they don't agree around a vertex, so - artefacts will be smoothed out. When you're using art assets of - unknown quality this can avoid extra seams on the visible surface. - However, if your artists are good, they will be hiding texture seams - in folds of the model and thus you can turn this option on, which will - prevent the results of those seams from getting smoothed into other - areas, which is exactly what you want. - @note This option is automatically disabled if you provide any strip or - fan based geometry. - */ - void setSplitMirrored(bool split) { mSplitMirrored = split; } - - /** Gets whether or not to split vertices when a mirrored tangent space - transition is detected. - */ - bool getSplitMirrored() const { return mSplitMirrored; } - - /** Sets whether or not to split vertices when tangent space rotates - more than 90 degrees around a vertex. - - This defaults to 'off' because it's the safest option; tangents will be - interpolated in all cases even if they don't agree around a vertex, so - artefacts will be smoothed out. When you're using art assets of - unknown quality this can avoid extra seams on the visible surface. - However, if your artists are good, they will be hiding texture inconsistencies - in folds of the model and thus you can turn this option on, which will - prevent the results of those seams from getting smoothed into other - areas, which is exactly what you want. - @note This option is automatically disabled if you provide any strip or - fan based geometry. - */ - void setSplitRotated(bool split) { mSplitRotated = split; } - /** Sets whether or not to split vertices when tangent space rotates - more than 90 degrees around a vertex. - */ - bool getSplitRotated() const { return mSplitRotated; } - - /** Build a tangent space basis from the provided data. - - Only indexed triangle lists are allowed. Strips and fans cannot be - supported because it may be necessary to split the geometry up to - respect deviances in the tangent space basis better. - @param sourceTexCoordSet The texture coordinate index which should be used as the source - of 2D texture coordinates, with which to calculate the tangents. - @return - A structure containing the results of the tangent space build. Vertex data - will always be modified but it's also possible that the index data - could be adjusted. This happens when mirroring is used on a mesh, which - causes the tangent space to be inverted on opposite sides of an edge. - This is discontinuous, therefore the vertices have to be split along - this edge, resulting in new vertices. - */ - Result build(unsigned short sourceTexCoordSet = 0); - - OGRE_DEPRECATED Result build(VertexElementSemantic targetSemantic, unsigned short sourceTexCoordSet = 0, - unsigned short index = 0) - { - OgreAssert(targetSemantic == VES_TANGENT && index == 0, "Invalid Parameters"); - return build(sourceTexCoordSet); - } - - private: - - VertexData* mVData; - typedef std::vector IndexDataList; - typedef std::vector OpTypeList; - IndexDataList mIDataList; - OpTypeList mOpTypes; - bool mSplitMirrored; - bool mSplitRotated; - bool mStoreParityInW; - - - struct VertexInfo - { - Vector3 pos; - Vector3 norm; - Vector2 uv; - Vector3 tangent; - Vector3 binormal; - // Which way the tangent space is oriented (+1 / -1) (set on first time found) - int parity; - // What index the opposite parity vertex copy is at (0 if not created yet) - size_t oppositeParityIndex; - - VertexInfo() : tangent(Vector3::ZERO), binormal(Vector3::ZERO), - parity(0), oppositeParityIndex(0) {} - }; - typedef std::vector VertexInfoArray; - VertexInfoArray mVertexArray; - - void extendBuffers(VertexSplits& splits); - void insertTangents(Result& res, - VertexElementSemantic targetSemantic, - unsigned short sourceTexCoordSet, unsigned short index); - - void populateVertexArray(unsigned short sourceTexCoordSet); - void processFaces(Result& result); - /// Calculate face tangent space, U and V are weighted by UV area, N is normalised - void calculateFaceTangentSpace(const size_t* vertInd, Vector3& tsU, Vector3& tsV, Vector3& tsN); - Real calculateAngleWeight(size_t v0, size_t v1, size_t v2); - int calculateParity(const Vector3& u, const Vector3& v, const Vector3& n); - void addFaceTangentSpaceToVertices(size_t indexSet, size_t faceIndex, size_t *localVertInd, - const Vector3& faceTsU, const Vector3& faceTsV, const Vector3& faceNorm, Result& result); - void normaliseVertices(); - void remapIndexes(Result& res); - template - void remapIndexes(T* ibuf, size_t indexSet, Result& res) - { - for (auto & remap : res.indexesRemapped) - { - // Note that because this is a vertex split situation, and vertex - // split is only for some faces, it's not a case of replacing all - // instances of vertex index A with vertex index B - // It actually matters which triangle we're talking about, so drive - // the update from the face index - - if (remap.indexSet == indexSet) - { - T* pBuf; - pBuf = ibuf + remap.faceIndex * 3; - - for (int v = 0; v < 3; ++v, ++pBuf) - { - if (*pBuf == remap.splitVertex.first) - { - *pBuf = (T)remap.splitVertex.second; - } - } - } - - - } - } - - - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreTechnique.h b/OgreMain/include/OgreTechnique.h deleted file mode 100644 index cdff340ce55..00000000000 --- a/OgreMain/include/OgreTechnique.h +++ /dev/null @@ -1,709 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Technique_H__ -#define __Technique_H__ - -#include "OgrePrerequisites.h" -#include "OgreCommon.h" -#include "OgrePass.h" -#include "OgreRenderSystemCapabilities.h" -#include "OgreUserObjectBindings.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Materials - * @{ - */ - /** Class representing an approach to rendering this particular Material. - - Ogre will attempt to use the best technique supported by the active hardware, - unless you specifically request a lower detail technique (say for distant - rendering). - */ - class _OgreExport Technique : public TechniqueAlloc - { - public: - typedef std::vector Passes; - - private: - /// Illumination pass state type - enum IlluminationPassesState : int8 - { - IPS_COMPILE_DISABLED = -1, - IPS_NOT_COMPILED = 0, - IPS_COMPILED = 1 - }; - - /// List of primary passes - Passes mPasses; - /// List of derived passes, categorised into IlluminationStage (ordered) - IlluminationPassList mIlluminationPasses; - // Raw pointer since we don't want child to stop parent's destruction - Material* mParent; - IlluminationPassesState mIlluminationPassesCompilationPhase; - - bool mIsSupported; - /// LOD level - unsigned short mLodIndex; - /** Scheme index, derived from scheme name but the names are held on - MaterialManager, for speed an index is used here. - */ - unsigned short mSchemeIndex; - /// Optional name for the technique - String mName; - /// Internal method for clearing illumination pass list - void clearIlluminationPasses(void); - /// Internal method - check for manually assigned illumination passes - bool checkManuallyOrganisedIlluminationPasses(); - - - /** When casting shadow, if not using default Ogre shadow casting material, or - * nor using fixed function casting, mShadowCasterMaterial let you customize per material - * shadow caster behavior - */ - MaterialPtr mShadowCasterMaterial; - /** When casting shadow, if not using default Ogre shadow casting material, or - * nor using fixed function casting, mShadowCasterMaterial let you customize per material - * shadow caster behavior.There only material name is stored so that it can be loaded once all file parsed in a resource group. - */ - String mShadowCasterMaterialName; - /** When receiving shadow, if not using default Ogre shadow receiving material, or - * nor using fixed function texture projection receiving, mShadowReceiverMaterial let you customize per material - * shadow caster behavior - */ - MaterialPtr mShadowReceiverMaterial; - /** When receiving shadow, if not using default Ogre shadow receiving material, or - * nor using fixed function texture projection receiving, mShadowReceiverMaterial let you customize per material - * shadow caster behavior. There only material name is stored so that it can be loaded once all file parsed in a resource group. - */ - String mShadowReceiverMaterialName; - - // User objects binding. - UserObjectBindings mUserObjectBindings; - public: - /** Directive used to manually control technique support based on the - inclusion or exclusion of some factor. - */ - enum IncludeOrExclude - { - /// Inclusive - only support if present - INCLUDE = 0, - /// Exclusive - do not support if present - EXCLUDE = 1 - }; - /// Rule controlling whether technique is deemed supported based on GPU vendor - struct GPUVendorRule - { - GPUVendor vendor; - IncludeOrExclude includeOrExclude; - GPUVendorRule() - : vendor(GPU_UNKNOWN), includeOrExclude(EXCLUDE) {} - GPUVendorRule(GPUVendor v, IncludeOrExclude ie) - : vendor(v), includeOrExclude(ie) {} - }; - /// Rule controlling whether technique is deemed supported based on GPU device name - struct GPUDeviceNameRule - { - String devicePattern; - IncludeOrExclude includeOrExclude; - bool caseSensitive; - GPUDeviceNameRule() - : includeOrExclude(EXCLUDE), caseSensitive(false) {} - GPUDeviceNameRule(const String& pattern, IncludeOrExclude ie, bool caseSen) - : devicePattern(pattern), includeOrExclude(ie), caseSensitive(caseSen) {} - }; - typedef std::vector GPUVendorRuleList; - typedef std::vector GPUDeviceNameRuleList; - private: - GPUVendorRuleList mGPUVendorRules; - GPUDeviceNameRuleList mGPUDeviceNameRules; - public: - /// Constructor - Technique(Material* parent); - /// Copy constructor - Technique(Material* parent, const Technique& oth); - ~Technique(); - /** Indicates if this technique is supported by the current graphics card. - - This will only be correct after the Technique has been compiled, which is - usually done from Material::compile. - */ - bool isSupported(void) const; - /** Internal compilation method; see Material::compile. - @return Any information explaining problems with the compile. - */ - String _compile(bool autoManageTextureUnits); - /// Internal method for checking hardware support - bool checkHardwareSupport(bool autoManageTextureUnits, StringStream& compileErrors); - size_t calculateSize(void) const; - - typedef VectorIterator PassIterator; - typedef VectorIterator IlluminationPassIterator; - /// @name Passes - /// @{ - /** Creates a new Pass for this Technique. - - A Pass is a single rendering pass, i.e. a single draw of the given material. - Note that if you create a pass without a fragment program, during compilation of the - material the pass may be split into multiple passes if the graphics card cannot - handle the number of texture units requested. For passes with fragment programs, however, - the number of passes you create will never be altered, so you have to make sure - that you create an alternative fallback Technique for if a card does not have - enough facilities for what you're asking for. - */ - Pass* createPass(void); - /** Retrieves the Pass with the given index.*/ - Pass* getPass(size_t index) const { return mPasses.at(index); } - /** Retrieves the Pass matching name. - Returns 0 if name match is not found. - */ - Pass* getPass(const String& name) const; - /** Retrieves the number of passes. */ - size_t getNumPasses(void) const { return mPasses.size(); } - /** Removes the Pass with the given index. */ - void removePass(unsigned short index); - /** Removes all Passes from this Technique. */ - void removeAllPasses(void); - /** Move a pass from source index to destination index. - If successful then returns true. - */ - bool movePass(const unsigned short sourceIndex, const unsigned short destinationIndex); - - /** Gets an iterator over the passes in this Technique. - * @deprecated use getPasses() */ - OGRE_DEPRECATED const PassIterator getPassIterator(void); - - /** Gets the passes in this Technique. */ - const Passes& getPasses(void) const { - return mPasses; - } - - /** Gets the illumination-stage categorised passes - * @note triggers compilation if needed */ - const IlluminationPassList& getIlluminationPasses(); - - /** Internal method for splitting the passes into illumination passes. */ - void _compileIlluminationPasses(void); - /// @} - - /// Gets the parent Material - Material* getParent(void) const { return mParent; } - - /** Overloaded operator to copy on Technique to another. */ - Technique& operator=(const Technique& rhs); - - /// Gets the resource group of the ultimate parent Material - const String& getResourceGroup(void) const; - - /** Returns true if this Technique involves transparency. - - This basically boils down to whether the first pass - has a scene blending factor. Even if the other passes - do not, the base colour, including parts of the original - scene, may be used for blending, therefore we have to treat - the whole Technique as transparent. - */ - bool isTransparent(void) const; - - /** Returns true if this Technique has transparent sorting enabled. - - This basically boils down to whether the first pass - has transparent sorting enabled or not - */ - bool isTransparentSortingEnabled(void) const; - - /** Returns true if this Technique has transparent sorting forced. - - This basically boils down to whether the first pass - has transparent sorting forced or not - */ - bool isTransparentSortingForced(void) const; - - /** Internal prepare method, derived from call to Material::prepare. */ - void _prepare(void); - /** Internal unprepare method, derived from call to Material::unprepare. */ - void _unprepare(void); - /** Internal load method, derived from call to Material::load. */ - void _load(void); - /** Internal unload method, derived from call to Material::unload. */ - void _unload(void); - - /// Is this loaded? - bool isLoaded(void) const; - - /** Tells the technique that it needs recompilation. */ - void _notifyNeedsRecompile(void); - - /// @name Shadow Materials - /// @{ - /** return this material specific shadow casting specific material - */ - MaterialPtr getShadowCasterMaterial() const; - /** Sets the details of the material to use when rendering as a - shadow caster. - - Texture-based shadows require that the caster is rendered to a texture - in a solid colour (the shadow colour in the case of modulative texture - shadows). Whilst Ogre can arrange this for the fixed function - pipeline, passes which use vertex programs might need the vertex - programs still to run in order to preserve any deformation etc - that it does. However, lighting calculations must be a lot simpler, - with only the ambient colour being used (which the engine will ensure - is bound to the shadow colour). - @par - Therefore, it is up to implementors of vertex programs to provide an - alternative material which can be used to render the object - to a shadow texture. Do all the same vertex transforms, but set the - colour of the vertex to the ambient colour, as bound using the - standard auto parameter binding mechanism. - */ - void setShadowCasterMaterial(MaterialPtr val); - /** set this material specific shadow casting specific material - */ - void setShadowCasterMaterial(const String &name); - /** return this material specific shadow receiving specific material - */ - MaterialPtr getShadowReceiverMaterial() const; - /** set this material specific shadow receiving specific material - */ - void setShadowReceiverMaterial(MaterialPtr val); - /** set this material specific shadow receiving specific material - */ - void setShadowReceiverMaterial(const String &name); - /// @} - - /** @name Forwarded Pass Properties - - The following methods are to make migration from previous versions simpler - and to make code easier to write when dealing with simple materials - They set the properties which have been moved to Pass for all Techniques and all Passes - */ - - /// @{ - /** Sets the point size properties for every Pass in this Technique. - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setPointSize - */ - void setPointSize(Real ps); - - /** Sets the ambient colour reflectance properties for every Pass in every Technique. - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setAmbient - */ - void setAmbient(float red, float green, float blue); - - /// @overload - void setAmbient(const ColourValue& ambient); - - /** Sets the diffuse colour reflectance properties of every Pass in every Technique. - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setDiffuse - */ - void setDiffuse(float red, float green, float blue, float alpha); - - /// @overload - void setDiffuse(const ColourValue& diffuse); - - /** Sets the specular colour reflectance properties of every Pass in every Technique. - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setSpecular - */ - void setSpecular(float red, float green, float blue, float alpha); - - /// @overload - void setSpecular(const ColourValue& specular); - - /** Sets the shininess properties of every Pass in every Technique. - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setShininess - */ - void setShininess(Real val); - - /** Sets the amount of self-illumination of every Pass in every Technique. - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setSelfIllumination - */ - void setSelfIllumination(float red, float green, float blue); - - /// @overload - void setSelfIllumination(const ColourValue& selfIllum); - - /** Sets whether or not each Pass renders with depth-buffer checking on or not. - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setDepthCheckEnabled - */ - void setDepthCheckEnabled(bool enabled); - - /** Sets whether or not each Pass renders with depth-buffer writing on or not. - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setDepthWriteEnabled - */ - void setDepthWriteEnabled(bool enabled); - - /** Sets the function used to compare depth values when depth checking is on. - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setDepthFunction - */ - void setDepthFunction( CompareFunction func ); - - /** Sets whether or not colour buffer writing is enabled for each Pass. - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setColourWriteEnabled - */ - void setColourWriteEnabled(bool enabled); - - /** Sets which colour buffer channels are enabled for writing for each Pass. - @see Pass::setColourWriteEnabled - */ - void setColourWriteEnabled(bool red, bool green, bool blue, bool alpha); - - /** Sets the culling mode for each pass based on the 'vertex winding'. - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setCullingMode - */ - void setCullingMode( CullingMode mode ); - - /** Sets the manual culling mode, performed by CPU rather than hardware. - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setManualCullingMode - */ - void setManualCullingMode( ManualCullingMode mode ); - - /** Sets whether or not dynamic lighting is enabled for every Pass. - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setLightingEnabled - */ - void setLightingEnabled(bool enabled); - - /** Sets the type of light shading required - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setShadingMode - */ - void setShadingMode( ShadeOptions mode ); - - /** Sets the fogging mode applied to each pass. - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setFog - */ - void setFog( - bool overrideScene, - FogMode mode = FOG_NONE, - const ColourValue& colour = ColourValue::White, - Real expDensity = 0.001f, Real linearStart = 0.0f, Real linearEnd = 1.0f ); - - /** Sets the depth bias to be used for each Pass. - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setDepthBias - */ - void setDepthBias(float constantBias, float slopeScaleBias); - - /** Set texture filtering for every texture unit in every Pass - @note - This property actually exists on the TextureUnitState class - For simplicity, this method allows you to set these properties for - every current TeextureUnitState, If you need more precision, retrieve the - Pass and TextureUnitState instances and set the property there. - @see TextureUnitState::setTextureFiltering - */ - void setTextureFiltering(TextureFilterOptions filterType); - /** Sets the anisotropy level to be used for all textures. - @note - This property has been moved to the TextureUnitState class, which is accessible via the - Technique and Pass. For simplicity, this method allows you to set these properties for - every current TeextureUnitState, If you need more precision, retrieve the Technique, - Pass and TextureUnitState instances and set the property there. - @see TextureUnitState::setTextureAnisotropy - */ - void setTextureAnisotropy(unsigned int maxAniso); - - /** Sets the kind of blending every pass has with the existing contents of the scene. - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setSceneBlending - */ - void setSceneBlending( const SceneBlendType sbt ); - - /** Sets the kind of blending every pass has with the existing contents of the scene, using individual factors both color and alpha channels - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setSeparateSceneBlending - */ - void setSeparateSceneBlending( const SceneBlendType sbt, const SceneBlendType sbta ); - - /** Allows very fine control of blending every Pass with the existing contents of the scene. - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setSceneBlending - */ - void setSceneBlending( const SceneBlendFactor sourceFactor, const SceneBlendFactor destFactor); - - /** Allows very fine control of blending every Pass with the existing contents of the scene, using individual factors both color and alpha channels - @note - This property actually exists on the Pass class. For simplicity, this method allows - you to set these properties for every current Pass within this Technique. If - you need more precision, retrieve the Pass instance and set the - property there. - @see Pass::setSeparateSceneBlending - */ - void setSeparateSceneBlending( const SceneBlendFactor sourceFactor, const SceneBlendFactor destFactor, const SceneBlendFactor sourceFactorAlpha, const SceneBlendFactor destFactorAlpha); - /// @} - - /** Assigns a level-of-detail (LOD) index to this Technique. - - As noted previously, as well as providing fallback support for various - graphics cards, multiple Technique objects can also be used to implement - material LOD, where the detail of the material diminishes with distance to - save rendering power. - @par - By default, all Techniques have a LOD index of 0, which means they are the highest - level of detail. Increasing LOD indexes are lower levels of detail. You can - assign more than one Technique to the same LOD index, meaning that the best - Technique that is supported at that LOD index is used. - @par - You should not leave gaps in the LOD sequence; Ogre will allow you to do this - and will continue to function as if the LODs were sequential, but it will - confuse matters. - */ - void setLodIndex(unsigned short index); - /** Gets the level-of-detail index assigned to this Technique. */ - unsigned short getLodIndex(void) const { return mLodIndex; } - - /** Set the 'scheme name' for this technique. - - Material schemes are used to control top-level switching from one - set of techniques to another. For example, you might use this to - define 'high', 'medium' and 'low' complexity levels on materials - to allow a user to pick a performance / quality ratio. Another - possibility is that you have a fully HDR-enabled pipeline for top - machines, rendering all objects using unclamped shaders, and a - simpler pipeline for others; this can be implemented using - schemes. - @par - Every technique belongs to a scheme - if you don't specify one, the - Technique belongs to the scheme called 'Default', which is also the - scheme used to render by default. The active scheme is set one of - two ways - either by calling Viewport::setMaterialScheme, or - by manually calling MaterialManager::setActiveScheme. - */ - void setSchemeName(const String& schemeName); - /** Returns the scheme to which this technique is assigned. - @see Technique::setSchemeName - */ - const String& getSchemeName(void) const; - - /// Internal method for getting the scheme index - unsigned short _getSchemeIndex(void) const; - - /** Is depth writing going to occur on this technique? */ - bool isDepthWriteEnabled(void) const; - - /** Is depth checking going to occur on this technique? */ - bool isDepthCheckEnabled(void) const; - - /** Exists colour writing disabled pass on this technique? */ - bool hasColourWriteDisabled(void) const; - - /** Set the name of the technique. - - The use of technique name is optional. Its useful in material scripts where a material could inherit - from another material and only want to modify a particular technique. - */ - void setName(const String& name); - /// Gets the name of the technique - const String& getName(void) const { return mName; } - - typedef ConstVectorIterator GPUVendorRuleIterator; - typedef ConstVectorIterator GPUDeviceNameRuleIterator; - /// @name GPU Vendor Rules - /// @{ - - /// Internal method for checking GPU vendor / device rules - bool checkGPURules(StringStream& errors); - /** Add a rule which manually influences the support for this technique based - on a GPU vendor. - - You can use this facility to manually control whether a technique is - considered supported, based on a GPU vendor. You can add inclusive - or exclusive rules, and you can add as many of each as you like. If - at least one inclusive rule is added, a technique is considered - unsupported if it does not match any of those inclusive rules. If exclusive rules are - added, the technique is considered unsupported if it matches any of - those inclusive rules. - @note - Any rule for the same vendor will be removed before adding this one. - @param vendor The GPU vendor - @param includeOrExclude Whether this is an inclusive or exclusive rule - */ - void addGPUVendorRule(GPUVendor vendor, IncludeOrExclude includeOrExclude); - /** Add a rule which manually influences the support for this technique based - on a GPU vendor. - - You can use this facility to manually control whether a technique is - considered supported, based on a GPU vendor. You can add inclusive - or exclusive rules, and you can add as many of each as you like. If - at least one inclusive rule is added, a technique is considered - unsupported if it does not match any of those inclusive rules. If exclusive rules are - added, the technique is considered unsupported if it matches any of - those inclusive rules. - @note - Any rule for the same vendor will be removed before adding this one. - */ - void addGPUVendorRule(const GPUVendorRule& rule); - /** Removes a matching vendor rule. - @see addGPUVendorRule - */ - void removeGPUVendorRule(GPUVendor vendor); - /// @deprecated use getGPUVendorRules() - OGRE_DEPRECATED GPUVendorRuleIterator getGPUVendorRuleIterator() const; - /// Get the currently registered vendor rules. - const GPUVendorRuleList& getGPUVendorRules() const { - return mGPUVendorRules; - } - - /** Add a rule which manually influences the support for this technique based - on a pattern that matches a GPU device name (e.g. '*8800*'). - - You can use this facility to manually control whether a technique is - considered supported, based on a GPU device name pattern. You can add inclusive - or exclusive rules, and you can add as many of each as you like. If - at least one inclusive rule is added, a technique is considered - unsupported if it does not match any of those inclusive rules. If exclusive rules are - added, the technique is considered unsupported if it matches any of - those inclusive rules. The pattern you supply can include wildcard - characters ('*') if you only want to match part of the device name. - @note - Any rule for the same device pattern will be removed before adding this one. - @param devicePattern The GPU vendor - @param includeOrExclude Whether this is an inclusive or exclusive rule - @param caseSensitive Whether the match is case sensitive or not - */ - void addGPUDeviceNameRule(const String& devicePattern, IncludeOrExclude includeOrExclude, bool caseSensitive = false); - /// @overload - void addGPUDeviceNameRule(const GPUDeviceNameRule& rule); - /** Removes a matching device name rule. - @see addGPUDeviceNameRule - */ - void removeGPUDeviceNameRule(const String& devicePattern); - /// @deprecated use getGPUDeviceNameRules() - OGRE_DEPRECATED GPUDeviceNameRuleIterator getGPUDeviceNameRuleIterator() const; - /// Get the currently registered device name rules. - const GPUDeviceNameRuleList& getGPUDeviceNameRules() const { return mGPUDeviceNameRules; } - /// @} - - /// @copydoc UserObjectBindings - UserObjectBindings& getUserObjectBindings() { return mUserObjectBindings; } - - /// @overload - const UserObjectBindings& getUserObjectBindings() const { return mUserObjectBindings; } - - }; - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreTexture.h b/OgreMain/include/OgreTexture.h deleted file mode 100644 index 1636c5d617a..00000000000 --- a/OgreMain/include/OgreTexture.h +++ /dev/null @@ -1,525 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _Texture_H__ -#define _Texture_H__ - -#include "OgrePrerequisites.h" -#include "OgreHardwareBuffer.h" -#include "OgreResource.h" -#include "OgreImage.h" -#include "OgreHeaderPrefix.h" -#include "OgreSharedPtr.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - /** Enum identifying the texture usage - */ - enum TextureUsage - { - /// same as #HBU_GPU_TO_CPU - TU_STATIC = HBU_GPU_TO_CPU, - /// same as #HBU_CPU_ONLY - TU_DYNAMIC = HBU_CPU_ONLY, - /// same as #HBU_DETAIL_WRITE_ONLY - TU_WRITE_ONLY = HBU_DETAIL_WRITE_ONLY, - /// same as #HBU_GPU_ONLY - TU_STATIC_WRITE_ONLY = HBU_GPU_ONLY, - /// same as #HBU_CPU_TO_GPU - TU_DYNAMIC_WRITE_ONLY = HBU_CPU_TO_GPU, - /// @deprecated do not use - TU_DYNAMIC_WRITE_ONLY_DISCARDABLE = HBU_CPU_TO_GPU, - /// Mipmaps will be automatically generated for this texture - TU_AUTOMIPMAP = 0x10, - /** This texture will be a render target, i.e. used as a target for render to texture - setting this flag will ignore all other texture usages except TU_AUTOMIPMAP, TU_UAV, TU_NOT_SRV */ - TU_RENDERTARGET = 0x20, - /// Texture would not be used as Shader Resource View, i.e. as regular texture. - /// That flag could be combined with TU_RENDERTARGET or TU_UAV to remove possible limitations on some hardware - TU_NOT_SRV = 0x40, - /// Texture can be bound as an Unordered Access View - /// (imageStore/imageRead/glBindImageTexture in GL jargon) - TU_UNORDERED_ACCESS = 0x80, - /// Texture can be used as an UAV, but not as a regular texture. - TU_UAV_NOT_SRV = TU_UNORDERED_ACCESS | TU_NOT_SRV, - /// Default to automatic mipmap generation static textures - TU_DEFAULT = TU_AUTOMIPMAP | HBU_GPU_ONLY, - - /// @deprecated - TU_NOTSHADERRESOURCE = TU_NOT_SRV, - /// @deprecated - TU_UAV = TU_UNORDERED_ACCESS - }; - - /** Enum identifying the texture access privilege - */ - enum TextureAccess - { - TA_READ = 0x01, - TA_WRITE = 0x10, - TA_READ_WRITE = TA_READ | TA_WRITE - }; - - /** Enum identifying the texture type - */ - enum TextureType : uint8 - { - /// 1D texture, used in combination with 1D texture coordinates - TEX_TYPE_1D = 1, - /// 2D texture, used in combination with 2D texture coordinates (default) - TEX_TYPE_2D = 2, - /// 3D volume texture, used in combination with 3D texture coordinates - TEX_TYPE_3D = 3, - /// cube map (six two dimensional textures, one for each cube face), used in combination with 3D - /// texture coordinates - TEX_TYPE_CUBE_MAP = 4, - /// 2D texture array - TEX_TYPE_2D_ARRAY = 5, - /// GLES2 only OES texture type - TEX_TYPE_EXTERNAL_OES = 6 - }; - - /** Enum identifying special mipmap numbers - */ - enum TextureMipmap - { - /// Generate mipmaps up to 1x1 - MIP_UNLIMITED = 0x7FFFFFFF, - /// Use TextureManager default - MIP_DEFAULT = -1 - }; - - /** Abstract class representing a Texture resource. - - The actual concrete subclass which will exist for a texture - is dependent on the rendering system in use (Direct3D, OpenGL etc). - This class represents the commonalities, and is the one 'used' - by programmers even though the real implementation could be - different in reality. Texture objects are created through - the 'create' method of the TextureManager concrete subclass. - */ - class _OgreExport Texture : public Resource - { - public: - Texture(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual = false, ManualResourceLoader* loader = 0); - - virtual ~Texture() {} - - /** Sets the type of texture; can only be changed before load() - */ - void setTextureType(TextureType ttype ) { mTextureType = ttype; } - - /** Gets the type of texture - */ - TextureType getTextureType(void) const { return mTextureType; } - - /** Gets the number of mipmaps to be used for this texture. - */ - uint32 getNumMipmaps(void) const {return mNumMipmaps;} - - /** Sets the number of mipmaps to be used for this texture. - @note - Must be set before calling any 'load' method. - */ - void setNumMipmaps(uint32 num) - { - mNumRequestedMipmaps = mNumMipmaps = num; - if (!num) - mUsage &= ~TU_AUTOMIPMAP; - } - - /** Are mipmaps hardware generated? - - Will only be accurate after texture load, or createInternalResources - */ - bool getMipmapsHardwareGenerated(void) const { return mMipmapsHardwareGenerated; } - - /** Returns the gamma adjustment factor applied to this texture on loading. - */ - float getGamma(void) const { return mGamma; } - - /** Sets the gamma adjustment factor applied to this texture on loading the - data. - @note - Must be called before any 'load' method. This gamma factor will - be premultiplied in and may reduce the precision of your textures. - You can use setHardwareGamma if supported to apply gamma on - sampling the texture instead. - */ - void setGamma(float g) { mGamma = g; } - - /** Sets whether this texture will be set up so that on sampling it, - hardware gamma correction is applied. - - 24-bit textures are often saved in gamma colour space; this preserves - precision in the 'darks'. However, if you're performing blending on - the sampled colours, you really want to be doing it in linear space. - One way is to apply a gamma correction value on loading (see setGamma), - but this means you lose precision in those dark colours. An alternative - is to get the hardware to do the gamma correction when reading the - texture and converting it to a floating point value for the rest of - the pipeline. This option allows you to do that; it's only supported - in relatively recent hardware (others will ignore it) but can improve - the quality of colour reproduction. - @note - Must be called before any 'load' method since it may affect the - construction of the underlying hardware resources. - Also note this only useful on textures using 8-bit colour channels. - */ - void setHardwareGammaEnabled(bool enabled) { mHwGamma = enabled; } - - /** Gets whether this texture will be set up so that on sampling it, - hardware gamma correction is applied. - */ - bool isHardwareGammaEnabled() const { return mHwGamma; } - - /** Set the level of multisample AA to be used if this texture is a - rendertarget. - @note This option will be ignored if TU_RENDERTARGET is not part of the - usage options on this texture, or if the hardware does not support it. - @param fsaa The number of samples - @param fsaaHint Any hinting text (see Root::createRenderWindow) - */ - void setFSAA(uint fsaa, const String& fsaaHint) { mFSAA = fsaa; mFSAAHint = fsaaHint; } - - /** Get the level of multisample AA to be used if this texture is a - rendertarget. - */ - uint getFSAA() const { return mFSAA; } - - /** Get the multisample AA hint if this texture is a rendertarget. - */ - const String& getFSAAHint() const { return mFSAAHint; } - - /** Returns the height of the texture. - */ - uint32 getHeight(void) const { return mHeight; } - - /** Returns the width of the texture. - */ - uint32 getWidth(void) const { return mWidth; } - - /** Returns the depth of the texture (only applicable for 3D textures). - */ - uint32 getDepth(void) const { return mDepth; } - - /** Returns the height of the original input texture (may differ due to hardware requirements). - */ - uint32 getSrcHeight(void) const { return mSrcHeight; } - - /** Returns the width of the original input texture (may differ due to hardware requirements). - */ - uint32 getSrcWidth(void) const { return mSrcWidth; } - - /** Returns the original depth of the input texture (only applicable for 3D textures). - */ - uint32 getSrcDepth(void) const { return mSrcDepth; } - - /** Set the height of the texture; can only do this before load(); - */ - void setHeight(uint32 h) { mHeight = mSrcHeight = h; } - - /** Set the width of the texture; can only do this before load(); - */ - void setWidth(uint32 w) { mWidth = mSrcWidth = w; } - - /** Set the depth of the texture (only applicable for 3D textures); - can only do this before load(); - */ - void setDepth(uint32 d) { mDepth = mSrcDepth = d; } - - /** Returns the TextureUsage identifier for this Texture - */ - int getUsage() const - { - return mUsage; - } - - /** Sets the TextureUsage identifier for this Texture; only useful before load() - - @param u is a combination of TU_STATIC, TU_DYNAMIC, TU_WRITE_ONLY - TU_AUTOMIPMAP and TU_RENDERTARGET (see TextureUsage enum). You are - strongly advised to use HBU_GPU_ONLY wherever possible, if you need to - update regularly, consider HBU_CPU_TO_GPU. - */ - void setUsage(int u) { mUsage = u; } - - /** Creates the internal texture resources for this texture. - - This method creates the internal texture resources (pixel buffers, - texture surfaces etc) required to begin using this texture. You do - not need to call this method directly unless you are manually creating - a texture, in which case something must call it, after having set the - size and format of the texture (e.g. the ManualResourceLoader might - be the best one to call it). If you are not defining a manual texture, - or if you use one of the self-contained load...() methods, then it will be - called for you. - */ - void createInternalResources(void); - - /** Copies (and maybe scales to fit) the contents of this texture to - another texture. */ - virtual void copyToTexture( TexturePtr& target ); - - /** Loads the data from an image. - @attention only call this from outside the load() routine of a - Resource. Don't call it within (including ManualResourceLoader) - use - _loadImages() instead. This method is designed to be external, - performs locking and checks the load status before loading. - */ - void loadImage( const Image &img ); - - /** Loads the data from a raw stream. - @attention only call this from outside the load() routine of a - Resource. Don't call it within (including ManualResourceLoader) - use - _loadImages() instead. This method is designed to be external, - performs locking and checks the load status before loading. - @param stream Data stream containing the raw pixel data - @param uWidth Width of the image - @param uHeight Height of the image - @param eFormat The format of the pixel data - */ - void loadRawData( DataStreamPtr& stream, - ushort uWidth, ushort uHeight, PixelFormat eFormat); - - /** Internal method to load the texture from a set of images. - @attention Do NOT call this method unless you are inside the load() routine - already, e.g. a ManualResourceLoader. It is not threadsafe and does - not check or update resource loading status. - */ - void _loadImages( const ConstImagePtrList& images ); - - /** Returns the pixel format for the texture surface. */ - PixelFormat getFormat() const - { - return mFormat; - } - - /** Returns the desired pixel format for the texture surface. */ - PixelFormat getDesiredFormat(void) const - { - return mDesiredFormat; - } - - /** Returns the pixel format of the original input texture (may differ due to - hardware requirements and pixel format conversion). - */ - PixelFormat getSrcFormat(void) const - { - return mSrcFormat; - } - - /** Sets the desired pixel format for the texture surface; can only be set before load(). */ - void setFormat(PixelFormat pf); - - /** Returns true if the texture has an alpha layer. */ - bool hasAlpha(void) const; - - /** Sets desired bit depth for integer pixel format textures. - - Available values: 0, 16 and 32, where 0 (the default) means keep original format - as it is. This value is number of bits for the pixel. - */ - void setDesiredIntegerBitDepth(ushort bits); - - /** gets desired bit depth for integer pixel format textures. - */ - ushort getDesiredIntegerBitDepth(void) const; - - /** Sets desired bit depth for float pixel format textures. - - Available values: 0, 16 and 32, where 0 (the default) means keep original format - as it is. This value is number of bits for a channel of the pixel. - */ - void setDesiredFloatBitDepth(ushort bits); - - /** gets desired bit depth for float pixel format textures. - */ - ushort getDesiredFloatBitDepth(void) const; - - /** Sets desired bit depth for integer and float pixel format. - */ - void setDesiredBitDepths(ushort integerBits, ushort floatBits); - - /// @deprecated use setFormat(PF_A8) - OGRE_DEPRECATED void setTreatLuminanceAsAlpha(bool asAlpha); - - /** Return the number of faces this texture has. This will be 6 for a cubemap - texture and 1 for a 1D, 2D or 3D one. - */ - uint32 getNumFaces() const; - - /** Return hardware pixel buffer for a surface. This buffer can then - be used to copy data from and to a particular level of the texture. - @param face Face number, in case of a cubemap texture. Must be 0 - for other types of textures. - For cubemaps, this is one of - +X (0), -X (1), +Y (2), -Y (3), +Z (4), -Z (5) - @param mipmap Mipmap level. This goes from 0 for the first, largest - mipmap level to getNumMipmaps()-1 for the smallest. - @return A shared pointer to a hardware pixel buffer. - @remarks The buffer is invalidated when the resource is unloaded or destroyed. - Do not use it after the lifetime of the containing texture. - */ - virtual const HardwarePixelBufferSharedPtr& getBuffer(size_t face=0, size_t mipmap=0); - - - /** Populate an Image with the contents of this texture. - @param destImage The target image (contents will be overwritten) - @param includeMipMaps Whether to embed mipmaps in the image - */ - void convertToImage(Image& destImage, bool includeMipMaps = false); - - /** Retrieve a platform or API-specific piece of information from this texture. - This method of retrieving information should only be used if you know what you're doing. - - | Name | Description | - |-------------|------------------------------| - | GLID | The OpenGL texture object id | - - @param name The name of the attribute to retrieve. - @param pData Pointer to memory matching the type of data you want to retrieve. - */ - virtual void getCustomAttribute(const String& name, void* pData); - - /** simplified API for bindings - * - * @overload - */ - uint getCustomAttribute(const String& name) - { - uint ret = 0; - getCustomAttribute(name, &ret); - return ret; - } - - /** Enable read and/or write privileges to the texture from shaders. - @param bindPoint The buffer binding location for shader access. For OpenGL this must be unique and is not related to the texture binding point. - @param access The texture access privileges given to the shader. - @param mipmapLevel The texture mipmap level to use. - @param textureArrayIndex The index of the texture array to use. If texture is not a texture array, set to 0. - @param format Texture format to be read in by shader. For OpenGL this may be different than the bound texture format. - */ - virtual void createShaderAccessPoint(uint bindPoint, TextureAccess access = TA_READ_WRITE, - int mipmapLevel = 0, int textureArrayIndex = 0, - PixelFormat format = PF_UNKNOWN) {} - /** Set image names to be loaded as layers (3d & texture array) or cubemap faces - */ - void setLayerNames(const std::vector& names) - { - mLayerNames = names; - } - - protected: - uint32 mHeight; - uint32 mWidth; - uint32 mDepth; - - uint32 mNumRequestedMipmaps; - uint32 mNumMipmaps; - - float mGamma; - uint mFSAA; - - PixelFormat mFormat; - int mUsage; /// Bit field, so this can't be TextureUsage - - PixelFormat mSrcFormat; - uint32 mSrcWidth, mSrcHeight, mSrcDepth; - - bool mTreatLuminanceAsAlpha; - bool mInternalResourcesCreated; - bool mMipmapsHardwareGenerated; - bool mHwGamma; - - String mFSAAHint; - - /// Vector of pointers to subsurfaces - typedef std::vector SurfaceList; - SurfaceList mSurfaceList; - - TextureType mTextureType; - - void prepareImpl() override; - void unprepareImpl() override; - void loadImpl() override; - - /// @copydoc Resource::calculateSize - size_t calculateSize(void) const override; - - - /** Implementation of creating internal texture resources - */ - virtual void createInternalResourcesImpl(void) = 0; - - /** Implementation of freeing internal texture resources - */ - virtual void freeInternalResourcesImpl(void) = 0; - - /** Default implementation of unload which calls freeInternalResources */ - void unloadImpl(void) override; - - /** Returns the maximum number of Mipmaps that can be generated until we reach - the mininum possible size. This does not count the base level. - - @return how many times we can divide this texture in 2 until we reach 1x1. - */ - uint32 getMaxMipmaps() const; - - private: - uchar mDesiredIntegerBitDepth; - uchar mDesiredFloatBitDepth; - PixelFormat mDesiredFormat; - - /// vector of images that should be loaded (cubemap/ texture array) - std::vector mLayerNames; - - /** Vector of images that were pulled from disk by - prepareLoad but have yet to be pushed into texture memory - by loadImpl. Images should be deleted by loadImpl and unprepareImpl. - */ - typedef std::vector LoadedImages; - LoadedImages mLoadedImages; - - void readImage(LoadedImages& imgs, const String& name, const String& ext, bool haveNPOT); - void freeInternalResources(void); - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreTextureManager.h b/OgreMain/include/OgreTextureManager.h deleted file mode 100644 index aa17e9f56fa..00000000000 --- a/OgreMain/include/OgreTextureManager.h +++ /dev/null @@ -1,464 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _TextureManager_H__ -#define _TextureManager_H__ - - -#include "OgrePrerequisites.h" - -#include "OgreResourceManager.h" -#include "OgreTexture.h" -#include "OgreSingleton.h" -#include "OgreTextureUnitState.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - /** Class for loading & managing textures. - - Note that this class is abstract - the particular - RenderSystem that is in use at the time will create - a concrete subclass of this. Note that the concrete - class will be available via the abstract singleton - obtained from TextureManager::getSingleton(), but - you should not assume that it is available until you - have a) initialised Ogre (after selecting a RenderSystem - and calling initialise from the Root object), and b) - created at least one window - this may be done at the - same time as part a if you allow Ogre to autocreate one. - */ - class _OgreExport TextureManager : public ResourceManager, public Singleton - { - public: - - TextureManager(void); - virtual ~TextureManager(); - - /// create a new sampler - SamplerPtr createSampler(const String& name = BLANKSTRING); - - /// retrieve an named sampler - const SamplerPtr& getSampler(const String& name) const; - - /// clear the list of named samplers - /// @copydetails removeAll() - void removeAllNamedSamplers() { mNamedSamplers.clear(); } - - /// Create a new texture - /// @copydetails ResourceManager::createResource - TexturePtr create (const String& name, const String& group, - bool isManual = false, ManualResourceLoader* loader = 0, - const NameValuePairList* createParams = 0); - /// @copydoc ResourceManager::getResourceByName - TexturePtr getByName(const String& name, const String& groupName OGRE_RESOURCE_GROUP_INIT) const; - - using ResourceManager::createOrRetrieve; - - /** @overload createOrRetrieve - - @copydetails ResourceManager::createResource - - @param - texType The type of texture to load/create, defaults to normal 2D textures - @param - numMipmaps The number of pre-filtered mipmaps to generate. If left to MIP_DEFAULT then - the TextureManager's default number of mipmaps will be used (see setDefaultNumMipmaps()) - If set to MIP_UNLIMITED mipmaps will be generated until the lowest possible - level, 1x1x1. - @param - gamma The gamma adjustment factor to apply to this texture (brightening/darkening) - @param - isAlpha deprecated: same as specifying #PF_A8 for @c desiredFormat - @param - desiredFormat The format you would like to have used instead of - the format being based on the contents of the texture - @param hwGammaCorrection Pass 'true' to enable hardware gamma correction - (sRGB) on this texture. The hardware will convert from gamma space - to linear space when reading from this texture. Only applicable for - 8-bits per channel textures, will be ignored for other types. Has the advantage - over pre-applied gamma that the texture precision is maintained. - */ - ResourceCreateOrRetrieveResult createOrRetrieve( - const String &name, const String& group, bool isManual, - ManualResourceLoader* loader, const NameValuePairList* createParams, - TextureType texType, int numMipmaps = MIP_DEFAULT, - Real gamma = 1.0f, bool isAlpha = false, - PixelFormat desiredFormat = PF_UNKNOWN, bool hwGammaCorrection = false); - - /** Prepares to loads a texture from a file. - @copydetails TextureManager::load - @param isAlpha deprecated: same as specifying #PF_A8 for @c desiredFormat - */ - TexturePtr prepare( - const String& name, const String& group, - TextureType texType = TEX_TYPE_2D, int numMipmaps = MIP_DEFAULT, - Real gamma = 1.0f, bool isAlpha = false, - PixelFormat desiredFormat = PF_UNKNOWN, bool hwGammaCorrection = false); - - /** Loads a texture from a file. - @param - name The file to load, or a String identifier in some cases - @param - group The name of the resource group to assign the texture to - @param - texType The type of texture to load/create, defaults to normal 2D textures - @param - numMipmaps The number of pre-filtered mipmaps to generate. If left to MIP_DEFAULT then - the TextureManager's default number of mipmaps will be used (see setDefaultNumMipmaps()) - If set to MIP_UNLIMITED mipmaps will be generated until the lowest possible - level, 1x1x1. - @param - gamma The gamma adjustment factor to apply to this texture (brightening/darkening) - - @param - desiredFormat The format you would like to have used instead of - the format being based on the contents of the texture; the manager reserves - the right to create a different format for the texture if the - original format is not available in this context. - @param hwGammaCorrection pass 'true' to enable hardware gamma correction - (sRGB) on this texture. The hardware will convert from gamma space - to linear space when reading from this texture. Only applicable for - 8-bits per channel textures, will be ignored for other types. Has the advantage - over pre-applied gamma that the texture precision is maintained. - */ - TexturePtr load(const String& name, const String& group, TextureType texType = TEX_TYPE_2D, - int numMipmaps = MIP_DEFAULT, Real gamma = 1.0f, - PixelFormat desiredFormat = PF_UNKNOWN, bool hwGammaCorrection = false); - /// @deprecated - OGRE_DEPRECATED TexturePtr load(const String& name, const String& group, TextureType texType, - int numMipmaps, Real gamma, bool isAlpha, - PixelFormat desiredFormat = PF_UNKNOWN, - bool hwGammaCorrection = false); - - /** Loads a texture from an Image object. - @note - The texture will create as manual texture without loader. - @copydetails TextureManager::prepare - @param - img The Image object which contains the data to load - */ - virtual TexturePtr loadImage( - const String &name, const String& group, const Image &img, - TextureType texType = TEX_TYPE_2D, - int numMipmaps = MIP_DEFAULT, Real gamma = 1.0f, bool isAlpha = false, - PixelFormat desiredFormat = PF_UNKNOWN, bool hwGammaCorrection = false); - - /** Loads a texture from a raw data stream. - @note - The texture will create as manual texture without loader. - @param name - The name to give the resulting texture - @param group - The name of the resource group to assign the texture to - @param stream - Incoming data stream - @param width - The width of the texture - @param height - The height of the texture - @param format - The format of the data being passed in; the manager reserves - the right to create a different format for the texture if the - original format is not available in this context. - @param texType - The type of texture to load/create, defaults to normal 2D textures - @param numMipmaps - The number of pre-filtered mipmaps to generate. If left to MIP_DEFAULT then - the TextureManager's default number of mipmaps will be used (see setDefaultNumMipmaps()) - If set to MIP_UNLIMITED mipmaps will be generated until the lowest possible - level, 1x1x1. - @param gamma - The gamma adjustment factor to apply to this texture (brightening/darkening) - while loading - @param hwGammaCorrection Pass 'true' to enable hardware gamma correction - (sRGB) on this texture. The hardware will convert from gamma space - to linear space when reading from this texture. Only applicable for - 8-bits per channel textures, will be ignored for other types. Has the advantage - over pre-applied gamma that the texture precision is maintained. - */ - virtual TexturePtr loadRawData(const String &name, const String& group, - DataStreamPtr& stream, ushort width, ushort height, - PixelFormat format, TextureType texType = TEX_TYPE_2D, - int numMipmaps = MIP_DEFAULT, Real gamma = 1.0f, bool hwGammaCorrection = false); - - /** Create a manual texture with specified width, height and depth (not loaded from a file). - @param - name The name to give the resulting texture - @param - group The name of the resource group to assign the texture to - @param - texType The type of texture to load/create, defaults to normal 2D textures - @param width - The width of the texture - @param height - The height of the texture - @param depth - The depth of the texture - @param - numMipmaps The number of pre-filtered mipmaps to generate. If left to MIP_DEFAULT then - the TextureManager's default number of mipmaps will be used (see setDefaultNumMipmaps()) - If set to MIP_UNLIMITED mipmaps will be generated until the lowest possible - level, 1x1x1. - @param - format The internal format you wish to request; the manager reserves - the right to create a different format if the one you select is - not available in this context. - @param - usage The kind of usage this texture is intended for. It - is a combination of TU_STATIC, TU_DYNAMIC, TU_WRITE_ONLY, - TU_AUTOMIPMAP and TU_RENDERTARGET (see TextureUsage enum). You are - strongly advised to use HBU_GPU_ONLY wherever possible, if you need to - update regularly, consider HBU_CPU_TO_GPU. - @param - loader If you intend the contents of the manual texture to be - regularly updated, to the extent that you don't need to recover - the contents if the texture content is lost somehow, you can leave - this parameter as 0. However, if you intend to populate the - texture only once, then you should implement ManualResourceLoader - and pass a pointer to it in this parameter; this means that if the - manual texture ever needs to be reloaded, the ManualResourceLoader - will be called to do it. - @param hwGammaCorrection pass 'true' to enable hardware gamma correction - (sRGB) on this texture. The hardware will convert from gamma space - to linear space when reading from this texture. Only applicable for - 8-bits per channel textures, will be ignored for other types. Has the advantage - over pre-applied gamma that the texture precision is maintained. - @param fsaa The level of multisampling to use if this is a render target. Ignored - if usage does not include TU_RENDERTARGET or if the device does - not support it. - @param fsaaHint @copybrief RenderTarget::getFSAAHint - */ - virtual TexturePtr createManual(const String & name, const String& group, - TextureType texType, uint width, uint height, uint depth, - int numMipmaps, PixelFormat format, int usage = TU_DEFAULT, ManualResourceLoader* loader = 0, - bool hwGammaCorrection = false, uint fsaa = 0, const String& fsaaHint = BLANKSTRING); - - /** @overload - */ - TexturePtr createManual(const String & name, const String& group, - TextureType texType, uint width, uint height, int numMipmaps, - PixelFormat format, int usage = TU_DEFAULT, ManualResourceLoader* loader = 0, - bool hwGammaCorrection = false, uint fsaa = 0, const String& fsaaHint = BLANKSTRING) - { - return createManual(name, group, texType, width, height, 1, - numMipmaps, format, usage, loader, hwGammaCorrection, fsaa, fsaaHint); - } - - /** Sets preferred bit depth for integer pixel format textures. - @param - bits Number of bits. Available values: 0, 16 and 32, where 0 (the default) means keep - original format as it is. This value is number of bits for the pixel. - @param - reloadTextures If true (the default), will reloading all reloadable textures. - */ - virtual void setPreferredIntegerBitDepth(ushort bits, bool reloadTextures = true); - - /** Gets preferred bit depth for integer pixel format textures. - */ - virtual ushort getPreferredIntegerBitDepth(void) const; - - /** Sets preferred bit depth for float pixel format textures. - @param - bits Number of bits. Available values: 0, 16 and 32, where 0 (the default) means keep - original format as it is. This value is number of bits for a channel of the pixel. - @param - reloadTextures If true (the default), will reloading all reloadable textures. - */ - virtual void setPreferredFloatBitDepth(ushort bits, bool reloadTextures = true); - - /** Gets preferred bit depth for float pixel format textures. - */ - virtual ushort getPreferredFloatBitDepth(void) const; - - /** Sets preferred bit depth for integer and float pixel format. - @param - integerBits Number of bits. Available values: 0, 16 and 32, where 0 (the default) means keep - original format as it is. This value is number of bits for the pixel. - @param - floatBits Number of bits. Available values: 0, 16 and 32, where 0 (the default) means keep - original format as it is. This value is number of bits for a channel of the pixel. - @param - reloadTextures If true (the default), will reloading all reloadable textures. - */ - virtual void setPreferredBitDepths(ushort integerBits, ushort floatBits, bool reloadTextures = true); - - /** Returns whether this render system can natively support the precise texture - format requested with the given usage options. - - You can still create textures with this format even if this method returns - false; the texture format will just be altered to one which the device does - support. - @note - Sometimes the device may just slightly change the format, such as reordering the - channels or packing the channels differently, without it making and qualitative - differences to the texture. If you want to just detect whether the quality of a - given texture will be reduced, use isEquivalentFormatSupport instead. - @param ttype The type of texture - @param format The pixel format requested - @param usage The kind of usage this texture is intended for, a combination of - the TextureUsage flags. - @return true if the format is natively supported, false if a fallback would be used. - */ - virtual bool isFormatSupported(TextureType ttype, PixelFormat format, int usage); - - /** Returns whether this render system can support the texture format requested - with the given usage options, or another format with no quality reduction. - */ - virtual bool isEquivalentFormatSupported(TextureType ttype, PixelFormat format, int usage); - - /** Gets the format which will be natively used for a requested format given the - constraints of the current device. - */ - virtual PixelFormat getNativeFormat(TextureType ttype, PixelFormat format, int usage) = 0; - - /** Returns whether this render system has hardware filtering supported for the - texture format requested with the given usage options. - - Not all texture format are supports filtering by the hardware, i.e. some - cards support floating point format, but it doesn't supports filtering on - the floating point texture at all, or only a subset floating point formats - have flitering supported. - @par - In the case you want to write shader to work with floating point texture, and - you want to produce better visual quality, it's necessary to flitering the - texture manually in shader (potential requires four or more texture fetch - instructions, plus several arithmetic instructions) if filtering doesn't - supported by hardware. But in case on the hardware that supports floating - point filtering natively, it had better to adopt this capability for - performance (because only one texture fetch instruction are required) and - doesn't loss visual quality. - @par - This method allow you queries hardware texture filtering capability to deciding - which version of the shader to be used. Note it's up to you to write multi-version - shaders for support various hardware, internal engine can't do that for you - automatically. - @note - Under GL, texture filtering are always supported by driver, but if it's not - supported by hardware natively, software simulation will be used, and you - will end up with very slow speed (less than 0.1 fps for example). To slove - this performance problem, you must disable filtering manually (by use - filtering none in the material script's texture_unit section, or - call TextureUnitState::setTextureFiltering with TFO_NONE if populate - material in code). - @param ttype The texture type requested - @param format The pixel format requested - @param usage The kind of usage this texture is intended for, a combination of - the TextureUsage flags. - @param preciseFormatOnly Whether precise or fallback format mode is used to detecting. - In case the pixel format doesn't supported by device, false will be returned - if in precise mode, and natively used pixel format will be actually use to - check if in fallback mode. - @return true if the texture filtering is supported. - */ - virtual bool isHardwareFilteringSupported(TextureType ttype, PixelFormat format, int usage, - bool preciseFormatOnly = false); - - /** Sets the default number of mipmaps to be used for loaded textures, for when textures are - loaded automatically (e.g. by Material class) or when 'load' is called with the default - parameters by the application. - If set to MIP_UNLIMITED mipmaps will be generated until the lowest possible - level, 1x1x1. - @note - The default value is 0. - */ - virtual void setDefaultNumMipmaps(uint32 num); - - /** Gets the default number of mipmaps to be used for loaded textures. - */ - virtual uint32 getDefaultNumMipmaps() - { - return mDefaultNumMipmaps; - } - - /// Internal method to create a warning texture (bound when a texture unit is blank) - const TexturePtr& _getWarningTexture(); - - /// get the default sampler - const SamplerPtr& getDefaultSampler(); - - /// @copydoc Singleton::getSingleton() - static TextureManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static TextureManager* getSingletonPtr(void); - - protected: - - virtual SamplerPtr _createSamplerImpl() { return std::make_shared(); } - - ushort mPreferredIntegerBitDepth; - ushort mPreferredFloatBitDepth; - uint32 mDefaultNumMipmaps; - TexturePtr mWarningTexture; - SamplerPtr mDefaultSampler; - std::map mNamedSamplers; - }; - - /// Specialisation of TextureManager for offline processing. Cannot be used with an active RenderSystem. - class _OgreExport DefaultTextureManager : public TextureManager - { - /// noop implementation - class NullTexture : public Texture - { - public: - NullTexture(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group) - : Texture(creator, name, handle, group) - { - } - const HardwarePixelBufferSharedPtr& getBuffer(size_t, size_t) override - { - static HardwarePixelBufferSharedPtr nullBuffer; - return nullBuffer; - } - - protected: - void createInternalResourcesImpl() override {} - void freeInternalResourcesImpl() override {} - void loadImpl() override {} - }; - - Resource* createImpl(const String& name, ResourceHandle handle, const String& group, bool, - ManualResourceLoader*, const NameValuePairList*) override - { - return new NullTexture(this, name, handle, group); - } - - public: - bool isHardwareFilteringSupported(TextureType, PixelFormat, int, bool) override { return false; } - PixelFormat getNativeFormat(TextureType, PixelFormat, int) override { return PF_UNKNOWN; } - }; - /** @} */ - /** @} */ -}// Namespace - -#endif diff --git a/OgreMain/include/OgreTextureUnitState.h b/OgreMain/include/OgreTextureUnitState.h deleted file mode 100644 index 06ea470af2d..00000000000 --- a/OgreMain/include/OgreTextureUnitState.h +++ /dev/null @@ -1,1140 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __TextureUnitState_H__ -#define __TextureUnitState_H__ - -#include "OgrePrerequisites.h" -#include "OgreCommon.h" -#include "OgreBlendMode.h" -#include "OgreMatrix4.h" -#include "OgreTexture.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - enum TexCoordCalcMethod : uint8; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Materials - * @{ - */ - - /** Class which determines how a TextureUnitState accesses data from a Texture - - There are a number of parameters affecting how texture data is fetched. - Most notably @ref FilterOptions and @ref TextureAddressingMode. - */ - class _OgreExport Sampler { - public: - /** Texture addressing mode for each texture coordinate. */ - struct UVWAddressingMode - { - TextureAddressingMode u, v, w; - }; - - /// must be created through TextureManager - Sampler(); - virtual ~Sampler(); - - /** Set the texture filtering for this unit, using the simplified interface. - - You also have the option of specifying the minification, magnification - and mip filter individually if you want more control over filtering - options. See the alternative setTextureFiltering methods for details. - @param filterType - The high-level filter type to use. - */ - void setFiltering(TextureFilterOptions filterType); - /** Set a single filtering option on this texture unit. - @param ftype - The filtering type to set. - @param opts - The filtering option to set. - */ - void setFiltering(FilterType ftype, FilterOptions opts); - /** Set a the detailed filtering options on this texture unit. - @param minFilter - The filtering to use when reducing the size of the texture. - Can be Ogre::FO_POINT, Ogre::FO_LINEAR or Ogre::FO_ANISOTROPIC. - @param magFilter - The filtering to use when increasing the size of the texture. - Can be Ogre::FO_POINT, Ogre::FO_LINEAR or Ogre::FO_ANISOTROPIC. - @param mipFilter - The filtering to use between mip levels. - Can be Ogre::FO_NONE (turns off mipmapping), Ogre::FO_POINT or Ogre::FO_LINEAR (trilinear filtering). - */ - void setFiltering(FilterOptions minFilter, FilterOptions magFilter, FilterOptions mipFilter); - /// Get the texture filtering for the given type. - FilterOptions getFiltering(FilterType ftype) const; - - /** Gets the texture addressing mode for a given coordinate, - i.e. what happens at uv values above 1.0. - @note - The default is TAM_WRAP i.e. the texture repeats over values of 1.0. - */ - const UVWAddressingMode& getAddressingMode() const { return mAddressMode; } - - /** Sets the texture addressing mode, i.e. what happens at uv values above 1.0. - - The default is TAM_WRAP i.e. the texture repeats over values of 1.0. - This is a shortcut method which sets the addressing mode for all - coordinates at once; you can also call the more specific method - to set the addressing mode per coordinate. - - This is a shortcut method which sets the addressing mode for all - coordinates at once; you can also call the more specific method - to set the addressing mode per coordinate. - */ - void setAddressingMode(TextureAddressingMode tam) { setAddressingMode({tam, tam, tam}); } - - /** Sets the texture addressing mode, i.e. what happens at uv values above 1.0. - - The default is #TAM_WRAP i.e. the texture repeats over values of 1.0. - */ - void setAddressingMode(TextureAddressingMode u, TextureAddressingMode v, - TextureAddressingMode w) - { - setAddressingMode({u, v, w}); - } - /// @overload - void setAddressingMode(const UVWAddressingMode& uvw); - - /** Sets the anisotropy level to be used for this texture level. - - The degree of anisotropy is the ratio between the height of the texture segment visible in a - screen space region versus the width - so for example a floor plane, which stretches on into - the distance and thus the vertical texture coordinates change much faster than the - horizontal ones, has a higher anisotropy than a wall which is facing you head on (which has - an anisotropy of 1 if your line of sight is perfectly perpendicular to it).The maximum value - is determined by the hardware, but it is usually 8 or 16. - - In order for this to be used, you have to set the minification and/or the magnification - option on this texture to Ogre::FO_ANISOTROPIC. - @param maxAniso - The maximal anisotropy level, should be between 2 and the maximum - supported by hardware (1 is the default, ie. no anisotropy). - */ - void setAnisotropy(unsigned int maxAniso) - { - mMaxAniso = maxAniso; - mDirty = true; - } - /// Get this layer texture anisotropy level. - unsigned int getAnisotropy() const { return mMaxAniso; } - - /** Sets the bias value applied to the mipmap calculation. - - You can alter the mipmap calculation by biasing the result with a - single floating point value. After the mip level has been calculated, - this bias value is added to the result to give the final mip level. - Lower mip levels are larger (higher detail), so a negative bias will - force the larger mip levels to be used, and a positive bias - will cause smaller mip levels to be used. The bias values are in - mip levels, so a -1 bias will force mip levels one larger than by the - default calculation. - - In order for this option to be used, your hardware has to support mipmap biasing - (exposed through Ogre::RSC_MIPMAP_LOD_BIAS), and your minification filtering has to be - set to point or linear. - */ - void setMipmapBias(float bias) - { - mMipmapBias = bias; - mDirty = true; - } - /** Gets the bias value applied to the mipmap calculation. - @see TextureUnitState::setTextureMipmapBias - */ - float getMipmapBias(void) const { return mMipmapBias; } - - /** Enables or disables the comparison test for depth textures. - * - * When enabled, sampling the texture returns how the sampled value compares against a - * reference value instead of the sampled value itself. Combined with linear filtering this - * can be used to implement hardware PCF for shadow maps. - */ - void setCompareEnabled(bool enabled) - { - mCompareEnabled = enabled; - mDirty = true; - } - bool getCompareEnabled() const { return mCompareEnabled; } - - void setCompareFunction(CompareFunction function) - { - mCompareFunc = function; - mDirty = true; - } - CompareFunction getCompareFunction() const { return mCompareFunc; } - - /** Sets the texture border colour. - - The default is ColourValue::Black, and this value only used when addressing mode - is TAM_BORDER. - */ - void setBorderColour(const ColourValue& colour) - { - mBorderColour = colour; - mDirty = true; - } - const ColourValue& getBorderColour(void) const { return mBorderColour; } - - protected: - ColourValue mBorderColour; - /// Texture anisotropy. - unsigned int mMaxAniso; - /// Mipmap bias (always float, not Real). - float mMipmapBias; - UVWAddressingMode mAddressMode; - /// Texture filtering - minification. - FilterOptions mMinFilter; - /// Texture filtering - magnification. - FilterOptions mMagFilter; - /// Texture filtering - mipmapping. - FilterOptions mMipFilter; - CompareFunction mCompareFunc; - bool mCompareEnabled : 1; - bool mDirty : 1; // flag for derived classes to sync with implementation - }; - typedef std::shared_ptr SamplerPtr; - - /** Class representing the state of a single texture unit during a Pass of a - Technique, of a Material. - - Texture units are pipelines for retrieving texture data for rendering onto - your objects in the world. Using them is common to both the fixed-function and - the programmable (vertex and fragment program) pipeline, but some of the - settings will only have an effect in the fixed-function pipeline (for example, - setting a texture rotation will have no effect if you use the programmable - pipeline, because this is overridden by the fragment program). The effect - of each setting as regards the 2 pipelines is commented in each setting. - - When I use the term 'fixed-function pipeline' I mean traditional rendering - where you do not use vertex or fragment programs (shaders). Programmable - pipeline means that for this pass you are using vertex or fragment programs. - */ - class _OgreExport TextureUnitState : public TextureUnitStateAlloc - { - friend class RenderSystem; - public: - /** Definition of the broad types of texture effect you can apply to a texture unit. - */ - enum TextureEffectType - { - /// Generate all texture coords based on angle between camera and vertex. - ET_ENVIRONMENT_MAP, - /// Generate texture coords based on a frustum. - ET_PROJECTIVE_TEXTURE, - /// Constant u/v scrolling effect. - ET_UVSCROLL, - /// Constant u scrolling effect. - ET_USCROLL, - /// Constant u/v scrolling effect. - ET_VSCROLL, - /// Constant rotation. - ET_ROTATE, - /// More complex transform. - ET_TRANSFORM - - }; - - /// %Texture coordinate generation method for environment mapping. - enum EnvMapType - { - /// 2D texture coordinates using view space position. Same as ENV_CURVED on all backends. - ENV_PLANAR, - /// 2D texture coordinates using spherical reflection mapping - ENV_CURVED, - /// Cubic texture coordinates using the reflection vector - ENV_REFLECTION, - /// Cubic texture coordinates using the normal vector - ENV_NORMAL - }; - - /** Useful enumeration when dealing with procedural transforms. - */ - enum TextureTransformType - { - TT_TRANSLATE_U, - TT_TRANSLATE_V, - TT_SCALE_U, - TT_SCALE_V, - TT_ROTATE - }; - - - static const Ogre::TextureAddressingMode TAM_WRAP = Ogre::TAM_WRAP; - static const Ogre::TextureAddressingMode TAM_MIRROR = Ogre::TAM_MIRROR; - static const Ogre::TextureAddressingMode TAM_CLAMP = Ogre::TAM_CLAMP; - static const Ogre::TextureAddressingMode TAM_BORDER = Ogre::TAM_BORDER; - - OGRE_DEPRECATED typedef Ogre::TextureAddressingMode TextureAddressingMode; - OGRE_DEPRECATED typedef Sampler::UVWAddressingMode UVWAddressingMode; - - /** Enum identifying the frame indexes for faces of a cube map (not the composite 3D type. - */ - enum TextureCubeFace - { - CUBE_FRONT = 0, - CUBE_BACK = 1, - CUBE_LEFT = 2, - CUBE_RIGHT = 3, - CUBE_UP = 4, - CUBE_DOWN = 5 - }; - - /** Internal structure defining a texture effect. - */ - struct TextureEffect { - TextureEffectType type; - int subtype; - Real arg1, arg2; - WaveformType waveType; - Real base; - Real frequency; - Real phase; - Real amplitude; - ControllerFloat* controller; - const Frustum* frustum; - }; - - /** Texture effects in a multimap paired array. - */ - typedef std::multimap EffectMap; - - /** Default constructor. - */ - TextureUnitState(Pass* parent); - - TextureUnitState(Pass* parent, const TextureUnitState& oth ); - - TextureUnitState & operator = ( const TextureUnitState& oth ); - - /** Default destructor. - */ - ~TextureUnitState(); - - /** Name-based constructor. - @param parent the parent Pass object. - @param texName - The basic name of the texture e.g. brickwall.jpg, stonefloor.png. - @param texCoordSet - The index of the texture coordinate set to use. - */ - TextureUnitState( Pass* parent, const String& texName, uint8 texCoordSet = 0); - - /** Get the name of current texture image for this layer. - - This will either always be a single name for this layer, - or will be the name of the current frame for an animated - or otherwise multi-frame texture. - */ - const String& getTextureName(void) const; - - /** Sets this texture layer to use a single texture, given the - name of the texture to use on this layer. - */ - void setTextureName( const String& name); - - /// @overload - void setTextureName( const String& name, TextureType ttype); - - /** Sets this texture layer to use a single texture, given the - pointer to the texture to use on this layer. - */ - void setTexture( const TexturePtr& texPtr); - - /** - @deprecated use setTextureName() - */ - OGRE_DEPRECATED void setCubicTextureName( const String& name, bool forUVW = false ) - { - setTextureName(name, TEX_TYPE_CUBE_MAP); - } - - /** - @deprecated use setLayerArrayNames() - */ - OGRE_DEPRECATED void setCubicTextureName( const String* const names, bool forUVW = false ); - - /** - @deprecated use setTexture() - */ - OGRE_DEPRECATED void setCubicTexture( const TexturePtr* const texPtrs, bool forUVW = false ) - { - setTexture(*texPtrs); - } - - /** Sets the names of the texture images for an animated texture. - - Animated textures are just a series of images making up the frames of the animation. All the images - must be the same size, and their names must have a frame number appended before the extension, e.g. - if you specify a name of "flame.jpg" with 3 frames, the image names must be "flame_0.jpg", "flame_1.jpg" - and "flame_2.jpg". - - You can change the active frame on a texture layer by calling the Ogre::TextureUnitState::setCurrentFrame method. - @note - If you can't make your texture images conform to the naming standard laid out here, you - can call the alternative setAnimatedTextureName method which takes an array of names instead. - @param name - The base name of the textures to use e.g. flame.jpg for frames flame_0.jpg, flame_1.jpg etc. - @param numFrames - The number of frames in the sequence. - @param duration - The length of time it takes to display the whole animation sequence, in seconds. - If 0, no automatic transition occurs. - */ - void setAnimatedTextureName( const String& name, size_t numFrames, Real duration = 0 ); - - /// @overload - /// @deprecated use setAnimatedTextureName( const std::vector&, Real ) - void setAnimatedTextureName( const String* const names, size_t numFrames, Real duration = 0 ); - - /// @overload - void setAnimatedTextureName( const std::vector& names, Real duration = 0 ) - { - setAnimatedTextureName(names.data(), names.size(), duration); - } - - /// Sets this texture layer to use an array of texture maps - void setLayerArrayNames(TextureType type, const std::vector& names); - - /** Returns the width and height of the texture in the given frame. - */ - std::pair getTextureDimensions(unsigned int frame = 0) const; - - /** Changes the active frame in an animated or multi-image texture. - - An animated texture (or a cubic texture where the images are not combined for 3D use) is made up of - a number of frames. This method sets the active frame. - */ - void setCurrentFrame( unsigned int frameNumber ); - - /** Gets the active frame in an animated or multi-image texture layer. - */ - unsigned int getCurrentFrame(void) const; - - /** Gets the name of the texture associated with a frame number. - Throws an exception if frameNumber exceeds the number of stored frames. - */ - const String& getFrameTextureName(unsigned int frameNumber) const; - - /** Sets the name of the texture associated with a frame. - @param name - The name of the texture. - @param frameNumber - The frame the texture name is to be placed in. - @note - Throws an exception if frameNumber exceeds the number of stored frames. - */ - void setFrameTextureName(const String& name, unsigned int frameNumber); - - /** Add a Texture name to the end of the frame container. - @param name - The name of the texture. - */ - void addFrameTextureName(const String& name); - /** Deletes a specific texture frame. The texture used is not deleted but the - texture will no longer be used by the Texture Unit. An exception is raised - if the frame number exceeds the number of actual frames. - @param frameNumber - The frame number of the texture to be deleted. - */ - void deleteFrameTextureName(const size_t frameNumber); - /** Gets the number of frames for a texture. - */ - unsigned int getNumFrames(void) const; - - /** Enum identifying the type of content this texture unit contains. - */ - enum ContentType : uint8 - { - /// The default option, this derives texture content from a texture name, loaded by - /// ordinary means from a file or having been manually created with a given name. - CONTENT_NAMED = 0, - /// A shadow texture, automatically bound by engine - CONTENT_SHADOW = 1, - /// This option allows you to reference a texture from a compositor, and is only valid - /// when the pass is rendered within a compositor sequence. - CONTENT_COMPOSITOR = 2 - }; - - /** Set the type of content this TextureUnitState references. - - The default is to reference a standard named texture, but this unit - can also reference automated content like a shadow texture. - */ - void setContentType(ContentType ct); - /** Get the type of content this TextureUnitState references. */ - ContentType getContentType(void) const; - - /// @deprecated use getTextureType() - OGRE_DEPRECATED bool isCubic(void) const { return getTextureType() == TEX_TYPE_CUBE_MAP; } - - /// @deprecated use getTextureType() - OGRE_DEPRECATED bool is3D(void) const { return getTextureType() == TEX_TYPE_CUBE_MAP; } - - /** Returns the type of this texture. - */ - TextureType getTextureType(void) const; - - /// @copydoc Texture::setFormat - void setDesiredFormat(PixelFormat desiredFormat); - - /// @copydoc Texture::getDesiredFormat - PixelFormat getDesiredFormat(void) const; - - /// @copydoc Texture::setNumMipmaps - void setNumMipmaps(int numMipmaps); - - /** Gets how many mipmaps have been requested for the texture. - */ - int getNumMipmaps(void) const; - - /// @deprecated use setDesiredFormat(PF_A8) - OGRE_DEPRECATED void setIsAlpha(bool isAlpha); - - /// @copydoc Texture::getGamma - float getGamma() const; - /// @copydoc Texture::setGamma - void setGamma(float gamma); - - /// @copydoc Texture::setHardwareGammaEnabled - void setHardwareGammaEnabled(bool enabled); - /// @copydoc Texture::isHardwareGammaEnabled - bool isHardwareGammaEnabled() const; - - /** Gets the index of the set of texture co-ords this layer uses. - @note - Only applies to the fixed function pipeline and has no effect if a fragment program is used. - */ - uint8 getTextureCoordSet(void) const; - - /** Sets which texture coordinate set is to be used for this texture layer. - - A mesh can define multiple sets of texture coordinates, this sets which one this - material uses. - */ - void setTextureCoordSet(uint8 set); - - /// Enables Unordered Access to the provided mipLevel of the texture - void setUnorderedAccessMipLevel(int mipLevel) { mUnorderedAccessMipLevel = mipLevel; } - int getUnorderedAccessMipLevel() const { return mUnorderedAccessMipLevel; } - - /** Sets a matrix used to transform any texture coordinates on this layer. - - Texture coordinates can be modified on a texture layer to create effects like scrolling - textures. A texture transform can either be applied to a layer which takes the source coordinates - from a fixed set in the geometry, or to one which generates them dynamically (e.g. environment mapping). - - It's obviously a bit impractical to create scrolling effects by calling this method manually since you - would have to call it every frame with a slight alteration each time, which is tedious. Instead - you can use setTransformAnimation which will manage the - effect over time for you. - - In addition, if you can et the individual texture transformations rather than concatenating them - yourself. - - @see Ogre::TextureUnitState::setTextureScroll - @see Ogre::TextureUnitState::setTextureScale - @see Ogre::TextureUnitState::setTextureRotate - */ - void setTextureTransform(const Matrix4& xform); - - /** Gets the current texture transformation matrix. - - Causes a reclaculation of the matrix if any parameters have been changed via - setTextureScroll, setTextureScale and setTextureRotate. - */ - const Matrix4& getTextureTransform(void) const; - - /** Sets the translation offset of the texture, ie scrolls the texture. - - This method sets the translation element of the texture transformation, and is easier to - use than setTextureTransform if you are combining translation, scaling and rotation in your - texture transformation. - If you want to animate these values use Ogre::TextureUnitState::setScrollAnimation - @param u - The amount the texture should be moved horizontally (u direction). - @param v - The amount the texture should be moved vertically (v direction). - */ - void setTextureScroll(Real u, Real v); - - /** As setTextureScroll, but sets only U value. - */ - void setTextureUScroll(Real value); - /// Get texture uscroll value. - Real getTextureUScroll(void) const; - - /** As setTextureScroll, but sets only V value. - */ - void setTextureVScroll(Real value); - /// Get texture vscroll value. - Real getTextureVScroll(void) const; - - /** As setTextureScale, but sets only U value. - */ - void setTextureUScale(Real value); - /// Get texture uscale value. - Real getTextureUScale(void) const; - - /** As setTextureScale, but sets only V value. - */ - void setTextureVScale(Real value); - /// Get texture vscale value. - Real getTextureVScale(void) const; - - /** Sets the scaling factor applied to texture coordinates. - - This method sets the scale element of the texture transformation, and is easier to use than - setTextureTransform if you are combining translation, scaling and rotation in your texture transformation. - - If you want to animate these values use Ogre::TextureUnitState::setTransformAnimation - @param uScale - The value by which the texture is to be scaled horizontally. - @param vScale - The value by which the texture is to be scaled vertically. - */ - void setTextureScale(Real uScale, Real vScale); - - /** Sets the anticlockwise rotation factor applied to texture coordinates. - - This sets a fixed rotation angle - if you wish to animate this, use Ogre::TextureUnitState::setRotateAnimation - @param angle - The angle of rotation (anticlockwise). - */ - void setTextureRotate(const Radian& angle); - /// Get texture rotation effects angle value. - const Radian& getTextureRotate(void) const; - - /// get the associated sampler - const SamplerPtr& getSampler() const { return mSampler; } - void setSampler(const SamplerPtr& sampler) - { - OgreAssert(sampler, "sampler must not be NULL"); - mSampler = sampler; - } - - /// @copydoc Sampler::setAddressingMode - const Sampler::UVWAddressingMode& getTextureAddressingMode(void) const - { - return mSampler->getAddressingMode(); - } - /// @copydoc Sampler::setAddressingMode - void setTextureAddressingMode( Ogre::TextureAddressingMode tam) { _getLocalSampler()->setAddressingMode(tam); } - /// @copydoc Sampler::setAddressingMode - void setTextureAddressingMode(Ogre::TextureAddressingMode u, Ogre::TextureAddressingMode v, - Ogre::TextureAddressingMode w) - { - _getLocalSampler()->setAddressingMode(u, v, w); - } - /// @copydoc Sampler::setAddressingMode - void setTextureAddressingMode( const Sampler::UVWAddressingMode& uvw) { _getLocalSampler()->setAddressingMode(uvw); } - /// @copydoc Sampler::setBorderColour - void setTextureBorderColour(const ColourValue& colour) { _getLocalSampler()->setBorderColour(colour); } - /// @copydoc Sampler::getBorderColour - const ColourValue& getTextureBorderColour() const { return mSampler->getBorderColour(); } - /// @copydoc Sampler::setFiltering(TextureFilterOptions) - void setTextureFiltering(TextureFilterOptions filterType) - { - _getLocalSampler()->setFiltering(filterType); - } - /// @copydoc Sampler::setFiltering(FilterType, FilterOptions) - void setTextureFiltering(FilterType ftype, FilterOptions opts) - { - _getLocalSampler()->setFiltering(ftype, opts); - } - /// @copydoc Sampler::setFiltering(FilterOptions, FilterOptions, FilterOptions) - void setTextureFiltering(FilterOptions minFilter, FilterOptions magFilter, FilterOptions mipFilter) - { - _getLocalSampler()->setFiltering(minFilter, magFilter, mipFilter); - } - /// @copydoc Sampler::getFiltering - FilterOptions getTextureFiltering(FilterType ftype) const { return mSampler->getFiltering(ftype); } - /// @copydoc Sampler::setCompareEnabled - void setTextureCompareEnabled(bool enabled) { _getLocalSampler()->setCompareEnabled(enabled); } - /// @copydoc Sampler::getCompareEnabled - bool getTextureCompareEnabled() const { return mSampler->getCompareEnabled(); } - /// @copydoc Sampler::setCompareFunction - void setTextureCompareFunction(CompareFunction function) { _getLocalSampler()->setCompareFunction(function); } - /// @copydoc Sampler::getCompareFunction - CompareFunction getTextureCompareFunction() const { return mSampler->getCompareFunction(); } - /// @copydoc Sampler::setAnisotropy - void setTextureAnisotropy(unsigned int maxAniso) { _getLocalSampler()->setAnisotropy(maxAniso); } - /// @copydoc Sampler::getAnisotropy - unsigned int getTextureAnisotropy() const { return mSampler->getAnisotropy(); } - /// @copydoc Sampler::setMipmapBias - void setTextureMipmapBias(float bias) { _getLocalSampler()->setMipmapBias(bias); } - /// @copydoc Sampler::getMipmapBias - float getTextureMipmapBias(void) const { return mSampler->getMipmapBias(); } - - - /** Setting advanced blending options. - - This is an extended version of the Ogre::TextureUnitState::setColourOperation method which allows - extremely detailed control over the blending applied between this and earlier layers. - See the Warning below about the issues between mulitpass and multitexturing that - using this method can create. - - Texture colour operations determine how the final colour of the surface appears when - rendered. Texture units are used to combine colour values from various sources (ie. the - diffuse colour of the surface from lighting calculations, combined with the colour of - the texture). This method allows you to specify the 'operation' to be used, ie. the - calculation such as adds or multiplies, and which values to use as arguments, such as - a fixed value or a value from a previous calculation. - - The defaults for each layer are: - - op = Ogre::LBX_MODULATE - - source1 = Ogre::LBS_TEXTURE - - source2 = Ogre::LBS_CURRENT - - ie. each layer takes the colour results of the previous layer, and multiplies them - with the new texture being applied. Bear in mind that colours are RGB values from - 0.0 - 1.0 so multiplying them together will result in values in the same range, - 'tinted' by the multiply. Note however that a straight multiply normally has the - effect of darkening the textures - for this reason there are brightening operations - like Ogre::LBX_MODULATE_X2. See the Ogre::LayerBlendOperation and Ogre::LayerBlendSource enumerated - types for full details. - - The final 3 parameters are only required if you decide to pass values manually - into the operation, i.e. you want one or more of the inputs to the colour calculation - to come from a fixed value that you supply. Hence you only need to fill these in if - you supply Ogre::LBS_MANUAL to the corresponding source, or use the Ogre::LBX_BLEND_MANUAL - operation. - @warning - Ogre tries to use multitexturing hardware to blend texture layers - together. However, if it runs out of texturing units (e.g. 2 of a GeForce2, 4 on a - GeForce3) it has to fall back on multipass rendering, i.e. rendering the same object - multiple times with different textures. This is both less efficient and there is a smaller - range of blending operations which can be performed. For this reason, if you use this method - you MUST also call Ogre::TextureUnitState::setColourOpMultipassFallback to specify which effect you - want to fall back on if sufficient hardware is not available. - @warning - If you wish to avoid having to do this, use the simpler Ogre::TextureUnitState::setColourOperation method - which allows less flexible blending options but sets up the multipass fallback automatically, - since it only allows operations which have direct multipass equivalents. - @param op - The operation to be used, e.g. modulate (multiply), add, subtract. - @param source1 - The source of the first colour to the operation e.g. texture colour. - @param source2 - The source of the second colour to the operation e.g. current surface colour. - @param arg1 - Manually supplied colour value (only required if source1 = LBS_MANUAL). - @param arg2 - Manually supplied colour value (only required if source2 = LBS_MANUAL). - @param manualBlend - Manually supplied 'blend' value - only required for operations - which require manual blend e.g. LBX_BLEND_MANUAL. - */ - void setColourOperationEx( - LayerBlendOperationEx op, - LayerBlendSource source1 = LBS_TEXTURE, - LayerBlendSource source2 = LBS_CURRENT, - - const ColourValue& arg1 = ColourValue::White, - const ColourValue& arg2 = ColourValue::White, - - Real manualBlend = 0.0); - - /** Determines how this texture layer is combined with the one below it (or the diffuse colour of - the geometry if this is layer 0). - - This method is the simplest way to blend texture layers, because it requires only one parameter, - gives you the most common blending types, and automatically sets up 2 blending methods: one for - if single-pass multitexturing hardware is available, and another for if it is not and the blending must - be achieved through multiple rendering passes. It is, however, quite limited and does not expose - the more flexible multitexturing operations, simply because these can't be automatically supported in - multipass fallback mode. If want to use the fancier options, use Ogre::TextureUnitState::setColourOperationEx, - but you'll either have to be sure that enough multitexturing units will be available, or you should - explicitly set a fallback using Ogre::TextureUnitState::setColourOpMultipassFallback. - @note - The default method is Ogre::LBO_MODULATE for all layers. - @param op - One of the Ogre::LayerBlendOperation enumerated blending types. - */ - void setColourOperation( const LayerBlendOperation op); - - /** Sets the multipass fallback operation for this layer, if you used TextureUnitState::setColourOperationEx - and not enough multitexturing hardware is available. - - Because some effects exposed using Ogre::TextureUnitState::setColourOperationEx are only supported under - multitexturing hardware, if the hardware is lacking the system must fallback on multipass rendering, - which unfortunately doesn't support as many effects. This method is for you to specify the fallback - operation which most suits you. - - You'll notice that the interface is the same as the Ogre::TMaterial::setSceneBlending method; this is - because multipass rendering IS effectively scene blending, since each layer is rendered on top - of the last using the same mechanism as making an object transparent, it's just being rendered - in the same place repeatedly to get the multitexture effect. - - If you use the simpler (and hence less flexible) Ogre::TextureUnitState::setColourOperation method you - don't need to call this as the system sets up the fallback for you. - @note - This option has no effect in the programmable pipeline, because there is no multipass fallback - and multitexture blending is handled by the fragment shader. - */ - void setColourOpMultipassFallback( const SceneBlendFactor sourceFactor, const SceneBlendFactor destFactor); - - /** Get multitexturing colour blending mode. - */ - const LayerBlendModeEx& getColourBlendMode(void) const; - - /** Get multitexturing alpha blending mode. - */ - const LayerBlendModeEx& getAlphaBlendMode(void) const; - - /** Get the multipass fallback for colour blending operation source factor. - */ - SceneBlendFactor getColourBlendFallbackSrc(void) const; - - /** Get the multipass fallback for colour blending operation destination factor. - */ - SceneBlendFactor getColourBlendFallbackDest(void) const; - - /** Sets the alpha operation to be applied to this texture. - - This works in exactly the same way as setColourOperationEx, except - that the effect is applied to the level of alpha (i.e. transparency) - of the texture rather than its colour. When the alpha of a texel (a pixel - on a texture) is 1.0, it is opaque, whereas it is fully transparent if the - alpha is 0.0. Please refer to the Ogre::TextureUnitState::setColourOperationEx method for more info. - @param op - The operation to be used, e.g. modulate (multiply), add, subtract - @param source1 - The source of the first alpha value to the operation e.g. texture alpha - @param source2 - The source of the second alpha value to the operation e.g. current surface alpha - @param arg1 - Manually supplied alpha value (only required if source1 = Ogre::LBS_MANUAL) - @param arg2 - Manually supplied alpha value (only required if source2 = Ogre::LBS_MANUAL) - @param manualBlend - Manually supplied 'blend' value - only required for operations - which require manual blend e.g. Ogre::LBX_BLEND_MANUAL - */ - void setAlphaOperation(LayerBlendOperationEx op, - LayerBlendSource source1 = LBS_TEXTURE, - LayerBlendSource source2 = LBS_CURRENT, - Real arg1 = 1.0, - Real arg2 = 1.0, - Real manualBlend = 0.0); - - /** Generic method for setting up texture effects. - - Allows you to specify effects directly by using the #TextureEffectType enumeration. The - arguments that go with it depend on the effect type. Only one effect of - each type can be applied to a texture layer. - @par - This method is used internally by Ogre but it is better generally for applications to use the - more intuitive specialised methods such as #setEnvironmentMap and #setTextureScroll. - */ - void addEffect(TextureEffect& effect); - - /** Turns on/off texture coordinate effect that makes this layer an environment map. - - Environment maps make an object look reflective by using the object's vertex normals relative - to the camera view to generate texture coordinates. - - The vectors generated can either be used to address a single 2D texture which - is a 'fish-eye' lens view of a scene, or a 3D cubic environment map which requires 6 textures - for each side of the inside of a cube. - - This effect works best if the object has lots of gradually changing normals. The texture also - has to be designed for this effect - see the example spheremap.png included with the sample - application for a 2D environment map; a cubic map can be generated by rendering 6 views of a - scene to each of the cube faces with orthogonal views. - - Enabling this disables any other texture coordinate generation effects. - However it can be combined with texture coordinate modification functions, which then operate on the - generated coordinates rather than static model texture coordinates. - @param enable - True to enable, false to disable - @param texGenType texture coordinate generation type - */ - void setEnvironmentMap(bool enable, EnvMapType texGenType = ENV_CURVED); - - /** Sets up an animated scroll for the texture layer. - - Useful for creating constant scrolling effects on a texture layer (for varying scrolls, see Ogre::TextureUnitState::setTransformAnimation). - @param uSpeed - The number of horizontal loops per second (+ve=moving right, -ve = moving left). - @param vSpeed - The number of vertical loops per second (+ve=moving up, -ve= moving down). - */ - void setScrollAnimation(Real uSpeed, Real vSpeed); - - /** Sets up an animated texture rotation for this layer. - - Useful for constant rotations (for varying rotations, see Ogre::TextureUnitState::setTransformAnimation). - @param speed - The number of complete anticlockwise revolutions per second (use -ve for clockwise) - */ - void setRotateAnimation(Real speed); - - /** Sets up a general time-relative texture modification effect. - - This can be called multiple times for different values of ttype, but only the latest effect - applies if called multiple time for the same ttype. - @param ttype - The type of transform, either translate (scroll), scale (stretch) or rotate (spin). - @param waveType - The shape of the wave, see Ogre::WaveformType enum for details. - @param base - The base value for the function (range of output = {base, base + amplitude}). - @param frequency - The speed of the wave in cycles per second. - @param phase - The offset of the start of the wave, e.g. 0.5 to start half-way through the wave. - @param amplitude - Scales the output so that instead of lying within 0..1 it lies within 0..1*amplitude for exaggerated effects. - */ - void setTransformAnimation( const TextureTransformType ttype, - const WaveformType waveType, Real base = 0, Real frequency = 1, Real phase = 0, Real amplitude = 1 ); - - - /** Enables or disables projective texturing on this texture unit. - - Projective texturing allows you to generate texture coordinates - based on a Frustum, which gives the impression that a texture is - being projected onto the surface. Note that once you have called - this method, the texture unit continues to monitor the Frustum you - passed in and the projection will change if you can alter it. It also - means that you must ensure that the Frustum object you pass a pointer - to remains in existence for as long as this TextureUnitState does. - @par - This effect cannot be combined with other texture generation effects, - such as environment mapping. It also has no effect on passes which - have a vertex program enabled - projective texturing has to be done - in the vertex program instead. - @param enabled - Whether to enable / disable. - @param projectionSettings - The Frustum which will be used to derive the - projection parameters. - */ - void setProjectiveTexturing(bool enabled, const Frustum* projectionSettings = 0); - - /** Removes all effects applied to this texture layer. - */ - void removeAllEffects(void); - - /** Removes a single effect applied to this texture layer. - @note - Because you can only have 1 effect of each type (e.g. 1 texture coordinate generation) applied - to a layer, only the effect type is required. - */ - void removeEffect( const TextureEffectType type ); - - /** Determines if this texture layer is currently blank. - @note - This can happen if a texture fails to load or some other non-fatal error. Worth checking after - setting texture name. - */ - bool isBlank(void) const; - - /** Sets this texture layer to be blank. - */ - void setBlank(void); - - /** Tests if the texture associated with this unit has failed to load. - */ - bool isTextureLoadFailing() const { return mTextureLoadFailed; } - - /** Tells the unit to retry loading the texture if it had failed to load. - */ - void retryTextureLoad() { mTextureLoadFailed = false; } - - /// Get texture effects in a multimap paired array. - const EffectMap& getEffects(void) const; - /// Get the animated-texture animation duration. - Real getAnimationDuration(void) const; - - /// Returns true if this texture unit is using the default Sampler - bool isDefaultFiltering() const; - - /** Set the compositor reference for this texture unit state. - - Only valid when content type is compositor. - @param compositorName - The name of the compositor to reference. - @param textureName - The name of the texture to reference. - @param mrtIndex - The index of the wanted texture, if referencing an MRT. - */ - void setCompositorReference(const String& compositorName, const String& textureName, uint32 mrtIndex = 0); - - /** Gets the name of the compositor that this texture references. */ - const String& getReferencedCompositorName() const { return mCompositorRefName; } - /** Gets the name of the texture in the compositor that this texture references. */ - const String& getReferencedTextureName() const { return mCompositorRefTexName; } - /** Gets the MRT index of the texture in the compositor that this texture references. */ - uint32 getReferencedMRTIndex() const { return mCompositorRefMrtIndex; } - - /// Gets the parent Pass object. - Pass* getParent(void) const { return mParent; } - - /** Internal method for preparing this object for load, as part of Material::prepare. */ - void _prepare(void); - /** Internal method for undoing the preparation this object as part of Material::unprepare. */ - void _unprepare(void); - /** Internal method for loading this object as part of Material::load. */ - void _load(void); - /** Internal method for unloading this object as part of Material::unload. */ - void _unload(void); - - /// Is this loaded? - bool isLoaded(void) const; - /** Tells the class that it needs recompilation. */ - void _notifyNeedsRecompile(void); - - /** Set the name of the Texture Unit State. - - The name of the Texture Unit State is optional. Its useful in material scripts where a material could inherit - from another material and only want to modify a particular Texture Unit State. - */ - void setName(const String& name); - /// Get the name of the Texture Unit State. - const String& getName(void) const { return mName; } - - /// @deprecated use setName() - OGRE_DEPRECATED void setTextureNameAlias(const String& name) { setName(name); } - /// @deprecated use getName() - OGRE_DEPRECATED const String& getTextureNameAlias(void) const { return getName();} - - /** Notify this object that its parent has changed. */ - void _notifyParent(Pass* parent); - - /** Get the texture pointer for the current frame. */ - const TexturePtr& _getTexturePtr(void) const; - /** Get the texture pointer for a given frame. */ - const TexturePtr& _getTexturePtr(size_t frame) const; - - /** Set the texture pointer for the current frame (internal use only!). */ - void _setTexturePtr(const TexturePtr& texptr); - /** Set the texture pointer for a given frame (internal use only!). */ - void _setTexturePtr(const TexturePtr& texptr, size_t frame); - - size_t calculateSize(void) const; - - /** Gets the animation controller (as created because of setAnimatedTexture) - if it exists. - */ - ControllerFloat* _getAnimController() const { return mAnimController; } - - /// return a sampler local to this TUS instead of the shared global one - const SamplerPtr& _getLocalSampler(); - - TexCoordCalcMethod _deriveTexCoordCalcMethod() const; -private: - // State - /// The current animation frame. - unsigned int mCurrentFrame; - - /// Duration of animation in seconds. - Real mAnimDuration; - - int mUnorderedAccessMipLevel; - - LayerBlendModeEx mColourBlendMode; - SceneBlendFactor mColourBlendFallbackSrc; - SceneBlendFactor mColourBlendFallbackDest; - - LayerBlendModeEx mAlphaBlendMode; - Real mGamma; - Real mUMod, mVMod; - Real mUScale, mVScale; - Radian mRotate; - mutable Matrix4 mTexModMatrix; - - /// Content type of texture (normal loaded texture, auto-texture). - ContentType mContentType; - - mutable bool mTextureLoadFailed; - mutable bool mRecalcTexMatrix; - - uint8 mTextureCoordSetIndex; - - /// The index of the referenced texture if referencing an MRT in a compositor. - uint32 mCompositorRefMrtIndex; - - //----------------------------------------------------------------------------- - // Complex members (those that can't be copied using memcpy) are at the end to - // allow for fast copying of the basic members. - // - mutable std::vector mFramePtrs; // must at least contain a single nullptr - SamplerPtr mSampler; - String mName; ///< Optional name for the TUS. - EffectMap mEffects; - /// The data that references the compositor. - String mCompositorRefName; - String mCompositorRefTexName; - //----------------------------------------------------------------------------- - - //----------------------------------------------------------------------------- - // Pointer members (those that can't be copied using memcpy), and MUST - // preserving even if assign from others - // - Pass* mParent; - ControllerFloat* mAnimController; - //----------------------------------------------------------------------------- - - - /** Internal method for calculating texture matrix. - */ - void recalcTextureMatrix(void) const; - - /** Internal method for creating animation controller. - */ - void createAnimController(void); - - /** Internal method for creating texture effect controller. - */ - void createEffectController(TextureEffect& effect); - - /** Internal method for ensuring the texture for a given frame is prepared. */ - void ensurePrepared(size_t frame) const; - /** Internal method for ensuring the texture for a given frame is loaded. */ - void ensureLoaded(size_t frame) const; - - TexturePtr retrieveTexture(const String& name); - - bool checkTexCalcSettings(const TexturePtr& tex) const; - }; - - /** @} */ - /** @} */ - -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif // __TextureUnitState_H__ diff --git a/OgreMain/include/OgreTimer.h b/OgreMain/include/OgreTimer.h deleted file mode 100644 index f9568a105e8..00000000000 --- a/OgreMain/include/OgreTimer.h +++ /dev/null @@ -1,62 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __OGRE_TIMER_H__ -#define __OGRE_TIMER_H__ - -#include "OgrePrerequisites.h" -#include - -namespace Ogre -{ - /** Timer class */ - class _OgreExport Timer : public TimerAlloc - { - private: - std::chrono::steady_clock::time_point start; - clock_t zeroClock; - public: - Timer(); - - /** Resets timer */ - void reset(); - - /** Returns milliseconds since initialisation or last reset */ - uint64_t getMilliseconds(); - - /** Returns microseconds since initialisation or last reset */ - uint64_t getMicroseconds(); - - /** Returns milliseconds since initialisation or last reset, only CPU time measured */ - uint64_t getMillisecondsCPU(); - - /** Returns microseconds since initialisation or last reset, only CPU time measured */ - uint64_t getMicrosecondsCPU(); - }; -} -#endif diff --git a/OgreMain/include/OgreUserObjectBindings.h b/OgreMain/include/OgreUserObjectBindings.h deleted file mode 100644 index f21ea481dbf..00000000000 --- a/OgreMain/include/OgreUserObjectBindings.h +++ /dev/null @@ -1,138 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _UserObjectsBinding_H__ -#define _UserObjectsBinding_H__ - -#include "OgrePrerequisites.h" -#include "OgreAny.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - - /** Class that provides convenient interface to establish a linkage between - custom user application objects and %Ogre core classes. - */ - class _OgreExport UserObjectBindings : public GeneralAllocatedObject - { - public: - /** Sets any kind of user object on this class instance. - - This method allows you to associate any user object you like with - this class. This can be a pointer back to one of your own - classes for instance. - @note This method is key less meaning that each call for it will override - previous object that were set. If you need to associate multiple objects - with this class use the extended version that takes key. - */ - void setUserAny(const Any& anything); - - /** Retrieves the custom key less user object associated with this class. - */ - const Any& getUserAny(void) const; - - /** Sets any kind of user object on this class instance. - - This method allows you to associate multiple object with this class. - This can be a pointer back to one of your own classes for instance. - Use a unique key to distinguish between each of these objects. - @param key The key that this data is associate with. - @param anything The data to associate with the given key. - */ - void setUserAny(const String& key, const Any& anything); - - /** Retrieves the custom user object associated with this class and key. - @param key The key that the requested user object is associated with. - - In case no object associated with this key the returned Any object will be empty. - */ - const Any& getUserAny(const String& key) const; - - /** Erase the custom user object associated with this class and key from this binding. - @param key The key that the requested user object is associated with. - */ - void eraseUserAny(const String& key); - - /** Clear all user objects from this binding. */ - void clear(); - - UserObjectBindings() = default; - - /** Copy constructor. Performs a copy of all stored UserAny. */ - UserObjectBindings(const UserObjectBindings& other); - - UserObjectBindings& swap(UserObjectBindings& rhs); - - UserObjectBindings& operator=(const UserObjectBindings& rhs); - - // Types. - private: - typedef std::map UserObjectsMap; - typedef UserObjectsMap::iterator UserObjectsMapIterator; - typedef UserObjectsMap::const_iterator UserObjectsMapConstIterator; - - /** Internal class that uses as data storage container. - */ - struct Attributes : public GeneralAllocatedObject - { - Attributes() = default; - - /** Copy ctor. Copies the attribute storage. */ - Attributes(const Attributes& other) : - mKeylessAny(other.mKeylessAny) - { - if (other.mUserObjectsMap) - mUserObjectsMap.reset(new UserObjectsMap(*other.mUserObjectsMap)); - } - - Any mKeylessAny;// Will hold key less associated user object for fast access. - std::unique_ptr mUserObjectsMap;// Will hold a map between user keys to user objects. - }; - - /** \brief Protected getter for the attributes map, to allow derived classes to inspect its elements. */ - const Attributes* getAttributes() const { return mAttributes.get(); } - Attributes* getAttributes() { return mAttributes.get(); } - - // Attributes. - private: - std::unique_ptr mAttributes; // Class attributes - will be allocated on demand. - }; - - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreVector.h b/OgreMain/include/OgreVector.h deleted file mode 100644 index 3d753b95f9a..00000000000 --- a/OgreMain/include/OgreVector.h +++ /dev/null @@ -1,888 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Vector_H__ -#define __Vector_H__ - - -#include "OgrePrerequisites.h" -#include "OgreMath.h" -#include "OgreQuaternion.h" - -namespace Ogre -{ - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - /// helper class to implement legacy API. Notably x, y, z access - template struct VectorBase - { - VectorBase() {} - VectorBase(T _x, T _y) - { - static_assert(dims > 1, "must have at least 2 dimensions"); - data[0] = _x; data[1] = _y; - } - VectorBase(T _x, T _y, T _z) - { - static_assert(dims > 2, "must have at least 3 dimensions"); - data[0] = _x; data[1] = _y; data[2] = _z; - } - VectorBase(T _x, T _y, T _z, T _w) - { - static_assert(dims > 3, "must have at least 4 dimensions"); - data[0] = _x; data[1] = _y; data[2] = _z; data[3] = _w; - } - T data[dims]; - T* ptr() { return data; } - const T* ptr() const { return data; } - }; - template <> struct _OgreExport VectorBase<2, Real> - { - VectorBase() {} - VectorBase(Real _x, Real _y) : x(_x), y(_y) {} - Real x, y; - Real* ptr() { return &x; } - const Real* ptr() const { return &x; } - - /** Returns a vector at a point half way between this and the passed - in vector. - */ - Vector2 midPoint( const Vector2& vec ) const; - - /** Calculates the 2 dimensional cross-product of 2 vectors, which results - in a single floating point value which is 2 times the area of the triangle. - */ - Real crossProduct( const VectorBase& rkVector ) const - { - return x * rkVector.y - y * rkVector.x; - } - - /** Generates a vector perpendicular to this vector (eg an 'up' vector). - - This method will return a vector which is perpendicular to this - vector. There are an infinite number of possibilities but this - method will guarantee to generate one of them. If you need more - control you should use the Quaternion class. - */ - Vector2 perpendicular(void) const; - - /** Generates a new random vector which deviates from this vector by a - given angle in a random direction. - - This method assumes that the random number generator has already - been seeded appropriately. - @param angle - The angle at which to deviate in radians - @return - A random vector which deviates from this vector by angle. This - vector will not be normalised, normalise it if you wish - afterwards. - */ - Vector2 randomDeviant(Radian angle) const; - - /** Gets the oriented angle between 2 vectors. - - Vectors do not have to be unit-length but must represent directions. - The angle is comprised between 0 and 2 PI. - */ - Radian angleTo(const Vector2& other) const; - - // special points - static const Vector2 ZERO; - static const Vector2 UNIT_X; - static const Vector2 UNIT_Y; - static const Vector2 NEGATIVE_UNIT_X; - static const Vector2 NEGATIVE_UNIT_Y; - static const Vector2 UNIT_SCALE; - }; - - template <> struct _OgreExport VectorBase<3, Real> - { - VectorBase() {} - VectorBase(Real _x, Real _y, Real _z) : x(_x), y(_y), z(_z) {} - Real x, y, z; - Real* ptr() { return &x; } - const Real* ptr() const { return &x; } - - /** Calculates the cross-product of 2 vectors, i.e. the vector that - lies perpendicular to them both. - - The cross-product is normally used to calculate the normal - vector of a plane, by calculating the cross-product of 2 - non-equivalent vectors which lie on the plane (e.g. 2 edges - of a triangle). - @param rkVector - Vector which, together with this one, will be used to - calculate the cross-product. - @return - A vector which is the result of the cross-product. This - vector will NOT be normalised, to maximise efficiency - - call Vector3::normalise on the result if you wish this to - be done. As for which side the resultant vector will be on, the - returned vector will be on the side from which the arc from 'this' - to rkVector is anticlockwise, e.g. UNIT_Y.crossProduct(UNIT_Z) - = UNIT_X, whilst UNIT_Z.crossProduct(UNIT_Y) = -UNIT_X. - This is because OGRE uses a right-handed coordinate system. - @par - For a clearer explanation, look a the left and the bottom edges - of your monitor's screen. Assume that the first vector is the - left edge and the second vector is the bottom edge, both of - them starting from the lower-left corner of the screen. The - resulting vector is going to be perpendicular to both of them - and will go inside the screen, towards the cathode tube - (assuming you're using a CRT monitor, of course). - */ - Vector3 crossProduct( const Vector3& rkVector ) const; - - /** Generates a vector perpendicular to this vector (eg an 'up' vector). - - This method will return a vector which is perpendicular to this - vector. There are an infinite number of possibilities but this - method will guarantee to generate one of them. If you need more - control you should use the Quaternion class. - */ - Vector3 perpendicular(void) const; - - /** Calculates the absolute dot (scalar) product of this vector with another. - - This function work similar dotProduct, except it use absolute value - of each component of the vector to computing. - @param - vec Vector with which to calculate the absolute dot product (together - with this one). - @return - A Real representing the absolute dot product value. - */ - Real absDotProduct(const VectorBase& vec) const - { - return Math::Abs(x * vec.x) + Math::Abs(y * vec.y) + Math::Abs(z * vec.z); - } - - /** Returns a vector at a point half way between this and the passed - in vector. - */ - Vector3 midPoint( const Vector3& vec ) const; - - /** Generates a new random vector which deviates from this vector by a - given angle in a random direction. - - This method assumes that the random number generator has already - been seeded appropriately. - @param - angle The angle at which to deviate - @param - up Any vector perpendicular to this one (which could generated - by cross-product of this vector and any other non-colinear - vector). If you choose not to provide this the function will - derive one on it's own, however if you provide one yourself the - function will be faster (this allows you to reuse up vectors if - you call this method more than once) - @return - A random vector which deviates from this vector by angle. This - vector will not be normalised, normalise it if you wish - afterwards. - */ - Vector3 randomDeviant(const Radian& angle, const Vector3& up = ZERO) const; - - /** Gets the shortest arc quaternion to rotate this vector to the destination - vector. - - If you call this with a dest vector that is close to the inverse - of this vector, we will rotate 180 degrees around the 'fallbackAxis' - (if specified, or a generated axis if not) since in this case - ANY axis of rotation is valid. - */ - Quaternion getRotationTo(const Vector3& dest, const Vector3& fallbackAxis = ZERO) const; - - /** Returns whether this vector is within a positional tolerance - of another vector, also take scale of the vectors into account. - @param rhs The vector to compare with - @param tolerance The amount (related to the scale of vectors) that distance - of the vector may vary by and still be considered close - */ - bool positionCloses(const Vector3& rhs, Real tolerance = 1e-03f) const; - - /** Returns whether this vector is within a directional tolerance - of another vector. - @param rhs The vector to compare with - @param tolerance The maximum angle by which the vectors may vary and - still be considered equal - @note Both vectors should be normalised. - */ - bool directionEquals(const Vector3& rhs, const Radian& tolerance) const; - - /// Extract the primary (dominant) axis from this direction vector - const Vector3& primaryAxis() const; - - // special points - static const Vector3 ZERO; - static const Vector3 UNIT_X; - static const Vector3 UNIT_Y; - static const Vector3 UNIT_Z; - static const Vector3 NEGATIVE_UNIT_X; - static const Vector3 NEGATIVE_UNIT_Y; - static const Vector3 NEGATIVE_UNIT_Z; - static const Vector3 UNIT_SCALE; - }; - - template <> struct _OgreExport VectorBase<4, Real> - { - VectorBase() {} - VectorBase(Real _x, Real _y, Real _z, Real _w) : x(_x), y(_y), z(_z), w(_w) {} - Real x, y, z, w; - Real* ptr() { return &x; } - const Real* ptr() const { return &x; } - - // special points - static const Vector4 ZERO; - }; - - /** Standard N-dimensional vector. - - A direction in N-D space represented as distances along the - orthogonal axes. Note that positions, directions and - scaling factors can be represented by a vector, depending on how - you interpret the values. - */ - template - class _OgreMaybeExport Vector : public VectorBase - { - public: - using VectorBase::ptr; - - /** Default constructor. - @note It does NOT initialize the vector for efficiency. - */ - Vector() {} - Vector(T _x, T _y) : VectorBase(_x, _y) {} - Vector(T _x, T _y, T _z) : VectorBase(_x, _y, _z) {} - Vector(T _x, T _y, T _z, T _w) : VectorBase(_x, _y, _z, _w) {} - - // use enable_if as function parameter for VC < 2017 compatibility - template - explicit Vector(const typename std::enable_if>::type& rhs, T fW = 1.0f) : VectorBase(rhs[0], rhs[1], rhs[2], fW) {} - - template - explicit Vector(const U* _ptr) { - for (int i = 0; i < dims; i++) - ptr()[i] = T(_ptr[i]); - } - - template - explicit Vector(const Vector& o) : Vector(o.ptr()) {} - - - explicit Vector(T s) - { - for (int i = 0; i < dims; i++) - ptr()[i] = s; - } - - /** Swizzle-like narrowing operations - */ - Vector<3, T> xyz() const - { - static_assert(dims > 3, "just use assignment"); - return Vector<3, T>(ptr()); - } - Vector<2, T> xy() const - { - static_assert(dims > 2, "just use assignment"); - return Vector<2, T>(ptr()); - } - - T operator[](size_t i) const - { - assert(i < dims); - return ptr()[i]; - } - - T& operator[](size_t i) - { - assert(i < dims); - return ptr()[i]; - } - - bool operator==(const Vector& v) const - { - for (int i = 0; i < dims; i++) - if (ptr()[i] != v[i]) - return false; - return true; - } - - /** Returns whether this vector is within a positional tolerance - of another vector. - @param rhs The vector to compare with - @param tolerance The amount that each element of the vector may vary by - and still be considered equal - */ - bool positionEquals(const Vector& rhs, Real tolerance = 1e-03f) const - { - for (int i = 0; i < dims; i++) - if (!Math::RealEqual(ptr()[i], rhs[i], tolerance)) - return false; - return true; - } - - bool operator!=(const Vector& v) const { return !(*this == v); } - - /** Returns true if the vector's scalar components are all greater - that the ones of the vector it is compared against. - */ - bool operator<(const Vector& rhs) const - { - for (int i = 0; i < dims; i++) - if (!(ptr()[i] < rhs[i])) - return false; - return true; - } - - /** Returns true if the vector's scalar components are all smaller - that the ones of the vector it is compared against. - */ - bool operator>(const Vector& rhs) const - { - for (int i = 0; i < dims; i++) - if (!(ptr()[i] > rhs[i])) - return false; - return true; - } - - /** Sets this vector's components to the minimum of its own and the - ones of the passed in vector. - - 'Minimum' in this case means the combination of the lowest - value of x, y and z from both vectors. Lowest is taken just - numerically, not magnitude, so -1 < 0. - */ - void makeFloor(const Vector& cmp) - { - for (int i = 0; i < dims; i++) - if (cmp[i] < ptr()[i]) - ptr()[i] = cmp[i]; - } - - /** Sets this vector's components to the maximum of its own and the - ones of the passed in vector. - - 'Maximum' in this case means the combination of the highest - value of x, y and z from both vectors. Highest is taken just - numerically, not magnitude, so 1 > -3. - */ - void makeCeil(const Vector& cmp) - { - for (int i = 0; i < dims; i++) - if (cmp[i] > ptr()[i]) - ptr()[i] = cmp[i]; - } - - /** Calculates the dot (scalar) product of this vector with another. - - The dot product can be used to calculate the angle between 2 - vectors. If both are unit vectors, the dot product is the - cosine of the angle; otherwise the dot product must be - divided by the product of the lengths of both vectors to get - the cosine of the angle. This result can further be used to - calculate the distance of a point from a plane. - @param - vec Vector with which to calculate the dot product (together - with this one). - @return - A float representing the dot product value. - */ - T dotProduct(const VectorBase& vec) const - { - T ret = 0; - for (int i = 0; i < dims; i++) - ret += ptr()[i] * vec.ptr()[i]; - return ret; - } - - /** Returns the square of the length(magnitude) of the vector. - - This method is for efficiency - calculating the actual - length of a vector requires a square root, which is expensive - in terms of the operations required. This method returns the - square of the length of the vector, i.e. the same as the - length but before the square root is taken. Use this if you - want to find the longest / shortest vector without incurring - the square root. - */ - T squaredLength() const { return dotProduct(*this); } - - /** Returns true if this vector is zero length. */ - bool isZeroLength() const - { - return squaredLength() < 1e-06 * 1e-06; - } - - /** Returns the length (magnitude) of the vector. - @warning - This operation requires a square root and is expensive in - terms of CPU operations. If you don't need to know the exact - length (e.g. for just comparing lengths) use squaredLength() - instead. - */ - Real length() const { return Math::Sqrt(squaredLength()); } - - /** Returns the distance to another vector. - @warning - This operation requires a square root and is expensive in - terms of CPU operations. If you don't need to know the exact - distance (e.g. for just comparing distances) use squaredDistance() - instead. - */ - Real distance(const Vector& rhs) const - { - return (*this - rhs).length(); - } - - /** Returns the square of the distance to another vector. - - This method is for efficiency - calculating the actual - distance to another vector requires a square root, which is - expensive in terms of the operations required. This method - returns the square of the distance to another vector, i.e. - the same as the distance but before the square root is taken. - Use this if you want to find the longest / shortest distance - without incurring the square root. - */ - T squaredDistance(const Vector& rhs) const - { - return (*this - rhs).squaredLength(); - } - - /** Normalises the vector. - - This method normalises the vector such that it's - length / magnitude is 1. The result is called a unit vector. - @note - This function will not crash for zero-sized vectors, but there - will be no changes made to their components. - @return The previous length of the vector. - */ - Real normalise() - { - Real fLength = length(); - - // Will also work for zero-sized vectors, but will change nothing - // We're not using epsilons because we don't need to. - // Read http://www.ogre3d.org/forums/viewtopic.php?f=4&t=61259 - if (fLength > Real(0.0f)) - { - Real fInvLength = 1.0f / fLength; - for (int i = 0; i < dims; i++) - ptr()[i] *= fInvLength; - } - - return fLength; - } - - /** As normalise, except that this vector is unaffected and the - normalised vector is returned as a copy. */ - Vector normalisedCopy() const - { - Vector ret = *this; - ret.normalise(); - return ret; - } - -#ifndef OGRE_FAST_MATH - /// Check whether this vector contains valid values - bool isNaN() const - { - for (int i = 0; i < dims; i++) - if (Math::isNaN(ptr()[i])) - return true; - return false; - } -#endif - - /** Gets the angle between 2 vectors. - - Vectors do not have to be unit-length but must represent directions. - */ - Radian angleBetween(const Vector& dest) const - { - Real lenProduct = length() * dest.length(); - - // Divide by zero check - if(lenProduct < 1e-6f) - lenProduct = 1e-6f; - - Real f = dotProduct(dest) / lenProduct; - - f = Math::Clamp(f, (Real)-1.0, (Real)1.0); - return Math::ACos(f); - - } - - /** Calculates a reflection vector to the plane with the given normal . - @remarks NB assumes 'this' is pointing AWAY FROM the plane, invert if it is not. - */ - Vector reflect(const Vector& normal) const { return *this - (2 * dotProduct(normal) * normal); } - - // Vector: arithmetic updates - Vector& operator*=(Real s) - { - for (int i = 0; i < dims; i++) - ptr()[i] *= s; - return *this; - } - - Vector& operator/=(Real s) - { - assert( s != 0.0 ); // legacy assert - Real fInv = 1.0f/s; - for (int i = 0; i < dims; i++) - ptr()[i] *= fInv; - return *this; - } - - Vector& operator+=(Real s) - { - for (int i = 0; i < dims; i++) - ptr()[i] += s; - return *this; - } - - Vector& operator-=(Real s) - { - for (int i = 0; i < dims; i++) - ptr()[i] -= s; - return *this; - } - - Vector& operator+=(const Vector& b) - { - for (int i = 0; i < dims; i++) - ptr()[i] += b[i]; - return *this; - } - - Vector& operator-=(const Vector& b) - { - for (int i = 0; i < dims; i++) - ptr()[i] -= b[i]; - return *this; - } - - Vector& operator*=(const Vector& b) - { - for (int i = 0; i < dims; i++) - ptr()[i] *= b[i]; - return *this; - } - - Vector& operator/=(const Vector& b) - { - for (int i = 0; i < dims; i++) - ptr()[i] /= b[i]; - return *this; - } - - // Scalar * Vector - friend Vector operator*(Real s, Vector v) - { - v *= s; - return v; - } - - friend Vector operator+(Real s, Vector v) - { - v += s; - return v; - } - - friend Vector operator-(Real s, const Vector& v) - { - Vector ret; - for (int i = 0; i < dims; i++) - ret[i] = s - v[i]; - return ret; - } - - friend Vector operator/(Real s, const Vector& v) - { - Vector ret; - for (int i = 0; i < dims; i++) - ret[i] = s / v[i]; - return ret; - } - - // Vector * Scalar - Vector operator-() const - { - return -1 * *this; - } - - const Vector& operator+() const - { - return *this; - } - - Vector operator*(Real s) const - { - return s * *this; - } - - Vector operator/(Real s) const - { - assert( s != 0.0 ); // legacy assert - Real fInv = 1.0f / s; - return fInv * *this; - } - - Vector operator-(Real s) const - { - return -s + *this; - } - - Vector operator+(Real s) const - { - return s + *this; - } - - // Vector * Vector - Vector operator+(const Vector& b) const - { - Vector ret = *this; - ret += b; - return ret; - } - - Vector operator-(const Vector& b) const - { - Vector ret = *this; - ret -= b; - return ret; - } - - Vector operator*(const Vector& b) const - { - Vector ret = *this; - ret *= b; - return ret; - } - - Vector operator/(const Vector& b) const - { - Vector ret = *this; - ret /= b; - return ret; - } - - friend std::ostream& operator<<(std::ostream& o, const Vector& v) - { - o << "Vector" << dims << "("; - for (int i = 0; i < dims; i++) { - o << v[i]; - if(i != dims - 1) o << ", "; - } - o << ")"; - return o; - } - }; - - inline Vector2 VectorBase<2, Real>::midPoint( const Vector2& vec ) const - { - return Vector2( - ( x + vec.x ) * 0.5f, - ( y + vec.y ) * 0.5f ); - } - - inline Vector2 VectorBase<2, Real>::randomDeviant(Radian angle) const - { - angle *= Math::RangeRandom(-1, 1); - Real cosa = Math::Cos(angle); - Real sina = Math::Sin(angle); - return Vector2(cosa * x - sina * y, - sina * x + cosa * y); - } - - inline Radian VectorBase<2, Real>::angleTo(const Vector2& other) const - { - Radian angle = ((const Vector2*)this)->angleBetween(other); - - if (crossProduct(other)<0) - angle = Radian(Math::TWO_PI) - angle; - - return angle; - } - - inline Vector2 VectorBase<2, Real>::perpendicular(void) const - { - return Vector2(-y, x); - } - - inline Vector3 VectorBase<3, Real>::perpendicular() const - { - // From Sam Hocevar's article "On picking an orthogonal - // vector (and combing coconuts)" - Vector3 perp = Math::Abs(x) > Math::Abs(z) - ? Vector3(-y, x, 0.0) : Vector3(0.0, -z, y); - return perp.normalisedCopy(); - } - - inline Vector3 VectorBase<3, Real>::crossProduct( const Vector3& rkVector ) const - { - return Vector3( - y * rkVector.z - z * rkVector.y, - z * rkVector.x - x * rkVector.z, - x * rkVector.y - y * rkVector.x); - } - - inline Vector3 VectorBase<3, Real>::midPoint( const Vector3& vec ) const - { - return Vector3( - ( x + vec.x ) * 0.5f, - ( y + vec.y ) * 0.5f, - ( z + vec.z ) * 0.5f ); - } - - inline Vector3 VectorBase<3, Real>::randomDeviant(const Radian& angle, const Vector3& up) const - { - Vector3 newUp; - - if (up == ZERO) - { - // Generate an up vector - newUp = ((const Vector3*)this)->perpendicular(); - } - else - { - newUp = up; - } - - // Rotate up vector by random amount around this - Quaternion q; - q.FromAngleAxis( Radian(Math::UnitRandom() * Math::TWO_PI), (const Vector3&)*this ); - newUp = q * newUp; - - // Finally rotate this by given angle around randomised up - q.FromAngleAxis( angle, newUp ); - return q * (const Vector3&)(*this); - } - - inline Quaternion VectorBase<3, Real>::getRotationTo(const Vector3& dest, const Vector3& fallbackAxis) const - { - // From Sam Hocevar's article "Quaternion from two vectors: - // the final version" - Real a = Math::Sqrt(((const Vector3*)this)->squaredLength() * dest.squaredLength()); - Real b = a + dest.dotProduct(*this); - - if (Math::RealEqual(b, 2 * a) || a == 0) - return Quaternion::IDENTITY; - - Vector3 axis; - - if (b < (Real)1e-06 * a) - { - b = (Real)0.0; - axis = fallbackAxis != Vector3::ZERO ? fallbackAxis - : Math::Abs(x) > Math::Abs(z) ? Vector3(-y, x, (Real)0.0) - : Vector3((Real)0.0, -z, y); - } - else - { - axis = this->crossProduct(dest); - } - - Quaternion q(b, axis.x, axis.y, axis.z); - q.normalise(); - return q; - } - - inline bool VectorBase<3, Real>::positionCloses(const Vector3& rhs, Real tolerance) const - { - return ((const Vector3*)this)->squaredDistance(rhs) <= - (((const Vector3*)this)->squaredLength() + rhs.squaredLength()) * tolerance; - } - - inline bool VectorBase<3, Real>::directionEquals(const Vector3& rhs, const Radian& tolerance) const - { - Real dot = rhs.dotProduct(*this); - Radian angle = Math::ACos(dot); - - return Math::Abs(angle.valueRadians()) <= tolerance.valueRadians(); - } - - inline const Vector3& VectorBase<3, Real>::primaryAxis() const - { - Real absx = Math::Abs(x); - Real absy = Math::Abs(y); - Real absz = Math::Abs(z); - if (absx > absy) - if (absx > absz) - return x > 0 ? UNIT_X : NEGATIVE_UNIT_X; - else - return z > 0 ? UNIT_Z : NEGATIVE_UNIT_Z; - else // absx <= absy - if (absy > absz) - return y > 0 ? UNIT_Y : NEGATIVE_UNIT_Y; - else - return z > 0 ? UNIT_Z : NEGATIVE_UNIT_Z; - } - - // Math functions - inline Vector3 Math::calculateBasicFaceNormal(const Vector3& v1, const Vector3& v2, const Vector3& v3) - { - Vector3 normal = (v2 - v1).crossProduct(v3 - v1); - normal.normalise(); - return normal; - } - inline Vector4 Math::calculateFaceNormal(const Vector3& v1, const Vector3& v2, const Vector3& v3) - { - Vector3 normal = calculateBasicFaceNormal(v1, v2, v3); - // Now set up the w (distance of tri from origin - return Vector4(normal.x, normal.y, normal.z, -(normal.dotProduct(v1))); - } - inline Vector3 Math::calculateBasicFaceNormalWithoutNormalize( - const Vector3& v1, const Vector3& v2, const Vector3& v3) - { - return (v2 - v1).crossProduct(v3 - v1); - } - - inline Vector4 Math::calculateFaceNormalWithoutNormalize(const Vector3& v1, - const Vector3& v2, - const Vector3& v3) - { - Vector3 normal = calculateBasicFaceNormalWithoutNormalize(v1, v2, v3); - // Now set up the w (distance of tri from origin) - return Vector4(normal.x, normal.y, normal.z, -(normal.dotProduct(v1))); - } - /** @} */ - /** @} */ - -} -#endif diff --git a/OgreMain/include/OgreVector2.h b/OgreMain/include/OgreVector2.h deleted file mode 100644 index fe09efd3224..00000000000 --- a/OgreMain/include/OgreVector2.h +++ /dev/null @@ -1,2 +0,0 @@ -#include "OgreVector.h" -#pragma message( __FILE__ " is deprecated, migrate to Ogre.h") diff --git a/OgreMain/include/OgreVector3.h b/OgreMain/include/OgreVector3.h deleted file mode 100644 index fe09efd3224..00000000000 --- a/OgreMain/include/OgreVector3.h +++ /dev/null @@ -1,2 +0,0 @@ -#include "OgreVector.h" -#pragma message( __FILE__ " is deprecated, migrate to Ogre.h") diff --git a/OgreMain/include/OgreVector4.h b/OgreMain/include/OgreVector4.h deleted file mode 100644 index fe09efd3224..00000000000 --- a/OgreMain/include/OgreVector4.h +++ /dev/null @@ -1,2 +0,0 @@ -#include "OgreVector.h" -#pragma message( __FILE__ " is deprecated, migrate to Ogre.h") diff --git a/OgreMain/include/OgreVertexBoneAssignment.h b/OgreMain/include/OgreVertexBoneAssignment.h deleted file mode 100644 index 3535855abf6..00000000000 --- a/OgreMain/include/OgreVertexBoneAssignment.h +++ /dev/null @@ -1,62 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __VertexBoneAssignment_H__ -#define __VertexBoneAssignment_H__ - -#include "OgrePrerequisites.h" - - -namespace Ogre -{ - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Animation - * @{ - */ - /** Records the assignment of a single vertex to a single bone with the corresponding weight. - - This simple struct simply holds a vertex index, bone index and weight representing the - assignment of a vertex to a bone for skeletal animation. There may be many of these - per vertex if blended vertex assignments are allowed. - */ - struct VertexBoneAssignment - { - uint32 vertexIndex; - uint16 boneIndex; - float weight; - }; - - /** @} */ - /** @} */ - -} - -#endif diff --git a/OgreMain/include/OgreVertexIndexData.h b/OgreMain/include/OgreVertexIndexData.h deleted file mode 100644 index bc06c7e6829..00000000000 --- a/OgreMain/include/OgreVertexIndexData.h +++ /dev/null @@ -1,313 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __VertexIndexData_H__ -#define __VertexIndexData_H__ - -#include "OgrePrerequisites.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreHardwareIndexBuffer.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - - /** collects together all the vertex-related information used to render geometry. - * - * The RenderOperation requires a pointer to a VertexData object, and it is also used in Mesh and - * SubMesh to store the vertex positions, normals, texture coordinates etc. VertexData can either be - * used alone (in order to render unindexed geometry, where the stream of vertices defines the - * triangles), or in combination with IndexData where the triangles are defined by indexes which refer - * to the entries in VertexData. It’s worth noting that you don’t necessarily have to use VertexData to - * store your applications geometry; all that is required is that you can build a VertexData structure - * when it comes to rendering. This is pretty easy since all of VertexData’s members are pointers, so - * you could maintain your vertex buffers and declarations in alternative structures if you like, so - * long as you can convert them for rendering. - */ - class _OgreExport VertexData : public VertexDataAlloc - { - private: - /// Protected copy constructor, to prevent misuse - VertexData(const VertexData& rhs); /* do nothing, should not use */ - /// Protected operator=, to prevent misuse - VertexData& operator=(const VertexData& rhs); /* do not use */ - - HardwareBufferManagerBase* mMgr; - - typedef std::vector BufferUsageList; - void reorganiseBuffers(VertexDeclaration* newDeclaration, const BufferUsageList& bufferUsage, - HardwareBufferManagerBase* mgr); - public: - /** Constructor. - @note - This constructor creates the VertexDeclaration and VertexBufferBinding - automatically, and arranges for their deletion afterwards. - @param mgr Optional HardwareBufferManager from which to create resources - */ - VertexData(HardwareBufferManagerBase* mgr = 0); - /** Constructor. - @note - This constructor receives the VertexDeclaration and VertexBufferBinding - from the caller, and as such does not arrange for their deletion afterwards, - the caller remains responsible for that. - @param dcl The VertexDeclaration to use - @param bind The VertexBufferBinding to use - */ - VertexData(VertexDeclaration* dcl, VertexBufferBinding* bind); - ~VertexData(); - - /** Declaration of the the format of the vertex input. - Note that this is created for you on construction. - */ - VertexDeclaration* vertexDeclaration; - /** Defines which vertex buffers are bound to which sources. - Note that this is created for you on construction. - */ - VertexBufferBinding* vertexBufferBinding; - /// Whether this class should delete the declaration and binding - bool mDeleteDclBinding; - /// The position in the bound buffers to start reading vertex data from. This allows you to use a single buffer for many different renderables. - uint32 vertexStart; - /// The number of vertices to process in this particular rendering group - uint32 vertexCount; - - - /// Struct used to hold hardware morph / pose vertex data information - struct HardwareAnimationData - { - unsigned short targetBufferIndex; - float parametric; - }; - typedef std::vector HardwareAnimationDataList; - /// Number of hardware animation data items used - uint32 hwAnimDataItemsUsed; - /// VertexElements used for hardware morph / pose animation - HardwareAnimationDataList hwAnimationDataList; - - /** Clones this vertex data, potentially including replicating any vertex buffers. - @param copyData Whether to create new vertex buffers too or just reference the existing ones - @param mgr If supplied, the buffer manager through which copies should be made - @remarks The caller is expected to delete the returned pointer when ready - */ - VertexData* clone(bool copyData = true, HardwareBufferManagerBase* mgr = 0) const OGRE_NODISCARD; - - /** Modifies the vertex data to be suitable for use for rendering shadow geometry as in @cite mcguire2003fast - - Preparing vertex data to generate a shadow volume involves firstly ensuring that the - vertex buffer containing the positions is a standalone vertex buffer, - with no other components in it. This method will therefore break apart any existing - vertex buffers if position is sharing a vertex buffer. - Secondly, it will double the size of this vertex buffer so that there are 2 copies of - the position data for the mesh. The first half is used for the original, and the second - half is used for the 'extruded' version. The vertex count used to render will remain - the same though, so as not to add any overhead to regular rendering of the object. - Both copies of the position are required in one buffer because shadow volumes stretch - from the original mesh to the extruded version. - - It's important to appreciate that this method can fundamentally change the structure of your - vertex buffers, although in reality they will be new buffers. As it happens, if other - objects are using the original buffers then they will be unaffected because the reference - counting will keep them intact. However, if you have made any assumptions about the - structure of the vertex data in the buffers of this object, you may have to rethink them. - - Because shadow volumes are rendered in turn, no additional - index buffer space is allocated by this method, a shared index buffer allocated by the - shadow rendering algorithm is used for addressing this extended vertex buffer. - */ - void prepareForShadowVolume(void); - - /// converts between #VET_FLOAT3 or #VET_FLOAT4 and #VET_INT_10_10_10_2_NORM - void convertVertexElement(VertexElementSemantic semantic, VertexElementType dstType); - - /** Additional shadow volume vertex buffer storage. - - This additional buffer is only used where we have prepared this VertexData for - use in shadow volume construction, and where the current render system supports - vertex programs. This buffer contains the 'w' vertex position component which will - be used by that program to differentiate between extruded and non-extruded vertices. - This 'w' component cannot be included in the original position buffer because - DirectX does not allow 4-component positions in the fixed-function pipeline, and the original - position buffer must still be usable for fixed-function rendering. - @par - Note that we don't store any vertex declaration or vertex buffer binding here because this - can be reused in the shadow algorithm. - */ - HardwareVertexBufferSharedPtr hardwareShadowVolWBuffer; - - /** Reorganises the data in the vertex buffers according to the - new vertex declaration passed in. Note that new vertex buffers - are created and written to, so if the buffers being referenced - by this vertex data object are also used by others, then the - original buffers will not be damaged by this operation. - Once this operation has completed, the new declaration - passed in will overwrite the current one. - This version of the method derives the buffer usages from the existing - buffers, by using the 'most flexible' usage from the equivalent sources. - @param newDeclaration The vertex declaration which will be used - for the reorganised buffer state. Note that the new delcaration - must not include any elements which do not already exist in the - current declaration; you can drop elements by - excluding them from the declaration if you wish, however. - @param mgr Optional pointer to the manager to use to create new declarations - and buffers etc. If not supplied, the HardwareBufferManager singleton will be used - */ - void reorganiseBuffers(VertexDeclaration* newDeclaration, HardwareBufferManagerBase* mgr = 0); - - /** Remove any gaps in the vertex buffer bindings. - - This is useful if you've removed elements and buffers from this vertex - data and want to remove any gaps in the vertex buffer bindings. This - method is mainly useful when reorganising vertex data manually. - @note - This will cause binding index of the elements in the vertex declaration - to be altered to new binding index. - */ - void closeGapsInBindings(void); - - /** Remove all vertex buffers that never used by the vertex declaration. - - This is useful if you've removed elements from the vertex declaration - and want to unreference buffers that never used any more. This method - is mainly useful when reorganising vertex data manually. - @note - This also remove any gaps in the vertex buffer bindings. - */ - void removeUnusedBuffers(void); - - /** Convert all packed colour values (VET_COLOUR_*) in buffers used to - another type. - @param srcType The source colour type to assume if the ambiguous VET_COLOUR - is encountered. - @param destType The destination colour type, must be VET_COLOUR_ABGR or - VET_COLOUR_ARGB. - */ - void convertPackedColour(VertexElementType srcType, VertexElementType destType); - - - /** Allocate elements to serve a holder of morph / pose target data - for hardware morphing / pose blending. - - This method will allocate the given number of 3D texture coordinate - sets for use as a morph target or target pose offset (3D position). - These elements will be saved in hwAnimationDataList. - It will also assume that the source of these new elements will be new - buffers which are not bound at this time, so will start the sources to - 1 higher than the current highest binding source. The caller is - expected to bind these new buffers when appropriate. For morph animation - the original position buffer will be the 'from' keyframe data, whilst - for pose animation it will be the original vertex data. - If normals are animated, then twice the number of 3D texture coordinates are required - @return The number of sets that were supported - */ - ushort allocateHardwareAnimationElements(ushort count, bool animateNormals); - - /** Internal method to clone vertex data definitions but to remove blend buffers. */ - VertexData* _cloneRemovingBlendData() const; - }; - - /** Summary class collecting together index data source information. */ - class _OgreExport IndexData : public IndexDataAlloc - { - public: - IndexData(); - ~IndexData(); - /// Pointer to the HardwareIndexBuffer to use, must be specified if useIndexes = true - HardwareIndexBufferSharedPtr indexBuffer; - - /// Index in the buffer to start from for this operation - uint32 indexStart; - - /// The number of indexes to use from the buffer - uint32 indexCount; - - /** Clones this index data, potentially including replicating the index buffer. - @param copyData Whether to create new buffers too or just reference the existing ones - @param mgr If supplied, the buffer manager through which copies should be made - @remarks The caller is expected to delete the returned pointer when finished - */ - IndexData* clone(bool copyData = true, HardwareBufferManagerBase* mgr = 0) const; - - /** Re-order the indexes in this index data structure to be more - vertex cache friendly; that is to re-use the same vertices as close - together as possible. - - Can only be used for index data which consists of triangle lists. - It would in fact be pointless to use it on triangle strips or fans - in any case. - */ - void optimiseVertexCacheTriList(void); - - }; - - /** Vertex cache profiler. - - Utility class for evaluating the effectiveness of the use of the vertex - cache by a given index buffer. - */ - class _OgreExport VertexCacheProfiler : public BufferAlloc - { - public: - VertexCacheProfiler(unsigned int cachesize = 16) - : size ( cachesize ), tail (0), buffersize (0), hit (0), miss (0) - { - cache = OGRE_ALLOC_T(uint32, size, MEMCATEGORY_GEOMETRY); - } - - ~VertexCacheProfiler() - { - OGRE_FREE(cache, MEMCATEGORY_GEOMETRY); - } - - void profile(const HardwareIndexBufferSharedPtr& indexBuffer); - void reset() { hit = 0; miss = 0; tail = 0; buffersize = 0; } - void flush() { tail = 0; buffersize = 0; } - - unsigned int getHits() { return hit; } - unsigned int getMisses() { return miss; } - unsigned int getSize() { return size; } - private: - unsigned int size; - uint32 *cache; - - unsigned int tail, buffersize; - unsigned int hit, miss; - - bool inCache(unsigned int index); - }; - /** @} */ - /** @} */ -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreViewport.h b/OgreMain/include/OgreViewport.h deleted file mode 100644 index 0335a0aba8e..00000000000 --- a/OgreMain/include/OgreViewport.h +++ /dev/null @@ -1,395 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Viewport_H__ -#define __Viewport_H__ - -#include "OgrePrerequisites.h" -#include "OgreCommon.h" -#include "OgreFrustum.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup RenderSystem - * @{ - */ - /** An abstraction of a viewport, i.e. a rendering region on a render - target. - - A viewport is the meeting of a camera and a rendering surface - - the camera renders the scene from a viewpoint, and places its - results into some subset of a rendering target, which may be the - whole surface or just a part of the surface. Each viewport has a - single camera as source and a single target as destination. A - camera only has 1 viewport, but a render target may have several. - A viewport also has a Z-order, i.e. if there is more than one - viewport on a single render target and they overlap, one must - obscure the other in some predetermined way. - */ - class _OgreExport Viewport : public ViewportAlloc - { - public: - /** Listener interface so you can be notified of Viewport changes. */ - class _OgreExport Listener - { - public: - virtual ~Listener() {} - - /** Notification of when a new camera is set to target listening Viewport. */ - virtual void viewportCameraChanged(Viewport* viewport) {} - - /** Notification of when target listening Viewport's dimensions changed. */ - virtual void viewportDimensionsChanged(Viewport* viewport) {} - - /** Notification of when target listening Viewport's is destroyed. */ - virtual void viewportDestroyed(Viewport* viewport) {} - }; - - /** The usual constructor. - @param camera - Pointer to a camera to be the source for the image. - @param target - Pointer to the render target to be the destination - for the rendering. - @param left, top, width, height - Dimensions of the viewport, expressed as a value between - 0 and 1. This allows the dimensions to apply irrespective of - changes in the target's size: e.g. to fill the whole area, - values of 0,0,1,1 are appropriate. - @param ZOrder - Relative Z-order on the target. Lower = further to - the front. - */ - Viewport(Camera* camera, RenderTarget* target, float left, float top, float width, float height, int ZOrder); - - /** Default destructor. - */ - virtual ~Viewport(); - - /** Notifies the viewport of a possible change in dimensions. - - Used by the target to update the viewport's dimensions - (usually the result of a change in target size). - @note - Internal use by Ogre only. - */ - void _updateDimensions(void); - - /** Instructs the viewport to updates its contents. - */ - void update(void); - - /** Instructs the viewport to clear itself, without performing an update. - - You would not normally call this method when updating the viewport, - since the viewport usually clears itself when updating anyway (@see - Viewport::setClearEveryFrame). However, if you wish you have the - option of manually clearing the frame buffer (or elements of it) - using this method. - @param buffers Bitmask identifying which buffer elements to clear - @param colour The colour value to clear to, if FBT_COLOUR is included - @param depth The depth value to clear to, if FBT_DEPTH is included - @param stencil The stencil value to clear to, if FBT_STENCIL is included - */ - void clear(uint32 buffers = FBT_COLOUR | FBT_DEPTH, const ColourValue& colour = ColourValue::Black, - float depth = 1.0f, uint16 stencil = 0); - - /** Retrieves a pointer to the render target for this viewport. - */ - RenderTarget* getTarget(void) const { return mTarget; } - - /** Retrieves a pointer to the camera for this viewport. - */ - Camera* getCamera(void) const { return mCamera; } - - /** Sets the camera to use for rendering to this viewport. */ - void setCamera(Camera* cam); - - /** Gets the Z-Order of this viewport. */ - int getZOrder(void) const { return mZOrder; } - /** Gets one of the relative dimensions of the viewport, - a value between 0.0 and 1.0. - */ - float getLeft(void) const { return mRelRect.left; } - - /** Gets one of the relative dimensions of the viewport, a value - between 0.0 and 1.0. - */ - float getTop(void) const { return mRelRect.top; } - - /** Gets one of the relative dimensions of the viewport, a value - between 0.0 and 1.0. - */ - float getWidth(void) const { return mRelRect.width(); } - /** Gets one of the relative dimensions of the viewport, a value - between 0.0 and 1.0. - */ - float getHeight(void) const { return mRelRect.height(); } - /** Gets one of the actual dimensions of the viewport, a value in - pixels. - */ - - int getActualLeft(void) const { return mActRect.left; } - /** Gets one of the actual dimensions of the viewport, a value in - pixels. - */ - - int getActualTop(void) const { return mActRect.top; } - /** Gets one of the actual dimensions of the viewport, a value in - pixels. - */ - int getActualWidth(void) const { return mActRect.width(); } - /** Gets one of the actual dimensions of the viewport, a value in - pixels. - */ - - int getActualHeight(void) const { return mActRect.height(); } - - /** Sets the dimensions (after creation). - @param - left Left point of viewport. - @param - top Top point of the viewport. - @param - width Width of the viewport. - @param - height Height of the viewport. - @note Dimensions relative to the size of the target, - represented as real values between 0 and 1. i.e. the full - target area is 0, 0, 1, 1. - */ - void setDimensions(float left, float top, float width, float height); - - /** Sets the initial background colour of the viewport (before - rendering). - */ - void setBackgroundColour(const ColourValue& colour) { mBackColour = colour; } - - /** Gets the background colour. - */ - const ColourValue& getBackgroundColour(void) const { return mBackColour; } - - /** Sets the initial depth buffer value of the viewport (before - rendering). Default is 1 - */ - void setDepthClear( float depth ) { mDepthClearValue = depth; } - - /** Gets the default depth buffer value to which the viewport is cleared. - */ - float getDepthClear(void) const { return mDepthClearValue; } - - /** Determines whether to clear the viewport before rendering. - - You can use this method to set which buffers are cleared - (if any) before rendering every frame. - @param clear Whether or not to clear any buffers - @param buffers One or more values from FrameBufferType denoting - which buffers to clear, if clear is set to true. Note you should - not clear the stencil buffer here unless you know what you're doing. - */ - void setClearEveryFrame(bool clear, unsigned int buffers = FBT_COLOUR | FBT_DEPTH); - - /** Determines if the viewport is cleared before every frame. - */ - bool getClearEveryFrame(void) const { return mClearEveryFrame; } - - /** Gets which buffers are to be cleared each frame. */ - unsigned int getClearBuffers(void) const { return mClearBuffers; } - - /** Sets whether this viewport should be automatically updated - if Ogre's rendering loop or RenderTarget::update is being used. - - By default, if you use Ogre's own rendering loop (Root::startRendering) - or call RenderTarget::update, all viewports are updated automatically. - This method allows you to control that behaviour, if for example you - have a viewport which you only want to update periodically. - @param autoupdate If true, the viewport is updated during the automatic - render loop or when RenderTarget::update() is called. If false, the - viewport is only updated when its update() method is called explicitly. - */ - void setAutoUpdated(bool autoupdate) { mIsAutoUpdated = autoupdate; } - /** Gets whether this viewport is automatically updated if - Ogre's rendering loop or RenderTarget::update is being used. - */ - bool isAutoUpdated() const { return mIsAutoUpdated; } - - /** Set the material scheme which the viewport should use. - - This allows you to tell the system to use a particular - material scheme when rendering this viewport, which can - involve using different techniques to render your materials. - @see Technique::setSchemeName - */ - void setMaterialScheme(const String& schemeName) - { mMaterialSchemeName = schemeName; } - - /** Get the material scheme which the viewport should use. - */ - const String& getMaterialScheme(void) const - { return mMaterialSchemeName; } - - /** Access to actual dimensions (based on target size). - */ - Rect getActualDimensions() const { return mActRect; } - - /// @deprecated - OGRE_DEPRECATED void getActualDimensions(int& left, int& top, int& width, int& height) const; - - bool _isUpdated(void) const; - void _clearUpdatedFlag(void); - - /** Gets the number of rendered faces in the last update. - */ - unsigned int _getNumRenderedFaces(void) const; - - /** Gets the number of rendered batches in the last update. - */ - unsigned int _getNumRenderedBatches(void) const; - - /** Tells this viewport whether it should display Overlay objects. - - Overlay objects are layers which appear on top of the scene. They are created via - SceneManager::createOverlay and every viewport displays these by default. - However, you probably don't want this if you're using multiple viewports, - because one of them is probably a picture-in-picture which is not supposed to - have overlays of it's own. In this case you can turn off overlays on this viewport - by calling this method. - @param enabled If true, any overlays are displayed, if false they are not. - */ - void setOverlaysEnabled(bool enabled) { mShowOverlays = enabled; } - - /** Returns whether or not Overlay objects (created in the SceneManager) are displayed in this - viewport. */ - bool getOverlaysEnabled(void) const { return mShowOverlays; } - - /** Tells this viewport whether it should display skies. - - Skies are layers which appear on background of the scene. They are created via - SceneManager::setSkyBox, SceneManager::setSkyPlane and SceneManager::setSkyDome and - every viewport displays these by default. However, you probably don't want this if - you're using multiple viewports, because one of them is probably a picture-in-picture - which is not supposed to have skies of it's own. In this case you can turn off skies - on this viewport by calling this method. - @param enabled If true, any skies are displayed, if false they are not. - */ - void setSkiesEnabled(bool enabled) { mShowSkies = enabled; } - - /** Returns whether or not skies (created in the SceneManager) are displayed in this - viewport. */ - bool getSkiesEnabled(void) const { return mShowSkies; } - - /** Tells this viewport whether it should display shadows. - - This setting enables you to disable shadow rendering for a given viewport. The global - shadow technique set on SceneManager still controls the type and nature of shadows, - but this flag can override the setting so that no shadows are rendered for a given - viewport to save processing time where they are not required. - @param enabled If true, any shadows are displayed, if false they are not. - */ - void setShadowsEnabled(bool enabled) { mShowShadows = enabled; } - - /** Returns whether or not shadows (defined in the SceneManager) are displayed in this - viewport. */ - bool getShadowsEnabled(void) const { return mShowShadows; } - - - /** Sets a per-viewport visibility mask. - - The visibility mask is a way to exclude objects from rendering for - a given viewport. For each object in the frustum, a check is made - between this mask and the objects visibility flags - (@see MovableObject::setVisibilityFlags), and if a binary 'and' - returns zero, the object will not be rendered. - */ - void setVisibilityMask(uint32 mask) { mVisibilityMask = mask; } - - /** Gets a per-viewport visibility mask. - @see Viewport::setVisibilityMask - */ - uint getVisibilityMask(void) const { return mVisibilityMask; } - - /// Add a listener to this viewport - void addListener(Listener* l); - /// Remove a listener to this viewport - void removeListener(Listener* l); - - /** Sets the draw buffer type for the next frame. - - Specifies the particular buffer that will be - targeted by the render target. Should be used if - the render target supports quad buffer stereo. If - the render target does not support stereo (ie. left - and right), then only back and front will be used. - @param - colourBuffer Specifies the particular buffer that will be - targeted by the render target. - */ - void setDrawBuffer(ColourBufferType colourBuffer) { mColourBuffer = colourBuffer; } - - /** Returns the current colour buffer type for this viewport.*/ - ColourBufferType getDrawBuffer() const { return mColourBuffer; } - - private: - Camera* mCamera; - RenderTarget* mTarget; - /// Relative dimensions, irrespective of target dimensions (0..1) - FloatRect mRelRect; - /// Actual dimensions, based on target dimensions - Rect mActRect; - /// Z-order - int mZOrder; - /// Background options - ColourValue mBackColour; - float mDepthClearValue; - bool mClearEveryFrame; - unsigned int mClearBuffers; - bool mUpdated; - bool mShowOverlays; - bool mShowSkies; - bool mShowShadows; - uint32 mVisibilityMask; - /// Material scheme - String mMaterialSchemeName; - - /// Automatic rendering on/off - bool mIsAutoUpdated; - - typedef std::vector ListenerList; - ListenerList mListeners; - ColourBufferType mColourBuffer; - }; - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/OgreWireBoundingBox.h b/OgreMain/include/OgreWireBoundingBox.h deleted file mode 100644 index 89797bfcf93..00000000000 --- a/OgreMain/include/OgreWireBoundingBox.h +++ /dev/null @@ -1,87 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _WireBoundingBox_H__ -#define _WireBoundingBox_H__ - -#include "OgrePrerequisites.h" - -#include "OgreSimpleRenderable.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** Allows the rendering of a wireframe bounding box. - - This class builds a wireframe renderable from a given aabb. A pointer to this class can be - added to a render queue to display the bounding box of an object. - */ - class _OgreExport WireBoundingBox : public SimpleRenderable - { - private: - /** Override this method to prevent parent transforms (rotation,translation,scale) - */ - void getWorldTransforms( Matrix4* xform ) const override; - - /** Builds the wireframe line list. - */ - void setupBoundingBoxVertices(const AxisAlignedBox& aab); - - Real mRadius; - - void _initWireBoundingBox(); - - public: - - WireBoundingBox(); - WireBoundingBox(const String& name); - ~WireBoundingBox(); - - /** Builds the wireframe line list. - @param - aabb bounding box to build a wireframe from. - */ - void setupBoundingBox(const AxisAlignedBox& aabb); - - Real getSquaredViewDepth(const Camera* cam) const override; - - Real getBoundingRadius(void) const override { return mRadius; } - - }; - /** @} */ - /** @} */ - -}// namespace - -#endif - - diff --git a/OgreMain/include/OgreWorkQueue.h b/OgreMain/include/OgreWorkQueue.h deleted file mode 100644 index 155f77a30be..00000000000 --- a/OgreMain/include/OgreWorkQueue.h +++ /dev/null @@ -1,322 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OgreWorkQueue_H__ -#define __OgreWorkQueue_H__ - -#include "OgrePrerequisites.h" -#include "OgreAny.h" -#include "OgreSharedPtr.h" -#include "OgreCommon.h" -#include "Threading/OgreThreadHeaders.h" -#include "OgreHeaderPrefix.h" - -#include -#include - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - - /** Interface to a general purpose task-basedbackground work queue. - - A work queue is a simple structure, where tasks of work are placed - onto the queue, then removed by a worker for processing. - The typical use for this is in a threaded environment, - although any kind of deferred processing could use this approach to - decouple and distribute work over a period of time even - if it was single threaded. - - WorkQueues also incorporate thread pools. One or more background worker threads - can wait on the queue and be notified when a request is waiting to be - processed. For maximal thread usage, a WorkQueue instance should be shared - among many sources of work, rather than many work queues being created. - This way, you can share a small number of hardware threads among a large - number of background tasks. This doesn't mean you have to implement all the - request processing in one class, you can plug in many handlers in order to - process the tasks. - - This is an abstract interface definition; users can subclass this and - provide their own implementation if required to centralise task management - in their own subsystems. We also provide a default implementation in the - form of DefaultWorkQueue. - */ - class _OgreExport WorkQueue : public UtilityAlloc - { - public: - /// Numeric identifier for a request - typedef unsigned long long int RequestID; - - /** General purpose request structure. - */ - class _OgreExport Request : public UtilityAlloc - { - friend class WorkQueue; - protected: - /// The request channel, as an integer - uint16 mChannel; - /// The request type, as an integer within the channel (user can define enumerations on this) - uint16 mType; - /// The details of the request (user defined) - Any mData; - /// Retry count - set this to non-zero to have the request try again on failure - uint8 mRetryCount; - /// Identifier (assigned by the system) - RequestID mID; - /// Abort Flag - mutable bool mAborted; - - public: - /// Constructor - Request(uint16 channel, uint16 rtype, const Any& rData, uint8 retry, RequestID rid); - ~Request(); - /// Get the request channel (top level categorisation) - uint16 getChannel() const { return mChannel; } - /// Get the type of this request within the given channel - uint16 getType() const { return mType; } - /// Get the user details of this request - const Any& getData() const { return mData; } - /// Get the remaining retry count - uint8 getRetryCount() const { return mRetryCount; } - /// Get the identifier of this request - RequestID getID() const { return mID; } - }; - - /** General purpose response structure. - */ - struct _OgreExport Response : public UtilityAlloc - { - /// Pointer to the request that this response is in relation to - const Request* mRequest; - /// Whether the work item succeeded or not - bool mSuccess; - /// Any diagnostic messages - String mMessages; - /// Data associated with the result of the process - Any mData; - - public: - Response(const Request* rq, bool success, const Any& data, const String& msg = BLANKSTRING); - ~Response(); - /// Get the request that this is a response to (NB destruction destroys this) - const Request* getRequest() const { return mRequest; } - /// Return whether this is a successful response - bool succeeded() const { return mSuccess; } - /// Get any diagnostic messages about the process - const String& getMessages() const { return mMessages; } - /// Return the response data (user defined, only valid on success) - const Any& getData() const { return mData; } - }; - WorkQueue() {} - virtual ~WorkQueue() {} - - /** Start up the queue with the options that have been set. - @param forceRestart If the queue is already running, whether to shut it - down and restart. - */ - virtual void startup(bool forceRestart = true) = 0; - - /** Add a new task to the queue */ - virtual void addTask(std::function task) = 0; - - /** Set whether to pause further processing of any requests. - If true, any further requests will simply be queued and not processed until - setPaused(false) is called. Any requests which are in the process of being - worked on already will still continue. - */ - virtual void setPaused(bool pause) = 0; - /// Return whether the queue is paused ie not sending more work to workers - virtual bool isPaused() const = 0; - - /** Set whether to accept new requests or not. - If true, requests are added to the queue as usual. If false, requests - are silently ignored until setRequestsAccepted(true) is called. - */ - virtual void setRequestsAccepted(bool accept) = 0; - /// Returns whether requests are being accepted right now - virtual bool getRequestsAccepted() const = 0; - - /** Process the tasks in the main-thread queue. - - This method must be called from the main render - thread to 'pump' tasks through the system. The method will usually - try to clear all tasks before returning; however, you can specify - a time limit on the tasks processing to limit the impact of - spikes in demand by calling @ref setMainThreadProcessingTimeLimit. - */ - virtual void processMainThreadTasks(); - - /// @deprecated use @ref processMainThreadTasks - OGRE_DEPRECATED virtual void processResponses() { } - - /** Get the time limit imposed on the processing of tasks in a - single frame, in milliseconds (0 indicates no limit). - */ - uint64 getMainThreadProcessingTimeLimit() const { return getResponseProcessingTimeLimit(); } - - /// @deprecated use @ref getMainThreadProcessingTimeLimit() - virtual unsigned long getResponseProcessingTimeLimit() const = 0; - - /** Set the time limit imposed on the processing of tasks in a - single frame, in milliseconds (0 indicates no limit). - This sets the maximum time that will be spent in @ref processMainThreadTasks() in - a single frame. The default is 10ms. - */ - void setMainThreadProcessingTimeLimit(uint64 ms) { setResponseProcessingTimeLimit(ms); } - - /// @deprecated use @ref setMainThreadProcessingTimeLimit - virtual void setResponseProcessingTimeLimit(unsigned long ms) = 0; - - /** Add a deferred task that will be processed on the main render thread */ - virtual void addMainThreadTask(std::function task) = 0; - - /** Shut down the queue. - */ - virtual void shutdown() = 0; - }; - - /** Base for a general purpose task-based background work queue. - */ - class _OgreExport DefaultWorkQueueBase : public WorkQueue - { - public: - - /** Constructor. - Call startup() to initialise. - @param name Optional name, just helps to identify logging output - */ - DefaultWorkQueueBase(const String& name = BLANKSTRING); - virtual ~DefaultWorkQueueBase(); - /// Get the name of the work queue - const String& getName() const; - /** Get the number of worker threads that this queue will start when - startup() is called. - */ - virtual size_t getWorkerThreadCount() const; - - /** Set the number of worker threads that this queue will start - when startup() is called (default 1). - Calling this will have no effect unless the queue is shut down and - restarted. - */ - virtual void setWorkerThreadCount(size_t c); - - /** Get whether worker threads will be allowed to access render system - resources. - Accessing render system resources from a separate thread can require that - a context is maintained for that thread. Also, it requires that the - render system is running in threadsafe mode, which only happens - when OGRE_THREAD_SUPPORT=1. This option defaults to false, which means - that threads can not use GPU resources, and the render system can - work in non-threadsafe mode, which is more efficient. - */ - virtual bool getWorkersCanAccessRenderSystem() const; - - - /** Set whether worker threads will be allowed to access render system - resources. - Accessing render system resources from a separate thread can require that - a context is maintained for that thread. Also, it requires that the - render system is running in threadsafe mode, which only happens - when OGRE_THREAD_SUPPORT=1. This option defaults to false, which means - that threads can not use GPU resources, and the render system can - work in non-threadsafe mode, which is more efficient. - Calling this will have no effect unless the queue is shut down and - restarted. - */ - virtual void setWorkersCanAccessRenderSystem(bool access); - - /** Process the next request on the queue. - - This method is public, but only intended for advanced users to call. - The only reason you would call this, is if you were using your - own thread to drive the worker processing. The thread calling this - method will be the thread used to call the RequestHandler. - */ - virtual void _processNextRequest(); - - /// Main function for each thread spawned. - virtual void _threadMain() = 0; - - /** Returns whether the queue is trying to shut down. */ - virtual bool isShuttingDown() const { return mShuttingDown; } - - /// @copydoc WorkQueue::setPaused - void setPaused(bool pause) override; - /// @copydoc WorkQueue::isPaused - bool isPaused() const override; - /// @copydoc WorkQueue::setRequestsAccepted - void setRequestsAccepted(bool accept) override; - /// @copydoc WorkQueue::getRequestsAccepted - virtual bool getRequestsAccepted() const override; - void processMainThreadTasks() override; - /// @copydoc WorkQueue::getResponseProcessingTimeLimit - unsigned long getResponseProcessingTimeLimit() const override { return mResposeTimeLimitMS; } - /// @copydoc WorkQueue::setResponseProcessingTimeLimit - void setResponseProcessingTimeLimit(unsigned long ms) override { mResposeTimeLimitMS = ms; } - - void addMainThreadTask(std::function task) override; - void addTask(std::function task) override; - protected: - String mName; - size_t mWorkerThreadCount; - bool mWorkerRenderSystemAccess; - bool mIsRunning; - unsigned long mResposeTimeLimitMS; - - std::deque> mTasks; - std::deque> mMainThreadTasks; - - bool mPaused; - bool mAcceptRequests; - bool mShuttingDown; - - OGRE_WQ_MUTEX(mRequestMutex); - OGRE_WQ_MUTEX(mResponseMutex); - - /// Notify workers about a new request. - virtual void notifyWorkers() = 0; - }; - - - - - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/include/OgreZip.h b/OgreMain/include/OgreZip.h deleted file mode 100644 index 0798c585b9f..00000000000 --- a/OgreMain/include/OgreZip.h +++ /dev/null @@ -1,122 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Zip_H__ -#define __Zip_H__ - -#include "OgrePrerequisites.h" - -#include "OgreArchive.h" -#include "OgreArchiveFactory.h" -#include "OgreHeaderPrefix.h" -#include "Threading/OgreThreadHeaders.h" - -struct AAssetManager; -struct AAsset; - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - - /** Specialisation to allow reading of files from a zip - format source archive. - - This archive format supports all archives compressed in the standard - zip format, including iD pk3 files. - */ - class _OgreExport ZipArchiveFactory : public ArchiveFactory - { - public: - virtual ~ZipArchiveFactory() {} - /// @copydoc FactoryObj::getType - const String& getType(void) const override; - - using ArchiveFactory::createInstance; - - Archive *createInstance( const String& name, bool readOnly ) override; - }; - - /** Specialisation of ZipArchiveFactory for embedded Zip files. */ - class _OgreExport EmbeddedZipArchiveFactory : public ZipArchiveFactory - { - public: - EmbeddedZipArchiveFactory(); - virtual ~EmbeddedZipArchiveFactory(); - - const String& getType(void) const override; - - using ArchiveFactory::createInstance; - - Archive *createInstance( const String& name, bool readOnly ) override; - void destroyInstance( Archive* ptr) override; - - /** a function type to decrypt embedded zip file - @param pos pos in file - @param buf current buffer to decrypt - @param len - length of buffer - @return success - */ - typedef bool (*DecryptEmbeddedZipFileFunc)(size_t pos, void* buf, size_t len); - - /// Add an embedded file to the embedded file list - static void addEmbbeddedFile(const String& name, const uint8 * fileData, - size_t fileSize, DecryptEmbeddedZipFileFunc decryptFunc); - - /// Remove an embedded file to the embedded file list - static void removeEmbbeddedFile(const String& name); - - }; - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - class APKZipArchiveFactory : public EmbeddedZipArchiveFactory - { - std::map mOpenAssets; - private: - AAssetManager* mAssetMgr; - public: - APKZipArchiveFactory(AAssetManager* assetMgr) : mAssetMgr(assetMgr) {} - virtual ~APKZipArchiveFactory() {} - - const String& getType(void) const override; - Archive *createInstance( const String& name, bool readOnly ) override; - void destroyInstance( Archive* ptr) override; - }; -#endif - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/include/Threading/OgreThreadDefines.h b/OgreMain/include/Threading/OgreThreadDefines.h deleted file mode 100644 index 88e2d7f7cfb..00000000000 --- a/OgreMain/include/Threading/OgreThreadDefines.h +++ /dev/null @@ -1,69 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ -#ifndef __OgreThreadDefines_H__ -#define __OgreThreadDefines_H__ - -#define OGRE_AUTO_MUTEX_NAME mutex -#if OGRE_THREAD_PROVIDER == 0 - #include "OgreThreadDefinesNone.h" -#elif OGRE_THREAD_PROVIDER == 1 - #include "OgreThreadDefinesBoost.h" -#elif OGRE_THREAD_PROVIDER == 2 - #include "OgreThreadDefinesPoco.h" -#elif OGRE_THREAD_PROVIDER == 3 - #include "OgreThreadDefinesTBB.h" -#elif OGRE_THREAD_PROVIDER == 4 - #include "OgreThreadDefinesSTD.h" -#endif - -#if OGRE_THREAD_SUPPORT == 3 - #include "OgreThreadDefinesNone.h" - - // all empty definitions - #define OGRE_MUTEX(name) - - #define OGRE_LOCK_MUTEX(name) - #define OGRE_LOCK_MUTEX_NAMED(mutexName, lockName) - - #define OGRE_RW_MUTEX(name) - #define OGRE_LOCK_RW_MUTEX_READ(name) - #define OGRE_LOCK_RW_MUTEX_WRITE(name) - #define OGRE_THREAD_SYNCHRONISER(sync) -#else - // alias to WQ names - #define OGRE_MUTEX(name) OGRE_WQ_MUTEX(name) - - #define OGRE_LOCK_MUTEX(name) OGRE_WQ_LOCK_MUTEX(name) - #define OGRE_LOCK_MUTEX_NAMED(mutexName, lockName) OGRE_WQ_LOCK_MUTEX_NAMED(mutexName, lockName) - - #define OGRE_RW_MUTEX(name) OGRE_WQ_RW_MUTEX(name) - #define OGRE_LOCK_RW_MUTEX_READ(name) OGRE_WQ_LOCK_RW_MUTEX_READ(name) - #define OGRE_LOCK_RW_MUTEX_WRITE(name) OGRE_WQ_LOCK_RW_MUTEX_WRITE(name) - #define OGRE_THREAD_SYNCHRONISER(sync) OGRE_WQ_THREAD_SYNCHRONISER(sync) -#endif - -#endif - diff --git a/OgreMain/include/Threading/OgreThreadDefinesBoost.h b/OgreMain/include/Threading/OgreThreadDefinesBoost.h deleted file mode 100644 index 92ee9ee81fe..00000000000 --- a/OgreMain/include/Threading/OgreThreadDefinesBoost.h +++ /dev/null @@ -1,83 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ -#ifndef __OgreThreadDefinesBoost_H__ -#define __OgreThreadDefinesBoost_H__ - -// Thread objects and related functions -#define OGRE_THREAD_TYPE boost::thread -#define OGRE_THREAD_CREATE(name, worker) boost::thread* name = OGRE_NEW_T(boost::thread, MEMCATEGORY_GENERAL)(worker) -#define OGRE_THREAD_DESTROY(name) OGRE_DELETE_T(name, thread, MEMCATEGORY_GENERAL) -#define OGRE_THREAD_CURRENT_ID boost::this_thread::get_id() -#define OGRE_THREAD_HARDWARE_CONCURRENCY boost::thread::hardware_concurrency() -#define OGRE_THREAD_WORKER_INHERIT - -#define OGRE_THREAD_WAIT(sync, mutex, lock) sync.wait(lock) -#define OGRE_THREAD_NOTIFY_ONE(sync) sync.notify_one() -#define OGRE_THREAD_NOTIFY_ALL(sync) sync.notify_all() - -// Read-write mutex -#define OGRE_WQ_RW_MUTEX(name) mutable boost::shared_mutex name -#define OGRE_WQ_LOCK_RW_MUTEX_READ(name) boost::shared_lock OGRE_TOKEN_PASTE(ogrenameLock, __LINE__) (name) -#define OGRE_WQ_LOCK_RW_MUTEX_WRITE(name) boost::unique_lock OGRE_TOKEN_PASTE(ogrenameLock, __LINE__) (name) - -#define OGRE_WQ_MUTEX(name) mutable boost::recursive_mutex name -#if BOOST_THREAD_VERSION < 4 -#define OGRE_WQ_LOCK_MUTEX(name) boost::recursive_mutex::scoped_lock OGRE_TOKEN_PASTE(ogrenameLock, __LINE__) (name) -#define OGRE_WQ_LOCK_MUTEX_NAMED(mutexName, lockName) boost::recursive_mutex::scoped_lock lockName(mutexName) -#define OGRE_WQ_THREAD_SYNCHRONISER(sync) boost::condition sync -#else -#define OGRE_WQ_LOCK_MUTEX(name) boost::unique_lock OGRE_TOKEN_PASTE(ogrenameLock, __LINE__) (name) -#define OGRE_WQ_LOCK_MUTEX_NAMED(mutexName, lockName) boost::unique_lock lockName(mutexName) -#define OGRE_WQ_THREAD_SYNCHRONISER(sync) boost::condition_variable_any sync -#endif - -#if OGRE_THREAD_SUPPORT != 3 -#if BOOST_THREAD_VERSION < 4 -#define OGRE_LOCK_AUTO_MUTEX boost::recursive_mutex::scoped_lock ogreAutoMutexLock(OGRE_AUTO_MUTEX_NAME) -#define OGRE_THREAD_SLEEP(ms) boost::this_thread::sleep(boost::posix_time::millisec(ms)) -#else -#define OGRE_LOCK_AUTO_MUTEX boost::unique_lock ogreAutoMutexLock(OGRE_AUTO_MUTEX_NAME) -#define OGRE_THREAD_SLEEP(ms) boost::this_thread::sleep_for(boost::chrono::milliseconds(ms)) -#endif - -#define OGRE_AUTO_MUTEX mutable boost::recursive_mutex OGRE_AUTO_MUTEX_NAME -#define OGRE_STATIC_MUTEX(name) static boost::recursive_mutex name -#define OGRE_STATIC_MUTEX_INSTANCE(name) boost::recursive_mutex name -// like OGRE_AUTO_MUTEX but mutex held by pointer -#define OGRE_AUTO_SHARED_MUTEX mutable boost::recursive_mutex *OGRE_AUTO_MUTEX_NAME -#define OGRE_LOCK_AUTO_SHARED_MUTEX assert(OGRE_AUTO_MUTEX_NAME); boost::recursive_mutex::scoped_lock ogreAutoMutexLock(*OGRE_AUTO_MUTEX_NAME) -#define OGRE_NEW_AUTO_SHARED_MUTEX assert(!OGRE_AUTO_MUTEX_NAME); OGRE_AUTO_MUTEX_NAME = new boost::recursive_mutex() -#define OGRE_DELETE_AUTO_SHARED_MUTEX do { assert(OGRE_AUTO_MUTEX_NAME); delete OGRE_AUTO_MUTEX_NAME; } while (0) -#define OGRE_COPY_AUTO_SHARED_MUTEX(from) assert(!OGRE_AUTO_MUTEX_NAME); OGRE_AUTO_MUTEX_NAME = from -#define OGRE_SET_AUTO_SHARED_MUTEX_NULL OGRE_AUTO_MUTEX_NAME = 0 -#define OGRE_MUTEX_CONDITIONAL(mutex) if (mutex) - -// Utility -#define OGRE_THREAD_ID_TYPE boost::thread::id -#define OGRE_THREAD_YIELD boost::this_thread::yield() -#endif - -#endif diff --git a/OgreMain/include/Threading/OgreThreadDefinesNone.h b/OgreMain/include/Threading/OgreThreadDefinesNone.h deleted file mode 100644 index 864750fdc79..00000000000 --- a/OgreMain/include/Threading/OgreThreadDefinesNone.h +++ /dev/null @@ -1,63 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ -#ifndef __OgreThreadDefinesNone_H__ -#define __OgreThreadDefinesNone_H__ - -#if OGRE_THREAD_SUPPORT != 3 -#define OGRE_THREAD_HARDWARE_CONCURRENCY 1 -#define OGRE_THREAD_CURRENT_ID "main" -#define OGRE_THREAD_WORKER_INHERIT - -// will be defined by the respective thread provider -#define OGRE_WQ_MUTEX(name) -#define OGRE_WQ_LOCK_MUTEX(name) -#define OGRE_WQ_LOCK_MUTEX_NAMED(mutexName, lockName) - -#define OGRE_WQ_RW_MUTEX(name) -#define OGRE_WQ_LOCK_RW_MUTEX_READ(name) -#define OGRE_WQ_LOCK_RW_MUTEX_WRITE(name) - -#define OGRE_WQ_THREAD_SYNCHRONISER(sync) -#define OGRE_THREAD_NOTIFY_ONE(sync) -#define OGRE_THREAD_NOTIFY_ALL(sync) -#endif - -#define OGRE_AUTO_MUTEX -#define OGRE_LOCK_AUTO_MUTEX -#define OGRE_STATIC_MUTEX(name) -#define OGRE_STATIC_MUTEX_INSTANCE(name) -#define OGRE_AUTO_SHARED_MUTEX -#define OGRE_LOCK_AUTO_SHARED_MUTEX -#define OGRE_NEW_AUTO_SHARED_MUTEX -#define OGRE_DELETE_AUTO_SHARED_MUTEX -#define OGRE_COPY_AUTO_SHARED_MUTEX(from) -#define OGRE_SET_AUTO_SHARED_MUTEX_NULL -#define OGRE_MUTEX_CONDITIONAL(name) if(true) - -#define OGRE_THREAD_SLEEP(ms) -#define OGRE_THREAD_YIELD - -#endif diff --git a/OgreMain/include/Threading/OgreThreadDefinesPoco.h b/OgreMain/include/Threading/OgreThreadDefinesPoco.h deleted file mode 100644 index 22e7a4422c2..00000000000 --- a/OgreMain/include/Threading/OgreThreadDefinesPoco.h +++ /dev/null @@ -1,72 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ -#ifndef __OgreThreadDefinesPoco_H__ -#define __OgreThreadDefinesPoco_H__ - -// Thread objects and related functions -#define OGRE_THREAD_TYPE Poco::Thread -#define OGRE_THREAD_CREATE(name, worker) Poco::Thread* name = OGRE_NEW_T(Poco::Thread, MEMCATEGORY_GENERAL)(); name->start(worker) -#define OGRE_THREAD_DESTROY(name) OGRE_DELETE_T(name, Thread, MEMCATEGORY_GENERAL) -#define OGRE_THREAD_HARDWARE_CONCURRENCY Poco::Environment::processorCount() -#define OGRE_THREAD_CURRENT_ID (size_t)Poco::Thread::current() -#define OGRE_THREAD_WORKER_INHERIT : public Poco::Runnable - -#define OGRE_WQ_MUTEX(name) mutable Poco::Mutex name -#define OGRE_WQ_LOCK_MUTEX(name) Poco::Mutex::ScopedLock OGRE_TOKEN_PASTE(ogrenameLock, __LINE__) (name) -#define OGRE_WQ_LOCK_MUTEX_NAMED(mutexName, lockName) Poco::Mutex::ScopedLock lockName(mutexName) - -// Read-write mutex -#define OGRE_WQ_RW_MUTEX(name) mutable Poco::RWLock name -#define OGRE_WQ_LOCK_RW_MUTEX_READ(name) Poco::RWLock::ScopedLock OGRE_TOKEN_PASTE(ogrenameLock, __LINE__) (name, false) -#define OGRE_WQ_LOCK_RW_MUTEX_WRITE(name) Poco::RWLock::ScopedLock OGRE_TOKEN_PASTE(ogrenameLock, __LINE__) (name, true) - -#define OGRE_WQ_THREAD_SYNCHRONISER(sync) Poco::Condition sync -#define OGRE_THREAD_WAIT(sync, mutex, lock) sync.wait(mutex) -#define OGRE_THREAD_NOTIFY_ONE(sync) sync.signal() -#define OGRE_THREAD_NOTIFY_ALL(sync) sync.broadcast() - -#if OGRE_THREAD_SUPPORT != 3 -#define OGRE_AUTO_MUTEX mutable Poco::Mutex OGRE_AUTO_MUTEX_NAME -#define OGRE_LOCK_AUTO_MUTEX Poco::Mutex::ScopedLock ogreAutoMutexLock(OGRE_AUTO_MUTEX_NAME) -#define OGRE_STATIC_MUTEX(name) static Poco::Mutex name -#define OGRE_STATIC_MUTEX_INSTANCE(name) Poco::Mutex name -// like OGRE_AUTO_MUTEX but mutex held by pointer -#define OGRE_AUTO_SHARED_MUTEX mutable Poco::Mutex *OGRE_AUTO_MUTEX_NAME -#define OGRE_LOCK_AUTO_SHARED_MUTEX assert(OGRE_AUTO_MUTEX_NAME); Poco::Mutex::ScopedLock ogreAutoMutexLock(*OGRE_AUTO_MUTEX_NAME) -#define OGRE_NEW_AUTO_SHARED_MUTEX assert(!OGRE_AUTO_MUTEX_NAME); OGRE_AUTO_MUTEX_NAME = new Poco::Mutex() -#define OGRE_DELETE_AUTO_SHARED_MUTEX assert(OGRE_AUTO_MUTEX_NAME); delete OGRE_AUTO_MUTEX_NAME -#define OGRE_COPY_AUTO_SHARED_MUTEX(from) assert(!OGRE_AUTO_MUTEX_NAME); OGRE_AUTO_MUTEX_NAME = from -#define OGRE_SET_AUTO_SHARED_MUTEX_NULL OGRE_AUTO_MUTEX_NAME = 0 -#define OGRE_MUTEX_CONDITIONAL(mutex) if (mutex) - -// (hardware concurrency is not accessible via POCO atm) -// Utility -#define OGRE_THREAD_SLEEP(ms) Poco::Thread::sleep(ms) -#define OGRE_THREAD_ID_TYPE size_t -#define OGRE_THREAD_YIELD Poco::Thread::yield() -#endif - -#endif diff --git a/OgreMain/include/Threading/OgreThreadDefinesSTD.h b/OgreMain/include/Threading/OgreThreadDefinesSTD.h deleted file mode 100644 index d29a406ff81..00000000000 --- a/OgreMain/include/Threading/OgreThreadDefinesSTD.h +++ /dev/null @@ -1,72 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ -#ifndef __OgreThreadDefinesSTD_H__ -#define __OgreThreadDefinesSTD_H__ - -// Thread objects and related functions -#define OGRE_THREAD_TYPE std::thread -#define OGRE_THREAD_CREATE(name, worker) std::thread* name = OGRE_NEW_T(std::thread, MEMCATEGORY_GENERAL)(worker) -#define OGRE_THREAD_DESTROY(name) OGRE_DELETE_T(name, thread, MEMCATEGORY_GENERAL) -#define OGRE_THREAD_HARDWARE_CONCURRENCY std::thread::hardware_concurrency() -#define OGRE_THREAD_CURRENT_ID std::this_thread::get_id() -#define OGRE_THREAD_WORKER_INHERIT - -#define OGRE_WQ_MUTEX(name) mutable std::recursive_mutex name -#define OGRE_WQ_LOCK_MUTEX(name) std::unique_lock OGRE_TOKEN_PASTE(ogrenameLock, __LINE__) (name) -#define OGRE_WQ_LOCK_MUTEX_NAMED(mutexName, lockName) std::unique_lock lockName(mutexName) - -// Read-write mutex -#define OGRE_WQ_RW_MUTEX(name) mutable std::recursive_mutex name -#define OGRE_WQ_LOCK_RW_MUTEX_READ(name) std::unique_lock OGRE_TOKEN_PASTE(ogrenameLock, __LINE__) (name) -#define OGRE_WQ_LOCK_RW_MUTEX_WRITE(name) std::unique_lock OGRE_TOKEN_PASTE(ogrenameLock, __LINE__) (name) - -#define OGRE_WQ_THREAD_SYNCHRONISER(sync) std::condition_variable_any sync -#define OGRE_THREAD_WAIT(sync, mutex, lock) sync.wait(lock) -#define OGRE_THREAD_NOTIFY_ONE(sync) sync.notify_one() -#define OGRE_THREAD_NOTIFY_ALL(sync) sync.notify_all() - -#if OGRE_THREAD_SUPPORT != 3 -#define OGRE_LOCK_AUTO_MUTEX std::unique_lock ogreAutoMutexLock(OGRE_AUTO_MUTEX_NAME) -#define OGRE_THREAD_SLEEP(ms) std::this_thread::sleep_for(std::chrono::milliseconds(ms)) - -#define OGRE_AUTO_MUTEX mutable std::recursive_mutex OGRE_AUTO_MUTEX_NAME -#define OGRE_STATIC_MUTEX(name) static std::recursive_mutex name -#define OGRE_STATIC_MUTEX_INSTANCE(name) std::recursive_mutex name -// like OGRE_AUTO_MUTEX but mutex held by pointer -#define OGRE_AUTO_SHARED_MUTEX mutable std::recursive_mutex *OGRE_AUTO_MUTEX_NAME -#define OGRE_LOCK_AUTO_SHARED_MUTEX assert(OGRE_AUTO_MUTEX_NAME); std::recursive_mutex::scoped_lock ogreAutoMutexLock(*OGRE_AUTO_MUTEX_NAME) -#define OGRE_NEW_AUTO_SHARED_MUTEX assert(!OGRE_AUTO_MUTEX_NAME); OGRE_AUTO_MUTEX_NAME = new std::recursive_mutex() -#define OGRE_DELETE_AUTO_SHARED_MUTEX do { assert(OGRE_AUTO_MUTEX_NAME); delete OGRE_AUTO_MUTEX_NAME; } while (0) -#define OGRE_COPY_AUTO_SHARED_MUTEX(from) assert(!OGRE_AUTO_MUTEX_NAME); OGRE_AUTO_MUTEX_NAME = from -#define OGRE_SET_AUTO_SHARED_MUTEX_NULL OGRE_AUTO_MUTEX_NAME = 0 -#define OGRE_MUTEX_CONDITIONAL(mutex) if (mutex) - -// Utility -#define OGRE_THREAD_ID_TYPE std::thread::id -#define OGRE_THREAD_YIELD std::this_thread::yield() -#endif - -#endif diff --git a/OgreMain/include/Threading/OgreThreadHeaders.h b/OgreMain/include/Threading/OgreThreadHeaders.h deleted file mode 100644 index 49110a4495c..00000000000 --- a/OgreMain/include/Threading/OgreThreadHeaders.h +++ /dev/null @@ -1,47 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ -#ifndef __OgreThreadHeaders_H__ -#define __OgreThreadHeaders_H__ - -#if !defined(NOMINMAX) && defined(_MSC_VER) -# define NOMINMAX // required to stop windows.h messing up std::min -#endif - -#if OGRE_THREAD_PROVIDER == 1 - #include "OgreThreadHeadersBoost.h" -#elif OGRE_THREAD_PROVIDER == 2 - #include "OgreThreadHeadersPoco.h" -#elif OGRE_THREAD_PROVIDER == 3 - #include "OgreThreadHeadersTBB.h" -#elif OGRE_THREAD_PROVIDER == 4 - #include "OgreThreadHeadersSTD.h" -#endif - -#include "OgreThreadDefines.h" - -#endif - - diff --git a/OgreMain/include/Threading/OgreThreadHeadersBoost.h b/OgreMain/include/Threading/OgreThreadHeadersBoost.h deleted file mode 100644 index 36fe3a95a6c..00000000000 --- a/OgreMain/include/Threading/OgreThreadHeadersBoost.h +++ /dev/null @@ -1,58 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ -#ifndef __OgreThreadHeadersBoost_H__ -#define __OgreThreadHeadersBoost_H__ - -#if OGRE_COMPILER == OGRE_COMPILER_CLANG || OGRE_COMPILER == OGRE_COMPILER_GNUC -# pragma GCC diagnostic push -#if OGRE_COMPILER == OGRE_COMPILER_GNUC -# pragma GCC diagnostic ignored "-Wpragmas" -#elif OGRE_COMPILER == OGRE_COMPILER_CLANG -# pragma GCC diagnostic ignored "-Wdocumentation" -# pragma GCC diagnostic ignored "-Wconstexpr-not-const" -#endif -# pragma GCC diagnostic ignored "-Wshadow" -# pragma GCC diagnostic ignored "-Wpadded" -# pragma GCC diagnostic ignored "-Wweak-vtables" -# pragma GCC diagnostic ignored "-Wall" -# pragma GCC diagnostic ignored "-Wshorten-64-to-32" -# pragma GCC diagnostic ignored "-Wunused-local-typedefs" -# pragma GCC diagnostic ignored "-Wunused-variable" -# pragma GCC diagnostic ignored "-Wundef" -#endif - -#include -#include -#include -#include -#include -#include - -#if OGRE_COMPILER == OGRE_COMPILER_CLANG || OGRE_COMPILER == OGRE_COMPILER_GNUC -# pragma GCC diagnostic pop -#endif - -#endif diff --git a/OgreMain/include/Threading/OgreThreadHeadersPoco.h b/OgreMain/include/Threading/OgreThreadHeadersPoco.h deleted file mode 100644 index 4abe5c17223..00000000000 --- a/OgreMain/include/Threading/OgreThreadHeadersPoco.h +++ /dev/null @@ -1,42 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ -#ifndef __OgreThreadHeadersPoco_H__ -#define __OgreThreadHeadersPoco_H__ - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 -#define POCO_NO_UNWINDOWS -#endif - -#include -#include -#include -#include -#include -#include -#include - -#endif - diff --git a/OgreMain/include/Threading/OgreThreadHeadersSTD.h b/OgreMain/include/Threading/OgreThreadHeadersSTD.h deleted file mode 100644 index e0628000f8b..00000000000 --- a/OgreMain/include/Threading/OgreThreadHeadersSTD.h +++ /dev/null @@ -1,34 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ -#ifndef __OgreThreadHeadersSTD_H__ -#define __OgreThreadHeadersSTD_H__ - -#include -#include -#include -#include - -#endif diff --git a/OgreMain/src/Android/OgreAPKFileSystemArchive.cpp b/OgreMain/src/Android/OgreAPKFileSystemArchive.cpp deleted file mode 100644 index b17f4b08a78..00000000000 --- a/OgreMain/src/Android/OgreAPKFileSystemArchive.cpp +++ /dev/null @@ -1,239 +0,0 @@ -#include "OgreStableHeaders.h" - -#include - -namespace Ogre{ -namespace { - class APKFileSystemArchive : public Archive - { - private: - AAssetManager* mAssetMgr; - String mPathPreFix; - - public: - APKFileSystemArchive(const String& name, const String& archType, AAssetManager* assetMgr); - ~APKFileSystemArchive(); - - /// @copydoc Archive::isCaseSensitive - bool isCaseSensitive(void) const override; - - /// @copydoc Archive::load - void load() override; - /// @copydoc Archive::unload - void unload() override; - - /// @copydoc Archive::open - DataStreamPtr open(const String& filename, bool readOnly = true) const override; - - /// @copydoc Archive::create - DataStreamPtr create(const String& filename) override; - - /// @copydoc Archive::remove - void remove(const String& filename) override; - - /// @copydoc Archive::list - StringVectorPtr list(bool recursive = true, bool dirs = false) const override; - - /// @copydoc Archive::listFileInfo - FileInfoListPtr listFileInfo(bool recursive = true, bool dirs = false) const override; - - /// @copydoc Archive::find - StringVectorPtr find(const String& pattern, bool recursive = true, bool dirs = false) const override; - - /// @copydoc Archive::findFileInfo - FileInfoListPtr findFileInfo(const String& pattern, bool recursive = true, bool dirs = false) const override; - - /// @copydoc Archive::exists - bool exists(const String& filename) const override; - - /// @copydoc Archive::getModifiedTime - time_t getModifiedTime(const String& filename) const override; - }; - - std::map > mFiles; - - bool IsFolderParsed( const String& Folder ) { - bool parsed = false; - std::map >::iterator iter = mFiles.find( Folder ); - if(iter != mFiles.end()) parsed = true; - return parsed; - } - - void ParseFolder( AAssetManager* AssetMgr, const String& Folder ) { - std::vector mFilenames; - AAssetDir* dir = AAssetManager_openDir(AssetMgr, Folder.c_str()); - const char* fileName = NULL; - while((fileName = AAssetDir_getNextFileName(dir)) != NULL) { - mFilenames.push_back( String( fileName ) ); - } - mFiles.insert( std::make_pair( Folder, mFilenames ) ); - } -} - APKFileSystemArchive::APKFileSystemArchive(const String& name, const String& archType, AAssetManager* assetMgr) - :Archive(name, archType), mAssetMgr(assetMgr) - { - if (mName.size() > 0 && mName[0] == '/') - mName.erase(mName.begin()); - - mPathPreFix = mName; - if (mPathPreFix.size() > 0) - mPathPreFix += "/"; - - if(!IsFolderParsed( mName )) { - ParseFolder( mAssetMgr, mName ); - } - } - - APKFileSystemArchive::~APKFileSystemArchive() - { - std::map >::iterator iter = mFiles.find( mName ); - if (iter != mFiles.end()) { - iter->second.clear(); - mFiles.erase( iter ); - } - unload(); - } - - bool APKFileSystemArchive::isCaseSensitive() const - { - return true; - } - - void APKFileSystemArchive::load() - { - - } - - void APKFileSystemArchive::unload() - { - - } - - DataStreamPtr APKFileSystemArchive::open(const Ogre::String &filename, bool readOnly) const - { - MemoryDataStreamPtr stream; - AAsset* asset = AAssetManager_open(mAssetMgr, (mPathPreFix + filename).c_str(), AASSET_MODE_BUFFER); - if(asset) - { - off_t length = AAsset_getLength(asset); - stream = std::make_shared(filename, length, true, true); - memcpy(stream->getPtr(), AAsset_getBuffer(asset), length); - AAsset_close(asset); - } - return stream; - } - - DataStreamPtr APKFileSystemArchive::create(const Ogre::String &filename) - { - return DataStreamPtr(); - } - - void APKFileSystemArchive::remove(const String &filename) - { - - } - - StringVectorPtr APKFileSystemArchive::list(bool recursive, bool dirs) const - { - StringVectorPtr files(new StringVector); - std::map >::iterator iter = mFiles.find( mName ); - std::vector< String > fileList = iter->second; - for( size_t i = 0; i < fileList.size(); i++ ) - { - files->push_back(fileList[i]); - } - return files; - } - - FileInfoListPtr APKFileSystemArchive::listFileInfo(bool recursive, bool dirs) const - { - FileInfoListPtr files(new FileInfoList); - std::map >::iterator iter = mFiles.find( mName ); - std::vector< String > fileList = iter->second; - for( size_t i = 0; i < fileList.size(); i++ ) - { - AAsset* asset = AAssetManager_open(mAssetMgr, (mPathPreFix + fileList[i]).c_str(), AASSET_MODE_UNKNOWN); - if(asset) - { - FileInfo info; - info.archive = this; - info.filename = fileList[i]; - info.path = mName; - info.basename = fileList[i]; - info.compressedSize = AAsset_getLength(asset); - info.uncompressedSize = info.compressedSize; - files->push_back(info); - AAsset_close(asset); - } - } - return files; - } - - StringVectorPtr APKFileSystemArchive::find(const String& pattern, bool recursive, bool dirs) const - { - StringVectorPtr files(new StringVector); - std::map >::iterator iter = mFiles.find( mName ); - std::vector< String > fileList = iter->second; - for( size_t i = 0; i < fileList.size(); i++ ) - { - if(StringUtil::match(fileList[i], pattern)) - files->push_back(fileList[i]); - } - return files; - } - - FileInfoListPtr APKFileSystemArchive::findFileInfo(const String& pattern, bool recursive, bool dirs) const - { - FileInfoListPtr files(new FileInfoList); - std::map >::iterator iter = mFiles.find( mName ); - std::vector< String > fileList = iter->second; - for( size_t i = 0; i < fileList.size(); i++ ) - { - if(StringUtil::match(fileList[i], pattern)) - { - AAsset* asset = AAssetManager_open(mAssetMgr, (mPathPreFix + fileList[i]).c_str(), AASSET_MODE_UNKNOWN); - if(asset) { - FileInfo info; - info.archive = this; - info.filename = fileList[i]; - info.path = mName; - info.basename = fileList[i]; - info.compressedSize = AAsset_getLength(asset); - info.uncompressedSize = info.compressedSize; - files->push_back(info); - AAsset_close(asset); - } - } - } - return files; - } - - bool APKFileSystemArchive::exists(const String& filename) const - { - AAsset* asset = AAssetManager_open(mAssetMgr, (mPathPreFix + filename).c_str(), AASSET_MODE_UNKNOWN); - if(asset) - { - AAsset_close(asset); - return true; - } - return false; - } - - time_t APKFileSystemArchive::getModifiedTime(const Ogre::String &filename) const - { - return 0; - } - - ////////////////////////////////////////////////////////////////////////////// - - const String &APKFileSystemArchiveFactory::getType() const - { - static String type = "APKFileSystem"; - return type; - } - - Archive *APKFileSystemArchiveFactory::createInstance( const String& name, bool readOnly ) - { - return OGRE_NEW APKFileSystemArchive(name, getType(), mAssetMgr); - } -} diff --git a/OgreMain/src/Android/OgreAPKZipArchive.cpp b/OgreMain/src/Android/OgreAPKZipArchive.cpp deleted file mode 100644 index fe02aa14db6..00000000000 --- a/OgreMain/src/Android/OgreAPKZipArchive.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include "OgreStableHeaders.h" -#include - -namespace Ogre{ - //----------------------------------------------------------------------- - const String &APKZipArchiveFactory::getType() const - { - static String type = "APKZip"; - return type; - } - //----------------------------------------------------------------------- - Archive *APKZipArchiveFactory::createInstance( const String& name, bool readOnly ) - { - String apkName = name; - if (apkName.size() > 0 && apkName[0] == '/') - apkName.erase(apkName.begin()); - - AAsset* asset = AAssetManager_open(mAssetMgr, apkName.c_str(), AASSET_MODE_BUFFER); - if(asset) - { - EmbeddedZipArchiveFactory::addEmbbeddedFile(apkName, (const Ogre::uint8*)AAsset_getBuffer(asset), AAsset_getLength(asset), 0); - mOpenAssets.emplace(apkName, asset); - } - - return EmbeddedZipArchiveFactory::createInstance(apkName, readOnly); - } - void APKZipArchiveFactory::destroyInstance(Archive* ptr) - { - AAsset_close(mOpenAssets[ptr->getName()]); - EmbeddedZipArchiveFactory::destroyInstance(ptr); - } -} diff --git a/OgreMain/src/Android/OgreAndroidLogListener.cpp b/OgreMain/src/Android/OgreAndroidLogListener.cpp deleted file mode 100644 index 2ff947c10cc..00000000000 --- a/OgreMain/src/Android/OgreAndroidLogListener.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "Android/OgreAndroidLogListener.h" -#include - -#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "OGRE", __VA_ARGS__)) -#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "OGRE", __VA_ARGS__)) - -namespace Ogre -{ - void AndroidLogListener::messageLogged(const String& message, LogMessageLevel lml, bool maskDebug, const String &logName, bool& skipThisMessage ) - { - if(lml < Ogre::LML_CRITICAL) - { - LOGI("%s", message.c_str()); - } - else - { - LOGE("%s", message.c_str()); - } - } -} diff --git a/OgreMain/src/Android/OgreAndroidLogListener.h b/OgreMain/src/Android/OgreAndroidLogListener.h deleted file mode 100644 index b4c6f9eadb8..00000000000 --- a/OgreMain/src/Android/OgreAndroidLogListener.h +++ /dev/null @@ -1,44 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __AndroidLogListener_H__ -#define __AndroidLogListener_H__ - -#include "OgreLog.h" - -namespace Ogre -{ - - class AndroidLogListener : public LogListener, public LogAlloc - { - public: - void messageLogged(const String& message, LogMessageLevel lml, bool maskDebug, const String &logName, bool& skipThisMessage ) override; - }; -} - -#endif diff --git a/OgreMain/src/Android/OgreFileSystemLayer.cpp b/OgreMain/src/Android/OgreFileSystemLayer.cpp deleted file mode 100644 index 7b508ac329f..00000000000 --- a/OgreMain/src/Android/OgreFileSystemLayer.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#include "OgreFileSystemLayer.h" - -#include - -namespace Ogre -{ - String FileSystemLayer::resolveBundlePath(String path) - { - return path; - } - - void FileSystemLayer::getConfigPaths() - { - } - //--------------------------------------------------------------------- - void FileSystemLayer::prepareUserHome(const Ogre::String& subdir) - { - } - //--------------------------------------------------------------------- - bool FileSystemLayer::fileExists(const Ogre::String& path) - { - return access(path.c_str(), 00) == 0; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::createDirectory(const Ogre::String& path) - { - return false; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::removeDirectory(const Ogre::String& path) - { - return false; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::removeFile(const Ogre::String& path) - { - return false; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::renameFile(const Ogre::String& oldname, const Ogre::String& newname) - { - return false; - } -} diff --git a/OgreMain/src/GLX/OgreFileSystemLayer.cpp b/OgreMain/src/GLX/OgreFileSystemLayer.cpp deleted file mode 100644 index b17c02f81ed..00000000000 --- a/OgreMain/src/GLX/OgreFileSystemLayer.cpp +++ /dev/null @@ -1,203 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#include "OgreFileSystemLayer.h" -#include -#include -#include -#include -#include -#include - -namespace Ogre -{ - namespace { - /** Get actual file pointed to by symlink */ - const Ogre::String resolveSymlink(const Ogre::String& symlink) - { - ssize_t bufsize = 256; - char* resolved = 0; - do - { - char* buf = OGRE_ALLOC_T(char, bufsize, Ogre::MEMCATEGORY_GENERAL); - ssize_t retval = readlink(symlink.c_str(), buf, bufsize); - if (retval == -1) - { - OGRE_FREE(buf, Ogre::MEMCATEGORY_GENERAL); - break; - } - - if (retval < bufsize) - { - // operation was successful. - // readlink does not guarantee to 0-terminate, so do this manually - buf[retval] = '\0'; - resolved = buf; - } - else - { - // buffer was too small, grow buffer and try again - OGRE_FREE(buf, Ogre::MEMCATEGORY_GENERAL); - bufsize <<= 1; - } - } while (!resolved); - - if (resolved) - { - Ogre::String result (resolved); - OGRE_FREE(resolved, Ogre::MEMCATEGORY_GENERAL); - return result; - } - else - return ""; - } - } - - String FileSystemLayer::resolveBundlePath(String path) - { - // With Ubuntu snaps absolute paths are relative to the snap package. - char* env_SNAP = getenv("SNAP"); - if (env_SNAP && !path.empty() && path[0] == '/' && // only adjust absolute dirs - !StringUtil::startsWith(path, "/snap")) // not a snap path already - path = env_SNAP + path; - - return path; - } - //--------------------------------------------------------------------- - void FileSystemLayer::getConfigPaths() - { - // try to determine the application's path: - // recent systems should provide the executable path via the /proc system - Ogre::String appPath = resolveSymlink("/proc/self/exe"); - if (appPath.empty()) - { - // if /proc/self/exe isn't available, try it via the program's pid - pid_t pid = getpid(); - char proc[64]; - int retval = snprintf(proc, sizeof(proc), "/proc/%llu/exe", (unsigned long long) pid); - if (retval > 0 && retval < (long)sizeof(proc)) - appPath = resolveSymlink(proc); - } - - if (!appPath.empty()) - { - // we need to strip the executable name from the path - Ogre::String::size_type pos = appPath.rfind('/'); - if (pos != Ogre::String::npos) - appPath.erase(pos); - - // use application path as first config search path - mConfigPaths.push_back(appPath + '/'); - } - - Dl_info info; - if (dladdr((const void*)resolveSymlink, &info)) - { - String base(info.dli_fname); - // need to strip the module filename from the path - String::size_type pos = base.rfind('/'); - if (pos != String::npos) - base.erase(pos); - - String dirname = StringUtil::format("OGRE-%d.%d/", OGRE_VERSION_MAJOR, OGRE_VERSION_MINOR); - // search inside ../share/OGRE-X.Y - mConfigPaths.push_back(StringUtil::normalizeFilePath(base + "/../share/"+dirname, false)); - // then look relative to PIP structure - mConfigPaths.push_back(StringUtil::normalizeFilePath(base+"/../../../../share/"+dirname)); - } - - // then try system wide /etc - mConfigPaths.push_back("/etc/OGRE/"); - } - //--------------------------------------------------------------------- - void FileSystemLayer::prepareUserHome(const Ogre::String& subdir) - { - char* xdg_cache = getenv("XDG_CACHE_HOME"); - - if(xdg_cache) { - mHomePath = xdg_cache; - mHomePath.append("/"); - } else { - struct passwd* pwd = getpwuid(getuid()); - if (pwd) - { - mHomePath = pwd->pw_dir; - } - else - { - // try the $HOME environment variable - mHomePath = getenv("HOME"); - } - - if(!mHomePath.empty()) { - mHomePath.append("/.cache/"); - } - } - - if (!mHomePath.empty()) - { - // create the given subdir - mHomePath.append(subdir + '/'); - if (mkdir(mHomePath.c_str(), 0755) != 0 && errno != EEXIST) - { - // can't create dir - mHomePath.clear(); - } - } - - if (mHomePath.empty()) - { - // couldn't create dir in home directory, fall back to cwd - mHomePath = "./"; - } - } - //--------------------------------------------------------------------- - bool FileSystemLayer::fileExists(const Ogre::String& path) - { - return access(path.c_str(), R_OK) == 0; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::createDirectory(const Ogre::String& path) - { - return !mkdir(path.c_str(), 0755) || errno == EEXIST; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::removeDirectory(const Ogre::String& path) - { - return !rmdir(path.c_str()) || errno == ENOENT; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::removeFile(const Ogre::String& path) - { - return !unlink(path.c_str()) || errno == ENOENT; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::renameFile(const Ogre::String& oldname, const Ogre::String& newname) - { - return !rename(oldname.c_str(), newname.c_str()); - } -} diff --git a/OgreMain/src/OSX/OgreFileSystemLayer.cpp b/OgreMain/src/OSX/OgreFileSystemLayer.cpp deleted file mode 100644 index 16bc152bd85..00000000000 --- a/OgreMain/src/OSX/OgreFileSystemLayer.cpp +++ /dev/null @@ -1,121 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#include "OgreFileSystemLayer.h" -#include "macUtils.h" -#include -#include -#include -#include -#include - -namespace Ogre -{ - String FileSystemLayer::resolveBundlePath(String path) - { - if(!path.empty() && path[0] != '/') // only adjust relative dirs - path = macBundlePath() + "/" + path; - - return path; - } - - void FileSystemLayer::getConfigPaths() - { - mConfigPaths.push_back(Ogre::macBundlePath() + "/Contents/Resources/"); - mConfigPaths.push_back(Ogre::macBundlePath() + "/"); - - Dl_info info; - if (dladdr((const void*)macBundlePath, &info)) - { - String base(info.dli_fname); - // need to strip the module filename from the path - String::size_type pos = base.rfind('/'); - if (pos != String::npos) - base.erase(pos); - - // look relative to the dylib according to PIP structure - mConfigPaths.push_back(StringUtil::normalizeFilePath(base+"/../../../../bin/")); - } - } - //--------------------------------------------------------------------- - void FileSystemLayer::prepareUserHome(const Ogre::String& subdir) - { - struct passwd* pwd = getpwuid(getuid()); - if (pwd) - { - mHomePath = pwd->pw_dir; - } - else - { - // try the $HOME environment variable - mHomePath = getenv("HOME"); - } - - if (!mHomePath.empty()) - { - mHomePath.append("/Library/Application Support/"); - // now create the given subdir - mHomePath.append(subdir + '/'); - if (mkdir(mHomePath.c_str(), 0755) != 0 && errno != EEXIST) - { - // can't create dir - mHomePath.clear(); - } - } - - if (mHomePath.empty()) - { - // couldn't create dir in home directory, fall back to cwd - mHomePath = "./"; - } - } - //--------------------------------------------------------------------- - bool FileSystemLayer::fileExists(const Ogre::String& path) - { - return access(path.c_str(), R_OK) == 0; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::createDirectory(const Ogre::String& path) - { - return !mkdir(path.c_str(), 0755) || errno == EEXIST; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::removeDirectory(const Ogre::String& path) - { - return !rmdir(path.c_str()) || errno == ENOENT; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::removeFile(const Ogre::String& path) - { - return !unlink(path.c_str()) || errno == ENOENT; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::renameFile(const Ogre::String& oldname, const Ogre::String& newname) - { - return !rename(oldname.c_str(), newname.c_str()); - } -} diff --git a/OgreMain/src/OSX/macUtils.h b/OgreMain/src/OSX/macUtils.h deleted file mode 100644 index b4c6790e2e8..00000000000 --- a/OgreMain/src/OSX/macUtils.h +++ /dev/null @@ -1,41 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include -#include "../OgrePrerequisites.h" - -namespace Ogre { - - CFBundleRef mac_loadExeBundle(const char *path); - void * mac_getBundleSym(CFBundleRef bundle, const char *name); - bool mac_unloadExeBundle(CFBundleRef bundle); - void* mac_loadDylib(const char* name); - void* mac_loadFramework(String name); - String macBundlePath(); - String macCachePath(); - String macTempFileName(void); -} diff --git a/OgreMain/src/OSX/macUtils.mm b/OgreMain/src/OSX/macUtils.mm deleted file mode 100644 index 4607ee20c1b..00000000000 --- a/OgreMain/src/OSX/macUtils.mm +++ /dev/null @@ -1,158 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#import "macUtils.h" - -#import "OgreString.h" -#import -#import - -namespace Ogre { - - CFBundleRef mac_loadExeBundle(const char *name) { - CFBundleRef baseBundle = CFBundleGetBundleWithIdentifier(CFSTR("org.ogre3d.Ogre")); - CFBundleRef mainBundle = CFBundleGetMainBundle(); - CFStringRef nameRef = CFStringCreateWithCString(NULL, name, kCFStringEncodingASCII); - CFURLRef bundleURL = 0; //URL of bundle to load - CFBundleRef bundle = 0; //bundle to load - - //cut off .bundle if present - if(CFStringHasSuffix(nameRef, CFSTR(".bundle"))) { - CFStringRef nameTempRef = nameRef; - long end = CFStringGetLength(nameTempRef) - CFStringGetLength(CFSTR(".bundle")); - nameRef = CFStringCreateWithSubstring(NULL, nameTempRef, CFRangeMake(0, end)); - CFRelease(nameTempRef); - } - - //assume relative to Resources/ directory of Main bundle - bundleURL = CFBundleCopyResourceURL(mainBundle, nameRef, CFSTR("bundle"), NULL); - if(bundleURL) { - bundle = CFBundleCreate(NULL, bundleURL); - CFRelease(bundleURL); - } - - //otherwise, try Resources/ directory of Ogre Framework bundle - if(!bundle) { - bundleURL = CFBundleCopyResourceURL(baseBundle, nameRef, CFSTR("bundle"), NULL); - if(bundleURL) { - bundle = CFBundleCreate(NULL, bundleURL); - CFRelease(bundleURL); - } - } - CFRelease(nameRef); - - if(bundle) { - if(CFBundleLoadExecutable(bundle)) { - return bundle; - } - else { - CFRelease(bundle); - } - } - - return 0; - } - - void *mac_getBundleSym(CFBundleRef bundle, const char *name) { - CFStringRef nameRef = CFStringCreateWithCString(NULL, name, kCFStringEncodingASCII); - void *sym = CFBundleGetFunctionPointerForName(bundle, nameRef); - CFRelease(nameRef); - return sym; - } - - //returns 1 on error, 0 otherwise - bool mac_unloadExeBundle(CFBundleRef bundle) { - if(bundle) { - //no-op, can't unload Obj-C bundles without crashing - return 0; - } - return 1; - } - - void* mac_loadFramework(String name) - { - size_t lastSlashPos = name.find_last_of('/'); - size_t extensionPos = name.rfind(".framework"); - - if (lastSlashPos != String::npos && extensionPos != String::npos && extensionPos > lastSlashPos) - { - // path, like "/Library/Frameworks/OgreTerrain.framework", append /OgreTerrain - String realName = name.substr(lastSlashPos + 1, extensionPos - lastSlashPos - 1); - - name += "/" + realName; - } - - return dlopen(name.c_str(), RTLD_LAZY | RTLD_GLOBAL); - } - - void* mac_loadDylib(const char* name) - { - return dlopen(name, RTLD_LAZY | RTLD_GLOBAL); - } - - String macBundlePath() - { - char path[1024]; - CFBundleRef mainBundle = CFBundleGetMainBundle(); - assert(mainBundle); - - CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle); - assert(mainBundleURL); - - CFStringRef cfStringRef = CFURLCopyFileSystemPath( mainBundleURL, kCFURLPOSIXPathStyle); - assert(cfStringRef); - - CFStringGetFileSystemRepresentation(cfStringRef, path, 1024); - - CFRelease(mainBundleURL); - CFRelease(cfStringRef); - - return String(path); - } - - String macCachePath() - { - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); - NSString *cachesDirectory = [paths objectAtIndex:0]; - - return [cachesDirectory cStringUsingEncoding:NSASCIIStringEncoding]; - } - - String macTempFileName() - { - NSString *tempFilePath; - NSFileManager *fileManager = [NSFileManager defaultManager]; - for (;;) { - NSString *baseName = [NSString stringWithFormat:@"tmp-%x", arc4random()]; - tempFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:baseName]; - if (![fileManager fileExistsAtPath:tempFilePath]) - break; - } - return String([tempFilePath cStringUsingEncoding:NSASCIIStringEncoding]); - } -} diff --git a/OgreMain/src/OgreASTCCodec.cpp b/OgreMain/src/OgreASTCCodec.cpp deleted file mode 100644 index b85903c5775..00000000000 --- a/OgreMain/src/OgreASTCCodec.cpp +++ /dev/null @@ -1,291 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" -#include "OgreASTCCodec.h" - -#include -#include "OgreImage.h" - -namespace Ogre { - - const uint32 ASTC_MAGIC = 0x5CA1AB13; - - typedef struct - { - uint8 magic[4]; - uint8 blockdim_x; - uint8 blockdim_y; - uint8 blockdim_z; - uint8 xsize[3]; // x-size = xsize[0] + xsize[1] + xsize[2] - uint8 ysize[3]; // x-size, y-size and z-size are given in texels; - uint8 zsize[3]; // block count is inferred - } ASTCHeader; - - float ASTCCodec::getBitrateForPixelFormat(PixelFormat fmt) - { - switch (fmt) - { - case PF_ASTC_RGBA_4X4_LDR: - return 8.00; - case PF_ASTC_RGBA_5X4_LDR: - return 6.40; - case PF_ASTC_RGBA_5X5_LDR: - return 5.12; - case PF_ASTC_RGBA_6X5_LDR: - return 4.27; - case PF_ASTC_RGBA_6X6_LDR: - return 3.56; - case PF_ASTC_RGBA_8X5_LDR: - return 3.20; - case PF_ASTC_RGBA_8X6_LDR: - return 2.67; - case PF_ASTC_RGBA_8X8_LDR: - return 2.00; - case PF_ASTC_RGBA_10X5_LDR: - return 2.56; - case PF_ASTC_RGBA_10X6_LDR: - return 2.13; - case PF_ASTC_RGBA_10X8_LDR: - return 1.60; - case PF_ASTC_RGBA_10X10_LDR: - return 1.28; - case PF_ASTC_RGBA_12X10_LDR: - return 1.07; - case PF_ASTC_RGBA_12X12_LDR: - return 0.89; - - default: - return 0; - } - } - - // Utility function to determine 2D block dimensions from a target bitrate. Used for 3D textures. - // Taken from astc_toplevel.cpp in ARM's ASTC Evaluation Codec - void ASTCCodec::getClosestBlockDim2d(float targetBitrate, int *x, int *y) const - { - int blockdims[6] = { 4, 5, 6, 8, 10, 12 }; - - float best_error = 1000; - float aspect_of_best = 1; - int i, j; - - // Y dimension - for (i = 0; i < 6; i++) - { - // X dimension - for (j = i; j < 6; j++) - { - // NxN MxN 8x5 10x5 10x6 - int is_legal = (j==i) || (j==i+1) || (j==3 && i==1) || (j==4 && i==1) || (j==4 && i==2); - - if(is_legal) - { - float bitrate = 128.0f / (blockdims[i] * blockdims[j]); - float bitrate_error = std::fabs(bitrate - targetBitrate); - float aspect = (float)blockdims[j] / blockdims[i]; - if (bitrate_error < best_error || (bitrate_error == best_error && aspect < aspect_of_best)) - { - *x = blockdims[j]; - *y = blockdims[i]; - best_error = bitrate_error; - aspect_of_best = aspect; - } - } - } - } - } - - // Taken from astc_toplevel.cpp in ARM's ASTC Evaluation Codec - void ASTCCodec::getClosestBlockDim3d(float targetBitrate, int *x, int *y, int *z) - { - int blockdims[4] = { 3, 4, 5, 6 }; - - float best_error = 1000; - float aspect_of_best = 1; - int i, j, k; - - for (i = 0; i < 4; i++) // Z - { - for (j = i; j < 4; j++) // Y - { - for (k = j; k < 4; k++) // X - { - // NxNxN MxNxN MxMxN - int is_legal = ((k==j)&&(j==i)) || ((k==j+1)&&(j==i)) || ((k==j)&&(j==i+1)); - - if(is_legal) - { - float bitrate = 128.0f / (blockdims[i] * blockdims[j] * blockdims[k]); - float bitrate_error = std::fabs(bitrate - targetBitrate); - float aspect = (float)blockdims[k] / blockdims[j] + (float)blockdims[j] / blockdims[i] + (float)blockdims[k] / blockdims[i]; - - if (bitrate_error < best_error || (bitrate_error == best_error && aspect < aspect_of_best)) - { - *x = blockdims[k]; - *y = blockdims[j]; - *z = blockdims[i]; - best_error = bitrate_error; - aspect_of_best = aspect; - } - } - } - } - } - } - //--------------------------------------------------------------------- - ASTCCodec* ASTCCodec::msInstance = 0; - //--------------------------------------------------------------------- - void ASTCCodec::startup(void) - { - if (!msInstance) - { - msInstance = OGRE_NEW ASTCCodec(); - Codec::registerCodec(msInstance); - } - - LogManager::getSingleton().logMessage(LML_NORMAL, - "ASTC codec registering"); - } - //--------------------------------------------------------------------- - void ASTCCodec::shutdown(void) - { - if(msInstance) - { - Codec::unregisterCodec(msInstance); - OGRE_DELETE msInstance; - msInstance = 0; - } - } - //--------------------------------------------------------------------- - ASTCCodec::ASTCCodec(): - mType("astc") - { - } - //--------------------------------------------------------------------- - void ASTCCodec::decode(const DataStreamPtr& stream, const Any& output) const - { - Image* image = any_cast(output); - ASTCHeader header; - - // Read the ASTC header - stream->read(&header, sizeof(ASTCHeader)); - - if (memcmp(&ASTC_MAGIC, &header.magic, sizeof(uint32)) != 0 ) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "This is not a valid ASTC file!", "ASTCCodec::decode"); - - int xdim = header.blockdim_x; - int ydim = header.blockdim_y; - int zdim = header.blockdim_z; - - int xsize = header.xsize[0] + 256 * header.xsize[1] + 65536 * header.xsize[2]; - int ysize = header.ysize[0] + 256 * header.ysize[1] + 65536 * header.ysize[2]; - int zsize = header.zsize[0] + 256 * header.zsize[1] + 65536 * header.zsize[2]; - - PixelFormat format = PF_UNKNOWN; - - // For 3D we calculate the bitrate then find the nearest 2D block size. - if(zdim > 1) - { - float bitrate = 128.0f / (xdim * ydim * zdim); - getClosestBlockDim2d(bitrate, &xdim, &ydim); - } - - if(xdim == 4) - { - format = PF_ASTC_RGBA_4X4_LDR; - } - else if(xdim == 5) - { - if(ydim == 4) - format = PF_ASTC_RGBA_5X4_LDR; - else if(ydim == 5) - format = PF_ASTC_RGBA_5X5_LDR; - } - else if(xdim == 6) - { - if(ydim == 5) - format = PF_ASTC_RGBA_6X5_LDR; - else if(ydim == 6) - format = PF_ASTC_RGBA_6X6_LDR; - } - else if(xdim == 8) - { - if(ydim == 5) - format = PF_ASTC_RGBA_8X5_LDR; - else if(ydim == 6) - format = PF_ASTC_RGBA_8X6_LDR; - else if(ydim == 8) - format = PF_ASTC_RGBA_8X8_LDR; - } - else if(xdim == 10) - { - if(ydim == 5) - format = PF_ASTC_RGBA_10X5_LDR; - else if(ydim == 6) - format = PF_ASTC_RGBA_10X6_LDR; - else if(ydim == 8) - format = PF_ASTC_RGBA_10X8_LDR; - else if(ydim == 10) - format = PF_ASTC_RGBA_10X10_LDR; - } - else if(xdim == 12) - { - if(ydim == 10) - format = PF_ASTC_RGBA_12X10_LDR; - else if(ydim == 12) - format = PF_ASTC_RGBA_12X12_LDR; - } - - // Always one face, cubemaps are not currently supported - // Always 1 mip level per file - image->create(format, xsize, ysize, zsize, 1, 0); - stream->read(image->getData(), image->getSize()); - } - //--------------------------------------------------------------------- - String ASTCCodec::getType() const - { - return mType; - } - //--------------------------------------------------------------------- - String ASTCCodec::magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const - { - if (maxbytes >= sizeof(uint32)) - { - uint32 fileType; - memcpy(&fileType, magicNumberPtr, sizeof(uint32)); - flipEndian(&fileType, sizeof(uint32), 1); - - if (ASTC_MAGIC == fileType) - return String("astc"); - } - - return BLANKSTRING; - } -} diff --git a/OgreMain/src/OgreASTCCodec.h b/OgreMain/src/OgreASTCCodec.h deleted file mode 100644 index e3f36f97287..00000000000 --- a/OgreMain/src/OgreASTCCodec.h +++ /dev/null @@ -1,79 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2013 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OgreASTCCodec_H__ -#define __OgreASTCCodec_H__ - -#include "OgreImageCodec.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Image - * @{ - */ - - /** Codec specialized in loading ASTC (ARM Adaptive Scalable Texture Compression) images. - - We implement our own codec here since we need to be able to keep ASTC - data compressed if the card supports it. - */ - class ASTCCodec : public ImageCodec - { - private: - String mType; - - /// Single registered codec instance - static ASTCCodec* msInstance; - - public: - ASTCCodec(); - virtual ~ASTCCodec() { } - - void decode(const DataStreamPtr& input, const Any& output) const override; - String magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const override; - String getType() const override; - - /// Static method to startup and register the ASTC codec - static void startup(void); - /// Static method to shutdown and unregister the ASTC codec - static void shutdown(void); - - private: - void getClosestBlockDim2d(float targetBitrate, int *x, int *y) const; - static void getClosestBlockDim3d(float targetBitrate, int *x, int *y, int *z); - static float getBitrateForPixelFormat(PixelFormat fmt); - - }; - /** @} */ - /** @} */ - -} // namespace - -#endif - diff --git a/OgreMain/src/OgreAlignedAllocator.cpp b/OgreMain/src/OgreAlignedAllocator.cpp deleted file mode 100644 index b798673623a..00000000000 --- a/OgreMain/src/OgreAlignedAllocator.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgrePlatformInformation.h" - -/** -* -* |___2___|3|_________5__________|__6__| -* ^ ^ -* 1 4 -* -* 1 -> Pointer to start of the block allocated by new. -* 2 -> Gap used to get 4 aligned on given alignment -* 3 -> Byte offset between 1 and 4 -* 4 -> Pointer to the start of data block. -* 5 -> Data block. -* 6 -> Wasted memory at rear of data block. -*/ - -namespace Ogre { - - /** Allocate memory with given alignment. - @param - size The size of memory need to allocate. - @param - alignment The alignment of result pointer, must be power of two - and in range [1, 128]. - @return - The allocated memory pointer. - @par - On failure, exception will be throw. - */ - void* AlignedMemory::allocate(size_t size, size_t alignment) - { - assert(0 < alignment && alignment <= 128 && Bitwise::isPO2(alignment)); - - unsigned char* p = new unsigned char[size + alignment]; - size_t offset = alignment - (size_t(p) & (alignment-1)); - - unsigned char* result = p + offset; - result[-1] = (unsigned char)offset; - - return result; - } - //--------------------------------------------------------------------- - void* AlignedMemory::allocate(size_t size) - { - return allocate(size, OGRE_SIMD_ALIGNMENT); - } - //--------------------------------------------------------------------- - void AlignedMemory::deallocate(void* p) - { - if (p) - { - unsigned char* mem = (unsigned char*)p; - mem = mem - mem[-1]; - delete [] mem; - } - } - -} diff --git a/OgreMain/src/OgreAnimable.cpp b/OgreMain/src/OgreAnimable.cpp deleted file mode 100644 index fac31b520fd..00000000000 --- a/OgreMain/src/OgreAnimable.cpp +++ /dev/null @@ -1,159 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreAnimable.h" - -namespace Ogre { - void AnimableValue::resetToBaseValue(void) - { - switch(mType) - { - case INT: - setValue(mBaseValueInt); - break; - case REAL: - setValue(mBaseValueReal[0]); - break; - case VECTOR2: - setValue(Vector2(mBaseValueReal)); - break; - case VECTOR3: - setValue(Vector3(mBaseValueReal)); - break; - case VECTOR4: - setValue(Vector4(mBaseValueReal)); - break; - case QUATERNION: - setValue(Quaternion(mBaseValueReal)); - break; - case COLOUR: - setValue(ColourValue(mBaseValueReal[0], mBaseValueReal[1], - mBaseValueReal[2], mBaseValueReal[3])); - break; - case RADIAN: - setValue(Radian(mBaseValueReal[0])); - break; - } - } - //-------------------------------------------------------------------------- - void AnimableValue::setAsBaseValue(const Any& val) - { - switch(mType) - { - case INT: - setAsBaseValue(any_cast(val)); - break; - case REAL: - setAsBaseValue(any_cast(val)); - break; - case VECTOR2: - setAsBaseValue(any_cast(val)); - break; - case VECTOR3: - setAsBaseValue(any_cast(val)); - break; - case VECTOR4: - setAsBaseValue(any_cast(val)); - break; - case QUATERNION: - setAsBaseValue(any_cast(val)); - break; - case COLOUR: - setAsBaseValue(any_cast(val)); - break; - case RADIAN: - setAsBaseValue(any_cast(val)); - break; - } - } - //-------------------------------------------------------------------------- - void AnimableValue::setValue(const Any& val) - { - switch(mType) - { - case INT: - setValue(any_cast(val)); - break; - case REAL: - setValue(any_cast(val)); - break; - case VECTOR2: - setValue(any_cast(val)); - break; - case VECTOR3: - setValue(any_cast(val)); - break; - case VECTOR4: - setValue(any_cast(val)); - break; - case QUATERNION: - setValue(any_cast(val)); - break; - case COLOUR: - setValue(any_cast(val)); - break; - case RADIAN: - setValue(any_cast(val)); - break; - } - } - //-------------------------------------------------------------------------- - void AnimableValue::applyDeltaValue(const Any& val) - { - switch(mType) - { - case INT: - applyDeltaValue(any_cast(val)); - break; - case REAL: - applyDeltaValue(any_cast(val)); - break; - case VECTOR2: - applyDeltaValue(any_cast(val)); - break; - case VECTOR3: - applyDeltaValue(any_cast(val)); - break; - case VECTOR4: - applyDeltaValue(any_cast(val)); - break; - case QUATERNION: - applyDeltaValue(any_cast(val)); - break; - case COLOUR: - applyDeltaValue(any_cast(val)); - break; - case RADIAN: - applyDeltaValue(any_cast(val)); - break; - } - } - - - -} diff --git a/OgreMain/src/OgreAnimation.cpp b/OgreMain/src/OgreAnimation.cpp deleted file mode 100644 index 54792861ad5..00000000000 --- a/OgreMain/src/OgreAnimation.cpp +++ /dev/null @@ -1,745 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreAnimation.h" -#include "OgreKeyFrame.h" -#include "OgreEntity.h" -#include "OgreSubEntity.h" - -namespace Ogre { - - Animation::InterpolationMode Animation::msDefaultInterpolationMode = Animation::IM_LINEAR; - Animation::RotationInterpolationMode - Animation::msDefaultRotationInterpolationMode = Animation::RIM_LINEAR; - //--------------------------------------------------------------------- - Animation::Animation(const String& name, Real length) - : mName(name) - , mLength(length) - , mInterpolationMode(msDefaultInterpolationMode) - , mRotationInterpolationMode(msDefaultRotationInterpolationMode) - , mKeyFrameTimesDirty(false) - , mUseBaseKeyFrame(false) - , mBaseKeyFrameTime(0.0f) - , mBaseKeyFrameAnimationName(BLANKSTRING) - , mContainer(0) - { - } - //--------------------------------------------------------------------- - Animation::~Animation() - { - destroyAllTracks(); - } - //--------------------------------------------------------------------- - Real Animation::getLength(void) const - { - return mLength; - } - //--------------------------------------------------------------------- - void Animation::setLength(Real len) - { - mLength = len; - } - //--------------------------------------------------------------------- - NodeAnimationTrack* Animation::createNodeTrack(unsigned short handle) - { - if (hasNodeTrack(handle)) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "Node track with the specified handle " + - StringConverter::toString(handle) + " already exists", - "Animation::createNodeTrack"); - } - - NodeAnimationTrack* ret = OGRE_NEW NodeAnimationTrack(this, handle); - - mNodeTrackList[handle] = ret; - return ret; - } - //--------------------------------------------------------------------- - NodeAnimationTrack* Animation::createNodeTrack(unsigned short handle, Node* node) - { - NodeAnimationTrack* ret = createNodeTrack(handle); - - ret->setAssociatedNode(node); - - return ret; - } - //--------------------------------------------------------------------- - unsigned short Animation::getNumNodeTracks(void) const - { - return (unsigned short)mNodeTrackList.size(); - } - //--------------------------------------------------------------------- - bool Animation::hasNodeTrack(unsigned short handle) const - { - return (mNodeTrackList.find(handle) != mNodeTrackList.end()); - } - //--------------------------------------------------------------------- - NodeAnimationTrack* Animation::getNodeTrack(unsigned short handle) const - { - NodeTrackList::const_iterator i = mNodeTrackList.find(handle); - - if (i == mNodeTrackList.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Cannot find node track with the specified handle " + - StringConverter::toString(handle), - "Animation::getNodeTrack"); - } - - return i->second; - - } - //--------------------------------------------------------------------- - void Animation::destroyNodeTrack(unsigned short handle) - { - NodeTrackList::iterator i = mNodeTrackList.find(handle); - - if (i != mNodeTrackList.end()) - { - OGRE_DELETE i->second; - mNodeTrackList.erase(i); - _keyFrameListChanged(); - } - } - //--------------------------------------------------------------------- - void Animation::destroyAllNodeTracks(void) - { - for (auto& t : mNodeTrackList) - { - OGRE_DELETE t.second; - } - mNodeTrackList.clear(); - _keyFrameListChanged(); - } - //--------------------------------------------------------------------- - NumericAnimationTrack* Animation::createNumericTrack(unsigned short handle, const AnimableValuePtr& anim) - { - if (hasNumericTrack(handle)) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "Numeric track with the specified handle " + - StringConverter::toString(handle) + " already exists", - "Animation::createNumericTrack"); - } - - NumericAnimationTrack* ret = OGRE_NEW NumericAnimationTrack(this, handle, anim); - - mNumericTrackList[handle] = ret; - return ret; - } - //--------------------------------------------------------------------- - unsigned short Animation::getNumNumericTracks(void) const - { - return (unsigned short)mNumericTrackList.size(); - } - //--------------------------------------------------------------------- - bool Animation::hasNumericTrack(unsigned short handle) const - { - return (mNumericTrackList.find(handle) != mNumericTrackList.end()); - } - //--------------------------------------------------------------------- - NumericAnimationTrack* Animation::getNumericTrack(unsigned short handle) const - { - NumericTrackList::const_iterator i = mNumericTrackList.find(handle); - - if (i == mNumericTrackList.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Cannot find numeric track with the specified handle " + - StringConverter::toString(handle), - "Animation::getNumericTrack"); - } - - return i->second; - - } - //--------------------------------------------------------------------- - void Animation::destroyNumericTrack(unsigned short handle) - { - NumericTrackList::iterator i = mNumericTrackList.find(handle); - - if (i != mNumericTrackList.end()) - { - OGRE_DELETE i->second; - mNumericTrackList.erase(i); - _keyFrameListChanged(); - } - } - //--------------------------------------------------------------------- - void Animation::destroyAllNumericTracks(void) - { - for (auto& t : mNumericTrackList) - { - OGRE_DELETE t.second; - } - mNumericTrackList.clear(); - _keyFrameListChanged(); - } - //--------------------------------------------------------------------- - VertexAnimationTrack* Animation::createVertexTrack(unsigned short handle, - VertexAnimationType animType) - { - if (hasVertexTrack(handle)) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "Vertex track with the specified handle " + - StringConverter::toString(handle) + " already exists", - "Animation::createVertexTrack"); - } - - VertexAnimationTrack* ret = OGRE_NEW VertexAnimationTrack(this, handle, animType); - - mVertexTrackList[handle] = ret; - return ret; - - } - //--------------------------------------------------------------------- - VertexAnimationTrack* Animation::createVertexTrack(unsigned short handle, - VertexData* data, VertexAnimationType animType) - { - VertexAnimationTrack* ret = createVertexTrack(handle, animType); - - ret->setAssociatedVertexData(data); - - return ret; - } - //--------------------------------------------------------------------- - unsigned short Animation::getNumVertexTracks(void) const - { - return (unsigned short)mVertexTrackList.size(); - } - //--------------------------------------------------------------------- - bool Animation::hasVertexTrack(unsigned short handle) const - { - return (mVertexTrackList.find(handle) != mVertexTrackList.end()); - } - //--------------------------------------------------------------------- - VertexAnimationTrack* Animation::getVertexTrack(unsigned short handle) const - { - VertexTrackList::const_iterator i = mVertexTrackList.find(handle); - - if (i == mVertexTrackList.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Cannot find vertex track with the specified handle " + - StringConverter::toString(handle), - "Animation::getVertexTrack"); - } - - return i->second; - - } - //--------------------------------------------------------------------- - void Animation::destroyVertexTrack(unsigned short handle) - { - VertexTrackList::iterator i = mVertexTrackList.find(handle); - - if (i != mVertexTrackList.end()) - { - OGRE_DELETE i->second; - mVertexTrackList.erase(i); - _keyFrameListChanged(); - } - } - //--------------------------------------------------------------------- - void Animation::destroyAllVertexTracks(void) - { - VertexTrackList::iterator i; - for (i = mVertexTrackList.begin(); i != mVertexTrackList.end(); ++i) - { - OGRE_DELETE i->second; - } - mVertexTrackList.clear(); - _keyFrameListChanged(); - } - //--------------------------------------------------------------------- - void Animation::destroyAllTracks(void) - { - destroyAllNodeTracks(); - destroyAllNumericTracks(); - destroyAllVertexTracks(); - } - //--------------------------------------------------------------------- - const String& Animation::getName(void) const - { - return mName; - } - //--------------------------------------------------------------------- - void Animation::apply(Real timePos, Real weight, Real scale) - { - _applyBaseKeyFrame(); - - // Calculate time index for fast keyframe search - TimeIndex timeIndex = _getTimeIndex(timePos); - - for (auto& i : mNodeTrackList) - { - i.second->apply(timeIndex, weight, scale); - } - for (auto& j : mNumericTrackList) - { - j.second->apply(timeIndex, weight, scale); - } - for (auto& k : mVertexTrackList) - { - k.second->apply(timeIndex, weight, scale); - } - } - //--------------------------------------------------------------------- - void Animation::applyToNode(Node* node, Real timePos, Real weight, Real scale) - { - _applyBaseKeyFrame(); - - // Calculate time index for fast keyframe search - TimeIndex timeIndex = _getTimeIndex(timePos); - - for (auto& t : mNodeTrackList) - { - t.second->applyToNode(node, timeIndex, weight, scale); - } - } - //--------------------------------------------------------------------- - void Animation::apply(Skeleton* skel, Real timePos, Real weight, - Real scale) - { - _applyBaseKeyFrame(); - - // Calculate time index for fast keyframe search - TimeIndex timeIndex = _getTimeIndex(timePos); - - for (auto& t : mNodeTrackList) - { - // get bone to apply to - Bone* b = skel->getBone(t.first); - t.second->applyToNode(b, timeIndex, weight, scale); - } - - - } - //--------------------------------------------------------------------- - void Animation::apply(Skeleton* skel, Real timePos, float weight, - const AnimationState::BoneBlendMask* blendMask, Real scale) - { - _applyBaseKeyFrame(); - - // Calculate time index for fast keyframe search - TimeIndex timeIndex = _getTimeIndex(timePos); - - for (auto& t : mNodeTrackList) - { - Bone* b = skel->getBone(t.first); - t.second->applyToNode(b, timeIndex, (*blendMask)[b->getHandle()] * weight, scale); - } - } - //--------------------------------------------------------------------- - void Animation::apply(Entity* entity, Real timePos, Real weight, - bool software, bool hardware) - { - _applyBaseKeyFrame(); - - // Calculate time index for fast keyframe search - TimeIndex timeIndex = _getTimeIndex(timePos); - - VertexTrackList::iterator i; - for (auto& t : mVertexTrackList) - { - unsigned short handle = t.first; - VertexAnimationTrack* track = t.second; - - VertexData* swVertexData; - VertexData* hwVertexData; - if (handle == 0) - { - // shared vertex data - swVertexData = entity->_getSoftwareVertexAnimVertexData(); - hwVertexData = entity->_getHardwareVertexAnimVertexData(); - entity->_markBuffersUsedForAnimation(); - } - else - { - // sub entity vertex data (-1) - SubEntity* s = entity->getSubEntity(handle - 1); - // Skip this track if subentity is not visible - if (!s->isVisible()) - continue; - swVertexData = s->_getSoftwareVertexAnimVertexData(); - hwVertexData = s->_getHardwareVertexAnimVertexData(); - s->_markBuffersUsedForAnimation(); - } - // Apply to both hardware and software, if requested - if (software) - { - track->setTargetMode(VertexAnimationTrack::TM_SOFTWARE); - track->applyToVertexData(swVertexData, timeIndex, weight, - &(entity->getMesh()->getPoseList())); - } - if (hardware) - { - track->setTargetMode(VertexAnimationTrack::TM_HARDWARE); - track->applyToVertexData(hwVertexData, timeIndex, weight, - &(entity->getMesh()->getPoseList())); - } - } - - } - //--------------------------------------------------------------------- - void Animation::applyToAnimable(const AnimableValuePtr& anim, Real timePos, Real weight, Real scale) - { - _applyBaseKeyFrame(); - - // Calculate time index for fast keyframe search - _getTimeIndex(timePos); - - for (auto& j : mNumericTrackList) - { - j.second->applyToAnimable(anim, timePos, weight, scale); - } - } - //--------------------------------------------------------------------- - void Animation::applyToVertexData(VertexData* data, Real timePos, float weight) - { - _applyBaseKeyFrame(); - - // Calculate time index for fast keyframe search - TimeIndex timeIndex = _getTimeIndex(timePos); - - for (auto& k : mVertexTrackList) - { - k.second->applyToVertexData(data, timeIndex, weight); - } - } - //--------------------------------------------------------------------- - void Animation::setInterpolationMode(InterpolationMode im) - { - mInterpolationMode = im; - } - //--------------------------------------------------------------------- - Animation::InterpolationMode Animation::getInterpolationMode(void) const - { - return mInterpolationMode; - } - //--------------------------------------------------------------------- - void Animation::setDefaultInterpolationMode(InterpolationMode im) - { - msDefaultInterpolationMode = im; - } - //--------------------------------------------------------------------- - Animation::InterpolationMode Animation::getDefaultInterpolationMode(void) - { - return msDefaultInterpolationMode; - } - //--------------------------------------------------------------------- - const Animation::NodeTrackList& Animation::_getNodeTrackList(void) const - { - return mNodeTrackList; - - } - //--------------------------------------------------------------------- - const Animation::NumericTrackList& Animation::_getNumericTrackList(void) const - { - return mNumericTrackList; - } - //--------------------------------------------------------------------- - const Animation::VertexTrackList& Animation::_getVertexTrackList(void) const - { - return mVertexTrackList; - } - //--------------------------------------------------------------------- - void Animation::setRotationInterpolationMode(RotationInterpolationMode im) - { - mRotationInterpolationMode = im; - } - //--------------------------------------------------------------------- - Animation::RotationInterpolationMode Animation::getRotationInterpolationMode(void) const - { - return mRotationInterpolationMode; - } - //--------------------------------------------------------------------- - void Animation::setDefaultRotationInterpolationMode(RotationInterpolationMode im) - { - msDefaultRotationInterpolationMode = im; - } - //--------------------------------------------------------------------- - Animation::RotationInterpolationMode Animation::getDefaultRotationInterpolationMode(void) - { - return msDefaultRotationInterpolationMode; - } - //--------------------------------------------------------------------- - void Animation::optimise(bool discardIdentityNodeTracks) - { - optimiseNodeTracks(discardIdentityNodeTracks); - optimiseVertexTracks(); - - } - //----------------------------------------------------------------------- - void Animation::_collectIdentityNodeTracks(TrackHandleList& tracks) const - { - for (auto& t : mNodeTrackList) - { - const NodeAnimationTrack* track = t.second; - if (track->hasNonZeroKeyFrames()) - { - tracks.erase(t.first); - } - } - } - //----------------------------------------------------------------------- - void Animation::_destroyNodeTracks(const TrackHandleList& tracks) - { - for (auto t : tracks) - { - destroyNodeTrack(t); - } - } - //----------------------------------------------------------------------- - void Animation::optimiseNodeTracks(bool discardIdentityTracks) - { - // Iterate over the node tracks and identify those with no useful keyframes - std::list tracksToDestroy; - for (auto& t : mNodeTrackList) - { - NodeAnimationTrack* track = t.second; - if (discardIdentityTracks && !track->hasNonZeroKeyFrames()) - { - // mark the entire track for destruction - tracksToDestroy.push_back(t.first); - } - else - { - track->optimise(); - } - } - - // Now destroy the tracks we marked for death - for(unsigned short& h : tracksToDestroy) - { - destroyNodeTrack(h); - } - } - //----------------------------------------------------------------------- - void Animation::optimiseVertexTracks(void) - { - // Iterate over the node tracks and identify those with no useful keyframes - std::list tracksToDestroy; - for (auto& t : mVertexTrackList) - { - VertexAnimationTrack* track = t.second; - if (!track->hasNonZeroKeyFrames()) - { - // mark the entire track for destruction - tracksToDestroy.push_back(t.first); - } - else - { - track->optimise(); - } - } - - // Now destroy the tracks we marked for death - for(unsigned short& h : tracksToDestroy) - { - destroyVertexTrack(h); - } - } - //----------------------------------------------------------------------- - Animation* Animation::clone(const String& newName) const - { - Animation* newAnim = OGRE_NEW Animation(newName, mLength); - newAnim->mInterpolationMode = mInterpolationMode; - newAnim->mRotationInterpolationMode = mRotationInterpolationMode; - - // Clone all tracks - for (auto i : mNodeTrackList) - { - i.second->_clone(newAnim); - } - for (auto i : mNumericTrackList) - { - i.second->_clone(newAnim); - } - for (auto i : mVertexTrackList) - { - i.second->_clone(newAnim); - } - - newAnim->_keyFrameListChanged(); - return newAnim; - - } - //----------------------------------------------------------------------- - TimeIndex Animation::_getTimeIndex(Real timePos) const - { - // Uncomment following statement for work as previous - //return timePos; - - // Build keyframe time list on demand - if (mKeyFrameTimesDirty) - { - buildKeyFrameTimeList(); - } - - // Wrap time - Real totalAnimationLength = mLength; - - if( timePos > totalAnimationLength && totalAnimationLength > 0.0f ) - timePos = std::fmod( timePos, totalAnimationLength ); - - // Search for global index - auto it = std::lower_bound(mKeyFrameTimes.begin(), mKeyFrameTimes.end() - 1, timePos); - return TimeIndex(timePos, static_cast(std::distance(mKeyFrameTimes.begin(), it))); - } - //----------------------------------------------------------------------- - void Animation::buildKeyFrameTimeList(void) const - { - // Clear old keyframe times - mKeyFrameTimes.clear(); - - // Collect all keyframe times from each track - for (auto& i : mNodeTrackList) - { - i.second->_collectKeyFrameTimes(mKeyFrameTimes); - } - for (auto& j : mNumericTrackList) - { - j.second->_collectKeyFrameTimes(mKeyFrameTimes); - } - for (auto& k : mVertexTrackList) - { - k.second->_collectKeyFrameTimes(mKeyFrameTimes); - } - - // Build global index to local index map for each track - for (auto& i : mNodeTrackList) - { - i.second->_buildKeyFrameIndexMap(mKeyFrameTimes); - } - for (auto& j : mNumericTrackList) - { - j.second->_buildKeyFrameIndexMap(mKeyFrameTimes); - } - for (auto& k : mVertexTrackList) - { - k.second->_buildKeyFrameIndexMap(mKeyFrameTimes); - } - - // Reset dirty flag - mKeyFrameTimesDirty = false; - } - //----------------------------------------------------------------------- - void Animation::setUseBaseKeyFrame(bool useBaseKeyFrame, Real keyframeTime, const String& baseAnimName) - { - if (useBaseKeyFrame != mUseBaseKeyFrame || - keyframeTime != mBaseKeyFrameTime || - baseAnimName != mBaseKeyFrameAnimationName) - { - mUseBaseKeyFrame = useBaseKeyFrame; - mBaseKeyFrameTime = keyframeTime; - mBaseKeyFrameAnimationName = baseAnimName; - } - } - //----------------------------------------------------------------------- - bool Animation::getUseBaseKeyFrame() const - { - return mUseBaseKeyFrame; - } - //----------------------------------------------------------------------- - Real Animation::getBaseKeyFrameTime() const - { - return mBaseKeyFrameTime; - } - //----------------------------------------------------------------------- - const String& Animation::getBaseKeyFrameAnimationName() const - { - return mBaseKeyFrameAnimationName; - } - //----------------------------------------------------------------------- - void Animation::_applyBaseKeyFrame() - { - if (mUseBaseKeyFrame) - { - Animation* baseAnim = this; - if (!mBaseKeyFrameAnimationName.empty() && mContainer) - baseAnim = mContainer->getAnimation(mBaseKeyFrameAnimationName); - - if (baseAnim) - { - for (auto& i : mNodeTrackList) - { - NodeAnimationTrack* track = i.second; - - NodeAnimationTrack* baseTrack; - if (baseAnim == this) - baseTrack = track; - else - baseTrack = baseAnim->getNodeTrack(track->getHandle()); - - TransformKeyFrame kf(baseTrack, mBaseKeyFrameTime); - baseTrack->getInterpolatedKeyFrame(baseAnim->_getTimeIndex(mBaseKeyFrameTime), &kf); - track->_applyBaseKeyFrame(&kf); - } - - for (auto& i : mVertexTrackList) - { - VertexAnimationTrack* track = i.second; - - if (track->getAnimationType() == VAT_POSE) - { - VertexAnimationTrack* baseTrack; - if (baseAnim == this) - baseTrack = track; - else - baseTrack = baseAnim->getVertexTrack(track->getHandle()); - - VertexPoseKeyFrame kf(baseTrack, mBaseKeyFrameTime); - baseTrack->getInterpolatedKeyFrame(baseAnim->_getTimeIndex(mBaseKeyFrameTime), &kf); - track->_applyBaseKeyFrame(&kf); - - } - } - - } - - // Re-base has been done, this is a one-way translation - mUseBaseKeyFrame = false; - } - - } - //----------------------------------------------------------------------- - void Animation::_notifyContainer(AnimationContainer* c) - { - mContainer = c; - } - //----------------------------------------------------------------------- - AnimationContainer* Animation::getContainer() - { - return mContainer; - } -} - - diff --git a/OgreMain/src/OgreAnimationState.cpp b/OgreMain/src/OgreAnimationState.cpp deleted file mode 100644 index ade86079db2..00000000000 --- a/OgreMain/src/OgreAnimationState.cpp +++ /dev/null @@ -1,407 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreAnimationState.h" - - -namespace Ogre -{ - - //--------------------------------------------------------------------- - AnimationState::AnimationState(AnimationStateSet* parent, const AnimationState &rhs) - : mAnimationName(rhs.mAnimationName) - , mParent(parent) - , mTimePos(rhs.mTimePos) - , mLength(rhs.mLength) - , mWeight(rhs.mWeight) - , mEnabled(rhs.mEnabled) - , mLoop(rhs.mLoop) - { - mParent->_notifyDirty(); - } - //--------------------------------------------------------------------- - AnimationState::AnimationState(const String& animName, - AnimationStateSet *parent, Real timePos, Real length, Real weight, - bool enabled) - : mAnimationName(animName) - , mParent(parent) - , mTimePos(timePos) - , mLength(length) - , mWeight(weight) - , mEnabled(enabled) - , mLoop(true) - { - mParent->_notifyDirty(); - } - //--------------------------------------------------------------------- - const String& AnimationState::getAnimationName() const - { - return mAnimationName; - } - //--------------------------------------------------------------------- - Real AnimationState::getTimePosition(void) const - { - return mTimePos; - } - //--------------------------------------------------------------------- - void AnimationState::setTimePosition(Real timePos) - { - if (timePos != mTimePos) - { - mTimePos = timePos; - if (mLoop) - { - // Wrap - mTimePos = std::fmod(mTimePos, mLength); - if(mTimePos < 0) mTimePos += mLength; - } - else - { - // Clamp - mTimePos = Math::Clamp(mTimePos, Real(0), mLength); - } - - if (mEnabled) - mParent->_notifyDirty(); - } - - } - //--------------------------------------------------------------------- - Real AnimationState::getLength() const - { - return mLength; - } - //--------------------------------------------------------------------- - void AnimationState::setLength(Real len) - { - mLength = len; - } - //--------------------------------------------------------------------- - Real AnimationState::getWeight(void) const - { - return mWeight; - } - //--------------------------------------------------------------------- - void AnimationState::setWeight(Real weight) - { - mWeight = weight; - - if (mEnabled) - mParent->_notifyDirty(); - } - //--------------------------------------------------------------------- - void AnimationState::addTime(Real offset) - { - setTimePosition(mTimePos + offset); - } - //--------------------------------------------------------------------- - bool AnimationState::hasEnded(void) const - { - return (mTimePos >= mLength && !mLoop); - } - //--------------------------------------------------------------------- - bool AnimationState::getEnabled(void) const - { - return mEnabled; - } - //--------------------------------------------------------------------- - void AnimationState::setEnabled(bool enabled) - { - mEnabled = enabled; - mParent->_notifyAnimationStateEnabled(this, enabled); - } - //--------------------------------------------------------------------- - bool AnimationState::operator==(const AnimationState& rhs) const - { - if (mAnimationName == rhs.mAnimationName && - mEnabled == rhs.mEnabled && - mTimePos == rhs.mTimePos && - mWeight == rhs.mWeight && - mLength == rhs.mLength && - mLoop == rhs.mLoop) - { - return true; - } - else - { - return false; - } - } - //--------------------------------------------------------------------- - bool AnimationState::operator!=(const AnimationState& rhs) const - { - return !(*this == rhs); - } - //--------------------------------------------------------------------- - void AnimationState::copyStateFrom(const AnimationState& animState) - { - mTimePos = animState.mTimePos; - mLength = animState.mLength; - mWeight = animState.mWeight; - mEnabled = animState.mEnabled; - mLoop = animState.mLoop; - mParent->_notifyDirty(); - - } - //--------------------------------------------------------------------- - void AnimationState::setBlendMaskEntry(size_t boneHandle, float weight) - { - assert(mBlendMask.size() > boneHandle); - mBlendMask[boneHandle] = weight; - if (mEnabled) - mParent->_notifyDirty(); - } - //--------------------------------------------------------------------- - void AnimationState::_setBlendMaskData(const float* blendMaskData) - { - assert(!mBlendMask.empty() && "No BlendMask set!"); - // input 0? - if(!blendMaskData) - { - destroyBlendMask(); - return; - } - // dangerous memcpy - memcpy(mBlendMask.data(), blendMaskData, sizeof(float) * mBlendMask.size()); - if (mEnabled) - mParent->_notifyDirty(); - } - //--------------------------------------------------------------------- - void AnimationState::_setBlendMask(const BoneBlendMask* blendMask) - { - if(mBlendMask.empty()) - { - createBlendMask(blendMask->size(), false); - } - _setBlendMaskData(blendMask->data()); - } - //--------------------------------------------------------------------- - void AnimationState::createBlendMask(size_t blendMaskSizeHint, float initialWeight) - { - if(mBlendMask.empty()) - { - if(initialWeight >= 0) - { - mBlendMask.resize(blendMaskSizeHint, initialWeight); - } - else - { - mBlendMask.resize(blendMaskSizeHint); - } - } - } - //--------------------------------------------------------------------- - void AnimationState::destroyBlendMask() - { - mBlendMask.clear(); - mBlendMask.shrink_to_fit(); - } - //--------------------------------------------------------------------- - - //--------------------------------------------------------------------- - AnimationStateSet::AnimationStateSet() - : mDirtyFrameNumber(std::numeric_limits::max()) - { - } - //--------------------------------------------------------------------- - AnimationStateSet::AnimationStateSet(const AnimationStateSet& rhs) - : mDirtyFrameNumber(std::numeric_limits::max()) - { - // lock rhs - OGRE_LOCK_MUTEX(rhs.OGRE_AUTO_MUTEX_NAME); - - for (const auto & mAnimationState : rhs.mAnimationStates) - { - AnimationState* src = mAnimationState.second; - mAnimationStates[src->getAnimationName()] = OGRE_NEW AnimationState(this, *src); - } - - // Clone enabled animation state list - for (auto src : rhs.mEnabledAnimationStates) - { - mEnabledAnimationStates.push_back(getAnimationState(src->getAnimationName())); - } - } - //--------------------------------------------------------------------- - AnimationStateSet::~AnimationStateSet() - { - // Destroy - removeAllAnimationStates(); - } - //--------------------------------------------------------------------- - void AnimationStateSet::removeAnimationState(const String& name) - { - OGRE_LOCK_AUTO_MUTEX; - - AnimationStateMap::iterator i = mAnimationStates.find(name); - if (i != mAnimationStates.end()) - { - mEnabledAnimationStates.remove(i->second); - - OGRE_DELETE i->second; - mAnimationStates.erase(i); - } - } - //--------------------------------------------------------------------- - void AnimationStateSet::removeAllAnimationStates(void) - { - OGRE_LOCK_AUTO_MUTEX; - - for (auto & mAnimationState : mAnimationStates) - { - OGRE_DELETE mAnimationState.second; - } - mAnimationStates.clear(); - mEnabledAnimationStates.clear(); - } - //--------------------------------------------------------------------- - AnimationState* AnimationStateSet::createAnimationState(const String& name, - Real timePos, Real length, Real weight, bool enabled) - { - OGRE_LOCK_AUTO_MUTEX; - - AnimationStateMap::iterator i = mAnimationStates.find(name); - if (i != mAnimationStates.end()) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "State for animation named '" + name + "' already exists.", - "AnimationStateSet::createAnimationState"); - } - - AnimationState* newState = OGRE_NEW AnimationState(name, this, timePos, - length, weight, enabled); - mAnimationStates[name] = newState; - return newState; - - } - //--------------------------------------------------------------------- - AnimationState* AnimationStateSet::getAnimationState(const String& name) const - { - OGRE_LOCK_AUTO_MUTEX; - - AnimationStateMap::const_iterator i = mAnimationStates.find(name); - if (i == mAnimationStates.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "No state found for animation named '" + name + "'", - "AnimationStateSet::getAnimationState"); - } - return i->second; - } - //--------------------------------------------------------------------- - bool AnimationStateSet::hasAnimationState(const String& name) const - { - OGRE_LOCK_AUTO_MUTEX; - - return mAnimationStates.find(name) != mAnimationStates.end(); - } - //--------------------------------------------------------------------- - AnimationStateIterator AnimationStateSet::getAnimationStateIterator(void) - { - OGRE_LOCK_AUTO_MUTEX; - // returned iterator not threadsafe, noted in header - return AnimationStateIterator( - mAnimationStates.begin(), mAnimationStates.end()); - } - //--------------------------------------------------------------------- - ConstAnimationStateIterator AnimationStateSet::getAnimationStateIterator(void) const - { - OGRE_LOCK_AUTO_MUTEX; - // returned iterator not threadsafe, noted in header - return ConstAnimationStateIterator( - mAnimationStates.begin(), mAnimationStates.end()); - } - //--------------------------------------------------------------------- - void AnimationStateSet::copyMatchingState(AnimationStateSet* target) const - { - // lock target - OGRE_LOCK_MUTEX(target->OGRE_AUTO_MUTEX_NAME); - // lock source - OGRE_LOCK_AUTO_MUTEX; - - for (auto& t : target->mAnimationStates) { - AnimationStateMap::const_iterator iother = mAnimationStates.find(t.first); - if (iother == mAnimationStates.end()) { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "No animation entry found named " + t.first, - "AnimationStateSet::copyMatchingState"); - } else { - t.second->copyStateFrom(*(iother->second)); - } - } - - // Copy matching enabled animation state list - target->mEnabledAnimationStates.clear(); - - for (auto *src : mEnabledAnimationStates) - { - AnimationStateMap::const_iterator itarget = target->mAnimationStates.find(src->getAnimationName()); - if (itarget != target->mAnimationStates.end()) - { - target->mEnabledAnimationStates.push_back(itarget->second); - } - } - - target->mDirtyFrameNumber = mDirtyFrameNumber; - } - //--------------------------------------------------------------------- - void AnimationStateSet::_notifyDirty(void) - { - OGRE_LOCK_AUTO_MUTEX; - ++mDirtyFrameNumber; - } - //--------------------------------------------------------------------- - void AnimationStateSet::_notifyAnimationStateEnabled(AnimationState* target, bool enabled) - { - OGRE_LOCK_AUTO_MUTEX; - // Remove from enabled animation state list first - mEnabledAnimationStates.remove(target); - - // Add to enabled animation state list if need - if (enabled) - { - mEnabledAnimationStates.push_back(target); - } - - // Set the dirty frame number - _notifyDirty(); - } - //--------------------------------------------------------------------- - ConstEnabledAnimationStateIterator AnimationStateSet::getEnabledAnimationStateIterator(void) const - { - OGRE_LOCK_AUTO_MUTEX; - // returned iterator not threadsafe, noted in header - return ConstEnabledAnimationStateIterator( - mEnabledAnimationStates.begin(), mEnabledAnimationStates.end()); - } - - ControllerValueRealPtr AnimationStateControllerValue::create(AnimationState* targetAnimationState, bool addTime) - { - return std::make_shared(targetAnimationState, addTime); - } -} - diff --git a/OgreMain/src/OgreAnimationTrack.cpp b/OgreMain/src/OgreAnimationTrack.cpp deleted file mode 100644 index 04287d77d2a..00000000000 --- a/OgreMain/src/OgreAnimationTrack.cpp +++ /dev/null @@ -1,1022 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreAnimationTrack.h" -#include "OgreAnimation.h" -#include "OgreKeyFrame.h" - -namespace Ogre { - - namespace { - // Locally key frame search helper - struct KeyFrameTimeLess - { - bool operator() (const KeyFrame* kf, const KeyFrame* kf2) const - { - return kf->getTime() < kf2->getTime(); - } - }; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - AnimationTrack::AnimationTrack(Animation* parent, unsigned short handle) : - mParent(parent), mListener(0), mHandle(handle) - { - } - //--------------------------------------------------------------------- - AnimationTrack::~AnimationTrack() - { - removeAllKeyFrames(); - } - //--------------------------------------------------------------------- - float AnimationTrack::getKeyFramesAtTime(const TimeIndex& timeIndex, KeyFrame** keyFrame1, KeyFrame** keyFrame2, - unsigned short* firstKeyIndex) const - { - // Parametric time - // t1 = time of previous keyframe - // t2 = time of next keyframe - Real t1, t2; - - Real timePos = timeIndex.getTimePos(); - - // Find first keyframe after or on current time - KeyFrameList::const_iterator i; - if (timeIndex.hasKeyIndex()) - { - // Global keyframe index available, map to local keyframe index directly. - assert(timeIndex.getKeyIndex() < mKeyFrameIndexMap.size()); - i = mKeyFrames.begin() + mKeyFrameIndexMap[timeIndex.getKeyIndex()]; -#if OGRE_DEBUG_MODE - KeyFrame timeKey(NULL, timePos); - if (i != std::lower_bound(mKeyFrames.begin(), mKeyFrames.end() - 1, &timeKey, KeyFrameTimeLess())) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Optimised key frame search failed"); - } -#endif - } - else - { - // Wrap time - Real totalAnimationLength = mParent->getLength(); - OgreAssertDbg(totalAnimationLength > 0.0f, "Invalid animation length!"); - - if( timePos > totalAnimationLength && totalAnimationLength > 0.0f ) - timePos = std::fmod( timePos, totalAnimationLength ); - - // No global keyframe index, need to search with local keyframes. - KeyFrame timeKey(NULL, timePos); - i = std::lower_bound(mKeyFrames.begin(), mKeyFrames.end() - 1, &timeKey, KeyFrameTimeLess()); - } - - OgreAssertDbg(i != mKeyFrames.end(), "time should have been wrapped before this"); - - *keyFrame2 = *i; - t2 = (*keyFrame2)->getTime(); - - // Find last keyframe before or on current time - if (i != mKeyFrames.begin() && timePos < (*i)->getTime()) - { - --i; - } - - // Fill index of the first key - if (firstKeyIndex) - { - *firstKeyIndex = static_cast(std::distance(mKeyFrames.begin(), i)); - } - - *keyFrame1 = *i; - - t1 = (*keyFrame1)->getTime(); - - if (t1 == t2) - { - // Same KeyFrame (only one) - return 0.0f; - } - else - { - return (timePos - t1) / (t2 - t1); - } - } - //--------------------------------------------------------------------- - KeyFrame* AnimationTrack::createKeyFrame(Real timePos) - { - KeyFrame* kf = createKeyFrameImpl(timePos); - - // Insert just before upper bound - KeyFrameList::iterator i = - std::upper_bound(mKeyFrames.begin(), mKeyFrames.end(), kf, KeyFrameTimeLess()); - mKeyFrames.insert(i, kf); - - _keyFrameDataChanged(); - mParent->_keyFrameListChanged(); - - return kf; - - } - //--------------------------------------------------------------------- - void AnimationTrack::removeKeyFrame(unsigned short index) - { - // If you hit this assert, then the keyframe index is out of bounds - assert( index < (ushort)mKeyFrames.size() ); - - KeyFrameList::iterator i = mKeyFrames.begin(); - - i += index; - - OGRE_DELETE *i; - - mKeyFrames.erase(i); - - _keyFrameDataChanged(); - mParent->_keyFrameListChanged(); - - - } - //--------------------------------------------------------------------- - void AnimationTrack::removeAllKeyFrames(void) - { - for (auto *f : mKeyFrames) - OGRE_DELETE f; - - _keyFrameDataChanged(); - mParent->_keyFrameListChanged(); - - mKeyFrames.clear(); - - } - //--------------------------------------------------------------------- - void AnimationTrack::_collectKeyFrameTimes(std::vector& keyFrameTimes) - { - for (auto k : mKeyFrames) - { - Real timePos = k->getTime(); - - std::vector::iterator it = - std::lower_bound(keyFrameTimes.begin(), keyFrameTimes.end(), timePos); - if (it == keyFrameTimes.end() || *it != timePos) - { - keyFrameTimes.insert(it, timePos); - } - } - } - //--------------------------------------------------------------------- - void AnimationTrack::_buildKeyFrameIndexMap(const std::vector& keyFrameTimes) - { - // Pre-allocate memory - mKeyFrameIndexMap.resize(keyFrameTimes.size()); - - size_t i = 0, j = 0; - - while (j < keyFrameTimes.size()) - { - mKeyFrameIndexMap[j] = static_cast(i); - while (i < (mKeyFrames.size() - 1) && mKeyFrames[i]->getTime() <= keyFrameTimes[j]) - { - ++i; - } - ++j; - } - } - //-------------------------------------------------------------------------- - void AnimationTrack::_applyBaseKeyFrame(const KeyFrame*) - { - - } - //--------------------------------------------------------------------- - void AnimationTrack::populateClone(AnimationTrack* clone) const - { - for (auto k : mKeyFrames) - { - KeyFrame* clonekf = k->_clone(clone); - clone->mKeyFrames.push_back(clonekf); - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - // Numeric specialisations - //--------------------------------------------------------------------- - NumericAnimationTrack::NumericAnimationTrack(Animation* parent, - unsigned short handle, const AnimableValuePtr& target) - :AnimationTrack(parent, handle), mTargetAnim(target) - { - } - //--------------------------------------------------------------------- - KeyFrame* NumericAnimationTrack::createKeyFrameImpl(Real time) - { - return OGRE_NEW NumericKeyFrame(this, time); - } - - static Any lerpAny(const Any& v0, const Any& v1, Real t, AnimableValue::ValueType type) - { - switch(type) - { - default: - case AnimableValue::INT: - return Math::lerp(any_cast(v0), any_cast(v1), t); - case AnimableValue::REAL: - return Math::lerp(any_cast(v0), any_cast(v1), t); - case AnimableValue::VECTOR2: - return Math::lerp(any_cast(v0), any_cast(v1), t); - case AnimableValue::VECTOR3: - return Math::lerp(any_cast(v0), any_cast(v1), t); - case AnimableValue::VECTOR4: - return Math::lerp(any_cast(v0), any_cast(v1), t); - case AnimableValue::QUATERNION: - return Math::lerp(any_cast(v0), any_cast(v1), t); - case AnimableValue::COLOUR: - return Math::lerp(any_cast(v0), any_cast(v1), t); - case AnimableValue::RADIAN: - return Math::lerp(any_cast(v0), any_cast(v1), t); - } - } - - //--------------------------------------------------------------------- - void NumericAnimationTrack::getInterpolatedKeyFrame(const TimeIndex& timeIndex, - KeyFrame* kf) const - { - if (mListener) - { - if (mListener->getInterpolatedKeyFrame(this, timeIndex, kf)) - return; - } - - NumericKeyFrame* kret = static_cast(kf); - - // Keyframe pointers - KeyFrame *kBase1, *kBase2; - NumericKeyFrame *k1, *k2; - unsigned short firstKeyIndex; - - Real t = this->getKeyFramesAtTime(timeIndex, &kBase1, &kBase2, &firstKeyIndex); - k1 = static_cast(kBase1); - k2 = static_cast(kBase2); - - if (t == 0.0) - { - // Just use k1 - kret->setValue(k1->getValue()); - } - else - { - // Interpolate by t - kret->setValue(lerpAny(k1->getValue(), k2->getValue(), t, mTargetAnim->getType())); - } - } - //--------------------------------------------------------------------- - void NumericAnimationTrack::apply(const TimeIndex& timeIndex, Real weight, Real scale) - { - applyToAnimable(mTargetAnim, timeIndex, weight, scale); - } - //--------------------------------------------------------------------- - static Any scaleAny(const Any& v, Real s, AnimableValue::ValueType type) - { - switch(type) - { - default: - case AnimableValue::INT: - return any_cast(v) * s; - case AnimableValue::REAL: - return any_cast(v) * s; - case AnimableValue::VECTOR2: - return any_cast(v) * s; - case AnimableValue::VECTOR3: - return any_cast(v) * s; - case AnimableValue::VECTOR4: - return any_cast(v) * s; - case AnimableValue::QUATERNION: - return any_cast(v) * s; - case AnimableValue::COLOUR: - return any_cast(v) * s; - case AnimableValue::RADIAN: - return any_cast(v) * s; - } - } - void NumericAnimationTrack::applyToAnimable(const AnimableValuePtr& anim, const TimeIndex& timeIndex, - Real weight, Real scale) - { - // Nothing to do if no keyframes or zero weight, scale - if (mKeyFrames.empty() || !weight || !scale) - return; - - NumericKeyFrame kf(0, timeIndex.getTimePos()); - getInterpolatedKeyFrame(timeIndex, &kf); - // add to existing. Weights are not relative, but treated as - // absolute multipliers for the animation - anim->applyDeltaValue(scaleAny(kf.getValue(), weight * scale, mTargetAnim->getType())); - - } - //-------------------------------------------------------------------------- - NumericKeyFrame* NumericAnimationTrack::createNumericKeyFrame(Real timePos) - { - return static_cast(createKeyFrame(timePos)); - } - //-------------------------------------------------------------------------- - NumericKeyFrame* NumericAnimationTrack::getNumericKeyFrame(unsigned short index) const - { - return static_cast(getKeyFrame(index)); - } - //--------------------------------------------------------------------- - NumericAnimationTrack* NumericAnimationTrack::_clone(Animation* newParent) const - { - NumericAnimationTrack* newTrack = newParent->createNumericTrack(mHandle, mTargetAnim); - populateClone(newTrack); - return newTrack; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - // Node specialisations - //--------------------------------------------------------------------- - NodeAnimationTrack::NodeAnimationTrack(Animation* parent, unsigned short handle) - : NodeAnimationTrack(parent, handle, 0) - { - } - //--------------------------------------------------------------------- - NodeAnimationTrack::NodeAnimationTrack(Animation* parent, unsigned short handle, Node* targetNode) - : AnimationTrack(parent, handle), mSplineBuildNeeded(false), mUseShortestRotationPath(true), - mTargetNode(targetNode), mSplines(0) - - { - } - //--------------------------------------------------------------------- - NodeAnimationTrack::~NodeAnimationTrack() - { - OGRE_DELETE_T(mSplines, Splines, MEMCATEGORY_ANIMATION); - } - //--------------------------------------------------------------------- - void NodeAnimationTrack::getInterpolatedKeyFrame(const TimeIndex& timeIndex, KeyFrame* kf) const - { - if (mListener) - { - if (mListener->getInterpolatedKeyFrame(this, timeIndex, kf)) - return; - } - - TransformKeyFrame* kret = static_cast(kf); - - // Keyframe pointers - KeyFrame *kBase1, *kBase2; - TransformKeyFrame *k1, *k2; - unsigned short firstKeyIndex; - - Real t = this->getKeyFramesAtTime(timeIndex, &kBase1, &kBase2, &firstKeyIndex); - k1 = static_cast(kBase1); - k2 = static_cast(kBase2); - - if (t == 0.0) - { - // Just use k1 - kret->setRotation(k1->getRotation()); - kret->setTranslate(k1->getTranslate()); - kret->setScale(k1->getScale()); - } - else - { - // Interpolate by t - Animation::InterpolationMode im = mParent->getInterpolationMode(); - Animation::RotationInterpolationMode rim = - mParent->getRotationInterpolationMode(); - Vector3 base; - switch(im) - { - case Animation::IM_LINEAR: - // Interpolate linearly - // Rotation - // Interpolate to nearest rotation if mUseShortestRotationPath set - if (rim == Animation::RIM_LINEAR) - { - kret->setRotation( Quaternion::nlerp(t, k1->getRotation(), - k2->getRotation(), mUseShortestRotationPath) ); - } - else //if (rim == Animation::RIM_SPHERICAL) - { - kret->setRotation( Quaternion::Slerp(t, k1->getRotation(), - k2->getRotation(), mUseShortestRotationPath) ); - } - - // Translation - base = k1->getTranslate(); - kret->setTranslate( base + ((k2->getTranslate() - base) * t) ); - - // Scale - base = k1->getScale(); - kret->setScale( base + ((k2->getScale() - base) * t) ); - break; - - case Animation::IM_SPLINE: - // Spline interpolation - - // Build splines if required - if (mSplineBuildNeeded) - { - buildInterpolationSplines(); - } - - // Rotation, take mUseShortestRotationPath into account - kret->setRotation( mSplines->rotationSpline.interpolate(firstKeyIndex, t, - mUseShortestRotationPath) ); - - // Translation - kret->setTranslate( mSplines->positionSpline.interpolate(firstKeyIndex, t) ); - - // Scale - kret->setScale( mSplines->scaleSpline.interpolate(firstKeyIndex, t) ); - - break; - } - - } - } - //--------------------------------------------------------------------- - void NodeAnimationTrack::apply(const TimeIndex& timeIndex, Real weight, Real scale) - { - applyToNode(mTargetNode, timeIndex, weight, scale); - - } - //--------------------------------------------------------------------- - Node* NodeAnimationTrack::getAssociatedNode(void) const - { - return mTargetNode; - } - //--------------------------------------------------------------------- - void NodeAnimationTrack::setAssociatedNode(Node* node) - { - mTargetNode = node; - } - //--------------------------------------------------------------------- - void NodeAnimationTrack::applyToNode(Node* node, const TimeIndex& timeIndex, Real weight, - Real scl) - { - // Nothing to do if no keyframes or zero weight or no node - if (mKeyFrames.empty() || !weight || !node) - return; - - TransformKeyFrame kf(0, timeIndex.getTimePos()); - getInterpolatedKeyFrame(timeIndex, &kf); - - // add to existing. Weights are not relative, but treated as absolute multipliers for the animation - Vector3 translate = kf.getTranslate() * weight * scl; - node->translate(translate); - - // interpolate between no-rotation and full rotation, to point 'weight', so 0 = no rotate, 1 = full - Quaternion rotate; - Animation::RotationInterpolationMode rim = - mParent->getRotationInterpolationMode(); - if (rim == Animation::RIM_LINEAR) - { - rotate = Quaternion::nlerp(weight, Quaternion::IDENTITY, kf.getRotation(), mUseShortestRotationPath); - } - else //if (rim == Animation::RIM_SPHERICAL) - { - rotate = Quaternion::Slerp(weight, Quaternion::IDENTITY, kf.getRotation(), mUseShortestRotationPath); - } - node->rotate(rotate); - - Vector3 scale = kf.getScale(); - // Not sure how to modify scale for cumulative anims... leave it alone - //scale = ((Vector3::UNIT_SCALE - kf.getScale()) * weight) + Vector3::UNIT_SCALE; - if (scale != Vector3::UNIT_SCALE) - { - if (scl != 1.0f) - scale = Vector3::UNIT_SCALE + (scale - Vector3::UNIT_SCALE) * scl; - else if (weight != 1.0f) - scale = Vector3::UNIT_SCALE + (scale - Vector3::UNIT_SCALE) * weight; - } - node->scale(scale); - - } - //--------------------------------------------------------------------- - void NodeAnimationTrack::buildInterpolationSplines(void) const - { - // Allocate splines if not exists - if (!mSplines) - { - mSplines = OGRE_NEW_T(Splines, MEMCATEGORY_ANIMATION); - } - - // Cache to register for optimisation - Splines* splines = mSplines; - - // Don't calc automatically, do it on request at the end - splines->positionSpline.setAutoCalculate(false); - splines->rotationSpline.setAutoCalculate(false); - splines->scaleSpline.setAutoCalculate(false); - - splines->positionSpline.clear(); - splines->rotationSpline.clear(); - splines->scaleSpline.clear(); - - for (auto *f : mKeyFrames) - { - TransformKeyFrame* kf = static_cast(f); - splines->positionSpline.addPoint(kf->getTranslate()); - splines->rotationSpline.addPoint(kf->getRotation()); - splines->scaleSpline.addPoint(kf->getScale()); - } - - splines->positionSpline.recalcTangents(); - splines->rotationSpline.recalcTangents(); - splines->scaleSpline.recalcTangents(); - - - mSplineBuildNeeded = false; - } - - //--------------------------------------------------------------------- - void NodeAnimationTrack::setUseShortestRotationPath(bool useShortestPath) - { - mUseShortestRotationPath = useShortestPath ; - } - - //--------------------------------------------------------------------- - bool NodeAnimationTrack::getUseShortestRotationPath() const - { - return mUseShortestRotationPath ; - } - //--------------------------------------------------------------------- - void NodeAnimationTrack::_keyFrameDataChanged(void) const - { - mSplineBuildNeeded = true; - } - //--------------------------------------------------------------------- - bool NodeAnimationTrack::hasNonZeroKeyFrames(void) const - { - for (auto *k : mKeyFrames) - { - // look for keyframes which have any component which is non-zero - // Since exporters can be a little inaccurate sometimes we use a - // tolerance value rather than looking for nothing - TransformKeyFrame* kf = static_cast(k); - Vector3 trans = kf->getTranslate(); - Vector3 scale = kf->getScale(); - Vector3 axis; - Radian angle; - kf->getRotation().ToAngleAxis(angle, axis); - Real tolerance = 1e-3f; - if (!trans.positionEquals(Vector3::ZERO, tolerance) || - !scale.positionEquals(Vector3::UNIT_SCALE, tolerance) || - !Math::RealEqual(angle.valueRadians(), 0.0f, tolerance)) - { - return true; - } - } - - return false; - } - //--------------------------------------------------------------------- - void NodeAnimationTrack::optimise(void) - { - // Eliminate duplicate keyframes from 2nd to penultimate keyframe - // NB only eliminate middle keys from sequences of 5+ identical keyframes - // since we need to preserve the boundary keys in place, and we need - // 2 at each end to preserve tangents for spline interpolation - Vector3 lasttrans = Vector3::ZERO; - Vector3 lastscale = Vector3::ZERO; - Quaternion lastorientation; - Radian quatTolerance(1e-3f); - std::list removeList; - unsigned short k = 0; - ushort dupKfCount = 0; - for (auto *f : mKeyFrames) - { - auto kf = static_cast(f); - Vector3 newtrans = kf->getTranslate(); - Vector3 newscale = kf->getScale(); - Quaternion neworientation = kf->getRotation(); - // Ignore first keyframe; now include the last keyframe as we eliminate - // only k-2 in a group of 5 to ensure we only eliminate middle keys - if (k && newtrans.positionEquals(lasttrans) && - newscale.positionEquals(lastscale) && - neworientation.equals(lastorientation, quatTolerance)) - { - ++dupKfCount; - - // 4 indicates this is the 5th duplicate keyframe - if (dupKfCount == 4) - { - // remove the 'middle' keyframe - removeList.push_back(k-2); - --dupKfCount; - } - } - else - { - // reset - dupKfCount = 0; - lasttrans = newtrans; - lastscale = newscale; - lastorientation = neworientation; - } - ++k; - } - - // Now remove keyframes, in reverse order to avoid index revocation - std::list::reverse_iterator r = removeList.rbegin(); - for (; r!= removeList.rend(); ++r) - { - removeKeyFrame(*r); - } - } - //-------------------------------------------------------------------------- - KeyFrame* NodeAnimationTrack::createKeyFrameImpl(Real time) - { - return OGRE_NEW TransformKeyFrame(this, time); - } - //-------------------------------------------------------------------------- - TransformKeyFrame* NodeAnimationTrack::createNodeKeyFrame(Real timePos) - { - return static_cast(createKeyFrame(timePos)); - } - //-------------------------------------------------------------------------- - TransformKeyFrame* NodeAnimationTrack::getNodeKeyFrame(unsigned short index) const - { - return static_cast(getKeyFrame(index)); - } - //--------------------------------------------------------------------- - NodeAnimationTrack* NodeAnimationTrack::_clone(Animation* newParent) const - { - NodeAnimationTrack* newTrack = - newParent->createNodeTrack(mHandle, mTargetNode); - newTrack->mUseShortestRotationPath = mUseShortestRotationPath; - populateClone(newTrack); - return newTrack; - } - //-------------------------------------------------------------------------- - void NodeAnimationTrack::_applyBaseKeyFrame(const KeyFrame* b) - { - const TransformKeyFrame* base = static_cast(b); - - for (auto& k : mKeyFrames) - { - TransformKeyFrame* kf = static_cast(k); - kf->setTranslate(kf->getTranslate() - base->getTranslate()); - kf->setRotation(base->getRotation().Inverse() * kf->getRotation()); - kf->setScale(kf->getScale() * (Vector3::UNIT_SCALE / base->getScale())); - } - - } - //-------------------------------------------------------------------------- - VertexAnimationTrack::VertexAnimationTrack(Animation* parent, - unsigned short handle, VertexAnimationType animType) - : AnimationTrack(parent, handle) - , mAnimationType(animType) - { - } - //-------------------------------------------------------------------------- - VertexAnimationTrack::VertexAnimationTrack(Animation* parent, unsigned short handle, - VertexAnimationType animType, VertexData* targetData, TargetMode target) - : AnimationTrack(parent, handle) - , mAnimationType(animType) - , mTargetMode(target) - , mTargetVertexData(targetData) - { - } - //-------------------------------------------------------------------------- - VertexMorphKeyFrame* VertexAnimationTrack::createVertexMorphKeyFrame(Real timePos) - { - OgreAssert(mAnimationType == VAT_MORPH, "Type mismatch"); - return static_cast(createKeyFrame(timePos)); - } - //-------------------------------------------------------------------------- - VertexPoseKeyFrame* VertexAnimationTrack::createVertexPoseKeyFrame(Real timePos) - { - OgreAssert(mAnimationType == VAT_POSE, "Type mismatch"); - return static_cast(createKeyFrame(timePos)); - } - //-------------------------------------------------------------------------- - void VertexAnimationTrack::getInterpolatedKeyFrame(const TimeIndex& timeIndex, KeyFrame* kf) const - { - // Only relevant for pose animation - if (mAnimationType == VAT_POSE) - { - // Get keyframes - KeyFrame *kf1, *kf2; - Real t = getKeyFramesAtTime(timeIndex, &kf1, &kf2); - - VertexPoseKeyFrame* vkfOut = static_cast(kf); - VertexPoseKeyFrame* vkf1 = static_cast(kf1); - VertexPoseKeyFrame* vkf2 = static_cast(kf2); - - // For each pose reference in key 1, we need to locate the entry in - // key 2 and interpolate the influence - const VertexPoseKeyFrame::PoseRefList& poseList1 = vkf1->getPoseReferences(); - const VertexPoseKeyFrame::PoseRefList& poseList2 = vkf2->getPoseReferences(); - for (auto& p1 : poseList1) - { - Real startInfluence = p1.influence; - Real endInfluence = 0; - // Search for entry in keyframe 2 list (if not there, will be 0) - for (auto& p2 : poseList2) - { - if (p1.poseIndex == p2.poseIndex) - { - endInfluence = p2.influence; - break; - } - } - // Interpolate influence - Real influence = startInfluence + t*(endInfluence - startInfluence); - - vkfOut->addPoseReference(p1.poseIndex, influence); - - - } - // Now deal with any poses in key 2 which are not in key 1 - for (auto& p2 : poseList2) - { - bool found = false; - for (auto& p1 : poseList1) - { - if (p1.poseIndex == p2.poseIndex) - { - found = true; - break; - } - } - if (!found) - { - // Need to apply this pose too, scaled from 0 start - Real influence = t * p2.influence; - - vkfOut->addPoseReference(p2.poseIndex, influence); - - } - } // key 2 iteration - - } - } - //-------------------------------------------------------------------------- - bool VertexAnimationTrack::getVertexAnimationIncludesNormals() const - { - if (mAnimationType == VAT_NONE) - return false; - - if (mAnimationType == VAT_MORPH) - { - bool normals = false; - for (KeyFrameList::const_iterator i = mKeyFrames.begin(); i != mKeyFrames.end(); ++i) - { - VertexMorphKeyFrame* kf = static_cast(*i); - bool thisnorm = kf->getVertexBuffer()->getVertexSize() > 12; - if (i == mKeyFrames.begin()) - normals = thisnorm; - else - // Only support normals if ALL keyframes include them - normals = normals && thisnorm; - - } - return normals; - } - else - { - // needs to derive from Mesh::PoseList, can't tell here - return false; - } - } - //-------------------------------------------------------------------------- - void VertexAnimationTrack::apply(const TimeIndex& timeIndex, Real weight, Real scale) - { - applyToVertexData(mTargetVertexData, timeIndex, weight); - } - //-------------------------------------------------------------------------- - void VertexAnimationTrack::applyToVertexData(VertexData* data, - const TimeIndex& timeIndex, float weight, const PoseList* poseList) - { - // Nothing to do if no keyframes or no vertex data - if (mKeyFrames.empty() || !data) - return; - - // Get keyframes - KeyFrame *kf1, *kf2; - float t = getKeyFramesAtTime(timeIndex, &kf1, &kf2); - - if (mAnimationType == VAT_MORPH) - { - VertexMorphKeyFrame* vkf1 = static_cast(kf1); - VertexMorphKeyFrame* vkf2 = static_cast(kf2); - - if (mTargetMode == TM_HARDWARE) - { - // If target mode is hardware, need to bind our 2 keyframe buffers, - // one to main pos, one to morph target texcoord - assert(!data->hwAnimationDataList.empty() && - "Haven't set up hardware vertex animation elements!"); - - // no use for TempBlendedBufferInfo here btw - // NB we assume that position buffer is unshared, except for normals - // VertexDeclaration::getAutoOrganisedDeclaration should see to that - const VertexElement* posElem = - data->vertexDeclaration->findElementBySemantic(VES_POSITION); - // Set keyframe1 data as original position - data->vertexBufferBinding->setBinding( - posElem->getSource(), vkf1->getVertexBuffer()); - // Set keyframe2 data as derived - data->vertexBufferBinding->setBinding( - data->hwAnimationDataList[0].targetBufferIndex, - vkf2->getVertexBuffer()); - // save T for use later - data->hwAnimationDataList[0].parametric = t; - - } - else - { - // If target mode is software, need to software interpolate each vertex - Mesh::softwareVertexMorph( - t, vkf1->getVertexBuffer(), vkf2->getVertexBuffer(), data); - } - } - else - { - // Pose - OgreAssert(poseList, "Pose list required for pose animation"); - VertexPoseKeyFrame* vkf1 = static_cast(kf1); - VertexPoseKeyFrame* vkf2 = static_cast(kf2); - // For each pose reference in key 1, we need to locate the entry in - // key 2 and interpolate the influence - const VertexPoseKeyFrame::PoseRefList& poseList1 = vkf1->getPoseReferences(); - const VertexPoseKeyFrame::PoseRefList& poseList2 = vkf2->getPoseReferences(); - for (auto& p1 : poseList1) - { - float startInfluence = p1.influence; - float endInfluence = 0; - // Search for entry in keyframe 2 list (if not there, will be 0) - for (auto& p2 : poseList2) - { - if (p1.poseIndex == p2.poseIndex) - { - endInfluence = p2.influence; - break; - } - } - // Interpolate influence - float influence = startInfluence + t*(endInfluence - startInfluence); - // Scale by animation weight - influence = weight * influence; - // Get pose - assert (p1.poseIndex < poseList->size()); - Pose* pose = (*poseList)[p1.poseIndex]; - // apply - applyPoseToVertexData(pose, data, influence); - } - // Now deal with any poses in key 2 which are not in key 1 - for (auto& p2 : poseList2) - { - bool found = false; - for (auto& p1 : poseList1) - { - if (p1.poseIndex == p2.poseIndex) - { - found = true; - break; - } - } - if (!found) - { - // Need to apply this pose too, scaled from 0 start - float influence = t * p2.influence; - // Scale by animation weight - influence = weight * influence; - // Get pose - assert (p2.poseIndex < poseList->size()); - const Pose* pose = (*poseList)[p2.poseIndex]; - // apply - applyPoseToVertexData(pose, data, influence); - } - } // key 2 iteration - } // morph or pose animation - } - //----------------------------------------------------------------------------- - void VertexAnimationTrack::applyPoseToVertexData(const Pose* pose, - VertexData* data, float influence) - { - if (mTargetMode == TM_HARDWARE) - { - // Hardware - // If target mode is hardware, need to bind our pose buffer - // to a target texcoord - assert(!data->hwAnimationDataList.empty() && - "Haven't set up hardware vertex animation elements!"); - // no use for TempBlendedBufferInfo here btw - // Set pose target as required - size_t hwIndex = data->hwAnimDataItemsUsed++; - // If we try to use too many poses, ignore extras - if (hwIndex < data->hwAnimationDataList.size()) - { - VertexData::HardwareAnimationData& animData = data->hwAnimationDataList[hwIndex]; - data->vertexBufferBinding->setBinding( - animData.targetBufferIndex, - pose->_getHardwareVertexBuffer(data)); - // save final influence in parametric - animData.parametric = influence; - - } - } - else - { - // Software - Mesh::softwareVertexPoseBlend(influence, pose->getVertexOffsets(), pose->getNormals(), data); - } - - } - //-------------------------------------------------------------------------- - VertexMorphKeyFrame* VertexAnimationTrack::getVertexMorphKeyFrame(unsigned short index) const - { - OgreAssert(mAnimationType == VAT_MORPH, "Type mismatch"); - return static_cast(getKeyFrame(index)); - } - //-------------------------------------------------------------------------- - VertexPoseKeyFrame* VertexAnimationTrack::getVertexPoseKeyFrame(unsigned short index) const - { - OgreAssert(mAnimationType == VAT_POSE, "Type mismatch"); - return static_cast(getKeyFrame(index)); - } - //-------------------------------------------------------------------------- - KeyFrame* VertexAnimationTrack::createKeyFrameImpl(Real time) - { - switch(mAnimationType) - { - default: - case VAT_MORPH: - return OGRE_NEW VertexMorphKeyFrame(this, time); - case VAT_POSE: - return OGRE_NEW VertexPoseKeyFrame(this, time); - }; - - } - //--------------------------------------------------------------------- - bool VertexAnimationTrack::hasNonZeroKeyFrames(void) const - { - if (mAnimationType == VAT_MORPH) - { - return !mKeyFrames.empty(); - } - else - { - for (auto kf : mKeyFrames) - { - // look for keyframes which have a pose influence which is non-zero - auto& poses = static_cast(kf)->getPoseReferences(); - for (auto& poseIt : poses) - { - if (poseIt.influence > 0.0f) - return true; - } - } - - return false; - } - } - //--------------------------------------------------------------------- - void VertexAnimationTrack::optimise(void) - { - // TODO - remove sequences of duplicate pose references? - - } - //--------------------------------------------------------------------- - VertexAnimationTrack* VertexAnimationTrack::_clone(Animation* newParent) const - { - VertexAnimationTrack* newTrack = - newParent->createVertexTrack(mHandle, mAnimationType); - newTrack->mTargetMode = mTargetMode; - populateClone(newTrack); - return newTrack; - } - //-------------------------------------------------------------------------- - void VertexAnimationTrack::_applyBaseKeyFrame(const KeyFrame* b) - { - const VertexPoseKeyFrame* base = static_cast(b); - - for (auto& k : mKeyFrames) - { - VertexPoseKeyFrame* kf = static_cast(k); - - kf->_applyBaseKeyFrame(base); - } - } -} diff --git a/OgreMain/src/OgreArchive.cpp b/OgreMain/src/OgreArchive.cpp deleted file mode 100644 index 838a2b5b2bb..00000000000 --- a/OgreMain/src/OgreArchive.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" - -namespace Ogre { - //--------------------------------------------------------------------- - DataStreamPtr Archive::create(const String&) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, - "This archive does not support creation of files.", - "Archive::create"); - } - //--------------------------------------------------------------------- - void Archive::remove(const String&) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, - "This archive does not support removal of files.", - "Archive::remove"); - } - //--------------------------------------------------------------------- -} diff --git a/OgreMain/src/OgreArchiveManager.cpp b/OgreMain/src/OgreArchiveManager.cpp deleted file mode 100644 index 9a7bfdcafbc..00000000000 --- a/OgreMain/src/OgreArchiveManager.cpp +++ /dev/null @@ -1,132 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -namespace Ogre { - typedef void (*createFunc)( Archive**, const String& ); - - //----------------------------------------------------------------------- - template<> ArchiveManager* Singleton::msSingleton = 0; - ArchiveManager* ArchiveManager::getSingletonPtr(void) - { - return msSingleton; - } - ArchiveManager& ArchiveManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //----------------------------------------------------------------------- - ArchiveManager::ArchiveManager() - { - } - //----------------------------------------------------------------------- - Archive* ArchiveManager::load( const String& filename, const String& archiveType, bool readOnly) - { - ArchiveMap::iterator i = mArchives.find(filename); - Archive* pArch = 0; - - if (i == mArchives.end()) - { - // Search factories - ArchiveFactoryMap::iterator it = mArchFactories.find(archiveType); - if (it == mArchFactories.end()) - { - // Factory not found - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Cannot find an ArchiveFactory for type '" + archiveType + "'"); - } - - pArch = it->second->createInstance(filename, readOnly); - pArch->load(); - mArchives[filename] = pArch; - - } - else - { - pArch = i->second; - OgreAssert(pArch->isReadOnly() == readOnly, "existing archive location has different readOnly status"); - } - - return pArch; - } - //----------------------------------------------------------------------- - void ArchiveManager::unload(Archive* arch) - { - unload(arch->getName()); - } - //----------------------------------------------------------------------- - void ArchiveManager::unload(const String& filename) - { - ArchiveMap::iterator i = mArchives.find(filename); - - if (i != mArchives.end()) - { - i->second->unload(); - // Find factory to destroy. An archive factory created this file, it should still be there! - ArchiveFactoryMap::iterator fit = mArchFactories.find(i->second->getType()); - assert( fit != mArchFactories.end() && "Cannot find an ArchiveFactory " - "to deal with archive this type" ); - fit->second->destroyInstance(i->second); - mArchives.erase(i); - } - } - //----------------------------------------------------------------------- - ArchiveManager::ArchiveMapIterator ArchiveManager::getArchiveIterator(void) - { - return ArchiveMapIterator(mArchives.begin(), mArchives.end()); - } - //----------------------------------------------------------------------- - ArchiveManager::~ArchiveManager() - { - // Thanks to http://www.viva64.com/en/examples/V509/ for finding the error for us! - // (originally, it detected we were throwing using OGRE_EXCEPT in the destructor) - // We now raise an assert. - - // Unload & delete resources in turn - for (auto& a : mArchives) - { - // Unload - a.second->unload(); - // Find factory to destroy. An archive factory created this file, it should still be there! - ArchiveFactoryMap::iterator fit = mArchFactories.find(a.second->getType()); - assert( fit != mArchFactories.end() && "Cannot find an ArchiveFactory " - "to deal with archive this type" ); - fit->second->destroyInstance(a.second); - } - // Empty the list - mArchives.clear(); - } - //----------------------------------------------------------------------- - void ArchiveManager::addArchiveFactory(ArchiveFactory* factory) - { - mArchFactories.emplace(factory->getType(), factory); - LogManager::getSingleton().logMessage("ArchiveFactory for type '" + factory->getType() + "' registered"); - } - -} - diff --git a/OgreMain/src/OgreAutoParamDataSource.cpp b/OgreMain/src/OgreAutoParamDataSource.cpp deleted file mode 100644 index e35af3943a4..00000000000 --- a/OgreMain/src/OgreAutoParamDataSource.cpp +++ /dev/null @@ -1,1153 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreAutoParamDataSource.h" -#include "OgreRenderable.h" -#include "OgreRenderTarget.h" -#include "OgreControllerManager.h" -#include "OgreViewport.h" - -namespace Ogre { - //----------------------------------------------------------------------------- - AutoParamDataSource::AutoParamDataSource() - : mWorldMatrixCount(0), - mWorldMatrixArray(0), - mWorldMatrixDirty(true), - mViewMatrixDirty(true), - mProjMatrixDirty(true), - mWorldViewMatrixDirty(true), - mViewProjMatrixDirty(true), - mWorldViewProjMatrixDirty(true), - mInverseWorldMatrixDirty(true), - mInverseWorldViewMatrixDirty(true), - mInverseViewMatrixDirty(true), - mInverseTransposeWorldMatrixDirty(true), - mInverseTransposeWorldViewMatrixDirty(true), - mCameraPositionDirty(true), - mCameraPositionObjectSpaceDirty(true), - mAmbientLight(ColourValue::Black), - mPassNumber(0), - mSceneDepthRangeDirty(true), - mLodCameraPositionDirty(true), - mLodCameraPositionObjectSpaceDirty(true), - mCurrentRenderable(0), - mCurrentCamera(0), - mCameraRelativeRendering(false), - mCurrentLightList(0), - mCurrentRenderTarget(0), - mCurrentViewport(0), - mCurrentSceneManager(0), - mMainCamBoundsInfo(0), - mCurrentPass(0), - mDummyNode(NULL) - { - mBlankLight.setDiffuseColour(ColourValue::Black); - mBlankLight.setSpecularColour(ColourValue::Black); - mBlankLight.setAttenuation(0,1,0,0); - mDummyNode.attachObject(&mBlankLight); - for(size_t i = 0; i < OGRE_MAX_SIMULTANEOUS_LIGHTS; ++i) - { - mTextureViewProjMatrixDirty[i] = true; - mTextureWorldViewProjMatrixDirty[i] = true; - mSpotlightViewProjMatrixDirty[i] = true; - mSpotlightWorldViewProjMatrixDirty[i] = true; - mCurrentTextureProjector[i] = 0; - mShadowCamDepthRangesDirty[i] = false; - } - - } - //----------------------------------------------------------------------------- - const Camera* AutoParamDataSource::getCurrentCamera() const - { - return mCurrentCamera; - } - //----------------------------------------------------------------------------- - const Light& AutoParamDataSource::getLight(size_t index) const - { - // If outside light range, return a blank light to ensure zeroised for program - if (mCurrentLightList && index < mCurrentLightList->size()) - { - return *((*mCurrentLightList)[index]); - } - else - { - return mBlankLight; - } - } - //----------------------------------------------------------------------------- - void AutoParamDataSource::setCurrentRenderable(const Renderable* rend) - { - mCurrentRenderable = rend; - mWorldMatrixDirty = true; - mViewMatrixDirty = true; - mProjMatrixDirty = true; - mWorldViewMatrixDirty = true; - mViewProjMatrixDirty = true; - mWorldViewProjMatrixDirty = true; - mInverseWorldMatrixDirty = true; - mInverseViewMatrixDirty = true; - mInverseWorldViewMatrixDirty = true; - mInverseTransposeWorldMatrixDirty = true; - mInverseTransposeWorldViewMatrixDirty = true; - mCameraPositionObjectSpaceDirty = true; - mLodCameraPositionObjectSpaceDirty = true; - for(size_t i = 0; i < OGRE_MAX_SIMULTANEOUS_LIGHTS; ++i) - { - mTextureWorldViewProjMatrixDirty[i] = true; - mSpotlightWorldViewProjMatrixDirty[i] = true; - } - - } - //----------------------------------------------------------------------------- - void AutoParamDataSource::setCurrentCamera(const Camera* cam, bool useCameraRelative) - { - mCurrentCamera = cam; - mCameraRelativeRendering = useCameraRelative; - mCameraRelativePosition = cam->getDerivedPosition(); - mViewMatrixDirty = true; - mProjMatrixDirty = true; - mWorldViewMatrixDirty = true; - mViewProjMatrixDirty = true; - mWorldViewProjMatrixDirty = true; - mInverseViewMatrixDirty = true; - mInverseWorldViewMatrixDirty = true; - mInverseTransposeWorldViewMatrixDirty = true; - mCameraPositionObjectSpaceDirty = true; - mCameraPositionDirty = true; - mLodCameraPositionObjectSpaceDirty = true; - mLodCameraPositionDirty = true; - } - //----------------------------------------------------------------------------- - void AutoParamDataSource::setCurrentLightList(const LightList* ll) - { - mCurrentLightList = ll; - for(size_t i = 0; i < ll->size() && i < OGRE_MAX_SIMULTANEOUS_LIGHTS; ++i) - { - mSpotlightViewProjMatrixDirty[i] = true; - mSpotlightWorldViewProjMatrixDirty[i] = true; - } - - } - //--------------------------------------------------------------------- - float AutoParamDataSource::getLightNumber(size_t index) const - { - return static_cast(getLight(index)._getIndexInFrame()); - } - //----------------------------------------------------------------------------- - const ColourValue& AutoParamDataSource::getLightDiffuseColour(size_t index) const - { - return getLight(index).getDiffuseColour(); - } - //----------------------------------------------------------------------------- - const ColourValue& AutoParamDataSource::getLightSpecularColour(size_t index) const - { - return getLight(index).getSpecularColour(); - } - //----------------------------------------------------------------------------- - const ColourValue AutoParamDataSource::getLightDiffuseColourWithPower(size_t index) const - { - const Light& l = getLight(index); - ColourValue scaled(l.getDiffuseColour()); - Real power = l.getPowerScale(); - // scale, but not alpha - scaled.r *= power; - scaled.g *= power; - scaled.b *= power; - return scaled; - } - //----------------------------------------------------------------------------- - const ColourValue AutoParamDataSource::getLightSpecularColourWithPower(size_t index) const - { - const Light& l = getLight(index); - ColourValue scaled(l.getSpecularColour()); - Real power = l.getPowerScale(); - // scale, but not alpha - scaled.r *= power; - scaled.g *= power; - scaled.b *= power; - return scaled; - } - //----------------------------------------------------------------------------- - Vector3 AutoParamDataSource::getLightPosition(size_t index) const - { - return getLight(index).getDerivedPosition(true); - } - //----------------------------------------------------------------------------- - Vector4 AutoParamDataSource::getLightAs4DVector(size_t index) const - { - return getLight(index).getAs4DVector(true); - } - //----------------------------------------------------------------------------- - Vector3 AutoParamDataSource::getLightDirection(size_t index) const - { - return getLight(index).getDerivedDirection(); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getLightPowerScale(size_t index) const - { - return getLight(index).getPowerScale(); - } - //----------------------------------------------------------------------------- - Vector4f AutoParamDataSource::getLightAttenuation(size_t index) const - { - const Light& l = getLight(index); - if(l.getType() == Light::LT_RECTLIGHT) - { - auto rot = getViewMatrix().linear(); - return Vector4f(rot * l.getDerivedSourceHalfHeight(), 0.0); - } - // range, const, linear, quad - return l.getAttenuation(); - } - //----------------------------------------------------------------------------- - Vector4f AutoParamDataSource::getSpotlightParams(size_t index) const - { - // inner, outer, fallof, isSpot - const Light& l = getLight(index); - if (l.getType() == Light::LT_SPOTLIGHT) - { - return Vector4f(Math::Cos(l.getSpotlightInnerAngle().valueRadians() * 0.5f), - Math::Cos(l.getSpotlightOuterAngle().valueRadians() * 0.5f), - l.getSpotlightFalloff(), - 1.0); - } - else if(l.getType() == Light::LT_RECTLIGHT) - { - auto rot = getViewMatrix().linear(); - return Vector4f(rot * l.getDerivedSourceHalfWidth(), 2.0); - } - else - { - // Use safe values which result in no change to point & dir light calcs - // The spot factor applied to the usual lighting calc is - // pow((dot(spotDir, lightDir) - y) / (x - y), z) - // Therefore if we set z to 0.0f then the factor will always be 1 - // since pow(anything, 0) == 1 - // However we also need to ensure we don't overflow because of the division - // therefore set x = 1 and y = 0 so divisor doesn't change scale - return Vector4f(1.0, 0.0, 0.0, 0.0); // since the main op is pow(.., vec4.z), this will result in 1.0 - } - } - //----------------------------------------------------------------------------- - void AutoParamDataSource::setMainCamBoundsInfo(VisibleObjectsBoundsInfo* info) - { - mMainCamBoundsInfo = info; - mSceneDepthRangeDirty = true; - } - //----------------------------------------------------------------------------- - void AutoParamDataSource::setCurrentSceneManager(const SceneManager* sm) - { - mCurrentSceneManager = sm; - } - //----------------------------------------------------------------------------- - void AutoParamDataSource::setWorldMatrices(const Affine3* m, size_t count) - { - mWorldMatrixArray = m; - mWorldMatrixCount = count; - mWorldMatrixDirty = false; - } - //----------------------------------------------------------------------------- - const Affine3& AutoParamDataSource::getWorldMatrix(void) const - { - if (mWorldMatrixDirty) - { - mWorldMatrixArray = mWorldMatrix; - mCurrentRenderable->getWorldTransforms(reinterpret_cast(mWorldMatrix)); - mWorldMatrixCount = mCurrentRenderable->getNumWorldTransforms(); - if (mCameraRelativeRendering && !mCurrentRenderable->getUseIdentityView()) - { - size_t worldMatrixCount = MeshManager::getBonesUseObjectSpace() ? 1 : mWorldMatrixCount; - for (size_t i = 0; i < worldMatrixCount; ++i) - { - mWorldMatrix[i].setTrans(mWorldMatrix[i].getTrans() - mCameraRelativePosition); - } - } - mWorldMatrixDirty = false; - } - return mWorldMatrixArray[0]; - } - //----------------------------------------------------------------------------- - size_t AutoParamDataSource::getBoneMatrixCount(void) const - { - // trigger derivation - getWorldMatrix(); - return mWorldMatrixCount == 1 ? 1 : mWorldMatrixCount - int(MeshManager::getBonesUseObjectSpace()); - } - //----------------------------------------------------------------------------- - const Affine3* AutoParamDataSource::getBoneMatrixArray(void) const - { - // trigger derivation - getWorldMatrix(); - return mWorldMatrixArray + int(MeshManager::getBonesUseObjectSpace()); - } - //----------------------------------------------------------------------------- - const Affine3& AutoParamDataSource::getViewMatrix(void) const - { - if (mViewMatrixDirty) - { - if (mCurrentRenderable && mCurrentRenderable->getUseIdentityView()) - mViewMatrix = Affine3::IDENTITY; - else - { - mViewMatrix = mCurrentCamera->getViewMatrix(true); - if (mCameraRelativeRendering) - { - mViewMatrix.setTrans(Vector3::ZERO); - } - - } - mViewMatrixDirty = false; - } - return mViewMatrix; - } - //----------------------------------------------------------------------------- - const Matrix4& AutoParamDataSource::getViewProjectionMatrix(void) const - { - if (mViewProjMatrixDirty) - { - mViewProjMatrix = getProjectionMatrix() * getViewMatrix(); - mViewProjMatrixDirty = false; - } - return mViewProjMatrix; - } - //----------------------------------------------------------------------------- - const Matrix4& AutoParamDataSource::getProjectionMatrix(void) const - { - if (mProjMatrixDirty) - { - // NB use API-independent projection matrix since GPU programs - // bypass the API-specific handedness and use right-handed coords - if (mCurrentRenderable && mCurrentRenderable->getUseIdentityProjection()) - { - // Use identity projection matrix, still need to take RS depth into account. - RenderSystem* rs = Root::getSingleton().getRenderSystem(); - rs->_convertProjectionMatrix(Matrix4::IDENTITY, mProjectionMatrix, true); - } - else - { - mProjectionMatrix = mCurrentCamera->getProjectionMatrixWithRSDepth(); - } - if (mCurrentRenderTarget && mCurrentRenderTarget->requiresTextureFlipping()) - { - // Because we're not using setProjectionMatrix, this needs to be done here - // Invert transformed y - mProjectionMatrix[1][0] = -mProjectionMatrix[1][0]; - mProjectionMatrix[1][1] = -mProjectionMatrix[1][1]; - mProjectionMatrix[1][2] = -mProjectionMatrix[1][2]; - mProjectionMatrix[1][3] = -mProjectionMatrix[1][3]; - } - mProjMatrixDirty = false; - } - return mProjectionMatrix; - } - //----------------------------------------------------------------------------- - const Affine3& AutoParamDataSource::getWorldViewMatrix(void) const - { - if (mWorldViewMatrixDirty) - { - mWorldViewMatrix = getViewMatrix() * getWorldMatrix(); - mWorldViewMatrixDirty = false; - } - return mWorldViewMatrix; - } - //----------------------------------------------------------------------------- - const Matrix4& AutoParamDataSource::getWorldViewProjMatrix(void) const - { - if (mWorldViewProjMatrixDirty) - { - mWorldViewProjMatrix = getProjectionMatrix() * getWorldViewMatrix(); - mWorldViewProjMatrixDirty = false; - } - return mWorldViewProjMatrix; - } - //----------------------------------------------------------------------------- - const Affine3& AutoParamDataSource::getInverseWorldMatrix(void) const - { - if (mInverseWorldMatrixDirty) - { - mInverseWorldMatrix = getWorldMatrix().inverse(); - mInverseWorldMatrixDirty = false; - } - return mInverseWorldMatrix; - } - //----------------------------------------------------------------------------- - const Affine3& AutoParamDataSource::getInverseWorldViewMatrix(void) const - { - if (mInverseWorldViewMatrixDirty) - { - mInverseWorldViewMatrix = getWorldViewMatrix().inverse(); - mInverseWorldViewMatrixDirty = false; - } - return mInverseWorldViewMatrix; - } - //----------------------------------------------------------------------------- - const Affine3& AutoParamDataSource::getInverseViewMatrix(void) const - { - if (mInverseViewMatrixDirty) - { - mInverseViewMatrix = getViewMatrix().inverse(); - mInverseViewMatrixDirty = false; - } - return mInverseViewMatrix; - } - //----------------------------------------------------------------------------- - const Matrix4& AutoParamDataSource::getInverseTransposeWorldMatrix(void) const - { - if (mInverseTransposeWorldMatrixDirty) - { - mInverseTransposeWorldMatrix = getInverseWorldMatrix().transpose(); - mInverseTransposeWorldMatrixDirty = false; - } - return mInverseTransposeWorldMatrix; - } - //----------------------------------------------------------------------------- - const Matrix4& AutoParamDataSource::getInverseTransposeWorldViewMatrix(void) const - { - if (mInverseTransposeWorldViewMatrixDirty) - { - mInverseTransposeWorldViewMatrix = getInverseWorldViewMatrix().transpose(); - mInverseTransposeWorldViewMatrixDirty = false; - } - return mInverseTransposeWorldViewMatrix; - } - //----------------------------------------------------------------------------- - const Vector4& AutoParamDataSource::getCameraPosition(void) const - { - if(mCameraPositionDirty) - { - Vector3 vec3 = mCurrentCamera->getDerivedPosition(); - if (mCameraRelativeRendering) - { - vec3 -= mCameraRelativePosition; - } - mCameraPosition[0] = vec3[0]; - mCameraPosition[1] = vec3[1]; - mCameraPosition[2] = vec3[2]; - mCameraPosition[3] = 1.0; - mCameraPositionDirty = false; - } - return mCameraPosition; - } - //----------------------------------------------------------------------------- - const Vector4& AutoParamDataSource::getCameraPositionObjectSpace(void) const - { - if (mCameraPositionObjectSpaceDirty) - { - if (mCameraRelativeRendering) - { - mCameraPositionObjectSpace = Vector4(getInverseWorldMatrix() * Vector3::ZERO); - } - else - { - mCameraPositionObjectSpace = - Vector4(getInverseWorldMatrix() * mCurrentCamera->getDerivedPosition()); - } - mCameraPositionObjectSpaceDirty = false; - } - return mCameraPositionObjectSpace; - } - //----------------------------------------------------------------------------- - const Vector4 AutoParamDataSource::getCameraRelativePosition (void) const - { - return Ogre::Vector4 (mCameraRelativePosition.x, mCameraRelativePosition.y, mCameraRelativePosition.z, 1); - } - //----------------------------------------------------------------------------- - const Vector4& AutoParamDataSource::getLodCameraPosition(void) const - { - if(mLodCameraPositionDirty) - { - Vector3 vec3 = mCurrentCamera->getLodCamera()->getDerivedPosition(); - if (mCameraRelativeRendering) - { - vec3 -= mCameraRelativePosition; - } - mLodCameraPosition[0] = vec3[0]; - mLodCameraPosition[1] = vec3[1]; - mLodCameraPosition[2] = vec3[2]; - mLodCameraPosition[3] = 1.0; - mLodCameraPositionDirty = false; - } - return mLodCameraPosition; - } - //----------------------------------------------------------------------------- - const Vector4& AutoParamDataSource::getLodCameraPositionObjectSpace(void) const - { - if (mLodCameraPositionObjectSpaceDirty) - { - if (mCameraRelativeRendering) - { - mLodCameraPositionObjectSpace = - Vector4(getInverseWorldMatrix() * - (mCurrentCamera->getLodCamera()->getDerivedPosition() - - mCameraRelativePosition)); - } - else - { - mLodCameraPositionObjectSpace = - Vector4(getInverseWorldMatrix() * - (mCurrentCamera->getLodCamera()->getDerivedPosition())); - } - mLodCameraPositionObjectSpaceDirty = false; - } - return mLodCameraPositionObjectSpace; - } - //----------------------------------------------------------------------------- - void AutoParamDataSource::setAmbientLightColour(const ColourValue& ambient) - { - mAmbientLight = ambient; - } - //--------------------------------------------------------------------- - float AutoParamDataSource::getLightCount() const - { - return static_cast(mCurrentLightList->size()); - } - //--------------------------------------------------------------------- - float AutoParamDataSource::getLightCastsShadows(size_t index) const - { - return getLight(index).getCastShadows() ? 1.0f : 0.0f; - } - //----------------------------------------------------------------------------- - const ColourValue& AutoParamDataSource::getAmbientLightColour(void) const - { - return mAmbientLight; - - } - //----------------------------------------------------------------------------- - void AutoParamDataSource::setCurrentPass(const Pass* pass) - { - mCurrentPass = pass; - } - //----------------------------------------------------------------------------- - const Pass* AutoParamDataSource::getCurrentPass(void) const - { - return mCurrentPass; - } - //----------------------------------------------------------------------------- - Vector4f AutoParamDataSource::getTextureSize(size_t index) const - { - Vector4f size = Vector4f(1,1,1,1); - - if (index < mCurrentPass->getNumTextureUnitStates()) - { - const TexturePtr& tex = mCurrentPass->getTextureUnitState( - static_cast(index))->_getTexturePtr(); - if (tex) - { - size[0] = static_cast(tex->getWidth()); - size[1] = static_cast(tex->getHeight()); - size[2] = static_cast(tex->getDepth()); - size[3] = static_cast(tex->getNumMipmaps()); - } - } - - return size; - } - //----------------------------------------------------------------------------- - Vector4f AutoParamDataSource::getInverseTextureSize(size_t index) const - { - Vector4f size = getTextureSize(index); - return 1 / size; - } - //----------------------------------------------------------------------------- - Vector4f AutoParamDataSource::getPackedTextureSize(size_t index) const - { - Vector4f size = getTextureSize(index); - return Vector4f(size[0], size[1], 1 / size[0], 1 / size[1]); - } - //----------------------------------------------------------------------------- - const ColourValue& AutoParamDataSource::getSurfaceAmbientColour(void) const - { - return mCurrentPass->getAmbient(); - } - //----------------------------------------------------------------------------- - const ColourValue& AutoParamDataSource::getSurfaceDiffuseColour(void) const - { - return mCurrentPass->getDiffuse(); - } - //----------------------------------------------------------------------------- - const ColourValue& AutoParamDataSource::getSurfaceSpecularColour(void) const - { - return mCurrentPass->getSpecular(); - } - //----------------------------------------------------------------------------- - const ColourValue& AutoParamDataSource::getSurfaceEmissiveColour(void) const - { - return mCurrentPass->getSelfIllumination(); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getSurfaceShininess(void) const - { - return mCurrentPass->getShininess(); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getSurfaceAlphaRejectionValue(void) const - { - return static_cast(static_cast(mCurrentPass->getAlphaRejectValue())) / 255.0f; - } - //----------------------------------------------------------------------------- - ColourValue AutoParamDataSource::getDerivedAmbientLightColour(void) const - { - auto result = getAmbientLightColour() * getSurfaceAmbientColour(); - result.a = getSurfaceDiffuseColour().a; - return result; - } - //----------------------------------------------------------------------------- - ColourValue AutoParamDataSource::getDerivedSceneColour(void) const - { - ColourValue result = getDerivedAmbientLightColour() + getSurfaceEmissiveColour(); - result.a = getSurfaceDiffuseColour().a; - return result; - } - //----------------------------------------------------------------------------- - void AutoParamDataSource::setFog(FogMode mode, const ColourValue& colour, - Real expDensity, Real linearStart, Real linearEnd) - { - (void)mode; // ignored - mFogColour = colour; - mFogParams[0] = expDensity; - mFogParams[1] = linearStart; - mFogParams[2] = linearEnd; - mFogParams[3] = linearEnd != linearStart ? 1 / (linearEnd - linearStart) : 0; - } - //----------------------------------------------------------------------------- - const ColourValue& AutoParamDataSource::getFogColour(void) const - { - return mFogColour; - } - //----------------------------------------------------------------------------- - const Vector4f& AutoParamDataSource::getFogParams(void) const - { - return mFogParams; - } - - void AutoParamDataSource::setPointParameters(bool attenuation, const Vector4f& params) - { - mPointParams = params; - if(attenuation) - mPointParams[0] *= getViewportHeight(); - } - - const Vector4f& AutoParamDataSource::getPointParams() const - { - return mPointParams; - } - //----------------------------------------------------------------------------- - void AutoParamDataSource::setTextureProjector(const Frustum* frust, size_t index = 0) - { - if (index < OGRE_MAX_SIMULTANEOUS_LIGHTS) - { - mCurrentTextureProjector[index] = frust; - mTextureViewProjMatrixDirty[index] = true; - mTextureWorldViewProjMatrixDirty[index] = true; - mShadowCamDepthRangesDirty[index] = true; - } - - } - //----------------------------------------------------------------------------- - const Matrix4& AutoParamDataSource::getTextureViewProjMatrix(size_t index) const - { - if (index < OGRE_MAX_SIMULTANEOUS_LIGHTS && mCurrentTextureProjector[index]) - { - if (mTextureViewProjMatrixDirty[index]) - { - if (mCameraRelativeRendering) - { - // World positions are now going to be relative to the camera position - // so we need to alter the projector view matrix to compensate - Matrix4 viewMatrix; - mCurrentTextureProjector[index]->calcViewMatrixRelative( - mCurrentCamera->getDerivedPosition(), viewMatrix); - mTextureViewProjMatrix[index] = - Matrix4::CLIPSPACE2DTOIMAGESPACE * - mCurrentTextureProjector[index]->getProjectionMatrixWithRSDepth() * - viewMatrix; - } - else - { - mTextureViewProjMatrix[index] = - Matrix4::CLIPSPACE2DTOIMAGESPACE * - mCurrentTextureProjector[index]->getProjectionMatrixWithRSDepth() * - mCurrentTextureProjector[index]->getViewMatrix(); - } - mTextureViewProjMatrixDirty[index] = false; - } - return mTextureViewProjMatrix[index]; - } - else - return Matrix4::IDENTITY; - } - //----------------------------------------------------------------------------- - const Matrix4& AutoParamDataSource::getTextureWorldViewProjMatrix(size_t index) const - { - if (index < OGRE_MAX_SIMULTANEOUS_LIGHTS && mCurrentTextureProjector[index]) - { - if (mTextureWorldViewProjMatrixDirty[index]) - { - mTextureWorldViewProjMatrix[index] = - getTextureViewProjMatrix(index) * getWorldMatrix(); - mTextureWorldViewProjMatrixDirty[index] = false; - } - return mTextureWorldViewProjMatrix[index]; - } - else - return Matrix4::IDENTITY; - } - //----------------------------------------------------------------------------- - const Matrix4& AutoParamDataSource::getSpotlightViewProjMatrix(size_t index) const - { - if (index < OGRE_MAX_SIMULTANEOUS_LIGHTS) - { - const Light& l = getLight(index); - - if (&l != &mBlankLight && - l.getType() == Light::LT_SPOTLIGHT && - mSpotlightViewProjMatrixDirty[index]) - { - Frustum frust; - SceneNode dummyNode(0); - dummyNode.attachObject(&frust); - - frust.setProjectionType(PT_PERSPECTIVE); - frust.setFOVy(l.getSpotlightOuterAngle()); - frust.setAspectRatio(1.0f); - // set near clip the same as main camera, since they are likely - // to both reflect the nature of the scene - frust.setNearClipDistance(mCurrentCamera->getNearClipDistance()); - // Calculate position, which same as spotlight position, in camera-relative coords if required - dummyNode.setPosition(l.getDerivedPosition(true)); - // Calculate direction, which same as spotlight direction - Vector3 dir = - l.getDerivedDirection(); // backwards since point down -z - dir.normalise(); - Vector3 up = Vector3::UNIT_Y; - // Check it's not coincident with dir - if (Math::Abs(up.dotProduct(dir)) >= 1.0f) - { - // Use camera up - up = Vector3::UNIT_Z; - } - dummyNode.setOrientation(Math::lookRotation(dir, up)); - - // The view matrix here already includes camera-relative changes if necessary - // since they are built into the frustum position - mSpotlightViewProjMatrix[index] = - Matrix4::CLIPSPACE2DTOIMAGESPACE * - frust.getProjectionMatrixWithRSDepth() * - frust.getViewMatrix(); - - mSpotlightViewProjMatrixDirty[index] = false; - } - return mSpotlightViewProjMatrix[index]; - } - else - return Matrix4::IDENTITY; - } - //----------------------------------------------------------------------------- - const Matrix4& AutoParamDataSource::getSpotlightWorldViewProjMatrix(size_t index) const - { - if (index < OGRE_MAX_SIMULTANEOUS_LIGHTS) - { - const Light& l = getLight(index); - - if (&l != &mBlankLight && - l.getType() == Light::LT_SPOTLIGHT && - mSpotlightWorldViewProjMatrixDirty[index]) - { - mSpotlightWorldViewProjMatrix[index] = - getSpotlightViewProjMatrix(index) * getWorldMatrix(); - mSpotlightWorldViewProjMatrixDirty[index] = false; - } - return mSpotlightWorldViewProjMatrix[index]; - } - else - return Matrix4::IDENTITY; - } -//----------------------------------------------------------------------------- - const Matrix4& AutoParamDataSource::getTextureTransformMatrix(size_t index) const - { - // make sure the current pass is set - assert(mCurrentPass && "current pass is NULL!"); - // check if there is a texture unit with the given index in the current pass - if(index < mCurrentPass->getNumTextureUnitStates()) - { - // texture unit existent, return its currently set transform - return mCurrentPass->getTextureUnitState(static_cast(index))->getTextureTransform(); - } - else - { - // no such texture unit, return unity - return Matrix4::IDENTITY; - } - } - //----------------------------------------------------------------------------- - void AutoParamDataSource::setCurrentRenderTarget(const RenderTarget* target) - { - mCurrentRenderTarget = target; - } - //----------------------------------------------------------------------------- - const RenderTarget* AutoParamDataSource::getCurrentRenderTarget(void) const - { - return mCurrentRenderTarget; - } - //----------------------------------------------------------------------------- - void AutoParamDataSource::setCurrentViewport(const Viewport* viewport) - { - mCurrentViewport = viewport; - } - //----------------------------------------------------------------------------- - void AutoParamDataSource::setShadowDirLightExtrusionDistance(Real dist) - { - mDirLightExtrusionDistance = dist; - } - //----------------------------------------------------------------------------- - void AutoParamDataSource::setShadowPointLightExtrusionDistance(Real dist) - { - mPointLightExtrusionDistance = dist; - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getShadowExtrusionDistance(void) const - { - const Light& l = getLight(0); // only ever applies to one light at once - return (l.getType() == Light::LT_DIRECTIONAL) ? - mDirLightExtrusionDistance : mPointLightExtrusionDistance; - } - //----------------------------------------------------------------------------- - const Renderable* AutoParamDataSource::getCurrentRenderable(void) const - { - return mCurrentRenderable; - } - //----------------------------------------------------------------------------- - Matrix4 AutoParamDataSource::getInverseViewProjMatrix(void) const - { - return this->getViewProjectionMatrix().inverse(); - } - //----------------------------------------------------------------------------- - Matrix4 AutoParamDataSource::getInverseTransposeViewProjMatrix(void) const - { - return this->getInverseViewProjMatrix().transpose(); - } - //----------------------------------------------------------------------------- - Matrix4 AutoParamDataSource::getTransposeViewProjMatrix(void) const - { - return this->getViewProjectionMatrix().transpose(); - } - //----------------------------------------------------------------------------- - Matrix4 AutoParamDataSource::getTransposeViewMatrix(void) const - { - return this->getViewMatrix().transpose(); - } - //----------------------------------------------------------------------------- - Matrix4 AutoParamDataSource::getInverseTransposeViewMatrix(void) const - { - return this->getInverseViewMatrix().transpose(); - } - //----------------------------------------------------------------------------- - Matrix4 AutoParamDataSource::getTransposeProjectionMatrix(void) const - { - return this->getProjectionMatrix().transpose(); - } - //----------------------------------------------------------------------------- - Matrix4 AutoParamDataSource::getInverseProjectionMatrix(void) const - { - return this->getProjectionMatrix().inverse(); - } - //----------------------------------------------------------------------------- - Matrix4 AutoParamDataSource::getInverseTransposeProjectionMatrix(void) const - { - return this->getInverseProjectionMatrix().transpose(); - } - //----------------------------------------------------------------------------- - Matrix4 AutoParamDataSource::getTransposeWorldViewProjMatrix(void) const - { - return this->getWorldViewProjMatrix().transpose(); - } - //----------------------------------------------------------------------------- - Matrix4 AutoParamDataSource::getInverseWorldViewProjMatrix(void) const - { - return this->getWorldViewProjMatrix().inverse(); - } - //----------------------------------------------------------------------------- - Matrix4 AutoParamDataSource::getInverseTransposeWorldViewProjMatrix(void) const - { - return this->getInverseWorldViewProjMatrix().transpose(); - } - //----------------------------------------------------------------------------- - Matrix4 AutoParamDataSource::getTransposeWorldViewMatrix(void) const - { - return this->getWorldViewMatrix().transpose(); - } - //----------------------------------------------------------------------------- - Matrix4 AutoParamDataSource::getTransposeWorldMatrix(void) const - { - return this->getWorldMatrix().transpose(); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getTime(void) const - { - return ControllerManager::getSingleton().getElapsedTime(); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getTime_0_X(Real x) const - { - return std::fmod(this->getTime(), x); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getCosTime_0_X(Real x) const - { - return std::cos(this->getTime_0_X(x)); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getSinTime_0_X(Real x) const - { - return std::sin(this->getTime_0_X(x)); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getTanTime_0_X(Real x) const - { - return std::tan(this->getTime_0_X(x)); - } - //----------------------------------------------------------------------------- - Vector4f AutoParamDataSource::getTime_0_X_packed(Real x) const - { - float t = this->getTime_0_X(x); - return Vector4f(t, std::sin(t), std::cos(t), std::tan(t)); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getTime_0_1(Real x) const - { - return this->getTime_0_X(x)/x; - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getCosTime_0_1(Real x) const - { - return std::cos(this->getTime_0_1(x)); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getSinTime_0_1(Real x) const - { - return std::sin(this->getTime_0_1(x)); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getTanTime_0_1(Real x) const - { - return std::tan(this->getTime_0_1(x)); - } - //----------------------------------------------------------------------------- - Vector4f AutoParamDataSource::getTime_0_1_packed(Real x) const - { - float t = this->getTime_0_1(x); - return Vector4f(t, std::sin(t), std::cos(t), std::tan(t)); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getTime_0_2Pi(Real x) const - { - return this->getTime_0_X(x)/x*2*Math::PI; - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getCosTime_0_2Pi(Real x) const - { - return std::cos(this->getTime_0_2Pi(x)); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getSinTime_0_2Pi(Real x) const - { - return std::sin(this->getTime_0_2Pi(x)); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getTanTime_0_2Pi(Real x) const - { - return std::tan(this->getTime_0_2Pi(x)); - } - //----------------------------------------------------------------------------- - Vector4f AutoParamDataSource::getTime_0_2Pi_packed(Real x) const - { - float t = this->getTime_0_2Pi(x); - return Vector4f(t, std::sin(t), std::cos(t), std::tan(t)); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getFrameTime(void) const - { - return ControllerManager::getSingleton().getFrameTimeSource()->getValue(); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getFPS() const - { - return mCurrentRenderTarget->getStatistics().lastFPS; - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getViewportWidth() const - { - return static_cast(mCurrentViewport->getActualWidth()); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getViewportHeight() const - { - return static_cast(mCurrentViewport->getActualHeight()); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getInverseViewportWidth() const - { - return 1.0f/mCurrentViewport->getActualWidth(); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getInverseViewportHeight() const - { - return 1.0f/mCurrentViewport->getActualHeight(); - } - //----------------------------------------------------------------------------- - Vector3 AutoParamDataSource::getViewDirection() const - { - return mCurrentCamera->getDerivedDirection(); - } - //----------------------------------------------------------------------------- - Vector3 AutoParamDataSource::getViewSideVector() const - { - return mCurrentCamera->getDerivedRight(); - } - //----------------------------------------------------------------------------- - Vector3 AutoParamDataSource::getViewUpVector() const - { - return mCurrentCamera->getDerivedUp(); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getFOV() const - { - return mCurrentCamera->getFOVy().valueRadians(); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getNearClipDistance() const - { - return mCurrentCamera->getNearClipDistance(); - } - //----------------------------------------------------------------------------- - Real AutoParamDataSource::getFarClipDistance() const - { - return mCurrentCamera->getFarClipDistance(); - } - //----------------------------------------------------------------------------- - int AutoParamDataSource::getPassNumber(void) const - { - return mPassNumber; - } - //----------------------------------------------------------------------------- - void AutoParamDataSource::setPassNumber(const int passNumber) - { - mPassNumber = passNumber; - } - //----------------------------------------------------------------------------- - void AutoParamDataSource::incPassNumber(void) - { - ++mPassNumber; - } - int AutoParamDataSource::getMaterialLodIndex() const - { - return mCurrentRenderable->_getMaterialLodIndex(); - } - //----------------------------------------------------------------------------- - const Vector4& AutoParamDataSource::getSceneDepthRange() const - { - static Vector4 dummy(0, 100000, 100000, 1.f/100000); - - if (mSceneDepthRangeDirty) - { - // calculate depth information - Real depthRange = mMainCamBoundsInfo->maxDistanceInFrustum - mMainCamBoundsInfo->minDistanceInFrustum; - if (depthRange > std::numeric_limits::epsilon()) - { - mSceneDepthRange = Vector4( - mMainCamBoundsInfo->minDistanceInFrustum, - mMainCamBoundsInfo->maxDistanceInFrustum, - depthRange, - 1.0f / depthRange); - } - else - { - mSceneDepthRange = dummy; - } - mSceneDepthRangeDirty = false; - } - - return mSceneDepthRange; - - } - //----------------------------------------------------------------------------- - const Vector4& AutoParamDataSource::getShadowSceneDepthRange(size_t index) const - { - static Vector4 dummy(0, 100000, 100000, 1.0f/100000); - - if (!mCurrentSceneManager->isShadowTechniqueTextureBased()) - return dummy; - - if (index < OGRE_MAX_SIMULTANEOUS_LIGHTS) - { - if (mShadowCamDepthRangesDirty[index] && mCurrentTextureProjector[index]) - { - const VisibleObjectsBoundsInfo& info = - mCurrentSceneManager->getVisibleObjectsBoundsInfo( - (const Camera*)mCurrentTextureProjector[index]); - - Real depthRange = info.maxDistanceInFrustum - info.minDistanceInFrustum; - if (depthRange > std::numeric_limits::epsilon()) - { - mShadowCamDepthRanges[index] = Vector4( - info.minDistanceInFrustum, - info.maxDistanceInFrustum, - depthRange, - 1.0f / depthRange); - } - else - { - mShadowCamDepthRanges[index] = dummy; - } - - mShadowCamDepthRangesDirty[index] = false; - } - return mShadowCamDepthRanges[index]; - } - else - return dummy; - } - //--------------------------------------------------------------------- - const ColourValue& AutoParamDataSource::getShadowColour() const - { - return mCurrentSceneManager->getShadowColour(); - } - //------------------------------------------------------------------------- - void AutoParamDataSource::updateLightCustomGpuParameter(const GpuProgramParameters::AutoConstantEntry& constantEntry, GpuProgramParameters *params) const - { - uint16 lightIndex = static_cast(constantEntry.data & 0xFFFF), - paramIndex = static_cast((constantEntry.data >> 16) & 0xFFFF); - if(mCurrentLightList && lightIndex < mCurrentLightList->size()) - { - const Light &light = getLight(lightIndex); - light._updateCustomGpuParameter(paramIndex, constantEntry, params); - } - } - -} - diff --git a/OgreMain/src/OgreAxisAlignedBox.cpp b/OgreMain/src/OgreAxisAlignedBox.cpp deleted file mode 100644 index 619bb42ac1a..00000000000 --- a/OgreMain/src/OgreAxisAlignedBox.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -namespace Ogre -{ - const AxisAlignedBox AxisAlignedBox::BOX_NULL; - const AxisAlignedBox AxisAlignedBox::BOX_INFINITE(AxisAlignedBox::EXTENT_INFINITE); -} - diff --git a/OgreMain/src/OgreBillboard.cpp b/OgreMain/src/OgreBillboard.cpp deleted file mode 100644 index eddf562c0f3..00000000000 --- a/OgreMain/src/OgreBillboard.cpp +++ /dev/null @@ -1,81 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreBillboard.h" -#include "OgreBillboardSet.h" - -namespace Ogre { - - //----------------------------------------------------------------------- - Billboard::Billboard(): - mOwnDimensions(false), - mUseTexcoordRect(false), - mTexcoordIndex(0), - mPosition(Vector3::ZERO), - mDirection(Vector3::ZERO), - mColour(0xFFFFFFFF), - mRotation(0) - { - } - //----------------------------------------------------------------------- - Billboard::~Billboard() - { - } - //----------------------------------------------------------------------- - Billboard::Billboard(const Vector3& position, BillboardSet* owner, const ColourValue& colour) - : mOwnDimensions(false) - , mUseTexcoordRect(false) - , mTexcoordIndex(0) - , mPosition(position) - , mDirection(Vector3::ZERO) - , mColour(colour.getAsBYTE()) - , mRotation(0) - { - } - //----------------------------------------------------------------------- - void Billboard::setDimensions(float width, float height) - { - mOwnDimensions = true; - mWidth = width; - mHeight = height; - } - //----------------------------------------------------------------------- - void Billboard::setTexcoordIndex(uint16 texcoordIndex) - { - mTexcoordIndex = texcoordIndex; - mUseTexcoordRect = false; - } - //----------------------------------------------------------------------- - void Billboard::setTexcoordRect(const FloatRect& texcoordRect) - { - mTexcoordRect = texcoordRect; - mUseTexcoordRect = true; - } -} - diff --git a/OgreMain/src/OgreBillboardChain.cpp b/OgreMain/src/OgreBillboardChain.cpp deleted file mode 100644 index b8024fb79a6..00000000000 --- a/OgreMain/src/OgreBillboardChain.cpp +++ /dev/null @@ -1,755 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -// Thanks to Vincent Cantin (karmaGfa) for the original implementation of this -// class, although it has now been mostly rewritten - -#include "OgreStableHeaders.h" -#include "OgreBillboardChain.h" -#include "OgreViewport.h" - -#include -#include - -namespace Ogre { - const size_t BillboardChain::SEGMENT_EMPTY = std::numeric_limits::max(); - //----------------------------------------------------------------------- - BillboardChain::Element::Element(const Vector3 &_position, - float _width, - float _texCoord, - const ColourValue &_colour, - const Quaternion &_orientation) : - position(_position), - width(_width), - texCoord(_texCoord), - colour(_colour), - orientation(_orientation) - { - } - //----------------------------------------------------------------------- - BillboardChain::BillboardChain(const String& name, size_t maxElements, - size_t numberOfChains, bool useTextureCoords, bool useColours, bool dynamic) - :MovableObject(name), - mMaxElementsPerChain(maxElements), - mChainCount(numberOfChains), - mUseTexCoords(useTextureCoords), - mUseVertexColour(useColours), - mVertexDeclDirty(true), - mBuffersNeedRecreating(true), - mBoundsDirty(true), - mIndexContentDirty(true), - mVertexContentDirty(true), - mRadius(0.0f), - mTexCoordDir(TCD_U), - mFaceCamera(true), - mNormalBase(Vector3::UNIT_X), - mVertexCameraUsed(0) - { - mVertexData = std::make_unique(); - mIndexData = std::make_unique(); - - mOtherTexCoordRange[0] = 0.0f; - mOtherTexCoordRange[1] = 1.0f; - - setupChainContainers(); - - mVertexData->vertexStart = 0; - // index data set up later - // set basic white material - mMaterial = MaterialManager::getSingleton().getDefaultMaterial(false); - mMaterial->load(); - } - - BillboardChain::~BillboardChain() = default; // ensure unique_ptr destructors are in cpp - - //----------------------------------------------------------------------- - void BillboardChain::setupChainContainers(void) - { - // Allocate enough space for everything - mChainElementList.resize(mChainCount * mMaxElementsPerChain); - mVertexData->vertexCount = mChainElementList.size() * 2; - - // Configure chains - mChainSegmentList.resize(mChainCount); - for (size_t i = 0; i < mChainCount; ++i) - { - ChainSegment& seg = mChainSegmentList[i]; - seg.start = i * mMaxElementsPerChain; - seg.tail = seg.head = SEGMENT_EMPTY; - - } - - - } - //----------------------------------------------------------------------- - void BillboardChain::setupVertexDeclaration(void) - { - if (mVertexDeclDirty) - { - VertexDeclaration* decl = mVertexData->vertexDeclaration; - decl->removeAllElements(); - - size_t offset = 0; - // Add a description for the buffer of the positions of the vertices - offset += decl->addElement(0, offset, VET_FLOAT3, VES_POSITION).getSize(); - - if (mUseVertexColour) - { - offset += decl->addElement(0, offset, VET_UBYTE4_NORM, VES_DIFFUSE).getSize(); - } - - if (mUseTexCoords) - { - decl->addElement(0, offset, VET_FLOAT2, VES_TEXTURE_COORDINATES); - } - - if (!mUseTexCoords && !mUseVertexColour) - { - LogManager::getSingleton().logError( - "BillboardChain '" + mName + "' is using neither " - "texture coordinates nor vertex colours; it will not be " - "visible on some rendering APIs so you should change this " - "so you use one or the other."); - } - mVertexDeclDirty = false; - } - } - //----------------------------------------------------------------------- - void BillboardChain::setupBuffers(void) - { - setupVertexDeclaration(); - if (mBuffersNeedRecreating) - { - // Create the vertex buffer (always dynamic due to the camera adjust) - HardwareVertexBufferSharedPtr pBuffer = - HardwareBufferManager::getSingleton().createVertexBuffer( - mVertexData->vertexDeclaration->getVertexSize(0), - mVertexData->vertexCount, - HBU_CPU_TO_GPU); - - // (re)Bind the buffer - // Any existing buffer will lose its reference count and be destroyed - mVertexData->vertexBufferBinding->setBinding(0, pBuffer); - - mIndexData->indexBuffer = - HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, - mChainCount * mMaxElementsPerChain * 6, // max we can use - HBU_GPU_ONLY); - // NB we don't set the indexCount on IndexData here since we will - // probably use less than the maximum number of indices - - mBuffersNeedRecreating = false; - } - } - //----------------------------------------------------------------------- - void BillboardChain::setMaxChainElements(size_t maxElements) - { - mMaxElementsPerChain = maxElements; - setupChainContainers(); - mBuffersNeedRecreating = mIndexContentDirty = mVertexContentDirty = true; - } - //----------------------------------------------------------------------- - void BillboardChain::setNumberOfChains(size_t numChains) - { - mChainCount = numChains; - setupChainContainers(); - mBuffersNeedRecreating = mIndexContentDirty = mVertexContentDirty = true; - } - //----------------------------------------------------------------------- - void BillboardChain::setUseTextureCoords(bool use) - { - mUseTexCoords = use; - mVertexDeclDirty = mBuffersNeedRecreating = true; - mIndexContentDirty = mVertexContentDirty = true; - } - //----------------------------------------------------------------------- - void BillboardChain::setTextureCoordDirection(BillboardChain::TexCoordDirection dir) - { - mTexCoordDir = dir; - mVertexContentDirty = true; - } - //----------------------------------------------------------------------- - void BillboardChain::setOtherTextureCoordRange(Real start, Real end) - { - mOtherTexCoordRange[0] = start; - mOtherTexCoordRange[1] = end; - mVertexContentDirty = true; - } - //----------------------------------------------------------------------- - void BillboardChain::setUseVertexColours(bool use) - { - mUseVertexColour = use; - mVertexDeclDirty = mBuffersNeedRecreating = true; - mIndexContentDirty = mVertexContentDirty = true; - } - void BillboardChain::setAutoUpdate(bool autoUpdate) - { - mAutoUpdate = autoUpdate; - } - //----------------------------------------------------------------------- - void BillboardChain::addChainElement(size_t chainIndex, - const BillboardChain::Element& dtls) - { - ChainSegment& seg = mChainSegmentList.at(chainIndex); - if (seg.head == SEGMENT_EMPTY) - { - // Tail starts at end, head grows backwards - seg.tail = mMaxElementsPerChain - 1; - seg.head = seg.tail; - } - else - { - if (seg.head == 0) - { - // Wrap backwards - seg.head = mMaxElementsPerChain - 1; - } - else - { - // Just step backward - --seg.head; - } - // Run out of elements? - if (seg.head == seg.tail) - { - // Move tail backwards too, losing the end of the segment and re-using - // it in the head - if (seg.tail == 0) - seg.tail = mMaxElementsPerChain - 1; - else - --seg.tail; - } - } - - // Set the details - mChainElementList[seg.start + seg.head] = dtls; - - mVertexContentDirty = true; - mIndexContentDirty = true; - mBoundsDirty = true; - // tell parent node to update bounds - if (mParentNode) - mParentNode->needUpdate(); - - } - //----------------------------------------------------------------------- - void BillboardChain::removeChainElement(size_t chainIndex) - { - ChainSegment& seg = mChainSegmentList.at(chainIndex); - if (seg.head == SEGMENT_EMPTY) - return; // do nothing, nothing to remove - - - if (seg.tail == seg.head) - { - // last item - seg.head = seg.tail = SEGMENT_EMPTY; - } - else if (seg.tail == 0) - { - seg.tail = mMaxElementsPerChain - 1; - } - else - { - --seg.tail; - } - - // we removed an entry so indexes need updating - mVertexContentDirty = true; - mIndexContentDirty = true; - mBoundsDirty = true; - // tell parent node to update bounds - if (mParentNode) - mParentNode->needUpdate(); - - } - //----------------------------------------------------------------------- - void BillboardChain::clearChain(size_t chainIndex) - { - ChainSegment& seg = mChainSegmentList.at(chainIndex); - - // Just reset head & tail - seg.tail = seg.head = SEGMENT_EMPTY; - - // we removed an entry so indexes need updating - mVertexContentDirty = true; - mIndexContentDirty = true; - mBoundsDirty = true; - // tell parent node to update bounds - if (mParentNode) - mParentNode->needUpdate(); - - } - //----------------------------------------------------------------------- - void BillboardChain::clearAllChains(void) - { - for (size_t i = 0; i < mChainCount; ++i) - { - clearChain(i); - } - - } - //----------------------------------------------------------------------- - void BillboardChain::setFaceCamera( bool faceCamera, const Vector3 &normalVector ) - { - mFaceCamera = faceCamera; - mNormalBase = normalVector.normalisedCopy(); - mVertexContentDirty = true; - } - //----------------------------------------------------------------------- - void BillboardChain::updateChainElement(size_t chainIndex, size_t elementIndex, - const BillboardChain::Element& dtls) - { - ChainSegment& seg = mChainSegmentList.at(chainIndex); - OgreAssert(seg.head != SEGMENT_EMPTY, "Chain segment is empty"); - - size_t idx = seg.head + elementIndex; - // adjust for the edge and start - idx = (idx % mMaxElementsPerChain) + seg.start; - - mChainElementList[idx] = dtls; - - mVertexContentDirty = true; - mBoundsDirty = true; - // tell parent node to update bounds - if (mParentNode) - mParentNode->needUpdate(); - - - } - //----------------------------------------------------------------------- - const BillboardChain::Element& - BillboardChain::getChainElement(size_t chainIndex, size_t elementIndex) const - { - const ChainSegment& seg = mChainSegmentList.at(chainIndex); - OgreAssert(seg.head != SEGMENT_EMPTY, "Chain segment is empty"); - - size_t idx = seg.head + elementIndex; - // adjust for the edge and start - idx = (idx % mMaxElementsPerChain) + seg.start; - - return mChainElementList[idx]; - } - //----------------------------------------------------------------------- - size_t BillboardChain::getNumChainElements(size_t chainIndex) const - { - const ChainSegment& seg = mChainSegmentList.at(chainIndex); - - if (seg.head == SEGMENT_EMPTY) - { - return 0; - } - else if (seg.tail < seg.head) - { - return seg.tail - seg.head + mMaxElementsPerChain + 1; - } - else - { - return seg.tail - seg.head + 1; - } - } - //----------------------------------------------------------------------- - void BillboardChain::updateBoundingBox(void) const - { - if (mBoundsDirty) - { - mAABB.setNull(); - Vector3 widthVector; - for (const auto& seg : mChainSegmentList) - { - if (seg.head != SEGMENT_EMPTY) - { - - for(size_t e = seg.head; ; ++e) // until break - { - // Wrap forwards - if (e == mMaxElementsPerChain) - e = 0; - - const Element& elem = mChainElementList[seg.start + e]; - - widthVector.x = widthVector.y = widthVector.z = elem.width; - mAABB.merge(elem.position - widthVector); - mAABB.merge(elem.position + widthVector); - - if (e == seg.tail) - break; - - } - } - - } - - // Set the current radius - if (mAABB.isNull()) - { - mRadius = 0.0f; - } - else - { - mRadius = Math::Sqrt( - std::max(mAABB.getMinimum().squaredLength(), - mAABB.getMaximum().squaredLength())); - } - - mBoundsDirty = false; - } - } - //----------------------------------------------------------------------- - void BillboardChain::updateVertexBuffer(Camera* cam) - { - setupBuffers(); - - if (!mVertexContentDirty && !mAutoUpdate) - return; - - HardwareVertexBufferSharedPtr pBuffer = - mVertexData->vertexBufferBinding->getBuffer(0); - HardwareBufferLockGuard vertexLock(pBuffer, HardwareBuffer::HBL_DISCARD); - - const Vector3& camPos = cam->getDerivedPosition(); - Vector3 eyePos = mParentNode->convertWorldToLocalPosition(camPos); - - Vector3 chainTangent; - for (auto& seg : mChainSegmentList) - { - // Skip 0 or 1 element segment counts - if (seg.head != SEGMENT_EMPTY && seg.head != seg.tail) - { - size_t laste = seg.head; - for (size_t e = seg.head; ; ++e) // until break - { - // Wrap forwards - if (e == mMaxElementsPerChain) - e = 0; - - Element& elem = mChainElementList[e + seg.start]; - assert (((e + seg.start) * 2) < 65536 && "Too many elements!"); - uint16 baseIdx = static_cast((e + seg.start) * 2); - - // Determine base pointer to vertex #1 - float* pFloat = reinterpret_cast( - static_cast(vertexLock.pData) + - pBuffer->getVertexSize() * baseIdx); - - // Get index of next item - size_t nexte = e + 1; - if (nexte == mMaxElementsPerChain) - nexte = 0; - - if (e == seg.head) - { - // No laste, use next item - chainTangent = mChainElementList[nexte + seg.start].position - elem.position; - } - else if (e == seg.tail) - { - // No nexte, use only last item - chainTangent = elem.position - mChainElementList[laste + seg.start].position; - } - else - { - // A mid position, use tangent across both prev and next - chainTangent = mChainElementList[nexte + seg.start].position - mChainElementList[laste + seg.start].position; - - } - - Vector3 vP1ToEye; - - if( mFaceCamera ) - vP1ToEye = eyePos - elem.position; - else - vP1ToEye = elem.orientation * mNormalBase; - - Vector3 vPerpendicular = chainTangent.crossProduct(vP1ToEye); - vPerpendicular.normalise(); - vPerpendicular *= (elem.width * 0.5f); - - Vector3 pos0 = elem.position - vPerpendicular; - Vector3 pos1 = elem.position + vPerpendicular; - - // pos1 - *pFloat++ = pos0.x; - *pFloat++ = pos0.y; - *pFloat++ = pos0.z; - - if (mUseVertexColour) - { - RGBA col = elem.colour.getAsBYTE(); - memcpy(pFloat++, &col, sizeof(RGBA)); - } - - if (mUseTexCoords) - { - if (mTexCoordDir == TCD_U) - { - *pFloat++ = elem.texCoord; - *pFloat++ = mOtherTexCoordRange[0]; - } - else - { - *pFloat++ = mOtherTexCoordRange[0]; - *pFloat++ = elem.texCoord; - } - } - - // pos2 - *pFloat++ = pos1.x; - *pFloat++ = pos1.y; - *pFloat++ = pos1.z; - - if (mUseVertexColour) - { - RGBA col = elem.colour.getAsBYTE(); - memcpy(pFloat++, &col, sizeof(RGBA)); - } - - if (mUseTexCoords) - { - if (mTexCoordDir == TCD_U) - { - *pFloat++ = elem.texCoord; - *pFloat++ = mOtherTexCoordRange[1]; - } - else - { - *pFloat++ = mOtherTexCoordRange[1]; - *pFloat++ = elem.texCoord; - } - } - - if (e == seg.tail) - break; // last one - - laste = e; - - } // element - } // segment valid? - - } // each segment - - mVertexCameraUsed = cam; - mVertexContentDirty = false; - } - //----------------------------------------------------------------------- - void BillboardChain::updateIndexBuffer(void) - { - - setupBuffers(); - if (mIndexContentDirty) - { - HardwareBufferLockGuard indexLock(mIndexData->indexBuffer, HardwareBuffer::HBL_DISCARD); - uint16* pShort = static_cast(indexLock.pData); - mIndexData->indexCount = 0; - // indexes - for (auto& seg : mChainSegmentList) - { - // Skip 0 or 1 element segment counts - if (seg.head != SEGMENT_EMPTY && seg.head != seg.tail) - { - // Start from head + 1 since it's only useful in pairs - size_t laste = seg.head; - while(1) // until break - { - size_t e = laste + 1; - // Wrap forwards - if (e == mMaxElementsPerChain) - e = 0; - // indexes of this element are (e * 2) and (e * 2) + 1 - // indexes of the last element are the same, -2 - assert (((e + seg.start) * 2) < 65536 && "Too many elements!"); - uint16 baseIdx = static_cast((e + seg.start) * 2); - uint16 lastBaseIdx = static_cast((laste + seg.start) * 2); - *pShort++ = lastBaseIdx; - *pShort++ = lastBaseIdx + 1; - *pShort++ = baseIdx; - *pShort++ = lastBaseIdx + 1; - *pShort++ = baseIdx + 1; - *pShort++ = baseIdx; - - mIndexData->indexCount += 6; - - - if (e == seg.tail) - break; // last one - - laste = e; - - } - } - - } - - mIndexContentDirty = false; - } - - } - //----------------------------------------------------------------------- - Real BillboardChain::getSquaredViewDepth(const Camera* cam) const - { - return (cam->getDerivedPosition() - mAABB.getCenter()).squaredLength(); - } - //----------------------------------------------------------------------- - Real BillboardChain::getBoundingRadius(void) const - { - return mRadius; - } - //----------------------------------------------------------------------- - const AxisAlignedBox& BillboardChain::getBoundingBox(void) const - { - updateBoundingBox(); - return mAABB; - } - //----------------------------------------------------------------------- - const MaterialPtr& BillboardChain::getMaterial(void) const - { - return mMaterial; - } - //----------------------------------------------------------------------- - void BillboardChain::setMaterialName( const String& name, const String& groupName /* = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME */) - { - mMaterial = MaterialManager::getSingleton().getByName(name, groupName); - - if (!mMaterial) - { - logMaterialNotFound(name, groupName, "BillboardChain", mName); - mMaterial = MaterialManager::getSingleton().getDefaultMaterial(false); - } - // Ensure new material loaded (will not load again if already loaded) - mMaterial->load(); - } - //----------------------------------------------------------------------- - const String& BillboardChain::getMovableType(void) const - { - return MOT_BILLBOARD_CHAIN; - } - //----------------------------------------------------------------------- - void BillboardChain::_updateRenderQueue(RenderQueue* queue) - { - updateIndexBuffer(); - - if (mIndexData->indexCount > 0) - { - if (mRenderQueuePrioritySet) - queue->addRenderable(this, mRenderQueueID, mRenderQueuePriority); - else if (mRenderQueueIDSet) - queue->addRenderable(this, mRenderQueueID); - else - queue->addRenderable(this); - } - } - //----------------------------------------------------------------------- - void BillboardChain::getRenderOperation(RenderOperation& op) - { - op.indexData = mIndexData.get(); - op.operationType = RenderOperation::OT_TRIANGLE_LIST; - op.srcRenderable = this; - op.useIndexes = true; - op.vertexData = mVertexData.get(); - } - //----------------------------------------------------------------------- - bool BillboardChain::preRender(SceneManager* sm, RenderSystem* rsys) - { - // Retrieve the current viewport from the scene manager. - // The viewport is only valid during a viewport update. - Viewport *currentViewport = sm->getCurrentViewport(); - if( !currentViewport ) - return false; - - updateVertexBuffer(currentViewport->getCamera()); - return true; - } - //----------------------------------------------------------------------- - void BillboardChain::getWorldTransforms(Matrix4* xform) const - { - *xform = _getParentNodeFullTransform(); - } - //----------------------------------------------------------------------- - const LightList& BillboardChain::getLights(void) const - { - return queryLights(); - } - //--------------------------------------------------------------------- - void BillboardChain::visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables) - { - // only one renderable - visitor->visit(this, 0, false); - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - const String MOT_BILLBOARD_CHAIN = "BillboardChain"; - //----------------------------------------------------------------------- - const String& BillboardChainFactory::getType(void) const - { - return MOT_BILLBOARD_CHAIN; - } - //----------------------------------------------------------------------- - MovableObject* BillboardChainFactory::createInstanceImpl( const String& name, - const NameValuePairList* params) - { - size_t maxElements = 20; - size_t numberOfChains = 1; - bool useTex = true; - bool useCol = true; - bool dynamic = true; - // optional params - if (params != 0) - { - NameValuePairList::const_iterator ni = params->find("maxElements"); - if (ni != params->end()) - { - maxElements = StringConverter::parseSizeT(ni->second); - } - ni = params->find("numberOfChains"); - if (ni != params->end()) - { - numberOfChains = StringConverter::parseSizeT(ni->second); - } - ni = params->find("useTextureCoords"); - if (ni != params->end()) - { - useTex = StringConverter::parseBool(ni->second); - } - ni = params->find("useVertexColours"); - if (ni != params->end()) - { - useCol = StringConverter::parseBool(ni->second); - } - ni = params->find("dynamic"); - if (ni != params->end()) - { - dynamic = StringConverter::parseBool(ni->second); - } - } - - return OGRE_NEW BillboardChain(name, maxElements, numberOfChains, useTex, useCol, dynamic); - - } -} diff --git a/OgreMain/src/OgreBillboardParticleRenderer.cpp b/OgreMain/src/OgreBillboardParticleRenderer.cpp deleted file mode 100644 index 42cf01e1c2c..00000000000 --- a/OgreMain/src/OgreBillboardParticleRenderer.cpp +++ /dev/null @@ -1,441 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreBillboardParticleRenderer.h" -#include "OgreParticle.h" -#include "OgreBillboard.h" - -namespace Ogre { - static String rendererTypeName = "billboard"; - - /** Command object for billboard type (see ParamCommand).*/ - class _OgrePrivate CmdBillboardType : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for billboard origin (see ParamCommand).*/ - class _OgrePrivate CmdBillboardOrigin : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for billboard rotation type (see ParamCommand).*/ - class _OgrePrivate CmdBillboardRotationType : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for common direction (see ParamCommand).*/ - class _OgrePrivate CmdCommonDirection : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for common up-vector (see ParamCommand).*/ - class _OgrePrivate CmdCommonUpVector : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for point rendering (see ParamCommand).*/ - class _OgrePrivate CmdPointRendering : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for accurate facing(see ParamCommand).*/ - class _OgrePrivate CmdAccurateFacing : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - static CmdBillboardType msBillboardTypeCmd; - static CmdBillboardOrigin msBillboardOriginCmd; - static CmdBillboardRotationType msBillboardRotationTypeCmd; - static CmdCommonDirection msCommonDirectionCmd; - static CmdCommonUpVector msCommonUpVectorCmd; - static CmdPointRendering msPointRenderingCmd; - static CmdAccurateFacing msAccurateFacingCmd; - - static class CmdStacksAndSlices : public ParamCommand - { - public: - String doGet(const void* target) const override - { - return StringConverter::toString( - static_cast(target)->getTextureStacksAndSlices()); - } - void doSet(void* target, const String& val) override - { - Vector2 tmp = StringConverter::parseVector2(val); - static_cast(target)->setTextureStacksAndSlices(tmp.x, tmp.y); - } - } msStacksAndSlicesCmd; - - //----------------------------------------------------------------------- - BillboardParticleRenderer::BillboardParticleRenderer() : mStacksSlices(1, 1) - { - if (createParamDictionary("BillboardParticleRenderer")) - { - ParamDictionary* dict = getParamDictionary(); - dict->addParameter(ParameterDef("billboard_type", - "The type of billboard to use. 'point' means a simulated spherical particle, " - "'oriented_common' means all particles in the set are oriented around common_direction, " - "'oriented_self' means particles are oriented around their own direction, " - "'perpendicular_common' means all particles are perpendicular to common_direction, " - "and 'perpendicular_self' means particles are perpendicular to their own direction.", - PT_STRING), - &msBillboardTypeCmd); - - dict->addParameter(ParameterDef("billboard_origin", - "This setting controls the fine tuning of where a billboard appears in relation to it's position. " - "Possible value are: 'top_left', 'top_center', 'top_right', 'center_left', 'center', 'center_right', " - "'bottom_left', 'bottom_center' and 'bottom_right'. Default value is 'center'.", - PT_STRING), - &msBillboardOriginCmd); - - dict->addParameter(ParameterDef("billboard_rotation_type", - "This setting controls the billboard rotation type. " - "'vertex' means rotate the billboard's vertices around their facing direction." - "'texcoord' means rotate the billboard's texture coordinates. Default value is 'texcoord'.", - PT_STRING), - &msBillboardRotationTypeCmd); - - dict->addParameter(ParameterDef("common_direction", - "Only useful when billboard_type is oriented_common or perpendicular_common. " - "When billboard_type is oriented_common, this parameter sets the common orientation for " - "all particles in the set (e.g. raindrops may all be oriented downwards). " - "When billboard_type is perpendicular_common, this parameter sets the perpendicular vector for " - "all particles in the set (e.g. an aureola around the player and parallel to the ground).", - PT_VECTOR3), - &msCommonDirectionCmd); - - dict->addParameter(ParameterDef("common_up_vector", - "Only useful when billboard_type is perpendicular_self or perpendicular_common. This " - "parameter sets the common up-vector for all particles in the set (e.g. an aureola around " - "the player and parallel to the ground).", - PT_VECTOR3), - &msCommonUpVectorCmd); - dict->addParameter(ParameterDef("point_rendering", - "Set whether or not particles will use point rendering " - "rather than manually generated quads. This allows for faster " - "rendering of point-oriented particles although introduces some " - "limitations too such as requiring a common particle size." - "Possible values are 'true' or 'false'.", - PT_BOOL), - &msPointRenderingCmd); - dict->addParameter(ParameterDef("accurate_facing", - "Set whether or not particles will be oriented to the camera " - "based on the relative position to the camera rather than just " - "the camera direction. This is more accurate but less optimal. " - "Cannot be combined with point rendering.", - PT_BOOL), - &msAccurateFacingCmd); - - dict->addParameter(ParameterDef("texture_sheet_size", "", - PT_UNSIGNED_INT), - &msStacksAndSlicesCmd); - } - - // Create billboard set - mBillboardSet = OGRE_NEW BillboardSet("", 0, true); - // World-relative axes - mBillboardSet->setBillboardsInWorldSpace(true); - } - //----------------------------------------------------------------------- - BillboardParticleRenderer::~BillboardParticleRenderer() - { - // mBillboardSet is never actually attached to a node, we just passthrough - // based on the particle system's attachment. So manually notify that it's - // no longer attached. - mBillboardSet->_notifyAttached(0); - OGRE_DELETE mBillboardSet; - } - //----------------------------------------------------------------------- - const String& BillboardParticleRenderer::getType(void) const - { - return rendererTypeName; - } - //----------------------------------------------------------------------- - void BillboardParticleRenderer::_updateRenderQueue(RenderQueue* queue, - std::vector& currentParticles, bool cullIndividually) - { - mBillboardSet->setCullIndividually(cullIndividually); - - // Update billboard set geometry - mBillboardSet->beginBillboards(currentParticles.size()); - Billboard bb; - - for (Particle* p : currentParticles) - { - bb.mPosition = p->mPosition; - - if (mBillboardSet->getBillboardType() == BBT_ORIENTED_SELF || - mBillboardSet->getBillboardType() == BBT_PERPENDICULAR_SELF) - { - // Normalise direction vector - bb.mDirection = p->mDirection; - bb.mDirection.normalise(); - } - bb.mColour = p->mColour; - bb.mRotation = p->mRotation; - bb.mTexcoordIndex = p->mTexcoordIndex; - bb.mOwnDimensions = p->mWidth != mBillboardSet->getDefaultWidth() || - p->mHeight != mBillboardSet->getDefaultHeight(); - if (bb.mOwnDimensions) - { - bb.mWidth = p->mWidth; - bb.mHeight = p->mHeight; - } - mBillboardSet->injectBillboard(bb); - } - - mBillboardSet->endBillboards(); - - // Update the queue - mBillboardSet->_updateRenderQueue(queue); - } - - void BillboardParticleRenderer::_notifyBoundingBox(const AxisAlignedBox& aabb) - { - mBillboardSet->setBounds(aabb, Math::boundingRadiusFromAABB(aabb)); - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - const String& BillboardParticleRendererFactory::getType() const - { - return rendererTypeName; - } - //----------------------------------------------------------------------- - ParticleSystemRenderer* BillboardParticleRendererFactory::createInstance( - const String& name ) - { - return OGRE_NEW BillboardParticleRenderer(); - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String CmdBillboardType::doGet(const void* target) const - { - BillboardType t = static_cast(target)->getBillboardType(); - switch(t) - { - case BBT_POINT: - return "point"; - break; - case BBT_ORIENTED_COMMON: - return "oriented_common"; - break; - case BBT_ORIENTED_SELF: - return "oriented_self"; - break; - case BBT_PERPENDICULAR_COMMON: - return "perpendicular_common"; - case BBT_PERPENDICULAR_SELF: - return "perpendicular_self"; - } - // Compiler nicety - return ""; - } - void CmdBillboardType::doSet(void* target, const String& val) - { - BillboardType t; - if (val == "point") - { - t = BBT_POINT; - } - else if (val == "oriented_common") - { - t = BBT_ORIENTED_COMMON; - } - else if (val == "oriented_self") - { - t = BBT_ORIENTED_SELF; - } - else if (val == "perpendicular_common") - { - t = BBT_PERPENDICULAR_COMMON; - } - else if (val == "perpendicular_self") - { - t = BBT_PERPENDICULAR_SELF; - } - else - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Invalid billboard_type '" + val + "'", - "ParticleSystem::CmdBillboardType::doSet"); - } - - static_cast(target)->setBillboardType(t); - } - //----------------------------------------------------------------------- - String CmdBillboardOrigin::doGet(const void* target) const - { - BillboardOrigin o = static_cast(target)->getBillboardOrigin(); - switch (o) - { - case BBO_TOP_LEFT: - return "top_left"; - case BBO_TOP_CENTER: - return "top_center"; - case BBO_TOP_RIGHT: - return "top_right"; - case BBO_CENTER_LEFT: - return "center_left"; - case BBO_CENTER: - return "center"; - case BBO_CENTER_RIGHT: - return "center_right"; - case BBO_BOTTOM_LEFT: - return "bottom_left"; - case BBO_BOTTOM_CENTER: - return "bottom_center"; - case BBO_BOTTOM_RIGHT: - return "bottom_right"; - } - // Compiler nicety - return BLANKSTRING; - } - void CmdBillboardOrigin::doSet(void* target, const String& val) - { - BillboardOrigin o; - if (val == "top_left") - o = BBO_TOP_LEFT; - else if (val =="top_center") - o = BBO_TOP_CENTER; - else if (val =="top_right") - o = BBO_TOP_RIGHT; - else if (val =="center_left") - o = BBO_CENTER_LEFT; - else if (val =="center") - o = BBO_CENTER; - else if (val =="center_right") - o = BBO_CENTER_RIGHT; - else if (val =="bottom_left") - o = BBO_BOTTOM_LEFT; - else if (val =="bottom_center") - o = BBO_BOTTOM_CENTER; - else if (val =="bottom_right") - o = BBO_BOTTOM_RIGHT; - else - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Invalid billboard_origin '" + val + "'", - "ParticleSystem::CmdBillboardOrigin::doSet"); - } - - static_cast(target)->setBillboardOrigin(o); - } - //----------------------------------------------------------------------- - String CmdBillboardRotationType::doGet(const void* target) const - { - BillboardRotationType r = static_cast(target)->getBillboardRotationType(); - switch(r) - { - case BBR_VERTEX: - return "vertex"; - case BBR_TEXCOORD: - return "texcoord"; - } - // Compiler nicety - return BLANKSTRING; - } - void CmdBillboardRotationType::doSet(void* target, const String& val) - { - BillboardRotationType r; - if (val == "vertex") - r = BBR_VERTEX; - else if (val == "texcoord") - r = BBR_TEXCOORD; - else - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Invalid billboard_rotation_type '" + val + "'", - "ParticleSystem::CmdBillboardRotationType::doSet"); - } - - static_cast(target)->setBillboardRotationType(r); - } - //----------------------------------------------------------------------- - String CmdCommonDirection::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getCommonDirection() ); - } - void CmdCommonDirection::doSet(void* target, const String& val) - { - static_cast(target)->setCommonDirection( - StringConverter::parseVector3(val)); - } - //----------------------------------------------------------------------- - String CmdCommonUpVector::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getCommonUpVector() ); - } - void CmdCommonUpVector::doSet(void* target, const String& val) - { - static_cast(target)->setCommonUpVector( - StringConverter::parseVector3(val)); - } - //----------------------------------------------------------------------- - String CmdPointRendering::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->isPointRenderingEnabled() ); - } - void CmdPointRendering::doSet(void* target, const String& val) - { - static_cast(target)->setPointRenderingEnabled( - StringConverter::parseBool(val)); - } - //----------------------------------------------------------------------- - String CmdAccurateFacing::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getUseAccurateFacing() ); - } - void CmdAccurateFacing::doSet(void* target, const String& val) - { - static_cast(target)->setUseAccurateFacing( - StringConverter::parseBool(val)); - } - -} - - diff --git a/OgreMain/src/OgreBillboardSet.cpp b/OgreMain/src/OgreBillboardSet.cpp deleted file mode 100644 index cad2f466739..00000000000 --- a/OgreMain/src/OgreBillboardSet.cpp +++ /dev/null @@ -1,1174 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreBillboardSet.h" -#include "OgreBillboard.h" - -#include -#include - -namespace Ogre { - //----------------------------------------------------------------------- - BillboardSet::BillboardSet() : - mBoundingRadius(0.0f), - mOriginType( BBO_CENTER ), - mRotationType( BBR_TEXCOORD ), - mAutoExtendPool( true ), - mSortingEnabled(false), - mAccurateFacing(false), - mWorldSpace(false), - mCullIndividual( false ), - mBillboardType(BBT_POINT), - mCommonDirection(Ogre::Vector3::UNIT_Z), - mCommonUpVector(Vector3::UNIT_Y), - mPointRendering(false), - mBuffersCreated(false), - mPoolSize(0), - mExternalData(false), - mAutoUpdate(true), - mBillboardDataChanged(true) - { - setDefaultDimensions( 100, 100 ); - mMaterial = MaterialManager::getSingleton().getDefaultMaterial(); - mMaterial->load(); - mCastShadows = false; - setTextureStacksAndSlices( 1, 1 ); - } - - //----------------------------------------------------------------------- - BillboardSet::BillboardSet( - const String& name, - unsigned int poolSize, - bool externalData) : - MovableObject(name), - mBoundingRadius(0.0f), - mOriginType( BBO_CENTER ), - mRotationType( BBR_TEXCOORD ), - mAutoExtendPool( true ), - mSortingEnabled(false), - mAccurateFacing(false), - mWorldSpace(false), - mActiveBillboards(0), - mCullIndividual( false ), - mBillboardType(BBT_POINT), - mCommonDirection(Ogre::Vector3::UNIT_Z), - mCommonUpVector(Vector3::UNIT_Y), - mPointRendering(false), - mBuffersCreated(false), - mPoolSize(poolSize), - mExternalData(externalData), - mAutoUpdate(true), - mBillboardDataChanged(true) - { - setDefaultDimensions( 100, 100 ); - mMaterial = MaterialManager::getSingleton().getDefaultMaterial(); - mMaterial->load(); - setPoolSize( poolSize ); - mCastShadows = false; - setTextureStacksAndSlices( 1, 1 ); - } - //----------------------------------------------------------------------- - BillboardSet::~BillboardSet() - { - // Free pool items - for (auto *b : mBillboardPool) - { - OGRE_DELETE b; - } - - // Delete shared buffers - _destroyBuffers(); - } - //----------------------------------------------------------------------- - Billboard* BillboardSet::createBillboard( - const Vector3& position, - const ColourValue& colour ) - { - if( mActiveBillboards == mBillboardPool.size() ) - { - if( mAutoExtendPool ) - { - setPoolSize( getPoolSize() * 2 ); - } - else - { - return 0; - } - } - - // Get a new billboard - Billboard* newBill = mBillboardPool[mActiveBillboards++]; - newBill->setPosition(position); - newBill->setColour(colour); - newBill->mDirection = Vector3::ZERO; - newBill->setRotation(Radian(0)); - newBill->setTexcoordIndex(0); - newBill->resetDimensions(); - - // Merge into bounds - Real adjust = std::max(mDefaultWidth, mDefaultHeight); - Vector3 vecAdjust(adjust, adjust, adjust); - Vector3 newMin = position - vecAdjust; - Vector3 newMax = position + vecAdjust; - - mAABB.merge(newMin); - mAABB.merge(newMax); - - mBoundingRadius = Math::boundingRadiusFromAABB(mAABB); - - return newBill; - } - - //----------------------------------------------------------------------- - void BillboardSet::clear() - { - mActiveBillboards = 0; - } - - //----------------------------------------------------------------------- - Billboard* BillboardSet::getBillboard( unsigned int index ) const - { - assert(index < mActiveBillboards && "Billboard index out of bounds."); - return mBillboardPool[index]; - } - - //----------------------------------------------------------------------- - void BillboardSet::removeBillboard(unsigned int index) - { - assert(index < mActiveBillboards && "Billboard isn't in the active list."); - std::swap(mBillboardPool[index], mBillboardPool[--mActiveBillboards]); - } - - //----------------------------------------------------------------------- - void BillboardSet::removeBillboard( Billboard* pBill ) - { - auto it = std::find(mBillboardPool.begin(), mBillboardPool.begin() + mActiveBillboards, pBill); - removeBillboard(std::distance(mBillboardPool.begin(), it)); - } - //----------------------------------------------------------------------- - void BillboardSet::setMaterialName( const String& name , const String& groupName /* = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME */ ) - { - mMaterial = MaterialManager::getSingleton().getByName(name, groupName); - - if (!mMaterial) - OGRE_EXCEPT( Exception::ERR_ITEM_NOT_FOUND, "Could not find material " + name, - "BillboardSet::setMaterialName" ); - - /* Ensure that the new material was loaded (will not load again if - already loaded anyway) - */ - mMaterial->load(); - } - - //----------------------------------------------------------------------- - void BillboardSet::_sortBillboards( Camera* cam) - { - static RadixSort mRadixSorter; - - switch (_getSortMode()) - { - case SM_DIRECTION: - mRadixSorter.sort(mBillboardPool.begin(), mBillboardPool.begin() + mActiveBillboards, - SortByDirectionFunctor(-mCamDir)); - break; - case SM_DISTANCE: - mRadixSorter.sort(mBillboardPool.begin(), mBillboardPool.begin() + mActiveBillboards, - SortByDistanceFunctor(mCamPos)); - break; - } - } - BillboardSet::SortByDirectionFunctor::SortByDirectionFunctor(const Vector3& dir) - : sortDir(dir) - { - } - float BillboardSet::SortByDirectionFunctor::operator()(Billboard* bill) const - { - return sortDir.dotProduct(bill->getPosition()); - } - BillboardSet::SortByDistanceFunctor::SortByDistanceFunctor(const Vector3& pos) - : sortPos(pos) - { - } - float BillboardSet::SortByDistanceFunctor::operator()(Billboard* bill) const - { - // Sort descending by squared distance - return - (sortPos - bill->getPosition()).squaredLength(); - } - //----------------------------------------------------------------------- - SortMode BillboardSet::_getSortMode(void) const - { - // Need to sort by distance if we're using accurate facing, or perpendicular billboard type. - if (mAccurateFacing || - mBillboardType == BBT_PERPENDICULAR_SELF || - mBillboardType == BBT_PERPENDICULAR_COMMON) - { - return SM_DISTANCE; - } - else - { - return SM_DIRECTION; - } - } - //----------------------------------------------------------------------- - void BillboardSet::_notifyCurrentCamera( Camera* cam ) - { - MovableObject::_notifyCurrentCamera(cam); - - mCurrentCamera = cam; - - // Calculate camera orientation and position - mCamQ = mCurrentCamera->getDerivedOrientation(); - mCamPos = mCurrentCamera->getDerivedPosition(); - if (!mWorldSpace) - { - // Default behaviour is that billboards are in local node space - // so orientation of camera (in world space) must be reverse-transformed - // into node space - mCamQ = mParentNode->convertWorldToLocalOrientation(mCamQ); - mCamPos = mParentNode->convertWorldToLocalPosition(mCamPos); - } - - // Camera direction points down -Z - mCamDir = mCamQ * Vector3::NEGATIVE_UNIT_Z; - } - //----------------------------------------------------------------------- - void BillboardSet::beginBillboards(size_t numBillboards) - { - /* Generate the vertices for all the billboards relative to the camera - Also take the opportunity to update the vertex colours - May as well do it here to save on loops elsewhere - */ - - /* NOTE: most engines generate world coordinates for the billboards - directly, taking the world axes of the camera as offsets to the - center points. I take a different approach, reverse-transforming - the camera world axes into local billboard space. - Why? - Well, it's actually more efficient this way, because I only have to - reverse-transform using the billboardset world matrix (inverse) - once, from then on it's simple additions (assuming identically - sized billboards). If I transformed every billboard center by it's - world transform, that's a matrix multiplication per billboard - instead. - I leave the final transform to the render pipeline since that can - use hardware TnL if it is available. - */ - - // create vertex and index buffers if they haven't already been - if(!mBuffersCreated) - _createBuffers(); - - // Only calculate vertex offets et al if we're not point rendering - if (!mPointRendering) - { - - // Get offsets for origin type - getParametricOffsets(mLeftOff, mRightOff, mTopOff, mBottomOff); - - // Generate axes etc up-front if not oriented per-billboard - if (mBillboardType != BBT_ORIENTED_SELF && - mBillboardType != BBT_PERPENDICULAR_SELF && - !(mAccurateFacing && mBillboardType != BBT_PERPENDICULAR_COMMON)) - { - genBillboardAxes(&mCamX, &mCamY); - - /* If all billboards are the same size we can precalculate the - offsets and just use '+' instead of '*' for each billboard, - and it should be faster. - */ - genVertOffsets(mLeftOff, mRightOff, mTopOff, mBottomOff, - mDefaultWidth, mDefaultHeight, mCamX, mCamY, mVOffset); - - } - } - - // Init num visible - mNumVisibleBillboards = 0; - - // Lock the buffer - if (numBillboards) // optimal lock - { - // clamp to max - numBillboards = std::min(mPoolSize, numBillboards); - - size_t billboardSize; - if (mPointRendering) - { - // just one vertex per billboard (this also excludes texcoords) - billboardSize = mMainBuf->getVertexSize(); - } - else - { - // 4 corners - billboardSize = mMainBuf->getVertexSize() * 4; - } - assert (numBillboards * billboardSize <= mMainBuf->getSizeInBytes()); - - mLockPtr = static_cast( - mMainBuf->lock(0, numBillboards * billboardSize, - mMainBuf->getUsage() & HardwareBuffer::HBU_DYNAMIC ? - HardwareBuffer::HBL_DISCARD : HardwareBuffer::HBL_NORMAL) ); - } - else // lock the entire thing - mLockPtr = static_cast( - mMainBuf->lock(mMainBuf->getUsage() & HardwareBuffer::HBU_DYNAMIC ? - HardwareBuffer::HBL_DISCARD : HardwareBuffer::HBL_NORMAL) ); - - } - //----------------------------------------------------------------------- - void BillboardSet::injectBillboard(const Billboard& bb) - { - // Don't accept injections beyond pool size - if (mNumVisibleBillboards == mPoolSize) return; - - // Skip if not visible (NB always true if not bounds checking individual billboards) - if (!billboardVisible(mCurrentCamera, bb)) return; - - // Increment visibles - mNumVisibleBillboards++; - - if(mPointRendering) - { - genPointVertices(bb); - return; - } - - if ((mBillboardType == BBT_ORIENTED_SELF || mBillboardType == BBT_PERPENDICULAR_SELF || - (mAccurateFacing && mBillboardType != BBT_PERPENDICULAR_COMMON))) - { - // Have to generate axes & offsets per billboard - genBillboardAxes(&mCamX, &mCamY, &bb); - } - - if ((mBillboardType == BBT_ORIENTED_SELF || mBillboardType == BBT_PERPENDICULAR_SELF || - bb.mOwnDimensions || (mAccurateFacing && mBillboardType != BBT_PERPENDICULAR_COMMON))) - { - // If it has own dimensions, or self-oriented, gen offsets - Vector3 vOwnOffset[4]; - Real width = bb.mOwnDimensions ? bb.mWidth : mDefaultWidth; - Real height = bb.mOwnDimensions ? bb.mHeight : mDefaultHeight; - genVertOffsets(mLeftOff, mRightOff, mTopOff, mBottomOff, - width, height, mCamX, mCamY, vOwnOffset); - genQuadVertices(vOwnOffset, bb); - } - else - { - // Use default dimension, already computed before the loop, for faster creation - genQuadVertices(mVOffset, bb); - } - } - //----------------------------------------------------------------------- - void BillboardSet::endBillboards(void) - { - mMainBuf->unlock(); - } - //----------------------------------------------------------------------- - void BillboardSet::setBounds(const AxisAlignedBox& box, Real radius) - { - mAABB = box; - mBoundingRadius = radius; - } - //----------------------------------------------------------------------- - void BillboardSet::_updateBounds(void) - { - if (mActiveBillboards == 0) - { - // No billboards, null bbox - mAABB.setNull(); - mBoundingRadius = 0.0f; - } - else - { - mAABB.setNull(); - auto iend = mBillboardPool.begin() + mActiveBillboards; - Affine3 invWorld; - bool invert = mWorldSpace && getParentSceneNode(); - if (invert) - invWorld = getParentSceneNode()->_getFullTransform().inverse(); - - for (auto i = mBillboardPool.begin(); i != iend; ++i) - { - Vector3 pos = (*i)->getPosition(); - // transform from world space to local space - if (invert) - pos = invWorld * pos; - - mAABB.merge(pos); - } - // Adjust for billboard size - Real adjust = std::max(mDefaultWidth, mDefaultHeight); - Vector3 vecAdjust(adjust, adjust, adjust); - - mAABB.setExtents(mAABB.getMinimum() - vecAdjust, mAABB.getMaximum() + vecAdjust); - mBoundingRadius = Math::boundingRadiusFromAABB(mAABB); - } - - if (mParentNode) - mParentNode->needUpdate(); - - } - - //----------------------------------------------------------------------- - void BillboardSet::_updateRenderQueue(RenderQueue* queue) - { - // If we're driving this from our own data, update geometry if need to. - if (!mExternalData && (mAutoUpdate || mBillboardDataChanged || !mBuffersCreated)) - { - if (mSortingEnabled) - { - _sortBillboards(mCurrentCamera); - } - - beginBillboards(mActiveBillboards); - auto iend = mBillboardPool.begin() + mActiveBillboards; - for (auto it = mBillboardPool.begin(); it != iend; ++it) - { - injectBillboard(*(*it)); - } - endBillboards(); - mBillboardDataChanged = false; - } - - //only set the render queue group if it has been explicitly set. - if (mRenderQueuePrioritySet) - { - assert(mRenderQueueIDSet == true); - queue->addRenderable(this, mRenderQueueID, mRenderQueuePriority); - } - else if( mRenderQueueIDSet ) - { - queue->addRenderable(this, mRenderQueueID); - } else { - queue->addRenderable(this); - } - - } - - void BillboardSet::setMaterial( const MaterialPtr& material ) - { - OgreAssert(material, "material is NULL"); - mMaterial = material; - - // Ensure new material loaded (will not load again if already loaded) - mMaterial->load(); - } - - //----------------------------------------------------------------------- - void BillboardSet::getRenderOperation(RenderOperation& op) - { - op.vertexData = mVertexData.get(); - op.vertexData->vertexStart = 0; - - if (mPointRendering) - { - op.operationType = RenderOperation::OT_POINT_LIST; - op.useIndexes = false; - op.useGlobalInstancing = false; - op.indexData = 0; - op.vertexData->vertexCount = mNumVisibleBillboards; - } - else - { - op.operationType = RenderOperation::OT_TRIANGLE_LIST; - op.useIndexes = true; - - op.vertexData->vertexCount = mNumVisibleBillboards * 4; - - op.indexData = mIndexData.get(); - op.indexData->indexCount = mNumVisibleBillboards * 6; - op.indexData->indexStart = 0; - } - } - - //----------------------------------------------------------------------- - void BillboardSet::getWorldTransforms( Matrix4* xform ) const - { - if (mWorldSpace) - { - *xform = Matrix4::IDENTITY; - } - else - { - *xform = _getParentNodeFullTransform(); - } - } - - //----------------------------------------------------------------------- - void BillboardSet::setPoolSize( size_t size ) - { - // If we're driving this from our own data, allocate billboards - if (!mExternalData) - { - // Never shrink below size() - size_t currSize = mBillboardPool.size(); - if (currSize >= size) - return; - - this->increasePool(size); - } - - mPoolSize = size; - - _destroyBuffers(); - } - - //----------------------------------------------------------------------- - void BillboardSet::_createBuffers(void) - { - /* Allocate / reallocate vertex data - Note that we allocate enough space for ALL the billboards in the pool, but only issue - rendering operations for the sections relating to the active billboards - */ - - /* Alloc positions ( 1 or 4 verts per billboard, 3 components ) - colours ( 1 x RGBA per vertex ) - indices ( 6 per billboard ( 2 tris ) if not point rendering ) - tex. coords ( 2D coords, 1 or 4 per billboard ) - */ - - // Warn if user requested an invalid setup - // Do it here so it only appears once - if (mPointRendering && mBillboardType != BBT_POINT) - { - - LogManager::getSingleton().logWarning("BillboardSet " + - mName + " has point rendering enabled but is using a type " - "other than BBT_POINT, this may not give you the results you " - "expect."); - } - - mVertexData = std::make_unique(); - if (mPointRendering) - mVertexData->vertexCount = mPoolSize; - else - mVertexData->vertexCount = mPoolSize * 4; - - mVertexData->vertexStart = 0; - - // Vertex declaration - VertexDeclaration* decl = mVertexData->vertexDeclaration; - VertexBufferBinding* binding = mVertexData->vertexBufferBinding; - - size_t offset = 0; - offset += decl->addElement(0, offset, VET_FLOAT3, VES_POSITION).getSize(); - offset += decl->addElement(0, offset, VET_UBYTE4_NORM, VES_DIFFUSE).getSize(); - // Texture coords irrelevant when enabled point rendering (generated - // in point sprite mode, and unused in standard point mode) - if (!mPointRendering) - { - decl->addElement(0, offset, VET_FLOAT2, VES_TEXTURE_COORDINATES, 0); - } - - mMainBuf = - HardwareBufferManager::getSingleton().createVertexBuffer( - decl->getVertexSize(0), - mVertexData->vertexCount, - mAutoUpdate ? HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE : - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - // bind position and diffuses - binding->setBinding(0, mMainBuf); - - if (!mPointRendering) - { - mIndexData = std::make_unique(); - mIndexData->indexStart = 0; - mIndexData->indexCount = mPoolSize * 6; - - mIndexData->indexBuffer = HardwareBufferManager::getSingleton(). - createIndexBuffer(HardwareIndexBuffer::IT_16BIT, - mIndexData->indexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - /* Create indexes (will be the same every frame) - Using indexes because it means 1/3 less vertex transforms (4 instead of 6) - - Billboard layout relative to camera: - - 0-----1 - | /| - | / | - |/ | - 2-----3 - */ - - HardwareBufferLockGuard indexLock(mIndexData->indexBuffer, HardwareBuffer::HBL_DISCARD); - ushort* pIdx = static_cast(indexLock.pData); - - for( - size_t idx, idxOff, bboard = 0; - bboard < mPoolSize; - ++bboard ) - { - // Do indexes - idx = bboard * 6; - idxOff = bboard * 4; - - pIdx[idx] = static_cast(idxOff); // + 0;, for clarity - pIdx[idx+1] = static_cast(idxOff + 2); - pIdx[idx+2] = static_cast(idxOff + 1); - pIdx[idx+3] = static_cast(idxOff + 1); - pIdx[idx+4] = static_cast(idxOff + 2); - pIdx[idx+5] = static_cast(idxOff + 3); - - } - } - mBuffersCreated = true; - } - //----------------------------------------------------------------------- - void BillboardSet::_destroyBuffers(void) - { - mVertexData.reset(); - mIndexData.reset(); - mMainBuf.reset(); - - mBuffersCreated = false; - } - - //----------------------------------------------------------------------- - void BillboardSet::getParametricOffsets( - Real& left, Real& right, Real& top, Real& bottom ) - { - switch( mOriginType ) - { - case BBO_TOP_LEFT: - left = 0.0f; - right = 1.0f; - top = 0.0f; - bottom = -1.0f; - break; - - case BBO_TOP_CENTER: - left = -0.5f; - right = 0.5f; - top = 0.0f; - bottom = -1.0f; - break; - - case BBO_TOP_RIGHT: - left = -1.0f; - right = 0.0f; - top = 0.0f; - bottom = -1.0f; - break; - - case BBO_CENTER_LEFT: - left = 0.0f; - right = 1.0f; - top = 0.5f; - bottom = -0.5f; - break; - - case BBO_CENTER: - left = -0.5f; - right = 0.5f; - top = 0.5f; - bottom = -0.5f; - break; - - case BBO_CENTER_RIGHT: - left = -1.0f; - right = 0.0f; - top = 0.5f; - bottom = -0.5f; - break; - - case BBO_BOTTOM_LEFT: - left = 0.0f; - right = 1.0f; - top = 1.0f; - bottom = 0.0f; - break; - - case BBO_BOTTOM_CENTER: - left = -0.5f; - right = 0.5f; - top = 1.0f; - bottom = 0.0f; - break; - - case BBO_BOTTOM_RIGHT: - left = -1.0f; - right = 0.0f; - top = 1.0f; - bottom = 0.0f; - break; - } - } - //----------------------------------------------------------------------- - bool BillboardSet::billboardVisible(Camera* cam, const Billboard& bill) - { - // Return always visible if not culling individually - if (!mCullIndividual) return true; - - // Cull based on sphere (have to transform less) - Sphere sph; - Matrix4 xworld; - - getWorldTransforms(&xworld); - - sph.setCenter(xworld * bill.mPosition); - - if (bill.mOwnDimensions) - { - sph.setRadius(std::max(bill.mWidth, bill.mHeight)); - } - else - { - sph.setRadius(std::max(mDefaultWidth, mDefaultHeight)); - } - - return cam->isVisible(sph); - - } - //----------------------------------------------------------------------- - void BillboardSet::increasePool(size_t size) - { - size_t oldSize = mBillboardPool.size(); - - // Increase size - mBillboardPool.resize(size); - - // Create new billboards - for( size_t i = oldSize; i < size; ++i ) - mBillboardPool[i] = OGRE_NEW Billboard(); - - } - //----------------------------------------------------------------------- - void BillboardSet::genBillboardAxes(Vector3* pX, Vector3 *pY, const Billboard* bb) - { - // If we're using accurate facing, recalculate camera direction per BB - if (mAccurateFacing && - (mBillboardType == BBT_POINT || - mBillboardType == BBT_ORIENTED_COMMON || - mBillboardType == BBT_ORIENTED_SELF)) - { - // cam -> bb direction - mCamDir = bb->mPosition - mCamPos; - mCamDir.normalise(); - } - - - switch (mBillboardType) - { - case BBT_POINT: - if (mAccurateFacing) - { - // Point billboards will have 'up' based on but not equal to cameras - // Use pY temporarily to avoid allocation - *pY = mCamQ * Vector3::UNIT_Y; - *pX = mCamDir.crossProduct(*pY); - pX->normalise(); - *pY = pX->crossProduct(mCamDir); // both normalised already - } - else - { - // Get camera axes for X and Y (depth is irrelevant) - *pX = mCamQ * Vector3::UNIT_X; - *pY = mCamQ * Vector3::UNIT_Y; - } - break; - - case BBT_ORIENTED_COMMON: - // Y-axis is common direction - // X-axis is cross with camera direction - *pY = mCommonDirection; - *pX = mCamDir.crossProduct(*pY); - pX->normalise(); - break; - - case BBT_ORIENTED_SELF: - // Y-axis is direction - // X-axis is cross with camera direction - // Scale direction first - *pY = bb->mDirection; - *pX = mCamDir.crossProduct(*pY); - pX->normalise(); - break; - - case BBT_PERPENDICULAR_COMMON: - // X-axis is up-vector cross common direction - // Y-axis is common direction cross X-axis - *pX = mCommonUpVector.crossProduct(mCommonDirection); - *pY = mCommonDirection.crossProduct(*pX); - break; - - case BBT_PERPENDICULAR_SELF: - // X-axis is up-vector cross own direction - // Y-axis is own direction cross X-axis - *pX = mCommonUpVector.crossProduct(bb->mDirection); - pX->normalise(); - *pY = bb->mDirection.crossProduct(*pX); // both should be normalised - break; - } - - } - //----------------------------------------------------------------------- - uint32 BillboardSet::getTypeFlags(void) const - { - return SceneManager::FX_TYPE_MASK; - } - //----------------------------------------------------------------------- - void BillboardSet::genPointVertices(const Billboard& bb) - { - RGBA colour = bb.mColour; - // Single vertex per billboard, ignore offsets - // position - *mLockPtr++ = bb.mPosition.x; - *mLockPtr++ = bb.mPosition.y; - *mLockPtr++ = bb.mPosition.z; - // Colour - memcpy(mLockPtr++, &colour, sizeof(RGBA)); - // No texture coords in point rendering - } - void BillboardSet::genQuadVertices(const Vector3* const offsets, const Billboard& bb) - { - RGBA colour = bb.mColour; - - // Texcoords - assert(bb.mUseTexcoordRect || bb.mTexcoordIndex < mTextureCoords.size()); - const Ogre::FloatRect& r = - bb.mUseTexcoordRect ? bb.mTexcoordRect : mTextureCoords[bb.mTexcoordIndex]; - - if (bb.mRotation == Radian(0)) - { - // Left-top - // Positions - *mLockPtr++ = offsets[0].x + bb.mPosition.x; - *mLockPtr++ = offsets[0].y + bb.mPosition.y; - *mLockPtr++ = offsets[0].z + bb.mPosition.z; - // Colour - memcpy(mLockPtr++, &colour, sizeof(RGBA)); - // Texture coords - *mLockPtr++ = r.left; - *mLockPtr++ = r.top; - - // Right-top - // Positions - *mLockPtr++ = offsets[1].x + bb.mPosition.x; - *mLockPtr++ = offsets[1].y + bb.mPosition.y; - *mLockPtr++ = offsets[1].z + bb.mPosition.z; - // Colour - memcpy(mLockPtr++, &colour, sizeof(RGBA)); - // Texture coords - *mLockPtr++ = r.right; - *mLockPtr++ = r.top; - - // Left-bottom - // Positions - *mLockPtr++ = offsets[2].x + bb.mPosition.x; - *mLockPtr++ = offsets[2].y + bb.mPosition.y; - *mLockPtr++ = offsets[2].z + bb.mPosition.z; - // Colour - memcpy(mLockPtr++, &colour, sizeof(RGBA)); - // Texture coords - *mLockPtr++ = r.left; - *mLockPtr++ = r.bottom; - - // Right-bottom - // Positions - *mLockPtr++ = offsets[3].x + bb.mPosition.x; - *mLockPtr++ = offsets[3].y + bb.mPosition.y; - *mLockPtr++ = offsets[3].z + bb.mPosition.z; - // Colour - memcpy(mLockPtr++, &colour, sizeof(RGBA)); - // Texture coords - *mLockPtr++ = r.right; - *mLockPtr++ = r.bottom; - } - else if (mRotationType == BBR_VERTEX) - { - // TODO: Cache axis when billboard type is BBT_POINT or BBT_PERPENDICULAR_COMMON - Vector3 axis = (offsets[3] - offsets[0]).crossProduct(offsets[2] - offsets[1]).normalisedCopy(); - - Matrix3 rotation; - rotation.FromAngleAxis(axis, bb.mRotation); - - Vector3 pt; - - // Left-top - // Positions - pt = rotation * offsets[0]; - *mLockPtr++ = pt.x + bb.mPosition.x; - *mLockPtr++ = pt.y + bb.mPosition.y; - *mLockPtr++ = pt.z + bb.mPosition.z; - // Colour - memcpy(mLockPtr++, &colour, sizeof(RGBA)); - // Texture coords - *mLockPtr++ = r.left; - *mLockPtr++ = r.top; - - // Right-top - // Positions - pt = rotation * offsets[1]; - *mLockPtr++ = pt.x + bb.mPosition.x; - *mLockPtr++ = pt.y + bb.mPosition.y; - *mLockPtr++ = pt.z + bb.mPosition.z; - // Colour - memcpy(mLockPtr++, &colour, sizeof(RGBA)); - // Texture coords - *mLockPtr++ = r.right; - *mLockPtr++ = r.top; - - // Left-bottom - // Positions - pt = rotation * offsets[2]; - *mLockPtr++ = pt.x + bb.mPosition.x; - *mLockPtr++ = pt.y + bb.mPosition.y; - *mLockPtr++ = pt.z + bb.mPosition.z; - // Colour - memcpy(mLockPtr++, &colour, sizeof(RGBA)); - // Texture coords - *mLockPtr++ = r.left; - *mLockPtr++ = r.bottom; - - // Right-bottom - // Positions - pt = rotation * offsets[3]; - *mLockPtr++ = pt.x + bb.mPosition.x; - *mLockPtr++ = pt.y + bb.mPosition.y; - *mLockPtr++ = pt.z + bb.mPosition.z; - // Colour - memcpy(mLockPtr++, &colour, sizeof(RGBA)); - // Texture coords - *mLockPtr++ = r.right; - *mLockPtr++ = r.bottom; - } - else - { - const Real cos_rot ( Math::Cos(bb.mRotation) ); - const Real sin_rot ( Math::Sin(bb.mRotation) ); - - float width = (r.right-r.left)/2; - float height = (r.bottom-r.top)/2; - float mid_u = r.left+width; - float mid_v = r.top+height; - - float cos_rot_w = cos_rot * width; - float cos_rot_h = cos_rot * height; - float sin_rot_w = sin_rot * width; - float sin_rot_h = sin_rot * height; - - // Left-top - // Positions - *mLockPtr++ = offsets[0].x + bb.mPosition.x; - *mLockPtr++ = offsets[0].y + bb.mPosition.y; - *mLockPtr++ = offsets[0].z + bb.mPosition.z; - // Colour - memcpy(mLockPtr++, &colour, sizeof(RGBA)); - // Texture coords - *mLockPtr++ = mid_u - cos_rot_w + sin_rot_h; - *mLockPtr++ = mid_v - sin_rot_w - cos_rot_h; - - // Right-top - // Positions - *mLockPtr++ = offsets[1].x + bb.mPosition.x; - *mLockPtr++ = offsets[1].y + bb.mPosition.y; - *mLockPtr++ = offsets[1].z + bb.mPosition.z; - // Colour - memcpy(mLockPtr++, &colour, sizeof(RGBA)); - // Texture coords - *mLockPtr++ = mid_u + cos_rot_w + sin_rot_h; - *mLockPtr++ = mid_v + sin_rot_w - cos_rot_h; - - // Left-bottom - // Positions - *mLockPtr++ = offsets[2].x + bb.mPosition.x; - *mLockPtr++ = offsets[2].y + bb.mPosition.y; - *mLockPtr++ = offsets[2].z + bb.mPosition.z; - // Colour - memcpy(mLockPtr++, &colour, sizeof(RGBA)); - // Texture coords - *mLockPtr++ = mid_u - cos_rot_w - sin_rot_h; - *mLockPtr++ = mid_v - sin_rot_w + cos_rot_h; - - // Right-bottom - // Positions - *mLockPtr++ = offsets[3].x + bb.mPosition.x; - *mLockPtr++ = offsets[3].y + bb.mPosition.y; - *mLockPtr++ = offsets[3].z + bb.mPosition.z; - // Colour - memcpy(mLockPtr++, &colour, sizeof(RGBA)); - // Texture coords - *mLockPtr++ = mid_u + cos_rot_w - sin_rot_h; - *mLockPtr++ = mid_v + sin_rot_w + cos_rot_h; - } - } - //----------------------------------------------------------------------- - void BillboardSet::genVertOffsets(Real inleft, Real inright, Real intop, Real inbottom, - Real width, Real height, const Vector3& x, const Vector3& y, Vector3* pDestVec) - { - Vector3 vLeftOff, vRightOff, vTopOff, vBottomOff; - /* Calculate default offsets. Scale the axes by - parametric offset and dimensions, ready to be added to - positions. - */ - - vLeftOff = x * ( inleft * width ); - vRightOff = x * ( inright * width ); - vTopOff = y * ( intop * height ); - vBottomOff = y * ( inbottom * height ); - - // Make final offsets to vertex positions - pDestVec[0] = vLeftOff + vTopOff; - pDestVec[1] = vRightOff + vTopOff; - pDestVec[2] = vLeftOff + vBottomOff; - pDestVec[3] = vRightOff + vBottomOff; - - } - //----------------------------------------------------------------------- - const String& BillboardSet::getMovableType(void) const - { - return MOT_BILLBOARD_SET; - } - //----------------------------------------------------------------------- - Real BillboardSet::getSquaredViewDepth(const Camera* const cam) const - { - assert(mParentNode); - return mParentNode->getSquaredViewDepth(cam); - } - //----------------------------------------------------------------------- - const LightList& BillboardSet::getLights(void) const - { - // It's actually quite unlikely that this will be called, - // because most billboards are unlit, but here we go anyway - return queryLights(); - } - //--------------------------------------------------------------------- - void BillboardSet::visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables) - { - // only one renderable - visitor->visit(this, 0, false); - } - - - void BillboardSet::setTextureCoords(const std::vector& coords) - { - if(coords.empty()) { - setTextureStacksAndSlices(1, 1); - return; - } - mTextureCoords = coords; - } - - void BillboardSet::setTextureStacksAndSlices( uchar stacks, uchar slices ) -{ - if(stacks == 0) stacks = 1; - if(slices == 0) slices = 1; - // clear out any previous allocation (as vectors may not shrink) - TextureCoordSets().swap(mTextureCoords); - // make room - mTextureCoords.resize((size_t)stacks * slices); - unsigned int coordIndex = 0; - // spread the U and V coordinates across the rects - for(uint v = 0; v < stacks; ++v) { - // (float)X / X is guaranteed to be == 1.0f for X up to 8 million, so - // our range of 1..256 is quite enough to guarantee perfect coverage. - float top = (float)v / (float)stacks; - float bottom = ((float)v + 1) / (float)stacks; - for(uint u = 0; u < slices; ++u) { - Ogre::FloatRect & r = mTextureCoords[coordIndex]; - r.left = (float)u / (float)slices; - r.bottom = bottom; - r.right = ((float)u + 1) / (float)slices; - r.top = top; - ++coordIndex; - } - } - assert( coordIndex == (size_t)stacks * slices ); - } - //----------------------------------------------------------------------- - void BillboardSet::setPointRenderingEnabled(bool enabled) - { - // Override point rendering if not supported - if (enabled && !Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_POINT_SPRITES)) - { - enabled = false; - } - - if (enabled != mPointRendering) - { - mPointRendering = enabled; - // Different buffer structure (1 or 4 verts per billboard) - _destroyBuffers(); - } - } - - //----------------------------------------------------------------------- - void BillboardSet::setAutoUpdate(bool autoUpdate) - { - // Case auto update buffers changed we have to destroy the current buffers - // since their usage will be different. - if (autoUpdate != mAutoUpdate) - { - mAutoUpdate = autoUpdate; - _destroyBuffers(); - } - } - - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - const String MOT_BILLBOARD_SET = "BillboardSet"; - //----------------------------------------------------------------------- - const String& BillboardSetFactory::getType(void) const - { - return MOT_BILLBOARD_SET; - } - //----------------------------------------------------------------------- - MovableObject* BillboardSetFactory::createInstanceImpl( const String& name, - const NameValuePairList* params) - { - // may have parameters - bool externalData = false; - unsigned int poolSize = 0; - - if (params != 0) - { - NameValuePairList::const_iterator ni = params->find("poolSize"); - if (ni != params->end()) - { - poolSize = StringConverter::parseUnsignedInt(ni->second); - } - ni = params->find("externalData"); - if (ni != params->end()) - { - externalData = StringConverter::parseBool(ni->second); - } - } - - if (poolSize > 0) - { - return OGRE_NEW BillboardSet(name, poolSize, externalData); - } - else - { - return OGRE_NEW BillboardSet(name); - } - } -} diff --git a/OgreMain/src/OgreBone.cpp b/OgreMain/src/OgreBone.cpp deleted file mode 100644 index c35e63dc8d1..00000000000 --- a/OgreMain/src/OgreBone.cpp +++ /dev/null @@ -1,133 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -namespace Ogre { - - //--------------------------------------------------------------------- - Bone::Bone(unsigned short handle, Skeleton* creator) - : Node(), mCreator(creator), mHandle(handle), mManuallyControlled(false) - { - } - //--------------------------------------------------------------------- - Bone::Bone(const String& name, unsigned short handle, Skeleton* creator) - : Node(name), mCreator(creator), mHandle(handle), mManuallyControlled(false) - { - } - //--------------------------------------------------------------------- - Bone::~Bone() - { - } - //--------------------------------------------------------------------- - Bone* Bone::createChild(unsigned short handle, const Vector3& inTranslate, - const Quaternion& inRotate) - { - Bone* retBone = mCreator->createBone(handle); - retBone->translate(inTranslate); - retBone->rotate(inRotate); - this->addChild(retBone); - return retBone; - } - //--------------------------------------------------------------------- - Node* Bone::createChildImpl(void) - { - return mCreator->createBone(); - } - //--------------------------------------------------------------------- - Node* Bone::createChildImpl(const String& name) - { - return mCreator->createBone(name); - } - //--------------------------------------------------------------------- - void Bone::setBindingPose(void) - { - setInitialState(); - - // Save inverse derived position/scale/orientation, used for calculate offset transform later - mBindDerivedInversePosition = - _getDerivedPosition(); - mBindDerivedInverseScale = Vector3::UNIT_SCALE / _getDerivedScale(); - mBindDerivedInverseOrientation = _getDerivedOrientation().Inverse(); - } - //--------------------------------------------------------------------- - void Bone::reset(void) - { - resetToInitialState(); - } - //--------------------------------------------------------------------- - void Bone::setManuallyControlled(bool manuallyControlled) - { - mManuallyControlled = manuallyControlled; - mCreator->_notifyManualBoneStateChange(this); - } - //--------------------------------------------------------------------- - bool Bone::isManuallyControlled() const { - return mManuallyControlled; - } - //--------------------------------------------------------------------- - void Bone::_getOffsetTransform(Affine3& m) const - { - // Combine scale with binding pose inverse scale, - // NB just combine as equivalent axes, no shearing - Vector3 locScale = _getDerivedScale() * mBindDerivedInverseScale; - - // Combine orientation with binding pose inverse orientation - Quaternion locRotate = _getDerivedOrientation() * mBindDerivedInverseOrientation; - - // Combine position with binding pose inverse position, - // Note that translation is relative to scale & rotation, - // so first reverse transform original derived position to - // binding pose bone space, and then transform to current - // derived bone space. - Vector3 locTranslate = _getDerivedPosition() + locRotate * (locScale * mBindDerivedInversePosition); - - m.makeTransform(locTranslate, locScale, locRotate); - } - //--------------------------------------------------------------------- - unsigned short Bone::getHandle(void) const - { - return mHandle; - } - //--------------------------------------------------------------------- - void Bone::needUpdate(bool forceParentUpdate) - { - Node::needUpdate(forceParentUpdate); - - if (isManuallyControlled()) - { - // Dirty the skeleton if manually controlled so animation can be updated - mCreator->_notifyManualBonesDirty(); - } - - } - - - - - -} - diff --git a/OgreMain/src/OgreBuiltinMovableFactories.h b/OgreMain/src/OgreBuiltinMovableFactories.h deleted file mode 100644 index d14f6b10bc0..00000000000 --- a/OgreMain/src/OgreBuiltinMovableFactories.h +++ /dev/null @@ -1,87 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#ifndef __BUILTIN_MOVABLE_FACTORIES_H_ -#define __BUILTIN_MOVABLE_FACTORIES_H_ - -#include -#include - -namespace Ogre -{ -class BillboardChainFactory : public MovableObjectFactory -{ - MovableObject* createInstanceImpl( const String& name, const NameValuePairList* params) override; - -public: - const String& getType(void) const override; -}; - -class BillboardSetFactory : public MovableObjectFactory -{ - MovableObject* createInstanceImpl( const String& name, const NameValuePairList* params) override; - -public: - const String& getType(void) const override; -}; - -class EntityFactory : public MovableObjectFactory -{ - MovableObject* createInstanceImpl( const String& name, const NameValuePairList* params) override; - -public: - const String& getType(void) const override; -}; - -class LightFactory : public MovableObjectFactory -{ - MovableObject* createInstanceImpl( const String& name, const NameValuePairList* params) override; - -public: - const String& getType(void) const override; -}; - -class ManualObjectFactory : public MovableObjectFactory -{ - MovableObject* createInstanceImpl( const String& name, const NameValuePairList* params) override; - -public: - const String& getType(void) const override; -}; - -class ParticleSystemFactory : public MovableObjectFactory -{ - MovableObject* createInstanceImpl(const String& name, const NameValuePairList* params) override; - -public: - const String& getType(void) const override; -}; - -class Rectangle2DFactory : public MovableObjectFactory -{ - MovableObject* createInstanceImpl(const String& name, const NameValuePairList* params) override; - -public: - const String& getType(void) const override { return MOT_RECTANGLE2D; } -}; - -class RibbonTrailFactory : public MovableObjectFactory -{ - MovableObject* createInstanceImpl( const String& name, const NameValuePairList* params) override; - -public: - const String& getType(void) const override; -}; - -class StaticGeometryFactory : public MovableObjectFactory -{ - MovableObject* createInstanceImpl( const String& name, const NameValuePairList* params) override { return NULL; } - -public: - const String& getType(void) const override { return MOT_STATIC_GEOMETRY; } -}; -} // namespace Ogre - -#endif \ No newline at end of file diff --git a/OgreMain/src/OgreBuiltinScriptTranslators.h b/OgreMain/src/OgreBuiltinScriptTranslators.h deleted file mode 100644 index 76e11c97759..00000000000 --- a/OgreMain/src/OgreBuiltinScriptTranslators.h +++ /dev/null @@ -1,204 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __BUILTIN_SCRIPTTRANSLATORS_H_ -#define __BUILTIN_SCRIPTTRANSLATORS_H_ - -#include "OgreScriptTranslator.h" - -namespace Ogre{ - /************************************************************************** - * Material compilation section - *************************************************************************/ - class MaterialTranslator : public ScriptTranslator - { - protected: - Material *mMaterial; - Ogre::AliasTextureNamePairList mTextureAliases; - public: - MaterialTranslator(); - void translate(ScriptCompiler *compiler, const AbstractNodePtr &node) override; - }; - - class TechniqueTranslator : public ScriptTranslator - { - protected: - Technique *mTechnique; - public: - TechniqueTranslator(); - void translate(ScriptCompiler *compiler, const AbstractNodePtr &node) override; - }; - - class PassTranslator : public ScriptTranslator - { - protected: - Pass *mPass; - public: - PassTranslator(); - void translate(ScriptCompiler *compiler, const AbstractNodePtr &node) override; - protected: - void translateProgramRef(GpuProgramType type, ScriptCompiler *compiler, ObjectAbstractNode *node); - void translateShadowCasterProgramRef(GpuProgramType type, ScriptCompiler *compiler, ObjectAbstractNode *node); - void translateShadowReceiverProgramRef(GpuProgramType type, ScriptCompiler *compiler, ObjectAbstractNode *node); - }; - - class TextureUnitTranslator : public ScriptTranslator - { - protected: - TextureUnitState *mUnit; - public: - TextureUnitTranslator(); - void translate(ScriptCompiler *compiler, const AbstractNodePtr &node) override; - }; - - struct SamplerTranslator : public ScriptTranslator - { - static void translateSamplerParam(ScriptCompiler *compiler, const SamplerPtr& sampler, PropertyAbstractNode* node); - void translate(ScriptCompiler *compiler, const AbstractNodePtr &node) override; - }; - - class TextureSourceTranslator : public ScriptTranslator - { - public: - TextureSourceTranslator(); - void translate(ScriptCompiler *compiler, const AbstractNodePtr &node) override; - }; - - class GpuProgramTranslator : public ScriptTranslator - { - public: - GpuProgramTranslator(); - void translate(ScriptCompiler *compiler, const AbstractNodePtr &node) override; - protected: - void translateGpuProgram(ScriptCompiler *compiler, ObjectAbstractNode *obj, String language); - public: - static void translateProgramParameters(ScriptCompiler *compiler, const GpuProgramParametersSharedPtr& params, ObjectAbstractNode *obj); - }; - - class SharedParamsTranslator : public ScriptTranslator - { - public: - SharedParamsTranslator(); - void translate(ScriptCompiler *compiler, const AbstractNodePtr &node) override; - protected: - }; - - /************************************************************************** - * Particle System section - *************************************************************************/ - class ParticleSystemTranslator : public ScriptTranslator - { - protected: - Ogre::ParticleSystem *mSystem; - public: - ParticleSystemTranslator(); - void translate(ScriptCompiler *compiler, const AbstractNodePtr &node) override; - }; - class ParticleEmitterTranslator : public ScriptTranslator - { - protected: - Ogre::ParticleEmitter *mEmitter; - public: - ParticleEmitterTranslator(); - void translate(ScriptCompiler *compiler, const AbstractNodePtr &node) override; - }; - class ParticleAffectorTranslator : public ScriptTranslator - { - protected: - Ogre::ParticleAffector *mAffector; - public: - ParticleAffectorTranslator(); - void translate(ScriptCompiler *compiler, const AbstractNodePtr &node) override; - }; - - /************************************************************************** - * Compositor section - *************************************************************************/ - class CompositorTranslator : public ScriptTranslator - { - protected: - Compositor *mCompositor; - public: - CompositorTranslator(); - void translate(ScriptCompiler *compiler, const AbstractNodePtr &node) override; - }; - class CompositionTechniqueTranslator : public ScriptTranslator - { - protected: - CompositionTechnique *mTechnique; - public: - CompositionTechniqueTranslator(); - void translate(ScriptCompiler *compiler, const AbstractNodePtr &node) override; - }; - class CompositionTargetPassTranslator : public ScriptTranslator - { - protected: - CompositionTargetPass *mTarget; - public: - CompositionTargetPassTranslator(); - void translate(ScriptCompiler *compiler, const AbstractNodePtr &node) override; - }; - class CompositionPassTranslator : public ScriptTranslator - { - protected: - CompositionPass *mPass; - public: - CompositionPassTranslator(); - void translate(ScriptCompiler *compiler, const AbstractNodePtr &node) override; - }; - /************************************************************************** - * BuiltinScriptTranslatorManager - *************************************************************************/ - /// This class manages the builtin translators - class BuiltinScriptTranslatorManager : public ScriptTranslatorManager - { - private: - MaterialTranslator mMaterialTranslator; - TechniqueTranslator mTechniqueTranslator; - PassTranslator mPassTranslator; - TextureUnitTranslator mTextureUnitTranslator; - SamplerTranslator mSamplerTranslator; - TextureSourceTranslator mTextureSourceTranslator; - GpuProgramTranslator mGpuProgramTranslator; - SharedParamsTranslator mSharedParamsTranslator; - ParticleSystemTranslator mParticleSystemTranslator; - ParticleEmitterTranslator mParticleEmitterTranslator; - ParticleAffectorTranslator mParticleAffectorTranslator; - CompositorTranslator mCompositorTranslator; - CompositionTechniqueTranslator mCompositionTechniqueTranslator; - CompositionTargetPassTranslator mCompositionTargetPassTranslator; - CompositionPassTranslator mCompositionPassTranslator; - public: - BuiltinScriptTranslatorManager(); - /// Returns a manager for the given object abstract node, or null if it is not supported - ScriptTranslator *getTranslator(const AbstractNodePtr &node) override; - }; -} - -#endif - diff --git a/OgreMain/src/OgreCamera.cpp b/OgreMain/src/OgreCamera.cpp deleted file mode 100644 index 3a34386a75b..00000000000 --- a/OgreMain/src/OgreCamera.cpp +++ /dev/null @@ -1,1167 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreViewport.h" -#include "OgreMovablePlane.h" - -namespace Ogre { - - const String MOT_CAMERA = "Camera"; - //----------------------------------------------------------------------- - Camera::Camera( const String& name, SceneManager* sm) - : Frustum(name), - mWindowSet(false), - mAutoAspectRatio(false), - mUseRenderingDistance(true), - mUseMinPixelSize(false), -#ifdef OGRE_NODELESS_POSITIONING - mOrientation(Quaternion::IDENTITY), - mPosition(Vector3::ZERO), - mAutoTrackTarget(0), - mAutoTrackOffset(Vector3::ZERO), -#endif - mSceneLodFactor(1.0f), - mSceneLodFactorInv(1.0f), - mLastViewport(0), - mCullFrustum(0), - mLodCamera(0), - mPixelDisplayRatio(0), - mSortMode(SM_DISTANCE), - mSceneDetail(PM_SOLID) - { - - // Reasonable defaults to camera params - mFOVy = Radian(Math::PI/4.0f); - mNearDist = 100.0f; - mFarDist = 100000.0f; - mAspect = 1.33333333333333f; - mProjType = PT_PERSPECTIVE; - -#ifdef OGRE_NODELESS_POSITIONING - mYawFixed = true; // Default to fixed yaw, like freelook since most people expect this - mYawFixedAxis = Vector3::UNIT_Y; -#endif - - invalidateFrustum(); - invalidateView(); - - // Init matrices - mViewMatrix = Affine3::ZERO; - - mParentNode = 0; - - // no reflection - mReflect = false; - - mVisible = false; - mManager = sm; - } - - //----------------------------------------------------------------------- - Camera::~Camera() - { - ListenerList listenersCopy = mListeners; - for (auto & i : listenersCopy) - { - i->cameraDestroyed(this); - } - } - //----------------------------------------------------------------------- - SceneManager* Camera::getSceneManager(void) const - { - return mManager; - } - - - //----------------------------------------------------------------------- - void Camera::setPolygonMode(PolygonMode sd) - { - mSceneDetail = sd; - } - - //----------------------------------------------------------------------- - PolygonMode Camera::getPolygonMode(void) const - { - return mSceneDetail; - } -#ifdef OGRE_NODELESS_POSITIONING - //----------------------------------------------------------------------- - void Camera::setPosition(Real x, Real y, Real z) - { - mPosition.x = x; - mPosition.y = y; - mPosition.z = z; - invalidateView(); - } - - //----------------------------------------------------------------------- - void Camera::setPosition(const Vector3& vec) - { - mPosition = vec; - invalidateView(); - } - - //----------------------------------------------------------------------- - const Vector3& Camera::getPosition(void) const - { - return mPosition; - } - - //----------------------------------------------------------------------- - void Camera::move(const Vector3& vec) - { - mPosition = mPosition + vec; - invalidateView(); - } - - //----------------------------------------------------------------------- - void Camera::moveRelative(const Vector3& vec) - { - // Transform the axes of the relative vector by camera's local axes - Vector3 trans = mOrientation * vec; - - mPosition = mPosition + trans; - invalidateView(); - } - - //----------------------------------------------------------------------- - void Camera::setDirection(Real x, Real y, Real z) - { - OGRE_IGNORE_DEPRECATED_BEGIN - setDirection(Vector3(x,y,z)); - OGRE_IGNORE_DEPRECATED_END - } - - //----------------------------------------------------------------------- - void Camera::setDirection(const Vector3& vec) - { - // Do nothing if given a zero vector - // (Replaced assert since this could happen with auto tracking camera and - // camera passes through the lookAt point) - if (vec == Vector3::ZERO) return; - - // Remember, camera points down -Z of local axes! - // Therefore reverse direction of direction vector before determining local Z - Vector3 zAdjustVec = -vec; - zAdjustVec.normalise(); - - Quaternion targetWorldOrientation; - - if( mYawFixed ) - { - targetWorldOrientation = Math::lookRotation(zAdjustVec, mYawFixedAxis); - } - else - { - - // Get axes from current quaternion - Vector3 axes[3]; - updateView(); - mRealOrientation.ToAxes(axes); - Quaternion rotQuat; - if ( (axes[2]+zAdjustVec).squaredLength() < 0.00005f) - { - // Oops, a 180 degree turn (infinite possible rotation axes) - // Default to yaw i.e. use current UP - rotQuat.FromAngleAxis(Radian(Math::PI), axes[1]); - } - else - { - // Derive shortest arc to new direction - rotQuat = axes[2].getRotationTo(zAdjustVec); - - } - targetWorldOrientation = rotQuat * mRealOrientation; - } - - // transform to parent space - if (mParentNode) - { - mOrientation = mParentNode->convertWorldToLocalOrientation(targetWorldOrientation); - } - else - { - mOrientation = targetWorldOrientation; - } - - // TODO If we have a fixed yaw axis, we mustn't break it by using the - // shortest arc because this will sometimes cause a relative yaw - // which will tip the camera - - invalidateView(); - - } - - //----------------------------------------------------------------------- - Vector3 Camera::getDirection(void) const - { - // Direction points down -Z by default - return mOrientation * -Vector3::UNIT_Z; - } - - //----------------------------------------------------------------------- - Vector3 Camera::getUp(void) const - { - return mOrientation * Vector3::UNIT_Y; - } - - //----------------------------------------------------------------------- - Vector3 Camera::getRight(void) const - { - return mOrientation * Vector3::UNIT_X; - } - - //----------------------------------------------------------------------- - void Camera::lookAt(const Vector3& targetPoint) - { - updateView(); - OGRE_IGNORE_DEPRECATED_BEGIN - this->setDirection(targetPoint - mRealPosition); - OGRE_IGNORE_DEPRECATED_END - } - - //----------------------------------------------------------------------- - void Camera::lookAt( Real x, Real y, Real z ) - { - Vector3 vTemp( x, y, z ); - OGRE_IGNORE_DEPRECATED_BEGIN - this->lookAt(vTemp); - OGRE_IGNORE_DEPRECATED_END - } - - //----------------------------------------------------------------------- - void Camera::roll(const Radian& angle) - { - // Rotate around local Z axis - Vector3 zAxis = mOrientation * Vector3::UNIT_Z; - OGRE_IGNORE_DEPRECATED_BEGIN - rotate(zAxis, angle); - OGRE_IGNORE_DEPRECATED_END - - invalidateView(); - } - - //----------------------------------------------------------------------- - void Camera::yaw(const Radian& angle) - { - Vector3 yAxis; - - if (mYawFixed) - { - // Rotate around fixed yaw axis - yAxis = mYawFixedAxis; - } - else - { - // Rotate around local Y axis - yAxis = mOrientation * Vector3::UNIT_Y; - } - - OGRE_IGNORE_DEPRECATED_BEGIN - rotate(yAxis, angle); - OGRE_IGNORE_DEPRECATED_END - - invalidateView(); - } - - //----------------------------------------------------------------------- - void Camera::pitch(const Radian& angle) - { - // Rotate around local X axis - Vector3 xAxis = mOrientation * Vector3::UNIT_X; - OGRE_IGNORE_DEPRECATED_BEGIN - rotate(xAxis, angle); - OGRE_IGNORE_DEPRECATED_END - - invalidateView(); - - } - - //----------------------------------------------------------------------- - void Camera::rotate(const Vector3& axis, const Radian& angle) - { - Quaternion q; - q.FromAngleAxis(angle,axis); - OGRE_IGNORE_DEPRECATED_BEGIN - rotate(q); - OGRE_IGNORE_DEPRECATED_END - } - - //----------------------------------------------------------------------- - void Camera::rotate(const Quaternion& q) - { - // Note the order of the mult, i.e. q comes after - - // Normalise the quat to avoid cumulative problems with precision - Quaternion qres = q * mOrientation; - qres.normalise(); - mOrientation = qres; - - invalidateView(); - - } - - //----------------------------------------------------------------------- - void Camera::setFixedYawAxis(bool useFixed, const Vector3& fixedAxis) - { - mYawFixed = useFixed; - mYawFixedAxis = fixedAxis; - } - //----------------------------------------------------------------------- - const Quaternion& Camera::getOrientation(void) const - { - return mOrientation; - } - //----------------------------------------------------------------------- - void Camera::_autoTrack(void) - { - // NB assumes that all scene nodes have been updated - if (mAutoTrackTarget) - { - OGRE_IGNORE_DEPRECATED_BEGIN - lookAt(mAutoTrackTarget->_getFullTransform() * mAutoTrackOffset); - OGRE_IGNORE_DEPRECATED_END - } - } - - //----------------------------------------------------------------------- - void Camera::setOrientation(const Quaternion& q) - { - mOrientation = q; - mOrientation.normalise(); - invalidateView(); - } - //----------------------------------------------------------------------- - void Camera::setAutoTracking(bool enabled, SceneNode* const target, - const Vector3& offset) - { - if (enabled) - { - assert (target != 0 && "target cannot be a null pointer if tracking is enabled"); - mAutoTrackTarget = target; - mAutoTrackOffset = offset; - } - else - { - mAutoTrackTarget = 0; - } - } - //----------------------------------------------------------------------- - const Vector3& Camera::getPositionForViewUpdate(void) const - { - // Note no update, because we're calling this from the update! - return mRealPosition; - } - //----------------------------------------------------------------------- - const Quaternion& Camera::getOrientationForViewUpdate(void) const - { - return mRealOrientation; - } -#endif - //----------------------------------------------------------------------- - bool Camera::isViewOutOfDate(void) const - { -#ifdef OGRE_NODELESS_POSITIONING - // Overridden from Frustum to use local orientation / position offsets - // Attached to node? - if (mParentNode != 0) - { - if (mRecalcView || - mParentNode->_getDerivedOrientation() != mLastParentOrientation || - mParentNode->_getDerivedPosition() != mLastParentPosition) - { - // Ok, we're out of date with SceneNode we're attached to - mLastParentOrientation = mParentNode->_getDerivedOrientation(); - mLastParentPosition = mParentNode->_getDerivedPosition(); - mRealOrientation = mParentNode->convertLocalToWorldOrientation(mOrientation); - mRealPosition = mParentNode->convertLocalToWorldPosition(mPosition); - mRecalcView = true; - mRecalcWindow = true; - } - } - else - { - // Rely on own updates - mRealOrientation = mOrientation; - mRealPosition = mPosition; - } - - // Deriving reflection from linked plane? - if (mReflect && mLinkedReflectPlane && - !(mLastLinkedReflectionPlane == mLinkedReflectPlane->_getDerivedPlane())) - { - mReflectPlane = mLinkedReflectPlane->_getDerivedPlane(); - mReflectMatrix = Math::buildReflectionMatrix(mReflectPlane); - mLastLinkedReflectionPlane = mLinkedReflectPlane->_getDerivedPlane(); - mRecalcView = true; - mRecalcWindow = true; - } -#else - if(Frustum::isViewOutOfDate()) - mRecalcWindow = true; -#endif - - // Deriving reflected orientation / position - if (mRecalcView) - { -#ifndef OGRE_NODELESS_POSITIONING - const auto& mRealOrientation = mLastParentOrientation; - const auto& mRealPosition = mLastParentPosition; -#endif - - if (mReflect) - { - // Calculate reflected orientation, use up-vector as fallback axis. - Vector3 dir = -mRealOrientation.zAxis(); - Vector3 rdir = dir.reflect(mReflectPlane.normal); - Vector3 up = mRealOrientation.yAxis(); - mDerivedOrientation = dir.getRotationTo(rdir, up) * mRealOrientation; - - // Calculate reflected position. - mDerivedPosition = mReflectMatrix * mRealPosition; - } - else - { - mDerivedOrientation = mRealOrientation; - mDerivedPosition = mRealPosition; - } - } - - return mRecalcView; - - } - - // ------------------------------------------------------------------- - void Camera::invalidateView() const - { - mRecalcWindow = true; - Frustum::invalidateView(); - } - // ------------------------------------------------------------------- - void Camera::invalidateFrustum(void) const - { - mRecalcWindow = true; - Frustum::invalidateFrustum(); - } - //----------------------------------------------------------------------- - void Camera::_renderScene(Viewport *vp) - { - OgreProfileBeginGPUEvent(getName()); - - //update the pixel display ratio - if (mProjType == Ogre::PT_PERSPECTIVE) - { - mPixelDisplayRatio = (2 * Ogre::Math::Tan(mFOVy * 0.5f)) / vp->getActualHeight(); - } - else - { - mPixelDisplayRatio = -mExtents.height() / vp->getActualHeight(); - } - - //notify prerender scene - ListenerList listenersCopy = mListeners; - for (auto & i : listenersCopy) - { - i->cameraPreRenderScene(this); - } - - //render scene - mManager->_renderScene(this, vp); - - // Listener list may have change - listenersCopy = mListeners; - - //notify postrender scene - for (auto & i : listenersCopy) - { - i->cameraPostRenderScene(this); - } - OgreProfileEndGPUEvent(getName()); - } - //--------------------------------------------------------------------- - void Camera::addListener(Listener* l) - { - if (std::find(mListeners.begin(), mListeners.end(), l) == mListeners.end()) - mListeners.push_back(l); - } - //--------------------------------------------------------------------- - void Camera::removeListener(Listener* l) - { - ListenerList::iterator i = std::find(mListeners.begin(), mListeners.end(), l); - if (i != mListeners.end()) - mListeners.erase(i); - } - //----------------------------------------------------------------------- - std::ostream& operator<<( std::ostream& o, const Camera& c ) - { - o << "Camera(Name='" << c.mName << "'"; -#ifdef OGRE_NODELESS_POSITIONING - o << ", pos=" << c.mPosition << ", direction=" << -c.mOrientation.zAxis(); -#else - o << ", pos=" << c.mLastParentPosition << ", direction=" << -c.mLastParentOrientation.zAxis(); -#endif - o << ",near=" << c.mNearDist; - o << ", far=" << c.mFarDist << ", FOVy=" << c.mFOVy.valueDegrees(); - o << ", aspect=" << c.mAspect << ", "; - o << ", xoffset=" << c.mFrustumOffset.x << ", yoffset=" << c.mFrustumOffset.y; - o << ", focalLength=" << c.mFocalLength << ", "; - o << "NearFrustumPlane=" << c.mFrustumPlanes[FRUSTUM_PLANE_NEAR] << ", "; - o << "FarFrustumPlane=" << c.mFrustumPlanes[FRUSTUM_PLANE_FAR] << ", "; - o << "LeftFrustumPlane=" << c.mFrustumPlanes[FRUSTUM_PLANE_LEFT] << ", "; - o << "RightFrustumPlane=" << c.mFrustumPlanes[FRUSTUM_PLANE_RIGHT] << ", "; - o << "TopFrustumPlane=" << c.mFrustumPlanes[FRUSTUM_PLANE_TOP] << ", "; - o << "BottomFrustumPlane=" << c.mFrustumPlanes[FRUSTUM_PLANE_BOTTOM]; - o << ")"; - - return o; - } - //----------------------------------------------------------------------- - void Camera::_notifyRenderedFaces(unsigned int numfaces) - { - mVisFacesLastRender = numfaces; - } - - //----------------------------------------------------------------------- - void Camera::_notifyRenderedBatches(unsigned int numbatches) - { - mVisBatchesLastRender = numbatches; - } - - //----------------------------------------------------------------------- - unsigned int Camera::_getNumRenderedFaces(void) const - { - return mVisFacesLastRender; - } - //----------------------------------------------------------------------- - unsigned int Camera::_getNumRenderedBatches(void) const - { - return mVisBatchesLastRender; - } - //----------------------------------------------------------------------- - const Quaternion& Camera::getDerivedOrientation(void) const - { - updateView(); - return mDerivedOrientation; - } - //----------------------------------------------------------------------- - const Vector3& Camera::getDerivedPosition(void) const - { - updateView(); - return mDerivedPosition; - } - //----------------------------------------------------------------------- - Vector3 Camera::getDerivedDirection(void) const - { - // Direction points down -Z - updateView(); - return -mDerivedOrientation.zAxis(); - } - //----------------------------------------------------------------------- - Vector3 Camera::getDerivedUp(void) const - { - updateView(); - return mDerivedOrientation.yAxis(); - } - //----------------------------------------------------------------------- - Vector3 Camera::getDerivedRight(void) const - { - updateView(); - return mDerivedOrientation.xAxis(); - } - //----------------------------------------------------------------------- - const Quaternion& Camera::getRealOrientation(void) const - { - updateView(); -#ifdef OGRE_NODELESS_POSITIONING - return mRealOrientation; -#else - return mLastParentOrientation; -#endif - } - //----------------------------------------------------------------------- - const Vector3& Camera::getRealPosition(void) const - { - updateView(); -#ifdef OGRE_NODELESS_POSITIONING - return mRealPosition; -#else - return mLastParentPosition; -#endif - } - //----------------------------------------------------------------------- - Vector3 Camera::getRealDirection(void) const - { - // Direction points down -Z - updateView(); -#ifdef OGRE_NODELESS_POSITIONING - return mRealOrientation * Vector3::NEGATIVE_UNIT_Z; -#else - return -mLastParentOrientation.zAxis(); -#endif - } - //----------------------------------------------------------------------- - Vector3 Camera::getRealUp(void) const - { - updateView(); -#ifdef OGRE_NODELESS_POSITIONING - return mRealOrientation * Vector3::UNIT_Y; -#else - return mLastParentOrientation.yAxis(); -#endif - } - //----------------------------------------------------------------------- - Vector3 Camera::getRealRight(void) const - { - updateView(); -#ifdef OGRE_NODELESS_POSITIONING - return mRealOrientation * Vector3::UNIT_X; -#else - return mLastParentOrientation.xAxis(); -#endif - } - //----------------------------------------------------------------------- - const String& Camera::getMovableType(void) const - { - return MOT_CAMERA; - } - //----------------------------------------------------------------------- - void Camera::setLodBias(Real factor) - { - assert(factor > 0.0f && "Bias factor must be > 0!"); - mSceneLodFactor = factor; - mSceneLodFactorInv = 1.0f / factor; - } - //----------------------------------------------------------------------- - Real Camera::getLodBias(void) const - { - return mSceneLodFactor; - } - //----------------------------------------------------------------------- - Real Camera::_getLodBiasInverse(void) const - { - return mSceneLodFactorInv; - } - //----------------------------------------------------------------------- - void Camera::setLodCamera(const Camera* lodCam) - { - if (lodCam == this) - mLodCamera = 0; - else - mLodCamera = lodCam; - } - //--------------------------------------------------------------------- - const Camera* Camera::getLodCamera() const - { - return mLodCamera? mLodCamera : this; - } - //----------------------------------------------------------------------- - Ray Camera::getCameraToViewportRay(Real screenX, Real screenY) const - { - Ray ret; - getCameraToViewportRay(screenX, screenY, &ret); - return ret; - } - //--------------------------------------------------------------------- - void Camera::getCameraToViewportRay(Real screenX, Real screenY, Ray* outRay) const - { - Matrix4 inverseVP = (getProjectionMatrix() * getViewMatrix(true)).inverse(); - - Real nx = (2.0f * screenX) - 1.0f; - Real ny = 1.0f - (2.0f * screenY); - Vector3 nearPoint(nx, ny, -1.f); - // Use midPoint rather than far point to avoid issues with infinite projection - Vector3 midPoint (nx, ny, 0.0f); - - // Get ray origin and ray target on near plane in world space - Vector3 rayOrigin, rayTarget; - - rayOrigin = inverseVP * nearPoint; - rayTarget = inverseVP * midPoint; - - Vector3 rayDirection = rayTarget - rayOrigin; - rayDirection.normalise(); - - outRay->setOrigin(rayOrigin); - outRay->setDirection(rayDirection); - } - //--------------------------------------------------------------------- - PlaneBoundedVolume Camera::getCameraToViewportBoxVolume(Real screenLeft, - Real screenTop, Real screenRight, Real screenBottom, bool includeFarPlane) - { - PlaneBoundedVolume vol; - getCameraToViewportBoxVolume(screenLeft, screenTop, screenRight, screenBottom, - &vol, includeFarPlane); - return vol; - - } - //---------------------------------------------------------------------() - void Camera::getCameraToViewportBoxVolume(Real screenLeft, - Real screenTop, Real screenRight, Real screenBottom, - PlaneBoundedVolume* outVolume, bool includeFarPlane) - { - outVolume->planes.clear(); - - if (mProjType == PT_PERSPECTIVE) - { - - // Use the corner rays to generate planes - Ray ul = getCameraToViewportRay(screenLeft, screenTop); - Ray ur = getCameraToViewportRay(screenRight, screenTop); - Ray bl = getCameraToViewportRay(screenLeft, screenBottom); - Ray br = getCameraToViewportRay(screenRight, screenBottom); - - - Vector3 normal; - // top plane - normal = ul.getDirection().crossProduct(ur.getDirection()); - normal.normalise(); - outVolume->planes.push_back( - Plane(normal, getDerivedPosition())); - - // right plane - normal = ur.getDirection().crossProduct(br.getDirection()); - normal.normalise(); - outVolume->planes.push_back( - Plane(normal, getDerivedPosition())); - - // bottom plane - normal = br.getDirection().crossProduct(bl.getDirection()); - normal.normalise(); - outVolume->planes.push_back( - Plane(normal, getDerivedPosition())); - - // left plane - normal = bl.getDirection().crossProduct(ul.getDirection()); - normal.normalise(); - outVolume->planes.push_back( - Plane(normal, getDerivedPosition())); - - } - else - { - // ortho planes are parallel to frustum planes - - Ray ul = getCameraToViewportRay(screenLeft, screenTop); - Ray br = getCameraToViewportRay(screenRight, screenBottom); - - updateFrustumPlanes(); - outVolume->planes.push_back( - Plane(mFrustumPlanes[FRUSTUM_PLANE_TOP].normal, ul.getOrigin())); - outVolume->planes.push_back( - Plane(mFrustumPlanes[FRUSTUM_PLANE_RIGHT].normal, br.getOrigin())); - outVolume->planes.push_back( - Plane(mFrustumPlanes[FRUSTUM_PLANE_BOTTOM].normal, br.getOrigin())); - outVolume->planes.push_back( - Plane(mFrustumPlanes[FRUSTUM_PLANE_LEFT].normal, ul.getOrigin())); - - - } - - // near & far plane applicable to both projection types - outVolume->planes.push_back(getFrustumPlane(FRUSTUM_PLANE_NEAR)); - if (includeFarPlane) - outVolume->planes.push_back(getFrustumPlane(FRUSTUM_PLANE_FAR)); - } - // ------------------------------------------------------------------- - void Camera::setWindow (Real Left, Real Top, Real Right, Real Bottom) - { - mWLeft = Left; - mWTop = Top; - mWRight = Right; - mWBottom = Bottom; - - mWindowSet = true; - mRecalcWindow = true; - } - // ------------------------------------------------------------------- - void Camera::resetWindow () - { - mWindowSet = false; - } - // ------------------------------------------------------------------- - void Camera::setWindowImpl() const - { - if (!mWindowSet || !mRecalcWindow) - return; - - // Calculate general projection parameters - RealRect vp = calcProjectionParameters(); - - Real vpWidth = vp.width(); - Real vpHeight = -vp.height(); - - Real wvpLeft = vp.left + mWLeft * vpWidth; - Real wvpRight = vp.left + mWRight * vpWidth; - Real wvpTop = vp.top - mWTop * vpHeight; - Real wvpBottom = vp.top - mWBottom * vpHeight; - - Vector3 vp_ul (wvpLeft, wvpTop, -mNearDist); - Vector3 vp_ur (wvpRight, wvpTop, -mNearDist); - Vector3 vp_bl (wvpLeft, wvpBottom, -mNearDist); - Vector3 vp_br (wvpRight, wvpBottom, -mNearDist); - - Affine3 inv = mViewMatrix.inverse(); - - Vector3 vw_ul = inv * vp_ul; - Vector3 vw_ur = inv * vp_ur; - Vector3 vw_bl = inv * vp_bl; - Vector3 vw_br = inv * vp_br; - - mWindowClipPlanes.clear(); - if (mProjType == PT_PERSPECTIVE) - { - Vector3 position = getPositionForViewUpdate(); - mWindowClipPlanes.push_back(Plane(position, vw_bl, vw_ul)); - mWindowClipPlanes.push_back(Plane(position, vw_ul, vw_ur)); - mWindowClipPlanes.push_back(Plane(position, vw_ur, vw_br)); - mWindowClipPlanes.push_back(Plane(position, vw_br, vw_bl)); - } - else - { - Vector3 x_axis(inv[0][0], inv[0][1], inv[0][2]); - Vector3 y_axis(inv[1][0], inv[1][1], inv[1][2]); - x_axis.normalise(); - y_axis.normalise(); - mWindowClipPlanes.push_back(Plane( x_axis, vw_bl)); - mWindowClipPlanes.push_back(Plane(-x_axis, vw_ur)); - mWindowClipPlanes.push_back(Plane( y_axis, vw_bl)); - mWindowClipPlanes.push_back(Plane(-y_axis, vw_ur)); - } - - mRecalcWindow = false; - - } - // ------------------------------------------------------------------- - const std::vector& Camera::getWindowPlanes(void) const - { - updateView(); - setWindowImpl(); - return mWindowClipPlanes; - } - // ------------------------------------------------------------------- - Real Camera::getBoundingRadius(void) const - { - // return a little bigger than the near distance - // just to keep things just outside - return mNearDist * 1.5f; - - } - //----------------------------------------------------------------------- - bool Camera::getAutoAspectRatio(void) const - { - return mAutoAspectRatio; - } - //----------------------------------------------------------------------- - void Camera::setAutoAspectRatio(bool autoratio) - { - mAutoAspectRatio = autoratio; - } - //----------------------------------------------------------------------- - bool Camera::isVisible(const AxisAlignedBox& bound, FrustumPlane* culledBy) const - { - if (mCullFrustum) - { - return mCullFrustum->isVisible(bound, culledBy); - } - else - { - return Frustum::isVisible(bound, culledBy); - } - } - //----------------------------------------------------------------------- - bool Camera::isVisible(const Sphere& bound, FrustumPlane* culledBy) const - { - if (mCullFrustum) - { - return mCullFrustum->isVisible(bound, culledBy); - } - else - { - return Frustum::isVisible(bound, culledBy); - } - } - //----------------------------------------------------------------------- - bool Camera::isVisible(const Vector3& vert, FrustumPlane* culledBy) const - { - if (mCullFrustum) - { - return mCullFrustum->isVisible(vert, culledBy); - } - else - { - return Frustum::isVisible(vert, culledBy); - } - } - //----------------------------------------------------------------------- - const Frustum::Corners& Camera::getWorldSpaceCorners(void) const - { - if (mCullFrustum) - { - return mCullFrustum->getWorldSpaceCorners(); - } - else - { - return Frustum::getWorldSpaceCorners(); - } - } - //----------------------------------------------------------------------- - const Plane& Camera::getFrustumPlane( unsigned short plane ) const - { - if (mCullFrustum) - { - return mCullFrustum->getFrustumPlane(plane); - } - else - { - return Frustum::getFrustumPlane(plane); - } - } - //----------------------------------------------------------------------- - bool Camera::projectSphere(const Sphere& sphere, - Real* left, Real* top, Real* right, Real* bottom) const - { - if (mCullFrustum) - { - return mCullFrustum->projectSphere(sphere, left, top, right, bottom); - } - else - { - return Frustum::projectSphere(sphere, left, top, right, bottom); - } - } - //----------------------------------------------------------------------- - Real Camera::getNearClipDistance(void) const - { - if (mCullFrustum) - { - return mCullFrustum->getNearClipDistance(); - } - else - { - return Frustum::getNearClipDistance(); - } - } - //----------------------------------------------------------------------- - Real Camera::getFarClipDistance(void) const - { - if (mCullFrustum) - { - return mCullFrustum->getFarClipDistance(); - } - else - { - return Frustum::getFarClipDistance(); - } - } - //----------------------------------------------------------------------- - const Affine3& Camera::getViewMatrix(void) const - { - if (mCullFrustum) - { - return mCullFrustum->getViewMatrix(); - } - else - { - return Frustum::getViewMatrix(); - } - } - //----------------------------------------------------------------------- - const Affine3& Camera::getViewMatrix(bool ownFrustumOnly) const - { - if (ownFrustumOnly) - { - return Frustum::getViewMatrix(); - } - else - { - return getViewMatrix(); - } - } - //----------------------------------------------------------------------- - //_______________________________________________________ - //| | - //| getRayForwardIntersect | - //| ----------------------------- | - //| get the intersections of frustum rays with a plane | - //| of interest. The plane is assumed to have constant | - //| z. If this is not the case, rays | - //| should be rotated beforehand to work in a | - //| coordinate system in which this is true. | - //|_____________________________________________________| - // - std::vector Camera::getRayForwardIntersect(const Vector3& anchor, const Vector3 *dir, Real planeOffset) const - { - std::vector res; - - if(!dir) - return res; - - int infpt[4] = {0, 0, 0, 0}; // 0=finite, 1=infinite, 2=straddles infinity - Vector3 vec[4]; - - // find how much the anchor point must be displaced in the plane's - // constant variable - Real delta = planeOffset - anchor.z; - - // now set the intersection point and note whether it is a - // point at infinity or straddles infinity - unsigned int i; - for (i=0; i<4; i++) - { - Real test = dir[i].z * delta; - if (test == 0.0) { - vec[i] = dir[i]; - infpt[i] = 1; - } - else { - Real lambda = delta / dir[i].z; - vec[i] = anchor + (lambda * dir[i]); - if(test < 0.0) - infpt[i] = 2; - } - } - - for (i=0; i<4; i++) - { - // store the finite intersection points - if (infpt[i] == 0) - res.push_back(Vector4(vec[i].x, vec[i].y, vec[i].z, 1.0)); - else - { - // handle the infinite points of intersection; - // cases split up into the possible frustum planes - // pieces which may contain a finite intersection point - int nextind = (i+1) % 4; - int prevind = (i+3) % 4; - if ((infpt[prevind] == 0) || (infpt[nextind] == 0)) - { - if (infpt[i] == 1) - res.push_back(Vector4(vec[i].x, vec[i].y, vec[i].z, 0.0)); - else - { - // handle the intersection points that straddle infinity (back-project) - if(infpt[prevind] == 0) - { - Vector3 temp = vec[prevind] - vec[i]; - res.push_back(Vector4(temp.x, temp.y, temp.z, 0.0)); - } - if(infpt[nextind] == 0) - { - Vector3 temp = vec[nextind] - vec[i]; - res.push_back(Vector4(temp.x, temp.y, temp.z, 0.0)); - } - } - } // end if we need to add an intersection point to the list - } // end if infinite point needs to be considered - } // end loop over frustun corners - - // we end up with either 0, 3, 4, or 5 intersection points - - return res; - } - - //_______________________________________________________ - //| | - //| forwardIntersect | - //| ----------------------------- | - //| Forward intersect the camera's frustum rays with | - //| a specified plane of interest. | - //| Note that if the frustum rays shoot out and would | - //| back project onto the plane, this means the forward | - //| intersection of the frustum would occur at the | - //| line at infinity. | - //|_____________________________________________________| - // - void Camera::forwardIntersect(const Plane& worldPlane, std::vector* intersect3d) const - { - if(!intersect3d) - return; - - Vector3 trCorner = getWorldSpaceCorners()[0]; - Vector3 tlCorner = getWorldSpaceCorners()[1]; - Vector3 blCorner = getWorldSpaceCorners()[2]; - Vector3 brCorner = getWorldSpaceCorners()[3]; - - // need some sort of rotation that will bring the plane normal to the z axis - Plane pval = worldPlane; - if(pval.normal.z < 0.0) - { - pval.normal *= -1.0; - pval.d *= -1.0; - } - Quaternion invPlaneRot = pval.normal.getRotationTo(Vector3::UNIT_Z); - - // get rotated light - Vector3 lPos = invPlaneRot * getDerivedPosition(); - Vector3 vec[4]; - vec[0] = invPlaneRot * trCorner - lPos; - vec[1] = invPlaneRot * tlCorner - lPos; - vec[2] = invPlaneRot * blCorner - lPos; - vec[3] = invPlaneRot * brCorner - lPos; - - // compute intersection points on plane - std::vector iPnt = getRayForwardIntersect(lPos, vec, -pval.d); - - - // return wanted data - if(intersect3d) - { - Quaternion planeRot = invPlaneRot.Inverse(); - (*intersect3d).clear(); - for(auto & i : iPnt) - { - Vector3 intersection = planeRot * Vector3(i.x, i.y, i.z); - (*intersect3d).push_back(Vector4(intersection.x, intersection.y, intersection.z, i.w)); - } - } - } - //----------------------------------------------------------------------- - void Camera::synchroniseBaseSettingsWith(const Camera* cam) - { - this->setProjectionType(cam->getProjectionType()); -#ifdef OGRE_NODELESS_POSITIONING - mPosition = cam->mPosition; - mOrientation = cam->mOrientation; -#endif - invalidateView(); - this->setAspectRatio(cam->getAspectRatio()); - this->setNearClipDistance(cam->getNearClipDistance()); - this->setFarClipDistance(cam->getFarClipDistance()); - this->setUseRenderingDistance(cam->getUseRenderingDistance()); - this->setFOVy(cam->getFOVy()); - this->setFocalLength(cam->getFocalLength()); - - // Don't do these, they're not base settings and can cause referencing issues - //this->setLodCamera(cam->getLodCamera()); - //this->setCullingFrustum(cam->getCullingFrustum()); - - } - - -} // namespace Ogre diff --git a/OgreMain/src/OgreCodec.cpp b/OgreMain/src/OgreCodec.cpp deleted file mode 100644 index d468865f319..00000000000 --- a/OgreMain/src/OgreCodec.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreCodec.h" - -namespace Ogre { - - std::map< String, Codec * > Codec::msMapCodecs; - - Codec::~Codec() { - } - - DataStreamPtr Codec::encode(const Any& input) const - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, getType() + " - encoding to memory not supported"); - return DataStreamPtr(); - } - - void Codec::encodeToFile(const Any& input, const String& outFileName) const - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, getType() + " - encoding to file not supported"); - } - - StringVector Codec::getExtensions(void) - { - StringVector result; - result.reserve(msMapCodecs.size()); - for (auto& c : msMapCodecs) - { - result.push_back(c.first); - } - return result; - } - - void Codec::registerCodec(Codec* pCodec) - { - auto ret = msMapCodecs.emplace(pCodec->getType(), pCodec); - if (!ret.second) - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, pCodec->getType() + " already has a registered codec"); - } - - Codec* Codec::getCodec(const String& extension) - { - String lwrcase = extension; - StringUtil::toLowerCase(lwrcase); - CodecList::const_iterator i = msMapCodecs.find(lwrcase); - if (i == msMapCodecs.end()) - { - String formats_str; - if(msMapCodecs.empty()) - formats_str = "There are no formats supported (no codecs registered)."; - else - formats_str = "Supported formats are: " + StringConverter::toString(getExtensions()) + "."; - - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Can not find codec for '" + extension + "' format.\n" + formats_str); - } - - return i->second; - } - - Codec* Codec::getCodec(char *magicNumberPtr, size_t maxbytes) - { - for (auto& c : msMapCodecs) - { - String ext = c.second->magicNumberToFileExt(magicNumberPtr, maxbytes); - if (!ext.empty()) - { - // check codec type matches - // if we have a single codec class that can handle many types, - // and register many instances of it against different types, we - // can end up matching the wrong one here, so grab the right one - if (ext == c.second->getType()) - return c.second; - else - return getCodec(ext); - } - } - - return 0; - } -} diff --git a/OgreMain/src/OgreColourValue.cpp b/OgreMain/src/OgreColourValue.cpp deleted file mode 100644 index dd337ce2179..00000000000 --- a/OgreMain/src/OgreColourValue.cpp +++ /dev/null @@ -1,375 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -namespace Ogre { - - const ColourValue ColourValue::ZERO = ColourValue(0.0,0.0,0.0,0.0); - const ColourValue ColourValue::Black = ColourValue(0.0,0.0,0.0); - const ColourValue ColourValue::White = ColourValue(1.0,1.0,1.0); - const ColourValue ColourValue::Red = ColourValue(1.0,0.0,0.0); - const ColourValue ColourValue::Green = ColourValue(0.0,1.0,0.0); - const ColourValue ColourValue::Blue = ColourValue(0.0,0.0,1.0); - - //--------------------------------------------------------------------- -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - ABGR ColourValue::getAsABGR(void) const -#else - RGBA ColourValue::getAsRGBA(void) const -#endif - { - uint8 val8; - uint32 val32 = 0; - - // Convert to 32bit pattern - // (RGBA = 8888) - - // Red - val8 = static_cast(r * 255); - val32 = val8 << 24; - - // Green - val8 = static_cast(g * 255); - val32 += val8 << 16; - - // Blue - val8 = static_cast(b * 255); - val32 += val8 << 8; - - // Alpha - val8 = static_cast(a * 255); - val32 += val8; - - return val32; - } - //--------------------------------------------------------------------- -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - BGRA ColourValue::getAsBGRA(void) const -#else - ARGB ColourValue::getAsARGB(void) const -#endif - { - uint8 val8; - uint32 val32 = 0; - - // Convert to 32bit pattern - // (ARGB = 8888) - - // Alpha - val8 = static_cast(a * 255); - val32 = val8 << 24; - - // Red - val8 = static_cast(r * 255); - val32 += val8 << 16; - - // Green - val8 = static_cast(g * 255); - val32 += val8 << 8; - - // Blue - val8 = static_cast(b * 255); - val32 += val8; - - - return val32; - } - //--------------------------------------------------------------------- -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - ARGB ColourValue::getAsARGB(void) const -#else - BGRA ColourValue::getAsBGRA(void) const -#endif - { - uint8 val8; - uint32 val32 = 0; - - // Convert to 32bit pattern - // (ARGB = 8888) - - // Blue - val8 = static_cast(b * 255); - val32 = val8 << 24; - - // Green - val8 = static_cast(g * 255); - val32 += val8 << 16; - - // Red - val8 = static_cast(r * 255); - val32 += val8 << 8; - - // Alpha - val8 = static_cast(a * 255); - val32 += val8; - - - return val32; - } - //--------------------------------------------------------------------- -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - RGBA ColourValue::getAsRGBA(void) const -#else - ABGR ColourValue::getAsABGR(void) const -#endif - { - uint8 val8; - uint32 val32 = 0; - - // Convert to 32bit pattern - // (ABRG = 8888) - - // Alpha - val8 = static_cast(a * 255); - val32 = val8 << 24; - - // Blue - val8 = static_cast(b * 255); - val32 += val8 << 16; - - // Green - val8 = static_cast(g * 255); - val32 += val8 << 8; - - // Red - val8 = static_cast(r * 255); - val32 += val8; - - - return val32; - } - //--------------------------------------------------------------------- -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - void ColourValue::setAsABGR(ABGR val32) -#else - void ColourValue::setAsRGBA(RGBA val32) -#endif - { - // Convert from 32bit pattern - // (RGBA = 8888) - - // Red - r = float((val32 >> 24) & 0xFF) / 255.0f; - - // Green - g = float((val32 >> 16) & 0xFF) / 255.0f; - - // Blue - b = float((val32 >> 8) & 0xFF) / 255.0f; - - // Alpha - a = float(val32 & 0xFF) / 255.0f; - } - //--------------------------------------------------------------------- -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - void ColourValue::setAsBGRA(BGRA val32) -#else - void ColourValue::setAsARGB(ARGB val32) -#endif - { - // Convert from 32bit pattern - // (ARGB = 8888) - - // Alpha - a = float((val32 >> 24) & 0xFF) / 255.0f; - - // Red - r = float((val32 >> 16) & 0xFF) / 255.0f; - - // Green - g = float((val32 >> 8) & 0xFF) / 255.0f; - - // Blue - b = float(val32 & 0xFF) / 255.0f; - } - //--------------------------------------------------------------------- -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - void ColourValue::setAsARGB(ARGB val32) -#else - void ColourValue::setAsBGRA(BGRA val32) -#endif - { - // Convert from 32bit pattern - // (ARGB = 8888) - - // Blue - b = float((val32 >> 24) & 0xFF) / 255.0f; - - // Green - g = float((val32 >> 16) & 0xFF) / 255.0f; - - // Red - r = float((val32 >> 8) & 0xFF) / 255.0f; - - // Alpha - a = float(val32 & 0xFF) / 255.0f; - } - //--------------------------------------------------------------------- -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - void ColourValue::setAsRGBA(RGBA val32) -#else - void ColourValue::setAsABGR(ABGR val32) -#endif - { - // Convert from 32bit pattern - // (ABGR = 8888) - - // Alpha - a = float((val32 >> 24) & 0xFF) / 255.0f; - - // Blue - b = float((val32 >> 16) & 0xFF) / 255.0f; - - // Green - g = float((val32 >> 8) & 0xFF) / 255.0f; - - // Red - r = float(val32 & 0xFF) / 255.0f; - } - //--------------------------------------------------------------------- - void ColourValue::setHSB(float hue, float saturation, float brightness) - { - // wrap hue - hue = std::fmod(hue, 1.0f); - - // clamp saturation / brightness - saturation = Math::saturate(saturation); - brightness = Math::saturate(brightness); - - if (brightness == 0.0f) - { - // early exit, this has to be black - r = g = b = 0.0f; - return; - } - - if (saturation == 0.0f) - { - // early exit, this has to be grey - - r = g = b = brightness; - return; - } - - - float hueDomain = hue * 6.0f; - if (hueDomain >= 6.0f) - { - // wrap around, and allow mathematical errors - hueDomain = 0.0f; - } - unsigned short domain = (unsigned short)hueDomain; - float f1 = brightness * (1 - saturation); - float f2 = brightness * (1 - saturation * (hueDomain - domain)); - float f3 = brightness * (1 - saturation * (1 - (hueDomain - domain))); - - switch (domain) - { - case 0: - // red domain; green ascends - r = brightness; - g = f3; - b = f1; - break; - case 1: - // yellow domain; red descends - r = f2; - g = brightness; - b = f1; - break; - case 2: - // green domain; blue ascends - r = f1; - g = brightness; - b = f3; - break; - case 3: - // cyan domain; green descends - r = f1; - g = f2; - b = brightness; - break; - case 4: - // blue domain; red ascends - r = f3; - g = f1; - b = brightness; - break; - case 5: - // magenta domain; blue descends - r = brightness; - g = f1; - b = f2; - break; - } - - - } - //--------------------------------------------------------------------- - void ColourValue::getHSB(float& hue, float& saturation, float& brightness) const - { - - float vMin = std::min(r, std::min(g, b)); - float vMax = std::max(r, std::max(g, b)); - float delta = vMax - vMin; - - brightness = vMax; - - if (Math::RealEqual(delta, 0.0f, 1e-6f)) - { - // grey - hue = 0; - saturation = 0; - } - else - { - // a colour - saturation = delta / vMax; - - float deltaR = (((vMax - r) / 6.0f) + (delta / 2.0f)) / delta; - float deltaG = (((vMax - g) / 6.0f) + (delta / 2.0f)) / delta; - float deltaB = (((vMax - b) / 6.0f) + (delta / 2.0f)) / delta; - - if (Math::RealEqual(r, vMax)) - hue = deltaB - deltaG; - else if (Math::RealEqual(g, vMax)) - hue = 0.3333333f + deltaR - deltaB; - else if (Math::RealEqual(b, vMax)) - hue = 0.6666667f + deltaG - deltaR; - - if (hue < 0.0f) - hue += 1.0f; - if (hue > 1.0f) - hue -= 1.0f; - } - - - } - -} - diff --git a/OgreMain/src/OgreCommon.cpp b/OgreMain/src/OgreCommon.cpp deleted file mode 100644 index 05d20cf5fd0..00000000000 --- a/OgreMain/src/OgreCommon.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -namespace Ogre -{ - int findCommandLineOpts(int numargs, char** argv, UnaryOptionList& unaryOptList, - BinaryOptionList& binOptList) - { - int startIndex = 1; - for (int i = 1; i < numargs; ++i) - { - String tmp(argv[i]); - if (StringUtil::startsWith(tmp, "-")) - { - UnaryOptionList::iterator ui = unaryOptList.find(argv[i]); - if(ui != unaryOptList.end()) - { - ui->second = true; - ++startIndex; - continue; - } - BinaryOptionList::iterator bi = binOptList.find(argv[i]); - if(bi != binOptList.end()) - { - bi->second = argv[i+1]; - startIndex += 2; - ++i; - continue; - } - - // Invalid option - LogManager::getSingleton().logMessage("Invalid option " + tmp, LML_CRITICAL); - - } - } - return startIndex; - } - - void logMaterialNotFound(const String& name, const String& groupName, const String& destType, - const String& destName, LogMessageLevel lml) - { - LogManager::getSingleton().logMessage( - StringUtil::format("Can't assign material to %s '%s'. Material '%s' not found in group '%s'. Have you " - "forgotten to define it in a .material script?", - destType.c_str(), destName.c_str(), name.c_str(), groupName.c_str()), - lml); - } -} diff --git a/OgreMain/src/OgreCompositionPass.cpp b/OgreMain/src/OgreCompositionPass.cpp deleted file mode 100644 index 7e18edc6d14..00000000000 --- a/OgreMain/src/OgreCompositionPass.cpp +++ /dev/null @@ -1,301 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreCompositionPass.h" -#include "OgreRenderQueue.h" - -namespace Ogre { - -CompositionPass::CompositionPass(CompositionTargetPass *parent): - mParent(parent), - mType(PT_RENDERQUAD) -{ -} -//----------------------------------------------------------------------- -CompositionPass::~CompositionPass() -{ -} -//----------------------------------------------------------------------- -void CompositionPass::setType(CompositionPass::PassType type) -{ - mType = type; -} -//----------------------------------------------------------------------- -CompositionPass::PassType CompositionPass::getType() const -{ - return mType; -} -//----------------------------------------------------------------------- -void CompositionPass::setIdentifier(uint32 id) -{ - mMaterial.identifier = id; -} -//----------------------------------------------------------------------- -uint32 CompositionPass::getIdentifier() const -{ - return mMaterial.identifier; -} -//----------------------------------------------------------------------- -void CompositionPass::setMaterial(const MaterialPtr& mat) -{ - mMaterial.material = mat; -} -//----------------------------------------------------------------------- -void CompositionPass::setMaterialName(const String &name) -{ - mMaterial.material = MaterialManager::getSingleton().getByName(name); -} -//----------------------------------------------------------------------- -const MaterialPtr& CompositionPass::getMaterial() const -{ - return mMaterial.material; -} -//----------------------------------------------------------------------- -void CompositionPass::setClearBuffers(uint32 val) -{ - mClear.buffers = val; -} -//----------------------------------------------------------------------- -uint32 CompositionPass::getClearBuffers() const -{ - return mClear.buffers; -} -//----------------------------------------------------------------------- -void CompositionPass::setClearColour(const ColourValue &val) -{ - mClear.colour = val; -} -//----------------------------------------------------------------------- -const ColourValue &CompositionPass::getClearColour() const -{ - return mClear.colour; -} -//----------------------------------------------------------------------- -void CompositionPass::setAutomaticColour(bool val) -{ - mClear.automaticColour = val; -} -//----------------------------------------------------------------------- -bool CompositionPass::getAutomaticColour() const -{ - return mClear.automaticColour; -} -//----------------------------------------------------------------------- -void CompositionPass::setInput(size_t id, const String &input, size_t mrtIndex) -{ - assert(id < OGRE_MAX_TEXTURE_LAYERS); - mMaterial.inputs[id] = InputTex(input, mrtIndex); -} -//----------------------------------------------------------------------- -const CompositionPass::InputTex &CompositionPass::getInput(size_t id) const -{ - assert(id < OGRE_MAX_TEXTURE_LAYERS); - return mMaterial.inputs[id]; -} -//----------------------------------------------------------------------- -size_t CompositionPass::getNumInputs() const -{ - size_t count = 0; - for(size_t x = 0; x < OGRE_MAX_TEXTURE_LAYERS; ++x) - { - if(!mMaterial.inputs[x].name.empty()) - count = x+1; - } - return count; -} -//----------------------------------------------------------------------- -void CompositionPass::clearAllInputs() -{ - for(auto& input : mMaterial.inputs) - { - input.name.clear(); - } -} -//----------------------------------------------------------------------- -CompositionTargetPass *CompositionPass::getParent() -{ - return mParent; -} -//----------------------------------------------------------------------- -void CompositionPass::setFirstRenderQueue(uint8 id) -{ - mRenderScene.firstRenderQueue = id; -} -//----------------------------------------------------------------------- -uint8 CompositionPass::getFirstRenderQueue() const -{ - return mRenderScene.firstRenderQueue; -} -//----------------------------------------------------------------------- -void CompositionPass::setLastRenderQueue(uint8 id) -{ - mRenderScene.lastRenderQueue = id; -} -//----------------------------------------------------------------------- -uint8 CompositionPass::getLastRenderQueue() const -{ - return mRenderScene.lastRenderQueue ; -} -//----------------------------------------------------------------------- -void CompositionPass::setMaterialScheme(const String& schemeName) -{ - mRenderScene.materialScheme = schemeName; -} -//----------------------------------------------------------------------- -const String& CompositionPass::getMaterialScheme(void) const -{ - return mRenderScene.materialScheme; -} -//----------------------------------------------------------------------- -void CompositionPass::setClearDepth(float depth) -{ - mClear.depth = depth; -} -float CompositionPass::getClearDepth() const -{ - return mClear.depth; -} -void CompositionPass::setClearStencil(uint16 value) -{ - mClear.stencil = value; -} -uint16 CompositionPass::getClearStencil() const -{ - return mClear.stencil; -} - -void CompositionPass::setStencilCheck(bool value) -{ - mStencilState.enabled = value; -} -bool CompositionPass::getStencilCheck() const -{ - return mStencilState.enabled; -} -void CompositionPass::setStencilFunc(CompareFunction value) -{ - mStencilState.compareOp = value; -} -CompareFunction CompositionPass::getStencilFunc() const -{ - return mStencilState.compareOp; -} -void CompositionPass::setStencilRefValue(uint32 value) -{ - mStencilState.referenceValue = value; -} -uint32 CompositionPass::getStencilRefValue() const -{ - return mStencilState.referenceValue; -} -void CompositionPass::setStencilMask(uint32 value) -{ - mStencilState.compareMask = value; -} -uint32 CompositionPass::getStencilMask() const -{ - return mStencilState.compareMask ; -} -void CompositionPass::setStencilFailOp(StencilOperation value) -{ - mStencilState.stencilFailOp = value; -} -StencilOperation CompositionPass::getStencilFailOp() const -{ - return mStencilState.stencilFailOp; -} -void CompositionPass::setStencilDepthFailOp(StencilOperation value) -{ - mStencilState.depthFailOp = value; -} -StencilOperation CompositionPass::getStencilDepthFailOp() const -{ - return mStencilState.depthFailOp; -} -void CompositionPass::setStencilPassOp(StencilOperation value) -{ - mStencilState.depthStencilPassOp = value; -} -StencilOperation CompositionPass::getStencilPassOp() const -{ - return mStencilState.depthStencilPassOp; -} -void CompositionPass::setStencilTwoSidedOperation(bool value) -{ - mStencilState.twoSidedOperation = value; -} -bool CompositionPass::getStencilTwoSidedOperation() const -{ - return mStencilState.twoSidedOperation; -} -void CompositionPass::setQuadFarCorners(bool farCorners, bool farCornersViewSpace) -{ - mQuad.farCorners = farCorners; - mQuad.farCornersViewSpace = farCornersViewSpace; -} -bool CompositionPass::getQuadFarCorners() const -{ - return mQuad.farCorners; -} -bool CompositionPass::getQuadFarCornersViewSpace() const -{ - return mQuad.farCornersViewSpace; -} - -void CompositionPass::setCustomType(const String& customType) -{ - mCustomType = customType; -} - -const String& CompositionPass::getCustomType() const -{ - return mCustomType; -} -//----------------------------------------------------------------------- -bool CompositionPass::_isSupported(void) -{ - // A pass is supported if material referenced have a supported technique - - if (mType == PT_RENDERQUAD) - { - if (!mMaterial.material) - { - return false; - } - - mMaterial.material->load(); - if (mMaterial.material->getSupportedTechniques().empty()) - { - return false; - } - } - - return true; -} - -} diff --git a/OgreMain/src/OgreCompositionTargetPass.cpp b/OgreMain/src/OgreCompositionTargetPass.cpp deleted file mode 100644 index cb6d4b515bc..00000000000 --- a/OgreMain/src/OgreCompositionTargetPass.cpp +++ /dev/null @@ -1,176 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreCompositionTargetPass.h" -#include "OgreCompositionPass.h" - -namespace Ogre { - -CompositionTargetPass::CompositionTargetPass(CompositionTechnique *parent): - mParent(parent), - mInputMode(IM_NONE), - mOnlyInitial(false), - mVisibilityMask(0xFFFFFFFF), - mLodBias(1.0f), - mMaterialScheme(MaterialManager::DEFAULT_SCHEME_NAME), - mShadowsEnabled(true), - mOutputSlice(0) -{ - if (Root::getSingleton().getRenderSystem()) - { - mMaterialScheme = Root::getSingleton().getRenderSystem()->_getDefaultViewportMaterialScheme(); - } -} -//----------------------------------------------------------------------- -CompositionTargetPass::~CompositionTargetPass() -{ - removeAllPasses(); -} -//----------------------------------------------------------------------- -void CompositionTargetPass::setInputMode(InputMode mode) -{ - mInputMode = mode; -} -//----------------------------------------------------------------------- -CompositionTargetPass::InputMode CompositionTargetPass::getInputMode() const -{ - return mInputMode; -} -//----------------------------------------------------------------------- -void CompositionTargetPass::setOutputName(const String &out) -{ - mOutputName = out; -} -//----------------------------------------------------------------------- -const String &CompositionTargetPass::getOutputName() const -{ - return mOutputName; -} -//----------------------------------------------------------------------- -void CompositionTargetPass::setOnlyInitial(bool value) -{ - mOnlyInitial = value; -} -//----------------------------------------------------------------------- -bool CompositionTargetPass::getOnlyInitial() -{ - return mOnlyInitial; -} -//----------------------------------------------------------------------- -void CompositionTargetPass::setVisibilityMask(uint32 mask) -{ - mVisibilityMask = mask; -} -//----------------------------------------------------------------------- -uint32 CompositionTargetPass::getVisibilityMask() -{ - return mVisibilityMask; -} -//----------------------------------------------------------------------- -void CompositionTargetPass::setLodBias(float bias) -{ - mLodBias = bias; -} -//----------------------------------------------------------------------- -float CompositionTargetPass::getLodBias() -{ - return mLodBias; -} -//----------------------------------------------------------------------- -void CompositionTargetPass::setMaterialScheme(const String& schemeName) -{ - mMaterialScheme = schemeName; -} -//----------------------------------------------------------------------- -const String& CompositionTargetPass::getMaterialScheme(void) const -{ - return mMaterialScheme; -} -//----------------------------------------------------------------------- -void CompositionTargetPass::setShadowsEnabled(bool enabled) -{ - mShadowsEnabled = enabled; -} -//----------------------------------------------------------------------- -bool CompositionTargetPass::getShadowsEnabled(void) const -{ - return mShadowsEnabled; -} -//----------------------------------------------------------------------- -CompositionPass *CompositionTargetPass::createPass(CompositionPass::PassType type) -{ - CompositionPass *t = OGRE_NEW CompositionPass(this); - t->setType(type); - mPasses.push_back(t); - return t; -} -//----------------------------------------------------------------------- - -void CompositionTargetPass::removePass(size_t index) -{ - assert (index < mPasses.size() && "Index out of bounds."); - Passes::iterator i = mPasses.begin() + index; - OGRE_DELETE (*i); - mPasses.erase(i); -} -//----------------------------------------------------------------------- -void CompositionTargetPass::removeAllPasses() -{ - for (auto p : mPasses) - { - OGRE_DELETE (p); - } - mPasses.clear(); -} -//----------------------------------------------------------------------- -CompositionTargetPass::PassIterator CompositionTargetPass::getPassIterator(void) -{ - return PassIterator(mPasses.begin(), mPasses.end()); -} - -//----------------------------------------------------------------------- -CompositionTechnique *CompositionTargetPass::getParent() -{ - return mParent; -} - -//----------------------------------------------------------------------- -bool CompositionTargetPass::_isSupported(void) -{ - // A target pass is supported if all passes are supported - for (auto *p : mPasses) - { - if (!p->_isSupported()) - { - return false; - } - } - return true; -} - -} diff --git a/OgreMain/src/OgreCompositionTechnique.cpp b/OgreMain/src/OgreCompositionTechnique.cpp deleted file mode 100644 index 9f2549df0a7..00000000000 --- a/OgreMain/src/OgreCompositionTechnique.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreCompositionTechnique.h" -#include "OgreCompositionTargetPass.h" - -namespace Ogre { - -CompositionTechnique::CompositionTechnique(Compositor *parent): - mParent(parent) -{ - mOutputTarget = OGRE_NEW CompositionTargetPass(this); -} -//----------------------------------------------------------------------- -CompositionTechnique::~CompositionTechnique() -{ - removeAllTextureDefinitions(); - removeAllTargetPasses(); - OGRE_DELETE mOutputTarget; -} -//----------------------------------------------------------------------- -CompositionTechnique::TextureDefinition *CompositionTechnique::createTextureDefinition(const String &name) -{ - if(getTextureDefinition(name)) - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, "Texture '"+name+"' already exists"); - - TextureDefinition *t = OGRE_NEW TextureDefinition(); - t->name = name; - mTextureDefinitions.push_back(t); - return t; -} -//----------------------------------------------------------------------- - -void CompositionTechnique::removeTextureDefinition(size_t index) -{ - assert (index < mTextureDefinitions.size() && "Index out of bounds."); - TextureDefinitions::iterator i = mTextureDefinitions.begin() + index; - OGRE_DELETE (*i); - mTextureDefinitions.erase(i); -} -//--------------------------------------------------------------------- -CompositionTechnique::TextureDefinition *CompositionTechnique::getTextureDefinition(const String& name) const -{ - for (auto *t : mTextureDefinitions) - { - if (t->name == name) - return t; - } - return 0; - -} -//----------------------------------------------------------------------- -void CompositionTechnique::removeAllTextureDefinitions() -{ - for (auto *t : mTextureDefinitions) - { - OGRE_DELETE t; - } - mTextureDefinitions.clear(); -} -//----------------------------------------------------------------------- -CompositionTechnique::TextureDefinitionIterator CompositionTechnique::getTextureDefinitionIterator(void) -{ - return TextureDefinitionIterator(mTextureDefinitions.begin(), mTextureDefinitions.end()); -} - -//----------------------------------------------------------------------- -CompositionTargetPass *CompositionTechnique::createTargetPass() -{ - CompositionTargetPass *t = OGRE_NEW CompositionTargetPass(this); - mTargetPasses.push_back(t); - return t; -} -//----------------------------------------------------------------------- - -void CompositionTechnique::removeTargetPass(size_t index) -{ - assert (index < mTargetPasses.size() && "Index out of bounds."); - TargetPasses::iterator i = mTargetPasses.begin() + index; - OGRE_DELETE (*i); - mTargetPasses.erase(i); -} -//----------------------------------------------------------------------- -void CompositionTechnique::removeAllTargetPasses() -{ - for (auto *t : mTargetPasses) - { - OGRE_DELETE t; - } - mTargetPasses.clear(); -} -//----------------------------------------------------------------------- -CompositionTechnique::TargetPassIterator CompositionTechnique::getTargetPassIterator(void) -{ - return TargetPassIterator(mTargetPasses.begin(), mTargetPasses.end()); -} -//----------------------------------------------------------------------- -bool CompositionTechnique::isSupported(bool acceptTextureDegradation) -{ - // A technique is supported if all materials referenced have a supported - // technique, and the intermediate texture formats requested are supported - // Material support is a cast-iron requirement, but if no texture formats - // are directly supported we can let the rendersystem create the closest - // match for the least demanding technique - - - // Check output target pass is supported - if (!mOutputTarget->_isSupported()) - { - return false; - } - - // Check all target passes is supported - for (auto *p : mTargetPasses) - { - if (!p->_isSupported()) - { - return false; - } - } - - TextureManager& texMgr = TextureManager::getSingleton(); - for (auto *td : mTextureDefinitions) - { - // Firstly check MRTs - if (td->formatList.size() > - Root::getSingleton().getRenderSystem()->getCapabilities()->getNumMultiRenderTargets()) - { - return false; - } - - - for (auto& pfi : td->formatList) - { - // Check whether equivalent supported - // Need a format which is the same number of bits to pass - bool accepted = texMgr.isEquivalentFormatSupported(td->type, pfi, TU_RENDERTARGET); - if(!accepted && acceptTextureDegradation) - { - // Don't care about exact format so long as something is supported - accepted = texMgr.getNativeFormat(td->type, pfi, TU_RENDERTARGET) != PF_UNKNOWN; - } - - if(!accepted) - return false; - } - - //Check all render targets have same number of bits - if( Root::getSingleton().getRenderSystem()->getCapabilities()-> - hasCapability( RSC_MRT_SAME_BIT_DEPTHS ) && !td->formatList.empty() ) - { - PixelFormat nativeFormat = texMgr.getNativeFormat( td->type, td->formatList.front(), - TU_RENDERTARGET ); - size_t nativeBits = PixelUtil::getNumElemBits( nativeFormat ); - for( PixelFormatList::iterator pfi = td->formatList.begin()+1; - pfi != td->formatList.end(); ++pfi ) - { - PixelFormat nativeTmp = texMgr.getNativeFormat( td->type, *pfi, TU_RENDERTARGET ); - if( PixelUtil::getNumElemBits( nativeTmp ) != nativeBits ) - { - return false; - } - } - } - } - - // Must be ok - return true; -} -//----------------------------------------------------------------------- -Compositor *CompositionTechnique::getParent() -{ - return mParent; -} -//--------------------------------------------------------------------- -void CompositionTechnique::setSchemeName(const String& schemeName) -{ - mSchemeName = schemeName; -} - -} diff --git a/OgreMain/src/OgreCompositor.cpp b/OgreMain/src/OgreCompositor.cpp deleted file mode 100644 index 6de573e0fe5..00000000000 --- a/OgreMain/src/OgreCompositor.cpp +++ /dev/null @@ -1,346 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreCompositor.h" -#include "OgreCompositionTechnique.h" -#include "OgreRenderTexture.h" -#include "OgreRenderTarget.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreCompositorInstance.h" - -namespace Ogre { - -//----------------------------------------------------------------------- -Compositor::Compositor(ResourceManager* creator, const String& name, ResourceHandle handle, const String& group, bool isManual, ManualResourceLoader* loader): - Resource(creator, name, handle, group, isManual, loader), - mCompilationRequired(true) -{ -} -//----------------------------------------------------------------------- - -Compositor::~Compositor() -{ - removeAllTechniques(); - // have to call this here reather than in Resource destructor - // since calling virtual methods in base destructors causes crash - unload(); -} -//----------------------------------------------------------------------- -CompositionTechnique *Compositor::createTechnique() -{ - CompositionTechnique *t = OGRE_NEW CompositionTechnique(this); - mTechniques.push_back(t); - mCompilationRequired = true; - return t; -} -//----------------------------------------------------------------------- - -void Compositor::removeTechnique(size_t index) -{ - assert (index < mTechniques.size() && "Index out of bounds."); - Techniques::iterator i = mTechniques.begin() + index; - OGRE_DELETE (*i); - mTechniques.erase(i); - mSupportedTechniques.clear(); - mCompilationRequired = true; -} -//----------------------------------------------------------------------- -void Compositor::removeAllTechniques() -{ - for (auto *t : mTechniques) - { - OGRE_DELETE t; - } - mTechniques.clear(); - mSupportedTechniques.clear(); - mCompilationRequired = true; -} -//----------------------------------------------------------------------- -Compositor::TechniqueIterator Compositor::getTechniqueIterator(void) -{ - return TechniqueIterator(mTechniques.begin(), mTechniques.end()); -} -//----------------------------------------------------------------------- - -Compositor::TechniqueIterator Compositor::getSupportedTechniqueIterator(void) -{ - return TechniqueIterator(mSupportedTechniques.begin(), mSupportedTechniques.end()); -} -//----------------------------------------------------------------------- -void Compositor::loadImpl(void) -{ - // compile if required - if (mCompilationRequired) - compile(); - - createGlobalTextures(); -} -//----------------------------------------------------------------------- -void Compositor::unloadImpl(void) -{ - freeGlobalTextures(); -} -//----------------------------------------------------------------------- -size_t Compositor::calculateSize(void) const -{ - return 0; -} - -//----------------------------------------------------------------------- -void Compositor::compile() -{ - /// Sift out supported techniques - mSupportedTechniques.clear(); - - for (auto t : mTechniques) - { - // Allow texture support with degraded pixel format - if (t->isSupported(true)) - { - mSupportedTechniques.push_back(t); - } - } - - if (mSupportedTechniques.empty()) - LogManager::getSingleton().logError("Compositor '" + getName() + "' has no supported techniques"); - - mCompilationRequired = false; -} -//--------------------------------------------------------------------- -CompositionTechnique* Compositor::getSupportedTechnique(const String& schemeName) -{ - for(auto & t : mSupportedTechniques) - { - if (t->getSchemeName() == schemeName) - { - return t; - } - } - - // didn't find a matching one - for(auto & t : mSupportedTechniques) - { - if (t->getSchemeName().empty()) - { - return t; - } - } - - return 0; - -} -//----------------------------------------------------------------------- -void Compositor::createGlobalTextures() -{ - static size_t dummyCounter = 0; - if (mSupportedTechniques.empty()) - return; - - //To make sure that we are consistent, it is demanded that all composition - //techniques define the same set of global textures. - - typedef std::set StringSet; - StringSet globalTextureNames; - - //Initialize global textures from first supported technique - CompositionTechnique* firstTechnique = mSupportedTechniques[0]; - - const CompositionTechnique::TextureDefinitions& tdefs = firstTechnique->getTextureDefinitions(); - CompositionTechnique::TextureDefinitions::const_iterator texDefIt = tdefs.begin(); - for (; texDefIt != tdefs.end(); ++texDefIt) - { - CompositionTechnique::TextureDefinition* def = *texDefIt; - if (def->scope == CompositionTechnique::TS_GLOBAL) - { - //Check that this is a legit global texture - OgreAssert(def->refCompName.empty(), "Global compositor texture definition can not be a reference"); - OgreAssert(def->width && def->height, "Global compositor texture definition must have absolute size"); - if (def->pooled) - { - LogManager::getSingleton().logWarning("Pooling global compositor textures has no effect"); - } - globalTextureNames.insert(def->name); - - //TODO GSOC : Heavy copy-pasting from CompositorInstance. How to we solve it? - - /// Make the tetxure - RenderTarget* rendTarget; - if (def->formatList.size() > 1) - { - String MRTbaseName = "mrt/c" + StringConverter::toString(dummyCounter++) + - "/" + mName + "/" + def->name; - MultiRenderTarget* mrt = - Root::getSingleton().getRenderSystem()->createMultiRenderTarget(MRTbaseName); - mGlobalMRTs[def->name] = mrt; - - // create and bind individual surfaces - size_t atch = 0; - for (PixelFormatList::iterator p = def->formatList.begin(); - p != def->formatList.end(); ++p, ++atch) - { - - String texname = MRTbaseName + "/" + StringConverter::toString(atch); - TexturePtr tex; - - tex = TextureManager::getSingleton().createManual( - texname, - ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D, - (uint)def->width, (uint)def->height, 0, *p, TU_RENDERTARGET, 0, - def->hwGammaWrite && !PixelUtil::isFloatingPoint(*p), def->fsaa); - - RenderTexture* rt = tex->getBuffer()->getRenderTarget(); - rt->setAutoUpdated(false); - mrt->bindSurface(atch, rt); - - // Also add to local textures so we can look up - String mrtLocalName = CompositorInstance::getMRTTexLocalName(def->name, atch); - mGlobalTextures[mrtLocalName] = tex; - - } - - rendTarget = mrt; - } - else - { - String texName = "c" + StringConverter::toString(dummyCounter++) + - "/" + mName + "/" + def->name; - - // space in the name mixup the cegui in the compositor demo - // this is an auto generated name - so no spaces can't hart us. - std::replace( texName.begin(), texName.end(), ' ', '_' ); - - TexturePtr tex; - tex = TextureManager::getSingleton().createManual( - texName, - ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D, - (uint)def->width, (uint)def->height, 0, def->formatList[0], TU_RENDERTARGET, 0, - def->hwGammaWrite && !PixelUtil::isFloatingPoint(def->formatList[0]), def->fsaa); - - - rendTarget = tex->getBuffer()->getRenderTarget(); - mGlobalTextures[def->name] = tex; - } - - //Set DepthBuffer pool for sharing - rendTarget->setDepthBufferPool( def->depthBufferId ); - } - } - - //Validate that all other supported techniques expose the same set of global textures. - for (size_t i=1; igetTextureDefinitions(); - texDefIt = tdefs2.begin(); - for (; texDefIt != tdefs2.end(); ++texDefIt) - { - CompositionTechnique::TextureDefinition* texDef = *texDefIt; - if (texDef->scope == CompositionTechnique::TS_GLOBAL) - { - if (globalTextureNames.find(texDef->name) == globalTextureNames.end()) - { - isConsistent = false; - break; - } - numGlobals++; - } - } - if (numGlobals != globalTextureNames.size()) - isConsistent = false; - - OgreAssert(isConsistent, "Different composition techniques define different global textures"); - } - -} -//----------------------------------------------------------------------- -void Compositor::freeGlobalTextures() -{ - GlobalTextureMap::iterator i = mGlobalTextures.begin(); - while (i != mGlobalTextures.end()) - { - TextureManager::getSingleton().remove(i->second); - ++i; - } - mGlobalTextures.clear(); - - GlobalMRTMap::iterator mrti = mGlobalMRTs.begin(); - while (mrti != mGlobalMRTs.end()) - { - // remove MRT - Root::getSingleton().getRenderSystem()->destroyRenderTarget(mrti->second->getName()); - ++mrti; - } - mGlobalMRTs.clear(); - -} -//----------------------------------------------------------------------- -const String& Compositor::getTextureInstanceName(const String& name, size_t mrtIndex) -{ - return getTextureInstance(name, mrtIndex)->getName(); -} -//----------------------------------------------------------------------- -const TexturePtr& Compositor::getTextureInstance(const String& name, size_t mrtIndex) -{ - //Try simple texture - GlobalTextureMap::iterator i = mGlobalTextures.find(name); - if(i != mGlobalTextures.end()) - { - return i->second; - } - //Try MRT - String mrtName = CompositorInstance::getMRTTexLocalName(name, mrtIndex); - i = mGlobalTextures.find(mrtName); - if(i != mGlobalTextures.end()) - { - return i->second; - } - - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Non-existent global texture name", - "Compositor::getTextureInstance"); - -} -//--------------------------------------------------------------------- -RenderTarget* Compositor::getRenderTarget(const String& name, int slice) -{ - // try simple texture - GlobalTextureMap::iterator i = mGlobalTextures.find(name); - if(i != mGlobalTextures.end()) - return i->second->getBuffer(slice)->getRenderTarget(); - - // try MRTs - GlobalMRTMap::iterator mi = mGlobalMRTs.find(name); - if (mi != mGlobalMRTs.end()) - return mi->second; - else - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Non-existent global texture name", - "Compositor::getRenderTarget"); -} -//--------------------------------------------------------------------- -} diff --git a/OgreMain/src/OgreCompositorChain.cpp b/OgreMain/src/OgreCompositorChain.cpp deleted file mode 100644 index 09cf872806d..00000000000 --- a/OgreMain/src/OgreCompositorChain.cpp +++ /dev/null @@ -1,645 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreCompositor.h" -#include "OgreCompositorChain.h" -#include "OgreCompositionTechnique.h" -#include "OgreCompositorInstance.h" -#include "OgreCompositionTargetPass.h" -#include "OgreCompositionPass.h" -#include "OgreCompositorManager.h" -#include "OgreRenderTarget.h" - -namespace Ogre { -CompositorChain::CompositorChain(Viewport *vp): - mViewport(vp), - mOriginalScene(0), - mDirty(true), - mAnyCompositorsEnabled(false), - mOldLodBias(1.0f) -{ - assert(vp); - mOldClearEveryFrameBuffers = vp->getClearBuffers(); - vp->addListener(this); - - createOriginalScene(); - vp->getTarget()->addListener(this); -} -//----------------------------------------------------------------------- -CompositorChain::~CompositorChain() -{ - destroyResources(); -} -//----------------------------------------------------------------------- -void CompositorChain::destroyResources(void) -{ - clearCompiledState(); - - if (mViewport) - { - mViewport->getTarget()->removeListener(this); - mViewport->removeListener(this); - removeAllCompositors(); - destroyOriginalScene(); - - // destory base "original scene" compositor - CompositorManager::getSingleton().remove(getCompositorName(), ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME); - - mViewport = 0; - } -} -//----------------------------------------------------------------------- -const String CompositorChain::getCompositorName() const -{ - return StringUtil::format("Ogre/Scene/%zu", (size_t)mViewport); -} -//----------------------------------------------------------------------- -void CompositorChain::createOriginalScene() -{ - /// Create "default" compositor - /** Compositor that is used to implicitly represent the original - render in the chain. This is an identity compositor with only an output pass: - compositor Ogre/Scene - { - technique - { - target_output - { - pass clear - { - /// Clear frame - } - pass render_scene - { - visibility_mask 0xFFFFFFFF - render_queues SKIES_EARLY SKIES_LATE - } - } - } - }; - */ - - // If two viewports use the same scheme but differ in settings like visibility masks, shadows, etc we don't - // want compositors to share their technique. Otherwise both compositors will have to recompile every time they - // render. Thus we generate a unique compositor per viewport. - const String compName = getCompositorName(); - - mOriginalSceneScheme = mViewport->getMaterialScheme(); - CompositorPtr scene = CompositorManager::getSingleton().getByName(compName, ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME); - if (!scene) - { - /// Create base "original scene" compositor - scene = CompositorManager::getSingleton().create(compName, ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME); - CompositionTargetPass *tp = scene->createTechnique()->getOutputTargetPass(); - auto pass = tp->createPass(CompositionPass::PT_CLEAR); - pass->setAutomaticColour(true); - - /// Render everything, including skies - pass = tp->createPass(CompositionPass::PT_RENDERSCENE); - pass->setFirstRenderQueue(RENDER_QUEUE_BACKGROUND); - pass->setLastRenderQueue(RENDER_QUEUE_TRANSPARENTS); - scene->load(); - } - mOriginalScene = OGRE_NEW CompositorInstance(scene->getSupportedTechnique(), this); -} -//----------------------------------------------------------------------- -void CompositorChain::destroyOriginalScene() -{ - /// Destroy "original scene" compositor instance - if (mOriginalScene) - { - OGRE_DELETE mOriginalScene; - mOriginalScene = 0; - } -} - -//----------------------------------------------------------------------- -CompositorInstance* CompositorChain::addCompositor(const CompositorPtr& filter, size_t addPosition, const String& scheme) -{ - - - filter->touch(); - CompositionTechnique *tech = filter->getSupportedTechnique(scheme); - if(!tech) - { - return 0; - } - CompositorInstance *t = OGRE_NEW CompositorInstance(tech, this); - - if(addPosition == LAST) - addPosition = mInstances.size(); - else - assert(addPosition <= mInstances.size() && "Index out of bounds."); - mInstances.insert(mInstances.begin()+addPosition, t); - - mDirty = true; - mAnyCompositorsEnabled = true; - return t; -} -//----------------------------------------------------------------------- -void CompositorChain::removeCompositor(size_t index) -{ - if(index == LAST) - index = mInstances.size() - 1; - - assert (index < mInstances.size() && "Index out of bounds."); - Instances::iterator i = mInstances.begin() + index; - OGRE_DELETE *i; - mInstances.erase(i); - - mDirty = true; -} -//----------------------------------------------------------------------- -size_t CompositorChain::getNumCompositors() -{ - return mInstances.size(); -} -//----------------------------------------------------------------------- -void CompositorChain::removeAllCompositors() -{ - for (auto *i : mInstances) - { - OGRE_DELETE i; - } - mInstances.clear(); - - mDirty = true; -} -//----------------------------------------------------------------------- -void CompositorChain::_removeInstance(CompositorInstance *i) -{ - Instances::iterator it = std::find(mInstances.begin(), mInstances.end(), i); - assert(it != mInstances.end()); - if(it != mInstances.end()) - { - mInstances.erase(it); - OGRE_DELETE i; - } -} -//----------------------------------------------------------------------- -void CompositorChain::_queuedOperation(CompositorInstance::RenderSystemOperation* op) -{ - mRenderSystemOperations.push_back(op); - -} -//----------------------------------------------------------------------- -size_t CompositorChain::getCompositorPosition(const String& name) const -{ - for (auto it = mInstances.begin(); it != mInstances.end(); ++it) - { - if ((*it)->getCompositor()->getName() == name) - { - return std::distance(mInstances.begin(), it); - } - } - return NPOS; -} -CompositorInstance *CompositorChain::getCompositor(const String& name) const -{ - size_t idx = getCompositorPosition(name); - return idx == NPOS ? NULL : mInstances[idx]; -} -//----------------------------------------------------------------------- -CompositorChain::InstanceIterator CompositorChain::getCompositors() -{ - return InstanceIterator(mInstances.begin(), mInstances.end()); -} -//----------------------------------------------------------------------- -void CompositorChain::setCompositorEnabled(size_t position, bool state) -{ - CompositorInstance* inst = mInstances[position]; - if (!state && inst->getEnabled()) - { - // If we're disabling a 'middle' compositor in a chain, we have to be - // careful about textures which might have been shared by non-adjacent - // instances which have now become adjacent. - CompositorInstance* nextInstance = getNextInstance(inst, true); - if (nextInstance) - { - const CompositionTechnique::TargetPasses& tps = - nextInstance->getTechnique()->getTargetPasses(); - CompositionTechnique::TargetPasses::const_iterator tpit = tps.begin(); - for(;tpit != tps.end(); ++tpit) - { - CompositionTargetPass* tp = *tpit; - if (tp->getInputMode() == CompositionTargetPass::IM_PREVIOUS) - { - if (nextInstance->getTechnique()->getTextureDefinition(tp->getOutputName())->pooled) - { - // recreate - nextInstance->freeResources(false, true); - nextInstance->createResources(false); - } - } - - } - } - - } - inst->setEnabled(state); -} -//----------------------------------------------------------------------- -static const Quaternion& getCubemapRotation(int i) -{ - static const Quaternion CubemapRotations[6] = { - Quaternion(Degree(-90), Vector3::UNIT_Y), //+X - Quaternion(Degree(90), Vector3::UNIT_Y), //-X - Quaternion(Degree(90), Vector3::UNIT_X), //+Y - Quaternion(Degree(-90), Vector3::UNIT_X), //-Y - Quaternion::IDENTITY, //+Z - Quaternion(Degree(180), Vector3::UNIT_Y) //-Z - }; - - return CubemapRotations[i]; -} -void CompositorChain::preRenderTargetUpdate(const RenderTargetEvent& evt) -{ - /// Compile if state is dirty - if(mDirty) - _compile(); - - // Do nothing if no compositors enabled - if (!mAnyCompositorsEnabled) - { - return; - } - - - /// Update dependent render targets; this is done in the preRenderTarget - /// and not the preViewportUpdate for a reason: at this time, the - /// target Rendertarget will not yet have been set as current. - /// ( RenderSystem::setViewport(...) ) if it would have been, the rendering - /// order would be screwed up and problems would arise with copying rendertextures. - Camera *cam = mViewport->getCamera(); - if (cam) - { - cam->getSceneManager()->_setActiveCompositorChain(this); - } - - /// Iterate over compiled state - for(auto& op : mCompiledState) - { - /// Skip if this is a target that should only be initialised initially - if(op.onlyInitial && op.hasBeenRendered) - continue; - op.hasBeenRendered = true; - - auto vp = op.target->getViewport(0); - if (!op.cameraOverride.empty()) - { - SceneManager *sm = cam->getSceneManager(); - cam = sm->getCamera(op.cameraOverride); - vp->setCamera(cam); - } - - if (op.alignCameraToFace > -1) - { - cam->getParentSceneNode()->setOrientation(getCubemapRotation(op.alignCameraToFace)); - } - - /// Setup and render - preTargetOperation(op, vp, cam); - op.target->update(); - postTargetOperation(op, vp, cam); - } -} -//----------------------------------------------------------------------- -void CompositorChain::postRenderTargetUpdate(const RenderTargetEvent& evt) -{ - Camera *cam = mViewport->getCamera(); - if (cam) - { - cam->getSceneManager()->_setActiveCompositorChain(0); - } -} -//----------------------------------------------------------------------- -void CompositorChain::preViewportUpdate(const RenderTargetViewportEvent& evt) -{ - // Only set up if there is at least one compositor enabled, and it's this viewport - if(evt.source != mViewport || !mAnyCompositorsEnabled) - return; - - // set original scene details from viewport - CompositionPass* pass = mOriginalScene->getTechnique()->getOutputTargetPass()->getPasses()[0]; - CompositionTargetPass* passParent = pass->getParent(); - if (pass->getClearBuffers() != mOldClearEveryFrameBuffers || - pass->getClearDepth() != mViewport->getDepthClear() || - passParent->getVisibilityMask() != mViewport->getVisibilityMask() || - passParent->getMaterialScheme() != mViewport->getMaterialScheme() || - passParent->getShadowsEnabled() != mViewport->getShadowsEnabled()) - { - // recompile if viewport settings are different - pass->setClearBuffers(mOldClearEveryFrameBuffers); - pass->setClearDepth(mViewport->getDepthClear()); - passParent->setVisibilityMask(mViewport->getVisibilityMask()); - passParent->setMaterialScheme(mViewport->getMaterialScheme()); - passParent->setShadowsEnabled(mViewport->getShadowsEnabled()); - _compile(); - } - - Camera *cam = mViewport->getCamera(); - if (cam) - { - /// Prepare for output operation - preTargetOperation(mOutputOperation, mViewport, cam); - } -} -//----------------------------------------------------------------------- -void CompositorChain::preTargetOperation(CompositorInstance::TargetOperation &op, Viewport *vp, Camera *cam) -{ - if (cam) - { - SceneManager *sm = cam->getSceneManager(); - /// Set up render target listener - mOurListener.setOperation(&op, sm, sm->getDestinationRenderSystem()); - mOurListener.notifyViewport(vp); - /// Register it - sm->addRenderQueueListener(&mOurListener); - /// Set whether we find visibles - mOldFindVisibleObjects = sm->getFindVisibleObjects(); - sm->setFindVisibleObjects(op.findVisibleObjects); - /// Set LOD bias level - mOldLodBias = cam->getLodBias(); - cam->setLodBias(cam->getLodBias() * op.lodBias); - } - - // Set the visibility mask - mOldVisibilityMask = vp->getVisibilityMask(); - vp->setVisibilityMask(op.visibilityMask); - /// Set material scheme - mOldMaterialScheme = vp->getMaterialScheme(); - vp->setMaterialScheme(op.materialScheme); - /// Set shadows enabled - mOldShadowsEnabled = vp->getShadowsEnabled(); - vp->setShadowsEnabled(op.shadowsEnabled); - /// XXX TODO - //vp->setClearEveryFrame( true ); - //vp->setOverlaysEnabled( false ); - //vp->setBackgroundColour( op.clearColour ); -} -//----------------------------------------------------------------------- -void CompositorChain::postTargetOperation(CompositorInstance::TargetOperation &op, Viewport *vp, Camera *cam) -{ - if (cam) - { - SceneManager *sm = cam->getSceneManager(); - /// Unregister our listener - sm->removeRenderQueueListener(&mOurListener); - /// Restore default scene and camera settings - sm->setFindVisibleObjects(mOldFindVisibleObjects); - cam->setLodBias(mOldLodBias); - } - - vp->setVisibilityMask(mOldVisibilityMask); - vp->setMaterialScheme(mOldMaterialScheme); - vp->setShadowsEnabled(mOldShadowsEnabled); -} -//----------------------------------------------------------------------- -void CompositorChain::postViewportUpdate(const RenderTargetViewportEvent& evt) -{ - // Only tidy up if there is at least one compositor enabled, and it's this viewport - if(evt.source != mViewport || !mAnyCompositorsEnabled) - return; - - Camera *cam = mViewport->getCamera(); - postTargetOperation(mOutputOperation, mViewport, cam); -} -//----------------------------------------------------------------------- -void CompositorChain::viewportCameraChanged(Viewport* viewport) -{ - Camera* camera = viewport->getCamera(); - for (auto *i : mInstances) - { - i->notifyCameraChanged(camera); - } -} -//----------------------------------------------------------------------- -void CompositorChain::viewportDimensionsChanged(Viewport* viewport) -{ - for (auto *i : mInstances) - { - i->notifyResized(); - } -} -//----------------------------------------------------------------------- -void CompositorChain::viewportDestroyed(Viewport* viewport) -{ - // this chain is now orphaned. tell compositor manager to delete it. - CompositorManager::getSingleton().removeCompositorChain(viewport); -} -//----------------------------------------------------------------------- -void CompositorChain::clearCompiledState() -{ - for (auto *r : mRenderSystemOperations) - { - OGRE_DELETE r; - } - mRenderSystemOperations.clear(); - - /// Clear compiled state - mCompiledState.clear(); - mOutputOperation = CompositorInstance::TargetOperation(0); - -} -//----------------------------------------------------------------------- -void CompositorChain::_compile() -{ - // remove original scene if it has the wrong material scheme - if( mOriginalSceneScheme != mViewport->getMaterialScheme() ) - { - destroyOriginalScene(); - createOriginalScene(); - } - - clearCompiledState(); - - bool compositorsEnabled = false; - - // force default scheme so materials for compositor quads will determined correctly - MaterialManager& matMgr = MaterialManager::getSingleton(); - String prevMaterialScheme = matMgr.getActiveScheme(); - matMgr.setActiveScheme(Root::getSingleton().getRenderSystem()->_getDefaultViewportMaterialScheme()); - - /// Set previous CompositorInstance for each compositor in the list - CompositorInstance *lastComposition = mOriginalScene; - mOriginalScene->mPreviousInstance = 0; - for(auto *i : mInstances) - { - if(i->getEnabled()) - { - compositorsEnabled = true; - i->mPreviousInstance = lastComposition; - lastComposition = i; - } - } - - - /// Compile misc targets - lastComposition->_compileTargetOperations(mCompiledState); - - /// Final target viewport (0) - mOutputOperation.renderSystemOperations.clear(); - lastComposition->_compileOutputOperation(mOutputOperation); - - // Deal with viewport settings - if (compositorsEnabled != mAnyCompositorsEnabled) - { - mAnyCompositorsEnabled = compositorsEnabled; - if (mAnyCompositorsEnabled) - { - // Save old viewport clearing options - mOldClearEveryFrameBuffers = mViewport->getClearBuffers(); - // Don't clear anything every frame since we have our own clear ops - mViewport->setClearEveryFrame(false); - } - else - { - // Reset clearing options - mViewport->setClearEveryFrame(mOldClearEveryFrameBuffers > 0, - mOldClearEveryFrameBuffers); - } - } - - // restore material scheme - matMgr.setActiveScheme(prevMaterialScheme); - - - mDirty = false; -} -//----------------------------------------------------------------------- -void CompositorChain::_markDirty() -{ - mDirty = true; -} -//----------------------------------------------------------------------- -Viewport *CompositorChain::getViewport() -{ - return mViewport; -} -//--------------------------------------------------------------------- -void CompositorChain::_notifyViewport(Viewport* vp) -{ - if (vp != mViewport) - { - if (mViewport != NULL) - mViewport->removeListener(this); - - if (vp != NULL) - vp->addListener(this); - - if (!vp || !mViewport || vp->getTarget() != mViewport->getTarget()) - { - if(mViewport) - mViewport->getTarget()->removeListener(this); - - if(vp) - vp->getTarget()->addListener(this); - } - mOurListener.notifyViewport(vp); - mViewport = vp; - } -} -//----------------------------------------------------------------------- -void CompositorChain::RQListener::renderQueueStarted(uint8 id, - const String& cameraName, bool& skipThisQueue) -{ - // Skip when not matching viewport - // shadows update is nested within main viewport update - if (mSceneManager->getCurrentViewport() != mViewport) - return; - - flushUpTo(id); - /// If no one wants to render this queue, skip it - /// Don't skip the OVERLAY queue because that's handled separately - if(!mOperation->renderQueues.test(id) && id!=RENDER_QUEUE_OVERLAY) - { - skipThisQueue = true; - } -} -//----------------------------------------------------------------------- -void CompositorChain::RQListener::setOperation(CompositorInstance::TargetOperation *op,SceneManager *sm,RenderSystem *rs) -{ - mOperation = op; - mSceneManager = sm; - mRenderSystem = rs; - currentOp = op->renderSystemOperations.begin(); - lastOp = op->renderSystemOperations.end(); -} -//----------------------------------------------------------------------- -void CompositorChain::RQListener::flushUpTo(uint8 id) -{ - /// Process all RenderSystemOperations up to and including render queue id. - /// Including, because the operations for RenderQueueGroup x should be executed - /// at the beginning of the RenderQueueGroup render for x. - while(currentOp != lastOp && currentOp->first <= id) - { - currentOp->second->execute(mSceneManager, mRenderSystem); - ++currentOp; - } -} -//----------------------------------------------------------------------- -CompositorInstance* CompositorChain::getPreviousInstance(CompositorInstance* curr, bool activeOnly) -{ - bool found = false; - for(Instances::reverse_iterator i=mInstances.rbegin(); i!=mInstances.rend(); ++i) - { - if (found) - { - if ((*i)->getEnabled() || !activeOnly) - return *i; - } - else if(*i == curr) - { - found = true; - } - } - - return 0; -} -//--------------------------------------------------------------------- -CompositorInstance* CompositorChain::getNextInstance(CompositorInstance* curr, bool activeOnly) -{ - bool found = false; - for(auto *i : mInstances) - { - if (found) - { - if (i->getEnabled() || !activeOnly) - return i; - } - else if(i == curr) - { - found = true; - } - } - - return 0; -} -//--------------------------------------------------------------------- -} - diff --git a/OgreMain/src/OgreCompositorInstance.cpp b/OgreMain/src/OgreCompositorInstance.cpp deleted file mode 100644 index c5af02583d2..00000000000 --- a/OgreMain/src/OgreCompositorInstance.cpp +++ /dev/null @@ -1,1252 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreCompositor.h" -#include "OgreCompositorInstance.h" -#include "OgreCompositorChain.h" -#include "OgreCompositorManager.h" -#include "OgreCompositionTargetPass.h" -#include "OgreCustomCompositionPass.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreCompositorLogic.h" -#include "OgreRenderTarget.h" -#include "OgreRenderTexture.h" -#include "OgreRectangle2D.h" -#include "OgreDepthBuffer.h" - -namespace Ogre { -CompositorInstance::CompositorInstance(CompositionTechnique *technique, - CompositorChain *chain): - mCompositor(technique->getParent()), mTechnique(technique), mChain(chain), - mEnabled(false), - mAlive(false) -{ - OgreAssert(mChain, "Undefined compositor chain"); - mEnabled = false; - const String& logicName = mTechnique->getCompositorLogicName(); - if (!logicName.empty()) - { - CompositorManager::getSingleton(). - getCompositorLogic(logicName)->compositorInstanceCreated(this); - } -} -//----------------------------------------------------------------------- -CompositorInstance::~CompositorInstance() -{ - const String& logicName = mTechnique->getCompositorLogicName(); - if (!logicName.empty()) - { - CompositorManager::getSingleton(). - getCompositorLogic(logicName)->compositorInstanceDestroyed(this); - } - - freeResources(false, true); -} -//----------------------------------------------------------------------- -void CompositorInstance::setEnabled(bool value) -{ - if (mEnabled != value) - { - mEnabled = value; - - //Probably first time enabling, create resources. - if( mEnabled && !mAlive ) - setAlive( true ); - - /// Notify chain state needs recompile. - mChain->_markDirty(); - } -} -//----------------------------------------------------------------------- -void CompositorInstance::setAlive(bool value) -{ - if (mAlive != value) - { - mAlive = value; - - // Create of free resource. - if (value) - { - createResources(false); - } - else - { - freeResources(false, true); - setEnabled(false); - } - - /// Notify chain state needs recompile. - mChain->_markDirty(); - } -} -//----------------------------------------------------------------------- - -/** Clear framebuffer RenderSystem operation - */ -class RSClearOperation: public CompositorInstance::RenderSystemOperation -{ -public: - RSClearOperation(uint32 inBuffers, ColourValue inColour, Real inDepth, unsigned short inStencil, CompositorChain *inChain): - chain(inChain), buffers(inBuffers), colour(inColour), depth(inDepth), stencil(inStencil) - {} - /// Automatic colour from original viewport background colour - CompositorChain* chain; - /// Which buffers to clear (FrameBufferType) - uint32 buffers; - /// Colour to clear in case FBT_COLOUR is set - ColourValue colour; - /// Depth to set in case FBT_DEPTH is set - Real depth; - /// Stencil value to set in case FBT_STENCIL is set - unsigned short stencil; - - void execute(SceneManager *sm, RenderSystem *rs) override - { - if((buffers & FBT_COLOUR) && chain) // if chain is present, query colour from dst viewport - colour = chain->getViewport()->getBackgroundColour(); - rs->clearFrameBuffer(buffers, colour, depth, stencil); - } -}; - -/** "Set stencil state" RenderSystem operation - */ -class RSStencilOperation: public CompositorInstance::RenderSystemOperation -{ -public: - RSStencilOperation(const StencilState& inState) : state(inState) {} - - StencilState state; - - void execute(SceneManager *sm, RenderSystem *rs) override - { - rs->setStencilState(state); - } -}; - -/** "Render quad" RenderSystem operation - */ -class RSQuadOperation: public CompositorInstance::RenderSystemOperation -{ -public: - RSQuadOperation(CompositorInstance *inInstance, uint32 inPass_id, const MaterialPtr& inMat): - mat(inMat), instance(inInstance), pass_id(inPass_id), - mQuadCornerModified(false), - mQuadFarCorners(false), - mQuadFarCornersViewSpace(false), - mQuad(-1, 1, 1, -1) - { - instance->_fireNotifyMaterialSetup(pass_id, mat); - technique = mat->getBestTechnique(); - assert(technique); - } - MaterialPtr mat; - Technique *technique; - CompositorInstance *instance; - uint32 pass_id; - - bool mQuadCornerModified, mQuadFarCorners, mQuadFarCornersViewSpace; - FloatRect mQuad; - - void setQuadCorners(const FloatRect& quad) - { - mQuad = quad; - mQuadCornerModified=true; - } - - void setQuadFarCorners(bool farCorners, bool farCornersViewSpace) - { - mQuadFarCorners = farCorners; - mQuadFarCornersViewSpace = farCornersViewSpace; - } - - void execute(SceneManager *sm, RenderSystem *rs) override - { - // Fire listener - instance->_fireNotifyMaterialRender(pass_id, mat); - - Viewport* vp = rs->_getViewport(); - Rectangle2D *rect = static_cast(CompositorManager::getSingleton()._getTexturedRectangle2D()); - - if (mQuadCornerModified) - { - // insure positions are using peculiar render system offsets - Real hOffset = rs->getHorizontalTexelOffset() / (0.5f * vp->getActualWidth()); - Real vOffset = rs->getVerticalTexelOffset() / (0.5f * vp->getActualHeight()); - rect->setCorners(mQuad.left + hOffset, mQuad.top - vOffset, mQuad.right + hOffset, mQuad.bottom - vOffset); - } - - if(mQuadFarCorners) - { - const Ogre::Vector3 *corners = vp->getCamera()->getWorldSpaceCorners(); - if(mQuadFarCornersViewSpace) - { - const Affine3 &viewMat = vp->getCamera()->getViewMatrix(true); - rect->setNormals(viewMat*corners[5], viewMat*corners[6], viewMat*corners[4], viewMat*corners[7]); - } - else - { - rect->setNormals(corners[5], corners[6], corners[4], corners[7]); - } - } - - // Queue passes from mat - for(auto *p : technique->getPasses()) - { - sm->_injectRenderWithPass( - p, - rect, - false // don't allow replacement of shadow passes - ); - } - } -}; - -/** "Set material scheme" RenderSystem operation - */ -class RSSetSchemeOperation: public CompositorInstance::RenderSystemOperation -{ -public: - RSSetSchemeOperation(const String& schemeName) : mPreviousLateResolving(false), mSchemeName(schemeName) {} - - String mPreviousScheme; - bool mPreviousLateResolving; - - String mSchemeName; - - void execute(SceneManager *sm, RenderSystem *rs) override - { - MaterialManager& matMgr = MaterialManager::getSingleton(); - mPreviousScheme = matMgr.getActiveScheme(); - matMgr.setActiveScheme(mSchemeName); - - mPreviousLateResolving = sm->isLateMaterialResolving(); - sm->setLateMaterialResolving(true); - } - - const String& getPreviousScheme() const { return mPreviousScheme; } - bool getPreviousLateResolving() const { return mPreviousLateResolving; } -}; - -/** Restore the settings changed by the set scheme operation */ -class RSRestoreSchemeOperation: public CompositorInstance::RenderSystemOperation -{ -public: - RSRestoreSchemeOperation(const RSSetSchemeOperation* setOperation) : - mSetOperation(setOperation) {} - - const RSSetSchemeOperation* mSetOperation; - - void execute(SceneManager *sm, RenderSystem *rs) override - { - MaterialManager::getSingleton().setActiveScheme(mSetOperation->getPreviousScheme()); - sm->setLateMaterialResolving(mSetOperation->getPreviousLateResolving()); - } -}; - -class RSComputeOperation : public CompositorInstance::RenderSystemOperation -{ -public: - MaterialPtr mat; - Technique *technique; - Vector3i thread_groups; - CompositorInstance *instance; - uint32 pass_id; - - RSComputeOperation(CompositorInstance *inInstance, uint32 inPass_id, const MaterialPtr& inMat): - mat(inMat), instance(inInstance), pass_id(inPass_id) - { - instance->_fireNotifyMaterialSetup(pass_id, mat); - technique = mat->getBestTechnique(); - } - - void execute(SceneManager *sm, RenderSystem *rs) override - { - // Fire listener - instance->_fireNotifyMaterialRender(pass_id, mat); - // Queue passes from mat - for(auto* pass : technique->getPasses()) - { - int tuIdx = 0; - for(auto* tu : pass->getTextureUnitStates()) - rs->_setTextureUnitSettings(tuIdx++, *tu); - auto params = pass->getGpuProgramParameters(GPT_COMPUTE_PROGRAM); - params->_updateAutoParams(sm->_getAutoParamDataSource(), GPV_GLOBAL); - rs->bindGpuProgram(pass->getComputeProgram()->_getBindingDelegate()); - rs->bindGpuProgramParameters(GPT_COMPUTE_PROGRAM, params, GPV_GLOBAL); - rs->_dispatchCompute(thread_groups); - } - } -}; - -void CompositorInstance::collectPasses(TargetOperation &finalState, const CompositionTargetPass *target) -{ - /// Here, passes are converted into render target operations - Pass *targetpass; - Technique *srctech; - MaterialPtr mat, srcmat; - - for (CompositionPass* pass : target->getPasses()) - { - bool isCompute = false; - switch(pass->getType()) - { - case CompositionPass::PT_CLEAR: - queueRenderSystemOp(finalState, OGRE_NEW RSClearOperation( - pass->getClearBuffers(), - pass->getClearColour(), - pass->getClearDepth(), - pass->getClearStencil(), - pass->getAutomaticColour() ? mChain : NULL - )); - break; - case CompositionPass::PT_STENCIL: - queueRenderSystemOp(finalState, OGRE_NEW RSStencilOperation(pass->getStencilState())); - break; - case CompositionPass::PT_RENDERSCENE: - { - if(pass->getFirstRenderQueue() < finalState.currentQueueGroupID) - { - /// XXX We could support repeating the last queue, with some effort - LogManager::getSingleton().logError(StringUtil::format( - "Compositor '%s': cannot use first_render_queue %d after last_render_queue %d", - mCompositor->getName().c_str(), pass->getFirstRenderQueue(), finalState.currentQueueGroupID - 1)); - } - - RSSetSchemeOperation* setSchemeOperation = 0; - if (!pass->getMaterialScheme().empty()) - { - //Add the triggers that will set the scheme and restore it each frame - finalState.currentQueueGroupID = pass->getFirstRenderQueue(); - setSchemeOperation = OGRE_NEW RSSetSchemeOperation(pass->getMaterialScheme()); - queueRenderSystemOp(finalState, setSchemeOperation); - } - - /// Add render queues - for(int x=pass->getFirstRenderQueue(); x<=pass->getLastRenderQueue(); ++x) - { - assert(x>=0); - finalState.renderQueues.set(x); - } - finalState.currentQueueGroupID = pass->getLastRenderQueue()+1; - - if (setSchemeOperation != 0) - { - //Restoring the scheme after the queues have been rendered - queueRenderSystemOp(finalState, - OGRE_NEW RSRestoreSchemeOperation(setSchemeOperation)); - } - - finalState.cameraOverride = pass->getCameraName(); - finalState.alignCameraToFace = pass->getAlignCameraToFace() ? target->getOutputSlice() : -1; - - finalState.findVisibleObjects = true; - - break; - } - case CompositionPass::PT_COMPUTE: - isCompute = true; - OGRE_FALLTHROUGH; - case CompositionPass::PT_RENDERQUAD: { - srcmat = pass->getMaterial(); - if(!srcmat) - { - /// No material -- warn user - LogManager::getSingleton().logWarning("in compilation of Compositor " - +mCompositor->getName()+": No material defined for composition pass"); - break; - } - srcmat->load(); - if(srcmat->getSupportedTechniques().empty()) - { - /// No supported techniques -- warn user - LogManager::getSingleton().logWarning("in compilation of Compositor " - +mCompositor->getName()+": material "+srcmat->getName()+" has no supported techniques"); - break; - } - srctech = srcmat->getBestTechnique(0); - /// Create local material - MaterialPtr localMat = createLocalMaterial(srcmat->getName()); - /// Copy and adapt passes from source material - for(auto *srcpass : srctech->getPasses()) - { - /// Create new target pass - targetpass = localMat->getTechnique(0)->createPass(); - (*targetpass) = (*srcpass); - - if (isCompute && !targetpass->hasGpuProgram(GPT_COMPUTE_PROGRAM)) - { - LogManager::getSingleton().logError( - "in compilation of Compositor " + mCompositor->getName() + ": material " + - srcmat->getName() + " has no compute program"); - continue; - } - - /// Set up inputs - for(size_t x=0; xgetNumInputs(); ++x) - { - const CompositionPass::InputTex& inp = pass->getInput(x); - if(!inp.name.empty()) - { - if(x < targetpass->getNumTextureUnitStates()) - { - targetpass->getTextureUnitState((ushort)x)->setTexture(getSourceForTex(inp.name, inp.mrtIndex)); - } - else - { - /// Texture unit not there - LogManager::getSingleton().logWarning("in compilation of Compositor " - +mCompositor->getName()+": material "+srcmat->getName()+" texture unit " - +StringConverter::toString(x)+" out of bounds"); - } - } - } - } - - localMat->load(); - - if (isCompute) - { - auto computeOperation = new RSComputeOperation(this, pass->getIdentifier(), localMat); - computeOperation->thread_groups = pass->getThreadGroups(); - queueRenderSystemOp(finalState, computeOperation); - } - else - { - auto rsQuadOperation = new RSQuadOperation(this, pass->getIdentifier(), localMat); - FloatRect quad; - if (pass->getQuadCorners(quad)) - rsQuadOperation->setQuadCorners(quad); - rsQuadOperation->setQuadFarCorners(pass->getQuadFarCorners(), - pass->getQuadFarCornersViewSpace()); - queueRenderSystemOp(finalState, rsQuadOperation); - } - } - break; - case CompositionPass::PT_RENDERCUSTOM: - RenderSystemOperation* customOperation = CompositorManager::getSingleton(). - getCustomCompositionPass(pass->getCustomType())->createOperation(this, pass); - queueRenderSystemOp(finalState, customOperation); - break; - } - } -} -//----------------------------------------------------------------------- -void CompositorInstance::_compileTargetOperations(CompiledState &compiledState) -{ - /// Collect targets of previous state - if(mPreviousInstance) - mPreviousInstance->_compileTargetOperations(compiledState); - /// Texture targets - for (CompositionTargetPass *target : mTechnique->getTargetPasses()) - { - TargetOperation ts(getTargetForTex(target->getOutputName(), target->getOutputSlice())); - /// Set "only initial" flag, visibilityMask and lodBias according to CompositionTargetPass. - ts.onlyInitial = target->getOnlyInitial(); - ts.visibilityMask = target->getVisibilityMask(); - ts.lodBias = target->getLodBias(); - ts.shadowsEnabled = target->getShadowsEnabled(); - ts.materialScheme = target->getMaterialScheme(); - /// Check for input mode previous - if(target->getInputMode() == CompositionTargetPass::IM_PREVIOUS) - { - /// Collect target state for previous compositor - /// The TargetOperation for the final target is collected separately as it is merged - /// with later operations - mPreviousInstance->_compileOutputOperation(ts); - } - /// Collect passes of our own target - collectPasses(ts, target); - compiledState.push_back(ts); - } -} -//----------------------------------------------------------------------- -void CompositorInstance::_compileOutputOperation(TargetOperation &finalState) -{ - /// Final target - CompositionTargetPass *tpass = mTechnique->getOutputTargetPass(); - - /// Logical-and together the visibilityMask, and multiply the lodBias - finalState.visibilityMask &= tpass->getVisibilityMask(); - finalState.lodBias *= tpass->getLodBias(); - finalState.materialScheme = tpass->getMaterialScheme(); - finalState.shadowsEnabled = tpass->getShadowsEnabled(); - - if(tpass->getInputMode() == CompositionTargetPass::IM_PREVIOUS) - { - /// Collect target state for previous compositor - /// The TargetOperation for the final target is collected separately as it is merged - /// with later operations - mPreviousInstance->_compileOutputOperation(finalState); - } - /// Collect passes - collectPasses(finalState, tpass); -} -//----------------------------------------------------------------------- -void CompositorInstance::setTechnique(CompositionTechnique* tech, bool reuseTextures) -{ - if (mTechnique != tech) - { - if (reuseTextures) - { - // make sure we store all (shared) textures in use in our reserve pool - // this will ensure they don't get destroyed as unreferenced - // so they're ready to use again later - const CompositionTechnique::TextureDefinitions& tdefs = mTechnique->getTextureDefinitions(); - for (auto *def : tdefs) - { - if (def->pooled) - { - LocalTextureMap::iterator i = mLocalTextures.find(def->name); - if (i != mLocalTextures.end()) - { - // overwriting duplicates is fine, we only want one entry per def - mReserveTextures[def] = i->second; - } - - } - } - } - // replace technique - mTechnique = tech; - - if (mAlive) - { - // free up resources, but keep reserves if reusing - freeResources(false, !reuseTextures); - createResources(false); - /// Notify chain state needs recompile. - mChain->_markDirty(); - } - - } -} -//--------------------------------------------------------------------- -void CompositorInstance::setScheme(const String& schemeName, bool reuseTextures) -{ - CompositionTechnique* tech = mCompositor->getSupportedTechnique(schemeName); - if (tech) - { - setTechnique(tech, reuseTextures); - } -} -//----------------------------------------------------------------------- -CompositorChain *CompositorInstance::getChain() -{ - return mChain; -} -//----------------------------------------------------------------------- -const String& CompositorInstance::getTextureInstanceName(const String& name, - size_t mrtIndex) -{ - return getSourceForTex(name, mrtIndex)->getName(); -} -//--------------------------------------------------------------------- -const TexturePtr& CompositorInstance::getTextureInstance(const String& name, size_t mrtIndex) -{ - // try simple textures first - LocalTextureMap::iterator i = mLocalTextures.find(name); - if(i != mLocalTextures.end()) - { - return i->second; - } - - // try MRTs - texture (rather than target) - i = mLocalTextures.find(getMRTTexLocalName(name, mrtIndex)); - if (i != mLocalTextures.end()) - { - return i->second; - } - - // not present - static TexturePtr nullPtr; - return nullPtr; - -} -//----------------------------------------------------------------------- -MaterialPtr CompositorInstance::createLocalMaterial(const String& srcName) -{ - static size_t dummyCounter = 0; - MaterialPtr mat = MaterialManager::getSingleton().create( - StringUtil::format("c%zu/%s", dummyCounter++, srcName.c_str()), - ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME); - /// This is safe, as we hold a private reference - MaterialManager::getSingleton().remove(mat); - /// Remove all passes from first technique - mat->getTechnique(0)->removeAllPasses(); - return mat; -} -//--------------------------------------------------------------------- -void CompositorInstance::notifyResized() -{ - freeResources(true, true); - createResources(true); - /// Notify chain state needs recompile. - mChain->_markDirty(); -} -//----------------------------------------------------------------------- -void CompositorInstance::createResources(bool forResizeOnly) -{ - static size_t dummyCounter = 0; - /// Create temporary textures - /// In principle, temporary textures could be shared between multiple viewports - /// (CompositorChains). This will save a lot of memory in case more viewports - /// are composited. - CompositorManager::UniqueTextureSet assignedTextures; - - for (auto def : mTechnique->getTextureDefinitions()) - { - if (!def->refCompName.empty()) { - //This is a reference, isn't created in this compositor - continue; - } - - if (def->scope == CompositionTechnique::TS_GLOBAL) { - //This is a global texture, just link the created resources from the parent - Compositor* parentComp = mTechnique->getParent(); - if (def->formatList.size() > 1) - { - size_t atch = 0; - for (PixelFormatList::iterator p = def->formatList.begin(); - p != def->formatList.end(); ++p, ++atch) - { - Ogre::TexturePtr tex = parentComp->getTextureInstance(def->name, atch); - mLocalTextures[getMRTTexLocalName(def->name, atch)] = tex; - } - MultiRenderTarget* mrt = static_cast - (parentComp->getRenderTarget(def->name)); - mLocalMRTs[def->name] = mrt; - - setupRenderTarget(mrt, def->depthBufferId); - } else { - Ogre::TexturePtr tex = parentComp->getTextureInstance(def->name, 0); - mLocalTextures[def->name] = tex; - - for(size_t i = 0; i < tex->getNumFaces(); i++) - setupRenderTarget(tex->getBuffer(i)->getRenderTarget(), def->depthBufferId); - } - - } else { - /// Determine width and height - uint32 width = def->width; - uint32 height = def->height; - uint fsaa = 0; - String fsaaHint; - bool hwGamma = false; - - // Skip this one if we're only (re)creating for a resize & it's not derived - // from the target size - if (forResizeOnly && width != 0 && height != 0) - continue; - - deriveTextureRenderTargetOptions(def->name, &hwGamma, &fsaa, &fsaaHint); - - if(width == 0) - { - width = static_cast(mChain->getViewport()->getActualWidth()) * def->widthFactor; - width = width == 0 ? 1 : width; - } - if(height == 0) - { - height = static_cast(mChain->getViewport()->getActualHeight()) * def->heightFactor; - height = height == 0 ? 1 : height; - } - - // determine options as a combination of selected options and possible options - if (!def->fsaa) - { - fsaa = 0; - fsaaHint = BLANKSTRING; - } - hwGamma = hwGamma || def->hwGammaWrite; - - /// Make the tetxure - if (def->formatList.size() > 1) - { - String MRTbaseName = "mrt/c" + StringConverter::toString(dummyCounter++) + - "/" + def->name + "/" + mChain->getViewport()->getTarget()->getName(); - MultiRenderTarget* mrt = - Root::getSingleton().getRenderSystem()->createMultiRenderTarget(MRTbaseName); - mLocalMRTs[def->name] = mrt; - - // create and bind individual surfaces - size_t atch = 0; - for (PixelFormatList::iterator p = def->formatList.begin(); - p != def->formatList.end(); ++p, ++atch) - { - - String texname = MRTbaseName + "/" + StringConverter::toString(atch); - String mrtLocalName = getMRTTexLocalName(def->name, atch); - TexturePtr tex; - if (def->pooled) - { - // get / create pooled texture - tex = CompositorManager::getSingleton().getPooledTexture(texname, - mrtLocalName, - width, height, *p, fsaa, fsaaHint, - hwGamma && !PixelUtil::isFloatingPoint(*p), - assignedTextures, this, def->scope, def->type); - } - else - { - tex = TextureManager::getSingleton().createManual(texname, - RGN_INTERNAL, def->type, - width, height, 0, *p, TU_RENDERTARGET, 0, - hwGamma && !PixelUtil::isFloatingPoint(*p), fsaa, fsaaHint ); - } - - RenderTexture* rt = tex->getBuffer()->getRenderTarget(); - rt->setAutoUpdated(false); - mrt->bindSurface(atch, rt); - - // Also add to local textures so we can look up - mLocalTextures[mrtLocalName] = tex; - - } - - setupRenderTarget(mrt, def->depthBufferId); - } - else - { - String texName = "c" + StringConverter::toString(dummyCounter++) + - "/" + def->name + "/" + mChain->getViewport()->getTarget()->getName(); - - // space in the name mixup the cegui in the compositor demo - // this is an auto generated name - so no spaces can't hart us. - std::replace( texName.begin(), texName.end(), ' ', '_' ); - - hwGamma = hwGamma && !PixelUtil::isFloatingPoint(def->formatList[0]); - - TexturePtr tex; - if (def->pooled) - { - // get / create pooled texture - tex = CompositorManager::getSingleton().getPooledTexture(texName, - def->name, width, height, def->formatList[0], fsaa, fsaaHint, - hwGamma, assignedTextures, - this, def->scope, def->type); - } - else - { - tex = TextureManager::getSingleton().createManual( - texName, RGN_INTERNAL, def->type, width, height, 0, def->formatList[0], - TU_RENDERTARGET, 0, hwGamma, fsaa, fsaaHint); - } - - mLocalTextures[def->name] = tex; - - for(size_t i = 0; i < tex->getNumFaces(); i++) - setupRenderTarget(tex->getBuffer(i)->getRenderTarget(), def->depthBufferId); - } - } - } - - _fireNotifyResourcesCreated(forResizeOnly); -} - -void CompositorInstance::setupRenderTarget(RenderTarget* rendTarget, uint16 depthBufferId) -{ - if(rendTarget->getDepthBufferPool() != DepthBuffer::POOL_NO_DEPTH) - { - //Set DepthBuffer pool for sharing - rendTarget->setDepthBufferPool( depthBufferId ); - } - - /// Set up viewport over entire texture - rendTarget->setAutoUpdated( false ); - - // We may be sharing / reusing this texture, so test before adding viewport - if (rendTarget->getNumViewports() != 0) - return; - - Viewport* v; - Camera* camera = mChain->getViewport()->getCamera(); - if (!camera) - { - v = rendTarget->addViewport( camera ); - } - else - { - // Save last viewport and current aspect ratio - Viewport* oldViewport = camera->getViewport(); - Real aspectRatio = camera->getAspectRatio(); - - v = rendTarget->addViewport( camera ); - - // Should restore aspect ratio, in case of auto aspect ratio - // enabled, it'll changed when add new viewport. - camera->setAspectRatio(aspectRatio); - // Should restore last viewport, i.e. never disturb user code - // which might based on that. - camera->_notifyViewport(oldViewport); - } - - v->setClearEveryFrame( false ); - v->setOverlaysEnabled( false ); - v->setBackgroundColour( ColourValue( 0, 0, 0, 0 ) ); -} - -//--------------------------------------------------------------------- -void CompositorInstance::deriveTextureRenderTargetOptions( - const String& texname, bool *hwGammaWrite, uint *fsaa, String* fsaaHint) -{ - // search for passes on this texture def that either include a render_scene - // or use input previous - bool renderingScene = false; - - const CompositionTechnique::TargetPasses& passes = mTechnique->getTargetPasses(); - for (auto *tp : passes) - { - if (tp->getOutputName() == texname) - { - if (tp->getInputMode() == CompositionTargetPass::IM_PREVIOUS) - { - // this may be rendering the scene implicitly - // Can't check mPreviousInstance against mChain->_getOriginalSceneCompositor() - // at this time, so check the position - renderingScene = true; - for(CompositorInstance* inst : mChain->getCompositorInstances()) - { - if (inst == this) - break; - else if (inst->getEnabled()) - { - // nope, we have another compositor before us, this will - // be doing the AA - renderingScene = false; - } - } - if (renderingScene) - break; - } - else - { - // look for a render_scene pass - CompositionTargetPass::Passes::const_iterator pit = tp->getPasses().begin(); - - for (;pit != tp->getPasses().end(); ++pit) - { - CompositionPass* pass = *pit; - if (pass->getType() == CompositionPass::PT_RENDERSCENE) - { - renderingScene = true; - break; - } - } - } - - } - } - - if (renderingScene) - { - // Ok, inherit settings from target - RenderTarget* target = mChain->getViewport()->getTarget(); - *hwGammaWrite = target->isHardwareGammaEnabled(); - *fsaa = target->getFSAA(); - *fsaaHint = target->getFSAAHint(); - } - else - { - *hwGammaWrite = false; - *fsaa = 0; - *fsaaHint = BLANKSTRING; - } - -} -//--------------------------------------------------------------------- -String CompositorInstance::getMRTTexLocalName(const String& baseName, size_t attachment) -{ - return StringUtil::format("%s/%zu", baseName.c_str(), attachment); -} -//----------------------------------------------------------------------- -void CompositorInstance::freeResources(bool forResizeOnly, bool clearReserveTextures) -{ - // send notification, this is usefull when a RTT is used and need - // to free other resources before the destruction - _fireNotifyResourcesReleased(forResizeOnly); - - // Remove temporary textures - // We only remove those that are not shared, shared textures are dealt with - // based on their reference count. - // We can also only free textures which are derived from the target size, if - // required (saves some time & memory thrashing / fragmentation on resize) - - const CompositionTechnique::TextureDefinitions& tdefs = mTechnique->getTextureDefinitions(); - for (auto *def : tdefs) - { - if (!def->refCompName.empty()) - { - //This is a reference, isn't created here - continue; - } - - // potentially only remove this one if based on size - if (!forResizeOnly || (def->width == 0) || (def->height == 0)) - { - size_t subSurf = def->formatList.size(); - - // Potentially many surfaces - for (size_t s = 0; s < subSurf; ++s) - { - String texName = subSurf > 1 ? getMRTTexLocalName(def->name, s) - : def->name; - - LocalTextureMap::iterator i = mLocalTextures.find(texName); - if (i != mLocalTextures.end()) - { - if (!def->pooled && def->scope != CompositionTechnique::TS_GLOBAL) - { - // remove myself from central only if not pooled and not global - TextureManager::getSingleton().remove(i->second); - } - - // remove from local - // reserves are potentially cleared later - mLocalTextures.erase(i); - - } - - } // subSurf - - if (subSurf > 1) - { - LocalMRTMap::iterator mrti = mLocalMRTs.find(def->name); - if (mrti != mLocalMRTs.end()) - { - if (def->scope != CompositionTechnique::TS_GLOBAL) - { - // remove MRT if not global - Root::getSingleton().getRenderSystem()->destroyRenderTarget(mrti->second->getName()); - } - - mLocalMRTs.erase(mrti); - } - - } - - } // not for resize or width/height 0 - } - - if (clearReserveTextures) - { - if (forResizeOnly) - { - // just remove the ones which would be affected by a resize - for (auto& t : mReserveTextures) - { - if (t.first->width == 0 || t.first->height == 0) - { - mReserveTextures.erase(t.first); - } - } - } - else - { - // clear all - mReserveTextures.clear(); - } - } - - // Now we tell the central list of textures to check if its unreferenced, - // and to remove if necessary. Anything shared that was left in the reserve textures - // will not be released here - CompositorManager::getSingleton().freePooledTextures(true); -} -//--------------------------------------------------------------------- -RenderTarget* CompositorInstance::getRenderTarget(const String& name, int slice) -{ - return getTargetForTex(name, slice); -} - -CompositionTechnique::TextureDefinition* -CompositorInstance::resolveTexReference(const CompositionTechnique::TextureDefinition* texDef) -{ - //This TextureDefinition is reference. - //Since referenced TD's have no info except name we have to find original TD - - CompositionTechnique::TextureDefinition* refTexDef = 0; - - //Try chain first - if (CompositorInstance* refCompInst = mChain->getCompositor(texDef->refCompName)) - { - refTexDef = refCompInst->getCompositor() - ->getSupportedTechnique(refCompInst->getScheme()) - ->getTextureDefinition(texDef->refTexName); - } - - if(!refTexDef) - { - //Still NULL. Try global search. - const CompositorPtr &refComp = CompositorManager::getSingleton().getByName(texDef->refCompName); - if(refComp) - { - refTexDef = refComp->getSupportedTechnique()->getTextureDefinition(texDef->refTexName); - } - - if (refTexDef && refTexDef->scope != CompositionTechnique::TS_GLOBAL) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Referenced texture '" + texDef->refTexName + "' must have global scope"); - } - - OgreAssert(refTexDef, "Referencing non-existent compositor texture"); - - if (refTexDef->scope == CompositionTechnique::TS_LOCAL) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Referenced texture '" + texDef->refTexName + "' has only local scope"); - - return refTexDef; -} - -//----------------------------------------------------------------------- -RenderTarget *CompositorInstance::getTargetForTex(const String &name, int slice) -{ - // try simple texture - LocalTextureMap::iterator i = mLocalTextures.find(name); - if(i != mLocalTextures.end()) - return i->second->getBuffer(slice)->getRenderTarget(); - - // try MRTs - LocalMRTMap::iterator mi = mLocalMRTs.find(name); - if (mi != mLocalMRTs.end()) - return mi->second; - - //Try reference : Find the instance and check if it is before us - CompositionTechnique::TextureDefinition* texDef = mTechnique->getTextureDefinition(name); - if (texDef != 0 && !texDef->refCompName.empty()) - { - auto refTexDef = resolveTexReference(texDef); - - switch(refTexDef->scope) - { - case CompositionTechnique::TS_CHAIN: - { - //Find the instance and check if it is before us - CompositorInstance* refCompInst = 0; - bool beforeMe = true; - for (CompositorInstance* nextCompInst : mChain->getCompositorInstances()) - { - if (nextCompInst->getCompositor()->getName() == texDef->refCompName) - { - refCompInst = nextCompInst; - break; - } - if (nextCompInst == this) - { - //We encountered ourselves while searching for the compositor - - //we are earlier in the chain. - beforeMe = false; - } - } - - OgreAssert(refCompInst && refCompInst->getEnabled(), "Referencing inactive compositor texture"); - OgreAssert(beforeMe, "Referencing compositor that is later in the chain"); - return refCompInst->getRenderTarget(texDef->refTexName, slice); - } - case CompositionTechnique::TS_GLOBAL: - { - //Chain and global case - the referenced compositor will know how to handle - const CompositorPtr& refComp = CompositorManager::getSingleton().getByName(texDef->refCompName); - OgreAssert(refComp, "Referencing non-existent compositor"); - return refComp->getRenderTarget(texDef->refTexName, slice); - } - case CompositionTechnique::TS_LOCAL: - break; // handled by resolveTexReference - } - } - - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Non-existent local texture name", - "CompositorInstance::getTargetForTex"); - -} -//----------------------------------------------------------------------- -const TexturePtr &CompositorInstance::getSourceForTex(const String &name, size_t mrtIndex) -{ - CompositionTechnique::TextureDefinition* texDef = mTechnique->getTextureDefinition(name); - OgreAssert(texDef, "Referencing non-existent TextureDefinition"); - - //Check if texture definition is reference - if(!texDef->refCompName.empty()) - { - auto refTexDef = resolveTexReference(texDef); - - switch(refTexDef->scope) - { - case CompositionTechnique::TS_CHAIN: - { - //Find the instance and check if it is before us - CompositorInstance* refCompInst = 0; - bool beforeMe = true; - for (CompositorInstance* nextCompInst : mChain->getCompositorInstances()) - { - if (nextCompInst->getCompositor()->getName() == texDef->refCompName) - { - refCompInst = nextCompInst; - break; - } - if (nextCompInst == this) - { - //We encountered ourselves while searching for the compositor - - //we are earlier in the chain. - beforeMe = false; - } - } - - OgreAssert(refCompInst && refCompInst->getEnabled(), "Referencing inactive compositor texture"); - OgreAssert(beforeMe, "Referencing compositor that is later in the chain"); - return refCompInst->getTextureInstance(texDef->refTexName, mrtIndex); - } - case CompositionTechnique::TS_GLOBAL: - { - //Chain and global case - the referenced compositor will know how to handle - const CompositorPtr& refComp = CompositorManager::getSingleton().getByName(texDef->refCompName); - OgreAssert(refComp, "Referencing non-existent compositor"); - return refComp->getTextureInstance(texDef->refTexName, mrtIndex); - } - case CompositionTechnique::TS_LOCAL: - break; // handled by resolveTexReference - } - - } // End of handling texture references - - if (texDef->formatList.size() == 1) - { - //This is a simple texture - LocalTextureMap::iterator i = mLocalTextures.find(name); - if(i != mLocalTextures.end()) - { - return i->second; - } - } - else - { - // try MRTs - texture (rather than target) - LocalTextureMap::iterator i = mLocalTextures.find(getMRTTexLocalName(name, mrtIndex)); - if (i != mLocalTextures.end()) - { - return i->second; - } - } - - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Non-existent local texture name", - "CompositorInstance::getSourceForTex"); -} -//----------------------------------------------------------------------- -void CompositorInstance::queueRenderSystemOp(TargetOperation &finalState, RenderSystemOperation *op) -{ - /// Store operation for current QueueGroup ID - finalState.renderSystemOperations.push_back(RenderSystemOpPair(finalState.currentQueueGroupID, op)); - /// Tell parent for deletion - mChain->_queuedOperation(op); -} -//----------------------------------------------------------------------- -void CompositorInstance::addListener(Listener *l) -{ - if (std::find(mListeners.begin(), mListeners.end(), l) == mListeners.end()) - mListeners.push_back(l); -} -//----------------------------------------------------------------------- -void CompositorInstance::removeListener(Listener *l) -{ - Listeners::iterator i = std::find(mListeners.begin(), mListeners.end(), l); - if (i != mListeners.end()) - mListeners.erase(i); -} -//----------------------------------------------------------------------- -void CompositorInstance::_fireNotifyMaterialSetup(uint32 pass_id, MaterialPtr &mat) -{ - for(auto *l : mListeners) - l->notifyMaterialSetup(pass_id, mat); -} -//----------------------------------------------------------------------- -void CompositorInstance::_fireNotifyMaterialRender(uint32 pass_id, MaterialPtr &mat) -{ - for(auto *l : mListeners) - l->notifyMaterialRender(pass_id, mat); -} -//----------------------------------------------------------------------- -void CompositorInstance::_fireNotifyResourcesCreated(bool forResizeOnly) -{ - for(auto *l : mListeners) - l->notifyResourcesCreated(forResizeOnly); -} -//----------------------------------------------------------------------- -void CompositorInstance::_fireNotifyResourcesReleased(bool forResizeOnly) -{ - for(auto *l : mListeners) - l->notifyResourcesReleased(forResizeOnly); -} -//----------------------------------------------------------------------- -void CompositorInstance::notifyCameraChanged(Camera* camera) -{ - // update local texture's viewports. - LocalTextureMap::iterator localTexIter = mLocalTextures.begin(); - LocalTextureMap::iterator localTexIterEnd = mLocalTextures.end(); - while (localTexIter != localTexIterEnd) - { - RenderTexture* target = localTexIter->second->getBuffer()->getRenderTarget(); - // skip target that has no viewport (this means texture is under MRT) - if (target->getNumViewports() == 1) - { - target->getViewport(0)->setCamera(camera); - } - ++localTexIter; - } - - // update MRT's viewports. - LocalMRTMap::iterator localMRTIter = mLocalMRTs.begin(); - LocalMRTMap::iterator localMRTIterEnd = mLocalMRTs.end(); - while (localMRTIter != localMRTIterEnd) - { - MultiRenderTarget* target = localMRTIter->second; - if(target->getNumViewports()) - target->getViewport(0)->setCamera(camera); - ++localMRTIter; - } -} -//----------------------------------------------------------------------- -CompositorInstance::RenderSystemOperation::~RenderSystemOperation() -{ -} -//----------------------------------------------------------------------- -CompositorInstance::Listener::~Listener() -{ -} -void CompositorInstance::Listener::notifyMaterialSetup(uint32 pass_id, MaterialPtr &mat) -{ -} -void CompositorInstance::Listener::notifyMaterialRender(uint32 pass_id, MaterialPtr &mat) -{ -} -void CompositorInstance::Listener::notifyResourcesCreated(bool forResizeOnly) -{ -} -void CompositorInstance::Listener::notifyResourcesReleased(bool forResizeOnly) -{ -} - -} diff --git a/OgreMain/src/OgreCompositorManager.cpp b/OgreMain/src/OgreCompositorManager.cpp deleted file mode 100644 index 52b6b0069f2..00000000000 --- a/OgreMain/src/OgreCompositorManager.cpp +++ /dev/null @@ -1,524 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreCompositor.h" -#include "OgreCompositorManager.h" -#include "OgreCompositorChain.h" -#include "OgreCompositionPass.h" -#include "OgreCompositionTargetPass.h" -#include "OgreCompositionTechnique.h" -#include "OgreRectangle2D.h" -#include "OgreRenderTarget.h" - -namespace Ogre { - -template<> CompositorManager* Singleton::msSingleton = 0; -CompositorManager* CompositorManager::getSingletonPtr(void) -{ - return msSingleton; -} -CompositorManager& CompositorManager::getSingleton(void) -{ - assert( msSingleton ); return ( *msSingleton ); -}//----------------------------------------------------------------------- -CompositorManager::CompositorManager(): - mRectangle(0) -{ - // Loading order (just after materials) - mLoadOrder = 110.0f; - - // Resource type - mResourceType = "Compositor"; - - // Register with resource group manager - ResourceGroupManager::getSingleton()._registerResourceManager(mResourceType, this); - -} -//----------------------------------------------------------------------- -CompositorManager::~CompositorManager() -{ - freeChains(); - freePooledTextures(false); - OGRE_DELETE mRectangle; - - // Resources cleared by superclass - // Unregister with resource group manager - ResourceGroupManager::getSingleton()._unregisterResourceManager(mResourceType); - ResourceGroupManager::getSingleton()._unregisterScriptLoader(this); -} -//----------------------------------------------------------------------- -Resource* CompositorManager::createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* params) -{ - return OGRE_NEW Compositor(this, name, handle, group, isManual, loader); -} -//----------------------------------------------------------------------- -CompositorPtr CompositorManager::create (const String& name, const String& group, - bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams) -{ - return static_pointer_cast(createResource(name,group,isManual,loader,createParams)); -} -//----------------------------------------------------------------------- -CompositorPtr CompositorManager::getByName(const String& name, const String& groupName) const -{ - return static_pointer_cast(getResourceByName(name, groupName)); -} -//----------------------------------------------------------------------- -CompositorChain *CompositorManager::getCompositorChain(Viewport *vp) -{ - Chains::iterator i=mChains.find(vp); - if(i != mChains.end()) - { - return i->second; - } - else - { - CompositorChain *chain = OGRE_NEW CompositorChain(vp); - mChains[vp] = chain; - return chain; - } -} -//----------------------------------------------------------------------- -bool CompositorManager::hasCompositorChain(const Viewport *vp) const -{ - return mChains.find(vp) != mChains.end(); -} -//----------------------------------------------------------------------- -void CompositorManager::removeCompositorChain(const Viewport *vp) -{ - Chains::iterator i = mChains.find(vp); - if (i != mChains.end()) - { - OGRE_DELETE i->second; - mChains.erase(i); - } -} -//----------------------------------------------------------------------- -void CompositorManager::removeAll(void) -{ - freeChains(); - ResourceManager::removeAll(); -} -//----------------------------------------------------------------------- -void CompositorManager::freeChains() -{ - for(auto& c : mChains) - { - OGRE_DELETE c.second; - } - mChains.clear(); -} -//----------------------------------------------------------------------- -Renderable *CompositorManager::_getTexturedRectangle2D() -{ - if(!mRectangle) - { - /// 2D rectangle, to use for render_quad passes - mRectangle = OGRE_NEW Rectangle2D(true, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE); - } - RenderSystem* rs = Root::getSingleton().getRenderSystem(); - Viewport* vp = rs->_getViewport(); - Real hOffset = rs->getHorizontalTexelOffset() / (0.5f * vp->getActualWidth()); - Real vOffset = rs->getVerticalTexelOffset() / (0.5f * vp->getActualHeight()); - mRectangle->setCorners(-1 + hOffset, 1 - vOffset, 1 + hOffset, -1 - vOffset); - return mRectangle; -} -//----------------------------------------------------------------------- -CompositorInstance *CompositorManager::addCompositor(Viewport *vp, const String &compositor, int addPosition) -{ - CompositorPtr comp = getByName(compositor); - if(!comp) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Compositor '"+compositor+"' not found"); - CompositorChain *chain = getCompositorChain(vp); - return chain->addCompositor(comp, addPosition==-1 ? CompositorChain::LAST : (size_t)addPosition); -} -//----------------------------------------------------------------------- -void CompositorManager::removeCompositor(Viewport *vp, const String &compositor) -{ - CompositorChain *chain = getCompositorChain(vp); - size_t pos = chain->getCompositorPosition(compositor); - - if(pos == CompositorChain::NPOS) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Compositor '"+compositor+"' not in chain"); - - chain->removeCompositor(pos); -} -//----------------------------------------------------------------------- -void CompositorManager::setCompositorEnabled(Viewport *vp, const String &compositor, bool value) -{ - CompositorChain *chain = getCompositorChain(vp); - size_t pos = chain->getCompositorPosition(compositor); - - if(pos == CompositorChain::NPOS) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Compositor '"+compositor+"' not in chain"); - - chain->setCompositorEnabled(pos, value); -} -//--------------------------------------------------------------------- -void CompositorManager::_reconstructAllCompositorResources() -{ - // In order to deal with shared resources, we have to disable *all* compositors - // first, that way shared resources will get freed - typedef std::vector InstVec; - InstVec instancesToReenable; - for (auto & it : mChains) - { - CompositorChain* chain = it.second; - for (CompositorInstance* inst : chain->getCompositorInstances()) - { - if (inst->getEnabled()) - { - inst->setEnabled(false); - instancesToReenable.push_back(inst); - } - } - } - - //UVs are lost, and will never be reconstructed unless we do them again, now - if( mRectangle ) - mRectangle->setDefaultUVs(); - - for (auto inst : instancesToReenable) - { - inst->setEnabled(true); - } -} -//--------------------------------------------------------------------- -TexturePtr CompositorManager::getPooledTexture(const String& name, - const String& localName, - uint32 w, uint32 h, PixelFormat f, uint aa, const String& aaHint, bool srgb, - CompositorManager::UniqueTextureSet& texturesAssigned, - CompositorInstance* inst, CompositionTechnique::TextureScope scope, TextureType type) -{ - OgreAssert(scope != CompositionTechnique::TS_GLOBAL, "Global scope texture can not be pooled"); - - TextureDef def(w, h, type, f, aa, aaHint, srgb); - - if (scope == CompositionTechnique::TS_CHAIN) - { - StringPair pair = std::make_pair(inst->getCompositor()->getName(), localName); - TextureDefMap& defMap = mChainTexturesByDef[pair]; - TextureDefMap::iterator it = defMap.find(def); - if (it != defMap.end()) - { - return it->second; - } - // ok, we need to create a new one - TexturePtr newTex = TextureManager::getSingleton().createManual( - name, - ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D, - (uint)w, (uint)h, 0, f, TU_RENDERTARGET, 0, - srgb, aa, aaHint); - defMap.emplace(def, newTex); - return newTex; - } - - TexturesByDef::iterator i = mTexturesByDef.emplace(def, TextureList()).first; - - CompositorInstance* previous = inst->getChain()->getPreviousInstance(inst); - CompositorInstance* next = inst->getChain()->getNextInstance(inst); - - TexturePtr ret; - TextureList& texList = i->second; - // iterate over the existing textures and check if we can re-use - for (auto & tex : texList) - { - // check not already used - if (texturesAssigned.find(tex.get()) == texturesAssigned.end()) - { - bool allowReuse = true; - // ok, we didn't use this one already - // however, there is an edge case where if we re-use a texture - // which has an 'input previous' pass, and it is chained from another - // compositor, we can end up trying to use the same texture for both - // so, never allow a texture with an input previous pass to be - // shared with its immediate predecessor in the chain - if (isInputPreviousTarget(inst, localName)) - { - // Check whether this is also an input to the output target of previous - // can't use CompositorInstance::mPreviousInstance, only set up - // during compile - if (previous && isInputToOutputTarget(previous, tex)) - allowReuse = false; - } - // now check the other way around since we don't know what order they're bound in - if (isInputToOutputTarget(inst, localName)) - { - - if (next && isInputPreviousTarget(next, tex)) - allowReuse = false; - } - - if (allowReuse) - { - ret = tex; - break; - } - - } - } - - if (!ret) - { - // ok, we need to create a new one - ret = TextureManager::getSingleton().createManual( - name, - ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D, - w, h, 0, f, TU_RENDERTARGET, 0, - srgb, aa, aaHint); - - texList.push_back(ret); - - } - - // record that we used this one in the requester's list - texturesAssigned.insert(ret.get()); - - - return ret; -} -//--------------------------------------------------------------------- -bool CompositorManager::isInputPreviousTarget(CompositorInstance* inst, const Ogre::String& localName) -{ - const CompositionTechnique::TargetPasses& passes = inst->getTechnique()->getTargetPasses(); - for (auto *tp : passes) - { - if (tp->getInputMode() == CompositionTargetPass::IM_PREVIOUS && - tp->getOutputName() == localName) - { - return true; - } - - } - - return false; - -} -//--------------------------------------------------------------------- -bool CompositorManager::isInputPreviousTarget(CompositorInstance* inst, const TexturePtr& tex) -{ - const CompositionTechnique::TargetPasses& passes = inst->getTechnique()->getTargetPasses(); - for (auto *tp : passes) - { - if (tp->getInputMode() == CompositionTargetPass::IM_PREVIOUS) - { - // Don't have to worry about an MRT, because no MRT can be input previous - TexturePtr t = inst->getTextureInstance(tp->getOutputName(), 0); - if (t && t.get() == tex.get()) - return true; - } - - } - - return false; - -} -//--------------------------------------------------------------------- -bool CompositorManager::isInputToOutputTarget(CompositorInstance* inst, const Ogre::String& localName) -{ - CompositionTargetPass* tp = inst->getTechnique()->getOutputTargetPass(); - for (auto *p : tp->getPasses()) - { - for (size_t i = 0; i < p->getNumInputs(); ++i) - { - if (p->getInput(i).name == localName) - return true; - } - } - - return false; - -} -//---------------------------------------------------------------------() -bool CompositorManager::isInputToOutputTarget(CompositorInstance* inst, const TexturePtr& tex) -{ - CompositionTargetPass* tp = inst->getTechnique()->getOutputTargetPass(); - for (auto *p : tp->getPasses()) - { - for (size_t i = 0; i < p->getNumInputs(); ++i) - { - TexturePtr t = inst->getTextureInstance(p->getInput(i).name, 0); - if (t && t.get() == tex.get()) - return true; - } - } - - return false; - -} -//--------------------------------------------------------------------- -void CompositorManager::freePooledTextures(bool onlyIfUnreferenced) -{ - if (onlyIfUnreferenced) - { - for (auto & i : mTexturesByDef) - { - TextureList& texList = i.second; - for (auto j = texList.begin(); j != texList.end();) - { - // if the resource system, plus this class, are the only ones to have a reference.. - // NOTE: any material references will stop this texture getting freed (e.g. compositor demo) - // until this routine is called again after the material no longer references the texture - if (j->use_count() == ResourceGroupManager::RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS + 1) - { - TextureManager::getSingleton().remove((*j)->getHandle()); - j = texList.erase(j); - } - else - ++j; - } - } - for (auto & i : mChainTexturesByDef) - { - TextureDefMap& texMap = i.second; - for (TextureDefMap::iterator j = texMap.begin(); j != texMap.end();) - { - const TexturePtr& tex = j->second; - if (tex.use_count() == ResourceGroupManager::RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS + 1) - { - TextureManager::getSingleton().remove(tex->getHandle()); - texMap.erase(j++); - } - else - ++j; - } - } - } - else - { - // destroy all - mTexturesByDef.clear(); - mChainTexturesByDef.clear(); - } - -} -//--------------------------------------------------------------------- -void CompositorManager::registerCompositorLogic(const String& name, CompositorLogic* logic) -{ - OgreAssert(!name.empty(), "Compositor logic name must not be empty"); - if (mCompositorLogics.find(name) != mCompositorLogics.end()) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "Compositor logic '" + name + "' already exists.", - "CompositorManager::registerCompositorLogic"); - } - mCompositorLogics[name] = logic; -} -//--------------------------------------------------------------------- -void CompositorManager::unregisterCompositorLogic(const String& name) -{ - CompositorLogicMap::iterator itor = mCompositorLogics.find(name); - if( itor == mCompositorLogics.end() ) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Compositor logic '" + name + "' not registered.", - "CompositorManager::unregisterCompositorLogic"); - } - - mCompositorLogics.erase( itor ); -} -//--------------------------------------------------------------------- -CompositorLogic* CompositorManager::getCompositorLogic(const String& name) -{ - CompositorLogicMap::iterator it = mCompositorLogics.find(name); - if (it == mCompositorLogics.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Compositor logic '" + name + "' not registered.", - "CompositorManager::getCompositorLogic"); - } - return it->second; -} -//--------------------------------------------------------------------- -bool CompositorManager::hasCompositorLogic(const String& name) -{ - return mCompositorLogics.find(name) != mCompositorLogics.end(); -} -//--------------------------------------------------------------------- -void CompositorManager::registerCustomCompositionPass(const String& name, CustomCompositionPass* logic) -{ - OgreAssert(!name.empty(), "Compositor pass name must not be empty"); - if (mCustomCompositionPasses.find(name) != mCustomCompositionPasses.end()) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "Custom composition pass '" + name + "' already exists.", - "CompositorManager::registerCustomCompositionPass"); - } - mCustomCompositionPasses[name] = logic; -} -//--------------------------------------------------------------------- -void CompositorManager::unregisterCustomCompositionPass(const String& name) -{ - CustomCompositionPassMap::iterator itor = mCustomCompositionPasses.find(name); - if( itor == mCustomCompositionPasses.end() ) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Custom composition pass '" + name + "' not registered.", - "CompositorManager::unRegisterCustomCompositionPass"); - } - mCustomCompositionPasses.erase( itor ); -} -//--------------------------------------------------------------------- -bool CompositorManager::hasCustomCompositionPass(const String& name) -{ - return mCustomCompositionPasses.find(name) != mCustomCompositionPasses.end(); -} -//--------------------------------------------------------------------- -CustomCompositionPass* CompositorManager::getCustomCompositionPass(const String& name) -{ - CustomCompositionPassMap::iterator it = mCustomCompositionPasses.find(name); - if (it == mCustomCompositionPasses.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Custom composition pass '" + name + "' not registered.", - "CompositorManager::getCustomCompositionPass"); - } - return it->second; -} -//----------------------------------------------------------------------- -void CompositorManager::_relocateChain( Viewport* sourceVP, Viewport* destVP ) -{ - if (sourceVP != destVP) - { - CompositorChain *chain = getCompositorChain(sourceVP); - Ogre::RenderTarget *srcTarget = sourceVP->getTarget(); - Ogre::RenderTarget *dstTarget = destVP->getTarget(); - if (srcTarget != dstTarget) - { - srcTarget->removeListener(chain); - dstTarget->addListener(chain); - } - chain->_notifyViewport(destVP); - mChains.erase(sourceVP); - mChains[destVP] = chain; - } -} -//----------------------------------------------------------------------- -} diff --git a/OgreMain/src/OgreConfigFile.cpp b/OgreMain/src/OgreConfigFile.cpp deleted file mode 100644 index bb452538bf4..00000000000 --- a/OgreMain/src/OgreConfigFile.cpp +++ /dev/null @@ -1,198 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreConfigFile.h" -#include "OgreResourceGroupManager.h" - -#include - -namespace Ogre { - - //----------------------------------------------------------------------- - ConfigFile::ConfigFile() - { - } - //----------------------------------------------------------------------- - void ConfigFile::clear(void) - { - mSettings.clear(); - mSettingsPtr.clear(); - } - //----------------------------------------------------------------------- - void ConfigFile::load(const String& filename, const String& separators, bool trimWhitespace) - { - loadDirect(filename, separators, trimWhitespace); - } - //----------------------------------------------------------------------- - void ConfigFile::load(const String& filename, const String& resourceGroup, - const String& separators, bool trimWhitespace) - { - loadFromResourceSystem(filename, resourceGroup, separators, trimWhitespace); - } - //----------------------------------------------------------------------- - void ConfigFile::loadDirect(const String& filename, const String& separators, - bool trimWhitespace) - { - load(_openFileStream(filename, std::ios::in | std::ios::binary), separators, trimWhitespace); - } - //----------------------------------------------------------------------- - void ConfigFile::loadFromResourceSystem(const String& filename, - const String& resourceGroup, const String& separators, bool trimWhitespace) - { - DataStreamPtr stream = - ResourceGroupManager::getSingleton().openResource(filename, resourceGroup); - load(stream, separators, trimWhitespace); - } - //----------------------------------------------------------------------- - void ConfigFile::load(const DataStreamPtr& stream, const String& separators, - bool trimWhitespace) - { - /* Clear current settings map */ - clear(); - - String currentSection = BLANKSTRING; - SettingsMultiMap* currentSettings = &mSettings[currentSection]; - mSettingsPtr[currentSection] = currentSettings; - - - /* Process the file line for line */ - String line, optName, optVal; - while (!stream->eof()) - { - line = stream->getLine(); - /* Ignore comments & blanks */ - if (line.length() > 0 && line.at(0) != '#' && line.at(0) != '@') - { - if (line.at(0) == '[' && line.at(line.length()-1) == ']') - { - // Section - currentSection = line.substr(1, line.length() - 2); - currentSettings = &mSettings[currentSection]; - mSettingsPtr[currentSection] = currentSettings; - } - else - { - /* Find the first separator character and split the string there */ - Ogre::String::size_type separator_pos = line.find_first_of(separators, 0); - if (separator_pos != Ogre::String::npos) - { - optName = line.substr(0, separator_pos); - /* Find the first non-separator character following the name */ - Ogre::String::size_type nonseparator_pos = line.find_first_not_of(separators, separator_pos); - /* ... and extract the value */ - /* Make sure we don't crash on an empty setting (it might be a valid value) */ - optVal = (nonseparator_pos == Ogre::String::npos) ? "" : line.substr(nonseparator_pos); - if (trimWhitespace) - { - StringUtil::trim(optVal); - StringUtil::trim(optName); - } - currentSettings->emplace(optName, optVal); - } - } - } - } - } - //----------------------------------------------------------------------- - String ConfigFile::getSetting(const String& key, const String& section, const String& defaultValue) const - { - - SettingsBySection_::const_iterator seci = mSettings.find(section); - if (seci == mSettings.end()) - { - return defaultValue; - } - else - { - SettingsMultiMap::const_iterator i = seci->second.find(key); - if (i == seci->second.end()) - { - return defaultValue; - } - else - { - return i->second; - } - } - } - - //----------------------------------------------------------------------- - StringVector ConfigFile::getMultiSetting(const String& key, const String& section) const - { - StringVector ret; - - SettingsBySection_::const_iterator seci = mSettings.find(section); - if (seci != mSettings.end()) - { - SettingsMultiMap::const_iterator i; - - i = seci->second.find(key); - // Iterate over matches - while (i != seci->second.end() && i->first == key) - { - ret.push_back(i->second); - ++i; - } - } - return ret; - - - } - //----------------------------------------------------------------------- - ConfigFile::SettingsIterator ConfigFile::getSettingsIterator(const String& section) - { - SettingsBySection_::iterator seci = mSettings.find(section); - if (seci == mSettings.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Cannot find section " + section, - "ConfigFile::getSettingsIterator"); - } - - return SettingsIterator(seci->second.begin(), seci->second.end()); - } - //----------------------------------------------------------------------- - const ConfigFile::SettingsMultiMap& ConfigFile::getSettings(const String& section) const - { - SettingsBySection_::const_iterator seci = mSettings.find(section); - if (seci == mSettings.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Cannot find section " + section, - "ConfigFile::getSettings"); - } - - return seci->second; - } - //----------------------------------------------------------------------- - ConfigFile::SectionIterator ConfigFile::getSectionIterator(void) - { - return SectionIterator(mSettingsPtr.begin(), mSettingsPtr.end()); - } - -} diff --git a/OgreMain/src/OgreControllerManager.cpp b/OgreMain/src/OgreControllerManager.cpp deleted file mode 100644 index 66ad391e893..00000000000 --- a/OgreMain/src/OgreControllerManager.cpp +++ /dev/null @@ -1,243 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreControllerManager.h" - -#include "OgrePredefinedControllers.h" - -namespace Ogre { - //----------------------------------------------------------------------- - template<> ControllerManager* Singleton::msSingleton = 0; - ControllerManager* ControllerManager::getSingletonPtr(void) - { - return msSingleton; - } - ControllerManager& ControllerManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //----------------------------------------------------------------------- - ControllerManager::ControllerManager() - : mFrameTimeController(OGRE_NEW FrameTimeControllerValue()) - , mPassthroughFunction(OGRE_NEW PassthroughControllerFunction()) - , mLastFrameNumber(0) - { - - } - //----------------------------------------------------------------------- - ControllerManager::~ControllerManager() - { - clearControllers(); - } - //----------------------------------------------------------------------- - ControllerFloat* ControllerManager::createController( - const ControllerValueRealPtr& src, const ControllerValueRealPtr& dest, - const ControllerFunctionRealPtr& func) - { - ControllerFloat* c = OGRE_NEW ControllerFloat(src, dest, func); - - mControllers.push_back(c); - return c; - } - //----------------------------------------------------------------------- - ControllerFloat* ControllerManager::createFrameTimePassthroughController( - const ControllerValueRealPtr& dest) - { - return createController(getFrameTimeSource(), dest, getPassthroughControllerFunction()); - } - //----------------------------------------------------------------------- - void ControllerManager::updateAllControllers(void) - { - // Only update once per frame - unsigned long thisFrameNumber = Root::getSingleton().getNextFrameNumber(); - if (thisFrameNumber != mLastFrameNumber) - { - for (auto *ci : mControllers) - { - ci->update(); - } - mLastFrameNumber = thisFrameNumber; - } - } - //----------------------------------------------------------------------- - void ControllerManager::clearControllers(void) - { - for (auto *ci : mControllers) - { - OGRE_DELETE ci; - } - mControllers.clear(); - } - //----------------------------------------------------------------------- - const ControllerValueRealPtr& ControllerManager::getFrameTimeSource(void) const - { - return mFrameTimeController; - } - //----------------------------------------------------------------------- - const ControllerFunctionRealPtr& ControllerManager::getPassthroughControllerFunction(void) const - { - return mPassthroughFunction; - } - //----------------------------------------------------------------------- - ControllerFloat* ControllerManager::createTextureAnimator(TextureUnitState* layer, Real sequenceTime) - { - return createController(mFrameTimeController, TextureFrameControllerValue::create(layer), - AnimationControllerFunction::create(sequenceTime)); - } - //----------------------------------------------------------------------- - ControllerFloat* ControllerManager::createTextureUVScroller(TextureUnitState* layer, Real speed) - { - ControllerFloat* ret = 0; - - if (speed != 0) - { - // We do both scrolls with a single controller - // Create function: use -speed since we're altering texture coords so they have reverse effect - ret = createController(mFrameTimeController, TexCoordModifierControllerValue::create(layer, true, true), - ScaleControllerFunction::create(-speed, true)); - } - - return ret; - } - //----------------------------------------------------------------------- - ControllerFloat* ControllerManager::createTextureUScroller(TextureUnitState* layer, Real uSpeed) - { - ControllerFloat* ret = 0; - - if (uSpeed != 0) - { - // Create function: use -speed since we're altering texture coords so they have reverse effect - ret = createController(mFrameTimeController, TexCoordModifierControllerValue::create(layer, true), - ScaleControllerFunction::create(-uSpeed, true)); - } - - return ret; - } - //----------------------------------------------------------------------- - ControllerFloat* ControllerManager::createTextureVScroller(TextureUnitState* layer, Real vSpeed) - { - ControllerFloat* ret = 0; - - if (vSpeed != 0) - { - // Set up a second controller for v scroll - // Create function: use -speed since we're altering texture coords so they have reverse effect - ret = createController(mFrameTimeController, TexCoordModifierControllerValue::create(layer, false, true), - ScaleControllerFunction::create(-vSpeed, true)); - } - - return ret; - } - //----------------------------------------------------------------------- - ControllerFloat* ControllerManager::createTextureRotater(TextureUnitState* layer, Real speed) - { - // Target value is texture coord rotation - // Function is simple scale (seconds * speed) - // Use -speed since altering texture coords has the reverse visible effect - return createController(mFrameTimeController, - TexCoordModifierControllerValue::create(layer, false, false, false, false, true), - ScaleControllerFunction::create(-speed, true)); - } - //----------------------------------------------------------------------- - ControllerFloat* ControllerManager::createTextureWaveTransformer(TextureUnitState* layer, - TextureUnitState::TextureTransformType ttype, WaveformType waveType, Real base, Real frequency, Real phase, Real amplitude) - { - ControllerValueRealPtr val; - - switch (ttype) - { - case TextureUnitState::TT_TRANSLATE_U: - // Target value is a u scroll - val = TexCoordModifierControllerValue::create(layer, true); - break; - case TextureUnitState::TT_TRANSLATE_V: - // Target value is a v scroll - val = TexCoordModifierControllerValue::create(layer, false, true); - break; - case TextureUnitState::TT_SCALE_U: - // Target value is a u scale - val = TexCoordModifierControllerValue::create(layer, false, false, true); - break; - case TextureUnitState::TT_SCALE_V: - // Target value is a v scale - val = TexCoordModifierControllerValue::create(layer, false, false, false, true); - break; - case TextureUnitState::TT_ROTATE: - // Target value is texture coord rotation - val = TexCoordModifierControllerValue::create(layer, false, false, false, false, true); - break; - } - // Create new wave function for alterations - return createController(mFrameTimeController, val, - WaveformControllerFunction::create(waveType, base, frequency, phase, amplitude, true)); - } - //----------------------------------------------------------------------- - ControllerFloat* ControllerManager::createGpuProgramTimerParam( - GpuProgramParametersSharedPtr params, size_t paramIndex, Real timeFactor) - { - return createController(mFrameTimeController, FloatGpuParameterControllerValue::create(params, paramIndex), - ScaleControllerFunction::create(timeFactor, true)); - } - //----------------------------------------------------------------------- - void ControllerManager::destroyController(ControllerFloat* controller) - { - ControllerList::iterator i = std::find(mControllers.begin(), mControllers.end(), controller); - if (i != mControllers.end()) - { - std::swap(*i, mControllers.back()); - mControllers.pop_back(); - OGRE_DELETE controller; - } - } - //----------------------------------------------------------------------- - Real ControllerManager::getTimeFactor(void) const { - return static_cast(mFrameTimeController.get())->getTimeFactor(); - } - //----------------------------------------------------------------------- - void ControllerManager::setTimeFactor(Real tf) { - static_cast(mFrameTimeController.get())->setTimeFactor(tf); - } - //----------------------------------------------------------------------- - Real ControllerManager::getFrameDelay(void) const { - return static_cast(mFrameTimeController.get())->getFrameDelay(); - } - //----------------------------------------------------------------------- - void ControllerManager::setFrameDelay(Real fd) { - static_cast(mFrameTimeController.get())->setFrameDelay(fd); - } - //----------------------------------------------------------------------- - Real ControllerManager::getElapsedTime(void) const - { - return static_cast(mFrameTimeController.get())->getElapsedTime(); - } - //----------------------------------------------------------------------- - void ControllerManager::setElapsedTime(Real elapsedTime) - { - static_cast(mFrameTimeController.get())->setElapsedTime(elapsedTime); - } -} diff --git a/OgreMain/src/OgreConvexBody.cpp b/OgreMain/src/OgreConvexBody.cpp deleted file mode 100644 index 12b134adea0..00000000000 --- a/OgreMain/src/OgreConvexBody.cpp +++ /dev/null @@ -1,1203 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Copyright (c) 2006 Matthias Fink, netAllied GmbH - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreConvexBody.h" - -namespace Ogre -{ - - - //----------------------------------------------------------------------- - // Statics - //----------------------------------------------------------------------- - ConvexBody::PolygonList ConvexBody::msFreePolygons; - OGRE_STATIC_MUTEX_INSTANCE(ConvexBody::msFreePolygonsMutex); - //----------------------------------------------------------------------- - void ConvexBody::_initialisePool() - { - OGRE_LOCK_MUTEX(msFreePolygonsMutex); - - if (msFreePolygons.empty()) - { - const size_t initialSize = 30; - - // Initialise polygon pool with 30 polys - msFreePolygons.resize(initialSize); - for (size_t i = 0; i < initialSize; ++i) - { - msFreePolygons[i] = OGRE_NEW_T(Polygon, MEMCATEGORY_SCENE_CONTROL)(); - } - } - } - //----------------------------------------------------------------------- - void ConvexBody::_destroyPool() - { - OGRE_LOCK_MUTEX(msFreePolygonsMutex); - - for (auto *p : msFreePolygons) - { - OGRE_DELETE_T(p, Polygon, MEMCATEGORY_SCENE_CONTROL); - } - msFreePolygons.clear(); - } - //----------------------------------------------------------------------- - Polygon* ConvexBody::allocatePolygon() - { - OGRE_LOCK_MUTEX(msFreePolygonsMutex); - - if (msFreePolygons.empty()) - { - // if we ran out of polys to use, create a new one - // hopefully this one will return to the pool in due course - return OGRE_NEW_T(Polygon, MEMCATEGORY_SCENE_CONTROL)(); - } - else - { - Polygon* ret = msFreePolygons.back(); - ret->reset(); - - msFreePolygons.pop_back(); - - return ret; - - } - } - //----------------------------------------------------------------------- - void ConvexBody::freePolygon(Polygon* poly) - { - OGRE_LOCK_MUTEX(msFreePolygonsMutex); - msFreePolygons.push_back(poly); - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - ConvexBody::ConvexBody() - { - // Reserve space for 8 polys, normally 6 faces plus a couple of clips - mPolygons.reserve(8); - - } - //----------------------------------------------------------------------- - ConvexBody::~ConvexBody() - { - reset(); - } - //----------------------------------------------------------------------- - ConvexBody::ConvexBody( const ConvexBody& cpy ) - { - for ( size_t i = 0; i < cpy.getPolygonCount(); ++i ) - { - Polygon *p = allocatePolygon(); - *p = cpy.getPolygon( i ); - mPolygons.push_back( p ); - } - } - //----------------------------------------------------------------------- - void ConvexBody::define(const Frustum& frustum) - { - // ordering of the points: - // near (0-3), far (4-7); each (top-right, top-left, bottom-left, bottom-right) - // 5-----4 - // /| /| - // / | / | - // 1-----0 | - // | 6--|--7 - // | / | / - // |/ |/ - // 2-----3 - - const Vector3 *pts = frustum.getWorldSpaceCorners(); - - /// reset ConvexBody - reset(); - - /// update vertices: near, far, left, right, bottom, top; fill in ccw - Polygon *poly; - - // near - poly = allocatePolygon(); - poly->insertVertex( pts[0] ); - poly->insertVertex( pts[1] ); - poly->insertVertex( pts[2] ); - poly->insertVertex( pts[3] ); - mPolygons.push_back( poly ); - - // far - poly = allocatePolygon(); - poly->insertVertex( pts[5] ); - poly->insertVertex( pts[4] ); - poly->insertVertex( pts[7] ); - poly->insertVertex( pts[6] ); - mPolygons.push_back( poly ); - - // left - poly = allocatePolygon(); - poly->insertVertex( pts[5] ); - poly->insertVertex( pts[6] ); - poly->insertVertex( pts[2] ); - poly->insertVertex( pts[1] ); - mPolygons.push_back( poly ); - - // right - poly = allocatePolygon(); - poly->insertVertex( pts[4] ); - poly->insertVertex( pts[0] ); - poly->insertVertex( pts[3] ); - poly->insertVertex( pts[7] ); - mPolygons.push_back( poly ); - - // bottom - poly = allocatePolygon(); - poly->insertVertex( pts[6] ); - poly->insertVertex( pts[7] ); - poly->insertVertex( pts[3] ); - poly->insertVertex( pts[2] ); - mPolygons.push_back( poly ); - - // top - poly = allocatePolygon(); - poly->insertVertex( pts[4] ); - poly->insertVertex( pts[5] ); - poly->insertVertex( pts[1] ); - poly->insertVertex( pts[0] ); - mPolygons.push_back( poly ); - } - //----------------------------------------------------------------------- - void ConvexBody::define(const AxisAlignedBox& aab) - { - // ordering of the AAB points: - // 1-----2 - // /| /| - // / | / | - // 5-----4 | - // | 0--|--3 - // | / | / - // |/ |/ - // 6-----7 - - const Vector3& min = aab.getMinimum(); - const Vector3& max = aab.getMaximum(); - - Vector3 currentVertex = min; - - Polygon *poly; - - // reset body - reset(); - - // far - poly = allocatePolygon(); - poly->insertVertex( currentVertex ); // 0 - currentVertex.y = max.y; - poly->insertVertex( currentVertex ); // 1 - currentVertex.x = max.x; - poly->insertVertex( currentVertex ); // 2 - currentVertex.y = min.y; - poly->insertVertex( currentVertex ); // 3 - insertPolygon( poly ); - - // right - poly = allocatePolygon(); - poly->insertVertex( currentVertex ); // 3 - currentVertex.y = max.y; - poly->insertVertex( currentVertex ); // 2 - currentVertex.z = max.z; - poly->insertVertex( currentVertex ); // 4 - currentVertex.y = min.y; - poly->insertVertex( currentVertex ); // 7 - insertPolygon( poly ); - - // near - poly = allocatePolygon(); - poly->insertVertex( currentVertex ); // 7 - currentVertex.y = max.y; - poly->insertVertex( currentVertex ); // 4 - currentVertex.x = min.x; - poly->insertVertex( currentVertex ); // 5 - currentVertex.y = min.y; - poly->insertVertex( currentVertex ); // 6 - insertPolygon( poly ); - - // left - poly = allocatePolygon(); - poly->insertVertex( currentVertex ); // 6 - currentVertex.y = max.y; - poly->insertVertex( currentVertex ); // 5 - currentVertex.z = min.z; - poly->insertVertex( currentVertex ); // 1 - currentVertex.y = min.y; - poly->insertVertex( currentVertex ); // 0 - insertPolygon( poly ); - - // bottom - poly = allocatePolygon(); - poly->insertVertex( currentVertex ); // 0 - currentVertex.x = max.x; - poly->insertVertex( currentVertex ); // 3 - currentVertex.z = max.z; - poly->insertVertex( currentVertex ); // 7 - currentVertex.x = min.x; - poly->insertVertex( currentVertex ); // 6 - insertPolygon( poly ); - - // top - poly = allocatePolygon(); - currentVertex = max; - poly->insertVertex( currentVertex ); // 4 - currentVertex.z = min.z; - poly->insertVertex( currentVertex ); // 2 - currentVertex.x = min.x; - poly->insertVertex( currentVertex ); // 1 - currentVertex.z = max.z; - poly->insertVertex( currentVertex ); // 5 - insertPolygon( poly ); - - } - //----------------------------------------------------------------------- - void ConvexBody::clip(const AxisAlignedBox& aab) - { - // only process finite boxes - if (!aab.isFinite()) - return; - // ordering of the AAB points: - // 1-----2 - // /| /| - // / | / | - // 5-----4 | - // | 0--|--3 - // | / | / - // |/ |/ - // 6-----7 - - const Vector3& min = aab.getMinimum(); - const Vector3& max = aab.getMaximum(); - - // clip object for each plane of the AAB - Plane p; - - - // front - p.redefine(Vector3::UNIT_Z, max); - clip(p); - - // back - p.redefine(Vector3::NEGATIVE_UNIT_Z, min); - clip(p); - - // left - p.redefine(Vector3::NEGATIVE_UNIT_X, min); - clip(p); - - // right - p.redefine(Vector3::UNIT_X, max); - clip(p); - - // bottom - p.redefine(Vector3::NEGATIVE_UNIT_Y, min); - clip(p); - - // top - p.redefine(Vector3::UNIT_Y, max); - clip(p); - - } - //----------------------------------------------------------------------- - void ConvexBody::clip(const Frustum& fr) - { - // clip the body with each plane - for ( unsigned short i = 0; i < 6; ++i ) - { - // clip, but keep positive space this time since frustum planes are - // the opposite to other cases (facing inwards rather than outwards) - clip(fr.getFrustumPlane(i), false); - } - } - //----------------------------------------------------------------------- - void ConvexBody::clip(const ConvexBody& body) - { - if ( this == &body ) - return; - - // for each polygon; clip 'this' with each plane of 'body' - // front vertex representation is ccw - - Plane pl; - - for ( size_t iPoly = 0; iPoly < body.getPolygonCount(); ++iPoly ) - { - const Polygon& p = body.getPolygon( iPoly ); - - OgreAssertDbg( p.getVertexCount() >= 3, "A valid polygon must contain at least three vertices." ); - - // set up plane with first three vertices of the polygon (a polygon is always planar) - pl.redefine( p.getVertex( 0 ), p.getVertex( 1 ), p.getVertex( 2 ) ); - - clip(pl); - } - } - //----------------------------------------------------------------------- - void ConvexBody::extend(const Vector3& pt) - { - // Erase all polygons facing towards the point. For all edges that - // are not removed twice (once in AB and once BA direction) build a - // convex polygon (triangle) with the point. - Polygon::EdgeMap edgeMap; - - for ( size_t i = 0; i < getPolygonCount(); ++i ) - { - const Vector3& normal = getNormal( i ); - // direction of the point in regard to the polygon - // the polygon is planar so we can take an arbitrary vertex - Vector3 ptDir = pt - getVertex( i, 0 ); - ptDir.normalise(); - - // remove polygon if dot product is greater or equals null. - if ( normal.dotProduct( ptDir ) >= 0 ) - { - // store edges (copy them because if the polygon is deleted - // its vertices are also deleted) - storeEdgesOfPolygon( i, &edgeMap ); - - // remove polygon - deletePolygon( i ); - - // decrement iterator because of deleted polygon - --i; - } - } - - // point is already a part of the hull (point lies inside) - if ( edgeMap.empty() ) - return; - - // remove the edges that are twice in the list (once from each side: AB,BA) - - Polygon::EdgeMap::iterator it; - // iterate from first to the element before the last one - for (Polygon::EdgeMap::iterator itStart = edgeMap.begin(); - itStart != edgeMap.end(); ) - { - // compare with iterator + 1 to end - // don't need to skip last entry in itStart since omitted in inner loop - it = itStart; - ++it; - - bool erased = false; - // iterate from itStart+1 to the element before the last one - for ( ; it != edgeMap.end(); ++it ) - { - if (itStart->first.positionEquals(it->second) && - itStart->second.positionEquals(it->first)) - { - edgeMap.erase(it); - // increment itStart before deletion (iterator invalidation) - Polygon::EdgeMap::iterator delistart = itStart++; - edgeMap.erase(delistart); - erased = true; - - break; // found and erased - } - } - // increment itStart if we didn't do it when erasing - if (!erased) - ++itStart; - - } - - // use the remaining edges to build triangles with the point - // the vertices of the edges are in ccw order (edgePtA-edgePtB-point - // to form a ccw polygon) - while ( !edgeMap.empty() ) - { - Polygon::EdgeMap::iterator mapIt = edgeMap.begin(); - - // build polygon it.first, it.second, point - Polygon *p = allocatePolygon(); - - p->insertVertex(mapIt->first); - p->insertVertex(mapIt->second); - - p->insertVertex( pt ); - // attach polygon to body - insertPolygon( p ); - - // erase the vertices from the list - // pointers are now held by the polygon - edgeMap.erase( mapIt ); - } - } - //----------------------------------------------------------------------- - void ConvexBody::reset( void ) - { - for (auto *p : mPolygons) - { - freePolygon(p); - } - mPolygons.clear(); - } - //----------------------------------------------------------------------- - size_t ConvexBody::getPolygonCount( void ) const - { - return mPolygons.size(); - } - //----------------------------------------------------------------------- - size_t ConvexBody::getVertexCount( size_t poly ) const - { - OgreAssertDbg(poly < getPolygonCount(), "Search position out of range" ); - - return mPolygons[ poly ]->getVertexCount(); - } - //----------------------------------------------------------------------- - bool ConvexBody::hasClosedHull( void ) const - { - // if this map is returned empty, the body is closed - Polygon::EdgeMap edgeMap = getSingleEdges(); - - return edgeMap.empty(); - } - //----------------------------------------------------------------------- - void ConvexBody::mergePolygons( void ) - { - // Merge all polygons that lay in the same plane as one big polygon. - // A convex body does not have two separate regions (separated by polygons - // with different normals) where the same normal occurs, so we can simply - // search all similar normals of a polygon. Two different options are - // possible when the normals fit: - // - the two polygons are neighbors - // - the two polygons aren't neighbors (but a third, fourth,.. polygon lays - // in between) - - // Signals if the body holds polygons which aren't neighbors but have the same - // normal. That means another step has to be processed. - bool bDirty = false; - - for ( size_t iPolyA = 0; iPolyA < getPolygonCount(); ++iPolyA ) - { - - for ( size_t iPolyB = iPolyA+1; iPolyB < getPolygonCount(); ++iPolyB ) - { - const Vector3& n1 = getNormal( iPolyA ); - const Vector3& n2 = getNormal( iPolyB ); - - // if the normals point into the same direction - if ( n1.directionEquals( n2, Radian( Degree( 0.00001 ) ) ) ) - { - // indicates if a neighbor has been found and joined - bool bFound = false; - - // search the two fitting vertices (if there are any) for the common edge - const size_t numVerticesA = getVertexCount( iPolyA ); - for ( size_t iVertexA = 0; iVertexA < numVerticesA; ++iVertexA ) - { - const size_t numVerticesB = getVertexCount( iPolyB ); - for ( size_t iVertexB = 0; iVertexB < numVerticesB; ++iVertexB ) - { - const Vector3& aCurrent = getVertex( iPolyA, iVertexA ); - const Vector3& aNext = getVertex( iPolyA, (iVertexA + 1) % getVertexCount( iPolyA ) ); - const Vector3& bCurrent = getVertex( iPolyB, iVertexB ); - const Vector3& bNext = getVertex( iPolyB, (iVertexB + 1) % getVertexCount( iPolyB ) ); - - // if the edge is the same the current vertex of A has to be equal to the next of B and the other - // way round - if ( aCurrent.positionEquals(bNext) && - bCurrent.positionEquals(aNext)) - { - // polygons are neighbors, assemble new one - Polygon *pNew = allocatePolygon(); - - // insert all vertices of A up to the join (including the common vertex, ignoring - // whether the first vertex of A may be a shared vertex) - for ( size_t i = 0; i <= iVertexA; ++i ) - { - pNew->insertVertex( getVertex( iPolyA, i%numVerticesA ) ); - } - - // insert all vertices of B _after_ the join to the end - for ( size_t i = iVertexB + 2; i < numVerticesB; ++i ) - { - pNew->insertVertex( getVertex( iPolyB, i ) ); - } - - // insert all vertices of B from the beginning up to the join (including the common vertex - // and excluding the first vertex if the first is part of the shared edge) - for ( size_t i = 0; i <= iVertexB; ++i ) - { - pNew->insertVertex( getVertex( iPolyB, i%numVerticesB ) ); - } - - // insert all vertices of A _after_ the join to the end - for ( size_t i = iVertexA + 2; i < numVerticesA; ++i ) - { - pNew->insertVertex( getVertex( iPolyA, i ) ); - } - - // in case there are double vertices (in special cases), remove them - for ( size_t i = 0; i < pNew->getVertexCount(); ++i ) - { - const Vector3& a = pNew->getVertex( i ); - const Vector3& b = pNew->getVertex( (i + 1) % pNew->getVertexCount() ); - - // if the two vertices are the same... - if (a.positionEquals(b)) - { - // remove a - pNew->deleteVertex( i ); - - // decrement counter - --i; - } - } - - // delete the two old ones - OgreAssertDbg( iPolyA != iPolyB, "PolyA and polyB are the same!" ); - - // polyB is always higher than polyA, so delete polyB first - deletePolygon( iPolyB ); - deletePolygon( iPolyA ); - - // continue with next (current is deleted, so don't jump to the next after the next) - --iPolyA; - --iPolyB; - - // insert new polygon - insertPolygon( pNew ); - - bFound = true; - break; - } - } - - if ( bFound ) - { - break; - } - } - - if ( bFound == false ) - { - // there are two polygons available with the same normal direction, but they - // could not be merged into one single because of no shared edge - bDirty = true; - break; - } - } - } - } - - // recursion to merge the previous non-neighbors - if ( bDirty ) - { - mergePolygons(); - } - } - //----------------------------------------------------------------------- - const Vector3& ConvexBody::getNormal( size_t poly ) - { - OgreAssertDbg( poly < getPolygonCount(), "Search position out of range" ); - - return mPolygons[ poly ]->getNormal(); - } - //----------------------------------------------------------------------- - AxisAlignedBox ConvexBody::getAABB( void ) const - { - AxisAlignedBox aab; - - for ( size_t i = 0; i < getPolygonCount(); ++i ) - { - for ( size_t j = 0; j < getVertexCount( i ); ++j ) - { - aab.merge( getVertex( i, j ) ); - } - } - - return aab; - } - //----------------------------------------------------------------------- - bool ConvexBody::operator == ( const ConvexBody& rhs ) const - { - if ( getPolygonCount() != rhs.getPolygonCount() ) - return false; - - // Compare the polygons. They may not be in correct order. - // A correct convex body does not have identical polygons in its body. - bool *bChecked = OGRE_ALLOC_T(bool, getPolygonCount(), MEMCATEGORY_SCENE_CONTROL); - for ( size_t i=0; iinsertVertex(vdata, vertex); - } - //----------------------------------------------------------------------- - void ConvexBody::insertVertex(size_t poly, const Vector3& vdata) - { - OgreAssertDbg(poly < getPolygonCount(), "Search position (polygon) out of range" ); - - mPolygons[poly]->insertVertex(vdata); - } - //----------------------------------------------------------------------- - void ConvexBody::deletePolygon(size_t poly) - { - OgreAssertDbg(poly < getPolygonCount(), "Search position out of range" ); - - PolygonList::iterator it = mPolygons.begin(); - std::advance(it, poly); - - freePolygon(*it); - mPolygons.erase(it); - } - //----------------------------------------------------------------------- - Polygon* ConvexBody::unlinkPolygon(size_t poly) - { - OgreAssertDbg( poly < getPolygonCount(), "Search position out of range" ); - - PolygonList::iterator it = mPolygons.begin(); - std::advance(it, poly); - - // safe address - Polygon *pRet = *it; - - // delete entry - mPolygons.erase(it); - - // return polygon pointer - - return pRet; - } - //----------------------------------------------------------------------- - void ConvexBody::moveDataFromBody(ConvexBody& body) - { - body.mPolygons.swap(this->mPolygons); - } - //----------------------------------------------------------------------- - void ConvexBody::deleteVertex(size_t poly, size_t vertex) - { - OgreAssertDbg(poly < getPolygonCount(), "Search position out of range" ); - - mPolygons[poly]->deleteVertex(vertex); - } - //----------------------------------------------------------------------- - const Polygon& ConvexBody::getPolygon(size_t poly) const - { - OgreAssertDbg(poly < getPolygonCount(), "Search position out of range"); - - return *mPolygons[poly]; - } - //----------------------------------------------------------------------- - void ConvexBody::setPolygon(Polygon* pdata, size_t poly) - { - OgreAssertDbg(poly < getPolygonCount(), "Search position out of range" ); - OgreAssertDbg(pdata != NULL, "Polygon is NULL" ); - - if (pdata != mPolygons[poly]) - { - // delete old polygon - freePolygon(mPolygons[ poly ]); - - // set new polygon - mPolygons[poly] = pdata; - } - } - //----------------------------------------------------------------------- - const Vector3& ConvexBody::getVertex(size_t poly, size_t vertex) const - { - OgreAssertDbg( poly < getPolygonCount(), "Search position out of range" ); - - return mPolygons[poly]->getVertex(vertex); - } - //----------------------------------------------------------------------- - void ConvexBody::setVertex(size_t poly, const Vector3& vdata, size_t vertex) - { - OgreAssertDbg(poly < getPolygonCount(), "Search position out of range"); - - mPolygons[poly]->setVertex(vdata, vertex); - } - //----------------------------------------------------------------------- - void ConvexBody::storeEdgesOfPolygon(size_t poly, Polygon::EdgeMap *edgeMap ) const - { - OgreAssertDbg(poly <= getPolygonCount(), "Search position out of range" ); - OgreAssertDbg( edgeMap != NULL, "TEdgeMap ptr is NULL" ); - - mPolygons[poly]->storeEdges(edgeMap); - } - //----------------------------------------------------------------------- - Polygon::EdgeMap ConvexBody::getSingleEdges() const - { - Polygon::EdgeMap edgeMap; - - // put all edges of all polygons into a list every edge has to be - // walked in each direction once - for ( size_t i = 0; i < getPolygonCount(); ++i ) - { - const Polygon& p = getPolygon( i ); - - for ( size_t j = 0; j < p.getVertexCount(); ++j ) - { - const Vector3& a = p.getVertex( j ); - const Vector3& b = p.getVertex( ( j + 1 ) % p.getVertexCount() ); - - edgeMap.insert( Polygon::Edge( a, b ) ); - } - } - - // search corresponding parts - Polygon::EdgeMap::iterator it; - Polygon::EdgeMap::iterator itStart; - Polygon::EdgeMap::const_iterator itEnd; - while( !edgeMap.empty() ) - { - it = edgeMap.begin(); ++it; // start one element after itStart - itStart = edgeMap.begin(); // the element to be compared with the others - itEnd = edgeMap.end(); // beyond the last element - - bool bFound = false; - - for ( ; it != itEnd; ++it ) - { - if (itStart->first.positionEquals(it->second) && - itStart->second.positionEquals(it->first)) - { - // erase itStart and it - edgeMap.erase( it ); - edgeMap.erase( itStart ); - - bFound = true; - - break; // found - } - } - - if ( bFound == false ) - { - break; // not all edges could be matched - // body is not closed - } - } - - return edgeMap; - } - //----------------------------------------------------------------------- - void ConvexBody::allocateSpace( size_t numPolygons, size_t numVertices ) - { - reset(); - - // allocate numPolygons polygons with each numVertices vertices - for ( size_t iPoly = 0; iPoly < numPolygons; ++iPoly ) - { - Polygon *poly = allocatePolygon(); - - for ( size_t iVertex = 0; iVertex < numVertices; ++iVertex ) - { - poly->insertVertex( Vector3::ZERO ); - } - - mPolygons.push_back( poly ); - } - } - //----------------------------------------------------------------------- - void ConvexBody::clip( const Plane& pl, bool keepNegative ) - { - if ( getPolygonCount() == 0 ) - return; - - // current will be used as the reference body - ConvexBody current; - current.moveDataFromBody(*this); - - OgreAssert( this->getPolygonCount() == 0, "Body not empty!" ); - OgreAssert( current.getPolygonCount() != 0, "Body empty!" ); - - // holds all intersection edges for the different polygons - Polygon::EdgeMap intersectionEdges; - - // clip all polygons by the intersection plane - // add only valid or intersected polygons to *this - for ( size_t iPoly = 0; iPoly < current.getPolygonCount(); ++iPoly ) - { - - // fetch vertex count and ignore polygons with less than three vertices - // the polygon is not valid and won't be added - const size_t vertexCount = current.getVertexCount( iPoly ); - if ( vertexCount < 3 ) - continue; - - // current polygon - const Polygon& p = current.getPolygon( iPoly ); - - // the polygon to assemble - Polygon *pNew = allocatePolygon(); - - // the intersection polygon (indeed it's an edge or it's empty) - Polygon *pIntersect = allocatePolygon(); - - // check if polygons lie inside or outside (or on the plane) - // for each vertex check where it is situated in regard to the plane - // three possibilities appear: - Plane::Side clipSide = keepNegative ? Plane::POSITIVE_SIDE : Plane::NEGATIVE_SIDE; - // - side is clipSide: vertex will be clipped - // - side is !clipSide: vertex will be untouched - // - side is NOSIDE: vertex will be untouched - Plane::Side *side = OGRE_ALLOC_T(Plane::Side, vertexCount, MEMCATEGORY_SCENE_CONTROL); - for ( size_t iVertex = 0; iVertex < vertexCount; ++iVertex ) - { - side[ iVertex ] = pl.getSide( p.getVertex( iVertex ) ); - } - - // now we check the side combinations for the current and the next vertex - // four different combinations exist: - // - both points inside (or on the plane): keep the second (add it to the body) - // - both points outside: discard both (don't add them to the body) - // - first vertex is inside, second is outside: add the intersection point - // - first vertex is outside, second is inside: add the intersection point, then the second - for ( size_t iVertex = 0; iVertex < vertexCount; ++iVertex ) - { - // determine the next vertex - size_t iNextVertex = ( iVertex + 1 ) % vertexCount; - - const Vector3& vCurrent = p.getVertex( iVertex ); - const Vector3& vNext = p.getVertex( iNextVertex ); - - // case 1: both points inside (store next) - if ( side[ iVertex ] != clipSide && // NEGATIVE or NONE - side[ iNextVertex ] != clipSide ) // NEGATIVE or NONE - { - // keep the second - pNew->insertVertex( vNext ); - } - - // case 3: inside -> outside (store intersection) - else if ( side[ iVertex ] != clipSide && - side[ iNextVertex ] == clipSide ) - { - // Do an intersection with the plane. We use a ray with a start point and a direction. - // The ray is forced to hit the plane with any option available (eigher current or next - // is the starting point) - - // intersect from the outside vertex towards the inside one - Vector3 vDirection = vCurrent - vNext; - vDirection.normalise(); - Ray ray( vNext, vDirection ); - std::pair< bool, Real > intersect = ray.intersects( pl ); - - // store intersection - if ( intersect.first ) - { - // convert distance to vector - Vector3 vIntersect = ray.getPoint( intersect.second ); - - // store intersection - pNew->insertVertex( vIntersect ); - pIntersect->insertVertex( vIntersect ); - } - } - - // case 4: outside -> inside (store intersection, store next) - else if ( side[ iVertex ] == clipSide && - side[ iNextVertex ] != clipSide ) - { - // Do an intersection with the plane. We use a ray with a start point and a direction. - // The ray is forced to hit the plane with any option available (eigher current or next - // is the starting point) - - // intersect from the outside vertex towards the inside one - Vector3 vDirection = vNext - vCurrent; - vDirection.normalise(); - Ray ray( vCurrent, vDirection ); - std::pair< bool, Real > intersect = ray.intersects( pl ); - - // store intersection - if ( intersect.first ) - { - // convert distance to vector - Vector3 vIntersect = ray.getPoint( intersect.second ); - - // store intersection - pNew->insertVertex( vIntersect ); - pIntersect->insertVertex( vIntersect ); - } - - pNew->insertVertex( vNext ); - - } - // else: - // case 2: both outside (do nothing) - - } - - // insert the polygon only, if at least three vertices are present - if ( pNew->getVertexCount() >= 3 ) - { - // in case there are double vertices, remove them - pNew->removeDuplicates(); - - // in case there are still at least three vertices, insert the polygon - if ( pNew->getVertexCount() >= 3 ) - { - this->insertPolygon( pNew ); - } - else - { - // delete pNew because it's empty or invalid - freePolygon(pNew); - pNew = 0; - } - } - else - { - // delete pNew because it's empty or invalid - freePolygon(pNew); - pNew = 0; - } - - // insert intersection polygon only, if there are two vertices present - if ( pIntersect->getVertexCount() == 2 ) - { - intersectionEdges.insert( Polygon::Edge( pIntersect->getVertex( 0 ), - pIntersect->getVertex( 1 ) ) ); - } - - // delete intersection polygon - // vertices were copied (if there were any) - freePolygon(pIntersect); - pIntersect = 0; - - // delete side info - OGRE_FREE(side, MEMCATEGORY_SCENE_CONTROL); - side = 0; - } - - // if the polygon was partially clipped, close it - // at least three edges are needed for a polygon - if ( intersectionEdges.size() >= 3 ) - { - Polygon *pClosing = allocatePolygon(); - - // Analyze the intersection list and insert the intersection points in ccw order - // Each point is twice in the list because of the fact that we have a convex body - // with convex polygons. All we have to do is order the edges (an even-odd pair) - // in a ccw order. The plane normal shows us the direction. - Polygon::EdgeMap::iterator it = intersectionEdges.begin(); - - // check the cross product of the first two edges - Vector3 vFirst = it->first; - Vector3 vSecond = it->second; - - // remove inserted edge - intersectionEdges.erase( it ); - - Vector3 vNext; - - // find mating edge - if (findAndEraseEdgePair(vSecond, intersectionEdges, vNext)) - { - // detect the orientation - // the polygon must have the same normal direction as the plane and then n - Vector3 vCross = ( vFirst - vSecond ).crossProduct( vNext - vSecond ); - bool frontside = ( pl.normal ).directionEquals( vCross, Degree( 1 ) ); - - // first inserted vertex - Vector3 firstVertex; - // currently inserted vertex - Vector3 currentVertex; - // direction equals -> front side (walk ccw) - if ( frontside ) - { - // start with next as first vertex, then second, then first and continue with first to walk ccw - pClosing->insertVertex( vNext ); - pClosing->insertVertex( vSecond ); - pClosing->insertVertex( vFirst ); - firstVertex = vNext; - currentVertex = vFirst; - - #ifdef _DEBUG_INTERSECTION_LIST - std::cout << "Plane: n=" << pl.normal << ", d=" << pl.d << std::endl; - std::cout << "First inserted vertex: " << *next << std::endl; - std::cout << "Second inserted vertex: " << *vSecond << std::endl; - std::cout << "Third inserted vertex: " << *vFirst << std::endl; - #endif - } - // direction does not equal -> back side (walk cw) - else - { - // start with first as first vertex, then second, then next and continue with next to walk ccw - pClosing->insertVertex( vFirst ); - pClosing->insertVertex( vSecond ); - pClosing->insertVertex( vNext ); - firstVertex = vFirst; - currentVertex = vNext; - - #ifdef _DEBUG_INTERSECTION_LIST - std::cout << "Plane: n=" << pl.normal << ", d=" << pl.d << std::endl; - std::cout << "First inserted vertex: " << *vFirst << std::endl; - std::cout << "Second inserted vertex: " << *vSecond << std::endl; - std::cout << "Third inserted vertex: " << *next << std::endl; - #endif - } - - // search mating edges that have a point in common - // continue this operation as long as edges are present - while ( !intersectionEdges.empty() ) - { - - if (findAndEraseEdgePair(currentVertex, intersectionEdges, vNext)) - { - // insert only if it's not the last (which equals the first) vertex - if ( !intersectionEdges.empty() ) - { - currentVertex = vNext; - pClosing->insertVertex( vNext ); - } - } - else - { - // degenerated... - break; - } - - } // while intersectionEdges not empty - - // insert polygon (may be degenerated!) - this->insertPolygon( pClosing ); - - } - // mating intersection edge NOT found! - else - { - freePolygon(pClosing); - } - - } // if intersectionEdges contains more than three elements - } - //----------------------------------------------------------------------- - bool ConvexBody::findAndEraseEdgePair(const Vector3& vec, - Polygon::EdgeMap& intersectionEdges, Vector3& vNext ) const - { - for (Polygon::EdgeMap::iterator it = intersectionEdges.begin(); - it != intersectionEdges.end(); ++it) - { - if (it->first.positionEquals(vec)) - { - vNext = it->second; - - // erase found edge - intersectionEdges.erase( it ); - - return true; // found! - } - else if (it->second.positionEquals(vec)) - { - vNext = it->first; - - // erase found edge - intersectionEdges.erase( it ); - - return true; // found! - } - } - - return false; // not found! - } -} - diff --git a/OgreMain/src/OgreDDSCodec.cpp b/OgreMain/src/OgreDDSCodec.cpp deleted file mode 100644 index 7fffc0d2093..00000000000 --- a/OgreMain/src/OgreDDSCodec.cpp +++ /dev/null @@ -1,1048 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" - -#include "OgreDDSCodec.h" -#include "OgreImage.h" - -namespace Ogre { - // Internal DDS structure definitions -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -#pragma pack (push, 1) -#else -#pragma pack (1) -#endif - - // Nested structure - struct DDSPixelFormat - { - uint32 size; - uint32 flags; - uint32 fourCC; - uint32 rgbBits; - uint32 redMask; - uint32 greenMask; - uint32 blueMask; - uint32 alphaMask; - }; - - // Nested structure - struct DDSCaps - { - uint32 caps1; - uint32 caps2; - uint32 caps3; - uint32 caps4; - }; - // Main header, note preceded by 'DDS ' - struct DDSHeader - { - uint32 size; - uint32 flags; - uint32 height; - uint32 width; - uint32 sizeOrPitch; - uint32 depth; - uint32 mipMapCount; - uint32 reserved1[11]; - DDSPixelFormat pixelFormat; - DDSCaps caps; - uint32 reserved2; - }; - - // Extended header - struct DDSExtendedHeader - { - uint32 dxgiFormat; - uint32 resourceDimension; - uint32 miscFlag; // see D3D11_RESOURCE_MISC_FLAG - uint32 arraySize; - uint32 reserved; - }; - - - // An 8-byte DXT colour block, represents a 4x4 texel area. Used by all DXT formats - struct DXTColourBlock - { - // 2 colour ranges - uint16 colour_0; - uint16 colour_1; - // 16 2-bit indexes, each byte here is one row - uint8 indexRow[4]; - }; - // An 8-byte DXT explicit alpha block, represents a 4x4 texel area. Used by DXT2/3 - struct DXTExplicitAlphaBlock - { - // 16 4-bit values, each 16-bit value is one row - uint16 alphaRow[4]; - }; - // An 8-byte DXT interpolated alpha block, represents a 4x4 texel area. Used by DXT4/5 - struct DXTInterpolatedAlphaBlock - { - // 2 alpha ranges - uint8 alpha_0; - uint8 alpha_1; - // 16 3-bit indexes. Unfortunately 3 bits doesn't map too well to row bytes - // so just stored raw - uint8 indexes[6]; - }; - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -#pragma pack (pop) -#else -#pragma pack () -#endif - -namespace { - const uint32 DDS_MAGIC = FOURCC('D', 'D', 'S', ' '); - const uint32 DDS_PIXELFORMAT_SIZE = 8 * sizeof(uint32); - const uint32 DDS_CAPS_SIZE = 4 * sizeof(uint32); - const uint32 DDS_HEADER_SIZE = 19 * sizeof(uint32) + DDS_PIXELFORMAT_SIZE + DDS_CAPS_SIZE; - - const uint32 DDSD_CAPS = 0x00000001; - const uint32 DDSD_HEIGHT = 0x00000002; - const uint32 DDSD_WIDTH = 0x00000004; - const uint32 DDSD_PIXELFORMAT = 0x00001000; - const uint32 DDSD_DEPTH = 0x00800000; - const uint32 DDPF_ALPHAPIXELS = 0x00000001; - const uint32 DDPF_FOURCC = 0x00000004; - const uint32 DDPF_RGB = 0x00000040; - const uint32 DDSCAPS_COMPLEX = 0x00000008; - const uint32 DDSCAPS_TEXTURE = 0x00001000; - const uint32 DDSCAPS_MIPMAP = 0x00400000; - const uint32 DDSCAPS2_CUBEMAP = 0x00000200; - const uint32 DDSCAPS2_CUBEMAP_POSITIVEX = 0x00000400; - const uint32 DDSCAPS2_CUBEMAP_NEGATIVEX = 0x00000800; - const uint32 DDSCAPS2_CUBEMAP_POSITIVEY = 0x00001000; - const uint32 DDSCAPS2_CUBEMAP_NEGATIVEY = 0x00002000; - const uint32 DDSCAPS2_CUBEMAP_POSITIVEZ = 0x00004000; - const uint32 DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x00008000; - const uint32 DDSCAPS2_VOLUME = 0x00200000; - - // Currently unused -// const uint32 DDSD_PITCH = 0x00000008; -// const uint32 DDSD_MIPMAPCOUNT = 0x00020000; -// const uint32 DDSD_LINEARSIZE = 0x00080000; - - // Special FourCC codes - const uint32 D3DFMT_R16F = 111; - const uint32 D3DFMT_G16R16F = 112; - const uint32 D3DFMT_A16B16G16R16F = 113; - const uint32 D3DFMT_R32F = 114; - const uint32 D3DFMT_G32R32F = 115; - const uint32 D3DFMT_A32B32G32R32F = 116; -} - - //--------------------------------------------------------------------- - DDSCodec* DDSCodec::msInstance = 0; - //--------------------------------------------------------------------- - void DDSCodec::startup(void) - { - if (!msInstance) - { - - LogManager::getSingleton().logMessage( - LML_NORMAL, - "DDS codec registering"); - - msInstance = OGRE_NEW DDSCodec(); - Codec::registerCodec(msInstance); - } - - } - //--------------------------------------------------------------------- - void DDSCodec::shutdown(void) - { - if(msInstance) - { - Codec::unregisterCodec(msInstance); - OGRE_DELETE msInstance; - msInstance = 0; - } - - } - //--------------------------------------------------------------------- - DDSCodec::DDSCodec(): - mType("dds") - { - } - //--------------------------------------------------------------------- - void DDSCodec::encodeToFile(const Any& input, const String& outFileName) const - { - Image* image = any_cast(input); - - bool isCubeMap = image->hasFlag(IF_CUBEMAP); - - // Establish texture attributes - bool isVolume = (image->getDepth() > 1); - bool isFloat32r = (image->getFormat() == PF_FLOAT32_R); - bool isFloat16 = (image->getFormat() == PF_FLOAT16_RGBA); - bool isFloat16r = (image->getFormat() == PF_FLOAT16_R); - bool isFloat32 = (image->getFormat() == PF_FLOAT32_RGBA); - bool notImplemented = false; - String notImplementedString = ""; - - // Check for all the 'not implemented' conditions - if ((isVolume == true)&&(image->getWidth() != image->getHeight())) - { - // Square textures only - notImplemented = true; - notImplementedString += "non square textures"; - } - - uint32 size = 1; - while (size < image->getWidth()) - { - size <<= 1; - } - if (size != image->getWidth()) - { - // Power two textures only - notImplemented = true; - notImplementedString += "non power two textures"; - } - - switch(image->getFormat()) - { - case PF_A8R8G8B8: - case PF_X8R8G8B8: - case PF_R8G8B8: - case PF_A8B8G8R8: - case PF_X8B8G8R8: - case PF_B8G8R8: - case PF_FLOAT32_R: - case PF_FLOAT16_R: - case PF_FLOAT16_RGBA: - case PF_FLOAT32_RGBA: - break; - default: - // No crazy FOURCC or 565 et al. file formats at this stage - notImplemented = true; - notImplementedString = PixelUtil::getFormatName(image->getFormat()); - break; - } - - - - // Except if any 'not implemented' conditions were met - if (notImplemented) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, - "DDS encoding for " + notImplementedString + " not supported"); - } - else - { - // Build header and write to disk - - // Variables for some DDS header flags - bool hasAlpha = false; - uint32 ddsHeaderFlags = 0; - uint32 ddsHeaderRgbBits = 0; - uint32 ddsHeaderSizeOrPitch = 0; - uint32 ddsHeaderCaps1 = 0; - uint32 ddsHeaderCaps2 = 0; - uint32 ddsMagic = DDS_MAGIC; - - // Initalise the header flags - ddsHeaderFlags = (isVolume) ? DDSD_CAPS|DDSD_WIDTH|DDSD_HEIGHT|DDSD_DEPTH|DDSD_PIXELFORMAT : - DDSD_CAPS|DDSD_WIDTH|DDSD_HEIGHT|DDSD_PIXELFORMAT; - - bool flipRgbMasks = false; - - // Initalise the rgbBits flags - switch(image->getFormat()) - { - case PF_A8B8G8R8: - flipRgbMasks = true; - OGRE_FALLTHROUGH; - case PF_A8R8G8B8: - ddsHeaderRgbBits = 8 * 4; - hasAlpha = true; - break; - case PF_X8B8G8R8: - flipRgbMasks = true; - OGRE_FALLTHROUGH; - case PF_X8R8G8B8: - ddsHeaderRgbBits = 8 * 4; - break; - case PF_B8G8R8: - case PF_R8G8B8: - ddsHeaderRgbBits = 8 * 3; - break; - case PF_FLOAT32_R: - ddsHeaderRgbBits = 32; - break; - case PF_FLOAT16_R: - ddsHeaderRgbBits = 16; - break; - case PF_FLOAT16_RGBA: - ddsHeaderRgbBits = 16 * 4; - hasAlpha = true; - break; - case PF_FLOAT32_RGBA: - ddsHeaderRgbBits = 32 * 4; - hasAlpha = true; - break; - default: - ddsHeaderRgbBits = 0; - break; - } - - // Initalise the SizeOrPitch flags (power two textures for now) - ddsHeaderSizeOrPitch = static_cast(ddsHeaderRgbBits * image->getWidth()); - - // Initalise the caps flags - ddsHeaderCaps1 = (isVolume||isCubeMap) ? DDSCAPS_COMPLEX|DDSCAPS_TEXTURE : DDSCAPS_TEXTURE; - if (isVolume) - { - ddsHeaderCaps2 = DDSCAPS2_VOLUME; - } - else if (isCubeMap) - { - ddsHeaderCaps2 = DDSCAPS2_CUBEMAP| - DDSCAPS2_CUBEMAP_POSITIVEX|DDSCAPS2_CUBEMAP_NEGATIVEX| - DDSCAPS2_CUBEMAP_POSITIVEY|DDSCAPS2_CUBEMAP_NEGATIVEY| - DDSCAPS2_CUBEMAP_POSITIVEZ|DDSCAPS2_CUBEMAP_NEGATIVEZ; - } - - if( image->getNumMipmaps() > 0 ) - ddsHeaderCaps1 |= DDSCAPS_MIPMAP; - - // Populate the DDS header information - DDSHeader ddsHeader; - ddsHeader.size = DDS_HEADER_SIZE; - ddsHeader.flags = ddsHeaderFlags; - ddsHeader.width = image->getWidth(); - ddsHeader.height = image->getHeight(); - ddsHeader.depth = (uint32)(isVolume ? image->getDepth() : 0); - ddsHeader.depth = (uint32)(isCubeMap ? 6 : ddsHeader.depth); - ddsHeader.mipMapCount = image->getNumMipmaps() + 1; - ddsHeader.sizeOrPitch = ddsHeaderSizeOrPitch; - for (unsigned int & reserved1 : ddsHeader.reserved1) // XXX nasty constant 11 - { - reserved1 = 0; - } - ddsHeader.reserved2 = 0; - - ddsHeader.pixelFormat.size = DDS_PIXELFORMAT_SIZE; - ddsHeader.pixelFormat.flags = (hasAlpha) ? DDPF_RGB|DDPF_ALPHAPIXELS : DDPF_RGB; - ddsHeader.pixelFormat.flags = (isFloat32r || isFloat16r || isFloat16 || isFloat32) ? DDPF_FOURCC : ddsHeader.pixelFormat.flags; - if (isFloat32r) { - ddsHeader.pixelFormat.fourCC = D3DFMT_R32F; - } - else if (isFloat16r) { - ddsHeader.pixelFormat.fourCC = D3DFMT_R16F; - } - else if (isFloat16) { - ddsHeader.pixelFormat.fourCC = D3DFMT_A16B16G16R16F; - } - else if (isFloat32) { - ddsHeader.pixelFormat.fourCC = D3DFMT_A32B32G32R32F; - } - else { - ddsHeader.pixelFormat.fourCC = 0; - } - ddsHeader.pixelFormat.rgbBits = ddsHeaderRgbBits; - - ddsHeader.pixelFormat.alphaMask = (hasAlpha) ? 0xFF000000 : 0x00000000; - ddsHeader.pixelFormat.alphaMask = (isFloat32r || isFloat16r) ? 0x00000000 : ddsHeader.pixelFormat.alphaMask; - ddsHeader.pixelFormat.redMask = (isFloat32r || isFloat16r) ? 0xFFFFFFFF :0x00FF0000; - ddsHeader.pixelFormat.greenMask = (isFloat32r || isFloat16r) ? 0x00000000 :0x0000FF00; - ddsHeader.pixelFormat.blueMask = (isFloat32r || isFloat16r) ? 0x00000000 :0x000000FF; - - if( flipRgbMasks ) - std::swap( ddsHeader.pixelFormat.redMask, ddsHeader.pixelFormat.blueMask ); - - ddsHeader.caps.caps1 = ddsHeaderCaps1; - ddsHeader.caps.caps2 = ddsHeaderCaps2; -// ddsHeader.caps.reserved[0] = 0; -// ddsHeader.caps.reserved[1] = 0; - - // Swap endian - flipEndian(&ddsMagic, sizeof(uint32)); - flipEndian(&ddsHeader, 4, sizeof(DDSHeader) / 4); - - char *tmpData = 0; - char *dataPtr = (char*)image->getData(); - - if( image->getFormat() == PF_B8G8R8 ) - { - PixelBox src( image->getSize() / 3, 1, 1, PF_B8G8R8, image->getData() ); - tmpData = new char[image->getSize()]; - PixelBox dst( image->getSize() / 3, 1, 1, PF_R8G8B8, tmpData ); - - PixelUtil::bulkPixelConversion( src, dst ); - - dataPtr = tmpData; - } - - try - { - // Write the file - std::ofstream of; - of.open(outFileName.c_str(), std::ios_base::binary|std::ios_base::out); - of.write((const char *)&ddsMagic, sizeof(uint32)); - of.write((const char *)&ddsHeader, DDS_HEADER_SIZE); - // XXX flipEndian on each pixel chunk written unless isFloat32r ? - of.write(dataPtr, image->getSize()); - of.close(); - } - catch(...) - { - } - delete [] tmpData; - } - } - //--------------------------------------------------------------------- - PixelFormat DDSCodec::convertDXToOgreFormat(uint32 dxfmt) const - { - switch (dxfmt) { - case 2: // DXGI_FORMAT_R32G32B32A32_FLOAT - return PF_FLOAT32_RGBA; - case 3: // DXGI_FORMAT_R32G32B32A32_UINT - return PF_R32G32B32A32_UINT; - case 4: //DXGI_FORMAT_R32G32B32A32_SINT - return PF_R32G32B32A32_SINT; - case 6: // DXGI_FORMAT_R32G32B32_FLOAT - return PF_FLOAT32_RGB; - case 7: // DXGI_FORMAT_R32G32B32_UINT - return PF_R32G32B32_UINT; - case 8: // DXGI_FORMAT_R32G32B32_SINT - return PF_R32G32B32_SINT; - case 10: // DXGI_FORMAT_R16G16B16A16_FLOAT - return PF_FLOAT16_RGBA; - case 12: // DXGI_FORMAT_R16G16B16A16_UINT - return PF_R16G16B16A16_UINT; - case 13: // DXGI_FORMAT_R16G16B16A16_SNORM - return PF_R16G16B16A16_SNORM; - case 14: // DXGI_FORMAT_R16G16B16A16_SINT - return PF_R16G16B16A16_SINT; - case 16: // DXGI_FORMAT_R32G32_FLOAT - return PF_FLOAT32_GR; - case 17: // DXGI_FORMAT_R32G32_UINT - return PF_R32G32_UINT; - case 18: // DXGI_FORMAT_R32G32_SINT - return PF_R32G32_SINT; - case 24: // DXGI_FORMAT_R10G10B10A2_UNORM - case 25: // DXGI_FORMAT_R10G10B10A2_UINT - return PF_A2B10G10R10; - case 26: // DXGI_FORMAT_R11G11B10_FLOAT - return PF_R11G11B10_FLOAT; - case 28: // DXGI_FORMAT_R8G8B8A8_UNORM - case 29: // DXGI_FORMAT_R8G8B8A8_UNORM_SRGB - return PF_A8B8G8R8; - case 30: // DXGI_FORMAT_R8G8B8A8_UINT - return PF_R8G8B8A8_UINT; - case 31: // DXGI_FORMAT_R8G8B8A8_SNORM - return PF_R8G8B8A8_SNORM; - case 32: // DXGI_FORMAT_R8G8B8A8_SINT - return PF_R8G8B8A8_SINT; - case 34: // DXGI_FORMAT_R16G16_FLOAT - return PF_FLOAT16_GR; - case 35: // DXGI_FORMAT_R16G16_UNORM - return PF_SHORT_GR; - case 36: // DXGI_FORMAT_R16G16_UINT - return PF_R16G16_UINT; - case 37: // DXGI_FORMAT_R16G16_SNORM - return PF_R16G16_SNORM; - case 38: // DXGI_FORMAT_R16G16_SINT - return PF_R16G16_SINT; - case 41: // DXGI_FORMAT_R32_FLOAT - return PF_FLOAT32_R; - case 42: // DXGI_FORMAT_R32_UINT - return PF_R32_UINT; - case 43: // DXGI_FORMAT_R32_SINT - return PF_R32_SINT; - case 49: // DXGI_FORMAT_R8G8_UNORM - case 50: // DXGI_FORMAT_R8G8_UINT - return PF_R8G8_UINT; - case 52: // DXGI_FORMAT_R8G8_SINT - return PF_R8G8_SINT; - case 54: // DXGI_FORMAT_R16_FLOAT - return PF_FLOAT16_R; - case 56: // DXGI_FORMAT_R16_UNORM - return PF_L16; - case 57: // DXGI_FORMAT_R16_UINT - return PF_R16_UINT; - case 58: // DXGI_FORMAT_R16_SNORM - return PF_R16_SNORM; - case 59: // DXGI_FORMAT_R16_SINT - return PF_R16_SINT; - case 61: // DXGI_FORMAT_R8_UNORM - return PF_R8; - case 62: // DXGI_FORMAT_R8_UINT - return PF_R8_UINT; - case 63: // DXGI_FORMAT_R8_SNORM - return PF_R8_SNORM; - case 64: // DXGI_FORMAT_R8_SINT - return PF_R8_SINT; - case 65: // DXGI_FORMAT_A8_UNORM - return PF_A8; - case 80: // DXGI_FORMAT_BC4_UNORM - return PF_BC4_UNORM; - case 81: // DXGI_FORMAT_BC4_SNORM - return PF_BC4_SNORM; - case 83: // DXGI_FORMAT_BC5_UNORM - return PF_BC5_UNORM; - case 84: // DXGI_FORMAT_BC5_SNORM - return PF_BC5_SNORM; - case 85: // DXGI_FORMAT_B5G6R5_UNORM - return PF_R5G6B5; - case 86: // DXGI_FORMAT_B5G5R5A1_UNORM - return PF_A1R5G5B5; - case 87: // DXGI_FORMAT_B8G8R8A8_UNORM - return PF_A8R8G8B8; - case 88: // DXGI_FORMAT_B8G8R8X8_UNORM - return PF_X8R8G8B8; - case 95: // DXGI_FORMAT_BC6H_UF16 - return PF_BC6H_UF16; - case 96: // DXGI_FORMAT_BC6H_SF16 - return PF_BC6H_SF16; - case 98: // DXGI_FORMAT_BC7_UNORM - case 99: // DXGI_FORMAT_BC7_UNORM_SRGB - return PF_BC7_UNORM; - case 20: // DXGI_FORMAT_D32_FLOAT_S8X24_UINT - case 22: // DXGI_FORMAT_X32_TYPELESS_G8X24_UINT - case 40: // DXGI_FORMAT_D32_FLOAT - case 45: // DXGI_FORMAT_D24_UNORM_S8_UINT - case 47: // DXGI_FORMAT_X24_TYPELESS_G8_UINT - case 55: // DXGI_FORMAT_D16_UNORM - default: - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Unsupported DirectX format found in DDS file", - "DDSCodec::convertDXToOgreFormat"); - } - } - //--------------------------------------------------------------------- - PixelFormat DDSCodec::convertFourCCFormat(uint32 fourcc) const - { - // convert dxt pixel format - switch(fourcc) - { - case FOURCC('D','X','T','1'): - return PF_DXT1; - case FOURCC('D','X','T','2'): - return PF_DXT2; - case FOURCC('D','X','T','3'): - return PF_DXT3; - case FOURCC('D','X','T','4'): - return PF_DXT4; - case FOURCC('D','X','T','5'): - return PF_DXT5; - case FOURCC('A','T','I','1'): - case FOURCC('B','C','4','U'): - return PF_BC4_UNORM; - case FOURCC('B','C','4','S'): - return PF_BC4_SNORM; - case FOURCC('A','T','I','2'): - case FOURCC('B','C','5','U'): - return PF_BC5_UNORM; - case FOURCC('B','C','5','S'): - return PF_BC5_SNORM; - case D3DFMT_R16F: - return PF_FLOAT16_R; - case D3DFMT_G16R16F: - return PF_FLOAT16_GR; - case D3DFMT_A16B16G16R16F: - return PF_FLOAT16_RGBA; - case D3DFMT_R32F: - return PF_FLOAT32_R; - case D3DFMT_G32R32F: - return PF_FLOAT32_GR; - case D3DFMT_A32B32G32R32F: - return PF_FLOAT32_RGBA; - // We could support 3Dc here, but only ATI cards support it, not nVidia - default: - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Unsupported FourCC format found in DDS file", - "DDSCodec::convertFourCCFormat"); - }; - - } - //--------------------------------------------------------------------- - PixelFormat DDSCodec::convertPixelFormat(uint32 rgbBits, uint32 rMask, - uint32 gMask, uint32 bMask, uint32 aMask) const - { - // General search through pixel formats - for (int i = PF_UNKNOWN + 1; i < PF_COUNT; ++i) - { - PixelFormat pf = static_cast(i); - if (PixelUtil::getNumElemBits(pf) == rgbBits) - { - uint64 testMasks[4]; - PixelUtil::getBitMasks(pf, testMasks); - int testBits[4]; - PixelUtil::getBitDepths(pf, testBits); - if (testMasks[0] == rMask && testMasks[1] == gMask && - testMasks[2] == bMask && - // for alpha, deal with 'X8' formats by checking bit counts - (testMasks[3] == aMask || (aMask == 0 && testBits[3] == 0))) - { - return pf; - } - } - - } - - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Cannot determine pixel format", - "DDSCodec::convertPixelFormat"); - } - //--------------------------------------------------------------------- - void DDSCodec::unpackDXTColour(PixelFormat pf, const DXTColourBlock& block, - ColourValue* pCol) const - { - // Note - we assume all values have already been endian swapped - - // Colour lookup table - ColourValue derivedColours[4]; - - if (pf == PF_DXT1 && block.colour_0 <= block.colour_1) - { - // 1-bit alpha - PixelUtil::unpackColour(&(derivedColours[0]), PF_R5G6B5, &(block.colour_0)); - PixelUtil::unpackColour(&(derivedColours[1]), PF_R5G6B5, &(block.colour_1)); - // one intermediate colour, half way between the other two - derivedColours[2] = (derivedColours[0] + derivedColours[1]) / 2; - // transparent colour - derivedColours[3] = ColourValue::ZERO; - } - else - { - PixelUtil::unpackColour(&(derivedColours[0]), PF_R5G6B5, &(block.colour_0)); - PixelUtil::unpackColour(&(derivedColours[1]), PF_R5G6B5, &(block.colour_1)); - // first interpolated colour, 1/3 of the way along - derivedColours[2] = (2 * derivedColours[0] + derivedColours[1]) / 3; - // second interpolated colour, 2/3 of the way along - derivedColours[3] = (derivedColours[0] + 2 * derivedColours[1]) / 3; - } - - // Process 4x4 block of texels - for (size_t row = 0; row < 4; ++row) - { - for (size_t x = 0; x < 4; ++x) - { - // LSB come first - uint8 colIdx = static_cast(block.indexRow[row] >> (x * 2) & 0x3); - if (pf == PF_DXT1) - { - // Overwrite entire colour - pCol[(row * 4) + x] = derivedColours[colIdx]; - } - else - { - // alpha has already been read (alpha precedes colour) - ColourValue& col = pCol[(row * 4) + x]; - col.r = derivedColours[colIdx].r; - col.g = derivedColours[colIdx].g; - col.b = derivedColours[colIdx].b; - } - } - - } - - - } - //--------------------------------------------------------------------- - void DDSCodec::unpackDXTAlpha( - const DXTExplicitAlphaBlock& block, ColourValue* pCol) const - { - // Note - we assume all values have already been endian swapped - - // This is an explicit alpha block, 4 bits per pixel, LSB first - for (unsigned short row : block.alphaRow) - { - for (size_t x = 0; x < 4; ++x) - { - // Shift and mask off to 4 bits - uint8 val = static_cast(row >> (x * 4) & 0xF); - // Convert to [0,1] - pCol->a = (Real)val / (Real)0xF; - pCol++; - - } - - } - - } - //--------------------------------------------------------------------- - void DDSCodec::unpackDXTAlpha( - const DXTInterpolatedAlphaBlock& block, ColourValue* pCol) const - { - // Adaptive 3-bit alpha part - float derivedAlphas[8]; - - // Explicit extremes - derivedAlphas[0] = ((float) block.alpha_0) * (1.0f / 255.0f); - derivedAlphas[1] = ((float) block.alpha_1) * (1.0f / 255.0f); - - if(block.alpha_0 > block.alpha_1) - { - // 6 interpolated alpha values. - // full range including extremes at [0] and [7] - // we want to fill in [1] through [6] at weights ranging - // from 1/7 to 6/7 - for(size_t i = 1; i < 7; ++i) - derivedAlphas[i + 1] = (derivedAlphas[0] * (7 - i) + derivedAlphas[1] * i) * (1.0f / 7.0f); - } - else - { - // 4 interpolated alpha values. - // full range including extremes at [0] and [5] - // we want to fill in [1] through [4] at weights ranging - // from 1/5 to 4/5 - for(size_t i = 1; i < 5; ++i) - derivedAlphas[i + 1] = (derivedAlphas[0] * (5 - i) + derivedAlphas[1] * i) * (1.0f / 5.0f); - - derivedAlphas[6] = 0.0f; - derivedAlphas[7] = 1.0f; - } - - // Ok, now we've built the reference values, process the indexes - uint32 dw = block.indexes[0] | (block.indexes[1] << 8) | (block.indexes[2] << 16); - - for(size_t i = 0; i < 8; ++i, dw >>= 3) - pCol[i].a = derivedAlphas[dw & 0x7]; - - dw = block.indexes[3] | (block.indexes[4] << 8) | (block.indexes[5] << 16); - - for(size_t i = 8; i < 16; ++i, dw >>= 3) - pCol[i].a = derivedAlphas[dw & 0x7]; - } - //--------------------------------------------------------------------- - void DDSCodec::decode(const DataStreamPtr& stream, const Any& output) const - { - Image* image = any_cast(output); - // Read 4 character code - uint32 fileType; - stream->read(&fileType, sizeof(uint32)); - flipEndian(&fileType, sizeof(uint32)); - - if (FOURCC('D', 'D', 'S', ' ') != fileType) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "This is not a DDS file!", "DDSCodec::decode"); - } - - // Read header in full - DDSHeader header; - stream->read(&header, sizeof(DDSHeader)); - - // Endian flip if required, all 32-bit values - flipEndian(&header, 4, sizeof(DDSHeader) / 4); - - // Check some sizes - if (header.size != DDS_HEADER_SIZE) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "DDS header size mismatch!", "DDSCodec::decode"); - } - if (header.pixelFormat.size != DDS_PIXELFORMAT_SIZE) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "DDS header size mismatch!", "DDSCodec::decode"); - } - - uint32 imgDepth = 1; // (deal with volume later) - uint32 numFaces = 1; // assume one face until we know otherwise - uint32 num_mipmaps = 0; - PixelFormat format = PF_UNKNOWN; - - if (header.caps.caps1 & DDSCAPS_MIPMAP) - { - num_mipmaps = static_cast(header.mipMapCount - 1); - } - else - { - num_mipmaps = 0; - } - - bool decompressDXT = false; - // Figure out basic image type - if (header.caps.caps2 & DDSCAPS2_CUBEMAP) - { - numFaces = 6; - } - else if (header.caps.caps2 & DDSCAPS2_VOLUME) - { - imgDepth = header.depth; - } - // Pixel format - PixelFormat sourceFormat = PF_UNKNOWN; - - if (header.pixelFormat.flags & DDPF_FOURCC) - { - // Check if we have an DX10 style extended header and read it. This is necessary for B6H and B7 formats - if(header.pixelFormat.fourCC == FOURCC('D', 'X', '1', '0')) - { - DDSExtendedHeader extHeader; - stream->read(&extHeader, sizeof(DDSExtendedHeader)); - - // Endian flip if required, all 32-bit values - flipEndian(&header, sizeof(DDSExtendedHeader)); - sourceFormat = convertDXToOgreFormat(extHeader.dxgiFormat); - } - else - { - sourceFormat = convertFourCCFormat(header.pixelFormat.fourCC); - } - } - else - { - sourceFormat = convertPixelFormat(header.pixelFormat.rgbBits, - header.pixelFormat.redMask, header.pixelFormat.greenMask, - header.pixelFormat.blueMask, - header.pixelFormat.flags & DDPF_ALPHAPIXELS ? - header.pixelFormat.alphaMask : 0); - } - - if (PixelUtil::isCompressed(sourceFormat)) - { - if (Root::getSingleton().getRenderSystem() == NULL || - !Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_TEXTURE_COMPRESSION_DXT)) - { - // We'll need to decompress - decompressDXT = true; - // Convert format - switch (sourceFormat) - { - case PF_DXT1: - // source can be either 565 or 5551 depending on whether alpha present - // unfortunately you have to read a block to figure out which - // Note that we upgrade to 32-bit pixel formats here, even - // though the source is 16-bit; this is because the interpolated - // values will benefit from the 32-bit results, and the source - // from which the 16-bit samples are calculated may have been - // 32-bit so can benefit from this. - DXTColourBlock block; - stream->read(&block, sizeof(DXTColourBlock)); - flipEndian(&(block.colour_0), sizeof(uint16)); - flipEndian(&(block.colour_1), sizeof(uint16)); - // skip back since we'll need to read this again - stream->skip(0 - (long)sizeof(DXTColourBlock)); - // colour_0 <= colour_1 means transparency in DXT1 - if (block.colour_0 <= block.colour_1) - { - format = PF_BYTE_RGBA; - } - else - { - format = PF_BYTE_RGB; - } - break; - case PF_DXT2: - case PF_DXT3: - case PF_DXT4: - case PF_DXT5: - // full alpha present, formats vary only in encoding - format = PF_BYTE_RGBA; - break; - default: - // all other cases need no special format handling - break; - } - } - else - { - // Use original format - format = sourceFormat; - } - } - else // not compressed - { - // Don't test against DDPF_RGB since greyscale DDS doesn't set this - // just derive any other kind of format - format = sourceFormat; - } - - // Calculate total size from number of mipmaps, faces and size - image->create(format, header.width, header.height, imgDepth, numFaces, num_mipmaps); - - // Now deal with the data - void* destPtr = image->getData(); - - // all mips for a face, then each face - for(size_t i = 0; i < numFaces; ++i) - { - uint32 width = image->getWidth(); - uint32 height = image->getHeight(); - uint32 depth = image->getDepth(); - - for(size_t mip = 0; mip <= num_mipmaps; ++mip) - { - size_t dstPitch = width * PixelUtil::getNumElemBytes(format); - - if (PixelUtil::isCompressed(sourceFormat)) - { - // Compressed data - if (decompressDXT) - { - DXTColourBlock col; - DXTInterpolatedAlphaBlock iAlpha; - DXTExplicitAlphaBlock eAlpha; - // 4x4 block of decompressed colour - ColourValue tempColours[16]; - size_t destBpp = PixelUtil::getNumElemBytes(format); - - // slices are done individually - for(size_t z = 0; z < depth; ++z) - { - size_t remainingHeight = height; - - // 4x4 blocks in x/y - for (size_t y = 0; y < height; y += 4) - { - size_t sy = std::min( remainingHeight, 4u ); - remainingHeight -= sy; - - size_t remainingWidth = width; - - for (size_t x = 0; x < width; x += 4) - { - size_t sx = std::min( remainingWidth, 4u ); - size_t destPitchMinus4 = dstPitch - destBpp * sx; - - remainingWidth -= sx; - - if (sourceFormat == PF_DXT2 || - sourceFormat == PF_DXT3) - { - // explicit alpha - stream->read(&eAlpha, sizeof(DXTExplicitAlphaBlock)); - flipEndian(eAlpha.alphaRow, sizeof(uint16), 4); - unpackDXTAlpha(eAlpha, tempColours) ; - } - else if (sourceFormat == PF_DXT4 || - sourceFormat == PF_DXT5) - { - // interpolated alpha - stream->read(&iAlpha, sizeof(DXTInterpolatedAlphaBlock)); - flipEndian(&(iAlpha.alpha_0), sizeof(uint16)); - flipEndian(&(iAlpha.alpha_1), sizeof(uint16)); - unpackDXTAlpha(iAlpha, tempColours) ; - } - // always read colour - stream->read(&col, sizeof(DXTColourBlock)); - flipEndian(&(col.colour_0), sizeof(uint16)); - flipEndian(&(col.colour_1), sizeof(uint16)); - unpackDXTColour(sourceFormat, col, tempColours); - - // write 4x4 block to uncompressed version - for (size_t by = 0; by < sy; ++by) - { - for (size_t bx = 0; bx < sx; ++bx) - { - PixelUtil::packColour(tempColours[by*4+bx], - format, destPtr); - destPtr = static_cast( - static_cast(destPtr) + destBpp); - } - // advance to next row - destPtr = static_cast( - static_cast(destPtr) + destPitchMinus4); - } - // next block. Our dest pointer is 4 lines down - // from where it started - if (x + 4 >= width) - { - // Jump back to the start of the line - destPtr = static_cast( - static_cast(destPtr) - destPitchMinus4); - } - else - { - // Jump back up 4 rows and 4 pixels to the - // right to be at the next block to the right - destPtr = static_cast( - static_cast(destPtr) - dstPitch * sy + destBpp * sx); - - } - - } - - } - } - - } - else - { - // load directly - // DDS format lies! sizeOrPitch is not always set for DXT!! - size_t dxtSize = PixelUtil::getMemorySize(width, height, depth, format); - stream->read(destPtr, dxtSize); - destPtr = static_cast(static_cast(destPtr) + dxtSize); - } - - } - else - { - // Note: We assume the source and destination have the same pitch - for (size_t z = 0; z < depth; ++z) - { - for (size_t y = 0; y < height; ++y) - { - stream->read(destPtr, dstPitch); - destPtr = static_cast(static_cast(destPtr) + dstPitch); - } - } - } - - /// Next mip - if(width!=1) width /= 2; - if(height!=1) height /= 2; - if(depth!=1) depth /= 2; - } - - } - } - //--------------------------------------------------------------------- - String DDSCodec::getType() const - { - return mType; - } - //--------------------------------------------------------------------- - String DDSCodec::magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const - { - if (maxbytes >= sizeof(uint32)) - { - uint32 fileType; - memcpy(&fileType, magicNumberPtr, sizeof(uint32)); - flipEndian(&fileType, sizeof(uint32)); - - if (DDS_MAGIC == fileType) - { - return String("dds"); - } - } - - return BLANKSTRING; - - } - -} - diff --git a/OgreMain/src/OgreDDSCodec.h b/OgreMain/src/OgreDDSCodec.h deleted file mode 100644 index 576165667c4..00000000000 --- a/OgreMain/src/OgreDDSCodec.h +++ /dev/null @@ -1,94 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OgreDDSCodec_H__ -#define __OgreDDSCodec_H__ - -#include "OgreImageCodec.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Image - * @{ - */ - - // Forward declarations - struct DXTColourBlock; - struct DXTExplicitAlphaBlock; - struct DXTInterpolatedAlphaBlock; - - /** Codec specialized in loading DDS (Direct Draw Surface) images. - - We implement our own codec here since we need to be able to keep DXT - data compressed if the card supports it. - */ - class DDSCodec : public ImageCodec - { - private: - String mType; - - PixelFormat convertFourCCFormat(uint32 fourcc) const; - PixelFormat convertDXToOgreFormat(uint32 fourcc) const; - PixelFormat convertPixelFormat(uint32 rgbBits, uint32 rMask, - uint32 gMask, uint32 bMask, uint32 aMask) const; - - /// Unpack DXT colours into array of 16 colour values - void unpackDXTColour(PixelFormat pf, const DXTColourBlock& block, ColourValue* pCol) const; - /// Unpack DXT alphas into array of 16 colour values - void unpackDXTAlpha(const DXTExplicitAlphaBlock& block, ColourValue* pCol) const; - /// Unpack DXT alphas into array of 16 colour values - void unpackDXTAlpha(const DXTInterpolatedAlphaBlock& block, ColourValue* pCol) const; - - /// Single registered codec instance - static DDSCodec* msInstance; - public: - DDSCodec(); - virtual ~DDSCodec() { } - - void encodeToFile(const Any& input, const String& outFileName) const override; - void decode(const DataStreamPtr& input, const Any& output) const override; - String magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const override; - String getType() const override; - - /// Static method to startup and register the DDS codec - static void startup(void); - /// Static method to shutdown and unregister the DDS codec - static void shutdown(void); - - }; - /** @} */ - /** @} */ - -} // namespace - -#include "OgreHeaderSuffix.h" - -#endif - diff --git a/OgreMain/src/OgreDataStream.cpp b/OgreMain/src/OgreDataStream.cpp deleted file mode 100644 index 6d4f9d21aad..00000000000 --- a/OgreMain/src/OgreDataStream.cpp +++ /dev/null @@ -1,764 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -namespace Ogre { - - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - template DataStream& DataStream::operator >>(T& val) - { - read(static_cast(&val), sizeof(T)); - return *this; - } - //----------------------------------------------------------------------- - String DataStream::getLine(bool trimAfter) - { - char tmpBuf[OGRE_STREAM_TEMP_SIZE]; - String retString; - size_t readCount; - // Keep looping while not hitting delimiter - while ((readCount = read(tmpBuf, OGRE_STREAM_TEMP_SIZE-1)) != 0) - { - // Terminate string - tmpBuf[readCount] = '\0'; - - char* p = strchr(tmpBuf, '\n'); - if (p != 0) - { - // Reposition backwards - skip((long)(p + 1 - tmpBuf - readCount)); - *p = '\0'; - } - - retString += tmpBuf; - - if (p != 0) - { - // Trim off trailing CR if this was a CR/LF entry - if (retString.length() && retString[retString.length()-1] == '\r') - { - retString.erase(retString.length()-1, 1); - } - - // Found terminator, break out - break; - } - } - - if (trimAfter) - { - StringUtil::trim(retString); - } - - return retString; - } - //----------------------------------------------------------------------- - size_t DataStream::readLine(char* buf, size_t maxCount, const String& delim) - { - // Deal with both Unix & Windows LFs - bool trimCR = false; - if (delim.find_first_of('\n') != String::npos) - { - trimCR = true; - } - - char tmpBuf[OGRE_STREAM_TEMP_SIZE]; - size_t chunkSize = std::min(maxCount, (size_t)OGRE_STREAM_TEMP_SIZE-1); - size_t totalCount = 0; - size_t readCount; - while (chunkSize && (readCount = read(tmpBuf, chunkSize)) != 0) - { - // Terminate - tmpBuf[readCount] = '\0'; - - // Find first delimiter - size_t pos = strcspn(tmpBuf, delim.c_str()); - - if (pos < readCount) - { - // Found terminator, reposition backwards - skip((long)(pos + 1 - readCount)); - } - - // Are we genuinely copying? - if (buf) - { - memcpy(buf+totalCount, tmpBuf, pos); - } - totalCount += pos; - - if (pos < readCount) - { - // Trim off trailing CR if this was a CR/LF entry - if (trimCR && totalCount && buf && buf[totalCount-1] == '\r') - { - --totalCount; - } - - // Found terminator, break out - break; - } - - // Adjust chunkSize for next time - chunkSize = std::min(maxCount-totalCount, (size_t)OGRE_STREAM_TEMP_SIZE-1); - } - - // Terminate - if(buf) - buf[totalCount] = '\0'; - - return totalCount; - } - //----------------------------------------------------------------------- - size_t DataStream::skipLine(const String& delim) - { - char tmpBuf[OGRE_STREAM_TEMP_SIZE]; - size_t total = 0; - size_t readCount; - // Keep looping while not hitting delimiter - while ((readCount = read(tmpBuf, OGRE_STREAM_TEMP_SIZE-1)) != 0) - { - // Terminate string - tmpBuf[readCount] = '\0'; - - // Find first delimiter - size_t pos = strcspn(tmpBuf, delim.c_str()); - - if (pos < readCount) - { - // Found terminator, reposition backwards - skip((long)(pos + 1 - readCount)); - - total += pos + 1; - - // break out - break; - } - - total += readCount; - } - - return total; - } - //----------------------------------------------------------------------- - String DataStream::getAsString(void) - { - // Read the entire buffer - ideally in one read, but if the size of - // the buffer is unknown, do multiple fixed size reads. - size_t bufSize = (mSize > 0 ? mSize : 4096); - char* pBuf = OGRE_ALLOC_T(char, bufSize, MEMCATEGORY_GENERAL); - // Ensure read from begin of stream - seek(0); - String result; - while (!eof()) - { - size_t nr = read(pBuf, bufSize); - result.append(pBuf, nr); - } - OGRE_FREE(pBuf, MEMCATEGORY_GENERAL); - return result; - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - MemoryDataStream::MemoryDataStream(void* pMem, size_t inSize, bool freeOnClose, bool readOnly) - : DataStream(static_cast(readOnly ? READ : (READ | WRITE))) - { - mData = mPos = static_cast(pMem); - mSize = inSize; - mEnd = mData + mSize; - mFreeOnClose = freeOnClose; - assert(mEnd >= mPos); - } - //----------------------------------------------------------------------- - MemoryDataStream::MemoryDataStream(const String& name, void* pMem, size_t inSize, - bool freeOnClose, bool readOnly) - : DataStream(name, static_cast(readOnly ? READ : (READ | WRITE))) - { - mData = mPos = static_cast(pMem); - mSize = inSize; - mEnd = mData + mSize; - mFreeOnClose = freeOnClose; - assert(mEnd >= mPos); - } - //----------------------------------------------------------------------- - MemoryDataStream::MemoryDataStream(DataStream& sourceStream, - bool freeOnClose, bool readOnly) - : DataStream(static_cast(readOnly ? READ : (READ | WRITE))) - { - // Copy data from incoming stream - mSize = sourceStream.size(); - if (mSize == 0 && !sourceStream.eof()) - { - // size of source is unknown, read all of it into memory - String contents = sourceStream.getAsString(); - mSize = contents.size(); - mData = OGRE_ALLOC_T(uchar, mSize, MEMCATEGORY_GENERAL); - mPos = mData; - memcpy(mData, contents.data(), mSize); - mEnd = mData + mSize; - } - else - { - mData = OGRE_ALLOC_T(uchar, mSize, MEMCATEGORY_GENERAL); - mPos = mData; - mEnd = mData + sourceStream.read(mData, mSize); - } - mFreeOnClose = freeOnClose; - assert(mEnd >= mPos); - } - //----------------------------------------------------------------------- - MemoryDataStream::MemoryDataStream(const DataStreamPtr& sourceStream, - bool freeOnClose, bool readOnly) - : DataStream(static_cast(readOnly ? READ : (READ | WRITE))) - { - // Copy data from incoming stream - mSize = sourceStream->size(); - if (mSize == 0 && !sourceStream->eof()) - { - // size of source is unknown, read all of it into memory - String contents = sourceStream->getAsString(); - mSize = contents.size(); - mData = OGRE_ALLOC_T(uchar, mSize, MEMCATEGORY_GENERAL); - mPos = mData; - memcpy(mData, contents.data(), mSize); - mEnd = mData + mSize; - } - else - { - mData = OGRE_ALLOC_T(uchar, mSize, MEMCATEGORY_GENERAL); - mPos = mData; - mEnd = mData + sourceStream->read(mData, mSize); - } - mFreeOnClose = freeOnClose; - assert(mEnd >= mPos); - } - //----------------------------------------------------------------------- - MemoryDataStream::MemoryDataStream(const String& name, DataStream& sourceStream, - bool freeOnClose, bool readOnly) - : DataStream(name, static_cast(readOnly ? READ : (READ | WRITE))) - { - // Copy data from incoming stream - mSize = sourceStream.size(); - if (mSize == 0 && !sourceStream.eof()) - { - // size of source is unknown, read all of it into memory - String contents = sourceStream.getAsString(); - mSize = contents.size(); - mData = OGRE_ALLOC_T(uchar, mSize, MEMCATEGORY_GENERAL); - mPos = mData; - memcpy(mData, contents.data(), mSize); - mEnd = mData + mSize; - } - else - { - mData = OGRE_ALLOC_T(uchar, mSize, MEMCATEGORY_GENERAL); - mPos = mData; - mEnd = mData + sourceStream.read(mData, mSize); - } - mFreeOnClose = freeOnClose; - assert(mEnd >= mPos); - } - //----------------------------------------------------------------------- - MemoryDataStream::MemoryDataStream(const String& name, const DataStreamPtr& sourceStream, - bool freeOnClose, bool readOnly) - : DataStream(name, static_cast(readOnly ? READ : (READ | WRITE))) - { - // Copy data from incoming stream - mSize = sourceStream->size(); - if (mSize == 0 && !sourceStream->eof()) - { - // size of source is unknown, read all of it into memory - String contents = sourceStream->getAsString(); - mSize = contents.size(); - mData = OGRE_ALLOC_T(uchar, mSize, MEMCATEGORY_GENERAL); - mPos = mData; - memcpy(mData, contents.data(), mSize); - mEnd = mData + mSize; - } - else - { - mData = OGRE_ALLOC_T(uchar, mSize, MEMCATEGORY_GENERAL); - mPos = mData; - mEnd = mData + sourceStream->read(mData, mSize); - } - mFreeOnClose = freeOnClose; - assert(mEnd >= mPos); - } - //----------------------------------------------------------------------- - MemoryDataStream::MemoryDataStream(size_t inSize, bool freeOnClose, bool readOnly) - : DataStream(static_cast(readOnly ? READ : (READ | WRITE))) - { - mSize = inSize; - mData = OGRE_ALLOC_T(uchar, mSize, MEMCATEGORY_GENERAL); - mPos = mData; - mEnd = mData + mSize; - mFreeOnClose = freeOnClose; - assert(mEnd >= mPos); - } - //----------------------------------------------------------------------- - MemoryDataStream::MemoryDataStream(const String& name, size_t inSize, - bool freeOnClose, bool readOnly) - : DataStream(name, static_cast(readOnly ? READ : (READ | WRITE))) - { - mSize = inSize; - mData = OGRE_ALLOC_T(uchar, mSize, MEMCATEGORY_GENERAL); - mPos = mData; - mEnd = mData + mSize; - mFreeOnClose = freeOnClose; - assert(mEnd >= mPos); - } - //----------------------------------------------------------------------- - MemoryDataStream::~MemoryDataStream() - { - close(); - } - //----------------------------------------------------------------------- - size_t MemoryDataStream::read(void* buf, size_t count) - { - size_t cnt = count; - // Read over end of memory? - if (mPos + cnt > mEnd) - cnt = mEnd - mPos; - if (cnt == 0) - return 0; - - assert (cnt<=count); - - memcpy(buf, mPos, cnt); - mPos += cnt; - return cnt; - } - //--------------------------------------------------------------------- - size_t MemoryDataStream::write(const void* buf, size_t count) - { - size_t written = 0; - if (isWriteable()) - { - written = count; - // we only allow writing within the extents of allocated memory - // check for buffer overrun & disallow - if (mPos + written > mEnd) - written = mEnd - mPos; - if (written == 0) - return 0; - - memcpy(mPos, buf, written); - mPos += written; - } - return written; - } - //----------------------------------------------------------------------- - size_t MemoryDataStream::readLine(char* buf, size_t maxCount, - const String& delim) - { - // Deal with both Unix & Windows LFs - bool trimCR = false; - if (delim.find_first_of('\n') != String::npos) - { - trimCR = true; - } - - size_t pos = 0; - - // Make sure pos can never go past the end of the data - while (pos < maxCount && mPos < mEnd) - { - if (delim.find(*mPos) != String::npos) - { - // Trim off trailing CR if this was a CR/LF entry - if (trimCR && pos && buf[pos-1] == '\r') - { - // terminate 1 character early - --pos; - } - - // Found terminator, skip and break out - ++mPos; - break; - } - - buf[pos++] = *mPos++; - } - - // terminate - buf[pos] = '\0'; - - return pos; - } - //----------------------------------------------------------------------- - size_t MemoryDataStream::skipLine(const String& delim) - { - size_t pos = 0; - - // Make sure pos can never go past the end of the data - while (mPos < mEnd) - { - ++pos; - if (delim.find(*mPos++) != String::npos) - { - // Found terminator, break out - break; - } - } - - return pos; - - } - //----------------------------------------------------------------------- - void MemoryDataStream::skip(long count) - { - size_t newpos = (size_t)( ( mPos - mData ) + count ); - assert( mData + newpos <= mEnd ); - - mPos = mData + newpos; - } - //----------------------------------------------------------------------- - void MemoryDataStream::seek( size_t pos ) - { - assert( mData + pos <= mEnd ); - mPos = mData + pos; - } - //----------------------------------------------------------------------- - size_t MemoryDataStream::tell(void) const - { - //mData is start, mPos is current location - return mPos - mData; - } - //----------------------------------------------------------------------- - bool MemoryDataStream::eof(void) const - { - return mPos >= mEnd; - } - //----------------------------------------------------------------------- - void MemoryDataStream::close(void) - { - mAccess = 0; - if (mFreeOnClose && mData) - { - OGRE_FREE(mData, MEMCATEGORY_GENERAL); - mData = 0; - } - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - FileStreamDataStream::FileStreamDataStream(std::ifstream* s, bool freeOnClose) - : DataStream(), mInStream(s), mFStreamRO(s), mFStream(0), mFreeOnClose(freeOnClose) - { - // calculate the size - mInStream->seekg(0, std::ios_base::end); - mSize = (size_t)mInStream->tellg(); - mInStream->seekg(0, std::ios_base::beg); - determineAccess(); - } - //----------------------------------------------------------------------- - FileStreamDataStream::FileStreamDataStream(const String& name, - std::ifstream* s, bool freeOnClose) - : DataStream(name), mInStream(s), mFStreamRO(s), mFStream(0), mFreeOnClose(freeOnClose) - { - // calculate the size - mInStream->seekg(0, std::ios_base::end); - mSize = (size_t)mInStream->tellg(); - mInStream->seekg(0, std::ios_base::beg); - determineAccess(); - } - //----------------------------------------------------------------------- - FileStreamDataStream::FileStreamDataStream(const String& name, - std::ifstream* s, size_t inSize, bool freeOnClose) - : DataStream(name), mInStream(s), mFStreamRO(s), mFStream(0), mFreeOnClose(freeOnClose) - { - // Size is passed in - mSize = inSize; - determineAccess(); - } - //--------------------------------------------------------------------- - FileStreamDataStream::FileStreamDataStream(std::fstream* s, bool freeOnClose) - : DataStream(false), mInStream(s), mFStreamRO(0), mFStream(s), mFreeOnClose(freeOnClose) - { - // writeable! - // calculate the size - mInStream->seekg(0, std::ios_base::end); - mSize = (size_t)mInStream->tellg(); - mInStream->seekg(0, std::ios_base::beg); - determineAccess(); - - } - //----------------------------------------------------------------------- - FileStreamDataStream::FileStreamDataStream(const String& name, - std::fstream* s, bool freeOnClose) - : DataStream(name, false), mInStream(s), mFStreamRO(0), mFStream(s), mFreeOnClose(freeOnClose) - { - // writeable! - // calculate the size - mInStream->seekg(0, std::ios_base::end); - mSize = (size_t)mInStream->tellg(); - mInStream->seekg(0, std::ios_base::beg); - determineAccess(); - } - //----------------------------------------------------------------------- - FileStreamDataStream::FileStreamDataStream(const String& name, - std::fstream* s, size_t inSize, bool freeOnClose) - : DataStream(name, false), mInStream(s), mFStreamRO(0), mFStream(s), mFreeOnClose(freeOnClose) - { - // writeable! - // Size is passed in - mSize = inSize; - determineAccess(); - } - //--------------------------------------------------------------------- - void FileStreamDataStream::determineAccess() - { - mAccess = 0; - if (mInStream) - mAccess |= READ; - if (mFStream) - mAccess |= WRITE; - } - //----------------------------------------------------------------------- - FileStreamDataStream::~FileStreamDataStream() - { - close(); - } - //----------------------------------------------------------------------- - size_t FileStreamDataStream::read(void* buf, size_t count) - { - mInStream->read(static_cast(buf), static_cast(count)); - return (size_t)mInStream->gcount(); - } - //----------------------------------------------------------------------- - size_t FileStreamDataStream::write(const void* buf, size_t count) - { - size_t written = 0; - if (isWriteable() && mFStream) - { - mFStream->write(static_cast(buf), static_cast(count)); - written = count; - } - return written; - } - //----------------------------------------------------------------------- - size_t FileStreamDataStream::readLine(char* buf, size_t maxCount, - const String& delim) - { - if (delim.empty()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "No delimiter provided", - "FileStreamDataStream::readLine"); - } - if (delim.size() > 1) - { - LogManager::getSingleton().logWarning( - "FileStreamDataStream::readLine - using only first delimiter"); - } - // Deal with both Unix & Windows LFs - bool trimCR = false; - if (delim.at(0) == '\n') - { - trimCR = true; - } - // maxCount + 1 since count excludes terminator in getline - mInStream->getline(buf, static_cast(maxCount+1), delim.at(0)); - size_t ret = (size_t)mInStream->gcount(); - // three options - // 1) we had an eof before we read a whole line - // 2) we ran out of buffer space - // 3) we read a whole line - in this case the delim character is taken from the stream but not written in the buffer so the read data is of length ret-1 and thus ends at index ret-2 - // in all cases the buffer will be null terminated for us - - if (mInStream->eof()) - { - // no problem - } - else if (mInStream->fail()) - { - // Did we fail because of maxCount hit? No - no terminating character - // in included in the count in this case - if (ret == maxCount) - { - // clear failbit for next time - mInStream->clear(); - } - else - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Streaming error occurred", - "FileStreamDataStream::readLine"); - } - } - else - { - // we need to adjust ret because we want to use it as a - // pointer to the terminating null character and it is - // currently the length of the data read from the stream - // i.e. 1 more than the length of the data in the buffer and - // hence 1 more than the _index_ of the NULL character - --ret; - } - - // trim off CR if we found CR/LF - if (trimCR && ret && buf[ret-1] == '\r') - { - --ret; - buf[ret] = '\0'; - } - return ret; - } - //----------------------------------------------------------------------- - void FileStreamDataStream::skip(long count) - { -#if defined(STLPORT) - // Workaround for STLport issues: After reached eof of file stream, - // it's seems the stream was putted in intermediate state, and will be - // fail if try to repositioning relative to current position. - // Note: tellg() fail in this case too. - if (mInStream->eof()) - { - mInStream->clear(); - // Use seek relative to either begin or end to bring the stream - // back to normal state. - mInStream->seekg(0, std::ios::end); - } -#endif - mInStream->clear(); //Clear fail status in case eof was set - mInStream->seekg(static_cast(count), std::ios::cur); - } - //----------------------------------------------------------------------- - void FileStreamDataStream::seek( size_t pos ) - { - mInStream->clear(); //Clear fail status in case eof was set - mInStream->seekg(static_cast(pos), std::ios::beg); - } - //----------------------------------------------------------------------- - size_t FileStreamDataStream::tell(void) const - { - mInStream->clear(); //Clear fail status in case eof was set - return (size_t)mInStream->tellg(); - } - //----------------------------------------------------------------------- - bool FileStreamDataStream::eof(void) const - { - return mInStream->eof(); - } - //----------------------------------------------------------------------- - void FileStreamDataStream::close(void) - { - mAccess = 0; - if (mInStream) - { - // Unfortunately, there is no file-specific shared class hierarchy between fstream and ifstream (!!) - if (mFStreamRO) - mFStreamRO->close(); - if (mFStream) - { - mFStream->flush(); - mFStream->close(); - } - - if (mFreeOnClose) - { - // delete the stream too - OGRE_DELETE_T(mFStreamRO, basic_ifstream, MEMCATEGORY_GENERAL); - OGRE_DELETE_T(mFStream, basic_fstream, MEMCATEGORY_GENERAL); - } - - mInStream = 0; - mFStreamRO = 0; - mFStream = 0; - } - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - FileHandleDataStream::FileHandleDataStream(FILE* handle, uint16 accessMode) - : DataStream(accessMode), mFileHandle(handle) - { - // Determine size - fseek(mFileHandle, 0, SEEK_END); - mSize = ftell(mFileHandle); - fseek(mFileHandle, 0, SEEK_SET); - } - //----------------------------------------------------------------------- - FileHandleDataStream::FileHandleDataStream(const String& name, FILE* handle, uint16 accessMode) - : DataStream(name, accessMode), mFileHandle(handle) - { - // Determine size - fseek(mFileHandle, 0, SEEK_END); - mSize = ftell(mFileHandle); - fseek(mFileHandle, 0, SEEK_SET); - } - //----------------------------------------------------------------------- - FileHandleDataStream::~FileHandleDataStream() - { - close(); - } - //----------------------------------------------------------------------- - size_t FileHandleDataStream::read(void* buf, size_t count) - { - return fread(buf, 1, count, mFileHandle); - } - //----------------------------------------------------------------------- - size_t FileHandleDataStream::write(const void* buf, size_t count) - { - if (!isWriteable()) - return 0; - else - return fwrite(buf, 1, count, mFileHandle); - } - //--------------------------------------------------------------------- - //----------------------------------------------------------------------- - void FileHandleDataStream::skip(long count) - { - fseek(mFileHandle, count, SEEK_CUR); - } - //----------------------------------------------------------------------- - void FileHandleDataStream::seek( size_t pos ) - { - fseek(mFileHandle, static_cast(pos), SEEK_SET); - } - //----------------------------------------------------------------------- - size_t FileHandleDataStream::tell(void) const - { - return ftell( mFileHandle ); - } - //----------------------------------------------------------------------- - bool FileHandleDataStream::eof(void) const - { - return feof(mFileHandle) != 0; - } - //----------------------------------------------------------------------- - void FileHandleDataStream::close(void) - { - mAccess = 0; - if (mFileHandle != 0) - { - fclose(mFileHandle); - mFileHandle = 0; - } - } - //----------------------------------------------------------------------- - -} diff --git a/OgreMain/src/OgreDefaultDebugDrawer.cpp b/OgreMain/src/OgreDefaultDebugDrawer.cpp deleted file mode 100644 index 06387dae090..00000000000 --- a/OgreMain/src/OgreDefaultDebugDrawer.cpp +++ /dev/null @@ -1,200 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. - -#include "OgreDefaultDebugDrawer.h" -#include "OgreStableHeaders.h" - -namespace Ogre -{ - -DefaultDebugDrawer::DefaultDebugDrawer() : mLines(""), mAxes(""), mDrawType(0), mStatic(false), mBoneAxesSize(1.0f) {} - -void DefaultDebugDrawer::preFindVisibleObjects(SceneManager* source, - SceneManager::IlluminationRenderStage irs, Viewport* v) -{ - mDrawType = 0; - - if (source->getDisplaySceneNodes()) - mDrawType |= DT_AXES; - if (source->getShowBoundingBoxes()) - mDrawType |= DT_WIREBOX; -} -void DefaultDebugDrawer::beginLines() -{ - if (mLines.getSections().empty()) - { - const char* matName = "Ogre/Debug/LinesMat"; - auto mat = MaterialManager::getSingleton().getByName(matName, RGN_INTERNAL); - if (!mat) - { - mat = MaterialManager::getSingleton().create(matName, RGN_INTERNAL); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->setVertexColourTracking(TVC_AMBIENT); - } - mLines.setBufferUsage(HBU_CPU_TO_GPU); - mLines.begin(mat, RenderOperation::OT_LINE_LIST); - } - else if (mLines.getCurrentVertexCount() == 0) - mLines.beginUpdate(0); -} -void DefaultDebugDrawer::drawWireBox(const AxisAlignedBox& aabb, const ColourValue& colour) -{ - beginLines(); - - int base = mLines.getCurrentVertexCount(); - for (const auto& corner : aabb.getAllCorners()) - { - mLines.position(corner); - mLines.colour(colour); - } - // see AxisAlignedBox::getAllCorners - int idx[] = {0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 6, 1, 5, 2, 4, 3, 7}; - for (int i : idx) - mLines.index(base + i); -} -void DefaultDebugDrawer::drawFrustum(const Frustum* frust) -{ - beginLines(); - - int base = mLines.getCurrentVertexCount(); - for (const auto& corner : frust->getWorldSpaceCorners()) - { - mLines.position(corner); - mLines.colour(frust->getDebugColour()); - } - // see ConvexBody::define - int idx[] = {0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 2, 6, 1, 5, 0, 4, 3, 7}; - for (int i : idx) - mLines.index(base + i); -} -void DefaultDebugDrawer::drawAxes(const Affine3& pose, float size) -{ - if (mAxes.getSections().empty()) - { - const char* matName = "Ogre/Debug/AxesMat"; - auto mat = MaterialManager::getSingleton().getByName(matName, RGN_INTERNAL); - if (!mat) - { - mat = MaterialManager::getSingleton().create(matName, RGN_INTERNAL); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->setPolygonModeOverrideable(false); - p->setVertexColourTracking(TVC_AMBIENT); - p->setSceneBlending(SBT_TRANSPARENT_ALPHA); - p->setCullingMode(CULL_NONE); - p->setDepthWriteEnabled(false); - p->setDepthCheckEnabled(false); - } - - mAxes.setBufferUsage(HBU_CPU_TO_GPU); - mAxes.begin(mat); - } - else if (mAxes.getCurrentVertexCount() == 0) - mAxes.beginUpdate(0); - - /* 3 axes, each made up of 2 of these (base plane = XY) - * .------------|\ - * '------------|/ - */ - Vector3 basepos[7] = - { - // stalk - Vector3(0, 0.05, 0), - Vector3(0, -0.05, 0), - Vector3(0.7, -0.05, 0), - Vector3(0.7, 0.05, 0), - // head - Vector3(0.7, -0.15, 0), - Vector3(1, 0, 0), - Vector3(0.7, 0.15, 0) - }; - - ColourValue col[3] = {ColourValue(1, 0, 0, 0.8), ColourValue(0, 1, 0, 0.8), ColourValue(0, 0, 1, 0.8)}; - - Matrix3 rot[6]; - - // x-axis - rot[0] = Matrix3::IDENTITY; - rot[1].FromAxes(Vector3::UNIT_X, Vector3::NEGATIVE_UNIT_Z, Vector3::UNIT_Y); - // y-axis - rot[2].FromAxes(Vector3::UNIT_Y, Vector3::NEGATIVE_UNIT_X, Vector3::UNIT_Z); - rot[3].FromAxes(Vector3::UNIT_Y, Vector3::UNIT_Z, Vector3::UNIT_X); - // z-axis - rot[4].FromAxes(Vector3::UNIT_Z, Vector3::UNIT_Y, Vector3::NEGATIVE_UNIT_X); - rot[5].FromAxes(Vector3::UNIT_Z, Vector3::UNIT_X, Vector3::UNIT_Y); - - // 6 arrows - for (size_t i = 0; i < 6; ++i) - { - uint32 base = mAxes.getCurrentVertexCount(); - // vertices - for (const auto& p : basepos) - { - mAxes.position(pose * (rot[i] * p * size)); - mAxes.colour(col[i / 2]); - } - - // indices - mAxes.quad(base + 0, base + 1, base + 2, base + 3); - mAxes.triangle(base + 4, base + 5, base + 6); - } -} -void DefaultDebugDrawer::setBoneAxesSize(float size) -{ - mBoneAxesSize = size; -} -void DefaultDebugDrawer::drawBone(const Node* node, const Affine3 & transform) -{ - drawAxes(transform * node->_getFullTransform(), mBoneAxesSize); -} -void DefaultDebugDrawer::drawSceneNode(const SceneNode* node) -{ - // skip drawing root scene node as it contains the camera frustum - if(!node->getParent()) - return; - - const auto& aabb = node->_getWorldAABB(); - //Skip all bounding boxes that are infinite. - if (aabb.isInfinite()) { - return; - } - if (mDrawType & DT_AXES) - { - // remove scale here as it will be in full transform below too - Vector3f hs(aabb.getHalfSize() / node->_getDerivedScale()); - float sz = std::min(hs[0], hs[1]); - sz = std::min(sz, hs[2]); - sz = std::max(sz, 1.0f); - drawAxes(node->_getFullTransform(), sz); - } - - if (node->getShowBoundingBox() || (mDrawType & DT_WIREBOX)) - { - drawWireBox(aabb); - } -} -void DefaultDebugDrawer::postFindVisibleObjects(SceneManager* source, - SceneManager::IlluminationRenderStage irs, Viewport* v) -{ - auto queue = source->getRenderQueue(); - if (mLines.getCurrentVertexCount()) - { - mLines.end(); - mLines._updateRenderQueue(queue); - } - if (mAxes.getCurrentVertexCount()) - { - mAxes.end(); - mAxes._updateRenderQueue(queue); - } - - if (mStatic) - { - mLines._updateRenderQueue(queue); - mAxes._updateRenderQueue(queue); - } -} - -} /* namespace Ogre */ diff --git a/OgreMain/src/OgreDefaultHardwareBufferManager.cpp b/OgreMain/src/OgreDefaultHardwareBufferManager.cpp deleted file mode 100644 index 0a439d8f67d..00000000000 --- a/OgreMain/src/OgreDefaultHardwareBufferManager.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreDefaultHardwareBufferManager.h" - -namespace Ogre { - - DefaultHardwareBuffer::DefaultHardwareBuffer(size_t sizeInBytes) - : HardwareBuffer(HBU_CPU_ONLY, false) // always software, never shadowed - { - mSizeInBytes = sizeInBytes; - // Allocate aligned memory for better SIMD processing friendly. - mData = (uchar*)AlignedMemory::allocate(mSizeInBytes); - } - //----------------------------------------------------------------------- - DefaultHardwareBuffer::~DefaultHardwareBuffer() - { - AlignedMemory::deallocate(mData); - } - //----------------------------------------------------------------------- - void* DefaultHardwareBuffer::lockImpl(size_t offset, size_t length, LockOptions options) - { - // Only for use internally, no 'locking' as such - return mData + offset; - } - //----------------------------------------------------------------------- - void DefaultHardwareBuffer::unlockImpl(void) - { - // Nothing to do - } - //----------------------------------------------------------------------- - void DefaultHardwareBuffer::readData(size_t offset, size_t length, void* pDest) - { - assert((offset + length) <= mSizeInBytes); - memcpy(pDest, mData + offset, length); - } - //----------------------------------------------------------------------- - void DefaultHardwareBuffer::writeData(size_t offset, size_t length, const void* pSource, - bool discardWholeBuffer) - { - assert((offset + length) <= mSizeInBytes); - // ignore discard, memory is not guaranteed to be zeroised - memcpy(mData + offset, pSource, length); - } - //----------------------------------------------------------------------- - DefaultHardwareBufferManagerBase::DefaultHardwareBufferManagerBase() - { - } - //----------------------------------------------------------------------- - DefaultHardwareBufferManagerBase::~DefaultHardwareBufferManagerBase() - { - destroyAllDeclarations(); - destroyAllBindings(); - } - //----------------------------------------------------------------------- - HardwareVertexBufferSharedPtr - DefaultHardwareBufferManagerBase::createVertexBuffer(size_t vertexSize, - size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer) - { - return std::make_shared(this, vertexSize, numVerts, - new DefaultHardwareBuffer(vertexSize * numVerts)); - } - //----------------------------------------------------------------------- - HardwareIndexBufferSharedPtr - DefaultHardwareBufferManagerBase::createIndexBuffer(HardwareIndexBuffer::IndexType itype, - size_t numIndexes, HardwareBuffer::Usage usage, bool useShadowBuffer) - { - return std::make_shared( - this, itype, numIndexes, - new DefaultHardwareBuffer(HardwareIndexBuffer::indexSize(itype) * numIndexes)); - } -} diff --git a/OgreMain/src/OgreDefaultSceneQueries.cpp b/OgreMain/src/OgreDefaultSceneQueries.cpp deleted file mode 100644 index c4304a8ce17..00000000000 --- a/OgreMain/src/OgreDefaultSceneQueries.cpp +++ /dev/null @@ -1,254 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -namespace Ogre { - //--------------------------------------------------------------------- - DefaultIntersectionSceneQuery::DefaultIntersectionSceneQuery(SceneManager* creator) - : IntersectionSceneQuery(creator) - { - } - //--------------------------------------------------------------------- - DefaultIntersectionSceneQuery::~DefaultIntersectionSceneQuery() - { - } - //--------------------------------------------------------------------- - void DefaultIntersectionSceneQuery::execute(IntersectionSceneQueryListener* listener) - { - // Iterate over all movable types - const auto& factories = Root::getSingleton().getMovableObjectFactories(); - auto factIt = factories.begin(); - while(factIt != factories.end()) - { - const auto& objsA = mParentSceneMgr->getMovableObjects((factIt++)->first); - auto objItA = objsA.begin(); - while (objItA != objsA.end()) - { - MovableObject* a = (objItA++)->second; - // skip entire section if type doesn't match - if (!(a->getTypeFlags() & mQueryTypeMask)) - break; - - // Skip if a does not pass the mask - if (!(a->getQueryFlags() & mQueryMask) || !a->isInScene()) - continue; - - // Check against later objects in the same group - auto objItB = objItA; - while (objItB != objsA.end()) - { - MovableObject* b = (objItB++)->second; - - // Apply mask to b (both must pass) - if ((b->getQueryFlags() & mQueryMask) && b->isInScene()) - { - const AxisAlignedBox& box1 = a->getWorldBoundingBox(); - const AxisAlignedBox& box2 = b->getWorldBoundingBox(); - - if (box1.intersects(box2)) - { - if (!listener->queryResult(a, b)) return; - } - } - } - // Check against later groups - auto factItLater = factIt; - while (factItLater != factories.end()) - { - for (const auto& objItC : - mParentSceneMgr->getMovableObjects((factItLater++)->first)) - { - MovableObject* c = objItC.second; - // skip entire section if type doesn't match - if (!(c->getTypeFlags() & mQueryTypeMask)) - break; - - // Apply mask to c (both must pass) - if ((c->getQueryFlags() & mQueryMask) && c->isInScene()) - { - const AxisAlignedBox& box1 = a->getWorldBoundingBox(); - const AxisAlignedBox& box2 = c->getWorldBoundingBox(); - - if (box1.intersects(box2)) - { - if (!listener->queryResult(a, c)) return; - } - } - } - - } - - } - - - } - - } - //--------------------------------------------------------------------- - DefaultAxisAlignedBoxSceneQuery:: - DefaultAxisAlignedBoxSceneQuery(SceneManager* creator) - : AxisAlignedBoxSceneQuery(creator) - { - } - //--------------------------------------------------------------------- - DefaultAxisAlignedBoxSceneQuery::~DefaultAxisAlignedBoxSceneQuery() - { - } - //--------------------------------------------------------------------- - void DefaultAxisAlignedBoxSceneQuery::execute(SceneQueryListener* listener) - { - // Iterate over all movable types - for(const auto& factIt : Root::getSingleton().getMovableObjectFactories()) - { - for (const auto& objIt : mParentSceneMgr->getMovableObjects(factIt.first)) - { - MovableObject* a = objIt.second; - // skip whole group if type doesn't match - if (!(a->getTypeFlags() & mQueryTypeMask)) - break; - - if ((a->getQueryFlags() & mQueryMask) && a->isInScene() && - mAABB.intersects(a->getWorldBoundingBox())) - { - if (!listener->queryResult(a)) return; - } - } - } - } - //--------------------------------------------------------------------- - DefaultRaySceneQuery:: - DefaultRaySceneQuery(SceneManager* creator) : RaySceneQuery(creator) - { - } - //--------------------------------------------------------------------- - DefaultRaySceneQuery::~DefaultRaySceneQuery() - { - } - //--------------------------------------------------------------------- - void DefaultRaySceneQuery::execute(RaySceneQueryListener* listener) - { - // Note that because we have no scene partitioning, we actually - // perform a complete scene search even if restricted results are - // requested; smarter scene manager queries can utilise the paritioning - // of the scene in order to reduce the number of intersection tests - // required to fulfil the query - - // Iterate over all movable types - for(const auto& factIt : Root::getSingleton().getMovableObjectFactories()) - { - for (const auto& objIt : mParentSceneMgr->getMovableObjects(factIt.first)) - { - MovableObject* a = objIt.second; - // skip whole group if type doesn't match - if (!(a->getTypeFlags() & mQueryTypeMask)) - break; - - if ((a->getQueryFlags() & mQueryMask) && a->isInScene()) - { - // Do ray / box test - std::pair result = mRay.intersects(a->getWorldBoundingBox()); - - if (result.first) - { - if (!listener->queryResult(a, result.second)) return; - } - } - } - } - - } - //--------------------------------------------------------------------- - DefaultSphereSceneQuery:: - DefaultSphereSceneQuery(SceneManager* creator) : SphereSceneQuery(creator) - { - } - //--------------------------------------------------------------------- - DefaultSphereSceneQuery::~DefaultSphereSceneQuery() - { - } - //--------------------------------------------------------------------- - void DefaultSphereSceneQuery::execute(SceneQueryListener* listener) - { - // Iterate over all movable types - for(const auto& factIt : Root::getSingleton().getMovableObjectFactories()) - { - for (const auto& objIt : mParentSceneMgr->getMovableObjects(factIt.first)) - { - MovableObject* a = objIt.second; - // skip whole group if type doesn't match - if (!(a->getTypeFlags() & mQueryTypeMask)) - break; - // Skip unattached - if (!a->isInScene() || !(a->getQueryFlags() & mQueryMask)) - continue; - - // Do sphere / sphere test - if (mSphere.intersects(a->getWorldBoundingSphere())) - { - if (!listener->queryResult(a)) return; - } - } - } - } - //--------------------------------------------------------------------- - DefaultPlaneBoundedVolumeListSceneQuery:: - DefaultPlaneBoundedVolumeListSceneQuery(SceneManager* creator) - : PlaneBoundedVolumeListSceneQuery(creator) - { - } - //--------------------------------------------------------------------- - DefaultPlaneBoundedVolumeListSceneQuery::~DefaultPlaneBoundedVolumeListSceneQuery() - { - } - //--------------------------------------------------------------------- - void DefaultPlaneBoundedVolumeListSceneQuery::execute(SceneQueryListener* listener) - { - // Iterate over all movable types - for(const auto& factIt : Root::getSingleton().getMovableObjectFactories()) - { - for (const auto& objIt : mParentSceneMgr->getMovableObjects(factIt.first)) - { - MovableObject* a = objIt.second; - // skip whole group if type doesn't match - if (!(a->getTypeFlags() & mQueryTypeMask)) - break; - - for (const auto& vol : mVolumes) - { - // Do AABB / plane volume test - if ((a->getQueryFlags() & mQueryMask) && a->isInScene() && - vol.intersects(a->getWorldBoundingBox())) - { - if (!listener->queryResult(a)) return; - break; - } - } - } - } - } -} diff --git a/OgreMain/src/OgreDefaultWorkQueueStandard.cpp b/OgreMain/src/OgreDefaultWorkQueueStandard.cpp deleted file mode 100644 index 96dbd0a16e6..00000000000 --- a/OgreMain/src/OgreDefaultWorkQueueStandard.cpp +++ /dev/null @@ -1,178 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - DefaultWorkQueue::DefaultWorkQueue(const String& name) - : DefaultWorkQueueBase(name), mNumThreadsRegisteredWithRS(0) - { - } - //--------------------------------------------------------------------- - DefaultWorkQueue::~DefaultWorkQueue() - { - shutdown(); - } - //--------------------------------------------------------------------- - void DefaultWorkQueue::startup(bool forceRestart) - { - if (mIsRunning) - { - if (forceRestart) - shutdown(); - else - return; - } - - mShuttingDown = false; - - LogManager::getSingleton().stream() << - "DefaultWorkQueue('" << mName << "') initialising on thread " << - OGRE_THREAD_CURRENT_ID - << "."; - -#if OGRE_THREAD_SUPPORT - if (mWorkerRenderSystemAccess) - Root::getSingleton().getRenderSystem()->preExtraThreadsStarted(); - - mNumThreadsRegisteredWithRS = 0; - for (size_t i = 0; i < mWorkerThreadCount; ++i) - { - OGRE_THREAD_CREATE(t, [this]() { _threadMain(); }); - mWorkers.push_back(t); - } - - if (mWorkerRenderSystemAccess) - { - OGRE_WQ_LOCK_MUTEX_NAMED(mInitMutex, initLock); - // have to wait until all threads are registered with the render system - while (mNumThreadsRegisteredWithRS < mWorkerThreadCount) - OGRE_THREAD_WAIT(mInitSync, mInitMutex, initLock); - - Root::getSingleton().getRenderSystem()->postExtraThreadsStarted(); - - } -#endif - - mIsRunning = true; - } - //--------------------------------------------------------------------- - void DefaultWorkQueue::notifyThreadRegistered() - { - OGRE_WQ_LOCK_MUTEX(mInitMutex); - - ++mNumThreadsRegisteredWithRS; - - // wake up main thread - OGRE_THREAD_NOTIFY_ALL(mInitSync); - - } - //--------------------------------------------------------------------- - void DefaultWorkQueue::shutdown() - { - if( !mIsRunning ) - return; - - LogManager::getSingleton().stream() << - "DefaultWorkQueue('" << mName << "') shutting down on thread " << - OGRE_THREAD_CURRENT_ID - << "."; - - mShuttingDown = true; - -#if OGRE_THREAD_SUPPORT - // wake all threads (they should check shutting down as first thing after wait) - OGRE_THREAD_NOTIFY_ALL(mRequestCondition); - - // all our threads should have been woken now, so join - for (WorkerThreadList::iterator i = mWorkers.begin(); i != mWorkers.end(); ++i) - { - (*i)->join(); - OGRE_THREAD_DESTROY(*i); - } - mWorkers.clear(); -#endif - - mIsRunning = false; - } - //--------------------------------------------------------------------- - void DefaultWorkQueue::notifyWorkers() - { - // wake up waiting thread - OGRE_THREAD_NOTIFY_ONE(mRequestCondition); - } - - //--------------------------------------------------------------------- - void DefaultWorkQueue::waitForNextRequest() - { -#if OGRE_THREAD_SUPPORT - // Lock; note that OGRE_THREAD_WAIT will free the lock - OGRE_WQ_LOCK_MUTEX_NAMED(mRequestMutex, queueLock); - if (mTasks.empty()) - { - // frees lock and suspends the thread - OGRE_THREAD_WAIT(mRequestCondition, mRequestMutex, queueLock); - } - // When we get back here, it's because we've been notified - // and thus the thread has been woken up. Lock has also been - // re-acquired, but we won't use it. It's safe to try processing and fail - // if another thread has got in first and grabbed the request -#endif - - } - //--------------------------------------------------------------------- - void DefaultWorkQueue::_threadMain() - { - // default worker thread -#if OGRE_THREAD_SUPPORT - LogManager::getSingleton().stream() << - "DefaultWorkQueue('" << getName() << "')::WorkerFunc - thread " - << OGRE_THREAD_CURRENT_ID << " starting."; - - // Initialise the thread for RS if necessary - if (mWorkerRenderSystemAccess) - { - Root::getSingleton().getRenderSystem()->registerThread(); - notifyThreadRegistered(); - } - - // Spin forever until we're told to shut down - while (!isShuttingDown()) - { - waitForNextRequest(); - _processNextRequest(); - } - - LogManager::getSingleton().stream() << - "DefaultWorkQueue('" << getName() << "')::WorkerFunc - thread " - << OGRE_THREAD_CURRENT_ID << " stopped."; -#endif - } - -} diff --git a/OgreMain/src/OgreDeflate.cpp b/OgreMain/src/OgreDeflate.cpp deleted file mode 100644 index 3fe981e885b..00000000000 --- a/OgreMain/src/OgreDeflate.cpp +++ /dev/null @@ -1,463 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#include "OgreStableHeaders.h" - -#if OGRE_NO_ZIP_ARCHIVE == 0 - -#include "OgreDeflate.h" -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS || OGRE_PLATFORM == OGRE_PLATFORM_APPLE -#include "macUtils.h" -#endif - -#define MINIZ_HEADER_FILE_ONLY -#include - -namespace Ogre -{ - // memory implementations - static void* OgreZalloc(void* opaque, size_t items, size_t size) - { - return OGRE_MALLOC(items * size, MEMCATEGORY_GENERAL); - } - static void OgreZfree(void* opaque, void* address) - { - OGRE_FREE(address, MEMCATEGORY_GENERAL); - } - #define OGRE_DEFLATE_TMP_SIZE 16384 - //--------------------------------------------------------------------- - DeflateStream::DeflateStream(const DataStreamPtr& compressedStream, const String& tmpFileName, size_t avail_in) - : DataStream(compressedStream->getAccessMode()) - , mCompressedStream(compressedStream) - , mTempFileName(tmpFileName) - , mZStream(0) - , mCurrentPos(0) - , mAvailIn(avail_in) - , mTmp(0) - , mStreamType(ZLib) - { - init(); - } - //--------------------------------------------------------------------- - DeflateStream::DeflateStream(const String& name, const DataStreamPtr& compressedStream, const String& tmpFileName, size_t avail_in) - : DataStream(name, compressedStream->getAccessMode()) - , mCompressedStream(compressedStream) - , mTempFileName(tmpFileName) - , mZStream(0) - , mCurrentPos(0) - , mAvailIn(avail_in) - , mTmp(0) - , mStreamType(ZLib) - { - init(); - } - //--------------------------------------------------------------------- - DeflateStream::DeflateStream(const String& name, const DataStreamPtr& compressedStream, StreamType streamType, const String& tmpFileName, size_t avail_in) - : DataStream(name, compressedStream->getAccessMode()) - , mCompressedStream(compressedStream) - , mTempFileName(tmpFileName) - , mZStream(0) - , mCurrentPos(0) - , mAvailIn(avail_in) - , mTmp(0) - , mStreamType(streamType) - { - init(); - } - //--------------------------------------------------------------------- - size_t DeflateStream::getAvailInForSinglePass() - { - size_t ret = OGRE_DEFLATE_TMP_SIZE; - - // if we are doing particial-uncompressing - if(mAvailIn>0) - { - if(mAvailInzalloc = OgreZalloc; - mZStream->zfree = OgreZfree; - - if (getAccessMode() == READ) - { - mTmp = (unsigned char*)OGRE_MALLOC(OGRE_DEFLATE_TMP_SIZE, MEMCATEGORY_GENERAL); - size_t restorePoint = mCompressedStream->tell(); - // read early chunk - mZStream->next_in = mTmp; - mZStream->avail_in = static_cast(mCompressedStream->read(mTmp, getAvailInForSinglePass())); - - int windowBits = (mStreamType == Deflate) ? -MAX_WBITS : (mStreamType == GZip) ? 16 + MAX_WBITS : MAX_WBITS; - if (inflateInit2(mZStream, windowBits) != Z_OK) - { - mStreamType = Invalid; - } - - if (mStreamType != Invalid) - { - // in fact, inflateInit on some implementations doesn't try to read - // anything. We need to at least read something to test - Bytef testOut[4]; - size_t savedIn = mZStream->avail_in; - mZStream->avail_out = 4; - mZStream->next_out = testOut; - if (inflate(mZStream, Z_SYNC_FLUSH) != Z_OK) - mStreamType = Invalid; - // restore for reading - mZStream->avail_in = static_cast(savedIn); - mZStream->next_in = mTmp; - - inflateReset(mZStream); - } - - if (mStreamType == Invalid) - { - // Not compressed data! - // Fail gracefully, fall back on reading the underlying stream direct - destroy(); - mCompressedStream->seek(restorePoint); - } - } - else - { - if(mTempFileName.empty()) - { - // Write to temp file -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT - char* tmpname = _tempnam(".", "ogre"); - if (!tmpname) - { - // Having no file name here will cause various problems later. - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Temporary file name generation failed.", "DeflateStream::init"); - } - else - { - mTempFileName = tmpname; - free(tmpname); - } -#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS || OGRE_PLATFORM == OGRE_PLATFORM_APPLE - mTempFileName = macTempFileName(); -#else - char tmpname[] = "/tmp/ogreXXXXXX"; - if (mkstemp(tmpname) == -1) - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Temporary file name generation failed.", "DeflateStream::init"); - - mTempFileName = tmpname; -#endif - } - - mTmpWriteStream = _openFileStream(mTempFileName, std::ios::binary | std::ios::out); - - } - - } - //--------------------------------------------------------------------- - void DeflateStream::destroy() - { - if (getAccessMode() == READ) - inflateEnd(mZStream); - - OGRE_FREE(mZStream, MEMCATEGORY_GENERAL); - mZStream = 0; - OGRE_FREE(mTmp, MEMCATEGORY_GENERAL); - mTmp = 0; - } - //--------------------------------------------------------------------- - DeflateStream::~DeflateStream() - { - close(); - } - //--------------------------------------------------------------------- - size_t DeflateStream::read(void* buf, size_t count) - { - if (mStreamType == Invalid) - { - return mCompressedStream->read(buf, count); - } - - if (getAccessMode() & WRITE) - { - return mTmpWriteStream->read(buf, count); - } - else - { - - size_t restorePoint = mCompressedStream->tell(); - // read from cache first - size_t cachereads = mReadCache.read(buf, count); - - size_t newReadUncompressed = 0; - - if (cachereads < count) - { - mZStream->avail_out = static_cast(count - cachereads); - mZStream->next_out = (Bytef*)buf + cachereads; - - while (mZStream->avail_out) - { - // Pull next chunk of compressed data from the underlying stream - if (!mZStream->avail_in && !mCompressedStream->eof()) - { - mZStream->avail_in = static_cast(mCompressedStream->read(mTmp, getAvailInForSinglePass())); - mZStream->next_in = mTmp; - } - - if (mZStream->avail_in || mZStream->avail_out) - { - int availpre = mZStream->avail_out; - mStatus = inflate(mZStream, Z_SYNC_FLUSH); - size_t readUncompressed = availpre - mZStream->avail_out; - newReadUncompressed += readUncompressed; - if (mStatus != Z_OK) - { - // End of data, or error - if (mStatus != Z_STREAM_END) - { - mCompressedStream->seek(restorePoint); - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Error in compressed stream"); - } - else - { - // back up the stream so that it can be used from the end onwards - long unusedCompressed = mZStream->avail_in; - mCompressedStream->skip(-unusedCompressed); - } - - break; - } - } - } - - // Cache the last bytes read not from cache - mReadCache.cacheData((char*)buf + cachereads, newReadUncompressed); - } - - mCurrentPos += newReadUncompressed + cachereads; - - return newReadUncompressed + cachereads; - } - } - //--------------------------------------------------------------------- - size_t DeflateStream::write(const void* buf, size_t count) - { - if ((getAccessMode() & WRITE) == 0) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Not a writable stream", "DeflateStream::write"); - - return mTmpWriteStream->write(buf, count); - } - //--------------------------------------------------------------------- - void DeflateStream::compressFinal() - { - // Prevent reenterancy - if( !mTmpWriteStream ) - return; - - // Close temp stream - mTmpWriteStream->close(); - mTmpWriteStream.reset(); - - // Copy & compress - // We do this rather than compress directly because some code seeks - // around while writing (e.g. to update size blocks) which is not - // possible when compressing on the fly - - int ret, flush; - char in[OGRE_DEFLATE_TMP_SIZE]; - char out[OGRE_DEFLATE_TMP_SIZE]; - - int windowBits = (mStreamType == Deflate) ? -MAX_WBITS : (mStreamType == GZip) ? 16 + MAX_WBITS : MAX_WBITS; - if (deflateInit2(mZStream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, windowBits, 8, Z_DEFAULT_STRATEGY) != Z_OK) - { - destroy(); - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, - "Error initialising deflate compressed stream!", - "DeflateStream::init"); - } - - std::ifstream inFile; - inFile.open(mTempFileName.c_str(), std::ios::in | std::ios::binary); - - do - { - inFile.read(in, OGRE_DEFLATE_TMP_SIZE); - mZStream->avail_in = (uInt)inFile.gcount(); - if (inFile.bad()) - { - deflateEnd(mZStream); - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, - "Error reading temp uncompressed stream!", - "DeflateStream::init"); - } - flush = inFile.eof() ? Z_FINISH : Z_NO_FLUSH; - mZStream->next_in = (Bytef*)in; - - /* run deflate() on input until output buffer not full, finish - compression if all of source has been read in */ - do - { - mZStream->avail_out = OGRE_DEFLATE_TMP_SIZE; - mZStream->next_out = (Bytef*)out; - ret = deflate(mZStream, flush); /* no bad return value */ - assert(ret != Z_STREAM_ERROR); /* state not clobbered */ - size_t compressed = OGRE_DEFLATE_TMP_SIZE - mZStream->avail_out; - mCompressedStream->write(out, compressed); - } while (mZStream->avail_out == 0); - assert(mZStream->avail_in == 0); /* all input will be used */ - - /* done when last data in file processed */ - } while (flush != Z_FINISH); - assert(ret == Z_STREAM_END); /* stream will be complete */ - (void)ret; - deflateEnd(mZStream); - - inFile.close(); - remove(mTempFileName.c_str()); - - } - //--------------------------------------------------------------------- - void DeflateStream::skip(long count) - { - if (mStreamType == Invalid) - { - mCompressedStream->skip(count); - return; - } - - if (getAccessMode() & WRITE) - { - mTmpWriteStream->skip(count); - } - else - { - if (count > 0) - { - if (!mReadCache.ff(count)) - { - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, - "You can only skip within the cache range in a deflate stream.", - "DeflateStream::skip"); - } - } - else if (count < 0) - { - if (!mReadCache.rewind((size_t)(-count))) - { - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, - "You can only skip within the cache range in a deflate stream.", - "DeflateStream::skip"); - } - } - } - mCurrentPos = static_cast(static_cast(mCurrentPos) + count); - - - } - //--------------------------------------------------------------------- - void DeflateStream::seek( size_t pos ) - { - if (mStreamType == Invalid) - { - mCompressedStream->seek(pos); - return; - } - if (getAccessMode() & WRITE) - { - mTmpWriteStream->seek(pos); - } - else - { - if (pos == 0) - { - mCurrentPos = 0; - mZStream->next_in = mTmp; - mCompressedStream->seek(0); - mZStream->avail_in = static_cast(mCompressedStream->read(mTmp, getAvailInForSinglePass())); - inflateReset(mZStream); - mReadCache.clear(); - } - else - { - skip(pos - tell()); - } - } - } - //--------------------------------------------------------------------- - size_t DeflateStream::tell(void) const - { - if (mStreamType == Invalid) - { - return mCompressedStream->tell(); - } - else if(getAccessMode() & WRITE) - { - return mTmpWriteStream->tell(); - } - else - { - return mCurrentPos; - } - - } - //--------------------------------------------------------------------- - bool DeflateStream::eof(void) const - { - if (getAccessMode() & WRITE) - return mTmpWriteStream->eof(); - else - { - if (mStreamType == Invalid) - return mCompressedStream->eof(); - else - return mCompressedStream->eof() && mStatus == Z_STREAM_END; - } - } - //--------------------------------------------------------------------- - void DeflateStream::close(void) - { - if (getAccessMode() & WRITE) - compressFinal(); - - destroy(); - - mAccess = 0; - - // don't close underlying compressed stream in case used for something else - } - //--------------------------------------------------------------------- - - -} - -#endif diff --git a/OgreMain/src/OgreDepthBuffer.cpp b/OgreMain/src/OgreDepthBuffer.cpp deleted file mode 100644 index cdef4b0b726..00000000000 --- a/OgreMain/src/OgreDepthBuffer.cpp +++ /dev/null @@ -1,113 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreDepthBuffer.h" -#include "OgreRenderTarget.h" - -namespace Ogre -{ - DepthBuffer::DepthBuffer( uint16 poolId, uint32 width, uint32 height, - uint32 fsaa, bool manual ) : - mPoolId(poolId), - mWidth(width), - mHeight(height), - mFsaa(fsaa), - mManual(manual) - { - } - - DepthBuffer::~DepthBuffer() - { - detachFromAllRenderTargets(); - } - - void DepthBuffer::_setPoolId( uint16 poolId ) - { - //Change the pool Id - mPoolId = poolId; - - //Render Targets were attached to us, but they have a different pool Id, - //so detach ourselves from them - detachFromAllRenderTargets(); - } - //----------------------------------------------------------------------- - uint16 DepthBuffer::getPoolId() const - { - return mPoolId; - } - //----------------------------------------------------------------------- - uint32 DepthBuffer::getWidth() const - { - return mWidth; - } - //---------------------------------------------------------------------- - uint32 DepthBuffer::getHeight() const - { - return mHeight; - } - //----------------------------------------------------------------------- - bool DepthBuffer::isManual() const - { - return mManual; - } - //----------------------------------------------------------------------- - bool DepthBuffer::isCompatible( RenderTarget *renderTarget ) const - { - if( this->getWidth() >= renderTarget->getWidth() && - this->getHeight() >= renderTarget->getHeight() && - this->getFSAA() == renderTarget->getFSAA() ) - { - return true; - } - - return false; - } - //----------------------------------------------------------------------- - void DepthBuffer::_notifyRenderTargetAttached( RenderTarget *renderTarget ) - { - assert( mAttachedRenderTargets.find( renderTarget ) == mAttachedRenderTargets.end() ); - - mAttachedRenderTargets.insert( renderTarget ); - } - //----------------------------------------------------------------------- - void DepthBuffer::_notifyRenderTargetDetached( RenderTarget *renderTarget ) - { - RenderTargetSet::iterator itor = mAttachedRenderTargets.find( renderTarget ); - assert( itor != mAttachedRenderTargets.end() ); - - mAttachedRenderTargets.erase( itor ); - } - //----------------------------------------------------------------------- - void DepthBuffer::detachFromAllRenderTargets() - { - for (auto *r : mAttachedRenderTargets) - r->_detachDepthBuffer(); - - mAttachedRenderTargets.clear(); - } -} diff --git a/OgreMain/src/OgreDistanceLodStrategy.cpp b/OgreMain/src/OgreDistanceLodStrategy.cpp deleted file mode 100644 index c7adf3252f9..00000000000 --- a/OgreMain/src/OgreDistanceLodStrategy.cpp +++ /dev/null @@ -1,201 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" -#include "OgreDistanceLodStrategy.h" -#include "OgreViewport.h" - -#include - -namespace Ogre { - DistanceLodStrategyBase::DistanceLodStrategyBase(const String& name) - : LodStrategy(name) - , mReferenceViewEnabled(false) - , mReferenceViewValue(-1) - { } - //----------------------------------------------------------------------- - Real DistanceLodStrategyBase::getValueImpl(const MovableObject *movableObject, const Ogre::Camera *camera) const - { - Real squaredDist = getSquaredDepth(movableObject, camera); - - // Check if reference view needs to be taken into account - if (mReferenceViewEnabled) - { - // Reference view only applicable to perspective projection - assert(camera->getProjectionType() == PT_PERSPECTIVE && "Camera projection type must be perspective!"); - - // Get camera viewport - Viewport *viewport = camera->getViewport(); - - // Get viewport area - Real viewportArea = static_cast(viewport->getActualWidth() * viewport->getActualHeight()); - - // Get projection matrix (this is done to avoid computation of tan(FOV / 2)) - const Matrix4& projectionMatrix = camera->getProjectionMatrix(); - - // Compute bias value (note that this is similar to the method used for PixelCountLodStrategy) - Real biasValue = viewportArea * projectionMatrix[0][0] * projectionMatrix[1][1]; - - // Scale squared distance appropriately - squaredDist *= (mReferenceViewValue / biasValue); - } - - // Squared distance should never be below 0, so clamp - squaredDist = std::max(squaredDist, Real(0)); - - // Now adjust it by the camera bias and return the computed value - return squaredDist * camera->_getLodBiasInverse(); - } - //----------------------------------------------------------------------- - Real DistanceLodStrategyBase::getBaseValue() const - { - return Real(0); - } - //--------------------------------------------------------------------- - Real DistanceLodStrategyBase::transformBias(Real factor) const - { - assert(factor > 0.0f && "Bias factor must be > 0!"); - return 1.0f / factor; - } - //----------------------------------------------------------------------- - Real DistanceLodStrategyBase::transformUserValue(Real userValue) const - { - // Square user-supplied distance - return Math::Sqr(userValue); - } - //----------------------------------------------------------------------- - ushort DistanceLodStrategyBase::getIndex(Real value, const Mesh::MeshLodUsageList& meshLodUsageList) const - { - // Get index assuming ascending values - return getIndexAscending(value, meshLodUsageList); - } - //----------------------------------------------------------------------- - ushort DistanceLodStrategyBase::getIndex(Real value, const Material::LodValueList& materialLodValueList) const - { - // Get index assuming ascending values - return getIndexAscending(value, materialLodValueList); - } - //--------------------------------------------------------------------- - bool DistanceLodStrategyBase::isSorted(const Mesh::LodValueList& values) const - { - // Determine if sorted ascending - return isSortedAscending(values); - } - //--------------------------------------------------------------------- - void DistanceLodStrategyBase::sort(Mesh::MeshLodUsageList& meshLodUsageList) const - { - // Sort ascending - return sortAscending(meshLodUsageList); - } - //--------------------------------------------------------------------- - void DistanceLodStrategyBase::setReferenceView(Real viewportWidth, Real viewportHeight, Radian fovY) - { - // Determine x FOV based on aspect ratio - Radian fovX = fovY * (viewportWidth / viewportHeight); - - // Determine viewport area - Real viewportArea = viewportHeight * viewportWidth; - - // Compute reference view value based on viewport area and FOVs - mReferenceViewValue = viewportArea * Math::Tan(fovX * 0.5f) * Math::Tan(fovY * 0.5f); - - // Enable use of reference view - mReferenceViewEnabled = true; - } - //--------------------------------------------------------------------- - void DistanceLodStrategyBase::setReferenceViewEnabled(bool value) - { - // Ensure reference value has been set before being enabled - if (value) - assert(mReferenceViewValue != -1 && "Reference view must be set before being enabled!"); - - mReferenceViewEnabled = value; - } - //--------------------------------------------------------------------- - bool DistanceLodStrategyBase::isReferenceViewEnabled() const - { - return mReferenceViewEnabled; - } - - /************************************************************************/ - /* */ - /************************************************************************/ - - //----------------------------------------------------------------------- - template<> DistanceLodSphereStrategy* Singleton::msSingleton = 0; - DistanceLodSphereStrategy* DistanceLodSphereStrategy::getSingletonPtr(void) - { - return msSingleton; - } - DistanceLodSphereStrategy& DistanceLodSphereStrategy::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //----------------------------------------------------------------------- - DistanceLodSphereStrategy::DistanceLodSphereStrategy() - : DistanceLodStrategyBase("distance_sphere") - { } - //----------------------------------------------------------------------- - Real DistanceLodSphereStrategy::getSquaredDepth(const MovableObject *movableObject, const Ogre::Camera *camera) const - { - // Get squared distance taking into account bounding radius - // (d - r) ^ 2 = d^2 - 2dr + r^2, but this requires a lot - // more computation (including a sqrt) so we approximate - // it with d^2 - r^2, which is good enough for determining - // LOD. - - return movableObject->getParentNode()->getSquaredViewDepth(camera) - Math::Sqr(movableObject->getBoundingRadiusScaled()); - } - //----------------------------------------------------------------------- - - /************************************************************************/ - /* */ - /************************************************************************/ - - //----------------------------------------------------------------------- - template<> DistanceLodBoxStrategy* Singleton::msSingleton = 0; - DistanceLodBoxStrategy* DistanceLodBoxStrategy::getSingletonPtr(void) - { - return msSingleton; - } - DistanceLodBoxStrategy& DistanceLodBoxStrategy::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //----------------------------------------------------------------------- - DistanceLodBoxStrategy::DistanceLodBoxStrategy() - : DistanceLodStrategyBase("distance_box") - { } - //----------------------------------------------------------------------- - Real DistanceLodBoxStrategy::getSquaredDepth(const MovableObject *movableObject, const Ogre::Camera *camera) const - { - return movableObject->getWorldBoundingBox().squaredDistance(camera->getDerivedPosition()); - } - //----------------------------------------------------------------------- - -} // namespace diff --git a/OgreMain/src/OgreDualQuaternion.cpp b/OgreMain/src/OgreDualQuaternion.cpp deleted file mode 100644 index 33edfd086d5..00000000000 --- a/OgreMain/src/OgreDualQuaternion.cpp +++ /dev/null @@ -1,120 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -/* dqconv.c - - Conversion routines between (regular quaternion, translation) and dual quaternion. - - Version 1.0.0, February 7th, 2007 - - Copyright (C) 2006-2007 University of Dublin, Trinity College, All Rights - Reserved - - This software is provided 'as-is', without any express or implied - warranty. In no event will the author(s) 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. - - Author: Ladislav Kavan, kavanl@cs.tcd.ie - -*/ - -#include "OgreStableHeaders.h" -#include "OgreDualQuaternion.h" - - -namespace Ogre { - - //Based on dqconv.c from http://isg.cs.tcd.ie/projects/DualQuaternions/ - //----------------------------------------------------------------------- - void DualQuaternion::fromRotationTranslation (const Quaternion& q, const Vector3& trans) - { - // non-dual part (just copy the quaternion): - w = q.w; - x = q.x; - y = q.y; - z = q.z; - - // dual part: - Real half = 0.5; - dw = -half * (trans.x * x + trans.y * y + trans.z * z ); - dx = half * (trans.x * w + trans.y * z - trans.z * y ); - dy = half * (-trans.x * z + trans.y * w + trans.z * x ); - dz = half * (trans.x * y - trans.y * x + trans.z * w ); - } - - //Based on dqconv.c from http://isg.cs.tcd.ie/projects/DualQuaternions/ - //----------------------------------------------------------------------- - void DualQuaternion::toRotationTranslation (Quaternion& q, Vector3& translation) const - { - // regular quaternion (just copy the non-dual part): - q.w = w; - q.x = x; - q.y = y; - q.z = z; - - // translation vector: - Real doub = 2.0; - translation.x = doub * (-dw*x + dx*w - dy*z + dz*y); - translation.y = doub * (-dw*y + dx*z + dy*w - dz*x); - translation.z = doub * (-dw*z - dx*y + dy*x + dz*w); - } - - //----------------------------------------------------------------------- - void DualQuaternion::fromTransformationMatrix (const Affine3& kTrans) - { - Vector3 pos; - Vector3 scale; - Quaternion rot; - - kTrans.decomposition(pos, scale, rot); - fromRotationTranslation(rot, pos); - } - - //----------------------------------------------------------------------- - void DualQuaternion::toTransformationMatrix (Affine3& kTrans) const - { - Vector3 pos; - Quaternion rot; - toRotationTranslation(rot, pos); - - Vector3 scale = Vector3::UNIT_SCALE; - kTrans.makeTransform(pos, scale, rot); - } -} diff --git a/OgreMain/src/OgreDynLib.cpp b/OgreMain/src/OgreDynLib.cpp deleted file mode 100644 index 02f2dbd701c..00000000000 --- a/OgreMain/src/OgreDynLib.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreDynLib.h" - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 -# define DYNLIB_LOAD( a ) LoadLibraryEx( a, NULL, 0 ) // we can not use LOAD_WITH_ALTERED_SEARCH_PATH with relative paths -# define DYNLIB_GETSYM( a, b ) GetProcAddress( a, b ) -# define DYNLIB_UNLOAD( a ) !FreeLibrary( a ) -#elif OGRE_PLATFORM == OGRE_PLATFORM_WINRT -# define DYNLIB_LOAD( a ) LoadPackagedLibrary( stringToWstring(a).c_str(), 0 ) -# define DYNLIB_GETSYM( a, b ) GetProcAddress( a, b ) -# define DYNLIB_UNLOAD( a ) !FreeLibrary( a ) -#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN -# define DYNLIB_LOAD( a ) dlopen( a, RTLD_LAZY | RTLD_GLOBAL) -# define DYNLIB_GETSYM( a, b ) dlsym( a, b ) -# define DYNLIB_UNLOAD( a ) dlclose( a ) -#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE || OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS -# define DYNLIB_LOAD( a ) mac_loadDylib( a ) -# define FRAMEWORK_LOAD( a ) mac_loadFramework( a ) -# define DYNLIB_GETSYM( a, b ) dlsym( a, b ) -# define DYNLIB_UNLOAD( a ) dlclose( a ) -#endif - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT -# define WIN32_LEAN_AND_MEAN -# if !defined(NOMINMAX) && defined(_MSC_VER) -# define NOMINMAX // required to stop windows.h messing up std::min -# endif -# include -#else -extern "C" { -# include -} -#endif - -#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT -static std::wstring stringToWstring(const std::string& s) -{ - int len = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), s.length(), NULL, 0); - std::wstring ws(L"", len); - wchar_t* pWSBuf = const_cast(ws.c_str()); - MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, pWSBuf, len); - return ws; -} -#endif - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE || OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS -# include "macUtils.h" -extern "C" { -# include -# include -# include -} -#endif - -namespace Ogre { - - //----------------------------------------------------------------------- - DynLib::DynLib( const String& name ) - { - mName = name; - mInst = NULL; - } - - //----------------------------------------------------------------------- - DynLib::~DynLib() - { - } - - //----------------------------------------------------------------------- - void DynLib::load() - { - String name = mName; -#if OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - if (name.find(".js") == String::npos) - name += ".js"; -#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX - // dlopen() does not add .so to the filename, like windows does for .dll - if (name.find(".so") == String::npos) - { - name += StringUtil::format(".so.%d.%d", OGRE_VERSION_MAJOR, OGRE_VERSION_MINOR); - } -#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE - // dlopen() does not add .dylib to the filename, like windows does for .dll - if(name.substr(name.find_last_of(".") + 1) != "dylib") - name += ".dylib"; -#elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT - - // Although LoadLibraryEx will add .dll itself when you only specify the library name, - // if you include a relative path then it does not. So, add it to be sure. - if(name.substr(name.find_last_of(".") + 1) != "dll") - name += OGRE_BUILD_SUFFIX ".dll"; -#endif - // Log library load - LogManager::getSingleton().logMessage("Loading library " + name); - - mInst = (DYNLIB_HANDLE)DYNLIB_LOAD( name.c_str() ); -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE - if(!mInst) - { - name = mName; - if(name.substr(name.find_last_of(".") + 1) != "framework") - name += ".framework"; - // Try again as a framework - mInst = (DYNLIB_HANDLE)FRAMEWORK_LOAD( name ); - } -#endif - if( !mInst ) - OGRE_EXCEPT( - Exception::ERR_INTERNAL_ERROR, - "Could not load dynamic library " + mName + - ". System Error: " + dynlibError(), - "DynLib::load" ); - } - - //----------------------------------------------------------------------- - void DynLib::unload() - { - // Log library unload - LogManager::getSingleton().logMessage("Unloading library " + mName); - - if( DYNLIB_UNLOAD( mInst ) ) - { - OGRE_EXCEPT( - Exception::ERR_INTERNAL_ERROR, - "Could not unload dynamic library " + mName + - ". System Error: " + dynlibError(), - "DynLib::unload"); - } - - } - - //----------------------------------------------------------------------- - void* DynLib::getSymbol( const String& strName ) const throw() - { - return (void*)DYNLIB_GETSYM( mInst, strName.c_str() ); - } - //----------------------------------------------------------------------- - String DynLib::dynlibError( void ) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - LPTSTR lpMsgBuf; - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPTSTR)&lpMsgBuf, - 0, - NULL - ); - String ret = lpMsgBuf; - // Free the buffer. - LocalFree( lpMsgBuf ); - return ret; -#elif OGRE_PLATFORM == OGRE_PLATFORM_WINRT - WCHAR wideMsgBuf[1024]; - if(0 == FormatMessageW( - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - wideMsgBuf, - sizeof(wideMsgBuf) / sizeof(wideMsgBuf[0]), - NULL - )) - { - wideMsgBuf[0] = 0; - } - - char narrowMsgBuf[2048] = ""; - if(0 == WideCharToMultiByte( - CP_ACP, 0, - wideMsgBuf, -1, - narrowMsgBuf, sizeof(narrowMsgBuf) / sizeof(narrowMsgBuf[0]), - NULL, NULL)) - { - narrowMsgBuf[0] = 0; - } - String ret = narrowMsgBuf; - - return ret; -#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_APPLE - return String(dlerror()); -#else - return String(""); -#endif - } - -} diff --git a/OgreMain/src/OgreDynLibManager.cpp b/OgreMain/src/OgreDynLibManager.cpp deleted file mode 100644 index b1e47cd9bd2..00000000000 --- a/OgreMain/src/OgreDynLibManager.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreDynLibManager.h" -#include "OgreDynLib.h" - -namespace Ogre -{ - //----------------------------------------------------------------------- - template<> DynLibManager* Singleton::msSingleton = 0; - DynLibManager* DynLibManager::getSingletonPtr(void) - { - return msSingleton; - } - //----------------------------------------------------------------------- - DynLibManager& DynLibManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //----------------------------------------------------------------------- - DynLibManager::DynLibManager() - { - } - //----------------------------------------------------------------------- - DynLib* DynLibManager::load( const String& filename) - { - DynLibList::iterator i = mLibList.find(filename); - if (i != mLibList.end()) - { - return i->second; - } - else - { - DynLib* pLib = OGRE_NEW DynLib(filename); - pLib->load(); - mLibList[filename] = pLib; - return pLib; - } - } - //----------------------------------------------------------------------- - void DynLibManager::unload(DynLib* lib) - { - DynLibList::iterator i = mLibList.find(lib->getName()); - if (i != mLibList.end()) - { - mLibList.erase(i); - } - lib->unload(); - OGRE_DELETE lib; - } - //----------------------------------------------------------------------- - DynLibManager::~DynLibManager() - { - // Unload & delete resources in turn - for(auto & it : mLibList) - { - it.second->unload(); - OGRE_DELETE it.second; - } - - // Empty the list - mLibList.clear(); - } -} diff --git a/OgreMain/src/OgreETCCodec.cpp b/OgreMain/src/OgreETCCodec.cpp deleted file mode 100644 index 9bf665cbeac..00000000000 --- a/OgreMain/src/OgreETCCodec.cpp +++ /dev/null @@ -1,349 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" - -#include "OgreETCCodec.h" -#include "OgreImage.h" - -#define KTX_ENDIAN_REF (0x04030201) -#define KTX_ENDIAN_REF_REV (0x01020304) - -// In a PKM-file, the codecs are stored using the following identifiers -// -// identifier value codec -// -------------------------------------------------------------------- -// ETC1_RGB_NO_MIPMAPS 0 GL_ETC1_RGB8_OES -// ETC2PACKAGE_RGB_NO_MIPMAPS 1 GL_COMPRESSED_RGB8_ETC2 -// ETC2PACKAGE_RGBA_NO_MIPMAPS_OLD 2, not used - -// ETC2PACKAGE_RGBA_NO_MIPMAPS 3 GL_COMPRESSED_RGBA8_ETC2_EAC -// ETC2PACKAGE_RGBA1_NO_MIPMAPS 4 GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 -// ETC2PACKAGE_R_NO_MIPMAPS 5 GL_COMPRESSED_R11_EAC -// ETC2PACKAGE_RG_NO_MIPMAPS 6 GL_COMPRESSED_RG11_EAC -// ETC2PACKAGE_R_SIGNED_NO_MIPMAPS 7 GL_COMPRESSED_SIGNED_R11_EAC -// ETC2PACKAGE_RG_SIGNED_NO_MIPMAPS 8 GL_COMPRESSED_SIGNED_RG11_EAC - -namespace Ogre { - - const uint32 PKM_MAGIC = FOURCC('P', 'K', 'M', ' '); - const uint32 KTX_MAGIC = FOURCC(0xAB, 0x4B, 0x54, 0x58); - - typedef struct { - uint8 name[4]; - uint8 version[2]; - uint8 iTextureTypeMSB; - uint8 iTextureTypeLSB; - uint8 iPaddedWidthMSB; - uint8 iPaddedWidthLSB; - uint8 iPaddedHeightMSB; - uint8 iPaddedHeightLSB; - uint8 iWidthMSB; - uint8 iWidthLSB; - uint8 iHeightMSB; - uint8 iHeightLSB; - } PKMHeader; - - typedef struct { - uint8 identifier[12]; - uint32 endianness; - uint32 glType; - uint32 glTypeSize; - uint32 glFormat; - uint32 glInternalFormat; - uint32 glBaseInternalFormat; - uint32 pixelWidth; - uint32 pixelHeight; - uint32 pixelDepth; - uint32 numberOfArrayElements; - uint32 numberOfFaces; - uint32 numberOfMipmapLevels; - uint32 bytesOfKeyValueData; - } KTXHeader; - - //--------------------------------------------------------------------- - ETCCodec* ETCCodec::msPKMInstance = 0; - ETCCodec* ETCCodec::msKTXInstance = 0; - //--------------------------------------------------------------------- - void ETCCodec::startup(void) - { - if (!msPKMInstance) - { - msPKMInstance = OGRE_NEW ETCCodec("pkm"); - Codec::registerCodec(msPKMInstance); - } - - if (!msKTXInstance) - { - msKTXInstance = OGRE_NEW ETCCodec("ktx"); - Codec::registerCodec(msKTXInstance); - } - - LogManager::getSingleton().logMessage(LML_NORMAL, - "ETC codec registering"); - } - //--------------------------------------------------------------------- - void ETCCodec::shutdown(void) - { - if(msPKMInstance) - { - Codec::unregisterCodec(msPKMInstance); - OGRE_DELETE msPKMInstance; - msPKMInstance = 0; - } - - if(msKTXInstance) - { - Codec::unregisterCodec(msKTXInstance); - OGRE_DELETE msKTXInstance; - msKTXInstance = 0; - } - } - //--------------------------------------------------------------------- - ETCCodec::ETCCodec(const String &type): - mType(type) - { - } - //--------------------------------------------------------------------- - void ETCCodec::decode(const DataStreamPtr& stream, const Any& output) const - { - Image* image = any_cast(output); - - mType == "pkm" ? decodePKM(stream, image) : decodeKTX(stream, image); - } - //--------------------------------------------------------------------- - String ETCCodec::getType() const - { - return mType; - } - //--------------------------------------------------------------------- - String ETCCodec::magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const - { - if (maxbytes >= sizeof(uint32)) - { - uint32 fileType; - memcpy(&fileType, magicNumberPtr, sizeof(uint32)); - flipEndian(&fileType, sizeof(uint32)); - - if (PKM_MAGIC == fileType) - return String("pkm"); - - if (KTX_MAGIC == fileType) - return String("ktx"); - } - - return BLANKSTRING; - } - //--------------------------------------------------------------------- - void ETCCodec::decodePKM(const DataStreamPtr& stream, Image* image) - { - PKMHeader header; - - // Read the ETC header - stream->read(&header, sizeof(PKMHeader)); - - if (PKM_MAGIC != FOURCC(header.name[0], header.name[1], header.name[2], header.name[3]) ) // "PKM 10" - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "No PKM header found"); - - uint16 width = (header.iWidthMSB << 8) | header.iWidthLSB; - uint16 height = (header.iHeightMSB << 8) | header.iHeightLSB; - //uint16 paddedWidth = (header.iPaddedWidthMSB << 8) | header.iPaddedWidthLSB; - //uint16 paddedHeight = (header.iPaddedHeightMSB << 8) | header.iPaddedHeightLSB; - uint16 type = (header.iTextureTypeMSB << 8) | header.iTextureTypeLSB; - - PixelFormat format = PF_UNKNOWN; - - // File version 2.0 supports ETC2 in addition to ETC1 - if(header.version[0] == '2' && header.version[1] == '0') - { - switch (type) { - case 0: - format = PF_ETC1_RGB8; - break; - - // GL_COMPRESSED_RGB8_ETC2 - case 1: - format = PF_ETC2_RGB8; - break; - - // GL_COMPRESSED_RGBA8_ETC2_EAC - case 3: - format = PF_ETC2_RGBA8; - break; - - // GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 - case 4: - format = PF_ETC2_RGB8A1; - break; - - // Default case is ETC1 - default: - format = PF_ETC1_RGB8; - break; - } - } - else - format = PF_ETC1_RGB8; - - // ETC has no support for mipmaps - malideveloper.com has a example - // where the load mipmap levels from different external files - image->create(format, width, height); - stream->read(image->getData(), image->getSize()); - } - //--------------------------------------------------------------------- - void ETCCodec::decodeKTX(const DataStreamPtr& stream, Image* image) - { - KTXHeader header; - // Read the KTX header - stream->read(&header, sizeof(KTXHeader)); - - const uint8 KTXFileIdentifier[12] = { 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A }; - if (memcmp(KTXFileIdentifier, &header.identifier, sizeof(KTXFileIdentifier)) != 0) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "No KTX header found"); - - if (header.endianness == KTX_ENDIAN_REF_REV) - flipEndian(&header.glType, sizeof(uint32)); - - PixelFormat format = PF_UNKNOWN; - - switch(header.glInternalFormat) - { - case 37492: // GL_COMPRESSED_RGB8_ETC2 - format = PF_ETC2_RGB8; - break; - case 37496:// GL_COMPRESSED_RGBA8_ETC2_EAC - format = PF_ETC2_RGBA8; - break; - case 37494: // GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 - format = PF_ETC2_RGB8A1; - break; - case 35986: // ATC_RGB - format = PF_ATC_RGB; - break; - case 35987: // ATC_RGB_Explicit - format = PF_ATC_RGBA_EXPLICIT_ALPHA; - break; - case 34798: // ATC_RGB_Interpolated - format = PF_ATC_RGBA_INTERPOLATED_ALPHA; - break; - case 33777: // DXT 1 - format = PF_DXT1; - break; - case 33778: // DXT 3 - format = PF_DXT3; - break; - case 33779: // DXT 5 - format = PF_DXT5; - break; - case 0x8c00: // COMPRESSED_RGB_PVRTC_4BPPV1_IMG - format = PF_PVRTC_RGB4; - break; - case 0x8c01: // COMPRESSED_RGB_PVRTC_2BPPV1_IMG - format = PF_PVRTC_RGB2; - break; - case 0x8c02: // COMPRESSED_RGBA_PVRTC_4BPPV1_IMG - format = PF_PVRTC_RGBA4; - break; - case 0x8c03: // COMPRESSED_RGBA_PVRTC_2BPPV1_IMG - format = PF_PVRTC_RGBA2; - break; - case 0x93B0: // COMPRESSED_RGBA_ASTC_4x4_KHR - format = PF_ASTC_RGBA_4X4_LDR; - break; - case 0x93B1: // COMPRESSED_RGBA_ASTC_5x4_KHR - format = PF_ASTC_RGBA_5X4_LDR; - break; - case 0x93B2: // COMPRESSED_RGBA_ASTC_5x5_KHR - format = PF_ASTC_RGBA_5X5_LDR; - break; - case 0x93B3: // COMPRESSED_RGBA_ASTC_6x5_KHR - format = PF_ASTC_RGBA_6X5_LDR; - break; - case 0x93B4: // COMPRESSED_RGBA_ASTC_6x6_KHR - format = PF_ASTC_RGBA_6X6_LDR; - break; - case 0x93B5: // COMPRESSED_RGBA_ASTC_8x5_KHR - format = PF_ASTC_RGBA_8X5_LDR; - break; - case 0x93B6: // COMPRESSED_RGBA_ASTC_8x6_KHR - format = PF_ASTC_RGBA_8X6_LDR; - break; - case 0x93B7: // COMPRESSED_RGBA_ASTC_8x8_KHR - format = PF_ASTC_RGBA_8X8_LDR; - break; - case 0x93B8: // COMPRESSED_RGBA_ASTC_10x5_KHR - format = PF_ASTC_RGBA_10X5_LDR; - break; - case 0x93B9: // COMPRESSED_RGBA_ASTC_10x6_KHR - format = PF_ASTC_RGBA_10X6_LDR; - break; - case 0x93BA: // COMPRESSED_RGBA_ASTC_10x8_KHR - format = PF_ASTC_RGBA_10X8_LDR; - break; - case 0x93BB: // COMPRESSED_RGBA_ASTC_10x10_KHR - format = PF_ASTC_RGBA_10X10_LDR; - break; - case 0x93BC: // COMPRESSED_RGBA_ASTC_12x10_KHR - format = PF_ASTC_RGBA_12X10_LDR; - break; - case 0x93BD: // COMPRESSED_RGBA_ASTC_12x12_KHR - format = PF_ASTC_RGBA_12X12_LDR; - break; - case 0x8D64: // GL_ETC1_RGB8_OES - format = PF_ETC1_RGB8; - break; - case 0x8C3A: // GL_R11F_G11F_B10F - format = PF_R11G11B10_FLOAT; - break; - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Unsupported glInternalFormat"); - } - - image->create(format, header.pixelWidth, header.pixelHeight, 1, header.numberOfFaces, - header.numberOfMipmapLevels - 1); - - stream->skip(header.bytesOfKeyValueData); - - // Now deal with the data - uchar* destPtr = image->getData(); - uint32 mipOffset = 0; - uint32 numFaces = header.numberOfFaces; - size_t size = image->getSize(); - for (uint32 level = 0; level < header.numberOfMipmapLevels; ++level) - { - uint32 imageSize = 0; - stream->read(&imageSize, sizeof(uint32)); - - for(uint32 face = 0; face < numFaces; ++face) - { - uchar* placePtr = destPtr + ((size)/numFaces)*face + mipOffset; // shuffle mip and face - stream->read(placePtr, imageSize); - } - mipOffset += imageSize; - } - } -} diff --git a/OgreMain/src/OgreETCCodec.h b/OgreMain/src/OgreETCCodec.h deleted file mode 100644 index 4e2c10bafa0..00000000000 --- a/OgreMain/src/OgreETCCodec.h +++ /dev/null @@ -1,78 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OgreETCCodec_H__ -#define __OgreETCCodec_H__ - -#include "OgreImageCodec.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Image - * @{ - */ - - /** Codec specialized in loading ETC (Ericsson Texture Compression) images. - - We implement our own codec here since we need to be able to keep ETC - data compressed if the card supports it. - */ - class ETCCodec : public ImageCodec - { - private: - String mType; - - /// Single registered codec instance - static ETCCodec* msPKMInstance; - static ETCCodec* msKTXInstance; - - public: - ETCCodec(const String &type); - virtual ~ETCCodec() { } - - void decode(const DataStreamPtr& input, const Any& output) const override; - String magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const override; - String getType() const override; - - /// Static method to startup and register the ETC codec - static void startup(void); - /// Static method to shutdown and unregister the ETC codec - static void shutdown(void); - private: - static void decodePKM(const DataStreamPtr& input, Image* image); - static void decodeKTX(const DataStreamPtr& input, Image* image); - - }; - /** @} */ - /** @} */ - -} // namespace - -#endif - diff --git a/OgreMain/src/OgreEdgeListBuilder.cpp b/OgreMain/src/OgreEdgeListBuilder.cpp deleted file mode 100644 index c65ec9b44fb..00000000000 --- a/OgreMain/src/OgreEdgeListBuilder.cpp +++ /dev/null @@ -1,557 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreEdgeListBuilder.h" -#include "OgreVertexIndexData.h" -#include "OgreOptimisedUtil.h" - -namespace Ogre { - - EdgeData::EdgeData() : isClosed(false){} - - void EdgeData::log(Log* l) - { - EdgeGroupList::iterator i, iend; - EdgeList::iterator ei, eiend; - TriangleList::iterator ti, tiend; - tiend = triangles.end(); - l->logMessage("Edge Data"); - l->logMessage("---------"); - size_t num = 0; - for (ti = triangles.begin(); ti != tiend; ++ti, ++num) - { - Triangle& t = *ti; - l->logMessage("Triangle " + StringConverter::toString(num) + " = {" + - "indexSet=" + StringConverter::toString(t.indexSet) + ", " + - "vertexSet=" + StringConverter::toString(t.vertexSet) + ", " + - "v0=" + StringConverter::toString(t.vertIndex[0]) + ", " + - "v1=" + StringConverter::toString(t.vertIndex[1]) + ", " + - "v2=" + StringConverter::toString(t.vertIndex[2]) + "}"); - } - iend = edgeGroups.end(); - for (i = edgeGroups.begin(); i != iend; ++i) - { - num = 0; - eiend = i->edges.end(); - l->logMessage("Edge Group vertexSet=" + StringConverter::toString(i->vertexSet)); - for (ei = i->edges.begin(); ei != eiend; ++ei, ++num) - { - Edge& e = *ei; - l->logMessage( - "Edge " + StringConverter::toString(num) + " = {\n" + - " tri0=" + StringConverter::toString(e.triIndex[0]) + ", \n" + - " tri1=" + StringConverter::toString(e.triIndex[1]) + ", \n" + - " v0=" + StringConverter::toString(e.vertIndex[0]) + ", \n" + - " v1=" + StringConverter::toString(e.vertIndex[1]) + ", \n" - " degenerate=" + StringConverter::toString(e.degenerate) + " \n" - "}"); - } - } - } - //--------------------------------------------------------------------- - EdgeListBuilder::EdgeListBuilder() - : mEdgeData(0) - { - } - //--------------------------------------------------------------------- - void EdgeListBuilder::addVertexData(const VertexData* vertexData) - { - OgreAssert(vertexData->vertexStart == 0, - "The base vertex index of the vertex data must be zero for build edge list"); - mVertexDataList.push_back(vertexData); - } - //--------------------------------------------------------------------- - void EdgeListBuilder::addIndexData(const IndexData* indexData, - size_t vertexSet, RenderOperation::OperationType opType) - { - OgreAssert(opType == RenderOperation::OT_TRIANGLE_LIST || - opType == RenderOperation::OT_TRIANGLE_FAN || - opType == RenderOperation::OT_TRIANGLE_STRIP, - "Unsupported RenderOperation"); - OgreAssert(indexData->indexCount, "Index data must not be empty"); - - Geometry geometry; - geometry.indexData = indexData; - geometry.vertexSet = vertexSet; - geometry.opType = opType; - geometry.indexSet = mGeometryList.size(); - mGeometryList.push_back(geometry); - } - //--------------------------------------------------------------------- - EdgeData* EdgeListBuilder::build(void) - { - /* Ok, here's the algorithm: - For each set of indices in turn - For each set of 3 indexes - Create a new Triangle entry in the list - For each vertex referenced by the tri indexes - Get the position of the vertex as a Vector3 from the correct vertex buffer - Attempt to locate this position in the existing common vertex set - If not found - Create a new common vertex entry in the list - End If - Populate the original vertex index and common vertex index - Next vertex - Connect to existing edge(v1, v0) or create a new edge(v0, v1) - Connect to existing edge(v2, v1) or create a new edge(v1, v2) - Connect to existing edge(v0, v2) or create a new edge(v2, v0) - Next set of 3 indexes - Next index set - - Note that all edges 'belong' to the index set which originally caused them - to be created, which also means that the 2 vertices on the edge are both referencing the - vertex buffer which this index set uses. - */ - - - /* - There is a major consideration: 'What is a common vertex'? This is a - crucial decision, since to form a completely close hull, you need to treat - vertices which are not physically the same as equivalent. This is because - there will be 'seams' in the model, where discrepancies in vertex components - other than position (such as normals or texture coordinates) will mean - that there are 2 vertices in the same place, and we MUST 'weld' them - into a single common vertex in order to have a closed hull. Just looking - at the unique vertex indices is not enough, since these seams would render - the hull invalid. - - So, we look for positions which are the same across vertices, and treat - those as as single vertex for our edge calculation. However, this has - it's own problems. There are OTHER vertices which may have a common - position that should not be welded. Imagine 2 cubes touching along one - single edge. The common vertices on that edge, if welded, will cause - an ambiguous hull, since the edge will have 4 triangles attached to it, - whilst a manifold mesh should only have 2 triangles attached to each edge. - This is a problem. - - We deal with this with allow welded multiple pairs of edges. Using this - techniques, we can build a individual hull even if the model which has a - potentially ambiguous hull. This is feasible, because in the case of - multiple hulls existing, each hull can cast same shadow in any situation. - Notice: For stencil shadow, we intent to build a valid shadow volume for - the mesh, not the valid hull for the mesh. - */ - - // Sort the geometries in the order of vertex set, so we can grouping - // triangles by vertex set easy. - std::sort(mGeometryList.begin(), mGeometryList.end(), geometryLess()); - // Initialize edge data - mEdgeData = OGRE_NEW EdgeData(); - // resize the edge group list to equal the number of vertex sets - mEdgeData->edgeGroups.resize(mVertexDataList.size()); - // Initialise edge group data - for (unsigned short vSet = 0; vSet < mVertexDataList.size(); ++vSet) - { - mEdgeData->edgeGroups[vSet].vertexSet = vSet; - mEdgeData->edgeGroups[vSet].vertexData = mVertexDataList[vSet]; - mEdgeData->edgeGroups[vSet].triStart = 0; - mEdgeData->edgeGroups[vSet].triCount = 0; - } - - // Build triangles and edge list - for (auto& g : mGeometryList) - { - buildTrianglesEdges(g); - } - - // Allocate memory for light facing calculate - mEdgeData->triangleLightFacings.resize(mEdgeData->triangles.size()); - - // Record closed, ie the mesh is manifold - mEdgeData->isClosed = mEdgeMap.empty(); - - return mEdgeData; - } - //--------------------------------------------------------------------- - void EdgeListBuilder::buildTrianglesEdges(const Geometry &geometry) - { - size_t indexSet = geometry.indexSet; - size_t vertexSet = geometry.vertexSet; - const IndexData* indexData = geometry.indexData; - RenderOperation::OperationType opType = geometry.opType; - - size_t iterations; - - switch (opType) - { - case RenderOperation::OT_TRIANGLE_LIST: - iterations = indexData->indexCount / 3; - break; - case RenderOperation::OT_TRIANGLE_FAN: - case RenderOperation::OT_TRIANGLE_STRIP: - iterations = indexData->indexCount - 2; - break; - default: - return; // Just in case - }; - - // The edge group now we are dealing with. - EdgeData::EdgeGroup& eg = mEdgeData->edgeGroups[vertexSet]; - - // locate position element & the buffer to go with it - const VertexData* vertexData = mVertexDataList[vertexSet]; - const VertexElement* posElem = vertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); - HardwareVertexBufferSharedPtr vbuf = - vertexData->vertexBufferBinding->getBuffer(posElem->getSource()); - // lock the buffer for reading - HardwareBufferLockGuard vertexLock(vbuf, HardwareBuffer::HBL_READ_ONLY); - unsigned char* pBaseVertex = static_cast(vertexLock.pData); - - // Get the indexes ready for reading - bool idx32bit = (indexData->indexBuffer->getType() == HardwareIndexBuffer::IT_32BIT); - HardwareBufferLockGuard indexLock(indexData->indexBuffer, HardwareBuffer::HBL_READ_ONLY); - unsigned short* p16Idx = static_cast(indexLock.pData) + indexData->indexStart; - unsigned int* p32Idx = static_cast(indexLock.pData) + indexData->indexStart; - - // Iterate over all the groups of 3 indexes - unsigned int index[3]; - // Get the triangle start, if we have more than one index set then this - // will not be zero - size_t triangleIndex = mEdgeData->triangles.size(); - // If it's first time dealing with the edge group, setup triStart for it. - // Note that we are assume geometries sorted by vertex set. - if (!eg.triCount) - { - eg.triStart = triangleIndex; - } - // Pre-reserve memory for less thrashing - mEdgeData->triangles.reserve(triangleIndex + iterations); - mEdgeData->triangleFaceNormals.reserve(triangleIndex + iterations); - for (size_t t = 0; t < iterations; ++t) - { - EdgeData::Triangle tri; - tri.indexSet = indexSet; - tri.vertexSet = vertexSet; - - if (opType == RenderOperation::OT_TRIANGLE_LIST || t == 0) - { - // Standard 3-index read for tri list or first tri in strip / fan - if (idx32bit) - { - index[0] = p32Idx[0]; - index[1] = p32Idx[1]; - index[2] = p32Idx[2]; - p32Idx += 3; - } - else - { - index[0] = p16Idx[0]; - index[1] = p16Idx[1]; - index[2] = p16Idx[2]; - p16Idx += 3; - } - } - else - { - // Strips are formed from last 2 indexes plus the current one for - // triangles after the first. - // For fans, all the triangles share the first vertex, plus last - // one index and the current one for triangles after the first. - // We also make sure that all the triangles are process in the - // _anti_ clockwise orientation - index[(opType == RenderOperation::OT_TRIANGLE_STRIP) && (t & 1) ? 0 : 1] = index[2]; - // Read for the last tri index - if (idx32bit) - index[2] = *p32Idx++; - else - index[2] = *p16Idx++; - } - - Vector3 v[3]; - for (size_t i = 0; i < 3; ++i) - { - // Populate tri original vertex index - tri.vertIndex[i] = index[i]; - - // Retrieve the vertex position - unsigned char* pVertex = pBaseVertex + (index[i] * vbuf->getVertexSize()); - float* pFloat; - posElem->baseVertexPointerToElement(pVertex, &pFloat); - v[i].x = *pFloat++; - v[i].y = *pFloat++; - v[i].z = *pFloat++; - // find this vertex in the existing vertex map, or create it - tri.sharedVertIndex[i] = - findOrCreateCommonVertex(v[i], vertexSet, indexSet, index[i]); - } - - // Ignore degenerate triangle - if (tri.sharedVertIndex[0] != tri.sharedVertIndex[1] && - tri.sharedVertIndex[1] != tri.sharedVertIndex[2] && - tri.sharedVertIndex[2] != tri.sharedVertIndex[0]) - { - // Calculate triangle normal (NB will require recalculation for - // skeletally animated meshes) - mEdgeData->triangleFaceNormals.push_back( - Math::calculateFaceNormalWithoutNormalize(v[0], v[1], v[2])); - // Add triangle to list - mEdgeData->triangles.push_back(tri); - // Connect or create edges from common list - connectOrCreateEdge(vertexSet, triangleIndex, - tri.vertIndex[0], tri.vertIndex[1], - tri.sharedVertIndex[0], tri.sharedVertIndex[1]); - connectOrCreateEdge(vertexSet, triangleIndex, - tri.vertIndex[1], tri.vertIndex[2], - tri.sharedVertIndex[1], tri.sharedVertIndex[2]); - connectOrCreateEdge(vertexSet, triangleIndex, - tri.vertIndex[2], tri.vertIndex[0], - tri.sharedVertIndex[2], tri.sharedVertIndex[0]); - ++triangleIndex; - } - } - - // Update triCount for the edge group. Note that we are assume - // geometries sorted by vertex set. - eg.triCount = triangleIndex - eg.triStart; - } - //--------------------------------------------------------------------- - void EdgeListBuilder::connectOrCreateEdge(size_t vertexSet, size_t triangleIndex, - size_t vertIndex0, size_t vertIndex1, size_t sharedVertIndex0, - size_t sharedVertIndex1) - { - // Find the existing edge (should be reversed order) on shared vertices - EdgeMap::iterator emi = mEdgeMap.find(std::pair(sharedVertIndex1, sharedVertIndex0)); - if (emi != mEdgeMap.end()) - { - // The edge already exist, connect it - EdgeData::Edge& e = mEdgeData->edgeGroups[emi->second.first].edges[emi->second.second]; - // update with second side - e.triIndex[1] = triangleIndex; - e.degenerate = false; - - // Remove from the edge map, so we never supplied to connect edge again - mEdgeMap.erase(emi); - } - else - { - // Not found, create new edge - mEdgeMap.emplace(std::pair(sharedVertIndex0, sharedVertIndex1), - std::pair(vertexSet, mEdgeData->edgeGroups[vertexSet].edges.size())); - EdgeData::Edge e; - e.degenerate = true; // initialise as degenerate - - // Set only first tri, the other will be completed in connect existing edge - e.triIndex[0] = triangleIndex; - e.triIndex[1] = static_cast(~0); - e.sharedVertIndex[0] = sharedVertIndex0; - e.sharedVertIndex[1] = sharedVertIndex1; - e.vertIndex[0] = vertIndex0; - e.vertIndex[1] = vertIndex1; - mEdgeData->edgeGroups[vertexSet].edges.push_back(e); - } - } - //--------------------------------------------------------------------- - size_t EdgeListBuilder::findOrCreateCommonVertex(const Vector3& vec, - size_t vertexSet, size_t indexSet, size_t originalIndex) - { - // Because the algorithm doesn't care about manifold or not, we just identifying - // the common vertex by EXACT same position. - // Hint: We can use quantize method for welding almost same position vertex fastest. - std::pair inserted = mCommonVertexMap.emplace(vec, mVertices.size()); - if (!inserted.second) - { - // Already existing, return old one - return inserted.first->second; - } - // Not found, insert - CommonVertex newCommon; - newCommon.index = mVertices.size(); - newCommon.position = vec; - newCommon.vertexSet = vertexSet; - newCommon.indexSet = indexSet; - newCommon.originalIndex = originalIndex; - mVertices.push_back(newCommon); - return newCommon.index; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - void EdgeData::updateTriangleLightFacing(const Vector4& lightPos) - { - // Triangle face normals should be 1:1 with light facing flags - assert(triangleFaceNormals.size() == triangleLightFacings.size()); - - // Use optimised util to determine if triangle's face normal are light facing - if(!triangleFaceNormals.empty()) - { - OptimisedUtil::getImplementation()->calculateLightFacing( - lightPos, - &triangleFaceNormals.front(), - &triangleLightFacings.front(), - triangleLightFacings.size()); - } - } - //--------------------------------------------------------------------- - void EdgeData::updateFaceNormals(size_t vertexSet, - const HardwareVertexBufferSharedPtr& positionBuffer) - { - assert (positionBuffer->getVertexSize() == sizeof(float) * 3 - && "Position buffer should contain only positions!"); - - // Triangle face normals should be 1:1 with triangles - assert(triangleFaceNormals.size() == triangles.size()); - - // Calculate triangles which are using this vertex set - const EdgeData::EdgeGroup& eg = edgeGroups[vertexSet]; - if (eg.triCount != 0) - { - HardwareBufferLockGuard positionsLock(positionBuffer, HardwareBuffer::HBL_READ_ONLY); - OptimisedUtil::getImplementation()->calculateFaceNormals( - static_cast(positionsLock.pData), - &triangles[eg.triStart], - &triangleFaceNormals[eg.triStart], - eg.triCount); - } - } - //--------------------------------------------------------------------- - EdgeData* EdgeData::clone() - { - EdgeData* newEdgeData = OGRE_NEW EdgeData(); - newEdgeData->triangles = triangles; - newEdgeData->triangleFaceNormals = triangleFaceNormals; - newEdgeData->triangleLightFacings = triangleLightFacings; - newEdgeData->edgeGroups = edgeGroups; - newEdgeData->isClosed = isClosed; - return newEdgeData; - } - //--------------------------------------------------------------------- - void EdgeListBuilder::log(Log* l) - { - l->logMessage("EdgeListBuilder Log"); - l->logMessage("-------------------"); - l->logMessage("Number of vertex sets: " + StringConverter::toString(mVertexDataList.size())); - l->logMessage("Number of index sets: " + StringConverter::toString(mGeometryList.size())); - - size_t i, j, k; - // Log original vertex data - for(i = 0; i < mVertexDataList.size(); ++i) - { - const VertexData* vData = mVertexDataList[i]; - l->logMessage("."); - l->logMessage("Original vertex set " + - StringConverter::toString(i) + " - vertex count " + - StringConverter::toString(vData->vertexCount)); - const VertexElement* posElem = vData->vertexDeclaration->findElementBySemantic(VES_POSITION); - HardwareVertexBufferSharedPtr vbuf = - vData->vertexBufferBinding->getBuffer(posElem->getSource()); - // lock the buffer for reading - HardwareBufferLockGuard vertexLock(vbuf, HardwareBuffer::HBL_READ_ONLY); - unsigned char* pBaseVertex = static_cast(vertexLock.pData); - float* pFloat; - for (j = 0; j < vData->vertexCount; ++j) - { - posElem->baseVertexPointerToElement(pBaseVertex, &pFloat); - l->logMessage("Vertex " + StringConverter::toString(j) + - ": (" + StringConverter::toString(pFloat[0]) + - ", " + StringConverter::toString(pFloat[1]) + - ", " + StringConverter::toString(pFloat[2]) + ")"); - pBaseVertex += vbuf->getVertexSize(); - } - } - - // Log original index data - for(i = 0; i < mGeometryList.size(); i++) - { - const IndexData* iData = mGeometryList[i].indexData; - l->logMessage("."); - l->logMessage("Original triangle set " + - StringConverter::toString(mGeometryList[i].indexSet) + " - index count " + - StringConverter::toString(iData->indexCount) + " - " + - "vertex set " + StringConverter::toString(mGeometryList[i].vertexSet) + " - " + - "operationType " + StringConverter::toString(mGeometryList[i].opType)); - // Get the indexes ready for reading - HardwareBufferLockGuard indexLock(iData->indexBuffer, HardwareBuffer::HBL_READ_ONLY); - unsigned short* p16Idx = static_cast(indexLock.pData); - unsigned int* p32Idx = static_cast(indexLock.pData); - bool isIT32 = iData->indexBuffer->getType() == HardwareIndexBuffer::IT_32BIT; - - for (j = 0; j < iData->indexCount; ) - { - if (isIT32) - { - if (mGeometryList[i].opType == RenderOperation::OT_TRIANGLE_LIST - || j == 0) - { - unsigned int n1 = *p32Idx++; - unsigned int n2 = *p32Idx++; - unsigned int n3 = *p32Idx++; - l->logMessage("Triangle " + StringConverter::toString(j) + - ": (" + StringConverter::toString(n1) + - ", " + StringConverter::toString(n2) + - ", " + StringConverter::toString(n3) + ")"); - j += 3; - } - else - { - l->logMessage("Triangle " + StringConverter::toString(j) + - ": (" + StringConverter::toString(*p32Idx++) + ")"); - j++; - } - } - else - { - if (mGeometryList[i].opType == RenderOperation::OT_TRIANGLE_LIST - || j == 0) - { - unsigned short n1 = *p16Idx++; - unsigned short n2 = *p16Idx++; - unsigned short n3 = *p16Idx++; - l->logMessage("Index " + StringConverter::toString(j) + - ": (" + StringConverter::toString(n1) + - ", " + StringConverter::toString(n2) + - ", " + StringConverter::toString(n3) + ")"); - j += 3; - } - else - { - l->logMessage("Triangle " + StringConverter::toString(j) + - ": (" + StringConverter::toString(*p16Idx++) + ")"); - j++; - } - } - } - - // Log common vertex list - l->logMessage("."); - l->logMessage("Common vertex list - vertex count " + - StringConverter::toString(mVertices.size())); - for (k = 0; k < mVertices.size(); ++k) - { - CommonVertex& c = mVertices[k]; - l->logMessage("Common vertex " + StringConverter::toString(k) + - ": (vertexSet=" + StringConverter::toString(c.vertexSet) + - ", originalIndex=" + StringConverter::toString(c.originalIndex) + - ", position=" + StringConverter::toString(c.position)); - } - } - - } - - - -} - diff --git a/OgreMain/src/OgreEntity.cpp b/OgreMain/src/OgreEntity.cpp deleted file mode 100644 index 8324db88443..00000000000 --- a/OgreMain/src/OgreEntity.cpp +++ /dev/null @@ -1,2389 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#include "OgreStableHeaders.h" -#include "OgreEntity.h" -#include "OgreSubEntity.h" -#include "OgreTagPoint.h" -#include "OgreSkeletonInstance.h" -#include "OgreOptimisedUtil.h" -#include "OgreLodStrategy.h" -#include "OgreLodListener.h" - - -namespace Ogre { - //----------------------------------------------------------------------- - Entity::Entity () - : mAnimationState(NULL), - mTempSkelAnimInfo(), - mTempVertexAnimInfo(), - mVertexAnimationAppliedThisFrame(false), - mPreparedForShadowVolumes(false), - mDisplaySkeleton(false), - mCurrentHWAnimationState(false), - mSkipAnimStateUpdates(false), - mAlwaysUpdateMainSkeleton(false), - mUpdateBoundingBoxFromSkeleton(false), - mVertexProgramInUse(false), - mInitialised(false), - mHardwarePoseCount(0), - mNumBoneMatrices(0), - mBoneWorldMatrices(NULL), - mBoneMatrices(NULL), - mFrameAnimationLastUpdated(std::numeric_limits::max()), - mFrameBonesLastUpdated(NULL), - mSharedSkeletonEntities(NULL), - mSoftwareAnimationRequests(0), - mSoftwareAnimationNormalsRequests(0), - mMeshLodIndex(0), - mMeshLodFactorTransformed(1.0f), - mMinMeshLodIndex(99), - mMaxMeshLodIndex(0), // Backwards, remember low value = high detail - mMaterialLodFactor(1.0f), - mMinMaterialLodIndex(99), - mMaxMaterialLodIndex(0), // Backwards, remember low value = high detail - mSkeletonInstance(0), - mLastParentXform(Affine3::ZERO), - mMeshStateCount(0), - mFullBoundingBox() - { - } - //----------------------------------------------------------------------- - Entity::Entity( const String& name, const MeshPtr& mesh) : Entity() - { - mName = name; - mMesh = mesh; - _initialise(); - } - //----------------------------------------------------------------------- - void Entity::loadingComplete(Resource* res) - { - if (res == mMesh.get()) - { - // mesh loading has finished, we can construct ourselves now - _initialise(); - } - } - //----------------------------------------------------------------------- - void Entity::_initialise(bool forceReinitialise) - { - if (forceReinitialise) - _deinitialise(); - - if (mInitialised) - return; - - if (mMesh->isBackgroundLoaded() && !mMesh->isLoaded()) - { - // register for a callback when mesh is finished loading - // do this before asking for load to happen to avoid race - mMesh->addListener(this); - } - - // On-demand load - mMesh->load(); - // If loading failed, or deferred loading isn't done yet, defer - // Will get a callback in the case of deferred loading - // Skeletons are cascade-loaded so no issues there - if (!mMesh->isLoaded()) - return; - - // Is mesh skeletally animated? - if (mMesh->hasSkeleton() && mMesh->getSkeleton()) - { - mSkeletonInstance = OGRE_NEW SkeletonInstance(mMesh->getSkeleton()); - mSkeletonInstance->load(); - // if mUpdateBoundingBoxFromSkeleton was turned on before the mesh was loaded, and mesh hasn't computed the boneBoundingRadius yet, - if ( mUpdateBoundingBoxFromSkeleton && mMesh->getBoneBoundingRadius() == Real(0)) - { - mMesh->_computeBoneBoundingRadius(); - } - } - - // Build main subentity list - buildSubEntityList(mMesh, &mSubEntityList); -#if !OGRE_NO_MESHLOD - // Check if mesh is using manual LOD - if (mMesh->hasManualLodLevel()) - { - ushort i, numLod; - numLod = mMesh->getNumLodLevels(); - // NB skip LOD 0 which is the original - for (i = 1; i < numLod; ++i) - { - const MeshLodUsage& usage = mMesh->getLodLevel(i); - Entity* lodEnt; - if(!usage.manualName.empty()){ - // Disabled to prevent recursion when a.mesh has manualLod to b.mesh and b.mesh has manualLod to a.mesh. - OgreAssert(usage.manualMesh->getNumLodLevels() == 1, "Manual Lod Mesh can't have Lod levels!"); - - if(usage.manualMesh->getNumLodLevels() != 1) { - // To prevent crash in release builds, we will remove Lod levels. - usage.manualMesh->removeLodLevels(); - } - - // Manually create entity - lodEnt = OGRE_NEW Entity(mName + "Lod" + StringConverter::toString(i), - usage.manualMesh); - } else { - // Autogenerated lod uses original entity - lodEnt = this; - } - mLodEntityList.push_back(lodEnt); - } - } -#endif - - // Initialise the AnimationState, if Mesh has animation - if (hasSkeleton()) - { - mFrameBonesLastUpdated = OGRE_ALLOC_T(unsigned long, 1, MEMCATEGORY_ANIMATION); - *mFrameBonesLastUpdated = std::numeric_limits::max(); - mNumBoneMatrices = mSkeletonInstance->getNumBones(); - mBoneMatrices = static_cast(OGRE_MALLOC_SIMD(sizeof(Affine3) * mNumBoneMatrices, MEMCATEGORY_ANIMATION)); - } - if (hasSkeleton() || hasVertexAnimation()) - { - mAnimationState = OGRE_NEW AnimationStateSet(); - mMesh->_initAnimationState(mAnimationState); - prepareTempBlendBuffers(); - } - - reevaluateVertexProcessing(); - - // Update of bounds of the parent SceneNode, if Entity already attached - // this can happen if Mesh is loaded in background or after reinitialisation - if( mParentNode ) - { - getParentSceneNode()->needUpdate(); - } - - mInitialised = true; - mMeshStateCount = mMesh->getStateCount(); - } - //----------------------------------------------------------------------- - void Entity::_deinitialise(void) - { - if (!mInitialised) - return; - - // Delete submeshes - for (auto *s : mSubEntityList) - { - // Delete SubEntity - OGRE_DELETE s; - s = nullptr; - } - mSubEntityList.clear(); - -#if !OGRE_NO_MESHLOD - // Delete LOD entities - for (auto *li : mLodEntityList) - { - if(li != this) { - li->mParentNode = NULL; // prevent LODs from unregistering themselves - OGRE_DELETE li; - } - } - mLodEntityList.clear(); -#endif - // Delete shadow renderables - clearShadowRenderableList(mShadowRenderables); - - // Detach all child objects, do this manually to avoid needUpdate() call - // which can fail because of deleted items - detachAllObjectsImpl(); - - if (mSkeletonInstance) { - OGRE_FREE_SIMD(mBoneWorldMatrices, MEMCATEGORY_ANIMATION); - mBoneWorldMatrices = 0; - - if (mSharedSkeletonEntities) { - mSharedSkeletonEntities->erase(this); - if (mSharedSkeletonEntities->size() == 1) - { - (*mSharedSkeletonEntities->begin())->stopSharingSkeletonInstance(); - } - // Should never occur, just in case - else if (mSharedSkeletonEntities->empty()) - { - OGRE_DELETE_T(mSharedSkeletonEntities, EntitySet, MEMCATEGORY_ANIMATION); mSharedSkeletonEntities = 0; - // using OGRE_FREE since unsigned long is not a destructor - OGRE_FREE(mFrameBonesLastUpdated, MEMCATEGORY_ANIMATION); mFrameBonesLastUpdated = 0; - OGRE_DELETE mSkeletonInstance; mSkeletonInstance = 0; - OGRE_FREE_SIMD(mBoneMatrices, MEMCATEGORY_ANIMATION); mBoneMatrices = 0; - OGRE_DELETE mAnimationState; mAnimationState = 0; - } - } else { - // using OGRE_FREE since unsigned long is not a destructor - OGRE_FREE(mFrameBonesLastUpdated, MEMCATEGORY_ANIMATION); mFrameBonesLastUpdated = 0; - OGRE_DELETE mSkeletonInstance; mSkeletonInstance = 0; - OGRE_FREE_SIMD(mBoneMatrices, MEMCATEGORY_ANIMATION); mBoneMatrices = 0; - OGRE_DELETE mAnimationState; mAnimationState = 0; - } - } - else - { - //Non-skeletally animated objects don't share the mAnimationState. Always delete. - //See https://ogre3d.atlassian.net/browse/OGRE-504 - OGRE_DELETE mAnimationState; - mAnimationState = 0; - } - - mSkelAnimVertexData.reset(); - mSoftwareVertexAnimVertexData.reset(); - mHardwareVertexAnimVertexData.reset(); - - mInitialised = false; - } - //----------------------------------------------------------------------- - Entity::~Entity() - { - _deinitialise(); - // Unregister our listener - mMesh->removeListener(this); - } - //----------------------------------------------------------------------- - void Entity::_releaseManualHardwareResources() - { - clearShadowRenderableList(mShadowRenderables); - } - //----------------------------------------------------------------------- - void Entity::_restoreManualHardwareResources() - { - // mShadowRenderables are lazy initialized - } - //----------------------------------------------------------------------- - bool Entity::hasVertexAnimation(void) const - { - return mMesh->hasVertexAnimation(); - } - //----------------------------------------------------------------------- - const MeshPtr& Entity::getMesh(void) const - { - return mMesh; - } - //----------------------------------------------------------------------- - SubEntity* Entity::getSubEntity(const String& name) const - { - ushort index = mMesh->_getSubMeshIndex(name); - return getSubEntity(index); - } - //----------------------------------------------------------------------- - Entity* Entity::clone( const String& newName) const - { - OgreAssert(mManager, "Cannot clone an Entity that wasn't created through a SceneManager"); - Entity* newEnt = mManager->createEntity(newName, getMesh()->getName() ); - - if (mInitialised) - { - // Copy material settings - unsigned int n = 0; - for (const auto *e : mSubEntityList) - { - newEnt->getSubEntities()[n++]->setMaterialName(e->getMaterialName()); - } - if (mAnimationState) - { - OGRE_DELETE newEnt->mAnimationState; - newEnt->mAnimationState = OGRE_NEW AnimationStateSet(*mAnimationState); - } - } - - return newEnt; - } - //----------------------------------------------------------------------- - void Entity::setMaterialName( const String& name, const String& groupName /* = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME */) - { - // Set for all subentities - for (auto *s : mSubEntityList) - { - s->setMaterialName(name, groupName); - } - - } - //----------------------------------------------------------------------- - void Entity::setMaterial( const MaterialPtr& material ) - { - // Set for all subentities - for (auto *s : mSubEntityList) - { - s->setMaterial(material); - } - } - //----------------------------------------------------------------------- - void Entity::_notifyCurrentCamera(Camera* cam) - { - MovableObject::_notifyCurrentCamera(cam); - - // Calculate the LOD - if (mParentNode) - { -#if !OGRE_NO_MESHLOD - // Get mesh lod strategy - const LodStrategy *meshStrategy = mMesh->getLodStrategy(); - // Get the appropriate LOD value - Real lodValue = meshStrategy->getValue(this, cam); - // Bias the LOD value - Real biasedMeshLodValue = lodValue * mMeshLodFactorTransformed; - - - // Get the index at this biased depth - ushort newMeshLodIndex = mMesh->getLodIndex(biasedMeshLodValue); - // Apply maximum detail restriction (remember lower = higher detail, higher = lower detail) - newMeshLodIndex = Math::Clamp(newMeshLodIndex, mMaxMeshLodIndex, mMinMeshLodIndex); - - // Construct event object - EntityMeshLodChangedEvent evt; - evt.entity = this; - evt.camera = cam; - evt.lodValue = biasedMeshLodValue; - evt.previousLodIndex = mMeshLodIndex; - evt.newLodIndex = newMeshLodIndex; - - // Notify LOD event listeners - cam->getSceneManager()->_notifyEntityMeshLodChanged(evt); - - // Change LOD index - mMeshLodIndex = evt.newLodIndex; -#endif - - - for (auto *s : mSubEntityList) - { - // Get sub-entity material - const MaterialPtr& material = s->getMaterial(); - - // Get material LOD strategy - const LodStrategy *materialStrategy = material->getLodStrategy(); - - // Recalculate LOD value if strategies do not match - Real biasedMaterialLodValue; -#if !OGRE_NO_MESHLOD - if (meshStrategy == materialStrategy) - biasedMaterialLodValue = biasedMeshLodValue; - else -#endif - biasedMaterialLodValue = materialStrategy->getValue(this, cam) * materialStrategy->transformBias(mMaterialLodFactor); - - // Get the index at this biased depth - unsigned short idx = material->getLodIndex(biasedMaterialLodValue); - // Apply maximum detail restriction (remember lower = higher detail, higher = lower detail) - idx = Math::Clamp(idx, mMaxMaterialLodIndex, mMinMaterialLodIndex); - - // Construct event object - EntityMaterialLodChangedEvent subEntEvt; - subEntEvt.subEntity = s; - subEntEvt.camera = cam; - subEntEvt.lodValue = biasedMaterialLodValue; - subEntEvt.previousLodIndex = s->mMaterialLodIndex; - subEntEvt.newLodIndex = idx; - - // Notify LOD event listeners - cam->getSceneManager()->_notifyEntityMaterialLodChanged(subEntEvt); - - // Change LOD index - s->mMaterialLodIndex = subEntEvt.newLodIndex; - // Also invalidate any camera distance cache - s->_invalidateCameraCache (); - } - - - } - // Notify any child objects - for(auto child : mChildObjectList) - { - child->_notifyCurrentCamera(cam); - } - } - //----------------------------------------------------------------------- - void Entity::setUpdateBoundingBoxFromSkeleton(bool update) - { - mUpdateBoundingBoxFromSkeleton = update; - if (mMesh->isLoaded() && mMesh->getBoneBoundingRadius() == Real(0)) - { - mMesh->_computeBoneBoundingRadius(); - } - } - //----------------------------------------------------------------------- - const AxisAlignedBox& Entity::getBoundingBox(void) const - { - // Get from Mesh - if (mMesh->isLoaded()) - { - if ( mUpdateBoundingBoxFromSkeleton && hasSkeleton() ) - { - // get from skeleton - // self bounding box without children - AxisAlignedBox bbox; - bbox.setNull(); - Real maxScale = Real(0); - bool boneHasVerts[ OGRE_MAX_NUM_BONES ]; - uint16 numBones = mSkeletonInstance->getNumBones(); - for (size_t iBone = 0; iBone < numBones; ++iBone) - { - boneHasVerts[ iBone ] = false; - } - // for each bone that has vertices weighted to it, - for (unsigned long iBone : mMesh->sharedBlendIndexToBoneIndexMap) - { - // record which bones have vertices assigned - boneHasVerts[ iBone ] = true; - } - // for each submesh, - for (uint16 iSubMesh = 0; iSubMesh < mMesh->getNumSubMeshes(); ++iSubMesh) - { - SubMesh* submesh = mMesh->getSubMesh( iSubMesh ); - // if the submesh has own vertices, - if ( ! submesh->useSharedVertices ) - { - // record which bones have vertices assigned - for (unsigned long iBone : submesh->blendIndexToBoneIndexMap) - { - boneHasVerts[ iBone ] = true; - } - } - } - // for each bone that has vertices weighted to it, - for (uint16 iBone = 0; iBone < numBones; ++iBone) - { - if ( boneHasVerts[ iBone ] ) - { - const Bone* bone = mSkeletonInstance->getBone( iBone ); - Vector3 scaleVec = bone->_getDerivedScale(); - Real scale = std::max( std::max( Math::Abs(scaleVec.x), Math::Abs(scaleVec.y)), Math::Abs(scaleVec.z) ); - maxScale = std::max( maxScale, scale ); - // only include bones that aren't scaled to zero - if (scale > Real(0)) - { - bbox.merge( bone->_getDerivedPosition() ); - } - } - } - // unless all bones were scaled to zero, - if (! bbox.isNull()) - { - // inflate the bounding box - float r = mMesh->getBoneBoundingRadius() * maxScale; // adjust bone bounding radius by max scale of any bone - Vector3 expansion(r, r, r); - bbox.setExtents( bbox.getMinimum() - expansion, bbox.getMaximum() + expansion ); - } - bbox.merge(getChildObjectsBoundingBox()); - // if bounding box has changed, - if (bbox != mFullBoundingBox) - { - mFullBoundingBox = bbox; - Node::queueNeedUpdate( mParentNode ); // inform the parent node to update its AABB (without this, changes to the bbox won't propagate to the scene node) - } - } - else - { - // Get from Mesh - mFullBoundingBox = mMesh->getBounds(); - mFullBoundingBox.merge(getChildObjectsBoundingBox()); - } - // Don't scale here, this is taken into account when world BBox calculation is done - } - else - { - mFullBoundingBox.setNull(); - } - - return mFullBoundingBox; - } - //----------------------------------------------------------------------- - AxisAlignedBox Entity::getChildObjectsBoundingBox(void) const - { - AxisAlignedBox aa_box; - AxisAlignedBox full_aa_box; - full_aa_box.setNull(); - - for(auto child : mChildObjectList) - { - aa_box = child->getBoundingBox(); - TagPoint* tp = static_cast(child->getParentNode()); - // Use transform local to skeleton since world xform comes later - aa_box.transform(tp->_getFullLocalTransform()); - - full_aa_box.merge(aa_box); - } - - return full_aa_box; - } - //----------------------------------------------------------------------- - const AxisAlignedBox& Entity::getWorldBoundingBox(bool derive) const - { - if (derive) - { - // derive child bounding boxes - for(auto child : mChildObjectList) - { - child->getWorldBoundingBox(true); - } - } - return MovableObject::getWorldBoundingBox(derive); - } - //----------------------------------------------------------------------- - const Sphere& Entity::getWorldBoundingSphere(bool derive) const - { - if (derive) - { - // derive child bounding boxes - for(auto child : mChildObjectList) - { - child->getWorldBoundingSphere(true); - } - } - return MovableObject::getWorldBoundingSphere(derive); - - } - //----------------------------------------------------------------------- - void Entity::_updateRenderQueue(RenderQueue* queue) - { - // Do nothing if not initialised yet - if (!mInitialised) - return; - - // Check mesh state count, will be incremented if reloaded - if (mMesh->getStateCount() != mMeshStateCount) - { - // force reinitialise - _initialise(true); - } - - Entity* displayEntity = this; -#if !OGRE_NO_MESHLOD - // Check we're not using a manual LOD - if (mMeshLodIndex > 0 && mMesh->hasManualLodLevel()) - { - // Use alternate entity - assert( static_cast< size_t >( mMeshLodIndex - 1 ) < mLodEntityList.size() && - "No LOD EntityList - did you build the manual LODs after creating the entity?"); - // index - 1 as we skip index 0 (original LOD) - displayEntity = mLodEntityList[mMeshLodIndex-1]; - - if (displayEntity != this && hasSkeleton() && displayEntity->hasSkeleton()) - { - // Copy the animation state set to lod entity, we assume the lod - // entity only has a subset animation states - AnimationStateSet* targetState = displayEntity->mAnimationState; - if (mAnimationState != targetState) // only copy if LODs use different skeleton instances - { - if (mAnimationState->getDirtyFrameNumber() != targetState->getDirtyFrameNumber()) // only copy if animation was updated - mAnimationState->copyMatchingState(targetState); - } - } - } -#endif - - // Add each visible SubEntity to the queue - for (auto *s : displayEntity->mSubEntityList) - { - if(s->isVisible()) - { - // Order: first use subentity queue settings, if available - // if not then use entity queue settings, if available - // finally fall back on default queue settings - if(s->isRenderQueuePrioritySet()) - { - assert(s->isRenderQueueGroupSet() == true); - queue->addRenderable(s, s->getRenderQueueGroup(), s->getRenderQueuePriority()); - } - else if(s->isRenderQueueGroupSet()) - { - queue->addRenderable(s, s->getRenderQueueGroup()); - } - else if (mRenderQueuePrioritySet) - { - assert(mRenderQueueIDSet == true); - queue->addRenderable(s, mRenderQueueID, mRenderQueuePriority); - } - else if(mRenderQueueIDSet) - { - queue->addRenderable(s, mRenderQueueID); - } - else - { - queue->addRenderable(s); - } - } - } -#if !OGRE_NO_MESHLOD - if (getAlwaysUpdateMainSkeleton() && hasSkeleton() && (mMeshLodIndex > 0)) - { - //check if an update was made - if (cacheBoneMatrices()) - { - getSkeleton()->_updateTransforms(); - //We will mark the skeleton as dirty. Otherwise, if in the same frame the entity will - //be rendered first with a low LOD and then with a high LOD the system wont know that - //the bone matrices has changed and there for will not update the vertex buffers - getSkeleton()->_notifyManualBonesDirty(); - } - } -#endif - // Since we know we're going to be rendered, take this opportunity to - // update the animation - if (displayEntity->hasSkeleton() || displayEntity->hasVertexAnimation()) - { - displayEntity->updateAnimation(); - - //--- pass this point, we are sure that the transformation matrix of each bone and tagPoint have been updated - for(auto child : mChildObjectList) - { - bool visible = child->isVisible(); - if (visible && (displayEntity != this)) - { - //Check if the bone exists in the current LOD - - //The child is connected to a tagpoint which is connected to a bone - Bone* bone = static_cast(child->getParentNode()->getParent()); - if (!displayEntity->getSkeleton()->hasBone(bone->getName())) - { - //Current LOD entity does not have the bone that the - //child is connected to. Do not display. - visible = false; - } - } - if (visible) - { - child->_updateRenderQueue(queue); - } - } - } - - // HACK to display bones - if (mDisplaySkeleton && hasSkeleton() && mManager && mManager->getDebugDrawer()) - { - for (Bone* bone : mSkeletonInstance->getBones()) - { - mManager->getDebugDrawer()->drawBone(bone, mParentNode->_getFullTransform()); - } - } - } - //----------------------------------------------------------------------- - AnimationState* Entity::getAnimationState(const String& name) const - { - OgreAssert(mAnimationState, "Entity is not animated"); - return mAnimationState->getAnimationState(name); - } - //----------------------------------------------------------------------- - bool Entity::hasAnimationState(const String& name) const - { - return mAnimationState && mAnimationState->hasAnimationState(name); - } - //----------------------------------------------------------------------- - AnimationStateSet* Entity::getAllAnimationStates(void) const - { - return mAnimationState; - } - //----------------------------------------------------------------------- - const String& Entity::getMovableType(void) const - { - return MOT_ENTITY; - } - //----------------------------------------------------------------------- - bool Entity::tempVertexAnimBuffersBound(void) const - { - // Do we still have temp buffers for software vertex animation bound? - bool ret = true; - if (mMesh->sharedVertexData && mMesh->getSharedVertexDataAnimationType() != VAT_NONE) - { - ret = ret && mTempVertexAnimInfo.buffersCheckedOut(true, mMesh->getSharedVertexDataAnimationIncludesNormals()); - } - for (auto sub : mSubEntityList) - { - if (!sub->getSubMesh()->useSharedVertices - && sub->getSubMesh()->getVertexAnimationType() != VAT_NONE) - { - ret = ret && sub->mTempVertexAnimInfo.buffersCheckedOut( - true, sub->getSubMesh()->getVertexAnimationIncludesNormals()); - } - } - return ret; - } - //----------------------------------------------------------------------- - bool Entity::tempSkelAnimBuffersBound(bool requestNormals) const - { - // Do we still have temp buffers for software skeleton animation bound? - if (mSkelAnimVertexData) - { - if (!mTempSkelAnimInfo.buffersCheckedOut(true, requestNormals)) - return false; - } - for (auto sub : mSubEntityList) - { - if (sub->isVisible() && sub->mSkelAnimVertexData) - { - if (!sub->mTempSkelAnimInfo.buffersCheckedOut(true, requestNormals)) - return false; - } - } - return true; - } - //----------------------------------------------------------------------- - void Entity::updateAnimation(void) - { - // Do nothing if not initialised yet - if (!mInitialised) - return; - - Root& root = Root::getSingleton(); - bool hwAnimation = isHardwareAnimationEnabled(); - bool isNeedUpdateHardwareAnim = hwAnimation && !mCurrentHWAnimationState; - bool forcedSwAnimation = getSoftwareAnimationRequests()>0; - bool forcedNormals = getSoftwareAnimationNormalsRequests()>0; - bool stencilShadows = false; - if (getCastShadows() && hasEdgeList() && root._getCurrentSceneManager()) - stencilShadows = root._getCurrentSceneManager()->isShadowTechniqueStencilBased(); - bool softwareAnimation = !hwAnimation || stencilShadows || forcedSwAnimation; - // Blend normals in s/w only if we're not using h/w animation, - // since shadows only require positions - bool blendNormals = !hwAnimation || forcedNormals; - // Animation dirty if animation state modified or manual bones modified - bool animationDirty = - (mFrameAnimationLastUpdated != mAnimationState->getDirtyFrameNumber()) || - (hasSkeleton() && getSkeleton()->getManualBonesDirty()); - - //update the current hardware animation state - mCurrentHWAnimationState = hwAnimation; - - // We only do these tasks if animation is dirty - // Or, if we're using a skeleton and manual bones have been moved - // Or, if we're using software animation and temp buffers are unbound - if (animationDirty || - (softwareAnimation && hasVertexAnimation() && !tempVertexAnimBuffersBound()) || - (softwareAnimation && hasSkeleton() && !tempSkelAnimBuffersBound(blendNormals))) - { - if (hasVertexAnimation()) - { - if (softwareAnimation) - { - // grab & bind temporary buffer for positions (& normals if they are included) - if (mSoftwareVertexAnimVertexData - && mMesh->getSharedVertexDataAnimationType() != VAT_NONE) - { - bool useNormals = mMesh->getSharedVertexDataAnimationIncludesNormals(); - mTempVertexAnimInfo.checkoutTempCopies(true, useNormals); - // NB we suppress hardware upload while doing blend if we're - // hardware animation, because the only reason for doing this - // is for shadow, which need only be uploaded then - mTempVertexAnimInfo.bindTempCopies(mSoftwareVertexAnimVertexData.get(), - hwAnimation); - } - for (auto *se : mSubEntityList) - { - // Blend dedicated geometry - if (se->isVisible() && se->mSoftwareVertexAnimVertexData - && se->getSubMesh()->getVertexAnimationType() != VAT_NONE) - { - bool useNormals = se->getSubMesh()->getVertexAnimationIncludesNormals(); - se->mTempVertexAnimInfo.checkoutTempCopies(true, useNormals); - se->mTempVertexAnimInfo.bindTempCopies(se->mSoftwareVertexAnimVertexData.get(), - hwAnimation); - } - } - } - applyVertexAnimation(hwAnimation, stencilShadows); - } - - if (hasSkeleton()) - { - cacheBoneMatrices(); - - // Software blend? - if (softwareAnimation) - { - const Affine3* blendMatrices[OGRE_MAX_NUM_BONES]; - - // Ok, we need to do a software blend - // Firstly, check out working vertex buffers - if (mSkelAnimVertexData) - { - // Blend shared geometry - // NB we suppress hardware upload while doing blend if we're - // hardware animation, because the only reason for doing this - // is for shadow, which need only be uploaded then - mTempSkelAnimInfo.checkoutTempCopies(true, blendNormals); - mTempSkelAnimInfo.bindTempCopies(mSkelAnimVertexData.get(), - hwAnimation); - // Prepare blend matrices, TODO: Move out of here - Mesh::prepareMatricesForVertexBlend(blendMatrices, - mBoneMatrices, mMesh->sharedBlendIndexToBoneIndexMap); - // Blend, taking source from either mesh data or morph data - Mesh::softwareVertexBlend( - (mMesh->getSharedVertexDataAnimationType() != VAT_NONE) ? - mSoftwareVertexAnimVertexData.get() : mMesh->sharedVertexData, - mSkelAnimVertexData.get(), - blendMatrices, mMesh->sharedBlendIndexToBoneIndexMap.size(), - blendNormals); - } - - for (auto *se : mSubEntityList) - { - // Blend dedicated geometry - if (se->isVisible() && se->mSkelAnimVertexData) - { - se->mTempSkelAnimInfo.checkoutTempCopies(true, blendNormals); - se->mTempSkelAnimInfo.bindTempCopies(se->mSkelAnimVertexData.get(), - hwAnimation); - // Prepare blend matrices, TODO: Move out of here - Mesh::prepareMatricesForVertexBlend(blendMatrices, - mBoneMatrices, se->mSubMesh->blendIndexToBoneIndexMap); - // Blend, taking source from either mesh data or morph data - Mesh::softwareVertexBlend( - (se->getSubMesh()->getVertexAnimationType() != VAT_NONE)? - se->mSoftwareVertexAnimVertexData.get() : se->mSubMesh->vertexData, - se->mSkelAnimVertexData.get(), - blendMatrices, se->mSubMesh->blendIndexToBoneIndexMap.size(), - blendNormals); - } - - } - - } - } - - // Trigger update of bounding box if necessary - if (!mChildObjectList.empty()) - mParentNode->needUpdate(); - - mFrameAnimationLastUpdated = mAnimationState->getDirtyFrameNumber(); - } - - // Need to update the child object's transforms when animation dirty - // or parent node transform has altered. - if (hasSkeleton() && - (isNeedUpdateHardwareAnim || - animationDirty || mLastParentXform != _getParentNodeFullTransform())) - { - // Cache last parent transform for next frame use too. - mLastParentXform = _getParentNodeFullTransform(); - - //--- Update the child object's transforms - for(auto child : mChildObjectList) - { - child->getParentNode()->_update(true, true); - } - - // Also calculate bone world matrices, since are used as replacement world matrices, - // but only if it's used (when using hardware animation and skeleton animated). - if (hwAnimation && _isSkeletonAnimated() && !MeshManager::getBonesUseObjectSpace()) - { - // Allocate bone world matrices on demand, for better memory footprint - // when using software animation. - if (!mBoneWorldMatrices) - { - mBoneWorldMatrices = - static_cast(OGRE_MALLOC_SIMD(sizeof(Affine3) * mNumBoneMatrices, MEMCATEGORY_ANIMATION)); - std::fill(mBoneWorldMatrices, mBoneWorldMatrices + mNumBoneMatrices, Affine3::IDENTITY); - } - - OptimisedUtil::getImplementation()->concatenateAffineMatrices( - mLastParentXform, - mBoneMatrices, - mBoneWorldMatrices, - mNumBoneMatrices); - } - } - } - //----------------------------------------------------------------------- - ushort Entity::initHardwareAnimationElements(VertexData* vdata, - ushort numberOfElements, bool animateNormals) - { - ushort elemsSupported = numberOfElements; - if (vdata->hwAnimationDataList.size() < numberOfElements) - { - elemsSupported = - vdata->allocateHardwareAnimationElements(numberOfElements, animateNormals); - } - // Initialise parametrics in case we don't use all of them - for (auto & i : vdata->hwAnimationDataList) - { - i.parametric = 0.0f; - } - // reset used count - vdata->hwAnimDataItemsUsed = 0; - - return elemsSupported; - - } - //----------------------------------------------------------------------- - void Entity::applyVertexAnimation(bool hardwareAnimation, bool stencilShadows) - { - const MeshPtr& msh = getMesh(); - bool swAnim = !hardwareAnimation || stencilShadows || (mSoftwareAnimationRequests>0); - - // make sure we have enough hardware animation elements to play with - if (hardwareAnimation) - { - if (mHardwareVertexAnimVertexData - && msh->getSharedVertexDataAnimationType() != VAT_NONE) - { - ushort supportedCount = - initHardwareAnimationElements(mHardwareVertexAnimVertexData.get(), - (msh->getSharedVertexDataAnimationType() == VAT_POSE) - ? mHardwarePoseCount : 1, - msh->getSharedVertexDataAnimationIncludesNormals()); - - if (msh->getSharedVertexDataAnimationType() == VAT_POSE && - supportedCount < mHardwarePoseCount) - { - LogManager::getSingleton().stream() << - "Vertex program assigned to Entity '" << mName << - "' claimed to support " << mHardwarePoseCount << - " morph/pose vertex sets, but in fact only " << supportedCount << - " were able to be supported in the shared mesh data."; - mHardwarePoseCount = supportedCount; - } - -} - for (auto sub : mSubEntityList) - { - if (sub->getSubMesh()->getVertexAnimationType() != VAT_NONE && - !sub->getSubMesh()->useSharedVertices) - { - ushort supportedCount = initHardwareAnimationElements( - sub->_getHardwareVertexAnimVertexData(), - (sub->getSubMesh()->getVertexAnimationType() == VAT_POSE) - ? sub->mHardwarePoseCount : 1, - sub->getSubMesh()->getVertexAnimationIncludesNormals()); - - if (sub->getSubMesh()->getVertexAnimationType() == VAT_POSE && - supportedCount < sub->mHardwarePoseCount) - { - LogManager::getSingleton().stream() << - "Vertex program assigned to SubEntity of '" << mName << - "' claimed to support " << sub->mHardwarePoseCount << - " morph/pose vertex sets, but in fact only " << supportedCount << - " were able to be supported in the mesh data."; - sub->mHardwarePoseCount = supportedCount; - } - - } - } - - } - else - { - // May be blending multiple poses in software - // Suppress hardware upload of buffers - // Note, we query position buffer here but it may also include normals - if (mSoftwareVertexAnimVertexData && - mMesh->getSharedVertexDataAnimationType() == VAT_POSE) - { - const VertexElement* elem = mSoftwareVertexAnimVertexData - ->vertexDeclaration->findElementBySemantic(VES_POSITION); - HardwareVertexBufferSharedPtr buf = mSoftwareVertexAnimVertexData - ->vertexBufferBinding->getBuffer(elem->getSource()); - buf->suppressHardwareUpdate(true); - - initialisePoseVertexData(mMesh->sharedVertexData, mSoftwareVertexAnimVertexData.get(), - mMesh->getSharedVertexDataAnimationIncludesNormals()); - } - for (auto sub : mSubEntityList) - { - if (!sub->getSubMesh()->useSharedVertices && - sub->getSubMesh()->getVertexAnimationType() == VAT_POSE) - { - VertexData* data = sub->_getSoftwareVertexAnimVertexData(); - const VertexElement* elem = data->vertexDeclaration - ->findElementBySemantic(VES_POSITION); - HardwareVertexBufferSharedPtr buf = data - ->vertexBufferBinding->getBuffer(elem->getSource()); - buf->suppressHardwareUpdate(true); - // if we're animating normals, we need to start with zeros - initialisePoseVertexData(sub->getSubMesh()->vertexData, data, - sub->getSubMesh()->getVertexAnimationIncludesNormals()); - } - } - } - - - // Now apply the animation(s) - // Note - you should only apply one morph animation to each set of vertex data - // at once; if you do more, only the last one will actually apply - markBuffersUnusedForAnimation(); - EnabledAnimationStateList::const_iterator animIt; - for(auto *state : mAnimationState->getEnabledAnimationStates()) - { - Animation* anim = msh->_getAnimationImpl(state->getAnimationName()); - if (anim) - { - anim->apply(this, state->getTimePosition(), state->getWeight(), - swAnim, hardwareAnimation); - } - } - // Deal with cases where no animation applied - restoreBuffersForUnusedAnimation(hardwareAnimation); - - // Unsuppress hardware upload if we suppressed it - if (!hardwareAnimation) - { - if (mSoftwareVertexAnimVertexData && - msh->getSharedVertexDataAnimationType() == VAT_POSE) - { - // if we're animating normals, if pose influence < 1 need to use the base mesh - if (mMesh->getSharedVertexDataAnimationIncludesNormals()) - finalisePoseNormals(mMesh->sharedVertexData, mSoftwareVertexAnimVertexData.get()); - - const VertexElement* elem = mSoftwareVertexAnimVertexData - ->vertexDeclaration->findElementBySemantic(VES_POSITION); - HardwareVertexBufferSharedPtr buf = mSoftwareVertexAnimVertexData - ->vertexBufferBinding->getBuffer(elem->getSource()); - buf->suppressHardwareUpdate(false); - } - for (auto sub : mSubEntityList) - { - if (!sub->getSubMesh()->useSharedVertices && - sub->getSubMesh()->getVertexAnimationType() == VAT_POSE) - { - VertexData* data = sub->_getSoftwareVertexAnimVertexData(); - // if we're animating normals, if pose influence < 1 need to use the base mesh - if (sub->getSubMesh()->getVertexAnimationIncludesNormals()) - finalisePoseNormals(sub->getSubMesh()->vertexData, data); - - const VertexElement* elem = data->vertexDeclaration - ->findElementBySemantic(VES_POSITION); - HardwareVertexBufferSharedPtr buf = data - ->vertexBufferBinding->getBuffer(elem->getSource()); - buf->suppressHardwareUpdate(false); - } - } - } - - } - //----------------------------------------------------------------------------- - void Entity::markBuffersUnusedForAnimation(void) - { - mVertexAnimationAppliedThisFrame = false; - for (auto & i : mSubEntityList) - { - i->_markBuffersUnusedForAnimation(); - } - } - //----------------------------------------------------------------------------- - void Entity::_markBuffersUsedForAnimation(void) - { - mVertexAnimationAppliedThisFrame = true; - // no cascade - } - //----------------------------------------------------------------------------- - void Entity::restoreBuffersForUnusedAnimation(bool hardwareAnimation) - { - // Rebind original positions if: - // We didn't apply any animation and - // We're morph animated (hardware binds keyframe, software is missing) - // or we're pose animated and software (hardware is fine, still bound) - if (mMesh->sharedVertexData && - !mVertexAnimationAppliedThisFrame && - (!hardwareAnimation || mMesh->getSharedVertexDataAnimationType() == VAT_MORPH)) - { - // Note, VES_POSITION is specified here but if normals are included in animation - // then these will be re-bound too (buffers must be shared) - const VertexElement* srcPosElem = - mMesh->sharedVertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); - HardwareVertexBufferSharedPtr srcBuf = - mMesh->sharedVertexData->vertexBufferBinding->getBuffer( - srcPosElem->getSource()); - - // Bind to software - const VertexElement* destPosElem = - mSoftwareVertexAnimVertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); - mSoftwareVertexAnimVertexData->vertexBufferBinding->setBinding( - destPosElem->getSource(), srcBuf); - - } - - // rebind any missing hardware pose buffers - // Caused by not having any animations enabled, or keyframes which reference - // no poses - if (mMesh->sharedVertexData && hardwareAnimation - && mMesh->getSharedVertexDataAnimationType() == VAT_POSE) - { - bindMissingHardwarePoseBuffers(mMesh->sharedVertexData, mHardwareVertexAnimVertexData.get()); - } - - - for (auto & i : mSubEntityList) - { - i->_restoreBuffersForUnusedAnimation(hardwareAnimation); - } - - } - //--------------------------------------------------------------------- - void Entity::bindMissingHardwarePoseBuffers(const VertexData* srcData, - VertexData* destData) - { - // For hardware pose animation, also make sure we've bound buffers to all the elements - // required - if there are missing bindings for elements in use, - // some rendersystems can complain because elements refer - // to an unbound source. - // Get the original position source, we'll use this to fill gaps - const VertexElement* srcPosElem = - srcData->vertexDeclaration->findElementBySemantic(VES_POSITION); - HardwareVertexBufferSharedPtr srcBuf = - srcData->vertexBufferBinding->getBuffer( - srcPosElem->getSource()); - - for (auto animData : destData->hwAnimationDataList) - { - if (!destData->vertexBufferBinding->isBufferBound( - animData.targetBufferIndex)) - { - // Bind to a safe default - destData->vertexBufferBinding->setBinding( - animData.targetBufferIndex, srcBuf); - } - } - - } - //----------------------------------------------------------------------- - void Entity::initialisePoseVertexData(const VertexData* srcData, - VertexData* destData, bool animateNormals) - { - - // First time through for a piece of pose animated vertex data - // We need to copy the original position values to the temp accumulator - const VertexElement* origelem = - srcData->vertexDeclaration->findElementBySemantic(VES_POSITION); - const VertexElement* destelem = - destData->vertexDeclaration->findElementBySemantic(VES_POSITION); - HardwareVertexBufferSharedPtr origBuffer = - srcData->vertexBufferBinding->getBuffer(origelem->getSource()); - HardwareVertexBufferSharedPtr destBuffer = - destData->vertexBufferBinding->getBuffer(destelem->getSource()); - destBuffer->copyData(*origBuffer.get(), 0, 0, destBuffer->getSizeInBytes(), true); - - // If normals are included in animation, we want to reset the normals to zero - if (animateNormals) - { - const VertexElement* normElem = - destData->vertexDeclaration->findElementBySemantic(VES_NORMAL); - - if (normElem) - { - HardwareVertexBufferSharedPtr buf = - destData->vertexBufferBinding->getBuffer(normElem->getSource()); - HardwareBufferLockGuard vertexLock(buf, HardwareBuffer::HBL_NORMAL); - char* pBase = static_cast(vertexLock.pData) + destData->vertexStart * buf->getVertexSize(); - - for (size_t v = 0; v < destData->vertexCount; ++v) - { - float* pNorm; - normElem->baseVertexPointerToElement(pBase, &pNorm); - *pNorm++ = 0.0f; - *pNorm++ = 0.0f; - *pNorm++ = 0.0f; - - pBase += buf->getVertexSize(); - } - } - } - } - //----------------------------------------------------------------------- - void Entity::finalisePoseNormals(const VertexData* srcData, VertexData* destData) - { - const VertexElement* destNormElem = - destData->vertexDeclaration->findElementBySemantic(VES_NORMAL); - const VertexElement* srcNormElem = - srcData->vertexDeclaration->findElementBySemantic(VES_NORMAL); - - if (destNormElem && srcNormElem) - { - auto srcbuf = srcData->vertexBufferBinding->getBuffer(srcNormElem->getSource()); - auto dstbuf = destData->vertexBufferBinding->getBuffer(destNormElem->getSource()); - - HardwareBufferLockGuard dstLock(dstbuf, HardwareBuffer::HBL_NORMAL); - char* pDstBase = static_cast(dstLock.pData) + destData->vertexStart * dstbuf->getVertexSize(); - char* pSrcBase = pDstBase; - - HardwareBufferLockGuard srcLock; - if (srcbuf != dstbuf) - { - srcLock.lock(srcbuf, HardwareBuffer::HBL_READ_ONLY); - pSrcBase = static_cast(srcLock.pData) + srcData->vertexStart * srcbuf->getVertexSize(); - } - // The goal here is to detect the length of the vertices, and to apply - // the base mesh vertex normal at one minus that length; this deals with - // any individual vertices which were either not affected by any pose, or - // were not affected to a complete extent - // We also normalise every normal to deal with over-weighting - for (size_t v = 0; v < destData->vertexCount; ++v) - { - float* pDstNorm; - destNormElem->baseVertexPointerToElement(pDstBase, &pDstNorm); - Vector3 norm(pDstNorm[0], pDstNorm[1], pDstNorm[2]); - Real len = norm.length(); - if (len + 1e-4f < 1.0f) - { - // Poses did not completely fill in this normal - // Apply base mesh - float baseWeight = 1.0f - (float)len; - float* pSrcNorm; - srcNormElem->baseVertexPointerToElement(pSrcBase, &pSrcNorm); - norm.x += *pSrcNorm++ * baseWeight; - norm.y += *pSrcNorm++ * baseWeight; - norm.z += *pSrcNorm++ * baseWeight; - } - norm.normalise(); - - *pDstNorm++ = (float)norm.x; - *pDstNorm++ = (float)norm.y; - *pDstNorm++ = (float)norm.z; - - pDstBase += dstbuf->getVertexSize(); - pSrcBase += dstbuf->getVertexSize(); - } - } - } - //----------------------------------------------------------------------- - void Entity::_updateAnimation(void) - { - // Externally visible method - if (hasSkeleton() || hasVertexAnimation()) - { - updateAnimation(); - } - } - //----------------------------------------------------------------------- - bool Entity::_isAnimated(void) const - { - return (mAnimationState && mAnimationState->hasEnabledAnimationState()) || - (getSkeleton() && getSkeleton()->hasManualBones()); - } - //----------------------------------------------------------------------- - bool Entity::_isSkeletonAnimated(void) const - { - return getSkeleton() && - (mAnimationState->hasEnabledAnimationState() || getSkeleton()->hasManualBones()); - } - //----------------------------------------------------------------------- - VertexData* Entity::_getSkelAnimVertexData(void) const - { - assert (mSkelAnimVertexData && "Not software skinned or has no shared vertex data!"); - return mSkelAnimVertexData.get(); - } - //----------------------------------------------------------------------- - VertexData* Entity::_getSoftwareVertexAnimVertexData(void) const - { - assert (mSoftwareVertexAnimVertexData && "Not vertex animated or has no shared vertex data!"); - return mSoftwareVertexAnimVertexData.get(); - } - //----------------------------------------------------------------------- - VertexData* Entity::_getHardwareVertexAnimVertexData(void) const - { - assert (mHardwareVertexAnimVertexData && "Not vertex animated or has no shared vertex data!"); - return mHardwareVertexAnimVertexData.get(); - } - //----------------------------------------------------------------------- - bool Entity::cacheBoneMatrices(void) - { - Root& root = Root::getSingleton(); - unsigned long currentFrameNumber = root.getNextFrameNumber(); - if ((*mFrameBonesLastUpdated != currentFrameNumber) || - (hasSkeleton() && getSkeleton()->getManualBonesDirty())) - { - if ((!mSkipAnimStateUpdates) && (*mFrameBonesLastUpdated != currentFrameNumber)) - mSkeletonInstance->setAnimationState(*mAnimationState); - mSkeletonInstance->_getBoneMatrices(mBoneMatrices); - *mFrameBonesLastUpdated = currentFrameNumber; - - return true; - } - return false; - } - //----------------------------------------------------------------------- - void Entity::setDisplaySkeleton(bool display) - { - mDisplaySkeleton = display; - } - //----------------------------------------------------------------------- - bool Entity::getDisplaySkeleton(void) const - { - return mDisplaySkeleton; - } - //----------------------------------------------------------------------- - size_t Entity::getNumManualLodLevels(void) const - { -#if !OGRE_NO_MESHLOD - return mLodEntityList.size(); -#else - return 0; -#endif - } - - //----------------------------------------------------------------------- - Entity* Entity::getManualLodLevel(size_t index) const - { -#if !OGRE_NO_MESHLOD - assert(index < mLodEntityList.size()); - - return mLodEntityList[index]; -#else - OgreAssert(0, "This feature is disabled in ogre configuration!"); - return NULL; -#endif - } -#if !OGRE_NO_MESHLOD - //----------------------------------------------------------------------- - void Entity::setMeshLodBias(Real factor, ushort maxDetailIndex, ushort minDetailIndex) - { - mMeshLodFactorTransformed = mMesh->getLodStrategy()->transformBias(factor); - mMaxMeshLodIndex = maxDetailIndex; - mMinMeshLodIndex = minDetailIndex; - } -#endif - //----------------------------------------------------------------------- - void Entity::setMaterialLodBias(Real factor, ushort maxDetailIndex, ushort minDetailIndex) - { - mMaterialLodFactor = factor; - mMaxMaterialLodIndex = maxDetailIndex; - mMinMaterialLodIndex = minDetailIndex; - } - - //----------------------------------------------------------------------- - void Entity::buildSubEntityList(MeshPtr& mesh, SubEntityList* sublist) - { - // Create SubEntities - size_t i, numSubMeshes; - - numSubMeshes = mesh->getNumSubMeshes(); - for (i = 0; i < numSubMeshes; ++i) - { - SubMesh* subMesh = mesh->getSubMesh(i); - SubEntity* subEnt = OGRE_NEW SubEntity(this, subMesh); - if (subMesh->getMaterial()) - subEnt->setMaterial(subMesh->getMaterial()); - sublist->push_back(subEnt); - } - } - //----------------------------------------------------------------------- - void Entity::setPolygonModeOverrideable(bool overrideable) - { - for(auto *s : mSubEntityList) - { - s->setPolygonModeOverrideable(overrideable); - } - } - - //----------------------------------------------------------------------- - - struct MovableObjectNameExists { - const String& name; - bool operator()(const MovableObject* mo) { - return mo->getName() == name; - } - }; - - TagPoint* Entity::attachObjectToBone(const String &boneName, MovableObject *pMovable, const Quaternion &offsetOrientation, const Vector3 &offsetPosition) - { - MovableObjectNameExists pred = {pMovable->getName()}; - auto it = std::find_if(mChildObjectList.begin(), mChildObjectList.end(), pred); - if (it != mChildObjectList.end()) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "An object with the name " + pMovable->getName() + " already attached", - "Entity::attachObjectToBone"); - } - OgreAssert(!pMovable->isAttached(), "Object already attached to a sceneNode or a Bone"); - OgreAssert(hasSkeleton(), "This entity's mesh has no skeleton to attach object to"); - Bone* bone = mSkeletonInstance->getBone(boneName); - if (!bone) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot locate bone named " + boneName, - "Entity::attachObjectToBone"); - } - - TagPoint *tp = mSkeletonInstance->createTagPointOnBone( - bone, offsetOrientation, offsetPosition); - tp->setParentEntity(this); - tp->setChildObject(pMovable); - - attachObjectImpl(pMovable, tp); - - // Trigger update of bounding box if necessary - if (mParentNode) - mParentNode->needUpdate(); - - return tp; - } - - //----------------------------------------------------------------------- - void Entity::attachObjectImpl(MovableObject *pObject, TagPoint *pAttachingPoint) - { - assert(std::find_if(mChildObjectList.begin(), mChildObjectList.end(), - MovableObjectNameExists{pObject->getName()}) == mChildObjectList.end()); - - mChildObjectList.push_back(pObject); - pObject->_notifyAttached(pAttachingPoint, true); - } - - //----------------------------------------------------------------------- - MovableObject* Entity::detachObjectFromBone(const String &name) - { - MovableObjectNameExists pred = {name}; - auto it = std::find_if(mChildObjectList.begin(), mChildObjectList.end(), pred); - - if (it == mChildObjectList.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "No child object entry found named " + name, - "Entity::detachObjectFromBone"); - } - detachObjectImpl(*it); - std::swap(*it, mChildObjectList.back()); - mChildObjectList.pop_back(); - - // Trigger update of bounding box if necessary - if (mParentNode) - mParentNode->needUpdate(); - - return *it; - } - //----------------------------------------------------------------------- - void Entity::detachObjectFromBone(MovableObject* obj) - { - auto it = std::find(mChildObjectList.begin(), mChildObjectList.end(), obj); - OgreAssert(it != mChildObjectList.end(), "Object not attached to this entity"); - detachObjectImpl(*it); - std::swap(*it, mChildObjectList.back()); - mChildObjectList.pop_back(); - - // Trigger update of bounding box if necessary - if (mParentNode) - mParentNode->needUpdate(); - } - //----------------------------------------------------------------------- - void Entity::detachAllObjectsFromBone(void) - { - detachAllObjectsImpl(); - - // Trigger update of bounding box if necessary - if (mParentNode) - mParentNode->needUpdate(); - } - //----------------------------------------------------------------------- - void Entity::detachObjectImpl(MovableObject* pObject) - { - TagPoint* tp = static_cast(pObject->getParentNode()); - - // free the TagPoint so we can reuse it later - mSkeletonInstance->freeTagPoint(tp); - - pObject->_notifyAttached((TagPoint*)0); - } - //----------------------------------------------------------------------- - void Entity::detachAllObjectsImpl(void) - { - for (auto child : mChildObjectList) - { - detachObjectImpl(child); - } - mChildObjectList.clear(); - } - - //----------------------------------------------------------------------- - Entity::ChildObjectListIterator Entity::getAttachedObjectIterator() - { - return ChildObjectListIterator(mChildObjectList.begin(), mChildObjectList.end()); - } - //----------------------------------------------------------------------- - Real Entity::getBoundingRadius(void) const - { - return mMesh->getBoundingSphereRadius(); - } - //----------------------------------------------------------------------- - void Entity::prepareTempBlendBuffers(void) - { - mSkelAnimVertexData.reset(); - mSoftwareVertexAnimVertexData.reset(); - mHardwareVertexAnimVertexData.reset(); - - if (hasVertexAnimation()) - { - // Shared data - if (mMesh->sharedVertexData - && mMesh->getSharedVertexDataAnimationType() != VAT_NONE) - { - // Create temporary vertex blend info - // Prepare temp vertex data if needed - // Clone without copying data, don't remove any blending info - // (since if we skeletally animate too, we need it) - mSoftwareVertexAnimVertexData.reset(mMesh->sharedVertexData->clone(false)); - mTempVertexAnimInfo.extractFrom(mSoftwareVertexAnimVertexData.get()); - - // Also clone for hardware usage, don't remove blend info since we'll - // need it if we also hardware skeletally animate - mHardwareVertexAnimVertexData.reset(mMesh->sharedVertexData->clone(false)); - } - } - - if (hasSkeleton()) - { - // Shared data - if (mMesh->sharedVertexData) - { - // Create temporary vertex blend info - // Prepare temp vertex data if needed - // Clone without copying data, remove blending info - // (since blend is performed in software) - mSkelAnimVertexData.reset(mMesh->sharedVertexData->_cloneRemovingBlendData()); - mTempSkelAnimInfo.extractFrom(mSkelAnimVertexData.get()); - } - - } - - // Do SubEntities - for (auto *s : mSubEntityList) - { - s->prepareTempBlendBuffers(); - } - - // It's prepared for shadow volumes only if mesh has been prepared for shadow volumes. - mPreparedForShadowVolumes = mMesh->isPreparedForShadowVolumes(); - } - //----------------------------------------------------------------------- - EdgeData* Entity::getEdgeList(void) - { - // Get from Mesh - return mMesh->getEdgeList(mMeshLodIndex); - } - //----------------------------------------------------------------------- - bool Entity::isHardwareAnimationEnabled(void) - { - //find whether the entity has hardware animation for the current active sceme - unsigned short schemeIndex = MaterialManager::getSingleton()._getActiveSchemeIndex(); - for(const auto& p : mSchemeHardwareAnim) - { - if(p.first == schemeIndex) return p.second; - } - bool ret = calcVertexProcessing(); - mSchemeHardwareAnim.emplace_back(schemeIndex, ret); - return ret; - } - - //----------------------------------------------------------------------- - void Entity::reevaluateVertexProcessing(void) - { - //clear the cache so that the values will be reevaluated - mSchemeHardwareAnim.clear(); - } - //----------------------------------------------------------------------- - bool Entity::calcVertexProcessing(void) - { - // init - bool hasHardwareAnimation = false; - bool firstPass = true; - - for (auto *sub : mSubEntityList) - { - const MaterialPtr& m = sub->getMaterial(); - // Make sure it's loaded - m->load(); - Technique* t = m->getBestTechnique(0, sub); - if (!t) - { - // No supported techniques - continue; - } - if (t->getNumPasses() == 0) - { - // No passes, invalid - continue; - } - Pass* p = t->getPass(0); - if (p->hasVertexProgram()) - { - if (mVertexProgramInUse == false) - { - // If one material uses a vertex program, set this flag - // Causes some special processing like forcing a separate light cap - mVertexProgramInUse = true; - - // If shadow renderables already created create their light caps - ShadowRenderableList::iterator si = mShadowRenderables.begin(); - ShadowRenderableList::iterator siend = mShadowRenderables.end(); - for (si = mShadowRenderables.begin(); si != siend; ++si) - { - static_cast(*si)->_createSeparateLightCap(); - } - } - - if (hasSkeleton()) - { - // All materials must support skinning for us to consider using - // hardware animation - if one fails we use software - if (firstPass) - { - hasHardwareAnimation = p->getVertexProgram()->isSkeletalAnimationIncluded(); - firstPass = false; - } - else - { - hasHardwareAnimation = hasHardwareAnimation && - p->getVertexProgram()->isSkeletalAnimationIncluded(); - } - } - - VertexAnimationType animType = VAT_NONE; - if (sub->getSubMesh()->useSharedVertices) - { - animType = mMesh->getSharedVertexDataAnimationType(); - } - else - { - animType = sub->getSubMesh()->getVertexAnimationType(); - } - if (animType == VAT_MORPH) - { - // All materials must support morph animation for us to consider using - // hardware animation - if one fails we use software - if (firstPass) - { - hasHardwareAnimation = p->getVertexProgram()->isMorphAnimationIncluded(); - firstPass = false; - } - else - { - hasHardwareAnimation = hasHardwareAnimation && - p->getVertexProgram()->isMorphAnimationIncluded(); - } - } - else if (animType == VAT_POSE) - { - // All materials must support pose animation for us to consider using - // hardware animation - if one fails we use software - if (firstPass) - { - hasHardwareAnimation = p->getVertexProgram()->isPoseAnimationIncluded(); - if (sub->getSubMesh()->useSharedVertices) - mHardwarePoseCount = p->getVertexProgram()->getNumberOfPosesIncluded(); - else - sub->mHardwarePoseCount = p->getVertexProgram()->getNumberOfPosesIncluded(); - firstPass = false; - } - else - { - hasHardwareAnimation = hasHardwareAnimation && - p->getVertexProgram()->isPoseAnimationIncluded(); - if (sub->getSubMesh()->useSharedVertices) - mHardwarePoseCount = std::max(mHardwarePoseCount, - p->getVertexProgram()->getNumberOfPosesIncluded()); - else - sub->mHardwarePoseCount = std::max(sub->mHardwarePoseCount, - p->getVertexProgram()->getNumberOfPosesIncluded()); - } - } - - } - } - - // Should be force update of animation if they exists, due reevaluate - // vertex processing might switchs between hardware/software animation, - // and then we'll end with NULL or incorrect mBoneWorldMatrices, or - // incorrect blended software animation buffers. - if (mAnimationState) - { - mFrameAnimationLastUpdated = mAnimationState->getDirtyFrameNumber() - 1; - } - - return hasHardwareAnimation; - } - - //----------------------------------------------------------------------- - Real Entity::_getMeshLodFactorTransformed() const - { - return mMeshLodFactorTransformed; - } - //----------------------------------------------------------------------- - const ShadowRenderableList& - Entity::getShadowVolumeRenderableList(const Light* light, const HardwareIndexBufferPtr& indexBuffer, - size_t& indexBufferUsedSize, float extrusionDistance, int flags) - { - assert(indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT && - "Only 16-bit indexes supported for now"); - - // Check mesh state count, will be incremented if reloaded - if (mMesh->getStateCount() != mMeshStateCount) - { - // force reinitialise - _initialise(true); - } - -#if !OGRE_NO_MESHLOD - // Potentially delegate to LOD entity - if (mMesh->hasManualLodLevel() && mMeshLodIndex > 0) - { - // Use alternate entity - assert( static_cast< size_t >( mMeshLodIndex - 1 ) < mLodEntityList.size() && - "No LOD EntityList - did you build the manual LODs after creating the entity?"); - - Entity* requiredEntity = mLodEntityList[mMeshLodIndex-1]; - if (requiredEntity != this) { - // delegate, we're using manual LOD and not the top lod index - if (hasSkeleton() && mLodEntityList[mMeshLodIndex-1]->hasSkeleton()) - { - // Copy the animation state set to lod entity, we assume the lod - // entity only has a subset animation states - AnimationStateSet* targetState = mLodEntityList[mMeshLodIndex-1]->mAnimationState; - if (mAnimationState != targetState) // only copy if lods have different skeleton instances - { - if (mAnimationState && mAnimationState->getDirtyFrameNumber() != targetState->getDirtyFrameNumber()) // only copy if animation was updated - mAnimationState->copyMatchingState(targetState); - } - } - return mLodEntityList[mMeshLodIndex - 1]->getShadowVolumeRenderableList( - light, indexBuffer, indexBufferUsedSize, extrusionDistance, flags); - } - } -#endif - - // Prepare temp buffers if required - if (!mPreparedForShadowVolumes) - { - mMesh->prepareForShadowVolume(); - // reset frame last updated to force update of animations if they exist - if (mAnimationState) - mFrameAnimationLastUpdated = mAnimationState->getDirtyFrameNumber() - 1; - // re-prepare buffers - prepareTempBlendBuffers(); - } - - - bool hasAnimation = (hasSkeleton() || hasVertexAnimation()); - - // Update any animation - if (hasAnimation) - { - updateAnimation(); - } - - // Calculate the object space light details - Vector4 lightPos = light->getAs4DVector(); - Affine3 world2Obj = mParentNode->_getFullTransform().inverse(); - lightPos = world2Obj * lightPos; - Matrix3 world2Obj3x3 = world2Obj.linear(); - extrusionDistance *= Math::Sqrt(std::min(std::min(world2Obj3x3.GetColumn(0).squaredLength(), world2Obj3x3.GetColumn(1).squaredLength()), world2Obj3x3.GetColumn(2).squaredLength())); - - // We need to search the edge list for silhouette edges - EdgeData* edgeList = getEdgeList(); - - if (!edgeList) - { - // we can't get an edge list for some reason, return blank - // really we shouldn't be able to get here, but this is a safeguard - return mShadowRenderables; - } - - // Init shadow renderable list if required - bool init = mShadowRenderables.empty(); - - EdgeData::EdgeGroupList::iterator egi; - ShadowRenderableList::iterator si, siend; - if (init) - mShadowRenderables.resize(edgeList->edgeGroups.size()); - - bool isAnimated = hasAnimation; - bool updatedSharedGeomNormals = false; - bool extrude = flags & SRF_EXTRUDE_IN_SOFTWARE; - siend = mShadowRenderables.end(); - egi = edgeList->edgeGroups.begin(); - for (si = mShadowRenderables.begin(); si != siend; ++si, ++egi) - { - const VertexData *pVertData; - if (isAnimated) - { - // Use temp buffers - pVertData = findBlendedVertexData(egi->vertexData); - } - else - { - pVertData = egi->vertexData; - } - if (init) - { - // Try to find corresponding SubEntity; this allows the - // linkage of visibility between ShadowRenderable and SubEntity - SubEntity* subent = findSubEntityForVertexData(egi->vertexData); - // Create a new renderable, create a separate light cap if - // we're using a vertex program (either for this model, or - // for extruding the shadow volume) since otherwise we can - // get depth-fighting on the light cap - - *si = OGRE_NEW EntityShadowRenderable(this, indexBuffer, pVertData, - mVertexProgramInUse || !extrude, subent); - } - else - { - // If we have animation, we have no guarantee that the position - // buffer we used last frame is the same one we used last frame - // since a temporary buffer is requested each frame - // therefore, we need to update the EntityShadowRenderable - // with the current position buffer - static_cast(*si)->rebindPositionBuffer(pVertData, hasAnimation); - - } - // Get shadow renderable - HardwareVertexBufferSharedPtr esrPositionBuffer = (*si)->getPositionBuffer(); - // For animated entities we need to recalculate the face normals - if (hasAnimation) - { - if (egi->vertexData != mMesh->sharedVertexData || !updatedSharedGeomNormals) - { - // recalculate face normals - edgeList->updateFaceNormals(egi->vertexSet, esrPositionBuffer); - // If we're not extruding in software we still need to update - // the latter part of the buffer (the hardware extruded part) - // with the latest animated positions - if (!extrude) - { - // Lock, we'll be locking the (suppressed hardware update) shadow buffer - HardwareBufferLockGuard posLock(esrPositionBuffer, HardwareBuffer::HBL_NORMAL); - float* pSrc = static_cast(posLock.pData); - float* pDest = pSrc + (egi->vertexData->vertexCount * 3); - memcpy(pDest, pSrc, sizeof(float) * 3 * egi->vertexData->vertexCount); - } - if (egi->vertexData == mMesh->sharedVertexData) - { - updatedSharedGeomNormals = true; - } - } - } - // Extrude vertices in software if required - if (extrude) - { - extrudeVertices(esrPositionBuffer, - egi->vertexData->vertexCount, - lightPos, extrusionDistance); - - } - // Stop suppressing hardware update now, if we were - esrPositionBuffer->suppressHardwareUpdate(false); - - } - // Calc triangle light facing - updateEdgeListLightFacing(edgeList, lightPos); - - // Generate indexes and update renderables - generateShadowVolume(edgeList, indexBuffer, indexBufferUsedSize, light, mShadowRenderables, flags); - - return mShadowRenderables; - } - //----------------------------------------------------------------------- - const VertexData* Entity::findBlendedVertexData(const VertexData* orig) - { - bool skel = hasSkeleton(); - - if (orig == mMesh->sharedVertexData) - { - return skel? mSkelAnimVertexData.get() : mSoftwareVertexAnimVertexData.get(); - } - - for (auto *se : mSubEntityList) - { - if (orig == se->getSubMesh()->vertexData) - { - return skel? se->_getSkelAnimVertexData() : se->_getSoftwareVertexAnimVertexData(); - } - } - // None found - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Cannot find blended version of the vertex data specified.", - "Entity::findBlendedVertexData"); - } - //----------------------------------------------------------------------- - SubEntity* Entity::findSubEntityForVertexData(const VertexData* orig) - { - if (orig == mMesh->sharedVertexData) - { - return 0; - } - - for (auto *se : mSubEntityList) - { - if (orig == se->getSubMesh()->vertexData) - { - return se; - } - } - - // None found - return 0; - } - //----------------------------------------------------------------------- - void Entity::addSoftwareAnimationRequest(bool normalsAlso) - { - mSoftwareAnimationRequests++; - if (normalsAlso) { - mSoftwareAnimationNormalsRequests++; - } - } - //----------------------------------------------------------------------- - void Entity::removeSoftwareAnimationRequest(bool normalsAlso) - { - if (mSoftwareAnimationRequests == 0 || - (normalsAlso && mSoftwareAnimationNormalsRequests == 0)) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Attempt to remove nonexistent request.", - "Entity::removeSoftwareAnimationRequest"); - } - mSoftwareAnimationRequests--; - if (normalsAlso) { - mSoftwareAnimationNormalsRequests--; - } - } - //----------------------------------------------------------------------- - void Entity::_notifyAttached(Node* parent, bool isTagPoint) - { - MovableObject::_notifyAttached(parent, isTagPoint); -#if !OGRE_NO_MESHLOD - // Also notify LOD entities - for (auto *e : mLodEntityList) - { - if(e != this) - e->_notifyAttached(parent, isTagPoint); - } -#endif - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - Entity::EntityShadowRenderable::EntityShadowRenderable(MovableObject* parent, - const HardwareIndexBufferSharedPtr& indexBuffer, - const VertexData* vertexData, - bool createSeparateLightCap, SubEntity* subent, - bool isLightCap) - : ShadowRenderable(parent, indexBuffer, vertexData, false, isLightCap), mSubEntity(subent) - { - // Save link to vertex data - mCurrentVertexData = vertexData; - mOriginalPosBufferBinding = - vertexData->vertexDeclaration->findElementBySemantic(VES_POSITION)->getSource(); - if (!isLightCap && createSeparateLightCap) // we passed createSeparateLightCap=false to parent - { - _createSeparateLightCap(); - } - } - - //----------------------------------------------------------------------- - void Entity::EntityShadowRenderable::_createSeparateLightCap() - { - if (mLightCap == NULL) - { - // Create child light cap - mLightCap = OGRE_NEW EntityShadowRenderable(mParent, - mRenderOp.indexData->indexBuffer, mCurrentVertexData, false, mSubEntity, true); - } - } - //----------------------------------------------------------------------- - void Entity::EntityShadowRenderable::rebindPositionBuffer(const VertexData* vertexData, bool force) - { - if (force || mCurrentVertexData != vertexData) - { - mCurrentVertexData = vertexData; - mPositionBuffer = mCurrentVertexData->vertexBufferBinding->getBuffer( - mOriginalPosBufferBinding); - mRenderOp.vertexData->vertexBufferBinding->setBinding(0, mPositionBuffer); - if (mLightCap) - { - static_cast(mLightCap)->rebindPositionBuffer(vertexData, force); - } - } - } - //----------------------------------------------------------------------- - bool Entity::EntityShadowRenderable::isVisible(void) const - { - if (mSubEntity) - { - return mSubEntity->isVisible(); - } - else - { - return ShadowRenderable::isVisible(); - } - } - //----------------------------------------------------------------------- - void Entity::setRenderQueueGroup(uint8 queueID) - { - MovableObject::setRenderQueueGroup(queueID); -#if !OGRE_NO_MESHLOD - // Set render queue for all manual LOD entities - if (mMesh->hasManualLodLevel()) - { - for (auto *e : mLodEntityList) - { - if(e != this) - e->setRenderQueueGroup(queueID); - } - } -#endif - } - //----------------------------------------------------------------------- - void Entity::setRenderQueueGroupAndPriority(uint8 queueID, ushort priority) - { - MovableObject::setRenderQueueGroupAndPriority(queueID, priority); -#if !OGRE_NO_MESHLOD - // Set render queue for all manual LOD entities - if (mMesh->hasManualLodLevel()) - { - for (auto *e : mLodEntityList) - { - if(e != this) - e->setRenderQueueGroupAndPriority(queueID, priority); - } - } -#endif - } - //----------------------------------------------------------------------- - void Entity::shareSkeletonInstanceWith(Entity* entity) - { - OgreAssert(entity->getMesh()->getSkeleton() == getMesh()->getSkeleton(), - "The supplied entity has a different skeleton"); - OgreAssert(mSkeletonInstance, "This entity has no skeleton"); - OgreAssert(!mSharedSkeletonEntities || !entity->mSharedSkeletonEntities, - "Both entities already shares their SkeletonInstances! At least one of the instances " - "must not share it's instance"); - - //check if we already share our skeletoninstance, we don't want to delete it if so - if (mSharedSkeletonEntities != NULL) - { - entity->shareSkeletonInstanceWith(this); - } - else - { - OGRE_DELETE mSkeletonInstance; - OGRE_FREE_SIMD(mBoneMatrices, MEMCATEGORY_ANIMATION); - OGRE_DELETE mAnimationState; - // using OGRE_FREE since unsigned long is not a destructor - OGRE_FREE(mFrameBonesLastUpdated, MEMCATEGORY_ANIMATION); - mSkeletonInstance = entity->mSkeletonInstance; - mNumBoneMatrices = entity->mNumBoneMatrices; - mBoneMatrices = entity->mBoneMatrices; - mAnimationState = entity->mAnimationState; - mFrameBonesLastUpdated = entity->mFrameBonesLastUpdated; - if (entity->mSharedSkeletonEntities == NULL) - { - entity->mSharedSkeletonEntities = OGRE_NEW_T(EntitySet, MEMCATEGORY_ANIMATION)(); - entity->mSharedSkeletonEntities->insert(entity); - } - mSharedSkeletonEntities = entity->mSharedSkeletonEntities; - mSharedSkeletonEntities->insert(this); - } - } - //----------------------------------------------------------------------- - void Entity::stopSharingSkeletonInstance() - { - OgreAssert(mSharedSkeletonEntities, "This entity is not sharing it's skeletoninstance"); - //check if there's no other than us sharing the skeleton instance - if (mSharedSkeletonEntities->size() == 1) - { - //just reset - OGRE_DELETE_T(mSharedSkeletonEntities, EntitySet, MEMCATEGORY_ANIMATION); - mSharedSkeletonEntities = 0; - } - else - { - mSkeletonInstance = OGRE_NEW SkeletonInstance(mMesh->getSkeleton()); - mSkeletonInstance->load(); - mAnimationState = OGRE_NEW AnimationStateSet(); - mMesh->_initAnimationState(mAnimationState); - mFrameBonesLastUpdated = OGRE_ALLOC_T(unsigned long, 1, MEMCATEGORY_ANIMATION); - *mFrameBonesLastUpdated = std::numeric_limits::max(); - mNumBoneMatrices = mSkeletonInstance->getNumBones(); - mBoneMatrices = static_cast(OGRE_MALLOC_SIMD(sizeof(Affine3) * mNumBoneMatrices, MEMCATEGORY_ANIMATION)); - - mSharedSkeletonEntities->erase(this); - if (mSharedSkeletonEntities->size() == 1) - { - (*mSharedSkeletonEntities->begin())->stopSharingSkeletonInstance(); - } - mSharedSkeletonEntities = 0; - } - } - //----------------------------------------------------------------------- - void Entity::refreshAvailableAnimationState(void) - { - mMesh->_refreshAnimationState(mAnimationState); - } - //----------------------------------------------------------------------- - uint32 Entity::getTypeFlags(void) const - { - return SceneManager::ENTITY_TYPE_MASK; - } - //----------------------------------------------------------------------- - VertexData* Entity::getVertexDataForBinding(void) - { - Entity::VertexDataBindChoice c = - chooseVertexDataForBinding(mMesh->getSharedVertexDataAnimationType() != VAT_NONE); - switch(c) - { - case BIND_ORIGINAL: - return mMesh->sharedVertexData; - case BIND_HARDWARE_MORPH: - return mHardwareVertexAnimVertexData.get(); - case BIND_SOFTWARE_MORPH: - return mSoftwareVertexAnimVertexData.get(); - case BIND_SOFTWARE_SKELETAL: - return mSkelAnimVertexData.get(); - }; - // keep compiler happy - return mMesh->sharedVertexData; - } - //----------------------------------------------------------------------- - Entity::VertexDataBindChoice Entity::chooseVertexDataForBinding(bool vertexAnim) - { - if (hasSkeleton()) - { - if (!isHardwareAnimationEnabled()) - { - // all software skeletal binds same vertex data - // may be a 2-stage s/w transform including morph earlier though - return BIND_SOFTWARE_SKELETAL; - } - else if (vertexAnim) - { - // hardware morph animation - return BIND_HARDWARE_MORPH; - } - else - { - // hardware skeletal, no morphing - return BIND_ORIGINAL; - } - } - else if (vertexAnim) - { - // morph only, no skeletal - if (isHardwareAnimationEnabled()) - { - return BIND_HARDWARE_MORPH; - } - else - { - return BIND_SOFTWARE_MORPH; - } - - } - else - { - return BIND_ORIGINAL; - } - - } - //--------------------------------------------------------------------- - void Entity::visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables) - { - // Visit each SubEntity - for (auto& i : mSubEntityList) - { - visitor->visit(i, 0, false); - } -#if !OGRE_NO_MESHLOD - // if manual LOD is in use, visit those too - ushort lodi = 1; - for (LODEntityList::iterator e = mLodEntityList.begin(); - e != mLodEntityList.end(); ++e, ++lodi) - { - if(*e != this) { - size_t nsub = (*e)->getNumSubEntities(); - for (uint s = 0; s < nsub; ++s) - { - visitor->visit((*e)->getSubEntity(s), lodi, false); - } - } - } -#endif - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - const String MOT_ENTITY = "Entity"; - //----------------------------------------------------------------------- - const String& EntityFactory::getType(void) const - { - return MOT_ENTITY; - } - //----------------------------------------------------------------------- - MovableObject* EntityFactory::createInstanceImpl( const String& name, - const NameValuePairList* params) - { - // must have mesh parameter - MeshPtr pMesh; - if (params != 0) - { - String groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME; - - NameValuePairList::const_iterator ni; - - ni = params->find("resourceGroup"); - if (ni != params->end()) - { - groupName = ni->second; - } - - ni = params->find("mesh"); - if (ni != params->end()) - { - // Get mesh (load if required) - pMesh = MeshManager::getSingleton().load( - ni->second, - // autodetect group location - groupName ); - } - - } - if (!pMesh) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "'mesh' parameter required when constructing an Entity.", - "EntityFactory::createInstance"); - } - - return OGRE_NEW Entity(name, pMesh); - - } - //----------------------------------------------------------------------------- - //----------------------------------------------------------------------------- - //----------------------------------------------------------------------------- - Entity::TempBlendedBufferInfo::~TempBlendedBufferInfo(void) - { - // check that temp buffers have been released - if (destPositionBuffer) - destPositionBuffer->getManager()->releaseVertexBufferCopy(destPositionBuffer); - if (destNormalBuffer) - destNormalBuffer->getManager()->releaseVertexBufferCopy(destNormalBuffer); - - } - //----------------------------------------------------------------------------- - void Entity::TempBlendedBufferInfo::extractFrom(const VertexData* sourceData) - { - // Release old buffer copies first - if (destPositionBuffer) - { - destPositionBuffer->getManager()->releaseVertexBufferCopy(destPositionBuffer); - assert(!destPositionBuffer); - } - if (destNormalBuffer) - { - destNormalBuffer->getManager()->releaseVertexBufferCopy(destNormalBuffer); - assert(!destNormalBuffer); - } - - VertexDeclaration* decl = sourceData->vertexDeclaration; - VertexBufferBinding* bind = sourceData->vertexBufferBinding; - const VertexElement *posElem = decl->findElementBySemantic(VES_POSITION); - const VertexElement *normElem = decl->findElementBySemantic(VES_NORMAL); - - assert(posElem && "Positions are required"); - - posBindIndex = posElem->getSource(); - srcPositionBuffer = bind->getBuffer(posBindIndex); - srcNormalBuffer.reset(); - - if (!normElem) - { - posNormalShareBuffer = false; - posNormalExtraData = posElem->getSize() != srcPositionBuffer->getVertexSize(); - } - else - { - normBindIndex = normElem->getSource(); - if (normBindIndex == posBindIndex) - { - posNormalShareBuffer = true; - posNormalExtraData = (posElem->getSize() + normElem->getSize()) != srcPositionBuffer->getVertexSize(); - } - else - { - posNormalExtraData = false; - posNormalShareBuffer = false; - srcNormalBuffer = bind->getBuffer(normBindIndex); - } - } - } - //----------------------------------------------------------------------------- - void Entity::TempBlendedBufferInfo::checkoutTempCopies(bool positions, bool normals) - { - bindPositions = positions; - bindNormals = normals; - - if (positions && !destPositionBuffer) - { - destPositionBuffer = - srcPositionBuffer->getManager()->allocateVertexBufferCopy(srcPositionBuffer, this, posNormalExtraData); - } - if (normals && !posNormalShareBuffer && srcNormalBuffer && !destNormalBuffer) - { - destNormalBuffer = srcNormalBuffer->getManager()->allocateVertexBufferCopy(srcNormalBuffer, this); - } - } - //----------------------------------------------------------------------------- - bool Entity::TempBlendedBufferInfo::buffersCheckedOut(bool positions, bool normals) const - { - if (positions || (normals && posNormalShareBuffer)) - { - if (!destPositionBuffer) - return false; - - destPositionBuffer->getManager()->touchVertexBufferCopy(destPositionBuffer); - } - - if (normals && !posNormalShareBuffer) - { - if (!destNormalBuffer) - return false; - - destNormalBuffer->getManager()->touchVertexBufferCopy(destNormalBuffer); - } - - return true; - } - //----------------------------------------------------------------------------- - void Entity::TempBlendedBufferInfo::bindTempCopies(VertexData* targetData, bool suppressHardwareUpload) - { - this->destPositionBuffer->suppressHardwareUpdate(suppressHardwareUpload); - targetData->vertexBufferBinding->setBinding( - this->posBindIndex, this->destPositionBuffer); - if (bindNormals && !posNormalShareBuffer && destNormalBuffer) - { - this->destNormalBuffer->suppressHardwareUpdate(suppressHardwareUpload); - targetData->vertexBufferBinding->setBinding( - this->normBindIndex, this->destNormalBuffer); - } - } - //----------------------------------------------------------------------------- - void Entity::TempBlendedBufferInfo::licenseExpired(HardwareBuffer* buffer) - { - assert(buffer == destPositionBuffer.get() - || buffer == destNormalBuffer.get()); - - if (buffer == destPositionBuffer.get()) - destPositionBuffer.reset(); - if (buffer == destNormalBuffer.get()) - destNormalBuffer.reset(); - } -} diff --git a/OgreMain/src/OgreException.cpp b/OgreMain/src/OgreException.cpp deleted file mode 100644 index 1e4c5c5cc79..00000000000 --- a/OgreMain/src/OgreException.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#ifdef __BORLANDC__ - #include -#endif - -namespace Ogre { - - Exception::Exception(int num, const String& desc, const String& src) : - Exception(num, desc, src, "", "", 0) - { - } - - Exception::Exception(int num, const String& desc, const String& src, - const char* typ, const char* fil, long lin) : - line( lin ), - typeName(typ), - description( desc ), - source( src ), - file( fil ) - { - StringStream ss; - - ss << typeName << ": " - << description - << " in " << source; - - if( line > 0 ) - { - ss << " at " << file << " (line " << line << ")"; - } - - fullDesc = ss.str(); - } - - Exception::Exception(const Exception& rhs) - : line( rhs.line ), - typeName( rhs.typeName ), - description( rhs.description ), - source( rhs.source ), - file( rhs.file ) - { - } -} - diff --git a/OgreMain/src/OgreExternalTextureSource.cpp b/OgreMain/src/OgreExternalTextureSource.cpp deleted file mode 100644 index f15f990a55f..00000000000 --- a/OgreMain/src/OgreExternalTextureSource.cpp +++ /dev/null @@ -1,214 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -/*************************************************************************** -OgreExternalTextureSource.cpp - - Implementation of texture controller class - -------------------- -date : Jan 1 2004 -email : pjcast@yahoo.com -***************************************************************************/ - -#include "OgreStableHeaders.h" -#include "OgreExternalTextureSource.h" - -namespace Ogre -{ - //------------------------------------------------------------------------------// - /* Command objects for specifying some base features */ - /* Any Plugins wishing to add more specific params to "ExternalTextureSourcePlugins"*/ - /* dictionary, feel free to do so, that's why this is here */ - class _OgrePrivate CmdInputFileName : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - class _OgrePrivate CmdFPS : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - class _OgrePrivate CmdPlayMode : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - class _OgrePrivate CmdTecPassState : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - static CmdInputFileName msCmdInputFile; /// Command for setting input file name - static CmdFPS msCmdFramesPerSecond; /// Command for setting frames per second - static CmdPlayMode msCmdPlayMode; /// Command for setting play mode - static CmdTecPassState msCmdTecPassState; /// Command for setting the technique, pass, & state level - //---------------------------------------------------------------------------------------// - - ExternalTextureSource::ExternalTextureSource() : mTechniqueLevel(0), mPassLevel(0), mStateLevel(0) - { - mInputFileName = "None"; - mDictionaryName = "NotAssigned"; - mUpdateEveryFrame = false; - mFramesPerSecond = 24; - mMode = TextureEffectPause; - } - - //---------------------------------------------------------------------------------------// - - void ExternalTextureSource::addBaseParams() - { - if( mDictionaryName == "NotAssigned" ) - OGRE_EXCEPT(Exception::ERR_FILE_NOT_FOUND, - "Plugin " + mPluginName + - " needs to override default mDictionaryName", - "ExternalTextureSource::addBaseParams"); - - //Create Dictionary Here - if (createParamDictionary( mDictionaryName )) - { - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter(ParameterDef("filename", - "A source for the texture effect (only certain plugins require this)" - , PT_STRING), - &msCmdInputFile); - dict->addParameter(ParameterDef("frames_per_second", - "How fast should playback be (only certain plugins use this)" - , PT_INT), - &msCmdFramesPerSecond); - dict->addParameter(ParameterDef("play_mode", - "How the playback starts(only certain plugins use this)" - , PT_STRING), - &msCmdPlayMode); - dict->addParameter(ParameterDef("set_T_P_S", - "Set the technique, pass, and state level of this texture_unit (eg. 0 0 0 )" - , PT_STRING), - &msCmdTecPassState); - } - } - - //---------------------------------------------------------------------------------------// - //*** String Interface Command Class Definitions *****************************************/ - String CmdInputFileName::doGet(const void* target) const - { - return static_cast(target)->getInputName(); - } - void CmdInputFileName::doSet(void* target, const String& val) - { - static_cast(target)->setInputName( val ); - } - - //------------------------------------------------------------------------------// - String CmdFPS::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getFPS() ); - } - void CmdFPS::doSet(void* target, const String& val) - { - static_cast(target)->setFPS(StringConverter::parseInt(val)); - } - //------------------------------------------------------------------------------// - String CmdPlayMode::doGet(const void* target) const - { - eTexturePlayMode eMode = static_cast(target)->getPlayMode(); - String val; - - switch(eMode) - { - case TextureEffectPlay_ASAP: - val = "play"; - break; - case TextureEffectPlay_Looping: - val = "loop"; - break; - case TextureEffectPause: - val = "pause"; - break; - default: - val = "error"; - break; - } - - return val; - } - void CmdPlayMode::doSet(void* target, const String& val) - { - eTexturePlayMode eMode = TextureEffectPause; - - if( val == "play" ) - eMode = TextureEffectPlay_ASAP; - if( val == "loop" ) - eMode = TextureEffectPlay_Looping; - if( val == "pause" ) - eMode = TextureEffectPause; - - static_cast(target)->setPlayMode( eMode ); - } - - //------------------------------------------------------------------------------// - String CmdTecPassState::doGet(const void* target) const - { - int t = 0, p = 0, s = 0; - - static_cast(target)->getTextureTecPassStateLevel(t, p, s); - - String ret = StringConverter::toString( t ) + " " - + StringConverter::toString( p ) + " " - + StringConverter::toString( s ); - - return ret; - } - - void CmdTecPassState::doSet(void* target, const String& val) - { - int t = 0, p = 0, s = 0; - - StringVector vecparams = StringUtil::split(val, " \t"); - - if( vecparams.size() == 3 ) - { - t = StringConverter::parseInt( vecparams[0] ); - p = StringConverter::parseInt( vecparams[1] ); - s = StringConverter::parseInt( vecparams[2] ); - } - else - { - LogManager::getSingleton().logMessage("Texture controller had problems extracting technique, pass, and state level... Default to 0, 0, 0", LML_CRITICAL); - t = p = s = 0; - } - - static_cast(target)->setTextureTecPassStateLevel(t,p,s); - } -} - diff --git a/OgreMain/src/OgreExternalTextureSourceManager.cpp b/OgreMain/src/OgreExternalTextureSourceManager.cpp deleted file mode 100644 index 8a9782635be..00000000000 --- a/OgreMain/src/OgreExternalTextureSourceManager.cpp +++ /dev/null @@ -1,138 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -/*************************************************************************** -OgreExternalTextureSourceManager.cpp - - Implementation of the manager class - -------------------- -date : Jan 1 2004 -email : pjcast@yahoo.com -***************************************************************************/ - -#include "OgreStableHeaders.h" -#include "OgreExternalTextureSourceManager.h" - - -namespace Ogre -{ - //**************************************************************************************** - template<> ExternalTextureSourceManager* Singleton::msSingleton = 0; - ExternalTextureSourceManager* ExternalTextureSourceManager::getSingletonPtr(void) - { - return msSingleton; - } - ExternalTextureSourceManager& ExternalTextureSourceManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //**************************************************************************************** - - //**************************************************************************************** - ExternalTextureSourceManager::ExternalTextureSourceManager() - { - mCurrExternalTextureSource = 0; - } - - //**************************************************************************************** - ExternalTextureSourceManager::~ExternalTextureSourceManager() - { - mTextureSystems.clear(); - } - - //**************************************************************************************** - - void ExternalTextureSourceManager::setCurrentPlugIn( const String& sTexturePlugInType ) - { - TextureSystemList::iterator i; - - for( i = mTextureSystems.begin(); i != mTextureSystems.end(); ++i ) - { - if( i->first == sTexturePlugInType ) - { - mCurrExternalTextureSource = i->second; - mCurrExternalTextureSource->initialise(); //Now call overridden Init function - return; - } - } - mCurrExternalTextureSource = 0; - } - - //**************************************************************************************** - void ExternalTextureSourceManager::destroyAdvancedTexture( const String& sTextureName, - const String& groupName ) - { - for(auto& t : mTextureSystems) - { - //Broadcast to every registered System... Only the true one will destroy texture - t.second->destroyAdvancedTexture( sTextureName, groupName ); - } - } - - //**************************************************************************************** - void ExternalTextureSourceManager::setExternalTextureSource( const String& sTexturePlugInType, ExternalTextureSource* pTextureSystem ) - { - LogManager::getSingleton().logMessage( "Registering Texture Controller: Type = " - + sTexturePlugInType + " Name = " + pTextureSystem->getPluginStringName()); - - for(auto& t : mTextureSystems) - { - if( t.first == sTexturePlugInType ) - { - LogManager::getSingleton().logMessage( "Shutting Down Texture Controller: " - + t.second->getPluginStringName() - + " To be replaced by: " - + pTextureSystem->getPluginStringName()); - - t.second->shutDown(); //Only one plugIn of Sent Type can be registered at a time - //so shut down old plugin before starting new plugin - t.second = pTextureSystem; - // **Moved this line b/c Rendersystem needs to be selected before things - // such as framelistners can be added - // pTextureSystem->Initialise(); - return; - } - } - mTextureSystems[sTexturePlugInType] = pTextureSystem; //If we got here then add it to map - } - - //**************************************************************************************** - ExternalTextureSource* ExternalTextureSourceManager::getExternalTextureSource( const String& sTexturePlugInType ) - { - for(auto& t : mTextureSystems) - { - if(t.first == sTexturePlugInType) - return t.second; - } - return 0; - } - - //**************************************************************************************** - -} //End Ogre Namespace - diff --git a/OgreMain/src/OgreFileSystem.cpp b/OgreMain/src/OgreFileSystem.cpp deleted file mode 100644 index 57689658007..00000000000 --- a/OgreMain/src/OgreFileSystem.cpp +++ /dev/null @@ -1,572 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include - -#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_APPLE || \ - OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS || \ - OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || \ - OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN -# include "OgreSearchOps.h" -# include -#endif - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT -# define WIN32_LEAN_AND_MEAN -# if !defined(NOMINMAX) && defined(_MSC_VER) -# define NOMINMAX // required to stop windows.h messing up std::min -# endif -# include -# include -# include -//# define _OGRE_FILESYSTEM_ARCHIVE_UNICODE // base path and resources subpathes expected to be in UTF-8 and wchar_t file IO routines are used -#endif - -namespace Ogre { - -namespace { - /** Specialisation of the Archive class to allow reading of files from - filesystem folders / directories. - */ - class FileSystemArchive : public Archive - { - protected: - /** Utility method to retrieve all files in a directory matching pattern. - @param pattern - File pattern. - @param recursive - Whether to cascade down directories. - @param dirs - Set to @c true if you want the directories to be listed instead of files. - @param simpleList - Populated if retrieving a simple list. - @param detailList - Populated if retrieving a detailed list. - */ - void findFiles(const String& pattern, bool recursive, bool dirs, - StringVector* simpleList, FileInfoList* detailList) const; - - OGRE_AUTO_MUTEX; - public: - FileSystemArchive(const String& name, const String& archType, bool readOnly ); - ~FileSystemArchive(); - - /// @copydoc Archive::isCaseSensitive - bool isCaseSensitive(void) const override; - - /// @copydoc Archive::load - void load() override; - /// @copydoc Archive::unload - void unload() override; - - /// @copydoc Archive::open - DataStreamPtr open(const String& filename, bool readOnly = true) const override; - - /// @copydoc Archive::create - DataStreamPtr create(const String& filename) override; - - /// @copydoc Archive::remove - void remove(const String& filename) override; - - /// @copydoc Archive::list - StringVectorPtr list(bool recursive = true, bool dirs = false) const override; - - /// @copydoc Archive::listFileInfo - FileInfoListPtr listFileInfo(bool recursive = true, bool dirs = false) const override; - - /// @copydoc Archive::find - StringVectorPtr find(const String& pattern, bool recursive = true, - bool dirs = false) const override; - - /// @copydoc Archive::findFileInfo - FileInfoListPtr findFileInfo(const String& pattern, bool recursive = true, - bool dirs = false) const override; - - /// @copydoc Archive::exists - bool exists(const String& filename) const override; - - /// @copydoc Archive::getModifiedTime - time_t getModifiedTime(const String& filename) const override; - }; - - bool gIgnoreHidden = true; -} - - //----------------------------------------------------------------------- - FileSystemArchive::FileSystemArchive(const String& name, const String& archType, bool readOnly ) - : Archive(name, archType) - { - // Even failed attempt to write to read only location violates Apple AppStore validation process. - // And successful writing to some probe file does not prove that whole location with subfolders - // is writable. Therefore we accept read only flag from outside and do not try to be too smart. - mReadOnly = readOnly; - } - //----------------------------------------------------------------------- - bool FileSystemArchive::isCaseSensitive(void) const - { - #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT - return false; - #else - return true; - #endif - - } - //----------------------------------------------------------------------- -#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE - static bool is_reserved_dir (const wchar_t *fn) -#else - static bool is_reserved_dir (const char *fn) -#endif - { - return (fn [0] == '.' && (fn [1] == 0 || (fn [1] == '.' && fn [2] == 0))); - } - //----------------------------------------------------------------------- - static bool is_absolute_path(const char* path) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT - if (isalpha(uchar(path[0])) && path[1] == ':') - return true; -#endif - return path[0] == '/' || path[0] == '\\'; - } - //----------------------------------------------------------------------- - static String concatenate_path(const String& base, const String& name) - { - if (base.empty() || is_absolute_path(name.c_str())) - return name; - else - return base + '/' + name; - } - //----------------------------------------------------------------------- -#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE - static std::wstring to_wpath(const String& text, unsigned codepage = CP_UTF8) - { - const int utf16Length = ::MultiByteToWideChar(codepage, 0, text.c_str(), (int)text.size(), NULL, 0); - if(utf16Length > 0) - { - std::wstring wt; - wt.resize(utf16Length); - if(0 != ::MultiByteToWideChar(codepage, 0, text.c_str(), (int)text.size(), &wt[0], (int)wt.size())) - return wt; - } - return L""; - } - static String from_wpath(const std::wstring& text, unsigned codepage = CP_UTF8) - { - const int length = ::WideCharToMultiByte(codepage, 0, text.c_str(), (int)text.size(), NULL, 0, NULL, NULL); - if(length > 0) - { - String str; - str.resize(length); - if(0 != ::WideCharToMultiByte(codepage, 0, text.c_str(), (int)text.size(), &str[0], (int)str.size(), NULL, NULL)) - return str; - } - return ""; - } -#endif - //----------------------------------------------------------------------- - void FileSystemArchive::findFiles(const String& pattern, bool recursive, - bool dirs, StringVector* simpleList, FileInfoList* detailList) const - { - intptr_t lHandle, res; -#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE - struct _wfinddata_t tagData; -#else - struct _finddata_t tagData; -#endif - - // pattern can contain a directory name, separate it from mask - size_t pos1 = pattern.rfind ('/'); - size_t pos2 = pattern.rfind ('\\'); - if (pos1 == pattern.npos || ((pos2 != pattern.npos) && (pos1 < pos2))) - pos1 = pos2; - String directory; - if (pos1 != pattern.npos) - directory = pattern.substr (0, pos1 + 1); - - String full_pattern = concatenate_path(mName, pattern); - -#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE - lHandle = _wfindfirst(to_wpath(full_pattern).c_str(), &tagData); -#else - lHandle = _findfirst(full_pattern.c_str(), &tagData); -#endif - res = 0; - while (lHandle != -1 && res != -1) - { - if ((dirs == ((tagData.attrib & _A_SUBDIR) != 0)) && - ( !gIgnoreHidden || (tagData.attrib & _A_HIDDEN) == 0 ) && - (!dirs || !is_reserved_dir (tagData.name))) - { - if (simpleList) - { -#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE - simpleList->push_back(directory + from_wpath(tagData.name)); -#else - simpleList->push_back(directory + tagData.name); -#endif - } - else if (detailList) - { - FileInfo fi; - fi.archive = this; -#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE - fi.filename = directory + from_wpath(tagData.name); - fi.basename = from_wpath(tagData.name); -#else - fi.filename = directory + tagData.name; - fi.basename = tagData.name; -#endif - fi.path = directory; - fi.compressedSize = tagData.size; - fi.uncompressedSize = tagData.size; - detailList->push_back(fi); - } - } -#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE - res = _wfindnext( lHandle, &tagData ); -#else - res = _findnext( lHandle, &tagData ); -#endif - } - // Close if we found any files - if(lHandle != -1) - _findclose(lHandle); - - // Now find directories - if (recursive) - { - String base_dir = mName; - if (!directory.empty ()) - { - base_dir = concatenate_path(mName, directory); - // Remove the last '/' - base_dir.erase (base_dir.length () - 1); - } - base_dir.append ("/*"); - - // Remove directory name from pattern - String mask ("/"); - if (pos1 != pattern.npos) - mask.append (pattern.substr (pos1 + 1)); - else - mask.append (pattern); - -#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE - lHandle = _wfindfirst(to_wpath(base_dir).c_str(), &tagData); -#else - lHandle = _findfirst(base_dir.c_str (), &tagData); -#endif - res = 0; - while (lHandle != -1 && res != -1) - { - if ((tagData.attrib & _A_SUBDIR) && - ( !gIgnoreHidden || (tagData.attrib & _A_HIDDEN) == 0 ) && - !is_reserved_dir (tagData.name)) - { - // recurse - base_dir = directory; -#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE - base_dir.append (from_wpath(tagData.name)).append (mask); -#else - base_dir.append (tagData.name).append (mask); -#endif - findFiles(base_dir, recursive, dirs, simpleList, detailList); - } -#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE - res = _wfindnext( lHandle, &tagData ); -#else - res = _findnext( lHandle, &tagData ); -#endif - } - // Close if we found any files - if(lHandle != -1) - _findclose(lHandle); - } - } - //----------------------------------------------------------------------- - FileSystemArchive::~FileSystemArchive() - { - unload(); - } - //----------------------------------------------------------------------- - void FileSystemArchive::load() - { - // nothing to do here - } - //----------------------------------------------------------------------- - void FileSystemArchive::unload() - { - // nothing to see here, move along - } - //----------------------------------------------------------------------- - DataStreamPtr FileSystemArchive::open(const String& filename, bool readOnly) const - { - if (!readOnly && isReadOnly()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot open a file in read-write mode in a read-only archive"); - } - - // Always open in binary mode - // Also, always include reading - std::ios::openmode mode = std::ios::in | std::ios::binary; - - if(!readOnly) mode |= std::ios::out; - - return _openFileStream(concatenate_path(mName, filename), mode, filename); - } - DataStreamPtr _openFileStream(const String& full_path, std::ios::openmode mode, const String& name) - { - // Use filesystem to determine size - // (quicker than streaming to the end and back) -#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE - struct _stat64i32 tagStat; - int ret = _wstat(to_wpath(full_path).c_str(), &tagStat); -#else - struct stat tagStat; - int ret = stat(full_path.c_str(), &tagStat); -#endif - size_t st_size = ret == 0 ? tagStat.st_size : 0; - - std::istream* baseStream = 0; - std::ifstream* roStream = 0; - std::fstream* rwStream = 0; - - if (mode & std::ios::out) - { - rwStream = OGRE_NEW_T(std::fstream, MEMCATEGORY_GENERAL)(); -#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE - rwStream->open(to_wpath(full_path).c_str(), mode); -#else - rwStream->open(full_path.c_str(), mode); -#endif - baseStream = rwStream; - } - else - { - roStream = OGRE_NEW_T(std::ifstream, MEMCATEGORY_GENERAL)(); -#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE - roStream->open(to_wpath(full_path).c_str(), mode); -#else - roStream->open(full_path.c_str(), mode); -#endif - baseStream = roStream; - } - - - // Should check ensure open succeeded, in case fail for some reason. - if (baseStream->fail()) - { - OGRE_DELETE_T(roStream, basic_ifstream, MEMCATEGORY_GENERAL); - OGRE_DELETE_T(rwStream, basic_fstream, MEMCATEGORY_GENERAL); - OGRE_EXCEPT(Exception::ERR_FILE_NOT_FOUND, "Cannot open file: " + full_path); - } - - /// Construct return stream, tell it to delete on destroy - FileStreamDataStream* stream = 0; - const String& streamname = name.empty() ? full_path : name; - if (rwStream) - { - // use the writeable stream - stream = OGRE_NEW FileStreamDataStream(streamname, rwStream, st_size); - } - else - { - OgreAssertDbg(ret == 0, "Problem getting file size"); - // read-only stream - stream = OGRE_NEW FileStreamDataStream(streamname, roStream, st_size); - } - return DataStreamPtr(stream); - } - //--------------------------------------------------------------------- - DataStreamPtr FileSystemArchive::create(const String& filename) - { - if (isReadOnly()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot create a file in a read-only archive"); - } - - String full_path = concatenate_path(mName, filename); - - // Always open in binary mode - // Also, always include reading - std::ios::openmode mode = std::ios::out | std::ios::binary; - std::fstream* rwStream = OGRE_NEW_T(std::fstream, MEMCATEGORY_GENERAL)(); -#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE - rwStream->open(to_wpath(full_path).c_str(), mode); -#else - rwStream->open(full_path.c_str(), mode); -#endif - - // Should check ensure open succeeded, in case fail for some reason. - if (rwStream->fail()) - { - OGRE_DELETE_T(rwStream, basic_fstream, MEMCATEGORY_GENERAL); - OGRE_EXCEPT(Exception::ERR_FILE_NOT_FOUND, "Cannot open file: " + filename); - } - - /// Construct return stream, tell it to delete on destroy - FileStreamDataStream* stream = OGRE_NEW FileStreamDataStream(filename, - rwStream, 0, true); - - return DataStreamPtr(stream); - } - //--------------------------------------------------------------------- - void FileSystemArchive::remove(const String& filename) - { - if (isReadOnly()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot remove a file from a read-only archive"); - } - String full_path = concatenate_path(mName, filename); -#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE - ::_wremove(to_wpath(full_path).c_str()); -#else - ::remove(full_path.c_str()); -#endif - } - //----------------------------------------------------------------------- - StringVectorPtr FileSystemArchive::list(bool recursive, bool dirs) const - { - // directory change requires locking due to saved returns - auto ret = std::make_shared(); - - findFiles("*", recursive, dirs, ret.get(), 0); - - return ret; - } - //----------------------------------------------------------------------- - FileInfoListPtr FileSystemArchive::listFileInfo(bool recursive, bool dirs) const - { - auto ret = std::make_shared(); - - findFiles("*", recursive, dirs, 0, ret.get()); - - return ret; - } - //----------------------------------------------------------------------- - StringVectorPtr FileSystemArchive::find(const String& pattern, - bool recursive, bool dirs) const - { - auto ret = std::make_shared(); - - findFiles(pattern, recursive, dirs, ret.get(), 0); - - return ret; - - } - //----------------------------------------------------------------------- - FileInfoListPtr FileSystemArchive::findFileInfo(const String& pattern, - bool recursive, bool dirs) const - { - auto ret = std::make_shared(); - - findFiles(pattern, recursive, dirs, 0, ret.get()); - - return ret; - } - //----------------------------------------------------------------------- - bool FileSystemArchive::exists(const String& filename) const - { - if (filename.empty()) - return false; - - String full_path = concatenate_path(mName, filename); - -#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE - struct _stat64i32 tagStat; - bool ret = (_wstat(to_wpath(full_path).c_str(), &tagStat) == 0); -#else - struct stat tagStat; - bool ret = (stat(full_path.c_str(), &tagStat) == 0); -#endif - - // stat will return true if the filename is absolute, but we need to check - // the file is actually in this archive - if (ret && is_absolute_path(filename.c_str())) - { - // only valid if full path starts with our base -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT - // case insensitive on windows - String lowerCaseName = mName; - StringUtil::toLowerCase(lowerCaseName); - ret = Ogre::StringUtil::startsWith(full_path, lowerCaseName, true); -#else - // case sensitive - ret = Ogre::StringUtil::startsWith(full_path, mName, false); -#endif - } - - return ret; - } - //--------------------------------------------------------------------- - time_t FileSystemArchive::getModifiedTime(const String& filename) const - { - String full_path = concatenate_path(mName, filename); - -#ifdef _OGRE_FILESYSTEM_ARCHIVE_UNICODE - struct _stat64i32 tagStat; - bool ret = (_wstat(to_wpath(full_path).c_str(), &tagStat) == 0); -#else - struct stat tagStat; - bool ret = (stat(full_path.c_str(), &tagStat) == 0); -#endif - - if (ret) - { - return tagStat.st_mtime; - } - else - { - return 0; - } - - } - //----------------------------------------------------------------------- - const String& FileSystemArchiveFactory::getType(void) const - { - static String name = "FileSystem"; - return name; - } - - Archive *FileSystemArchiveFactory::createInstance( const String& name, bool readOnly ) - { - return OGRE_NEW FileSystemArchive(name, getType(), readOnly); - } - - void FileSystemArchiveFactory::setIgnoreHidden(bool ignore) - { - gIgnoreHidden = ignore; - } - - bool FileSystemArchiveFactory::getIgnoreHidden() - { - return gIgnoreHidden; - } -} diff --git a/OgreMain/src/OgreFileSystemLayerNoOp.cpp b/OgreMain/src/OgreFileSystemLayerNoOp.cpp deleted file mode 100644 index 7cab4058b26..00000000000 --- a/OgreMain/src/OgreFileSystemLayerNoOp.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#include "OgreFileSystemLayer.h" - -namespace Ogre -{ - String FileSystemLayer::resolveBundlePath(String path) - { - return path; - } - //--------------------------------------------------------------------- - void FileSystemLayer::getConfigPaths() - { - } - //--------------------------------------------------------------------- - void FileSystemLayer::prepareUserHome(const Ogre::String& subdir) - { - } - //--------------------------------------------------------------------- - bool FileSystemLayer::fileExists(const Ogre::String& path) - { - return false; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::removeDirectory(const Ogre::String& path) - { - return false; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::removeFile(const Ogre::String& path) - { - return false; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::renameFile(const Ogre::String& oldname, const Ogre::String& newname) - { - return false; - } -} diff --git a/OgreMain/src/OgreFrustum.cpp b/OgreMain/src/OgreFrustum.cpp deleted file mode 100644 index 81b61c2c33d..00000000000 --- a/OgreMain/src/OgreFrustum.cpp +++ /dev/null @@ -1,1112 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreMovablePlane.h" - -namespace Ogre { - - const String MOT_FRUSTUM = "Frustum"; - const String MOT_FRUSTRUM = MOT_FRUSTUM; - const Real Frustum::INFINITE_FAR_PLANE_ADJUST = 0.00001; - //----------------------------------------------------------------------- - Frustum::Frustum(const String& name) : - mFOVy(Radian(Math::PI/4.0f)), - mFarDist(100000.0f), - mNearDist(100.0f), - mAspect(1.33333333333333f), - mOrthoHeight(1000), - mFrustumOffset(Vector2::ZERO), - mFocalLength(1.0f), - mLastParentOrientation(Quaternion::IDENTITY), - mLastParentPosition(Vector3::ZERO), - mRecalcFrustum(true), - mRecalcView(true), - mRecalcFrustumPlanes(true), - mRecalcWorldSpaceCorners(true), - mCustomViewMatrix(false), - mCustomProjMatrix(false), - mFrustumExtentsManuallySet(false), - mProjType(PT_PERSPECTIVE), - mLinkedReflectPlane(0), - mLinkedObliqueProjPlane(0), - mReflect(false), - mObliqueDepthProjection(false) - { - // Alter superclass members - mVisible = false; - mParentNode = 0; - mName = name; - - mLastLinkedReflectionPlane.normal = Vector3::ZERO; - mLastLinkedObliqueProjPlane.normal = Vector3::ZERO; - - updateView(); - updateFrustum(); - } - - //----------------------------------------------------------------------- - Frustum::~Frustum() - { - // Do nothing - } - - //----------------------------------------------------------------------- - void Frustum::setFOVy(const Radian& fov) - { - mFOVy = fov; - invalidateFrustum(); - } - - //----------------------------------------------------------------------- - const Radian& Frustum::getFOVy(void) const - { - return mFOVy; - } - - - //----------------------------------------------------------------------- - void Frustum::setFarClipDistance(Real farPlane) - { - mFarDist = farPlane; - invalidateFrustum(); - } - - //----------------------------------------------------------------------- - Real Frustum::getFarClipDistance(void) const - { - return mFarDist; - } - - //----------------------------------------------------------------------- - void Frustum::setNearClipDistance(Real nearPlane) - { - OgreAssert(nearPlane > 0, "Invalid clip distance"); - mNearDist = nearPlane; - invalidateFrustum(); - } - - //----------------------------------------------------------------------- - Real Frustum::getNearClipDistance(void) const - { - return mNearDist; - } - - //--------------------------------------------------------------------- - void Frustum::setFrustumOffset(const Vector2& offset) - { - mFrustumOffset = offset; - invalidateFrustum(); - } - //--------------------------------------------------------------------- - void Frustum::setFrustumOffset(Real horizontal, Real vertical) - { - setFrustumOffset(Vector2(horizontal, vertical)); - } - //--------------------------------------------------------------------- - const Vector2& Frustum::getFrustumOffset() const - { - return mFrustumOffset; - } - //--------------------------------------------------------------------- - void Frustum::setFocalLength(Real focalLength) - { - OgreAssert(focalLength > 0, "Invalid focal length"); - mFocalLength = focalLength; - invalidateFrustum(); - } - //--------------------------------------------------------------------- - Real Frustum::getFocalLength() const - { - return mFocalLength; - } - //----------------------------------------------------------------------- - const Matrix4& Frustum::getProjectionMatrix(void) const - { - - updateFrustum(); - - return mProjMatrix; - } - //----------------------------------------------------------------------- - const Matrix4& Frustum::getProjectionMatrixWithRSDepth(void) const - { - - updateFrustum(); - - return mProjMatrixRSDepth; - } - //----------------------------------------------------------------------- - const Affine3& Frustum::getViewMatrix(void) const - { - updateView(); - - return mViewMatrix; - - } - - //----------------------------------------------------------------------- - const Plane* Frustum::getFrustumPlanes(void) const - { - // Make any pending updates to the calculated frustum planes - updateFrustumPlanes(); - - return mFrustumPlanes; - } - - //----------------------------------------------------------------------- - const Plane& Frustum::getFrustumPlane(unsigned short plane) const - { - // Make any pending updates to the calculated frustum planes - updateFrustumPlanes(); - - return mFrustumPlanes[plane]; - - } - - //----------------------------------------------------------------------- - bool Frustum::isVisible(const AxisAlignedBox& bound, FrustumPlane* culledBy) const - { - // Null boxes always invisible - if (bound.isNull()) return false; - - // Infinite boxes always visible - if (bound.isInfinite()) return true; - - // Make any pending updates to the calculated frustum planes - updateFrustumPlanes(); - - // Get centre of the box - Vector3 centre = bound.getCenter(); - // Get the half-size of the box - Vector3 halfSize = bound.getHalfSize(); - - // For each plane, see if all points are on the negative side - // If so, object is not visible - for (int plane = 0; plane < 6; ++plane) - { - // Skip far plane if infinite view frustum - if (plane == FRUSTUM_PLANE_FAR && mFarDist == 0) - continue; - - Plane::Side side = mFrustumPlanes[plane].getSide(centre, halfSize); - if (side == Plane::NEGATIVE_SIDE) - { - // ALL corners on negative side therefore out of view - if (culledBy) - *culledBy = (FrustumPlane)plane; - return false; - } - - } - - return true; - } - - //----------------------------------------------------------------------- - bool Frustum::isVisible(const Vector3& vert, FrustumPlane* culledBy) const - { - // Make any pending updates to the calculated frustum planes - updateFrustumPlanes(); - - // For each plane, see if all points are on the negative side - // If so, object is not visible - for (int plane = 0; plane < 6; ++plane) - { - // Skip far plane if infinite view frustum - if (plane == FRUSTUM_PLANE_FAR && mFarDist == 0) - continue; - - if (mFrustumPlanes[plane].getSide(vert) == Plane::NEGATIVE_SIDE) - { - // ALL corners on negative side therefore out of view - if (culledBy) - *culledBy = (FrustumPlane)plane; - return false; - } - - } - - return true; - } - //----------------------------------------------------------------------- - bool Frustum::isVisible(const Sphere& sphere, FrustumPlane* culledBy) const - { - // Make any pending updates to the calculated frustum planes - updateFrustumPlanes(); - - // For each plane, see if sphere is on negative side - // If so, object is not visible - for (int plane = 0; plane < 6; ++plane) - { - // Skip far plane if infinite view frustum - if (plane == FRUSTUM_PLANE_FAR && mFarDist == 0) - continue; - - // If the distance from sphere center to plane is negative, and 'more negative' - // than the radius of the sphere, sphere is outside frustum - if (mFrustumPlanes[plane].getDistance(sphere.getCenter()) < -sphere.getRadius()) - { - // ALL corners on negative side therefore out of view - if (culledBy) - *culledBy = (FrustumPlane)plane; - return false; - } - - } - - return true; - } - //--------------------------------------------------------------------- - uint32 Frustum::getTypeFlags(void) const - { - return SceneManager::FRUSTUM_TYPE_MASK; - } - //----------------------------------------------------------------------- - RealRect Frustum::calcProjectionParameters() const - { - if (mCustomProjMatrix) - { - // Convert clipspace corners to camera space - Matrix4 invProj = mProjMatrix.inverse(); - Vector4 topLeft(-1.0f, 1.0f, -1.0f, 1.0f); - Vector4 bottomRight(1.0f, -1.0f, -1.0f, 1.0f); - - topLeft = invProj * topLeft; - bottomRight = invProj * bottomRight; - - topLeft /= topLeft.w; - bottomRight /= bottomRight.w; - - mExtents = RealRect(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y); - } - else - { - if (mFrustumExtentsManuallySet) - { - return mExtents; - } - // Calculate general projection parameters - else if (mProjType == PT_PERSPECTIVE) - { - Radian thetaY (mFOVy * 0.5f); - Real tanThetaY = Math::Tan(thetaY); - Real tanThetaX = tanThetaY * mAspect; - - Real nearFocal = mNearDist / mFocalLength; - Real nearOffsetX = mFrustumOffset.x * nearFocal; - Real nearOffsetY = mFrustumOffset.y * nearFocal; - Real half_w = tanThetaX * mNearDist; - Real half_h = tanThetaY * mNearDist; - - mExtents = RealRect(-half_w + nearOffsetX, +half_h + nearOffsetY, - +half_w + nearOffsetX, -half_h + nearOffsetY); - } - else - { - // Unknown how to apply frustum offset to orthographic camera, just ignore here - Real half_w = getOrthoWindowWidth() * 0.5f; - Real half_h = getOrthoWindowHeight() * 0.5f; - - mExtents = RealRect(-half_w, +half_h, +half_w, -half_h); - } - } - - return mExtents; - } - //----------------------------------------------------------------------- - void Frustum::updateFrustumImpl(void) const - { - // Common calcs - RealRect rect = calcProjectionParameters(); - Real left = rect.left, right = rect.right, top = rect.top, bottom = rect.bottom; - - if (!mCustomProjMatrix) - { - // Recalc if frustum params changed - if (mProjType == PT_PERSPECTIVE) - { - mProjMatrix = Math::makePerspectiveMatrix(left, right, bottom, top, mNearDist, mFarDist); - - if (mObliqueDepthProjection) - { - // Translate the plane into view space - - // Don't use getViewMatrix here, incase overrided by - // camera and return a cull frustum view matrix - updateView(); - Plane plane = mViewMatrix * mObliqueProjPlane; - - // Thanks to Eric Lenyel for posting this calculation - // at www.terathon.com - - // Calculate the clip-space corner point opposite the - // clipping plane - // as (sgn(clipPlane.x), sgn(clipPlane.y), 1, 1) and - // transform it into camera space by multiplying it - // by the inverse of the projection matrix - - /* generalised version - Vector4 q = matrix.inverse() * - Vector4(Math::Sign(plane.normal.x), - Math::Sign(plane.normal.y), 1.0f, 1.0f); - */ - Vector4 qVec; - qVec.x = (Math::Sign(plane.normal.x) + mProjMatrix[0][2]) / mProjMatrix[0][0]; - qVec.y = (Math::Sign(plane.normal.y) + mProjMatrix[1][2]) / mProjMatrix[1][1]; - qVec.z = -1; - qVec.w = (1 + mProjMatrix[2][2]) / mProjMatrix[2][3]; - - // Calculate the scaled plane vector - Vector4 clipPlane4d(plane.normal.x, plane.normal.y, plane.normal.z, plane.d); - Vector4 c = clipPlane4d * (2 / (clipPlane4d.dotProduct(qVec))); - - // Replace the third row of the projection matrix - mProjMatrix[2][0] = c.x; - mProjMatrix[2][1] = c.y; - mProjMatrix[2][2] = c.z + 1; - mProjMatrix[2][3] = c.w; - } - } // perspective - else if (mProjType == PT_ORTHOGRAPHIC) - { - // The code below will dealing with general projection - // parameters, similar glOrtho. - // Doesn't optimise manually except division operator, so the - // code more self-explaining. - - Real inv_w = 1 / (right - left); - Real inv_h = 1 / (top - bottom); - Real inv_d = 1 / (mFarDist - mNearDist); - - Real A = 2 * inv_w; - Real B = 2 * inv_h; - Real C = - (right + left) * inv_w; - Real D = - (top + bottom) * inv_h; - Real q, qn; - if (mFarDist == 0) - { - // Can not do infinite far plane here, avoid divided zero only - q = - Frustum::INFINITE_FAR_PLANE_ADJUST / mNearDist; - qn = - Frustum::INFINITE_FAR_PLANE_ADJUST - 1; - } - else - { - q = - 2 * inv_d; - qn = - (mFarDist + mNearDist) * inv_d; - } - - // NB: This creates 'uniform' orthographic projection matrix, - // which depth range [-1,1], right-handed rules - // - // [ A 0 0 C ] - // [ 0 B 0 D ] - // [ 0 0 q qn ] - // [ 0 0 0 1 ] - // - // A = 2 * / (right - left) - // B = 2 * / (top - bottom) - // C = - (right + left) / (right - left) - // D = - (top + bottom) / (top - bottom) - // q = - 2 / (far - near) - // qn = - (far + near) / (far - near) - - mProjMatrix = Matrix4::ZERO; - mProjMatrix[0][0] = A; - mProjMatrix[0][3] = C; - mProjMatrix[1][1] = B; - mProjMatrix[1][3] = D; - mProjMatrix[2][2] = q; - mProjMatrix[2][3] = qn; - mProjMatrix[3][3] = 1; - } // ortho - } // !mCustomProjMatrix - - RenderSystem* renderSystem = Root::getSingleton().getRenderSystem(); - - if(renderSystem) - { - // API specific - renderSystem->_convertProjectionMatrix(mProjMatrix, mProjMatrixRSDepth, true); - } - else - { - mProjMatrixRSDepth = mProjMatrix; - } - - // Calculate bounding box (local) - // Box is from 0, down -Z, max dimensions as determined from far plane - // If infinite view frustum just pick a far value - Real farDist = (mFarDist == 0) ? 100000 : mFarDist; - // Near plane bounds - Vector3 min(left, bottom, -farDist); - Vector3 max(right, top, 0); - - if (mCustomProjMatrix) - { - // Some custom projection matrices can have unusual inverted settings - // So make sure the AABB is the right way around to start with - Vector3 tmp = min; - min.makeFloor(max); - max.makeCeil(tmp); - } - - if (mProjType == PT_PERSPECTIVE) - { - // Merge with far plane bounds - Real radio = farDist / mNearDist; - min.makeFloor(Vector3(left * radio, bottom * radio, -farDist)); - max.makeCeil(Vector3(right * radio, top * radio, 0)); - } - mBoundingBox.setExtents(min, max); - - mRecalcFrustum = false; - - // Signal to update frustum clipping planes - mRecalcFrustumPlanes = true; - } - //----------------------------------------------------------------------- - void Frustum::updateFrustum(void) const - { - if (isFrustumOutOfDate()) - { - updateFrustumImpl(); - } - } - //----------------------------------------------------------------------- - bool Frustum::isViewOutOfDate(void) const - { - // Attached to node? - if (mParentNode) - { - if (mRecalcView || - mParentNode->_getDerivedOrientation() != mLastParentOrientation || - mParentNode->_getDerivedPosition() != mLastParentPosition) - { - // Ok, we're out of date with SceneNode we're attached to - mLastParentOrientation = mParentNode->_getDerivedOrientation(); - mLastParentPosition = mParentNode->_getDerivedPosition(); - mRecalcView = true; - } - } - // Deriving reflection from linked plane? - if (mLinkedReflectPlane && - !(mLastLinkedReflectionPlane == mLinkedReflectPlane->_getDerivedPlane())) - { - mReflectPlane = mLinkedReflectPlane->_getDerivedPlane(); - mReflectMatrix = Math::buildReflectionMatrix(mReflectPlane); - mLastLinkedReflectionPlane = mLinkedReflectPlane->_getDerivedPlane(); - mRecalcView = true; - } - - return mRecalcView; - } - - //----------------------------------------------------------------------- - bool Frustum::isFrustumOutOfDate(void) const - { - // Deriving custom near plane from linked plane? - if (mObliqueDepthProjection) - { - // Out of date when view out of data since plane needs to be in view space - if (isViewOutOfDate()) - { - mRecalcFrustum = true; - } - // Update derived plane - if (mLinkedObliqueProjPlane && - !(mLastLinkedObliqueProjPlane == mLinkedObliqueProjPlane->_getDerivedPlane())) - { - mObliqueProjPlane = mLinkedObliqueProjPlane->_getDerivedPlane(); - mLastLinkedObliqueProjPlane = mObliqueProjPlane; - mRecalcFrustum = true; - } - } - - return mRecalcFrustum; - } - - //----------------------------------------------------------------------- - void Frustum::updateViewImpl(void) const - { - // ---------------------- - // Update the view matrix - // ---------------------- - - // Get orientation from quaternion - - if (!mCustomViewMatrix) - { - Matrix3 rot; - const Quaternion& orientation = getOrientationForViewUpdate(); - const Vector3& position = getPositionForViewUpdate(); - - mViewMatrix = Math::makeViewMatrix(position, orientation, mReflect? &mReflectMatrix : 0); - } - - mRecalcView = false; - - // Signal to update frustum clipping planes - mRecalcFrustumPlanes = true; - // Signal to update world space corners - mRecalcWorldSpaceCorners = true; - // Signal to update frustum if oblique plane enabled, - // since plane needs to be in view space - if (mObliqueDepthProjection) - { - mRecalcFrustum = true; - } - } - //--------------------------------------------------------------------- - void Frustum::calcViewMatrixRelative(const Vector3& relPos, Matrix4& matToUpdate) const - { - Affine3 matTrans = Affine3::IDENTITY; - matTrans.setTrans(relPos); - matToUpdate = getViewMatrix() * matTrans; - - } - //----------------------------------------------------------------------- - void Frustum::updateView(void) const - { - if (isViewOutOfDate()) - { - updateViewImpl(); - } - } - - //----------------------------------------------------------------------- - void Frustum::updateFrustumPlanesImpl(void) const - { - // ------------------------- - // Update the frustum planes - // ------------------------- - Matrix4 combo = mProjMatrix * mViewMatrix; - - mFrustumPlanes[FRUSTUM_PLANE_LEFT].normal.x = combo[3][0] + combo[0][0]; - mFrustumPlanes[FRUSTUM_PLANE_LEFT].normal.y = combo[3][1] + combo[0][1]; - mFrustumPlanes[FRUSTUM_PLANE_LEFT].normal.z = combo[3][2] + combo[0][2]; - mFrustumPlanes[FRUSTUM_PLANE_LEFT].d = combo[3][3] + combo[0][3]; - - mFrustumPlanes[FRUSTUM_PLANE_RIGHT].normal.x = combo[3][0] - combo[0][0]; - mFrustumPlanes[FRUSTUM_PLANE_RIGHT].normal.y = combo[3][1] - combo[0][1]; - mFrustumPlanes[FRUSTUM_PLANE_RIGHT].normal.z = combo[3][2] - combo[0][2]; - mFrustumPlanes[FRUSTUM_PLANE_RIGHT].d = combo[3][3] - combo[0][3]; - - mFrustumPlanes[FRUSTUM_PLANE_TOP].normal.x = combo[3][0] - combo[1][0]; - mFrustumPlanes[FRUSTUM_PLANE_TOP].normal.y = combo[3][1] - combo[1][1]; - mFrustumPlanes[FRUSTUM_PLANE_TOP].normal.z = combo[3][2] - combo[1][2]; - mFrustumPlanes[FRUSTUM_PLANE_TOP].d = combo[3][3] - combo[1][3]; - - mFrustumPlanes[FRUSTUM_PLANE_BOTTOM].normal.x = combo[3][0] + combo[1][0]; - mFrustumPlanes[FRUSTUM_PLANE_BOTTOM].normal.y = combo[3][1] + combo[1][1]; - mFrustumPlanes[FRUSTUM_PLANE_BOTTOM].normal.z = combo[3][2] + combo[1][2]; - mFrustumPlanes[FRUSTUM_PLANE_BOTTOM].d = combo[3][3] + combo[1][3]; - - mFrustumPlanes[FRUSTUM_PLANE_NEAR].normal.x = combo[3][0] + combo[2][0]; - mFrustumPlanes[FRUSTUM_PLANE_NEAR].normal.y = combo[3][1] + combo[2][1]; - mFrustumPlanes[FRUSTUM_PLANE_NEAR].normal.z = combo[3][2] + combo[2][2]; - mFrustumPlanes[FRUSTUM_PLANE_NEAR].d = combo[3][3] + combo[2][3]; - - mFrustumPlanes[FRUSTUM_PLANE_FAR].normal.x = combo[3][0] - combo[2][0]; - mFrustumPlanes[FRUSTUM_PLANE_FAR].normal.y = combo[3][1] - combo[2][1]; - mFrustumPlanes[FRUSTUM_PLANE_FAR].normal.z = combo[3][2] - combo[2][2]; - mFrustumPlanes[FRUSTUM_PLANE_FAR].d = combo[3][3] - combo[2][3]; - - // Renormalise any normals which were not unit length - for(auto & p : mFrustumPlanes) - { - Real length = p.normal.normalise(); - p.d /= length; - } - - mRecalcFrustumPlanes = false; - } - //----------------------------------------------------------------------- - void Frustum::updateFrustumPlanes(void) const - { - updateView(); - updateFrustum(); - - if (mRecalcFrustumPlanes) - { - updateFrustumPlanesImpl(); - } - } - //----------------------------------------------------------------------- - void Frustum::updateWorldSpaceCornersImpl(void) const - { - Affine3 eyeToWorld = mViewMatrix.inverse(); - - // Note: Even though we can dealing with general projection matrix here, - // but because it's incompatibly with infinite far plane, thus, we - // still need to working with projection parameters. - - // Calc near plane corners - RealRect vp = calcProjectionParameters(); - Real nearLeft = vp.left, nearRight = vp.right, nearBottom = vp.bottom, nearTop = vp.top; - - // Treat infinite fardist as some arbitrary far value - Real farDist = (mFarDist == 0) ? 100000 : mFarDist; - - // Calc far palne corners - Real radio = mProjType == PT_PERSPECTIVE ? farDist / mNearDist : 1; - Real farLeft = nearLeft * radio; - Real farRight = nearRight * radio; - Real farBottom = nearBottom * radio; - Real farTop = nearTop * radio; - - // near - mWorldSpaceCorners[0] = eyeToWorld * Vector3(nearRight, nearTop, -mNearDist); - mWorldSpaceCorners[1] = eyeToWorld * Vector3(nearLeft, nearTop, -mNearDist); - mWorldSpaceCorners[2] = eyeToWorld * Vector3(nearLeft, nearBottom, -mNearDist); - mWorldSpaceCorners[3] = eyeToWorld * Vector3(nearRight, nearBottom, -mNearDist); - // far - mWorldSpaceCorners[4] = eyeToWorld * Vector3(farRight, farTop, -farDist); - mWorldSpaceCorners[5] = eyeToWorld * Vector3(farLeft, farTop, -farDist); - mWorldSpaceCorners[6] = eyeToWorld * Vector3(farLeft, farBottom, -farDist); - mWorldSpaceCorners[7] = eyeToWorld * Vector3(farRight, farBottom, -farDist); - - mRecalcWorldSpaceCorners = false; - } - //----------------------------------------------------------------------- - void Frustum::updateWorldSpaceCorners(void) const - { - updateView(); - - if (mRecalcWorldSpaceCorners) - { - updateWorldSpaceCornersImpl(); - } - - } - - //----------------------------------------------------------------------- - Real Frustum::getAspectRatio(void) const - { - return mAspect; - } - - //----------------------------------------------------------------------- - void Frustum::setAspectRatio(Real r) - { - mAspect = r; - invalidateFrustum(); - } - - //----------------------------------------------------------------------- - const AxisAlignedBox& Frustum::getBoundingBox(void) const - { - return mBoundingBox; - } - //----------------------------------------------------------------------- - void Frustum::_updateRenderQueue(RenderQueue* queue) - { - if (mDebugDisplay && mManager && mManager->getDebugDrawer()) - { - // Add self - mManager->getDebugDrawer()->drawFrustum(this); - } - } - //----------------------------------------------------------------------- - const String& Frustum::getMovableType(void) const - { - return MOT_FRUSTUM; - } - //----------------------------------------------------------------------- - Real Frustum::getBoundingRadius(void) const - { - return (mFarDist == 0)? 100000 : mFarDist; - } - //----------------------------------------------------------------------- - void Frustum::_notifyCurrentCamera(Camera* cam) - { - // Make sure bounding box up-to-date - updateFrustum(); - - MovableObject::_notifyCurrentCamera(cam); - } - - // ------------------------------------------------------------------- - void Frustum::invalidateFrustum() const - { - mRecalcFrustum = true; - mRecalcFrustumPlanes = true; - mRecalcWorldSpaceCorners = true; - } - // ------------------------------------------------------------------- - void Frustum::invalidateView() const - { - mRecalcView = true; - mRecalcFrustumPlanes = true; - mRecalcWorldSpaceCorners = true; - } - // ------------------------------------------------------------------- - const Frustum::Corners& Frustum::getWorldSpaceCorners(void) const - { - updateWorldSpaceCorners(); - - return mWorldSpaceCorners; - } - //----------------------------------------------------------------------- - void Frustum::setProjectionType(ProjectionType pt) - { - mProjType = pt; - invalidateFrustum(); - } - - //----------------------------------------------------------------------- - ProjectionType Frustum::getProjectionType(void) const - { - return mProjType; - } - //----------------------------------------------------------------------- - const Vector3& Frustum::getPositionForViewUpdate(void) const - { - return mLastParentPosition; - } - //----------------------------------------------------------------------- - const Quaternion& Frustum::getOrientationForViewUpdate(void) const - { - return mLastParentOrientation; - } - //----------------------------------------------------------------------- - void Frustum::enableReflection(const Plane& p) - { - mReflect = true; - mReflectPlane = p; - mLinkedReflectPlane = 0; - mReflectMatrix = Math::buildReflectionMatrix(p); - invalidateView(); - - } - //----------------------------------------------------------------------- - void Frustum::enableReflection(const MovablePlane* p) - { - mReflect = true; - mLinkedReflectPlane = p; - mReflectPlane = mLinkedReflectPlane->_getDerivedPlane(); - mReflectMatrix = Math::buildReflectionMatrix(mReflectPlane); - mLastLinkedReflectionPlane = mLinkedReflectPlane->_getDerivedPlane(); - invalidateView(); - } - //----------------------------------------------------------------------- - void Frustum::disableReflection(void) - { - mReflect = false; - mLinkedReflectPlane = 0; - mLastLinkedReflectionPlane.normal = Vector3::ZERO; - invalidateView(); - } - //--------------------------------------------------------------------- - bool Frustum::projectSphere(const Sphere& sphere, - Real* left, Real* top, Real* right, Real* bottom) const - { - // See http://www.gamasutra.com/features/20021011/lengyel_06.htm - // Transform light position into camera space - - updateView(); - Vector3 eyeSpacePos = mViewMatrix * sphere.getCenter(); - - // initialise - *left = *bottom = -1.0f; - *right = *top = 1.0f; - - if (eyeSpacePos.z < 0) - { - updateFrustum(); - const Matrix4& projMatrix = getProjectionMatrix(); - Real r = sphere.getRadius(); - Real rsq = r * r; - - // early-exit - if (eyeSpacePos.squaredLength() <= rsq) - return false; - - Real Lxz = Math::Sqr(eyeSpacePos.x) + Math::Sqr(eyeSpacePos.z); - Real Lyz = Math::Sqr(eyeSpacePos.y) + Math::Sqr(eyeSpacePos.z); - - // Find the tangent planes to the sphere - // XZ first - // calculate quadratic discriminant: b*b - 4ac - // x = Nx - // a = Lx^2 + Lz^2 - // b = -2rLx - // c = r^2 - Lz^2 - Real a = Lxz; - Real b = -2.0f * r * eyeSpacePos.x; - Real c = rsq - Math::Sqr(eyeSpacePos.z); - Real D = b*b - 4.0f*a*c; - - // two roots? - if (D > 0) - { - Real sqrootD = Math::Sqrt(D); - // solve the quadratic to get the components of the normal - Real Nx0 = (-b + sqrootD) / (2 * a); - Real Nx1 = (-b - sqrootD) / (2 * a); - - // Derive Z from this - Real Nz0 = (r - Nx0 * eyeSpacePos.x) / eyeSpacePos.z; - Real Nz1 = (r - Nx1 * eyeSpacePos.x) / eyeSpacePos.z; - - // Get the point of tangency - // Only consider points of tangency in front of the camera - Real Pz0 = (Lxz - rsq) / (eyeSpacePos.z - ((Nz0 / Nx0) * eyeSpacePos.x)); - if (Pz0 < 0) - { - // Project point onto near plane in worldspace - Real nearx0 = (Nz0 * mNearDist) / Nx0; - // now we need to map this to viewport coords - // use projection matrix since that will take into account all factors - Vector3 relx0 = projMatrix * Vector3(nearx0, 0, -mNearDist); - - // find out whether this is a left side or right side - Real Px0 = -(Pz0 * Nz0) / Nx0; - if (Px0 > eyeSpacePos.x) - { - *right = std::min(*right, relx0.x); - } - else - { - *left = std::max(*left, relx0.x); - } - } - Real Pz1 = (Lxz - rsq) / (eyeSpacePos.z - ((Nz1 / Nx1) * eyeSpacePos.x)); - if (Pz1 < 0) - { - // Project point onto near plane in worldspace - Real nearx1 = (Nz1 * mNearDist) / Nx1; - // now we need to map this to viewport coords - // use projection matrix since that will take into account all factors - Vector3 relx1 = projMatrix * Vector3(nearx1, 0, -mNearDist); - - // find out whether this is a left side or right side - Real Px1 = -(Pz1 * Nz1) / Nx1; - if (Px1 > eyeSpacePos.x) - { - *right = std::min(*right, relx1.x); - } - else - { - *left = std::max(*left, relx1.x); - } - } - } - - - // Now YZ - // calculate quadratic discriminant: b*b - 4ac - // x = Ny - // a = Ly^2 + Lz^2 - // b = -2rLy - // c = r^2 - Lz^2 - a = Lyz; - b = -2.0f * r * eyeSpacePos.y; - c = rsq - Math::Sqr(eyeSpacePos.z); - D = b*b - 4.0f*a*c; - - // two roots? - if (D > 0) - { - Real sqrootD = Math::Sqrt(D); - // solve the quadratic to get the components of the normal - Real Ny0 = (-b + sqrootD) / (2 * a); - Real Ny1 = (-b - sqrootD) / (2 * a); - - // Derive Z from this - Real Nz0 = (r - Ny0 * eyeSpacePos.y) / eyeSpacePos.z; - Real Nz1 = (r - Ny1 * eyeSpacePos.y) / eyeSpacePos.z; - - // Get the point of tangency - // Only consider points of tangency in front of the camera - Real Pz0 = (Lyz - rsq) / (eyeSpacePos.z - ((Nz0 / Ny0) * eyeSpacePos.y)); - if (Pz0 < 0) - { - // Project point onto near plane in worldspace - Real neary0 = (Nz0 * mNearDist) / Ny0; - // now we need to map this to viewport coords - // use projection matriy since that will take into account all factors - Vector3 rely0 = projMatrix * Vector3(0, neary0, -mNearDist); - - // find out whether this is a top side or bottom side - Real Py0 = -(Pz0 * Nz0) / Ny0; - if (Py0 > eyeSpacePos.y) - { - *top = std::min(*top, rely0.y); - } - else - { - *bottom = std::max(*bottom, rely0.y); - } - } - Real Pz1 = (Lyz - rsq) / (eyeSpacePos.z - ((Nz1 / Ny1) * eyeSpacePos.y)); - if (Pz1 < 0) - { - // Project point onto near plane in worldspace - Real neary1 = (Nz1 * mNearDist) / Ny1; - // now we need to map this to viewport coords - // use projection matriy since that will take into account all factors - Vector3 rely1 = projMatrix * Vector3(0, neary1, -mNearDist); - - // find out whether this is a top side or bottom side - Real Py1 = -(Pz1 * Nz1) / Ny1; - if (Py1 > eyeSpacePos.y) - { - *top = std::min(*top, rely1.y); - } - else - { - *bottom = std::max(*bottom, rely1.y); - } - } - } - } - - return (*left != -1.0f) || (*top != 1.0f) || (*right != 1.0f) || (*bottom != -1.0f); - - } - //--------------------------------------------------------------------- - void Frustum::enableCustomNearClipPlane(const MovablePlane* plane) - { - mObliqueDepthProjection = true; - mLinkedObliqueProjPlane = plane; - mObliqueProjPlane = plane->_getDerivedPlane(); - invalidateFrustum(); - } - //--------------------------------------------------------------------- - void Frustum::enableCustomNearClipPlane(const Plane& plane) - { - mObliqueDepthProjection = true; - mLinkedObliqueProjPlane = 0; - mObliqueProjPlane = plane; - invalidateFrustum(); - } - //--------------------------------------------------------------------- - void Frustum::disableCustomNearClipPlane(void) - { - mObliqueDepthProjection = false; - mLinkedObliqueProjPlane = 0; - invalidateFrustum(); - } - //--------------------------------------------------------------------- - void Frustum::setCustomViewMatrix(bool enable, const Affine3& viewMatrix) - { - mCustomViewMatrix = enable; - if (enable) - { - mViewMatrix = viewMatrix; - } - invalidateView(); - } - //--------------------------------------------------------------------- - void Frustum::setCustomProjectionMatrix(bool enable, const Matrix4& projMatrix) - { - mCustomProjMatrix = enable; - if (enable) - { - mProjMatrix = projMatrix; - } - invalidateFrustum(); - } - //--------------------------------------------------------------------- - void Frustum::setOrthoWindow(Real w, Real h) - { - mOrthoHeight = h; - mAspect = w / h; - invalidateFrustum(); - } - //--------------------------------------------------------------------- - void Frustum::setOrthoWindowHeight(Real h) - { - mOrthoHeight = h; - invalidateFrustum(); - } - //--------------------------------------------------------------------- - void Frustum::setOrthoWindowWidth(Real w) - { - mOrthoHeight = w / mAspect; - invalidateFrustum(); - } - //--------------------------------------------------------------------- - Real Frustum::getOrthoWindowHeight() const - { - return mOrthoHeight; - } - //--------------------------------------------------------------------- - Real Frustum::getOrthoWindowWidth() const - { - return mOrthoHeight * mAspect; - } - //--------------------------------------------------------------------- - void Frustum::visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables) - { - // Only displayed in debug - if (debugRenderables) - { - //visitor->visit(this, 0, true); - } - - } - //--------------------------------------------------------------------- - void Frustum::setFrustumExtents(Real left, Real right, Real top, Real bottom) - { - mFrustumExtentsManuallySet = true; - mExtents = RealRect(left, top, right, bottom); - - invalidateFrustum(); - } - //--------------------------------------------------------------------- - void Frustum::resetFrustumExtents() - { - mFrustumExtentsManuallySet = false; - invalidateFrustum(); - } - //--------------------------------------------------------------------- - RealRect Frustum::getFrustumExtents() const - { - updateFrustum(); - return mExtents; - } - //--------------------------------------------------------------------- - PlaneBoundedVolume Frustum::getPlaneBoundedVolume() - { - updateFrustumPlanes(); - - PlaneBoundedVolume volume; - volume.planes.push_back(mFrustumPlanes[FRUSTUM_PLANE_NEAR]); - volume.planes.push_back(mFrustumPlanes[FRUSTUM_PLANE_FAR]); - volume.planes.push_back(mFrustumPlanes[FRUSTUM_PLANE_BOTTOM]); - volume.planes.push_back(mFrustumPlanes[FRUSTUM_PLANE_TOP]); - volume.planes.push_back(mFrustumPlanes[FRUSTUM_PLANE_LEFT]); - volume.planes.push_back(mFrustumPlanes[FRUSTUM_PLANE_RIGHT]); - return volume; - } - - -} // namespace Ogre diff --git a/OgreMain/src/OgreGpuProgram.cpp b/OgreMain/src/OgreGpuProgram.cpp deleted file mode 100644 index 0ee235ea499..00000000000 --- a/OgreMain/src/OgreGpuProgram.cpp +++ /dev/null @@ -1,527 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreGpuProgram.h" - -#include -#include "OgreGpuProgramManager.h" -#include "OgreRenderSystemCapabilities.h" - -namespace Ogre -{ - //----------------------------------------------------------------------------- - namespace { - /// Command object - see ParamCommand - class CmdType : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - class CmdSyntax : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - class CmdSkeletal : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - class CmdMorph : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - class CmdPose : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - class CmdVTF : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - class CmdManualNamedConstsFile : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - using CmdInstancing = SimpleParamCommand; - // Command object for setting / getting parameters - static CmdType msTypeCmd; - static CmdSyntax msSyntaxCmd; - static CmdInstancing msInstancingCmd; - static CmdSkeletal msSkeletalCmd; - static CmdMorph msMorphCmd; - static CmdPose msPoseCmd; - static CmdVTF msVTFCmd; - static CmdManualNamedConstsFile msManNamedConstsFileCmd; - } - - //----------------------------------------------------------------------------- - GpuProgram::GpuProgram(ResourceManager* creator, const String& name, ResourceHandle handle, const String& group, - bool isManual, ManualResourceLoader* loader) - : Resource(creator, name, handle, group, isManual, loader), mType(GPT_VERTEX_PROGRAM), mLoadFromFile(true), - mInstancing(false), mSkeletalAnimation(false), mMorphAnimation(false), mVertexTextureFetch(false), - mNeedsAdjacencyInfo(false), mCompileError(false), mLoadedManualNamedConstants(false), mPoseAnimation(0) - { - createParameterMappingStructures(); - } - //----------------------------------------------------------------------------- - void GpuProgram::setType(GpuProgramType t) - { - mType = t; - } - //----------------------------------------------------------------------------- - void GpuProgram::setSyntaxCode(const String& syntax) - { - mSyntaxCode = syntax; - } - //----------------------------------------------------------------------------- - void GpuProgram::setSourceFile(const String& filename) - { - OgreAssert(!filename.empty(), "invalid filename"); - - mFilename = filename; - mSource.clear(); - mLoadFromFile = true; - mCompileError = false; - } - //----------------------------------------------------------------------------- - void GpuProgram::setSource(const String& source) - { - mSource = source; - mFilename.clear(); - mLoadFromFile = false; - mCompileError = false; - } - - uint32 GpuProgram::_getHash(uint32 seed) const - { - // include filename as same source can be used with different defines & entry points - uint32 hash = FastHash(mName.c_str(), mName.size(), seed); - return FastHash(mSource.c_str(), mSource.size(), hash); - } - - size_t GpuProgram::calculateSize(void) const - { - size_t memSize = sizeof(*this); - memSize += mManualNamedConstantsFile.size() * sizeof(char); - memSize += mFilename.size() * sizeof(char); - memSize += mSource.size() * sizeof(char); - memSize += mSyntaxCode.size() * sizeof(char); - - size_t paramsSize = 0; - if(mDefaultParams) - paramsSize += mDefaultParams->calculateSize(); - if(mConstantDefs) - paramsSize += mConstantDefs->calculateSize(); - - return memSize + paramsSize; - } - //----------------------------------------------------------------------------- - void GpuProgram::prepareImpl() - { - if (!mLoadFromFile) - return; - - mSource = ResourceGroupManager::getSingleton().openResource(mFilename, mGroup, this)->getAsString(); - } - - void GpuProgram::safePrepare() - { - try - { - prepare(); - } - catch (const RuntimeAssertionException&) - { - throw; - } - catch (const Exception& e) - { - // will already have been logged - LogManager::getSingleton().stream(LML_CRITICAL) - << "Program '" << mName << "' is not supported: " << e.getDescription(); - - mCompileError = true; - } - } - - void GpuProgram::loadImpl(void) - { - if(mCompileError) - return; - - // Call polymorphic load - try - { - loadFromSource(); - } - catch (const RuntimeAssertionException&) - { - throw; - } - catch (const Exception& e) - { - // will already have been logged - LogManager::getSingleton().stream(LML_CRITICAL) - << "Program '" << mName << "' is not supported: " << e.getDescription(); - - mCompileError = true; - } - } - void GpuProgram::postLoadImpl() - { - if (!mDefaultParams || mCompileError) - return; - - // Keep a reference to old ones to copy - GpuProgramParametersSharedPtr savedParams = mDefaultParams; - // reset params to stop them being referenced in the next create - mDefaultParams.reset(); - - // Create new params - mDefaultParams = createParameters(); - - // Copy old (matching) values across - // Don't use copyConstantsFrom since program may be different - mDefaultParams->copyMatchingNamedConstantsFrom(*savedParams.get()); - } - - //----------------------------------------------------------------------------- - bool GpuProgram::isRequiredCapabilitiesSupported(void) const - { - const RenderSystemCapabilities* caps = - Root::getSingleton().getRenderSystem()->getCapabilities(); - - // Basic support check - if ((getType() == GPT_GEOMETRY_PROGRAM && !caps->hasCapability(RSC_GEOMETRY_PROGRAM)) || - (getType() == GPT_DOMAIN_PROGRAM && !caps->hasCapability(RSC_TESSELLATION_DOMAIN_PROGRAM)) || - (getType() == GPT_HULL_PROGRAM && !caps->hasCapability(RSC_TESSELLATION_HULL_PROGRAM)) || - (getType() == GPT_COMPUTE_PROGRAM && !caps->hasCapability(RSC_COMPUTE_PROGRAM))) - { - return false; - } - - // Vertex texture fetch required? - if (isVertexTextureFetchRequired() && - !caps->hasCapability(RSC_VERTEX_TEXTURE_FETCH)) - { - return false; - } - - return true; - } - //----------------------------------------------------------------------------- - bool GpuProgram::isSupported(void) const - { - if (mCompileError || !isRequiredCapabilitiesSupported()) - return false; - - return GpuProgramManager::getSingleton().isSyntaxSupported(mSyntaxCode); - } - //--------------------------------------------------------------------- - void GpuProgram::createParameterMappingStructures(bool recreateIfExists) - { - createLogicalParameterMappingStructures(recreateIfExists); - createNamedParameterMappingStructures(recreateIfExists); - } - //--------------------------------------------------------------------- - void GpuProgram::createLogicalParameterMappingStructures(bool recreateIfExists) - { - if (recreateIfExists || !mLogicalToPhysical) - mLogicalToPhysical = std::make_shared(); - } - //--------------------------------------------------------------------- - void GpuProgram::createNamedParameterMappingStructures(bool recreateIfExists) - { - if (recreateIfExists || !mConstantDefs) - mConstantDefs = std::make_shared(); - } - //--------------------------------------------------------------------- - void GpuProgram::setManualNamedConstantsFile(const String& paramDefFile) - { - mManualNamedConstantsFile = paramDefFile; - mLoadedManualNamedConstants = false; - } - //--------------------------------------------------------------------- - void GpuProgram::setManualNamedConstants(const GpuNamedConstants& namedConstants) - { - createParameterMappingStructures(); - *mConstantDefs.get() = namedConstants; - - mLogicalToPhysical->bufferSize = mConstantDefs->bufferSize; - mLogicalToPhysical->map.clear(); - // need to set up logical mappings too for some rendersystems - for (GpuConstantDefinitionMap::const_iterator i = mConstantDefs->map.begin(); - i != mConstantDefs->map.end(); ++i) - { - const String& name = i->first; - const GpuConstantDefinition& def = i->second; - // only consider non-array entries - if (name.find('[') == String::npos) - { - GpuLogicalIndexUseMap::value_type val( - def.logicalIndex, - GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, def.variability, - GpuConstantDefinition::getBaseType(def.constType))); - mLogicalToPhysical->map.emplace(val); - } - } - - - } - //----------------------------------------------------------------------------- - GpuProgramParametersSharedPtr GpuProgram::createParameters(void) - { - // Default implementation simply returns standard parameters. - GpuProgramParametersSharedPtr ret = - GpuProgramManager::getSingleton().createParameters(); - - - // optionally load manually supplied named constants - if (!mManualNamedConstantsFile.empty() && !mLoadedManualNamedConstants) - { - try - { - GpuNamedConstants namedConstants; - DataStreamPtr stream = - ResourceGroupManager::getSingleton().openResource( - mManualNamedConstantsFile, mGroup, this); - namedConstants.load(stream); - setManualNamedConstants(namedConstants); - } - catch(const Exception& e) - { - LogManager::getSingleton().stream() << - "Unable to load manual named constants for GpuProgram " << mName << - ": " << e.getDescription(); - } - mLoadedManualNamedConstants = true; - } - - - // set up named parameters, if any - if (mConstantDefs && !mConstantDefs->map.empty()) - { - ret->_setNamedConstants(mConstantDefs); - } - // link shared logical / physical map for low-level use - ret->_setLogicalIndexes(mLogicalToPhysical); - - // Copy in default parameters if present - if (mDefaultParams) - ret->copyConstantsFrom(*(mDefaultParams.get())); - - return ret; - } - //----------------------------------------------------------------------------- - const GpuProgramParametersPtr& GpuProgram::getDefaultParameters(void) - { - if (!mDefaultParams) - { - mDefaultParams = createParameters(); - } - return mDefaultParams; - } - //----------------------------------------------------------------------------- - const String GpuProgram::getProgramTypeName(GpuProgramType programType) - { - switch (programType) - { - case GPT_VERTEX_PROGRAM: - return "vertex"; - case GPT_GEOMETRY_PROGRAM: - return "geometry"; - case GPT_FRAGMENT_PROGRAM: - return "fragment"; - case GPT_DOMAIN_PROGRAM: - return "domain"; - case GPT_HULL_PROGRAM: - return "hull"; - case GPT_COMPUTE_PROGRAM: - return "compute"; - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Unexpected GPU program type", - "GpuProgram::GetName"); - } - } - //----------------------------------------------------------------------------- - void GpuProgram::setupBaseParamDictionary(void) - { - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter( - ParameterDef("type", "'vertex_program', 'geometry_program', 'fragment_program', 'hull_program', 'domain_program', 'compute_program'", - PT_STRING), &msTypeCmd); - dict->addParameter( - ParameterDef("syntax", "Syntax code, e.g. vs_1_1", PT_STRING), &msSyntaxCmd); - dict->addParameter("includes_instancing", &msInstancingCmd); - dict->addParameter( - ParameterDef("includes_skeletal_animation", - "Whether this vertex program includes skeletal animation", PT_BOOL), - &msSkeletalCmd); - dict->addParameter( - ParameterDef("includes_morph_animation", - "Whether this vertex program includes morph animation", PT_BOOL), - &msMorphCmd); - dict->addParameter( - ParameterDef("includes_pose_animation", - "The number of poses this vertex program supports for pose animation", PT_INT), - &msPoseCmd); - dict->addParameter( - ParameterDef("uses_vertex_texture_fetch", - "Whether this vertex program requires vertex texture fetch support.", PT_BOOL), - &msVTFCmd); - dict->addParameter( - ParameterDef("manual_named_constants", - "File containing named parameter mappings for low-level programs.", PT_BOOL), - &msManNamedConstsFileCmd); - } - - //----------------------------------------------------------------------- - const String& GpuProgram::getLanguage(void) const - { - static const String language = "asm"; - - return language; - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String CmdType::doGet(const void* target) const - { - const GpuProgram* t = static_cast(target); - return GpuProgram::getProgramTypeName(t->getType()) + "_program"; - } - void CmdType::doSet(void* target, const String& val) - { - GpuProgram* t = static_cast(target); - if (val == "vertex_program") - { - t->setType(GPT_VERTEX_PROGRAM); - } - else if (val == "geometry_program") - { - t->setType(GPT_GEOMETRY_PROGRAM); - } - else if (val == "domain_program") - { - t->setType(GPT_DOMAIN_PROGRAM); - } - else if (val == "hull_program") - { - t->setType(GPT_HULL_PROGRAM); - } - else if (val == "compute_program") - { - t->setType(GPT_COMPUTE_PROGRAM); - } - else - { - t->setType(GPT_FRAGMENT_PROGRAM); - } - } - //----------------------------------------------------------------------- - String CmdSyntax::doGet(const void* target) const - { - const GpuProgram* t = static_cast(target); - return t->getSyntaxCode(); - } - void CmdSyntax::doSet(void* target, const String& val) - { - GpuProgram* t = static_cast(target); - t->setSyntaxCode(val); - } - //----------------------------------------------------------------------- - String CmdSkeletal::doGet(const void* target) const - { - const GpuProgram* t = static_cast(target); - return StringConverter::toString(t->isSkeletalAnimationIncluded()); - } - void CmdSkeletal::doSet(void* target, const String& val) - { - GpuProgram* t = static_cast(target); - t->setSkeletalAnimationIncluded(StringConverter::parseBool(val)); - } - //----------------------------------------------------------------------- - String CmdMorph::doGet(const void* target) const - { - const GpuProgram* t = static_cast(target); - return StringConverter::toString(t->isMorphAnimationIncluded()); - } - void CmdMorph::doSet(void* target, const String& val) - { - GpuProgram* t = static_cast(target); - t->setMorphAnimationIncluded(StringConverter::parseBool(val)); - } - //----------------------------------------------------------------------- - String CmdPose::doGet(const void* target) const - { - const GpuProgram* t = static_cast(target); - return StringConverter::toString(t->getNumberOfPosesIncluded()); - } - void CmdPose::doSet(void* target, const String& val) - { - GpuProgram* t = static_cast(target); - t->setPoseAnimationIncluded((ushort)StringConverter::parseUnsignedInt(val)); - } - //----------------------------------------------------------------------- - String CmdVTF::doGet(const void* target) const - { - const GpuProgram* t = static_cast(target); - return StringConverter::toString(t->isVertexTextureFetchRequired()); - } - void CmdVTF::doSet(void* target, const String& val) - { - GpuProgram* t = static_cast(target); - t->setVertexTextureFetchRequired(StringConverter::parseBool(val)); - } - //----------------------------------------------------------------------- - String CmdManualNamedConstsFile::doGet(const void* target) const - { - const GpuProgram* t = static_cast(target); - return t->getManualNamedConstantsFile(); - } - void CmdManualNamedConstsFile::doSet(void* target, const String& val) - { - GpuProgram* t = static_cast(target); - t->setManualNamedConstantsFile(val); - } -} - diff --git a/OgreMain/src/OgreGpuProgramManager.cpp b/OgreMain/src/OgreGpuProgramManager.cpp deleted file mode 100644 index 8336715e3bb..00000000000 --- a/OgreMain/src/OgreGpuProgramManager.cpp +++ /dev/null @@ -1,462 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreGpuProgramManager.h" - -#include -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreUnifiedHighLevelGpuProgram.h" -#include "OgreStreamSerialiser.h" - -namespace Ogre { -namespace { - uint32 CACHE_CHUNK_ID = StreamSerialiser::makeIdentifier("OGPC"); // Ogre Gpu Program cache - - String sNullLang = "null"; - class NullProgram : public GpuProgram - { - protected: - /** Internal load implementation, must be implemented by subclasses. - */ - void loadFromSource(void) override {} - void unloadImpl() override {} - - public: - NullProgram(ResourceManager* creator, - const String& name, ResourceHandle handle, const String& group, - bool isManual, ManualResourceLoader* loader) - : GpuProgram(creator, name, handle, group, isManual, loader){} - ~NullProgram() {} - /// Overridden from GpuProgram - never supported - bool isSupported(void) const override { return false; } - /// Overridden from GpuProgram - const String& getLanguage(void) const override { return sNullLang; } - size_t calculateSize(void) const override { return 0; } - - /// Overridden from StringInterface - bool setParameter(const String& name, const String& value) - { - // always silently ignore all parameters so as not to report errors on - // unsupported platforms - return true; - } - - }; - class NullProgramFactory : public HighLevelGpuProgramFactory - { - public: - NullProgramFactory() {} - ~NullProgramFactory() {} - /// Get the name of the language this factory creates programs for - const String& getLanguage(void) const override - { - return sNullLang; - } - GpuProgram* create(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) override - { - return OGRE_NEW NullProgram(creator, name, handle, group, isManual, loader); - } - }; -} - - Resource* GpuProgramManager::createImpl(const String& name, ResourceHandle handle, const String& group, - bool isManual, ManualResourceLoader* loader, - const NameValuePairList* params) - { - OgreAssert(params, "params cannot be null"); - - auto langIt = params->find("language"); - auto typeIt = params->find("type"); - - if(langIt == params->end()) - langIt = params->find("syntax"); - - if (langIt == params->end() || typeIt == params->end()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "You must supply 'language' or 'syntax' and 'type' parameters"); - } - - // "syntax" and "type" will be applied by ResourceManager::createResource - return getFactory(langIt->second)->create(this, name, handle, group, isManual, loader); - } - - //----------------------------------------------------------------------- - template<> GpuProgramManager* Singleton::msSingleton = 0; - GpuProgramManager* GpuProgramManager::getSingletonPtr(void) - { - return msSingleton; - } - GpuProgramManager& GpuProgramManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //----------------------------------------------------------------------- - GpuProgramPtr GpuProgramManager::getByName(const String& name, const String& group) const - { - return static_pointer_cast(getResourceByName(name, group)); - } - //--------------------------------------------------------------------------- - GpuProgramManager::GpuProgramManager() - { - // Loading order - mLoadOrder = 50.0f; - // Resource type - mResourceType = "GpuProgram"; - mSaveMicrocodesToCache = false; - mCacheDirty = false; - - mNullFactory = std::make_unique(); - addFactory(mNullFactory.get()); - mUnifiedFactory = std::make_unique(); - addFactory(mUnifiedFactory.get()); - - ResourceGroupManager::getSingleton()._registerResourceManager(mResourceType, this); - } - //--------------------------------------------------------------------------- - GpuProgramManager::~GpuProgramManager() - { - ResourceGroupManager::getSingleton()._unregisterResourceManager(mResourceType); - } - //--------------------------------------------------------------------------- - GpuProgramPtr GpuProgramManager::load(const String& name, - const String& groupName, const String& filename, - GpuProgramType gptype, const String& syntaxCode) - { - GpuProgramPtr prg; - { - OGRE_LOCK_AUTO_MUTEX; - prg = getByName(name, groupName); - if (!prg) - { - prg = createProgram(name, groupName, filename, gptype, syntaxCode); - } - - } - prg->load(); - return prg; - } - //--------------------------------------------------------------------------- - GpuProgramPtr GpuProgramManager::loadFromString(const String& name, - const String& groupName, const String& code, - GpuProgramType gptype, const String& syntaxCode) - { - GpuProgramPtr prg; - { - OGRE_LOCK_AUTO_MUTEX; - prg = getByName(name, groupName); - if (!prg) - { - prg = createProgramFromString(name, groupName, code, gptype, syntaxCode); - } - - } - prg->load(); - return prg; - } - //--------------------------------------------------------------------------- - GpuProgramPtr GpuProgramManager::create(const String& name, const String& group, GpuProgramType gptype, - const String& syntaxCode, bool isManual, - ManualResourceLoader* loader) - { - auto prg = getFactory(syntaxCode)->create(this, name, getNextHandle(), group, isManual, loader); - prg->setType(gptype); - prg->setSyntaxCode(syntaxCode); - - ResourcePtr ret(prg); - addImpl(ret); - // Tell resource group manager - if(ret) - ResourceGroupManager::getSingleton()._notifyResourceCreated(ret); - return static_pointer_cast(ret); - } - //--------------------------------------------------------------------------- - GpuProgramPtr GpuProgramManager::createProgram(const String& name, const String& groupName, - const String& filename, GpuProgramType gptype, - const String& syntaxCode) - { - GpuProgramPtr prg = createProgram(name, groupName, syntaxCode, gptype); - prg->setSourceFile(filename); - return prg; - } - //--------------------------------------------------------------------------- - GpuProgramPtr GpuProgramManager::createProgramFromString(const String& name, - const String& groupName, const String& code, GpuProgramType gptype, - const String& syntaxCode) - { - GpuProgramPtr prg = createProgram(name, groupName, syntaxCode, gptype); - prg->setSource(code); - return prg; - } - //--------------------------------------------------------------------------- - const GpuProgramManager::SyntaxCodes& GpuProgramManager::getSupportedSyntax(void) - { - // Use the current render system - RenderSystem* rs = Root::getSingleton().getRenderSystem(); - - // Get the supported syntaxed from RenderSystemCapabilities - return rs->getCapabilities()->getSupportedShaderProfiles(); - } - - //--------------------------------------------------------------------------- - bool GpuProgramManager::isSyntaxSupported(const String& syntaxCode) - { - // Use the current render system - RenderSystem* rs = Root::getSingleton().getRenderSystem(); - - // Get the supported syntax from RenderSystemCapabilities - return rs && rs->getCapabilities()->isShaderProfileSupported(syntaxCode); - } - //--------------------------------------------------------------------- - GpuSharedParametersPtr GpuProgramManager::createSharedParameters(const String& name) - { - if (mSharedParametersMap.find(name) != mSharedParametersMap.end()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "The shared parameter set '" + name + "' already exists!", - "GpuProgramManager::createSharedParameters"); - } - GpuSharedParametersPtr ret(OGRE_NEW GpuSharedParameters(name)); - mSharedParametersMap[name] = ret; - return ret; - } - //--------------------------------------------------------------------- - GpuSharedParametersPtr GpuProgramManager::getSharedParameters(const String& name) const - { - SharedParametersMap::const_iterator i = mSharedParametersMap.find(name); - if (i == mSharedParametersMap.end()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "No shared parameter set with name '" + name + "'!", - "GpuProgramManager::getSharedParameters"); - } - return i->second; - } - //--------------------------------------------------------------------- - const GpuProgramManager::SharedParametersMap& - GpuProgramManager::getAvailableSharedParameters() const - { - return mSharedParametersMap; - } - //--------------------------------------------------------------------- - bool GpuProgramManager::getSaveMicrocodesToCache() const - { - return mSaveMicrocodesToCache; - } - //--------------------------------------------------------------------- - bool GpuProgramManager::canGetCompiledShaderBuffer() - { - // Use the current render system - RenderSystem* rs = Root::getSingleton().getRenderSystem(); - - // Check if the supported - return rs->getCapabilities()->hasCapability(RSC_CAN_GET_COMPILED_SHADER_BUFFER); - } - //--------------------------------------------------------------------- - void GpuProgramManager::setSaveMicrocodesToCache( const bool val ) - { - // Check that saving shader microcode is supported - if(!canGetCompiledShaderBuffer()) - mSaveMicrocodesToCache = false; - else - mSaveMicrocodesToCache = val; - } - //--------------------------------------------------------------------- - bool GpuProgramManager::isCacheDirty( void ) const - { - return mCacheDirty; - } - //--------------------------------------------------------------------- - String GpuProgramManager::addRenderSystemToName( const String & name ) - { - // Use the current render system - RenderSystem* rs = Root::getSingleton().getRenderSystem(); - - return rs->getName() + "_" + name; - } - //--------------------------------------------------------------------- - bool GpuProgramManager::isMicrocodeAvailableInCache( uint32 id ) const - { - return mMicrocodeCache.find(id) != mMicrocodeCache.end(); - } - //--------------------------------------------------------------------- - const GpuProgramManager::Microcode & GpuProgramManager::getMicrocodeFromCache( uint32 id ) const - { - return mMicrocodeCache.find(id)->second; - } - //--------------------------------------------------------------------- - void GpuProgramManager::addMicrocodeToCache( uint32 id, const GpuProgramManager::Microcode & microcode ) - { - auto foundIter = mMicrocodeCache.find(id); - if ( foundIter == mMicrocodeCache.end() ) - { - mMicrocodeCache.insert(make_pair(id, microcode)); - // if cache is modified, mark it as dirty. - mCacheDirty = true; - } - else - { - foundIter->second = microcode; - - } - } - //--------------------------------------------------------------------- - void GpuProgramManager::removeMicrocodeFromCache( uint32 id ) - { - auto foundIter = mMicrocodeCache.find(id); - - if (foundIter != mMicrocodeCache.end()) - { - mMicrocodeCache.erase( foundIter ); - mCacheDirty = true; - } - } - //--------------------------------------------------------------------- - void GpuProgramManager::saveMicrocodeCache( const DataStreamPtr& stream ) const - { - if (!mCacheDirty) - return; - - if (!stream->isWriteable()) - { - OGRE_EXCEPT(Exception::ERR_CANNOT_WRITE_TO_FILE, - "Unable to write to stream " + stream->getName(), - "GpuProgramManager::saveMicrocodeCache"); - } - - StreamSerialiser serialiser(stream); - serialiser.writeChunkBegin(CACHE_CHUNK_ID, 2); - - // write the size of the array - uint32 sizeOfArray = static_cast(mMicrocodeCache.size()); - serialiser.write(&sizeOfArray); - - // loop the array and save it - for ( const auto& entry : mMicrocodeCache ) - { - // saves the id of the shader - serialiser.write(&entry.first); - - // saves the microcode - const Microcode & microcodeOfShader = entry.second; - uint32 microcodeLength = static_cast(microcodeOfShader->size()); - serialiser.write(µcodeLength); - serialiser.writeData(microcodeOfShader->getPtr(), 1, microcodeLength); - } - - serialiser.writeChunkEnd(CACHE_CHUNK_ID); - } - //--------------------------------------------------------------------- - void GpuProgramManager::loadMicrocodeCache( const DataStreamPtr& stream ) - { - mMicrocodeCache.clear(); - - StreamSerialiser serialiser(stream); - const StreamSerialiser::Chunk* chunk; - - try - { - chunk = serialiser.readChunkBegin(); - } - catch (const InvalidStateException& e) - { - LogManager::getSingleton().logWarning("Could not load Microcode Cache: " + - e.getDescription()); - return; - } - - if(chunk->id != CACHE_CHUNK_ID || chunk->version != 2) - { - LogManager::getSingleton().logWarning("Invalid Microcode Cache"); - return; - } - // write the size of the array - uint32 sizeOfArray = 0; - serialiser.read(&sizeOfArray); - - // loop the array and load it - for ( uint32 i = 0 ; i < sizeOfArray ; i++ ) - { - // loads the id of the shader - uint32 id; - serialiser.read(&id); - - // loads the microcode - uint32 microcodeLength = 0; - serialiser.read(µcodeLength); - - Microcode microcodeOfShader(OGRE_NEW MemoryDataStream(microcodeLength)); - microcodeOfShader->seek(0); - serialiser.readData(microcodeOfShader->getPtr(), 1, microcodeLength); - - mMicrocodeCache.insert(make_pair(id, microcodeOfShader)); - } - serialiser.readChunkEnd(CACHE_CHUNK_ID); - - // if cache is not modified, mark it as clean. - mCacheDirty = false; - - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------------- - void GpuProgramManager::addFactory(GpuProgramFactory* factory) - { - // deliberately allow later plugins to override earlier ones - mFactories[factory->getLanguage()] = factory; - } - //--------------------------------------------------------------------------- - void GpuProgramManager::removeFactory(GpuProgramFactory* factory) - { - // Remove only if equal to registered one, since it might overridden - // by other plugins - FactoryMap::iterator it = mFactories.find(factory->getLanguage()); - if (it != mFactories.end() && it->second == factory) - { - mFactories.erase(it); - } - } - //--------------------------------------------------------------------------- - GpuProgramFactory* GpuProgramManager::getFactory(const String& language) - { - FactoryMap::iterator i = mFactories.find(language); - - if (i == mFactories.end()) - { - // use the null factory to create programs that will never be supported - i = mFactories.find(sNullLang); - } - return i->second; - } - //--------------------------------------------------------------------- - bool GpuProgramManager::isLanguageSupported(const String& lang) const - { - return mFactories.find(lang) != mFactories.end(); - } -} diff --git a/OgreMain/src/OgreGpuProgramParams.cpp b/OgreMain/src/OgreGpuProgramParams.cpp deleted file mode 100644 index 338dfd03a57..00000000000 --- a/OgreMain/src/OgreGpuProgramParams.cpp +++ /dev/null @@ -1,2650 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#include "OgreStableHeaders.h" -#include "OgreGpuProgramParams.h" -#include "OgreGpuProgramManager.h" -#include "OgreDualQuaternion.h" -#include "OgreRenderTarget.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - GpuProgramParameters::AutoConstantDefinition GpuProgramParameters::AutoConstantDictionary[] = { - AutoConstantDefinition(ACT_WORLD_MATRIX, "world_matrix", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_INVERSE_WORLD_MATRIX, "inverse_world_matrix", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_TRANSPOSE_WORLD_MATRIX, "transpose_world_matrix", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_INVERSE_TRANSPOSE_WORLD_MATRIX, "inverse_transpose_world_matrix", 16, ET_REAL, ACDT_NONE), - - AutoConstantDefinition(ACT_BONE_MATRIX_ARRAY_3x4, "bone_matrix_array_3x4", 12, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_BONE_MATRIX_ARRAY, "bone_matrix_array", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_BONE_DUALQUATERNION_ARRAY_2x4, "bone_dualquaternion_array_2x4", 8, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_BONE_SCALE_SHEAR_MATRIX_ARRAY_3x4, "bone_scale_shear_matrix_array_3x4", 12, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_VIEW_MATRIX, "view_matrix", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_INVERSE_VIEW_MATRIX, "inverse_view_matrix", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_TRANSPOSE_VIEW_MATRIX, "transpose_view_matrix", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_INVERSE_TRANSPOSE_VIEW_MATRIX, "inverse_transpose_view_matrix", 16, ET_REAL, ACDT_NONE), - - AutoConstantDefinition(ACT_PROJECTION_MATRIX, "projection_matrix", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_INVERSE_PROJECTION_MATRIX, "inverse_projection_matrix", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_TRANSPOSE_PROJECTION_MATRIX, "transpose_projection_matrix", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_INVERSE_TRANSPOSE_PROJECTION_MATRIX, "inverse_transpose_projection_matrix", 16, ET_REAL, ACDT_NONE), - - AutoConstantDefinition(ACT_VIEWPROJ_MATRIX, "viewproj_matrix", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_INVERSE_VIEWPROJ_MATRIX, "inverse_viewproj_matrix", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_TRANSPOSE_VIEWPROJ_MATRIX, "transpose_viewproj_matrix", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_INVERSE_TRANSPOSE_VIEWPROJ_MATRIX, "inverse_transpose_viewproj_matrix", 16, ET_REAL, ACDT_NONE), - - AutoConstantDefinition(ACT_WORLDVIEW_MATRIX, "worldview_matrix", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_INVERSE_WORLDVIEW_MATRIX, "inverse_worldview_matrix", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_TRANSPOSE_WORLDVIEW_MATRIX, "transpose_worldview_matrix", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_INVERSE_TRANSPOSE_WORLDVIEW_MATRIX, "inverse_transpose_worldview_matrix", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_NORMAL_MATRIX, "normal_matrix", 9, ET_REAL, ACDT_NONE), - - AutoConstantDefinition(ACT_WORLDVIEWPROJ_MATRIX, "worldviewproj_matrix", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_INVERSE_WORLDVIEWPROJ_MATRIX, "inverse_worldviewproj_matrix", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_TRANSPOSE_WORLDVIEWPROJ_MATRIX, "transpose_worldviewproj_matrix", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_INVERSE_TRANSPOSE_WORLDVIEWPROJ_MATRIX, "inverse_transpose_worldviewproj_matrix", 16, ET_REAL, ACDT_NONE), - - AutoConstantDefinition(ACT_RENDER_TARGET_FLIPPING, "render_target_flipping", 1, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_VERTEX_WINDING, "vertex_winding", 1, ET_REAL, ACDT_NONE), - - AutoConstantDefinition(ACT_FOG_COLOUR, "fog_colour", 4, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_FOG_PARAMS, "fog_params", 4, ET_REAL, ACDT_NONE), - - AutoConstantDefinition(ACT_SURFACE_AMBIENT_COLOUR, "surface_ambient_colour", 4, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_SURFACE_DIFFUSE_COLOUR, "surface_diffuse_colour", 4, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_SURFACE_SPECULAR_COLOUR, "surface_specular_colour", 4, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_SURFACE_EMISSIVE_COLOUR, "surface_emissive_colour", 4, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_SURFACE_SHININESS, "surface_shininess", 1, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_SURFACE_ALPHA_REJECTION_VALUE, "surface_alpha_rejection_value", 1, ET_REAL, ACDT_NONE), - - AutoConstantDefinition(ACT_LIGHT_COUNT, "light_count", 1, ET_REAL, ACDT_NONE), - - AutoConstantDefinition(ACT_AMBIENT_LIGHT_COLOUR, "ambient_light_colour", 4, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_LIGHT_DIFFUSE_COLOUR, "light_diffuse_colour", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_SPECULAR_COLOUR, "light_specular_colour", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_ATTENUATION, "light_attenuation", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_SPOTLIGHT_PARAMS, "spotlight_params", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_POSITION, "light_position", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_POSITION_OBJECT_SPACE, "light_position_object_space", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_POSITION_VIEW_SPACE, "light_position_view_space", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_DIRECTION, "light_direction", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_DIRECTION_OBJECT_SPACE, "light_direction_object_space", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_DIRECTION_VIEW_SPACE, "light_direction_view_space", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_DISTANCE_OBJECT_SPACE, "light_distance_object_space", 1, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_POWER_SCALE, "light_power", 1, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_DIFFUSE_COLOUR_POWER_SCALED, "light_diffuse_colour_power_scaled", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_SPECULAR_COLOUR_POWER_SCALED, "light_specular_colour_power_scaled", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_DIFFUSE_COLOUR_ARRAY, "light_diffuse_colour_array", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_SPECULAR_COLOUR_ARRAY, "light_specular_colour_array", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_DIFFUSE_COLOUR_POWER_SCALED_ARRAY, "light_diffuse_colour_power_scaled_array", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_SPECULAR_COLOUR_POWER_SCALED_ARRAY, "light_specular_colour_power_scaled_array", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_ATTENUATION_ARRAY, "light_attenuation_array", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_POSITION_ARRAY, "light_position_array", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_POSITION_OBJECT_SPACE_ARRAY, "light_position_object_space_array", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_POSITION_VIEW_SPACE_ARRAY, "light_position_view_space_array", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_DIRECTION_ARRAY, "light_direction_array", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_DIRECTION_OBJECT_SPACE_ARRAY, "light_direction_object_space_array", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_DIRECTION_VIEW_SPACE_ARRAY, "light_direction_view_space_array", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_DISTANCE_OBJECT_SPACE_ARRAY, "light_distance_object_space_array", 1, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_POWER_SCALE_ARRAY, "light_power_array", 1, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_SPOTLIGHT_PARAMS_ARRAY, "spotlight_params_array", 4, ET_REAL, ACDT_INT), - - AutoConstantDefinition(ACT_DERIVED_AMBIENT_LIGHT_COLOUR, "derived_ambient_light_colour", 4, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_DERIVED_SCENE_COLOUR, "derived_scene_colour", 4, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_DERIVED_LIGHT_DIFFUSE_COLOUR, "derived_light_diffuse_colour", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_DERIVED_LIGHT_SPECULAR_COLOUR, "derived_light_specular_colour", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_DERIVED_LIGHT_DIFFUSE_COLOUR_ARRAY, "derived_light_diffuse_colour_array", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_DERIVED_LIGHT_SPECULAR_COLOUR_ARRAY, "derived_light_specular_colour_array", 4, ET_REAL, ACDT_INT), - - AutoConstantDefinition(ACT_LIGHT_NUMBER, "light_number", 1, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_CASTS_SHADOWS, "light_casts_shadows", 1, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LIGHT_CASTS_SHADOWS_ARRAY, "light_casts_shadows_array", 1, ET_REAL, ACDT_INT), - - AutoConstantDefinition(ACT_SHADOW_EXTRUSION_DISTANCE, "shadow_extrusion_distance", 1, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_CAMERA_POSITION, "camera_position", 3, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_CAMERA_POSITION_OBJECT_SPACE, "camera_position_object_space", 3, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_CAMERA_RELATIVE_POSITION, "camera_relative_position", 3, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_TEXTURE_VIEWPROJ_MATRIX, "texture_viewproj_matrix", 16, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_TEXTURE_VIEWPROJ_MATRIX_ARRAY, "texture_viewproj_matrix_array", 16, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_TEXTURE_WORLDVIEWPROJ_MATRIX, "texture_worldviewproj_matrix",16, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_TEXTURE_WORLDVIEWPROJ_MATRIX_ARRAY, "texture_worldviewproj_matrix_array",16, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_SPOTLIGHT_VIEWPROJ_MATRIX, "spotlight_viewproj_matrix", 16, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_SPOTLIGHT_VIEWPROJ_MATRIX_ARRAY, "spotlight_viewproj_matrix_array", 16, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_SPOTLIGHT_WORLDVIEWPROJ_MATRIX, "spotlight_worldviewproj_matrix",16, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_SPOTLIGHT_WORLDVIEWPROJ_MATRIX_ARRAY, "spotlight_worldviewproj_matrix_array",16, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_CUSTOM, "custom", 4, ET_REAL, ACDT_INT), // *** needs to be tested - AutoConstantDefinition(ACT_TIME, "time", 1, ET_REAL, ACDT_REAL), - AutoConstantDefinition(ACT_TIME_0_X, "time_0_x", 1, ET_REAL, ACDT_REAL), - AutoConstantDefinition(ACT_COSTIME_0_X, "costime_0_x", 1, ET_REAL, ACDT_REAL), - AutoConstantDefinition(ACT_SINTIME_0_X, "sintime_0_x", 1, ET_REAL, ACDT_REAL), - AutoConstantDefinition(ACT_TANTIME_0_X, "tantime_0_x", 1, ET_REAL, ACDT_REAL), - AutoConstantDefinition(ACT_TIME_0_X_PACKED, "time_0_x_packed", 4, ET_REAL, ACDT_REAL), - AutoConstantDefinition(ACT_TIME_0_1, "time_0_1", 1, ET_REAL, ACDT_REAL), - AutoConstantDefinition(ACT_COSTIME_0_1, "costime_0_1", 1, ET_REAL, ACDT_REAL), - AutoConstantDefinition(ACT_SINTIME_0_1, "sintime_0_1", 1, ET_REAL, ACDT_REAL), - AutoConstantDefinition(ACT_TANTIME_0_1, "tantime_0_1", 1, ET_REAL, ACDT_REAL), - AutoConstantDefinition(ACT_TIME_0_1_PACKED, "time_0_1_packed", 4, ET_REAL, ACDT_REAL), - AutoConstantDefinition(ACT_TIME_0_2PI, "time_0_2pi", 1, ET_REAL, ACDT_REAL), - AutoConstantDefinition(ACT_COSTIME_0_2PI, "costime_0_2pi", 1, ET_REAL, ACDT_REAL), - AutoConstantDefinition(ACT_SINTIME_0_2PI, "sintime_0_2pi", 1, ET_REAL, ACDT_REAL), - AutoConstantDefinition(ACT_TANTIME_0_2PI, "tantime_0_2pi", 1, ET_REAL, ACDT_REAL), - AutoConstantDefinition(ACT_TIME_0_2PI_PACKED, "time_0_2pi_packed", 4, ET_REAL, ACDT_REAL), - AutoConstantDefinition(ACT_FRAME_TIME, "frame_time", 1, ET_REAL, ACDT_REAL), - AutoConstantDefinition(ACT_FPS, "fps", 1, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_VIEWPORT_WIDTH, "viewport_width", 1, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_VIEWPORT_HEIGHT, "viewport_height", 1, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_INVERSE_VIEWPORT_WIDTH, "inverse_viewport_width", 1, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_INVERSE_VIEWPORT_HEIGHT, "inverse_viewport_height", 1, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_VIEWPORT_SIZE, "viewport_size", 4, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_VIEW_DIRECTION, "view_direction", 3, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_VIEW_SIDE_VECTOR, "view_side_vector", 3, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_VIEW_UP_VECTOR, "view_up_vector", 3, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_FOV, "fov", 1, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_NEAR_CLIP_DISTANCE, "near_clip_distance", 1, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_FAR_CLIP_DISTANCE, "far_clip_distance", 1, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_PASS_NUMBER, "pass_number", 1, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_PASS_ITERATION_NUMBER, "pass_iteration_number", 1, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_ANIMATION_PARAMETRIC, "animation_parametric", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_TEXEL_OFFSETS, "texel_offsets", 4, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_SCENE_DEPTH_RANGE, "scene_depth_range", 4, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_SHADOW_SCENE_DEPTH_RANGE, "shadow_scene_depth_range", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_SHADOW_SCENE_DEPTH_RANGE_ARRAY, "shadow_scene_depth_range_array", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_SHADOW_COLOUR, "shadow_colour", 4, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_TEXTURE_SIZE, "texture_size", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_INVERSE_TEXTURE_SIZE, "inverse_texture_size", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_PACKED_TEXTURE_SIZE, "packed_texture_size", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_TEXTURE_MATRIX, "texture_matrix", 16, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_LOD_CAMERA_POSITION, "lod_camera_position", 3, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_LOD_CAMERA_POSITION_OBJECT_SPACE, "lod_camera_position_object_space", 3, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_LIGHT_CUSTOM, "light_custom", 4, ET_REAL, ACDT_INT), - AutoConstantDefinition(ACT_POINT_PARAMS, "point_params", 4, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_MATERIAL_LOD_INDEX, "material_lod_index", 1, ET_INT, ACDT_NONE), - - // NOTE: new auto constants must be added before this line, as the following are merely aliases - // to allow legacy world_ names in scripts - AutoConstantDefinition(ACT_BONE_MATRIX_ARRAY_3x4, "world_matrix_array_3x4", 12, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_BONE_MATRIX_ARRAY, "world_matrix_array", 16, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_BONE_DUALQUATERNION_ARRAY_2x4, "world_dualquaternion_array_2x4", 8, ET_REAL, ACDT_NONE), - AutoConstantDefinition(ACT_BONE_SCALE_SHEAR_MATRIX_ARRAY_3x4, "world_scale_shear_matrix_array_3x4", 12, ET_REAL, ACDT_NONE), - }; - - GpuNamedConstants::GpuNamedConstants() : bufferSize(0), registerCount(0) {} - GpuNamedConstants::~GpuNamedConstants() {} - - GpuLogicalBufferStruct::GpuLogicalBufferStruct() : bufferSize(0) {} - GpuLogicalBufferStruct::~GpuLogicalBufferStruct() {} - - //--------------------------------------------------------------------- - // GpuNamedConstants methods - //--------------------------------------------------------------------- - void GpuNamedConstants::save(const String& filename) const - { - GpuNamedConstantsSerializer ser; - ser.exportNamedConstants(this, filename); - } - //--------------------------------------------------------------------- - void GpuNamedConstants::load(DataStreamPtr& stream) - { - GpuNamedConstantsSerializer ser; - ser.importNamedConstants(stream, this); - } - //----------------------------------------------------------------------------- - size_t GpuNamedConstants::calculateSize(void) const - { - size_t memSize = sizeof(*this); - // Tally up constant defs - memSize += sizeof(GpuConstantDefinition) * map.size(); - - return memSize; - } - //--------------------------------------------------------------------- - // GpuNamedConstantsSerializer methods - //--------------------------------------------------------------------- - GpuNamedConstantsSerializer::GpuNamedConstantsSerializer() - { - mVersion = "[v1.0]"; - } - //--------------------------------------------------------------------- - GpuNamedConstantsSerializer::~GpuNamedConstantsSerializer() - { - - } - //--------------------------------------------------------------------- - void GpuNamedConstantsSerializer::exportNamedConstants( - const GpuNamedConstants* pConsts, const String& filename, Endian endianMode) - { - DataStreamPtr stream = _openFileStream(filename, std::ios::binary | std::ios::out); - exportNamedConstants(pConsts, stream, endianMode); - - stream->close(); - } - //--------------------------------------------------------------------- - void GpuNamedConstantsSerializer::exportNamedConstants( - const GpuNamedConstants* pConsts, DataStreamPtr stream, Endian endianMode) - { - // Decide on endian mode - determineEndianness(endianMode); - - mStream =stream; - if (!stream->isWriteable()) - { - OGRE_EXCEPT(Exception::ERR_CANNOT_WRITE_TO_FILE, - "Unable to write to stream " + stream->getName(), - "GpuNamedConstantsSerializer::exportNamedConstants"); - } - - writeFileHeader(); - - writeInts(((const uint32*)&pConsts->bufferSize), 1); - writeInts(((const uint32*)&pConsts->bufferSize), 1); - writeInts(((const uint32*)&pConsts->bufferSize), 1); - - // simple export of all the named constants, no chunks - // name, physical index - for (const auto& i : pConsts->map) - { - const String& name = i.first; - const GpuConstantDefinition& def = i.second; - - writeString(name); - writeInts(((const uint32*)&def.physicalIndex), 1); - writeInts(((const uint32*)&def.logicalIndex), 1); - uint32 constType = static_cast(def.constType); - writeInts(&constType, 1); - writeInts(((const uint32*)&def.elementSize), 1); - writeInts(((const uint32*)&def.arraySize), 1); - } - - } - //--------------------------------------------------------------------- - void GpuNamedConstantsSerializer::importNamedConstants( - DataStreamPtr& stream, GpuNamedConstants* pDest) - { - // Determine endianness (must be the first thing we do!) - determineEndianness(stream); - - // Check header - readFileHeader(stream); - - // simple file structure, no chunks - pDest->map.clear(); - - readInts(stream, ((uint32*)&pDest->bufferSize), 1); - readInts(stream, ((uint32*)&pDest->bufferSize), 1); - readInts(stream, ((uint32*)&pDest->bufferSize), 1); - - while (!stream->eof()) - { - GpuConstantDefinition def; - String name = readString(stream); - // Hmm, deal with trailing information - if (name.empty()) - continue; - readInts(stream, ((uint32*)&def.physicalIndex), 1); - readInts(stream, ((uint32*)&def.logicalIndex), 1); - uint constType; - readInts(stream, &constType, 1); - def.constType = static_cast(constType); - readInts(stream, ((uint32*)&def.elementSize), 1); - readInts(stream, ((uint32*)&def.arraySize), 1); - - pDest->map[name] = def; - } - } - - //----------------------------------------------------------------------------- - // GpuSharedParameters Methods - //----------------------------------------------------------------------------- - GpuSharedParameters::GpuSharedParameters(const String& name) - :mName(name) - , mVersion(0), mOffset(0), mDirty(false) - { - - } - //----------------------------------------------------------------------------- - size_t GpuSharedParameters::calculateSize(void) const - { - size_t memSize = sizeof(*this); - - memSize += mConstants.size(); - memSize += mName.size() * sizeof(char); - - return memSize; - } - //--------------------------------------------------------------------- - void GpuSharedParameters::addConstantDefinition(const String& name, GpuConstantType constType, uint32 arraySize) - { - if (mNamedConstants.map.find(name) != mNamedConstants.map.end()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Constant entry with name '" + name + "' already exists. ", - "GpuSharedParameters::addConstantDefinition"); - } - GpuConstantDefinition def; - def.arraySize = arraySize; - def.constType = constType; - - // here, we do not consider padding, but rather alignment - def.elementSize = GpuConstantDefinition::getElementSize(constType, false); - - // we try to adhere to GLSL std140 packing rules - // handle alignment requirements - size_t align_size = std::min(def.elementSize == 3 ? 4 : def.elementSize, 4); // vec3 is 16 byte aligned, which is max - align_size *= 4; // bytes - - size_t nextAlignedOffset = ((mOffset + align_size - 1) / align_size) * align_size; - - // abuse logical index to store offset - if (mOffset + align_size > nextAlignedOffset) - { - def.logicalIndex = nextAlignedOffset; - } - else - { - def.logicalIndex = mOffset; - } - - mOffset = def.logicalIndex + (def.constType == GCT_MATRIX_4X3 ? 16 : def.elementSize) * 4; // mat4x3 have a size of 64 bytes - - def.variability = (uint16)GPV_GLOBAL; - - if (def.isFloat()) - { - def.physicalIndex = mConstants.size(); - mConstants.resize(mConstants.size() + def.arraySize * def.elementSize*4); - } - else if (def.isDouble()) - { - def.physicalIndex = mConstants.size(); - mConstants.resize(mConstants.size() + def.arraySize * def.elementSize*8); - } - else if (def.isInt() || def.isUnsignedInt() || def.isBool()) - { - def.physicalIndex = mConstants.size(); - mConstants.resize(mConstants.size() + def.arraySize * def.elementSize*4); - } - else - { - //FIXME Is this the right exception type? - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Constant entry with name '" + name + "' is not a known type.", - "GpuSharedParameters::addConstantDefinition"); - } - - mNamedConstants.map[name] = def; - - ++mVersion; - } - //--------------------------------------------------------------------- - void GpuSharedParameters::removeConstantDefinition(const String& name) - { - GpuConstantDefinitionMap::iterator i = mNamedConstants.map.find(name); - if (i != mNamedConstants.map.end()) - { - GpuConstantDefinition& def = i->second; - size_t numElems = def.elementSize * def.arraySize; - - for (auto& j : mNamedConstants.map) - { - GpuConstantDefinition& otherDef = j.second; - // comes after in the buffer - if (otherDef.physicalIndex > def.physicalIndex) - { - // adjust index - otherDef.logicalIndex -= numElems; - otherDef.physicalIndex -= numElems; - } - } - - // remove and reduce buffer - if (def.isFloat() || def.isInt() || def.isUnsignedInt() || def.isBool()) - { - mNamedConstants.bufferSize -= numElems; - - ConstantList::iterator beg = mConstants.begin(); - std::advance(beg, def.physicalIndex); - ConstantList::iterator en = beg; - std::advance(en, numElems*4); - mConstants.erase(beg, en); - } - else { - //TODO exception handling - } - - ++mVersion; - } - - } - - void GpuSharedParameters::_upload() const - { - OgreAssert(mHardwareBuffer, "not backed by a HardwareBuffer"); - - if (!mDirty) - return; - - mHardwareBuffer->writeData(0, mConstants.size(), mConstants.data()); - } - void GpuSharedParameters::download() - { - OgreAssert(mHardwareBuffer, "not backed by a HardwareBuffer"); - mHardwareBuffer->readData(0, mConstants.size(), mConstants.data()); - } - //--------------------------------------------------------------------- - void GpuSharedParameters::removeAllConstantDefinitions() - { - mOffset = 0; - mNamedConstants.map.clear(); - mNamedConstants.bufferSize = 0; - mConstants.clear(); - } - //--------------------------------------------------------------------- - GpuConstantDefinitionIterator GpuSharedParameters::getConstantDefinitionIterator(void) const - { - return GpuConstantDefinitionIterator(mNamedConstants.map.begin(), mNamedConstants.map.end()); - } - //--------------------------------------------------------------------- - const GpuConstantDefinition& GpuSharedParameters::getConstantDefinition(const String& name) const - { - GpuConstantDefinitionMap::const_iterator i = mNamedConstants.map.find(name); - if (i == mNamedConstants.map.end()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Constant entry with name '" + name + "' does not exist. ", - "GpuSharedParameters::getConstantDefinition"); - } - return i->second; - } - //--------------------------------------------------------------------- - const GpuNamedConstants& GpuSharedParameters::getConstantDefinitions() const - { - return mNamedConstants; - } - //--------------------------------------------------------------------- - void GpuSharedParameters::setNamedConstant(const String& name, const Matrix4& m) - { - _setNamedConstant(name, m[0], 16); - } - //--------------------------------------------------------------------- - void GpuSharedParameters::setNamedConstant(const String& name, const Matrix4* m, uint32 numEntries) - { - _setNamedConstant(name, m[0][0], 16 * numEntries); - } - //--------------------------------------------------------------------- - void GpuSharedParameters::setNamedConstant(const String& name, const ColourValue& colour) - { - _setNamedConstant(name, colour.ptr(), 4); - } - //--------------------------------------------------------------------- - template void GpuSharedParameters::_setNamedConstant(const String& name, const T* val, uint32 count) - { - GpuConstantDefinitionMap::const_iterator i = mNamedConstants.map.find(name); - if (i == mNamedConstants.map.end()) - return; // ignore - - const GpuConstantDefinition& def = i->second; - memcpy(&mConstants[def.physicalIndex], val, sizeof(float) * std::min(count, def.elementSize * def.arraySize)); - _markDirty(); - } - void GpuSharedParameters::setNamedConstant(const String& name, const float* val, uint32 count) - { - _setNamedConstant(name, val, count); - } - //--------------------------------------------------------------------- - void GpuSharedParameters::setNamedConstant(const String& name, const double* val, uint32 count) - { - _setNamedConstant(name, val, count); - } - //--------------------------------------------------------------------- - void GpuSharedParameters::setNamedConstant(const String& name, const int* val, uint32 count) - { - _setNamedConstant(name, val, count); - } - //--------------------------------------------------------------------- - void GpuSharedParameters::setNamedConstant(const String& name, const uint* val, uint32 count) - { - _setNamedConstant(name, val, count); - } - //--------------------------------------------------------------------- - void GpuSharedParameters::_markClean() - { - mDirty = false; - } - //--------------------------------------------------------------------- - void GpuSharedParameters::_markDirty() - { - mDirty = true; - } - - - //----------------------------------------------------------------------------- - // GpuSharedParametersUsage Methods - //----------------------------------------------------------------------------- - GpuSharedParametersUsage::GpuSharedParametersUsage(GpuSharedParametersPtr sharedParams, - GpuProgramParameters* params) - : mSharedParams(sharedParams) - , mParams(params) - { - initCopyData(); - } - //--------------------------------------------------------------------- - void GpuSharedParametersUsage::initCopyData() - { - - mCopyDataList.clear(); - - const GpuConstantDefinitionMap& sharedmap = mSharedParams->getConstantDefinitions().map; - for (const auto& i : sharedmap) - { - const String& pName = i.first; - const GpuConstantDefinition& shareddef = i.second; - - const GpuConstantDefinition* instdef = mParams->_findNamedConstantDefinition(pName, false); - if (instdef) - { - // Check that the definitions are the same - if (instdef->constType == shareddef.constType && - instdef->arraySize <= shareddef.arraySize) - { - CopyDataEntry e; - e.srcDefinition = &shareddef; - e.dstDefinition = instdef; - mCopyDataList.push_back(e); - } - else - LogManager::getSingleton().logWarning("cannot copy shared parameter '" + pName + - "' - type or variability mismatch"); - } - } - - mCopyDataVersion = mSharedParams->getVersion(); - } - //--------------------------------------------------------------------- - void GpuSharedParametersUsage::_copySharedParamsToTargetParams() const - { - // check copy data version - if (mCopyDataVersion != mSharedParams->getVersion()) - const_cast(this)->initCopyData(); - - // force const call to get*Pointer - const GpuSharedParameters* sharedParams = mSharedParams.get(); - - for (const CopyDataEntry& e : mCopyDataList) - { - if (e.dstDefinition->isFloat()) - { - const float* pSrc = sharedParams->getFloatPointer(e.srcDefinition->physicalIndex); - float* pDst = mParams->getFloatPointer(e.dstDefinition->physicalIndex); - - // Deal with matrix transposition here!!! - // transposition is specific to the dest param set, shared params don't do it - if (mParams->getTransposeMatrices() && (e.dstDefinition->constType == GCT_MATRIX_4X4)) - { - // for each matrix that needs to be transposed and copied, - for (size_t iMat = 0; iMat < e.dstDefinition->arraySize; ++iMat) - { - for (int row = 0; row < 4; ++row) - for (int col = 0; col < 4; ++col) - pDst[row * 4 + col] = pSrc[col * 4 + row]; - pSrc += 16; - pDst += 16; - } - } - else - { - if (e.dstDefinition->elementSize == e.srcDefinition->elementSize) - { - // simple copy - memcpy(pDst, pSrc, sizeof(float) * e.dstDefinition->elementSize * e.dstDefinition->arraySize); - } - else - { - // target params may be padded to 4 elements, shared params are packed - assert(e.dstDefinition->elementSize % 4 == 0); - size_t iterations = e.dstDefinition->elementSize / 4 - * e.dstDefinition->arraySize; - assert(iterations > 0); - size_t valsPerIteration = e.srcDefinition->elementSize; - for (size_t l = 0; l < iterations; ++l) - { - memcpy(pDst, pSrc, sizeof(float) * valsPerIteration); - pSrc += valsPerIteration; - pDst += 4; - } - } - } - } - else if (e.dstDefinition->isDouble()) - { - const double* pSrc = sharedParams->getDoublePointer(e.srcDefinition->physicalIndex); - double* pDst = mParams->getDoublePointer(e.dstDefinition->physicalIndex); - - // Deal with matrix transposition here!!! - // transposition is specific to the dest param set, shared params don't do it - if (mParams->getTransposeMatrices() && (e.dstDefinition->constType == GCT_MATRIX_DOUBLE_4X4)) - { - // for each matrix that needs to be transposed and copied, - for (size_t iMat = 0; iMat < e.dstDefinition->arraySize; ++iMat) - { - for (int row = 0; row < 4; ++row) - for (int col = 0; col < 4; ++col) - pDst[row * 4 + col] = pSrc[col * 4 + row]; - pSrc += 16; - pDst += 16; - } - } - else - { - if (e.dstDefinition->elementSize == e.srcDefinition->elementSize) - { - // simple copy - memcpy(pDst, pSrc, sizeof(double) * e.dstDefinition->elementSize * e.dstDefinition->arraySize); - } - else - { - // target params may be padded to 4 elements, shared params are packed - assert(e.dstDefinition->elementSize % 4 == 0); - size_t iterations = e.dstDefinition->elementSize / 4 - * e.dstDefinition->arraySize; - assert(iterations > 0); - size_t valsPerIteration = e.srcDefinition->elementSize; - for (size_t l = 0; l < iterations; ++l) - { - memcpy(pDst, pSrc, sizeof(double) * valsPerIteration); - pSrc += valsPerIteration; - pDst += 4; - } - } - } - } - else if (e.dstDefinition->isInt()) - { - const int* pSrc = sharedParams->getIntPointer(e.srcDefinition->physicalIndex); - int* pDst = mParams->getIntPointer(e.dstDefinition->physicalIndex); - - if (e.dstDefinition->elementSize == e.srcDefinition->elementSize) - { - // simple copy - memcpy(pDst, pSrc, sizeof(int) * e.dstDefinition->elementSize * e.dstDefinition->arraySize); - } - else - { - // target params may be padded to 4 elements, shared params are packed - assert(e.dstDefinition->elementSize % 4 == 0); - size_t iterations = (e.dstDefinition->elementSize / 4) - * e.dstDefinition->arraySize; - assert(iterations > 0); - size_t valsPerIteration = e.srcDefinition->elementSize; - for (size_t l = 0; l < iterations; ++l) - { - memcpy(pDst, pSrc, sizeof(int) * valsPerIteration); - pSrc += valsPerIteration; - pDst += 4; - } - } - } - else if (e.dstDefinition->isUnsignedInt() || e.dstDefinition->isBool()) - { - const uint* pSrc = sharedParams->getUnsignedIntPointer(e.srcDefinition->physicalIndex); - uint* pDst = mParams->getUnsignedIntPointer(e.dstDefinition->physicalIndex); - - if (e.dstDefinition->elementSize == e.srcDefinition->elementSize) - { - // simple copy - memcpy(pDst, pSrc, sizeof(uint) * e.dstDefinition->elementSize * e.dstDefinition->arraySize); - } - else - { - // target params may be padded to 4 elements, shared params are packed - assert(e.dstDefinition->elementSize % 4 == 0); - size_t iterations = (e.dstDefinition->elementSize / 4) - * e.dstDefinition->arraySize; - assert(iterations > 0); - size_t valsPerIteration = e.srcDefinition->elementSize; - for (size_t l = 0; l < iterations; ++l) - { - memcpy(pDst, pSrc, sizeof(uint) * valsPerIteration); - pSrc += valsPerIteration; - pDst += 4; - } - } - } - else { - //TODO add error - } - } - } - - - - //----------------------------------------------------------------------------- - // GpuProgramParameters Methods - //----------------------------------------------------------------------------- - GpuProgramParameters::GpuProgramParameters() : - mCombinedVariability(GPV_GLOBAL) - , mTransposeMatrices(false) - , mIgnoreMissingParams(false) - , mActivePassIterationIndex(std::numeric_limits::max()) - { - static_assert((sizeof(AutoConstantDictionary) / sizeof(AutoConstantDefinition) - 5) == ACT_MATERIAL_LOD_INDEX, - "AutoConstantDictionary out of sync"); - } - GpuProgramParameters::~GpuProgramParameters() {} - - //----------------------------------------------------------------------------- - - GpuProgramParameters::GpuProgramParameters(const GpuProgramParameters& oth) - { - *this = oth; - } - - //----------------------------------------------------------------------------- - GpuProgramParameters& GpuProgramParameters::operator=(const GpuProgramParameters& oth) - { - // let compiler perform shallow copies of structures - // AutoConstantEntry, RealConstantEntry, IntConstantEntry - mConstants = oth.mConstants; - mRegisters = oth.mRegisters; - mAutoConstants = oth.mAutoConstants; - mLogicalToPhysical = oth.mLogicalToPhysical; - mNamedConstants = oth.mNamedConstants; - copySharedParamSetUsage(oth.mSharedParamSets); - - mCombinedVariability = oth.mCombinedVariability; - mTransposeMatrices = oth.mTransposeMatrices; - mIgnoreMissingParams = oth.mIgnoreMissingParams; - mActivePassIterationIndex = oth.mActivePassIterationIndex; - - return *this; - } - //--------------------------------------------------------------------- - void GpuProgramParameters::copySharedParamSetUsage(const GpuSharedParamUsageList& srcList) - { - mSharedParamSets.clear(); - for (const auto& i : srcList) - { - mSharedParamSets.push_back(GpuSharedParametersUsage(i.getSharedParams(), this)); - } - - } - //----------------------------------------------------------------------------- - size_t GpuProgramParameters::calculateSize(void) const - { - size_t memSize = sizeof(*this); - - memSize += mConstants.size(); - memSize += mRegisters.size()*4; - - for (const auto& ac : mAutoConstants) - { - memSize += sizeof(ac); - } - - return memSize; - } - //--------------------------------------------------------------------- - void GpuProgramParameters::_setNamedConstants( - const GpuNamedConstantsPtr& namedConstants) - { - mNamedConstants = namedConstants; - - // Determine any extension to local buffers - - // Size and reset buffer (fill with zero to make comparison later ok) - if (namedConstants->bufferSize*4 > mConstants.size()) - { - mConstants.insert(mConstants.end(), namedConstants->bufferSize * 4 - mConstants.size(), 0); - } - - if(namedConstants->registerCount > mRegisters.size()) - mRegisters.insert(mRegisters.end(), namedConstants->registerCount - mRegisters.size(), 0); - } - //--------------------------------------------------------------------- - void GpuProgramParameters::_setLogicalIndexes(const GpuLogicalBufferStructPtr& indexMap) - { - mLogicalToPhysical = indexMap; - - // resize the internal buffers - // Note that these will only contain something after the first parameter - // set has set some parameters - - // Size and reset buffer (fill with zero to make comparison later ok) - if (indexMap && indexMap->bufferSize*4 > mConstants.size()) - { - mConstants.insert(mConstants.end(), indexMap->bufferSize * 4 - mConstants.size(), 0); - } - } - //---------------------------------------------------------------------() - void GpuProgramParameters::setConstant(size_t index, const Vector4& vec) - { - setConstant(index, vec.ptr(), 1); - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::setConstant(size_t index, Real val) - { - setConstant(index, Vector4(val, 0.0f, 0.0f, 0.0f)); - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::setConstant(size_t index, const Vector3& vec) - { - setConstant(index, Vector4(vec.x, vec.y, vec.z, 1.0f)); - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::setConstant(size_t index, const Vector2& vec) - { - setConstant(index, Vector4(vec.x, vec.y, 1.0f, 1.0f)); - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::setConstant(size_t index, const Matrix4& m) - { - // set as 4x 4-element floats - if (mTransposeMatrices) - { - Matrix4 t = m.transpose(); - GpuProgramParameters::setConstant(index, t[0], 4); - } - else - { - GpuProgramParameters::setConstant(index, m[0], 4); - } - - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::setConstant(size_t index, const Matrix4* pMatrix, - size_t numEntries) - { - if (mTransposeMatrices) - { - for (size_t i = 0; i < numEntries; ++i) - { - Matrix4 t = pMatrix[i].transpose(); - GpuProgramParameters::setConstant(index, t[0], 4); - index += 4; - } - } - else - { - GpuProgramParameters::setConstant(index, pMatrix[0][0], 4 * numEntries); - } - - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::setConstant(size_t index, const ColourValue& colour) - { - setConstant(index, colour.ptr(), 1); - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::setConstant(size_t index, const float *val, size_t count) - { - // Raw buffer size is 4x count - size_t rawCount = count * 4; - // get physical index - assert(mLogicalToPhysical && "GpuProgram hasn't set up the logical -> physical map!"); - - size_t physicalIndex = _getConstantPhysicalIndex(index, rawCount, GPV_GLOBAL, BCT_FLOAT); - - // Copy - _writeRawConstants(physicalIndex, val, rawCount); - - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::setConstant(size_t index, const double *val, size_t count) - { - // Raw buffer size is 4x count - size_t rawCount = count * 4; - // get physical index - assert(mLogicalToPhysical && "GpuProgram hasn't set up the logical -> physical map!"); - - size_t physicalIndex = _getConstantPhysicalIndex(index, rawCount, GPV_GLOBAL, BCT_DOUBLE); - // Copy - _writeRawConstants(physicalIndex, val, rawCount); - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::setConstant(size_t index, const int *val, size_t count) - { - // Raw buffer size is 4x count - size_t rawCount = count * 4; - // get physical index - assert(mLogicalToPhysical && "GpuProgram hasn't set up the logical -> physical map!"); - - size_t physicalIndex = _getConstantPhysicalIndex(index, rawCount, GPV_GLOBAL, BCT_INT); - // Copy - _writeRawConstants(physicalIndex, val, rawCount); - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::setConstant(size_t index, const uint *val, size_t count) - { - // Raw buffer size is 4x count - size_t rawCount = count * 4; - // get physical index - assert(mLogicalToPhysical && "GpuProgram hasn't set up the logical -> physical map!"); - - size_t physicalIndex = _getConstantPhysicalIndex(index, rawCount, GPV_GLOBAL, BCT_INT); - // Copy - _writeRawConstants(physicalIndex, val, rawCount); - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::_writeRawConstant(size_t physicalIndex, const Matrix4& m, size_t elementCount) - { - - // remember, raw content access uses raw float count rather than float4 - if (mTransposeMatrices) - { - Matrix4 t = m.transpose(); - _writeRawConstants(physicalIndex, t[0], elementCount > 16 ? 16 : elementCount); - } - else - { - _writeRawConstants(physicalIndex, m[0], elementCount > 16 ? 16 : elementCount); - } - - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::_writeRawConstant(size_t physicalIndex, const Matrix3& m, size_t elementCount) - { - - // remember, raw content access uses raw float count rather than float4 - if (mTransposeMatrices) - { - Matrix3 t = m.transpose(); - _writeRawConstants(physicalIndex, t[0], elementCount > 9 ? 9 : elementCount); - } - else - { - _writeRawConstants(physicalIndex, m[0], elementCount > 9 ? 9 : elementCount); - } - - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::_writeRawConstant(size_t physicalIndex, const TransformBaseReal* pMatrix, size_t numEntries) - { - // remember, raw content access uses raw float count rather than float4 - if (mTransposeMatrices) - { - for (size_t i = 0; i < numEntries; ++i) - { - Matrix4 t = pMatrix[i].transpose(); - _writeRawConstants(physicalIndex, t[0], 16); - physicalIndex += 16*sizeof(Real); - } - } - else - { - _writeRawConstants(physicalIndex, pMatrix[0][0], 16 * numEntries); - } - - - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::_writeRawConstant(size_t physicalIndex, - const ColourValue& colour, size_t count) - { - // write either the number requested (for packed types) or up to 4 - _writeRawConstants(physicalIndex, colour.ptr(), std::min(count, (size_t)4)); - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::_writeRawConstants(size_t physicalIndex, const double* val, size_t count) - { - assert(physicalIndex + sizeof(float) * count <= mConstants.size()); - for (size_t i = 0; i < count; ++i) - { - float tmp = val[i]; - memcpy(&mConstants[physicalIndex + i * sizeof(float)], &tmp, sizeof(float)); - } - } - void GpuProgramParameters::_writeRegisters(size_t index, const int* val, size_t count) - { - assert(index + count <= mRegisters.size()); - memcpy(&mRegisters[index], val, sizeof(int) * count); - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::_readRawConstants(size_t physicalIndex, size_t count, float* dest) - { - assert(physicalIndex + count <= mConstants.size()); - memcpy(dest, &mConstants[physicalIndex], sizeof(float) * count); - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::_readRawConstants(size_t physicalIndex, size_t count, int* dest) - { - assert(physicalIndex + count <= mConstants.size()); - memcpy(dest, &mConstants[physicalIndex], sizeof(int) * count); - } - //--------------------------------------------------------------------- - uint16 GpuProgramParameters::deriveVariability(GpuProgramParameters::AutoConstantType act) - { - switch(act) - { - case ACT_VIEW_MATRIX: - case ACT_INVERSE_VIEW_MATRIX: - case ACT_TRANSPOSE_VIEW_MATRIX: - case ACT_INVERSE_TRANSPOSE_VIEW_MATRIX: - case ACT_PROJECTION_MATRIX: - case ACT_INVERSE_PROJECTION_MATRIX: - case ACT_TRANSPOSE_PROJECTION_MATRIX: - case ACT_INVERSE_TRANSPOSE_PROJECTION_MATRIX: - case ACT_VIEWPROJ_MATRIX: - case ACT_INVERSE_VIEWPROJ_MATRIX: - case ACT_TRANSPOSE_VIEWPROJ_MATRIX: - case ACT_INVERSE_TRANSPOSE_VIEWPROJ_MATRIX: - case ACT_RENDER_TARGET_FLIPPING: - case ACT_VERTEX_WINDING: - case ACT_AMBIENT_LIGHT_COLOUR: - case ACT_DERIVED_AMBIENT_LIGHT_COLOUR: - case ACT_DERIVED_SCENE_COLOUR: - case ACT_FOG_COLOUR: - case ACT_FOG_PARAMS: - case ACT_SURFACE_AMBIENT_COLOUR: - case ACT_SURFACE_DIFFUSE_COLOUR: - case ACT_SURFACE_SPECULAR_COLOUR: - case ACT_SURFACE_EMISSIVE_COLOUR: - case ACT_SURFACE_SHININESS: - case ACT_SURFACE_ALPHA_REJECTION_VALUE: - case ACT_CAMERA_POSITION: - case ACT_CAMERA_RELATIVE_POSITION: - case ACT_TIME: - case ACT_TIME_0_X: - case ACT_COSTIME_0_X: - case ACT_SINTIME_0_X: - case ACT_TANTIME_0_X: - case ACT_TIME_0_X_PACKED: - case ACT_TIME_0_1: - case ACT_COSTIME_0_1: - case ACT_SINTIME_0_1: - case ACT_TANTIME_0_1: - case ACT_TIME_0_1_PACKED: - case ACT_TIME_0_2PI: - case ACT_COSTIME_0_2PI: - case ACT_SINTIME_0_2PI: - case ACT_TANTIME_0_2PI: - case ACT_TIME_0_2PI_PACKED: - case ACT_FRAME_TIME: - case ACT_FPS: - case ACT_VIEWPORT_WIDTH: - case ACT_VIEWPORT_HEIGHT: - case ACT_INVERSE_VIEWPORT_WIDTH: - case ACT_INVERSE_VIEWPORT_HEIGHT: - case ACT_VIEWPORT_SIZE: - case ACT_TEXEL_OFFSETS: - case ACT_TEXTURE_SIZE: - case ACT_INVERSE_TEXTURE_SIZE: - case ACT_PACKED_TEXTURE_SIZE: - case ACT_SCENE_DEPTH_RANGE: - case ACT_VIEW_DIRECTION: - case ACT_VIEW_SIDE_VECTOR: - case ACT_VIEW_UP_VECTOR: - case ACT_FOV: - case ACT_NEAR_CLIP_DISTANCE: - case ACT_FAR_CLIP_DISTANCE: - case ACT_PASS_NUMBER: - case ACT_TEXTURE_MATRIX: - case ACT_LOD_CAMERA_POSITION: - - return (uint16)GPV_GLOBAL; - - case ACT_WORLD_MATRIX: - case ACT_INVERSE_WORLD_MATRIX: - case ACT_TRANSPOSE_WORLD_MATRIX: - case ACT_INVERSE_TRANSPOSE_WORLD_MATRIX: - case ACT_WORLD_MATRIX_ARRAY_3x4: - case ACT_WORLD_MATRIX_ARRAY: - case ACT_WORLD_DUALQUATERNION_ARRAY_2x4: - case ACT_WORLD_SCALE_SHEAR_MATRIX_ARRAY_3x4: - case ACT_WORLDVIEW_MATRIX: - case ACT_INVERSE_WORLDVIEW_MATRIX: - case ACT_TRANSPOSE_WORLDVIEW_MATRIX: - case ACT_INVERSE_TRANSPOSE_WORLDVIEW_MATRIX: - case ACT_NORMAL_MATRIX: - case ACT_WORLDVIEWPROJ_MATRIX: - case ACT_INVERSE_WORLDVIEWPROJ_MATRIX: - case ACT_TRANSPOSE_WORLDVIEWPROJ_MATRIX: - case ACT_INVERSE_TRANSPOSE_WORLDVIEWPROJ_MATRIX: - case ACT_CAMERA_POSITION_OBJECT_SPACE: - case ACT_LOD_CAMERA_POSITION_OBJECT_SPACE: - case ACT_CUSTOM: - case ACT_ANIMATION_PARAMETRIC: - - return (uint16)GPV_PER_OBJECT; - - case ACT_LIGHT_POSITION_OBJECT_SPACE: - case ACT_LIGHT_DIRECTION_OBJECT_SPACE: - case ACT_LIGHT_DISTANCE_OBJECT_SPACE: - case ACT_LIGHT_POSITION_OBJECT_SPACE_ARRAY: - case ACT_LIGHT_DIRECTION_OBJECT_SPACE_ARRAY: - case ACT_LIGHT_DISTANCE_OBJECT_SPACE_ARRAY: - case ACT_TEXTURE_WORLDVIEWPROJ_MATRIX: - case ACT_TEXTURE_WORLDVIEWPROJ_MATRIX_ARRAY: - case ACT_SPOTLIGHT_WORLDVIEWPROJ_MATRIX: - case ACT_SPOTLIGHT_WORLDVIEWPROJ_MATRIX_ARRAY: - case ACT_SHADOW_EXTRUSION_DISTANCE: - - // These depend on BOTH lights and objects - return ((uint16)GPV_PER_OBJECT) | ((uint16)GPV_LIGHTS); - - case ACT_LIGHT_COUNT: - case ACT_LIGHT_DIFFUSE_COLOUR: - case ACT_LIGHT_SPECULAR_COLOUR: - case ACT_LIGHT_POSITION: - case ACT_LIGHT_DIRECTION: - case ACT_LIGHT_POSITION_VIEW_SPACE: - case ACT_LIGHT_DIRECTION_VIEW_SPACE: - case ACT_SHADOW_SCENE_DEPTH_RANGE: - case ACT_SHADOW_SCENE_DEPTH_RANGE_ARRAY: - case ACT_SHADOW_COLOUR: - case ACT_LIGHT_POWER_SCALE: - case ACT_LIGHT_DIFFUSE_COLOUR_POWER_SCALED: - case ACT_LIGHT_SPECULAR_COLOUR_POWER_SCALED: - case ACT_LIGHT_NUMBER: - case ACT_LIGHT_CASTS_SHADOWS: - case ACT_LIGHT_CASTS_SHADOWS_ARRAY: - case ACT_LIGHT_ATTENUATION: - case ACT_SPOTLIGHT_PARAMS: - case ACT_LIGHT_DIFFUSE_COLOUR_ARRAY: - case ACT_LIGHT_SPECULAR_COLOUR_ARRAY: - case ACT_LIGHT_DIFFUSE_COLOUR_POWER_SCALED_ARRAY: - case ACT_LIGHT_SPECULAR_COLOUR_POWER_SCALED_ARRAY: - case ACT_LIGHT_POSITION_ARRAY: - case ACT_LIGHT_DIRECTION_ARRAY: - case ACT_LIGHT_POSITION_VIEW_SPACE_ARRAY: - case ACT_LIGHT_DIRECTION_VIEW_SPACE_ARRAY: - case ACT_LIGHT_POWER_SCALE_ARRAY: - case ACT_LIGHT_ATTENUATION_ARRAY: - case ACT_SPOTLIGHT_PARAMS_ARRAY: - case ACT_TEXTURE_VIEWPROJ_MATRIX: - case ACT_TEXTURE_VIEWPROJ_MATRIX_ARRAY: - case ACT_SPOTLIGHT_VIEWPROJ_MATRIX: - case ACT_SPOTLIGHT_VIEWPROJ_MATRIX_ARRAY: - case ACT_LIGHT_CUSTOM: - - return (uint16)GPV_LIGHTS; - - case ACT_DERIVED_LIGHT_DIFFUSE_COLOUR: - case ACT_DERIVED_LIGHT_SPECULAR_COLOUR: - case ACT_DERIVED_LIGHT_DIFFUSE_COLOUR_ARRAY: - case ACT_DERIVED_LIGHT_SPECULAR_COLOUR_ARRAY: - - return ((uint16)GPV_GLOBAL | (uint16)GPV_LIGHTS); - - case ACT_PASS_ITERATION_NUMBER: - - return (uint16)GPV_PASS_ITERATION_NUMBER; - - default: - return (uint16)GPV_GLOBAL; - }; - - } - //--------------------------------------------------------------------- - GpuLogicalIndexUse* GpuProgramParameters::getConstantLogicalIndexUse( - size_t logicalIndex, size_t requestedSize, uint16 variability, BaseConstantType type) - { - OgreAssert(type != BCT_SAMPLER, ""); - if (!mLogicalToPhysical) - return NULL; - - GpuLogicalIndexUse* indexUse = 0; - OGRE_LOCK_MUTEX(mLogicalToPhysical->mutex); - - auto logi = mLogicalToPhysical->map.find(logicalIndex); - if (logi == mLogicalToPhysical->map.end()) - { - if (requestedSize) - { - size_t physicalIndex = mConstants.size(); - - // Expand at buffer end - mConstants.insert(mConstants.end(), requestedSize*4, 0); - - // Record extended size for future GPU params re-using this information - mLogicalToPhysical->bufferSize = mConstants.size()/4; - - // low-level programs will not know about mapping ahead of time, so - // populate it. Other params objects will be able to just use this - // accepted mapping since the constant structure will be the same - - // Set up a mapping for all items in the count - size_t currPhys = physicalIndex; - size_t count = requestedSize / 4; - GpuLogicalIndexUseMap::iterator insertedIterator; - - for (size_t logicalNum = 0; logicalNum < count; ++logicalNum) - { - GpuLogicalIndexUseMap::iterator it = - mLogicalToPhysical->map.emplace( - logicalIndex + logicalNum, - GpuLogicalIndexUse(currPhys, requestedSize, variability, type)).first; - currPhys += 4; - - if (logicalNum == 0) - insertedIterator = it; - } - - indexUse = &(insertedIterator->second); - } - else - { - // no match & ignore - return 0; - } - - } - else - { - size_t physicalIndex = logi->second.physicalIndex; - indexUse = &(logi->second); - // check size - if (logi->second.currentSize < requestedSize) - { - // init buffer entry wasn't big enough; could be a mistake on the part - // of the original use, or perhaps a variable length we can't predict - // until first actual runtime use e.g. world matrix array - size_t insertCount = requestedSize - logi->second.currentSize; - auto insertPos = mConstants.begin(); - std::advance(insertPos, physicalIndex); - mConstants.insert(insertPos, insertCount*4, 0); - - // shift all physical positions after this one - for (auto& p : mLogicalToPhysical->map) - { - if (p.second.physicalIndex > physicalIndex) - p.second.physicalIndex += insertCount*4; - } - mLogicalToPhysical->bufferSize += insertCount; - for (auto& ac : mAutoConstants) - { - auto def = getAutoConstantDefinition(ac.paramType); - if (ac.physicalIndex > physicalIndex && def) - { - ac.physicalIndex += insertCount*4; - } - } - if (mNamedConstants) - { - for (auto& p : mNamedConstants->map) - { - if (p.second.physicalIndex > physicalIndex) - p.second.physicalIndex += insertCount * 4; - } - mNamedConstants->bufferSize += insertCount; - } - - logi->second.currentSize += insertCount; - } - } - - if (indexUse && requestedSize) - indexUse->variability = variability; - - return indexUse; - } - //----------------------------------------------------------------------------- - size_t GpuProgramParameters::_getConstantPhysicalIndex( - size_t logicalIndex, size_t requestedSize, uint16 variability, BaseConstantType type) - { - GpuLogicalIndexUse* indexUse = getConstantLogicalIndexUse(logicalIndex, requestedSize, variability, type); - return indexUse ? indexUse->physicalIndex : 0; - } - //----------------------------------------------------------------------------- - size_t GpuProgramParameters::getLogicalIndexForPhysicalIndex(size_t physicalIndex) - { - // perhaps build a reverse map of this sometime (shared in GpuProgram) - for (const auto& p : mLogicalToPhysical->map) - { - if (p.second.physicalIndex == physicalIndex) - return p.first; - } - return std::numeric_limits::max(); - } - //----------------------------------------------------------------------------- - GpuConstantDefinitionIterator GpuProgramParameters::getConstantDefinitionIterator(void) const - { - if (!mNamedConstants) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Named constants have not been initialised, perhaps a compile error"); - - return GpuConstantDefinitionIterator(mNamedConstants->map.begin(), - mNamedConstants->map.end()); - - } - //----------------------------------------------------------------------------- - const GpuNamedConstants& GpuProgramParameters::getConstantDefinitions() const - { - if (!mNamedConstants) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Named constants have not been initialised, perhaps a compile error"); - - return *mNamedConstants; - } - //----------------------------------------------------------------------------- - const GpuConstantDefinition& GpuProgramParameters::getConstantDefinition(const String& name) const - { - if (!mNamedConstants) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Named constants have not been initialised, perhaps a compile error", - "GpuProgramParameters::getConstantDefinitionIterator"); - - - // locate, and throw exception if not found - const GpuConstantDefinition* def = _findNamedConstantDefinition(name, true); - - return *def; - - } - //----------------------------------------------------------------------------- - const GpuConstantDefinition* - GpuProgramParameters::_findNamedConstantDefinition(const String& name, - bool throwExceptionIfNotFound) const - { - if (!mNamedConstants) - { - if (throwExceptionIfNotFound) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Named constants have not been initialised, perhaps a compile error"); - return 0; - } - - // strip array extension - size_t arrStart = name.back() == ']' ? name.find('[') : String::npos; - auto i = mNamedConstants->map.find(arrStart == String::npos ? name : name.substr(0, arrStart)); - if (i == mNamedConstants->map.end() || (i->second.arraySize == 1 && arrStart != String::npos)) - { - if (throwExceptionIfNotFound) - { - String knownNames; -#if OGRE_DEBUG_MODE - // make it easy to catch typo and/or unused shader parameter elimination made by some drivers - knownNames = "Known names are: "; - for (i = mNamedConstants->map.begin(); i != mNamedConstants->map.end(); ++i) - knownNames.append(i->first).append(" "); -#endif - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Parameter called " + name + " does not exist. " + knownNames, - "GpuProgramParameters::_findNamedConstantDefinition"); - } - return 0; - } - else - { - return &(i->second); - } - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::setAutoConstant(size_t index, AutoConstantType acType, uint32 extraInfo) - { - // Get auto constant definition for sizing - const AutoConstantDefinition* autoDef = getAutoConstantDefinition(acType); - - if(!autoDef) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "No constant definition found for type " + - StringConverter::toString(acType), - "GpuProgramParameters::setAutoConstant"); - - // round up to nearest multiple of 4 - size_t sz = autoDef->elementCount; - if (sz % 4 > 0) - { - sz += 4 - (sz % 4); - } - - GpuLogicalIndexUse* indexUse = getConstantLogicalIndexUse(index, sz, deriveVariability(acType), BCT_FLOAT); - - if(indexUse) - _setRawAutoConstant(indexUse->physicalIndex, acType, extraInfo, indexUse->variability, sz); - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::_setRawAutoConstant(size_t physicalIndex, - AutoConstantType acType, uint32 extraInfo, uint16 variability, uint8 elementSize) - { - // update existing index if it exists - bool found = false; - for (auto& ac : mAutoConstants) - { - if (ac.physicalIndex == physicalIndex) - { - ac.paramType = acType; - ac.data = extraInfo; - ac.elementCount = elementSize; - ac.variability = variability; - found = true; - break; - } - } - if (!found) - mAutoConstants.push_back(AutoConstantEntry(acType, physicalIndex, extraInfo, variability, elementSize)); - - mCombinedVariability |= variability; - - - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::_setRawAutoConstantReal(size_t physicalIndex, - AutoConstantType acType, float rData, uint16 variability, uint8 elementSize) - { - // update existing index if it exists - bool found = false; - for (auto& ac : mAutoConstants) - { - if (ac.physicalIndex == physicalIndex) - { - ac.paramType = acType; - ac.fData = rData; - ac.elementCount = elementSize; - ac.variability = variability; - found = true; - break; - } - } - if (!found) - mAutoConstants.push_back(AutoConstantEntry(acType, physicalIndex, rData, variability, elementSize)); - - mCombinedVariability |= variability; - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::clearAutoConstant(size_t index) - { - GpuLogicalIndexUse* indexUse = getConstantLogicalIndexUse(index, 0, GPV_GLOBAL, BCT_FLOAT); - - if (indexUse) - { - // do not clear variability, indexUse is shared across all instances - - size_t physicalIndex = indexUse->physicalIndex; - // update existing index if it exists - for (AutoConstantList::iterator i = mAutoConstants.begin(); - i != mAutoConstants.end(); ++i) - { - if (i->physicalIndex == physicalIndex) - { - mAutoConstants.erase(i); - break; - } - } - } - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::clearNamedAutoConstant(const String& name) - { - const GpuConstantDefinition* def = _findNamedConstantDefinition(name); - if (def) - { - // do not clear variability, def is shared across all instances - - // Autos are always floating point - if (def->isFloat()) { - for (AutoConstantList::iterator i = mAutoConstants.begin(); - i != mAutoConstants.end(); ++i) - { - if (i->physicalIndex == def->physicalIndex) - { - mAutoConstants.erase(i); - break; - } - } - } - } - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::clearAutoConstants(void) - { - mAutoConstants.clear(); - mCombinedVariability = GPV_GLOBAL; - } - //----------------------------------------------------------------------------- - void GpuProgramParameters::setAutoConstantReal(size_t index, AutoConstantType acType, float rData) - { - // Get auto constant definition for sizing - const AutoConstantDefinition* autoDef = getAutoConstantDefinition(acType); - - if(!autoDef) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "No constant definition found for type " + - StringConverter::toString(acType), - "GpuProgramParameters::setAutoConstantReal"); - - // round up to nearest multiple of 4 - size_t sz = autoDef->elementCount; - if (sz % 4 > 0) - { - sz += 4 - (sz % 4); - } - - GpuLogicalIndexUse* indexUse = getConstantLogicalIndexUse(index, sz, deriveVariability(acType), BCT_FLOAT); - - _setRawAutoConstantReal(indexUse->physicalIndex, acType, rData, indexUse->variability, sz); - } - //----------------------------------------------------------------------------- - - //----------------------------------------------------------------------------- - void GpuProgramParameters::_updateAutoParams(const AutoParamDataSource* source, uint16 mask) - { - // abort early if no autos - if (!hasAutoConstants()) return; - // abort early if variability doesn't match any param - if (!(mask & mCombinedVariability)) - return; - - size_t index; - size_t numMatrices; - const Affine3* pMatrix; - size_t m; - Vector3 vec3; - Vector4 vec4; - Matrix3 m3; - Matrix4 scaleM; - DualQuaternion dQuat; - - mActivePassIterationIndex = std::numeric_limits::max(); - - // Autoconstant index is not a physical index - for (const auto& ac : mAutoConstants) - { - // Only update needed slots - if (ac.variability & mask) - { - - switch(ac.paramType) - { - case ACT_VIEW_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getViewMatrix(),ac.elementCount); - break; - case ACT_INVERSE_VIEW_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getInverseViewMatrix(),ac.elementCount); - break; - case ACT_TRANSPOSE_VIEW_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getTransposeViewMatrix(),ac.elementCount); - break; - case ACT_INVERSE_TRANSPOSE_VIEW_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getInverseTransposeViewMatrix(),ac.elementCount); - break; - - case ACT_PROJECTION_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getProjectionMatrix(),ac.elementCount); - break; - case ACT_INVERSE_PROJECTION_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getInverseProjectionMatrix(),ac.elementCount); - break; - case ACT_TRANSPOSE_PROJECTION_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getTransposeProjectionMatrix(),ac.elementCount); - break; - case ACT_INVERSE_TRANSPOSE_PROJECTION_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getInverseTransposeProjectionMatrix(),ac.elementCount); - break; - - case ACT_VIEWPROJ_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getViewProjectionMatrix(),ac.elementCount); - break; - case ACT_INVERSE_VIEWPROJ_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getInverseViewProjMatrix(),ac.elementCount); - break; - case ACT_TRANSPOSE_VIEWPROJ_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getTransposeViewProjMatrix(),ac.elementCount); - break; - case ACT_INVERSE_TRANSPOSE_VIEWPROJ_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getInverseTransposeViewProjMatrix(),ac.elementCount); - break; - case ACT_RENDER_TARGET_FLIPPING: - _writeRawConstant(ac.physicalIndex, source->getCurrentRenderTarget()->requiresTextureFlipping() ? -1.f : +1.f); - break; - case ACT_VERTEX_WINDING: - { - RenderSystem* rsys = Root::getSingleton().getRenderSystem(); - _writeRawConstant(ac.physicalIndex, rsys->getInvertVertexWinding() ? -1.f : +1.f); - } - break; - - // NB ambient light still here because it's not related to a specific light - case ACT_AMBIENT_LIGHT_COLOUR: - _writeRawConstant(ac.physicalIndex, source->getAmbientLightColour(), - ac.elementCount); - break; - case ACT_DERIVED_AMBIENT_LIGHT_COLOUR: - _writeRawConstant(ac.physicalIndex, source->getDerivedAmbientLightColour(), - ac.elementCount); - break; - case ACT_DERIVED_SCENE_COLOUR: - _writeRawConstant(ac.physicalIndex, source->getDerivedSceneColour(), - ac.elementCount); - break; - - case ACT_FOG_COLOUR: - _writeRawConstant(ac.physicalIndex, source->getFogColour(), ac.elementCount); - break; - case ACT_FOG_PARAMS: - _writeRawConstant(ac.physicalIndex, source->getFogParams(), ac.elementCount); - break; - case ACT_POINT_PARAMS: - _writeRawConstant(ac.physicalIndex, source->getPointParams(), ac.elementCount); - break; - case ACT_SURFACE_AMBIENT_COLOUR: - _writeRawConstant(ac.physicalIndex, source->getSurfaceAmbientColour(), - ac.elementCount); - break; - case ACT_SURFACE_DIFFUSE_COLOUR: - _writeRawConstant(ac.physicalIndex, source->getSurfaceDiffuseColour(), - ac.elementCount); - break; - case ACT_SURFACE_SPECULAR_COLOUR: - _writeRawConstant(ac.physicalIndex, source->getSurfaceSpecularColour(), - ac.elementCount); - break; - case ACT_SURFACE_EMISSIVE_COLOUR: - _writeRawConstant(ac.physicalIndex, source->getSurfaceEmissiveColour(), - ac.elementCount); - break; - case ACT_SURFACE_SHININESS: - _writeRawConstant(ac.physicalIndex, source->getSurfaceShininess()); - break; - case ACT_SURFACE_ALPHA_REJECTION_VALUE: - _writeRawConstant(ac.physicalIndex, source->getSurfaceAlphaRejectionValue()); - break; - - case ACT_CAMERA_POSITION: - _writeRawConstant(ac.physicalIndex, source->getCameraPosition(), ac.elementCount); - break; - case ACT_CAMERA_RELATIVE_POSITION: - _writeRawConstant (ac.physicalIndex, source->getCameraRelativePosition(), ac.elementCount); - break; - case ACT_TIME: - _writeRawConstant(ac.physicalIndex, source->getTime() * ac.fData); - break; - case ACT_TIME_0_X: - _writeRawConstant(ac.physicalIndex, source->getTime_0_X(ac.fData)); - break; - case ACT_COSTIME_0_X: - _writeRawConstant(ac.physicalIndex, source->getCosTime_0_X(ac.fData)); - break; - case ACT_SINTIME_0_X: - _writeRawConstant(ac.physicalIndex, source->getSinTime_0_X(ac.fData)); - break; - case ACT_TANTIME_0_X: - _writeRawConstant(ac.physicalIndex, source->getTanTime_0_X(ac.fData)); - break; - case ACT_TIME_0_X_PACKED: - _writeRawConstant(ac.physicalIndex, source->getTime_0_X_packed(ac.fData), ac.elementCount); - break; - case ACT_TIME_0_1: - _writeRawConstant(ac.physicalIndex, source->getTime_0_1(ac.fData)); - break; - case ACT_COSTIME_0_1: - _writeRawConstant(ac.physicalIndex, source->getCosTime_0_1(ac.fData)); - break; - case ACT_SINTIME_0_1: - _writeRawConstant(ac.physicalIndex, source->getSinTime_0_1(ac.fData)); - break; - case ACT_TANTIME_0_1: - _writeRawConstant(ac.physicalIndex, source->getTanTime_0_1(ac.fData)); - break; - case ACT_TIME_0_1_PACKED: - _writeRawConstant(ac.physicalIndex, source->getTime_0_1_packed(ac.fData), ac.elementCount); - break; - case ACT_TIME_0_2PI: - _writeRawConstant(ac.physicalIndex, source->getTime_0_2Pi(ac.fData)); - break; - case ACT_COSTIME_0_2PI: - _writeRawConstant(ac.physicalIndex, source->getCosTime_0_2Pi(ac.fData)); - break; - case ACT_SINTIME_0_2PI: - _writeRawConstant(ac.physicalIndex, source->getSinTime_0_2Pi(ac.fData)); - break; - case ACT_TANTIME_0_2PI: - _writeRawConstant(ac.physicalIndex, source->getTanTime_0_2Pi(ac.fData)); - break; - case ACT_TIME_0_2PI_PACKED: - _writeRawConstant(ac.physicalIndex, source->getTime_0_2Pi_packed(ac.fData), ac.elementCount); - break; - case ACT_FRAME_TIME: - _writeRawConstant(ac.physicalIndex, source->getFrameTime() * ac.fData); - break; - case ACT_FPS: - _writeRawConstant(ac.physicalIndex, source->getFPS()); - break; - case ACT_VIEWPORT_WIDTH: - _writeRawConstant(ac.physicalIndex, source->getViewportWidth()); - break; - case ACT_VIEWPORT_HEIGHT: - _writeRawConstant(ac.physicalIndex, source->getViewportHeight()); - break; - case ACT_INVERSE_VIEWPORT_WIDTH: - _writeRawConstant(ac.physicalIndex, source->getInverseViewportWidth()); - break; - case ACT_INVERSE_VIEWPORT_HEIGHT: - _writeRawConstant(ac.physicalIndex, source->getInverseViewportHeight()); - break; - case ACT_VIEWPORT_SIZE: - _writeRawConstant(ac.physicalIndex, Vector4f( - source->getViewportWidth(), - source->getViewportHeight(), - source->getInverseViewportWidth(), - source->getInverseViewportHeight()), ac.elementCount); - break; - case ACT_TEXEL_OFFSETS: - { - RenderSystem* rsys = Root::getSingleton().getRenderSystem(); - _writeRawConstant(ac.physicalIndex, Vector4f( - rsys->getHorizontalTexelOffset(), - rsys->getVerticalTexelOffset(), - rsys->getHorizontalTexelOffset() * source->getInverseViewportWidth(), - rsys->getVerticalTexelOffset() * source->getInverseViewportHeight()), - ac.elementCount); - } - break; - case ACT_TEXTURE_SIZE: - _writeRawConstant(ac.physicalIndex, source->getTextureSize(ac.data), ac.elementCount); - break; - case ACT_INVERSE_TEXTURE_SIZE: - _writeRawConstant(ac.physicalIndex, source->getInverseTextureSize(ac.data), ac.elementCount); - break; - case ACT_PACKED_TEXTURE_SIZE: - _writeRawConstant(ac.physicalIndex, source->getPackedTextureSize(ac.data), ac.elementCount); - break; - case ACT_SCENE_DEPTH_RANGE: - _writeRawConstant(ac.physicalIndex, source->getSceneDepthRange(), ac.elementCount); - break; - case ACT_VIEW_DIRECTION: - _writeRawConstant(ac.physicalIndex, source->getViewDirection()); - break; - case ACT_VIEW_SIDE_VECTOR: - _writeRawConstant(ac.physicalIndex, source->getViewSideVector()); - break; - case ACT_VIEW_UP_VECTOR: - _writeRawConstant(ac.physicalIndex, source->getViewUpVector()); - break; - case ACT_FOV: - _writeRawConstant(ac.physicalIndex, source->getFOV()); - break; - case ACT_NEAR_CLIP_DISTANCE: - _writeRawConstant(ac.physicalIndex, source->getNearClipDistance()); - break; - case ACT_FAR_CLIP_DISTANCE: - _writeRawConstant(ac.physicalIndex, source->getFarClipDistance()); - break; - case ACT_PASS_NUMBER: - _writeRawConstant(ac.physicalIndex, (float)source->getPassNumber()); - break; - case ACT_PASS_ITERATION_NUMBER: - // this is actually just an initial set-up, it's bound separately, so still global - _writeRawConstant(ac.physicalIndex, 0.0f); - mActivePassIterationIndex = ac.physicalIndex; - break; - case ACT_TEXTURE_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getTextureTransformMatrix(ac.data),ac.elementCount); - break; - case ACT_LOD_CAMERA_POSITION: - _writeRawConstant(ac.physicalIndex, source->getLodCameraPosition(), ac.elementCount); - break; - case ACT_MATERIAL_LOD_INDEX: - _writeRawConstant(ac.physicalIndex, (float)source->getMaterialLodIndex()); - break; - case ACT_TEXTURE_WORLDVIEWPROJ_MATRIX: - // can also be updated in lights - _writeRawConstant(ac.physicalIndex, source->getTextureWorldViewProjMatrix(ac.data),ac.elementCount); - break; - case ACT_TEXTURE_WORLDVIEWPROJ_MATRIX_ARRAY: - for (size_t l = 0; l < ac.data; ++l) - { - // can also be updated in lights - _writeRawConstant(ac.physicalIndex + l*sizeof(Matrix4), - source->getTextureWorldViewProjMatrix(l),ac.elementCount); - } - break; - case ACT_SPOTLIGHT_WORLDVIEWPROJ_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getSpotlightWorldViewProjMatrix(ac.data),ac.elementCount); - break; - case ACT_SPOTLIGHT_WORLDVIEWPROJ_MATRIX_ARRAY: - for (size_t l = 0; l < ac.data; ++l) - _writeRawConstant(ac.physicalIndex + l*sizeof(Matrix4), source->getSpotlightWorldViewProjMatrix(l), ac.elementCount); - break; - case ACT_LIGHT_POSITION_OBJECT_SPACE: - _writeRawConstant(ac.physicalIndex, - source->getInverseWorldMatrix() * - source->getLightAs4DVector(ac.data), - ac.elementCount); - break; - case ACT_LIGHT_DIRECTION_OBJECT_SPACE: - // We need the inverse of the inverse transpose - m3 = source->getTransposeWorldMatrix().linear(); - vec3 = m3 * source->getLightDirection(ac.data); - vec3.normalise(); - // Set as 4D vector for compatibility - _writeRawConstant(ac.physicalIndex, Vector4f(vec3.x, vec3.y, vec3.z, 0.0f), ac.elementCount); - break; - case ACT_LIGHT_DISTANCE_OBJECT_SPACE: - vec3 = source->getInverseWorldMatrix() * source->getLightPosition(ac.data); - _writeRawConstant(ac.physicalIndex, vec3.length()); - break; - case ACT_LIGHT_POSITION_OBJECT_SPACE_ARRAY: - for (size_t l = 0; l < ac.data; ++l) - _writeRawConstant(ac.physicalIndex + l*sizeof(Vector4f), - source->getInverseWorldMatrix() * - source->getLightAs4DVector(l), - ac.elementCount); - break; - - case ACT_LIGHT_DIRECTION_OBJECT_SPACE_ARRAY: - // We need the inverse of the inverse transpose - m3 = source->getTransposeWorldMatrix().linear(); - for (size_t l = 0; l < ac.data; ++l) - { - vec3 = m3 * source->getLightDirection(l); - vec3.normalise(); - _writeRawConstant(ac.physicalIndex + l*sizeof(Vector4f), - Vector4f(vec3.x, vec3.y, vec3.z, 0.0f), ac.elementCount); - } - break; - - case ACT_LIGHT_DISTANCE_OBJECT_SPACE_ARRAY: - for (size_t l = 0; l < ac.data; ++l) - { - vec3 = source->getInverseWorldMatrix() * source->getLightPosition(l); - _writeRawConstant(ac.physicalIndex + l*sizeof(Real), vec3.length()); - } - break; - - case ACT_WORLD_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getWorldMatrix(),ac.elementCount); - break; - case ACT_INVERSE_WORLD_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getInverseWorldMatrix(),ac.elementCount); - break; - case ACT_TRANSPOSE_WORLD_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getTransposeWorldMatrix(),ac.elementCount); - break; - case ACT_INVERSE_TRANSPOSE_WORLD_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getInverseTransposeWorldMatrix(),ac.elementCount); - break; - - case ACT_BONE_MATRIX_ARRAY_3x4: - // Loop over matrices - pMatrix = source->getBoneMatrixArray(); - numMatrices = source->getBoneMatrixCount(); - index = ac.physicalIndex; - for (m = 0; m < numMatrices; ++m) - { - _writeRawConstants(index, (*pMatrix)[0], 12); - index += 12*sizeof(Real); - ++pMatrix; - } - break; - case ACT_BONE_MATRIX_ARRAY: - _writeRawConstant(ac.physicalIndex, source->getBoneMatrixArray(), - source->getBoneMatrixCount()); - break; - case ACT_BONE_DUALQUATERNION_ARRAY_2x4: - // Loop over matrices - pMatrix = source->getBoneMatrixArray(); - numMatrices = source->getBoneMatrixCount(); - index = ac.physicalIndex; - for (m = 0; m < numMatrices; ++m) - { - dQuat.fromTransformationMatrix(*pMatrix); - _writeRawConstants(index, dQuat.ptr(), 8); - index += sizeof(DualQuaternion); - ++pMatrix; - } - break; - case ACT_BONE_SCALE_SHEAR_MATRIX_ARRAY_3x4: - // Loop over matrices - pMatrix = source->getBoneMatrixArray(); - numMatrices = source->getBoneMatrixCount(); - index = ac.physicalIndex; - - scaleM = Matrix4::IDENTITY; - - for (m = 0; m < numMatrices; ++m) - { - //Based on Matrix4::decompostion, but we don't need the rotation or position components - //but do need the scaling and shearing. Shearing isn't available from Matrix4::decomposition - m3 = pMatrix->linear(); - - Matrix3 matQ; - Vector3 scale; - - //vecU is the scaling component with vecU[0] = u01, vecU[1] = u02, vecU[2] = u12 - //vecU[0] is shearing (x,y), vecU[1] is shearing (x,z), and vecU[2] is shearing (y,z) - //The first component represents the coordinate that is being sheared, - //while the second component represents the coordinate which performs the shearing. - Vector3 vecU; - m3.QDUDecomposition( matQ, scale, vecU ); - - scaleM[0][0] = scale.x; - scaleM[1][1] = scale.y; - scaleM[2][2] = scale.z; - - scaleM[0][1] = vecU[0]; - scaleM[0][2] = vecU[1]; - scaleM[1][2] = vecU[2]; - - _writeRawConstants(index, scaleM[0], 12); - index += 12*sizeof(Real); - ++pMatrix; - } - break; - case ACT_WORLDVIEW_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getWorldViewMatrix(),ac.elementCount); - break; - case ACT_INVERSE_WORLDVIEW_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getInverseWorldViewMatrix(),ac.elementCount); - break; - case ACT_TRANSPOSE_WORLDVIEW_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getTransposeWorldViewMatrix(),ac.elementCount); - break; - case ACT_NORMAL_MATRIX: - if(ac.elementCount == 9) // check if shader supports packed data - { - _writeRawConstant(ac.physicalIndex, source->getInverseTransposeWorldViewMatrix().linear(),ac.elementCount); - break; - } - OGRE_FALLTHROUGH; // fallthrough to padded 4x4 matrix - case ACT_INVERSE_TRANSPOSE_WORLDVIEW_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getInverseTransposeWorldViewMatrix(),ac.elementCount); - break; - - case ACT_WORLDVIEWPROJ_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getWorldViewProjMatrix(),ac.elementCount); - break; - case ACT_INVERSE_WORLDVIEWPROJ_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getInverseWorldViewProjMatrix(),ac.elementCount); - break; - case ACT_TRANSPOSE_WORLDVIEWPROJ_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getTransposeWorldViewProjMatrix(),ac.elementCount); - break; - case ACT_INVERSE_TRANSPOSE_WORLDVIEWPROJ_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getInverseTransposeWorldViewProjMatrix(),ac.elementCount); - break; - case ACT_CAMERA_POSITION_OBJECT_SPACE: - _writeRawConstant(ac.physicalIndex, source->getCameraPositionObjectSpace(), ac.elementCount); - break; - case ACT_LOD_CAMERA_POSITION_OBJECT_SPACE: - _writeRawConstant(ac.physicalIndex, source->getLodCameraPositionObjectSpace(), ac.elementCount); - break; - - case ACT_CUSTOM: - case ACT_ANIMATION_PARAMETRIC: - source->getCurrentRenderable()->_updateCustomGpuParameter(ac, this); - break; - case ACT_LIGHT_CUSTOM: - source->updateLightCustomGpuParameter(ac, this); - break; - case ACT_LIGHT_COUNT: - _writeRawConstant(ac.physicalIndex, source->getLightCount()); - break; - case ACT_LIGHT_DIFFUSE_COLOUR: - _writeRawConstant(ac.physicalIndex, source->getLightDiffuseColour(ac.data), ac.elementCount); - break; - case ACT_LIGHT_SPECULAR_COLOUR: - _writeRawConstant(ac.physicalIndex, source->getLightSpecularColour(ac.data), ac.elementCount); - break; - case ACT_LIGHT_POSITION: - // Get as 4D vector, works for directional lights too - // Use element count in case uniform slot is smaller - _writeRawConstant(ac.physicalIndex, - source->getLightAs4DVector(ac.data), ac.elementCount); - break; - case ACT_LIGHT_DIRECTION: - vec3 = source->getLightDirection(ac.data); - // Set as 4D vector for compatibility - // Use element count in case uniform slot is smaller - _writeRawConstant(ac.physicalIndex, Vector4f(vec3.x, vec3.y, vec3.z, 1.0f), ac.elementCount); - break; - case ACT_LIGHT_POSITION_VIEW_SPACE: - _writeRawConstant(ac.physicalIndex, - source->getViewMatrix() * source->getLightAs4DVector(ac.data), ac.elementCount); - break; - case ACT_LIGHT_DIRECTION_VIEW_SPACE: - m3 = source->getInverseTransposeViewMatrix().linear(); - // inverse transpose in case of scaling - vec3 = m3 * source->getLightDirection(ac.data); - vec3.normalise(); - // Set as 4D vector for compatibility - _writeRawConstant(ac.physicalIndex, Vector4f(vec3.x, vec3.y, vec3.z, 0.0f),ac.elementCount); - break; - case ACT_SHADOW_EXTRUSION_DISTANCE: - // extrusion is in object-space, so we have to rescale by the inverse - // of the world scaling to deal with scaled objects - m3 = source->getWorldMatrix().linear(); - _writeRawConstant(ac.physicalIndex, source->getShadowExtrusionDistance() / - Math::Sqrt(std::max(std::max(m3.GetColumn(0).squaredLength(), m3.GetColumn(1).squaredLength()), m3.GetColumn(2).squaredLength()))); - break; - case ACT_SHADOW_SCENE_DEPTH_RANGE: - _writeRawConstant(ac.physicalIndex, source->getShadowSceneDepthRange(ac.data)); - break; - case ACT_SHADOW_SCENE_DEPTH_RANGE_ARRAY: - for (size_t l = 0; l < ac.data; ++l) - _writeRawConstant(ac.physicalIndex + l*ac.elementCount, source->getShadowSceneDepthRange(l), ac.elementCount); - break; - case ACT_SHADOW_COLOUR: - _writeRawConstant(ac.physicalIndex, source->getShadowColour(), ac.elementCount); - break; - case ACT_LIGHT_POWER_SCALE: - _writeRawConstant(ac.physicalIndex, source->getLightPowerScale(ac.data)); - break; - case ACT_LIGHT_DIFFUSE_COLOUR_POWER_SCALED: - _writeRawConstant(ac.physicalIndex, source->getLightDiffuseColourWithPower(ac.data), ac.elementCount); - break; - case ACT_LIGHT_SPECULAR_COLOUR_POWER_SCALED: - _writeRawConstant(ac.physicalIndex, source->getLightSpecularColourWithPower(ac.data), ac.elementCount); - break; - case ACT_LIGHT_NUMBER: - _writeRawConstant(ac.physicalIndex, source->getLightNumber(ac.data)); - break; - case ACT_LIGHT_CASTS_SHADOWS: - _writeRawConstant(ac.physicalIndex, source->getLightCastsShadows(ac.data)); - break; - case ACT_LIGHT_CASTS_SHADOWS_ARRAY: - for (size_t l = 0; l < ac.data; ++l) - _writeRawConstant(ac.physicalIndex + l*sizeof(float), source->getLightCastsShadows(l)); - break; - case ACT_LIGHT_ATTENUATION: - _writeRawConstant(ac.physicalIndex, source->getLightAttenuation(ac.data), ac.elementCount); - break; - case ACT_SPOTLIGHT_PARAMS: - _writeRawConstant(ac.physicalIndex, source->getSpotlightParams(ac.data), ac.elementCount); - break; - case ACT_LIGHT_DIFFUSE_COLOUR_ARRAY: - for (size_t l = 0; l < ac.data; ++l) - _writeRawConstant(ac.physicalIndex + l*sizeof(ColourValue), - source->getLightDiffuseColour(l), ac.elementCount); - break; - - case ACT_LIGHT_SPECULAR_COLOUR_ARRAY: - for (size_t l = 0; l < ac.data; ++l) - _writeRawConstant(ac.physicalIndex + l*sizeof(ColourValue), - source->getLightSpecularColour(l), ac.elementCount); - break; - case ACT_LIGHT_DIFFUSE_COLOUR_POWER_SCALED_ARRAY: - for (size_t l = 0; l < ac.data; ++l) - _writeRawConstant(ac.physicalIndex + l*sizeof(ColourValue), - source->getLightDiffuseColourWithPower(l), ac.elementCount); - break; - - case ACT_LIGHT_SPECULAR_COLOUR_POWER_SCALED_ARRAY: - for (size_t l = 0; l < ac.data; ++l) - _writeRawConstant(ac.physicalIndex + l*sizeof(ColourValue), - source->getLightSpecularColourWithPower(l), ac.elementCount); - break; - - case ACT_LIGHT_POSITION_ARRAY: - // Get as 4D vector, works for directional lights too - for (size_t l = 0; l < ac.data; ++l) - _writeRawConstant(ac.physicalIndex + l*sizeof(Vector4f), - source->getLightAs4DVector(l), ac.elementCount); - break; - - case ACT_LIGHT_DIRECTION_ARRAY: - for (size_t l = 0; l < ac.data; ++l) - { - vec3 = source->getLightDirection(l); - // Set as 4D vector for compatibility - _writeRawConstant(ac.physicalIndex + l*sizeof(Vector4f), - Vector4f(vec3.x, vec3.y, vec3.z, 0.0f), ac.elementCount); - } - break; - - case ACT_LIGHT_POSITION_VIEW_SPACE_ARRAY: - for (size_t l = 0; l < ac.data; ++l) - _writeRawConstant(ac.physicalIndex + l*sizeof(Vector4f), - source->getViewMatrix() * - source->getLightAs4DVector(l), - ac.elementCount); - break; - - case ACT_LIGHT_DIRECTION_VIEW_SPACE_ARRAY: - m3 = source->getInverseTransposeViewMatrix().linear(); - for (size_t l = 0; l < ac.data; ++l) - { - vec3 = m3 * source->getLightDirection(l); - vec3.normalise(); - // Set as 4D vector for compatibility - _writeRawConstant(ac.physicalIndex + l*sizeof(Vector4f), - Vector4f(vec3.x, vec3.y, vec3.z, 0.0f), ac.elementCount); - } - break; - - case ACT_LIGHT_POWER_SCALE_ARRAY: - for (size_t l = 0; l < ac.data; ++l) - _writeRawConstant(ac.physicalIndex + l*sizeof(Real), - source->getLightPowerScale(l)); - break; - - case ACT_LIGHT_ATTENUATION_ARRAY: - for (size_t l = 0; l < ac.data; ++l) - { - _writeRawConstant(ac.physicalIndex + l*sizeof(Vector4f), - source->getLightAttenuation(l), ac.elementCount); - } - break; - case ACT_SPOTLIGHT_PARAMS_ARRAY: - for (size_t l = 0 ; l < ac.data; ++l) - { - _writeRawConstant(ac.physicalIndex + l*sizeof(Vector4f), source->getSpotlightParams(l), - ac.elementCount); - } - break; - case ACT_DERIVED_LIGHT_DIFFUSE_COLOUR: - _writeRawConstant(ac.physicalIndex, - source->getLightDiffuseColourWithPower(ac.data) * source->getSurfaceDiffuseColour(), - ac.elementCount); - break; - case ACT_DERIVED_LIGHT_SPECULAR_COLOUR: - _writeRawConstant(ac.physicalIndex, - source->getLightSpecularColourWithPower(ac.data) * source->getSurfaceSpecularColour(), - ac.elementCount); - break; - case ACT_DERIVED_LIGHT_DIFFUSE_COLOUR_ARRAY: - for (size_t l = 0; l < ac.data; ++l) - { - _writeRawConstant(ac.physicalIndex + l*sizeof(ColourValue), - source->getLightDiffuseColourWithPower(l) * source->getSurfaceDiffuseColour(), - ac.elementCount); - } - break; - case ACT_DERIVED_LIGHT_SPECULAR_COLOUR_ARRAY: - for (size_t l = 0; l < ac.data; ++l) - { - _writeRawConstant(ac.physicalIndex + l*sizeof(ColourValue), - source->getLightSpecularColourWithPower(l) * source->getSurfaceSpecularColour(), - ac.elementCount); - } - break; - case ACT_TEXTURE_VIEWPROJ_MATRIX: - // can also be updated in lights - _writeRawConstant(ac.physicalIndex, source->getTextureViewProjMatrix(ac.data),ac.elementCount); - break; - case ACT_TEXTURE_VIEWPROJ_MATRIX_ARRAY: - for (size_t l = 0; l < ac.data; ++l) - { - // can also be updated in lights - _writeRawConstant(ac.physicalIndex + l*sizeof(Matrix4), - source->getTextureViewProjMatrix(l),ac.elementCount); - } - break; - case ACT_SPOTLIGHT_VIEWPROJ_MATRIX: - _writeRawConstant(ac.physicalIndex, source->getSpotlightViewProjMatrix(ac.data),ac.elementCount); - break; - case ACT_SPOTLIGHT_VIEWPROJ_MATRIX_ARRAY: - for (size_t l = 0; l < ac.data; ++l) - { - // can also be updated in lights - _writeRawConstant(ac.physicalIndex + l*sizeof(Matrix4), - source->getSpotlightViewProjMatrix(l),ac.elementCount); - } - break; - - default: - break; - }; - } - } - - } - //--------------------------------------------------------------------------- - static size_t withArrayOffset(const GpuConstantDefinition* def, const String& name) - { - uint32 offset = 0; - if(name.back() == ']') - { - size_t start = name.find('['); - offset = StringConverter::parseInt(name.substr(start + 1, name.size() - start - 2)); - offset = std::min(offset, def->arraySize - 1); - size_t type_sz = def->isDouble() ? 8 : ( def->isSampler() ? 1 : 4); - offset *= type_sz; - } - - return def->physicalIndex + offset * def->elementSize; - } - - void GpuProgramParameters::setNamedConstant(const String& name, Real val) - { - // look up, and throw an exception if we're not ignoring missing - const GpuConstantDefinition* def = - _findNamedConstantDefinition(name, !mIgnoreMissingParams); - if (def) - _writeRawConstant(withArrayOffset(def, name), val); - } - //--------------------------------------------------------------------------- - void GpuProgramParameters::setNamedConstant(const String& name, int val) - { - // look up, and throw an exception if we're not ignoring missing - const GpuConstantDefinition* def = _findNamedConstantDefinition(name, !mIgnoreMissingParams); - - if(!def) - return; - - if(def->isSampler()) - _writeRegisters(withArrayOffset(def, name), &val, 1); - else - _writeRawConstant(withArrayOffset(def, name), val); - } - //--------------------------------------------------------------------------- - void GpuProgramParameters::setNamedConstant(const String& name, uint val) - { - // look up, and throw an exception if we're not ignoring missing - const GpuConstantDefinition* def = - _findNamedConstantDefinition(name, !mIgnoreMissingParams); - if (def) - _writeRawConstant(withArrayOffset(def, name), val); - } - //--------------------------------------------------------------------------- - void GpuProgramParameters::setNamedConstant(const String& name, const Vector4& vec) - { - // look up, and throw an exception if we're not ignoring missing - const GpuConstantDefinition* def = - _findNamedConstantDefinition(name, !mIgnoreMissingParams); - if (def) - _writeRawConstant(withArrayOffset(def, name), vec, def->elementSize); - } - //--------------------------------------------------------------------------- - void GpuProgramParameters::setNamedConstant(const String& name, const Vector3& vec) - { - // look up, and throw an exception if we're not ignoring missing - const GpuConstantDefinition* def = - _findNamedConstantDefinition(name, !mIgnoreMissingParams); - if (def) - _writeRawConstant(withArrayOffset(def, name), vec); - } - //--------------------------------------------------------------------------- - void GpuProgramParameters::setNamedConstant(const String& name, const Vector2& vec) - { - // look up, and throw an exception if we're not ignoring missing - const GpuConstantDefinition* def = - _findNamedConstantDefinition(name, !mIgnoreMissingParams); - if (def) - _writeRawConstant(withArrayOffset(def, name), vec); - } - //--------------------------------------------------------------------------- - void GpuProgramParameters::setNamedConstant(const String& name, const Matrix4& m) - { - // look up, and throw an exception if we're not ignoring missing - const GpuConstantDefinition* def = - _findNamedConstantDefinition(name, !mIgnoreMissingParams); - if (def) - _writeRawConstant(withArrayOffset(def, name), m, def->elementSize); - } - //--------------------------------------------------------------------------- - void GpuProgramParameters::setNamedConstant(const String& name, const Matrix4* m, - size_t numEntries) - { - // look up, and throw an exception if we're not ignoring missing - const GpuConstantDefinition* def = - _findNamedConstantDefinition(name, !mIgnoreMissingParams); - if (def) - _writeRawConstant(withArrayOffset(def, name), m, numEntries); - } - //--------------------------------------------------------------------------- - void GpuProgramParameters::setNamedConstant(const String& name, const ColourValue& colour) - { - // look up, and throw an exception if we're not ignoring missing - const GpuConstantDefinition* def = - _findNamedConstantDefinition(name, !mIgnoreMissingParams); - if (def) - _writeRawConstant(withArrayOffset(def, name), colour, def->elementSize); - } - //--------------------------------------------------------------------------- - template void GpuProgramParameters::_setNamedConstant(const String& name, const T* val, size_t count) - { - // look up, and throw an exception if we're not ignoring missing - const GpuConstantDefinition* def = _findNamedConstantDefinition(name, !mIgnoreMissingParams); - - if (!def) - return; - - if (count > def->arraySize * def->elementSize) - { - // The shader compiler may trim the array if the trailing elements - // are unused or their usage can be optimized away. Therefore, - // a count exceeding the array size not not an error. - count = def->arraySize * def->elementSize; - } - - _writeRawConstants(withArrayOffset(def, name), val, count); - } - void GpuProgramParameters::setNamedConstant(const String& name, const float* val, size_t count, size_t multiple) - { - _setNamedConstant(name, val, count * multiple); - } - //--------------------------------------------------------------------------- - void GpuProgramParameters::setNamedConstant(const String& name, const double* val, size_t count, size_t multiple) - { - _setNamedConstant(name, val, count * multiple); - } - //--------------------------------------------------------------------------- - void GpuProgramParameters::setNamedConstant(const String& name, - const int *val, size_t count, size_t multiple) - { - size_t rawCount = count * multiple; - // look up, and throw an exception if we're not ignoring missing - const GpuConstantDefinition* def = _findNamedConstantDefinition(name, !mIgnoreMissingParams); - - if(!def) - return; - - if (rawCount > def->arraySize * def->elementSize) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - StringUtil::format("Too many values for parameter %s: %zu > %d", name.c_str(), count, - def->arraySize * def->elementSize)); - - if (def->isSampler()) - _writeRegisters(withArrayOffset(def, name), val, rawCount); - else - _writeRawConstants(withArrayOffset(def, name), val, rawCount); - } - //--------------------------------------------------------------------------- - void GpuProgramParameters::setNamedConstant(const String& name, const uint* val, size_t count, size_t multiple) - { - _setNamedConstant(name, val, count * multiple); - } - //--------------------------------------------------------------------------- - void GpuProgramParameters::setNamedAutoConstant(const String& name, - AutoConstantType acType, uint32 extraInfo) - { - // look up, and throw an exception if we're not ignoring missing - const GpuConstantDefinition* def = - _findNamedConstantDefinition(name, !mIgnoreMissingParams); - if (def) - { - OgreAssert(def->isFloat(), "incompatible parameter type in shader"); - def->variability = deriveVariability(acType); - // make sure we also set variability on the logical index map - getConstantLogicalIndexUse(def->logicalIndex, def->elementSize * def->arraySize, def->variability, BCT_FLOAT); - _setRawAutoConstant(withArrayOffset(def, name), acType, extraInfo, def->variability, def->elementSize); - } - - } - //--------------------------------------------------------------------------- - void GpuProgramParameters::setNamedAutoConstantReal(const String& name, - AutoConstantType acType, Real rData) - { - // look up, and throw an exception if we're not ignoring missing - const GpuConstantDefinition* def = - _findNamedConstantDefinition(name, !mIgnoreMissingParams); - if (def) - { - OgreAssert(def->isFloat(), "incompatible parameter type in shader"); - def->variability = deriveVariability(acType); - // make sure we also set variability on the logical index map - getConstantLogicalIndexUse(def->logicalIndex, def->elementSize * def->arraySize, def->variability, BCT_FLOAT); - _setRawAutoConstantReal(withArrayOffset(def, name), acType, rData, def->variability, def->elementSize); - } - } - //--------------------------------------------------------------------------- - GpuProgramParameters::AutoConstantEntry* GpuProgramParameters::getAutoConstantEntry(const size_t index) - { - if (index < mAutoConstants.size()) - { - return &(mAutoConstants[index]); - } - else - { - return NULL; - } - } - //--------------------------------------------------------------------------- - const GpuProgramParameters::AutoConstantEntry* - GpuProgramParameters::findFloatAutoConstantEntry(size_t logicalIndex) - { - if (!mLogicalToPhysical) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "This is not a low-level parameter parameter object", - "GpuProgramParameters::findFloatAutoConstantEntry"); - - return _findRawAutoConstantEntryFloat( - _getConstantPhysicalIndex(logicalIndex, 0, GPV_GLOBAL, BCT_FLOAT)); - - } - //--------------------------------------------------------------------------- - const GpuProgramParameters::AutoConstantEntry* - GpuProgramParameters::findAutoConstantEntry(const String& paramName) const - { - if (!mNamedConstants) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "This params object is not based on a program with named parameters.", - "GpuProgramParameters::findAutoConstantEntry"); - - const GpuConstantDefinition& def = getConstantDefinition(paramName); - if(def.isSampler()) - return NULL; - return _findRawAutoConstantEntryFloat(def.physicalIndex); - } - //--------------------------------------------------------------------------- - const GpuProgramParameters::AutoConstantEntry* - GpuProgramParameters::_findRawAutoConstantEntryFloat(size_t physicalIndex) const - { - for(const auto& ac : mAutoConstants) - { - // should check that auto is float and not int so that physicalIndex - // doesn't have any ambiguity - // However, all autos are float I think so no need - if (ac.physicalIndex == physicalIndex) - return ∾ - } - - return 0; - - } - //--------------------------------------------------------------------------- - void GpuProgramParameters::copyConstantsFrom(const GpuProgramParameters& source) - { - // Pull buffers & auto constant list over directly - mConstants = source.getConstantList(); - mRegisters = source.mRegisters; - mAutoConstants = source.getAutoConstantList(); - mCombinedVariability = source.mCombinedVariability; - copySharedParamSetUsage(source.mSharedParamSets); - } - //--------------------------------------------------------------------- - void GpuProgramParameters::copyMatchingNamedConstantsFrom(const GpuProgramParameters& source) - { - if (mNamedConstants && source.mNamedConstants) - { - std::map srcToDestNamedMap; - for (auto& m : source.mNamedConstants->map) - { - const String& paramName = m.first; - const GpuConstantDefinition& olddef = m.second; - const GpuConstantDefinition* newdef = _findNamedConstantDefinition(paramName, false); - if (newdef) - { - // Copy data across, based on smallest common definition size - size_t srcsz = olddef.elementSize * olddef.arraySize; - size_t destsz = newdef->elementSize * newdef->arraySize; - size_t sz = std::min(srcsz, destsz); - if (newdef->isFloat() || newdef->isInt() || newdef->isUnsignedInt() || newdef->isBool()) - { - OgreAssertDbg(mConstants.size() >= (newdef->physicalIndex + sz * 4), "Invalid physical index"); - memcpy(getFloatPointer(newdef->physicalIndex), - source.getFloatPointer(olddef.physicalIndex), - sz * 4); - } - else if (newdef->isDouble()) - { - - memcpy(getDoublePointer(newdef->physicalIndex), - source.getDoublePointer(olddef.physicalIndex), - sz * sizeof(double)); - } - else if (newdef->isSampler()) - { - *getRegPointer(newdef->physicalIndex) = *source.getRegPointer(olddef.physicalIndex); - } - else - { - //TODO exception handling - } - // we'll use this map to resolve autos later - // ignore the [0] aliases - if (!StringUtil::endsWith(paramName, "[0]") && source.findAutoConstantEntry(paramName)) - srcToDestNamedMap[olddef.physicalIndex] = paramName; - } - } - - for (const auto& autoEntry : source.mAutoConstants) - { - // find dest physical index - std::map::iterator mi = srcToDestNamedMap.find(autoEntry.physicalIndex); - if (mi != srcToDestNamedMap.end()) - { - if (getAutoConstantDefinition(autoEntry.paramType)->dataType == ACDT_REAL) - { - setNamedAutoConstantReal(mi->second, autoEntry.paramType, autoEntry.fData); - } - else - { - setNamedAutoConstant(mi->second, autoEntry.paramType, autoEntry.data); - } - } - - } - - // Copy shared param sets - for (const auto& usage : source.mSharedParamSets) - { - if (!isUsingSharedParameters(usage.getName())) - { - addSharedParameters(usage.getSharedParams()); - } - } - } - } - //----------------------------------------------------------------------- - const GpuProgramParameters::AutoConstantDefinition* - GpuProgramParameters::getAutoConstantDefinition(const String& name) - { - // find a constant definition that matches name by iterating through the - // constant definition array - bool nameFound = false; - size_t i = 0; - const size_t numDefs = getNumAutoConstantDefinitions(); - while (!nameFound && (i < numDefs)) - { - if (name == AutoConstantDictionary[i].name) - nameFound = true; - else - ++i; - } - - if (nameFound) - return &AutoConstantDictionary[i]; - else - return 0; - } - - //----------------------------------------------------------------------- - const GpuProgramParameters::AutoConstantDefinition* - GpuProgramParameters::getAutoConstantDefinition(AutoConstantType idx) - { - // verify index is equal to acType - // if they are not equal then the dictionary was not setup properly - assert(idx == AutoConstantDictionary[idx].acType); - return &AutoConstantDictionary[idx]; - } - //----------------------------------------------------------------------- - size_t GpuProgramParameters::getNumAutoConstantDefinitions(void) - { - return sizeof(AutoConstantDictionary)/sizeof(AutoConstantDefinition); - } - - //----------------------------------------------------------------------- - void GpuProgramParameters::incPassIterationNumber(void) - { - if (mActivePassIterationIndex != std::numeric_limits::max()) - { - // This is a physical index - *getFloatPointer(mActivePassIterationIndex) += 1; - } - } - //--------------------------------------------------------------------- - void GpuProgramParameters::addSharedParameters(GpuSharedParametersPtr sharedParams) - { - if (!isUsingSharedParameters(sharedParams->getName())) - { - mSharedParamSets.push_back(GpuSharedParametersUsage(sharedParams, this)); - } - } - //--------------------------------------------------------------------- - void GpuProgramParameters::addSharedParameters(const String& sharedParamsName) - { - addSharedParameters(GpuProgramManager::getSingleton().getSharedParameters(sharedParamsName)); - } - //--------------------------------------------------------------------- - bool GpuProgramParameters::isUsingSharedParameters(const String& sharedParamsName) const - { - for (const auto& mSharedParamSet : mSharedParamSets) - { - if (mSharedParamSet.getName() == sharedParamsName) - return true; - } - return false; - } - //--------------------------------------------------------------------- - void GpuProgramParameters::removeSharedParameters(const String& sharedParamsName) - { - for (GpuSharedParamUsageList::iterator i = mSharedParamSets.begin(); - i != mSharedParamSets.end(); ++i) - { - if (i->getName() == sharedParamsName) - { - mSharedParamSets.erase(i); - break; - } - } - } - //--------------------------------------------------------------------- - void GpuProgramParameters::removeAllSharedParameters() - { - mSharedParamSets.clear(); - } - //--------------------------------------------------------------------- - const GpuProgramParameters::GpuSharedParamUsageList& - GpuProgramParameters::getSharedParameters() const - { - return mSharedParamSets; - } - //--------------------------------------------------------------------- - void GpuProgramParameters::_copySharedParams() - { - for (auto& usage : mSharedParamSets) - { - usage._copySharedParamsToTargetParams(); - } - } - - void GpuProgramParameters::_updateSharedParams() - { - for (auto& usage : mSharedParamSets) - { - const GpuSharedParametersPtr& sharedParams = usage.getSharedParams(); - if(sharedParams->_getHardwareBuffer()) - { - sharedParams->_upload(); - sharedParams->_markClean(); - continue; - } - - usage._copySharedParamsToTargetParams(); - } - } -} diff --git a/OgreMain/src/OgreGpuProgramUsage.cpp b/OgreMain/src/OgreGpuProgramUsage.cpp deleted file mode 100644 index 0cd5cd386bd..00000000000 --- a/OgreMain/src/OgreGpuProgramUsage.cpp +++ /dev/null @@ -1,188 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreGpuProgramUsage.h" -#include "OgreGpuProgramManager.h" - -namespace Ogre -{ - //----------------------------------------------------------------------------- - GpuProgramUsage::GpuProgramUsage(GpuProgramType gptype, Pass* parent) : - mParent(parent), mProgram(), mRecreateParams(false),mType(gptype) - { - } - //----------------------------------------------------------------------------- - GpuProgramUsage::GpuProgramUsage(const GpuProgramUsage& oth, Pass* parent) - : mParent(parent) - , mProgram(oth.mProgram) - // nfz: parameters should be copied not just use a shared ptr to the original - , mParameters(OGRE_NEW GpuProgramParameters(*oth.mParameters)) - , mRecreateParams(false) - , mType(oth.mType) - { - } - //--------------------------------------------------------------------- - GpuProgramUsage::~GpuProgramUsage() - { - if (mProgram) - mProgram->removeListener(this); - } - //----------------------------------------------------------------------------- - - GpuProgramPtr GpuProgramUsage::_getProgramByName(const String& name, const String& group, - GpuProgramType type) - { - GpuProgramPtr program = - GpuProgramManager::getSingleton().getByName(name, group); - - //Look again without the group if not found - if (!program) - program = GpuProgramManager::getSingleton().getByName( - name, ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME); - - if (!program) - { - String progType = GpuProgram::getProgramTypeName(type); - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Unable to locate " + progType + " program called " + name); - } - - return program; - } - - void GpuProgramUsage::setProgramName(const String& name, bool resetParams) - { - setProgram(_getProgramByName(name, mParent->getResourceGroup(), mType), resetParams); - } - //----------------------------------------------------------------------------- - void GpuProgramUsage::setParameters(const GpuProgramParametersSharedPtr& params) - { - mParameters = params; - } - //----------------------------------------------------------------------------- - const GpuProgramParametersSharedPtr& GpuProgramUsage::getParameters(void) const - { - if (!mParameters) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "You must specify a program before " - "you can retrieve parameters.", "GpuProgramUsage::getParameters"); - } - - return mParameters; - } - //----------------------------------------------------------------------------- - void GpuProgramUsage::setProgram(const GpuProgramPtr& prog, bool resetParams) - { - if (mProgram) - { - mProgram->removeListener(this); - mRecreateParams = true; - } - - mProgram = prog; - - // Reset parameters - if (resetParams || !mParameters || mRecreateParams) - { - recreateParameters(); - } - - // Listen in on reload events so we can regenerate params - mProgram->addListener(this); - } - //----------------------------------------------------------------------------- - size_t GpuProgramUsage::calculateSize(void) const - { - size_t memSize = sizeof(*this); - - // Tally up passes - if(mProgram) - memSize += mProgram->calculateSize(); - if(mParameters) - memSize += mParameters->calculateSize(); - - return memSize; - } - //----------------------------------------------------------------------------- - void GpuProgramUsage::_load(void) - { - if (!mProgram->isLoaded()) - mProgram->load(); - - // check type - if (mProgram->isLoaded() && mProgram->getType() != mType) - { - String myType = GpuProgram::getProgramTypeName(mType); - String yourType = GpuProgram::getProgramTypeName(mProgram->getType()); - - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - mProgram->getName() + " is a " + yourType + " program, but you are assigning it to a " - + myType + " program slot. This is invalid"); - - } - } - //----------------------------------------------------------------------------- - void GpuProgramUsage::_unload(void) - { - // TODO? - } - //--------------------------------------------------------------------- - void GpuProgramUsage::unloadingComplete(Resource* prog) - { - mRecreateParams = true; - - } - //--------------------------------------------------------------------- - void GpuProgramUsage::loadingComplete(Resource* prog) - { - // Need to re-create parameters - if (mRecreateParams) - recreateParameters(); - - } - //--------------------------------------------------------------------- - void GpuProgramUsage::recreateParameters() - { - // Keep a reference to old ones to copy - GpuProgramParametersSharedPtr savedParams = mParameters; - - // Create new params - mParameters = mProgram->createParameters(); - - // Copy old (matching) values across - // Don't use copyConstantsFrom since program may be different - if (savedParams) - mParameters->copyMatchingNamedConstantsFrom(*savedParams.get()); - - mRecreateParams = false; - - } - - - -} diff --git a/OgreMain/src/OgreHardwareBufferManager.cpp b/OgreMain/src/OgreHardwareBufferManager.cpp deleted file mode 100644 index 632e6318a29..00000000000 --- a/OgreMain/src/OgreHardwareBufferManager.cpp +++ /dev/null @@ -1,381 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreVertexIndexData.h" - -namespace Ogre { - - //----------------------------------------------------------------------- - template<> HardwareBufferManager* Singleton::msSingleton = 0; - HardwareBufferManager* HardwareBufferManager::getSingletonPtr(void) - { - return msSingleton; - } - HardwareBufferManager& HardwareBufferManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //--------------------------------------------------------------------- - HardwareBufferManager::HardwareBufferManager() - { - } - //--------------------------------------------------------------------- - HardwareBufferManager::~HardwareBufferManager() - { - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - // Free temporary vertex buffers every 5 minutes on 100fps - const size_t HardwareBufferManagerBase::UNDER_USED_FRAME_THRESHOLD = 30000; - const size_t HardwareBufferManagerBase::EXPIRED_DELAY_FRAME_THRESHOLD = 5; - //----------------------------------------------------------------------- - HardwareBufferManagerBase::HardwareBufferManagerBase() - : mUnderUsedFrameCount(0) - { - } - //----------------------------------------------------------------------- - HardwareBufferManagerBase::~HardwareBufferManagerBase() - { - // Destroy everything - destroyAllDeclarations(); - destroyAllBindings(); - // No need to destroy main buffers - they will be destroyed by removal of bindings - - // No need to destroy temp buffers - they will be destroyed automatically. - } - //----------------------------------------------------------------------- - VertexDeclaration* HardwareBufferManagerBase::createVertexDeclaration(void) - { - VertexDeclaration* decl = createVertexDeclarationImpl(); - OGRE_LOCK_MUTEX(mVertexDeclarationsMutex); - mVertexDeclarations.insert(decl); - return decl; - } - //----------------------------------------------------------------------- - void HardwareBufferManagerBase::destroyVertexDeclaration(VertexDeclaration* decl) - { - OGRE_LOCK_MUTEX(mVertexDeclarationsMutex); - OgreAssertDbg(mVertexDeclarations.find(decl) != mVertexDeclarations.end(), "unknown decl"); - mVertexDeclarations.erase(decl); - destroyVertexDeclarationImpl(decl); - } - //----------------------------------------------------------------------- - VertexBufferBinding* HardwareBufferManagerBase::createVertexBufferBinding(void) - { - VertexBufferBinding* ret = createVertexBufferBindingImpl(); - OGRE_LOCK_MUTEX(mVertexBufferBindingsMutex); - mVertexBufferBindings.insert(ret); - return ret; - } - //----------------------------------------------------------------------- - void HardwareBufferManagerBase::destroyVertexBufferBinding(VertexBufferBinding* binding) - { - OGRE_LOCK_MUTEX(mVertexBufferBindingsMutex); - OgreAssertDbg(mVertexBufferBindings.find(binding) != mVertexBufferBindings.end(), - "unknown binding"); - mVertexBufferBindings.erase(binding); - destroyVertexBufferBindingImpl(binding); - } - //----------------------------------------------------------------------- - VertexDeclaration* HardwareBufferManagerBase::createVertexDeclarationImpl(void) - { - return OGRE_NEW VertexDeclaration(); - } - //----------------------------------------------------------------------- - void HardwareBufferManagerBase::destroyVertexDeclarationImpl(VertexDeclaration* decl) - { - OGRE_DELETE decl; - } - //----------------------------------------------------------------------- - VertexBufferBinding* HardwareBufferManagerBase::createVertexBufferBindingImpl(void) - { - return OGRE_NEW VertexBufferBinding(); - } - //----------------------------------------------------------------------- - void HardwareBufferManagerBase::destroyVertexBufferBindingImpl(VertexBufferBinding* binding) - { - OGRE_DELETE binding; - } - //----------------------------------------------------------------------- - void HardwareBufferManagerBase::destroyAllDeclarations(void) - { - OGRE_LOCK_MUTEX(mVertexDeclarationsMutex); - for (auto *decl : mVertexDeclarations) - { - destroyVertexDeclarationImpl(decl); - } - mVertexDeclarations.clear(); - } - //----------------------------------------------------------------------- - void HardwareBufferManagerBase::destroyAllBindings(void) - { - OGRE_LOCK_MUTEX(mVertexBufferBindingsMutex); - for (auto *bind : mVertexBufferBindings) - { - destroyVertexBufferBindingImpl(bind); - } - mVertexBufferBindings.clear(); - } - //----------------------------------------------------------------------- - HardwareVertexBufferSharedPtr - HardwareBufferManagerBase::allocateVertexBufferCopy( - const HardwareVertexBufferSharedPtr& sourceBuffer, - HardwareBufferLicensee* licensee, - bool copyData) - { - // pre-lock the mVertexBuffers mutex, which would usually get locked in - // createVertexBuffer - // this prevents a deadlock in _notifyVertexBufferDestroyed - // which locks the same mutexes (via other methods) but in reverse order - OGRE_LOCK_MUTEX(mVertexBuffersMutex); - { - OGRE_LOCK_MUTEX(mTempBuffersMutex); - HardwareVertexBufferSharedPtr vbuf; - - // Locate existing buffer copy in temporary vertex buffers - FreeTemporaryVertexBufferMap::iterator i = - mFreeTempVertexBufferMap.find(sourceBuffer.get()); - if (i == mFreeTempVertexBufferMap.end()) - { - // create new copy buffer, use shadow buffer and make dynamic - vbuf = createVertexBuffer(sourceBuffer->getVertexSize(), sourceBuffer->getNumVertices(), HBU_CPU_TO_GPU, - true); - } - else - { - // Allocate existing copy - vbuf = i->second; - mFreeTempVertexBufferMap.erase(i); - } - - // Copy data? - if (copyData) - { - vbuf->copyData(*(sourceBuffer.get()), 0, 0, sourceBuffer->getSizeInBytes(), true); - } - - // Insert copy into licensee list - mTempVertexBufferLicenses.emplace( - vbuf.get(), - VertexBufferLicense(sourceBuffer.get(), EXPIRED_DELAY_FRAME_THRESHOLD, vbuf, licensee)); - return vbuf; - } - - } - //----------------------------------------------------------------------- - void HardwareBufferManagerBase::releaseVertexBufferCopy( - const HardwareVertexBufferSharedPtr& bufferCopy) - { - OGRE_LOCK_MUTEX(mTempBuffersMutex); - TemporaryVertexBufferLicenseMap::iterator i = - mTempVertexBufferLicenses.find(bufferCopy.get()); - if (i != mTempVertexBufferLicenses.end()) - { - const VertexBufferLicense& vbl = i->second; - vbl.licensee->licenseExpired(vbl.buffer.get()); - mFreeTempVertexBufferMap.emplace(vbl.originalBufferPtr, vbl.buffer); - mTempVertexBufferLicenses.erase(i); - } - } - //----------------------------------------------------------------------- - void HardwareBufferManagerBase::touchVertexBufferCopy( - const HardwareVertexBufferSharedPtr& bufferCopy) - { - OGRE_LOCK_MUTEX(mTempBuffersMutex); - TemporaryVertexBufferLicenseMap::iterator i = - mTempVertexBufferLicenses.find(bufferCopy.get()); - if (i != mTempVertexBufferLicenses.end()) - { - VertexBufferLicense& vbl = i->second; - vbl.expiredDelay = EXPIRED_DELAY_FRAME_THRESHOLD; - } - } - //----------------------------------------------------------------------- - void HardwareBufferManagerBase::_freeUnusedBufferCopies(void) - { - OGRE_LOCK_MUTEX(mTempBuffersMutex); - size_t numFreed = 0; - - // Free unused temporary buffers - FreeTemporaryVertexBufferMap::iterator i; - i = mFreeTempVertexBufferMap.begin(); - while (i != mFreeTempVertexBufferMap.end()) - { - FreeTemporaryVertexBufferMap::iterator icur = i++; - // Free the temporary buffer that referenced by ourself only. - // TODO: Some temporary buffers are bound to vertex buffer bindings - // but not checked out, need to sort out method to unbind them. - if (icur->second.use_count() <= 1) - { - ++numFreed; - mFreeTempVertexBufferMap.erase(icur); - } - } - - StringStream str; - if (numFreed) - { - str << "HardwareBufferManager: Freed " << numFreed << " unused temporary vertex buffers."; - } - else - { - str << "HardwareBufferManager: No unused temporary vertex buffers found."; - } - LogManager::getSingleton().logMessage(str.str(), LML_TRIVIAL); - } - //----------------------------------------------------------------------- - void HardwareBufferManagerBase::_releaseBufferCopies(bool forceFreeUnused) - { - OGRE_LOCK_MUTEX(mTempBuffersMutex); - size_t numUnused = mFreeTempVertexBufferMap.size(); - size_t numUsed = mTempVertexBufferLicenses.size(); - - // Erase the copies which are automatic licensed out - TemporaryVertexBufferLicenseMap::iterator i; - i = mTempVertexBufferLicenses.begin(); - while (i != mTempVertexBufferLicenses.end()) - { - TemporaryVertexBufferLicenseMap::iterator icur = i++; - VertexBufferLicense& vbl = icur->second; - if (forceFreeUnused || --vbl.expiredDelay <= 0) - { - vbl.licensee->licenseExpired(vbl.buffer.get()); - - mFreeTempVertexBufferMap.emplace(vbl.originalBufferPtr, vbl.buffer); - mTempVertexBufferLicenses.erase(icur); - } - } - - // Check whether or not free unused temporary vertex buffers. - if (forceFreeUnused) - { - _freeUnusedBufferCopies(); - mUnderUsedFrameCount = 0; - } - else - { - if (numUsed < numUnused) - { - // Free temporary vertex buffers if too many unused for a long time. - // Do overall temporary vertex buffers instead of per source buffer - // to avoid overhead. - ++mUnderUsedFrameCount; - if (mUnderUsedFrameCount >= UNDER_USED_FRAME_THRESHOLD) - { - _freeUnusedBufferCopies(); - mUnderUsedFrameCount = 0; - } - } - else - { - mUnderUsedFrameCount = 0; - } - } - } - //----------------------------------------------------------------------- - void HardwareBufferManagerBase::_forceReleaseBufferCopies( - const HardwareVertexBufferSharedPtr& sourceBuffer) - { - _forceReleaseBufferCopies(sourceBuffer.get()); - } - //----------------------------------------------------------------------- - void HardwareBufferManagerBase::_forceReleaseBufferCopies( - HardwareVertexBuffer* sourceBuffer) - { - OGRE_LOCK_MUTEX(mTempBuffersMutex); - // Erase the copies which are licensed out - TemporaryVertexBufferLicenseMap::iterator i; - i = mTempVertexBufferLicenses.begin(); - while (i != mTempVertexBufferLicenses.end()) - { - TemporaryVertexBufferLicenseMap::iterator icur = i++; - const VertexBufferLicense& vbl = icur->second; - if (vbl.originalBufferPtr == sourceBuffer) - { - // Just tell the owner that this is being released - vbl.licensee->licenseExpired(vbl.buffer.get()); - mTempVertexBufferLicenses.erase(icur); - } - } - - // Erase the free copies - // - // Why we need this unusual code? It's for resolve reenter problem. - // - // Using mFreeTempVertexBufferMap.erase(sourceBuffer) directly will - // cause reenter into here because vertex buffer destroyed notify. - // In most time there are no problem. But when sourceBuffer is the - // last item of the mFreeTempVertexBufferMap, some STL multimap - // implementation (VC and STLport) will call to clear(), which will - // causing intermediate state of mFreeTempVertexBufferMap, in that - // time destroyed notify back to here cause illegal accessing in - // the end. - // - // For safely reason, use following code to resolve reenter problem. - // - typedef FreeTemporaryVertexBufferMap::iterator _Iter; - std::pair<_Iter, _Iter> range = mFreeTempVertexBufferMap.equal_range(sourceBuffer); - if (range.first != range.second) - { - std::list holdForDelayDestroy; - for (_Iter it = range.first; it != range.second; ++it) - { - if (it->second.use_count() <= 1) - { - holdForDelayDestroy.push_back(it->second); - } - } - - mFreeTempVertexBufferMap.erase(range.first, range.second); - - // holdForDelayDestroy will destroy auto. - } - } - //----------------------------------------------------------------------- - void HardwareBufferManagerBase::_notifyVertexBufferDestroyed(HardwareVertexBuffer* buf) - { - OGRE_LOCK_MUTEX(mVertexBuffersMutex); - VertexBufferList::iterator i = mVertexBuffers.find(buf); - if (i != mVertexBuffers.end()) - { - // release vertex buffer copies - mVertexBuffers.erase(i); - _forceReleaseBufferCopies(buf); - } - } - RenderToVertexBufferSharedPtr HardwareBufferManagerBase::createRenderToVertexBuffer() - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "not supported by RenderSystem"); - } - HardwareBufferPtr HardwareBufferManagerBase::createUniformBuffer(size_t sizeBytes, - HardwareBufferUsage usage, - bool useShadowBuffer) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "not supported by RenderSystem"); - } -} diff --git a/OgreMain/src/OgreHardwareIndexBuffer.cpp b/OgreMain/src/OgreHardwareIndexBuffer.cpp deleted file mode 100644 index 845cf176f1f..00000000000 --- a/OgreMain/src/OgreHardwareIndexBuffer.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreHardwareIndexBuffer.h" - -#include -#include "OgreDefaultHardwareBufferManager.h" - - -namespace Ogre { - - //----------------------------------------------------------------------------- - HardwareIndexBuffer::HardwareIndexBuffer(HardwareBufferManagerBase* mgr, IndexType idxType, - size_t numIndexes, HardwareBuffer::Usage usage, bool useShadowBuffer) - : HardwareBuffer(usage, useShadowBuffer) - , mIndexType(idxType) - , mMgr(mgr) - , mNumIndexes(numIndexes) - { - // Calculate the size of the indexes - mIndexSize = indexSize(idxType); - mSizeInBytes = mIndexSize * mNumIndexes; - - if (idxType == IT_32BIT && Root::getSingletonPtr() && Root::getSingleton().getRenderSystem()) - { - if (!Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_32BIT_INDEX)) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "32 bit index buffers are not supported"); - } - } - - // Create a shadow buffer if required - if (useShadowBuffer) - { - mShadowBuffer = std::make_unique(mSizeInBytes); - } - } - - HardwareIndexBuffer::HardwareIndexBuffer(HardwareBufferManagerBase* mgr, IndexType idxType, - size_t numIndexes, HardwareBuffer* delegate) - : HardwareIndexBuffer(mgr, idxType, numIndexes, delegate->getUsage(), false) - { - mDelegate.reset(delegate); - } - - //----------------------------------------------------------------------------- - HardwareIndexBuffer::~HardwareIndexBuffer() - { - } - -} - diff --git a/OgreMain/src/OgreHardwareOcclusionQuery.cpp b/OgreMain/src/OgreHardwareOcclusionQuery.cpp deleted file mode 100644 index 0b3b889d9cb..00000000000 --- a/OgreMain/src/OgreHardwareOcclusionQuery.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" -#include "OgreHardwareOcclusionQuery.h" - -namespace Ogre { - - - HardwareOcclusionQuery::HardwareOcclusionQuery() : - mPixelCount(0), - mIsQueryResultStillOutstanding(false) - { - } - HardwareOcclusionQuery::~HardwareOcclusionQuery() - { - } - -} - diff --git a/OgreMain/src/OgreHardwarePixelBuffer.cpp b/OgreMain/src/OgreHardwarePixelBuffer.cpp deleted file mode 100644 index 51679f5807f..00000000000 --- a/OgreMain/src/OgreHardwarePixelBuffer.cpp +++ /dev/null @@ -1,194 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreImage.h" -#include "OgreRenderTexture.h" - -namespace Ogre -{ - - //----------------------------------------------------------------------------- - HardwarePixelBuffer::HardwarePixelBuffer(uint32 width, uint32 height, uint32 depth, - PixelFormat format, - HardwareBuffer::Usage usage, bool useShadowBuffer): - HardwareBuffer(usage, useShadowBuffer), - mCurrentLockOptions(), mWidth(width), mHeight(height), mDepth(depth), - mFormat(format) - { - // Default - mRowPitch = mWidth; - mSlicePitch = mHeight*mWidth; - mSizeInBytes = PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat); - } - - //----------------------------------------------------------------------------- - HardwarePixelBuffer::~HardwarePixelBuffer() - { - if (mUsage & TU_RENDERTARGET) - { - // Delete all render targets that are not yet deleted via _clearSliceRTT because the rendertarget - // was deleted by the user. - for (auto rt : mSliceTRT) - { - if (rt) - Root::getSingleton().getRenderSystem()->destroyRenderTarget(rt->getName()); - } - } - } - - //----------------------------------------------------------------------------- - void* HardwarePixelBuffer::lock(size_t offset, size_t length, LockOptions options) - { - OgreAssert(!isLocked(), "already locked"); - OgreAssert(offset == 0 && length == mSizeInBytes, "must lock box or entire buffer"); - - Box myBox(0, 0, 0, mWidth, mHeight, mDepth); - const PixelBox &rv = lock(myBox, options); - return rv.data; - } - - //----------------------------------------------------------------------------- - const PixelBox& HardwarePixelBuffer::lock(const Box& lockBox, LockOptions options) - { - if (mShadowBuffer) - { - if (options != HBL_READ_ONLY) - { - // we have to assume a read / write lock so we use the shadow buffer - // and tag for sync on unlock() - mShadowUpdated = true; - } - - mCurrentLock = static_cast(mShadowBuffer.get())->lock(lockBox, options); - } - else - { - mCurrentLockOptions = options; - mLockedBox = lockBox; - // Lock the real buffer if there is no shadow buffer - mCurrentLock = lockImpl(lockBox, options); - mIsLocked = true; - } - - return mCurrentLock; - } - - //----------------------------------------------------------------------------- - const PixelBox& HardwarePixelBuffer::getCurrentLock() - { - OgreAssert(isLocked(), "buffer not locked"); - return mCurrentLock; - } - - //----------------------------------------------------------------------------- - /// Internal implementation of lock() - void* HardwarePixelBuffer::lockImpl(size_t offset, size_t length, LockOptions options) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "lockImpl(offset,length) is not valid for PixelBuffers and should never be called", - "HardwarePixelBuffer::lockImpl"); - } - - //----------------------------------------------------------------------------- - - void HardwarePixelBuffer::blit(const HardwarePixelBufferSharedPtr &src, const Box &srcBox, const Box &dstBox) - { - if(isLocked() || src->isLocked()) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Source and destination buffer may not be locked!"); - } - if(src.get() == this) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Source must not be the same object"); - } - - LockOptions method = HBL_WRITE_ONLY; - if (dstBox.left == 0 && dstBox.top == 0 && dstBox.front == 0 && dstBox.right == mWidth && - dstBox.bottom == mHeight && dstBox.back == mDepth) - // Entire buffer -- we can discard the previous contents - method = HBL_DISCARD; - - src->blitToMemory(srcBox, lock(dstBox, method)); - unlock(); - } - //----------------------------------------------------------------------------- - void HardwarePixelBuffer::blit(const HardwarePixelBufferSharedPtr &src) - { - blit(src, Box(src->getSize()), Box(getSize())); - } - //----------------------------------------------------------------------------- - void HardwarePixelBuffer::readData(size_t offset, size_t length, void* pDest) - { - // allow easy full buffer reads - if (offset == 0 && length == mSizeInBytes) - { - Box box(0, 0, 0, mWidth, mHeight, mDepth); - blitToMemory(box, PixelBox(box, mFormat, pDest)); - return; - } - - // TODO - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, - "Reading a byte range is not implemented. Use blitToMemory.", - "HardwarePixelBuffer::readData"); - } - //----------------------------------------------------------------------------- - - void HardwarePixelBuffer::writeData(size_t offset, size_t length, const void* pSource, - bool discardWholeBuffer) - { - // allow easy full buffer updates - if (offset == 0 && length == mSizeInBytes) - { - Box box(0, 0, 0, mWidth, mHeight, mDepth); - // we know pSource will not be written to - blitFromMemory(PixelBox(box, mFormat, const_cast(pSource)), box); - return; - } - - // TODO - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, - "Writing a byte range is not implemented. Use blitFromMemory.", - "HardwarePixelBuffer::writeData"); - } - //----------------------------------------------------------------------------- - - RenderTexture *HardwarePixelBuffer::getRenderTarget(size_t zoffset) - { - assert(mUsage & TU_RENDERTARGET); - return mSliceTRT.at(zoffset); - } - //----------------------------------------------------------------------------- - - void HardwarePixelBuffer::_clearSliceRTT(size_t zoffset) - { - if(zoffset < mSliceTRT.size()) - mSliceTRT[zoffset] = NULL; - } - -} diff --git a/OgreMain/src/OgreHardwareVertexBuffer.cpp b/OgreMain/src/OgreHardwareVertexBuffer.cpp deleted file mode 100644 index ba3359eb98d..00000000000 --- a/OgreMain/src/OgreHardwareVertexBuffer.cpp +++ /dev/null @@ -1,750 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreHardwareVertexBuffer.h" - -#include -#include "OgreDefaultHardwareBufferManager.h" - -namespace Ogre { - - //----------------------------------------------------------------------------- - HardwareVertexBuffer::HardwareVertexBuffer(HardwareBufferManagerBase* mgr, size_t vertexSize, - size_t numVertices, HardwareBuffer::Usage usage, bool useShadowBuffer) - : HardwareBuffer(usage, useShadowBuffer), - mIsInstanceData(false), - mMgr(mgr), - mNumVertices(numVertices), - mVertexSize(vertexSize), - mInstanceDataStepRate(1) - { - // Calculate the size of the vertices - mSizeInBytes = mVertexSize * numVertices; - - // Create a shadow buffer if required - if (useShadowBuffer) - { - mShadowBuffer = std::make_unique(mSizeInBytes); - } - - } - HardwareVertexBuffer::HardwareVertexBuffer(HardwareBufferManagerBase* mgr, size_t vertexSize, - size_t numVertices, HardwareBuffer* delegate) - : HardwareVertexBuffer(mgr, vertexSize, numVertices, delegate->getUsage(), false) - { - mDelegate.reset(delegate); - } - //----------------------------------------------------------------------------- - HardwareVertexBuffer::~HardwareVertexBuffer() - { - if (mMgr) - { - mMgr->_notifyVertexBufferDestroyed(this); - } - } - //----------------------------------------------------------------------------- - void HardwareVertexBuffer::setIsInstanceData( const bool val ) - { - RenderSystem* rs = Root::getSingleton().getRenderSystem(); - - OgreAssert(!val || rs->getCapabilities()->hasCapability(RSC_VERTEX_BUFFER_INSTANCE_DATA), - "unsupported by rendersystem"); - - mIsInstanceData = val; - } - //----------------------------------------------------------------------------- - uint32 HardwareVertexBuffer::getInstanceDataStepRate() const - { - return mInstanceDataStepRate; - } - //----------------------------------------------------------------------------- - void HardwareVertexBuffer::setInstanceDataStepRate( const size_t val ) - { - if (val > 0) - { - mInstanceDataStepRate = val; - } - else - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Instance data step rate must be bigger then 0.", - "HardwareVertexBuffer::setInstanceDataStepRate"); - } - } - //----------------------------------------------------------------------------- - // VertexElement - //----------------------------------------------------------------------------- - VertexElement::VertexElement(unsigned short source, size_t offset, VertexElementType theType, - VertexElementSemantic semantic, unsigned short index) - : mOffset(offset), mSource(source), mIndex(index), mType(theType), mSemantic(semantic) - { - } - //----------------------------------------------------------------------------- - size_t VertexElement::getSize(void) const - { - return getTypeSize(mType); - } - //----------------------------------------------------------------------------- - size_t VertexElement::getTypeSize(VertexElementType etype) - { - switch(etype) - { - case VET_FLOAT1: - return sizeof(float); - case VET_FLOAT2: - return sizeof(float)*2; - case VET_FLOAT3: - return sizeof(float)*3; - case VET_FLOAT4: - return sizeof(float)*4; - case VET_DOUBLE1: - return sizeof(double); - case VET_DOUBLE2: - return sizeof(double)*2; - case VET_DOUBLE3: - return sizeof(double)*3; - case VET_DOUBLE4: - return sizeof(double)*4; - case VET_SHORT1: - case VET_USHORT1: - return sizeof( short ); - case VET_SHORT2: - case VET_SHORT2_NORM: - case VET_USHORT2: - case VET_USHORT2_NORM: - return sizeof( short ) * 2; - case VET_SHORT3: - case VET_USHORT3: - return sizeof( short ) * 3; - case VET_SHORT4: - case VET_SHORT4_NORM: - case VET_USHORT4: - case VET_USHORT4_NORM: - return sizeof( short ) * 4; - case VET_INT1: - case VET_UINT1: - return sizeof( int ); - case VET_INT2: - case VET_UINT2: - return sizeof( int ) * 2; - case VET_INT3: - case VET_UINT3: - return sizeof( int ) * 3; - case VET_INT4: - case VET_UINT4: - return sizeof( int ) * 4; - case VET_BYTE4: - case VET_BYTE4_NORM: - case VET_UBYTE4: - case VET_UBYTE4_NORM: - case _DETAIL_SWAP_RB: - return sizeof(char)*4; - case VET_INT_10_10_10_2_NORM: - return 4; - } - return 0; - } - //----------------------------------------------------------------------------- - unsigned short VertexElement::getTypeCount(VertexElementType etype) - { - switch (etype) - { - case VET_FLOAT1: - case VET_SHORT1: - case VET_USHORT1: - case VET_UINT1: - case VET_INT1: - case VET_DOUBLE1: - return 1; - case VET_FLOAT2: - case VET_SHORT2: - case VET_SHORT2_NORM: - case VET_USHORT2: - case VET_USHORT2_NORM: - case VET_UINT2: - case VET_INT2: - case VET_DOUBLE2: - return 2; - case VET_FLOAT3: - case VET_SHORT3: - case VET_USHORT3: - case VET_UINT3: - case VET_INT3: - case VET_DOUBLE3: - return 3; - case VET_FLOAT4: - case VET_SHORT4: - case VET_SHORT4_NORM: - case VET_USHORT4: - case VET_USHORT4_NORM: - case VET_UINT4: - case VET_INT4: - case VET_DOUBLE4: - case VET_BYTE4: - case VET_UBYTE4: - case VET_BYTE4_NORM: - case VET_UBYTE4_NORM: - case _DETAIL_SWAP_RB: - case VET_INT_10_10_10_2_NORM: - return 4; - } - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Invalid type", - "VertexElement::getTypeCount"); - } - //----------------------------------------------------------------------------- - VertexElementType VertexElement::multiplyTypeCount(VertexElementType baseType, - unsigned short count) - { - OgreAssert(count > 0 && count < 5, "Count out of range"); - - switch (baseType) - { - case VET_FLOAT1: - case VET_DOUBLE1: - case VET_INT1: - case VET_UINT1: - // evil enumeration arithmetic - return static_cast( baseType + count - 1 ); - - case VET_SHORT1: - case VET_SHORT2: - if ( count <= 2 ) - { - return VET_SHORT2; - } - return VET_SHORT4; - - case VET_USHORT1: - case VET_USHORT2: - if ( count <= 2 ) - { - return VET_USHORT2; - } - return VET_USHORT4; - - case VET_SHORT2_NORM: - if ( count <= 2 ) - { - return VET_SHORT2_NORM; - } - return VET_SHORT4_NORM; - - case VET_USHORT2_NORM: - if ( count <= 2 ) - { - return VET_USHORT2_NORM; - } - return VET_USHORT4_NORM; - - case VET_BYTE4: - case VET_BYTE4_NORM: - case VET_UBYTE4: - case VET_UBYTE4_NORM: - return baseType; - - default: - break; - } - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Invalid base type", - "VertexElement::multiplyTypeCount"); - } - //-------------------------------------------------------------------------- - void VertexElement::convertColourValue(VertexElementType srcType, VertexElementType dstType, uint32* ptr) - { - if (srcType == dstType) - return; - - // Conversion between ARGB and ABGR is always a case of flipping R/B - *ptr = ((*ptr & 0x00FF0000) >> 16) | ((*ptr & 0x000000FF) << 16) | (*ptr & 0xFF00FF00); - } - //----------------------------------------------------------------------------- - VertexElementType VertexElement::getBaseType(VertexElementType multiType) - { - switch (multiType) - { - case VET_FLOAT1: - case VET_FLOAT2: - case VET_FLOAT3: - case VET_FLOAT4: - return VET_FLOAT1; - case VET_DOUBLE1: - case VET_DOUBLE2: - case VET_DOUBLE3: - case VET_DOUBLE4: - return VET_DOUBLE1; - case VET_INT1: - case VET_INT2: - case VET_INT3: - case VET_INT4: - return VET_INT1; - case VET_UINT1: - case VET_UINT2: - case VET_UINT3: - case VET_UINT4: - return VET_UINT1; - case VET_SHORT1: - case VET_SHORT2: - case VET_SHORT3: - case VET_SHORT4: - return VET_SHORT1; - case VET_USHORT1: - case VET_USHORT2: - case VET_USHORT3: - case VET_USHORT4: - return VET_USHORT1; - case VET_SHORT2_NORM: - case VET_SHORT4_NORM: - return VET_SHORT2_NORM; - case VET_USHORT2_NORM: - case VET_USHORT4_NORM: - return VET_USHORT2_NORM; - case VET_BYTE4: - return VET_BYTE4; - case VET_BYTE4_NORM: - return VET_BYTE4_NORM; - case VET_UBYTE4: - return VET_UBYTE4; - case VET_UBYTE4_NORM: - case _DETAIL_SWAP_RB: - return VET_UBYTE4_NORM; - case VET_INT_10_10_10_2_NORM: - return VET_INT_10_10_10_2_NORM; - }; - // To keep compiler happy - return VET_FLOAT1; - } - //----------------------------------------------------------------------------- - VertexDeclaration::VertexDeclaration() - { - } - //----------------------------------------------------------------------------- - VertexDeclaration::~VertexDeclaration() - { - } - //----------------------------------------------------------------------------- - const VertexDeclaration::VertexElementList& VertexDeclaration::getElements(void) const - { - return mElementList; - } - //----------------------------------------------------------------------------- - const VertexElement& VertexDeclaration::addElement(unsigned short source, - size_t offset, VertexElementType theType, - VertexElementSemantic semantic, unsigned short index) - { - mElementList.push_back(VertexElement(source, offset, theType, semantic, index)); - notifyChanged(); - return mElementList.back(); - } - //----------------------------------------------------------------------------- - const VertexElement& VertexDeclaration::insertElement(unsigned short atPosition, - unsigned short source, size_t offset, VertexElementType theType, - VertexElementSemantic semantic, unsigned short index) - { - if (atPosition >= mElementList.size()) - { - return addElement(source, offset, theType, semantic, index); - } - - VertexElementList::iterator i = mElementList.begin(); - for (unsigned short n = 0; n < atPosition; ++n) - ++i; - - i = mElementList.insert(i, - VertexElement(source, offset, theType, semantic, index)); - - notifyChanged(); - return *i; - } - //----------------------------------------------------------------------------- - const VertexElement* VertexDeclaration::getElement(unsigned short index) const - { - assert(index < mElementList.size() && "Index out of bounds"); - - VertexElementList::const_iterator i = mElementList.begin(); - for (unsigned short n = 0; n < index; ++n) - ++i; - - return &(*i); - - } - //----------------------------------------------------------------------------- - void VertexDeclaration::removeElement(unsigned short elem_index) - { - assert(elem_index < mElementList.size() && "Index out of bounds"); - VertexElementList::iterator i = mElementList.begin(); - for (unsigned short n = 0; n < elem_index; ++n) - ++i; - mElementList.erase(i); - notifyChanged(); - } - //----------------------------------------------------------------------------- - void VertexDeclaration::removeElement(VertexElementSemantic semantic, unsigned short index) - { - VertexElementList::iterator ei, eiend; - eiend = mElementList.end(); - for (ei = mElementList.begin(); ei != eiend; ++ei) - { - if (ei->getSemantic() == semantic && ei->getIndex() == index) - { - mElementList.erase(ei); - notifyChanged(); - break; - } - } - } - //----------------------------------------------------------------------------- - void VertexDeclaration::removeAllElements(void) - { - mElementList.clear(); - notifyChanged(); - } - //----------------------------------------------------------------------------- - void VertexDeclaration::modifyElement(unsigned short elem_index, - unsigned short source, size_t offset, VertexElementType theType, - VertexElementSemantic semantic, unsigned short index) - { - assert(elem_index < mElementList.size() && "Index out of bounds"); - VertexElementList::iterator i = mElementList.begin(); - std::advance(i, elem_index); - (*i) = VertexElement(source, offset, theType, semantic, index); - notifyChanged(); - } - //----------------------------------------------------------------------------- - const VertexElement* VertexDeclaration::findElementBySemantic( - VertexElementSemantic sem, unsigned short index) const - { - for (auto& e : mElementList) - { - if (e.getSemantic() == sem && e.getIndex() == index) - { - return &e; - } - } - - return NULL; - } - //----------------------------------------------------------------------------- - VertexDeclaration::VertexElementList VertexDeclaration::findElementsBySource( - unsigned short source) const - { - VertexElementList retList; - for (auto& e : mElementList) - { - if (e.getSource() == source) - { - retList.push_back(e); - } - } - return retList; - } - - //----------------------------------------------------------------------------- - size_t VertexDeclaration::getVertexSize(unsigned short source) const - { - size_t sz = 0; - for (auto& e : mElementList) - { - if (e.getSource() == source) - { - sz += e.getSize(); - - } - } - return sz; - } - //----------------------------------------------------------------------------- - VertexDeclaration* VertexDeclaration::clone(HardwareBufferManagerBase* mgr) const - { - HardwareBufferManagerBase* pManager = mgr ? mgr : HardwareBufferManager::getSingletonPtr(); - VertexDeclaration* ret = pManager->createVertexDeclaration(); - - for (auto& e : mElementList) - { - ret->addElement(e.getSource(), e.getOffset(), e.getType(), e.getSemantic(), e.getIndex()); - } - return ret; - } - //----------------------------------------------------------------------------- - // Sort routine for VertexElement - static bool vertexElementLess(const VertexElement& e1, const VertexElement& e2) - { - // Sort by source first - if (e1.getSource() < e2.getSource()) - { - return true; - } - else if (e1.getSource() == e2.getSource()) - { - // Use ordering of semantics to sort - if (e1.getSemantic() < e2.getSemantic()) - { - return true; - } - else if (e1.getSemantic() == e2.getSemantic()) - { - // Use index to sort - if (e1.getIndex() < e2.getIndex()) - { - return true; - } - } - } - return false; - } - void VertexDeclaration::sort(void) - { - mElementList.sort(vertexElementLess); - } - //----------------------------------------------------------------------------- - void VertexDeclaration::closeGapsInSource(void) - { - if (mElementList.empty()) - return; - - // Sort first - sort(); - - unsigned short targetIdx = 0; - unsigned short lastIdx = getElement(0)->getSource(); - unsigned short c = 0; - for (auto& elem : mElementList) - { - if (lastIdx != elem.getSource()) - { - targetIdx++; - lastIdx = elem.getSource(); - } - if (targetIdx != elem.getSource()) - { - modifyElement(c, targetIdx, elem.getOffset(), elem.getType(), - elem.getSemantic(), elem.getIndex()); - } - - ++c; - } - } - //----------------------------------------------------------------------- - VertexDeclaration* VertexDeclaration::getAutoOrganisedDeclaration( - bool skeletalAnimation, bool vertexAnimation, bool vertexAnimationNormals) const - { - VertexDeclaration* newDecl = this->clone(); - // Set all sources to the same buffer (for now) - const VertexDeclaration::VertexElementList& elems = newDecl->getElements(); - unsigned short c = 0; - for (auto& elem : elems) - { - // Set source & offset to 0 for now, before sort - newDecl->modifyElement(c, 0, 0, elem.getType(), elem.getSemantic(), elem.getIndex()); - ++c; - } - newDecl->sort(); - // Now sort out proper buffer assignments and offsets - size_t offset = 0; - c = 0; - unsigned short buffer = 0; - VertexElementSemantic prevSemantic = VES_POSITION; - for (auto& elem : elems) - { - bool splitWithPrev = false; - bool splitWithNext = false; - switch (elem.getSemantic()) - { - case VES_POSITION: - // Split positions if vertex animated with only positions - // group with normals otherwise - splitWithPrev = false; - splitWithNext = vertexAnimation && !vertexAnimationNormals; - break; - case VES_NORMAL: - // Normals can't share with blend weights/indices - splitWithPrev = (prevSemantic == VES_BLEND_WEIGHTS || prevSemantic == VES_BLEND_INDICES); - // All animated meshes have to split after normal - splitWithNext = (skeletalAnimation || (vertexAnimation && vertexAnimationNormals)); - break; - case VES_BLEND_WEIGHTS: - // Blend weights/indices can be sharing with their own buffer only - splitWithPrev = true; - break; - case VES_BLEND_INDICES: - // Blend weights/indices can be sharing with their own buffer only - splitWithNext = true; - break; - default: - case VES_DIFFUSE: - case VES_SPECULAR: - case VES_TEXTURE_COORDINATES: - case VES_BINORMAL: - case VES_TANGENT: - // Make sure position is separate if animated & there were no normals - splitWithPrev = prevSemantic == VES_POSITION && - (skeletalAnimation || vertexAnimation); - break; - } - - if (splitWithPrev && offset) - { - ++buffer; - offset = 0; - } - - prevSemantic = elem.getSemantic(); - newDecl->modifyElement(c, buffer, offset, - elem.getType(), elem.getSemantic(), elem.getIndex()); - - if (splitWithNext) - { - ++buffer; - offset = 0; - } - else - { - offset += elem.getSize(); - } - ++c; - } - - return newDecl; - - - } - //----------------------------------------------------------------------------- - unsigned short VertexDeclaration::getMaxSource(void) const - { - unsigned short ret = 0; - for (auto& e : mElementList) - { - if (e.getSource() > ret) - { - ret = e.getSource(); - } - } - return ret; - } - //----------------------------------------------------------------------------- - unsigned short VertexDeclaration::getNextFreeTextureCoordinate() const - { - unsigned short texCoord = 0; - for (const auto & el : mElementList) - { - if (el.getSemantic() == VES_TEXTURE_COORDINATES) - { - ++texCoord; - } - } - return texCoord; - } - //----------------------------------------------------------------------------- - VertexBufferBinding::VertexBufferBinding() : mHighIndex(0) - { - } - //----------------------------------------------------------------------------- - VertexBufferBinding::~VertexBufferBinding() - { - unsetAllBindings(); - } - //----------------------------------------------------------------------------- - void VertexBufferBinding::setBinding(unsigned short index, const HardwareVertexBufferSharedPtr& buffer) - { - // NB will replace any existing buffer ptr at this index, and will thus cause - // reference count to decrement on that buffer (possibly destroying it) - mBindingMap[index] = buffer; - mHighIndex = std::max(mHighIndex, (unsigned short)(index+1)); - } - //----------------------------------------------------------------------------- - void VertexBufferBinding::unsetBinding(unsigned short index) - { - VertexBufferBindingMap::iterator i = mBindingMap.find(index); - if (i == mBindingMap.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Cannot find buffer binding for index " + StringConverter::toString(index), - "VertexBufferBinding::unsetBinding"); - } - mBindingMap.erase(i); - } - //----------------------------------------------------------------------------- - void VertexBufferBinding::unsetAllBindings(void) - { - mBindingMap.clear(); - mHighIndex = 0; - } - //----------------------------------------------------------------------------- - const VertexBufferBinding::VertexBufferBindingMap& - VertexBufferBinding::getBindings(void) const - { - return mBindingMap; - } - //----------------------------------------------------------------------------- - const HardwareVertexBufferSharedPtr& VertexBufferBinding::getBuffer(unsigned short index) const - { - VertexBufferBindingMap::const_iterator i = mBindingMap.find(index); - if (i == mBindingMap.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "No buffer is bound to that index.", - "VertexBufferBinding::getBuffer"); - } - return i->second; - } - //----------------------------------------------------------------------------- - bool VertexBufferBinding::isBufferBound(unsigned short index) const - { - return mBindingMap.find(index) != mBindingMap.end(); - } - //----------------------------------------------------------------------------- - unsigned short VertexBufferBinding::getLastBoundIndex(void) const - { - return mBindingMap.empty() ? 0 : mBindingMap.rbegin()->first + 1; - } - //----------------------------------------------------------------------------- - bool VertexBufferBinding::hasGaps(void) const - { - if (mBindingMap.empty()) - return false; - if (mBindingMap.rbegin()->first + 1 == (int) mBindingMap.size()) - return false; - return true; - } - //----------------------------------------------------------------------------- - void VertexBufferBinding::closeGaps(BindingIndexMap& bindingIndexMap) - { - bindingIndexMap.clear(); - - VertexBufferBindingMap newBindingMap; - - VertexBufferBindingMap::const_iterator it; - ushort targetIndex = 0; - for (it = mBindingMap.begin(); it != mBindingMap.end(); ++it, ++targetIndex) - { - bindingIndexMap[it->first] = targetIndex; - newBindingMap[targetIndex] = it->second; - } - - mBindingMap.swap(newBindingMap); - mHighIndex = targetIndex; - } -} diff --git a/OgreMain/src/OgreHighLevelGpuProgram.cpp b/OgreMain/src/OgreHighLevelGpuProgram.cpp deleted file mode 100644 index 2672127b71f..00000000000 --- a/OgreMain/src/OgreHighLevelGpuProgram.cpp +++ /dev/null @@ -1,387 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreHighLevelGpuProgram.h" -#include "OgreGpuProgramManager.h" - -namespace Ogre -{ - /// Command object for setting macro defines - class CmdPreprocessorDefines : public ParamCommand - { - public: - //----------------------------------------------------------------------- - String doGet(const void* target) const override - { - return static_cast(target)->getPreprocessorDefines(); - } - void doSet(void* target, const String& val) override - { - static_cast(target)->setPreprocessorDefines(val); - } - }; - static CmdPreprocessorDefines msCmdPreprocessorDefines; - - /// Command object for setting entry point - class CmdEntryPoint : public ParamCommand - { - public: - String doGet(const void* target) const override - { - return static_cast(target)->getEntryPoint(); - } - void doSet(void* target, const String& val) override { static_cast(target)->setEntryPoint(val); } - }; - static CmdEntryPoint msCmdEntryPoint; - - void HighLevelGpuProgram::setupBaseParamDictionary() - { - GpuProgram::setupBaseParamDictionary(); - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter("preprocessor_defines", &msCmdPreprocessorDefines); - dict->addParameter("entry_point", &msCmdEntryPoint); - } - - //--------------------------------------------------------------------------- - HighLevelGpuProgram::HighLevelGpuProgram(ResourceManager* creator, - const String& name, ResourceHandle handle, const String& group, - bool isManual, ManualResourceLoader* loader) - : GpuProgram(creator, name, handle, group, isManual, loader), - mHighLevelLoaded(false), mConstantDefsBuilt(false), mEntryPoint("main") - { - } - //--------------------------------------------------------------------------- - void HighLevelGpuProgram::loadImpl() - { - if (isSupported()) - { - // load self - loadHighLevel(); - - // create low-level implementation - createLowLevelImpl(); - // load constructed assembler program (if it exists) - if (mAssemblerProgram) - { - mAssemblerProgram->load(); - } - - } - } - //--------------------------------------------------------------------------- - void HighLevelGpuProgram::unloadImpl() - { - if (mAssemblerProgram) - { - mAssemblerProgram->getCreator()->remove(mAssemblerProgram); - mAssemblerProgram.reset(); - } - - unloadHighLevel(); - resetCompileError(); - } - //--------------------------------------------------------------------------- - HighLevelGpuProgram::~HighLevelGpuProgram() - { - // superclasses will trigger unload - } - //--------------------------------------------------------------------------- - GpuProgramParametersSharedPtr HighLevelGpuProgram::createParameters(void) - { - // Lock mutex before allowing this since this is a top-level method - // called outside of the load() - OGRE_LOCK_AUTO_MUTEX; - - // Make sure param defs are loaded - GpuProgramParametersSharedPtr params = GpuProgramManager::getSingleton().createParameters(); - // Only populate named parameters if we can support this program - if (this->isSupported()) - { - safePrepare(); // loads source - loadHighLevel(); - // Errors during load may have prevented compile - if (this->isSupported()) - { - populateParameterNames(params); - } - } - // Copy in default parameters if present - if (mDefaultParams) - params->copyConstantsFrom(*(mDefaultParams.get())); - return params; - } - size_t HighLevelGpuProgram::calculateSize(void) const - { - size_t memSize = GpuProgram::calculateSize(); - if(mAssemblerProgram) - memSize += mAssemblerProgram->calculateSize(); - - return memSize; - } - - std::vector> HighLevelGpuProgram::parseDefines(String& defines) - { - std::vector> ret; - if (defines.empty()) - return ret; - - String::size_type pos = 0; - while (pos != String::npos) - { - // Find delims - String::size_type endPos = defines.find_first_of(";,=", pos); - if (endPos != String::npos) - { - String::size_type macro_name_start = pos; - pos = endPos; - - // Check definition part - if (defines[pos] == '=') - { - // Setup null character for macro name - defines[pos] = '\0'; - // set up a definition, skip delim - ++pos; - String::size_type macro_val_start = pos; - - endPos = defines.find_first_of(";,", pos); - if (endPos == String::npos) - { - pos = endPos; - } - else - { - defines[endPos] = '\0'; - pos = endPos+1; - } - - ret.push_back({&defines[macro_name_start], &defines[macro_val_start]}); - } - else - { - // Setup null character for macro name - defines[pos] = '\0'; - // No definition part, define as "1" - ++pos; - - if(defines[macro_name_start] != '\0') // e.g ",DEFINE" or "DEFINE," - ret.push_back({&defines[macro_name_start], "1"}); - } - } - else - { - if(pos < defines.size()) - ret.push_back({&defines[pos], "1"}); - - pos = endPos; - } - } - - return ret; - } - - String HighLevelGpuProgram::appendBuiltinDefines(String defines) - { - if(!defines.empty()) defines += ","; - - auto renderSystem = Root::getSingleton().getRenderSystem(); - - // OGRE_HLSL, OGRE_GLSL etc. - String tmp = getLanguage(); - StringUtil::toUpperCase(tmp); - auto ver = renderSystem ? renderSystem->getNativeShadingLanguageVersion() : 0; - defines += StringUtil::format("OGRE_%s=%d", tmp.c_str(), ver); - - // OGRE_VERTEX_SHADER, OGRE_FRAGMENT_SHADER - tmp = GpuProgram::getProgramTypeName(getType()); - StringUtil::toUpperCase(tmp); - defines += ",OGRE_"+tmp+"_SHADER"; - - if(renderSystem && renderSystem->isReverseDepthBufferEnabled()) - defines += ",OGRE_REVERSED_Z"; - - return defines; - } - - //--------------------------------------------------------------------------- - void HighLevelGpuProgram::loadHighLevel(void) - { - if (!mHighLevelLoaded) - { - GpuProgram::loadImpl(); - mHighLevelLoaded = !mCompileError; - } - } - //--------------------------------------------------------------------------- - void HighLevelGpuProgram::unloadHighLevel(void) - { - if (mHighLevelLoaded) - { - unloadHighLevelImpl(); - // Clear saved constant defs - mConstantDefsBuilt = false; - createParameterMappingStructures(true); - - mHighLevelLoaded = false; - } - } - //--------------------------------------------------------------------- - const GpuNamedConstants& HighLevelGpuProgram::getConstantDefinitions() - { - if (!mConstantDefsBuilt) - { - buildConstantDefinitions(); - mConstantDefsBuilt = true; - } - return *mConstantDefs.get(); - - } - //--------------------------------------------------------------------- - void HighLevelGpuProgram::populateParameterNames(const GpuProgramParametersSharedPtr& params) - { - getConstantDefinitions(); - params->_setNamedConstants(mConstantDefs); - // also set logical / physical maps for programs which use this - params->_setLogicalIndexes(mLogicalToPhysical); - } - - //----------------------------------------------------------------------- - String HighLevelGpuProgram::_resolveIncludes(const String& inSource, Resource* resourceBeingLoaded, const String& fileName, bool supportsFilename) - { - String outSource; - // output will be at least this big - outSource.reserve(inSource.length()); - - size_t startMarker = 0; - size_t i = inSource.find("#include"); - - String lineFilename = supportsFilename ? StringUtil::format(" \"%s\"", fileName.c_str()) : " 0"; - - while (i != String::npos) - { - size_t includePos = i; - size_t afterIncludePos = includePos + 8; - size_t newLineBefore = inSource.rfind('\n', includePos); - - // check we're not in a comment - size_t lineCommentIt = inSource.rfind("//", includePos); - if (lineCommentIt != String::npos) - { - if (newLineBefore == String::npos || lineCommentIt > newLineBefore) - { - // commented - i = inSource.find("#include", afterIncludePos); - continue; - } - - } - size_t blockCommentIt = inSource.rfind("/*", includePos); - if (blockCommentIt != String::npos) - { - size_t closeCommentIt = inSource.rfind("*/", includePos); - if (closeCommentIt == String::npos || closeCommentIt < blockCommentIt) - { - // commented - i = inSource.find("#include", afterIncludePos); - continue; - } - - } - - // find following newline (or EOF) - size_t newLineAfter = std::min(inSource.find('\n', afterIncludePos), inSource.size()); - // find include file string container - char endDelimiter = '"'; - size_t startIt = inSource.find('"', afterIncludePos); - if (startIt == String::npos || startIt > newLineAfter) - { - // try <> - startIt = inSource.find('<', afterIncludePos); - if (startIt == String::npos || startIt > newLineAfter) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Badly formed #include directive (expected \" or <) in file " + fileName + ": " + - inSource.substr(includePos, newLineAfter - includePos)); - } - else - { - endDelimiter = '>'; - } - } - size_t endIt = inSource.find(endDelimiter, startIt+1); - if (endIt == String::npos || endIt <= startIt) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Badly formed #include directive (expected " + String(1, endDelimiter) + - ") in file " + fileName + ": " + - inSource.substr(includePos, newLineAfter - includePos)); - } - - // extract filename - String filename(inSource.substr(startIt+1, endIt-startIt-1)); - - // open included file - DataStreamPtr resource = ResourceGroupManager::getSingleton(). - openResource(filename, resourceBeingLoaded->getGroup(), resourceBeingLoaded); - - // replace entire include directive line - // copy up to just before include - if (newLineBefore != String::npos && newLineBefore >= startMarker) - outSource.append(inSource.substr(startMarker, newLineBefore-startMarker+1)); - - // Count the line number of #include statement, +1 for new line after the statement - size_t lineCount = std::count(inSource.begin(), inSource.begin() + newLineAfter, '\n') + 1; - - // use include filename if supported (cg) - else use include line as id (glsl) - String incLineFilename = supportsFilename ? StringUtil::format(" \"%s\"", filename.c_str()) : StringUtil::format(" %zu", lineCount); - - // Add #line to the start of the included file to correct the line count) - outSource.append("#line 1 " + incLineFilename + "\n"); - - // recurse into include - outSource.append(_resolveIncludes(resource->getAsString(), resourceBeingLoaded, filename, supportsFilename)); - - // Add #line to the end of the included file to correct the line count. - // +1 as #line specifies the number of the following line - outSource.append("\n#line " + std::to_string(lineCount + 1) + lineFilename); - - startMarker = newLineAfter; - - if (startMarker != String::npos) - i = inSource.find("#include", startMarker); - else - i = String::npos; - - } - // copy any remaining characters - outSource.append(inSource.substr(startMarker)); - - return outSource; - } -} diff --git a/OgreMain/src/OgreImage.cpp b/OgreMain/src/OgreImage.cpp deleted file mode 100644 index 874edca9daf..00000000000 --- a/OgreMain/src/OgreImage.cpp +++ /dev/null @@ -1,632 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreImage.h" -#include "OgreImageCodec.h" -#include "OgreImageResampler.h" - -namespace Ogre { - //----------------------------------------------------------------------------- - Image::Image(PixelFormat format, uint32 width, uint32 height, uint32 depth, uchar* buffer, bool autoDelete) - : mWidth(0), - mHeight(0), - mDepth(0), - mNumMipmaps(0), - mBufSize(0), - mFlags(0), - mFormat(format), - mBuffer( NULL ), - mAutoDelete( true ) - { - if (format == PF_UNKNOWN) - return; - - size_t size = calculateSize(0, 1, width, height, depth, mFormat); - - if (size == 0) - return; - - if (!buffer) - buffer = OGRE_ALLOC_T(uchar, size, MEMCATEGORY_GENERAL); - loadDynamicImage(buffer, width, height, depth, format, autoDelete); - } - - void Image::create(PixelFormat format, uint32 width, uint32 height, uint32 depth, uint32 numFaces, - uint32 numMipMaps) - { - size_t size = calculateSize(numMipMaps, numFaces, width, height, depth, format); - if (!mAutoDelete || !mBuffer || mBufSize != size) - { - freeMemory(); - mBuffer = new uchar[size]; // allocate - } - - // make sure freeMemory() does nothing, we set this true immediately after - mAutoDelete = false; - loadDynamicImage(mBuffer, width, height, depth, format, true, numFaces, numMipMaps); - } - - //----------------------------------------------------------------------------- - Image::Image( const Image &img ) - : mBuffer( NULL ), - mAutoDelete( true ) - { - // call assignment operator - *this = img; - } - - //----------------------------------------------------------------------------- - Image::~Image() - { - freeMemory(); - } - //--------------------------------------------------------------------- - void Image::freeMemory() - { - //Only delete if this was not a dynamic image (meaning app holds & destroys buffer) - if( mBuffer && mAutoDelete ) - { - OGRE_FREE(mBuffer, MEMCATEGORY_GENERAL); - mBuffer = NULL; - } - - } - - //----------------------------------------------------------------------------- - Image& Image::operator=(const Image& img) - { - if (this == &img) - return *this; - - // Only create & copy when other data was owning - if (img.mBuffer && img.mAutoDelete) - { - create(img.mFormat, img.mWidth, img.mHeight, img.mDepth, img.getNumFaces(), img.mNumMipmaps); - memcpy(mBuffer, img.mBuffer, mBufSize); - } - else - { - loadDynamicImage(img.mBuffer, img.mWidth, img.mHeight, img.mDepth, img.mFormat, false, - img.getNumFaces(), img.mNumMipmaps); - } - - return *this; - } - - void Image::setTo(const ColourValue& col) - { - OgreAssert(mBuffer, "No image data loaded"); - if(col == ColourValue::ZERO) - { - memset(mBuffer, 0, getSize()); - return; - } - - uchar rawCol[4 * sizeof(float)]; // max packed size currently is 4*float - PixelUtil::packColour(col, mFormat, rawCol); - for(size_t p = 0; p < mBufSize; p += mPixelSize) - { - memcpy(mBuffer + p, rawCol, mPixelSize); - } - } - - //----------------------------------------------------------------------------- - Image & Image::flipAroundY() - { - OgreAssert(mBuffer, "No image data loaded"); - mNumMipmaps = 0; // Image operations lose precomputed mipmaps - - uint32 y; - switch (mPixelSize) - { - case 1: - for (y = 0; y < mHeight; y++) - { - std::reverse(mBuffer + mWidth * y, mBuffer + mWidth * (y + 1)); - } - break; - - case 2: - for (y = 0; y < mHeight; y++) - { - std::reverse((ushort*)mBuffer + mWidth * y, (ushort*)mBuffer + mWidth * (y + 1)); - } - break; - - case 3: - typedef uchar uchar3[3]; - for (y = 0; y < mHeight; y++) - { - std::reverse((uchar3*)mBuffer + mWidth * y, (uchar3*)mBuffer + mWidth * (y + 1)); - } - break; - - case 4: - for (y = 0; y < mHeight; y++) - { - std::reverse((uint*)mBuffer + mWidth * y, (uint*)mBuffer + mWidth * (y + 1)); - } - break; - - default: - OGRE_EXCEPT( - Exception::ERR_INTERNAL_ERROR, - "Unknown pixel depth", - "Image::flipAroundY" ); - break; - } - - return *this; - - } - - //----------------------------------------------------------------------------- - Image & Image::flipAroundX() - { - OgreAssert(mBuffer, "No image data loaded"); - - mNumMipmaps = 0; // Image operations lose precomputed mipmaps - PixelUtil::bulkPixelVerticalFlip(getPixelBox()); - - return *this; - } - - //----------------------------------------------------------------------------- - Image& Image::loadDynamicImage(uchar* pData, uint32 uWidth, uint32 uHeight, uint32 depth, - PixelFormat eFormat, bool autoDelete, uint32 numFaces, uint32 numMipMaps) - { - - freeMemory(); - // Set image metadata - mWidth = uWidth; - mHeight = uHeight; - mDepth = depth; - mFormat = eFormat; - mPixelSize = static_cast(PixelUtil::getNumElemBytes( mFormat )); - mNumMipmaps = numMipMaps; - mFlags = 0; - // Set flags - if (PixelUtil::isCompressed(eFormat)) - mFlags |= IF_COMPRESSED; - if (mDepth != 1) - mFlags |= IF_3D_TEXTURE; - if(numFaces == 6) - mFlags |= IF_CUBEMAP; - OgreAssert(numFaces == 6 || numFaces == 1, "Invalid number of faces"); - - mBufSize = calculateSize(numMipMaps, numFaces, uWidth, uHeight, depth, eFormat); - mBuffer = pData; - mAutoDelete = autoDelete; - - return *this; - } - - //----------------------------------------------------------------------------- - Image& Image::loadRawData(const DataStreamPtr& stream, uint32 uWidth, uint32 uHeight, uint32 uDepth, - PixelFormat eFormat, uint32 numFaces, uint32 numMipMaps) - { - - size_t size = calculateSize(numMipMaps, numFaces, uWidth, uHeight, uDepth, eFormat); - OgreAssert(size == stream->size(), "Wrong stream size"); - - uchar *buffer = OGRE_ALLOC_T(uchar, size, MEMCATEGORY_GENERAL); - stream->read(buffer, size); - - return loadDynamicImage(buffer, - uWidth, uHeight, uDepth, - eFormat, true, numFaces, numMipMaps); - - } - //----------------------------------------------------------------------------- - Image & Image::load(const String& strFileName, const String& group) - { - - String strExt; - - size_t pos = strFileName.find_last_of('.'); - if( pos != String::npos && pos < (strFileName.length() - 1)) - { - strExt = strFileName.substr(pos+1); - } - - DataStreamPtr encoded = ResourceGroupManager::getSingleton().openResource(strFileName, group); - return load(encoded, strExt); - - } - //----------------------------------------------------------------------------- - void Image::save(const String& filename) - { - OgreAssert(mBuffer, "No image data loaded"); - - String base, ext; - StringUtil::splitBaseFilename(filename, base, ext); - - // getCodec throws when no codec is found - Codec::getCodec(ext)->encodeToFile(this, filename); - } - //--------------------------------------------------------------------- - DataStreamPtr Image::encode(const String& formatextension) - { - OgreAssert(mBuffer, "No image data loaded"); - // getCodec throws when no codec is found - return Codec::getCodec(formatextension)->encode(this); - } - //----------------------------------------------------------------------------- - Image & Image::load(const DataStreamPtr& stream, const String& type ) - { - freeMemory(); - - Codec * pCodec = 0; - if (!type.empty()) - { - // use named codec - pCodec = Codec::getCodec(type); - } - else - { - // derive from magic number - // read the first 32 bytes or file size, if less - size_t magicLen = std::min(stream->size(), (size_t)32); - char magicBuf[32]; - stream->read(magicBuf, magicLen); - // return to start - stream->seek(0); - pCodec = Codec::getCodec(magicBuf, magicLen); - - if (!pCodec) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Unable to load image: Image format is unknown. Unable to identify codec. " - "Check it or specify format explicitly."); - } - - pCodec->decode(stream, this); - - // compute the pixel size - mPixelSize = static_cast(PixelUtil::getNumElemBytes( mFormat )); - // make sure we delete - mAutoDelete = true; - - return *this; - } - //--------------------------------------------------------------------- - String Image::getFileExtFromMagic(const DataStreamPtr stream) - { - // read the first 32 bytes or file size, if less - size_t magicLen = std::min(stream->size(), (size_t)32); - char magicBuf[32]; - stream->read(magicBuf, magicLen); - // return to start - stream->seek(0); - Codec* pCodec = Codec::getCodec(magicBuf, magicLen); - - if(pCodec) - return pCodec->getType(); - else - return BLANKSTRING; - - } - - //----------------------------------------------------------------------------- - bool Image::getHasAlpha(void) const - { - return PixelUtil::getFlags(mFormat) & PFF_HASALPHA; - } - //----------------------------------------------------------------------------- - void Image::applyGamma( uchar *buffer, Real gamma, size_t size, uchar bpp ) - { - if( gamma == 1.0f ) - return; - - OgreAssert( bpp == 24 || bpp == 32, ""); - - uint stride = bpp >> 3; - - uchar gammaramp[256]; - const Real exponent = 1.0f / gamma; - for(int i = 0; i < 256; i++) { - gammaramp[i] = static_cast(Math::Pow(i/255.0f, exponent)*255+0.5f); - } - - for( size_t i = 0, j = size / stride; i < j; i++, buffer += stride ) - { - buffer[0] = gammaramp[buffer[0]]; - buffer[1] = gammaramp[buffer[1]]; - buffer[2] = gammaramp[buffer[2]]; - } - } - //----------------------------------------------------------------------------- - void Image::resize(ushort width, ushort height, Filter filter) - { - OgreAssert(mAutoDelete, "resizing dynamic images is not supported"); - OgreAssert(mDepth == 1, "only 2D formats supported"); - - // reassign buffer to temp image, make sure auto-delete is true - Image temp(mFormat, mWidth, mHeight, 1, mBuffer, true); - - // do not delete[] mBuffer! temp will destroy it - mBuffer = 0; - - // set new dimensions, allocate new buffer - create(mFormat, width, height); // Loses precomputed mipmaps - - // scale the image from temp into our resized buffer - Image::scale(temp.getPixelBox(), getPixelBox(), filter); - } - //----------------------------------------------------------------------- - void Image::scale(const PixelBox &src, const PixelBox &scaled, Filter filter) - { - assert(PixelUtil::isAccessible(src.format)); - assert(PixelUtil::isAccessible(scaled.format)); - Image buf; // For auto-delete - // Assume no intermediate buffer needed - PixelBox temp = scaled; - switch (filter) - { - default: - case FILTER_NEAREST: - if(src.format != scaled.format) - { - // Allocate temporary buffer of destination size in source format - buf.create(src.format, scaled.getWidth(), scaled.getHeight(), scaled.getDepth()); - temp = buf.getPixelBox(); - } - // super-optimized: no conversion - switch (PixelUtil::getNumElemBytes(src.format)) - { - case 1: NearestResampler<1>::scale(src, temp); break; - case 2: NearestResampler<2>::scale(src, temp); break; - case 3: NearestResampler<3>::scale(src, temp); break; - case 4: NearestResampler<4>::scale(src, temp); break; - case 6: NearestResampler<6>::scale(src, temp); break; - case 8: NearestResampler<8>::scale(src, temp); break; - case 12: NearestResampler<12>::scale(src, temp); break; - case 16: NearestResampler<16>::scale(src, temp); break; - default: - // never reached - assert(false); - } - if(temp.data != scaled.data) - { - // Blit temp buffer - PixelUtil::bulkPixelConversion(temp, scaled); - } - break; - - case FILTER_BILINEAR: - switch (src.format) - { - case PF_L8: case PF_R8: case PF_A8: case PF_BYTE_LA: - case PF_R8G8B8: case PF_B8G8R8: - case PF_R8G8B8A8: case PF_B8G8R8A8: - case PF_A8B8G8R8: case PF_A8R8G8B8: - case PF_X8B8G8R8: case PF_X8R8G8B8: - if(src.format != scaled.format) - { - // Allocate temp buffer of destination size in source format - buf.create(src.format, scaled.getWidth(), scaled.getHeight(), scaled.getDepth()); - temp = buf.getPixelBox(); - } - // super-optimized: byte-oriented math, no conversion - switch (PixelUtil::getNumElemBytes(src.format)) - { - case 1: LinearResampler_Byte<1>::scale(src, temp); break; - case 2: LinearResampler_Byte<2>::scale(src, temp); break; - case 3: LinearResampler_Byte<3>::scale(src, temp); break; - case 4: LinearResampler_Byte<4>::scale(src, temp); break; - default: - // never reached - assert(false); - } - if(temp.data != scaled.data) - { - // Blit temp buffer - PixelUtil::bulkPixelConversion(temp, scaled); - } - break; - case PF_FLOAT32_RGB: - case PF_FLOAT32_RGBA: - if (scaled.format == PF_FLOAT32_RGB || scaled.format == PF_FLOAT32_RGBA) - { - // float32 to float32, avoid unpack/repack overhead - LinearResampler_Float32::scale(src, scaled); - break; - } - // else, fall through - default: - // non-optimized: floating-point math, performs conversion but always works - LinearResampler::scale(src, scaled); - } - break; - } - } - - //----------------------------------------------------------------------------- - - ColourValue Image::getColourAt(uint32 x, uint32 y, uint32 z) const - { - ColourValue rval; - PixelUtil::unpackColour(&rval, mFormat, getData(x, y, z)); - return rval; - } - - //----------------------------------------------------------------------------- - - void Image::setColourAt(ColourValue const &cv, uint32 x, uint32 y, uint32 z) - { - PixelUtil::packColour(cv, mFormat, getData(x, y, z)); - } - - //----------------------------------------------------------------------------- - - PixelBox Image::getPixelBox(uint32 face, uint32 mipmap) const - { - // Image data is arranged as: - // face 0, top level (mip 0) - // face 0, mip 1 - // face 0, mip 2 - // face 1, top level (mip 0) - // face 1, mip 1 - // face 1, mip 2 - // etc - OgreAssert(mipmap <= getNumMipmaps(), "out of range"); - OgreAssert(face < getNumFaces(), "out of range"); - // Calculate mipmap offset and size - uint8 *offset = mBuffer; - // Base offset is number of full faces - uint32 width = getWidth(), height=getHeight(), depth=getDepth(); - uint32 numMips = getNumMipmaps(); - - // Figure out the offsets - size_t fullFaceSize = 0; - size_t finalFaceSize = 0; - uint32 finalWidth = 0, finalHeight = 0, finalDepth = 0; - for(uint32 mip=0; mip <= numMips; ++mip) - { - if (mip == mipmap) - { - finalFaceSize = fullFaceSize; - finalWidth = width; - finalHeight = height; - finalDepth = depth; - } - fullFaceSize += PixelUtil::getMemorySize(width, height, depth, getFormat()); - - /// Half size in each dimension - if(width!=1) width /= 2; - if(height!=1) height /= 2; - if(depth!=1) depth /= 2; - } - // Advance pointer by number of full faces, plus mip offset into - offset += face * fullFaceSize; - offset += finalFaceSize; - // Return subface as pixelbox - PixelBox src(finalWidth, finalHeight, finalDepth, getFormat(), offset); - return src; - } - //----------------------------------------------------------------------------- - size_t Image::calculateSize(uint32 mipmaps, uint32 faces, uint32 width, uint32 height, uint32 depth, - PixelFormat format) - { - size_t size = 0; - for(uint32 mip=0; mip<=mipmaps; ++mip) - { - size += PixelUtil::getMemorySize(width, height, depth, format)*faces; - if(width!=1) width /= 2; - if(height!=1) height /= 2; - if(depth!=1) depth /= 2; - } - return size; - } - //--------------------------------------------------------------------- - Image & Image::loadTwoImagesAsRGBA(const String& rgbFilename, const String& alphaFilename, - const String& groupName, PixelFormat fmt) - { - Image rgb, alpha; - - rgb.load(rgbFilename, groupName); - alpha.load(alphaFilename, groupName); - - return combineTwoImagesAsRGBA(rgb, alpha, fmt); - - } - //--------------------------------------------------------------------- - Image& Image::loadTwoImagesAsRGBA(const DataStreamPtr& rgbStream, - const DataStreamPtr& alphaStream, PixelFormat fmt, - const String& rgbType, const String& alphaType) - { - Image rgb, alpha; - - rgb.load(rgbStream, rgbType); - alpha.load(alphaStream, alphaType); - - return combineTwoImagesAsRGBA(rgb, alpha, fmt); - - } - //--------------------------------------------------------------------- - Image & Image::combineTwoImagesAsRGBA(const Image& rgb, const Image& alpha, PixelFormat fmt) - { - // the images should be the same size, have the same number of mipmaps - OgreAssert(rgb.getWidth() == alpha.getWidth() && rgb.getHeight() == alpha.getHeight() && - rgb.getDepth() == alpha.getDepth(), - "Images must be the same dimensions"); - OgreAssert(rgb.getNumMipmaps() == alpha.getNumMipmaps() && rgb.getNumFaces() == alpha.getNumFaces(), - "Images must have the same number of surfaces"); - - // Format check - OgreAssert(PixelUtil::getComponentCount(fmt) == 4, "Target format must have 4 components"); - - OgreAssert(!(PixelUtil::isCompressed(fmt) || PixelUtil::isCompressed(rgb.getFormat()) || - PixelUtil::isCompressed(alpha.getFormat())), - "Compressed formats are not supported in this method"); - - uint32 numFaces = rgb.getNumFaces(); - create(fmt, rgb.getWidth(), rgb.getHeight(), rgb.getDepth(), numFaces, rgb.getNumMipmaps()); - - for (uint32 face = 0; face < numFaces; ++face) - { - for (uint8 mip = 0; mip <= mNumMipmaps; ++mip) - { - // convert the RGB first - PixelBox srcRGB = rgb.getPixelBox(face, mip); - PixelBox dst = getPixelBox(face, mip); - PixelUtil::bulkPixelConversion(srcRGB, dst); - - // now selectively add the alpha - PixelBox srcAlpha = alpha.getPixelBox(face, mip); - uchar* psrcAlpha = srcAlpha.data; - uchar* pdst = dst.data; - for (uint32 d = 0; d < mDepth; ++d) - { - for (uint32 y = 0; y < mHeight; ++y) - { - for (uint32 x = 0; x < mWidth; ++x) - { - ColourValue colRGBA, colA; - // read RGB back from dest to save having another pointer - PixelUtil::unpackColour(&colRGBA, mFormat, pdst); - PixelUtil::unpackColour(&colA, alpha.getFormat(), psrcAlpha); - - // combine RGB from alpha source texture - colRGBA.a = (colA.r + colA.g + colA.b) / 3.0f; - - PixelUtil::packColour(colRGBA, mFormat, pdst); - - psrcAlpha += PixelUtil::getNumElemBytes(alpha.getFormat()); - pdst += PixelUtil::getNumElemBytes(mFormat); - } - } - } - } - } - - return *this; - } - //--------------------------------------------------------------------- - - -} diff --git a/OgreMain/src/OgreImageResampler.h b/OgreMain/src/OgreImageResampler.h deleted file mode 100644 index 086c9cd70a4..00000000000 --- a/OgreMain/src/OgreImageResampler.h +++ /dev/null @@ -1,345 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef OGREIMAGERESAMPLER_H -#define OGREIMAGERESAMPLER_H - -#include - -// this file is inlined into OgreImage.cpp! -// do not include anywhere else. -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Image - * @{ - */ - -// variable name hints: -// sx_48 = 16/48-bit fixed-point x-position in source -// stepx = difference between adjacent sx_48 values -// sx1 = lower-bound integer x-position in source -// sx2 = upper-bound integer x-position in source -// sxf = fractional weight between sx1 and sx2 -// x,y,z = location of output pixel in destination - -// nearest-neighbor resampler, does not convert formats. -// templated on bytes-per-pixel to allow compiler optimizations, such -// as simplifying memcpy() and replacing multiplies with bitshifts -template struct NearestResampler { - static void scale(const PixelBox& src, const PixelBox& dst) { - // assert(src.format == dst.format); - - // srcdata stays at beginning, pdst is a moving pointer - uchar* srcdata = (uchar*)src.getTopLeftFrontPixelPtr(); - uchar* pdst = (uchar*)dst.getTopLeftFrontPixelPtr(); - - // sx_48,sy_48,sz_48 represent current position in source - // using 16/48-bit fixed precision, incremented by steps - uint64 stepx = ((uint64)src.getWidth() << 48) / dst.getWidth(); - uint64 stepy = ((uint64)src.getHeight() << 48) / dst.getHeight(); - uint64 stepz = ((uint64)src.getDepth() << 48) / dst.getDepth(); - - // note: ((stepz>>1) - 1) is an extra half-step increment to adjust - // for the center of the destination pixel, not the top-left corner - uint64 sz_48 = (stepz >> 1) - 1; - for (size_t z = dst.front; z < dst.back; z++, sz_48 += stepz) { - size_t srczoff = (size_t)(sz_48 >> 48) * src.slicePitch; - - uint64 sy_48 = (stepy >> 1) - 1; - for (size_t y = dst.top; y < dst.bottom; y++, sy_48 += stepy) { - size_t srcyoff = (size_t)(sy_48 >> 48) * src.rowPitch; - - uint64 sx_48 = (stepx >> 1) - 1; - for (size_t x = dst.left; x < dst.right; x++, sx_48 += stepx) { - uchar* psrc = srcdata + - elemsize*((size_t)(sx_48 >> 48) + srcyoff + srczoff); - memcpy(pdst, psrc, elemsize); - pdst += elemsize; - } - pdst += elemsize*dst.getRowSkip(); - } - pdst += elemsize*dst.getSliceSkip(); - } - } -}; - - -// default floating-point linear resampler, does format conversion -struct LinearResampler { - static void scale(const PixelBox& src, const PixelBox& dst) { - size_t srcelemsize = PixelUtil::getNumElemBytes(src.format); - size_t dstelemsize = PixelUtil::getNumElemBytes(dst.format); - - // srcdata stays at beginning, pdst is a moving pointer - uchar* srcdata = (uchar*)src.getTopLeftFrontPixelPtr(); - uchar* pdst = (uchar*)dst.getTopLeftFrontPixelPtr(); - - // sx_48,sy_48,sz_48 represent current position in source - // using 16/48-bit fixed precision, incremented by steps - uint64 stepx = ((uint64)src.getWidth() << 48) / dst.getWidth(); - uint64 stepy = ((uint64)src.getHeight() << 48) / dst.getHeight(); - uint64 stepz = ((uint64)src.getDepth() << 48) / dst.getDepth(); - - // note: ((stepz>>1) - 1) is an extra half-step increment to adjust - // for the center of the destination pixel, not the top-left corner - uint64 sz_48 = (stepz >> 1) - 1; - for (size_t z = dst.front; z < dst.back; z++, sz_48+=stepz) { - // temp is 16/16 bit fixed precision, used to adjust a source - // coordinate (x, y, or z) backwards by half a pixel so that the - // integer bits represent the first sample (eg, sx1) and the - // fractional bits are the blend weight of the second sample - unsigned int temp = static_cast(sz_48 >> 32); - - temp = (temp > 0x8000)? temp - 0x8000 : 0; - uint32 sz1 = temp >> 16; // src z, sample #1 - uint32 sz2 = std::min(sz1+1,src.getDepth()-1);// src z, sample #2 - float szf = (temp & 0xFFFF) / 65536.f; // weight of sample #2 - - uint64 sy_48 = (stepy >> 1) - 1; - for (size_t y = dst.top; y < dst.bottom; y++, sy_48+=stepy) { - temp = static_cast(sy_48 >> 32); - temp = (temp > 0x8000)? temp - 0x8000 : 0; - uint32 sy1 = temp >> 16; // src y #1 - uint32 sy2 = std::min(sy1+1,src.getHeight()-1);// src y #2 - float syf = (temp & 0xFFFF) / 65536.f; // weight of #2 - - uint64 sx_48 = (stepx >> 1) - 1; - for (size_t x = dst.left; x < dst.right; x++, sx_48+=stepx) { - temp = static_cast(sx_48 >> 32); - temp = (temp > 0x8000)? temp - 0x8000 : 0; - uint32 sx1 = temp >> 16; // src x #1 - uint32 sx2 = std::min(sx1+1,src.getWidth()-1);// src x #2 - float sxf = (temp & 0xFFFF) / 65536.f; // weight of #2 - - ColourValue x1y1z1, x2y1z1, x1y2z1, x2y2z1; - ColourValue x1y1z2, x2y1z2, x1y2z2, x2y2z2; - -#define UNPACK(dst,x,y,z) PixelUtil::unpackColour(&dst, src.format, \ - srcdata + srcelemsize*((x)+(y)*src.rowPitch+(z)*src.slicePitch)) - - UNPACK(x1y1z1,sx1,sy1,sz1); UNPACK(x2y1z1,sx2,sy1,sz1); - UNPACK(x1y2z1,sx1,sy2,sz1); UNPACK(x2y2z1,sx2,sy2,sz1); - UNPACK(x1y1z2,sx1,sy1,sz2); UNPACK(x2y1z2,sx2,sy1,sz2); - UNPACK(x1y2z2,sx1,sy2,sz2); UNPACK(x2y2z2,sx2,sy2,sz2); -#undef UNPACK - - ColourValue accum = - x1y1z1 * ((1.0f - sxf)*(1.0f - syf)*(1.0f - szf)) + - x2y1z1 * ( sxf *(1.0f - syf)*(1.0f - szf)) + - x1y2z1 * ((1.0f - sxf)* syf *(1.0f - szf)) + - x2y2z1 * ( sxf * syf *(1.0f - szf)) + - x1y1z2 * ((1.0f - sxf)*(1.0f - syf)* szf ) + - x2y1z2 * ( sxf *(1.0f - syf)* szf ) + - x1y2z2 * ((1.0f - sxf)* syf * szf ) + - x2y2z2 * ( sxf * syf * szf ); - - PixelUtil::packColour(accum, dst.format, pdst); - - pdst += dstelemsize; - } - pdst += dstelemsize*dst.getRowSkip(); - } - pdst += dstelemsize*dst.getSliceSkip(); - } - } -}; - - -// float32 linear resampler, converts FLOAT32_RGB/FLOAT32_RGBA only. -// avoids overhead of pixel unpack/repack function calls -struct LinearResampler_Float32 { - static void scale(const PixelBox& src, const PixelBox& dst) { - size_t srcchannels = PixelUtil::getNumElemBytes(src.format) / sizeof(float); - size_t dstchannels = PixelUtil::getNumElemBytes(dst.format) / sizeof(float); - // assert(srcchannels == 3 || srcchannels == 4); - // assert(dstchannels == 3 || dstchannels == 4); - - // srcdata stays at beginning, pdst is a moving pointer - float* srcdata = (float*)src.getTopLeftFrontPixelPtr(); - float* pdst = (float*)dst.getTopLeftFrontPixelPtr(); - - // sx_48,sy_48,sz_48 represent current position in source - // using 16/48-bit fixed precision, incremented by steps - uint64 stepx = ((uint64)src.getWidth() << 48) / dst.getWidth(); - uint64 stepy = ((uint64)src.getHeight() << 48) / dst.getHeight(); - uint64 stepz = ((uint64)src.getDepth() << 48) / dst.getDepth(); - - // note: ((stepz>>1) - 1) is an extra half-step increment to adjust - // for the center of the destination pixel, not the top-left corner - uint64 sz_48 = (stepz >> 1) - 1; - for (size_t z = dst.front; z < dst.back; z++, sz_48+=stepz) { - // temp is 16/16 bit fixed precision, used to adjust a source - // coordinate (x, y, or z) backwards by half a pixel so that the - // integer bits represent the first sample (eg, sx1) and the - // fractional bits are the blend weight of the second sample - unsigned int temp = static_cast(sz_48 >> 32); - - temp = (temp > 0x8000)? temp - 0x8000 : 0; - uint32 sz1 = temp >> 16; // src z, sample #1 - uint32 sz2 = std::min(sz1+1,src.getDepth()-1);// src z, sample #2 - float szf = (temp & 0xFFFF) / 65536.f; // weight of sample #2 - - uint64 sy_48 = (stepy >> 1) - 1; - for (size_t y = dst.top; y < dst.bottom; y++, sy_48+=stepy) { - temp = static_cast(sy_48 >> 32); - temp = (temp > 0x8000)? temp - 0x8000 : 0; - uint32 sy1 = temp >> 16; // src y #1 - uint32 sy2 = std::min(sy1+1,src.getHeight()-1);// src y #2 - float syf = (temp & 0xFFFF) / 65536.f; // weight of #2 - - uint64 sx_48 = (stepx >> 1) - 1; - for (size_t x = dst.left; x < dst.right; x++, sx_48+=stepx) { - temp = static_cast(sx_48 >> 32); - temp = (temp > 0x8000)? temp - 0x8000 : 0; - uint32 sx1 = temp >> 16; // src x #1 - uint32 sx2 = std::min(sx1+1,src.getWidth()-1);// src x #2 - float sxf = (temp & 0xFFFF) / 65536.f; // weight of #2 - - // process R,G,B,A simultaneously for cache coherence? - float accum[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; - -#define ACCUM3(x,y,z,factor) \ - { float f = factor; \ - size_t off = (x+y*src.rowPitch+z*src.slicePitch)*srcchannels; \ - accum[0]+=srcdata[off+0]*f; accum[1]+=srcdata[off+1]*f; \ - accum[2]+=srcdata[off+2]*f; } - -#define ACCUM4(x,y,z,factor) \ - { float f = factor; \ - size_t off = (x+y*src.rowPitch+z*src.slicePitch)*srcchannels; \ - accum[0]+=srcdata[off+0]*f; accum[1]+=srcdata[off+1]*f; \ - accum[2]+=srcdata[off+2]*f; accum[3]+=srcdata[off+3]*f; } - - if (srcchannels == 3 || dstchannels == 3) { - // RGB, no alpha - ACCUM3(sx1,sy1,sz1,(1.0f-sxf)*(1.0f-syf)*(1.0f-szf)); - ACCUM3(sx2,sy1,sz1, sxf *(1.0f-syf)*(1.0f-szf)); - ACCUM3(sx1,sy2,sz1,(1.0f-sxf)* syf *(1.0f-szf)); - ACCUM3(sx2,sy2,sz1, sxf * syf *(1.0f-szf)); - ACCUM3(sx1,sy1,sz2,(1.0f-sxf)*(1.0f-syf)* szf ); - ACCUM3(sx2,sy1,sz2, sxf *(1.0f-syf)* szf ); - ACCUM3(sx1,sy2,sz2,(1.0f-sxf)* syf * szf ); - ACCUM3(sx2,sy2,sz2, sxf * syf * szf ); - accum[3] = 1.0f; - } else { - // RGBA - ACCUM4(sx1,sy1,sz1,(1.0f-sxf)*(1.0f-syf)*(1.0f-szf)); - ACCUM4(sx2,sy1,sz1, sxf *(1.0f-syf)*(1.0f-szf)); - ACCUM4(sx1,sy2,sz1,(1.0f-sxf)* syf *(1.0f-szf)); - ACCUM4(sx2,sy2,sz1, sxf * syf *(1.0f-szf)); - ACCUM4(sx1,sy1,sz2,(1.0f-sxf)*(1.0f-syf)* szf ); - ACCUM4(sx2,sy1,sz2, sxf *(1.0f-syf)* szf ); - ACCUM4(sx1,sy2,sz2,(1.0f-sxf)* syf * szf ); - ACCUM4(sx2,sy2,sz2, sxf * syf * szf ); - } - - memcpy(pdst, accum, sizeof(float)*dstchannels); - -#undef ACCUM3 -#undef ACCUM4 - - pdst += dstchannels; - } - pdst += dstchannels*dst.getRowSkip(); - } - pdst += dstchannels*dst.getSliceSkip(); - } - } -}; - - - -// byte linear resampler, does not do any format conversions. -// only handles pixel formats that use 1 byte per color channel. -// 2D only; punts 3D pixelboxes to default LinearResampler (slow). -// templated on bytes-per-pixel to allow compiler optimizations, such -// as unrolling loops and replacing multiplies with bitshifts -template struct LinearResampler_Byte { - static void scale(const PixelBox& src, const PixelBox& dst) { - // assert(src.format == dst.format); - - // only optimized for 2D - if (src.getDepth() > 1 || dst.getDepth() > 1) { - LinearResampler::scale(src, dst); - return; - } - - // srcdata stays at beginning of slice, pdst is a moving pointer - uchar* srcdata = (uchar*)src.getTopLeftFrontPixelPtr(); - uchar* pdst = (uchar*)dst.getTopLeftFrontPixelPtr(); - - // sx_48,sy_48 represent current position in source - // using 16/48-bit fixed precision, incremented by steps - uint64 stepx = ((uint64)src.getWidth() << 48) / dst.getWidth(); - uint64 stepy = ((uint64)src.getHeight() << 48) / dst.getHeight(); - - uint64 sy_48 = (stepy >> 1) - 1; - for (size_t y = dst.top; y < dst.bottom; y++, sy_48+=stepy) { - // bottom 28 bits of temp are 16/12 bit fixed precision, used to - // adjust a source coordinate backwards by half a pixel so that the - // integer bits represent the first sample (eg, sx1) and the - // fractional bits are the blend weight of the second sample - unsigned int temp = static_cast(sy_48 >> 36); - temp = (temp > 0x800)? temp - 0x800: 0; - unsigned int syf = temp & 0xFFF; - uint32 sy1 = temp >> 12; - uint32 sy2 = std::min(sy1+1, src.bottom-src.top-1); - size_t syoff1 = sy1 * src.rowPitch; - size_t syoff2 = sy2 * src.rowPitch; - - uint64 sx_48 = (stepx >> 1) - 1; - for (size_t x = dst.left; x < dst.right; x++, sx_48+=stepx) { - temp = static_cast(sx_48 >> 36); - temp = (temp > 0x800)? temp - 0x800 : 0; - unsigned int sxf = temp & 0xFFF; - uint32 sx1 = temp >> 12; - uint32 sx2 = std::min(sx1+1, src.right-src.left-1); - - unsigned int sxfsyf = sxf*syf; - for (unsigned int k = 0; k < channels; k++) { - unsigned int accum = - srcdata[(sx1 + syoff1)*channels+k]*(0x1000000-(sxf<<12)-(syf<<12)+sxfsyf) + - srcdata[(sx2 + syoff1)*channels+k]*((sxf<<12)-sxfsyf) + - srcdata[(sx1 + syoff2)*channels+k]*((syf<<12)-sxfsyf) + - srcdata[(sx2 + syoff2)*channels+k]*sxfsyf; - // accum is computed using 8/24-bit fixed-point math - // (maximum is 0xFF000000; rounding will not cause overflow) - *pdst++ = static_cast((accum + 0x800000) >> 24); - } - } - pdst += channels*dst.getRowSkip(); - } - } -}; -/** @} */ -/** @} */ - -} - -#endif diff --git a/OgreMain/src/OgreInstanceBatch.cpp b/OgreMain/src/OgreInstanceBatch.cpp deleted file mode 100644 index 365f4a48c6d..00000000000 --- a/OgreMain/src/OgreInstanceBatch.cpp +++ /dev/null @@ -1,589 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreInstanceManager.h" -#include "OgreInstanceBatch.h" -#include "OgreInstancedEntity.h" -#include "OgreRenderQueue.h" -#include "OgreLodListener.h" - -namespace Ogre -{ - const String MOT_INSTANCE_BATCH = "InstanceBatch"; - - InstanceBatch::InstanceBatch( InstanceManager *creator, MeshPtr &meshReference, - const MaterialPtr &material, size_t instancesPerBatch, - const Mesh::IndexMap *indexToBoneMap, const String &batchName ) : - Renderable(), - MovableObject(), - mInstancesPerBatch( instancesPerBatch ), - mCreator( creator ), - mMaterial( material ), - mMeshReference( meshReference ), - mIndexToBoneMap( indexToBoneMap ), - mBoundingRadius( 0 ), - mBoundsDirty( false ), - mBoundsUpdated( false ), - mCurrentCamera( 0 ), - mDirtyAnimation(true), - mTechnSupportsSkeletal( true ), - mCameraDistLastUpdateFrameNumber( std::numeric_limits::max() ), - mCachedCamera( 0 ), - mTransformSharingDirty(true), - mRemoveOwnVertexData(false), - mRemoveOwnIndexData(false) - { - assert( mInstancesPerBatch ); - - //Force batch visibility to be always visible. The instanced entities - //have individual visibility flags. If none matches the scene's current, - //then this batch won't rendered. - mVisibilityFlags = std::numeric_limits::max(); - - if( indexToBoneMap ) - { - assert( !(meshReference->hasSkeleton() && indexToBoneMap->empty()) ); - } - - mFullBoundingBox.setExtents( -Vector3::ZERO, Vector3::ZERO ); - - mName = batchName; - if (mCreator != NULL) - { - mCustomParams.resize( mCreator->getNumCustomParams() * mInstancesPerBatch, Vector4f(0) ); - } - - } - - InstanceBatch::~InstanceBatch() - { - deleteAllInstancedEntities(); - - //Remove the parent scene node automatically - SceneNode *sceneNode = getParentSceneNode(); - if( sceneNode ) - { - sceneNode->detachAllObjects(); - sceneNode->getParentSceneNode()->removeAndDestroyChild( sceneNode ); - } - - if( mRemoveOwnVertexData ) - OGRE_DELETE mRenderOperation.vertexData; - if( mRemoveOwnIndexData ) - OGRE_DELETE mRenderOperation.indexData; - - } - - void InstanceBatch::_setInstancesPerBatch( size_t instancesPerBatch ) - { - OgreAssert(mInstancedEntities.empty(), - "Instances per batch can only be changed before building the batch"); - mInstancesPerBatch = instancesPerBatch; - } - //----------------------------------------------------------------------- - bool InstanceBatch::checkSubMeshCompatibility( const SubMesh* baseSubMesh ) - { - OgreAssert(baseSubMesh->operationType == RenderOperation::OT_TRIANGLE_LIST, - "Only meshes with OT_TRIANGLE_LIST are supported"); - - if( !mCustomParams.empty() && mCreator->getInstancingTechnique() != InstanceManager::HWInstancingBasic ) - { - //Implementing this for ShaderBased is impossible. All other variants can be. - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Custom parameters not supported for this " - "technique. Do you dare implementing it?" - "See InstanceManager::setNumCustomParams " - "documentation.", - "InstanceBatch::checkSubMeshCompatibility"); - } - - return true; - } - //----------------------------------------------------------------------- - void InstanceBatch::_updateBounds(void) - { - mFullBoundingBox.setNull(); - Real maxScale = 0; - - for(auto *e : mInstancedEntities) - { - //Only increase the bounding box for those objects we know are in the scene - if(e->isInScene()) - { - maxScale = std::max(maxScale, e->getMaxScaleCoef()); - mFullBoundingBox.merge( e->_getDerivedPosition() ); - } - } - - Real addToBound = maxScale * _getMeshReference()->getBoundingSphereRadius(); - mFullBoundingBox.setMaximum(mFullBoundingBox.getMaximum() + addToBound); - mFullBoundingBox.setMinimum(mFullBoundingBox.getMinimum() - addToBound); - - - mBoundingRadius = Math::boundingRadiusFromAABBCentered( mFullBoundingBox ); - if (mParentNode) { - mParentNode->needUpdate(); - } - mBoundsUpdated = true; - mBoundsDirty = false; - } - - //----------------------------------------------------------------------- - void InstanceBatch::updateVisibility(void) - { - mVisible = false; - - InstancedEntityVec::const_iterator itor = mInstancedEntities.begin(); - InstancedEntityVec::const_iterator end = mInstancedEntities.end(); - - while( itor != end && !mVisible ) - { - //Trick to force Ogre not to render us if none of our instances is visible - //Because we do Camera::isVisible(), it is better if the SceneNode from the - //InstancedEntity is not part of the scene graph (i.e. ultimate parent is root node) - //to avoid unnecessary wasteful calculations - mVisible |= (*itor)->findVisible( mCurrentCamera ); - ++itor; - } - } - //----------------------------------------------------------------------- - void InstanceBatch::createAllInstancedEntities() - { - mInstancedEntities.reserve( mInstancesPerBatch ); - mUnusedEntities.reserve( mInstancesPerBatch ); - - for( size_t i=0; i(num)); - } - //----------------------------------------------------------------------- - void InstanceBatch::deleteAllInstancedEntities() - { - for (auto *e : mInstancedEntities) - { - if(e->getParentSceneNode() ) - e->getParentSceneNode()->detachObject(e); - OGRE_DELETE e; - } - } - //----------------------------------------------------------------------- - void InstanceBatch::deleteUnusedInstancedEntities() - { - for (auto *e : mUnusedEntities) - OGRE_DELETE e; - - mUnusedEntities.clear(); - } - //----------------------------------------------------------------------- - void InstanceBatch::makeMatrixCameraRelative3x4( Matrix3x4f *mat3x4, size_t count ) - { - const Vector3 &cameraRelativePosition = mCurrentCamera->getDerivedPosition(); - - for( size_t i=0; i(cameraRelativePosition)); - } - } - //----------------------------------------------------------------------- - RenderOperation InstanceBatch::build( const SubMesh* baseSubMesh ) - { - if( checkSubMeshCompatibility( baseSubMesh ) ) - { - //Only triangle list at the moment - mRenderOperation.operationType = RenderOperation::OT_TRIANGLE_LIST; - mRenderOperation.srcRenderable = this; - mRenderOperation.useIndexes = true; - setupVertices( baseSubMesh ); - setupIndices( baseSubMesh ); - - createAllInstancedEntities(); - } - - return mRenderOperation; - } - //----------------------------------------------------------------------- - void InstanceBatch::buildFrom( const SubMesh *baseSubMesh, const RenderOperation &renderOperation ) - { - mRenderOperation = renderOperation; - createAllInstancedEntities(); - } - //----------------------------------------------------------------------- - InstancedEntity* InstanceBatch::createInstancedEntity() - { - InstancedEntity *retVal = 0; - - if( !mUnusedEntities.empty() ) - { - retVal = mUnusedEntities.back(); - mUnusedEntities.pop_back(); - - retVal->setInUse(true); - } - - return retVal; - } - //----------------------------------------------------------------------- - void InstanceBatch::removeInstancedEntity( InstancedEntity *instancedEntity ) - { - OgreAssert(instancedEntity->mBatchOwner == this, - "Trying to remove an InstancedEntity from scene created with a different InstanceBatch"); - OgreAssert(instancedEntity->isInUse(), "Trying to remove an InstancedEntity that is already removed"); - - if( instancedEntity->getParentSceneNode() ) - instancedEntity->getParentSceneNode()->detachObject( instancedEntity ); - - instancedEntity->setInUse(false); - instancedEntity->stopSharingTransform(); - - //Put it back into the queue - mUnusedEntities.push_back( instancedEntity ); - } - //----------------------------------------------------------------------- - void InstanceBatch::getInstancedEntitiesInUse( InstancedEntityVec &outEntities, - CustomParamsVec &outParams ) - { - for (auto *e : mInstancedEntities) { - if (e->isInUse()) { - outEntities.push_back(e); - for( unsigned char i=0; igetNumCustomParams(); ++i ) - outParams.push_back(_getCustomParam(e, i)); - } - } - } - //----------------------------------------------------------------------- - void InstanceBatch::defragmentBatchNoCull( InstancedEntityVec &usedEntities, - CustomParamsVec &usedParams ) - { - const size_t maxInstancesToCopy = std::min( mInstancesPerBatch, usedEntities.size() ); - InstancedEntityVec::iterator first = usedEntities.end() - maxInstancesToCopy; - CustomParamsVec::iterator firstParams = usedParams.end() - maxInstancesToCopy * - mCreator->getNumCustomParams(); - - //Copy from the back to front, into m_instancedEntities - mInstancedEntities.insert( mInstancedEntities.begin(), first, usedEntities.end() ); - //Remove them from the array - usedEntities.resize( usedEntities.size() - maxInstancesToCopy ); - - mCustomParams.insert( mCustomParams.begin(), firstParams, usedParams.end() ); - } - //----------------------------------------------------------------------- - void InstanceBatch::defragmentBatchDoCull( InstancedEntityVec &usedEntities, - CustomParamsVec &usedParams ) - { - //Get the the entity closest to the minimum bbox edge and put into "first" - InstancedEntityVec::const_iterator itor = usedEntities.begin(); - InstancedEntityVec::const_iterator end = usedEntities.end(); - - Vector3 vMinPos = Vector3::ZERO, firstPos = Vector3::ZERO; - InstancedEntity *first = 0; - - if( !usedEntities.empty() ) - { - first = *usedEntities.begin(); - firstPos = first->_getDerivedPosition(); - vMinPos = first->_getDerivedPosition(); - } - - while( itor != end ) - { - const Vector3 &vPos = (*itor)->_getDerivedPosition(); - - vMinPos.x = std::min( vMinPos.x, vPos.x ); - vMinPos.y = std::min( vMinPos.y, vPos.y ); - vMinPos.z = std::min( vMinPos.z, vPos.z ); - - if( vMinPos.squaredDistance( vPos ) < vMinPos.squaredDistance( firstPos ) ) - { - firstPos = vPos; - } - - ++itor; - } - - //Now collect entities closest to 'first' - while( !usedEntities.empty() && mInstancedEntities.size() < mInstancesPerBatch ) - { - InstancedEntityVec::iterator closest = usedEntities.begin(); - InstancedEntityVec::iterator it = usedEntities.begin(); - InstancedEntityVec::iterator e = usedEntities.end(); - - Vector3 closestPos; - closestPos = (*closest)->_getDerivedPosition(); - - while( it != e ) - { - const Vector3 &vPos = (*it)->_getDerivedPosition(); - - if( firstPos.squaredDistance( vPos ) < firstPos.squaredDistance( closestPos ) ) - { - closest = it; - closestPos = vPos; - } - - ++it; - } - - mInstancedEntities.push_back( *closest ); - //Now the custom params - const size_t idx = closest - usedEntities.begin(); - for( unsigned char i=0; igetNumCustomParams(); ++i ) - { - mCustomParams.push_back( usedParams[idx + i] ); - } - - //Remove 'closest' from usedEntities & usedParams using swap and pop_back trick - *closest = *(usedEntities.end() - 1); - usedEntities.pop_back(); - - for( unsigned char i=1; i<=mCreator->getNumCustomParams(); ++i ) - { - usedParams[idx + mCreator->getNumCustomParams() - i] = *(usedParams.end() - 1); - usedParams.pop_back(); - } - } - } - //----------------------------------------------------------------------- - void InstanceBatch::_defragmentBatch( bool optimizeCulling, InstancedEntityVec &usedEntities, - CustomParamsVec &usedParams ) - { - //Remove and clear what we don't need - mInstancedEntities.clear(); - mCustomParams.clear(); - deleteUnusedInstancedEntities(); - - if( !optimizeCulling ) - defragmentBatchNoCull( usedEntities, usedParams ); - else - defragmentBatchDoCull( usedEntities, usedParams ); - - //Reassign instance IDs and tell we're the new parent - uint32 instanceId = 0; - for (auto *e : mInstancedEntities) { - e->mInstanceId = instanceId++; - e->mBatchOwner = this; - } - - //Recreate unused entities, if there's left space in our container - assert( (signed)(mInstancesPerBatch) - (signed)(mInstancedEntities.size()) >= 0 ); - mInstancedEntities.reserve( mInstancesPerBatch ); - mUnusedEntities.reserve( mInstancesPerBatch ); - mCustomParams.reserve( mCreator->getNumCustomParams() * mInstancesPerBatch ); - for( size_t i=mInstancedEntities.size(); i_addDirtyBatch( this ); - mBoundsDirty = true; - } - //----------------------------------------------------------------------- - const String& InstanceBatch::getMovableType(void) const - { - return MOT_INSTANCE_BATCH; - } - //----------------------------------------------------------------------- - void InstanceBatch::_notifyCurrentCamera( Camera* cam ) - { - mCurrentCamera = cam; - - //See DistanceLodStrategy::getValueImpl() - //We use our own because our SceneNode is just filled with zeroes, and updating it - //with real values is expensive, plus we would need to make sure it doesn't get to - //the shader - Real depth = Math::Sqrt(getSquaredViewDepth(cam)) - getBoundingRadius(); - depth = std::max( depth, Real(0) ); - - Real lodValue = depth * cam->_getLodBiasInverse(); - - //Now calculate Material LOD - /*const LodStrategy *materialStrategy = m_material->getLodStrategy(); - - //Calculate LOD value for given strategy - Real lodValue = materialStrategy->getValue( this, cam );*/ - - //Get the index at this depth - unsigned short idx = mMaterial->getLodIndex( lodValue ); - - //TODO: Replace subEntity for MovableObject - // Construct event object - /*EntityMaterialLodChangedEvent subEntEvt; - subEntEvt.subEntity = this; - subEntEvt.camera = cam; - subEntEvt.lodValue = lodValue; - subEntEvt.previousLodIndex = m_materialLodIndex; - subEntEvt.newLodIndex = idx; - - //Notify LOD event listeners - cam->getSceneManager()->_notifyEntityMaterialLodChanged(subEntEvt);*/ - - // Change LOD index - mMaterialLodIndex = idx; - - mBeyondFarDistance = false; - - if (cam->getUseRenderingDistance() && mUpperDistance > 0) - { - if (depth > mUpperDistance) - mBeyondFarDistance = true; - } - - if (!mBeyondFarDistance && cam->getUseMinPixelSize() && mMinPixelSize > 0) - { - Real pixelRatio = cam->getPixelDisplayRatio(); - - Ogre::Vector3 objBound = - getBoundingBox().getSize() * getParentNode()->_getDerivedScale(); - objBound.x = Math::Sqr(objBound.x); - objBound.y = Math::Sqr(objBound.y); - objBound.z = Math::Sqr(objBound.z); - float sqrObjMedianSize = std::max( - std::max(std::min(objBound.x, objBound.y), std::min(objBound.x, objBound.z)), - std::min(objBound.y, objBound.z)); - - // If we have a perspective camera calculations are done relative to distance - Real sqrDistance = 1; - - if (cam->getProjectionType() == PT_PERSPECTIVE) - sqrDistance = getSquaredViewDepth(cam->getLodCamera()); // it's ok - - mBeyondFarDistance = - sqrObjMedianSize < sqrDistance * Math::Sqr(pixelRatio * mMinPixelSize); - } - - if (mParentNode) - { - MovableObjectLodChangedEvent evt; - evt.movableObject = this; - evt.camera = cam; - - cam->getSceneManager()->_notifyMovableObjectLodChanged(evt); - } - - mRenderingDisabled = mListener && !mListener->objectRendering(this, cam); - - // MovableObject::_notifyCurrentCamera( cam ); // it does not suit - } - //----------------------------------------------------------------------- - const AxisAlignedBox& InstanceBatch::getBoundingBox(void) const - { - return mFullBoundingBox; - } - //----------------------------------------------------------------------- - Real InstanceBatch::getBoundingRadius(void) const - { - return mBoundingRadius; - } - //----------------------------------------------------------------------- - Real InstanceBatch::getSquaredViewDepth( const Camera* cam ) const - { - unsigned long currentFrameNumber = Root::getSingleton().getNextFrameNumber(); - - if (mCameraDistLastUpdateFrameNumber != currentFrameNumber || mCachedCamera != cam) - { - mCachedCameraDist = - getBoundingBox().getCenter().squaredDistance(cam->getDerivedPosition()); - - mCachedCamera = cam; - mCameraDistLastUpdateFrameNumber = currentFrameNumber; - } - - return mCachedCameraDist; - } - //----------------------------------------------------------------------- - const LightList& InstanceBatch::getLights( void ) const - { - return queryLights(); - } - //----------------------------------------------------------------------- - void InstanceBatch::_updateRenderQueue( RenderQueue* queue ) - { - /*if( m_boundsDirty ) - _updateBounds();*/ - - mDirtyAnimation = false; - - //Is at least one object in the scene? - updateVisibility(); - - if( mVisible ) - { - if( mMeshReference->hasSkeleton() ) { - for (auto *e : mInstancedEntities) { - mDirtyAnimation |= e->_updateAnimation(); - } - } - - queue->addRenderable( this, mRenderQueueID, mRenderQueuePriority ); - } - - //Reset visibility once we skipped addRenderable (which saves GPU time), because OGRE for some - //reason stops updating our render queue afterwards, preventing us to recalculate visibility - mVisible = true; - } - //----------------------------------------------------------------------- - void InstanceBatch::visitRenderables( Renderable::Visitor* visitor, bool debugRenderables ) - { - visitor->visit( this, 0, false ); - } - //----------------------------------------------------------------------- - void InstanceBatch::_setCustomParam( InstancedEntity *instancedEntity, unsigned char idx, - const Vector4f &newParam ) - { - mCustomParams[instancedEntity->mInstanceId * mCreator->getNumCustomParams() + idx] = newParam; - } - //----------------------------------------------------------------------- - const Vector4f& InstanceBatch::_getCustomParam( InstancedEntity *instancedEntity, unsigned char idx ) - { - return mCustomParams[instancedEntity->mInstanceId * mCreator->getNumCustomParams() + idx]; - } -} diff --git a/OgreMain/src/OgreInstanceBatchHW.cpp b/OgreMain/src/OgreInstanceBatchHW.cpp deleted file mode 100644 index 33320199027..00000000000 --- a/OgreMain/src/OgreInstanceBatchHW.cpp +++ /dev/null @@ -1,232 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreInstanceBatchHW.h" -#include "OgreRenderOperation.h" -#include "OgreInstancedEntity.h" - -namespace Ogre -{ - InstanceBatchHW::InstanceBatchHW( InstanceManager *creator, MeshPtr &meshReference, - const MaterialPtr &material, size_t instancesPerBatch, - const Mesh::IndexMap *indexToBoneMap, const String &batchName ) : - InstanceBatch( creator, meshReference, material, instancesPerBatch, - indexToBoneMap, batchName ), - mKeepStatic( false ) - { - //Override defaults, so that InstancedEntities don't create a skeleton instance - mTechnSupportsSkeletal = false; - } - - InstanceBatchHW::~InstanceBatchHW() - { - } - - //----------------------------------------------------------------------- - size_t InstanceBatchHW::calculateMaxNumInstances( const SubMesh *baseSubMesh, uint16 flags ) const - { - size_t retVal = 0; - - RenderSystem *renderSystem = Root::getSingleton().getRenderSystem(); - const RenderSystemCapabilities *capabilities = renderSystem->getCapabilities(); - - if( capabilities->hasCapability( RSC_VERTEX_BUFFER_INSTANCE_DATA ) ) - { - //This value is arbitrary (theorical max is 2^30 for D3D9) but is big enough and safe - retVal = 65535; - } - - return retVal; - } - //----------------------------------------------------------------------- - void InstanceBatchHW::buildFrom( const SubMesh *baseSubMesh, const RenderOperation &renderOperation ) - { - InstanceBatch::buildFrom( baseSubMesh, renderOperation ); - - //We need to clone the VertexData (but just reference all buffers, except the last one) - //because last buffer contains data specific to this batch, we need a different binding - mRenderOperation.vertexData = mRenderOperation.vertexData->clone( false ); - mRemoveOwnVertexData = true; - VertexData *thisVertexData = mRenderOperation.vertexData; - const unsigned short lastSource = thisVertexData->vertexDeclaration->getMaxSource(); - auto vertexBuffer = HardwareBufferManager::getSingleton().createVertexBuffer( - thisVertexData->vertexDeclaration->getVertexSize(lastSource), mInstancesPerBatch, HBU_CPU_TO_GPU); - thisVertexData->vertexBufferBinding->setBinding( lastSource, vertexBuffer ); - vertexBuffer->setIsInstanceData( true ); - vertexBuffer->setInstanceDataStepRate( 1 ); - } - //----------------------------------------------------------------------- - void InstanceBatchHW::setupVertices( const SubMesh* baseSubMesh ) - { - //No skeletal animation support in this technique, sorry - mRenderOperation.vertexData = baseSubMesh->vertexData->_cloneRemovingBlendData(); - mRemoveOwnVertexData = true; //Raise flag to remove our own vertex data in the end (not always needed) - - VertexData *thisVertexData = mRenderOperation.vertexData; - - //Modify the declaration so it contains an extra source, where we can put the per instance data - size_t offset = 0; - unsigned short nextTexCoord = thisVertexData->vertexDeclaration->getNextFreeTextureCoordinate(); - const unsigned short newSource = thisVertexData->vertexDeclaration->getMaxSource() + 1; - for (unsigned char i = 0; i < 3 + mCreator->getNumCustomParams(); ++i) - { - thisVertexData->vertexDeclaration->addElement( newSource, offset, VET_FLOAT4, - VES_TEXTURE_COORDINATES, nextTexCoord++ ); - offset = thisVertexData->vertexDeclaration->getVertexSize( newSource ); - } - - //Create the vertex buffer containing per instance data - auto vertexBuffer = HardwareBufferManager::getSingleton().createVertexBuffer( - thisVertexData->vertexDeclaration->getVertexSize(newSource), mInstancesPerBatch, HBU_CPU_TO_GPU); - thisVertexData->vertexBufferBinding->setBinding( newSource, vertexBuffer ); - vertexBuffer->setIsInstanceData( true ); - vertexBuffer->setInstanceDataStepRate( 1 ); - } - //----------------------------------------------------------------------- - void InstanceBatchHW::setupIndices( const SubMesh* baseSubMesh ) - { - //We could use just a reference, but the InstanceManager will in the end attampt to delete - //the pointer, and we can't give it something that doesn't belong to us. - mRenderOperation.indexData = baseSubMesh->indexData->clone( true ); - mRemoveOwnIndexData = true; //Raise flag to remove our own index data in the end (not always needed) - } - //----------------------------------------------------------------------- - bool InstanceBatchHW::checkSubMeshCompatibility( const SubMesh* baseSubMesh ) - { - //Max number of texture coordinates is _usually_ 8, we need at least 3 available - if( baseSubMesh->vertexData->vertexDeclaration->getNextFreeTextureCoordinate() > 8-2 ) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Given mesh must have at " - "least 3 free TEXCOORDs", - "InstanceBatchHW::checkSubMeshCompatibility"); - } - if( baseSubMesh->vertexData->vertexDeclaration->getNextFreeTextureCoordinate() > - 8-2-mCreator->getNumCustomParams() || - 3 + mCreator->getNumCustomParams() >= 8 ) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "There are not enough free TEXCOORDs to hold the " - "custom parameters (required: " + - Ogre::StringConverter::toString( 3 + mCreator-> - getNumCustomParams() ) + "). See InstanceManager" - "::setNumCustomParams documentation", - "InstanceBatchHW::checkSubMeshCompatibility"); - } - - return InstanceBatch::checkSubMeshCompatibility( baseSubMesh ); - } - //----------------------------------------------------------------------- - size_t InstanceBatchHW::updateVertexBuffer( Camera *currentCamera ) - { - size_t retVal = 0; - - //Now lock the vertex buffer and copy the 4x3 matrices, only those who need it! - VertexBufferBinding* binding = mRenderOperation.vertexData->vertexBufferBinding; - const ushort bufferIdx = ushort(binding->getBufferCount()-1); - HardwareBufferLockGuard vertexLock(binding->getBuffer(bufferIdx), HardwareBuffer::HBL_DISCARD); - float *pDest = static_cast(vertexLock.pData); - unsigned char numCustomParams = mCreator->getNumCustomParams(); - size_t customParamIdx = 0; - - for (auto *e : mInstancedEntities) - { - //Cull on an individual basis, the less entities are visible, the less instances we draw. - //No need to use null matrices at all! - if (e->findVisible(currentCamera )) - { - const size_t floatsWritten = e->getTransforms3x4( (Matrix3x4f*)pDest); - - if( mManager->getCameraRelativeRendering() ) - makeMatrixCameraRelative3x4((Matrix3x4f*)pDest, floatsWritten / 12); - - pDest += floatsWritten; - - //Write custom parameters, if any - for (unsigned char i = 0; i < numCustomParams; ++i) - { - memcpy(pDest, mCustomParams[customParamIdx+i].ptr(), sizeof(Vector4f)); - pDest += 4; - } - ++retVal; - } - customParamIdx += numCustomParams; - } - - return retVal; - } - //----------------------------------------------------------------------- - void InstanceBatchHW::_boundsDirty(void) - { - //Don't update if we're static, but still mark we're dirty - if( !mBoundsDirty && !mKeepStatic ) - mCreator->_addDirtyBatch( this ); - mBoundsDirty = true; - } - //----------------------------------------------------------------------- - void InstanceBatchHW::setStaticAndUpdate( bool bStatic ) - { - //We were dirty but didn't update bounds. Do it now. - if( mKeepStatic && mBoundsDirty ) - mCreator->_addDirtyBatch( this ); - - mKeepStatic = bStatic; - if( mKeepStatic ) - { - //One final update, since there will be none from now on - //(except further calls to this function). Pass NULL because - //we want to include only those who were added to the scene - //but we don't want to perform culling - mRenderOperation.numberOfInstances = updateVertexBuffer( 0 ); - } - } - //----------------------------------------------------------------------- - void InstanceBatchHW::getWorldTransforms( Matrix4* xform ) const - { - *xform = Matrix4::IDENTITY; - } - //----------------------------------------------------------------------- - void InstanceBatchHW::_updateRenderQueue( RenderQueue* queue ) - { - if( !mKeepStatic ) - { - //Completely override base functionality, since we don't cull on an "all-or-nothing" basis - //and we don't support skeletal animation - if( (mRenderOperation.numberOfInstances = updateVertexBuffer( mCurrentCamera )) ) - queue->addRenderable( this, mRenderQueueID, mRenderQueuePriority ); - } - else - { - OgreAssert(!mManager->getCameraRelativeRendering(), - "Camera-relative rendering is incompatible with Instancing's static batches. " - "Disable at least one of them"); - - //Don't update when we're static - if( mRenderOperation.numberOfInstances ) - queue->addRenderable( this, mRenderQueueID, mRenderQueuePriority ); - } - } -} diff --git a/OgreMain/src/OgreInstanceBatchHW_VTF.cpp b/OgreMain/src/OgreInstanceBatchHW_VTF.cpp deleted file mode 100644 index e7d4787b251..00000000000 --- a/OgreMain/src/OgreInstanceBatchHW_VTF.cpp +++ /dev/null @@ -1,535 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreInstanceBatchHW_VTF.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreInstancedEntity.h" - -namespace Ogre -{ - static const uint16 c_maxTexWidthHW = 4096; - static const uint16 c_maxTexHeightHW = 4096; - - InstanceBatchHW_VTF::InstanceBatchHW_VTF( - InstanceManager *creator, MeshPtr &meshReference, - const MaterialPtr &material, size_t instancesPerBatch, - const Mesh::IndexMap *indexToBoneMap, const String &batchName ) - : BaseInstanceBatchVTF( creator, meshReference, material, - instancesPerBatch, indexToBoneMap, batchName), - mKeepStatic( false ) - { - } - //----------------------------------------------------------------------- - InstanceBatchHW_VTF::~InstanceBatchHW_VTF() - { - } - //----------------------------------------------------------------------- - void InstanceBatchHW_VTF::setupVertices( const SubMesh* baseSubMesh ) - { - mRenderOperation.vertexData = OGRE_NEW VertexData(); - mRemoveOwnVertexData = true; //Raise flag to remove our own vertex data in the end (not always needed) - - VertexData *thisVertexData = mRenderOperation.vertexData; - VertexData *baseVertexData = baseSubMesh->vertexData; - - thisVertexData->vertexStart = 0; - thisVertexData->vertexCount = baseVertexData->vertexCount; - mRenderOperation.numberOfInstances = mInstancesPerBatch; - - HardwareBufferManager::getSingleton().destroyVertexDeclaration(thisVertexData->vertexDeclaration ); - thisVertexData->vertexDeclaration = baseVertexData->vertexDeclaration->clone(); - - //Reuse all vertex buffers - for (auto& v : baseVertexData->vertexBufferBinding->getBindings()) - { - const unsigned short bufferIdx = v.first; - const HardwareVertexBufferSharedPtr vBuf = v.second; - thisVertexData->vertexBufferBinding->setBinding( bufferIdx, vBuf ); - } - - //Remove the blend weights & indices - HWBoneIdxVec hwBoneIdx; - HWBoneWgtVec hwBoneWgt; - - //Blend weights may not be present because HW_VTF does not require to be skeletally animated - const VertexElement *veWeights = baseVertexData->vertexDeclaration->findElementBySemantic( VES_BLEND_WEIGHTS ); - if( veWeights ) - mWeightCount = forceOneWeight() ? 1 : veWeights->getSize() / sizeof(float); - else - mWeightCount = 1; - - hwBoneIdx.resize( baseVertexData->vertexCount * mWeightCount, 0 ); - - if( mMeshReference->hasSkeleton() && mMeshReference->getSkeleton() ) - { - if(mWeightCount > 1) - { - hwBoneWgt.resize( baseVertexData->vertexCount * mWeightCount, 0 ); - retrieveBoneIdxWithWeights(baseVertexData, hwBoneIdx, hwBoneWgt); - } - else - { - retrieveBoneIdx( baseVertexData, hwBoneIdx ); - } - - const VertexElement* pElement = thisVertexData->vertexDeclaration->findElementBySemantic - (VES_BLEND_INDICES); - if (pElement) - { - unsigned short skelDataSource = pElement->getSource(); - thisVertexData->vertexDeclaration->removeElement( VES_BLEND_INDICES ); - thisVertexData->vertexDeclaration->removeElement( VES_BLEND_WEIGHTS ); - if (thisVertexData->vertexDeclaration->findElementsBySource(skelDataSource).empty()) - { - thisVertexData->vertexDeclaration->closeGapsInSource(); - thisVertexData->vertexBufferBinding->unsetBinding(skelDataSource); - VertexBufferBinding::BindingIndexMap tmpMap; - thisVertexData->vertexBufferBinding->closeGaps(tmpMap); - } - } - } - - createVertexTexture( baseSubMesh ); - createVertexSemantics( thisVertexData, baseVertexData, hwBoneIdx, hwBoneWgt); - } - //----------------------------------------------------------------------- - void InstanceBatchHW_VTF::setupIndices( const SubMesh* baseSubMesh ) - { - //We could use just a reference, but the InstanceManager will in the end attampt to delete - //the pointer, and we can't give it something that doesn't belong to us. - mRenderOperation.indexData = baseSubMesh->indexData->clone( true ); - mRemoveOwnIndexData = true; //Raise flag to remove our own index data in the end (not always needed) - } - //----------------------------------------------------------------------- - void InstanceBatchHW_VTF::createVertexSemantics( VertexData *thisVertexData, - VertexData *baseVertexData, - const HWBoneIdxVec &hwBoneIdx, - const HWBoneWgtVec& hwBoneWgt) - { - const float texWidth = static_cast(mMatrixTexture->getWidth()); - - //Only one weight per vertex is supported. It would not only be complex, but prohibitively slow. - //Put them in a new buffer, since it's 16 bytes aligned :-) - unsigned short newSource = thisVertexData->vertexDeclaration->getMaxSource() + 1; - - size_t offset = 0; - - size_t maxFloatsPerVector = 4; - - //Can fit two dual quaternions in every float4, but only one 3x4 matrix - for(size_t i = 0; i < mWeightCount; i += maxFloatsPerVector / mRowLength) - { - offset += thisVertexData->vertexDeclaration->addElement( newSource, offset, VET_FLOAT4, VES_TEXTURE_COORDINATES, - thisVertexData->vertexDeclaration->getNextFreeTextureCoordinate() ).getSize(); - } - - //Add the weights (supports up to four, which is Ogre's limit) - if(mWeightCount > 1) - { - thisVertexData->vertexDeclaration->addElement(newSource, offset, VET_FLOAT4, VES_BLEND_WEIGHTS, - 0 ).getSize(); - } - - //Create our own vertex buffer - HardwareVertexBufferSharedPtr vertexBuffer = - HardwareBufferManager::getSingleton().createVertexBuffer( - thisVertexData->vertexDeclaration->getVertexSize(newSource), - thisVertexData->vertexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY ); - thisVertexData->vertexBufferBinding->setBinding( newSource, vertexBuffer ); - - HardwareBufferLockGuard vertexLock(vertexBuffer, HardwareBuffer::HBL_DISCARD); - float *thisFloat = static_cast(vertexLock.pData); - - //Create the UVs to sample from the right bone/matrix - for( size_t j=0; j < baseVertexData->vertexCount * mWeightCount; j += mWeightCount) - { - size_t numberOfMatricesInLine = 0; - - //Write the matrices, adding padding as needed - for(size_t i = 0; i < mWeightCount; ++i) - { - //Write the matrix - for( size_t k=0; k < mRowLength; ++k) - { - //Only calculate U (not V) since all matrices are in the same row. We use the instanced - //(repeated) buffer to tell how much U & V we need to offset - size_t instanceIdx = hwBoneIdx[j+i] * mRowLength + k; - *thisFloat++ = instanceIdx / texWidth; - } - - ++numberOfMatricesInLine; - - //If another matrix can't be fit, we're on another line, or if this is the last weight - if((numberOfMatricesInLine + 1) * mRowLength > maxFloatsPerVector || (i+1) == mWeightCount) - { - //Place zeroes in the remaining coordinates - for ( size_t k=mRowLength * numberOfMatricesInLine; k < maxFloatsPerVector; ++k) - { - *thisFloat++ = 0.0f; - } - - numberOfMatricesInLine = 0; - } - } - - //Don't need to write weights if there is only one - if(mWeightCount > 1) - { - //Write the weights - for(size_t i = 0; i < mWeightCount; ++i) - { - *thisFloat++ = hwBoneWgt[j+i]; - } - - //Write the empty space - for(size_t i = mWeightCount; i < maxFloatsPerVector; ++i) - { - *thisFloat++ = 0.0f; - } - } - } - - vertexLock.unlock(); - - //Now create the instance buffer that will be incremented per instance, contains UV offsets - newSource = thisVertexData->vertexDeclaration->getMaxSource() + 1; - offset = thisVertexData->vertexDeclaration->addElement( newSource, 0, VET_FLOAT2, VES_TEXTURE_COORDINATES,thisVertexData->vertexDeclaration->getNextFreeTextureCoordinate() ).getSize(); - if (useBoneMatrixLookup()) - { - //if using bone matrix lookup we will need to add 3 more float4 to contain the matrix. containing - //the personal world transform of each entity. - offset += thisVertexData->vertexDeclaration->addElement( newSource, offset, VET_FLOAT4, VES_TEXTURE_COORDINATES, - thisVertexData->vertexDeclaration->getNextFreeTextureCoordinate() ).getSize(); - offset += thisVertexData->vertexDeclaration->addElement( newSource, offset, VET_FLOAT4, VES_TEXTURE_COORDINATES, - thisVertexData->vertexDeclaration->getNextFreeTextureCoordinate() ).getSize(); - thisVertexData->vertexDeclaration->addElement( newSource, offset, VET_FLOAT4, VES_TEXTURE_COORDINATES, - thisVertexData->vertexDeclaration->getNextFreeTextureCoordinate() ).getSize(); - //Add two floats of padding here? or earlier? - //If not using bone matrix lookup, is it ok that it is 8 bytes since divides evenly into 16 - - } - - //Create our own vertex buffer - mInstanceVertexBuffer = HardwareBufferManager::getSingleton().createVertexBuffer( - thisVertexData->vertexDeclaration->getVertexSize(newSource), - mInstancesPerBatch, - HardwareBuffer::HBU_STATIC_WRITE_ONLY ); - thisVertexData->vertexBufferBinding->setBinding( newSource, mInstanceVertexBuffer ); - - //Mark this buffer as instanced - mInstanceVertexBuffer->setIsInstanceData( true ); - mInstanceVertexBuffer->setInstanceDataStepRate( 1 ); - - updateInstanceDataBuffer(true, NULL); - } - - //updates the vertex buffer containing the per instance data - size_t InstanceBatchHW_VTF::updateInstanceDataBuffer(bool isFirstTime, Camera* currentCamera) - { - size_t visibleEntityCount = 0; - bool useMatrixLookup = useBoneMatrixLookup(); - if (isFirstTime ^ useMatrixLookup) - { - //update the mTransformLookupNumber value in the entities if needed - updateSharedLookupIndexes(); - - const float texWidth = static_cast(mMatrixTexture->getWidth()); - const float texHeight = static_cast(mMatrixTexture->getHeight()); - - //Calculate the texel offsets to correct them offline - //Awkwardly enough, the offset is needed in OpenGL too - Vector2 texelOffsets; - //RenderSystem *renderSystem = Root::getSingleton().getRenderSystem(); - texelOffsets.x = /*renderSystem->getHorizontalTexelOffset()*/ -0.5f / texWidth; - texelOffsets.y = /*renderSystem->getHorizontalTexelOffset()*/ -0.5f / texHeight; - - HardwareBufferLockGuard instanceVertexLock(mInstanceVertexBuffer, HardwareBuffer::HBL_DISCARD); - float *thisVec = static_cast(instanceVertexLock.pData); - - const size_t maxPixelsPerLine = std::min( static_cast(mMatrixTexture->getWidth()), mMaxFloatsPerLine >> 2 ); - - //Calculate UV offsets, which change per instance - for( size_t i=0; ifindVisible(currentCamera))) - { - size_t matrixIndex = useMatrixLookup ? entity->mTransformLookupNumber : i; - size_t instanceIdx = matrixIndex * mMatricesPerInstance * mRowLength; - *thisVec = ((instanceIdx % maxPixelsPerLine) / texWidth) - (float)(texelOffsets.x); - *(thisVec + 1) = ((instanceIdx / maxPixelsPerLine) / texHeight) - (float)(texelOffsets.y); - thisVec += 2; - - if (useMatrixLookup) - { - const Affine3& mat = entity->_getParentNodeFullTransform(); - *(thisVec) = static_cast( mat[0][0] ); - *(thisVec + 1) = static_cast( mat[0][1] ); - *(thisVec + 2) = static_cast( mat[0][2] ); - *(thisVec + 3) = static_cast( mat[0][3] ); - *(thisVec + 4) = static_cast( mat[1][0] ); - *(thisVec + 5) = static_cast( mat[1][1] ); - *(thisVec + 6) = static_cast( mat[1][2] ); - *(thisVec + 7) = static_cast( mat[1][3] ); - *(thisVec + 8) = static_cast( mat[2][0] ); - *(thisVec + 9) = static_cast( mat[2][1] ); - *(thisVec + 10)= static_cast( mat[2][2] ); - *(thisVec + 11)= static_cast( mat[2][3] ); - if(currentCamera && mManager->getCameraRelativeRendering()) // && useMatrixLookup - { - const Vector3 &cameraRelativePosition = currentCamera->getDerivedPosition(); - *(thisVec + 3) -= static_cast( cameraRelativePosition.x ); - *(thisVec + 7) -= static_cast( cameraRelativePosition.y ); - *(thisVec + 11) -= static_cast( cameraRelativePosition.z ); - } - thisVec += 12; - } - ++visibleEntityCount; - } - } - } - else - { - visibleEntityCount = mInstancedEntities.size(); - } - return visibleEntityCount; - } - - //----------------------------------------------------------------------- - bool InstanceBatchHW_VTF::checkSubMeshCompatibility( const SubMesh* baseSubMesh ) - { - //Max number of texture coordinates is _usually_ 8, we need at least 2 available - unsigned short neededTextureCoord = 2; - if (useBoneMatrixLookup()) - { - //we need another 3 for the unique world transform of each instanced entity - neededTextureCoord += 3; - } - if( baseSubMesh->vertexData->vertexDeclaration->getNextFreeTextureCoordinate() > 8 - neededTextureCoord ) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, - String("Given mesh must have at least ") + - StringConverter::toString(neededTextureCoord) + "free TEXCOORDs", - "InstanceBatchHW_VTF::checkSubMeshCompatibility"); - } - - return InstanceBatch::checkSubMeshCompatibility( baseSubMesh ); - } - //----------------------------------------------------------------------- - size_t InstanceBatchHW_VTF::calculateMaxNumInstances( - const SubMesh *baseSubMesh, uint16 flags ) const - { - size_t retVal = 0; - - RenderSystem *renderSystem = Root::getSingleton().getRenderSystem(); - const RenderSystemCapabilities *capabilities = renderSystem->getCapabilities(); - - //VTF & HW Instancing must be supported - if( capabilities->hasCapability( RSC_VERTEX_BUFFER_INSTANCE_DATA ) && - capabilities->hasCapability( RSC_VERTEX_TEXTURE_FETCH ) ) - { - //TODO: Check PF_FLOAT32_RGBA is supported (should be, since it was the 1st one) - const size_t numBones = std::max( 1, baseSubMesh->blendIndexToBoneIndexMap.size() ); - - // mRowLength can only be 2 or 3 - static_assert(3 * OGRE_MAX_NUM_BONES < c_maxTexWidthHW, "Too many bones for VTF"); - const size_t maxUsableWidth = c_maxTexWidthHW - (c_maxTexWidthHW % (numBones * mRowLength)); - - //See InstanceBatchHW::calculateMaxNumInstances for the 65535 - retVal = std::min( 65535, maxUsableWidth * c_maxTexHeightHW / mRowLength / numBones ); - - if( flags & IM_VTFBESTFIT ) - { - size_t numUsedSkeletons = mInstancesPerBatch; - if (flags & IM_VTFBONEMATRIXLOOKUP) - numUsedSkeletons = std::min(getMaxLookupTableInstances(), numUsedSkeletons); - const size_t instancesPerBatch = std::min( retVal, numUsedSkeletons ); - //Do the same as in createVertexTexture(), but changing c_maxTexWidthHW for maxUsableWidth - const size_t numWorldMatrices = instancesPerBatch * numBones; - - size_t texWidth = std::min( numWorldMatrices * mRowLength, maxUsableWidth ); - size_t texHeight = numWorldMatrices * mRowLength / maxUsableWidth; - - const size_t remainder = (numWorldMatrices * mRowLength) % maxUsableWidth; - - if( remainder && texHeight > 0 ) - retVal = static_cast(texWidth * texHeight / (float)mRowLength / (float)(numBones)); - } - } - - return retVal; - } - //----------------------------------------------------------------------- - size_t InstanceBatchHW_VTF::updateVertexTexture( Camera *currentCamera ) - { - size_t renderedInstances = 0; - bool useMatrixLookup = useBoneMatrixLookup(); - if (useMatrixLookup) - { - //if we are using bone matrix look up we have to update the instance buffer for the - //vertex texture to be relevant - - //also note that in this case the number of instances to render comes directly from the - //updateInstanceDataBuffer() function, not from this function. - renderedInstances = updateInstanceDataBuffer(false, currentCamera); - } - - - mDirtyAnimation = false; - - //Now lock the texture and copy the 4x3 matrices! - HardwareBufferLockGuard matTexLock(mMatrixTexture->getBuffer(), HardwareBuffer::HBL_DISCARD); - const PixelBox &pixelBox = mMatrixTexture->getBuffer()->getCurrentLock(); - - float *pSource = reinterpret_cast(pixelBox.data); - - InstancedEntityVec::const_iterator itor = mInstancedEntities.begin(); - - std::vector writtenPositions(getMaxLookupTableInstances(), false); - - size_t floatPerEntity = mMatricesPerInstance * mRowLength * 4; - size_t entitiesPerPadding = (size_t)(mMaxFloatsPerLine / floatPerEntity); - - size_t instanceCount = mInstancedEntities.size(); - size_t updatedInstances = 0; - - Matrix3x4f* transforms = NULL; - //If using dual quaternions, write 3x4 matrices to a temporary buffer, then convert to dual quaternions - if(mUseBoneDualQuaternions) - { - transforms = (Matrix3x4f*)mTempTransformsArray3x4; - } - - for(size_t i = 0 ; i < instanceCount ; ++i) - { - InstancedEntity* entity = mInstancedEntities[i]; - size_t textureLookupPosition = updatedInstances; - if (useMatrixLookup) - { - textureLookupPosition = entity->mTransformLookupNumber; - } - //Check that we are not using a lookup matrix or that we have not already written - //The bone data - if (((!useMatrixLookup) || !writtenPositions[entity->mTransformLookupNumber]) && - //Cull on an individual basis, the less entities are visible, the less instances we draw. - //No need to use null matrices at all! - (entity->findVisible( currentCamera ))) - { - float* pDest = pSource + floatPerEntity * textureLookupPosition + - (size_t)(textureLookupPosition / entitiesPerPadding) * mWidthFloatsPadding; - - if(!mUseBoneDualQuaternions) - { - transforms = (Matrix3x4f*)pDest; - } - - if( mMeshReference->hasSkeleton() ) - mDirtyAnimation |= entity->_updateAnimation(); - - size_t floatsWritten = entity->getTransforms3x4( transforms ); - - if( !useMatrixLookup && mManager->getCameraRelativeRendering() ) - makeMatrixCameraRelative3x4( transforms, floatsWritten / 12 ); - - if(mUseBoneDualQuaternions) - { - convert3x4MatricesToDualQuaternions(transforms, floatsWritten / 12, pDest); - } - - if (useMatrixLookup) - { - writtenPositions[entity->mTransformLookupNumber] = true; - } - else - { - ++updatedInstances; - } - } - - ++itor; - } - - if (!useMatrixLookup) - { - renderedInstances = updatedInstances; - } - - return renderedInstances; - } - //----------------------------------------------------------------------- - void InstanceBatchHW_VTF::_boundsDirty(void) - { - //Don't update if we're static, but still mark we're dirty - if( !mBoundsDirty && !mKeepStatic && mCreator) - mCreator->_addDirtyBatch( this ); - mBoundsDirty = true; - } - //----------------------------------------------------------------------- - void InstanceBatchHW_VTF::setStaticAndUpdate( bool bStatic ) - { - //We were dirty but didn't update bounds. Do it now. - if( mKeepStatic && mBoundsDirty ) - mCreator->_addDirtyBatch( this ); - - mKeepStatic = bStatic; - if( mKeepStatic ) - { - //One final update, since there will be none from now on - //(except further calls to this function). Pass NULL because - //we want to include only those who were added to the scene - //but we don't want to perform culling - mRenderOperation.numberOfInstances = updateVertexTexture( 0 ); - } - } - //----------------------------------------------------------------------- - void InstanceBatchHW_VTF::_updateRenderQueue( RenderQueue* queue ) - { - if( !mKeepStatic ) - { - //Completely override base functionality, since we don't cull on an "all-or-nothing" basis - if( (mRenderOperation.numberOfInstances = updateVertexTexture( mCurrentCamera )) ) - queue->addRenderable( this, mRenderQueueID, mRenderQueuePriority ); - } - else - { - OgreAssert(!mManager->getCameraRelativeRendering(), - "Camera-relative rendering is incompatible with Instancing's static batches. " - "Disable at least one of them"); - - //Don't update when we're static - if( mRenderOperation.numberOfInstances ) - queue->addRenderable( this, mRenderQueueID, mRenderQueuePriority ); - } - } -} diff --git a/OgreMain/src/OgreInstanceBatchShader.cpp b/OgreMain/src/OgreInstanceBatchShader.cpp deleted file mode 100644 index b4dd920e1f1..00000000000 --- a/OgreMain/src/OgreInstanceBatchShader.cpp +++ /dev/null @@ -1,323 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreInstanceBatchShader.h" -#include "OgreRenderOperation.h" -#include "OgreInstancedEntity.h" - -namespace Ogre -{ - InstanceBatchShader::InstanceBatchShader( InstanceManager *creator, MeshPtr &meshReference, - const MaterialPtr &material, size_t instancesPerBatch, - const Mesh::IndexMap *indexToBoneMap, const String &batchName ) : - InstanceBatch( creator, meshReference, material, instancesPerBatch, - indexToBoneMap, batchName ), - mNumWorldMatrices( instancesPerBatch ) - { - } - - //----------------------------------------------------------------------- - size_t InstanceBatchShader::calculateMaxNumInstances( const SubMesh *baseSubMesh, uint16 flags ) const - { - const size_t numBones = std::max( 1, baseSubMesh->blendIndexToBoneIndexMap.size() ); - - mMaterial->load(); - Technique *technique = mMaterial->getBestTechnique(); - if( technique ) - { - GpuProgramParametersSharedPtr vertexParam = technique->getPass(0)->getVertexProgramParameters(); - for(auto& it : vertexParam->getConstantDefinitions().map) - { - const GpuConstantDefinition &constDef = it.second; - if(((constDef.constType == GCT_MATRIX_3X4 || - constDef.constType == GCT_MATRIX_4X3 || //OGL GLSL bitches without this - constDef.constType == GCT_MATRIX_2X4 || - constDef.constType == GCT_FLOAT4) //OGL GLSL bitches without this - && constDef.isFloat()) || - ((constDef.constType == GCT_MATRIX_DOUBLE_3X4 || - constDef.constType == GCT_MATRIX_DOUBLE_4X3 || //OGL GLSL bitches without this - constDef.constType == GCT_MATRIX_DOUBLE_2X4 || - constDef.constType == GCT_DOUBLE4) //OGL GLSL bitches without this - && constDef.isDouble()) - ) - { - const GpuProgramParameters::AutoConstantEntry *entry = - vertexParam->_findRawAutoConstantEntryFloat( constDef.physicalIndex ); - if( entry && (entry->paramType == GpuProgramParameters::ACT_WORLD_MATRIX_ARRAY_3x4 || entry->paramType == GpuProgramParameters::ACT_WORLD_DUALQUATERNION_ARRAY_2x4)) - { - //Material is correctly done! - size_t arraySize = constDef.arraySize; - - //Deal with GL "hacky" way of doing 4x3 matrices - if(entry->paramType == GpuProgramParameters::ACT_WORLD_MATRIX_ARRAY_3x4 && constDef.constType == GCT_FLOAT4) - arraySize /= 3; - else if(entry->paramType == GpuProgramParameters::ACT_WORLD_DUALQUATERNION_ARRAY_2x4 && constDef.constType == GCT_FLOAT4) - arraySize /= 2; - - //Check the num of arrays - size_t retVal = arraySize / numBones; - - if( flags & IM_USE16BIT ) - { - if( baseSubMesh->vertexData->vertexCount * retVal > 0xFFFF ) - retVal = 0xFFFF / baseSubMesh->vertexData->vertexCount; - } - - if((retVal < 3 && entry->paramType == GpuProgramParameters::ACT_WORLD_MATRIX_ARRAY_3x4) || - (retVal < 2 && entry->paramType == GpuProgramParameters::ACT_WORLD_DUALQUATERNION_ARRAY_2x4)) - { - LogManager::getSingleton().logWarning( "InstanceBatchShader: Mesh '" + - mMeshReference->getName() + "' using material '" + - mMaterial->getName() + "'. The amount of possible " - "instances per batch is very low. Performance benefits will " - "be minimal, if any. It might be even slower!"); - } - - return retVal; - } - } - } - - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Material '" + mMaterial->getName() + "' does not support hardware skinning"); - } - - //Reaching here the material is just unsupported. - - return 0; - } - //----------------------------------------------------------------------- - void InstanceBatchShader::buildFrom( const SubMesh *baseSubMesh, const RenderOperation &renderOperation ) - { - if( mMeshReference->hasSkeleton() && mMeshReference->getSkeleton() ) - mNumWorldMatrices = mInstancesPerBatch * baseSubMesh->blendIndexToBoneIndexMap.size(); - InstanceBatch::buildFrom( baseSubMesh, renderOperation ); - } - //----------------------------------------------------------------------- - void InstanceBatchShader::setupVertices( const SubMesh* baseSubMesh ) - { - mRenderOperation.vertexData = OGRE_NEW VertexData(); - mRemoveOwnVertexData = true; //Raise flag to remove our own vertex data in the end (not always needed) - - VertexData *thisVertexData = mRenderOperation.vertexData; - VertexData *baseVertexData = baseSubMesh->vertexData; - - thisVertexData->vertexStart = 0; - thisVertexData->vertexCount = baseVertexData->vertexCount * mInstancesPerBatch; - - HardwareBufferManager::getSingleton().destroyVertexDeclaration( thisVertexData->vertexDeclaration ); - thisVertexData->vertexDeclaration = baseVertexData->vertexDeclaration->clone(); - - if( mMeshReference->hasSkeleton() && mMeshReference->getSkeleton() ) - { - //Building hw skinned batches follow a different path - setupHardwareSkinned( baseSubMesh, thisVertexData, baseVertexData ); - return; - } - - //TODO: Can't we, instead of using another source, put the index ID in the same source? - thisVertexData->vertexDeclaration->addElement( - thisVertexData->vertexDeclaration->getMaxSource() + 1, 0, - VET_UBYTE4, VES_BLEND_INDICES ); - - - for( uint16 i=0; ivertexDeclaration->getMaxSource(); ++i ) - { - //Create our own vertex buffer - HardwareVertexBufferSharedPtr vertexBuffer = - HardwareBufferManager::getSingleton().createVertexBuffer( - thisVertexData->vertexDeclaration->getVertexSize(i), - thisVertexData->vertexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY ); - thisVertexData->vertexBufferBinding->setBinding( i, vertexBuffer ); - - //Grab the base submesh data - HardwareVertexBufferSharedPtr baseVertexBuffer = - baseVertexData->vertexBufferBinding->getBuffer(i); - - HardwareBufferLockGuard thisLock(vertexBuffer, HardwareBuffer::HBL_DISCARD); - HardwareBufferLockGuard baseLock(baseVertexBuffer, HardwareBuffer::HBL_READ_ONLY); - char* thisBuf = static_cast(thisLock.pData); - char* baseBuf = static_cast(baseLock.pData); - - //Copy and repeat - for( size_t j=0; jvertexCount * - baseVertexData->vertexDeclaration->getVertexSize(i); - memcpy( thisBuf + j * sizeOfBuffer, baseBuf, sizeOfBuffer ); - } - } - - { - //Now create the vertices "index ID" to individualize each instance - const unsigned short lastSource = thisVertexData->vertexDeclaration->getMaxSource(); - HardwareVertexBufferSharedPtr vertexBuffer = - HardwareBufferManager::getSingleton().createVertexBuffer( - thisVertexData->vertexDeclaration->getVertexSize( lastSource ), - thisVertexData->vertexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY ); - thisVertexData->vertexBufferBinding->setBinding( lastSource, vertexBuffer ); - - HardwareBufferLockGuard thisLock(vertexBuffer, HardwareBuffer::HBL_DISCARD); - char* thisBuf = static_cast(thisLock.pData); - for( uint8 j=0; jvertexCount; ++k ) - { - *thisBuf++ = j; - *thisBuf++ = j; - *thisBuf++ = j; - *thisBuf++ = j; - } - } - - } - } - //----------------------------------------------------------------------- - void InstanceBatchShader::setupIndices( const SubMesh* baseSubMesh ) - { - mRenderOperation.indexData = OGRE_NEW IndexData(); - mRemoveOwnIndexData = true; //Raise flag to remove our own index data in the end (not always needed) - - IndexData *thisIndexData = mRenderOperation.indexData; - IndexData *baseIndexData = baseSubMesh->indexData; - - thisIndexData->indexStart = 0; - thisIndexData->indexCount = baseIndexData->indexCount * mInstancesPerBatch; - - //TODO: Check numVertices is below max supported by GPU - HardwareIndexBuffer::IndexType indexType = HardwareIndexBuffer::IT_16BIT; - if( mRenderOperation.vertexData->vertexCount > 65535 ) - indexType = HardwareIndexBuffer::IT_32BIT; - thisIndexData->indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( - indexType, thisIndexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY ); - - HardwareBufferLockGuard thisLock(thisIndexData->indexBuffer, HardwareBuffer::HBL_DISCARD); - HardwareBufferLockGuard baseLock(baseIndexData->indexBuffer, HardwareBuffer::HBL_READ_ONLY); - uint16 *thisBuf16 = static_cast(thisLock.pData); - uint32 *thisBuf32 = static_cast(thisLock.pData); - bool baseIndex16bit = baseIndexData->indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT; - - for( size_t i=0; ivertexCount / mInstancesPerBatch; - - const uint16 *initBuf16 = static_cast(baseLock.pData); - const uint32 *initBuf32 = static_cast(baseLock.pData); - - for( size_t j=0; jindexCount; ++j ) - { - uint32 originalVal = baseIndex16bit ? *initBuf16++ : *initBuf32++; - - if( indexType == HardwareIndexBuffer::IT_16BIT ) - *thisBuf16++ = static_cast(originalVal + vertexOffset); - else - *thisBuf32++ = static_cast(originalVal + vertexOffset); - } - } - } - //----------------------------------------------------------------------- - void InstanceBatchShader::setupHardwareSkinned( const SubMesh* baseSubMesh, VertexData *thisVertexData, - VertexData *baseVertexData ) - { - const uint8 numBones = uint8(baseSubMesh->blendIndexToBoneIndexMap.size()); - mNumWorldMatrices = mInstancesPerBatch * numBones; - - for( uint16 i=0; i<=thisVertexData->vertexDeclaration->getMaxSource(); ++i ) - { - //Create our own vertex buffer - HardwareVertexBufferSharedPtr vertexBuffer = - HardwareBufferManager::getSingleton().createVertexBuffer( - thisVertexData->vertexDeclaration->getVertexSize(i), - thisVertexData->vertexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY ); - thisVertexData->vertexBufferBinding->setBinding( i, vertexBuffer ); - - VertexDeclaration::VertexElementList veList = - thisVertexData->vertexDeclaration->findElementsBySource(i); - - //Grab the base submesh data - HardwareVertexBufferSharedPtr baseVertexBuffer = - baseVertexData->vertexBufferBinding->getBuffer(i); - - HardwareBufferLockGuard thisVertexLock(vertexBuffer, HardwareBuffer::HBL_DISCARD); - HardwareBufferLockGuard baseVertexLock(baseVertexBuffer, HardwareBuffer::HBL_READ_ONLY); - char* thisBuf = static_cast(thisVertexLock.pData); - char* baseBuf = static_cast(baseVertexLock.pData); - char *startBuf = baseBuf; - - //Copy and repeat - for (uint8 j = 0; j < uint8(mInstancesPerBatch); ++j) - { - //Repeat source - baseBuf = startBuf; - - for (size_t k = 0; k < baseVertexData->vertexCount; ++k) - { - for (auto& vl : veList) - { - switch (vl.getSemantic()) - { - case VES_BLEND_INDICES: - *(thisBuf + vl.getOffset() + 0) = *(baseBuf + vl.getOffset() + 0) + j * numBones; - *(thisBuf + vl.getOffset() + 1) = *(baseBuf + vl.getOffset() + 1) + j * numBones; - *(thisBuf + vl.getOffset() + 2) = *(baseBuf + vl.getOffset() + 2) + j * numBones; - *(thisBuf + vl.getOffset() + 3) = *(baseBuf + vl.getOffset() + 3) + j * numBones; - break; - default: - memcpy( thisBuf + vl.getOffset(), baseBuf + vl.getOffset(), vl.getSize() ); - break; - } - } - thisBuf += baseVertexData->vertexDeclaration->getVertexSize(i); - baseBuf += baseVertexData->vertexDeclaration->getVertexSize(i); - } - } - } - } - //----------------------------------------------------------------------- - void InstanceBatchShader::getWorldTransforms( Matrix4* xform ) const - { - if (MeshManager::getBonesUseObjectSpace()) - { - *xform = Affine3::IDENTITY; - xform++; - } - - for (auto *e : mInstancedEntities) - { - xform += e->getTransforms(xform); - } - } - //----------------------------------------------------------------------- - unsigned short InstanceBatchShader::getNumWorldTransforms(void) const - { - return uint16(mNumWorldMatrices) + uint16(MeshManager::getBonesUseObjectSpace()); - } -} diff --git a/OgreMain/src/OgreInstanceBatchVTF.cpp b/OgreMain/src/OgreInstanceBatchVTF.cpp deleted file mode 100644 index be70bd51c21..00000000000 --- a/OgreMain/src/OgreInstanceBatchVTF.cpp +++ /dev/null @@ -1,716 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreInstanceBatchVTF.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreInstancedEntity.h" -#include "OgreMaterial.h" -#include "OgreDualQuaternion.h" - -namespace Ogre -{ - static const uint16 c_maxTexWidth = 4096; - static const uint16 c_maxTexHeight = 4096; - - BaseInstanceBatchVTF::BaseInstanceBatchVTF( InstanceManager *creator, MeshPtr &meshReference, - const MaterialPtr &material, size_t instancesPerBatch, - const Mesh::IndexMap *indexToBoneMap, const String &batchName) : - InstanceBatch( creator, meshReference, material, instancesPerBatch, - indexToBoneMap, batchName ), - mMatricesPerInstance(0), - mNumWorldMatrices( instancesPerBatch ), - mWidthFloatsPadding( 0 ), - mMaxFloatsPerLine( std::numeric_limits::max() ), - mRowLength(3), - mWeightCount(1), - mTempTransformsArray3x4(0), - mUseBoneMatrixLookup(false), - mMaxLookupTableInstances(16), - mUseBoneDualQuaternions(false), - mForceOneWeight(false), - mUseOneWeight(false) - { - cloneMaterial( mMaterial ); - } - - BaseInstanceBatchVTF::~BaseInstanceBatchVTF() - { - //Remove cloned caster materials (if any) - Material::Techniques::const_iterator it; - for(it = mMaterial->getTechniques().begin(); it != mMaterial->getTechniques().end(); ++it) - { - Technique *technique = *it; - - if (technique->getShadowCasterMaterial()) - MaterialManager::getSingleton().remove( technique->getShadowCasterMaterial() ); - } - - //Remove cloned material - MaterialManager::getSingleton().remove( mMaterial ); - - //Remove the VTF texture - if( mMatrixTexture ) - TextureManager::getSingleton().remove( mMatrixTexture ); - - delete[] mTempTransformsArray3x4; - } - - //----------------------------------------------------------------------- - void BaseInstanceBatchVTF::buildFrom( const SubMesh *baseSubMesh, const RenderOperation &renderOperation ) - { - if (useBoneMatrixLookup()) - { - //when using bone matrix lookup resource are not shared - // - //Future implementation: while the instance vertex buffer can't be shared - //The texture can be. - // - build(baseSubMesh); - } - else - { - createVertexTexture( baseSubMesh ); - InstanceBatch::buildFrom( baseSubMesh, renderOperation ); - } - } - //----------------------------------------------------------------------- - void BaseInstanceBatchVTF::cloneMaterial( const MaterialPtr &material ) - { - //Used to track down shadow casters, so the same material caster doesn't get cloned twice - typedef std::map MatMap; - MatMap clonedMaterials; - - //We need to clone the material so we can have different textures for each batch. - mMaterial = material->clone( mName + "/VTFMaterial" ); - - //Now do the same with the techniques which have a material shadow caster - Material::Techniques::const_iterator it; - for(it = material->getTechniques().begin(); it != material->getTechniques().end(); ++it) - { - Technique *technique = *it; - - if( technique->getShadowCasterMaterial() ) - { - const MaterialPtr &casterMat = technique->getShadowCasterMaterial(); - const String &casterName = casterMat->getName(); - - //Was this material already cloned? - MatMap::const_iterator itor = clonedMaterials.find(casterName); - - if( itor == clonedMaterials.end() ) - { - //No? Clone it and track it - MaterialPtr cloned = casterMat->clone( mName + "/VTFMaterialCaster" + - StringConverter::toString(clonedMaterials.size()) ); - technique->setShadowCasterMaterial( cloned ); - clonedMaterials[casterName] = cloned; - } - else - technique->setShadowCasterMaterial( itor->second ); //Reuse the previously cloned mat - } - } - } - //----------------------------------------------------------------------- - void BaseInstanceBatchVTF::retrieveBoneIdx( VertexData *baseVertexData, HWBoneIdxVec &outBoneIdx ) - { - const VertexElement *ve = baseVertexData->vertexDeclaration-> - findElementBySemantic( VES_BLEND_INDICES ); - const VertexElement *veWeights = baseVertexData->vertexDeclaration->findElementBySemantic( VES_BLEND_WEIGHTS ); - - HardwareVertexBufferSharedPtr buff = baseVertexData->vertexBufferBinding->getBuffer(ve->getSource()); - HardwareBufferLockGuard baseVertexLock(buff, HardwareBuffer::HBL_READ_ONLY); - char const *baseBuffer = static_cast(baseVertexLock.pData); - - for( size_t i=0; ivertexCount; ++i ) - { - float const *pWeights = reinterpret_cast(baseBuffer + veWeights->getOffset()); - - uint8 biggestWeightIdx = 0; - for( uint8 j=1; j< uint8(mWeightCount); ++j ) - { - biggestWeightIdx = pWeights[biggestWeightIdx] < pWeights[j] ? j : biggestWeightIdx; - } - - uint8 const *pIndex = reinterpret_cast(baseBuffer + ve->getOffset()); - outBoneIdx[i] = pIndex[biggestWeightIdx]; - - baseBuffer += baseVertexData->vertexDeclaration->getVertexSize(ve->getSource()); - } - } - - //----------------------------------------------------------------------- - void BaseInstanceBatchVTF::retrieveBoneIdxWithWeights(VertexData *baseVertexData, HWBoneIdxVec &outBoneIdx, HWBoneWgtVec &outBoneWgt) - { - const VertexElement *ve = baseVertexData->vertexDeclaration->findElementBySemantic( VES_BLEND_INDICES ); - const VertexElement *veWeights = baseVertexData->vertexDeclaration->findElementBySemantic( VES_BLEND_WEIGHTS ); - - HardwareVertexBufferSharedPtr buff = baseVertexData->vertexBufferBinding->getBuffer(ve->getSource()); - HardwareBufferLockGuard baseVertexLock(buff, HardwareBuffer::HBL_READ_ONLY); - char const *baseBuffer = static_cast(baseVertexLock.pData); - - for( size_t i=0; ivertexCount * mWeightCount; i += mWeightCount) - { - float const *pWeights = reinterpret_cast(baseBuffer + veWeights->getOffset()); - uint8 const *pIndex = reinterpret_cast(baseBuffer + ve->getOffset()); - - float weightMagnitude = 0.0f; - for( size_t j=0; j < mWeightCount; ++j ) - { - outBoneWgt[i+j] = pWeights[j]; - weightMagnitude += pWeights[j]; - outBoneIdx[i+j] = pIndex[j]; - } - - //Normalize the bone weights so they add to one - for(size_t j=0; j < mWeightCount; ++j) - { - outBoneWgt[i+j] /= weightMagnitude; - } - - baseBuffer += baseVertexData->vertexDeclaration->getVertexSize(ve->getSource()); - } - } - - //----------------------------------------------------------------------- - void BaseInstanceBatchVTF::setupMaterialToUseVTF( TextureType textureType, MaterialPtr &material ) const - { - Material::Techniques::const_iterator t; - for(t = material->getTechniques().begin(); t != material->getTechniques().end(); ++t) - for (auto *technique : material->getTechniques()) - { - for (auto *pass : technique->getPasses()) - { - for(auto *texUnit : pass->getTextureUnitStates()) - { - if( texUnit->getName() == "InstancingVTF" ) - { - texUnit->setTextureName( mMatrixTexture->getName(), textureType ); - texUnit->setTextureFiltering( TFO_NONE ); - } - } - } - - if( technique->getShadowCasterMaterial() ) - { - MaterialPtr matCaster = technique->getShadowCasterMaterial(); - setupMaterialToUseVTF(textureType, matCaster ); - } - } - } - //----------------------------------------------------------------------- - void BaseInstanceBatchVTF::createVertexTexture( const SubMesh* baseSubMesh ) - { - /* - TODO: Find a way to retrieve max texture resolution, - http://www.ogre3d.org/forums/viewtopic.php?t=38305 - - Currently assuming it's 4096x4096, which is a safe bet for any hardware with decent VTF*/ - - size_t uniqueAnimations = mInstancesPerBatch; - if (useBoneMatrixLookup()) - { - uniqueAnimations = std::min(getMaxLookupTableInstances(), uniqueAnimations); - } - mMatricesPerInstance = std::max( 1, baseSubMesh->blendIndexToBoneIndexMap.size() ); - - if(mUseBoneDualQuaternions && !mTempTransformsArray3x4) - { - mTempTransformsArray3x4 = new Matrix3x4f[mMatricesPerInstance]; - } - - mNumWorldMatrices = uniqueAnimations * mMatricesPerInstance; - - //Calculate the width & height required to hold all the matrices. Start by filling the width - //first (i.e. 4096x1 4096x2 4096x3, etc) - - size_t texWidth = std::min( mNumWorldMatrices * mRowLength, c_maxTexWidth ); - size_t maxUsableWidth = texWidth; - if( matricesTogetherPerRow() ) - { - //The technique requires all matrices from the same instance in the same row - //i.e. 4094 -> 4095 -> skip 4096 -> 0 (next row) contains data from a new instance - mWidthFloatsPadding = texWidth % (mMatricesPerInstance * mRowLength); - - if( mWidthFloatsPadding ) - { - mMaxFloatsPerLine = texWidth - mWidthFloatsPadding; - - maxUsableWidth = mMaxFloatsPerLine; - - //Values are in pixels, convert them to floats (1 pixel = 4 floats) - mWidthFloatsPadding *= 4; - mMaxFloatsPerLine *= 4; - } - } - - size_t texHeight = mNumWorldMatrices * mRowLength / maxUsableWidth; - - if( (mNumWorldMatrices * mRowLength) % maxUsableWidth ) - texHeight += 1; - - //Don't use 1D textures, as OGL goes crazy because the shader should be calling texture1D()... - TextureType texType = TEX_TYPE_2D; - - mMatrixTexture = TextureManager::getSingleton().createManual( - mName + "/VTF", mMeshReference->getGroup(), texType, - (uint)texWidth, (uint)texHeight, - 0, PF_FLOAT32_RGBA, TU_DYNAMIC_WRITE_ONLY_DISCARDABLE ); - - OgreAssert(mMatrixTexture->getFormat() == PF_FLOAT32_RGBA, "float texture support required"); - //Set our cloned material to use this custom texture! - setupMaterialToUseVTF( texType, mMaterial ); - } - - //----------------------------------------------------------------------- - size_t BaseInstanceBatchVTF::convert3x4MatricesToDualQuaternions(Matrix3x4f* matrices, size_t numOfMatrices, float* outDualQuaternions) - { - DualQuaternion dQuat; - size_t floatsWritten = 0; - - for (size_t m = 0; m < numOfMatrices; ++m) - { - dQuat.fromTransformationMatrix(Affine3(matrices[m][0])); - - //Copy the 2x4 matrix - for(int i = 0; i < 8; ++i) - { - *outDualQuaternions++ = static_cast( dQuat[i] ); - ++floatsWritten; - } - } - - return floatsWritten; - } - - //----------------------------------------------------------------------- - void BaseInstanceBatchVTF::updateVertexTexture(void) - { - //Now lock the texture and copy the 4x3 matrices! - HardwareBufferLockGuard matTexLock(mMatrixTexture->getBuffer(), HardwareBuffer::HBL_DISCARD); - const PixelBox &pixelBox = mMatrixTexture->getBuffer()->getCurrentLock(); - - float *pDest = reinterpret_cast(pixelBox.data); - - InstancedEntityVec::const_iterator itor = mInstancedEntities.begin(); - InstancedEntityVec::const_iterator end = mInstancedEntities.end(); - - Matrix3x4f* transforms; - - //If using dual quaternion skinning, write the transforms to a temporary buffer, - //then convert to dual quaternions, then later write to the pixel buffer - //Otherwise simply write the transforms to the pixel buffer directly - if(mUseBoneDualQuaternions) - { - transforms = mTempTransformsArray3x4; - } - else - { - transforms = (Matrix3x4f*)pDest; - } - - - while( itor != end ) - { - size_t floatsWritten = (*itor)->getTransforms3x4( transforms ); - - if( mManager->getCameraRelativeRendering() ) - makeMatrixCameraRelative3x4( transforms, floatsWritten / 12 ); - - if(mUseBoneDualQuaternions) - { - floatsWritten = convert3x4MatricesToDualQuaternions(transforms, floatsWritten / 12, pDest); - pDest += floatsWritten; - } - else - { - transforms += floatsWritten / 12; - } - - ++itor; - } - } - /** update the lookup numbers for entities with shared transforms */ - void BaseInstanceBatchVTF::updateSharedLookupIndexes() - { - if (mTransformSharingDirty) - { - if (useBoneMatrixLookup()) - { - //In each entity update the "transform lookup number" so that: - // 1. All entities sharing the same transformation will share the same unique number - // 2. "transform lookup number" will be numbered from 0 up to getMaxLookupTableInstances - uint16 lookupCounter = 0; - typedef std::map MapTransformId; - MapTransformId transformToId; - InstancedEntityVec::const_iterator itEnt = mInstancedEntities.begin(), - itEntEnd = mInstancedEntities.end(); - for(;itEnt != itEntEnd ; ++itEnt) - { - if ((*itEnt)->isInScene()) - { - Affine3* transformUniqueId = (*itEnt)->mBoneMatrices; - MapTransformId::iterator itLu = transformToId.find(transformUniqueId); - if (itLu == transformToId.end()) - { - itLu = transformToId.insert(std::make_pair(transformUniqueId,lookupCounter)).first; - ++lookupCounter; - } - (*itEnt)->setTransformLookupNumber(itLu->second); - } - else - { - (*itEnt)->setTransformLookupNumber(0); - } - } - - if (lookupCounter > getMaxLookupTableInstances()) - { - OGRE_EXCEPT(Exception::ERR_INVALID_STATE,"Number of unique bone matrix states exceeds current limitation.","BaseInstanceBatchVTF::updateSharedLookupIndexes()"); - } - } - - mTransformSharingDirty = false; - } - } - - //----------------------------------------------------------------------- - InstancedEntity* BaseInstanceBatchVTF::generateInstancedEntity(size_t num) - { - InstancedEntity* sharedTransformEntity = NULL; - if ((useBoneMatrixLookup()) && (num >= getMaxLookupTableInstances())) - { - sharedTransformEntity = mInstancedEntities[num % getMaxLookupTableInstances()]; - if (sharedTransformEntity->mSharedTransformEntity) - { - sharedTransformEntity = sharedTransformEntity->mSharedTransformEntity; - } - } - - return OGRE_NEW InstancedEntity(this, static_cast(num), sharedTransformEntity); - } - - - //----------------------------------------------------------------------- - void BaseInstanceBatchVTF::getWorldTransforms( Matrix4* xform ) const - { - *xform = Matrix4::IDENTITY; - } - //----------------------------------------------------------------------- - void BaseInstanceBatchVTF::_updateRenderQueue(RenderQueue* queue) - { - InstanceBatch::_updateRenderQueue( queue ); - - if( mBoundsUpdated || mDirtyAnimation || mManager->getCameraRelativeRendering() ) - updateVertexTexture(); - - mBoundsUpdated = false; - } - //----------------------------------------------------------------------- - // InstanceBatchVTF - //----------------------------------------------------------------------- - InstanceBatchVTF::InstanceBatchVTF( - InstanceManager *creator, MeshPtr &meshReference, - const MaterialPtr &material, size_t instancesPerBatch, - const Mesh::IndexMap *indexToBoneMap, const String &batchName ) - : BaseInstanceBatchVTF (creator, meshReference, material, - instancesPerBatch, indexToBoneMap, batchName) - { - - } - //----------------------------------------------------------------------- - InstanceBatchVTF::~InstanceBatchVTF() - { - } - //----------------------------------------------------------------------- - void InstanceBatchVTF::setupVertices( const SubMesh* baseSubMesh ) - { - mRenderOperation.vertexData = OGRE_NEW VertexData(); - mRemoveOwnVertexData = true; //Raise flag to remove our own vertex data in the end (not always needed) - - VertexData *thisVertexData = mRenderOperation.vertexData; - VertexData *baseVertexData = baseSubMesh->vertexData; - - thisVertexData->vertexStart = 0; - thisVertexData->vertexCount = baseVertexData->vertexCount * mInstancesPerBatch; - - HardwareBufferManager::getSingleton().destroyVertexDeclaration( thisVertexData->vertexDeclaration ); - thisVertexData->vertexDeclaration = baseVertexData->vertexDeclaration->clone(); - - HWBoneIdxVec hwBoneIdx; - HWBoneWgtVec hwBoneWgt; - - //Blend weights may not be present because HW_VTF does not require to be skeletally animated - const VertexElement *veWeights = baseVertexData->vertexDeclaration-> - findElementBySemantic( VES_BLEND_WEIGHTS ); - if( veWeights ) - { - //One weight is recommended for VTF - mWeightCount = (forceOneWeight() || useOneWeight()) ? - 1 : veWeights->getSize() / sizeof(float); - } - else - { - mWeightCount = 1; - } - - hwBoneIdx.resize( baseVertexData->vertexCount * mWeightCount, 0 ); - - if( mMeshReference->hasSkeleton() && mMeshReference->getSkeleton() ) - { - if(mWeightCount > 1) - { - hwBoneWgt.resize( baseVertexData->vertexCount * mWeightCount, 0 ); - retrieveBoneIdxWithWeights(baseVertexData, hwBoneIdx, hwBoneWgt); - } - else - { - retrieveBoneIdx( baseVertexData, hwBoneIdx ); - thisVertexData->vertexDeclaration->removeElement( VES_BLEND_INDICES ); - thisVertexData->vertexDeclaration->removeElement( VES_BLEND_WEIGHTS ); - - thisVertexData->vertexDeclaration->closeGapsInSource(); - } - - } - - for( unsigned short i=0; ivertexDeclaration->getMaxSource()+1; ++i ) - { - //Create our own vertex buffer - HardwareVertexBufferSharedPtr vertexBuffer = - HardwareBufferManager::getSingleton().createVertexBuffer( - thisVertexData->vertexDeclaration->getVertexSize(i), - thisVertexData->vertexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY ); - thisVertexData->vertexBufferBinding->setBinding( i, vertexBuffer ); - - //Grab the base submesh data - HardwareVertexBufferSharedPtr baseVertexBuffer = - baseVertexData->vertexBufferBinding->getBuffer(i); - - HardwareBufferLockGuard thisLock(vertexBuffer, HardwareBuffer::HBL_DISCARD); - HardwareBufferLockGuard baseLock(baseVertexBuffer, HardwareBuffer::HBL_READ_ONLY); - char* thisBuf = static_cast(thisLock.pData); - char* baseBuf = static_cast(baseLock.pData); - - //Copy and repeat - for( size_t j=0; jvertexCount * - baseVertexData->vertexDeclaration->getVertexSize(i); - memcpy( thisBuf + j * sizeOfBuffer, baseBuf, sizeOfBuffer ); - } - } - - createVertexTexture( baseSubMesh ); - createVertexSemantics( thisVertexData, baseVertexData, hwBoneIdx, hwBoneWgt); - } - //----------------------------------------------------------------------- - void InstanceBatchVTF::setupIndices( const SubMesh* baseSubMesh ) - { - mRenderOperation.indexData = OGRE_NEW IndexData(); - mRemoveOwnIndexData = true; //Raise flag to remove our own index data in the end (not always needed) - - IndexData *thisIndexData = mRenderOperation.indexData; - IndexData *baseIndexData = baseSubMesh->indexData; - - thisIndexData->indexStart = 0; - thisIndexData->indexCount = baseIndexData->indexCount * mInstancesPerBatch; - - //TODO: Check numVertices is below max supported by GPU - HardwareIndexBuffer::IndexType indexType = HardwareIndexBuffer::IT_16BIT; - if( mRenderOperation.vertexData->vertexCount > 65535 ) - indexType = HardwareIndexBuffer::IT_32BIT; - thisIndexData->indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( - indexType, thisIndexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY ); - - HardwareBufferLockGuard thisLock(thisIndexData->indexBuffer, HardwareBuffer::HBL_DISCARD); - HardwareBufferLockGuard baseLock(baseIndexData->indexBuffer, HardwareBuffer::HBL_READ_ONLY); - uint16 *thisBuf16 = static_cast(thisLock.pData); - uint32 *thisBuf32 = static_cast(thisLock.pData); - bool baseIndex16bit = baseIndexData->indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT; - - for( size_t i=0; ivertexCount / mInstancesPerBatch; - - const uint16 *initBuf16 = static_cast(baseLock.pData); - const uint32 *initBuf32 = static_cast(baseLock.pData); - - for( size_t j=0; jindexCount; ++j ) - { - uint32 originalVal = baseIndex16bit ? *initBuf16++ : *initBuf32++; - - if( indexType == HardwareIndexBuffer::IT_16BIT ) - *thisBuf16++ = static_cast(originalVal + vertexOffset); - else - *thisBuf32++ = static_cast(originalVal + vertexOffset); - } - } - } - //----------------------------------------------------------------------- - void InstanceBatchVTF::createVertexSemantics( - VertexData *thisVertexData, VertexData *baseVertexData, const HWBoneIdxVec &hwBoneIdx, const HWBoneWgtVec &hwBoneWgt) - { - const size_t texWidth = mMatrixTexture->getWidth(); - const size_t texHeight = mMatrixTexture->getHeight(); - - //Calculate the texel offsets to correct them offline - //Akwardly enough, the offset is needed in OpenGL too - Vector2 texelOffsets; - //RenderSystem *renderSystem = Root::getSingleton().getRenderSystem(); - texelOffsets.x = /*renderSystem->getHorizontalTexelOffset()*/ -0.5f / (float)texWidth; - texelOffsets.y = /*renderSystem->getVerticalTexelOffset()*/ -0.5f / (float)texHeight; - - //Only one weight per vertex is supported. It would not only be complex, but prohibitively slow. - //Put them in a new buffer, since it's 32 bytes aligned :-) - const unsigned short newSource = thisVertexData->vertexDeclaration->getMaxSource() + 1; - size_t maxFloatsPerVector = 4; - size_t offset = 0; - - for(size_t i = 0; i < mWeightCount; i += maxFloatsPerVector / mRowLength) - { - offset += thisVertexData->vertexDeclaration->addElement( newSource, offset, VET_FLOAT4, VES_TEXTURE_COORDINATES, - thisVertexData->vertexDeclaration-> - getNextFreeTextureCoordinate() ).getSize(); - offset += thisVertexData->vertexDeclaration->addElement( newSource, offset, VET_FLOAT4, VES_TEXTURE_COORDINATES, - thisVertexData->vertexDeclaration-> - getNextFreeTextureCoordinate() ).getSize(); - } - - //Add the weights (supports up to four, which is Ogre's limit) - if(mWeightCount > 1) - { - thisVertexData->vertexDeclaration->addElement(newSource, offset, VET_FLOAT4, VES_BLEND_WEIGHTS, - thisVertexData->vertexDeclaration->getNextFreeTextureCoordinate() ).getSize(); - } - - //Create our own vertex buffer - HardwareVertexBufferSharedPtr vertexBuffer = - HardwareBufferManager::getSingleton().createVertexBuffer( - thisVertexData->vertexDeclaration->getVertexSize(newSource), - thisVertexData->vertexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY ); - thisVertexData->vertexBufferBinding->setBinding( newSource, vertexBuffer ); - - HardwareBufferLockGuard vertexLock(vertexBuffer, HardwareBuffer::HBL_DISCARD); - float *thisFloat = static_cast(vertexLock.pData); - - //Copy and repeat - for( size_t i=0; ivertexCount * mWeightCount; j += mWeightCount ) - { - size_t numberOfMatricesInLine = 0; - - for(size_t wgtIdx = 0; wgtIdx < mWeightCount; ++wgtIdx) - { - for( size_t k=0; k < mRowLength; ++k) - { - size_t instanceIdx = (hwBoneIdx[j+wgtIdx] + i * mMatricesPerInstance) * mRowLength + k; - //x - *thisFloat++ = ((instanceIdx % texWidth) / (float)texWidth) - (float)texelOffsets.x; - //y - *thisFloat++ = ((instanceIdx / texWidth) / (float)texHeight) - (float)texelOffsets.y; - } - - ++numberOfMatricesInLine; - - //If another matrix can't be fit, we're on another line, or if this is the last weight - if((numberOfMatricesInLine + 1) * mRowLength > maxFloatsPerVector || (wgtIdx+1) == mWeightCount) - { - //Place zeroes in the remaining coordinates - for ( size_t k=mRowLength * numberOfMatricesInLine; k < maxFloatsPerVector; ++k) - { - *thisFloat++ = 0.0f; - *thisFloat++ = 0.0f; - } - - numberOfMatricesInLine = 0; - } - } - - //Don't need to write weights if there is only one - if(mWeightCount > 1) - { - //Write the weights - for(size_t wgtIdx = 0; wgtIdx < mWeightCount; ++wgtIdx) - { - *thisFloat++ = hwBoneWgt[j+wgtIdx]; - } - - //Fill the rest of the line with zeros - for(size_t wgtIdx = mWeightCount; wgtIdx < maxFloatsPerVector; ++wgtIdx) - { - *thisFloat++ = 0.0f; - } - } - } - } - } - //----------------------------------------------------------------------- - size_t InstanceBatchVTF::calculateMaxNumInstances( - const SubMesh *baseSubMesh, uint16 flags ) const - { - size_t retVal = 0; - - RenderSystem *renderSystem = Root::getSingleton().getRenderSystem(); - const RenderSystemCapabilities *capabilities = renderSystem->getCapabilities(); - - //VTF must be supported - if( capabilities->hasCapability( RSC_VERTEX_TEXTURE_FETCH ) ) - { - //TODO: Check PF_FLOAT32_RGBA is supported (should be, since it was the 1st one) - const size_t numBones = std::max( 1, baseSubMesh->blendIndexToBoneIndexMap.size() ); - retVal = c_maxTexWidth * c_maxTexHeight / mRowLength / numBones; - - if( flags & IM_USE16BIT ) - { - if( baseSubMesh->vertexData->vertexCount * retVal > 0xFFFF ) - retVal = 0xFFFF / baseSubMesh->vertexData->vertexCount; - } - - if( flags & IM_VTFBESTFIT ) - { - const size_t instancesPerBatch = std::min( retVal, mInstancesPerBatch ); - //Do the same as in createVertexTexture() - const size_t numWorldMatrices = instancesPerBatch * numBones; - - size_t texWidth = std::min( numWorldMatrices * mRowLength, c_maxTexWidth ); - size_t texHeight = numWorldMatrices * mRowLength / c_maxTexWidth; - - const size_t remainder = (numWorldMatrices * mRowLength) % c_maxTexWidth; - - if( remainder && texHeight > 0 ) - retVal = static_cast(texWidth * texHeight / (float)mRowLength / (float)(numBones)); - } - } - - return retVal; - - } -} diff --git a/OgreMain/src/OgreInstanceManager.cpp b/OgreMain/src/OgreInstanceManager.cpp deleted file mode 100644 index 9b13af6f1f9..00000000000 --- a/OgreMain/src/OgreInstanceManager.cpp +++ /dev/null @@ -1,627 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreInstanceManager.h" -#include "OgreInstanceBatchHW.h" -#include "OgreInstanceBatchHW_VTF.h" -#include "OgreInstanceBatchShader.h" -#include "OgreInstanceBatchVTF.h" - -namespace Ogre -{ - InstanceManager::InstanceManager( const String &customName, SceneManager *sceneManager, - const String &meshName, const String &groupName, - InstancingTechnique instancingTechnique, uint16 instancingFlags, - size_t instancesPerBatch, unsigned short subMeshIdx, bool useBoneMatrixLookup ) : - mName( customName ), - mIdCount( 0 ), - mInstancesPerBatch( instancesPerBatch ), - mInstancingTechnique( instancingTechnique ), - mInstancingFlags( instancingFlags ), - mSubMeshIdx( subMeshIdx ), - mSceneManager( sceneManager ), - mMaxLookupTableInstances(16), - mNumCustomParams( 0 ) - { - mMeshReference = MeshManager::getSingleton().load( meshName, groupName ); - - if(mMeshReference->sharedVertexData) - unshareVertices(mMeshReference); - - if( mMeshReference->hasSkeleton() && mMeshReference->getSkeleton() ) - mMeshReference->getSubMesh(mSubMeshIdx)->_compileBoneAssignments(); - } - - InstanceManager::~InstanceManager() - { - //Remove all batches from all materials we created - for (auto& i : mInstanceBatches) - { - for (auto *it : i.second) - OGRE_DELETE it; - } - } - //---------------------------------------------------------------------- - void InstanceManager::setInstancesPerBatch( size_t instancesPerBatch ) - { - OgreAssert(mInstanceBatches.empty(), "can only be changed before building the batch"); - mInstancesPerBatch = instancesPerBatch; - } - - //---------------------------------------------------------------------- - void InstanceManager::setMaxLookupTableInstances( size_t maxLookupTableInstances ) - { - OgreAssert(mInstanceBatches.empty(), "can only be changed before building the batch"); - mMaxLookupTableInstances = maxLookupTableInstances; - } - - //---------------------------------------------------------------------- - void InstanceManager::setNumCustomParams( unsigned char numCustomParams ) - { - OgreAssert(mInstanceBatches.empty(), "can only be changed before building the batch"); - mNumCustomParams = numCustomParams; - } - //---------------------------------------------------------------------- - size_t InstanceManager::getMaxOrBestNumInstancesPerBatch( const String &materialName, size_t suggestedSize, - uint16 flags ) - { - //Get the material - MaterialPtr mat = MaterialManager::getSingleton().getByName( materialName, - mMeshReference->getGroup() ); - InstanceBatch *batch = 0; - - //Base material couldn't be found - if( !mat ) - return 0; - - switch( mInstancingTechnique ) - { - case ShaderBased: - batch = OGRE_NEW InstanceBatchShader( this, mMeshReference, mat, suggestedSize, - 0, mName + "/TempBatch" ); - break; - case TextureVTF: - batch = OGRE_NEW InstanceBatchVTF( this, mMeshReference, mat, suggestedSize, - 0, mName + "/TempBatch" ); - static_cast(batch)->setBoneDualQuaternions((mInstancingFlags & IM_USEBONEDUALQUATERNIONS) != 0); - static_cast(batch)->setUseOneWeight((mInstancingFlags & IM_USEONEWEIGHT) != 0); - static_cast(batch)->setForceOneWeight((mInstancingFlags & IM_FORCEONEWEIGHT) != 0); - break; - case HWInstancingBasic: - batch = OGRE_NEW InstanceBatchHW( this, mMeshReference, mat, suggestedSize, - 0, mName + "/TempBatch" ); - break; - case HWInstancingVTF: - batch = OGRE_NEW InstanceBatchHW_VTF( this, mMeshReference, mat, suggestedSize, - 0, mName + "/TempBatch" ); - static_cast(batch)->setBoneMatrixLookup((mInstancingFlags & IM_VTFBONEMATRIXLOOKUP) != 0, mMaxLookupTableInstances); - static_cast(batch)->setBoneDualQuaternions((mInstancingFlags & IM_USEBONEDUALQUATERNIONS) != 0); - static_cast(batch)->setUseOneWeight((mInstancingFlags & IM_USEONEWEIGHT) != 0); - static_cast(batch)->setForceOneWeight((mInstancingFlags & IM_FORCEONEWEIGHT) != 0); - break; - default: - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, - "Unimplemented instancing technique: " + - StringConverter::toString(mInstancingTechnique), - "InstanceBatch::getMaxOrBestNumInstancesPerBatches()"); - } - - const size_t retVal = batch->calculateMaxNumInstances( mMeshReference->getSubMesh(mSubMeshIdx), - flags ); - - OGRE_DELETE batch; - - return retVal; - } - //---------------------------------------------------------------------- - InstancedEntity* InstanceManager::createInstancedEntity( const String &materialName ) - { - InstanceBatch *instanceBatch; - - if( mInstanceBatches.empty() || - (mInstanceBatches[materialName].size () == 0)) - instanceBatch = buildNewBatch( materialName, true ); - else - instanceBatch = getFreeBatch( materialName ); - - return instanceBatch->createInstancedEntity(); - } - //----------------------------------------------------------------------- - inline InstanceBatch* InstanceManager::getFreeBatch( const String &materialName ) - { - InstanceBatchVec &batchVec = mInstanceBatches[materialName]; - for (auto *b : batchVec) - { - if(!b->isBatchFull()) - return b; - } - - //None found, or they're all full - return buildNewBatch( materialName, false ); - } - //----------------------------------------------------------------------- - InstanceBatch* InstanceManager::buildNewBatch( const String &materialName, bool firstTime ) - { - //Get the bone to index map for the batches - Mesh::IndexMap &idxMap = mMeshReference->getSubMesh(mSubMeshIdx)->blendIndexToBoneIndexMap; - idxMap = idxMap.empty() ? mMeshReference->sharedBlendIndexToBoneIndexMap : idxMap; - - //Get the material - MaterialPtr mat = MaterialManager::getSingleton().getByName( materialName, - mMeshReference->getGroup() ); - - //Get the array of batches grouped by this material - InstanceBatchVec &materialInstanceBatch = mInstanceBatches[materialName]; - - InstanceBatch *batch = 0; - - switch( mInstancingTechnique ) - { - case ShaderBased: - batch = OGRE_NEW InstanceBatchShader( this, mMeshReference, mat, mInstancesPerBatch, - &idxMap, mName + "/InstanceBatch_" + - StringConverter::toString(mIdCount++) ); - break; - case TextureVTF: - batch = OGRE_NEW InstanceBatchVTF( this, mMeshReference, mat, mInstancesPerBatch, - &idxMap, mName + "/InstanceBatch_" + - StringConverter::toString(mIdCount++) ); - static_cast(batch)->setBoneDualQuaternions((mInstancingFlags & IM_USEBONEDUALQUATERNIONS) != 0); - static_cast(batch)->setUseOneWeight((mInstancingFlags & IM_USEONEWEIGHT) != 0); - static_cast(batch)->setForceOneWeight((mInstancingFlags & IM_FORCEONEWEIGHT) != 0); - break; - case HWInstancingBasic: - batch = OGRE_NEW InstanceBatchHW( this, mMeshReference, mat, mInstancesPerBatch, - &idxMap, mName + "/InstanceBatch_" + - StringConverter::toString(mIdCount++) ); - break; - case HWInstancingVTF: - batch = OGRE_NEW InstanceBatchHW_VTF( this, mMeshReference, mat, mInstancesPerBatch, - &idxMap, mName + "/InstanceBatch_" + - StringConverter::toString(mIdCount++) ); - static_cast(batch)->setBoneMatrixLookup((mInstancingFlags & IM_VTFBONEMATRIXLOOKUP) != 0, mMaxLookupTableInstances); - static_cast(batch)->setBoneDualQuaternions((mInstancingFlags & IM_USEBONEDUALQUATERNIONS) != 0); - static_cast(batch)->setUseOneWeight((mInstancingFlags & IM_USEONEWEIGHT) != 0); - static_cast(batch)->setForceOneWeight((mInstancingFlags & IM_FORCEONEWEIGHT) != 0); - break; - default: - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, - "Unimplemented instancing technique: " + - StringConverter::toString(mInstancingTechnique), - "InstanceBatch::buildNewBatch()"); - } - - batch->_notifyManager( mSceneManager ); - - - if( !firstTime ) - { - //TODO: Check different materials have the same mInstancesPerBatch upper limit - //otherwise we can't share - batch->buildFrom( mMeshReference->getSubMesh(mSubMeshIdx), mSharedRenderOperation ); - } - else - { - //Ensure we don't request more than we can - const size_t maxInstPerBatch = batch->calculateMaxNumInstances( mMeshReference-> - getSubMesh(mSubMeshIdx), mInstancingFlags ); - mInstancesPerBatch = std::min( maxInstPerBatch, mInstancesPerBatch ); - batch->_setInstancesPerBatch( mInstancesPerBatch ); - - OgreAssert(mInstancesPerBatch, "unsupported instancing technique"); - //TODO: Create a "merge" function that merges all submeshes into one big submesh - //instead of just sending submesh #0 - - //Get the RenderOperation to be shared with further instances. - mSharedRenderOperation = batch->build( mMeshReference->getSubMesh(mSubMeshIdx) ); - } - - const BatchSettings &batchSettings = mBatchSettings[materialName]; - batch->setCastShadows( batchSettings.setting[CAST_SHADOWS] ); - - //Batches need to be part of a scene node so that their renderable can be rendered - SceneNode *sceneNode = mSceneManager->getRootSceneNode()->createChildSceneNode(); - sceneNode->attachObject( batch ); - sceneNode->showBoundingBox( batchSettings.setting[SHOW_BOUNDINGBOX] ); - - materialInstanceBatch.push_back( batch ); - - return batch; - } - //----------------------------------------------------------------------- - void InstanceManager::cleanupEmptyBatches(void) - { - //Do this now to avoid any dangling pointer inside mDirtyBatches - _updateDirtyBatches(); - - InstanceBatchMap::iterator itor = mInstanceBatches.begin(); - InstanceBatchMap::iterator end = mInstanceBatches.end(); - - while( itor != end ) - { - InstanceBatchVec::iterator it = itor->second.begin(); - InstanceBatchVec::iterator en = itor->second.end(); - - while( it != en ) - { - if( (*it)->isBatchUnused() ) - { - OGRE_DELETE *it; - //Remove it from the list swapping with the last element and popping back - size_t idx = it - itor->second.begin(); - *it = itor->second.back(); - itor->second.pop_back(); - - //Restore invalidated iterators - it = itor->second.begin() + idx; - en = itor->second.end(); - } - else - ++it; - } - - ++itor; - } - - //By this point it may happen that all mInstanceBatches' objects are also empty - //however if we call mInstanceBatches.clear(), next time we'll create an InstancedObject - //we'll end up calling buildFirstTime() instead of buildNewBatch(), which is not the idea - //(takes more time and will leak the shared render operation) - } - //----------------------------------------------------------------------- - void InstanceManager::defragmentBatches( bool optimizeCull, - InstanceBatch::InstancedEntityVec &usedEntities, - InstanceBatch::CustomParamsVec &usedParams, - InstanceBatchVec &fragmentedBatches ) - { - InstanceBatchVec::iterator itor = fragmentedBatches.begin(); - InstanceBatchVec::iterator end = fragmentedBatches.end(); - - while( itor != end && !usedEntities.empty() ) - { - if( !(*itor)->isStatic() ) - (*itor)->_defragmentBatch( optimizeCull, usedEntities, usedParams ); - ++itor; - } - - InstanceBatchVec::iterator lastImportantBatch = itor; - - while( itor != end ) - { - if( !(*itor)->isStatic() ) - { - //If we get here, this means we hit remaining batches which will be unused. - //Destroy them - //Call this to avoid freeing InstancedEntities that were just reparented - (*itor)->_defragmentBatchDiscard(); - OGRE_DELETE *itor; - } - else - { - //This isn't a meaningless batch, move it forward so it doesn't get wipe - //when we resize the container (faster than removing element by element) - *lastImportantBatch++ = *itor; - } - - ++itor; - } - - //Remove remaining batches all at once from the vector - const size_t remainingBatches = end - lastImportantBatch; - fragmentedBatches.resize( fragmentedBatches.size() - remainingBatches ); - } - //----------------------------------------------------------------------- - void InstanceManager::defragmentBatches( bool optimizeCulling ) - { - //Do this now to avoid any dangling pointer inside mDirtyBatches - _updateDirtyBatches(); - - //Do this for every material - for (auto& b : mInstanceBatches) - { - InstanceBatch::InstancedEntityVec usedEntities; - InstanceBatch::CustomParamsVec usedParams; - usedEntities.reserve(b.second.size() * mInstancesPerBatch ); - - //Collect all Instanced Entities being used by _all_ batches from this material - for (auto *it : b.second) - { - //Don't collect instances from static batches, we assume they're correctly set - //Plus, we don't want to put InstancedEntities from non-static into static batches - if (!it->isStatic()) - it->getInstancedEntitiesInUse(usedEntities, usedParams); - } - - defragmentBatches(optimizeCulling, usedEntities, usedParams, b.second ); - } - } - //----------------------------------------------------------------------- - void InstanceManager::setSetting( BatchSettingId id, bool value, const String &materialName ) - { - assert( id < NUM_SETTINGS ); - - if( materialName == BLANKSTRING ) - { - //Setup all existing materials - for (auto& i : mInstanceBatches) - { - mBatchSettings[i.first].setting[id] = value; - applySettingToBatches( id, value, i.second ); - } - } - else - { - //Setup a given material - mBatchSettings[materialName].setting[id] = value; - - InstanceBatchMap::const_iterator itor = mInstanceBatches.find( materialName ); - //Don't crash or throw if the batch with that material hasn't been created yet - if( itor != mInstanceBatches.end() ) - applySettingToBatches( id, value, itor->second ); - } - } - //----------------------------------------------------------------------- - bool InstanceManager::getSetting( BatchSettingId id, const String &materialName ) const - { - assert( id < NUM_SETTINGS ); - - BatchSettingsMap::const_iterator itor = mBatchSettings.find( materialName ); - if( itor != mBatchSettings.end() ) - return itor->second.setting[id]; //Return current setting - - //Return default - return BatchSettings().setting[id]; - } - bool InstanceManager::hasSettings(const String& materialName) const - { - return mBatchSettings.find(materialName) != mBatchSettings.end(); - } - //----------------------------------------------------------------------- - void InstanceManager::applySettingToBatches( BatchSettingId id, bool value, - const InstanceBatchVec &container ) - { - for (auto *s : container) - { - switch(id) - { - case CAST_SHADOWS: - s->setCastShadows(value); - break; - case SHOW_BOUNDINGBOX: - s->getParentSceneNode()->showBoundingBox(value); - break; - default: - break; - } - } - } - //----------------------------------------------------------------------- - void InstanceManager::setBatchesAsStaticAndUpdate( bool bStatic ) - { - for (auto& b : mInstanceBatches) - { - for (auto *it : b.second) - { - it->setStaticAndUpdate(bStatic); - } - } - } - //----------------------------------------------------------------------- - void InstanceManager::_addDirtyBatch( InstanceBatch *dirtyBatch ) - { - if( mDirtyBatches.empty() ) - mSceneManager->_addDirtyInstanceManager( this ); - - mDirtyBatches.push_back( dirtyBatch ); - } - //----------------------------------------------------------------------- - void InstanceManager::_updateDirtyBatches(void) - { - for (auto *d : mDirtyBatches) - { - d->_updateBounds(); - } - mDirtyBatches.clear(); - } - //----------------------------------------------------------------------- - // Helper functions to unshare the vertices - //----------------------------------------------------------------------- - typedef std::map IndicesMap; - - template< typename TIndexType > - void collectUsedIndices(IndicesMap& indicesMap, IndexData* idxData) - { - HardwareBufferLockGuard indexLock(idxData->indexBuffer, - idxData->indexStart * sizeof(TIndexType), - idxData->indexCount * sizeof(TIndexType), - HardwareBuffer::HBL_READ_ONLY); - TIndexType *data = (TIndexType*)indexLock.pData; - - for (size_t i = 0; i < idxData->indexCount; i++) - { - TIndexType index = data[i]; - if (indicesMap.find(index) == indicesMap.end()) - { - //We need to guarantee that the size is read before an entry is added, hence these are on separate lines. - uint32 size = (uint32)(indicesMap.size()); - indicesMap[index] = size; - } - } - } - //----------------------------------------------------------------------- - template< typename TIndexType > - void copyIndexBuffer(IndexData* idxData, const IndicesMap& indicesMap, uint32 indexStart) - { - size_t start = std::max(indexStart, idxData->indexStart); - size_t count = idxData->indexCount - (start - idxData->indexStart); - - //We get errors if we try to lock a zero size buffer. - if (count == 0) { - return; - } - HardwareBufferLockGuard indexLock(idxData->indexBuffer, - start * sizeof(TIndexType), - count * sizeof(TIndexType), - HardwareBuffer::HBL_NORMAL); - TIndexType *data = (TIndexType*)indexLock.pData; - - for (size_t i = 0; i < count; i++) - { - //Access data and write on two separate lines, to avoid compiler confusion. - auto originalPos = data[i]; - auto indexEntry = indicesMap.find(originalPos); - data[i] = (TIndexType)(indexEntry->second); - } - } - //----------------------------------------------------------------------- - void InstanceManager::unshareVertices(const Ogre::MeshPtr &mesh) - { - // Retrieve data to copy bone assignments - const Mesh::VertexBoneAssignmentList& boneAssignments = mesh->getBoneAssignments(); - size_t curVertexOffset = 0; - - // Access shared vertices - VertexData* sharedVertexData = mesh->sharedVertexData; - - for (size_t subMeshIdx = 0; subMeshIdx < mesh->getNumSubMeshes(); subMeshIdx++) - { - SubMesh *subMesh = mesh->getSubMesh(subMeshIdx); - - IndexData *indexData = subMesh->indexData; - HardwareIndexBuffer::IndexType idxType = indexData->indexBuffer->getType(); - IndicesMap indicesMap; - if (idxType == HardwareIndexBuffer::IT_16BIT) { - collectUsedIndices(indicesMap, indexData); - } else { - collectUsedIndices(indicesMap, indexData); - } - - //Also collect indices for all LOD faces. - for (auto& lodIndex : subMesh->mLodFaceList) { - //Typically the LOD indices would use the same buffer type as the main index. But we'll check to make extra sure. - if (lodIndex->indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT) { - collectUsedIndices(indicesMap, lodIndex); - } else { - collectUsedIndices(indicesMap, lodIndex); - } - } - - VertexData *newVertexData = new VertexData(); - newVertexData->vertexCount = indicesMap.size(); - newVertexData->vertexDeclaration = sharedVertexData->vertexDeclaration->clone(); - - for (uint16 bufIdx = 0; bufIdx < uint16(sharedVertexData->vertexBufferBinding->getBufferCount()); bufIdx++) - { - HardwareVertexBufferSharedPtr sharedVertexBuffer = sharedVertexData->vertexBufferBinding->getBuffer(bufIdx); - size_t vertexSize = sharedVertexBuffer->getVertexSize(); - - HardwareVertexBufferSharedPtr newVertexBuffer = HardwareBufferManager::getSingleton().createVertexBuffer - (vertexSize, newVertexData->vertexCount, sharedVertexBuffer->getUsage(), sharedVertexBuffer->hasShadowBuffer()); - - HardwareBufferLockGuard oldLock(sharedVertexBuffer, 0, sharedVertexData->vertexCount * vertexSize, HardwareBuffer::HBL_READ_ONLY); - HardwareBufferLockGuard newLock(newVertexBuffer, 0, newVertexData->vertexCount * vertexSize, HardwareBuffer::HBL_NORMAL); - - for (auto& id : indicesMap) - { - memcpy((uint8*)newLock.pData + vertexSize * id.second, - (uint8*)oldLock.pData + vertexSize * id.first, vertexSize); - } - - newVertexData->vertexBufferBinding->setBinding(bufIdx, newVertexBuffer); - } - - if (idxType == HardwareIndexBuffer::IT_16BIT) - { - copyIndexBuffer(indexData, indicesMap, 0); - } - else - { - copyIndexBuffer(indexData, indicesMap, 0); - } - - //Need to adjust all of the LOD faces too. - size_t lastIndexEnd = 0; - for (size_t i = 0; i < subMesh->mLodFaceList.size(); ++i) { - auto lodIndex = subMesh->mLodFaceList[i]; - //When using "generated" mesh lods, the indices are shared, so that index[n] would overlap with - //index[n]. We need to take this into account to make sure we don't process data twice (with incorrect - //data as a result). We check if the index either is the first one, or if it has a different buffer - //than the previous one we processed. Since the overlap seems to be progressing we only need to keep - // track of the last used index. - if (i == 0 || lodIndex->indexBuffer != subMesh->mLodFaceList[i - 1]->indexBuffer) { - lastIndexEnd = 0; - } - - //Typically the LOD indices would use the same buffer type as the main index. But we'll check to make extra sure. - if (lodIndex->indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT) { - copyIndexBuffer(lodIndex, indicesMap, lastIndexEnd); - } else { - copyIndexBuffer(lodIndex, indicesMap, lastIndexEnd); - } - lastIndexEnd = lodIndex->indexStart + lodIndex->indexCount; - } - - // Store new attributes - subMesh->resetVertexData(newVertexData); - - // Transfer bone assignments to the submesh - size_t offset = curVertexOffset + newVertexData->vertexCount; - for (auto& b : boneAssignments) - { - size_t vertexIdx = b.first; - if (vertexIdx > offset) - break; - - VertexBoneAssignment boneAssignment = b.second; - boneAssignment.vertexIndex = static_cast(boneAssignment.vertexIndex - curVertexOffset); - subMesh->addBoneAssignment(boneAssignment); - } - curVertexOffset = newVertexData->vertexCount + 1; - } - - // Release shared vertex data - mesh->resetVertexData(); - mesh->clearBoneAssignments(); - - if( mesh->isEdgeListBuilt() ) - { - mesh->freeEdgeList(); - mesh->buildEdgeList(); - } - } - //----------------------------------------------------------------------- - InstanceManager::InstanceBatchIterator InstanceManager::getInstanceBatchIterator( const String &materialName ) const - { - InstanceBatchMap::const_iterator it = mInstanceBatches.find( materialName ); - if(it != mInstanceBatches.end()) - return InstanceBatchIterator( it->second.begin(), it->second.end() ); - - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Cannot create instance batch iterator. " - "Material " + materialName + " cannot be found"); - } -} diff --git a/OgreMain/src/OgreInstancedEntity.cpp b/OgreMain/src/OgreInstancedEntity.cpp deleted file mode 100644 index faf83f79af5..00000000000 --- a/OgreMain/src/OgreInstancedEntity.cpp +++ /dev/null @@ -1,522 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreInstancedEntity.h" -#include "OgreInstanceBatch.h" -#include "OgreSkeletonInstance.h" -#include "OgreAnimationState.h" -#include "OgreOptimisedUtil.h" -#include "OgreNameGenerator.h" - -namespace Ogre -{ - const String MOT_INSTANCED_ENTITY = "InstancedEntity"; - - NameGenerator InstancedEntity::msNameGenerator(""); - - InstancedEntity::InstancedEntity( InstanceBatch *batchOwner, uint32 instanceID, InstancedEntity* sharedTransformEntity ) : - MovableObject(), - mInstanceId( instanceID ), - mInUse( false ), - mBatchOwner( batchOwner ), - mAnimationState( 0 ), - mSkeletonInstance( 0 ), - mBoneMatrices(0), - mBoneWorldMatrices(0), - mFrameAnimationLastUpdated(std::numeric_limits::max() - 1), - mSharedTransformEntity( 0 ), - mTransformLookupNumber(instanceID), - mPosition(Vector3::ZERO), - mDerivedLocalPosition(Vector3::ZERO), - mOrientation(Quaternion::IDENTITY), - mScale(Vector3::UNIT_SCALE), - mMaxScaleLocal(1), - mNeedTransformUpdate(true), - mNeedAnimTransformUpdate(true), - mUseLocalTransform(false) - - - { - //Use a static name generator to ensure this name stays unique (which may not happen - //otherwise due to reparenting when defragmenting) - mName = batchOwner->getName() + "/InstancedEntity_" + StringConverter::toString(mInstanceId) + "/"+ - msNameGenerator.generate(); - - if (sharedTransformEntity) - { - sharedTransformEntity->shareTransformWith(this); - } - else - { - createSkeletonInstance(); - } - updateTransforms(); - } - - InstancedEntity::~InstancedEntity() - { - unlinkTransform(); - destroySkeletonInstance(); - } - - bool InstancedEntity::shareTransformWith( InstancedEntity *slave ) - { - if( !this->mBatchOwner->_getMeshRef()->hasSkeleton() || - !this->mBatchOwner->_getMeshRef()->getSkeleton() || - !this->mBatchOwner->_supportsSkeletalAnimation() ) - { - return false; - } - - if( this->mSharedTransformEntity ) - { - OGRE_EXCEPT( Exception::ERR_INVALID_STATE, "Attempted to share '" + mName + "' transforms " - "with slave '" + slave->mName + "' but '" + mName +"' is " - "already sharing. Hierarchical sharing not allowed.", - "InstancedEntity::shareTransformWith" ); - return false; - } - - if( this->mBatchOwner->_getMeshRef()->getSkeleton() != - slave->mBatchOwner->_getMeshRef()->getSkeleton() ) - { - OGRE_EXCEPT( Exception::ERR_INVALID_STATE, "Sharing transforms requires both instanced" - " entities to have the same skeleton", - "InstancedEntity::shareTransformWith" ); - return false; - } - - slave->unlinkTransform(); - slave->destroySkeletonInstance(); - - slave->mSkeletonInstance = this->mSkeletonInstance; - slave->mAnimationState = this->mAnimationState; - slave->mBoneMatrices = this->mBoneMatrices; - if (mBatchOwner->useBoneWorldMatrices()) - { - slave->mBoneWorldMatrices = this->mBoneWorldMatrices; - } - slave->mSharedTransformEntity = this; - //The sharing partners are kept in the parent entity - this->mSharingPartners.push_back( slave ); - - slave->mBatchOwner->_markTransformSharingDirty(); - - return true; - } - //----------------------------------------------------------------------- - void InstancedEntity::stopSharingTransform() - { - if( mSharedTransformEntity ) - { - stopSharingTransformAsSlave( true ); - } - else - { - //Tell the ones sharing skeleton with us to use their own - InstancedEntityVec::const_iterator itor = mSharingPartners.begin(); - InstancedEntityVec::const_iterator end = mSharingPartners.end(); - while( itor != end ) - { - (*itor)->stopSharingTransformAsSlave( false ); - ++itor; - } - mSharingPartners.clear(); - } - } - //----------------------------------------------------------------------- - const String& InstancedEntity::getMovableType(void) const - { - return MOT_INSTANCED_ENTITY; - } - //----------------------------------------------------------------------- - size_t InstancedEntity::getTransforms( Matrix4 *xform ) const - { - size_t retVal = 1; - - //When not attached, returns zero matrix to avoid rendering this one, not identity - if( isVisible() && isInScene() ) - { - if( !mSkeletonInstance ) - { - *xform = mBatchOwner->useBoneWorldMatrices() ? - _getParentNodeFullTransform() : Matrix4::IDENTITY; - } - else - { - Affine3* matrices = mBatchOwner->useBoneWorldMatrices() ? mBoneWorldMatrices : mBoneMatrices; - const Mesh::IndexMap *indexMap = mBatchOwner->_getIndexToBoneMap(); - Mesh::IndexMap::const_iterator itor = indexMap->begin(); - Mesh::IndexMap::const_iterator end = indexMap->end(); - - while( itor != end ) - *xform++ = matrices[*itor++]; - - retVal = indexMap->size(); - } - } - else - { - if( mSkeletonInstance ) - retVal = mBatchOwner->_getIndexToBoneMap()->size(); - - std::fill_n( xform, retVal, Matrix4::ZERO ); - } - - return retVal; - } - //----------------------------------------------------------------------- - size_t InstancedEntity::getTransforms3x4( Matrix3x4f *xform ) const - { - size_t retVal; - //When not attached, returns zero matrix to avoid rendering this one, not identity - if( isVisible() && isInScene() ) - { - if( !mSkeletonInstance ) - { - const Affine3& mat = mBatchOwner->useBoneWorldMatrices() ? - _getParentNodeFullTransform() : Affine3::IDENTITY; - - *xform = Matrix3x4f(mat[0]); - retVal = 12; - } - else - { - Affine3* matrices = mBatchOwner->useBoneWorldMatrices() ? mBoneWorldMatrices : mBoneMatrices; - const Mesh::IndexMap *indexMap = mBatchOwner->_getIndexToBoneMap(); - - for(auto i : *indexMap) - { - *xform++ = Matrix3x4f(matrices[i][0]); - } - - retVal = indexMap->size() * 4 * 3; - } - } - else - { - if( mSkeletonInstance ) - retVal = mBatchOwner->_getIndexToBoneMap()->size() * 3 * 4; - else - retVal = 12; - - std::fill_n( xform, retVal/12, Matrix3x4f(Affine3::ZERO[0]) ); - } - - return retVal; - } - //----------------------------------------------------------------------- - bool InstancedEntity::findVisible( Camera *camera ) const - { - //Object is active - bool retVal = isInScene(); - if (retVal) - { - //check object is explicitly visible - retVal = isVisible(); - - //Object's bounding box is viewed by the camera - if( retVal && camera ) - retVal = camera->isVisible(Sphere(_getDerivedPosition(),getBoundingRadius() * getMaxScaleCoef())); - } - - return retVal; - } - //----------------------------------------------------------------------- - void InstancedEntity::createSkeletonInstance() - { - //Is mesh skeletally animated? - if( mBatchOwner->_getMeshRef()->hasSkeleton() && - mBatchOwner->_getMeshRef()->getSkeleton() && - mBatchOwner->_supportsSkeletalAnimation() ) - { - mSkeletonInstance = OGRE_NEW SkeletonInstance( mBatchOwner->_getMeshRef()->getSkeleton() ); - mSkeletonInstance->load(); - - mBoneMatrices = static_cast(OGRE_MALLOC_SIMD( sizeof(Affine3) * - mSkeletonInstance->getNumBones(), - MEMCATEGORY_ANIMATION)); - if (mBatchOwner->useBoneWorldMatrices()) - { - mBoneWorldMatrices = static_cast(OGRE_MALLOC_SIMD( sizeof(Affine3) * - mSkeletonInstance->getNumBones(), - MEMCATEGORY_ANIMATION)); - std::fill(mBoneWorldMatrices, mBoneWorldMatrices + mSkeletonInstance->getNumBones(), Affine3::IDENTITY); - } - - mAnimationState = OGRE_NEW AnimationStateSet(); - mBatchOwner->_getMeshRef()->_initAnimationState( mAnimationState ); - } - } - //----------------------------------------------------------------------- - void InstancedEntity::destroySkeletonInstance() - { - if( mSkeletonInstance ) - { - //Tell the ones sharing skeleton with us to use their own - //sharing partners will remove themselves from notifyUnlink - while( mSharingPartners.empty() == false ) - { - mSharingPartners.front()->stopSharingTransform(); - } - mSharingPartners.clear(); - - OGRE_DELETE mSkeletonInstance; - OGRE_DELETE mAnimationState; - OGRE_FREE_SIMD( mBoneMatrices, MEMCATEGORY_ANIMATION ); - OGRE_FREE_SIMD( mBoneWorldMatrices, MEMCATEGORY_ANIMATION ); - - mSkeletonInstance = 0; - mAnimationState = 0; - mBoneMatrices = 0; - mBoneWorldMatrices = 0; - } - } - //----------------------------------------------------------------------- - void InstancedEntity::stopSharingTransformAsSlave( bool notifyMaster ) - { - unlinkTransform( notifyMaster ); - createSkeletonInstance(); - } - //----------------------------------------------------------------------- - void InstancedEntity::unlinkTransform( bool notifyMaster ) - { - if( mSharedTransformEntity ) - { - //Tell our master we're no longer his slave - if( notifyMaster ) - mSharedTransformEntity->notifyUnlink( this ); - mBatchOwner->_markTransformSharingDirty(); - - mSkeletonInstance = 0; - mAnimationState = 0; - mBoneMatrices = 0; - mBoneWorldMatrices = 0; - mSharedTransformEntity = 0; - } - } - //----------------------------------------------------------------------- - void InstancedEntity::notifyUnlink( const InstancedEntity *slave ) - { - //Find the slave and remove it - InstancedEntityVec::iterator itor = mSharingPartners.begin(); - InstancedEntityVec::iterator end = mSharingPartners.end(); - while( itor != end ) - { - if( *itor == slave ) - { - std::swap(*itor,mSharingPartners.back()); - mSharingPartners.pop_back(); - break; - } - - ++itor; - } - } - //----------------------------------------------------------------------- - const AxisAlignedBox& InstancedEntity::getBoundingBox(void) const - { - //TODO: Add attached objects (TagPoints) to the bbox - return mBatchOwner->_getMeshReference()->getBounds(); - } - - //----------------------------------------------------------------------- - Real InstancedEntity::getBoundingRadius(void) const - { - return mBatchOwner->_getMeshReference()->getBoundingSphereRadius(); - } - //----------------------------------------------------------------------- - Real InstancedEntity::getSquaredViewDepth( const Camera* cam ) const - { - return _getDerivedPosition().squaredDistance(cam->getDerivedPosition()); - } - //----------------------------------------------------------------------- - void InstancedEntity::_notifyMoved(void) - { - markTransformDirty(); - MovableObject::_notifyMoved(); - updateTransforms(); - } - - //----------------------------------------------------------------------- - void InstancedEntity::_notifyAttached( Node* parent, bool isTagPoint ) - { - markTransformDirty(); - MovableObject::_notifyAttached( parent, isTagPoint ); - updateTransforms(); - } - //----------------------------------------------------------------------- - AnimationState* InstancedEntity::getAnimationState(const String& name) const - { - if (!mAnimationState) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Entity is not animated", - "InstancedEntity::getAnimationState"); - } - - return mAnimationState->getAnimationState(name); - } - //----------------------------------------------------------------------- - AnimationStateSet* InstancedEntity::getAllAnimationStates(void) const - { - return mAnimationState; - } - //----------------------------------------------------------------------- - bool InstancedEntity::_updateAnimation(void) - { - if (mSharedTransformEntity) - { - return mSharedTransformEntity->_updateAnimation(); - } - else - { - const bool animationDirty = - (mFrameAnimationLastUpdated != mAnimationState->getDirtyFrameNumber()) || - (mSkeletonInstance->getManualBonesDirty()); - - if( animationDirty || (mNeedAnimTransformUpdate && mBatchOwner->useBoneWorldMatrices())) - { - mSkeletonInstance->setAnimationState( *mAnimationState ); - mSkeletonInstance->_getBoneMatrices( mBoneMatrices ); - - // Cache last parent transform for next frame use too. - if (mBatchOwner->useBoneWorldMatrices()) - { - OptimisedUtil::getImplementation()->concatenateAffineMatrices( - _getParentNodeFullTransform(), - mBoneMatrices, - mBoneWorldMatrices, - mSkeletonInstance->getNumBones() ); - mNeedAnimTransformUpdate = false; - } - - mFrameAnimationLastUpdated = mAnimationState->getDirtyFrameNumber(); - - return true; - } - } - - return false; - } - - //----------------------------------------------------------------------- - void InstancedEntity::markTransformDirty() - { - mNeedTransformUpdate = true; - mNeedAnimTransformUpdate = true; - mBatchOwner->_boundsDirty(); - } - - //--------------------------------------------------------------------------- - void InstancedEntity::setPosition(const Vector3& position, bool doUpdate) - { - mPosition = position; - mDerivedLocalPosition = position; - mUseLocalTransform = true; - markTransformDirty(); - if (doUpdate) updateTransforms(); - } - - //--------------------------------------------------------------------------- - void InstancedEntity::setOrientation(const Quaternion& orientation, bool doUpdate) - { - mOrientation = orientation; - mUseLocalTransform = true; - markTransformDirty(); - if (doUpdate) updateTransforms(); - } - - //--------------------------------------------------------------------------- - void InstancedEntity::setScale(const Vector3& scale, bool doUpdate) - { - mScale = scale; - mMaxScaleLocal = std::max(std::max( - Math::Abs(mScale.x), Math::Abs(mScale.y)), Math::Abs(mScale.z)); - mUseLocalTransform = true; - markTransformDirty(); - if (doUpdate) updateTransforms(); - } - - //--------------------------------------------------------------------------- - Real InstancedEntity::getMaxScaleCoef() const - { - return mMaxScaleLocal; - } - - //--------------------------------------------------------------------------- - void InstancedEntity::updateTransforms() - { - if (mNeedTransformUpdate) - { - if (mUseLocalTransform) - { - if (mParentNode) - { - const Vector3& parentPosition = mParentNode->_getDerivedPosition(); - const Quaternion& parentOrientation = mParentNode->_getDerivedOrientation(); - const Vector3& parentScale = mParentNode->_getDerivedScale(); - - Quaternion derivedOrientation = parentOrientation * mOrientation; - Vector3 derivedScale = parentScale * mScale; - mDerivedLocalPosition = parentOrientation * (parentScale * mPosition) + parentPosition; - - mFullLocalTransform.makeTransform(mDerivedLocalPosition, derivedScale, derivedOrientation); - } - else - { - mFullLocalTransform.makeTransform(mPosition,mScale,mOrientation); - } - } else { - if (mParentNode) { - const Ogre::Vector3& parentScale = mParentNode->_getDerivedScale(); - mMaxScaleLocal = std::max(std::max( - Math::Abs(parentScale.x), Math::Abs(parentScale.y)), Math::Abs(parentScale.z)); - } - } - mNeedTransformUpdate = false; - } - } - - //--------------------------------------------------------------------------- - void InstancedEntity::setInUse( bool used ) - { - mInUse = used; - //Remove the use of local transform if the object is deleted - mUseLocalTransform &= used; - } - //--------------------------------------------------------------------------- - void InstancedEntity::setCustomParam( unsigned char idx, const Vector4f &newParam ) - { - mBatchOwner->_setCustomParam( this, idx, newParam ); - } - //--------------------------------------------------------------------------- - const Vector4f& InstancedEntity::getCustomParam( unsigned char idx ) - { - return mBatchOwner->_getCustomParam( this, idx ); - } -} diff --git a/OgreMain/src/OgreKeyFrame.cpp b/OgreMain/src/OgreKeyFrame.cpp deleted file mode 100644 index 484be83a562..00000000000 --- a/OgreMain/src/OgreKeyFrame.cpp +++ /dev/null @@ -1,226 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreKeyFrame.h" -#include "OgreAnimationTrack.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - KeyFrame::KeyFrame(const AnimationTrack* parent, Real time) - : mTime(time), mParentTrack(parent) - { - } - //--------------------------------------------------------------------- - KeyFrame* KeyFrame::_clone(AnimationTrack* newParent) const - { - return OGRE_NEW KeyFrame(newParent, mTime); - } - //--------------------------------------------------------------------- - NumericKeyFrame::NumericKeyFrame(const AnimationTrack* parent, Real time) - :KeyFrame(parent, time) - { - } - //--------------------------------------------------------------------- - KeyFrame* NumericKeyFrame::_clone(AnimationTrack* newParent) const - { - NumericKeyFrame* newKf = OGRE_NEW NumericKeyFrame(newParent, mTime); - newKf->mValue = mValue; - return newKf; - } - //--------------------------------------------------------------------- - TransformKeyFrame::TransformKeyFrame(const AnimationTrack* parent, Real time) - :KeyFrame(parent, time), mTranslate(Vector3::ZERO), - mScale(Vector3::UNIT_SCALE), mRotate(Quaternion::IDENTITY) - { - } - //--------------------------------------------------------------------- - void TransformKeyFrame::setTranslate(const Vector3& trans) - { - mTranslate = trans; - if (mParentTrack) - mParentTrack->_keyFrameDataChanged(); - } - //--------------------------------------------------------------------- - const Vector3& TransformKeyFrame::getTranslate(void) const - { - return mTranslate; - } - //--------------------------------------------------------------------- - void TransformKeyFrame::setScale(const Vector3& scale) - { - mScale = scale; - if (mParentTrack) - mParentTrack->_keyFrameDataChanged(); - } - //--------------------------------------------------------------------- - const Vector3& TransformKeyFrame::getScale(void) const - { - return mScale; - } - //--------------------------------------------------------------------- - void TransformKeyFrame::setRotation(const Quaternion& rot) - { - mRotate = rot; - if (mParentTrack) - mParentTrack->_keyFrameDataChanged(); - } - //--------------------------------------------------------------------- - const Quaternion& TransformKeyFrame::getRotation(void) const - { - return mRotate; - } - //--------------------------------------------------------------------- - KeyFrame* TransformKeyFrame::_clone(AnimationTrack* newParent) const - { - TransformKeyFrame* newKf = OGRE_NEW TransformKeyFrame(newParent, mTime); - newKf->mTranslate = mTranslate; - newKf->mScale = mScale; - newKf->mRotate = mRotate; - return newKf; - } - //--------------------------------------------------------------------- - VertexMorphKeyFrame::VertexMorphKeyFrame(const AnimationTrack* parent, Real time) - : KeyFrame(parent, time) - { - } - //--------------------------------------------------------------------- - void VertexMorphKeyFrame::setVertexBuffer(const HardwareVertexBufferSharedPtr& buf) - { - mBuffer = buf; - } - //--------------------------------------------------------------------- - const HardwareVertexBufferSharedPtr& - VertexMorphKeyFrame::getVertexBuffer(void) const - { - return mBuffer; - } - //--------------------------------------------------------------------- - KeyFrame* VertexMorphKeyFrame::_clone(AnimationTrack* newParent) const - { - VertexMorphKeyFrame* newKf = OGRE_NEW VertexMorphKeyFrame(newParent, mTime); - newKf->mBuffer = mBuffer; - return newKf; - } - //--------------------------------------------------------------------- - VertexPoseKeyFrame::VertexPoseKeyFrame(const AnimationTrack* parent, Real time) - :KeyFrame(parent, time) - { - } - //--------------------------------------------------------------------- - void VertexPoseKeyFrame::addPoseReference(ushort poseIndex, float influence) - { - mPoseRefs.push_back(PoseRef(poseIndex, influence)); - } - //--------------------------------------------------------------------- - void VertexPoseKeyFrame::updatePoseReference(ushort poseIndex, float influence) - { - for (auto & poseRef : mPoseRefs) - { - if (poseRef.poseIndex == poseIndex) - { - poseRef.influence = influence; - return; - } - } - // if we got here, we didn't find it - addPoseReference(poseIndex, influence); - - } - //--------------------------------------------------------------------- - void VertexPoseKeyFrame::removePoseReference(ushort poseIndex) - { - for (PoseRefList::iterator i = mPoseRefs.begin(); i != mPoseRefs.end(); ++i) - { - if (i->poseIndex == poseIndex) - { - mPoseRefs.erase(i); - return; - } - } - } - //--------------------------------------------------------------------- - void VertexPoseKeyFrame::removeAllPoseReferences(void) - { - mPoseRefs.clear(); - } - //--------------------------------------------------------------------- - const VertexPoseKeyFrame::PoseRefList& - VertexPoseKeyFrame::getPoseReferences(void) const - { - return mPoseRefs; - } - //--------------------------------------------------------------------- - VertexPoseKeyFrame::PoseRefIterator - VertexPoseKeyFrame::getPoseReferenceIterator(void) - { - return PoseRefIterator(mPoseRefs.begin(), mPoseRefs.end()); - } - //--------------------------------------------------------------------- - VertexPoseKeyFrame::ConstPoseRefIterator - VertexPoseKeyFrame::getPoseReferenceIterator(void) const - { - return ConstPoseRefIterator(mPoseRefs.begin(), mPoseRefs.end()); - } - //--------------------------------------------------------------------- - KeyFrame* VertexPoseKeyFrame::_clone(AnimationTrack* newParent) const - { - VertexPoseKeyFrame* newKf = OGRE_NEW VertexPoseKeyFrame(newParent, mTime); - // By-value copy ok - newKf->mPoseRefs = mPoseRefs; - return newKf; - } - //--------------------------------------------------------------------- - void VertexPoseKeyFrame::_applyBaseKeyFrame(const VertexPoseKeyFrame* base) - { - // We subtract the matching pose influences in the base keyframe from the - // influences in this keyframe - for (auto & myPoseRef : mPoseRefs) - { - PoseRefList::const_iterator basePoseIt = base->getPoseReferences().begin(); - Real baseInfluence = 0.0f; - for (;basePoseIt != base->getPoseReferences().end(); ++basePoseIt) - { - const PoseRef& basePoseRef = *basePoseIt; - if (basePoseRef.poseIndex == myPoseRef.poseIndex) - { - baseInfluence = basePoseRef.influence; - break; - } - } - - myPoseRef.influence -= baseInfluence; - - } - - } - - -} - diff --git a/OgreMain/src/OgreLight.cpp b/OgreMain/src/OgreLight.cpp deleted file mode 100644 index 2b77bc8460f..00000000000 --- a/OgreMain/src/OgreLight.cpp +++ /dev/null @@ -1,948 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -namespace Ogre { - //----------------------------------------------------------------------- - Light::Light() : Light(BLANKSTRING) {} - //----------------------------------------------------------------------- - Light::Light(const String& name) : MovableObject(name), -#ifdef OGRE_NODELESS_POSITIONING - mPosition(Vector3::ZERO), - mDirection(Vector3::NEGATIVE_UNIT_Z), - mDerivedPosition(Vector3::ZERO), - mDerivedDirection(Vector3::NEGATIVE_UNIT_Z), - mDerivedCamRelativeDirty(false), - mDerivedTransformDirty(false), -#endif - mDiffuse(ColourValue::White), - mSpecular(ColourValue::Black), - mSpotOuter(Degree(40.0f)), - mSpotInner(Degree(30.0f)), - mSpotFalloff(1.0f), - mSpotNearClip(0.0f), - mAttenuation(100000.f, 1.f, 0.f, 0.f), - mShadowFarDist(0), - mShadowFarDistSquared(0), - mIndexInFrame(0), - mShadowNearClipDist(-1), - mShadowFarClipDist(-1), - mCameraToBeRelativeTo(0), - mPowerScale(1.0f), - mSourceSize(0, 0), - mLightType(LT_POINT), - mOwnShadowFarDist(false) - { - //mMinPixelSize should always be zero for lights otherwise lights will disapear - mMinPixelSize = 0; - } - //----------------------------------------------------------------------- - Light::~Light() - { - } - //----------------------------------------------------------------------- - void Light::setType(LightTypes type) - { - mLightType = type; - } - //----------------------------------------------------------------------- - Light::LightTypes Light::getType(void) const - { - return mLightType; - } -#ifdef OGRE_NODELESS_POSITIONING - //----------------------------------------------------------------------- - void Light::setPosition(Real x, Real y, Real z) - { - mPosition.x = x; - mPosition.y = y; - mPosition.z = z; - mDerivedTransformDirty = true; - } - //----------------------------------------------------------------------- - void Light::setPosition(const Vector3& vec) - { - mPosition = vec; - mDerivedTransformDirty = true; - } - //----------------------------------------------------------------------- - const Vector3& Light::getPosition(void) const - { - return mPosition; - } - //----------------------------------------------------------------------- - void Light::setDirection(Real x, Real y, Real z) - { - mDirection.x = x; - mDirection.y = y; - mDirection.z = z; - mDerivedTransformDirty = true; - } - //----------------------------------------------------------------------- - void Light::setDirection(const Vector3& vec) - { - mDirection = vec; - mDerivedTransformDirty = true; - } - //----------------------------------------------------------------------- - const Vector3& Light::getDirection(void) const - { - return mDirection; - } -#endif - //----------------------------------------------------------------------- - void Light::setSpotlightRange(const Radian& innerAngle, const Radian& outerAngle, Real falloff) - { - mSpotInner = innerAngle; - mSpotOuter = outerAngle; - mSpotFalloff = falloff; - } - //----------------------------------------------------------------------- - void Light::setSpotlightInnerAngle(const Radian& val) - { - mSpotInner = val; - } - //----------------------------------------------------------------------- - void Light::setSpotlightOuterAngle(const Radian& val) - { - mSpotOuter = val; - } - //----------------------------------------------------------------------- - void Light::setSpotlightFalloff(Real val) - { - mSpotFalloff = val; - } - //----------------------------------------------------------------------- - const Radian& Light::getSpotlightInnerAngle(void) const - { - return mSpotInner; - } - //----------------------------------------------------------------------- - const Radian& Light::getSpotlightOuterAngle(void) const - { - return mSpotOuter; - } - //----------------------------------------------------------------------- - Real Light::getSpotlightFalloff(void) const - { - return mSpotFalloff; - } - //----------------------------------------------------------------------- - void Light::setDiffuseColour(float red, float green, float blue) - { - mDiffuse.r = red; - mDiffuse.b = blue; - mDiffuse.g = green; - } - //----------------------------------------------------------------------- - void Light::setDiffuseColour(const ColourValue& colour) - { - mDiffuse = colour; - } - //----------------------------------------------------------------------- - const ColourValue& Light::getDiffuseColour(void) const - { - return mDiffuse; - } - //----------------------------------------------------------------------- - void Light::setSpecularColour(float red, float green, float blue) - { - mSpecular.r = red; - mSpecular.b = blue; - mSpecular.g = green; - } - //----------------------------------------------------------------------- - void Light::setSpecularColour(const ColourValue& colour) - { - mSpecular = colour; - } - //----------------------------------------------------------------------- - const ColourValue& Light::getSpecularColour(void) const - { - return mSpecular; - } - //----------------------------------------------------------------------- - void Light::setPowerScale(Real power) - { - mPowerScale = power; - } - //----------------------------------------------------------------------- - Real Light::getPowerScale(void) const - { - return mPowerScale; - } -#ifdef OGRE_NODELESS_POSITIONING - //----------------------------------------------------------------------- - void Light::update(void) const - { - if (mDerivedTransformDirty) - { - if (mParentNode) - { - // Ok, update with SceneNode we're attached to - mDerivedDirection = mParentNode->convertLocalToWorldDirection(mDirection, false); - mDerivedPosition = mParentNode->convertLocalToWorldPosition(mPosition); - } - else - { - mDerivedPosition = mPosition; - mDerivedDirection = mDirection; - } - - mDerivedTransformDirty = false; - //if the position has been updated we must update also the relative position - mDerivedCamRelativeDirty = true; - } - if (mCameraToBeRelativeTo && mDerivedCamRelativeDirty) - { - mDerivedCamRelativePosition = mDerivedPosition - mCameraToBeRelativeTo->getDerivedPosition(); - mDerivedCamRelativeDirty = false; - } - } - //----------------------------------------------------------------------- - void Light::_notifyAttached(Node* parent, bool isTagPoint) - { - mDerivedTransformDirty = true; - - MovableObject::_notifyAttached(parent, isTagPoint); - } - //----------------------------------------------------------------------- - void Light::_notifyMoved(void) - { - mDerivedTransformDirty = true; - - MovableObject::_notifyMoved(); - } -#endif - //----------------------------------------------------------------------- - const AxisAlignedBox& Light::getBoundingBox(void) const - { - // zero extent to still allow SceneQueries to work - static AxisAlignedBox box(Vector3(0, 0, 0), Vector3(0, 0, 0)); - return box; - } - //----------------------------------------------------------------------- - void Light::visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables) - { - // nothing to render - } - //----------------------------------------------------------------------- - const String& Light::getMovableType(void) const - { - return MOT_LIGHT; - } -#ifdef OGRE_NODELESS_POSITIONING - //----------------------------------------------------------------------- - const Vector3& Light::getDerivedPosition(bool cameraRelative) const - { - update(); - if (cameraRelative && mCameraToBeRelativeTo) - { - return mDerivedCamRelativePosition; - } - else - { - return mDerivedPosition; - } - } - //----------------------------------------------------------------------- - const Vector3& Light::getDerivedDirection(void) const - { - update(); - return mDerivedDirection; - } -#endif - //----------------------------------------------------------------------- - Vector4 Light::getAs4DVector(bool cameraRelativeIfSet) const - { - if (mLightType == Light::LT_DIRECTIONAL) - { - return Vector4(-getDerivedDirection(), // negate direction as 'position' - 0.0); // infinite distance - } - else - { - return Vector4(getDerivedPosition(cameraRelativeIfSet), 1.0); - } - } - Vector3f Light::getDerivedSourceHalfWidth() const - { - auto& ori = mParentNode->_getDerivedOrientation(); - auto& scale = mParentNode->_getDerivedScale(); - return ori.xAxis() * mSourceSize[0] * scale[0] * 0.5f; - } - Vector3f Light::getDerivedSourceHalfHeight() const - { - auto& ori = mParentNode->_getDerivedOrientation(); - auto& scale = mParentNode->_getDerivedScale(); - return ori.yAxis() * mSourceSize[1] * scale[1] * 0.5f; - } - //----------------------------------------------------------------------- - const PlaneBoundedVolume& Light::_getNearClipVolume(const Camera* const cam) const - { - // First check if the light is close to the near plane, since - // in this case we have to build a degenerate clip volume - mNearClipVolume.planes.clear(); - mNearClipVolume.outside = Plane::NEGATIVE_SIDE; - - Real n = cam->getNearClipDistance(); - // Homogenous position - Vector4 lightPos = getAs4DVector(); - // 3D version (not the same as _getDerivedPosition, is -direction for - // directional lights) - Vector3 lightPos3 = Vector3(lightPos.x, lightPos.y, lightPos.z); - - // Get eye-space light position - // use 4D vector so directional lights still work - Vector4 eyeSpaceLight = cam->getViewMatrix() * lightPos; - // Find distance to light, project onto -Z axis - Real d = eyeSpaceLight.dotProduct( - Vector4(0, 0, -1, -n) ); - #define THRESHOLD 1e-6 - if (d > THRESHOLD || d < -THRESHOLD) - { - // light is not too close to the near plane - // First find the worldspace positions of the corners of the viewport - const Vector3 *corner = cam->getWorldSpaceCorners(); - int winding = (d < 0) ^ cam->isReflected() ? +1 : -1; - // Iterate over world points and form side planes - Vector3 normal; - Vector3 lightDir; - for (unsigned int i = 0; i < 4; ++i) - { - // Figure out light dir - lightDir = lightPos3 - (corner[i] * lightPos.w); - // Cross with anticlockwise corner, therefore normal points in - normal = (corner[i] - corner[(i+winding)%4]) - .crossProduct(lightDir); - normal.normalise(); - mNearClipVolume.planes.push_back(Plane(normal, corner[i])); - } - - // Now do the near plane plane - normal = cam->getFrustumPlane(FRUSTUM_PLANE_NEAR).normal; - if (d < 0) - { - // Behind near plane - normal = -normal; - } - const Vector3& cameraPos = cam->getDerivedPosition(); - mNearClipVolume.planes.push_back(Plane(normal, cameraPos)); - - // Finally, for a point/spot light we can add a sixth plane - // This prevents false positives from behind the light - if (mLightType != LT_DIRECTIONAL) - { - // Direction from light perpendicular to near plane - mNearClipVolume.planes.push_back(Plane(-normal, lightPos3)); - } - } - else - { - // light is close to being on the near plane - // degenerate volume including the entire scene - // we will always require light / dark caps - mNearClipVolume.planes.push_back(Plane(Vector3::UNIT_Z, -n)); - mNearClipVolume.planes.push_back(Plane(-Vector3::UNIT_Z, n)); - } - - return mNearClipVolume; - } - //----------------------------------------------------------------------- - const PlaneBoundedVolumeList& Light::_getFrustumClipVolumes(const Camera* const cam) const - { - - // Homogenous light position - Vector4 lightPos = getAs4DVector(); - // 3D version (not the same as _getDerivedPosition, is -direction for - // directional lights) - Vector3 lightPos3 = Vector3(lightPos.x, lightPos.y, lightPos.z); - - const Vector3 *clockwiseVerts[4]; - - // Get worldspace frustum corners - const Vector3* corners = cam->getWorldSpaceCorners(); - int windingPt0 = cam->isReflected() ? 1 : 0; - int windingPt1 = cam->isReflected() ? 0 : 1; - - bool infiniteViewDistance = (cam->getFarClipDistance() == 0); - - Vector3 notSoFarCorners[4]; - if(infiniteViewDistance) - { - Vector3 camPosition = cam->getRealPosition(); - notSoFarCorners[0] = corners[0] + corners[0] - camPosition; - notSoFarCorners[1] = corners[1] + corners[1] - camPosition; - notSoFarCorners[2] = corners[2] + corners[2] - camPosition; - notSoFarCorners[3] = corners[3] + corners[3] - camPosition; - } - - mFrustumClipVolumes.clear(); - for (unsigned short n = 0; n < 6; ++n) - { - // Skip far plane if infinite view frustum - if (infiniteViewDistance && n == FRUSTUM_PLANE_FAR) - continue; - - const Plane& plane = cam->getFrustumPlane(n); - Vector4 planeVec(plane.normal.x, plane.normal.y, plane.normal.z, plane.d); - // planes face inwards, we need to know if light is on negative side - Real d = planeVec.dotProduct(lightPos); - if (d < -1e-06) - { - // Ok, this is a valid one - // clockwise verts mean we can cross-product and always get normals - // facing into the volume we create - - mFrustumClipVolumes.push_back(PlaneBoundedVolume()); - PlaneBoundedVolume& vol = mFrustumClipVolumes.back(); - switch(n) - { - case(FRUSTUM_PLANE_NEAR): - clockwiseVerts[0] = corners + 3; - clockwiseVerts[1] = corners + 2; - clockwiseVerts[2] = corners + 1; - clockwiseVerts[3] = corners + 0; - break; - case(FRUSTUM_PLANE_FAR): - clockwiseVerts[0] = corners + 7; - clockwiseVerts[1] = corners + 6; - clockwiseVerts[2] = corners + 5; - clockwiseVerts[3] = corners + 4; - break; - case(FRUSTUM_PLANE_LEFT): - clockwiseVerts[0] = infiniteViewDistance ? notSoFarCorners + 1 : corners + 5; - clockwiseVerts[1] = corners + 1; - clockwiseVerts[2] = corners + 2; - clockwiseVerts[3] = infiniteViewDistance ? notSoFarCorners + 2 : corners + 6; - break; - case(FRUSTUM_PLANE_RIGHT): - clockwiseVerts[0] = infiniteViewDistance ? notSoFarCorners + 3 : corners + 7; - clockwiseVerts[1] = corners + 3; - clockwiseVerts[2] = corners + 0; - clockwiseVerts[3] = infiniteViewDistance ? notSoFarCorners + 0 : corners + 4; - break; - case(FRUSTUM_PLANE_TOP): - clockwiseVerts[0] = infiniteViewDistance ? notSoFarCorners + 0 : corners + 4; - clockwiseVerts[1] = corners + 0; - clockwiseVerts[2] = corners + 1; - clockwiseVerts[3] = infiniteViewDistance ? notSoFarCorners + 1 : corners + 5; - break; - case(FRUSTUM_PLANE_BOTTOM): - clockwiseVerts[0] = infiniteViewDistance ? notSoFarCorners + 2 : corners + 6; - clockwiseVerts[1] = corners + 2; - clockwiseVerts[2] = corners + 3; - clockwiseVerts[3] = infiniteViewDistance ? notSoFarCorners + 3 : corners + 7; - break; - }; - - // Build a volume - // Iterate over world points and form side planes - Vector3 normal; - Vector3 lightDir; - unsigned int infiniteViewDistanceInt = infiniteViewDistance ? 1 : 0; - for (unsigned int i = 0; i < 4 - infiniteViewDistanceInt; ++i) - { - // Figure out light dir - lightDir = lightPos3 - (*(clockwiseVerts[i]) * lightPos.w); - Vector3 edgeDir = *(clockwiseVerts[(i+windingPt1)%4]) - *(clockwiseVerts[(i+windingPt0)%4]); - // Cross with anticlockwise corner, therefore normal points in - normal = edgeDir.crossProduct(lightDir); - normal.normalise(); - vol.planes.push_back(Plane(normal, *(clockwiseVerts[i]))); - } - - // Now do the near plane (this is the plane of the side we're - // talking about, with the normal inverted (d is already interpreted as -ve) - vol.planes.push_back( Plane(-plane.normal, plane.d) ); - - // Finally, for a point/spot light we can add a sixth plane - // This prevents false positives from behind the light - if (mLightType != LT_DIRECTIONAL) - { - // re-use our own plane normal - vol.planes.push_back(Plane(plane.normal, lightPos3)); - } - } - } - - return mFrustumClipVolumes; - } - //----------------------------------------------------------------------- - uint32 Light::getTypeFlags(void) const - { - return SceneManager::LIGHT_TYPE_MASK; - } - //--------------------------------------------------------------------- - void Light::_calcTempSquareDist(const Vector3& worldPos) - { - if (mLightType == LT_DIRECTIONAL) - { - // make sure directional lights are always in front - // even of point lights at worldPos - // tempSquareDist is just a tag for sorting, and nobody will take the sqrt - tempSquareDist = -1; - } - else - { - tempSquareDist = - (worldPos - getDerivedPosition()).squaredLength(); - } - - } - //----------------------------------------------------------------------- - class LightDiffuseColourValue : public AnimableValue - { - protected: - Light* mLight; - public: - LightDiffuseColourValue(Light* l) :AnimableValue(COLOUR) - { mLight = l; } - void setValue(const ColourValue& val) override - { - mLight->setDiffuseColour(val); - } - void applyDeltaValue(const ColourValue& val) override - { - setValue(mLight->getDiffuseColour() + val); - } - void setCurrentStateAsBaseValue(void) override - { - setAsBaseValue(mLight->getDiffuseColour()); - } - - }; - //----------------------------------------------------------------------- - class LightSpecularColourValue : public AnimableValue - { - protected: - Light* mLight; - public: - LightSpecularColourValue(Light* l) :AnimableValue(COLOUR) - { mLight = l; } - void setValue(const ColourValue& val) override - { - mLight->setSpecularColour(val); - } - void applyDeltaValue(const ColourValue& val) override - { - setValue(mLight->getSpecularColour() + val); - } - void setCurrentStateAsBaseValue(void) override - { - setAsBaseValue(mLight->getSpecularColour()); - } - - }; - //----------------------------------------------------------------------- - class LightAttenuationValue : public AnimableValue - { - protected: - Light* mLight; - public: - LightAttenuationValue(Light* l) :AnimableValue(VECTOR4) - { mLight = l; } - void setValue(const Vector4& val) override - { - mLight->setAttenuation(val.x, val.y, val.z, val.w); - } - void applyDeltaValue(const Vector4& val) override - { - const auto& attenuation = mLight->getAttenuation(); - setValue(Vector4(attenuation[0], attenuation[1], attenuation[2], attenuation[3]) + val); - } - void setCurrentStateAsBaseValue(void) override - { - setAsBaseValue(mLight->getAttenuation()); - } - - }; - //----------------------------------------------------------------------- - class LightSpotlightInnerValue : public AnimableValue - { - protected: - Light* mLight; - public: - LightSpotlightInnerValue(Light* l) : AnimableValue(RADIAN), mLight(l) {} - void setValue(const Radian& val) override - { - mLight->setSpotlightInnerAngle(val); - } - void applyDeltaValue(const Radian& val) override - { - setValue(mLight->getSpotlightInnerAngle() + val); - } - void setCurrentStateAsBaseValue(void) override - { - setAsBaseValue(mLight->getSpotlightInnerAngle()); - } - - }; - //----------------------------------------------------------------------- - class LightSpotlightOuterValue : public AnimableValue - { - protected: - Light* mLight; - public: - LightSpotlightOuterValue(Light* l) : AnimableValue(RADIAN), mLight(l) {} - void setValue(const Radian& val) override - { - mLight->setSpotlightOuterAngle(val); - } - void applyDeltaValue(const Radian& val) override - { - setValue(mLight->getSpotlightOuterAngle() + val); - } - void setCurrentStateAsBaseValue(void) override - { - setAsBaseValue(mLight->getSpotlightOuterAngle()); - } - - }; - //----------------------------------------------------------------------- - class LightSpotlightFalloffValue : public AnimableValue - { - protected: - Light* mLight; - public: - LightSpotlightFalloffValue(Light* l) :AnimableValue(REAL) - { mLight = l; } - void setValue(Real val) override - { - mLight->setSpotlightFalloff(val); - } - void applyDeltaValue(Real val) override - { - setValue(mLight->getSpotlightFalloff() + val); - } - void setCurrentStateAsBaseValue(void) override - { - setAsBaseValue(mLight->getSpotlightFalloff()); - } - - }; - //----------------------------------------------------------------------- - AnimableValuePtr Light::createAnimableValue(const String& valueName) - { - if (valueName == "diffuseColour") - { - return AnimableValuePtr( - OGRE_NEW LightDiffuseColourValue(this)); - } - else if(valueName == "specularColour") - { - return AnimableValuePtr( - OGRE_NEW LightSpecularColourValue(this)); - } - else if (valueName == "attenuation") - { - return AnimableValuePtr( - OGRE_NEW LightAttenuationValue(this)); - } - else if (valueName == "spotlightInner") - { - return AnimableValuePtr( - OGRE_NEW LightSpotlightInnerValue(this)); - } - else if (valueName == "spotlightOuter") - { - return AnimableValuePtr( - OGRE_NEW LightSpotlightOuterValue(this)); - } - else if (valueName == "spotlightFalloff") - { - return AnimableValuePtr( - OGRE_NEW LightSpotlightFalloffValue(this)); - } - else - { - return MovableObject::createAnimableValue(valueName); - } - } - //----------------------------------------------------------------------- - void Light::setCustomShadowCameraSetup(const ShadowCameraSetupPtr& customShadowSetup) - { - mCustomShadowCameraSetup = customShadowSetup; - } - //----------------------------------------------------------------------- - void Light::resetCustomShadowCameraSetup() - { - mCustomShadowCameraSetup.reset(); - } - //----------------------------------------------------------------------- - const ShadowCameraSetupPtr& Light::getCustomShadowCameraSetup() const - { - return mCustomShadowCameraSetup; - } - //----------------------------------------------------------------------- - void Light::setShadowFarDistance(Real distance) - { - mOwnShadowFarDist = true; - mShadowFarDist = distance; - mShadowFarDistSquared = distance * distance; - } - //----------------------------------------------------------------------- - void Light::resetShadowFarDistance(void) - { - mOwnShadowFarDist = false; - } - //----------------------------------------------------------------------- - Real Light::getShadowFarDistance(void) const - { - if (mOwnShadowFarDist) - return mShadowFarDist; - else - return mManager->getShadowFarDistance (); - } - //----------------------------------------------------------------------- - Real Light::getShadowFarDistanceSquared(void) const - { - if (mOwnShadowFarDist) - return mShadowFarDistSquared; - else - return mManager->getShadowFarDistanceSquared (); - } - //--------------------------------------------------------------------- - void Light::_setCameraRelative(Camera* cam) - { - mCameraToBeRelativeTo = cam; -#ifdef OGRE_NODELESS_POSITIONING - mDerivedCamRelativeDirty = true; -#endif - } - //--------------------------------------------------------------------- - Real Light::_deriveShadowNearClipDistance(const Camera* maincam) const - { - if (mShadowNearClipDist > 0) - return mShadowNearClipDist; - else - return maincam->getNearClipDistance(); - } - //--------------------------------------------------------------------- - Real Light::_deriveShadowFarClipDistance() const - { - if (mShadowFarClipDist >= 0) - return mShadowFarClipDist; - else - { - if (mLightType == LT_DIRECTIONAL) - return 0; - else - return mAttenuation[0]; - } - } - //----------------------------------------------------------------------- - void Light::setCustomParameter(uint16 index, const Ogre::Vector4f &value) - { - mCustomParameters[index] = value; - } - //----------------------------------------------------------------------- - const Vector4f &Light::getCustomParameter(uint16 index) const - { - CustomParameterMap::const_iterator i = mCustomParameters.find(index); - if (i != mCustomParameters.end()) - { - return i->second; - } - else - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Parameter at the given index was not found.", - "Light::getCustomParameter"); - } - } - //----------------------------------------------------------------------- - void Light::_updateCustomGpuParameter(uint16 paramIndex, const GpuProgramParameters::AutoConstantEntry& constantEntry, GpuProgramParameters *params) const - { - CustomParameterMap::const_iterator i = mCustomParameters.find(paramIndex); - if (i != mCustomParameters.end()) - { - params->_writeRawConstant(constantEntry.physicalIndex, i->second, - constantEntry.elementCount); - } - } - //----------------------------------------------------------------------- - bool Light::isInLightRange(const Ogre::Sphere& container) const - { - bool isIntersect = true; - //directional light always intersects (check only spotlight and point) - if (mLightType != LT_DIRECTIONAL) - { -#ifndef OGRE_NODELESS_POSITIONING - const auto& mDerivedDirection = getDerivedDirection(); - const auto& mDerivedPosition = mParentNode->_getDerivedPosition(); -#endif - //Check that the sphere is within the sphere of the light - isIntersect = container.intersects(Sphere(mDerivedPosition, mAttenuation[0])); - //If this is a spotlight, check that the sphere is within the cone of the spot light - if ((isIntersect) && (mLightType == LT_SPOTLIGHT)) - { - //check first check of the sphere surrounds the position of the light - //(this covers the case where the center of the sphere is behind the position of the light - // something which is not covered in the next test). - isIntersect = container.intersects(mDerivedPosition); - //if not test cones - if (!isIntersect) - { - //Calculate the cone that exists between the sphere and the center position of the light - Ogre::Vector3 lightSphereConeDirection = container.getCenter() - mDerivedPosition; - Ogre::Radian halfLightSphereConeAngle = Math::ASin(container.getRadius() / lightSphereConeDirection.length()); - - //Check that the light cone and the light-position-to-sphere cone intersect) - Radian angleBetweenConeDirections = lightSphereConeDirection.angleBetween(mDerivedDirection); - isIntersect = angleBetweenConeDirections <= halfLightSphereConeAngle + mSpotOuter * 0.5; - } - } - } - return isIntersect; - } - - //----------------------------------------------------------------------- - bool Light::isInLightRange(const Ogre::AxisAlignedBox& container) const - { -#ifndef OGRE_NODELESS_POSITIONING - const auto& mDerivedDirection = getDerivedDirection(); - const auto& mDerivedPosition = mParentNode->_getDerivedPosition(); -#endif - bool isIntersect = true; - //Check the 2 simple / obvious situations. Light is directional or light source is inside the container - if ((mLightType != LT_DIRECTIONAL) && (container.intersects(mDerivedPosition) == false)) - { - float range = mAttenuation[0]; - //Check that the container is within the sphere of the light - isIntersect = Math::intersects(Sphere(mDerivedPosition, range),container); - //If this is a spotlight, do a more specific check - if ((isIntersect) && (mLightType == LT_SPOTLIGHT) && (mSpotOuter.valueRadians() <= Math::PI)) - { - //Create a rough bounding box around the light and check if - Quaternion localToWorld = Vector3::NEGATIVE_UNIT_Z.getRotationTo(mDerivedDirection); - - Real boxOffset = Math::Sin(mSpotOuter * 0.5) * range; - AxisAlignedBox lightBoxBound; - lightBoxBound.merge(Vector3::ZERO); - lightBoxBound.merge(localToWorld * Vector3(boxOffset, boxOffset, -range)); - lightBoxBound.merge(localToWorld * Vector3(-boxOffset, boxOffset, -range)); - lightBoxBound.merge(localToWorld * Vector3(-boxOffset, -boxOffset, -range)); - lightBoxBound.merge(localToWorld * Vector3(boxOffset, -boxOffset, -range)); - lightBoxBound.setMaximum(lightBoxBound.getMaximum() + mDerivedPosition); - lightBoxBound.setMinimum(lightBoxBound.getMinimum() + mDerivedPosition); - isIntersect = lightBoxBound.intersects(container); - - //If the bounding box check succeeded do one more test - if (isIntersect) - { - //Check intersection again with the bounding sphere of the container - //Helpful for when the light is at an angle near one of the vertexes of the bounding box - isIntersect = isInLightRange(Sphere(container.getCenter(), - container.getHalfSize().length())); - } - } - } - return isIntersect; - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - const String MOT_LIGHT = "Light"; - //----------------------------------------------------------------------- - const String& LightFactory::getType(void) const - { - return MOT_LIGHT; - } - //----------------------------------------------------------------------- - MovableObject* LightFactory::createInstanceImpl( const String& name, - const NameValuePairList* params) - { - - Light* light = OGRE_NEW Light(name); - - if(params) - { - NameValuePairList::const_iterator ni; - - // Setting the light type first before any property specific to a certain light type - if ((ni = params->find("type")) != params->end()) - { - if (ni->second == "point") - light->setType(Light::LT_POINT); - else if (ni->second == "directional") - light->setType(Light::LT_DIRECTIONAL); - else if (ni->second == "spotlight") - light->setType(Light::LT_SPOTLIGHT); - else - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Invalid light type '" + ni->second + "'.", - "LightFactory::createInstance"); - } - - // Common properties - //if ((ni = params->find("position")) != params->end()) - // light->setPosition(StringConverter::parseVector3(ni->second)); - - //if ((ni = params->find("direction")) != params->end()) - // light->setDirection(StringConverter::parseVector3(ni->second)); - - if ((ni = params->find("diffuseColour")) != params->end()) - light->setDiffuseColour(StringConverter::parseColourValue(ni->second)); - - if ((ni = params->find("specularColour")) != params->end()) - light->setSpecularColour(StringConverter::parseColourValue(ni->second)); - - if ((ni = params->find("attenuation")) != params->end()) - { - Vector4 attenuation = StringConverter::parseVector4(ni->second); - light->setAttenuation(attenuation.x, attenuation.y, attenuation.z, attenuation.w); - } - - if ((ni = params->find("castShadows")) != params->end()) - light->setCastShadows(StringConverter::parseBool(ni->second)); - - if ((ni = params->find("visible")) != params->end()) - light->setVisible(StringConverter::parseBool(ni->second)); - - if ((ni = params->find("powerScale")) != params->end()) - light->setPowerScale(StringConverter::parseReal(ni->second)); - - if ((ni = params->find("shadowFarDistance")) != params->end()) - light->setShadowFarDistance(StringConverter::parseReal(ni->second)); - - - // Spotlight properties - if ((ni = params->find("spotlightInner")) != params->end()) - light->setSpotlightInnerAngle(StringConverter::parseAngle(ni->second)); - - if ((ni = params->find("spotlightOuter")) != params->end()) - light->setSpotlightOuterAngle(StringConverter::parseAngle(ni->second)); - - if ((ni = params->find("spotlightFalloff")) != params->end()) - light->setSpotlightFalloff(StringConverter::parseReal(ni->second)); - } - - return light; - } -} // Namespace diff --git a/OgreMain/src/OgreLodStrategy.cpp b/OgreMain/src/OgreLodStrategy.cpp deleted file mode 100644 index e5da951f664..00000000000 --- a/OgreMain/src/OgreLodStrategy.cpp +++ /dev/null @@ -1,165 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" -#include "OgreLodStrategy.h" - -namespace Ogre { - //----------------------------------------------------------------------- - LodStrategy::LodStrategy(const String& name) - : mName(name) - { } - //----------------------------------------------------------------------- - LodStrategy::~LodStrategy() - { } - //----------------------------------------------------------------------- - Real LodStrategy::transformUserValue(Real userValue) const - { - // No transformation by default - return userValue; - } - //----------------------------------------------------------------------- - Real LodStrategy::getValue(const MovableObject *movableObject, const Camera *camera) const - { - // Just return implementation with LOD camera - return getValueImpl(movableObject, camera->getLodCamera()); - } - //----------------------------------------------------------------------- - void LodStrategy::assertSorted(const Mesh::LodValueList &values) const - { - assert(isSorted(values) && "The LOD values must be sorted"); - } - //--------------------------------------------------------------------- - bool LodStrategy::isSortedAscending(const Mesh::LodValueList& values) - { - Mesh::LodValueList::const_iterator it = values.begin(); - Real prev = (*it); - for (++it; it != values.end(); ++it) - { - Real cur = (*it); - if (cur < prev) - return false; - prev = cur; - } - - return true; - } - //--------------------------------------------------------------------- - bool LodStrategy::isSortedDescending(const Mesh::LodValueList& values) - { - Mesh::LodValueList::const_iterator it = values.begin(); - Real prev = (*it); - for (++it; it != values.end(); ++it) - { - Real cur = (*it); - if (cur > prev) - return false; - prev = cur; - } - - return true; - } - //--------------------------------------------------------------------- - void LodStrategy::sortAscending(Mesh::MeshLodUsageList& meshLodUsageList) - { - // Perform standard sort - std::sort(meshLodUsageList.begin(), meshLodUsageList.end(), - [](const MeshLodUsage& mesh1, const MeshLodUsage& mesh2) { return mesh1.value < mesh2.value; }); - } - //--------------------------------------------------------------------- - void LodStrategy::sortDescending(Mesh::MeshLodUsageList& meshLodUsageList) - { - // Perform standard sort - std::sort(meshLodUsageList.begin(), meshLodUsageList.end(), - [](const MeshLodUsage& mesh1, const MeshLodUsage& mesh2) { return mesh1.value > mesh2.value; }); - } - //--------------------------------------------------------------------- - ushort LodStrategy::getIndexAscending(Real value, const Mesh::MeshLodUsageList& meshLodUsageList) - { - ushort index = 0; - for (auto& m : meshLodUsageList) - { - if (m.value > value) - { - return index ? index - 1 : 0; - } - ++index; - } - - // If we fall all the way through, use the highest value - return static_cast(meshLodUsageList.size() - 1); - } - //--------------------------------------------------------------------- - ushort LodStrategy::getIndexDescending(Real value, const Mesh::MeshLodUsageList& meshLodUsageList) - { - ushort index = 0; - for (auto& m : meshLodUsageList) - { - if (m.value < value) - { - return index ? index - 1 : 0; - } - ++index; - } - - // If we fall all the way through, use the highest value - return static_cast(meshLodUsageList.size() - 1); - } - //--------------------------------------------------------------------- - ushort LodStrategy::getIndexAscending(Real value, const Material::LodValueList& materialLodValueList) - { - unsigned short index = 0; - for (auto& m : materialLodValueList) - { - if (m > value) - { - return index ? index - 1 : 0; - } - ++index; - } - - // If we fall all the way through, use the highest value - return static_cast(materialLodValueList.size() - 1); - } - //--------------------------------------------------------------------- - ushort LodStrategy::getIndexDescending(Real value, const Material::LodValueList& materialLodValueList) - { - unsigned short index = 0; - for (auto& m : materialLodValueList) - { - if (m < value) - { - return index ? index - 1 : 0; - } - ++index; - } - - // If we fall all the way through, use the highest value - return static_cast(materialLodValueList.size() - 1); - } -} // namespace diff --git a/OgreMain/src/OgreLodStrategyManager.cpp b/OgreMain/src/OgreLodStrategyManager.cpp deleted file mode 100644 index 01380d60b8b..00000000000 --- a/OgreMain/src/OgreLodStrategyManager.cpp +++ /dev/null @@ -1,153 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" -#include "OgreLodStrategyManager.h" - -#include "OgreDistanceLodStrategy.h" -#include "OgrePixelCountLodStrategy.h" - -namespace Ogre { - //----------------------------------------------------------------------- - template<> LodStrategyManager* Singleton::msSingleton = 0; - LodStrategyManager* LodStrategyManager::getSingletonPtr(void) - { - return msSingleton; - } - LodStrategyManager& LodStrategyManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //----------------------------------------------------------------------- - LodStrategyManager::LodStrategyManager() - { - // Add distance strategies for bounding box and bounding sphere - LodStrategy *strategy = OGRE_NEW DistanceLodBoxStrategy(); - addStrategy(strategy); - strategy = OGRE_NEW DistanceLodSphereStrategy(); - addStrategy(strategy); - - // Set the default strategy to distance_sphere - setDefaultStrategy(strategy); - - // Add pixel-count strategies (internally based on bounding sphere) - strategy = OGRE_NEW AbsolutePixelCountLodStrategy(); - addStrategy(strategy); - strategy = OGRE_NEW ScreenRatioPixelCountLodStrategy(); - addStrategy(strategy); - } - //----------------------------------------------------------------------- - LodStrategyManager::~LodStrategyManager() - { - // Destroy all strategies and clear the map - removeAllStrategies(); - } - //----------------------------------------------------------------------- - void LodStrategyManager::addStrategy(LodStrategy *strategy) - { - // Check for invalid strategy name - if (strategy->getName() == "default") - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Lod strategy name must not be \"default\".", "LodStrategyManager::addStrategy"); - - // Insert the strategy into the map with its name as the key - mStrategies.insert(std::make_pair(strategy->getName(), strategy)); - } - //----------------------------------------------------------------------- - LodStrategy *LodStrategyManager::removeStrategy(const String& name) - { - // Find strategy with specified name - StrategyMap::iterator it = mStrategies.find(name); - - // If not found, return null - if (it == mStrategies.end()) - return 0; - - LodStrategy *strat = it->second; - - // Otherwise, erase the strategy from the map - mStrategies.erase(it); - - // Return the strategy that was removed - return strat; - } - //----------------------------------------------------------------------- - void LodStrategyManager::removeAllStrategies() - { - // Get beginning iterator - for (auto & s : mStrategies) - { - OGRE_DELETE s.second; - } - mStrategies.clear(); - } - //----------------------------------------------------------------------- - LodStrategy *LodStrategyManager::getStrategy(const String& name) - { - // If name is "default", return the default strategy instead of performing a lookup - if (name == "default") { - return getDefaultStrategy(); - } else if (name == "Distance") { - return getStrategy("distance_box"); // Backward compatibility for loading old meshes. - } else if (name == "PixelCount") { - return getStrategy("pixel_count"); // Backward compatibility for loading old meshes. - } - // Find strategy with specified name - StrategyMap::iterator it = mStrategies.find(name); - - // If not found, return null - if (it == mStrategies.end()) - return 0; - - // Otherwise, return the strategy - return it->second; - } - //----------------------------------------------------------------------- - void LodStrategyManager::setDefaultStrategy(LodStrategy *strategy) - { - mDefaultStrategy = strategy; - } - //----------------------------------------------------------------------- - void LodStrategyManager::setDefaultStrategy(const String& name) - { - // Lookup by name and set default strategy - setDefaultStrategy(getStrategy(name)); - } - //----------------------------------------------------------------------- - LodStrategy *LodStrategyManager::getDefaultStrategy() - { - return mDefaultStrategy; - } - //----------------------------------------------------------------------- - MapIterator LodStrategyManager::getIterator() - { - // Construct map iterator from strategy map and return - return MapIterator(mStrategies); - } - //----------------------------------------------------------------------- - -} diff --git a/OgreMain/src/OgreLog.cpp b/OgreMain/src/OgreLog.cpp deleted file mode 100644 index 7131ff4cc86..00000000000 --- a/OgreMain/src/OgreLog.cpp +++ /dev/null @@ -1,204 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT -# include -# if _WIN32_WINNT >= _WIN32_WINNT_VISTA -# include -# endif -#endif - -// LogMessageLevel + LoggingLevel > OGRE_LOG_THRESHOLD = message logged -#define OGRE_LOG_THRESHOLD 4 - -namespace { - const char* RED = "\x1b[31;1m"; - const char* YELLOW = "\x1b[33;1m"; - const char* RESET = "\x1b[0m"; -} - -namespace Ogre -{ - //----------------------------------------------------------------------- - Log::Log( const String& name, bool debuggerOutput, bool suppressFile ) : - mLogLevel(LML_NORMAL), mDebugOut(debuggerOutput), - mSuppressFile(suppressFile), mTimeStamp(true), mLogName(name), mTermHasColours(false) - { - if (!mSuppressFile) - { - mLog.open(name.c_str()); - -#if (OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT) && _WIN32_WINNT >= _WIN32_WINNT_VISTA - // Register log file to be collected by Windows Error Reporting - const int utf16Length = ::MultiByteToWideChar(CP_ACP, 0, name.c_str(), (int)name.size(), NULL, 0); - if(utf16Length > 0) - { - std::wstring wname; - wname.resize(utf16Length); - if (0 != ::MultiByteToWideChar(CP_ACP, 0, name.c_str(), (int)name.size(), &wname[0], (int)wname.size())) - WerRegisterFile(wname.c_str(), WerRegFileTypeOther, WER_FILE_ANONYMOUS_DATA); - } -#endif - } - -#if OGRE_PLATFORM != OGRE_PLATFORM_WINRT - char* val = getenv("OGRE_MIN_LOGLEVEL"); - int min_lml; - if(val && StringConverter::parse(val, min_lml)) - setMinLogLevel(LogMessageLevel(min_lml)); - - if(mDebugOut) - { - val = getenv("TERM"); - mTermHasColours = val && String(val).find("xterm") != String::npos; - } -#endif - } - //----------------------------------------------------------------------- - Log::~Log() - { - OGRE_LOCK_AUTO_MUTEX; - if (!mSuppressFile) - { - mLog.close(); - } - } - - //----------------------------------------------------------------------- - void Log::logMessage( const String& message, LogMessageLevel lml, bool maskDebug ) - { - OGRE_LOCK_AUTO_MUTEX; - if (lml >= mLogLevel) - { - bool skipThisMessage = false; - for(auto & l : mListeners) - l->messageLogged( message, lml, maskDebug, mLogName, skipThisMessage); - - if (!skipThisMessage) - { - if (mDebugOut && !maskDebug) - { -# if (OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT) && OGRE_DEBUG_MODE - OutputDebugStringA("Ogre: "); - OutputDebugStringA(message.c_str()); - OutputDebugStringA("\n"); -# endif - - std::ostream& os = int(lml) >= int(LML_WARNING) ? std::cerr : std::cout; - - if(mTermHasColours) { - if(lml == LML_WARNING) - os << YELLOW; - if(lml == LML_CRITICAL) - os << RED; - } - - os << message; - - if(mTermHasColours) { - os << RESET; - } - - os << std::endl; - } - - // Write time into log - if (!mSuppressFile) - { - if (mTimeStamp) - { - struct tm *pTime; - time_t ctTime; time(&ctTime); - pTime = localtime( &ctTime ); - mLog << std::setw(2) << std::setfill('0') << pTime->tm_hour - << ":" << std::setw(2) << std::setfill('0') << pTime->tm_min - << ":" << std::setw(2) << std::setfill('0') << pTime->tm_sec - << ": "; - } - mLog << message << std::endl; - - // Flush stcmdream to ensure it is written (incase of a crash, we need log to be up to date) - mLog.flush(); - } - } - } - } - - //----------------------------------------------------------------------- - void Log::setTimeStampEnabled(bool timeStamp) - { - OGRE_LOCK_AUTO_MUTEX; - mTimeStamp = timeStamp; - } - - //----------------------------------------------------------------------- - void Log::setDebugOutputEnabled(bool debugOutput) - { - OGRE_LOCK_AUTO_MUTEX; - mDebugOut = debugOutput; - } - - //----------------------------------------------------------------------- - void Log::setLogDetail(LoggingLevel ll) - { - OGRE_LOCK_AUTO_MUTEX; - mLogLevel = LogMessageLevel(OGRE_LOG_THRESHOLD - ll); - } - - void Log::setMinLogLevel(LogMessageLevel lml) - { - OGRE_LOCK_AUTO_MUTEX; - mLogLevel = lml; - } - - //----------------------------------------------------------------------- - void Log::addListener(LogListener* listener) - { - OGRE_LOCK_AUTO_MUTEX; - if (std::find(mListeners.begin(), mListeners.end(), listener) == mListeners.end()) - mListeners.push_back(listener); - } - - //----------------------------------------------------------------------- - void Log::removeListener(LogListener* listener) - { - OGRE_LOCK_AUTO_MUTEX; - mtLogListener::iterator i = std::find(mListeners.begin(), mListeners.end(), listener); - if (i != mListeners.end()) - mListeners.erase(i); - } - //--------------------------------------------------------------------- - Log::Stream Log::stream(LogMessageLevel lml, bool maskDebug) - { - return Stream(this, lml, maskDebug); - - } -} diff --git a/OgreMain/src/OgreLogManager.cpp b/OgreMain/src/OgreLogManager.cpp deleted file mode 100644 index 1503eb90209..00000000000 --- a/OgreMain/src/OgreLogManager.cpp +++ /dev/null @@ -1,169 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -namespace Ogre { - - //----------------------------------------------------------------------- - template<> LogManager* Singleton::msSingleton = 0; - LogManager* LogManager::getSingletonPtr(void) - { - return msSingleton; - } - LogManager& LogManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //----------------------------------------------------------------------- - LogManager::LogManager() - { - mDefaultLog = NULL; - } - //----------------------------------------------------------------------- - LogManager::~LogManager() - { - OGRE_LOCK_AUTO_MUTEX; - // Destroy all logs - LogList::iterator i; - for (i = mLogs.begin(); i != mLogs.end(); ++i) - { - OGRE_DELETE i->second; - } - } - //----------------------------------------------------------------------- - Log* LogManager::createLog( const String& name, bool defaultLog, bool debuggerOutput, - bool suppressFileOutput) - { - OGRE_LOCK_AUTO_MUTEX; - - Log* newLog = OGRE_NEW Log(name, debuggerOutput, suppressFileOutput); - - if( !mDefaultLog || defaultLog ) - { - mDefaultLog = newLog; - } - - mLogs.emplace(name, newLog); - - return newLog; - } - //----------------------------------------------------------------------- - Log* LogManager::getDefaultLog() - { - OGRE_LOCK_AUTO_MUTEX; - return mDefaultLog; - } - //----------------------------------------------------------------------- - Log* LogManager::setDefaultLog(Log* newLog) - { - OGRE_LOCK_AUTO_MUTEX; - Log* oldLog = mDefaultLog; - mDefaultLog = newLog; - return oldLog; - } - //----------------------------------------------------------------------- - Log* LogManager::getLog( const String& name) - { - OGRE_LOCK_AUTO_MUTEX; - LogList::iterator i = mLogs.find(name); - OgreAssert(i != mLogs.end(), "Log not found"); - return i->second; - } - //----------------------------------------------------------------------- - void LogManager::destroyLog(const String& name) - { - LogList::iterator i = mLogs.find(name); - if (i != mLogs.end()) - { - if (mDefaultLog == i->second) - { - mDefaultLog = 0; - } - OGRE_DELETE i->second; - mLogs.erase(i); - } - - // Set another default log if this one removed - if (!mDefaultLog && !mLogs.empty()) - { - mDefaultLog = mLogs.begin()->second; - } - } - //----------------------------------------------------------------------- - void LogManager::destroyLog(Log* log) - { - OgreAssert(log, "Cannot destroy a null log"); - destroyLog(log->getName()); - } - //----------------------------------------------------------------------- - void LogManager::logMessage( const String& message, LogMessageLevel lml, bool maskDebug) - { - OGRE_LOCK_AUTO_MUTEX; - if (mDefaultLog) - { - mDefaultLog->logMessage(message, lml, maskDebug); - } - } - - void LogManager::logError(const String& message, bool maskDebug ) - { - stream(LML_CRITICAL, maskDebug) << "Error: " << message; - } - - void LogManager::logWarning(const String& message, bool maskDebug ) - { - stream(LML_WARNING, maskDebug) << "Warning: " << message; - } - //----------------------------------------------------------------------- - void LogManager::setLogDetail(LoggingLevel ll) - { - OGRE_LOCK_AUTO_MUTEX; - if (mDefaultLog) - { - OGRE_IGNORE_DEPRECATED_BEGIN - mDefaultLog->setLogDetail(ll); - OGRE_IGNORE_DEPRECATED_END - } - } - //----------------------------------------------------------------------- - void LogManager::setMinLogLevel(LogMessageLevel lml) - { - OGRE_LOCK_AUTO_MUTEX; - if (mDefaultLog) - { - mDefaultLog->setMinLogLevel(lml); - } - } - //--------------------------------------------------------------------- - Log::Stream LogManager::stream(LogMessageLevel lml, bool maskDebug) - { - OGRE_LOCK_AUTO_MUTEX; - OgreAssert(mDefaultLog, "Default log not found"); - return mDefaultLog->stream(lml, maskDebug); - } -} diff --git a/OgreMain/src/OgreManualObject.cpp b/OgreMain/src/OgreManualObject.cpp deleted file mode 100644 index 515ac11a1b1..00000000000 --- a/OgreMain/src/OgreManualObject.cpp +++ /dev/null @@ -1,749 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreEdgeListBuilder.h" - -namespace Ogre { - -#define TEMP_INITIAL_SIZE 50 -#define TEMP_VERTEXSIZE_GUESS sizeof(float) * 12 -#define TEMP_INITIAL_VERTEX_SIZE TEMP_VERTEXSIZE_GUESS * TEMP_INITIAL_SIZE -#define TEMP_INITIAL_INDEX_SIZE sizeof(uint32) * TEMP_INITIAL_SIZE - //----------------------------------------------------------------------------- -ManualObject::ManualObject(const String& name) - : MovableObject(name), mBufferUsage(HBU_GPU_ONLY), mCurrentSection(0), - mCurrentUpdating(false), mFirstVertex(true), mTempVertexPending(false), mTempVertexBuffer(0), - mTempVertexSize(TEMP_INITIAL_VERTEX_SIZE), mTempIndexBuffer(0), - mTempIndexSize(TEMP_INITIAL_INDEX_SIZE), mDeclSize(0), mEstVertexCount(0), mEstIndexCount(0), - mTexCoordIndex(0), mRadius(0), mAnyIndexed(false), mEdgeList(0), mUseIdentityProjection(false), - mUseIdentityView(false), mKeepDeclarationOrder(false) -{ - } - //----------------------------------------------------------------------------- - ManualObject::~ManualObject() - { - clear(); - } - //----------------------------------------------------------------------------- - void ManualObject::clear(void) - { - resetTempAreas(); - for (auto & i : mSectionList) - { - OGRE_DELETE i; - } - mSectionList.clear(); - mRadius = 0; - mAABB.setNull(); - OGRE_DELETE mEdgeList; - mEdgeList = 0; - mAnyIndexed = false; - - clearShadowRenderableList(mShadowRenderables); - } - //----------------------------------------------------------------------------- - void ManualObject::resetTempAreas(void) - { - OGRE_FREE(mTempVertexBuffer, MEMCATEGORY_GEOMETRY); - OGRE_FREE(mTempIndexBuffer, MEMCATEGORY_GEOMETRY); - mTempVertexBuffer = 0; - mTempIndexBuffer = 0; - mTempVertexSize = TEMP_INITIAL_VERTEX_SIZE; - mTempIndexSize = TEMP_INITIAL_INDEX_SIZE; - } - //----------------------------------------------------------------------------- - void ManualObject::resizeTempVertexBufferIfNeeded(size_t numVerts) - { - // Calculate byte size - // Use decl if we know it by now, otherwise default size to pos/norm/texcoord*2 - size_t newSize = (mFirstVertex ? TEMP_VERTEXSIZE_GUESS : mDeclSize) * numVerts; - - if(newSize <= mTempVertexSize && mTempVertexBuffer) { - return; - } - - // init or increase to at least double current - newSize = std::max(newSize, mTempVertexBuffer ? mTempVertexSize*2 : mTempVertexSize); - - // copy old data - char* tmp = mTempVertexBuffer; - mTempVertexBuffer = OGRE_ALLOC_T(char, newSize, MEMCATEGORY_GEOMETRY); - if (tmp) - { - memcpy(mTempVertexBuffer, tmp, mTempVertexSize); - // delete old buffer - OGRE_FREE(tmp, MEMCATEGORY_GEOMETRY); - } - mTempVertexSize = newSize; - } - //----------------------------------------------------------------------------- - void ManualObject::resizeTempIndexBufferIfNeeded(size_t numInds) - { - size_t newSize = numInds * sizeof(uint32); - - if(newSize <= mTempIndexSize && mTempIndexBuffer) { - return; - } - - // init or increase to at least double current - newSize = std::max(newSize, mTempIndexBuffer ? mTempIndexSize*2 : mTempIndexSize); - - numInds = newSize / sizeof(uint32); - uint32* tmp = mTempIndexBuffer; - mTempIndexBuffer = OGRE_ALLOC_T(uint32, numInds, MEMCATEGORY_GEOMETRY); - if (tmp) - { - memcpy(mTempIndexBuffer, tmp, mTempIndexSize); - OGRE_FREE(tmp, MEMCATEGORY_GEOMETRY); - } - mTempIndexSize = newSize; - } - //----------------------------------------------------------------------------- - void ManualObject::estimateVertexCount(uint32 vcount) - { - resizeTempVertexBufferIfNeeded(vcount); - mEstVertexCount = vcount; - } - //----------------------------------------------------------------------------- - void ManualObject::estimateIndexCount(uint32 icount) - { - resizeTempIndexBufferIfNeeded(icount); - mEstIndexCount = icount; - } - //----------------------------------------------------------------------------- - void ManualObject::begin(const String& materialName, - RenderOperation::OperationType opType, const String& groupName) - { - OgreAssert(!mCurrentSection, "You cannot call begin() again until after you call end()"); - - // Check that a valid material was provided - MaterialPtr material = MaterialManager::getSingleton().getByName(materialName, groupName); - - if(!material) - { - logMaterialNotFound(materialName, groupName, "ManualObject", mName); - material = MaterialManager::getSingleton().getDefaultMaterial(); - } - - mCurrentSection = OGRE_NEW ManualObjectSection(this, material, opType); - mCurrentUpdating = false; - mCurrentSection->setUseIdentityProjection(mUseIdentityProjection); - mCurrentSection->setUseIdentityView(mUseIdentityView); - mSectionList.push_back(mCurrentSection); - mFirstVertex = true; - mDeclSize = 0; - mTexCoordIndex = 0; - } - //----------------------------------------------------------------------------- - void ManualObject::begin(const MaterialPtr& mat, RenderOperation::OperationType opType) - { - OgreAssert(!mCurrentSection, "You cannot call begin() again until after you call end()"); - - if (mat) - { - mCurrentSection = OGRE_NEW ManualObjectSection(this, mat, opType); - } - else - { - LogManager::getSingleton().logMessage("Can't assign null material", LML_CRITICAL); - const MaterialPtr defaultMat = MaterialManager::getSingleton().getDefaultMaterial(); - mCurrentSection = OGRE_NEW ManualObjectSection(this, defaultMat, opType); - } - - mCurrentUpdating = false; - mCurrentSection->setUseIdentityProjection(mUseIdentityProjection); - mCurrentSection->setUseIdentityView(mUseIdentityView); - mSectionList.push_back(mCurrentSection); - mFirstVertex = true; - mDeclSize = 0; - mTexCoordIndex = 0; - } - //----------------------------------------------------------------------------- - void ManualObject::beginUpdate(size_t sectionIndex) - { - OgreAssert(!mCurrentSection, "You cannot call begin() again until after you call end()"); - mCurrentSection = mSectionList.at(sectionIndex); - mCurrentUpdating = true; - mFirstVertex = true; - mTexCoordIndex = 0; - // reset vertex & index count - RenderOperation* rop = mCurrentSection->getRenderOperation(); - rop->vertexData->vertexCount = 0; - if (rop->indexData) - rop->indexData->indexCount = 0; - rop->useIndexes = false; - mDeclSize = rop->vertexData->vertexDeclaration->getVertexSize(0); - } - //----------------------------------------------------------------------------- - void ManualObject::declareElement(VertexElementType t, VertexElementSemantic s) - { - // defining declaration - ushort idx = s == VES_TEXTURE_COORDINATES ? mTexCoordIndex : 0; - mDeclSize += mCurrentSection->getRenderOperation() - ->vertexData->vertexDeclaration->addElement(0, mDeclSize, t, s, idx) - .getSize(); - } - //----------------------------------------------------------------------------- - size_t ManualObject::getCurrentVertexCount() const - { - if (!mCurrentSection) - return 0; - - RenderOperation* rop = mCurrentSection->getRenderOperation(); - - // There's an unfinished vertex being defined, so include it in count - if (mTempVertexPending) - return rop->vertexData->vertexCount + 1; - else - return rop->vertexData->vertexCount; - - } - //----------------------------------------------------------------------------- - size_t ManualObject::getCurrentIndexCount() const - { - if (!mCurrentSection) - return 0; - - RenderOperation* rop = mCurrentSection->getRenderOperation(); - if (rop->indexData) - return rop->indexData->indexCount; - else - return 0; - - } - //----------------------------------------------------------------------------- - void ManualObject::copyTempVertexToBuffer(void) - { - mTempVertexPending = false; - RenderOperation* rop = mCurrentSection->getRenderOperation(); - if (rop->vertexData->vertexCount == 0 && !mCurrentUpdating) - { - // first vertex, autoorganise decl - VertexDeclaration* oldDcl = rop->vertexData->vertexDeclaration; - rop->vertexData->vertexDeclaration = - oldDcl->getAutoOrganisedDeclaration(false, false, false); - HardwareBufferManager::getSingleton().destroyVertexDeclaration(oldDcl); - } - resizeTempVertexBufferIfNeeded(++rop->vertexData->vertexCount); - - // get base pointer - char* pBase = mTempVertexBuffer + (mDeclSize * (rop->vertexData->vertexCount-1)); - const VertexDeclaration::VertexElementList& elemList = - rop->vertexData->vertexDeclaration->getElements(); - for (const auto & elem : elemList) - { - float* pFloat = 0; - RGBA* pRGBA = 0; - switch(elem.getType()) - { - case VET_FLOAT1: - case VET_FLOAT2: - case VET_FLOAT3: - case VET_FLOAT4: - OgreAssert(elem.getSemantic() != VES_COLOUR, "must use VET_UBYTE4_NORM"); - elem.baseVertexPointerToElement(pBase, &pFloat); - break; - case VET_UBYTE4_NORM: - OgreAssert(elem.getSemantic() == VES_COLOUR, "must use VES_COLOUR"); - elem.baseVertexPointerToElement(pBase, &pRGBA); - break; - default: - OgreAssert(false, "invalid element type"); - break; - }; - - unsigned short dims; - switch(elem.getSemantic()) - { - case VES_POSITION: - memcpy(pFloat, mTempVertex.position.ptr(), sizeof(Vector3f)); - break; - case VES_NORMAL: - memcpy(pFloat, mTempVertex.normal.ptr(), sizeof(Vector3f)); - break; - case VES_TANGENT: - memcpy(pFloat, mTempVertex.tangent.ptr(), sizeof(Vector3f)); - break; - case VES_TEXTURE_COORDINATES: - dims = VertexElement::getTypeCount(elem.getType()); - memcpy(pFloat, mTempVertex.texCoord[elem.getIndex()].ptr(), sizeof(float)*dims); - break; - case VES_COLOUR: - *pRGBA = mTempVertex.colour.getAsBYTE(); - break; - default: - OgreAssert(false, "invalid semantic"); - break; - }; - - } - - } - //----------------------------------------------------------------------------- - ManualObject::ManualObjectSection* ManualObject::end(void) - { - OgreAssert(mCurrentSection, "You cannot call end() until after you call begin()"); - if (mTempVertexPending) - { - // bake current vertex - copyTempVertexToBuffer(); - } - - // pointer that will be returned - ManualObjectSection* result = NULL; - - RenderOperation* rop = mCurrentSection->getRenderOperation(); - // Check for empty content - if (rop->vertexData->vertexCount == 0 || - (rop->useIndexes && rop->indexData->indexCount == 0)) - { - // You're wasting my time sonny - if (mCurrentUpdating) - { - // Can't just undo / remove since may be in the middle - // Just allow counts to be 0, will not be issued to renderer - - // return the finished section (though it has zero vertices) - result = mCurrentSection; - } - else - { - // First creation, can really undo - // Has already been added to section list end, so remove - mSectionList.pop_back(); - OGRE_DELETE mCurrentSection; - - } - } - else // not an empty section - { - - // Bake the real buffers - HardwareVertexBufferSharedPtr vbuf; - // Check buffer sizes - bool vbufNeedsCreating = true; - bool ibufNeedsCreating = rop->useIndexes; - // Work out if we require 16 or 32-bit index buffers - HardwareIndexBuffer::IndexType indexType = mCurrentSection->get32BitIndices()? - HardwareIndexBuffer::IT_32BIT : HardwareIndexBuffer::IT_16BIT; - if (mCurrentUpdating) - { - // May be able to reuse buffers, check sizes - vbuf = rop->vertexData->vertexBufferBinding->getBuffer(0); - if (vbuf->getNumVertices() >= rop->vertexData->vertexCount) - vbufNeedsCreating = false; - - if (rop->useIndexes) - { - if ((rop->indexData->indexBuffer->getNumIndexes() >= rop->indexData->indexCount) && - (indexType == rop->indexData->indexBuffer->getType())) - ibufNeedsCreating = false; - } - - } - if (vbufNeedsCreating) - { - // Make the vertex buffer larger if estimated vertex count higher - // to allow for user-configured growth area - size_t vertexCount = std::max(rop->vertexData->vertexCount, - mEstVertexCount); - vbuf = HardwareBufferManager::getSingleton().createVertexBuffer(mDeclSize, vertexCount, - mBufferUsage); - rop->vertexData->vertexBufferBinding->setBinding(0, vbuf); - } - if (ibufNeedsCreating) - { - // Make the index buffer larger if estimated index count higher - // to allow for user-configured growth area - size_t indexCount = std::max(rop->indexData->indexCount, mEstIndexCount); - rop->indexData->indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( - indexType, indexCount, mBufferUsage); - } - // Write vertex data - vbuf->writeData( - 0, rop->vertexData->vertexCount * vbuf->getVertexSize(), - mTempVertexBuffer, true); - // Write index data - if(rop->useIndexes) - { - if (HardwareIndexBuffer::IT_32BIT == indexType) - { - // direct copy from the mTempIndexBuffer - rop->indexData->indexBuffer->writeData( - 0, - rop->indexData->indexCount - * rop->indexData->indexBuffer->getIndexSize(), - mTempIndexBuffer, true); - } - else //(HardwareIndexBuffer::IT_16BIT == indexType) - { - HardwareBufferLockGuard indexLock(rop->indexData->indexBuffer, HardwareBuffer::HBL_DISCARD); - uint16* pIdx = static_cast(indexLock.pData); - uint32* pSrc = mTempIndexBuffer; - for (size_t i = 0; i < rop->indexData->indexCount; i++) - { - *pIdx++ = static_cast(*pSrc++); - } - } - } - - // return the finished section - result = mCurrentSection; - - } // empty section check - - mCurrentSection = 0; - resetTempAreas(); - - // Tell parent if present - if (mParentNode) - { - mParentNode->needUpdate(); - } - - // will return the finished section or NULL if - // the section was empty (i.e. zero vertices/indices) - return result; - } - //----------------------------------------------------------------------------- - MeshPtr ManualObject::convertToMesh(const String& meshName, const String& groupName) - { - OgreAssert(!mCurrentSection, "You cannot call convertToMesh() whilst you are in the middle of " - "defining the object; call end() first."); - OgreAssert(!mSectionList.empty(), "No data defined to convert to a mesh."); - - MeshPtr m = MeshManager::getSingleton().createManual(meshName, groupName); - - for (auto sec : mSectionList) - { - SubMesh* sm = m->createSubMesh(); - sec->convertToSubMesh(sm); - sm->setMaterial(sec->getMaterial()); - } - // update bounds - m->_setBounds(mAABB); - m->_setBoundingSphereRadius(mRadius); - - m->load(); - - return m; - } - //----------------------------------------------------------------------------- - void ManualObject::setUseIdentityProjection(bool useIdentityProjection) - { - // Set existing - for (auto & i : mSectionList) - { - i->setUseIdentityProjection(useIdentityProjection); - } - - // Save setting for future sections - mUseIdentityProjection = useIdentityProjection; - } - //----------------------------------------------------------------------------- - void ManualObject::setUseIdentityView(bool useIdentityView) - { - // Set existing - for (auto & i : mSectionList) - { - i->setUseIdentityView(useIdentityView); - } - - // Save setting for future sections - mUseIdentityView = useIdentityView; - } - //----------------------------------------------------------------------------- - const String& ManualObject::getMovableType(void) const - { - return MOT_MANUAL_OBJECT; - } - //----------------------------------------------------------------------------- - void ManualObject::_updateRenderQueue(RenderQueue* queue) - { - // To be used when order of creation must be kept while rendering - unsigned short priority = queue->getDefaultRenderablePriority(); - - for (auto & i : mSectionList) - { - // Skip empty sections (only happens if non-empty first, then updated) - RenderOperation* rop = i->getRenderOperation(); - if (rop->vertexData->vertexCount == 0 || - (rop->useIndexes && rop->indexData->indexCount == 0)) - continue; - - if (mRenderQueuePrioritySet) - { - assert(mRenderQueueIDSet == true); - queue->addRenderable(i, mRenderQueueID, mRenderQueuePriority); - } - else if (mRenderQueueIDSet) - queue->addRenderable(i, mRenderQueueID, mKeepDeclarationOrder ? priority++ : queue->getDefaultRenderablePriority()); - else - queue->addRenderable(i, queue->getDefaultQueueGroup(), mKeepDeclarationOrder ? priority++ : queue->getDefaultRenderablePriority()); - } - } - //----------------------------------------------------------------------------- - void ManualObject::visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables) - { - for (auto & i : mSectionList) - { - visitor->visit(i, 0, false); - } - - } - //----------------------------------------------------------------------------- - EdgeData* ManualObject::getEdgeList(void) - { - // Build on demand - if (!mEdgeList && mAnyIndexed) - { - EdgeListBuilder eb; - size_t vertexSet = 0; - bool anyBuilt = false; - for (auto & i : mSectionList) - { - RenderOperation* rop = i->getRenderOperation(); - // Only indexed triangle geometry supported for stencil shadows - if (rop->useIndexes && rop->indexData->indexCount != 0 && - (rop->operationType == RenderOperation::OT_TRIANGLE_FAN || - rop->operationType == RenderOperation::OT_TRIANGLE_LIST || - rop->operationType == RenderOperation::OT_TRIANGLE_STRIP)) - { - eb.addVertexData(rop->vertexData); - eb.addIndexData(rop->indexData, vertexSet++); - anyBuilt = true; - } - } - - if (anyBuilt) - mEdgeList = eb.build(); - - } - return mEdgeList; - } - //----------------------------------------------------------------------------- - const ShadowRenderableList& ManualObject::getShadowVolumeRenderableList( - const Light* light, const HardwareIndexBufferPtr& indexBuffer, size_t& indexBufferUsedSize, - float extrusionDistance, int flags) - { - EdgeData* edgeList = getEdgeList(); - if (!edgeList) - { - return mShadowRenderables; - } - - // Calculate the object space light details - Vector4 lightPos = light->getAs4DVector(); - Affine3 world2Obj = mParentNode->_getFullTransform().inverse(); - lightPos = world2Obj * lightPos; - Matrix3 world2Obj3x3 = world2Obj.linear(); - extrusionDistance *= Math::Sqrt(std::min(std::min(world2Obj3x3.GetColumn(0).squaredLength(), world2Obj3x3.GetColumn(1).squaredLength()), world2Obj3x3.GetColumn(2).squaredLength())); - - // Init shadow renderable list if required (only allow indexed) - bool init = mShadowRenderables.empty() && mAnyIndexed; - bool extrude = flags & SRF_EXTRUDE_IN_SOFTWARE; - - EdgeData::EdgeGroupList::iterator egi; - ShadowRenderableList::iterator si, siend; - SectionList::iterator seci; - if (init) - mShadowRenderables.resize(edgeList->edgeGroups.size()); - - siend = mShadowRenderables.end(); - egi = edgeList->edgeGroups.begin(); - seci = mSectionList.begin(); - for (si = mShadowRenderables.begin(); si != siend; ++seci) - { - // Skip non-indexed geometry - if (!(*seci)->getRenderOperation()->useIndexes) - { - continue; - } - - if (init) - { - // Create a new renderable, create a separate light cap if - // we're using a vertex program (either for this model, or - // for extruding the shadow volume) since otherwise we can - // get depth-fighting on the light cap - MaterialPtr mat = (*seci)->getMaterial(); - mat->load(); - bool vertexProgram = false; - Technique* t = mat->getBestTechnique(0, *seci); - for (auto pass : t->getPasses()) - { - if (pass->hasVertexProgram()) - { - vertexProgram = true; - break; - } - } - *si = OGRE_NEW ShadowRenderable(this, indexBuffer, egi->vertexData, - vertexProgram || !extrude); - } - // Extrude vertices in software if required - if (extrude) - { - extrudeVertices((*si)->getPositionBuffer(), egi->vertexData->vertexCount, lightPos, - extrusionDistance); - } - - ++si; - ++egi; - } - // Calc triangle light facing - updateEdgeListLightFacing(edgeList, lightPos); - - // Generate indexes and update renderables - generateShadowVolume(edgeList, indexBuffer, indexBufferUsedSize, light, mShadowRenderables, flags); - - return mShadowRenderables; - } - //----------------------------------------------------------------------------- - //----------------------------------------------------------------------------- - //----------------------------------------------------------------------------- - ManualObject::ManualObjectSection::ManualObjectSection(ManualObject* parent, - const String& materialName, RenderOperation::OperationType opType, const String & groupName) - : mParent(parent), mMaterialName(materialName), mGroupName(groupName), m32BitIndices(false) - { - mRenderOperation.operationType = opType; - // default to no indexes unless we're told - mRenderOperation.useIndexes = false; - mRenderOperation.useGlobalInstancing = false; - mRenderOperation.vertexData = OGRE_NEW VertexData(); - mRenderOperation.vertexData->vertexCount = 0; - } - ManualObject::ManualObjectSection::ManualObjectSection(ManualObject* parent, - const MaterialPtr& mat, RenderOperation::OperationType opType) - : mParent(parent), mMaterial(mat), m32BitIndices(false) - { - assert(mMaterial); - mMaterialName = mMaterial->getName(); - mGroupName = mMaterial->getGroup(); - - mRenderOperation.operationType = opType; - mRenderOperation.useIndexes = false; - mRenderOperation.useGlobalInstancing = false; - mRenderOperation.vertexData = OGRE_NEW VertexData(); - mRenderOperation.vertexData->vertexCount = 0; - } - //----------------------------------------------------------------------------- - ManualObject::ManualObjectSection::~ManualObjectSection() - { - OGRE_DELETE mRenderOperation.vertexData; - OGRE_DELETE mRenderOperation.indexData; // ok to delete 0 - } - //----------------------------------------------------------------------------- - RenderOperation* ManualObject::ManualObjectSection::getRenderOperation(void) - { - return &mRenderOperation; - } - //----------------------------------------------------------------------------- - const MaterialPtr& ManualObject::ManualObjectSection::getMaterial(void) const - { - if (!mMaterial) - { - mMaterial = static_pointer_cast(MaterialManager::getSingleton().load(mMaterialName, mGroupName)); - } - return mMaterial; - } - //----------------------------------------------------------------------------- - void ManualObject::ManualObjectSection::setMaterialName(const String& name, - const String& groupName /* = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME */) - { - if (mMaterialName != name || mGroupName != groupName) - { - mMaterialName = name; - mGroupName = groupName; - mMaterial.reset(); - } - } - //----------------------------------------------------------------------------- - void ManualObject::ManualObjectSection::setMaterial(const MaterialPtr& mat) - { - assert(mat); - mMaterial = mat; - mMaterialName = mat->getName(); - mGroupName = mat->getGroup(); - } - //----------------------------------------------------------------------------- - void ManualObject::ManualObjectSection::getRenderOperation(RenderOperation& op) - { - // direct copy - op = mRenderOperation; - } - //----------------------------------------------------------------------------- - void ManualObject::ManualObjectSection::getWorldTransforms(Matrix4* xform) const - { - xform[0] = mParent->_getParentNodeFullTransform(); - } - //----------------------------------------------------------------------------- - Real ManualObject::ManualObjectSection::getSquaredViewDepth(const Ogre::Camera *cam) const - { - Node* n = mParent->getParentNode(); - return n ? n->getSquaredViewDepth(cam) : 0; - } - //----------------------------------------------------------------------------- - const LightList& ManualObject::ManualObjectSection::getLights(void) const - { - return mParent->queryLights(); - } - //----------------------------------------------------------------------------- - void ManualObject::ManualObjectSection::convertToSubMesh(SubMesh* sm) const - { - sm->useSharedVertices = false; - sm->operationType = mRenderOperation.operationType; - // Copy vertex data; replicate buffers too - sm->vertexData = mRenderOperation.vertexData->clone(true); - - // Copy index data; replicate buffers too; delete the default, old one to avoid memory leaks - - // check if index data is present - if (mRenderOperation.indexData) - { - // Copy index data; replicate buffers too; delete the default, old one to avoid memory leaks - OGRE_DELETE sm->indexData; - sm->indexData = mRenderOperation.indexData->clone(true); - } - } - //----------------------------------------------------------------------------- - //----------------------------------------------------------------------------- - const String MOT_MANUAL_OBJECT = "ManualObject"; - //----------------------------------------------------------------------------- - const String& ManualObjectFactory::getType(void) const - { - return MOT_MANUAL_OBJECT; - } - //----------------------------------------------------------------------------- - MovableObject* ManualObjectFactory::createInstanceImpl( - const String& name, const NameValuePairList* params) - { - return OGRE_NEW ManualObject(name); - } -} diff --git a/OgreMain/src/OgreMaterial.cpp b/OgreMain/src/OgreMaterial.cpp deleted file mode 100644 index 1e19307e398..00000000000 --- a/OgreMain/src/OgreMaterial.cpp +++ /dev/null @@ -1,586 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreMaterial.h" -#include "OgreLodStrategyManager.h" -#include "OgreLodStrategy.h" - -namespace Ogre { - - //----------------------------------------------------------------------- - Material::Material(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - :Resource(creator, name, handle, group, false, NULL), - mReceiveShadows(true), - mTransparencyCastsShadows(false), - mCompilationRequired(true) - { - // Override isManual, not applicable for Material (we always want to call loadImpl) - if(isManual) - { - LogManager::getSingleton().logWarning("Material " + name + - " was requested with isManual=true, but this is not applicable " - "for materials; the flag has been reset to false"); - } - - // Initialise to default strategy - mLodStrategy = LodStrategyManager::getSingleton().getDefaultStrategy(); - - mLodValues.push_back(0.0f); - - applyDefaults(); - - /* For consistency with StringInterface, but we don't add any parameters here - That's because the Resource implementation of StringInterface is to - list all the options that need to be set before loading, of which - we have none as such. Full details can be set through scripts. - */ - createParamDictionary("Material"); - } - //----------------------------------------------------------------------- - Material::~Material() - { - removeAllTechniques(); - // have to call this here reather than in Resource destructor - // since calling virtual methods in base destructors causes crash - unload(); - } - //----------------------------------------------------------------------- - Material& Material::operator=(const Material& rhs) - { - if (this == &rhs) - return *this; - - Resource::operator=(rhs); - mReceiveShadows = rhs.mReceiveShadows; - mTransparencyCastsShadows = rhs.mTransparencyCastsShadows; - - // Copy Techniques - this->removeAllTechniques(); - for(auto *t : rhs.mTechniques) - { - Technique* tech = this->createTechnique(); - *tech = *t; - if (t->isSupported()) - { - insertSupportedTechnique(tech); - } - } - - // Also copy LOD information - mUserLodValues = rhs.mUserLodValues; - mLodValues = rhs.mLodValues; - mLodStrategy = rhs.mLodStrategy; - mCompilationRequired = rhs.mCompilationRequired; - // illumination passes are not compiled right away so - // mIsLoaded state should still be the same as the original material - assert(isLoaded() == rhs.isLoaded()); - - return *this; - } - - - //----------------------------------------------------------------------- - void Material::prepareImpl(void) - { - // compile if required - if (mCompilationRequired) - compile(); - // Load all supported techniques - for (auto *t : mSupportedTechniques) - { - t->_prepare(); - } - } - //----------------------------------------------------------------------- - void Material::unprepareImpl(void) - { - // Load all supported techniques - for (auto *t : mSupportedTechniques) - { - t->_unprepare(); - } - } - //----------------------------------------------------------------------- - void Material::loadImpl(void) - { - // Load all supported techniques - for (auto *t : mSupportedTechniques) - { - t->_load(); - } - - } - //----------------------------------------------------------------------- - void Material::unloadImpl(void) - { - // Unload all supported techniques - for (auto *t : mSupportedTechniques) - { - t->_unload(); - } - } - //----------------------------------------------------------------------- - size_t Material::calculateSize(void) const - { - size_t memSize = sizeof(*this) + Resource::calculateSize(); - - // Tally up techniques - for (auto t : mTechniques) - { - memSize += t->calculateSize(); - } - - memSize += mUnsupportedReasons.size() * sizeof(char); - - return memSize; - } - //----------------------------------------------------------------------- - MaterialPtr Material::clone(const String& newName, const String& newGroup) const - { - MaterialPtr newMat = - MaterialManager::getSingleton().create(newName, newGroup.empty() ? mGroup : newGroup); - - if(!newMat) // interception by collision handler - return newMat; - - // Keep handle (see below, copy overrides everything) - ResourceHandle newHandle = newMat->getHandle(); - // Assign values from this - *newMat = *this; - // Restore new group if required, will have been overridden by operator - if (!newGroup.empty()) - { - newMat->mGroup = newGroup; - } - - // Correct the name & handle, they get copied too - newMat->mName = newName; - newMat->mHandle = newHandle; - - //if we're cloning from a loaded material, notify the creator or otherwise size won't be right - if (newMat->getLoadingState() == LOADSTATE_LOADED) - { - // Notify manager - if (mCreator) - mCreator->_notifyResourceLoaded(newMat.get()); - } - - return newMat; - } - //----------------------------------------------------------------------- - void Material::copyDetailsTo(MaterialPtr& mat) const - { - // Keep handle (see below, copy overrides everything) - ResourceHandle savedHandle = mat->mHandle; - String savedName = mat->mName; - String savedGroup = mat->mGroup; - // Assign values from this - *mat = *this; - // Correct the name & handle, they get copied too - mat->mName = savedName; - mat->mHandle = savedHandle; - mat->mGroup = savedGroup; - } - //----------------------------------------------------------------------- - void Material::applyDefaults(void) - { - MaterialPtr defaults = MaterialManager::getSingleton().getDefaultSettings(); - - if (defaults) - { - // save name & handle - String savedName = mName; - String savedGroup = mGroup; - ResourceHandle savedHandle = mHandle; - *this = *defaults; - // restore name & handle - mName = savedName; - mHandle = savedHandle; - mGroup = savedGroup; - } - mCompilationRequired = true; - - } - //----------------------------------------------------------------------- - Technique* Material::createTechnique(void) - { - Technique *t = OGRE_NEW Technique(this); - mTechniques.push_back(t); - mCompilationRequired = true; - return t; - } - //----------------------------------------------------------------------- - Technique* Material::getTechnique(const String& name) const - { - Technique* foundTechnique = 0; - // iterate through techniques to find a match - for (auto *t : mTechniques) - { - if (t->getName() == name) - { - foundTechnique = t; - break; - } - } - - return foundTechnique; - } - //----------------------------------------------------------------------- - unsigned short Material::getNumLodLevels(unsigned short schemeIndex) const - { - // Safety check - empty list? - if (mBestTechniquesBySchemeList.empty()) - return 0; - - BestTechniquesBySchemeList::const_iterator i = - mBestTechniquesBySchemeList.find(schemeIndex); - if (i == mBestTechniquesBySchemeList.end()) - { - // get the first item, will be 0 (the default) if default - // scheme techniques exist, otherwise the earliest defined - i = mBestTechniquesBySchemeList.begin(); - } - - return static_cast(i->second.size()); - } - //----------------------------------------------------------------------- - unsigned short Material::getNumLodLevels(const String& schemeName) const - { - return getNumLodLevels( - MaterialManager::getSingleton()._getSchemeIndex(schemeName)); - } - //----------------------------------------------------------------------- - void Material::insertSupportedTechnique(Technique* t) - { - mSupportedTechniques.push_back(t); - // get scheme - unsigned short schemeIndex = t->_getSchemeIndex(); - - // Insert won't replace if supported technique for this scheme/lod is - // already there, which is what we want - mBestTechniquesBySchemeList[schemeIndex].emplace(t->getLodIndex(), t); - - } - //----------------------------------------------------------------------------- - Technique* Material::getBestTechnique(unsigned short lodIndex, const Renderable* rend) - { - if (mSupportedTechniques.empty()) - { - return NULL; - } - else - { - Technique* ret = 0; - MaterialManager& matMgr = MaterialManager::getSingleton(); - // get scheme - auto si = mBestTechniquesBySchemeList.find(matMgr._getActiveSchemeIndex()); - // scheme not found? - if (si == mBestTechniquesBySchemeList.end()) - { - // listener specified alternative technique available? - ret = matMgr._arbitrateMissingTechniqueForActiveScheme(this, lodIndex, rend); - if (ret) - return ret; - - OgreAssert(!mBestTechniquesBySchemeList.empty(), "handleSchemeNotFound() must not remove techniques"); - // Nope, use default - // get the first item, will be 0 (the default) if default - // scheme techniques exist, otherwise the earliest defined - si = mBestTechniquesBySchemeList.begin(); - } - - // get LOD - auto li = si->second.find(lodIndex); - // LOD not found? - if (li == si->second.end()) - { - // Use the next LOD level up - for (auto rli = si->second.rbegin(); rli != si->second.rend(); ++rli) - { - if (rli->second->getLodIndex() < lodIndex) - { - ret = rli->second; - break; - } - - } - if (!ret) - { - // shouldn't ever hit this really, unless user defines no LOD 0 - // pick the first LOD we have (must be at least one to have a scheme entry) - ret = si->second.begin()->second; - } - - } - else - { - // LOD found - ret = li->second; - } - - return ret; - - } - } - //----------------------------------------------------------------------- - void Material::removeTechnique(unsigned short index) - { - assert (index < mTechniques.size() && "Index out of bounds."); - Techniques::iterator i = mTechniques.begin() + index; - OGRE_DELETE(*i); - mTechniques.erase(i); - clearBestTechniqueList(); - } - //----------------------------------------------------------------------- - void Material::removeAllTechniques(void) - { - for (auto *t : mTechniques) - { - OGRE_DELETE t; - } - mTechniques.clear(); - clearBestTechniqueList(); - } - //----------------------------------------------------------------------- - Material::TechniqueIterator Material::getTechniqueIterator(void) - { - return TechniqueIterator(mTechniques.begin(), mTechniques.end()); - } - //----------------------------------------------------------------------- - Material::TechniqueIterator Material::getSupportedTechniqueIterator(void) - { - return TechniqueIterator(mSupportedTechniques.begin(), mSupportedTechniques.end()); - } - //----------------------------------------------------------------------- - bool Material::isTransparent(void) const - { - // Check each technique - for (auto *t : mTechniques) - { - if (t->isTransparent()) - return true; - } - return false; - } - //----------------------------------------------------------------------- - void Material::compile(bool autoManageTextureUnits) - { - // Compile each technique, then add it to the list of supported techniques - clearBestTechniqueList(); - mUnsupportedReasons.clear(); - - size_t techNo = 0; - for (auto *t : mTechniques) - { - String compileMessages = t->_compile(autoManageTextureUnits); - if (t->isSupported()) - { - insertSupportedTechnique(t); - } - else - { - // Log informational - StringStream str; - str << "Material " << mName << " Technique " << techNo; - if (!t->getName().empty()) - str << "(" << t->getName() << ")"; - str << " is not supported. " << compileMessages; - LogManager::getSingleton().logMessage(str.str(), LML_TRIVIAL); - mUnsupportedReasons += compileMessages; - } - ++techNo; - } - - mCompilationRequired = false; - - // Did we find any? - if (mSupportedTechniques.empty()) - { - LogManager::getSingleton().stream(LML_WARNING) - << "Warning: material " << mName << " has no supportable " - << "Techniques and will be blank. Explanation: \n" << mUnsupportedReasons; - } - } - //----------------------------------------------------------------------- - void Material::clearBestTechniqueList(void) - { - mSupportedTechniques.clear(); - mBestTechniquesBySchemeList.clear(); - mCompilationRequired = true; - } - //----------------------------------------------------------------------- - #define ALL_TECHNIQUES(fncall) for(auto t : mTechniques) t->fncall - void Material::setPointSize(Real ps) { ALL_TECHNIQUES(setPointSize(ps)); } - //----------------------------------------------------------------------- - void Material::setAmbient(float red, float green, float blue) { setAmbient(ColourValue(red, green, blue)); } - //----------------------------------------------------------------------- - void Material::setAmbient(const ColourValue& ambient) { ALL_TECHNIQUES(setAmbient(ambient)); } - //----------------------------------------------------------------------- - void Material::setDiffuse(float red, float green, float blue, float alpha) - { - ALL_TECHNIQUES(setDiffuse(red, green, blue, alpha)); - } - //----------------------------------------------------------------------- - void Material::setDiffuse(const ColourValue& diffuse) { setDiffuse(diffuse.r, diffuse.g, diffuse.b, diffuse.a); } - //----------------------------------------------------------------------- - void Material::setSpecular(float red, float green, float blue, float alpha) - { - ALL_TECHNIQUES(setSpecular(red, green, blue, alpha)); - } - //----------------------------------------------------------------------- - void Material::setSpecular(const ColourValue& specular) - { - setSpecular(specular.r, specular.g, specular.b, specular.a); - } - //----------------------------------------------------------------------- - void Material::setShininess(Real val) { ALL_TECHNIQUES(setShininess(val)); } - //----------------------------------------------------------------------- - void Material::setSelfIllumination(float red, float green, float blue) - { - setSelfIllumination(ColourValue(red, green, blue)); - } - //----------------------------------------------------------------------- - void Material::setSelfIllumination(const ColourValue& selfIllum) { ALL_TECHNIQUES(setSelfIllumination(selfIllum)); } - //----------------------------------------------------------------------- - void Material::setDepthCheckEnabled(bool enabled) { ALL_TECHNIQUES(setDepthCheckEnabled(enabled)); } - //----------------------------------------------------------------------- - void Material::setDepthWriteEnabled(bool enabled) { ALL_TECHNIQUES(setDepthWriteEnabled(enabled)); } - //----------------------------------------------------------------------- - void Material::setDepthFunction(CompareFunction func) { ALL_TECHNIQUES(setDepthFunction(func)); } - //----------------------------------------------------------------------- - void Material::setColourWriteEnabled(bool enabled) { ALL_TECHNIQUES(setColourWriteEnabled(enabled)); } - //----------------------------------------------------------------------- - void Material::setColourWriteEnabled(bool red, bool green, bool blue, bool alpha) - { - ALL_TECHNIQUES(setColourWriteEnabled(red, green, blue, alpha)); - } - //----------------------------------------------------------------------- - void Material::setCullingMode(CullingMode mode) { ALL_TECHNIQUES(setCullingMode(mode)); } - //----------------------------------------------------------------------- - void Material::setManualCullingMode(ManualCullingMode mode) { ALL_TECHNIQUES(setManualCullingMode(mode)); } - //----------------------------------------------------------------------- - void Material::setLightingEnabled(bool enabled) { ALL_TECHNIQUES(setLightingEnabled(enabled)); } - //----------------------------------------------------------------------- - void Material::setShadingMode(ShadeOptions mode) { ALL_TECHNIQUES(setShadingMode(mode)); } - //----------------------------------------------------------------------- - void Material::setFog(bool overrideScene, FogMode mode, const ColourValue& colour, Real expDensity, - Real linearStart, Real linearEnd) - { - ALL_TECHNIQUES(setFog(overrideScene, mode, colour, expDensity, linearStart, linearEnd)); - } - //----------------------------------------------------------------------- - void Material::setDepthBias(float constantBias, float slopeScaleBias) - { - ALL_TECHNIQUES(setDepthBias(constantBias, slopeScaleBias)); - } - //----------------------------------------------------------------------- - void Material::setTextureFiltering(TextureFilterOptions filterType) - { - ALL_TECHNIQUES(setTextureFiltering(filterType)); - } - // -------------------------------------------------------------------- - void Material::setTextureAnisotropy(int maxAniso) { ALL_TECHNIQUES(setTextureAnisotropy(maxAniso)); } - // -------------------------------------------------------------------- - void Material::setSceneBlending(const SceneBlendType sbt) { ALL_TECHNIQUES(setSceneBlending(sbt)); } - // -------------------------------------------------------------------- - void Material::setSeparateSceneBlending(const SceneBlendType sbt, const SceneBlendType sbta) - { - ALL_TECHNIQUES(setSeparateSceneBlending(sbt, sbta)); - } - // -------------------------------------------------------------------- - void Material::setSceneBlending(const SceneBlendFactor sourceFactor, const SceneBlendFactor destFactor) - { - ALL_TECHNIQUES(setSceneBlending(sourceFactor, destFactor)); - } - // -------------------------------------------------------------------- - void Material::setSeparateSceneBlending( const SceneBlendFactor sourceFactor, const SceneBlendFactor destFactor, const SceneBlendFactor sourceFactorAlpha, const SceneBlendFactor destFactorAlpha) - { - ALL_TECHNIQUES(setSeparateSceneBlending(sourceFactor, destFactor, sourceFactorAlpha, destFactorAlpha)); - } - #undef ALL_TECHNIQUES - // -------------------------------------------------------------------- - void Material::_notifyNeedsRecompile(void) - { - mCompilationRequired = true; - // Also need to unload to ensure we loaded any new items - if (isLoaded()) // needed to stop this being called in 'loading' state - unload(); - } - // -------------------------------------------------------------------- - void Material::setLodLevels(const LodValueList& lodValues) - { - // Square the distances for the internal list - // First, clear and add single zero entry - mLodValues.clear(); - mUserLodValues.clear(); - mUserLodValues.push_back(0); - if (mLodStrategy) - mLodValues.push_back(mLodStrategy->getBaseValue()); - for (auto& v : lodValues) - { - mUserLodValues.push_back(v); - if (mLodStrategy) - mLodValues.push_back(mLodStrategy->transformUserValue(v)); - } - } - // -------------------------------------------------------------------- - ushort Material::getLodIndex(Real value) const - { - return mLodStrategy->getIndex(value, mLodValues); - } - // -------------------------------------------------------------------- - Material::LodValueIterator Material::getLodValueIterator(void) const - { - return LodValueIterator(mLodValues.begin(), mLodValues.end()); - } - // -------------------------------------------------------------------- - Material::LodValueIterator Material::getUserLodValueIterator(void) const - { - return LodValueIterator(mUserLodValues.begin(), mUserLodValues.end()); - } - //--------------------------------------------------------------------- - const LodStrategy *Material::getLodStrategy() const - { - return mLodStrategy; - } - //--------------------------------------------------------------------- - void Material::setLodStrategy(LodStrategy *lodStrategy) - { - mLodStrategy = lodStrategy; - - assert(mLodValues.size()); - mLodValues[0] = mLodStrategy->getBaseValue(); - - // Re-transform all user LOD values (starting at index 1, no need to transform base value) - for (size_t i = 1; i < mUserLodValues.size(); ++i) - mLodValues[i] = mLodStrategy->transformUserValue(mUserLodValues[i]); - } - //--------------------------------------------------------------------- -} diff --git a/OgreMain/src/OgreMaterialManager.cpp b/OgreMain/src/OgreMaterialManager.cpp deleted file mode 100644 index 82851436add..00000000000 --- a/OgreMain/src/OgreMaterialManager.cpp +++ /dev/null @@ -1,300 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreLodStrategyManager.h" - - -namespace Ogre { - const String MSN_DEFAULT = "Default"; - const String MSN_SHADERGEN = "ShaderGeneratorDefaultScheme"; - - //----------------------------------------------------------------------- - template<> MaterialManager* Singleton::msSingleton = 0; - MaterialManager* MaterialManager::getSingletonPtr(void) - { - return msSingleton; - } - MaterialManager& MaterialManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - String MaterialManager::DEFAULT_SCHEME_NAME = MSN_DEFAULT; - //----------------------------------------------------------------------- - MaterialManager::MaterialManager() - { - // Loading order - mLoadOrder = 100.0f; - // Scripting is supported by this manager - - // Resource type - mResourceType = "Material"; - - // Register with resource group manager - ResourceGroupManager::getSingleton()._registerResourceManager(mResourceType, this); - - // Default scheme - mActiveSchemeIndex = 0; - mActiveSchemeName = MSN_DEFAULT; - mSchemes[mActiveSchemeName] = 0; - - } - //----------------------------------------------------------------------- - MaterialManager::~MaterialManager() - { - mDefaultSettings.reset(); - - Pass::processPendingPassUpdates(); // make sure pass graveyard is cleaned - - // Resources cleared by superclass - // Unregister with resource group manager - ResourceGroupManager::getSingleton()._unregisterResourceManager(mResourceType); - ResourceGroupManager::getSingleton()._unregisterScriptLoader(this); - } - //----------------------------------------------------------------------- - Resource* MaterialManager::createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* params) - { - return OGRE_NEW Material(this, name, handle, group, isManual, loader); - } - //----------------------------------------------------------------------- - MaterialPtr MaterialManager::create (const String& name, const String& group, - bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams) - { - return static_pointer_cast(createResource(name,group,isManual,loader,createParams)); - } - //----------------------------------------------------------------------- - MaterialPtr MaterialManager::getByName(const String& name, const String& groupName) const - { - return static_pointer_cast(getResourceByName(name, groupName)); - } - - MaterialPtr MaterialManager::getDefaultMaterial(bool useLighting) { - MaterialPtr ret = getByName(useLighting ? "BaseWhite" : "BaseWhiteNoLighting", - ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME); - - OgreAssert(ret, - "Can't find default material Did you forget to call MaterialManager::initialise()?"); - - return ret; - } - - //----------------------------------------------------------------------- - void MaterialManager::initialise(void) - { - // Set up default material - don't use name constructor as we want to avoid applying defaults - mDefaultSettings = create("DefaultSettings", ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME); - // Add a single technique and pass, non-programmable - mDefaultSettings->createTechnique()->createPass(); - - // Set the default LOD strategy - mDefaultSettings->setLodStrategy(LodStrategyManager::getSingleton().getDefaultStrategy()); - - // Set up a lit base white material - create("BaseWhite", ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME); - // Set up an unlit base white material - MaterialPtr baseWhiteNoLighting = create("BaseWhiteNoLighting", - ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME); - baseWhiteNoLighting->setLightingEnabled(false); - - } - //----------------------------------------------------------------------- - void MaterialManager::setDefaultTextureFiltering(TextureFilterOptions fo) - { - TextureManager::getSingleton().getDefaultSampler()->setFiltering(fo); - } - //----------------------------------------------------------------------- - void MaterialManager::setDefaultAnisotropy(unsigned int maxAniso) - { - TextureManager::getSingleton().getDefaultSampler()->setAnisotropy(maxAniso); - } - //----------------------------------------------------------------------- - unsigned int MaterialManager::getDefaultAnisotropy() const - { - return TextureManager::getSingleton().getDefaultSampler()->getAnisotropy(); - } - //----------------------------------------------------------------------- - void MaterialManager::setDefaultTextureFiltering(FilterType ftype, FilterOptions opts) - { - TextureManager::getSingleton().getDefaultSampler()->setFiltering(ftype, opts); - } - //----------------------------------------------------------------------- - void MaterialManager::setDefaultTextureFiltering(FilterOptions minFilter, - FilterOptions magFilter, FilterOptions mipFilter) - { - TextureManager::getSingleton().getDefaultSampler()->setFiltering(minFilter, magFilter, mipFilter); - } - //----------------------------------------------------------------------- - FilterOptions MaterialManager::getDefaultTextureFiltering(FilterType ftype) const - { - return TextureManager::getSingleton().getDefaultSampler()->getFiltering(ftype); - } - //----------------------------------------------------------------------- - unsigned short MaterialManager::_getSchemeIndex(const String& schemeName) - { - unsigned short ret = 0; - SchemeMap::iterator i = mSchemes.find(schemeName); - if (i != mSchemes.end()) - { - ret = i->second; - } - else - { - // Create new - ret = static_cast(mSchemes.size()); - mSchemes[schemeName] = ret; - } - return ret; - - } - //----------------------------------------------------------------------- - const String& MaterialManager::_getSchemeName(unsigned short index) - { - for (auto & scheme : mSchemes) - { - if (scheme.second == index) - return scheme.first; - } - return MSN_DEFAULT; - } - //----------------------------------------------------------------------- - void MaterialManager::setActiveScheme(const String& schemeName) - { - if (mActiveSchemeName != schemeName) - { - // Allow the creation of new scheme indexes on demand - // even if they're not specified in any Technique - mActiveSchemeIndex = _getSchemeIndex(schemeName); - mActiveSchemeName = schemeName; - } - } - //----------------------------------------------------------------------- - void MaterialManager::addListener(Listener* l, const Ogre::String& schemeName) - { - mListenerMap[schemeName].push_back(l); - } - //--------------------------------------------------------------------- - void MaterialManager::removeListener(Listener* l, const Ogre::String& schemeName) - { - mListenerMap[schemeName].remove(l); - } - //--------------------------------------------------------------------- - Technique* MaterialManager::_arbitrateMissingTechniqueForActiveScheme( - Material* mat, unsigned short lodIndex, const Renderable* rend) - { - //First, check the scheme specific listeners - ListenerMap::iterator it = mListenerMap.find(mActiveSchemeName); - if (it != mListenerMap.end()) - { - ListenerList& listenerList = it->second; - for (auto & i : listenerList) - { - Technique* t = i->handleSchemeNotFound(mActiveSchemeIndex, mActiveSchemeName, mat, lodIndex, rend); - if (t) - return t; - } - } - - //If no success, check generic listeners - it = mListenerMap.find(BLANKSTRING); - if (it != mListenerMap.end()) - { - ListenerList& listenerList = it->second; - for (auto & i : listenerList) - { - Technique* t = i->handleSchemeNotFound(mActiveSchemeIndex, mActiveSchemeName, mat, lodIndex, rend); - if (t) - return t; - } - } - - - return 0; - - } - - void MaterialManager::_notifyAfterIlluminationPassesCreated(Technique* tech) - { - // First, check the scheme specific listeners - ListenerMap::iterator it = mListenerMap.find(mActiveSchemeName); - if(it != mListenerMap.end()) - { - ListenerList& listenerList = it->second; - for(auto & i : listenerList) - { - bool handled = i->afterIlluminationPassesCreated(tech); - if(handled) - return; - } - } - - //If no success, check generic listeners - it = mListenerMap.find(BLANKSTRING); - if(it != mListenerMap.end()) - { - ListenerList& listenerList = it->second; - for(auto & i : listenerList) - { - bool handled = i->afterIlluminationPassesCreated(tech); - if(handled) - return; - } - } - } - - void MaterialManager::_notifyBeforeIlluminationPassesCleared(Technique* tech) - { - // First, check the scheme specific listeners - ListenerMap::iterator it = mListenerMap.find(mActiveSchemeName); - if(it != mListenerMap.end()) - { - ListenerList& listenerList = it->second; - for(auto & i : listenerList) - { - bool handled = i->beforeIlluminationPassesCleared(tech); - if(handled) - return; - } - } - - //If no success, check generic listeners - it = mListenerMap.find(BLANKSTRING); - if(it != mListenerMap.end()) - { - ListenerList& listenerList = it->second; - for(auto & i : listenerList) - { - bool handled = i->beforeIlluminationPassesCleared(tech); - if(handled) - return; - } - } - } - -} diff --git a/OgreMain/src/OgreMaterialSerializer.cpp b/OgreMain/src/OgreMaterialSerializer.cpp deleted file mode 100644 index 60368169caf..00000000000 --- a/OgreMain/src/OgreMaterialSerializer.cpp +++ /dev/null @@ -1,1912 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreTextureUnitState.h" -#include "OgreGpuProgramManager.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreExternalTextureSourceManager.h" -#include "OgreLodStrategyManager.h" -#include "OgreDistanceLodStrategy.h" -#include "OgreHighLevelGpuProgram.h" - -namespace Ogre -{ - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - MaterialSerializer::MaterialSerializer() - { - mDefaults = false; - mBuffer.clear(); - } - //----------------------------------------------------------------------- - void MaterialSerializer::exportMaterial(const MaterialPtr& pMat, const String &fileName, bool exportDefaults, - const bool includeProgDef, const String& programFilename, const String& materialName) - { - clearQueue(); - mDefaults = exportDefaults; - writeMaterial(pMat, materialName); - exportQueued(fileName, includeProgDef, programFilename); - } - //----------------------------------------------------------------------- - void MaterialSerializer::exportQueued(const String &fileName, const bool includeProgDef, const String& programFilename) - { - // write out gpu program definitions to the buffer - writeGpuPrograms(); - - if (mBuffer.empty()) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Queue is empty !", "MaterialSerializer::exportQueued"); - - LogManager::getSingleton().logMessage("MaterialSerializer : writing material(s) to material script : " + fileName, LML_NORMAL); - FILE *fp; - fp = fopen(fileName.c_str(), "w"); - if (!fp) - OGRE_EXCEPT(Exception::ERR_CANNOT_WRITE_TO_FILE, "Cannot create material file.", - "MaterialSerializer::export"); - - // output gpu program definitions to material script file if includeProgDef is true - if (includeProgDef && !mGpuProgramBuffer.empty()) - { - fputs(mGpuProgramBuffer.c_str(), fp); - } - - // output main buffer holding material script - fputs(mBuffer.c_str(), fp); - fclose(fp); - - // write program script if program filename and program definitions - // were not included in material script - if (!includeProgDef && !mGpuProgramBuffer.empty() && !programFilename.empty()) - { - FILE *locFp; - locFp = fopen(programFilename.c_str(), "w"); - if (!locFp) - OGRE_EXCEPT(Exception::ERR_CANNOT_WRITE_TO_FILE, "Cannot create program material file.", - "MaterialSerializer::export"); - fputs(mGpuProgramBuffer.c_str(), locFp); - fclose(locFp); - } - - LogManager::getSingleton().logMessage("MaterialSerializer : done.", LML_NORMAL); - clearQueue(); - } - //----------------------------------------------------------------------- - void MaterialSerializer::queueForExport(const MaterialPtr& pMat, - bool clearQueued, bool exportDefaults, const String& materialName) - { - if (clearQueued) - clearQueue(); - - mDefaults = exportDefaults; - writeMaterial(pMat, materialName); - } - //----------------------------------------------------------------------- - void MaterialSerializer::clearQueue() - { - mBuffer.clear(); - mGpuProgramBuffer.clear(); - mGpuProgramDefinitionContainer.clear(); - } - //----------------------------------------------------------------------- - const String &MaterialSerializer::getQueuedAsString() const - { - return mBuffer; - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeMaterial(const MaterialPtr& pMat, const String& materialName) - { - String outMaterialName; - - if (materialName.length() > 0) - { - outMaterialName = materialName; - } - else - { - outMaterialName = pMat->getName(); - } - - LogManager::getSingleton().logMessage("MaterialSerializer : writing material " + outMaterialName + " to queue.", LML_NORMAL); - - bool skipWriting = false; - - // Fire pre-write event. - fireMaterialEvent(MSE_PRE_WRITE, skipWriting, pMat.get()); - if (skipWriting) - return; - - // Material name - writeAttribute(0, "material"); - writeValue(quoteWord(outMaterialName)); - - beginSection(0); - { - // Fire write begin event. - fireMaterialEvent(MSE_WRITE_BEGIN, skipWriting, pMat.get()); - - // Write LOD information - Material::LodValueList::const_iterator valueIt = pMat->getUserLodValues().begin(); - // Skip zero value - if (!pMat->getUserLodValues().empty()) - valueIt++; - String attributeVal; - while (valueIt != pMat->getUserLodValues().end()) - { - attributeVal.append(StringConverter::toString(*valueIt++)); - if (valueIt != pMat->getUserLodValues().end()) - attributeVal.append(" "); - } - if (!attributeVal.empty()) - { - writeAttribute(1, "lod_values"); - writeValue(attributeVal); - } - - - // Shadow receive - if (mDefaults || - pMat->getReceiveShadows() != true) - { - writeAttribute(1, "receive_shadows"); - writeValue(pMat->getReceiveShadows() ? "on" : "off"); - } - - // When rendering shadows, treat transparent things as opaque? - if (mDefaults || - pMat->getTransparencyCastsShadows() == true) - { - writeAttribute(1, "transparency_casts_shadows"); - writeValue(pMat->getTransparencyCastsShadows() ? "on" : "off"); - } - - // Iterate over techniques - for(auto t : pMat->getTechniques()) - { - // skip RTSS generated techniques - if(!mDefaults && t->getSchemeName() == "ShaderGeneratorDefaultScheme") - continue; - writeTechnique(t); - mBuffer += "\n"; - } - - // Fire write end event. - fireMaterialEvent(MSE_WRITE_END, skipWriting, pMat.get()); - } - endSection(0); - mBuffer += "\n"; - - // Fire post section write event. - fireMaterialEvent(MSE_POST_WRITE, skipWriting, pMat.get()); - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeTechnique(const Technique* pTech) - { - bool skipWriting = false; - - // Fire pre-write event. - fireTechniqueEvent(MSE_PRE_WRITE, skipWriting, pTech); - if (skipWriting) - return; - - // Technique header - writeAttribute(1, "technique"); - // only output technique name if it exists. - if (!pTech->getName().empty()) - writeValue(quoteWord(pTech->getName())); - - beginSection(1); - { - // Fire write begin event. - fireTechniqueEvent(MSE_WRITE_BEGIN, skipWriting, pTech); - - // LOD index - if (mDefaults || - pTech->getLodIndex() != 0) - { - writeAttribute(2, "lod_index"); - writeValue(StringConverter::toString(pTech->getLodIndex())); - } - - // Scheme name - if (mDefaults || pTech->getSchemeName() != MSN_DEFAULT) - { - writeAttribute(2, "scheme"); - writeValue(quoteWord(pTech->getSchemeName())); - } - - // ShadowCasterMaterial name - if (pTech->getShadowCasterMaterial()) - { - writeAttribute(2, "shadow_caster_material"); - writeValue(quoteWord(pTech->getShadowCasterMaterial()->getName())); - } - // ShadowReceiverMaterial name - if (pTech->getShadowReceiverMaterial()) - { - writeAttribute(2, "shadow_receiver_material"); - writeValue(quoteWord(pTech->getShadowReceiverMaterial()->getName())); - } - // GPU vendor rules - Technique::GPUVendorRuleList::const_iterator vrit; - for (vrit = pTech->getGPUVendorRules().begin(); vrit != pTech->getGPUVendorRules().end(); ++vrit) - { - const Technique::GPUVendorRule& rule = *vrit; - writeAttribute(2, "gpu_vendor_rule"); - if (rule.includeOrExclude == Technique::INCLUDE) - writeValue("include"); - else - writeValue("exclude"); - writeValue(quoteWord(RenderSystemCapabilities::vendorToString(rule.vendor))); - } - // GPU device rules - Technique::GPUDeviceNameRuleList::const_iterator dnit; - for (dnit = pTech->getGPUDeviceNameRules().begin(); dnit != pTech->getGPUDeviceNameRules().end(); ++dnit) - { - const Technique::GPUDeviceNameRule& rule = *dnit; - writeAttribute(2, "gpu_device_rule"); - if (rule.includeOrExclude == Technique::INCLUDE) - writeValue("include"); - else - writeValue("exclude"); - writeValue(quoteWord(rule.devicePattern)); - writeValue(StringConverter::toString(rule.caseSensitive)); - } - // Iterate over passes - for(auto& p : pTech->getPasses()) - { - writePass(p); - mBuffer += "\n"; - } - - // Fire write end event. - fireTechniqueEvent(MSE_WRITE_END, skipWriting, pTech); - } - endSection(1); - - // Fire post section write event. - fireTechniqueEvent(MSE_POST_WRITE, skipWriting, pTech); - - } - //----------------------------------------------------------------------- - void MaterialSerializer::writePass(const Pass* pPass) - { - bool skipWriting = false; - - // Fire pre-write event. - firePassEvent(MSE_PRE_WRITE, skipWriting, pPass); - if (skipWriting) - return; - - writeAttribute(2, "pass"); - // only output pass name if its not the default name - if (pPass->getName() != StringConverter::toString(pPass->getIndex())) - writeValue(quoteWord(pPass->getName())); - - beginSection(2); - { - // Fire write begin event. - firePassEvent(MSE_WRITE_BEGIN, skipWriting, pPass); - - //lighting - if (mDefaults || - pPass->getLightingEnabled() != true) - { - writeAttribute(3, "lighting"); - writeValue(pPass->getLightingEnabled() ? "on" : "off"); - } - // max_lights - if (mDefaults || - pPass->getMaxSimultaneousLights() != OGRE_MAX_SIMULTANEOUS_LIGHTS) - { - writeAttribute(3, "max_lights"); - writeValue(StringConverter::toString(pPass->getMaxSimultaneousLights())); - } - // start_light - if (mDefaults || - pPass->getStartLight() != 0) - { - writeAttribute(3, "start_light"); - writeValue(StringConverter::toString(pPass->getStartLight())); - } - // iteration - if (mDefaults || - pPass->getIteratePerLight() || (pPass->getPassIterationCount() > 1)) - { - writeAttribute(3, "iteration"); - // pass iteration count - if (pPass->getPassIterationCount() > 1 || pPass->getLightCountPerIteration() > 1) - { - writeValue(StringConverter::toString(pPass->getPassIterationCount())); - if (pPass->getIteratePerLight()) - { - if (pPass->getLightCountPerIteration() > 1) - { - writeValue("per_n_lights"); - writeValue(StringConverter::toString( - pPass->getLightCountPerIteration())); - } - else - { - writeValue("per_light"); - } - } - } - else - { - writeValue(pPass->getIteratePerLight() ? "once_per_light" : "once"); - } - - if (pPass->getIteratePerLight() && pPass->getRunOnlyForOneLightType()) - { - switch (pPass->getOnlyLightType()) - { - case Light::LT_DIRECTIONAL: - writeValue("directional"); - break; - case Light::LT_POINT: - writeValue("point"); - break; - case Light::LT_SPOTLIGHT: - writeValue("spot"); - break; - case Light::LT_RECTLIGHT: - writeValue("rect"); - break; - }; - } - } - - if(mDefaults || pPass->getLightMask() != 0xFFFFFFFF) - { - writeAttribute(3, "light_mask"); - writeValue(StringConverter::toString(pPass->getLightMask())); - } - - if (pPass->getLightingEnabled()) - { - // Ambient - if (mDefaults || - pPass->getAmbient().r != 1 || - pPass->getAmbient().g != 1 || - pPass->getAmbient().b != 1 || - pPass->getAmbient().a != 1 || - (pPass->getVertexColourTracking() & TVC_AMBIENT)) - { - writeAttribute(3, "ambient"); - if (pPass->getVertexColourTracking() & TVC_AMBIENT) - writeValue("vertexcolour"); - else - writeColourValue(pPass->getAmbient(), true); - } - - // Diffuse - if (mDefaults || - pPass->getDiffuse().r != 1 || - pPass->getDiffuse().g != 1 || - pPass->getDiffuse().b != 1 || - pPass->getDiffuse().a != 1 || - (pPass->getVertexColourTracking() & TVC_DIFFUSE)) - { - writeAttribute(3, "diffuse"); - if (pPass->getVertexColourTracking() & TVC_DIFFUSE) - writeValue("vertexcolour"); - else - writeColourValue(pPass->getDiffuse(), true); - } - - // Specular - if (mDefaults || - pPass->getSpecular().r != 0 || - pPass->getSpecular().g != 0 || - pPass->getSpecular().b != 0 || - pPass->getSpecular().a != 1 || - pPass->getShininess() != 0 || - (pPass->getVertexColourTracking() & TVC_SPECULAR)) - { - writeAttribute(3, "specular"); - if (pPass->getVertexColourTracking() & TVC_SPECULAR) - { - writeValue("vertexcolour"); - } - else - { - writeColourValue(pPass->getSpecular(), true); - } - writeValue(StringConverter::toString(pPass->getShininess())); - - } - - // Emissive - if (mDefaults || - pPass->getSelfIllumination().r != 0 || - pPass->getSelfIllumination().g != 0 || - pPass->getSelfIllumination().b != 0 || - pPass->getSelfIllumination().a != 1 || - (pPass->getVertexColourTracking() & TVC_EMISSIVE)) - { - writeAttribute(3, "emissive"); - if (pPass->getVertexColourTracking() & TVC_EMISSIVE) - writeValue("vertexcolour"); - else - writeColourValue(pPass->getSelfIllumination(), true); - } - } - - // Point size - if (mDefaults || - pPass->getPointSize() != 1.0) - { - writeAttribute(3, "point_size"); - writeValue(StringConverter::toString(pPass->getPointSize())); - } - - // Point sprites - if (mDefaults || - pPass->getPointSpritesEnabled()) - { - writeAttribute(3, "point_sprites"); - writeValue(pPass->getPointSpritesEnabled() ? "on" : "off"); - } - - // Point attenuation - if (mDefaults || - pPass->isPointAttenuationEnabled()) - { - writeAttribute(3, "point_size_attenuation"); - writeValue(pPass->isPointAttenuationEnabled() ? "on" : "off"); - if (pPass->isPointAttenuationEnabled() && - (pPass->getPointAttenuationConstant() != 0.0 || - pPass->getPointAttenuationLinear() != 1.0 || - pPass->getPointAttenuationQuadratic() != 0.0)) - { - writeValue(StringConverter::toString(pPass->getPointAttenuationConstant())); - writeValue(StringConverter::toString(pPass->getPointAttenuationLinear())); - writeValue(StringConverter::toString(pPass->getPointAttenuationQuadratic())); - } - } - - // Point min size - if (mDefaults || - pPass->getPointMinSize() != 0.0) - { - writeAttribute(3, "point_size_min"); - writeValue(StringConverter::toString(pPass->getPointMinSize())); - } - - // Point max size - if (mDefaults || - pPass->getPointMaxSize() != 0.0) - { - writeAttribute(3, "point_size_max"); - writeValue(StringConverter::toString(pPass->getPointMaxSize())); - } - - // scene blend factor - if (mDefaults || - pPass->getSourceBlendFactor() != SBF_ONE || - pPass->getDestBlendFactor() != SBF_ZERO || - pPass->getSourceBlendFactorAlpha() != SBF_ONE || - pPass->getDestBlendFactorAlpha() != SBF_ZERO) - { - writeAttribute(3, "separate_scene_blend"); - writeSceneBlendFactor(pPass->getSourceBlendFactor(), pPass->getDestBlendFactor(), - pPass->getSourceBlendFactorAlpha(), pPass->getDestBlendFactorAlpha()); - } - - - //depth check - if (mDefaults || - pPass->getDepthCheckEnabled() != true) - { - writeAttribute(3, "depth_check"); - writeValue(pPass->getDepthCheckEnabled() ? "on" : "off"); - } - // alpha_rejection - if (mDefaults || - pPass->getAlphaRejectFunction() != CMPF_ALWAYS_PASS || - pPass->getAlphaRejectValue() != 0) - { - writeAttribute(3, "alpha_rejection"); - writeCompareFunction(pPass->getAlphaRejectFunction()); - writeValue(StringConverter::toString(pPass->getAlphaRejectValue())); - } - // alpha_to_coverage - if (mDefaults || - pPass->isAlphaToCoverageEnabled()) - { - writeAttribute(3, "alpha_to_coverage"); - writeValue(pPass->isAlphaToCoverageEnabled() ? "on" : "off"); - } - // transparent_sorting - if (mDefaults || - pPass->getTransparentSortingForced() == true || - pPass->getTransparentSortingEnabled() != true) - { - writeAttribute(3, "transparent_sorting"); - writeValue(pPass->getTransparentSortingForced() ? "force" : - (pPass->getTransparentSortingEnabled() ? "on" : "off")); - } - - - //depth write - if (mDefaults || - pPass->getDepthWriteEnabled() != true) - { - writeAttribute(3, "depth_write"); - writeValue(pPass->getDepthWriteEnabled() ? "on" : "off"); - } - - //depth function - if (mDefaults || - pPass->getDepthFunction() != CMPF_LESS_EQUAL) - { - writeAttribute(3, "depth_func"); - writeCompareFunction(pPass->getDepthFunction()); - } - - //depth bias - if (mDefaults || - pPass->getDepthBiasConstant() != 0 || - pPass->getDepthBiasSlopeScale() != 0) - { - writeAttribute(3, "depth_bias"); - writeValue(StringConverter::toString(pPass->getDepthBiasConstant())); - writeValue(StringConverter::toString(pPass->getDepthBiasSlopeScale())); - } - //iteration depth bias - if (mDefaults || - pPass->getIterationDepthBias() != 0) - { - writeAttribute(3, "iteration_depth_bias"); - writeValue(StringConverter::toString(pPass->getIterationDepthBias())); - } - - //light scissor - if (mDefaults || - pPass->getLightScissoringEnabled() != false) - { - writeAttribute(3, "light_scissor"); - writeValue(pPass->getLightScissoringEnabled() ? "on" : "off"); - } - - //light clip planes - if (mDefaults || - pPass->getLightClipPlanesEnabled() != false) - { - writeAttribute(3, "light_clip_planes"); - writeValue(pPass->getLightClipPlanesEnabled() ? "on" : "off"); - } - - // illumination stage - if (pPass->getIlluminationStage() != IS_UNKNOWN) - { - writeAttribute(3, "illumination_stage"); - switch(pPass->getIlluminationStage()) - { - case IS_AMBIENT: - writeValue("ambient"); - break; - case IS_PER_LIGHT: - writeValue("per_light"); - break; - case IS_DECAL: - writeValue("decal"); - break; - case IS_UNKNOWN: - break; - }; - } - - // hardware culling mode - if (mDefaults || - pPass->getCullingMode() != CULL_CLOCKWISE) - { - CullingMode hcm = pPass->getCullingMode(); - writeAttribute(3, "cull_hardware"); - switch (hcm) - { - case CULL_NONE : - writeValue("none"); - break; - case CULL_CLOCKWISE : - writeValue("clockwise"); - break; - case CULL_ANTICLOCKWISE : - writeValue("anticlockwise"); - break; - } - } - - // software culling mode - if (mDefaults || - pPass->getManualCullingMode() != MANUAL_CULL_BACK) - { - ManualCullingMode scm = pPass->getManualCullingMode(); - writeAttribute(3, "cull_software"); - switch (scm) - { - case MANUAL_CULL_NONE : - writeValue("none"); - break; - case MANUAL_CULL_BACK : - writeValue("back"); - break; - case MANUAL_CULL_FRONT : - writeValue("front"); - break; - } - } - - //shading - if (mDefaults || - pPass->getShadingMode() != SO_GOURAUD) - { - writeAttribute(3, "shading"); - switch (pPass->getShadingMode()) - { - case SO_FLAT: - writeValue("flat"); - break; - case SO_GOURAUD: - writeValue("gouraud"); - break; - case SO_PHONG: - writeValue("phong"); - break; - } - } - - - if (mDefaults || - pPass->getPolygonMode() != PM_SOLID) - { - writeAttribute(3, "polygon_mode"); - switch (pPass->getPolygonMode()) - { - case PM_POINTS: - writeValue("points"); - break; - case PM_WIREFRAME: - writeValue("wireframe"); - break; - case PM_SOLID: - writeValue("solid"); - break; - } - } - - // polygon mode overrideable - if (mDefaults || - !pPass->getPolygonModeOverrideable()) - { - writeAttribute(3, "polygon_mode_overrideable"); - writeValue(pPass->getPolygonModeOverrideable() ? "on" : "off"); - } - - //fog override - if (mDefaults || - pPass->getFogOverride() != false) - { - writeAttribute(3, "fog_override"); - writeValue(pPass->getFogOverride() ? "true" : "false"); - if (pPass->getFogOverride()) - { - switch (pPass->getFogMode()) - { - case FOG_NONE: - writeValue("none"); - break; - case FOG_LINEAR: - writeValue("linear"); - break; - case FOG_EXP2: - writeValue("exp2"); - break; - case FOG_EXP: - writeValue("exp"); - break; - } - - if (pPass->getFogMode() != FOG_NONE) - { - writeColourValue(pPass->getFogColour()); - writeValue(StringConverter::toString(pPass->getFogDensity())); - writeValue(StringConverter::toString(pPass->getFogStart())); - writeValue(StringConverter::toString(pPass->getFogEnd())); - } - } - } - - // GPU Vertex and Fragment program references and parameters - if (pPass->hasVertexProgram()) - { - writeVertexProgramRef(pPass); - } - - if (pPass->hasFragmentProgram()) - { - writeFragmentProgramRef(pPass); - } - - if(pPass->hasTessellationHullProgram()) - { - writeTesselationHullProgramRef(pPass); - } - - if(pPass->hasTessellationDomainProgram()) - { - writeTesselationDomainProgramRef(pPass); - } - - if (pPass->hasGeometryProgram()) - { - writeGeometryProgramRef(pPass); - } - - // Nested texture layers - for(auto& s : pPass->getTextureUnitStates()) - { - writeTextureUnit(s); - } - - // Fire write end event. - firePassEvent(MSE_WRITE_END, skipWriting, pPass); - } - endSection(2); - - // Fire post section write event. - firePassEvent(MSE_POST_WRITE, skipWriting, pPass); - - LogManager::getSingleton().logMessage("MaterialSerializer : done.", LML_NORMAL); - } - //----------------------------------------------------------------------- - String MaterialSerializer::convertFiltering(FilterOptions fo) - { - switch (fo) - { - case FO_NONE: - return "none"; - case FO_POINT: - return "point"; - case FO_LINEAR: - return "linear"; - case FO_ANISOTROPIC: - return "anisotropic"; - } - - return "point"; - } - //----------------------------------------------------------------------- - static String convertTexAddressMode(TextureAddressingMode tam) - { - switch (tam) - { - case TextureUnitState::TAM_BORDER: - return "border"; - case TextureUnitState::TAM_CLAMP: - return "clamp"; - case TextureUnitState::TAM_MIRROR: - return "mirror"; - case TextureUnitState::TAM_WRAP: - return "wrap"; - } - - return "wrap"; - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeTextureUnit(const TextureUnitState *pTex) - { - bool skipWriting = false; - - // Fire pre-write event. - fireTextureUnitStateEvent(MSE_PRE_WRITE, skipWriting, pTex); - if (skipWriting) - return; - - LogManager::getSingleton().logMessage("MaterialSerializer : parsing texture layer.", LML_NORMAL); - mBuffer += "\n"; - writeAttribute(3, "texture_unit"); - // only write out name if its not equal to the default name - if (pTex->getName() != StringConverter::toString(pTex->getParent()->getTextureUnitStateIndex(pTex))) - writeValue(quoteWord(pTex->getName())); - - beginSection(3); - { - // Fire write begin event. - fireTextureUnitStateEvent(MSE_WRITE_BEGIN, skipWriting, pTex); - - OGRE_IGNORE_DEPRECATED_BEGIN - // texture_alias - if (!pTex->getTextureNameAlias().empty() && pTex->getTextureNameAlias() != pTex->getName()) - { - writeAttribute(4, "texture_alias"); - writeValue(quoteWord(pTex->getTextureNameAlias())); - } - OGRE_IGNORE_DEPRECATED_END - - //texture name - if (pTex->getNumFrames() == 1 && !pTex->getTextureName().empty()) - { - writeAttribute(4, "texture"); - writeValue(quoteWord(pTex->getTextureName())); - - switch (pTex->getTextureType()) - { - case TEX_TYPE_1D: - writeValue("1d"); - break; - case TEX_TYPE_2D: - // nothing, this is the default - break; - case TEX_TYPE_2D_ARRAY: - writeValue("2darray"); - break; - case TEX_TYPE_3D: - writeValue("3d"); - break; - case TEX_TYPE_CUBE_MAP: - writeValue("cubic"); - break; - default: - break; - }; - - if (uint32(pTex->getNumMipmaps()) != TextureManager::getSingleton().getDefaultNumMipmaps()) - { - writeValue(StringConverter::toString(pTex->getNumMipmaps())); - } - - if (pTex->getDesiredFormat() != PF_UNKNOWN) - { - writeValue(PixelUtil::getFormatName(pTex->getDesiredFormat())); - } - } - - //anim. texture - if (pTex->getNumFrames() > 1) - { - writeAttribute(4, "anim_texture"); - for (unsigned int n = 0; n < pTex->getNumFrames(); n++) - writeValue(quoteWord(pTex->getFrameTextureName(n))); - writeValue(StringConverter::toString(pTex->getAnimationDuration())); - } - - //anisotropy level - if (mDefaults || - pTex->getTextureAnisotropy() != 1) - { - writeAttribute(4, "max_anisotropy"); - writeValue(StringConverter::toString(pTex->getTextureAnisotropy())); - } - - //texture coordinate set - if (mDefaults || - pTex->getTextureCoordSet() != 0) - { - writeAttribute(4, "tex_coord_set"); - writeValue(StringConverter::toString(pTex->getTextureCoordSet())); - } - - //addressing mode - const Sampler::UVWAddressingMode& uvw = - pTex->getTextureAddressingMode(); - if (mDefaults || - uvw.u != Ogre::TextureUnitState::TAM_WRAP || - uvw.v != Ogre::TextureUnitState::TAM_WRAP || - uvw.w != Ogre::TextureUnitState::TAM_WRAP ) - { - writeAttribute(4, "tex_address_mode"); - if (uvw.u == uvw.v && uvw.u == uvw.w) - { - writeValue(convertTexAddressMode(uvw.u)); - } - else - { - writeValue(convertTexAddressMode(uvw.u)); - writeValue(convertTexAddressMode(uvw.v)); - if (uvw.w != TextureUnitState::TAM_WRAP) - { - writeValue(convertTexAddressMode(uvw.w)); - } - } - } - - //border colour - const ColourValue& borderColour = - pTex->getTextureBorderColour(); - if (mDefaults || - borderColour != ColourValue::Black) - { - writeAttribute(4, "tex_border_colour"); - writeColourValue(borderColour, true); - } - - //filtering - if (TextureManager::getSingletonPtr() && (mDefaults || !pTex->isDefaultFiltering())) - { - writeAttribute(4, "filtering"); - writeValue( - convertFiltering(pTex->getTextureFiltering(FT_MIN)) - + " " - + convertFiltering(pTex->getTextureFiltering(FT_MAG)) - + " " - + convertFiltering(pTex->getTextureFiltering(FT_MIP))); - } - - // Mip biasing - if (mDefaults || - pTex->getTextureMipmapBias() != 0.0f) - { - writeAttribute(4, "mipmap_bias"); - writeValue( - StringConverter::toString(pTex->getTextureMipmapBias())); - } - - // colour_op_ex - if (mDefaults || - pTex->getColourBlendMode().operation != LBX_MODULATE || - pTex->getColourBlendMode().source1 != LBS_TEXTURE || - pTex->getColourBlendMode().source2 != LBS_CURRENT) - { - writeAttribute(4, "colour_op_ex"); - writeLayerBlendOperationEx(pTex->getColourBlendMode().operation); - writeLayerBlendSource(pTex->getColourBlendMode().source1); - writeLayerBlendSource(pTex->getColourBlendMode().source2); - if (pTex->getColourBlendMode().operation == LBX_BLEND_MANUAL) - writeValue(StringConverter::toString(pTex->getColourBlendMode().factor)); - if (pTex->getColourBlendMode().source1 == LBS_MANUAL) - writeColourValue(pTex->getColourBlendMode().colourArg1, false); - if (pTex->getColourBlendMode().source2 == LBS_MANUAL) - writeColourValue(pTex->getColourBlendMode().colourArg2, false); - - //colour_op_multipass_fallback - writeAttribute(4, "colour_op_multipass_fallback"); - writeSceneBlendFactor(pTex->getColourBlendFallbackSrc()); - writeSceneBlendFactor(pTex->getColourBlendFallbackDest()); - } - - // alpha_op_ex - if (mDefaults || - pTex->getAlphaBlendMode().operation != LBX_MODULATE || - pTex->getAlphaBlendMode().source1 != LBS_TEXTURE || - pTex->getAlphaBlendMode().source2 != LBS_CURRENT) - { - writeAttribute(4, "alpha_op_ex"); - writeLayerBlendOperationEx(pTex->getAlphaBlendMode().operation); - writeLayerBlendSource(pTex->getAlphaBlendMode().source1); - writeLayerBlendSource(pTex->getAlphaBlendMode().source2); - if (pTex->getAlphaBlendMode().operation == LBX_BLEND_MANUAL) - writeValue(StringConverter::toString(pTex->getAlphaBlendMode().factor)); - else if (pTex->getAlphaBlendMode().source1 == LBS_MANUAL) - writeValue(StringConverter::toString(pTex->getAlphaBlendMode().alphaArg1)); - else if (pTex->getAlphaBlendMode().source2 == LBS_MANUAL) - writeValue(StringConverter::toString(pTex->getAlphaBlendMode().alphaArg2)); - } - - bool individualTransformElems = false; - // rotate - if (mDefaults || - pTex->getTextureRotate() != Radian(0)) - { - writeAttribute(4, "rotate"); - writeValue(StringConverter::toString(pTex->getTextureRotate().valueDegrees())); - individualTransformElems = true; - } - - // scroll - if (mDefaults || - pTex->getTextureUScroll() != 0 || - pTex->getTextureVScroll() != 0 ) - { - writeAttribute(4, "scroll"); - writeValue(StringConverter::toString(pTex->getTextureUScroll())); - writeValue(StringConverter::toString(pTex->getTextureVScroll())); - individualTransformElems = true; - } - // scale - if (mDefaults || - pTex->getTextureUScale() != 1.0 || - pTex->getTextureVScale() != 1.0 ) - { - writeAttribute(4, "scale"); - writeValue(StringConverter::toString(pTex->getTextureUScale())); - writeValue(StringConverter::toString(pTex->getTextureVScale())); - individualTransformElems = true; - } - - // free transform - if (!individualTransformElems && - (mDefaults || - pTex->getTextureTransform() != Matrix4::IDENTITY)) - { - writeAttribute(4, "transform"); - const Matrix4& xform = pTex->getTextureTransform(); - for (int row = 0; row < 4; ++row) - { - for (int col = 0; col < 4; ++col) - { - writeValue(StringConverter::toString(xform[row][col])); - } - } - } - - // Used to store the u and v speeds of scroll animation effects - float scrollAnimU = 0; - float scrollAnimV = 0; - - EffectMap effMap = pTex->getEffects(); - if (!effMap.empty()) - { - EffectMap::const_iterator it; - for (it = effMap.begin(); it != effMap.end(); ++it) - { - const TextureUnitState::TextureEffect& ef = it->second; - switch (ef.type) - { - case TextureUnitState::ET_ENVIRONMENT_MAP : - writeEnvironmentMapEffect(ef, pTex); - break; - case TextureUnitState::ET_ROTATE : - writeRotationEffect(ef, pTex); - break; - case TextureUnitState::ET_UVSCROLL : - scrollAnimU = scrollAnimV = ef.arg1; - break; - case TextureUnitState::ET_USCROLL : - scrollAnimU = ef.arg1; - break; - case TextureUnitState::ET_VSCROLL : - scrollAnimV = ef.arg1; - break; - case TextureUnitState::ET_TRANSFORM : - writeTransformEffect(ef, pTex); - break; - default: - break; - } - } - } - - // u and v scroll animation speeds merged, if present serialize scroll_anim - if(scrollAnimU || scrollAnimV) { - TextureUnitState::TextureEffect texEffect; - texEffect.arg1 = scrollAnimU; - texEffect.arg2 = scrollAnimV; - writeScrollEffect(texEffect, pTex); - } - - // Content type - if (mDefaults || - pTex->getContentType() != TextureUnitState::CONTENT_NAMED) - { - writeAttribute(4, "content_type"); - switch(pTex->getContentType()) - { - case TextureUnitState::CONTENT_NAMED: - writeValue("named"); - break; - case TextureUnitState::CONTENT_SHADOW: - writeValue("shadow"); - break; - case TextureUnitState::CONTENT_COMPOSITOR: - writeValue("compositor"); - writeValue(quoteWord(pTex->getReferencedCompositorName())); - writeValue(quoteWord(pTex->getReferencedTextureName())); - writeValue(StringConverter::toString(pTex->getReferencedMRTIndex())); - break; - }; - } - - // Fire write end event. - fireTextureUnitStateEvent(MSE_WRITE_END, skipWriting, pTex); - } - endSection(3); - - // Fire post section write event. - fireTextureUnitStateEvent(MSE_POST_WRITE, skipWriting, pTex); - - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeEnvironmentMapEffect(const TextureUnitState::TextureEffect& effect, const TextureUnitState *pTex) - { - writeAttribute(4, "env_map"); - switch (effect.subtype) - { - case TextureUnitState::ENV_PLANAR: - writeValue("planar"); - break; - case TextureUnitState::ENV_CURVED: - writeValue("spherical"); - break; - case TextureUnitState::ENV_NORMAL: - writeValue("cubic_normal"); - break; - case TextureUnitState::ENV_REFLECTION: - writeValue("cubic_reflection"); - break; - } - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeRotationEffect(const TextureUnitState::TextureEffect& effect, const TextureUnitState *pTex) - { - if (effect.arg1) - { - writeAttribute(4, "rotate_anim"); - writeValue(StringConverter::toString(effect.arg1)); - } - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeTransformEffect(const TextureUnitState::TextureEffect& effect, const TextureUnitState *pTex) - { - writeAttribute(4, "wave_xform"); - - switch (effect.subtype) - { - case TextureUnitState::TT_ROTATE: - writeValue("rotate"); - break; - case TextureUnitState::TT_SCALE_U: - writeValue("scale_x"); - break; - case TextureUnitState::TT_SCALE_V: - writeValue("scale_y"); - break; - case TextureUnitState::TT_TRANSLATE_U: - writeValue("scroll_x"); - break; - case TextureUnitState::TT_TRANSLATE_V: - writeValue("scroll_y"); - break; - } - - switch (effect.waveType) - { - case WFT_INVERSE_SAWTOOTH: - writeValue("inverse_sawtooth"); - break; - case WFT_SAWTOOTH: - writeValue("sawtooth"); - break; - case WFT_SINE: - writeValue("sine"); - break; - case WFT_SQUARE: - writeValue("square"); - break; - case WFT_TRIANGLE: - writeValue("triangle"); - break; - case WFT_PWM: - writeValue("pwm"); - break; - } - - writeValue(StringConverter::toString(effect.base)); - writeValue(StringConverter::toString(effect.frequency)); - writeValue(StringConverter::toString(effect.phase)); - writeValue(StringConverter::toString(effect.amplitude)); - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeScrollEffect( - const TextureUnitState::TextureEffect& effect, const TextureUnitState *pTex) - { - if (effect.arg1 || effect.arg2) - { - writeAttribute(4, "scroll_anim"); - writeValue(StringConverter::toString(effect.arg1)); - writeValue(StringConverter::toString(effect.arg2)); - } - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeSceneBlendFactor(const SceneBlendFactor sbf) - { - switch (sbf) - { - case SBF_DEST_ALPHA: - writeValue("dest_alpha"); - break; - case SBF_DEST_COLOUR: - writeValue("dest_colour"); - break; - case SBF_ONE: - writeValue("one"); - break; - case SBF_ONE_MINUS_DEST_ALPHA: - writeValue("one_minus_dest_alpha"); - break; - case SBF_ONE_MINUS_DEST_COLOUR: - writeValue("one_minus_dest_colour"); - break; - case SBF_ONE_MINUS_SOURCE_ALPHA: - writeValue("one_minus_src_alpha"); - break; - case SBF_ONE_MINUS_SOURCE_COLOUR: - writeValue("one_minus_src_colour"); - break; - case SBF_SOURCE_ALPHA: - writeValue("src_alpha"); - break; - case SBF_SOURCE_COLOUR: - writeValue("src_colour"); - break; - case SBF_ZERO: - writeValue("zero"); - break; - } - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeSceneBlendFactor(const SceneBlendFactor sbf_src, const SceneBlendFactor sbf_dst) - { - if (sbf_src == SBF_ONE && sbf_dst == SBF_ONE ) - writeValue("add"); - else if (sbf_src == SBF_DEST_COLOUR && sbf_dst == SBF_ZERO) - writeValue("modulate"); - else if (sbf_src == SBF_SOURCE_COLOUR && sbf_dst == SBF_ONE_MINUS_SOURCE_COLOUR) - writeValue("colour_blend"); - else if (sbf_src == SBF_SOURCE_ALPHA && sbf_dst == SBF_ONE_MINUS_SOURCE_ALPHA) - writeValue("alpha_blend"); - else - { - writeSceneBlendFactor(sbf_src); - writeSceneBlendFactor(sbf_dst); - } - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeSceneBlendFactor( - const SceneBlendFactor c_src, const SceneBlendFactor c_dest, - const SceneBlendFactor a_src, const SceneBlendFactor a_dest) - { - writeSceneBlendFactor(c_src, c_dest); - writeSceneBlendFactor(a_src, a_dest); - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeCompareFunction(const CompareFunction cf) - { - switch (cf) - { - case CMPF_ALWAYS_FAIL: - writeValue("always_fail"); - break; - case CMPF_ALWAYS_PASS: - writeValue("always_pass"); - break; - case CMPF_EQUAL: - writeValue("equal"); - break; - case CMPF_GREATER: - writeValue("greater"); - break; - case CMPF_GREATER_EQUAL: - writeValue("greater_equal"); - break; - case CMPF_LESS: - writeValue("less"); - break; - case CMPF_LESS_EQUAL: - writeValue("less_equal"); - break; - case CMPF_NOT_EQUAL: - writeValue("not_equal"); - break; - } - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeColourValue(const ColourValue &colour, bool writeAlpha) - { - writeValue(StringConverter::toString(colour.r)); - writeValue(StringConverter::toString(colour.g)); - writeValue(StringConverter::toString(colour.b)); - if (writeAlpha) - writeValue(StringConverter::toString(colour.a)); - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeLayerBlendOperationEx(const LayerBlendOperationEx op) - { - switch (op) - { - case LBX_ADD: - writeValue("add"); - break; - case LBX_ADD_SIGNED: - writeValue("add_signed"); - break; - case LBX_ADD_SMOOTH: - writeValue("add_smooth"); - break; - case LBX_BLEND_CURRENT_ALPHA: - writeValue("blend_current_alpha"); - break; - case LBX_BLEND_DIFFUSE_COLOUR: - writeValue("blend_diffuse_colour"); - break; - case LBX_BLEND_DIFFUSE_ALPHA: - writeValue("blend_diffuse_alpha"); - break; - case LBX_BLEND_MANUAL: - writeValue("blend_manual"); - break; - case LBX_BLEND_TEXTURE_ALPHA: - writeValue("blend_texture_alpha"); - break; - case LBX_MODULATE: - writeValue("modulate"); - break; - case LBX_MODULATE_X2: - writeValue("modulate_x2"); - break; - case LBX_MODULATE_X4: - writeValue("modulate_x4"); - break; - case LBX_SOURCE1: - writeValue("source1"); - break; - case LBX_SOURCE2: - writeValue("source2"); - break; - case LBX_SUBTRACT: - writeValue("subtract"); - break; - case LBX_DOTPRODUCT: - writeValue("dotproduct"); - break; - } - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeLayerBlendSource(const LayerBlendSource lbs) - { - switch (lbs) - { - case LBS_CURRENT: - writeValue("src_current"); - break; - case LBS_DIFFUSE: - writeValue("src_diffuse"); - break; - case LBS_MANUAL: - writeValue("src_manual"); - break; - case LBS_SPECULAR: - writeValue("src_specular"); - break; - case LBS_TEXTURE: - writeValue("src_texture"); - break; - } - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeVertexProgramRef(const Pass* pPass) - { - writeGpuProgramRef("vertex_program_ref", - pPass->getVertexProgram(), pPass->getVertexProgramParameters()); - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeTesselationHullProgramRef(const Pass* pPass) - { - writeGpuProgramRef("tesselation_hull_program_ref", - pPass->getTessellationHullProgram(), pPass->getTessellationHullProgramParameters()); - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeTesselationDomainProgramRef(const Pass* pPass) - { - writeGpuProgramRef("tesselation_domain_program_ref", - pPass->getTessellationDomainProgram(), pPass->getTessellationDomainProgramParameters()); - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeGeometryProgramRef(const Pass* pPass) - { - writeGpuProgramRef("geometry_program_ref", - pPass->getGeometryProgram(), pPass->getGeometryProgramParameters()); - } - //-- - //----------------------------------------------------------------------- - void MaterialSerializer::writeFragmentProgramRef(const Pass* pPass) - { - writeGpuProgramRef("fragment_program_ref", - pPass->getFragmentProgram(), pPass->getFragmentProgramParameters()); - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeGpuProgramRef(const String& attrib, - const GpuProgramPtr& program, const GpuProgramParametersSharedPtr& params) - { - bool skipWriting = false; - - // Fire pre-write event. - fireGpuProgramRefEvent(MSE_PRE_WRITE, skipWriting, attrib, program, params, NULL); - if (skipWriting) - return; - - mBuffer += "\n"; - writeAttribute(3, attrib); - writeValue(quoteWord(program->getName())); - beginSection(3); - { - // write out parameters - GpuProgramParameters* defaultParams = 0; - // does the GPU program have default parameters? - if (program->hasDefaultParameters()) - defaultParams = program->getDefaultParameters().get(); - - // Fire write begin event. - fireGpuProgramRefEvent(MSE_WRITE_BEGIN, skipWriting, attrib, program, params, defaultParams); - - writeGPUProgramParameters(params, defaultParams); - - // Fire write end event. - fireGpuProgramRefEvent(MSE_WRITE_END, skipWriting, attrib, program, params, defaultParams); - } - endSection(3); - - // add to GpuProgram container - mGpuProgramDefinitionContainer.insert(program->getName()); - - // Fire post section write event. - fireGpuProgramRefEvent(MSE_POST_WRITE, skipWriting, attrib, program, params, NULL); - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeGPUProgramParameters( - const GpuProgramParametersSharedPtr& params, - GpuProgramParameters* defaultParams, unsigned short level, - const bool useMainBuffer) - { - // iterate through the constant definitions - if (params->hasNamedParameters()) - { - writeNamedGpuProgramParameters(params, defaultParams, level, useMainBuffer); - } - else - { - writeLowLevelGpuProgramParameters(params, defaultParams, level, useMainBuffer); - } - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeNamedGpuProgramParameters( - const GpuProgramParametersSharedPtr& params, - GpuProgramParameters* defaultParams, unsigned short level, - const bool useMainBuffer) - { - for(auto& it : params->getConstantDefinitions().map) - { - // get the constant definition - const String& paramName = it.first; - const GpuConstantDefinition& def = it.second; - - // get any auto-link - const GpuProgramParameters::AutoConstantEntry* autoEntry = - params->findAutoConstantEntry(paramName); - const GpuProgramParameters::AutoConstantEntry* defaultAutoEntry = 0; - if (defaultParams) - { - defaultAutoEntry = - defaultParams->findAutoConstantEntry(paramName); - } - - writeGpuProgramParameter("param_named", - paramName, autoEntry, defaultAutoEntry, - def.isFloat(), def.isDouble(), def.isInt(), def.isUnsignedInt(), def.isSampler(), - def.physicalIndex, def.elementSize * def.arraySize, - params, defaultParams, level, useMainBuffer); - } - - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeLowLevelGpuProgramParameters( - const GpuProgramParametersSharedPtr& params, - GpuProgramParameters* defaultParams, unsigned short level, - const bool useMainBuffer) - { - // Iterate over the logical->physical mappings - // This will represent the values which have been set - - // float params - GpuLogicalBufferStructPtr floatLogical = params->getLogicalBufferStruct(); - if( floatLogical ) - { - OGRE_LOCK_MUTEX(floatLogical->mutex); - - for(GpuLogicalIndexUseMap::const_iterator i = floatLogical->map.begin(); - i != floatLogical->map.end(); ++i) - { - size_t logicalIndex = i->first; - const GpuLogicalIndexUse& logicalUse = i->second; - - const GpuProgramParameters::AutoConstantEntry* autoEntry = - params->findFloatAutoConstantEntry(logicalIndex); - const GpuProgramParameters::AutoConstantEntry* defaultAutoEntry = 0; - if (defaultParams) - { - defaultAutoEntry = defaultParams->findFloatAutoConstantEntry(logicalIndex); - } - - writeGpuProgramParameter("param_indexed", - StringConverter::toString(logicalIndex), autoEntry, - defaultAutoEntry, true, false, false, false, false, - logicalUse.physicalIndex, logicalUse.currentSize, - params, defaultParams, level, useMainBuffer); - } - } - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeGpuProgramParameter( - const String& commandName, const String& identifier, - const GpuProgramParameters::AutoConstantEntry* autoEntry, - const GpuProgramParameters::AutoConstantEntry* defaultAutoEntry, - bool isFloat, bool isDouble, bool isInt, bool isUnsignedInt, bool isRegister, - size_t physicalIndex, size_t physicalSize, - const GpuProgramParametersSharedPtr& params, GpuProgramParameters* defaultParams, - const ushort level, const bool useMainBuffer) - { - // Skip any params with array qualifiers - // These are only for convenience of setters, the full array will be - // written using the base, non-array identifier - if (identifier.find('[') != String::npos) - { - return; - } - - // get any auto-link - // don't duplicate constants that are defined as a default parameter - bool different = false; - if (defaultParams) - { - // if default is auto but we're not or vice versa - if ((autoEntry == 0) != (defaultAutoEntry == 0)) - { - different = true; - } - else if (autoEntry) - { - // both must be auto - // compare the auto values - different = (autoEntry->paramType != defaultAutoEntry->paramType - || autoEntry->data != defaultAutoEntry->data); - } - else - { - // compare the non-auto (raw buffer) values - // param buffers are always initialised with all zeros - // so unset == unset - if (isRegister) { - different = memcmp( - params->getRegPointer(physicalIndex), - defaultParams->getRegPointer(physicalIndex), - sizeof(int) * physicalSize) != 0; - } - else if (isFloat) - { - different = memcmp( - params->getFloatPointer(physicalIndex), - defaultParams->getFloatPointer(physicalIndex), - sizeof(float) * physicalSize) != 0; - } - else if (isDouble) - { - different = memcmp( - params->getDoublePointer(physicalIndex), - defaultParams->getDoublePointer(physicalIndex), - sizeof(double) * physicalSize) != 0; - } - else if (isInt) - { - different = memcmp( - params->getIntPointer(physicalIndex), - defaultParams->getIntPointer(physicalIndex), - sizeof(int) * physicalSize) != 0; - } - else if (isUnsignedInt) - { - different = memcmp( - params->getUnsignedIntPointer(physicalIndex), - defaultParams->getUnsignedIntPointer(physicalIndex), - sizeof(uint) * physicalSize) != 0; - } - //else if (isBool) - //{ - // // different = memcmp( - // // params->getBoolPointer(physicalIndex), - // // defaultParams->getBoolPointer(physicalIndex), - // // sizeof(bool) * physicalSize) != 0; - // different = memcmp( - // params->getUnsignedIntPointer(physicalIndex), - // defaultParams->getUnsignedIntPointer(physicalIndex), - // sizeof(uint) * physicalSize) != 0; - //} - } - } - - if (!defaultParams || different) - { - String label = commandName; - - // is it auto - if (autoEntry) - label += "_auto"; - - writeAttribute(level, label, useMainBuffer); - // output param index / name - writeValue(quoteWord(identifier), useMainBuffer); - - // if auto output auto type name and data if needed - if (autoEntry) - { - const GpuProgramParameters::AutoConstantDefinition* autoConstDef = - GpuProgramParameters::getAutoConstantDefinition(autoEntry->paramType); - - // output auto constant name - writeValue(quoteWord(autoConstDef->name), useMainBuffer); - // output data if it uses it - switch(autoConstDef->dataType) - { - case GpuProgramParameters::ACDT_REAL: - writeValue(StringConverter::toString(autoEntry->fData), useMainBuffer); - break; - - case GpuProgramParameters::ACDT_INT: - writeValue(StringConverter::toString(autoEntry->data), useMainBuffer); - break; - - default: - break; - } - } - else // not auto so output all the values used - { - String countLabel; - - // only write a number if > 1 - if (physicalSize > 1) - countLabel = StringConverter::toString(physicalSize); - - if (isRegister) - { - // Get pointer to start of values - const int* pInt = params->getRegPointer(physicalIndex); - - writeValue("int" + countLabel, useMainBuffer); - // iterate through real constants - for (size_t f = 0; f < physicalSize; ++f) - { - writeValue(StringConverter::toString(*pInt++), useMainBuffer); - } - } - else if (isFloat) - { - // Get pointer to start of values - const float* pFloat = params->getFloatPointer(physicalIndex); - - writeValue("float" + countLabel, useMainBuffer); - // iterate through real constants - for (size_t f = 0; f < physicalSize; ++f) - { - writeValue(StringConverter::toString(*pFloat++), useMainBuffer); - } - } - else if (isDouble) - { - // Get pointer to start of values - const double* pDouble = params->getDoublePointer(physicalIndex); - - writeValue("double" + countLabel, useMainBuffer); - // iterate through double constants - for (size_t f = 0; f < physicalSize; ++f) - { - writeValue(StringConverter::toString(*pDouble++), useMainBuffer); - } - } - else if (isInt) - { - // Get pointer to start of values - const int* pInt = params->getIntPointer(physicalIndex); - - writeValue("int" + countLabel, useMainBuffer); - // iterate through int constants - for (size_t f = 0; f < physicalSize; ++f) - { - writeValue(StringConverter::toString(*pInt++), useMainBuffer); - } - } - else if (isUnsignedInt) - { - // Get pointer to start of values - const uint* pUInt = params->getUnsignedIntPointer(physicalIndex); - - writeValue("uint" + countLabel, useMainBuffer); - // iterate through uint constants - for (size_t f = 0; f < physicalSize; ++f) - { - writeValue(StringConverter::toString(*pUInt++), useMainBuffer); - } - } - //else if (isBool) - //{ - // // Get pointer to start of values - // // const bool* pBool = params->getBoolPointer(physicalIndex); - // const uint* pBool = params->getUnsignedIntPointer(physicalIndex); - - // writeValue("bool" + countLabel, useMainBuffer); - // // iterate through bool constants - // for (size_t f = 0; f < physicalSize; ++f) - // { - // writeValue(StringConverter::toString(*pBool++), useMainBuffer); - // } - //} - } - } - } - //----------------------------------------------------------------------- - void MaterialSerializer::writeGpuPrograms(void) - { - // iterate through gpu program names in container - GpuProgramDefIterator currentDef = mGpuProgramDefinitionContainer.begin(); - GpuProgramDefIterator endDef = mGpuProgramDefinitionContainer.end(); - - while (currentDef != endDef) - { - // get gpu program from gpu program manager - GpuProgramPtr program = GpuProgramManager::getSingleton().getByName( - *currentDef, ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME); - // write gpu program definition type to buffer - // check program type for vertex program - // write program type - mGpuProgramBuffer += "\n"; - writeAttribute(0, program->getParameter("type"), false); - - // write program name - writeValue( quoteWord(program->getName()), false); - // write program language - const String language = program->getLanguage(); - writeValue( language, false ); - // write opening braces - beginSection(0, false); - { - // write program source + filename - writeAttribute(1, "source", false); - writeValue(quoteWord(program->getSourceFile()), false); - // write special parameters based on language - for (const auto& name : program->getParameters()) - { - if (name != "type" && - name != "assemble_code" && - name != "micro_code" && - name != "external_micro_code") - { - String paramstr = program->getParameter(name); - if ((name == "includes_skeletal_animation") && (paramstr == "false")) - paramstr.clear(); - if ((name == "includes_morph_animation") && (paramstr == "false")) - paramstr.clear(); - if ((name == "includes_pose_animation") && (paramstr == "0")) - paramstr.clear(); - if ((name == "uses_vertex_texture_fetch") && (paramstr == "false")) - paramstr.clear(); - - if ((language != "asm") && (name == "syntax")) - paramstr.clear(); - - if (!paramstr.empty()) - { - writeAttribute(1, name, false); - writeValue(paramstr, false); - } - } - } - - // write default parameters - if (program->hasDefaultParameters()) - { - mGpuProgramBuffer += "\n"; - GpuProgramParametersSharedPtr gpuDefaultParams = program->getDefaultParameters(); - writeAttribute(1, "default_params", false); - beginSection(1, false); - writeGPUProgramParameters(gpuDefaultParams, 0, 2, false); - endSection(1, false); - } - } - // write closing braces - endSection(0, false); - - ++currentDef; - - } - - mGpuProgramBuffer += "\n"; - } - - //--------------------------------------------------------------------- - void MaterialSerializer::addListener(Listener* listener) - { - mListeners.push_back(listener); - } - - //--------------------------------------------------------------------- - void MaterialSerializer::removeListener(Listener* listener) - { - ListenerList::iterator i = std::find(mListeners.begin(), mListeners.end(), listener); - if (i != mListeners.end()) - mListeners.erase(i); - } - - //--------------------------------------------------------------------- - void MaterialSerializer::fireMaterialEvent(SerializeEvent event, bool& skip, const Material* mat) - { - for (auto *l : mListeners) - { - l->materialEventRaised(this, event, skip, mat); - if (skip) - break; - } - } - - //--------------------------------------------------------------------- - void MaterialSerializer::fireTechniqueEvent(SerializeEvent event, bool& skip, const Technique* tech) - { - for (auto *l : mListeners) - { - l->techniqueEventRaised(this, event, skip, tech); - if (skip) - break; - } - } - - //--------------------------------------------------------------------- - void MaterialSerializer::firePassEvent(SerializeEvent event, bool& skip, const Pass* pass) - { - for (auto *l : mListeners) - { - l->passEventRaised(this, event, skip, pass); - if (skip) - break; - } - } - - //--------------------------------------------------------------------- - void MaterialSerializer::fireGpuProgramRefEvent(SerializeEvent event, bool& skip, - const String& attrib, - const GpuProgramPtr& program, - const GpuProgramParametersSharedPtr& params, - GpuProgramParameters* defaultParams) - { - for (auto *l : mListeners) - { - l->gpuProgramRefEventRaised(this, event, skip, attrib, program, params, defaultParams); - if (skip) - break; - } - } - - //--------------------------------------------------------------------- - void MaterialSerializer::fireTextureUnitStateEvent(SerializeEvent event, bool& skip, - const TextureUnitState* textureUnit) - { - for (auto *l : mListeners) - { - l->textureUnitStateEventRaised(this, event, skip, textureUnit); - if (skip) - break; - } - } -} diff --git a/OgreMain/src/OgreMath.cpp b/OgreMain/src/OgreMath.cpp deleted file mode 100644 index d79d4edc59e..00000000000 --- a/OgreMain/src/OgreMath.cpp +++ /dev/null @@ -1,788 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -namespace Ogre -{ - - constexpr Real Math::POS_INFINITY; - constexpr Real Math::NEG_INFINITY; - constexpr Real Math::PI; - constexpr Real Math::TWO_PI; - constexpr Real Math::HALF_PI; - constexpr float Math::fDeg2Rad; - constexpr float Math::fRad2Deg; - constexpr Real Math::LOG2; - - int Math::mTrigTableSize; - Math::AngleUnit Math::msAngleUnit; - - float Math::mTrigTableFactor; - float *Math::mSinTable = NULL; - float *Math::mTanTable = NULL; - - Math::RandomValueProvider* Math::mRandProvider = NULL; - - //----------------------------------------------------------------------- - Math::Math( unsigned int trigTableSize ) - { - msAngleUnit = AU_DEGREE; - mTrigTableSize = trigTableSize; - mTrigTableFactor = mTrigTableSize / Math::TWO_PI; - - mSinTable = OGRE_ALLOC_T(float, mTrigTableSize, MEMCATEGORY_GENERAL); - mTanTable = OGRE_ALLOC_T(float, mTrigTableSize, MEMCATEGORY_GENERAL); - - buildTrigTables(); - } - - //----------------------------------------------------------------------- - Math::~Math() - { - OGRE_FREE(mSinTable, MEMCATEGORY_GENERAL); - OGRE_FREE(mTanTable, MEMCATEGORY_GENERAL); - } - - //----------------------------------------------------------------------- - void Math::buildTrigTables(void) - { - // Build trig lookup tables - // Could get away with building only PI sized Sin table but simpler this - // way. Who cares, it'll ony use an extra 8k of memory anyway and I like - // simplicity. - float angle; - for (int i = 0; i < mTrigTableSize; ++i) - { - angle = Math::TWO_PI * i / Real(mTrigTableSize); - mSinTable[i] = std::sin(angle); - mTanTable[i] = std::tan(angle); - } - } - //----------------------------------------------------------------------- - float Math::SinTable (float fValue) - { - // Convert range to index values, wrap if required - int idx; - if (fValue >= 0) - { - idx = int(fValue * mTrigTableFactor) % mTrigTableSize; - } - else - { - idx = mTrigTableSize - (int(-fValue * mTrigTableFactor) % mTrigTableSize) - 1; - } - - return mSinTable[idx]; - } - //----------------------------------------------------------------------- - float Math::TanTable (float fValue) - { - // Convert range to index values, wrap if required - int idx = int(fValue * mTrigTableFactor) % mTrigTableSize; - return mTanTable[idx]; - } - //----------------------------------------------------------------------- - Radian Math::ACos (Real fValue) - { - if ( -1.0 < fValue ) - { - if ( fValue < 1.0 ) - return Radian(std::acos(fValue)); - else - return Radian(0.0); - } - else - { - return Radian(PI); - } - } - //----------------------------------------------------------------------- - Radian Math::ASin (Real fValue) - { - if ( -1.0 < fValue ) - { - if ( fValue < 1.0 ) - return Radian(std::asin(fValue)); - else - return Radian(HALF_PI); - } - else - { - return Radian(-HALF_PI); - } - } - //----------------------------------------------------------------------- - float Math::UnitRandom () - { - if (mRandProvider) - return mRandProvider->getRandomUnit(); - else return rand() / float(RAND_MAX); - } - - //----------------------------------------------------------------------- - void Math::SetRandomValueProvider(RandomValueProvider* provider) - { - mRandProvider = provider; - } - - //----------------------------------------------------------------------- - void Math::setAngleUnit(Math::AngleUnit unit) - { - msAngleUnit = unit; - } - //----------------------------------------------------------------------- - Math::AngleUnit Math::getAngleUnit(void) - { - return msAngleUnit; - } - //----------------------------------------------------------------------- - float Math::AngleUnitsToRadians(float angleunits) - { - if (msAngleUnit == AU_DEGREE) - return angleunits * fDeg2Rad; - else - return angleunits; - } - - //----------------------------------------------------------------------- - float Math::RadiansToAngleUnits(float radians) - { - if (msAngleUnit == AU_DEGREE) - return radians * fRad2Deg; - else - return radians; - } - - //----------------------------------------------------------------------- - float Math::AngleUnitsToDegrees(float angleunits) - { - if (msAngleUnit == AU_RADIAN) - return angleunits * fRad2Deg; - else - return angleunits; - } - - //----------------------------------------------------------------------- - float Math::DegreesToAngleUnits(float degrees) - { - if (msAngleUnit == AU_RADIAN) - return degrees * fDeg2Rad; - else - return degrees; - } - - //----------------------------------------------------------------------- - bool Math::pointInTri2D(const Vector2& p, const Vector2& a, - const Vector2& b, const Vector2& c) - { - // Winding must be consistent from all edges for point to be inside - Vector2 v1, v2; - Real dot[3]; - bool zeroDot[3]; - - v1 = b - a; - v2 = p - a; - - // Note we don't care about normalisation here since sign is all we need - // It means we don't have to worry about magnitude of cross products either - dot[0] = v1.crossProduct(v2); - zeroDot[0] = Math::RealEqual(dot[0], 0.0f, 1e-3); - - - v1 = c - b; - v2 = p - b; - - dot[1] = v1.crossProduct(v2); - zeroDot[1] = Math::RealEqual(dot[1], 0.0f, 1e-3); - - // Compare signs (ignore colinear / coincident points) - if(!zeroDot[0] && !zeroDot[1] - && Math::Sign(dot[0]) != Math::Sign(dot[1])) - { - return false; - } - - v1 = a - c; - v2 = p - c; - - dot[2] = v1.crossProduct(v2); - zeroDot[2] = Math::RealEqual(dot[2], 0.0f, 1e-3); - // Compare signs (ignore colinear / coincident points) - if((!zeroDot[0] && !zeroDot[2] - && Math::Sign(dot[0]) != Math::Sign(dot[2])) || - (!zeroDot[1] && !zeroDot[2] - && Math::Sign(dot[1]) != Math::Sign(dot[2]))) - { - return false; - } - - - return true; - } - //----------------------------------------------------------------------- - bool Math::pointInTri3D(const Vector3& p, const Vector3& a, - const Vector3& b, const Vector3& c, const Vector3& normal) - { - // Winding must be consistent from all edges for point to be inside - Vector3 v1, v2; - Real dot[3]; - bool zeroDot[3]; - - v1 = b - a; - v2 = p - a; - - // Note we don't care about normalisation here since sign is all we need - // It means we don't have to worry about magnitude of cross products either - dot[0] = v1.crossProduct(v2).dotProduct(normal); - zeroDot[0] = Math::RealEqual(dot[0], 0.0f, 1e-3); - - - v1 = c - b; - v2 = p - b; - - dot[1] = v1.crossProduct(v2).dotProduct(normal); - zeroDot[1] = Math::RealEqual(dot[1], 0.0f, 1e-3); - - // Compare signs (ignore colinear / coincident points) - if(!zeroDot[0] && !zeroDot[1] - && Math::Sign(dot[0]) != Math::Sign(dot[1])) - { - return false; - } - - v1 = a - c; - v2 = p - c; - - dot[2] = v1.crossProduct(v2).dotProduct(normal); - zeroDot[2] = Math::RealEqual(dot[2], 0.0f, 1e-3); - // Compare signs (ignore colinear / coincident points) - if((!zeroDot[0] && !zeroDot[2] - && Math::Sign(dot[0]) != Math::Sign(dot[2])) || - (!zeroDot[1] && !zeroDot[2] - && Math::Sign(dot[1]) != Math::Sign(dot[2]))) - { - return false; - } - - - return true; - } - //----------------------------------------------------------------------- - std::pair Math::intersects(const Ray& ray, - const std::vector& planes, bool normalIsOutside) - { - bool allInside = true; - std::pair ret; - std::pair end; - ret.first = false; - ret.second = 0.0f; - end.first = false; - end.second = 0; - - // derive side - // NB we don't pass directly since that would require Plane::Side in - // interface, which results in recursive includes since Math is so fundamental - Plane::Side outside = normalIsOutside ? Plane::POSITIVE_SIDE : Plane::NEGATIVE_SIDE; - for (auto& plane : planes) - { - // is origin outside? - if (plane.getSide(ray.getOrigin()) == outside) - { - allInside = false; - // Test single plane - std::pair planeRes = - ray.intersects(plane); - if (planeRes.first) - { - // Ok, we intersected - ret.first = true; - // Use the most distant result since convex volume - ret.second = std::max(ret.second, planeRes.second); - } - else - { - ret.first =false; - ret.second=0.0f; - return ret; - } - } - else - { - std::pair planeRes = - ray.intersects(plane); - if (planeRes.first) - { - if( !end.first ) - { - end.first = true; - end.second = planeRes.second; - } - else - { - end.second = std::min( planeRes.second, end.second ); - } - - } - - } - } - - if (allInside) - { - // Intersecting at 0 distance since inside the volume! - ret.first = true; - ret.second = 0.0f; - return ret; - } - - if( end.first ) - { - if( end.second < ret.second ) - { - ret.first = false; - return ret; - } - } - return ret; - } - //----------------------------------------------------------------------- - std::pair Math::intersects(const Ray& ray, const AxisAlignedBox& box) - { - if (box.isNull()) return std::pair(false, (Real)0); - if (box.isInfinite()) return std::pair(true, (Real)0); - - Real lowt = 0.0f; - Real t; - bool hit = false; - Vector3 hitpoint; - const Vector3& min = box.getMinimum(); - const Vector3& max = box.getMaximum(); - const Vector3& rayorig = ray.getOrigin(); - const Vector3& raydir = ray.getDirection(); - - // Check origin inside first - if ( rayorig > min && rayorig < max ) - { - return std::pair(true, (Real)0); - } - - // Check each face in turn, only check closest 3 - // Min x - if (rayorig.x <= min.x && raydir.x > 0) - { - t = (min.x - rayorig.x) / raydir.x; - - // Substitute t back into ray and check bounds and dist - hitpoint = rayorig + raydir * t; - if (hitpoint.y >= min.y && hitpoint.y <= max.y && - hitpoint.z >= min.z && hitpoint.z <= max.z && - (!hit || t < lowt)) - { - hit = true; - lowt = t; - } - } - // Max x - if (rayorig.x >= max.x && raydir.x < 0) - { - t = (max.x - rayorig.x) / raydir.x; - - // Substitute t back into ray and check bounds and dist - hitpoint = rayorig + raydir * t; - if (hitpoint.y >= min.y && hitpoint.y <= max.y && - hitpoint.z >= min.z && hitpoint.z <= max.z && - (!hit || t < lowt)) - { - hit = true; - lowt = t; - } - } - // Min y - if (rayorig.y <= min.y && raydir.y > 0) - { - t = (min.y - rayorig.y) / raydir.y; - - // Substitute t back into ray and check bounds and dist - hitpoint = rayorig + raydir * t; - if (hitpoint.x >= min.x && hitpoint.x <= max.x && - hitpoint.z >= min.z && hitpoint.z <= max.z && - (!hit || t < lowt)) - { - hit = true; - lowt = t; - } - } - // Max y - if (rayorig.y >= max.y && raydir.y < 0) - { - t = (max.y - rayorig.y) / raydir.y; - - // Substitute t back into ray and check bounds and dist - hitpoint = rayorig + raydir * t; - if (hitpoint.x >= min.x && hitpoint.x <= max.x && - hitpoint.z >= min.z && hitpoint.z <= max.z && - (!hit || t < lowt)) - { - hit = true; - lowt = t; - } - } - // Min z - if (rayorig.z <= min.z && raydir.z > 0) - { - t = (min.z - rayorig.z) / raydir.z; - - // Substitute t back into ray and check bounds and dist - hitpoint = rayorig + raydir * t; - if (hitpoint.x >= min.x && hitpoint.x <= max.x && - hitpoint.y >= min.y && hitpoint.y <= max.y && - (!hit || t < lowt)) - { - hit = true; - lowt = t; - } - } - // Max z - if (rayorig.z >= max.z && raydir.z < 0) - { - t = (max.z - rayorig.z) / raydir.z; - - // Substitute t back into ray and check bounds and dist - hitpoint = rayorig + raydir * t; - if (hitpoint.x >= min.x && hitpoint.x <= max.x && - hitpoint.y >= min.y && hitpoint.y <= max.y && - (!hit || t < lowt)) - { - hit = true; - lowt = t; - } - } - - return std::pair(hit, (Real)lowt); - - } - //----------------------------------------------------------------------- - bool Math::intersects(const Ray& ray, const AxisAlignedBox& box, - Real* d1, Real* d2) - { - if (box.isNull()) - return false; - - if (box.isInfinite()) - { - if (d1) *d1 = 0; - if (d2) *d2 = Math::POS_INFINITY; - return true; - } - - const Vector3& min = box.getMinimum(); - const Vector3& max = box.getMaximum(); - const Vector3& rayorig = ray.getOrigin(); - const Vector3& raydir = ray.getDirection(); - - Vector3 absDir; - absDir[0] = Math::Abs(raydir[0]); - absDir[1] = Math::Abs(raydir[1]); - absDir[2] = Math::Abs(raydir[2]); - - // Sort the axis, ensure check minimise floating error axis first - int imax = 0, imid = 1, imin = 2; - if (absDir[0] < absDir[2]) - { - imax = 2; - imin = 0; - } - if (absDir[1] < absDir[imin]) - { - imid = imin; - imin = 1; - } - else if (absDir[1] > absDir[imax]) - { - imid = imax; - imax = 1; - } - - Real start = 0, end = Math::POS_INFINITY; - -#define _CALC_AXIS(i) \ - do { \ - Real denom = 1 / raydir[i]; \ - Real newstart = (min[i] - rayorig[i]) * denom; \ - Real newend = (max[i] - rayorig[i]) * denom; \ - if (newstart > newend) std::swap(newstart, newend); \ - if (newstart > end || newend < start) return false; \ - if (newstart > start) start = newstart; \ - if (newend < end) end = newend; \ - } while(0) - - // Check each axis in turn - - _CALC_AXIS(imax); - - if (absDir[imid] < std::numeric_limits::epsilon()) - { - // Parallel with middle and minimise axis, check bounds only - if (rayorig[imid] < min[imid] || rayorig[imid] > max[imid] || - rayorig[imin] < min[imin] || rayorig[imin] > max[imin]) - return false; - } - else - { - _CALC_AXIS(imid); - - if (absDir[imin] < std::numeric_limits::epsilon()) - { - // Parallel with minimise axis, check bounds only - if (rayorig[imin] < min[imin] || rayorig[imin] > max[imin]) - return false; - } - else - { - _CALC_AXIS(imin); - } - } -#undef _CALC_AXIS - - if (d1) *d1 = start; - if (d2) *d2 = end; - - return true; - } - //----------------------------------------------------------------------- - std::pair Math::intersects(const Ray& ray, const Vector3& a, const Vector3& b, - const Vector3& c, bool positiveSide, bool negativeSide) - { - const Real EPSILON = 1e-6f; - Vector3 E1 = b - a; - Vector3 E2 = c - a; - Vector3 P = ray.getDirection().crossProduct(E2); - Real det = E1.dotProduct(P); - - // if determinant is near zero, ray lies in plane of triangle - if((!positiveSide || det <= EPSILON) && (!negativeSide || det >= -EPSILON)) - return {false, (Real)0}; - Real inv_det = 1.0f / det; - - // calculate u parameter and test bounds - Vector3 T = ray.getOrigin() - a; - Real u = T.dotProduct(P) * inv_det; - if(u < 0.0f || u > 1.0f) - return {false, (Real)0}; - - // calculate v parameter and test bounds - Vector3 Q = T.crossProduct(E1); - Real v = ray.getDirection().dotProduct(Q) * inv_det; - if (v < 0.0f || u + v > 1.0f) - return {false, (Real)0}; - - // calculate t, ray intersects triangle - Real t = E2.dotProduct(Q) * inv_det; - if (t < 0.0f) - return {false, (Real)0}; - - return {true, t}; - } - //----------------------------------------------------------------------- - bool Math::intersects(const Sphere& sphere, const AxisAlignedBox& box) - { - if (box.isNull()) return false; - if (box.isInfinite()) return true; - - // Use splitting planes - const Vector3& center = sphere.getCenter(); - Real radius = sphere.getRadius(); - const Vector3& min = box.getMinimum(); - const Vector3& max = box.getMaximum(); - - // Arvo's algorithm - Real s, d = 0; - for (int i = 0; i < 3; ++i) - { - if (center.ptr()[i] < min.ptr()[i]) - { - s = center.ptr()[i] - min.ptr()[i]; - d += s * s; - } - else if(center.ptr()[i] > max.ptr()[i]) - { - s = center.ptr()[i] - max.ptr()[i]; - d += s * s; - } - } - return d <= radius * radius; - - } - //----------------------------------------------------------------------- - Vector3 Math::calculateTangentSpaceVector( - const Vector3& position1, const Vector3& position2, const Vector3& position3, - Real u1, Real v1, Real u2, Real v2, Real u3, Real v3) - { - //side0 is the vector along one side of the triangle of vertices passed in, - //and side1 is the vector along another side. Taking the cross product of these returns the normal. - Vector3 side0 = position1 - position2; - Vector3 side1 = position3 - position1; - //Calculate face normal - Vector3 normal = side1.crossProduct(side0); - normal.normalise(); - //Now we use a formula to calculate the tangent. - Real deltaV0 = v1 - v2; - Real deltaV1 = v3 - v1; - Vector3 tangent = deltaV1 * side0 - deltaV0 * side1; - tangent.normalise(); - //Calculate binormal - Real deltaU0 = u1 - u2; - Real deltaU1 = u3 - u1; - Vector3 binormal = deltaU1 * side0 - deltaU0 * side1; - binormal.normalise(); - //Now, we take the cross product of the tangents to get a vector which - //should point in the same direction as our normal calculated above. - //If it points in the opposite direction (the dot product between the normals is less than zero), - //then we need to reverse the s and t tangents. - //This is because the triangle has been mirrored when going from tangent space to object space. - //reverse tangents if necessary - Vector3 tangentCross = tangent.crossProduct(binormal); - if (tangentCross.dotProduct(normal) < 0.0f) - { - tangent = -tangent; - binormal = -binormal; - } - - return tangent; - - } - //----------------------------------------------------------------------- - Affine3 Math::buildReflectionMatrix(const Plane& p) - { - return Affine3( - -2 * p.normal.x * p.normal.x + 1, -2 * p.normal.x * p.normal.y, -2 * p.normal.x * p.normal.z, -2 * p.normal.x * p.d, - -2 * p.normal.y * p.normal.x, -2 * p.normal.y * p.normal.y + 1, -2 * p.normal.y * p.normal.z, -2 * p.normal.y * p.d, - -2 * p.normal.z * p.normal.x, -2 * p.normal.z * p.normal.y, -2 * p.normal.z * p.normal.z + 1, -2 * p.normal.z * p.d); - } - //----------------------------------------------------------------------- - Real Math::gaussianDistribution(Real x, Real offset, Real scale) - { - Real nom = Math::Exp( - -Math::Sqr(x - offset) / (2 * Math::Sqr(scale))); - Real denom = scale * Math::Sqrt(2 * Math::PI); - - return nom / denom; - - } - //--------------------------------------------------------------------- - Affine3 Math::makeViewMatrix(const Vector3& position, const Quaternion& orientation, - const Affine3* reflectMatrix) - { - // This is most efficiently done using 3x3 Matrices - Matrix3 rot; - orientation.ToRotationMatrix(rot); - - // Make the translation relative to new axes - Matrix3 rotT = rot.Transpose(); - Vector3 trans = -rotT * position; - - // Make final matrix - Affine3 viewMatrix = Affine3::IDENTITY; - viewMatrix = rotT; // fills upper 3x3 - viewMatrix[0][3] = trans.x; - viewMatrix[1][3] = trans.y; - viewMatrix[2][3] = trans.z; - - // Deal with reflections - if (reflectMatrix) - { - viewMatrix = viewMatrix * (*reflectMatrix); - } - - return viewMatrix; - - } - - Matrix4 Math::makePerspectiveMatrix(Real left, Real right, Real bottom, Real top, Real zNear, Real zFar) - { - // The code below will dealing with general projection - // parameters, similar glFrustum. - // Doesn't optimise manually except division operator, so the - // code more self-explaining. - - Real inv_w = 1 / (right - left); - Real inv_h = 1 / (top - bottom); - Real inv_d = 1 / (zFar - zNear); - - // Calc matrix elements - Real A = 2 * zNear * inv_w; - Real B = 2 * zNear * inv_h; - Real C = (right + left) * inv_w; - Real D = (top + bottom) * inv_h; - Real q, qn; - - if (zFar == 0) - { - // Infinite far plane - q = Frustum::INFINITE_FAR_PLANE_ADJUST - 1; - qn = zNear * (Frustum::INFINITE_FAR_PLANE_ADJUST - 2); - } - else - { - q = - (zFar + zNear) * inv_d; - qn = -2 * (zFar * zNear) * inv_d; - } - - Matrix4 ret = Matrix4::ZERO; - ret[0][0] = A; - ret[0][2] = C; - ret[1][1] = B; - ret[1][2] = D; - ret[2][2] = q; - ret[2][3] = qn; - ret[3][2] = -1; - - return ret; - } - //--------------------------------------------------------------------- - Real Math::boundingRadiusFromAABB(const AxisAlignedBox& aabb) - { - const Vector3& max = aabb.getMaximum(); - const Vector3& min = aabb.getMinimum(); - - Vector3 magnitude = max; - magnitude.makeCeil(-max); - magnitude.makeCeil(min); - magnitude.makeCeil(-min); - - return magnitude.length(); - } - - Real Math::boundingRadiusFromAABBCentered(const AxisAlignedBox& aabb) - { - const Vector3& max = aabb.getMaximum(); - const Vector3& min = aabb.getMinimum(); - - return ((min - max) * 0.5f).length(); - } -} diff --git a/OgreMain/src/OgreMatrix3.cpp b/OgreMain/src/OgreMatrix3.cpp deleted file mode 100644 index 57710426cb1..00000000000 --- a/OgreMain/src/OgreMatrix3.cpp +++ /dev/null @@ -1,1363 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -// Adapted from Matrix math by Wild Magic http://www.geometrictools.com/ - -namespace Ogre -{ - const Real Matrix3::EPSILON = 1e-06; - const Matrix3 Matrix3::ZERO(0,0,0,0,0,0,0,0,0); - const Matrix3 Matrix3::IDENTITY(1,0,0,0,1,0,0,0,1); - const unsigned int Matrix3::msSvdMaxIterations = 64; - - //----------------------------------------------------------------------- - bool Matrix3::operator== (const Matrix3& rkMatrix) const - { - for (size_t iRow = 0; iRow < 3; iRow++) - { - for (size_t iCol = 0; iCol < 3; iCol++) - { - if ( m[iRow][iCol] != rkMatrix.m[iRow][iCol] ) - return false; - } - } - - return true; - } - //----------------------------------------------------------------------- - Matrix3 Matrix3::operator+ (const Matrix3& rkMatrix) const - { - Matrix3 kSum; - for (size_t iRow = 0; iRow < 3; iRow++) - { - for (size_t iCol = 0; iCol < 3; iCol++) - { - kSum.m[iRow][iCol] = m[iRow][iCol] + - rkMatrix.m[iRow][iCol]; - } - } - return kSum; - } - //----------------------------------------------------------------------- - Matrix3 Matrix3::operator- (const Matrix3& rkMatrix) const - { - Matrix3 kDiff; - for (size_t iRow = 0; iRow < 3; iRow++) - { - for (size_t iCol = 0; iCol < 3; iCol++) - { - kDiff.m[iRow][iCol] = m[iRow][iCol] - - rkMatrix.m[iRow][iCol]; - } - } - return kDiff; - } - //----------------------------------------------------------------------- - Matrix3 Matrix3::operator* (const Matrix3& rkMatrix) const - { - Matrix3 kProd; - for (size_t iRow = 0; iRow < 3; iRow++) - { - for (size_t iCol = 0; iCol < 3; iCol++) - { - kProd.m[iRow][iCol] = - m[iRow][0]*rkMatrix.m[0][iCol] + - m[iRow][1]*rkMatrix.m[1][iCol] + - m[iRow][2]*rkMatrix.m[2][iCol]; - } - } - return kProd; - } - //----------------------------------------------------------------------- - Vector3 operator* (const Vector3& rkPoint, const Matrix3& rkMatrix) - { - Vector3 kProd; - for (size_t iRow = 0; iRow < 3; iRow++) - { - kProd[iRow] = - rkPoint[0]*rkMatrix.m[0][iRow] + - rkPoint[1]*rkMatrix.m[1][iRow] + - rkPoint[2]*rkMatrix.m[2][iRow]; - } - return kProd; - } - //----------------------------------------------------------------------- - Matrix3 Matrix3::operator- () const - { - Matrix3 kNeg; - for (size_t iRow = 0; iRow < 3; iRow++) - { - for (size_t iCol = 0; iCol < 3; iCol++) - kNeg[iRow][iCol] = -m[iRow][iCol]; - } - return kNeg; - } - //----------------------------------------------------------------------- - Matrix3 Matrix3::operator* (Real fScalar) const - { - Matrix3 kProd; - for (size_t iRow = 0; iRow < 3; iRow++) - { - for (size_t iCol = 0; iCol < 3; iCol++) - kProd[iRow][iCol] = fScalar*m[iRow][iCol]; - } - return kProd; - } - //----------------------------------------------------------------------- - Matrix3 operator* (Real fScalar, const Matrix3& rkMatrix) - { - Matrix3 kProd; - for (size_t iRow = 0; iRow < 3; iRow++) - { - for (size_t iCol = 0; iCol < 3; iCol++) - kProd[iRow][iCol] = fScalar*rkMatrix.m[iRow][iCol]; - } - return kProd; - } - //----------------------------------------------------------------------- - Matrix3 Matrix3::Transpose () const - { - Matrix3 kTranspose; - for (size_t iRow = 0; iRow < 3; iRow++) - { - for (size_t iCol = 0; iCol < 3; iCol++) - kTranspose[iRow][iCol] = m[iCol][iRow]; - } - return kTranspose; - } - //----------------------------------------------------------------------- - bool Matrix3::Inverse (Matrix3& rkInverse, Real fTolerance) const - { - // Invert a 3x3 using cofactors. This is about 8 times faster than - // the Numerical Recipes code which uses Gaussian elimination. - - rkInverse[0][0] = m[1][1]*m[2][2] - - m[1][2]*m[2][1]; - rkInverse[0][1] = m[0][2]*m[2][1] - - m[0][1]*m[2][2]; - rkInverse[0][2] = m[0][1]*m[1][2] - - m[0][2]*m[1][1]; - rkInverse[1][0] = m[1][2]*m[2][0] - - m[1][0]*m[2][2]; - rkInverse[1][1] = m[0][0]*m[2][2] - - m[0][2]*m[2][0]; - rkInverse[1][2] = m[0][2]*m[1][0] - - m[0][0]*m[1][2]; - rkInverse[2][0] = m[1][0]*m[2][1] - - m[1][1]*m[2][0]; - rkInverse[2][1] = m[0][1]*m[2][0] - - m[0][0]*m[2][1]; - rkInverse[2][2] = m[0][0]*m[1][1] - - m[0][1]*m[1][0]; - - Real fDet = - m[0][0]*rkInverse[0][0] + - m[0][1]*rkInverse[1][0]+ - m[0][2]*rkInverse[2][0]; - - if ( Math::Abs(fDet) <= fTolerance ) - return false; - - Real fInvDet = 1.0f/fDet; - for (size_t iRow = 0; iRow < 3; iRow++) - { - for (size_t iCol = 0; iCol < 3; iCol++) - rkInverse[iRow][iCol] *= fInvDet; - } - - return true; - } - //----------------------------------------------------------------------- - Matrix3 Matrix3::Inverse (Real fTolerance) const - { - Matrix3 kInverse = Matrix3::ZERO; - Inverse(kInverse,fTolerance); - return kInverse; - } - //----------------------------------------------------------------------- - void Matrix3::Bidiagonalize (Matrix3& kA, Matrix3& kL, - Matrix3& kR) - { - Real afV[3], afW[3]; - Real fLength, fSign, fT1, fInvT1, fT2; - bool bIdentity; - - // map first column to (*,0,0) - fLength = Math::Sqrt(kA[0][0]*kA[0][0] + kA[1][0]*kA[1][0] + - kA[2][0]*kA[2][0]); - if ( fLength > 0.0 ) - { - fSign = (kA[0][0] > 0.0f ? 1.0f : -1.0f); - fT1 = kA[0][0] + fSign*fLength; - fInvT1 = 1.0f/fT1; - afV[1] = kA[1][0]*fInvT1; - afV[2] = kA[2][0]*fInvT1; - - fT2 = -2.0f/(1.0f+afV[1]*afV[1]+afV[2]*afV[2]); - afW[0] = fT2*(kA[0][0]+kA[1][0]*afV[1]+kA[2][0]*afV[2]); - afW[1] = fT2*(kA[0][1]+kA[1][1]*afV[1]+kA[2][1]*afV[2]); - afW[2] = fT2*(kA[0][2]+kA[1][2]*afV[1]+kA[2][2]*afV[2]); - kA[0][0] += afW[0]; - kA[0][1] += afW[1]; - kA[0][2] += afW[2]; - kA[1][1] += afV[1]*afW[1]; - kA[1][2] += afV[1]*afW[2]; - kA[2][1] += afV[2]*afW[1]; - kA[2][2] += afV[2]*afW[2]; - - kL[0][0] = 1.0f+fT2; - kL[0][1] = kL[1][0] = fT2*afV[1]; - kL[0][2] = kL[2][0] = fT2*afV[2]; - kL[1][1] = 1.0f+fT2*afV[1]*afV[1]; - kL[1][2] = kL[2][1] = fT2*afV[1]*afV[2]; - kL[2][2] = 1.0f+fT2*afV[2]*afV[2]; - bIdentity = false; - } - else - { - kL = Matrix3::IDENTITY; - bIdentity = true; - } - - // map first row to (*,*,0) - fLength = Math::Sqrt(kA[0][1]*kA[0][1]+kA[0][2]*kA[0][2]); - if ( fLength > 0.0 ) - { - fSign = (kA[0][1] > 0.0f ? 1.0f : -1.0f); - fT1 = kA[0][1] + fSign*fLength; - afV[2] = kA[0][2]/fT1; - - fT2 = -2.0f/(1.0f+afV[2]*afV[2]); - afW[0] = fT2*(kA[0][1]+kA[0][2]*afV[2]); - afW[1] = fT2*(kA[1][1]+kA[1][2]*afV[2]); - afW[2] = fT2*(kA[2][1]+kA[2][2]*afV[2]); - kA[0][1] += afW[0]; - kA[1][1] += afW[1]; - kA[1][2] += afW[1]*afV[2]; - kA[2][1] += afW[2]; - kA[2][2] += afW[2]*afV[2]; - - kR[0][0] = 1.0; - kR[0][1] = kR[1][0] = 0.0; - kR[0][2] = kR[2][0] = 0.0; - kR[1][1] = 1.0f+fT2; - kR[1][2] = kR[2][1] = fT2*afV[2]; - kR[2][2] = 1.0f+fT2*afV[2]*afV[2]; - } - else - { - kR = Matrix3::IDENTITY; - } - - // map second column to (*,*,0) - fLength = Math::Sqrt(kA[1][1]*kA[1][1]+kA[2][1]*kA[2][1]); - if ( fLength > 0.0 ) - { - fSign = (kA[1][1] > 0.0f ? 1.0f : -1.0f); - fT1 = kA[1][1] + fSign*fLength; - afV[2] = kA[2][1]/fT1; - - fT2 = -2.0f/(1.0f+afV[2]*afV[2]); - afW[1] = fT2*(kA[1][1]+kA[2][1]*afV[2]); - afW[2] = fT2*(kA[1][2]+kA[2][2]*afV[2]); - kA[1][1] += afW[1]; - kA[1][2] += afW[2]; - kA[2][2] += afV[2]*afW[2]; - - Real fA = 1.0f+fT2; - Real fB = fT2*afV[2]; - Real fC = 1.0f+fB*afV[2]; - - if ( bIdentity ) - { - kL[0][0] = 1.0; - kL[0][1] = kL[1][0] = 0.0; - kL[0][2] = kL[2][0] = 0.0; - kL[1][1] = fA; - kL[1][2] = kL[2][1] = fB; - kL[2][2] = fC; - } - else - { - for (int iRow = 0; iRow < 3; iRow++) - { - Real fTmp0 = kL[iRow][1]; - Real fTmp1 = kL[iRow][2]; - kL[iRow][1] = fA*fTmp0+fB*fTmp1; - kL[iRow][2] = fB*fTmp0+fC*fTmp1; - } - } - } - } - //----------------------------------------------------------------------- - void Matrix3::GolubKahanStep (Matrix3& kA, Matrix3& kL, - Matrix3& kR) - { - Real fT11 = kA[0][1]*kA[0][1]+kA[1][1]*kA[1][1]; - Real fT22 = kA[1][2]*kA[1][2]+kA[2][2]*kA[2][2]; - Real fT12 = kA[1][1]*kA[1][2]; - Real fTrace = fT11+fT22; - Real fDiff = fT11-fT22; - Real fDiscr = Math::Sqrt(fDiff*fDiff+4.0f*fT12*fT12); - Real fRoot1 = 0.5f*(fTrace+fDiscr); - Real fRoot2 = 0.5f*(fTrace-fDiscr); - - // adjust right - Real fY = kA[0][0] - (Math::Abs(fRoot1-fT22) <= - Math::Abs(fRoot2-fT22) ? fRoot1 : fRoot2); - Real fZ = kA[0][1]; - Real fInvLength = Math::InvSqrt(fY*fY+fZ*fZ); - Real fSin = fZ*fInvLength; - Real fCos = -fY*fInvLength; - - Real fTmp0 = kA[0][0]; - Real fTmp1 = kA[0][1]; - kA[0][0] = fCos*fTmp0-fSin*fTmp1; - kA[0][1] = fSin*fTmp0+fCos*fTmp1; - kA[1][0] = -fSin*kA[1][1]; - kA[1][1] *= fCos; - - size_t iRow; - for (iRow = 0; iRow < 3; iRow++) - { - fTmp0 = kR[0][iRow]; - fTmp1 = kR[1][iRow]; - kR[0][iRow] = fCos*fTmp0-fSin*fTmp1; - kR[1][iRow] = fSin*fTmp0+fCos*fTmp1; - } - - // adjust left - fY = kA[0][0]; - fZ = kA[1][0]; - fInvLength = Math::InvSqrt(fY*fY+fZ*fZ); - fSin = fZ*fInvLength; - fCos = -fY*fInvLength; - - kA[0][0] = fCos*kA[0][0]-fSin*kA[1][0]; - fTmp0 = kA[0][1]; - fTmp1 = kA[1][1]; - kA[0][1] = fCos*fTmp0-fSin*fTmp1; - kA[1][1] = fSin*fTmp0+fCos*fTmp1; - kA[0][2] = -fSin*kA[1][2]; - kA[1][2] *= fCos; - - size_t iCol; - for (iCol = 0; iCol < 3; iCol++) - { - fTmp0 = kL[iCol][0]; - fTmp1 = kL[iCol][1]; - kL[iCol][0] = fCos*fTmp0-fSin*fTmp1; - kL[iCol][1] = fSin*fTmp0+fCos*fTmp1; - } - - // adjust right - fY = kA[0][1]; - fZ = kA[0][2]; - fInvLength = Math::InvSqrt(fY*fY+fZ*fZ); - fSin = fZ*fInvLength; - fCos = -fY*fInvLength; - - kA[0][1] = fCos*kA[0][1]-fSin*kA[0][2]; - fTmp0 = kA[1][1]; - fTmp1 = kA[1][2]; - kA[1][1] = fCos*fTmp0-fSin*fTmp1; - kA[1][2] = fSin*fTmp0+fCos*fTmp1; - kA[2][1] = -fSin*kA[2][2]; - kA[2][2] *= fCos; - - for (iRow = 0; iRow < 3; iRow++) - { - fTmp0 = kR[1][iRow]; - fTmp1 = kR[2][iRow]; - kR[1][iRow] = fCos*fTmp0-fSin*fTmp1; - kR[2][iRow] = fSin*fTmp0+fCos*fTmp1; - } - - // adjust left - fY = kA[1][1]; - fZ = kA[2][1]; - fInvLength = Math::InvSqrt(fY*fY+fZ*fZ); - fSin = fZ*fInvLength; - fCos = -fY*fInvLength; - - kA[1][1] = fCos*kA[1][1]-fSin*kA[2][1]; - fTmp0 = kA[1][2]; - fTmp1 = kA[2][2]; - kA[1][2] = fCos*fTmp0-fSin*fTmp1; - kA[2][2] = fSin*fTmp0+fCos*fTmp1; - - for (iCol = 0; iCol < 3; iCol++) - { - fTmp0 = kL[iCol][1]; - fTmp1 = kL[iCol][2]; - kL[iCol][1] = fCos*fTmp0-fSin*fTmp1; - kL[iCol][2] = fSin*fTmp0+fCos*fTmp1; - } - } - //----------------------------------------------------------------------- - void Matrix3::SingularValueDecomposition (Matrix3& kL, Vector3& kS, - Matrix3& kR) const - { - // temas: currently unused - //const int iMax = 16; - size_t iRow, iCol; - - Matrix3 kA = *this; - Bidiagonalize(kA,kL,kR); - - // Compute 'threshold = multiplier*epsilon*|kA|' as the threshold for - // diagonal entries effectively zero; that is, |d| <= |threshold| - // implies that d is (effectively) zero. We will use the L2-norm |kA|. - Real norm = Math::Sqrt(kA[0][0] * kA[0][0] + kA[0][1] * kA[0][1] + - kA[1][1] * kA[1][1] + kA[1][2] * kA[1][2] + kA[2][2] * kA[2][2]); - Real const multiplier = (Real)8; - Real const epsilon = std::numeric_limits::epsilon(); - Real const threshold = multiplier * epsilon * norm; - - for (unsigned int i = 0; ; i++) - { - if(i == msSvdMaxIterations) - { - // ensure that we exit loop via branch that update kS - if(Math::Abs(kA[0][1]) <= Math::Abs(kA[1][2])) - kA[0][1] = 0.; - else - kA[1][2] = 0.; - } - - Real fTmp, fTmp0, fTmp1; - Real fSin0, fCos0, fTan0; - Real fSin1, fCos1, fTan1; - - bool bTest1 = (Math::Abs(kA[0][1]) <= threshold); - bool bTest2 = (Math::Abs(kA[1][2]) <= threshold); - if ( bTest1 ) - { - if ( bTest2 ) - { - kS[0] = kA[0][0]; - kS[1] = kA[1][1]; - kS[2] = kA[2][2]; - break; - } - else - { - // 2x2 closed form factorization - fTmp = (kA[1][1]*kA[1][1] - kA[2][2]*kA[2][2] + - kA[1][2]*kA[1][2])/(kA[1][2]*kA[2][2]); - fTan0 = 0.5f*(fTmp+Math::Sqrt(fTmp*fTmp + 4.0f)); - fCos0 = Math::InvSqrt(1.0f+fTan0*fTan0); - fSin0 = fTan0*fCos0; - - for (iCol = 0; iCol < 3; iCol++) - { - fTmp0 = kL[iCol][1]; - fTmp1 = kL[iCol][2]; - kL[iCol][1] = fCos0*fTmp0-fSin0*fTmp1; - kL[iCol][2] = fSin0*fTmp0+fCos0*fTmp1; - } - - fTan1 = (kA[1][2]-kA[2][2]*fTan0)/kA[1][1]; - fCos1 = Math::InvSqrt(1.0f+fTan1*fTan1); - fSin1 = -fTan1*fCos1; - - for (iRow = 0; iRow < 3; iRow++) - { - fTmp0 = kR[1][iRow]; - fTmp1 = kR[2][iRow]; - kR[1][iRow] = fCos1*fTmp0-fSin1*fTmp1; - kR[2][iRow] = fSin1*fTmp0+fCos1*fTmp1; - } - - kS[0] = kA[0][0]; - kS[1] = fCos0*fCos1*kA[1][1] - - fSin1*(fCos0*kA[1][2]-fSin0*kA[2][2]); - kS[2] = fSin0*fSin1*kA[1][1] + - fCos1*(fSin0*kA[1][2]+fCos0*kA[2][2]); - break; - } - } - else - { - if ( bTest2 ) - { - // 2x2 closed form factorization - fTmp = (kA[0][0]*kA[0][0] - kA[1][1]*kA[1][1] + - kA[0][1]*kA[0][1])/(kA[0][1]*kA[1][1]); - fTan0 = 0.5f*(fTmp+Math::Sqrt(fTmp*fTmp + 4.0f)); - fCos0 = Math::InvSqrt(1.0f+fTan0*fTan0); - fSin0 = fTan0*fCos0; - - for (iCol = 0; iCol < 3; iCol++) - { - fTmp0 = kL[iCol][0]; - fTmp1 = kL[iCol][1]; - kL[iCol][0] = fCos0*fTmp0-fSin0*fTmp1; - kL[iCol][1] = fSin0*fTmp0+fCos0*fTmp1; - } - - fTan1 = (kA[0][1]-kA[1][1]*fTan0)/kA[0][0]; - fCos1 = Math::InvSqrt(1.0f+fTan1*fTan1); - fSin1 = -fTan1*fCos1; - - for (iRow = 0; iRow < 3; iRow++) - { - fTmp0 = kR[0][iRow]; - fTmp1 = kR[1][iRow]; - kR[0][iRow] = fCos1*fTmp0-fSin1*fTmp1; - kR[1][iRow] = fSin1*fTmp0+fCos1*fTmp1; - } - - kS[0] = fCos0*fCos1*kA[0][0] - - fSin1*(fCos0*kA[0][1]-fSin0*kA[1][1]); - kS[1] = fSin0*fSin1*kA[0][0] + - fCos1*(fSin0*kA[0][1]+fCos0*kA[1][1]); - kS[2] = kA[2][2]; - break; - } - else - { - GolubKahanStep(kA,kL,kR); - } - } - } - - // positize diagonal - for (iRow = 0; iRow < 3; iRow++) - { - if ( kS[iRow] < 0.0 ) - { - kS[iRow] = -kS[iRow]; - for (iCol = 0; iCol < 3; iCol++) - kR[iRow][iCol] = -kR[iRow][iCol]; - } - } - } - //----------------------------------------------------------------------- - void Matrix3::SingularValueComposition (const Matrix3& kL, - const Vector3& kS, const Matrix3& kR) - { - size_t iRow, iCol; - Matrix3 kTmp; - - // product S*R - for (iRow = 0; iRow < 3; iRow++) - { - for (iCol = 0; iCol < 3; iCol++) - kTmp[iRow][iCol] = kS[iRow]*kR[iRow][iCol]; - } - - // product L*S*R - for (iRow = 0; iRow < 3; iRow++) - { - for (iCol = 0; iCol < 3; iCol++) - { - m[iRow][iCol] = 0.0; - for (int iMid = 0; iMid < 3; iMid++) - m[iRow][iCol] += kL[iRow][iMid]*kTmp[iMid][iCol]; - } - } - } - //----------------------------------------------------------------------- - void Matrix3::QDUDecomposition (Matrix3& kQ, - Vector3& kD, Vector3& kU) const - { - // Factor M = QR = QDU where Q is orthogonal, D is diagonal, - // and U is upper triangular with ones on its diagonal. Algorithm uses - // Gram-Schmidt orthogonalization (the QR algorithm). - // - // If M = [ m0 | m1 | m2 ] and Q = [ q0 | q1 | q2 ], then - // - // q0 = m0/|m0| - // q1 = (m1-(q0*m1)q0)/|m1-(q0*m1)q0| - // q2 = (m2-(q0*m2)q0-(q1*m2)q1)/|m2-(q0*m2)q0-(q1*m2)q1| - // - // where |V| indicates length of vector V and A*B indicates dot - // product of vectors A and B. The matrix R has entries - // - // r00 = q0*m0 r01 = q0*m1 r02 = q0*m2 - // r10 = 0 r11 = q1*m1 r12 = q1*m2 - // r20 = 0 r21 = 0 r22 = q2*m2 - // - // so D = diag(r00,r11,r22) and U has entries u01 = r01/r00, - // u02 = r02/r00, and u12 = r12/r11. - - // Q = rotation - // D = scaling - // U = shear - - // D stores the three diagonal entries r00, r11, r22 - // U stores the entries U[0] = u01, U[1] = u02, U[2] = u12 - - // build orthogonal matrix Q - kQ = orthonormalised(); - - // guarantee that orthogonal matrix has determinant 1 (no reflections) - if ( kQ.determinant() < 0.0 ) - { - for (size_t iRow = 0; iRow < 3; iRow++) - for (size_t iCol = 0; iCol < 3; iCol++) - kQ[iRow][iCol] = -kQ[iRow][iCol]; - } - - // build "right" matrix R - Matrix3 kR; - kR[0][0] = kQ.GetColumn(0).dotProduct(GetColumn(0)); - kR[0][1] = kQ.GetColumn(0).dotProduct(GetColumn(1)); - kR[0][2] = kQ.GetColumn(0).dotProduct(GetColumn(2)); - kR[1][1] = kQ.GetColumn(1).dotProduct(GetColumn(1)); - kR[1][2] = kQ.GetColumn(1).dotProduct(GetColumn(2)); - kR[2][2] = kQ.GetColumn(2).dotProduct(GetColumn(2)); - - // the scaling component - kD[0] = kR[0][0]; - kD[1] = kR[1][1]; - kD[2] = kR[2][2]; - - // the shear component - Real fInvD0 = 1.0f/kD[0]; - kU[0] = kR[0][1]*fInvD0; - kU[1] = kR[0][2]*fInvD0; - kU[2] = kR[1][2]/kD[1]; - } - //----------------------------------------------------------------------- - Real Matrix3::MaxCubicRoot (Real afCoeff[3]) - { - // Spectral norm is for A^T*A, so characteristic polynomial - // P(x) = c[0]+c[1]*x+c[2]*x^2+x^3 has three positive real roots. - // This yields the assertions c[0] < 0 and c[2]*c[2] >= 3*c[1]. - - // quick out for uniform scale (triple root) - const Real fOneThird = 1.0/3.0; - const Real fEpsilon = 1e-06; - Real fDiscr = afCoeff[2]*afCoeff[2] - 3.0f*afCoeff[1]; - if ( fDiscr <= fEpsilon ) - return -fOneThird*afCoeff[2]; - - // Compute an upper bound on roots of P(x). This assumes that A^T*A - // has been scaled by its largest entry. - Real fX = 1.0; - Real fPoly = afCoeff[0]+fX*(afCoeff[1]+fX*(afCoeff[2]+fX)); - if ( fPoly < 0.0 ) - { - // uses a matrix norm to find an upper bound on maximum root - fX = Math::Abs(afCoeff[0]); - Real fTmp = 1.0f+Math::Abs(afCoeff[1]); - if ( fTmp > fX ) - fX = fTmp; - fTmp = 1.0f+Math::Abs(afCoeff[2]); - if ( fTmp > fX ) - fX = fTmp; - } - - // Newton's method to find root - Real fTwoC2 = 2.0f*afCoeff[2]; - for (int i = 0; i < 16; i++) - { - fPoly = afCoeff[0]+fX*(afCoeff[1]+fX*(afCoeff[2]+fX)); - if ( Math::Abs(fPoly) <= fEpsilon ) - return fX; - - Real fDeriv = afCoeff[1]+fX*(fTwoC2+3.0f*fX); - fX -= fPoly/fDeriv; - } - - return fX; - } - //----------------------------------------------------------------------- - Real Matrix3::SpectralNorm () const - { - Matrix3 kP; - size_t iRow, iCol; - Real fPmax = 0.0; - for (iRow = 0; iRow < 3; iRow++) - { - for (iCol = 0; iCol < 3; iCol++) - { - kP[iRow][iCol] = 0.0; - for (int iMid = 0; iMid < 3; iMid++) - { - kP[iRow][iCol] += - m[iMid][iRow]*m[iMid][iCol]; - } - if ( kP[iRow][iCol] > fPmax ) - fPmax = kP[iRow][iCol]; - } - } - - Real fInvPmax = 1.0f/fPmax; - for (iRow = 0; iRow < 3; iRow++) - { - for (iCol = 0; iCol < 3; iCol++) - kP[iRow][iCol] *= fInvPmax; - } - - Real afCoeff[3]; - afCoeff[0] = -(kP[0][0]*(kP[1][1]*kP[2][2]-kP[1][2]*kP[2][1]) + - kP[0][1]*(kP[2][0]*kP[1][2]-kP[1][0]*kP[2][2]) + - kP[0][2]*(kP[1][0]*kP[2][1]-kP[2][0]*kP[1][1])); - afCoeff[1] = kP[0][0]*kP[1][1]-kP[0][1]*kP[1][0] + - kP[0][0]*kP[2][2]-kP[0][2]*kP[2][0] + - kP[1][1]*kP[2][2]-kP[1][2]*kP[2][1]; - afCoeff[2] = -(kP[0][0]+kP[1][1]+kP[2][2]); - - Real fRoot = MaxCubicRoot(afCoeff); - Real fNorm = Math::Sqrt(fPmax*fRoot); - return fNorm; - } - //----------------------------------------------------------------------- - void Matrix3::ToAngleAxis (Vector3& rkAxis, Radian& rfRadians) const - { - // Let (x,y,z) be the unit-length axis and let A be an angle of rotation. - // The rotation matrix is R = I + sin(A)*P + (1-cos(A))*P^2 where - // I is the identity and - // - // +- -+ - // P = | 0 -z +y | - // | +z 0 -x | - // | -y +x 0 | - // +- -+ - // - // If A > 0, R represents a counterclockwise rotation about the axis in - // the sense of looking from the tip of the axis vector towards the - // origin. Some algebra will show that - // - // cos(A) = (trace(R)-1)/2 and R - R^t = 2*sin(A)*P - // - // In the event that A = pi, R-R^t = 0 which prevents us from extracting - // the axis through P. Instead note that R = I+2*P^2 when A = pi, so - // P^2 = (R-I)/2. The diagonal entries of P^2 are x^2-1, y^2-1, and - // z^2-1. We can solve these for axis (x,y,z). Because the angle is pi, - // it does not matter which sign you choose on the square roots. - - Real fTrace = m[0][0] + m[1][1] + m[2][2]; - Real fCos = 0.5f*(fTrace-1.0f); - rfRadians = Math::ACos(fCos); // in [0,PI] - - if ( rfRadians > Radian(0.0) ) - { - if ( rfRadians < Radian(Math::PI) ) - { - rkAxis.x = m[2][1]-m[1][2]; - rkAxis.y = m[0][2]-m[2][0]; - rkAxis.z = m[1][0]-m[0][1]; - rkAxis.normalise(); - } - else - { - // angle is PI - float fHalfInverse; - if ( m[0][0] >= m[1][1] ) - { - // r00 >= r11 - if ( m[0][0] >= m[2][2] ) - { - // r00 is maximum diagonal term - rkAxis.x = 0.5f*Math::Sqrt(m[0][0] - - m[1][1] - m[2][2] + 1.0f); - fHalfInverse = 0.5f/rkAxis.x; - rkAxis.y = fHalfInverse*m[0][1]; - rkAxis.z = fHalfInverse*m[0][2]; - } - else - { - // r22 is maximum diagonal term - rkAxis.z = 0.5f*Math::Sqrt(m[2][2] - - m[0][0] - m[1][1] + 1.0f); - fHalfInverse = 0.5f/rkAxis.z; - rkAxis.x = fHalfInverse*m[0][2]; - rkAxis.y = fHalfInverse*m[1][2]; - } - } - else - { - // r11 > r00 - if ( m[1][1] >= m[2][2] ) - { - // r11 is maximum diagonal term - rkAxis.y = 0.5f*Math::Sqrt(m[1][1] - - m[0][0] - m[2][2] + 1.0f); - fHalfInverse = 0.5f/rkAxis.y; - rkAxis.x = fHalfInverse*m[0][1]; - rkAxis.z = fHalfInverse*m[1][2]; - } - else - { - // r22 is maximum diagonal term - rkAxis.z = 0.5f*Math::Sqrt(m[2][2] - - m[0][0] - m[1][1] + 1.0f); - fHalfInverse = 0.5f/rkAxis.z; - rkAxis.x = fHalfInverse*m[0][2]; - rkAxis.y = fHalfInverse*m[1][2]; - } - } - } - } - else - { - // The angle is 0 and the matrix is the identity. Any axis will - // work, so just use the x-axis. - rkAxis.x = 1.0; - rkAxis.y = 0.0; - rkAxis.z = 0.0; - } - } - //----------------------------------------------------------------------- - void Matrix3::FromAngleAxis (const Vector3& rkAxis, const Radian& fRadians) - { - Real fCos = Math::Cos(fRadians); - Real fSin = Math::Sin(fRadians); - Real fOneMinusCos = 1.0f-fCos; - Real fX2 = rkAxis.x*rkAxis.x; - Real fY2 = rkAxis.y*rkAxis.y; - Real fZ2 = rkAxis.z*rkAxis.z; - Real fXYM = rkAxis.x*rkAxis.y*fOneMinusCos; - Real fXZM = rkAxis.x*rkAxis.z*fOneMinusCos; - Real fYZM = rkAxis.y*rkAxis.z*fOneMinusCos; - Real fXSin = rkAxis.x*fSin; - Real fYSin = rkAxis.y*fSin; - Real fZSin = rkAxis.z*fSin; - - m[0][0] = fX2*fOneMinusCos+fCos; - m[0][1] = fXYM-fZSin; - m[0][2] = fXZM+fYSin; - m[1][0] = fXYM+fZSin; - m[1][1] = fY2*fOneMinusCos+fCos; - m[1][2] = fYZM-fXSin; - m[2][0] = fXZM-fYSin; - m[2][1] = fYZM+fXSin; - m[2][2] = fZ2*fOneMinusCos+fCos; - } - //----------------------------------------------------------------------- - bool Matrix3::ToEulerAnglesXYZ (Radian& rfYAngle, Radian& rfPAngle, - Radian& rfRAngle) const - { - // rot = cy*cz -cy*sz sy - // cz*sx*sy+cx*sz cx*cz-sx*sy*sz -cy*sx - // -cx*cz*sy+sx*sz cz*sx+cx*sy*sz cx*cy - - rfPAngle = Radian(Math::ASin(m[0][2])); - if ( rfPAngle < Radian(Math::HALF_PI) ) - { - if ( rfPAngle > Radian(-Math::HALF_PI) ) - { - rfYAngle = Math::ATan2(-m[1][2],m[2][2]); - rfRAngle = Math::ATan2(-m[0][1],m[0][0]); - return true; - } - else - { - // WARNING. Not a unique solution. - Radian fRmY = Math::ATan2(m[1][0],m[1][1]); - rfRAngle = Radian(0.0); // any angle works - rfYAngle = rfRAngle - fRmY; - return false; - } - } - else - { - // WARNING. Not a unique solution. - Radian fRpY = Math::ATan2(m[1][0],m[1][1]); - rfRAngle = Radian(0.0); // any angle works - rfYAngle = fRpY - rfRAngle; - return false; - } - } - //----------------------------------------------------------------------- - bool Matrix3::ToEulerAnglesXZY (Radian& rfYAngle, Radian& rfPAngle, - Radian& rfRAngle) const - { - // rot = cy*cz -sz cz*sy - // sx*sy+cx*cy*sz cx*cz -cy*sx+cx*sy*sz - // -cx*sy+cy*sx*sz cz*sx cx*cy+sx*sy*sz - - rfPAngle = Math::ASin(-m[0][1]); - if ( rfPAngle < Radian(Math::HALF_PI) ) - { - if ( rfPAngle > Radian(-Math::HALF_PI) ) - { - rfYAngle = Math::ATan2(m[2][1],m[1][1]); - rfRAngle = Math::ATan2(m[0][2],m[0][0]); - return true; - } - else - { - // WARNING. Not a unique solution. - Radian fRmY = Math::ATan2(-m[2][0],m[2][2]); - rfRAngle = Radian(0.0); // any angle works - rfYAngle = rfRAngle - fRmY; - return false; - } - } - else - { - // WARNING. Not a unique solution. - Radian fRpY = Math::ATan2(-m[2][0],m[2][2]); - rfRAngle = Radian(0.0); // any angle works - rfYAngle = fRpY - rfRAngle; - return false; - } - } - //----------------------------------------------------------------------- - bool Matrix3::ToEulerAnglesYXZ (Radian& rfYAngle, Radian& rfPAngle, - Radian& rfRAngle) const - { - // rot = cy*cz+sx*sy*sz cz*sx*sy-cy*sz cx*sy - // cx*sz cx*cz -sx - // -cz*sy+cy*sx*sz cy*cz*sx+sy*sz cx*cy - - rfPAngle = Math::ASin(-m[1][2]); - if ( rfPAngle < Radian(Math::HALF_PI) ) - { - if ( rfPAngle > Radian(-Math::HALF_PI) ) - { - rfYAngle = Math::ATan2(m[0][2],m[2][2]); - rfRAngle = Math::ATan2(m[1][0],m[1][1]); - return true; - } - else - { - // WARNING. Not a unique solution. - Radian fRmY = Math::ATan2(-m[0][1],m[0][0]); - rfRAngle = Radian(0.0); // any angle works - rfYAngle = rfRAngle - fRmY; - return false; - } - } - else - { - // WARNING. Not a unique solution. - Radian fRpY = Math::ATan2(-m[0][1],m[0][0]); - rfRAngle = Radian(0.0); // any angle works - rfYAngle = fRpY - rfRAngle; - return false; - } - } - //----------------------------------------------------------------------- - bool Matrix3::ToEulerAnglesYZX (Radian& rfYAngle, Radian& rfPAngle, - Radian& rfRAngle) const - { - // rot = cy*cz sx*sy-cx*cy*sz cx*sy+cy*sx*sz - // sz cx*cz -cz*sx - // -cz*sy cy*sx+cx*sy*sz cx*cy-sx*sy*sz - - rfPAngle = Math::ASin(m[1][0]); - if ( rfPAngle < Radian(Math::HALF_PI) ) - { - if ( rfPAngle > Radian(-Math::HALF_PI) ) - { - rfYAngle = Math::ATan2(-m[2][0],m[0][0]); - rfRAngle = Math::ATan2(-m[1][2],m[1][1]); - return true; - } - else - { - // WARNING. Not a unique solution. - Radian fRmY = Math::ATan2(m[2][1],m[2][2]); - rfRAngle = Radian(0.0); // any angle works - rfYAngle = rfRAngle - fRmY; - return false; - } - } - else - { - // WARNING. Not a unique solution. - Radian fRpY = Math::ATan2(m[2][1],m[2][2]); - rfRAngle = Radian(0.0); // any angle works - rfYAngle = fRpY - rfRAngle; - return false; - } - } - //----------------------------------------------------------------------- - bool Matrix3::ToEulerAnglesZXY (Radian& rfYAngle, Radian& rfPAngle, - Radian& rfRAngle) const - { - // rot = cy*cz-sx*sy*sz -cx*sz cz*sy+cy*sx*sz - // cz*sx*sy+cy*sz cx*cz -cy*cz*sx+sy*sz - // -cx*sy sx cx*cy - - rfPAngle = Math::ASin(m[2][1]); - if ( rfPAngle < Radian(Math::HALF_PI) ) - { - if ( rfPAngle > Radian(-Math::HALF_PI) ) - { - rfYAngle = Math::ATan2(-m[0][1],m[1][1]); - rfRAngle = Math::ATan2(-m[2][0],m[2][2]); - return true; - } - else - { - // WARNING. Not a unique solution. - Radian fRmY = Math::ATan2(m[0][2],m[0][0]); - rfRAngle = Radian(0.0); // any angle works - rfYAngle = rfRAngle - fRmY; - return false; - } - } - else - { - // WARNING. Not a unique solution. - Radian fRpY = Math::ATan2(m[0][2],m[0][0]); - rfRAngle = Radian(0.0); // any angle works - rfYAngle = fRpY - rfRAngle; - return false; - } - } - //----------------------------------------------------------------------- - bool Matrix3::ToEulerAnglesZYX (Radian& rfYAngle, Radian& rfPAngle, - Radian& rfRAngle) const - { - // rot = cy*cz cz*sx*sy-cx*sz cx*cz*sy+sx*sz - // cy*sz cx*cz+sx*sy*sz -cz*sx+cx*sy*sz - // -sy cy*sx cx*cy - - rfPAngle = Math::ASin(-m[2][0]); - if ( rfPAngle < Radian(Math::HALF_PI) ) - { - if ( rfPAngle > Radian(-Math::HALF_PI) ) - { - rfYAngle = Math::ATan2(m[1][0],m[0][0]); - rfRAngle = Math::ATan2(m[2][1],m[2][2]); - return true; - } - else - { - // WARNING. Not a unique solution. - Radian fRmY = Math::ATan2(-m[0][1],m[0][2]); - rfRAngle = Radian(0.0); // any angle works - rfYAngle = rfRAngle - fRmY; - return false; - } - } - else - { - // WARNING. Not a unique solution. - Radian fRpY = Math::ATan2(-m[0][1],m[0][2]); - rfRAngle = Radian(0.0); // any angle works - rfYAngle = fRpY - rfRAngle; - return false; - } - } - //----------------------------------------------------------------------- - void Matrix3::FromEulerAnglesXYZ (const Radian& fYAngle, const Radian& fPAngle, - const Radian& fRAngle) - { - Real fCos, fSin; - - fCos = Math::Cos(fYAngle); - fSin = Math::Sin(fYAngle); - Matrix3 kXMat(1.0,0.0,0.0,0.0,fCos,-fSin,0.0,fSin,fCos); - - fCos = Math::Cos(fPAngle); - fSin = Math::Sin(fPAngle); - Matrix3 kYMat(fCos,0.0,fSin,0.0,1.0,0.0,-fSin,0.0,fCos); - - fCos = Math::Cos(fRAngle); - fSin = Math::Sin(fRAngle); - Matrix3 kZMat(fCos,-fSin,0.0,fSin,fCos,0.0,0.0,0.0,1.0); - - *this = kXMat*(kYMat*kZMat); - } - //----------------------------------------------------------------------- - void Matrix3::FromEulerAnglesXZY (const Radian& fYAngle, const Radian& fPAngle, - const Radian& fRAngle) - { - Real fCos, fSin; - - fCos = Math::Cos(fYAngle); - fSin = Math::Sin(fYAngle); - Matrix3 kXMat(1.0,0.0,0.0,0.0,fCos,-fSin,0.0,fSin,fCos); - - fCos = Math::Cos(fPAngle); - fSin = Math::Sin(fPAngle); - Matrix3 kZMat(fCos,-fSin,0.0,fSin,fCos,0.0,0.0,0.0,1.0); - - fCos = Math::Cos(fRAngle); - fSin = Math::Sin(fRAngle); - Matrix3 kYMat(fCos,0.0,fSin,0.0,1.0,0.0,-fSin,0.0,fCos); - - *this = kXMat*(kZMat*kYMat); - } - //----------------------------------------------------------------------- - void Matrix3::FromEulerAnglesYXZ (const Radian& fYAngle, const Radian& fPAngle, - const Radian& fRAngle) - { - Real fCos, fSin; - - fCos = Math::Cos(fYAngle); - fSin = Math::Sin(fYAngle); - Matrix3 kYMat(fCos,0.0,fSin,0.0,1.0,0.0,-fSin,0.0,fCos); - - fCos = Math::Cos(fPAngle); - fSin = Math::Sin(fPAngle); - Matrix3 kXMat(1.0,0.0,0.0,0.0,fCos,-fSin,0.0,fSin,fCos); - - fCos = Math::Cos(fRAngle); - fSin = Math::Sin(fRAngle); - Matrix3 kZMat(fCos,-fSin,0.0,fSin,fCos,0.0,0.0,0.0,1.0); - - *this = kYMat*(kXMat*kZMat); - } - //----------------------------------------------------------------------- - void Matrix3::FromEulerAnglesYZX (const Radian& fYAngle, const Radian& fPAngle, - const Radian& fRAngle) - { - Real fCos, fSin; - - fCos = Math::Cos(fYAngle); - fSin = Math::Sin(fYAngle); - Matrix3 kYMat(fCos,0.0,fSin,0.0,1.0,0.0,-fSin,0.0,fCos); - - fCos = Math::Cos(fPAngle); - fSin = Math::Sin(fPAngle); - Matrix3 kZMat(fCos,-fSin,0.0,fSin,fCos,0.0,0.0,0.0,1.0); - - fCos = Math::Cos(fRAngle); - fSin = Math::Sin(fRAngle); - Matrix3 kXMat(1.0,0.0,0.0,0.0,fCos,-fSin,0.0,fSin,fCos); - - *this = kYMat*(kZMat*kXMat); - } - //----------------------------------------------------------------------- - void Matrix3::FromEulerAnglesZXY (const Radian& fYAngle, const Radian& fPAngle, - const Radian& fRAngle) - { - Real fCos, fSin; - - fCos = Math::Cos(fYAngle); - fSin = Math::Sin(fYAngle); - Matrix3 kZMat(fCos,-fSin,0.0,fSin,fCos,0.0,0.0,0.0,1.0); - - fCos = Math::Cos(fPAngle); - fSin = Math::Sin(fPAngle); - Matrix3 kXMat(1.0,0.0,0.0,0.0,fCos,-fSin,0.0,fSin,fCos); - - fCos = Math::Cos(fRAngle); - fSin = Math::Sin(fRAngle); - Matrix3 kYMat(fCos,0.0,fSin,0.0,1.0,0.0,-fSin,0.0,fCos); - - *this = kZMat*(kXMat*kYMat); - } - //----------------------------------------------------------------------- - void Matrix3::FromEulerAnglesZYX (const Radian& fYAngle, const Radian& fPAngle, - const Radian& fRAngle) - { - Real fCos, fSin; - - fCos = Math::Cos(fYAngle); - fSin = Math::Sin(fYAngle); - Matrix3 kZMat(fCos,-fSin,0.0,fSin,fCos,0.0,0.0,0.0,1.0); - - fCos = Math::Cos(fPAngle); - fSin = Math::Sin(fPAngle); - Matrix3 kYMat(fCos,0.0,fSin,0.0,1.0,0.0,-fSin,0.0,fCos); - - fCos = Math::Cos(fRAngle); - fSin = Math::Sin(fRAngle); - Matrix3 kXMat(1.0,0.0,0.0,0.0,fCos,-fSin,0.0,fSin,fCos); - - *this = kZMat*(kYMat*kXMat); - } - //----------------------------------------------------------------------- - void Matrix3::Tridiagonal (Real afDiag[3], Real afSubDiag[3]) - { - // Householder reduction T = Q^t M Q - // Input: - // mat, symmetric 3x3 matrix M - // Output: - // mat, orthogonal matrix Q - // diag, diagonal entries of T - // subd, subdiagonal entries of T (T is symmetric) - - Real fA = m[0][0]; - Real fB = m[0][1]; - Real fC = m[0][2]; - Real fD = m[1][1]; - Real fE = m[1][2]; - Real fF = m[2][2]; - - afDiag[0] = fA; - afSubDiag[2] = 0.0; - if ( Math::Abs(fC) >= EPSILON ) - { - Real fLength = Math::Sqrt(fB*fB+fC*fC); - Real fInvLength = 1.0f/fLength; - fB *= fInvLength; - fC *= fInvLength; - Real fQ = 2.0f*fB*fE+fC*(fF-fD); - afDiag[1] = fD+fC*fQ; - afDiag[2] = fF-fC*fQ; - afSubDiag[0] = fLength; - afSubDiag[1] = fE-fB*fQ; - m[0][0] = 1.0; - m[0][1] = 0.0; - m[0][2] = 0.0; - m[1][0] = 0.0; - m[1][1] = fB; - m[1][2] = fC; - m[2][0] = 0.0; - m[2][1] = fC; - m[2][2] = -fB; - } - else - { - afDiag[1] = fD; - afDiag[2] = fF; - afSubDiag[0] = fB; - afSubDiag[1] = fE; - m[0][0] = 1.0; - m[0][1] = 0.0; - m[0][2] = 0.0; - m[1][0] = 0.0; - m[1][1] = 1.0; - m[1][2] = 0.0; - m[2][0] = 0.0; - m[2][1] = 0.0; - m[2][2] = 1.0; - } - } - //----------------------------------------------------------------------- - bool Matrix3::QLAlgorithm (Real afDiag[3], Real afSubDiag[3]) - { - // QL iteration with implicit shifting to reduce matrix from tridiagonal - // to diagonal - - for (int i0 = 0; i0 < 3; i0++) - { - const unsigned int iMaxIter = 32; - unsigned int iIter; - for (iIter = 0; iIter < iMaxIter; iIter++) - { - int i1; - for (i1 = i0; i1 <= 1; i1++) - { - Real fSum = Math::Abs(afDiag[i1]) + - Math::Abs(afDiag[i1+1]); - if ( Math::Abs(afSubDiag[i1]) + fSum == fSum ) - break; - } - if ( i1 == i0 ) - break; - - Real fTmp0 = (afDiag[i0+1]-afDiag[i0])/(2.0f*afSubDiag[i0]); - Real fTmp1 = Math::Sqrt(fTmp0*fTmp0+1.0f); - if ( fTmp0 < 0.0 ) - fTmp0 = afDiag[i1]-afDiag[i0]+afSubDiag[i0]/(fTmp0-fTmp1); - else - fTmp0 = afDiag[i1]-afDiag[i0]+afSubDiag[i0]/(fTmp0+fTmp1); - Real fSin = 1.0; - Real fCos = 1.0; - Real fTmp2 = 0.0; - for (int i2 = i1-1; i2 >= i0; i2--) - { - Real fTmp3 = fSin*afSubDiag[i2]; - Real fTmp4 = fCos*afSubDiag[i2]; - if ( Math::Abs(fTmp3) >= Math::Abs(fTmp0) ) - { - fCos = fTmp0/fTmp3; - fTmp1 = Math::Sqrt(fCos*fCos+1.0f); - afSubDiag[i2+1] = fTmp3*fTmp1; - fSin = 1.0f/fTmp1; - fCos *= fSin; - } - else - { - fSin = fTmp3/fTmp0; - fTmp1 = Math::Sqrt(fSin*fSin+1.0f); - afSubDiag[i2+1] = fTmp0*fTmp1; - fCos = 1.0f/fTmp1; - fSin *= fCos; - } - fTmp0 = afDiag[i2+1]-fTmp2; - fTmp1 = (afDiag[i2]-fTmp0)*fSin+2.0f*fTmp4*fCos; - fTmp2 = fSin*fTmp1; - afDiag[i2+1] = fTmp0+fTmp2; - fTmp0 = fCos*fTmp1-fTmp4; - - for (int iRow = 0; iRow < 3; iRow++) - { - fTmp3 = m[iRow][i2+1]; - m[iRow][i2+1] = fSin*m[iRow][i2] + - fCos*fTmp3; - m[iRow][i2] = fCos*m[iRow][i2] - - fSin*fTmp3; - } - } - afDiag[i0] -= fTmp2; - afSubDiag[i0] = fTmp0; - afSubDiag[i1] = 0.0; - } - - if ( iIter == iMaxIter ) - { - // should not get here under normal circumstances - return false; - } - } - - return true; - } - //----------------------------------------------------------------------- - void Matrix3::EigenSolveSymmetric (Real afEigenvalue[3], - Vector3 akEigenvector[3]) const - { - Matrix3 kMatrix = *this; - Real afSubDiag[3]; - kMatrix.Tridiagonal(afEigenvalue,afSubDiag); - kMatrix.QLAlgorithm(afEigenvalue,afSubDiag); - - for (size_t i = 0; i < 3; i++) - { - akEigenvector[i][0] = kMatrix[0][i]; - akEigenvector[i][1] = kMatrix[1][i]; - akEigenvector[i][2] = kMatrix[2][i]; - } - - // make eigenvectors form a right--handed system - Vector3 kCross = akEigenvector[1].crossProduct(akEigenvector[2]); - Real fDet = akEigenvector[0].dotProduct(kCross); - if ( fDet < 0.0 ) - { - akEigenvector[2][0] = - akEigenvector[2][0]; - akEigenvector[2][1] = - akEigenvector[2][1]; - akEigenvector[2][2] = - akEigenvector[2][2]; - } - } - //----------------------------------------------------------------------- - void Matrix3::TensorProduct (const Vector3& rkU, const Vector3& rkV, - Matrix3& rkProduct) - { - for (size_t iRow = 0; iRow < 3; iRow++) - { - for (size_t iCol = 0; iCol < 3; iCol++) - rkProduct[iRow][iCol] = rkU[iRow]*rkV[iCol]; - } - } - //----------------------------------------------------------------------- -} diff --git a/OgreMain/src/OgreMatrix4.cpp b/OgreMain/src/OgreMatrix4.cpp deleted file mode 100644 index 0dcc5a225c8..00000000000 --- a/OgreMain/src/OgreMatrix4.cpp +++ /dev/null @@ -1,259 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -namespace Ogre -{ - - const Matrix4 Matrix4::ZERO( - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0 ); - - const Affine3 Affine3::ZERO( - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0); - - const Affine3 Affine3::IDENTITY( - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0); - - const Matrix4 Matrix4::IDENTITY( - 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 ); - - const Matrix4 Matrix4::CLIPSPACE2DTOIMAGESPACE( - 0.5, 0, 0, 0.5, - 0, -0.5, 0, 0.5, - 0, 0, 1, 0, - 0, 0, 0, 1); - - //----------------------------------------------------------------------- - static Real - MINOR(const TransformBaseReal& m, const size_t r0, const size_t r1, const size_t r2, - const size_t c0, const size_t c1, const size_t c2) - { - return m[r0][c0] * (m[r1][c1] * m[r2][c2] - m[r2][c1] * m[r1][c2]) - - m[r0][c1] * (m[r1][c0] * m[r2][c2] - m[r2][c0] * m[r1][c2]) + - m[r0][c2] * (m[r1][c0] * m[r2][c1] - m[r2][c0] * m[r1][c1]); - } - //----------------------------------------------------------------------- - Matrix4 Matrix4::adjoint() const - { - return Matrix4( MINOR(*this, 1, 2, 3, 1, 2, 3), - -MINOR(*this, 0, 2, 3, 1, 2, 3), - MINOR(*this, 0, 1, 3, 1, 2, 3), - -MINOR(*this, 0, 1, 2, 1, 2, 3), - - -MINOR(*this, 1, 2, 3, 0, 2, 3), - MINOR(*this, 0, 2, 3, 0, 2, 3), - -MINOR(*this, 0, 1, 3, 0, 2, 3), - MINOR(*this, 0, 1, 2, 0, 2, 3), - - MINOR(*this, 1, 2, 3, 0, 1, 3), - -MINOR(*this, 0, 2, 3, 0, 1, 3), - MINOR(*this, 0, 1, 3, 0, 1, 3), - -MINOR(*this, 0, 1, 2, 0, 1, 3), - - -MINOR(*this, 1, 2, 3, 0, 1, 2), - MINOR(*this, 0, 2, 3, 0, 1, 2), - -MINOR(*this, 0, 1, 3, 0, 1, 2), - MINOR(*this, 0, 1, 2, 0, 1, 2)); - } - //----------------------------------------------------------------------- - Real TransformBaseReal::determinant() const - { - return m[0][0] * MINOR(*this, 1, 2, 3, 1, 2, 3) - - m[0][1] * MINOR(*this, 1, 2, 3, 0, 2, 3) + - m[0][2] * MINOR(*this, 1, 2, 3, 0, 1, 3) - - m[0][3] * MINOR(*this, 1, 2, 3, 0, 1, 2); - } - //----------------------------------------------------------------------- - Matrix4 Matrix4::inverse() const - { - Real m00 = m[0][0], m01 = m[0][1], m02 = m[0][2], m03 = m[0][3]; - Real m10 = m[1][0], m11 = m[1][1], m12 = m[1][2], m13 = m[1][3]; - Real m20 = m[2][0], m21 = m[2][1], m22 = m[2][2], m23 = m[2][3]; - Real m30 = m[3][0], m31 = m[3][1], m32 = m[3][2], m33 = m[3][3]; - - Real v0 = m20 * m31 - m21 * m30; - Real v1 = m20 * m32 - m22 * m30; - Real v2 = m20 * m33 - m23 * m30; - Real v3 = m21 * m32 - m22 * m31; - Real v4 = m21 * m33 - m23 * m31; - Real v5 = m22 * m33 - m23 * m32; - - Real t00 = + (v5 * m11 - v4 * m12 + v3 * m13); - Real t10 = - (v5 * m10 - v2 * m12 + v1 * m13); - Real t20 = + (v4 * m10 - v2 * m11 + v0 * m13); - Real t30 = - (v3 * m10 - v1 * m11 + v0 * m12); - - Real invDet = 1 / (t00 * m00 + t10 * m01 + t20 * m02 + t30 * m03); - - Real d00 = t00 * invDet; - Real d10 = t10 * invDet; - Real d20 = t20 * invDet; - Real d30 = t30 * invDet; - - Real d01 = - (v5 * m01 - v4 * m02 + v3 * m03) * invDet; - Real d11 = + (v5 * m00 - v2 * m02 + v1 * m03) * invDet; - Real d21 = - (v4 * m00 - v2 * m01 + v0 * m03) * invDet; - Real d31 = + (v3 * m00 - v1 * m01 + v0 * m02) * invDet; - - v0 = m10 * m31 - m11 * m30; - v1 = m10 * m32 - m12 * m30; - v2 = m10 * m33 - m13 * m30; - v3 = m11 * m32 - m12 * m31; - v4 = m11 * m33 - m13 * m31; - v5 = m12 * m33 - m13 * m32; - - Real d02 = + (v5 * m01 - v4 * m02 + v3 * m03) * invDet; - Real d12 = - (v5 * m00 - v2 * m02 + v1 * m03) * invDet; - Real d22 = + (v4 * m00 - v2 * m01 + v0 * m03) * invDet; - Real d32 = - (v3 * m00 - v1 * m01 + v0 * m02) * invDet; - - v0 = m21 * m10 - m20 * m11; - v1 = m22 * m10 - m20 * m12; - v2 = m23 * m10 - m20 * m13; - v3 = m22 * m11 - m21 * m12; - v4 = m23 * m11 - m21 * m13; - v5 = m23 * m12 - m22 * m13; - - Real d03 = - (v5 * m01 - v4 * m02 + v3 * m03) * invDet; - Real d13 = + (v5 * m00 - v2 * m02 + v1 * m03) * invDet; - Real d23 = - (v4 * m00 - v2 * m01 + v0 * m03) * invDet; - Real d33 = + (v3 * m00 - v1 * m01 + v0 * m02) * invDet; - - return Matrix4( - d00, d01, d02, d03, - d10, d11, d12, d13, - d20, d21, d22, d23, - d30, d31, d32, d33); - } - //----------------------------------------------------------------------- - Affine3 Affine3::inverse() const - { - Real m10 = m[1][0], m11 = m[1][1], m12 = m[1][2]; - Real m20 = m[2][0], m21 = m[2][1], m22 = m[2][2]; - - Real t00 = m22 * m11 - m21 * m12; - Real t10 = m20 * m12 - m22 * m10; - Real t20 = m21 * m10 - m20 * m11; - - Real m00 = m[0][0], m01 = m[0][1], m02 = m[0][2]; - - Real invDet = 1 / (m00 * t00 + m01 * t10 + m02 * t20); - - t00 *= invDet; t10 *= invDet; t20 *= invDet; - - m00 *= invDet; m01 *= invDet; m02 *= invDet; - - Real r00 = t00; - Real r01 = m02 * m21 - m01 * m22; - Real r02 = m01 * m12 - m02 * m11; - - Real r10 = t10; - Real r11 = m00 * m22 - m02 * m20; - Real r12 = m02 * m10 - m00 * m12; - - Real r20 = t20; - Real r21 = m01 * m20 - m00 * m21; - Real r22 = m00 * m11 - m01 * m10; - - Real m03 = m[0][3], m13 = m[1][3], m23 = m[2][3]; - - Real r03 = - (r00 * m03 + r01 * m13 + r02 * m23); - Real r13 = - (r10 * m03 + r11 * m13 + r12 * m23); - Real r23 = - (r20 * m03 + r21 * m13 + r22 * m23); - - return Affine3( - r00, r01, r02, r03, - r10, r11, r12, r13, - r20, r21, r22, r23); - } - //----------------------------------------------------------------------- - void TransformBaseReal::makeTransform(const Vector3& position, const Vector3& scale, const Quaternion& orientation) - { - // Ordering: - // 1. Scale - // 2. Rotate - // 3. Translate - - Matrix3 rot3x3; - orientation.ToRotationMatrix(rot3x3); - - // Set up final matrix with scale, rotation and translation - m[0][0] = scale.x * rot3x3[0][0]; m[0][1] = scale.y * rot3x3[0][1]; m[0][2] = scale.z * rot3x3[0][2]; m[0][3] = position.x; - m[1][0] = scale.x * rot3x3[1][0]; m[1][1] = scale.y * rot3x3[1][1]; m[1][2] = scale.z * rot3x3[1][2]; m[1][3] = position.y; - m[2][0] = scale.x * rot3x3[2][0]; m[2][1] = scale.y * rot3x3[2][1]; m[2][2] = scale.z * rot3x3[2][2]; m[2][3] = position.z; - - // No projection term - m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1; - } - //----------------------------------------------------------------------- - void TransformBaseReal::makeInverseTransform(const Vector3& position, const Vector3& scale, const Quaternion& orientation) - { - // Invert the parameters - Vector3 invTranslate = -position; - Vector3 invScale(1 / scale.x, 1 / scale.y, 1 / scale.z); - Quaternion invRot = orientation.Inverse(); - - // Because we're inverting, order is translation, rotation, scale - // So make translation relative to scale & rotation - invTranslate = invRot * invTranslate; // rotate - invTranslate *= invScale; // scale - - // Next, make a 3x3 rotation matrix - Matrix3 rot3x3; - invRot.ToRotationMatrix(rot3x3); - - // Set up final matrix with scale, rotation and translation - m[0][0] = invScale.x * rot3x3[0][0]; m[0][1] = invScale.x * rot3x3[0][1]; m[0][2] = invScale.x * rot3x3[0][2]; m[0][3] = invTranslate.x; - m[1][0] = invScale.y * rot3x3[1][0]; m[1][1] = invScale.y * rot3x3[1][1]; m[1][2] = invScale.y * rot3x3[1][2]; m[1][3] = invTranslate.y; - m[2][0] = invScale.z * rot3x3[2][0]; m[2][1] = invScale.z * rot3x3[2][1]; m[2][2] = invScale.z * rot3x3[2][2]; m[2][3] = invTranslate.z; - - // No projection term - m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1; - } - //----------------------------------------------------------------------- - void Affine3::decomposition(Vector3& position, Vector3& scale, Quaternion& orientation) const - { - Matrix3 matQ; - Vector3 vecU; - linear().QDUDecomposition( matQ, scale, vecU ); - - orientation = Quaternion( matQ ); - position = Vector3( m[0][3], m[1][3], m[2][3] ); - } - -} diff --git a/OgreMain/src/OgreMesh.cpp b/OgreMain/src/OgreMesh.cpp deleted file mode 100644 index 453d17ac4bf..00000000000 --- a/OgreMain/src/OgreMesh.cpp +++ /dev/null @@ -1,2366 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreSkeletonManager.h" -#include "OgreEdgeListBuilder.h" -#include "OgreAnimation.h" -#include "OgreAnimationState.h" -#include "OgreAnimationTrack.h" -#include "OgreOptimisedUtil.h" -#include "OgreTangentSpaceCalc.h" -#include "OgreLodStrategyManager.h" -#include "OgrePixelCountLodStrategy.h" - -namespace Ogre { - //----------------------------------------------------------------------- - Mesh::Mesh(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - : Resource(creator, name, handle, group, isManual, loader), - mBoundRadius(0.0f), - mBoneBoundingRadius(0.0f), - mBoneAssignmentsOutOfDate(false), - mLodStrategy(LodStrategyManager::getSingleton().getDefaultStrategy()), - mHasManualLodLevel(false), - mNumLods(1), - mBufferManager(0), - mVertexBufferUsage(HBU_GPU_ONLY), - mIndexBufferUsage(HBU_GPU_ONLY), - mVertexBufferShadowBuffer(false), - mIndexBufferShadowBuffer(false), - mPreparedForShadowVolumes(false), - mEdgeListsBuilt(false), - mAutoBuildEdgeLists(false), // will be set to true by serializers of 1.20 and below - mSharedVertexDataAnimationType(VAT_NONE), - mSharedVertexDataAnimationIncludesNormals(false), - mAnimationTypesDirty(true), - mPosesIncludeNormals(false), - sharedVertexData(0) - { - // Init first (manual) lod - MeshLodUsage lod; - lod.userValue = 0; // User value not used for base LOD level - lod.value = getLodStrategy()->getBaseValue(); - lod.edgeData = NULL; - lod.manualMesh.reset(); - mMeshLodUsageList.push_back(lod); - } - //----------------------------------------------------------------------- - Mesh::~Mesh() - { - if (!HardwareBufferManager::getSingletonPtr()) // LogManager might be also gone already - { - printf("ERROR: '%s' is being destroyed after HardwareBufferManager. This is a bug in user code.\n", mName.c_str()); - OgreAssertDbg(false, "Mesh destroyed after HardwareBufferManager"); // assert in debug mode - return; // try not to crash - } - // have to call this here reather than in Resource destructor - // since calling virtual methods in base destructors causes crash - unload(); - } - //----------------------------------------------------------------------- - HardwareBufferManagerBase* Mesh::getHardwareBufferManager() - { - return mBufferManager ? mBufferManager : HardwareBufferManager::getSingletonPtr(); - } - //----------------------------------------------------------------------- - SubMesh* Mesh::createSubMesh() - { - SubMesh* sub = OGRE_NEW SubMesh(); - sub->parent = this; - - mSubMeshList.push_back(sub); - - if (isLoaded()) - _dirtyState(); - - return sub; - } - //----------------------------------------------------------------------- - SubMesh* Mesh::createSubMesh(const String& name) - { - SubMesh *sub = createSubMesh(); - nameSubMesh(name, (ushort)mSubMeshList.size()-1); - return sub ; - } - //----------------------------------------------------------------------- - void Mesh::destroySubMesh(unsigned short index) - { - OgreAssert(index < mSubMeshList.size(), ""); - SubMeshList::iterator i = mSubMeshList.begin(); - std::advance(i, index); - OGRE_DELETE *i; - mSubMeshList.erase(i); - - // Fix up any name/index entries - for(SubMeshNameMap::iterator ni = mSubMeshNameMap.begin(); ni != mSubMeshNameMap.end();) - { - if (ni->second == index) - { - SubMeshNameMap::iterator eraseIt = ni++; - mSubMeshNameMap.erase(eraseIt); - } - else - { - // reduce indexes following - if (ni->second > index) - ni->second = ni->second - 1; - - ++ni; - } - } - - // fix edge list data by simply recreating all edge lists - if( mEdgeListsBuilt) - { - this->freeEdgeList(); - this->buildEdgeList(); - } - - if (isLoaded()) - _dirtyState(); - - } - //----------------------------------------------------------------------- - void Mesh::destroySubMesh(const String& name) - { - unsigned short index = _getSubMeshIndex(name); - destroySubMesh(index); - } - //--------------------------------------------------------------------- - void Mesh::nameSubMesh(const String& name, ushort index) - { - mSubMeshNameMap[name] = index ; - } - - //--------------------------------------------------------------------- - void Mesh::unnameSubMesh(const String& name) - { - SubMeshNameMap::iterator i = mSubMeshNameMap.find(name); - if (i != mSubMeshNameMap.end()) - mSubMeshNameMap.erase(i); - } - //----------------------------------------------------------------------- - SubMesh* Mesh::getSubMesh(const String& name) const - { - ushort index = _getSubMeshIndex(name); - return getSubMesh(index); - } - //----------------------------------------------------------------------- - void Mesh::postLoadImpl(void) - { - // Prepare for shadow volumes? - if (MeshManager::getSingleton().getPrepareAllMeshesForShadowVolumes()) - { - if (mEdgeListsBuilt || mAutoBuildEdgeLists) - { - prepareForShadowVolume(); - } - - if (!mEdgeListsBuilt && mAutoBuildEdgeLists) - { - buildEdgeList(); - } - } -#if !OGRE_NO_MESHLOD - // The loading process accesses LOD usages directly, so - // transformation of user values must occur after loading is complete. - - // Transform user LOD values (starting at index 1, no need to transform base value) - for (MeshLodUsageList::iterator i = mMeshLodUsageList.begin() + 1; i != mMeshLodUsageList.end(); ++i) - i->value = mLodStrategy->transformUserValue(i->userValue); - // Rewrite first value - mMeshLodUsageList[0].value = mLodStrategy->getBaseValue(); -#endif - } - //----------------------------------------------------------------------- - void Mesh::prepareImpl() - { - // Load from specified 'name' - if (getCreator()->getVerbose()) - LogManager::getSingleton().logMessage("Mesh: Loading "+mName+"."); - - mFreshFromDisk = - ResourceGroupManager::getSingleton().openResource( - mName, mGroup, this); - - // fully prebuffer into host RAM - mFreshFromDisk = DataStreamPtr(OGRE_NEW MemoryDataStream(mName,mFreshFromDisk)); - } - //----------------------------------------------------------------------- - void Mesh::unprepareImpl() - { - mFreshFromDisk.reset(); - } - void Mesh::loadImpl() - { - // If the only copy is local on the stack, it will be cleaned - // up reliably in case of exceptions, etc - DataStreamPtr data(mFreshFromDisk); - mFreshFromDisk.reset(); - - if (!data) { - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, - "Data doesn't appear to have been prepared in " + mName, - "Mesh::loadImpl()"); - } - - String baseName, strExt; - StringUtil::splitBaseFilename(mName, baseName, strExt); - auto codec = Codec::getCodec(strExt); - if (!codec) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "No codec found to load " + mName); - - codec->decode(data, this); - } - - //----------------------------------------------------------------------- - void Mesh::unloadImpl() - { - // Teardown submeshes - for (auto & i : mSubMeshList) - { - OGRE_DELETE i; - } - if (sharedVertexData) - { - resetVertexData(); - } - // Clear SubMesh lists - mSubMeshList.clear(); - mSubMeshNameMap.clear(); - - freeEdgeList(); -#if !OGRE_NO_MESHLOD - // Removes all LOD data - removeLodLevels(); -#endif - mPreparedForShadowVolumes = false; - - // remove all poses & animations - removeAllAnimations(); - removeAllPoses(); - - // Clear bone assignments - mBoneAssignments.clear(); - mBoneAssignmentsOutOfDate = false; - - // Removes reference to skeleton - mSkeleton.reset(); - } - //----------------------------------------------------------------------- - void Mesh::reload(LoadingFlags flags) - { - bool wasPreparedForShadowVolumes = mPreparedForShadowVolumes; - bool wasEdgeListsBuilt = mEdgeListsBuilt; - bool wasAutoBuildEdgeLists = mAutoBuildEdgeLists; - - Resource::reload(flags); - - if(flags & LF_PRESERVE_STATE) - { - if(wasPreparedForShadowVolumes) - prepareForShadowVolume(); - if(wasEdgeListsBuilt) - buildEdgeList(); - setAutoBuildEdgeLists(wasAutoBuildEdgeLists); - } - } - //----------------------------------------------------------------------- - MeshPtr Mesh::clone(const String& newName, const String& newGroup) - { - // This is a bit like a copy constructor, but with the additional aspect of registering the clone with - // the MeshManager - - // New Mesh is assumed to be manually defined rather than loaded since you're cloning it for a reason - String theGroup = newGroup.empty() ? this->getGroup() : newGroup; - MeshPtr newMesh = MeshManager::getSingleton().createManual(newName, theGroup); - - if(!newMesh) // interception by collision handler - return newMesh; - - newMesh->mBufferManager = mBufferManager; - newMesh->mVertexBufferUsage = mVertexBufferUsage; - newMesh->mIndexBufferUsage = mIndexBufferUsage; - newMesh->mVertexBufferShadowBuffer = mVertexBufferShadowBuffer; - newMesh->mIndexBufferShadowBuffer = mIndexBufferShadowBuffer; - - // Copy submeshes first - for (auto *subi : mSubMeshList) - { - subi->clone("", newMesh.get()); - } - - // Copy shared geometry and index map, if any - if (sharedVertexData) - { - newMesh->resetVertexData(sharedVertexData->clone(true, mBufferManager)); - newMesh->sharedBlendIndexToBoneIndexMap = sharedBlendIndexToBoneIndexMap; - } - - // Copy submesh names - newMesh->mSubMeshNameMap = mSubMeshNameMap ; - // Copy any bone assignments - newMesh->mBoneAssignments = mBoneAssignments; - newMesh->mBoneAssignmentsOutOfDate = mBoneAssignmentsOutOfDate; - // Copy bounds - newMesh->mAABB = mAABB; - newMesh->mBoundRadius = mBoundRadius; - newMesh->mBoneBoundingRadius = mBoneBoundingRadius; - newMesh->mAutoBuildEdgeLists = mAutoBuildEdgeLists; - newMesh->mEdgeListsBuilt = mEdgeListsBuilt; - -#if !OGRE_NO_MESHLOD - newMesh->mHasManualLodLevel = mHasManualLodLevel; - newMesh->mLodStrategy = mLodStrategy; - newMesh->mNumLods = mNumLods; - newMesh->mMeshLodUsageList = mMeshLodUsageList; -#endif - // Unreference edge lists, otherwise we'll delete the same lot twice, build on demand - MeshLodUsageList::iterator lodOldi; - lodOldi = mMeshLodUsageList.begin(); - for (auto& lodi : newMesh->mMeshLodUsageList) { - MeshLodUsage& lod = *lodOldi; - lodi.manualName = lod.manualName; - lodi.userValue = lod.userValue; - lodi.value = lod.value; - if (lod.edgeData) { - lodi.edgeData = lod.edgeData->clone(); - } - ++lodOldi; - } - - newMesh->mSkeleton = mSkeleton; - - // Keep prepared shadow volume info (buffers may already be prepared) - newMesh->mPreparedForShadowVolumes = mPreparedForShadowVolumes; - - newMesh->mEdgeListsBuilt = mEdgeListsBuilt; - - // Clone vertex animation - for (auto & i : mAnimationsList) - { - Animation *newAnim = i.second->clone(i.second->getName()); - newMesh->mAnimationsList[i.second->getName()] = newAnim; - } - // Clone pose list - for (auto & i : mPoseList) - { - Pose* newPose = i->clone(); - newMesh->mPoseList.push_back(newPose); - } - newMesh->mSharedVertexDataAnimationType = mSharedVertexDataAnimationType; - newMesh->mAnimationTypesDirty = true; - - newMesh->load(); - newMesh->touch(); - - return newMesh; - } - //----------------------------------------------------------------------- - const AxisAlignedBox& Mesh::getBounds(void) const - { - return mAABB; - } - //----------------------------------------------------------------------- - void Mesh::_setBounds(const AxisAlignedBox& bounds, bool pad) - { - mAABB = bounds; - mBoundRadius = Math::boundingRadiusFromAABB(mAABB); - - if( mAABB.isFinite() ) - { - Vector3 max = mAABB.getMaximum(); - Vector3 min = mAABB.getMinimum(); - - if (pad) - { - // Pad out the AABB a little, helps with most bounds tests - Vector3 scaler = (max - min) * MeshManager::getSingleton().getBoundsPaddingFactor(); - mAABB.setExtents(min - scaler, max + scaler); - // Pad out the sphere a little too - mBoundRadius = mBoundRadius + (mBoundRadius * MeshManager::getSingleton().getBoundsPaddingFactor()); - } - } - } - //----------------------------------------------------------------------- - void Mesh::_setBoundingSphereRadius(Real radius) - { - mBoundRadius = radius; - } - //----------------------------------------------------------------------- - void Mesh::_setBoneBoundingRadius(Real radius) - { - mBoneBoundingRadius = radius; - } - //----------------------------------------------------------------------- - void Mesh::_updateBoundsFromVertexBuffers(bool pad) - { - bool extendOnly = false; // First time we need full AABB of the given submesh, but on the second call just extend that one. - if (sharedVertexData){ - _calcBoundsFromVertexBuffer(sharedVertexData, mAABB, mBoundRadius, extendOnly); - extendOnly = true; - } - for (auto & i : mSubMeshList){ - if (i->vertexData){ - _calcBoundsFromVertexBuffer(i->vertexData, mAABB, mBoundRadius, extendOnly); - extendOnly = true; - } - } - if (pad) - { - Vector3 max = mAABB.getMaximum(); - Vector3 min = mAABB.getMinimum(); - // Pad out the AABB a little, helps with most bounds tests - Vector3 scaler = (max - min) * MeshManager::getSingleton().getBoundsPaddingFactor(); - mAABB.setExtents(min - scaler, max + scaler); - // Pad out the sphere a little too - mBoundRadius = mBoundRadius + (mBoundRadius * MeshManager::getSingleton().getBoundsPaddingFactor()); - } - } - void Mesh::_calcBoundsFromVertexBuffer(VertexData* vertexData, AxisAlignedBox& outAABB, Real& outRadius, bool extendOnly /*= false*/) - { - if (vertexData->vertexCount == 0) { - if (!extendOnly) { - outAABB = AxisAlignedBox(Vector3::ZERO, Vector3::ZERO); - outRadius = 0; - } - return; - } - const VertexElement* elemPos = vertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); - HardwareVertexBufferSharedPtr vbuf = vertexData->vertexBufferBinding->getBuffer(elemPos->getSource()); - HardwareBufferLockGuard vertexLock(vbuf, HardwareBuffer::HBL_READ_ONLY); - unsigned char* vertex = static_cast(vertexLock.pData); - - if (!extendOnly){ - // init values - outRadius = 0; - float* pFloat; - elemPos->baseVertexPointerToElement(vertex, &pFloat); - Vector3 basePos(pFloat[0], pFloat[1], pFloat[2]); - outAABB.setExtents(basePos, basePos); - } - size_t vSize = vbuf->getVertexSize(); - unsigned char* vEnd = vertex + vertexData->vertexCount * vSize; - Real radiusSqr = outRadius * outRadius; - // Loop through all vertices. - for (; vertex < vEnd; vertex += vSize) { - float* pFloat; - elemPos->baseVertexPointerToElement(vertex, &pFloat); - Vector3 pos(pFloat[0], pFloat[1], pFloat[2]); - outAABB.getMinimum().makeFloor(pos); - outAABB.getMaximum().makeCeil(pos); - radiusSqr = std::max(radiusSqr, pos.squaredLength()); - } - outRadius = std::sqrt(radiusSqr); - } - //----------------------------------------------------------------------- - void Mesh::setSkeletonName(const String& skelName) - { - if (skelName != getSkeletonName()) - { - if (skelName.empty()) - { - // No skeleton - mSkeleton.reset(); - } - else - { - // Load skeleton - try { - mSkeleton = static_pointer_cast(SkeletonManager::getSingleton().load(skelName, mGroup)); - } - catch (...) - { - mSkeleton.reset(); - // Log this error - String msg = "Unable to load skeleton '"; - msg += skelName + "' for Mesh '" + mName + "'. This Mesh will not be animated."; - LogManager::getSingleton().logError(msg); - - } - - - } - if (isLoaded()) - _dirtyState(); - } - } - //----------------------------------------------------------------------- - void Mesh::addBoneAssignment(const VertexBoneAssignment& vertBoneAssign) - { - mBoneAssignments.emplace(vertBoneAssign.vertexIndex, vertBoneAssign); - mBoneAssignmentsOutOfDate = true; - } - //----------------------------------------------------------------------- - void Mesh::clearBoneAssignments(void) - { - mBoneAssignments.clear(); - mBoneAssignmentsOutOfDate = true; - } - //----------------------------------------------------------------------- - void Mesh::_initAnimationState(AnimationStateSet* animSet) - { - // Animation states for skeletal animation - if (mSkeleton) - { - // Delegate to Skeleton - mSkeleton->_initAnimationState(animSet); - - // Take the opportunity to update the compiled bone assignments - _updateCompiledBoneAssignments(); - - } - - // Animation states for vertex animation - for (auto & i : mAnimationsList) - { - // Only create a new animation state if it doesn't exist - // We can have the same named animation in both skeletal and vertex - // with a shared animation state affecting both, for combined effects - // The animations should be the same length if this feature is used! - if (!animSet->hasAnimationState(i.second->getName())) - { - animSet->createAnimationState(i.second->getName(), 0.0, - i.second->getLength()); - } - - } - - } - //--------------------------------------------------------------------- - void Mesh::_refreshAnimationState(AnimationStateSet* animSet) - { - if (mSkeleton) - { - mSkeleton->_refreshAnimationState(animSet); - } - - // Merge in any new vertex animations - for (auto& i : mAnimationsList) - { - // Create animation at time index 0, default params mean this has weight 1 and is disabled - auto anim = i.second; - const String& animName = anim->getName(); - if (!animSet->hasAnimationState(animName)) - { - animSet->createAnimationState(animName, 0.0, anim->getLength()); - } - else - { - // Update length incase changed - AnimationState* animState = animSet->getAnimationState(animName); - animState->setLength(anim->getLength()); - animState->setTimePosition(std::min(anim->getLength(), animState->getTimePosition())); - } - } - } - //----------------------------------------------------------------------- - void Mesh::_updateCompiledBoneAssignments(void) - { - if (mBoneAssignmentsOutOfDate) - _compileBoneAssignments(); - - for (auto *m : mSubMeshList) - { - if (m->mBoneAssignmentsOutOfDate) - { - m->_compileBoneAssignments(); - } - } - } - //----------------------------------------------------------------------- - typedef std::multimap WeightIteratorMap; - unsigned short Mesh::_rationaliseBoneAssignments(size_t vertexCount, Mesh::VertexBoneAssignmentList& assignments) - { - // Iterate through, finding the largest # bones per vertex - unsigned short maxBones = 0; - bool existsNonSkinnedVertices = false; - VertexBoneAssignmentList::iterator i; - - for (size_t v = 0; v < vertexCount; ++v) - { - // Get number of entries for this vertex - short currBones = static_cast(assignments.count(v)); - if (currBones <= 0) - existsNonSkinnedVertices = true; - - // Deal with max bones update - // (note this will record maxBones even if they exceed limit) - if (maxBones < currBones) - maxBones = currBones; - // does the number of bone assignments exceed limit? - if (currBones > OGRE_MAX_BLEND_WEIGHTS) - { - // To many bone assignments on this vertex - // Find the start & end (end is in iterator terms ie exclusive) - std::pair range; - // map to sort by weight - WeightIteratorMap weightToAssignmentMap; - range = assignments.equal_range(v); - // Add all the assignments to map - for (i = range.first; i != range.second; ++i) - { - // insert value weight->iterator - weightToAssignmentMap.emplace(i->second.weight, i); - } - // Reverse iterate over weight map, remove lowest n - unsigned short numToRemove = currBones - OGRE_MAX_BLEND_WEIGHTS; - WeightIteratorMap::iterator remIt = weightToAssignmentMap.begin(); - - while (numToRemove--) - { - // Erase this one - assignments.erase(remIt->second); - ++remIt; - } - } // if (currBones > OGRE_MAX_BLEND_WEIGHTS) - - // Make sure the weights are normalised - // Do this irrespective of whether we had to remove assignments or not - // since it gives us a guarantee that weights are normalised - // We assume this, so it's a good idea since some modellers may not - std::pair normalise_range = assignments.equal_range(v); - Real totalWeight = 0; - // Find total first - for (i = normalise_range.first; i != normalise_range.second; ++i) - { - totalWeight += i->second.weight; - } - // Now normalise if total weight is outside tolerance - if (!Math::RealEqual(totalWeight, 1.0f)) - { - for (i = normalise_range.first; i != normalise_range.second; ++i) - { - i->second.weight = i->second.weight / totalWeight; - } - } - - } - - if (maxBones > OGRE_MAX_BLEND_WEIGHTS) - { - // Warn that we've reduced bone assignments - LogManager::getSingleton().logWarning("the mesh '" + mName + "' " - "includes vertices with more than " + - StringConverter::toString(OGRE_MAX_BLEND_WEIGHTS) + " bone assignments. " - "The lowest weighted assignments beyond this limit have been removed, so " - "your animation may look slightly different. To eliminate this, reduce " - "the number of bone assignments per vertex on your mesh to " + - StringConverter::toString(OGRE_MAX_BLEND_WEIGHTS) + "."); - // we've adjusted them down to the max - maxBones = OGRE_MAX_BLEND_WEIGHTS; - - } - - if (existsNonSkinnedVertices) - { - // Warn that we've non-skinned vertices - LogManager::getSingleton().logWarning("the mesh '" + mName + "' " - "includes vertices without bone assignments. Those vertices will " - "transform to wrong position when skeletal animation enabled. " - "To eliminate this, assign at least one bone assignment per vertex " - "on your mesh."); - } - - return maxBones; - } - //----------------------------------------------------------------------- - void Mesh::_compileBoneAssignments(void) - { - if (sharedVertexData) - { - unsigned short maxBones = _rationaliseBoneAssignments(sharedVertexData->vertexCount, mBoneAssignments); - - if (maxBones != 0) - { - compileBoneAssignments(mBoneAssignments, maxBones, - sharedBlendIndexToBoneIndexMap, sharedVertexData); - } - } - mBoneAssignmentsOutOfDate = false; - } - //--------------------------------------------------------------------- - void Mesh::buildIndexMap(const VertexBoneAssignmentList& boneAssignments, - IndexMap& boneIndexToBlendIndexMap, IndexMap& blendIndexToBoneIndexMap) - { - if (boneAssignments.empty()) - { - // Just in case - boneIndexToBlendIndexMap.clear(); - blendIndexToBoneIndexMap.clear(); - return; - } - - typedef std::set BoneIndexSet; - BoneIndexSet usedBoneIndices; - - // Collect actually used bones - for (auto& itVBA : boneAssignments) - { - usedBoneIndices.insert(itVBA.second.boneIndex); - } - - // Allocate space for index map - blendIndexToBoneIndexMap.resize(usedBoneIndices.size()); - boneIndexToBlendIndexMap.resize(*usedBoneIndices.rbegin() + 1); - - // Make index map between bone index and blend index - unsigned short blendIndex = 0; - for (auto& itBoneIndex : usedBoneIndices) - { - boneIndexToBlendIndexMap[itBoneIndex] = blendIndex; - blendIndexToBoneIndexMap[blendIndex] = itBoneIndex; - ++blendIndex; - } - } - //--------------------------------------------------------------------- - void Mesh::compileBoneAssignments( - const VertexBoneAssignmentList& boneAssignments, - unsigned short numBlendWeightsPerVertex, - IndexMap& blendIndexToBoneIndexMap, - VertexData* targetVertexData) - { - // Create or reuse blend weight / indexes buffer - // Indices are always a UBYTE4 no matter how many weights per vertex - VertexDeclaration* decl = targetVertexData->vertexDeclaration; - VertexBufferBinding* bind = targetVertexData->vertexBufferBinding; - unsigned short bindIndex; - - // Build the index map brute-force. It's possible to store the index map - // in .mesh, but maybe trivial. - IndexMap boneIndexToBlendIndexMap; - buildIndexMap(boneAssignments, boneIndexToBlendIndexMap, blendIndexToBoneIndexMap); - - const VertexElement* testElem = - decl->findElementBySemantic(VES_BLEND_INDICES); - if (testElem) - { - // Already have a buffer, unset it & delete elements - bindIndex = testElem->getSource(); - // unset will cause deletion of buffer - bind->unsetBinding(bindIndex); - decl->removeElement(VES_BLEND_INDICES); - decl->removeElement(VES_BLEND_WEIGHTS); - } - else - { - // Get new binding - bindIndex = bind->getNextIndex(); - } - // type of Weights is settable on the MeshManager. - VertexElementType weightsBaseType = MeshManager::getSingleton().getBlendWeightsBaseElementType(); - VertexElementType weightsVertexElemType = VertexElement::multiplyTypeCount( weightsBaseType, numBlendWeightsPerVertex ); - HardwareVertexBufferSharedPtr vbuf = getHardwareBufferManager()->createVertexBuffer( - sizeof( unsigned char ) * 4 + VertexElement::getTypeSize( weightsVertexElemType ), - targetVertexData->vertexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY, - true // use shadow buffer - ); - // bind new buffer - bind->setBinding(bindIndex, vbuf); - const VertexElement *pIdxElem, *pWeightElem; - - // add new vertex elements - // Note, insert directly after all elements using the same source as - // position to abide by pre-Dx9 format restrictions - const VertexElement* firstElem = decl->getElement(0); - if(firstElem->getSemantic() == VES_POSITION) - { - unsigned short insertPoint = 1; - while (insertPoint < decl->getElementCount() && - decl->getElement(insertPoint)->getSource() == firstElem->getSource()) - { - ++insertPoint; - } - const VertexElement& idxElem = - decl->insertElement(insertPoint, bindIndex, 0, VET_UBYTE4, VES_BLEND_INDICES); - const VertexElement& wtElem = - decl->insertElement(insertPoint+1, bindIndex, sizeof(unsigned char)*4, weightsVertexElemType, VES_BLEND_WEIGHTS); - pIdxElem = &idxElem; - pWeightElem = &wtElem; - } - else - { - // Position is not the first semantic, therefore this declaration is - // not pre-Dx9 compatible anyway, so just tack it on the end - const VertexElement& idxElem = - decl->addElement(bindIndex, 0, VET_UBYTE4, VES_BLEND_INDICES); - const VertexElement& wtElem = - decl->addElement(bindIndex, sizeof(unsigned char)*4, weightsVertexElemType, VES_BLEND_WEIGHTS ); - pIdxElem = &idxElem; - pWeightElem = &wtElem; - } - - unsigned int maxIntWt = 0; - // keeping a switch out of the loop - switch ( weightsBaseType ) - { - default: - OgreAssert(false, "Invalid BlendWeightsBaseElementType"); - break; - case VET_FLOAT1: - break; - case VET_UBYTE4_NORM: - maxIntWt = 0xff; - break; - case VET_USHORT2_NORM: - maxIntWt = 0xffff; - break; - case VET_SHORT2_NORM: - maxIntWt = 0x7fff; - break; - } - // Assign data - size_t v; - VertexBoneAssignmentList::const_iterator i, iend; - i = boneAssignments.begin(); - iend = boneAssignments.end(); - HardwareBufferLockGuard vertexLock(vbuf, HardwareBuffer::HBL_DISCARD); - unsigned char *pBase = static_cast(vertexLock.pData); - // Iterate by vertex - for (v = 0; v < targetVertexData->vertexCount; ++v) - { - // collect the indices/weights in these arrays - unsigned char indices[ 4 ] = { 0, 0, 0, 0 }; - float weights[ 4 ] = { 1.0f, 0.0f, 0.0f, 0.0f }; - for (unsigned short bone = 0; bone < numBlendWeightsPerVertex; ++bone) - { - // Do we still have data for this vertex? - if (i != iend && i->second.vertexIndex == v) - { - // If so, grab weight and index - weights[ bone ] = i->second.weight; - indices[ bone ] = static_cast( boneIndexToBlendIndexMap[ i->second.boneIndex ] ); - ++i; - } - } - // if weights are integers, - if ( weightsBaseType != VET_FLOAT1 ) - { - // pack the float weights into shorts/bytes - unsigned int intWeights[ 4 ]; - unsigned int sum = 0; - const unsigned int wtScale = maxIntWt; // this value corresponds to a weight of 1.0 - for ( int ii = 0; ii < 4; ++ii ) - { - unsigned int bw = static_cast( weights[ ii ] * wtScale ); - intWeights[ ii ] = bw; - sum += bw; - } - // if the sum doesn't add up due to roundoff error, we need to adjust the intWeights so that the sum is wtScale - if ( sum != maxIntWt ) - { - // find the largest weight (it isn't necessarily the first one...) - int iMaxWeight = 0; - unsigned int maxWeight = 0; - for ( int ii = 0; ii < 4; ++ii ) - { - unsigned int bw = intWeights[ ii ]; - if ( bw > maxWeight ) - { - iMaxWeight = ii; - maxWeight = bw; - } - } - // Adjust the largest weight to make sure the sum is correct. - // The idea is that changing the largest weight will have the smallest effect - // on the ratio of weights. This works best when there is one dominant weight, - // and worst when 2 or more weights are similar in magnitude. - // A better method could be used to reduce the quantization error, but this is - // being done at run-time so it needs to be quick. - intWeights[ iMaxWeight ] += maxIntWt - sum; - } - - // now write the weights - if ( weightsBaseType == VET_UBYTE4_NORM ) - { - // write out the weights as bytes - unsigned char* pWeight; - pWeightElem->baseVertexPointerToElement( pBase, &pWeight ); - // NOTE: always writes out 4 regardless of numBlendWeightsPerVertex - for (unsigned int intWeight : intWeights) - { - *pWeight++ = static_cast( intWeight ); - } - } - else - { - // write out the weights as shorts - unsigned short* pWeight; - pWeightElem->baseVertexPointerToElement( pBase, &pWeight ); - for ( int ii = 0; ii < numBlendWeightsPerVertex; ++ii ) - { - *pWeight++ = static_cast( intWeights[ ii ] ); - } - } - } - else - { - // write out the weights as floats - float* pWeight; - pWeightElem->baseVertexPointerToElement( pBase, &pWeight ); - for ( int ii = 0; ii < numBlendWeightsPerVertex; ++ii ) - { - *pWeight++ = weights[ ii ]; - } - } - unsigned char* pIndex; - pIdxElem->baseVertexPointerToElement( pBase, &pIndex ); - for (unsigned char indice : indices) - { - *pIndex++ = indice; - } - pBase += vbuf->getVertexSize(); - } - } - //--------------------------------------------------------------------- - static Real distLineSegToPoint( const Vector3& line0, const Vector3& line1, const Vector3& pt ) - { - Vector3 v01 = line1 - line0; - Real tt = v01.dotProduct( pt - line0 ) / std::max( v01.dotProduct(v01), std::numeric_limits::epsilon() ); - tt = Math::Clamp( tt, Real(0.0f), Real(1.0f) ); - Vector3 onLine = line0 + tt * v01; - return pt.distance( onLine ); - } - //--------------------------------------------------------------------- - static Real _computeBoneBoundingRadiusHelper( VertexData* vertexData, - const Mesh::VertexBoneAssignmentList& boneAssignments, - const std::vector& bonePositions, - const std::vector< std::vector >& boneChildren - ) - { - std::vector vertexPositions; - { - // extract vertex positions - const VertexElement* posElem = vertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); - HardwareVertexBufferSharedPtr vbuf = vertexData->vertexBufferBinding->getBuffer(posElem->getSource()); - // if usage is write only, - if ( !vbuf->hasShadowBuffer() && (vbuf->getUsage() & HBU_DETAIL_WRITE_ONLY) ) - { - // can't do it - return Real(0.0f); - } - vertexPositions.resize( vertexData->vertexCount ); - HardwareBufferLockGuard vertexLock(vbuf, HardwareBuffer::HBL_READ_ONLY); - unsigned char* vertex = static_cast(vertexLock.pData); - float* pFloat; - - for(size_t i = 0; i < vertexData->vertexCount; ++i) - { - posElem->baseVertexPointerToElement(vertex, &pFloat); - vertexPositions[ i ] = Vector3( pFloat[0], pFloat[1], pFloat[2] ); - vertex += vbuf->getVertexSize(); - } - } - Real maxRadius = Real(0); - Real minWeight = Real(0.01); - // for each vertex-bone assignment, - for (const auto & boneAssignment : boneAssignments) - { - // if weight is close to zero, ignore - if (boneAssignment.second.weight > minWeight) - { - // if we have a bounding box around all bone origins, we consider how far outside this box the - // current vertex could ever get (assuming it is only attached to the given bone, and the bones all have unity scale) - size_t iBone = boneAssignment.second.boneIndex; - const Vector3& v = vertexPositions[ boneAssignment.second.vertexIndex ]; - Vector3 diff = v - bonePositions[ iBone ]; - Real dist = diff.length(); // max distance of vertex v outside of bounding box - // if this bone has children, we can reduce the dist under the assumption that the children may rotate wrt their parent, but don't translate - for (size_t iChild = 0; iChild < boneChildren[iBone].size(); ++iChild) - { - // given this assumption, we know that the bounding box will enclose both the bone origin as well as the origin of the child bone, - // and therefore everything on a line segment between the bone origin and the child bone will be inside the bounding box as well - size_t iChildBone = boneChildren[ iBone ][ iChild ]; - // compute distance from vertex to line segment between bones - Real distChild = distLineSegToPoint( bonePositions[ iBone ], bonePositions[ iChildBone ], v ); - dist = std::min( dist, distChild ); - } - // scale the distance by the weight, this prevents the radius from being over-inflated because of a vertex that is lightly influenced by a faraway bone - dist *= boneAssignment.second.weight; - maxRadius = std::max( maxRadius, dist ); - } - } - return maxRadius; - } - //--------------------------------------------------------------------- - void Mesh::_computeBoneBoundingRadius() - { - if (mBoneBoundingRadius == Real(0) && mSkeleton) - { - Real radius = Real(0); - std::vector bonePositions; - std::vector< std::vector > boneChildren; // for each bone, a list of children - { - // extract binding pose bone positions, and also indices for child bones - uint16 numBones = mSkeleton->getNumBones(); - mSkeleton->setBindingPose(); - mSkeleton->_updateTransforms(); - bonePositions.resize( numBones ); - boneChildren.resize( numBones ); - // for each bone, - for (uint16 iBone = 0; iBone < numBones; ++iBone) - { - Bone* bone = mSkeleton->getBone( iBone ); - bonePositions[ iBone ] = bone->_getDerivedPosition(); - boneChildren[ iBone ].reserve( bone->numChildren() ); - for (uint16 iChild = 0; iChild < bone->numChildren(); ++iChild) - { - Bone* child = static_cast( bone->getChild( iChild ) ); - boneChildren[ iBone ].push_back( child->getHandle() ); - } - } - } - if (sharedVertexData) - { - // check shared vertices - radius = _computeBoneBoundingRadiusHelper(sharedVertexData, mBoneAssignments, bonePositions, boneChildren); - } - - // check submesh vertices - for(auto *submesh : mSubMeshList) - { - if (!submesh->useSharedVertices && submesh->vertexData) - { - Real r = _computeBoneBoundingRadiusHelper(submesh->vertexData, submesh->mBoneAssignments, bonePositions, boneChildren); - radius = std::max( radius, r ); - } - } - if (radius > Real(0)) - { - mBoneBoundingRadius = radius; - } - else - { - // fallback if we failed to find the vertices - mBoneBoundingRadius = mBoundRadius; - } - } - } - //--------------------------------------------------------------------- - void Mesh::_notifySkeleton(const SkeletonPtr& pSkel) - { - mSkeleton = pSkel; - } - //--------------------------------------------------------------------- - Mesh::BoneAssignmentIterator Mesh::getBoneAssignmentIterator(void) - { - return BoneAssignmentIterator(mBoneAssignments.begin(), - mBoneAssignments.end()); - } - //--------------------------------------------------------------------- - const String& Mesh::getSkeletonName(void) const - { - return mSkeleton ? mSkeleton->getName() : BLANKSTRING; - } - //--------------------------------------------------------------------- - const MeshLodUsage& Mesh::getLodLevel(ushort index) const - { -#if !OGRE_NO_MESHLOD - index = std::min(index, (ushort)(mMeshLodUsageList.size() - 1)); - if (this->_isManualLodLevel(index) && index > 0 && !mMeshLodUsageList[index].manualMesh) - { - // Load the mesh now - try { - mMeshLodUsageList[index].manualMesh = - MeshManager::getSingleton().load( - mMeshLodUsageList[index].manualName, - getGroup()); - // get the edge data, if required - if (!mMeshLodUsageList[index].edgeData) - { - mMeshLodUsageList[index].edgeData = - mMeshLodUsageList[index].manualMesh->getEdgeList(0); - } - } - catch (Exception& ) - { - LogManager::getSingleton().stream() - << "Error while loading manual LOD level " - << mMeshLodUsageList[index].manualName - << " - this LOD level will not be rendered. You can " - << "ignore this error in offline mesh tools."; - } - - } - return mMeshLodUsageList[index]; -#else - return mMeshLodUsageList[0]; -#endif - } - //--------------------------------------------------------------------- - ushort Mesh::getLodIndex(Real value) const - { -#if !OGRE_NO_MESHLOD - // Get index from strategy - return mLodStrategy->getIndex(value, mMeshLodUsageList); -#else - return 0; -#endif - } - //--------------------------------------------------------------------- -#if !OGRE_NO_MESHLOD - void Mesh::updateManualLodLevel(ushort index, const String& meshName) - { - - // Basic prerequisites - assert(index != 0 && "Can't modify first LOD level (full detail)"); - assert(index < mMeshLodUsageList.size() && "Idndex out of bounds"); - // get lod - MeshLodUsage* lod = &(mMeshLodUsageList[index]); - - lod->manualName = meshName; - lod->manualMesh.reset(); - OGRE_DELETE lod->edgeData; - lod->edgeData = 0; - } - //--------------------------------------------------------------------- - void Mesh::_setLodInfo(unsigned short numLevels) - { - assert(!mEdgeListsBuilt && "Can't modify LOD after edge lists built"); - - // Basic prerequisites - assert(numLevels > 0 && "Must be at least one level (full detail level must exist)"); - - mNumLods = numLevels; - mMeshLodUsageList.resize(numLevels); - // Resize submesh face data lists too - for (auto & i : mSubMeshList) - { - i->mLodFaceList.resize(numLevels - 1); - } - } - //--------------------------------------------------------------------- - void Mesh::_setLodUsage(unsigned short level, const MeshLodUsage& usage) - { - assert(!mEdgeListsBuilt && "Can't modify LOD after edge lists built"); - - // Basic prerequisites - assert(level != 0 && "Can't modify first LOD level (full detail)"); - assert(level < mMeshLodUsageList.size() && "Index out of bounds"); - - mMeshLodUsageList[level] = usage; - - if(!mMeshLodUsageList[level].manualName.empty()){ - mHasManualLodLevel = true; - } - } - //--------------------------------------------------------------------- - void Mesh::_setSubMeshLodFaceList(unsigned short subIdx, unsigned short level, - IndexData* facedata) - { - assert(!mEdgeListsBuilt && "Can't modify LOD after edge lists built"); - - // Basic prerequisites - assert(mMeshLodUsageList[level].manualName.empty() && "Not using generated LODs!"); - assert(subIdx < mSubMeshList.size() && "Index out of bounds"); - assert(level != 0 && "Can't modify first LOD level (full detail)"); - assert(level-1 < (unsigned short)mSubMeshList[subIdx]->mLodFaceList.size() && "Index out of bounds"); - - SubMesh* sm = mSubMeshList[subIdx]; - sm->mLodFaceList[level - 1] = facedata; - } -#endif - //--------------------------------------------------------------------- - bool Mesh::_isManualLodLevel( unsigned short level ) const - { -#if !OGRE_NO_MESHLOD - return !mMeshLodUsageList[level].manualName.empty(); -#else - return false; -#endif - } - //--------------------------------------------------------------------- - ushort Mesh::_getSubMeshIndex(const String& name) const - { - SubMeshNameMap::const_iterator i = mSubMeshNameMap.find(name) ; - if (i == mSubMeshNameMap.end()) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "No SubMesh named " + name + " found.", - "Mesh::_getSubMeshIndex"); - - return i->second; - } - //-------------------------------------------------------------------- - void Mesh::removeLodLevels(void) - { -#if !OGRE_NO_MESHLOD - // Remove data from SubMeshes - for (auto *isub : mSubMeshList) - { - isub->removeLodLevels(); - } - - bool edgeListWasBuilt = isEdgeListBuilt(); - freeEdgeList(); - - // Reinitialise - mNumLods = 1; - mMeshLodUsageList.resize(1); - mMeshLodUsageList[0].edgeData = NULL; - - if(edgeListWasBuilt) - buildEdgeList(); -#endif - } - - //--------------------------------------------------------------------- - Real Mesh::getBoundingSphereRadius(void) const - { - return mBoundRadius; - } - //--------------------------------------------------------------------- - Real Mesh::getBoneBoundingRadius(void) const - { - return mBoneBoundingRadius; - } - //--------------------------------------------------------------------- - void Mesh::setVertexBufferPolicy(HardwareBuffer::Usage vbUsage, bool shadowBuffer) - { - mVertexBufferUsage = (HardwareBufferUsage)vbUsage; - mVertexBufferShadowBuffer = shadowBuffer; - } - //--------------------------------------------------------------------- - void Mesh::setIndexBufferPolicy(HardwareBuffer::Usage vbUsage, bool shadowBuffer) - { - mIndexBufferUsage = (HardwareBufferUsage)vbUsage; - mIndexBufferShadowBuffer = shadowBuffer; - } - //--------------------------------------------------------------------- - void Mesh::mergeAdjacentTexcoords( unsigned short finalTexCoordSet, - unsigned short texCoordSetToDestroy ) - { - if( sharedVertexData ) - mergeAdjacentTexcoords( finalTexCoordSet, texCoordSetToDestroy, sharedVertexData ); - - for (auto *s : mSubMeshList) - { - if(!s->useSharedVertices) - mergeAdjacentTexcoords (finalTexCoordSet, texCoordSetToDestroy, s->vertexData ); - } - } - //--------------------------------------------------------------------- - void Mesh::mergeAdjacentTexcoords( unsigned short finalTexCoordSet, - unsigned short texCoordSetToDestroy, - VertexData *vertexData ) - { - VertexDeclaration *vDecl = vertexData->vertexDeclaration; - - const VertexElement *uv0 = vDecl->findElementBySemantic( VES_TEXTURE_COORDINATES, - finalTexCoordSet ); - const VertexElement *uv1 = vDecl->findElementBySemantic( VES_TEXTURE_COORDINATES, - texCoordSetToDestroy ); - - if( uv0 && uv1 ) - { - //Check that both base types are compatible (mix floats w/ shorts) and there's enough space - VertexElementType baseType0 = VertexElement::getBaseType( uv0->getType() ); - VertexElementType baseType1 = VertexElement::getBaseType( uv1->getType() ); - - unsigned short totalTypeCount = VertexElement::getTypeCount( uv0->getType() ) + - VertexElement::getTypeCount( uv1->getType() ); - if( baseType0 == baseType1 && totalTypeCount <= 4 ) - { - const VertexDeclaration::VertexElementList &veList = vDecl->getElements(); - VertexDeclaration::VertexElementList::const_iterator uv0Itor = std::find( veList.begin(), - veList.end(), *uv0 ); - unsigned short elem_idx = std::distance( veList.begin(), uv0Itor ); - VertexElementType newType = VertexElement::multiplyTypeCount( baseType0, - totalTypeCount ); - - if( ( uv0->getOffset() + uv0->getSize() == uv1->getOffset() || - uv1->getOffset() + uv1->getSize() == uv0->getOffset() ) && - uv0->getSource() == uv1->getSource() ) - { - //Special case where they adjacent, just change the declaration & we're done. - size_t newOffset = std::min( uv0->getOffset(), uv1->getOffset() ); - unsigned short newIdx = std::min( uv0->getIndex(), uv1->getIndex() ); - - vDecl->modifyElement( elem_idx, uv0->getSource(), newOffset, newType, - VES_TEXTURE_COORDINATES, newIdx ); - vDecl->removeElement( VES_TEXTURE_COORDINATES, texCoordSetToDestroy ); - uv1 = 0; - } - - vDecl->closeGapsInSource(); - } - } - } - //--------------------------------------------------------------------- - void Mesh::organiseTangentsBuffer(VertexData *vertexData, - VertexElementSemantic targetSemantic, unsigned short index, - unsigned short sourceTexCoordSet) - { - VertexDeclaration *vDecl = vertexData->vertexDeclaration ; - VertexBufferBinding *vBind = vertexData->vertexBufferBinding ; - - const VertexElement *tangentsElem = vDecl->findElementBySemantic(targetSemantic, index); - bool needsToBeCreated = false; - - if (!tangentsElem) - { // no tex coords with index 1 - needsToBeCreated = true ; - } - else if (tangentsElem->getType() != VET_FLOAT3) - { - // buffer exists, but not 3D - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Target semantic set already exists but is not 3D, therefore " - "cannot contain tangents. Pick an alternative destination semantic. ", - "Mesh::organiseTangentsBuffer"); - } - - HardwareVertexBufferSharedPtr newBuffer; - if (needsToBeCreated) - { - // To be most efficient with our vertex streams, - // tack the new tangents onto the same buffer as the - // source texture coord set - const VertexElement* prevTexCoordElem = - vertexData->vertexDeclaration->findElementBySemantic( - VES_TEXTURE_COORDINATES, sourceTexCoordSet); - if (!prevTexCoordElem) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Cannot locate the first texture coordinate element to " - "which to append the new tangents.", - "Mesh::orgagniseTangentsBuffer"); - } - // Find the buffer associated with this element - HardwareVertexBufferSharedPtr origBuffer = - vertexData->vertexBufferBinding->getBuffer( - prevTexCoordElem->getSource()); - // Now create a new buffer, which includes the previous contents - // plus extra space for the 3D coords - newBuffer = getHardwareBufferManager()->createVertexBuffer( - origBuffer->getVertexSize() + 3*sizeof(float), - vertexData->vertexCount, - origBuffer->getUsage(), - origBuffer->hasShadowBuffer() ); - // Add the new element - vDecl->addElement( - prevTexCoordElem->getSource(), - origBuffer->getVertexSize(), - VET_FLOAT3, - targetSemantic, - index); - // Now copy the original data across - HardwareBufferLockGuard srcLock(origBuffer, HardwareBuffer::HBL_READ_ONLY); - HardwareBufferLockGuard dstLock(newBuffer, HardwareBuffer::HBL_DISCARD); - unsigned char* pSrc = static_cast(srcLock.pData); - unsigned char* pDest = static_cast(dstLock.pData); - size_t vertSize = origBuffer->getVertexSize(); - for (size_t v = 0; v < vertexData->vertexCount; ++v) - { - // Copy original vertex data - memcpy(pDest, pSrc, vertSize); - pSrc += vertSize; - pDest += vertSize; - // Set the new part to 0 since we'll accumulate in this - memset(pDest, 0, sizeof(float)*3); - pDest += sizeof(float)*3; - } - - // Rebind the new buffer - vBind->setBinding(prevTexCoordElem->getSource(), newBuffer); - } - } - //--------------------------------------------------------------------- - void Mesh::buildTangentVectors(unsigned short sourceTexCoordSet, bool splitMirrored, bool splitRotated, - bool storeParityInW) - { - - TangentSpaceCalc tangentsCalc; - tangentsCalc.setSplitMirrored(splitMirrored); - tangentsCalc.setSplitRotated(splitRotated); - tangentsCalc.setStoreParityInW(storeParityInW); - - // shared geometry first - if (sharedVertexData) - { - tangentsCalc.setVertexData(sharedVertexData); - bool found = false; - for (auto sm : mSubMeshList) - { - if (sm->useSharedVertices) - { - tangentsCalc.addIndexData(sm->indexData); - found = true; - } - } - if (found) - { - TangentSpaceCalc::Result res = tangentsCalc.build(sourceTexCoordSet); - - // If any vertex splitting happened, we have to give them bone assignments - if (mSkeleton) - { - for (auto & remap : res.indexesRemapped) - { - // Copy all bone assignments from the split vertex - VertexBoneAssignmentList::iterator vbstart = mBoneAssignments.lower_bound(remap.splitVertex.first); - VertexBoneAssignmentList::iterator vbend = mBoneAssignments.upper_bound(remap.splitVertex.first); - for (VertexBoneAssignmentList::iterator vba = vbstart; vba != vbend; ++vba) - { - VertexBoneAssignment newAsgn = vba->second; - newAsgn.vertexIndex = static_cast(remap.splitVertex.second); - // multimap insert doesn't invalidate iterators - addBoneAssignment(newAsgn); - } - - } - } - - // Update poses (some vertices might have been duplicated) - // we will just check which vertices have been split and copy - // the offset for the original vertex to the corresponding new vertex - for (auto *current_pose : mPoseList) - { - const Pose::VertexOffsetMap& offset_map = current_pose->getVertexOffsets(); - for(auto& split : res.vertexSplits) - { - Pose::VertexOffsetMap::const_iterator found_offset = offset_map.find(split.first); - - // copy the offset - if( found_offset != offset_map.end() ) - { - current_pose->addVertex (split.second, found_offset->second ); - } - } - } - } - } - - // Dedicated geometry - for (auto sm : mSubMeshList) - { - if (!sm->useSharedVertices) - { - tangentsCalc.clear(); - tangentsCalc.setVertexData(sm->vertexData); - tangentsCalc.addIndexData(sm->indexData, sm->operationType); - TangentSpaceCalc::Result res = tangentsCalc.build(sourceTexCoordSet); - - // If any vertex splitting happened, we have to give them bone assignments - if (mSkeleton) - { - for (auto & remap : res.indexesRemapped) - { - // Copy all bone assignments from the split vertex - VertexBoneAssignmentList::const_iterator vbstart = - sm->getBoneAssignments().lower_bound(remap.splitVertex.first); - VertexBoneAssignmentList::const_iterator vbend = - sm->getBoneAssignments().upper_bound(remap.splitVertex.first); - for (VertexBoneAssignmentList::const_iterator vba = vbstart; vba != vbend; ++vba) - { - VertexBoneAssignment newAsgn = vba->second; - newAsgn.vertexIndex = static_cast(remap.splitVertex.second); - // multimap insert doesn't invalidate iterators - sm->addBoneAssignment(newAsgn); - } - - } - - } - } - } - - } - //--------------------------------------------------------------------- - bool Mesh::suggestTangentVectorBuildParams(unsigned short& outSourceCoordSet) - { - // Go through all the vertex data and locate source and dest (must agree) - bool sharedGeometryDone = false; - bool foundExisting = false; - bool firstOne = true; - for (auto *sm : mSubMeshList) - { - VertexData* vertexData; - if (sm->useSharedVertices) - { - if (sharedGeometryDone) - continue; - vertexData = sharedVertexData; - sharedGeometryDone = true; - } - else - { - vertexData = sm->vertexData; - } - - const VertexElement *sourceElem = 0; - unsigned short targetIndex = 0; - for (targetIndex = 0; targetIndex < OGRE_MAX_TEXTURE_COORD_SETS; ++targetIndex) - { - auto testElem = - vertexData->vertexDeclaration->findElementBySemantic(VES_TEXTURE_COORDINATES, targetIndex); - if (!testElem) - break; // finish if we've run out, t will be the target - - // We're still looking for the source texture coords - if (testElem->getType() == VET_FLOAT2) - { - // Ok, we found it - sourceElem = testElem; - break; - } - } - - // After iterating, we should have a source and a possible destination (t) - if (!sourceElem) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Cannot locate an appropriate 2D texture coordinate set for " - "all the vertex data in this mesh to create tangents from. "); - } - - // Look for existing semantic - foundExisting = vertexData->vertexDeclaration->findElementBySemantic(VES_TANGENT); - - // Check that we agree with previous decisions, if this is not the - // first one, and if we're not just using the existing one - if (!firstOne && !foundExisting) - { - if (sourceElem->getIndex() != outSourceCoordSet) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Multiple sets of vertex data in this mesh disagree on " - "the appropriate index to use for the texture coordinates. " - "This ambiguity must be rectified before tangents can be generated."); - } - } - - // Otherwise, save this result - outSourceCoordSet = sourceElem->getIndex(); - - firstOne = false; - - } - - return foundExisting; - - } - //--------------------------------------------------------------------- - void Mesh::buildEdgeList(void) - { - if (mEdgeListsBuilt) - return; -#if !OGRE_NO_MESHLOD - // Loop over LODs - for (unsigned short lodIndex = 0; lodIndex < (unsigned short)mMeshLodUsageList.size(); ++lodIndex) - { - // use getLodLevel to enforce loading of manual mesh lods - const MeshLodUsage& usage = getLodLevel(lodIndex); - - if (!usage.manualName.empty() && lodIndex != 0) - { - // Delegate edge building to manual mesh - // It should have already built it's own edge list while loading - if (usage.manualMesh) - { - usage.edgeData = usage.manualMesh->getEdgeList(0); - } - } - else - { - // Build - EdgeListBuilder eb; - size_t vertexSetCount = 0; - bool atLeastOneIndexSet = false; - - if (sharedVertexData) - { - eb.addVertexData(sharedVertexData); - vertexSetCount++; - } - - // Prepare the builder using the submesh information - for (auto *s : mSubMeshList) - { - if (s->operationType != RenderOperation::OT_TRIANGLE_FAN && - s->operationType != RenderOperation::OT_TRIANGLE_LIST && - s->operationType != RenderOperation::OT_TRIANGLE_STRIP) - { - continue; - } - if (s->useSharedVertices) - { - // Use shared vertex data, index as set 0 - if (lodIndex == 0) - { - eb.addIndexData(s->indexData, 0, s->operationType); - } - else - { - eb.addIndexData(s->mLodFaceList[lodIndex-1], 0, - s->operationType); - } - } - else if(s->isBuildEdgesEnabled()) - { - // own vertex data, add it and reference it directly - eb.addVertexData(s->vertexData); - if (lodIndex == 0) - { - // Base index data - eb.addIndexData(s->indexData, vertexSetCount++, - s->operationType); - } - else - { - // LOD index data - eb.addIndexData(s->mLodFaceList[lodIndex-1], - vertexSetCount++, s->operationType); - } - - } - atLeastOneIndexSet = true; - } - - if (atLeastOneIndexSet) - { - usage.edgeData = eb.build(); - - #if OGRE_DEBUG_MODE - // Override default log - Log* log = LogManager::getSingleton().createLog( - mName + "_lod" + StringConverter::toString(lodIndex) + - "_prepshadow.log", false, false); - usage.edgeData->log(log); - // clean up log & close file handle - LogManager::getSingleton().destroyLog(log); - #endif - } - else - { - // create empty edge data - usage.edgeData = OGRE_NEW EdgeData(); - } - } - } -#else - // Build - EdgeListBuilder eb; - size_t vertexSetCount = 0; - if (sharedVertexData) - { - eb.addVertexData(sharedVertexData); - vertexSetCount++; - } - - // Prepare the builder using the submesh information - for (auto *s : mSubMeshList) - { - if (s->operationType != RenderOperation::OT_TRIANGLE_FAN && - s->operationType != RenderOperation::OT_TRIANGLE_LIST && - s->operationType != RenderOperation::OT_TRIANGLE_STRIP) - { - continue; - } - if (s->useSharedVertices) - { - eb.addIndexData(s->indexData, 0, s->operationType); - } - else if(s->isBuildEdgesEnabled()) - { - // own vertex data, add it and reference it directly - eb.addVertexData(s->vertexData); - // Base index data - eb.addIndexData(s->indexData, vertexSetCount++, - s->operationType); - } - } - - mMeshLodUsageList[0].edgeData = eb.build(); - -#if OGRE_DEBUG_MODE - // Override default log - Log* log = LogManager::getSingleton().createLog( - mName + "_lod0"+ - "_prepshadow.log", false, false); - mMeshLodUsageList[0].edgeData->log(log); - // clean up log & close file handle - LogManager::getSingleton().destroyLog(log); -#endif -#endif - mEdgeListsBuilt = true; - } - //--------------------------------------------------------------------- - void Mesh::freeEdgeList(void) - { - if (!mEdgeListsBuilt) - return; -#if !OGRE_NO_MESHLOD - // Loop over LODs - unsigned short index = 0; - for (auto& usage : mMeshLodUsageList) - { - if (usage.manualName.empty() || index == 0) - { - // Only delete if we own this data - // Manual LODs > 0 own their own - OGRE_DELETE usage.edgeData; - } - usage.edgeData = NULL; - ++index; - } -#else - OGRE_DELETE mMeshLodUsageList[0].edgeData; - mMeshLodUsageList[0].edgeData = NULL; -#endif - mEdgeListsBuilt = false; - } - //--------------------------------------------------------------------- - void Mesh::prepareForShadowVolume(void) - { - if (mPreparedForShadowVolumes) - return; - - if (sharedVertexData) - { - sharedVertexData->prepareForShadowVolume(); - } - for (auto *s : mSubMeshList) - { - if (!s->useSharedVertices && - (s->operationType == RenderOperation::OT_TRIANGLE_FAN || - s->operationType == RenderOperation::OT_TRIANGLE_LIST || - s->operationType == RenderOperation::OT_TRIANGLE_STRIP)) - { - s->vertexData->prepareForShadowVolume(); - } - } - mPreparedForShadowVolumes = true; - } - //--------------------------------------------------------------------- - EdgeData* Mesh::getEdgeList(unsigned short lodIndex) - { - // Build edge list on demand - if (!mEdgeListsBuilt && mAutoBuildEdgeLists) - { - buildEdgeList(); - } -#if !OGRE_NO_MESHLOD - return getLodLevel(lodIndex).edgeData; -#else - assert(lodIndex == 0); - return mMeshLodUsageList[0].edgeData; -#endif - } - //--------------------------------------------------------------------- - const EdgeData* Mesh::getEdgeList(unsigned short lodIndex) const - { -#if !OGRE_NO_MESHLOD - return getLodLevel(lodIndex).edgeData; -#else - assert(lodIndex == 0); - return mMeshLodUsageList[0].edgeData; -#endif - } - //--------------------------------------------------------------------- - void Mesh::prepareMatricesForVertexBlend(const Affine3** blendMatrices, - const Affine3* boneMatrices, const IndexMap& indexMap) - { - assert(indexMap.size() <= OGRE_MAX_NUM_BONES); - for (auto& i : indexMap) - { - *blendMatrices++ = boneMatrices + i; - } - } - //--------------------------------------------------------------------- - void Mesh::softwareVertexBlend(const VertexData* sourceVertexData, - const VertexData* targetVertexData, - const Affine3* const* blendMatrices, size_t numMatrices, - bool blendNormals) - { - float *pSrcPos = 0; - float *pSrcNorm = 0; - float *pDestPos = 0; - float *pDestNorm = 0; - float *pBlendWeight = 0; - unsigned char* pBlendIdx = 0; - size_t srcNormStride = 0; - size_t destNormStride = 0; - - // Get elements for source - auto srcElemPos = sourceVertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); - auto srcElemNorm = sourceVertexData->vertexDeclaration->findElementBySemantic(VES_NORMAL); - auto srcElemBlendIndices = sourceVertexData->vertexDeclaration->findElementBySemantic(VES_BLEND_INDICES); - auto srcElemBlendWeights = sourceVertexData->vertexDeclaration->findElementBySemantic(VES_BLEND_WEIGHTS); - OgreAssert(srcElemPos && srcElemBlendIndices && srcElemBlendWeights, - "You must supply at least positions, blend indices and blend weights"); - // Get elements for target - auto destElemPos = targetVertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); - auto destElemNorm = targetVertexData->vertexDeclaration->findElementBySemantic(VES_NORMAL); - - // Get buffers for source - HardwareVertexBufferSharedPtr srcPosBuf = sourceVertexData->vertexBufferBinding->getBuffer(srcElemPos->getSource()); - HardwareVertexBufferSharedPtr srcIdxBuf = sourceVertexData->vertexBufferBinding->getBuffer(srcElemBlendIndices->getSource()); - HardwareVertexBufferSharedPtr srcWeightBuf = sourceVertexData->vertexBufferBinding->getBuffer(srcElemBlendWeights->getSource()); - HardwareVertexBufferSharedPtr srcNormBuf; - - // Get buffers for target - HardwareVertexBufferSharedPtr destPosBuf = targetVertexData->vertexBufferBinding->getBuffer(destElemPos->getSource()); - - // Lock source buffers for reading - HardwareBufferLockGuard srcPosLock(srcPosBuf, HardwareBuffer::HBL_READ_ONLY); - srcElemPos->baseVertexPointerToElement(srcPosLock.pData, &pSrcPos); - - // Do we have normals and want to blend them? - bool includeNormals = blendNormals && srcElemNorm && destElemNorm; - HardwareVertexBufferSharedPtr destNormBuf; - HardwareBufferLockGuard srcNormLock; - if (includeNormals) - { - // Get buffers for source - srcNormBuf = sourceVertexData->vertexBufferBinding->getBuffer(srcElemNorm->getSource()); - srcNormStride = srcNormBuf->getVertexSize(); - // Get buffers for target - destNormBuf = targetVertexData->vertexBufferBinding->getBuffer(destElemNorm->getSource()); - destNormStride = destNormBuf->getVertexSize(); - - if (srcNormBuf != srcPosBuf) - { - // Different buffer - srcNormLock.lock(srcNormBuf, HardwareBuffer::HBL_READ_ONLY); - } - srcElemNorm->baseVertexPointerToElement(srcNormLock.pData ? srcNormLock.pData : srcPosLock.pData, &pSrcNorm); - } - - // Indices must be 4 bytes - assert(srcElemBlendIndices->getType() == VET_UBYTE4 && "Blend indices must be VET_UBYTE4"); - HardwareBufferLockGuard srcIdxLock(srcIdxBuf, HardwareBuffer::HBL_READ_ONLY); - srcElemBlendIndices->baseVertexPointerToElement(srcIdxLock.pData, &pBlendIdx); - HardwareBufferLockGuard srcWeightLock; - if (srcWeightBuf != srcIdxBuf) - { - // Lock buffer - srcWeightLock.lock(srcWeightBuf, HardwareBuffer::HBL_READ_ONLY); - } - srcElemBlendWeights->baseVertexPointerToElement(srcWeightLock.pData ? srcWeightLock.pData : srcIdxLock.pData, &pBlendWeight); - unsigned short numWeightsPerVertex = VertexElement::getTypeCount(srcElemBlendWeights->getType()); - - // Lock destination buffers for writing - HardwareBufferLockGuard destPosLock(destPosBuf, - (destNormBuf != destPosBuf && destPosBuf->getVertexSize() == destElemPos->getSize()) || - (destNormBuf == destPosBuf && destPosBuf->getVertexSize() == destElemPos->getSize() + destElemNorm->getSize()) ? - HardwareBuffer::HBL_DISCARD : HardwareBuffer::HBL_NORMAL); - destElemPos->baseVertexPointerToElement(destPosLock.pData, &pDestPos); - HardwareBufferLockGuard destNormLock; - if (includeNormals) - { - if (destNormBuf != destPosBuf) - { - destNormLock.lock(destNormBuf, destNormBuf->getVertexSize() == destElemNorm->getSize() - ? HardwareBuffer::HBL_DISCARD - : HardwareBuffer::HBL_NORMAL); - } - destElemNorm->baseVertexPointerToElement(destNormLock.pData ? destNormLock.pData : destPosLock.pData, &pDestNorm); - } - - auto srcPosStride = srcPosBuf->getVertexSize(); - auto destPosStride = destPosBuf->getVertexSize(); - auto blendIdxStride = srcIdxBuf->getVertexSize(); - auto blendWeightStride = srcWeightBuf->getVertexSize(); - - OptimisedUtil::getImplementation()->softwareVertexSkinning( - pSrcPos, pDestPos, - pSrcNorm, pDestNorm, - pBlendWeight, pBlendIdx, - blendMatrices, - srcPosStride, destPosStride, - srcNormStride, destNormStride, - blendWeightStride, blendIdxStride, - numWeightsPerVertex, - targetVertexData->vertexCount); - } - //--------------------------------------------------------------------- - void Mesh::softwareVertexMorph(float t, - const HardwareVertexBufferSharedPtr& b1, - const HardwareVertexBufferSharedPtr& b2, - VertexData* targetVertexData) - { - HardwareBufferLockGuard b1Lock(b1, HardwareBuffer::HBL_READ_ONLY); - float* pb1 = static_cast(b1Lock.pData); - HardwareBufferLockGuard b2Lock; - float* pb2; - if (b1.get() != b2.get()) - { - b2Lock.lock(b2, HardwareBuffer::HBL_READ_ONLY); - pb2 = static_cast(b2Lock.pData); - } - else - { - // Same buffer - track with only one entry or time index exactly matching - // one keyframe - // For simplicity of main code, interpolate still but with same val - pb2 = pb1; - } - - const VertexElement* posElem = - targetVertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); - assert(posElem); - const VertexElement* normElem = - targetVertexData->vertexDeclaration->findElementBySemantic(VES_NORMAL); - - bool morphNormals = false; - if (normElem && normElem->getSource() == posElem->getSource() && - b1->getVertexSize() == 24 && b2->getVertexSize() == 24) - morphNormals = true; - - HardwareVertexBufferSharedPtr destBuf = - targetVertexData->vertexBufferBinding->getBuffer( - posElem->getSource()); - assert((posElem->getSize() == destBuf->getVertexSize() - || (morphNormals && posElem->getSize() + normElem->getSize() == destBuf->getVertexSize())) && - "Positions (or positions & normals) must be in a buffer on their own for morphing"); - HardwareBufferLockGuard destLock(destBuf, HardwareBuffer::HBL_DISCARD); - float* pdst = static_cast(destLock.pData); - - OptimisedUtil::getImplementation()->softwareVertexMorph( - t, pb1, pb2, pdst, - b1->getVertexSize(), b2->getVertexSize(), destBuf->getVertexSize(), - targetVertexData->vertexCount, - morphNormals); - } - //--------------------------------------------------------------------- - void Mesh::softwareVertexPoseBlend(float weight, - const std::map& vertexOffsetMap, - const std::map& normalsMap, - VertexData* targetVertexData) - { - // Do nothing if no weight - if (weight == 0.0f) - return; - - const VertexElement* posElem = - targetVertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); - const VertexElement* normElem = - targetVertexData->vertexDeclaration->findElementBySemantic(VES_NORMAL); - assert(posElem); - // Support normals if they're in the same buffer as positions and pose includes them - bool normals = normElem && !normalsMap.empty() && posElem->getSource() == normElem->getSource(); - HardwareVertexBufferSharedPtr destBuf = - targetVertexData->vertexBufferBinding->getBuffer( - posElem->getSource()); - - size_t elemsPerVertex = destBuf->getVertexSize()/sizeof(float); - - // Have to lock in normal mode since this is incremental - HardwareBufferLockGuard destLock(destBuf, HardwareBuffer::HBL_NORMAL); - float* pBase = static_cast(destLock.pData); - - // Iterate over affected vertices - for (const auto & i : vertexOffsetMap) - { - // Adjust pointer - float *pdst = pBase + i.first*elemsPerVertex; - - *pdst = *pdst + (i.second[0] * weight); - ++pdst; - *pdst = *pdst + (i.second[01] * weight); - ++pdst; - *pdst = *pdst + (i.second[2] * weight); - ++pdst; - - } - - if (normals) - { - float* pNormBase; - normElem->baseVertexPointerToElement((void*)pBase, &pNormBase); - for (const auto & i : normalsMap) - { - // Adjust pointer - float *pdst = pNormBase + i.first*elemsPerVertex; - - *pdst = *pdst + (i.second[0] * weight); - ++pdst; - *pdst = *pdst + (i.second[1] * weight); - ++pdst; - *pdst = *pdst + (i.second[2] * weight); - ++pdst; - - } - } - } - //--------------------------------------------------------------------- - size_t Mesh::calculateSize(void) const - { - // calculate GPU size - size_t ret = 0; - unsigned short i; - // Shared vertices - if (sharedVertexData) - { - for (i = 0; - i < sharedVertexData->vertexBufferBinding->getBufferCount(); - ++i) - { - ret += sharedVertexData->vertexBufferBinding - ->getBuffer(i)->getSizeInBytes(); - } - } - - for (auto *s : mSubMeshList) - { - // Dedicated vertices - if (!s->useSharedVertices) - { - for (i = 0; - i < s->vertexData->vertexBufferBinding->getBufferCount(); - ++i) - { - ret += s->vertexData->vertexBufferBinding - ->getBuffer(i)->getSizeInBytes(); - } - } - if (s->indexData->indexBuffer) - { - // Index data - ret += s->indexData->indexBuffer->getSizeInBytes(); - } - - } - return ret; - } - //----------------------------------------------------------------------------- - bool Mesh::hasVertexAnimation(void) const - { - return !mAnimationsList.empty(); - } - //--------------------------------------------------------------------- - VertexAnimationType Mesh::getSharedVertexDataAnimationType(void) const - { - if (mAnimationTypesDirty) - { - _determineAnimationTypes(); - } - - return mSharedVertexDataAnimationType; - } - //--------------------------------------------------------------------- - void Mesh::_determineAnimationTypes(void) const - { - // Don't check flag here; since detail checks on track changes are not - // done, allow caller to force if they need to - - // Initialise all types to nothing - mSharedVertexDataAnimationType = VAT_NONE; - mSharedVertexDataAnimationIncludesNormals = false; - for (auto i : mSubMeshList) - { - i->mVertexAnimationType = VAT_NONE; - i->mVertexAnimationIncludesNormals = false; - } - - mPosesIncludeNormals = false; - for (PoseList::const_iterator i = mPoseList.begin(); i != mPoseList.end(); ++i) - { - if (i == mPoseList.begin()) - mPosesIncludeNormals = (*i)->getIncludesNormals(); - else if (mPosesIncludeNormals != (*i)->getIncludesNormals()) - // only support normals if consistently included - mPosesIncludeNormals = mPosesIncludeNormals && (*i)->getIncludesNormals(); - } - - // Scan all animations and determine the type of animation tracks - // relating to each vertex data - for(const auto& ai : mAnimationsList) - { - for (const auto& vit : ai.second->_getVertexTrackList()) - { - VertexAnimationTrack* track = vit.second; - ushort handle = vit.first; - if (handle == 0) - { - // shared data - if (mSharedVertexDataAnimationType != VAT_NONE && - mSharedVertexDataAnimationType != track->getAnimationType()) - { - // Mixing of morph and pose animation on same data is not allowed - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Animation tracks for shared vertex data on mesh " - + mName + " try to mix vertex animation types, which is " - "not allowed.", - "Mesh::_determineAnimationTypes"); - } - mSharedVertexDataAnimationType = track->getAnimationType(); - if (track->getAnimationType() == VAT_MORPH) - mSharedVertexDataAnimationIncludesNormals = track->getVertexAnimationIncludesNormals(); - else - mSharedVertexDataAnimationIncludesNormals = mPosesIncludeNormals; - - } - else - { - // submesh index (-1) - SubMesh* sm = getSubMesh(handle-1); - if (sm->mVertexAnimationType != VAT_NONE && - sm->mVertexAnimationType != track->getAnimationType()) - { - // Mixing of morph and pose animation on same data is not allowed - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Animation tracks for dedicated vertex data " - + StringConverter::toString(handle-1) + " on mesh " - + mName + " try to mix vertex animation types, which is " - "not allowed.", - "Mesh::_determineAnimationTypes"); - } - sm->mVertexAnimationType = track->getAnimationType(); - if (track->getAnimationType() == VAT_MORPH) - sm->mVertexAnimationIncludesNormals = track->getVertexAnimationIncludesNormals(); - else - sm->mVertexAnimationIncludesNormals = mPosesIncludeNormals; - - } - } - } - - mAnimationTypesDirty = false; - } - //--------------------------------------------------------------------- - Animation* Mesh::createAnimation(const String& name, Real length) - { - // Check name not used - if (mAnimationsList.find(name) != mAnimationsList.end()) - { - OGRE_EXCEPT( - Exception::ERR_DUPLICATE_ITEM, - "An animation with the name " + name + " already exists", - "Mesh::createAnimation"); - } - - Animation* ret = OGRE_NEW Animation(name, length); - ret->_notifyContainer(this); - - // Add to list - mAnimationsList[name] = ret; - - // Mark animation types dirty - mAnimationTypesDirty = true; - - return ret; - - } - //--------------------------------------------------------------------- - Animation* Mesh::getAnimation(const String& name) const - { - Animation* ret = _getAnimationImpl(name); - if (!ret) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "No animation entry found named " + name, - "Mesh::getAnimation"); - } - - return ret; - } - //--------------------------------------------------------------------- - Animation* Mesh::getAnimation(unsigned short index) const - { - // If you hit this assert, then the index is out of bounds. - assert( index < mAnimationsList.size() ); - - AnimationList::const_iterator i = mAnimationsList.begin(); - - std::advance(i, index); - - return i->second; - - } - //--------------------------------------------------------------------- - unsigned short Mesh::getNumAnimations(void) const - { - return static_cast(mAnimationsList.size()); - } - //--------------------------------------------------------------------- - bool Mesh::hasAnimation(const String& name) const - { - return _getAnimationImpl(name) != 0; - } - //--------------------------------------------------------------------- - Animation* Mesh::_getAnimationImpl(const String& name) const - { - Animation* ret = 0; - AnimationList::const_iterator i = mAnimationsList.find(name); - - if (i != mAnimationsList.end()) - { - ret = i->second; - } - - return ret; - - } - //--------------------------------------------------------------------- - void Mesh::removeAnimation(const String& name) - { - AnimationList::iterator i = mAnimationsList.find(name); - - if (i == mAnimationsList.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "No animation entry found named " + name, - "Mesh::getAnimation"); - } - - OGRE_DELETE i->second; - - mAnimationsList.erase(i); - - mAnimationTypesDirty = true; - } - //--------------------------------------------------------------------- - void Mesh::removeAllAnimations(void) - { - for (auto& a : mAnimationsList) - { - OGRE_DELETE a.second; - } - mAnimationsList.clear(); - mAnimationTypesDirty = true; - } - //--------------------------------------------------------------------- - VertexData* Mesh::getVertexDataByTrackHandle(unsigned short handle) - { - if (handle == 0) - { - return sharedVertexData; - } - else - { - return getSubMesh(handle-1)->vertexData; - } - } - //--------------------------------------------------------------------- - Pose* Mesh::createPose(ushort target, const String& name) - { - Pose* retPose = OGRE_NEW Pose(target, name); - mPoseList.push_back(retPose); - return retPose; - } - //--------------------------------------------------------------------- - Pose* Mesh::getPose(const String& name) const - { - for (auto i : mPoseList) - { - if (i->getName() == name) - return i; - } - StringStream str; - str << "No pose called " << name << " found in Mesh " << mName; - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - str.str(), - "Mesh::getPose"); - - } - //--------------------------------------------------------------------- - void Mesh::removePose(ushort index) - { - OgreAssert(index < mPoseList.size(), ""); - PoseList::iterator i = mPoseList.begin(); - std::advance(i, index); - OGRE_DELETE *i; - mPoseList.erase(i); - - } - //--------------------------------------------------------------------- - void Mesh::removePose(const String& name) - { - for (PoseList::iterator i = mPoseList.begin(); i != mPoseList.end(); ++i) - { - if ((*i)->getName() == name) - { - OGRE_DELETE *i; - mPoseList.erase(i); - return; - } - } - StringStream str; - str << "No pose called " << name << " found in Mesh " << mName; - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - str.str(), - "Mesh::removePose"); - } - //--------------------------------------------------------------------- - void Mesh::removeAllPoses(void) - { - for (auto & i : mPoseList) - { - OGRE_DELETE i; - } - mPoseList.clear(); - } - //--------------------------------------------------------------------- - Mesh::PoseIterator Mesh::getPoseIterator(void) - { - return PoseIterator(mPoseList.begin(), mPoseList.end()); - } - //--------------------------------------------------------------------- - Mesh::ConstPoseIterator Mesh::getPoseIterator(void) const - { - return ConstPoseIterator(mPoseList.begin(), mPoseList.end()); - } - //----------------------------------------------------------------------------- - const PoseList& Mesh::getPoseList(void) const - { - return mPoseList; - } - //--------------------------------------------------------------------- - const LodStrategy *Mesh::getLodStrategy() const - { - return mLodStrategy; - } -#if !OGRE_NO_MESHLOD - //--------------------------------------------------------------------- - void Mesh::setLodStrategy(LodStrategy *lodStrategy) - { - mLodStrategy = lodStrategy; - - assert(mMeshLodUsageList.size()); - - // Re-transform user LOD values (starting at index 1, no need to transform base value) - for (MeshLodUsageList::iterator i = mMeshLodUsageList.begin()+1; i != mMeshLodUsageList.end(); ++i) - i->value = mLodStrategy->transformUserValue(i->userValue); - - // Rewrite first value - mMeshLodUsageList[0].value = mLodStrategy->getBaseValue(); - } -#endif - - void Mesh::_convertVertexElement(VertexElementSemantic semantic, VertexElementType dstType) - { - if (sharedVertexData) - sharedVertexData->convertVertexElement(semantic, dstType); - - for (auto s : getSubMeshes()) - if (s->vertexData) - s->vertexData->convertVertexElement(semantic, dstType); - } -} - diff --git a/OgreMain/src/OgreMeshFileFormat.h b/OgreMain/src/OgreMeshFileFormat.h deleted file mode 100644 index be213bff2c9..00000000000 --- a/OgreMain/src/OgreMeshFileFormat.h +++ /dev/null @@ -1,295 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __MeshFileFormat_H__ -#define __MeshFileFormat_H__ - -#include "OgrePrerequisites.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ -/** Definition of the OGRE .mesh file format - - .mesh files are binary files (for read efficiency at runtime) and are arranged into chunks - of data, very like 3D Studio's format. - A chunk always consists of: - unsigned short CHUNK_ID : one of the following chunk ids identifying the chunk - unsigned long LENGTH : length of the chunk in bytes, including this header - void* DATA : the data, which may contain other sub-chunks (various data types) - - A .mesh file can contain both the definition of the Mesh itself, and optionally the definitions - of the materials is uses (although these can be omitted, if so the Mesh assumes that at runtime the - Materials referred to by name in the Mesh are loaded/created from another source) - - A .mesh file only contains a single mesh, which can itself have multiple submeshes. - -*/ - - enum MeshChunkID { - M_HEADER = 0x1000, - // char* version : Version number check - M_MESH = 0x3000, - // bool skeletallyAnimated // important flag which affects h/w buffer policies - // Optional M_GEOMETRY chunk - M_SUBMESH = 0x4000, - // char* materialName - // bool useSharedVertices - // unsigned int indexCount - // bool indexes32Bit - // unsigned int* faceVertexIndices (indexCount) - // OR - // unsigned short* faceVertexIndices (indexCount) - // M_GEOMETRY chunk (Optional: present only if useSharedVertices = false) - M_SUBMESH_OPERATION = 0x4010, // optional, trilist assumed if missing - // unsigned short operationType - M_SUBMESH_BONE_ASSIGNMENT = 0x4100, - // Optional bone weights (repeating section) - // unsigned int vertexIndex; - // unsigned short boneIndex; - // float weight; - // Optional chunk that matches a texture name to an alias - // a texture alias is sent to the submesh material to use this texture name - // instead of the one in the texture unit with a matching alias name - M_SUBMESH_TEXTURE_ALIAS = 0x4200, // Repeating section - // char* aliasName; - // char* textureName; - - M_GEOMETRY = 0x5000, // NB this chunk is embedded within M_MESH and M_SUBMESH - // unsigned int vertexCount - M_GEOMETRY_VERTEX_DECLARATION = 0x5100, - M_GEOMETRY_VERTEX_ELEMENT = 0x5110, // Repeating section - // unsigned short source; // buffer bind source - // unsigned short type; // VertexElementType - // unsigned short semantic; // VertexElementSemantic - // unsigned short offset; // start offset in buffer in bytes - // unsigned short index; // index of the semantic (for colours and texture coords) - M_GEOMETRY_VERTEX_BUFFER = 0x5200, // Repeating section - // unsigned short bindIndex; // Index to bind this buffer to - // unsigned short vertexSize; // Per-vertex size, must agree with declaration at this index - M_GEOMETRY_VERTEX_BUFFER_DATA = 0x5210, - // raw buffer data - M_MESH_SKELETON_LINK = 0x6000, - // Optional link to skeleton - // char* skeletonName : name of .skeleton to use - M_MESH_BONE_ASSIGNMENT = 0x7000, - // Optional bone weights (repeating section) - // unsigned int vertexIndex; - // unsigned short boneIndex; - // float weight; - M_MESH_LOD_LEVEL = 0x8000, - // Optional LOD information - // string strategyName; - // unsigned short numLevels; - // bool manual; (true for manual alternate meshes, false for generated) - M_MESH_LOD_USAGE = 0x8100, - // Repeating section, ordered in increasing depth - // NB LOD 0 (full detail from 0 depth) is omitted - // LOD value - this is a distance, a pixel count etc, based on strategy - // float lodValue; - M_MESH_LOD_MANUAL = 0x8110, - // Required if M_MESH_LOD section manual = true - // String manualMeshName; - M_MESH_LOD_GENERATED = 0x8120, - // Required if M_MESH_LOD section manual = false - // Repeating section (1 per submesh) - // unsigned int indexCount; - // bool indexes32Bit - // unsigned short* faceIndexes; (indexCount) - // OR - // unsigned int* faceIndexes; (indexCount) - M_MESH_BOUNDS = 0x9000, - // float minx, miny, minz - // float maxx, maxy, maxz - // float radius - - // Added By DrEvil - // optional chunk that contains a table of submesh indexes and the names of - // the sub-meshes. - M_SUBMESH_NAME_TABLE = 0xA000, - // Subchunks of the name table. Each chunk contains an index & string - M_SUBMESH_NAME_TABLE_ELEMENT = 0xA100, - // short index - // char* name - - // Optional chunk which stores precomputed edge data - M_EDGE_LISTS = 0xB000, - // Each LOD has a separate edge list - M_EDGE_LIST_LOD = 0xB100, - // unsigned short lodIndex - // bool isManual // If manual, no edge data here, loaded from manual mesh - // bool isClosed - // unsigned long numTriangles - // unsigned long numEdgeGroups - // Triangle* triangleList - // unsigned long indexSet - // unsigned long vertexSet - // unsigned long vertIndex[3] - // unsigned long sharedVertIndex[3] - // float normal[4] - - M_EDGE_GROUP = 0xB110, - // unsigned long vertexSet - // unsigned long triStart - // unsigned long triCount - // unsigned long numEdges - // Edge* edgeList - // unsigned long triIndex[2] - // unsigned long vertIndex[2] - // unsigned long sharedVertIndex[2] - // bool degenerate - - // Optional poses section, referred to by pose keyframes - M_POSES = 0xC000, - M_POSE = 0xC100, - // char* name (may be blank) - // unsigned short target // 0 for shared geometry, - // 1+ for submesh index + 1 - // bool includesNormals [1.8+] - M_POSE_VERTEX = 0xC111, - // unsigned long vertexIndex - // float xoffset, yoffset, zoffset - // float xnormal, ynormal, znormal (optional, 1.8+) - // Optional vertex animation chunk - M_ANIMATIONS = 0xD000, - M_ANIMATION = 0xD100, - // char* name - // float length - M_ANIMATION_BASEINFO = 0xD105, - // [Optional] base keyframe information (pose animation only) - // char* baseAnimationName (blank for self) - // float baseKeyFrameTime - - M_ANIMATION_TRACK = 0xD110, - // unsigned short type // 1 == morph, 2 == pose - // unsigned short target // 0 for shared geometry, - // 1+ for submesh index + 1 - M_ANIMATION_MORPH_KEYFRAME = 0xD111, - // float time - // bool includesNormals [1.8+] - // float x,y,z // repeat by number of vertices in original geometry - M_ANIMATION_POSE_KEYFRAME = 0xD112, - // float time - M_ANIMATION_POSE_REF = 0xD113, // repeat for number of referenced poses - // unsigned short poseIndex - // float influence - - // Optional submesh extreme vertex list chink - M_TABLE_EXTREMES = 0xE000, - // unsigned short submesh_index; - // float extremes [n_extremes][3]; - - /* Version 1.2 of the .mesh format (deprecated) - enum MeshChunkID { - M_HEADER = 0x1000, - // char* version : Version number check - M_MESH = 0x3000, - // bool skeletallyAnimated // important flag which affects h/w buffer policies - // Optional M_GEOMETRY chunk - M_SUBMESH = 0x4000, - // char* materialName - // bool useSharedVertices - // unsigned int indexCount - // bool indexes32Bit - // unsigned int* faceVertexIndices (indexCount) - // OR - // unsigned short* faceVertexIndices (indexCount) - // M_GEOMETRY chunk (Optional: present only if useSharedVertices = false) - M_SUBMESH_OPERATION = 0x4010, // optional, trilist assumed if missing - // unsigned short operationType - M_SUBMESH_BONE_ASSIGNMENT = 0x4100, - // Optional bone weights (repeating section) - // unsigned int vertexIndex; - // unsigned short boneIndex; - // float weight; - M_GEOMETRY = 0x5000, // NB this chunk is embedded within M_MESH and M_SUBMESH - */ - // unsigned int vertexCount - // float* pVertices (x, y, z order x numVertices) - M_GEOMETRY_NORMALS = 0x5100, //(Optional) - // float* pNormals (x, y, z order x numVertices) - M_GEOMETRY_COLOURS = 0x5200, //(Optional) - // unsigned long* pColours (RGBA 8888 format x numVertices) - M_GEOMETRY_TEXCOORDS = 0x5300 //(Optional, REPEATABLE, each one adds an extra set) - // unsigned short dimensions (1 for 1D, 2 for 2D, 3 for 3D) - // float* pTexCoords (u [v] [w] order, dimensions x numVertices) - /* - M_MESH_SKELETON_LINK = 0x6000, - // Optional link to skeleton - // char* skeletonName : name of .skeleton to use - M_MESH_BONE_ASSIGNMENT = 0x7000, - // Optional bone weights (repeating section) - // unsigned int vertexIndex; - // unsigned short boneIndex; - // float weight; - M_MESH_LOD = 0x8000, - // Optional LOD information - // unsigned short numLevels; - // bool manual; (true for manual alternate meshes, false for generated) - M_MESH_LOD_USAGE = 0x8100, - // Repeating section, ordered in increasing depth - // NB LOD 0 (full detail from 0 depth) is omitted - // float fromSquaredDepth; - M_MESH_LOD_MANUAL = 0x8110, - // Required if M_MESH_LOD section manual = true - // String manualMeshName; - M_MESH_LOD_GENERATED = 0x8120, - // Required if M_MESH_LOD section manual = false - // Repeating section (1 per submesh) - // unsigned int indexCount; - // bool indexes32Bit - // unsigned short* faceIndexes; (indexCount) - // OR - // unsigned int* faceIndexes; (indexCount) - M_MESH_BOUNDS = 0x9000 - // float minx, miny, minz - // float maxx, maxy, maxz - // float radius - - // Added By DrEvil - // optional chunk that contains a table of submesh indexes and the names of - // the sub-meshes. - M_SUBMESH_NAME_TABLE, - // Subchunks of the name table. Each chunk contains an index & string - M_SUBMESH_NAME_TABLE_ELEMENT, - // short index - // char* name - - */ - }; - /** @} */ - /** @} */ - -} // namespace - - -#endif diff --git a/OgreMain/src/OgreMeshManager.cpp b/OgreMain/src/OgreMeshManager.cpp deleted file mode 100644 index 53df6ad45b4..00000000000 --- a/OgreMain/src/OgreMeshManager.cpp +++ /dev/null @@ -1,370 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include - -#include "OgreStableHeaders.h" - -#include "OgrePatchMesh.h" -#include "OgrePrefabFactory.h" - -namespace Ogre -{ - struct MeshCodec : public Codec - { - String magicNumberToFileExt(const char* magicNumberPtr, size_t maxbytes) const override { return ""; } - String getType() const override { return "mesh"; } - void decode(const DataStreamPtr& input, const Any& output) const override - { - Mesh* dst = any_cast(output); - MeshSerializer serializer; - serializer.setListener(MeshManager::getSingleton().getListener()); - serializer.importMesh(input, dst); - } - }; - - //----------------------------------------------------------------------- - template<> MeshManager* Singleton::msSingleton = 0; - - bool MeshManager::mBonesUseObjectSpace = true; - MeshManager* MeshManager::getSingletonPtr(void) - { - return msSingleton; - } - MeshManager& MeshManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //----------------------------------------------------------------------- - MeshManager::MeshManager(): - mBoundsPaddingFactor(0.01), mListener(0) - { - mBlendWeightsBaseElementType = VET_FLOAT1; - mPrepAllMeshesForShadowVolumes = false; - - mLoadOrder = 350.0f; - mResourceType = "Mesh"; - - mMeshCodec = std::make_unique(); - Codec::registerCodec(mMeshCodec.get()); - - ResourceGroupManager::getSingleton()._registerResourceManager(mResourceType, this); - - mPrefabLoader = std::make_unique(); - } - //----------------------------------------------------------------------- - MeshManager::~MeshManager() - { - Codec::unregisterCodec(mMeshCodec.get()); - ResourceGroupManager::getSingleton()._unregisterResourceManager(mResourceType); - } - //----------------------------------------------------------------------- - MeshPtr MeshManager::getByName(const String& name, const String& groupName) const - { - return static_pointer_cast(getResourceByName(name, groupName)); - } - //----------------------------------------------------------------------- - void MeshManager::_initialise(void) - { - // Create prefab objects - createManual("Prefab_Sphere", RGN_INTERNAL, mPrefabLoader.get()); - createManual("Prefab_Cube", RGN_INTERNAL, mPrefabLoader.get()); - // Planes can never be manifold - createManual("Prefab_Plane", RGN_INTERNAL, mPrefabLoader.get())->setAutoBuildEdgeLists(false); - } - //----------------------------------------------------------------------- - MeshManager::ResourceCreateOrRetrieveResult MeshManager::createOrRetrieve( - const String& name, const String& group, - bool isManual, ManualResourceLoader* loader, - const NameValuePairList* params, - HardwareBuffer::Usage vertexBufferUsage, - HardwareBuffer::Usage indexBufferUsage, - bool vertexBufferShadowed, bool indexBufferShadowed) - { - ResourceCreateOrRetrieveResult res = - ResourceManager::createOrRetrieve(name,group,isManual,loader,params); - MeshPtr pMesh = static_pointer_cast(res.first); - // Was it created? - if (res.second) - { - pMesh->setVertexBufferPolicy(vertexBufferUsage, vertexBufferShadowed); - pMesh->setIndexBufferPolicy(indexBufferUsage, indexBufferShadowed); - } - return res; - - } - //----------------------------------------------------------------------- - MeshPtr MeshManager::prepare( const String& filename, const String& groupName, - HardwareBuffer::Usage vertexBufferUsage, - HardwareBuffer::Usage indexBufferUsage, - bool vertexBufferShadowed, bool indexBufferShadowed) - { - MeshPtr pMesh = static_pointer_cast(createOrRetrieve(filename,groupName,false,0,0, - vertexBufferUsage,indexBufferUsage, - vertexBufferShadowed,indexBufferShadowed).first); - pMesh->prepare(); - return pMesh; - } - //----------------------------------------------------------------------- - MeshPtr MeshManager::load( const String& filename, const String& groupName, - HardwareBuffer::Usage vertexBufferUsage, - HardwareBuffer::Usage indexBufferUsage, - bool vertexBufferShadowed, bool indexBufferShadowed) - { - MeshPtr pMesh = static_pointer_cast(createOrRetrieve(filename,groupName,false,0,0, - vertexBufferUsage,indexBufferUsage, - vertexBufferShadowed,indexBufferShadowed).first); - pMesh->load(); - return pMesh; - } - //----------------------------------------------------------------------- - MeshPtr MeshManager::create (const String& name, const String& group, - bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams) - { - return static_pointer_cast(createResource(name,group,isManual,loader,createParams)); - } - //----------------------------------------------------------------------- - MeshPtr MeshManager::createManual( const String& name, const String& groupName, - ManualResourceLoader* loader) - { - // Don't try to get existing, create should fail if already exists - return create(name, groupName, true, loader); - } - //----------------------------------------------------------------------- - MeshPtr MeshManager::createPlane( const String& name, const String& groupName, - const Plane& plane, Real width, Real height, int xsegments, int ysegments, - bool normals, unsigned short numTexCoordSets, Real xTile, Real yTile, const Vector3& upVector, - HardwareBuffer::Usage vertexBufferUsage, HardwareBuffer::Usage indexBufferUsage, - bool vertexShadowBuffer, bool indexShadowBuffer) - { - // Create manual mesh which calls back self to load - MeshPtr pMesh = createManual(name, groupName, mPrefabLoader.get()); - // Planes can never be manifold - pMesh->setAutoBuildEdgeLists(false); - // store parameters - MeshBuildParams params = {}; - params.type = MBT_PLANE; - params.plane = plane; - params.width = width; - params.height = height; - params.xsegments = xsegments; - params.ysegments = ysegments; - params.normals = normals; - params.numTexCoordSets = numTexCoordSets; - params.xTile = xTile; - params.yTile = yTile; - params.upVector = upVector; - params.vertexBufferUsage = vertexBufferUsage; - params.indexBufferUsage = indexBufferUsage; - params.vertexShadowBuffer = vertexShadowBuffer; - params.indexShadowBuffer = indexShadowBuffer; - - pMesh->getUserObjectBindings().setUserAny("_MeshBuildParams", Any(params)); - - // to preserve previous behaviour, load immediately - pMesh->load(); - - return pMesh; - } - - //----------------------------------------------------------------------- - MeshPtr MeshManager::createCurvedPlane( const String& name, const String& groupName, - const Plane& plane, Real width, Real height, Real bow, int xsegments, int ysegments, - bool normals, unsigned short numTexCoordSets, Real xTile, Real yTile, const Vector3& upVector, - HardwareBuffer::Usage vertexBufferUsage, HardwareBuffer::Usage indexBufferUsage, - bool vertexShadowBuffer, bool indexShadowBuffer) - { - // Create manual mesh which calls back self to load - MeshPtr pMesh = createManual(name, groupName, mPrefabLoader.get()); - // Planes can never be manifold - pMesh->setAutoBuildEdgeLists(false); - // store parameters - MeshBuildParams params = {}; - params.type = MBT_CURVED_PLANE; - params.plane = plane; - params.width = width; - params.height = height; - params.curvature = bow; - params.xsegments = xsegments; - params.ysegments = ysegments; - params.normals = normals; - params.numTexCoordSets = numTexCoordSets; - params.xTile = xTile; - params.yTile = yTile; - params.upVector = upVector; - params.vertexBufferUsage = vertexBufferUsage; - params.indexBufferUsage = indexBufferUsage; - params.vertexShadowBuffer = vertexShadowBuffer; - params.indexShadowBuffer = indexShadowBuffer; - - pMesh->getUserObjectBindings().setUserAny("_MeshBuildParams", Any(params)); - - // to preserve previous behaviour, load immediately - pMesh->load(); - - return pMesh; - - } - //----------------------------------------------------------------------- - MeshPtr MeshManager::createCurvedIllusionPlane( - const String& name, const String& groupName, const Plane& plane, - Real width, Real height, Real curvature, - int xsegments, int ysegments, - bool normals, unsigned short numTexCoordSets, - Real uTile, Real vTile, const Vector3& upVector, - const Quaternion& orientation, - HardwareBuffer::Usage vertexBufferUsage, - HardwareBuffer::Usage indexBufferUsage, - bool vertexShadowBuffer, bool indexShadowBuffer, - int ySegmentsToKeep) - { - // Create manual mesh which calls back self to load - MeshPtr pMesh = createManual(name, groupName, mPrefabLoader.get()); - // Planes can never be manifold - pMesh->setAutoBuildEdgeLists(false); - // store parameters - MeshBuildParams params; - params.type = MBT_CURVED_ILLUSION_PLANE; - params.plane = plane; - params.width = width; - params.height = height; - params.curvature = curvature; - params.xsegments = xsegments; - params.ysegments = ysegments; - params.normals = normals; - params.numTexCoordSets = numTexCoordSets; - params.xTile = uTile; - params.yTile = vTile; - params.upVector = upVector; - params.orientation = orientation; - params.vertexBufferUsage = vertexBufferUsage; - params.indexBufferUsage = indexBufferUsage; - params.vertexShadowBuffer = vertexShadowBuffer; - params.indexShadowBuffer = indexShadowBuffer; - params.ySegmentsToKeep = ySegmentsToKeep; - - pMesh->getUserObjectBindings().setUserAny("_MeshBuildParams", Any(params)); - - // to preserve previous behaviour, load immediately - pMesh->load(); - - return pMesh; - } - //------------------------------------------------------------------------- - void MeshManager::setListener(Ogre::MeshSerializerListener *listener) - { - mListener = listener; - } - //------------------------------------------------------------------------- - MeshSerializerListener *MeshManager::getListener() - { - return mListener; - } - //----------------------------------------------------------------------- - PatchMeshPtr MeshManager::createBezierPatch(const String& name, const String& groupName, - void* controlPointBuffer, VertexDeclaration *declaration, - size_t width, size_t height, - size_t uMaxSubdivisionLevel, size_t vMaxSubdivisionLevel, - PatchSurface::VisibleSide visibleSide, - HardwareBuffer::Usage vbUsage, HardwareBuffer::Usage ibUsage, - bool vbUseShadow, bool ibUseShadow) - { - if (width < 3 || height < 3) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Bezier patch require at least 3x3 control points", - "MeshManager::createBezierPatch"); - } - - MeshPtr pMesh = getByName(name, groupName); - if (pMesh) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, "A mesh called " + name + - " already exists!", "MeshManager::createBezierPatch"); - } - PatchMesh* pm = OGRE_NEW PatchMesh(this, name, getNextHandle(), groupName); - pm->define(controlPointBuffer, declaration, width, height, - uMaxSubdivisionLevel, vMaxSubdivisionLevel, visibleSide, vbUsage, ibUsage, - vbUseShadow, ibUseShadow); - pm->load(); - ResourcePtr res(pm); - addImpl(res); - - return static_pointer_cast(res); - } - //----------------------------------------------------------------------- - void MeshManager::setPrepareAllMeshesForShadowVolumes(bool enable) - { - mPrepAllMeshesForShadowVolumes = enable; - } - //----------------------------------------------------------------------- - bool MeshManager::getPrepareAllMeshesForShadowVolumes(void) - { - return mPrepAllMeshesForShadowVolumes; - } - //----------------------------------------------------------------------- - VertexElementType MeshManager::getBlendWeightsBaseElementType() const - { - return mBlendWeightsBaseElementType; - } - //----------------------------------------------------------------------- - void MeshManager::setBlendWeightsBaseElementType( VertexElementType vet ) - { - switch ( vet ) - { - case VET_UBYTE4_NORM: - case VET_USHORT2_NORM: - case VET_FLOAT1: - mBlendWeightsBaseElementType = vet; - break; - default: - OgreAssert(false, "Unsupported BlendWeightsBaseElementType"); - break; - } - } - //----------------------------------------------------------------------- - Real MeshManager::getBoundsPaddingFactor( void ) - { - return mBoundsPaddingFactor; - } - //----------------------------------------------------------------------- - void MeshManager::setBoundsPaddingFactor(Real paddingFactor) - { - mBoundsPaddingFactor = paddingFactor; - } - //----------------------------------------------------------------------- - Resource* MeshManager::createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams) - { - // no use for createParams here - return OGRE_NEW Mesh(this, name, handle, group, isManual, loader); - } - //----------------------------------------------------------------------- - -} diff --git a/OgreMain/src/OgreMeshSerializer.cpp b/OgreMain/src/OgreMeshSerializer.cpp deleted file mode 100644 index c73a7f30cb0..00000000000 --- a/OgreMain/src/OgreMeshSerializer.cpp +++ /dev/null @@ -1,205 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreMeshSerializerImpl.h" - -namespace Ogre { - - class _OgrePrivate MeshVersionData : public SerializerAlloc - { - public: - MeshVersion version; - String versionString; - MeshSerializerImpl* impl; - - MeshVersionData(MeshVersion _ver, const String& _string, MeshSerializerImpl* _impl) - : version(_ver), versionString(_string), impl(_impl) {} - - ~MeshVersionData() { OGRE_DELETE impl; } - - }; - - const unsigned short HEADER_CHUNK_ID = 0x1000; - //--------------------------------------------------------------------- - MeshSerializer::MeshSerializer() - :mListener(0) - { - // Init implementations - // String identifiers have not always been 100% unified with OGRE version - - // Note MUST be added in reverse order so latest is first in the list - - // This one is a little ugly, 1.10 is used for version 1.1 legacy meshes. - // So bump up to 1.100 - mVersionData.push_back(OGRE_NEW MeshVersionData( - MESH_VERSION_1_10, "[MeshSerializer_v1.100]", - OGRE_NEW MeshSerializerImpl())); - - mVersionData.push_back(OGRE_NEW MeshVersionData( - MESH_VERSION_1_8, "[MeshSerializer_v1.8]", - OGRE_NEW MeshSerializerImpl_v1_8())); - - mVersionData.push_back(OGRE_NEW MeshVersionData( - MESH_VERSION_1_7, "[MeshSerializer_v1.41]", - OGRE_NEW MeshSerializerImpl_v1_41())); - - mVersionData.push_back(OGRE_NEW MeshVersionData( - MESH_VERSION_1_4, "[MeshSerializer_v1.40]", - OGRE_NEW MeshSerializerImpl_v1_4())); - - mVersionData.push_back(OGRE_NEW MeshVersionData( - MESH_VERSION_1_0, "[MeshSerializer_v1.30]", - OGRE_NEW MeshSerializerImpl_v1_3())); - mVersionData.push_back(OGRE_NEW MeshVersionData( - MESH_VERSION_LEGACY, "[MeshSerializer_v1.20]", - OGRE_NEW MeshSerializerImpl_v1_2())); - - mVersionData.push_back(OGRE_NEW MeshVersionData( - MESH_VERSION_LEGACY, "[MeshSerializer_v1.10]", - OGRE_NEW MeshSerializerImpl_v1_1())); - - } - //--------------------------------------------------------------------- - MeshSerializer::~MeshSerializer() - { - // delete map - for (auto & i : mVersionData) - { - OGRE_DELETE i; - } - mVersionData.clear(); - - } - //--------------------------------------------------------------------- - void MeshSerializer::exportMesh(const Mesh* pMesh, const String& filename, - MeshVersion version, Endian endianMode) - { - DataStreamPtr stream = _openFileStream(filename, std::ios::binary | std::ios::out); - - exportMesh(pMesh, stream, version, endianMode); - - stream->close(); - } - //--------------------------------------------------------------------- - void MeshSerializer::exportMesh(const Mesh* pMesh, DataStreamPtr stream, - MeshVersion version, Endian endianMode) - { - if (version == MESH_VERSION_LEGACY) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "You may not supply a legacy version number (pre v1.0) for writing meshes.", - "MeshSerializer::exportMesh"); - - MeshSerializerImpl* impl = 0; - if (version == MESH_VERSION_LATEST) - impl = mVersionData[0]->impl; - else - { - for (auto & i : mVersionData) - { - if (version == i->version) - { - impl = i->impl; - break; - } - } - } - - if (!impl) - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Cannot find serializer implementation for " - "specified version", "MeshSerializer::exportMesh"); - - - impl->exportMesh(pMesh, stream, endianMode); - } - //--------------------------------------------------------------------- - void MeshSerializer::importMesh(const DataStreamPtr& stream, Mesh* pDest) - { - determineEndianness(stream); - - // Read header and determine the version - unsigned short headerID; - - // Read header ID - readShorts(stream, &headerID, 1); - - if (headerID != HEADER_CHUNK_ID) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "File header not found", - "MeshSerializer::importMesh"); - } - // Read version - String ver = readString(stream); - // Jump back to start - stream->seek(0); - - // Find the implementation to use - MeshSerializerImpl* impl = 0; - for (auto & i : mVersionData) - { - if (i->versionString == ver) - { - impl = i->impl; - break; - } - } - if (!impl) - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Cannot find serializer implementation for " - "mesh version " + ver, "MeshSerializer::importMesh"); - - // Call implementation - impl->importMesh(stream, pDest, mListener); - // Warn on old version of mesh - if (ver != mVersionData[0]->versionString) - { - LogManager::getSingleton().logWarning(pDest->getName() + " uses an old format " + ver + - "; upgrade with the OgreMeshUpgrader tool"); - } - - if(mListener) - mListener->processMeshCompleted(pDest); - - auto rs = Root::getSingletonPtr() ? Root::getSingleton().getRenderSystem() : NULL; - if (!rs || !rs->getCapabilities()->hasCapability(RSC_VERTEX_FORMAT_INT_10_10_10_2)) - { - // unpacks to floats, if packed - pDest->_convertVertexElement(VES_NORMAL, VET_FLOAT3); - pDest->_convertVertexElement(VES_TANGENT, VET_FLOAT4); - } - } - //--------------------------------------------------------------------- - void MeshSerializer::setListener(Ogre::MeshSerializerListener *listener) - { - mListener = listener; - } - //------------------------------------------------------------------------- - MeshSerializerListener *MeshSerializer::getListener() - { - return mListener; - } -} - diff --git a/OgreMain/src/OgreMeshSerializerImpl.cpp b/OgreMain/src/OgreMeshSerializerImpl.cpp deleted file mode 100644 index b5f4235ba03..00000000000 --- a/OgreMain/src/OgreMeshSerializerImpl.cpp +++ /dev/null @@ -1,4010 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreMeshSerializerImpl.h" -#include "OgreMeshFileFormat.h" -#include "OgreAnimation.h" -#include "OgreAnimationTrack.h" -#include "OgreLodStrategyManager.h" -#include "OgreDistanceLodStrategy.h" - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -// Disable conversion warnings, we do a lot of them, intentionally -# pragma warning (disable : 4267) -#endif - - -namespace Ogre { - - /// stream overhead = ID + size - const long MSTREAM_OVERHEAD_SIZE = sizeof(uint16) + sizeof(uint32); - //--------------------------------------------------------------------- - MeshSerializerImpl::MeshSerializerImpl() - { - // Version number - mVersion = "[MeshSerializer_v1.100]"; - } - //--------------------------------------------------------------------- - MeshSerializerImpl::~MeshSerializerImpl() - { - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::exportMesh(const Mesh* pMesh, - const DataStreamPtr& stream, Endian endianMode) - { - LogManager::getSingleton().logMessage("MeshSerializer writing mesh data to stream " + stream->getName() + "..."); - - // Decide on endian mode - determineEndianness(endianMode); - - // Check that the mesh has it's bounds set - if (pMesh->getBounds().isNull() || pMesh->getBoundingSphereRadius() == 0.0f) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "The Mesh you have supplied does not have its" - " bounds completely defined. Define them first before exporting.", - "MeshSerializerImpl::exportMesh"); - } - mStream = stream; - if (!mStream->isWriteable()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Unable to use stream " + mStream->getName() + " for writing", - "MeshSerializerImpl::exportMesh"); - } - - writeFileHeader(); - LogManager::getSingleton().logMessage("File header written."); - - - LogManager::getSingleton().logMessage("Writing mesh data..."); - pushInnerChunk(mStream); - writeMesh(pMesh); - popInnerChunk(mStream); - LogManager::getSingleton().logMessage("Mesh data exported."); - - LogManager::getSingleton().logMessage("MeshSerializer export successful."); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::importMesh(const DataStreamPtr& stream, Mesh* pMesh, MeshSerializerListener *listener) - { - // Determine endianness (must be the first thing we do!) - determineEndianness(stream); - -#if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE - enableValidation(); -#endif - // Check header - readFileHeader(stream); - pushInnerChunk(stream); - unsigned short streamID = readChunk(stream); - - while(!stream->eof()) - { - switch (streamID) - { - case M_MESH: - readMesh(stream, pMesh, listener); - break; - } - - streamID = readChunk(stream); - } - popInnerChunk(stream); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::writeMesh(const Mesh* pMesh) - { - exportedLodCount = 1; // generate edge data for original mesh - - // Header - writeChunkHeader(M_MESH, calcMeshSize(pMesh)); - { - // bool skeletallyAnimated - bool skelAnim = pMesh->hasSkeleton(); - writeBools(&skelAnim, 1); - - pushInnerChunk(mStream); - - // Write shared geometry - if (pMesh->sharedVertexData) - writeGeometry(pMesh->sharedVertexData); - - // Write Submeshes - for (unsigned short i = 0; i < pMesh->getNumSubMeshes(); ++i) - { - LogManager::getSingleton().logMessage("Writing submesh..."); - writeSubMesh(pMesh->getSubMesh(i)); - LogManager::getSingleton().logMessage("Submesh exported."); - } - - // Write skeleton info if required - if (pMesh->hasSkeleton()) - { - LogManager::getSingleton().logMessage("Exporting skeleton link..."); - // Write skeleton link - writeSkeletonLink(pMesh->getSkeletonName()); - LogManager::getSingleton().logMessage("Skeleton link exported."); - - // Write bone assignments - if (!pMesh->mBoneAssignments.empty()) - { - LogManager::getSingleton().logMessage("Exporting shared geometry bone assignments..."); - - Mesh::VertexBoneAssignmentList::const_iterator vi; - for (vi = pMesh->mBoneAssignments.begin(); - vi != pMesh->mBoneAssignments.end(); ++vi) - { - writeMeshBoneAssignment(vi->second); - } - - LogManager::getSingleton().logMessage("Shared geometry bone assignments exported."); - } - } - -#if !OGRE_NO_MESHLOD - // Write LOD data if any - if (pMesh->getNumLodLevels() > 1) - { - LogManager::getSingleton().logMessage("Exporting LOD information...."); - writeLodLevel(pMesh); - LogManager::getSingleton().logMessage("LOD information exported."); - - } -#endif - - // Write bounds information - LogManager::getSingleton().logMessage("Exporting bounds information...."); - writeBoundsInfo(pMesh); - LogManager::getSingleton().logMessage("Bounds information exported."); - - // Write submesh name table - LogManager::getSingleton().logMessage("Exporting submesh name table..."); - writeSubMeshNameTable(pMesh); - LogManager::getSingleton().logMessage("Submesh name table exported."); - - // Write edge lists - if (pMesh->isEdgeListBuilt()) - { - LogManager::getSingleton().logMessage("Exporting edge lists..."); - writeEdgeList(pMesh); - LogManager::getSingleton().logMessage("Edge lists exported"); - } - - // Write morph animation - writePoses(pMesh); - if (pMesh->hasVertexAnimation()) - { - writeAnimations(pMesh); - } - - // Write submesh extremes - writeExtremes(pMesh); - popInnerChunk(mStream); - } - } - //--------------------------------------------------------------------- - // Added by DrEvil - void MeshSerializerImpl::writeSubMeshNameTable(const Mesh* pMesh) - { - // Header - writeChunkHeader(M_SUBMESH_NAME_TABLE, calcSubMeshNameTableSize(pMesh)); - // Loop through and save out the index and names. - pushInnerChunk(mStream); - for (auto& s : pMesh->mSubMeshNameMap) - { - // Header - writeChunkHeader(M_SUBMESH_NAME_TABLE_ELEMENT, MSTREAM_OVERHEAD_SIZE + - sizeof(unsigned short) + calcStringSize(s.first)); - - // write the index - writeShorts(&s.second, 1); - // name - writeString(s.first); - } - popInnerChunk(mStream); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::writeSubMesh(const SubMesh* s) - { - // Header - writeChunkHeader(M_SUBMESH, calcSubMeshSize(s)); - - // char* materialName - writeString(s->getMaterialName()); - - // bool useSharedVertices - writeBools(&s->useSharedVertices, 1); - - unsigned int indexCount = static_cast(s->indexData->indexCount); - writeInts(&indexCount, 1); - - // bool indexes32Bit - bool idx32bit = (s->indexData->indexBuffer && - s->indexData->indexBuffer->getType() == HardwareIndexBuffer::IT_32BIT); - writeBools(&idx32bit, 1); - - if (indexCount > 0) - { - // unsigned short* faceVertexIndices ((indexCount) - HardwareIndexBufferSharedPtr ibuf = s->indexData->indexBuffer; - HardwareBufferLockGuard ibufLock(ibuf, HardwareBuffer::HBL_READ_ONLY); - if (idx32bit) - { - unsigned int* pIdx32 = static_cast(ibufLock.pData); - writeInts(pIdx32, s->indexData->indexCount); - } - else - { - unsigned short* pIdx16 = static_cast(ibufLock.pData); - writeShorts(pIdx16, s->indexData->indexCount); - } - } - - pushInnerChunk(mStream); - - // M_GEOMETRY stream (Optional: present only if useSharedVertices = false) - if (!s->useSharedVertices) - { - writeGeometry(s->vertexData); - } - - // Operation type - writeSubMeshOperation(s); - - // Bone assignments - if (!s->mBoneAssignments.empty()) - { - LogManager::getSingleton().logMessage("Exporting dedicated geometry bone assignments..."); - for (auto& vi : s->mBoneAssignments) - { - writeSubMeshBoneAssignment(vi.second); - } - LogManager::getSingleton().logMessage("Dedicated geometry bone assignments exported."); - } - popInnerChunk(mStream); - - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::writeExtremes(const Mesh *pMesh) - { - bool has_extremes = false; - for (unsigned short i = 0; i < pMesh->getNumSubMeshes(); ++i) - { - SubMesh *sm = pMesh->getSubMesh(i); - if (sm->extremityPoints.empty()) - continue; - if (!has_extremes) - { - has_extremes = true; - LogManager::getSingleton().logMessage("Writing submesh extremes..."); - } - writeSubMeshExtremes(i, sm); - } - if (has_extremes) - LogManager::getSingleton().logMessage("Extremes exported."); - } - size_t MeshSerializerImpl::calcExtremesSize(const Mesh* pMesh) - { - size_t size = 0; - for (auto *s : pMesh->getSubMeshes()) - { - if (!s->extremityPoints.empty()){ - size += calcSubMeshExtremesSize(s); - } - } - return size; - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::writeSubMeshExtremes(unsigned short idx, const SubMesh* s) - { - writeChunkHeader(M_TABLE_EXTREMES, calcSubMeshExtremesSize(s)); - - writeShorts(&idx, 1); - writeFloats(s->extremityPoints.front().ptr(), s->extremityPoints.size () * 3); - } - - size_t MeshSerializerImpl::calcSubMeshExtremesSize(const SubMesh* s) - { - return MSTREAM_OVERHEAD_SIZE + sizeof (unsigned short) + - s->extremityPoints.size() * sizeof (float)* 3; - } - - //--------------------------------------------------------------------- - void MeshSerializerImpl::writeSubMeshOperation(const SubMesh* sm) - { - // Header - writeChunkHeader(M_SUBMESH_OPERATION, calcSubMeshOperationSize()); - - // unsigned short operationType - unsigned short opType = static_cast(sm->operationType); - writeShorts(&opType, 1); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::writeGeometry(const VertexData* vertexData) - { - const VertexDeclaration::VertexElementList& elemList = - vertexData->vertexDeclaration->getElements(); - const VertexBufferBinding::VertexBufferBindingMap& bindings = - vertexData->vertexBufferBinding->getBindings(); - - // Header - writeChunkHeader(M_GEOMETRY, calcGeometrySize(vertexData)); - - unsigned int vertexCount = static_cast(vertexData->vertexCount); - writeInts(&vertexCount, 1); - - pushInnerChunk(mStream); - { - // Vertex declaration - size_t size = MSTREAM_OVERHEAD_SIZE + elemList.size() * (MSTREAM_OVERHEAD_SIZE + sizeof(unsigned short)* 5); - writeChunkHeader(M_GEOMETRY_VERTEX_DECLARATION, size); - - pushInnerChunk(mStream); - { - unsigned short tmp; - size = MSTREAM_OVERHEAD_SIZE + sizeof(unsigned short) * 5; - for (auto& elem : elemList) - { - writeChunkHeader(M_GEOMETRY_VERTEX_ELEMENT, size); - // unsigned short source; // buffer bind source - tmp = elem.getSource(); - writeShorts(&tmp, 1); - // unsigned short type; // VertexElementType - tmp = static_cast(elem.getType()); - writeShorts(&tmp, 1); - // unsigned short semantic; // VertexElementSemantic - tmp = static_cast(elem.getSemantic()); - writeShorts(&tmp, 1); - // unsigned short offset; // start offset in buffer in bytes - tmp = static_cast(elem.getOffset()); - writeShorts(&tmp, 1); - // unsigned short index; // index of the semantic (for colours and texture coords) - tmp = elem.getIndex(); - writeShorts(&tmp, 1); - - } - } - popInnerChunk(mStream); - - - // Buffers and bindings - for (auto& vbi : bindings) - { - const HardwareVertexBufferSharedPtr& vbuf = vbi.second; - size_t vbufSizeInBytes = vbuf->getVertexSize() * vertexData->vertexCount; // vbuf->getSizeInBytes() is too large for meshes prepared for shadow volumes - size = (MSTREAM_OVERHEAD_SIZE * 2) + (sizeof(unsigned short) * 2) + vbufSizeInBytes; - writeChunkHeader(M_GEOMETRY_VERTEX_BUFFER, size); - // unsigned short bindIndex; // Index to bind this buffer to - unsigned short tmp = vbi.first; - writeShorts(&tmp, 1); - // unsigned short vertexSize; // Per-vertex size, must agree with declaration at this index - tmp = (unsigned short)vbuf->getVertexSize(); - writeShorts(&tmp, 1); - pushInnerChunk(mStream); - { - // Data - size = MSTREAM_OVERHEAD_SIZE + vbufSizeInBytes; - writeChunkHeader(M_GEOMETRY_VERTEX_BUFFER_DATA, size); - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_READ_ONLY); - - if (mFlipEndian) - { - // endian conversion - // Copy data - unsigned char* tempData = OGRE_ALLOC_T(unsigned char, vbufSizeInBytes, MEMCATEGORY_GEOMETRY); - memcpy(tempData, vbufLock.pData, vbufSizeInBytes); - flipToLittleEndian( - tempData, - vertexData->vertexCount, - vbuf->getVertexSize(), - vertexData->vertexDeclaration->findElementsBySource(vbi.first)); - writeData(tempData, vbuf->getVertexSize(), vertexData->vertexCount); - OGRE_FREE(tempData, MEMCATEGORY_GEOMETRY); - } - else - { - writeData(vbufLock.pData, vbuf->getVertexSize(), vertexData->vertexCount); - } - } - popInnerChunk(mStream); - } - } - popInnerChunk(mStream); - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl::calcSubMeshNameTableSize(const Mesh* pMesh) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - // Figure out the size of the Name table. - // Iterate through the subMeshList & add up the size of the indexes and names. - for (auto& s : pMesh->mSubMeshNameMap) - { - // size of the index + header size for each element chunk - size += MSTREAM_OVERHEAD_SIZE + sizeof(uint16); - // name - size += calcStringSize(s.first); - } - - // size of the sub-mesh name table. - return size; - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl::calcMeshSize(const Mesh* pMesh) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - - // bool hasSkeleton - size += sizeof(bool); - - // Geometry - if (pMesh->sharedVertexData) - { - size += calcGeometrySize(pMesh->sharedVertexData); - } - - // Submeshes - for (auto *s : pMesh->getSubMeshes()) - { - size += calcSubMeshSize(s); - } - - // Skeleton link - if (pMesh->hasSkeleton()) - { - size += calcSkeletonLinkSize(pMesh->getSkeletonName()); - // Write bone assignments - size += pMesh->mBoneAssignments.size() * calcBoneAssignmentSize(); - } - -#if !OGRE_NO_MESHLOD - // Write LOD data if any - if (pMesh->getNumLodLevels() > 1) - { - size += calcLodLevelSize(pMesh); - } -#endif - - size += calcBoundsInfoSize(); - - // Submesh name table - size += calcSubMeshNameTableSize(pMesh); - - // Edge list - if (pMesh->isEdgeListBuilt()) - { - size += calcEdgeListSize(pMesh); - } - - // Morph animation - size += calcPosesSize(pMesh); - - // Vertex animation - if (pMesh->hasVertexAnimation()) - { - size += calcAnimationsSize(pMesh); - } - - size += calcExtremesSize(pMesh); - - return size; - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl::calcSubMeshSize(const SubMesh* pSub) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - - // Material name - size += calcStringSize(pSub->getMaterialName()); - - // bool useSharedVertices - size += sizeof(bool); - // unsigned int indexCount - size += sizeof(unsigned int); - // bool indexes32bit - size += sizeof(bool); - - bool idx32bit = (pSub->indexData->indexBuffer && - pSub->indexData->indexBuffer->getType() == HardwareIndexBuffer::IT_32BIT); - // unsigned int* / unsigned short* faceVertexIndices - if (idx32bit) - size += sizeof(unsigned int) * pSub->indexData->indexCount; - else - size += sizeof(unsigned short) * pSub->indexData->indexCount; - - // Geometry - if (!pSub->useSharedVertices) - { - size += calcGeometrySize(pSub->vertexData); - } - - size += calcSubMeshOperationSize(); - - // Bone assignments - size += pSub->mBoneAssignments.size() * calcBoneAssignmentSize(); - - return size; - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl::calcSubMeshOperationSize() - { - return MSTREAM_OVERHEAD_SIZE + sizeof(uint16); - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl::calcGeometrySize(const VertexData* vertexData) - { - const VertexDeclaration::VertexElementList& elemList = - vertexData->vertexDeclaration->getElements(); - const VertexBufferBinding::VertexBufferBindingMap& bindings = - vertexData->vertexBufferBinding->getBindings(); - size_t size = MSTREAM_OVERHEAD_SIZE; - - // Vertex count - size += sizeof(unsigned int); - - // Vertex declaration - size += MSTREAM_OVERHEAD_SIZE + elemList.size() * (MSTREAM_OVERHEAD_SIZE + sizeof(unsigned short)* 5); - - // Buffers and bindings - size += bindings.size() * ((MSTREAM_OVERHEAD_SIZE * 2) + (sizeof(unsigned short)* 2)); - // Buffer data - for (auto& vbi : bindings) - { - const HardwareVertexBufferSharedPtr& vbuf = vbi.second; - size += vbuf->getVertexSize() * vertexData->vertexCount; // vbuf->getSizeInBytes() is too large for meshes prepared for shadow volumes - } - return size; - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readGeometry(const DataStreamPtr& stream, Mesh* pMesh, - VertexData* dest) - { - - dest->vertexStart = 0; - - unsigned int vertexCount = 0; - readInts(stream, &vertexCount, 1); - dest->vertexCount = vertexCount; - // Find optional geometry streams - if (!stream->eof()) - { - pushInnerChunk(stream); - unsigned short streamID = readChunk(stream); - while(!stream->eof() && - (streamID == M_GEOMETRY_VERTEX_DECLARATION || - streamID == M_GEOMETRY_VERTEX_BUFFER )) - { - switch (streamID) - { - case M_GEOMETRY_VERTEX_DECLARATION: - readGeometryVertexDeclaration(stream, pMesh, dest); - break; - case M_GEOMETRY_VERTEX_BUFFER: - readGeometryVertexBuffer(stream, pMesh, dest); - break; - } - // Get next stream - if (!stream->eof()) - { - streamID = readChunk(stream); - } - } - if (!stream->eof()) - { - // Backpedal back to start of non-submesh stream - backpedalChunkHeader(stream); - } - popInnerChunk(stream); - } - - // Perform any necessary colour conversions from ARGB to ABGR (UBYTE4) - dest->convertPackedColour(_DETAIL_SWAP_RB, VET_UBYTE4_NORM); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readGeometryVertexDeclaration(const DataStreamPtr& stream, - Mesh* pMesh, VertexData* dest) - { - // Find optional geometry streams - if (!stream->eof()) - { - pushInnerChunk(stream); - unsigned short streamID = readChunk(stream); - while(!stream->eof() && - (streamID == M_GEOMETRY_VERTEX_ELEMENT )) - { - switch (streamID) - { - case M_GEOMETRY_VERTEX_ELEMENT: - readGeometryVertexElement(stream, pMesh, dest); - break; - } - // Get next stream - if (!stream->eof()) - { - streamID = readChunk(stream); - } - } - if (!stream->eof()) - { - // Backpedal back to start of non-submesh stream - backpedalChunkHeader(stream); - } - popInnerChunk(stream); - } - - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readGeometryVertexElement(const DataStreamPtr& stream, - Mesh* pMesh, VertexData* dest) - { - unsigned short source, offset, index, tmp; - VertexElementType vType; - VertexElementSemantic vSemantic; - // unsigned short source; // buffer bind source - readShorts(stream, &source, 1); - // unsigned short type; // VertexElementType - readShorts(stream, &tmp, 1); - if(tmp == 4 || tmp == 11) - vType = VET_UBYTE4_NORM; - else - vType = static_cast(tmp); - // unsigned short semantic; // VertexElementSemantic - readShorts(stream, &tmp, 1); - vSemantic = static_cast(tmp); - // unsigned short offset; // start offset in buffer in bytes - readShorts(stream, &offset, 1); - // unsigned short index; // index of the semantic - readShorts(stream, &index, 1); - - dest->vertexDeclaration->addElement(source, offset, vType, vSemantic, index); - - if (vType == _DETAIL_SWAP_RB) - { - LogManager::getSingleton().stream(LML_WARNING) - << "Warning: VET_COLOUR_ARGB element type is deprecated and incurs conversion on load. " - << "Use OgreMeshUpgrader on '" << pMesh->getName() << "' as soon as possible."; - } - - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readGeometryVertexBuffer(const DataStreamPtr& stream, - Mesh* pMesh, VertexData* dest) - { - unsigned short bindIndex, vertexSize; - // unsigned short bindIndex; // Index to bind this buffer to - readShorts(stream, &bindIndex, 1); - // unsigned short vertexSize; // Per-vertex size, must agree with declaration at this index - readShorts(stream, &vertexSize, 1); - pushInnerChunk(stream); - { - // Check for vertex data header - unsigned short headerID; - headerID = readChunk(stream); - if (headerID != M_GEOMETRY_VERTEX_BUFFER_DATA) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Can't find vertex buffer data area", - "MeshSerializerImpl::readGeometryVertexBuffer"); - } - // Check that vertex size agrees - if (dest->vertexDeclaration->getVertexSize(bindIndex) != vertexSize) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Buffer vertex size does not agree with vertex declaration", - "MeshSerializerImpl::readGeometryVertexBuffer"); - } - - // Create / populate vertex buffer - HardwareVertexBufferSharedPtr vbuf; - vbuf = pMesh->getHardwareBufferManager()->createVertexBuffer( - vertexSize, - dest->vertexCount, - pMesh->mVertexBufferUsage, - pMesh->mVertexBufferShadowBuffer); - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - stream->read(vbufLock.pData, dest->vertexCount * vertexSize); - - // endian conversion for OSX - flipFromLittleEndian( - vbufLock.pData, - dest->vertexCount, - vertexSize, - dest->vertexDeclaration->findElementsBySource(bindIndex)); - - // Set binding - dest->vertexBufferBinding->setBinding(bindIndex, vbuf); - } - popInnerChunk(stream); - - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readSubMeshNameTable(const DataStreamPtr& stream, Mesh* pMesh) - { - // The map for - std::map subMeshNames; - unsigned short streamID, subMeshIndex; - - // Need something to store the index, and the objects name - // This table is a method that imported meshes can retain their naming - // so that the names established in the modelling software can be used - // to get the sub-meshes by name. The exporter must support exporting - // the optional stream M_SUBMESH_NAME_TABLE. - - // Read in all the sub-streams. Each sub-stream should contain an index and Ogre::String for the name. - if (!stream->eof()) - { - pushInnerChunk(stream); - streamID = readChunk(stream); - while(!stream->eof() && (streamID == M_SUBMESH_NAME_TABLE_ELEMENT )) - { - // Read in the index of the submesh. - readShorts(stream, &subMeshIndex, 1); - // Read in the String and map it to its index. - subMeshNames[subMeshIndex] = readString(stream); - - // If we're not end of file get the next stream ID - if (!stream->eof()) - streamID = readChunk(stream); - } - if (!stream->eof()) - { - // Backpedal back to start of stream - backpedalChunkHeader(stream); - } - popInnerChunk(stream); - } - - // Set all the submeshes names - // ? - // Loop through and save out the index and names. - for (auto& sn : subMeshNames) - { - // Name this submesh to the stored name. - pMesh->nameSubMesh(sn.second, sn.first); - } - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readMesh(const DataStreamPtr& stream, Mesh* pMesh, MeshSerializerListener *listener) - { - // Never automatically build edge lists for this version - // expect them in the file or not at all - pMesh->mAutoBuildEdgeLists = false; - - // bool skeletallyAnimated - bool skeletallyAnimated; - readBools(stream, &skeletallyAnimated, 1); - - // Find all substreams - if (!stream->eof()) - { - pushInnerChunk(stream); - unsigned short streamID = readChunk(stream); - while(!stream->eof() && - (streamID == M_GEOMETRY || - streamID == M_SUBMESH || - streamID == M_MESH_SKELETON_LINK || - streamID == M_MESH_BONE_ASSIGNMENT || - streamID == M_MESH_LOD_LEVEL || - streamID == M_MESH_BOUNDS || - streamID == M_SUBMESH_NAME_TABLE || - streamID == M_EDGE_LISTS || - streamID == M_POSES || - streamID == M_ANIMATIONS || - streamID == M_TABLE_EXTREMES)) - { - switch(streamID) - { - case M_GEOMETRY: - pMesh->createVertexData(); - try { - readGeometry(stream, pMesh, pMesh->sharedVertexData); - } - catch (ItemIdentityException&) - { - // duff geometry data entry with 0 vertices - pMesh->resetVertexData(); - // Skip this stream (pointer will have been returned to just after header) - stream->skip(mCurrentstreamLen - MSTREAM_OVERHEAD_SIZE); - } - break; - case M_SUBMESH: - readSubMesh(stream, pMesh, listener); - break; - case M_MESH_SKELETON_LINK: - readSkeletonLink(stream, pMesh, listener); - break; - case M_MESH_BONE_ASSIGNMENT: - readMeshBoneAssignment(stream, pMesh); - break; - case M_MESH_LOD_LEVEL: - readMeshLodLevel(stream, pMesh); - break; - case M_MESH_BOUNDS: - readBoundsInfo(stream, pMesh); - break; - case M_SUBMESH_NAME_TABLE: - readSubMeshNameTable(stream, pMesh); - break; - case M_EDGE_LISTS: - readEdgeList(stream, pMesh); - break; - case M_POSES: - readPoses(stream, pMesh); - break; - case M_ANIMATIONS: - readAnimations(stream, pMesh); - break; - case M_TABLE_EXTREMES: - readExtremes(stream, pMesh); - break; - } - - if (!stream->eof()) - { - streamID = readChunk(stream); - } - - } - if (!stream->eof()) - { - // Backpedal back to start of stream - backpedalChunkHeader(stream); - } - popInnerChunk(stream); - } - - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readSubMesh(const DataStreamPtr& stream, Mesh* pMesh, MeshSerializerListener *listener) - { - unsigned short streamID; - - SubMesh* sm = pMesh->createSubMesh(); - - // char* materialName - String materialName = readString(stream); - if(listener) - listener->processMaterialName(pMesh, &materialName); - if (auto material = MaterialManager::getSingleton().getByName(materialName, pMesh->getGroup())) - { - sm->setMaterial(material); - } - else - { - logMaterialNotFound(materialName, pMesh->getGroup(), "SubMesh of", pMesh->getName(), LML_WARNING); - } - - // bool useSharedVertices - readBools(stream,&sm->useSharedVertices, 1); - - sm->indexData->indexStart = 0; - unsigned int indexCount = 0; - readInts(stream, &indexCount, 1); - sm->indexData->indexCount = indexCount; - - HardwareIndexBufferSharedPtr ibuf; - // bool indexes32Bit - bool idx32bit; - readBools(stream, &idx32bit, 1); - if (indexCount > 0) - { - if (idx32bit) - { - ibuf = pMesh->getHardwareBufferManager()->createIndexBuffer( - HardwareIndexBuffer::IT_32BIT, - sm->indexData->indexCount, - pMesh->mIndexBufferUsage, - pMesh->mIndexBufferShadowBuffer); - HardwareBufferLockGuard ibufLock(ibuf, HardwareBuffer::HBL_DISCARD); - readInts(stream, static_cast(ibufLock.pData), sm->indexData->indexCount); - - } - else // 16-bit - { - ibuf = pMesh->getHardwareBufferManager()->createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, - sm->indexData->indexCount, - pMesh->mIndexBufferUsage, - pMesh->mIndexBufferShadowBuffer); - HardwareBufferLockGuard ibufLock(ibuf, HardwareBuffer::HBL_DISCARD); - readShorts(stream, static_cast(ibufLock.pData), sm->indexData->indexCount); - } - } - sm->indexData->indexBuffer = ibuf; - - pushInnerChunk(stream); - { - // M_GEOMETRY stream (Optional: present only if useSharedVertices = false) - if (!sm->useSharedVertices) - { - streamID = readChunk(stream); - if (streamID != M_GEOMETRY) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Missing geometry data in mesh file", - "MeshSerializerImpl::readSubMesh"); - } - sm->createVertexData(); - readGeometry(stream, pMesh, sm->vertexData); - } - - - // Find all bone assignments, submesh operation, and texture aliases (if present) - if (!stream->eof()) - { - streamID = readChunk(stream); - bool seenTexAlias = false; - while(!stream->eof() && - (streamID == M_SUBMESH_BONE_ASSIGNMENT || - streamID == M_SUBMESH_OPERATION || - streamID == M_SUBMESH_TEXTURE_ALIAS)) - { - switch(streamID) - { - case M_SUBMESH_OPERATION: - readSubMeshOperation(stream, pMesh, sm); - break; - case M_SUBMESH_BONE_ASSIGNMENT: - readSubMeshBoneAssignment(stream, pMesh, sm); - break; - case M_SUBMESH_TEXTURE_ALIAS: - seenTexAlias = true; - String aliasName = readString(stream); - String textureName = readString(stream); - break; - } - - if (!stream->eof()) - { - streamID = readChunk(stream); - } - - } - - if (seenTexAlias) - LogManager::getSingleton().logError("texture aliases for SubMeshes are unsupported - " + - stream->getName()); - - if (!stream->eof()) - { - // Backpedal back to start of stream - backpedalChunkHeader(stream); - } - } - } - popInnerChunk(stream); - - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readSubMeshOperation(const DataStreamPtr& stream, - Mesh* pMesh, SubMesh* sm) - { - // unsigned short operationType - unsigned short opType; - readShorts(stream, &opType, 1); - sm->operationType = static_cast(opType); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::writeSkeletonLink(const String& skelName) - { - writeChunkHeader(M_MESH_SKELETON_LINK, calcSkeletonLinkSize(skelName)); - - writeString(skelName); - - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readSkeletonLink(const DataStreamPtr& stream, Mesh* pMesh, MeshSerializerListener *listener) - { - String skelName = readString(stream); - - if(listener) - listener->processSkeletonName(pMesh, &skelName); - - pMesh->setSkeletonName(skelName); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readTextureLayer(const DataStreamPtr& stream, Mesh* pMesh, - MaterialPtr& pMat) - { - // Material definition section phased out of 1.1 - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl::calcSkeletonLinkSize(const String& skelName) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - - size += calcStringSize(skelName); - - return size; - - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::writeMeshBoneAssignment(const VertexBoneAssignment& assign) - { - writeChunkHeader(M_MESH_BONE_ASSIGNMENT, calcBoneAssignmentSize()); - - // unsigned int vertexIndex; - writeInts(&(assign.vertexIndex), 1); - // unsigned short boneIndex; - writeShorts(&(assign.boneIndex), 1); - // float weight; - writeFloats(&(assign.weight), 1); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::writeSubMeshBoneAssignment(const VertexBoneAssignment& assign) - { - writeChunkHeader(M_SUBMESH_BONE_ASSIGNMENT, calcBoneAssignmentSize()); - - // unsigned int vertexIndex; - writeInts(&(assign.vertexIndex), 1); - // unsigned short boneIndex; - writeShorts(&(assign.boneIndex), 1); - // float weight; - writeFloats(&(assign.weight), 1); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readMeshBoneAssignment(const DataStreamPtr& stream, Mesh* pMesh) - { - VertexBoneAssignment assign; - - // unsigned int vertexIndex; - readInts(stream, &(assign.vertexIndex),1); - // unsigned short boneIndex; - readShorts(stream, &(assign.boneIndex),1); - // float weight; - readFloats(stream, &(assign.weight), 1); - - pMesh->addBoneAssignment(assign); - - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readSubMeshBoneAssignment(const DataStreamPtr& stream, - Mesh* pMesh, SubMesh* sub) - { - VertexBoneAssignment assign; - - // unsigned int vertexIndex; - readInts(stream, &(assign.vertexIndex),1); - // unsigned short boneIndex; - readShorts(stream, &(assign.boneIndex),1); - // float weight; - readFloats(stream, &(assign.weight), 1); - - sub->addBoneAssignment(assign); - - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl::calcBoneAssignmentSize(void) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - - // Vert index - size += sizeof(unsigned int); - // Bone index - size += sizeof(unsigned short); - // weight - size += sizeof(float); - - return size; - } - //--------------------------------------------------------------------- -#if !OGRE_NO_MESHLOD - void MeshSerializerImpl::writeLodLevel(const Mesh* pMesh) - { - const LodStrategy *strategy = pMesh->getLodStrategy(); - exportedLodCount = pMesh->getNumLodLevels(); - writeChunkHeader(M_MESH_LOD_LEVEL, calcLodLevelSize(pMesh)); - writeString(strategy->getName()); // string strategyName; - writeShorts(&exportedLodCount, 1); // unsigned short numLevels; - - pushInnerChunk(mStream); - // Loop from LOD 1 (not 0, this is full detail) - for (ushort i = 1; i < exportedLodCount; ++i) - { - const MeshLodUsage& usage = pMesh->mMeshLodUsageList[i]; - if (pMesh->_isManualLodLevel(i)) - { - writeLodUsageManual(usage); - } - else - { - writeLodUsageGenerated(pMesh, usage, i); - } - } - popInnerChunk(mStream); - } - - //--------------------------------------------------------------------- - void MeshSerializerImpl::writeLodUsageManual(const MeshLodUsage& usage) - { - writeChunkHeader(M_MESH_LOD_MANUAL, calcLodUsageManualSize(usage)); - float userValue = static_cast(usage.userValue); - writeFloats(&userValue, 1); - writeString(usage.manualName); - } - - void MeshSerializerImpl::writeLodUsageGeneratedSubmesh( const SubMesh* submesh, unsigned short lodNum ) - { - const IndexData* indexData = submesh->mLodFaceList[lodNum-1]; - HardwareIndexBufferSharedPtr ibuf = indexData->indexBuffer; - assert(ibuf); - unsigned int bufferIndex = -1; - for(ushort i = 1; i < lodNum; i++){ - // it will check any previous Lod levels for the same buffer. - // This will allow to use merged/shared/compressed buffers. - const IndexData* prevIndexData = submesh->mLodFaceList[i-1]; - if(prevIndexData->indexCount != 0 && prevIndexData->indexBuffer == indexData->indexBuffer){ - bufferIndex = i; - } - } - - unsigned int indexCount = static_cast(indexData->indexCount); - writeInts(&indexCount, 1); - unsigned int indexStart = static_cast(indexData->indexStart); - writeInts(&indexStart, 1); - writeInts(&bufferIndex, 1); - - if(bufferIndex == (unsigned int)-1) { // It has its own buffer (Not compressed). - bool is32BitIndices = (ibuf->getType() == HardwareIndexBuffer::IT_32BIT); - writeBools(&is32BitIndices, 1); - - unsigned int bufIndexCount = static_cast(ibuf->getNumIndexes()); - writeInts(&bufIndexCount, 1); - - if (bufIndexCount > 0) - { - if (is32BitIndices) - { - HardwareBufferLockGuard ibufLock(ibuf, HardwareBuffer::HBL_READ_ONLY); - writeInts(static_cast(ibufLock.pData), bufIndexCount); - } - else - { - HardwareBufferLockGuard ibufLock(ibuf, HardwareBuffer::HBL_READ_ONLY); - writeShorts(static_cast(ibufLock.pData), bufIndexCount); - } - } - } - } - void MeshSerializerImpl::writeLodUsageGenerated(const Mesh* pMesh, const MeshLodUsage& usage, unsigned short lodNum) - { - writeChunkHeader(M_MESH_LOD_GENERATED, calcLodUsageGeneratedSize(pMesh, usage, lodNum)); - float userValue = static_cast(usage.userValue); - writeFloats(&userValue, 1); - for (ushort i = 0; i < pMesh->getNumSubMeshes(); i++) - { - SubMesh* submesh = pMesh->getSubMesh(i); - writeLodUsageGeneratedSubmesh(submesh, lodNum); - } - } -#endif - size_t MeshSerializerImpl::calcLodLevelSize(const Mesh* pMesh) - { - exportedLodCount = pMesh->getNumLodLevels(); - size_t size = MSTREAM_OVERHEAD_SIZE; // Header - size += calcStringSize(pMesh->getLodStrategy()->getName()); // string strategyName; - size += sizeof(unsigned short); // unsigned short numLevels; - //size += sizeof(bool); // bool manual; <== this is removed in v1_9 - - // Loop from LOD 1 (not 0, this is full detail) - for (ushort i = 1; i < exportedLodCount; ++i) - { - const MeshLodUsage& usage = pMesh->mMeshLodUsageList[i]; - if (pMesh->_isManualLodLevel(i)) - { - size += calcLodUsageManualSize(usage); - } - else - { - size += calcLodUsageGeneratedSize(pMesh, usage, i); - } - } - return size; - } - - size_t MeshSerializerImpl::calcLodUsageManualSize(const MeshLodUsage& usage) - { - size_t size = MSTREAM_OVERHEAD_SIZE;// Header - size += sizeof(float);// float usage.userValue; - size += calcStringSize(usage.manualName); - return size; - } - - size_t MeshSerializerImpl::calcLodUsageGeneratedSize(const Mesh* pMesh, const MeshLodUsage& usage, unsigned short lodNum) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - size += sizeof(float); // float usage.userValue; - for (auto *s : pMesh->getSubMeshes()) - { - size += calcLodUsageGeneratedSubmeshSize(s, lodNum); - } - return size; - } - size_t MeshSerializerImpl::calcLodUsageGeneratedSubmeshSize( const SubMesh* submesh, unsigned short lodNum ) - { - size_t size = 0; - - const IndexData* indexData = submesh->mLodFaceList[lodNum-1]; - HardwareIndexBufferSharedPtr ibuf = indexData->indexBuffer; - assert(ibuf); - unsigned int bufferIndex = -1; - for(ushort i = 1; i < lodNum; i++){ - // it will check any previous Lod levels for the same buffer. - // This will allow to use merged/shared/compressed buffers. - const IndexData* prevIndexData = submesh->mLodFaceList[i-1]; - if(prevIndexData->indexCount != 0 && prevIndexData->indexBuffer == indexData->indexBuffer){ - bufferIndex = i; - } - } - - size += sizeof(unsigned int); // unsigned int indexData->indexCount; - size += sizeof(unsigned int); // unsigned int indexData->indexStart; - size += sizeof(unsigned int); // unsigned int bufferIndex; - if(bufferIndex == (unsigned int)-1) { - size += sizeof(bool); // bool indexes32Bit - size += sizeof(unsigned int); // unsigned int ibuf->getNumIndexes() - size += !ibuf ? 0 : static_cast(ibuf->getIndexSize() * ibuf->getNumIndexes()); // faces - } - return size; - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::writeBoundsInfo(const Mesh* pMesh) - { - writeChunkHeader(M_MESH_BOUNDS, calcBoundsInfoSize()); - - // float minx, miny, minz - const Vector3& min = pMesh->mAABB.getMinimum(); - const Vector3& max = pMesh->mAABB.getMaximum(); - writeFloats(min.ptr(), 3); - writeFloats(max.ptr(), 3); - writeFloats(&pMesh->mBoundRadius, 1); - - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readBoundsInfo(const DataStreamPtr& stream, Mesh* pMesh) - { - Vector3 min, max; - readFloats(stream, min.ptr(), 3); - readFloats(stream, max.ptr(), 3); - AxisAlignedBox box(min, max); - pMesh->_setBounds(box, false); - - float radius; - readFloats(stream, &radius, 1); - pMesh->_setBoundingSphereRadius(radius); - } - size_t MeshSerializerImpl::calcBoundsInfoSize() - { - unsigned long size = MSTREAM_OVERHEAD_SIZE; - size += sizeof(float) * 7; - return size; - } - //--------------------------------------------------------------------- - - void MeshSerializerImpl::readMeshLodLevel(const DataStreamPtr& stream, Mesh* pMesh) - { -#if OGRE_NO_MESHLOD - - /* - //Since the chunk sizes in old versions are messed up, we can't use this clean solution. - // We need to walk through the data to not rely on the chunk size! - stream->skip(mCurrentstreamLen); - - // Since we got here, we have already read the chunk header. - backpedalChunkHeader(stream); - */ - uint16 numSubs = pMesh->getNumSubMeshes(); - String strategyName = readString(stream); - uint16 numLods; - readShorts(stream, &numLods, 1); - pushInnerChunk(stream); - for (int lodID = 1; lodID < numLods; lodID++){ - unsigned short streamID = readChunk(stream); - Real usageValue; - readFloats(stream, &usageValue, 1); - switch (streamID){ - case M_MESH_LOD_MANUAL: - { - String manualName = readString(stream); - break; - } - case M_MESH_LOD_GENERATED: - for (int i = 0; i < numSubs; ++i) - { - unsigned int numIndexes; - readInts(stream, &numIndexes, 1); - - unsigned int offset; - readInts(stream, &offset, 1); - - // For merged buffers, you can pass the index of previous Lod. - // To create buffer it should be -1. - unsigned int bufferIndex; - readInts(stream, &bufferIndex, 1); - if (bufferIndex == (unsigned int)-1) { - // generate buffers - - // bool indexes32Bit - bool idx32Bit; - readBools(stream, &idx32Bit, 1); - - unsigned int buffIndexCount; - readInts(stream, &buffIndexCount, 1); - - size_t buffSize = buffIndexCount * (idx32Bit ? 4 : 2); - stream->skip(buffSize); - } - } - break; - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Invalid Lod Usage type in " + pMesh->getName(), - "MeshSerializerImpl::readMeshLodInfo"); - } - } - popInnerChunk(stream); -#else - // Read the strategy to be used for this mesh - String strategyName = readString(stream); - LodStrategy *strategy = LodStrategyManager::getSingleton().getStrategy(strategyName); - - // Check that valid strategy name was given, otherwise use default - if (strategy == 0) - strategy = LodStrategyManager::getSingleton().getDefaultStrategy(); - - pMesh->setLodStrategy(strategy); - - // unsigned short numLevels; - readShorts(stream, &(pMesh->mNumLods), 1); - pMesh->mMeshLodUsageList.resize(pMesh->mNumLods); - for (auto *s : pMesh->getSubMeshes()) - { - assert(s->mLodFaceList.empty()); - s->mLodFaceList.resize(pMesh->mNumLods-1); - } - pushInnerChunk(stream); - // lodID=0 is the original mesh. We need to skip it. - for(int lodID = 1; lodID < pMesh->mNumLods; lodID++){ - // Read depth - MeshLodUsage& usage = pMesh->mMeshLodUsageList[lodID]; - unsigned short streamID = readChunk(stream); - readFloats(stream, &(usage.userValue), 1); - switch(streamID){ - case M_MESH_LOD_MANUAL: - readMeshLodUsageManual(stream, pMesh, lodID, usage); - break; - case M_MESH_LOD_GENERATED: - readMeshLodUsageGenerated(stream, pMesh, lodID, usage); - break; - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Invalid Lod Usage type in " + pMesh->getName(), - "MeshSerializerImpl::readMeshLodInfo"); - } - usage.manualMesh.reset(); // will trigger load later with manual Lod - usage.edgeData = NULL; - } - popInnerChunk(stream); -#endif - } -#if !OGRE_NO_MESHLOD - //--------------------------------------------------------------------- - void MeshSerializerImpl::readMeshLodUsageManual( const DataStreamPtr& stream, Mesh* pMesh, unsigned short lodNum, MeshLodUsage& usage ) - { - pMesh->mHasManualLodLevel = true; - usage.manualName = readString(stream); - - // Generate for mixed - for (auto *s : pMesh->getSubMeshes()) - { - s->mLodFaceList[lodNum-1] = OGRE_NEW IndexData(); - } - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readMeshLodUsageGenerated( const DataStreamPtr& stream, Mesh* pMesh, unsigned short lodNum, MeshLodUsage& usage ) - { - usage.manualName = ""; - - // Get one set of detail per SubMesh - for (auto *s : pMesh->getSubMeshes()) - { - s->mLodFaceList[lodNum - 1] = OGRE_NEW IndexData(); - IndexData* indexData = s->mLodFaceList[lodNum - 1]; - - unsigned int numIndexes; - readInts(stream, &numIndexes, 1); - indexData->indexCount = static_cast(numIndexes); - - unsigned int offset; - readInts(stream, &offset, 1); - indexData->indexStart = static_cast(offset); - - // For merged buffers, you can pass the index of previous Lod. - // To create buffer it should be -1. - unsigned int bufferIndex; - readInts(stream, &bufferIndex, 1); - if(bufferIndex != (unsigned int)-1) { - // copy buffer pointer - indexData->indexBuffer = s->mLodFaceList[bufferIndex - 1]->indexBuffer; - assert(indexData->indexBuffer); - } else { - // generate buffers - - // bool indexes32Bit - bool idx32Bit; - readBools(stream, &idx32Bit, 1); - - unsigned int buffIndexCount; - readInts(stream, &buffIndexCount, 1); - - indexData->indexBuffer = pMesh->getHardwareBufferManager()->createIndexBuffer( - idx32Bit ? HardwareIndexBuffer::IT_32BIT : HardwareIndexBuffer::IT_16BIT, - buffIndexCount, pMesh->mIndexBufferUsage, pMesh->mIndexBufferShadowBuffer); - HardwareBufferLockGuard ibufLock(indexData->indexBuffer, HardwareBuffer::HBL_DISCARD); - - if (idx32Bit) - { - readInts(stream, (uint32*)ibufLock.pData, buffIndexCount); - } - else - { - readShorts(stream, (uint16*)ibufLock.pData, buffIndexCount); - } - } - } - } -#endif - //--------------------------------------------------------------------- - void MeshSerializerImpl::flipFromLittleEndian(void* pData, size_t vertexCount, - size_t vertexSize, const VertexDeclaration::VertexElementList& elems) - { - if (mFlipEndian) - { - flipEndian(pData, vertexCount, vertexSize, elems); - } - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::flipToLittleEndian(void* pData, size_t vertexCount, - size_t vertexSize, const VertexDeclaration::VertexElementList& elems) - { - if (mFlipEndian) - { - flipEndian(pData, vertexCount, vertexSize, elems); - } - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::flipEndian(void* pData, size_t vertexCount, - size_t vertexSize, const VertexDeclaration::VertexElementList& elems) - { - void *pBase = pData; - for (size_t v = 0; v < vertexCount; ++v) - { - for (auto& e : elems) - { - void *pElem; - // re-base pointer to the element - e.baseVertexPointerToElement(pBase, &pElem); - // Flip the endian based on the type - size_t typeSize = 0; - switch (VertexElement::getBaseType(e.getType())) - { - case VET_FLOAT1: - typeSize = sizeof(float); - break; - case VET_DOUBLE1: - typeSize = sizeof(double); - break; - case VET_SHORT1: - typeSize = sizeof(short); - break; - case VET_USHORT1: - typeSize = sizeof(unsigned short); - break; - case VET_INT1: - typeSize = sizeof(int); - break; - case VET_UINT1: - typeSize = sizeof(unsigned int); - break; - case VET_UBYTE4_NORM: - case VET_UBYTE4: - typeSize = 0; // NO FLIPPING - break; - default: - assert(false); // Should never happen - }; - Bitwise::bswapChunks(pElem, typeSize, - VertexElement::getTypeCount(e.getType())); - } - - pBase = static_cast( - static_cast(pBase) + vertexSize); - } - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl::calcEdgeListSize(const Mesh* pMesh) - { - - size_t size = MSTREAM_OVERHEAD_SIZE; - - for (ushort i = 0; i < exportedLodCount; ++i) - { - - const EdgeData* edgeData = pMesh->getEdgeList(i); - bool isManual = !pMesh->mMeshLodUsageList[i].manualName.empty(); - - size += calcEdgeListLodSize(edgeData, isManual); - - } - - return size; - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl::calcEdgeListLodSize(const EdgeData* edgeData, bool isManual) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - - // unsigned short lodIndex - size += sizeof(uint16); - - // bool isManual // If manual, no edge data here, loaded from manual mesh - size += sizeof(bool); - if (!isManual) - { - // bool isClosed - size += sizeof(bool); - // unsigned long numTriangles - size += sizeof(uint32); - // unsigned long numEdgeGroups - size += sizeof(uint32); - // Triangle* triangleList - size_t triSize = 0; - // unsigned long indexSet - // unsigned long vertexSet - // unsigned long vertIndex[3] - // unsigned long sharedVertIndex[3] - // float normal[4] - triSize += sizeof(uint32) * 8 - + sizeof(float) * 4; - - size += triSize * edgeData->triangles.size(); - // Write the groups - for (const auto & edgeGroup : edgeData->edgeGroups) - { - size += calcEdgeGroupSize(edgeGroup); - } - - } - - return size; - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl::calcEdgeGroupSize(const EdgeData::EdgeGroup& group) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - - // unsigned long vertexSet - size += sizeof(uint32); - // unsigned long triStart - size += sizeof(uint32); - // unsigned long triCount - size += sizeof(uint32); - // unsigned long numEdges - size += sizeof(uint32); - // Edge* edgeList - size_t edgeSize = 0; - // unsigned long triIndex[2] - // unsigned long vertIndex[2] - // unsigned long sharedVertIndex[2] - // bool degenerate - edgeSize += sizeof(uint32) * 6 + sizeof(bool); - size += edgeSize * group.edges.size(); - - return size; - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::writeEdgeList(const Mesh* pMesh) - { - writeChunkHeader(M_EDGE_LISTS, calcEdgeListSize(pMesh)); - pushInnerChunk(mStream); - { - for (ushort i = 0; i < exportedLodCount; ++i) - { - const EdgeData* edgeData = pMesh->getEdgeList(i); - bool isManual = !pMesh->mMeshLodUsageList[i].manualName.empty(); - writeChunkHeader(M_EDGE_LIST_LOD, calcEdgeListLodSize(edgeData, isManual)); - - // unsigned short lodIndex - writeShorts(&i, 1); - - // bool isManual // If manual, no edge data here, loaded from manual mesh - writeBools(&isManual, 1); - if (!isManual) - { - // bool isClosed - writeBools(&edgeData->isClosed, 1); - // unsigned long numTriangles - uint32 count = static_cast(edgeData->triangles.size()); - writeInts(&count, 1); - // unsigned long numEdgeGroups - count = static_cast(edgeData->edgeGroups.size()); - writeInts(&count, 1); - // Triangle* triangleList - // Iterate rather than writing en-masse to allow endian conversion - EdgeData::TriangleFaceNormalList::const_iterator fni = edgeData->triangleFaceNormals.begin(); - for (const auto& tri : edgeData->triangles) - { - // unsigned long indexSet; - uint32 tmp[3]; - tmp[0] = static_cast(tri.indexSet); - writeInts(tmp, 1); - // unsigned long vertexSet; - tmp[0] = static_cast(tri.vertexSet); - writeInts(tmp, 1); - // unsigned long vertIndex[3]; - tmp[0] = static_cast(tri.vertIndex[0]); - tmp[1] = static_cast(tri.vertIndex[1]); - tmp[2] = static_cast(tri.vertIndex[2]); - writeInts(tmp, 3); - // unsigned long sharedVertIndex[3]; - tmp[0] = static_cast(tri.sharedVertIndex[0]); - tmp[1] = static_cast(tri.sharedVertIndex[1]); - tmp[2] = static_cast(tri.sharedVertIndex[2]); - writeInts(tmp, 3); - // float normal[4]; - writeFloats(&(fni->x), 4); - - ++fni; - } - pushInnerChunk(mStream); - { - // Write the groups - for (const auto& edgeGroup : edgeData->edgeGroups) - { - writeChunkHeader(M_EDGE_GROUP, calcEdgeGroupSize(edgeGroup)); - // unsigned long vertexSet - uint32 vertexSet = static_cast(edgeGroup.vertexSet); - writeInts(&vertexSet, 1); - // unsigned long triStart - uint32 triStart = static_cast(edgeGroup.triStart); - writeInts(&triStart, 1); - // unsigned long triCount - uint32 triCount = static_cast(edgeGroup.triCount); - writeInts(&triCount, 1); - // unsigned long numEdges - count = static_cast(edgeGroup.edges.size()); - writeInts(&count, 1); - // Edge* edgeList - // Iterate rather than writing en-masse to allow endian conversion - for (const auto & edge : edgeGroup.edges) - { - uint32 tmp[2]; - // unsigned long triIndex[2] - tmp[0] = static_cast(edge.triIndex[0]); - tmp[1] = static_cast(edge.triIndex[1]); - writeInts(tmp, 2); - // unsigned long vertIndex[2] - tmp[0] = static_cast(edge.vertIndex[0]); - tmp[1] = static_cast(edge.vertIndex[1]); - writeInts(tmp, 2); - // unsigned long sharedVertIndex[2] - tmp[0] = static_cast(edge.sharedVertIndex[0]); - tmp[1] = static_cast(edge.sharedVertIndex[1]); - writeInts(tmp, 2); - // bool degenerate - writeBools(&(edge.degenerate), 1); - } - - } - } - popInnerChunk(mStream); - } - } - } - popInnerChunk(mStream); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readEdgeList(const DataStreamPtr& stream, Mesh* pMesh) - { - if (!stream->eof()) - { - pushInnerChunk(stream); - unsigned short streamID = readChunk(stream); - while(!stream->eof() && - streamID == M_EDGE_LIST_LOD) - { - // Process single LOD - - // unsigned short lodIndex - unsigned short lodIndex; - readShorts(stream, &lodIndex, 1); - - // bool isManual // If manual, no edge data here, loaded from manual mesh - bool isManual; - readBools(stream, &isManual, 1); - // Only load in non-manual levels; others will be connected up by Mesh on demand -#if OGRE_NO_MESHLOD - // - if (!isManual) - if (lodIndex != 0) { - readEdgeListLodInfo(stream, NULL); - } else { -#else - if (!isManual) { -#endif - MeshLodUsage& usage = pMesh->mMeshLodUsageList[lodIndex]; - - usage.edgeData = OGRE_NEW EdgeData(); - - // Read detail information of the edge list - readEdgeListLodInfo(stream, usage.edgeData); - - // Postprocessing edge groups - for (auto& edgeGroup : usage.edgeData->edgeGroups) - { - // Populate edgeGroup.vertexData pointers - // If there is shared vertex data, vertexSet 0 is that, - // otherwise 0 is first dedicated - if (pMesh->sharedVertexData) - { - if (edgeGroup.vertexSet == 0) - { - edgeGroup.vertexData = pMesh->sharedVertexData; - } - else - { - edgeGroup.vertexData = pMesh->getSubMesh( - (unsigned short)edgeGroup.vertexSet-1)->vertexData; - } - } - else - { - edgeGroup.vertexData = pMesh->getSubMesh( - (unsigned short)edgeGroup.vertexSet)->vertexData; - } - } - } - - if (!stream->eof()) - { - streamID = readChunk(stream); - } - - } - if (!stream->eof()) - { - // Backpedal back to start of stream - backpedalChunkHeader(stream); - } - popInnerChunk(stream); - } - - pMesh->mEdgeListsBuilt = true; - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readEdgeListLodInfo(const DataStreamPtr& stream, - EdgeData* edgeData) - { -#if OGRE_NO_MESHLOD - if (edgeData == NULL) { // skip it! - bool isClosed; - readBools(stream, &isClosed, 1); - // unsigned long numTriangles - uint32 numTriangles; - readInts(stream, &numTriangles, 1); - // unsigned long numEdgeGroups - uint32 numEdgeGroups; - readInts(stream, &numEdgeGroups, 1); - stream->skip(numTriangles * (8 * sizeof(uint32) + 4 * sizeof(float))); - pushInnerChunk(stream); - for (uint32 eg = 0; eg < numEdgeGroups; ++eg) - { - unsigned short streamID = readChunk(stream); - if (streamID != M_EDGE_GROUP) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Missing M_EDGE_GROUP stream", - "MeshSerializerImpl::readEdgeListLodInfo"); - } - uint32 tmp[3]; - // unsigned long vertexSet - readInts(stream, &tmp[0], 3); - uint32 numEdges; - readInts(stream, &numEdges, 1); - - stream->skip(numEdges * (6 * sizeof(uint32) + sizeof(bool))); - } - popInnerChunk(stream); - return; - } -#endif - // bool isClosed - readBools(stream, &edgeData->isClosed, 1); - // unsigned long numTriangles - uint32 numTriangles; - readInts(stream, &numTriangles, 1); - // Allocate correct amount of memory - edgeData->triangles.resize(numTriangles); - edgeData->triangleFaceNormals.resize(numTriangles); - edgeData->triangleLightFacings.resize(numTriangles); - // unsigned long numEdgeGroups - uint32 numEdgeGroups; - readInts(stream, &numEdgeGroups, 1); - // Allocate correct amount of memory - edgeData->edgeGroups.resize(numEdgeGroups); - // Triangle* triangleList - uint32 tmp[3]; - for (size_t t = 0; t < numTriangles; ++t) - { - EdgeData::Triangle& tri = edgeData->triangles[t]; - // unsigned long indexSet - readInts(stream, tmp, 1); - tri.indexSet = tmp[0]; - // unsigned long vertexSet - readInts(stream, tmp, 1); - tri.vertexSet = tmp[0]; - // unsigned long vertIndex[3] - readInts(stream, tmp, 3); - - tri.vertIndex[0] = tmp[0]; - tri.vertIndex[1] = tmp[1]; - tri.vertIndex[2] = tmp[2]; - // unsigned long sharedVertIndex[3] - readInts(stream, tmp, 3); - tri.sharedVertIndex[0] = tmp[0]; - tri.sharedVertIndex[1] = tmp[1]; - tri.sharedVertIndex[2] = tmp[2]; - // float normal[4] - readFloats(stream, &(edgeData->triangleFaceNormals[t].x), 4); - - } - pushInnerChunk(stream); - for (uint32 eg = 0; eg < numEdgeGroups; ++eg) - { - unsigned short streamID = readChunk(stream); - if (streamID != M_EDGE_GROUP) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Missing M_EDGE_GROUP stream", - "MeshSerializerImpl::readEdgeListLodInfo"); - } - EdgeData::EdgeGroup& edgeGroup = edgeData->edgeGroups[eg]; - - // unsigned long vertexSet - readInts(stream, tmp, 1); - edgeGroup.vertexSet = tmp[0]; - // unsigned long triStart - readInts(stream, tmp, 1); - edgeGroup.triStart = tmp[0]; - // unsigned long triCount - readInts(stream, tmp, 1); - edgeGroup.triCount = tmp[0]; - // unsigned long numEdges - uint32 numEdges; - readInts(stream, &numEdges, 1); - edgeGroup.edges.resize(numEdges); - // Edge* edgeList - for (uint32 e = 0; e < numEdges; ++e) - { - EdgeData::Edge& edge = edgeGroup.edges[e]; - // unsigned long triIndex[2] - readInts(stream, tmp, 2); - edge.triIndex[0] = tmp[0]; - edge.triIndex[1] = tmp[1]; - // unsigned long vertIndex[2] - readInts(stream, tmp, 2); - edge.vertIndex[0] = tmp[0]; - edge.vertIndex[1] = tmp[1]; - // unsigned long sharedVertIndex[2] - readInts(stream, tmp, 2); - edge.sharedVertIndex[0] = tmp[0]; - edge.sharedVertIndex[1] = tmp[1]; - // bool degenerate - readBools(stream, &(edge.degenerate), 1); - } - } - popInnerChunk(stream); - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl::calcAnimationsSize(const Mesh* pMesh) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - - for (unsigned short a = 0; a < pMesh->getNumAnimations(); ++a) - { - Animation* anim = pMesh->getAnimation(a); - size += calcAnimationSize(anim); - } - return size; - - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl::calcAnimationSize(const Animation* anim) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - size += calcStringSize(anim->getName()); - - // float length - size += sizeof(float); - - for (const auto& trackIt : anim->_getVertexTrackList()) - { - size += calcAnimationTrackSize(trackIt.second); - } - - return size; - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl::calcAnimationTrackSize(const VertexAnimationTrack* track) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - // uint16 type - size += sizeof(uint16); - // unsigned short target // 0 for shared geometry, - size += sizeof(unsigned short); - - if (track->getAnimationType() == VAT_MORPH) - { - for (unsigned short i = 0; i < track->getNumKeyFrames(); ++i) - { - VertexMorphKeyFrame* kf = track->getVertexMorphKeyFrame(i); - size += calcMorphKeyframeSize(kf, track->getAssociatedVertexData()->vertexCount); - } - } - else - { - for (unsigned short i = 0; i < track->getNumKeyFrames(); ++i) - { - VertexPoseKeyFrame* kf = track->getVertexPoseKeyFrame(i); - size += calcPoseKeyframeSize(kf); - } - } - return size; - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl::calcMorphKeyframeSize(const VertexMorphKeyFrame* kf, - size_t vertexCount) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - // float time - size += sizeof(float); - // float x,y,z[,nx,ny,nz] - bool includesNormals = kf->getVertexBuffer()->getVertexSize() > (sizeof(float) * 3); - size += sizeof(float) * (includesNormals ? 6 : 3) * vertexCount; - - return size; - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl::calcPoseKeyframeSize(const VertexPoseKeyFrame* kf) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - - // float time - size += sizeof(float); - - size += calcPoseKeyframePoseRefSize() * kf->getPoseReferences().size(); - - return size; - - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl::calcPoseKeyframePoseRefSize(void) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - // unsigned short poseIndex - size += sizeof(uint16); - // float influence - size += sizeof(float); - - return size; - - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl::calcPosesSize(const Mesh* pMesh) - { - size_t size = 0; - - if (!pMesh->getPoseList().empty()) - { - size += MSTREAM_OVERHEAD_SIZE; - for (auto& p : pMesh->getPoseList()) - { - size += calcPoseSize(p); - } - } - return size; - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl::calcPoseSize(const Pose* pose) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - - size += calcStringSize(pose->getName()); - // unsigned short target - size += sizeof(uint16); - // bool includesNormals - size += sizeof(bool); - - // vertex offsets - size += pose->getVertexOffsets().size() * calcPoseVertexSize(pose); - - return size; - - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl::calcPoseVertexSize(const Pose* pose) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - // unsigned long vertexIndex - size += sizeof(uint32); - // float xoffset, yoffset, zoffset - size += sizeof(float) * 3; - // optional normals - if (!pose->getNormals().empty()) - size += sizeof(float) * 3; - - return size; - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::writePoses(const Mesh* pMesh) - { - if (!pMesh->getPoseList().empty()) - { - writeChunkHeader(M_POSES, calcPosesSize(pMesh)); - pushInnerChunk(mStream); - for(auto& p : pMesh->getPoseList()) - { - writePose(p); - } - popInnerChunk(mStream); - } - - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::writePose(const Pose* pose) - { - writeChunkHeader(M_POSE, calcPoseSize(pose)); - - // char* name (may be blank) - writeString(pose->getName()); - - // unsigned short target - ushort val = pose->getTarget(); - writeShorts(&val, 1); - - // bool includesNormals - bool includesNormals = !pose->getNormals().empty(); - writeBools(&includesNormals, 1); - pushInnerChunk(mStream); - { - size_t vertexSize = calcPoseVertexSize(pose); - auto nit = pose->getNormals().begin(); - for (const auto& it : pose->getVertexOffsets()) - { - uint32 vertexIndex = (uint32)it.first; - writeChunkHeader(M_POSE_VERTEX, vertexSize); - // unsigned long vertexIndex - writeInts(&vertexIndex, 1); - // float xoffset, yoffset, zoffset - writeFloats(it.second.ptr(), 3); - if (includesNormals) - { - // float xnormal, ynormal, znormal - writeFloats(nit->second.ptr(), 3); - nit++; - } - } - } - popInnerChunk(mStream); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::writeAnimations(const Mesh* pMesh) - { - writeChunkHeader(M_ANIMATIONS, calcAnimationsSize(pMesh)); - pushInnerChunk(mStream); - for (unsigned short a = 0; a < pMesh->getNumAnimations(); ++a) - { - Animation* anim = pMesh->getAnimation(a); - LogManager::getSingleton().logMessage("Exporting animation " + anim->getName()); - writeAnimation(anim); - LogManager::getSingleton().logMessage("Animation exported."); - } - popInnerChunk(mStream); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::writeAnimation(const Animation* anim) - { - writeChunkHeader(M_ANIMATION, calcAnimationSize(anim)); - // char* name - writeString(anim->getName()); - // float length - float len = anim->getLength(); - writeFloats(&len, 1); - pushInnerChunk(mStream); - if (anim->getUseBaseKeyFrame()) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - size += calcStringSize(anim->getBaseKeyFrameAnimationName()); - // float baseKeyFrameTime - size += sizeof(float); - - writeChunkHeader(M_ANIMATION_BASEINFO, size); - - // char* baseAnimationName (blank for self) - writeString(anim->getBaseKeyFrameAnimationName()); - - // float baseKeyFrameTime - float t = (float)anim->getBaseKeyFrameTime(); - writeFloats(&t, 1); - } - - // tracks - for (const auto& trackIt : anim->_getVertexTrackList()) - { - writeAnimationTrack(trackIt.second); - } - popInnerChunk(mStream); - - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::writeAnimationTrack(const VertexAnimationTrack* track) - { - writeChunkHeader(M_ANIMATION_TRACK, calcAnimationTrackSize(track)); - // unsigned short type // 1 == morph, 2 == pose - uint16 animType = (uint16)track->getAnimationType(); - writeShorts(&animType, 1); - // unsigned short target - uint16 target = track->getHandle(); - writeShorts(&target, 1); - pushInnerChunk(mStream); - { - if (track->getAnimationType() == VAT_MORPH) - { - for (unsigned short i = 0; i < track->getNumKeyFrames(); ++i) - { - VertexMorphKeyFrame* kf = track->getVertexMorphKeyFrame(i); - writeMorphKeyframe(kf, track->getAssociatedVertexData()->vertexCount); - } - } - else // VAT_POSE - { - for (unsigned short i = 0; i < track->getNumKeyFrames(); ++i) - { - VertexPoseKeyFrame* kf = track->getVertexPoseKeyFrame(i); - writePoseKeyframe(kf); - } - } - } - popInnerChunk(mStream); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::writeMorphKeyframe(const VertexMorphKeyFrame* kf, size_t vertexCount) - { - writeChunkHeader(M_ANIMATION_MORPH_KEYFRAME, calcMorphKeyframeSize(kf, vertexCount)); - // float time - float timePos = kf->getTime(); - writeFloats(&timePos, 1); - // bool includeNormals - bool includeNormals = kf->getVertexBuffer()->getVertexSize() > (sizeof(float) * 3); - writeBools(&includeNormals, 1); - // float x,y,z // repeat by number of vertices in original geometry - HardwareBufferLockGuard vbufLock(kf->getVertexBuffer(), HardwareBuffer::HBL_READ_ONLY); - writeFloats(static_cast(vbufLock.pData), vertexCount * (includeNormals ? 6 : 3)); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::writePoseKeyframe(const VertexPoseKeyFrame* kf) - { - writeChunkHeader(M_ANIMATION_POSE_KEYFRAME, calcPoseKeyframeSize(kf)); - // float time - float timePos = kf->getTime(); - writeFloats(&timePos, 1); - pushInnerChunk(mStream); - // pose references - for (auto& p : kf->getPoseReferences()) - { - writePoseKeyframePoseRef(p); - } - popInnerChunk(mStream); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::writePoseKeyframePoseRef( - const VertexPoseKeyFrame::PoseRef& poseRef) - { - writeChunkHeader(M_ANIMATION_POSE_REF, calcPoseKeyframePoseRefSize()); - // unsigned short poseIndex - writeShorts(&(poseRef.poseIndex), 1); - // float influence - writeFloats(&(poseRef.influence), 1); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readPoses(const DataStreamPtr& stream, Mesh* pMesh) - { - // Find all substreams - if (!stream->eof()) - { - pushInnerChunk(stream); - unsigned short streamID = readChunk(stream); - while(!stream->eof() && - (streamID == M_POSE)) - { - switch(streamID) - { - case M_POSE: - readPose(stream, pMesh); - break; - - } - - if (!stream->eof()) - { - streamID = readChunk(stream); - } - - } - if (!stream->eof()) - { - // Backpedal back to start of stream - backpedalChunkHeader(stream); - } - popInnerChunk(stream); - } - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readPose(const DataStreamPtr& stream, Mesh* pMesh) - { - // char* name (may be blank) - String name = readString(stream); - // unsigned short target - unsigned short target; - readShorts(stream, &target, 1); - - // bool includesNormals - bool includesNormals; - readBools(stream, &includesNormals, 1); - - Pose* pose = pMesh->createPose(target, name); - - // Find all substreams - if (!stream->eof()) - { - pushInnerChunk(stream); - unsigned short streamID = readChunk(stream); - while(!stream->eof() && - (streamID == M_POSE_VERTEX)) - { - switch(streamID) - { - case M_POSE_VERTEX: - // create vertex offset - uint32 vertIndex; - Vector3f offset, normal; - // unsigned long vertexIndex - readInts(stream, &vertIndex, 1); - // float xoffset, yoffset, zoffset - readFloats(stream, offset.ptr(), 3); - - if (includesNormals) - { - readFloats(stream, normal.ptr(), 3); - pose->addVertex(vertIndex, offset, normal); - } - else - { - pose->addVertex(vertIndex, offset); - } - - - break; - - } - - if (!stream->eof()) - { - streamID = readChunk(stream); - } - - } - if (!stream->eof()) - { - // Backpedal back to start of stream - backpedalChunkHeader(stream); - } - popInnerChunk(stream); - } - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readAnimations(const DataStreamPtr& stream, Mesh* pMesh) - { - // Find all substreams - if (!stream->eof()) - { - pushInnerChunk(stream); - unsigned short streamID = readChunk(stream); - while(!stream->eof() && - (streamID == M_ANIMATION)) - { - switch(streamID) - { - case M_ANIMATION: - readAnimation(stream, pMesh); - break; - - } - - if (!stream->eof()) - { - streamID = readChunk(stream); - } - - } - if (!stream->eof()) - { - // Backpedal back to start of stream - backpedalChunkHeader(stream); - } - popInnerChunk(stream); - } - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readAnimation(const DataStreamPtr& stream, Mesh* pMesh) - { - // char* name - String name = readString(stream); - // float length - float len; - readFloats(stream, &len, 1); - - Animation* anim = pMesh->createAnimation(name, len); - - // tracks - if (!stream->eof()) - { - pushInnerChunk(stream); - unsigned short streamID = readChunk(stream); - - // Optional base info is possible - if (streamID == M_ANIMATION_BASEINFO) - { - // char baseAnimationName - String baseAnimName = readString(stream); - // float baseKeyFrameTime - float baseKeyTime; - readFloats(stream, &baseKeyTime, 1); - - anim->setUseBaseKeyFrame(true, baseKeyTime, baseAnimName); - - if (!stream->eof()) - { - // Get next stream - streamID = readChunk(stream); - } - } - - while(!stream->eof() && - streamID == M_ANIMATION_TRACK) - { - switch(streamID) - { - case M_ANIMATION_TRACK: - readAnimationTrack(stream, anim, pMesh); - break; - }; - if (!stream->eof()) - { - streamID = readChunk(stream); - } - - } - if (!stream->eof()) - { - // Backpedal back to start of stream - backpedalChunkHeader(stream); - } - popInnerChunk(stream); - } - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readAnimationTrack(const DataStreamPtr& stream, - Animation* anim, Mesh* pMesh) - { - // ushort type - uint16 inAnimType; - readShorts(stream, &inAnimType, 1); - VertexAnimationType animType = (VertexAnimationType)inAnimType; - - // unsigned short target - uint16 target; - readShorts(stream, &target, 1); - - VertexAnimationTrack* track = anim->createVertexTrack(target, - pMesh->getVertexDataByTrackHandle(target), animType); - - // keyframes - if (!stream->eof()) - { - pushInnerChunk(stream); - unsigned short streamID = readChunk(stream); - while(!stream->eof() && - (streamID == M_ANIMATION_MORPH_KEYFRAME || - streamID == M_ANIMATION_POSE_KEYFRAME)) - { - switch(streamID) - { - case M_ANIMATION_MORPH_KEYFRAME: - readMorphKeyFrame(stream, pMesh, track); - break; - case M_ANIMATION_POSE_KEYFRAME: - readPoseKeyFrame(stream, track); - break; - }; - if (!stream->eof()) - { - streamID = readChunk(stream); - } - - } - if (!stream->eof()) - { - // Backpedal back to start of stream - backpedalChunkHeader(stream); - } - popInnerChunk(stream); - } - - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readMorphKeyFrame(const DataStreamPtr& stream, Mesh* pMesh, VertexAnimationTrack* track) - { - // float time - float timePos; - readFloats(stream, &timePos, 1); - - // bool includesNormals - bool includesNormals; - readBools(stream, &includesNormals, 1); - - VertexMorphKeyFrame* kf = track->createVertexMorphKeyFrame(timePos); - - // Create buffer, allow read and use shadow buffer - size_t vertexCount = track->getAssociatedVertexData()->vertexCount; - size_t vertexSize = sizeof(float) * (includesNormals ? 6 : 3); - HardwareVertexBufferSharedPtr vbuf = - pMesh->getHardwareBufferManager()->createVertexBuffer( - vertexSize, vertexCount, - HardwareBuffer::HBU_STATIC, true); - // float x,y,z // repeat by number of vertices in original geometry - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - readFloats(stream, static_cast(vbufLock.pData), vertexCount * (includesNormals ? 6 : 3)); - kf->setVertexBuffer(vbuf); - - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readPoseKeyFrame(const DataStreamPtr& stream, VertexAnimationTrack* track) - { - // float time - float timePos; - readFloats(stream, &timePos, 1); - - // Create keyframe - VertexPoseKeyFrame* kf = track->createVertexPoseKeyFrame(timePos); - - if (!stream->eof()) - { - pushInnerChunk(stream); - unsigned short streamID = readChunk(stream); - while(!stream->eof() && - streamID == M_ANIMATION_POSE_REF) - { - switch(streamID) - { - case M_ANIMATION_POSE_REF: - uint16 poseIndex; - float influence; - // unsigned short poseIndex - readShorts(stream, &poseIndex, 1); - // float influence - readFloats(stream, &influence, 1); - - kf->addPoseReference(poseIndex, influence); - - break; - }; - if (!stream->eof()) - { - streamID = readChunk(stream); - } - } - if (!stream->eof()) - { - // Backpedal back to start of stream - backpedalChunkHeader(stream); - } - popInnerChunk(stream); - } - } - //--------------------------------------------------------------------- - void MeshSerializerImpl::readExtremes(const DataStreamPtr& stream, Mesh *pMesh) - { - unsigned short idx; - readShorts(stream, &idx, 1); - - SubMesh *sm = pMesh->getSubMesh (idx); - - int n_floats = (mCurrentstreamLen - MSTREAM_OVERHEAD_SIZE - - sizeof (unsigned short)) / sizeof (float); - - assert ((n_floats % 3) == 0); - - sm->extremityPoints.resize(n_floats / 3); - - readFloats(stream, sm->extremityPoints.front().ptr(), n_floats); - } - - void MeshSerializerImpl::enableValidation() - { -#if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE - mReportChunkErrors = true; -#endif - } - - - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - MeshSerializerImpl_v1_8::MeshSerializerImpl_v1_8() - { - // Version number - mVersion = "[MeshSerializer_v1.8]"; - } - //--------------------------------------------------------------------- - MeshSerializerImpl_v1_8::~MeshSerializerImpl_v1_8() - { - } - //-------------------------------------------------------------------- - String MeshSerializerImpl_v1_8::compatibleLodStrategyName(String strategyName) - { - if(strategyName == "distance_box" || strategyName == "distance_sphere") - strategyName = "Distance"; - else if(strategyName == "pixel_count" || strategyName == "screen_ratio_pixel_count") - strategyName = "PixelCount"; - return strategyName; - } - //-------------------------------------------------------------------- - bool MeshSerializerImpl_v1_8::isLodMixed(const Mesh* pMesh) - { - if(!pMesh->hasManualLodLevel()) { - return false; - } - - unsigned short numLods = pMesh->getNumLodLevels(); - for (unsigned short i = 1; i < numLods; ++i) - { - if(!pMesh->_isManualLodLevel(i)){ - return true; - } - } - - return false; - } - size_t MeshSerializerImpl_v1_8::calcLodLevelSize(const Mesh* pMesh) - { - if (isLodMixed(pMesh)) { - return 0; // Supported in v1_9+ - } - exportedLodCount = pMesh->getNumLodLevels(); - size_t size = MSTREAM_OVERHEAD_SIZE; // Header - size += calcStringSize(compatibleLodStrategyName(pMesh->getLodStrategy()->getName())); // string strategyName; - size += sizeof(unsigned short); // unsigned short numLevels; - size += sizeof(bool); // bool manual; <== this is removed in v1_9 - - // Loop from LOD 1 (not 0, this is full detail) - for (ushort i = 1; i < exportedLodCount; ++i) - { - const MeshLodUsage& usage = pMesh->mMeshLodUsageList[i]; - if (pMesh->_isManualLodLevel(i)) - { - size += calcLodUsageManualSize(usage); - } - else - { - size += calcLodUsageGeneratedSize(pMesh, usage, i); - } - } - return size; - } - size_t MeshSerializerImpl_v1_8::calcLodUsageManualSize(const MeshLodUsage& usage) - { - // Header - size_t size = MSTREAM_OVERHEAD_SIZE; // M_MESH_LOD_USAGE <== this is removed in v1_9 - - // float fromDepthSquared; - size += sizeof(float); - - // Manual part size - size += MSTREAM_OVERHEAD_SIZE; // M_MESH_LOD_MANUAL - // String manualMeshName; - size += calcStringSize(usage.manualName); - return size; - } - - size_t MeshSerializerImpl_v1_8::calcLodUsageGeneratedSize(const Mesh* pMesh, const MeshLodUsage& usage, unsigned short lodNum) - { - // Usage Header - size_t size = MSTREAM_OVERHEAD_SIZE; - // float fromDepthSquared; - size += sizeof(float); - - // Calc generated SubMesh sections size - for (auto& s : pMesh->getSubMeshes()) - { - size += calcLodUsageGeneratedSubmeshSize(s, lodNum); - } - return size; - } - size_t MeshSerializerImpl_v1_8::calcLodUsageGeneratedSubmeshSize(const SubMesh* submesh, unsigned short lodNum) - { - const IndexData* indexData = submesh->mLodFaceList[lodNum - 1]; - const HardwareIndexBufferSharedPtr& ibuf = indexData->indexBuffer; - - size_t size = MSTREAM_OVERHEAD_SIZE; // M_MESH_LOD_GENERATED - size += sizeof(unsigned int); // unsigned int indexData->indexCount; - size += sizeof(bool); // bool indexes32Bit - size += !ibuf ? 0 : ibuf->getIndexSize() * indexData->indexCount; // faces - return size; - } -#if !OGRE_NO_MESHLOD - //-------------------------------------------------------------------- - void MeshSerializerImpl_v1_8::writeLodLevel(const Mesh* pMesh) - { - if (isLodMixed(pMesh)) { - LogManager::getSingleton().logMessage("MeshSerializer_v1_8 older mesh format is incompatible with mixed manual/generated Lod levels. Lod levels will not be exported."); - } else { - - exportedLodCount = pMesh->getNumLodLevels(); - bool manual = pMesh->hasManualLodLevel(); - - writeChunkHeader(M_MESH_LOD_LEVEL, calcLodLevelSize(pMesh)); - - // string strategyName; - writeString(compatibleLodStrategyName(pMesh->getLodStrategy()->getName())); - // unsigned short numLevels; - writeShorts(&exportedLodCount, 1); - // bool manual; (true for manual alternate meshes, false for generated) - writeBools(&manual, 1); - - pushInnerChunk(mStream); - // Loop from LOD 1 (not 0, this is full detail) - for (ushort i = 1; i < exportedLodCount; ++i) - { - const MeshLodUsage& usage = pMesh->mMeshLodUsageList[i]; - assert(pMesh->_isManualLodLevel(i) == manual); - if (manual) - { - writeLodUsageManual(usage); - } - else - { - writeLodUsageGenerated(pMesh, usage, i); - } - } - popInnerChunk(mStream); - } - } - //--------------------------------------------------------------------- - /*void MeshSerializerImpl_v1_8::writeLodUsageGenerated( const Mesh* pMesh, const MeshLodUsage& usage, unsigned short lodNum ) - { - writeChunkHeader(M_MESH_LOD_USAGE, calcLodUsageGeneratedSize(pMesh, usage, lodNum)); - writeFloats(&(usage.userValue), 1); - pushInnerChunk(mStream); - // Now write sections - for (unsigned short subidx = 0; subidx < pMesh->getNumSubMeshes(); ++subidx) - { - SubMesh* sm = pMesh->getSubMesh(subidx); - const IndexData* indexData = sm->mLodFaceList[lodNum-1]; - - // Lock index buffer to write - HardwareIndexBufferSharedPtr ibuf = indexData->indexBuffer; - - bool idx32 = (ibuf && ibuf->getType() == HardwareIndexBuffer::IT_32BIT); - - writeChunkHeader(M_MESH_LOD_GENERATED, calcLodUsageGeneratedSubmeshSize(sm, lodNum)); - unsigned int idxCount = static_cast(indexData->indexCount); - writeInts(&idxCount, 1); - writeBools(&idx32, 1); - - if (idxCount > 0) - { - HardwareBufferLockGuard ibufLock(ibuf, HardwareBuffer::HBL_READ_ONLY); - if (idx32) - { - unsigned int* pIdx = static_cast(ibufLock.pData); - writeInts(pIdx + indexData->indexStart, indexData->indexCount); - } - else - { - unsigned short* pIdx = static_cast(ibufLock.pData); - writeShorts(pIdx + indexData->indexStart, indexData->indexCount); - } - } - } - popInnerChunk(mStream); - }*/ - - void MeshSerializerImpl_v1_8::writeLodUsageGenerated(const Mesh* pMesh, const MeshLodUsage& usage, unsigned short lodNum) - { - writeChunkHeader(M_MESH_LOD_USAGE, calcLodUsageGeneratedSize(pMesh, usage, lodNum)); - float userValue = static_cast(usage.userValue); - writeFloats(&userValue, 1); - pushInnerChunk(mStream); - for (auto& s : pMesh->getSubMeshes()) - { - writeLodUsageGeneratedSubmesh(s, lodNum); - } - popInnerChunk(mStream); - } - void MeshSerializerImpl_v1_8::writeLodUsageGeneratedSubmesh(const SubMesh* submesh, unsigned short lodNum) - { - const IndexData* indexData = submesh->mLodFaceList[lodNum - 1]; - HardwareIndexBufferSharedPtr ibuf = indexData->indexBuffer; - assert(ibuf); - - writeChunkHeader(M_MESH_LOD_GENERATED, calcLodUsageGeneratedSubmeshSize(submesh, lodNum)); - unsigned int indexCount = static_cast(indexData->indexCount); - writeInts(&indexCount, 1); - bool is32BitIndices = (ibuf->getType() == HardwareIndexBuffer::IT_32BIT); - writeBools(&is32BitIndices, 1); - - HardwareBufferLockGuard ibufLock(ibuf, HardwareBuffer::HBL_READ_ONLY); - if (is32BitIndices) - { - unsigned int* pIdx = static_cast(ibufLock.pData); - writeInts(pIdx + indexData->indexStart, indexCount); - } - else - { - unsigned short* pIdx = static_cast(ibufLock.pData); - writeShorts(pIdx + indexData->indexStart, indexCount); - } - } - //--------------------------------------------------------------------- - void MeshSerializerImpl_v1_8::writeLodUsageManual(const MeshLodUsage& usage) - { - writeChunkHeader(M_MESH_LOD_USAGE, calcLodUsageManualSize(usage)); - writeFloats(&(usage.userValue), 1); - pushInnerChunk(mStream); - writeChunkHeader(M_MESH_LOD_MANUAL, MSTREAM_OVERHEAD_SIZE + calcStringSize(usage.manualName)); - writeString(usage.manualName); - popInnerChunk(mStream); - } - //--------------------------------------------------------------------- - - void MeshSerializerImpl_v1_8::readMeshLodUsageGenerated( const DataStreamPtr& stream, Mesh* pMesh, unsigned short lodNum, MeshLodUsage& usage ) - { - usage.manualName = ""; - usage.manualMesh.reset(); - pushInnerChunk(stream); - { - // Get one set of detail per SubMesh - for (auto *sm : pMesh->getSubMeshes()) - { - unsigned long streamID = readChunk(stream); - if (streamID != M_MESH_LOD_GENERATED) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Missing M_MESH_LOD_GENERATED stream in " + pMesh->getName(), - "MeshSerializerImpl::readMeshLodUsageGenerated"); - } - - IndexData* indexData = OGRE_NEW IndexData(); - sm->mLodFaceList[lodNum - 1] = indexData; - unsigned int numIndexes; - readInts(stream, &numIndexes, 1); - indexData->indexCount = static_cast(numIndexes); - bool idx32Bit; - readBools(stream, &idx32Bit, 1); - - if (idx32Bit) - { - indexData->indexBuffer = pMesh->getHardwareBufferManager()->createIndexBuffer( - HardwareIndexBuffer::IT_32BIT, indexData->indexCount, - pMesh->mIndexBufferUsage, pMesh->mIndexBufferShadowBuffer); - HardwareBufferLockGuard ibufLock(indexData->indexBuffer, HardwareBuffer::HBL_DISCARD); - readInts(stream, static_cast(ibufLock.pData), indexData->indexCount); - } - else - { - indexData->indexBuffer = pMesh->getHardwareBufferManager()->createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, indexData->indexCount, - pMesh->mIndexBufferUsage, pMesh->mIndexBufferShadowBuffer); - HardwareBufferLockGuard ibufLock(indexData->indexBuffer, HardwareBuffer::HBL_DISCARD); - readShorts(stream, static_cast(ibufLock.pData), indexData->indexCount); - } - } - } - popInnerChunk(stream); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl_v1_8::readMeshLodUsageManual(const DataStreamPtr& stream, - Mesh* pMesh, unsigned short lodNum, MeshLodUsage& usage) - { - pushInnerChunk(stream); - unsigned long streamID; - // Read detail stream - streamID = readChunk(stream); - if (streamID != M_MESH_LOD_MANUAL) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Missing M_MESH_LOD_MANUAL stream in " + pMesh->getName(), - "MeshSerializerImpl::readMeshLodUsageManual"); - } - - usage.manualName = readString(stream); - usage.manualMesh.reset(); // will trigger load later - popInnerChunk(stream); - } - -#endif - void MeshSerializerImpl_v1_8::readMeshLodLevel(const DataStreamPtr& stream, Mesh* pMesh) - { -#if OGRE_NO_MESHLOD - - /* - //Since the chunk sizes in old versions are messed up, we can't use this clean solution. - // We need to walk through the data to not rely on the chunk size! - stream->skip(mCurrentstreamLen); - - // Since we got here, we have already read the chunk header. - backpedalChunkHeader(stream); - */ - uint16 numSubs = pMesh->getNumSubMeshes(); - String strategyName = readString(stream); - uint16 numLods; - readShorts(stream, &numLods, 1); - bool manual; - readBools(stream, &manual, 1); // missing in v1_9 - pushInnerChunk(stream); - for (uint16 i = 1; i < numLods; ++i) - { - uint16 streamID = readChunk(stream); - if (streamID != M_MESH_LOD_USAGE) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Missing M_MESH_LOD_USAGE stream in " + pMesh->getName(), - "MeshSerializerImpl::readMeshLodInfo"); - } - float usageValue; - readFloats(stream, &usageValue, 1); - - if (manual) - { - // Read detail stream - streamID = readChunk(stream); - if (streamID != M_MESH_LOD_MANUAL) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Missing M_MESH_LOD_MANUAL stream in " + pMesh->getName(), - "MeshSerializerImpl::readMeshLodUsageManual"); - } - - String manualName = readString(stream); - } - else - { - pushInnerChunk(stream); - for (uint16 n = 0; n < numSubs; ++n) - { - streamID = readChunk(stream); - if (streamID != M_MESH_LOD_GENERATED) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Missing M_MESH_LOD_GENERATED stream in " + pMesh->getName(), - "MeshSerializerImpl::readMeshLodUsageGenerated"); - } - - unsigned int numIndexes; - readInts(stream, &numIndexes, 1); - - bool idx32Bit; - readBools(stream, &idx32Bit, 1); - - size_t buffSize = numIndexes * (idx32Bit ? 4 : 2); - stream->skip(buffSize); - } - popInnerChunk(stream); - } - } - popInnerChunk(stream); -#else - unsigned short streamID, i; - - // Read the strategy to be used for this mesh - String strategyName = readString(stream); - LodStrategy *strategy = LodStrategyManager::getSingleton().getStrategy(strategyName); - - if (strategy) - pMesh->setLodStrategy(strategy); - - // unsigned short numLevels; - readShorts(stream, &(pMesh->mNumLods), 1); - // bool manual; (true for manual alternate meshes, false for generated) - readBools(stream, &(pMesh->mHasManualLodLevel), 1); - - // Preallocate submesh lod face data if not manual - if (!pMesh->hasManualLodLevel()) - { - unsigned short numsubs = pMesh->getNumSubMeshes(); - for (i = 0; i < numsubs; ++i) - { - SubMesh* sm = pMesh->getSubMesh(i); - assert(sm->mLodFaceList.empty()); - sm->mLodFaceList.resize(pMesh->mNumLods - 1); - } - } - - pushInnerChunk(stream); - // Loop from 1 rather than 0 (full detail index is not in file) - for (i = 1; i < pMesh->mNumLods; ++i) - { - streamID = readChunk(stream); - if (streamID != M_MESH_LOD_USAGE) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Missing M_MESH_LOD_USAGE stream in " + pMesh->getName(), - "MeshSerializerImpl::readMeshLodInfo"); - } - // Read depth - MeshLodUsage usage; - readFloats(stream, &(usage.userValue), 1); - - // Set default values - usage.manualName = ""; - usage.manualMesh.reset(); - usage.edgeData = NULL; - - if (pMesh->hasManualLodLevel()) - { - readMeshLodUsageManual(stream, pMesh, i, usage); - } - else //(!pMesh->hasManualLodLevel()) - { - readMeshLodUsageGenerated(stream, pMesh, i, usage); - } - usage.edgeData = NULL; - - // Save usage - pMesh->mMeshLodUsageList.push_back(usage); - } - popInnerChunk(stream); -#endif - } - - void MeshSerializerImpl_v1_8::enableValidation() - { -#if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE - mReportChunkErrors = false; -#endif - } - - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - MeshSerializerImpl_v1_41::MeshSerializerImpl_v1_41() - { - // Version number - mVersion = "[MeshSerializer_v1.41]"; - } - //--------------------------------------------------------------------- - MeshSerializerImpl_v1_41::~MeshSerializerImpl_v1_41() - { - } - //--------------------------------------------------------------------- - void MeshSerializerImpl_v1_41::writeMorphKeyframe(const VertexMorphKeyFrame* kf, size_t vertexCount) - { - writeChunkHeader(M_ANIMATION_MORPH_KEYFRAME, calcMorphKeyframeSize(kf, vertexCount)); - // float time - float timePos = kf->getTime(); - writeFloats(&timePos, 1); - // float x,y,z // repeat by number of vertices in original geometry - HardwareBufferLockGuard vbufLock(kf->getVertexBuffer(), HardwareBuffer::HBL_READ_ONLY); - writeFloats(static_cast(vbufLock.pData), vertexCount * 3); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl_v1_41::readMorphKeyFrame(const DataStreamPtr& stream, Mesh* pMesh, VertexAnimationTrack* track) - { - // float time - float timePos; - readFloats(stream, &timePos, 1); - - VertexMorphKeyFrame* kf = track->createVertexMorphKeyFrame(timePos); - - // Create buffer, allow read and use shadow buffer - size_t vertexCount = track->getAssociatedVertexData()->vertexCount; - HardwareVertexBufferSharedPtr vbuf = - pMesh->getHardwareBufferManager()->createVertexBuffer( - VertexElement::getTypeSize(VET_FLOAT3), vertexCount, - HardwareBuffer::HBU_STATIC, true); - // float x,y,z // repeat by number of vertices in original geometry - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - readFloats(stream, static_cast(vbufLock.pData), vertexCount * 3); - kf->setVertexBuffer(vbuf); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl_v1_41::writePose(const Pose* pose) - { - writeChunkHeader(M_POSE, calcPoseSize(pose)); - - // char* name (may be blank) - writeString(pose->getName()); - - // unsigned short target - ushort val = pose->getTarget(); - writeShorts(&val, 1); - pushInnerChunk(mStream); - size_t vertexSize = calcPoseVertexSize(); - for (const auto& it : pose->getVertexOffsets()) - { - uint32 vertexIndex = (uint32)it.first; - writeChunkHeader(M_POSE_VERTEX, vertexSize); - // unsigned long vertexIndex - writeInts(&vertexIndex, 1); - // float xoffset, yoffset, zoffset - writeFloats(it.second.ptr(), 3); - } - popInnerChunk(mStream); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl_v1_41::readPose(const DataStreamPtr& stream, Mesh* pMesh) - { - // char* name (may be blank) - String name = readString(stream); - // unsigned short target - unsigned short target; - readShorts(stream, &target, 1); - - Pose* pose = pMesh->createPose(target, name); - - // Find all substreams - if (!stream->eof()) - { - pushInnerChunk(stream); - unsigned short streamID = readChunk(stream); - while(!stream->eof() && - (streamID == M_POSE_VERTEX)) - { - switch(streamID) - { - case M_POSE_VERTEX: - // create vertex offset - uint32 vertIndex; - Vector3f offset; - // unsigned long vertexIndex - readInts(stream, &vertIndex, 1); - // float xoffset, yoffset, zoffset - readFloats(stream, offset.ptr(), 3); - - pose->addVertex(vertIndex, offset); - break; - - } - - if (!stream->eof()) - { - streamID = readChunk(stream); - } - - } - if (!stream->eof()) - { - // Backpedal back to start of stream - backpedalChunkHeader(stream); - } - popInnerChunk(stream); - } - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl_v1_41::calcPoseSize(const Pose* pose) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - - size += calcStringSize(pose->getName()); - // unsigned short target - size += sizeof(uint16); - - // vertex offsets - size += pose->getVertexOffsets().size() * calcPoseVertexSize(); - - return size; - - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl_v1_41::calcPoseVertexSize(void) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - // unsigned long vertexIndex - size += sizeof(uint32); - // float xoffset, yoffset, zoffset - size += sizeof(float) * 3; - - return size; - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl_v1_41::calcMorphKeyframeSize(const VertexMorphKeyFrame* kf, - size_t vertexCount) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - // float time - size += sizeof(float); - // float x,y,z - size += sizeof(float) * 3 * vertexCount; - - return size; - } - - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - MeshSerializerImpl_v1_4::MeshSerializerImpl_v1_4() - { - // Version number - mVersion = "[MeshSerializer_v1.40]"; - } - //--------------------------------------------------------------------- - MeshSerializerImpl_v1_4::~MeshSerializerImpl_v1_4() - { - } - size_t MeshSerializerImpl_v1_4::calcLodLevelSize(const Mesh* pMesh) - { - if (isLodMixed(pMesh) || pMesh->getLodStrategy() != DistanceLodBoxStrategy::getSingletonPtr()) { - return 0; // Supported in v1_9+ - } - exportedLodCount = pMesh->getNumLodLevels(); - size_t size = MSTREAM_OVERHEAD_SIZE; // Header - //size += calcStringSize(pMesh->getLodStrategy()->getName()); // string strategyName; <== missing in v1_4 - size += sizeof(unsigned short); // unsigned short numLevels; - size += sizeof(bool); // bool manual; <== this is removed in v1_9 - - // Loop from LOD 1 (not 0, this is full detail) - for (ushort i = 1; i < exportedLodCount; ++i) - { - const MeshLodUsage& usage = pMesh->mMeshLodUsageList[i]; - if (pMesh->_isManualLodLevel(i)) - { - size += calcLodUsageManualSize(usage); - } - else - { - size += calcLodUsageGeneratedSize(pMesh, usage, i); - } - } - return size; - } -#if !OGRE_NO_MESHLOD - //--------------------------------------------------------------------- - void MeshSerializerImpl_v1_4::writeLodLevel(const Mesh* pMesh) - { - if (isLodMixed(pMesh)) { - LogManager::getSingleton().logMessage("MeshSerializer_v1_4 or older mesh format is incompatible with mixed manual/generated Lod levels. Lod levels will not be exported."); - } else if (pMesh->getLodStrategy() != DistanceLodBoxStrategy::getSingletonPtr()) { - LogManager::getSingleton().logMessage("MeshSerializer_v1_4 or older mesh format is only compatible with Distance Lod Strategy. Lod levels will not be exported."); - } else { - exportedLodCount = pMesh->getNumLodLevels(); - bool manual = pMesh->hasManualLodLevel(); - - writeChunkHeader(M_MESH_LOD_LEVEL, calcLodLevelSize(pMesh)); - - // Details - // string strategyName; - //writeString(pMesh->getLodStrategy()->getName()); <== missing in v1_4 - // unsigned short numLevels; - writeShorts(&exportedLodCount, 1); - // bool manual; (true for manual alternate meshes, false for generated) - writeBools(&manual, 1); - - pushInnerChunk(mStream); - // Loop from LOD 1 (not 0, this is full detail) - for (ushort i = 1; i < exportedLodCount; ++i) - { - const MeshLodUsage& usage = pMesh->mMeshLodUsageList[i]; - assert(pMesh->_isManualLodLevel(i) == manual); - if (manual) - { - writeLodUsageManual(usage); - } - else - { - /*readFloats(stream, &(usage.value), 1); - usage.userValue = Math::Sqrt(usage.value);*/ - writeLodUsageGenerated(pMesh, usage, i); - } - } - popInnerChunk(mStream); - } - } - //--------------------------------------------------------------------- - void MeshSerializerImpl_v1_4::writeLodUsageGenerated(const Mesh* pMesh, const MeshLodUsage& usage, unsigned short lodNum) - { - writeChunkHeader(M_MESH_LOD_USAGE, calcLodUsageGeneratedSize(pMesh, usage, lodNum)); - float value = static_cast(usage.value); - writeFloats(&value, 1); // <== In v1_4 this is value instead of userValue - pushInnerChunk(mStream); - for (auto *s : pMesh->getSubMeshes()) - { - writeLodUsageGeneratedSubmesh(s, lodNum); - } - popInnerChunk(mStream); - } -#endif - //--------------------------------------------------------------------- - void MeshSerializerImpl_v1_4::readMeshLodLevel(const DataStreamPtr& stream, Mesh* pMesh) - { -#if OGRE_NO_MESHLOD - - /* - //Since the chunk sizes in old versions are messed up, we can't use this clean solution. - // We need to walk through the data to not rely on the chunk size! - stream->skip(mCurrentstreamLen); - - // Since we got here, we have already read the chunk header. - backpedalChunkHeader(stream); - */ - uint16 numSubs = pMesh->getNumSubMeshes(); - // String strategyName = readString(stream); // missing in v1_4 - uint16 numLods; - readShorts(stream, &numLods, 1); - bool manual; - readBools(stream, &manual, 1); // missing in v1_9 - pushInnerChunk(stream); - for (uint16 i = 1; i < numLods; ++i) - { - uint16 streamID = readChunk(stream); - if (streamID != M_MESH_LOD_USAGE) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Missing M_MESH_LOD_USAGE stream in " + pMesh->getName(), - "MeshSerializerImpl::readMeshLodInfo"); - } - float usageValue; - readFloats(stream, &usageValue, 1); - - if (manual) - { - // Read detail stream - streamID = readChunk(stream); - if (streamID != M_MESH_LOD_MANUAL) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Missing M_MESH_LOD_MANUAL stream in " + pMesh->getName(), - "MeshSerializerImpl::readMeshLodUsageManual"); - } - - String manualName = readString(stream); - } - else - { - pushInnerChunk(stream); - for (uint16 n = 0; n < numSubs; ++n) - { - streamID = readChunk(stream); - if (streamID != M_MESH_LOD_GENERATED) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Missing M_MESH_LOD_GENERATED stream in " + pMesh->getName(), - "MeshSerializerImpl::readMeshLodUsageGenerated"); - } - - unsigned int numIndexes; - readInts(stream, &numIndexes, 1); - - bool idx32Bit; - readBools(stream, &idx32Bit, 1); - - size_t buffSize = numIndexes * (idx32Bit ? 4 : 2); - stream->skip(buffSize); - } - popInnerChunk(stream); - } - } - popInnerChunk(stream); -#else - unsigned short streamID, i; - - // Use the old strategy for this mesh - LodStrategy *strategy = DistanceLodSphereStrategy::getSingletonPtr(); - pMesh->setLodStrategy(strategy); - - // unsigned short numLevels; - readShorts(stream, &(pMesh->mNumLods), 1); - bool manual; // true for manual alternate meshes, false for generated - readBools(stream, &manual, 1); - - pMesh->mHasManualLodLevel = manual; - - // Preallocate submesh LOD face data if not manual - if (!manual) - { - for (auto *s : pMesh->getSubMeshes()) - { - assert(s->mLodFaceList.empty()); - s->mLodFaceList.resize(pMesh->mNumLods - 1); - } - } - pushInnerChunk(stream); - // Loop from 1 rather than 0 (full detail index is not in file) - for (i = 1; i < pMesh->mNumLods; ++i) - { - streamID = readChunk(stream); - if (streamID != M_MESH_LOD_USAGE) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Missing M_MESH_LOD_USAGE stream in " + pMesh->getName(), - "MeshSerializerImpl::readMeshLodInfo"); - } - // Read depth - MeshLodUsage usage; - readFloats(stream, &(usage.value), 1); - usage.userValue = Math::Sqrt(usage.value); - - // Set default values - usage.manualName = ""; - usage.manualMesh.reset(); - usage.edgeData = NULL; - - if (manual) - { - readMeshLodUsageManual(stream, pMesh, i, usage); - } - else //(!pMesh->isLodManual) - { - readMeshLodUsageGenerated(stream, pMesh, i, usage); - } - usage.edgeData = NULL; - - // Save usage - pMesh->mMeshLodUsageList.push_back(usage); - } - popInnerChunk(stream); -#endif - } - - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - MeshSerializerImpl_v1_3::MeshSerializerImpl_v1_3() - { - // Version number - mVersion = "[MeshSerializer_v1.30]"; - } - //--------------------------------------------------------------------- - MeshSerializerImpl_v1_3::~MeshSerializerImpl_v1_3() - { - } - //--------------------------------------------------------------------- - void MeshSerializerImpl_v1_3::readEdgeListLodInfo(const DataStreamPtr& stream, - EdgeData* edgeData) - { -#if OGRE_NO_MESHLOD - if (edgeData == NULL) { // skip it! - // unsigned long numTriangles - uint32 numTriangles; - readInts(stream, &numTriangles, 1); - // unsigned long numEdgeGroups - uint32 numEdgeGroups; - readInts(stream, &numEdgeGroups, 1); - stream->skip(numTriangles * (8 * sizeof(uint32) + 4 * sizeof(float))); - - pushInnerChunk(stream); - uint32 tmp[6]; - for (uint32 eg = 0; eg < numEdgeGroups; ++eg) - { - unsigned short streamID = readChunk(stream); - if (streamID != M_EDGE_GROUP) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Missing M_EDGE_GROUP stream", - "MeshSerializerImpl_v1_3::readEdgeListLodInfo"); - } - - // unsigned long vertexSet - readInts(stream, tmp, 1); - // unsigned long numEdges - uint32 numEdges; - readInts(stream, &numEdges, 1); - // Edge* edgeList - stream->skip(numEdges * (6 * sizeof(uint32) + sizeof(bool))); - } - popInnerChunk(stream); - return; - } -#endif - // unsigned long numTriangles - uint32 numTriangles; - readInts(stream, &numTriangles, 1); - // Allocate correct amount of memory - edgeData->triangles.resize(numTriangles); - edgeData->triangleFaceNormals.resize(numTriangles); - edgeData->triangleLightFacings.resize(numTriangles); - // unsigned long numEdgeGroups - uint32 numEdgeGroups; - readInts(stream, &numEdgeGroups, 1); - // Allocate correct amount of memory - edgeData->edgeGroups.resize(numEdgeGroups); - // Triangle* triangleList - uint32 tmp[3]; - for (size_t t = 0; t < numTriangles; ++t) - { - EdgeData::Triangle& tri = edgeData->triangles[t]; - // unsigned long indexSet - readInts(stream, tmp, 1); - tri.indexSet = tmp[0]; - // unsigned long vertexSet - readInts(stream, tmp, 1); - tri.vertexSet = tmp[0]; - // unsigned long vertIndex[3] - readInts(stream, tmp, 3); - tri.vertIndex[0] = tmp[0]; - tri.vertIndex[1] = tmp[1]; - tri.vertIndex[2] = tmp[2]; - // unsigned long sharedVertIndex[3] - readInts(stream, tmp, 3); - tri.sharedVertIndex[0] = tmp[0]; - tri.sharedVertIndex[1] = tmp[1]; - tri.sharedVertIndex[2] = tmp[2]; - // float normal[4] - readFloats(stream, &(edgeData->triangleFaceNormals[t].x), 4); - - } - - // Assume the mesh is closed, it will update later - edgeData->isClosed = true; - - pushInnerChunk(stream); - for (uint32 eg = 0; eg < numEdgeGroups; ++eg) - { - unsigned short streamID = readChunk(stream); - if (streamID != M_EDGE_GROUP) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Missing M_EDGE_GROUP stream", - "MeshSerializerImpl_v1_3::readEdgeListLodInfo"); - } - EdgeData::EdgeGroup& edgeGroup = edgeData->edgeGroups[eg]; - - // unsigned long vertexSet - readInts(stream, tmp, 1); - edgeGroup.vertexSet = tmp[0]; - // unsigned long numEdges - uint32 numEdges; - readInts(stream, &numEdges, 1); - edgeGroup.edges.resize(numEdges); - // Edge* edgeList - for (uint32 e = 0; e < numEdges; ++e) - { - EdgeData::Edge& edge = edgeGroup.edges[e]; - // unsigned long triIndex[2] - readInts(stream, tmp, 2); - edge.triIndex[0] = tmp[0]; - edge.triIndex[1] = tmp[1]; - // unsigned long vertIndex[2] - readInts(stream, tmp, 2); - edge.vertIndex[0] = tmp[0]; - edge.vertIndex[1] = tmp[1]; - // unsigned long sharedVertIndex[2] - readInts(stream, tmp, 2); - edge.sharedVertIndex[0] = tmp[0]; - edge.sharedVertIndex[1] = tmp[1]; - // bool degenerate - readBools(stream, &(edge.degenerate), 1); - - // The mesh is closed only if no degenerate edge here - if (edge.degenerate) - { - edgeData->isClosed = false; - } - } - } - popInnerChunk(stream); - reorganiseTriangles(edgeData); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl_v1_3::reorganiseTriangles(EdgeData* edgeData) - { - size_t numTriangles = edgeData->triangles.size(); - - if (edgeData->edgeGroups.size() == 1) - { - // Special case for only one edge group in the edge list, which occurring - // most time. In this case, all triangles belongs to that group. - edgeData->edgeGroups.front().triStart = 0; - edgeData->edgeGroups.front().triCount = numTriangles; - } - else - { - EdgeData::EdgeGroupList::iterator egi, egend; - egend = edgeData->edgeGroups.end(); - - // Calculate number of triangles for edge groups - - for (auto& g : edgeData->edgeGroups) - { - g.triStart = 0; - g.triCount = 0; - } - - bool isGrouped = true; - EdgeData::EdgeGroup* lastEdgeGroup = 0; - for (size_t t = 0; t < numTriangles; ++t) - { - // Gets the edge group that the triangle belongs to - const EdgeData::Triangle& tri = edgeData->triangles[t]; - EdgeData::EdgeGroup* edgeGroup = &edgeData->edgeGroups[tri.vertexSet]; - - // Does edge group changes from last edge group? - if (isGrouped && edgeGroup != lastEdgeGroup) - { - // Remember last edge group - lastEdgeGroup = edgeGroup; - - // Is't first time encounter this edge group? - if (!edgeGroup->triCount && !edgeGroup->triStart) - { - // setup first triangle of this edge group - edgeGroup->triStart = t; - } - else - { - // original triangles doesn't grouping by edge group - isGrouped = false; - } - } - - // Count number of triangles for this edge group - if(edgeGroup) - ++edgeGroup->triCount; - } - - // - // Note that triangles has been sorted by vertex set for a long time, - // but never stored to old version mesh file. - // - // Adopt this fact to avoid remap triangles here. - // - - // Does triangles grouped by vertex set? - if (!isGrouped) - { - // Ok, the triangles of this edge list isn't grouped by vertex set - // perfectly, seems ancient mesh file. - // - // We need work hardly to group triangles by vertex set. - // - - // Calculate triStart and reset triCount to zero for each edge group first - size_t triStart = 0; - for (auto& g : edgeData->edgeGroups) - { - g.triStart = triStart; - triStart += g.triCount; - g.triCount = 0; - } - - // The map used to mapping original triangle index to new index - typedef std::vector TriangleIndexRemap; - TriangleIndexRemap triangleIndexRemap(numTriangles); - - // New triangles information that should be group by vertex set. - EdgeData::TriangleList newTriangles(numTriangles); - EdgeData::TriangleFaceNormalList newTriangleFaceNormals(numTriangles); - - // Calculate triangle index map and organise triangles information - for (size_t t = 0; t < numTriangles; ++t) - { - // Gets the edge group that the triangle belongs to - const EdgeData::Triangle& tri = edgeData->triangles[t]; - EdgeData::EdgeGroup& edgeGroup = edgeData->edgeGroups[tri.vertexSet]; - - // Calculate new index - size_t newIndex = edgeGroup.triStart + edgeGroup.triCount; - ++edgeGroup.triCount; - - // Setup triangle index mapping entry - triangleIndexRemap[t] = newIndex; - - // Copy triangle info to new placement - newTriangles[newIndex] = tri; - newTriangleFaceNormals[newIndex] = edgeData->triangleFaceNormals[t]; - } - - // Replace with new triangles information - edgeData->triangles.swap(newTriangles); - edgeData->triangleFaceNormals.swap(newTriangleFaceNormals); - - // Now, update old triangle indices to new index - for (egi = edgeData->edgeGroups.begin(); egi != egend; ++egi) - { - EdgeData::EdgeList::iterator ei, eend; - eend = egi->edges.end(); - for (ei = egi->edges.begin(); ei != eend; ++ei) - { - ei->triIndex[0] = triangleIndexRemap[ei->triIndex[0]]; - if (!ei->degenerate) - { - ei->triIndex[1] = triangleIndexRemap[ei->triIndex[1]]; - } - } - } - } - } - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl_v1_3::calcEdgeListLodSize(const EdgeData* edgeData, bool isManual) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - - // unsigned short lodIndex - size += sizeof(uint16); - - // bool isManual // If manual, no edge data here, loaded from manual mesh - size += sizeof(bool); - if (!isManual) - { - // bool isClosed - //size += sizeof(bool); <== missing in v1_3 - // unsigned long numTriangles - size += sizeof(uint32); - // unsigned long numEdgeGroups - size += sizeof(uint32); - // Triangle* triangleList - size_t triSize = 0; - // unsigned long indexSet - // unsigned long vertexSet - // unsigned long vertIndex[3] - // unsigned long sharedVertIndex[3] - // float normal[4] - triSize += sizeof(uint32)* 8 - + sizeof(float)* 4; - - size += triSize * edgeData->triangles.size(); - // Write the groups - for (const auto & edgeGroup : edgeData->edgeGroups) - { - size += calcEdgeGroupSize(edgeGroup); - } - - } - - return size; - } - //--------------------------------------------------------------------- - size_t MeshSerializerImpl_v1_3::calcEdgeGroupSize(const EdgeData::EdgeGroup& group) - { - size_t size = MSTREAM_OVERHEAD_SIZE; - - // unsigned long vertexSet - size += sizeof(uint32); - // unsigned long triStart - //size += sizeof(uint32); <== missing in v1_3 - // unsigned long triCount - //size += sizeof(uint32); <== missing in v1_3 - // unsigned long numEdges - size += sizeof(uint32); - // Edge* edgeList - size_t edgeSize = 0; - // unsigned long triIndex[2] - // unsigned long vertIndex[2] - // unsigned long sharedVertIndex[2] - // bool degenerate - edgeSize += sizeof(uint32)* 6 + sizeof(bool); - size += edgeSize * group.edges.size(); - - return size; - } - //--------------------------------------------------------------------- - void MeshSerializerImpl_v1_3::writeEdgeList(const Mesh* pMesh) - { - assert(exportedLodCount != 0); - writeChunkHeader(M_EDGE_LISTS, calcEdgeListSize(pMesh)); - pushInnerChunk(mStream); - for (ushort i = 0; i < exportedLodCount; ++i) - { - const EdgeData* edgeData = pMesh->getEdgeList(i); - bool isManual = !pMesh->mMeshLodUsageList[i].manualName.empty(); - writeChunkHeader(M_EDGE_LIST_LOD, calcEdgeListLodSize(edgeData, isManual)); - - // unsigned short lodIndex - writeShorts(&i, 1); - - // bool isManual // If manual, no edge data here, loaded from manual mesh - writeBools(&isManual, 1); - if (!isManual) - { - // unsigned long numTriangles - uint32 count = static_cast(edgeData->triangles.size()); - writeInts(&count, 1); - // unsigned long numEdgeGroups - count = static_cast(edgeData->edgeGroups.size()); - writeInts(&count, 1); - // Triangle* triangleList - // Iterate rather than writing en-masse to allow endian conversion - EdgeData::TriangleFaceNormalList::const_iterator fni = edgeData->triangleFaceNormals.begin(); - for (auto& tri : edgeData->triangles) - { - // unsigned long indexSet; - uint32 tmp[3]; - tmp[0] = static_cast(tri.indexSet); - writeInts(tmp, 1); - // unsigned long vertexSet; - tmp[0] = static_cast(tri.vertexSet); - writeInts(tmp, 1); - // unsigned long vertIndex[3]; - tmp[0] = static_cast(tri.vertIndex[0]); - tmp[1] = static_cast(tri.vertIndex[1]); - tmp[2] = static_cast(tri.vertIndex[2]); - writeInts(tmp, 3); - // unsigned long sharedVertIndex[3]; - tmp[0] = static_cast(tri.sharedVertIndex[0]); - tmp[1] = static_cast(tri.sharedVertIndex[1]); - tmp[2] = static_cast(tri.sharedVertIndex[2]); - writeInts(tmp, 3); - // float normal[4]; - writeFloats(&(fni->x), 4); - ++fni; - } - pushInnerChunk(mStream); - // Write the groups - for (const auto& edgeGroup : edgeData->edgeGroups) - { - writeChunkHeader(M_EDGE_GROUP, calcEdgeGroupSize(edgeGroup)); - // unsigned long vertexSet - uint32 vertexSet = static_cast(edgeGroup.vertexSet); - writeInts(&vertexSet, 1); - // unsigned long numEdges - count = static_cast(edgeGroup.edges.size()); - writeInts(&count, 1); - // Edge* edgeList - // Iterate rather than writing en-masse to allow endian conversion - for (const auto& edge : edgeGroup.edges) - { - uint32 tmp[2]; - // unsigned long triIndex[2] - tmp[0] = static_cast(edge.triIndex[0]); - tmp[1] = static_cast(edge.triIndex[1]); - writeInts(tmp, 2); - // unsigned long vertIndex[2] - tmp[0] = static_cast(edge.vertIndex[0]); - tmp[1] = static_cast(edge.vertIndex[1]); - writeInts(tmp, 2); - // unsigned long sharedVertIndex[2] - tmp[0] = static_cast(edge.sharedVertIndex[0]); - tmp[1] = static_cast(edge.sharedVertIndex[1]); - writeInts(tmp, 2); - // bool degenerate - writeBools(&(edge.degenerate), 1); - } - - } - popInnerChunk(mStream); - - } - - } - popInnerChunk(mStream); - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - MeshSerializerImpl_v1_2::MeshSerializerImpl_v1_2() - { - // Version number - mVersion = "[MeshSerializer_v1.20]"; - } - //--------------------------------------------------------------------- - MeshSerializerImpl_v1_2::~MeshSerializerImpl_v1_2() - { - } - //--------------------------------------------------------------------- - void MeshSerializerImpl_v1_2::readMesh(const DataStreamPtr& stream, Mesh* pMesh, MeshSerializerListener *listener) - { - MeshSerializerImpl::readMesh(stream, pMesh, listener); - // Always automatically build edge lists for this version - pMesh->mAutoBuildEdgeLists = true; - - } - //--------------------------------------------------------------------- - void MeshSerializerImpl_v1_2::readGeometry(const DataStreamPtr& stream, Mesh* pMesh, - VertexData* dest) - { - unsigned short bindIdx = 0; - - dest->vertexStart = 0; - - unsigned int vertexCount = 0; - readInts(stream, &vertexCount, 1); - dest->vertexCount = vertexCount; - - // Vertex buffers - - readGeometryPositions(bindIdx, stream, pMesh, dest); - ++bindIdx; - // Find optional geometry streams - if (!stream->eof()) - { - pushInnerChunk(stream); - unsigned short streamID = readChunk(stream); - unsigned short texCoordSet = 0; - - while(!stream->eof() && - (streamID == M_GEOMETRY_NORMALS || - streamID == M_GEOMETRY_COLOURS || - streamID == M_GEOMETRY_TEXCOORDS )) - { - switch (streamID) - { - case M_GEOMETRY_NORMALS: - readGeometryNormals(bindIdx++, stream, pMesh, dest); - break; - case M_GEOMETRY_COLOURS: - readGeometryColours(bindIdx++, stream, pMesh, dest); - break; - case M_GEOMETRY_TEXCOORDS: - readGeometryTexCoords(bindIdx++, stream, pMesh, dest, texCoordSet++); - break; - } - // Get next stream - if (!stream->eof()) - { - streamID = readChunk(stream); - } - } - if (!stream->eof()) - { - // Backpedal back to start of non-submesh stream - backpedalChunkHeader(stream); - } - popInnerChunk(stream); - } - } - //--------------------------------------------------------------------- - void MeshSerializerImpl_v1_2::readGeometryPositions(unsigned short bindIdx, - const DataStreamPtr& stream, Mesh* pMesh, VertexData* dest) - { - HardwareVertexBufferSharedPtr vbuf; - // float* pVertices (x, y, z order x numVertices) - dest->vertexDeclaration->addElement(bindIdx, 0, VET_FLOAT3, VES_POSITION); - vbuf = pMesh->getHardwareBufferManager()->createVertexBuffer( - dest->vertexDeclaration->getVertexSize(bindIdx), - dest->vertexCount, - pMesh->mVertexBufferUsage, - pMesh->mVertexBufferShadowBuffer); - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - readFloats(stream, static_cast(vbufLock.pData), dest->vertexCount * 3); - dest->vertexBufferBinding->setBinding(bindIdx, vbuf); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl_v1_2::readGeometryNormals(unsigned short bindIdx, - const DataStreamPtr& stream, Mesh* pMesh, VertexData* dest) - { - HardwareVertexBufferSharedPtr vbuf; - // float* pNormals (x, y, z order x numVertices) - dest->vertexDeclaration->addElement(bindIdx, 0, VET_FLOAT3, VES_NORMAL); - vbuf = pMesh->getHardwareBufferManager()->createVertexBuffer( - dest->vertexDeclaration->getVertexSize(bindIdx), - dest->vertexCount, - pMesh->mVertexBufferUsage, - pMesh->mVertexBufferShadowBuffer); - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - readFloats(stream, static_cast(vbufLock.pData), dest->vertexCount * 3); - dest->vertexBufferBinding->setBinding(bindIdx, vbuf); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl_v1_2::readGeometryColours(unsigned short bindIdx, - const DataStreamPtr& stream, Mesh* pMesh, VertexData* dest) - { - HardwareVertexBufferSharedPtr vbuf; - // unsigned long* pColours (RGBA 8888 format x numVertices) - dest->vertexDeclaration->addElement(bindIdx, 0, VET_COLOUR, VES_DIFFUSE); - vbuf = pMesh->getHardwareBufferManager()->createVertexBuffer( - dest->vertexDeclaration->getVertexSize(bindIdx), - dest->vertexCount, - pMesh->mVertexBufferUsage, - pMesh->mVertexBufferShadowBuffer); - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - readInts(stream, static_cast(vbufLock.pData), dest->vertexCount); - dest->vertexBufferBinding->setBinding(bindIdx, vbuf); - } - //--------------------------------------------------------------------- - void MeshSerializerImpl_v1_2::readGeometryTexCoords(unsigned short bindIdx, - const DataStreamPtr& stream, Mesh* pMesh, VertexData* dest, unsigned short texCoordSet) - { - HardwareVertexBufferSharedPtr vbuf; - // unsigned short dimensions (1 for 1D, 2 for 2D, 3 for 3D) - unsigned short dim; - readShorts(stream, &dim, 1); - // float* pTexCoords (u [v] [w] order, dimensions x numVertices) - dest->vertexDeclaration->addElement( - bindIdx, - 0, - VertexElement::multiplyTypeCount(VET_FLOAT1, dim), - VES_TEXTURE_COORDINATES, - texCoordSet); - vbuf = pMesh->getHardwareBufferManager()->createVertexBuffer( - dest->vertexDeclaration->getVertexSize(bindIdx), - dest->vertexCount, - pMesh->mVertexBufferUsage, - pMesh->mVertexBufferShadowBuffer); - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - readFloats(stream, static_cast(vbufLock.pData), dest->vertexCount * dim); - dest->vertexBufferBinding->setBinding(bindIdx, vbuf); - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - MeshSerializerImpl_v1_1::MeshSerializerImpl_v1_1() - { - // Version number - mVersion = "[MeshSerializer_v1.10]"; - } - //--------------------------------------------------------------------- - MeshSerializerImpl_v1_1::~MeshSerializerImpl_v1_1() - { - } - //--------------------------------------------------------------------- - void MeshSerializerImpl_v1_1::readGeometryTexCoords(unsigned short bindIdx, - const DataStreamPtr& stream, Mesh* pMesh, VertexData* dest, unsigned short texCoordSet) - { - float *pFloat = 0; - HardwareVertexBufferSharedPtr vbuf; - // unsigned short dimensions (1 for 1D, 2 for 2D, 3 for 3D) - unsigned short dim; - readShorts(stream, &dim, 1); - // float* pTexCoords (u [v] [w] order, dimensions x numVertices) - dest->vertexDeclaration->addElement( - bindIdx, - 0, - VertexElement::multiplyTypeCount(VET_FLOAT1, dim), - VES_TEXTURE_COORDINATES, - texCoordSet); - vbuf = pMesh->getHardwareBufferManager()->createVertexBuffer( - dest->vertexDeclaration->getVertexSize(bindIdx), - dest->vertexCount, - pMesh->getVertexBufferUsage(), - pMesh->isVertexBufferShadowed()); - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - pFloat = static_cast(vbufLock.pData); - readFloats(stream, pFloat, dest->vertexCount * dim); - - // Adjust individual v values to (1 - v) - if (dim == 2) - { - for (size_t i = 0; i < dest->vertexCount; ++i) - { - ++pFloat; // skip u - *pFloat = 1.0f - *pFloat; // v = 1 - v - ++pFloat; - } - - } - dest->vertexBufferBinding->setBinding(bindIdx, vbuf); - } -} diff --git a/OgreMain/src/OgreMeshSerializerImpl.h b/OgreMain/src/OgreMeshSerializerImpl.h deleted file mode 100644 index 593a12903e1..00000000000 --- a/OgreMain/src/OgreMeshSerializerImpl.h +++ /dev/null @@ -1,315 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __MeshSerializerImpl_H__ -#define __MeshSerializerImpl_H__ - -#include "OgrePrerequisites.h" -#include "OgreSerializer.h" -#include "OgreEdgeListBuilder.h" -#include "OgreKeyFrame.h" -#include "OgreVertexBoneAssignment.h" - -namespace Ogre { - - class MeshSerializerListener; - struct MeshLodUsage; - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - /** Internal implementation of Mesh reading / writing for the latest version of the - .mesh format. - - In order to maintain compatibility with older versions of the .mesh format, there - will be alternative subclasses of this class to load older versions, whilst this class - will remain to load the latest version. - - @note - This mesh format was used from Ogre v1.10. - - */ - class _OgrePrivate MeshSerializerImpl : public Serializer - { - public: - MeshSerializerImpl(); - virtual ~MeshSerializerImpl(); - /** Exports a mesh to the file specified. - - This method takes an externally created Mesh object, and exports both it - and optionally the Materials it uses to a .mesh file. - @param pMesh Pointer to the Mesh to export - @param stream The destination stream - @param endianMode The endian mode for the written file - */ - void exportMesh(const Mesh* pMesh, const DataStreamPtr& stream, - Endian endianMode = ENDIAN_NATIVE); - - /** Imports Mesh and (optionally) Material data from a .mesh file DataStream. - - This method imports data from a DataStream opened from a .mesh file and places it's - contents into the Mesh object which is passed in. - @param stream The DataStream holding the .mesh data. Must be initialised (pos at the start of the buffer). - @param pDest Pointer to the Mesh object which will receive the data. Should be blank already. - */ - void importMesh(const DataStreamPtr& stream, Mesh* pDest, MeshSerializerListener *listener); - - protected: - - // Internal methods - virtual void writeSubMeshNameTable(const Mesh* pMesh); - virtual void writeMesh(const Mesh* pMesh); - virtual void writeSubMesh(const SubMesh* s); - virtual void writeSubMeshOperation(const SubMesh* s); - virtual void writeGeometry(const VertexData* pGeom); - virtual void writeSkeletonLink(const String& skelName); - virtual void writeMeshBoneAssignment(const VertexBoneAssignment& assign); - virtual void writeSubMeshBoneAssignment(const VertexBoneAssignment& assign); -#if !OGRE_NO_MESHLOD - virtual void writeLodLevel(const Mesh* pMesh); - virtual void writeLodUsageManual(const MeshLodUsage& usage); - virtual void writeLodUsageGenerated(const Mesh* pMesh, const MeshLodUsage& usage, unsigned short lodNum); - virtual void writeLodUsageGeneratedSubmesh(const SubMesh* submesh, unsigned short lodNum); -#endif - virtual void writeBoundsInfo(const Mesh* pMesh); - virtual void writeEdgeList(const Mesh* pMesh); - virtual void writeAnimations(const Mesh* pMesh); - virtual void writeAnimation(const Animation* anim); - virtual void writePoses(const Mesh* pMesh); - virtual void writePose(const Pose* pose); - virtual void writeAnimationTrack(const VertexAnimationTrack* track); - virtual void writeMorphKeyframe(const VertexMorphKeyFrame* kf, size_t vertexCount); - virtual void writePoseKeyframe(const VertexPoseKeyFrame* kf); - virtual void writePoseKeyframePoseRef(const VertexPoseKeyFrame::PoseRef& poseRef); - virtual void writeExtremes(const Mesh *pMesh); - virtual void writeSubMeshExtremes(unsigned short idx, const SubMesh* s); - - virtual size_t calcMeshSize(const Mesh* pMesh); - virtual size_t calcSubMeshSize(const SubMesh* pSub); - virtual size_t calcGeometrySize(const VertexData* pGeom); - virtual size_t calcSkeletonLinkSize(const String& skelName); - virtual size_t calcBoneAssignmentSize(void); - virtual size_t calcSubMeshOperationSize(); - virtual size_t calcSubMeshNameTableSize(const Mesh* pMesh); - virtual size_t calcLodLevelSize(const Mesh* pMesh); - virtual size_t calcLodUsageManualSize(const MeshLodUsage& usage); - virtual size_t calcLodUsageGeneratedSize(const Mesh* pMesh, const MeshLodUsage& usage, unsigned short lodNum); - virtual size_t calcLodUsageGeneratedSubmeshSize(const SubMesh* submesh, unsigned short lodNum); - virtual size_t calcEdgeListSize(const Mesh* pMesh); - virtual size_t calcEdgeListLodSize(const EdgeData* data, bool isManual); - virtual size_t calcEdgeGroupSize(const EdgeData::EdgeGroup& group); - virtual size_t calcPosesSize(const Mesh* pMesh); - virtual size_t calcPoseSize(const Pose* pose); - virtual size_t calcAnimationsSize(const Mesh* pMesh); - virtual size_t calcAnimationSize(const Animation* anim); - virtual size_t calcAnimationTrackSize(const VertexAnimationTrack* track); - virtual size_t calcMorphKeyframeSize(const VertexMorphKeyFrame* kf, size_t vertexCount); - virtual size_t calcPoseKeyframeSize(const VertexPoseKeyFrame* kf); - virtual size_t calcPoseKeyframePoseRefSize(void); - virtual size_t calcPoseVertexSize(const Pose* pose); - virtual size_t calcBoundsInfoSize(); - virtual size_t calcExtremesSize(const Mesh* pMesh); - virtual size_t calcSubMeshExtremesSize(const SubMesh* s); - - virtual void readTextureLayer(const DataStreamPtr& stream, Mesh* pMesh, MaterialPtr& pMat); - virtual void readSubMeshNameTable(const DataStreamPtr& stream, Mesh* pMesh); - virtual void readMesh(const DataStreamPtr& stream, Mesh* pMesh, MeshSerializerListener *listener); - virtual void readSubMesh(const DataStreamPtr& stream, Mesh* pMesh, MeshSerializerListener *listener); - virtual void readSubMeshOperation(const DataStreamPtr& stream, Mesh* pMesh, SubMesh* sub); - virtual void readGeometry(const DataStreamPtr& stream, Mesh* pMesh, VertexData* dest); - virtual void readGeometryVertexDeclaration(const DataStreamPtr& stream, Mesh* pMesh, VertexData* dest); - virtual void readGeometryVertexElement(const DataStreamPtr& stream, Mesh* pMesh, VertexData* dest); - virtual void readGeometryVertexBuffer(const DataStreamPtr& stream, Mesh* pMesh, VertexData* dest); - - virtual void readSkeletonLink(const DataStreamPtr& stream, Mesh* pMesh, MeshSerializerListener *listener); - virtual void readMeshBoneAssignment(const DataStreamPtr& stream, Mesh* pMesh); - virtual void readSubMeshBoneAssignment(const DataStreamPtr& stream, Mesh* pMesh, - SubMesh* sub); - virtual void readMeshLodLevel(const DataStreamPtr& stream, Mesh* pMesh); -#if !OGRE_NO_MESHLOD - virtual void readMeshLodUsageManual(const DataStreamPtr& stream, Mesh* pMesh, unsigned short lodNum, MeshLodUsage& usage); - virtual void readMeshLodUsageGenerated(const DataStreamPtr& stream, Mesh* pMesh, unsigned short lodNum, MeshLodUsage& usage); -#endif - virtual void readBoundsInfo(const DataStreamPtr& stream, Mesh* pMesh); - virtual void readEdgeList(const DataStreamPtr& stream, Mesh* pMesh); - virtual void readEdgeListLodInfo(const DataStreamPtr& stream, EdgeData* edgeData); - virtual void readPoses(const DataStreamPtr& stream, Mesh* pMesh); - virtual void readPose(const DataStreamPtr& stream, Mesh* pMesh); - virtual void readAnimations(const DataStreamPtr& stream, Mesh* pMesh); - virtual void readAnimation(const DataStreamPtr& stream, Mesh* pMesh); - virtual void readAnimationTrack(const DataStreamPtr& stream, Animation* anim, - Mesh* pMesh); - virtual void readMorphKeyFrame(const DataStreamPtr& stream, Mesh* pMesh, VertexAnimationTrack* track); - virtual void readPoseKeyFrame(const DataStreamPtr& stream, VertexAnimationTrack* track); - virtual void readExtremes(const DataStreamPtr& stream, Mesh *pMesh); - - - /// Flip an entire vertex buffer from little endian - virtual void flipFromLittleEndian(void* pData, size_t vertexCount, size_t vertexSize, const VertexDeclaration::VertexElementList& elems); - /// Flip an entire vertex buffer to little endian - virtual void flipToLittleEndian(void* pData, size_t vertexCount, size_t vertexSize, const VertexDeclaration::VertexElementList& elems); - /// Flip the endianness of an entire vertex buffer, passed in as a - /// pointer to locked or temporary memory - virtual void flipEndian(void* pData, size_t vertexCount, size_t vertexSize, const VertexDeclaration::VertexElementList& elems); - - /// This function can be overloaded to disable validation in debug builds. - virtual void enableValidation(); - - ushort exportedLodCount; // Needed to limit exported Edge data, when exporting - }; - - - /** Class for providing backwards-compatibility for loading version 1.8 of the .mesh format. - This mesh format was used from Ogre v1.8. - */ - class _OgrePrivate MeshSerializerImpl_v1_8 : public MeshSerializerImpl - { - public: - MeshSerializerImpl_v1_8(); - ~MeshSerializerImpl_v1_8(); - protected: - // In the past we could select to use manual or automatic generated Lod levels, - // but now we can mix them. If it is mixed, we can't export it to older mesh formats. - String compatibleLodStrategyName(String lodStrategyName); - virtual bool isLodMixed(const Mesh* pMesh); - size_t calcLodLevelSize(const Mesh* pMesh) override; - size_t calcLodUsageManualSize(const MeshLodUsage& usage) override; - size_t calcLodUsageGeneratedSize(const Mesh* pMesh, const MeshLodUsage& usage, unsigned short lodNum) override; - size_t calcLodUsageGeneratedSubmeshSize(const SubMesh* submesh, unsigned short lodNum) override; -#if !OGRE_NO_MESHLOD - void writeLodLevel(const Mesh* pMesh) override; - void writeLodUsageGenerated(const Mesh* pMesh, const MeshLodUsage& usage, unsigned short lodNum) override; - void writeLodUsageGeneratedSubmesh(const SubMesh* submesh, unsigned short lodNum) override; - void writeLodUsageManual(const MeshLodUsage& usage) override; - - void readMeshLodUsageGenerated(const DataStreamPtr& stream, Mesh* pMesh, - unsigned short lodNum, MeshLodUsage& usage) override; - void readMeshLodUsageManual(const DataStreamPtr& stream, Mesh* pMesh, unsigned short lodNum, MeshLodUsage& usage) override; -#endif - void readMeshLodLevel(const DataStreamPtr& stream, Mesh* pMesh) override; - void enableValidation() override; - }; - - /** Class for providing backwards-compatibility for loading version 1.41 of the .mesh format. - This mesh format was used from Ogre v1.7. - */ - class _OgrePrivate MeshSerializerImpl_v1_41 : public MeshSerializerImpl_v1_8 - { - public: - MeshSerializerImpl_v1_41(); - ~MeshSerializerImpl_v1_41(); - protected: - void writeMorphKeyframe(const VertexMorphKeyFrame* kf, size_t vertexCount) override; - void readMorphKeyFrame(const DataStreamPtr& stream, Mesh* pMesh, VertexAnimationTrack* track) override; - void writePose(const Pose* pose) override; - void readPose(const DataStreamPtr& stream, Mesh* pMesh) override; - size_t calcMorphKeyframeSize(const VertexMorphKeyFrame* kf, size_t vertexCount) override; - size_t calcPoseSize(const Pose* pose) override; - size_t calcPoseVertexSize(void); - using MeshSerializerImpl::calcPoseVertexSize; - }; - - /** Class for providing backwards-compatibility for loading version 1.4 of the .mesh format. - This mesh format was used from Ogre v1.4. - */ - class _OgrePrivate MeshSerializerImpl_v1_4 : public MeshSerializerImpl_v1_41 - { - public: - MeshSerializerImpl_v1_4(); - ~MeshSerializerImpl_v1_4(); - protected: - size_t calcLodLevelSize(const Mesh* pMesh) override; - void readMeshLodLevel(const DataStreamPtr& stream, Mesh* pMesh) override; -#if !OGRE_NO_MESHLOD - void writeLodLevel(const Mesh* pMesh) override; - void writeLodUsageGenerated(const Mesh* pMesh, const MeshLodUsage& usage, unsigned short lodNum) override; -#endif - }; - - /** Class for providing backwards-compatibility for loading version 1.3 of the .mesh format. - This mesh format was used from Ogre v1.0 (and some pre-releases) - */ - class _OgrePrivate MeshSerializerImpl_v1_3 : public MeshSerializerImpl_v1_4 - { - public: - MeshSerializerImpl_v1_3(); - ~MeshSerializerImpl_v1_3(); - protected: - void readEdgeListLodInfo(const DataStreamPtr& stream, EdgeData* edgeData) override; - - /// Reorganise triangles of the edge list to group by vertex set - virtual void reorganiseTriangles(EdgeData* edgeData); - - void writeEdgeList(const Mesh* pMesh) override; - size_t calcEdgeListLodSize(const EdgeData* edgeData, bool isManual) override; - size_t calcEdgeGroupSize(const EdgeData::EdgeGroup& group) override; - }; - - /** Class for providing backwards-compatibility for loading version 1.2 of the .mesh format. - This is a LEGACY FORMAT that pre-dates version Ogre 1.0 - */ - class _OgrePrivate MeshSerializerImpl_v1_2 : public MeshSerializerImpl_v1_3 - { - public: - MeshSerializerImpl_v1_2(); - ~MeshSerializerImpl_v1_2(); - protected: - void readMesh(const DataStreamPtr& stream, Mesh* pMesh, MeshSerializerListener *listener) override; - void readGeometry(const DataStreamPtr& stream, Mesh* pMesh, VertexData* dest) override; - virtual void readGeometryPositions(unsigned short bindIdx, const DataStreamPtr& stream, - Mesh* pMesh, VertexData* dest); - virtual void readGeometryNormals(unsigned short bindIdx, const DataStreamPtr& stream, - Mesh* pMesh, VertexData* dest); - virtual void readGeometryColours(unsigned short bindIdx, const DataStreamPtr& stream, - Mesh* pMesh, VertexData* dest); - virtual void readGeometryTexCoords(unsigned short bindIdx, const DataStreamPtr& stream, - Mesh* pMesh, VertexData* dest, unsigned short set); - }; - - /** Class for providing backwards-compatibility for loading version 1.1 of the .mesh format. - This is a LEGACY FORMAT that pre-dates version Ogre 1.0 - */ - class _OgrePrivate MeshSerializerImpl_v1_1 : public MeshSerializerImpl_v1_2 - { - public: - MeshSerializerImpl_v1_1(); - ~MeshSerializerImpl_v1_1(); - protected: - void readGeometryTexCoords(unsigned short bindIdx, const DataStreamPtr& stream, - Mesh* pMesh, VertexData* dest, unsigned short set) override; - }; - - /** @} */ - /** @} */ - -} - -#endif diff --git a/OgreMain/src/OgreMovableObject.cpp b/OgreMain/src/OgreMovableObject.cpp deleted file mode 100644 index 795887d7d34..00000000000 --- a/OgreMain/src/OgreMovableObject.cpp +++ /dev/null @@ -1,456 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreTagPoint.h" -#include "OgreEntity.h" -#include "OgreLodListener.h" - -namespace Ogre { - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - uint32 MovableObject::msDefaultQueryFlags = 0xFFFFFFFF; - uint32 MovableObject::msDefaultVisibilityFlags = 0xFFFFFFFF; - //----------------------------------------------------------------------- - MovableObject::MovableObject() : MovableObject(BLANKSTRING) {} - //----------------------------------------------------------------------- - MovableObject::MovableObject(const String& name) - : mName(name) - , mCreator(0) - , mManager(0) - , mParentNode(0) - , mListener(0) - , mParentIsTagPoint(false) - , mVisible(true) - , mDebugDisplay(false) - , mBeyondFarDistance(false) - , mCastShadows(true) - , mRenderQueueIDSet(false) - , mRenderQueuePrioritySet(false) - , mRenderingDisabled(false) - , mRenderQueueID(RENDER_QUEUE_MAIN) - , mRenderQueuePriority(100) - , mUpperDistance(0) - , mSquaredUpperDistance(0) - , mMinPixelSize(0) - , mQueryFlags(msDefaultQueryFlags) - , mVisibilityFlags(msDefaultVisibilityFlags) - , mLightListUpdated(0) - , mLightMask(0xFFFFFFFF) - { - if (Root::getSingletonPtr()) - mMinPixelSize = Root::getSingleton().getDefaultMinPixelSize(); - } - //----------------------------------------------------------------------- - MovableObject::~MovableObject() - { - // Call listener (note, only called if there's something to do) - if (mListener) - { - mListener->objectDestroyed(this); - } - - detachFromParent(); // this should never throw, if it does terminating is the thing to do - } - //----------------------------------------------------------------------- - void MovableObject::_notifyAttached(Node* parent, bool isTagPoint) - { - assert(!mParentNode || !parent); - - bool different = (parent != mParentNode); - - mParentNode = parent; - mParentIsTagPoint = isTagPoint; - - // Mark light list being dirty, simply decrease - // counter by one for minimise overhead - --mLightListUpdated; - - // Call listener (note, only called if there's something to do) - if (mListener && different) - { - if (mParentNode) - mListener->objectAttached(this); - else - mListener->objectDetached(this); - } - } - //----------------------------------------------------------------------- - SceneNode* MovableObject::getParentSceneNode(void) const - { - if (mParentIsTagPoint) - { - TagPoint* tp = static_cast(mParentNode); - return tp->getParentEntity()->getParentSceneNode(); - } - else - { - return static_cast(mParentNode); - } - } - //--------------------------------------------------------------------- - void MovableObject::detachFromParent(void) - { - if (isAttached()) - { - if (mParentIsTagPoint) - { - TagPoint* tp = static_cast(mParentNode); - tp->getParentEntity()->detachObjectFromBone(this); - } - else - { - SceneNode* sn = static_cast(mParentNode); - sn->detachObject(this); - } - } - } - //----------------------------------------------------------------------- - bool MovableObject::isInScene(void) const - { - if (mParentNode != 0) - { - if (mParentIsTagPoint) - { - TagPoint* tp = static_cast(mParentNode); - return tp->getParentEntity()->isInScene(); - } - else - { - SceneNode* sn = static_cast(mParentNode); - return sn->isInSceneGraph(); - } - } - else - { - return false; - } - } - //----------------------------------------------------------------------- - void MovableObject::_notifyMoved(void) - { - // Mark light list being dirty, simply decrease - // counter by one for minimise overhead - --mLightListUpdated; - - // Notify listener if exists - if (mListener) - { - mListener->objectMoved(this); - } - } - //----------------------------------------------------------------------- - bool MovableObject::isVisible(void) const - { - if (!mVisible || mBeyondFarDistance || mRenderingDisabled) - return false; - - SceneManager* sm = Root::getSingleton()._getCurrentSceneManager(); - if (sm && !(getVisibilityFlags() & sm->_getCombinedVisibilityMask())) - return false; - - return true; - } - //----------------------------------------------------------------------- - void MovableObject::_notifyCurrentCamera(Camera* cam) - { - if (mParentNode) - { - mBeyondFarDistance = false; - - if (cam->getUseRenderingDistance() && mUpperDistance > 0) - { - Real rad = getBoundingRadiusScaled(); - Real squaredDist = mParentNode->getSquaredViewDepth(cam->getLodCamera()); - - // Max distance to still render - Real maxDist = mUpperDistance + rad; - if (squaredDist > Math::Sqr(maxDist)) - { - mBeyondFarDistance = true; - } - } - - if (!mBeyondFarDistance && cam->getUseMinPixelSize() && mMinPixelSize > 0) - { - - Real pixelRatio = cam->getPixelDisplayRatio(); - - //if ratio is relative to distance than the distance at which the object should be displayed - //is the size of the radius divided by the ratio - //get the size of the entity in the world - Ogre::Vector3 objBound = getBoundingBox().getSize() * - getParentNode()->_getDerivedScale(); - - //We object are projected from 3 dimensions to 2. The shortest displayed dimension of - //as object will always be at most the second largest dimension of the 3 dimensional - //bounding box. - //The square calculation come both to get rid of minus sign and for improve speed - //in the final calculation - objBound.x = Math::Sqr(objBound.x); - objBound.y = Math::Sqr(objBound.y); - objBound.z = Math::Sqr(objBound.z); - float sqrObjMedianSize = std::max(std::max( - std::min(objBound.x,objBound.y), - std::min(objBound.x,objBound.z)), - std::min(objBound.y,objBound.z)); - - //If we have a perspective camera calculations are done relative to distance - Real sqrDistance = 1; - if (cam->getProjectionType() == PT_PERSPECTIVE) - { - sqrDistance = mParentNode->getSquaredViewDepth(cam->getLodCamera()); - } - - //Final Calculation to tell whether the object is to small - mBeyondFarDistance = sqrObjMedianSize < - sqrDistance * Math::Sqr(pixelRatio * mMinPixelSize); - } - - // Construct event object - MovableObjectLodChangedEvent evt; - evt.movableObject = this; - evt.camera = cam; - - // Notify LOD event listeners - cam->getSceneManager()->_notifyMovableObjectLodChanged(evt); - - } - - mRenderingDisabled = mListener && !mListener->objectRendering(this, cam); - } - //----------------------------------------------------------------------- - void MovableObject::setRenderQueueGroup(uint8 queueID) - { - assert(queueID <= RENDER_QUEUE_MAX && "Render queue out of range!"); - mRenderQueueID = queueID; - mRenderQueueIDSet = true; - } - - //----------------------------------------------------------------------- - void MovableObject::setRenderQueueGroupAndPriority(uint8 queueID, ushort priority) - { - setRenderQueueGroup(queueID); - mRenderQueuePriority = priority; - mRenderQueuePrioritySet = true; - - } - - //----------------------------------------------------------------------- - const Affine3& MovableObject::_getParentNodeFullTransform(void) const - { - - if(mParentNode) - { - // object attached to a sceneNode - return mParentNode->_getFullTransform(); - } - // fallback - return Affine3::IDENTITY; - } - - Real MovableObject::getBoundingRadiusScaled() const - { - const Vector3& scl = mParentNode->_getDerivedScale(); - Real factor = std::max(std::max(std::abs(scl.x), std::abs(scl.y)), std::abs(scl.z)); - return getBoundingRadius() * factor; - } - - //----------------------------------------------------------------------- - const AxisAlignedBox& MovableObject::getWorldBoundingBox(bool derive) const - { - if (derive) - { - mWorldAABB = this->getBoundingBox(); - mWorldAABB.transform(_getParentNodeFullTransform()); - } - - return mWorldAABB; - - } - //----------------------------------------------------------------------- - const Sphere& MovableObject::getWorldBoundingSphere(bool derive) const - { - if (derive) - { - mWorldBoundingSphere.setRadius(getBoundingRadiusScaled()); - mWorldBoundingSphere.setCenter(mParentNode->_getDerivedPosition()); - } - return mWorldBoundingSphere; - } - //----------------------------------------------------------------------- - const LightList& MovableObject::queryLights(void) const - { - // Try listener first - if (mListener) - { - const LightList* lightList = - mListener->objectQueryLights(this); - if (lightList) - { - return *lightList; - } - } - - // Query from parent entity if exists - if (mParentIsTagPoint) - { - TagPoint* tp = static_cast(mParentNode); - return tp->getParentEntity()->queryLights(); - } - - if (mParentNode) - { - SceneNode* sn = static_cast(mParentNode); - - // Make sure we only update this only if need. - ulong frame = sn->getCreator()->_getLightsDirtyCounter(); - if (mLightListUpdated != frame) - { - mLightListUpdated = frame; - - sn->findLights(mLightList, getBoundingRadiusScaled(), this->getLightMask()); - } - } - else - { - mLightList.clear(); - } - - return mLightList; - } - //----------------------------------------------------------------------- - const ShadowRenderableList& MovableObject::getShadowVolumeRenderableList( - const Light* light, const HardwareIndexBufferPtr& indexBuffer, size_t& indexBufferUsedSize, - float extrusionDist, int flags) - { - static ShadowRenderableList dummyList; - return dummyList; - } - //----------------------------------------------------------------------- - const AxisAlignedBox& MovableObject::getLightCapBounds(void) const - { - // Same as original bounds - return getWorldBoundingBox(); - } - //----------------------------------------------------------------------- - const AxisAlignedBox& MovableObject::getDarkCapBounds(const Light& light, Real extrusionDist) const - { - // Extrude own light cap bounds - mWorldDarkCapBounds = getLightCapBounds(); - this->extrudeBounds(mWorldDarkCapBounds, light.getAs4DVector(), - extrusionDist); - return mWorldDarkCapBounds; - - } - //----------------------------------------------------------------------- - Real MovableObject::getPointExtrusionDistance(const Light* l) const - { - if (mParentNode) - { - // exclude distance from the light to the shadow caster from the extrusion - Real extrusionDistance = l->getAttenuationRange() - getWorldBoundingBox().distance(l->getDerivedPosition()); - if(extrusionDistance < 0) - extrusionDistance = 0; - - // Take into account that extrusion would be done in object-space, - // and non-uniformly scaled objects would cast non-uniformly scaled shadows. - Matrix3 m3 = _getParentNodeFullTransform().linear(); - Real c0 = m3.GetColumn(0).squaredLength(), c1 = m3.GetColumn(1).squaredLength(), c2 = m3.GetColumn(2).squaredLength(); - Real minScale = Math::Sqrt(std::min(std::min(c0, c1), c2)); - Real maxScale = Math::Sqrt(std::max(std::max(c0, c1), c2)); - if(minScale > 0.0) - extrusionDistance *= (maxScale / minScale); - - return extrusionDistance; - } - else - { - return 0; - } - } - //----------------------------------------------------------------------- - uint32 MovableObject::getTypeFlags(void) const - { - if (mCreator) - { - return mCreator->getTypeFlags(); - } - else - { - return 0xFFFFFFFF; - } - } - //--------------------------------------------------------------------- - void MovableObject::setLightMask(uint32 lightMask) - { - this->mLightMask = lightMask; - //make sure to request a new light list from the scene manager if mask changed - mLightListUpdated = 0; - } - //--------------------------------------------------------------------- - class MORecvShadVisitor : public Renderable::Visitor - { - public: - bool anyReceiveShadows; - MORecvShadVisitor() : anyReceiveShadows(false) - { - - } - void visit(Renderable* rend, ushort lodIndex, bool isDebug, - Any* pAny = 0) override - { - Technique* tech = rend->getTechnique(); - bool techReceivesShadows = tech && tech->getParent()->getReceiveShadows(); - anyReceiveShadows = anyReceiveShadows || - techReceivesShadows || !tech; - } - }; - //--------------------------------------------------------------------- - bool MovableObject::getReceivesShadows() - { - MORecvShadVisitor visitor; - visitRenderables(&visitor); - return visitor.anyReceiveShadows; - - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - MovableObject* MovableObjectFactory::createInstance( - const String& name, SceneManager* manager, - const NameValuePairList* params) - { - MovableObject* m = createInstanceImpl(name, params); - m->_notifyCreator(this); - m->_notifyManager(manager); - return m; - } - - -} - diff --git a/OgreMain/src/OgreMovablePlane.cpp b/OgreMain/src/OgreMovablePlane.cpp deleted file mode 100644 index 892ed48a854..00000000000 --- a/OgreMain/src/OgreMovablePlane.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreMovablePlane.h" - -namespace Ogre { - - const String MOT_MOVABLE_PLANE = "MovablePlane"; - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - MovablePlane::MovablePlane(const String& name) : Plane(), MovableObject(name), - mLastTranslate(Vector3::ZERO), - mLastRotate(Quaternion::IDENTITY), - mDirty(true) - { - } - //----------------------------------------------------------------------- - MovablePlane::MovablePlane (const Plane& rhs) : Plane(rhs), - mLastTranslate(Vector3::ZERO), mLastRotate(Quaternion::IDENTITY), - mDirty(true) - { - } - //----------------------------------------------------------------------- - MovablePlane::MovablePlane (const Vector3& rkNormal, Real fConstant) - : Plane (rkNormal, fConstant), mLastTranslate(Vector3::ZERO), - mLastRotate(Quaternion::IDENTITY), mDirty(true) - { - } - //----------------------------------------------------------------------- - MovablePlane::MovablePlane (const Vector3& rkNormal, const Vector3& rkPoint) - : Plane(rkNormal, rkPoint), mLastTranslate(Vector3::ZERO), - mLastRotate(Quaternion::IDENTITY), mDirty(true) - { - } - //----------------------------------------------------------------------- - MovablePlane::MovablePlane (const Vector3& rkPoint0, const Vector3& rkPoint1, - const Vector3& rkPoint2) - : Plane(rkPoint0, rkPoint1, rkPoint2), mLastTranslate(Vector3::ZERO), - mLastRotate(Quaternion::IDENTITY), mDirty(true) - { - } - //----------------------------------------------------------------------- - const Plane& MovablePlane::_getDerivedPlane(void) const - { - if (mParentNode) - { - if (mDirty || - !(mParentNode->_getDerivedOrientation() == mLastRotate && - mParentNode->_getDerivedPosition() == mLastTranslate)) - { - mLastRotate = mParentNode->_getDerivedOrientation(); - mLastTranslate = mParentNode->_getDerivedPosition(); - // Rotate normal - mDerivedPlane.normal = mLastRotate * normal; - // d remains the same in rotation, since rotation happens first - mDerivedPlane.d = d; - // Add on the effect of the translation (project onto new normal) - mDerivedPlane.d -= mDerivedPlane.normal.dotProduct(mLastTranslate); - - mDirty = false; - - } - } - else - { - return *this; - } - - return mDerivedPlane; - } - //----------------------------------------------------------------------- - const String& MovablePlane::getMovableType(void) const - { - return MOT_MOVABLE_PLANE; - } -} diff --git a/OgreMain/src/OgreMurmurHash3.cpp b/OgreMain/src/OgreMurmurHash3.cpp deleted file mode 100644 index c3f8b3b15ac..00000000000 --- a/OgreMain/src/OgreMurmurHash3.cpp +++ /dev/null @@ -1,337 +0,0 @@ -//----------------------------------------------------------------------------- -// MurmurHash3 was written by Austin Appleby, and is placed in the public -// domain. The author hereby disclaims copyright to this source code. - -// Note - The x86 and x64 versions do _not_ produce the same results, as the -// algorithms are optimized for their respective platforms. You can still -// compile and run any of them on any platform, but your performance with the -// non-native version will be less than optimal. - -#include "OgreStableHeaders.h" - -//----------------------------------------------------------------------------- -// Platform-specific functions and macros - -// Microsoft Visual Studio - -#if defined(_MSC_VER) - -#define FORCE_INLINE __forceinline - -#include - -#define ROTL32(x,y) _rotl(x,y) -#define ROTL64(x,y) _rotl64(x,y) - -#define BIG_CONSTANT(x) (x) - -// Other compilers - -#else // defined(_MSC_VER) - -#define FORCE_INLINE inline __attribute__((always_inline)) - -inline uint32_t rotl32 ( uint32_t x, int8_t r ) -{ - return (x << r) | (x >> (32 - r)); -} - -inline uint64_t rotl64 ( uint64_t x, int8_t r ) -{ - return (x << r) | (x >> (64 - r)); -} - -#define ROTL32(x,y) rotl32(x,y) -#define ROTL64(x,y) rotl64(x,y) - -#define BIG_CONSTANT(x) (x##LLU) - -#endif // !defined(_MSC_VER) - -namespace Ogre -{ -//----------------------------------------------------------------------------- -// Block read - if your platform needs to do endian-swapping or can only -// handle aligned reads, do the conversion here - -FORCE_INLINE uint32_t getblock32 ( const uint32_t * p, int i ) -{ - return p[i]; -} - -FORCE_INLINE uint64_t getblock64 ( const uint64_t * p, int i ) -{ - return p[i]; -} - -//----------------------------------------------------------------------------- -// Finalization mix - force all bits of a hash block to avalanche - -FORCE_INLINE uint32_t fmix32 ( uint32_t h ) -{ - h ^= h >> 16; - h *= 0x85ebca6b; - h ^= h >> 13; - h *= 0xc2b2ae35; - h ^= h >> 16; - - return h; -} - -//---------- - -FORCE_INLINE uint64_t fmix64 ( uint64_t k ) -{ - k ^= k >> 33; - k *= BIG_CONSTANT(0xff51afd7ed558ccd); - k ^= k >> 33; - k *= BIG_CONSTANT(0xc4ceb9fe1a85ec53); - k ^= k >> 33; - - return k; -} - -//----------------------------------------------------------------------------- - -void _OgreExport MurmurHash3_x86_32 ( const void * key, const size_t len, - uint32_t seed, void * out ) -{ - const uint8_t * data = (const uint8_t*)key; - const int nblocks = len / 4; - - uint32_t h1 = seed; - - const uint32_t c1 = 0xcc9e2d51; - const uint32_t c2 = 0x1b873593; - - //---------- - // body - - const uint32_t * blocks = (const uint32_t *)(data + nblocks*4); - - for(int i = -nblocks; i; i++) - { - uint32_t k1 = getblock32(blocks,i); - - k1 *= c1; - k1 = ROTL32(k1,15); - k1 *= c2; - - h1 ^= k1; - h1 = ROTL32(h1,13); - h1 = h1*5+0xe6546b64; - } - - //---------- - // tail - - const uint8_t * tail = (const uint8_t*)(data + nblocks*4); - - uint32_t k1 = 0; - - switch(len & 3) - { - case 3: k1 ^= tail[2] << 16; OGRE_FALLTHROUGH; - case 2: k1 ^= tail[1] << 8; OGRE_FALLTHROUGH; - case 1: k1 ^= tail[0]; - k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1; - }; - - //---------- - // finalization - - h1 ^= len; - - h1 = fmix32(h1); - - *(uint32_t*)out = h1; -} - -//----------------------------------------------------------------------------- - -void _OgreExport MurmurHash3_x86_128 ( const void * key, const size_t len, - uint32_t seed, void * out ) -{ - const uint8_t * data = (const uint8_t*)key; - const int nblocks = len / 16; - - uint32_t h1 = seed; - uint32_t h2 = seed; - uint32_t h3 = seed; - uint32_t h4 = seed; - - const uint32_t c1 = 0x239b961b; - const uint32_t c2 = 0xab0e9789; - const uint32_t c3 = 0x38b34ae5; - const uint32_t c4 = 0xa1e38b93; - - //---------- - // body - - const uint32_t * blocks = (const uint32_t *)(data + nblocks*16); - - for(int i = -nblocks; i; i++) - { - uint32_t k1 = getblock32(blocks,i*4+0); - uint32_t k2 = getblock32(blocks,i*4+1); - uint32_t k3 = getblock32(blocks,i*4+2); - uint32_t k4 = getblock32(blocks,i*4+3); - - k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1; - - h1 = ROTL32(h1,19); h1 += h2; h1 = h1*5+0x561ccd1b; - - k2 *= c2; k2 = ROTL32(k2,16); k2 *= c3; h2 ^= k2; - - h2 = ROTL32(h2,17); h2 += h3; h2 = h2*5+0x0bcaa747; - - k3 *= c3; k3 = ROTL32(k3,17); k3 *= c4; h3 ^= k3; - - h3 = ROTL32(h3,15); h3 += h4; h3 = h3*5+0x96cd1c35; - - k4 *= c4; k4 = ROTL32(k4,18); k4 *= c1; h4 ^= k4; - - h4 = ROTL32(h4,13); h4 += h1; h4 = h4*5+0x32ac3b17; - } - - //---------- - // tail - - const uint8_t * tail = (const uint8_t*)(data + nblocks*16); - - uint32_t k1 = 0; - uint32_t k2 = 0; - uint32_t k3 = 0; - uint32_t k4 = 0; - - switch(len & 15) - { - case 15: k4 ^= tail[14] << 16; OGRE_FALLTHROUGH; - case 14: k4 ^= tail[13] << 8; OGRE_FALLTHROUGH; - case 13: k4 ^= tail[12] << 0; - k4 *= c4; k4 = ROTL32(k4,18); k4 *= c1; h4 ^= k4; OGRE_FALLTHROUGH; - - case 12: k3 ^= tail[11] << 24; OGRE_FALLTHROUGH; - case 11: k3 ^= tail[10] << 16; OGRE_FALLTHROUGH; - case 10: k3 ^= tail[ 9] << 8; OGRE_FALLTHROUGH; - case 9: k3 ^= tail[ 8] << 0; - k3 *= c3; k3 = ROTL32(k3,17); k3 *= c4; h3 ^= k3; OGRE_FALLTHROUGH; - - case 8: k2 ^= tail[ 7] << 24; OGRE_FALLTHROUGH; - case 7: k2 ^= tail[ 6] << 16; OGRE_FALLTHROUGH; - case 6: k2 ^= tail[ 5] << 8; OGRE_FALLTHROUGH; - case 5: k2 ^= tail[ 4] << 0; - k2 *= c2; k2 = ROTL32(k2,16); k2 *= c3; h2 ^= k2; OGRE_FALLTHROUGH; - - case 4: k1 ^= tail[ 3] << 24; OGRE_FALLTHROUGH; - case 3: k1 ^= tail[ 2] << 16; OGRE_FALLTHROUGH; - case 2: k1 ^= tail[ 1] << 8; OGRE_FALLTHROUGH; - case 1: k1 ^= tail[ 0] << 0; - k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1; - }; - - //---------- - // finalization - - h1 ^= len; h2 ^= len; h3 ^= len; h4 ^= len; - - h1 += h2; h1 += h3; h1 += h4; - h2 += h1; h3 += h1; h4 += h1; - - h1 = fmix32(h1); - h2 = fmix32(h2); - h3 = fmix32(h3); - h4 = fmix32(h4); - - h1 += h2; h1 += h3; h1 += h4; - h2 += h1; h3 += h1; h4 += h1; - - ((uint32_t*)out)[0] = h1; - ((uint32_t*)out)[1] = h2; - ((uint32_t*)out)[2] = h3; - ((uint32_t*)out)[3] = h4; -} - -//----------------------------------------------------------------------------- - -void _OgreExport MurmurHash3_x64_128 ( const void * key, const size_t len, - const uint32_t seed, void * out ) -{ - const uint8_t * data = (const uint8_t*)key; - const int nblocks = len / 16; - - uint64_t h1 = seed; - uint64_t h2 = seed; - - const uint64_t c1 = BIG_CONSTANT(0x87c37b91114253d5); - const uint64_t c2 = BIG_CONSTANT(0x4cf5ad432745937f); - - //---------- - // body - - const uint64_t * blocks = (const uint64_t *)(data); - - for(int i = 0; i < nblocks; i++) - { - uint64_t k1 = getblock64(blocks,i*2+0); - uint64_t k2 = getblock64(blocks,i*2+1); - - k1 *= c1; k1 = ROTL64(k1,31); k1 *= c2; h1 ^= k1; - - h1 = ROTL64(h1,27); h1 += h2; h1 = h1*5+0x52dce729; - - k2 *= c2; k2 = ROTL64(k2,33); k2 *= c1; h2 ^= k2; - - h2 = ROTL64(h2,31); h2 += h1; h2 = h2*5+0x38495ab5; - } - - //---------- - // tail - - const uint8_t * tail = (const uint8_t*)(data + nblocks*16); - - uint64_t k1 = 0; - uint64_t k2 = 0; - - switch(len & 15) - { - case 15: k2 ^= ((uint64_t)tail[14]) << 48; OGRE_FALLTHROUGH; - case 14: k2 ^= ((uint64_t)tail[13]) << 40; OGRE_FALLTHROUGH; - case 13: k2 ^= ((uint64_t)tail[12]) << 32; OGRE_FALLTHROUGH; - case 12: k2 ^= ((uint64_t)tail[11]) << 24; OGRE_FALLTHROUGH; - case 11: k2 ^= ((uint64_t)tail[10]) << 16; OGRE_FALLTHROUGH; - case 10: k2 ^= ((uint64_t)tail[ 9]) << 8; OGRE_FALLTHROUGH; - case 9: k2 ^= ((uint64_t)tail[ 8]) << 0; - k2 *= c2; k2 = ROTL64(k2,33); k2 *= c1; h2 ^= k2; OGRE_FALLTHROUGH; - - case 8: k1 ^= ((uint64_t)tail[ 7]) << 56; OGRE_FALLTHROUGH; - case 7: k1 ^= ((uint64_t)tail[ 6]) << 48; OGRE_FALLTHROUGH; - case 6: k1 ^= ((uint64_t)tail[ 5]) << 40; OGRE_FALLTHROUGH; - case 5: k1 ^= ((uint64_t)tail[ 4]) << 32; OGRE_FALLTHROUGH; - case 4: k1 ^= ((uint64_t)tail[ 3]) << 24; OGRE_FALLTHROUGH; - case 3: k1 ^= ((uint64_t)tail[ 2]) << 16; OGRE_FALLTHROUGH; - case 2: k1 ^= ((uint64_t)tail[ 1]) << 8; OGRE_FALLTHROUGH; - case 1: k1 ^= ((uint64_t)tail[ 0]) << 0; - k1 *= c1; k1 = ROTL64(k1,31); k1 *= c2; h1 ^= k1; - }; - - //---------- - // finalization - - h1 ^= len; h2 ^= len; - - h1 += h2; - h2 += h1; - - h1 = fmix64(h1); - h2 = fmix64(h2); - - h1 += h2; - h2 += h1; - - ((uint64_t*)out)[0] = h1; - ((uint64_t*)out)[1] = h2; -} - -//----------------------------------------------------------------------------- -} diff --git a/OgreMain/src/OgreNode.cpp b/OgreMain/src/OgreNode.cpp deleted file mode 100644 index 9ae051bf528..00000000000 --- a/OgreMain/src/OgreNode.cpp +++ /dev/null @@ -1,746 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -namespace Ogre { - - Node::QueuedUpdates Node::msQueuedUpdates; - //----------------------------------------------------------------------- - Node::Node() : Node(BLANKSTRING) {} - //----------------------------------------------------------------------- - Node::Node(const String& name) - :mParent(0), - mName(name), - mNeedParentUpdate(false), - mNeedChildUpdate(false), - mParentNotified(false), - mQueuedForUpdate(false), - mInheritOrientation(true), - mInheritScale(true), - mCachedTransformOutOfDate(true), - mOrientation(Quaternion::IDENTITY), - mPosition(Vector3::ZERO), - mScale(Vector3::UNIT_SCALE), - mDerivedOrientation(Quaternion::IDENTITY), - mDerivedPosition(Vector3::ZERO), - mDerivedScale(Vector3::UNIT_SCALE), - mInitialPosition(Vector3::ZERO), - mInitialOrientation(Quaternion::IDENTITY), - mInitialScale(Vector3::UNIT_SCALE), - mListener(0) - { - needUpdate(); - } - - //----------------------------------------------------------------------- - Node::~Node() - { - // Call listener (note, only called if there's something to do) - if (mListener) - { - mListener->nodeDestroyed(this); - } - - removeAllChildren(); - if(mParent) - mParent->removeChild(this); - - if (mQueuedForUpdate) - { - // Erase from queued updates - QueuedUpdates::iterator it = - std::find(msQueuedUpdates.begin(), msQueuedUpdates.end(), this); - assert(it != msQueuedUpdates.end()); - if (it != msQueuedUpdates.end()) - { - // Optimised algorithm to erase an element from unordered vector. - *it = msQueuedUpdates.back(); - msQueuedUpdates.pop_back(); - } - } - - } - - //----------------------------------------------------------------------- - void Node::setParent(Node* parent) - { - bool different = (parent != mParent); - - mParent = parent; - // Request update from parent - mParentNotified = false ; - needUpdate(); - - // Call listener (note, only called if there's something to do) - if (mListener && different) - { - if (mParent) - mListener->nodeAttached(this); - else - mListener->nodeDetached(this); - } - - } - - //----------------------------------------------------------------------- - const Affine3& Node::_getFullTransform(void) const - { - if (mCachedTransformOutOfDate) - { -#if OGRE_NODE_INHERIT_TRANSFORM - Affine3 tr; - tr.makeTransform(mPosition, mScale, mOrientation); - - if(mParent == NULL) - { - mCachedTransform = tr; - } - else if(mInheritOrientation && mInheritScale) // everything is inherited - { - mCachedTransform = mParent->_getFullTransform() * tr; - } - else if(!mInheritOrientation && !mInheritScale) // only position is inherited - { - mCachedTransform = tr; - mCachedTransform.setTrans(tr.getTrans() + mParent->_getFullTransform().getTrans()); - } - else // shear is inherited together with orientation, controlled by mInheritOrientation - { - const Affine3& parentTr = mParent->_getFullTransform(); - Vector3 parentScale( - parentTr.transformDirection(Vector3::UNIT_X).length(), - parentTr.transformDirection(Vector3::UNIT_Y).length(), - parentTr.transformDirection(Vector3::UNIT_Z).length()); - - assert(mInheritOrientation ^ mInheritScale); - mCachedTransform = (mInheritOrientation ? Affine3::getScale(1.0f / parentScale) * parentTr : Affine3::getScale(parentScale)) * tr; - } -#else - // Use derived values - mCachedTransform.makeTransform( - _getDerivedPosition(), - _getDerivedScale(), - _getDerivedOrientation()); -#endif - mCachedTransformOutOfDate = false; - } - return mCachedTransform; - } - //----------------------------------------------------------------------- - void Node::_update(bool updateChildren, bool parentHasChanged) - { - // always clear information about parent notification - mParentNotified = false; - - // See if we should process everyone - if (mNeedParentUpdate || parentHasChanged) - { - // Update transforms from parent - _updateFromParent(); - } - - if(updateChildren) - { - if (mNeedChildUpdate || parentHasChanged) - { - ChildNodeMap::iterator it, itend; - itend = mChildren.end(); - for (it = mChildren.begin(); it != itend; ++it) - { - Node* child = *it; - child->_update(true, true); - } - } - else - { - // Just update selected children - ChildUpdateSet::iterator it, itend; - itend = mChildrenToUpdate.end(); - for(it = mChildrenToUpdate.begin(); it != itend; ++it) - { - Node* child = *it; - child->_update(true, false); - } - - } - - mChildrenToUpdate.clear(); - mNeedChildUpdate = false; - } - } - //----------------------------------------------------------------------- - void Node::_updateFromParent(void) const - { - updateFromParentImpl(); - - // Call listener (note, this method only called if there's something to do) - if (mListener) - { - mListener->nodeUpdated(this); - } - } - //----------------------------------------------------------------------- - void Node::updateFromParentImpl(void) const - { - mCachedTransformOutOfDate = true; - - if (mParent) - { -#if OGRE_NODE_INHERIT_TRANSFORM - // Decompose full transform to position, orientation and scale, shear is lost here. - _getFullTransform().decomposition(mDerivedPosition, mDerivedScale, mDerivedOrientation); -#else - // Update orientation - const Quaternion& parentOrientation = mParent->_getDerivedOrientation(); - if (mInheritOrientation) - { - // Combine orientation with that of parent - mDerivedOrientation = parentOrientation * mOrientation; - } - else - { - // No inheritance - mDerivedOrientation = mOrientation; - } - - // Update scale - const Vector3& parentScale = mParent->_getDerivedScale(); - if (mInheritScale) - { - // Scale own position by parent scale, NB just combine - // as equivalent axes, no shearing - mDerivedScale = parentScale * mScale; - } - else - { - // No inheritance - mDerivedScale = mScale; - } - - // Change position vector based on parent's orientation & scale - mDerivedPosition = parentOrientation * (parentScale * mPosition); - - // Add altered position vector to parents - mDerivedPosition += mParent->_getDerivedPosition(); -#endif - } - else - { - // Root node, no parent - mDerivedOrientation = mOrientation; - mDerivedPosition = mPosition; - mDerivedScale = mScale; - } - - mNeedParentUpdate = false; - - } - //----------------------------------------------------------------------- - Node* Node::createChild(const Vector3& inTranslate, const Quaternion& inRotate) - { - Node* newNode = createChildImpl(); - newNode->setPosition(inTranslate); - newNode->setOrientation(inRotate); - this->addChild(newNode); - - return newNode; - } - //----------------------------------------------------------------------- - Node* Node::createChild(const String& name, const Vector3& inTranslate, const Quaternion& inRotate) - { - OgreAssert(!name.empty(), ""); - Node* newNode = createChildImpl(name); - newNode->setPosition(inTranslate); - newNode->setOrientation(inRotate); - this->addChild(newNode); - - return newNode; - } - //----------------------------------------------------------------------- - void Node::addChild(Node* child) - { - if (child->mParent) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Node '" + child->getName() + "' already was a child of '" + - child->mParent->getName() + "'.", - "Node::addChild"); - } - - mChildren.push_back(child); - child->setParent(this); - - } - //----------------------------------------------------------------------- - Node* Node::getChild(unsigned short index) const - { - if( index < mChildren.size() ) - { - return mChildren[index]; - } - else - return NULL; - } - //----------------------------------------------------------------------- - Node* Node::removeChild(unsigned short index) - { - OgreAssert(index < mChildren.size(), ""); - - ChildNodeMap::iterator i = mChildren.begin(); - i += index; - Node* ret = *i; - - // cancel any pending update - cancelUpdate(ret); - - std::swap(*i, mChildren.back()); - mChildren.pop_back(); - ret->setParent(NULL); - return ret; - } - //----------------------------------------------------------------------- - Node* Node::removeChild(Node* child) - { - if (child) - { - ChildNodeMap::iterator i = std::find(mChildren.begin(), mChildren.end(), child); - if(i != mChildren.end() && *i == child) - { - // cancel any pending update - cancelUpdate(child); - - std::swap(*i, mChildren.back()); - mChildren.pop_back(); - child->setParent(NULL); - } - } - return child; - } - - //----------------------------------------------------------------------- - void Node::setOrientation( const Quaternion & q ) - { -#ifndef OGRE_FAST_MATH - OgreAssertDbg(!q.isNaN(), "Invalid orientation supplied as parameter"); -#endif - mOrientation = q; - mOrientation.normalise(); - needUpdate(); - } - //----------------------------------------------------------------------- - void Node::setOrientation( Real w, Real x, Real y, Real z) - { - setOrientation(Quaternion(w, x, y, z)); - } - //----------------------------------------------------------------------- - void Node::resetOrientation(void) - { - mOrientation = Quaternion::IDENTITY; - needUpdate(); - } - - //----------------------------------------------------------------------- - void Node::setPosition(const Vector3& pos) - { -#ifndef OGRE_FAST_MATH - assert(!pos.isNaN() && "Invalid vector supplied as parameter"); -#endif - mPosition = pos; - needUpdate(); - } - - //----------------------------------------------------------------------- - Matrix3 Node::getLocalAxes(void) const - { - Matrix3 ret; - mOrientation.ToRotationMatrix(ret); - return ret; - } - - //----------------------------------------------------------------------- - void Node::translate(const Vector3& d, TransformSpace relativeTo) - { - switch(relativeTo) - { - case TS_LOCAL: - // position is relative to parent so transform downwards - mPosition += mOrientation * d; - break; - case TS_WORLD: - // position is relative to parent so transform upwards - if (mParent) - { - mPosition += mParent->convertWorldToLocalDirection(d, true); - } - else - { - mPosition += d; - } - break; - case TS_PARENT: - mPosition += d; - break; - } - needUpdate(); - - } - //----------------------------------------------------------------------- - void Node::rotate(const Quaternion& q, TransformSpace relativeTo) - { - switch(relativeTo) - { - case TS_PARENT: - // Rotations are normally relative to local axes, transform up - mOrientation = q * mOrientation; - break; - case TS_WORLD: - // Rotations are normally relative to local axes, transform up - mOrientation = mOrientation * _getDerivedOrientation().Inverse() - * q * _getDerivedOrientation(); - break; - case TS_LOCAL: - // Note the order of the mult, i.e. q comes after - mOrientation = mOrientation * q; - break; - } - - // Normalise quaternion to avoid drift - mOrientation.normalise(); - - needUpdate(); - } - - - //----------------------------------------------------------------------- - void Node::_setDerivedPosition( const Vector3& pos ) - { - //find where the node would end up in parent's local space - if(mParent) - setPosition( mParent->convertWorldToLocalPosition( pos ) ); - } - //----------------------------------------------------------------------- - void Node::_setDerivedOrientation( const Quaternion& q ) - { - //find where the node would end up in parent's local space - if(mParent) - setOrientation( mParent->convertWorldToLocalOrientation( q ) ); - } - - //----------------------------------------------------------------------- - const Quaternion & Node::_getDerivedOrientation(void) const - { - if (mNeedParentUpdate) - { - _updateFromParent(); - } - return mDerivedOrientation; - } - //----------------------------------------------------------------------- - const Vector3 & Node::_getDerivedPosition(void) const - { - if (mNeedParentUpdate) - { - _updateFromParent(); - } - return mDerivedPosition; - } - //----------------------------------------------------------------------- - const Vector3 & Node::_getDerivedScale(void) const - { - if (mNeedParentUpdate) - { - _updateFromParent(); - } - return mDerivedScale; - } - //----------------------------------------------------------------------- - Vector3 Node::convertWorldToLocalPosition( const Vector3 &worldPos ) - { - if (mNeedParentUpdate) - { - _updateFromParent(); - } -#if OGRE_NODE_INHERIT_TRANSFORM - return _getFullTransform().inverse() * worldPos; -#else - return mDerivedOrientation.Inverse() * (worldPos - mDerivedPosition) / mDerivedScale; -#endif - } - //----------------------------------------------------------------------- - Vector3 Node::convertLocalToWorldPosition( const Vector3 &localPos ) - { - if (mNeedParentUpdate) - { - _updateFromParent(); - } - return _getFullTransform() * localPos; - } - //----------------------------------------------------------------------- - Vector3 Node::convertWorldToLocalDirection( const Vector3 &worldDir, bool useScale ) - { - if (mNeedParentUpdate) - { - _updateFromParent(); - } - - return useScale ? -#if OGRE_NODE_INHERIT_TRANSFORM - _getFullTransform().inverseAffine().transformDirectionAffine(worldDir) : - mDerivedOrientation.Inverse() * worldDir; -#else - mDerivedOrientation.Inverse() * worldDir / mDerivedScale : - mDerivedOrientation.Inverse() * worldDir; -#endif - } - //----------------------------------------------------------------------- - Vector3 Node::convertLocalToWorldDirection( const Vector3 &localDir, bool useScale ) - { - if (mNeedParentUpdate) - { - _updateFromParent(); - } - return useScale ? _getFullTransform().linear() * localDir : mDerivedOrientation * localDir; - } - //----------------------------------------------------------------------- - Quaternion Node::convertWorldToLocalOrientation( const Quaternion &worldOrientation ) - { - if (mNeedParentUpdate) - { - _updateFromParent(); - } - return mDerivedOrientation.Inverse() * worldOrientation; - } - //----------------------------------------------------------------------- - Quaternion Node::convertLocalToWorldOrientation( const Quaternion &localOrientation ) - { - if (mNeedParentUpdate) - { - _updateFromParent(); - } - return mDerivedOrientation * localOrientation; - - } - //----------------------------------------------------------------------- - void Node::removeAllChildren(void) - { - for (auto *c : mChildren) - { - c->setParent(0); - } - mChildren.clear(); - mChildrenToUpdate.clear(); - } - //----------------------------------------------------------------------- - void Node::setScale(const Vector3& inScale) - { -#ifndef OGRE_FAST_MATH - assert(!inScale.isNaN() && "Invalid vector supplied as parameter"); -#endif - mScale = inScale; - needUpdate(); - } - //----------------------------------------------------------------------- - void Node::setInheritOrientation(bool inherit) - { - mInheritOrientation = inherit; - needUpdate(); - } - //----------------------------------------------------------------------- - void Node::setInheritScale(bool inherit) - { - mInheritScale = inherit; - needUpdate(); - } - //----------------------------------------------------------------------- - void Node::scale(const Vector3& inScale) - { - mScale = mScale * inScale; - needUpdate(); - - } - //----------------------------------------------------------------------- - void Node::scale(Real x, Real y, Real z) - { - mScale.x *= x; - mScale.y *= y; - mScale.z *= z; - needUpdate(); - - } - //----------------------------------------------------------------------- - void Node::setInitialState(void) - { - mInitialPosition = mPosition; - mInitialOrientation = mOrientation; - mInitialScale = mScale; - } - //----------------------------------------------------------------------- - void Node::resetToInitialState(void) - { - mPosition = mInitialPosition; - mOrientation = mInitialOrientation; - mScale = mInitialScale; - - needUpdate(); - } - //----------------------------------------------------------------------- - struct NodeNameExists { - const String& name; - bool operator()(const Node* mo) { - return mo->getName() == name; - } - }; - Node* Node::getChild(const String& name) const - { - NodeNameExists pred = {name}; - ChildNodeMap::const_iterator i = std::find_if(mChildren.begin(), mChildren.end(), pred); - - if (i == mChildren.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Child node named " + name + - " does not exist.", "Node::getChild"); - } - - return *i; - } - //----------------------------------------------------------------------- - Node* Node::removeChild(const String& name) - { - OgreAssert(!name.empty(), ""); - NodeNameExists pred = {name}; - ChildNodeMap::iterator i = std::find_if(mChildren.begin(), mChildren.end(), pred); - - if (i == mChildren.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Child node named " + name + - " does not exist.", "Node::removeChild"); - } - - Node* ret = *i; - - // Cancel any pending update - cancelUpdate(ret); - std::swap(*i, mChildren.back()); - mChildren.pop_back(); - ret->setParent(NULL); - - return ret; - - - } - //----------------------------------------------------------------------- - Node::ChildNodeIterator Node::getChildIterator(void) - { - return ChildNodeIterator(mChildren.begin(), mChildren.end()); - } - //----------------------------------------------------------------------- - Node::ConstChildNodeIterator Node::getChildIterator(void) const - { - return ConstChildNodeIterator(mChildren.begin(), mChildren.end()); - } - //----------------------------------------------------------------------- - Real Node::getSquaredViewDepth(const Camera* cam) const - { - Vector3 diff = _getDerivedPosition() - cam->getDerivedPosition(); - Vector3 zAxis = cam->getDerivedDirection(); - - // NB use squared length to avoid square root - return cam->getSortMode() == SM_DISTANCE ? diff.squaredLength() : Math::Sqr(zAxis.dotProduct(diff)); - } - //----------------------------------------------------------------------- - void Node::needUpdate(bool forceParentUpdate) - { - - mNeedParentUpdate = true; - mNeedChildUpdate = true; - mCachedTransformOutOfDate = true; - - // Make sure we're not root and parent hasn't been notified before - if (mParent && (!mParentNotified || forceParentUpdate)) - { - mParent->requestUpdate(this, forceParentUpdate); - mParentNotified = true ; - } - - // all children will be updated - mChildrenToUpdate.clear(); - } - //----------------------------------------------------------------------- - void Node::requestUpdate(Node* child, bool forceParentUpdate) - { - // If we're already going to update everything this doesn't matter - if (mNeedChildUpdate) - { - return; - } - - mChildrenToUpdate.insert(child); - // Request selective update of me, if we didn't do it before - if (mParent && (!mParentNotified || forceParentUpdate)) - { - mParent->requestUpdate(this, forceParentUpdate); - mParentNotified = true ; - } - - } - //----------------------------------------------------------------------- - void Node::cancelUpdate(Node* child) - { - mChildrenToUpdate.erase(child); - - // Propagate this up if we're done - if (mChildrenToUpdate.empty() && mParent && !mNeedChildUpdate) - { - mParent->cancelUpdate(this); - mParentNotified = false ; - } - } - //----------------------------------------------------------------------- - void Node::queueNeedUpdate(Node* n) - { - // Don't queue the node more than once - if (!n->mQueuedForUpdate) - { - n->mQueuedForUpdate = true; - msQueuedUpdates.push_back(n); - } - } - //----------------------------------------------------------------------- - void Node::processQueuedUpdates(void) - { - for (auto *n : msQueuedUpdates) - { - // Update, and force parent update since chances are we've ended - // up with some mixed state in there due to re-entrancy - n->mQueuedForUpdate = false; - n->needUpdate(true); - } - msQueuedUpdates.clear(); - } -} - diff --git a/OgreMain/src/OgreNumerics.cpp b/OgreMain/src/OgreNumerics.cpp deleted file mode 100644 index 8f56622ea4c..00000000000 --- a/OgreMain/src/OgreNumerics.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" -#include "OgreNumerics.h" - - -namespace Ogre -{ - bool NumericSolver::solveNxNLinearSysDestr(int n, double **coeff, double *col) - { - // we'll use standard row reduction; since we only care about systems with unique - // solutions, our job is slightly easier. more can probably be done later to improve - // precision versus this naive method - - int i, j; - - for(j=0; j OptimisedUtilList; - OptimisedUtilList mOptimisedUtils; - - public: - OptimisedUtilProfiler(void) - { - mOptimisedUtils.push_back(_getOptimisedUtilGeneral()); -#if __OGRE_HAVE_SSE || __OGRE_HAVE_NEON - //if (PlatformInformation::getCpuFeatures() & PlatformInformation::CPU_FEATURE_SSE) - { - mOptimisedUtils.push_back(_getOptimisedUtilSSE()); - } -#endif - } - - virtual void softwareVertexSkinning( - const float *srcPosPtr, float *destPosPtr, - const float *srcNormPtr, float *destNormPtr, - const float *blendWeightPtr, const unsigned char* blendIndexPtr, - const Affine3* const* blendMatrices, - size_t srcPosStride, size_t destPosStride, - size_t srcNormStride, size_t destNormStride, - size_t blendWeightStride, size_t blendIndexStride, - size_t numWeightsPerVertex, - size_t numVertices) - { - static ProfileItems results; - static size_t index; - index = Root::getSingleton().getNextFrameNumber() % mOptimisedUtils.size(); - OptimisedUtil* impl = mOptimisedUtils[index]; - ProfileItem& profile = results[index]; - - profile.begin(); - impl->softwareVertexSkinning( - srcPosPtr, destPosPtr, - srcNormPtr, destNormPtr, - blendWeightPtr, blendIndexPtr, - blendMatrices, - srcPosStride, destPosStride, - srcNormStride, destNormStride, - blendWeightStride, blendIndexStride, - numWeightsPerVertex, - numVertices); - profile.end(); - - LogManager::getSingleton().logMessage(StringUtil::format( - "OptimisedUtilProfiler: %s - impl %zu = %u avg ticks\n", __FUNCTION__, index, profile.mAvgTicks)); - // You can put break point here while running test application, to - // watch profile results. - ++index; // So we can put break point here even if in release build - } - - virtual void softwareVertexMorph( - float t, - const float *srcPos1, const float *srcPos2, - float *dstPos, - size_t pos1VSize, size_t pos2VSize, size_t dstVSize, - size_t numVertices, - bool morphNormals) - { - static ProfileItems results; - static size_t index; - index = Root::getSingleton().getNextFrameNumber() % mOptimisedUtils.size(); - OptimisedUtil* impl = mOptimisedUtils[index]; - ProfileItem& profile = results[index]; - - profile.begin(); - impl->softwareVertexMorph( - t, - srcPos1, srcPos2, - dstPos, - pos1VSize, pos2VSize, dstVSize, - numVertices, - morphNormals); - profile.end(); - - LogManager::getSingleton().logMessage(StringUtil::format( - "OptimisedUtilProfiler: %s - impl %zu = %u avg ticks\n", __FUNCTION__, index, profile.mAvgTicks)); - - // You can put break point here while running test application, to - // watch profile results. - ++index; // So we can put break point here even if in release build - } - - virtual void concatenateAffineMatrices( - const Affine3& baseMatrix, - const Affine3* srcMatrices, - Affine3* dstMatrices, - size_t numMatrices) - { - static ProfileItems results; - static size_t index; - index = Root::getSingleton().getNextFrameNumber() % mOptimisedUtils.size(); - OptimisedUtil* impl = mOptimisedUtils[index]; - ProfileItem& profile = results[index]; - - profile.begin(); - impl->concatenateAffineMatrices( - baseMatrix, - srcMatrices, - dstMatrices, - numMatrices); - profile.end(); - - LogManager::getSingleton().logMessage(StringUtil::format( - "OptimisedUtilProfiler: %s - impl %zu = %u avg ticks\n", __FUNCTION__, index, profile.mAvgTicks)); - - // You can put break point here while running test application, to - // watch profile results. - ++index; // So we can put break point here even if in release build - } - - /// @copydoc OptimisedUtil::calculateFaceNormals - virtual void calculateFaceNormals( - const float *positions, - const EdgeData::Triangle *triangles, - Vector4 *faceNormals, - size_t numTriangles) - { - static ProfileItems results; - static size_t index; - index = Root::getSingleton().getNextFrameNumber() % mOptimisedUtils.size(); - OptimisedUtil* impl = mOptimisedUtils[index]; - ProfileItem& profile = results[index]; - - profile.begin(); - impl->calculateFaceNormals( - positions, - triangles, - faceNormals, - numTriangles); - profile.end(); - - // - // Dagon SkeletonAnimation sample test results (CPU timestamp per-function call): - // - // Pentium 4 3.0G HT Athlon XP 2500+ - // - // General 657080 486494 - // SSE 223559 399495 - // - - LogManager::getSingleton().logMessage(StringUtil::format( - "OptimisedUtilProfiler: %s - impl %zu = %u avg ticks\n", __FUNCTION__, index, profile.mAvgTicks)); - - // You can put break point here while running test application, to - // watch profile results. - ++index; // So we can put break point here even if in release build - } - - /// @copydoc OptimisedUtil::calculateLightFacing - virtual void calculateLightFacing( - const Vector4& lightPos, - const Vector4* faceNormals, - char* lightFacings, - size_t numFaces) - { - static ProfileItems results; - static size_t index; - index = Root::getSingleton().getNextFrameNumber() % mOptimisedUtils.size(); - OptimisedUtil* impl = mOptimisedUtils[index]; - ProfileItem& profile = results[index]; - - profile.begin(); - impl->calculateLightFacing( - lightPos, - faceNormals, - lightFacings, - numFaces); - profile.end(); - - // - // Dagon SkeletonAnimation sample test results (CPU timestamp per-function call): - // - // Pentium 4 3.0G HT Athlon XP 2500+ - // - // General 171875 86998 - // SSE 47934 63995 - // - - LogManager::getSingleton().logMessage(StringUtil::format( - "OptimisedUtilProfiler: %s - impl %zu = %u avg ticks\n", __FUNCTION__, index, profile.mAvgTicks)); - - // You can put break point here while running test application, to - // watch profile results. - ++index; // So we can put break point here even if in release build - } - - virtual void extrudeVertices( - const Vector4& lightPos, - Real extrudeDist, - const float* srcPositions, - float* destPositions, - size_t numVertices) - { - static ProfileItems results; - static size_t index; - index = Root::getSingleton().getNextFrameNumber() % mOptimisedUtils.size(); - OptimisedUtil* impl = mOptimisedUtils[index]; - ProfileItem& profile = results[index]; - - profile.begin(); - impl->extrudeVertices( - lightPos, - extrudeDist, - srcPositions, - destPositions, - numVertices); - profile.end(); - - // - // Dagon SkeletonAnimation sample test results (CPU timestamp per-function call): - // - // Pentium 4 3.0G HT Athlon XP 2500+ - // - // Directional Light, General 38106 92306 - // Directional Light, SSE 27292 67055 - // - // Point Light, General 224209 155483 - // Point Light, SSE 56817 106663 - // - - LogManager::getSingleton().logMessage(StringUtil::format( - "OptimisedUtilProfiler: %s - impl %zu = %u avg ticks\n", __FUNCTION__, index, profile.mAvgTicks)); - - // You can put break point here while running test application, to - // watch profile results. - ++index; // So we can put break point here even if in release build - } - - }; -#endif // __DO_PROFILE__ - - //--------------------------------------------------------------------- - OptimisedUtil* OptimisedUtil::msImplementation = OptimisedUtil::_detectImplementation(); - - //--------------------------------------------------------------------- - OptimisedUtil* OptimisedUtil::_detectImplementation(void) - { - // - // Some speed test results (averaged number of CPU timestamp (RDTSC) per-function call): - // - // Dagon SkeletonAnimation sample - softwareVertexSkinning: - // - // Pentium 4 3.0G HT Athlon XP 2500+ Athlon 64 X2 Dual Core 3800+ - // - // Shared Buffers, General C 763677 462903 473038 - // Shared Buffers, Unrolled SSE 210030 *best* 369762 228328 *best* - // Shared Buffers, General SSE 286202 352412 *best* 302796 - // - // Separated Buffers, General C 762640 464840 478740 - // Separated Buffers, Unrolled SSE 219222 *best* 287992 *best* 238770 *best* - // Separated Buffers, General SSE 290129 341614 307262 - // - // PosOnly, General C 388663 257350 262831 - // PosOnly, Unrolled SSE 139814 *best* 200323 *best* 168995 *best* - // PosOnly, General SSE 172693 213704 175447 - // - // Another my own test scene - softwareVertexSkinning: - // - // Pentium P4 3.0G HT Athlon XP 2500+ - // - // Shared Buffers, General C 74527 - - // Shared Buffers, Unrolled SSE 22743 *best* - - // Shared Buffers, General SSE 28527 - - // - // - // Note that speed test appears unaligned load/store instruction version - // loss performance 5%-10% than aligned load/store version, even if both - // of them access to aligned data. Thus, we should use aligned load/store - // as soon as possible. - // - // - // We are pick up the implementation based on test results above. - // -#ifdef __DO_PROFILE__ - { - static OptimisedUtilProfiler msOptimisedUtilProfiler; - return &msOptimisedUtilProfiler; - } - -#else // !__DO_PROFILE__ - -#if __OGRE_HAVE_SSE - if (PlatformInformation::getCpuFeatures() & PlatformInformation::CPU_FEATURE_SSE) - { - return _getOptimisedUtilSSE(); - } - else -#elif __OGRE_HAVE_NEON - if (PlatformInformation::getCpuFeatures() & PlatformInformation::CPU_FEATURE_NEON) - { - return _getOptimisedUtilSSE(); - } - else -#endif // __OGRE_HAVE_SSE - { - return _getOptimisedUtilGeneral(); - } - -#endif // __DO_PROFILE__ - } - -} diff --git a/OgreMain/src/OgreOptimisedUtilGeneral.cpp b/OgreMain/src/OgreOptimisedUtilGeneral.cpp deleted file mode 100644 index ff9ad58e57c..00000000000 --- a/OgreMain/src/OgreOptimisedUtilGeneral.cpp +++ /dev/null @@ -1,376 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreOptimisedUtil.h" - -namespace Ogre { - -//------------------------------------------------------------------------- -// Local classes -//------------------------------------------------------------------------- - - /** General implementation of OptimisedUtil. - @note - Don't use this class directly, use OptimisedUtil instead. - */ - class _OgrePrivate OptimisedUtilGeneral : public OptimisedUtil - { - public: - /// @copydoc OptimisedUtil::softwareVertexSkinning - void softwareVertexSkinning( - const float *srcPosPtr, float *destPosPtr, - const float *srcNormPtr, float *destNormPtr, - const float *blendWeightPtr, const unsigned char* blendIndexPtr, - const Affine3* const* blendMatrices, - size_t srcPosStride, size_t destPosStride, - size_t srcNormStride, size_t destNormStride, - size_t blendWeightStride, size_t blendIndexStride, - size_t numWeightsPerVertex, - size_t numVertices) override; - - /// @copydoc OptimisedUtil::softwareVertexMorph - void softwareVertexMorph( - float t, - const float *srcPos1, const float *srcPos2, - float *dstPos, - size_t pos1VSize, size_t pos2VSize, size_t dstVSize, - size_t numVertices, - bool morphNormals) override; - - /// @copydoc OptimisedUtil::concatenateAffineMatrices - void concatenateAffineMatrices( - const Affine3& baseMatrix, - const Affine3* srcMatrices, - Affine3* dstMatrices, - size_t numMatrices) override; - - /// @copydoc OptimisedUtil::calculateFaceNormals - void calculateFaceNormals( - const float *positions, - const EdgeData::Triangle *triangles, - Vector4 *faceNormals, - size_t numTriangles) override; - - /// @copydoc OptimisedUtil::calculateLightFacing - void calculateLightFacing( - const Vector4& lightPos, - const Vector4* faceNormals, - char* lightFacings, - size_t numFaces) override; - - /// @copydoc OptimisedUtil::extrudeVertices - void extrudeVertices( - const Vector4& lightPos, - Real extrudeDist, - const float* srcPositions, - float* destPositions, - size_t numVertices) override; - }; - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - void OptimisedUtilGeneral::softwareVertexSkinning( - const float *pSrcPos, float *pDestPos, - const float *pSrcNorm, float *pDestNorm, - const float *pBlendWeight, const unsigned char* pBlendIndex, - const Affine3* const* blendMatrices, - size_t srcPosStride, size_t destPosStride, - size_t srcNormStride, size_t destNormStride, - size_t blendWeightStride, size_t blendIndexStride, - size_t numWeightsPerVertex, - size_t numVertices) - { - // Source vectors - Vector3 sourceVec = Vector3::ZERO, sourceNorm = Vector3::ZERO; - // Accumulation vectors - Vector3 accumVecPos, accumVecNorm; - - // Loop per vertex - for (size_t vertIdx = 0; vertIdx < numVertices; ++vertIdx) - { - // Load source vertex elements - sourceVec.x = pSrcPos[0]; - sourceVec.y = pSrcPos[1]; - sourceVec.z = pSrcPos[2]; - - if (pSrcNorm) - { - sourceNorm.x = pSrcNorm[0]; - sourceNorm.y = pSrcNorm[1]; - sourceNorm.z = pSrcNorm[2]; - } - - // Load accumulators - accumVecPos = Vector3::ZERO; - accumVecNorm = Vector3::ZERO; - - // Loop per blend weight - // - // Note: Don't change "unsigned short" here!!! If use "size_t" instead, - // VC7.1 unroll this loop to four blend weights pre-iteration, and then - // loss performance 10% in this function. Ok, this give a hint that we - // should unroll this loop manually for better performance, will do that - // later. - // - for (unsigned short blendIdx = 0; blendIdx < numWeightsPerVertex; ++blendIdx) - { - // Blend by multiplying source by blend matrix and scaling by weight - // Add to accumulator - // NB weights must be normalised!! - Real weight = pBlendWeight[blendIdx]; - if (weight) - { - // Blend position, use 3x4 matrix - const Affine3& mat = *blendMatrices[pBlendIndex[blendIdx]]; - accumVecPos.x += - (mat[0][0] * sourceVec.x + - mat[0][1] * sourceVec.y + - mat[0][2] * sourceVec.z + - mat[0][3]) - * weight; - accumVecPos.y += - (mat[1][0] * sourceVec.x + - mat[1][1] * sourceVec.y + - mat[1][2] * sourceVec.z + - mat[1][3]) - * weight; - accumVecPos.z += - (mat[2][0] * sourceVec.x + - mat[2][1] * sourceVec.y + - mat[2][2] * sourceVec.z + - mat[2][3]) - * weight; - if (pSrcNorm) - { - // Blend normal - // We should blend by inverse transpose here, but because we're assuming the 3x3 - // aspect of the matrix is orthogonal (no non-uniform scaling), the inverse transpose - // is equal to the main 3x3 matrix - // Note because it's a normal we just extract the rotational part, saves us renormalising here - accumVecNorm.x += - (mat[0][0] * sourceNorm.x + - mat[0][1] * sourceNorm.y + - mat[0][2] * sourceNorm.z) - * weight; - accumVecNorm.y += - (mat[1][0] * sourceNorm.x + - mat[1][1] * sourceNorm.y + - mat[1][2] * sourceNorm.z) - * weight; - accumVecNorm.z += - (mat[2][0] * sourceNorm.x + - mat[2][1] * sourceNorm.y + - mat[2][2] * sourceNorm.z) - * weight; - } - } - } - - // Stored blended vertex in hardware buffer - pDestPos[0] = accumVecPos.x; - pDestPos[1] = accumVecPos.y; - pDestPos[2] = accumVecPos.z; - - // Stored blended vertex in temp buffer - if (pSrcNorm) - { - // Normalise - accumVecNorm.normalise(); - pDestNorm[0] = accumVecNorm.x; - pDestNorm[1] = accumVecNorm.y; - pDestNorm[2] = accumVecNorm.z; - // Advance pointers - advanceRawPointer(pSrcNorm, srcNormStride); - advanceRawPointer(pDestNorm, destNormStride); - } - - // Advance pointers - advanceRawPointer(pSrcPos, srcPosStride); - advanceRawPointer(pDestPos, destPosStride); - advanceRawPointer(pBlendWeight, blendWeightStride); - advanceRawPointer(pBlendIndex, blendIndexStride); - } - } - //--------------------------------------------------------------------- - void OptimisedUtilGeneral::concatenateAffineMatrices( - const Affine3& baseMatrix, - const Affine3* pSrcMat, - Affine3* pDstMat, - size_t numMatrices) - { - for (size_t i = 0; i < numMatrices; ++i) - { - *pDstMat = baseMatrix * *pSrcMat ; - - ++pSrcMat; - ++pDstMat; - } - } - //--------------------------------------------------------------------- - void OptimisedUtilGeneral::softwareVertexMorph( - float t, - const float *pSrc1, const float *pSrc2, - float *pDst, - size_t pos1VSize, size_t pos2VSize, size_t dstVSize, - size_t numVertices, - bool morphNormals) - { - size_t src1Skip = pos1VSize/sizeof(float) - 3 - (morphNormals ? 3 : 0); - size_t src2Skip = pos2VSize/sizeof(float) - 3 - (morphNormals ? 3 : 0); - size_t dstSkip = dstVSize/sizeof(float) - 3 - (morphNormals ? 3 : 0); - - Vector3f nlerpNormal; - for (size_t i = 0; i < numVertices; ++i) - { - // x - *pDst++ = *pSrc1 + t * (*pSrc2 - *pSrc1) ; - ++pSrc1; ++pSrc2; - // y - *pDst++ = *pSrc1 + t * (*pSrc2 - *pSrc1) ; - ++pSrc1; ++pSrc2; - // z - *pDst++ = *pSrc1 + t * (*pSrc2 - *pSrc1) ; - ++pSrc1; ++pSrc2; - - if (morphNormals) - { - // normals must be in the same buffer as pos - // perform an nlerp - // we don't have enough information for a spherical interp - nlerpNormal[0] = *pSrc1 + t * (*pSrc2 - *pSrc1); - ++pSrc1; ++pSrc2; - nlerpNormal[1] = *pSrc1 + t * (*pSrc2 - *pSrc1); - ++pSrc1; ++pSrc2; - nlerpNormal[2] = *pSrc1 + t * (*pSrc2 - *pSrc1); - ++pSrc1; ++pSrc2; - nlerpNormal.normalise(); - *pDst++ = nlerpNormal[0]; - *pDst++ = nlerpNormal[1]; - *pDst++ = nlerpNormal[2]; - } - - pSrc1 += src1Skip; - pSrc2 += src2Skip; - pDst += dstSkip; - - } - } - //--------------------------------------------------------------------- - void OptimisedUtilGeneral::calculateFaceNormals( - const float *positions, - const EdgeData::Triangle *triangles, - Vector4 *faceNormals, - size_t numTriangles) - { - for ( ; numTriangles; --numTriangles) - { - const EdgeData::Triangle& t = *triangles++; - size_t offset; - - offset = t.vertIndex[0] * 3; - Vector3 v1(positions[offset+0], positions[offset+1], positions[offset+2]); - - offset = t.vertIndex[1] * 3; - Vector3 v2(positions[offset+0], positions[offset+1], positions[offset+2]); - - offset = t.vertIndex[2] * 3; - Vector3 v3(positions[offset+0], positions[offset+1], positions[offset+2]); - - *faceNormals++ = Math::calculateFaceNormalWithoutNormalize(v1, v2, v3); - } - } - //--------------------------------------------------------------------- - void OptimisedUtilGeneral::calculateLightFacing( - const Vector4& lightPos, - const Vector4* faceNormals, - char* lightFacings, - size_t numFaces) - { - for (size_t i = 0; i < numFaces; ++i) - { - *lightFacings++ = (lightPos.dotProduct(*faceNormals++) > 0); - } - } - //--------------------------------------------------------------------- - void OptimisedUtilGeneral::extrudeVertices( - const Vector4& lightPos, - Real extrudeDist, - const float* pSrcPos, - float* pDestPos, - size_t numVertices) - { - if (lightPos.w == 0.0f) - { - // Directional light, extrusion is along light direction - - Vector3 extrusionDir( - -lightPos.x, - -lightPos.y, - -lightPos.z); - extrusionDir.normalise(); - extrusionDir *= extrudeDist; - - for (size_t vert = 0; vert < numVertices; ++vert) - { - *pDestPos++ = *pSrcPos++ + extrusionDir.x; - *pDestPos++ = *pSrcPos++ + extrusionDir.y; - *pDestPos++ = *pSrcPos++ + extrusionDir.z; - } - } - else - { - // Point light, calculate extrusionDir for every vertex - assert(lightPos.w == 1.0f); - - for (size_t vert = 0; vert < numVertices; ++vert) - { - Vector3 extrusionDir( - pSrcPos[0] - lightPos.x, - pSrcPos[1] - lightPos.y, - pSrcPos[2] - lightPos.z); - extrusionDir.normalise(); - extrusionDir *= extrudeDist; - - *pDestPos++ = *pSrcPos++ + extrusionDir.x; - *pDestPos++ = *pSrcPos++ + extrusionDir.y; - *pDestPos++ = *pSrcPos++ + extrusionDir.z; - } - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - extern OptimisedUtil* _getOptimisedUtilGeneral(void); - extern OptimisedUtil* _getOptimisedUtilGeneral(void) - { - static OptimisedUtilGeneral msOptimisedUtilGeneral; - return &msOptimisedUtilGeneral; - } - -} diff --git a/OgreMain/src/OgreOptimisedUtilSSE.cpp b/OgreMain/src/OgreOptimisedUtilSSE.cpp deleted file mode 100644 index 1d54b809265..00000000000 --- a/OgreMain/src/OgreOptimisedUtilSSE.cpp +++ /dev/null @@ -1,2153 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreOptimisedUtil.h" - - -#if __OGRE_HAVE_SSE || __OGRE_HAVE_NEON - -// Should keep this includes at latest to avoid potential "xmmintrin.h" included by -// other header file on some platform for some reason. -#include "OgreSIMDHelper.h" - -// I'd like to merge this file with OgreOptimisedUtil.cpp, but it's -// impossible when compile with gcc, due SSE instructions can only -// enable/disable at file level. - -//------------------------------------------------------------------------- -// -// The routines implemented in this file are performance oriented, -// which means saving every penny as possible. This requirement might -// break some C++/STL-rules. -// -// -// Some rules I'd like to respects: -// -// 1. Had better use unpacklo/hi, movelh/hl instead of shuffle because -// it can saving one byte of binary code :) -// 2. Use add/sub instead of mul. -// 3. Eliminate prolog code of function call. -// -// The last, anything recommended by Intel Optimization Reference Manual. -// -//------------------------------------------------------------------------- - -// Use unrolled SSE version when vertices exceeds this limit -#define OGRE_SSE_SKINNING_UNROLL_VERTICES 16 - -namespace Ogre { - -//------------------------------------------------------------------------- -// Local classes -//------------------------------------------------------------------------- - - /** SSE implementation of OptimisedUtil. - @note - Don't use this class directly, use OptimisedUtil instead. - */ - class _OgrePrivate OptimisedUtilSSE : public OptimisedUtil - { - protected: - /// Do we prefer to use a general SSE version for position/normal shared buffers? - bool mPreferGeneralVersionForSharedBuffers; - - public: - /// Constructor - OptimisedUtilSSE(void); - - /// @copydoc OptimisedUtil::softwareVertexSkinning - void __OGRE_SIMD_ALIGN_ATTRIBUTE softwareVertexSkinning( - const float *srcPosPtr, float *destPosPtr, - const float *srcNormPtr, float *destNormPtr, - const float *blendWeightPtr, const unsigned char* blendIndexPtr, - const Affine3* const* blendMatrices, - size_t srcPosStride, size_t destPosStride, - size_t srcNormStride, size_t destNormStride, - size_t blendWeightStride, size_t blendIndexStride, - size_t numWeightsPerVertex, - size_t numVertices) override; - - /// @copydoc OptimisedUtil::softwareVertexMorph - void __OGRE_SIMD_ALIGN_ATTRIBUTE softwareVertexMorph( - float t, - const float *srcPos1, const float *srcPos2, - float *dstPos, - size_t pos1VSize, size_t pos2VSize, size_t dstVSize, - size_t numVertices, - bool morphNormals) override; - - /// @copydoc OptimisedUtil::concatenateAffineMatrices - void __OGRE_SIMD_ALIGN_ATTRIBUTE concatenateAffineMatrices( - const Affine3& baseMatrix, - const Affine3* srcMatrices, - Affine3* dstMatrices, - size_t numMatrices) override; - - /// @copydoc OptimisedUtil::calculateFaceNormals - void __OGRE_SIMD_ALIGN_ATTRIBUTE calculateFaceNormals( - const float *positions, - const EdgeData::Triangle *triangles, - Vector4 *faceNormals, - size_t numTriangles) override; - - /// @copydoc OptimisedUtil::calculateLightFacing - void __OGRE_SIMD_ALIGN_ATTRIBUTE calculateLightFacing( - const Vector4& lightPos, - const Vector4* faceNormals, - char* lightFacings, - size_t numFaces) override; - - /// @copydoc OptimisedUtil::extrudeVertices - void __OGRE_SIMD_ALIGN_ATTRIBUTE extrudeVertices( - const Vector4& lightPos, - Real extrudeDist, - const float* srcPositions, - float* destPositions, - size_t numVertices) override; - }; - -#if defined(__OGRE_SIMD_ALIGN_STACK) - /** Stack-align implementation of OptimisedUtil. - - User code compiled by icc and gcc might not align stack - properly, we need ensure stack align to a 16-bytes boundary - when execute SSE function. - @par - We implemeted as align stack following a virtual function call, - then should guarantee call instruction are used instead of inline - underlying function body here (which might causing problem). - @note - Don't use this class directly, use OptimisedUtil instead. - */ - class _OgrePrivate OptimisedUtilWithStackAlign : public OptimisedUtil - { - protected: - /// The actual implementation - OptimisedUtil* mImpl; - - public: - /// Constructor - OptimisedUtilWithStackAlign(OptimisedUtil* impl) - : mImpl(impl) - { - } - - /// @copydoc OptimisedUtil::softwareVertexSkinning - virtual void softwareVertexSkinning( - const float *srcPosPtr, float *destPosPtr, - const float *srcNormPtr, float *destNormPtr, - const float *blendWeightPtr, const unsigned char* blendIndexPtr, - const Affine3* const* blendMatrices, - size_t srcPosStride, size_t destPosStride, - size_t srcNormStride, size_t destNormStride, - size_t blendWeightStride, size_t blendIndexStride, - size_t numWeightsPerVertex, - size_t numVertices) - { - __OGRE_SIMD_ALIGN_STACK(); - - mImpl->softwareVertexSkinning( - srcPosPtr, destPosPtr, - srcNormPtr, destNormPtr, - blendWeightPtr, blendIndexPtr, - blendMatrices, - srcPosStride, destPosStride, - srcNormStride, destNormStride, - blendWeightStride, blendIndexStride, - numWeightsPerVertex, - numVertices); - } - - /// @copydoc OptimisedUtil::softwareVertexMorph - virtual void softwareVertexMorph( - float t, - const float *srcPos1, const float *srcPos2, - float *dstPos, - size_t pos1VSize, size_t pos2VSize, size_t dstVSize, - size_t numVertices, - bool morphNormals) - { - __OGRE_SIMD_ALIGN_STACK(); - - mImpl->softwareVertexMorph( - t, - srcPos1, srcPos2, - dstPos, - pos1VSize, pos2VSize, dstVSize, - numVertices, - morphNormals); - } - - /// @copydoc OptimisedUtil::concatenateAffineMatrices - virtual void concatenateAffineMatrices( - const Affine3& baseMatrix, - const Affine3* srcMatrices, - Affine3* dstMatrices, - size_t numMatrices) - { - __OGRE_SIMD_ALIGN_STACK(); - - mImpl->concatenateAffineMatrices( - baseMatrix, - srcMatrices, - dstMatrices, - numMatrices); - } - - /// @copydoc OptimisedUtil::calculateFaceNormals - virtual void calculateFaceNormals( - const float *positions, - const EdgeData::Triangle *triangles, - Vector4 *faceNormals, - size_t numTriangles) - { - __OGRE_SIMD_ALIGN_STACK(); - - mImpl->calculateFaceNormals( - positions, - triangles, - faceNormals, - numTriangles); - } - - /// @copydoc OptimisedUtil::calculateLightFacing - virtual void calculateLightFacing( - const Vector4& lightPos, - const Vector4* faceNormals, - char* lightFacings, - size_t numFaces) - { - __OGRE_SIMD_ALIGN_STACK(); - - mImpl->calculateLightFacing( - lightPos, - faceNormals, - lightFacings, - numFaces); - } - - /// @copydoc OptimisedUtil::extrudeVertices - virtual void extrudeVertices( - const Vector4& lightPos, - Real extrudeDist, - const float* srcPositions, - float* destPositions, - size_t numVertices) - { - __OGRE_SIMD_ALIGN_STACK(); - - mImpl->extrudeVertices( - lightPos, - extrudeDist, - srcPositions, - destPositions, - numVertices); - } - }; -#endif // !defined(__OGRE_SIMD_ALIGN_STACK) - -//--------------------------------------------------------------------- -// Some useful macro for collapse matrices. -//--------------------------------------------------------------------- - -#define __LOAD_MATRIX(row0, row1, row2, pMatrix) \ - { \ - row0 = __MM_LOAD_PS((*pMatrix)[0]); \ - row1 = __MM_LOAD_PS((*pMatrix)[1]); \ - row2 = __MM_LOAD_PS((*pMatrix)[2]); \ - } - -#define __LERP_MATRIX(row0, row1, row2, weight, pMatrix) \ - { \ - row0 = __MM_LERP_PS(weight, row0, __MM_LOAD_PS((*pMatrix)[0])); \ - row1 = __MM_LERP_PS(weight, row1, __MM_LOAD_PS((*pMatrix)[1])); \ - row2 = __MM_LERP_PS(weight, row2, __MM_LOAD_PS((*pMatrix)[2])); \ - } - -#define __LOAD_WEIGHTED_MATRIX(row0, row1, row2, weight, pMatrix) \ - { \ - row0 = _mm_mul_ps(__MM_LOAD_PS((*pMatrix)[0]), weight); \ - row1 = _mm_mul_ps(__MM_LOAD_PS((*pMatrix)[1]), weight); \ - row2 = _mm_mul_ps(__MM_LOAD_PS((*pMatrix)[2]), weight); \ - } - -#define __ACCUM_WEIGHTED_MATRIX(row0, row1, row2, weight, pMatrix) \ - { \ - row0 = __MM_MADD_PS(__MM_LOAD_PS((*pMatrix)[0]), weight, row0); \ - row1 = __MM_MADD_PS(__MM_LOAD_PS((*pMatrix)[1]), weight, row1); \ - row2 = __MM_MADD_PS(__MM_LOAD_PS((*pMatrix)[2]), weight, row2); \ - } - -//--------------------------------------------------------------------- -// The following macros request variables declared by caller. -// -// :) Thank row-major matrix used in Ogre, it make we accessing affine matrix easy. -//--------------------------------------------------------------------- - -/** Collapse one-weighted matrix. - Eliminated multiply by weight since the weight should be equal to one always -*/ -#define __COLLAPSE_MATRIX_W1(row0, row1, row2, ppMatrices, pIndices, pWeights) \ - { \ - pMatrix0 = blendMatrices[pIndices[0]]; \ - __LOAD_MATRIX(row0, row1, row2, pMatrix0); \ - } - -/** Collapse two-weighted matrix. - Based on the fact that accumulated weights are equal to one, by use lerp, - replaced two multiplies and one additive with one multiplie and two additives. -*/ -#define __COLLAPSE_MATRIX_W2(row0, row1, row2, ppMatrices, pIndices, pWeights) \ - { \ - weight = _mm_load_ps1(pWeights + 1); \ - pMatrix0 = ppMatrices[pIndices[0]]; \ - __LOAD_MATRIX(row0, row1, row2, pMatrix0); \ - pMatrix1 = ppMatrices[pIndices[1]]; \ - __LERP_MATRIX(row0, row1, row2, weight, pMatrix1); \ - } - -/** Collapse three-weighted matrix. -*/ -#define __COLLAPSE_MATRIX_W3(row0, row1, row2, ppMatrices, pIndices, pWeights) \ - { \ - weight = _mm_load_ps1(pWeights + 0); \ - pMatrix0 = ppMatrices[pIndices[0]]; \ - __LOAD_WEIGHTED_MATRIX(row0, row1, row2, weight, pMatrix0); \ - weight = _mm_load_ps1(pWeights + 1); \ - pMatrix1 = ppMatrices[pIndices[1]]; \ - __ACCUM_WEIGHTED_MATRIX(row0, row1, row2, weight, pMatrix1); \ - weight = _mm_load_ps1(pWeights + 2); \ - pMatrix2 = ppMatrices[pIndices[2]]; \ - __ACCUM_WEIGHTED_MATRIX(row0, row1, row2, weight, pMatrix2); \ - } - -/** Collapse four-weighted matrix. -*/ -#define __COLLAPSE_MATRIX_W4(row0, row1, row2, ppMatrices, pIndices, pWeights) \ - { \ - /* Load four blend weights at one time, they will be shuffled later */ \ - weights = _mm_loadu_ps(pWeights); \ - \ - pMatrix0 = ppMatrices[pIndices[0]]; \ - weight = __MM_SELECT(weights, 0); \ - __LOAD_WEIGHTED_MATRIX(row0, row1, row2, weight, pMatrix0); \ - pMatrix1 = ppMatrices[pIndices[1]]; \ - weight = __MM_SELECT(weights, 1); \ - __ACCUM_WEIGHTED_MATRIX(row0, row1, row2, weight, pMatrix1); \ - pMatrix2 = ppMatrices[pIndices[2]]; \ - weight = __MM_SELECT(weights, 2); \ - __ACCUM_WEIGHTED_MATRIX(row0, row1, row2, weight, pMatrix2); \ - pMatrix3 = ppMatrices[pIndices[3]]; \ - weight = __MM_SELECT(weights, 3); \ - __ACCUM_WEIGHTED_MATRIX(row0, row1, row2, weight, pMatrix3); \ - } - - - - //--------------------------------------------------------------------- - // Collapse a matrix at one time. The collapsed matrix are weighted by - // blend-weights, and then can use to transform corresponding vertex directly. - // - // I'd like use inline function instead of macro here, but I also want to - // ensure compiler integrate this code into its callers (release build at - // least), doesn't matter about specific compile options. Inline function - // work fine for VC, but looks like gcc (3.4.4 here) generate function-call - // when implemented as inline function, even if compile with "-O3" option. - // -#define _collapseOneMatrix( \ - m00, m01, m02, \ - pBlendWeight, pBlendIndex, \ - blendMatrices, \ - blendWeightStride, blendIndexStride, \ - numWeightsPerVertex) \ - { \ - /* Important Note: If reuse pMatrixXXX frequently, M$ VC7.1 will */ \ - /* generate wrong code here!!! */ \ - const Affine3* pMatrix0, *pMatrix1, *pMatrix2, *pMatrix3; \ - __m128 weight, weights; \ - \ - switch (numWeightsPerVertex) \ - { \ - default: /* Just in case and make compiler happy */ \ - case 1: \ - __COLLAPSE_MATRIX_W1(m00, m01, m02, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 0 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 0 * blendWeightStride)); \ - break; \ - \ - case 2: \ - __COLLAPSE_MATRIX_W2(m00, m01, m02, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 0 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 0 * blendWeightStride)); \ - break; \ - \ - case 3: \ - __COLLAPSE_MATRIX_W3(m00, m01, m02, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 0 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 0 * blendWeightStride)); \ - break; \ - \ - case 4: \ - __COLLAPSE_MATRIX_W4(m00, m01, m02, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 0 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 0 * blendWeightStride)); \ - break; \ - } \ - } - - //--------------------------------------------------------------------- - // Collapse four matrices at one time. The collapsed matrix are weighted by - // blend-weights, and then can use to transform corresponding vertex directly. - // - // I'd like use inline function instead of macro here, but I also want to - // ensure compiler integrate this code into its callers (release build at - // least), doesn't matter about specific compile options. Inline function - // work fine for VC, but looks like gcc (3.4.4 here) generate function-call - // when implemented as inline function, even if compile with "-O3" option. - // -#define _collapseFourMatrices( \ - m00, m01, m02, \ - m10, m11, m12, \ - m20, m21, m22, \ - m30, m31, m32, \ - pBlendWeight, pBlendIndex, \ - blendMatrices, \ - blendWeightStride, blendIndexStride, \ - numWeightsPerVertex) \ - { \ - /* Important Note: If reuse pMatrixXXX frequently, M$ VC7.1 will */ \ - /* generate wrong code here!!! */ \ - const Affine3* pMatrix0, *pMatrix1, *pMatrix2, *pMatrix3; \ - __m128 weight, weights; \ - \ - switch (numWeightsPerVertex) \ - { \ - default: /* Just in case and make compiler happy */ \ - case 1: \ - __COLLAPSE_MATRIX_W1(m00, m01, m02, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 0 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 0 * blendWeightStride)); \ - __COLLAPSE_MATRIX_W1(m10, m11, m12, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 1 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 1 * blendWeightStride)); \ - __COLLAPSE_MATRIX_W1(m20, m21, m22, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 2 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 2 * blendWeightStride)); \ - __COLLAPSE_MATRIX_W1(m30, m31, m32, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 3 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 3 * blendWeightStride)); \ - break; \ - \ - case 2: \ - __COLLAPSE_MATRIX_W2(m00, m01, m02, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 0 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 0 * blendWeightStride)); \ - __COLLAPSE_MATRIX_W2(m10, m11, m12, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 1 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 1 * blendWeightStride)); \ - __COLLAPSE_MATRIX_W2(m20, m21, m22, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 2 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 2 * blendWeightStride)); \ - __COLLAPSE_MATRIX_W2(m30, m31, m32, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 3 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 3 * blendWeightStride)); \ - break; \ - \ - case 3: \ - __COLLAPSE_MATRIX_W3(m00, m01, m02, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 0 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 0 * blendWeightStride)); \ - __COLLAPSE_MATRIX_W3(m10, m11, m12, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 1 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 1 * blendWeightStride)); \ - __COLLAPSE_MATRIX_W3(m20, m21, m22, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 2 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 2 * blendWeightStride)); \ - __COLLAPSE_MATRIX_W3(m30, m31, m32, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 3 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 3 * blendWeightStride)); \ - break; \ - \ - case 4: \ - __COLLAPSE_MATRIX_W4(m00, m01, m02, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 0 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 0 * blendWeightStride)); \ - __COLLAPSE_MATRIX_W4(m10, m11, m12, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 1 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 1 * blendWeightStride)); \ - __COLLAPSE_MATRIX_W4(m20, m21, m22, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 2 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 2 * blendWeightStride)); \ - __COLLAPSE_MATRIX_W4(m30, m31, m32, blendMatrices, \ - rawOffsetPointer(pBlendIndex, 3 * blendIndexStride), \ - rawOffsetPointer(pBlendWeight, 3 * blendWeightStride)); \ - break; \ - } \ - } - - - //--------------------------------------------------------------------- - // General SSE version skinning positions, and optional skinning normals. - static void softwareVertexSkinning_SSE_General( - const float *pSrcPos, float *pDestPos, - const float *pSrcNorm, float *pDestNorm, - const float *pBlendWeight, const unsigned char* pBlendIndex, - const Affine3* const* blendMatrices, - size_t srcPosStride, size_t destPosStride, - size_t srcNormStride, size_t destNormStride, - size_t blendWeightStride, size_t blendIndexStride, - size_t numWeightsPerVertex, - size_t numVertices) - { - for (size_t i = 0; i < numVertices; ++i) - { - // Collapse matrices - __m128 m00, m01, m02; - _collapseOneMatrix( - m00, m01, m02, - pBlendWeight, pBlendIndex, - blendMatrices, - blendWeightStride, blendIndexStride, - numWeightsPerVertex); - - // Advance blend weight and index pointers - advanceRawPointer(pBlendWeight, blendWeightStride); - advanceRawPointer(pBlendIndex, blendIndexStride); - - //------------------------------------------------------------------ - - // Rearrange to column-major matrix with rows shuffled order to: Z 0 X Y - __m128 m03 = _mm_setzero_ps(); - __MM_TRANSPOSE4x4_PS(m02, m03, m00, m01); - - //------------------------------------------------------------------ - // Transform position - //------------------------------------------------------------------ - - __m128 s0, s1, s2; - - // Load source position - s0 = _mm_load_ps1(pSrcPos + 0); - s1 = _mm_load_ps1(pSrcPos + 1); - s2 = _mm_load_ps1(pSrcPos + 2); - - // Transform by collapsed matrix - __m128 accumPos = __MM_DOT4x3_PS(m02, m03, m00, m01, s0, s1, s2); // z 0 x y - - // Store blended position, no aligned requirement - _mm_storeh_pi((__m64*)pDestPos, accumPos); - _mm_store_ss(pDestPos+2, accumPos); - - // Advance source and target position pointers - advanceRawPointer(pSrcPos, srcPosStride); - advanceRawPointer(pDestPos, destPosStride); - - //------------------------------------------------------------------ - // Optional blend normal - //------------------------------------------------------------------ - - if (pSrcNorm) - { - // Load source normal - s0 = _mm_load_ps1(pSrcNorm + 0); - s1 = _mm_load_ps1(pSrcNorm + 1); - s2 = _mm_load_ps1(pSrcNorm + 2); - - // Transform by collapsed matrix - __m128 accumNorm = __MM_DOT3x3_PS(m02, m03, m00, s0, s1, s2); // z 0 x y - - // Normalise normal - __m128 tmp = _mm_mul_ps(accumNorm, accumNorm); // z^2 0 x^2 y^2 - tmp = __MM_ACCUM3_PS(tmp, - _mm_shuffle_ps(tmp, tmp, _MM_SHUFFLE(0,3,1,2)), // x^2 0 y^2 z^2 - _mm_shuffle_ps(tmp, tmp, _MM_SHUFFLE(2,0,1,3))); // y^2 0 z^2 x^2 - // Note: zero divided here, but neglectable - tmp = __MM_RSQRT_PS(tmp); - accumNorm = _mm_mul_ps(accumNorm, tmp); - - // Store blended normal, no aligned requirement - _mm_storeh_pi((__m64*)pDestNorm, accumNorm); - _mm_store_ss(pDestNorm+2, accumNorm); - - // Advance source and target normal pointers - advanceRawPointer(pSrcNorm, srcNormStride); - advanceRawPointer(pDestNorm, destNormStride); - } - } - } - //--------------------------------------------------------------------- - // Special SSE version skinning shared buffers of position and normal, - // and the buffer are packed. - template - struct SoftwareVertexSkinning_SSE_PosNorm_Shared_Packed - { - static void apply( - const float* pSrc, float* pDest, - const float* pBlendWeight, const unsigned char* pBlendIndex, - const Affine3* const* blendMatrices, - size_t blendWeightStride, size_t blendIndexStride, - size_t numWeightsPerVertex, - size_t numIterations) - { - typedef SSEMemoryAccessor SrcAccessor; - typedef SSEMemoryAccessor DestAccessor; - - // Blending 4 vertices per-iteration - for (size_t i = 0; i < numIterations; ++i) - { - // Collapse matrices - __m128 m00, m01, m02, m10, m11, m12, m20, m21, m22, m30, m31, m32; - _collapseFourMatrices( - m00, m01, m02, - m10, m11, m12, - m20, m21, m22, - m30, m31, m32, - pBlendWeight, pBlendIndex, - blendMatrices, - blendWeightStride, blendIndexStride, - numWeightsPerVertex); - - // Advance 4 vertices - advanceRawPointer(pBlendWeight, 4 * blendWeightStride); - advanceRawPointer(pBlendIndex, 4 * blendIndexStride); - - //------------------------------------------------------------------ - // Transform position/normals - //------------------------------------------------------------------ - - __m128 s0, s1, s2, s3, s4, s5, d0, d1, d2, d3, d4, d5; - __m128 t0, t1, t2, t3, t4, t5; - - // Load source position/normals - s0 = SrcAccessor::load(pSrc + 0); // px0 py0 pz0 nx0 - s1 = SrcAccessor::load(pSrc + 4); // ny0 nz0 px1 py1 - s2 = SrcAccessor::load(pSrc + 8); // pz1 nx1 ny1 nz1 - s3 = SrcAccessor::load(pSrc + 12); // px2 py2 pz2 nx2 - s4 = SrcAccessor::load(pSrc + 16); // ny2 nz2 px3 py3 - s5 = SrcAccessor::load(pSrc + 20); // pz3 nx3 ny3 nz3 - - // Rearrange to component-major for batches calculate. - - t0 = _mm_unpacklo_ps(s0, s3); // px0 px2 py0 py2 - t1 = _mm_unpackhi_ps(s0, s3); // pz0 pz2 nx0 nx2 - t2 = _mm_unpacklo_ps(s1, s4); // ny0 ny2 nz0 nz2 - t3 = _mm_unpackhi_ps(s1, s4); // px1 px3 py1 py3 - t4 = _mm_unpacklo_ps(s2, s5); // pz1 pz3 nx1 nx3 - t5 = _mm_unpackhi_ps(s2, s5); // ny1 ny3 nz1 nz3 - - s0 = _mm_unpacklo_ps(t0, t3); // px0 px1 px2 px3 - s1 = _mm_unpackhi_ps(t0, t3); // py0 py1 py2 py3 - s2 = _mm_unpacklo_ps(t1, t4); // pz0 pz1 pz2 pz3 - s3 = _mm_unpackhi_ps(t1, t4); // nx0 nx1 nx2 nx3 - s4 = _mm_unpacklo_ps(t2, t5); // ny0 ny1 ny2 ny3 - s5 = _mm_unpackhi_ps(t2, t5); // nz0 nz1 nz2 nz3 - - // Transform by collapsed matrix - - // Shuffle row 0 of four collapsed matrices for calculate X component - __MM_TRANSPOSE4x4_PS(m00, m10, m20, m30); - - // Transform X components - d0 = __MM_DOT4x3_PS(m00, m10, m20, m30, s0, s1, s2); // PX0 PX1 PX2 PX3 - d3 = __MM_DOT3x3_PS(m00, m10, m20, s3, s4, s5); // NX0 NX1 NX2 NX3 - - // Shuffle row 1 of four collapsed matrices for calculate Y component - __MM_TRANSPOSE4x4_PS(m01, m11, m21, m31); - - // Transform Y components - d1 = __MM_DOT4x3_PS(m01, m11, m21, m31, s0, s1, s2); // PY0 PY1 PY2 PY3 - d4 = __MM_DOT3x3_PS(m01, m11, m21, s3, s4, s5); // NY0 NY1 NY2 NY3 - - // Shuffle row 2 of four collapsed matrices for calculate Z component - __MM_TRANSPOSE4x4_PS(m02, m12, m22, m32); - - // Transform Z components - d2 = __MM_DOT4x3_PS(m02, m12, m22, m32, s0, s1, s2); // PZ0 PZ1 PZ2 PZ3 - d5 = __MM_DOT3x3_PS(m02, m12, m22, s3, s4, s5); // NZ0 NZ1 NZ2 NZ3 - - // Normalise normals - __m128 tmp = __MM_DOT3x3_PS(d3, d4, d5, d3, d4, d5); - tmp = __MM_RSQRT_PS(tmp); - d3 = _mm_mul_ps(d3, tmp); - d4 = _mm_mul_ps(d4, tmp); - d5 = _mm_mul_ps(d5, tmp); - - // Arrange back to continuous format for store results - - t0 = _mm_unpacklo_ps(d0, d1); // PX0 PY0 PX1 PY1 - t1 = _mm_unpackhi_ps(d0, d1); // PX2 PY2 PX3 PY3 - t2 = _mm_unpacklo_ps(d2, d3); // PZ0 NX0 PZ1 NX1 - t3 = _mm_unpackhi_ps(d2, d3); // PZ2 NX2 PZ3 NX3 - t4 = _mm_unpacklo_ps(d4, d5); // NY0 NZ0 NY1 NZ1 - t5 = _mm_unpackhi_ps(d4, d5); // NY2 NZ2 NY3 NZ3 - - d0 = _mm_movelh_ps(t0, t2); // PX0 PY0 PZ0 NX0 - d1 = _mm_shuffle_ps(t4, t0, _MM_SHUFFLE(3,2,1,0)); // NY0 NZ0 PX1 PY1 - d2 = _mm_movehl_ps(t4, t2); // PZ1 NX1 NY1 NZ1 - d3 = _mm_movelh_ps(t1, t3); // PX2 PY2 PZ2 NX2 - d4 = _mm_shuffle_ps(t5, t1, _MM_SHUFFLE(3,2,1,0)); // NY2 NZ2 PX3 PY3 - d5 = _mm_movehl_ps(t5, t3); // PZ3 NX3 NY3 NZ3 - - // Store blended position/normals - DestAccessor::store(pDest + 0, d0); - DestAccessor::store(pDest + 4, d1); - DestAccessor::store(pDest + 8, d2); - DestAccessor::store(pDest + 12, d3); - DestAccessor::store(pDest + 16, d4); - DestAccessor::store(pDest + 20, d5); - - // Advance 4 vertices - pSrc += 4 * (3 + 3); - pDest += 4 * (3 + 3); - } - } - }; - static OGRE_FORCE_INLINE void softwareVertexSkinning_SSE_PosNorm_Shared_Packed( - const float* pSrcPos, float* pDestPos, - const float* pBlendWeight, const unsigned char* pBlendIndex, - const Affine3* const* blendMatrices, - size_t blendWeightStride, size_t blendIndexStride, - size_t numWeightsPerVertex, - size_t numIterations) - { - // pSrcPos might can't align to 16 bytes because 8 bytes alignment shift per-vertex - - // Instantiating two version only, since other alignment combinations are not that important. - if (_isAlignedForSSE(pSrcPos) && _isAlignedForSSE(pDestPos)) - { - SoftwareVertexSkinning_SSE_PosNorm_Shared_Packed::apply( - pSrcPos, pDestPos, - pBlendWeight, pBlendIndex, - blendMatrices, - blendWeightStride, blendIndexStride, - numWeightsPerVertex, - numIterations); - } - else - { - SoftwareVertexSkinning_SSE_PosNorm_Shared_Packed::apply( - pSrcPos, pDestPos, - pBlendWeight, pBlendIndex, - blendMatrices, - blendWeightStride, blendIndexStride, - numWeightsPerVertex, - numIterations); - } - } - //--------------------------------------------------------------------- - // Special SSE version skinning separated buffers of position and normal, - // both of position and normal buffer are packed. - template - struct SoftwareVertexSkinning_SSE_PosNorm_Separated_Packed - { - static void apply( - const float* pSrcPos, float* pDestPos, - const float* pSrcNorm, float* pDestNorm, - const float* pBlendWeight, const unsigned char* pBlendIndex, - const Affine3* const* blendMatrices, - size_t blendWeightStride, size_t blendIndexStride, - size_t numWeightsPerVertex, - size_t numIterations) - { - typedef SSEMemoryAccessor SrcPosAccessor; - typedef SSEMemoryAccessor DestPosAccessor; - typedef SSEMemoryAccessor SrcNormAccessor; - typedef SSEMemoryAccessor DestNormAccessor; - - // Blending 4 vertices per-iteration - for (size_t i = 0; i < numIterations; ++i) - { - // Collapse matrices - __m128 m00, m01, m02, m10, m11, m12, m20, m21, m22, m30, m31, m32; - _collapseFourMatrices( - m00, m01, m02, - m10, m11, m12, - m20, m21, m22, - m30, m31, m32, - pBlendWeight, pBlendIndex, - blendMatrices, - blendWeightStride, blendIndexStride, - numWeightsPerVertex); - - // Advance 4 vertices - advanceRawPointer(pBlendWeight, 4 * blendWeightStride); - advanceRawPointer(pBlendIndex, 4 * blendIndexStride); - - //------------------------------------------------------------------ - // Transform positions - //------------------------------------------------------------------ - - __m128 s0, s1, s2, d0, d1, d2; - - // Load source positions - s0 = SrcPosAccessor::load(pSrcPos + 0); // x0 y0 z0 x1 - s1 = SrcPosAccessor::load(pSrcPos + 4); // y1 z1 x2 y2 - s2 = SrcPosAccessor::load(pSrcPos + 8); // z2 x3 y3 z3 - - // Arrange to 3x4 component-major for batches calculate - __MM_TRANSPOSE4x3_PS(s0, s1, s2); - - // Transform by collapsed matrix - - // Shuffle row 0 of four collapsed matrices for calculate X component - __MM_TRANSPOSE4x4_PS(m00, m10, m20, m30); - - // Transform X components - d0 = __MM_DOT4x3_PS(m00, m10, m20, m30, s0, s1, s2); // X0 X1 X2 X3 - - // Shuffle row 1 of four collapsed matrices for calculate Y component - __MM_TRANSPOSE4x4_PS(m01, m11, m21, m31); - - // Transform Y components - d1 = __MM_DOT4x3_PS(m01, m11, m21, m31, s0, s1, s2); // Y0 Y1 Y2 Y3 - - // Shuffle row 2 of four collapsed matrices for calculate Z component - __MM_TRANSPOSE4x4_PS(m02, m12, m22, m32); - - // Transform Z components - d2 = __MM_DOT4x3_PS(m02, m12, m22, m32, s0, s1, s2); // Z0 Z1 Z2 Z3 - - // Arrange back to 4x3 continuous format for store results - __MM_TRANSPOSE3x4_PS(d0, d1, d2); - - // Store blended positions - DestPosAccessor::store(pDestPos + 0, d0); - DestPosAccessor::store(pDestPos + 4, d1); - DestPosAccessor::store(pDestPos + 8, d2); - - // Advance 4 vertices - pSrcPos += 4 * 3; - pDestPos += 4 * 3; - - //------------------------------------------------------------------ - // Transform normals - //------------------------------------------------------------------ - - // Load source normals - s0 = SrcNormAccessor::load(pSrcNorm + 0); // x0 y0 z0 x1 - s1 = SrcNormAccessor::load(pSrcNorm + 4); // y1 z1 x2 y2 - s2 = SrcNormAccessor::load(pSrcNorm + 8); // z2 x3 y3 z3 - - // Arrange to 3x4 component-major for batches calculate - __MM_TRANSPOSE4x3_PS(s0, s1, s2); - - // Transform by collapsed and shuffled matrices - d0 = __MM_DOT3x3_PS(m00, m10, m20, s0, s1, s2); // X0 X1 X2 X3 - d1 = __MM_DOT3x3_PS(m01, m11, m21, s0, s1, s2); // Y0 Y1 Y2 Y3 - d2 = __MM_DOT3x3_PS(m02, m12, m22, s0, s1, s2); // Z0 Z1 Z2 Z3 - - // Normalise normals - __m128 tmp = __MM_DOT3x3_PS(d0, d1, d2, d0, d1, d2); - tmp = __MM_RSQRT_PS(tmp); - d0 = _mm_mul_ps(d0, tmp); - d1 = _mm_mul_ps(d1, tmp); - d2 = _mm_mul_ps(d2, tmp); - - // Arrange back to 4x3 continuous format for store results - __MM_TRANSPOSE3x4_PS(d0, d1, d2); - - // Store blended normals - DestNormAccessor::store(pDestNorm + 0, d0); - DestNormAccessor::store(pDestNorm + 4, d1); - DestNormAccessor::store(pDestNorm + 8, d2); - - // Advance 4 vertices - pSrcNorm += 4 * 3; - pDestNorm += 4 * 3; - } - } - }; - static OGRE_FORCE_INLINE void softwareVertexSkinning_SSE_PosNorm_Separated_Packed( - const float* pSrcPos, float* pDestPos, - const float* pSrcNorm, float* pDestNorm, - const float* pBlendWeight, const unsigned char* pBlendIndex, - const Affine3* const* blendMatrices, - size_t blendWeightStride, size_t blendIndexStride, - size_t numWeightsPerVertex, - size_t numIterations) - { - assert(_isAlignedForSSE(pSrcPos)); - - // Instantiating two version only, since other alignment combination not that important. - if (_isAlignedForSSE(pSrcNorm) && _isAlignedForSSE(pDestPos) && _isAlignedForSSE(pDestNorm)) - { - SoftwareVertexSkinning_SSE_PosNorm_Separated_Packed::apply( - pSrcPos, pDestPos, - pSrcNorm, pDestNorm, - pBlendWeight, pBlendIndex, - blendMatrices, - blendWeightStride, blendIndexStride, - numWeightsPerVertex, - numIterations); - } - else - { - SoftwareVertexSkinning_SSE_PosNorm_Separated_Packed::apply( - pSrcPos, pDestPos, - pSrcNorm, pDestNorm, - pBlendWeight, pBlendIndex, - blendMatrices, - blendWeightStride, blendIndexStride, - numWeightsPerVertex, - numIterations); - } - } - //--------------------------------------------------------------------- - // Special SSE version skinning position only, the position buffer are - // packed. - template - struct SoftwareVertexSkinning_SSE_PosOnly_Packed - { - static void apply( - const float* pSrcPos, float* pDestPos, - const float* pBlendWeight, const unsigned char* pBlendIndex, - const Affine3* const* blendMatrices, - size_t blendWeightStride, size_t blendIndexStride, - size_t numWeightsPerVertex, - size_t numIterations) - { - typedef SSEMemoryAccessor SrcPosAccessor; - typedef SSEMemoryAccessor DestPosAccessor; - - // Blending 4 vertices per-iteration - for (size_t i = 0; i < numIterations; ++i) - { - // Collapse matrices - __m128 m00, m01, m02, m10, m11, m12, m20, m21, m22, m30, m31, m32; - _collapseFourMatrices( - m00, m01, m02, - m10, m11, m12, - m20, m21, m22, - m30, m31, m32, - pBlendWeight, pBlendIndex, - blendMatrices, - blendWeightStride, blendIndexStride, - numWeightsPerVertex); - - // Advance 4 vertices - advanceRawPointer(pBlendWeight, 4 * blendWeightStride); - advanceRawPointer(pBlendIndex, 4 * blendIndexStride); - - //------------------------------------------------------------------ - // Transform positions - //------------------------------------------------------------------ - - __m128 s0, s1, s2, d0, d1, d2; - - // Load source positions - s0 = SrcPosAccessor::load(pSrcPos + 0); // x0 y0 z0 x1 - s1 = SrcPosAccessor::load(pSrcPos + 4); // y1 z1 x2 y2 - s2 = SrcPosAccessor::load(pSrcPos + 8); // z2 x3 y3 z3 - - // Arrange to 3x4 component-major for batches calculate - __MM_TRANSPOSE4x3_PS(s0, s1, s2); - - // Transform by collapsed matrix - - // Shuffle row 0 of four collapsed matrices for calculate X component - __MM_TRANSPOSE4x4_PS(m00, m10, m20, m30); - - // Transform X components - d0 = __MM_DOT4x3_PS(m00, m10, m20, m30, s0, s1, s2); // X0 X1 X2 X3 - - // Shuffle row 1 of four collapsed matrices for calculate Y component - __MM_TRANSPOSE4x4_PS(m01, m11, m21, m31); - - // Transform Y components - d1 = __MM_DOT4x3_PS(m01, m11, m21, m31, s0, s1, s2); // Y0 Y1 Y2 Y3 - - // Shuffle row 2 of four collapsed matrices for calculate Z component - __MM_TRANSPOSE4x4_PS(m02, m12, m22, m32); - - // Transform Z components - d2 = __MM_DOT4x3_PS(m02, m12, m22, m32, s0, s1, s2); // Z0 Z1 Z2 Z3 - - // Arrange back to 4x3 continuous format for store results - __MM_TRANSPOSE3x4_PS(d0, d1, d2); - - // Store blended positions - DestPosAccessor::store(pDestPos + 0, d0); - DestPosAccessor::store(pDestPos + 4, d1); - DestPosAccessor::store(pDestPos + 8, d2); - - // Advance 4 vertices - pSrcPos += 4 * 3; - pDestPos += 4 * 3; - } - } - }; - static OGRE_FORCE_INLINE void softwareVertexSkinning_SSE_PosOnly_Packed( - const float* pSrcPos, float* pDestPos, - const float* pBlendWeight, const unsigned char* pBlendIndex, - const Affine3* const* blendMatrices, - size_t blendWeightStride, size_t blendIndexStride, - size_t numWeightsPerVertex, - size_t numIterations) - { - assert(_isAlignedForSSE(pSrcPos)); - - // Instantiating two version only, since other alignment combination not that important. - if (_isAlignedForSSE(pDestPos)) - { - SoftwareVertexSkinning_SSE_PosOnly_Packed::apply( - pSrcPos, pDestPos, - pBlendWeight, pBlendIndex, - blendMatrices, - blendWeightStride, blendIndexStride, - numWeightsPerVertex, - numIterations); - } - else - { - SoftwareVertexSkinning_SSE_PosOnly_Packed::apply( - pSrcPos, pDestPos, - pBlendWeight, pBlendIndex, - blendMatrices, - blendWeightStride, blendIndexStride, - numWeightsPerVertex, - numIterations); - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - OptimisedUtilSSE::OptimisedUtilSSE(void) - : mPreferGeneralVersionForSharedBuffers(false) - { - // For AMD Athlon XP (but not that for Althon 64), it's prefer to never use - // unrolled version for shared buffers at all, I guess because that version - // run out of usable CPU registers, or L1/L2 cache related problem, causing - // slight performance loss than general version. - // -#if __OGRE_HAVE_NEON == 0 - if (PlatformInformation::getCpuIdentifier().find("AuthenticAMD") != String::npos) - { - // How can I check it's an Athlon XP but not Althon 64? - // Ok, just test whether supports SSE2/SSE3 or not, if not, - // assume general version faster than unrolled version :) - // - if (!(PlatformInformation::getCpuFeatures() & - (PlatformInformation::CPU_FEATURE_SSE2 | PlatformInformation::CPU_FEATURE_SSE3))) - { - mPreferGeneralVersionForSharedBuffers = true; - } - } -#endif - } - //--------------------------------------------------------------------- - void OptimisedUtilSSE::softwareVertexSkinning( - const float *pSrcPos, float *pDestPos, - const float *pSrcNorm, float *pDestNorm, - const float *pBlendWeight, const unsigned char* pBlendIndex, - const Affine3* const* blendMatrices, - size_t srcPosStride, size_t destPosStride, - size_t srcNormStride, size_t destNormStride, - size_t blendWeightStride, size_t blendIndexStride, - size_t numWeightsPerVertex, - size_t numVertices) - { - - __OGRE_CHECK_STACK_ALIGNED_FOR_SSE(); - - // All position/normal pointers should be perfect aligned, but still check here - // for avoid hardware buffer which allocated by potential buggy driver doesn't - // support alignment properly. - // Because we are used meta-function technique here, the code is easy to maintenance - // and still provides all possible alignment combination. - // - - // Use unrolled routines only if there a lot of vertices - if (numVertices > OGRE_SSE_SKINNING_UNROLL_VERTICES) - { - if (pSrcNorm) - { - // Blend position and normal - - if (!mPreferGeneralVersionForSharedBuffers && - srcPosStride == sizeof(float) * (3 + 3) && destPosStride == sizeof(float) * (3 + 3) && - pSrcNorm == pSrcPos + 3 && pDestNorm == pDestPos + 3) - { - // Position and normal are sharing with packed buffer - - size_t srcPosAlign = (size_t)pSrcPos & 15; - assert((srcPosAlign & 3) == 0); - - // Blend unaligned vertices with general SIMD routine - if (srcPosAlign == 8) // Because 8 bytes alignment shift per-vertex - { - size_t count = srcPosAlign / 8; - numVertices -= count; - softwareVertexSkinning_SSE_General( - pSrcPos, pDestPos, - pSrcNorm, pDestNorm, - pBlendWeight, pBlendIndex, - blendMatrices, - srcPosStride, destPosStride, - srcNormStride, destNormStride, - blendWeightStride, blendIndexStride, - numWeightsPerVertex, - count); - - pSrcPos += count * (3 + 3); - pDestPos += count * (3 + 3); - pSrcNorm += count * (3 + 3); - pDestNorm += count * (3 + 3); - advanceRawPointer(pBlendWeight, count * blendWeightStride); - advanceRawPointer(pBlendIndex, count * blendIndexStride); - } - - // Blend vertices, four vertices per-iteration - size_t numIterations = numVertices / 4; - softwareVertexSkinning_SSE_PosNorm_Shared_Packed( - pSrcPos, pDestPos, - pBlendWeight, pBlendIndex, - blendMatrices, - blendWeightStride, blendIndexStride, - numWeightsPerVertex, - numIterations); - - // Advance pointers for remaining vertices - numVertices &= 3; - if (numVertices) - { - pSrcPos += numIterations * 4 * (3 + 3); - pDestPos += numIterations * 4 * (3 + 3); - pSrcNorm += numIterations * 4 * (3 + 3); - pDestNorm += numIterations * 4 * (3 + 3); - advanceRawPointer(pBlendWeight, numIterations * 4 * blendWeightStride); - advanceRawPointer(pBlendIndex, numIterations * 4 * blendIndexStride); - } - } - else if (srcPosStride == sizeof(float) * 3 && destPosStride == sizeof(float) * 3 && - srcNormStride == sizeof(float) * 3 && destNormStride == sizeof(float) * 3) - { - // Position and normal are separate buffers, and all of them are packed - - size_t srcPosAlign = (size_t)pSrcPos & 15; - assert((srcPosAlign & 3) == 0); - - // Blend unaligned vertices with general SIMD routine - if (srcPosAlign) - { - size_t count = srcPosAlign / 4; - numVertices -= count; - softwareVertexSkinning_SSE_General( - pSrcPos, pDestPos, - pSrcNorm, pDestNorm, - pBlendWeight, pBlendIndex, - blendMatrices, - srcPosStride, destPosStride, - srcNormStride, destNormStride, - blendWeightStride, blendIndexStride, - numWeightsPerVertex, - count); - - pSrcPos += count * 3; - pDestPos += count * 3; - pSrcNorm += count * 3; - pDestNorm += count * 3; - advanceRawPointer(pBlendWeight, count * blendWeightStride); - advanceRawPointer(pBlendIndex, count * blendIndexStride); - } - - // Blend vertices, four vertices per-iteration - size_t numIterations = numVertices / 4; - softwareVertexSkinning_SSE_PosNorm_Separated_Packed( - pSrcPos, pDestPos, - pSrcNorm, pDestNorm, - pBlendWeight, pBlendIndex, - blendMatrices, - blendWeightStride, blendIndexStride, - numWeightsPerVertex, - numIterations); - - // Advance pointers for remaining vertices - numVertices &= 3; - if (numVertices) - { - pSrcPos += numIterations * 4 * 3; - pDestPos += numIterations * 4 * 3; - pSrcNorm += numIterations * 4 * 3; - pDestNorm += numIterations * 4 * 3; - advanceRawPointer(pBlendWeight, numIterations * 4 * blendWeightStride); - advanceRawPointer(pBlendIndex, numIterations * 4 * blendIndexStride); - } - } - else // Not 'packed' form or wrong order between position and normal - { - // Should never occur, do nothing here just in case - } - } - else // !pSrcNorm - { - // Blend position only - - if (srcPosStride == sizeof(float) * 3 && destPosStride == sizeof(float) * 3) - { - // All buffers are packed - - size_t srcPosAlign = (size_t)pSrcPos & 15; - assert((srcPosAlign & 3) == 0); - - // Blend unaligned vertices with general SIMD routine - if (srcPosAlign) - { - size_t count = srcPosAlign / 4; - numVertices -= count; - softwareVertexSkinning_SSE_General( - pSrcPos, pDestPos, - pSrcNorm, pDestNorm, - pBlendWeight, pBlendIndex, - blendMatrices, - srcPosStride, destPosStride, - srcNormStride, destNormStride, - blendWeightStride, blendIndexStride, - numWeightsPerVertex, - count); - - pSrcPos += count * 3; - pDestPos += count * 3; - advanceRawPointer(pBlendWeight, count * blendWeightStride); - advanceRawPointer(pBlendIndex, count * blendIndexStride); - } - - // Blend vertices, four vertices per-iteration - size_t numIterations = numVertices / 4; - softwareVertexSkinning_SSE_PosOnly_Packed( - pSrcPos, pDestPos, - pBlendWeight, pBlendIndex, - blendMatrices, - blendWeightStride, blendIndexStride, - numWeightsPerVertex, - numIterations); - - // Advance pointers for remaining vertices - numVertices &= 3; - if (numVertices) - { - pSrcPos += numIterations * 4 * 3; - pDestPos += numIterations * 4 * 3; - advanceRawPointer(pBlendWeight, numIterations * 4 * blendWeightStride); - advanceRawPointer(pBlendIndex, numIterations * 4 * blendIndexStride); - } - } - else // Not 'packed' form - { - // Might occur only if user forced software blending position only - } - } - } - - // Blend remaining vertices, need to do it with SIMD for identical result, - // since mixing general floating-point and SIMD algorithm will causing - // floating-point error. - if (numVertices) - { - softwareVertexSkinning_SSE_General( - pSrcPos, pDestPos, - pSrcNorm, pDestNorm, - pBlendWeight, pBlendIndex, - blendMatrices, - srcPosStride, destPosStride, - srcNormStride, destNormStride, - blendWeightStride, blendIndexStride, - numWeightsPerVertex, - numVertices); - } - } - //--------------------------------------------------------------------- - void OptimisedUtilSSE::softwareVertexMorph( - float t, - const float *pSrc1, const float *pSrc2, - float *pDst, - size_t pos1VSize, size_t pos2VSize, size_t dstVSize, - size_t numVertices, - bool morphNormals) - { - OgreAssert(pos1VSize == pos2VSize && pos2VSize == dstVSize && dstVSize == (morphNormals ? 24 : 12), - "stride not supported"); - __OGRE_CHECK_STACK_ALIGNED_FOR_SSE(); - - __m128 src01, src02, src11, src12, src21, src22; - __m128 dst0, dst1, dst2; - - __m128 t4 = _mm_load_ps1(&t); - - - // If we're morphing normals, we have twice the number of floats to process - // Positions are interleaved with normals, so we'll have to separately - // normalise just the normals later; we'll just lerp in the first pass - // We can't normalise as we go because normals & positions are only 3 floats - // each so are not aligned for SSE, we'd mix the data up - size_t normalsMultiplier = morphNormals ? 2 : 1; - size_t numIterations = (numVertices*normalsMultiplier) / 4; - size_t numVerticesRemainder = (numVertices*normalsMultiplier) & 3; - - // Save for later - float *pStartDst = pDst; - - // Never use meta-function technique to accessing memory because looks like - // VC7.1 generate a bit inefficient binary code when put following code into - // inline function. - - if (_isAlignedForSSE(pSrc1) && _isAlignedForSSE(pSrc2) && _isAlignedForSSE(pDst)) - { - // All data aligned - - // Morph 4 vertices per-iteration. Special designed for use all - // available CPU registers as possible (7 registers used here), - // and avoid temporary values allocated in stack for suppress - // extra memory access. - for (size_t i = 0; i < numIterations; ++i) - { - // 12 floating-point values - src01 = __MM_LOAD_PS(pSrc1 + 0); - src02 = __MM_LOAD_PS(pSrc2 + 0); - src11 = __MM_LOAD_PS(pSrc1 + 4); - src12 = __MM_LOAD_PS(pSrc2 + 4); - src21 = __MM_LOAD_PS(pSrc1 + 8); - src22 = __MM_LOAD_PS(pSrc2 + 8); - pSrc1 += 12; pSrc2 += 12; - - dst0 = __MM_LERP_PS(t4, src01, src02); - dst1 = __MM_LERP_PS(t4, src11, src12); - dst2 = __MM_LERP_PS(t4, src21, src22); - - __MM_STORE_PS(pDst + 0, dst0); - __MM_STORE_PS(pDst + 4, dst1); - __MM_STORE_PS(pDst + 8, dst2); - pDst += 12; - } - - // Morph remaining vertices - switch (numVerticesRemainder) - { - case 3: - // 9 floating-point values - src01 = __MM_LOAD_PS(pSrc1 + 0); - src02 = __MM_LOAD_PS(pSrc2 + 0); - src11 = __MM_LOAD_PS(pSrc1 + 4); - src12 = __MM_LOAD_PS(pSrc2 + 4); - src21 = _mm_load_ss(pSrc1 + 8); - src22 = _mm_load_ss(pSrc2 + 8); - - dst0 = __MM_LERP_PS(t4, src01, src02); - dst1 = __MM_LERP_PS(t4, src11, src12); - dst2 = __MM_LERP_SS(t4, src21, src22); - - __MM_STORE_PS(pDst + 0, dst0); - __MM_STORE_PS(pDst + 4, dst1); - _mm_store_ss(pDst + 8, dst2); - break; - - case 2: - // 6 floating-point values - src01 = __MM_LOAD_PS(pSrc1 + 0); - src02 = __MM_LOAD_PS(pSrc2 + 0); - src11 = _mm_loadl_pi(t4, (const __m64*)(pSrc1 + 4)); // t4 is meaningless here - src12 = _mm_loadl_pi(t4, (const __m64*)(pSrc2 + 4)); // t4 is meaningless here - - dst0 = __MM_LERP_PS(t4, src01, src02); - dst1 = __MM_LERP_PS(t4, src11, src12); - - __MM_STORE_PS(pDst + 0, dst0); - _mm_storel_pi((__m64*)(pDst + 4), dst1); - break; - - case 1: - // 3 floating-point values - src01 = _mm_load_ss(pSrc1 + 2); - src02 = _mm_load_ss(pSrc2 + 2); - src01 = _mm_loadh_pi(src01, (const __m64*)(pSrc1 + 0)); - src02 = _mm_loadh_pi(src02, (const __m64*)(pSrc2 + 0)); - - dst0 = __MM_LERP_PS(t4, src01, src02); - - _mm_storeh_pi((__m64*)(pDst + 0), dst0); - _mm_store_ss(pDst + 2, dst0); - break; - } - } - else // Should never occur, just in case of buggy drivers - { - // Assume all data unaligned - - // Morph 4 vertices per-iteration. Special designed for use all - // available CPU registers as possible (7 registers used here), - // and avoid temporary values allocated in stack for suppress - // extra memory access. - for (size_t i = 0; i < numIterations; ++i) - { - // 12 floating-point values - src01 = _mm_loadu_ps(pSrc1 + 0); - src02 = _mm_loadu_ps(pSrc2 + 0); - src11 = _mm_loadu_ps(pSrc1 + 4); - src12 = _mm_loadu_ps(pSrc2 + 4); - src21 = _mm_loadu_ps(pSrc1 + 8); - src22 = _mm_loadu_ps(pSrc2 + 8); - pSrc1 += 12; pSrc2 += 12; - - dst0 = __MM_LERP_PS(t4, src01, src02); - dst1 = __MM_LERP_PS(t4, src11, src12); - dst2 = __MM_LERP_PS(t4, src21, src22); - - _mm_storeu_ps(pDst + 0, dst0); - _mm_storeu_ps(pDst + 4, dst1); - _mm_storeu_ps(pDst + 8, dst2); - pDst += 12; - - } - - // Morph remaining vertices - switch (numVerticesRemainder) - { - case 3: - // 9 floating-point values - src01 = _mm_loadu_ps(pSrc1 + 0); - src02 = _mm_loadu_ps(pSrc2 + 0); - src11 = _mm_loadu_ps(pSrc1 + 4); - src12 = _mm_loadu_ps(pSrc2 + 4); - src21 = _mm_load_ss(pSrc1 + 8); - src22 = _mm_load_ss(pSrc2 + 8); - - dst0 = __MM_LERP_PS(t4, src01, src02); - dst1 = __MM_LERP_PS(t4, src11, src12); - dst2 = __MM_LERP_SS(t4, src21, src22); - - _mm_storeu_ps(pDst + 0, dst0); - _mm_storeu_ps(pDst + 4, dst1); - _mm_store_ss(pDst + 8, dst2); - break; - - case 2: - // 6 floating-point values - src01 = _mm_loadu_ps(pSrc1 + 0); - src02 = _mm_loadu_ps(pSrc2 + 0); - src11 = _mm_loadl_pi(t4, (const __m64*)(pSrc1 + 4)); // t4 is meaningless here - src12 = _mm_loadl_pi(t4, (const __m64*)(pSrc2 + 4)); // t4 is meaningless here - - dst0 = __MM_LERP_PS(t4, src01, src02); - dst1 = __MM_LERP_PS(t4, src11, src12); - - _mm_storeu_ps(pDst + 0, dst0); - _mm_storel_pi((__m64*)(pDst + 4), dst1); - break; - - case 1: - // 3 floating-point values - src01 = _mm_load_ss(pSrc1 + 2); - src02 = _mm_load_ss(pSrc2 + 2); - src01 = _mm_loadh_pi(src01, (const __m64*)(pSrc1 + 0)); - src02 = _mm_loadh_pi(src02, (const __m64*)(pSrc2 + 0)); - - dst0 = __MM_LERP_PS(t4, src01, src02); - - _mm_storeh_pi((__m64*)(pDst + 0), dst0); - _mm_store_ss(pDst + 2, dst0); - break; - } - - } - - if (morphNormals) - { - - // Now we need to do and unaligned normalise on the normals data we just - // lerped; because normals are 3 elements each they're always unaligned - float *pNorm = pStartDst; - - // Offset past first position - pNorm += 3; - - // We'll do one normal each iteration, but still use SSE - for (size_t n = 0; n < numVertices; ++n) - { - // normalise function - __m128 norm; - - // load 3 floating-point normal values - // This loads into [0] and clears the rest - norm = _mm_load_ss(pNorm + 2); - // This loads into [2,3]. [1] is unused - norm = _mm_loadh_pi(norm, (__m64*)(pNorm + 0)); - - // Fill a 4-vec with vector length - // square - __m128 tmp = _mm_mul_ps(norm, norm); - // Add - for this we want this effect: - // orig 3 | 2 | 1 | 0 - // add1 0 | 0 | 0 | 2 - // add2 2 | 3 | 0 | 3 - // This way elements 0, 2 and 3 have the sum of all entries (except 1 which is unused) - - tmp = _mm_add_ps(tmp, _mm_shuffle_ps(tmp, tmp, _MM_SHUFFLE(0,0,0,2))); - // Add final combination & sqrt - // bottom 3 elements of l will have length, we don't care about 4 - tmp = _mm_add_ps(tmp, _mm_shuffle_ps(tmp, tmp, _MM_SHUFFLE(2,3,0,3))); - // Then divide to normalise - norm = _mm_div_ps(norm, _mm_sqrt_ps(tmp)); - - // Store back in the same place - _mm_storeh_pi((__m64*)(pNorm + 0), norm); - _mm_store_ss(pNorm + 2, norm); - - // Skip to next vertex (3x normal components, 3x position components) - pNorm += 6; - - - } - - - } - } - //--------------------------------------------------------------------- - void OptimisedUtilSSE::concatenateAffineMatrices( - const Affine3& baseMatrix, - const Affine3* pSrcMat, - Affine3* pDstMat, - size_t numMatrices) - { - __OGRE_CHECK_STACK_ALIGNED_FOR_SSE(); - - assert(_isAlignedForSSE(pSrcMat)); - assert(_isAlignedForSSE(pDstMat)); - - // Load base matrix, unaligned - __m128 m0 = _mm_loadu_ps(baseMatrix[0]); - __m128 m1 = _mm_loadu_ps(baseMatrix[1]); - __m128 m2 = _mm_loadu_ps(baseMatrix[2]); - __m128 m3 = _mm_loadu_ps(baseMatrix[3]); // m3 should be equal to (0, 0, 0, 1) - - for (size_t i = 0; i < numMatrices; ++i) - { - // Load source matrix, aligned - __m128 s0 = __MM_LOAD_PS((*pSrcMat)[0]); - __m128 s1 = __MM_LOAD_PS((*pSrcMat)[1]); - __m128 s2 = __MM_LOAD_PS((*pSrcMat)[2]); - - ++pSrcMat; - - __m128 t0, t1, t2, t3; - - // Concatenate matrix, and store results - - // Row 0 - t0 = _mm_mul_ps(__MM_SELECT(m0, 0), s0); - t1 = _mm_mul_ps(__MM_SELECT(m0, 1), s1); - t2 = _mm_mul_ps(__MM_SELECT(m0, 2), s2); - t3 = _mm_mul_ps(m0, m3); // Compiler should optimise this out of the loop - __MM_STORE_PS((*pDstMat)[0], __MM_ACCUM4_PS(t0,t1,t2,t3)); - - // Row 1 - t0 = _mm_mul_ps(__MM_SELECT(m1, 0), s0); - t1 = _mm_mul_ps(__MM_SELECT(m1, 1), s1); - t2 = _mm_mul_ps(__MM_SELECT(m1, 2), s2); - t3 = _mm_mul_ps(m1, m3); // Compiler should optimise this out of the loop - __MM_STORE_PS((*pDstMat)[1], __MM_ACCUM4_PS(t0,t1,t2,t3)); - - // Row 2 - t0 = _mm_mul_ps(__MM_SELECT(m2, 0), s0); - t1 = _mm_mul_ps(__MM_SELECT(m2, 1), s1); - t2 = _mm_mul_ps(__MM_SELECT(m2, 2), s2); - t3 = _mm_mul_ps(m2, m3); // Compiler should optimise this out of the loop - __MM_STORE_PS((*pDstMat)[2], __MM_ACCUM4_PS(t0,t1,t2,t3)); - - ++pDstMat; - } - } - //--------------------------------------------------------------------- - void OptimisedUtilSSE::calculateFaceNormals( - const float *positions, - const EdgeData::Triangle *triangles, - Vector4 *faceNormals, - size_t numTriangles) - { - __OGRE_CHECK_STACK_ALIGNED_FOR_SSE(); - - assert(_isAlignedForSSE(faceNormals)); - -// Load Vector3 as: (x, 0, y, z) -#define __LOAD_VECTOR3(p) _mm_loadh_pi(_mm_load_ss(p), (const __m64*)((p)+1)) - - // Mask used to changes sign of single precision floating point values. - OGRE_SIMD_ALIGNED_DECL(static const uint32, msSignMask[4]) = - { - 0x80000000, 0x80000000, 0x80000000, 0x80000000, - }; - - size_t numIterations = numTriangles / 4; - numTriangles &= 3; - - // Four triangles per-iteration - for (size_t i = 0; i < numIterations; ++i) - { - -// Load four Vector3 as: (x0, x1, x2, x3), (y0, y1, y2, y3), (z0, z1, z2, z3) -#define __LOAD_FOUR_VECTOR3(x, y, z, p0, p1, p2, p3) \ - { \ - __m128 v0 = __LOAD_VECTOR3(p0); /* x0 -- y0 z0 */ \ - __m128 v1 = __LOAD_VECTOR3(p1); /* x1 -- y1 z1 */ \ - __m128 v2 = __LOAD_VECTOR3(p2); /* x2 -- y2 z2 */ \ - __m128 v3 = __LOAD_VECTOR3(p3); /* x3 -- y3 z3 */ \ - __m128 t0, t1; \ - \ - t0 = _mm_unpacklo_ps(v0, v2); /* x0 x2 -- -- */ \ - t1 = _mm_unpacklo_ps(v1, v3); /* x1 x3 -- -- */ \ - x = _mm_unpacklo_ps(t0, t1); /* x0 x1 x2 x3 */ \ - \ - t0 = _mm_unpackhi_ps(v0, v2); /* y0 y2 z0 z2 */ \ - t1 = _mm_unpackhi_ps(v1, v3); /* y1 y3 z1 z3 */ \ - y = _mm_unpacklo_ps(t0, t1); /* y0 y1 y2 y3 */ \ - z = _mm_unpackhi_ps(t0, t1); /* z0 z1 z2 z3 */ \ - } - - __m128 x0, x1, x2, y0, y1, y2, z0, z1, z2; - - // Load vertex 0 of four triangles, packed as component-major format: xxxx yyyy zzzz - __LOAD_FOUR_VECTOR3(x0, y0, z0, - positions + triangles[0].vertIndex[0] * 3, - positions + triangles[1].vertIndex[0] * 3, - positions + triangles[2].vertIndex[0] * 3, - positions + triangles[3].vertIndex[0] * 3); - - // Load vertex 1 of four triangles, packed as component-major format: xxxx yyyy zzzz - __LOAD_FOUR_VECTOR3(x1, y1, z1, - positions + triangles[0].vertIndex[1] * 3, - positions + triangles[1].vertIndex[1] * 3, - positions + triangles[2].vertIndex[1] * 3, - positions + triangles[3].vertIndex[1] * 3); - - // Load vertex 2 of four triangles, packed as component-major format: xxxx yyyy zzzz - __LOAD_FOUR_VECTOR3(x2, y2, z2, - positions + triangles[0].vertIndex[2] * 3, - positions + triangles[1].vertIndex[2] * 3, - positions + triangles[2].vertIndex[2] * 3, - positions + triangles[3].vertIndex[2] * 3); - - triangles += 4; - - // Calculate triangle face normals - - // a = v1 - v0 - __m128 ax = _mm_sub_ps(x1, x0); - __m128 ay = _mm_sub_ps(y1, y0); - __m128 az = _mm_sub_ps(z1, z0); - - // b = v2 - v0 - __m128 bx = _mm_sub_ps(x2, x0); - __m128 by = _mm_sub_ps(y2, y0); - __m128 bz = _mm_sub_ps(z2, z0); - - // n = a cross b - __m128 nx = _mm_sub_ps(_mm_mul_ps(ay, bz), _mm_mul_ps(az, by)); - __m128 ny = _mm_sub_ps(_mm_mul_ps(az, bx), _mm_mul_ps(ax, bz)); - __m128 nz = _mm_sub_ps(_mm_mul_ps(ax, by), _mm_mul_ps(ay, bx)); - - // w = - (n dot v0) - __m128 nw = _mm_xor_ps( - __MM_DOT3x3_PS(nx, ny, nz, x0, y0, z0), - *(const __m128 *)&msSignMask); - - // Arrange to per-triangle face normal major format - __MM_TRANSPOSE4x4_PS(nx, ny, nz, nw); - - // Store results - __MM_STORE_PS(&faceNormals[0].x, nx); - __MM_STORE_PS(&faceNormals[1].x, ny); - __MM_STORE_PS(&faceNormals[2].x, nz); - __MM_STORE_PS(&faceNormals[3].x, nw); - faceNormals += 4; - -#undef __LOAD_FOUR_VECTOR3 - } - - // Dealing with remaining triangles - for (size_t j = 0; j < numTriangles; ++j) - { - // Load vertices of the triangle - __m128 v0 = __LOAD_VECTOR3(positions + triangles->vertIndex[0] * 3); - __m128 v1 = __LOAD_VECTOR3(positions + triangles->vertIndex[1] * 3); - __m128 v2 = __LOAD_VECTOR3(positions + triangles->vertIndex[2] * 3); - ++triangles; - - // Calculate face normal - - __m128 t0, t1; - - __m128 a = _mm_sub_ps(v1, v0); // ax 0 ay az - __m128 b = _mm_sub_ps(v2, v0); // bx 0 by bz - t0 = _mm_shuffle_ps(a, a, _MM_SHUFFLE(2,0,1,3)); // az 0 ax ay - t1 = _mm_shuffle_ps(b, b, _MM_SHUFFLE(2,0,1,3)); // bz 0 bx by - t0 = _mm_mul_ps(t0, b); // az*bx 0 ax*by ay*bz - t1 = _mm_mul_ps(t1, a); // ax*bz 0 ay*bx az*by - - __m128 n = _mm_sub_ps(t0, t1); // ny 0 nz nx - - __m128 d = _mm_mul_ps( // dy 0 dz dx - _mm_shuffle_ps(v0, v0, _MM_SHUFFLE(0,3,1,2)), n); - - n = _mm_sub_ps(_mm_sub_ps(_mm_sub_ps( // nx ny nz -(dx+dy+dz) - _mm_shuffle_ps(n, n, _MM_SHUFFLE(1,2,0,3)), // nx ny nz 0 - _mm_shuffle_ps(d, d, _MM_SHUFFLE(3,1,1,1))), // 0 0 0 dx - _mm_shuffle_ps(d, d, _MM_SHUFFLE(0,1,1,1))), // 0 0 0 dy - _mm_shuffle_ps(d, d, _MM_SHUFFLE(2,1,1,1))); // 0 0 0 dz - - // Store result - __MM_STORE_PS(&faceNormals->x, n); - ++faceNormals; - } - -#undef __LOAD_VECTOR3 - } - //--------------------------------------------------------------------- - void OptimisedUtilSSE::calculateLightFacing( - const Vector4& lightPos, - const Vector4* faceNormals, - char* lightFacings, - size_t numFaces) - { - __OGRE_CHECK_STACK_ALIGNED_FOR_SSE(); - - assert(_isAlignedForSSE(faceNormals)); - - // Map to convert 4-bits mask to 4 byte values - static const char msMaskMapping[16][4] = - { - {0, 0, 0, 0}, {1, 0, 0, 0}, {0, 1, 0, 0}, {1, 1, 0, 0}, - {0, 0, 1, 0}, {1, 0, 1, 0}, {0, 1, 1, 0}, {1, 1, 1, 0}, - {0, 0, 0, 1}, {1, 0, 0, 1}, {0, 1, 0, 1}, {1, 1, 0, 1}, - {0, 0, 1, 1}, {1, 0, 1, 1}, {0, 1, 1, 1}, {1, 1, 1, 1}, - }; - - __m128 n0, n1, n2, n3; - __m128 t0, t1; - __m128 dp; - int bitmask; - - // Load light vector, unaligned - __m128 lp = _mm_loadu_ps(&lightPos.x); - - // Perload zero to register for compare dot product values - __m128 zero = _mm_setzero_ps(); - - size_t numIterations = numFaces / 4; - numFaces &= 3; - - // Four faces per-iteration - for (size_t i = 0; i < numIterations; ++i) - { - // Load face normals, aligned - n0 = __MM_LOAD_PS(&faceNormals[0].x); - n1 = __MM_LOAD_PS(&faceNormals[1].x); - n2 = __MM_LOAD_PS(&faceNormals[2].x); - n3 = __MM_LOAD_PS(&faceNormals[3].x); - faceNormals += 4; - - // Multiply by light vector - n0 = _mm_mul_ps(n0, lp); // x0 y0 z0 w0 - n1 = _mm_mul_ps(n1, lp); // x1 y1 z1 w1 - n2 = _mm_mul_ps(n2, lp); // x2 y2 z2 w2 - n3 = _mm_mul_ps(n3, lp); // x3 y3 z3 w3 - - // Horizontal add four vector values. - t0 = _mm_add_ps( // x0+z0 x1+z1 y0+w0 y1+w1 - _mm_unpacklo_ps(n0, n1), // x0 x1 y0 y1 - _mm_unpackhi_ps(n0, n1)); // z0 z1 w0 w1 - t1 = _mm_add_ps( // x2+z2 x3+z3 y2+w2 y3+w3 - _mm_unpacklo_ps(n2, n3), // x2 x3 y2 y3 - _mm_unpackhi_ps(n2, n3)); // z2 z3 w2 w3 - dp = _mm_add_ps( // dp0 dp1 dp2 dp3 - _mm_movelh_ps(t0, t1), // x0+z0 x1+z1 x2+z2 x3+z3 - _mm_movehl_ps(t1, t0)); // y0+w0 y1+w1 y2+w2 y3+w3 - - // Compare greater than zero and setup 4-bits mask. Use '_mm_cmpnle_ps' - // instead of '_mm_cmpgt_ps' here because we want keep 'zero' untouch, - // i.e. it's 2nd operand of the assembly instruction. And in fact - // '_mm_cmpgt_ps' was implemented as 'CMPLTPS' with operands swapped - // in VC7.1. - bitmask = _mm_movemask_ps(_mm_cmpnle_ps(dp, zero)); - - // Convert 4-bits mask to 4 bytes, and store results. - /* - *reinterpret_cast(lightFacings) = - *reinterpret_cast(msMaskMapping[bitmask]); - */ - memcpy(lightFacings, msMaskMapping[bitmask], sizeof(uint32)); - - - lightFacings += 4; - } - - // Dealing with remaining faces - switch (numFaces) - { - case 3: - n0 = __MM_LOAD_PS(&faceNormals[0].x); - n1 = __MM_LOAD_PS(&faceNormals[1].x); - n2 = __MM_LOAD_PS(&faceNormals[2].x); - - n0 = _mm_mul_ps(n0, lp); // x0 y0 z0 w0 - n1 = _mm_mul_ps(n1, lp); // x1 y1 z1 w1 - n2 = _mm_mul_ps(n2, lp); // x2 y2 z2 w2 - - t0 = _mm_add_ps( // x0+z0 x1+z1 y0+w0 y1+w1 - _mm_unpacklo_ps(n0, n1), // x0 x1 y0 y1 - _mm_unpackhi_ps(n0, n1)); // z0 z1 w0 w1 - t1 = _mm_add_ps( // x2+z2 x2+z2 y2+w2 y2+w2 - _mm_unpacklo_ps(n2, n2), // x2 x2 y2 y2 - _mm_unpackhi_ps(n2, n2)); // z2 z2 w2 w2 - dp = _mm_add_ps( // dp0 dp1 dp2 dp2 - _mm_movelh_ps(t0, t1), // x0+z0 x1+z1 x2+z2 x2+z2 - _mm_movehl_ps(t1, t0)); // y0+w0 y1+w1 y2+w2 y2+w2 - - bitmask = _mm_movemask_ps(_mm_cmpnle_ps(dp, zero)); - - lightFacings[0] = msMaskMapping[bitmask][0]; - lightFacings[1] = msMaskMapping[bitmask][1]; - lightFacings[2] = msMaskMapping[bitmask][2]; - break; - - case 2: - n0 = __MM_LOAD_PS(&faceNormals[0].x); - n1 = __MM_LOAD_PS(&faceNormals[1].x); - - n0 = _mm_mul_ps(n0, lp); // x0 y0 z0 w0 - n1 = _mm_mul_ps(n1, lp); // x1 y1 z1 w1 - - t0 = _mm_add_ps( // x0+z0 x1+z1 y0+w0 y1+w1 - _mm_unpacklo_ps(n0, n1), // x0 x1 y0 y1 - _mm_unpackhi_ps(n0, n1)); // z0 z1 w0 w1 - dp = _mm_add_ps( // dp0 dp1 dp0 dp1 - _mm_movelh_ps(t0, t0), // x0+z0 x1+z1 x0+z0 x1+z1 - _mm_movehl_ps(t0, t0)); // y0+w0 y1+w1 y0+w0 y1+w1 - - bitmask = _mm_movemask_ps(_mm_cmpnle_ps(dp, zero)); - - lightFacings[0] = msMaskMapping[bitmask][0]; - lightFacings[1] = msMaskMapping[bitmask][1]; - break; - - case 1: - n0 = __MM_LOAD_PS(&faceNormals[0].x); - - n0 = _mm_mul_ps(n0, lp); // x0 y0 z0 w0 - - t0 = _mm_add_ps( // x0+z0 x0+z0 y0+w0 y0+w0 - _mm_unpacklo_ps(n0, n0), // x0 x0 y0 y0 - _mm_unpackhi_ps(n0, n0)); // z0 z0 w0 w0 - dp = _mm_add_ps( // dp0 dp0 dp0 dp0 - _mm_movelh_ps(t0, t0), // x0+z0 x0+z0 x0+z0 x0+z0 - _mm_movehl_ps(t0, t0)); // y0+w0 y0+w0 y0+w0 y0+w0 - - bitmask = _mm_movemask_ps(_mm_cmpnle_ps(dp, zero)); - - lightFacings[0] = msMaskMapping[bitmask][0]; - break; - } - } - //--------------------------------------------------------------------- - // Template to extrude vertices for directional light. - template - struct ExtrudeVertices_SSE_DirectionalLight - { - static void apply( - const Vector4& lightPos, - Real extrudeDist, - const float* pSrcPos, - float* pDestPos, - size_t numVertices) - { - typedef SSEMemoryAccessor SrcAccessor; - typedef SSEMemoryAccessor DestAccessor; - - // Directional light, extrusion is along light direction - - // Load light vector, unaligned - __m128 lp = _mm_loadu_ps(&lightPos.x); - - // Calculate extrusion direction, note that we use inverted direction here - // for eliminate an extra negative instruction, we'll compensate for that - // by use subtract instruction instead later. - __m128 tmp = _mm_mul_ps(lp, lp); - tmp = _mm_add_ss(_mm_add_ss(tmp, _mm_shuffle_ps(tmp, tmp, 1)), _mm_movehl_ps(tmp, tmp)); - // Looks like VC7.1 generate a bit inefficient code for 'rsqrtss', so use 'rsqrtps' instead - tmp = _mm_mul_ss(_mm_rsqrt_ps(tmp), _mm_load_ss(&extrudeDist)); - __m128 dir = _mm_mul_ps(lp, __MM_SELECT(tmp, 0)); // X Y Z - - - // Prepare extrude direction for extruding 4 vertices parallelly - __m128 dir0 = _mm_shuffle_ps(dir, dir, _MM_SHUFFLE(0,2,1,0)); // X Y Z X - __m128 dir1 = _mm_shuffle_ps(dir, dir, _MM_SHUFFLE(1,0,2,1)); // Y Z X Y - __m128 dir2 = _mm_shuffle_ps(dir, dir, _MM_SHUFFLE(2,1,0,2)); // Z X Y Z - - __m128 s0, s1, s2; - __m128 d0, d1, d2; - - size_t numIterations = numVertices / 4; - numVertices &= 3; - - // Extruding 4 vertices per-iteration - for (size_t i = 0; i < numIterations; ++i) - { - s0 = SrcAccessor::load(pSrcPos + 0); - s1 = SrcAccessor::load(pSrcPos + 4); - s2 = SrcAccessor::load(pSrcPos + 8); - pSrcPos += 12; - - // The extrusion direction is inverted, use subtract instruction here - d0 = _mm_sub_ps(s0, dir0); // X0 Y0 Z0 X1 - d1 = _mm_sub_ps(s1, dir1); // Y1 Z1 X2 Y2 - d2 = _mm_sub_ps(s2, dir2); // Z2 X3 Y3 Z3 - - DestAccessor::store(pDestPos + 0, d0); - DestAccessor::store(pDestPos + 4, d1); - DestAccessor::store(pDestPos + 8, d2); - pDestPos += 12; - } - - // Dealing with remaining vertices - switch (numVertices) - { - case 3: - // 9 floating-point values - s0 = SrcAccessor::load(pSrcPos + 0); - s1 = SrcAccessor::load(pSrcPos + 4); - s2 = _mm_load_ss(pSrcPos + 8); - - // The extrusion direction is inverted, use subtract instruction here - d0 = _mm_sub_ps(s0, dir0); // X0 Y0 Z0 X1 - d1 = _mm_sub_ps(s1, dir1); // Y1 Z1 X2 Y2 - d2 = _mm_sub_ss(s2, dir2); // Z2 -- -- -- - - DestAccessor::store(pDestPos + 0, d0); - DestAccessor::store(pDestPos + 4, d1); - _mm_store_ss(pDestPos + 8, d2); - break; - - case 2: - // 6 floating-point values - s0 = SrcAccessor::load(pSrcPos + 0); - s1 = _mm_loadl_pi(dir1, (const __m64*)(pSrcPos + 4)); // dir1 is meaningless here - - // The extrusion direction is inverted, use subtract instruction here - d0 = _mm_sub_ps(s0, dir0); // X0 Y0 Z0 X1 - d1 = _mm_sub_ps(s1, dir1); // Y1 Z1 -- -- - - DestAccessor::store(pDestPos + 0, d0); - _mm_storel_pi((__m64*)(pDestPos + 4), d1); - break; - - case 1: - // 3 floating-point values - s0 = _mm_loadl_pi(dir0, (const __m64*)(pSrcPos + 0)); // dir0 is meaningless here - s1 = _mm_load_ss(pSrcPos + 2); - - // The extrusion direction is inverted, use subtract instruction here - d0 = _mm_sub_ps(s0, dir0); // X0 Y0 -- -- - d1 = _mm_sub_ss(s1, dir2); // Z0 -- -- -- - - _mm_storel_pi((__m64*)(pDestPos + 0), d0); - _mm_store_ss(pDestPos + 2, d1); - break; - } - } - }; - //--------------------------------------------------------------------- - // Template to extrude vertices for point light. - template - struct ExtrudeVertices_SSE_PointLight - { - static void apply( - const Vector4& lightPos, - Real extrudeDist, - const float* pSrcPos, - float* pDestPos, - size_t numVertices) - { - typedef SSEMemoryAccessor SrcAccessor; - typedef SSEMemoryAccessor DestAccessor; - - // Point light, will calculate extrusion direction for every vertex - - // Load light vector, unaligned - __m128 lp = _mm_loadu_ps(&lightPos.x); - - // Load extrude distance - __m128 extrudeDist4 = _mm_load_ps1(&extrudeDist); - - size_t numIterations = numVertices / 4; - numVertices &= 3; - - // Extruding 4 vertices per-iteration - for (size_t i = 0; i < numIterations; ++i) - { - // Load source positions - __m128 s0 = SrcAccessor::load(pSrcPos + 0); // x0 y0 z0 x1 - __m128 s1 = SrcAccessor::load(pSrcPos + 4); // y1 z1 x2 y2 - __m128 s2 = SrcAccessor::load(pSrcPos + 8); // z2 x3 y3 z3 - pSrcPos += 12; - - // Arrange to 3x4 component-major for batches calculate - __MM_TRANSPOSE4x3_PS(s0, s1, s2); - - // Calculate unnormalised extrusion direction - __m128 dx = _mm_sub_ps(s0, __MM_SELECT(lp, 0)); // X0 X1 X2 X3 - __m128 dy = _mm_sub_ps(s1, __MM_SELECT(lp, 1)); // Y0 Y1 Y2 Y3 - __m128 dz = _mm_sub_ps(s2, __MM_SELECT(lp, 2)); // Z0 Z1 Z2 Z3 - - // Normalise extrusion direction and multiply by extrude distance - __m128 tmp = __MM_DOT3x3_PS(dx, dy, dz, dx, dy, dz); - tmp = _mm_mul_ps(_mm_rsqrt_ps(tmp), extrudeDist4); - dx = _mm_mul_ps(dx, tmp); - dy = _mm_mul_ps(dy, tmp); - dz = _mm_mul_ps(dz, tmp); - - // Calculate extruded positions - __m128 d0 = _mm_add_ps(dx, s0); - __m128 d1 = _mm_add_ps(dy, s1); - __m128 d2 = _mm_add_ps(dz, s2); - - // Arrange back to 4x3 continuous format for store results - __MM_TRANSPOSE3x4_PS(d0, d1, d2); - - // Store extruded positions - DestAccessor::store(pDestPos + 0, d0); - DestAccessor::store(pDestPos + 4, d1); - DestAccessor::store(pDestPos + 8, d2); - pDestPos += 12; - } - - // Dealing with remaining vertices - for (size_t j = 0; j < numVertices; ++j) - { - // Load source position - __m128 src = _mm_loadh_pi(_mm_load_ss(pSrcPos + 0), (const __m64*)(pSrcPos + 1)); // x 0 y z - pSrcPos += 3; - - // Calculate unnormalised extrusion direction - __m128 dir = _mm_sub_ps(src, _mm_shuffle_ps(lp, lp, _MM_SHUFFLE(2,1,3,0))); // X 1 Y Z - - // Normalise extrusion direction and multiply by extrude distance - __m128 tmp = _mm_mul_ps(dir, dir); - tmp = _mm_add_ss(_mm_add_ss(tmp, _mm_movehl_ps(tmp, tmp)), _mm_shuffle_ps(tmp, tmp, 3)); - // Looks like VC7.1 generate a bit inefficient code for 'rsqrtss', so use 'rsqrtps' instead - tmp = _mm_mul_ss(_mm_rsqrt_ps(tmp), extrudeDist4); - dir = _mm_mul_ps(dir, __MM_SELECT(tmp, 0)); - - // Calculate extruded position - __m128 dst = _mm_add_ps(dir, src); - - // Store extruded position - _mm_store_ss(pDestPos + 0, dst); - _mm_storeh_pi((__m64*)(pDestPos + 1), dst); - pDestPos += 3; - } - } - }; - //--------------------------------------------------------------------- - void OptimisedUtilSSE::extrudeVertices( - const Vector4& lightPos, - Real extrudeDist, - const float* pSrcPos, - float* pDestPos, - size_t numVertices) - { - __OGRE_CHECK_STACK_ALIGNED_FOR_SSE(); - - // Note: Since pDestPos is following tail of pSrcPos, we can't assume - // it's aligned to SIMD alignment properly, so must check for it here. - // - // TODO: Add extra vertex to the vertex buffer for make sure pDestPos - // aligned same as pSrcPos. - // - - // We are use SSE reciprocal square root directly while calculating - // extrusion direction, since precision loss not that important here. - // - if (lightPos.w == 0.0f) - { - if (_isAlignedForSSE(pSrcPos)) - { - if (_isAlignedForSSE(pDestPos)) - ExtrudeVertices_SSE_DirectionalLight::apply( - lightPos, extrudeDist, pSrcPos, pDestPos, numVertices); - else - ExtrudeVertices_SSE_DirectionalLight::apply( - lightPos, extrudeDist, pSrcPos, pDestPos, numVertices); - } - else - { - if (_isAlignedForSSE(pDestPos)) - ExtrudeVertices_SSE_DirectionalLight::apply( - lightPos, extrudeDist, pSrcPos, pDestPos, numVertices); - else - ExtrudeVertices_SSE_DirectionalLight::apply( - lightPos, extrudeDist, pSrcPos, pDestPos, numVertices); - } - } - else - { - assert(lightPos.w == 1.0f); - - if (_isAlignedForSSE(pSrcPos)) - { - if (_isAlignedForSSE(pDestPos)) - ExtrudeVertices_SSE_PointLight::apply( - lightPos, extrudeDist, pSrcPos, pDestPos, numVertices); - else - ExtrudeVertices_SSE_PointLight::apply( - lightPos, extrudeDist, pSrcPos, pDestPos, numVertices); - } - else - { - if (_isAlignedForSSE(pDestPos)) - ExtrudeVertices_SSE_PointLight::apply( - lightPos, extrudeDist, pSrcPos, pDestPos, numVertices); - else - ExtrudeVertices_SSE_PointLight::apply( - lightPos, extrudeDist, pSrcPos, pDestPos, numVertices); - } - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - extern OptimisedUtil* _getOptimisedUtilSSE(void); - extern OptimisedUtil* _getOptimisedUtilSSE(void) - { - static OptimisedUtilSSE msOptimisedUtilSSE; -#if defined(__OGRE_SIMD_ALIGN_STACK) - static OptimisedUtilWithStackAlign msOptimisedUtilWithStackAlign(&msOptimisedUtilSSE); - return &msOptimisedUtilWithStackAlign; -#else - return &msOptimisedUtilSSE; -#endif - } - -} - -#endif // __OGRE_HAVE_SSE diff --git a/OgreMain/src/OgrePVRTCCodec.cpp b/OgreMain/src/OgrePVRTCCodec.cpp deleted file mode 100644 index 9cae83fbf57..00000000000 --- a/OgreMain/src/OgrePVRTCCodec.cpp +++ /dev/null @@ -1,305 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" - -#include "OgrePVRTCCodec.h" -#include "OgreImage.h" - -#define PVR_TEXTURE_FLAG_TYPE_MASK 0xff - -namespace Ogre { - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -#pragma pack (push, 1) -#else -#pragma pack (1) -#endif - - const uint32 PVR2_MAGIC = FOURCC('P', 'V', 'R', '!'); - const uint32 PVR3_MAGIC = FOURCC('P', 'V', 'R', 3); - - enum - { - kPVRTextureFlagTypePVRTC_2 = 24, - kPVRTextureFlagTypePVRTC_4 - }; - - enum - { - kPVRTC1_PF_2BPP_RGB, - kPVRTC1_PF_2BPP_RGBA, - kPVRTC1_PF_4BPP_RGB, - kPVRTC1_PF_4BPP_RGBA, - kPVRTC2_PF_2BPP, - kPVRTC2_PF_4BPP - }; - - typedef struct _PVRTCTexHeaderV2 - { - uint32 headerLength; - uint32 height; - uint32 width; - uint32 numMipmaps; - uint32 flags; - uint32 dataLength; - uint32 bpp; - uint32 bitmaskRed; - uint32 bitmaskGreen; - uint32 bitmaskBlue; - uint32 bitmaskAlpha; - uint32 pvrTag; - uint32 numSurfs; - } PVRTCTexHeaderV2; - - typedef struct _PVRTCTexHeaderV3 - { - uint32 version; //Version of the file header, used to identify it. - uint32 flags; //Various format flags. - uint64 pixelFormat; //The pixel format, 8cc value storing the 4 channel identifiers and their respective sizes. - uint32 colourSpace; //The Colour Space of the texture, currently either linear RGB or sRGB. - uint32 channelType; //Variable type that the channel is stored in. Supports signed/unsigned int/short/byte or float for now. - uint32 height; //Height of the texture. - uint32 width; //Width of the texture. - uint32 depth; //Depth of the texture. (Z-slices) - uint32 numSurfaces; //Number of members in a Texture Array. - uint32 numFaces; //Number of faces in a Cube Map. Maybe be a value other than 6. - uint32 mipMapCount; //Number of MIP Maps in the texture - NB: Includes top level. - uint32 metaDataSize; //Size of the accompanying meta data. - } PVRTCTexHeaderV3; - - typedef struct _PVRTCMetaData - { - uint32 DevFOURCC; - uint32 u32Key; - uint32 u32DataSize; - uint8* Data; - } PVRTCMetadata; - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -#pragma pack (pop) -#else -#pragma pack () -#endif - - //--------------------------------------------------------------------- - PVRTCCodec* PVRTCCodec::msInstance = 0; - //--------------------------------------------------------------------- - void PVRTCCodec::startup(void) - { - if (!msInstance) - { - LogManager::getSingleton().logMessage( - LML_NORMAL, - "PVRTC codec registering"); - - msInstance = OGRE_NEW PVRTCCodec(); - Codec::registerCodec(msInstance); - } - } - //--------------------------------------------------------------------- - void PVRTCCodec::shutdown(void) - { - if(msInstance) - { - Codec::unregisterCodec(msInstance); - OGRE_DELETE msInstance; - msInstance = 0; - } - } - //--------------------------------------------------------------------- - PVRTCCodec::PVRTCCodec(): - mType("pvr") - { - } - //--------------------------------------------------------------------- - void PVRTCCodec::decode(const DataStreamPtr& stream, const Any& output) const - { - Image* image = any_cast(output); - - // Assume its a pvr 2 header - PVRTCTexHeaderV2 headerV2; - stream->read(&headerV2, sizeof(PVRTCTexHeaderV2)); - stream->seek(0); - - if (PVR2_MAGIC == headerV2.pvrTag) - { - decodeV2(stream, image); - return; - } - - // Try it as pvr 3 header - PVRTCTexHeaderV3 headerV3; - stream->read(&headerV3, sizeof(PVRTCTexHeaderV3)); - stream->seek(0); - - if (PVR3_MAGIC == headerV3.version) - { - decodeV3(stream, image); - return; - } - - - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "This is not a PVR2 / PVR3 file!", "PVRTCCodec::decode"); - } - //--------------------------------------------------------------------- - void PVRTCCodec::decodeV2(const DataStreamPtr& stream, Image* image) - { - PVRTCTexHeaderV2 header; - uint32 flags = 0, formatFlags = 0; - - // Read the PVRTC header - stream->read(&header, sizeof(PVRTCTexHeaderV2)); - - // Get format flags - flags = header.flags; - flipEndian(&flags, sizeof(uint32)); - formatFlags = flags & PVR_TEXTURE_FLAG_TYPE_MASK; - - uint32 bitmaskAlpha = header.bitmaskAlpha; - flipEndian(&bitmaskAlpha, sizeof(uint32)); - - PixelFormat format = PF_UNKNOWN; - if (formatFlags == kPVRTextureFlagTypePVRTC_4 || formatFlags == kPVRTextureFlagTypePVRTC_2) - { - if (formatFlags == kPVRTextureFlagTypePVRTC_4) - { - format = bitmaskAlpha ? PF_PVRTC_RGBA4 : PF_PVRTC_RGB4; - } - else if (formatFlags == kPVRTextureFlagTypePVRTC_2) - { - format = bitmaskAlpha ? PF_PVRTC_RGBA2 : PF_PVRTC_RGB2; - } - } - else - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Invalid format"); - } - - // Calculate total size from number of mipmaps, faces and size - image->create(format, header.width, header.height, 1, 1, header.numMipmaps); - stream->read(image->getData(), image->getSize()); - } - //--------------------------------------------------------------------- - void PVRTCCodec::decodeV3(const DataStreamPtr& stream, Image* image) - { - PVRTCTexHeaderV3 header; - PVRTCMetadata metadata; - uint32 flags = 0; - - // Read the PVRTC header - stream->read(&header, sizeof(PVRTCTexHeaderV3)); - - // Read the PVRTC metadata - if(header.metaDataSize) - { - stream->read(&metadata, sizeof(PVRTCMetadata)); - } - - // Identify the pixel format - PixelFormat format = PF_UNKNOWN; - switch (header.pixelFormat) - { - case kPVRTC1_PF_2BPP_RGB: - format = PF_PVRTC_RGB2; - break; - case kPVRTC1_PF_2BPP_RGBA: - format = PF_PVRTC_RGBA2; - break; - case kPVRTC1_PF_4BPP_RGB: - format = PF_PVRTC_RGB4; - break; - case kPVRTC1_PF_4BPP_RGBA: - format = PF_PVRTC_RGBA4; - break; - case kPVRTC2_PF_2BPP: - format = PF_PVRTC2_2BPP; - break; - case kPVRTC2_PF_4BPP: - format = PF_PVRTC2_4BPP; - break; - } - - // Get format flags - flags = header.flags; - flipEndian(&flags, sizeof(uint32)); - - // Calculate total size from number of mipmaps, faces and size - image->create(format, header.width, header.height, header.depth, header.numFaces, header.mipMapCount); - - // Now deal with the data - void *destPtr = image->getData(); - - uint width = image->getWidth(); - uint height = image->getHeight(); - uint depth = image->getDepth(); - - // All mips for a surface, then each face - for(size_t mip = 0; mip <= image->getNumMipmaps(); ++mip) - { - for(size_t surface = 0; surface < header.numSurfaces; ++surface) - { - for(size_t i = 0; i < image->getNumFaces(); ++i) - { - // Load directly - size_t pvrSize = PixelUtil::getMemorySize(width, height, depth, format); - stream->read(destPtr, pvrSize); - destPtr = static_cast(static_cast(destPtr) + pvrSize); - } - } - - // Next mip - if(width!=1) width /= 2; - if(height!=1) height /= 2; - if(depth!=1) depth /= 2; - } - } - //--------------------------------------------------------------------- - String PVRTCCodec::getType() const - { - return mType; - } - //--------------------------------------------------------------------- - String PVRTCCodec::magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const - { - if (maxbytes >= sizeof(uint32)) - { - uint32 fileType; - memcpy(&fileType, magicNumberPtr, sizeof(uint32)); - flipEndian(&fileType, sizeof(uint32)); - - if (PVR3_MAGIC == fileType || PVR2_MAGIC == fileType) - { - return String("pvr"); - } - } - - return BLANKSTRING; - } -} diff --git a/OgreMain/src/OgrePVRTCCodec.h b/OgreMain/src/OgrePVRTCCodec.h deleted file mode 100644 index 234b7baf55f..00000000000 --- a/OgreMain/src/OgrePVRTCCodec.h +++ /dev/null @@ -1,80 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OgrePVRTCCodec_H__ -#define __OgrePVRTCCodec_H__ - -#include "OgreImageCodec.h" - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Image - * @{ - */ - - /** Codec specialized in loading PVRTC (PowerVR) images. - - We implement our own codec here since we need to be able to keep PVRTC - data compressed if the card supports it. - */ - class PVRTCCodec : public ImageCodec - { - private: - String mType; - - /// Single registered codec instance - static PVRTCCodec* msInstance; - - public: - PVRTCCodec(); - virtual ~PVRTCCodec() { } - - void decode(const DataStreamPtr& input, const Any& output) const override; - String magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const override; - String getType() const override; - - /// Static method to startup and register the PVRTC codec - static void startup(void); - /// Static method to shutdown and unregister the PVRTC codec - static void shutdown(void); - - private: - /// Decode PVRTCV2 image format - static void decodeV2(const DataStreamPtr& stream, Image* image); - - /// Decode PVRTCV3 image format - static void decodeV3(const DataStreamPtr& stream, Image* image); - }; - /** @} */ - /** @} */ - -} // namespace - -#endif - diff --git a/OgreMain/src/OgreParticleEmitter.cpp b/OgreMain/src/OgreParticleEmitter.cpp deleted file mode 100644 index dc2081f2302..00000000000 --- a/OgreMain/src/OgreParticleEmitter.cpp +++ /dev/null @@ -1,713 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreParticleEmitter.h" -#include "OgreParticleEmitterFactory.h" -#include "OgreParticleEmitterCommands.h" - -namespace Ogre -{ - // Command object for setting / getting parameters - static EmitterCommands::CmdAngle msAngleCmd; - static EmitterCommands::CmdColour msColourCmd; - static EmitterCommands::CmdColourRangeStart msColourRangeStartCmd; - static EmitterCommands::CmdColourRangeEnd msColourRangeEndCmd; - static EmitterCommands::CmdDirection msDirectionCmd; - static EmitterCommands::CmdUp msUpCmd; - static EmitterCommands::CmdDirPositionRef msDirPositionRefCmd; - static EmitterCommands::CmdEmissionRate msEmissionRateCmd; - static EmitterCommands::CmdMaxTTL msMaxTTLCmd; - static EmitterCommands::CmdMaxVelocity msMaxVelocityCmd; - static EmitterCommands::CmdMinTTL msMinTTLCmd; - static EmitterCommands::CmdMinVelocity msMinVelocityCmd; - static EmitterCommands::CmdPosition msPositionCmd; - static EmitterCommands::CmdTTL msTTLCmd; - static EmitterCommands::CmdVelocity msVelocityCmd; - static EmitterCommands::CmdDuration msDurationCmd; - static EmitterCommands::CmdMinDuration msMinDurationCmd; - static EmitterCommands::CmdMaxDuration msMaxDurationCmd; - static EmitterCommands::CmdRepeatDelay msRepeatDelayCmd; - static EmitterCommands::CmdMinRepeatDelay msMinRepeatDelayCmd; - static EmitterCommands::CmdMaxRepeatDelay msMaxRepeatDelayCmd; - static EmitterCommands::CmdName msNameCmd; - static EmitterCommands::CmdEmittedEmitter msEmittedEmitterCmd; - - - //----------------------------------------------------------------------- - ParticleEmitter::ParticleEmitter(ParticleSystem* psys) - : mParent(psys), - mUseDirPositionRef(false), - mDirPositionRef(Vector3::ZERO), - mStartTime(0), - mDurationMin(0), - mDurationMax(0), - mDurationRemain(0), - mRepeatDelayMin(0), - mRepeatDelayMax(0), - mRepeatDelayRemain(0) - { - - // Reasonable defaults - mAngle = 0; - setDirection(Vector3::UNIT_X); - mEmissionRate = 10; - mMaxSpeed = mMinSpeed = 1; - mMaxTTL = mMinTTL = 5; - mPosition = Vector3::ZERO; - mColourRangeStart = mColourRangeEnd = ColourValue::White; - mEnabled = true; - mRemainder = 0; - mName = BLANKSTRING; - mEmittedEmitter = BLANKSTRING; - mEmitted = false; - } - //----------------------------------------------------------------------- - ParticleEmitter::~ParticleEmitter() - { - } - //----------------------------------------------------------------------- - void ParticleEmitter::setPosition(const Vector3& pos) - { - mPosition = pos; - } - //----------------------------------------------------------------------- - const Vector3& ParticleEmitter::getPosition(void) const - { - return mPosition; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setDirection(const Vector3& inDirection) - { - mDirection = inDirection; - mDirection.normalise(); - // Generate a default up vector. - mUp = mDirection.perpendicular(); - mUp.normalise(); - } - //----------------------------------------------------------------------- - const Vector3& ParticleEmitter::getDirection(void) const - { - return mDirection; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setUp(const Vector3& inUp) - { - mUp = inUp; - mUp.normalise(); - } - //----------------------------------------------------------------------- - const Vector3& ParticleEmitter::getUp(void) const - { - return mUp; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setDirPositionReference( const Vector3& nposition, bool enable ) - { - mUseDirPositionRef = enable; - mDirPositionRef = nposition; - } - //----------------------------------------------------------------------- - const Vector3& ParticleEmitter::getDirPositionReference() const - { - return mDirPositionRef; - } - //----------------------------------------------------------------------- - bool ParticleEmitter::getDirPositionReferenceEnabled() const - { - return mUseDirPositionRef; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setAngle(const Radian& angle) - { - // Store as radians for efficiency - mAngle = angle; - } - //----------------------------------------------------------------------- - const Radian& ParticleEmitter::getAngle(void) const - { - return mAngle; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setParticleVelocity(Real speed) - { - assert(std::isfinite(speed)); - mMinSpeed = mMaxSpeed = speed; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setParticleVelocity(Real min, Real max) - { - assert(std::isfinite(min) && std::isfinite(max)); - mMinSpeed = min; - mMaxSpeed = max; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setEmissionRate(Real particlesPerSecond) - { - mEmissionRate = particlesPerSecond; - } - //----------------------------------------------------------------------- - Real ParticleEmitter::getEmissionRate(void) const - { - return mEmissionRate; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setTimeToLive(Real ttl) - { - assert (ttl >= 0 && "Time to live can not be negative"); - mMinTTL = mMaxTTL = ttl; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setTimeToLive(Real minTtl, Real maxTtl) - { - assert (minTtl >= 0 && "Time to live can not be negative"); - assert (maxTtl >= 0 && "Time to live can not be negative"); - mMinTTL = minTtl; - mMaxTTL = maxTtl; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setColour(const ColourValue& inColour) - { - mColourRangeStart = mColourRangeEnd = inColour; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setColour(const ColourValue& colourStart, const ColourValue& colourEnd) - { - mColourRangeStart = colourStart; - mColourRangeEnd = colourEnd; - } - //----------------------------------------------------------------------- - const String& ParticleEmitter::getName(void) const - { - return mName; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setName(const String& newName) - { - mName = newName; - } - //----------------------------------------------------------------------- - const String& ParticleEmitter::getEmittedEmitter(void) const - { - return mEmittedEmitter; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setEmittedEmitter(const String& emittedEmitter) - { - mEmittedEmitter = emittedEmitter; - } - //----------------------------------------------------------------------- - bool ParticleEmitter::isEmitted(void) const - { - return mEmitted; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setEmitted(bool emitted) - { - mEmitted = emitted; - } - //----------------------------------------------------------------------- - static float sampleSphereUniform(const float& maxAngle) - { - float cosMax = -std::cos(maxAngle) + 1; // for maxAngle = pi, cosMax = 2 - // see https://corysimon.github.io/articles/uniformdistn-on-sphere/ - return std::acos(1 - cosMax * Math::UnitRandom()); - } - - void ParticleEmitter::genEmissionDirection( const Vector3 &particlePos, Vector3& destVector ) - { - if( mUseDirPositionRef ) - { - Vector3 particleDir = particlePos - mDirPositionRef; - particleDir.normalise(); - - if (mAngle != Radian(0)) - { - // Randomise angle - Radian angle(sampleSphereUniform(mAngle.valueRadians())); - - // Randomise direction - destVector = particleDir.randomDeviant( angle ); - } - else - { - // Constant angle - destVector = particleDir; - } - } - else - { - if (mAngle != Radian(0)) - { - // Randomise angle - Radian angle(sampleSphereUniform(mAngle.valueRadians())); - - // Randomise direction - destVector = mDirection.randomDeviant(angle, mUp); - } - else - { - // Constant angle - destVector = mDirection; - } - } - - // Don't normalise, we can assume that it will still be a unit vector since - // both direction and 'up' are. - } - //----------------------------------------------------------------------- - void ParticleEmitter::genEmissionVelocity(Vector3& destVector) - { - Real scalar; - if (mMinSpeed != mMaxSpeed) - { - scalar = mMinSpeed + (Math::UnitRandom() * (mMaxSpeed - mMinSpeed)); - } - else - { - scalar = mMinSpeed; - } - - destVector *= scalar; - } - //----------------------------------------------------------------------- - Real ParticleEmitter::genEmissionTTL(void) - { - if (mMaxTTL != mMinTTL) - { - return mMinTTL + (Math::UnitRandom() * (mMaxTTL - mMinTTL)); - } - else - { - return mMinTTL; - } - } - //----------------------------------------------------------------------- - unsigned short ParticleEmitter::genConstantEmissionCount(Real timeElapsed) - { - if (mEnabled) - { - if(mDurationMax < 0) - { - // single-shot burst - setEnabled(false); - return mEmissionRate; - } - - unsigned short intRequest = (unsigned short)mRemainder; - mRemainder -= intRequest; - - // Keep fractions, otherwise a high frame rate will result in zero emissions! - mRemainder += mEmissionRate * timeElapsed; - - // Check duration - if (mDurationMax) - { - mDurationRemain -= timeElapsed; - if (mDurationRemain <= 0) - { - // Disable, duration is out (takes effect next time) - setEnabled(false); - } - } - return intRequest; - } - else - { - // Check repeat - if (mRepeatDelayMax) - { - mRepeatDelayRemain -= timeElapsed; - if (mRepeatDelayRemain <= 0) - { - // Enable, repeat delay is out (takes effect next time) - setEnabled(true); - } - } - if(mStartTime) - { - mStartTime -= timeElapsed; - if(mStartTime <= 0) - { - setEnabled(true); - mStartTime = 0; - } - } - return 0; - } - - } - //----------------------------------------------------------------------- - void ParticleEmitter::genEmissionColour(RGBA& destColour) - { - if (mColourRangeStart != mColourRangeEnd) - { - // Randomise - ColourValue t(Math::UnitRandom(), Math::UnitRandom(), Math::UnitRandom(), Math::UnitRandom()); - destColour = (mColourRangeStart + t * (mColourRangeEnd - mColourRangeStart)).getAsBYTE(); - } - else - { - destColour = mColourRangeStart.getAsBYTE(); - } - } - //----------------------------------------------------------------------- - void ParticleEmitter::addBaseParameters(void) - { - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter(ParameterDef("angle", - "The angle up to which particles may vary in their initial direction " - "from the emitters direction, in degrees." , PT_REAL), - &msAngleCmd); - - dict->addParameter(ParameterDef("colour", - "The colour of emitted particles.", PT_COLOURVALUE), - &msColourCmd); - - dict->addParameter(ParameterDef("colour_range_start", - "The start of a range of colours to be assigned to emitted particles.", PT_COLOURVALUE), - &msColourRangeStartCmd); - - dict->addParameter(ParameterDef("colour_range_end", - "The end of a range of colours to be assigned to emitted particles.", PT_COLOURVALUE), - &msColourRangeEndCmd); - - dict->addParameter(ParameterDef("direction", - "The base direction of the emitter." , PT_VECTOR3), - &msDirectionCmd); - - dict->addParameter(ParameterDef("up", - "The up vector of the emitter." , PT_VECTOR3), - &msUpCmd); - - dict->addParameter(ParameterDef("direction_position_reference", - "The reference position to calculate the direction of emitted particles " - "based on their position. Good for explosions and implosions (use negative velocity)" , PT_COLOURVALUE), - &msDirPositionRefCmd); - - dict->addParameter(ParameterDef("emission_rate", - "The number of particles emitted per second." , PT_REAL), - &msEmissionRateCmd); - - dict->addParameter(ParameterDef("position", - "The position of the emitter relative to the particle system center." , PT_VECTOR3), - &msPositionCmd); - - dict->addParameter(ParameterDef("velocity", - "The initial velocity to be assigned to every particle, in world units per second." , PT_REAL), - &msVelocityCmd); - - dict->addParameter(ParameterDef("velocity_min", - "The minimum initial velocity to be assigned to each particle." , PT_REAL), - &msMinVelocityCmd); - - dict->addParameter(ParameterDef("velocity_max", - "The maximum initial velocity to be assigned to each particle." , PT_REAL), - &msMaxVelocityCmd); - - dict->addParameter(ParameterDef("time_to_live", - "The lifetime of each particle in seconds." , PT_REAL), - &msTTLCmd); - - dict->addParameter(ParameterDef("time_to_live_min", - "The minimum lifetime of each particle in seconds." , PT_REAL), - &msMinTTLCmd); - - dict->addParameter(ParameterDef("time_to_live_max", - "The maximum lifetime of each particle in seconds." , PT_REAL), - &msMaxTTLCmd); - - dict->addParameter(ParameterDef("duration", - "The length of time in seconds which an emitter stays enabled for." , PT_REAL), - &msDurationCmd); - - dict->addParameter(ParameterDef("duration_min", - "The minimum length of time in seconds which an emitter stays enabled for." , PT_REAL), - &msMinDurationCmd); - - dict->addParameter(ParameterDef("duration_max", - "The maximum length of time in seconds which an emitter stays enabled for." , PT_REAL), - &msMaxDurationCmd); - - dict->addParameter(ParameterDef("repeat_delay", - "If set, after disabling an emitter will repeat (reenable) after this many seconds." , PT_REAL), - &msRepeatDelayCmd); - - dict->addParameter(ParameterDef("repeat_delay_min", - "If set, after disabling an emitter will repeat (reenable) after this minimum number of seconds." , PT_REAL), - &msMinRepeatDelayCmd); - - dict->addParameter(ParameterDef("repeat_delay_max", - "If set, after disabling an emitter will repeat (reenable) after this maximum number of seconds." , PT_REAL), - &msMaxRepeatDelayCmd); - - dict->addParameter(ParameterDef("name", - "This is the name of the emitter" , PT_STRING), - &msNameCmd); - - dict->addParameter(ParameterDef("emit_emitter", - "If set, this emitter will emit other emitters instead of visual particles" , PT_STRING), - &msEmittedEmitterCmd); - } - //----------------------------------------------------------------------- - Real ParticleEmitter::getParticleVelocity(void) const - { - return mMinSpeed; - } - //----------------------------------------------------------------------- - Real ParticleEmitter::getMinParticleVelocity(void) const - { - return mMinSpeed; - } - //----------------------------------------------------------------------- - Real ParticleEmitter::getMaxParticleVelocity(void) const - { - return mMaxSpeed; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setMinParticleVelocity(Real min) - { - assert(std::isfinite(min)); - mMinSpeed = min; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setMaxParticleVelocity(Real max) - { - assert(std::isfinite(max)); - mMaxSpeed = max; - } - //----------------------------------------------------------------------- - Real ParticleEmitter::getTimeToLive(void) const - { - return mMinTTL; - } - //----------------------------------------------------------------------- - Real ParticleEmitter::getMinTimeToLive(void) const - { - return mMinTTL; - } - //----------------------------------------------------------------------- - Real ParticleEmitter::getMaxTimeToLive(void) const - { - return mMaxTTL; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setMinTimeToLive(Real min) - { - mMinTTL = min; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setMaxTimeToLive(Real max) - { - mMaxTTL = max; - } - //----------------------------------------------------------------------- - const ColourValue& ParticleEmitter::getColour(void) const - { - return mColourRangeStart; - } - //----------------------------------------------------------------------- - const ColourValue& ParticleEmitter::getColourRangeStart(void) const - { - return mColourRangeStart; - } - //----------------------------------------------------------------------- - const ColourValue& ParticleEmitter::getColourRangeEnd(void) const - { - return mColourRangeEnd; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setColourRangeStart(const ColourValue& val) - { - mColourRangeStart = val; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setColourRangeEnd(const ColourValue& val ) - { - mColourRangeEnd = val; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setEnabled(bool enabled) - { - mEnabled = enabled; - mRemainder = 1.0f; // make sure we emit a particle on next update. Turns emission rate to (t0;r] interval - // Reset duration & repeat - initDurationRepeat(); - } - //----------------------------------------------------------------------- - bool ParticleEmitter::getEnabled(void) const - { - return mEnabled; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setStartTime(Real startTime) - { - setEnabled(false); - mStartTime = startTime; - } - //----------------------------------------------------------------------- - Real ParticleEmitter::getStartTime(void) const - { - return mStartTime; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setDuration(Real duration) - { - setDuration(duration, duration); - } - //----------------------------------------------------------------------- - Real ParticleEmitter::getDuration(void) const - { - return mDurationMin; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setDuration(Real min, Real max) - { - mDurationMin = min; - mDurationMax = max; - initDurationRepeat(); - } - //----------------------------------------------------------------------- - void ParticleEmitter::setMinDuration(Real min) - { - mDurationMin = min; - initDurationRepeat(); - } - //----------------------------------------------------------------------- - void ParticleEmitter::setMaxDuration(Real max) - { - mDurationMax = max; - initDurationRepeat(); - } - //----------------------------------------------------------------------- - void ParticleEmitter::initDurationRepeat(void) - { - if (mEnabled) - { - if (mDurationMin == mDurationMax) - { - mDurationRemain = mDurationMin; - } - else - { - mDurationRemain = Math::RangeRandom(mDurationMin, mDurationMax); - } - } - else - { - // Reset repeat - if (mRepeatDelayMin == mRepeatDelayMax) - { - mRepeatDelayRemain = mRepeatDelayMin; - } - else - { - mRepeatDelayRemain = Math::RangeRandom(mRepeatDelayMax, mRepeatDelayMin); - } - - } - } - //----------------------------------------------------------------------- - void ParticleEmitter::setRepeatDelay(Real delay) - { - setRepeatDelay(delay, delay); - } - //----------------------------------------------------------------------- - Real ParticleEmitter::getRepeatDelay(void) const - { - return mRepeatDelayMin; - } - //----------------------------------------------------------------------- - void ParticleEmitter::setRepeatDelay(Real min, Real max) - { - mRepeatDelayMin = min; - mRepeatDelayMax = max; - initDurationRepeat(); - } - //----------------------------------------------------------------------- - void ParticleEmitter::setMinRepeatDelay(Real min) - { - mRepeatDelayMin = min; - initDurationRepeat(); - } - //----------------------------------------------------------------------- - void ParticleEmitter::setMaxRepeatDelay(Real max) - { - mRepeatDelayMax = max; - initDurationRepeat(); - } - //----------------------------------------------------------------------- - Real ParticleEmitter::getMinDuration(void) const - { - return mDurationMin; - } - //----------------------------------------------------------------------- - Real ParticleEmitter::getMaxDuration(void) const - { - return mDurationMax; - } - //----------------------------------------------------------------------- - Real ParticleEmitter::getMinRepeatDelay(void) const - { - return mRepeatDelayMin; - } - //----------------------------------------------------------------------- - Real ParticleEmitter::getMaxRepeatDelay(void) const - { - return mRepeatDelayMax; - } - - //----------------------------------------------------------------------- - ParticleEmitterFactory::~ParticleEmitterFactory() - { - OGRE_IGNORE_DEPRECATED_BEGIN - // Destroy all emitters - for (auto& e : mEmitters) - { - OGRE_DELETE e; - } - - mEmitters.clear(); - OGRE_IGNORE_DEPRECATED_END - } - //----------------------------------------------------------------------- - void ParticleEmitterFactory::destroyEmitter(ParticleEmitter* e) - { - delete e; - OGRE_IGNORE_DEPRECATED_BEGIN - auto i = std::find(std::begin(mEmitters), std::end(mEmitters), e); - if (i != std::end(mEmitters)) { - mEmitters.erase(i); - } - OGRE_IGNORE_DEPRECATED_END - } - - //----------------------------------------------------------------------- -} - diff --git a/OgreMain/src/OgreParticleEmitterCommands.cpp b/OgreMain/src/OgreParticleEmitterCommands.cpp deleted file mode 100644 index 87165ac9f10..00000000000 --- a/OgreMain/src/OgreParticleEmitterCommands.cpp +++ /dev/null @@ -1,274 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreParticleEmitterCommands.h" -#include "OgreParticleEmitter.h" - -namespace Ogre { - - namespace EmitterCommands { - - //----------------------------------------------------------------------- - String CmdAngle::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getAngle() ); - } - void CmdAngle::doSet(void* target, const String& val) - { - static_cast(target)->setAngle(StringConverter::parseAngle(val)); - } - //----------------------------------------------------------------------- - String CmdColour::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getColour() ); - } - void CmdColour::doSet(void* target, const String& val) - { - static_cast(target)->setColour(StringConverter::parseColourValue(val)); - } - //----------------------------------------------------------------------- - String CmdColourRangeStart::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getColourRangeStart() ); - } - void CmdColourRangeStart::doSet(void* target, const String& val) - { - static_cast(target)->setColourRangeStart(StringConverter::parseColourValue(val)); - } - //----------------------------------------------------------------------- - String CmdColourRangeEnd::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getColourRangeEnd() ); - } - void CmdColourRangeEnd::doSet(void* target, const String& val) - { - static_cast(target)->setColourRangeEnd(StringConverter::parseColourValue(val)); - } - //----------------------------------------------------------------------- - String CmdDirection::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getDirection() ); - } - void CmdDirection::doSet(void* target, const String& val) - { - static_cast(target)->setDirection(StringConverter::parseVector3(val)); - } - //----------------------------------------------------------------------- - String CmdUp::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getUp() ); - } - void CmdUp::doSet(void* target, const String& val) - { - static_cast(target)->setUp(StringConverter::parseVector3(val)); - } - //----------------------------------------------------------------------- - String CmdDirPositionRef::doGet(const void* target) const - { - Vector4 val( static_cast(target)->getDirPositionReference() ); - val.w = static_cast(target)->getDirPositionReferenceEnabled(); - return StringConverter::toString( val ); - } - void CmdDirPositionRef::doSet(void* target, const String& val) - { - const Vector4 parsed = StringConverter::parseVector4(val); - const Vector3 vPos( parsed.x, parsed.y, parsed.z ); - static_cast(target)->setDirPositionReference( vPos, parsed.w != 0 ); - } - //----------------------------------------------------------------------- - String CmdEmissionRate::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getEmissionRate() ); - } - void CmdEmissionRate::doSet(void* target, const String& val) - { - static_cast(target)->setEmissionRate(StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String CmdMaxTTL::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getMaxTimeToLive() ); - } - void CmdMaxTTL::doSet(void* target, const String& val) - { - static_cast(target)->setMaxTimeToLive(StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String CmdMinTTL::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getMinTimeToLive() ); - } - void CmdMinTTL::doSet(void* target, const String& val) - { - static_cast(target)->setMinTimeToLive(StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String CmdMaxVelocity::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getMaxParticleVelocity() ); - } - void CmdMaxVelocity::doSet(void* target, const String& val) - { - static_cast(target)->setMaxParticleVelocity(StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String CmdMinVelocity::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getMinParticleVelocity() ); - } - void CmdMinVelocity::doSet(void* target, const String& val) - { - static_cast(target)->setMinParticleVelocity(StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String CmdPosition::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getPosition() ); - } - void CmdPosition::doSet(void* target, const String& val) - { - static_cast(target)->setPosition(StringConverter::parseVector3(val)); - } - //----------------------------------------------------------------------- - String CmdTTL::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getTimeToLive() ); - } - void CmdTTL::doSet(void* target, const String& val) - { - static_cast(target)->setTimeToLive(StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String CmdVelocity::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getParticleVelocity() ); - } - void CmdVelocity::doSet(void* target, const String& val) - { - static_cast(target)->setParticleVelocity(StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String CmdDuration::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getDuration() ); - } - void CmdDuration::doSet(void* target, const String& val) - { - static_cast(target)->setDuration(StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String CmdMinDuration::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getMinDuration() ); - } - void CmdMinDuration::doSet(void* target, const String& val) - { - static_cast(target)->setMinDuration(StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String CmdMaxDuration::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getMaxDuration() ); - } - void CmdMaxDuration::doSet(void* target, const String& val) - { - static_cast(target)->setMaxDuration(StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String CmdRepeatDelay::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getRepeatDelay() ); - } - void CmdRepeatDelay::doSet(void* target, const String& val) - { - static_cast(target)->setRepeatDelay(StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String CmdMinRepeatDelay::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getMinRepeatDelay() ); - } - void CmdMinRepeatDelay::doSet(void* target, const String& val) - { - static_cast(target)->setMinRepeatDelay(StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String CmdMaxRepeatDelay::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getMaxRepeatDelay() ); - } - void CmdMaxRepeatDelay::doSet(void* target, const String& val) - { - static_cast(target)->setMaxRepeatDelay(StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String CmdName::doGet(const void* target) const - { - return - static_cast(target)->getName(); - } - void CmdName::doSet(void* target, const String& val) - { - static_cast(target)->setName(val); - } - //----------------------------------------------------------------------- - String CmdEmittedEmitter::doGet(const void* target) const - { - return - static_cast(target)->getEmittedEmitter(); - } - void CmdEmittedEmitter::doSet(void* target, const String& val) - { - static_cast(target)->setEmittedEmitter(val); - } - - - - } -} - diff --git a/OgreMain/src/OgreParticleEmitterCommands.h b/OgreMain/src/OgreParticleEmitterCommands.h deleted file mode 100644 index f9aef4e0961..00000000000 --- a/OgreMain/src/OgreParticleEmitterCommands.h +++ /dev/null @@ -1,223 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ParticleEmitterCommands_H__ -#define __ParticleEmitterCommands_H__ - -#include "OgrePrerequisites.h" -#include "OgreStringInterface.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Effects - * @{ - */ - - namespace EmitterCommands { - /// Command object for ParticleEmitter - see ParamCommand - class CmdAngle : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for particle emitter - see ParamCommand - class CmdColour : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /// Command object for particle emitter - see ParamCommand - class CmdColourRangeStart : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for particle emitter - see ParamCommand - class CmdColourRangeEnd : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /// Command object for particle emitter - see ParamCommand - class CmdDirection : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /// Command object for particle emitter - see ParamCommand - class CmdUp : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /// Command object for particle emitter - see ParamCommand - class CmdDirPositionRef : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /// Command object for particle emitter - see ParamCommand - class CmdEmissionRate : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for particle emitter - see ParamCommand - class CmdVelocity : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for particle emitter - see ParamCommand - class CmdMinVelocity : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for particle emitter - see ParamCommand - class CmdMaxVelocity : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for particle emitter - see ParamCommand - class CmdTTL : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for particle emitter - see ParamCommand - class CmdMinTTL : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for particle emitter - see ParamCommand - class CmdMaxTTL : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for particle emitter - see ParamCommand - class CmdPosition : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for particle emitter - see ParamCommand - class CmdDuration : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for particle emitter - see ParamCommand - class CmdMinDuration : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for particle emitter - see ParamCommand - class CmdMaxDuration : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for particle emitter - see ParamCommand - class CmdRepeatDelay : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for particle emitter - see ParamCommand - class CmdMinRepeatDelay : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for particle emitter - see ParamCommand - class CmdMaxRepeatDelay : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for particle emitter - see ParamCommand - class CmdName : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /// Command object for particle emitter - see ParamCommand - class CmdEmittedEmitter : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - } - /** @} */ - /** @} */ - -} - - - - - -#endif - diff --git a/OgreMain/src/OgreParticleSystem.cpp b/OgreMain/src/OgreParticleSystem.cpp deleted file mode 100644 index 1f525f69c02..00000000000 --- a/OgreMain/src/OgreParticleSystem.cpp +++ /dev/null @@ -1,1582 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreParticleSystem.h" -#include "OgreParticleEmitter.h" -#include "OgreParticleAffector.h" -#include "OgreParticle.h" -#include "OgreParticleAffectorFactory.h" -#include "OgreParticleSystemRenderer.h" -#include "OgreControllerManager.h" - -namespace Ogre { - /** Command object for quota (see ParamCommand).*/ - class _OgrePrivate CmdQuota : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for emittedEmitterQuota (see ParamCommand).*/ - class _OgrePrivate CmdEmittedEmitterQuota : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for material (see ParamCommand).*/ - class _OgrePrivate CmdMaterial : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for cull_each (see ParamCommand).*/ - class _OgrePrivate CmdCull : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for particle_width (see ParamCommand).*/ - class _OgrePrivate CmdWidth : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for particle_height (see ParamCommand).*/ - class _OgrePrivate CmdHeight : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for renderer (see ParamCommand).*/ - class _OgrePrivate CmdRenderer : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for sorting (see ParamCommand).*/ - class CmdSorted : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for local space (see ParamCommand).*/ - class CmdLocalSpace : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for iteration interval(see ParamCommand).*/ - class CmdIterationInterval : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for nonvisible timeout (see ParamCommand).*/ - class CmdNonvisibleTimeout : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command objects - static CmdCull msCullCmd; - static CmdHeight msHeightCmd; - static CmdMaterial msMaterialCmd; - static CmdQuota msQuotaCmd; - static CmdEmittedEmitterQuota msEmittedEmitterQuotaCmd; - static CmdWidth msWidthCmd; - static CmdRenderer msRendererCmd; - static CmdSorted msSortedCmd; - static CmdLocalSpace msLocalSpaceCmd; - static CmdIterationInterval msIterationIntervalCmd; - static CmdNonvisibleTimeout msNonvisibleTimeoutCmd; - - Real ParticleSystem::msDefaultIterationInterval = 0; - Real ParticleSystem::msDefaultNonvisibleTimeout = 0; - - //----------------------------------------------------------------------- - // Local class for updating based on time - class ParticleSystemUpdateValue : public ControllerValue - { - protected: - ParticleSystem* mTarget; - public: - ParticleSystemUpdateValue(ParticleSystem* target) : mTarget(target) {} - - float getValue(void) const override { return 0; } // N/A - - void setValue(float value) override { mTarget->_update(value); } - - }; - //----------------------------------------------------------------------- - ParticleSystem::ParticleSystem() - : mAABB(), - mBoundingRadius(1.0f), - mBoundsAutoUpdate(true), - mBoundsUpdateTime(10.0f), - mUpdateRemainTime(0), - mResourceGroupName(ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME), - mIsRendererConfigured(false), - mSpeedFactor(1.0f), - mIterationInterval(0), - mIterationIntervalSet(false), - mSorted(false), - mLocalSpace(false), - mNonvisibleTimeout(0), - mNonvisibleTimeoutSet(false), - mTimeSinceLastVisible(0), - mLastVisibleFrame(0), - mTimeController(0), - mEmittedEmitterPoolInitialised(false), - mIsEmitting(true), - mRenderer(0), - mCullIndividual(false), - mPoolSize(0), - mEmittedEmitterPoolSize(0) - { - initParameters(); - - // Default to billboard renderer - setRenderer("billboard"); - mCastShadows = false; - } - //----------------------------------------------------------------------- - ParticleSystem::ParticleSystem(const String& name, const String& resourceGroup) - : MovableObject(name), - mAABB(), - mBoundingRadius(1.0f), - mBoundsAutoUpdate(true), - mBoundsUpdateTime(10.0f), - mUpdateRemainTime(0), - mResourceGroupName(resourceGroup), - mIsRendererConfigured(false), - mSpeedFactor(1.0f), - mIterationInterval(0), - mIterationIntervalSet(false), - mSorted(false), - mLocalSpace(false), - mNonvisibleTimeout(0), - mNonvisibleTimeoutSet(false), - mTimeSinceLastVisible(0), - mLastVisibleFrame(Root::getSingleton().getNextFrameNumber()), - mTimeController(0), - mEmittedEmitterPoolInitialised(false), - mIsEmitting(true), - mRenderer(0), - mCullIndividual(false), - mPoolSize(0), - mEmittedEmitterPoolSize(0) - { - setDefaultDimensions( 100, 100 ); - mMaterial = MaterialManager::getSingleton().getDefaultMaterial(); - // Default to 10 particles, expect app to specify (will only be increased, not decreased) - setParticleQuota( 10 ); - setEmittedEmitterQuota( 3 ); - initParameters(); - - // Default to billboard renderer - setRenderer("billboard"); - mCastShadows = false; - } - //----------------------------------------------------------------------- - ParticleSystem::~ParticleSystem() - { - if (mTimeController) - { - // Destroy controller - ControllerManager::getSingleton().destroyController(mTimeController); - mTimeController = 0; - } - - // Arrange for the deletion of emitters & affectors - removeAllEmitters(); - removeAllEmittedEmitters(); - removeAllAffectors(); - - // Free pool items - for (auto p : mParticlePool) - { - OGRE_DELETE p; - } - - if (mRenderer) - { - ParticleSystemManager::getSingleton()._destroyRenderer(mRenderer); - mRenderer = 0; - } - - } - //----------------------------------------------------------------------- - ParticleEmitter* ParticleSystem::addEmitter(const String& emitterType) - { - ParticleEmitter* em = - ParticleSystemManager::getSingleton()._createEmitter(emitterType, this); - mEmitters.push_back(em); - return em; - } - //----------------------------------------------------------------------- - ParticleEmitter* ParticleSystem::getEmitter(unsigned short index) const - { - assert(index < mEmitters.size() && "Emitter index out of bounds!"); - return mEmitters[index]; - } - //----------------------------------------------------------------------- - unsigned short ParticleSystem::getNumEmitters(void) const - { - return static_cast< unsigned short >( mEmitters.size() ); - } - //----------------------------------------------------------------------- - void ParticleSystem::removeEmitter(unsigned short index) - { - assert(index < mEmitters.size() && "Emitter index out of bounds!"); - ParticleEmitterList::iterator ei = mEmitters.begin() + index; - ParticleSystemManager::getSingleton()._destroyEmitter(*ei); - mEmitters.erase(ei); - } - //----------------------------------------------------------------------- - void ParticleSystem::removeEmitter(ParticleEmitter* emitter) - { - auto ei = std::find(mEmitters.begin(), mEmitters.end(), emitter); - OgreAssert(ei != mEmitters.end(), "Emitter is not a part of ParticleSystem!"); - ParticleSystemManager::getSingleton()._destroyEmitter(*ei); - mEmitters.erase(ei); - } - //----------------------------------------------------------------------- - void ParticleSystem::removeAllEmitters(void) - { - // DON'T delete directly, we don't know what heap these have been created on - for (auto e : mEmitters) - { - ParticleSystemManager::getSingleton()._destroyEmitter(e); - } - mEmitters.clear(); - } - //----------------------------------------------------------------------- - ParticleAffector* ParticleSystem::addAffector(const String& affectorType) - { - ParticleAffector* af = - ParticleSystemManager::getSingleton()._createAffector(affectorType, this); - mAffectors.push_back(af); - return af; - } - //----------------------------------------------------------------------- - ParticleAffector* ParticleSystem::getAffector(unsigned short index) const - { - assert(index < mAffectors.size() && "Affector index out of bounds!"); - return mAffectors[index]; - } - //----------------------------------------------------------------------- - unsigned short ParticleSystem::getNumAffectors(void) const - { - return static_cast< unsigned short >( mAffectors.size() ); - } - //----------------------------------------------------------------------- - void ParticleSystem::removeAffector(unsigned short index) - { - assert(index < mAffectors.size() && "Affector index out of bounds!"); - ParticleAffectorList::iterator ai = mAffectors.begin() + index; - ParticleSystemManager::getSingleton()._destroyAffector(*ai); - mAffectors.erase(ai); - } - //----------------------------------------------------------------------- - void ParticleSystem::removeAllAffectors(void) - { - // DON'T delete directly, we don't know what heap these have been created on - for (auto a : mAffectors) - { - ParticleSystemManager::getSingleton()._destroyAffector(a); - } - mAffectors.clear(); - } - //----------------------------------------------------------------------- - ParticleSystem& ParticleSystem::operator=(const ParticleSystem& rhs) - { - // Blank this system's emitters & affectors - removeAllEmitters(); - removeAllEmittedEmitters(); - removeAllAffectors(); - - // Copy emitters - for(unsigned short i = 0; i < rhs.getNumEmitters(); ++i) - { - ParticleEmitter* rhsEm = rhs.getEmitter(i); - ParticleEmitter* newEm = addEmitter(rhsEm->getType()); - rhsEm->copyParametersTo(newEm); - } - // Copy affectors - for(unsigned short i = 0; i < rhs.getNumAffectors(); ++i) - { - ParticleAffector* rhsAf = rhs.getAffector(i); - ParticleAffector* newAf = addAffector(rhsAf->getType()); - rhsAf->copyParametersTo(newAf); - } - setParticleQuota(rhs.getParticleQuota()); - setEmittedEmitterQuota(rhs.getEmittedEmitterQuota()); - setMaterialName(rhs.getMaterialName()); - setDefaultDimensions(rhs.mDefaultWidth, rhs.mDefaultHeight); - mCullIndividual = rhs.mCullIndividual; - mSorted = rhs.mSorted; - mLocalSpace = rhs.mLocalSpace; - mIterationInterval = rhs.mIterationInterval; - mIterationIntervalSet = rhs.mIterationIntervalSet; - mNonvisibleTimeout = rhs.mNonvisibleTimeout; - mNonvisibleTimeoutSet = rhs.mNonvisibleTimeoutSet; - // last frame visible and time since last visible should be left default - - setRenderer(rhs.getRendererName()); - // Copy settings - if (mRenderer && rhs.getRenderer()) - { - rhs.getRenderer()->copyParametersTo(mRenderer); - } - - return *this; - - } - //----------------------------------------------------------------------- - size_t ParticleSystem::getNumParticles(void) const - { - return mActiveParticles.size(); - } - //----------------------------------------------------------------------- - size_t ParticleSystem::getParticleQuota(void) const - { - return mPoolSize; - } - //----------------------------------------------------------------------- - void ParticleSystem::setParticleQuota(size_t size) - { - // Never shrink below size() - size_t currSize = mParticlePool.size(); - - if( currSize < size ) - { - // Will allocate particles on demand - mPoolSize = size; - - } - } - //----------------------------------------------------------------------- - size_t ParticleSystem::getEmittedEmitterQuota(void) const - { - return mEmittedEmitterPoolSize; - } - //----------------------------------------------------------------------- - void ParticleSystem::setEmittedEmitterQuota(size_t size) - { - // Never shrink below size() - size_t currSize = 0; - for (auto& kv : mEmittedEmitterPool) - { - currSize += kv.second.size(); - } - - if( currSize < size ) - { - // Will allocate emitted emitters on demand - mEmittedEmitterPoolSize = size; - } - } - //----------------------------------------------------------------------- - void ParticleSystem::setNonVisibleUpdateTimeout(Real timeout) - { - mNonvisibleTimeout = timeout; - mNonvisibleTimeoutSet = true; - } - //----------------------------------------------------------------------- - void ParticleSystem::setIterationInterval(Real interval) - { - mIterationInterval = interval; - mIterationIntervalSet = true; - } - //----------------------------------------------------------------------- - void ParticleSystem::_update(Real timeElapsed) - { - // Only update if attached to a node - if (!mParentNode) - return; - - Real nonvisibleTimeout = mNonvisibleTimeoutSet ? - mNonvisibleTimeout : msDefaultNonvisibleTimeout; - - if (nonvisibleTimeout > 0) - { - // Check whether it's been more than one frame (update is ahead of - // camera notification by one frame because of the ordering) - long frameDiff = Root::getSingleton().getNextFrameNumber() - mLastVisibleFrame; - if (frameDiff > 1 || frameDiff < 0) // < 0 if wrap only - { - mTimeSinceLastVisible += timeElapsed; - if (mTimeSinceLastVisible >= nonvisibleTimeout) - { - // No update - return; - } - } - } - - // Scale incoming speed for the rest of the calculation - timeElapsed *= mSpeedFactor; - - // Init renderer if not done already - configureRenderer(); - - // Initialise emitted emitters list if not done already - initialiseEmittedEmitters(); - - Real iterationInterval = mIterationIntervalSet ? - mIterationInterval : msDefaultIterationInterval; - if (iterationInterval > 0) - { - mUpdateRemainTime += timeElapsed; - - while (mUpdateRemainTime >= iterationInterval) - { - // Update existing particles - _expire(iterationInterval); - _triggerAffectors(iterationInterval); - _applyMotion(iterationInterval); - - if(mIsEmitting) - { - // Emit new particles - _triggerEmitters(iterationInterval); - } - - mUpdateRemainTime -= iterationInterval; - } - } - else - { - // Update existing particles - _expire(timeElapsed); - _triggerAffectors(timeElapsed); - _applyMotion(timeElapsed); - - if(mIsEmitting) - { - // Emit new particles - _triggerEmitters(timeElapsed); - } - } - - if (!mBoundsAutoUpdate && mBoundsUpdateTime > 0.0f) - mBoundsUpdateTime -= timeElapsed; // count down - _updateBounds(); - - } - //----------------------------------------------------------------------- - void ParticleSystem::_expire(Real timeElapsed) - { - Particle* pParticle; - ParticleEmitter* pParticleEmitter; - - auto iend = mActiveParticles.end(); - for (auto i = mActiveParticles.begin(); i != iend;) - { - pParticle = static_cast(*i); - if (pParticle->mTimeToLive < timeElapsed) - { - // Notify renderer - mRenderer->_notifyParticleExpired(pParticle); - - // Identify the particle type - if (pParticle->mParticleType == Particle::Visual) - { - // add back to free list - mFreeParticles.push_back(pParticle); - } - else - { - // For now, it can only be an emitted emitter - pParticleEmitter = static_cast(*i); - std::list* fee = findFreeEmittedEmitter(pParticleEmitter->getName()); - fee->push_back(pParticleEmitter); - - // Also erase from mActiveEmittedEmitters - removeFromActiveEmittedEmitters (pParticleEmitter); - } - - // And remove from mActiveParticles - *i = *(--iend); - } - else - { - // Decrement TTL - pParticle->mTimeToLive -= timeElapsed; - ++i; - } - } - - mActiveParticles.erase(iend, mActiveParticles.end()); - } - //----------------------------------------------------------------------- - void ParticleSystem::_triggerEmitters(Real timeElapsed) - { - // Add up requests for emission - static std::vector requested; - static std::vector emittedRequested; - - if( requested.size() != mEmitters.size() ) - requested.resize( mEmitters.size() ); - if( emittedRequested.size() != mEmittedEmitterPoolSize) - emittedRequested.resize( mEmittedEmitterPoolSize ); - - size_t totalRequested, emitterCount, emittedEmitterCount, i, emissionAllowed; - ParticleEmitterList::iterator itEmit, iEmitEnd; - ActiveEmittedEmitterList::iterator itActiveEmit, itActiveEnd; - - iEmitEnd = mEmitters.end(); - emitterCount = mEmitters.size(); - emittedEmitterCount=mActiveEmittedEmitters.size(); - itActiveEnd=mActiveEmittedEmitters.end(); - emissionAllowed = mFreeParticles.size(); - totalRequested = 0; - - // Count up total requested emissions for regular emitters (and exclude the ones that are used as - // a template for emitted emitters) - for (itEmit = mEmitters.begin(), i = 0; itEmit != iEmitEnd; ++itEmit, ++i) - { - if (!(*itEmit)->isEmitted()) - { - requested[i] = (*itEmit)->_getEmissionCount(timeElapsed); - totalRequested += requested[i]; - } - } - - // Add up total requested emissions for (active) emitted emitters - for (itActiveEmit = mActiveEmittedEmitters.begin(), i=0; itActiveEmit != itActiveEnd; ++itActiveEmit, ++i) - { - emittedRequested[i] = (*itActiveEmit)->_getEmissionCount(timeElapsed); - totalRequested += emittedRequested[i]; - } - - // Check if the quota will be exceeded, if so reduce demand - Real ratio = 1.0f; - if (totalRequested > emissionAllowed) - { - // Apportion down requested values to allotted values - ratio = (Real)emissionAllowed / (Real)totalRequested; - for (i = 0; i < emitterCount; ++i) - { - requested[i] = static_cast(requested[i] * ratio); - } - for (i = 0; i < emittedEmitterCount; ++i) - { - emittedRequested[i] = static_cast(emittedRequested[i] * ratio); - } - } - - // Emit - // For each emission, apply a subset of the motion for the frame - // this ensures an even distribution of particles when many are - // emitted in a single frame - for (itEmit = mEmitters.begin(), i = 0; itEmit != iEmitEnd; ++itEmit, ++i) - { - // Trigger the emitters, but exclude the emitters that are already in the emitted emitters list; - // they are handled in a separate loop - if (!(*itEmit)->isEmitted()) - _executeTriggerEmitters (*itEmit, static_cast(requested[i]), timeElapsed); - } - - // Do the same with all active emitted emitters - for (itActiveEmit = mActiveEmittedEmitters.begin(), i = 0; itActiveEmit != mActiveEmittedEmitters.end(); ++itActiveEmit, ++i) - _executeTriggerEmitters (*itActiveEmit, emittedRequested[i], timeElapsed); - } - //----------------------------------------------------------------------- - void ParticleSystem::_executeTriggerEmitters(ParticleEmitter* emitter, unsigned requested, Real timeElapsed) - { - Real timePoint = 0.0f; - - - // avoid any divide by zero conditions - if(!requested) - return; - - Real timeInc = timeElapsed / requested; - - for (unsigned int j = 0; j < requested; ++j) - { - // Create a new particle & init using emitter - // The particle is a visual particle if the emit_emitter property of the emitter isn't set - Particle* p = 0; - String emitterName = emitter->getEmittedEmitter(); - if (emitterName.empty()) - p = createParticle(); - else - p = createEmitterParticle(emitterName); - - // Only continue if the particle was really created (not null) - if (!p) - return; - - emitter->_initParticle(p); - - // Translate position & direction into world space - if (!mLocalSpace) - { - p->mPosition = mParentNode->convertLocalToWorldPosition(p->mPosition); - p->mDirection = mParentNode->convertLocalToWorldDirection(p->mDirection, false); - } - - // apply partial frame motion to this particle - p->mPosition += (p->mDirection * timePoint); - - // apply particle initialization by the affectors - for (auto a : mAffectors) - a->_initParticle(p); - - // Increment time fragment - timePoint += timeInc; - - // Notify renderer - mRenderer->_notifyParticleEmitted(p); - } - } - //----------------------------------------------------------------------- - void ParticleSystem::_applyMotion(Real timeElapsed) - { - for (auto pParticle : mActiveParticles) - { - pParticle->mPosition += (pParticle->mDirection * timeElapsed); - } - - // Notify renderer - mRenderer->_notifyParticleMoved(mActiveParticles); - } - //----------------------------------------------------------------------- - void ParticleSystem::_triggerAffectors(Real timeElapsed) - { - for (auto a : mAffectors) - { - a->_affectParticles(this, timeElapsed); - } - } - //----------------------------------------------------------------------- - void ParticleSystem::increasePool(size_t size) - { - size_t oldSize = mParticlePool.size(); - - // Increase size - mParticlePool.resize(size); - - // Create new particles - for( size_t i = oldSize; i < size; i++ ) - { - mParticlePool[i] = OGRE_NEW Particle(); - } - } - //----------------------------------------------------------------------- - Particle* ParticleSystem::getParticle(size_t index) - { - assert (index < mActiveParticles.size() && "Index out of bounds!"); - return mActiveParticles[index]; - } - //----------------------------------------------------------------------- - Particle* ParticleSystem::createParticle(void) - { - Particle* p = 0; - if (!mFreeParticles.empty()) - { - // Fast creation (don't use superclass since emitter will init) - p = mFreeParticles.back(); - mActiveParticles.push_back(p); - mFreeParticles.pop_back(); - } - - return p; - - } - //----------------------------------------------------------------------- - Particle* ParticleSystem::createEmitterParticle(const String& emitterName) - { - // Get the appropriate list and retrieve an emitter - ParticleEmitter* p = 0; - std::list* fee = findFreeEmittedEmitter(emitterName); - if (fee && !fee->empty()) - { - p = fee->front(); - p->mParticleType = Particle::Emitter; - fee->pop_front(); - mActiveParticles.push_back(p); - - // Also add to mActiveEmittedEmitters. This is needed to traverse through all active emitters - // that are emitted. Don't use mActiveParticles for that (although they are added to - // mActiveParticles also), because it would take too long to traverse. - mActiveEmittedEmitters.push_back(p); - } - - return p; - } - //----------------------------------------------------------------------- - void ParticleSystem::_updateRenderQueue(RenderQueue* queue) - { - if (mRenderer) - { - mRenderer->_updateRenderQueue(queue, mActiveParticles, mCullIndividual); - } - } - //--------------------------------------------------------------------- - void ParticleSystem::visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables) - { - if (mRenderer) - { - mRenderer->_notifyCastShadows(mCastShadows); - mRenderer->visitRenderables(visitor, debugRenderables); - } - } - //--------------------------------------------------------------------- - void ParticleSystem::initParameters(void) - { - if (createParamDictionary("ParticleSystem")) - { - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter(ParameterDef("quota", - "The maximum number of particles allowed at once in this system.", - PT_UNSIGNED_INT), - &msQuotaCmd); - - dict->addParameter(ParameterDef("emit_emitter_quota", - "The maximum number of emitters to be emitted at once in this system.", - PT_UNSIGNED_INT), - &msEmittedEmitterQuotaCmd); - - dict->addParameter(ParameterDef("material", - "The name of the material to be used to render all particles in this system.", - PT_STRING), - &msMaterialCmd); - - dict->addParameter(ParameterDef("particle_width", - "The width of particles in world units.", - PT_REAL), - &msWidthCmd); - - dict->addParameter(ParameterDef("particle_height", - "The height of particles in world units.", - PT_REAL), - &msHeightCmd); - - dict->addParameter(ParameterDef("cull_each", - "If true, each particle is culled in it's own right. If false, the entire system is culled as a whole.", - PT_BOOL), - &msCullCmd); - - dict->addParameter(ParameterDef("renderer", - "Sets the particle system renderer to use (default 'billboard').", - PT_STRING), - &msRendererCmd); - - dict->addParameter(ParameterDef("sorted", - "Sets whether particles should be sorted relative to the camera. ", - PT_BOOL), - &msSortedCmd); - - dict->addParameter(ParameterDef("local_space", - "Sets whether particles should be kept in local space rather than " - "emitted into world space. ", - PT_BOOL), - &msLocalSpaceCmd); - - dict->addParameter(ParameterDef("iteration_interval", - "Sets a fixed update interval for the system, or 0 for the frame rate. ", - PT_REAL), - &msIterationIntervalCmd); - - dict->addParameter(ParameterDef("nonvisible_update_timeout", - "Sets a timeout on updates to the system if the system is not visible " - "for the given number of seconds (0 to always update)", - PT_REAL), - &msNonvisibleTimeoutCmd); - - } - } - //----------------------------------------------------------------------- - void ParticleSystem::_updateBounds() - { - - if (mParentNode && (mBoundsAutoUpdate || mBoundsUpdateTime > 0.0f)) - { - if (mActiveParticles.empty()) - { - // No particles, reset to null if auto update bounds - if (mBoundsAutoUpdate) - { - mWorldAABB.setNull(); - } - } - else - { - Vector3 min; - Vector3 max; - if (!mBoundsAutoUpdate && mWorldAABB.isFinite()) - { - // We're on a limit, grow rather than reset each time - // so that we pick up the worst case scenario - min = mWorldAABB.getMinimum(); - max = mWorldAABB.getMaximum(); - } - else - { - min.x = min.y = min.z = Math::POS_INFINITY; - max.x = max.y = max.z = Math::NEG_INFINITY; - } - Vector3 halfScale = Vector3::UNIT_SCALE * 0.5; - for (auto p : mActiveParticles) - { - Vector3 padding = halfScale * std::max(p->mWidth, p->mHeight); - min.makeFloor(p->mPosition - padding); - max.makeCeil(p->mPosition + padding); - } - mWorldAABB.setExtents(min, max); - } - - - if (mLocalSpace) - { - if (mBoundsAutoUpdate) - mAABB = mWorldAABB; - else - // Merge calculated box with current AABB to preserve any user-set AABB - mAABB.merge(mWorldAABB); - } - else - { - // We've already put particles in world space to decouple them from the - // node transform, so reverse transform back since we're expected to - // provide a local AABB - AxisAlignedBox newAABB(mWorldAABB); - newAABB.transform(mParentNode->_getFullTransform().inverse()); - - if (mBoundsAutoUpdate) - mAABB = newAABB; - else - // Merge calculated box with current AABB to preserve any user-set AABB - mAABB.merge(newAABB); - } - - mParentNode->needUpdate(); - - if (mRenderer) - mRenderer->_notifyBoundingBox(mAABB); - } - } - //----------------------------------------------------------------------- - void ParticleSystem::fastForward(Real time, Real interval) - { - // First make sure all transforms are up to date - size_t steps = std::lround(time/interval); - for (size_t i = 0; i < steps; i++) - { - _update(interval); - } - } - //----------------------------------------------------------------------- - void ParticleSystem::setEmitting(bool v) - { - mIsEmitting = v; - } - //----------------------------------------------------------------------- - bool ParticleSystem::getEmitting() const - { - return mIsEmitting; - } - //----------------------------------------------------------------------- - const String& ParticleSystem::getMovableType(void) const - { - return MOT_PARTICLE_SYSTEM; - } - //----------------------------------------------------------------------- - void ParticleSystem::setDefaultDimensions( Real width, Real height ) - { - assert(width >= 0 && height >= 0 && "Particle dimensions can not be negative"); - mDefaultWidth = width; - mDefaultHeight = height; - if (mRenderer) - { - mRenderer->_notifyDefaultDimensions(width, height); - } - } - //----------------------------------------------------------------------- - void ParticleSystem::setDefaultWidth(Real width) - { - assert(width >= 0 && "Particle dimensions can not be negative"); - mDefaultWidth = width; - if (mRenderer) - { - mRenderer->_notifyDefaultDimensions(mDefaultWidth, mDefaultHeight); - } - } - //----------------------------------------------------------------------- - Real ParticleSystem::getDefaultWidth(void) const - { - return mDefaultWidth; - } - //----------------------------------------------------------------------- - void ParticleSystem::setDefaultHeight(Real height) - { - assert(height >= 0 && "Particle dimensions can not be negative"); - mDefaultHeight = height; - if (mRenderer) - { - mRenderer->_notifyDefaultDimensions(mDefaultWidth, mDefaultHeight); - } - } - //----------------------------------------------------------------------- - Real ParticleSystem::getDefaultHeight(void) const - { - return mDefaultHeight; - } - //----------------------------------------------------------------------- - void ParticleSystem::_notifyCurrentCamera(Camera* cam) - { - MovableObject::_notifyCurrentCamera(cam); - - // Record visible - if (isVisible()) - { - mLastVisibleFrame = Root::getSingleton().getNextFrameNumber(); - mTimeSinceLastVisible = 0.0f; - - if (mSorted) - { - _sortParticles(cam); - } - - if (mRenderer) - { - if (!mIsRendererConfigured) - configureRenderer(); - - mRenderer->_notifyCurrentCamera(cam); - } - } - } - //----------------------------------------------------------------------- - void ParticleSystem::_notifyAttached(Node* parent, bool isTagPoint) - { - MovableObject::_notifyAttached(parent, isTagPoint); - if (mRenderer && mIsRendererConfigured) - { - mRenderer->_notifyAttached(parent, isTagPoint); - } - - if (parent && !mTimeController) - { - // Assume visible - mTimeSinceLastVisible = 0; - mLastVisibleFrame = Root::getSingleton().getNextFrameNumber(); - - // Create time controller when attached - ControllerManager& mgr = ControllerManager::getSingleton(); - ControllerValueRealPtr updValue(OGRE_NEW ParticleSystemUpdateValue(this)); - mTimeController = mgr.createFrameTimePassthroughController(updValue); - } - else if (!parent && mTimeController) - { - // Destroy controller - ControllerManager::getSingleton().destroyController(mTimeController); - mTimeController = 0; - } - } - //----------------------------------------------------------------------- - void ParticleSystem::setMaterialName( const String& name, const String& groupName /* = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME */) - { - mMaterial = MaterialManager::getSingleton().getByName(name, groupName); - if (!mMaterial) - { - logMaterialNotFound(name, groupName, "ParticleSystem", mName); - mMaterial = MaterialManager::getSingleton().getDefaultMaterial(false); - } - if (mIsRendererConfigured) - { - mMaterial->load(); - mRenderer->_setMaterial(mMaterial); - } - } - //----------------------------------------------------------------------- - const String& ParticleSystem::getMaterialName(void) const - { - return mMaterial->getName(); - } - //----------------------------------------------------------------------- - void ParticleSystem::clear() - { - // Notify renderer if exists - if (mRenderer) - { - mRenderer->_notifyParticleCleared(mActiveParticles); - } - - // reset active and free lists - mActiveParticles.clear(); - mFreeParticles.clear(); - mFreeParticles.insert(mFreeParticles.end(), mParticlePool.begin(), mParticlePool.end()); - - // Add active emitted emitters to free list - addActiveEmittedEmittersToFreeList(); - - // Remove all active emitted emitter instances - mActiveEmittedEmitters.clear(); - - // Reset update remain time - mUpdateRemainTime = 0; - } - //----------------------------------------------------------------------- - void ParticleSystem::setRenderer(const String& rendererName) - { - if (mRenderer) - { - // Destroy existing - ParticleSystemManager::getSingleton()._destroyRenderer(mRenderer); - mRenderer = 0; - } - - if (!rendererName.empty()) - { - mRenderer = ParticleSystemManager::getSingleton()._createRenderer(rendererName); - mIsRendererConfigured = false; - } - } - //----------------------------------------------------------------------- - void ParticleSystem::configureRenderer(void) - { - // Actual allocate particles - size_t currSize = mParticlePool.size(); - size_t size = mPoolSize; - if( currSize < size ) - { - this->increasePool(size); - - // Add new items to the queue - mFreeParticles.insert(mFreeParticles.end(), mParticlePool.begin() + currSize, - mParticlePool.end()); - - // Tell the renderer, if already configured - if (mRenderer && mIsRendererConfigured) - { - mRenderer->_notifyParticleQuota(size); - } - } - - if (mRenderer && !mIsRendererConfigured) - { - mRenderer->_notifyParticleQuota(mParticlePool.size()); - mRenderer->_notifyAttached(mParentNode, mParentIsTagPoint); - mRenderer->_notifyDefaultDimensions(mDefaultWidth, mDefaultHeight); - mMaterial->load(); - mRenderer->_setMaterial(mMaterial); - if (mRenderQueueIDSet) - mRenderer->setRenderQueueGroup(mRenderQueueID); - mRenderer->setKeepParticlesInLocalSpace(mLocalSpace); - mIsRendererConfigured = true; - } - } - //----------------------------------------------------------------------- - ParticleSystemRenderer* ParticleSystem::getRenderer(void) const - { - return mRenderer; - } - //----------------------------------------------------------------------- - const String& ParticleSystem::getRendererName(void) const - { - if (mRenderer) - { - return mRenderer->getType(); - } - else - { - return BLANKSTRING; - } - } - //----------------------------------------------------------------------- - bool ParticleSystem::getCullIndividually(void) const - { - return mCullIndividual; - } - //----------------------------------------------------------------------- - void ParticleSystem::setCullIndividually(bool cullIndividual) - { - mCullIndividual = cullIndividual; - } - //----------------------------------------------------------------------- - void ParticleSystem::setBounds(const AxisAlignedBox& aabb) - { - mAABB = aabb; - mBoundingRadius = Math::boundingRadiusFromAABB(mAABB); - - } - //----------------------------------------------------------------------- - void ParticleSystem::setBoundsAutoUpdated(bool autoUpdate, Real stopIn) - { - mBoundsAutoUpdate = autoUpdate; - mBoundsUpdateTime = stopIn; - } - //----------------------------------------------------------------------- - void ParticleSystem::setRenderQueueGroup(uint8 queueID) - { - MovableObject::setRenderQueueGroup(queueID); - if (mRenderer) - { - mRenderer->setRenderQueueGroup(queueID); - } - } - //----------------------------------------------------------------------- - void ParticleSystem::setRenderQueueGroupAndPriority(uint8 queueID, ushort priority) - { - MovableObject::setRenderQueueGroupAndPriority(queueID, priority); - if (mRenderer) - { - mRenderer->setRenderQueueGroupAndPriority(queueID, priority); - } - } - //----------------------------------------------------------------------- - void ParticleSystem::setKeepParticlesInLocalSpace(bool keepLocal) - { - mLocalSpace = keepLocal; - if (mRenderer) - { - mRenderer->setKeepParticlesInLocalSpace(keepLocal); - } - } - //----------------------------------------------------------------------- - void ParticleSystem::_sortParticles(Camera* cam) - { - static RadixSort mRadixSorter; - if (mRenderer) - { - SortMode sortMode = - cam->getSortMode() == SM_DIRECTION ? SM_DIRECTION : mRenderer->_getSortMode(); - - if (sortMode == SM_DIRECTION) - { - Vector3 camDir = cam->getDerivedDirection(); - if (mLocalSpace) - { - // transform the camera direction into local space - camDir = mParentNode->convertWorldToLocalDirection(camDir, false); - } - mRadixSorter.sort(mActiveParticles, SortByDirectionFunctor(- camDir)); - } - else if (sortMode == SM_DISTANCE) - { - Vector3 camPos = cam->getDerivedPosition(); - if (mLocalSpace) - { - // transform the camera position into local space - camPos = mParentNode->convertWorldToLocalPosition(camPos); - } - mRadixSorter.sort(mActiveParticles, SortByDistanceFunctor(camPos)); - } - } - } - ParticleSystem::SortByDirectionFunctor::SortByDirectionFunctor(const Vector3& dir) - : sortDir(dir) - { - } - float ParticleSystem::SortByDirectionFunctor::operator()(Particle* p) const - { - return sortDir.dotProduct(p->mPosition); - } - ParticleSystem::SortByDistanceFunctor::SortByDistanceFunctor(const Vector3& pos) - : sortPos(pos) - { - } - float ParticleSystem::SortByDistanceFunctor::operator()(Particle* p) const - { - // Sort descending by squared distance - return - (sortPos - p->mPosition).squaredLength(); - } - //----------------------------------------------------------------------- - uint32 ParticleSystem::getTypeFlags(void) const - { - return SceneManager::FX_TYPE_MASK; - } - //----------------------------------------------------------------------- - void ParticleSystem::initialiseEmittedEmitters(void) - { - // Initialise the pool if needed - size_t currSize = 0; - if (mEmittedEmitterPool.empty()) - { - if (mEmittedEmitterPoolInitialised) - { - // It was already initialised, but apparently no emitted emitters were used - return; - } - else - { - initialiseEmittedEmitterPool(); - } - } - else - { - for (auto& kv : mEmittedEmitterPool) - { - currSize += kv.second.size(); - } - } - - size_t size = mEmittedEmitterPoolSize; - if( currSize < size && !mEmittedEmitterPool.empty()) - { - // Increase the pool. Equally distribute over all vectors in the map - increaseEmittedEmitterPool(size); - - // Add new items to the free list - addFreeEmittedEmitters(); - } - } - - //----------------------------------------------------------------------- - void ParticleSystem::initialiseEmittedEmitterPool(void) - { - if (mEmittedEmitterPoolInitialised) - return; - - // Run through mEmitters and add keys to the pool - for (ParticleEmitter* emitter : mEmitters) - { - // Determine the names of all emitters that are emitted - if (!emitter->getEmittedEmitter().empty()) - { - // This one will be emitted, register its name and leave the vector empty! - mEmittedEmitterPool[emitter->getEmittedEmitter()]; - } - } - - // Determine whether the emitter itself will be emitted and set the 'mEmitted' attribute - for (ParticleEmitter* emitter : mEmitters) - { - if (mEmittedEmitterPool.find(emitter->getName()) != mEmittedEmitterPool.end()) - { - emitter->setEmitted(true); - } - } - - mEmittedEmitterPoolInitialised = true; - } - //----------------------------------------------------------------------- - void ParticleSystem::increaseEmittedEmitterPool(size_t size) - { - // Don't proceed if the pool doesn't contain any keys of emitted emitters - if (mEmittedEmitterPool.empty()) - return; - - ParticleEmitter* clonedEmitter = 0; - size_t maxNumberOfEmitters = size / mEmittedEmitterPool.size(); // equally distribute the number for each emitted emitter list - - // Run through mEmittedEmitterPool and search for every key (=name) its corresponding emitter in mEmitters - for (auto& kv : mEmittedEmitterPool) - { - const auto& name = kv.first; - auto& e = kv.second; - - // Search the correct emitter in the mEmitters vector - for (ParticleEmitter* emitter : mEmitters) - { - if (name == emitter->getName()) - { - // Found the right emitter, clone each emitter a number of times - size_t oldSize = e.size(); - for (size_t t = oldSize; t < maxNumberOfEmitters; ++t) - { - clonedEmitter = ParticleSystemManager::getSingleton()._createEmitter(emitter->getType(), this); - emitter->copyParametersTo(clonedEmitter); - clonedEmitter->setEmitted(emitter->isEmitted()); // is always 'true' by the way, but just in case - - // Initially deactivate the emitted emitter if duration/repeat_delay are set - if (clonedEmitter->getDuration() != 0.0f && clonedEmitter->getRepeatDelay() > 0.0f) - clonedEmitter->setEnabled(false); - - // Add cloned emitters to the pool - e.push_back(clonedEmitter); - } - } - } - } - } - //----------------------------------------------------------------------- - void ParticleSystem::addFreeEmittedEmitters(void) - { - // Don't proceed if the EmittedEmitterPool is empty - if (mEmittedEmitterPool.empty()) - return; - - // Copy all pooled emitters to the free list - std::list* fee = 0; - - // Run through the emittedEmitterPool map - for (auto& kv : mEmittedEmitterPool) - { - const auto& name = kv.first; - auto& emittedEmitters = kv.second; - fee = findFreeEmittedEmitter(name); - - // If its not in the map, create an empty one - if (!fee) - { - mFreeEmittedEmitters[name]; - fee = findFreeEmittedEmitter(name); - } - - // Check anyway if its ok now - if (!fee) - return; // forget it! - - // Add all emitted emitters from the pool to the free list - for(ParticleEmitter* emitter : emittedEmitters) - { - fee->push_back(emitter); - } - } - } - //----------------------------------------------------------------------- - void ParticleSystem::removeAllEmittedEmitters(void) - { - for (auto& kv : mEmittedEmitterPool) - { - for (ParticleEmitter* emitter : kv.second) - { - ParticleSystemManager::getSingleton()._destroyEmitter(emitter); - } - kv.second.clear(); - } - - // Don't leave any references behind - mEmittedEmitterPool.clear(); - mFreeEmittedEmitters.clear(); - mActiveEmittedEmitters.clear(); - } - //----------------------------------------------------------------------- - std::list* ParticleSystem::findFreeEmittedEmitter (const String& name) - { - FreeEmittedEmitterMap::iterator it; - it = mFreeEmittedEmitters.find (name); - if (it != mFreeEmittedEmitters.end()) - { - // Found it - return &it->second; - } - - return 0; - } - //----------------------------------------------------------------------- - void ParticleSystem::removeFromActiveEmittedEmitters (ParticleEmitter* emitter) - { - assert(emitter && "Emitter to be removed is 0!"); - ActiveEmittedEmitterList::iterator itActiveEmit; - for (itActiveEmit = mActiveEmittedEmitters.begin(); itActiveEmit != mActiveEmittedEmitters.end(); ++itActiveEmit) - { - if (emitter == (*itActiveEmit)) - { - mActiveEmittedEmitters.erase(itActiveEmit); - break; - } - } - } - //----------------------------------------------------------------------- - void ParticleSystem::addActiveEmittedEmittersToFreeList (void) - { - ActiveEmittedEmitterList::iterator itActiveEmit; - for (itActiveEmit = mActiveEmittedEmitters.begin(); itActiveEmit != mActiveEmittedEmitters.end(); ++itActiveEmit) - { - std::list* fee = findFreeEmittedEmitter ((*itActiveEmit)->getName()); - if (fee) - fee->push_back(*itActiveEmit); - } - } - //----------------------------------------------------------------------- - void ParticleSystem::_notifyReorganiseEmittedEmitterData (void) - { - removeAllEmittedEmitters(); - mEmittedEmitterPoolInitialised = false; // Don't rearrange immediately; it will be performed in the regular flow - } - //----------------------------------------------------------------------- - String CmdCull::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getCullIndividually() ); - } - void CmdCull::doSet(void* target, const String& val) - { - static_cast(target)->setCullIndividually( - StringConverter::parseBool(val)); - } - //----------------------------------------------------------------------- - String CmdHeight::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getDefaultHeight() ); - } - void CmdHeight::doSet(void* target, const String& val) - { - static_cast(target)->setDefaultHeight( - StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String CmdWidth::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getDefaultWidth() ); - } - void CmdWidth::doSet(void* target, const String& val) - { - static_cast(target)->setDefaultWidth( - StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String CmdMaterial::doGet(const void* target) const - { - return static_cast(target)->getMaterialName(); - } - void CmdMaterial::doSet(void* target, const String& val) - { - static_cast(target)->setMaterialName(val); - } - //----------------------------------------------------------------------- - String CmdQuota::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getParticleQuota() ); - } - void CmdQuota::doSet(void* target, const String& val) - { - static_cast(target)->setParticleQuota( - StringConverter::parseUnsignedInt(val)); - } - //----------------------------------------------------------------------- - String CmdEmittedEmitterQuota::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getEmittedEmitterQuota() ); - } - void CmdEmittedEmitterQuota::doSet(void* target, const String& val) - { - static_cast(target)->setEmittedEmitterQuota( - StringConverter::parseUnsignedInt(val)); - } - //----------------------------------------------------------------------- - String CmdRenderer::doGet(const void* target) const - { - return static_cast(target)->getRendererName(); - } - void CmdRenderer::doSet(void* target, const String& val) - { - static_cast(target)->setRenderer(val); - } - //----------------------------------------------------------------------- - String CmdSorted::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getSortingEnabled()); - } - void CmdSorted::doSet(void* target, const String& val) - { - static_cast(target)->setSortingEnabled( - StringConverter::parseBool(val)); - } - //----------------------------------------------------------------------- - String CmdLocalSpace::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getKeepParticlesInLocalSpace()); - } - void CmdLocalSpace::doSet(void* target, const String& val) - { - static_cast(target)->setKeepParticlesInLocalSpace( - StringConverter::parseBool(val)); - } - //----------------------------------------------------------------------- - String CmdIterationInterval::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getIterationInterval()); - } - void CmdIterationInterval::doSet(void* target, const String& val) - { - static_cast(target)->setIterationInterval( - StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String CmdNonvisibleTimeout::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getNonVisibleUpdateTimeout()); - } - void CmdNonvisibleTimeout::doSet(void* target, const String& val) - { - static_cast(target)->setNonVisibleUpdateTimeout( - StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - ParticleAffector::~ParticleAffector() - { - } - //----------------------------------------------------------------------- - ParticleAffectorFactory::~ParticleAffectorFactory() - { - OGRE_IGNORE_DEPRECATED_BEGIN - // Destroy all affectors - for (auto *a : mAffectors) - { - OGRE_DELETE a; - } - - mAffectors.clear(); - OGRE_IGNORE_DEPRECATED_END - } - //----------------------------------------------------------------------- - void ParticleAffectorFactory::destroyAffector(ParticleAffector* e) - { - delete e; - OGRE_IGNORE_DEPRECATED_BEGIN - std::vector::iterator i; - for (i = mAffectors.begin(); i != mAffectors.end(); ++i) - { - if ((*i) == e) - { - mAffectors.erase(i); - break; - } - } - OGRE_IGNORE_DEPRECATED_END - } - -} diff --git a/OgreMain/src/OgreParticleSystemManager.cpp b/OgreMain/src/OgreParticleSystemManager.cpp deleted file mode 100644 index 8bbdc4735b5..00000000000 --- a/OgreMain/src/OgreParticleSystemManager.cpp +++ /dev/null @@ -1,401 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreParticleEmitterFactory.h" -#include "OgreParticleAffectorFactory.h" -#include "OgreParticleSystemRenderer.h" -#include "OgreBillboardParticleRenderer.h" -#include "OgreParticleSystem.h" - -namespace Ogre { - //----------------------------------------------------------------------- - // Shortcut to set up billboard particle renderer - BillboardParticleRendererFactory* mBillboardRendererFactory = 0; - //----------------------------------------------------------------------- - template<> ParticleSystemManager* Singleton::msSingleton = 0; - ParticleSystemManager* ParticleSystemManager::getSingletonPtr(void) - { - return msSingleton; - } - ParticleSystemManager& ParticleSystemManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //----------------------------------------------------------------------- - ParticleSystemManager::ParticleSystemManager() - { - OGRE_LOCK_AUTO_MUTEX; - mFactory = OGRE_NEW ParticleSystemFactory(); - Root::getSingleton().addMovableObjectFactory(mFactory); - } - //----------------------------------------------------------------------- - ParticleSystemManager::~ParticleSystemManager() - { - removeAllTemplates(true); // Destroy all templates - OGRE_LOCK_AUTO_MUTEX; - // delete billboard factory - if (mBillboardRendererFactory) - { - OGRE_DELETE mBillboardRendererFactory; - mBillboardRendererFactory = 0; - } - - if (mFactory) - { - // delete particle system factory - Root::getSingleton().removeMovableObjectFactory(mFactory); - OGRE_DELETE mFactory; - mFactory = 0; - } - - } - //----------------------------------------------------------------------- - void ParticleSystemManager::addEmitterFactory(ParticleEmitterFactory* factory) - { - OGRE_LOCK_AUTO_MUTEX; - String name = factory->getName(); - mEmitterFactories[name] = factory; - LogManager::getSingleton().logMessage("Particle Emitter Type '" + name + "' registered"); - } - //----------------------------------------------------------------------- - void ParticleSystemManager::addAffectorFactory(ParticleAffectorFactory* factory) - { - OGRE_LOCK_AUTO_MUTEX; - String name = factory->getName(); - mAffectorFactories[name] = factory; - LogManager::getSingleton().logMessage("Particle Affector Type '" + name + "' registered"); - } - //----------------------------------------------------------------------- - void ParticleSystemManager::addRendererFactory(ParticleSystemRendererFactory* factory) - { - OGRE_LOCK_AUTO_MUTEX ; - String name = factory->getType(); - mRendererFactories[name] = factory; - LogManager::getSingleton().logMessage("Particle Renderer Type '" + name + "' registered"); - } - //----------------------------------------------------------------------- - void ParticleSystemManager::addTemplate(const String& name, ParticleSystem* sysTemplate) - { - OGRE_LOCK_AUTO_MUTEX; - // check name - if (mSystemTemplates.find(name) != mSystemTemplates.end()) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "ParticleSystem template with name '" + name + "' already exists.", - "ParticleSystemManager::addTemplate"); - } - - mSystemTemplates[name] = sysTemplate; - } - //----------------------------------------------------------------------- - void ParticleSystemManager::removeTemplate(const String& name, bool deleteTemplate) - { - OGRE_LOCK_AUTO_MUTEX; - ParticleTemplateMap::iterator itr = mSystemTemplates.find(name); - if (itr == mSystemTemplates.end()) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "ParticleSystem template with name '" + name + "' cannot be found.", - "ParticleSystemManager::removeTemplate"); - - if (deleteTemplate) - OGRE_DELETE itr->second; - - mSystemTemplates.erase(itr); - } - //----------------------------------------------------------------------- - void ParticleSystemManager::removeAllTemplates(bool deleteTemplate) - { - OGRE_LOCK_AUTO_MUTEX; - if (deleteTemplate) - { - ParticleTemplateMap::iterator itr; - for (itr = mSystemTemplates.begin(); itr != mSystemTemplates.end(); ++itr) - OGRE_DELETE itr->second; - } - - mSystemTemplates.clear(); - } - //----------------------------------------------------------------------- - void ParticleSystemManager::removeTemplatesByResourceGroup(const String& resourceGroup) - { - OGRE_LOCK_AUTO_MUTEX; - - ParticleTemplateMap::iterator i = mSystemTemplates.begin(); - while (i != mSystemTemplates.end()) - { - ParticleTemplateMap::iterator icur = i++; - - if(icur->second->getResourceGroupName() == resourceGroup) - { - delete icur->second; - mSystemTemplates.erase(icur); - } - } - } - //----------------------------------------------------------------------- - ParticleSystem* ParticleSystemManager::createTemplate(const String& name, - const String& resourceGroup) - { - OGRE_LOCK_AUTO_MUTEX; - // check name - if (mSystemTemplates.find(name) != mSystemTemplates.end()) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT - LogManager::getSingleton().logMessage("ParticleSystem template with name '" + name + "' already exists."); - return NULL; -#else - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "ParticleSystem template with name '" + name + "' already exists.", - "ParticleSystemManager::createTemplate"); -#endif - } - - ParticleSystem* tpl = OGRE_NEW ParticleSystem(name, resourceGroup); - addTemplate(name, tpl); - return tpl; - - } - //----------------------------------------------------------------------- - ParticleSystem* ParticleSystemManager::getTemplate(const String& name) - { - OGRE_LOCK_AUTO_MUTEX; - ParticleTemplateMap::iterator i = mSystemTemplates.find(name); - if (i != mSystemTemplates.end()) - { - return i->second; - } - else - { - return 0; - } - } - //----------------------------------------------------------------------- - ParticleSystem* ParticleSystemManager::createSystemImpl(const String& name, - size_t quota, const String& resourceGroup) - { - ParticleSystem* sys = OGRE_NEW ParticleSystem(name, resourceGroup); - sys->setParticleQuota(quota); - return sys; - } - //----------------------------------------------------------------------- - ParticleSystem* ParticleSystemManager::createSystemImpl(const String& name, - const String& templateName) - { - // Look up template - ParticleSystem* pTemplate = getTemplate(templateName); - if (!pTemplate) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot find required template '" + templateName + "'", "ParticleSystemManager::createSystem"); - } - - ParticleSystem* sys = createSystemImpl(name, pTemplate->getParticleQuota(), - pTemplate->getResourceGroupName()); - // Copy template settings - *sys = *pTemplate; - return sys; - - } - //----------------------------------------------------------------------- - ParticleEmitter* ParticleSystemManager::_createEmitter( - const String& emitterType, ParticleSystem* psys) - { - OGRE_LOCK_AUTO_MUTEX; - // Locate emitter type - ParticleEmitterFactoryMap::iterator pFact = mEmitterFactories.find(emitterType); - - if (pFact == mEmitterFactories.end()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot find emitter type '" + emitterType + "'"); - } - - return pFact->second->createEmitter(psys); - } - //----------------------------------------------------------------------- - void ParticleSystemManager::_destroyEmitter(ParticleEmitter* emitter) - { - if(!emitter) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot destroy a null ParticleEmitter.", "ParticleSystemManager::_destroyEmitter"); - - OGRE_LOCK_AUTO_MUTEX; - // Destroy using the factory which created it - ParticleEmitterFactoryMap::iterator pFact = mEmitterFactories.find(emitter->getType()); - - if (pFact == mEmitterFactories.end()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot find emitter factory to destroy emitter.", - "ParticleSystemManager::_destroyEmitter"); - } - - pFact->second->destroyEmitter(emitter); - } - //----------------------------------------------------------------------- - ParticleAffector* ParticleSystemManager::_createAffector( - const String& affectorType, ParticleSystem* psys) - { - OGRE_LOCK_AUTO_MUTEX; - // Locate affector type - ParticleAffectorFactoryMap::iterator pFact = mAffectorFactories.find(affectorType); - - if (pFact == mAffectorFactories.end()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot find affector type '" + affectorType + "'"); - } - - return pFact->second->createAffector(psys); - - } - //----------------------------------------------------------------------- - void ParticleSystemManager::_destroyAffector(ParticleAffector* affector) - { - if(!affector) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot destroy a null ParticleAffector.", "ParticleSystemManager::_destroyAffector"); - - OGRE_LOCK_AUTO_MUTEX; - // Destroy using the factory which created it - ParticleAffectorFactoryMap::iterator pFact = mAffectorFactories.find(affector->getType()); - - if (pFact == mAffectorFactories.end()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot find affector factory to destroy affector.", - "ParticleSystemManager::_destroyAffector"); - } - - pFact->second->destroyAffector(affector); - } - //----------------------------------------------------------------------- - ParticleSystemRenderer* ParticleSystemManager::_createRenderer(const String& rendererType) - { - OGRE_LOCK_AUTO_MUTEX; - // Locate affector type - ParticleSystemRendererFactoryMap::iterator pFact = mRendererFactories.find(rendererType); - - if (pFact == mRendererFactories.end()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot find requested renderer type.", - "ParticleSystemManager::_createRenderer"); - } - - return pFact->second->createInstance(rendererType); - } - //----------------------------------------------------------------------- - void ParticleSystemManager::_destroyRenderer(ParticleSystemRenderer* renderer) - { - if(!renderer) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot destroy a null ParticleSystemRenderer.", "ParticleSystemManager::_destroyRenderer"); - - OGRE_LOCK_AUTO_MUTEX; - // Destroy using the factory which created it - ParticleSystemRendererFactoryMap::iterator pFact = mRendererFactories.find(renderer->getType()); - - if (pFact == mRendererFactories.end()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot find renderer factory to destroy renderer.", - "ParticleSystemManager::_destroyRenderer"); - } - - pFact->second->destroyInstance(renderer); - } - //----------------------------------------------------------------------- - void ParticleSystemManager::_initialise(void) - { - OGRE_LOCK_AUTO_MUTEX; - // Create Billboard renderer factory - mBillboardRendererFactory = OGRE_NEW BillboardParticleRendererFactory(); - addRendererFactory(mBillboardRendererFactory); - - } - //----------------------------------------------------------------------- - ParticleSystemManager::ParticleAffectorFactoryIterator - ParticleSystemManager::getAffectorFactoryIterator(void) - { - return ParticleAffectorFactoryIterator( - mAffectorFactories.begin(), mAffectorFactories.end()); - } - //----------------------------------------------------------------------- - ParticleSystemManager::ParticleEmitterFactoryIterator - ParticleSystemManager::getEmitterFactoryIterator(void) - { - return ParticleEmitterFactoryIterator( - mEmitterFactories.begin(), mEmitterFactories.end()); - } - //----------------------------------------------------------------------- - ParticleSystemManager::ParticleRendererFactoryIterator - ParticleSystemManager::getRendererFactoryIterator(void) - { - return ParticleRendererFactoryIterator( - mRendererFactories.begin(), mRendererFactories.end()); - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - const String MOT_PARTICLE_SYSTEM = "ParticleSystem"; - //----------------------------------------------------------------------- - MovableObject* ParticleSystemFactory::createInstanceImpl( const String& name, - const NameValuePairList* params) - { - if (params != 0) - { - NameValuePairList::const_iterator ni = params->find("templateName"); - if (ni != params->end()) - { - String templateName = ni->second; - // create using manager - return ParticleSystemManager::getSingleton().createSystemImpl( - name, templateName); - } - } - // Not template based, look for quota & resource name - size_t quota = 500; - String resourceGroup = ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME; - if (params != 0) - { - NameValuePairList::const_iterator ni = params->find("quota"); - if (ni != params->end()) - { - quota = StringConverter::parseUnsignedInt(ni->second); - } - ni = params->find("resourceGroup"); - if (ni != params->end()) - { - resourceGroup = ni->second; - } - } - // create using manager - return ParticleSystemManager::getSingleton().createSystemImpl( - name, quota, resourceGroup); - - - } - //----------------------------------------------------------------------- - const String& ParticleSystemFactory::getType(void) const - { - return MOT_PARTICLE_SYSTEM; - } - //----------------------------------------------------------------------- -} diff --git a/OgreMain/src/OgrePass.cpp b/OgreMain/src/OgrePass.cpp deleted file mode 100644 index d83c3d12883..00000000000 --- a/OgreMain/src/OgrePass.cpp +++ /dev/null @@ -1,1126 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include - -#include "OgreStableHeaders.h" - -#include "OgreGpuProgramUsage.h" -#include "OgreTextureUnitState.h" - -namespace Ogre { - - /** Default pass hash function. - - Tries to minimise the number of texture changes. - */ - struct MinTextureStateChangeHashFunc : public Pass::HashFunc - { - uint32 operator()(const Pass* p) const override - { - OGRE_LOCK_MUTEX(p->mTexUnitChangeMutex); - uint32 hash = 0; - ushort c = p->getNumTextureUnitStates(); - - for (ushort i = 0; i < c; ++i) - { - const TextureUnitState* tus = 0; - tus = p->getTextureUnitState(i); - hash = FastHash(tus->getTextureName().c_str(), tus->getTextureName().size(), hash); - } - - return hash; - } - }; - MinTextureStateChangeHashFunc sMinTextureStateChangeHashFunc; - /** Alternate pass hash function. - - Tries to minimise the number of GPU program changes. - */ - struct MinGpuProgramChangeHashFunc : public Pass::HashFunc - { - uint32 operator()(const Pass* p) const override - { - OGRE_LOCK_MUTEX(p->mGpuProgramChangeMutex); - uint32 hash = 0; - - for(int i = 0; i < GPT_COUNT; i++) - { - const String& name = p->getGpuProgramName(GpuProgramType(i)); - if(!name.empty()) { - hash = FastHash(name.c_str(), name.size(), hash); - } - } - - return hash; - } - }; - MinGpuProgramChangeHashFunc sMinGpuProgramChangeHashFunc; - //----------------------------------------------------------------------------- - Pass::PassSet Pass::msDirtyHashList; - Pass::PassSet Pass::msPassGraveyard; - OGRE_STATIC_MUTEX_INSTANCE(Pass::msDirtyHashListMutex); - OGRE_STATIC_MUTEX_INSTANCE(Pass::msPassGraveyardMutex); - - Pass::HashFunc* Pass::msHashFunc = &sMinGpuProgramChangeHashFunc; - //----------------------------------------------------------------------------- - Pass::HashFunc* Pass::getBuiltinHashFunction(BuiltinHashFunction builtin) - { - Pass::HashFunc* hashFunc = NULL; - - switch(builtin) - { - case MIN_TEXTURE_CHANGE: - hashFunc = &sMinTextureStateChangeHashFunc; - break; - case MIN_GPU_PROGRAM_CHANGE: - hashFunc = &sMinGpuProgramChangeHashFunc; - break; - } - - return hashFunc; - } - //----------------------------------------------------------------------------- - void Pass::setHashFunction(BuiltinHashFunction builtin) - { - switch(builtin) - { - case MIN_TEXTURE_CHANGE: - msHashFunc = &sMinTextureStateChangeHashFunc; - break; - case MIN_GPU_PROGRAM_CHANGE: - msHashFunc = &sMinGpuProgramChangeHashFunc; - break; - } - } - //----------------------------------------------------------------------------- - Pass::Pass(Technique* parent, unsigned short index) - : mParent(parent) - , mHash(0) - , mAmbient(ColourValue::White) - , mDiffuse(ColourValue::White) - , mSpecular(ColourValue::Black) - , mEmissive(ColourValue::Black) - , mShininess(0) - , mTracking(TVC_NONE) - , mHashDirtyQueued(false) - , mDepthCheck(true) - , mDepthWrite(true) - , mAlphaToCoverageEnabled(false) - , mTransparentSorting(true) - , mTransparentSortingForced(false) - , mLightingEnabled(true) - , mIteratePerLight(false) - , mRunOnlyForOneLightType(false) - , mPolygonModeOverrideable(true) - , mFogOverride(false) - , mQueuedForDeletion(false) - , mLightScissoring(false) - , mLightClipPlanes(false) - , mPointSpritesEnabled(false) - , mPointAttenuationEnabled(false) - , mContentTypeLookupBuilt(false) - , mAlphaRejectVal(0) - , mDepthBiasConstant(0.0f) - , mDepthBiasSlopeScale(0.0f) - , mDepthBiasPerIteration(0.0f) - , mDepthFunc(CMPF_LESS_EQUAL) - , mAlphaRejectFunc(CMPF_ALWAYS_PASS) - , mCullMode(CULL_CLOCKWISE) - , mManualCullMode(MANUAL_CULL_BACK) - , mMaxSimultaneousLights(OGRE_MAX_SIMULTANEOUS_LIGHTS) - , mStartLight(0) - , mLightsPerIteration(1) - , mIndex(index) - , mLightMask(0xFFFFFFFF) - , mFogColour(ColourValue::White) - , mFogStart(0.0) - , mFogEnd(1.0) - , mFogDensity(0.001) - , mLineWidth(1.0f) - , mPassIterationCount(1) - , mPointMinSize(0.0f) - , mPointMaxSize(0.0f) - , mPointAttenution(1.0f, 1.0f, 0.0f, 0.0f) - , mShadeOptions(SO_GOURAUD) - , mPolygonMode(PM_SOLID) - , mIlluminationStage(IS_UNKNOWN) - , mOnlyLightType(Light::LT_POINT) - , mFogMode(FOG_NONE) - { - // init the hash inline - _recalculateHash(); - } - - //----------------------------------------------------------------------------- - Pass::Pass(Technique *parent, unsigned short index, const Pass& oth) - : mParent(parent), mQueuedForDeletion(false), mIndex(index), mPassIterationCount(1) - { - *this = oth; - mParent = parent; - mIndex = index; - mQueuedForDeletion = false; - - // init the hash inline - _recalculateHash(); - } - Pass::~Pass() = default; // ensure unique_ptr destructors are in cpp - //----------------------------------------------------------------------------- - Pass& Pass::operator=(const Pass& oth) - { - mName = oth.mName; - mHash = oth.mHash; - mAmbient = oth.mAmbient; - mDiffuse = oth.mDiffuse; - mSpecular = oth.mSpecular; - mEmissive = oth.mEmissive; - mShininess = oth.mShininess; - mTracking = oth.mTracking; - - // Copy fog parameters - mFogOverride = oth.mFogOverride; - mFogMode = oth.mFogMode; - mFogColour = oth.mFogColour; - mFogStart = oth.mFogStart; - mFogEnd = oth.mFogEnd; - mFogDensity = oth.mFogDensity; - - // Default blending (overwrite) - mBlendState = oth.mBlendState; - - mDepthCheck = oth.mDepthCheck; - mDepthWrite = oth.mDepthWrite; - mAlphaRejectFunc = oth.mAlphaRejectFunc; - mAlphaRejectVal = oth.mAlphaRejectVal; - mAlphaToCoverageEnabled = oth.mAlphaToCoverageEnabled; - mTransparentSorting = oth.mTransparentSorting; - mTransparentSortingForced = oth.mTransparentSortingForced; - mDepthFunc = oth.mDepthFunc; - mDepthBiasConstant = oth.mDepthBiasConstant; - mDepthBiasSlopeScale = oth.mDepthBiasSlopeScale; - mDepthBiasPerIteration = oth.mDepthBiasPerIteration; - mCullMode = oth.mCullMode; - mManualCullMode = oth.mManualCullMode; - mLightingEnabled = oth.mLightingEnabled; - mMaxSimultaneousLights = oth.mMaxSimultaneousLights; - mStartLight = oth.mStartLight; - mIteratePerLight = oth.mIteratePerLight; - mLightsPerIteration = oth.mLightsPerIteration; - mRunOnlyForOneLightType = oth.mRunOnlyForOneLightType; - mOnlyLightType = oth.mOnlyLightType; - mShadeOptions = oth.mShadeOptions; - mPolygonMode = oth.mPolygonMode; - mPolygonModeOverrideable = oth.mPolygonModeOverrideable; - mPassIterationCount = oth.mPassIterationCount; - mLineWidth = oth.mLineWidth; - mPointAttenution = oth.mPointAttenution; - mPointMinSize = oth.mPointMinSize; - mPointMaxSize = oth.mPointMaxSize; - mPointSpritesEnabled = oth.mPointSpritesEnabled; - mPointAttenuationEnabled = oth.mPointAttenuationEnabled; - mShadowContentTypeLookup = oth.mShadowContentTypeLookup; - mContentTypeLookupBuilt = oth.mContentTypeLookupBuilt; - mLightScissoring = oth.mLightScissoring; - mLightClipPlanes = oth.mLightClipPlanes; - mIlluminationStage = oth.mIlluminationStage; - mLightMask = oth.mLightMask; - - for(int i = 0; i < GPT_COUNT; i++) - { - auto& programUsage = mProgramUsage[i]; - auto& othUsage = oth.mProgramUsage[i]; - programUsage = othUsage ? std::make_unique(*othUsage, this) : nullptr; - } - - // Clear texture units but doesn't notify need recompilation in the case - // we are cloning, The parent material will take care of this. - for (auto *t : mTextureUnitStates) - { - OGRE_DELETE t; - } - - mTextureUnitStates.clear(); - - // Copy texture units - for (auto *s : oth.mTextureUnitStates) - { - TextureUnitState* t = OGRE_NEW TextureUnitState(this, *s); - mTextureUnitStates.push_back(t); - } - - _dirtyHash(); - - return *this; - } - //----------------------------------------------------------------------------- - size_t Pass::calculateSize(void) const - { - size_t memSize = 0; - - // Tally up TU states - for (auto *t : mTextureUnitStates) - { - memSize += t->calculateSize(); - } - for(const auto& u : mProgramUsage) - memSize += u ? u->calculateSize() : 0; - - return memSize; - } - //----------------------------------------------------------------------- - void Pass::setPointAttenuation(bool enabled, float constant, float linear, float quadratic) - { - mPointAttenuationEnabled = enabled; - mPointAttenution[1] = enabled ? constant : 1.0f; - mPointAttenution[2] = enabled ? linear : 0.0f; - mPointAttenution[3] = enabled ? quadratic : 0.0f; - } - //----------------------------------------------------------------------- - void Pass::setPointMinSize(Real min) - { - mPointMinSize = min; - } - //----------------------------------------------------------------------- - Real Pass::getPointMinSize(void) const - { - return mPointMinSize; - } - //----------------------------------------------------------------------- - void Pass::setPointMaxSize(Real max) - { - mPointMaxSize = max; - } - //----------------------------------------------------------------------- - Real Pass::getPointMaxSize(void) const - { - return mPointMaxSize; - } - //----------------------------------------------------------------------- - void Pass::setAmbient(float red, float green, float blue) - { - mAmbient.r = red; - mAmbient.g = green; - mAmbient.b = blue; - - } - //----------------------------------------------------------------------- - void Pass::setDiffuse(float red, float green, float blue, float alpha) - { - mDiffuse.r = red; - mDiffuse.g = green; - mDiffuse.b = blue; - mDiffuse.a = alpha; - } - //----------------------------------------------------------------------- - void Pass::setSpecular(float red, float green, float blue, float alpha) - { - mSpecular.r = red; - mSpecular.g = green; - mSpecular.b = blue; - mSpecular.a = alpha; - } - //----------------------------------------------------------------------- - void Pass::setSelfIllumination(float red, float green, float blue) - { - mEmissive.r = red; - mEmissive.g = green; - mEmissive.b = blue; - } - //----------------------------------------------------------------------- - TextureUnitState* Pass::createTextureUnitState(void) - { - TextureUnitState *t = OGRE_NEW TextureUnitState(this); - addTextureUnitState(t); - mContentTypeLookupBuilt = false; - return t; - } - //----------------------------------------------------------------------- - TextureUnitState* Pass::createTextureUnitState( - const String& textureName, unsigned short texCoordSet) - { - TextureUnitState *t = OGRE_NEW TextureUnitState(this); - t->setTextureName(textureName); - t->setTextureCoordSet(texCoordSet); - addTextureUnitState(t); - mContentTypeLookupBuilt = false; - return t; - } - //----------------------------------------------------------------------- - void Pass::addTextureUnitState(TextureUnitState* state) - { - OGRE_LOCK_MUTEX(mTexUnitChangeMutex); - - OgreAssert(state , "TextureUnitState is NULL"); - - // only attach TUS to pass if TUS does not belong to another pass - OgreAssert(!state->getParent() || (state->getParent() == this), "TextureUnitState already attached to another pass"); - - mTextureUnitStates.push_back(state); - // Notify state - state->_notifyParent(this); - // if texture unit state name is empty then give it a default name based on its index - if (state->getName().empty()) - { - // its the last entry in the container so its index is size - 1 - size_t idx = mTextureUnitStates.size() - 1; - - // allow 8 digit hex number. there should never be that many texture units. - // This sprintf replaced a call to StringConverter::toString for performance reasons - state->setName( StringUtil::format("%lx", static_cast(idx))); - } - _notifyNeedsRecompile(); - _dirtyHash(); - - mContentTypeLookupBuilt = false; - } - //----------------------------------------------------------------------------- - TextureUnitState* Pass::getTextureUnitState(const String& name) const - { - OGRE_LOCK_MUTEX(mTexUnitChangeMutex); - TextureUnitState* foundTUS = 0; - - // iterate through TUS Container to find a match - for (auto *t : mTextureUnitStates) - { - if (t->getName() == name) - { - foundTUS = t; - break; - } - } - - return foundTUS; - } - - //----------------------------------------------------------------------- - unsigned short Pass::getTextureUnitStateIndex(const TextureUnitState* state) const - { - OGRE_LOCK_MUTEX(mTexUnitChangeMutex); - assert(state && "state is 0 in Pass::getTextureUnitStateIndex()"); - - // only find index for state attached to this pass - OgreAssert(state->getParent() == this, "TextureUnitState is not attached to this pass"); - auto i = std::find(mTextureUnitStates.begin(), mTextureUnitStates.end(), state); - assert(i != mTextureUnitStates.end() && "state is supposed to attached to this pass"); - return static_cast(std::distance(mTextureUnitStates.begin(), i)); - } - - //----------------------------------------------------------------------- - Pass::TextureUnitStateIterator - Pass::getTextureUnitStateIterator(void) - { - return TextureUnitStateIterator(mTextureUnitStates.begin(), mTextureUnitStates.end()); - } - //----------------------------------------------------------------------- - Pass::ConstTextureUnitStateIterator - Pass::getTextureUnitStateIterator(void) const - { - return ConstTextureUnitStateIterator(mTextureUnitStates.begin(), mTextureUnitStates.end()); - } - //----------------------------------------------------------------------- - void Pass::removeTextureUnitState(unsigned short index) - { - OGRE_LOCK_MUTEX(mTexUnitChangeMutex); - assert (index < mTextureUnitStates.size() && "Index out of bounds"); - - TextureUnitStates::iterator i = mTextureUnitStates.begin() + index; - OGRE_DELETE *i; - mTextureUnitStates.erase(i); - _notifyNeedsRecompile(); - _dirtyHash(); - mContentTypeLookupBuilt = false; - } - //----------------------------------------------------------------------- - void Pass::removeAllTextureUnitStates(void) - { - OGRE_LOCK_MUTEX(mTexUnitChangeMutex); - TextureUnitStates::iterator i, iend; - iend = mTextureUnitStates.end(); - for (i = mTextureUnitStates.begin(); i != iend; ++i) - { - OGRE_DELETE *i; - } - mTextureUnitStates.clear(); - _notifyNeedsRecompile(); - _dirtyHash(); - mContentTypeLookupBuilt = false; - } - //----------------------------------------------------------------------- - static void _getBlendFlags(SceneBlendType type, SceneBlendFactor& source, SceneBlendFactor& dest) - { - switch ( type ) - { - case SBT_TRANSPARENT_ALPHA: - source = SBF_SOURCE_ALPHA; - dest = SBF_ONE_MINUS_SOURCE_ALPHA; - return; - case SBT_TRANSPARENT_COLOUR: - source = SBF_SOURCE_COLOUR; - dest = SBF_ONE_MINUS_SOURCE_COLOUR; - return; - case SBT_MODULATE: - source = SBF_DEST_COLOUR; - dest = SBF_ZERO; - return; - case SBT_ADD: - source = SBF_ONE; - dest = SBF_ONE; - return; - default: - case SBT_REPLACE: - source = SBF_ONE; - dest = SBF_ZERO; - return; - } - } - //----------------------------------------------------------------------- - void Pass::setSceneBlending(SceneBlendType sbt) - { - // Convert type into blend factors - - SceneBlendFactor source; - SceneBlendFactor dest; - _getBlendFlags(sbt, source, dest); - - // Set blend factors - - setSceneBlending(source, dest); - } - //----------------------------------------------------------------------- - void Pass::setSeparateSceneBlending( const SceneBlendType sbt, const SceneBlendType sbta ) - { - // Convert types into blend factors - - SceneBlendFactor source; - SceneBlendFactor dest; - _getBlendFlags(sbt, source, dest); - - SceneBlendFactor sourceAlpha; - SceneBlendFactor destAlpha; - _getBlendFlags(sbta, sourceAlpha, destAlpha); - - // Set blend factors - - setSeparateSceneBlending(source, dest, sourceAlpha, destAlpha); - } - - //----------------------------------------------------------------------- - void Pass::setSceneBlending(SceneBlendFactor sourceFactor, SceneBlendFactor destFactor) - { - mBlendState.sourceFactor = sourceFactor; - mBlendState.sourceFactorAlpha = sourceFactor; - mBlendState.destFactor = destFactor; - mBlendState.destFactorAlpha = destFactor; - } - //----------------------------------------------------------------------- - void Pass::setSeparateSceneBlending( const SceneBlendFactor sourceFactor, const SceneBlendFactor destFactor, const SceneBlendFactor sourceFactorAlpha, const SceneBlendFactor destFactorAlpha ) - { - mBlendState.sourceFactor = sourceFactor; - mBlendState.destFactor = destFactor; - mBlendState.sourceFactorAlpha = sourceFactorAlpha; - mBlendState.destFactorAlpha = destFactorAlpha; - } - //----------------------------------------------------------------------- - void Pass::setSceneBlendingOperation(SceneBlendOperation op) - { - mBlendState.operation = op; - mBlendState.alphaOperation = op; - } - //----------------------------------------------------------------------- - void Pass::setSeparateSceneBlendingOperation(SceneBlendOperation op, SceneBlendOperation alphaOp) - { - mBlendState.operation = op; - mBlendState.alphaOperation = alphaOp; - } - //----------------------------------------------------------------------- - bool Pass::isTransparent(void) const - { - // Transparent if any of the destination colour is taken into account - if (mBlendState.destFactor == SBF_ZERO && - mBlendState.sourceFactor != SBF_DEST_COLOUR && - mBlendState.sourceFactor != SBF_ONE_MINUS_DEST_COLOUR && - mBlendState.sourceFactor != SBF_DEST_ALPHA && - mBlendState.sourceFactor != SBF_ONE_MINUS_DEST_ALPHA) - { - return false; - } - else - { - return true; - } - } - //----------------------------------------------------------------------- - void Pass::setAlphaRejectSettings(CompareFunction func, unsigned char value, bool alphaToCoverage) - { - mAlphaRejectFunc = func; - mAlphaRejectVal = value; - mAlphaToCoverageEnabled = alphaToCoverage; - } - //----------------------------------------------------------------------- - void Pass::setColourWriteEnabled(bool enabled) - { - mBlendState.writeR = enabled; - mBlendState.writeG = enabled; - mBlendState.writeB = enabled; - mBlendState.writeA = enabled; - } - //----------------------------------------------------------------------- - bool Pass::getColourWriteEnabled() const - { - return mBlendState.writeR || mBlendState.writeG || mBlendState.writeB || - mBlendState.writeA; - } - //----------------------------------------------------------------------- - - void Pass::setColourWriteEnabled(bool red, bool green, bool blue, bool alpha) - { - mBlendState.writeR = red; - mBlendState.writeG = green; - mBlendState.writeB = blue; - mBlendState.writeA = alpha; - } - //----------------------------------------------------------------------- - void Pass::getColourWriteEnabled(bool& red, bool& green, bool& blue, bool& alpha) const - { - red = mBlendState.writeR; - green = mBlendState.writeG; - blue = mBlendState.writeB; - alpha = mBlendState.writeA; - } - //----------------------------------------------------------------------- - void Pass::setIteratePerLight(bool enabled, - bool onlyForOneLightType, Light::LightTypes lightType) - { - mIteratePerLight = enabled; - mRunOnlyForOneLightType = onlyForOneLightType; - mOnlyLightType = lightType; - } - //----------------------------------------------------------------------- - void Pass::setManualCullingMode(ManualCullingMode mode) - { - mManualCullMode = mode; - } - //----------------------------------------------------------------------- - ManualCullingMode Pass::getManualCullingMode(void) const - { - return mManualCullMode; - } - //----------------------------------------------------------------------- - void Pass::setFog(bool overrideScene, FogMode mode, const ColourValue& colour, float density, float start, float end) - { - mFogOverride = overrideScene; - if (overrideScene) - { - mFogMode = mode; - mFogColour = colour; - mFogStart = start; - mFogEnd = end; - mFogDensity = density; - } - } - //----------------------------------------------------------------------- - void Pass::setDepthBias(float constantBias, float slopeScaleBias) - { - mDepthBiasConstant = constantBias; - mDepthBiasSlopeScale = slopeScaleBias; - } - //----------------------------------------------------------------------- - Pass* Pass::_split(unsigned short numUnits) - { - OgreAssert( - !isProgrammable(), - "Programmable passes cannot be automatically split, define a fallback technique instead"); - - if (mTextureUnitStates.size() > numUnits) - { - size_t start = mTextureUnitStates.size() - numUnits; - - Pass* newPass = mParent->createPass(); - - TextureUnitStates::iterator istart, i, iend; - iend = mTextureUnitStates.end(); - i = istart = mTextureUnitStates.begin() + start; - // Set the new pass to fallback using scene blend - newPass->setSceneBlending( - (*i)->getColourBlendFallbackSrc(), (*i)->getColourBlendFallbackDest()); - // Fixup the texture unit 0 of new pass blending method to replace - // all colour and alpha with texture without adjustment, because we - // assume it's detail texture. - (*i)->setColourOperationEx(LBX_SOURCE1, LBS_TEXTURE, LBS_CURRENT); - (*i)->setAlphaOperation(LBX_SOURCE1, LBS_TEXTURE, LBS_CURRENT); - - // Add all the other texture unit states - for (; i != iend; ++i) - { - // detach from parent first - (*i)->_notifyParent(0); - newPass->addTextureUnitState(*i); - } - // Now remove texture units from this Pass, we don't need to delete since they've - // been transferred - mTextureUnitStates.erase(istart, iend); - _dirtyHash(); - mContentTypeLookupBuilt = false; - return newPass; - } - return NULL; - } - //----------------------------------------------------------------------------- - void Pass::_notifyIndex(unsigned short index) - { - if (mIndex != index) - { - mIndex = index; - _dirtyHash(); - } - } - //----------------------------------------------------------------------- - void Pass::_prepare(void) - { - // We assume the Technique only calls this when the material is being - // prepared - // prepare each TextureUnitState - for (auto *t : mTextureUnitStates) - { - t->_prepare(); - } - - } - //----------------------------------------------------------------------- - void Pass::_unprepare(void) - { - // unprepare each TextureUnitState - for (auto *t : mTextureUnitStates) - { - t->_unprepare(); - } - - } - //----------------------------------------------------------------------- - void Pass::_load(void) - { - // We assume the Technique only calls this when the material is being - // loaded - // Load each TextureUnitState - for (auto *t : mTextureUnitStates) - { - t->_load(); - } - - // Load programs - for (const auto& u : mProgramUsage) - if(u) u->_load(); - - if (mHashDirtyQueued) - { - _dirtyHash(); - } - - } - //----------------------------------------------------------------------- - void Pass::_unload(void) - { - // Unload each TextureUnitState - for (auto *t : mTextureUnitStates) - { - t->_unload(); - } - - // TODO Unload programs - } - //----------------------------------------------------------------------- - void Pass::setVertexProgram(const String& name, bool resetParams) - { - setGpuProgram(GPT_VERTEX_PROGRAM, name, resetParams); - } - //----------------------------------------------------------------------- - void Pass::setGpuProgramParameters(GpuProgramType type, const GpuProgramParametersSharedPtr& params) - { - OGRE_LOCK_MUTEX(mGpuProgramChangeMutex); - - const auto& programUsage = getProgramUsage(type); - if (!programUsage) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "This pass does not have this program type assigned!"); - } - programUsage->setParameters(params); - } - void Pass::setVertexProgramParameters(GpuProgramParametersSharedPtr params) - { - setGpuProgramParameters(GPT_VERTEX_PROGRAM, params); - } - //----------------------------------------------------------------------- - void Pass::setGpuProgram(GpuProgramType type, const GpuProgramPtr& program, bool resetParams) - { - OGRE_LOCK_MUTEX(mGpuProgramChangeMutex); - - std::unique_ptr& programUsage = getProgramUsage(type); - - // Turn off fragment program if name blank - if (!program) - { - programUsage.reset(); - } - else - { - if (!programUsage) - { - programUsage = std::make_unique(type, this); - } - programUsage->setProgram(program, resetParams); - } - // Needs recompilation - _notifyNeedsRecompile(); - - if( Pass::getHashFunction() == Pass::getBuiltinHashFunction( Pass::MIN_GPU_PROGRAM_CHANGE ) ) - { - _dirtyHash(); - } - } - - void Pass::setGpuProgram(GpuProgramType type, const String& name, bool resetParams) - { - if (getGpuProgramName(type) == name) - return; - - GpuProgramPtr program; - if (!name.empty()) - program = GpuProgramUsage::_getProgramByName(name, getResourceGroup(), type); - - setGpuProgram(type, program, resetParams); - } - - void Pass::setFragmentProgram(const String& name, bool resetParams) - { - setGpuProgram(GPT_FRAGMENT_PROGRAM, name, resetParams); - } - //----------------------------------------------------------------------- - void Pass::setFragmentProgramParameters(GpuProgramParametersSharedPtr params) - { - setGpuProgramParameters(GPT_FRAGMENT_PROGRAM, params); - } - //----------------------------------------------------------------------- - void Pass::setGeometryProgram(const String& name, bool resetParams) - { - setGpuProgram(GPT_GEOMETRY_PROGRAM, name, resetParams); - } - //----------------------------------------------------------------------- - void Pass::setGeometryProgramParameters(GpuProgramParametersSharedPtr params) - { - setGpuProgramParameters(GPT_GEOMETRY_PROGRAM, params); - } - //----------------------------------------------------------------------- - void Pass::setTessellationHullProgram(const String& name, bool resetParams) - { - setGpuProgram(GPT_HULL_PROGRAM, name, resetParams); - } - //----------------------------------------------------------------------- - void Pass::setTessellationHullProgramParameters(GpuProgramParametersSharedPtr params) - { - setGpuProgramParameters(GPT_HULL_PROGRAM, params); - } - //----------------------------------------------------------------------- - void Pass::setTessellationDomainProgram(const String& name, bool resetParams) - { - setGpuProgram(GPT_DOMAIN_PROGRAM, name, resetParams); - } - //----------------------------------------------------------------------- - void Pass::setTessellationDomainProgramParameters(GpuProgramParametersSharedPtr params) - { - setGpuProgramParameters(GPT_DOMAIN_PROGRAM, params); - } - //----------------------------------------------------------------------- - void Pass::setComputeProgram(const String& name, bool resetParams) - { - setGpuProgram(GPT_COMPUTE_PROGRAM, name, resetParams); - } - //----------------------------------------------------------------------- - void Pass::setComputeProgramParameters(GpuProgramParametersSharedPtr params) - { - setGpuProgramParameters(GPT_COMPUTE_PROGRAM, params); - } - //----------------------------------------------------------------------- - const GpuProgramParametersSharedPtr& Pass::getGpuProgramParameters(GpuProgramType type) const - { - OGRE_LOCK_MUTEX(mGpuProgramChangeMutex); - const auto& programUsage = getProgramUsage(type); - if (!programUsage) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "This pass has no " + to_string(type) + " program"); - } - return programUsage->getParameters(); - } - - GpuProgramParametersSharedPtr Pass::getVertexProgramParameters(void) const - { - return getGpuProgramParameters(GPT_VERTEX_PROGRAM); - } - - std::unique_ptr& Pass::getProgramUsage(GpuProgramType programType) { - return mProgramUsage[programType]; - } - - const std::unique_ptr& Pass::getProgramUsage(GpuProgramType programType) const - { - return mProgramUsage[programType]; - } - - bool Pass::hasGpuProgram(GpuProgramType programType) const { - return getProgramUsage(programType) != NULL; - } - const GpuProgramPtr& Pass::getGpuProgram(GpuProgramType programType) const - { - OGRE_LOCK_MUTEX(mGpuProgramChangeMutex); - OgreAssert(mProgramUsage[programType], "check whether program is available using hasGpuProgram()"); - return mProgramUsage[programType]->getProgram(); - } - //----------------------------------------------------------------------- - const String& Pass::getGpuProgramName(GpuProgramType type) const - { - OGRE_LOCK_MUTEX(mGpuProgramChangeMutex); - - const std::unique_ptr& programUsage = getProgramUsage(type); - if (!programUsage) - return BLANKSTRING; - else - return programUsage->getProgramName(); - } - //----------------------------------------------------------------------- - GpuProgramParametersSharedPtr Pass::getFragmentProgramParameters(void) const - { - return getGpuProgramParameters(GPT_FRAGMENT_PROGRAM); - } - //----------------------------------------------------------------------- - GpuProgramParametersSharedPtr Pass::getGeometryProgramParameters(void) const - { - return getGpuProgramParameters(GPT_GEOMETRY_PROGRAM); - } - //----------------------------------------------------------------------- - GpuProgramParametersSharedPtr Pass::getTessellationHullProgramParameters(void) const - { - return getGpuProgramParameters(GPT_HULL_PROGRAM); - } - //----------------------------------------------------------------------- - GpuProgramParametersSharedPtr Pass::getTessellationDomainProgramParameters(void) const - { - return getGpuProgramParameters(GPT_DOMAIN_PROGRAM); - } - //----------------------------------------------------------------------- - GpuProgramParametersSharedPtr Pass::getComputeProgramParameters(void) const - { - return getGpuProgramParameters(GPT_COMPUTE_PROGRAM); - } - //----------------------------------------------------------------------- - bool Pass::isLoaded(void) const - { - return mParent->isLoaded(); - } - //----------------------------------------------------------------------- - void Pass::_recalculateHash(void) - { - /* Hash format is 32-bit, divided as follows (high to low bits) - bits purpose - 4 Pass index (i.e. max 16 passes!) - 28 Pass contents - */ - mHash = (*msHashFunc)(this); - - // overwrite the 4 upper bits with pass index - mHash = (uint32(mIndex) << 28) | (mHash >> 4); - } - //----------------------------------------------------------------------- - void Pass::_dirtyHash(void) - { - if (mQueuedForDeletion) - return; - - Material* mat = mParent->getParent(); - if (mat->isLoading() || mat->isLoaded()) - { - OGRE_LOCK_MUTEX(msDirtyHashListMutex); - // Mark this hash as for follow up - msDirtyHashList.insert(this); - mHashDirtyQueued = false; - } - else - { - mHashDirtyQueued = true; - } - } - //--------------------------------------------------------------------- - void Pass::clearDirtyHashList(void) - { - OGRE_LOCK_MUTEX(msDirtyHashListMutex); - msDirtyHashList.clear(); - } - //----------------------------------------------------------------------- - void Pass::_notifyNeedsRecompile(void) - { - if (!mQueuedForDeletion) - mParent->_notifyNeedsRecompile(); - } - //----------------------------------------------------------------------- - void Pass::setTextureFiltering(TextureFilterOptions filterType) - { - OGRE_LOCK_MUTEX(mTexUnitChangeMutex); - for (auto *t : mTextureUnitStates) - { - t->setTextureFiltering(filterType); - } - } - // -------------------------------------------------------------------- - void Pass::setTextureAnisotropy(unsigned int maxAniso) - { - OGRE_LOCK_MUTEX(mTexUnitChangeMutex); - for (auto *t : mTextureUnitStates) - { - t->setTextureAnisotropy(maxAniso); - } - } - //----------------------------------------------------------------------- - void Pass::_updateAutoParams(const AutoParamDataSource* source, uint16 mask) const - { - for(int i = 0; i < GPT_COUNT; i++) - { - const auto& programUsage = getProgramUsage(GpuProgramType(i)); - if (programUsage) - { - // Update program auto params - programUsage->getParameters()->_updateAutoParams(source, mask); - } - } - } - //----------------------------------------------------------------------- - void Pass::processPendingPassUpdates(void) - { - { - OGRE_LOCK_MUTEX(msPassGraveyardMutex); - // Delete items in the graveyard - for (auto& i : msPassGraveyard) - { - OGRE_DELETE i; - } - msPassGraveyard.clear(); - } - PassSet tempDirtyHashList; - { - OGRE_LOCK_MUTEX(msDirtyHashListMutex); - // The dirty ones will have been removed from the groups above using the old hash now - tempDirtyHashList.swap(msDirtyHashList); - } - for (auto *p : tempDirtyHashList) - { - p->_recalculateHash(); - } - } - //----------------------------------------------------------------------- - void Pass::queueForDeletion(void) - { - mQueuedForDeletion = true; - - removeAllTextureUnitStates(); - for (auto& u : mProgramUsage) - u.reset(); - - // remove from dirty list, if there - { - OGRE_LOCK_MUTEX(msDirtyHashListMutex); - msDirtyHashList.erase(this); - } - { - OGRE_LOCK_MUTEX(msPassGraveyardMutex); - msPassGraveyard.insert(this); - } - } - //----------------------------------------------------------------------- - bool Pass::isAmbientOnly(void) const - { - // treat as ambient if lighting is off, or colour write is off, - // or all non-ambient (& emissive) colours are black - // NB a vertex program could override this, but passes using vertex - // programs are expected to indicate they are ambient only by - // setting the state so it matches one of the conditions above, even - // though this state is not used in rendering. - return (!mLightingEnabled || !getColourWriteEnabled() || - (mDiffuse == ColourValue::Black && - mSpecular == ColourValue::Black)); - } - //----------------------------------------------------------------------- - const String& Pass::getResourceGroup(void) const - { - return mParent->getResourceGroup(); - } - //----------------------------------------------------------------------- - unsigned short Pass::_getTextureUnitWithContentTypeIndex( - TextureUnitState::ContentType contentType, unsigned short index) const - { - if (!mContentTypeLookupBuilt) - { - mShadowContentTypeLookup.clear(); - for (unsigned short i = 0; i < mTextureUnitStates.size(); ++i) - { - if (mTextureUnitStates[i]->getContentType() == TextureUnitState::CONTENT_SHADOW) - { - mShadowContentTypeLookup.push_back(i); - } - } - mContentTypeLookupBuilt = true; - } - - switch(contentType) - { - case TextureUnitState::CONTENT_SHADOW: - if (index < mShadowContentTypeLookup.size()) - { - return mShadowContentTypeLookup[index]; - } - break; - default: - // Simple iteration - for (unsigned short i = 0; i < mTextureUnitStates.size(); ++i) - { - if (mTextureUnitStates[i]->getContentType() == TextureUnitState::CONTENT_SHADOW) - { - if (index == 0) - { - return i; - } - else - { - --index; - } - } - } - break; - } - - // not found - return out of range - return static_cast(mTextureUnitStates.size() + 1); - - } -} diff --git a/OgreMain/src/OgrePatchMesh.cpp b/OgreMain/src/OgrePatchMesh.cpp deleted file mode 100644 index 4764bcc8108..00000000000 --- a/OgreMain/src/OgrePatchMesh.cpp +++ /dev/null @@ -1,119 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgrePatchMesh.h" - -namespace Ogre { - - //----------------------------------------------------------------------- - PatchMesh::PatchMesh(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group) - : Mesh(creator, name, handle, group, false, 0), mDeclaration(0) - { - } - //----------------------------------------------------------------------- - void PatchMesh::define(void* controlPointBuffer, - VertexDeclaration *declaration, size_t width, size_t height, - size_t uMaxSubdivisionLevel, size_t vMaxSubdivisionLevel, - PatchSurface::VisibleSide visibleSide, HardwareBuffer::Usage vbUsage, - HardwareBuffer::Usage ibUsage, - bool vbUseShadow, bool ibUseShadow) - { - setVertexBufferPolicy(vbUsage, vbUseShadow); - setIndexBufferPolicy(ibUsage, ibUseShadow); - - // Init patch builder - // define the surface - // NB clone the declaration to make it independent - mDeclaration = declaration->clone(); - mSurface.defineSurface(controlPointBuffer, mDeclaration, width, height, - PatchSurface::PST_BEZIER, uMaxSubdivisionLevel, vMaxSubdivisionLevel, - visibleSide); - - } - //----------------------------------------------------------------------- - void PatchMesh::update(void* controlPointBuffer, size_t width, size_t height, - size_t uMaxSubdivisionLevel, size_t vMaxSubdivisionLevel, - PatchSurface::VisibleSide visibleSide) - { - mSurface.defineSurface(controlPointBuffer, mDeclaration, width, height, PatchSurface::PST_BEZIER, uMaxSubdivisionLevel, vMaxSubdivisionLevel, visibleSide); - Ogre::SubMesh* sm = this->getSubMesh(0); - Ogre::VertexData* vertex_data = sm->useSharedVertices ? this->sharedVertexData : sm->vertexData; - const Ogre::VertexElement* posElem = vertex_data->vertexDeclaration->findElementBySemantic(Ogre::VES_POSITION); - Ogre::HardwareVertexBufferSharedPtr vbuf = vertex_data->vertexBufferBinding->getBuffer(posElem->getSource()); - - // Build patch with new control points - mSurface.build(vbuf, 0, sm->indexData->indexBuffer, 0); - } - //----------------------------------------------------------------------- - void PatchMesh::setSubdivision(Real factor) - { - mSurface.setSubdivisionFactor(factor); - SubMesh* sm = this->getSubMesh(0); - sm->indexData->indexCount = mSurface.getCurrentIndexCount(); - - } - //----------------------------------------------------------------------- - void PatchMesh::loadImpl(void) - { - SubMesh* sm = this->createSubMesh(); - sm->createVertexData(); - - // Set up vertex buffer - sm->vertexData->vertexStart = 0; - sm->vertexData->vertexCount = mSurface.getRequiredVertexCount(); - sm->vertexData->vertexDeclaration = mDeclaration; - HardwareVertexBufferSharedPtr vbuf = getHardwareBufferManager()-> - createVertexBuffer( - mDeclaration->getVertexSize(0), - sm->vertexData->vertexCount, - getVertexBufferUsage(), - isVertexBufferShadowed()); - sm->vertexData->vertexBufferBinding->setBinding(0, vbuf); - - // Set up index buffer - sm->indexData->indexStart = 0; - sm->indexData->indexCount = mSurface.getRequiredIndexCount(); - sm->indexData->indexBuffer = getHardwareBufferManager()-> - createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, // only 16-bit indexes supported, patches shouldn't be bigger than that - sm->indexData->indexCount, - getIndexBufferUsage(), - isIndexBufferShadowed()); - - // Build patch - mSurface.build(vbuf, 0, sm->indexData->indexBuffer, 0); - - // Set bounds - this->_setBounds(mSurface.getBounds(), true); - this->_setBoundingSphereRadius(mSurface.getBoundingSphereRadius()); - - } - -} - diff --git a/OgreMain/src/OgrePatchSurface.cpp b/OgreMain/src/OgrePatchSurface.cpp deleted file mode 100644 index 283073208fe..00000000000 --- a/OgreMain/src/OgrePatchSurface.cpp +++ /dev/null @@ -1,684 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgrePatchSurface.h" - -#define LEVEL_WIDTH(lvl) ((1 << (lvl+1)) + 1) - -namespace Ogre { - - // TODO: make this deal with specular colours and more than 2 texture coords - - //----------------------------------------------------------------------- - PatchSurface::PatchSurface() - { - mType = PST_BEZIER; - } - //----------------------------------------------------------------------- - PatchSurface::~PatchSurface() - { - } - //----------------------------------------------------------------------- - void PatchSurface::defineSurface(void* controlPointBuffer, - VertexDeclaration *declaration, size_t width, size_t height, - PatchSurfaceType pType, size_t uMaxSubdivisionLevel, - size_t vMaxSubdivisionLevel, VisibleSide visibleSide) - { - if (height == 0 || width == 0) - return; // Do nothing - garbage - - mType = pType; - mCtlWidth = width; - mCtlHeight = height; - mCtlCount = width * height; - mControlPointBuffer = controlPointBuffer; - mDeclaration = declaration; - - // Copy positions into Vector3 vector - mVecCtlPoints.clear(); - const VertexElement* elem = declaration->findElementBySemantic(VES_POSITION); - size_t vertSize = declaration->getVertexSize(0); - uchar *pVert = static_cast(controlPointBuffer); - float* pFloat; - for (size_t i = 0; i < mCtlCount; ++i) - { - elem->baseVertexPointerToElement(pVert, &pFloat); - mVecCtlPoints.push_back(Vector3(pFloat[0], pFloat[1], pFloat[2])); - pVert += vertSize; - } - - mVSide = visibleSide; - - // Determine max level - // Initialise to 100% detail - mSubdivisionFactor = 1.0f; - if (uMaxSubdivisionLevel == (size_t)AUTO_LEVEL) - { - mULevel = mMaxULevel = getAutoULevel(); - } - else - { - mULevel = mMaxULevel = uMaxSubdivisionLevel; - } - - if (vMaxSubdivisionLevel == (size_t)AUTO_LEVEL) - { - mVLevel = mMaxVLevel = getAutoVLevel(); - } - else - { - mVLevel = mMaxVLevel = vMaxSubdivisionLevel; - } - - - - // Derive mesh width / height - mMeshWidth = (LEVEL_WIDTH(mMaxULevel)-1) * ((mCtlWidth-1)/2) + 1; - mMeshHeight = (LEVEL_WIDTH(mMaxVLevel)-1) * ((mCtlHeight-1)/2) + 1; - - - // Calculate number of required vertices / indexes at max resolution - mRequiredVertexCount = mMeshWidth * mMeshHeight; - int iterations = (mVSide == VS_BOTH)? 2 : 1; - mRequiredIndexCount = (mMeshWidth-1) * (mMeshHeight-1) * 2 * iterations * 3; - - // Calculate bounds based on control points - Vector3 min = Vector3::ZERO, max = Vector3::UNIT_SCALE; - Real maxSqRadius = 0; - bool first = true; - for (const auto& ctli : mVecCtlPoints) - { - if (first) - { - min = max = ctli; - maxSqRadius = ctli.squaredLength(); - first = false; - } - else - { - min.makeFloor(ctli); - max.makeCeil(ctli); - maxSqRadius = std::max(ctli.squaredLength(), maxSqRadius); - } - } - mAABB.setExtents(min, max); - mBoundingSphere = Math::Sqrt(maxSqRadius); - - } - //----------------------------------------------------------------------- - const AxisAlignedBox& PatchSurface::getBounds(void) const - { - return mAABB; - } - //----------------------------------------------------------------------- - Real PatchSurface::getBoundingSphereRadius(void) const - { - return mBoundingSphere; - } - //----------------------------------------------------------------------- - size_t PatchSurface::getRequiredVertexCount(void) const - { - return mRequiredVertexCount; - } - //----------------------------------------------------------------------- - size_t PatchSurface::getRequiredIndexCount(void) const - { - return mRequiredIndexCount; - } - //----------------------------------------------------------------------- - void PatchSurface::build(HardwareVertexBufferSharedPtr destVertexBuffer, - size_t vertexStart, HardwareIndexBufferSharedPtr destIndexBuffer, size_t indexStart) - { - - if (mVecCtlPoints.empty()) - return; - - mVertexBuffer = destVertexBuffer; - mVertexOffset = vertexStart; - mIndexBuffer = destIndexBuffer; - mIndexOffset = indexStart; - - // Lock just the region we are interested in - HardwareBufferLockGuard vertexLock(mVertexBuffer, - mVertexOffset * mDeclaration->getVertexSize(0), - mRequiredVertexCount * mDeclaration->getVertexSize(0), - HardwareBuffer::HBL_NO_OVERWRITE); - - distributeControlPoints(vertexLock.pData); - - // Subdivide the curve to the MAX :) - // Do u direction first, so need to step over v levels not done yet - size_t vStep = 1 << mMaxVLevel; - size_t uStep = 1 << mMaxULevel; - - size_t v, u; - for (v = 0; v < mMeshHeight; v += vStep) - { - // subdivide this row in u - subdivideCurve(vertexLock.pData, v*mMeshWidth, uStep, mMeshWidth / uStep, mULevel); - } - - // Now subdivide in v direction, this time all the u direction points are there so no step - for (u = 0; u < mMeshWidth; ++u) - { - subdivideCurve(vertexLock.pData, u, vStep*mMeshWidth, mMeshHeight / vStep, mVLevel); - } - - - vertexLock.unlock(); - - // Make triangles from mesh at this current level of detail - makeTriangles(); - - } - //----------------------------------------------------------------------- - size_t PatchSurface::getAutoULevel(bool forMax) - { - // determine levels - // Derived from work by Bart Sekura in Rogl - Vector3 a,b,c; - size_t u,v; - bool found=false; - // Find u level - for(v = 0; v < mCtlHeight; v++) { - for(u = 0; u < mCtlWidth-1; u += 2) { - a = mVecCtlPoints[v * mCtlWidth + u]; - b = mVecCtlPoints[v * mCtlWidth + u+1]; - c = mVecCtlPoints[v * mCtlWidth + u+2]; - if(a!=c) { - found=true; - break; - } - } - if(found) break; - } - if(!found) { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Can't find suitable control points for determining U subdivision level", - "PatchSurface::getAutoULevel"); - } - - return findLevel(a,b,c); - - } - //----------------------------------------------------------------------- - size_t PatchSurface::getAutoVLevel(bool forMax) - { - Vector3 a,b,c; - size_t u,v; - bool found=false; - for(u = 0; u < mCtlWidth; u++) { - for(v = 0; v < mCtlHeight-1; v += 2) { - a = mVecCtlPoints[v * mCtlWidth + u]; - b = mVecCtlPoints[(v+1) * mCtlWidth + u]; - c = mVecCtlPoints[(v+2) * mCtlWidth + u]; - if(a!=c) { - found=true; - break; - } - } - if(found) break; - } - if(!found) { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Can't find suitable control points for determining V subdivision level", - "PatchSurface::getAutoVLevel"); - } - - return findLevel(a,b,c); - - } - //----------------------------------------------------------------------- - void PatchSurface::setSubdivisionFactor(Real factor) - { - assert(factor >= 0.0f && factor <= 1.0f); - - mSubdivisionFactor = factor; - mULevel = static_cast(factor * mMaxULevel); - mVLevel = static_cast(factor * mMaxVLevel); - - makeTriangles(); - - - } - //----------------------------------------------------------------------- - Real PatchSurface::getSubdivisionFactor(void) const - { - return mSubdivisionFactor; - } - //----------------------------------------------------------------------- - size_t PatchSurface::getCurrentIndexCount(void) const - { - return mCurrIndexCount; - } - //----------------------------------------------------------------------- - size_t PatchSurface::findLevel(Vector3& a, Vector3& b, Vector3& c) - { - // Derived from work by Bart Sekura in rogl - // Apart from I think I fixed a bug - see below - // I also commented the code, the only thing wrong with rogl is almost no comments!! - - const size_t max_levels = 5; - const float subdiv = 10; - size_t level; - - float test=subdiv*subdiv; - Vector3 s,t,d; - for(level=0; levelsharedVertexData = OGRE_NEW VertexData(); - // Copy all vertex parameters - mMesh->sharedVertexData->vertexStart = 0; - // Vertex count will be set on build() because it depends on current level - // NB clone the declaration because Mesh's VertexData will destroy it - mMesh->sharedVertexData->vertexDeclaration = mDeclaration->clone(); - // Create buffer (only a single buffer) - // Allocate enough buffer memory for maximum subdivision, not current subdivision - HardwareVertexBufferSharedPtr vbuf = HardwareBufferManager::getSingleton(). - createVertexBuffer( - mDeclaration->getVertexSize(0), - mMaxMeshHeight * mMaxMeshWidth, // maximum size - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY); // dynamic for changing level - - // Set binding - mMesh->sharedVertexData->vertexBufferBinding->setBinding(0, vbuf); - - SubMesh* sm = mMesh->createSubMesh(); - // Allocate enough index data for max subdivision - sm->indexData->indexStart = 0; - // Index count will be set on build() - unsigned short iterations = (mVSide == VS_BOTH ? 2 : 1); - sm->indexData->indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, - (mMaxMeshWidth-1) * (mMaxMeshHeight-1) * 2 * iterations * 3, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY); - - mMesh->load(); - - // Derive bounds from control points, cannot stray outside that - Vector3 min, max; - Real maxSquaredRadius; - bool first = true; - std::vector::iterator i, iend; - iend = mVecCtlPoints.end(); - for (i = mVecCtlPoints.begin(); i != iend; ++i) - { - if (first) - { - min = max = *i; - maxSquaredRadius = i->squaredLength(); - } - else - { - min.makeFloor(*i); - max.makeCeil(*i); - maxSquaredRadius = std::max(maxSquaredRadius, i->squaredLength()); - } - - } - mMesh->_setBounds(AxisAlignedBox(min, max)); - mMesh->_setBoundingSphereRadius(Math::Sqrt(maxSquaredRadius)); - - - - } - */ - //----------------------------------------------------------------------- - void PatchSurface::distributeControlPoints(void* lockedBuffer) - { - // Insert original control points into expanded mesh - size_t uStep = 1 << mULevel; - size_t vStep = 1 << mVLevel; - - void* pSrc = mControlPointBuffer; - size_t vertexSize = mDeclaration->getVertexSize(0); - float *pSrcReal, *pDestReal; - RGBA *pSrcRGBA, *pDestRGBA; - const VertexElement* elemPos = mDeclaration->findElementBySemantic(VES_POSITION); - const VertexElement* elemNorm = mDeclaration->findElementBySemantic(VES_NORMAL); - const VertexElement* elemTex0 = mDeclaration->findElementBySemantic(VES_TEXTURE_COORDINATES, 0); - const VertexElement* elemTex1 = mDeclaration->findElementBySemantic(VES_TEXTURE_COORDINATES, 1); - const VertexElement* elemDiffuse = mDeclaration->findElementBySemantic(VES_DIFFUSE); - for (size_t v = 0; v < mMeshHeight; v += vStep) - { - // set dest by v from base - void* pDest = static_cast( - static_cast(lockedBuffer) + (vertexSize * mMeshWidth * v)); - for (size_t u = 0; u < mMeshWidth; u += uStep) - { - - // Copy Position - elemPos->baseVertexPointerToElement(pSrc, &pSrcReal); - elemPos->baseVertexPointerToElement(pDest, &pDestReal); - *pDestReal++ = *pSrcReal++; - *pDestReal++ = *pSrcReal++; - *pDestReal++ = *pSrcReal++; - - // Copy Normals - if (elemNorm) - { - elemNorm->baseVertexPointerToElement(pSrc, &pSrcReal); - elemNorm->baseVertexPointerToElement(pDest, &pDestReal); - *pDestReal++ = *pSrcReal++; - *pDestReal++ = *pSrcReal++; - *pDestReal++ = *pSrcReal++; - } - - // Copy Diffuse - if (elemDiffuse) - { - elemDiffuse->baseVertexPointerToElement(pSrc, &pSrcRGBA); - elemDiffuse->baseVertexPointerToElement(pDest, &pDestRGBA); - *pDestRGBA++ = *pSrcRGBA++; - } - - // Copy texture coords - if (elemTex0) - { - elemTex0->baseVertexPointerToElement(pSrc, &pSrcReal); - elemTex0->baseVertexPointerToElement(pDest, &pDestReal); - for (size_t dim = 0; dim < VertexElement::getTypeCount(elemTex0->getType()); ++dim) - *pDestReal++ = *pSrcReal++; - } - if (elemTex1) - { - elemTex1->baseVertexPointerToElement(pSrc, &pSrcReal); - elemTex1->baseVertexPointerToElement(pDest, &pDestReal); - for (size_t dim = 0; dim < VertexElement::getTypeCount(elemTex1->getType()); ++dim) - *pDestReal++ = *pSrcReal++; - } - - // Increment source by one vertex - pSrc = static_cast( - static_cast(pSrc) + vertexSize); - // Increment dest by 1 vertex * uStep - pDest = static_cast( - static_cast(pDest) + (vertexSize * uStep)); - } // u - } // v - - - } - //----------------------------------------------------------------------- - void PatchSurface::subdivideCurve(void* lockedBuffer, size_t startIdx, size_t stepSize, size_t numSteps, size_t iterations) - { - // Subdivides a curve within a sparsely populated buffer (gaps are already there to be interpolated into) - size_t maxIdx; - - maxIdx = startIdx + (numSteps * stepSize); - size_t step = stepSize; - - while(iterations--) - { - size_t leftIdx, rightIdx, destIdx, halfStep; - halfStep = step / 2; - leftIdx = startIdx; - destIdx = leftIdx + halfStep; - rightIdx = leftIdx + step; - bool firstSegment = true; - while (leftIdx < maxIdx) - { - // Interpolate - interpolateVertexData(lockedBuffer, leftIdx, rightIdx, destIdx); - - // If 2nd or more segment, interpolate current left between current and last mid points - if (!firstSegment) - { - interpolateVertexData(lockedBuffer, leftIdx - halfStep, leftIdx + halfStep, leftIdx); - } - // Next segment - leftIdx = rightIdx; - destIdx = leftIdx + halfStep; - rightIdx = leftIdx + step; - firstSegment = false; - } - - step = halfStep; - } - } - //----------------------------------------------------------------------- - void PatchSurface::makeTriangles(void) - { - // Our vertex buffer is subdivided to the highest level, we need to generate tris - // which step over the vertices we don't need for this level of detail. - - // Calculate steps - int vStep = 1 << (mMaxVLevel - mVLevel); - int uStep = 1 << (mMaxULevel - mULevel); - size_t currWidth = (LEVEL_WIDTH(mULevel)-1) * ((mCtlWidth-1)/2) + 1; - size_t currHeight = (LEVEL_WIDTH(mVLevel)-1) * ((mCtlHeight-1)/2) + 1; - - bool use32bitindexes = (mIndexBuffer->getType() == HardwareIndexBuffer::IT_32BIT); - - // The mesh is built, just make a list of indexes to spit out the triangles - int vInc; - - size_t uCount, v, iterations; - - if (mVSide == VS_BOTH) - { - iterations = 2; - vInc = vStep; - v = 0; // Start with front - } - else - { - iterations = 1; - if (mVSide == VS_FRONT) - { - vInc = vStep; - v = 0; - } - else - { - vInc = -vStep; - v = mMeshHeight - 1; - } - } - - // Calc num indexes - mCurrIndexCount = (currWidth - 1) * (currHeight - 1) * 6 * iterations; - - size_t v1, v2, v3; - // Lock just the section of the buffer we need - HardwareBufferLockGuard indexLock(mIndexBuffer, - mIndexOffset * (use32bitindexes ? 4 : 2), - mRequiredIndexCount * (use32bitindexes ? 4 : 2), - HardwareBuffer::HBL_NO_OVERWRITE); - unsigned short* p16 = static_cast(indexLock.pData); - unsigned int* p32 = static_cast(indexLock.pData); - - while (iterations--) - { - // Make tris in a zigzag pattern (compatible with strips) - size_t u = 0; - int uInc = uStep; // Start with moving +u - - size_t vCount = currHeight - 1; - while (vCount--) - { - uCount = currWidth - 1; - while (uCount--) - { - // First Tri in cell - // ----------------- - v1 = ((v + vInc) * mMeshWidth) + u; - v2 = (v * mMeshWidth) + u; - v3 = ((v + vInc) * mMeshWidth) + (u + uInc); - // Output indexes - if (use32bitindexes) - { - *p32++ = static_cast(v1); - *p32++ = static_cast(v2); - *p32++ = static_cast(v3); - } - else - { - *p16++ = static_cast(v1); - *p16++ = static_cast(v2); - *p16++ = static_cast(v3); - } - // Second Tri in cell - // ------------------ - v1 = ((v + vInc) * mMeshWidth) + (u + uInc); - v2 = (v * mMeshWidth) + u; - v3 = (v * mMeshWidth) + (u + uInc); - // Output indexes - if (use32bitindexes) - { - *p32++ = static_cast(v1); - *p32++ = static_cast(v2); - *p32++ = static_cast(v3); - } - else - { - *p16++ = static_cast(v1); - *p16++ = static_cast(v2); - *p16++ = static_cast(v3); - } - - // Next column - u += uInc; - } - // Next row - v += vInc; - u = 0; - - - } - - // Reverse vInc for double sided - v = mMeshHeight - 1; - vInc = -vInc; - - } - } - //----------------------------------------------------------------------- - void PatchSurface::interpolateVertexData(void* lockedBuffer, size_t leftIdx, size_t rightIdx, size_t destIdx) - { - size_t vertexSize = mDeclaration->getVertexSize(0); - const VertexElement* elemPos = mDeclaration->findElementBySemantic(VES_POSITION); - const VertexElement* elemNorm = mDeclaration->findElementBySemantic(VES_NORMAL); - const VertexElement* elemDiffuse = mDeclaration->findElementBySemantic(VES_DIFFUSE); - const VertexElement* elemTex0 = mDeclaration->findElementBySemantic(VES_TEXTURE_COORDINATES, 0); - const VertexElement* elemTex1 = mDeclaration->findElementBySemantic(VES_TEXTURE_COORDINATES, 1); - - float *pDestReal, *pLeftReal, *pRightReal; - unsigned char *pDestChar, *pLeftChar, *pRightChar; - unsigned char *pDest, *pLeft, *pRight; - - // Set up pointers & interpolate - pDest = static_cast(lockedBuffer) + (vertexSize * destIdx); - pLeft = static_cast(lockedBuffer) + (vertexSize * leftIdx); - pRight = static_cast(lockedBuffer) + (vertexSize * rightIdx); - - // Position - elemPos->baseVertexPointerToElement(pDest, &pDestReal); - elemPos->baseVertexPointerToElement(pLeft, &pLeftReal); - elemPos->baseVertexPointerToElement(pRight, &pRightReal); - - *pDestReal++ = (*pLeftReal++ + *pRightReal++) * 0.5f; - *pDestReal++ = (*pLeftReal++ + *pRightReal++) * 0.5f; - *pDestReal++ = (*pLeftReal++ + *pRightReal++) * 0.5f; - - if (elemNorm) - { - elemNorm->baseVertexPointerToElement(pDest, &pDestReal); - elemNorm->baseVertexPointerToElement(pLeft, &pLeftReal); - elemNorm->baseVertexPointerToElement(pRight, &pRightReal); - Vector3 norm; - norm.x = (*pLeftReal++ + *pRightReal++) * 0.5f; - norm.y = (*pLeftReal++ + *pRightReal++) * 0.5f; - norm.z = (*pLeftReal++ + *pRightReal++) * 0.5f; - norm.normalise(); - - *pDestReal++ = norm.x; - *pDestReal++ = norm.y; - *pDestReal++ = norm.z; - } - if (elemDiffuse) - { - // Blend each byte individually - elemDiffuse->baseVertexPointerToElement(pDest, &pDestChar); - elemDiffuse->baseVertexPointerToElement(pLeft, &pLeftChar); - elemDiffuse->baseVertexPointerToElement(pRight, &pRightChar); - // 4 bytes to RGBA - *pDestChar++ = static_cast(((*pLeftChar++) + (*pRightChar++)) * 0.5); - *pDestChar++ = static_cast(((*pLeftChar++) + (*pRightChar++)) * 0.5); - *pDestChar++ = static_cast(((*pLeftChar++) + (*pRightChar++)) * 0.5); - *pDestChar++ = static_cast(((*pLeftChar++) + (*pRightChar++)) * 0.5); - } - if (elemTex0) - { - elemTex0->baseVertexPointerToElement(pDest, &pDestReal); - elemTex0->baseVertexPointerToElement(pLeft, &pLeftReal); - elemTex0->baseVertexPointerToElement(pRight, &pRightReal); - - for (size_t dim = 0; dim < VertexElement::getTypeCount(elemTex0->getType()); ++dim) - *pDestReal++ = ((*pLeftReal++) + (*pRightReal++)) * 0.5f; - } - if (elemTex1) - { - elemTex1->baseVertexPointerToElement(pDest, &pDestReal); - elemTex1->baseVertexPointerToElement(pLeft, &pLeftReal); - elemTex1->baseVertexPointerToElement(pRight, &pRightReal); - - for (size_t dim = 0; dim < VertexElement::getTypeCount(elemTex1->getType()); ++dim) - *pDestReal++ = ((*pLeftReal++) + (*pRightReal++)) * 0.5f; - } - } - -} - diff --git a/OgreMain/src/OgrePixelConversions.h b/OgreMain/src/OgrePixelConversions.h deleted file mode 100644 index f0fa513a2fb..00000000000 --- a/OgreMain/src/OgrePixelConversions.h +++ /dev/null @@ -1,490 +0,0 @@ - /* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -/** Internal include file -- do not use externally */ -//using namespace Ogre; - -// NB VC6 can't handle these templates -#if OGRE_COMPILER != OGRE_COMPILER_MSVC || OGRE_COMP_VER >= 1300 - -#define FMTCONVERTERID(from,to) (((from)<<8)|(to)) -/** \addtogroup Core -* @{ -*/ -/** \addtogroup Image -* @{ -*/ - -/** - * Convert a box of pixel from one type to another. Who needs automatic code - * generation when we have C++ templates and the policy design pattern. - * - * @remarks Policy class to facilitate pixel-to-pixel conversion. This class - * has at least two typedefs: SrcType and DstType. SrcType is the source element type, - * dstType is the destination element type. It also has a static method, pixelConvert, that - * converts a srcType into a dstType. - */ -template struct PixelBoxConverter -{ - static const int ID = U::ID; - static void conversion(const Ogre::PixelBox &src, const Ogre::PixelBox &dst) - { - typename U::SrcType *srcptr = reinterpret_cast(src.data) - + (src.left + src.top * src.rowPitch + src.front * src.slicePitch); - typename U::DstType *dstptr = reinterpret_cast(dst.data) - + (dst.left + dst.top * dst.rowPitch + dst.front * dst.slicePitch); - const size_t srcSliceSkip = src.getSliceSkip(); - const size_t dstSliceSkip = dst.getSliceSkip(); - const size_t k = src.right - src.left; - for(size_t z=src.front; z struct PixelConverter { - static const int ID = id; - typedef T SrcType; - typedef U DstType; - - //inline static DstType pixelConvert(const SrcType &inp); -}; - - -/** Type for PF_R8G8B8/PF_B8G8R8 */ -struct Col3b { - Col3b(unsigned int a, unsigned int b, unsigned int c): - x((Ogre::uint8)a), y((Ogre::uint8)b), z((Ogre::uint8)c) { } - Ogre::uint8 x,y,z; -}; -/** Type for PF_FLOAT32_RGB */ -struct Col3f { - Col3f(float inR, float inG, float inB): - r(inR), g(inG), b(inB) { } - float r,g,b; -}; -/** Type for PF_FLOAT32_RGBA */ -struct Col4f { - Col4f(float inR, float inG, float inB, float inA): - r(inR), g(inG), b(inB), a(inA) { } - float r,g,b,a; -}; - -struct A8R8G8B8toA8B8G8R8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return ((inp&0x000000FF)<<16)|(inp&0xFF00FF00)|((inp&0x00FF0000)>>16); - } -}; - -struct A8R8G8B8toB8G8R8A8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return ((inp&0x000000FF)<<24)|((inp&0x0000FF00)<<8)|((inp&0x00FF0000)>>8)|((inp&0xFF000000)>>24); - } -}; - -struct A8R8G8B8toR8G8B8A8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return ((inp&0x00FFFFFF)<<8)|((inp&0xFF000000)>>24); - } -}; - -struct A8B8G8R8toA8R8G8B8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return ((inp&0x000000FF)<<16)|(inp&0xFF00FF00)|((inp&0x00FF0000)>>16); - } -}; - -struct A8B8G8R8toB8G8R8A8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return ((inp&0x00FFFFFF)<<8)|((inp&0xFF000000)>>24); - } -}; - -struct A8B8G8R8toR8G8B8A8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return ((inp&0x000000FF)<<24)|((inp&0x0000FF00)<<8)|((inp&0x00FF0000)>>8)|((inp&0xFF000000)>>24); - } -}; - -struct B8G8R8A8toA8R8G8B8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return ((inp&0x000000FF)<<24)|((inp&0x0000FF00)<<8)|((inp&0x00FF0000)>>8)|((inp&0xFF000000)>>24); - } -}; - -struct B8G8R8A8toA8B8G8R8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return ((inp&0x000000FF)<<24)|((inp&0xFFFFFF00)>>8); - } -}; - -struct B8G8R8A8toR8G8B8A8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return ((inp&0x0000FF00)<<16)|(inp&0x00FF00FF)|((inp&0xFF000000)>>16); - } -}; - -struct R8G8B8A8toA8R8G8B8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return ((inp&0x000000FF)<<24)|((inp&0xFFFFFF00)>>8); - } -}; - -struct R8G8B8A8toA8B8G8R8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return ((inp&0x000000FF)<<24)|((inp&0x0000FF00)<<8)|((inp&0x00FF0000)>>8)|((inp&0xFF000000)>>24); - } -}; - -struct R8G8B8A8toB8G8R8A8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return ((inp&0x0000FF00)<<16)|(inp&0x00FF00FF)|((inp&0xFF000000)>>16); - } -}; - -struct A8B8G8R8toR8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return (Ogre::uint8)(inp&0x000000FF); - } -}; - -struct R8toA8B8G8R8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return 0xFF000000|((unsigned int)inp); - } -}; - -struct A8R8G8B8toR8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return (Ogre::uint8)((inp&0x00FF0000)>>16); - } -}; - -struct R8toA8R8G8B8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return 0xFF000000|(((unsigned int)inp)<<16); - } -}; - -struct B8G8R8A8toR8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return (Ogre::uint8)((inp&0x0000FF00)>>8); - } -}; - -struct R8toB8G8R8A8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return 0x000000FF|(((unsigned int)inp)<<8); - } -}; - -struct A8B8G8R8toL8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return (Ogre::uint8)(inp&0x000000FF); - } -}; - -struct L8toA8B8G8R8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return 0xFF000000|(((unsigned int)inp)<<0)|(((unsigned int)inp)<<8)|(((unsigned int)inp)<<16); - } -}; - -struct A8R8G8B8toL8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return (Ogre::uint8)((inp&0x00FF0000)>>16); - } -}; - -struct L8toA8R8G8B8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return 0xFF000000|(((unsigned int)inp)<<0)|(((unsigned int)inp)<<8)|(((unsigned int)inp)<<16); - } -}; - -struct B8G8R8A8toL8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return (Ogre::uint8)((inp&0x0000FF00)>>8); - } -}; - -struct L8toB8G8R8A8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return 0x000000FF|(((unsigned int)inp)<<8)|(((unsigned int)inp)<<16)|(((unsigned int)inp)<<24); - } -}; - -struct L8toL16: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return (Ogre::uint16)((((unsigned int)inp)<<8)|(((unsigned int)inp))); - } -}; - -struct L16toL8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return (Ogre::uint8)(inp>>8); - } -}; - -struct R8G8B8toB8G8R8: public PixelConverter -{ - inline static DstType pixelConvert(const SrcType &inp) - { - return Col3b(inp.z, inp.y, inp.x); - } -}; - -struct B8G8R8toR8G8B8: public PixelConverter -{ - inline static DstType pixelConvert(const SrcType &inp) - { - return Col3b(inp.z, inp.y, inp.x); - } -}; - -// X8Y8Z8 -> X8< struct Col3btoUint32swizzler: - public PixelConverter -{ - inline static Ogre::uint32 pixelConvert(const Col3b &inp) - { -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - return (0xFF< { }; -struct B8G8R8toA8R8G8B8: public Col3btoUint32swizzler { }; -struct R8G8B8toA8B8G8R8: public Col3btoUint32swizzler { }; -struct B8G8R8toA8B8G8R8: public Col3btoUint32swizzler { }; -struct R8G8B8toB8G8R8A8: public Col3btoUint32swizzler { }; -struct B8G8R8toB8G8R8A8: public Col3btoUint32swizzler { }; - -struct A8R8G8B8toR8G8B8: public PixelConverter -{ - inline static DstType pixelConvert(Ogre::uint32 inp) - { - return Col3b((Ogre::uint8)((inp>>16)&0xFF), (Ogre::uint8)((inp>>8)&0xFF), (Ogre::uint8)((inp>>0)&0xFF)); - } -}; -struct A8R8G8B8toB8G8R8: public PixelConverter -{ - inline static DstType pixelConvert(Ogre::uint32 inp) - { - return Col3b((Ogre::uint8)((inp>>0)&0xFF), (Ogre::uint8)((inp>>8)&0xFF), (Ogre::uint8)((inp>>16)&0xFF)); - } -}; - -// Only conversions from X8R8G8B8 to formats with alpha need to be defined, the rest is implicitly the same -// as A8R8G8B8 -struct X8R8G8B8toA8R8G8B8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return inp | 0xFF000000; - } -}; -struct X8R8G8B8toA8B8G8R8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return ((inp&0x0000FF)<<16)|((inp&0xFF0000)>>16)|(inp&0x00FF00)|0xFF000000; - } -}; -struct X8R8G8B8toB8G8R8A8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return ((inp&0x0000FF)<<24)|((inp&0xFF0000)>>8)|((inp&0x00FF00)<<8)|0x000000FF; - } -}; -struct X8R8G8B8toR8G8B8A8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return ((inp&0xFFFFFF)<<8)|0x000000FF; - } -}; - -// X8B8G8R8 -struct X8B8G8R8toA8R8G8B8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return ((inp&0x0000FF)<<16)|((inp&0xFF0000)>>16)|(inp&0x00FF00)|0xFF000000; - } -}; -struct X8B8G8R8toA8B8G8R8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return inp | 0xFF000000; - } -}; -struct X8B8G8R8toB8G8R8A8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return ((inp&0xFFFFFF)<<8)|0x000000FF; - } -}; -struct X8B8G8R8toR8G8B8A8: public PixelConverter -{ - inline static DstType pixelConvert(SrcType inp) - { - return ((inp&0x0000FF)<<24)|((inp&0xFF0000)>>8)|((inp&0x00FF00)<<8)|0x000000FF; - } -}; - - -#define CASECONVERTER(type) case type::ID : PixelBoxConverter::conversion(src, dst); return 1; - -inline int doOptimizedConversion(const Ogre::PixelBox &src, const Ogre::PixelBox &dst) -{; - switch(FMTCONVERTERID(src.format, dst.format)) - { - // Register converters here - CASECONVERTER(A8R8G8B8toA8B8G8R8); - CASECONVERTER(A8R8G8B8toB8G8R8A8); - CASECONVERTER(A8R8G8B8toR8G8B8A8); - CASECONVERTER(A8B8G8R8toA8R8G8B8); - CASECONVERTER(A8B8G8R8toB8G8R8A8); - CASECONVERTER(A8B8G8R8toR8G8B8A8); - CASECONVERTER(B8G8R8A8toA8R8G8B8); - CASECONVERTER(B8G8R8A8toA8B8G8R8); - CASECONVERTER(B8G8R8A8toR8G8B8A8); - CASECONVERTER(R8G8B8A8toA8R8G8B8); - CASECONVERTER(R8G8B8A8toA8B8G8R8); - CASECONVERTER(R8G8B8A8toB8G8R8A8); - CASECONVERTER(A8B8G8R8toR8); - CASECONVERTER(R8toA8B8G8R8); - CASECONVERTER(A8R8G8B8toR8); - CASECONVERTER(R8toA8R8G8B8); - CASECONVERTER(B8G8R8A8toR8); - CASECONVERTER(R8toB8G8R8A8); - CASECONVERTER(A8B8G8R8toL8); - CASECONVERTER(L8toA8B8G8R8); - CASECONVERTER(A8R8G8B8toL8); - CASECONVERTER(L8toA8R8G8B8); - CASECONVERTER(B8G8R8A8toL8); - CASECONVERTER(L8toB8G8R8A8); - CASECONVERTER(L8toL16); - CASECONVERTER(L16toL8); - CASECONVERTER(B8G8R8toR8G8B8); - CASECONVERTER(R8G8B8toB8G8R8); - CASECONVERTER(R8G8B8toA8R8G8B8); - CASECONVERTER(B8G8R8toA8R8G8B8); - CASECONVERTER(R8G8B8toA8B8G8R8); - CASECONVERTER(B8G8R8toA8B8G8R8); - CASECONVERTER(R8G8B8toB8G8R8A8); - CASECONVERTER(B8G8R8toB8G8R8A8); - CASECONVERTER(A8R8G8B8toR8G8B8); - CASECONVERTER(A8R8G8B8toB8G8R8); - CASECONVERTER(X8R8G8B8toA8R8G8B8); - CASECONVERTER(X8R8G8B8toA8B8G8R8); - CASECONVERTER(X8R8G8B8toB8G8R8A8); - CASECONVERTER(X8R8G8B8toR8G8B8A8); - CASECONVERTER(X8B8G8R8toA8R8G8B8); - CASECONVERTER(X8B8G8R8toA8B8G8R8); - CASECONVERTER(X8B8G8R8toB8G8R8A8); - CASECONVERTER(X8B8G8R8toR8G8B8A8); - - default: - return 0; - } -} -#undef CASECONVERTER -/** @} */ -/** @} */ - -#endif // VC6 protection diff --git a/OgreMain/src/OgrePixelCountLodStrategy.cpp b/OgreMain/src/OgrePixelCountLodStrategy.cpp deleted file mode 100644 index 2bcd53e1538..00000000000 --- a/OgreMain/src/OgrePixelCountLodStrategy.cpp +++ /dev/null @@ -1,177 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" -#include "OgrePixelCountLodStrategy.h" - -#include "OgreViewport.h" - -namespace Ogre { - //----------------------------------------------------------------------- - PixelCountLodStrategyBase::PixelCountLodStrategyBase(const String& name) - : LodStrategy(name) - { } - //--------------------------------------------------------------------- - Real PixelCountLodStrategyBase::getBaseValue() const - { - // Use the maximum possible value as base - return std::numeric_limits::max(); - } - //--------------------------------------------------------------------- - Real PixelCountLodStrategyBase::transformBias(Real factor) const - { - // No transformation required for pixel count strategy - return factor; - } - //--------------------------------------------------------------------- - ushort PixelCountLodStrategyBase::getIndex(Real value, const Mesh::MeshLodUsageList& meshLodUsageList) const - { - // Values are descending - return getIndexDescending(value, meshLodUsageList); - } - //--------------------------------------------------------------------- - ushort PixelCountLodStrategyBase::getIndex(Real value, const Material::LodValueList& materialLodValueList) const - { - // Values are descending - return getIndexDescending(value, materialLodValueList); - } - //--------------------------------------------------------------------- - void PixelCountLodStrategyBase::sort(Mesh::MeshLodUsageList& meshLodUsageList) const - { - // Sort descending - sortDescending(meshLodUsageList); - } - //--------------------------------------------------------------------- - bool PixelCountLodStrategyBase::isSorted(const Mesh::LodValueList& values) const - { - // Check if values are sorted descending - return isSortedDescending(values); - } - - /************************************************************************/ - /* AbsolutPixelCountLodStrategy */ - /************************************************************************/ - - //----------------------------------------------------------------------- - template<> AbsolutePixelCountLodStrategy* Singleton::msSingleton = 0; - AbsolutePixelCountLodStrategy* AbsolutePixelCountLodStrategy::getSingletonPtr(void) - { - return msSingleton; - } - AbsolutePixelCountLodStrategy& AbsolutePixelCountLodStrategy::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //----------------------------------------------------------------------- - AbsolutePixelCountLodStrategy::AbsolutePixelCountLodStrategy() - : PixelCountLodStrategyBase("pixel_count") - { } - AbsolutePixelCountLodStrategy::~AbsolutePixelCountLodStrategy() {} - //----------------------------------------------------------------------- - Real PixelCountLodStrategyBase::getValueImpl(const MovableObject *movableObject, const Ogre::Camera *camera) const - { - // Get area of unprojected circle with object bounding radius - Real boundingArea = Math::PI * Math::Sqr(movableObject->getBoundingRadiusScaled()); - - // Base computation on projection type - switch (camera->getProjectionType()) - { - case PT_PERSPECTIVE: - { - // Get camera distance - Real distanceSquared = movableObject->getParentNode()->getSquaredViewDepth(camera); - - // Check for 0 distance - if (distanceSquared <= std::numeric_limits::epsilon()) - return getBaseValue(); - - // Get projection matrix (this is done to avoid computation of tan(FOV / 2)) - const Matrix4& projectionMatrix = camera->getProjectionMatrix(); - - // Estimate pixel count - // multiplied out version of $A = pi * r^2$ - // where r is projected using a gluPerspective matrix as $pr = cot(fovy / 2) * r / z$ - // and then converted to pixels as $pr * height / 2$ - return 0.25 * (boundingArea * projectionMatrix[0][0] * projectionMatrix[1][1]) / - distanceSquared; - } - case PT_ORTHOGRAPHIC: - { - // Compute orthographic area - Real orthoArea = camera->getOrthoWindowHeight() * camera->getOrthoWindowWidth(); - - // Check for 0 orthographic area - if (orthoArea <= std::numeric_limits::epsilon()) - return getBaseValue(); - - // Estimate covered area - return boundingArea / orthoArea; - } - default: - { - // This case is not covered for obvious reasons - throw; - } - } - } - //----------------------------------------------------------------------- - Real AbsolutePixelCountLodStrategy::getValueImpl(const MovableObject *movableObject, const Ogre::Camera *camera) const - { - // Get ratio of screen size to absolutely covered pixel count - Real absoluteValue = PixelCountLodStrategyBase::getValueImpl(movableObject, camera); - - // Get viewport area - const Viewport *viewport = camera->getViewport(); - Real viewportArea = static_cast(viewport->getActualWidth() * viewport->getActualHeight()); - - // Return absolute pixel count - return absoluteValue * viewportArea; - } - - /************************************************************************/ - /* ScreenRatioPixelCountLodStrategy */ - /************************************************************************/ - - //----------------------------------------------------------------------- - template<> ScreenRatioPixelCountLodStrategy* Singleton::msSingleton = 0; - ScreenRatioPixelCountLodStrategy* ScreenRatioPixelCountLodStrategy::getSingletonPtr(void) - { - return msSingleton; - } - ScreenRatioPixelCountLodStrategy& ScreenRatioPixelCountLodStrategy::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //----------------------------------------------------------------------- - ScreenRatioPixelCountLodStrategy::ScreenRatioPixelCountLodStrategy() - : PixelCountLodStrategyBase("screen_ratio_pixel_count") - { } - ScreenRatioPixelCountLodStrategy::~ScreenRatioPixelCountLodStrategy() {} - //----------------------------------------------------------------------- - -} // namespace diff --git a/OgreMain/src/OgrePixelFormat.cpp b/OgreMain/src/OgrePixelFormat.cpp deleted file mode 100644 index de414f44ba5..00000000000 --- a/OgreMain/src/OgrePixelFormat.cpp +++ /dev/null @@ -1,838 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgrePixelFormat.h" -#include "OgrePixelFormatDescriptions.h" - -namespace { -#include "OgrePixelConversions.h" -} - -namespace Ogre { - - //----------------------------------------------------------------------- - size_t PixelBox::getConsecutiveSize() const - { - return PixelUtil::getMemorySize(getWidth(), getHeight(), getDepth(), format); - } - PixelBox PixelBox::getSubVolume(const Box &def, bool resetOrigin /* = true */) const - { - OgreAssert(contains(def), ""); - - if(PixelUtil::isCompressed(format) && (def.left != left || def.top != top || def.right != right || def.bottom != bottom)) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot return subvolume of compressed PixelBuffer with less than slice granularity", "PixelBox::getSubVolume"); - - // Calculate new pixelbox and optionally reset origin. - PixelBox rval(def, format, data); - rval.rowPitch = rowPitch; - rval.slicePitch = slicePitch; - - if(resetOrigin) - { - if(PixelUtil::isCompressed(format)) - { - if(rval.front > 0) - { - rval.data = (uint8*)rval.data + rval.front * PixelUtil::getMemorySize(getWidth(), getHeight(), 1, format); - rval.back -= rval.front; - rval.front = 0; - } - } - else - { - rval.data = rval.getTopLeftFrontPixelPtr(); - rval.right -= rval.left; - rval.bottom -= rval.top; - rval.back -= rval.front; - rval.front = rval.top = rval.left = 0; - } - } - - return rval; - } - uchar* PixelBox::getTopLeftFrontPixelPtr() const - { - return data + (left + top * rowPitch + front * slicePitch) * PixelUtil::getNumElemBytes(format); - } - //----------------------------------------------------------------------- - /** - * Directly get the description record for provided pixel format. For debug builds, - * this checks the bounds of fmt with an assertion. - */ - static inline const PixelFormatDescription &getDescriptionFor(const PixelFormat fmt) - { - const int ord = (int)fmt; - assert(ord>=0 && ord 0; - } - //----------------------------------------------------------------------- - bool PixelUtil::isFloatingPoint(PixelFormat format) - { - return (PixelUtil::getFlags(format) & PFF_FLOAT) > 0; - } - //----------------------------------------------------------------------- - bool PixelUtil::isInteger(PixelFormat format) - { - return (PixelUtil::getFlags(format) & PFF_INTEGER) > 0; - } - //----------------------------------------------------------------------- - bool PixelUtil::isCompressed(PixelFormat format) - { - return (PixelUtil::getFlags(format) & PFF_COMPRESSED) > 0; - } - //----------------------------------------------------------------------- - bool PixelUtil::isDepth(PixelFormat format) - { - return (PixelUtil::getFlags(format) & PFF_DEPTH) > 0; - } - //----------------------------------------------------------------------- - bool PixelUtil::isNativeEndian(PixelFormat format) - { - return (PixelUtil::getFlags(format) & PFF_NATIVEENDIAN) > 0; - } - //----------------------------------------------------------------------- - bool PixelUtil::isLuminance(PixelFormat format) - { - return (PixelUtil::getFlags(format) & PFF_LUMINANCE) > 0; - } - //----------------------------------------------------------------------- - void PixelUtil::getBitDepths(PixelFormat format, int rgba[4]) - { - const PixelFormatDescription &des = getDescriptionFor(format); - rgba[0] = des.rbits; - rgba[1] = des.gbits; - rgba[2] = des.bbits; - rgba[3] = des.abits; - } - //----------------------------------------------------------------------- - void PixelUtil::getBitMasks(PixelFormat format, uint64 rgba[4]) - { - const PixelFormatDescription &des = getDescriptionFor(format); - rgba[0] = des.rmask; - rgba[1] = des.gmask; - rgba[2] = des.bmask; - rgba[3] = des.amask; - } - //--------------------------------------------------------------------- - void PixelUtil::getBitShifts(PixelFormat format, unsigned char rgba[4]) - { - const PixelFormatDescription &des = getDescriptionFor(format); - rgba[0] = des.rshift; - rgba[1] = des.gshift; - rgba[2] = des.bshift; - rgba[3] = des.ashift; - } - //----------------------------------------------------------------------- - const String& PixelUtil::getFormatName(PixelFormat srcformat) - { - return getDescriptionFor(srcformat).name; - } - //----------------------------------------------------------------------- - bool PixelUtil::isAccessible(PixelFormat srcformat) - { - return (srcformat != PF_UNKNOWN) && !isCompressed(srcformat); - } - //----------------------------------------------------------------------- - PixelComponentType PixelUtil::getComponentType(PixelFormat fmt) - { - const PixelFormatDescription &des = getDescriptionFor(fmt); - return des.componentType; - } - //----------------------------------------------------------------------- - uint8 PixelUtil::getComponentCount(PixelFormat fmt) - { - const PixelFormatDescription &des = getDescriptionFor(fmt); - return des.componentCount; - } - //----------------------------------------------------------------------- - PixelFormat PixelUtil::getFormatFromName(const String& name, bool accessibleOnly, bool caseSensitive) - { - String tmp = name; - if (!caseSensitive) - { - // We are stored upper-case format names. - StringUtil::toUpperCase(tmp); - } - - for (int i = 0; i < PF_COUNT; ++i) - { - PixelFormat pf = static_cast(i); - if (!accessibleOnly || isAccessible(pf)) - { - if (tmp == getFormatName(pf)) - return pf; - } - } - - // allow look-up by alias name - if(tmp == "PF_BYTE_RGB") - return PF_BYTE_RGB; - if(tmp == "PF_BYTE_RGBA") - return PF_BYTE_RGBA; - if(tmp == "PF_BYTE_BGR") - return PF_BYTE_BGR; - if(tmp == "PF_BYTE_BGRA") - return PF_BYTE_BGRA; - - return PF_UNKNOWN; - } - //----------------------------------------------------------------------- - PixelFormat PixelUtil::getFormatForBitDepths(PixelFormat fmt, ushort integerBits, ushort floatBits) - { - switch (integerBits) - { - case 16: - switch (fmt) - { - case PF_R8G8B8: - case PF_X8R8G8B8: - return PF_R5G6B5; - - case PF_B8G8R8: - case PF_X8B8G8R8: - return PF_B5G6R5; - - case PF_A8R8G8B8: - case PF_R8G8B8A8: - case PF_A8B8G8R8: - case PF_B8G8R8A8: - return PF_A4R4G4B4; - - case PF_A2R10G10B10: - case PF_A2B10G10R10: - return PF_A1R5G5B5; - - default: - // use original image format - break; - } - break; - - case 32: - switch (fmt) - { - case PF_R5G6B5: - return PF_X8R8G8B8; - - case PF_B5G6R5: - return PF_X8B8G8R8; - - case PF_A4R4G4B4: - return PF_A8R8G8B8; - - case PF_A1R5G5B5: - return PF_A2R10G10B10; - - default: - // use original image format - break; - } - break; - - default: - // use original image format - break; - } - - switch (floatBits) - { - case 16: - switch (fmt) - { - case PF_FLOAT32_R: - return PF_FLOAT16_R; - - case PF_FLOAT32_RGB: - return PF_FLOAT16_RGB; - - case PF_FLOAT32_RGBA: - return PF_FLOAT16_RGBA; - - default: - // use original image format - break; - } - break; - - case 32: - switch (fmt) - { - case PF_FLOAT16_R: - return PF_FLOAT32_R; - - case PF_FLOAT16_RGB: - return PF_FLOAT32_RGB; - - case PF_FLOAT16_RGBA: - return PF_FLOAT32_RGBA; - - default: - // use original image format - break; - } - break; - - default: - // use original image format - break; - } - - return fmt; - } - //----------------------------------------------------------------------- - /************************************************************************* - * Pixel packing/unpacking utilities - */ - void PixelUtil::packColour(const uint8 r, const uint8 g, const uint8 b, const uint8 a, const PixelFormat pf, void* dest) - { - const PixelFormatDescription &des = getDescriptionFor(pf); - if(des.flags & PFF_NATIVEENDIAN) { - // Shortcut for integer formats packing - unsigned int value = ((Bitwise::fixedToFixed(r, 8, des.rbits)<>des.rshift, des.rbits, 8); - } - else - { - *r = (uint8)Bitwise::fixedToFixed((value & des.rmask)>>des.rshift, des.rbits, 8); - *g = (uint8)Bitwise::fixedToFixed((value & des.gmask)>>des.gshift, des.gbits, 8); - *b = (uint8)Bitwise::fixedToFixed((value & des.bmask)>>des.bshift, des.bbits, 8); - } - if(des.flags & PFF_HASALPHA) - { - *a = (uint8)Bitwise::fixedToFixed((value & des.amask)>>des.ashift, des.abits, 8); - } - else - { - *a = 255; // No alpha, default a component to full - } - } else { - // Do the operation with the more generic floating point - float rr = 0, gg = 0, bb = 0, aa = 0; - unpackColour(&rr,&gg,&bb,&aa, pf, src); - *r = (uint8)Bitwise::floatToFixed(rr, 8); - *g = (uint8)Bitwise::floatToFixed(gg, 8); - *b = (uint8)Bitwise::floatToFixed(bb, 8); - *a = (uint8)Bitwise::floatToFixed(aa, 8); - } - } - //----------------------------------------------------------------------- - void PixelUtil::unpackColour(float *r, float *g, float *b, float *a, - PixelFormat pf, const void* src) - { - const PixelFormatDescription &des = getDescriptionFor(pf); - if(des.flags & PFF_NATIVEENDIAN) { - // Shortcut for integer formats unpacking - const unsigned int value = Bitwise::intRead(src, des.elemBytes); - if(des.flags & PFF_LUMINANCE) - { - // Luminance format -- only rbits used - *r = *g = *b = Bitwise::fixedToFloat( - (value & des.rmask)>>des.rshift, des.rbits); - } - else - { - *r = Bitwise::fixedToFloat((value & des.rmask)>>des.rshift, des.rbits); - *g = Bitwise::fixedToFloat((value & des.gmask)>>des.gshift, des.gbits); - *b = Bitwise::fixedToFloat((value & des.bmask)>>des.bshift, des.bbits); - } - if(des.flags & PFF_HASALPHA) - { - *a = Bitwise::fixedToFloat((value & des.amask)>>des.ashift, des.abits); - } - else - { - *a = 1.0f; // No alpha, default a component to full - } - } else { - switch(pf) - { - case PF_FLOAT32_R: - *r = *g = *b = ((const float*)src)[0]; - *a = 1.0f; - break; - case PF_FLOAT32_GR: - *g = ((const float*)src)[0]; - *r = *b = ((const float*)src)[1]; - *a = 1.0f; - break; - case PF_FLOAT32_RGB: - *r = ((const float*)src)[0]; - *g = ((const float*)src)[1]; - *b = ((const float*)src)[2]; - *a = 1.0f; - break; - case PF_FLOAT32_RGBA: - *r = ((const float*)src)[0]; - *g = ((const float*)src)[1]; - *b = ((const float*)src)[2]; - *a = ((const float*)src)[3]; - break; - case PF_FLOAT16_R: - *r = *g = *b = Bitwise::halfToFloat(((const uint16*)src)[0]); - *a = 1.0f; - break; - case PF_FLOAT16_GR: - *g = Bitwise::halfToFloat(((const uint16*)src)[0]); - *r = *b = Bitwise::halfToFloat(((const uint16*)src)[1]); - *a = 1.0f; - break; - case PF_FLOAT16_RGB: - *r = Bitwise::halfToFloat(((const uint16*)src)[0]); - *g = Bitwise::halfToFloat(((const uint16*)src)[1]); - *b = Bitwise::halfToFloat(((const uint16*)src)[2]); - *a = 1.0f; - break; - case PF_FLOAT16_RGBA: - *r = Bitwise::halfToFloat(((const uint16*)src)[0]); - *g = Bitwise::halfToFloat(((const uint16*)src)[1]); - *b = Bitwise::halfToFloat(((const uint16*)src)[2]); - *a = Bitwise::halfToFloat(((const uint16*)src)[3]); - break; - case PF_SHORT_RGB: - *r = Bitwise::fixedToFloat(((const uint16*)src)[0], 16); - *g = Bitwise::fixedToFloat(((const uint16*)src)[1], 16); - *b = Bitwise::fixedToFloat(((const uint16*)src)[2], 16); - *a = 1.0f; - break; - case PF_SHORT_RGBA: - *r = Bitwise::fixedToFloat(((const uint16*)src)[0], 16); - *g = Bitwise::fixedToFloat(((const uint16*)src)[1], 16); - *b = Bitwise::fixedToFloat(((const uint16*)src)[2], 16); - *a = Bitwise::fixedToFloat(((const uint16*)src)[3], 16); - break; - case PF_BYTE_LA: - *r = *g = *b = Bitwise::fixedToFloat(((const uint8*)src)[0], 8); - *a = Bitwise::fixedToFloat(((const uint8*)src)[1], 8); - break; - default: - // Not yet supported - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, - "unpack from "+getFormatName(pf)+" not implemented", - "PixelUtil::unpackColour"); - break; - } - } - } - //----------------------------------------------------------------------- - /* Convert pixels from one format to another */ - void PixelUtil::bulkPixelConversion(const PixelBox &src, const PixelBox &dst) - { - OgreAssert(src.getSize() == dst.getSize(), ""); - - // Check for compressed formats, we don't support decompression, compression or recoding - if(PixelUtil::isCompressed(src.format) || PixelUtil::isCompressed(dst.format)) - { - OgreAssert(src.format == dst.format && src.isConsecutive() && dst.isConsecutive(), - "This method can not be used to compress or decompress images"); - // we can copy with slice granularity, useful for Tex2DArray handling - size_t bytesPerSlice = getMemorySize(src.getWidth(), src.getHeight(), 1, src.format); - memcpy(dst.data + bytesPerSlice * dst.front, src.data + bytesPerSlice * src.front, - bytesPerSlice * src.getDepth()); - return; - } - - // The easy case - if(src.format == dst.format) { - uint8 *srcptr = src.getTopLeftFrontPixelPtr(); - uint8 *dstptr = dst.getTopLeftFrontPixelPtr(); - - // Everything consecutive? - if(src.isConsecutive() && dst.isConsecutive()) - { - memcpy(dstptr, srcptr, src.getConsecutiveSize()); - return; - } - - const size_t srcPixelSize = PixelUtil::getNumElemBytes(src.format); - const size_t dstPixelSize = PixelUtil::getNumElemBytes(dst.format); - - // Calculate pitches+skips in bytes - const size_t srcRowPitchBytes = src.rowPitch*srcPixelSize; - //const size_t srcRowSkipBytes = src.getRowSkip()*srcPixelSize; - const size_t srcSliceSkipBytes = src.getSliceSkip()*srcPixelSize; - - const size_t dstRowPitchBytes = dst.rowPitch*dstPixelSize; - //const size_t dstRowSkipBytes = dst.getRowSkip()*dstPixelSize; - const size_t dstSliceSkipBytes = dst.getSliceSkip()*dstPixelSize; - - // Otherwise, copy per row - const size_t rowSize = src.getWidth()*srcPixelSize; - for(size_t z=src.front; z= 1300 - // Is there a specialized, inlined, conversion? - if(doOptimizedConversion(src, dst)) - { - // If so, good - return; - } -#endif - - const size_t srcPixelSize = PixelUtil::getNumElemBytes(src.format); - const size_t dstPixelSize = PixelUtil::getNumElemBytes(dst.format); - uint8* srcptr = src.getTopLeftFrontPixelPtr(); - uint8* dstptr = dst.getTopLeftFrontPixelPtr(); - - // Old way, not taking into account box dimensions - //uint8 *srcptr = static_cast(src.data), *dstptr = static_cast(dst.data); - - // Calculate pitches+skips in bytes - const size_t srcRowSkipBytes = src.getRowSkip()*srcPixelSize; - const size_t srcSliceSkipBytes = src.getSliceSkip()*srcPixelSize; - const size_t dstRowSkipBytes = dst.getRowSkip()*dstPixelSize; - const size_t dstSliceSkipBytes = dst.getSliceSkip()*dstPixelSize; - - // The brute force fallback - float r = 0, g = 0, b = 0, a = 1; - for(size_t z=src.front; z> 1; - for(size_t z = box.front; z < box.back; z++) - { - uint8* srcptr = basesrcptr; - uint8* dstptr = basedstptr; - for(size_t y = 0; y < halfRowCount; y++) - { - // swap rows - memcpy(tmpptr, dstptr, copySize); - memcpy(dstptr, srcptr, copySize); - memcpy(srcptr, tmpptr, copySize); - srcptr += rowPitchBytes; - dstptr -= rowPitchBytes; - } - basesrcptr += slicePitchBytes; - basedstptr += slicePitchBytes; - } - - OGRE_FREE_SIMD(tmpptr, MEMCATEGORY_GENERAL); - } - - ColourValue PixelBox::getColourAt(size_t x, size_t y, size_t z) const - { - ColourValue cv; - - size_t pixelSize = PixelUtil::getNumElemBytes(format); - size_t pixelOffset = pixelSize * (z * slicePitch + y * rowPitch + x); - PixelUtil::unpackColour(&cv, format, (unsigned char *)data + pixelOffset); - - return cv; - } - - void PixelBox::setColourAt(ColourValue const &cv, size_t x, size_t y, size_t z) - { - size_t pixelSize = PixelUtil::getNumElemBytes(format); - size_t pixelOffset = pixelSize * (z * slicePitch + y * rowPitch + x); - PixelUtil::packColour(cv, format, (unsigned char *)data + pixelOffset); - } - -} diff --git a/OgreMain/src/OgrePixelFormatDescriptions.h b/OgreMain/src/OgrePixelFormatDescriptions.h deleted file mode 100644 index 5cdf5d3896b..00000000000 --- a/OgreMain/src/OgrePixelFormatDescriptions.h +++ /dev/null @@ -1,1549 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __PixelFormatDescriptions_H__ -#define __PixelFormatDescriptions_H__ - -namespace Ogre { - //----------------------------------------------------------------------- - /** - * A record that describes a pixel format in detail. - */ - struct PixelFormatDescription { - /* Name of the format, as in the enum */ - const String name; - /* Number of bytes one element (colour value) takes. */ - unsigned char elemBytes; - /* Pixel format flags, see enum PixelFormatFlags for the bit field - * definitions - */ - uint32 flags; - /** Component type - */ - PixelComponentType componentType; - /** Component count - */ - unsigned char componentCount; - /* Number of bits for red(or luminance), green, blue, alpha - */ - unsigned char rbits, gbits, bbits, abits; /*, ibits, dbits, ... */ - - /* Masks and shifts as used by packers/unpackers */ - uint64 rmask, gmask, bmask, amask; - unsigned char rshift, gshift, bshift, ashift; - }; - //----------------------------------------------------------------------- - /** Pixel format database */ - PixelFormatDescription _pixelFormats[PF_COUNT] = { - //----------------------------------------------------------------------- - {"PF_UNKNOWN", - /* Bytes per element */ - 0, - /* Flags */ - 0, - /* Component type and count */ - PCT_BYTE, 0, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_L8", - /* Bytes per element */ - 1, - /* Flags */ - PFF_LUMINANCE | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 1, - /* rbits, gbits, bbits, abits */ - 8, 0, 0, 0, - /* Masks and shifts */ - 0xFF, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_L16", - /* Bytes per element */ - 2, - /* Flags */ - PFF_LUMINANCE | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_SHORT, 1, - /* rbits, gbits, bbits, abits */ - 16, 0, 0, 0, - /* Masks and shifts */ - 0xFFFF, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_A8", - /* Bytes per element */ - 1, - /* Flags */ - PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 1, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 8, - /* Masks and shifts */ - 0, 0, 0, 0xFF, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_BYTE_LA", - /* Bytes per element */ - 2, - /* Flags */ - PFF_HASALPHA | PFF_LUMINANCE, - /* Component type and count */ - PCT_BYTE, 2, - /* rbits, gbits, bbits, abits */ - 8, 0, 0, 8, - /* Masks and shifts */ - 0xFF,0,0,0xFF00,0,0,0,8 - }, - //----------------------------------------------------------------------- - {"PF_R5G6B5", - /* Bytes per element */ - 2, - /* Flags */ - PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 3, - /* rbits, gbits, bbits, abits */ - 5, 6, 5, 0, - /* Masks and shifts */ - 0xF800, 0x07E0, 0x001F, 0, - 11, 5, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_B5G6R5", - /* Bytes per element */ - 2, - /* Flags */ - PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 3, - /* rbits, gbits, bbits, abits */ - 5, 6, 5, 0, - /* Masks and shifts */ - 0x001F, 0x07E0, 0xF800, 0, - 0, 5, 11, 0 - }, - //----------------------------------------------------------------------- - {"PF_A4R4G4B4", - /* Bytes per element */ - 2, - /* Flags */ - PFF_HASALPHA | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 4, 4, 4, 4, - /* Masks and shifts */ - 0x0F00, 0x00F0, 0x000F, 0xF000, - 8, 4, 0, 12 - }, - //----------------------------------------------------------------------- - {"PF_A1R5G5B5", - /* Bytes per element */ - 2, - /* Flags */ - PFF_HASALPHA | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 5, 5, 5, 1, - /* Masks and shifts */ - 0x7C00, 0x03E0, 0x001F, 0x8000, - 10, 5, 0, 15, - }, - //----------------------------------------------------------------------- - {"PF_R8G8B8", - /* Bytes per element */ - 3, // 24 bit integer -- special - /* Flags */ - PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 3, - /* rbits, gbits, bbits, abits */ - 8, 8, 8, 0, - /* Masks and shifts */ - 0xFF0000, 0x00FF00, 0x0000FF, 0, - 16, 8, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_B8G8R8", - /* Bytes per element */ - 3, // 24 bit integer -- special - /* Flags */ - PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 3, - /* rbits, gbits, bbits, abits */ - 8, 8, 8, 0, - /* Masks and shifts */ - 0x0000FF, 0x00FF00, 0xFF0000, 0, - 0, 8, 16, 0 - }, - //----------------------------------------------------------------------- - {"PF_A8R8G8B8", - /* Bytes per element */ - 4, - /* Flags */ - PFF_HASALPHA | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 8, 8, 8, 8, - /* Masks and shifts */ - 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000, - 16, 8, 0, 24 - }, - //----------------------------------------------------------------------- - {"PF_A8B8G8R8", - /* Bytes per element */ - 4, - /* Flags */ - PFF_HASALPHA | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 8, 8, 8, 8, - /* Masks and shifts */ - 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000, - 0, 8, 16, 24, - }, - //----------------------------------------------------------------------- - {"PF_B8G8R8A8", - /* Bytes per element */ - 4, - /* Flags */ - PFF_HASALPHA | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 8, 8, 8, 8, - /* Masks and shifts */ - 0x0000FF00, 0x00FF0000, 0xFF000000, 0x000000FF, - 8, 16, 24, 0 - }, - //----------------------------------------------------------------------- - {"PF_A2R10G10B10", - /* Bytes per element */ - 4, - /* Flags */ - PFF_HASALPHA | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 10, 10, 10, 2, - /* Masks and shifts */ - 0x3FF00000, 0x000FFC00, 0x000003FF, 0xC0000000, - 20, 10, 0, 30 - }, - //----------------------------------------------------------------------- - {"PF_A2B10G10R10", - /* Bytes per element */ - 4, - /* Flags */ - PFF_HASALPHA | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 10, 10, 10, 2, - /* Masks and shifts */ - 0x000003FF, 0x000FFC00, 0x3FF00000, 0xC0000000, - 0, 10, 20, 30 - }, - //----------------------------------------------------------------------- - {"PF_DXT1", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED, - /* Component type and count */ - PCT_BYTE, 3, // No alpha - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_DXT2", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_DXT3", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_DXT4", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_DXT5", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_FLOAT16_RGB", - /* Bytes per element */ - 6, - /* Flags */ - PFF_FLOAT, - /* Component type and count */ - PCT_FLOAT16, 3, - /* rbits, gbits, bbits, abits */ - 16, 16, 16, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_FLOAT16_RGBA", - /* Bytes per element */ - 8, - /* Flags */ - PFF_FLOAT | PFF_HASALPHA, - /* Component type and count */ - PCT_FLOAT16, 4, - /* rbits, gbits, bbits, abits */ - 16, 16, 16, 16, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_FLOAT32_RGB", - /* Bytes per element */ - 12, - /* Flags */ - PFF_FLOAT, - /* Component type and count */ - PCT_FLOAT32, 3, - /* rbits, gbits, bbits, abits */ - 32, 32, 32, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_FLOAT32_RGBA", - /* Bytes per element */ - 16, - /* Flags */ - PFF_FLOAT | PFF_HASALPHA, - /* Component type and count */ - PCT_FLOAT32, 4, - /* rbits, gbits, bbits, abits */ - 32, 32, 32, 32, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_X8R8G8B8", - /* Bytes per element */ - 4, - /* Flags */ - PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 3, - /* rbits, gbits, bbits, abits */ - 8, 8, 8, 0, - /* Masks and shifts */ - 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000, - 16, 8, 0, 24 - }, - //----------------------------------------------------------------------- - {"PF_X8B8G8R8", - /* Bytes per element */ - 4, - /* Flags */ - PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 3, - /* rbits, gbits, bbits, abits */ - 8, 8, 8, 0, - /* Masks and shifts */ - 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000, - 0, 8, 16, 24 - }, - //----------------------------------------------------------------------- - {"PF_R8G8B8A8", - /* Bytes per element */ - 4, - /* Flags */ - PFF_HASALPHA | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 8, 8, 8, 8, - /* Masks and shifts */ - 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF, - 24, 16, 8, 0 - }, - //----------------------------------------------------------------------- - {"PF_DEPTH16", - /* Bytes per element */ - 2, - /* Flags */ - PFF_LUMINANCE | PFF_DEPTH | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_SHORT, 1, - /* rbits, gbits, bbits, abits */ - 16, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_SHORT_RGBA", - /* Bytes per element */ - 8, - /* Flags */ - PFF_HASALPHA, - /* Component type and count */ - PCT_SHORT, 4, - /* rbits, gbits, bbits, abits */ - 16, 16, 16, 16, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R3G3B2", - /* Bytes per element */ - 1, - /* Flags */ - PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 3, - /* rbits, gbits, bbits, abits */ - 3, 3, 2, 0, - /* Masks and shifts */ - 0xE0, 0x1C, 0x03, 0, - 5, 2, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_FLOAT16_R", - /* Bytes per element */ - 2, - /* Flags */ - PFF_FLOAT, - /* Component type and count */ - PCT_FLOAT16, 1, - /* rbits, gbits, bbits, abits */ - 16, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_FLOAT32_R", - /* Bytes per element */ - 4, - /* Flags */ - PFF_FLOAT, - /* Component type and count */ - PCT_FLOAT32, 1, - /* rbits, gbits, bbits, abits */ - 32, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_SHORT_GR", - /* Bytes per element */ - 4, - /* Flags */ - PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_SHORT, 2, - /* rbits, gbits, bbits, abits */ - 16, 16, 0, 0, - /* Masks and shifts */ - 0x0000FFFF, 0xFFFF0000, 0, 0, - 0, 16, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_FLOAT16_GR", - /* Bytes per element */ - 4, - /* Flags */ - PFF_FLOAT, - /* Component type and count */ - PCT_FLOAT16, 2, - /* rbits, gbits, bbits, abits */ - 16, 16, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_FLOAT32_GR", - /* Bytes per element */ - 8, - /* Flags */ - PFF_FLOAT, - /* Component type and count */ - PCT_FLOAT32, 2, - /* rbits, gbits, bbits, abits */ - 32, 32, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_SHORT_RGB", - /* Bytes per element */ - 6, - /* Flags */ - 0, - /* Component type and count */ - PCT_SHORT, 3, - /* rbits, gbits, bbits, abits */ - 16, 16, 16, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_PVRTC_RGB2", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED, - /* Component type and count */ - PCT_BYTE, 3, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_PVRTC_RGBA2", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_PVRTC_RGB4", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED, - /* Component type and count */ - PCT_BYTE, 3, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_PVRTC_RGBA4", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_PVRTC2_2BPP", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_PVRTC2_4BPP", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R11G11B10_FLOAT", - /* Bytes per element */ - 4, - /* Flags */ - PFF_FLOAT, - /* Component type and count */ - PCT_FLOAT32, 1, - /* rbits, gbits, bbits, abits */ - 11, 11, 10, 0, - /* Masks and shifts */ - 0xFFC00000, 0x03FF800, 0x000007FF, 0, - 24, 16, 8, 0 - }, - //----------------------------------------------------------------------- - {"PF_R8_UINT", - /* Bytes per element */ - 1, - /* Flags */ - PFF_INTEGER | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_UINT, 1, - /* rbits, gbits, bbits, abits */ - 8, 0, 0, 0, - /* Masks and shifts */ - 0xFF, 0, 0, 0, - 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R8G8_UINT", - /* Bytes per element */ - 2, - /* Flags */ - PFF_INTEGER | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_UINT, 2, - /* rbits, gbits, bbits, abits */ - 8, 8, 0, 0, - /* Masks and shifts */ - 0xFF00, 0x00FF, 0, 0, - 8, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R8G8B8_UINT", - /* Bytes per element */ - 3, - /* Flags */ - PFF_INTEGER | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_UINT, 3, - /* rbits, gbits, bbits, abits */ - 8, 8, 8, 0, - /* Masks and shifts */ - 0xFF0000, 0x00FF00, 0x0000FF, 0, - 16, 8, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R8G8B8A8_UINT", - /* Bytes per element */ - 4, - /* Flags */ - PFF_INTEGER | PFF_HASALPHA | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_UINT, 4, - /* rbits, gbits, bbits, abits */ - 8, 8, 8, 8, - /* Masks and shifts */ - 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF, - 24, 16, 8, 0 - }, - //----------------------------------------------------------------------- - {"PF_R16_UINT", - /* Bytes per element */ - 2, - /* Flags */ - PFF_INTEGER | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_UINT, 1, - /* rbits, gbits, bbits, abits */ - 16, 0, 0, 0, - /* Masks and shifts */ - 0xFFFF, 0, 0, 0, - 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R16G16_UINT", - /* Bytes per element */ - 4, - /* Flags */ - PFF_INTEGER | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_UINT, 2, - /* rbits, gbits, bbits, abits */ - 16, 16, 0, 0, - /* Masks and shifts */ - 0xFFFF0000, 0x0000FFFF, 0, 0, - 16, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R16G16B16_UINT", - /* Bytes per element */ - 6, - /* Flags */ - PFF_INTEGER | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_UINT, 3, - /* rbits, gbits, bbits, abits */ - 16, 16, 16, 0, - /* Masks and shifts */ - 0xFFFF00000000ULL, 0x0000FFFF0000ULL, 0x00000000FFFFULL, 0, - 32, 16, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R16G16B16A16_UINT", - /* Bytes per element */ - 8, - /* Flags */ - PFF_INTEGER | PFF_HASALPHA | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_UINT, 4, - /* rbits, gbits, bbits, abits */ - 16, 16, 16, 16, - /* Masks and shifts */ - 0xFFFF000000000000ULL, 0x0000FFFF00000000ULL, 0x00000000FFFF0000ULL, 0x000000000000FFFFULL, - 48, 32, 16, 0 - }, - //----------------------------------------------------------------------- - {"PF_R32_UINT", - /* Bytes per element */ - 4, - /* Flags */ - PFF_INTEGER | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_UINT, 1, - /* rbits, gbits, bbits, abits */ - 32, 0, 0, 0, - /* Masks and shifts */ - 0xFFFFFFFF, 0, 0, 0, - 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R32G32_UINT", - /* Bytes per element */ - 8, - /* Flags */ - PFF_INTEGER | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_UINT, 2, - /* rbits, gbits, bbits, abits */ - 32, 32, 0, 0, - /* Masks and shifts */ - 0xFFFFFFFF00000000ULL, 0xFFFFFFFFULL, 0, 0, - 32, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R32G32B32_UINT", - /* Bytes per element */ - 12, - /* Flags */ - PFF_INTEGER | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_UINT, 3, - /* rbits, gbits, bbits, abits */ - 32, 32, 32, 0, - /* Masks and shifts */ - 0, 0, 0, 0, - 64, 32, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R32G32B32A32_UINT", - /* Bytes per element */ - 16, - /* Flags */ - PFF_INTEGER | PFF_HASALPHA | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_UINT, 4, - /* rbits, gbits, bbits, abits */ - 32, 32, 32, 32, - /* Masks and shifts */ - 0, 0, 0, 0, - 96, 64, 32, 0 - }, - //----------------------------------------------------------------------- - {"PF_R8_SINT", - /* Bytes per element */ - 1, - /* Flags */ - PFF_INTEGER | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_SINT, 1, - /* rbits, gbits, bbits, abits */ - 8, 0, 0, 0, - /* Masks and shifts */ - 0xFF, 0, 0, 0, - 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R8G8_SINT", - /* Bytes per element */ - 2, - /* Flags */ - PFF_INTEGER | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_SINT, 2, - /* rbits, gbits, bbits, abits */ - 8, 8, 0, 0, - /* Masks and shifts */ - 0xFF00, 0x00FF, 0, 0, - 8, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R8G8B8_SINT", - /* Bytes per element */ - 3, - /* Flags */ - PFF_INTEGER | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_SINT, 3, - /* rbits, gbits, bbits, abits */ - 8, 8, 8, 0, - /* Masks and shifts */ - 0xFF0000, 0x00FF00, 0x0000FF, 0, - 16, 8, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R8G8B8A8_SINT", - /* Bytes per element */ - 4, - /* Flags */ - PFF_INTEGER | PFF_HASALPHA | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_SINT, 4, - /* rbits, gbits, bbits, abits */ - 8, 8, 8, 8, - /* Masks and shifts */ - 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF, - 24, 16, 8, 0 - }, - //----------------------------------------------------------------------- - {"PF_R16_SINT", - /* Bytes per element */ - 2, - /* Flags */ - PFF_INTEGER | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_SINT, 1, - /* rbits, gbits, bbits, abits */ - 16, 0, 0, 0, - /* Masks and shifts */ - 0xFFFF, 0, 0, 0, - 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R16G16_SINT", - /* Bytes per element */ - 4, - /* Flags */ - PFF_INTEGER | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_SINT, 2, - /* rbits, gbits, bbits, abits */ - 16, 16, 0, 0, - /* Masks and shifts */ - 0xFFFF0000, 0x0000FFFF, 0, 0, - 16, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R16G16B16_SINT", - /* Bytes per element */ - 6, - /* Flags */ - PFF_INTEGER | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_SINT, 3, - /* rbits, gbits, bbits, abits */ - 16, 16, 16, 0, - /* Masks and shifts */ - 0xFFFF00000000ULL, 0x0000FFFF0000ULL, 0x00000000FFFFULL, 0, - 32, 16, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R16G16B16A16_SINT", - /* Bytes per element */ - 8, - /* Flags */ - PFF_INTEGER | PFF_HASALPHA | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_SINT, 4, - /* rbits, gbits, bbits, abits */ - 16, 16, 16, 16, - /* Masks and shifts */ - 0xFFFF000000000000ULL, 0x0000FFFF00000000ULL, 0x00000000FFFF0000ULL, 0x000000000000FFFFULL, - 48, 32, 16, 0 - }, - //----------------------------------------------------------------------- - {"PF_R32_SINT", - /* Bytes per element */ - 4, - /* Flags */ - PFF_INTEGER | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_SINT, 1, - /* rbits, gbits, bbits, abits */ - 32, 0, 0, 0, - /* Masks and shifts */ - 0xFFFFFFFF, 0, 0, 0, - 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R32G32_SINT", - /* Bytes per element */ - 8, - /* Flags */ - PFF_INTEGER | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_SINT, 2, - /* rbits, gbits, bbits, abits */ - 32, 32, 0, 0, - /* Masks and shifts */ - 0xFFFFFFFF00000000ULL, 0xFFFFFFFFULL, 0, 0, - 32, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R32G32B32_SINT", - /* Bytes per element */ - 12, - /* Flags */ - PFF_INTEGER | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_SINT, 3, - /* rbits, gbits, bbits, abits */ - 32, 32, 32, 0, - /* Masks and shifts */ - 0, 0, 0, 0, - 64, 32, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R32G32B32A32_SINT", - /* Bytes per element */ - 16, - /* Flags */ - PFF_INTEGER | PFF_HASALPHA | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_SINT, 4, - /* rbits, gbits, bbits, abits */ - 32, 32, 32, 32, - /* Masks and shifts */ - 0, 0, 0, 0, - 96, 64, 32, 0 - }, - //----------------------------------------------------------------------- - {"PF_R9G9B9E5_SHAREDEXP", - /* Bytes per element */ - 4, - /* Flags */ - PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 9, 9, 9, 0, - /* Masks and shifts */ - 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF, - 24, 16, 8, 0 - }, - //----------------------------------------------------------------------- - {"PF_BC4_UNORM", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED, - /* Component type and count */ - PCT_BYTE, 1, // Red only - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_BC4_SNORM", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED, - /* Component type and count */ - PCT_BYTE, 1, // Red only - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_BC5_UNORM", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED, - /* Component type and count */ - PCT_BYTE, 2, // Red-Green only - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_BC5_SNORM", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED, - /* Component type and count */ - PCT_BYTE, 2, // Red-Green only - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_BC6H_UF16", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED, - /* Component type and count */ - PCT_BYTE, 3, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_BC6H_SF16", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED, - /* Component type and count */ - PCT_BYTE, 3, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_BC7_UNORM", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R8", - /* Bytes per element */ - 1, - /* Flags */ - PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 1, - /* rbits, gbits, bbits, abits */ - 8, 0, 0, 0, - /* Masks and shifts */ - 0xFF, 0, 0, 0, - 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R8G8", - /* Bytes per element */ - 2, - /* Flags */ - PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 2, - /* rbits, gbits, bbits, abits */ - 8, 8, 0, 0, - /* Masks and shifts */ - 0xFF0000, 0x00FF00, 0, 0, - 8, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R8_SNORM", - /* Bytes per element */ - 1, - /* Flags */ - PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 1, - /* rbits, gbits, bbits, abits */ - 8, 0, 0, 0, - /* Masks and shifts */ - 0xFF, 0, 0, 0, - 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R8G8_SNORM", - /* Bytes per element */ - 2, - /* Flags */ - PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 2, - /* rbits, gbits, bbits, abits */ - 8, 8, 0, 0, - /* Masks and shifts */ - 0xFF00, 0x00FF, 0, 0, - 8, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R8G8B8_SNORM", - /* Bytes per element */ - 3, - /* Flags */ - PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 3, - /* rbits, gbits, bbits, abits */ - 8, 8, 8, 0, - /* Masks and shifts */ - 0xFF0000, 0x00FF00, 0x0000FF, 0, - 16, 8, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R8G8B8A8_SNORM", - /* Bytes per element */ - 4, - /* Flags */ - PFF_HASALPHA | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 8, 8, 8, 8, - /* Masks and shifts */ - 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF, - 24, 16, 8, 0 - }, - //----------------------------------------------------------------------- - {"PF_R16_SNORM", - /* Bytes per element */ - 2, - /* Flags */ - PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 1, - /* rbits, gbits, bbits, abits */ - 16, 0, 0, 0, - /* Masks and shifts */ - 0xFFFF, 0, 0, 0, - 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R16G16_SNORM", - /* Bytes per element */ - 4, - /* Flags */ - PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 2, - /* rbits, gbits, bbits, abits */ - 16, 16, 0, 0, - /* Masks and shifts */ - 0xFFFF0000, 0x0000FFFF, 0, 0, - 16, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R16G16B16_SNORM", - /* Bytes per element */ - 6, - /* Flags */ - PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 3, - /* rbits, gbits, bbits, abits */ - 16, 16, 16, 0, - /* Masks and shifts */ - 0xFFFF00000000ULL, 0x0000FFFF0000ULL, 0x00000000FFFFULL, 0, - 32, 16, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_R16G16B16A16_SNORM", - /* Bytes per element */ - 8, - /* Flags */ - PFF_HASALPHA | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 16, 16, 16, 16, - /* Masks and shifts */ - 0xFFFF000000000000ULL, 0x0000FFFF00000000ULL, 0x00000000FFFF0000ULL, 0x000000000000FFFFULL, - 48, 32, 16, 0 - }, - - //----------------------------------------------------------------------- - {"PF_ETC1_RGB8", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED, - /* Component type and count */ - PCT_BYTE, 3, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ETC2_RGB8", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED, - /* Component type and count */ - PCT_BYTE, 3, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ETC2_RGBA8", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ETC2_RGB8A1", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ATC_RGB", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED, - /* Component type and count */ - PCT_BYTE, 3, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ATC_RGBA_EXPLICIT_ALPHA", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ATC_RGBA_INTERPOLATED_ALPHA", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ASTC_RGBA_4X4_LDR", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ASTC_RGBA_5X4_LDR", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ASTC_RGBA_5X5_LDR", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ASTC_RGBA_6X5_LDR", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ASTC_RGBA_6X6_LDR", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ASTC_RGBA_8X5_LDR", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ASTC_RGBA_8X6_LDR", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ASTC_RGBA_8X8_LDR", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ASTC_RGBA_10X5_LDR", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ASTC_RGBA_10X6_LDR", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ASTC_RGBA_10X8_LDR", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ASTC_RGBA_10X10_LDR", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ASTC_RGBA_12X10_LDR", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_ASTC_RGBA_12X12_LDR", - /* Bytes per element */ - 0, - /* Flags */ - PFF_COMPRESSED | PFF_HASALPHA, - /* Component type and count */ - PCT_BYTE, 4, - /* rbits, gbits, bbits, abits */ - 0, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - {"PF_DEPTH32", - /* Bytes per element */ - 4, - /* Flags */ - PFF_LUMINANCE | PFF_DEPTH | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_UINT, 1, - /* rbits, gbits, bbits, abits */ - 32, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - //----------------------------------------------------------------------- - {"PF_DEPTH32F", - /* Bytes per element */ - 4, - /* Flags */ - PFF_LUMINANCE | PFF_DEPTH | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_FLOAT32, 1, - /* rbits, gbits, bbits, abits */ - 32, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - {"PF_DEPTH24_STENCIL8", - /* Bytes per element */ - 4, - /* Flags */ - PFF_LUMINANCE | PFF_DEPTH | PFF_NATIVEENDIAN, - /* Component type and count */ - PCT_UINT, 1, - /* rbits, gbits, bbits, abits */ - 24, 0, 0, 0, - /* Masks and shifts */ - 0, 0, 0, 0, 0, 0, 0, 0 - }, - }; - /** @} */ - /** @} */ - -} - -#endif diff --git a/OgreMain/src/OgrePlatformInformation.cpp b/OgreMain/src/OgrePlatformInformation.cpp deleted file mode 100644 index ad8beee35f2..00000000000 --- a/OgreMain/src/OgrePlatformInformation.cpp +++ /dev/null @@ -1,725 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -#include // For SEH values -#include -#elif OGRE_COMPILER == OGRE_COMPILER_GNUC || OGRE_COMPILER == OGRE_COMPILER_CLANG -#include -#include - - #if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - #include - #elif OGRE_CPU == OGRE_CPU_ARM && OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - #include - #if __MACH__ - #include - #ifndef CPU_SUBTYPE_ARM64_V8 - #define CPU_SUBTYPE_ARM64_V8 ((cpu_subtype_t) 1) - #endif - #ifndef CPU_SUBTYPE_ARM_V8 - #define CPU_SUBTYPE_ARM_V8 ((cpu_subtype_t) 13) - #endif - #endif - #endif -#endif - -// Yes, I know, this file looks very ugly, but there aren't other ways to do it better. - -namespace Ogre { - -#if OGRE_CPU == OGRE_CPU_X86 - - //--------------------------------------------------------------------- - // Struct for store CPUID instruction result, compiler-independent - //--------------------------------------------------------------------- - struct CpuidResult - { - // Note: DO NOT CHANGE THE ORDER, some code based on that. - uint _eax; - uint _ebx; - uint _edx; - uint _ecx; - }; - - //--------------------------------------------------------------------- - // Compiler-dependent routines - //--------------------------------------------------------------------- - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -#pragma warning(push) -#pragma warning(disable: 4035) // no return value -#endif - - //--------------------------------------------------------------------- - // Detect whether CPU supports CPUID instruction, returns non-zero if supported. - static int _isSupportCpuid(void) - { -#if OGRE_COMPILER == OGRE_COMPILER_MSVC - // Visual Studio 2005 & 64-bit compilers always supports __cpuid intrinsic - // note that even though this is a build rather than runtime setting, all - // 64-bit CPUs support this so since binary is 64-bit only we're ok - #if _MSC_VER >= 1400 && defined(_M_X64) - return true; - #else - // If we can modify flag register bit 21, the cpu is supports CPUID instruction - __asm - { - // Read EFLAG - pushfd - pop eax - mov ecx, eax - - // Modify bit 21 - xor eax, 0x200000 - push eax - popfd - - // Read back EFLAG - pushfd - pop eax - - // Restore EFLAG - push ecx - popfd - - // Check bit 21 modifiable - xor eax, ecx - neg eax - sbb eax, eax - - // Return values in eax, no return statement requirement here for VC. - } - #endif -#elif (OGRE_COMPILER == OGRE_COMPILER_GNUC || OGRE_COMPILER == OGRE_COMPILER_CLANG) && OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN - #if OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_64 - return true; - #else - unsigned oldFlags, newFlags; - __asm__ - ( - "pushfl \n\t" - "pop %0 \n\t" - "mov %0, %1 \n\t" - "xor %2, %0 \n\t" - "push %0 \n\t" - "popfl \n\t" - "pushfl \n\t" - "pop %0 \n\t" - "push %1 \n\t" - "popfl \n\t" - : "=r" (oldFlags), "=r" (newFlags) - : "n" (0x200000) - ); - return oldFlags != newFlags; - #endif // 64 -#else - // TODO: Supports other compiler - return false; -#endif - } - - //--------------------------------------------------------------------- - // Performs CPUID instruction with 'query', fill the results, and return value of eax. - static uint _performCpuid(int query, CpuidResult& result) - { -#if OGRE_COMPILER == OGRE_COMPILER_MSVC - int CPUInfo[4]; - __cpuid(CPUInfo, query); - result._eax = CPUInfo[0]; - result._ebx = CPUInfo[1]; - result._ecx = CPUInfo[2]; - result._edx = CPUInfo[3]; - return result._eax; -#elif (OGRE_COMPILER == OGRE_COMPILER_GNUC || OGRE_COMPILER == OGRE_COMPILER_CLANG) && OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN - #if OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_64 - __asm__ - ( - "cpuid": "=a" (result._eax), "=b" (result._ebx), "=c" (result._ecx), "=d" (result._edx) : "a" (query) - ); - #else - __asm__ - ( - "pushl %%ebx \n\t" - "cpuid \n\t" - "movl %%ebx, %%edi \n\t" - "popl %%ebx \n\t" - : "=a" (result._eax), "=D" (result._ebx), "=c" (result._ecx), "=d" (result._edx) - : "a" (query) - ); - #endif // OGRE_ARCHITECTURE_64 - return result._eax; - -#else - // TODO: Supports other compiler - return 0; -#endif - } - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -#pragma warning(pop) -#endif - - //--------------------------------------------------------------------- - // Detect whether or not os support Streaming SIMD Extension. -#if OGRE_COMPILER == OGRE_COMPILER_GNUC || OGRE_COMPILER == OGRE_COMPILER_CLANG - #if OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_32 && OGRE_CPU == OGRE_CPU_X86 - static jmp_buf sIllegalJmpBuf; - static void _illegalHandler(int x) - { - (void)(x); // Unused - longjmp(sIllegalJmpBuf, 1); - } - #endif -#endif - static bool _checkOperatingSystemSupportSSE(void) - { -#if OGRE_COMPILER == OGRE_COMPILER_MSVC - /* - The FP part of SSE introduces a new architectural state and therefore - requires support from the operating system. So even if CPUID indicates - support for SSE FP, the application might not be able to use it. If - CPUID indicates support for SSE FP, check here whether it is also - supported by the OS, and turn off the SSE FP feature bit if there - is no OS support for SSE FP. - - Operating systems that do not support SSE FP return an illegal - instruction exception if execution of an SSE FP instruction is performed. - Here, a sample SSE FP instruction is executed, and is checked for an - exception using the (non-standard) __try/__except mechanism - of Microsoft Visual C/C++. - */ - // Visual Studio 2005, Both AMD and Intel x64 support SSE - // note that even though this is a build rather than runtime setting, all - // 64-bit CPUs support this so since binary is 64-bit only we're ok - #if _MSC_VER >= 1400 && defined(_M_X64) - return true; - #else - __try - { - __asm orps xmm0, xmm0 - return true; - } - __except(EXCEPTION_EXECUTE_HANDLER) - { - return false; - } - #endif -#elif (OGRE_COMPILER == OGRE_COMPILER_GNUC || OGRE_COMPILER == OGRE_COMPILER_CLANG) && OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN - #if OGRE_ARCH_TYPE == OGRE_ARCHITECTURE_64 - return true; - #else - // Does gcc have __try/__except similar mechanism? - // Use signal, setjmp/longjmp instead. - void (*oldHandler)(int); - oldHandler = signal(SIGILL, _illegalHandler); - - if (setjmp(sIllegalJmpBuf)) - { - signal(SIGILL, oldHandler); - return false; - } - else - { - __asm__ __volatile__ ("orps %xmm0, %xmm0"); - signal(SIGILL, oldHandler); - return true; - } - #endif -#else - // TODO: Supports other compiler, assumed is supported by default - return true; -#endif - } - - //--------------------------------------------------------------------- - // Compiler-independent routines - //--------------------------------------------------------------------- - - static uint queryCpuFeatures(void) - { - -#define CPUID_FUNC_VENDOR_ID 0x0 -#define CPUID_FUNC_STANDARD_FEATURES 0x1 -#define CPUID_FUNC_EXTENSION_QUERY 0x80000000 -#define CPUID_FUNC_EXTENDED_FEATURES 0x80000001 -#define CPUID_FUNC_ADVANCED_POWER_MANAGEMENT 0x80000007 - -#define CPUID_STD_FPU (1<<0) -#define CPUID_STD_TSC (1<<4) -#define CPUID_STD_CMOV (1<<15) -#define CPUID_STD_MMX (1<<23) -#define CPUID_STD_SSE (1<<25) -#define CPUID_STD_SSE2 (1<<26) -#define CPUID_STD_HTT (1<<28) // EDX[28] - Bit 28 set indicates Hyper-Threading Technology is supported in hardware. - -#define CPUID_STD_SSE3 (1<<0) // ECX[0] - Bit 0 of standard function 1 indicate SSE3 supported -#define CPUID_STD_SSE41 (1<<19) // ECX[19] - Bit 0 of standard function 1 indicate SSE41 supported -#define CPUID_STD_SSE42 (1<<20) // ECX[20] - Bit 0 of standard function 1 indicate SSE42 supported - -#define CPUID_FAMILY_ID_MASK 0x0F00 // EAX[11:8] - Bit 11 thru 8 contains family processor id -#define CPUID_EXT_FAMILY_ID_MASK 0x0F00000 // EAX[23:20] - Bit 23 thru 20 contains extended family processor id -#define CPUID_PENTIUM4_ID 0x0F00 // Pentium 4 family processor id - -#define CPUID_EXT_3DNOW (1<<31) -#define CPUID_EXT_AMD_3DNOWEXT (1<<30) -#define CPUID_EXT_AMD_MMXEXT (1<<22) - - -#define CPUID_APM_INVARIANT_TSC (1<<8) // EDX[8] - Bit 8 of function 0x80000007 indicates support for invariant TSC. - - uint features = 0; - - // Supports CPUID instruction ? - if (_isSupportCpuid()) - { - CpuidResult result; - - // Has standard feature ? - if (_performCpuid(CPUID_FUNC_VENDOR_ID, result)) - { - // Check vendor strings - if (memcmp(&result._ebx, "GenuineIntel", 12) == 0) - { - if (result._eax > 2) - features |= PlatformInformation::CPU_FEATURE_PRO; - - // Check standard feature - _performCpuid(CPUID_FUNC_STANDARD_FEATURES, result); - - if (result._edx & CPUID_STD_FPU) - features |= PlatformInformation::CPU_FEATURE_FPU; - if (result._edx & CPUID_STD_TSC) - features |= PlatformInformation::CPU_FEATURE_TSC; - if (result._edx & CPUID_STD_CMOV) - features |= PlatformInformation::CPU_FEATURE_CMOV; - if (result._edx & CPUID_STD_MMX) - features |= PlatformInformation::CPU_FEATURE_MMX; - if (result._edx & CPUID_STD_SSE) - features |= PlatformInformation::CPU_FEATURE_MMXEXT | PlatformInformation::CPU_FEATURE_SSE; - if (result._edx & CPUID_STD_SSE2) - features |= PlatformInformation::CPU_FEATURE_SSE2; - if (result._ecx & CPUID_STD_SSE3) - features |= PlatformInformation::CPU_FEATURE_SSE3; - if (result._ecx & CPUID_STD_SSE41) - features |= PlatformInformation::CPU_FEATURE_SSE41; - if (result._ecx & CPUID_STD_SSE42) - features |= PlatformInformation::CPU_FEATURE_SSE42; - - // Check to see if this is a Pentium 4 or later processor - if ((result._eax & CPUID_EXT_FAMILY_ID_MASK) || - (result._eax & CPUID_FAMILY_ID_MASK) == CPUID_PENTIUM4_ID) - { - // Check hyper-threading technology - if (result._edx & CPUID_STD_HTT) - features |= PlatformInformation::CPU_FEATURE_HTT; - } - - - const uint maxExtensionFunctionSupport = _performCpuid(CPUID_FUNC_EXTENSION_QUERY, result); - if (maxExtensionFunctionSupport >= CPUID_FUNC_ADVANCED_POWER_MANAGEMENT) - { - _performCpuid(CPUID_FUNC_ADVANCED_POWER_MANAGEMENT, result); - - if (result._edx & CPUID_APM_INVARIANT_TSC) - features |= PlatformInformation::CPU_FEATURE_INVARIANT_TSC; - } - } - else if (memcmp(&result._ebx, "AuthenticAMD", 12) == 0) - { - features |= PlatformInformation::CPU_FEATURE_PRO; - - // Check standard feature - _performCpuid(CPUID_FUNC_STANDARD_FEATURES, result); - - if (result._edx & CPUID_STD_FPU) - features |= PlatformInformation::CPU_FEATURE_FPU; - if (result._edx & CPUID_STD_TSC) - features |= PlatformInformation::CPU_FEATURE_TSC; - if (result._edx & CPUID_STD_CMOV) - features |= PlatformInformation::CPU_FEATURE_CMOV; - if (result._edx & CPUID_STD_MMX) - features |= PlatformInformation::CPU_FEATURE_MMX; - if (result._edx & CPUID_STD_SSE) - features |= PlatformInformation::CPU_FEATURE_SSE; - if (result._edx & CPUID_STD_SSE2) - features |= PlatformInformation::CPU_FEATURE_SSE2; - - if (result._ecx & CPUID_STD_SSE3) - features |= PlatformInformation::CPU_FEATURE_SSE3; - - // Has extended feature ? - const uint maxExtensionFunctionSupport = _performCpuid(CPUID_FUNC_EXTENSION_QUERY, result); - if (maxExtensionFunctionSupport >= CPUID_FUNC_EXTENDED_FEATURES) - { - // Check extended feature - _performCpuid(CPUID_FUNC_EXTENDED_FEATURES, result); - - if (result._edx & CPUID_EXT_3DNOW) - features |= PlatformInformation::CPU_FEATURE_3DNOW; - if (result._edx & CPUID_EXT_AMD_3DNOWEXT) - features |= PlatformInformation::CPU_FEATURE_3DNOWEXT; - if (result._edx & CPUID_EXT_AMD_MMXEXT) - features |= PlatformInformation::CPU_FEATURE_MMXEXT; - } - - - if (maxExtensionFunctionSupport >= CPUID_FUNC_ADVANCED_POWER_MANAGEMENT) - { - _performCpuid(CPUID_FUNC_ADVANCED_POWER_MANAGEMENT, result); - - if (result._edx & CPUID_APM_INVARIANT_TSC) - features |= PlatformInformation::CPU_FEATURE_INVARIANT_TSC; - } - } - } - } - - return features; - } - //--------------------------------------------------------------------- - static uint _detectCpuFeatures(void) - { - uint features = queryCpuFeatures(); - - const uint sse_features = 0 - | PlatformInformation::CPU_FEATURE_SSE - | PlatformInformation::CPU_FEATURE_SSE2 - | PlatformInformation::CPU_FEATURE_SSE3 - | PlatformInformation::CPU_FEATURE_SSE41 - | PlatformInformation::CPU_FEATURE_SSE42; - - if ((features & sse_features) && !_checkOperatingSystemSupportSSE()) - { - features &= ~sse_features; - } - - return features; - } - //--------------------------------------------------------------------- - static String _detectCpuIdentifier(void) - { - // Supports CPUID instruction ? - if (_isSupportCpuid()) - { - CpuidResult result; - uint nExIds; - char CPUString[0x20]; - char CPUBrandString[0x40]; - - StringStream detailedIdentStr; - - - // Has standard feature ? - if (_performCpuid(0, result)) - { - memset(CPUString, 0, sizeof(CPUString)); - memset(CPUBrandString, 0, sizeof(CPUBrandString)); - - //*((int*)CPUString) = result._ebx; - //*((int*)(CPUString+4)) = result._edx; - //*((int*)(CPUString+8)) = result._ecx; - memcpy(CPUString, &result._ebx, sizeof(int)); - memcpy(CPUString+4, &result._edx, sizeof(int)); - memcpy(CPUString+8, &result._ecx, sizeof(int)); - - detailedIdentStr << CPUString; - - // Calling _performCpuid with 0x80000000 as the query argument - // gets the number of valid extended IDs. - nExIds = _performCpuid(0x80000000, result); - - for (uint i=0x80000000; i<=nExIds; ++i) - { - _performCpuid(i, result); - - // Interpret CPU brand string and cache information. - if (i == 0x80000002) - { - memcpy(CPUBrandString + 0, &result._eax, sizeof(result._eax)); - memcpy(CPUBrandString + 4, &result._ebx, sizeof(result._ebx)); - memcpy(CPUBrandString + 8, &result._ecx, sizeof(result._ecx)); - memcpy(CPUBrandString + 12, &result._edx, sizeof(result._edx)); - } - else if (i == 0x80000003) - { - memcpy(CPUBrandString + 16 + 0, &result._eax, sizeof(result._eax)); - memcpy(CPUBrandString + 16 + 4, &result._ebx, sizeof(result._ebx)); - memcpy(CPUBrandString + 16 + 8, &result._ecx, sizeof(result._ecx)); - memcpy(CPUBrandString + 16 + 12, &result._edx, sizeof(result._edx)); - } - else if (i == 0x80000004) - { - memcpy(CPUBrandString + 32 + 0, &result._eax, sizeof(result._eax)); - memcpy(CPUBrandString + 32 + 4, &result._ebx, sizeof(result._ebx)); - memcpy(CPUBrandString + 32 + 8, &result._ecx, sizeof(result._ecx)); - memcpy(CPUBrandString + 32 + 12, &result._edx, sizeof(result._edx)); - } - } - - String brand(CPUBrandString); - StringUtil::trim(brand); - if (!brand.empty()) - detailedIdentStr << ": " << brand; - - return detailedIdentStr.str(); - } - } - - return "X86"; - } - -#elif OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - static uint _detectCpuFeatures(void) - { - uint features = 0; -#if OGRE_CPU == OGRE_CPU_ARM - uint64_t cpufeatures = android_getCpuFeatures(); - if (cpufeatures & ANDROID_CPU_ARM_FEATURE_NEON) - { - features |= PlatformInformation::CPU_FEATURE_NEON; - } - - if (cpufeatures & ANDROID_CPU_ARM_FEATURE_VFPv3) - { - features |= PlatformInformation::CPU_FEATURE_VFP; - } -#elif OGRE_CPU == OGRE_CPU_X86 - // see https://developer.android.com/ndk/guides/abis.html - features |= PlatformInformation::CPU_FEATURE_SSE; - features |= PlatformInformation::CPU_FEATURE_SSE2; - features |= PlatformInformation::CPU_FEATURE_SSE3; -#endif - return features; - } - //--------------------------------------------------------------------- - static String _detectCpuIdentifier(void) - { - String cpuID; - AndroidCpuFamily cpuInfo = android_getCpuFamily(); - - switch (cpuInfo) { - case ANDROID_CPU_FAMILY_ARM64: - cpuID = "ARM64"; - break; - case ANDROID_CPU_FAMILY_ARM: - { - if (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_ARMv7) - { - cpuID = "ARMv7"; - } - else - { - cpuID = "Unknown ARM"; - } - } - break; - case ANDROID_CPU_FAMILY_X86: - cpuID = "Unknown X86"; - break; - default: - cpuID = "Unknown"; - break; - } - return cpuID; - } - -#elif OGRE_CPU == OGRE_CPU_ARM // OGRE_CPU == OGRE_CPU_ARM - - //--------------------------------------------------------------------- - static uint _detectCpuFeatures(void) - { - // Use preprocessor definitions to determine architecture and CPU features - uint features = 0; -#if defined(__ARM_NEON__) -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - int hasNEON; - size_t len = sizeof(size_t); - sysctlbyname("hw.optional.neon", &hasNEON, &len, NULL, 0); - - if(hasNEON) -#endif - features |= PlatformInformation::CPU_FEATURE_NEON; -#elif defined(__VFP_FP__) - features |= PlatformInformation::CPU_FEATURE_VFP; -#endif - return features; - } - //--------------------------------------------------------------------- - static String _detectCpuIdentifier(void) - { - String cpuID; -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - // Get the size of the CPU subtype struct - size_t size; - sysctlbyname("hw.cpusubtype", NULL, &size, NULL, 0); - - // Get the ARM CPU subtype - cpu_subtype_t cpusubtype = 0; - sysctlbyname("hw.cpusubtype", &cpusubtype, &size, NULL, 0); - - switch(cpusubtype) - { - case CPU_SUBTYPE_ARM_V6: - cpuID = "ARMv6"; - break; - case CPU_SUBTYPE_ARM_V7: - cpuID = "ARMv7"; - break; - case CPU_SUBTYPE_ARM_V7F: - cpuID = "ARM Cortex-A9"; - break; - case CPU_SUBTYPE_ARM_V7S: - cpuID = "ARM Swift"; - break; - case CPU_SUBTYPE_ARM_V8: - cpuID = "ARMv8"; - break; - case CPU_SUBTYPE_ARM64_V8: - cpuID = "ARM64v8"; - break; - default: - cpuID = "Unknown ARM"; - break; - } -#endif - return cpuID; - } - -#elif OGRE_CPU == OGRE_CPU_MIPS // OGRE_CPU == OGRE_CPU_ARM - - //--------------------------------------------------------------------- - static uint _detectCpuFeatures(void) - { - // Use preprocessor definitions to determine architecture and CPU features - uint features = 0; -#if defined(__mips_msa) - features |= PlatformInformation::CPU_FEATURE_MSA; -#endif - return features; - } - //--------------------------------------------------------------------- - static String _detectCpuIdentifier(void) - { - String cpuID = "MIPS"; - - return cpuID; - } - -#else // OGRE_CPU == OGRE_CPU_MIPS - - //--------------------------------------------------------------------- - static uint _detectCpuFeatures(void) - { - return 0; - } - //--------------------------------------------------------------------- - static String _detectCpuIdentifier(void) - { - return "Unknown"; - } - -#endif // OGRE_CPU - - //--------------------------------------------------------------------- - // Platform-independent routines, but the returns value are platform-dependent - //--------------------------------------------------------------------- - - const String& PlatformInformation::getCpuIdentifier(void) - { - static const String sIdentifier = _detectCpuIdentifier(); - return sIdentifier; - } - //--------------------------------------------------------------------- - uint PlatformInformation::getCpuFeatures(void) - { - static const uint sFeatures = _detectCpuFeatures(); - return sFeatures; - } - //--------------------------------------------------------------------- - bool PlatformInformation::hasCpuFeature(CpuFeatures feature) - { - return (getCpuFeatures() & feature) != 0; - } - //--------------------------------------------------------------------- - void PlatformInformation::log(Log* pLog) - { - pLog->logMessage("CPU Identifier & Features"); - pLog->logMessage("-------------------------"); - pLog->logMessage( - " * CPU ID: " + getCpuIdentifier()); -#if OGRE_CPU == OGRE_CPU_X86 - if(_isSupportCpuid()) - { - pLog->logMessage( - " * SSE: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_SSE), true)); - pLog->logMessage( - " * SSE2: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_SSE2), true)); - pLog->logMessage( - " * SSE3: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_SSE3), true)); - pLog->logMessage( - " * SSE41: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_SSE41), true)); - pLog->logMessage( - " * SSE42: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_SSE42), true)); - pLog->logMessage( - " * MMX: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_MMX), true)); - pLog->logMessage( - " * MMXEXT: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_MMXEXT), true)); - pLog->logMessage( - " * 3DNOW: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_3DNOW), true)); - pLog->logMessage( - " * 3DNOWEXT: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_3DNOWEXT), true)); - pLog->logMessage( - " * CMOV: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_CMOV), true)); - pLog->logMessage( - " * TSC: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_TSC), true)); - pLog->logMessage( - " *INVARIANT TSC: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_INVARIANT_TSC), true)); - pLog->logMessage( - " * FPU: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_FPU), true)); - pLog->logMessage( - " * PRO: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_PRO), true)); - pLog->logMessage( - " * HT: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_HTT), true)); - } -#elif OGRE_CPU == OGRE_CPU_ARM || OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - pLog->logMessage( - " * VFP: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_VFP), true)); - pLog->logMessage( - " * NEON: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_NEON), true)); -#elif OGRE_CPU == OGRE_CPU_MIPS - pLog->logMessage( - " * MSA: " + StringConverter::toString(hasCpuFeature(CPU_FEATURE_MSA), true)); -#endif - pLog->logMessage("-------------------------"); - - } - - -} diff --git a/OgreMain/src/OgrePolygon.cpp b/OgreMain/src/OgrePolygon.cpp deleted file mode 100644 index 5e8f1d87d36..00000000000 --- a/OgreMain/src/OgrePolygon.cpp +++ /dev/null @@ -1,262 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Copyright (c) 2006 Matthias Fink, netAllied GmbH - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgrePolygon.h" - -namespace Ogre -{ - - //----------------------------------------------------------------------- - Polygon::Polygon() - : mNormal( Vector3::ZERO ) - , mIsNormalSet(false) - { - // reserve space for 6 vertices to reduce allocation cost - mVertexList.reserve(6); - } - //----------------------------------------------------------------------- - Polygon::~Polygon() - { - } - //----------------------------------------------------------------------- - Polygon::Polygon( const Polygon& cpy ) - { - mVertexList = cpy.mVertexList; - mNormal = cpy.mNormal; - mIsNormalSet = cpy.mIsNormalSet; - } - //----------------------------------------------------------------------- - void Polygon::insertVertex(const Vector3& vdata, size_t vertex ) - { - // TODO: optional: check planarity - OgreAssertDbg(vertex <= getVertexCount(), "Insert position out of range" ); - - VertexList::iterator it = mVertexList.begin(); - - std::advance(it, vertex); - mVertexList.insert(it, vdata); - - } - //----------------------------------------------------------------------- - void Polygon::insertVertex(const Vector3& vdata) - { - mVertexList.push_back(vdata); - } - //----------------------------------------------------------------------- - const Vector3& Polygon::getVertex( size_t vertex ) const - { - OgreAssertDbg(vertex < getVertexCount(), "Search position out of range"); - - return mVertexList[vertex]; - } - //----------------------------------------------------------------------- - void Polygon::setVertex(const Vector3& vdata, size_t vertex ) - { - // TODO: optional: check planarity - OgreAssertDbg(vertex < getVertexCount(), "Search position out of range" ); - - // set new vertex - mVertexList[ vertex ] = vdata; - } - //----------------------------------------------------------------------- - void Polygon::removeDuplicates( void ) - { - for ( size_t i = 0; i < getVertexCount(); ++i ) - { - const Vector3& a = getVertex( i ); - const Vector3& b = getVertex( (i + 1)%getVertexCount() ); - - if (a.positionEquals(b)) - { - deleteVertex(i); - --i; - } - } - } - //----------------------------------------------------------------------- - size_t Polygon::getVertexCount( void ) const - { - return mVertexList.size(); - } - //----------------------------------------------------------------------- - const Vector3& Polygon::getNormal( void ) const - { - updateNormal(); - - return mNormal; - } - //----------------------------------------------------------------------- - void Polygon::updateNormal( void ) const - { - OgreAssertDbg( getVertexCount() >= 3, "Insufficient vertex count!" ); - - if (mIsNormalSet) - return; - - // vertex order is ccw - const Vector3& a = getVertex( 0 ); - const Vector3& b = getVertex( 1 ); - const Vector3& c = getVertex( 2 ); - - // used method: Newell - mNormal.x = 0.5f * ( (a.y - b.y) * (a.z + b.z) + - (b.y - c.y) * (b.z + c.z) + - (c.y - a.y) * (c.z + a.z)); - - mNormal.y = 0.5f * ( (a.z - b.z) * (a.x + b.x) + - (b.z - c.z) * (b.x + c.x) + - (c.z - a.z) * (c.x + a.x)); - - mNormal.z = 0.5f * ( (a.x - b.x) * (a.y + b.y) + - (b.x - c.x) * (b.y + c.y) + - (c.x - a.x) * (c.y + a.y)); - - mNormal.normalise(); - - mIsNormalSet = true; - - } - //----------------------------------------------------------------------- - void Polygon::deleteVertex( size_t vertex ) - { - OgreAssertDbg( vertex < getVertexCount(), "Search position out of range" ); - - VertexList::iterator it = mVertexList.begin(); - std::advance(it, vertex); - - mVertexList.erase( it ); - } - //----------------------------------------------------------------------- - void Polygon::storeEdges( Polygon::EdgeMap *edgeMap ) const - { - OgreAssert( edgeMap != NULL, "EdgeMap ptr is NULL" ); - - size_t vertexCount = getVertexCount(); - - for ( size_t i = 0; i < vertexCount; ++i ) - { - edgeMap->insert( Edge( getVertex( i ), getVertex( ( i + 1 ) % vertexCount ) ) ); - } - } - //----------------------------------------------------------------------- - void Polygon::reset( void ) - { - // could use swap() to free memory here, but assume most may be reused so avoid realloc - mVertexList.clear(); - - mIsNormalSet = false; - } - //----------------------------------------------------------------------- - bool Polygon::operator == (const Polygon& rhs) const - { - if ( getVertexCount() != rhs.getVertexCount() ) - return false; - - // Compare vertices. They may differ in its starting position. - // find start - size_t start = 0; - bool foundStart = false; - for (size_t i = 0; i < getVertexCount(); ++i ) - { - if (getVertex(0).positionEquals(rhs.getVertex(i))) - { - start = i; - foundStart = true; - break; - } - } - - if (!foundStart) - return false; - - for (size_t i = 0; i < getVertexCount(); ++i ) - { - const Vector3& vA = getVertex( i ); - const Vector3& vB = rhs.getVertex( ( i + start) % getVertexCount() ); - - if (!vA.positionEquals(vB)) - return false; - } - - return true; - } - //----------------------------------------------------------------------- - Polygon& Polygon::operator=(const Ogre::Polygon& rhs) - { - mIsNormalSet = rhs.mIsNormalSet; - mNormal = rhs.mNormal; - mVertexList = rhs.mVertexList; - return *this; - } - //----------------------------------------------------------------------- - std::ostream& operator<< ( std::ostream& strm, const Polygon& poly ) - { - strm << "NUM VERTICES: " << poly.getVertexCount() << std::endl; - - for (size_t j = 0; j < poly.getVertexCount(); ++j ) - { - strm << "VERTEX " << j << ": " << poly.getVertex( j ) << std::endl; - } - - return strm; - } - //----------------------------------------------------------------------- - bool Polygon::isPointInside(const Vector3& point) const - { - // sum the angles - Real anglesum = 0; - size_t n = getVertexCount(); - for (size_t i = 0; i < n; i++) - { - const Vector3& p1 = getVertex(i); - const Vector3& p2 = getVertex((i + 1) % n); - - Vector3 v1 = p1 - point; - Vector3 v2 = p2 - point; - - Real len1 = v1.length(); - Real len2 = v2.length(); - - if (Math::RealEqual(len1 * len2, 0.0f, 1e-4f)) - { - // We are on a vertex so consider this inside - return true; - } - else - { - Real costheta = v1.dotProduct(v2) / (len1 * len2); - anglesum += std::acos(costheta); - } - } - - // result should be 2*PI if point is inside poly - return Math::RealEqual(anglesum, Math::TWO_PI, 1e-4f); - - } -} diff --git a/OgreMain/src/OgrePose.cpp b/OgreMain/src/OgrePose.cpp deleted file mode 100644 index 54e98349576..00000000000 --- a/OgreMain/src/OgrePose.cpp +++ /dev/null @@ -1,191 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgrePose.h" - -namespace Ogre { - //--------------------------------------------------------------------- - Pose::Pose(ushort target, const String& name) - : mTarget(target), mName(name) - { - } - //--------------------------------------------------------------------- - void Pose::addVertex(uint32 index, const Vector3f& offset) - { - OgreAssert(mNormalsMap.empty(), - "Inconsistent calls to addVertex, must include normals always or never"); - - if(offset.squaredLength() < 1e-6f) - { - return; - } - - mVertexOffsetMap[index] = offset; - mBuffer.reset(); - } - //--------------------------------------------------------------------- - void Pose::addVertex(uint32 index, const Vector3f& offset, const Vector3f& normal) - { - OgreAssert(mVertexOffsetMap.empty() || !mNormalsMap.empty(), - "Inconsistent calls to addVertex, must include normals always or never"); - - if(offset.squaredLength() < 1e-6f && normal.squaredLength() < 1e-6f) - { - return; - } - - mVertexOffsetMap[index] = offset; - mNormalsMap[index] = normal; - mBuffer.reset(); - } - //--------------------------------------------------------------------- - void Pose::removeVertex(uint32 index) - { - VertexOffsetMap::iterator i = mVertexOffsetMap.find(index); - if (i != mVertexOffsetMap.end()) - { - mVertexOffsetMap.erase(i); - mBuffer.reset(); - } - NormalsMap::iterator j = mNormalsMap.find(index); - if (j != mNormalsMap.end()) - { - mNormalsMap.erase(j); - } - } - //--------------------------------------------------------------------- - void Pose::clearVertices(void) - { - mVertexOffsetMap.clear(); - mNormalsMap.clear(); - mBuffer.reset(); - } - //--------------------------------------------------------------------- - Pose::ConstVertexOffsetIterator - Pose::getVertexOffsetIterator(void) const - { - return ConstVertexOffsetIterator(mVertexOffsetMap.begin(), mVertexOffsetMap.end()); - } - //--------------------------------------------------------------------- - Pose::VertexOffsetIterator - Pose::getVertexOffsetIterator(void) - { - return VertexOffsetIterator(mVertexOffsetMap.begin(), mVertexOffsetMap.end()); - } - //--------------------------------------------------------------------- - Pose::ConstNormalsIterator Pose::getNormalsIterator(void) const - { - return ConstNormalsIterator(mNormalsMap.begin(), mNormalsMap.end()); - } - //--------------------------------------------------------------------- - Pose::NormalsIterator Pose::getNormalsIterator(void) - { - return NormalsIterator(mNormalsMap.begin(), mNormalsMap.end()); - } - //--------------------------------------------------------------------- - const HardwareVertexBufferSharedPtr& Pose::_getHardwareVertexBuffer(const VertexData* origData) const - { - size_t numVertices = origData->vertexCount; - - if (!mBuffer) - { - // Create buffer - size_t vertexSize = VertexElement::getTypeSize(VET_FLOAT3); - bool normals = getIncludesNormals(); - if (normals) - vertexSize += VertexElement::getTypeSize(VET_FLOAT3); - - mBuffer = HardwareBufferManager::getSingleton().createVertexBuffer( - vertexSize, numVertices, HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - HardwareBufferLockGuard bufLock(mBuffer, HardwareBuffer::HBL_DISCARD); - float* pFloat = static_cast(bufLock.pData); - // initialise - these will be the values used where no pose vertex is included - memset(pFloat, 0, mBuffer->getSizeInBytes()); - if (normals) - { - // zeroes are fine for positions (deltas), but for normals we need the original - // mesh normals, since delta normals don't work (re-normalisation would - // always result in a blended normal even with full pose applied) - const VertexElement* origNormElem = - origData->vertexDeclaration->findElementBySemantic(VES_NORMAL, 0); - assert(origNormElem); - - const HardwareVertexBufferSharedPtr& origBuffer = - origData->vertexBufferBinding->getBuffer(origNormElem->getSource()); - HardwareBufferLockGuard origBufLock(origBuffer, HardwareBuffer::HBL_READ_ONLY); - float* pDst = pFloat + 3; - float* pSrc; - origNormElem->baseVertexPointerToElement(origBufLock.pData, &pSrc); - for (size_t v = 0; v < numVertices; ++v) - { - memcpy(pDst, pSrc, sizeof(float)*3); - - pDst += 6; - pSrc = (float*)(((char*)pSrc) + origBuffer->getVertexSize()); - } - } - // Set each vertex - VertexOffsetMap::const_iterator v = mVertexOffsetMap.begin(); - NormalsMap::const_iterator n = mNormalsMap.begin(); - - size_t numFloatsPerVertex = normals ? 6: 3; - - while(v != mVertexOffsetMap.end()) - { - // Remember, vertex maps are *sparse* so may have missing entries - // This is why we skip - float* pDst = pFloat + (numFloatsPerVertex * v->first); - *pDst++ = v->second[0]; - *pDst++ = v->second[1]; - *pDst++ = v->second[2]; - ++v; - if (normals) - { - *pDst++ = n->second[0]; - *pDst++ = n->second[1]; - *pDst++ = n->second[2]; - ++n; - } - - } - } - return mBuffer; - } - //--------------------------------------------------------------------- - Pose* Pose::clone(void) const - { - Pose* newPose = OGRE_NEW Pose(mTarget, mName); - newPose->mVertexOffsetMap = mVertexOffsetMap; - newPose->mNormalsMap = mNormalsMap; - // Allow buffer to recreate itself, contents may change anyway - return newPose; - } - -} - diff --git a/OgreMain/src/OgrePredefinedControllers.cpp b/OgreMain/src/OgrePredefinedControllers.cpp deleted file mode 100644 index 7672ce86673..00000000000 --- a/OgreMain/src/OgrePredefinedControllers.cpp +++ /dev/null @@ -1,331 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgrePredefinedControllers.h" -#include "OgreTextureUnitState.h" - -namespace Ogre -{ - //----------------------------------------------------------------------- - // FrameTimeControllerValue - //----------------------------------------------------------------------- - FrameTimeControllerValue::FrameTimeControllerValue() - { - // Register self - Root::getSingleton().addFrameListener(this); - mFrameTime = 0; - mTimeFactor = 1; - mFrameDelay = 0; - mElapsedTime = 0; - - } - //----------------------------------------------------------------------- - bool FrameTimeControllerValue::frameStarted(const FrameEvent &evt) - { - if(mFrameDelay) - { - // Fixed frame time - mFrameTime = mFrameDelay; - mTimeFactor = mFrameDelay / evt.timeSinceLastFrame; - } - else - { - // Save the time value after applying time factor - mFrameTime = mTimeFactor * evt.timeSinceLastFrame; - } - // Accumulate the elapsed time - mElapsedTime += mFrameTime; - return true; - } - //----------------------------------------------------------------------- - void FrameTimeControllerValue::setTimeFactor(Real tf) { - if(tf >= 0) - { - mTimeFactor = tf; - mFrameDelay = 0; - } - } - //----------------------------------------------------------------------- - void FrameTimeControllerValue::setFrameDelay(Real fd) { - mTimeFactor = 0; - mFrameDelay = fd; - } - //----------------------------------------------------------------------- - // TextureFrameControllerValue - //----------------------------------------------------------------------- - TextureFrameControllerValue::TextureFrameControllerValue(TextureUnitState* t) - { - mTextureLayer = t; - } - //----------------------------------------------------------------------- - float TextureFrameControllerValue::getValue(void) const - { - int numFrames = mTextureLayer->getNumFrames(); - return ((float)mTextureLayer->getCurrentFrame() / (float)numFrames); - } - //----------------------------------------------------------------------- - void TextureFrameControllerValue::setValue(float value) - { - int numFrames = mTextureLayer->getNumFrames(); - mTextureLayer->setCurrentFrame(numFrames ? (int)(value * numFrames) % numFrames : 0); - } - //----------------------------------------------------------------------- - // TexCoordModifierControllerValue - //----------------------------------------------------------------------- - TexCoordModifierControllerValue::TexCoordModifierControllerValue(TextureUnitState* t, - bool translateU, bool translateV, bool scaleU, bool scaleV, bool rotate ) - { - mTextureLayer = t; - mTransU = translateU; - mTransV = translateV; - mScaleU = scaleU; - mScaleV = scaleV; - mRotate = rotate; - } - //----------------------------------------------------------------------- - float TexCoordModifierControllerValue::getValue() const - { - const Matrix4& pMat = mTextureLayer->getTextureTransform(); - if (mTransU) - { - return pMat[0][3]; - } - else if (mTransV) - { - return pMat[1][3]; - } - else if (mScaleU) - { - return pMat[0][0]; - } - else if (mScaleV) - { - return pMat[1][1]; - } - // Shouldn't get here - return 0; - } - //----------------------------------------------------------------------- - void TexCoordModifierControllerValue::setValue(float value) - { - if (mTransU) - { - mTextureLayer->setTextureUScroll(value); - } - if (mTransV) - { - mTextureLayer->setTextureVScroll(value); - } - if (mScaleU) - { - mTextureLayer->setTextureUScale(value); - } - if (mScaleV) - { - mTextureLayer->setTextureVScale(value); - } - if (mRotate) - { - mTextureLayer->setTextureRotate(Radian(value * Math::TWO_PI)); - } - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - FloatGpuParameterControllerValue::FloatGpuParameterControllerValue( - const GpuProgramParametersSharedPtr& params, size_t index) : - mParams(params), mParamIndex(index) - { - } - //----------------------------------------------------------------------- - float FloatGpuParameterControllerValue::getValue(void) const - { - // do nothing, reading from a set of params not supported - return 0.0f; - } - //----------------------------------------------------------------------- - void FloatGpuParameterControllerValue::setValue(float val) - { - Vector4 v4 = Vector4(0,0,0,0); - v4.x = val; - mParams->setConstant(mParamIndex, v4); - } - //----------------------------------------------------------------------- - // PassthroughControllerFunction - //----------------------------------------------------------------------- - PassthroughControllerFunction::PassthroughControllerFunction(bool delta) - : ControllerFunction(delta) - { - } - //----------------------------------------------------------------------- - float PassthroughControllerFunction::calculate(float source) - { - return getAdjustedInput(source); - - } - //----------------------------------------------------------------------- - // AnimationControllerFunction - //----------------------------------------------------------------------- - AnimationControllerFunction::AnimationControllerFunction(Real sequenceTime, Real timeOffset) - : ControllerFunction(false) - { - mSeqTime = sequenceTime; - mTime = timeOffset; - } - //----------------------------------------------------------------------- - float AnimationControllerFunction::calculate(float source) - { - // Assume source is time since last update - mTime += source; - // Wrap - while (mTime >= mSeqTime) mTime -= mSeqTime; - while (mTime < 0) mTime += mSeqTime; - - // Return parametric - return mTime / mSeqTime; - } - //----------------------------------------------------------------------- - void AnimationControllerFunction::setTime(Real timeVal) - { - mTime = timeVal; - } - //----------------------------------------------------------------------- - void AnimationControllerFunction::setSequenceTime(Real seqVal) - { - mSeqTime = seqVal; - } - //----------------------------------------------------------------------- - // ScaleControllerFunction - //----------------------------------------------------------------------- - ScaleControllerFunction::ScaleControllerFunction(Real factor, bool delta) : ControllerFunction(delta) - { - mScale = factor; - } - //----------------------------------------------------------------------- - float ScaleControllerFunction::calculate(float source) - { - return getAdjustedInput(source * mScale); - - } - //----------------------------------------------------------------------- - // WaveformControllerFunction - //----------------------------------------------------------------------- - WaveformControllerFunction::WaveformControllerFunction(WaveformType wType, Real base, Real frequency, Real phase, Real amplitude, bool delta, Real dutyCycle) - :ControllerFunction(delta) - { - mWaveType = wType; - mBase = base; - mFrequency = frequency; - mPhase = phase; - mAmplitude = amplitude; - mDeltaCount = phase; - mDutyCycle = dutyCycle; - } - //----------------------------------------------------------------------- - Real WaveformControllerFunction::getAdjustedInput(Real input) - { - Real adjusted = ControllerFunction::getAdjustedInput(input); - - // If not delta, adjust by phase here - // (delta inputs have it adjusted at initialisation) - if (!mDeltaInput) - { - adjusted += mPhase; - } - - return adjusted; - } - //----------------------------------------------------------------------- - float WaveformControllerFunction::calculate(float source) - { - Real input = getAdjustedInput(source * mFrequency); - Real output = 0; - // For simplicity, factor input down to {0,1) - input = std::fmod(input, Real(1)); - if(input < 0) input += 1; - - // Calculate output in -1..1 range - switch (mWaveType) - { - case WFT_SINE: - output = Math::Sin(Radian(input * Math::TWO_PI)); - break; - case WFT_TRIANGLE: - if (input < 0.25) - output = input * 4; - else if (input >= 0.25 && input < 0.75) - output = 1.0f - ((input - 0.25f) * 4.0f); - else - output = ((input - 0.75f) * 4.0f) - 1.0f; - - break; - case WFT_SQUARE: - if (input <= 0.5f) - output = 1.0f; - else - output = -1.0f; - break; - case WFT_SAWTOOTH: - output = (input * 2.0f) - 1.0f; - break; - case WFT_INVERSE_SAWTOOTH: - output = -((input * 2.0f) - 1.0f); - break; - case WFT_PWM: - if( input <= mDutyCycle ) - output = 1.0f; - else - output = -1.0f; - break; - } - - // Scale output into 0..1 range and then by base + amplitude - return mBase + ((output + 1.0f) * 0.5f * mAmplitude); - - - } - //----------------------------------------------------------------------- - // LinearControllerFunction - //----------------------------------------------------------------------- - LinearControllerFunction::LinearControllerFunction(const std::vector& keys, const std::vector& values, Real frequency, bool deltaInput) : - ControllerFunction(deltaInput), mFrequency(frequency), mKeys(keys), mValues(values) { - assert(mKeys.size() == mValues.size()); - } - //----------------------------------------------------------------------- - float LinearControllerFunction::calculate(float source) { - Real input = getAdjustedInput(source*mFrequency); - - std::vector::iterator ifirst = std::lower_bound(mKeys.begin(), mKeys.end(), input); - size_t idx = ifirst - mKeys.begin() - 1; - - assert(ifirst != mKeys.end()); - - Real alpha = (input - mKeys[idx])/(mKeys[idx + 1] - mKeys[idx]); - return mValues[idx] + alpha * (mValues[idx + 1] - mValues[idx]); - } -} - diff --git a/OgreMain/src/OgrePrefabFactory.cpp b/OgreMain/src/OgrePrefabFactory.cpp deleted file mode 100644 index d3b991d0d99..00000000000 --- a/OgreMain/src/OgrePrefabFactory.cpp +++ /dev/null @@ -1,893 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" -#include "OgrePrefabFactory.h" - -namespace Ogre { - //----------------------------------------------------------------------- - void PrefabFactory::loadResource(Resource* res) - { - Mesh* msh = static_cast(res); - - // attempt to create a prefab mesh - const String& resourceName = msh->getName(); - if(resourceName == "Prefab_Plane") - { - createPlane(msh); - return; - } - else if(resourceName == "Prefab_Cube") - { - createCube(msh); - return; - } - else if(resourceName == "Prefab_Sphere") - { - createSphere(msh); - return; - } - - // the mesh was not a prefab.. grab build parameters - auto any = msh->getUserObjectBindings().getUserAny("_MeshBuildParams"); - - if (!any.has_value()) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "No prefab parameters in " + res->getName()); - - auto params = any_cast(any); - - switch(params.type) - { - case MBT_PLANE: - loadManualPlane(msh, params); - return; - case MBT_CURVED_ILLUSION_PLANE: - loadManualCurvedIllusionPlane(msh, params); - return; - case MBT_CURVED_PLANE: - loadManualCurvedPlane(msh, params); - return; - } - - OgreAssertDbg(false, "unknown prefab type"); - } - //--------------------------------------------------------------------- - void PrefabFactory::createPlane(Mesh* mesh) - { - //! [manual_plane_geometry] - float vertices[32] = { - -100, -100, 0, // pos - 0,0,1, // normal - 0,1, // texcoord - 100, -100, 0, - 0,0,1, - 1,1, - 100, 100, 0, - 0,0,1, - 1,0, - -100, 100, 0 , - 0,0,1, - 0,0 - }; - - uint16 faces[6] = {0,1,2, - 0,2,3 }; - //! [manual_plane_geometry] - - //! [vertex_data] - mesh->createVertexData(); - mesh->sharedVertexData->vertexCount = 4; - VertexDeclaration* decl = mesh->sharedVertexData->vertexDeclaration; - VertexBufferBinding* bind = mesh->sharedVertexData->vertexBufferBinding; - //! [vertex_data] - - //! [vertex_decl] - size_t offset = 0; - offset += decl->addElement(0, offset, VET_FLOAT3, VES_POSITION).getSize(); - offset += decl->addElement(0, offset, VET_FLOAT3, VES_NORMAL).getSize(); - offset += decl->addElement(0, offset, VET_FLOAT2, VES_TEXTURE_COORDINATES, 0).getSize(); - //! [vertex_decl] - - //! [vertex_buffer] - HardwareVertexBufferPtr vbuf = - HardwareBufferManager::getSingleton().createVertexBuffer(offset, 4, HBU_GPU_ONLY); - vbuf->writeData(0, vbuf->getSizeInBytes(), vertices, true); - bind->setBinding(0, vbuf); - - HardwareIndexBufferPtr ibuf = - HardwareBufferManager::getSingleton().createIndexBuffer(HardwareIndexBuffer::IT_16BIT, 6, HBU_GPU_ONLY); - ibuf->writeData(0, ibuf->getSizeInBytes(), faces, true); - //! [vertex_buffer] - - //! [sub_mesh] - SubMesh* sub = mesh->createSubMesh(); - sub->useSharedVertices = true; - sub->indexData->indexBuffer = ibuf; - sub->indexData->indexCount = 6; - sub->indexData->indexStart = 0; - //! [sub_mesh] - - mesh->_setBounds(AxisAlignedBox(-100,-100,0,100,100,0), true); - } - //--------------------------------------------------------------------- - void PrefabFactory::createCube(Mesh* mesh) - { - SubMesh* sub = mesh->createSubMesh(); - - const int NUM_VERTICES = 4 * 6; // 4 vertices per side * 6 sides - const int NUM_ENTRIES_PER_VERTEX = 8; - const int NUM_VERTEX_ENTRIES = NUM_VERTICES * NUM_ENTRIES_PER_VERTEX; - const int NUM_INDICES = 3 * 2 * 6; // 3 indices per face * 2 faces per side * 6 sides - - const float CUBE_SIZE = 100.0f; - const float CUBE_HALF_SIZE = CUBE_SIZE / 2.0f; - - // Create 4 vertices per side instead of 6 that are shared for the whole cube. - // The reason for this is with only 6 vertices the normals will look bad - // since each vertex can "point" in a different direction depending on the face it is included in. - float vertices[NUM_VERTEX_ENTRIES] = { - // front side - -CUBE_HALF_SIZE, -CUBE_HALF_SIZE, CUBE_HALF_SIZE, // pos - 0,0,1, // normal - 0,1, // texcoord - CUBE_HALF_SIZE, -CUBE_HALF_SIZE, CUBE_HALF_SIZE, - 0,0,1, - 1,1, - CUBE_HALF_SIZE, CUBE_HALF_SIZE, CUBE_HALF_SIZE, - 0,0,1, - 1,0, - -CUBE_HALF_SIZE, CUBE_HALF_SIZE, CUBE_HALF_SIZE , - 0,0,1, - 0,0, - - // back side - CUBE_HALF_SIZE, -CUBE_HALF_SIZE, -CUBE_HALF_SIZE, - 0,0,-1, - 0,1, - -CUBE_HALF_SIZE, -CUBE_HALF_SIZE, -CUBE_HALF_SIZE, - 0,0,-1, - 1,1, - -CUBE_HALF_SIZE, CUBE_HALF_SIZE, -CUBE_HALF_SIZE, - 0,0,-1, - 1,0, - CUBE_HALF_SIZE, CUBE_HALF_SIZE, -CUBE_HALF_SIZE, - 0,0,-1, - 0,0, - - // left side - -CUBE_HALF_SIZE, -CUBE_HALF_SIZE, -CUBE_HALF_SIZE, - -1,0,0, - 0,1, - -CUBE_HALF_SIZE, -CUBE_HALF_SIZE, CUBE_HALF_SIZE, - -1,0,0, - 1,1, - -CUBE_HALF_SIZE, CUBE_HALF_SIZE, CUBE_HALF_SIZE, - -1,0,0, - 1,0, - -CUBE_HALF_SIZE, CUBE_HALF_SIZE, -CUBE_HALF_SIZE, - -1,0,0, - 0,0, - - // right side - CUBE_HALF_SIZE, -CUBE_HALF_SIZE, CUBE_HALF_SIZE, - 1,0,0, - 0,1, - CUBE_HALF_SIZE, -CUBE_HALF_SIZE, -CUBE_HALF_SIZE, - 1,0,0, - 1,1, - CUBE_HALF_SIZE, CUBE_HALF_SIZE, -CUBE_HALF_SIZE, - 1,0,0, - 1,0, - CUBE_HALF_SIZE, CUBE_HALF_SIZE, CUBE_HALF_SIZE, - 1,0,0, - 0,0, - - // up side - -CUBE_HALF_SIZE, CUBE_HALF_SIZE, CUBE_HALF_SIZE, - 0,1,0, - 0,1, - CUBE_HALF_SIZE, CUBE_HALF_SIZE, CUBE_HALF_SIZE, - 0,1,0, - 1,1, - CUBE_HALF_SIZE, CUBE_HALF_SIZE, -CUBE_HALF_SIZE, - 0,1,0, - 1,0, - -CUBE_HALF_SIZE, CUBE_HALF_SIZE, -CUBE_HALF_SIZE, - 0,1,0, - 0,0, - - // down side - -CUBE_HALF_SIZE, -CUBE_HALF_SIZE, -CUBE_HALF_SIZE, - 0,-1,0, - 0,1, - CUBE_HALF_SIZE, -CUBE_HALF_SIZE, -CUBE_HALF_SIZE, - 0,-1,0, - 1,1, - CUBE_HALF_SIZE, -CUBE_HALF_SIZE, CUBE_HALF_SIZE, - 0,-1,0, - 1,0, - -CUBE_HALF_SIZE, -CUBE_HALF_SIZE, CUBE_HALF_SIZE, - 0,-1,0, - 0,0 - }; - - mesh->createVertexData(); - mesh->sharedVertexData->vertexCount = NUM_VERTICES; - VertexDeclaration* decl = mesh->sharedVertexData->vertexDeclaration; - VertexBufferBinding* bind = mesh->sharedVertexData->vertexBufferBinding; - - size_t offset = 0; - offset += decl->addElement(0, offset, VET_FLOAT3, VES_POSITION).getSize(); - offset += decl->addElement(0, offset, VET_FLOAT3, VES_NORMAL).getSize(); - offset += decl->addElement(0, offset, VET_FLOAT2, VES_TEXTURE_COORDINATES, 0).getSize(); - - HardwareVertexBufferSharedPtr vbuf = - HardwareBufferManager::getSingleton().createVertexBuffer( - offset, NUM_VERTICES, HardwareBuffer::HBU_STATIC_WRITE_ONLY); - bind->setBinding(0, vbuf); - - vbuf->writeData(0, vbuf->getSizeInBytes(), vertices, true); - - sub->useSharedVertices = true; - HardwareIndexBufferSharedPtr ibuf = HardwareBufferManager::getSingleton(). - createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, - NUM_INDICES, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - unsigned short faces[NUM_INDICES] = { - // front - 0,1,2, - 0,2,3, - - // back - 4,5,6, - 4,6,7, - - // left - 8,9,10, - 8,10,11, - - // right - 12,13,14, - 12,14,15, - - // up - 16,17,18, - 16,18,19, - - // down - 20,21,22, - 20,22,23 - }; - - sub->indexData->indexBuffer = ibuf; - sub->indexData->indexCount = NUM_INDICES; - sub->indexData->indexStart = 0; - ibuf->writeData(0, ibuf->getSizeInBytes(), faces, true); - - mesh->_setBounds(AxisAlignedBox(-CUBE_HALF_SIZE, -CUBE_HALF_SIZE, -CUBE_HALF_SIZE, - CUBE_HALF_SIZE, CUBE_HALF_SIZE, CUBE_HALF_SIZE), true); - } - //--------------------------------------------------------------------- - void PrefabFactory::createSphere(Mesh* mesh) - { - // sphere creation code taken from the DeferredShading sample, originally from the wiki - SubMesh *pSphereVertex = mesh->createSubMesh(); - - const int NUM_SEGMENTS = 16; - const int NUM_RINGS = 16; - const Real SPHERE_RADIUS = 50.0; - - mesh->createVertexData(); - VertexData* vertexData = mesh->sharedVertexData; - - // define the vertex format - VertexDeclaration* vertexDecl = vertexData->vertexDeclaration; - size_t currOffset = 0; - currOffset += vertexDecl->addElement(0, currOffset, VET_FLOAT3, VES_POSITION).getSize(); - currOffset += vertexDecl->addElement(0, currOffset, VET_FLOAT3, VES_NORMAL).getSize(); - currOffset += vertexDecl->addElement(0, currOffset, VET_FLOAT2, VES_TEXTURE_COORDINATES, 0).getSize(); - - // allocate the vertex buffer - vertexData->vertexCount = (NUM_RINGS + 1) * (NUM_SEGMENTS+1); - HardwareVertexBufferSharedPtr vBuf = HardwareBufferManager::getSingleton().createVertexBuffer(vertexDecl->getVertexSize(0), vertexData->vertexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY, false); - VertexBufferBinding* binding = vertexData->vertexBufferBinding; - binding->setBinding(0, vBuf); - HardwareBufferLockGuard vBufLock(vBuf, HardwareBuffer::HBL_DISCARD); - float* pVertex = static_cast(vBufLock.pData); - - // allocate index buffer - pSphereVertex->indexData->indexCount = 6 * NUM_RINGS * (NUM_SEGMENTS + 1); - pSphereVertex->indexData->indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer(HardwareIndexBuffer::IT_16BIT, pSphereVertex->indexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY, false); - HardwareIndexBufferSharedPtr iBuf = pSphereVertex->indexData->indexBuffer; - HardwareBufferLockGuard iBufLock(iBuf, HardwareBuffer::HBL_DISCARD); - unsigned short* pIndices = static_cast(iBufLock.pData); - - float fDeltaRingAngle = (Math::PI / NUM_RINGS); - float fDeltaSegAngle = (2 * Math::PI / NUM_SEGMENTS); - unsigned short wVerticeIndex = 0 ; - - // Generate the group of rings for the sphere - for( int ring = 0; ring <= NUM_RINGS; ring++ ) { - float r0 = SPHERE_RADIUS * sinf (ring * fDeltaRingAngle); - float y0 = SPHERE_RADIUS * cosf (ring * fDeltaRingAngle); - - // Generate the group of segments for the current ring - for(int seg = 0; seg <= NUM_SEGMENTS; seg++) { - float x0 = r0 * sinf(seg * fDeltaSegAngle); - float z0 = r0 * cosf(seg * fDeltaSegAngle); - - // Add one vertex to the strip which makes up the sphere - *pVertex++ = x0; - *pVertex++ = y0; - *pVertex++ = z0; - - Vector3 vNormal = Vector3(x0, y0, z0).normalisedCopy(); - *pVertex++ = vNormal.x; - *pVertex++ = vNormal.y; - *pVertex++ = vNormal.z; - - *pVertex++ = (float) seg / (float) NUM_SEGMENTS; - *pVertex++ = (float) ring / (float) NUM_RINGS; - - if (ring != NUM_RINGS) { - // each vertex (except the last) has six indicies pointing to it - *pIndices++ = wVerticeIndex + NUM_SEGMENTS + 1; - *pIndices++ = wVerticeIndex; - *pIndices++ = wVerticeIndex + NUM_SEGMENTS; - *pIndices++ = wVerticeIndex + NUM_SEGMENTS + 1; - *pIndices++ = wVerticeIndex + 1; - *pIndices++ = wVerticeIndex; - wVerticeIndex ++; - } - }; // end for seg - } // end for ring - - // Generate face list - pSphereVertex->useSharedVertices = true; - - // the original code was missing this line: - mesh->_setBounds( AxisAlignedBox( Vector3(-SPHERE_RADIUS, -SPHERE_RADIUS, -SPHERE_RADIUS), - Vector3(SPHERE_RADIUS, SPHERE_RADIUS, SPHERE_RADIUS) ), false ); - - mesh->_setBoundingSphereRadius(SPHERE_RADIUS); - } - //----------------------------------------------------------------------- - static void tesselate2DMesh(SubMesh* sm, unsigned short meshWidth, unsigned short meshHeight, bool doubleSided, - HardwareBuffer::Usage indexBufferUsage, bool indexShadowBuffer) - { - // The mesh is built, just make a list of indexes to spit out the triangles - unsigned short vInc, v, iterations; - - if (doubleSided) - { - iterations = 2; - vInc = 1; - v = 0; // Start with front - } - else - { - iterations = 1; - vInc = 1; - v = 0; - } - - // Allocate memory for faces - // Num faces, width*height*2 (2 tris per square), index count is * 3 on top - sm->indexData->indexCount = (meshWidth-1) * (meshHeight-1) * 2 * iterations * 3; - sm->indexData->indexBuffer = HardwareBufferManager::getSingleton(). - createIndexBuffer(HardwareIndexBuffer::IT_16BIT, - sm->indexData->indexCount, indexBufferUsage, indexShadowBuffer); - - unsigned short v1, v2, v3; - //bool firstTri = true; - HardwareIndexBufferSharedPtr ibuf = sm->indexData->indexBuffer; - // Lock the whole buffer - HardwareBufferLockGuard ibufLock(ibuf, HardwareBuffer::HBL_DISCARD); - unsigned short* pIndexes = static_cast(ibufLock.pData); - - while (iterations--) - { - // Make tris in a zigzag pattern (compatible with strips) - unsigned short u = 0; - unsigned short uInc = 1; // Start with moving +u - unsigned short vCount = meshHeight - 1; - - while (vCount--) - { - unsigned short uCount = meshWidth - 1; - while (uCount--) - { - // First Tri in cell - // ----------------- - v1 = ((v + vInc) * meshWidth) + u; - v2 = (v * meshWidth) + u; - v3 = ((v + vInc) * meshWidth) + (u + uInc); - // Output indexes - *pIndexes++ = v1; - *pIndexes++ = v2; - *pIndexes++ = v3; - // Second Tri in cell - // ------------------ - v1 = ((v + vInc) * meshWidth) + (u + uInc); - v2 = (v * meshWidth) + u; - v3 = (v * meshWidth) + (u + uInc); - // Output indexes - *pIndexes++ = v1; - *pIndexes++ = v2; - *pIndexes++ = v3; - - // Next column - u += uInc; - } - // Next row - v += vInc; - u = 0; - - - } - - // Reverse vInc for double sided - v = meshHeight - 1; - vInc = -vInc; - - } - } - //----------------------------------------------------------------------- - void PrefabFactory::loadManualPlane(Mesh* pMesh, MeshBuildParams& params) - { - if ((params.xsegments + 1) * (params.ysegments + 1) > 65536) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Plane tessellation is too high, must generate max 65536 vertices"); - SubMesh *pSub = pMesh->createSubMesh(); - - // Set up vertex data - // Use a single shared buffer - pMesh->createVertexData(); - VertexData* vertexData = pMesh->sharedVertexData; - // Set up Vertex Declaration - VertexDeclaration* vertexDecl = vertexData->vertexDeclaration; - size_t currOffset = 0; - // We always need positions - currOffset += vertexDecl->addElement(0, currOffset, VET_FLOAT3, VES_POSITION).getSize(); - // Optional normals - if(params.normals) - { - currOffset += vertexDecl->addElement(0, currOffset, VET_FLOAT3, VES_NORMAL).getSize(); - } - - for (unsigned short i = 0; i < params.numTexCoordSets; ++i) - { - // Assumes 2D texture coords - currOffset += vertexDecl->addElement(0, currOffset, VET_FLOAT2, VES_TEXTURE_COORDINATES, i).getSize(); - } - - vertexData->vertexCount = (params.xsegments + 1) * (params.ysegments + 1); - - // Allocate vertex buffer - HardwareVertexBufferSharedPtr vbuf = - pMesh->getHardwareBufferManager()->createVertexBuffer( - vertexDecl->getVertexSize(0), vertexData->vertexCount, - params.vertexBufferUsage, params.vertexShadowBuffer); - - // Set up the binding (one source only) - VertexBufferBinding* binding = vertexData->vertexBufferBinding; - binding->setBinding(0, vbuf); - - // Work out the transform required - // Default orientation of plane is normal along +z, distance 0 - Affine3 xlate, xform, rot; - Matrix3 rot3; - xlate = rot = Affine3::IDENTITY; - // Determine axes - Vector3 zAxis, yAxis, xAxis; - zAxis = params.plane.normal; - zAxis.normalise(); - yAxis = params.upVector; - yAxis.normalise(); - xAxis = yAxis.crossProduct(zAxis); - if (xAxis.squaredLength() == 0) - { - //upVector must be wrong - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "The upVector you supplied is parallel to the plane normal, so is not valid."); - } - xAxis.normalise(); - - rot3.FromAxes(xAxis, yAxis, zAxis); - rot = rot3; - - // Set up standard transform from origin - xlate.setTrans(params.plane.normal * -params.plane.d); - - // concatenate - xform = xlate * rot; - - // Generate vertex data - // Lock the whole buffer - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - float* pReal = static_cast(vbufLock.pData); - Real xSpace = params.width / params.xsegments; - Real ySpace = params.height / params.ysegments; - Real halfWidth = params.width / 2; - Real halfHeight = params.height / 2; - Real xTex = (1.0f * params.xTile) / params.xsegments; - Real yTex = (1.0f * params.yTile) / params.ysegments; - Vector3 vec; - AxisAlignedBox aabb; - - for (int y = 0; y < params.ysegments + 1; ++y) - { - for (int x = 0; x < params.xsegments + 1; ++x) - { - // Work out centered on origin - vec.x = (x * xSpace) - halfWidth; - vec.y = (y * ySpace) - halfHeight; - vec.z = 0.0f; - // Transform by orientation and distance - vec = xform * vec; - // Assign to geometry - *pReal++ = vec.x; - *pReal++ = vec.y; - *pReal++ = vec.z; - - // Build bounds as we go - aabb.merge(vec); - - if (params.normals) - { - // Default normal is along unit Z - vec = Vector3::UNIT_Z; - // Rotate - vec = rot * vec; - - *pReal++ = vec.x; - *pReal++ = vec.y; - *pReal++ = vec.z; - } - - for (unsigned short i = 0; i < params.numTexCoordSets; ++i) - { - *pReal++ = x * xTex; - *pReal++ = 1 - (y * yTex); - } - - - } // x - } // y - - // Unlock - vbufLock.unlock(); - // Generate face list - pSub->useSharedVertices = true; - tesselate2DMesh(pSub, params.xsegments + 1, params.ysegments + 1, false, - params.indexBufferUsage, params.indexShadowBuffer); - - pMesh->_setBounds(aabb, true); - } - //----------------------------------------------------------------------- - void PrefabFactory::loadManualCurvedPlane(Mesh* pMesh, MeshBuildParams& params) - { - if ((params.xsegments + 1) * (params.ysegments + 1) > 65536) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Plane tessellation is too high, must generate max 65536 vertices"); - SubMesh *pSub = pMesh->createSubMesh(); - - // Set options - pMesh->createVertexData(); - pMesh->sharedVertexData->vertexStart = 0; - VertexBufferBinding* bind = pMesh->sharedVertexData->vertexBufferBinding; - VertexDeclaration* decl = pMesh->sharedVertexData->vertexDeclaration; - - pMesh->sharedVertexData->vertexCount = (params.xsegments + 1) * (params.ysegments + 1); - - size_t offset = 0; - offset += decl->addElement(0, offset, VET_FLOAT3, VES_POSITION).getSize(); - if (params.normals) - { - offset += decl->addElement(0, 0, VET_FLOAT3, VES_NORMAL).getSize(); - } - - for (unsigned short i = 0; i < params.numTexCoordSets; ++i) - { - offset += decl->addElement(0, offset, VET_FLOAT2, VES_TEXTURE_COORDINATES, i).getSize(); - } - - - // Allocate memory - HardwareVertexBufferSharedPtr vbuf = - pMesh->getHardwareBufferManager()->createVertexBuffer( - offset, pMesh->sharedVertexData->vertexCount, - params.vertexBufferUsage, params.vertexShadowBuffer); - bind->setBinding(0, vbuf); - - // Work out the transform required - // Default orientation of plane is normal along +z, distance 0 - Affine3 xlate, xform, rot; - Matrix3 rot3; - xlate = rot = Affine3::IDENTITY; - // Determine axes - Vector3 zAxis, yAxis, xAxis; - zAxis = params.plane.normal; - zAxis.normalise(); - yAxis = params.upVector; - yAxis.normalise(); - xAxis = yAxis.crossProduct(zAxis); - if (xAxis.squaredLength() == 0) - { - //upVector must be wrong - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "The upVector you supplied is parallel to the plane normal, so is not valid."); - } - xAxis.normalise(); - - rot3.FromAxes(xAxis, yAxis, zAxis); - rot = rot3; - - // Set up standard transform from origin - xlate.setTrans(params.plane.normal * -params.plane.d); - - // concatenate - xform = xlate * rot; - - // Generate vertex data - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - float* pFloat = static_cast(vbufLock.pData); - Real xSpace = params.width / params.xsegments; - Real ySpace = params.height / params.ysegments; - Real halfWidth = params.width / 2; - Real halfHeight = params.height / 2; - Real xTex = (1.0f * params.xTile) / params.xsegments; - Real yTex = (1.0f * params.yTile) / params.ysegments; - Vector3 vec; - - AxisAlignedBox aabb; - - Real diff_x, diff_y, dist; - - for (int y = 0; y < params.ysegments + 1; ++y) - { - for (int x = 0; x < params.xsegments + 1; ++x) - { - // Work out centered on origin - vec.x = (x * xSpace) - halfWidth; - vec.y = (y * ySpace) - halfHeight; - - // Here's where curved plane is different from standard plane. Amazing, I know. - diff_x = (x - ((params.xsegments) / 2)) / static_cast((params.xsegments)); - diff_y = (y - ((params.ysegments) / 2)) / static_cast((params.ysegments)); - dist = std::sqrt(diff_x*diff_x + diff_y * diff_y ); - vec.z = (-std::sin((1-dist) * (Math::PI/2)) * params.curvature) + params.curvature; - - // Transform by orientation and distance - Vector3 pos = xform * vec; - // Assign to geometry - *pFloat++ = pos.x; - *pFloat++ = pos.y; - *pFloat++ = pos.z; - - // Record bounds - aabb.merge(vec); - - if (params.normals) - { - // This part is kinda 'wrong' for curved planes... but curved planes are - // very valuable outside sky planes, which don't typically need normals - // so I'm not going to mess with it for now. - - // Default normal is along unit Z - //vec = Vector3::UNIT_Z; - // Rotate - vec = rot * vec; - vec.normalise(); - - *pFloat++ = vec.x; - *pFloat++ = vec.y; - *pFloat++ = vec.z; - } - - for (unsigned short i = 0; i < params.numTexCoordSets; ++i) - { - *pFloat++ = x * xTex; - *pFloat++ = 1 - (y * yTex); - } - - } // x - } // y - vbufLock.unlock(); - - // Generate face list - tesselate2DMesh(pSub, params.xsegments + 1, params.ysegments + 1, - false, params.indexBufferUsage, params.indexShadowBuffer); - - pMesh->_setBounds(aabb, true); - } - //----------------------------------------------------------------------- - void PrefabFactory::loadManualCurvedIllusionPlane(Mesh* pMesh, MeshBuildParams& params) - { - if (params.ySegmentsToKeep == -1) params.ySegmentsToKeep = params.ysegments; - - if ((params.xsegments + 1) * (params.ySegmentsToKeep + 1) > 65536) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Plane tessellation is too high, must generate max 65536 vertices"); - SubMesh *pSub = pMesh->createSubMesh(); - - - // Set up vertex data - // Use a single shared buffer - pMesh->createVertexData(); - VertexData* vertexData = pMesh->sharedVertexData; - // Set up Vertex Declaration - VertexDeclaration* vertexDecl = vertexData->vertexDeclaration; - size_t currOffset = 0; - // We always need positions - currOffset += vertexDecl->addElement(0, currOffset, VET_FLOAT3, VES_POSITION).getSize(); - // Optional normals - if(params.normals) - { - currOffset += vertexDecl->addElement(0, currOffset, VET_FLOAT3, VES_NORMAL).getSize(); - } - - for (unsigned short i = 0; i < params.numTexCoordSets; ++i) - { - // Assumes 2D texture coords - currOffset += vertexDecl->addElement(0, currOffset, VET_FLOAT2, VES_TEXTURE_COORDINATES, i).getSize(); - } - - vertexData->vertexCount = (params.xsegments + 1) * (params.ySegmentsToKeep + 1); - - // Allocate vertex buffer - HardwareVertexBufferSharedPtr vbuf = - pMesh->getHardwareBufferManager()->createVertexBuffer( - vertexDecl->getVertexSize(0), vertexData->vertexCount, - params.vertexBufferUsage, params.vertexShadowBuffer); - - // Set up the binding (one source only) - VertexBufferBinding* binding = vertexData->vertexBufferBinding; - binding->setBinding(0, vbuf); - - // Work out the transform required - // Default orientation of plane is normal along +z, distance 0 - Affine3 xlate, xform, rot; - Matrix3 rot3; - xlate = rot = Affine3::IDENTITY; - // Determine axes - Vector3 zAxis, yAxis, xAxis; - zAxis = params.plane.normal; - zAxis.normalise(); - yAxis = params.upVector; - yAxis.normalise(); - xAxis = yAxis.crossProduct(zAxis); - if (xAxis.squaredLength() == 0) - { - //upVector must be wrong - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "The upVector you supplied is parallel to the plane normal, so is not valid."); - } - xAxis.normalise(); - - rot3.FromAxes(xAxis, yAxis, zAxis); - rot = rot3; - - // Set up standard transform from origin - xlate.setTrans(params.plane.normal * -params.plane.d); - - // concatenate - xform = xlate * rot; - - // Generate vertex data - // Imagine a large sphere with the camera located near the top - // The lower the curvature, the larger the sphere - // Use the angle from viewer to the points on the plane - // Credit to Aftershock for the general approach - Real camPos; // Camera position relative to sphere center - - // Derive sphere radius - Vector3 vertPos; // position relative to camera - Real sphDist; // Distance from camera to sphere along box vertex vector - // Vector3 camToSph; // camera position to sphere - Real sphereRadius;// Sphere radius - // Actual values irrelevant, it's the relation between sphere radius and camera position that's important - const Real SPHERE_RAD = 100.0; - const Real CAM_DIST = 5.0; - - sphereRadius = SPHERE_RAD - params.curvature; - camPos = sphereRadius - CAM_DIST; - - // Lock the whole buffer - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - float* pFloat = static_cast(vbufLock.pData); - Real xSpace = params.width / params.xsegments; - Real ySpace = params.height / params.ysegments; - Real halfWidth = params.width / 2; - Real halfHeight = params.height / 2; - Vector3 vec, norm; - AxisAlignedBox aabb; - - for (int y = params.ysegments - params.ySegmentsToKeep; y < params.ysegments + 1; ++y) - { - for (int x = 0; x < params.xsegments + 1; ++x) - { - // Work out centered on origin - vec.x = (x * xSpace) - halfWidth; - vec.y = (y * ySpace) - halfHeight; - vec.z = 0.0f; - // Transform by orientation and distance - vec = xform * vec; - // Assign to geometry - *pFloat++ = vec.x; - *pFloat++ = vec.y; - *pFloat++ = vec.z; - - // Build bounds as we go - aabb.merge(vec); - - if (params.normals) - { - // Default normal is along unit Z - norm = Vector3::UNIT_Z; - // Rotate - norm = params.orientation * norm; - - *pFloat++ = norm.x; - *pFloat++ = norm.y; - *pFloat++ = norm.z; - } - - // Generate texture coords - // Normalise position - // modify by orientation to return +y up - vec = params.orientation.Inverse() * vec; - vec.normalise(); - // Find distance to sphere - sphDist = Math::Sqrt(camPos*camPos * (vec.y*vec.y-1.0f) + sphereRadius*sphereRadius) - camPos*vec.y; - - vec.x *= sphDist; - vec.z *= sphDist; - - // Use x and y on sphere as texture coordinates, tiled - Real s = vec.x * (0.01f * params.xTile); - Real t = 1.0f - (vec.z * (0.01f * params.yTile)); - for (unsigned short i = 0; i < params.numTexCoordSets; ++i) - { - *pFloat++ = s; - *pFloat++ = t; - } - - - } // x - } // y - - // Unlock - vbufLock.unlock(); - // Generate face list - pSub->useSharedVertices = true; - tesselate2DMesh(pSub, params.xsegments + 1, params.ySegmentsToKeep + 1, false, - params.indexBufferUsage, params.indexShadowBuffer); - - pMesh->_setBounds(aabb, true); - } -} diff --git a/OgreMain/src/OgrePrefabFactory.h b/OgreMain/src/OgrePrefabFactory.h deleted file mode 100644 index 6ba3f887626..00000000000 --- a/OgreMain/src/OgrePrefabFactory.h +++ /dev/null @@ -1,111 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __PrefabFactory_H__ -#define __PrefabFactory_H__ - -#include "OgrePrerequisites.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - - /** Enum identifying the types of manual mesh built by this manager */ - enum MeshBuildType - { - MBT_PLANE, - MBT_CURVED_ILLUSION_PLANE, - MBT_CURVED_PLANE - }; - - /** Saved parameters used to (re)build a manual mesh built by this class */ - struct MeshBuildParams - { - MeshBuildType type; - Plane plane; - Real width; - Real height; - Real curvature; - int xsegments; - int ysegments; - bool normals; - unsigned short numTexCoordSets; - Real xTile; - Real yTile; - Vector3 upVector; - Quaternion orientation; - HardwareBuffer::Usage vertexBufferUsage; - HardwareBuffer::Usage indexBufferUsage; - bool vertexShadowBuffer; - bool indexShadowBuffer; - int ySegmentsToKeep; - }; - - /** A factory class that can create various mesh prefabs. - - This class is used by OgreMeshManager to offload the loading of various prefab types - to a central location. - */ - class PrefabFactory : public ManualResourceLoader - { - public: - /** If the given mesh has a UserObjectBinding for _MeshBuildParams or resource name (e.g "Prefab_Plane") - then this prefab will be created as a submesh of the given mesh. - - @param res The mesh that the potential prefab will be created in. - */ - void loadResource(Resource* res) override; - - private: - /// Creates a plane as a submesh of the given mesh - static void createPlane(Mesh* mesh); - - /// Creates a 100x100x100 cube as a submesh of the given mesh - static void createCube(Mesh* mesh); - - /// Creates a sphere with a diameter of 100 units as a submesh of the given mesh - static void createSphere(Mesh* mesh); - - /** Utility method for manual loading a plane */ - static void loadManualPlane(Mesh* pMesh, MeshBuildParams& params); - /** Utility method for manual loading a curved plane */ - static void loadManualCurvedPlane(Mesh* pMesh, MeshBuildParams& params); - /** Utility method for manual loading a curved illusion plane */ - static void loadManualCurvedIllusionPlane(Mesh* pMesh, MeshBuildParams& params); - }; - /** @} */ - /** @} */ - -} // namespace Ogre - -#endif diff --git a/OgreMain/src/OgreProfiler.cpp b/OgreMain/src/OgreProfiler.cpp deleted file mode 100644 index bc12ed9078b..00000000000 --- a/OgreMain/src/OgreProfiler.cpp +++ /dev/null @@ -1,605 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -/* - - Although the code is original, many of the ideas for the profiler were borrowed from -"Real-Time In-Game Profiling" by Steve Rabin which can be found in Game Programming -Gems 1. - - This code can easily be adapted to your own non-Ogre project. The only code that is -Ogre-dependent is in the visualization/logging routines and the use of the Timer class. - - Enjoy! - -*/ - -#include "OgreTimer.h" - -#ifdef USE_REMOTERY -#include "Remotery.h" -static Remotery* rmt; -#endif - -namespace Ogre { - //----------------------------------------------------------------------- - // PROFILE DEFINITIONS - //----------------------------------------------------------------------- - template<> Profiler* Singleton::msSingleton = 0; - Profiler* Profiler::getSingletonPtr(void) - { - return msSingleton; - } - Profiler& Profiler::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - - //----------------------------------------------------------------------- - // PROFILER DEFINITIONS - //----------------------------------------------------------------------- - Profiler::Profiler() - : mCurrent(&mRoot) - , mLast(NULL) - , mRoot() - , mInitialized(false) - , mUpdateDisplayFrequency(10) - , mCurrentFrame(0) - , mTimer(0) - , mTotalFrameTime(0) - , mEnabled(false) - , mNewEnableState(false) - , mProfileMask(0xFFFFFFFF) - , mMaxTotalFrameTime(0) - , mAverageFrameTime(0) - , mResetExtents(false) - { - mRoot.hierarchicalLvl = 0 - 1; - -#ifdef USE_REMOTERY - rmt_Settings()->reuse_open_port = true; - if(auto error = rmt_CreateGlobalInstance(&rmt)) - { - LogManager::getSingleton().logError("Could not launch Remotery - RMT_ERROR " + std::to_string(error)); - return; - } - rmt_SetCurrentThreadName("Ogre Main"); -#endif - } - //----------------------------------------------------------------------- - ProfileInstance::ProfileInstance(void) - : parent(NULL) - , frameNumber(0) - , accum(0) - , hierarchicalLvl(0) - { - history.numCallsThisFrame = 0; - history.totalTimePercent = 0; - history.totalTimeMillisecs = 0; - history.totalCalls = 0; - history.maxTimePercent = 0; - history.maxTimeMillisecs = 0; - history.minTimePercent = 1; - history.minTimeMillisecs = 100000; - history.currentTimePercent = 0; - history.currentTimeMillisecs = 0; - - frame.frameTime = 0; - frame.calls = 0; - } - ProfileInstance::~ProfileInstance(void) - { - for(auto & it : children) - { - ProfileInstance* instance = it.second; - OGRE_DELETE instance; - } - children.clear(); - } - //----------------------------------------------------------------------- - Profiler::~Profiler() - { -#ifdef USE_REMOTERY - rmt_DestroyGlobalInstance(rmt); -#else - if (!mRoot.children.empty()) - { - // log the results of our profiling before we quit - logResults(); - } - - // clear all our lists - mDisabledProfiles.clear(); -#endif - } - //----------------------------------------------------------------------- - void Profiler::setTimer(Timer* t) - { - mTimer = t; - } - //----------------------------------------------------------------------- - Timer* Profiler::getTimer() - { - assert(mTimer && "Timer not set!"); - return mTimer; - } - //----------------------------------------------------------------------- - void Profiler::setEnabled(bool enabled) - { - if (!mInitialized && enabled) - { - for(auto & l : mListeners) - l->initializeSession(); - - mInitialized = true; - } - else if (mInitialized) - { - for(auto & l : mListeners) - l->finializeSession(); - - mInitialized = false; - mEnabled = false; - } - // We store this enable/disable request until the frame ends - // (don't want to screw up any open profiles!) - mNewEnableState = enabled; - } - //----------------------------------------------------------------------- - bool Profiler::getEnabled() const - { - return mEnabled; - } - //----------------------------------------------------------------------- - void Profiler::changeEnableState() - { - for(auto & l : mListeners) - l->changeEnableState(mNewEnableState); - - mEnabled = mNewEnableState; - } - //----------------------------------------------------------------------- - void Profiler::disableProfile(const String& profileName) - { - // even if we are in the middle of this profile, endProfile() will still end it. - mDisabledProfiles.insert(profileName); - } - //----------------------------------------------------------------------- - void Profiler::enableProfile(const String& profileName) - { - mDisabledProfiles.erase(profileName); - } - //----------------------------------------------------------------------- - void Profiler::beginProfile(const String& profileName, uint32 groupID) - { -#ifdef USE_REMOTERY - // mask groups - if ((groupID & mProfileMask) == 0) - return; - - rmt_BeginCPUSampleDynamic(profileName.c_str(), RMTSF_Aggregate); -#else - // if the profiler is enabled - if (!mEnabled) - return; - - // mask groups - if ((groupID & mProfileMask) == 0) - return; - - // empty string is reserved for the root - // not really fatal anymore, however one shouldn't name one's profile as an empty string anyway. - assert ((profileName != "") && ("Profile name can't be an empty string")); - - // we only process this profile if isn't disabled - if (mDisabledProfiles.find(profileName) != mDisabledProfiles.end()) - return; - - // regardless of whether or not we are enabled, we need the application's root profile (ie the first profile started each frame) - // we need this so bogus profiles don't show up when users enable profiling mid frame - // so we check - - // this would be an internal error. - assert (mCurrent); - - // need a timer to profile! - assert (mTimer && "Timer not set!"); - - ProfileInstance*& instance = mCurrent->children[profileName]; - if(instance) - { // found existing child. - - // Sanity check. - assert(instance->name == profileName); - - if(instance->frameNumber != mCurrentFrame) - { // new frame, reset stats - instance->frame.calls = 0; - instance->frame.frameTime = 0; - instance->frameNumber = mCurrentFrame; - } - } - else - { // new child! - instance = OGRE_NEW ProfileInstance(); - instance->name = profileName; - instance->parent = mCurrent; - instance->hierarchicalLvl = mCurrent->hierarchicalLvl + 1; - } - - instance->frameNumber = mCurrentFrame; - - mCurrent = instance; - - // we do this at the very end of the function to get the most - // accurate timing results - mCurrent->currTime = mTimer->getMicroseconds(); -#endif - } - //----------------------------------------------------------------------- - void Profiler::endProfile(const String& profileName, uint32 groupID) - { -#ifdef USE_REMOTERY - // mask groups - if ((groupID & mProfileMask) == 0) - return; - - rmt_EndCPUSample(); -#else - if(!mEnabled) - { - // if the profiler received a request to be enabled or disabled - if(mNewEnableState != mEnabled) - { // note mNewEnableState == true to reach this. - changeEnableState(); - - // NOTE we will be in an 'error' state until the next begin. ie endProfile will likely get invoked using a profileName that was never started. - // even then, we can't be sure that the next beginProfile will be the true start of a new frame - } - - return; - } - else - { - if(mNewEnableState != mEnabled) - { // note mNewEnableState == false to reach this. - changeEnableState(); - - // unwind the hierarchy, should be easy enough - mCurrent = &mRoot; - mLast = NULL; - } - - if(&mRoot == mCurrent && mLast) - { // profiler was enabled this frame, but the first subsequent beginProfile was NOT the beinging of a new frame as we had hoped. - // we have bogus ProfileInstance in our hierarchy, we will need to remove it, then update the overlays so as not to confuse ze user - - for(auto& e : mRoot.children) - { - OGRE_DELETE e.second; - } - mRoot.children.clear(); - - mLast = NULL; - - processFrameStats(); - displayResults(); - } - } - - if(&mRoot == mCurrent) - return; - - // mask groups - if ((groupID & mProfileMask) == 0) - return; - - // need a timer to profile! - assert (mTimer && "Timer not set!"); - - // get the end time of this profile - // we do this as close the beginning of this function as possible - // to get more accurate timing results - const ulong endTime = mTimer->getMicroseconds(); - - // empty string is reserved for designating an empty parent - assert ((profileName != "") && ("Profile name can't be an empty string")); - - // we only process this profile if isn't disabled - // we check the current instance name against the provided profileName as a guard against disabling a profile name /after/ said profile began - if(mCurrent->name != profileName && mDisabledProfiles.find(profileName) != mDisabledProfiles.end()) - return; - - // calculate the elapsed time of this profile - const ulong timeElapsed = endTime - mCurrent->currTime; - - // update parent's accumulator if it isn't the root - if (&mRoot != mCurrent->parent) - { - // add this profile's time to the parent's accumlator - mCurrent->parent->accum += timeElapsed; - } - - mCurrent->frame.frameTime += timeElapsed; - ++mCurrent->frame.calls; - - mLast = mCurrent; - mCurrent = mCurrent->parent; - - if (&mRoot == mCurrent) - { - // the stack is empty and all the profiles have been completed - // we have reached the end of the frame so process the frame statistics - - // we know that the time elapsed of the main loop is the total time the frame took - mTotalFrameTime = timeElapsed; - - if(timeElapsed > mMaxTotalFrameTime) - mMaxTotalFrameTime = timeElapsed; - - // we got all the information we need, so process the profiles - // for this frame - processFrameStats(); - - // we display everything to the screen - displayResults(); - } -#endif - } - //----------------------------------------------------------------------- - void Profiler::processFrameStats(ProfileInstance* instance, Real& maxFrameTime) - { - // calculate what percentage of frame time this profile took - const Real framePercentage = (Real) instance->frame.frameTime / (Real) mTotalFrameTime; - - const Real frameTimeMillisecs = (Real) instance->frame.frameTime / 1000.0f; - - // update the profile stats - instance->history.currentTimePercent = framePercentage; - instance->history.currentTimeMillisecs = frameTimeMillisecs; - if(mResetExtents) - { - instance->history.totalTimePercent = framePercentage; - instance->history.totalTimeMillisecs = frameTimeMillisecs; - instance->history.totalCalls = 1; - } - else - { - instance->history.totalTimePercent += framePercentage; - instance->history.totalTimeMillisecs += frameTimeMillisecs; - instance->history.totalCalls++; - } - instance->history.numCallsThisFrame = instance->frame.calls; - - // if we find a new minimum for this profile, update it - if (frameTimeMillisecs < instance->history.minTimeMillisecs || mResetExtents) - { - instance->history.minTimePercent = framePercentage; - instance->history.minTimeMillisecs = frameTimeMillisecs; - } - - // if we find a new maximum for this profile, update it - if (frameTimeMillisecs > instance->history.maxTimeMillisecs || mResetExtents) - { - instance->history.maxTimePercent = framePercentage; - instance->history.maxTimeMillisecs = frameTimeMillisecs; - } - - if (instance->frame.frameTime > maxFrameTime) - maxFrameTime = (Real)instance->frame.frameTime; - - for (auto& i : instance->children) - { - ProfileInstance* child = i.second; - - // we set the number of times each profile was called per frame to 0 - // because not all profiles are called every frame - child->history.numCallsThisFrame = 0; - - if(child->frame.calls > 0) - { - processFrameStats(child, maxFrameTime); - } - } - } - //----------------------------------------------------------------------- - void Profiler::processFrameStats(void) - { - Real maxFrameTime = 0; - - for (auto& i : mRoot.children) - { - ProfileInstance* child = i.second; - - // we set the number of times each profile was called per frame to 0 - // because not all profiles are called every frame - child->history.numCallsThisFrame = 0; - - if(child->frame.calls > 0) - { - processFrameStats(child, maxFrameTime); - } - } - - // Calculate whether the extents are now so out of date they need regenerating - if (mCurrentFrame == 0) - mAverageFrameTime = maxFrameTime; - else - mAverageFrameTime = (mAverageFrameTime + maxFrameTime) * 0.5f; - - if ((Real)mMaxTotalFrameTime > mAverageFrameTime * 4) - { - mResetExtents = true; - mMaxTotalFrameTime = (ulong)mAverageFrameTime; - } - else - mResetExtents = false; - } - //----------------------------------------------------------------------- - void Profiler::displayResults() - { - // if its time to update the display - if (!(mCurrentFrame % mUpdateDisplayFrequency)) - { - // ensure the root won't be culled - mRoot.frame.calls = 1; - - for(auto& l : mListeners) - l->displayResults(mRoot, mMaxTotalFrameTime); - } - ++mCurrentFrame; - } - //----------------------------------------------------------------------- - bool Profiler::watchForMax(const String& profileName) - { - assert ((profileName != "") && ("Profile name can't be an empty string")); - - return mRoot.watchForMax(profileName); - } - //----------------------------------------------------------------------- - bool ProfileInstance::watchForMax(const String& profileName) - { - for(auto& i : children) - { - ProfileInstance* child = i.second; - if( (child->name == profileName && child->watchForMax()) || child->watchForMax(profileName)) - return true; - } - return false; - } - //----------------------------------------------------------------------- - bool Profiler::watchForMin(const String& profileName) - { - assert ((profileName != "") && ("Profile name can't be an empty string")); - return mRoot.watchForMin(profileName); - } - //----------------------------------------------------------------------- - bool ProfileInstance::watchForMin(const String& profileName) - { - for(auto& i : children) - { - ProfileInstance* child = i.second; - if( (child->name == profileName && child->watchForMin()) || child->watchForMin(profileName)) - return true; - } - return false; - } - //----------------------------------------------------------------------- - bool Profiler::watchForLimit(const String& profileName, Real limit, bool greaterThan) - { - assert ((profileName != "") && ("Profile name can't be an empty string")); - return mRoot.watchForLimit(profileName, limit, greaterThan); - } - //----------------------------------------------------------------------- - bool ProfileInstance::watchForLimit(const String& profileName, Real limit, bool greaterThan) - { - for(auto& i : children) - { - ProfileInstance* child = i.second; - if( (child->name == profileName && child->watchForLimit(limit, greaterThan)) || child->watchForLimit(profileName, limit, greaterThan)) - return true; - } - return false; - } - //----------------------------------------------------------------------- - void Profiler::logResults() - { - LogManager::getSingleton().logMessage("----------------------Profiler Results----------------------"); - - for(auto& it : mRoot.children) - { - it.second->logResults(); - } - - LogManager::getSingleton().logMessage("------------------------------------------------------------"); - } - //----------------------------------------------------------------------- - void ProfileInstance::logResults() - { - // create an indent that represents the hierarchical order of the profile - String indent = ""; - for (uint i = 0; i < hierarchicalLvl; ++i) - { - indent = indent + "\t"; - } - - LogManager::getSingleton().logMessage(indent + "Name " + name + - " | Min " + StringConverter::toString(history.minTimePercent) + - " | Max " + StringConverter::toString(history.maxTimePercent) + - " | Avg "+ StringConverter::toString(history.totalTimePercent / history.totalCalls)); - - for(auto& it : children) - { - it.second->logResults(); - } - } - //----------------------------------------------------------------------- - void Profiler::reset() - { - mRoot.reset(); - mMaxTotalFrameTime = 0; - } - //----------------------------------------------------------------------- - void ProfileInstance::reset(void) - { - history.currentTimePercent = history.maxTimePercent = history.totalTimePercent = 0; - history.currentTimeMillisecs = history.maxTimeMillisecs = history.totalTimeMillisecs = 0; - history.numCallsThisFrame = history.totalCalls = 0; - - history.minTimePercent = 1; - history.minTimeMillisecs = 100000; - for(auto& it : children) - { - it.second->reset(); - } - } - //----------------------------------------------------------------------- - void Profiler::setUpdateDisplayFrequency(uint freq) - { - mUpdateDisplayFrequency = freq; - } - //----------------------------------------------------------------------- - uint Profiler::getUpdateDisplayFrequency() const - { - return mUpdateDisplayFrequency; - } - //----------------------------------------------------------------------- - void Profiler::addListener(ProfileSessionListener* listener) - { - if (std::find(mListeners.begin(), mListeners.end(), listener) == mListeners.end()) - mListeners.push_back(listener); - } - //----------------------------------------------------------------------- - void Profiler::removeListener(ProfileSessionListener* listener) - { - TProfileSessionListener::iterator i = std::find(mListeners.begin(), mListeners.end(), listener); - if (i != mListeners.end()) - mListeners.erase(i); - } - //----------------------------------------------------------------------- -} diff --git a/OgreMain/src/OgreQuaternion.cpp b/OgreMain/src/OgreQuaternion.cpp deleted file mode 100644 index 9682ab66733..00000000000 --- a/OgreMain/src/OgreQuaternion.cpp +++ /dev/null @@ -1,550 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -// NOTE THAT THIS FILE IS BASED ON MATERIAL FROM: - -// Geometric Tools, LLC -// Copyright (c) 1998-2010 -// Distributed under the Boost Software License, Version 1.0. -// http://www.boost.org/LICENSE_1_0.txt -// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt - -namespace Ogre { - - const Real Quaternion::msEpsilon = 1e-03; - const Quaternion Quaternion::ZERO(0,0,0,0); - const Quaternion Quaternion::IDENTITY(1,0,0,0); - - //----------------------------------------------------------------------- - void Quaternion::FromRotationMatrix (const Matrix3& kRot) - { - // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes - // article "Quaternion Calculus and Fast Animation". - - Real fTrace = kRot[0][0]+kRot[1][1]+kRot[2][2]; - Real fRoot; - - if ( fTrace > 0.0 ) - { - // |w| > 1/2, may as well choose w > 1/2 - fRoot = Math::Sqrt(fTrace + 1.0f); // 2w - w = 0.5f*fRoot; - fRoot = 0.5f/fRoot; // 1/(4w) - x = (kRot[2][1]-kRot[1][2])*fRoot; - y = (kRot[0][2]-kRot[2][0])*fRoot; - z = (kRot[1][0]-kRot[0][1])*fRoot; - } - else - { - // |w| <= 1/2 - static size_t s_iNext[3] = { 1, 2, 0 }; - size_t i = 0; - if ( kRot[1][1] > kRot[0][0] ) - i = 1; - if ( kRot[2][2] > kRot[i][i] ) - i = 2; - size_t j = s_iNext[i]; - size_t k = s_iNext[j]; - - fRoot = Math::Sqrt(kRot[i][i]-kRot[j][j]-kRot[k][k] + 1.0f); - Real* apkQuat[3] = { &x, &y, &z }; - *apkQuat[i] = 0.5f*fRoot; - fRoot = 0.5f/fRoot; - w = (kRot[k][j]-kRot[j][k])*fRoot; - *apkQuat[j] = (kRot[j][i]+kRot[i][j])*fRoot; - *apkQuat[k] = (kRot[k][i]+kRot[i][k])*fRoot; - } - } - //----------------------------------------------------------------------- - void Quaternion::ToRotationMatrix (Matrix3& kRot) const - { - Real fTx = x+x; - Real fTy = y+y; - Real fTz = z+z; - Real fTwx = fTx*w; - Real fTwy = fTy*w; - Real fTwz = fTz*w; - Real fTxx = fTx*x; - Real fTxy = fTy*x; - Real fTxz = fTz*x; - Real fTyy = fTy*y; - Real fTyz = fTz*y; - Real fTzz = fTz*z; - - kRot[0][0] = 1.0f-(fTyy+fTzz); - kRot[0][1] = fTxy-fTwz; - kRot[0][2] = fTxz+fTwy; - kRot[1][0] = fTxy+fTwz; - kRot[1][1] = 1.0f-(fTxx+fTzz); - kRot[1][2] = fTyz-fTwx; - kRot[2][0] = fTxz-fTwy; - kRot[2][1] = fTyz+fTwx; - kRot[2][2] = 1.0f-(fTxx+fTyy); - } - //----------------------------------------------------------------------- - void Quaternion::FromAngleAxis (const Radian& rfAngle, - const Vector3& rkAxis) - { - // assert: axis[] is unit length - // - // The quaternion representing the rotation is - // q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k) - - Radian fHalfAngle ( 0.5*rfAngle ); - Real fSin = Math::Sin(fHalfAngle); - w = Math::Cos(fHalfAngle); - x = fSin*rkAxis.x; - y = fSin*rkAxis.y; - z = fSin*rkAxis.z; - } - //----------------------------------------------------------------------- - void Quaternion::ToAngleAxis (Radian& rfAngle, Vector3& rkAxis) const - { - // The quaternion representing the rotation is - // q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k) - - Real fSqrLength = x*x+y*y+z*z; - if ( fSqrLength > 0.0 ) - { - rfAngle = 2.0*Math::ACos(w); - Real fInvLength = Math::InvSqrt(fSqrLength); - rkAxis.x = x*fInvLength; - rkAxis.y = y*fInvLength; - rkAxis.z = z*fInvLength; - } - else - { - // angle is 0 (mod 2*pi), so any axis will do - rfAngle = Radian(0.0); - rkAxis.x = 1.0; - rkAxis.y = 0.0; - rkAxis.z = 0.0; - } - } - //----------------------------------------------------------------------- - void Quaternion::FromAxes (const Vector3* akAxis) - { - Matrix3 kRot; - - for (size_t iCol = 0; iCol < 3; iCol++) - { - kRot[0][iCol] = akAxis[iCol].x; - kRot[1][iCol] = akAxis[iCol].y; - kRot[2][iCol] = akAxis[iCol].z; - } - - FromRotationMatrix(kRot); - } - //----------------------------------------------------------------------- - void Quaternion::FromAxes (const Vector3& xaxis, const Vector3& yaxis, const Vector3& zaxis) - { - Matrix3 kRot; - kRot.FromAxes(xaxis, yaxis, zaxis); - FromRotationMatrix(kRot); - } - //----------------------------------------------------------------------- - void Quaternion::ToAxes (Vector3* akAxis) const - { - Matrix3 kRot; - - ToRotationMatrix(kRot); - - for (size_t iCol = 0; iCol < 3; iCol++) - { - akAxis[iCol].x = kRot[0][iCol]; - akAxis[iCol].y = kRot[1][iCol]; - akAxis[iCol].z = kRot[2][iCol]; - } - } - //----------------------------------------------------------------------- - Vector3 Quaternion::xAxis(void) const - { - //Real fTx = 2.0*x; - Real fTy = 2.0f*y; - Real fTz = 2.0f*z; - Real fTwy = fTy*w; - Real fTwz = fTz*w; - Real fTxy = fTy*x; - Real fTxz = fTz*x; - Real fTyy = fTy*y; - Real fTzz = fTz*z; - - return Vector3(1.0f-(fTyy+fTzz), fTxy+fTwz, fTxz-fTwy); - } - //----------------------------------------------------------------------- - Vector3 Quaternion::yAxis(void) const - { - Real fTx = 2.0f*x; - Real fTy = 2.0f*y; - Real fTz = 2.0f*z; - Real fTwx = fTx*w; - Real fTwz = fTz*w; - Real fTxx = fTx*x; - Real fTxy = fTy*x; - Real fTyz = fTz*y; - Real fTzz = fTz*z; - - return Vector3(fTxy-fTwz, 1.0f-(fTxx+fTzz), fTyz+fTwx); - } - //----------------------------------------------------------------------- - Vector3 Quaternion::zAxis(void) const - { - Real fTx = 2.0f*x; - Real fTy = 2.0f*y; - Real fTz = 2.0f*z; - Real fTwx = fTx*w; - Real fTwy = fTy*w; - Real fTxx = fTx*x; - Real fTxz = fTz*x; - Real fTyy = fTy*y; - Real fTyz = fTz*y; - - return Vector3(fTxz+fTwy, fTyz-fTwx, 1.0f-(fTxx+fTyy)); - } - //----------------------------------------------------------------------- - void Quaternion::ToAxes (Vector3& xaxis, Vector3& yaxis, Vector3& zaxis) const - { - Matrix3 kRot; - - ToRotationMatrix(kRot); - - xaxis.x = kRot[0][0]; - xaxis.y = kRot[1][0]; - xaxis.z = kRot[2][0]; - - yaxis.x = kRot[0][1]; - yaxis.y = kRot[1][1]; - yaxis.z = kRot[2][1]; - - zaxis.x = kRot[0][2]; - zaxis.y = kRot[1][2]; - zaxis.z = kRot[2][2]; - } - - //----------------------------------------------------------------------- - Quaternion Quaternion::operator+ (const Quaternion& rkQ) const - { - return Quaternion(w+rkQ.w,x+rkQ.x,y+rkQ.y,z+rkQ.z); - } - //----------------------------------------------------------------------- - Quaternion Quaternion::operator- (const Quaternion& rkQ) const - { - return Quaternion(w-rkQ.w,x-rkQ.x,y-rkQ.y,z-rkQ.z); - } - //----------------------------------------------------------------------- - Quaternion Quaternion::operator* (const Quaternion& rkQ) const - { - // NOTE: Multiplication is not generally commutative, so in most - // cases p*q != q*p. - - return Quaternion - ( - w * rkQ.w - x * rkQ.x - y * rkQ.y - z * rkQ.z, - w * rkQ.x + x * rkQ.w + y * rkQ.z - z * rkQ.y, - w * rkQ.y + y * rkQ.w + z * rkQ.x - x * rkQ.z, - w * rkQ.z + z * rkQ.w + x * rkQ.y - y * rkQ.x - ); - } - //----------------------------------------------------------------------- - Quaternion Quaternion::Inverse () const - { - Real fNorm = w*w+x*x+y*y+z*z; - if ( fNorm > 0.0 ) - { - Real fInvNorm = 1.0f/fNorm; - return Quaternion(w*fInvNorm,-x*fInvNorm,-y*fInvNorm,-z*fInvNorm); - } - else - { - // return an invalid result to flag the error - return ZERO; - } - } - //----------------------------------------------------------------------- - Quaternion Quaternion::UnitInverse () const - { - // assert: 'this' is unit length - return Quaternion(w,-x,-y,-z); - } - //----------------------------------------------------------------------- - Quaternion Quaternion::Exp () const - { - // If q = A*(x*i+y*j+z*k) where (x,y,z) is unit length, then - // exp(q) = e^w(cos(A)+sin(A)*(x*i+y*j+z*k)). If sin(A) is near zero, - // use exp(q) = e^w(cos(A)+(x*i+y*j+z*k)) since sin(A)/A has limit 1. - - Radian fAngle ( Math::Sqrt(x*x+y*y+z*z) ); - Real fSin = Math::Sin(fAngle); - Real fExpW = Math::Exp(w); - - Quaternion kResult; - kResult.w = fExpW*Math::Cos(fAngle); - - if ( Math::Abs(fAngle.valueRadians()) >= msEpsilon ) - { - Real fCoeff = fExpW*(fSin/(fAngle.valueRadians())); - kResult.x = fCoeff*x; - kResult.y = fCoeff*y; - kResult.z = fCoeff*z; - } - else - { - kResult.x = fExpW*x; - kResult.y = fExpW*y; - kResult.z = fExpW*z; - } - - return kResult; - } - //----------------------------------------------------------------------- - Quaternion Quaternion::Log () const - { - // If q = cos(A)+sin(A)*(x*i+y*j+z*k) where (x,y,z) is unit length, then - // log(q) = (A/sin(A))*(x*i+y*j+z*k). If sin(A) is near zero, use - // log(q) = (x*i+y*j+z*k) since A/sin(A) has limit 1. - - Quaternion kResult; - kResult.w = 0.0; - - if ( Math::Abs(w) < 1.0 ) - { - // According to Neil Dantam, atan2 has the best stability. - // http://www.neil.dantam.name/note/dantam-quaternion.pdf - Real fNormV = Math::Sqrt(x*x + y*y + z*z); - Radian fAngle ( Math::ATan2(fNormV, w) ); - - Real fSin = Math::Sin(fAngle); - if ( Math::Abs(fSin) >= msEpsilon ) - { - Real fCoeff = fAngle.valueRadians()/fSin; - kResult.x = fCoeff*x; - kResult.y = fCoeff*y; - kResult.z = fCoeff*z; - return kResult; - } - } - - kResult.x = x; - kResult.y = y; - kResult.z = z; - - return kResult; - } - //----------------------------------------------------------------------- - Vector3 Quaternion::operator* (const Vector3& v) const - { - // nVidia SDK implementation - Vector3 uv, uuv; - Vector3 qvec(x, y, z); - uv = qvec.crossProduct(v); - uuv = qvec.crossProduct(uv); - uv *= (2.0f * w); - uuv *= 2.0f; - - return v + uv + uuv; - - } - //----------------------------------------------------------------------- - Quaternion Quaternion::Slerp (Real fT, const Quaternion& rkP, - const Quaternion& rkQ, bool shortestPath) - { - Real fCos = rkP.Dot(rkQ); - Quaternion rkT; - - // Do we need to invert rotation? - if (fCos < 0.0f && shortestPath) - { - fCos = -fCos; - rkT = -rkQ; - } - else - { - rkT = rkQ; - } - - if (Math::Abs(fCos) < 1 - msEpsilon) - { - // Standard case (slerp) - Real fSin = Math::Sqrt(1 - Math::Sqr(fCos)); - Radian fAngle = Math::ATan2(fSin, fCos); - Real fInvSin = 1.0f / fSin; - Real fCoeff0 = Math::Sin((1.0f - fT) * fAngle) * fInvSin; - Real fCoeff1 = Math::Sin(fT * fAngle) * fInvSin; - return fCoeff0 * rkP + fCoeff1 * rkT; - } - else - { - // There are two situations: - // 1. "rkP" and "rkQ" are very close (fCos ~= +1), so we can do a linear - // interpolation safely. - // 2. "rkP" and "rkQ" are almost inverse of each other (fCos ~= -1), there - // are an infinite number of possibilities interpolation. but we haven't - // have method to fix this case, so just use linear interpolation here. - Quaternion t = (1.0f - fT) * rkP + fT * rkT; - // taking the complement requires renormalisation - t.normalise(); - return t; - } - } - //----------------------------------------------------------------------- - Quaternion Quaternion::SlerpExtraSpins (Real fT, - const Quaternion& rkP, const Quaternion& rkQ, int iExtraSpins) - { - Real fCos = rkP.Dot(rkQ); - Radian fAngle ( Math::ACos(fCos) ); - - if ( Math::Abs(fAngle.valueRadians()) < msEpsilon ) - return rkP; - - Real fSin = Math::Sin(fAngle); - Radian fPhase ( Math::PI*iExtraSpins*fT ); - Real fInvSin = 1.0f/fSin; - Real fCoeff0 = Math::Sin((1.0f-fT)*fAngle - fPhase)*fInvSin; - Real fCoeff1 = Math::Sin(fT*fAngle + fPhase)*fInvSin; - return fCoeff0*rkP + fCoeff1*rkQ; - } - //----------------------------------------------------------------------- - void Quaternion::Intermediate (const Quaternion& rkQ0, - const Quaternion& rkQ1, const Quaternion& rkQ2, - Quaternion& rkA, Quaternion& rkB) - { - // assert: q0, q1, q2 are unit quaternions - - Quaternion kQ0inv = rkQ0.UnitInverse(); - Quaternion kQ1inv = rkQ1.UnitInverse(); - Quaternion rkP0 = kQ0inv*rkQ1; - Quaternion rkP1 = kQ1inv*rkQ2; - Quaternion kArg = 0.25*(rkP0.Log()-rkP1.Log()); - Quaternion kMinusArg = -kArg; - - rkA = rkQ1*kArg.Exp(); - rkB = rkQ1*kMinusArg.Exp(); - } - //----------------------------------------------------------------------- - Quaternion Quaternion::Squad (Real fT, - const Quaternion& rkP, const Quaternion& rkA, - const Quaternion& rkB, const Quaternion& rkQ, bool shortestPath) - { - Real fSlerpT = 2.0f*fT*(1.0f-fT); - Quaternion kSlerpP = Slerp(fT, rkP, rkQ, shortestPath); - Quaternion kSlerpQ = Slerp(fT, rkA, rkB); - return Slerp(fSlerpT, kSlerpP ,kSlerpQ); - } - //----------------------------------------------------------------------- - Radian Quaternion::getRoll(bool reprojectAxis) const - { - if (reprojectAxis) - { - // roll = atan2(localx.y, localx.x) - // pick parts of xAxis() implementation that we need -// Real fTx = 2.0*x; - Real fTy = 2.0f*y; - Real fTz = 2.0f*z; - Real fTwz = fTz*w; - Real fTxy = fTy*x; - Real fTyy = fTy*y; - Real fTzz = fTz*z; - - // Vector3(1.0-(fTyy+fTzz), fTxy+fTwz, fTxz-fTwy); - - return Radian(Math::ATan2(fTxy+fTwz, 1.0f-(fTyy+fTzz))); - - } - else - { - return Radian(Math::ATan2(2*(x*y + w*z), w*w + x*x - y*y - z*z)); - } - } - //----------------------------------------------------------------------- - Radian Quaternion::getPitch(bool reprojectAxis) const - { - if (reprojectAxis) - { - // pitch = atan2(localy.z, localy.y) - // pick parts of yAxis() implementation that we need - Real fTx = 2.0f*x; -// Real fTy = 2.0f*y; - Real fTz = 2.0f*z; - Real fTwx = fTx*w; - Real fTxx = fTx*x; - Real fTyz = fTz*y; - Real fTzz = fTz*z; - - // Vector3(fTxy-fTwz, 1.0-(fTxx+fTzz), fTyz+fTwx); - return Radian(Math::ATan2(fTyz+fTwx, 1.0f-(fTxx+fTzz))); - } - else - { - // internal version - return Radian(Math::ATan2(2*(y*z + w*x), w*w - x*x - y*y + z*z)); - } - } - //----------------------------------------------------------------------- - Radian Quaternion::getYaw(bool reprojectAxis) const - { - if (reprojectAxis) - { - // yaw = atan2(localz.x, localz.z) - // pick parts of zAxis() implementation that we need - Real fTx = 2.0f*x; - Real fTy = 2.0f*y; - Real fTz = 2.0f*z; - Real fTwy = fTy*w; - Real fTxx = fTx*x; - Real fTxz = fTz*x; - Real fTyy = fTy*y; - - // Vector3(fTxz+fTwy, fTyz-fTwx, 1.0-(fTxx+fTyy)); - - return Radian(Math::ATan2(fTxz+fTwy, 1.0f-(fTxx+fTyy))); - - } - else - { - // internal version - return Radian(Math::ASin(-2*(x*z - w*y))); - } - } - //----------------------------------------------------------------------- - Quaternion Quaternion::nlerp(Real fT, const Quaternion& rkP, - const Quaternion& rkQ, bool shortestPath) - { - Quaternion result; - Real fCos = rkP.Dot(rkQ); - if (fCos < 0.0f && shortestPath) - { - result = rkP + fT * ((-rkQ) - rkP); - } - else - { - result = rkP + fT * (rkQ - rkP); - } - result.normalise(); - return result; - } -} diff --git a/OgreMain/src/OgreRadixSort.h b/OgreMain/src/OgreRadixSort.h deleted file mode 100644 index 5ab4a4f78a9..00000000000 --- a/OgreMain/src/OgreRadixSort.h +++ /dev/null @@ -1,336 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __RadixSort_H__ -#define __RadixSort_H__ - -#include "OgrePrerequisites.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - /** Class for performing a radix sort (fast comparison-less sort based on - byte value) on various standard STL containers. - - A radix sort is a very fast sort algorithm. It doesn't use comparisons - and thus is able to break the theoretical minimum O(N*logN) complexity. - Radix sort is complexity O(k*N), where k is a constant. Note that radix - sorting is not in-place, it requires additional storage, so it trades - memory for speed. The overhead of copying means that it is only faster - for fairly large datasets, so you are advised to only use it for collections - of at least a few hundred items. - @par - This is a template class to allow it to deal with a variety of containers, - and a variety of value types to sort on. In addition to providing the - container and value type on construction, you also need to supply a - functor object which will retrieve the value to compare on for each item - in the list. For example, if you had an std::vector of by-value instances - of an object of class 'Bibble', and you wanted to sort on - Bibble::getDoobrie(), you'd have to firstly create a functor - like this: - @code - struct BibbleSortFunctor - { - float operator()(const Bibble& val) const - { - return val.getDoobrie(); - } - } - @endcode - Then, you need to declare a RadixSort class which names the container type, - the value type in the container, and the type of the value you want to - sort by. You can then call the sort function. E.g. - @code - RadixSort radixSorter; - BibbleSortFunctor functor; - - radixSorter.sort(myBibbleList, functor); - @endcode - You should try to reuse RadixSort instances, since repeated allocation of the - internal storage is then avoided. - @note - Radix sorting is often associated with just unsigned integer values. Our - implementation can handle both unsigned and signed integers, as well as - floats (which are often not supported by other radix sorters). doubles - are not supported; you will need to implement your functor object to convert - to float if you wish to use this sort routine. - */ - template - class RadixSort - { - public: - typedef typename TContainer::iterator ContainerIter; - protected: - /// Alpha-pass counters of values (histogram) - /// 4 of them so we can radix sort a maximum of a 32bit value - int mCounters[4][256]; - /// Beta-pass offsets - int mOffsets[256]; - /// Sort area size - int mSortSize; - /// Number of passes for this type - int mNumPasses; - - struct SortEntry - { - TCompValueType key; - ContainerIter iter; - SortEntry() {} - SortEntry(TCompValueType k, ContainerIter it) - : key(k), iter(it) {} - - }; - /// Temp sort storage - typedef typename std::vector SortVector; - SortVector mSortArea1; - SortVector mSortArea2; - SortVector* mSrc; - SortVector* mDest; - TContainer mTmpContainer; // initial copy - - - void sortPass(int byteIndex) - { - // Calculate offsets - // Basically this just leaves gaps for duplicate entries to fill - mOffsets[0] = 0; - for (int i = 1; i < 256; ++i) - { - mOffsets[i] = mOffsets[i-1] + mCounters[byteIndex][i-1]; - } - - // Sort pass - for (int i = 0; i < mSortSize; ++i) - { - unsigned char byteVal = getByte(byteIndex, (*mSrc)[i].key); - (*mDest)[mOffsets[byteVal]++] = (*mSrc)[i]; - } - - } - template - void finalPass(int byteIndex, T val) - { - // default is to do normal pass - sortPass(byteIndex); - } - - // special case signed int - void finalPass(int byteIndex, int val) - { - int numNeg = 0; - // all negative values are in entries 128+ in most significant byte - for (int i = 128; i < 256; ++i) - { - numNeg += mCounters[byteIndex][i]; - } - // Calculate offsets - positive ones start at the number of negatives - // do positive numbers - mOffsets[0] = numNeg; - for (int i = 1; i < 128; ++i) - { - mOffsets[i] = mOffsets[i-1] + mCounters[byteIndex][i-1]; - } - // Do negative numbers (must start at zero) - // No need to invert ordering, already correct (-1 is highest number) - mOffsets[128] = 0; - for (int i = 129; i < 256; ++i) - { - mOffsets[i] = mOffsets[i-1] + mCounters[byteIndex][i-1]; - } - - // Sort pass - for (int i = 0; i < mSortSize; ++i) - { - unsigned char byteVal = getByte(byteIndex, (*mSrc)[i].key); - (*mDest)[mOffsets[byteVal]++] = (*mSrc)[i]; - } - } - - - // special case float - void finalPass(int byteIndex, float val) - { - // floats need to be special cased since negative numbers will come - // after positives (high bit = sign) and will be in reverse order - // (no ones-complement of the +ve value) - int numNeg = 0; - // all negative values are in entries 128+ in most significant byte - for (int i = 128; i < 256; ++i) - { - numNeg += mCounters[byteIndex][i]; - } - // Calculate offsets - positive ones start at the number of negatives - // do positive numbers normally - mOffsets[0] = numNeg; - for (int i = 1; i < 128; ++i) - { - mOffsets[i] = mOffsets[i-1] + mCounters[byteIndex][i-1]; - } - // Do negative numbers (must start at zero) - // Also need to invert ordering - // In order to preserve the stability of the sort (essential since - // we rely on previous bytes already being sorted) we have to count - // backwards in our offsets from - mOffsets[255] = mCounters[byteIndex][255]; - for (int i = 254; i > 127; --i) - { - mOffsets[i] = mOffsets[i+1] + mCounters[byteIndex][i]; - } - - // Sort pass - for (int i = 0; i < mSortSize; ++i) - { - unsigned char byteVal = getByte(byteIndex, (*mSrc)[i].key); - if (byteVal > 127) - { - // -ve; pre-decrement since offsets set to count - (*mDest)[--mOffsets[byteVal]] = (*mSrc)[i]; - } - else - { - // +ve - (*mDest)[mOffsets[byteVal]++] = (*mSrc)[i]; - } - } - } - - inline unsigned char getByte(int byteIndex, TCompValueType val) - { -#if OGRE_ENDIAN == OGRE_ENDIAN_LITTLE - return ((unsigned char*)(&val))[byteIndex]; -#else - return ((unsigned char*)(&val))[mNumPasses - byteIndex - 1]; -#endif - } - - public: - - RadixSort() {} - ~RadixSort() {} - - /** Main sort function - @param container A container of the type you declared when declaring - @param func A functor which returns the value for comparison when given - a container value - */ - template void sort(TContainer& container, TFunction func) - { - sort(container.begin(), container.end(), func); - } - - /// @overload - template - void sort(ContainerIter dbegin, ContainerIter dend, TFunction func) - { - // Set up the sort areas - mSortSize = static_cast(std::distance(dbegin, dend)); - - if (mSortSize == 0) - return; - - mSortArea1.resize(mSortSize); - mSortArea2.resize(mSortSize); - - // Copy data now (we need constant iterators for sorting) - mTmpContainer.assign(dbegin, dend); - - mNumPasses = sizeof(TCompValueType); - - // Counter pass - // Initialise the counts - int p; - for (p = 0; p < mNumPasses; ++p) - memset(mCounters[p], 0, sizeof(int) * 256); - - // Perform alpha pass to count - ContainerIter i = mTmpContainer.begin(); - TCompValueType prevValue = func.operator()(*i); - bool needsSorting = false; - for (int u = 0; i != mTmpContainer.end(); ++i, ++u) - { - // get sort value - TCompValueType val = func.operator()(*i); - // cheap check to see if needs sorting (temporal coherence) - if (!needsSorting && val < prevValue) - needsSorting = true; - - // Create a sort entry - mSortArea1[u].key = val; - mSortArea1[u].iter = i; - - // increase counters - for (p = 0; p < mNumPasses; ++p) - { - unsigned char byteVal = getByte(p, val); - mCounters[p][byteVal]++; - } - - prevValue = val; - - } - - // early exit if already sorted - if (!needsSorting) - return; - - - // Sort passes - mSrc = &mSortArea1; - mDest = &mSortArea2; - - for (p = 0; p < mNumPasses - 1; ++p) - { - sortPass(p); - // flip src/dst - SortVector* tmp = mSrc; - mSrc = mDest; - mDest = tmp; - } - // Final pass may differ, make polymorphic - finalPass(p, prevValue); - - // Copy everything back - int c = 0; - for (i = dbegin; i != dend; ++i, ++c) - { - *i = *((*mDest)[c].iter); - } - } - - }; - - /** @} */ - /** @} */ - -} -#endif - diff --git a/OgreMain/src/OgreRectangle2D.cpp b/OgreMain/src/OgreRectangle2D.cpp deleted file mode 100644 index e21934a1b90..00000000000 --- a/OgreMain/src/OgreRectangle2D.cpp +++ /dev/null @@ -1,222 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -namespace Ogre { -#define POSITION_BINDING 0 -#define NORMAL_BINDING 1 -#define TEXCOORD_BINDING 2 - - Rectangle2D::Rectangle2D(bool includeTextureCoords, Ogre::HardwareBuffer::Usage vBufUsage) - : SimpleRenderable() - { - _initRectangle2D(includeTextureCoords, vBufUsage); - } - - Rectangle2D::Rectangle2D(const String& name, bool includeTextureCoords, Ogre::HardwareBuffer::Usage vBufUsage) - : SimpleRenderable(name) - { - _initRectangle2D(includeTextureCoords, vBufUsage); - } - - void Rectangle2D::_initRectangle2D(bool includeTextureCoords, Ogre::HardwareBuffer::Usage vBufUsage) - { - // use identity projection and view matrices - mUseIdentityProjection = true; - mUseIdentityView = true; - - mBox.setInfinite(); // screenspace -> never culled - - mRenderOp.vertexData = OGRE_NEW VertexData(); - - mRenderOp.indexData = 0; - mRenderOp.vertexData->vertexCount = 4; - mRenderOp.vertexData->vertexStart = 0; - mRenderOp.operationType = RenderOperation::OT_TRIANGLE_STRIP; - mRenderOp.useIndexes = false; - mRenderOp.useGlobalInstancing = false; - - VertexDeclaration* decl = mRenderOp.vertexData->vertexDeclaration; - VertexBufferBinding* bind = mRenderOp.vertexData->vertexBufferBinding; - - decl->addElement(POSITION_BINDING, 0, VET_FLOAT3, VES_POSITION); - - auto& hbm = HardwareBufferManager::getSingleton(); - auto vbuf = - hbm.createVertexBuffer(decl->getVertexSize(POSITION_BINDING), mRenderOp.vertexData->vertexCount, vBufUsage); - - // Bind buffer - bind->setBinding(POSITION_BINDING, vbuf); - - setCorners(-1, 1, 1, -1, false); - - decl->addElement(NORMAL_BINDING, 0, VET_FLOAT3, VES_NORMAL); - - vbuf = - hbm.createVertexBuffer(decl->getVertexSize(NORMAL_BINDING), mRenderOp.vertexData->vertexCount, vBufUsage); - - bind->setBinding(NORMAL_BINDING, vbuf); - - setNormals({0, 0, 1}, {0, 0, 1}, {0, 0, 1}, {0, 0, 1}); - - if (includeTextureCoords) - { - decl->addElement(TEXCOORD_BINDING, 0, VET_FLOAT2, VES_TEXTURE_COORDINATES); - - auto tvbuf = hbm.createVertexBuffer(decl->getVertexSize(TEXCOORD_BINDING), - mRenderOp.vertexData->vertexCount, vBufUsage); - - // Bind buffer - bind->setBinding(TEXCOORD_BINDING, tvbuf); - - // Set up basic tex coordinates - setDefaultUVs(); - } - - // set basic white material - mMaterial = MaterialManager::getSingleton().getDefaultMaterial(false); - mMaterial->load(); - } - - Rectangle2D::~Rectangle2D() - { - OGRE_DELETE mRenderOp.vertexData; - } - - void Rectangle2D::setCorners(float left, float top, float right, float bottom, bool updateAABB) - { - HardwareVertexBufferSharedPtr vbuf = - mRenderOp.vertexData->vertexBufferBinding->getBuffer(POSITION_BINDING); - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - float* pFloat = static_cast(vbufLock.pData); - - *pFloat++ = left; - *pFloat++ = top; - *pFloat++ = -1; - - *pFloat++ = left; - *pFloat++ = bottom; - *pFloat++ = -1; - - *pFloat++ = right; - *pFloat++ = top; - *pFloat++ = -1; - - *pFloat++ = right; - *pFloat++ = bottom; - *pFloat++ = -1; - - if(updateAABB) - { - mBox.setExtents( - std::min(left, right), std::min(top, bottom), 0, - std::max(left, right), std::max(top, bottom), 0); - } - } - - void Rectangle2D::setNormals(const Vector3& topLeft, const Vector3& bottomLeft, const Vector3& topRight, - const Vector3& bottomRight) - { - HardwareVertexBufferSharedPtr vbuf = - mRenderOp.vertexData->vertexBufferBinding->getBuffer(NORMAL_BINDING); - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - float* pFloat = static_cast(vbufLock.pData); - - *pFloat++ = topLeft.x; - *pFloat++ = topLeft.y; - *pFloat++ = topLeft.z; - - *pFloat++ = bottomLeft.x; - *pFloat++ = bottomLeft.y; - *pFloat++ = bottomLeft.z; - - *pFloat++ = topRight.x; - *pFloat++ = topRight.y; - *pFloat++ = topRight.z; - - *pFloat++ = bottomRight.x; - *pFloat++ = bottomRight.y; - *pFloat++ = bottomRight.z; - } - - void Rectangle2D::setUVs(const Vector2& topLeft, const Vector2& bottomLeft, const Vector2& topRight, - const Vector2& bottomRight) - { - OgreAssert(mRenderOp.vertexData->vertexDeclaration->getElementCount() > TEXCOORD_BINDING, - "Vertex data wasn't built with UV buffer"); - - HardwareVertexBufferSharedPtr vbuf = - mRenderOp.vertexData->vertexBufferBinding->getBuffer(TEXCOORD_BINDING); - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - float* pFloat = static_cast(vbufLock.pData); - - *pFloat++ = topLeft.x; - *pFloat++ = topLeft.y; - - *pFloat++ = bottomLeft.x; - *pFloat++ = bottomLeft.y; - - *pFloat++ = topRight.x; - *pFloat++ = topRight.y; - - *pFloat++ = bottomRight.x; - *pFloat++ = bottomRight.y; - } - - void Rectangle2D::setDefaultUVs() - { - setUVs( Vector2::ZERO, Vector2::UNIT_Y, Vector2::UNIT_X, Vector2::UNIT_SCALE ); - } - - // Override this method to prevent parent transforms (rotation,translation,scale) - void Rectangle2D::getWorldTransforms( Matrix4* xform ) const - { - // return identity matrix to prevent parent transforms - *xform = Matrix4::IDENTITY; - } - - const String& Rectangle2D::getMovableType() const - { - return MOT_RECTANGLE2D; - } - - const String MOT_RECTANGLE2D = "Rectangle2D"; - - MovableObject* Rectangle2DFactory::createInstanceImpl(const String& name, const NameValuePairList* params) - { - bool includeTextureCoords = false; - if (params) - { - auto ni = params->find("includeTextureCoords"); - if (ni != params->end()) - StringConverter::parse(ni->second, includeTextureCoords); - } - return new Rectangle2D(includeTextureCoords); - } -} - diff --git a/OgreMain/src/OgreRenderQueue.cpp b/OgreMain/src/OgreRenderQueue.cpp deleted file mode 100644 index 072059d45ce..00000000000 --- a/OgreMain/src/OgreRenderQueue.cpp +++ /dev/null @@ -1,287 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreRenderQueue.h" - -#include -#include "OgreMaterial.h" -#include "OgreRenderQueueSortingGrouping.h" -#include "OgreSceneManagerEnumerator.h" - -namespace Ogre { - - //--------------------------------------------------------------------- - RenderQueue::RenderQueue() - : mSplitPassesByLightingType(false) - , mSplitNoShadowPasses(false) - , mShadowCastersCannotBeReceivers(false) - , mRenderableListener(0) - { - // Create the 'main' queue up-front since we'll always need that - mGroups[RENDER_QUEUE_MAIN] = std::make_unique( - mSplitPassesByLightingType, mSplitNoShadowPasses, mShadowCastersCannotBeReceivers); - - // set default queue - mDefaultQueueGroup = RENDER_QUEUE_MAIN; - mDefaultRenderablePriority = Renderable::DEFAULT_PRIORITY; - - } - //--------------------------------------------------------------------- - RenderQueue::~RenderQueue() - { - - // trigger the pending pass updates, otherwise we could leak - Pass::processPendingPassUpdates(); - } - - static bool onTransparentQueue(Technique* pTech) - { - // Transparent and depth/colour settings mean depth sorting is required? - // Note: colour write disabled with depth check/write enabled means - // setup depth buffer for other passes use. - if (pTech->isTransparentSortingForced() || - (pTech->isTransparent() && - (!pTech->isDepthWriteEnabled() || !pTech->isDepthCheckEnabled() || pTech->hasColourWriteDisabled()))) - { - return true; - } - - return false; - } - - //----------------------------------------------------------------------- - void RenderQueue::addRenderable(Renderable* pRend, uint8 groupID, ushort priority) - { - Technique* pTech; - - // tell material it's been used - if (pRend->getMaterial()) - pRend->getMaterial()->touch(); - - // Check material & technique supplied (the former since the default implementation - // of getTechnique is based on it for backwards compatibility - if(!pRend->getMaterial() || !pRend->getTechnique()) - { - // Use default base white, with lighting only if vertices has normals - RenderOperation op; - pRend->getRenderOperation(op); - bool useLighting = (NULL != op.vertexData->vertexDeclaration->findElementBySemantic(VES_NORMAL)); - MaterialPtr defaultMat = MaterialManager::getSingleton().getDefaultMaterial(useLighting); - defaultMat->load(); - pTech = defaultMat->getBestTechnique(); - } - else - pTech = pRend->getTechnique(); - - if (mRenderableListener) - { - // Allow listener to override technique and to abort - if (!mRenderableListener->renderableQueued(pRend, groupID, priority, - &pTech, this)) - return; // rejected - - // tell material it's been used (incase changed) - pTech->getParent()->touch(); - } - - if(groupID == mDefaultQueueGroup && onTransparentQueue(pTech)) - groupID = RENDER_QUEUE_TRANSPARENTS; - - // Find group - RenderQueueGroup* pGroup = getQueueGroup(groupID); - pGroup->addRenderable(pRend, pTech, priority); - - } - //----------------------------------------------------------------------- - void RenderQueue::clear(bool destroyPassMaps) - { - // Note: We clear dirty passes from all RenderQueues in all - // SceneManagers, because the following recalculation of pass hashes - // also considers all RenderQueues and could become inconsistent, otherwise. - for (auto p : SceneManagerEnumerator::getSingleton().getSceneManagers()) - { - RenderQueue* queue = p.second->getRenderQueue(); - - for (auto & g : queue->mGroups) - { - if(g) - g->clear(destroyPassMaps); - } - } - - // Now trigger the pending pass updates - Pass::processPendingPassUpdates(); - - // NB this leaves the items present (but empty) - // We're assuming that frame-by-frame, the same groups are likely to - // be used, so no point destroying the vectors and incurring the overhead - // that would cause, let them be destroyed in the destructor. - } - //----------------------------------------------------------------------- - void RenderQueue::addRenderable(Renderable* pRend, uint8 groupID) - { - addRenderable(pRend, groupID, mDefaultRenderablePriority); - } - //----------------------------------------------------------------------- - void RenderQueue::addRenderable(Renderable* pRend) - { - addRenderable(pRend, mDefaultQueueGroup, mDefaultRenderablePriority); - } - //----------------------------------------------------------------------- - uint8 RenderQueue::getDefaultQueueGroup(void) const - { - return mDefaultQueueGroup; - } - //----------------------------------------------------------------------- - void RenderQueue::setDefaultQueueGroup(uint8 grp) - { - mDefaultQueueGroup = grp; - } - //----------------------------------------------------------------------- - ushort RenderQueue::getDefaultRenderablePriority(void) const - { - return mDefaultRenderablePriority; - } - //----------------------------------------------------------------------- - void RenderQueue::setDefaultRenderablePriority(ushort priority) - { - mDefaultRenderablePriority = priority; - } - - - //----------------------------------------------------------------------- - RenderQueueGroup* RenderQueue::getQueueGroup(uint8 groupID) - { - if (!mGroups[groupID]) - { - // Insert new - mGroups[groupID] = std::make_unique(mSplitPassesByLightingType, mSplitNoShadowPasses, - mShadowCastersCannotBeReceivers); - } - - return mGroups[groupID].get(); - - } - //----------------------------------------------------------------------- - void RenderQueue::setSplitPassesByLightingType(bool split) - { - mSplitPassesByLightingType = split; - - for (auto & g : mGroups) - { - if(g) - g->setSplitPassesByLightingType(split); - } - } - //----------------------------------------------------------------------- - bool RenderQueue::getSplitPassesByLightingType(void) const - { - return mSplitPassesByLightingType; - } - //----------------------------------------------------------------------- - void RenderQueue::setSplitNoShadowPasses(bool split) - { - mSplitNoShadowPasses = split; - - for (auto & g : mGroups) - { - if(g) - g->setSplitNoShadowPasses(split); - } - } - //----------------------------------------------------------------------- - bool RenderQueue::getSplitNoShadowPasses(void) const - { - return mSplitNoShadowPasses; - } - //----------------------------------------------------------------------- - void RenderQueue::setShadowCastersCannotBeReceivers(bool ind) - { - mShadowCastersCannotBeReceivers = ind; - - for (auto & g : mGroups) - { - if(g) - g->setShadowCastersCannotBeReceivers(ind); - } - } - //----------------------------------------------------------------------- - bool RenderQueue::getShadowCastersCannotBeReceivers(void) const - { - return mShadowCastersCannotBeReceivers; - } - //----------------------------------------------------------------------- - void RenderQueue::merge( const RenderQueue* rhs ) - { - for (size_t i = 0; i < RENDER_QUEUE_COUNT; ++i) - { - if(!rhs->mGroups[i]) - continue; - - RenderQueueGroup* pDstGroup = getQueueGroup( i ); - pDstGroup->merge( rhs->mGroups[i].get() ); - } - } - - //--------------------------------------------------------------------- - void RenderQueue::processVisibleObject(MovableObject* mo, - Camera* cam, - bool onlyShadowCasters, - VisibleObjectsBoundsInfo* visibleBounds) - { - // receiveShadows is a material property, so we can query it before LOD - bool receiveShadows = getQueueGroup(mo->getRenderQueueGroup())->getShadowsEnabled() && mo->getReceivesShadows(); - - if(onlyShadowCasters && !mo->getCastShadows() && !receiveShadows) - return; - - mo->_notifyCurrentCamera(cam); - if (!mo->isVisible()) - return; - - const auto& bbox = mo->getWorldBoundingBox(true); - const auto& bsphere = mo->getWorldBoundingSphere(true); - - if (!onlyShadowCasters || mo->getCastShadows()) - { - mo->_updateRenderQueue(this); - if (visibleBounds) - { - visibleBounds->merge(bbox, bsphere, cam, receiveShadows); - } - } - // not shadow caster, receiver only? - else if (receiveShadows) - { - visibleBounds->mergeNonRenderedButInFrustum(bbox, bsphere, cam); - } - } - -} - diff --git a/OgreMain/src/OgreRenderQueueSortingGrouping.cpp b/OgreMain/src/OgreRenderQueueSortingGrouping.cpp deleted file mode 100644 index eb10fc743d7..00000000000 --- a/OgreMain/src/OgreRenderQueueSortingGrouping.cpp +++ /dev/null @@ -1,477 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreRenderQueueSortingGrouping.h" - -namespace Ogre { -namespace { - /// Comparator to order objects by descending camera distance - struct DistanceSortDescendingLess - { - const Camera* camera; - - DistanceSortDescendingLess(const Camera* cam) - : camera(cam) - { - } - - bool operator()(const RenderablePass& a, const RenderablePass& b) const - { - if (a.renderable == b.renderable) - { - // Same renderable, sort by pass hash - return a.pass->getHash() < b.pass->getHash(); - } - else - { - // Different renderables, sort by distance - Real adist = a.renderable->getSquaredViewDepth(camera); - Real bdist = b.renderable->getSquaredViewDepth(camera); - if (Math::RealEqual(adist, bdist)) - { - // Must return deterministic result, doesn't matter what - return a.pass < b.pass; - } - else - { - // Sort DESCENDING by dist (i.e. far objects first) - return (adist > bdist); - } - } - - } - }; - - /// Functor for accessing sort value 1 for radix sort (Pass) - struct RadixSortFunctorPass - { - uint32 operator()(const RenderablePass& p) const - { - return p.pass->getHash(); - } - }; - - /// Functor for descending sort value 2 for radix sort (distance) - struct RadixSortFunctorDistance - { - const Camera* camera; - - RadixSortFunctorDistance(const Camera* cam) - : camera(cam) - { - } - - float operator()(const RenderablePass& p) const - { - // Sort DESCENDING by depth (ie far objects first), use negative distance - // here because radix sorter always dealing with accessing sort - return static_cast(- p.renderable->getSquaredViewDepth(camera)); - } - }; -} - //----------------------------------------------------------------------- - RenderPriorityGroup::RenderPriorityGroup(RenderQueueGroup* parent, - bool splitPassesByLightingType, - bool splitNoShadowPasses, - bool shadowCastersNotReceivers) - : mParent(parent) - , mSplitPassesByLightingType(splitPassesByLightingType) - , mSplitNoShadowPasses(splitNoShadowPasses) - , mShadowCastersNotReceivers(shadowCastersNotReceivers) - { - // Initialise collection sorting options - // this can become dynamic according to invocation later - defaultOrganisationMode(); - - // Transparents will always be sorted this way - mTransparents.addOrganisationMode(QueuedRenderableCollection::OM_SORT_DESCENDING); - - - } - //----------------------------------------------------------------------- - void RenderPriorityGroup::resetOrganisationModes(void) - { - mSolidsBasic.resetOrganisationModes(); - mSolidsDiffuseSpecular.resetOrganisationModes(); - mSolidsDecal.resetOrganisationModes(); - mSolidsNoShadowReceive.resetOrganisationModes(); - mTransparentsUnsorted.resetOrganisationModes(); - } - //----------------------------------------------------------------------- - void RenderPriorityGroup::addOrganisationMode(QueuedRenderableCollection::OrganisationMode om) - { - mSolidsBasic.addOrganisationMode(om); - mSolidsDiffuseSpecular.addOrganisationMode(om); - mSolidsDecal.addOrganisationMode(om); - mSolidsNoShadowReceive.addOrganisationMode(om); - mTransparentsUnsorted.addOrganisationMode(om); - } - //----------------------------------------------------------------------- - void RenderPriorityGroup::defaultOrganisationMode(void) - { - resetOrganisationModes(); - addOrganisationMode(QueuedRenderableCollection::OM_PASS_GROUP); - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - static void addPassesTo(QueuedRenderableCollection& collection, Technique* pTech, Renderable* rend) - { - for (auto* p : pTech->getPasses()) - { - collection.addRenderable(p, rend); - } - } - void RenderPriorityGroup::addRenderable(Renderable* rend, Technique* pTech) - { - // Transparent and depth/colour settings mean depth sorting is required? - // Note: colour write disabled with depth check/write enabled means - // setup depth buffer for other passes use. - if (pTech->isTransparentSortingForced() || - (pTech->isTransparent() && - (!pTech->isDepthWriteEnabled() || - !pTech->isDepthCheckEnabled() || - pTech->hasColourWriteDisabled()))) - { - if (pTech->isTransparentSortingEnabled()) - addPassesTo(mTransparents, pTech, rend); - else - addPassesTo(mTransparentsUnsorted, pTech, rend); - } - else - { - if (mSplitNoShadowPasses && - mParent->getShadowsEnabled() && - (!pTech->getParent()->getReceiveShadows() || - (rend->getCastsShadows() && mShadowCastersNotReceivers))) - { - // Add solid renderable and add passes to no-shadow group - addPassesTo(mSolidsNoShadowReceive, pTech, rend); - } - else - { - if (mSplitPassesByLightingType && mParent->getShadowsEnabled()) - { - addSolidRenderableSplitByLightType(pTech, rend); - } - else - { - addPassesTo(mSolidsBasic, pTech, rend); - } - } - } - - } - //----------------------------------------------------------------------- - void RenderPriorityGroup::addSolidRenderableSplitByLightType(Technique* pTech, - Renderable* rend) - { - // Divide the passes into the 3 categories - const IlluminationPassList& passes = pTech->getIlluminationPasses(); - - for(auto p : passes) - { - // Insert into solid list - QueuedRenderableCollection* collection = NULL; - switch(p->stage) - { - case IS_AMBIENT: - collection = &mSolidsBasic; - break; - case IS_PER_LIGHT: - collection = &mSolidsDiffuseSpecular; - break; - case IS_DECAL: - collection = &mSolidsDecal; - break; - default: - assert(false); // should never happen - }; - - collection->addRenderable(p->pass, rend); - } - } - //----------------------------------------------------------------------- - void RenderPriorityGroup::removePassEntry(Pass* p) - { - mSolidsBasic.removePassGroup(p); - mSolidsDiffuseSpecular.removePassGroup(p); - mSolidsNoShadowReceive.removePassGroup(p); - mSolidsDecal.removePassGroup(p); - mTransparentsUnsorted.removePassGroup(p); - mTransparents.removePassGroup(p); // shouldn't be any, but for completeness - } - //----------------------------------------------------------------------- - void RenderPriorityGroup::clear(void) - { - // Delete queue groups which are using passes which are to be - // deleted, we won't need these any more and they clutter up - // the list and can cause problems with future clones - { - // Hmm, a bit hacky but least obtrusive for now - OGRE_LOCK_MUTEX(Pass::msPassGraveyardMutex); - const Pass::PassSet& graveyardList = Pass::getPassGraveyard(); - for (auto* p : graveyardList) - { - removePassEntry(p); - } - } - - // Now remove any dirty passes, these will have their hashes recalculated - // by the parent queue after all groups have been processed - // If we don't do this, the std::map will become inconsistent for new insterts - { - // Hmm, a bit hacky but least obtrusive for now - OGRE_LOCK_MUTEX(Pass::msDirtyHashListMutex); - const Pass::PassSet& dirtyList = Pass::getDirtyHashList(); - for (auto* p : dirtyList) - { - removePassEntry(p); - } - } - // NB we do NOT clear the graveyard or the dirty list here, because - // it needs to be acted on for all groups, the parent queue takes - // care of this afterwards - - // Now empty the remaining collections - // Note that groups don't get deleted, just emptied hence the difference - // between the pass groups which are removed above, and clearing done - // here - mSolidsBasic.clear(); - mSolidsDecal.clear(); - mSolidsDiffuseSpecular.clear(); - mSolidsNoShadowReceive.clear(); - mTransparentsUnsorted.clear(); - mTransparents.clear(); - - } - //----------------------------------------------------------------------- - void RenderPriorityGroup::sort(const Camera* cam) - { - mSolidsBasic.sort(cam); - mSolidsDecal.sort(cam); - mSolidsDiffuseSpecular.sort(cam); - mSolidsNoShadowReceive.sort(cam); - mTransparentsUnsorted.sort(cam); - mTransparents.sort(cam); - } - //----------------------------------------------------------------------- - void RenderPriorityGroup::merge( const RenderPriorityGroup* rhs ) - { - mSolidsBasic.merge( rhs->mSolidsBasic ); - mSolidsDecal.merge( rhs->mSolidsDecal ); - mSolidsDiffuseSpecular.merge( rhs->mSolidsDiffuseSpecular ); - mSolidsNoShadowReceive.merge( rhs->mSolidsNoShadowReceive ); - mTransparentsUnsorted.merge( rhs->mTransparentsUnsorted ); - mTransparents.merge( rhs->mTransparents ); - } - //----------------------------------------------------------------------- - QueuedRenderableCollection::QueuedRenderableCollection(void) - :mOrganisationMode(0) - { - } - - //----------------------------------------------------------------------- - void QueuedRenderableCollection::clear(void) - { - for (auto& i : mGrouped) - { - // Clear the list associated with this pass, but leave the pass entry - i.second.clear(); - } - - // Clear sorted list - mSortedDescending.clear(); - } - //----------------------------------------------------------------------- - void QueuedRenderableCollection::removePassGroup(Pass* p) - { - PassGroupRenderableMap::iterator i; - - i = mGrouped.find(p); - if (i != mGrouped.end()) - { - // erase from map - mGrouped.erase(i); - } - } - //----------------------------------------------------------------------- - void QueuedRenderableCollection::sort(const Camera* cam) - { - /// Radix sorter for accessing sort value 1 (Pass) - static RadixSort msRadixSorter1; - /// Radix sorter for sort value 2 (distance) - static RadixSort msRadixSorter2; - - // ascending and descending sort both set bit 1 - // We always sort descending, because the only difference is in the - // acceptVisitor method, where we iterate in reverse in ascending mode - if (mOrganisationMode & OM_SORT_DESCENDING) - { - - // We can either use a stable_sort and the 'less' implementation, - // or a 2-pass radix sort (once by pass, then by distance, since - // radix sorting is inherently stable this will work) - // We use stable_sort if the number of items is 512 or less, since - // the complexity of the radix sort is approximately O(10N), since - // each sort is O(5N) (1 pass histograms, 4 passes sort) - // Since stable_sort has a worst-case performance of O(N(logN)^2) - // the performance tipping point is from about 1500 items, but in - // stable_sorts best-case scenario O(NlogN) it would be much higher. - // Take a stab at 2000 items. - - if (mSortedDescending.size() > 2000) - { - // sort by pass - msRadixSorter1.sort(mSortedDescending, RadixSortFunctorPass()); - // sort by depth - msRadixSorter2.sort(mSortedDescending, RadixSortFunctorDistance(cam)); - } - else - { - std::stable_sort( - mSortedDescending.begin(), mSortedDescending.end(), - DistanceSortDescendingLess(cam)); - } - } - - // Nothing needs to be done for pass groups, they auto-organise - - } - //----------------------------------------------------------------------- - void QueuedRenderableCollection::addRenderable(Pass* pass, Renderable* rend) - { - // ascending and descending sort both set bit 1 - if (mOrganisationMode & OM_SORT_DESCENDING) - { - mSortedDescending.push_back(RenderablePass(rend, pass)); - } - - if (mOrganisationMode & OM_PASS_GROUP) - { - // Optionally create new pass entry, build a new list - // Note that this pass and list are never destroyed until the - // engine shuts down, or a pass is destroyed or has it's hash - // recalculated, although the lists will be cleared - PassGroupRenderableMap::iterator i = mGrouped.emplace(pass, RenderableList()).first; - - // Insert renderable - i->second.push_back(rend); - - } - - } - //----------------------------------------------------------------------- - void QueuedRenderableCollection::acceptVisitor( - QueuedRenderableVisitor* visitor, OrganisationMode om) const - { - if ((om & mOrganisationMode) == 0) - { - // try to fall back - if (OM_PASS_GROUP & mOrganisationMode) - om = OM_PASS_GROUP; - else if (OM_SORT_ASCENDING & mOrganisationMode) - om = OM_SORT_ASCENDING; - else if (OM_SORT_DESCENDING & mOrganisationMode) - om = OM_SORT_DESCENDING; - else - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Organisation mode requested in acceptVistor was not notified " - "to this class ahead of time, therefore may not be supported.", - "QueuedRenderableCollection::acceptVisitor"); - } - - switch(om) - { - case OM_PASS_GROUP: - acceptVisitorGrouped(visitor); - break; - case OM_SORT_DESCENDING: - acceptVisitorDescending(visitor); - break; - case OM_SORT_ASCENDING: - acceptVisitorAscending(visitor); - break; - } - - } - //----------------------------------------------------------------------- - void QueuedRenderableCollection::acceptVisitorGrouped( - QueuedRenderableVisitor* visitor) const - { - for (auto& ipass : mGrouped) - { - // Fast bypass if this group is now empty - if (ipass.second.empty()) continue; - - visitor->visit(ipass.first, const_cast(ipass.second)); - } - - } - //----------------------------------------------------------------------- - void QueuedRenderableCollection::acceptVisitorDescending( - QueuedRenderableVisitor* visitor) const - { - // List is already in descending order, so iterate forward - for (const auto& i : mSortedDescending) - { - visitor->visit(const_cast(&i)); - } - } - //----------------------------------------------------------------------- - void QueuedRenderableCollection::acceptVisitorAscending( - QueuedRenderableVisitor* visitor) const - { - // List is in descending order, so iterate in reverse - RenderablePassList::const_reverse_iterator i, iend; - - iend = mSortedDescending.rend(); - for (i = mSortedDescending.rbegin(); i != iend; ++i) - { - visitor->visit(const_cast(&(*i))); - } - - } - //----------------------------------------------------------------------- - void QueuedRenderableCollection::merge( const QueuedRenderableCollection& rhs ) - { - mSortedDescending.insert( mSortedDescending.end(), rhs.mSortedDescending.begin(), rhs.mSortedDescending.end() ); - - for (const auto& srcGroup : rhs.mGrouped) - { - // Optionally create new pass entry, build a new list - // Note that this pass and list are never destroyed until the - // engine shuts down, or a pass is destroyed or has it's hash - // recalculated, although the lists will be cleared - PassGroupRenderableMap::iterator dstGroup = mGrouped.emplace(srcGroup.first, RenderableList()).first; - - // Insert renderable - dstGroup->second.insert(dstGroup->second.end(), srcGroup.second.begin(), srcGroup.second.end() ); - } - } -} - diff --git a/OgreMain/src/OgreRenderSystem.cpp b/OgreMain/src/OgreRenderSystem.cpp deleted file mode 100644 index e0cd8b7ac42..00000000000 --- a/OgreMain/src/OgreRenderSystem.cpp +++ /dev/null @@ -1,919 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -// RenderSystem implementation -// Note that most of this class is abstract since -// we cannot know how to implement the behaviour without -// being aware of the 3D API. However there are a few -// simple functions which can have a base implementation - -#include "OgreRenderTarget.h" -#include "OgreDepthBuffer.h" -#include "OgreHardwareOcclusionQuery.h" -#include "OgreComponents.h" - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM -#include "OgreRTShaderConfig.h" -#endif - -namespace Ogre { - - RenderSystem::Listener* RenderSystem::msSharedEventListener = 0; - - static const TexturePtr sNullTexPtr; - - //----------------------------------------------------------------------- - RenderSystem::RenderSystem() - : mActiveRenderTarget(0) - , mTextureManager(0) - , mActiveViewport(0) - // This means CULL clockwise vertices, i.e. front of poly is counter-clockwise - // This makes it the same as OpenGL and other right-handed systems - , mCullingMode(CULL_CLOCKWISE) - , mBatchCount(0) - , mFaceCount(0) - , mVertexCount(0) - , mInvertVertexWinding(false) - , mIsReverseDepthBufferEnabled(false) - , mDisabledTexUnitsFrom(0) - , mCurrentPassIterationCount(0) - , mCurrentPassIterationNum(0) - , mDerivedDepthBias(false) - , mDerivedDepthBiasBase(0.0f) - , mDerivedDepthBiasMultiplier(0.0f) - , mDerivedDepthBiasSlopeScale(0.0f) - , mClipPlanesDirty(true) - , mRealCapabilities(0) - , mCurrentCapabilities(0) - , mUseCustomCapabilities(false) - , mNativeShadingLanguageVersion(0) - , mTexProjRelative(false) - , mTexProjRelativeOrigin(Vector3::ZERO) - , mGlobalInstanceVertexDeclaration(NULL) - , mGlobalNumberOfInstances(1) - { - mEventNames.push_back("RenderSystemCapabilitiesCreated"); - } - - void RenderSystem::initFixedFunctionParams() - { - if(mFixedFunctionParams) - return; - - GpuLogicalBufferStructPtr logicalBufferStruct(new GpuLogicalBufferStruct()); - mFixedFunctionParams.reset(new GpuProgramParameters); - mFixedFunctionParams->_setLogicalIndexes(logicalBufferStruct); - mFixedFunctionParams->setAutoConstant(0, GpuProgramParameters::ACT_WORLD_MATRIX); - mFixedFunctionParams->setAutoConstant(4, GpuProgramParameters::ACT_VIEW_MATRIX); - mFixedFunctionParams->setAutoConstant(8, GpuProgramParameters::ACT_PROJECTION_MATRIX); - mFixedFunctionParams->setAutoConstant(12, GpuProgramParameters::ACT_SURFACE_AMBIENT_COLOUR); - mFixedFunctionParams->setAutoConstant(13, GpuProgramParameters::ACT_SURFACE_DIFFUSE_COLOUR); - mFixedFunctionParams->setAutoConstant(14, GpuProgramParameters::ACT_SURFACE_SPECULAR_COLOUR); - mFixedFunctionParams->setAutoConstant(15, GpuProgramParameters::ACT_SURFACE_EMISSIVE_COLOUR); - mFixedFunctionParams->setAutoConstant(16, GpuProgramParameters::ACT_SURFACE_SHININESS); - mFixedFunctionParams->setAutoConstant(17, GpuProgramParameters::ACT_POINT_PARAMS); - mFixedFunctionParams->setConstant(18, Vector4::ZERO); // ACT_FOG_PARAMS - mFixedFunctionParams->setConstant(19, Vector4::ZERO); // ACT_FOG_COLOUR - mFixedFunctionParams->setAutoConstant(20, GpuProgramParameters::ACT_AMBIENT_LIGHT_COLOUR); - - // allocate per light parameters. slots 21..69 - for(int i = 0; i < OGRE_MAX_SIMULTANEOUS_LIGHTS; i++) - { - size_t light_offset = 21 + i * 6; - mFixedFunctionParams->setConstant(light_offset + 0, Vector4::ZERO); // position - mFixedFunctionParams->setConstant(light_offset + 1, Vector4::ZERO); // direction - mFixedFunctionParams->setConstant(light_offset + 2, Vector4::ZERO); // diffuse - mFixedFunctionParams->setConstant(light_offset + 3, Vector4::ZERO); // specular - mFixedFunctionParams->setConstant(light_offset + 4, Vector4::ZERO); // attenuation - mFixedFunctionParams->setConstant(light_offset + 5, Vector4::ZERO); // spotlight - } - } - - void RenderSystem::setFFPLightParams(uint32 index, bool enabled) - { - if(!mFixedFunctionParams) - return; - - size_t light_offset = 21 + 6 * index; - if (!enabled) - { - mFixedFunctionParams->clearAutoConstant(light_offset + 0); - mFixedFunctionParams->clearAutoConstant(light_offset + 1); - mFixedFunctionParams->clearAutoConstant(light_offset + 2); - mFixedFunctionParams->clearAutoConstant(light_offset + 3); - mFixedFunctionParams->clearAutoConstant(light_offset + 4); - mFixedFunctionParams->clearAutoConstant(light_offset + 5); - return; - } - mFixedFunctionParams->setAutoConstant(light_offset + 0, GpuProgramParameters::ACT_LIGHT_POSITION, index); - mFixedFunctionParams->setAutoConstant(light_offset + 1, GpuProgramParameters::ACT_LIGHT_DIRECTION, index); - mFixedFunctionParams->setAutoConstant(light_offset + 2, GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR, index); - mFixedFunctionParams->setAutoConstant(light_offset + 3, GpuProgramParameters::ACT_LIGHT_SPECULAR_COLOUR, index); - mFixedFunctionParams->setAutoConstant(light_offset + 4, GpuProgramParameters::ACT_LIGHT_ATTENUATION, index); - mFixedFunctionParams->setAutoConstant(light_offset + 5, GpuProgramParameters::ACT_SPOTLIGHT_PARAMS, index); - } - - //----------------------------------------------------------------------- - RenderSystem::~RenderSystem() - { - shutdown(); - OGRE_DELETE mRealCapabilities; - mRealCapabilities = 0; - // Current capabilities managed externally - mCurrentCapabilities = 0; - } - - RenderWindowDescription RenderSystem::getRenderWindowDescription() const - { - RenderWindowDescription ret; - auto& miscParams = ret.miscParams; - - auto end = mOptions.end(); - - auto opt = mOptions.find("Full Screen"); - if (opt == end) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Can't find 'Full Screen' option"); - - ret.useFullScreen = StringConverter::parseBool(opt->second.currentValue); - - opt = mOptions.find("Video Mode"); - if (opt == end) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Can't find 'Video Mode' option"); - - StringStream mode(opt->second.currentValue); - String token; - - mode >> ret.width; - mode >> token; // 'x' as seperator between width and height - mode >> ret.height; - - // backend specific options. Presence determined by getConfigOptions - mode >> token; // '@' as seperator between bpp on D3D - if(!mode.eof()) - { - uint32 bpp; - mode >> bpp; - miscParams.emplace("colourDepth", std::to_string(bpp)); - } - - if((opt = mOptions.find("FSAA")) != end) - { - StringStream fsaaMode(opt->second.currentValue); - uint32_t fsaa; - fsaaMode >> fsaa; - miscParams.emplace("FSAA", std::to_string(fsaa)); - - // D3D specific - if(!fsaaMode.eof()) - { - String hint; - fsaaMode >> hint; - miscParams.emplace("FSAAHint", hint); - } - } - - if((opt = mOptions.find("VSync")) != end) - miscParams.emplace("vsync", opt->second.currentValue); - - if((opt = mOptions.find("sRGB Gamma Conversion")) != end) - miscParams.emplace("gamma", opt->second.currentValue); - - if((opt = mOptions.find("Colour Depth")) != end) - miscParams.emplace("colourDepth", opt->second.currentValue); - - if((opt = mOptions.find("VSync Interval")) != end) - miscParams.emplace("vsyncInterval", opt->second.currentValue); - - if((opt = mOptions.find("Display Frequency")) != end) - miscParams.emplace("displayFrequency", opt->second.currentValue); - - if((opt = mOptions.find("Content Scaling Factor")) != end) - miscParams["contentScalingFactor"] = opt->second.currentValue; - - if((opt = mOptions.find("Rendering Device")) != end) - { - // try to parse "Monitor-NN-" - auto start = opt->second.currentValue.find('-') + 1; - auto len = opt->second.currentValue.find('-', start) - start; - if(start != String::npos) - miscParams["monitorIndex"] = opt->second.currentValue.substr(start, len); - } - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - if((opt = mOptions.find("Frame Sequential Stereo")) != end) - miscParams["stereoMode"] = opt->second.currentValue; -#endif - return ret; - } - - //----------------------------------------------------------------------- - void RenderSystem::_initRenderTargets(void) - { - - // Init stats - for (auto& rt : mRenderTargets) - { - rt.second->resetStatistics(); - } - } - //----------------------------------------------------------------------- - void RenderSystem::_updateAllRenderTargets(bool swapBuffers) - { - // Update all in order of priority - // This ensures render-to-texture targets get updated before render windows - for (auto& rt : mPrioritisedRenderTargets) - { - if (rt.second->isActive() && rt.second->isAutoUpdated()) - rt.second->update(swapBuffers); - } - } - //----------------------------------------------------------------------- - void RenderSystem::_swapAllRenderTargetBuffers() - { - OgreProfile("_swapAllRenderTargetBuffers"); - // Update all in order of priority - // This ensures render-to-texture targets get updated before render windows - for (auto& rt : mPrioritisedRenderTargets) - { - if (rt.second->isActive() && rt.second->isAutoUpdated()) - rt.second->swapBuffers(); - } - } - //----------------------------------------------------------------------- - void RenderSystem::_initialise() - { - // Have I been registered by call to Root::setRenderSystem? - /** Don't do this anymore, just allow via Root - RenderSystem* regPtr = Root::getSingleton().getRenderSystem(); - if (!regPtr || regPtr != this) - // Register self - library user has come to me direct - Root::getSingleton().setRenderSystem(this); - */ - - - // Subclasses should take it from here - // They should ALL call this superclass method from - // their own initialise() implementations. - - mProgramBound.fill(false); - } - - //--------------------------------------------------------------------------------------------- - void RenderSystem::useCustomRenderSystemCapabilities(RenderSystemCapabilities* capabilities) - { - if (mRealCapabilities) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Custom render capabilities must be set before the RenderSystem is initialised"); - } - - if (capabilities->getRenderSystemName() != getName()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Trying to use RenderSystemCapabilities that were created for a different RenderSystem"); - } - - mCurrentCapabilities = capabilities; - mUseCustomCapabilities = true; - } - - //--------------------------------------------------------------------------------------------- - RenderWindow* RenderSystem::_createRenderWindow(const String& name, unsigned int width, - unsigned int height, bool fullScreen, - const NameValuePairList* miscParams) - { - if (mRenderTargets.find(name) != mRenderTargets.end()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Window with name '" + name + "' already exists"); - } - - // Log a message - StringStream ss; - ss << "RenderSystem::_createRenderWindow \"" << name << "\", " << - width << "x" << height << " "; - if (fullScreen) - ss << "fullscreen "; - else - ss << "windowed "; - - if (miscParams) - { - ss << " miscParams: "; - NameValuePairList::const_iterator it; - for (const auto& p : *miscParams) - { - ss << p.first << "=" << p.second << " "; - } - } - LogManager::getSingleton().logMessage(ss.str()); - - return NULL; - } - //--------------------------------------------------------------------------------------------- - void RenderSystem::destroyRenderWindow(const String& name) - { - destroyRenderTarget(name); - } - //--------------------------------------------------------------------------------------------- - void RenderSystem::destroyRenderTexture(const String& name) - { - destroyRenderTarget(name); - } - //--------------------------------------------------------------------------------------------- - void RenderSystem::destroyRenderTarget(const String& name) - { - RenderTarget* rt = detachRenderTarget(name); - OGRE_DELETE rt; - } - //--------------------------------------------------------------------------------------------- - void RenderSystem::attachRenderTarget( RenderTarget &target ) - { - assert( target.getPriority() < OGRE_NUM_RENDERTARGET_GROUPS ); - - mRenderTargets.emplace(target.getName(), &target); - mPrioritisedRenderTargets.emplace(target.getPriority(), &target); - } - - //--------------------------------------------------------------------------------------------- - RenderTarget * RenderSystem::getRenderTarget( const String &name ) - { - RenderTargetMap::iterator it = mRenderTargets.find( name ); - RenderTarget *ret = NULL; - - if( it != mRenderTargets.end() ) - { - ret = it->second; - } - - return ret; - } - - //--------------------------------------------------------------------------------------------- - RenderTarget * RenderSystem::detachRenderTarget( const String &name ) - { - RenderTargetMap::iterator it = mRenderTargets.find( name ); - RenderTarget *ret = NULL; - - if( it != mRenderTargets.end() ) - { - ret = it->second; - - /* Remove the render target from the priority groups. */ - RenderTargetPriorityMap::iterator itarg, itargend; - itargend = mPrioritisedRenderTargets.end(); - for( itarg = mPrioritisedRenderTargets.begin(); itarg != itargend; ++itarg ) - { - if( itarg->second == ret ) { - mPrioritisedRenderTargets.erase( itarg ); - break; - } - } - - mRenderTargets.erase( it ); - } - /// If detached render target is the active render target, reset active render target - if(ret == mActiveRenderTarget) - mActiveRenderTarget = 0; - - return ret; - } - //----------------------------------------------------------------------- - Viewport* RenderSystem::_getViewport(void) - { - return mActiveViewport; - } - //----------------------------------------------------------------------- - void RenderSystem::_setTextureUnitSettings(size_t texUnit, TextureUnitState& tl) - { - if(texUnit >= getCapabilities()->getNumTextureUnits()) - return; - - // This method is only ever called to set a texture unit to valid details - // The method _disableTextureUnit is called to turn a unit off - TexturePtr tex = tl._getTexturePtr(); - if(!tex || tl.isTextureLoadFailing()) - tex = mTextureManager->_getWarningTexture(); - - if(tl.getUnorderedAccessMipLevel() > -1) - { - tex->createShaderAccessPoint(texUnit, TA_READ_WRITE, tl.getUnorderedAccessMipLevel()); - return; - } - - // Bind texture (may be blank) - _setTexture(texUnit, true, tex); - - _setSampler(texUnit, *tl.getSampler()); - - if(!getCapabilities()->hasCapability(RSC_FIXED_FUNCTION)) - return; - - // Set texture coordinate set - _setTextureCoordSet(texUnit, tl.getTextureCoordSet()); - - // Set blend modes - // Note, colour before alpha is important - _setTextureBlendMode(texUnit, tl.getColourBlendMode()); - _setTextureBlendMode(texUnit, tl.getAlphaBlendMode()); - - auto calcMode = tl._deriveTexCoordCalcMethod(); - if(calcMode == TEXCALC_PROJECTIVE_TEXTURE) - { - auto frustum = tl.getEffects().find(TextureUnitState::ET_PROJECTIVE_TEXTURE)->second.frustum; - _setTextureCoordCalculation(texUnit, calcMode, frustum); - } - else - { - _setTextureCoordCalculation(texUnit, calcMode); - } - - // Change tetxure matrix - _setTextureMatrix(texUnit, tl.getTextureTransform()); - } - //----------------------------------------------------------------------- - void RenderSystem::_disableTextureUnit(size_t texUnit) - { - _setTexture(texUnit, false, sNullTexPtr); - } - //--------------------------------------------------------------------- - void RenderSystem::_disableTextureUnitsFrom(size_t texUnit) - { - size_t disableTo = OGRE_MAX_TEXTURE_LAYERS; - if (disableTo > mDisabledTexUnitsFrom) - disableTo = mDisabledTexUnitsFrom; - mDisabledTexUnitsFrom = texUnit; - for (size_t i = texUnit; i < disableTo; ++i) - { - _disableTextureUnit(i); - } - } - //--------------------------------------------------------------------- - void RenderSystem::_cleanupDepthBuffers( bool bCleanManualBuffers ) - { - for (auto& m : mDepthBufferPool) - { - for (auto *b : m.second) - { - if (bCleanManualBuffers || !b->isManual()) - delete b; - } - m.second.clear(); - } - mDepthBufferPool.clear(); - } - //----------------------------------------------------------------------- - void RenderSystem::_beginFrame(void) - { - if (!mActiveViewport) - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Cannot begin frame - no viewport selected."); - } - //----------------------------------------------------------------------- - CullingMode RenderSystem::_getCullingMode(void) const - { - return mCullingMode; - } - //----------------------------------------------------------------------- - void RenderSystem::setDepthBufferFor( RenderTarget *renderTarget ) - { - uint16 poolId = renderTarget->getDepthBufferPool(); - if( poolId == DepthBuffer::POOL_NO_DEPTH ) - return; //RenderTarget explicitly requested no depth buffer - - //Find a depth buffer in the pool - bool bAttached = false; - for (auto& d : mDepthBufferPool[poolId]) { - bAttached = renderTarget->attachDepthBuffer(d); - if (bAttached) break; - } - - //Not found yet? Create a new one! - if( !bAttached ) - { - DepthBuffer *newDepthBuffer = _createDepthBufferFor( renderTarget ); - - if( newDepthBuffer ) - { - newDepthBuffer->_setPoolId( poolId ); - mDepthBufferPool[poolId].push_back( newDepthBuffer ); - - bAttached = renderTarget->attachDepthBuffer( newDepthBuffer ); - - OgreAssert( bAttached ,"A new DepthBuffer for a RenderTarget was created, but after creation" - " it says it's incompatible with that RT" ); - } - else - LogManager::getSingleton().logWarning( "Couldn't create a suited DepthBuffer" - "for RT: " + renderTarget->getName()); - } - } - //----------------------------------------------------------------------- - bool RenderSystem::isReverseDepthBufferEnabled() const - { - return mIsReverseDepthBufferEnabled; - } - //----------------------------------------------------------------------- - void RenderSystem::reinitialise() - { - shutdown(); - _initialise(); - } - - void RenderSystem::shutdown(void) - { - for (auto& q : mHwOcclusionQueries) - { - OGRE_DELETE q; - } - mHwOcclusionQueries.clear(); - - _cleanupDepthBuffers(); - - // Remove all the render targets. Destroy primary target last since others may depend on it. - // Keep mRenderTargets valid all the time, so that render targets could receive - // appropriate notifications, for example FBO based about GL context destruction. - RenderTarget* primary {nullptr}; - for (auto &&a : mRenderTargets) { - if (!primary && a.second->isPrimary()) { - primary = a.second; - continue; - } - OGRE_DELETE a.second; - mRenderTargets.erase(a.first); - } - OGRE_DELETE primary; - mRenderTargets.clear(); - - mPrioritisedRenderTargets.clear(); - } - - void RenderSystem::_setProjectionMatrix(Matrix4 m) - { - if (!mFixedFunctionParams) return; - - if (mActiveRenderTarget->requiresTextureFlipping()) - { - // Invert transformed y - m[1][0] = -m[1][0]; - m[1][1] = -m[1][1]; - m[1][2] = -m[1][2]; - m[1][3] = -m[1][3]; - } - - mFixedFunctionParams->setConstant(8, m); - applyFixedFunctionParams(mFixedFunctionParams, GPV_GLOBAL); - } - //----------------------------------------------------------------------- - void RenderSystem::_beginGeometryCount(void) - { - mBatchCount = mFaceCount = mVertexCount = 0; - - } - //----------------------------------------------------------------------- - unsigned int RenderSystem::_getFaceCount(void) const - { - return static_cast< unsigned int >( mFaceCount ); - } - //----------------------------------------------------------------------- - unsigned int RenderSystem::_getBatchCount(void) const - { - return static_cast< unsigned int >( mBatchCount ); - } - //----------------------------------------------------------------------- - unsigned int RenderSystem::_getVertexCount(void) const - { - return static_cast< unsigned int >( mVertexCount ); - } - //----------------------------------------------------------------------- - void RenderSystem::_render(const RenderOperation& op) - { - // Update stats - size_t val; - - if (op.useIndexes) - val = op.indexData->indexCount; - else - val = op.vertexData->vertexCount; - - size_t trueInstanceNum = std::max(op.numberOfInstances,1); - val *= trueInstanceNum; - - // account for a pass having multiple iterations - if (mCurrentPassIterationCount > 1) - val *= mCurrentPassIterationCount; - mCurrentPassIterationNum = 0; - - switch(op.operationType) - { - case RenderOperation::OT_TRIANGLE_LIST: - mFaceCount += (val / 3); - break; - case RenderOperation::OT_TRIANGLE_LIST_ADJ: - mFaceCount += (val / 6); - break; - case RenderOperation::OT_TRIANGLE_STRIP_ADJ: - mFaceCount += (val / 2 - 2); - break; - case RenderOperation::OT_TRIANGLE_STRIP: - case RenderOperation::OT_TRIANGLE_FAN: - mFaceCount += (val - 2); - break; - default: - break; - } - - mVertexCount += op.vertexData->vertexCount * trueInstanceNum; - mBatchCount += mCurrentPassIterationCount; - - // sort out clip planes - // have to do it here in case of matrix issues - if (mClipPlanesDirty) - { - setClipPlanesImpl(mClipPlanes); - mClipPlanesDirty = false; - } - } - //----------------------------------------------------------------------- - void RenderSystem::setInvertVertexWinding(bool invert) - { - mInvertVertexWinding = invert; - } - //----------------------------------------------------------------------- - bool RenderSystem::getInvertVertexWinding(void) const - { - return mInvertVertexWinding; - } - //--------------------------------------------------------------------- - void RenderSystem::setClipPlanes(const PlaneList& clipPlanes) - { - if (clipPlanes != mClipPlanes) - { - mClipPlanes = clipPlanes; - mClipPlanesDirty = true; - } - } - //----------------------------------------------------------------------- - void RenderSystem::_notifyCameraRemoved(const Camera* cam) - { - for (auto& rt : mRenderTargets) - { - auto target = rt.second; - target->_notifyCameraRemoved(cam); - } - } - - //--------------------------------------------------------------------- - bool RenderSystem::updatePassIterationRenderState(void) - { - if (mCurrentPassIterationCount <= 1) - return false; - - // Update derived depth bias - if (mDerivedDepthBias) - { - _setDepthBias(mDerivedDepthBiasBase + mDerivedDepthBiasMultiplier * mCurrentPassIterationNum, - mDerivedDepthBiasSlopeScale); - } - - --mCurrentPassIterationCount; - ++mCurrentPassIterationNum; - - const uint16 mask = GPV_PASS_ITERATION_NUMBER; - - for (int i = 0; i < GPT_COUNT; i++) - { - if (!mActiveParameters[i]) - continue; - mActiveParameters[i]->incPassIterationNumber(); - bindGpuProgramParameters(GpuProgramType(i), mActiveParameters[i], mask); - } - - return true; - } - - //----------------------------------------------------------------------- - void RenderSystem::setSharedListener(Listener* listener) - { - assert(msSharedEventListener == NULL || listener == NULL); // you can set or reset, but for safety not directly override - msSharedEventListener = listener; - } - //----------------------------------------------------------------------- - RenderSystem::Listener* RenderSystem::getSharedListener(void) - { - return msSharedEventListener; - } - //----------------------------------------------------------------------- - void RenderSystem::addListener(Listener* l) - { - mEventListeners.push_back(l); - } - //----------------------------------------------------------------------- - void RenderSystem::removeListener(Listener* l) - { - mEventListeners.remove(l); - } - //----------------------------------------------------------------------- - void RenderSystem::fireEvent(const String& name, const NameValuePairList* params) - { - for(auto& el : mEventListeners) - { - el->eventOccurred(name, params); - } - - if(msSharedEventListener) - msSharedEventListener->eventOccurred(name, params); - } - //----------------------------------------------------------------------- - void RenderSystem::destroyHardwareOcclusionQuery( HardwareOcclusionQuery *hq) - { - auto end = mHwOcclusionQueries.end(); - auto i = std::find(mHwOcclusionQueries.begin(), end, hq); - if (i != end) - { - mHwOcclusionQueries.erase(i); - OGRE_DELETE hq; - } - } - //----------------------------------------------------------------------- - void RenderSystem::bindGpuProgram(GpuProgram* prg) - { - auto gptype = prg->getType(); - // mark clip planes dirty if changed (programmable can change space) - if(gptype == GPT_VERTEX_PROGRAM && !mClipPlanes.empty() && !mProgramBound[gptype]) - mClipPlanesDirty = true; - - mProgramBound[gptype] = true; - } - //----------------------------------------------------------------------- - void RenderSystem::unbindGpuProgram(GpuProgramType gptype) - { - // mark clip planes dirty if changed (programmable can change space) - if(gptype == GPT_VERTEX_PROGRAM && !mClipPlanes.empty() && mProgramBound[gptype]) - mClipPlanesDirty = true; - - mProgramBound[gptype] = false; - } - //----------------------------------------------------------------------- - bool RenderSystem::isGpuProgramBound(GpuProgramType gptype) - { - return mProgramBound[gptype]; - } - //--------------------------------------------------------------------- - void RenderSystem::_setTextureProjectionRelativeTo(bool enabled, const Vector3& pos) - { - mTexProjRelative = enabled; - mTexProjRelativeOrigin = pos; - - } - //--------------------------------------------------------------------- - const String& RenderSystem::_getDefaultViewportMaterialScheme( void ) const - { -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS - if (!getCapabilities()->hasCapability(RSC_FIXED_FUNCTION)) - { - return MSN_SHADERGEN; - } -#endif - return MSN_DEFAULT; - } - //--------------------------------------------------------------------- - void RenderSystem::setGlobalInstanceVertexBuffer( const HardwareVertexBufferSharedPtr &val ) - { - OgreAssert(!val || val->isInstanceData(), "not an instance buffer"); - mGlobalInstanceVertexBuffer = val; - } - //--------------------------------------------------------------------- - void RenderSystem::getCustomAttribute(const String& name, void* pData) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Attribute not found.", "RenderSystem::getCustomAttribute"); - } - - void RenderSystem::initConfigOptions() - { - // FS setting possibilities - ConfigOption optFullScreen; - optFullScreen.name = "Full Screen"; - optFullScreen.possibleValues.push_back( "No" ); - optFullScreen.possibleValues.push_back( "Yes" ); - optFullScreen.currentValue = optFullScreen.possibleValues[0]; - optFullScreen.immutable = false; - mOptions[optFullScreen.name] = optFullScreen; - - // Video mode possibilities, can be overwritten by actual values - ConfigOption optVideoMode; - optVideoMode.name = "Video Mode"; - optVideoMode.possibleValues.push_back("1920 x 1080"); - optVideoMode.possibleValues.push_back("1280 x 720"); - optVideoMode.possibleValues.push_back("800 x 600"); - optVideoMode.currentValue = optVideoMode.possibleValues.back(); - optVideoMode.immutable = false; - mOptions[optVideoMode.name] = optVideoMode; - - ConfigOption optVSync; - optVSync.name = "VSync"; - optVSync.immutable = false; - optVSync.possibleValues.push_back("No"); - optVSync.possibleValues.push_back("Yes"); - optVSync.currentValue = optVSync.possibleValues[1]; - mOptions[optVSync.name] = optVSync; - - ConfigOption optVSyncInterval; - optVSyncInterval.name = "VSync Interval"; - optVSyncInterval.immutable = false; - optVSyncInterval.possibleValues.push_back("1"); - optVSyncInterval.possibleValues.push_back("2"); - optVSyncInterval.possibleValues.push_back("3"); - optVSyncInterval.possibleValues.push_back("4"); - optVSyncInterval.currentValue = optVSyncInterval.possibleValues[0]; - mOptions[optVSyncInterval.name] = optVSyncInterval; - - ConfigOption optSRGB; - optSRGB.name = "sRGB Gamma Conversion"; - optSRGB.immutable = false; - optSRGB.possibleValues.push_back("No"); - optSRGB.possibleValues.push_back("Yes"); - optSRGB.currentValue = optSRGB.possibleValues[0]; - mOptions[optSRGB.name] = optSRGB; - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - ConfigOption optStereoMode; - optStereoMode.name = "Frame Sequential Stereo"; - optStereoMode.possibleValues.push_back("Off"); - optStereoMode.possibleValues.push_back("On"); - optStereoMode.currentValue = optStereoMode.possibleValues[0]; - optStereoMode.immutable = false; - - mOptions[optStereoMode.name] = optStereoMode; -#endif - } - - CompareFunction RenderSystem::reverseCompareFunction(CompareFunction func) - { - switch(func) - { - default: - return func; - case CMPF_LESS: - return CMPF_GREATER; - case CMPF_LESS_EQUAL: - return CMPF_GREATER_EQUAL; - case CMPF_GREATER_EQUAL: - return CMPF_LESS_EQUAL; - case CMPF_GREATER: - return CMPF_LESS; - } - } - - bool RenderSystem::flipFrontFace() const - { - return mInvertVertexWinding != mActiveRenderTarget->requiresTextureFlipping(); - } - - void RenderSystem::setStencilCheckEnabled(bool enabled) - { - mStencilState.enabled = enabled; - if (!enabled) - setStencilState(mStencilState); - } - void RenderSystem::setStencilBufferParams(CompareFunction func, uint32 refValue, uint32 compareMask, - uint32 writeMask, StencilOperation stencilFailOp, - StencilOperation depthFailOp, StencilOperation passOp, - bool twoSidedOperation) - { - mStencilState.compareOp = func; - mStencilState.referenceValue = refValue; - mStencilState.compareMask = compareMask; - mStencilState.writeMask = writeMask; - mStencilState.stencilFailOp = stencilFailOp; - mStencilState.depthFailOp = depthFailOp; - mStencilState.depthStencilPassOp = passOp; - mStencilState.twoSidedOperation = twoSidedOperation; - if(mStencilState.enabled) - setStencilState(mStencilState); - } -} - diff --git a/OgreMain/src/OgreRenderSystemCapabilities.cpp b/OgreMain/src/OgreRenderSystemCapabilities.cpp deleted file mode 100644 index 6f6e3536409..00000000000 --- a/OgreMain/src/OgreRenderSystemCapabilities.cpp +++ /dev/null @@ -1,313 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreRenderSystemCapabilities.h" - -namespace Ogre { - - String DriverVersion::toString() const - { - StringStream str; - str << major << "." << minor << "." << release << "." << build; - return str.str(); - } - - void DriverVersion::fromString(const String& versionString) - { - StringVector tokens = StringUtil::split(versionString, "."); - if(!tokens.empty()) - { - major = StringConverter::parseInt(tokens[0]); - if (tokens.size() > 1) - minor = StringConverter::parseInt(tokens[1]); - if (tokens.size() > 2) - release = StringConverter::parseInt(tokens[2]); - if (tokens.size() > 3) - build = StringConverter::parseInt(tokens[3]); - } - } - - //----------------------------------------------------------------------- - RenderSystemCapabilities::RenderSystemCapabilities() - : mVendor(GPU_UNKNOWN) - , mNumTextureUnits(0) - , mStencilBufferBitDepth(8) - , mConstantFloatCount{} - , mNumMultiRenderTargets(1) - , mMaxPointSize(1) - , mNonPOW2TexturesLimited(false) - , mMaxSupportedAnisotropy(0) - , mGeometryProgramNumOutputVertices(0) - , mNumVertexAttributes(1) - { - for(int i = 0; i < CAPS_CATEGORY_COUNT; i++) - { - mCapabilities[i] = 0; - } - mCategoryRelevant[CAPS_CATEGORY_COMMON] = true; - mCategoryRelevant[CAPS_CATEGORY_COMMON_2] = true; - // each rendersystem should enable these - mCategoryRelevant[CAPS_CATEGORY_D3D9] = false; - mCategoryRelevant[CAPS_CATEGORY_GL] = false; - } - - void RenderSystemCapabilities::addShaderProfile(const String& profile) { mSupportedShaderProfiles.insert(profile); } - - void RenderSystemCapabilities::removeShaderProfile(const String& profile) - { - mSupportedShaderProfiles.erase(profile); - } - - bool RenderSystemCapabilities::isShaderProfileSupported(const String& profile) const - { - return (mSupportedShaderProfiles.end() != mSupportedShaderProfiles.find(profile)); - } - - //----------------------------------------------------------------------- - void RenderSystemCapabilities::log(Log* pLog) const - { - pLog->logMessage("RenderSystem capabilities"); - pLog->logMessage("-------------------------"); - pLog->logMessage("RenderSystem Name: " + getRenderSystemName()); - pLog->logMessage("GPU Vendor: " + vendorToString(getVendor())); - pLog->logMessage("Device Name: " + getDeviceName()); - pLog->logMessage("Driver Version: " + getDriverVersion().toString()); - pLog->logMessage(" * Fixed function pipeline: " + - StringConverter::toString(hasCapability(RSC_FIXED_FUNCTION), true)); - pLog->logMessage(" * 32-bit index buffers: " + StringConverter::toString(hasCapability(RSC_32BIT_INDEX), true)); - pLog->logMessage(" * Hardware stencil buffer: " + - StringConverter::toString(hasCapability(RSC_HWSTENCIL), true)); - if (hasCapability(RSC_HWSTENCIL)) - { - pLog->logMessage(" - Two sided stencil support: " + - StringConverter::toString(hasCapability(RSC_TWO_SIDED_STENCIL), true)); - pLog->logMessage(" - Wrap stencil values: " + - StringConverter::toString(hasCapability(RSC_STENCIL_WRAP), true)); - } - pLog->logMessage(" * Vertex programs: yes"); - pLog->logMessage(" - Number of constant 4-vectors: " + - StringConverter::toString(mConstantFloatCount[GPT_VERTEX_PROGRAM])); - pLog->logMessage(" * Fragment programs: yes"); - pLog->logMessage(" - Number of constant 4-vectors: " + - StringConverter::toString(mConstantFloatCount[GPT_FRAGMENT_PROGRAM])); - pLog->logMessage(" * Geometry programs: " + - StringConverter::toString(hasCapability(RSC_GEOMETRY_PROGRAM), true)); - if (hasCapability(RSC_GEOMETRY_PROGRAM)) - { - pLog->logMessage(" - Number of constant 4-vectors: " + - StringConverter::toString(mConstantFloatCount[GPT_GEOMETRY_PROGRAM])); - } - pLog->logMessage(" * Tessellation Hull programs: " + - StringConverter::toString(hasCapability(RSC_TESSELLATION_HULL_PROGRAM), true)); - if (hasCapability(RSC_TESSELLATION_HULL_PROGRAM)) - { - pLog->logMessage(" - Number of constant 4-vectors: " + - StringConverter::toString(mConstantFloatCount[GPT_HULL_PROGRAM])); - } - pLog->logMessage(" * Tessellation Domain programs: " + - StringConverter::toString(hasCapability(RSC_TESSELLATION_DOMAIN_PROGRAM), true)); - if (hasCapability(RSC_TESSELLATION_DOMAIN_PROGRAM)) - { - pLog->logMessage(" - Number of constant 4-vectors: " + - StringConverter::toString(mConstantFloatCount[GPT_DOMAIN_PROGRAM])); - } - pLog->logMessage(" * Compute programs: " + StringConverter::toString(hasCapability(RSC_COMPUTE_PROGRAM), true)); - if (hasCapability(RSC_COMPUTE_PROGRAM)) - { - pLog->logMessage(" - Number of constant 4-vectors: " + - StringConverter::toString(mConstantFloatCount[GPT_COMPUTE_PROGRAM])); - } - pLog->logMessage( - " * Supported Shader Profiles: " + - StringConverter::toString(StringVector(mSupportedShaderProfiles.begin(), mSupportedShaderProfiles.end()))); - pLog->logMessage(" * Read-back compiled shader: " + - StringConverter::toString(hasCapability(RSC_CAN_GET_COMPILED_SHADER_BUFFER), true)); - pLog->logMessage(" * Number of vertex attributes: " + StringConverter::toString(mNumVertexAttributes)); - pLog->logMessage(" * Textures"); - pLog->logMessage(" - Number of texture units: " + StringConverter::toString(mNumTextureUnits)); - pLog->logMessage(" - Floating point: " + StringConverter::toString(hasCapability(RSC_TEXTURE_FLOAT), true)); - pLog->logMessage( - " - Non-power-of-two: " + StringConverter::toString(hasCapability(RSC_NON_POWER_OF_2_TEXTURES), true) + - (mNonPOW2TexturesLimited ? " (limited)" : "")); - pLog->logMessage(" - 1D textures: " + StringConverter::toString(hasCapability(RSC_TEXTURE_1D), true)); - pLog->logMessage(" - 2D array textures: " + StringConverter::toString(hasCapability(RSC_TEXTURE_2D_ARRAY), true)); - pLog->logMessage(" - 3D textures: " + StringConverter::toString(hasCapability(RSC_TEXTURE_3D), true)); - pLog->logMessage(" - Anisotropic filtering: " + StringConverter::toString(hasCapability(RSC_ANISOTROPY), true)); - - pLog->logMessage( - " * Texture Compression: " - + StringConverter::toString(hasCapability(RSC_TEXTURE_COMPRESSION), true)); - if (hasCapability(RSC_TEXTURE_COMPRESSION)) - { - pLog->logMessage(" - DXT: " + - StringConverter::toString(hasCapability(RSC_TEXTURE_COMPRESSION_DXT), true)); - pLog->logMessage(" - VTC: " + - StringConverter::toString(hasCapability(RSC_TEXTURE_COMPRESSION_VTC), true)); - pLog->logMessage(" - PVRTC: " + - StringConverter::toString(hasCapability(RSC_TEXTURE_COMPRESSION_PVRTC), true)); - pLog->logMessage(" - ATC: " + - StringConverter::toString(hasCapability(RSC_TEXTURE_COMPRESSION_ATC), true)); - pLog->logMessage(" - ETC1: " + - StringConverter::toString(hasCapability(RSC_TEXTURE_COMPRESSION_ETC1), true)); - pLog->logMessage(" - ETC2: " + - StringConverter::toString(hasCapability(RSC_TEXTURE_COMPRESSION_ETC2), true)); - pLog->logMessage(" - BC4/BC5: " + - StringConverter::toString(hasCapability(RSC_TEXTURE_COMPRESSION_BC4_BC5), true)); - pLog->logMessage(" - BC6H/BC7: " + - StringConverter::toString(hasCapability(RSC_TEXTURE_COMPRESSION_BC6H_BC7), true)); - pLog->logMessage(" - ASTC: " + - StringConverter::toString(hasCapability(RSC_TEXTURE_COMPRESSION_ASTC), true)); - pLog->logMessage(" - Automatic mipmap generation: " + - StringConverter::toString(hasCapability(RSC_AUTOMIPMAP_COMPRESSED), true)); - } - - pLog->logMessage(" * Vertex Buffers"); - pLog->logMessage(" - Render to Vertex Buffer: " + - StringConverter::toString(hasCapability(RSC_HWRENDER_TO_VERTEX_BUFFER), true)); - pLog->logMessage(" - Instance Data: " + - StringConverter::toString(hasCapability(RSC_VERTEX_BUFFER_INSTANCE_DATA), true)); - pLog->logMessage(" - Primitive Restart: " + - StringConverter::toString(hasCapability(RSC_PRIMITIVE_RESTART), true)); - pLog->logMessage(" - INT_10_10_10_2_NORM element type: " + - StringConverter::toString(hasCapability(RSC_VERTEX_FORMAT_INT_10_10_10_2), true)); - pLog->logMessage(" * Vertex texture fetch: " + - StringConverter::toString(hasCapability(RSC_VERTEX_TEXTURE_FETCH), true)); - if (hasCapability(RSC_VERTEX_TEXTURE_FETCH)) - { - pLog->logMessage(" - Max vertex textures: " + StringConverter::toString(mNumVertexTextureUnits)); - } - pLog->logMessage(" * Read/Write Buffers: " + - StringConverter::toString(hasCapability(RSC_READ_WRITE_BUFFERS), true)); - pLog->logMessage( - " * Hardware Occlusion Query: " - + StringConverter::toString(hasCapability(RSC_HWOCCLUSION), true)); - pLog->logMessage( - " * User clip planes: " - + StringConverter::toString(hasCapability(RSC_USER_CLIP_PLANES), true)); - pLog->logMessage( - " * Depth clamping: " - + StringConverter::toString(hasCapability(RSC_DEPTH_CLAMP), true)); - pLog->logMessage( - " * Hardware render-to-texture: " - + StringConverter::toString(hasCapability(RSC_HWRENDER_TO_TEXTURE), true)); - pLog->logMessage(" - Multiple Render Targets: " + StringConverter::toString(mNumMultiRenderTargets)); - pLog->logMessage(" * Point Sprites: " + StringConverter::toString(hasCapability(RSC_POINT_SPRITES), true)); - if (hasCapability(RSC_POINT_SPRITES)) - { - pLog->logMessage(" - Max Size: " + StringConverter::toString(mMaxPointSize)); - } - pLog->logMessage( - " * Wide Lines: " - + StringConverter::toString(hasCapability(RSC_WIDE_LINES), true)); - pLog->logMessage( - " * Hardware Gamma: " - + StringConverter::toString(hasCapability(RSC_HW_GAMMA), true)); - if (mCategoryRelevant[CAPS_CATEGORY_GL]) - { - pLog->logMessage( - " * PBuffer support: " - + StringConverter::toString(hasCapability(RSC_PBUFFER), true)); - pLog->logMessage( - " * Vertex Array Objects: " - + StringConverter::toString(hasCapability(RSC_VAO), true)); - pLog->logMessage(" * Separate shader objects: " + - StringConverter::toString(hasCapability(RSC_SEPARATE_SHADER_OBJECTS), true)); - pLog->logMessage(" - redeclare GLSL interface block: " + - StringConverter::toString(hasCapability(RSC_GLSL_SSO_REDECLARE), true)); - pLog->logMessage( - " * Debugging/ profiling events: " - + StringConverter::toString(hasCapability(RSC_DEBUG), true)); - pLog->logMessage( - " * Map buffer storage: " - + StringConverter::toString(hasCapability(RSC_MAPBUFFER), true)); - } - - if (mCategoryRelevant[CAPS_CATEGORY_D3D9]) - { - pLog->logMessage( - " * DirectX per stage constants: " - + StringConverter::toString(hasCapability(RSC_PERSTAGECONSTANT), true)); - pLog->logMessage( - " * W-Buffer supported: " - + StringConverter::toString(hasCapability(RSC_WBUFFER), true)); - pLog->logMessage(" * Multiple Render Targets must have same bit depth: " + - StringConverter::toString(hasCapability(RSC_MRT_SAME_BIT_DEPTHS), true)); - } - } - //--------------------------------------------------------------------- - String RenderSystemCapabilities::msGPUVendorStrings[GPU_VENDOR_COUNT]; - //--------------------------------------------------------------------- - GPUVendor RenderSystemCapabilities::vendorFromString(const String& vendorString) - { - initVendorStrings(); - GPUVendor ret = GPU_UNKNOWN; - String cmpString = vendorString; - StringUtil::toLowerCase(cmpString); - for (int i = 0; i < GPU_VENDOR_COUNT; ++i) - { - // case insensitive (lower case) - if (msGPUVendorStrings[i] == cmpString) - { - ret = static_cast(i); - break; - } - } - - return ret; - - } - //--------------------------------------------------------------------- - const String& RenderSystemCapabilities::vendorToString(GPUVendor v) - { - initVendorStrings(); - return msGPUVendorStrings[v]; - } - //--------------------------------------------------------------------- - void RenderSystemCapabilities::initVendorStrings() - { - if (msGPUVendorStrings[0].empty()) - { - // Always lower case! - msGPUVendorStrings[GPU_UNKNOWN] = "unknown"; - msGPUVendorStrings[GPU_NVIDIA] = "nvidia"; - msGPUVendorStrings[GPU_AMD] = "amd"; - msGPUVendorStrings[GPU_INTEL] = "intel"; - msGPUVendorStrings[GPU_IMAGINATION_TECHNOLOGIES] = "imagination technologies"; - msGPUVendorStrings[GPU_APPLE] = "apple"; // iOS Simulator - msGPUVendorStrings[GPU_NOKIA] = "nokia"; - msGPUVendorStrings[GPU_MS_SOFTWARE] = "microsoft"; // Microsoft software device - msGPUVendorStrings[GPU_MS_WARP] = "ms warp"; - msGPUVendorStrings[GPU_ARM] = "arm"; - msGPUVendorStrings[GPU_QUALCOMM] = "qualcomm"; - msGPUVendorStrings[GPU_MOZILLA] = "mozilla"; - msGPUVendorStrings[GPU_WEBKIT] = "webkit"; - } - } - -} diff --git a/OgreMain/src/OgreRenderSystemCapabilitiesManager.cpp b/OgreMain/src/OgreRenderSystemCapabilitiesManager.cpp deleted file mode 100644 index 17672a924e7..00000000000 --- a/OgreMain/src/OgreRenderSystemCapabilitiesManager.cpp +++ /dev/null @@ -1,133 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreRenderSystemCapabilitiesManager.h" -#include "OgreRenderSystemCapabilitiesSerializer.h" -#include "OgreConfigFile.h" -#include "OgreFileSystemLayer.h" - -namespace Ogre { - - //----------------------------------------------------------------------- - template<> RenderSystemCapabilitiesManager* Singleton::msSingleton = 0; - RenderSystemCapabilitiesManager* RenderSystemCapabilitiesManager::getSingletonPtr(void) - { - return msSingleton; - } - RenderSystemCapabilitiesManager& RenderSystemCapabilitiesManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - - //----------------------------------------------------------------------- - RenderSystemCapabilitiesManager::RenderSystemCapabilitiesManager() : mSerializer(0), mScriptPattern("*.rendercaps") - { - mSerializer = OGRE_NEW RenderSystemCapabilitiesSerializer(); - } - //----------------------------------------------------------------------- - RenderSystemCapabilitiesManager::~RenderSystemCapabilitiesManager() - { - for (auto& cm : mCapabilitiesMap) - { - // free memory in RenderSystemCapabilities* - OGRE_DELETE cm.second; - } - - OGRE_DELETE mSerializer; - } - - RenderSystemCapabilities* RenderSystemCapabilitiesManager::loadCapabilitiesConfig(const String& customConfig) - { - ConfigFile cfg; - cfg.load(customConfig, "\t:=", false); - - // resolve relative path with regards to configfile - String baseDir, unused; - StringUtil::splitFilename(customConfig, unused, baseDir); - - // Capabilities Database setting must be in the same format as - // resources.cfg in Ogre examples. - for(auto& it : cfg.getSettings("Capabilities Database")) - { - String filename = it.second; - if(filename.empty() || filename[0] == '.') - filename = baseDir + it.second; - - filename = FileSystemLayer::resolveBundlePath(filename); - parseCapabilitiesFromArchive(filename, it.first, true); - } - - String capsName = cfg.getSetting("Custom Capabilities"); - // The custom capabilities have been parsed, let's retrieve them - RenderSystemCapabilities* rsc = loadParsedCapabilities(capsName); - if (rsc == 0) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Cannot load a RenderSystemCapability named '" + capsName + "'"); - } - - return rsc; - } - - //----------------------------------------------------------------------- - void RenderSystemCapabilitiesManager::parseCapabilitiesFromArchive(const String& filename, const String& archiveType, bool recursive) - { - // get the list of .rendercaps files - Archive* arch = ArchiveManager::getSingleton().load(filename, archiveType, true); - StringVectorPtr files = arch->find(mScriptPattern, recursive); - - // loop through .rendercaps files and load each one - for (auto& f : *files) - { - DataStreamPtr stream = arch->open(f); - mSerializer->parseScript(stream); - stream->close(); - } - } - - RenderSystemCapabilities* RenderSystemCapabilitiesManager::loadParsedCapabilities(const String& name) - { - return mCapabilitiesMap[name]; - } - - const std::map &RenderSystemCapabilitiesManager::getCapabilities() const - { - return mCapabilitiesMap; - } - - /** Method used by RenderSystemCapabilitiesSerializer::parseScript */ - void RenderSystemCapabilitiesManager::_addRenderSystemCapabilities(const String& name, RenderSystemCapabilities* caps) - { - mCapabilitiesMap.emplace(name, caps); - } -} - - - - - diff --git a/OgreMain/src/OgreRenderSystemCapabilitiesSerializer.cpp b/OgreMain/src/OgreRenderSystemCapabilitiesSerializer.cpp deleted file mode 100644 index f8315f1acb7..00000000000 --- a/OgreMain/src/OgreRenderSystemCapabilitiesSerializer.cpp +++ /dev/null @@ -1,474 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreRenderSystemCapabilitiesSerializer.h" -#include "OgreRenderSystemCapabilitiesManager.h" -#include "OgreRenderSystemCapabilities.h" - -namespace Ogre -{ - - RenderSystemCapabilitiesSerializer::RenderSystemCapabilitiesSerializer() : mCurrentLineNumber(0), mCurrentLine(0), - mCurrentCapabilities(0) - { - initialiaseDispatchTables(); - } - - //----------------------------------------------------------------------- - void RenderSystemCapabilitiesSerializer::write(const RenderSystemCapabilities* caps, const String &name, std::ostream &file) - { - using namespace std; - - file << "render_system_capabilities \"" << name << "\"" << endl; - file << "{" << endl; - - file << "\t" << "render_system_name " << caps->getRenderSystemName() << endl; - file << endl; - - - file << "\t" << "device_name " << caps->getDeviceName() << endl; - const DriverVersion& driverVer = caps->getDriverVersion(); - file << "\t" << "driver_version " << driverVer.toString() << endl; - file << "\t" << "vendor " << caps->vendorToString(caps->getVendor()); - - file << endl; - - file << endl; - - for(auto & it : mCapabilitiesMap) { - file << "\t" << it.first << " " << StringConverter::toString(caps->hasCapability(it.second)) << endl; - } - - file << endl; - - RenderSystemCapabilities::ShaderProfiles profiles = caps->getSupportedShaderProfiles(); - // write every profile - for(const auto & profile : profiles) - { - file << "\t" << "shader_profile " << profile << endl; - } - - file << endl; - file << "\t" << "max_point_size " << StringConverter::toString(caps->getMaxPointSize()) << endl; - - file << endl; - file << "\t" << "non_pow2_textures_limited " << StringConverter::toString(caps->getNonPOW2TexturesLimited()) << endl; - - file << endl; - file << "\t" << "num_texture_units " << StringConverter::toString(caps->getNumTextureUnits()) << endl; - file << "\t" << "num_multi_render_targets " << StringConverter::toString(caps->getNumMultiRenderTargets()) << endl; - file << "\t" << "vertex_program_constant_float_count " << StringConverter::toString(caps->getConstantFloatCount(GPT_VERTEX_PROGRAM)) << endl; - file << "\t" << "fragment_program_constant_float_count " << StringConverter::toString(caps->getConstantFloatCount(GPT_FRAGMENT_PROGRAM)) << endl; - file << "\t" << "geometry_program_constant_float_count " << StringConverter::toString(caps->getConstantFloatCount(GPT_GEOMETRY_PROGRAM)) << endl; - file << "\t" << "tessellation_hull_program_constant_float_count " << StringConverter::toString(caps->getConstantFloatCount(GPT_HULL_PROGRAM)) << endl; - file << "\t" << "tessellation_domain_program_constant_float_count " << StringConverter::toString(caps->getConstantFloatCount(GPT_DOMAIN_PROGRAM)) << endl; - file << "\t" << "compute_program_constant_float_count " << StringConverter::toString(caps->getConstantFloatCount(GPT_COMPUTE_PROGRAM)) << endl; - file << "\t" << "num_vertex_texture_units " << StringConverter::toString(caps->getNumVertexTextureUnits()) << endl; - file << "\t" << "num_vertex_attributes " << StringConverter::toString(caps->getNumVertexAttributes()) << endl; - - file << endl; - - file << "}" << endl; - } - - //----------------------------------------------------------------------- - void RenderSystemCapabilitiesSerializer::writeScript(const RenderSystemCapabilities* caps, const String &name, const String& filename) - { - using namespace std; - - ofstream file(filename.c_str()); - - write(caps, name, file); - - file.close(); - } - - //----------------------------------------------------------------------- - String RenderSystemCapabilitiesSerializer::writeString(const RenderSystemCapabilities* caps, const String &name) - { - using namespace std; - - stringstream stream; - - write(caps, name, stream); - - return stream.str(); - } - - //----------------------------------------------------------------------- - void RenderSystemCapabilitiesSerializer::parseScript(DataStreamPtr& stream) - { - // reset parsing data to NULL - mCurrentLineNumber = 0; - mCurrentLine = 0; - mCurrentStream.reset(); - mCurrentCapabilities = 0; - - mCurrentStream = stream; - - // parser operating data - String line; - ParseAction parseAction = PARSE_HEADER; - StringVector tokens; - bool parsedAtLeastOneRSC = false; - - // collect capabilities lines (i.e. everything that is not header, "{", "}", - // comment or empty line) for further processing - CapabilitiesLinesList capabilitiesLines; - - // for reading data - char tmpBuf[OGRE_STREAM_TEMP_SIZE]; - - - // TODO: build a smarter tokenizer so that "{" and "}" - // don't need separate lines - while (!stream->eof()) - { - stream->readLine(tmpBuf, OGRE_STREAM_TEMP_SIZE-1); - line = String(tmpBuf); - StringUtil::trim(line); - - // keep track of parse position - mCurrentLine = &line; - mCurrentLineNumber++; - - tokens = StringUtil::split(line); - - // skip empty and comment lines - // TODO: handle end of line comments - if (tokens[0] == "" || tokens[0].substr(0,2) == "//") - continue; - - switch (parseAction) - { - // header line must look like this: - // render_system_capabilities "Vendor Card Name Version xx.xxx" - - case PARSE_HEADER: - - if(tokens[0] != "render_system_capabilities") - { - logParseError("The first keyword must be render_system_capabilities. RenderSystemCapabilities NOT created!"); - return; - } - else - { - // the rest of the tokens are irrevelant, beause everything between "..." is one name - String rscName = line.substr(tokens[0].size()); - StringUtil::trim(rscName); - - // the second argument must be a "" delimited string - if (!StringUtil::match(rscName, "\"*\"")) - { - logParseError("The argument to render_system_capabilities must be a quote delimited (\"...\") string. RenderSystemCapabilities NOT created!"); - return; - } - else - { - // we have a valid header - - // remove quotes - rscName = rscName.substr(1); - rscName = rscName.substr(0, rscName.size() - 1); - - // create RSC - mCurrentCapabilities = OGRE_NEW RenderSystemCapabilities(); - // RSCManager is responsible for deleting mCurrentCapabilities - RenderSystemCapabilitiesManager::getSingleton()._addRenderSystemCapabilities(rscName, mCurrentCapabilities); - - LogManager::getSingleton().logMessage("Created RenderSystemCapabilities" + rscName); - - // do next action - parseAction = FIND_OPEN_BRACE; - parsedAtLeastOneRSC = true; - } - } - - break; - - case FIND_OPEN_BRACE: - if (tokens[0] != "{" || tokens.size() != 1) - { - logParseError("Expected '{' got: " + line + ". Continuing to next line."); - } - else - { - parseAction = COLLECT_LINES; - } - - break; - - case COLLECT_LINES: - if (tokens[0] == "}") - { - // this render_system_capabilities section is over - // let's process the data and look for the next one - parseCapabilitiesLines(capabilitiesLines); - capabilitiesLines.clear(); - parseAction = PARSE_HEADER; - - } - else - capabilitiesLines.push_back(CapabilitiesLinesList::value_type(line, mCurrentLineNumber)); - break; - - } - } - - // Datastream is empty - // if we are still looking for header, this means that we have either - // finished reading one, or this is an empty file - if(parseAction == PARSE_HEADER && parsedAtLeastOneRSC == false) - { - logParseError ("The file is empty"); - } - if(parseAction == FIND_OPEN_BRACE) - - { - logParseError ("Bad .rendercaps file. Were not able to find a '{'"); - } - if(parseAction == COLLECT_LINES) - { - logParseError ("Bad .rendercaps file. Were not able to find a '}'"); - } - - } - - void RenderSystemCapabilitiesSerializer::initialiaseDispatchTables() - { - // set up driver version parsing - addKeywordType("driver_version", SET_STRING_METHOD); - // set up the setters for driver versions - addSetStringMethod("driver_version", &RenderSystemCapabilities::parseDriverVersionFromString); - - // set up device name parsing - addKeywordType("device_name", SET_STRING_METHOD); - // set up the setters for device names - addSetStringMethod("device_name", &RenderSystemCapabilities::setDeviceName); - - // set up render system name parsing - addKeywordType("render_system_name", SET_STRING_METHOD); - // set up the setters - addSetStringMethod("render_system_name", &RenderSystemCapabilities::setRenderSystemName); - - // set up vendor parsing - addKeywordType("vendor", SET_STRING_METHOD); - // set up the setters for driver versions - addSetStringMethod("vendor", &RenderSystemCapabilities::parseVendorFromString); - - // initialize int types - addKeywordType("num_world_matrices", SET_INT_METHOD); - addKeywordType("num_texture_units", SET_INT_METHOD); - addKeywordType("stencil_buffer_bit_depth", SET_INT_METHOD); - addKeywordType("num_vertex_blend_matrices", SET_INT_METHOD); - addKeywordType("num_multi_render_targets", SET_INT_METHOD); - addKeywordType("vertex_program_constant_float_count", SET_INT_METHOD); - addKeywordType("vertex_program_constant_int_count", SET_INT_METHOD); - addKeywordType("vertex_program_constant_bool_count", SET_INT_METHOD); - addKeywordType("fragment_program_constant_float_count", SET_INT_METHOD); - addKeywordType("fragment_program_constant_int_count", SET_INT_METHOD); - addKeywordType("fragment_program_constant_bool_count", SET_INT_METHOD); - addKeywordType("geometry_program_constant_float_count", SET_INT_METHOD); - addKeywordType("geometry_program_constant_int_count", SET_INT_METHOD); - addKeywordType("geometry_program_constant_bool_count", SET_INT_METHOD); - addKeywordType("tessellation_hull_program_constant_float_count", SET_INT_METHOD); - addKeywordType("tessellation_hull_program_constant_int_count", SET_INT_METHOD); - addKeywordType("tessellation_hull_program_constant_bool_count", SET_INT_METHOD); - addKeywordType("tessellation_domain_program_constant_float_count", SET_INT_METHOD); - addKeywordType("tessellation_domain_program_constant_int_count", SET_INT_METHOD); - addKeywordType("tessellation_domain_program_constant_bool_count", SET_INT_METHOD); - addKeywordType("compute_program_constant_float_count", SET_INT_METHOD); - addKeywordType("compute_program_constant_int_count", SET_INT_METHOD); - addKeywordType("compute_program_constant_bool_count", SET_INT_METHOD); - addKeywordType("num_vertex_texture_units", SET_INT_METHOD); - - // initialize int setters - addSetIntMethod("num_texture_units", &RenderSystemCapabilities::setNumTextureUnits); - addSetIntMethod("stencil_buffer_bit_depth", &RenderSystemCapabilities::setStencilBufferBitDepth); - addSetIntMethod("num_multi_render_targets", &RenderSystemCapabilities::setNumMultiRenderTargets); - addSetIntMethod("vertex_program_constant_float_count", &RenderSystemCapabilities::setVertexProgramConstantFloatCount); - addSetIntMethod("fragment_program_constant_float_count", &RenderSystemCapabilities::setFragmentProgramConstantFloatCount); - addSetIntMethod("geometry_program_constant_float_count", &RenderSystemCapabilities::setGeometryProgramConstantFloatCount); - addSetIntMethod("tessellation_hull_program_constant_float_count", &RenderSystemCapabilities::setTessellationHullProgramConstantFloatCount); - addSetIntMethod("tessellation_domain_program_constant_float_count", &RenderSystemCapabilities::setTessellationDomainProgramConstantFloatCount); - addSetIntMethod("compute_program_constant_float_count", &RenderSystemCapabilities::setComputeProgramConstantFloatCount); - addSetIntMethod("num_vertex_texture_units", &RenderSystemCapabilities::setNumVertexTextureUnits); - - // initialize bool types - addKeywordType("non_pow2_textures_limited", SET_BOOL_METHOD); - - // initialize bool setters - addSetBoolMethod("non_pow2_textures_limited", &RenderSystemCapabilities::setNonPOW2TexturesLimited); - - // initialize Real types - addKeywordType("max_point_size", SET_REAL_METHOD); - - // initialize Real setters - addSetRealMethod("max_point_size", &RenderSystemCapabilities::setMaxPointSize); - - // there is no dispatch table for shader profiles, just the type - addKeywordType("shader_profile", ADD_SHADER_PROFILE_STRING); - - addCapabilitiesMapping("fixed_function", RSC_FIXED_FUNCTION); - addCapabilitiesMapping("anisotropy", RSC_ANISOTROPY); - addCapabilitiesMapping("hwstencil", RSC_HWSTENCIL); - addCapabilitiesMapping("32bit_index", RSC_32BIT_INDEX); - addCapabilitiesMapping("vertex_program", RSC_VERTEX_PROGRAM); - addCapabilitiesMapping("geometry_program", RSC_GEOMETRY_PROGRAM); - addCapabilitiesMapping("tessellation_hull_program", RSC_TESSELLATION_HULL_PROGRAM); - addCapabilitiesMapping("tessellation_domain_program", RSC_TESSELLATION_DOMAIN_PROGRAM); - addCapabilitiesMapping("compute_program", RSC_COMPUTE_PROGRAM); - addCapabilitiesMapping("two_sided_stencil", RSC_TWO_SIDED_STENCIL); - addCapabilitiesMapping("stencil_wrap", RSC_STENCIL_WRAP); - addCapabilitiesMapping("hwocclusion", RSC_HWOCCLUSION); - addCapabilitiesMapping("user_clip_planes", RSC_USER_CLIP_PLANES); - addCapabilitiesMapping("hwrender_to_texture", RSC_HWRENDER_TO_TEXTURE); - addCapabilitiesMapping("texture_float", RSC_TEXTURE_FLOAT); - addCapabilitiesMapping("non_power_of_2_textures", RSC_NON_POWER_OF_2_TEXTURES); - addCapabilitiesMapping("texture_3d", RSC_TEXTURE_3D); - addCapabilitiesMapping("texture_2d_array", RSC_TEXTURE_3D); - addCapabilitiesMapping("texture_1d", RSC_TEXTURE_1D); - addCapabilitiesMapping("point_sprites", RSC_POINT_SPRITES); - addCapabilitiesMapping("wide_lines", RSC_WIDE_LINES); - addCapabilitiesMapping("vertex_texture_fetch", RSC_VERTEX_TEXTURE_FETCH); - addCapabilitiesMapping("mipmap_lod_bias", RSC_MIPMAP_LOD_BIAS); - addCapabilitiesMapping("atomic_counters", RSC_READ_WRITE_BUFFERS); - addCapabilitiesMapping("texture_compression", RSC_TEXTURE_COMPRESSION); - addCapabilitiesMapping("texture_compression_dxt", RSC_TEXTURE_COMPRESSION_DXT); - addCapabilitiesMapping("texture_compression_vtc", RSC_TEXTURE_COMPRESSION_VTC); - addCapabilitiesMapping("texture_compression_pvrtc", RSC_TEXTURE_COMPRESSION_PVRTC); - addCapabilitiesMapping("texture_compression_atc", RSC_TEXTURE_COMPRESSION_ATC); - addCapabilitiesMapping("texture_compression_etc1", RSC_TEXTURE_COMPRESSION_ETC1); - addCapabilitiesMapping("texture_compression_etc2", RSC_TEXTURE_COMPRESSION_ETC2); - addCapabilitiesMapping("texture_compression_bc4_bc5", RSC_TEXTURE_COMPRESSION_BC4_BC5); - addCapabilitiesMapping("texture_compression_bc6h_bc7", RSC_TEXTURE_COMPRESSION_BC6H_BC7); - addCapabilitiesMapping("texture_compression_astc", RSC_TEXTURE_COMPRESSION_ASTC); - addCapabilitiesMapping("hwrender_to_vertex_buffer", RSC_HWRENDER_TO_VERTEX_BUFFER); - - addCapabilitiesMapping("pbuffer", RSC_PBUFFER); - addCapabilitiesMapping("perstageconstant", RSC_PERSTAGECONSTANT); - addCapabilitiesMapping("vao", RSC_VAO); - addCapabilitiesMapping("separate_shader_objects", RSC_SEPARATE_SHADER_OBJECTS); - addCapabilitiesMapping("glsl_sso_redeclare", RSC_GLSL_SSO_REDECLARE); - addCapabilitiesMapping("debug", RSC_DEBUG); - addCapabilitiesMapping("mapbuffer", RSC_MAPBUFFER); - addCapabilitiesMapping("automipmap_compressed", RSC_AUTOMIPMAP_COMPRESSED); - } - - void RenderSystemCapabilitiesSerializer::parseCapabilitiesLines(CapabilitiesLinesList& lines) - { - StringVector tokens; - - for (auto & line : lines) - { - // restore the current line information for debugging - mCurrentLine = &(line.first); - mCurrentLineNumber = line.second; - - tokens = StringUtil::split(line.first); - // check for incomplete lines - if(tokens.size() < 2) - { - logParseError("No parameters given for the capability keyword"); - continue; - } - - // the first token must the the keyword identifying the capability - // the remaining tokens are the parameters - String keyword = tokens[0]; - String everythingElse = ""; - for(unsigned int i = 1; i < tokens.size() - 1; i ++) - { - everythingElse = everythingElse + tokens[i] + " "; - } - everythingElse = everythingElse + tokens[tokens.size() - 1]; - - CapabilityKeywordType keywordType = getKeywordType(keyword); - - switch(keywordType) - { - case UNDEFINED_CAPABILITY_TYPE: - logParseError("Unknown capability keyword: " + keyword); - break; - case SET_STRING_METHOD: - callSetStringMethod(keyword, everythingElse); - break; - case SET_INT_METHOD: - { - ushort integer = (ushort)StringConverter::parseInt(tokens[1]); - callSetIntMethod(keyword, integer); - break; - } - case SET_BOOL_METHOD: - { - bool b = StringConverter::parseBool(tokens[1]); - callSetBoolMethod(keyword, b); - break; - } - case SET_REAL_METHOD: - { - Real real = StringConverter::parseReal(tokens[1]); - callSetRealMethod(keyword, real); - break; - } - case ADD_SHADER_PROFILE_STRING: - { - addShaderProfile(tokens[1]); - break; - } - case SET_CAPABILITY_ENUM_BOOL: - { - bool b = StringConverter::parseBool(tokens[1]); - setCapabilityEnumBool(tokens[0], b); - break; - } - } - } - } - - void RenderSystemCapabilitiesSerializer::logParseError(const String& error) const - { - // log the line with error in it if the current line is available - if (mCurrentLine != 0 && mCurrentStream) - { - LogManager::getSingleton().logMessage( - "Error in .rendercaps " + mCurrentStream->getName() + ":" + StringConverter::toString(mCurrentLineNumber) + - " : " + error); - } - else if (mCurrentStream) - { - LogManager::getSingleton().logMessage( - "Error in .rendercaps " + mCurrentStream->getName() + - " : " + error); - } - } - -} - - diff --git a/OgreMain/src/OgreRenderTarget.cpp b/OgreMain/src/OgreRenderTarget.cpp deleted file mode 100644 index 7792538f633..00000000000 --- a/OgreMain/src/OgreRenderTarget.cpp +++ /dev/null @@ -1,544 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreRenderTarget.h" - -#include "OgreViewport.h" -#include "OgreRenderTargetListener.h" -#include "OgreDepthBuffer.h" -#include "OgreTimer.h" - -namespace Ogre { - - RenderTarget::RenderTarget() - : mPriority(OGRE_DEFAULT_RT_GROUP) - , mDepthBufferPoolId(DepthBuffer::POOL_DEFAULT) - , mDepthBuffer(0) - , mActive(true) - , mAutoUpdate(true) - , mHwGamma(false) - , mFSAA(0) -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - , mStereoEnabled(true) -#else - , mStereoEnabled(false) -#endif - { - mTimer = Root::getSingleton().getTimer(); - resetStatistics(); - } - - RenderTarget::~RenderTarget() - { - // make a copy of the list to avoid crashes, the viewport destructor change the list - ViewportList vlist = mViewportList; - - // Delete viewports - for (auto & i : vlist) - { - fireViewportRemoved(i.second); - OGRE_DELETE i.second; - } - - //DepthBuffer keeps track of us, avoid a dangling pointer - detachDepthBuffer(); - - - // Write closing message - LogManager::getSingleton().stream(LML_TRIVIAL) - << "Render Target '" << mName << "' " - << "Average FPS: " << mStats.avgFPS << " " - << "Best FPS: " << mStats.bestFPS << " " - << "Worst FPS: " << mStats.worstFPS; - - } - - const String& RenderTarget::getName(void) const - { - return mName; - } - - - void RenderTarget::getMetrics(unsigned int& width, unsigned int& height) - { - width = mWidth; - height = mHeight; - } - - unsigned int RenderTarget::getWidth(void) const - { - return mWidth; - } - unsigned int RenderTarget::getHeight(void) const - { - return mHeight; - } - //----------------------------------------------------------------------- - void RenderTarget::setDepthBufferPool( uint16 poolId ) - { - if( mDepthBufferPoolId != poolId ) - { - mDepthBufferPoolId = poolId; - detachDepthBuffer(); - } - } - //----------------------------------------------------------------------- - uint16 RenderTarget::getDepthBufferPool() const - { - return mDepthBufferPoolId; - } - //----------------------------------------------------------------------- - DepthBuffer* RenderTarget::getDepthBuffer() const - { - return mDepthBuffer; - } - //----------------------------------------------------------------------- - bool RenderTarget::attachDepthBuffer( DepthBuffer *depthBuffer ) - { - bool retVal = false; - - if( (retVal = depthBuffer->isCompatible( this )) ) - { - detachDepthBuffer(); - mDepthBuffer = depthBuffer; - mDepthBuffer->_notifyRenderTargetAttached( this ); - } - - return retVal; - } - //----------------------------------------------------------------------- - void RenderTarget::detachDepthBuffer() - { - if( mDepthBuffer ) - { - mDepthBuffer->_notifyRenderTargetDetached( this ); - mDepthBuffer = 0; - } - } - //----------------------------------------------------------------------- - void RenderTarget::_detachDepthBuffer() - { - mDepthBuffer = 0; - } - - void RenderTarget::updateImpl(void) - { - _beginUpdate(); - _updateAutoUpdatedViewports(true); - _endUpdate(); - } - - void RenderTarget::_beginUpdate() - { - // notify listeners (pre) - firePreUpdate(); - - mStats.triangleCount = 0; - mStats.batchCount = 0; - } - - void RenderTarget::_updateAutoUpdatedViewports(bool updateStatistics) - { - // Go through viewports in Z-order - // Tell each to refresh - for (const auto& v : mViewportList) - { - Viewport* viewport = v.second; - if(viewport->isAutoUpdated()) - { - _updateViewport(viewport,updateStatistics); - } - } - } - - void RenderTarget::_endUpdate() - { - // notify listeners (post) - firePostUpdate(); - - // Update statistics (always on top) - updateStats(); - } - - void RenderTarget::_updateViewport(Viewport* viewport, bool updateStatistics) - { - assert(viewport->getTarget() == this && - "RenderTarget::_updateViewport the requested viewport is " - "not bound to the rendertarget!"); - - fireViewportPreUpdate(viewport); - viewport->update(); - if(updateStatistics) - { - mStats.triangleCount += viewport->_getNumRenderedFaces(); - mStats.batchCount += viewport->_getNumRenderedBatches(); - } - fireViewportPostUpdate(viewport); - } - - void RenderTarget::_updateViewport(int zorder, bool updateStatistics) - { - ViewportList::iterator it = mViewportList.find(zorder); - if (it != mViewportList.end()) - { - _updateViewport((*it).second,updateStatistics); - } - else - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND,"No viewport with given zorder : " - + StringConverter::toString(zorder), "RenderTarget::_updateViewport"); - } - } - - Viewport* RenderTarget::addViewport(Camera* cam, int ZOrder, float left, float top , - float width , float height) - { - // Check no existing viewport with this Z-order - ViewportList::iterator it = mViewportList.find(ZOrder); - - if (it != mViewportList.end()) - { - StringStream str; - str << "Can't create another viewport for " - << mName << " with Z-order " << ZOrder - << " because a viewport exists with this Z-order already."; - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, str.str(), "RenderTarget::addViewport"); - } - // Add viewport to list - // Order based on Z-order - Viewport* vp = OGRE_NEW Viewport(cam, this, left, top, width, height, ZOrder); - - mViewportList.emplace(ZOrder, vp); - - fireViewportAdded(vp); - - return vp; - } - //----------------------------------------------------------------------- - void RenderTarget::removeViewport(int ZOrder) - { - ViewportList::iterator it = mViewportList.find(ZOrder); - - if (it != mViewportList.end()) - { - fireViewportRemoved(it->second); - OGRE_DELETE (*it).second; - mViewportList.erase(ZOrder); - } - } - - void RenderTarget::removeAllViewports(void) - { - // make a copy of the list to avoid crashes, the viewport destructor change the list - ViewportList vlist = mViewportList; - - for (auto& vl : vlist) - { - fireViewportRemoved(vl.second); - OGRE_DELETE vl.second; - } - - mViewportList.clear(); - - } - - void RenderTarget::resetStatistics(void) - { - mStats.avgFPS = 0.0; - mStats.bestFPS = 0.0; - mStats.lastFPS = 0.0; - mStats.worstFPS = 999.0; - mStats.triangleCount = 0; - mStats.batchCount = 0; - mStats.bestFrameTime = 999999; - mStats.worstFrameTime = 0; - mStats.vBlankMissCount = -1; - - mLastTime = mTimer->getMilliseconds(); - mLastSecond = mLastTime; - mFrameCount = 0; - } - - void RenderTarget::updateStats(void) - { - ++mFrameCount; - unsigned long thisTime = mTimer->getMilliseconds(); - - // check frame time - unsigned long frameTime = thisTime - mLastTime ; - mLastTime = thisTime ; - - mStats.bestFrameTime = std::min(mStats.bestFrameTime, frameTime); - mStats.worstFrameTime = std::max(mStats.worstFrameTime, frameTime); - - // check if new second (update only once per second) - if (thisTime - mLastSecond > 1000) - { - // new second - not 100% precise - mStats.lastFPS = (float)mFrameCount / (float)(thisTime - mLastSecond) * 1000.0f; - - if (mStats.avgFPS == 0) - mStats.avgFPS = mStats.lastFPS; - else - mStats.avgFPS = (mStats.avgFPS + mStats.lastFPS) / 2; // not strictly correct, but good enough - - mStats.bestFPS = std::max(mStats.bestFPS, mStats.lastFPS); - mStats.worstFPS = std::min(mStats.worstFPS, mStats.lastFPS); - - mLastSecond = thisTime ; - mFrameCount = 0; - - } - - } - - void RenderTarget::getCustomAttribute(const String& name, void* pData) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Attribute not found. " + name, " RenderTarget::getCustomAttribute"); - } - //----------------------------------------------------------------------- - void RenderTarget::addListener(RenderTargetListener* listener) - { - if (std::find(mListeners.begin(), mListeners.end(), listener) == mListeners.end()) - mListeners.push_back(listener); - } - //----------------------------------------------------------------------- - void RenderTarget::insertListener(RenderTargetListener* listener, const unsigned int pos) - { - // if the position is larger than the list size we just set the listener at the end of the list - if (pos > mListeners.size()) - mListeners.push_back(listener); - else - mListeners.insert(mListeners.begin() + pos, listener); - } - //----------------------------------------------------------------------- - void RenderTarget::removeListener(RenderTargetListener* listener) - { - RenderTargetListenerList::iterator i = std::find(mListeners.begin(), mListeners.end(), listener); - if (i != mListeners.end()) - mListeners.erase(i); - } - //----------------------------------------------------------------------- - void RenderTarget::removeAllListeners(void) - { - mListeners.clear(); - } - //----------------------------------------------------------------------- - void RenderTarget::firePreUpdate(void) - { - RenderTargetEvent evt; - evt.source = this; - - for(auto& l : mListeners) - { - l->preRenderTargetUpdate(evt); - } - - - } - //----------------------------------------------------------------------- - void RenderTarget::firePostUpdate(void) - { - RenderTargetEvent evt; - evt.source = this; - - for(auto& l : mListeners) - { - l->postRenderTargetUpdate(evt); - } - } - //----------------------------------------------------------------------- - unsigned short RenderTarget::getNumViewports(void) const - { - return (unsigned short)mViewportList.size(); - - } - //----------------------------------------------------------------------- - Viewport* RenderTarget::getViewport(unsigned short index) - { - assert (index < mViewportList.size() && "Index out of bounds"); - - ViewportList::iterator i = mViewportList.begin(); - while (index--) - ++i; - return i->second; - } - //----------------------------------------------------------------------- - Viewport* RenderTarget::getViewportByZOrder(int ZOrder) - { - ViewportList::iterator i = mViewportList.find(ZOrder); - if(i == mViewportList.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND,"No viewport with given Z-order: " - + StringConverter::toString(ZOrder), "RenderTarget::getViewportByZOrder"); - } - return i->second; - } - //----------------------------------------------------------------------- - bool RenderTarget::hasViewportWithZOrder(int ZOrder) - { - ViewportList::iterator i = mViewportList.find(ZOrder); - return i != mViewportList.end(); - } - //----------------------------------------------------------------------- - bool RenderTarget::isActive() const - { - return mActive; - } - //----------------------------------------------------------------------- - void RenderTarget::setActive( bool state ) - { - mActive = state; - } - //----------------------------------------------------------------------- - void RenderTarget::fireViewportPreUpdate(Viewport* vp) - { - RenderTargetViewportEvent evt; - evt.source = vp; - - for(auto& l : mListeners) - { - l->preViewportUpdate(evt); - } - } - //----------------------------------------------------------------------- - void RenderTarget::fireViewportPostUpdate(Viewport* vp) - { - RenderTargetViewportEvent evt; - evt.source = vp; - - for(auto& l : mListeners) - { - l->postViewportUpdate(evt); - } - } - //----------------------------------------------------------------------- - void RenderTarget::fireViewportAdded(Viewport* vp) - { - RenderTargetViewportEvent evt; - evt.source = vp; - - for(auto& l : mListeners) - { - l->viewportAdded(evt); - } - } - //----------------------------------------------------------------------- - void RenderTarget::fireViewportRemoved(Viewport* vp) - { - RenderTargetViewportEvent evt; - evt.source = vp; - - // Make a temp copy of the listeners - // some will want to remove themselves as listeners when they get this - RenderTargetListenerList tempList = mListeners; - - for(auto& l : tempList) - { - l->viewportRemoved(evt); - } - } - //----------------------------------------------------------------------- - String RenderTarget::writeContentsToTimestampedFile(const String& filenamePrefix, const String& filenameSuffix) - { - auto t = std::time(nullptr); - auto pTime = std::localtime(&t); - - // use ISO 8601 order - StringStream oss; - oss << filenamePrefix - << std::put_time(pTime, "%Y%m%d_%H%M%S") - << std::setw(3) << std::setfill('0') << (mTimer->getMilliseconds() % 1000) - << filenameSuffix; - String filename = oss.str(); - writeContentsToFile(filename); - return filename; - - } - //----------------------------------------------------------------------- - void RenderTarget::writeContentsToFile(const String& filename) - { - Image img(suggestPixelFormat(), mWidth, mHeight); - - PixelBox pb = img.getPixelBox(); - copyContentsToMemory(pb, pb); - - img.save(filename); - } - //----------------------------------------------------------------------- - void RenderTarget::_notifyCameraRemoved(const Camera* cam) - { - ViewportList::iterator i, iend; - iend = mViewportList.end(); - for (auto& l : mViewportList) - { - Viewport* v = l.second; - if (v->getCamera() == cam) - { - // disable camera link - v->setCamera(0); - } - } - } - //----------------------------------------------------------------------- - void RenderTarget::setAutoUpdated(bool autoup) - { - mAutoUpdate = autoup; - } - //----------------------------------------------------------------------- - bool RenderTarget::isAutoUpdated(void) const - { - return mAutoUpdate; - } - //----------------------------------------------------------------------- - bool RenderTarget::isPrimary(void) const - { - // RenderWindow will override and return true for the primary window - return false; - } - //----------------------------------------------------------------------- - bool RenderTarget::isStereoEnabled(void) const - { - return mStereoEnabled; - } - //----------------------------------------------------------------------- - void RenderTarget::update(bool swap) - { - OgreProfileBeginGPUEvent(getName()); - // call implementation - updateImpl(); - - - if (swap) - { - // Swap buffers - swapBuffers(); - } - OgreProfileEndGPUEvent(getName()); - } -} diff --git a/OgreMain/src/OgreRenderTexture.cpp b/OgreMain/src/OgreRenderTexture.cpp deleted file mode 100644 index 6558e9cf30a..00000000000 --- a/OgreMain/src/OgreRenderTexture.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreRenderTexture.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreDepthBuffer.h" - -namespace Ogre -{ - - //----------------------------------------------------------------------------- - RenderTexture::RenderTexture(HardwarePixelBuffer *buffer, uint32 zoffset): - mBuffer(buffer), mZOffset(zoffset) - { - mPriority = OGRE_REND_TO_TEX_RT_GROUP; - mWidth = mBuffer->getWidth(); - mHeight = mBuffer->getHeight(); - - if(PixelUtil::isDepth(mBuffer->getFormat())) - mDepthBufferPoolId = DepthBuffer::POOL_NO_DEPTH; - } - RenderTexture::~RenderTexture() - { - mBuffer->_clearSliceRTT(0); - } - - void RenderTexture::copyContentsToMemory(const Box& src, const PixelBox &dst, FrameBuffer buffer) - { - if (buffer == FB_AUTO) buffer = FB_FRONT; - OgreAssert(buffer == FB_FRONT, "Invalid buffer"); - - mBuffer->blitToMemory(src, dst); - } - //--------------------------------------------------------------------- - PixelFormat RenderTexture::suggestPixelFormat() const - { - return mBuffer->getFormat(); - } - //----------------------------------------------------------------------------- - MultiRenderTarget::MultiRenderTarget(const String &name) - { - mPriority = OGRE_REND_TO_TEX_RT_GROUP; - mName = name; - /// Width and height is unknown with no targets attached - mWidth = mHeight = 0; - } - void MultiRenderTarget::bindSurface(size_t attachment, RenderTexture* target) - { - if(PixelUtil::isDepth(target->suggestPixelFormat())) - setDepthBufferPool(DepthBuffer::POOL_NO_DEPTH); // unbinds any previously bound depth render buffer - - for (size_t i = mBoundSurfaces.size(); i <= attachment; ++i) - { - mBoundSurfaces.push_back(0); - } - mBoundSurfaces[attachment] = target; - - bindSurfaceImpl(attachment, target); - } - - //----------------------------------------------------------------------------- - void MultiRenderTarget::copyContentsToMemory(const Box& src, const PixelBox &dst, FrameBuffer buffer) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Cannot get MultiRenderTargets pixels", - "MultiRenderTarget::copyContentsToMemory"); - } -} diff --git a/OgreMain/src/OgreRenderToVertexBuffer.cpp b/OgreMain/src/OgreRenderToVertexBuffer.cpp deleted file mode 100644 index cdab539e2bf..00000000000 --- a/OgreMain/src/OgreRenderToVertexBuffer.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" -#include "OgreRenderToVertexBuffer.h" - -#include - -namespace Ogre { - //----------------------------------------------------------------------- - RenderToVertexBuffer::RenderToVertexBuffer() : - mOperationType(RenderOperation::OT_TRIANGLE_LIST), - mResetsEveryUpdate(false), - mResetRequested(true), - mSourceRenderable(0), - mMaxVertexCount(1000) - { - mVertexData = std::make_unique(); - } - RenderToVertexBuffer::~RenderToVertexBuffer() = default; // ensure unique_ptr destructors are in cpp - //----------------------------------------------------------------------- - VertexDeclaration* RenderToVertexBuffer::getVertexDeclaration() - { - //TODO : Mark dirty? - return mVertexData->vertexDeclaration; - } - //----------------------------------------------------------------------- - void RenderToVertexBuffer::setRenderToBufferMaterialName(const String& materialName) - { - mMaterial = MaterialManager::getSingleton().getByName(materialName); - - if (!mMaterial) - OGRE_EXCEPT( Exception::ERR_ITEM_NOT_FOUND, "Could not find material " + materialName, - "RenderToVertexBuffer::setRenderToBufferMaterialName" ); - - /* Ensure that the new material was loaded (will not load again if - already loaded anyway) - */ - mMaterial->load(); - } - void RenderToVertexBuffer::getRenderOperation(RenderOperation& op) - { - op.operationType = mOperationType; - op.useIndexes = false; - op.vertexData = mVertexData.get(); - } - Pass* RenderToVertexBuffer::derivePass(SceneManager* sceneMgr) - { - // Single pass only for now. - Ogre::Pass* r2vbPass = mMaterial->getBestTechnique()->getPass(0); - // Set pass before binding buffers to activate the GPU programs. - sceneMgr->_setPass(r2vbPass); - - r2vbPass->_updateAutoParams(sceneMgr->_getAutoParamDataSource(), GPV_GLOBAL); - - // Bind shader parameters. - RenderSystem* targetRenderSystem = Root::getSingleton().getRenderSystem(); - if (r2vbPass->hasVertexProgram()) - { - targetRenderSystem->bindGpuProgramParameters(GPT_VERTEX_PROGRAM, - r2vbPass->getVertexProgramParameters(), GPV_ALL); - } - if (r2vbPass->hasGeometryProgram()) - { - targetRenderSystem->bindGpuProgramParameters(GPT_GEOMETRY_PROGRAM, - r2vbPass->getGeometryProgramParameters(), GPV_ALL); - } - //TODO add tessellation stages - - return r2vbPass; - } -} diff --git a/OgreMain/src/OgreRenderWindow.cpp b/OgreMain/src/OgreRenderWindow.cpp deleted file mode 100644 index ad9170af80b..00000000000 --- a/OgreMain/src/OgreRenderWindow.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreRenderWindow.h" - -namespace Ogre { - - RenderWindow::RenderWindow() - : RenderTarget(), mIsFullScreen(false), mIsPrimary(false), mClosed(false), mLeft(0), mTop(0), mVSyncInterval(1) - { - mAutoDeactivatedOnFocusChange = true; - } - - //----------------------------------------------------------------------- - void RenderWindow::getMetrics(unsigned int& width, unsigned int& height, - int& left, int& top) const - { - width = mWidth; - height = mHeight; - left = mLeft; - top = mTop; - } - //----------------------------------------------------------------------- - bool RenderWindow::isFullScreen(void) const - { - return mIsFullScreen; - } - //----------------------------------------------------------------------- - bool RenderWindow::isPrimary(void) const - { - return mIsPrimary; - } - - bool RenderWindow::isDeactivatedOnFocusChange() const - { - return mAutoDeactivatedOnFocusChange; - } - - void RenderWindow::setDeactivateOnFocusChange(bool deactivate) - { - mAutoDeactivatedOnFocusChange = deactivate; - } -} diff --git a/OgreMain/src/OgreRenderable.cpp b/OgreMain/src/OgreRenderable.cpp deleted file mode 100644 index 93514542183..00000000000 --- a/OgreMain/src/OgreRenderable.cpp +++ /dev/null @@ -1,40 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. - -#include "OgreStableHeaders.h" - -namespace Ogre -{ -void Renderable::setCustomParameter(size_t index, const Vector4f& value) { mCustomParameters[index] = value; } - -void Renderable::removeCustomParameter(size_t index) { mCustomParameters.erase(index); } - -bool Renderable::hasCustomParameter(size_t index) const -{ - return mCustomParameters.find(index) != mCustomParameters.end(); -} - -const Vector4f& Renderable::getCustomParameter(size_t index) const -{ - CustomParameterMap::const_iterator i = mCustomParameters.find(index); - if (i != mCustomParameters.end()) - { - return i->second; - } - else - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Parameter at the given index was not found."); - } -} - -void Renderable::_updateCustomGpuParameter(const GpuProgramParameters::AutoConstantEntry& constantEntry, - GpuProgramParameters* params) const -{ - CustomParameterMap::const_iterator i = mCustomParameters.find(constantEntry.data); - if (i != mCustomParameters.end()) - { - params->_writeRawConstant(constantEntry.physicalIndex, i->second, constantEntry.elementCount); - } -} -} // namespace Ogre diff --git a/OgreMain/src/OgreResource.cpp b/OgreMain/src/OgreResource.cpp deleted file mode 100644 index 7700b5c5332..00000000000 --- a/OgreMain/src/OgreResource.cpp +++ /dev/null @@ -1,418 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -// Ogre includes -#include "OgreStableHeaders.h" - -namespace Ogre -{ - //----------------------------------------------------------------------- - Resource::Resource(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - : mCreator(creator), mName(name), mGroup(group), mHandle(handle), - mLoadingState(LOADSTATE_UNLOADED), mIsBackgroundLoaded(false), - mIsManual(isManual), mSize(0), mLoader(loader), mStateCount(0) - { - } - //----------------------------------------------------------------------- - Resource::~Resource() - { - } - Resource& Resource::operator=(const Resource& rhs) - { - mName = rhs.mName; - mGroup = rhs.mGroup; - mCreator = rhs.mCreator; - mIsManual = rhs.mIsManual; - mLoader = rhs.mLoader; - mHandle = rhs.mHandle; - mSize = rhs.mSize; - - mLoadingState.store(rhs.mLoadingState.load()); - mIsBackgroundLoaded = rhs.mIsBackgroundLoaded; - - return *this; - } - //----------------------------------------------------------------------- - void Resource::escalateLoading() - { - // Just call load as if this is the background thread, locking on - // load status will prevent race conditions - load(true); - _fireLoadingComplete(); - } - //----------------------------------------------------------------------- - void Resource::prepare(bool background) - { - // quick check that avoids any synchronisation - LoadingState old = mLoadingState.load(); - if (old != LOADSTATE_UNLOADED && old != LOADSTATE_PREPARING) return; - - // atomically do slower check to make absolutely sure, - // and set the load state to PREPARING - old = LOADSTATE_UNLOADED; - if (!mLoadingState.compare_exchange_strong(old,LOADSTATE_PREPARING)) - { - while( mLoadingState.load() == LOADSTATE_PREPARING ) - { - OGRE_LOCK_AUTO_MUTEX; - } - - LoadingState state = mLoadingState.load(); - if( state != LOADSTATE_PREPARED && state != LOADSTATE_LOADING && state != LOADSTATE_LOADED ) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Another thread failed in resource operation", - "Resource::prepare"); - } - return; - } - - // Scope lock for actual loading - try - { - - OGRE_LOCK_AUTO_MUTEX; - - if (mIsManual) - { - if (mLoader) - { - mLoader->prepareResource(this); - } - else - { - // Warn that this resource is not reloadable - LogManager::getSingleton().stream(LML_TRIVIAL) - << "Note: " << mCreator->getResourceType() - << " instance '" << mName << "' was defined as manually " - << "loaded, but no manual loader was provided. This Resource " - << "will be lost if it has to be reloaded."; - } - } - else - { - if (mGroup == ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME) - { - // Derive resource group - changeGroupOwnership( - ResourceGroupManager::getSingleton() - .findGroupContainingResource(mName)); - } - prepareImpl(); - } - } - catch (...) - { - mLoadingState.store(LOADSTATE_UNLOADED); - - OGRE_LOCK_AUTO_MUTEX; - unloadImpl(); - - throw; - } - - mLoadingState.store(LOADSTATE_PREPARED); - - // Since we don't distinguish between GPU and CPU RAM, this - // seems pointless - //if(mCreator) - // mCreator->_notifyResourcePrepared(this); - - // Fire events (if not background) - if (!background) - _firePreparingComplete(); - - - } - //--------------------------------------------------------------------- - void Resource::load(bool background) - { - // Early-out without lock (mitigate perf cost of ensuring loaded) - // Don't load if: - // 1. We're already loaded - // 2. Another thread is loading right now - // 3. We're marked for background loading and this is not the background - // loading thread we're being called by - - if (mIsBackgroundLoaded && !background) return; - - // This next section is to deal with cases where 2 threads are fighting over - // who gets to prepare / load - this will only usually happen if loading is escalated - bool keepChecking = true; - LoadingState old = LOADSTATE_UNLOADED; - while (keepChecking) - { - // quick check that avoids any synchronisation - old = mLoadingState.load(); - - if ( old == LOADSTATE_PREPARING ) - { - while( mLoadingState.load() == LOADSTATE_PREPARING ) - { - OGRE_LOCK_AUTO_MUTEX; - } - old = mLoadingState.load(); - } - - if (old!=LOADSTATE_UNLOADED && old!=LOADSTATE_PREPARED && old!=LOADSTATE_LOADING) return; - - // atomically do slower check to make absolutely sure, - // and set the load state to LOADING - if (old==LOADSTATE_LOADING || !mLoadingState.compare_exchange_strong(old,LOADSTATE_LOADING)) - { - while( mLoadingState.load() == LOADSTATE_LOADING ) - { - OGRE_LOCK_AUTO_MUTEX; - } - - LoadingState state = mLoadingState.load(); - if( state == LOADSTATE_PREPARED || state == LOADSTATE_PREPARING ) - { - // another thread is preparing, loop around - continue; - } - else if( state != LOADSTATE_LOADED ) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Another thread failed in resource operation", - "Resource::load"); - } - return; - } - keepChecking = false; - } - - // Scope lock for actual loading - try - { - - OGRE_LOCK_AUTO_MUTEX; - - - - if (mIsManual) - { - if (old==LOADSTATE_UNLOADED && mLoader) - mLoader->prepareResource(this); - - preLoadImpl(); - - // Load from manual loader - if (mLoader) - { - mLoader->loadResource(this); - } - else - { - // Warn that this resource is not reloadable - LogManager::getSingleton().stream(LML_TRIVIAL) - << "Note: " << mCreator->getResourceType() - << " instance '" << mName << "' was defined as manually " - << "loaded, but no manual loader was provided. This Resource " - << "will be lost if it has to be reloaded."; - } - postLoadImpl(); - } - else - { - - if (old==LOADSTATE_UNLOADED) - prepareImpl(); - - preLoadImpl(); - - if (mGroup == ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME) - { - // Derive resource group - changeGroupOwnership( - ResourceGroupManager::getSingleton() - .findGroupContainingResource(mName)); - } - - loadImpl(); - - postLoadImpl(); - } - - // Calculate resource size - mSize = calculateSize(); - - } - catch (...) - { - // Reset loading in-progress flag, in case failed for some reason. - // We reset it to UNLOADED because the only other case is when - // old == PREPARED in which case the loadImpl should wipe out - // any prepared data since it might be invalid. - mLoadingState.store(LOADSTATE_UNLOADED); - - OGRE_LOCK_AUTO_MUTEX; - unloadImpl(); - - // Re-throw - throw; - } - - mLoadingState.store(LOADSTATE_LOADED); - _dirtyState(); - - // Notify manager - if(mCreator) - mCreator->_notifyResourceLoaded(this); - - // Fire events, if not background - if (!background) - _fireLoadingComplete(); - - - } - //--------------------------------------------------------------------- - size_t Resource::calculateSize(void) const - { - size_t memSize = 0; // sizeof(*this) should be called by deriving classes - memSize += mName.size() * sizeof(char); - memSize += mGroup.size() * sizeof(char); - memSize += mOrigin.size() * sizeof(char); - memSize += sizeof(void*) * mListenerList.size(); - - return memSize; - } - //--------------------------------------------------------------------- - void Resource::_dirtyState() - { - // don't worry about threading here, count only ever increases so - // doesn't matter if we get a lost increment (one is enough) - ++mStateCount; - } - //----------------------------------------------------------------------- - void Resource::changeGroupOwnership(const String& newGroup) - { - if (mGroup != newGroup) - { - String oldGroup = mGroup; - mGroup = newGroup; - ResourceGroupManager::getSingleton() - ._notifyResourceGroupChanged(oldGroup, this); - } - } - //----------------------------------------------------------------------- - void Resource::unload(void) - { - // Early-out without lock (mitigate perf cost of ensuring unloaded) - LoadingState old = mLoadingState.load(); - if (old!=LOADSTATE_LOADED && old!=LOADSTATE_PREPARED) return; - - - if (!mLoadingState.compare_exchange_strong(old,LOADSTATE_UNLOADING)) return; - - // Scope lock for actual unload - { - OGRE_LOCK_AUTO_MUTEX; - if (old==LOADSTATE_PREPARED) { - unprepareImpl(); - } else { - preUnloadImpl(); - unloadImpl(); - postUnloadImpl(); - } - } - - mLoadingState.store(LOADSTATE_UNLOADED); - - // Notify manager - // Note if we have gone from PREPARED to UNLOADED, then we haven't actually - // unloaded, i.e. there is no memory freed on the GPU. - if(old==LOADSTATE_LOADED && mCreator) - mCreator->_notifyResourceUnloaded(this); - - _fireUnloadingComplete(); - - - } - //----------------------------------------------------------------------- - void Resource::reload(LoadingFlags flags) - { - OGRE_LOCK_AUTO_MUTEX; - if (mLoadingState.load() == LOADSTATE_LOADED) - { - unload(); - load(); - } - } - //----------------------------------------------------------------------- - void Resource::touch(void) - { - // make sure loaded - load(); - - if(mCreator) - mCreator->_notifyResourceTouched(this); - } - //----------------------------------------------------------------------- - void Resource::addListener(Resource::Listener* lis) - { - OGRE_LOCK_MUTEX(mListenerListMutex); - mListenerList.insert(lis); - } - //----------------------------------------------------------------------- - void Resource::removeListener(Resource::Listener* lis) - { - // O(n) but not called very often - OGRE_LOCK_MUTEX(mListenerListMutex); - mListenerList.erase(lis); - } - //----------------------------------------------------------------------- - void Resource::_fireLoadingComplete(bool unused) - { - // Lock the listener list - OGRE_LOCK_MUTEX(mListenerListMutex); - for (auto& l : mListenerList) - { - l->loadingComplete(this); - } - } - //----------------------------------------------------------------------- - void Resource::_firePreparingComplete(bool unused) - { - // Lock the listener list - OGRE_LOCK_MUTEX(mListenerListMutex); - for (auto& l : mListenerList) - { - l->preparingComplete(this); - } - } - //----------------------------------------------------------------------- - void Resource::_fireUnloadingComplete(void) - { - // Lock the listener list - OGRE_LOCK_MUTEX(mListenerListMutex); - for (auto& l : mListenerList) - { - l->unloadingComplete(this); - } - } - -} diff --git a/OgreMain/src/OgreResourceBackgroundQueue.cpp b/OgreMain/src/OgreResourceBackgroundQueue.cpp deleted file mode 100644 index 4efec00d817..00000000000 --- a/OgreMain/src/OgreResourceBackgroundQueue.cpp +++ /dev/null @@ -1,142 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreResourceBackgroundQueue.h" - -namespace Ogre { - - // Note, no locks are required here anymore because all of the parallelisation - // is now contained in WorkQueue - this class is entirely single-threaded - //------------------------------------------------------------------------ - //----------------------------------------------------------------------- - template<> ResourceBackgroundQueue* Singleton::msSingleton = 0; - ResourceBackgroundQueue* ResourceBackgroundQueue::getSingletonPtr(void) - { - return msSingleton; - } - ResourceBackgroundQueue& ResourceBackgroundQueue::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //------------------------------------------------------------------------ - ResourceBackgroundQueue::ResourceBackgroundQueue() {} - ResourceBackgroundQueue::~ResourceBackgroundQueue() {} - //------------------------------------------------------------------------ - std::future ResourceBackgroundQueue::initialiseResourceGroup(const String& name) - { - auto task = std::make_shared>( - [name]() { ResourceGroupManager::getSingleton().initialiseResourceGroup(name); }); - Root::getSingleton().getWorkQueue()->addTask([task]() { (*task)(); }); - return task->get_future(); - } - //------------------------------------------------------------------------ - std::future ResourceBackgroundQueue::initialiseAllResourceGroups() - { - auto task = std::make_shared>( - []() { ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); }); - Root::getSingleton().getWorkQueue()->addTask([task]() { (*task)(); }); - return task->get_future(); - } - //------------------------------------------------------------------------ - std::future ResourceBackgroundQueue::prepareResourceGroup(const String& name) - { - auto task = std::make_shared>( - [name]() { ResourceGroupManager::getSingleton().prepareResourceGroup(name); }); - Root::getSingleton().getWorkQueue()->addTask([task]() { (*task)(); }); - return task->get_future(); - } - //------------------------------------------------------------------------ - std::future ResourceBackgroundQueue::loadResourceGroup(const String& name) - { - auto task = std::make_shared>([name]() - { -# if OGRE_THREAD_SUPPORT == 1 - ResourceGroupManager::getSingleton().loadResourceGroup(name); -# else - ResourceGroupManager::getSingleton().prepareResourceGroup(name); - Root::getSingleton().getWorkQueue()->addMainThreadTask( - [name]() { ResourceGroupManager::getSingleton().loadResourceGroup(name); }); -# endif - }); - Root::getSingleton().getWorkQueue()->addTask([task]() { (*task)(); }); - return task->get_future(); - } - //------------------------------------------------------------------------ - std::future ResourceBackgroundQueue::prepare(const ResourcePtr& res) - { - auto task = std::make_shared>( - [res]() - { - res->prepare(true); - Root::getSingleton().getWorkQueue()->addMainThreadTask([res]() { res->_firePreparingComplete(); }); - }); - Root::getSingleton().getWorkQueue()->addTask([task]() { (*task)(); }); - return task->get_future(); - } - //------------------------------------------------------------------------ - std::future ResourceBackgroundQueue::load(const ResourcePtr& res) - { - auto task = std::make_shared>( - [res]() - { -#if OGRE_THREAD_SUPPORT == 1 - res->load(true); - Root::getSingleton().getWorkQueue()->addMainThreadTask([res]() { res->_fireLoadingComplete(); }); -#else - res->prepare(true); - Root::getSingleton().getWorkQueue()->addMainThreadTask( - [res]() - { - res->load(true); - res->_fireLoadingComplete(); - }); -#endif - }); - Root::getSingleton().getWorkQueue()->addTask([task]() { (*task)(); }); - return task->get_future(); - } - //--------------------------------------------------------------------- - std::future ResourceBackgroundQueue::unload(const ResourcePtr& res) - { - auto task = std::make_shared>([res]() { res->unload(); }); - Root::getSingleton().getWorkQueue()->addTask([task]() { (*task)(); }); - return task->get_future(); - } - //--------------------------------------------------------------------- - std::future ResourceBackgroundQueue::unloadResourceGroup(const String& name) - { - auto task = std::make_shared>( - [name]() { ResourceGroupManager::getSingleton().unloadResourceGroup(name); }); - Root::getSingleton().getWorkQueue()->addTask([task]() { (*task)(); }); - return task->get_future(); - } - -} - - - diff --git a/OgreMain/src/OgreResourceGroupManager.cpp b/OgreMain/src/OgreResourceGroupManager.cpp deleted file mode 100644 index 1c2517eec73..00000000000 --- a/OgreMain/src/OgreResourceGroupManager.cpp +++ /dev/null @@ -1,1573 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreScriptLoader.h" - -namespace Ogre { - - //----------------------------------------------------------------------- - template<> ResourceGroupManager* Singleton::msSingleton = 0; - ResourceGroupManager* ResourceGroupManager::getSingletonPtr(void) - { - return msSingleton; - } - ResourceGroupManager& ResourceGroupManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - - const char* const RGN_DEFAULT = "General"; - const char* const RGN_INTERNAL = "OgreInternal"; - const char* const RGN_AUTODETECT = "OgreAutodetect"; - - const String ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME = RGN_DEFAULT; - const String ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME = RGN_INTERNAL; - const String ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME = RGN_AUTODETECT; - - // A reference count of 3 means that only RGM and RM have references - // RGM has one (this one) and RM has 2 (by name and by handle) - const long ResourceGroupManager::RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS = 3; - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - ResourceGroupManager::ResourceGroupManager() - : mLoadingListener(0), mCurrentGroup(0) - { - // Create the 'General' group - createResourceGroup(DEFAULT_RESOURCE_GROUP_NAME, true); // the "General" group is synonymous to global pool - // Create the 'Internal' group - createResourceGroup(INTERNAL_RESOURCE_GROUP_NAME, true); - // Create the 'Autodetect' group (only used for temp storage) - createResourceGroup(AUTODETECT_RESOURCE_GROUP_NAME, true); // autodetect includes the global pool - // default world group to the default group - mWorldGroupName = DEFAULT_RESOURCE_GROUP_NAME; - } - //----------------------------------------------------------------------- - ResourceGroupManager::~ResourceGroupManager() - { - // delete all resource groups - ResourceGroupMap::iterator i, iend; - iend = mResourceGroupMap.end(); - for (auto& g : mResourceGroupMap) - { - deleteGroup(g.second); - } - mResourceGroupMap.clear(); - } - //----------------------------------------------------------------------- - void ResourceGroupManager::createResourceGroup(const String& name, bool inGlobalPool) - { - LogManager::getSingleton().logMessage("Creating resource group " + name); - if (getResourceGroup(name)) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "Resource group with name '" + name + "' already exists!", - "ResourceGroupManager::createResourceGroup"); - } - ResourceGroup* grp = OGRE_NEW_T(ResourceGroup, MEMCATEGORY_RESOURCE)(); - grp->groupStatus = ResourceGroup::UNINITIALSED; - grp->name = name; - grp->inGlobalPool = inGlobalPool; - grp->customStageCount = 0; - - OGRE_LOCK_AUTO_MUTEX; - mResourceGroupMap.emplace(name, grp); - } - //----------------------------------------------------------------------- - void ResourceGroupManager::initialiseResourceGroup(const String& name) - { - LogManager::getSingleton().logMessage("Initialising resource group " + name); - ResourceGroup* grp = getResourceGroup(name, true); - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex; - - if (grp->groupStatus == ResourceGroup::UNINITIALSED) - { - // in the process of initialising - grp->groupStatus = ResourceGroup::INITIALISING; - // Set current group - parseResourceGroupScripts(grp); - mCurrentGroup = grp; - LogManager::getSingleton().logMessage("Creating resources for group " + name); - createDeclaredResources(grp); - grp->groupStatus = ResourceGroup::INITIALISED; - LogManager::getSingleton().logMessage("All done"); - // Reset current group - mCurrentGroup = 0; - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::initialiseAllResourceGroups(void) - { - OGRE_LOCK_AUTO_MUTEX; - - // Intialise all declared resource groups - for (auto& g : mResourceGroupMap) - { - ResourceGroup* grp = g.second; - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - if (grp->groupStatus == ResourceGroup::UNINITIALSED) - { - // in the process of initialising - grp->groupStatus = ResourceGroup::INITIALISING; - // Set current group - mCurrentGroup = grp; - parseResourceGroupScripts(grp); - LogManager::getSingleton().logMessage("Creating resources for group " + g.first); - createDeclaredResources(grp); - grp->groupStatus = ResourceGroup::INITIALISED; - LogManager::getSingleton().logMessage("All done"); - // Reset current group - mCurrentGroup = 0; - } - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::prepareResourceGroup(const String& name) - { - LogManager::getSingleton().stream() << "Preparing resource group '" << name << "'"; - // load all created resources - ResourceGroup* grp = getResourceGroup(name, true); - OGRE_LOCK_AUTO_MUTEX; - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - // Set current group - mCurrentGroup = grp; - - // Count up resources for starting event - size_t resourceCount = 0; - for (auto& oi : grp->loadResourceOrderMap) - { - resourceCount += oi.second.size(); - } - - fireResourceGroupPrepareStarted(name, resourceCount); - - // Now load for real - for (auto& oi : grp->loadResourceOrderMap) - { - size_t n = 0; - LoadUnloadResourceList::iterator l = oi.second.begin(); - while (l != oi.second.end()) - { - ResourcePtr res = *l; - - // Fire resource events no matter whether resource needs preparing - // or not. This ensures that the number of callbacks - // matches the number originally estimated, which is important - // for progress bars. - fireResourcePrepareStarted(res); - - // If preparing one of these resources cascade-prepares another resource, - // the list will get longer! But these should be prepared immediately - // Call prepare regardless, already prepared or loaded resources will be skipped - res->prepare(); - - fireResourcePrepareEnded(); - - ++n; - - // Did the resource change group? if so, our iterator will have - // been invalidated - if (res->getGroup() != name) - { - l = oi.second.begin(); - std::advance(l, n); - } - else - { - ++l; - } - } - } - fireResourceGroupPrepareEnded(name); - - // reset current group - mCurrentGroup = 0; - - LogManager::getSingleton().logMessage("Finished preparing resource group " + name); - } - //----------------------------------------------------------------------- - void ResourceGroupManager::loadResourceGroup(const String& name) - { - LogManager::getSingleton().stream() << "Loading resource group '" << name << "'"; - // load all created resources - ResourceGroup* grp = getResourceGroup(name, true); - OGRE_LOCK_AUTO_MUTEX; - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - // Set current group - mCurrentGroup = grp; - - // Count up resources for starting event - size_t resourceCount = grp->customStageCount; - for (auto& oi : grp->loadResourceOrderMap) - { - resourceCount += oi.second.size(); - } - - fireResourceGroupLoadStarted(name, resourceCount); - - // Now load for real - for (auto& oi : grp->loadResourceOrderMap) - { - size_t n = 0; - auto l = oi.second.begin(); - while (l != oi.second.end()) - { - ResourcePtr res = *l; - - // Fire resource events no matter whether resource is already - // loaded or not. This ensures that the number of callbacks - // matches the number originally estimated, which is important - // for progress bars. - fireResourceLoadStarted(res); - - // If loading one of these resources cascade-loads another resource, - // the list will get longer! But these should be loaded immediately - // Call load regardless, already loaded resources will be skipped - res->load(); - - fireResourceLoadEnded(); - - ++n; - - // Did the resource change group? if so, our iterator will have - // been invalidated - if (res->getGroup() != name) - { - l = oi.second.begin(); - std::advance(l, n); - } - else - { - ++l; - } - } - } - fireResourceGroupLoadEnded(name); - - // group is loaded - grp->groupStatus = ResourceGroup::LOADED; - - // reset current group - mCurrentGroup = 0; - - LogManager::getSingleton().logMessage("Finished loading resource group " + name); - } - //----------------------------------------------------------------------- - void ResourceGroupManager::unloadResourceGroup(const String& name, bool reloadableOnly) - { - LogManager::getSingleton().logMessage("Unloading resource group " + name); - ResourceGroup* grp = getResourceGroup(name, true); - OGRE_LOCK_AUTO_MUTEX; - // Set current group - mCurrentGroup = grp; - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - - // unload in reverse order - for (auto& oi : grp->loadResourceOrderMap) - { - for (auto& l : oi.second) - { - Resource* resource = l.get(); - if (!reloadableOnly || resource->isReloadable()) - { - resource->unload(); - } - } - } - - grp->groupStatus = ResourceGroup::INITIALISED; - - // reset current group - mCurrentGroup = 0; - LogManager::getSingleton().logMessage("Finished unloading resource group " + name); - } - //----------------------------------------------------------------------- - void ResourceGroupManager::unloadUnreferencedResourcesInGroup( - const String& name, bool reloadableOnly ) - { - LogManager::getSingleton().logMessage( - "Unloading unused resources in resource group " + name); - ResourceGroup* grp = getResourceGroup(name, true); - OGRE_LOCK_AUTO_MUTEX; - // Set current group - mCurrentGroup = grp; - - ResourceGroup::LoadResourceOrderMap::reverse_iterator oi; - // unload in reverse order - for (oi = grp->loadResourceOrderMap.rbegin(); oi != grp->loadResourceOrderMap.rend(); ++oi) - { - for (auto& l : oi->second) - { - // A use count of 3 means that only RGM and RM have references - // RGM has one (this one) and RM has 2 (by name and by handle) - if (l.use_count() == RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS) - { - Resource* resource = l.get(); - if (!reloadableOnly || resource->isReloadable()) - { - resource->unload(); - } - } - } - } - - grp->groupStatus = ResourceGroup::INITIALISED; - - // reset current group - mCurrentGroup = 0; - LogManager::getSingleton().logMessage( - "Finished unloading unused resources in resource group " + name); - } - //----------------------------------------------------------------------- - void ResourceGroupManager::clearResourceGroup(const String& name) - { - LogManager::getSingleton().logMessage("Clearing resource group " + name); - ResourceGroup* grp = getResourceGroup(name, true); - OGRE_LOCK_AUTO_MUTEX; - // set current group - mCurrentGroup = grp; - dropGroupContents(grp); - // clear initialised flag - grp->groupStatus = ResourceGroup::UNINITIALSED; - // reset current group - mCurrentGroup = 0; - LogManager::getSingleton().logMessage("Finished clearing resource group " + name); - } - //----------------------------------------------------------------------- - void ResourceGroupManager::destroyResourceGroup(const String& name) - { - LogManager::getSingleton().logMessage("Destroying resource group " + name); - ResourceGroup* grp = getResourceGroup(name, true); - OGRE_LOCK_AUTO_MUTEX; - // set current group - mCurrentGroup = grp; - unloadResourceGroup(name, false); // will throw an exception if name not valid - dropGroupContents(grp); - deleteGroup(grp); - mResourceGroupMap.erase(mResourceGroupMap.find(name)); - // reset current group - mCurrentGroup = 0; - } - //----------------------------------------------------------------------- - bool ResourceGroupManager::isResourceGroupInitialised(const String& name) const - { - ResourceGroup* grp = getResourceGroup(name, true); - return (grp->groupStatus != ResourceGroup::UNINITIALSED && - grp->groupStatus != ResourceGroup::INITIALISING); - } - //----------------------------------------------------------------------- - bool ResourceGroupManager::isResourceGroupLoaded(const String& name) const - { - return getResourceGroup(name, true)->groupStatus == ResourceGroup::LOADED; - } - //----------------------------------------------------------------------- - bool ResourceGroupManager::resourceGroupExists(const String& name) const - { - return getResourceGroup(name) ? true : false; - } - //----------------------------------------------------------------------- - bool ResourceGroupManager::resourceLocationExists(const String& name, - const String& resGroup) const - { - ResourceGroup* grp = getResourceGroup(resGroup); - if (!grp) - return false; - - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - - for (auto& li : grp->locationList) - { - Archive* pArch = li.archive; - if (pArch->getName() == name) - // Delete indexes - return true; - } - return false; - } - //----------------------------------------------------------------------- - void ResourceGroupManager::addResourceLocation(const String& name, - const String& locType, const String& resGroup, bool recursive, bool readOnly) - { - // Get archive - Archive* pArch = ArchiveManager::getSingleton().load( name, locType, readOnly ); - // Add to location list - - ResourceLocation loc = {pArch, recursive}; - StringVectorPtr vec = pArch->find("*", recursive); - - ResourceGroup* grp = getResourceGroup(resGroup); - if (!grp) - { - createResourceGroup(resGroup); - grp = getResourceGroup(resGroup); - } - - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - grp->locationList.push_back(loc); - - // Index resources - for (auto& s : *vec) - grp->addToIndex(s, pArch); - - StringStream msg; - msg << "Added resource location '" << name << "' of type '" << locType - << "' to resource group '" << resGroup << "'"; - if (recursive) - msg << " with recursive option"; - LogManager::getSingleton().logMessage(msg.str()); - - } - //----------------------------------------------------------------------- - void ResourceGroupManager::removeResourceLocation(const String& name, - const String& resGroup) - { - ResourceGroup* grp = getResourceGroup(resGroup, true); - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - - // Remove from location list - auto liend = grp->locationList.end(); - for (auto li = grp->locationList.begin(); li != liend; ++li) - { - Archive* pArch = li->archive; - if (pArch->getName() == name) - { - grp->removeFromIndex(pArch); - grp->locationList.erase(li); - ArchiveManager::getSingleton().unload(pArch); - break; - } - } - - LogManager::getSingleton().logMessage("Removed resource location " + name); - - - } - //----------------------------------------------------------------------- - void ResourceGroupManager::declareResource(const String& name, - const String& resourceType, const String& groupName, - const NameValuePairList& loadParameters) - { - declareResource(name, resourceType, groupName, 0, loadParameters); - } - //----------------------------------------------------------------------- - void ResourceGroupManager::declareResource(const String& name, - const String& resourceType, const String& groupName, - ManualResourceLoader* loader, - const NameValuePairList& loadParameters) - { - ResourceGroup* grp = getResourceGroup(groupName, true); - ResourceDeclaration dcl; - dcl.loader = loader; - dcl.parameters = loadParameters; - dcl.resourceName = name; - dcl.resourceType = resourceType; - - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - grp->resourceDeclarations.push_back(dcl); - } - //----------------------------------------------------------------------- - void ResourceGroupManager::undeclareResource(const String& name, - const String& groupName) - { - ResourceGroup* grp = getResourceGroup(groupName, true); - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - - for (auto i = grp->resourceDeclarations.begin(); - i != grp->resourceDeclarations.end(); ++i) - { - if (i->resourceName == name) - { - grp->resourceDeclarations.erase(i); - break; - } - } - } - //----------------------------------------------------------------------- - DataStreamPtr ResourceGroupManager::openResourceImpl(const String& resourceName, - const String& groupName, - bool searchGroupsIfNotFound, - Resource* resourceBeingLoaded, - bool throwOnFailure) const - { - OgreAssert(!resourceName.empty(), "resourceName is empty string"); - if(mLoadingListener) - { - DataStreamPtr stream = mLoadingListener->resourceLoading(resourceName, groupName, resourceBeingLoaded); - if(stream) - return stream; - } - - // Try to find in resource index first - ResourceGroup* grp = getResourceGroup(groupName, throwOnFailure); - if (!grp) - { - // we only get here if throwOnFailure is false - return DataStreamPtr(); - } - - Archive* pArch = resourceExists(grp, resourceName); - - if (pArch == NULL && (searchGroupsIfNotFound || - groupName == AUTODETECT_RESOURCE_GROUP_NAME || grp->inGlobalPool || - (!OGRE_RESOURCEMANAGER_STRICT && (groupName == DEFAULT_RESOURCE_GROUP_NAME)))) - { - std::pair ret = resourceExistsInAnyGroupImpl(resourceName); - - if(ret.second && resourceBeingLoaded && !grp->inGlobalPool) { - resourceBeingLoaded->changeGroupOwnership(ret.second->name); - } - - pArch = ret.first; - } - - if (pArch) - { - DataStreamPtr stream = pArch->open(resourceName); - if (mLoadingListener) - mLoadingListener->resourceStreamOpened(resourceName, groupName, resourceBeingLoaded, stream); - return stream; - } - - if(!throwOnFailure) - return DataStreamPtr(); - - OGRE_EXCEPT(Exception::ERR_FILE_NOT_FOUND, "Cannot locate resource " + - resourceName + " in resource group " + groupName + ".", - "ResourceGroupManager::openResource"); - - } - //----------------------------------------------------------------------- - DataStreamList ResourceGroupManager::openResources( - const String& pattern, const String& groupName) const - { - ResourceGroup* grp = getResourceGroup(groupName, true); - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - - // Iterate through all the archives and build up a combined list of - // streams - DataStreamList ret; - - for (auto& li : grp->locationList) - { - Archive* arch = li.archive; - // Find all the names based on whether this archive is recursive - StringVectorPtr names = arch->find(pattern, li.recursive); - - // Iterate over the names and load a stream for each - for (auto & ni : *names) - { - DataStreamPtr ptr = arch->open(ni); - if (ptr) - { - ret.push_back(ptr); - } - } - } - return ret; - - } - //--------------------------------------------------------------------- - DataStreamPtr ResourceGroupManager::createResource(const String& filename, - const String& groupName, bool overwrite, const String& locationPattern) - { - ResourceGroup* grp = getResourceGroup(groupName, true); - OGRE_LOCK_AUTO_MUTEX; - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - - for (auto& li : grp->locationList) - { - Archive* arch = li.archive; - - if (!arch->isReadOnly() && - (locationPattern.empty() || StringUtil::match(arch->getName(), locationPattern, false))) - { - if (!overwrite && arch->exists(filename)) - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "Cannot overwrite existing file " + filename, - "ResourceGroupManager::createResource"); - - // create it - DataStreamPtr ret = arch->create(filename); - grp->addToIndex(filename, arch); - - return ret; - } - } - - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Cannot find a writable location in group " + groupName, - "ResourceGroupManager::createResource"); - - } - //--------------------------------------------------------------------- - void ResourceGroupManager::deleteResource(const String& filename, const String& groupName, - const String& locationPattern) - { - ResourceGroup* grp = getResourceGroup(groupName, true); - OGRE_LOCK_AUTO_MUTEX; - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - - for (auto& li : grp->locationList) - { - Archive* arch = li.archive; - - if (!arch->isReadOnly() && - (locationPattern.empty() || StringUtil::match(arch->getName(), locationPattern, false))) - { - if (arch->exists(filename)) - { - arch->remove(filename); - grp->removeFromIndex(filename, arch); - - // only remove one file - break; - } - } - } - } - //--------------------------------------------------------------------- - void ResourceGroupManager::deleteMatchingResources(const String& filePattern, - const String& groupName, const String& locationPattern) - { - ResourceGroup* grp = getResourceGroup(groupName, true); - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - - for (auto& li : grp->locationList) - { - Archive* arch = li.archive; - - if (!arch->isReadOnly() && - (locationPattern.empty() || StringUtil::match(arch->getName(), locationPattern, false))) - { - StringVectorPtr matchingFiles = arch->find(filePattern); - for (auto& f : *matchingFiles) - { - arch->remove(f); - grp->removeFromIndex(f, arch); - } - } - } - - - } - //----------------------------------------------------------------------- - void ResourceGroupManager::addResourceGroupListener(ResourceGroupListener* l) - { - OGRE_LOCK_AUTO_MUTEX; - - mResourceGroupListenerList.push_back(l); - } - //----------------------------------------------------------------------- - void ResourceGroupManager::removeResourceGroupListener(ResourceGroupListener* l) - { - OGRE_LOCK_AUTO_MUTEX; - - for (ResourceGroupListenerList::iterator i = mResourceGroupListenerList.begin(); - i != mResourceGroupListenerList.end(); ++i) - { - if (*i == l) - { - mResourceGroupListenerList.erase(i); - break; - } - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::_registerResourceManager( - const String& resourceType, ResourceManager* rm) - { - OGRE_LOCK_AUTO_MUTEX; - - LogManager::getSingleton().logMessage( - "Registering ResourceManager for type " + resourceType); - mResourceManagerMap[resourceType] = rm; - } - //----------------------------------------------------------------------- - void ResourceGroupManager::_unregisterResourceManager( - const String& resourceType) - { - OGRE_LOCK_AUTO_MUTEX; - - LogManager::getSingleton().logMessage( - "Unregistering ResourceManager for type " + resourceType); - - ResourceManagerMap::iterator i = mResourceManagerMap.find(resourceType); - if (i != mResourceManagerMap.end()) - { - mResourceManagerMap.erase(i); - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::_registerScriptLoader(ScriptLoader* su) - { - OGRE_LOCK_AUTO_MUTEX; - - mScriptLoaderOrderMap.emplace(su->getLoadingOrder(), su); - } - //----------------------------------------------------------------------- - void ResourceGroupManager::_unregisterScriptLoader(ScriptLoader* su) - { - OGRE_LOCK_AUTO_MUTEX; - - Real order = su->getLoadingOrder(); - ScriptLoaderOrderMap::iterator oi = mScriptLoaderOrderMap.find(order); - while (oi != mScriptLoaderOrderMap.end() && oi->first == order) - { - if (oi->second == su) - { - // erase does not invalidate on multimap, except current - ScriptLoaderOrderMap::iterator del = oi++; - mScriptLoaderOrderMap.erase(del); - } - else - { - ++oi; - } - } - } - //----------------------------------------------------------------------- - ScriptLoader *ResourceGroupManager::_findScriptLoader(const String &pattern) const - { - OGRE_LOCK_AUTO_MUTEX; - for (auto& oi : mScriptLoaderOrderMap) - { - ScriptLoader* su = oi.second; - const StringVector& patterns = su->getScriptPatterns(); - - // Search for matches in the patterns - for (const auto& p : patterns) - { - if(p == pattern) - return su; - } - } - - return 0; // No loader was found - } - //----------------------------------------------------------------------- - void ResourceGroupManager::parseResourceGroupScripts(ResourceGroup* grp) const - { - - LogManager::getSingleton().logMessage( - "Parsing scripts for resource group " + grp->name); - - // Count up the number of scripts we have to parse - typedef std::pair LoaderFileListPair; - typedef std::vector ScriptLoaderFileList; - ScriptLoaderFileList scriptLoaderFileList; - size_t scriptCount = 0; - // Iterate over script users in loading order and get streams - for (auto& oi : mScriptLoaderOrderMap) - { - ScriptLoader* su = oi.second; - - scriptLoaderFileList.push_back(LoaderFileListPair(su, FileInfoList())); - - // Get all the patterns and search them - const StringVector& patterns = su->getScriptPatterns(); - for (const auto& pattern : patterns) - { - FileInfoListPtr fileList = findResourceFileInfo(grp->name, pattern); - FileInfoList& lst = scriptLoaderFileList.back().second; - lst.insert(lst.end(), fileList->begin(), fileList->end()); - } - - scriptCount += scriptLoaderFileList.back().second.size(); - } - // Fire scripting event - fireResourceGroupScriptingStarted(grp->name, scriptCount); - - // Iterate over scripts and parse - // Note we respect original ordering - for (auto & slfli : scriptLoaderFileList) - { - ScriptLoader* su = slfli.first; - // Iterate over each item in the list - for (auto & fii : slfli.second) - { - bool skipScript = false; - fireScriptStarted(fii.filename, skipScript); - if(skipScript) - { - LogManager::getSingleton().logMessage( - "Skipping script " + fii.filename); - } - else - { - LogManager::getSingleton().logMessage( - "Parsing script " + fii.filename); - DataStreamPtr stream = fii.archive->open(fii.filename); - if (stream) - { - if (mLoadingListener) - mLoadingListener->resourceStreamOpened(fii.filename, grp->name, 0, stream); - - if(fii.archive->getType() == "FileSystem" && stream->size() <= 1024 * 1024) - { - DataStreamPtr cachedCopy(OGRE_NEW MemoryDataStream(stream->getName(), stream)); - su->parseScript(cachedCopy, grp->name); - } - else - su->parseScript(stream, grp->name); - } - } - fireScriptEnded(fii.filename, skipScript); - } - } - - fireResourceGroupScriptingEnded(grp->name); - LogManager::getSingleton().logMessage( - "Finished parsing scripts for resource group " + grp->name); - } - //----------------------------------------------------------------------- - void ResourceGroupManager::createDeclaredResources(ResourceGroup* grp) - { - - for (auto& dcl : grp->resourceDeclarations) - { - // Retrieve the appropriate manager - ResourceManager* mgr = _getResourceManager(dcl.resourceType); - // Create the resource - ResourcePtr res = mgr->createResource(dcl.resourceName, grp->name, - dcl.loader != 0, dcl.loader, &dcl.parameters); - // Add resource to load list - ResourceGroup::LoadResourceOrderMap::iterator li = - grp->loadResourceOrderMap.find(mgr->getLoadingOrder()); - - if (li == grp->loadResourceOrderMap.end()) - { - grp->loadResourceOrderMap[mgr->getLoadingOrder()] = LoadUnloadResourceList(); - } - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::_notifyResourceCreated(ResourcePtr& res) const - { - if (mCurrentGroup && res->getGroup() == mCurrentGroup->name) - { - // Use current group (batch loading) - addCreatedResource(res, *mCurrentGroup); - } - else - { - // Find group - ResourceGroup* grp = getResourceGroup(res->getGroup()); - if (grp) - { - addCreatedResource(res, *grp); - } - } - - fireResourceCreated(res); - } - //----------------------------------------------------------------------- - void ResourceGroupManager::_notifyResourceRemoved(const ResourcePtr& res) const - { - fireResourceRemove(res); - - if (mCurrentGroup && res->getGroup() == mCurrentGroup->name) - { - // Do nothing - we're batch unloading so list will be cleared - } - else - { - // Find group - ResourceGroup* grp = getResourceGroup(res->getGroup()); - if (grp) - { - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - ResourceGroup::LoadResourceOrderMap::iterator i = - grp->loadResourceOrderMap.find( - res->getCreator()->getLoadingOrder()); - if (i != grp->loadResourceOrderMap.end()) - { - // Iterate over the resource list and remove - LoadUnloadResourceList& resList = i->second; - for (LoadUnloadResourceList::iterator l = resList.begin(); - l != resList.end(); ++ l) - { - if ((*l).get() == res.get()) - { - // this is the one - resList.erase(l); - break; - } - } - } - } - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::_notifyResourceGroupChanged(const String& oldGroup, - Resource* res) const - { - ResourcePtr resPtr; - - // find old entry - ResourceGroup* grp = getResourceGroup(oldGroup); - - if (grp) - { - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - - Real order = res->getCreator()->getLoadingOrder(); - ResourceGroup::LoadResourceOrderMap::iterator i = - grp->loadResourceOrderMap.find(order); - assert(i != grp->loadResourceOrderMap.end()); - LoadUnloadResourceList& loadList = i->second; - for (LoadUnloadResourceList::iterator l = loadList.begin(); - l != loadList.end(); ++l) - { - if ((*l).get() == res) - { - resPtr = *l; - loadList.erase(l); - break; - } - } - } - - if (resPtr) - { - // New group - ResourceGroup* newGrp = getResourceGroup(res->getGroup()); - - addCreatedResource(resPtr, *newGrp); - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::_notifyAllResourcesRemoved(ResourceManager* manager) const - { - OGRE_LOCK_AUTO_MUTEX; - - // Iterate over all groups - for (const auto & grpi : mResourceGroupMap) - { - OGRE_LOCK_MUTEX(grpi.second->OGRE_AUTO_MUTEX_NAME); - // Iterate over all priorities - for (auto & oi : grpi.second->loadResourceOrderMap) - { - // Iterate over all resources and collect which should be removed - std::vector arDel; - arDel.reserve(oi.second.size()); - for (const auto& iter : oi.second) { - if (iter->getCreator() == manager) - arDel.emplace_back(iter); - } - - // Remove the items here (not above) because during the erase the item destructor - // can unload some resources which can call _notifyResourceRemoved that removes - // the corresponding items from our container - this invalidates the iterator and we crash. - for (const auto& iter : arDel) - { - auto iFind = std::find(oi.second.begin(), oi.second.end(), iter); - if (iFind != oi.second.end()) - oi.second.erase(iFind); - } - } - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::addCreatedResource(ResourcePtr& res, ResourceGroup& grp) const - { - OGRE_LOCK_MUTEX(grp.OGRE_AUTO_MUTEX_NAME); - Real order = res->getCreator()->getLoadingOrder(); - - ResourceGroup::LoadResourceOrderMap::iterator i = grp.loadResourceOrderMap.find(order); - LoadUnloadResourceList& loadList = - i == grp.loadResourceOrderMap.end() ? grp.loadResourceOrderMap[order] : i->second; - - loadList.push_back(res); - } - //----------------------------------------------------------------------- - ResourceGroupManager::ResourceGroup* ResourceGroupManager::getResourceGroup(const String& name, - bool throwOnFailure) const - { - OGRE_LOCK_AUTO_MUTEX; - ResourceGroupMap::const_iterator i = mResourceGroupMap.find(name); - - if (i == mResourceGroupMap.end()) - { - if (throwOnFailure) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Cannot locate a resource group called '" + name + "'"); - - return nullptr; - } - - return i->second; - } - //----------------------------------------------------------------------- - ResourceManager* ResourceGroupManager::_getResourceManager(const String& resourceType) const - { - OGRE_LOCK_AUTO_MUTEX; - - ResourceManagerMap::const_iterator i = mResourceManagerMap.find(resourceType); - if (i == mResourceManagerMap.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Cannot locate resource manager for resource type '" + - resourceType + "'", "ResourceGroupManager::_getResourceManager"); - } - return i->second; - - } - //----------------------------------------------------------------------- - void ResourceGroupManager::dropGroupContents(ResourceGroup* grp) - { - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); - - bool groupSet = false; - if (!mCurrentGroup) - { - // Set current group to indicate ignoring of notifications - mCurrentGroup = grp; - groupSet = true; - } - // delete all the load list entries - for (auto& j : grp->loadResourceOrderMap) - { - // Iterate over resources - for (auto& k : j.second) - { - k->getCreator()->remove(k); - } - } - grp->loadResourceOrderMap.clear(); - - if (groupSet) - { - mCurrentGroup = 0; - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::deleteGroup(ResourceGroup* grp) - { - { - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); - // delete all the load list entries - grp->loadResourceOrderMap.clear(); - } - - // delete ResourceGroup - OGRE_DELETE_T(grp, ResourceGroup, MEMCATEGORY_RESOURCE); - } - //----------------------------------------------------------------------- - void ResourceGroupManager::fireResourceGroupScriptingStarted(const String& groupName, size_t scriptCount) const - { - OGRE_LOCK_AUTO_MUTEX; - for (auto l : mResourceGroupListenerList) - { - l->resourceGroupScriptingStarted(groupName, scriptCount); - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::fireScriptStarted(const String& scriptName, bool &skipScript) const - { - OGRE_LOCK_AUTO_MUTEX; - for (auto l : mResourceGroupListenerList) - { - bool temp = false; - l->scriptParseStarted(scriptName, temp); - if(temp) - skipScript = true; - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::fireScriptEnded(const String& scriptName, bool skipped) const - { - OGRE_LOCK_AUTO_MUTEX; - for (auto l : mResourceGroupListenerList) - { - l->scriptParseEnded(scriptName, skipped); - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::fireResourceGroupScriptingEnded(const String& groupName) const - { - OGRE_LOCK_AUTO_MUTEX; - for (auto l : mResourceGroupListenerList) - { - l->resourceGroupScriptingEnded(groupName); - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::fireResourceGroupLoadStarted(const String& groupName, size_t resourceCount) const - { - OGRE_LOCK_AUTO_MUTEX; - for (auto l : mResourceGroupListenerList) - { - l->resourceGroupLoadStarted(groupName, resourceCount); - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::fireResourceLoadStarted(const ResourcePtr& resource) const - { - OGRE_LOCK_AUTO_MUTEX; - for (auto l : mResourceGroupListenerList) - { - l->resourceLoadStarted(resource); - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::fireResourceLoadEnded(void) const - { - OGRE_LOCK_AUTO_MUTEX; - for (auto l : mResourceGroupListenerList) - { - l->resourceLoadEnded(); - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::_notifyCustomStageStarted(const String& desc) const - { - OGRE_LOCK_AUTO_MUTEX; - for (auto l : mResourceGroupListenerList) - { - l->customStageStarted(desc); - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::_notifyCustomStageEnded(void) const - { - OGRE_LOCK_AUTO_MUTEX; - for (auto l : mResourceGroupListenerList) - { - l->customStageEnded(); - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::fireResourceGroupLoadEnded(const String& groupName) const - { - OGRE_LOCK_AUTO_MUTEX; - for (auto l : mResourceGroupListenerList) - { - l->resourceGroupLoadEnded(groupName); - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::fireResourceGroupPrepareStarted(const String& groupName, size_t resourceCount) const - { - OGRE_LOCK_AUTO_MUTEX; - for (auto l : mResourceGroupListenerList) - { - l->resourceGroupPrepareStarted(groupName, resourceCount); - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::fireResourcePrepareStarted(const ResourcePtr& resource) const - { - OGRE_LOCK_AUTO_MUTEX; - for (auto l : mResourceGroupListenerList) - { - l->resourcePrepareStarted(resource); - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::fireResourcePrepareEnded(void) const - { - OGRE_LOCK_AUTO_MUTEX; - for (auto l : mResourceGroupListenerList) - { - l->resourcePrepareEnded(); - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::fireResourceGroupPrepareEnded(const String& groupName) const - { - OGRE_LOCK_AUTO_MUTEX; - for (auto l : mResourceGroupListenerList) - { - l->resourceGroupPrepareEnded(groupName); - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::fireResourceCreated(const ResourcePtr& resource) const - { - OGRE_LOCK_AUTO_MUTEX; - for (auto l : mResourceGroupListenerList) - { - l->resourceCreated(resource); - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::fireResourceRemove(const ResourcePtr& resource) const - { - OGRE_LOCK_AUTO_MUTEX; - for (auto l : mResourceGroupListenerList) - { - l->resourceRemove(resource); - } - } - //----------------------------------------------------------------------- - void ResourceGroupManager::shutdownAll(void) - { - OGRE_LOCK_AUTO_MUTEX; - - ResourceManagerMap::iterator i, iend; - iend = mResourceManagerMap.end(); - for (i = mResourceManagerMap.begin(); i != iend; ++i) - { - i->second->removeAll(); - } - } - //----------------------------------------------------------------------- - StringVectorPtr ResourceGroupManager::listResourceNames(const String& groupName, bool dirs) const - { - auto vec = std::make_shared(); - - // Try to find in resource index first - ResourceGroup* grp = getResourceGroup(groupName, true); - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - - // Iterate over the archives - for (auto& i : grp->locationList) - { - StringVectorPtr lst = i.archive->list(i.recursive, dirs); - vec->insert(vec->end(), lst->begin(), lst->end()); - } - - return vec; - - - } - //----------------------------------------------------------------------- - FileInfoListPtr ResourceGroupManager::listResourceFileInfo(const String& groupName, bool dirs) const - { - auto vec = std::make_shared(); - - // Try to find in resource index first - ResourceGroup* grp = getResourceGroup(groupName, true); - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - - // Iterate over the archives - for (auto& i : grp->locationList) - { - FileInfoListPtr lst = i.archive->listFileInfo(i.recursive, dirs); - vec->insert(vec->end(), lst->begin(), lst->end()); - } - - return vec; - - } - //----------------------------------------------------------------------- - StringVectorPtr ResourceGroupManager::findResourceNames(const String& groupName, - const String& pattern, bool dirs) const - { - auto vec = std::make_shared(); - - // Try to find in resource index first - ResourceGroup* grp = getResourceGroup(groupName, true); - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - - // Iterate over the archives - for (auto& i : grp->locationList) - { - StringVectorPtr lst = i.archive->find(pattern, i.recursive, dirs); - vec->insert(vec->end(), lst->begin(), lst->end()); - } - - return vec; - } - //----------------------------------------------------------------------- - FileInfoListPtr ResourceGroupManager::findResourceFileInfo(const String& groupName, - const String& pattern, bool dirs) const - { - auto vec = std::make_shared(); - - // Try to find in resource index first - ResourceGroup* grp = getResourceGroup(groupName, true); - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - - // Iterate over the archives - for (auto& i : grp->locationList) - { - FileInfoListPtr lst = i.archive->findFileInfo(pattern, i.recursive, dirs); - vec->insert(vec->end(), lst->begin(), lst->end()); - } - - return vec; - } - //----------------------------------------------------------------------- - bool ResourceGroupManager::resourceExists(const String& groupName, const String& resourceName) const - { - // Try to find in resource index first - ResourceGroup* grp = getResourceGroup(groupName, true); - return resourceExists(grp, resourceName) != 0; - } - //----------------------------------------------------------------------- - Archive* ResourceGroupManager::resourceExists(ResourceGroup* grp, const String& resourceName) const - { - - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - - // Try indexes first - ResourceLocationIndex::iterator rit = grp->resourceIndexCaseSensitive.find(resourceName); - if (rit != grp->resourceIndexCaseSensitive.end()) - { - // Found in the index - return rit->second; - } - -#if !OGRE_RESOURCEMANAGER_STRICT - // try case insensitive - String lcResourceName = resourceName; - StringUtil::toLowerCase(lcResourceName); - rit = grp->resourceIndexCaseInsensitive.find(lcResourceName); - if (rit != grp->resourceIndexCaseInsensitive.end()) - { - // Found in the index - return rit->second; - } - - // Search the hard way - for (auto& li : grp->locationList) - { - if (li.archive->exists(resourceName)) - { - return li.archive; - } - } -#endif - - return NULL; - - } - //----------------------------------------------------------------------- - time_t ResourceGroupManager::resourceModifiedTime(const String& groupName, const String& resourceName) const - { - // Try to find in resource index first - ResourceGroup* grp = getResourceGroup(groupName, true); - return resourceModifiedTime(grp, resourceName); - } - //----------------------------------------------------------------------- - time_t ResourceGroupManager::resourceModifiedTime(ResourceGroup* grp, const String& resourceName) const - { - Archive* arch = resourceExists(grp, resourceName); - if (arch) - { - return arch->getModifiedTime(resourceName); - } - - return 0; - } - //----------------------------------------------------------------------- - std::pair - ResourceGroupManager::resourceExistsInAnyGroupImpl(const String& filename) const - { - OgreAssert(!filename.empty(), "resourceName is empty string"); - OGRE_LOCK_AUTO_MUTEX; - - // Iterate over resource groups and find - for (const auto & i : mResourceGroupMap) - { - Archive* arch = resourceExists(i.second, filename); - if (arch) - return std::make_pair(arch, i.second); - } - // Not found - return std::pair(); - } - //----------------------------------------------------------------------- - bool ResourceGroupManager::resourceExistsInAnyGroup(const String& filename) const - { - return resourceExistsInAnyGroupImpl(filename).first != 0; - } - //----------------------------------------------------------------------- - const String& ResourceGroupManager::findGroupContainingResource(const String& filename) const - { - ResourceGroup* grp = resourceExistsInAnyGroupImpl(filename).second; - - if(grp) - return grp->name; - - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Unable to derive resource group for " + - filename + " automatically since the resource was not " - "found.", - "ResourceGroupManager::findGroupContainingResource"); - } - //----------------------------------------------------------------------- - StringVectorPtr ResourceGroupManager::listResourceLocations(const String& groupName) const - { - auto vec = std::make_shared(); - - // Try to find in resource index first - ResourceGroup* grp = getResourceGroup(groupName, true); - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - - // Iterate over the archives - for (auto& i : grp->locationList) - { - vec->push_back(i.archive->getName()); - } - - return vec; - } - //----------------------------------------------------------------------- - StringVectorPtr ResourceGroupManager::findResourceLocation(const String& groupName, const String& pattern) const - { - auto vec = std::make_shared(); - - // Try to find in resource index first - ResourceGroup* grp = getResourceGroup(groupName, true); - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - - // Iterate over the archives - for (auto& i : grp->locationList) - { - String location = i.archive->getName(); - // Search for the pattern - if(StringUtil::match(location, pattern)) - { - vec->push_back(location); - } - } - - return vec; - } - //----------------------------------------------------------------------- - void ResourceGroupManager::setCustomStagesForResourceGroup(const String& group, uint32 stageCount) - { - ResourceGroup* grp = getResourceGroup(group, true); - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - grp->customStageCount = stageCount; - } - //----------------------------------------------------------------------- - uint32 ResourceGroupManager::getCustomStagesForResourceGroup(const String& group) - { - ResourceGroup* grp = getResourceGroup(group, true); - OGRE_LOCK_MUTEX(grp->OGRE_AUTO_MUTEX_NAME); // lock group mutex - return grp->customStageCount; - } - //----------------------------------------------------------------------- - bool ResourceGroupManager::isResourceGroupInGlobalPool(const String& name) const - { - return getResourceGroup(name, true)->inGlobalPool; - } - //----------------------------------------------------------------------- - StringVector ResourceGroupManager::getResourceGroups(void) const - { - OGRE_LOCK_AUTO_MUTEX; - StringVector vec; - for (const auto & i : mResourceGroupMap) - { - vec.push_back(i.second->name); - } - return vec; - } - //----------------------------------------------------------------------- - ResourceGroupManager::ResourceDeclarationList - ResourceGroupManager::getResourceDeclarationList(const String& group) const - { - return getResourceGroup(group, true)->resourceDeclarations; - } - //--------------------------------------------------------------------- - const ResourceGroupManager::LocationList& - ResourceGroupManager::getResourceLocationList(const String& group) const - { - return getResourceGroup(group, true)->locationList; - } - //------------------------------------------------------------------------- - void ResourceGroupManager::setLoadingListener(ResourceLoadingListener *listener) - { - mLoadingListener = listener; - } - //------------------------------------------------------------------------- - ResourceLoadingListener *ResourceGroupManager::getLoadingListener() const - { - return mLoadingListener; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - void ResourceGroupManager::ResourceGroup::addToIndex(const String& filename, Archive* arch) - { - // internal, assumes mutex lock has already been obtained - this->resourceIndexCaseSensitive.emplace(filename, arch); - -#if !OGRE_RESOURCEMANAGER_STRICT - if (!arch->isCaseSensitive()) - { - String lcase = filename; - StringUtil::toLowerCase(lcase); - this->resourceIndexCaseInsensitive.emplace(lcase, arch); - } -#endif - } - //--------------------------------------------------------------------- - void ResourceGroupManager::ResourceGroup::removeFromIndex(const String& filename, Archive* arch) - { - // internal, assumes mutex lock has already been obtained - ResourceLocationIndex::iterator i = this->resourceIndexCaseSensitive.find(filename); - if (i != this->resourceIndexCaseSensitive.end() && i->second == arch) - this->resourceIndexCaseSensitive.erase(i); - -#if !OGRE_RESOURCEMANAGER_STRICT - if (!arch->isCaseSensitive()) - { - String lcase = filename; - StringUtil::toLowerCase(lcase); - i = this->resourceIndexCaseInsensitive.find(lcase); - if (i != this->resourceIndexCaseInsensitive.end() && i->second == arch) - this->resourceIndexCaseInsensitive.erase(i); - } -#endif - } - //--------------------------------------------------------------------- - void ResourceGroupManager::ResourceGroup::removeFromIndex(Archive* arch) - { - // Delete indexes - ResourceLocationIndex::iterator rit, ritend; -#if !OGRE_RESOURCEMANAGER_STRICT - ritend = this->resourceIndexCaseInsensitive.end(); - for (rit = this->resourceIndexCaseInsensitive.begin(); rit != ritend;) - { - if (rit->second == arch) - { - ResourceLocationIndex::iterator del = rit++; - this->resourceIndexCaseInsensitive.erase(del); - } - else - { - ++rit; - } - } -#endif - ritend = this->resourceIndexCaseSensitive.end(); - for (rit = this->resourceIndexCaseSensitive.begin(); rit != ritend;) - { - if (rit->second == arch) - { - ResourceLocationIndex::iterator del = rit++; - this->resourceIndexCaseSensitive.erase(del); - } - else - { - ++rit; - } - } - } -} diff --git a/OgreMain/src/OgreResourceManager.cpp b/OgreMain/src/OgreResourceManager.cpp deleted file mode 100644 index c6bc59f2a97..00000000000 --- a/OgreMain/src/OgreResourceManager.cpp +++ /dev/null @@ -1,551 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreResourceManager.h" - -namespace Ogre { - - //----------------------------------------------------------------------- - ResourceManager::ResourceManager() - : mNextHandle(1), mMemoryUsage(0), mVerbose(true), mLoadOrder(0) - { - // Init memory limit & usage - mMemoryBudget = std::numeric_limits::max(); - } - //----------------------------------------------------------------------- - ResourceManager::~ResourceManager() - { - destroyAllResourcePools(); - removeAll(); - } - void ResourceManager::parseScript(DataStreamPtr& stream, const String& groupName) - { - ScriptCompilerManager::getSingleton().parseScript(stream, groupName); - } - //----------------------------------------------------------------------- - ResourcePtr ResourceManager::createResource(const String& name, const String& group, - bool isManual, ManualResourceLoader* loader, const NameValuePairList* params) - { - OgreAssert(!name.empty(), "resource name must not be empty"); - - // Call creation implementation - ResourcePtr ret = ResourcePtr( - createImpl(name, getNextHandle(), group, isManual, loader, params)); - if (params) - ret->setParameterList(*params); - - addImpl(ret); - // Tell resource group manager - if(ret) - ResourceGroupManager::getSingleton()._notifyResourceCreated(ret); - return ret; - - } - //----------------------------------------------------------------------- - ResourceManager::ResourceCreateOrRetrieveResult - ResourceManager::createOrRetrieve( - const String& name, const String& group, - bool isManual, ManualResourceLoader* loader, - const NameValuePairList* params) - { - // Lock for the whole get / insert - OGRE_LOCK_AUTO_MUTEX; - - ResourcePtr res = getResourceByName(name, group); - bool created = false; - if (!res) - { - created = true; - res = createResource(name, group, isManual, loader, params); - } - - return ResourceCreateOrRetrieveResult(res, created); - } - //----------------------------------------------------------------------- - ResourcePtr ResourceManager::prepare(const String& name, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* loadParams, bool backgroundThread) - { - ResourcePtr r = createOrRetrieve(name,group,isManual,loader,loadParams).first; - // ensure prepared - r->prepare(backgroundThread); - return r; - } - //----------------------------------------------------------------------- - ResourcePtr ResourceManager::load(const String& name, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* loadParams, bool backgroundThread) - { - ResourcePtr r = createOrRetrieve(name,group,isManual,loader,loadParams).first; - // ensure loaded - r->load(backgroundThread); - - return r; - } - //----------------------------------------------------------------------- - void ResourceManager::addImpl( ResourcePtr& res ) - { - OGRE_LOCK_AUTO_MUTEX; - - std::pair result; - if(ResourceGroupManager::getSingleton().isResourceGroupInGlobalPool(res->getGroup())) - { - result = mResources.emplace(res->getName(), res); - } - else - { - // we will create the group if it doesn't exists in our list - auto resgroup = mResourcesWithGroup.emplace(res->getGroup(), ResourceMap()).first; - result = resgroup->second.emplace(res->getName(), res); - } - - // Attempt to resolve the collision - ResourceLoadingListener* listener = ResourceGroupManager::getSingleton().getLoadingListener(); - if (!result.second && listener) - { - if(listener->resourceCollision(res.get(), this) == false) - { - // explicitly use previous instance and destroy current - res.reset(); - return; - } - - // Try to do the addition again, no seconds attempts to resolve collisions are allowed - if(ResourceGroupManager::getSingleton().isResourceGroupInGlobalPool(res->getGroup())) - { - result = mResources.emplace(res->getName(), res); - } - else - { - auto resgroup = mResourcesWithGroup.emplace(res->getGroup(), ResourceMap()).first; - result = resgroup->second.emplace(res->getName(), res); - } - } - - if (!result.second) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, getResourceType()+" with the name " + res->getName() + - " already exists.", "ResourceManager::add"); - } - - // Insert the handle - std::pair resultHandle = mResourcesByHandle.emplace(res->getHandle(), res); - if (!resultHandle.second) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, getResourceType()+" with the handle " + - StringConverter::toString((long) (res->getHandle())) + - " already exists.", "ResourceManager::add"); - } - } - //----------------------------------------------------------------------- - void ResourceManager::removeImpl(const ResourcePtr& res ) - { - OgreAssert(res, "attempting to remove nullptr"); - - OGRE_LOCK_AUTO_MUTEX; - - if(ResourceGroupManager::getSingleton().isResourceGroupInGlobalPool(res->getGroup())) - { - ResourceMap::iterator nameIt = mResources.find(res->getName()); - if (nameIt != mResources.end()) - { - mResources.erase(nameIt); - } - } - else - { - ResourceWithGroupMap::iterator groupIt = mResourcesWithGroup.find(res->getGroup()); - if (groupIt != mResourcesWithGroup.end()) - { - ResourceMap::iterator nameIt = groupIt->second.find(res->getName()); - if (nameIt != groupIt->second.end()) - { - groupIt->second.erase(nameIt); - } - - if (groupIt->second.empty()) - { - mResourcesWithGroup.erase(groupIt); - } - } - } - - ResourceHandleMap::iterator handleIt = mResourcesByHandle.find(res->getHandle()); - if (handleIt != mResourcesByHandle.end()) - { - mResourcesByHandle.erase(handleIt); - } - // Tell resource group manager - ResourceGroupManager::getSingleton()._notifyResourceRemoved(res); - } - //----------------------------------------------------------------------- - void ResourceManager::setMemoryBudget( size_t bytes) - { - // Update limit & check usage - mMemoryBudget = bytes; - checkUsage(); - } - //----------------------------------------------------------------------- - size_t ResourceManager::getMemoryBudget(void) const - { - return mMemoryBudget; - } - //----------------------------------------------------------------------- - void ResourceManager::unload(const String& name, const String& group) - { - ResourcePtr res = getResourceByName(name, group); - -#if OGRE_RESOURCEMANAGER_STRICT - if (!res) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "attempting to unload unknown resource: " + name + " in group " + group); -#endif - - if (res) - { - res->unload(); - } - } - //----------------------------------------------------------------------- - void ResourceManager::unload(ResourceHandle handle) - { - ResourcePtr res = getByHandle(handle); - -#if OGRE_RESOURCEMANAGER_STRICT - OgreAssert(res, "attempting to unload unknown resource"); -#endif - - if (res) - { - res->unload(); - } - } - //----------------------------------------------------------------------- - void ResourceManager::unloadAll(Resource::LoadingFlags flags) - { - OGRE_LOCK_AUTO_MUTEX; - - bool reloadableOnly = (flags & Resource::LF_INCLUDE_NON_RELOADABLE) == 0; - bool unreferencedOnly = (flags & Resource::LF_ONLY_UNREFERENCED) != 0; - for (auto& r : mResources) - { - // A use count of 3 means that only RGM and RM have references - // RGM has one (this one) and RM has 2 (by name and by handle) - if (!unreferencedOnly || r.second.use_count() == ResourceGroupManager::RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS) - { - Resource* res = r.second.get(); - if (!reloadableOnly || res->isReloadable()) - { - res->unload(); - } - } - } - } - //----------------------------------------------------------------------- - void ResourceManager::reloadAll(Resource::LoadingFlags flags) - { - OGRE_LOCK_AUTO_MUTEX; - - bool reloadableOnly = (flags & Resource::LF_INCLUDE_NON_RELOADABLE) == 0; - bool unreferencedOnly = (flags & Resource::LF_ONLY_UNREFERENCED) != 0; - for (auto& r : mResources) - { - // A use count of 3 means that only RGM and RM have references - // RGM has one (this one) and RM has 2 (by name and by handle) - if (!unreferencedOnly || r.second.use_count() == ResourceGroupManager::RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS) - { - Resource* res = r.second.get(); - if (!reloadableOnly || res->isReloadable()) - { - res->reload(flags); - } - } - } - } - //----------------------------------------------------------------------- - void ResourceManager::remove(const ResourcePtr& res) - { - removeImpl(res); - } - //----------------------------------------------------------------------- - void ResourceManager::remove(const String& name, const String& group) - { - ResourcePtr res = getResourceByName(name, group); - -#if OGRE_RESOURCEMANAGER_STRICT - if (!res) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "attempting to remove unknown resource: " + name + " in group " + group); -#endif - - if (res) - { - removeImpl(res); - } - } - //----------------------------------------------------------------------- - void ResourceManager::remove(ResourceHandle handle) - { - ResourcePtr res = getByHandle(handle); - -#if OGRE_RESOURCEMANAGER_STRICT - OgreAssert(res, "attempting to remove unknown resource"); -#endif - - if (res) - { - removeImpl(res); - } - } - //----------------------------------------------------------------------- - void ResourceManager::removeAll(void) - { - OGRE_LOCK_AUTO_MUTEX; - - mResources.clear(); - mResourcesWithGroup.clear(); - mResourcesByHandle.clear(); - // Notify resource group manager - ResourceGroupManager::getSingleton()._notifyAllResourcesRemoved(this); - } - //----------------------------------------------------------------------- - void ResourceManager::removeUnreferencedResources(bool reloadableOnly) - { - OGRE_LOCK_AUTO_MUTEX; - - ResourceMap::iterator i, iend; - iend = mResources.end(); - for (i = mResources.begin(); i != iend;) - { - // A use count of 3 means that only RGM and RM have references - // RGM has one (this one) and RM has 2 (by name and by handle) - if (i->second.use_count() == ResourceGroupManager::RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS) - { - Resource* res = (i++)->second.get(); - if (!reloadableOnly || res->isReloadable()) - { - remove(res->getHandle()); - } - } - else { - ++i; - } - } - } - //----------------------------------------------------------------------- - ResourcePtr ResourceManager::getResourceByName(const String& name, const String& groupName) const - { - OGRE_LOCK_AUTO_MUTEX; - - // resource should be in global pool - bool isGlobal = ResourceGroupManager::getSingleton().isResourceGroupInGlobalPool(groupName); - - if(isGlobal) - { - auto it = mResources.find(name); - if( it != mResources.end()) - { - return it->second; - } - } - - // look in all grouped pools - if (groupName == ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME) - { - for (auto& r : mResourcesWithGroup) - { - auto resMapIt = r.second.find(name); - - if( resMapIt != r.second.end()) - { - return resMapIt->second; - } - } - } - else if (!isGlobal) - { - // look in the grouped pool - auto itGroup = mResourcesWithGroup.find(groupName); - if (itGroup != mResourcesWithGroup.end()) - { - auto it = itGroup->second.find(name); - - if( it != itGroup->second.end()) - { - return it->second; - } - } - -#if !OGRE_RESOURCEMANAGER_STRICT - // fall back to global - auto it = mResources.find(name); - if( it != mResources.end()) - { - return it->second; - } -#endif - } - - return ResourcePtr(); - } - //----------------------------------------------------------------------- - ResourcePtr ResourceManager::getByHandle(ResourceHandle handle) const - { - OGRE_LOCK_AUTO_MUTEX; - auto it = mResourcesByHandle.find(handle); - return it == mResourcesByHandle.end() ? ResourcePtr() : it->second; - } - //----------------------------------------------------------------------- - ResourceHandle ResourceManager::getNextHandle(void) - { - // This is an atomic operation and hence needs no locking - return mNextHandle++; - } - //----------------------------------------------------------------------- - void ResourceManager::checkUsage(void) - { - if (getMemoryUsage() > mMemoryBudget) - { - OGRE_LOCK_AUTO_MUTEX; - // unload unreferenced resources until we are within our budget again - ResourceMap::iterator i, iend; - iend = mResources.end(); - for (i = mResources.begin(); i != iend && getMemoryUsage() > mMemoryBudget; ++i) - { - // A use count of 3 means that only RGM and RM have references - // RGM has one (this one) and RM has 2 (by name and by handle) - if (i->second.use_count() == ResourceGroupManager::RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS) - { - Resource* res = i->second.get(); - if (res->isReloadable()) - { - res->unload(); - } - } - } - } - } - //----------------------------------------------------------------------- - void ResourceManager::_notifyResourceTouched(Resource* res) - { - // TODO - } - //----------------------------------------------------------------------- - void ResourceManager::_notifyResourceLoaded(Resource* res) - { - mMemoryUsage += res->getSize(); - checkUsage(); - } - //----------------------------------------------------------------------- - void ResourceManager::_notifyResourceUnloaded(Resource* res) - { - mMemoryUsage -= res->getSize(); - } - //--------------------------------------------------------------------- - ResourceManager::ResourcePool* ResourceManager::getResourcePool(const String& name) - { - OGRE_LOCK_AUTO_MUTEX; - - ResourcePoolMap::iterator i = mResourcePoolMap.find(name); - if (i == mResourcePoolMap.end()) - { - i = mResourcePoolMap.insert(ResourcePoolMap::value_type(name, - OGRE_NEW ResourcePool(name))).first; - } - return i->second; - - } - //--------------------------------------------------------------------- - void ResourceManager::destroyResourcePool(ResourcePool* pool) - { - OgreAssert(pool, "Cannot destroy a null ResourcePool"); - - OGRE_LOCK_AUTO_MUTEX; - - ResourcePoolMap::iterator i = mResourcePoolMap.find(pool->getName()); - if (i != mResourcePoolMap.end()) - mResourcePoolMap.erase(i); - - OGRE_DELETE pool; - - } - //--------------------------------------------------------------------- - void ResourceManager::destroyResourcePool(const String& name) - { - OGRE_LOCK_AUTO_MUTEX; - - ResourcePoolMap::iterator i = mResourcePoolMap.find(name); - if (i != mResourcePoolMap.end()) - { - OGRE_DELETE i->second; - mResourcePoolMap.erase(i); - } - - } - //--------------------------------------------------------------------- - void ResourceManager::destroyAllResourcePools() - { - OGRE_LOCK_AUTO_MUTEX; - - for (auto & i : mResourcePoolMap) - OGRE_DELETE i.second; - - mResourcePoolMap.clear(); - } - //----------------------------------------------------------------------- - //--------------------------------------------------------------------- - ResourceManager::ResourcePool::ResourcePool(const String& name) - : mName(name) - { - - } - //--------------------------------------------------------------------- - ResourceManager::ResourcePool::~ResourcePool() - { - clear(); - } - //--------------------------------------------------------------------- - const String& ResourceManager::ResourcePool::getName() const - { - return mName; - } - //--------------------------------------------------------------------- - void ResourceManager::ResourcePool::clear() - { - OGRE_LOCK_AUTO_MUTEX; - for (auto & i : mItems) - { - i->getCreator()->remove(i->getHandle()); - } - mItems.clear(); - } -} - - - - diff --git a/OgreMain/src/OgreRibbonTrail.cpp b/OgreMain/src/OgreRibbonTrail.cpp deleted file mode 100644 index d348ca58f99..00000000000 --- a/OgreMain/src/OgreRibbonTrail.cpp +++ /dev/null @@ -1,475 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreRibbonTrail.h" -#include "OgreController.h" - -namespace Ogre -{ - namespace - { - /** Controller value for pass frame time to RibbonTrail - */ - class _OgrePrivate TimeControllerValue : public ControllerValue - { - protected: - RibbonTrail* mTrail; - public: - TimeControllerValue(RibbonTrail* r) { mTrail = r; } - - float getValue(void) const override { return 0; }// not a source - void setValue(float value) override { mTrail->_timeUpdate(value); } - }; - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - RibbonTrail::RibbonTrail(const String& name, size_t maxElements, - size_t numberOfChains, bool useTextureCoords, bool useColours) - :BillboardChain(name, maxElements, 0, useTextureCoords, useColours, true), - mFadeController(0) - { - setTrailLength(100); - setNumberOfChains(numberOfChains); - mTimeControllerValue = ControllerValueRealPtr(OGRE_NEW TimeControllerValue(this)); - - // use V as varying texture coord, so we can use 1D textures to 'smear' - setTextureCoordDirection(TCD_V); - - - } - //----------------------------------------------------------------------- - RibbonTrail::~RibbonTrail() - { - // Detach listeners - for (auto & i : mNodeList) - { - i->setListener(0); - } - - if (mFadeController) - { - // destroy controller - ControllerManager::getSingleton().destroyController(mFadeController); - } - - } - //----------------------------------------------------------------------- - void RibbonTrail::addNode(Node* n) - { - if (mNodeList.size() == mChainCount) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - mName + " cannot monitor any more nodes, chain count exceeded", - "RibbonTrail::addNode"); - } - if (n->getListener()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - mName + " cannot monitor node " + n->getName() + " since it already has a listener.", - "RibbonTrail::addNode"); - } - - // get chain index - size_t chainIndex = mFreeChains.back(); - mFreeChains.pop_back(); - mNodeToChainSegment.push_back(chainIndex); - mNodeToSegMap[n] = chainIndex; - - // initialise the chain - resetTrail(chainIndex, n); - - mNodeList.push_back(n); - n->setListener(this); - - } - //----------------------------------------------------------------------- - size_t RibbonTrail::getChainIndexForNode(const Node* n) - { - NodeToChainSegmentMap::const_iterator i = mNodeToSegMap.find(n); - if (i == mNodeToSegMap.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "This node is not being tracked", "RibbonTrail::getChainIndexForNode"); - } - return i->second; - } - //----------------------------------------------------------------------- - void RibbonTrail::removeNode(const Node* n) - { - NodeList::iterator i = std::find(mNodeList.begin(), mNodeList.end(), n); - if (i != mNodeList.end()) - { - // also get matching chain segment - size_t index = std::distance(mNodeList.begin(), i); - IndexVector::iterator mi = mNodeToChainSegment.begin(); - std::advance(mi, index); - size_t chainIndex = *mi; - BillboardChain::clearChain(chainIndex); - // mark as free now - mFreeChains.push_back(chainIndex); - (*i)->setListener(0); - mNodeList.erase(i); - mNodeToChainSegment.erase(mi); - mNodeToSegMap.erase(mNodeToSegMap.find(n)); - - } - } - //----------------------------------------------------------------------- - RibbonTrail::NodeIterator - RibbonTrail::getNodeIterator(void) const - { - return NodeIterator(mNodeList.begin(), mNodeList.end()); - } - //----------------------------------------------------------------------- - void RibbonTrail::setTrailLength(Real len) - { - OgreAssert(len > 0, "invalid value"); - mTrailLength = len; - mElemLength = mTrailLength / mMaxElementsPerChain; - mSquaredElemLength = mElemLength * mElemLength; - } - //----------------------------------------------------------------------- - void RibbonTrail::setMaxChainElements(size_t maxElements) - { - BillboardChain::setMaxChainElements(maxElements); - mElemLength = mTrailLength / mMaxElementsPerChain; - mSquaredElemLength = mElemLength * mElemLength; - - resetAllTrails(); - } - //----------------------------------------------------------------------- - void RibbonTrail::setNumberOfChains(size_t numChains) - { - OgreAssert(numChains >= mNodeList.size(), - "Can't shrink the number of chains less than number of tracking nodes"); - size_t oldChains = getNumberOfChains(); - - BillboardChain::setNumberOfChains(numChains); - - mInitialColour.resize(numChains, ColourValue::White); - mDeltaColour.resize(numChains, ColourValue::ZERO); - mInitialWidth.resize(numChains, 10); - mDeltaWidth.resize(numChains, 0); - - if (oldChains > numChains) - { - // remove free chains - for (IndexVector::iterator i = mFreeChains.begin(); i != mFreeChains.end();) - { - if (*i >= numChains) - i = mFreeChains.erase(i); - else - ++i; - } - } - else if (oldChains < numChains) - { - // add new chains, at front to preserve previous ordering (pop_back) - for (size_t i = oldChains; i < numChains; ++i) - mFreeChains.insert(mFreeChains.begin(), i); - } - resetAllTrails(); - } - //----------------------------------------------------------------------- - void RibbonTrail::clearChain(size_t chainIndex) - { - BillboardChain::clearChain(chainIndex); - - // Reset if we are tracking for this chain - IndexVector::iterator i = std::find(mNodeToChainSegment.begin(), mNodeToChainSegment.end(), chainIndex); - if (i != mNodeToChainSegment.end()) - { - size_t nodeIndex = std::distance(mNodeToChainSegment.begin(), i); - resetTrail(*i, mNodeList[nodeIndex]); - } - } - //----------------------------------------------------------------------- - void RibbonTrail::setInitialColour(size_t chainIndex, const ColourValue& col) - { - setInitialColour(chainIndex, col.r, col.g, col.b, col.a); - } - //----------------------------------------------------------------------- - void RibbonTrail::setInitialColour(size_t chainIndex, float r, float g, float b, float a) - { - mInitialColour.at(chainIndex) = ColourValue(r, g, b, a); - } - //----------------------------------------------------------------------- - void RibbonTrail::setInitialWidth(size_t chainIndex, Real width) - { - mInitialWidth.at(chainIndex) = width; - } - //----------------------------------------------------------------------- - void RibbonTrail::setColourChange(size_t chainIndex, const ColourValue& valuePerSecond) - { - setColourChange(chainIndex, - valuePerSecond.r, valuePerSecond.g, valuePerSecond.b, valuePerSecond.a); - } - //----------------------------------------------------------------------- - void RibbonTrail::setColourChange(size_t chainIndex, float r, float g, float b, float a) - { - mDeltaColour.at(chainIndex) = ColourValue(r, g, b, a); - manageController(); - } - //----------------------------------------------------------------------- - void RibbonTrail::setWidthChange(size_t chainIndex, Real widthDeltaPerSecond) - { - mDeltaWidth.at(chainIndex) = widthDeltaPerSecond; - manageController(); - } - //----------------------------------------------------------------------- - void RibbonTrail::manageController(void) - { - bool needController = false; - for (size_t i = 0; i < mChainCount; ++i) - { - if (mDeltaWidth[i] != 0 || mDeltaColour[i] != ColourValue::ZERO) - { - needController = true; - break; - } - } - if (!mFadeController && needController) - { - // Set up fading via frame time controller - ControllerManager& mgr = ControllerManager::getSingleton(); - mFadeController = mgr.createFrameTimePassthroughController(mTimeControllerValue); - } - else if (mFadeController && !needController) - { - // destroy controller - ControllerManager::getSingleton().destroyController(mFadeController); - mFadeController = 0; - } - - } - //----------------------------------------------------------------------- - void RibbonTrail::nodeUpdated(const Node* node) - { - size_t chainIndex = getChainIndexForNode(node); - updateTrail(chainIndex, node); - } - //----------------------------------------------------------------------- - void RibbonTrail::nodeDestroyed(const Node* node) - { - removeNode(node); - - } - //----------------------------------------------------------------------- - void RibbonTrail::updateTrail(size_t index, const Node* node) - { - // Repeat this entire process if chain is stretched beyond its natural length - bool done = false; - while (!done) - { - // Node has changed somehow, we're only interested in the derived position - ChainSegment& seg = mChainSegmentList[index]; - Element& headElem = mChainElementList[seg.start + seg.head]; - size_t nextElemIdx = seg.head + 1; - // wrap - if (nextElemIdx == mMaxElementsPerChain) - nextElemIdx = 0; - Element& nextElem = mChainElementList[seg.start + nextElemIdx]; - - // Vary the head elem, but bake new version if that exceeds element len - Vector3 newPos = node->_getDerivedPosition(); - if (mParentNode) - { - // Transform position to ourself space - newPos = mParentNode->convertWorldToLocalPosition(newPos); - } - Vector3 diff = newPos - nextElem.position; - Real sqlen = diff.squaredLength(); - if (sqlen >= mSquaredElemLength) - { - // Move existing head to mElemLength - Vector3 scaledDiff = diff * (mElemLength / Math::Sqrt(sqlen)); - headElem.position = nextElem.position + scaledDiff; - // Add a new element to be the new head - Element newElem( newPos, mInitialWidth[index], 0.0f, - mInitialColour[index], node->_getDerivedOrientation() ); - addChainElement(index, newElem); - // alter diff to represent new head size - diff = newPos - headElem.position; - // check whether another step is needed or not - if (diff.squaredLength() <= mSquaredElemLength) - done = true; - - } - else - { - // Extend existing head - headElem.position = newPos; - done = true; - } - - // Is this segment full? - if ((seg.tail + 1) % mMaxElementsPerChain == seg.head) - { - // If so, shrink tail gradually to match head extension - Element& tailElem = mChainElementList[seg.start + seg.tail]; - size_t preTailIdx; - if (seg.tail == 0) - preTailIdx = mMaxElementsPerChain - 1; - else - preTailIdx = seg.tail - 1; - Element& preTailElem = mChainElementList[seg.start + preTailIdx]; - - // Measure tail diff from pretail to tail - Vector3 taildiff = tailElem.position - preTailElem.position; - Real taillen = taildiff.length(); - if (taillen > 1e-06) - { - Real tailsize = mElemLength - diff.length(); - taildiff *= tailsize / taillen; - tailElem.position = preTailElem.position + taildiff; - } - - } - } // end while - - - mBoundsDirty = true; - // Need to dirty the parent node, but can't do it using needUpdate() here - // since we're in the middle of the scene graph update (node listener), - // so re-entrant calls don't work. Queue. - if (mParentNode) - { - Node::queueNeedUpdate(getParentSceneNode()); - } - - } - //----------------------------------------------------------------------- - void RibbonTrail::_timeUpdate(Real time) - { - // Apply all segment effects - for (size_t s = 0; s < mChainSegmentList.size(); ++s) - { - ChainSegment& seg = mChainSegmentList[s]; - if (seg.head != SEGMENT_EMPTY && seg.head != seg.tail) - { - - for(size_t e = seg.head + 1;; ++e) // until break - { - e = e % mMaxElementsPerChain; - - Element& elem = mChainElementList[seg.start + e]; - elem.width = elem.width - (time * mDeltaWidth[s]); - elem.width = std::max(0.0f, elem.width); - elem.colour = elem.colour - (mDeltaColour[s] * time); - elem.colour.saturate(); - - if (e == seg.tail) - break; - } - } - } - mVertexContentDirty = true; - } - //----------------------------------------------------------------------- - void RibbonTrail::resetTrail(size_t index, const Node* node) - { - assert(index < mChainCount); - - ChainSegment& seg = mChainSegmentList[index]; - // set up this segment - seg.head = seg.tail = SEGMENT_EMPTY; - // Create new element, v coord is always 0.0f - // need to convert to take parent node's position into account - Vector3 position = node->_getDerivedPosition(); - if (mParentNode) - { - position = mParentNode->convertWorldToLocalPosition(position); - } - Element e(position, - mInitialWidth[index], 0.0f, mInitialColour[index], node->_getDerivedOrientation()); - // Add the start position - addChainElement(index, e); - // Add another on the same spot, this will extend - addChainElement(index, e); - } - //----------------------------------------------------------------------- - void RibbonTrail::resetAllTrails(void) - { - for (size_t i = 0; i < mNodeList.size(); ++i) - { - resetTrail(i, mNodeList[i]); - } - } - //----------------------------------------------------------------------- - const String& RibbonTrail::getMovableType(void) const - { - return MOT_RIBBON_TRAIL; - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - const String MOT_RIBBON_TRAIL = "RibbonTrail"; - //----------------------------------------------------------------------- - const String& RibbonTrailFactory::getType(void) const - { - return MOT_RIBBON_TRAIL; - } - //----------------------------------------------------------------------- - MovableObject* RibbonTrailFactory::createInstanceImpl( const String& name, - const NameValuePairList* params) - { - size_t maxElements = 20; - size_t numberOfChains = 1; - bool useTex = true; - bool useCol = true; - // optional params - if (params != 0) - { - NameValuePairList::const_iterator ni = params->find("maxElements"); - if (ni != params->end()) - { - maxElements = StringConverter::parseSizeT(ni->second); - } - ni = params->find("numberOfChains"); - if (ni != params->end()) - { - numberOfChains = StringConverter::parseSizeT(ni->second); - } - ni = params->find("useTextureCoords"); - if (ni != params->end()) - { - useTex = StringConverter::parseBool(ni->second); - } - ni = params->find("useVertexColours"); - if (ni != params->end()) - { - useCol = StringConverter::parseBool(ni->second); - } - - } - - return OGRE_NEW RibbonTrail(name, maxElements, numberOfChains, useTex, useCol); - - } - -} - diff --git a/OgreMain/src/OgreRoot.cpp b/OgreMain/src/OgreRoot.cpp deleted file mode 100644 index dc46846695a..00000000000 --- a/OgreMain/src/OgreRoot.cpp +++ /dev/null @@ -1,1289 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -// Ogre includes -#include - -#include "OgreStableHeaders.h" - -#include "OgreRenderWindow.h" -#include "OgreControllerManager.h" -#include "OgreDynLibManager.h" -#include "OgreDynLib.h" -#include "OgreConfigFile.h" -#include "OgreRenderSystemCapabilitiesManager.h" -#include "OgreSkeletonManager.h" -#include "OgreConfigDialog.h" -#include "OgrePlugin.h" -#include "OgreShadowVolumeExtrudeProgram.h" -#include "OgreResourceBackgroundQueue.h" -#include "OgreEntity.h" -#include "OgreBillboardSet.h" -#include "OgreBillboardChain.h" -#include "OgreRibbonTrail.h" -#include "OgreConvexBody.h" -#include "OgreTimer.h" -#include "OgreFrameListener.h" -#include "OgreLodStrategyManager.h" -#include "OgreFileSystemLayer.h" -#include "OgreStaticGeometry.h" -#include "OgreSceneManagerEnumerator.h" - -#if OGRE_NO_DDS_CODEC == 0 -#include "OgreDDSCodec.h" -#endif - -#include "OgreHardwareBufferManager.h" -#include "OgreGpuProgramManager.h" -#include "OgreExternalTextureSourceManager.h" -#include "OgreCompositorManager.h" - -#if OGRE_NO_PVRTC_CODEC == 0 -# include "OgrePVRTCCodec.h" -#endif -#if OGRE_NO_ETC_CODEC == 0 -# include "OgreETCCodec.h" -#endif -#if OGRE_NO_ASTC_CODEC == 0 -# include "OgreASTCCodec.h" -#endif - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE || OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS -#include "macUtils.h" -#endif - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID -#include "Android/OgreAndroidLogListener.h" -#endif - -namespace Ogre { - //----------------------------------------------------------------------- - template<> Root* Singleton::msSingleton = 0; - Root* Root::getSingletonPtr(void) - { - return msSingleton; - } - Root& Root::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - - typedef void (*DLL_START_PLUGIN)(void); - typedef void (*DLL_STOP_PLUGIN)(void); - - //----------------------------------------------------------------------- - Root::Root(const String& pluginFileName, const String& configFileName, - const String& logFileName) - : mQueuedEnd(false) - , mCurrentSceneManager(NULL) - , mNextFrame(0) - , mFrameSmoothingTime(0.0f) - , mRemoveQueueStructuresOnClear(false) - , mDefaultMinPixelSize(0) - , mNextMovableObjectTypeFlag(1) - , mIsInitialised(false) - , mIsBlendIndicesGpuRedundant(true) - , mIsBlendWeightsGpuRedundant(true) - { - // superclass will do singleton checking - - // Init - mActiveRenderer = 0; - mVersion = StringConverter::toString(OGRE_VERSION_MAJOR) + "." + - StringConverter::toString(OGRE_VERSION_MINOR) + "." + - StringConverter::toString(OGRE_VERSION_PATCH) + - OGRE_VERSION_SUFFIX + " " + - "(" + OGRE_VERSION_NAME + ")"; - mConfigFileName = configFileName; - - // Create log manager and default log file if there is no log manager yet - if(!LogManager::getSingletonPtr()) - { - mLogManager = std::make_unique(); - -#if OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - // suppress writing log to Emscripten virtual FS, improves performance - mLogManager->createLog(logFileName, true, true, true); -#else - mLogManager->createLog(logFileName, true, true); -#endif - } - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - mAndroidLogger.reset(new AndroidLogListener()); - mLogManager->getDefaultLog()->addListener(mAndroidLogger.get()); -#endif - - mDynLibManager = std::make_unique(); - mArchiveManager = std::make_unique(); - mResourceGroupManager = std::make_unique(); - - // WorkQueue (note: users can replace this if they want) - DefaultWorkQueue* defaultQ = OGRE_NEW DefaultWorkQueue("Root"); - // match threads to hardware - int threadCount = OGRE_THREAD_HARDWARE_CONCURRENCY; - // but clamp it at 2 by default - we dont scale much beyond that currently - // yet it helps on android where it needlessly burns CPU - threadCount = Math::Clamp(threadCount, 1, 2); - defaultQ->setWorkerThreadCount(threadCount); - - // only allow workers to access rendersystem if threadsupport is 1 - defaultQ->setWorkersCanAccessRenderSystem(OGRE_THREAD_SUPPORT == 1); - mWorkQueue.reset(defaultQ); - - // ResourceBackgroundQueue - mResourceBackgroundQueue = std::make_unique(); - - // Create SceneManager enumerator (note - will be managed by singleton) - mSceneManagerEnum = std::make_unique(); - mShadowTextureManager = std::make_unique(); - mRenderSystemCapabilitiesManager = std::make_unique(); - mMaterialManager = std::make_unique(); - mMeshManager = std::make_unique(); - mSkeletonManager = std::make_unique(); - mParticleManager = std::make_unique(); - mTimer = std::make_unique(); - mLodStrategyManager = std::make_unique(); - -#if OGRE_PROFILING - // Profiler - mProfiler.reset(new Profiler()); - Profiler::getSingleton().setTimer(mTimer.get()); -#endif - - - mFileSystemArchiveFactory = std::make_unique(); - ArchiveManager::getSingleton().addArchiveFactory( mFileSystemArchiveFactory.get() ); -# if OGRE_NO_ZIP_ARCHIVE == 0 - mZipArchiveFactory = std::make_unique(); - ArchiveManager::getSingleton().addArchiveFactory( mZipArchiveFactory.get() ); - mEmbeddedZipArchiveFactory = std::make_unique(); - ArchiveManager::getSingleton().addArchiveFactory( mEmbeddedZipArchiveFactory.get() ); -# endif - -#if OGRE_NO_DDS_CODEC == 0 - // Register image codecs - DDSCodec::startup(); -#endif -#if OGRE_NO_PVRTC_CODEC == 0 - PVRTCCodec::startup(); -#endif -#if OGRE_NO_ETC_CODEC == 0 - ETCCodec::startup(); -#endif -#if OGRE_NO_ASTC_CODEC == 0 - ASTCCodec::startup(); -#endif - - mGpuProgramManager = std::make_unique(); - mExternalTextureSourceManager = std::make_unique(); - mCompositorManager = std::make_unique(); - mCompilerManager = std::make_unique(); - - // Auto window - mAutoWindow = 0; - - // instantiate and register base movable factories - mEntityFactory = std::make_unique(); - addMovableObjectFactory(mEntityFactory.get()); - mLightFactory = std::make_unique(); - addMovableObjectFactory(mLightFactory.get()); - mBillboardSetFactory = std::make_unique(); - addMovableObjectFactory(mBillboardSetFactory.get()); - mManualObjectFactory = std::make_unique(); - addMovableObjectFactory(mManualObjectFactory.get()); - mBillboardChainFactory = std::make_unique(); - addMovableObjectFactory(mBillboardChainFactory.get()); - mRibbonTrailFactory = std::make_unique(); - addMovableObjectFactory(mRibbonTrailFactory.get()); - mStaticGeometryFactory = std::make_unique(); - addMovableObjectFactory(mStaticGeometryFactory.get()); - mRectangle2DFactory = std::make_unique(); - addMovableObjectFactory(mRectangle2DFactory.get()); - - // Load plugins - if (!pluginFileName.empty()) - loadPlugins(pluginFileName); - - LogManager::getSingleton().logMessage("*-*-* OGRE Initialising"); - LogManager::getSingleton().logMessage("*-*-* Version " + mVersion); - - // Can't create managers until initialised - mControllerManager = 0; - - mFirstTimePostWindowInit = false; - } - - //----------------------------------------------------------------------- - Root::~Root() - { - shutdown(); - -#if OGRE_NO_DDS_CODEC == 0 - DDSCodec::shutdown(); -#endif -#if OGRE_NO_PVRTC_CODEC == 0 - PVRTCCodec::shutdown(); -#endif -#if OGRE_NO_ETC_CODEC == 0 - ETCCodec::shutdown(); -#endif -#if OGRE_NO_ASTC_CODEC == 0 - ASTCCodec::shutdown(); -#endif - mCompositorManager.reset(); // needs rendersystem - mParticleManager.reset(); // may use plugins - mMaterialManager.reset(); // may use GPU program manager - mGpuProgramManager.reset(); // may use plugins - unloadPlugins(); - - mAutoWindow = 0; - - StringInterface::cleanupDictionary(); - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - mLogManager->getDefaultLog()->removeListener(mAndroidLogger.get()); -#endif - } - - //----------------------------------------------------------------------- - void Root::saveConfig(void) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - OGRE_EXCEPT(Exception::ERR_CANNOT_WRITE_TO_FILE, "saveConfig is not supported", - "Root::saveConfig"); -#endif -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - // Check the Documents directory within the application sandbox - Ogre::String outBaseName, extension, configFileName; - Ogre::StringUtil::splitFilename(mConfigFileName, outBaseName, extension); - configFileName = iOSDocumentsDirectory() + "/" + outBaseName; - std::ofstream of(configFileName.c_str()); - if (of.is_open()) - mConfigFileName = configFileName; - else - mConfigFileName.clear(); -#else - if (mConfigFileName.empty()) - return; - - std::ofstream of(mConfigFileName.c_str()); -#endif - if (!of) - OGRE_EXCEPT(Exception::ERR_CANNOT_WRITE_TO_FILE, "Cannot create settings file.", - "Root::saveConfig"); - - if (mActiveRenderer) - { - of << "Render System=" << mActiveRenderer->getName() << std::endl; - } - else - { - of << "Render System=" << std::endl; - } - - for (auto *rs : getAvailableRenderers()) - { - of << std::endl; - of << "[" << rs->getName() << "]" << std::endl; - const ConfigOptionMap& opts = rs->getConfigOptions(); - for (ConfigOptionMap::const_iterator pOpt = opts.begin(); pOpt != opts.end(); ++pOpt) - { - of << pOpt->first << "=" << pOpt->second.currentValue << std::endl; - } - } - - of.close(); - - } - //----------------------------------------------------------------------- - bool Root::restoreConfig(void) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - // Read the config from Documents first(user config) if it exists on iOS. - // If it doesn't exist or is invalid then use mConfigFileName - - Ogre::String outBaseName, extension, configFileName; - Ogre::StringUtil::splitFilename(mConfigFileName, outBaseName, extension); - configFileName = iOSDocumentsDirectory() + "/" + outBaseName; - - std::ifstream fp; - fp.open(configFileName.c_str(), std::ios::in); - if(fp.is_open()) - { - // A config file exists in the users Documents dir, we'll use it - mConfigFileName = configFileName; - } - else - { - std::ifstream configFp; - - // This might be the first run because there is no config file in the - // Documents directory. It could also mean that a config file isn't being used at all - - // Try the path passed into initialise - configFp.open(mConfigFileName.c_str(), std::ios::in); - - // If we can't open this file then we have no default config file to work with - // Use the documents dir then. - if(!configFp.is_open()) - { - // Check to see if one was included in the app bundle - mConfigFileName = macBundlePath() + "/ogre.cfg"; - - configFp.open(mConfigFileName.c_str(), std::ios::in); - - // If we can't open this file then we have no default config file to work with - // Use the Documents dir then. - if(!configFp.is_open()) - mConfigFileName = configFileName; - } - - configFp.close(); - } - - fp.close(); -#endif - - if (mConfigFileName.empty ()) - return true; - - // Restores configuration from saved state - // Returns true if a valid saved configuration is - // available, and false if no saved config is - // stored, or if there has been a problem - ConfigFile cfg; - - try { - // Don't trim whitespace - cfg.load(mConfigFileName, "\t:=", false); - } - catch (FileNotFoundException&) - { - return false; - } - - bool optionError = false; - for(auto& seci : cfg.getSettingsBySection()) { - const ConfigFile::SettingsMultiMap& settings = seci.second; - const String& renderSystem = seci.first; - - RenderSystem* rs = getRenderSystemByName(renderSystem); - if (!rs) - { - // Unrecognised render system - continue; - } - - for (const auto& p : settings) - { - try - { - rs->setConfigOption(p.first, p.second); - } - catch(const InvalidParametersException& e) - { - LogManager::getSingleton().logError(e.getDescription()); - optionError = true; - continue; - } - } - } - - RenderSystem* rs = getRenderSystemByName(cfg.getSetting("Render System")); - if (!rs) - { - // Unrecognised render system - return false; - } - - String err = rs->validateConfigOptions(); - if (err.length() > 0) - return false; - - setRenderSystem(rs); - - // Successful load - return !optionError; - } - - //----------------------------------------------------------------------- - bool Root::showConfigDialog(ConfigDialog* dialog) { - if(dialog) { - if(!mActiveRenderer) - restoreConfig(); - - if (dialog->display()) { - saveConfig(); - return true; - } - - return false; - } - - // just select the first available render system - if (!mRenderers.empty()) - { - setRenderSystem(mRenderers.front()); - return true; - } - - return false; - } - - //----------------------------------------------------------------------- - const RenderSystemList& Root::getAvailableRenderers(void) - { - // Returns a vector of renders - - return mRenderers; - - } - - //----------------------------------------------------------------------- - RenderSystem* Root::getRenderSystemByName(const String& name) - { - if (name.empty()) - { - // No render system - return NULL; - } - - for (auto *rs : getAvailableRenderers()) - { - if (rs->getName() == name) - return rs; - } - - // Unrecognised render system - return NULL; - } - - //----------------------------------------------------------------------- - void Root::setRenderSystem(RenderSystem* system) - { - // Sets the active rendering system - // Can be called direct or will be called by - // standard config dialog - - // Is there already an active renderer? - // If so, disable it and init the new one - if( mActiveRenderer && mActiveRenderer != system ) - { - mActiveRenderer->shutdown(); - } - - mActiveRenderer = system; - // Tell scene managers - if(mSceneManagerEnum) - mSceneManagerEnum->setRenderSystem(system); - - if(RenderSystem::Listener* ls = RenderSystem::getSharedListener()) - ls->eventOccurred("RenderSystemChanged"); - } - //----------------------------------------------------------------------- - void Root::addRenderSystem(RenderSystem *newRend) - { - mRenderers.push_back(newRend); - } - //----------------------------------------------------------------------- - RenderSystem* Root::getRenderSystem(void) - { - // Gets the currently active renderer - return mActiveRenderer; - - } - - //----------------------------------------------------------------------- - RenderWindow* Root::initialise(bool autoCreateWindow, const String& windowTitle) - { - OgreAssert(mActiveRenderer, "Cannot initialise"); - - if (!mControllerManager) - mControllerManager = std::make_unique(); - - PlatformInformation::log(LogManager::getSingleton().getDefaultLog()); - mActiveRenderer->_initialise(); - - // Initialise timer - mTimer->reset(); - - // Init pools - ConvexBody::_initialisePool(); - - mIsInitialised = true; - - if (autoCreateWindow) - { - auto desc = mActiveRenderer->getRenderWindowDescription(); - desc.name = windowTitle; - mAutoWindow = createRenderWindow(desc); - } - - return mAutoWindow; - - } - //----------------------------------------------------------------------- - void Root::useCustomRenderSystemCapabilities(RenderSystemCapabilities* capabilities) - { - mActiveRenderer->useCustomRenderSystemCapabilities(capabilities); - } - //----------------------------------------------------------------------- - void Root::addSceneManagerFactory(SceneManagerFactory* fact) - { - mSceneManagerEnum->addFactory(fact); - } - //----------------------------------------------------------------------- - void Root::removeSceneManagerFactory(SceneManagerFactory* fact) - { - mSceneManagerEnum->removeFactory(fact); - } - //----------------------------------------------------------------------- - const StringVector& Root::getSceneManagerTypes(void) const { return mSceneManagerEnum->getMetaData(); } - //----------------------------------------------------------------------- - SceneManager* Root::createSceneManager(const String& typeName, const String& instanceName) - { - return mSceneManagerEnum->createSceneManager(typeName, instanceName); - } - //----------------------------------------------------------------------- - void Root::destroySceneManager(SceneManager* sm) - { - mSceneManagerEnum->destroySceneManager(sm); - } - //----------------------------------------------------------------------- - SceneManager* Root::getSceneManager(const String& instanceName) const - { - return mSceneManagerEnum->getSceneManager(instanceName); - } - //--------------------------------------------------------------------- - bool Root::hasSceneManager(const String& instanceName) const - { - return mSceneManagerEnum->hasSceneManager(instanceName); - } - //----------------------------------------------------------------------- - const SceneManagerInstanceMap& Root::getSceneManagers(void) const { return mSceneManagerEnum->getSceneManagers(); } - //----------------------------------------------------------------------- - TextureManager* Root::getTextureManager(void) - { - return &TextureManager::getSingleton(); - } - //----------------------------------------------------------------------- - MeshManager* Root::getMeshManager(void) - { - return &MeshManager::getSingleton(); - } - //----------------------------------------------------------------------- - void Root::addFrameListener(FrameListener* newListener) - { - mRemovedFrameListeners.erase(newListener); - mAddedFrameListeners.insert(newListener); - } - //----------------------------------------------------------------------- - void Root::removeFrameListener(FrameListener* oldListener) - { - mAddedFrameListeners.erase(oldListener); - mRemovedFrameListeners.insert(oldListener); - } - //----------------------------------------------------------------------- - void Root::_syncAddedRemovedFrameListeners() - { - for (auto& l : mRemovedFrameListeners) - mFrameListeners.erase(l); - mRemovedFrameListeners.clear(); - - for (auto& l : mAddedFrameListeners) - mFrameListeners.insert(l); - mAddedFrameListeners.clear(); - } - //----------------------------------------------------------------------- - bool Root::_fireFrameStarted(FrameEvent& evt) - { - OgreProfileBeginGroup("Frame", OGREPROF_GENERAL); - _syncAddedRemovedFrameListeners(); - - // Tell all listeners - for (auto *l : mFrameListeners) - { - if(mRemovedFrameListeners.find(l) != mRemovedFrameListeners.end()) - continue; - - if (!l->frameStarted(evt)) - return false; - } - - return true; - } - //----------------------------------------------------------------------- - bool Root::_fireFrameRenderingQueued(FrameEvent& evt) - { - // Increment next frame number - ++mNextFrame; - _syncAddedRemovedFrameListeners(); - - // Tell all listeners - for (auto *l : mFrameListeners) - { - if(mRemovedFrameListeners.find(l) != mRemovedFrameListeners.end()) - continue; - - if (!l->frameRenderingQueued(evt)) - return false; - } - - return true; - } - //----------------------------------------------------------------------- - bool Root::_fireFrameEnded(FrameEvent& evt) - { - _syncAddedRemovedFrameListeners(); - - // Tell all listeners - bool ret = true; - for (auto *l : mFrameListeners) - { - if(mRemovedFrameListeners.find(l) != mRemovedFrameListeners.end()) - continue; - - if (!l->frameEnded(evt)) - { - ret = false; - break; - } - } - - // Tell buffer manager to free temp buffers used this frame - if (HardwareBufferManager::getSingletonPtr()) - HardwareBufferManager::getSingleton()._releaseBufferCopies(); - - // Tell the queue to process responses - mWorkQueue->processMainThreadTasks(); - - OgreProfileEndGroup("Frame", OGREPROF_GENERAL); - - return ret; - } - //----------------------------------------------------------------------- - bool Root::_fireFrameStarted() - { - FrameEvent evt; - populateFrameEvent(FETT_STARTED, evt); - - return _fireFrameStarted(evt); - } - //----------------------------------------------------------------------- - bool Root::_fireFrameRenderingQueued() - { - FrameEvent evt; - populateFrameEvent(FETT_QUEUED, evt); - - return _fireFrameRenderingQueued(evt); - } - //----------------------------------------------------------------------- - bool Root::_fireFrameEnded() - { - FrameEvent evt; - populateFrameEvent(FETT_ENDED, evt); - return _fireFrameEnded(evt); - } - //--------------------------------------------------------------------- - void Root::populateFrameEvent(FrameEventTimeType type, FrameEvent& evtToUpdate) - { - unsigned long now = mTimer->getMilliseconds(); - evtToUpdate.timeSinceLastEvent = calculateEventTime(now, FETT_ANY); - evtToUpdate.timeSinceLastFrame = calculateEventTime(now, type); - } - //----------------------------------------------------------------------- - Real Root::calculateEventTime(unsigned long now, FrameEventTimeType type) - { - // Calculate the average time passed between events of the given type - // during the last mFrameSmoothingTime seconds. - - EventTimesQueue& times = mEventTimes[type]; - times.push_back(now); - - if(times.size() == 1) - return 0; - - // Times up to mFrameSmoothingTime seconds old should be kept - unsigned long discardThreshold = - static_cast(mFrameSmoothingTime * 1000.0f); - - // Find the oldest time to keep - EventTimesQueue::iterator it = times.begin(), - end = times.end()-2; // We need at least two times - while(it != end) - { - if (now - *it > discardThreshold) - ++it; - else - break; - } - - // Remove old times - times.erase(times.begin(), it); - - return Real(times.back() - times.front()) / ((times.size()-1) * 1000); - } - //----------------------------------------------------------------------- - void Root::queueEndRendering(bool state /* = true */) - { - mQueuedEnd = state; - } - //----------------------------------------------------------------------- - bool Root::endRenderingQueued(void) - { - return mQueuedEnd; - } - //----------------------------------------------------------------------- - void Root::startRendering(void) - { - OgreAssert(mActiveRenderer, "no RenderSystem"); - - mActiveRenderer->_initRenderTargets(); - - // Clear event times - clearEventTimes(); - - // Infinite loop, until broken out of by frame listeners - // or break out by calling queueEndRendering() - mQueuedEnd = false; - - while( !mQueuedEnd ) - { - if (!renderOneFrame()) - break; - } - } - //----------------------------------------------------------------------- - bool Root::renderOneFrame(void) - { - if(!_fireFrameStarted()) - return false; - - if (!_updateAllRenderTargets()) - return false; - - return _fireFrameEnded(); - } - //--------------------------------------------------------------------- - bool Root::renderOneFrame(Real timeSinceLastFrame) - { - FrameEvent evt; - evt.timeSinceLastFrame = timeSinceLastFrame; - - unsigned long now = mTimer->getMilliseconds(); - evt.timeSinceLastEvent = calculateEventTime(now, FETT_ANY); - - if(!_fireFrameStarted(evt)) - return false; - - if (!_updateAllRenderTargets(evt)) - return false; - - now = mTimer->getMilliseconds(); - evt.timeSinceLastEvent = calculateEventTime(now, FETT_ANY); - - return _fireFrameEnded(evt); - } - //----------------------------------------------------------------------- - void Root::shutdown(void) - { - if(mActiveRenderer) - mActiveRenderer->_setViewport(NULL); - - // Since background thread might be access resources, - // ensure shutdown before destroying resource manager. - mWorkQueue->shutdown(); - - if(mSceneManagerEnum) - mSceneManagerEnum->shutdownAll(); - if(mFirstTimePostWindowInit) - { - shutdownPlugins(); - mParticleManager->removeAllTemplates(true); - mFirstTimePostWindowInit = false; - } - mSceneManagerEnum.reset(); - mShadowTextureManager.reset(); - - ShadowVolumeExtrudeProgram::shutdown(); - ResourceGroupManager::getSingleton().shutdownAll(); - - // Destroy pools - ConvexBody::_destroyPool(); - - - mIsInitialised = false; - - LogManager::getSingleton().logMessage("*-*-* OGRE Shutdown"); - } - //----------------------------------------------------------------------- - void Root::loadPlugins( const String& pluginsfile ) - { - StringVector pluginList; - String pluginDir; - ConfigFile cfg; - - try { - cfg.load( pluginsfile ); - } - catch (Exception& e) - { - LogManager::getSingleton().logError(e.getDescription()+" - skipping automatic plugin loading"); - return; - } - - pluginDir = cfg.getSetting("PluginFolder"); - pluginList = cfg.getMultiSetting("Plugin"); - - StringUtil::trim(pluginDir); - if(pluginDir.empty() || pluginDir[0] == '.') - { - // resolve relative path with regards to configfile - String baseDir, filename; - StringUtil::splitFilename(pluginsfile, filename, baseDir); - pluginDir = baseDir + pluginDir; - } - - if(char* val = getenv("OGRE_PLUGIN_DIR")) - { - pluginDir = val; - LogManager::getSingleton().logMessage( - "setting PluginFolder from OGRE_PLUGIN_DIR environment variable"); - } - - pluginDir = FileSystemLayer::resolveBundlePath(pluginDir); - - if (!pluginDir.empty() && *pluginDir.rbegin() != '/' && *pluginDir.rbegin() != '\\') - { -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT - pluginDir += "\\"; -#else - pluginDir += "/"; -#endif - } - - for(auto& p : pluginList) - { - loadPlugin(pluginDir + p); - } - } - //----------------------------------------------------------------------- - void Root::shutdownPlugins(void) - { - // NB Shutdown plugins in reverse order to enforce dependencies - for (PluginInstanceList::reverse_iterator i = mPlugins.rbegin(); i != mPlugins.rend(); ++i) - { - (*i)->shutdown(); - } - } - //----------------------------------------------------------------------- - void Root::initialisePlugins(void) - { - for (auto *p : mPlugins) - { - p->initialise(); - } - } - //----------------------------------------------------------------------- - void Root::unloadPlugins(void) - { -#if OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN - // unload dynamic libs first - for (PluginLibList::reverse_iterator i = mPluginLibs.rbegin(); i != mPluginLibs.rend(); ++i) - { - // Call plugin shutdown - #ifdef __GNUC__ - __extension__ - #endif - DLL_STOP_PLUGIN pFunc = reinterpret_cast((*i)->getSymbol("dllStopPlugin")); - // this will call uninstallPlugin - pFunc(); - // Unload library & destroy - DynLibManager::getSingleton().unload(*i); - - } - mPluginLibs.clear(); - - // now deal with any remaining plugins that were registered through other means - for (PluginInstanceList::reverse_iterator i = mPlugins.rbegin(); i != mPlugins.rend(); ++i) - { - // Note this does NOT call uninstallPlugin - this shutdown is for the - // detail objects - (*i)->uninstall(); - } - mPlugins.clear(); -#endif - } - //--------------------------------------------------------------------- - DataStreamPtr Root::createFileStream(const String& filename, const String& groupName, - bool overwrite, const String& locationPattern) - { - // Does this file include path specifiers? - String path, basename; - StringUtil::splitFilename(filename, basename, path); - - // no path elements, try the resource system first - DataStreamPtr stream; - if (path.empty()) - { - try - { - stream = ResourceGroupManager::getSingleton().createResource( - filename, groupName, overwrite, locationPattern); - } - catch (...) {} - - } - - if (!stream) - { - // save direct in filesystem - stream = _openFileStream(filename, std::ios::out | std::ios::binary); - } - - return stream; - - } - //--------------------------------------------------------------------- - DataStreamPtr Root::openFileStream(const String& filename, const String& groupName) - { - DataStreamPtr ret; - if(auto rgm = ResourceGroupManager::getSingletonPtr()) - ret = rgm->openResource(filename, groupName, NULL, false); - - if(ret) - return ret; - - return _openFileStream(filename, std::ios::in | std::ios::binary); - } - //----------------------------------------------------------------------- - RenderWindow* Root::getAutoCreatedWindow(void) - { - return mAutoWindow; - } - //----------------------------------------------------------------------- - RenderWindow* Root::createRenderWindow(const String &name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams) - { - OgreAssert(mIsInitialised, - "Cannot create window! Make sure to call Root::initialise before creating a window"); - OgreAssert(mActiveRenderer, "Cannot create window"); - - RenderWindow* ret; - ret = mActiveRenderer->_createRenderWindow(name, width, height, fullScreen, miscParams); - - // Initialisation for classes dependent on first window created - if(!mFirstTimePostWindowInit) - { - oneTimePostWindowInit(); - ret->_setPrimary(); - } - - return ret; - - } - //----------------------------------------------------------------------- - RenderTarget* Root::detachRenderTarget(RenderTarget* target) - { - OgreAssert(mActiveRenderer, "Cannot detach target"); - return mActiveRenderer->detachRenderTarget( target->getName() ); - } - //----------------------------------------------------------------------- - RenderTarget* Root::detachRenderTarget(const String &name) - { - OgreAssert(mActiveRenderer, "Cannot detach target"); - return mActiveRenderer->detachRenderTarget( name ); - } - //----------------------------------------------------------------------- - void Root::destroyRenderTarget(RenderTarget* target) - { - detachRenderTarget(target); - OGRE_DELETE target; - } - //----------------------------------------------------------------------- - void Root::destroyRenderTarget(const String &name) - { - RenderTarget* target = getRenderTarget(name); - destroyRenderTarget(target); - } - //----------------------------------------------------------------------- - RenderTarget* Root::getRenderTarget(const String &name) - { - OgreAssert(mActiveRenderer, "Cannot get target"); - return mActiveRenderer->getRenderTarget(name); - } - //--------------------------------------------------------------------- - void Root::installPlugin(Plugin* plugin) - { - LogManager::getSingleton().logMessage("Installing plugin: " + plugin->getName()); - - mPlugins.push_back(plugin); - plugin->install(); - - // if rendersystem is already initialised, call rendersystem init too - if (mIsInitialised) - { - plugin->initialise(); - } - - LogManager::getSingleton().logMessage("Plugin successfully installed"); - } - //--------------------------------------------------------------------- - void Root::uninstallPlugin(Plugin* plugin) - { - LogManager::getSingleton().logMessage("Uninstalling plugin: " + plugin->getName()); - PluginInstanceList::iterator i = - std::find(mPlugins.begin(), mPlugins.end(), plugin); - if (i != mPlugins.end()) - { - if (mIsInitialised) - plugin->shutdown(); - plugin->uninstall(); - mPlugins.erase(i); - } - LogManager::getSingleton().logMessage("Plugin successfully uninstalled"); - - } - //----------------------------------------------------------------------- - void Root::loadPlugin(const String& pluginName) - { -#if OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN - // Load plugin library - DynLib* lib = DynLibManager::getSingleton().load( pluginName ); - // Store for later unload - // Check for existence, because if called 2+ times DynLibManager returns existing entry - if (std::find(mPluginLibs.begin(), mPluginLibs.end(), lib) == mPluginLibs.end()) - { - mPluginLibs.push_back(lib); - - // Call startup function - #ifdef __GNUC__ - __extension__ - #endif - DLL_START_PLUGIN pFunc = (DLL_START_PLUGIN)lib->getSymbol("dllStartPlugin"); - - if (!pFunc) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Cannot find symbol dllStartPlugin in library " + pluginName, - "Root::loadPlugin"); - - // This must call installPlugin - pFunc(); - } -#endif - } - //----------------------------------------------------------------------- - void Root::unloadPlugin(const String& pluginName) - { -#if OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN - PluginLibList::iterator i; - - for (i = mPluginLibs.begin(); i != mPluginLibs.end(); ++i) - { - if ((*i)->getName() == pluginName) - { - // Call plugin shutdown - #ifdef __GNUC__ - __extension__ - #endif - DLL_STOP_PLUGIN pFunc = (DLL_STOP_PLUGIN)(*i)->getSymbol("dllStopPlugin"); - // this must call uninstallPlugin - pFunc(); - // Unload library (destroyed by DynLibManager) - DynLibManager::getSingleton().unload(*i); - mPluginLibs.erase(i); - return; - } - - } -#endif - } - //----------------------------------------------------------------------- - Timer* Root::getTimer(void) - { - return mTimer.get(); - } - //----------------------------------------------------------------------- - void Root::oneTimePostWindowInit(void) - { - // log RenderSystem caps - mActiveRenderer->getCapabilities()->log(LogManager::getSingleton().getDefaultLog()); - - // Background loader - mWorkQueue->startup(); - // Initialise material manager - mMaterialManager->initialise(); - // Init particle systems manager - mParticleManager->_initialise(); - // Init mesh manager - MeshManager::getSingleton()._initialise(); - // Init plugins - after window creation so rsys resources available - initialisePlugins(); - mFirstTimePostWindowInit = true; - } - //----------------------------------------------------------------------- - bool Root::_updateAllRenderTargets(void) - { - // update all targets but don't swap buffers - mActiveRenderer->_updateAllRenderTargets(false); - // give client app opportunity to use queued GPU time - bool ret = _fireFrameRenderingQueued(); - // block for final swap - mActiveRenderer->_swapAllRenderTargetBuffers(); - - // This belongs here, as all render targets must be updated before events are - // triggered, otherwise targets could be mismatched. This could produce artifacts, - // for instance, with shadows. - for (const auto& m : getSceneManagers()) - m.second->_handleLodEvents(); - - return ret; - } - //--------------------------------------------------------------------- - bool Root::_updateAllRenderTargets(FrameEvent& evt) - { - // update all targets but don't swap buffers - mActiveRenderer->_updateAllRenderTargets(false); - // give client app opportunity to use queued GPU time - bool ret = _fireFrameRenderingQueued(evt); - // block for final swap - mActiveRenderer->_swapAllRenderTargetBuffers(); - - // This belongs here, as all render targets must be updated before events are - // triggered, otherwise targets could be mismatched. This could produce artifacts, - // for instance, with shadows. - for (const auto& m : getSceneManagers()) - m.second->_handleLodEvents(); - - return ret; - } - //----------------------------------------------------------------------- - void Root::clearEventTimes(void) - { - // Clear event times - for(int i=0; igetType()); - if (!overrideExisting && facti != mMovableObjectFactoryMap.end()) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "A factory of type '" + fact->getType() + "' already exists.", - "Root::addMovableObjectFactory"); - } - - if (fact->requestTypeFlags()) - { - if (facti != mMovableObjectFactoryMap.end() && facti->second->requestTypeFlags()) - { - // Copy type flags from the factory we're replacing - fact->_notifyTypeFlags(facti->second->getTypeFlags()); - } - else - { - // Allocate new - fact->_notifyTypeFlags(_allocateNextMovableObjectTypeFlag()); - } - } - - // Save - mMovableObjectFactoryMap[fact->getType()] = fact; - - LogManager::getSingleton().logMessage("MovableObjectFactory for type '" + - fact->getType() + "' registered."); - - } - //--------------------------------------------------------------------- - bool Root::hasMovableObjectFactory(const String& typeName) const - { - return !(mMovableObjectFactoryMap.find(typeName) == mMovableObjectFactoryMap.end()); - } - //--------------------------------------------------------------------- - MovableObjectFactory* Root::getMovableObjectFactory(const String& typeName) - { - MovableObjectFactoryMap::iterator i = - mMovableObjectFactoryMap.find(typeName); - if (i == mMovableObjectFactoryMap.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "MovableObjectFactory of type " + typeName + " does not exist", - "Root::getMovableObjectFactory"); - } - return i->second; - } - //--------------------------------------------------------------------- - uint32 Root::_allocateNextMovableObjectTypeFlag(void) - { - if (mNextMovableObjectTypeFlag == SceneManager::USER_TYPE_MASK_LIMIT) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "Cannot allocate a type flag since " - "all the available flags have been used.", - "Root::_allocateNextMovableObjectTypeFlag"); - - } - uint32 ret = mNextMovableObjectTypeFlag; - mNextMovableObjectTypeFlag <<= 1; - return ret; - - } - //--------------------------------------------------------------------- - void Root::removeMovableObjectFactory(MovableObjectFactory* fact) - { - MovableObjectFactoryMap::iterator i = mMovableObjectFactoryMap.find( - fact->getType()); - if (i != mMovableObjectFactoryMap.end()) - { - mMovableObjectFactoryMap.erase(i); - } - - } - //--------------------------------------------------------------------- - Root::MovableObjectFactoryIterator - Root::getMovableObjectFactoryIterator(void) const - { - return MovableObjectFactoryIterator(mMovableObjectFactoryMap.begin(), - mMovableObjectFactoryMap.end()); - - } - //--------------------------------------------------------------------- - void Root::setWorkQueue(WorkQueue* queue) - { - if (mWorkQueue.get() != queue) - { - mWorkQueue.reset(queue); - if (mIsInitialised) - mWorkQueue->startup(); - - } - } -} diff --git a/OgreMain/src/OgreRotationSpline.cpp b/OgreMain/src/OgreRotationSpline.cpp deleted file mode 100644 index b0cdd691611..00000000000 --- a/OgreMain/src/OgreRotationSpline.cpp +++ /dev/null @@ -1,225 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreRotationalSpline.h" - - - -namespace Ogre { - - //--------------------------------------------------------------------- - RotationalSpline::RotationalSpline() - : mAutoCalc(true) - { - } - //--------------------------------------------------------------------- - RotationalSpline::~RotationalSpline() - { - } - //--------------------------------------------------------------------- - void RotationalSpline::addPoint(const Quaternion& p) - { - mPoints.push_back(p); - if (mAutoCalc) - { - recalcTangents(); - } - } - //--------------------------------------------------------------------- - Quaternion RotationalSpline::interpolate(Real t, bool useShortestPath) - { - // Work out which segment this is in - Real fSeg = t * (mPoints.size() - 1); - unsigned int segIdx = (unsigned int)fSeg; - // Apportion t - t = fSeg - segIdx; - - return interpolate(segIdx, t, useShortestPath); - - } - //--------------------------------------------------------------------- - Quaternion RotationalSpline::interpolate(unsigned int fromIndex, Real t, - bool useShortestPath) - { - // Bounds check - assert (fromIndex < mPoints.size() && - "fromIndex out of bounds"); - - if ((fromIndex + 1) == mPoints.size()) - { - // Duff request, cannot blend to nothing - // Just return source - return mPoints[fromIndex]; - - } - // Fast special cases - if (t == 0.0f) - { - return mPoints[fromIndex]; - } - else if(t == 1.0f) - { - return mPoints[fromIndex + 1]; - } - - // Real interpolation - // Use squad using tangents we've already set up - Quaternion &p = mPoints[fromIndex]; - Quaternion &q = mPoints[fromIndex+1]; - Quaternion &a = mTangents[fromIndex]; - Quaternion &b = mTangents[fromIndex+1]; - - // NB interpolate to nearest rotation - return Quaternion::Squad(t, p, a, b, q, useShortestPath); - - } - //--------------------------------------------------------------------- - void RotationalSpline::recalcTangents(void) - { - // ShoeMake (1987) approach - // Just like Catmull-Rom really, just more gnarly - // And no, I don't understand how to derive this! - // - // let p = point[i], pInv = p.Inverse - // tangent[i] = p * exp( -0.25 * ( log(pInv * point[i+1]) + log(pInv * point[i-1]) ) ) - // - // Assume endpoint tangents are parallel with line with neighbour - - unsigned int i, numPoints; - bool isClosed; - - numPoints = (unsigned int)mPoints.size(); - - if (numPoints < 2) - { - // Can't do anything yet - return; - } - - mTangents.resize(numPoints); - - if (mPoints[0] == mPoints[numPoints-1]) - { - isClosed = true; - } - else - { - isClosed = false; - } - - Quaternion invp, part1, part2, preExp; - for(i = 0; i < numPoints; ++i) - { - Quaternion &p = mPoints[i]; - invp = p.Inverse(); - - if (i ==0) - { - // special case start - part1 = (invp * mPoints[i+1]).Log(); - if (isClosed) - { - // Use numPoints-2 since numPoints-1 == end == start == this one - part2 = (invp * mPoints[numPoints-2]).Log(); - } - else - { - part2 = (invp * p).Log(); - } - } - else if (i == numPoints-1) - { - // special case end - if (isClosed) - { - // Wrap to [1] (not [0], this is the same as end == this one) - part1 = (invp * mPoints[1]).Log(); - } - else - { - part1 = (invp * p).Log(); - } - part2 = (invp * mPoints[i-1]).Log(); - } - else - { - part1 = (invp * mPoints[i+1]).Log(); - part2 = (invp * mPoints[i-1]).Log(); - } - - preExp = -0.25 * (part1 + part2); - mTangents[i] = p * preExp.Exp(); - - } - - - - } - //--------------------------------------------------------------------- - const Quaternion& RotationalSpline::getPoint(unsigned short index) const - { - assert (index < mPoints.size() && "Point index is out of bounds!!"); - - return mPoints[index]; - } - //--------------------------------------------------------------------- - unsigned short RotationalSpline::getNumPoints(void) const - { - return (unsigned short)mPoints.size(); - } - //--------------------------------------------------------------------- - void RotationalSpline::clear(void) - { - mPoints.clear(); - mTangents.clear(); - } - //--------------------------------------------------------------------- - void RotationalSpline::updatePoint(unsigned short index, const Quaternion& value) - { - assert (index < mPoints.size() && "Point index is out of bounds!!"); - - mPoints[index] = value; - if (mAutoCalc) - { - recalcTangents(); - } - } - //--------------------------------------------------------------------- - void RotationalSpline::setAutoCalculate(bool autoCalc) - { - mAutoCalc = autoCalc; - } - //--------------------------------------------------------------------- - - - -} - - - - diff --git a/OgreMain/src/OgreSIMDHelper.h b/OgreMain/src/OgreSIMDHelper.h deleted file mode 100644 index e9336928c12..00000000000 --- a/OgreMain/src/OgreSIMDHelper.h +++ /dev/null @@ -1,309 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __SIMDHelper_H__ -#define __SIMDHelper_H__ - -// Stack-alignment hackery. -// -// If macro __OGRE_SIMD_ALIGN_STACK defined, means there requests -// special code to ensure stack align to a 16-bytes boundary. -// -// Note: -// This macro can only guarantee callee stack pointer (esp) align -// to a 16-bytes boundary, but not that for frame pointer (ebp). -// Because most compiler might use frame pointer to access to stack -// variables, so you need to wrap those alignment required functions -// with extra function call. -// -#if defined(__INTEL_COMPILER) -// For intel's compiler, simply calling alloca seems to do the right -// thing. The size of the allocated block seems to be irrelevant. -#define __OGRE_SIMD_ALIGN_STACK() _alloca(16) -#define __OGRE_SIMD_ALIGN_ATTRIBUTE - -#elif OGRE_CPU == OGRE_CPU_X86 && (OGRE_COMPILER == OGRE_COMPILER_GNUC || OGRE_COMPILER == OGRE_COMPILER_CLANG) && (OGRE_ARCH_TYPE != OGRE_ARCHITECTURE_64) -// mark functions with GCC attribute to force stack alignment to 16 bytes -#define __OGRE_SIMD_ALIGN_ATTRIBUTE __attribute__((force_align_arg_pointer)) - -#elif defined(_MSC_VER) -// Fortunately, MSVC will align the stack automatically -#define __OGRE_SIMD_ALIGN_ATTRIBUTE - -#else -#define __OGRE_SIMD_ALIGN_ATTRIBUTE - -#endif - - -// Additional platform-dependent header files and declares. -// -// NOTE: Should be sync with __OGRE_HAVE_SSE macro. -// - -#if __OGRE_HAVE_SSE -#include -#elif __OGRE_HAVE_NEON -#include "SSE2NEON.h" - -// some conversions custom to OGRE -#define _mm_cmpnle_ps _mm_cmpgt_ps - -// self written -OGRE_FORCE_INLINE __m128 _mm_loadh_pi( __m128 a , __m64 const * p ) -{ - return vcombine_f32(vget_low_f32(a), vld1_f32((float32_t const *)p)); -} -// self written -OGRE_FORCE_INLINE void _mm_storeh_pi( __m64 * p , __m128 a ) -{ - vst1_f32((float32_t *)p, vget_high_f32((float32x4_t)a)); -} - -OGRE_FORCE_INLINE __m128 _mm_mul_ss(__m128 a, __m128 b) -{ - a[0] *= b[0]; - return a; -} - -OGRE_FORCE_INLINE __m128 _mm_sub_ss(__m128 a, __m128 b) -{ - a[0] -= b[0]; - return a; -} -#endif - - - -//--------------------------------------------------------------------- -// SIMD macros and helpers -//--------------------------------------------------------------------- - - -namespace Ogre { - /** \addtogroup Core - * @{ - */ - /** \addtogroup Math - * @{ - */ - -#if __OGRE_HAVE_SSE || __OGRE_HAVE_NEON - -#define __MM_RSQRT_PS(x) _mm_rsqrt_ps(x) - - -/** Performing the transpose of a 4x4 matrix of single precision floating - point values. - Arguments r0, r1, r2, and r3 are __m128 values whose elements - form the corresponding rows of a 4x4 matrix. - The matrix transpose is returned in arguments r0, r1, r2, and - r3 where r0 now holds column 0 of the original matrix, r1 now - holds column 1 of the original matrix, etc. -*/ -#define __MM_TRANSPOSE4x4_PS(r0, r1, r2, r3) \ - { \ - __m128 tmp3, tmp2, tmp1, tmp0; \ - \ - /* r00 r01 r02 r03 */ \ - /* r10 r11 r12 r13 */ \ - /* r20 r21 r22 r23 */ \ - /* r30 r31 r32 r33 */ \ - \ - tmp0 = _mm_unpacklo_ps(r0, r1); /* r00 r10 r01 r11 */ \ - tmp2 = _mm_unpackhi_ps(r0, r1); /* r02 r12 r03 r13 */ \ - tmp1 = _mm_unpacklo_ps(r2, r3); /* r20 r30 r21 r31 */ \ - tmp3 = _mm_unpackhi_ps(r2, r3); /* r22 r32 r23 r33 */ \ - \ - r0 = _mm_movelh_ps(tmp0, tmp1); /* r00 r10 r20 r30 */ \ - r1 = _mm_movehl_ps(tmp1, tmp0); /* r01 r11 r21 r31 */ \ - r2 = _mm_movelh_ps(tmp2, tmp3); /* r02 r12 r22 r32 */ \ - r3 = _mm_movehl_ps(tmp3, tmp2); /* r03 r13 r23 r33 */ \ - } - -/** Performing the transpose of a continuous stored rows of a 4x3 matrix to - a 3x4 matrix of single precision floating point values. - Arguments v0, v1, and v2 are __m128 values whose elements form the - corresponding continuous stored rows of a 4x3 matrix. - The matrix transpose is returned in arguments v0, v1, and v2, where - v0 now holds column 0 of the original matrix, v1 now holds column 1 - of the original matrix, etc. -*/ -#define __MM_TRANSPOSE4x3_PS(v0, v1, v2) \ - { \ - __m128 tmp0, tmp1, tmp2; \ - \ - /* r00 r01 r02 r10 */ \ - /* r11 r12 r20 r21 */ \ - /* r22 r30 r31 r32 */ \ - \ - tmp0 = _mm_shuffle_ps(v0, v2, _MM_SHUFFLE(3,0,3,0)); /* r00 r10 r22 r32 */ \ - tmp1 = _mm_shuffle_ps(v0, v1, _MM_SHUFFLE(1,0,2,1)); /* r01 r02 r11 r12 */ \ - tmp2 = _mm_shuffle_ps(v1, v2, _MM_SHUFFLE(2,1,3,2)); /* r20 r21 r30 r31 */ \ - \ - v0 = _mm_shuffle_ps(tmp0, tmp2, _MM_SHUFFLE(2,0,1,0)); /* r00 r10 r20 r30 */ \ - v1 = _mm_shuffle_ps(tmp1, tmp2, _MM_SHUFFLE(3,1,2,0)); /* r01 r11 r21 r31 */ \ - v2 = _mm_shuffle_ps(tmp1, tmp0, _MM_SHUFFLE(3,2,3,1)); /* r02 r12 r22 r32 */ \ - } - -/** Performing the transpose of a 3x4 matrix to a continuous stored rows of - a 4x3 matrix of single precision floating point values. - Arguments v0, v1, and v2 are __m128 values whose elements form the - corresponding columns of a 3x4 matrix. - The matrix transpose is returned in arguments v0, v1, and v2, as a - continuous stored rows of a 4x3 matrix. -*/ -#define __MM_TRANSPOSE3x4_PS(v0, v1, v2) \ - { \ - __m128 tmp0, tmp1, tmp2; \ - \ - /* r00 r10 r20 r30 */ \ - /* r01 r11 r21 r31 */ \ - /* r02 r12 r22 r32 */ \ - \ - tmp0 = _mm_shuffle_ps(v0, v2, _MM_SHUFFLE(2,0,3,1)); /* r10 r30 r02 r22 */ \ - tmp1 = _mm_shuffle_ps(v1, v2, _MM_SHUFFLE(3,1,3,1)); /* r11 r31 r12 r32 */ \ - tmp2 = _mm_shuffle_ps(v0, v1, _MM_SHUFFLE(2,0,2,0)); /* r00 r20 r01 r21 */ \ - \ - v0 = _mm_shuffle_ps(tmp2, tmp0, _MM_SHUFFLE(0,2,2,0)); /* r00 r01 r02 r10 */ \ - v1 = _mm_shuffle_ps(tmp1, tmp2, _MM_SHUFFLE(3,1,2,0)); /* r11 r12 r20 r21 */ \ - v2 = _mm_shuffle_ps(tmp0, tmp1, _MM_SHUFFLE(3,1,1,3)); /* r22 r30 r31 r32 */ \ - } - -/** Fill vector of single precision floating point with selected value. - Argument 'fp' is a digit[0123] that represents the fp of argument 'v'. -*/ -#define __MM_SELECT(v, fp) \ - _mm_shuffle_ps((v), (v), _MM_SHUFFLE((fp),(fp),(fp),(fp))) - -/// Accumulate four vector of single precision floating point values. -#define __MM_ACCUM4_PS(a, b, c, d) \ - _mm_add_ps(_mm_add_ps(a, b), _mm_add_ps(c, d)) - -/** Performing dot-product between two of four vector of single precision - floating point values. -*/ -#define __MM_DOT4x4_PS(a0, a1, a2, a3, b0, b1, b2, b3) \ - __MM_ACCUM4_PS(_mm_mul_ps(a0, b0), _mm_mul_ps(a1, b1), _mm_mul_ps(a2, b2), _mm_mul_ps(a3, b3)) - -/** Performing dot-product between four vector and three vector of single - precision floating point values. -*/ -#define __MM_DOT4x3_PS(r0, r1, r2, r3, v0, v1, v2) \ - __MM_ACCUM4_PS(_mm_mul_ps(r0, v0), _mm_mul_ps(r1, v1), _mm_mul_ps(r2, v2), r3) - -/// Accumulate three vector of single precision floating point values. -#define __MM_ACCUM3_PS(a, b, c) \ - _mm_add_ps(_mm_add_ps(a, b), c) - -/** Performing dot-product between two of three vector of single precision - floating point values. -*/ -#define __MM_DOT3x3_PS(r0, r1, r2, v0, v1, v2) \ - __MM_ACCUM3_PS(_mm_mul_ps(r0, v0), _mm_mul_ps(r1, v1), _mm_mul_ps(r2, v2)) - -/// Calculate multiply of two vector and plus another vector -#define __MM_MADD_PS(a, b, c) \ - _mm_add_ps(_mm_mul_ps(a, b), c) - -/// Linear interpolation -#define __MM_LERP_PS(t, a, b) \ - __MM_MADD_PS(_mm_sub_ps(b, a), t, a) - -/// Calculate multiply of two single floating value and plus another floating value -#define __MM_MADD_SS(a, b, c) \ - _mm_add_ss(_mm_mul_ss(a, b), c) - -/// Linear interpolation -#define __MM_LERP_SS(t, a, b) \ - __MM_MADD_SS(_mm_sub_ss(b, a), t, a) - -/// Same as _mm_load_ps, but can help VC generate more optimised code. -#define __MM_LOAD_PS(p) \ - (*(const __m128*)(p)) - -/// Same as _mm_store_ps, but can help VC generate more optimised code. -#define __MM_STORE_PS(p, v) \ - (*(__m128*)(p) = (v)) - - - /** Helper to load/store SSE data based on whether or not aligned. - */ - template - struct SSEMemoryAccessor - { - static OGRE_FORCE_INLINE __m128 load(const float *p) - { - return _mm_loadu_ps(p); - } - static OGRE_FORCE_INLINE void store(float *p, const __m128& v) - { - _mm_storeu_ps(p, v); - } - }; - // Special aligned accessor - template <> - struct SSEMemoryAccessor - { - static OGRE_FORCE_INLINE const __m128& load(const float *p) - { - return __MM_LOAD_PS(p); - } - static OGRE_FORCE_INLINE void store(float *p, const __m128& v) - { - __MM_STORE_PS(p, v); - } - }; - - /** Check whether or not the given pointer perfect aligned for SSE. - */ - static OGRE_FORCE_INLINE bool _isAlignedForSSE(const void *p) - { - return (((size_t)p) & 15) == 0; - } - -// Macro to check the stack aligned for SSE -#if OGRE_DEBUG_MODE -#define __OGRE_CHECK_STACK_ALIGNED_FOR_SSE() \ - { \ - __m128 test = {}; \ - assert(_isAlignedForSSE(&test)); \ - } - -#else // !OGRE_DEBUG_MODE -#define __OGRE_CHECK_STACK_ALIGNED_FOR_SSE() - -#endif // OGRE_DEBUG_MODE - - -#endif // __OGRE_HAVE_SSE - /** @} */ - /** @} */ - -} - -#endif // __SIMDHelper_H__ diff --git a/OgreMain/src/OgreSceneManager.cpp b/OgreMain/src/OgreSceneManager.cpp deleted file mode 100644 index 359c08a7da4..00000000000 --- a/OgreMain/src/OgreSceneManager.cpp +++ /dev/null @@ -1,3688 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreEntity.h" -#include "OgreControllerManager.h" -#include "OgreAnimation.h" -#include "OgreRenderObjectListener.h" -#include "OgreBillboardSet.h" -#include "OgreStaticGeometry.h" -#include "OgreSubEntity.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreBillboardChain.h" -#include "OgreRibbonTrail.h" -#include "OgreParticleSystem.h" -#include "OgreCompositorChain.h" -#include "OgreInstanceBatch.h" -#include "OgreInstancedEntity.h" -#include "OgreRenderTexture.h" -#include "OgreLodListener.h" -#include "OgreDefaultDebugDrawer.h" - -// This class implements the most basic scene manager - -#include -#include - -namespace Ogre { -//----------------------------------------------------------------------- -SceneManager::SceneManager(const String& name) : -mName(name), -mCameraInProgress(0), -mCurrentViewport(0), -mSkyPlane(this), -mSkyBox(this), -mSkyDome(this), -mFogMode(FOG_NONE), -mFogColour(), -mFogStart(0), -mFogEnd(0), -mFogDensity(0), -mSpecialCaseQueueMode(SCRQM_EXCLUDE), -mWorldGeometryRenderQueue(RENDER_QUEUE_WORLD_GEOMETRY_1), -mLastFrameNumber(0), -mResetIdentityView(false), -mResetIdentityProj(false), -mFlipCullingOnNegativeScale(true), -mLightsDirtyCounter(0), -mMovableNameGenerator("Ogre/MO"), -mDisplayNodes(false), -mShowBoundingBoxes(false), -mActiveCompositorChain(0), -mLateMaterialResolving(false), -mIlluminationStage(IRS_NONE), -mShadowRenderer(this), -mLightClippingInfoMapFrameNumber(999), -mVisibilityMask(0xFFFFFFFF), -mFindVisibleObjects(true), -mCameraRelativeRendering(false), -mLastLightHash(0), -mGpuParamsDirty((uint16)GPV_ALL) -{ - if (Root* root = Root::getSingletonPtr()) - _setDestinationRenderSystem(root->getRenderSystem()); - - // Setup default queued renderable visitor - mActiveQueuedRenderableVisitor = &mDefaultQueuedRenderableVisitor; - - // init shadow texture config - setShadowTextureCount(1); - - mDebugDrawer = std::make_unique(); - addListener(mDebugDrawer.get()); - - // create the auto param data source instance - mAutoParamDataSource.reset(createAutoParamDataSource()); -} -//----------------------------------------------------------------------- -SceneManager::~SceneManager() -{ - fireSceneManagerDestroyed(); - clearScene(); - destroyAllCameras(); - - // clear down movable object collection map - { - OGRE_LOCK_MUTEX(mMovableObjectCollectionMapMutex); - for (MovableObjectCollectionMap::iterator i = mMovableObjectCollectionMap.begin(); - i != mMovableObjectCollectionMap.end(); ++i) - { - OGRE_DELETE_T(i->second, MovableObjectCollection, MEMCATEGORY_SCENE_CONTROL); - } - mMovableObjectCollectionMap.clear(); - } -} -//----------------------------------------------------------------------- -RenderQueue* SceneManager::getRenderQueue(void) -{ - if (!mRenderQueue) - { - initRenderQueue(); - } - return mRenderQueue.get(); -} -//----------------------------------------------------------------------- -void SceneManager::initRenderQueue(void) -{ - mRenderQueue = std::make_unique(); - // init render queues that do not need shadows - mRenderQueue->getQueueGroup(RENDER_QUEUE_BACKGROUND)->setShadowsEnabled(false); - mRenderQueue->getQueueGroup(RENDER_QUEUE_OVERLAY)->setShadowsEnabled(false); - mRenderQueue->getQueueGroup(RENDER_QUEUE_SKIES_EARLY)->setShadowsEnabled(false); - mRenderQueue->getQueueGroup(RENDER_QUEUE_SKIES_LATE)->setShadowsEnabled(false); -} -//----------------------------------------------------------------------- -void SceneManager::addSpecialCaseRenderQueue(uint8 qid) -{ - mSpecialCaseQueueList.insert(qid); -} -//----------------------------------------------------------------------- -void SceneManager::removeSpecialCaseRenderQueue(uint8 qid) -{ - mSpecialCaseQueueList.erase(qid); -} -//----------------------------------------------------------------------- -void SceneManager::clearSpecialCaseRenderQueues(void) -{ - mSpecialCaseQueueList.clear(); -} -//----------------------------------------------------------------------- -void SceneManager::setSpecialCaseRenderQueueMode(SceneManager::SpecialCaseRenderQueueMode mode) -{ - mSpecialCaseQueueMode = mode; -} -//----------------------------------------------------------------------- -SceneManager::SpecialCaseRenderQueueMode SceneManager::getSpecialCaseRenderQueueMode(void) -{ - return mSpecialCaseQueueMode; -} -//----------------------------------------------------------------------- -bool SceneManager::isRenderQueueToBeProcessed(uint8 qid) -{ - bool inList = mSpecialCaseQueueList.find(qid) != mSpecialCaseQueueList.end(); - return (inList && mSpecialCaseQueueMode == SCRQM_INCLUDE) - || (!inList && mSpecialCaseQueueMode == SCRQM_EXCLUDE); -} -//----------------------------------------------------------------------- -Camera* SceneManager::createCamera(const String& name) -{ - // Check name not used - if (mCameras.find(name) != mCameras.end()) - { - OGRE_EXCEPT( - Exception::ERR_DUPLICATE_ITEM, - "A camera with the name " + name + " already exists", - "SceneManager::createCamera" ); - } - - Camera *c = OGRE_NEW Camera(name, this); - mCameras.emplace(name, c); - - // create visible bounds aab map entry - mCamVisibleObjectsMap[c] = VisibleObjectsBoundsInfo(); - - return c; -} - -//----------------------------------------------------------------------- -Camera* SceneManager::getCamera(const String& name) const -{ - CameraList::const_iterator i = mCameras.find(name); - if (i == mCameras.end()) - { - OGRE_EXCEPT( Exception::ERR_ITEM_NOT_FOUND, - "Cannot find Camera with name " + name, - "SceneManager::getCamera"); - } - else - { - return i->second; - } -} -//----------------------------------------------------------------------- -bool SceneManager::hasCamera(const String& name) const -{ - return (mCameras.find(name) != mCameras.end()); -} - -//----------------------------------------------------------------------- -void SceneManager::destroyCamera(Camera *cam) -{ - OgreAssert(cam, "Cannot destroy a null Camera"); - destroyCamera(cam->getName()); -} - -//----------------------------------------------------------------------- -void SceneManager::destroyCamera(const String& name) -{ - // Find in list - CameraList::iterator i = mCameras.find(name); - if (i != mCameras.end()) - { - // Remove visible boundary AAB entry - CamVisibleObjectsMap::iterator camVisObjIt = mCamVisibleObjectsMap.find( i->second ); - if ( camVisObjIt != mCamVisibleObjectsMap.end() ) - mCamVisibleObjectsMap.erase( camVisObjIt ); - - // Remove light-shadow cam mapping entry - auto camLightIt = mShadowRenderer.mShadowCamLightMapping.find( i->second ); - if ( camLightIt != mShadowRenderer.mShadowCamLightMapping.end() ) - mShadowRenderer.mShadowCamLightMapping.erase( camLightIt ); - - // Notify render system - if(mDestRenderSystem) - mDestRenderSystem->_notifyCameraRemoved(i->second); - OGRE_DELETE i->second; - mCameras.erase(i); - } - -} - -//----------------------------------------------------------------------- -void SceneManager::destroyAllCameras(void) -{ - CameraList::iterator camIt = mCameras.begin(); - while( camIt != mCameras.end() ) - { - bool dontDelete = false; - // dont destroy shadow texture cameras here. destroyAllCameras is public - for(auto camShadowTex : mShadowRenderer.mShadowTextureCameras) - { - if( camShadowTex == camIt->second ) - { - dontDelete = true; - break; - } - } - - if( dontDelete ) // skip this camera - ++camIt; - else - { - destroyCamera(camIt->second); - camIt = mCameras.begin(); // recreate iterator - } - } - -} -//----------------------------------------------------------------------- -Light* SceneManager::createLight(const String& name) -{ - return static_cast(createMovableObject(name, MOT_LIGHT)); -} -//----------------------------------------------------------------------- -Light* SceneManager::createLight() -{ - String name = mMovableNameGenerator.generate(); - return createLight(name); -} -//----------------------------------------------------------------------- -Light* SceneManager::getLight(const String& name) const -{ - return static_cast(getMovableObject(name, MOT_LIGHT)); -} -//----------------------------------------------------------------------- -const LightList& SceneManager::_getLightsAffectingFrustum(void) const -{ - return mLightsAffectingFrustum; -} -//----------------------------------------------------------------------- -void SceneManager::_populateLightList(const Vector3& position, Real radius, LightList& destList, uint32 lightMask) -{ - // Really basic trawl of the lights, then sort - // Subclasses could do something smarter - - // Pre-allocate memory - destList.clear(); - destList.reserve(mLightsAffectingFrustum.size()); - - size_t lightIndex = 0; - size_t numShadowTextures = isShadowTechniqueTextureBased() ? getShadowTextureConfigList().size() : 0; - size_t numShadowCastingLights = 0; - - // Pick up the lights that affecting frustum only, which should has been - // cached, so better than take all lights in the scene into account. - // this is partitioned as: | shadow casting lights | other lights | - // NOTE: no shadow casting lights might be in frustum, so we cannot rely on numShadowTextures - for (Light* lt : mLightsAffectingFrustum) - { - // check whether or not this light is suppose to be taken into consideration for the current light mask set for this operation - if(!(lt->getLightMask() & lightMask)) - continue; //skip this light - - // Calc squared distance - lt->_calcTempSquareDist(position); - - // only add in-range lights, but ensure texture shadow casters are there - if ((lt->getCastShadows() && lightIndex < numShadowTextures) || lt->isInLightRange(Sphere(position, radius))) - { - destList.push_back(lt); - } - - numShadowCastingLights += int(lt->getCastShadows()); - lightIndex++; - } - - auto start = destList.begin(); - // if we're using texture shadows, we actually want to use - // the first few lights unchanged from the frustum list, matching the - // texture shadows that were generated - // Thus we only allow object-relative sorting on the remainder of the list - std::advance(start, std::min(numShadowCastingLights, destList.size())); - // Sort (stable to guarantee ordering on directional lights) - std::stable_sort(start, destList.end(), - [](const Light* a, const Light* b) { return a->tempSquareDist < b->tempSquareDist; }); - - // Now assign indexes in the list so they can be examined if needed - lightIndex = 0; - for (auto lt : destList) - { - lt->_notifyIndexInFrame(lightIndex++); - } -} -//----------------------------------------------------------------------- -Entity* SceneManager::createEntity( - const String& entityName, - const String& meshName, - const String& groupName /* = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME */) -{ - // delegate to factory implementation - NameValuePairList params; - params["mesh"] = meshName; - params["resourceGroup"] = groupName; - return static_cast(createMovableObject(entityName, MOT_ENTITY, ¶ms)); -} -//--------------------------------------------------------------------- -Entity* SceneManager::createEntity(const String& entityName, const MeshPtr& pMesh) -{ - return createEntity(entityName, pMesh->getName(), pMesh->getGroup()); -} -//--------------------------------------------------------------------- -Entity* SceneManager::createEntity(const String& meshName) -{ - String name = mMovableNameGenerator.generate(); - // note, we can't allow groupName to be passes, it would be ambiguous (2 string params) - return createEntity(name, meshName, ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME); -} -//--------------------------------------------------------------------- -Entity* SceneManager::createEntity(const MeshPtr& pMesh) -{ - String name = mMovableNameGenerator.generate(); - return createEntity(name, pMesh); -} -//----------------------------------------------------------------------- -Entity* SceneManager::getEntity(const String& name) const -{ - return static_cast(getMovableObject(name, MOT_ENTITY)); -} -//----------------------------------------------------------------------- -ManualObject* SceneManager::createManualObject(const String& name) -{ - return static_cast(createMovableObject(name, MOT_MANUAL_OBJECT)); -} -//----------------------------------------------------------------------- -ManualObject* SceneManager::createManualObject() -{ - String name = mMovableNameGenerator.generate(); - return createManualObject(name); -} -//----------------------------------------------------------------------- -ManualObject* SceneManager::getManualObject(const String& name) const -{ - return static_cast(getMovableObject(name, MOT_MANUAL_OBJECT)); -} -Rectangle2D* SceneManager::createScreenSpaceRect(const String& name, bool includeTextureCoords) -{ - NameValuePairList params; - if(includeTextureCoords) - params["includeTextureCoords"] = "true"; - return static_cast(createMovableObject(name, MOT_RECTANGLE2D, ¶ms)); -} -Rectangle2D* SceneManager::createScreenSpaceRect(bool includeTextureCoords) -{ - return createScreenSpaceRect(mMovableNameGenerator.generate(), includeTextureCoords); -} - -Rectangle2D* SceneManager::getScreenSpaceRect(const String& name) const -{ - return static_cast(getMovableObject(name, MOT_RECTANGLE2D)); -} -//----------------------------------------------------------------------- -BillboardChain* SceneManager::createBillboardChain(const String& name) -{ - return static_cast(createMovableObject(name, MOT_BILLBOARD_CHAIN)); -} -//----------------------------------------------------------------------- -BillboardChain* SceneManager::createBillboardChain() -{ - String name = mMovableNameGenerator.generate(); - return createBillboardChain(name); -} -//----------------------------------------------------------------------- -BillboardChain* SceneManager::getBillboardChain(const String& name) const -{ - return static_cast(getMovableObject(name, MOT_BILLBOARD_CHAIN)); -} -//----------------------------------------------------------------------- -RibbonTrail* SceneManager::createRibbonTrail(const String& name) -{ - return static_cast(createMovableObject(name, MOT_RIBBON_TRAIL)); -} -//----------------------------------------------------------------------- -RibbonTrail* SceneManager::createRibbonTrail() -{ - String name = mMovableNameGenerator.generate(); - return createRibbonTrail(name); -} -//----------------------------------------------------------------------- -RibbonTrail* SceneManager::getRibbonTrail(const String& name) const -{ - return static_cast(getMovableObject(name, MOT_RIBBON_TRAIL)); -} -//----------------------------------------------------------------------- -ParticleSystem* SceneManager::createParticleSystem(const String& name, const String& templateName) -{ - NameValuePairList params; - params["templateName"] = templateName; - - return static_cast(createMovableObject(name, MOT_PARTICLE_SYSTEM, ¶ms)); -} -//----------------------------------------------------------------------- -ParticleSystem* SceneManager::createParticleSystem(const String& name, size_t quota, const String& group) -{ - NameValuePairList params; - params["quota"] = StringConverter::toString(quota); - params["resourceGroup"] = group; - - return static_cast(createMovableObject(name, MOT_PARTICLE_SYSTEM, ¶ms)); -} -//----------------------------------------------------------------------- -ParticleSystem* SceneManager::createParticleSystem(size_t quota, const String& group) -{ - String name = mMovableNameGenerator.generate(); - return createParticleSystem(name, quota, group); -} - -//----------------------------------------------------------------------- -ParticleSystem* SceneManager::getParticleSystem(const String& name) const -{ - return static_cast(getMovableObject(name, MOT_PARTICLE_SYSTEM)); -} -//----------------------------------------------------------------------- -void SceneManager::clearScene(void) -{ - mShadowRenderer.destroyShadowTextures(); - destroyAllStaticGeometry(); - destroyAllInstanceManagers(); - destroyAllMovableObjects(); - - // Clear root node of all children - getRootSceneNode()->removeAllChildren(); - getRootSceneNode()->detachAllObjects(); - - // Delete all SceneNodes, except root that is - for (auto *n : mSceneNodes) - { - OGRE_DELETE n; - } - mSceneNodes.clear(); - mNamedNodes.clear(); - mAutoTrackingSceneNodes.clear(); - - - - // Clear animations - destroyAllAnimations(); - - // Clear render queue, empty completely - if (mRenderQueue) - mRenderQueue->clear(true); - - // Reset ParamDataSource, when a resource is removed the mAutoParamDataSource keep bad references - mAutoParamDataSource.reset(createAutoParamDataSource()); -} -//----------------------------------------------------------------------- -SceneNode* SceneManager::createSceneNodeImpl(void) -{ - return OGRE_NEW SceneNode(this); -} -//----------------------------------------------------------------------- -SceneNode* SceneManager::createSceneNodeImpl(const String& name) -{ - return OGRE_NEW SceneNode(this, name); -}//----------------------------------------------------------------------- -SceneNode* SceneManager::createSceneNode(void) -{ - SceneNode* sn = createSceneNodeImpl(); - mSceneNodes.push_back(sn); - sn->mGlobalIndex = mSceneNodes.size() - 1; - return sn; -} -//----------------------------------------------------------------------- -SceneNode* SceneManager::createSceneNode(const String& name) -{ - // Check name not used - if (hasSceneNode(name)) - { - OGRE_EXCEPT( - Exception::ERR_DUPLICATE_ITEM, - "A scene node with the name " + name + " already exists", - "SceneManager::createSceneNode" ); - } - - SceneNode* sn = createSceneNodeImpl(name); - mSceneNodes.push_back(sn); - mNamedNodes[name] = sn; - sn->mGlobalIndex = mSceneNodes.size() - 1; - return sn; -} -//----------------------------------------------------------------------- -void SceneManager::destroySceneNode(const String& name) -{ - OgreAssert(!name.empty(), "name must not be empty"); - auto i = mNamedNodes.find(name); - destroySceneNode(i != mNamedNodes.end() ? i->second : NULL); -} - -void SceneManager::_destroySceneNode(SceneNodeList::iterator i) -{ - - if (i == mSceneNodes.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "SceneNode not found.", - "SceneManager::_destroySceneNode"); - } - - // Find any scene nodes which are tracking this node, and turn them off - AutoTrackingSceneNodes::iterator ai, aiend; - aiend = mAutoTrackingSceneNodes.end(); - for (ai = mAutoTrackingSceneNodes.begin(); ai != aiend; ) - { - // Pre-increment incase we delete - AutoTrackingSceneNodes::iterator curri = ai++; - SceneNode* n = *curri; - // Tracking this node - if (n->getAutoTrackTarget() == *i) - { - // turn off, this will notify SceneManager to remove - n->setAutoTracking(false); - } - // node is itself a tracker - else if (n == *i) - { - mAutoTrackingSceneNodes.erase(curri); - } - } - - // detach from parent (don't do this in destructor since bulk destruction - // behaves differently) - Node* parentNode = (*i)->getParent(); - if (parentNode) - { - parentNode->removeChild(*i); - } - if(!(*i)->getName().empty()) - mNamedNodes.erase((*i)->getName()); - OGRE_DELETE *i; - if (std::next(i) != mSceneNodes.end()) - { - std::swap(*i, mSceneNodes.back()); - (*i)->mGlobalIndex = i - mSceneNodes.begin(); - } - mSceneNodes.pop_back(); -} -//--------------------------------------------------------------------- -void SceneManager::destroySceneNode(SceneNode* sn) -{ - OgreAssert(sn, "Cannot destroy a null SceneNode"); - - auto pos = sn->mGlobalIndex < mSceneNodes.size() && - sn == *(mSceneNodes.begin() + sn->mGlobalIndex) - ? mSceneNodes.begin() + sn->mGlobalIndex - : mSceneNodes.end(); - - _destroySceneNode(pos); -} -//----------------------------------------------------------------------- -SceneNode* SceneManager::getRootSceneNode(void) -{ - if (!mSceneRoot) - { - // Create root scene node - mSceneRoot.reset(createSceneNodeImpl("Ogre/SceneRoot")); - mSceneRoot->_notifyRootNode(); - } - - return mSceneRoot.get(); -} -//----------------------------------------------------------------------- -SceneNode* SceneManager::getSceneNode(const String& name, bool throwExceptionIfNotFound) const -{ - OgreAssert(!name.empty(), "name must not be empty"); - auto i = mNamedNodes.find(name); - - if (i != mNamedNodes.end()) - return i->second; - - if (throwExceptionIfNotFound) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "SceneNode '" + name + "' not found."); - return NULL; -} - -//----------------------------------------------------------------------- -const Pass* SceneManager::_setPass(const Pass* pass, bool shadowDerivation) -{ - //If using late material resolving, swap now. - if (isLateMaterialResolving()) - { - Technique* lateTech = pass->getParent()->getParent()->getBestTechnique(); - if (lateTech->getNumPasses() > pass->getIndex()) - { - pass = lateTech->getPass(pass->getIndex()); - } - else - { - pass = lateTech->getPass(0); - } - //Should we warn or throw an exception if an illegal state was achieved? - } - - if (shadowDerivation) - { - pass = mShadowRenderer.deriveTextureShadowPass(pass); - } - - // Tell params about current pass - mAutoParamDataSource->setCurrentPass(pass); - - GpuProgram* vprog = pass->hasVertexProgram() ? pass->getVertexProgram().get() : 0; - GpuProgram* fprog = pass->hasFragmentProgram() ? pass->getFragmentProgram().get() : 0; - - bool passSurfaceAndLightParams = !vprog || vprog->getPassSurfaceAndLightStates(); - - if (vprog) - { - bindGpuProgram(vprog->_getBindingDelegate()); - } - else if (!mDestRenderSystem->getCapabilities()->hasCapability(RSC_FIXED_FUNCTION)) - { - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, - "RenderSystem does not support FixedFunction, " - "but technique of '" + - pass->getParent()->getParent()->getName() + - "' has no Vertex Shader. Use the RTSS or write custom shaders.", - "SceneManager::_setPass"); - } - else - { - // Unbind program? - if (mDestRenderSystem->isGpuProgramBound(GPT_VERTEX_PROGRAM)) - { - mDestRenderSystem->unbindGpuProgram(GPT_VERTEX_PROGRAM); - } - // Set fixed-function vertex parameters - } - - if (pass->hasGeometryProgram()) - { - bindGpuProgram(pass->getGeometryProgram()->_getBindingDelegate()); - // bind parameters later - } - else - { - // Unbind program? - if (mDestRenderSystem->isGpuProgramBound(GPT_GEOMETRY_PROGRAM)) - { - mDestRenderSystem->unbindGpuProgram(GPT_GEOMETRY_PROGRAM); - } - } - if (pass->hasTessellationHullProgram()) - { - bindGpuProgram(pass->getTessellationHullProgram()->_getBindingDelegate()); - // bind parameters later - } - else - { - // Unbind program? - if (mDestRenderSystem->isGpuProgramBound(GPT_HULL_PROGRAM)) - { - mDestRenderSystem->unbindGpuProgram(GPT_HULL_PROGRAM); - } - } - - if (pass->hasTessellationDomainProgram()) - { - bindGpuProgram(pass->getTessellationDomainProgram()->_getBindingDelegate()); - // bind parameters later - } - else - { - // Unbind program? - if (mDestRenderSystem->isGpuProgramBound(GPT_DOMAIN_PROGRAM)) - { - mDestRenderSystem->unbindGpuProgram(GPT_DOMAIN_PROGRAM); - } - } - - if (pass->hasComputeProgram()) - { - bindGpuProgram(pass->getComputeProgram()->_getBindingDelegate()); - // bind parameters later - } - else - { - // Unbind program? - if (mDestRenderSystem->isGpuProgramBound(GPT_COMPUTE_PROGRAM)) - { - mDestRenderSystem->unbindGpuProgram(GPT_COMPUTE_PROGRAM); - } - } - - if (passSurfaceAndLightParams) - { - // Dynamic lighting enabled? - mDestRenderSystem->setLightingEnabled(pass->getLightingEnabled()); - } - - // Using a fragment program? - if (fprog) - { - bindGpuProgram(fprog->_getBindingDelegate()); - } - else if (!mDestRenderSystem->getCapabilities()->hasCapability(RSC_FIXED_FUNCTION) && - !pass->hasGeometryProgram()) - { - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, - "RenderSystem does not support FixedFunction, " - "but technique of '" + - pass->getParent()->getParent()->getName() + - "' has no Fragment Shader. Use the RTSS or write custom shaders.", - "SceneManager::_setPass"); - } - else - { - // Unbind program? - if (mDestRenderSystem->isGpuProgramBound(GPT_FRAGMENT_PROGRAM)) - { - mDestRenderSystem->unbindGpuProgram(GPT_FRAGMENT_PROGRAM); - } - // Set fixed-function fragment settings - } - - // fog params can either be from scene or from material - const auto& newFogColour = pass->getFogOverride() ? pass->getFogColour() : mFogColour; - FogMode newFogMode; - Real newFogStart, newFogEnd, newFogDensity; - if (pass->getFogOverride()) - { - // fog params from material - newFogMode = pass->getFogMode(); - newFogStart = pass->getFogStart(); - newFogEnd = pass->getFogEnd(); - newFogDensity = pass->getFogDensity(); - } - else - { - // fog params from scene - newFogMode = mFogMode; - newFogStart = mFogStart; - newFogEnd = mFogEnd; - newFogDensity = mFogDensity; - } - - mAutoParamDataSource->setFog(newFogMode, newFogColour, newFogDensity, newFogStart, newFogEnd); - - // The rest of the settings are the same no matter whether we use programs or not - - if(mDestRenderSystem->getCapabilities()->hasCapability(RSC_FIXED_FUNCTION) && passSurfaceAndLightParams) - { - mFixedFunctionParams = mDestRenderSystem->getFixedFunctionParams(pass->getVertexColourTracking(), newFogMode); - } - - // Set scene blending - mDestRenderSystem->setColourBlendState(pass->getBlendState()); - - // Line width - if (mDestRenderSystem->getCapabilities()->hasCapability(RSC_WIDE_LINES)) - mDestRenderSystem->_setLineWidth(pass->getLineWidth()); - - // Set point parameters - mDestRenderSystem->_setPointParameters(pass->isPointAttenuationEnabled(), pass->getPointMinSize(), - pass->getPointMaxSize()); - - if (mDestRenderSystem->getCapabilities()->hasCapability(RSC_POINT_SPRITES)) - mDestRenderSystem->_setPointSpritesEnabled(pass->getPointSpritesEnabled()); - - mAutoParamDataSource->setPointParameters(pass->isPointAttenuationEnabled(), pass->getPointAttenuation()); - - // Texture unit settings - size_t unit = 0; - // Reset the shadow texture index for each pass - size_t startLightIndex = pass->getStartLight(); - size_t shadowTexUnitIndex = 0; - size_t shadowTexIndex = mShadowRenderer.getShadowTexIndex(startLightIndex); - for(auto *pTex : pass->getTextureUnitStates()) - { - if (!pass->getIteratePerLight() && isShadowTechniqueTextureBased() && - pTex->getContentType() == TextureUnitState::CONTENT_SHADOW) - { - // Need to bind the correct shadow texture, based on the start light - // Even though the light list can change per object, our restrictions - // say that when texture shadows are enabled, the lights up to the - // number of texture shadows will be fixed for all objects - // to match the shadow textures that have been generated - // see Listener::sortLightsAffectingFrustum and - // MovableObject::Listener::objectQueryLights - // Note that light iteration throws the indexes out so we don't bind here - // if that's the case, we have to bind when lights are iterated - // in renderSingleObject - - mShadowRenderer.resolveShadowTexture(pTex, shadowTexIndex, shadowTexUnitIndex); - ++shadowTexIndex; - ++shadowTexUnitIndex; - } - else if (mIlluminationStage == IRS_NONE) - { - // Manually set texture projector for shaders if present - // This won't get set any other way if using manual projection - auto effi = pTex->getEffects().find(TextureUnitState::ET_PROJECTIVE_TEXTURE); - if (effi != pTex->getEffects().end()) - { - mAutoParamDataSource->setTextureProjector(effi->second.frustum, unit); - } - } - if (pTex->getContentType() == TextureUnitState::CONTENT_COMPOSITOR) - { - CompositorChain* currentChain = _getActiveCompositorChain(); - if (!currentChain) - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, - "TextureUnitState references a compositor, but current viewport of '" + - mCurrentViewport->getTarget()->getName() + "' does not have a CompositorChain"); - auto compName = pTex->getReferencedCompositorName(); - CompositorInstance* refComp = currentChain->getCompositor(compName); - if (!refComp) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Current CompositorChain does not contain compositor named " + compName); - - auto texName = pTex->getReferencedTextureName(); - TexturePtr refTex = refComp->getTextureInstance(texName, pTex->getReferencedMRTIndex()); - - if (!refTex) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Compositor " + compName + " does not declare texture " + texName); - pTex->_setTexturePtr(refTex); - } - mDestRenderSystem->_setTextureUnitSettings(unit, *pTex); - ++unit; - } - // Disable remaining texture units - mDestRenderSystem->_disableTextureUnitsFrom(pass->getNumTextureUnitStates()); - - // Set up non-texture related material settings - // Depth buffer settings - mDestRenderSystem->_setDepthBufferParams(pass->getDepthCheckEnabled(), pass->getDepthWriteEnabled(), - pass->getDepthFunction()); - mDestRenderSystem->_setDepthBias(pass->getDepthBiasConstant(), pass->getDepthBiasSlopeScale()); - // Alpha-reject settings - mDestRenderSystem->_setAlphaRejectSettings(pass->getAlphaRejectFunction(), - pass->getAlphaRejectValue(), - pass->isAlphaToCoverageEnabled()); - - // Culling mode - if (isShadowTechniqueTextureBased() && mIlluminationStage == IRS_RENDER_TO_TEXTURE && - mShadowRenderer.mShadowCasterRenderBackFaces && pass->getCullingMode() == CULL_CLOCKWISE) - { - // render back faces into shadow caster, can help with depth comparison - mPassCullingMode = CULL_ANTICLOCKWISE; - } - else - { - mPassCullingMode = pass->getCullingMode(); - } - mDestRenderSystem->_setCullingMode(mPassCullingMode); - mDestRenderSystem->setShadingType(pass->getShadingMode()); - - mAutoParamDataSource->setPassNumber( pass->getIndex() ); - // mark global params as dirty - mGpuParamsDirty |= (uint16)GPV_GLOBAL; - - return pass; -} -//----------------------------------------------------------------------- -void SceneManager::prepareRenderQueue(void) -{ - RenderQueue* q = getRenderQueue(); - // Clear the render queue - q->clear(Root::getSingleton().getRemoveRenderQueueStructuresOnClear()); - - // Prep the ordering options - // We need this here to reset if coming out of a render queue sequence, - // but doing it resets any specialised settings set globally per render queue - // so only do it when necessary - it's nice to allow people to set the organisation - // mode manually for example - - // Default all the queue groups that are there, new ones will be created - // with defaults too - for (size_t i = 0; i < RENDER_QUEUE_COUNT; ++i) - { - if(!q->_getQueueGroups()[i]) - continue; - - q->_getQueueGroups()[i]->defaultOrganisationMode(); - } - - // Global split options - mShadowRenderer.updateSplitOptions(q); -} -//----------------------------------------------------------------------- -void SceneManager::_renderScene(Camera* camera, Viewport* vp, bool includeOverlays) -{ - assert(camera); - OgreProfileGroup(camera->getName(), OGREPROF_GENERAL); - - auto prevSceneManager = Root::getSingleton()._getCurrentSceneManager(); - Root::getSingleton()._setCurrentSceneManager(this); - mActiveQueuedRenderableVisitor->targetSceneMgr = this; - mAutoParamDataSource->setCurrentSceneManager(this); - - // preserve the previous scheme, in case this is a RTT update with an outer _renderScene pending - MaterialManager& matMgr = MaterialManager::getSingleton(); - String prevMaterialScheme = matMgr.getActiveScheme(); - - // Also set the internal viewport pointer at this point, for calls that need it - // However don't call setViewport just yet (see below) - mCurrentViewport = vp; - - // Set current draw buffer (default is CBT_BACK) - mDestRenderSystem->setDrawBuffer(mCurrentViewport->getDrawBuffer()); - - // reset light hash so even if light list is the same, we refresh the content every frame - useLights(NULL, 0); - - // Perform a quick pre-check to see whether we should override far distance - // When using stencil volumes we have to use infinite far distance - // to prevent dark caps getting clipped - if (isShadowTechniqueStencilBased() && - camera->getProjectionType() == PT_PERSPECTIVE && - camera->getFarClipDistance() != 0 && - mShadowRenderer.mShadowUseInfiniteFarPlane) - { - // infinite far distance - camera->setFarClipDistance(0); - } - - mCameraInProgress = camera; - - - // Update controllers - ControllerManager::getSingleton().updateAllControllers(); - - // Update the scene, only do this once per frame - unsigned long thisFrameNumber = Root::getSingleton().getNextFrameNumber(); - if (thisFrameNumber != mLastFrameNumber) - { - // Update animations - _applySceneAnimations(); - updateDirtyInstanceManagers(); - mLastFrameNumber = thisFrameNumber; - } - - { - // Lock scene graph mutex, no more changes until we're ready to render - OGRE_LOCK_MUTEX(sceneGraphMutex); - - // Update scene graph for this camera (can happen multiple times per frame) - { - OgreProfileGroup("_updateSceneGraph", OGREPROF_GENERAL); - _updateSceneGraph(camera); - - // Auto-track nodes - for (auto *a : mAutoTrackingSceneNodes) - { - a->_autoTrack(); - } -#ifdef OGRE_NODELESS_POSITIONING - // Auto-track camera if required - OGRE_IGNORE_DEPRECATED_BEGIN - camera->_autoTrack(); - OGRE_IGNORE_DEPRECATED_END -#endif - } - - if (mIlluminationStage != IRS_RENDER_TO_TEXTURE && mFindVisibleObjects) - { - // Locate any lights which could be affecting the frustum - findLightsAffectingFrustum(camera); - - // Prepare shadow textures if texture shadow based shadowing - // technique in use - if (isShadowTechniqueTextureBased() && vp->getShadowsEnabled()) - { - OgreProfileGroup("prepareShadowTextures", OGREPROF_GENERAL); - - // ******* - // WARNING - // ******* - // This call will result in re-entrant calls to this method - // therefore anything which comes before this is NOT - // guaranteed persistent. Make sure that anything which - // MUST be specific to this camera / target is done - // AFTER THIS POINT - prepareShadowTextures(camera, vp); - // reset the cameras & viewport because of the re-entrant call - mCameraInProgress = camera; - mCurrentViewport = vp; - } - } - - // Invert vertex winding? - mDestRenderSystem->setInvertVertexWinding(camera->isReflected()); - - // Set the viewport - this is deliberately after the shadow texture update - setViewport(vp); - - // Tell params about camera - mAutoParamDataSource->setCurrentCamera(camera, mCameraRelativeRendering); - // Set autoparams for finite dir light extrusion - mAutoParamDataSource->setShadowDirLightExtrusionDistance(mShadowRenderer.mShadowDirLightExtrudeDist); - - // Tell params about render target - mAutoParamDataSource->setCurrentRenderTarget(vp->getTarget()); - - - // Set camera window clipping planes (if any) - if (mDestRenderSystem->getCapabilities()->hasCapability(RSC_USER_CLIP_PLANES)) - { - mDestRenderSystem->setClipPlanes(camera->isWindowSet() ? camera->getWindowPlanes() : PlaneList()); - } - - // Prepare render queue for receiving new objects - { - OgreProfileGroup("prepareRenderQueue", OGREPROF_GENERAL); - prepareRenderQueue(); - } - - if (mFindVisibleObjects) - { - OgreProfileGroup("_findVisibleObjects", OGREPROF_CULLING); - - // Assemble an AAB on the fly which contains the scene elements visible - // by the camera. - CamVisibleObjectsMap::iterator camVisObjIt = mCamVisibleObjectsMap.find( camera ); - - assert (camVisObjIt != mCamVisibleObjectsMap.end() && - "Should never fail to find a visible object bound for a camera, " - "did you override SceneManager::createCamera or something?"); - - // reset the bounds - camVisObjIt->second.reset(); - - // Parse the scene and tag visibles - firePreFindVisibleObjects(vp); - _findVisibleObjects(camera, &(camVisObjIt->second), - mIlluminationStage == IRS_RENDER_TO_TEXTURE? true : false); - firePostFindVisibleObjects(vp); - - mAutoParamDataSource->setMainCamBoundsInfo(&(camVisObjIt->second)); - } - } // end lock on scene graph mutex - - mDestRenderSystem->_beginGeometryCount(); - // Clear the viewport if required - if (mCurrentViewport->getClearEveryFrame()) - { - mDestRenderSystem->clearFrameBuffer( - mCurrentViewport->getClearBuffers(), - mCurrentViewport->getBackgroundColour(), - mCurrentViewport->getDepthClear() ); - } - // Begin the frame - mDestRenderSystem->_beginFrame(); - - mDestRenderSystem->_setTextureProjectionRelativeTo(mCameraRelativeRendering, camera->getDerivedPosition()); - - // Render scene content - { - OgreProfileGroup("_renderVisibleObjects", OGREPROF_RENDERING); - _renderVisibleObjects(); - } - - // End frame - mDestRenderSystem->_endFrame(); - - // Notify camera of vis faces - camera->_notifyRenderedFaces(mDestRenderSystem->_getFaceCount()); - - // Notify camera of vis batches - camera->_notifyRenderedBatches(mDestRenderSystem->_getBatchCount()); - - matMgr.setActiveScheme(prevMaterialScheme); - Root::getSingleton()._setCurrentSceneManager(prevSceneManager); -} -//----------------------------------------------------------------------- -void SceneManager::_setDestinationRenderSystem(RenderSystem* sys) -{ - mDestRenderSystem = sys; - mShadowRenderer.mDestRenderSystem = sys; -} -//----------------------------------------------------------------------- -void SceneManager::_releaseManualHardwareResources() -{ - // release stencil shadows index buffer - mShadowRenderer.mShadowIndexBuffer.reset(); - - // release hardware resources inside all movable objects - OGRE_LOCK_MUTEX(mMovableObjectCollectionMapMutex); - for (const auto& m : mMovableObjectCollectionMap) - { - MovableObjectCollection* coll = m.second; - OGRE_LOCK_MUTEX(coll->mutex); - for(auto& i : coll->map) - i.second->_releaseManualHardwareResources(); - } -} -//----------------------------------------------------------------------- -void SceneManager::_restoreManualHardwareResources() -{ - // restore stencil shadows index buffer - if(isShadowTechniqueStencilBased()) - { - mShadowRenderer.mShadowIndexBuffer = HardwareBufferManager::getSingleton(). - createIndexBuffer(HardwareIndexBuffer::IT_16BIT, - mShadowRenderer.mShadowIndexBufferSize, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE, - false); - } - - // restore hardware resources inside all movable objects - OGRE_LOCK_MUTEX(mMovableObjectCollectionMapMutex); - for(const auto& m : mMovableObjectCollectionMap) - { - MovableObjectCollection* coll = m.second; - OGRE_LOCK_MUTEX(coll->mutex); - for(auto& i : coll->map) - i.second->_restoreManualHardwareResources(); - } -} -//----------------------------------------------------------------------- -void SceneManager::setWorldGeometry(const String& filename) -{ - // This default implementation cannot handle world geometry - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "World geometry is not supported by the generic SceneManager.", - "SceneManager::setWorldGeometry"); -} -//----------------------------------------------------------------------- -void SceneManager::setWorldGeometry(DataStreamPtr& stream, - const String& typeName) -{ - // This default implementation cannot handle world geometry - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "World geometry is not supported by the generic SceneManager.", - "SceneManager::setWorldGeometry"); -} -//----------------------------------------------------------------------- -void SceneManager::setSkyPlane( - bool enable, - const Plane& plane, - const String& materialName, - Real gscale, - Real tiling, - bool drawFirst, - Real bow, - int xsegments, int ysegments, - const String& groupName) -{ - _setSkyPlane(enable, plane, materialName, gscale, tiling, - drawFirst ? RENDER_QUEUE_SKIES_EARLY : RENDER_QUEUE_SKIES_LATE, bow, xsegments, ysegments, - groupName); -} - -void SceneManager::_setSkyPlane(bool enable, const Plane& plane, const String& materialName, - Real gscale, Real tiling, uint8 renderQueue, Real bow, - int xsegments, int ysegments, const String& groupName) -{ - mSkyPlane.setSkyPlane(enable, plane, materialName, gscale, tiling, renderQueue, bow, - xsegments, ysegments, groupName); -} - -//----------------------------------------------------------------------- -void SceneManager::setSkyBox( - bool enable, - const String& materialName, - Real distance, - bool drawFirst, - const Quaternion& orientation, - const String& groupName) -{ - _setSkyBox(enable, materialName, distance, - drawFirst ? RENDER_QUEUE_SKIES_EARLY : RENDER_QUEUE_SKIES_LATE, orientation, groupName); -} - -void SceneManager::_setSkyBox(bool enable, const String& materialName, Real distance, - uint8 renderQueue, const Quaternion& orientation, - const String& groupName) -{ - mSkyBox.setSkyBox(enable, materialName, distance, renderQueue, orientation, groupName); -} - -//----------------------------------------------------------------------- -void SceneManager::setSkyDome( - bool enable, - const String& materialName, - Real curvature, - Real tiling, - Real distance, - bool drawFirst, - const Quaternion& orientation, - int xsegments, int ysegments, int ySegmentsToKeep, - const String& groupName) -{ - _setSkyDome(enable, materialName, curvature, tiling, distance, - drawFirst ? RENDER_QUEUE_SKIES_EARLY : RENDER_QUEUE_SKIES_LATE, orientation, xsegments, - ysegments, ySegmentsToKeep, groupName); -} - -void SceneManager::_setSkyDome(bool enable, const String& materialName, Real curvature, Real tiling, - Real distance, uint8 renderQueue, const Quaternion& orientation, - int xsegments, int ysegments, int ysegments_keep, - const String& groupName) -{ - mSkyDome.setSkyDome(enable, materialName, curvature, tiling, distance, renderQueue, - orientation, xsegments, ysegments, ysegments_keep, groupName); -} - -//----------------------------------------------------------------------- -void SceneManager::_updateSceneGraph(Camera* cam) -{ - firePreUpdateSceneGraph(cam); - - // Process queued needUpdate calls - Node::processQueuedUpdates(); - - // Cascade down the graph updating transforms & world bounds - // In this implementation, just update from the root - // Smarter SceneManager subclasses may choose to update only - // certain scene graph branches - getRootSceneNode()->_update(true, false); - - firePostUpdateSceneGraph(cam); -} -//----------------------------------------------------------------------- -void SceneManager::_findVisibleObjects( - Camera* cam, VisibleObjectsBoundsInfo* visibleBounds, bool onlyShadowCasters) -{ - // Tell nodes to find, cascade down all nodes - getRootSceneNode()->_findVisibleObjects(cam, getRenderQueue(), visibleBounds, true, - mDisplayNodes, onlyShadowCasters); - -} -//----------------------------------------------------------------------- -void SceneManager::renderVisibleObjectsDefaultSequence(void) -{ - firePreRenderQueues(); - - // Render each separate queue - const RenderQueue::RenderQueueGroupMap& groups = getRenderQueue()->_getQueueGroups(); - - for (uint8 qId = 0; qId < RENDER_QUEUE_COUNT; ++qId) - { - if(!groups[qId]) - continue; - - // Get queue group id - RenderQueueGroup* pGroup = groups[qId].get(); - // Skip this one if not to be processed - if (!isRenderQueueToBeProcessed(qId)) - continue; - - - bool repeatQueue = false; - do // for repeating queues - { - // Fire queue started event - if (fireRenderQueueStarted(qId, mCameraInProgress->getName())) - { - // Someone requested we skip this queue - break; - } - - _renderQueueGroupObjects(pGroup, QueuedRenderableCollection::OM_PASS_GROUP); - - // Fire queue ended event - if (fireRenderQueueEnded(qId, mCameraInProgress->getName())) - { - // Someone requested we repeat this queue - repeatQueue = true; - } - else - { - repeatQueue = false; - } - } while (repeatQueue); - - } // for each queue group - - firePostRenderQueues(); - -} -//----------------------------------------------------------------------- -void SceneManager::SceneMgrQueuedRenderableVisitor::visit(const Pass* p, RenderableList& rs) -{ - // Give SM a chance to eliminate this pass - if (!targetSceneMgr->validatePassForRendering(p)) - return; - - // Set pass, store the actual one used - mUsedPass = targetSceneMgr->_setPass(p); - OgreProfileBeginGPUEvent(mUsedPass->getParent()->getParent()->getName()); - - SubMesh* lastsm = 0; - RenderableList instances; - - bool useInstancing = mUsedPass->hasVertexProgram() && mUsedPass->getVertexProgram()->isInstancingIncluded(); - - for (Renderable* r : rs) - { - // Give SM a chance to eliminate - if (!targetSceneMgr->validateRenderableForRendering(mUsedPass, r)) - continue; - - if(useInstancing) - { - if(auto se = dynamic_cast(r)) - { - if(lastsm == se->getSubMesh()) - { - instances.push_back(r); - continue; - } - - // different SubMesh -> flush and restart instances - if(!instances.empty()) - { - targetSceneMgr->renderInstancedObject(instances, mUsedPass, scissoring, autoLights, manualLightList); - instances.clear(); - } - - lastsm = se->getSubMesh(); - instances.push_back(r); - continue; - } - - // not a SubEntity -> flush instances and render this one - if(!instances.empty()) - { - targetSceneMgr->renderInstancedObject(instances, mUsedPass, scissoring, autoLights, manualLightList); - instances.clear(); - } - } - - // Render a single object, this will set up auto params if required - targetSceneMgr->renderSingleObject(r, mUsedPass, scissoring, autoLights, manualLightList); - } - - if (!instances.empty()) - targetSceneMgr->renderInstancedObject(instances, mUsedPass, scissoring, autoLights, manualLightList); - - OgreProfileEndGPUEvent(mUsedPass->getParent()->getParent()->getName()); -} -//----------------------------------------------------------------------- -void SceneManager::SceneMgrQueuedRenderableVisitor::visit(RenderablePass* rp) -{ - // Skip this one if we're in transparency cast shadows mode & it doesn't - // Don't need to implement this one in the other visit methods since - // transparents are never grouped, always sorted - if (transparentShadowCastersMode && - !rp->pass->getParent()->getParent()->getTransparencyCastsShadows()) - return; - - // Give SM a chance to eliminate - if (targetSceneMgr->validateRenderableForRendering(rp->pass, rp->renderable)) - { - mUsedPass = targetSceneMgr->_setPass(rp->pass); - OgreProfileBeginGPUEvent(mUsedPass->getParent()->getParent()->getName()); - targetSceneMgr->renderSingleObject(rp->renderable, mUsedPass, scissoring, - autoLights, manualLightList); - OgreProfileEndGPUEvent(mUsedPass->getParent()->getParent()->getName()); - } -} -//----------------------------------------------------------------------- -void SceneManager::SceneMgrQueuedRenderableVisitor::renderObjects(const QueuedRenderableCollection& objs, - QueuedRenderableCollection::OrganisationMode om, - bool lightScissoringClipping, bool doLightIteration, - const LightList* _manualLightList, bool _transparentShadowCastersMode) -{ - autoLights = doLightIteration; - manualLightList = _manualLightList; - transparentShadowCastersMode = _transparentShadowCastersMode; - scissoring = lightScissoringClipping; - // Use visitor - objs.acceptVisitor(this, om); - transparentShadowCastersMode = false; -} - -void SceneManager::SceneMgrQueuedRenderableVisitor::renderTransparents(const RenderPriorityGroup* priorityGrp, - QueuedRenderableCollection::OrganisationMode om) -{ - // Do unsorted transparents - renderObjects(priorityGrp->getTransparentsUnsorted(), om, true, true); - // Do transparents (always descending sort) - renderObjects(priorityGrp->getTransparents(), QueuedRenderableCollection::OM_SORT_DESCENDING, true, true); -} - -//----------------------------------------------------------------------- -bool SceneManager::validatePassForRendering(const Pass* pass) -{ - // Bypass if we're doing a texture shadow render and - // this pass is after the first (only 1 pass needed for shadow texture render, and - // one pass for shadow texture receive for modulative technique) - // Also bypass if passes above the first if render state changes are - // suppressed since we're not actually using this pass data anyway - if (mCurrentViewport->getShadowsEnabled() && - ((isShadowTechniqueModulative() && mIlluminationStage == IRS_RENDER_RECEIVER_PASS) || - mIlluminationStage == IRS_RENDER_TO_TEXTURE) && - pass->getIndex() > 0) - { - return false; - } - - // If using late material resolving, check if there is a pass with the same index - // as this one in the 'late' material. If not, skip. - if (isLateMaterialResolving()) - { - Technique* lateTech = pass->getParent()->getParent()->getBestTechnique(); - if (lateTech->getNumPasses() <= pass->getIndex()) - { - return false; - } - } - - return true; -} -//----------------------------------------------------------------------- -bool SceneManager::validateRenderableForRendering(const Pass* pass, const Renderable* rend) -{ - // Skip this renderable if we're doing modulative texture shadows, it casts shadows - // and we're doing the render receivers pass and we're not self-shadowing - // also if pass number > 0 - if (mCurrentViewport->getShadowsEnabled() && isShadowTechniqueTextureBased()) - { - if (mIlluminationStage == IRS_RENDER_RECEIVER_PASS && - rend->getCastsShadows() && !mShadowRenderer.mShadowTextureSelfShadow) - { - return false; - } - // Some duplication here with validatePassForRendering, for transparents - if (((isShadowTechniqueModulative() && mIlluminationStage == IRS_RENDER_RECEIVER_PASS) || - mIlluminationStage == IRS_RENDER_TO_TEXTURE) && - pass->getIndex() > 0) - { - return false; - } - } - - return true; - -} -//----------------------------------------------------------------------- -void SceneManager::_renderQueueGroupObjects(RenderQueueGroup* pGroup, - QueuedRenderableCollection::OrganisationMode om) -{ - bool doShadows = pGroup->getShadowsEnabled() && mCurrentViewport->getShadowsEnabled(); - - // Modulative texture shadows in use - if (isShadowTechniqueTextureBased() && mIlluminationStage == IRS_RENDER_TO_TEXTURE) - { - // Shadow caster pass - if (mCurrentViewport->getShadowsEnabled()) - { - mShadowRenderer.renderTextureShadowCasterQueueGroupObjects(pGroup, om); - } - return; - } - - // Ordinary + receiver pass - if (doShadows && mShadowRenderer.mShadowTechnique && !isShadowTechniqueIntegrated()) - { - mShadowRenderer.render(pGroup, om); - return; - } - - // No shadows, ordinary pass - renderBasicQueueGroupObjects(pGroup, om); -} -//----------------------------------------------------------------------- -void SceneManager::renderBasicQueueGroupObjects(RenderQueueGroup* pGroup, - QueuedRenderableCollection::OrganisationMode om) -{ - // Basic render loop - // Iterate through priorities - auto visitor = mActiveQueuedRenderableVisitor; - - for (const auto& pg : pGroup->getPriorityGroups()) - { - RenderPriorityGroup* pPriorityGrp = pg.second; - - // Sort the queue first - pPriorityGrp->sort(mCameraInProgress); - - // Do solids - visitor->renderObjects(pPriorityGrp->getSolidsBasic(), om, true, true); - visitor->renderTransparents(pPriorityGrp, om); - }// for each priority -} -//----------------------------------------------------------------------- -void SceneManager::setWorldTransform(Renderable* rend) -{ - // Issue view / projection changes if any - // Check view matrix - if (rend->getUseIdentityView()) - { - mGpuParamsDirty |= (uint16)GPV_GLOBAL; - mResetIdentityView = true; - } - - if (rend->getUseIdentityProjection()) - { - mGpuParamsDirty |= (uint16)GPV_GLOBAL; - - mResetIdentityProj = true; - } - - // mark per-object params as dirty - mGpuParamsDirty |= (uint16)GPV_PER_OBJECT; -} -//----------------------------------------------------------------------- -void SceneManager::issueRenderWithLights(Renderable* rend, const Pass* pass, - const LightList* pLightListToUse, - bool lightScissoringClipping) -{ - useLights(pLightListToUse, pass->getMaxSimultaneousLights()); - fireRenderSingleObject(rend, pass, mAutoParamDataSource.get(), pLightListToUse, false); - - // optional light scissoring & clipping - ClipResult scissored = CLIPPED_NONE; - ClipResult clipped = CLIPPED_NONE; - if (pLightListToUse && lightScissoringClipping && - (pass->getLightScissoringEnabled() || pass->getLightClipPlanesEnabled())) - { - // if there's no lights hitting the scene, then we might as - // well stop since clipping cannot include anything - if (pLightListToUse->empty()) - return; - - if (pass->getLightScissoringEnabled()) - scissored = buildAndSetScissor(*pLightListToUse, mCameraInProgress); - - if (pass->getLightClipPlanesEnabled()) - clipped = buildAndSetLightClip(*pLightListToUse); - - if (scissored == CLIPPED_ALL || clipped == CLIPPED_ALL) - return; - } - - // nfz: set up multipass rendering - mDestRenderSystem->setCurrentPassIterationCount(pass->getPassIterationCount()); - _issueRenderOp(rend, pass); - - if (scissored == CLIPPED_SOME) - resetScissor(); - if (clipped == CLIPPED_SOME) - resetLightClip(); -} -//----------------------------------------------------------------------- -static void injectGlobalInstancingDeclaration(RenderOperation& ro, const RenderSystem* rs) -{ - if (!ro.useGlobalInstancing) - return; - - // Create variables related to instancing. - VertexDeclaration* instanceDecl = rs->getGlobalInstanceVertexDeclaration(); - - if(!instanceDecl || instanceDecl->getElements().empty()) - return; - - auto instancingSrc = ro.vertexData->vertexDeclaration->getMaxSource(); - - auto testElement = instanceDecl->getElements().front(); - if(!ro.vertexData->vertexDeclaration->findElementBySemantic(testElement.getSemantic(), testElement.getIndex())) - { - instancingSrc += 1; - for (auto el : instanceDecl->getElements()) - { - ro.vertexData->vertexDeclaration->addElement(instancingSrc, el.getOffset(), el.getType(), el.getSemantic(), - el.getIndex()); - } - } - ro.vertexData->vertexBufferBinding->setBinding(instancingSrc, rs->getGlobalInstanceVertexBuffer()); - - ro.numberOfInstances *= rs->getGlobalInstanceCount(); -} - -static PolygonMode derivePolygonMode(const Pass* pass, const Renderable* rend, const Camera* cam) -{ - // Set up the solid / wireframe override - // Precedence is Camera, Object, Material - // Camera might not override object if not overrideable - PolygonMode reqMode = pass->getPolygonMode(); - if (pass->getPolygonModeOverrideable() && rend->getPolygonModeOverrideable()) - { - PolygonMode camPolyMode = cam->getPolygonMode(); - // check camera detial only when render detail is overridable - if (reqMode > camPolyMode) - { - // only downgrade detail; if cam says wireframe we don't go up to solid - reqMode = camPolyMode; - } - } - return reqMode; -} - -void SceneManager::renderInstancedObject(const RenderableList& rends, const Pass* pass, bool lightScissoringClipping, - bool doLightIteration, const LightList* manualLightList) -{ - mAutoParamDataSource->setCurrentRenderable(rends.front()); - // override: this is passed through the instance buffer - mAutoParamDataSource->setWorldMatrices(&Affine3::IDENTITY, 1); - - // Shader only path -> no normalise normals - - // We batch world matrices, so we skip setWorldTransform for each individual renderable - - // this copes with returning from negative scale in previous render op - // for same pass - if (mFlipCullingOnNegativeScale && mPassCullingMode != mDestRenderSystem->_getCullingMode()) - mDestRenderSystem->_setCullingMode(mPassCullingMode); - - mDestRenderSystem->_setPolygonMode(derivePolygonMode(pass, rends.front(), mCameraInProgress)); - - // TODO: manually driving lights - - // collect lights of all renderables, thus cannot handle start-light without re-sorting - std::set batchLights; - for (auto r : rends) - { - const LightList& rendLightList = r->getLights(); - batchLights.insert(rendLightList.begin(), rendLightList.end()); - } - LightList lightListToUse; - - if(pass->getLightMask() == 0xFFFFFFFF) - { - lightListToUse = LightList(batchLights.begin(), batchLights.end()); - } - else - { - for (auto l : batchLights) - if (pass->getLightMask() & l->getLightMask()) - lightListToUse.push_back(l); - } - - // TODO IterationDepthBias - - // TODO light scissoring & clipping - - useLights(&lightListToUse, pass->getMaxSimultaneousLights()); - fireRenderSingleObject(rends.front(), pass, mAutoParamDataSource.get(), &lightListToUse, false); - - updateGpuProgramParameters(pass); - - if(!rends.front()->preRender(this, mDestRenderSystem)) - { - rends.front()->postRender(this, mDestRenderSystem); - return; - } - - using Matrix3x4f = TransformBase<3, float>; - - // update instance buffer - if (!mInstanceBuffer || mInstanceBuffer->getNumVertices() < rends.size()) - { - mInstanceBuffer = HardwareBufferManager::getSingleton().createVertexBuffer(sizeof(Matrix3x4f), rends.size(), HBU_CPU_TO_GPU); - mInstanceBuffer->setIsInstanceData(true); - mInstanceBuffer->setInstanceDataStepRate(1); - } - - // fill instance data - { - HardwareBufferLockGuard lock(mInstanceBuffer, HardwareBuffer::HBL_DISCARD); - auto instanceData = static_cast(lock.pData); - - auto camPos = mAutoParamDataSource->getCurrentCamera()->getDerivedPosition(); - - for (auto r : rends) - { - auto worldT = static_cast(r)->getParent()->_getParentNodeFullTransform(); - if(mCameraRelativeRendering) - worldT.setTrans(worldT.getTrans() - camPos); - *instanceData++ = Matrix3x4f(worldT[0]); - } - } - - RenderOperation ro; - rends.front()->getRenderOperation(ro); - ro.srcRenderable = rends.front(); - ro.numberOfInstances = rends.size(); - - auto ielem = ro.vertexData->vertexDeclaration->findElementBySemantic(VES_TEXTURE_COORDINATES, 1); - - auto instancingSrc = ro.vertexData->vertexDeclaration->getMaxSource(); - if(!ielem || instancingSrc == 0) - { - ro.vertexData->vertexDeclaration->removeElement(VES_TEXTURE_COORDINATES, 1); - - instancingSrc += 1; - auto vec4sz = VertexElement::getTypeSize(VET_FLOAT4); - ro.vertexData->vertexDeclaration->addElement(instancingSrc, 0 * vec4sz, VET_FLOAT4, VES_TEXTURE_COORDINATES, 1); - ro.vertexData->vertexDeclaration->addElement(instancingSrc, 1 * vec4sz, VET_FLOAT4, VES_TEXTURE_COORDINATES, 2); - ro.vertexData->vertexDeclaration->addElement(instancingSrc, 2 * vec4sz, VET_FLOAT4, VES_TEXTURE_COORDINATES, 3); - // TODO ACT_CUSTOM - } - - // set again -> might have been recreated - ro.vertexData->vertexBufferBinding->setBinding(instancingSrc, mInstanceBuffer); - - injectGlobalInstancingDeclaration(ro, mDestRenderSystem); - - mDestRenderSystem->_render(ro); - - rends.front()->postRender(this, mDestRenderSystem); -} - -void SceneManager::renderSingleObject(Renderable* rend, const Pass* pass, - bool lightScissoringClipping, bool doLightIteration, - const LightList* manualLightList) -{ - // Tell auto params object about the renderable change - mAutoParamDataSource->setCurrentRenderable(rend); - - setWorldTransform(rend); - - // Sort out negative scaling - // Assume first world matrix representative - if (mFlipCullingOnNegativeScale) - { - CullingMode cullMode = mPassCullingMode; - - if (mAutoParamDataSource->getWorldMatrix().linear().hasNegativeScale()) - { - switch(mPassCullingMode) - { - case CULL_CLOCKWISE: - cullMode = CULL_ANTICLOCKWISE; - break; - case CULL_ANTICLOCKWISE: - cullMode = CULL_CLOCKWISE; - break; - case CULL_NONE: - break; - }; - } - - // this also copes with returning from negative scale in previous render op - // for same pass - if (cullMode != mDestRenderSystem->_getCullingMode()) - mDestRenderSystem->_setCullingMode(cullMode); - } - - mDestRenderSystem->_setPolygonMode(derivePolygonMode(pass, rend, mCameraInProgress)); - - if (!doLightIteration) - { - // Even if manually driving lights, check light type passes - if (!pass->getRunOnlyForOneLightType() || - (manualLightList && (manualLightList->size() != 1 || - manualLightList->front()->getType() == pass->getOnlyLightType()))) - { - issueRenderWithLights(rend, pass, manualLightList, lightScissoringClipping); - } - - // Reset view / projection changes if any - resetViewProjMode(); - return; - } - - // Here's where we issue the rendering operation to the render system - // Note that we may do this once per light, therefore it's in a loop - // and the light parameters are updated once per traversal through the - // loop - const LightList& rendLightList = rend->getLights(); - - bool iteratePerLight = pass->getIteratePerLight(); - - // deliberately unsigned in case start light exceeds number of lights - // in which case this pass would be skipped - int lightsLeft = 1; - if (iteratePerLight) - { - // Don't allow total light count for all iterations to exceed max per pass - lightsLeft = std::min(rendLightList.size() - pass->getStartLight(), - pass->getMaxSimultaneousLights()); - } - - const LightList* pLightListToUse; - // Start counting from the start light - size_t lightIndex = pass->getStartLight(); - size_t depthInc = 0; - - // Create local light list for faster light iteration setup - static LightList localLightList; - - while (lightsLeft > 0) - { - // Determine light list to use - if (iteratePerLight) - { - // Starting shadow texture index. - size_t shadowTexIndex = mShadowRenderer.getShadowTexIndex(lightIndex); - localLightList.resize(pass->getLightCountPerIteration()); - - LightList::iterator destit = localLightList.begin(); - unsigned short numShadowTextureLights = 0; - for (; destit != localLightList.end() && lightIndex < rendLightList.size(); - ++lightIndex, --lightsLeft) - { - Light* currLight = rendLightList[lightIndex]; - - // Check whether we need to filter this one out - if ((pass->getRunOnlyForOneLightType() && - pass->getOnlyLightType() != currLight->getType()) || - (pass->getLightMask() & currLight->getLightMask()) == 0) - { - // Skip - // Also skip shadow texture(s) - if (isShadowTechniqueTextureBased()) - { - shadowTexIndex += mShadowRenderer.mShadowTextureCountPerType[currLight->getType()]; - } - continue; - } - - *destit++ = currLight; - - if (!isShadowTechniqueTextureBased()) - continue; - - // potentially need to update content_type shadow texunit - // corresponding to this light - size_t textureCountPerLight = mShadowRenderer.mShadowTextureCountPerType[currLight->getType()]; - for (size_t j = 0; j < textureCountPerLight && shadowTexIndex < mShadowRenderer.mShadowTextures.size(); ++j) - { - // link the numShadowTextureLights'th shadow texture unit - ushort tuindex = pass->_getTextureUnitWithContentTypeIndex( - TextureUnitState::CONTENT_SHADOW, numShadowTextureLights); - if (tuindex > pass->getNumTextureUnitStates()) break; - - TextureUnitState* tu = pass->getTextureUnitState(tuindex); - const TexturePtr& shadowTex = mShadowRenderer.mShadowTextures[shadowTexIndex]; - tu->_setTexturePtr(shadowTex); - Camera *cam = shadowTex->getBuffer()->getRenderTarget()->getViewport(0)->getCamera(); - tu->setProjectiveTexturing(!pass->hasVertexProgram(), cam); - mAutoParamDataSource->setTextureProjector(cam, numShadowTextureLights); - ++numShadowTextureLights; - ++shadowTexIndex; - // Have to set TU on rendersystem right now, although - // autoparams will be set later - mDestRenderSystem->_setTextureUnitSettings(tuindex, *tu); - } - } - // Did we run out of lights before slots? e.g. 5 lights, 2 per iteration - if (destit != localLightList.end()) - { - localLightList.erase(destit, localLightList.end()); - lightsLeft = 0; - } - pLightListToUse = &localLightList; - - // deal with the case where we found no lights - // since this is light iteration, we shouldn't render at all - if (pLightListToUse->empty()) - break; - } - else // !iterate per light - { - // Use complete light list potentially adjusted by start light - if (pass->getStartLight() || pass->getMaxSimultaneousLights() != OGRE_MAX_SIMULTANEOUS_LIGHTS || - pass->getLightMask() != 0xFFFFFFFF) - { - // out of lights? - // skip manual 2nd lighting passes onwards if we run out of lights, but never the first one - if (pass->getStartLight() > 0 && pass->getStartLight() >= rendLightList.size()) - { - break; - } - - localLightList.clear(); - LightList::const_iterator copyStart = rendLightList.begin(); - std::advance(copyStart, pass->getStartLight()); - // Clamp lights to copy to avoid overrunning the end of the list - size_t lightsCopied = 0, lightsToCopy = std::min( - static_cast(pass->getMaxSimultaneousLights()), - rendLightList.size() - pass->getStartLight()); - - // Copy lights over - for(LightList::const_iterator iter = copyStart; iter != rendLightList.end() && lightsCopied < lightsToCopy; ++iter) - { - if((pass->getLightMask() & (*iter)->getLightMask()) != 0) - { - localLightList.push_back(*iter); - lightsCopied++; - } - } - - pLightListToUse = &localLightList; - } - else - { - pLightListToUse = &rendLightList; - } - lightsLeft = 0; - } - - // issue the render op - - // We might need to update the depth bias each iteration - if (pass->getIterationDepthBias() != 0.0f) - { - float depthBiasBase = - pass->getDepthBiasConstant() + pass->getIterationDepthBias() * depthInc; - // depthInc deals with light iteration - - // Note that we have to set the depth bias here even if the depthInc - // is zero (in which case you would think there is no change from - // what was set in _setPass(). The reason is that if there are - // multiple Renderables with this Pass, we won't go through _setPass - // again at the start of the iteration for the next Renderable - // because of Pass state grouping. So set it always - - // Set modified depth bias right away - mDestRenderSystem->_setDepthBias(depthBiasBase, pass->getDepthBiasSlopeScale()); - - // Set to increment internally too if rendersystem iterates - mDestRenderSystem->setDeriveDepthBias(true, - depthBiasBase, pass->getIterationDepthBias(), - pass->getDepthBiasSlopeScale()); - } - else - { - mDestRenderSystem->setDeriveDepthBias(false); - } - depthInc += pass->getPassIterationCount(); - - issueRenderWithLights(rend, pass, pLightListToUse, lightScissoringClipping); - } // possibly iterate per light - - // Reset view / projection changes if any - resetViewProjMode(); -} -//----------------------------------------------------------------------- -void SceneManager::setAmbientLight(const ColourValue& colour) -{ - mGpuParamsDirty |= GPV_GLOBAL; - mAutoParamDataSource->setAmbientLightColour(colour); -} -//----------------------------------------------------------------------- -const ColourValue& SceneManager::getAmbientLight(void) const -{ - return mAutoParamDataSource->getAmbientLightColour(); -} -//----------------------------------------------------------------------- -ViewPoint SceneManager::getSuggestedViewpoint(bool random) -{ - // By default return the origin - ViewPoint vp; - vp.position = Vector3::ZERO; - vp.orientation = Quaternion::IDENTITY; - return vp; -} -//----------------------------------------------------------------------- -void SceneManager::setFog(FogMode mode, const ColourValue& colour, Real density, Real start, Real end) -{ - mFogMode = mode; - mFogColour = colour; - mFogStart = start; - mFogEnd = end; - mFogDensity = density; -} -//----------------------------------------------------------------------- -FogMode SceneManager::getFogMode(void) const -{ - return mFogMode; -} -//----------------------------------------------------------------------- -const ColourValue& SceneManager::getFogColour(void) const -{ - return mFogColour; -} -//----------------------------------------------------------------------- -Real SceneManager::getFogStart(void) const -{ - return mFogStart; -} -//----------------------------------------------------------------------- -Real SceneManager::getFogEnd(void) const -{ - return mFogEnd; -} -//----------------------------------------------------------------------- -Real SceneManager::getFogDensity(void) const -{ - return mFogDensity; -} -//----------------------------------------------------------------------- -BillboardSet* SceneManager::createBillboardSet(const String& name, unsigned int poolSize) -{ - NameValuePairList params; - params["poolSize"] = StringConverter::toString(poolSize); - return static_cast(createMovableObject(name, MOT_BILLBOARD_SET, ¶ms)); -} -//----------------------------------------------------------------------- -BillboardSet* SceneManager::createBillboardSet(unsigned int poolSize) -{ - String name = mMovableNameGenerator.generate(); - return createBillboardSet(name, poolSize); -} -//----------------------------------------------------------------------- -BillboardSet* SceneManager::getBillboardSet(const String& name) const -{ - return static_cast(getMovableObject(name, MOT_BILLBOARD_SET)); -} -//----------------------------------------------------------------------- -void SceneManager::setDisplaySceneNodes(bool display) -{ - mDisplayNodes = display; -} -//----------------------------------------------------------------------- -Animation* SceneManager::createAnimation(const String& name, Real length) -{ - OGRE_LOCK_MUTEX(mAnimationsListMutex); - - // Check name not used - if (mAnimationsList.find(name) != mAnimationsList.end()) - { - OGRE_EXCEPT( - Exception::ERR_DUPLICATE_ITEM, - "An animation with the name " + name + " already exists", - "SceneManager::createAnimation" ); - } - - Animation* pAnim = OGRE_NEW Animation(name, length); - mAnimationsList[name] = pAnim; - return pAnim; -} -//----------------------------------------------------------------------- -Animation* SceneManager::getAnimation(const String& name) const -{ - OGRE_LOCK_MUTEX(mAnimationsListMutex); - - AnimationList::const_iterator i = mAnimationsList.find(name); - if (i == mAnimationsList.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Cannot find animation with name " + name, - "SceneManager::getAnimation"); - } - return i->second; -} -//----------------------------------------------------------------------- -bool SceneManager::hasAnimation(const String& name) const -{ - OGRE_LOCK_MUTEX(mAnimationsListMutex); - return (mAnimationsList.find(name) != mAnimationsList.end()); -} -//----------------------------------------------------------------------- -void SceneManager::destroyAnimation(const String& name) -{ - OGRE_LOCK_MUTEX(mAnimationsListMutex); - - // Also destroy any animation states referencing this animation - mAnimationStates.removeAnimationState(name); - - AnimationList::iterator i = mAnimationsList.find(name); - if (i == mAnimationsList.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Cannot find animation with name " + name, - "SceneManager::getAnimation"); - } - - // Free memory - OGRE_DELETE i->second; - - mAnimationsList.erase(i); - -} -//----------------------------------------------------------------------- -void SceneManager::destroyAllAnimations(void) -{ - OGRE_LOCK_MUTEX(mAnimationsListMutex); - // Destroy all states too, since they cannot reference destroyed animations - destroyAllAnimationStates(); - - for (auto& i : mAnimationsList) - { - // destroy - OGRE_DELETE i.second; - } - mAnimationsList.clear(); -} -//----------------------------------------------------------------------- -AnimationState* SceneManager::createAnimationState(const String& animName) -{ - // Get animation, this will throw an exception if not found - Animation* anim = getAnimation(animName); - - // Create new state - return mAnimationStates.createAnimationState(animName, 0, anim->getLength()); - -} -//----------------------------------------------------------------------- -AnimationState* SceneManager::getAnimationState(const String& animName) const -{ - return mAnimationStates.getAnimationState(animName); - -} -//----------------------------------------------------------------------- -bool SceneManager::hasAnimationState(const String& name) const -{ - return mAnimationStates.hasAnimationState(name); -} -//----------------------------------------------------------------------- -void SceneManager::destroyAnimationState(const String& name) -{ - mAnimationStates.removeAnimationState(name); -} -//----------------------------------------------------------------------- -void SceneManager::destroyAllAnimationStates(void) -{ - mAnimationStates.removeAllAnimationStates(); -} -//----------------------------------------------------------------------- -void SceneManager::_applySceneAnimations(void) -{ - // manual lock over states (extended duration required) - OGRE_LOCK_MUTEX(mAnimationStates.OGRE_AUTO_MUTEX_NAME); - - // Iterate twice, once to reset, once to apply, to allow blending - for(auto *state : mAnimationStates.getEnabledAnimationStates()) - { - Animation* anim = getAnimation(state->getAnimationName()); - - // Reset any nodes involved - for (const auto& it : anim->_getNodeTrackList()) - { - if (Node* nd = it.second->getAssociatedNode()) - nd->resetToInitialState(); - } - - for (const auto& it : anim->_getNumericTrackList()) - { - if (const auto& animPtr = it.second->getAssociatedAnimable()) - animPtr->resetToBaseValue(); - } - } - - // this should allow blended animations - for(auto *state : mAnimationStates.getEnabledAnimationStates()) - { - Animation* anim = getAnimation(state->getAnimationName()); - // Apply the animation - anim->apply(state->getTimePosition(), state->getWeight()); - } -} -//--------------------------------------------------------------------- -void SceneManager::manualRender(RenderOperation* rend, - Pass* pass, Viewport* vp, const Affine3& worldMatrix, - const Affine3& viewMatrix, const Matrix4& projMatrix, - bool doBeginEndFrame) -{ - if (vp) - setViewport(vp); - - if (doBeginEndFrame) - mDestRenderSystem->_beginFrame(); - - auto usedPass = _setPass(pass); - mAutoParamDataSource->setCurrentRenderable(0); - if (vp) - { - mAutoParamDataSource->setCurrentRenderTarget(vp->getTarget()); - } - mAutoParamDataSource->setCurrentSceneManager(this); - mAutoParamDataSource->setWorldMatrices(&worldMatrix, 1); - Camera dummyCam(BLANKSTRING, 0); - dummyCam.setCustomViewMatrix(true, viewMatrix); - dummyCam.setCustomProjectionMatrix(true, projMatrix); - mAutoParamDataSource->setCurrentCamera(&dummyCam, false); - updateGpuProgramParameters(usedPass); - mDestRenderSystem->_render(*rend); - - if (doBeginEndFrame) - mDestRenderSystem->_endFrame(); - -} -//--------------------------------------------------------------------- -void SceneManager::manualRender(Renderable* rend, const Pass* pass, Viewport* vp, - const Affine3& viewMatrix, - const Matrix4& projMatrix,bool doBeginEndFrame, - bool lightScissoringClipping, bool doLightIteration, const LightList* manualLightList) -{ - if (vp) - setViewport(vp); - - if (doBeginEndFrame) - mDestRenderSystem->_beginFrame(); - - auto usedPass = _setPass(pass); - Camera dummyCam(BLANKSTRING, 0); - dummyCam.setCustomViewMatrix(true, viewMatrix); - dummyCam.setCustomProjectionMatrix(true, projMatrix); - - if (vp) - { - mAutoParamDataSource->setCurrentRenderTarget(vp->getTarget()); - } - - const Camera* oldCam = mAutoParamDataSource->getCurrentCamera(); - - mAutoParamDataSource->setCurrentSceneManager(this); - mAutoParamDataSource->setCurrentCamera(&dummyCam, false); - - renderSingleObject(rend, usedPass, lightScissoringClipping, doLightIteration, manualLightList); - - mAutoParamDataSource->setCurrentCamera(oldCam, false); - - if (doBeginEndFrame) - mDestRenderSystem->_endFrame(); - -} -//--------------------------------------------------------------------- -void SceneManager::resetViewProjMode() -{ - if (mResetIdentityView) - { - // Coming back to normal from identity view - mGpuParamsDirty |= (uint16)GPV_GLOBAL; - - mResetIdentityView = false; - } - - if (mResetIdentityProj) - { - // Coming back from flat projection - mGpuParamsDirty |= (uint16)GPV_GLOBAL; - - mResetIdentityProj = false; - } - - -} -//--------------------------------------------------------------------- -void SceneManager::addRenderQueueListener(RenderQueueListener* newListener) -{ - mRenderQueueListeners.push_back(newListener); -} -//--------------------------------------------------------------------- -void SceneManager::removeRenderQueueListener(RenderQueueListener* delListener) -{ - RenderQueueListenerList::iterator i, iend; - iend = mRenderQueueListeners.end(); - for (i = mRenderQueueListeners.begin(); i != iend; ++i) - { - if (*i == delListener) - { - mRenderQueueListeners.erase(i); - break; - } - } - -} -//--------------------------------------------------------------------- -void SceneManager::addRenderObjectListener(RenderObjectListener* newListener) -{ - mRenderObjectListeners.push_back(newListener); -} -//--------------------------------------------------------------------- -void SceneManager::removeRenderObjectListener(RenderObjectListener* delListener) -{ - RenderObjectListenerList::iterator i, iend; - iend = mRenderObjectListeners.end(); - for (i = mRenderObjectListeners.begin(); i != iend; ++i) - { - if (*i == delListener) - { - mRenderObjectListeners.erase(i); - break; - } - } -} -void SceneManager::addListener(Listener* newListener) -{ - if (std::find(mListeners.begin(), mListeners.end(), newListener) == mListeners.end()) - mListeners.push_back(newListener); -} -//--------------------------------------------------------------------- -void SceneManager::removeListener(Listener* delListener) -{ - ListenerList::iterator i = std::find(mListeners.begin(), mListeners.end(), delListener); - if (i != mListeners.end()) - mListeners.erase(i); -} -void SceneManager::addShadowTextureListener(ShadowTextureListener* newListener) -{ - if (std::find(mShadowRenderer.mListeners.begin(), mShadowRenderer.mListeners.end(), newListener) == - mShadowRenderer.mListeners.end()) - mShadowRenderer.mListeners.push_back(newListener); -} -//--------------------------------------------------------------------- -void SceneManager::removeShadowTextureListener(ShadowTextureListener* delListener) -{ - auto i = std::find(mShadowRenderer.mListeners.begin(), mShadowRenderer.mListeners.end(), delListener); - if (i != mShadowRenderer.mListeners.end()) - mShadowRenderer.mListeners.erase(i); -} -//--------------------------------------------------------------------- -void SceneManager::firePreRenderQueues() -{ - for (auto *l : mRenderQueueListeners) - { - l->preRenderQueues(); - } -} -//--------------------------------------------------------------------- -void SceneManager::firePostRenderQueues() -{ - for (auto *l : mRenderQueueListeners) - { - l->postRenderQueues(); - } -} -//--------------------------------------------------------------------- -bool SceneManager::fireRenderQueueStarted(uint8 id, const String& cameraName) -{ - bool skip = false; - for (auto *l : mRenderQueueListeners) - { - l->renderQueueStarted(id, cameraName, skip); - } - return skip; -} -//--------------------------------------------------------------------- -bool SceneManager::fireRenderQueueEnded(uint8 id, const String& cameraName) -{ - bool repeat = false; - for (auto *l : mRenderQueueListeners) - { - l->renderQueueEnded(id, cameraName, repeat); - } - return repeat; -} -//--------------------------------------------------------------------- -void SceneManager::fireRenderSingleObject(Renderable* rend, const Pass* pass, - const AutoParamDataSource* source, - const LightList* pLightList, bool suppressRenderStateChanges) -{ - for (auto *l : mRenderObjectListeners) - { - l->notifyRenderSingleObject(rend, pass, source, pLightList, suppressRenderStateChanges); - } -} -//--------------------------------------------------------------------- -void SceneManager::firePreUpdateSceneGraph(Camera* camera) -{ - ListenerList listenersCopy = mListeners; - for (auto *l : listenersCopy) - { - l->preUpdateSceneGraph(this, camera); - } -} -//--------------------------------------------------------------------- -void SceneManager::firePostUpdateSceneGraph(Camera* camera) -{ - ListenerList listenersCopy = mListeners; - for (auto *l : listenersCopy) - { - l->postUpdateSceneGraph(this, camera); - } -} - -//--------------------------------------------------------------------- -void SceneManager::firePreFindVisibleObjects(Viewport* v) -{ - ListenerList listenersCopy = mListeners; - for (auto *l : listenersCopy) - { - l->preFindVisibleObjects(this, mIlluminationStage, v); - } - -} -//--------------------------------------------------------------------- -void SceneManager::firePostFindVisibleObjects(Viewport* v) -{ - ListenerList listenersCopy = mListeners; - for (auto *l : listenersCopy) - { - l->postFindVisibleObjects(this, mIlluminationStage, v); - } -} -//--------------------------------------------------------------------- -void SceneManager::fireSceneManagerDestroyed() -{ - ListenerList listenersCopy = mListeners; - for (auto *l : listenersCopy) - { - l->sceneManagerDestroyed(this); - } -} -//--------------------------------------------------------------------- -void SceneManager::setViewport(Viewport* vp) -{ - mCurrentViewport = vp; - // Tell params about viewport - mAutoParamDataSource->setCurrentViewport(vp); - // Set viewport in render system - mDestRenderSystem->_setViewport(vp); - // Set the active material scheme for this viewport - MaterialManager::getSingleton().setActiveScheme(vp->getMaterialScheme()); -} -//--------------------------------------------------------------------- -void SceneManager::showBoundingBoxes(bool bShow) -{ - mShowBoundingBoxes = bShow; -} -//--------------------------------------------------------------------- -bool SceneManager::getShowBoundingBoxes() const -{ - return mShowBoundingBoxes; -} -//--------------------------------------------------------------------- -void SceneManager::_notifyAutotrackingSceneNode(SceneNode* node, bool autoTrack) -{ - if (autoTrack) - { - mAutoTrackingSceneNodes.insert(node); - } - else - { - mAutoTrackingSceneNodes.erase(node); - } -} -void SceneManager::setShadowTechnique(ShadowTechnique technique) -{ - mShadowRenderer.setShadowTechnique(technique); -} -//----------------------------------------------------------------------- -void SceneManager::_notifyLightsDirty(void) -{ - ++mLightsDirtyCounter; -} -//--------------------------------------------------------------------- -void SceneManager::updateCachedLightInfos(const Camera* camera) -{ - // Update lights affecting frustum if changed - if (mCachedLightInfos != mTestLightInfos) - { - mLightsAffectingFrustum.resize(mTestLightInfos.size()); - LightInfoList::const_iterator i; - LightList::iterator j = mLightsAffectingFrustum.begin(); - for (i = mTestLightInfos.begin(); i != mTestLightInfos.end(); ++i, ++j) - { - *j = i->light; - // add cam distance for sorting if texture shadows - if (isShadowTechniqueTextureBased()) - { - (*j)->_calcTempSquareDist(camera->getDerivedPosition()); - } - } - - mShadowRenderer.sortLightsAffectingFrustum(mLightsAffectingFrustum); - // Use swap instead of copy operator for efficiently - mCachedLightInfos.swap(mTestLightInfos); - - // notify light dirty, so all movable objects will re-populate - // their light list next time - _notifyLightsDirty(); - } -} -void SceneManager::findLightsAffectingFrustum(const Camera* camera) -{ - // Basic iteration for this SM - - MovableObjectCollection* lights = getMovableObjectCollection(MOT_LIGHT); - - { - OGRE_LOCK_MUTEX(lights->mutex); - - // Pre-allocate memory - mTestLightInfos.clear(); - mTestLightInfos.reserve(lights->map.size()); - - MovableObjectIterator it(lights->map.begin(), lights->map.end()); - - while(it.hasMoreElements()) - { - Light* l = static_cast(it.getNext()); - - if (mCameraRelativeRendering) - l->_setCameraRelative(mCameraInProgress); - else - l->_setCameraRelative(0); - - if (l->isVisible()) - { - LightInfo lightInfo; - lightInfo.light = l; - lightInfo.type = l->getType(); - lightInfo.lightMask = l->getLightMask(); - if (lightInfo.type == Light::LT_DIRECTIONAL) - { - // Always visible - lightInfo.position = Vector3::ZERO; - lightInfo.range = 0; - mTestLightInfos.push_back(lightInfo); - } - else - { - // NB treating spotlight as point for simplicity - // Just see if the lights attenuation range is within the frustum - lightInfo.range = l->getAttenuationRange(); - lightInfo.position = l->getDerivedPosition(); - Sphere sphere(lightInfo.position, lightInfo.range); - if (camera->isVisible(sphere)) - { - mTestLightInfos.push_back(lightInfo); - } - } - } - } - } // release lock on lights collection - - updateCachedLightInfos(camera); -} -void SceneManager::initShadowVolumeMaterials() -{ - mShadowRenderer.initShadowVolumeMaterials(); -} -//--------------------------------------------------------------------- -static void buildScissor(const Light* light, const Camera* cam, RealRect& rect) -{ - // Project the sphere onto the camera - Sphere sphere(light->getDerivedPosition(), light->getAttenuationRange()); - cam->Frustum::projectSphere(sphere, &(rect.left), &(rect.top), &(rect.right), &(rect.bottom)); -} -const RealRect& SceneManager::getLightScissorRect(Light* l, const Camera* cam) -{ - checkCachedLightClippingInfo(); - - // Re-use calculations if possible - LightClippingInfoMap::iterator ci = mLightClippingInfoMap.emplace(l, LightClippingInfo()).first; - if (!ci->second.scissorValid) - { - - buildScissor(l, cam, ci->second.scissorRect); - ci->second.scissorValid = true; - } - - return ci->second.scissorRect; - -} -//--------------------------------------------------------------------- -ClipResult SceneManager::buildAndSetScissor(const LightList& ll, const Camera* cam) -{ - RealRect finalRect; - // init (inverted since we want to grow from nothing) - finalRect.left = finalRect.bottom = 1.0f; - finalRect.right = finalRect.top = -1.0f; - - for (auto *l : ll) - { - // a directional light is being used, no scissoring can be done, period. - if (l->getType() == Light::LT_DIRECTIONAL) - return CLIPPED_NONE; - - const RealRect& scissorRect = getLightScissorRect(l, cam); - - // merge with final - finalRect.left = std::min(finalRect.left, scissorRect.left); - finalRect.bottom = std::min(finalRect.bottom, scissorRect.bottom); - finalRect.right= std::max(finalRect.right, scissorRect.right); - finalRect.top = std::max(finalRect.top, scissorRect.top); - - - } - - if (finalRect.left >= 1.0f || finalRect.right <= -1.0f || - finalRect.top <= -1.0f || finalRect.bottom >= 1.0f) - { - // rect was offscreen - return CLIPPED_ALL; - } - - // Some scissoring? - if (finalRect.left > -1.0f || finalRect.right < 1.0f || - finalRect.bottom > -1.0f || finalRect.top < 1.0f) - { - // Turn normalised device coordinates into pixels - Rect vp = mCurrentViewport->getActualDimensions(); - - Rect scissor(vp.left + ((finalRect.left + 1) * 0.5 * vp.width()), - vp.top + ((-finalRect.top + 1) * 0.5 * vp.height()), - vp.left + ((finalRect.right + 1) * 0.5 * vp.width()), - vp.top + ((-finalRect.bottom + 1) * 0.5 * vp.height())); - mDestRenderSystem->setScissorTest(true, scissor); - - return CLIPPED_SOME; - } - else - return CLIPPED_NONE; - -} -//--------------------------------------------------------------------- -void SceneManager::resetScissor() -{ - mDestRenderSystem->setScissorTest(false); -} -//--------------------------------------------------------------------- -void SceneManager::invalidatePerFrameScissorRectCache() -{ - checkCachedLightClippingInfo(true); -} -//--------------------------------------------------------------------- -void SceneManager::checkCachedLightClippingInfo(bool forceScissorRectsInvalidation) -{ - unsigned long frame = Root::getSingleton().getNextFrameNumber(); - if (frame != mLightClippingInfoMapFrameNumber) - { - // reset cached clip information - mLightClippingInfoMap.clear(); - mLightClippingInfoMapFrameNumber = frame; - } - else if(forceScissorRectsInvalidation) - { - for(auto& c : mLightClippingInfoMap) - c.second.scissorValid = false; - } -} -//--------------------------------------------------------------------- -const PlaneList& SceneManager::getLightClippingPlanes(Light* l) -{ - checkCachedLightClippingInfo(); - - // Try to re-use clipping info if already calculated - LightClippingInfoMap::iterator ci = mLightClippingInfoMap.emplace(l, LightClippingInfo()).first; - - if (!ci->second.clipPlanesValid) - { - buildLightClip(l, ci->second.clipPlanes); - ci->second.clipPlanesValid = true; - } - return ci->second.clipPlanes; - -} -//--------------------------------------------------------------------- -ClipResult SceneManager::buildAndSetLightClip(const LightList& ll) -{ - if (!mDestRenderSystem->getCapabilities()->hasCapability(RSC_USER_CLIP_PLANES)) - return CLIPPED_NONE; - - Light* clipBase = 0; - for (auto *l : ll) - { - // a directional light is being used, no clipping can be done, period. - if (l->getType() == Light::LT_DIRECTIONAL) - return CLIPPED_NONE; - - if (clipBase) - { - // we already have a clip base, so we had more than one light - // in this list we could clip by, so clip none - return CLIPPED_NONE; - } - clipBase = l; - } - - if (clipBase) - { - const PlaneList& clipPlanes = getLightClippingPlanes(clipBase); - - mDestRenderSystem->setClipPlanes(clipPlanes); - return CLIPPED_SOME; - } - else - { - // Can only get here if no non-directional lights from which to clip from - // ie list must be empty - return CLIPPED_ALL; - } - - -} -//--------------------------------------------------------------------- -void SceneManager::buildLightClip(const Light* l, PlaneList& planes) -{ - if (!mDestRenderSystem->getCapabilities()->hasCapability(RSC_USER_CLIP_PLANES)) - return; - - planes.clear(); - - Vector3 pos = l->getDerivedPosition(); - Real r = l->getAttenuationRange(); - switch(l->getType()) - { - case Light::LT_POINT: - { - planes.push_back(Plane(Vector3::UNIT_X, pos + Vector3(-r, 0, 0))); - planes.push_back(Plane(Vector3::NEGATIVE_UNIT_X, pos + Vector3(r, 0, 0))); - planes.push_back(Plane(Vector3::UNIT_Y, pos + Vector3(0, -r, 0))); - planes.push_back(Plane(Vector3::NEGATIVE_UNIT_Y, pos + Vector3(0, r, 0))); - planes.push_back(Plane(Vector3::UNIT_Z, pos + Vector3(0, 0, -r))); - planes.push_back(Plane(Vector3::NEGATIVE_UNIT_Z, pos + Vector3(0, 0, r))); - } - break; - case Light::LT_SPOTLIGHT: - { - Vector3 dir = l->getDerivedDirection(); - // near & far planes - planes.push_back(Plane(dir, pos + dir * l->getSpotlightNearClipDistance())); - planes.push_back(Plane(-dir, pos + dir * r)); - // 4 sides of pyramids - // derive orientation - Vector3 up = Vector3::UNIT_Y; - // Check it's not coincident with dir - if (Math::Abs(up.dotProduct(dir)) >= 1.0f) - { - up = Vector3::UNIT_Z; - } - // Derive rotation from axes (negate dir since -Z) - Matrix3 q = Math::lookRotation(-dir, up); - - // derive pyramid corner vectors in world orientation - Vector3 tl, tr, bl, br; - Real d = Math::Tan(l->getSpotlightOuterAngle() * 0.5) * r; - tl = q * Vector3(-d, d, -r); - tr = q * Vector3(d, d, -r); - bl = q * Vector3(-d, -d, -r); - br = q * Vector3(d, -d, -r); - - // use cross product to derive normals, pass through light world pos - // top - planes.push_back(Plane(tl.crossProduct(tr).normalisedCopy(), pos)); - // right - planes.push_back(Plane(tr.crossProduct(br).normalisedCopy(), pos)); - // bottom - planes.push_back(Plane(br.crossProduct(bl).normalisedCopy(), pos)); - // left - planes.push_back(Plane(bl.crossProduct(tl).normalisedCopy(), pos)); - - } - break; - default: - // do nothing - break; - }; - -} -//--------------------------------------------------------------------- -void SceneManager::resetLightClip() -{ - if (!mDestRenderSystem->getCapabilities()->hasCapability(RSC_USER_CLIP_PLANES)) - return; - - mDestRenderSystem->setClipPlanes(PlaneList()); -} -//--------------------------------------------------------------------- -const ColourValue& SceneManager::getShadowColour(void) const -{ - return mShadowRenderer.mShadowColour; -} -//--------------------------------------------------------------------- -void SceneManager::setShadowFarDistance(Real distance) -{ - mShadowRenderer.mDefaultShadowFarDist = distance; - mShadowRenderer.mDefaultShadowFarDistSquared = distance * distance; -} -//--------------------------------------------------------------------- -void SceneManager::setShadowDirectionalLightExtrusionDistance(Real dist) -{ - mShadowRenderer.mShadowDirLightExtrudeDist = dist; -} -//--------------------------------------------------------------------- -Real SceneManager::getShadowDirectionalLightExtrusionDistance(void) const -{ - return mShadowRenderer.mShadowDirLightExtrudeDist; -} -void SceneManager::setShadowIndexBufferSize(size_t size) -{ - mShadowRenderer.setShadowIndexBufferSize(size); -} -//--------------------------------------------------------------------- -ConstShadowTextureConfigIterator SceneManager::getShadowTextureConfigIterator() const -{ - return ConstShadowTextureConfigIterator( - mShadowRenderer.mShadowTextureConfigList.begin(), mShadowRenderer.mShadowTextureConfigList.end()); - -} -//--------------------------------------------------------------------- -void SceneManager::setShadowTextureSelfShadow(bool selfShadow) -{ - mShadowRenderer.mShadowTextureSelfShadow = selfShadow; - if (isShadowTechniqueTextureBased()) - getRenderQueue()->setShadowCastersCannotBeReceivers(!selfShadow); -} -//--------------------------------------------------------------------- -void SceneManager::setShadowCameraSetup(const ShadowCameraSetupPtr& shadowSetup) -{ - mShadowRenderer.mDefaultShadowCameraSetup = shadowSetup; - -} -//--------------------------------------------------------------------- -const ShadowCameraSetupPtr& SceneManager::getShadowCameraSetup() const -{ - return mShadowRenderer.mDefaultShadowCameraSetup; -} -void SceneManager::ensureShadowTexturesCreated() -{ - mShadowRenderer.ensureShadowTexturesCreated(); -} -void SceneManager::destroyShadowTextures(void) -{ - mShadowRenderer.destroyShadowTextures(); -} -const std::vector& SceneManager::getShadowTextureCameras() -{ - return mShadowRenderer.mShadowTextureCameras; -} - -bool SceneManager::isShadowTextureConfigDirty() const -{ - return mShadowRenderer.mShadowTextureConfigDirty; -} - -void SceneManager::prepareShadowTextures(Camera* cam, Viewport* vp, const LightList* lightList) -{ - // Set the illumination stage, prevents recursive calls - IlluminationRenderStage savedStage = mIlluminationStage; - mIlluminationStage = IRS_RENDER_TO_TEXTURE; - - if (lightList == 0) - lightList = &mLightsAffectingFrustum; - - try - { - mShadowRenderer.prepareShadowTextures(cam, vp, lightList); - } - catch (Exception&) - { - // we must reset the illumination stage if an exception occurs - mIlluminationStage = savedStage; - throw; - } - - mIlluminationStage = savedStage; -} -//--------------------------------------------------------------------- -SceneManager::RenderContext* SceneManager::_pauseRendering() -{ - RenderContext* context = new RenderContext; - context->renderQueue = mRenderQueue.release(); - context->viewport = mCurrentViewport; - context->camera = mCameraInProgress; - context->activeChain = _getActiveCompositorChain(); - - mDestRenderSystem->_endFrame(); - mRenderQueue = 0; - return context; -} -//--------------------------------------------------------------------- -void SceneManager::_resumeRendering(SceneManager::RenderContext* context) -{ - mRenderQueue.reset(context->renderQueue); - _setActiveCompositorChain(context->activeChain); - Ogre::Viewport* vp = context->viewport; - Ogre::Camera* camera = context->camera; - - // Set the viewport - this is deliberately after the shadow texture update - setViewport(vp); - - // Tell params about camera - mAutoParamDataSource->setCurrentCamera(camera, mCameraRelativeRendering); - // Set autoparams for finite dir light extrusion - mAutoParamDataSource->setShadowDirLightExtrusionDistance(mShadowRenderer.mShadowDirLightExtrudeDist); - - // Tell params about render target - mAutoParamDataSource->setCurrentRenderTarget(vp->getTarget()); - - - // Set camera window clipping planes (if any) - if (mDestRenderSystem->getCapabilities()->hasCapability(RSC_USER_CLIP_PLANES)) - { - mDestRenderSystem->setClipPlanes(camera->isWindowSet() ? camera->getWindowPlanes() : PlaneList()); - } - mCameraInProgress = context->camera; - mDestRenderSystem->_beginFrame(); - - mDestRenderSystem->_setTextureProjectionRelativeTo(mCameraRelativeRendering, mCameraInProgress->getDerivedPosition()); - delete context; -} -//--------------------------------------------------------------------- -StaticGeometry* SceneManager::createStaticGeometry(const String& name) -{ - // Check not existing - if (mStaticGeometryList.find(name) != mStaticGeometryList.end()) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "StaticGeometry with name '" + name + "' already exists!", - "SceneManager::createStaticGeometry"); - } - StaticGeometry* ret = OGRE_NEW StaticGeometry(this, name); - mStaticGeometryList[name] = ret; - return ret; -} -//--------------------------------------------------------------------- -StaticGeometry* SceneManager::getStaticGeometry(const String& name) const -{ - StaticGeometryList::const_iterator i = mStaticGeometryList.find(name); - if (i == mStaticGeometryList.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "StaticGeometry with name '" + name + "' not found", - "SceneManager::createStaticGeometry"); - } - return i->second; -} -//----------------------------------------------------------------------- -bool SceneManager::hasStaticGeometry(const String& name) const -{ - return (mStaticGeometryList.find(name) != mStaticGeometryList.end()); -} - -//--------------------------------------------------------------------- -void SceneManager::destroyStaticGeometry(StaticGeometry* geom) -{ - destroyStaticGeometry(geom->getName()); -} -//--------------------------------------------------------------------- -void SceneManager::destroyStaticGeometry(const String& name) -{ - StaticGeometryList::iterator i = mStaticGeometryList.find(name); - if (i != mStaticGeometryList.end()) - { - OGRE_DELETE i->second; - mStaticGeometryList.erase(i); - } - -} -//--------------------------------------------------------------------- -void SceneManager::destroyAllStaticGeometry(void) -{ - for (auto& s : mStaticGeometryList) - { - OGRE_DELETE s.second; - } - mStaticGeometryList.clear(); -} -//--------------------------------------------------------------------- -InstanceManager* SceneManager::createInstanceManager( const String &customName, const String &meshName, - const String &groupName, - InstanceManager::InstancingTechnique technique, - size_t numInstancesPerBatch, uint16 flags, - unsigned short subMeshIdx ) -{ - if (mInstanceManagerMap.find(customName) != mInstanceManagerMap.end()) - { - OGRE_EXCEPT( Exception::ERR_DUPLICATE_ITEM, - "InstancedManager with name '" + customName + "' already exists!", - "SceneManager::createInstanceManager"); - } - - InstanceManager *retVal = new InstanceManager( customName, this, meshName, groupName, technique, - flags, numInstancesPerBatch, subMeshIdx ); - - mInstanceManagerMap[customName] = retVal; - return retVal; -} -//--------------------------------------------------------------------- -InstanceManager* SceneManager::getInstanceManager( const String &managerName ) const -{ - InstanceManagerMap::const_iterator itor = mInstanceManagerMap.find(managerName); - - if (itor == mInstanceManagerMap.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "InstancedManager with name '" + managerName + "' not found", - "SceneManager::getInstanceManager"); - } - - return itor->second; -} -//--------------------------------------------------------------------- -bool SceneManager::hasInstanceManager( const String &managerName ) const -{ - InstanceManagerMap::const_iterator itor = mInstanceManagerMap.find(managerName); - return itor != mInstanceManagerMap.end(); -} -//--------------------------------------------------------------------- -void SceneManager::destroyInstanceManager( const String &name ) -{ - //The manager we're trying to destroy might have been scheduled for updating - //while we haven't yet rendered a frame. Update now to avoid a dangling ptr - updateDirtyInstanceManagers(); - - InstanceManagerMap::iterator i = mInstanceManagerMap.find(name); - if (i != mInstanceManagerMap.end()) - { - OGRE_DELETE i->second; - mInstanceManagerMap.erase(i); - } -} -//--------------------------------------------------------------------- -void SceneManager::destroyInstanceManager( InstanceManager *instanceManager ) -{ - destroyInstanceManager( instanceManager->getName() ); -} -//--------------------------------------------------------------------- -void SceneManager::destroyAllInstanceManagers(void) -{ - for (auto& m : mInstanceManagerMap) - { - OGRE_DELETE m.second; - } - - mInstanceManagerMap.clear(); - mDirtyInstanceManagers.clear(); -} -//--------------------------------------------------------------------- -size_t SceneManager::getNumInstancesPerBatch( const String &meshName, const String &groupName, - const String &materialName, - InstanceManager::InstancingTechnique technique, - size_t numInstancesPerBatch, uint16 flags, - unsigned short subMeshIdx ) -{ - InstanceManager tmpMgr( "TmpInstanceManager", this, meshName, groupName, - technique, flags, numInstancesPerBatch, subMeshIdx ); - - return tmpMgr.getMaxOrBestNumInstancesPerBatch( materialName, numInstancesPerBatch, flags ); -} -//--------------------------------------------------------------------- -InstancedEntity* SceneManager::createInstancedEntity( const String &materialName, const String &managerName ) -{ - InstanceManagerMap::const_iterator itor = mInstanceManagerMap.find(managerName); - - if (itor == mInstanceManagerMap.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "InstancedManager with name '" + managerName + "' not found", - "SceneManager::createInstanceEntity"); - } - - return itor->second->createInstancedEntity( materialName ); -} -//--------------------------------------------------------------------- -void SceneManager::destroyInstancedEntity( InstancedEntity *instancedEntity ) -{ - instancedEntity->_getOwner()->removeInstancedEntity( instancedEntity ); -} -//--------------------------------------------------------------------- -void SceneManager::_addDirtyInstanceManager( InstanceManager *dirtyManager ) -{ - mDirtyInstanceManagers.push_back( dirtyManager ); -} -//--------------------------------------------------------------------- -void SceneManager::updateDirtyInstanceManagers(void) -{ - //Copy all dirty mgrs to a temporary buffer to iterate through them. We need this because - //if two InstancedEntities from different managers belong to the same SceneNode, one of the - //managers may have been tagged as dirty while the other wasn't, and _addDirtyInstanceManager - //will get called while iterating through them. The "while" loop will update all mgrs until - //no one is dirty anymore (i.e. A makes B aware it's dirty, B makes C aware it's dirty) - //mDirtyInstanceMgrsTmp isn't a local variable to prevent allocs & deallocs every frame. - mDirtyInstanceMgrsTmp.insert( mDirtyInstanceMgrsTmp.end(), mDirtyInstanceManagers.begin(), - mDirtyInstanceManagers.end() ); - mDirtyInstanceManagers.clear(); - - while( !mDirtyInstanceMgrsTmp.empty() ) - { - for(auto *d : mDirtyInstanceMgrsTmp) - { - d->_updateDirtyBatches(); - } - - //Clear temp buffer - mDirtyInstanceMgrsTmp.clear(); - - //Do it again? - mDirtyInstanceMgrsTmp.insert( mDirtyInstanceMgrsTmp.end(), mDirtyInstanceManagers.begin(), - mDirtyInstanceManagers.end() ); - mDirtyInstanceManagers.clear(); - } -} -//--------------------------------------------------------------------- -AxisAlignedBoxSceneQuery* -SceneManager::createAABBQuery(const AxisAlignedBox& box, uint32 mask) -{ - DefaultAxisAlignedBoxSceneQuery* q = OGRE_NEW DefaultAxisAlignedBoxSceneQuery(this); - q->setBox(box); - q->setQueryMask(mask); - return q; -} -//--------------------------------------------------------------------- -SphereSceneQuery* -SceneManager::createSphereQuery(const Sphere& sphere, uint32 mask) -{ - DefaultSphereSceneQuery* q = OGRE_NEW DefaultSphereSceneQuery(this); - q->setSphere(sphere); - q->setQueryMask(mask); - return q; -} -//--------------------------------------------------------------------- -PlaneBoundedVolumeListSceneQuery* -SceneManager::createPlaneBoundedVolumeQuery(const PlaneBoundedVolumeList& volumes, - uint32 mask) -{ - DefaultPlaneBoundedVolumeListSceneQuery* q = OGRE_NEW DefaultPlaneBoundedVolumeListSceneQuery(this); - q->setVolumes(volumes); - q->setQueryMask(mask); - return q; -} - -//--------------------------------------------------------------------- -RaySceneQuery* -SceneManager::createRayQuery(const Ray& ray, uint32 mask) -{ - DefaultRaySceneQuery* q = OGRE_NEW DefaultRaySceneQuery(this); - q->setRay(ray); - q->setQueryMask(mask); - return q; -} -//--------------------------------------------------------------------- -IntersectionSceneQuery* -SceneManager::createIntersectionQuery(uint32 mask) -{ - - DefaultIntersectionSceneQuery* q = OGRE_NEW DefaultIntersectionSceneQuery(this); - q->setQueryMask(mask); - return q; -} -//--------------------------------------------------------------------- -void SceneManager::destroyQuery(SceneQuery* query) -{ - OGRE_DELETE query; -} -//--------------------------------------------------------------------- -SceneManager::MovableObjectCollection* -SceneManager::getMovableObjectCollection(const String& typeName) -{ - // lock collection mutex - OGRE_LOCK_MUTEX(mMovableObjectCollectionMapMutex); - - MovableObjectCollectionMap::iterator i = - mMovableObjectCollectionMap.find(typeName); - if (i == mMovableObjectCollectionMap.end()) - { - // create - MovableObjectCollection* newCollection = OGRE_NEW_T(MovableObjectCollection, MEMCATEGORY_SCENE_CONTROL)(); - mMovableObjectCollectionMap[typeName] = newCollection; - return newCollection; - } - else - { - return i->second; - } -} -//--------------------------------------------------------------------- -const SceneManager::MovableObjectCollection* -SceneManager::getMovableObjectCollection(const String& typeName) const -{ - // lock collection mutex - OGRE_LOCK_MUTEX(mMovableObjectCollectionMapMutex); - - MovableObjectCollectionMap::const_iterator i = - mMovableObjectCollectionMap.find(typeName); - if (i == mMovableObjectCollectionMap.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Object collection named '" + typeName + "' does not exist.", - "SceneManager::getMovableObjectCollection"); - } - else - { - return i->second; - } -} -//--------------------------------------------------------------------- -MovableObject* SceneManager::createMovableObject(const String& name, - const String& typeName, const NameValuePairList* params) -{ - // Nasty hack to make generalised Camera functions work without breaking add-on SMs - if (typeName == MOT_CAMERA) - { - return createCamera(name); - } - MovableObjectFactory* factory = - Root::getSingleton().getMovableObjectFactory(typeName); - // Check for duplicate names - MovableObjectCollection* objectMap = getMovableObjectCollection(typeName); - - { - OGRE_LOCK_MUTEX(objectMap->mutex); - - if (objectMap->map.find(name) != objectMap->map.end()) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "An object of type '" + typeName + "' with name '" + name - + "' already exists.", - "SceneManager::createMovableObject"); - } - - MovableObject* newObj = factory->createInstance(name, this, params); - objectMap->map[name] = newObj; - return newObj; - } - -} -//--------------------------------------------------------------------- -MovableObject* SceneManager::createMovableObject(const String& typeName, const NameValuePairList* params /* = 0 */) -{ - String name = mMovableNameGenerator.generate(); - return createMovableObject(name, typeName, params); -} -//--------------------------------------------------------------------- -void SceneManager::destroyMovableObject(const String& name, const String& typeName) -{ - // Nasty hack to make generalised Camera functions work without breaking add-on SMs - if (typeName == MOT_CAMERA) - { - destroyCamera(name); - return; - } - MovableObjectCollection* objectMap = getMovableObjectCollection(typeName); - MovableObjectFactory* factory = - Root::getSingleton().getMovableObjectFactory(typeName); - - { - OGRE_LOCK_MUTEX(objectMap->mutex); - - MovableObjectMap::iterator mi = objectMap->map.find(name); - if (mi != objectMap->map.end()) - { - factory->destroyInstance(mi->second); - objectMap->map.erase(mi); - } - } -} -//--------------------------------------------------------------------- -void SceneManager::destroyAllMovableObjectsByType(const String& typeName) -{ - // Nasty hack to make generalised Camera functions work without breaking add-on SMs - if (typeName == MOT_CAMERA) - { - destroyAllCameras(); - return; - } - MovableObjectCollection* objectMap = getMovableObjectCollection(typeName); - MovableObjectFactory* factory = - Root::getSingleton().getMovableObjectFactory(typeName); - - { - OGRE_LOCK_MUTEX(objectMap->mutex); - for (auto& m : objectMap->map) - { - // Only destroy our own - if (m.second->_getManager() == this) - { - factory->destroyInstance(m.second); - } - } - objectMap->map.clear(); - } -} -//--------------------------------------------------------------------- -void SceneManager::destroyAllMovableObjects(void) -{ - // Lock collection mutex - OGRE_LOCK_MUTEX(mMovableObjectCollectionMapMutex); - for(auto& c : mMovableObjectCollectionMap) - { - MovableObjectCollection* coll = c.second; - - // lock map mutex - OGRE_LOCK_MUTEX(coll->mutex); - - if (Root::getSingleton().hasMovableObjectFactory(c.first)) - { - // Only destroy if we have a factory instance; otherwise must be injected - MovableObjectFactory* factory = - Root::getSingleton().getMovableObjectFactory(c.first); - for (auto& i : coll->map) - { - if (i.second->_getManager() == this) - { - factory->destroyInstance(i.second); - } - } - } - coll->map.clear(); - } -} -//--------------------------------------------------------------------- -MovableObject* SceneManager::getMovableObject(const String& name, const String& typeName) const -{ - // Nasty hack to make generalised Camera functions work without breaking add-on SMs - if (typeName == MOT_CAMERA) - { - return getCamera(name); - } - - const MovableObjectCollection* objectMap = getMovableObjectCollection(typeName); - - { - OGRE_LOCK_MUTEX(objectMap->mutex); - MovableObjectMap::const_iterator mi = objectMap->map.find(name); - if (mi == objectMap->map.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Object named '" + name + "' does not exist.", - "SceneManager::getMovableObject"); - } - return mi->second; - } - -} -//----------------------------------------------------------------------- -bool SceneManager::hasMovableObject(const String& name, const String& typeName) const -{ - // Nasty hack to make generalised Camera functions work without breaking add-on SMs - if (typeName == MOT_CAMERA) - { - return hasCamera(name); - } - OGRE_LOCK_MUTEX(mMovableObjectCollectionMapMutex); - - MovableObjectCollectionMap::const_iterator i = - mMovableObjectCollectionMap.find(typeName); - if (i == mMovableObjectCollectionMap.end()) - return false; - - { - OGRE_LOCK_MUTEX(i->second->mutex); - return (i->second->map.find(name) != i->second->map.end()); - } -} - -//--------------------------------------------------------------------- -const SceneManager::MovableObjectMap& -SceneManager::getMovableObjects(const String& typeName) -{ - MovableObjectCollection* objectMap = getMovableObjectCollection(typeName); - return objectMap->map; -} -SceneManager::MovableObjectIterator -SceneManager::getMovableObjectIterator(const String& typeName) -{ - MovableObjectCollection* objectMap = getMovableObjectCollection(typeName); - // Iterator not thread safe! Warned in header. - return MovableObjectIterator(objectMap->map.begin(), objectMap->map.end()); -} -//--------------------------------------------------------------------- -void SceneManager::destroyMovableObject(MovableObject* m) -{ - OgreAssert(m, "Cannot destroy a null MovableObject"); - destroyMovableObject(m->getName(), m->getMovableType()); -} -//--------------------------------------------------------------------- -void SceneManager::injectMovableObject(MovableObject* m) -{ - MovableObjectCollection* objectMap = getMovableObjectCollection(m->getMovableType()); - { - OGRE_LOCK_MUTEX(objectMap->mutex); - - objectMap->map[m->getName()] = m; - } -} -//--------------------------------------------------------------------- -void SceneManager::extractMovableObject(const String& name, const String& typeName) -{ - MovableObjectCollection* objectMap = getMovableObjectCollection(typeName); - { - OGRE_LOCK_MUTEX(objectMap->mutex); - MovableObjectMap::iterator mi = objectMap->map.find(name); - if (mi != objectMap->map.end()) - { - // no delete - objectMap->map.erase(mi); - } - } - -} -//--------------------------------------------------------------------- -void SceneManager::extractMovableObject(MovableObject* m) -{ - extractMovableObject(m->getName(), m->getMovableType()); -} -//--------------------------------------------------------------------- -void SceneManager::extractAllMovableObjectsByType(const String& typeName) -{ - MovableObjectCollection* objectMap = getMovableObjectCollection(typeName); - { - OGRE_LOCK_MUTEX(objectMap->mutex); - // no deletion - objectMap->map.clear(); - } -} -//--------------------------------------------------------------------- -void SceneManager::_injectRenderWithPass(Pass *pass, Renderable *rend, bool shadowDerivation, - bool doLightIteration, const LightList* manualLightList) -{ - // render something as if it came from the current queue - const Pass *usedPass = _setPass(pass, shadowDerivation); - renderSingleObject(rend, usedPass, false, doLightIteration, manualLightList); -} -//--------------------------------------------------------------------- -RenderSystem *SceneManager::getDestinationRenderSystem() -{ - return mDestRenderSystem; -} -//--------------------------------------------------------------------- -uint32 SceneManager::_getCombinedVisibilityMask(void) const -{ - return mCurrentViewport ? - mCurrentViewport->getVisibilityMask() & mVisibilityMask : mVisibilityMask; - -} -//--------------------------------------------------------------------- -const VisibleObjectsBoundsInfo& -SceneManager::getVisibleObjectsBoundsInfo(const Camera* cam) const -{ - static VisibleObjectsBoundsInfo nullBox; - - CamVisibleObjectsMap::const_iterator camVisObjIt = mCamVisibleObjectsMap.find( cam ); - - if ( camVisObjIt == mCamVisibleObjectsMap.end() ) - return nullBox; - else - return camVisObjIt->second; -} -const VisibleObjectsBoundsInfo& -SceneManager::getShadowCasterBoundsInfo( const Light* light, size_t iteration ) const -{ - return mShadowRenderer.getShadowCasterBoundsInfo(light, iteration); -} -//--------------------------------------------------------------------- -void SceneManager::setQueuedRenderableVisitor(SceneManager::SceneMgrQueuedRenderableVisitor* visitor) -{ - if (visitor) - mActiveQueuedRenderableVisitor = visitor; - else - mActiveQueuedRenderableVisitor = &mDefaultQueuedRenderableVisitor; -} -//--------------------------------------------------------------------- -void SceneManager::addLodListener(LodListener *listener) -{ - mLodListeners.insert(listener); -} -//--------------------------------------------------------------------- -void SceneManager::removeLodListener(LodListener *listener) -{ - LodListenerSet::iterator it = mLodListeners.find(listener); - if (it != mLodListeners.end()) - mLodListeners.erase(it); -} -//--------------------------------------------------------------------- -void SceneManager::_notifyMovableObjectLodChanged(MovableObjectLodChangedEvent& evt) -{ - // Notify listeners and determine if event needs to be queued - bool queueEvent = false; - for (auto *l : mLodListeners) - { - if (l->prequeueMovableObjectLodChanged(evt)) - queueEvent = true; - } - - // Push event onto queue if requested - if (queueEvent) - mMovableObjectLodChangedEvents.push_back(evt); -} -//--------------------------------------------------------------------- -void SceneManager::_notifyEntityMeshLodChanged(EntityMeshLodChangedEvent& evt) -{ - // Notify listeners and determine if event needs to be queued - bool queueEvent = false; - for (auto *l : mLodListeners) - { - if (l->prequeueEntityMeshLodChanged(evt)) - queueEvent = true; - } - - // Push event onto queue if requested - if (queueEvent) - mEntityMeshLodChangedEvents.push_back(evt); -} -//--------------------------------------------------------------------- -void SceneManager::_notifyEntityMaterialLodChanged(EntityMaterialLodChangedEvent& evt) -{ - // Notify listeners and determine if event needs to be queued - bool queueEvent = false; - for (auto *l : mLodListeners) - { - if (l->prequeueEntityMaterialLodChanged(evt)) - queueEvent = true; - } - - // Push event onto queue if requested - if (queueEvent) - mEntityMaterialLodChangedEvents.push_back(evt); -} -//--------------------------------------------------------------------- -void SceneManager::_handleLodEvents() -{ - // Handle events with each listener - for (auto *l : mLodListeners) - { - for (auto& e : mMovableObjectLodChangedEvents) - l->postqueueMovableObjectLodChanged(e); - - for (auto& e : mEntityMeshLodChangedEvents) - l->postqueueEntityMeshLodChanged(e); - - for (auto& e : mEntityMaterialLodChangedEvents) - l->postqueueEntityMaterialLodChanged(e); - } - - // Clear event queues - mMovableObjectLodChangedEvents.clear(); - mEntityMeshLodChangedEvents.clear(); - mEntityMaterialLodChangedEvents.clear(); -} -//--------------------------------------------------------------------- -void SceneManager::useLights(const LightList* lights, ushort limit) -{ - static LightList NULL_LIGHTS; - lights = lights ? lights : &NULL_LIGHTS; - - auto hash = FastHash((const char*)lights->data(), lights->size() * sizeof(Light*)); - if(hash != mLastLightHash) - { - mLastLightHash = hash; - - // Update any automatic gpu params for lights - // Other bits of information will have to be looked up - mAutoParamDataSource->setCurrentLightList(lights); - mGpuParamsDirty |= GPV_LIGHTS; - } - - mDestRenderSystem->_useLights(std::min(limit, lights->size())); -} -//--------------------------------------------------------------------- -void SceneManager::bindGpuProgram(GpuProgram* prog) -{ - // need to dirty the light hash, and params that need resetting, since program params will have been invalidated - // Use 1 to guarantee changing it (using 0 could result in no change if list is empty) - // Hash == 1 is almost impossible to achieve otherwise - mLastLightHash = 1; - mGpuParamsDirty = (uint16)GPV_ALL; - mDestRenderSystem->bindGpuProgram(prog); -} -//--------------------------------------------------------------------- -void SceneManager::_markGpuParamsDirty(uint16 mask) -{ - mGpuParamsDirty |= mask; -} -//--------------------------------------------------------------------- -void SceneManager::updateGpuProgramParameters(const Pass* pass) -{ - if (!mGpuParamsDirty) - return; - - if (pass->isProgrammable()) - { - pass->_updateAutoParams(mAutoParamDataSource.get(), mGpuParamsDirty); - - for (int i = 0; i < GPT_COMPUTE_PROGRAM; i++) // compute program is bound via RSComputeOperation - { - GpuProgramType t = (GpuProgramType)i; - if (pass->hasGpuProgram(t)) - { - mDestRenderSystem->bindGpuProgramParameters(t, pass->getGpuProgramParameters(t), - mGpuParamsDirty); - } - } - } - - // GLSL and HLSL2 allow FFP state access - if(mFixedFunctionParams) - { - mFixedFunctionParams->_updateAutoParams(mAutoParamDataSource.get(), mGpuParamsDirty); - mDestRenderSystem->applyFixedFunctionParams(mFixedFunctionParams, mGpuParamsDirty); - } - - mGpuParamsDirty = 0; -} -//--------------------------------------------------------------------- -void SceneManager::_issueRenderOp(Renderable* rend, const Pass* pass) -{ - // Finalise GPU parameter bindings - if(pass) - updateGpuProgramParameters(pass); - - if(rend->preRender(this, mDestRenderSystem)) - { - RenderOperation ro; - ro.srcRenderable = rend; - - rend->getRenderOperation(ro); - - injectGlobalInstancingDeclaration(ro, mDestRenderSystem); - - mDestRenderSystem->_render(ro); - } - - rend->postRender(this, mDestRenderSystem); -} -//--------------------------------------------------------------------- -VisibleObjectsBoundsInfo::VisibleObjectsBoundsInfo() -{ - reset(); -} -//--------------------------------------------------------------------- -void VisibleObjectsBoundsInfo::reset() -{ - aabb.setNull(); - receiverAabb.setNull(); - minDistance = minDistanceInFrustum = std::numeric_limits::infinity(); - maxDistance = maxDistanceInFrustum = 0; -} -//--------------------------------------------------------------------- -void VisibleObjectsBoundsInfo::merge(const AxisAlignedBox& boxBounds, const Sphere& sphereBounds, const Camera* cam, bool receiver) -{ - aabb.merge(boxBounds); - if (receiver) - receiverAabb.merge(boxBounds); - // use view matrix to determine distance, works with custom view matrices - Vector3 vsSpherePos = cam->getViewMatrix(true) * sphereBounds.getCenter(); - Real camDistToCenter = vsSpherePos.length(); - minDistance = std::min(minDistance, std::max((Real)0, camDistToCenter - sphereBounds.getRadius())); - maxDistance = std::max(maxDistance, camDistToCenter + sphereBounds.getRadius()); - minDistanceInFrustum = std::min(minDistanceInFrustum, std::max((Real)0, camDistToCenter - sphereBounds.getRadius())); - maxDistanceInFrustum = std::max(maxDistanceInFrustum, camDistToCenter + sphereBounds.getRadius()); -} -//--------------------------------------------------------------------- -void VisibleObjectsBoundsInfo::mergeNonRenderedButInFrustum(const AxisAlignedBox& boxBounds, const Sphere& sphereBounds, const Camera* cam) -{ - (void)boxBounds; - // use view matrix to determine distance, works with custom view matrices - Vector3 vsSpherePos = cam->getViewMatrix(true) * sphereBounds.getCenter(); - Real camDistToCenter = vsSpherePos.length(); - minDistanceInFrustum = std::min(minDistanceInFrustum, std::max((Real)0, camDistToCenter - sphereBounds.getRadius())); - maxDistanceInFrustum = std::max(maxDistanceInFrustum, camDistToCenter + sphereBounds.getRadius()); - -} -//--------------------------------------------------------------------- - -} diff --git a/OgreMain/src/OgreSceneManagerEnumerator.cpp b/OgreMain/src/OgreSceneManagerEnumerator.cpp deleted file mode 100644 index a4ca499a0fb..00000000000 --- a/OgreMain/src/OgreSceneManagerEnumerator.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreSceneManagerEnumerator.h" - - -namespace Ogre { - - //----------------------------------------------------------------------- - template<> SceneManagerEnumerator* Singleton::msSingleton = 0; - SceneManagerEnumerator* SceneManagerEnumerator::getSingletonPtr(void) - { - return msSingleton; - } - SceneManagerEnumerator& SceneManagerEnumerator::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - - //----------------------------------------------------------------------- - SceneManagerEnumerator::SceneManagerEnumerator() - : mInstanceCreateCount(0), mCurrentRenderSystem(0) - { - addFactory(&mDefaultFactory); - - } - //----------------------------------------------------------------------- - SceneManagerEnumerator::~SceneManagerEnumerator() - { - // Destroy all remaining instances - // Really should have shutdown and unregistered by now, but catch here in case - Instances instancesCopy = mInstances; - for (auto& i : instancesCopy) - { - // destroy instances - for(auto& fp : mFactories) - { - if (fp.first == i.second->getTypeName()) - { - fp.second->destroyInstance(i.second); - mInstances.erase(i.first); - break; - } - } - } - mInstances.clear(); - } - //----------------------------------------------------------------------- - void SceneManagerEnumerator::addFactory(SceneManagerFactory* fact) - { - mFactories[fact->getTypeName()] = fact; - // add to metadata - mMetaDataList.push_back(fact->getTypeName()); - // Log - LogManager::getSingleton().logMessage("SceneManagerFactory for type '" + fact->getTypeName() + "' registered."); - } - //----------------------------------------------------------------------- - void SceneManagerEnumerator::removeFactory(SceneManagerFactory* fact) - { - OgreAssert(fact, "Cannot remove a null SceneManagerFactory"); - - // destroy all instances for this factory - for (Instances::iterator i = mInstances.begin(); i != mInstances.end(); ) - { - SceneManager* instance = i->second; - if (instance->getTypeName() == fact->getTypeName()) - { - fact->destroyInstance(instance); - Instances::iterator deli = i++; - mInstances.erase(deli); - } - else - { - ++i; - } - } - // remove from metadata - auto it = std::remove(mMetaDataList.begin(), mMetaDataList.end(), fact->getTypeName()); - mMetaDataList.erase(it, mMetaDataList.end()); - mFactories.erase(fact->getTypeName()); - } - //----------------------------------------------------------------------- - SceneManager* SceneManagerEnumerator::createSceneManager( - const String& typeName, const String& instanceName) - { - if (mInstances.find(instanceName) != mInstances.end()) - { - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "SceneManager instance called '" + instanceName + "' already exists", - "SceneManagerEnumerator::createSceneManager"); - } - - auto it = mFactories.find(typeName); - - if (it == mFactories.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "No factory found for scene manager of type '" + typeName + "'"); - } - - SceneManager* inst = 0; - if (instanceName.empty()) - { - // generate a name - StringStream s; - s << "SceneManagerInstance" << ++mInstanceCreateCount; - inst = it->second->createInstance(s.str()); - } - else - { - inst = it->second->createInstance(instanceName); - } - - /// assign rs if already configured - if (mCurrentRenderSystem) - inst->_setDestinationRenderSystem(mCurrentRenderSystem); - - mInstances[inst->getName()] = inst; - - return inst; - - - } - //----------------------------------------------------------------------- - void SceneManagerEnumerator::destroySceneManager(SceneManager* sm) - { - OgreAssert(sm, "Cannot destroy a null SceneManager"); - - // Erase instance from map - mInstances.erase(sm->getName()); - - // Find factory to destroy - for(auto& fp : mFactories) - { - if (fp.first== sm->getTypeName()) - { - fp.second->destroyInstance(sm); - break; - } - } - } - //----------------------------------------------------------------------- - SceneManager* SceneManagerEnumerator::getSceneManager(const String& instanceName) const - { - Instances::const_iterator i = mInstances.find(instanceName); - if(i != mInstances.end()) - { - return i->second; - } - else - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "SceneManager instance with name '" + instanceName + "' not found.", - "SceneManagerEnumerator::getSceneManager"); - } - - } - //--------------------------------------------------------------------- - bool SceneManagerEnumerator::hasSceneManager(const String& instanceName) const - { - return mInstances.find(instanceName) != mInstances.end(); - } - //----------------------------------------------------------------------- - const SceneManagerEnumerator::Instances& SceneManagerEnumerator::getSceneManagers(void) const - { - return mInstances; - } - //----------------------------------------------------------------------- - void SceneManagerEnumerator::setRenderSystem(RenderSystem* rs) - { - mCurrentRenderSystem = rs; - - for (auto& i : mInstances) - { - i.second->_setDestinationRenderSystem(rs); - } - } - //----------------------------------------------------------------------- - void SceneManagerEnumerator::shutdownAll(void) - { - for (auto& i : mInstances) - { - // shutdown instances (clear scene) - i.second->clearScene(); - } - } - //----------------------------------------------------------------------- - const String SMT_DEFAULT = "DefaultSceneManager"; - //----------------------------------------------------------------------- - SceneManager* DefaultSceneManagerFactory::createInstance( - const String& instanceName) - { - return OGRE_NEW DefaultSceneManager(instanceName); - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - DefaultSceneManager::DefaultSceneManager(const String& name) - : SceneManager(name) - { - } - //----------------------------------------------------------------------- - DefaultSceneManager::~DefaultSceneManager() - { - } - //----------------------------------------------------------------------- - const String& DefaultSceneManager::getTypeName(void) const - { - return SMT_DEFAULT; - } - //----------------------------------------------------------------------- -} diff --git a/OgreMain/src/OgreSceneManagerEnumerator.h b/OgreMain/src/OgreSceneManagerEnumerator.h deleted file mode 100644 index 0029ca51312..00000000000 --- a/OgreMain/src/OgreSceneManagerEnumerator.h +++ /dev/null @@ -1,146 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __SceneManagerEnumerator_H__ -#define __SceneManagerEnumerator_H__ - -#include "OgrePrerequisites.h" - -#include "OgreSceneManager.h" -#include "OgreSingleton.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /// Factory for default scene manager - class DefaultSceneManagerFactory : public SceneManagerFactory - { - public: - DefaultSceneManagerFactory() {} - ~DefaultSceneManagerFactory() {} - SceneManager* createInstance(const String& instanceName) override; - const String& getTypeName(void) const override { return SMT_DEFAULT; } - }; - - /// Default scene manager - class DefaultSceneManager : public SceneManager - { - public: - DefaultSceneManager(const String& name); - ~DefaultSceneManager(); - const String& getTypeName(void) const override; - }; - - /** Enumerates the SceneManager classes available to applications. - - As described in the SceneManager class, SceneManagers are responsible - for organising the scene and issuing rendering commands to the - RenderSystem. Certain scene types can benefit from different - rendering approaches, and it is intended that subclasses will - be created to special case this. - @par - In order to give applications easy access to these implementations, - this class has a number of methods to create or retrieve a SceneManager - which is appropriate to the scene type. - @par - SceneManagers are created by SceneManagerFactory instances. New factories - for new types of SceneManager can be registered with this class to make - them available to clients. - @par - Note that you can still plug in your own custom SceneManager without - using a factory, should you choose, it's just not as flexible that way. - Just instantiate your own SceneManager manually and use it directly. - */ - class SceneManagerEnumerator : public Singleton, public SceneMgtAlloc - { - public: - /// Scene manager instances, indexed by instance name - typedef std::map Instances; - private: - /// Scene manager factories - typedef std::map Factories; - Factories mFactories; - Instances mInstances; - /// Stored separately to allow iteration - StringVector mMetaDataList; - /// Factory for default scene manager - DefaultSceneManagerFactory mDefaultFactory; - /// Count of creations for auto-naming - unsigned long mInstanceCreateCount; - /// Currently assigned render system - RenderSystem* mCurrentRenderSystem; - - - public: - SceneManagerEnumerator(); - ~SceneManagerEnumerator(); - - void addFactory(SceneManagerFactory* fact); - - void removeFactory(SceneManagerFactory* fact); - - const StringVector& getMetaData() const { return mMetaDataList; } - - SceneManager* createSceneManager(const String& typeName, - const String& instanceName = BLANKSTRING); - - void destroySceneManager(SceneManager* sm); - - SceneManager* getSceneManager(const String& instanceName) const; - - bool hasSceneManager(const String& instanceName) const; - - /// Get all the existing SceneManager instances. - const Instances& getSceneManagers() const; - - /** Notifies all SceneManagers of the destination rendering system. - */ - void setRenderSystem(RenderSystem* rs); - - /// Utility method to control shutdown of the managers - void shutdownAll(void); - /// @copydoc Singleton::getSingleton() - static SceneManagerEnumerator& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static SceneManagerEnumerator* getSingletonPtr(void); - - }; - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/src/OgreSceneNode.cpp b/OgreMain/src/OgreSceneNode.cpp deleted file mode 100644 index 423b8c42e4d..00000000000 --- a/OgreMain/src/OgreSceneNode.cpp +++ /dev/null @@ -1,635 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -namespace Ogre { - //----------------------------------------------------------------------- - SceneNode::SceneNode(SceneManager* creator) : SceneNode(creator, BLANKSTRING) - { - } - //----------------------------------------------------------------------- - SceneNode::SceneNode(SceneManager* creator, const String& name) - : Node(name) - , mCreator(creator) - , mAutoTrackTarget(0) - , mGlobalIndex(-1) - , mYawFixed(false) - , mIsInSceneGraph(false) - , mShowBoundingBox(false) - { - needUpdate(); - } - //----------------------------------------------------------------------- - SceneNode::~SceneNode() - { - // Detach all objects, do this manually to avoid needUpdate() call - // which can fail because of deleted items - for (auto & itr : mObjectsByName) - { - itr->_notifyAttached((SceneNode*)0); - } - mObjectsByName.clear(); - } - //----------------------------------------------------------------------- - void SceneNode::_update(bool updateChildren, bool parentHasChanged) - { - Node::_update(updateChildren, parentHasChanged); - _updateBounds(); - } - //----------------------------------------------------------------------- - void SceneNode::setParent(Node* parent) - { - Node::setParent(parent); - - if (parent) - { - SceneNode* sceneParent = static_cast(parent); - setInSceneGraph(sceneParent->isInSceneGraph()); - } - else - { - setInSceneGraph(false); - } - } - //----------------------------------------------------------------------- - void SceneNode::setInSceneGraph(bool inGraph) - { - if (inGraph != mIsInSceneGraph) - { - mIsInSceneGraph = inGraph; - // Tell children - for (auto child : getChildren()) - { - SceneNode* sceneChild = static_cast(child); - sceneChild->setInSceneGraph(inGraph); - } - } - } - //----------------------------------------------------------------------- - struct MovableObjectNameExists { - const String& name; - bool operator()(const MovableObject* mo) { - return mo->getName() == name; - } - }; - void SceneNode::attachObject(MovableObject* obj) - { - OgreAssert(!obj->isAttached(), "Object already attached to a SceneNode or a Bone"); - - obj->_notifyAttached(this); - - // Also add to name index - MovableObjectNameExists pred = {obj->getName()}; - ObjectMap::iterator it = std::find_if(mObjectsByName.begin(), mObjectsByName.end(), pred); - if (it != mObjectsByName.end()) - OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, - "An object named '" + obj->getName() + "' already attached to this SceneNode"); - mObjectsByName.push_back(obj); - - // Make sure bounds get updated (must go right to the top) - needUpdate(); - } - //----------------------------------------------------------------------- - MovableObject* SceneNode::getAttachedObject(const String& name) const - { - // Look up - MovableObjectNameExists pred = {name}; - auto i = std::find_if(mObjectsByName.begin(), mObjectsByName.end(), pred); - - if (i == mObjectsByName.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Attached object " + - name + " not found.", "SceneNode::getAttachedObject"); - } - - return *i; - } - //----------------------------------------------------------------------- - MovableObject* SceneNode::detachObject(unsigned short index) - { - OgreAssert(index < mObjectsByName.size(), "out of bounds"); - ObjectMap::iterator i = mObjectsByName.begin(); - i += index; - - MovableObject* ret = *i; - std::swap(*i, mObjectsByName.back()); - mObjectsByName.pop_back(); - - ret->_notifyAttached((SceneNode*)0); - - // Make sure bounds get updated (must go right to the top) - needUpdate(); - - return ret; - } - //----------------------------------------------------------------------- - MovableObject* SceneNode::detachObject(const String& name) - { - MovableObjectNameExists pred = {name}; - ObjectMap::iterator it = std::find_if(mObjectsByName.begin(), mObjectsByName.end(), pred); - - if (it == mObjectsByName.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Object " + name + " is not attached " - "to this node.", "SceneNode::detachObject"); - } - - MovableObject* ret = *it; - std::swap(*it, mObjectsByName.back()); - mObjectsByName.pop_back(); - - ret->_notifyAttached((SceneNode*)0); - // Make sure bounds get updated (must go right to the top) - needUpdate(); - - return ret; - - } - //----------------------------------------------------------------------- - void SceneNode::detachObject(MovableObject* obj) - { - auto it = std::find(mObjectsByName.begin(), mObjectsByName.end(), obj); - OgreAssert(it != mObjectsByName.end(), "Object is not attached to this node"); - std::swap(*it, mObjectsByName.back()); - mObjectsByName.pop_back(); - obj->_notifyAttached((SceneNode*)0); - - // Make sure bounds get updated (must go right to the top) - needUpdate(); - } - //----------------------------------------------------------------------- - void SceneNode::detachAllObjects(void) - { - for (auto & itr : mObjectsByName) - { - itr->_notifyAttached((SceneNode*)0); - } - mObjectsByName.clear(); - // Make sure bounds get updated (must go right to the top) - needUpdate(); - } - //----------------------------------------------------------------------- - void SceneNode::destroyAllObjects(void) - { - while (!getAttachedObjects().empty()) { - auto obj = getAttachedObjects().front(); - getCreator()->destroyMovableObject(obj); - } - needUpdate(); - } - //----------------------------------------------------------------------- - void SceneNode::_updateBounds(void) - { - // Reset bounds first - mWorldAABB.setNull(); - - // Update bounds from own attached objects - for (auto *o : mObjectsByName) - { - // Merge world bounds of each object - mWorldAABB.merge(o->getWorldBoundingBox(true)); - } - - // Merge with children - for (auto child : getChildren()) - { - SceneNode* sceneChild = static_cast(child); - mWorldAABB.merge(sceneChild->mWorldAABB); - } - - } - //----------------------------------------------------------------------- - void SceneNode::_findVisibleObjects(Camera* cam, RenderQueue* queue, - VisibleObjectsBoundsInfo* visibleBounds, bool includeChildren, - bool displayNodes, bool onlyShadowCasters) - { - // Check self visible - if (!cam->isVisible(mWorldAABB)) - return; - - // Add all entities - for (auto *o : mObjectsByName) - { - queue->processVisibleObject(o, cam, onlyShadowCasters, visibleBounds); - } - - if (includeChildren) - { - for (auto child : getChildren()) - { - SceneNode* sceneChild = static_cast(child); - sceneChild->_findVisibleObjects(cam, queue, visibleBounds, includeChildren, - displayNodes, onlyShadowCasters); - } - } - - if (mCreator && mCreator->getDebugDrawer()) - { - mCreator->getDebugDrawer()->drawSceneNode(this); - } - } - - SceneNode::ObjectIterator SceneNode::getAttachedObjectIterator(void) { - return ObjectIterator(mObjectsByName.begin(), mObjectsByName.end()); - } - SceneNode::ConstObjectIterator SceneNode::getAttachedObjectIterator(void) const { - return ConstObjectIterator(mObjectsByName.begin(), mObjectsByName.end()); - } - - //----------------------------------------------------------------------- - void SceneNode::updateFromParentImpl(void) const - { - Node::updateFromParentImpl(); - - // Notify objects that it has been moved - for (auto o : mObjectsByName) - { - o->_notifyMoved(); - } - } - //----------------------------------------------------------------------- - Node* SceneNode::createChildImpl(void) - { - assert(mCreator); - return mCreator->createSceneNode(); - } - //----------------------------------------------------------------------- - Node* SceneNode::createChildImpl(const String& name) - { - assert(mCreator); - return mCreator->createSceneNode(name); - } - //----------------------------------------------------------------------- - void SceneNode::removeAndDestroyChild(const String& name) - { - SceneNode* pChild = static_cast(removeChild(name)); - pChild->removeAndDestroyAllChildren(); - - pChild->getCreator()->destroySceneNode(name); - - } - //----------------------------------------------------------------------- - void SceneNode::removeAndDestroyChild(unsigned short index) - { - SceneNode* pChild = static_cast(removeChild(index)); - pChild->removeAndDestroyAllChildren(); - - pChild->getCreator()->destroySceneNode(pChild); - } - //----------------------------------------------------------------------- - void SceneNode::removeAndDestroyChild(SceneNode* child) - { - auto it = std::find(getChildren().begin(), getChildren().end(), child); - OgreAssert(it != getChildren().end(), "Not a child of this SceneNode"); - removeAndDestroyChild(it - getChildren().begin()); - } - //----------------------------------------------------------------------- - void SceneNode::removeAndDestroyAllChildren(void) - { - // do not store iterators (invalidated by - // SceneManager::destroySceneNode because it causes removal from parent) - while(!getChildren().empty()) { - SceneNode* sn = static_cast(getChildren().front()); - sn->removeAndDestroyAllChildren(); - sn->getCreator()->destroySceneNode(sn); - } - - mChildren.clear(); - needUpdate(); - } - //----------------------------------------------------------------------- - void SceneNode::destroyChildAndObjects(const String& name) { - SceneNode* pChild = static_cast(getChild(name)); - pChild->destroyAllChildrenAndObjects(); - - removeChild(name); - pChild->getCreator()->destroySceneNode(name); - - } - - void SceneNode::destroyChildAndObjects(unsigned short index) { - SceneNode* pChild = static_cast(removeChild(index)); - pChild->destroyAllChildrenAndObjects(); - - pChild->getCreator()->destroySceneNode(pChild); - } - - void SceneNode::destroyChildAndObjects(SceneNode * child) - { - auto it = std::find(getChildren().begin(), getChildren().end(), child); - OgreAssert(it != getChildren().end(), "Not a child of this SceneNode"); - destroyChildAndObjects(it - getChildren().begin()); - } - - void SceneNode::destroyAllChildrenAndObjects() - { - //remove objects directly attached to this node - destroyAllObjects(); - - //go over children - while(!getChildren().empty()) { - SceneNode* child = static_cast(getChildren().front()); - //recurse - child->destroyAllChildrenAndObjects(); - - //destroy child - child->getCreator()->destroySceneNode(child); - } - mChildren.clear(); - needUpdate(); - } - //----------------------------------------------------------------------- - void SceneNode::loadChildren(const String& filename) - { - String baseName, strExt; - StringUtil::splitBaseFilename(filename, baseName, strExt); - auto codec = Codec::getCodec(strExt); - if (!codec) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "No codec found to load " + filename); - - auto stream = Root::openFileStream( - filename, ResourceGroupManager::getSingleton().getWorldResourceGroupName()); - codec->decode(stream, this); - } - void SceneNode::saveChildren(const String& filename) - { - String baseName, strExt; - StringUtil::splitBaseFilename(filename, baseName, strExt); - auto codec = Codec::getCodec(strExt); - codec->encodeToFile(this, filename); - } - //----------------------------------------------------------------------- - SceneNode* SceneNode::createChildSceneNode(const Vector3& inTranslate, - const Quaternion& inRotate) - { - return static_cast(this->createChild(inTranslate, inRotate)); - } - //----------------------------------------------------------------------- - SceneNode* SceneNode::createChildSceneNode(const String& name, const Vector3& inTranslate, - const Quaternion& inRotate) - { - return static_cast(this->createChild(name, inTranslate, inRotate)); - } - //----------------------------------------------------------------------- - void SceneNode::findLights(LightList& destList, Real radius, uint32 lightMask) const - { - // No any optimisation here, hope inherits more smart for that. - // - // If a scene node is static and lights have moved, light list won't change - // can't use a simple global boolean flag since this is only called for - // visible nodes, so temporarily visible nodes will not be updated - // Since this is only called for visible nodes, skip the check for now - // - if (mCreator) - { - // Use SceneManager to calculate - mCreator->_populateLightList(this, radius, destList, lightMask); - } - else - { - destList.clear(); - } - } - //----------------------------------------------------------------------- - void SceneNode::setAutoTracking(bool enabled, SceneNode* const target, - const Vector3& localDirectionVector, - const Vector3& offset) - { - if (enabled) - { - mAutoTrackTarget = target; - mAutoTrackOffset = offset; - mAutoTrackLocalDirection = localDirectionVector; - } - else - { - mAutoTrackTarget = 0; - } - if (mCreator) - mCreator->_notifyAutotrackingSceneNode(this, enabled); - } - //----------------------------------------------------------------------- - void SceneNode::setFixedYawAxis(bool useFixed, const Vector3& fixedAxis) - { - mYawFixed = useFixed; - mYawFixedAxis = fixedAxis; - } - - //----------------------------------------------------------------------- - void SceneNode::yaw(const Radian& angle, TransformSpace relativeTo) - { - if (mYawFixed) - { - rotate(mYawFixedAxis, angle, relativeTo); - } - else - { - rotate(Vector3::UNIT_Y, angle, relativeTo); - } - - } - //----------------------------------------------------------------------- - void SceneNode::setDirection(Real x, Real y, Real z, TransformSpace relativeTo, - const Vector3& localDirectionVector) - { - setDirection(Vector3(x,y,z), relativeTo, localDirectionVector); - } - - //----------------------------------------------------------------------- - void SceneNode::setDirection(const Vector3& vec, TransformSpace relativeTo, - const Vector3& localDirectionVector) - { - // Do nothing if given a zero vector - if (vec == Vector3::ZERO) return; - - // The direction we want the local direction point to - Vector3 targetDir = vec.normalisedCopy(); - - // Transform target direction to world space - switch (relativeTo) - { - case TS_PARENT: - if (getInheritOrientation()) - { - if (getParent()) - { - targetDir = getParent()->_getDerivedOrientation() * targetDir; - } - } - break; - case TS_LOCAL: - targetDir = _getDerivedOrientation() * targetDir; - break; - case TS_WORLD: - // default orientation - break; - } - - // Calculate target orientation relative to world space - Quaternion targetOrientation; - if( mYawFixed ) - { - // Calculate the quaternion for rotate local Z to target direction - Vector3 yawAxis = mYawFixedAxis; - - if (getInheritOrientation() && getParent()) - { - yawAxis = getParent()->_getDerivedOrientation() * yawAxis; - } - - Quaternion unitZToTarget = Math::lookRotation(targetDir, yawAxis); - - if (localDirectionVector == Vector3::NEGATIVE_UNIT_Z) - { - // Specail case for avoid calculate 180 degree turn - targetOrientation = - Quaternion(-unitZToTarget.y, -unitZToTarget.z, unitZToTarget.w, unitZToTarget.x); - } - else - { - // Calculate the quaternion for rotate local direction to target direction - Quaternion localToUnitZ = localDirectionVector.getRotationTo(Vector3::UNIT_Z); - targetOrientation = unitZToTarget * localToUnitZ; - } - } - else - { - const Quaternion& currentOrient = _getDerivedOrientation(); - - // Get current local direction relative to world space - Vector3 currentDir = currentOrient * localDirectionVector; - - if ((currentDir+targetDir).squaredLength() < 0.00005f) - { - // Oops, a 180 degree turn (infinite possible rotation axes) - // Default to yaw i.e. use current UP - targetOrientation = - Quaternion(-currentOrient.y, -currentOrient.z, currentOrient.w, currentOrient.x); - } - else - { - // Derive shortest arc to new direction - Quaternion rotQuat = currentDir.getRotationTo(targetDir); - targetOrientation = rotQuat * currentOrient; - } - } - - // Set target orientation, transformed to parent space - if (getParent() && getInheritOrientation()) - setOrientation(getParent()->_getDerivedOrientation().UnitInverse() * targetOrientation); - else - setOrientation(targetOrientation); - } - //----------------------------------------------------------------------- - void SceneNode::lookAt( const Vector3& targetPoint, TransformSpace relativeTo, - const Vector3& localDirectionVector) - { - // Calculate ourself origin relative to the given transform space - Vector3 origin; - switch (relativeTo) - { - default: // Just in case - case TS_WORLD: - origin = _getDerivedPosition(); - break; - case TS_PARENT: - origin = getPosition(); - break; - case TS_LOCAL: - origin = Vector3::ZERO; - break; - } - - setDirection(targetPoint - origin, relativeTo, localDirectionVector); - } - //----------------------------------------------------------------------- - void SceneNode::_autoTrack(void) - { - // NB assumes that all scene nodes have been updated - if (mAutoTrackTarget) - { - lookAt(mAutoTrackTarget->_getDerivedPosition() + mAutoTrackOffset, - TS_WORLD, mAutoTrackLocalDirection); - // update self & children - _update(true, true); - } - } - //----------------------------------------------------------------------- - SceneNode* SceneNode::getParentSceneNode(void) const - { - return static_cast(getParent()); - } - //----------------------------------------------------------------------- - void SceneNode::setVisible(bool visible, bool cascade) const - { - for (auto o : mObjectsByName) - { - o->setVisible(visible); - } - - if (cascade) - { - for (auto c : getChildren()) - { - static_cast(c)->setVisible(visible, cascade); - } - } - } - //----------------------------------------------------------------------- - void SceneNode::setDebugDisplayEnabled(bool enabled, bool cascade) const - { - for (auto o : mObjectsByName) - { - o->setDebugDisplayEnabled(enabled); - } - - if (cascade) - { - for (auto c : getChildren()) - { - static_cast(c)->setDebugDisplayEnabled(enabled, cascade); - } - } - } - //----------------------------------------------------------------------- - void SceneNode::flipVisibility(bool cascade) const - { - for (auto o : mObjectsByName) - { - o->setVisible(!o->getVisible()); - } - - if (cascade) - { - for (auto c : getChildren()) - { - static_cast(c)->flipVisibility(cascade); - } - } - } -} diff --git a/OgreMain/src/OgreSceneQuery.cpp b/OgreMain/src/OgreSceneQuery.cpp deleted file mode 100644 index a5d4c90a481..00000000000 --- a/OgreMain/src/OgreSceneQuery.cpp +++ /dev/null @@ -1,331 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreSceneQuery.h" - -namespace Ogre { - - //----------------------------------------------------------------------- - SceneQuery::SceneQuery(SceneManager* mgr) - : mParentSceneMgr(mgr), mQueryMask(0xFFFFFFFF) - { - // default type mask to everything except lights & fx (previous behaviour) - mQueryTypeMask = (0xFFFFFFFF & ~SceneManager::FX_TYPE_MASK) - & ~SceneManager::LIGHT_TYPE_MASK; - - } - //----------------------------------------------------------------------- - SceneQuery::~SceneQuery() - { - } - //----------------------------------------------------------------------- - void SceneQuery::setQueryMask(uint32 mask) - { - mQueryMask = mask; - } - //----------------------------------------------------------------------- - uint32 SceneQuery::getQueryMask(void) const - { - return mQueryMask; - } - //----------------------------------------------------------------------- - void SceneQuery::setQueryTypeMask(uint32 mask) - { - mQueryTypeMask = mask; - } - //----------------------------------------------------------------------- - uint32 SceneQuery::getQueryTypeMask(void) const - { - return mQueryTypeMask; - } - //----------------------------------------------------------------------- - RegionSceneQuery::RegionSceneQuery(SceneManager* mgr) - :SceneQuery(mgr) - { - } - //----------------------------------------------------------------------- - RegionSceneQuery::~RegionSceneQuery() - { - clearResults(); - } - //----------------------------------------------------------------------- - const SceneQueryResult& RegionSceneQuery::getLastResults(void) const - { - return mLastResult; - } - //----------------------------------------------------------------------- - void RegionSceneQuery::clearResults(void) - { - mLastResult.movables.clear(); - mLastResult.worldFragments.clear(); - } - //--------------------------------------------------------------------- - SceneQueryResult& - RegionSceneQuery::execute(void) - { - clearResults(); - // Call callback version with self as listener - execute(this); - return mLastResult; - } - //--------------------------------------------------------------------- - bool RegionSceneQuery:: - queryResult(MovableObject* obj) - { - // Add to internal list - mLastResult.movables.push_back(obj); - // Continue - return true; - } - //--------------------------------------------------------------------- - bool RegionSceneQuery::queryResult(SceneQuery::WorldFragment* fragment) - { - // Add to internal list - mLastResult.worldFragments.push_back(fragment); - // Continue - return true; - } - //----------------------------------------------------------------------- - AxisAlignedBoxSceneQuery::AxisAlignedBoxSceneQuery(SceneManager* mgr) - : RegionSceneQuery(mgr) - { - } - //----------------------------------------------------------------------- - AxisAlignedBoxSceneQuery::~AxisAlignedBoxSceneQuery() - { - } - //----------------------------------------------------------------------- - void AxisAlignedBoxSceneQuery::setBox(const AxisAlignedBox& box) - { - mAABB = box; - } - //----------------------------------------------------------------------- - const AxisAlignedBox& AxisAlignedBoxSceneQuery::getBox(void) const - { - return mAABB; - } - //----------------------------------------------------------------------- - SphereSceneQuery::SphereSceneQuery(SceneManager* mgr) - : RegionSceneQuery(mgr) - { - } - //----------------------------------------------------------------------- - SphereSceneQuery::~SphereSceneQuery() - { - } - //----------------------------------------------------------------------- - void SphereSceneQuery::setSphere(const Sphere& sphere) - { - mSphere = sphere; - } - //----------------------------------------------------------------------- - const Sphere& SphereSceneQuery::getSphere() const - { - return mSphere; - } - - //----------------------------------------------------------------------- - PlaneBoundedVolumeListSceneQuery::PlaneBoundedVolumeListSceneQuery(SceneManager* mgr) - : RegionSceneQuery(mgr) - { - } - //----------------------------------------------------------------------- - PlaneBoundedVolumeListSceneQuery::~PlaneBoundedVolumeListSceneQuery() - { - } - //----------------------------------------------------------------------- - void PlaneBoundedVolumeListSceneQuery::setVolumes(const PlaneBoundedVolumeList& volumes) - { - mVolumes = volumes; - } - //----------------------------------------------------------------------- - const PlaneBoundedVolumeList& PlaneBoundedVolumeListSceneQuery::getVolumes() const - { - return mVolumes; - } - - //----------------------------------------------------------------------- - RaySceneQuery::RaySceneQuery(SceneManager* mgr) : SceneQuery(mgr) - { - mSortByDistance = false; - mMaxResults = 0; - } - //----------------------------------------------------------------------- - RaySceneQuery::~RaySceneQuery() - { - } - //----------------------------------------------------------------------- - void RaySceneQuery::setRay(const Ray& ray) - { - mRay = ray; - } - //----------------------------------------------------------------------- - const Ray& RaySceneQuery::getRay(void) const - { - return mRay; - } - //----------------------------------------------------------------------- - void RaySceneQuery::setSortByDistance(bool sort, ushort maxresults) - { - mSortByDistance = sort; - mMaxResults = maxresults; - } - //----------------------------------------------------------------------- - bool RaySceneQuery::getSortByDistance(void) const - { - return mSortByDistance; - } - //----------------------------------------------------------------------- - ushort RaySceneQuery::getMaxResults(void) const - { - return mMaxResults; - } - //----------------------------------------------------------------------- - RaySceneQueryResult& RaySceneQuery::execute(void) - { - // Clear without freeing the vector buffer - mResult.clear(); - - // Call callback version with self as listener - this->execute(this); - - if (mSortByDistance) - { - if (mMaxResults != 0 && mMaxResults < mResult.size()) - { - // Partially sort the N smallest elements, discard others - std::partial_sort(mResult.begin(), mResult.begin()+mMaxResults, mResult.end()); - mResult.resize(mMaxResults); - } - else - { - // Sort entire result array - std::sort(mResult.begin(), mResult.end()); - } - } - - return mResult; - } - //----------------------------------------------------------------------- - const RaySceneQueryResult& RaySceneQuery::getLastResults(void) const - { - return mResult; - } - //----------------------------------------------------------------------- - void RaySceneQuery::clearResults(void) - { - // C++ idiom to free vector buffer: swap with empty vector - RaySceneQueryResult().swap(mResult); - } - //----------------------------------------------------------------------- - bool RaySceneQuery::queryResult(MovableObject* obj, Real distance) - { - // Add to internal list - RaySceneQueryResultEntry dets; - dets.distance = distance; - dets.movable = obj; - dets.worldFragment = NULL; - mResult.push_back(dets); - // Continue - return true; - } - //----------------------------------------------------------------------- - bool RaySceneQuery::queryResult(SceneQuery::WorldFragment* fragment, Real distance) - { - // Add to internal list - RaySceneQueryResultEntry dets; - dets.distance = distance; - dets.movable = NULL; - dets.worldFragment = fragment; - mResult.push_back(dets); - // Continue - return true; - } - //----------------------------------------------------------------------- - IntersectionSceneQuery::IntersectionSceneQuery(SceneManager* mgr) - : SceneQuery(mgr), mLastResult(NULL) - { - } - //----------------------------------------------------------------------- - IntersectionSceneQuery::~IntersectionSceneQuery() - { - clearResults(); - } - //----------------------------------------------------------------------- - IntersectionSceneQueryResult& IntersectionSceneQuery::getLastResults(void) const - { - assert(mLastResult); - return *mLastResult; - } - //----------------------------------------------------------------------- - void IntersectionSceneQuery::clearResults(void) - { - OGRE_DELETE mLastResult; - mLastResult = NULL; - } - //--------------------------------------------------------------------- - IntersectionSceneQueryResult& - IntersectionSceneQuery::execute(void) - { - clearResults(); - mLastResult = OGRE_NEW IntersectionSceneQueryResult(); - // Call callback version with self as listener - execute(this); - return *mLastResult; - } - //--------------------------------------------------------------------- - bool IntersectionSceneQuery:: - queryResult(MovableObject* first, MovableObject* second) - { - // Add to internal list - mLastResult->movables2movables.push_back( - SceneQueryMovableObjectPair(first, second) - ); - // Continue - return true; - } - //--------------------------------------------------------------------- - bool IntersectionSceneQuery:: - queryResult(MovableObject* movable, SceneQuery::WorldFragment* fragment) - { - // Add to internal list - mLastResult->movables2world.push_back( - SceneQueryMovableObjectWorldFragmentPair(movable, fragment) - ); - // Continue - return true; - } - - - - -} - - - - diff --git a/OgreMain/src/OgreScriptCompiler.cpp b/OgreMain/src/OgreScriptCompiler.cpp deleted file mode 100644 index 7e679d47dcf..00000000000 --- a/OgreMain/src/OgreScriptCompiler.cpp +++ /dev/null @@ -1,1631 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" -#include "OgreScriptParser.h" -#include "OgreBuiltinScriptTranslators.h" -#include "OgreComponents.h" - -#define DEBUG_AST 0 - -namespace Ogre -{ - // AbstractNode - AbstractNode::AbstractNode(AbstractNode *ptr) - :line(0), type(ANT_UNKNOWN), parent(ptr) - {} - - // AtomAbstractNode - AtomAbstractNode::AtomAbstractNode(AbstractNode *ptr) - :AbstractNode(ptr), id(0) - { - type = ANT_ATOM; - } - - AbstractNode *AtomAbstractNode::clone() const - { - AtomAbstractNode *node = OGRE_NEW AtomAbstractNode(parent); - node->file = file; - node->line = line; - node->id = id; - node->type = type; - node->value = value; - return node; - } - - // ObjectAbstractNode - ObjectAbstractNode::ObjectAbstractNode(AbstractNode *ptr) - :AbstractNode(ptr), id(0), abstract(false) - { - type = ANT_OBJECT; - } - - AbstractNode *ObjectAbstractNode::clone() const - { - ObjectAbstractNode *node = OGRE_NEW ObjectAbstractNode(parent); - node->file = file; - node->line = line; - node->type = type; - node->name = name; - node->cls = cls; - node->id = id; - node->abstract = abstract; - for(const auto & i : children) - { - AbstractNodePtr newNode = AbstractNodePtr(i->clone()); - newNode->parent = node; - node->children.push_back(newNode); - } - for(const auto & value : values) - { - AbstractNodePtr newNode = AbstractNodePtr(value->clone()); - newNode->parent = node; - node->values.push_back(newNode); - } - node->mEnv = mEnv; - return node; - } - - void ObjectAbstractNode::addVariable(const Ogre::String &inName) - { - mEnv.insert(std::make_pair(inName, "")); - } - - void ObjectAbstractNode::setVariable(const Ogre::String &inName, const Ogre::String &value) - { - mEnv[inName] = value; - } - - std::pair ObjectAbstractNode::getVariable(const String &inName) const - { - std::map::const_iterator i = mEnv.find(inName); - if(i != mEnv.end()) - return std::make_pair(true, i->second); - - ObjectAbstractNode *parentNode = (ObjectAbstractNode*)this->parent; - while(parentNode) - { - i = parentNode->mEnv.find(inName); - if(i != parentNode->mEnv.end()) - return std::make_pair(true, i->second); - parentNode = (ObjectAbstractNode*)parentNode->parent; - } - return std::make_pair(false, ""); - } - - const std::map &ObjectAbstractNode::getVariables() const - { - return mEnv; - } - - // PropertyAbstractNode - PropertyAbstractNode::PropertyAbstractNode(AbstractNode *ptr) - :AbstractNode(ptr), id(0) - { - type = ANT_PROPERTY; - } - - AbstractNode *PropertyAbstractNode::clone() const - { - PropertyAbstractNode *node = OGRE_NEW PropertyAbstractNode(parent); - node->file = file; - node->line = line; - node->type = type; - node->name = name; - node->id = id; - for(const auto & value : values) - { - AbstractNodePtr newNode = AbstractNodePtr(value->clone()); - newNode->parent = node; - node->values.push_back(newNode); - } - return node; - } - - // ImportAbstractNode - ImportAbstractNode::ImportAbstractNode() - :AbstractNode(0) - { - type = ANT_IMPORT; - } - - AbstractNode *ImportAbstractNode::clone() const - { - ImportAbstractNode *node = OGRE_NEW ImportAbstractNode(); - node->file = file; - node->line = line; - node->type = type; - node->target = target; - node->source = source; - return node; - } - - // VariableAccessAbstractNode - VariableAccessAbstractNode::VariableAccessAbstractNode(AbstractNode *ptr) - :AbstractNode(ptr) - { - type = ANT_VARIABLE_ACCESS; - } - - AbstractNode *VariableAccessAbstractNode::clone() const - { - VariableAccessAbstractNode *node = OGRE_NEW VariableAccessAbstractNode(parent); - node->file = file; - node->line = line; - node->type = type; - node->name = name; - return node; - } - - // ScriptCompilerListener - ScriptCompilerListener::ScriptCompilerListener() - { - } - - ConcreteNodeListPtr ScriptCompilerListener::importFile(ScriptCompiler *compiler, const String &name) - { - return ConcreteNodeListPtr(); - } - - void ScriptCompilerListener::preConversion(ScriptCompiler *compiler, ConcreteNodeListPtr nodes) - { - - } - - bool ScriptCompilerListener::postConversion(ScriptCompiler *compiler, const AbstractNodeListPtr &nodes) - { - return true; - } - - void ScriptCompilerListener::handleError(ScriptCompiler *compiler, uint32 code, const String &file, int line, const String &msg) - { - StringStream ss; - ss << "ScriptCompiler - " << ScriptCompiler::formatErrorCode(code) << " in " << file << "(" << line << ")"; - if(!msg.empty()) - ss << ": " << msg; - - if(code == ScriptCompiler::CE_DEPRECATEDSYMBOL) - LogManager::getSingleton().logWarning(ss.str()); - else - LogManager::getSingleton().logError(ss.str()); - } - - bool ScriptCompilerListener::handleEvent(ScriptCompiler *compiler, ScriptCompilerEvent *evt, void *retval) - { - return false; - } - - // ScriptCompiler - String ScriptCompiler::formatErrorCode(uint32 code) - { - switch(code) - { - case CE_STRINGEXPECTED: - return "string expected"; - case CE_NUMBEREXPECTED: - return "number expected"; - case CE_FEWERPARAMETERSEXPECTED: - return "fewer parameters expected"; - case CE_VARIABLEEXPECTED: - return "variable expected"; - case CE_UNDEFINEDVARIABLE: - return "undefined variable"; - case CE_OBJECTNAMEEXPECTED: - return "object name expected"; - case CE_OBJECTALLOCATIONERROR: - return "no object created"; - case CE_OBJECTBASENOTFOUND: - return "base object not found"; - case CE_INVALIDPARAMETERS: - return "invalid parameters"; - case CE_DUPLICATEOVERRIDE: - return "duplicate object override"; - case CE_REFERENCETOANONEXISTINGOBJECT: - return "reference to a non existing object"; - case CE_UNEXPECTEDTOKEN: - return "unexpected token"; - case CE_DEPRECATEDSYMBOL: - return "deprecated symbol"; - default: - return "unknown error"; - } - } - - ScriptCompiler::ScriptCompiler() - :mListener(0) - { - initWordMap(); - } - - bool ScriptCompiler::compile(const String &str, const String &source, const String &group) - { - ConcreteNodeListPtr nodes = ScriptParser::parse(ScriptLexer::tokenize(str, source), source); - return compile(nodes, group); - } - -#if DEBUG_AST - static void logAST(int tabs, const AbstractNodePtr &node) - { - String msg = ""; - for(int i = 0; i < tabs; ++i) - msg += "\t"; - - switch(node->type) - { - case ANT_ATOM: - { - AtomAbstractNode *atom = static_cast(node.get()); - msg = msg + atom->value; - } - break; - case ANT_PROPERTY: - { - PropertyAbstractNode *prop = static_cast(node.get()); - msg = msg + prop->name + " ="; - for(AbstractNodeList::iterator i = prop->values.begin(); i != prop->values.end(); ++i) - { - if((*i)->type == ANT_ATOM) - msg = msg + " " + static_cast((*i).get())->value; - } - } - break; - case ANT_OBJECT: - { - ObjectAbstractNode *obj = static_cast(node.get()); - msg = msg + node->file + " - " + StringConverter::toString(node->line) + " - " + obj->cls + " \"" + obj->name + "\" ="; - for(AbstractNodeList::iterator i = obj->values.begin(); i != obj->values.end(); ++i) - { - if((*i)->type == ANT_ATOM) - msg = msg + " " + static_cast((*i).get())->value; - } - } - break; - default: - msg = msg + "Unacceptable node type: " + StringConverter::toString(node->type); - } - - LogManager::getSingleton().logMessage(msg); - - if(node->type == ANT_OBJECT) - { - ObjectAbstractNode *obj = static_cast(node.get()); - for(AbstractNodeList::iterator i = obj->children.begin(); i != obj->children.end(); ++i) - { - logAST(tabs + 1, *i); - } - } - } -#endif - - bool ScriptCompiler::compile(const ConcreteNodeListPtr &nodes, const String &group) - { - // Set up the compilation context - mGroup = group; - - // Clear the past errors - mErrors.clear(); - - // Clear the environment - mEnv.clear(); - - if(mListener) - mListener->preConversion(this, nodes); - - // Convert our nodes to an AST - AbstractNodeListPtr ast = convertToAST(*nodes); - // Processes the imports for this script - processImports(*ast); - // Process object inheritance - processObjects(*ast, *ast); - // Process variable expansion - processVariables(*ast); - - // Allows early bail-out through the listener - if(mListener && !mListener->postConversion(this, ast)) - return mErrors.empty(); - - // Translate the nodes - for(auto & i : *ast) - { -#if DEBUG_AST - logAST(0, *i); -#endif - if(i->type == ANT_OBJECT && static_cast(i.get())->abstract) - continue; - //LogManager::getSingleton().logMessage(static_cast((*i).get())->name); - ScriptTranslator *translator = ScriptCompilerManager::getSingleton().getTranslator(i); - if(translator) - translator->translate(this, i); - } - - mImports.clear(); - mImportRequests.clear(); - mImportTable.clear(); - - return mErrors.empty(); - } - - void ScriptCompiler::addError(uint32 code, const Ogre::String &file, int line, const String &msg) - { - if(mListener) - { - mListener->handleError(this, code, file, line, msg); - } - else - { - static ScriptCompilerListener defaultListener; - defaultListener.handleError(this, code, file, line, msg); - } - - mErrors.push_back({file, msg, line, code}); - } - - void ScriptCompiler::setListener(ScriptCompilerListener *listener) - { - mListener = listener; - } - - ScriptCompilerListener *ScriptCompiler::getListener() - { - return mListener; - } - - const String &ScriptCompiler::getResourceGroup() const - { - return mGroup; - } - - bool ScriptCompiler::_fireEvent(ScriptCompilerEvent *evt, void *retval) - { - if(mListener) - return mListener->handleEvent(this, evt, retval); - return false; - } - - AbstractNodeListPtr ScriptCompiler::convertToAST(const ConcreteNodeList &nodes) - { - AbstractTreeBuilder builder(this); - AbstractTreeBuilder::visit(&builder, nodes); - return builder.getResult(); - } - - void ScriptCompiler::processImports(AbstractNodeList &nodes) - { - // We only need to iterate over the top-level of nodes - AbstractNodeList::iterator i = nodes.begin(); - while(i != nodes.end()) - { - // We move to the next node here and save the current one. - // If any replacement happens, then we are still assured that - // i points to the node *after* the replaced nodes, no matter - // how many insertions and deletions may happen - AbstractNodeList::iterator cur = i++; - if((*cur)->type == ANT_IMPORT) - { - ImportAbstractNode *import = (ImportAbstractNode*)(*cur).get(); - // Only process if the file's contents haven't been loaded - if(mImports.find(import->source) == mImports.end()) - { - // Load the script - AbstractNodeListPtr importedNodes = loadImportPath(import->source); - if(importedNodes && !importedNodes->empty()) - { - processImports(*importedNodes); - processObjects(*importedNodes, *importedNodes); - } - else - { - addError(CE_REFERENCETOANONEXISTINGOBJECT, import->file, import->line, import->source); - } - - if(importedNodes && !importedNodes->empty()) - mImports.insert(std::make_pair(import->source, importedNodes)); - } - - ImportRequestMap::iterator iter = mImportRequests.lower_bound(import->source), - end = mImportRequests.upper_bound(import->source); - // Handle the target request now - // If it is a '*' import we remove all previous requests and just use the '*' - // Otherwise, ensure '*' isn't already registered and register our request - if(import->target == "*") - { - mImportRequests.erase(iter, end); - mImportRequests.insert(std::make_pair(import->source, "*")); - } - else - { - if(iter == end || iter->second != "*") - { - mImportRequests.insert(std::make_pair(import->source, import->target)); - } - } - - nodes.erase(cur); - } - } - - // All import nodes are removed - // We have cached the code blocks from all the imported scripts - // We can process all import requests now - for(auto & import : mImports) - { - ImportRequestMap::iterator j = mImportRequests.lower_bound(import.first), - end = mImportRequests.upper_bound(import.first); - if(j != end) - { - if(j->second == "*") - { - // Insert the entire AST into the import table - mImportTable.insert(mImportTable.begin(), import.second->begin(), import.second->end()); - continue; // Skip ahead to the next file - } - else - { - for(; j != end; ++j) - { - // Locate this target and insert it into the import table - AbstractNodeList newNodes = locateTarget(*import.second, j->second); - if(!newNodes.empty()) - mImportTable.insert(mImportTable.begin(), newNodes.begin(), newNodes.end()); - else - // -1 for line as we lost that info here - addError(CE_REFERENCETOANONEXISTINGOBJECT, nodes.front()->file, -1, j->second); - } - } - } - } - } - - AbstractNodeListPtr ScriptCompiler::loadImportPath(const Ogre::String &name) - { - AbstractNodeListPtr retval; - ConcreteNodeListPtr nodes; - - if(mListener) - nodes = mListener->importFile(this, name); - - if(!nodes && ResourceGroupManager::getSingletonPtr()) - { - auto stream = ResourceGroupManager::getSingleton().openResource(name, mGroup, NULL, false); - - if (!stream) - return retval; - - nodes = ScriptParser::parse(ScriptLexer::tokenize(stream->getAsString(), name), name); - } - - if(nodes) - retval = convertToAST(*nodes); - - return retval; - } - - AbstractNodeList ScriptCompiler::locateTarget(const AbstractNodeList& nodes, const Ogre::String &target) - { - SharedPtr iter = nullptr; - - // Search for a top-level object node - for(auto i : nodes) - { - if(i->type == ANT_OBJECT) - { - ObjectAbstractNode *impl = (ObjectAbstractNode*)i.get(); - if(impl->name == target) - iter = i; - } - } - - AbstractNodeList newNodes; - if(iter) - { - newNodes.push_back(iter); - } - return newNodes; - } - - void ScriptCompiler::processObjects(AbstractNodeList& nodes, const AbstractNodeList &top) - { - for(auto& node : nodes) - { - if(node->type == ANT_OBJECT) - { - ObjectAbstractNode *obj = (ObjectAbstractNode*)node.get(); - -#ifdef OGRE_BUILD_COMPONENT_OVERLAY - bool isOverlayElement = obj->cls == "overlay_element"; -#endif - // Overlay base classes in order. - for (String& base : obj->bases) - { - // Check the top level first, then check the import table - AbstractNodeList newNodes = locateTarget(top, base); - if(newNodes.empty()) - newNodes = locateTarget(mImportTable, base); - - if (newNodes.empty()) - addError(CE_OBJECTBASENOTFOUND, obj->file, obj->line, base); - - for(const auto& n : newNodes) - { - if(n->type != ANT_OBJECT) continue; - - auto src = static_cast(*n); - -#ifdef OGRE_BUILD_COMPONENT_OVERLAY - // uses custom inheritance for renaming children - if(isOverlayElement) - { - if(src.abstract) - base = ""; // hide from custom inheritance - else - continue; - } -#endif - overlayObject(src, *obj); - } - } - - // Recurse into children - processObjects(obj->children, top); - - // Overrides now exist in obj's overrides list. These are non-object nodes which must now - // Be placed in the children section of the object node such that overriding from parents - // into children works properly. - obj->children.insert(obj->children.begin(), obj->overrides.begin(), obj->overrides.end()); - } - } - } - - void ScriptCompiler::overlayObject(const ObjectAbstractNode &src, ObjectAbstractNode& dest) - { - // Overlay the environment of one on top the other first - for(const auto & i : src.getVariables()) - { - std::pair var = dest.getVariable(i.first); - if(!var.first) - dest.setVariable(i.first, i.second); - } - - // Create a vector storing each pairing of override between source and destination - typedef SharedPtr ObjectAbstractNodePtr; - std::vector > overrides; - // A list of indices for each destination node tracks the minimum - // source node they can index-match against - std::map indices; - // A map storing which nodes have overridden from the destination node - std::map overridden; - - // Fill the vector with objects from the source node (base) - // And insert non-objects into the overrides list of the destination - AbstractNodeList::iterator insertPos = dest.children.begin(); - for(const auto & i : src.children) - { - if(i->type == ANT_OBJECT) - { - overrides.push_back(std::make_pair(static_pointer_cast(i), dest.children.end())); - } - else - { - AbstractNodePtr newNode(i->clone()); - newNode->parent = &dest; - dest.overrides.push_back(newNode); - } - } - - // Track the running maximum override index in the name-matching phase - size_t maxOverrideIndex = 0; - - // Loop through destination children searching for name-matching overrides - for(AbstractNodeList::iterator i = dest.children.begin(); i != dest.children.end(); ) - { - if((*i)->type == ANT_OBJECT) - { - // Start tracking the override index position for this object - size_t overrideIndex = 0; - - ObjectAbstractNode *node = static_cast((*i).get()); - indices[node] = maxOverrideIndex; - overridden[node] = false; - - // special treatment for materials with * in their name - bool nodeHasWildcard=node->name.find('*') != String::npos; - - // Find the matching name node - for(size_t j = 0; j < overrides.size(); ++j) - { - ObjectAbstractNode *temp = overrides[j].first.get(); - // Consider a match a node that has a wildcard and matches an input name - bool wildcardMatch = nodeHasWildcard && - (StringUtil::match(temp->name,node->name,true) || - (node->name.size() == 1 && temp->name.empty())); - if(temp->cls == node->cls && !node->name.empty() && (temp->name == node->name || wildcardMatch)) - { - // Pair these two together unless it's already paired - if(overrides[j].second == dest.children.end()) - { - AbstractNodeList::iterator currentIterator = i; - ObjectAbstractNode *currentNode = node; - if (wildcardMatch) - { - //If wildcard is matched, make a copy of current material and put it before the iterator, matching its name to the parent. Use same reinterpret cast as above when node is set - AbstractNodePtr newNode((*i)->clone()); - currentIterator = dest.children.insert(currentIterator, newNode); - currentNode = static_cast((*currentIterator).get()); - currentNode->name = temp->name;//make the regex match its matcher - } - overrides[j] = std::make_pair(overrides[j].first, currentIterator); - // Store the max override index for this matched pair - overrideIndex = j; - overrideIndex = maxOverrideIndex = std::max(overrideIndex, maxOverrideIndex); - indices[currentNode] = overrideIndex; - overridden[currentNode] = true; - } - else - { - addError(CE_DUPLICATEOVERRIDE, node->file, node->line); - } - - if(!wildcardMatch) - break; - } - } - - if (nodeHasWildcard) - { - //if the node has a wildcard it will be deleted since it was duplicated for every match - AbstractNodeList::iterator deletable=i++; - dest.children.erase(deletable); - } - else - { - ++i; //Behavior in absence of regex, just increment iterator - } - } - else - { - ++i; //Behavior in absence of replaceable object, just increment iterator to find another - } - } - - // Now make matches based on index - // Loop through destination children searching for index-matching overrides - for(AbstractNodeList::iterator i = dest.children.begin(); i != dest.children.end(); ++i) - { - if((*i)->type == ANT_OBJECT) - { - ObjectAbstractNode *node = static_cast((*i).get()); - if(!overridden[node]) - { - // Retrieve the minimum override index from the map - size_t overrideIndex = indices[node]; - - if(overrideIndex < overrides.size()) - { - // Search for minimum matching override - for(size_t j = overrideIndex; j < overrides.size(); ++j) - { - ObjectAbstractNode *temp = overrides[j].first.get(); - if(temp->name.empty() && node->name.empty() && temp->cls == node->cls && overrides[j].second == dest.children.end()) - { - overrides[j] = std::make_pair(overrides[j].first, i); - break; - } - } - } - } - } - } - - // Loop through overrides, either inserting source nodes or overriding - insertPos = dest.children.begin(); - for(auto & override : overrides) - { - if(override.second != dest.children.end()) - { - // Override the destination with the source (base) object - overlayObject(*override.first, - static_cast(**override.second)); - insertPos = override.second; - insertPos++; - } - else - { - // No override was possible, so insert this node at the insert position - // into the destination (child) object - AbstractNodePtr newNode(override.first->clone()); - newNode->parent = &dest; - if(insertPos != dest.children.end()) - { - dest.children.insert(insertPos, newNode); - } - else - { - dest.children.push_back(newNode); - } - } - } - } - - bool ScriptCompiler::isNameExcluded(const ObjectAbstractNode& node, AbstractNode* parent) - { - // Run past the listener - bool excludeName = false; - ProcessNameExclusionScriptCompilerEvent evt(node.cls, parent); - if(_fireEvent(&evt, (void*)&excludeName)) - return excludeName; - - // Process the built-in name exclusions - if(node.id == ID_EMITTER || node.id == ID_AFFECTOR) - { - // emitters or affectors inside a particle_system are excluded - while(parent && parent->type == ANT_OBJECT) - { - ObjectAbstractNode *obj = static_cast(parent); - if(obj->id == ID_PARTICLE_SYSTEM) - return true; - parent = obj->parent; - } - } - else if(node.id == ID_PASS) - { - // passes inside compositors are excluded - while(parent && parent->type == ANT_OBJECT) - { - ObjectAbstractNode *obj = static_cast(parent); - if(obj->id == ID_TARGET || obj->id == ID_TARGET_OUTPUT) - return true; - parent = obj->parent; - } - } - else if(node.id == ID_TEXTURE_SOURCE) - { - // Parent must be texture_unit - while(parent && parent->type == ANT_OBJECT) - { - ObjectAbstractNode *obj = static_cast(parent); - if(obj->id == ID_TEXTURE_UNIT) - return true; - parent = obj->parent; - } - } - - return false; - } - - void ScriptCompiler::processVariables(AbstractNodeList& nodes) - { - AbstractNodeList::iterator i = nodes.begin(); - while(i != nodes.end()) - { - AbstractNodeList::iterator cur = i; - ++i; - - if((*cur)->type == ANT_OBJECT) - { - // Only process if this object is not abstract - ObjectAbstractNode *obj = (ObjectAbstractNode*)(*cur).get(); - if(!obj->abstract) - { - processVariables(obj->children); - processVariables(obj->values); - } - } - else if((*cur)->type == ANT_PROPERTY) - { - PropertyAbstractNode *prop = (PropertyAbstractNode*)(*cur).get(); - processVariables(prop->values); - } - else if((*cur)->type == ANT_VARIABLE_ACCESS) - { - VariableAccessAbstractNode *var = (VariableAccessAbstractNode*)(*cur).get(); - - // Look up the enclosing scope - ObjectAbstractNode *scope = 0; - AbstractNode *temp = var->parent; - while(temp) - { - if(temp->type == ANT_OBJECT) - { - scope = (ObjectAbstractNode*)temp; - break; - } - temp = temp->parent; - } - - // Look up the variable in the environment - std::pair varAccess; - if(scope) - varAccess = scope->getVariable(var->name); - if(!scope || !varAccess.first) - { - std::map::iterator k = mEnv.find(var->name); - varAccess.first = k != mEnv.end(); - if(varAccess.first) - varAccess.second = k->second; - } - - if(varAccess.first) - { - // Found the variable, so process it and insert it into the tree - ConcreteNodeListPtr cst = ScriptParser::parseChunk(ScriptLexer::tokenize(varAccess.second, var->file), var->file); - AbstractNodeListPtr ast = convertToAST(*cst); - - // Set up ownership for these nodes - for(auto & j : *ast) - j->parent = var->parent; - - // Recursively handle variable accesses within the variable expansion - processVariables(*ast); - - // Insert the nodes in place of the variable - nodes.insert(cur, ast->begin(), ast->end()); - } - else - { - // Error - addError(CE_UNDEFINEDVARIABLE, var->file, var->line, var->name); - } - - // Remove the variable node - nodes.erase(cur); - } - } - } - - void ScriptCompiler::initWordMap() - { - mIds["on"] = ID_ON; - mIds["off"] = ID_OFF; - mIds["true"] = ID_TRUE; - mIds["false"] = ID_FALSE; - mIds["yes"] = ID_YES; - mIds["no"] = ID_NO; - - // Material ids - mIds["material"] = ID_MATERIAL; - mIds["vertex_program"] = ID_VERTEX_PROGRAM; - mIds["geometry_program"] = ID_GEOMETRY_PROGRAM; - mIds["fragment_program"] = ID_FRAGMENT_PROGRAM; - mIds["tessellation_hull_program"] = ID_TESSELLATION_HULL_PROGRAM; - mIds["tessellation_domain_program"] = ID_TESSELLATION_DOMAIN_PROGRAM; - mIds["compute_program"] = ID_COMPUTE_PROGRAM; - mIds["technique"] = ID_TECHNIQUE; - mIds["pass"] = ID_PASS; - mIds["texture_unit"] = ID_TEXTURE_UNIT; - mIds["vertex_program_ref"] = ID_VERTEX_PROGRAM_REF; - mIds["geometry_program_ref"] = ID_GEOMETRY_PROGRAM_REF; - mIds["fragment_program_ref"] = ID_FRAGMENT_PROGRAM_REF; - mIds["tessellation_hull_program_ref"] = ID_TESSELLATION_HULL_PROGRAM_REF; - mIds["tessellation_domain_program_ref"] = ID_TESSELLATION_DOMAIN_PROGRAM_REF; - mIds["compute_program_ref"] = ID_COMPUTE_PROGRAM_REF; - mIds["shadow_caster_vertex_program_ref"] = ID_SHADOW_CASTER_VERTEX_PROGRAM_REF; - mIds["shadow_caster_fragment_program_ref"] = ID_SHADOW_CASTER_FRAGMENT_PROGRAM_REF; - mIds["shadow_receiver_vertex_program_ref"] = ID_SHADOW_RECEIVER_VERTEX_PROGRAM_REF; - mIds["shadow_receiver_fragment_program_ref"] = ID_SHADOW_RECEIVER_FRAGMENT_PROGRAM_REF; - - mIds["lod_values"] = ID_LOD_VALUES; - mIds["lod_strategy"] = ID_LOD_STRATEGY; - mIds["lod_distances"] = ID_LOD_DISTANCES; - mIds["receive_shadows"] = ID_RECEIVE_SHADOWS; - mIds["transparency_casts_shadows"] = ID_TRANSPARENCY_CASTS_SHADOWS; - mIds["set_texture_alias"] = ID_SET_TEXTURE_ALIAS; - - mIds["source"] = ID_SOURCE; - mIds["syntax"] = ID_SYNTAX; - mIds["default_params"] = ID_DEFAULT_PARAMS; - mIds["param_indexed"] = ID_PARAM_INDEXED; - mIds["param_named"] = ID_PARAM_NAMED; - mIds["param_indexed_auto"] = ID_PARAM_INDEXED_AUTO; - mIds["param_named_auto"] = ID_PARAM_NAMED_AUTO; - - mIds["scheme"] = ID_SCHEME; - mIds["lod_index"] = ID_LOD_INDEX; - mIds["shadow_caster_material"] = ID_SHADOW_CASTER_MATERIAL; - mIds["shadow_receiver_material"] = ID_SHADOW_RECEIVER_MATERIAL; - mIds["gpu_vendor_rule"] = ID_GPU_VENDOR_RULE; - mIds["gpu_device_rule"] = ID_GPU_DEVICE_RULE; - mIds["include"] = ID_INCLUDE; - mIds["exclude"] = ID_EXCLUDE; - - mIds["ambient"] = ID_AMBIENT; - mIds["diffuse"] = ID_DIFFUSE; - mIds["specular"] = ID_SPECULAR; - mIds["emissive"] = ID_EMISSIVE; - mIds["vertexcolour"] = ID_VERTEXCOLOUR; - mIds["scene_blend"] = ID_SCENE_BLEND; - mIds["colour_blend"] = ID_COLOUR_BLEND; - mIds["one"] = ID_ONE; - mIds["zero"] = ID_ZERO; - mIds["dest_colour"] = ID_DEST_COLOUR; - mIds["src_colour"] = ID_SRC_COLOUR; - mIds["one_minus_src_colour"] = ID_ONE_MINUS_SRC_COLOUR; - mIds["one_minus_dest_colour"] = ID_ONE_MINUS_DEST_COLOUR; - mIds["dest_alpha"] = ID_DEST_ALPHA; - mIds["src_alpha"] = ID_SRC_ALPHA; - mIds["one_minus_dest_alpha"] = ID_ONE_MINUS_DEST_ALPHA; - mIds["one_minus_src_alpha"] = ID_ONE_MINUS_SRC_ALPHA; - mIds["separate_scene_blend"] = ID_SEPARATE_SCENE_BLEND; - mIds["scene_blend_op"] = ID_SCENE_BLEND_OP; - mIds["reverse_subtract"] = ID_REVERSE_SUBTRACT; - mIds["min"] = ID_MIN; - mIds["max"] = ID_MAX; - mIds["separate_scene_blend_op"] = ID_SEPARATE_SCENE_BLEND_OP; - mIds["depth_check"] = ID_DEPTH_CHECK; - mIds["depth_write"] = ID_DEPTH_WRITE; - mIds["depth_func"] = ID_DEPTH_FUNC; - mIds["depth_bias"] = ID_DEPTH_BIAS; - mIds["iteration_depth_bias"] = ID_ITERATION_DEPTH_BIAS; - mIds["always_fail"] = ID_ALWAYS_FAIL; - mIds["always_pass"] = ID_ALWAYS_PASS; - mIds["less_equal"] = ID_LESS_EQUAL; - mIds["less"] = ID_LESS; - mIds["equal"] = ID_EQUAL; - mIds["not_equal"] = ID_NOT_EQUAL; - mIds["greater_equal"] = ID_GREATER_EQUAL; - mIds["greater"] = ID_GREATER; - mIds["alpha_rejection"] = ID_ALPHA_REJECTION; - mIds["alpha_to_coverage"] = ID_ALPHA_TO_COVERAGE; - mIds["light_scissor"] = ID_LIGHT_SCISSOR; - mIds["light_clip_planes"] = ID_LIGHT_CLIP_PLANES; - mIds["transparent_sorting"] = ID_TRANSPARENT_SORTING; - mIds["illumination_stage"] = ID_ILLUMINATION_STAGE; - mIds["decal"] = ID_DECAL; - mIds["cull_hardware"] = ID_CULL_HARDWARE; - mIds["clockwise"] = ID_CLOCKWISE; - mIds["anticlockwise"] = ID_ANTICLOCKWISE; - mIds["cull_software"] = ID_CULL_SOFTWARE; - mIds["back"] = ID_BACK; - mIds["front"] = ID_FRONT; - mIds["lighting"] = ID_LIGHTING; - mIds["shading"] = ID_SHADING; - mIds["flat"] = ID_FLAT; - mIds["gouraud"] = ID_GOURAUD; - mIds["phong"] = ID_PHONG; - mIds["polygon_mode"] = ID_POLYGON_MODE; - mIds["solid"] = ID_SOLID; - mIds["wireframe"] = ID_WIREFRAME; - mIds["points"] = ID_POINTS; - mIds["polygon_mode_overrideable"] = ID_POLYGON_MODE_OVERRIDEABLE; - mIds["fog_override"] = ID_FOG_OVERRIDE; - mIds["none"] = ID_NONE; - mIds["linear"] = ID_LINEAR; - mIds["exp"] = ID_EXP; - mIds["exp2"] = ID_EXP2; - mIds["colour_write"] = ID_COLOUR_WRITE; - mIds["max_lights"] = ID_MAX_LIGHTS; - mIds["start_light"] = ID_START_LIGHT; - mIds["iteration"] = ID_ITERATION; - mIds["once"] = ID_ONCE; - mIds["once_per_light"] = ID_ONCE_PER_LIGHT; - mIds["per_n_lights"] = ID_PER_N_LIGHTS; - mIds["per_light"] = ID_PER_LIGHT; - mIds["point"] = ID_POINT; - mIds["spot"] = ID_SPOT; - mIds["directional"] = ID_DIRECTIONAL; - mIds["light_mask"] = ID_LIGHT_MASK; - mIds["point_size"] = ID_POINT_SIZE; - mIds["point_sprites"] = ID_POINT_SPRITES; - mIds["point_size_min"] = ID_POINT_SIZE_MIN; - mIds["point_size_max"] = ID_POINT_SIZE_MAX; - mIds["point_size_attenuation"] = ID_POINT_SIZE_ATTENUATION; - - mIds["texture_alias"] = ID_TEXTURE_ALIAS; - mIds["texture"] = ID_TEXTURE; - mIds["1d"] = ID_1D; - mIds["2d"] = ID_2D; - mIds["3d"] = ID_3D; - mIds["cubic"] = ID_CUBIC; - mIds["unlimited"] = ID_UNLIMITED; - mIds["2darray"] = ID_2DARRAY; - mIds["alpha"] = ID_ALPHA; - mIds["gamma"] = ID_GAMMA; - mIds["anim_texture"] = ID_ANIM_TEXTURE; - mIds["cubic_texture"] = ID_CUBIC_TEXTURE; - mIds["separateUV"] = ID_SEPARATE_UV; - mIds["combinedUVW"] = ID_COMBINED_UVW; - mIds["tex_coord_set"] = ID_TEX_COORD_SET; - mIds["tex_address_mode"] = ID_TEX_ADDRESS_MODE; - mIds["wrap"] = ID_WRAP; - mIds["clamp"] = ID_CLAMP; - mIds["mirror"] = ID_MIRROR; - mIds["border"] = ID_BORDER; - mIds["tex_border_colour"] = ID_TEX_BORDER_COLOUR; - mIds["filtering"] = ID_FILTERING; - mIds["bilinear"] = ID_BILINEAR; - mIds["trilinear"] = ID_TRILINEAR; - mIds["anisotropic"] = ID_ANISOTROPIC; - mIds["compare_test"] = ID_CMPTEST; - mIds["compare_func"] = ID_CMPFUNC; - mIds["max_anisotropy"] = ID_MAX_ANISOTROPY; - mIds["mipmap_bias"] = ID_MIPMAP_BIAS; - mIds["colour_op"] = ID_COLOUR_OP; - mIds["replace"] = ID_REPLACE; - mIds["add"] = ID_ADD; - mIds["modulate"] = ID_MODULATE; - mIds["alpha_blend"] = ID_ALPHA_BLEND; - mIds["colour_op_ex"] = ID_COLOUR_OP_EX; - mIds["source1"] = ID_SOURCE1; - mIds["source2"] = ID_SOURCE2; - mIds["modulate"] = ID_MODULATE; - mIds["modulate_x2"] = ID_MODULATE_X2; - mIds["modulate_x4"] = ID_MODULATE_X4; - mIds["add"] = ID_ADD; - mIds["add_signed"] = ID_ADD_SIGNED; - mIds["add_smooth"] = ID_ADD_SMOOTH; - mIds["subtract"] = ID_SUBTRACT; - mIds["blend_diffuse_alpha"] = ID_BLEND_DIFFUSE_ALPHA; - mIds["blend_texture_alpha"] = ID_BLEND_TEXTURE_ALPHA; - mIds["blend_current_alpha"] = ID_BLEND_CURRENT_ALPHA; - mIds["blend_manual"] = ID_BLEND_MANUAL; - mIds["dotproduct"] = ID_DOT_PRODUCT; - mIds["blend_diffuse_colour"] = ID_BLEND_DIFFUSE_COLOUR; - mIds["src_current"] = ID_SRC_CURRENT; - mIds["src_texture"] = ID_SRC_TEXTURE; - mIds["src_diffuse"] = ID_SRC_DIFFUSE; - mIds["src_specular"] = ID_SRC_SPECULAR; - mIds["src_manual"] = ID_SRC_MANUAL; - mIds["colour_op_multipass_fallback"] = ID_COLOUR_OP_MULTIPASS_FALLBACK; - mIds["alpha_op_ex"] = ID_ALPHA_OP_EX; - mIds["env_map"] = ID_ENV_MAP; - mIds["spherical"] = ID_SPHERICAL; - mIds["planar"] = ID_PLANAR; - mIds["cubic_reflection"] = ID_CUBIC_REFLECTION; - mIds["cubic_normal"] = ID_CUBIC_NORMAL; - mIds["scroll"] = ID_SCROLL; - mIds["scroll_anim"] = ID_SCROLL_ANIM; - mIds["rotate"] = ID_ROTATE; - mIds["rotate_anim"] = ID_ROTATE_ANIM; - mIds["scale"] = ID_SCALE; - mIds["wave_xform"] = ID_WAVE_XFORM; - mIds["scroll_x"] = ID_SCROLL_X; - mIds["scroll_y"] = ID_SCROLL_Y; - mIds["scale_x"] = ID_SCALE_X; - mIds["scale_y"] = ID_SCALE_Y; - mIds["sine"] = ID_SINE; - mIds["triangle"] = ID_TRIANGLE; - mIds["sawtooth"] = ID_SAWTOOTH; - mIds["square"] = ID_SQUARE; - mIds["inverse_sawtooth"] = ID_INVERSE_SAWTOOTH; - mIds["transform"] = ID_TRANSFORM; - mIds["geometry"] = ID_GEOMETRY; - mIds["tessellation_hull"] = ID_TESSELLATION_HULL; - mIds["tessellation_domain"] = ID_TESSELLATION_DOMAIN; - mIds["compute"] = ID_COMPUTE; - mIds["content_type"] = ID_CONTENT_TYPE; - mIds["named"] = ID_NAMED; - mIds["shadow"] = ID_SHADOW; - mIds["texture_source"] = ID_TEXTURE_SOURCE; - mIds["shared_params"] = ID_SHARED_PARAMS; - mIds["shared_param_named"] = ID_SHARED_PARAM_NAMED; - mIds["shared_params_ref"] = ID_SHARED_PARAMS_REF; - - // Particle system - mIds["particle_system"] = ID_PARTICLE_SYSTEM; - mIds["emitter"] = ID_EMITTER; - mIds["affector"] = ID_AFFECTOR; - - // Compositor - mIds["compositor"] = ID_COMPOSITOR; - mIds["target"] = ID_TARGET; - mIds["target_output"] = ID_TARGET_OUTPUT; - - mIds["input"] = ID_INPUT; - //mIds["none"] = ID_NONE; - already registered - mIds["previous"] = ID_PREVIOUS; - mIds["target_width"] = ID_TARGET_WIDTH; - mIds["target_height"] = ID_TARGET_HEIGHT; - mIds["target_width_scaled"] = ID_TARGET_WIDTH_SCALED; - mIds["target_height_scaled"] = ID_TARGET_HEIGHT_SCALED; - mIds["pooled"] = ID_POOLED; - //mIds["gamma"] = ID_GAMMA; - already registered - mIds["no_fsaa"] = ID_NO_FSAA; - mIds["depth_pool"] = ID_DEPTH_POOL; - - mIds["texture_ref"] = ID_TEXTURE_REF; - mIds["local_scope"] = ID_SCOPE_LOCAL; - mIds["chain_scope"] = ID_SCOPE_CHAIN; - mIds["global_scope"] = ID_SCOPE_GLOBAL; - mIds["compositor_logic"] = ID_COMPOSITOR_LOGIC; - - mIds["only_initial"] = ID_ONLY_INITIAL; - mIds["visibility_mask"] = ID_VISIBILITY_MASK; - mIds["lod_bias"] = ID_LOD_BIAS; - mIds["material_scheme"] = ID_MATERIAL_SCHEME; - mIds["shadows"] = ID_SHADOWS_ENABLED; - - mIds["clear"] = ID_CLEAR; - mIds["stencil"] = ID_STENCIL; - mIds["render_scene"] = ID_RENDER_SCENE; - mIds["render_quad"] = ID_RENDER_QUAD; - mIds["identifier"] = ID_IDENTIFIER; - mIds["first_render_queue"] = ID_FIRST_RENDER_QUEUE; - mIds["last_render_queue"] = ID_LAST_RENDER_QUEUE; - mIds["quad_normals"] = ID_QUAD_NORMALS; - mIds["camera_far_corners_view_space"] = ID_CAMERA_FAR_CORNERS_VIEW_SPACE; - mIds["camera_far_corners_world_space"] = ID_CAMERA_FAR_CORNERS_WORLD_SPACE; - - mIds["buffers"] = ID_BUFFERS; - mIds["colour"] = ID_COLOUR; - mIds["depth"] = ID_DEPTH; - mIds["colour_value"] = ID_COLOUR_VALUE; - mIds["depth_value"] = ID_DEPTH_VALUE; - mIds["stencil_value"] = ID_STENCIL_VALUE; - - mIds["check"] = ID_CHECK; - mIds["comp_func"] = ID_COMP_FUNC; - mIds["ref_value"] = ID_REF_VALUE; - mIds["mask"] = ID_MASK; - mIds["fail_op"] = ID_FAIL_OP; - mIds["keep"] = ID_KEEP; - mIds["increment"] = ID_INCREMENT; - mIds["decrement"] = ID_DECREMENT; - mIds["increment_wrap"] = ID_INCREMENT_WRAP; - mIds["decrement_wrap"] = ID_DECREMENT_WRAP; - mIds["invert"] = ID_INVERT; - mIds["depth_fail_op"] = ID_DEPTH_FAIL_OP; - mIds["pass_op"] = ID_PASS_OP; - mIds["two_sided"] = ID_TWO_SIDED; - - mIds["line_width"] = ID_LINE_WIDTH; - mIds["sampler"] = ID_SAMPLER; - mIds["sampler_ref"] = ID_SAMPLER_REF; - mIds["thread_groups"] = ID_THREAD_GROUPS; - mIds["render_custom"] = ID_RENDER_CUSTOM; - mIds["auto"] = ID_AUTO; - mIds["camera"] = ID_CAMERA; - mIds["align_to_face"] = ID_ALIGN_TO_FACE; - mIds["unordered_access_mip"] = ID_UNORDERED_ACCESS_MIP; - - mLargestRegisteredWordId = ID_END_BUILTIN_IDS; - } - - uint32 ScriptCompiler::registerCustomWordId(const String &word) - { - // if the word is already registered, just return the right id - IdMap::iterator iter = mIds.find(word); - if(iter != mIds.end()) - return iter->second; - - // As there are no other function changing mIds than registerCustomWordId and initWordMap, - // we know that mLargestRegisteredWordId is the largest word id and therefore mLargestRegisteredWordId+1 - // wasn't used yet. - mLargestRegisteredWordId++; - mIds[word] = mLargestRegisteredWordId; - return mLargestRegisteredWordId; - } - - // AbstractTreeeBuilder - ScriptCompiler::AbstractTreeBuilder::AbstractTreeBuilder(ScriptCompiler *compiler) - :mNodes(std::make_shared()), mCurrent(0), mCompiler(compiler) - { - } - - const AbstractNodeListPtr &ScriptCompiler::AbstractTreeBuilder::getResult() const - { - return mNodes; - } - - void ScriptCompiler::AbstractTreeBuilder::visit(ConcreteNode *node) - { - AbstractNodePtr asn; - - // Import = "import" >> 2 children, mCurrent == null - if(node->type == CNT_IMPORT && mCurrent == 0) - { - if(node->children.size() > 2) - { - mCompiler->addError(CE_FEWERPARAMETERSEXPECTED, node->file, node->line); - return; - } - if(node->children.size() < 2) - { - mCompiler->addError(CE_STRINGEXPECTED, node->file, node->line); - return; - } - - ImportAbstractNode *impl = OGRE_NEW ImportAbstractNode(); - impl->line = node->line; - impl->file = node->file; - - ConcreteNodeList::iterator iter = node->children.begin(); - impl->target = (*iter)->token; - - iter++; - impl->source = (*iter)->token; - - asn = AbstractNodePtr(impl); - } - // variable set = "set" >> 2 children, children[0] == variable - else if(node->type == CNT_VARIABLE_ASSIGN) - { - if(node->children.size() > 2) - { - mCompiler->addError(CE_FEWERPARAMETERSEXPECTED, node->file, node->line); - return; - } - if(node->children.size() < 2) - { - mCompiler->addError(CE_STRINGEXPECTED, node->file, node->line); - return; - } - if(node->children.front()->type != CNT_VARIABLE) - { - mCompiler->addError(CE_VARIABLEEXPECTED, node->children.front()->file, node->children.front()->line); - return; - } - - ConcreteNodeList::iterator i = node->children.begin(); - String name = (*i)->token; - - ++i; - String value = (*i)->token; - - if(mCurrent && mCurrent->type == ANT_OBJECT) - { - ObjectAbstractNode *ptr = (ObjectAbstractNode*)mCurrent; - ptr->setVariable(name, value); - } - else - { - mCompiler->mEnv.insert(std::make_pair(name, value)); - } - } - // variable = $*, no children - else if(node->type == CNT_VARIABLE) - { - if(!node->children.empty()) - { - mCompiler->addError(CE_FEWERPARAMETERSEXPECTED, node->file, node->line); - return; - } - - VariableAccessAbstractNode *impl = OGRE_NEW VariableAccessAbstractNode(mCurrent); - impl->line = node->line; - impl->file = node->file; - impl->name = node->token; - - asn = AbstractNodePtr(impl); - } - // Handle properties and objects here - else if(!node->children.empty()) - { - // Grab the last two nodes - ConcreteNodePtr temp1, temp2; - ConcreteNodeList::reverse_iterator riter = node->children.rbegin(); - if(riter != node->children.rend()) - { - temp1 = *riter; - riter++; - } - if(riter != node->children.rend()) - temp2 = *riter; - - // object = last 2 children == { and } - if(temp1 && temp2 && - temp1->type == CNT_RBRACE && temp2->type == CNT_LBRACE) - { - if(node->children.size() < 2) - { - mCompiler->addError(CE_STRINGEXPECTED, node->file, node->line); - return; - } - - ObjectAbstractNode *impl = OGRE_NEW ObjectAbstractNode(mCurrent); - impl->line = node->line; - impl->file = node->file; - impl->abstract = false; - - // Create a temporary detail list - std::list temp; - if(node->token == "abstract") - { - impl->abstract = true; - for(ConcreteNodeList::const_iterator i = node->children.begin(); i != node->children.end(); ++i) - temp.push_back((*i).get()); - } - else - { - temp.push_back(node); - for(ConcreteNodeList::const_iterator i = node->children.begin(); i != node->children.end(); ++i) - temp.push_back((*i).get()); - } - - // Get the type of object - std::list::const_iterator iter = temp.begin(); - impl->cls = (*iter)->token; - ++iter; - - // try to map the cls to an id - ScriptCompiler::IdMap::const_iterator iter2 = mCompiler->mIds.find(impl->cls); - if(iter2 != mCompiler->mIds.end()) - { - impl->id = iter2->second; - } - else - { - mCompiler->addError(CE_UNEXPECTEDTOKEN, impl->file, impl->line, - "'" + impl->cls + "'. If this is a legacy script you must prepend the type (e.g. font, overlay)."); - } - - // Get the name - // Unless the type is in the exclusion list - if(iter != temp.end() && ((*iter)->type == CNT_WORD || (*iter)->type == CNT_QUOTE) && - !mCompiler->isNameExcluded(*impl, mCurrent)) - { - impl->name = (*iter)->token; - ++iter; - } - - // Everything up until the colon is a "value" of this object - while(iter != temp.end() && (*iter)->type != CNT_COLON && (*iter)->type != CNT_LBRACE) - { - if((*iter)->type == CNT_VARIABLE) - { - VariableAccessAbstractNode *var = OGRE_NEW VariableAccessAbstractNode(impl); - var->file = (*iter)->file; - var->line = (*iter)->line; - var->type = ANT_VARIABLE_ACCESS; - var->name = (*iter)->token; - impl->values.push_back(AbstractNodePtr(var)); - } - else - { - AtomAbstractNode *atom = OGRE_NEW AtomAbstractNode(impl); - atom->file = (*iter)->file; - atom->line = (*iter)->line; - atom->type = ANT_ATOM; - atom->value = (*iter)->token; - - auto idpos = mCompiler->mIds.find(atom->value); - if(idpos != mCompiler->mIds.end()) - atom->id = idpos->second; - - impl->values.push_back(AbstractNodePtr(atom)); - } - ++iter; - } - - // Find the bases - if(iter != temp.end() && (*iter)->type == CNT_COLON) - { - // Children of the ':' are bases - for(auto & j : (*iter)->children) - impl->bases.push_back(j->token); - ++iter; - } - - asn = AbstractNodePtr(impl); - mCurrent = impl; - - // Visit the children of the { - AbstractTreeBuilder::visit(this, temp2->children); - - // Go back up the stack - mCurrent = impl->parent; - } - // Otherwise, it is a property - else - { - PropertyAbstractNode *impl = OGRE_NEW PropertyAbstractNode(mCurrent); - impl->line = node->line; - impl->file = node->file; - impl->name = node->token; - - ScriptCompiler::IdMap::const_iterator iter2 = mCompiler->mIds.find(impl->name); - if(iter2 != mCompiler->mIds.end()) - impl->id = iter2->second; - - asn = AbstractNodePtr(impl); - mCurrent = impl; - - // Visit the children of the { - AbstractTreeBuilder::visit(this, node->children); - - // Go back up the stack - mCurrent = impl->parent; - } - } - // Otherwise, it is a standard atom - else - { - AtomAbstractNode *impl = OGRE_NEW AtomAbstractNode(mCurrent); - impl->line = node->line; - impl->file = node->file; - impl->value = node->token; - - ScriptCompiler::IdMap::const_iterator iter2 = mCompiler->mIds.find(impl->value); - if(iter2 != mCompiler->mIds.end()) - impl->id = iter2->second; - - asn = AbstractNodePtr(impl); - } - - // Here, we must insert the node into the tree - if(asn) - { - if(mCurrent) - { - if(mCurrent->type == ANT_PROPERTY) - { - PropertyAbstractNode *impl = static_cast(mCurrent); - impl->values.push_back(asn); - } - else - { - ObjectAbstractNode *impl = static_cast(mCurrent); - impl->children.push_back(asn); - } - } - else - { - mNodes->push_back(asn); - } - } - } - - void ScriptCompiler::AbstractTreeBuilder::visit(AbstractTreeBuilder *visitor, const ConcreteNodeList &nodes) - { - for(const auto & node : nodes) - visitor->visit(node.get()); - } - - - // ScriptCompilerManager - template<> ScriptCompilerManager *Singleton::msSingleton = 0; - - ScriptCompilerManager* ScriptCompilerManager::getSingletonPtr(void) - { - return msSingleton; - } - //----------------------------------------------------------------------- - ScriptCompilerManager& ScriptCompilerManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //----------------------------------------------------------------------- - ScriptCompilerManager::ScriptCompilerManager() - { - OGRE_LOCK_AUTO_MUTEX; - mScriptPatterns.push_back("*.program"); - mScriptPatterns.push_back("*.material"); - mScriptPatterns.push_back("*.particle"); - mScriptPatterns.push_back("*.compositor"); - mScriptPatterns.push_back("*.os"); - ResourceGroupManager::getSingleton()._registerScriptLoader(this); - - mBuiltinTranslatorManager = OGRE_NEW BuiltinScriptTranslatorManager(); - mManagers.push_back(mBuiltinTranslatorManager); - } - //----------------------------------------------------------------------- - ScriptCompilerManager::~ScriptCompilerManager() - { - OGRE_DELETE mBuiltinTranslatorManager; - } - //----------------------------------------------------------------------- - void ScriptCompilerManager::setListener(ScriptCompilerListener *listener) - { - OGRE_LOCK_AUTO_MUTEX; - mScriptCompiler.setListener(listener); - } - //----------------------------------------------------------------------- - ScriptCompilerListener *ScriptCompilerManager::getListener() - { - return mScriptCompiler.getListener(); - } - //----------------------------------------------------------------------- - void ScriptCompilerManager::addTranslatorManager(Ogre::ScriptTranslatorManager *man) - { - OGRE_LOCK_AUTO_MUTEX; - mManagers.push_back(man); - } - //----------------------------------------------------------------------- - void ScriptCompilerManager::removeTranslatorManager(Ogre::ScriptTranslatorManager *man) - { - OGRE_LOCK_AUTO_MUTEX; - - for(std::vector::iterator i = mManagers.begin(); i != mManagers.end(); ++i) - { - if(*i == man) - { - mManagers.erase(i); - break; - } - } - } - //------------------------------------------------------------------------- - void ScriptCompilerManager::clearTranslatorManagers() - { - mManagers.clear(); - } - //----------------------------------------------------------------------- - ScriptTranslator *ScriptCompilerManager::getTranslator(const AbstractNodePtr &node) - { - ScriptTranslator *translator = 0; - { - OGRE_LOCK_AUTO_MUTEX; - - // Start looking from the back - for(std::vector::reverse_iterator i = mManagers.rbegin(); i != mManagers.rend(); ++i) - { - translator = (*i)->getTranslator(node); - if(translator != 0) - break; - } - } - return translator; - } - //----------------------------------------------------------------------- - uint32 ScriptCompilerManager::registerCustomWordId(const String &word) - { - return mScriptCompiler.registerCustomWordId(word); - } - //----------------------------------------------------------------------- - void ScriptCompilerManager::addScriptPattern(const String &pattern) - { - mScriptPatterns.push_back(pattern); - } - //----------------------------------------------------------------------- - const StringVector& ScriptCompilerManager::getScriptPatterns(void) const - { - return mScriptPatterns; - } - //----------------------------------------------------------------------- - Real ScriptCompilerManager::getLoadingOrder(void) const - { - /// Load relatively early, before most script loaders run - return 90.0f; - } - //----------------------------------------------------------------------- - void ScriptCompilerManager::parseScript(DataStreamPtr& stream, const String& groupName) - { - ConcreteNodeListPtr nodes = - ScriptParser::parse(ScriptLexer::tokenize(stream->getAsString(), stream->getName()), stream->getName()); - { - // compile is not reentrant - OGRE_LOCK_AUTO_MUTEX; - mScriptCompiler.compile(nodes, groupName); - } - } - - //------------------------------------------------------------------------- - String ProcessResourceNameScriptCompilerEvent::eventType = "processResourceName"; - //------------------------------------------------------------------------- - String ProcessNameExclusionScriptCompilerEvent::eventType = "processNameExclusion"; - //---------------------------------------------------------------------------- - String CreateMaterialScriptCompilerEvent::eventType = "createMaterial"; - //---------------------------------------------------------------------------- - String CreateGpuProgramScriptCompilerEvent::eventType = "createGpuProgram"; - //------------------------------------------------------------------------- - String CreateGpuSharedParametersScriptCompilerEvent::eventType = "createGpuSharedParameters"; - //------------------------------------------------------------------------- - String CreateParticleSystemScriptCompilerEvent::eventType = "createParticleSystem"; - //------------------------------------------------------------------------- - String CreateCompositorScriptCompilerEvent::eventType = "createCompositor"; -} - - diff --git a/OgreMain/src/OgreScriptLexer.cpp b/OgreMain/src/OgreScriptLexer.cpp deleted file mode 100644 index 617c3b195ac..00000000000 --- a/OgreMain/src/OgreScriptLexer.cpp +++ /dev/null @@ -1,323 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreScriptLexer.h" - -namespace Ogre { - ScriptTokenList ScriptLexer::tokenize(const String &str, const String& source) - { - String error; - ScriptTokenList ret = _tokenize(str, source.c_str(), error); - - if (!error.empty()) - LogManager::getSingleton().logError("ScriptLexer - " + error); - - return ret; - } - - ScriptTokenList ScriptLexer::_tokenize(const String &str, const char* source, String& error) - { - // State enums - enum{ READY = 0, COMMENT, MULTICOMMENT, WORD, QUOTE, VAR, POSSIBLECOMMENT }; - - // Set up some constant characters of interest - const wchar_t varopener = '$', quote = '\"', slash = '/', backslash = '\\', openbrace = '{', closebrace = '}', colon = ':', star = '*', cr = '\r', lf = '\n'; - char c = 0, lastc = 0; - - String lexeme; - uint32 line = 1, state = READY, lastQuote = 0, firstOpenBrace = 0, braceLayer = 0; - ScriptTokenList tokens; - - // Iterate over the input - for(char i : str) - { - lastc = c; - c = i; - - if(c == quote) - lastQuote = line; - - if(state == READY || state == WORD || state == VAR) - { - if(c == openbrace) - { - if(braceLayer == 0) - firstOpenBrace = line; - - braceLayer ++; - } - else if(c == closebrace) - { - if (braceLayer == 0) - { - error = StringUtil::format( - "no matching open bracket '{' found for close bracket '}' at %s:%d", source, - line); - return tokens; - } - - braceLayer --; - } - } - - - switch(state) - { - case READY: - if(c == slash && lastc == slash) - { - // Comment start, clear out the lexeme - lexeme = ""; - state = COMMENT; - } - else if(c == star && lastc == slash) - { - lexeme = ""; - state = MULTICOMMENT; - } - else if(c == quote) - { - // Clear out the lexeme ready to be filled with quotes! - lexeme = c; - state = QUOTE; - } - else if(c == varopener) - { - // Set up to read in a variable - lexeme = c; - state = VAR; - } - else if(isNewline(c)) - { - lexeme = c; - setToken(lexeme, line, tokens); - } - else if(!isWhitespace(c)) - { - lexeme = c; - if(c == slash) - state = POSSIBLECOMMENT; - else - state = WORD; - } - break; - case COMMENT: - if(isNewline(c)) - { - lexeme = c; - setToken(lexeme, line, tokens); - state = READY; - } - break; - case MULTICOMMENT: - if(c == slash && lastc == star) - state = READY; - break; - case POSSIBLECOMMENT: - if(c == slash && lastc == slash) - { - lexeme = ""; - state = COMMENT; - break; - } - else if(c == star && lastc == slash) - { - lexeme = ""; - state = MULTICOMMENT; - break; - } - else - { - state = WORD; - OGRE_FALLTHROUGH; - } - case WORD: - if(isNewline(c)) - { - setToken(lexeme, line, tokens); - lexeme = c; - setToken(lexeme, line, tokens); - state = READY; - } - else if(isWhitespace(c)) - { - setToken(lexeme, line, tokens); - state = READY; - } - else if(c == openbrace || c == closebrace || c == colon) - { - setToken(lexeme, line, tokens); - lexeme = c; - setToken(lexeme, line, tokens); - state = READY; - } - else - { - lexeme += c; - } - break; - case QUOTE: - if(c != backslash) - { - // Allow embedded quotes with escaping - if(c == quote && lastc == backslash) - { - lexeme += c; - } - else if(c == quote) - { - lexeme += c; - setToken(lexeme, line, tokens); - state = READY; - } - else - { - // Backtrack here and allow a backslash normally within the quote - if(lastc == backslash) - lexeme = lexeme + "\\" + c; - else - lexeme += c; - } - } - break; - case VAR: - if(isNewline(c)) - { - setToken(lexeme, line, tokens); - lexeme = c; - setToken(lexeme, line, tokens); - state = READY; - } - else if(isWhitespace(c)) - { - setToken(lexeme, line, tokens); - state = READY; - } - else if(c == openbrace || c == closebrace || c == colon) - { - setToken(lexeme, line, tokens); - lexeme = c; - setToken(lexeme, line, tokens); - state = READY; - } - else - { - lexeme += c; - } - break; - } - - // Separate check for newlines just to track line numbers - if(c == cr || (c == lf && lastc != cr)) - line++; - } - - // Check for valid exit states - if(state == WORD || state == VAR) - { - if(!lexeme.empty()) - setToken(lexeme, line, tokens); - } - else - { - if(state == QUOTE) - { - error = StringUtil::format("no matching \" found for \" at %s:%d", source, lastQuote); - return tokens; - } - } - - // Check that all opened brackets have been closed - if (braceLayer == 1) - { - error = StringUtil::format("no matching closing bracket '}' for open bracket '{' at %s:%d", - source, firstOpenBrace); - } - else if (braceLayer > 1) - { - error = StringUtil::format( - "too many open brackets (%d) '{' without matching closing bracket '}' in %s", braceLayer, - source); - } - - return tokens; - } - - void ScriptLexer::setToken(const Ogre::String &lexeme, Ogre::uint32 line, ScriptTokenList& tokens) - { - const char openBracket = '{', closeBracket = '}', colon = ':', - quote = '\"', var = '$'; - - ScriptToken token; - token.line = line; - bool ignore = false; - - // Check the user token map first - if(lexeme.size() == 1 && isNewline(lexeme[0])) - { - token.type = TID_NEWLINE; - if(!tokens.empty() && tokens.back().type == TID_NEWLINE) - ignore = true; - } - else if(lexeme.size() == 1 && lexeme[0] == openBracket) - token.type = TID_LBRACKET; - else if(lexeme.size() == 1 && lexeme[0] == closeBracket) - token.type = TID_RBRACKET; - else if(lexeme.size() == 1 && lexeme[0] == colon) - token.type = TID_COLON; - else - { - token.lexeme = lexeme; - - // This is either a non-zero length phrase or quoted phrase - if(lexeme.size() >= 2 && lexeme[0] == quote && lexeme[lexeme.size() - 1] == quote) - { - token.type = TID_QUOTE; - } - else if(lexeme.size() > 1 && lexeme[0] == var) - token.type = TID_VARIABLE; - else - { - token.type = TID_WORD; - } - } - - if(!ignore) - tokens.push_back(token); - } - - bool ScriptLexer::isWhitespace(Ogre::String::value_type c) - { - return c == ' ' || c == '\r' || c == '\t'; - } - - bool ScriptLexer::isNewline(Ogre::String::value_type c) - { - return c == '\n' || c == '\r'; - } -} diff --git a/OgreMain/src/OgreScriptLexer.h b/OgreMain/src/OgreScriptLexer.h deleted file mode 100644 index 230808d31d5..00000000000 --- a/OgreMain/src/OgreScriptLexer.h +++ /dev/null @@ -1,86 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __ScriptLexer_H_ -#define __ScriptLexer_H_ - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - /** These codes represent token IDs which are numerical translations of - specific lexemes. Specific compilers using the lexer can register their - own token IDs which are given precedence over these built-in ones. - */ - enum{ - TID_LBRACKET = 0, // { - TID_RBRACKET, // } - TID_COLON, // : - TID_VARIABLE, // $... - TID_WORD, // * - TID_QUOTE, // "*" - TID_NEWLINE, // \n - TID_UNKNOWN, - TID_END - }; - - /** This struct represents a token, which is an ID'd lexeme from the - parsing input stream. - */ - struct ScriptToken - { - /// This is the lexeme for this token - String lexeme; - /// This is the id associated with the lexeme, which comes from a lexeme-token id mapping - uint32 type; - /// This holds the line number of the input stream where the token was found. - uint32 line; - }; - typedef std::vector ScriptTokenList; - - class _OgrePrivate ScriptLexer : public ScriptCompilerAlloc - { - public: - /** Tokenizes the given input and returns the list of tokens found */ - static ScriptTokenList tokenize(const String &str, const String &source); - private: // Private utility operations - static ScriptTokenList _tokenize(const String &str, const char* source, String& error); - static void setToken(const String &lexeme, uint32 line, ScriptTokenList& tokens); - static bool isWhitespace(Ogre::String::value_type c); - static bool isNewline(Ogre::String::value_type c); - }; - - /** @} */ - /** @} */ -} - -#endif diff --git a/OgreMain/src/OgreScriptParser.cpp b/OgreMain/src/OgreScriptParser.cpp deleted file mode 100644 index 43e655fe585..00000000000 --- a/OgreMain/src/OgreScriptParser.cpp +++ /dev/null @@ -1,498 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" -#include "OgreScriptParser.h" - -#include - -namespace Ogre -{ - static String unquoted(const String& str, bool trim = true) - { - return trim ? str.substr(1, str.size() - 2) : str; - } - - ConcreteNodeListPtr ScriptParser::parse(const ScriptTokenList &tokens, const String& file) - { - auto nodes = std::make_shared(); - - enum{READY, OBJECT}; - uint32 state = READY; - - ConcreteNode *parent = 0; - ConcreteNodePtr node; - const ScriptToken *token = 0; - ScriptTokenList::const_iterator i = tokens.begin(), end = tokens.end(); - while(i != end) - { - token = &*i; - - switch(state) - { - case READY: - if(token->type == TID_WORD) - { - if(token->lexeme == "import") - { - node = std::make_shared(); - node->token = token->lexeme; - node->file = file; - node->line = token->line; - node->type = CNT_IMPORT; - - // The next token is the target - ++i; - if(i == end || (i->type != TID_WORD && i->type != TID_QUOTE)) - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, - Ogre::String("expected import target at line ") + - Ogre::StringConverter::toString(node->line), - "ScriptParser::parse"); - ConcreteNodePtr temp(OGRE_NEW ConcreteNode()); - temp->parent = node.get(); - temp->file = file; - temp->line = i->line; - temp->type = i->type == TID_WORD ? CNT_WORD : CNT_QUOTE; - temp->token = unquoted(i->lexeme, temp->type == CNT_QUOTE); - node->children.push_back(temp); - - // The second-next token is the source - ++i; - ++i; - if(i == end || (i->type != TID_WORD && i->type != TID_QUOTE)) - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, - Ogre::String("expected import source at line ") + - Ogre::StringConverter::toString(node->line), - "ScriptParser::parse"); - temp = std::make_shared(); - temp->parent = node.get(); - temp->file = file; - temp->line = i->line; - temp->type = i->type == TID_WORD ? CNT_WORD : CNT_QUOTE; - temp->token = unquoted(i->lexeme, temp->type == CNT_QUOTE); - node->children.push_back(temp); - - // Consume all the newlines - i = skipNewlines(i, end); - - // Insert the node - if(parent) - { - node->parent = parent; - parent->children.push_back(node); - } - else - { - node->parent = 0; - nodes->push_back(node); - } - node = ConcreteNodePtr(); - } - else if(token->lexeme == "set") - { - node = std::make_shared(); - node->token = token->lexeme; - node->file = file; - node->line = token->line; - node->type = CNT_VARIABLE_ASSIGN; - - // The next token is the variable - ++i; - if(i == end || i->type != TID_VARIABLE) - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, - Ogre::String("expected variable name at line ") + - Ogre::StringConverter::toString(node->line), - "ScriptParser::parse"); - ConcreteNodePtr temp(OGRE_NEW ConcreteNode()); - temp->parent = node.get(); - temp->file = file; - temp->line = i->line; - temp->type = CNT_VARIABLE; - temp->token = i->lexeme; - node->children.push_back(temp); - - // The next token is the assignment - ++i; - if(i == end || (i->type != TID_WORD && i->type != TID_QUOTE)) - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, - Ogre::String("expected variable value at line ") + - Ogre::StringConverter::toString(node->line), - "ScriptParser::parse"); - temp = std::make_shared(); - temp->parent = node.get(); - temp->file = file; - temp->line = i->line; - temp->type = i->type == TID_WORD ? CNT_WORD : CNT_QUOTE; - temp->token = unquoted(i->lexeme, temp->type == CNT_QUOTE); - node->children.push_back(temp); - - // Consume all the newlines - i = skipNewlines(i, end); - - // Insert the node - if(parent) - { - node->parent = parent; - parent->children.push_back(node); - } - else - { - node->parent = 0; - nodes->push_back(node); - } - node = ConcreteNodePtr(); - } - else - { - node = std::make_shared(); - node->file = file; - node->line = token->line; - node->type = token->type == TID_WORD ? CNT_WORD : CNT_QUOTE; - node->token = unquoted(token->lexeme, node->type == CNT_QUOTE); - - // Insert the node - if(parent) - { - node->parent = parent; - parent->children.push_back(node); - } - else - { - node->parent = 0; - nodes->push_back(node); - } - - // Set the parent - parent = node.get(); - - // Switch states - state = OBJECT; - - node = ConcreteNodePtr(); - } - } - else if(token->type == TID_RBRACKET) - { - // Go up one level if we can - if(parent) - parent = parent->parent; - - node = std::make_shared(); - node->token = token->lexeme; - node->file = file; - node->line = token->line; - node->type = CNT_RBRACE; - - // Consume all the newlines - i = skipNewlines(i, end); - - // Insert the node - if(parent) - { - node->parent = parent; - parent->children.push_back(node); - } - else - { - node->parent = 0; - nodes->push_back(node); - } - - // Move up another level - if(parent) - parent = parent->parent; - - node = ConcreteNodePtr(); - } - break; - case OBJECT: - if(token->type == TID_NEWLINE) - { - // Look ahead to the next non-newline token and if it isn't an {, this was a property - ScriptTokenList::const_iterator next = skipNewlines(i, end); - if(next == end || next->type != TID_LBRACKET) - { - // Ended a property here - if(parent) - parent = parent->parent; - state = READY; - } - } - else if(token->type == TID_COLON) - { - node = std::make_shared(); - node->token = token->lexeme; - node->file = file; - node->line = token->line; - node->type = CNT_COLON; - - // The following token are the parent objects (base classes). - // Require at least one of them. - - ScriptTokenList::const_iterator j = i + 1; - j = skipNewlines(j, end); - if(j == end || (j->type != TID_WORD && j->type != TID_QUOTE)) { - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, - Ogre::String("expected object identifier at line ") + - Ogre::StringConverter::toString(node->line), - "ScriptParser::parse"); - } - - while(j != end && (j->type == TID_WORD || j->type == TID_QUOTE)) - { - ConcreteNodePtr tempNode = std::make_shared(); - tempNode->token = j->lexeme; - tempNode->file = file; - tempNode->line = j->line; - tempNode->type = j->type == TID_WORD ? CNT_WORD : CNT_QUOTE; - tempNode->parent = node.get(); - node->children.push_back(tempNode); - ++j; - } - - // Move it backwards once, since the end of the loop moves it forwards again anyway - i = --j; - - // Insert the node - if(parent) - { - node->parent = parent; - parent->children.push_back(node); - } - else - { - node->parent = 0; - nodes->push_back(node); - } - node = ConcreteNodePtr(); - } - else if(token->type == TID_LBRACKET) - { - node = std::make_shared(); - node->token = token->lexeme; - node->file = file; - node->line = token->line; - node->type = CNT_LBRACE; - - // Consume all the newlines - i = skipNewlines(i, end); - - // Insert the node - if(parent) - { - node->parent = parent; - parent->children.push_back(node); - } - else - { - node->parent = 0; - nodes->push_back(node); - } - - // Set the parent - parent = node.get(); - - // Change the state - state = READY; - - node = ConcreteNodePtr(); - } - else if(token->type == TID_RBRACKET) - { - // Go up one level if we can - if(parent) - parent = parent->parent; - - // If the parent is currently a { then go up again - if(parent && parent->type == CNT_LBRACE && parent->parent) - parent = parent->parent; - - node = std::make_shared(); - node->token = token->lexeme; - node->file = file; - node->line = token->line; - node->type = CNT_RBRACE; - - // Consume all the newlines - i = skipNewlines(i, end); - - // Insert the node - if(parent) - { - node->parent = parent; - parent->children.push_back(node); - } - else - { - node->parent = 0; - nodes->push_back(node); - } - - // Move up another level - if(parent) - parent = parent->parent; - - node = ConcreteNodePtr(); - state = READY; - } - else if(token->type == TID_VARIABLE) - { - node = std::make_shared(); - node->token = token->lexeme; - node->file = file; - node->line = token->line; - node->type = CNT_VARIABLE; - - // Insert the node - if(parent) - { - node->parent = parent; - parent->children.push_back(node); - } - else - { - node->parent = 0; - nodes->push_back(node); - } - node = ConcreteNodePtr(); - } - else if(token->type == TID_QUOTE) - { - node = std::make_shared(); - node->token = unquoted(token->lexeme); - node->file = file; - node->line = token->line; - node->type = CNT_QUOTE; - - // Insert the node - if(parent) - { - node->parent = parent; - parent->children.push_back(node); - } - else - { - node->parent = 0; - nodes->push_back(node); - } - node = ConcreteNodePtr(); - } - else if(token->type == TID_WORD) - { - node = std::make_shared(); - node->token = token->lexeme; - node->file = file; - node->line = token->line; - node->type = CNT_WORD; - - // Insert the node - if(parent) - { - node->parent = parent; - parent->children.push_back(node); - } - else - { - node->parent = 0; - nodes->push_back(node); - } - node = ConcreteNodePtr(); - } - break; - } - - ++i; - } - - return nodes; - } - - ConcreteNodeListPtr ScriptParser::parseChunk(const ScriptTokenList &tokens, const String& file) - { - auto nodes = std::make_shared(); - - ConcreteNodePtr node; - for(const auto& token : tokens) - { - switch(token.type) - { - case TID_VARIABLE: - node = std::make_shared(); - node->file = file; - node->line = token.line; - node->parent = 0; - node->token = token.lexeme; - node->type = CNT_VARIABLE; - break; - case TID_WORD: - node = std::make_shared(); - node->file = file; - node->line = token.line; - node->parent = 0; - node->token = token.lexeme; - node->type = CNT_WORD; - break; - case TID_QUOTE: - node = std::make_shared(); - node->file = file; - node->line = token.line; - node->parent = 0; - node->token= unquoted(token.lexeme); - node->type = CNT_QUOTE; - break; - default: - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, - Ogre::String("unexpected token") + token.lexeme + " at line " + - Ogre::StringConverter::toString(token.line), - "ScriptParser::parseChunk"); - } - - if(node) - nodes->push_back(node); - } - - return nodes; - } - - const ScriptToken *ScriptParser::getToken(ScriptTokenList::const_iterator i, ScriptTokenList::const_iterator end, int offset) - { - const ScriptToken *token = 0; - ScriptTokenList::const_iterator iter = i + offset; - if(iter != end) - token = &*i; - return token; - } - - ScriptTokenList::const_iterator ScriptParser::skipNewlines(ScriptTokenList::const_iterator i, ScriptTokenList::const_iterator end) - { - while(i != end && i->type == TID_NEWLINE) - ++i; - return i; - } - -} diff --git a/OgreMain/src/OgreScriptParser.h b/OgreMain/src/OgreScriptParser.h deleted file mode 100644 index c9c5a6e7ed2..00000000000 --- a/OgreMain/src/OgreScriptParser.h +++ /dev/null @@ -1,58 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __SCRIPTPARSER_H_ -#define __SCRIPTPARSER_H_ - -#include "OgreScriptLexer.h" -#include "OgreScriptCompiler.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup General - * @{ - */ - - class _OgrePrivate ScriptParser : public ScriptCompilerAlloc - { - public: - static ConcreteNodeListPtr parse(const ScriptTokenList &tokens, const String& file); - static ConcreteNodeListPtr parseChunk(const ScriptTokenList &tokens, const String& file); - private: - static const ScriptToken *getToken(ScriptTokenList::const_iterator i, ScriptTokenList::const_iterator end, int offset); - static ScriptTokenList::const_iterator skipNewlines(ScriptTokenList::const_iterator i, ScriptTokenList::const_iterator end); - }; - - /** @} */ - /** @} */ -} - -#endif diff --git a/OgreMain/src/OgreScriptTranslator.cpp b/OgreMain/src/OgreScriptTranslator.cpp deleted file mode 100644 index 32c41f44c3b..00000000000 --- a/OgreMain/src/OgreScriptTranslator.cpp +++ /dev/null @@ -1,5295 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" -#include "OgreBuiltinScriptTranslators.h" -#include "OgreGpuProgramManager.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreParticleSystemRenderer.h" -#include "OgreParticleEmitter.h" -#include "OgreParticleAffector.h" -#include "OgreCompositor.h" -#include "OgreCompositorManager.h" -#include "OgreCompositionTechnique.h" -#include "OgreCompositionTargetPass.h" -#include "OgreCompositionPass.h" -#include "OgreExternalTextureSourceManager.h" -#include "OgreLodStrategyManager.h" -#include "OgreDistanceLodStrategy.h" -#include "OgreDepthBuffer.h" -#include "OgreParticleSystem.h" -#include "OgreHighLevelGpuProgram.h" -#include "OgreGpuProgramUsage.h" - -namespace Ogre{ - static void applyTextureAliases(ScriptCompiler *compiler, const Material* mat, const NameValuePairList& aliasList) - { - for (auto t : mat->getTechniques()) - { - for (auto p : t->getPasses()) - { - for (auto tus : p->getTextureUnitStates()) - { - auto aliasIt = aliasList.find(tus->getName()); - if (aliasIt == aliasList.end()) - continue; - - ProcessResourceNameScriptCompilerEvent evt(ProcessResourceNameScriptCompilerEvent::TEXTURE, aliasIt->second); - compiler->_fireEvent(&evt, 0); - - if (tus->getNumFrames() > 1) - tus->setAnimatedTextureName(evt.mName, tus->getNumFrames(), - tus->getAnimationDuration()); - else - tus->setTextureName(evt.mName, tus->getTextureType()); - } - } - } - } - - static GpuProgramType translateIDToGpuProgramType(uint32 id) - { - switch (id) - { - case ID_VERTEX_PROGRAM: - default: - return GPT_VERTEX_PROGRAM; - case ID_GEOMETRY_PROGRAM: - return GPT_GEOMETRY_PROGRAM; - case ID_FRAGMENT_PROGRAM: - return GPT_FRAGMENT_PROGRAM; - case ID_TESSELLATION_HULL_PROGRAM: - return GPT_HULL_PROGRAM; - case ID_TESSELLATION_DOMAIN_PROGRAM: - return GPT_DOMAIN_PROGRAM; - case ID_COMPUTE_PROGRAM: - return GPT_COMPUTE_PROGRAM; - } - } - - String getPropertyName(const ScriptCompiler *compiler, uint32 id) - { - for(auto& kv : compiler->mIds) - if(kv.second == id) - return kv.first; - OgreAssertDbg(false, "should not get here"); - return "unknown"; - } - - template - bool getValue(const AbstractNodePtr &node, T& result); - template<> bool getValue(const AbstractNodePtr &node, float& result) - { - return StringConverter::parse(node->getString(), result); - } - template<> bool getValue(const AbstractNodePtr &node, double& result) - { - return StringConverter::parse(node->getString(), result); - } - template<> bool getValue(const AbstractNodePtr &node, bool& result) - { - return ScriptTranslator::getBoolean(node, &result); - } - template<> bool getValue(const AbstractNodePtr &node, uint32& result) - { - return StringConverter::parse(node->getString(), result); - } - template<> bool getValue(const AbstractNodePtr &node, int32& result) - { - return StringConverter::parse(node->getString(), result); - } - template<> bool getValue(const AbstractNodePtr &node, String& result) - { - return ScriptTranslator::getString(node, &result); - } - - template<> bool getValue(const AbstractNodePtr& node, CompareFunction& result) - { - return ScriptTranslator::getCompareFunction(node, &result); - } - - template<> bool getValue(const AbstractNodePtr& node, StencilOperation& result) - { - return ScriptTranslator::getStencilOp(node, &result); - } - - template<> bool getValue(const AbstractNodePtr& node, IlluminationStage& result) - { - if(node->type != ANT_ATOM) - return false; - - switch (static_cast(node.get())->id) - { - case ID_AMBIENT: - result = IS_AMBIENT; - return true; - case ID_PER_LIGHT: - result = IS_PER_LIGHT; - return true; - case ID_DECAL: - result = IS_DECAL; - return true; - default: - return false; - } - } - - template<> bool getValue(const AbstractNodePtr& node, SceneBlendType& result) - { - if(node->type != ANT_ATOM) - return false; - - switch (static_cast(node.get())->id) - { - case ID_ADD: - result = SBT_ADD; - break; - case ID_MODULATE: - result = SBT_MODULATE; - break; - case ID_COLOUR_BLEND: - result = SBT_TRANSPARENT_COLOUR; - break; - case ID_ALPHA_BLEND: - result = SBT_TRANSPARENT_ALPHA; - break; - default: - return false; - } - return true; - } - - template<> bool getValue(const AbstractNodePtr& node, SceneBlendOperation& result) - { - if(node->type != ANT_ATOM) - return false; - - switch (static_cast(node.get())->id) - { - case ID_ADD: - result = SBO_ADD; - break; - case ID_SUBTRACT: - result = SBO_SUBTRACT; - break; - case ID_REVERSE_SUBTRACT: - result = SBO_REVERSE_SUBTRACT; - break; - case ID_MIN: - result = SBO_MIN; - break; - case ID_MAX: - result = SBO_MAX; - break; - default: - return false; - } - return true; - } - - template<> bool getValue(const AbstractNodePtr& node, CullingMode& result) - { - if(node->type != ANT_ATOM) - return false; - - switch (static_cast(node.get())->id) - { - case ID_CLOCKWISE: - result = CULL_CLOCKWISE; - break; - case ID_ANTICLOCKWISE: - result = CULL_ANTICLOCKWISE; - break; - case ID_NONE: - result = CULL_NONE; - break; - default: - return false; - } - return true; - } - - template<> bool getValue(const AbstractNodePtr& node, ManualCullingMode& result) - { - if(node->type != ANT_ATOM) - return false; - - switch (static_cast(node.get())->id) - { - case ID_FRONT: - result = MANUAL_CULL_FRONT; - break; - case ID_BACK: - result = MANUAL_CULL_BACK; - break; - case ID_NONE: - result = MANUAL_CULL_NONE; - break; - default: - return false; - } - return true; - } - - template<> bool getValue(const AbstractNodePtr& node, ShadeOptions& result) - { - if(node->type != ANT_ATOM) - return false; - - switch (static_cast(node.get())->id) - { - case ID_FLAT: - result = SO_FLAT; - break; - case ID_GOURAUD: - result = SO_GOURAUD; - break; - case ID_PHONG: - result = SO_PHONG; - break; - default: - return false; - } - return true; - } - - template<> bool getValue(const AbstractNodePtr& node, PolygonMode& result) - { - if(node->type != ANT_ATOM) - return false; - - switch (static_cast(node.get())->id) - { - case ID_SOLID: - result = PM_SOLID; - break; - case ID_POINTS: - result = PM_POINTS; - break; - case ID_WIREFRAME: - result = PM_WIREFRAME; - break; - default: - return false; - } - return true; - } - - template<> bool getValue(const AbstractNodePtr& node, LayerBlendOperation& result) - { - if(node->type != ANT_ATOM) - return false; - - switch (static_cast(node.get())->id) - { - case ID_REPLACE: - result = LBO_REPLACE; - break; - case ID_ADD: - result = LBO_ADD; - break; - case ID_MODULATE: - result = LBO_MODULATE; - break; - case ID_ALPHA_BLEND: - result = LBO_ALPHA_BLEND; - break; - default: - return false; - } - return true; - } - - template<> bool getValue(const AbstractNodePtr& node, LayerBlendOperationEx& op) - { - if(node->type != ANT_ATOM) - return false; - - switch (static_cast(node.get())->id) - { - case ID_SOURCE1: - op = LBX_SOURCE1; - break; - case ID_SOURCE2: - op = LBX_SOURCE2; - break; - case ID_MODULATE: - op = LBX_MODULATE; - break; - case ID_MODULATE_X2: - op = LBX_MODULATE_X2; - break; - case ID_MODULATE_X4: - op = LBX_MODULATE_X4; - break; - case ID_ADD: - op = LBX_ADD; - break; - case ID_ADD_SIGNED: - op = LBX_ADD_SIGNED; - break; - case ID_ADD_SMOOTH: - op = LBX_ADD_SMOOTH; - break; - case ID_SUBTRACT: - op = LBX_SUBTRACT; - break; - case ID_BLEND_DIFFUSE_ALPHA: - op = LBX_BLEND_DIFFUSE_ALPHA; - break; - case ID_BLEND_TEXTURE_ALPHA: - op = LBX_BLEND_TEXTURE_ALPHA; - break; - case ID_BLEND_CURRENT_ALPHA: - op = LBX_BLEND_CURRENT_ALPHA; - break; - case ID_BLEND_MANUAL: - op = LBX_BLEND_MANUAL; - break; - case ID_DOT_PRODUCT: - op = LBX_DOTPRODUCT; - break; - case ID_BLEND_DIFFUSE_COLOUR: - op = LBX_BLEND_DIFFUSE_COLOUR; - break; - default: - return false; - } - return true; - } - - template<> bool getValue(const AbstractNodePtr& node, LayerBlendSource& source1) - { - if(node->type != ANT_ATOM) - return false; - - switch (static_cast(node.get())->id) - { - case ID_SRC_CURRENT: - source1 = LBS_CURRENT; - break; - case ID_SRC_TEXTURE: - source1 = LBS_TEXTURE; - break; - case ID_SRC_DIFFUSE: - source1 = LBS_DIFFUSE; - break; - case ID_SRC_SPECULAR: - source1 = LBS_SPECULAR; - break; - case ID_SRC_MANUAL: - source1 = LBS_MANUAL; - break; - default: - return false; - } - return true; - } - - template<> bool getValue(const AbstractNodePtr& node, CompositionTargetPass::InputMode& result) - { - if(node->type != ANT_ATOM) - return false; - - switch (static_cast(node.get())->id) - { - case ID_NONE: - result = CompositionTargetPass::IM_NONE; - break; - case ID_PREVIOUS: - result = CompositionTargetPass::IM_PREVIOUS; - break; - default: - return false; - } - return true; - } - - template<> bool getValue(const AbstractNodePtr& node, FilterOptions& tmip) - { - if(node->type != ANT_ATOM) - return false; - - switch (static_cast(node.get())->id) - { - case ID_NONE: - tmip = FO_NONE; - break; - case ID_POINT: - tmip = FO_POINT; - break; - case ID_LINEAR: - tmip = FO_LINEAR; - break; - case ID_ANISOTROPIC: - tmip = FO_ANISOTROPIC; - break; - default: - return false; - } - return true; - } - - template<> bool getValue(const AbstractNodePtr& node, TextureAddressingMode& result) - { - if(node->type != ANT_ATOM) - return false; - - switch (static_cast(node.get())->id) - { - case ID_WRAP: - result = TextureUnitState::TAM_WRAP; - break; - case ID_CLAMP: - result = TextureUnitState::TAM_CLAMP; - break; - case ID_MIRROR: - result = TextureUnitState::TAM_MIRROR; - break; - case ID_BORDER: - result = TextureUnitState::TAM_BORDER; - break; - default: - return false; - } - return true; - } - - template - static bool getValue(PropertyAbstractNode* prop, ScriptCompiler *compiler, T& val) - { - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - } - else if(prop->values.size() > 1) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - getPropertyName(compiler, prop->id) + - " must have at most 1 argument"); - } - else - { - if (getValue(prop->values.front(), val)) - return true; - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - prop->values.front()->getValue() + " is not a valid value for " + - getPropertyName(compiler, prop->id)); - } - - return false; - } - - template - static bool _getVector(AbstractNodeList::const_iterator i, AbstractNodeList::const_iterator end, - std::vector& vals, size_t count) - { - vals.reserve(count); - size_t n = 0; - while (n < count) - { - if (i != end) - { - T v; - if (!getValue(*i++, v)) - return false; - vals.push_back(v); - } - ++n; - } - - vals.resize(count); - return true; - } - - static GpuProgramType getProgramType(int id) - { - switch(id) - { - default: - assert(false); - OGRE_FALLTHROUGH; - case ID_VERTEX_PROGRAM: - case ID_VERTEX_PROGRAM_REF: - return GPT_VERTEX_PROGRAM; - case ID_FRAGMENT_PROGRAM: - case ID_FRAGMENT_PROGRAM_REF: - return GPT_FRAGMENT_PROGRAM; - case ID_GEOMETRY_PROGRAM: - case ID_GEOMETRY_PROGRAM_REF: - return GPT_GEOMETRY_PROGRAM; - case ID_TESSELLATION_DOMAIN_PROGRAM: - case ID_TESSELLATION_DOMAIN_PROGRAM_REF: - return GPT_DOMAIN_PROGRAM; - case ID_TESSELLATION_HULL_PROGRAM: - case ID_TESSELLATION_HULL_PROGRAM_REF: - return GPT_HULL_PROGRAM; - case ID_COMPUTE_PROGRAM: - case ID_COMPUTE_PROGRAM_REF: - return GPT_COMPUTE_PROGRAM; - } - } - - void ScriptTranslator::processNode(ScriptCompiler *compiler, const AbstractNodePtr &node) - { - if(node->type != ANT_OBJECT) - return; - - // Abstract objects are completely skipped - if((static_cast(node.get()))->abstract) - return; - - // Retrieve the translator to use - ScriptTranslator *translator = - ScriptCompilerManager::getSingleton().getTranslator(node); - - if(translator) - translator->translate(compiler, node); - else - compiler->addError(ScriptCompiler::CE_UNEXPECTEDTOKEN, node->file, node->line, - "token \"" + static_cast(node.get())->cls + "\" is not recognized"); - } - //------------------------------------------------------------------------- - AbstractNodeList::const_iterator ScriptTranslator::getNodeAt(const AbstractNodeList &nodes, size_t index) - { - if(index >= nodes.size()) - return nodes.end(); - - return std::next(nodes.begin(), index); - } - //------------------------------------------------------------------------- - bool ScriptTranslator::getBoolean(const AbstractNodePtr &node, bool *result) - { - if (node->type != ANT_ATOM) - return false; - AtomAbstractNode *atom = (AtomAbstractNode*)node.get(); - if (atom->id == 1 || atom->id == 2) - { - *result = atom->id == 1 ? true : false; - return true; - } - // return false; - return false; - } - //------------------------------------------------------------------------- - bool ScriptTranslator::getString(const AbstractNodePtr &node, String *result) - { - if(node->type != ANT_ATOM) - return false; - AtomAbstractNode *atom = (AtomAbstractNode*)node.get(); - *result = atom->value; - return true; - } - //------------------------------------------------------------------------- - bool ScriptTranslator::getFloat(const Ogre::AbstractNodePtr &node, float *result) - { - return StringConverter::parse(node->getString(), *result); - } - //------------------------------------------------------------------------- - bool ScriptTranslator::getDouble(const Ogre::AbstractNodePtr &node, double *result) - { - return StringConverter::parse(node->getString(), *result); - } - //------------------------------------------------------------------------- - bool ScriptTranslator::getInt(const Ogre::AbstractNodePtr &node, int *result) - { - return StringConverter::parse(node->getString(), *result); - } - //------------------------------------------------------------------------- - bool ScriptTranslator::getUInt(const Ogre::AbstractNodePtr &node, uint *result) - { - return StringConverter::parse(node->getString(), *result); - } - //------------------------------------------------------------------------- - bool ScriptTranslator::getColour(AbstractNodeList::const_iterator i, AbstractNodeList::const_iterator end, ColourValue *result, int maxEntries) - { - int n = 0; - while(i != end && n < maxEntries) - { - float v = 0; - if(getFloat(*i, &v)) - { - switch(n) - { - case 0: - result->r = v; - break; - case 1: - result->g = v; - break; - case 2: - result->b = v; - break; - case 3: - result->a = v; - break; - } - } - else - { - return false; - } - ++n; - ++i; - } - // return error if we found less than rgb before end, unless constrained - return (n >= 3 || n == maxEntries); - } - //------------------------------------------------------------------------- - bool ScriptTranslator::getSceneBlendFactor(const Ogre::AbstractNodePtr &node, Ogre::SceneBlendFactor *sbf) - { - if(node->type != ANT_ATOM) - return false; - AtomAbstractNode *atom = (AtomAbstractNode*)node.get(); - switch(atom->id) - { - case ID_ONE: - *sbf = SBF_ONE; - break; - case ID_ZERO: - *sbf = SBF_ZERO; - break; - case ID_DEST_COLOUR: - *sbf = SBF_DEST_COLOUR; - break; - case ID_DEST_ALPHA: - *sbf = SBF_DEST_ALPHA; - break; - case ID_SRC_ALPHA: - *sbf = SBF_SOURCE_ALPHA; - break; - case ID_SRC_COLOUR: - *sbf = SBF_SOURCE_COLOUR; - break; - case ID_ONE_MINUS_DEST_COLOUR: - *sbf = SBF_ONE_MINUS_DEST_COLOUR; - break; - case ID_ONE_MINUS_SRC_COLOUR: - *sbf = SBF_ONE_MINUS_SOURCE_COLOUR; - break; - case ID_ONE_MINUS_DEST_ALPHA: - *sbf = SBF_ONE_MINUS_DEST_ALPHA; - break; - case ID_ONE_MINUS_SRC_ALPHA: - *sbf = SBF_ONE_MINUS_SOURCE_ALPHA; - break; - default: - return false; - } - return true; - } - //------------------------------------------------------------------------- - bool ScriptTranslator::getCompareFunction(const AbstractNodePtr &node, CompareFunction *func) - { - if(node->type != ANT_ATOM) - return false; - AtomAbstractNode *atom = (AtomAbstractNode*)node.get(); - switch(atom->id) - { - case ID_ALWAYS_FAIL: - *func = CMPF_ALWAYS_FAIL; - break; - case ID_ALWAYS_PASS: - *func = CMPF_ALWAYS_PASS; - break; - case ID_LESS: - *func = CMPF_LESS; - break; - case ID_LESS_EQUAL: - *func = CMPF_LESS_EQUAL; - break; - case ID_EQUAL: - *func = CMPF_EQUAL; - break; - case ID_NOT_EQUAL: - *func = CMPF_NOT_EQUAL; - break; - case ID_GREATER_EQUAL: - *func = CMPF_GREATER_EQUAL; - break; - case ID_GREATER: - *func = CMPF_GREATER; - break; - default: - return false; - } - return true; - } - //------------------------------------------------------------------------- - bool ScriptTranslator::getMatrix4(AbstractNodeList::const_iterator i, AbstractNodeList::const_iterator end, Matrix4 *m) - { - int n = 0; - while (i != end && n < 16) - { - Real r = 0; - if (!getReal(*i, &r)) - return false; - - (*m)[n/4][n%4] = r; - ++i; - ++n; - } - return n == 16; - } - //------------------------------------------------------------------------- - bool ScriptTranslator::getInts(AbstractNodeList::const_iterator i, AbstractNodeList::const_iterator end, int *vals, int count) - { - bool success = true; - int n = 0; - while (n < count) - { - if (i != end) - { - int v = 0; - if (getInt(*i, &v)) - vals[n] = v; - else - break; - ++i; - } - else - vals[n] = 0; - ++n; - } - - if (n < count) - success = false; - - return success; - } - bool ScriptTranslator::getVector(AbstractNodeList::const_iterator i, AbstractNodeList::const_iterator end, std::vector& vals, size_t count) - { - return _getVector(i, end, vals, count); - } - //---------------------------------------------------------------------------- - bool ScriptTranslator::getFloats(AbstractNodeList::const_iterator i, AbstractNodeList::const_iterator end, float *vals, int count) - { - bool success = true; - int n = 0; - while (n < count) - { - if (i != end) - { - float v = 0; - if (getFloat(*i, &v)) - vals[n] = v; - else - break; - ++i; - } - else - vals[n] = 0; - ++n; - } - - if (n < count) - success = false; - - return success; - } - bool ScriptTranslator::getVector(AbstractNodeList::const_iterator i, AbstractNodeList::const_iterator end, std::vector& vals, size_t count) - { - return _getVector(i, end, vals, count); - } - //---------------------------------------------------------------------------- - bool ScriptTranslator::getDoubles(AbstractNodeList::const_iterator i, AbstractNodeList::const_iterator end, double *vals, int count) - { - bool success = true; - int n = 0; - while (n < count) - { - if (i != end) - { - double v = 0; - if (getDouble(*i, &v)) - vals[n] = v; - else - break; - ++i; - } - else - vals[n] = 0; - ++n; - } - - if (n < count) - success = false; - - return success; - } - //---------------------------------------------------------------------------- - bool ScriptTranslator::getUInts(AbstractNodeList::const_iterator i, AbstractNodeList::const_iterator end, uint *vals, int count) - { - bool success = true; - int n = 0; - while (n < count) - { - if (i != end) - { - uint v = 0; - if (getUInt(*i, &v)) - vals[n] = v; - else - break; - ++i; - } - else - vals[n] = 0; - ++n; - } - - if (n < count) - success = false; - - return success; - } - //---------------------------------------------------------------------------- - bool ScriptTranslator::getBooleans(AbstractNodeList::const_iterator i, AbstractNodeList::const_iterator end, uint *vals, int count) - { - bool success = true; - int n = 0; - while (n < count) - { - if (i != end) - { - bool v = false; - if (getBoolean(*i, &v)) - vals[n] = (v != 0); - else - break; - ++i; - } - else - vals[n] = false; - ++n; - } - - if (n < count) - success = false; - - return success; - } - //------------------------------------------------------------------------- - bool ScriptTranslator::getStencilOp(const Ogre::AbstractNodePtr &node, Ogre::StencilOperation *op) - { - if(node->type != ANT_ATOM) - return false; - AtomAbstractNode *atom = (AtomAbstractNode*)node.get(); - switch(atom->id) - { - case ID_KEEP: - *op = SOP_KEEP; - break; - case ID_ZERO: - *op = SOP_ZERO; - break; - case ID_REPLACE: - *op = SOP_REPLACE; - break; - case ID_INCREMENT: - *op = SOP_INCREMENT; - break; - case ID_DECREMENT: - *op = SOP_DECREMENT; - break; - case ID_INCREMENT_WRAP: - *op = SOP_INCREMENT_WRAP; - break; - case ID_DECREMENT_WRAP: - *op = SOP_DECREMENT_WRAP; - break; - case ID_INVERT: - *op = SOP_INVERT; - break; - default: - return false; - } - return true; - } - //--------------------------------------------------------------------- - bool ScriptTranslator::getConstantType(AbstractNodeList::const_iterator i, GpuConstantType *op) - { - const String& val = (*i)->getString(); - if(val.empty()) - return false; - - if (val.find("float") != String::npos) - { - int count = 1; - if (val.size() == 6) - count = StringConverter::parseInt(val.substr(5)); - else if (val.size() > 6) - return false; - - if (count > 4 || count == 0) - return false; - - *op = (GpuConstantType)(GCT_FLOAT1 + count - 1); - } - else if (val.find("double") != String::npos) - { - int count = 1; - if (val.size() == 7) - count = StringConverter::parseInt(val.substr(6)); - else if (val.size() > 7) - return false; - - if (count > 4 || count == 0) - return false; - - *op = (GpuConstantType)(GCT_DOUBLE1 + count - 1); - } - else if (val.find("uint") != String::npos) - { - int count = 1; - if (val.size() == 5) - count = StringConverter::parseInt(val.substr(4)); - else if (val.size() > 5) - return false; - - if (count > 4 || count == 0) - return false; - - *op = (GpuConstantType)(GCT_UINT1 + count - 1); - } - else if (val.find("int") != String::npos) - { - int count = 1; - if (val.size() == 4) - count = StringConverter::parseInt(val.substr(3)); - else if (val.size() > 4) - return false; - - if (count > 4 || count == 0) - return false; - - *op = (GpuConstantType)(GCT_INT1 + count - 1); - } - else if (val.find("bool") != String::npos) - { - int count = 1; - if (val.size() == 5) - count = StringConverter::parseInt(val.substr(4)); - else if (val.size() > 5) - return false; - - if (count > 4 || count == 0) - return false; - - *op = (GpuConstantType)(GCT_BOOL1 + count - 1); - } - else if(val.find("matrix") != String::npos) - { - int count1, count2; - - if (val.size() == 9) - { - count1 = StringConverter::parseInt(val.substr(6, 1)); - count2 = StringConverter::parseInt(val.substr(8, 1)); - } - else - return false; - - if (count1 > 4 || count1 < 2 || count2 > 4 || count2 < 2) - return false; - - switch(count1) - { - case 2: - *op = (GpuConstantType)(GCT_MATRIX_2X2 + count2 - 2); - break; - case 3: - *op = (GpuConstantType)(GCT_MATRIX_3X2 + count2 - 2); - break; - case 4: - *op = (GpuConstantType)(GCT_MATRIX_4X2 + count2 - 2); - break; - } - - } - else - { - return false; - } - - return true; - } - - /************************************************************************** - * MaterialTranslator - *************************************************************************/ - MaterialTranslator::MaterialTranslator() - :mMaterial(0) - { - } - //------------------------------------------------------------------------- - void MaterialTranslator::translate(ScriptCompiler *compiler, const AbstractNodePtr &node) - { - ObjectAbstractNode *obj = static_cast(node.get()); - if(obj->name.empty()) - compiler->addError(ScriptCompiler::CE_OBJECTNAMEEXPECTED, obj->file, obj->line); - - // Create a material with the given name - CreateMaterialScriptCompilerEvent evt(node->file, obj->name, compiler->getResourceGroup()); - bool processed = compiler->_fireEvent(&evt, (void*)&mMaterial); - - if(!processed) - { - mMaterial = MaterialManager::getSingleton().create(obj->name, compiler->getResourceGroup()).get(); - } - - if(!mMaterial) - { - compiler->addError(ScriptCompiler::CE_OBJECTALLOCATIONERROR, obj->file, obj->line, obj->name); - return; - } - - mMaterial->removeAllTechniques(); - obj->context = mMaterial; - mMaterial->_notifyOrigin(obj->file); - - bool bval; - String sval; - - for(auto & i : obj->children) - { - if(i->type == ANT_PROPERTY) - { - PropertyAbstractNode *prop = static_cast(i.get()); - switch(prop->id) - { - case ID_LOD_VALUES: - { - Material::LodValueList lods; - for(AbstractNodeList::iterator j = prop->values.begin(); j != prop->values.end(); ++j) - { - Real v = 0; - if(getReal(*j, &v)) - lods.push_back(v); - else - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - "lod_values expects only numbers as arguments"); - } - mMaterial->setLodLevels(lods); - } - break; - case ID_LOD_DISTANCES: - { - // Deprecated! Only for backwards compatibility. - // Set strategy hard-coded to 'distance' strategy, since that was the only one available back then, - // when using this material keyword was still current. - LodStrategy *strategy = DistanceLodSphereStrategy::getSingletonPtr(); - mMaterial->setLodStrategy(strategy); - - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, prop->file, - prop->line, - "lod_distances. Use lod_values."); - // Read in LOD distances - Material::LodValueList lods; - for(auto& j : prop->values) - { - Real v = 0; - if(getReal(j, &v)) - lods.push_back(v); - else - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - "lod_values expects only numbers as arguments"); - } - mMaterial->setLodLevels(lods); - } - break; - case ID_LOD_STRATEGY: - if(getValue(prop, compiler, sval)) - { - if (sval == "Distance" || sval == "PixelCount") - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, prop->file, prop->line, - sval + ". use distance_box or pixel_count"); - - LodStrategy* strategy = LodStrategyManager::getSingleton().getStrategy(sval); - if (strategy) - mMaterial->setLodStrategy(strategy); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, sval); - } - break; - case ID_RECEIVE_SHADOWS: - if(getValue(prop, compiler, bval)) - mMaterial->setReceiveShadows(bval); - break; - case ID_TRANSPARENCY_CASTS_SHADOWS: - if(getValue(prop, compiler, bval)) - mMaterial->setTransparencyCastsShadows(bval); - break; - case ID_SET_TEXTURE_ALIAS: - if(prop->values.size() != 2) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "set_texture_alias must have 2 string arguments"); - } - else - { - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, prop->file, prop->line, - "set_texture_alias. Use 'set $variable value'"); - - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), i1 = getNodeAt(prop->values, 1); - String name, value; - if(getString(*i0, &name) && getString(*i1, &value)) - mTextureAliases.insert(std::make_pair(name, value)); - } - break; - default: - compiler->addError(ScriptCompiler::CE_UNEXPECTEDTOKEN, prop->file, prop->line, - "token \"" + prop->name + "\" is not recognized"); - } - } - else if(i->type == ANT_OBJECT) - { - processNode(compiler, i); - } - } - - applyTextureAliases(compiler, mMaterial, mTextureAliases); - mTextureAliases.clear(); - } - - /************************************************************************** - * TechniqueTranslator - *************************************************************************/ - TechniqueTranslator::TechniqueTranslator() - :mTechnique(0) - { - } - //------------------------------------------------------------------------- - void TechniqueTranslator::translate(ScriptCompiler *compiler, const AbstractNodePtr &node) - { - ObjectAbstractNode *obj = static_cast(node.get()); - - // Create the technique from the material - Ogre::Material *material = Ogre::any_cast(obj->parent->context); - mTechnique = material->createTechnique(); - obj->context = mTechnique; - - // Get the name of the technique - if(!obj->name.empty()) - mTechnique->setName(obj->name); - - uint32 uival; - String sval; - - // Set the properties for the material - for(auto & i : obj->children) - { - if(i->type == ANT_PROPERTY) - { - PropertyAbstractNode *prop = static_cast(i.get()); - switch(prop->id) - { - case ID_SCHEME: - if(getValue(prop, compiler, sval)) - mTechnique->setSchemeName(sval); - break; - case ID_LOD_INDEX: - if(getValue(prop, compiler, uival)) - mTechnique->setLodIndex(static_cast(uival)); - break; - case ID_SHADOW_CASTER_MATERIAL: - if(getValue(prop, compiler, sval)) - { - ProcessResourceNameScriptCompilerEvent evt(ProcessResourceNameScriptCompilerEvent::MATERIAL, sval); - compiler->_fireEvent(&evt, 0); - mTechnique->setShadowCasterMaterial(evt.mName); // Use the processed name - } - break; - case ID_SHADOW_RECEIVER_MATERIAL: - if(getValue(prop, compiler, sval)) - { - ProcessResourceNameScriptCompilerEvent evt(ProcessResourceNameScriptCompilerEvent::MATERIAL, sval); - compiler->_fireEvent(&evt, 0); - mTechnique->setShadowReceiverMaterial(evt.mName); // Use the processed name - } - break; - case ID_GPU_VENDOR_RULE: - if(prop->values.size() < 2) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line, - "gpu_vendor_rule must have 2 arguments"); - } - else if(prop->values.size() > 2) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "gpu_vendor_rule must have 2 arguments"); - } - else - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0); - AbstractNodeList::const_iterator i1 = getNodeAt(prop->values, 1); - - Technique::GPUVendorRule rule; - if ((*i0)->type == ANT_ATOM) - { - AtomAbstractNode *atom0 = (AtomAbstractNode*)(*i0).get(); - if (atom0->id == ID_INCLUDE) - { - rule.includeOrExclude = Technique::INCLUDE; - } - else if (atom0->id == ID_EXCLUDE) - { - rule.includeOrExclude = Technique::EXCLUDE; - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "gpu_vendor_rule cannot accept \"" + (*i0)->getValue() + "\" as first argument"); - } - - String vendor; - if(!getString(*i1, &vendor)) - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "gpu_vendor_rule cannot accept \"" + (*i1)->getValue() + "\" as second argument"); - - rule.vendor = RenderSystemCapabilities::vendorFromString(vendor); - - if (rule.vendor != GPU_UNKNOWN) - { - mTechnique->addGPUVendorRule(rule); - } - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "gpu_vendor_rule cannot accept \"" + (*i0)->getValue() + "\" as first argument"); - } - - } - break; - case ID_GPU_DEVICE_RULE: - if(prop->values.size() < 2) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line, - "gpu_device_rule must have at least 2 arguments"); - } - else if(prop->values.size() > 3) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "gpu_device_rule must have at most 3 arguments"); - } - else - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0); - AbstractNodeList::const_iterator i1 = getNodeAt(prop->values, 1); - - Technique::GPUDeviceNameRule rule; - if ((*i0)->type == ANT_ATOM) - { - AtomAbstractNode *atom0 = (AtomAbstractNode*)(*i0).get(); - if (atom0->id == ID_INCLUDE) - { - rule.includeOrExclude = Technique::INCLUDE; - } - else if (atom0->id == ID_EXCLUDE) - { - rule.includeOrExclude = Technique::EXCLUDE; - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "gpu_device_rule cannot accept \"" + (*i0)->getValue() + "\" as first argument"); - } - - if(!getString(*i1, &rule.devicePattern)) - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "gpu_device_rule cannot accept \"" + (*i1)->getValue() + "\" as second argument"); - - if (prop->values.size() == 3) - { - AbstractNodeList::const_iterator i2 = getNodeAt(prop->values, 2); - if (!getBoolean(*i2, &rule.caseSensitive)) - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "gpu_device_rule third argument must be \"true\", \"false\", \"yes\", \"no\", \"on\", or \"off\""); - } - - mTechnique->addGPUDeviceNameRule(rule); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "gpu_device_rule cannot accept \"" + (*i0)->getValue() + "\" as first argument"); - } - - } - break; - default: - compiler->addError(ScriptCompiler::CE_UNEXPECTEDTOKEN, prop->file, prop->line, - "token \"" + prop->name + "\" is not recognized"); - } - } - else if(i->type == ANT_OBJECT) - { - processNode(compiler, i); - } - } - } - - /************************************************************************** - * PassTranslator - *************************************************************************/ - PassTranslator::PassTranslator() - :mPass(0) - { - } - //------------------------------------------------------------------------- - void PassTranslator::translate(ScriptCompiler *compiler, const AbstractNodePtr &node) - { - ObjectAbstractNode *obj = static_cast(node.get()); - - Technique *technique = any_cast(obj->parent->context); - mPass = technique->createPass(); - obj->context = mPass; - - // Get the name of the technique - if(!obj->name.empty()) - mPass->setName(obj->name); - - Real fval; - bool bval; - uint32 uival; - - // Set the properties for the material - for(auto & i : obj->children) - { - if(i->type == ANT_PROPERTY) - { - PropertyAbstractNode *prop = static_cast(i.get()); - switch(prop->id) - { - case ID_AMBIENT: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line); - } - else if(prop->values.size() > 4) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "ambient must have at most 4 parameters"); - } - else - { - if(prop->values.front()->type == ANT_ATOM && - ((AtomAbstractNode*)prop->values.front().get())->id == ID_VERTEXCOLOUR) - { - mPass->setVertexColourTracking(mPass->getVertexColourTracking() | TVC_AMBIENT); - } - else - { - ColourValue val = ColourValue::White; - if(getColour(prop->values.begin(), prop->values.end(), &val)) - mPass->setAmbient(val); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "ambient requires 3 or 4 colour arguments, or a \"vertexcolour\" directive"); - } - } - break; - case ID_DIFFUSE: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line); - } - else if(prop->values.size() > 4) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "diffuse must have at most 4 arguments"); - } - else - { - if(prop->values.front()->type == ANT_ATOM && - ((AtomAbstractNode*)prop->values.front().get())->id == ID_VERTEXCOLOUR) - { - mPass->setVertexColourTracking(mPass->getVertexColourTracking() | TVC_DIFFUSE); - } - else - { - ColourValue val = ColourValue::White; - if(getColour(prop->values.begin(), prop->values.end(), &val)) - mPass->setDiffuse(val); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "diffuse requires 3 or 4 colour arguments, or a \"vertexcolour\" directive"); - } - } - break; - case ID_SPECULAR: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line); - } - else if(prop->values.size() > 5) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "specular must have at most 5 arguments"); - } - else - { - if(prop->values.front()->type == ANT_ATOM && - ((AtomAbstractNode*)prop->values.front().get())->id == ID_VERTEXCOLOUR) - { - mPass->setVertexColourTracking(mPass->getVertexColourTracking() | TVC_SPECULAR); - - if(prop->values.size() >= 2) - { - Real val = 0; - if(getReal(prop->values.back(), &val)) - mPass->setShininess(val); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "specular does not support \"" + prop->values.back()->getValue() + "\" as its second argument"); - } - } - else - { - if(prop->values.size() < 4) - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - "specular expects at least 4 arguments"); - } - else - { - ColourValue val; - if(getColour(prop->values.begin(), prop->values.end(), &val)) - { - if(prop->values.size() == 4) - { - mPass->setShininess(val.a); - val.a = 1.0f; - mPass->setSpecular(val); - } - else - { - mPass->setSpecular(val); - - Real shininess; - if(getReal(*getNodeAt(prop->values, 4), &shininess)) - mPass->setShininess(shininess); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "specular fourth argument must be a valid number for shininess attribute"); - } - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "specular must have first 3 arguments be a valid colour"); - } - } - - } - } - break; - case ID_EMISSIVE: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line); - } - else if(prop->values.size() > 4) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "emissive must have at most 4 arguments"); - } - else - { - if(prop->values.front()->type == ANT_ATOM && - ((AtomAbstractNode*)prop->values.front().get())->id == ID_VERTEXCOLOUR) - { - mPass->setVertexColourTracking(mPass->getVertexColourTracking() | TVC_EMISSIVE); - } - else - { - ColourValue val(0.0f, 0.0f, 0.0f, 1.0f); - if(getColour(prop->values.begin(), prop->values.end(), &val)) - mPass->setSelfIllumination(val); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "emissive requires 3 or 4 colour arguments, or a \"vertexcolour\" directive"); - } - } - break; - case ID_SCENE_BLEND: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - } - else if(prop->values.size() > 2) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "scene_blend supports at most 2 arguments"); - } - else if(prop->values.size() == 1) - { - SceneBlendType enval; - if(getValue(prop->values.front(), enval)) - { - mPass->setSceneBlending(enval); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "scene_blend does not support \"" + prop->values.front()->getValue() + "\" for argument 1"); - } - } - else - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), i1 = getNodeAt(prop->values, 1); - SceneBlendFactor sbf0, sbf1; - if(getSceneBlendFactor(*i0, &sbf0) && getSceneBlendFactor(*i1, &sbf1)) - { - mPass->setSceneBlending(sbf0, sbf1); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "scene_blend does not support \"" + (*i0)->getValue() + "\" and \"" + (*i1)->getValue() + "\" as arguments"); - } - } - break; - case ID_SEPARATE_SCENE_BLEND: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - } - else if(prop->values.size() == 3) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "separate_scene_blend must have 2 or 4 arguments"); - } - else if(prop->values.size() > 4) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "separate_scene_blend must have 2 or 4 arguments"); - } - else if(prop->values.size() == 2) - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), i1 = getNodeAt(prop->values, 1); - SceneBlendType sbt0, sbt1; - if (getValue(*i0, sbt0) && getValue(*i1, sbt1)) - { - mPass->setSeparateSceneBlending(sbt0, sbt1); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "separate_scene_blend does not support \"" + (*i0)->getValue() + "\" as argument 1"); - } - } - else - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), i1 = getNodeAt(prop->values, 1), - i2 = getNodeAt(prop->values, 2), i3 = getNodeAt(prop->values, 3); - if((*i0)->type == ANT_ATOM && (*i1)->type == ANT_ATOM && (*i2)->type == ANT_ATOM && (*i3)->type == ANT_ATOM) - { - SceneBlendFactor sbf0, sbf1, sbf2, sbf3; - if(getSceneBlendFactor(*i0, &sbf0) && getSceneBlendFactor(*i1, &sbf1) && getSceneBlendFactor(*i2, &sbf2) && - getSceneBlendFactor(*i3, &sbf3)) - { - mPass->setSeparateSceneBlending(sbf0, sbf1, sbf2, sbf3); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "one of the arguments to separate_scene_blend is not a valid scene blend factor directive"); - } - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "one of the arguments to separate_scene_blend is not a valid scene blend factor directive"); - } - } - break; - case ID_SCENE_BLEND_OP: - SceneBlendOperation sop; - if(getValue(prop, compiler, sop)) - mPass->setSceneBlendingOperation(sop); - break; - case ID_SEPARATE_SCENE_BLEND_OP: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - } - else if(prop->values.size() != 2) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "separate_scene_blend_op must have 2 arguments"); - } - else - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), i1 = getNodeAt(prop->values, 1); - SceneBlendOperation op, alphaOp; - if(getValue(*i0, op) && getValue(*i1, alphaOp)) - { - mPass->setSeparateSceneBlendingOperation(op, alphaOp); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - prop->values.front()->getValue() + ": unrecognized argument"); - } - } - break; - case ID_DEPTH_CHECK: - if(getValue(prop, compiler, bval)) - mPass->setDepthCheckEnabled(bval); - break; - case ID_DEPTH_WRITE: - if(getValue(prop, compiler, bval)) - mPass->setDepthWriteEnabled(bval); - break; - case ID_DEPTH_BIAS: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - } - else if(prop->values.size() > 2) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "depth_bias must have at most 2 arguments"); - } - else - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), i1 = getNodeAt(prop->values, 1); - float val0, val1 = 0.0f; - if(getFloat(*i0, &val0)) - { - if(i1 != prop->values.end()) - getFloat(*i1, &val1); - mPass->setDepthBias(val0, val1); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "depth_bias does not support \"" + (*i0)->getValue() + "\" for argument 1"); - } - } - break; - case ID_DEPTH_FUNC: - CompareFunction dfunc; - if(getValue(prop, compiler, dfunc)) - mPass->setDepthFunction(dfunc); - break; - case ID_ITERATION_DEPTH_BIAS: - if(getValue(prop, compiler, fval)) - mPass->setIterationDepthBias(fval); - break; - case ID_ALPHA_REJECTION: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - } - else if(prop->values.size() > 2) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "alpha_rejection must have at most 2 arguments"); - } - else - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), i1 = getNodeAt(prop->values, 1); - CompareFunction func; - if(getCompareFunction(*i0, &func)) - { - if(i1 != prop->values.end()) - { - uint32 val = 0; - if(getUInt(*i1, &val)) - mPass->setAlphaRejectSettings(func, static_cast(val)); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*i1)->getValue() + " is not a valid integer"); - } - else - mPass->setAlphaRejectFunction(func); - } - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*i0)->getValue() + " is not a valid CompareFunction"); - } - break; - case ID_ALPHA_TO_COVERAGE: - if(getValue(prop, compiler, bval)) - mPass->setAlphaToCoverageEnabled(bval); - break; - case ID_LIGHT_SCISSOR: - if(getValue(prop, compiler, bval)) - mPass->setLightScissoringEnabled(bval); - break; - case ID_LIGHT_CLIP_PLANES: - if(getValue(prop, compiler, bval)) - mPass->setLightClipPlanesEnabled(bval); - break; - case ID_TRANSPARENT_SORTING: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - } - else if(prop->values.size() > 1) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "transparent_sorting must have at most 1 argument"); - } - else - { - bool val = true; - if(getBoolean(prop->values.front(), &val)) - { - mPass->setTransparentSortingEnabled(val); - mPass->setTransparentSortingForced(false); - } - else - { - String val2; - if (prop->values.front()->getString()=="force") - { - mPass->setTransparentSortingEnabled(true); - mPass->setTransparentSortingForced(true); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - prop->values.front()->getValue() + " must be boolean or force"); - } - } - } - break; - case ID_ILLUMINATION_STAGE: - IlluminationStage is; - if(getValue(prop, compiler, is)) - mPass->setIlluminationStage(is); - break; - case ID_CULL_HARDWARE: - CullingMode cmode; - if(getValue(prop, compiler, cmode)) - mPass->setCullingMode(cmode); - break; - case ID_CULL_SOFTWARE: - ManualCullingMode mmode; - if(getValue(prop, compiler, mmode)) - mPass->setManualCullingMode(mmode); - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, prop->file, prop->line, - prop->name + ". Only used by the BSP scene manager."); - break; - case ID_LIGHTING: - if(getValue(prop, compiler, bval)) - mPass->setLightingEnabled(bval); - break; - case ID_SHADING: - ShadeOptions smode; - if(getValue(prop, compiler, smode)) - mPass->setShadingMode(smode); - break; - case ID_POLYGON_MODE: - PolygonMode pmode; - if(getValue(prop, compiler, pmode)) - mPass->setPolygonMode(pmode); - break; - case ID_POLYGON_MODE_OVERRIDEABLE: - if(getValue(prop, compiler, bval)) - mPass->setPolygonModeOverrideable(bval); - break; - case ID_FOG_OVERRIDE: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - } - else if(prop->values.size() > 8) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "fog_override must have at most 8 arguments"); - } - else - { - AbstractNodeList::const_iterator i1 = getNodeAt(prop->values, 1), i2 = getNodeAt(prop->values, 2); - bool val = false; - if(getBoolean(prop->values.front(), &val)) - { - FogMode mode = FOG_NONE; - ColourValue clr = ColourValue::White; - Real dens = 0.001, start = 0.0f, end = 1.0f; - - if(i1 != prop->values.end()) - { - if((*i1)->type == ANT_ATOM) - { - AtomAbstractNode *atom = (AtomAbstractNode*)(*i1).get(); - switch(atom->id) - { - case ID_NONE: - mode = FOG_NONE; - break; - case ID_LINEAR: - mode = FOG_LINEAR; - break; - case ID_EXP: - mode = FOG_EXP; - break; - case ID_EXP2: - mode = FOG_EXP2; - break; - default: - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*i1)->getValue() + " is not a valid FogMode"); - break; - } - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*i1)->getValue() + " is not a valid FogMode"); - break; - } - } - - if(i2 != prop->values.end()) - { - if(!getColour(i2, prop->values.end(), &clr, 3)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*i2)->getValue() + " is not a valid colour"); - break; - } - - i2 = getNodeAt(prop->values, 5); - } - - if(i2 != prop->values.end()) - { - if(!getReal(*i2, &dens)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*i2)->getValue() + " is not a valid number"); - break; - } - ++i2; - } - - if(i2 != prop->values.end()) - { - if(!getReal(*i2, &start)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*i2)->getValue() + " is not a valid number"); - return; - } - ++i2; - } - - if(i2 != prop->values.end()) - { - if(!getReal(*i2, &end)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*i2)->getValue() + " is not a valid number"); - return; - } - ++i2; - } - - mPass->setFog(val, mode, clr, dens, start, end); - } - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - prop->values.front()->getValue() + " is not a valid boolean"); - } - break; - case ID_COLOUR_WRITE: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - } - else if(prop->values.size() == 1) - { - if(getValue(prop, compiler, bval)) - mPass->setColourWriteEnabled(bval); - } - else if(prop->values.size() != 4) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "colour_write must have exactly 1 or 4 arguments"); - } - else - { - bool colourMask[] = {false ,false ,false, false}; - - uint8 channelIndex = 0; - for(const AbstractNodePtr& abstractNode : prop->values) - { - if(!getBoolean(abstractNode, &colourMask[channelIndex++])) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - abstractNode->getValue() + " is not a valid boolean"); - break; - } - } - - mPass->setColourWriteEnabled(colourMask[0], colourMask[1], colourMask[2], colourMask[3]); - } - break; - case ID_MAX_LIGHTS: - if(getValue(prop, compiler, uival)) - mPass->setMaxSimultaneousLights(Math::uint16Cast(uival)); - break; - case ID_START_LIGHT: - if(getValue(prop, compiler, uival)) - mPass->setStartLight(static_cast(uival)); - break; - case ID_LIGHT_MASK: - if(getValue(prop, compiler, uival)) - mPass->setLightMask(static_cast(uival)); - break; - case ID_ITERATION: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - } - else - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0); - if((*i0)->type == ANT_ATOM) - { - AtomAbstractNode *atom = (AtomAbstractNode*)(*i0).get(); - if(atom->id == ID_ONCE) - { - mPass->setIteratePerLight(false); - } - else if(atom->id == ID_ONCE_PER_LIGHT) - { - AbstractNodeList::const_iterator i1 = getNodeAt(prop->values, 1); - if(i1 != prop->values.end() && (*i1)->type == ANT_ATOM) - { - atom = (AtomAbstractNode*)(*i1).get(); - switch(atom->id) - { - case ID_POINT: - mPass->setIteratePerLight(true); - break; - case ID_DIRECTIONAL: - mPass->setIteratePerLight(true, true, Light::LT_DIRECTIONAL); - break; - case ID_SPOT: - mPass->setIteratePerLight(true, true, Light::LT_SPOTLIGHT); - break; - default: - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - prop->values.front()->getValue() + " is not a valid light type (point, directional, or spot)"); - } - } - else - { - mPass->setIteratePerLight(true, false); - } - - } - else if(StringConverter::isNumber(atom->value)) - { - mPass->setPassIterationCount(Ogre::StringConverter::parseInt(atom->value)); - - AbstractNodeList::const_iterator i1 = getNodeAt(prop->values, 1); - if(i1 != prop->values.end() && (*i1)->type == ANT_ATOM) - { - atom = (AtomAbstractNode*)(*i1).get(); - if(atom->id == ID_PER_LIGHT) - { - AbstractNodeList::const_iterator i2 = getNodeAt(prop->values, 2); - if(i2 != prop->values.end() && (*i2)->type == ANT_ATOM) - { - atom = (AtomAbstractNode*)(*i2).get(); - switch(atom->id) - { - case ID_POINT: - mPass->setIteratePerLight(true); - break; - case ID_DIRECTIONAL: - mPass->setIteratePerLight(true, true, Light::LT_DIRECTIONAL); - break; - case ID_SPOT: - mPass->setIteratePerLight(true, true, Light::LT_SPOTLIGHT); - break; - default: - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*i2)->getValue() + " is not a valid light type (point, directional, or spot)"); - } - } - else - { - mPass->setIteratePerLight(true, false); - } - } - else if(atom->id == ID_PER_N_LIGHTS) - { - AbstractNodeList::const_iterator i2 = getNodeAt(prop->values, 2); - if(i2 != prop->values.end() && (*i2)->type == ANT_ATOM) - { - atom = (AtomAbstractNode*)(*i2).get(); - if(StringConverter::isNumber(atom->value)) - { - mPass->setLightCountPerIteration( - static_cast(StringConverter::parseInt(atom->value))); - - AbstractNodeList::const_iterator i3 = getNodeAt(prop->values, 3); - if(i3 != prop->values.end() && (*i3)->type == ANT_ATOM) - { - atom = (AtomAbstractNode*)(*i3).get(); - switch(atom->id) - { - case ID_POINT: - mPass->setIteratePerLight(true); - break; - case ID_DIRECTIONAL: - mPass->setIteratePerLight(true, true, Light::LT_DIRECTIONAL); - break; - case ID_SPOT: - mPass->setIteratePerLight(true, true, Light::LT_SPOTLIGHT); - break; - default: - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*i3)->getValue() + " is not a valid light type (point, directional, or spot)"); - } - } - else - { - mPass->setIteratePerLight(true, false); - } - } - else - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - (*i2)->getValue() + " is not a valid number"); - } - } - else - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - prop->values.front()->getValue() + " is not a valid number"); - } - } - } - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - } - break; - case ID_LINE_WIDTH: - if(getValue(prop, compiler, fval)) - mPass->setLineWidth(fval); - break; - case ID_POINT_SIZE: - if(getValue(prop, compiler, fval)) - mPass->setPointSize(fval); - break; - case ID_POINT_SPRITES: - if(getValue(prop, compiler, bval)) - mPass->setPointSpritesEnabled(bval); - break; - case ID_POINT_SIZE_ATTENUATION: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - } - else if(prop->values.size() > 4) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "point_size_attenuation must have at most 4 arguments"); - } - else - { - bool val = false; - if(getBoolean(prop->values.front(), &val)) - { - if(val) - { - AbstractNodeList::const_iterator i1 = getNodeAt(prop->values, 1), i2 = getNodeAt(prop->values, 2), - i3 = getNodeAt(prop->values, 3); - - if (prop->values.size() > 1) - { - - Real constant = 0.0f, linear = 1.0f, quadratic = 0.0f; - - if(i1 != prop->values.end() && (*i1)->type == ANT_ATOM) - { - AtomAbstractNode *atom = (AtomAbstractNode*)(*i1).get(); - if(StringConverter::isNumber(atom->value)) - constant = StringConverter::parseReal(atom->value); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*i1)->getValue() + " is not a valid number"); - } - - if(i2 != prop->values.end() && (*i2)->type == ANT_ATOM) - { - AtomAbstractNode *atom = (AtomAbstractNode*)(*i2).get(); - if(StringConverter::isNumber(atom->value)) - linear = StringConverter::parseReal(atom->value); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*i2)->getValue() + " is not a valid number"); - } - - if(i3 != prop->values.end() && (*i3)->type == ANT_ATOM) - { - AtomAbstractNode *atom = (AtomAbstractNode*)(*i3).get(); - if(StringConverter::isNumber(atom->value)) - quadratic = StringConverter::parseReal(atom->value); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*i3)->getValue() + " is not a valid number"); - } - - mPass->setPointAttenuation(true, constant, linear, quadratic); - } - else - { - mPass->setPointAttenuation(true); - } - } - else - { - mPass->setPointAttenuation(false); - } - } - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - prop->values.front()->getValue() + " is not a valid boolean"); - } - break; - case ID_POINT_SIZE_MIN: - if(getValue(prop, compiler, fval)) - mPass->setPointMinSize(fval); - break; - case ID_POINT_SIZE_MAX: - if(getValue(prop, compiler, fval)) - mPass->setPointMaxSize(fval); - break; - default: - compiler->addError(ScriptCompiler::CE_UNEXPECTEDTOKEN, prop->file, prop->line, - "token \"" + prop->name + "\" is not recognized"); - } - } - else if(i->type == ANT_OBJECT) - { - ObjectAbstractNode *child = static_cast(i.get()); - switch(child->id) - { - case ID_FRAGMENT_PROGRAM_REF: - case ID_VERTEX_PROGRAM_REF: - case ID_GEOMETRY_PROGRAM_REF: - case ID_TESSELLATION_HULL_PROGRAM_REF: - case ID_TESSELLATION_DOMAIN_PROGRAM_REF: - case ID_COMPUTE_PROGRAM_REF: - translateProgramRef(getProgramType(child->id), compiler, child); - break; - case ID_SHADOW_CASTER_VERTEX_PROGRAM_REF: - translateShadowCasterProgramRef(GPT_VERTEX_PROGRAM, compiler, child); - break; - case ID_SHADOW_CASTER_FRAGMENT_PROGRAM_REF: - translateShadowCasterProgramRef(GPT_FRAGMENT_PROGRAM, compiler, child); - break; - case ID_SHADOW_RECEIVER_VERTEX_PROGRAM_REF: - translateShadowReceiverProgramRef(GPT_VERTEX_PROGRAM, compiler, child); - break; - case ID_SHADOW_RECEIVER_FRAGMENT_PROGRAM_REF: - translateShadowReceiverProgramRef(GPT_FRAGMENT_PROGRAM, compiler, child); - break; - default: - processNode(compiler, i); - break; - case ID_FRAGMENT_PROGRAM: - case ID_VERTEX_PROGRAM: - case ID_GEOMETRY_PROGRAM: - case ID_TESSELLATION_HULL_PROGRAM: - case ID_TESSELLATION_DOMAIN_PROGRAM: - case ID_COMPUTE_PROGRAM: - { - // auto assign inline defined programs - processNode(compiler, i); - GpuProgramType type = getProgramType(child->id); - mPass->setGpuProgram(type, GpuProgramUsage::_getProgramByName(child->name, mPass->getResourceGroup(), type)); - } - } - } - } - } - - static GpuProgramPtr getProgram(ScriptCompiler* compiler, ObjectAbstractNode* node) - { - if(node->name.empty()) - { - compiler->addError(ScriptCompiler::CE_OBJECTNAMEEXPECTED, node->file, node->line); - return nullptr; - } - - ProcessResourceNameScriptCompilerEvent evt(ProcessResourceNameScriptCompilerEvent::GPU_PROGRAM, node->name); - compiler->_fireEvent(&evt, 0); - - auto& mgr = GpuProgramManager::getSingleton(); - if (auto ret = mgr.getByName(evt.mName, compiler->getResourceGroup())) - return ret; - - // recheck with auto resource group - if (auto ret = mgr.getByName(evt.mName, RGN_AUTODETECT)) - return ret; - - compiler->addError(ScriptCompiler::CE_REFERENCETOANONEXISTINGOBJECT, node->file, node->line, - evt.mName); - return nullptr; - } - - //------------------------------------------------------------------------- - void PassTranslator::translateProgramRef(GpuProgramType type, ScriptCompiler *compiler, ObjectAbstractNode *node) - { - auto program = getProgram(compiler, node); - if(!program) return; - auto pass = any_cast(node->parent->context); - - pass->setGpuProgram(type, program); - if(program->isSupported()) - { - GpuProgramParametersSharedPtr params = pass->getGpuProgramParameters(type); - GpuProgramTranslator::translateProgramParameters(compiler, params, node); - } - } - //------------------------------------------------------------------------- - void PassTranslator::translateShadowCasterProgramRef(GpuProgramType type, ScriptCompiler *compiler, ObjectAbstractNode *node) - { - auto program = getProgram(compiler, node); - if(!program) return; - auto pass = any_cast(node->parent->context); - - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, node->file, node->line, - node->cls + ". Use shadow_caster_material instead"); - - auto caster_mat = pass->getParent()->getShadowCasterMaterial(); - if(!caster_mat) - { - auto src_mat = pass->getParent()->getParent(); - // only first pass of this will be used. The caster material is technique specific. - caster_mat = src_mat->clone( - StringUtil::format("%s/%p/CasterFallback", src_mat->getName().c_str(), pass->getParent())); - pass->getParent()->setShadowCasterMaterial(caster_mat); - } - auto caster_pass = caster_mat->getTechnique(0)->getPass(0); - - caster_pass->setGpuProgram(type, program); - if(program->isSupported()) - { - GpuProgramParametersSharedPtr params = caster_pass->getGpuProgramParameters(type); - GpuProgramTranslator::translateProgramParameters(compiler, params, node); - } - } - //------------------------------------------------------------------------- - void PassTranslator::translateShadowReceiverProgramRef(GpuProgramType type,ScriptCompiler *compiler, ObjectAbstractNode *node) - { - auto program = getProgram(compiler, node); - if(!program) return; - auto pass = any_cast(node->parent->context); - - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, node->file, node->line, - node->cls + ". Use shadow_receiver_material instead"); - - auto receiver_mat = pass->getParent()->getShadowReceiverMaterial(); - if(!receiver_mat) - { - auto src_mat = pass->getParent()->getParent(); - // only first pass of this will be used - receiver_mat = src_mat->clone(src_mat->getName()+"/ReceiverFallback"); - pass->getParent()->setShadowReceiverMaterial(receiver_mat); - } - auto receiver_pass = receiver_mat->getTechnique(0)->getPass(0); - - receiver_pass->setGpuProgram(type, program); - if(program->isSupported()) - { - GpuProgramParametersSharedPtr params = receiver_pass->getGpuProgramParameters(type); - GpuProgramTranslator::translateProgramParameters(compiler, params, node); - } - } - /************************************************************************** - * TextureUnitTranslator - *************************************************************************/ - TextureUnitTranslator::TextureUnitTranslator() - :mUnit(0) - { - } - //------------------------------------------------------------------------- - void SamplerTranslator::translateSamplerParam(ScriptCompiler* compiler, const SamplerPtr& sampler, PropertyAbstractNode* prop) - { - bool bval; - Real fval; - uint32 uival; - - switch(prop->id) - { - case ID_TEX_ADDRESS_MODE: - { - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - } - else - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), - i1 = getNodeAt(prop->values, 1), - i2 = getNodeAt(prop->values, 2); - Sampler::UVWAddressingMode mode; - - if(!getValue(*i0, mode.u)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*i0)->getValue() + " not supported as first argument (must be \"wrap\", \"clamp\", \"mirror\", or \"border\")"); - return; - } - mode.v = mode.u; - mode.w = mode.u; - - if(i1 != prop->values.end()) - { - if(!getValue(*i1, mode.v)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*i1)->getValue() + " not supported as second argument (must be \"wrap\", \"clamp\", \"mirror\", or \"border\")"); - } - } - - if(i2 != prop->values.end()) - { - if(!getValue(*i2, mode.w)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*i2)->getValue() + " not supported as third argument (must be \"wrap\", \"clamp\", \"mirror\", or \"border\")"); - } - } - - sampler->setAddressingMode(mode); - } - } - break; - case ID_TEX_BORDER_COLOUR: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line); - } - else - { - ColourValue val; - if(getColour(prop->values.begin(), prop->values.end(), &val)) - sampler->setBorderColour(val); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "tex_border_colour only accepts a colour argument"); - } - break; - case ID_FILTERING: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - } - else if(prop->values.size() == 1) - { - if(prop->values.front()->type == ANT_ATOM) - { - AtomAbstractNode *atom = (AtomAbstractNode*)prop->values.front().get(); - switch(atom->id) - { - case ID_NONE: - sampler->setFiltering(TFO_NONE); - break; - case ID_BILINEAR: - sampler->setFiltering(TFO_BILINEAR); - break; - case ID_TRILINEAR: - sampler->setFiltering(TFO_TRILINEAR); - break; - case ID_ANISOTROPIC: - sampler->setFiltering(TFO_ANISOTROPIC); - break; - default: - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - prop->values.front()->getValue() + " not supported as first argument (must be \"none\", \"bilinear\", \"trilinear\", or \"anisotropic\")"); - } - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - prop->values.front()->getValue() + " not supported as first argument (must be \"none\", \"bilinear\", \"trilinear\", or \"anisotropic\")"); - } - } - else if(prop->values.size() == 3) - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), - i1 = getNodeAt(prop->values, 1), - i2 = getNodeAt(prop->values, 2); - FilterOptions tmin, tmax, tmip; - if (getValue(*i0, tmin) && getValue(*i1, tmax) && getValue(*i2, tmip)) - { - sampler->setFiltering(tmin, tmax, tmip); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - } - else - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "filtering must have either 1 or 3 arguments"); - } - break; - case ID_CMPTEST: - if(getValue(prop, compiler, bval)) - sampler->setCompareEnabled(bval); - break; - case ID_CMPFUNC: - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, prop->file, - prop->line, - "compare_func. Use comp_func."); - OGRE_FALLTHROUGH; - case ID_COMP_FUNC: - CompareFunction func; - if(getValue(prop, compiler, func)) - sampler->setCompareFunction(func); - break; - case ID_MAX_ANISOTROPY: - if(getValue(prop, compiler, uival)) - sampler->setAnisotropy(uival); - break; - case ID_MIPMAP_BIAS: - if(getValue(prop, compiler, fval)) - sampler->setMipmapBias(fval); - break; - } - } - void SamplerTranslator::translate(ScriptCompiler *compiler, const Ogre::AbstractNodePtr &node) - { - ObjectAbstractNode *obj = static_cast(node.get()); - - if(obj->name.empty()) - { - compiler->addError(ScriptCompiler::CE_OBJECTNAMEEXPECTED, obj->file, obj->line); - return; - } - - SamplerPtr sampler = TextureManager::getSingleton().createSampler(obj->name); - - // Set the properties for the material - for(auto & i : obj->children) - { - if(i->type == ANT_PROPERTY) - { - PropertyAbstractNode *prop = static_cast(i.get()); - switch(prop->id) - { - case ID_TEX_ADDRESS_MODE: - case ID_TEX_BORDER_COLOUR: - case ID_FILTERING: - case ID_CMPTEST: - case ID_COMP_FUNC: - case ID_MAX_ANISOTROPY: - case ID_MIPMAP_BIAS: - translateSamplerParam(compiler, sampler, prop); - break; - default: - compiler->addError(ScriptCompiler::CE_UNEXPECTEDTOKEN, prop->file, prop->line, - "token \"" + prop->name + "\" is not recognized"); - } - } - else if(i->type == ANT_OBJECT) - { - processNode(compiler, i); - } - } - } - - void TextureUnitTranslator::translate(ScriptCompiler *compiler, const Ogre::AbstractNodePtr &node) - { - ObjectAbstractNode *obj = static_cast(node.get()); - - Pass *pass = any_cast(obj->parent->context); - mUnit = pass->createTextureUnitState(); - obj->context = mUnit; - - // Get the name of the technique - if(!obj->name.empty()) - mUnit->setName(obj->name); - - Real fval; - uint32 uival; - String sval; - - // Set the properties for the material - for(auto & i : obj->children) - { - if(i->type == ANT_PROPERTY) - { - PropertyAbstractNode *prop = static_cast(i.get()); - switch(prop->id) - { - case ID_TEX_ADDRESS_MODE: - case ID_TEX_BORDER_COLOUR: - case ID_FILTERING: - case ID_CMPTEST: - case ID_CMPFUNC: - case ID_COMP_FUNC: - case ID_MAX_ANISOTROPY: - case ID_MIPMAP_BIAS: - SamplerTranslator::translateSamplerParam(compiler, mUnit->_getLocalSampler(), prop); - break; - case ID_SAMPLER_REF: - if(getValue(prop, compiler, sval)) - { - auto sampler = TextureManager::getSingleton().getSampler(sval); - if(sampler) - mUnit->setSampler(sampler); - else - compiler->addError(ScriptCompiler::CE_REFERENCETOANONEXISTINGOBJECT, - prop->file, prop->line, sval); - } - break; - case ID_UNORDERED_ACCESS_MIP: - if(getValue(prop, compiler, uival)) - mUnit->setUnorderedAccessMipLevel(uival); - break; - case ID_TEXTURE_ALIAS: - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, prop->file, prop->line, - "texture_alias. Use 'texture $variable'"); - if(getValue(prop, compiler, sval)) - mUnit->setName(sval); - break; - case ID_TEXTURE: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - } - else if(prop->values.size() > 5) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "texture must have at most 5 arguments"); - } - else - { - AbstractNodeList::const_iterator j = prop->values.begin(); - String val; - if(getString(*j, &val)) - { - TextureType texType = TEX_TYPE_2D; - bool isAlpha = false; - bool sRGBRead = false; - PixelFormat format = PF_UNKNOWN; - int mipmaps = MIP_DEFAULT; - - ++j; - while(j != prop->values.end()) - { - if((*j)->type == ANT_ATOM) - { - AtomAbstractNode *atom = (AtomAbstractNode*)(*j).get(); - switch(atom->id) - { - case ID_1D: - texType = TEX_TYPE_1D; - break; - case ID_2D: - texType = TEX_TYPE_2D; - break; - case ID_3D: - texType = TEX_TYPE_3D; - break; - case ID_CUBIC: - texType = TEX_TYPE_CUBE_MAP; - break; - case ID_2DARRAY: - texType = TEX_TYPE_2D_ARRAY; - break; - case ID_UNLIMITED: - mipmaps = MIP_UNLIMITED; - break; - case ID_ALPHA: - isAlpha = true; - break; - case ID_GAMMA: - sRGBRead = true; - break; - default: - if(!StringConverter::parse(atom->value, mipmaps)) - { - format = PixelUtil::getFormatFromName(atom->value, true); - - if (format == PF_UNKNOWN) - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, - prop->file, prop->line, atom->value); - } - } - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*j)->getValue() + " is not a supported argument to the texture property"); - } - ++j; - } - - ProcessResourceNameScriptCompilerEvent evt(ProcessResourceNameScriptCompilerEvent::TEXTURE, val); - compiler->_fireEvent(&evt, 0); - - if(isAlpha) - { - // format = PF_A8; should only be done, if src is luminance, which we dont know here - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, prop->file, - prop->line, "alpha. Use PF_A8 instead"); - } - - mUnit->setTextureName(evt.mName, texType); - mUnit->setDesiredFormat(format); - OGRE_IGNORE_DEPRECATED_BEGIN - mUnit->setIsAlpha(isAlpha); - OGRE_IGNORE_DEPRECATED_END - mUnit->setNumMipmaps(mipmaps); - mUnit->setHardwareGammaEnabled(sRGBRead); - } - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*j)->getValue() + " is not a valid texture name"); - } - break; - case ID_ANIM_TEXTURE: - if(prop->values.size() < 3) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - } - else - { - AbstractNodeList::const_iterator i1 = getNodeAt(prop->values, 1); - if((*i1)->type == ANT_ATOM && StringConverter::isNumber(((AtomAbstractNode*)(*i1).get())->value)) - { - // Short form - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), i2 = getNodeAt(prop->values, 2); - if((*i0)->type == ANT_ATOM && (*i1)->type == ANT_ATOM) - { - String val0; - uint32 val1; - Real val2; - if(getString(*i0, &val0) && getUInt(*i1, &val1) && getReal(*i2, &val2)) - { - ProcessResourceNameScriptCompilerEvent evt(ProcessResourceNameScriptCompilerEvent::TEXTURE, val0); - compiler->_fireEvent(&evt, 0); - - mUnit->setAnimatedTextureName(evt.mName, val1, val2); - } - else - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - "anim_texture short form requires a texture name, number of frames, and animation duration"); - } - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "anim_texture short form requires a texture name, number of frames, and animation duration"); - } - } - else - { - // Long form has n number of frames - Real duration = 0; - AbstractNodeList::const_iterator in = getNodeAt(prop->values, static_cast(prop->values.size()) - 1); - if(getReal(*in, &duration)) - { - std::vector names; - - AbstractNodeList::iterator j = prop->values.begin(); - while(j != in) - { - if((*j)->type == ANT_ATOM) - { - String name = ((AtomAbstractNode*)(*j).get())->value; - // Run the name through the listener - if(compiler->getListener()) - { - ProcessResourceNameScriptCompilerEvent evt(ProcessResourceNameScriptCompilerEvent::TEXTURE, name); - compiler->_fireEvent(&evt, 0); - names.push_back(evt.mName); - } - else - { - names.push_back(name); - } - } - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*j)->getValue() + " is not supported as a texture name"); - ++j; - } - - mUnit->setAnimatedTextureName(names, duration); - } - else - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - (*in)->getValue() + " is not supported for the duration argument"); - } - } - } - break; - case ID_CUBIC_TEXTURE: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - } - else if(prop->values.size() == 2) - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), - i1 = getNodeAt(prop->values, 1); - if((*i0)->type == ANT_ATOM && (*i1)->type == ANT_ATOM) - { - AtomAbstractNode *atom0 = (AtomAbstractNode*)(*i0).get(); - - ProcessResourceNameScriptCompilerEvent evt(ProcessResourceNameScriptCompilerEvent::TEXTURE, atom0->value); - compiler->_fireEvent(&evt, 0); - - mUnit->setTextureName(evt.mName, TEX_TYPE_CUBE_MAP); - - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, prop->file, prop->line, - "'cubic_texture ..'. Use 'texture .. cubic' instead."); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - } - else if(prop->values.size() == 7) - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), - i1 = getNodeAt(prop->values, 1), - i2 = getNodeAt(prop->values, 2), - i3 = getNodeAt(prop->values, 3), - i4 = getNodeAt(prop->values, 4), - i5 = getNodeAt(prop->values, 5), - i6 = getNodeAt(prop->values, 6); - if((*i0)->type == ANT_ATOM && (*i1)->type == ANT_ATOM && (*i2)->type == ANT_ATOM && (*i3)->type == ANT_ATOM && - (*i4)->type == ANT_ATOM && (*i5)->type == ANT_ATOM && (*i6)->type == ANT_ATOM) - { - AtomAbstractNode *atom0 = (AtomAbstractNode*)(*i0).get(), *atom1 = (AtomAbstractNode*)(*i1).get(), - *atom2 = (AtomAbstractNode*)(*i2).get(), *atom3 = (AtomAbstractNode*)(*i3).get(), - *atom4 = (AtomAbstractNode*)(*i4).get(), *atom5 = (AtomAbstractNode*)(*i5).get(), - *atom6 = (AtomAbstractNode*)(*i6).get(); - std::vector names(6); - // backward compatible order - names[4] = atom0->value; - names[5] = atom1->value; - names[1] = atom2->value; - names[0] = atom3->value; - names[2] = atom4->value; - names[3] = atom5->value; - - if(compiler->getListener()) - { - // Run each name through the listener - for(int j = 0; j < 6; ++j) - { - ProcessResourceNameScriptCompilerEvent evt(ProcessResourceNameScriptCompilerEvent::TEXTURE, names[j]); - compiler->_fireEvent(&evt, 0); - names[j] = evt.mName; - } - } - - if(atom6->id != ID_COMBINED_UVW) - { - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, prop->file, prop->line, - "separateUV is no longer supported."); - } - mUnit->setLayerArrayNames(TEX_TYPE_CUBE_MAP, names); - } - - } - else - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "cubic_texture must have at most 7 arguments"); - } - break; - case ID_TEX_COORD_SET: - if(getValue(prop, compiler, uival)) - mUnit->setTextureCoordSet(uival); - break; - - case ID_COLOUR_OP: - LayerBlendOperation cop; - if(getValue(prop, compiler, cop)) - mUnit->setColourOperation(cop); - break; - case ID_COLOUR_OP_EX: - if(prop->values.size() < 3) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line, - "colour_op_ex must have at least 3 arguments"); - } - else if(prop->values.size() > 10) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "colour_op_ex must have at most 10 arguments"); - } - else - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), - i1 = getNodeAt(prop->values, 1), - i2 = getNodeAt(prop->values, 2); - LayerBlendOperationEx op; - LayerBlendSource source1, source2; - if (getValue(*i0, op) && getValue(*i1, source1) && getValue(*i2, source2)) - { - ColourValue arg1 = ColourValue::White, arg2 = ColourValue::White; - Real manualBlend = 0.0f; - - if(op == LBX_BLEND_MANUAL) - { - AbstractNodeList::const_iterator i3 = getNodeAt(prop->values, 3); - if(i3 != prop->values.end()) - { - if(!getReal(*i3, &manualBlend)) - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*i3)->getValue() + " is not a valid number argument"); - } - else - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - "fourth argument expected when blend_manual is used"); - } - } - - AbstractNodeList::const_iterator j = getNodeAt(prop->values, 3); - if(op == LBX_BLEND_MANUAL) - ++j; - if(source1 == LBS_MANUAL) - { - if(j != prop->values.end()) - { - if(!getColour(j, prop->values.end(), &arg1, 3)) - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "valid colour expected when src_manual is used"); - } - else - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - "valid colour expected when src_manual is used"); - } - } - if(source2 == LBS_MANUAL) - { - if(j != prop->values.end()) - { - if(!getColour(j, prop->values.end(), &arg2, 3)) - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "valid colour expected when src_manual is used"); - } - else - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - "valid colour expected when src_manual is used"); - } - } - - mUnit->setColourOperationEx(op, source1, source2, arg1, arg2, manualBlend); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - } - break; - case ID_COLOUR_OP_MULTIPASS_FALLBACK: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - } - else if(prop->values.size() > 2) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "colour_op_multiplass_fallback must have at most 2 arguments"); - } - else if(prop->values.size() == 1) - { - if(prop->values.front()->type == ANT_ATOM) - { - AtomAbstractNode *atom = (AtomAbstractNode*)prop->values.front().get(); - switch(atom->id) - { - case ID_ADD: - mUnit->setColourOpMultipassFallback(SBF_ONE, SBF_ONE); - break; - case ID_MODULATE: - mUnit->setColourOpMultipassFallback(SBF_DEST_COLOUR, SBF_ZERO); - break; - case ID_COLOUR_BLEND: - mUnit->setColourOpMultipassFallback(SBF_SOURCE_COLOUR, SBF_ONE_MINUS_SOURCE_COLOUR); - break; - case ID_ALPHA_BLEND: - mUnit->setColourOpMultipassFallback(SBF_SOURCE_ALPHA, SBF_ONE_MINUS_SOURCE_ALPHA); - break; - case ID_REPLACE: - mUnit->setColourOpMultipassFallback(SBF_ONE, SBF_ZERO); - break; - default: - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "argument must be a valid scene blend type (add, modulate, colour_blend, alpha_blend, or replace)"); - } - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "argument must be a valid scene blend type (add, modulate, colour_blend, alpha_blend, or replace)"); - } - } - else - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), i1 = getNodeAt(prop->values, 1); - SceneBlendFactor sbf0, sbf1; - if(getSceneBlendFactor(*i0, &sbf0) && getSceneBlendFactor(*i1, &sbf1)) - mUnit->setColourOpMultipassFallback(sbf0, sbf1); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "arguments must be valid scene blend factors"); - } - break; - case ID_ALPHA_OP_EX: - if(prop->values.size() < 3) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line, - "alpha_op_ex must have at least 3 arguments"); - } - else if(prop->values.size() > 6) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "alpha_op_ex must have at most 6 arguments"); - } - else - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), - i1 = getNodeAt(prop->values, 1), - i2 = getNodeAt(prop->values, 2); - LayerBlendOperationEx op; - LayerBlendSource source1, source2; - if (getValue(*i0, op) && getValue(*i1, source1) && getValue(*i2, source2)) - { - Real arg1 = 0.0f, arg2 = 0.0f; - Real manualBlend = 0.0f; - - if(op == LBX_BLEND_MANUAL) - { - AbstractNodeList::const_iterator i3 = getNodeAt(prop->values, 3); - if(i3 != prop->values.end()) - { - if(!getReal(*i3, &manualBlend)) - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "valid number expected when blend_manual is used"); - } - else - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - "valid number expected when blend_manual is used"); - } - } - - AbstractNodeList::const_iterator j = getNodeAt(prop->values, 3); - if(op == LBX_BLEND_MANUAL) - ++j; - if(source1 == LBS_MANUAL) - { - if(j != prop->values.end()) - { - if(!getReal(*j, &arg1)) - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "valid colour expected when src_manual is used"); - else - ++j; - } - else - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - "valid colour expected when src_manual is used"); - } - } - if(source2 == LBS_MANUAL) - { - if(j != prop->values.end()) - { - if(!getReal(*j, &arg2)) - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "valid colour expected when src_manual is used"); - } - else - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - "valid colour expected when src_manual is used"); - } - } - - mUnit->setAlphaOperation(op, source1, source2, arg1, arg2, manualBlend); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - } - break; - case ID_ENV_MAP: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - } - else if(prop->values.size() > 1) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "env_map must have at most 1 argument"); - } - else - { - if(prop->values.front()->type == ANT_ATOM) - { - AtomAbstractNode *atom = (AtomAbstractNode*)prop->values.front().get(); - switch(atom->id) - { - case ScriptCompiler::ID_OFF: - mUnit->setEnvironmentMap(false); - break; - case ID_SPHERICAL: - mUnit->setEnvironmentMap(true, TextureUnitState::ENV_CURVED); - break; - case ID_PLANAR: - mUnit->setEnvironmentMap(true, TextureUnitState::ENV_PLANAR); - break; - case ID_CUBIC_REFLECTION: - mUnit->setEnvironmentMap(true, TextureUnitState::ENV_REFLECTION); - break; - case ID_CUBIC_NORMAL: - mUnit->setEnvironmentMap(true, TextureUnitState::ENV_NORMAL); - break; - default: - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - prop->values.front()->getValue() + " is not a valid argument (must be \"off\", \"spherical\", \"planar\", \"cubic_reflection\", or \"cubic_normal\")"); - } - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - prop->values.front()->getValue() + " is not a valid argument (must be \"off\", \"spherical\", \"planar\", \"cubic_reflection\", or \"cubic_normal\")"); - } - } - break; - case ID_SCROLL: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line); - } - else if(prop->values.size() > 2) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "scroll must have at most 2 arguments"); - } - else - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), i1 = getNodeAt(prop->values, 1); - Real x, y; - if(getReal(*i0, &x) && getReal(*i1, &y)) - mUnit->setTextureScroll(x, y); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*i0)->getValue() + " and/or " + (*i1)->getValue() + " is invalid; both must be numbers"); - } - break; - case ID_SCROLL_ANIM: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line); - } - else if(prop->values.size() > 2) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "scroll_anim must have at most 2 arguments"); - } - else - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), i1 = getNodeAt(prop->values, 1); - Real x, y; - if(getReal(*i0, &x) && getReal(*i1, &y)) - mUnit->setScrollAnimation(x, y); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - (*i0)->getValue() + " and/or " + (*i1)->getValue() + " is invalid; both must be numbers"); - } - break; - case ID_ROTATE: - if(getValue(prop, compiler, fval)) - mUnit->setTextureRotate(Degree(fval)); - break; - case ID_ROTATE_ANIM: - if(getValue(prop, compiler, fval)) - mUnit->setRotateAnimation(fval); - break; - case ID_SCALE: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line); - } - else if(prop->values.size() > 2) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "scale must have at most 2 arguments"); - } - else - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), i1 = getNodeAt(prop->values, 1); - Real x, y; - if(getReal(*i0, &x) && getReal(*i1, &y)) - mUnit->setTextureScale(x, y); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "first and second arguments must both be valid number values (received " + (*i0)->getValue() + ", " + (*i1)->getValue() + ")"); - } - break; - case ID_WAVE_XFORM: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line); - } - else if(prop->values.size() > 6) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "wave_xform must have at most 6 arguments"); - } - else - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), i1 = getNodeAt(prop->values, 1), - i2 = getNodeAt(prop->values, 2), i3 = getNodeAt(prop->values, 3), - i4 = getNodeAt(prop->values, 4), i5 = getNodeAt(prop->values, 5); - if((*i0)->type == ANT_ATOM && (*i1)->type == ANT_ATOM && (*i2)->type == ANT_ATOM && - (*i3)->type == ANT_ATOM && (*i4)->type == ANT_ATOM && (*i5)->type == ANT_ATOM) - { - AtomAbstractNode *atom0 = (AtomAbstractNode*)(*i0).get(), *atom1 = (AtomAbstractNode*)(*i1).get(); - TextureUnitState::TextureTransformType type = TextureUnitState::TT_ROTATE; - WaveformType wave = WFT_SINE; - Real base = 0.0f, freq = 0.0f, phase = 0.0f, amp = 0.0f; - - switch(atom0->id) - { - case ID_SCROLL_X: - type = TextureUnitState::TT_TRANSLATE_U; - break; - case ID_SCROLL_Y: - type = TextureUnitState::TT_TRANSLATE_V; - break; - case ID_SCALE_X: - type = TextureUnitState::TT_SCALE_U; - break; - case ID_SCALE_Y: - type = TextureUnitState::TT_SCALE_V; - break; - case ID_ROTATE: - type = TextureUnitState::TT_ROTATE; - break; - default: - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - atom0->value + " is not a valid transform type (must be \"scroll_x\", \"scroll_y\", \"scale_x\", \"scale_y\", or \"rotate\")"); - } - - switch(atom1->id) - { - case ID_SINE: - wave = WFT_SINE; - break; - case ID_TRIANGLE: - wave = WFT_TRIANGLE; - break; - case ID_SQUARE: - wave = WFT_SQUARE; - break; - case ID_SAWTOOTH: - wave = WFT_SAWTOOTH; - break; - case ID_INVERSE_SAWTOOTH: - wave = WFT_INVERSE_SAWTOOTH; - break; - default: - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - atom1->value + " is not a valid waveform type (must be \"sine\", \"triangle\", \"square\", \"sawtooth\", or \"inverse_sawtooth\")"); - } - - if(!getReal(*i2, &base) || !getReal(*i3, &freq) || !getReal(*i4, &phase) || !getReal(*i5, &)) - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "arguments 3, 4, 5, and 6 must be valid numbers; received " + (*i2)->getValue() + ", " + (*i3)->getValue() + ", " + (*i4)->getValue() + ", " + (*i5)->getValue()); - - mUnit->setTransformAnimation(type, wave, base, freq, phase, amp); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - } - break; - case ID_TRANSFORM: - { - Matrix4 m; - if(getMatrix4(prop->values.begin(), prop->values.end(), &m)) - mUnit->setTextureTransform(m); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - break; - case ID_CONTENT_TYPE: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line); - } - else if(prop->values.size() > 4) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line, - "content_type must have at most 4 arguments"); - } - else - { - if(prop->values.front()->type == ANT_ATOM) - { - AtomAbstractNode *atom = (AtomAbstractNode*)prop->values.front().get(); - switch(atom->id) - { - case ID_NAMED: - mUnit->setContentType(TextureUnitState::CONTENT_NAMED); - break; - case ID_SHADOW: - mUnit->setContentType(TextureUnitState::CONTENT_SHADOW); - break; - case ID_COMPOSITOR: - mUnit->setContentType(TextureUnitState::CONTENT_COMPOSITOR); - if (prop->values.size() >= 3) - { - String compositorName; - getString(*getNodeAt(prop->values, 1), &compositorName); - String textureName; - getString(*getNodeAt(prop->values, 2), &textureName); - - if (prop->values.size() == 4) - { - uint32 mrtIndex; - getUInt(*getNodeAt(prop->values, 3), (uint32*)&mrtIndex); - mUnit->setCompositorReference(compositorName, textureName, mrtIndex); - } - else - { - mUnit->setCompositorReference(compositorName, textureName); - } - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "content_type compositor must have an additional 2 or 3 parameters"); - } - - break; - default: - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - atom->value + " is not a valid content type (must be \"named\" or \"shadow\" or \"compositor\")"); - } - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - prop->values.front()->getValue() + " is not a valid content type"); - } - } - break; - default: - compiler->addError(ScriptCompiler::CE_UNEXPECTEDTOKEN, prop->file, prop->line, - "token \"" + prop->name + "\" is not recognized"); - } - } - else if(i->type == ANT_OBJECT) - { - processNode(compiler, i); - } - } - } - - /************************************************************************** - * TextureSourceTranslator - **************************************************************************/ - TextureSourceTranslator::TextureSourceTranslator() - { - } - //------------------------------------------------------------------------- - void TextureSourceTranslator::translate(Ogre::ScriptCompiler *compiler, const Ogre::AbstractNodePtr &node) - { - ObjectAbstractNode *obj = static_cast(node.get()); - - // It has to have one value identifying the texture source name - if(obj->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, node->file, node->line, - "texture_source requires a type value"); - return; - } - - // Set the value of the source - ExternalTextureSourceManager::getSingleton().setCurrentPlugIn(obj->values.front()->getValue()); - - if (!ExternalTextureSourceManager::getSingleton().getCurrentPlugIn()) - { - compiler->addError(ScriptCompiler::CE_REFERENCETOANONEXISTINGOBJECT, node->file, node->line, - obj->values.front()->getValue()); - return; - } - - // Set up the technique, pass, and texunit levels - TextureUnitState *texunit = any_cast(obj->parent->context); - Pass *pass = texunit->getParent(); - Technique *technique = pass->getParent(); - Material *material = technique->getParent(); - - unsigned short techniqueIndex = 0, passIndex = 0, texUnitIndex = 0; - for(unsigned short i = 0; i < material->getNumTechniques(); i++) - { - if(material->getTechnique(i) == technique) - { - techniqueIndex = i; - break; - } - } - for(unsigned short i = 0; i < technique->getNumPasses(); i++) - { - if(technique->getPass(i) == pass) - { - passIndex = i; - break; - } - } - for(unsigned short i = 0; i < pass->getNumTextureUnitStates(); i++) - { - if(pass->getTextureUnitState(i) == texunit) - { - texUnitIndex = i; - break; - } - } - - String tps; - tps = StringConverter::toString(techniqueIndex) + " " - + StringConverter::toString(passIndex) + " " - + StringConverter::toString(texUnitIndex); - - ExternalTextureSourceManager::getSingleton().getCurrentPlugIn()->setParameter( "set_T_P_S", tps ); - - for(auto & i : obj->children) - { - if(i->type == ANT_PROPERTY) - { - PropertyAbstractNode *prop = (PropertyAbstractNode*)i.get(); - // Glob the property values all together - String str = ""; - for(AbstractNodeList::iterator j = prop->values.begin(); j != prop->values.end(); ++j) - { - if(j != prop->values.begin()) - str = str + " "; - str = str + (*j)->getValue(); - } - ExternalTextureSourceManager::getSingleton().getCurrentPlugIn()->setParameter(prop->name, str); - } - else if(i->type == ANT_OBJECT) - { - processNode(compiler, i); - } - } - - ExternalTextureSourceManager::getSingleton().getCurrentPlugIn()->createDefinedTexture(material->getName(), material->getGroup()); - } - - /************************************************************************** - * GpuProgramTranslator - *************************************************************************/ - GpuProgramTranslator::GpuProgramTranslator() - { - } - //------------------------------------------------------------------------- - void GpuProgramTranslator::translate(ScriptCompiler *compiler, const AbstractNodePtr &node) - { - ObjectAbstractNode *obj = static_cast(node.get()); - - // Must have a name - if(obj->name.empty()) - { - compiler->addError(ScriptCompiler::CE_OBJECTNAMEEXPECTED, obj->file, obj->line, - "gpu program object must have names"); - return; - } - - // Must have a language type - if(obj->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, obj->file, obj->line, - "gpu program object require language declarations"); - return; - } - - // Get the language - String language; - for(const auto& lnode : obj->values) - { - if(!getString(lnode, &language)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, obj->file, obj->line); - return; - } - - if (language == "asm") - { - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, obj->file, obj->line, "asm. Use syntax code."); - break; // always supported - } - if (GpuProgramManager::getSingleton().isLanguageSupported(language)) - break; - } - - translateGpuProgram(compiler, obj, language); - } - //------------------------------------------------------------------------- - void GpuProgramTranslator::translateGpuProgram(ScriptCompiler *compiler, ObjectAbstractNode *obj, String language) - { - String syntax; - std::vector delegates; - std::vector > customParameters; - String source, profiles, target; - AbstractNodePtr params; - for(auto & i : obj->children) - { - if(i->type == ANT_PROPERTY) - { - PropertyAbstractNode *prop = (PropertyAbstractNode*)i.get(); - if(prop->id == ID_SOURCE) - { - if(!getValue(prop, compiler, source)) - return; - } - else if(prop->name == "delegate") - { - String value; - if(!getValue(prop, compiler, value)) - return; - - ProcessResourceNameScriptCompilerEvent evt(ProcessResourceNameScriptCompilerEvent::GPU_PROGRAM, value); - compiler->_fireEvent(&evt, 0); - delegates.push_back(evt.mName); - } - else - { - String value; - bool first = true; - for(AbstractNodeList::iterator it = prop->values.begin(); it != prop->values.end(); ++it) - { - if((*it)->type == ANT_ATOM) - { - if(!first) - value += " "; - else - first = false; - - if(prop->name == "attach") - { - ProcessResourceNameScriptCompilerEvent evt(ProcessResourceNameScriptCompilerEvent::GPU_PROGRAM, ((AtomAbstractNode*)(*it).get())->value); - compiler->_fireEvent(&evt, 0); - value += evt.mName; - - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, prop->file, - prop->line, - "attach. Use the #include directive instead"); - } - else - { - value += ((AtomAbstractNode*)(*it).get())->value; - } - } - } - - if(prop->name == "profiles") - profiles = value; - else if(prop->name == "target") - target = value; - else if(prop->id == ID_SYNTAX && language == "asm") - syntax = value; - else - customParameters.push_back(std::make_pair(prop, value)); - } - } - else if(i->type == ANT_OBJECT) - { - if(((ObjectAbstractNode*)i.get())->id == ID_DEFAULT_PARAMS) - params = i; - else - processNode(compiler, i); - } - } - - // Allocate the program - GpuProgramType gpt = translateIDToGpuProgramType(obj->id); - GpuProgram *prog = 0; - - if(language == "asm") - language = syntax; - CreateGpuProgramScriptCompilerEvent evt(obj->file, obj->name, compiler->getResourceGroup(), source, - language, gpt); - bool processed = compiler->_fireEvent(&evt, &prog); - - if(!processed) - { - prog = GpuProgramManager::getSingleton().create(obj->name, compiler->getResourceGroup(), gpt, language).get(); - - if (source.empty() && language != "unified") - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, obj->file, obj->line, - "No 'source' provided for GPU program"); - return; - } - - if(prog && !source.empty()) // prog=0 if duplicate definition resolved by "use previous" - prog->setSourceFile(source); - } - - if(!prog) - { - compiler->addError(ScriptCompiler::CE_OBJECTALLOCATIONERROR, obj->file, obj->line, obj->name); - return; - } - - obj->context = prog; - - prog->setMorphAnimationIncluded(false); - prog->setPoseAnimationIncluded(0); - prog->setSkeletalAnimationIncluded(false); - prog->setVertexTextureFetchRequired(false); - prog->_notifyOrigin(obj->file); - - // special case for Cg - if(!profiles.empty()) - prog->setParameter("profiles", profiles); - - // special case for HLSL - if(!target.empty()) - prog->setParameter("target", target); - - // special case for unified - for(const auto& d : delegates) - prog->setParameter("delegate", d); - - // Set the custom parameters - for(const auto& p : customParameters) - { - if(prog->isSupported() && !prog->setParameter(p.first->name, p.second)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, p.first->file, p.first->line, p.first->name); - } - } - - // Set up default parameters - if(prog->isSupported() && params) - { - GpuProgramParametersSharedPtr ptr = prog->getDefaultParameters(); - - if(prog->hasCompileError()) - return; - - GpuProgramTranslator::translateProgramParameters(compiler, ptr, static_cast(params.get())); - } - } - //------------------------------------------------------------------------- - static int parseProgramParameterDimensions(String& declarator, BaseConstantType& type) - { - // Assume 1 unless otherwise specified - int dimensions = 1; - type = BCT_UNKNOWN; - - // get the type - const char* typeStrings[] = {"float", "int", "uint", "double", "bool"}; - BaseConstantType baseTypes[] = {BCT_FLOAT, BCT_INT, BCT_UINT, BCT_DOUBLE, BCT_BOOL}; - - const char* typeStr = ""; - - for(int i = 0; i < 5; ++i) - { - if(declarator.find(typeStrings[i]) == 0) - { - type = baseTypes[i]; - typeStr = typeStrings[i]; - break; - } - } - - if(type == BCT_UNKNOWN) - return dimensions; - - size_t start = declarator.find_first_not_of(typeStr); - - if (start != String::npos) - { - size_t end = declarator.find_first_of('[', start); - - // int1, int2, etc. - if (end != start) - { - dimensions *= StringConverter::parseInt( - declarator.substr(start, end - start)); - start = end; - } - - // C-style array - while (start != String::npos) - { - end = declarator.find_first_of(']', start); - dimensions *= StringConverter::parseInt( - declarator.substr(start + 1, end - start - 1)); - start = declarator.find_first_of('[', end); - } - } - - return dimensions; - } - //------------------------------------------------------------------------- - template - static void safeSetConstant(const GpuProgramParametersPtr& params, const String& name, size_t index, It arrayStart, - It arrayEnd, size_t count, PropertyAbstractNode* prop, ScriptCompiler* compiler) - { - int roundedCount = (count + 3) / 4; // integer ceil - roundedCount *= 4; - - std::vector vals; - if (!_getVector(arrayStart, arrayEnd, vals, roundedCount)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - return; - } - - try - { - if (!name.empty()) - params->setNamedConstant(name, vals.data(), count, 1); - else - params->setConstant(index, vals.data(), roundedCount / 4); - } - catch (Exception& e) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, e.getDescription()); - } - } - - void GpuProgramTranslator::translateProgramParameters(ScriptCompiler *compiler, const GpuProgramParametersSharedPtr& params, ObjectAbstractNode *obj) - { - uint32 animParametricsCount = 0; - - String value; - for(auto & i : obj->children) - { - if(i->type == ANT_PROPERTY) - { - PropertyAbstractNode *prop = static_cast(i.get()); - switch(prop->id) - { - case ID_SHARED_PARAMS_REF: - if(getValue(prop, compiler, value)) - { - try - { - params->addSharedParameters(value); - } - catch(Exception& e) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - e.getDescription()); - } - } - break; - //TODO Refactor this case. - case ID_PARAM_INDEXED: - case ID_PARAM_NAMED: - { - if(prop->values.size() >= 3) - { - bool named = (prop->id == ID_PARAM_NAMED); - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), i1 = getNodeAt(prop->values, 1), - k = getNodeAt(prop->values, 2); - - if((*i0)->type != ANT_ATOM || (*i1)->type != ANT_ATOM) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "name or index and parameter type expected"); - return; - } - - AtomAbstractNode *atom0 = (AtomAbstractNode*)(*i0).get(), *atom1 = (AtomAbstractNode*)(*i1).get(); - if(!named && !StringConverter::isNumber(atom0->value)) - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - "parameter index expected"); - return; - } - - String name; - size_t index = 0; - // Assign the name/index - if(named) - name = atom0->value; - else - index = StringConverter::parseInt(atom0->value); - - // Determine the type - if(atom1->value == "matrix4x4") - { - Matrix4 m; - if(getMatrix4(k, prop->values.end(), &m)) - { - try - { - if(named) - params->setNamedConstant(name, m); - else - params->setConstant(index, m); - } - catch (Exception& e) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - e.getDescription()); - } - } - else - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - "incorrect matrix4x4 declaration"); - } - } - else - { - int count; - BaseConstantType type; - - // First, clear out any offending auto constants - if (named) - params->clearNamedAutoConstant(name); - else - params->clearAutoConstant(index); - - count = parseProgramParameterDimensions(atom1->value, type); - - if (type == BCT_FLOAT) - { - safeSetConstant(params, name, index, k, prop->values.cend(), count, prop, compiler); - } - else if (type == BCT_UINT) - { - safeSetConstant(params, name, index, k, prop->values.cend(), count, prop, compiler); - } - else if (type == BCT_INT) - { - safeSetConstant(params, name, index, k, prop->values.cend(), count, prop, compiler); - } - else if (type == BCT_DOUBLE) - { - safeSetConstant(params, name, index, k, prop->values.cend(), count, prop, compiler); - } - else if (type == BCT_BOOL) - { - std::vector tmp; - int roundedCount = (count + 3) / 4; // integer ceil - roundedCount *= 4; - if (_getVector(k, prop->values.end(), tmp, roundedCount)) - { - std::vector vals(tmp.begin(), tmp.end()); - try - { - if (named) - params->setNamedConstant(name, vals.data(), count, 1); - else - params->setConstant(index, vals.data(), roundedCount/4); - } - catch (Exception& e) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - e.getDescription()); - } - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "incorrect boolean constant declaration"); - } - - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, prop->file, prop->line, - "bool. Use uint instead"); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "incorrect type specified; only variants of int, uint, float, double, and bool allowed"); - } - } - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "param_named and param_indexed properties requires at least 3 arguments"); - } - } - break; - case ID_PARAM_INDEXED_AUTO: - case ID_PARAM_NAMED_AUTO: - { - bool named = (prop->id == ID_PARAM_NAMED_AUTO); - String name; - - if(prop->values.size() >= 2) - { - size_t index = 0; - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), - i1 = getNodeAt(prop->values, 1), i2 = getNodeAt(prop->values, 2), i3 = getNodeAt(prop->values, 3); - if((*i0)->type != ANT_ATOM || (*i1)->type != ANT_ATOM) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "name or index and auto constant type expected"); - return; - } - AtomAbstractNode *atom0 = (AtomAbstractNode*)(*i0).get(), *atom1 = (AtomAbstractNode*)(*i1).get(); - if(!named && !StringConverter::isNumber(atom0->value)) - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - "parameter index expected"); - return; - } - - if(named) - name = atom0->value; - else - index = StringConverter::parseInt(atom0->value); - - // Look up the auto constant - StringUtil::toLowerCase(atom1->value); - const GpuProgramParameters::AutoConstantDefinition *def = - GpuProgramParameters::getAutoConstantDefinition(atom1->value); - if(def) - { - switch(def->dataType) - { - case GpuProgramParameters::ACDT_NONE: - if (i2 != prop->values.end()) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, - prop->line, "unexpected parameter"); - } - - // Set the auto constant - try - { - if(named) - params->setNamedAutoConstant(name, def->acType); - else - params->setAutoConstant(index, def->acType); - } - catch(Exception& e) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - e.getDescription()); - } - break; - case GpuProgramParameters::ACDT_INT: - if(def->acType == GpuProgramParameters::ACT_ANIMATION_PARAMETRIC) - { - try - { - if(named) - params->setNamedAutoConstant(name, def->acType, animParametricsCount++); - else - params->setAutoConstant(index, def->acType, animParametricsCount++); - } - catch(Exception& e) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - e.getDescription()); - } - } - else - { - // Only certain texture projection auto params will assume 0 - // Otherwise we will expect that 3rd parameter - if(i2 == prop->values.end()) - { - if(def->acType == GpuProgramParameters::ACT_TEXTURE_VIEWPROJ_MATRIX || - def->acType == GpuProgramParameters::ACT_TEXTURE_WORLDVIEWPROJ_MATRIX || - def->acType == GpuProgramParameters::ACT_SPOTLIGHT_VIEWPROJ_MATRIX || - def->acType == GpuProgramParameters::ACT_SPOTLIGHT_WORLDVIEWPROJ_MATRIX - ) - { - try - { - if(named) - params->setNamedAutoConstant(name, def->acType, 0); - else - params->setAutoConstant(index, def->acType, 0); - } - catch (Exception& e) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - e.getDescription()); - } - } - else - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - " parameter required by constant definition " + atom1->value); - } - } - else - { - bool success = false; - uint32 extraInfo = 0; - if(i3 == prop->values.end()) - { // Handle only one extra value - if(getUInt(*i2, &extraInfo)) - { - success = true; - } - } - else - { // Handle two extra values - uint32 extraInfo1 = 0, extraInfo2 = 0; - if(getUInt(*i2, &extraInfo1) && getUInt(*i3, &extraInfo2)) - { - extraInfo = extraInfo1 | (extraInfo2 << 16); - success = true; - } - } - - if(success) - { - try - { - if(named) - params->setNamedAutoConstant(name, def->acType, extraInfo); - else - params->setAutoConstant(index, def->acType, extraInfo); - } - catch (Exception& e) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - e.getDescription()); - } - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "invalid auto constant parameter"); - } - } - } - break; - case GpuProgramParameters::ACDT_REAL: - if(def->acType == GpuProgramParameters::ACT_TIME || - def->acType == GpuProgramParameters::ACT_FRAME_TIME) - { - Real f = 1.0f; - if(i2 != prop->values.end()) - getReal(*i2, &f); - - try - { - if(named) - params->setNamedAutoConstantReal(name, def->acType, f); - else - params->setAutoConstantReal(index, def->acType, f); - } - catch (Exception& e) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - e.getDescription()); - } - } - else - { - if(i2 != prop->values.end()) - { - Real extraInfo = 0.0f; - if(getReal(*i2, &extraInfo)) - { - try - { - if(named) - params->setNamedAutoConstantReal(name, def->acType, extraInfo); - else - params->setAutoConstantReal(index, def->acType, extraInfo); - } - catch(Exception& e) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - e.getDescription()); - } - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "incorrect float argument definition in parameter"); - } - } - else - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - " parameter required by constant definition " + atom1->value); - } - } - break; - } - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, atom1->value); - } - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - } - break; - // case ID_COMPUTE_WORKGROUP_DIMENSIONS: - // if (obj->id != ID_COMPUTE_PROGRAM) - // break; - // if (prop->values.size() == 3) - // { - // AbstractNodeList::const_iterator first_dimension = getNodeAt(prop->values, 0); - - // uint *vals = OGRE_ALLOC_T(uint, roundedCount, MEMCATEGORY_SCRIPTING); - // if(getUInts(k, prop->values.end(), vals, 3)) - // { - // try - // { - // params->setNamedConstant(name, m); - // } - // catch(...) - // { - // compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - // "setting workgroup_dimensions parameter failed"); - // } - // } - // else - // { - // compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - // "incorrect workgroup_dimensions declaration"); - // } - // } - // else - // { - // compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - // "workgroup_dimensions property requires 3 arguments"); - // } - - - // break; - default: - compiler->addError(ScriptCompiler::CE_UNEXPECTEDTOKEN, prop->file, prop->line, - "token \"" + prop->name + "\" is not recognized"); - } - } - } - } - /************************************************************************** - * SharedParamsTranslator - *************************************************************************/ - SharedParamsTranslator::SharedParamsTranslator() - { - } - - //------------------------------------------------------------------------- - void SharedParamsTranslator::translate(ScriptCompiler *compiler, const AbstractNodePtr &node) - { - ObjectAbstractNode *obj = static_cast(node.get()); - - // Must have a name - if (obj->name.empty()) - { - compiler->addError(ScriptCompiler::CE_OBJECTNAMEEXPECTED, obj->file, obj->line); - return; - } - - GpuSharedParameters* sharedParams = 0; - CreateGpuSharedParametersScriptCompilerEvent evt(obj->file, obj->name, compiler->getResourceGroup()); - bool processed = compiler->_fireEvent(&evt, (void*)&sharedParams); - - if (!processed) - { - sharedParams = GpuProgramManager::getSingleton().createSharedParameters(obj->name).get(); - } - - if (!sharedParams) - { - compiler->addError(ScriptCompiler::CE_OBJECTALLOCATIONERROR, obj->file, obj->line, obj->name); - return; - } - - for (auto & i : obj->children) - { - if (i->type != ANT_PROPERTY) - continue; - - PropertyAbstractNode *prop = static_cast(i.get()); - if (prop->id != ID_SHARED_PARAM_NAMED) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - prop->name); - continue; - } - - if (prop->values.size() < 2) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "shared_param_named - expected 2 or more arguments"); - continue; - } - - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), i1 = getNodeAt(prop->values, 1); - - String pName; - GpuConstantType constType; - - if (!getValue(*i0, pName) || !getConstantType(i1, &constType)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "name and parameter type expected"); - continue; - } - - AbstractNodeList::const_iterator arrayStart = getNodeAt(prop->values, 2), arrayEnd = prop->values.end(); - uint32 arraySz = 1; - - if (arrayStart != arrayEnd) - { - String value; - getValue(*arrayStart, value); - - if (value.front() == '[' && value.back() == ']') - { - arraySz = StringConverter::parseInt(value.substr(1, value.size() - 2), 0); - if(!arraySz) - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line, - "invalid array size"); - continue; - } - arrayStart++; - } - } - - // define constant entry - try - { - sharedParams->addConstantDefinition(pName, constType, arraySz); - } - catch(Exception& e) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - e.getDescription()); - continue; - } - - // amount of individual numbers to read - arraySz *= GpuConstantDefinition::getElementSize(constType, false); - - switch (GpuConstantDefinition::getBaseType(constType)) - { - case BCT_FLOAT: - { - std::vector values; - if(_getVector(arrayStart, arrayEnd, values, arraySz)) - sharedParams->setNamedConstant(pName, &values[0], arraySz); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - break; - } - case BCT_INT: - { - std::vector values; - if(_getVector(arrayStart, arrayEnd, values, arraySz)) - sharedParams->setNamedConstant(pName, &values[0], arraySz); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - break; - } - case BCT_DOUBLE: - { - std::vector values; - if(_getVector(arrayStart, arrayEnd, values, arraySz)) - sharedParams->setNamedConstant(pName, &values[0], arraySz); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - break; - } - case BCT_UINT: - { - std::vector values; - if(_getVector(arrayStart, arrayEnd, values, arraySz)) - { - sharedParams->setNamedConstant(pName, &values[0], arraySz); - } - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - break; - } - case BCT_BOOL: - { - compiler->addError(ScriptCompiler::CE_DEPRECATEDSYMBOL, prop->file, prop->line, - "bool. Use uint instead"); - std::vector tmp; - if(_getVector(arrayStart, arrayEnd, tmp, arraySz)) - { - std::vector values(tmp.begin(), tmp.end()); - sharedParams->setNamedConstant(pName, &values[0], arraySz); - } - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - break; - } - default: - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "invalid parameter type"); - break; - } - } - } - - /************************************************************************** - * ParticleSystemTranslator - *************************************************************************/ - ParticleSystemTranslator::ParticleSystemTranslator() - :mSystem(0) - { - } - - void ParticleSystemTranslator::translate(ScriptCompiler* compiler, const AbstractNodePtr &node) - { - ObjectAbstractNode *obj = static_cast(node.get()); - // Find the name - if(obj->name.empty()) - { - compiler->addError(ScriptCompiler::CE_OBJECTNAMEEXPECTED, obj->file, obj->line); - return; - } - - // Allocate the particle system - CreateParticleSystemScriptCompilerEvent evt(obj->file, obj->name, compiler->getResourceGroup()); - bool processed = compiler->_fireEvent(&evt, (void*)&mSystem); - - if(!processed) - { - mSystem = ParticleSystemManager::getSingleton().createTemplate(obj->name, compiler->getResourceGroup()); - } - - if(!mSystem) - { - compiler->addError(ScriptCompiler::CE_OBJECTALLOCATIONERROR, obj->file, obj->line, obj->name); - return; - } - - mSystem->_notifyOrigin(obj->file); - - mSystem->removeAllEmitters(); - mSystem->removeAllAffectors(); - - obj->context = mSystem; - - for(auto & i : obj->children) - { - if(i->type == ANT_PROPERTY) - { - PropertyAbstractNode *prop = static_cast(i.get()); - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - return; - } - - String value; - if(prop->id == ID_MATERIAL) - { - if(prop->values.front()->type == ANT_ATOM) - { - value = ((AtomAbstractNode*)prop->values.front().get())->value; - - ProcessResourceNameScriptCompilerEvent locEvt(ProcessResourceNameScriptCompilerEvent::MATERIAL, value); - compiler->_fireEvent(&locEvt, 0); - value = locEvt.mName; - } - } - else - { - // Glob the values together - for(auto& v : prop->values) - { - if(v->type == ANT_ATOM) - { - if(value.empty()) - value = ((AtomAbstractNode*)v.get())->value; - else - value = value + " " + ((AtomAbstractNode*)v.get())->value; - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - return; - } - } - } - - if(!mSystem->setParameter(prop->name, value)) - { - if(auto renderer = mSystem->getRenderer()) - { - if(!renderer->setParameter(prop->name, value)) - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - } - } - else - { - processNode(compiler, i); - } - } - } - - /************************************************************************** - * ParticleEmitterTranslator - *************************************************************************/ - ParticleEmitterTranslator::ParticleEmitterTranslator() - :mEmitter(0) - { - } - //------------------------------------------------------------------------- - void ParticleEmitterTranslator::translate(ScriptCompiler *compiler, const AbstractNodePtr &node) - { - ObjectAbstractNode *obj = static_cast(node.get()); - - // Must have a type as the first value - if(obj->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, obj->file, obj->line); - return; - } - - ParticleSystem *system = any_cast(obj->parent->context); - - try - { - mEmitter = system->addEmitter(obj->values.front()->getString()); - } - catch(Exception &e) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, obj->file, obj->line, e.getDescription()); - return; - } - - for(auto & i : obj->children) - { - if(i->type == ANT_PROPERTY) - { - PropertyAbstractNode *prop = static_cast(i.get()); - String value; - - // Glob the values together - for(AbstractNodeList::iterator it = prop->values.begin(); it != prop->values.end(); ++it) - { - if((*it)->type == ANT_ATOM) - { - if(value.empty()) - value = ((AtomAbstractNode*)(*it).get())->value; - else - value = value + " " + ((AtomAbstractNode*)(*it).get())->value; - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - break; - } - } - - if(!mEmitter->setParameter(prop->name, value)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - } - else - { - processNode(compiler, i); - } - } - } - - /************************************************************************** - * ParticleAffectorTranslator - *************************************************************************/ - ParticleAffectorTranslator::ParticleAffectorTranslator() - :mAffector(0) - { - } - //------------------------------------------------------------------------- - void ParticleAffectorTranslator::translate(ScriptCompiler *compiler, const AbstractNodePtr &node) - { - ObjectAbstractNode *obj = static_cast(node.get()); - - // Must have a type as the first value - if(obj->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, obj->file, obj->line); - return; - } - - ParticleSystem *system = any_cast(obj->parent->context); - try - { - mAffector = system->addAffector(obj->values.front()->getString()); - } - catch(Exception &e) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, obj->file, obj->line, e.getDescription()); - return; - } - - for(auto & i : obj->children) - { - if(i->type == ANT_PROPERTY) - { - PropertyAbstractNode *prop = static_cast(i.get()); - String value; - - // Glob the values together - for(AbstractNodeList::iterator it = prop->values.begin(); it != prop->values.end(); ++it) - { - if((*it)->type == ANT_ATOM) - { - if(value.empty()) - value = ((AtomAbstractNode*)(*it).get())->value; - else - value = value + " " + ((AtomAbstractNode*)(*it).get())->value; - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - break; - } - } - - if(!mAffector->setParameter(prop->name, value)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - } - else - { - processNode(compiler, i); - } - } - } - - /************************************************************************** - * CompositorTranslator - *************************************************************************/ - CompositorTranslator::CompositorTranslator() - :mCompositor(0) - { - } - - void CompositorTranslator::translate(ScriptCompiler *compiler, const AbstractNodePtr &node) - { - ObjectAbstractNode *obj = static_cast(node.get()); - if(obj->name.empty()) - { - compiler->addError(ScriptCompiler::CE_OBJECTNAMEEXPECTED, obj->file, obj->line); - return; - } - - // Create the compositor - CreateCompositorScriptCompilerEvent evt(obj->file, obj->name, compiler->getResourceGroup()); - bool processed = compiler->_fireEvent(&evt, (void*)&mCompositor); - - if(!processed) - { - mCompositor = CompositorManager::getSingleton().create(obj->name, compiler->getResourceGroup()).get(); - } - - if(!mCompositor) - { - compiler->addError(ScriptCompiler::CE_OBJECTALLOCATIONERROR, obj->file, obj->line, obj->name); - return; - } - - // Prepare the compositor - mCompositor->removeAllTechniques(); - mCompositor->_notifyOrigin(obj->file); - obj->context = mCompositor; - - for(auto & i : obj->children) - { - if(i->type == ANT_OBJECT) - { - processNode(compiler, i); - } - else - { - compiler->addError(ScriptCompiler::CE_UNEXPECTEDTOKEN, i->file, i->line, - "token not recognized"); - } - } - } - - /************************************************************************** - * CompositionTechniqueTranslator - *************************************************************************/ - CompositionTechniqueTranslator::CompositionTechniqueTranslator() - :mTechnique(0) - { - } - //------------------------------------------------------------------------- - void CompositionTechniqueTranslator::translate(ScriptCompiler *compiler, const AbstractNodePtr &node) - { - ObjectAbstractNode *obj = static_cast(node.get()); - - Compositor *compositor = any_cast(obj->parent->context); - mTechnique = compositor->createTechnique(); - obj->context = mTechnique; - - String sval; - - for(auto & i : obj->children) - { - if(i->type == ANT_OBJECT) - { - processNode(compiler, i); - } - else if(i->type == ANT_PROPERTY) - { - PropertyAbstractNode *prop = static_cast(i.get()); - switch(prop->id) - { - case ID_TEXTURE: - { - size_t atomIndex = 1; - - AbstractNodeList::const_iterator it = getNodeAt(prop->values, 0); - - if((*it)->type != ANT_ATOM) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - return; - } - // Save the first atom, should be name - AtomAbstractNode *atom0 = (AtomAbstractNode*)(*it).get(); - - uint32 width = 0, height = 0; - float widthFactor = 1.0f, heightFactor = 1.0f; - bool widthSet = false, heightSet = false, formatSet = false; - bool pooled = false; - bool hwGammaWrite = false; - bool fsaa = true; - auto type = TEX_TYPE_2D; - uint16 depthBufferId = DepthBuffer::POOL_DEFAULT; - CompositionTechnique::TextureScope scope = CompositionTechnique::TS_LOCAL; - Ogre::PixelFormatList formats; - - while (atomIndex < prop->values.size()) - { - it = getNodeAt(prop->values, static_cast(atomIndex++)); - if((*it)->type != ANT_ATOM) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - return; - } - AtomAbstractNode *atom = (AtomAbstractNode*)(*it).get(); - - switch(atom->id) - { - case ID_TARGET_WIDTH: - width = 0; - widthSet = true; - break; - case ID_TARGET_HEIGHT: - height = 0; - heightSet = true; - break; - case ID_TARGET_WIDTH_SCALED: - case ID_TARGET_HEIGHT_SCALED: - { - bool *pSetFlag; - uint32 *pSize; - float *pFactor; - - if (atom->id == ID_TARGET_WIDTH_SCALED) - { - pSetFlag = &widthSet; - pSize = &width; - pFactor = &widthFactor; - } - else - { - pSetFlag = &heightSet; - pSize = &height; - pFactor = &heightFactor; - } - // advance to next to get scaling - it = getNodeAt(prop->values, static_cast(atomIndex++)); - if(prop->values.end() == it || (*it)->type != ANT_ATOM) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - return; - } - atom = (AtomAbstractNode*)(*it).get(); - if (!StringConverter::isNumber(atom->value)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - return; - } - - *pSize = 0; - *pFactor = StringConverter::parseReal(atom->value); - *pSetFlag = true; - } - break; - case ID_POOLED: - pooled = true; - break; - case ID_CUBIC: - type = TEX_TYPE_CUBE_MAP; - break; - case ID_SCOPE_LOCAL: - scope = CompositionTechnique::TS_LOCAL; - break; - case ID_SCOPE_CHAIN: - scope = CompositionTechnique::TS_CHAIN; - break; - case ID_SCOPE_GLOBAL: - scope = CompositionTechnique::TS_GLOBAL; - break; - case ID_GAMMA: - hwGammaWrite = true; - break; - case ID_NO_FSAA: - fsaa = false; - break; - case ID_DEPTH_POOL: - { - // advance to next to get the ID - it = getNodeAt(prop->values, static_cast(atomIndex++)); - if(prop->values.end() == it || (*it)->type != ANT_ATOM) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - return; - } - atom = (AtomAbstractNode*)(*it).get(); - if (!StringConverter::isNumber(atom->value)) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - return; - } - - depthBufferId = Math::uint16Cast(StringConverter::parseInt(atom->value)); - } - break; - default: - if (StringConverter::isNumber(atom->value)) - { - if (atomIndex == 2) - { - width = StringConverter::parseInt(atom->value); - widthSet = true; - } - else if (atomIndex == 3) - { - height = StringConverter::parseInt(atom->value); - heightSet = true; - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - return; - } - } - else - { - // pixel format? - PixelFormat format = PixelUtil::getFormatFromName(atom->value, true); - if (format == PF_UNKNOWN) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, atom->value); - return; - } - formats.push_back(format); - formatSet = true; - } - - } - } - if (!widthSet || !heightSet || !formatSet) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - return; - } - - - // No errors, create - CompositionTechnique::TextureDefinition *def = mTechnique->createTextureDefinition(atom0->value); - def->width = width; - def->height = height; - def->type = type; - def->widthFactor = widthFactor; - def->heightFactor = heightFactor; - def->formatList = formats; - def->fsaa = fsaa; - def->hwGammaWrite = hwGammaWrite; - def->depthBufferId = depthBufferId; - def->pooled = pooled; - def->scope = scope; - } - break; - case ID_TEXTURE_REF: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - } - else if(prop->values.size() != 3) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "texture_ref only supports 3 argument"); - } - else - { - String texName, refCompName, refTexName; - - AbstractNodeList::const_iterator it = getNodeAt(prop->values, 0); - if(!getString(*it, &texName)) - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "texture_ref must have 3 string arguments"); - - it = getNodeAt(prop->values, 1); - if(!getString(*it, &refCompName)) - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "texture_ref must have 3 string arguments"); - - it = getNodeAt(prop->values, 2); - if(!getString(*it, &refTexName)) - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, - "texture_ref must have 3 string arguments"); - - CompositionTechnique::TextureDefinition* refTexDef = - mTechnique->createTextureDefinition(texName); - - refTexDef->refCompName = refCompName; - refTexDef->refTexName = refTexName; - } - break; - case ID_SCHEME: - if(getValue(prop, compiler, sval)) - mTechnique->setSchemeName(sval); - break; - case ID_COMPOSITOR_LOGIC: - if(getValue(prop, compiler, sval)) - mTechnique->setCompositorLogicName(sval); - break; - default: - compiler->addError(ScriptCompiler::CE_UNEXPECTEDTOKEN, prop->file, prop->line, - "token \"" + prop->name + "\" is not recognized"); - } - } - } - } - - /************************************************************************** - * CompositionTargetPass - *************************************************************************/ - CompositionTargetPassTranslator::CompositionTargetPassTranslator() - :mTarget(0) - { - } - //------------------------------------------------------------------------- - void CompositionTargetPassTranslator::translate(ScriptCompiler *compiler, const AbstractNodePtr &node) - { - ObjectAbstractNode *obj = static_cast(node.get()); - - CompositionTechnique *technique = any_cast(obj->parent->context); - if(obj->id == ID_TARGET) - { - mTarget = technique->createTargetPass(); - if(obj->name.empty()) - { - compiler->addError(ScriptCompiler::CE_OBJECTNAMEEXPECTED, obj->file, obj->line); - return; - } - mTarget->setOutputName(obj->name); - - if(!obj->values.empty()) - { - int val; - if(getInt(obj->values.front(), &val)) - mTarget->setOutputSlice(val); - } - } - else if(obj->id == ID_TARGET_OUTPUT) - { - mTarget = technique->getOutputTargetPass(); - if (!mTarget->getPasses().empty() || mTarget->getInputMode() != CompositionTargetPass::IM_NONE) - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, obj->file, obj->line, - "target_output can only be used once per technique"); - } - } - obj->context = mTarget; - - bool bval; - Real fval; - uint32 uival; - String sval; - - for(auto & i : obj->children) - { - if(i->type == ANT_OBJECT) - { - processNode(compiler, i); - } - else if(i->type == ANT_PROPERTY) - { - PropertyAbstractNode *prop = static_cast(i.get()); - switch(prop->id) - { - case ID_INPUT: - CompositionTargetPass::InputMode im; - if(getValue(prop, compiler, im)) - mTarget->setInputMode(im); - break; - case ID_ONLY_INITIAL: - if(getValue(prop, compiler, bval)) - mTarget->setOnlyInitial(bval); - break; - case ID_VISIBILITY_MASK: - if(getValue(prop, compiler, uival)) - mTarget->setVisibilityMask(uival); - break; - case ID_LOD_BIAS: - if(getValue(prop, compiler, fval)) - mTarget->setLodBias(fval); - break; - case ID_MATERIAL_SCHEME: - if(getValue(prop, compiler, sval)) - mTarget->setMaterialScheme(sval); - break; - case ID_SHADOWS_ENABLED: - if(getValue(prop, compiler, bval)) - mTarget->setShadowsEnabled(bval); - break; - default: - compiler->addError(ScriptCompiler::CE_UNEXPECTEDTOKEN, prop->file, prop->line, - "token \"" + prop->name + "\" is not recognized"); - } - } - } - } - - /************************************************************************** - * CompositionPassTranslator - *************************************************************************/ - CompositionPassTranslator::CompositionPassTranslator() - :mPass(0) - { - } - - void CompositionPassTranslator::translate(ScriptCompiler *compiler, const AbstractNodePtr &node) - { - ObjectAbstractNode *obj = static_cast(node.get()); - - // The name is the type of the pass - if(obj->values.empty() || obj->values.front()->type != ANT_ATOM) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, obj->file, obj->line, "pass type missing"); - return; - } - - AtomAbstractNode* atom = static_cast(obj->values.front().get()); - - CompositionPass::PassType ptype; - switch(atom->id) - { - case ID_CLEAR: - ptype = CompositionPass::PT_CLEAR; - break; - case ID_STENCIL: - ptype = CompositionPass::PT_STENCIL; - break; - case ID_RENDER_QUAD: - ptype = CompositionPass::PT_RENDERQUAD; - break; - case ID_RENDER_SCENE: - ptype = CompositionPass::PT_RENDERSCENE; - break; - case ID_COMPUTE: - ptype = CompositionPass::PT_COMPUTE; - break; - case ID_RENDER_CUSTOM: - ptype = CompositionPass::PT_RENDERCUSTOM; - break; - default: - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, obj->file, obj->line, atom->value); - return; - } - - CompositionTargetPass *target = any_cast(obj->parent->context); - mPass = target->createPass(ptype); - obj->context = mPass; - - if(mPass->getType() == CompositionPass::PT_RENDERCUSTOM) - { - String customType; - //This is the ugly one liner for safe access to the second parameter. - if (obj->values.size() < 2 || !getString(*(++(obj->values.begin())), &customType)) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, obj->file, obj->line); - return; - } - mPass->setCustomType(customType); - } - - Real fval; - bool bval; - uint32 uival; - String sval; - StencilOperation sop; - - for(auto & i : obj->children) - { - if(i->type == ANT_OBJECT) - { - processNode(compiler, i); - } - else if(i->type == ANT_PROPERTY) - { - PropertyAbstractNode *prop = static_cast(i.get()); - switch(prop->id) - { - case ID_CHECK: - if(getValue(prop, compiler, bval)) - mPass->setStencilCheck(bval); - break; - case ID_COMP_FUNC: - CompareFunction func; - if(getValue(prop, compiler, func)) - mPass->setStencilFunc(func); - break; - case ID_REF_VALUE: - if(getValue(prop, compiler, uival)) - mPass->setStencilRefValue(uival); - break; - case ID_MASK: - if(getValue(prop, compiler, uival)) - mPass->setStencilMask(uival); - break; - case ID_FAIL_OP: - if(getValue(prop, compiler, sop)) - mPass->setStencilFailOp(sop); - break; - case ID_DEPTH_FAIL_OP: - if(getValue(prop, compiler, sop)) - mPass->setStencilDepthFailOp(sop); - break; - case ID_PASS_OP: - if(getValue(prop, compiler, sop)) - mPass->setStencilPassOp(sop); - break; - case ID_TWO_SIDED: - if(getValue(prop, compiler, bval)) - mPass->setStencilTwoSidedOperation(bval); - break; - case ID_BUFFERS: - { - uint32 buffers = 0; - for(AbstractNodeList::iterator k = prop->values.begin(); k != prop->values.end(); ++k) - { - if((*k)->type == ANT_ATOM) - { - switch(((AtomAbstractNode*)(*k).get())->id) - { - case ID_COLOUR: - buffers |= FBT_COLOUR; - break; - case ID_DEPTH: - buffers |= FBT_DEPTH; - break; - case ID_STENCIL: - buffers |= FBT_STENCIL; - break; - default: - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - } - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - mPass->setClearBuffers(buffers); - } - break; - case ID_COLOUR_VALUE: - { - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line); - return; - } - ColourValue val; - if (prop->values.front()->type == ANT_ATOM && - ((AtomAbstractNode*)prop->values.front().get())->id == ID_AUTO) - mPass->setAutomaticColour(true); - else if(getColour(prop->values.begin(), prop->values.end(), &val)) - mPass->setClearColour(val); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - break; - case ID_DEPTH_VALUE: - if(getValue(prop, compiler, fval)) - mPass->setClearDepth(fval); - break; - case ID_STENCIL_VALUE: - if(getValue(prop, compiler, uival)) - mPass->setClearStencil(uival); - break; - case ID_MATERIAL: - if(getValue(prop, compiler, sval)) - { - ProcessResourceNameScriptCompilerEvent evt(ProcessResourceNameScriptCompilerEvent::MATERIAL, sval); - compiler->_fireEvent(&evt, 0); - auto mat = MaterialManager::getSingleton().getByName(evt.mName, compiler->getResourceGroup()); - if (mat) - mPass->setMaterial(mat); - else - compiler->addError(ScriptCompiler::CE_REFERENCETOANONEXISTINGOBJECT, prop->file, - prop->line, evt.mName); - } - break; - case ID_INPUT: - if(prop->values.size() < 2) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - return; - } - else if (prop->values.size() > 3) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line); - return; - } - else - { - AbstractNodeList::const_iterator i0 = getNodeAt(prop->values, 0), i1 = getNodeAt(prop->values, 1), i2 = getNodeAt(prop->values, 2); - uint32 id; - String name; - if(getUInt(*i0, &id) && getString(*i1, &name)) - { - uint32 index = 0; - if(i2 != prop->values.end()) - { - if(!getUInt(*i2, &index)) - { - compiler->addError(ScriptCompiler::CE_NUMBEREXPECTED, prop->file, prop->line); - return; - } - } - - mPass->setInput(id, name, index); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - } - break; - case ID_IDENTIFIER: - if(getValue(prop, compiler, uival)) - mPass->setIdentifier(uival); - break; - case ID_FIRST_RENDER_QUEUE: - if(getValue(prop, compiler, uival)) - mPass->setFirstRenderQueue(static_cast(uival)); - break; - case ID_LAST_RENDER_QUEUE: - if(getValue(prop, compiler, uival)) - mPass->setLastRenderQueue(static_cast(uival)); - break; - case ID_MATERIAL_SCHEME: - if(getValue(prop, compiler, sval)) - mPass->setMaterialScheme(sval); - break; - case ID_THREAD_GROUPS: - { - std::vector g; - if(_getVector(prop->values.begin(), prop->values.end(), g, 3)) - mPass->setThreadGroups({g[0], g[1], g[2]}); - break; - } - case ID_QUAD_NORMALS: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - return; - } - else if (prop->values.size() > 1) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line); - return; - } - else - { - if(prop->values.front()->type == ANT_ATOM) - { - atom = static_cast(prop->values.front().get()); - if(atom->id == ID_CAMERA_FAR_CORNERS_VIEW_SPACE) - mPass->setQuadFarCorners(true, true); - else if(atom->id == ID_CAMERA_FAR_CORNERS_WORLD_SPACE) - mPass->setQuadFarCorners(true, false); - else - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - else - { - compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); - } - } - break; - case ID_CAMERA: - if(prop->values.empty()) - { - compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); - return; - } - else if (prop->values.size() > 2) - { - compiler->addError(ScriptCompiler::CE_FEWERPARAMETERSEXPECTED, prop->file, prop->line); - return; - } - else - { - if (!getValue(prop->values.front(), sval)) - return; - mPass->setCameraName(sval); - if (prop->values.back()->type == ANT_ATOM && - static_cast(prop->values.back().get())->id == - ID_ALIGN_TO_FACE) - { - mPass->setAlignCameraToFace(true); - } - } - break; - default: - compiler->addError(ScriptCompiler::CE_UNEXPECTEDTOKEN, prop->file, prop->line, - "token \"" + prop->name + "\" is not recognized"); - } - } - } - } - - /************************************************************************** - * BuiltinScriptTranslatorManager - *************************************************************************/ - BuiltinScriptTranslatorManager::BuiltinScriptTranslatorManager() - { - } - //------------------------------------------------------------------------- - ScriptTranslator *BuiltinScriptTranslatorManager::getTranslator(const AbstractNodePtr &node) - { - ScriptTranslator *translator = 0; - - if(node->type == ANT_OBJECT) - { - ObjectAbstractNode *obj = static_cast(node.get()); - ObjectAbstractNode *parent = obj->parent ? static_cast(obj->parent) : 0; - if(obj->id == ID_MATERIAL) - translator = &mMaterialTranslator; - else if(obj->id == ID_TECHNIQUE && parent && parent->id == ID_MATERIAL) - translator = &mTechniqueTranslator; - else if(obj->id == ID_PASS && parent && parent->id == ID_TECHNIQUE) - translator = &mPassTranslator; - else if(obj->id == ID_TEXTURE_UNIT && parent && parent->id == ID_PASS) - translator = &mTextureUnitTranslator; - else if(obj->id == ID_TEXTURE_SOURCE && parent && parent->id == ID_TEXTURE_UNIT) - translator = &mTextureSourceTranslator; - else if(obj->id == ID_FRAGMENT_PROGRAM || - obj->id == ID_VERTEX_PROGRAM || - obj->id == ID_GEOMETRY_PROGRAM || - obj->id == ID_TESSELLATION_HULL_PROGRAM || - obj->id == ID_TESSELLATION_DOMAIN_PROGRAM || - obj->id == ID_COMPUTE_PROGRAM) - translator = &mGpuProgramTranslator; - else if(obj->id == ID_SHARED_PARAMS) - translator = &mSharedParamsTranslator; - else if(obj->id == ID_PARTICLE_SYSTEM) - translator = &mParticleSystemTranslator; - else if(obj->id == ID_EMITTER) - translator = &mParticleEmitterTranslator; - else if(obj->id == ID_AFFECTOR) - translator = &mParticleAffectorTranslator; - else if(obj->id == ID_COMPOSITOR) - translator = &mCompositorTranslator; - else if(obj->id == ID_TECHNIQUE && parent && parent->id == ID_COMPOSITOR) - translator = &mCompositionTechniqueTranslator; - else if((obj->id == ID_TARGET || obj->id == ID_TARGET_OUTPUT) && parent && parent->id == ID_TECHNIQUE) - translator = &mCompositionTargetPassTranslator; - else if(obj->id == ID_PASS && parent && (parent->id == ID_TARGET || parent->id == ID_TARGET_OUTPUT)) - translator = &mCompositionPassTranslator; - else if(obj->id == ID_SAMPLER) - translator = &mSamplerTranslator; - } - - return translator; - } -} diff --git a/OgreMain/src/OgreSearchOps.cpp b/OgreMain/src/OgreSearchOps.cpp deleted file mode 100644 index 48fdc330c2b..00000000000 --- a/OgreMain/src/OgreSearchOps.cpp +++ /dev/null @@ -1,162 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -// Emulate _findfirst, _findnext on non-Windows platforms -#include "OgreSearchOps.h" -#include -#include -#include -#include -#include -#include - -/* Win32 directory operations emulation */ -#if OGRE_PLATFORM != OGRE_PLATFORM_WIN32 && OGRE_PLATFORM != OGRE_PLATFORM_WINRT - -struct _find_search_t -{ - char *pattern; - char *curfn; - char *directory; - int dirlen; - DIR *dirfd; -}; - -intptr_t _findfirst(const char *pattern, struct _finddata_t *data) -{ - _find_search_t *fs = new _find_search_t; - fs->curfn = NULL; - fs->pattern = NULL; - - // Separate the mask from directory name - const char *mask = strrchr (pattern, '/'); - if (mask) - { - fs->dirlen = static_cast(mask - pattern); - mask++; - fs->directory = (char *)malloc (fs->dirlen + 1); - memcpy (fs->directory, pattern, fs->dirlen); - fs->directory [fs->dirlen] = 0; - } - else - { - mask = pattern; - fs->directory = strdup ("."); - fs->dirlen = 1; - } - - fs->dirfd = opendir (fs->directory); - if (!fs->dirfd) - { - _findclose ((intptr_t)fs); - return -1; - } - - /* Hack for "*.*" -> "*' from DOS/Windows */ - if (strcmp (mask, "*.*") == 0) - mask += 2; - fs->pattern = strdup (mask); - - /* Get the first entry */ - if (_findnext ((intptr_t)fs, data) < 0) - { - _findclose ((intptr_t)fs); - return -1; - } - - return (intptr_t)fs; -} - -int _findnext(intptr_t id, struct _finddata_t *data) -{ - _find_search_t *fs = reinterpret_cast<_find_search_t *>(id); - - /* Loop until we run out of entries or find the next one */ - dirent *entry; - for (;;) - { - if (!(entry = readdir (fs->dirfd))) - return -1; - - /* See if the filename matches our pattern */ - if (fnmatch (fs->pattern, entry->d_name, 0) == 0) - break; - } - - if (fs->curfn) - free (fs->curfn); - data->name = fs->curfn = strdup (entry->d_name); - - size_t namelen = strlen (entry->d_name); - char *xfn = new char [fs->dirlen + 1 + namelen + 1]; - sprintf (xfn, "%s/%s", fs->directory, entry->d_name); - - /* stat the file to get if it's a subdir and to find its length */ - struct stat stat_buf; - if (stat (xfn, &stat_buf)) - { - // Hmm strange, imitate a zero-length file then - data->attrib = _A_NORMAL; - data->size = 0; - } - else - { - if (S_ISDIR(stat_buf.st_mode)) - data->attrib = _A_SUBDIR; - else - /* Default type to a normal file */ - data->attrib = _A_NORMAL; - - data->size = (unsigned long)stat_buf.st_size; - } - - delete [] xfn; - - /* Files starting with a dot are hidden files in Unix */ - if (data->name [0] == '.') - data->attrib |= _A_HIDDEN; - - return 0; -} - -int _findclose(intptr_t id) -{ - int ret; - _find_search_t *fs = reinterpret_cast<_find_search_t *>(id); - - ret = fs->dirfd ? closedir (fs->dirfd) : 0; - free (fs->pattern); - free (fs->directory); - if (fs->curfn) - free (fs->curfn); - delete fs; - - return ret; -} - -#endif diff --git a/OgreMain/src/OgreSearchOps.h b/OgreMain/src/OgreSearchOps.h deleted file mode 100644 index 884e1c7fa40..00000000000 --- a/OgreMain/src/OgreSearchOps.h +++ /dev/null @@ -1,60 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __SearchOps_H_ -#define __SearchOps_H_ - -// Emulate _findfirst, _findnext on non-Windows platforms - -#include "OgrePlatform.h" - - -#if OGRE_PLATFORM != OGRE_PLATFORM_WIN32 && OGRE_PLATFORM != OGRE_PLATFORM_WINRT - -#include - -/* Our simplified data entry structure */ -struct _finddata_t -{ - char *name; - int attrib; - unsigned long size; -}; - -#define _A_NORMAL 0x00 /* Normalfile-Noread/writerestrictions */ -#define _A_RDONLY 0x01 /* Read only file */ -#define _A_HIDDEN 0x02 /* Hidden file */ -#define _A_SYSTEM 0x04 /* System file */ -#define _A_ARCH 0x20 /* Archive file */ -#endif -#define _A_SUBDIR 0x10 /* Subdirectory */ - -intptr_t _findfirst(const char *pattern, struct _finddata_t *data); -int _findnext(intptr_t id, struct _finddata_t *data); -int _findclose(intptr_t id); - -#endif diff --git a/OgreMain/src/OgreSerializer.cpp b/OgreMain/src/OgreSerializer.cpp deleted file mode 100644 index c4e9a44f7e7..00000000000 --- a/OgreMain/src/OgreSerializer.cpp +++ /dev/null @@ -1,404 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -namespace Ogre { - - const uint16 HEADER_STREAM_ID = 0x1000; - const uint16 OTHER_ENDIAN_HEADER_STREAM_ID = 0x0010; - //--------------------------------------------------------------------- - Serializer::Serializer() : - mVersion("[Serializer_v1.00]"), // Version number - mFlipEndian(false) -#if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE - , mReportChunkErrors(true) -#endif - { - } - - //--------------------------------------------------------------------- - Serializer::~Serializer() - { - } - //--------------------------------------------------------------------- - void Serializer::determineEndianness(const DataStreamPtr& stream) - { - if (stream->tell() != 0) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Can only determine the endianness of the input stream if it " - "is at the start", "Serializer::determineEndianness"); - } - - uint16 dest; - // read header id manually (no conversion) - size_t actually_read = stream->read(&dest, sizeof(uint16)); - // skip back - stream->skip(0 - (long)actually_read); - if (actually_read != sizeof(uint16)) - { - // end of file? - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Couldn't read 16 bit header value from input stream.", - "Serializer::determineEndianness"); - } - if (dest == HEADER_STREAM_ID) - { - mFlipEndian = false; - } - else if (dest == OTHER_ENDIAN_HEADER_STREAM_ID) - { - mFlipEndian = true; - } - else - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Header chunk didn't match either endian: Corrupted stream?", - "Serializer::determineEndianness"); - } - } - //--------------------------------------------------------------------- - void Serializer::determineEndianness(Endian requestedEndian) - { - switch(requestedEndian) - { - case ENDIAN_NATIVE: - mFlipEndian = false; - break; - case ENDIAN_BIG: -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - mFlipEndian = false; -#else - mFlipEndian = true; -#endif - break; - case ENDIAN_LITTLE: -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - mFlipEndian = true; -#else - mFlipEndian = false; -#endif - break; - } - } - //--------------------------------------------------------------------- - void Serializer::writeFileHeader(void) - { - - uint16 val = HEADER_STREAM_ID; - writeShorts(&val, 1); - - writeString(mVersion); - - } - //--------------------------------------------------------------------- - void Serializer::writeChunkHeader(uint16 id, size_t size) - { -#if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE - if (!mChunkSizeStack.empty()){ - size_t pos = mStream->tell(); - if (pos != static_cast(mChunkSizeStack.back()) && mReportChunkErrors){ - LogManager::getSingleton().logMessage("Corrupted chunk detected! Stream name: '" + mStream->getName() - + "' Chunk id: " + StringConverter::toString(id)); - } - mChunkSizeStack.back() = pos + size; - } -#endif - writeShorts(&id, 1); - uint32 uint32size = static_cast(size); - writeInts(&uint32size, 1); - } - //--------------------------------------------------------------------- - void Serializer::writeFloats(const float* const pFloat, size_t count) - { - if (mFlipEndian) - { - float * pFloatToWrite = (float *)malloc(sizeof(float) * count); - memcpy(pFloatToWrite, pFloat, sizeof(float) * count); - - flipToLittleEndian(pFloatToWrite, sizeof(float), count); - writeData(pFloatToWrite, sizeof(float), count); - - free(pFloatToWrite); - } - else - { - writeData(pFloat, sizeof(float), count); - } - } - //--------------------------------------------------------------------- - void Serializer::writeFloats(const double* const pDouble, size_t count) - { - // Convert to float, then write - float* tmp = OGRE_ALLOC_T(float, count, MEMCATEGORY_GENERAL); - for (unsigned int i = 0; i < count; ++i) - { - tmp[i] = static_cast(pDouble[i]); - } - if(mFlipEndian) - { - flipToLittleEndian(tmp, sizeof(float), count); - writeData(tmp, sizeof(float), count); - } - else - { - writeData(tmp, sizeof(float), count); - } - OGRE_FREE(tmp, MEMCATEGORY_GENERAL); - } - //--------------------------------------------------------------------- - void Serializer::writeShorts(const uint16* const pShort, size_t count = 1) - { - if(mFlipEndian) - { - unsigned short * pShortToWrite = (unsigned short *)malloc(sizeof(unsigned short) * count); - memcpy(pShortToWrite, pShort, sizeof(unsigned short) * count); - - flipToLittleEndian(pShortToWrite, sizeof(unsigned short), count); - writeData(pShortToWrite, sizeof(unsigned short), count); - - free(pShortToWrite); - } - else - { - writeData(pShort, sizeof(unsigned short), count); - } - } - //--------------------------------------------------------------------- - void Serializer::writeInts(const uint32* const pInt, size_t count = 1) - { - if(mFlipEndian) - { - uint32 * pIntToWrite = (uint32 *)malloc(sizeof(uint32) * count); - memcpy(pIntToWrite, pInt, sizeof(uint32) * count); - - flipToLittleEndian(pIntToWrite, sizeof(uint32), count); - writeData(pIntToWrite, sizeof(uint32), count); - - free(pIntToWrite); - } - else - { - writeData(pInt, sizeof(uint32), count); - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - void Serializer::writeBools(const bool* const pBool, size_t count = 1) - { - //no endian flipping for 1-byte bools - static_assert(sizeof(bool) == 1, "add conversion to char for your platform"); - writeData(pBool, sizeof(bool), count); - } - - //--------------------------------------------------------------------- - void Serializer::writeData(const void* const buf, size_t size, size_t count) - { - mStream->write(buf, size * count); - } - //--------------------------------------------------------------------- - void Serializer::writeString(const String& string) - { - // Old, backwards compatible way - \n terminated - mStream->write(string.c_str(), string.length()); - // Write terminating newline char - char terminator = '\n'; - mStream->write(&terminator, 1); - } - //--------------------------------------------------------------------- - void Serializer::readFileHeader(const DataStreamPtr& stream) - { - unsigned short headerID; - - // Read header ID - readShorts(stream, &headerID, 1); - - if (headerID == HEADER_STREAM_ID) - { - // Read version - String ver = readString(stream); - if (ver != mVersion) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Invalid file: version incompatible, file reports " + String(ver) + - " Serializer is version " + mVersion, - "Serializer::readFileHeader"); - } - } - else - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Invalid file: no header", - "Serializer::readFileHeader"); - } - - } - //--------------------------------------------------------------------- - unsigned short Serializer::readChunk(const DataStreamPtr& stream) - { -#if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE - size_t pos = stream->tell(); -#endif - unsigned short id; - readShorts(stream, &id, 1); - - readInts(stream, &mCurrentstreamLen, 1); -#if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE - if (!mChunkSizeStack.empty() && !stream->eof()){ - if (pos != static_cast(mChunkSizeStack.back()) && mReportChunkErrors){ - LogManager::getSingleton().logMessage("Corrupted chunk detected! Stream name: '" + stream->getName() + "' Chunk id: " + StringConverter::toString(id)); - } - mChunkSizeStack.back() = pos + mCurrentstreamLen; - } -#endif - return id; - } - //--------------------------------------------------------------------- - void Serializer::readBools(const DataStreamPtr& stream, bool* pDest, size_t count) - { - static_assert(sizeof(bool) == 1, "add conversion to char for your platform"); - stream->read(pDest, sizeof(bool) * count); - } - //--------------------------------------------------------------------- - void Serializer::readFloats(const DataStreamPtr& stream, float* pDest, size_t count) - { - stream->read(pDest, sizeof(float) * count); - flipFromLittleEndian(pDest, sizeof(float), count); - } - //--------------------------------------------------------------------- - void Serializer::readFloats(const DataStreamPtr& stream, double* pDest, size_t count) - { - // Read from float, convert to double - float* tmp = OGRE_ALLOC_T(float, count, MEMCATEGORY_GENERAL); - float* ptmp = tmp; - stream->read(tmp, sizeof(float) * count); - flipFromLittleEndian(tmp, sizeof(float), count); - // Convert to doubles (no cast required) - while(count--) - { - *pDest++ = *ptmp++; - } - OGRE_FREE(tmp, MEMCATEGORY_GENERAL); - } - //--------------------------------------------------------------------- - void Serializer::readShorts(const DataStreamPtr& stream, unsigned short* pDest, size_t count) - { - stream->read(pDest, sizeof(unsigned short) * count); - flipFromLittleEndian(pDest, sizeof(unsigned short), count); - } - //--------------------------------------------------------------------- - void Serializer::readInts(const DataStreamPtr& stream, uint32* pDest, size_t count) - { - stream->read(pDest, sizeof(uint32) * count); - flipFromLittleEndian(pDest, sizeof(uint32), count); - } - //--------------------------------------------------------------------- - String Serializer::readString(const DataStreamPtr& stream) - { - return stream->getLine(false); - } - //--------------------------------------------------------------------- - void Serializer::writeObject(const Vector3& vec) - { - writeFloats(vec.ptr(), 3); - } - //--------------------------------------------------------------------- - void Serializer::writeObject(const Quaternion& q) - { - float tmp[4] = { - static_cast(q.x), - static_cast(q.y), - static_cast(q.z), - static_cast(q.w) - }; - writeFloats(tmp, 4); - } - //--------------------------------------------------------------------- - void Serializer::readObject(const DataStreamPtr& stream, Vector3& pDest) - { - readFloats(stream, pDest.ptr(), 3); - } - //--------------------------------------------------------------------- - void Serializer::readObject(const DataStreamPtr& stream, Quaternion& pDest) - { - float tmp[4]; - readFloats(stream, tmp, 4); - pDest.x = tmp[0]; - pDest.y = tmp[1]; - pDest.z = tmp[2]; - pDest.w = tmp[3]; - } - //--------------------------------------------------------------------- - - - void Serializer::flipToLittleEndian(void* pData, size_t size, size_t count) - { - if(mFlipEndian) - { - Bitwise::bswapChunks(pData, size, count); - } - } - - void Serializer::flipFromLittleEndian(void* pData, size_t size, size_t count) - { - if(mFlipEndian) - { - Bitwise::bswapChunks(pData, size, count); - } - } - - void Serializer::pushInnerChunk(const DataStreamPtr& stream) - { -#if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE - mChunkSizeStack.push_back(stream->tell()); -#endif - } - void Serializer::backpedalChunkHeader(const DataStreamPtr& stream) - { - if (!stream->eof()){ - stream->skip(-(int)calcChunkHeaderSize()); - } -#if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE - mChunkSizeStack.back() = stream->tell(); -#endif - } - void Serializer::popInnerChunk(const DataStreamPtr& stream) - { -#if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE - if (!mChunkSizeStack.empty()){ - size_t pos = stream->tell(); - if (pos != static_cast(mChunkSizeStack.back()) && !stream->eof() && mReportChunkErrors){ - LogManager::getSingleton().logMessage("Corrupted chunk detected! Stream name: " + stream->getName()); - } - - mChunkSizeStack.pop_back(); - } -#endif - } - -} - diff --git a/OgreMain/src/OgreShadowCameraSetup.cpp b/OgreMain/src/OgreShadowCameraSetup.cpp deleted file mode 100644 index 4e0f88f7ce3..00000000000 --- a/OgreMain/src/OgreShadowCameraSetup.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" - -#include "OgreShadowCameraSetup.h" -#include "OgreViewport.h" - - -namespace Ogre -{ - /// Default constructor - DefaultShadowCameraSetup::DefaultShadowCameraSetup() {} - - /// Destructor - DefaultShadowCameraSetup::~DefaultShadowCameraSetup() {} - - /// Default shadow camera setup implementation - void DefaultShadowCameraSetup::getShadowCamera (const SceneManager *sm, const Camera *cam, - const Viewport *vp, const Light *light, Camera *texCam, size_t iteration) const - { - Vector3 pos, dir; - - // reset custom view / projection matrix in case already set - texCam->setCustomViewMatrix(false); - texCam->setCustomProjectionMatrix(false); - texCam->setNearClipDistance(light->_deriveShadowNearClipDistance(cam)); - texCam->setFarClipDistance(light->_deriveShadowFarClipDistance()); - - // get the shadow far distance - Real shadowDist = light->getShadowFarDistance(); - if (!shadowDist) - { - // need a shadow distance, make one up - shadowDist = cam->getNearClipDistance() * 300; - } - Real shadowOffset = shadowDist * (sm->getShadowDirLightTextureOffset()); - - // Directional lights - if (light->getType() == Light::LT_DIRECTIONAL) - { - // now we need the clip distance - if(auto farClip = texCam->getFarClipDistance()) - shadowDist = farClip; - // set up the shadow texture - // Set ortho projection - texCam->setProjectionType(PT_ORTHOGRAPHIC); - // set ortho window so that texture covers far dist - texCam->setOrthoWindow(shadowDist * 2, shadowDist * 2); - - // Calculate look at position - // We want to look at a spot shadowOffset away from near plane - // 0.5 is a little too close for angles - Vector3 target = cam->getDerivedPosition() + - (cam->getDerivedDirection() * shadowOffset); - - // Calculate direction, which same as directional light direction - dir = - light->getDerivedDirection(); // backwards since point down -z - dir.normalise(); - - // Calculate position - // We want to be in the -ve direction of the light direction - // far enough to project for the dir light extrusion distance - pos = target + dir * sm->getShadowDirectionalLightExtrusionDistance(); - - // Round local x/y position based on a world-space texel; this helps to reduce - // jittering caused by the projection moving with the camera - // Viewport is 2 * near clip distance across (90 degree fov) - //~ Real worldTexelSize = (texCam->getNearClipDistance() * 20) / vp->getActualWidth(); - //~ pos.x -= fmod(pos.x, worldTexelSize); - //~ pos.y -= fmod(pos.y, worldTexelSize); - //~ pos.z -= fmod(pos.z, worldTexelSize); - Real worldTexelSize = (shadowDist * 2) / texCam->getViewport()->getActualWidth(); - - //get texCam orientation - - Vector3 up = Vector3::UNIT_Y; - // Check it's not coincident with dir - if (Math::Abs(up.dotProduct(dir)) >= 1.0f) - { - // Use camera up - up = Vector3::UNIT_Z; - } - Matrix3 rot = Math::lookRotation(dir, up); - - //convert world space camera position into light space - Vector3 lightSpacePos = rot.transpose() * pos; - - //snap to nearest texel - lightSpacePos.x -= std::fmod(lightSpacePos.x, worldTexelSize); - lightSpacePos.y -= std::fmod(lightSpacePos.y, worldTexelSize); - - //convert back to world space - pos = rot * lightSpacePos; - - texCam->getParentNode()->setPosition(pos); - texCam->getParentNode()->setOrientation(rot); - } - // Spotlight - else if (light->getType() == Light::LT_SPOTLIGHT || light->getType() == Light::LT_RECTLIGHT) - { - // Set perspective projection - texCam->setProjectionType(PT_PERSPECTIVE); - // set FOV slightly larger than the spotlight range to ensure coverage - Radian fovy = light->getSpotlightOuterAngle()*1.2; - // limit angle - if (fovy.valueDegrees() > 175) - fovy = Degree(175); - texCam->setFOVy(fovy); - - // keep position & orientation set by ShadowRenderer::prepareShadowTextures - } - // Point light - else - { - // Set perspective projection - texCam->setProjectionType(PT_PERSPECTIVE); - // Use 120 degree FOV for point light to ensure coverage more area - texCam->setFOVy(Degree(120)); - - // Calculate look at position - // We want to look at a spot shadowOffset away from near plane - // 0.5 is a little too close for angles - Vector3 target = cam->getDerivedPosition() + - (cam->getDerivedDirection() * shadowOffset); - - // Calculate position, which same as point light position - pos = light->getDerivedPosition(); - - dir = (pos - target); // backwards since point down -z - dir.normalise(); - - Vector3 up = Vector3::UNIT_Y; - // Check it's not coincident with dir - if (Math::Abs(up.dotProduct(dir)) >= 1.0f) - { - // Use camera up - up = Vector3::UNIT_Z; - } - texCam->getParentNode()->setOrientation(Math::lookRotation(dir, up)); - // keep position set by ShadowRenderer::prepareShadowTextures - } - } - - -} diff --git a/OgreMain/src/OgreShadowCameraSetupFocused.cpp b/OgreMain/src/OgreShadowCameraSetupFocused.cpp deleted file mode 100644 index 9a76f029188..00000000000 --- a/OgreMain/src/OgreShadowCameraSetupFocused.cpp +++ /dev/null @@ -1,510 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Copyright (c) 2006 Matthias Fink, netAllied GmbH - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" -#include "OgreShadowCameraSetupFocused.h" - -namespace Ogre -{ - /** transform from normal to light space */ - const Matrix4 FocusedShadowCameraSetup::msNormalToLightSpace( - 1, 0, 0, 0, // x - 0, 0, -1, 0, // y - 0, 1, 0, 0, // z - 0, 0, 0, 1); // w - /** transform from light to normal space */ - const Matrix4 FocusedShadowCameraSetup::msLightSpaceToNormal( - 1, 0, 0, 0, // x - 0, 0, 1, 0, // y - 0, -1, 0, 0, // z - 0, 0, 0, 1); // w - - FocusedShadowCameraSetup::FocusedShadowCameraSetup(bool useAggressiveRegion) - : mUseAggressiveRegion(useAggressiveRegion) - , mLightFrustumCamera(NULL) - , mLightFrustumCameraCalculated(true) - { - } - - FocusedShadowCameraSetup::~FocusedShadowCameraSetup() {} - //----------------------------------------------------------------------- - void FocusedShadowCameraSetup::calculateB(const SceneManager& sm, const Camera& cam, - const Light& light, const AxisAlignedBox& sceneBB, const AxisAlignedBox& receiverBB, - PointListBody *out_bodyB) const - { - OgreAssert(out_bodyB != NULL, "bodyB vertex list is NULL"); - - /// perform convex intersection of the form B = ((V \cap S) + l) \cap S \cap L - - // get V - mBodyB.define(cam); - - if (light.getType() != Light::LT_DIRECTIONAL) - { - // clip bodyB with sceneBB - /* Note, Matthias' original code states this: - "The procedure ((V \cap S) + l) \cap S \cap L (Wimmer et al.) leads in some - cases to disappearing shadows. Valid parts of the scene are clipped, so shadows - are partly incomplete. The cause may be the transformation into light space that - is only done for the corner points which may not contain the whole scene afterwards - any more. So we fall back to the method of Stamminger et al. (V + l) \cap S \cap L - which does not show these anomalies." - - .. leading to the commenting out of the below clip. However, ift makes a major - difference to the quality of the focus, and so far I haven't noticed - the clipping issues described. Intuitively I would have thought that - any clipping issue would be due to the findCastersForLight not being - quite right, since if the sceneBB includes those there is no reason for - this clip instruction to omit a genuine shadow caster. - - I have made this a user option since the quality effect is major and - the clipping problem only seems to occur in some specific cases. - */ - if (mUseAggressiveRegion) - mBodyB.clip(sceneBB); - - // form a convex hull of bodyB with the light position - mBodyB.extend(light.getDerivedPosition()); - - // clip bodyB with sceneBB - mBodyB.clip(sceneBB); - - // clip with the light frustum - mBodyB.clip(*mLightFrustumCamera); - - // extract bodyB vertices - out_bodyB->build(mBodyB); - - } - else - { - // For directional lights, all we care about is projecting the receivers - // backwards towards the light, clipped by the camera region - mBodyB.clip(receiverBB.intersection(sceneBB)); - - // Also clip based on shadow far distance if appropriate - Real farDist = light.getShadowFarDistance(); - if (farDist) - { - Vector3 pointOnPlane = cam.getDerivedPosition() + - (cam.getDerivedDirection() * farDist); - Plane p(cam.getDerivedDirection(), pointOnPlane); - mBodyB.clip(p); - } - - if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_DEPTH_CLAMP)) - { - out_bodyB->build(mBodyB); - return; - } - - // Extrude the intersection bodyB into the inverted light direction and store - // the info in the point list. - // Maximum extrusion extent is to the shadow far distance - out_bodyB->buildAndIncludeDirection(mBodyB, - farDist ? farDist : cam.getNearClipDistance() * 3000, - -light.getDerivedDirection()); - } - } - - //----------------------------------------------------------------------- - void FocusedShadowCameraSetup::calculateLVS(const SceneManager& sm, const Camera& cam, - const Light& light, const AxisAlignedBox& sceneBB, PointListBody *out_LVS) const - { - ConvexBody bodyLVS; - - // init body with view frustum - bodyLVS.define(cam); - - // clip the body with the light frustum (point + spot) - // for a directional light the space of the intersected - // view frustum and sceneBB is always lighted and in front - // of the viewer. - if (light.getType() != Light::LT_DIRECTIONAL) - { - // clip with the light frustum - bodyLVS.clip(*mLightFrustumCamera); - } - - // clip the body with the scene bounding box - bodyLVS.clip(sceneBB); - - // extract bodyLVS vertices - out_LVS->build(bodyLVS); - } - //----------------------------------------------------------------------- - Vector3 FocusedShadowCameraSetup::getLSProjViewDir(const Matrix4& lightSpace, - const Camera& cam, const PointListBody& bodyLVS) const - { - // goal is to construct a view direction - // because parallel lines are not parallel any more after perspective projection we have to transform - // a ray to point us the viewing direction - - // fetch a point near the camera - const Vector3 e_world = getNearCameraPoint_ws(cam.getViewMatrix(), bodyLVS); - - // plus the direction results in a second point - const Vector3 b_world = e_world + cam.getDerivedDirection(); - - // transformation into light space - const Vector3 e_ls = lightSpace * e_world; - const Vector3 b_ls = lightSpace * b_world; - - // calculate the projection direction, which is the subtraction of - // b_ls from e_ls. The y component is set to 0 to project the view - // direction into the shadow map plane. - Vector3 projectionDir(b_ls - e_ls); - projectionDir.y = 0; - - // deal with Y-only vectors - return Math::RealEqual(projectionDir.length(), 0.0) ? - Vector3::NEGATIVE_UNIT_Z : projectionDir.normalisedCopy(); - } - //----------------------------------------------------------------------- - Vector3 FocusedShadowCameraSetup::getNearCameraPoint_ws(const Affine3& viewMatrix, - const PointListBody& bodyLVS) const - { - if (bodyLVS.getPointCount() == 0) - return Vector3(0,0,0); - - Vector3 nearEye = viewMatrix * bodyLVS.getPoint(0), // for comparison - nearWorld = bodyLVS.getPoint(0); // represents the final point - - // store the vertex with the highest z-value which is the nearest point - for (size_t i = 1; i < bodyLVS.getPointCount(); ++i) - { - const Vector3& vWorld = bodyLVS.getPoint(i); - - // comparison is done from the viewer - Vector3 vEye = viewMatrix * vWorld; - - if (vEye.z > nearEye.z) - { - nearEye = vEye; - nearWorld = vWorld; - } - } - - return nearWorld; - } - //----------------------------------------------------------------------- - Matrix4 FocusedShadowCameraSetup::transformToUnitCube(const Matrix4& m, - const PointListBody& body) const - { - // map the transformed body AAB points to the unit cube (-1/-1/-1) / (+1/+1/+1) corners - AxisAlignedBox aab_trans; - - for (size_t i = 0; i < body.getPointCount(); ++i) - { - aab_trans.merge(m * body.getPoint(i)); - } - - Vector3 vMin, vMax; - - vMin = aab_trans.getMinimum(); - vMax = aab_trans.getMaximum(); - - const Vector3 trans(-(vMax.x + vMin.x) / (vMax.x - vMin.x), - -(vMax.y + vMin.y) / (vMax.y - vMin.y), - -(vMax.z + vMin.z) / (vMax.z - vMin.z)); - - const Vector3 scale(2 / (vMax.x - vMin.x), - 2 / (vMax.y - vMin.y), - 2 / (vMax.z - vMin.z)); - - Matrix4 mOut(Matrix4::IDENTITY); - mOut.setTrans(trans); - mOut.setScale(scale); - - return mOut; - } - //----------------------------------------------------------------------- - void FocusedShadowCameraSetup::getShadowCamera (const SceneManager *sm, const Camera *cam, - const Viewport *vp, const Light *light, Camera *texCam, size_t iteration) const - { - // check availability - viewport not needed - OgreAssert(sm != NULL, "SceneManager is NULL"); - OgreAssert(cam != NULL, "Camera (viewer) is NULL"); - OgreAssert(light != NULL, "Light is NULL"); - OgreAssert(texCam != NULL, "Camera (texture) is NULL"); - - texCam->setNearClipDistance(light->_deriveShadowNearClipDistance(cam)); - texCam->setFarClipDistance(light->_deriveShadowFarClipDistance()); - - // calculate standard shadow mapping matrix - DefaultShadowCameraSetup::getShadowCamera(sm, cam, vp, light, texCam, iteration); - mLightFrustumCamera = texCam; - - // build scene bounding box - const VisibleObjectsBoundsInfo& visInfo = sm->getVisibleObjectsBoundsInfo(texCam); - AxisAlignedBox sceneBB = visInfo.aabb; - AxisAlignedBox receiverAABB = sm->getVisibleObjectsBoundsInfo(cam).receiverAabb; - sceneBB.merge(cam->getDerivedPosition()); - - // in case the sceneBB is empty (e.g. nothing visible to the cam) simply - // return the standard shadow mapping matrix - if (sceneBB.isNull()) - { - return; - } - - // calculate the intersection body B - mPointListBodyB.reset(); - calculateB(*sm, *cam, *light, sceneBB, receiverAABB, &mPointListBodyB); - - // in case the bodyB is empty (e.g. nothing visible to the light or the cam) - // simply return the standard shadow mapping matrix - if (mPointListBodyB.getPointCount() == 0) - { - return; - } - - auto LView = texCam->getViewMatrix(); - auto LProj = texCam->getProjectionMatrix(); - // transform to light space: y -> -z, z -> y - LProj = msNormalToLightSpace * LProj; - - // calculate LVS so it does not need to be calculated twice - // calculate the body L \cap V \cap S to make sure all returned points are in - // front of the camera - mPointListBodyLVS.reset(); - calculateLVS(*sm, *cam, *light, sceneBB, &mPointListBodyLVS); - - // fetch the viewing direction - const Vector3 viewDir = getLSProjViewDir(LProj * LView, *cam, mPointListBodyLVS); - - // The light space will be rotated in such a way, that the projected light view - // always points upwards, so the up-vector is the y-axis (we already prepared the - // light space for this usage).The transformation matrix is set up with the - // following parameters: - // - position is the origin - // - the view direction is the calculated viewDir - // - the up vector is the y-axis - LProj = Matrix4(Math::lookRotation(-viewDir, Vector3::UNIT_Y).transpose()) * LProj; - - // map bodyB to unit cube - LProj = transformToUnitCube(LProj * LView, mPointListBodyB) * LProj; - - // transform from light space to normal space: y -> z, z -> -y - LProj = msLightSpaceToNormal * LProj; - - // set the two custom matrices - texCam->setCustomViewMatrix(true, LView); - texCam->setCustomProjectionMatrix(true, LProj); - } - - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //----------------------------------------------------------------------- - FocusedShadowCameraSetup::PointListBody::PointListBody() - { - // Preallocate some space - mBodyPoints.reserve(12); - } - //----------------------------------------------------------------------- - FocusedShadowCameraSetup::PointListBody::PointListBody(const ConvexBody& body) - { - build(body); - } - //----------------------------------------------------------------------- - FocusedShadowCameraSetup::PointListBody::~PointListBody() - { - } - //----------------------------------------------------------------------- - void FocusedShadowCameraSetup::PointListBody::merge(const PointListBody& plb) - { - size_t size = plb.getPointCount(); - for (size_t i = 0; i < size; ++i) - { - this->addPoint(plb.getPoint(i)); - } - } - //----------------------------------------------------------------------- - void FocusedShadowCameraSetup::PointListBody::build(const ConvexBody& body, bool filterDuplicates) - { - // erase list - mBodyPoints.clear(); - - // Try to reserve a representative amount of memory - mBodyPoints.reserve(body.getPolygonCount() * 6); - - // build new list - for (size_t i = 0; i < body.getPolygonCount(); ++i) - { - for (size_t j = 0; j < body.getVertexCount(i); ++j) - { - const Vector3 &vInsert = body.getVertex(i, j); - - // duplicates allowed? - if (filterDuplicates) - { - bool bPresent = false; - - for(auto & v : mBodyPoints) - { - if (vInsert.positionEquals(v)) - { - bPresent = true; - break; - } - } - - if (bPresent == false) - { - mBodyPoints.push_back(body.getVertex(i, j)); - } - } - - // else insert directly - else - { - mBodyPoints.push_back(body.getVertex(i, j)); - } - } - } - - // update AAB - // no points altered, so take body AAB - mAAB = body.getAABB(); - } - //----------------------------------------------------------------------- - void FocusedShadowCameraSetup::PointListBody::buildAndIncludeDirection( - const ConvexBody& body, Real extrudeDist, const Vector3& dir) - { - // reset point list - this->reset(); - - // intersect the rays formed by the points in the list with the given direction and - // insert them into the list - - const size_t polyCount = body.getPolygonCount(); - for (size_t iPoly = 0; iPoly < polyCount; ++iPoly) - { - - // store the old inserted point and plane info - // if the currently processed point hits a different plane than the previous point an - // intersection point is calculated that lies on the two planes' intersection edge - - // fetch current polygon - const Polygon& p = body.getPolygon(iPoly); - - size_t pointCount = p.getVertexCount(); - for (size_t iPoint = 0; iPoint < pointCount ; ++iPoint) - { - // base point - const Vector3& pt = p.getVertex(iPoint); - - // add the base point - this->addPoint(pt); - - // intersection ray - Ray ray(pt, dir); - - const Vector3 ptIntersect = ray.getPoint(extrudeDist); - this->addPoint(ptIntersect); - - } // for: polygon point iteration - - } // for: polygon iteration - } - //----------------------------------------------------------------------- - const AxisAlignedBox& FocusedShadowCameraSetup::PointListBody::getAAB(void) const - { - return mAAB; - } - //----------------------------------------------------------------------- - void FocusedShadowCameraSetup::PointListBody::addPoint(const Vector3& point) - { - // don't check for doubles, simply add - mBodyPoints.push_back(point); - - // update AAB - mAAB.merge(point); - } - //----------------------------------------------------------------------- - void FocusedShadowCameraSetup::PointListBody::addAAB(const AxisAlignedBox& aab) - { - const Vector3& min = aab.getMinimum(); - const Vector3& max = aab.getMaximum(); - - Vector3 currentVertex = min; - // min min min - addPoint(currentVertex); - - // min min max - currentVertex.z = max.z; - addPoint(currentVertex); - - // min max max - currentVertex.y = max.y; - addPoint(currentVertex); - - // min max min - currentVertex.z = min.z; - addPoint(currentVertex); - - // max max min - currentVertex.x = max.x; - addPoint(currentVertex); - - // max max max - currentVertex.z = max.z; - addPoint(currentVertex); - - // max min max - currentVertex.y = min.y; - addPoint(currentVertex); - - // max min min - currentVertex.z = min.z; - addPoint(currentVertex); - - } - //----------------------------------------------------------------------- - const Vector3& FocusedShadowCameraSetup::PointListBody::getPoint(size_t cnt) const - { - OgreAssertDbg(cnt < getPointCount(), "Search position out of range"); - - return mBodyPoints[ cnt ]; - } - //----------------------------------------------------------------------- - size_t FocusedShadowCameraSetup::PointListBody::getPointCount(void) const - { - return mBodyPoints.size(); - } - //----------------------------------------------------------------------- - void FocusedShadowCameraSetup::PointListBody::reset(void) - { - mBodyPoints.clear(); - mAAB.setNull(); - } - -} - - diff --git a/OgreMain/src/OgreShadowCameraSetupLiSPSM.cpp b/OgreMain/src/OgreShadowCameraSetupLiSPSM.cpp deleted file mode 100644 index 46123b45723..00000000000 --- a/OgreMain/src/OgreShadowCameraSetupLiSPSM.cpp +++ /dev/null @@ -1,298 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Copyright (c) 2006 Matthias Fink, netAllied GmbH - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" -#include "OgreShadowCameraSetupLiSPSM.h" - -namespace Ogre -{ - - - LiSPSMShadowCameraSetup::LiSPSMShadowCameraSetup(Real n, bool useSimpleNOpt, Degree angle) - : mOptAdjustFactor(n) - , mUseSimpleNOpt(useSimpleNOpt) - , mOptAdjustFactorTweak(1.0) - { - setCameraLightDirectionThreshold(angle); - } - //----------------------------------------------------------------------- - LiSPSMShadowCameraSetup::~LiSPSMShadowCameraSetup(void) - { - } - //----------------------------------------------------------------------- - Matrix4 LiSPSMShadowCameraSetup::calculateLiSPSM(const Matrix4& lightSpace, - const PointListBody& bodyB, const PointListBody& bodyLVS, - const SceneManager& sm, const Camera& cam, const Light& light) const - { - // set up bodyB AAB in light space - AxisAlignedBox bodyBAAB_ls; - for (size_t i = 0; i < bodyB.getPointCount(); ++i) - { - bodyBAAB_ls.merge(lightSpace * bodyB.getPoint(i)); - } - - // near camera point in light space - const Vector3 e_ls = lightSpace * getNearCameraPoint_ws(cam.getViewMatrix(), bodyLVS); - - // C_start has x and y of e and z from the bodyABB_ls (we look down the negative z axis, so take the maximum z value) - const Vector3 C_start_ls(e_ls.x, e_ls.y, bodyBAAB_ls.getMaximum().z); - - // calculate the optimal distance between origin and near plane - Real n_opt; - - if (mUseSimpleNOpt) - n_opt = calculateNOptSimple(bodyLVS, cam); - else - n_opt = calculateNOpt(lightSpace, bodyBAAB_ls, bodyLVS, cam); - - // in case n_opt is null, uniform shadow mapping will be done - if (n_opt <= 0.0) - { - return Matrix4::IDENTITY; - } - - // calculate the projection center C which is n units behind the near plane of P - // we look into the negative z direction so add n - const Vector3 C(C_start_ls + n_opt * Vector3::UNIT_Z); - - // set up a transformation matrix to transform the light space to its new origin - Matrix4 lightSpaceTranslation(Matrix4::IDENTITY); - lightSpaceTranslation.setTrans(-C); - - // range from bMin to bMax; d = |B_z_far - B_z_near| - Real d = Math::Abs(bodyBAAB_ls.getMaximum().z - bodyBAAB_ls.getMinimum().z); - - // set up the LiSPSM perspective transformation - // build up frustum to map P onto the unit cube with (-1/-1/-1) and (+1/+1/+1) - Matrix4 P = Math::makePerspectiveMatrix(-1, 1, -1, 1, n_opt + d, n_opt); - - return P * lightSpaceTranslation; - } - //----------------------------------------------------------------------- - Real LiSPSMShadowCameraSetup::calculateNOpt(const Matrix4& lightSpace, - const AxisAlignedBox& bodyBABB_ls, const PointListBody& bodyLVS, - const Camera& cam) const - { - // get inverse light space matrix - Matrix4 invLightSpace = lightSpace.inverse(); - - // get view matrix - const Affine3& viewMatrix = cam.getViewMatrix(); - - // calculate z0_ls - const Vector3 e_ws = getNearCameraPoint_ws(viewMatrix, bodyLVS); - const Vector3 z0_ls = calculateZ0_ls(lightSpace, e_ws, bodyBABB_ls.getMaximum().z, cam); - - // z1_ls has the same x and y values as z0_ls and the minimum z values of bodyABB_ls - const Vector3 z1_ls = Vector3(z0_ls.x, z0_ls.y, bodyBABB_ls.getMinimum().z); - - // world - const Vector3 z0_ws = invLightSpace * z0_ls; - const Vector3 z1_ws = invLightSpace * z1_ls; - - // eye - const Vector3 z0_es = viewMatrix * z0_ws; - const Vector3 z1_es = viewMatrix * z1_ws; - - const Real z0 = z0_es.z; - const Real z1 = z1_es.z; - - // check if we have to do uniform shadow mapping - if ((z0 < 0 && z1 > 0) || - (z1 < 0 && z0 > 0)) - { - // apply uniform shadow mapping - return 0.0; - } - return cam.getNearClipDistance() + Math::Sqrt(z0 * z1) * getOptimalAdjustFactor() * mOptAdjustFactorTweak; - } - //----------------------------------------------------------------------- - Real LiSPSMShadowCameraSetup::calculateNOptSimple(const PointListBody& bodyLVS, - const Camera& cam) const - { - // get view matrix - const Affine3& viewMatrix = cam.getViewMatrix(); - - // calculate e_es - const Vector3 e_ws = getNearCameraPoint_ws(viewMatrix, bodyLVS); - const Vector3 e_es = viewMatrix * e_ws; - - // according to the new formula (mainly for directional lights) - // n_opt = zn + sqrt(z0 * z1); - // zn is set to Abs(near eye point) - // z0 is set to the near camera clip distance - // z1 is set to the far camera clip distance - return (Math::Abs(e_es.z) + Math::Sqrt(cam.getNearClipDistance() * cam.getFarClipDistance())) * getOptimalAdjustFactor() * mOptAdjustFactorTweak; - } - //----------------------------------------------------------------------- - Vector3 LiSPSMShadowCameraSetup::calculateZ0_ls(const Matrix4& lightSpace, - const Vector3& e, Real bodyB_zMax_ls, const Camera& cam) const - { - // z0_ls lies on the intersection point between the planes 'bodyB_ls near plane - // (z = bodyB_zNear_ls)' and plane with normal UNIT_X where e_ls lies upon (x = e_ls_x) - // and the camera's near clipping plane (ls). We are looking towards the negative - // z-direction, so bodyB_zNear_ls equals bodyB_zMax_ls. - - const Vector3& camDir = cam.getDerivedDirection(); - const Vector3 e_ls = lightSpace * e; - - // set up a plane with the camera direction as normal and e as a point on the plane - Plane plane(camDir, e); - - plane = lightSpace * plane; - - // try to intersect plane with a ray from origin V3(e_ls_x, 0.0, bodyB_zNear_ls)T - // and direction +/- UNIT_Y - Ray ray(Vector3(e_ls.x, 0.0, bodyB_zMax_ls), Vector3::UNIT_Y); - std::pair< bool, Real > intersect = ray.intersects(plane); - - // we got an intersection point - if (intersect.first == true) - { - return ray.getPoint(intersect.second); - } - else - { - // try the other direction - ray = Ray(Vector3(e_ls.x, 0.0, bodyB_zMax_ls), Vector3::NEGATIVE_UNIT_Y); - intersect = ray.intersects(plane); - - // we got an intersection point - if (intersect.first == true) - { - return ray.getPoint(intersect.second); - } - else - { - // failure! - return Vector3(0.0, 0.0, 0.0); - } - } - } - //----------------------------------------------------------------------- - void LiSPSMShadowCameraSetup::getShadowCamera (const SceneManager *sm, const Camera *cam, - const Viewport *vp, const Light *light, Camera *texCam, size_t iteration) const - { - // check availability - viewport not needed - OgreAssert(sm != NULL, "SceneManager is NULL"); - OgreAssert(cam != NULL, "Camera (viewer) is NULL"); - OgreAssert(light != NULL, "Light is NULL"); - OgreAssert(texCam != NULL, "Camera (texture) is NULL"); - - // calculate standard shadow mapping matrix - DefaultShadowCameraSetup::getShadowCamera(sm, cam, vp, light, texCam, iteration); - mLightFrustumCamera = texCam; - - // if the direction of the light and the direction of the camera tend to be parallel, - // then tweak up the adjust factor - Real dot = Math::Abs(cam->getDerivedDirection().dotProduct(light->getDerivedDirection())); - if (dot >= mCosCamLightDirThreshold) - { - mOptAdjustFactorTweak = 1.0f + (20.0f * ((dot - mCosCamLightDirThreshold) / (1.0f - mCosCamLightDirThreshold)) ); - } - else - { - mOptAdjustFactorTweak = 1.0f; - } - - // build scene bounding box - const VisibleObjectsBoundsInfo& visInfo = sm->getVisibleObjectsBoundsInfo(texCam); - AxisAlignedBox sceneBB = visInfo.aabb; - AxisAlignedBox receiverAABB = sm->getVisibleObjectsBoundsInfo(cam).receiverAabb; - sceneBB.merge(cam->getDerivedPosition()); - - // in case the sceneBB is empty (e.g. nothing visible to the cam) simply - // return the standard shadow mapping matrix - if (sceneBB.isNull()) - { - return; - } - - // calculate the intersection body B - mPointListBodyB.reset(); - calculateB(*sm, *cam, *light, sceneBB, receiverAABB, &mPointListBodyB); - - // in case the bodyB is empty (e.g. nothing visible to the light or the cam) - // simply return the standard shadow mapping matrix - if (mPointListBodyB.getPointCount() == 0) - { - return; - } - - auto LView = texCam->getViewMatrix(); - auto LProj = texCam->getProjectionMatrix(); - - // transform to light space: y -> -z, z -> y - LProj = msNormalToLightSpace * LProj; - - // calculate LVS so it does not need to be calculated twice - // calculate the body L \cap V \cap S to make sure all returned points are in - // front of the camera - calculateLVS(*sm, *cam, *light, sceneBB, &mPointListBodyLVS); - - // fetch the viewing direction - const Vector3 viewDir = getLSProjViewDir(LProj * LView, *cam, mPointListBodyLVS); - - // The light space will be rotated in such a way, that the projected light view - // always points upwards, so the up-vector is the y-axis (we already prepared the - // light space for this usage).The transformation matrix is set up with the - // following parameters: - // - position is the origin - // - the view direction is the calculated viewDir - // - the up vector is the y-axis - LProj = Matrix4(Math::lookRotation(-viewDir, Vector3::UNIT_Y).transpose()) * LProj; - - // calculate LiSPSM projection - LProj = calculateLiSPSM(LProj * LView, mPointListBodyB, mPointListBodyLVS, *sm, *cam, *light) * LProj; - - // map bodyB to unit cube - LProj = transformToUnitCube(LProj * LView, mPointListBodyB) * LProj; - - // transform from light space to normal space: y -> z, z -> -y - LProj = msLightSpaceToNormal * LProj; - - // LView = Lv^-1 - // LProj = Switch_{-ls} * FocusBody * P * L_r * Switch_{ls} * L_p - texCam->setCustomViewMatrix(true, LView); - texCam->setCustomProjectionMatrix(true, LProj); - } - //--------------------------------------------------------------------- - void LiSPSMShadowCameraSetup::setCameraLightDirectionThreshold(Degree angle) - { - mCosCamLightDirThreshold = Math::Cos(angle.valueRadians()); - } - //--------------------------------------------------------------------- - Degree LiSPSMShadowCameraSetup::getCameraLightDirectionThreshold() const - { - return Degree(Math::ACos(mCosCamLightDirThreshold)); - } - - -} - diff --git a/OgreMain/src/OgreShadowCameraSetupPSSM.cpp b/OgreMain/src/OgreShadowCameraSetupPSSM.cpp deleted file mode 100644 index 560ac60b0ea..00000000000 --- a/OgreMain/src/OgreShadowCameraSetupPSSM.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Copyright (c) 2006 Matthias Fink, netAllied GmbH - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" -#include "OgreShadowCameraSetupPSSM.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - PSSMShadowCameraSetup::PSSMShadowCameraSetup() - : mSplitPadding(1.0f), mCurrentIteration(0) - { - calculateSplitPoints(3, 100, 100000); - setOptimalAdjustFactor(0, 5); - setOptimalAdjustFactor(1, 1); - setOptimalAdjustFactor(2, 0); - - - } - //--------------------------------------------------------------------- - PSSMShadowCameraSetup::~PSSMShadowCameraSetup() - { - } - //--------------------------------------------------------------------- - void PSSMShadowCameraSetup::calculateSplitPoints(uint splitCount, Real nearDist, Real farDist, Real lambda) - { - if (splitCount < 2) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot specify less than 2 splits", - "PSSMShadowCameraSetup::calculateSplitPoints"); - - mSplitPoints.resize(splitCount + 1); - mOptimalAdjustFactors.resize(splitCount); - mSplitCount = splitCount; - - mSplitPoints[0] = nearDist; - for (size_t i = 1; i < mSplitCount; i++) - { - Real fraction = (Real)i / (Real)mSplitCount; - Real splitPoint = lambda * nearDist * Math::Pow(farDist / nearDist, fraction) + - (1.0f - lambda) * (nearDist + fraction * (farDist - nearDist)); - - mSplitPoints[i] = splitPoint; - } - mSplitPoints[splitCount] = farDist; - - } - //--------------------------------------------------------------------- - void PSSMShadowCameraSetup::setSplitPoints(const SplitPointList& newSplitPoints) - { - if (newSplitPoints.size() < 3) // 3, not 2 since splits + 1 points - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot specify less than 2 splits", - "PSSMShadowCameraSetup::setSplitPoints"); - mSplitCount = static_cast(newSplitPoints.size() - 1); - mSplitPoints = newSplitPoints; - mOptimalAdjustFactors.resize(mSplitCount); - } - //--------------------------------------------------------------------- - void PSSMShadowCameraSetup::setOptimalAdjustFactor(size_t splitIndex, Real factor) - { - if (splitIndex >= mOptimalAdjustFactors.size()) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Split index out of range", - "PSSMShadowCameraSetup::setOptimalAdjustFactor"); - mOptimalAdjustFactors[splitIndex] = factor; - - } - //--------------------------------------------------------------------- - Real PSSMShadowCameraSetup::getOptimalAdjustFactor() const - { - // simplifies the overriding of the LiSPSM opt adjust factor use - return mOptimalAdjustFactors[mCurrentIteration]; - } - //--------------------------------------------------------------------- - void PSSMShadowCameraSetup::getShadowCamera(const Ogre::SceneManager *sm, const Ogre::Camera *cam, - const Ogre::Viewport *vp, const Ogre::Light *light, Ogre::Camera *texCam, size_t iteration) const - { - // apply the right clip distance. - Real nearDist = mSplitPoints[iteration]; - Real farDist = mSplitPoints[iteration + 1]; - - // Add a padding factor to internal distances so that the connecting split point will not have bad artifacts. - if (iteration > 0) - { - nearDist -= mSplitPadding; - } - if (iteration < mSplitCount - 1) - { - farDist += mSplitPadding; - } - - mCurrentIteration = iteration; - - // Ouch, I know this is hacky, but it's the easiest way to re-use LiSPSM / Focused - // functionality right now without major changes - Camera* _cam = const_cast(cam); - Real oldNear = _cam->getNearClipDistance(); - Real oldFar = _cam->getFarClipDistance(); - Frustum* oldCull = _cam->getCullingFrustum(); - _cam->setNearClipDistance(nearDist); - _cam->setFarClipDistance(farDist); - _cam->setCullingFrustum(NULL); - - LiSPSMShadowCameraSetup::getShadowCamera(sm, cam, vp, light, texCam, iteration); - - // restore near/far - _cam->setNearClipDistance(oldNear); - _cam->setFarClipDistance(oldFar); - _cam->setCullingFrustum(oldCull); - - } -} diff --git a/OgreMain/src/OgreShadowCameraSetupPlaneOptimal.cpp b/OgreMain/src/OgreShadowCameraSetupPlaneOptimal.cpp deleted file mode 100644 index 197671999c1..00000000000 --- a/OgreMain/src/OgreShadowCameraSetupPlaneOptimal.cpp +++ /dev/null @@ -1,416 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" -#include "OgreShadowCameraSetupPlaneOptimal.h" -#include "OgreNumerics.h" -#include "OgreMovablePlane.h" - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -// we do a lot of PreciseReal -> Real in here, casting is messy -// disable: "conversion from 'double' to 'float', possible loss of data -# pragma warning (disable : 4244) -# pragma warning (disable : 4305) -#endif - - -namespace Ogre -{ - // -------------------------------------------------------------------- - Matrix4 PlaneOptimalShadowCameraSetup::computeConstrainedProjection( - const Vector4& pinhole, - const std::vector& fpoint, - const std::vector& constraint) const - { - // NOTE: will assume the z coordinates should be decided such that - // the first 3 points (in fpoint) will have post projective - // z coordinates of about +1 and the 4th (in fpoint) will have a - // post projective z coordinate of about -1. - - // TODO: could use SVD to avoid arbitrarily choosing one - // matrix element to be 1.0 (and thereby fix the scale). - - Matrix4 ret; - int i; - bool incrPrecision = false; // use to control numerical solving - - if(fpoint.size() < 4 || constraint.size() < 4) { - return Matrix4::IDENTITY; - } - - // allocate memory - double **mat = NULL; - double **backmat = NULL; - { - mat = OGRE_ALLOC_T(double*, 11, MEMCATEGORY_SCENE_CONTROL); - if(incrPrecision) - backmat = OGRE_ALLOC_T(double*, 11, MEMCATEGORY_SCENE_CONTROL); - for(i=0; i<11; i++) - { - mat[i] = OGRE_ALLOC_T(double, 11, MEMCATEGORY_SCENE_CONTROL); - if(incrPrecision) - backmat[i] = OGRE_ALLOC_T(double, 11, MEMCATEGORY_SCENE_CONTROL); - } - } - - // set up linear system to solve for all rows of projective matrix - // except for the 3rd which corresponds to mapping of z values - - // we choose a nonzero element of the last row to set to the arbitrary - // constant 1.0. - int nzind = 3; - double col[11]; - double backcol[11]; - - // fill in light position constraints - mat[0][0] = pinhole.x; - mat[0][1] = pinhole.y; - mat[0][2] = pinhole.z; - mat[0][3] = pinhole.w; - for(i=4; i<11; i++) - mat[0][i] = 0.0; - col[0] = 0.0; - - for(i=0; i<11; i++) - mat[1][i] = 0.0; - mat[1][4] = pinhole.x; - mat[1][5] = pinhole.y; - mat[1][6] = pinhole.z; - mat[1][7] = pinhole.w; - col[1] = 0.0; - - double larr[4]; - larr[0] = pinhole.x; - larr[1] = pinhole.y; - larr[2] = pinhole.z; - larr[3] = pinhole.w; - for(i=0; i<8; i++) - mat[2][i] = 0.0; - int ind = 8; - for(i=0; i<4; i++) - { - if(nzind == i) - continue; - mat[2][ind++] = larr[i]; - } - col[2] = -larr[nzind]; - - // fill in all the other constraints - int row=3; - for(i=0; i<4; i++) - { - int j; - larr[0] = fpoint[i].x; - larr[1] = fpoint[i].y; - larr[2] = fpoint[i].z; - larr[3] = fpoint[i].w; - - // lexel s coordinate constraint - for(j=0; j<4; j++) - mat[row][j] = larr[j]; - for(j=4; j<8; j++) - mat[row][j] = 0.0; - ind=8; - for(j=0; j<4; j++) - { - if(nzind==j) - continue; - mat[row][ind++] = larr[j] * (-constraint[i].x); - } - col[row] = larr[nzind] * constraint[i].x; - ++row; - - // lexel t coordinate constraint - for(j=0; j<4; j++) - mat[row][j] = 0.0; - for(j=4; j<8; j++) - mat[row][j] = larr[j-4]; - - ind=8; - for(j=0; j<4; j++) - { - if(nzind==j) - continue; - mat[row][ind++] = larr[j] * (-constraint[i].y); - } - col[row] = larr[nzind] * constraint[i].y; - ++row; - } - - // copy the matrix and vector for later computation - if(incrPrecision) - { - for (i=0; i<11; i++) - { - for(int j=0; j<11; j++) - backmat[i][j] = mat[i][j]; - backcol[i] = col[i]; - } - } - - // solve for the matrix elements - if(!NumericSolver::solveNxNLinearSysDestr(11, mat, col)) - { - // error solving for projective matrix (rows 1,2,4) - } - - // get a little more precision - if(incrPrecision) - { - for (int k=0; k<3; k++) - { - double nvec[11]; - for(i=0; i<11; i++) - { - int j; - nvec[i] = backmat[i][0] * col[0]; - mat[i][0] = backmat[i][0]; - for(j=1; j<11; j++) - { - nvec[i] += backmat[i][j] * col[j]; - mat[i][j] = backmat[i][j]; - } - nvec[i] -= backcol[i]; - } - if(!NumericSolver::solveNxNLinearSysDestr(11, mat, nvec)) - { - // error solving for increased precision rows 1,2,4 - } - for(i=0; i<11; i++) - col[i] -= nvec[i]; - } - } - - double row4[4]; - ind = 8; - for(i=0; i<4; i++) - { - if (i == nzind) - row4[i] = 1.0; - else - row4[i] = col[ind++]; - } - - - // now solve for the 3rd row which affects depth precision - double zrow[4]; - - // we want the affine skew such that isoplanes of constant depth are parallel to - // the world plane of interest - // NOTE: recall we perturbed the last fpoint off the plane, so we'll again modify - // this one since we want 3 points on the plane = far plane, and 1 on the near plane - int nearind = 3; - for(i=0; i<3; i++) - { - mat[i][0] = fpoint[i].x; - mat[i][1] = fpoint[i].y; - mat[i][2] = fpoint[i].z; - mat[i][3] = 1.0; - zrow[i] = (row4[0] * fpoint[i].x + - row4[1] * fpoint[i].y + - row4[2] * fpoint[i].z + - row4[3]) * 0.99 ; - } - mat[3][0] = fpoint[nearind].x; - mat[3][1] = fpoint[nearind].y; - mat[3][2] = fpoint[nearind].z; - mat[3][3] = 1.0; - zrow[3] = -row4[0] * fpoint[nearind].x - - row4[1] * fpoint[nearind].y - - row4[2] * fpoint[nearind].z - - row4[3] ; - - // solve for the z row of the matrix - if(!NumericSolver::solveNxNLinearSysDestr(4, mat, zrow)) - { - // error solving for projective matrix (row 3) - } - - // set projective texture matrix - ret = Matrix4( col[0], col[1], col[2], col[3], - col[4], col[5], col[6], col[7], - zrow[0], zrow[1], zrow[2], zrow[3], - row4[0], row4[1], row4[2], row4[3] ); - - - // check for clip - Vector4 testCoord = ret * fpoint[0]; - if(testCoord.w < 0.0) - ret = ret * (-1.0); - - // free memory - for (i=0; i<11; i++) - { - if (mat[i]) - OGRE_FREE(mat[i], MEMCATEGORY_SCENE_CONTROL); - if (incrPrecision) - OGRE_FREE(backmat[i], MEMCATEGORY_SCENE_CONTROL); - } - OGRE_FREE(mat, MEMCATEGORY_SCENE_CONTROL); - if(incrPrecision) - OGRE_FREE(backmat, MEMCATEGORY_SCENE_CONTROL); - - return ret; - - } - - // -------------------------------------------------------------------- - - /// Construct object to consider a specified plane of interest - PlaneOptimalShadowCameraSetup::PlaneOptimalShadowCameraSetup(const MovablePlane* plane) - { - mPlane = plane; - } - - /// Destructor - PlaneOptimalShadowCameraSetup::~PlaneOptimalShadowCameraSetup() {} - - /// Implements the plane optimal shadow camera setup algorithm - void PlaneOptimalShadowCameraSetup::getShadowCamera (const SceneManager *sm, const Camera *cam, - const Viewport *vp, const Light *light, Camera *texCam, size_t iteration) const - { - // get the plane transformed by the parent node(s) - // Also, make sure the plane is normalized - Plane worldPlane = mPlane->_getDerivedPlane(); - worldPlane.normalise(); - - // get camera's projection matrix - Matrix4 camProjection = cam->getProjectionMatrix() * cam->getViewMatrix(); - - // get the world points to constrain - std::vector vhull; - cam->forwardIntersect(worldPlane, &vhull); - if (vhull.size() < 4) - return; - - // make sure the last point is a finite point (not point at infinity) - if (vhull[3].w == 0.0) - { - int finiteIndex = -1; - for (uint loopIndex = 0; loopIndex < vhull.size(); loopIndex++) - { - if (vhull[loopIndex].w != 0.0) - { - finiteIndex = loopIndex; - break; - } - } - if (finiteIndex == -1) - { - // there are no finite points, which means camera doesn't see plane of interest. - // so we don't care what the shadow map matrix is - // We'll map points off the shadow map so they aren't even stored - Matrix4 crazyMat(0.0, 0.0, 0.0, 5.0, - 0.0, 0.0, 0.0, 5.0, - 0.0, 0.0, 0.0, 5.0, - 0.0, 0.0, 0.0, 1.0); - texCam->setCustomViewMatrix(true, Affine3::IDENTITY); - texCam->setCustomProjectionMatrix(true, crazyMat); - return; - } - // swap finite point to last point - std::swap(vhull[3], vhull[finiteIndex]); - } - vhull.resize(4); - - // get the post-projective coordinate constraints - std::vector constraint; - for (int i=0; i<4; i++) - { - Vector4 postProjPt = camProjection * vhull[i]; - postProjPt *= 1.0 / postProjPt.w; - constraint.push_back(Vector2(postProjPt.x, postProjPt.y)); - } - - // perturb one point so we don't have coplanarity - const Vector4& pinhole = light->getAs4DVector(); - const Vector4& oldPt = vhull.back(); - Vector4 newPt; - if (pinhole.w == 0) - { - // It's directional light - static const Real NEAR_SCALE = 100.0; - newPt = oldPt + (pinhole * (cam->getNearClipDistance() * NEAR_SCALE)); - } - else - { - // It's point or spotlight - Vector4 displacement = oldPt - pinhole; - Vector3 displace3 = Vector3(displacement.x, displacement.y, displacement.z); - Real dotProd = std::fabs(displace3.dotProduct(worldPlane.normal)); - static const Real NEAR_FACTOR = 0.05; - newPt = pinhole + (displacement * (cam->getNearClipDistance() * NEAR_FACTOR / dotProd)); - } - vhull.back() = newPt; - - // solve for the matrix that stabilizes the plane - Matrix4 customMatrix = computeConstrainedProjection(pinhole, vhull, constraint); - - if (pinhole.w == 0) - { - // TODO: factor into view and projection pieces. - // Note: In fact, it's unnecessary to factor into view and projection pieces, - // but if we do, we will more according with academic requirement :) - texCam->setCustomViewMatrix(true, Affine3::IDENTITY); - texCam->setCustomProjectionMatrix(true, customMatrix); - return; - } - - Vector3 tempPos = Vector3(pinhole.x, pinhole.y, pinhole.z); - - // factor into view and projection pieces - Affine3 translation(1.0, 0.0, 0.0, tempPos.x, - 0.0, 1.0, 0.0, tempPos.y, - 0.0, 0.0, 1.0, tempPos.z); - Affine3 invTranslation(1.0, 0.0, 0.0, -tempPos.x, - 0.0, 1.0, 0.0, -tempPos.y, - 0.0, 0.0, 1.0, -tempPos.z); - Matrix4 tempMatrix = customMatrix * translation; - Vector3 zRow(-tempMatrix[3][0], -tempMatrix[3][1], -tempMatrix[3][2]); - zRow.normalise(); - Vector3 up; - if (zRow.y == 1.0) - up = Vector3(1,0,0); - else - up = Vector3(0,1,0); - - Affine3 rotation = Affine3::IDENTITY; - rotation = Math::lookRotation(zRow, up); - Matrix4 customProj = tempMatrix * rotation; - Affine3 customView(rotation.transpose() * invTranslation); - // note: now customProj * (0,0,0,1)^t = (0, 0, k, 0)^t for k some constant - // note: also customProj's 4th row is (0, 0, c, 0) for some negative c. - - - // set the shadow map camera - texCam->setCustomViewMatrix(true, customView); - texCam->setCustomProjectionMatrix(true, customProj); - } - -} - diff --git a/OgreMain/src/OgreShadowCaster.cpp b/OgreMain/src/OgreShadowCaster.cpp deleted file mode 100644 index c03fdf3b1c1..00000000000 --- a/OgreMain/src/OgreShadowCaster.cpp +++ /dev/null @@ -1,596 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreEdgeListBuilder.h" -#include "OgreOptimisedUtil.h" - -namespace Ogre { - ShadowRenderable::ShadowRenderable(MovableObject* parent, const HardwareIndexBufferSharedPtr& indexBuffer, - const VertexData* vertexData, bool createSeparateLightCap, - bool isLightCap) - : mLightCap(0), mParent(parent) - { - // Initialise render op - mRenderOp.indexData = OGRE_NEW IndexData(); - mRenderOp.indexData->indexBuffer = indexBuffer; - mRenderOp.indexData->indexStart = 0; - // index start and count are sorted out later - - // Create vertex data which just references position component (and 2 component) - mRenderOp.vertexData = OGRE_NEW VertexData(); - // Map in position data - mRenderOp.vertexData->vertexDeclaration->addElement(0,0,VET_FLOAT3, VES_POSITION); - ushort origPosBind = - vertexData->vertexDeclaration->findElementBySemantic(VES_POSITION)->getSource(); - mPositionBuffer = vertexData->vertexBufferBinding->getBuffer(origPosBind); - mRenderOp.vertexData->vertexBufferBinding->setBinding(0, mPositionBuffer); - // Map in w-coord buffer (if present) - if(vertexData->hardwareShadowVolWBuffer) - { - mRenderOp.vertexData->vertexDeclaration->addElement(1,0,VET_FLOAT1, VES_TEXTURE_COORDINATES, 0); - mWBuffer = vertexData->hardwareShadowVolWBuffer; - mRenderOp.vertexData->vertexBufferBinding->setBinding(1, mWBuffer); - } - // Use same vertex start as input - mRenderOp.vertexData->vertexStart = vertexData->vertexStart; - - if (isLightCap) - { - // Use original vertex count, no extrusion - mRenderOp.vertexData->vertexCount = vertexData->vertexCount; - } - else - { - // Vertex count must take into account the doubling of the buffer, - // because second half of the buffer is the extruded copy - mRenderOp.vertexData->vertexCount = vertexData->vertexCount * 2; - - if (createSeparateLightCap) - { - // Create child light cap - mLightCap = OGRE_NEW ShadowRenderable(parent, indexBuffer, vertexData, false, true); - } - } - } - ShadowRenderable::~ShadowRenderable() - { - delete mLightCap; - delete mRenderOp.indexData; - delete mRenderOp.vertexData; - } - void ShadowRenderable::rebindIndexBuffer(const HardwareIndexBufferSharedPtr& indexBuffer) - { - mRenderOp.indexData->indexBuffer = indexBuffer; - if (mLightCap) mLightCap->rebindIndexBuffer(indexBuffer); - } - void ShadowRenderable::getWorldTransforms(Matrix4* xform) const - { - *xform = mParent->_getParentNodeFullTransform(); - } - const LightList& ShadowRenderable::getLights(void) const - { - // return empty - static LightList ll; - return ll; - } - // ------------------------------------------------------------------------ - void ShadowCaster::clearShadowRenderableList(ShadowRenderableList& shadowRenderables) - { - for(auto & shadowRenderable : shadowRenderables) - { - OGRE_DELETE shadowRenderable; - shadowRenderable = 0; - } - shadowRenderables.clear(); - } - // ------------------------------------------------------------------------ - void ShadowCaster::updateEdgeListLightFacing(EdgeData* edgeData, - const Vector4& lightPos) - { - edgeData->updateTriangleLightFacing(lightPos); - } - // ------------------------------------------------------------------------ - static bool isBoundOkForMcGuire(const AxisAlignedBox& lightCapBounds, const Ogre::Vector3& lightPosition) - { - // If light position is inside light cap bound then extrusion could be in opposite directions - // and McGuire cap could intersect near clip plane of camera frustum without being noticed - if(lightCapBounds.contains(lightPosition)) - return false; - - // If angular size of object is too high then extrusion could be in almost opposite directions, - // interpolated points would be extruded by shorter distance, and strange geometry of McGuire cap - // could be visible even for well tesselated meshes. As a heuristic we will avoid McGuire cap if - // angular size is larger than 60 degrees - it guarantees that interpolated points would be - // extruded by at least cos(60deg/2) ~ 86% of the original extrusion distance. - if(lightCapBounds.getHalfSize().length() / (lightCapBounds.getCenter() - lightPosition).length() > 0.5) // if boundingSphereAngularSize > 60deg - { - // Calculate angular size one more time using edge corners angular distance comparision, - // Determine lit sides of the bound, store in mask - enum { L = 1, R = 2, B = 4, T = 8, F = 16, N = 32 }; // left, right, bottom, top, far, near - unsigned lightSidesMask = - (lightPosition.x < lightCapBounds.getMinimum().x ? L : 0) | // left - (lightPosition.x > lightCapBounds.getMaximum().x ? R : 0) | // right - (lightPosition.y < lightCapBounds.getMinimum().y ? B : 0) | // bottom - (lightPosition.y > lightCapBounds.getMaximum().y ? T : 0) | // top - (lightPosition.z < lightCapBounds.getMinimum().z ? F : 0) | // far - (lightPosition.z > lightCapBounds.getMaximum().z ? N : 0); // near - - // find corners on lit/unlit edge (should not be more than 6 simultaneously, but better be safe than sorry) - Ogre::Vector3 edgeCorners[8]; - unsigned edgeCornersCount = 0; - std::pair cornerMap[8] = { - { F|L|B, AxisAlignedBox::FAR_LEFT_BOTTOM }, { F|R|B, AxisAlignedBox::FAR_RIGHT_BOTTOM }, - { F|L|T, AxisAlignedBox::FAR_LEFT_TOP }, { F|R|T, AxisAlignedBox::FAR_RIGHT_TOP }, - { N|L|B, AxisAlignedBox::NEAR_LEFT_BOTTOM },{ N|R|B, AxisAlignedBox::NEAR_RIGHT_BOTTOM }, - { N|L|T, AxisAlignedBox::NEAR_LEFT_TOP }, { N|R|T, AxisAlignedBox::NEAR_RIGHT_TOP }}; - for(auto& c : cornerMap) - if((lightSidesMask & c.first) != 0 && (lightSidesMask & c.first) != c.first) // if adjacent sides not all lit or all unlit - edgeCorners[edgeCornersCount++] = lightCapBounds.getCorner(c.second); - - // find max angular size in range [0..pi] by finding min cos of angular size, range [1..-1] - Real cosAngle = 1.0; - for(unsigned i0 = 0; i0 + 1 < edgeCornersCount; ++i0) - for(unsigned i1 = i0 + 1; i1 < edgeCornersCount; ++i1) - { - // 4~6 edge corners, 6~15 angular distance calculations - Vector3 a = (edgeCorners[i0] - lightPosition).normalisedCopy(); - Vector3 b = (edgeCorners[i1] - lightPosition).normalisedCopy(); - Real cosAB = a.dotProduct(b); - if(cosAngle > cosAB) - cosAngle = cosAB; - } - - if(cosAngle < 0.5) // angularSize > 60 degrees - return false; - } - - return true; - } - // ------------------------------------------------------------------------ - void ShadowCaster::generateShadowVolume(EdgeData* edgeData, - const HardwareIndexBufferSharedPtr& indexBuffer, size_t& indexBufferUsedSize, - const Light* light, ShadowRenderableList& shadowRenderables, unsigned long flags) - { - // Edge groups should be 1:1 with shadow renderables - assert(edgeData->edgeGroups.size() == shadowRenderables.size()); - - Light::LightTypes lightType = light->getType(); - - // Whether to use the McGuire method, a triangle fan covering all silhouette - // This won't work properly with multiple separate edge groups (should be one fan per group, not implemented) - // or when light position is too close to light cap bound. - bool useMcGuire = edgeData->edgeGroups.size() <= 1 && - (lightType == Light::LT_DIRECTIONAL || isBoundOkForMcGuire(getLightCapBounds(), light->getDerivedPosition())); - ShadowRenderableList::const_iterator si; - - // pre-count the size of index data we need since it makes a big perf difference - // to GL in particular if we lock a smaller area of the index buffer - size_t preCountIndexes = 0; - - si = shadowRenderables.begin(); - for (auto& eg : edgeData->edgeGroups) - { - bool firstDarkCapTri = true; - for (auto& edge : eg.edges) - { - // Silhouette edge, when two tris has opposite light facing, or - // degenerate edge where only tri 1 is valid and the tri light facing - char lightFacing = edgeData->triangleLightFacings[edge.triIndex[0]]; - if ((edge.degenerate && lightFacing) || - (!edge.degenerate && (lightFacing != edgeData->triangleLightFacings[edge.triIndex[1]]))) - { - - preCountIndexes += 3; - - // Are we extruding to infinity? - if (!(lightType == Light::LT_DIRECTIONAL && - flags & SRF_EXTRUDE_TO_INFINITY)) - { - preCountIndexes += 3; - } - - if(useMcGuire) - { - // Do dark cap tri - // Use McGuire et al method, a triangle fan covering all silhouette - // edges and one point (taken from the initial tri) - if (flags & SRF_INCLUDE_DARK_CAP) - { - if (firstDarkCapTri) - { - firstDarkCapTri = false; - } - else - { - preCountIndexes += 3; - } - } - } - } - - } - - if(useMcGuire) - { - // Do light cap - if (flags & SRF_INCLUDE_LIGHT_CAP) - { - // Iterate over the triangles which are using this vertex set - EdgeData::TriangleList::const_iterator ti, tiend; - EdgeData::TriangleLightFacingList::const_iterator lfi; - ti = edgeData->triangles.begin() + eg.triStart; - tiend = ti + eg.triCount; - lfi = edgeData->triangleLightFacings.begin() + eg.triStart; - for ( ; ti != tiend; ++ti, ++lfi) - { - assert(ti->vertexSet == eg.vertexSet); - // Check it's light facing - if (*lfi) - { - preCountIndexes += 3; - } - } - - } - } - else - { - // Do both caps - int increment = ((flags & SRF_INCLUDE_DARK_CAP) ? 3 : 0) + ((flags & SRF_INCLUDE_LIGHT_CAP) ? 3 : 0); - if(increment != 0) - { - // Iterate over the triangles which are using this vertex set - EdgeData::TriangleList::const_iterator ti, tiend; - EdgeData::TriangleLightFacingList::const_iterator lfi; - ti = edgeData->triangles.begin() + eg.triStart; - tiend = ti + eg.triCount; - lfi = edgeData->triangleLightFacings.begin() + eg.triStart; - for ( ; ti != tiend; ++ti, ++lfi) - { - assert(ti->vertexSet == eg.vertexSet); - // Check it's light facing - if (*lfi) - preCountIndexes += increment; - } - } - } - ++si; - } - // End pre-count - - //Check if index buffer is to small - if (preCountIndexes > indexBuffer->getNumIndexes()) - { - LogManager::getSingleton().logWarning( - "shadow index buffer size to small. Auto increasing buffer size to" + - StringConverter::toString(sizeof(unsigned short) * preCountIndexes)); - - SceneManager* pManager = Root::getSingleton()._getCurrentSceneManager(); - if (pManager) - { - pManager->setShadowIndexBufferSize(preCountIndexes); - } - - //Check that the index buffer size has actually increased - if (preCountIndexes > indexBuffer->getNumIndexes()) - { - //increasing index buffer size has failed - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Lock request out of bounds.", - "ShadowCaster::generateShadowVolume"); - } - } - else if(indexBufferUsedSize + preCountIndexes > indexBuffer->getNumIndexes()) - { - indexBufferUsedSize = 0; - } - - // Lock index buffer for writing, just enough length as we need - HardwareBufferLockGuard indexLock(indexBuffer, - sizeof(unsigned short) * indexBufferUsedSize, sizeof(unsigned short) * preCountIndexes, - indexBufferUsedSize == 0 ? HardwareBuffer::HBL_DISCARD : HardwareBuffer::HBL_NO_OVERWRITE); - unsigned short* pIdx = static_cast(indexLock.pData); - size_t numIndices = indexBufferUsedSize; - - // Iterate over the groups and form renderables for each based on their - // lightFacing - si = shadowRenderables.begin(); - for (auto& eg : edgeData->edgeGroups) - { - // Initialise the index start for this shadow renderable - IndexData* indexData = (*si)->getRenderOperationForUpdate()->indexData; - - if (indexData->indexBuffer != indexBuffer) - { - (*si)->rebindIndexBuffer(indexBuffer); - indexData = (*si)->getRenderOperationForUpdate()->indexData; - } - - indexData->indexStart = numIndices; - // original number of verts (without extruded copy) - size_t originalVertexCount = eg.vertexData->vertexCount; - bool firstDarkCapTri = true; - unsigned short darkCapStart = 0; - - for (auto& edge : eg.edges) - { - // Silhouette edge, when two tris has opposite light facing, or - // degenerate edge where only tri 1 is valid and the tri light facing - char lightFacing = edgeData->triangleLightFacings[edge.triIndex[0]]; - if ((edge.degenerate && lightFacing) || - (!edge.degenerate && (lightFacing != edgeData->triangleLightFacings[edge.triIndex[1]]))) - { - size_t v0 = edge.vertIndex[0]; - size_t v1 = edge.vertIndex[1]; - if (!lightFacing) - { - // Inverse edge indexes when t1 is light away - std::swap(v0, v1); - } - - /* Note edge(v0, v1) run anticlockwise along the edge from - the light facing tri so to point shadow volume tris outward, - light cap indexes have to be backwards - - We emit 2 tris if light is a point light, 1 if light - is directional, because directional lights cause all - points to converge to a single point at infinity. - - First side tri = near1, near0, far0 - Second tri = far0, far1, near1 - - 'far' indexes are 'near' index + originalVertexCount - because 'far' verts are in the second half of the - buffer - */ - assert(v1 < 65536 && v0 < 65536 && (v0 + originalVertexCount) < 65536 && - "Vertex count exceeds 16-bit index limit!"); - *pIdx++ = static_cast(v1); - *pIdx++ = static_cast(v0); - *pIdx++ = static_cast(v0 + originalVertexCount); - numIndices += 3; - - // Are we extruding to infinity? - if (!(lightType == Light::LT_DIRECTIONAL && - flags & SRF_EXTRUDE_TO_INFINITY)) - { - // additional tri to make quad - *pIdx++ = static_cast(v0 + originalVertexCount); - *pIdx++ = static_cast(v1 + originalVertexCount); - *pIdx++ = static_cast(v1); - numIndices += 3; - } - - if(useMcGuire) - { - // Do dark cap tri - // Use McGuire et al method, a triangle fan covering all silhouette - // edges and one point (taken from the initial tri) - if (flags & SRF_INCLUDE_DARK_CAP) - { - if (firstDarkCapTri) - { - darkCapStart = static_cast(v0 + originalVertexCount); - firstDarkCapTri = false; - } - else - { - *pIdx++ = darkCapStart; - *pIdx++ = static_cast(v1 + originalVertexCount); - *pIdx++ = static_cast(v0 + originalVertexCount); - numIndices += 3; - } - - } - } - } - - } - - if(!useMcGuire) - { - // Do dark cap - if (flags & SRF_INCLUDE_DARK_CAP) - { - // Iterate over the triangles which are using this vertex set - EdgeData::TriangleList::const_iterator ti, tiend; - EdgeData::TriangleLightFacingList::const_iterator lfi; - ti = edgeData->triangles.begin() + eg.triStart; - tiend = ti + eg.triCount; - lfi = edgeData->triangleLightFacings.begin() + eg.triStart; - for ( ; ti != tiend; ++ti, ++lfi) - { - const EdgeData::Triangle& t = *ti; - assert(t.vertexSet == eg.vertexSet); - // Check it's light facing - if (*lfi) - { - assert(t.vertIndex[0] < 65536 && t.vertIndex[1] < 65536 && - t.vertIndex[2] < 65536 && - "16-bit index limit exceeded!"); - *pIdx++ = static_cast(t.vertIndex[1] + originalVertexCount); - *pIdx++ = static_cast(t.vertIndex[0] + originalVertexCount); - *pIdx++ = static_cast(t.vertIndex[2] + originalVertexCount); - numIndices += 3; - } - } - - } - } - - // Do light cap - if (flags & SRF_INCLUDE_LIGHT_CAP) - { - // separate light cap? - if ((*si)->isLightCapSeparate()) - { - // update index count for this shadow renderable - indexData->indexCount = numIndices - indexData->indexStart; - - // get light cap index data for update - indexData = (*si)->getLightCapRenderable()->getRenderOperationForUpdate()->indexData; - // start indexes after the current total - indexData->indexStart = numIndices; - } - - // Iterate over the triangles which are using this vertex set - EdgeData::TriangleList::const_iterator ti, tiend; - EdgeData::TriangleLightFacingList::const_iterator lfi; - ti = edgeData->triangles.begin() + eg.triStart; - tiend = ti + eg.triCount; - lfi = edgeData->triangleLightFacings.begin() + eg.triStart; - for ( ; ti != tiend; ++ti, ++lfi) - { - const EdgeData::Triangle& t = *ti; - assert(t.vertexSet == eg.vertexSet); - // Check it's light facing - if (*lfi) - { - assert(t.vertIndex[0] < 65536 && t.vertIndex[1] < 65536 && - t.vertIndex[2] < 65536 && - "16-bit index limit exceeded!"); - *pIdx++ = static_cast(t.vertIndex[0]); - *pIdx++ = static_cast(t.vertIndex[1]); - *pIdx++ = static_cast(t.vertIndex[2]); - numIndices += 3; - } - } - - } - - // update index count for current index data (either this shadow renderable or its light cap) - indexData->indexCount = numIndices - indexData->indexStart; - - ++si; - } - - // In debug mode, check we didn't overrun the index buffer - assert(numIndices == indexBufferUsedSize + preCountIndexes); - assert(numIndices <= indexBuffer->getNumIndexes() && - "Index buffer overrun while generating shadow volume!! " - "You must increase the size of the shadow index buffer."); - - indexBufferUsedSize = numIndices; - } - // ------------------------------------------------------------------------ - void ShadowCaster::extrudeVertices( - const HardwareVertexBufferSharedPtr& vertexBuffer, - size_t originalVertexCount, const Vector4& light, Real extrudeDist) - { - assert (vertexBuffer->getVertexSize() == sizeof(float) * 3 - && "Position buffer should contain only positions!"); - - // Extrude the first area of the buffer into the second area - // Lock the entire buffer for writing, even though we'll only be - // updating the latter because you can't have 2 locks on the same - // buffer - HardwareBufferLockGuard vertexLock(vertexBuffer, HardwareBuffer::HBL_NORMAL); - float* pSrc = static_cast(vertexLock.pData); - - // TODO: We should add extra (ununsed) vertices ensure source and - // destination buffer have same alignment for slight performance gain. - float* pDest = pSrc + originalVertexCount * 3; - - OptimisedUtil::getImplementation()->extrudeVertices( - light, extrudeDist, - pSrc, pDest, originalVertexCount); - } - // ------------------------------------------------------------------------ - void ShadowCaster::extrudeBounds(AxisAlignedBox& box, const Vector4& light, Real extrudeDist) const - { - Vector3 extrusionDir; - - if (light.w == 0) - { - // Parallel projection guarantees min/max relationship remains the same - extrusionDir.x = -light.x; - extrusionDir.y = -light.y; - extrusionDir.z = -light.z; - extrusionDir.normalise(); - extrusionDir *= extrudeDist; - box.setExtents(box.getMinimum() + extrusionDir, - box.getMaximum() + extrusionDir); - } - else - { - Vector3 oldMin, oldMax, currentCorner; - // Getting the original values - oldMin = box.getMinimum(); - oldMax = box.getMaximum(); - // Starting the box again with a null content - box.setNull(); - - // merging all the extruded corners - - // 0 : min min min - currentCorner = oldMin; - extrusionDir.x = currentCorner.x - light.x; - extrusionDir.y = currentCorner.y - light.y; - extrusionDir.z = currentCorner.z - light.z; - box.merge(currentCorner + extrudeDist * extrusionDir.normalisedCopy()); - - // 6 : min min max - // only z has changed - currentCorner.z = oldMax.z; - extrusionDir.z = currentCorner.z - light.z; - box.merge(currentCorner + extrudeDist * extrusionDir.normalisedCopy()); - - // 5 : min max max - currentCorner.y = oldMax.y; - extrusionDir.y = currentCorner.y - light.y; - box.merge(currentCorner + extrudeDist * extrusionDir.normalisedCopy()); - - // 1 : min max min - currentCorner.z = oldMin.z; - extrusionDir.z = currentCorner.z - light.z; - box.merge(currentCorner + extrudeDist * extrusionDir.normalisedCopy()); - - // 2 : max max min - currentCorner.x = oldMax.x; - extrusionDir.x = currentCorner.x - light.x; - box.merge(currentCorner + extrudeDist * extrusionDir.normalisedCopy()); - - // 4 : max max max - currentCorner.z = oldMax.z; - extrusionDir.z = currentCorner.z - light.z; - box.merge(currentCorner + extrudeDist * extrusionDir.normalisedCopy()); - - // 7 : max min max - currentCorner.y = oldMin.y; - extrusionDir.y = currentCorner.y - light.y; - box.merge(currentCorner + extrudeDist * extrusionDir.normalisedCopy()); - - // 3 : max min min - currentCorner.z = oldMin.z; - extrusionDir.z = currentCorner.z - light.z; - box.merge(currentCorner + extrudeDist * extrusionDir.normalisedCopy()); - - } - - } -} diff --git a/OgreMain/src/OgreShadowRenderer.cpp b/OgreMain/src/OgreShadowRenderer.cpp deleted file mode 100644 index 25c1bf4c36a..00000000000 --- a/OgreMain/src/OgreShadowRenderer.cpp +++ /dev/null @@ -1,1925 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include - -#include "OgreStableHeaders.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreRenderTexture.h" -#include "OgreViewport.h" -#include "OgreRectangle2D.h" -#include "OgreShadowCameraSetup.h" -#include "OgreShadowVolumeExtrudeProgram.h" -#include "OgreHighLevelGpuProgram.h" - -namespace Ogre { - -GpuProgramParametersSharedPtr SceneManager::ShadowRenderer::msInfiniteExtrusionParams; -GpuProgramParametersSharedPtr SceneManager::ShadowRenderer::msFiniteExtrusionParams; - -typedef std::vector ShadowCasterList; - -/// Inner class to use as callback for shadow caster scene query -class ShadowCasterSceneQueryListener : public SceneQueryListener -{ -protected: - SceneManager* mSceneMgr; - ShadowCasterList* mCasterList; - bool mIsLightInFrustum; - const PlaneBoundedVolumeList* mLightClipVolumeList; - const Camera* mCamera; - const Light* mLight; - Real mFarDistSquared; -public: - ShadowCasterSceneQueryListener(SceneManager* sm) : mSceneMgr(sm), - mCasterList(0), mIsLightInFrustum(false), mLightClipVolumeList(0), - mCamera(0), mFarDistSquared(0) {} - // Prepare the listener for use with a set of parameters - void prepare(bool lightInFrustum, const PlaneBoundedVolumeList* lightClipVolumes, const Light* light, - const Camera* cam, ShadowCasterList* casterList, Real farDistSquared) - { - mCasterList = casterList; - mIsLightInFrustum = lightInFrustum; - mLightClipVolumeList = lightClipVolumes; - mCamera = cam; - mLight = light; - mFarDistSquared = farDistSquared; - } - bool queryResult(MovableObject* object) override; -}; - -SceneManager::ShadowRenderer::ShadowRenderer(SceneManager* owner) : -mSceneManager(owner), -mShadowTechnique(SHADOWTYPE_NONE), -mShadowColour(ColourValue(0.25, 0.25, 0.25)), -mShadowCasterPlainBlackPass(0), -mShadowReceiverPass(0), -mShadowModulativePass(0), -mShadowDebugPass(0), -mShadowStencilPass(0), -mShadowIndexBufferSize(51200), -mShadowIndexBufferUsedSize(0), -mShadowTextureCustomCasterPass(0), -mShadowTextureCustomReceiverPass(0), -mFullScreenQuad(0), -mShadowAdditiveLightClip(false), -mDebugShadows(false), -mShadowMaterialInitDone(false), -mShadowUseInfiniteFarPlane(true), -mShadowDirLightExtrudeDist(10000), -mDefaultShadowFarDist(0), -mDefaultShadowFarDistSquared(0), -mShadowTextureOffset(0.6), -mShadowTextureFadeStart(0.7), -mShadowTextureFadeEnd(0.9), -mShadowTextureSelfShadow(false), -mShadowTextureConfigDirty(true), -mShadowCasterRenderBackFaces(true) -{ - mShadowCasterQueryListener = std::make_unique(mSceneManager); - - // set up default shadow camera setup - mDefaultShadowCameraSetup = DefaultShadowCameraSetup::create(); - - mCullCameraSetup = DefaultShadowCameraSetup::create(); - - // init shadow texture count per type. - mShadowTextureCountPerType[Light::LT_POINT] = 1; - mShadowTextureCountPerType[Light::LT_DIRECTIONAL] = 1; - mShadowTextureCountPerType[Light::LT_SPOTLIGHT] = 1; -} - -SceneManager::ShadowRenderer::~ShadowRenderer() {} - -void SceneManager::ShadowRenderer::setShadowColour(const ColourValue& colour) -{ - mShadowColour = colour; -} - -void SceneManager::ShadowRenderer::updateSplitOptions(RenderQueue* queue) -{ - int shadowTechnique = mShadowTechnique; - if(!mSceneManager->getCurrentViewport()->getShadowsEnabled()) - shadowTechnique = SHADOWTYPE_NONE; - - bool notIntegrated = (shadowTechnique & SHADOWDETAILTYPE_INTEGRATED) == 0; - - // Stencil Casters can always be receivers - queue->setShadowCastersCannotBeReceivers(!(shadowTechnique & SHADOWDETAILTYPE_STENCIL) && - !mShadowTextureSelfShadow); - - // Additive lighting, we need to split everything by illumination stage - queue->setSplitPassesByLightingType((shadowTechnique & SHADOWDETAILTYPE_ADDITIVE) && notIntegrated); - - // Tell render queue to split off non-shadowable materials - queue->setSplitNoShadowPasses(shadowTechnique && notIntegrated); -} - -void SceneManager::ShadowRenderer::render(RenderQueueGroup* group, - QueuedRenderableCollection::OrganisationMode om) -{ - if(mShadowTechnique & SHADOWDETAILTYPE_STENCIL) - { - if(mShadowTechnique & SHADOWDETAILTYPE_ADDITIVE) - { - // Additive stencil shadows in use - renderAdditiveStencilShadowedQueueGroupObjects(group, om); - return; - } - - // Modulative stencil shadows in use - renderModulativeStencilShadowedQueueGroupObjects(group, om); - return; - } - - // Receiver pass(es) - if (mShadowTechnique & SHADOWDETAILTYPE_ADDITIVE) - { - // Auto-additive - renderAdditiveTextureShadowedQueueGroupObjects(group, om); - return; - } - - // Modulative - renderModulativeTextureShadowedQueueGroupObjects(group, om); -} -size_t SceneManager::ShadowRenderer::getShadowTexIndex(size_t startLightIndex) -{ - size_t shadowTexIndex = mShadowTextures.size(); - if (mShadowTextureIndexLightList.size() > startLightIndex) - shadowTexIndex = mShadowTextureIndexLightList[startLightIndex]; - return shadowTexIndex; -} -//----------------------------------------------------------------------- -void SceneManager::ShadowRenderer::renderAdditiveStencilShadowedQueueGroupObjects( - RenderQueueGroup* pGroup, - QueuedRenderableCollection::OrganisationMode om) -{ - LightList lightList(1); - auto visitor = mSceneManager->getQueuedRenderableVisitor(); - - for (const auto& pg : pGroup->getPriorityGroups()) - { - RenderPriorityGroup* pPriorityGrp = pg.second; - - // Sort the queue first - pPriorityGrp->sort(mSceneManager->mCameraInProgress); - - // Render all the ambient passes first, no light iteration, no lights - visitor->renderObjects(pPriorityGrp->getSolidsBasic(), om, false, false); - // Also render any objects which have receive shadows disabled - visitor->renderObjects(pPriorityGrp->getSolidsNoShadowReceive(), om, true, true); - - - // Now iterate per light - // Iterate over lights, render all volumes to stencil - for (Light* l : mSceneManager->_getLightsAffectingFrustum()) - { - // Set light state - lightList[0] = l; - - // set up scissor, will cover shadow vol and regular light rendering - ClipResult scissored = mSceneManager->buildAndSetScissor(lightList, mSceneManager->mCameraInProgress); - ClipResult clipped = CLIPPED_NONE; - if (mShadowAdditiveLightClip) - clipped = mSceneManager->buildAndSetLightClip(lightList); - - // skip light if scissored / clipped entirely - if (scissored == CLIPPED_ALL || clipped == CLIPPED_ALL) - continue; - - if (l->getCastShadows()) - { - // Clear stencil - mDestRenderSystem->clearFrameBuffer(FBT_STENCIL); - renderShadowVolumesToStencil(l, mSceneManager->mCameraInProgress, false); - // NB we render where the stencil is equal to zero to render lit areas - StencilState stencilState; - stencilState.enabled = true; - stencilState.compareOp = CMPF_EQUAL; - mDestRenderSystem->setStencilState(stencilState); - } - - // render lighting passes for this light - visitor->renderObjects(pPriorityGrp->getSolidsDiffuseSpecular(), om, false, false, &lightList); - - // Reset stencil params - mDestRenderSystem->setStencilState(StencilState()); - - if (scissored == CLIPPED_SOME) - mSceneManager->resetScissor(); - if (clipped == CLIPPED_SOME) - mSceneManager->resetLightClip(); - - }// for each light - - - // Now render decal passes, no need to set lights as lighting will be disabled - visitor->renderObjects(pPriorityGrp->getSolidsDecal(), om, false, false); - - - }// for each priority - - for (const auto& pg : pGroup->getPriorityGroups()) - { - visitor->renderTransparents(pg.second, om); - } -} -//----------------------------------------------------------------------- -void SceneManager::ShadowRenderer::renderModulativeStencilShadowedQueueGroupObjects( - RenderQueueGroup* pGroup, - QueuedRenderableCollection::OrganisationMode om) -{ - /* For each light, we need to render all the solids from each group, - then do the modulative shadows, then render the transparents from - each group. - Now, this means we are going to reorder things more, but that it required - if the shadows are to look correct. The overall order is preserved anyway, - it's just that all the transparents are at the end instead of them being - interleaved as in the normal rendering loop. - */ - // Iterate through priorities - auto visitor = mSceneManager->getQueuedRenderableVisitor(); - for (const auto& pg : pGroup->getPriorityGroups()) - { - RenderPriorityGroup* pPriorityGrp = pg.second; - - // Sort the queue first - pPriorityGrp->sort(mSceneManager->mCameraInProgress); - - // Do (shadowable) solids - visitor->renderObjects(pPriorityGrp->getSolidsBasic(), om, true, true); - } - - // Override auto param ambient to force vertex programs to use shadow colour - ColourValue currAmbient = mSceneManager->getAmbientLight(); - mSceneManager->setAmbientLight(mShadowColour); - - // Iterate over lights, render all volumes to stencil - for (Light* l : mSceneManager->_getLightsAffectingFrustum()) - { - if (l->getCastShadows()) - { - // Clear stencil - mDestRenderSystem->clearFrameBuffer(FBT_STENCIL); - renderShadowVolumesToStencil(l, mSceneManager->mCameraInProgress, true); - // render full-screen shadow modulator for all lights - mSceneManager->_setPass(mShadowModulativePass); - // NB we render where the stencil is not equal to zero to render shadows, not lit areas - StencilState stencilState; - stencilState.enabled = true; - stencilState.compareOp = CMPF_NOT_EQUAL; - mDestRenderSystem->setStencilState(stencilState); - mSceneManager->renderSingleObject(mFullScreenQuad, mShadowModulativePass, false, false); - // Reset stencil params - mDestRenderSystem->setStencilState(StencilState()); - } - - }// for each light - - // Restore ambient light - mSceneManager->setAmbientLight(currAmbient); - - // Do non-shadowable solids - for (const auto& pg : pGroup->getPriorityGroups()) - { - visitor->renderObjects(pg.second->getSolidsNoShadowReceive(), om, true, true); - } - - for (const auto& pg : pGroup->getPriorityGroups()) - { - visitor->renderTransparents(pg.second, om); - } -} -//----------------------------------------------------------------------- -void SceneManager::ShadowRenderer::renderTextureShadowCasterQueueGroupObjects( - RenderQueueGroup* pGroup, - QueuedRenderableCollection::OrganisationMode om) -{ - // This is like the basic group render, except we skip all transparents - // and we also render any non-shadowed objects - // Note that non-shadow casters will have already been eliminated during - // _findVisibleObjects - - // Iterate through priorities - - // Override auto param ambient to force vertex programs and fixed function to - ColourValue currAmbient = mSceneManager->getAmbientLight(); - if (mShadowTechnique & SHADOWDETAILTYPE_ADDITIVE) - { - // Use simple black / white mask if additive - mSceneManager->setAmbientLight(ColourValue::Black); - } - else - { - // Use shadow colour as caster colour if modulative - mSceneManager->setAmbientLight(mShadowColour); - } - - auto visitor = mSceneManager->getQueuedRenderableVisitor(); - for (const auto& pg : pGroup->getPriorityGroups()) - { - RenderPriorityGroup* pPriorityGrp = pg.second; - - // Sort the queue first - pPriorityGrp->sort(mSceneManager->mCameraInProgress); - - // Do solids, override light list incase any vertex programs use them - visitor->renderObjects(pPriorityGrp->getSolidsBasic(), om, false, false); - visitor->renderObjects(pPriorityGrp->getSolidsNoShadowReceive(), om, false, false); - // Do unsorted transparents that cast shadows - visitor->renderObjects(pPriorityGrp->getTransparentsUnsorted(), om, false, false, nullptr, true); - // Do transparents that cast shadows - visitor->renderObjects(pPriorityGrp->getTransparents(), QueuedRenderableCollection::OM_SORT_DESCENDING, false, - false, nullptr, true); - - }// for each priority - - // reset ambient light - mSceneManager->setAmbientLight(currAmbient); -} -//----------------------------------------------------------------------- -void SceneManager::ShadowRenderer::renderModulativeTextureShadowedQueueGroupObjects( - RenderQueueGroup* pGroup, - QueuedRenderableCollection::OrganisationMode om) -{ - /* For each light, we need to render all the solids from each group, - then do the modulative shadows, then render the transparents from - each group. - Now, this means we are going to reorder things more, but that it required - if the shadows are to look correct. The overall order is preserved anyway, - it's just that all the transparents are at the end instead of them being - interleaved as in the normal rendering loop. - */ - // Iterate through priorities - auto visitor = mSceneManager->getQueuedRenderableVisitor(); - for (const auto& pg : pGroup->getPriorityGroups()) - { - RenderPriorityGroup* pPriorityGrp = pg.second; - - // Sort the queue first - pPriorityGrp->sort(mSceneManager->mCameraInProgress); - - // Do solids - visitor->renderObjects(pPriorityGrp->getSolidsBasic(), om, true, true); - visitor->renderObjects(pPriorityGrp->getSolidsNoShadowReceive(), om, true, true); - } - - - // Iterate over lights, render received shadows - // only perform this if we're in the 'normal' render stage, to avoid - // doing it during the render to texture - if (mSceneManager->mIlluminationStage == IRS_NONE) - { - mSceneManager->mIlluminationStage = IRS_RENDER_RECEIVER_PASS; - - LightList::const_iterator i, iend; - iend = mSceneManager->_getLightsAffectingFrustum().end(); - - size_t si = 0; - for (i = mSceneManager->_getLightsAffectingFrustum().begin(); - i != iend && si < mShadowTextures.size(); ++i) - { - Light* l = *i; - - if (!l->getCastShadows()) - continue; - - // Get camera for current shadow texture - Camera *cam = mShadowTextures[si]->getBuffer()->getRenderTarget()->getViewport(0)->getCamera(); - // Hook up receiver texture - Pass* targetPass = mShadowTextureCustomReceiverPass ? - mShadowTextureCustomReceiverPass : mShadowReceiverPass; - - // if this light is a spotlight, we need to add the spot fader layer - // BUT not if using a custom projection matrix, since then it will be - // inappropriately shaped most likely - if (l->getType() == Light::LT_SPOTLIGHT && !cam->isCustomProjectionMatrixEnabled()) - { - // remove all TUs except 0 & 1 - // (only an issue if additive shadows have been used) - while(targetPass->getNumTextureUnitStates() > 2) - targetPass->removeTextureUnitState(2); - - TextureUnitState* t = NULL; - // Add spot fader if not present already - if (targetPass->getNumTextureUnitStates() == 2 && - targetPass->getTextureUnitState(1)->_getTexturePtr() == mSpotFadeTexture) - { - // Just set - t = targetPass->getTextureUnitState(1); - } - else - { - // Remove any non-conforming spot layers - while(targetPass->getNumTextureUnitStates() > 1) - targetPass->removeTextureUnitState(1); - - t = targetPass->createTextureUnitState(); - t->setTexture(mSpotFadeTexture); - t->setColourOperation(LBO_ADD); - t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); - } - - t->setProjectiveTexturing(!targetPass->hasVertexProgram(), cam); - mSceneManager->mAutoParamDataSource->setTextureProjector(cam, 1); - } - else - { - // remove all TUs except 0 including spot - while(targetPass->getNumTextureUnitStates() > 1) - targetPass->removeTextureUnitState(1); - - } - - // account for the RTSS - if (auto betterTechnique = targetPass->getParent()->getParent()->getBestTechnique()) - { - targetPass = betterTechnique->getPass(0); - } - - TextureUnitState* texUnit = targetPass->getTextureUnitState(0); - // clamp to border colour in case this is a custom material - texUnit->setSampler(mBorderSampler); - resolveShadowTexture(texUnit, si, 0); - - // Set lighting / blending modes - targetPass->setSceneBlending(SBF_DEST_COLOUR, SBF_ZERO); - targetPass->setLightingEnabled(false); - - targetPass->_load(); - - // Fire pre-receiver event - fireShadowTexturesPreReceiver(l, cam); - - renderTextureShadowReceiverQueueGroupObjects(pGroup, om); - - ++si; - - } // for each light - - mSceneManager->mIlluminationStage = IRS_NONE; - - } - - for (const auto& pg : pGroup->getPriorityGroups()) - { - visitor->renderTransparents(pg.second, om); - } -} -//----------------------------------------------------------------------- -void SceneManager::ShadowRenderer::renderAdditiveTextureShadowedQueueGroupObjects( - RenderQueueGroup* pGroup, - QueuedRenderableCollection::OrganisationMode om) -{ - LightList lightList(1); - auto visitor = mSceneManager->getQueuedRenderableVisitor(); - - for (const auto& pg : pGroup->getPriorityGroups()) - { - RenderPriorityGroup* pPriorityGrp = pg.second; - - // Sort the queue first - pPriorityGrp->sort(mSceneManager->mCameraInProgress); - - // Render all the ambient passes first, no light iteration, no lights - visitor->renderObjects(pPriorityGrp->getSolidsBasic(), om, false, false); - // Also render any objects which have receive shadows disabled - visitor->renderObjects(pPriorityGrp->getSolidsNoShadowReceive(), om, true, true); - - - // only perform this next part if we're in the 'normal' render stage, to avoid - // doing it during the render to texture - if (mSceneManager->mIlluminationStage == IRS_NONE) - { - // Iterate over lights, render masked - size_t si = 0; - - for (Light* l : mSceneManager->_getLightsAffectingFrustum()) - { - if (l->getCastShadows() && si < mShadowTextures.size()) - { - // Hook up receiver texture - Pass* targetPass = mShadowTextureCustomReceiverPass ? - mShadowTextureCustomReceiverPass : mShadowReceiverPass; - - // account for the RTSS - if (auto betterTechnique = targetPass->getParent()->getParent()->getBestTechnique()) - { - targetPass = betterTechnique->getPass(0); - } - - TextureUnitState* texUnit = targetPass->getTextureUnitState(0); - // clamp to border colour in case this is a custom material - texUnit->setSampler(mBorderSampler); - resolveShadowTexture(texUnit, si, 0); - - // Remove any spot fader layer - if (targetPass->getNumTextureUnitStates() > 1 && - targetPass->getTextureUnitState(1)->getTextureName() == "spot_shadow_fade.dds") - { - // remove spot fader layer (should only be there if - // we previously used modulative shadows) - targetPass->removeTextureUnitState(1); - } - // Set lighting / blending modes - targetPass->setSceneBlending(SBF_ONE, SBF_ONE); - targetPass->setLightingEnabled(true); - targetPass->_load(); - - // increment shadow texture since used - ++si; - - mSceneManager->mIlluminationStage = IRS_RENDER_RECEIVER_PASS; - - } - else - { - mSceneManager->mIlluminationStage = IRS_NONE; - } - - // render lighting passes for this light - lightList[0] = l; - - // set up light scissoring, always useful in additive modes - ClipResult scissored = mSceneManager->buildAndSetScissor(lightList, mSceneManager->mCameraInProgress); - ClipResult clipped = CLIPPED_NONE; - if(mShadowAdditiveLightClip) - clipped = mSceneManager->buildAndSetLightClip(lightList); - // skip if entirely clipped - if(scissored == CLIPPED_ALL || clipped == CLIPPED_ALL) - continue; - - visitor->renderObjects(pPriorityGrp->getSolidsDiffuseSpecular(), om, false, false, &lightList); - if (scissored == CLIPPED_SOME) - mSceneManager->resetScissor(); - if (clipped == CLIPPED_SOME) - mSceneManager->resetLightClip(); - - }// for each light - - mSceneManager->mIlluminationStage = IRS_NONE; - - // Now render decal passes, no need to set lights as lighting will be disabled - visitor->renderObjects(pPriorityGrp->getSolidsDecal(), om, false, false); - - } - - - }// for each priority - - for (const auto& pg : pGroup->getPriorityGroups()) - { - visitor->renderTransparents(pg.second, om); - } -} -//----------------------------------------------------------------------- -void SceneManager::ShadowRenderer::renderTextureShadowReceiverQueueGroupObjects( - RenderQueueGroup* pGroup, - QueuedRenderableCollection::OrganisationMode om) -{ - // Iterate through priorities - - // Override auto param ambient to force vertex programs to go full-bright - ColourValue currAmbient = mSceneManager->getAmbientLight(); - mSceneManager->setAmbientLight(ColourValue::White); - auto visitor = mSceneManager->getQueuedRenderableVisitor(); - - for (const auto& pg : pGroup->getPriorityGroups()) - { - RenderPriorityGroup* pPriorityGrp = pg.second; - - // Do solids, override light list incase any vertex programs use them - visitor->renderObjects(pPriorityGrp->getSolidsBasic(), om, false, false); - - // Don't render transparents or passes which have shadow receipt disabled - - }// for each priority - - // reset ambient - mSceneManager->setAmbientLight(currAmbient); -} -//--------------------------------------------------------------------- -void SceneManager::ShadowRenderer::ensureShadowTexturesCreated() -{ - if(!mBorderSampler) - { - mBorderSampler = TextureManager::getSingleton().createSampler(); - mBorderSampler->setAddressingMode(TAM_BORDER); - mBorderSampler->setBorderColour(ColourValue::White); - mBorderSampler->setFiltering(FT_MIP, FO_NONE); // we do not have mips. GLES2 is particularly picky here. - } - - if (mShadowTextureConfigDirty) - { - destroyShadowTextures(); - ShadowTextureManager::getSingleton().getShadowTextures(mShadowTextureConfigList, mShadowTextures); - - // clear shadow cam - light mapping - mShadowCamLightMapping.clear(); - - //Used to get the depth buffer ID setting for each RTT - size_t __i = 0; - - // Recreate shadow textures - for (auto& shadowTex : mShadowTextures) - { - // Camera names are local to SM - String camName = shadowTex->getName() + "Cam"; - - RenderTexture *shadowRTT = shadowTex->getBuffer()->getRenderTarget(); - - //Set appropriate depth buffer - if(!PixelUtil::isDepth(shadowRTT->suggestPixelFormat())) - shadowRTT->setDepthBufferPool( mShadowTextureConfigList[__i].depthBufferPoolId ); - - // Create camera for this texture, but note that we have to rebind - // in prepareShadowTextures to coexist with multiple SMs - Camera* cam = mSceneManager->createCamera(camName); - cam->setAspectRatio((Real)shadowTex->getWidth() / (Real)shadowTex->getHeight()); - auto camNode = mSceneManager->getRootSceneNode()->createChildSceneNode(); - camNode->attachObject(cam); - mShadowTextureCameras.push_back(cam); - - // use separate culling camera, in case a focused shadow setup is used - // in which case we want to keep the original light frustum for culling - Camera* cullCam = mSceneManager->createCamera(camName+"/Cull"); - cullCam->setAspectRatio((Real)shadowTex->getWidth() / (Real)shadowTex->getHeight()); - cam->setCullingFrustum(cullCam); - camNode->attachObject(cullCam); - - - // Create a viewport, if not there already - if (shadowRTT->getNumViewports() == 0) - { - // Note camera assignment is transient when multiple SMs - Viewport *v = shadowRTT->addViewport(cam); - v->setClearEveryFrame(true); - // remove overlays - v->setOverlaysEnabled(false); - } - - // Don't update automatically - we'll do it when required - shadowRTT->setAutoUpdated(false); - - // insert dummy camera-light combination - mShadowCamLightMapping[cam] = 0; - - // Get null shadow texture - if (mShadowTextureConfigList.empty()) - { - mNullShadowTexture.reset(); - } - else - { - mNullShadowTexture = ShadowTextureManager::getSingleton().getNullShadowTexture( - mShadowTextureConfigList[0].format); - } - ++__i; - } - mShadowTextureConfigDirty = false; - } - -} -//--------------------------------------------------------------------- -void SceneManager::ShadowRenderer::destroyShadowTextures(void) -{ - for (auto cam : mShadowTextureCameras) - { - mSceneManager->getRootSceneNode()->removeAndDestroyChild(cam->getParentSceneNode()); - - // Always destroy camera since they are local to this SM - if(auto cullcam = dynamic_cast(cam->getCullingFrustum())) - mSceneManager->destroyCamera(cullcam); - - mSceneManager->destroyCamera(cam); - } - mShadowTextures.clear(); - mShadowTextureCameras.clear(); - - // set by render*TextureShadowedQueueGroupObjects - mSceneManager->mAutoParamDataSource->setTextureProjector(NULL, 0); - - // Will destroy if no other scene managers referencing - ShadowTextureManager::getSingleton().clearUnused(); - - mShadowTextureConfigDirty = true; -} -//--------------------------------------------------------------------- -void SceneManager::ShadowRenderer::prepareShadowTextures(Camera* cam, Viewport* vp, const LightList* lightList) -{ - // create shadow textures if needed - ensureShadowTexturesCreated(); - - // Determine far shadow distance - Real shadowDist = mDefaultShadowFarDist; - if (!shadowDist) - { - // need a shadow distance, make one up - shadowDist = cam->getNearClipDistance() * 300; - } - Real shadowOffset = shadowDist * mShadowTextureOffset; - // Precalculate fading info - Real shadowEnd = shadowDist + shadowOffset; - Real fadeStart = shadowEnd * mShadowTextureFadeStart; - Real fadeEnd = shadowEnd * mShadowTextureFadeEnd; - // Additive lighting should not use fogging, since it will overbrighten; use border clamp - if ((mShadowTechnique & SHADOWDETAILTYPE_ADDITIVE) == 0) - { - // set fogging to hide the shadow edge - mShadowReceiverPass->setFog(true, FOG_LINEAR, ColourValue::White, 0, fadeStart, fadeEnd); - } - else - { - // disable fogging explicitly - mShadowReceiverPass->setFog(true, FOG_NONE); - } - - // Iterate over the lights we've found, max out at the limit of light textures - // Note that the light sorting must now place shadow casting lights at the - // start of the light list, therefore we do not need to deal with potential - // mismatches in the light<->shadow texture list any more - - LightList::const_iterator i, iend; - ShadowTextureList::iterator si, siend; - CameraList::iterator ci; - iend = lightList->end(); - siend = mShadowTextures.end(); - ci = mShadowTextureCameras.begin(); - mShadowTextureIndexLightList.clear(); - size_t shadowTextureIndex = 0; - - for (i = lightList->begin(), si = mShadowTextures.begin(); i != iend && si != siend; ++i) - { - Light* light = *i; - - // skip light if shadows are disabled - if (!light->getCastShadows()) - continue; - - mDestRenderSystem->_setDepthClamp(light->getType() == Light::LT_DIRECTIONAL); - - // texture iteration per light. - size_t textureCountPerLight = mShadowTextureCountPerType[light->getType()]; - for (size_t j = 0; j < textureCountPerLight && si != siend; ++j) - { - TexturePtr &shadowTex = *si; - RenderTarget *shadowRTT = shadowTex->getBuffer()->getRenderTarget(); - Viewport *shadowView = shadowRTT->getViewport(0); - Camera *texCam = *ci; - // rebind camera, incase another SM in use which has switched to its cam - shadowView->setCamera(texCam); - - // Associate main view camera as LOD camera - texCam->setLodCamera(cam); - // set base - if (light->getType() != Light::LT_POINT) - { -#ifdef OGRE_NODELESS_POSITIONING - texCam->getParentSceneNode()->setDirection(light->getDerivedDirection(), Node::TS_WORLD); -#else - texCam->getParentSceneNode()->setOrientation(light->getParentNode()->_getDerivedOrientation()); -#endif - } - if (light->getType() != Light::LT_DIRECTIONAL) - texCam->getParentSceneNode()->setPosition(light->getDerivedPosition()); - - // also update culling camera - auto cullCam = dynamic_cast(texCam->getCullingFrustum()); - cullCam->_notifyViewport(shadowView); - mCullCameraSetup->getShadowCamera(mSceneManager, cam, vp, light, cullCam, j); - - // Use the material scheme of the main viewport - // This is required to pick up the correct shadow_caster_material and similar properties. - shadowView->setMaterialScheme(vp->getMaterialScheme()); - - // Set the viewport visibility flags - shadowView->setVisibilityMask(light->getLightMask() & vp->getVisibilityMask()); - - // update shadow cam - light mapping - ShadowCamLightMapping::iterator camLightIt = mShadowCamLightMapping.find( texCam ); - assert(camLightIt != mShadowCamLightMapping.end()); - camLightIt->second = light; - - if (!light->getCustomShadowCameraSetup()) - mDefaultShadowCameraSetup->getShadowCamera(mSceneManager, cam, vp, light, texCam, j); - else - light->getCustomShadowCameraSetup()->getShadowCamera(mSceneManager, cam, vp, light, texCam, j); - - // Setup background colour - shadowView->setBackgroundColour(ColourValue::White); - - // Fire shadow caster update, callee can alter camera settings - fireShadowTexturesPreCaster(light, texCam, j); - - // Update target - shadowRTT->update(); - - ++si; // next shadow texture - ++ci; // next camera - } - - mDestRenderSystem->_setDepthClamp(false); - - // set the first shadow texture index for this light. - mShadowTextureIndexLightList.push_back(shadowTextureIndex); - shadowTextureIndex += textureCountPerLight; - } - - fireShadowTexturesUpdated(std::min(lightList->size(), mShadowTextures.size())); - - ShadowTextureManager::getSingleton().clearUnused(); - -} -//--------------------------------------------------------------------- -void SceneManager::ShadowRenderer::renderShadowVolumesToStencil(const Light* light, - const Camera* camera, bool calcScissor) -{ - // Get the shadow caster list - const ShadowCasterList& casters = findShadowCastersForLight(light, camera); - // Check there are some shadow casters to render - if (casters.empty()) - { - // No casters, just do nothing - return; - } - - // Add light to internal list for use in render call - LightList lightList; - // const_cast is forgiveable here since we pass this const - lightList.push_back(const_cast(light)); - - // Set up scissor test (point & spot lights only) - ClipResult scissored = CLIPPED_NONE; - if (calcScissor) - { - scissored = mSceneManager->buildAndSetScissor(lightList, camera); - if (scissored == CLIPPED_ALL) - return; // nothing to do - } - - mDestRenderSystem->unbindGpuProgram(GPT_FRAGMENT_PROGRAM); - - // Can we do a 2-sided stencil? - bool stencil2sided = false; - if (mDestRenderSystem->getCapabilities()->hasCapability(RSC_TWO_SIDED_STENCIL) && - mDestRenderSystem->getCapabilities()->hasCapability(RSC_STENCIL_WRAP)) - { - // enable - stencil2sided = true; - } - - // Do we have access to vertex programs? - bool extrudeInSoftware = true; - bool finiteExtrude = !mShadowUseInfiniteFarPlane; - if (const auto& fprog = mShadowStencilPass->getFragmentProgram()) - { - extrudeInSoftware = false; - // attach the appropriate extrusion vertex program - // Note we never unset it because support for vertex programs is constant - mShadowStencilPass->setGpuProgram(GPT_VERTEX_PROGRAM, - ShadowVolumeExtrudeProgram::get(light->getType(), finiteExtrude), false); - // Set params - if (finiteExtrude) - { - mShadowStencilPass->setVertexProgramParameters(msFiniteExtrusionParams); - } - else - { - mShadowStencilPass->setVertexProgramParameters(msInfiniteExtrusionParams); - } - if (mDebugShadows) - { - mShadowDebugPass->setGpuProgram(GPT_VERTEX_PROGRAM, - ShadowVolumeExtrudeProgram::get(light->getType(), finiteExtrude), false); - - // Set params - if (finiteExtrude) - { - mShadowDebugPass->setVertexProgramParameters(msFiniteExtrusionParams); - } - else - { - mShadowDebugPass->setVertexProgramParameters(msInfiniteExtrusionParams); - } - } - - mSceneManager->bindGpuProgram(mShadowStencilPass->getVertexProgram()->_getBindingDelegate()); - mSceneManager->bindGpuProgram(fprog->_getBindingDelegate()); - } - else - { - mDestRenderSystem->unbindGpuProgram(GPT_VERTEX_PROGRAM); - } - if (mDestRenderSystem->getCapabilities()->hasCapability(RSC_GEOMETRY_PROGRAM)) - { - mDestRenderSystem->unbindGpuProgram(GPT_GEOMETRY_PROGRAM); - } - - mDestRenderSystem->_setAlphaRejectSettings(mShadowStencilPass->getAlphaRejectFunction(), - mShadowStencilPass->getAlphaRejectValue(), mShadowStencilPass->isAlphaToCoverageEnabled()); - - // Turn off colour writing and depth writing - ColourBlendState disabled; - disabled.writeR = disabled.writeG = disabled.writeB = disabled.writeA = false; - mDestRenderSystem->setColourBlendState(disabled); - mDestRenderSystem->_disableTextureUnitsFrom(0); - mDestRenderSystem->_setDepthBufferParams(true, false, CMPF_LESS); - - // Figure out the near clip volume - const PlaneBoundedVolume& nearClipVol = - light->_getNearClipVolume(camera); - - // Now iterate over the casters and render - for (auto *caster : casters) - { - bool zfailAlgo = camera->isCustomNearClipPlaneEnabled(); - unsigned long flags = 0; - - // Calculate extrusion distance - Real extrudeDist = mShadowDirLightExtrudeDist; - if (light->getType() != Light::LT_DIRECTIONAL) - { - // we have to limit shadow extrusion to avoid cliping by far clip plane - extrudeDist = std::min(caster->getPointExtrusionDistance(light), mShadowDirLightExtrudeDist); - // Set autoparams for finite point light extrusion - mSceneManager->mAutoParamDataSource->setShadowPointLightExtrusionDistance(extrudeDist); - } - - Real darkCapExtrudeDist = extrudeDist; - if (!extrudeInSoftware && !finiteExtrude) - { - // hardware extrusion, to infinity (and beyond!) - flags |= SRF_EXTRUDE_TO_INFINITY; - darkCapExtrudeDist = mShadowDirLightExtrudeDist; - } - - // Determine whether zfail is required - if (zfailAlgo || nearClipVol.intersects(caster->getWorldBoundingBox())) - { - // We use zfail for this object only because zfail - // compatible with zpass algorithm - zfailAlgo = true; - // We need to include the light and / or dark cap - // But only if they will be visible - if(camera->isVisible(caster->getLightCapBounds())) - { - flags |= SRF_INCLUDE_LIGHT_CAP; - } - // zfail needs dark cap - // UNLESS directional lights using hardware extrusion to infinity - // since that extrudes to a single point - if(!((flags & SRF_EXTRUDE_TO_INFINITY) && - light->getType() == Light::LT_DIRECTIONAL) && - camera->isVisible(caster->getDarkCapBounds(*light, darkCapExtrudeDist))) - { - flags |= SRF_INCLUDE_DARK_CAP; - } - } - else - { - // In zpass we need a dark cap if - // 1: infinite extrusion on point/spotlight sources in modulative shadows - // mode, since otherwise in areas where there is no depth (skybox) - // the infinitely projected volume will leave a dark band - // 2: finite extrusion on any light source since glancing angles - // can peek through the end and shadow objects behind incorrectly - if ((flags & SRF_EXTRUDE_TO_INFINITY) && - light->getType() != Light::LT_DIRECTIONAL && - (mShadowTechnique & SHADOWDETAILTYPE_MODULATIVE) && - camera->isVisible(caster->getDarkCapBounds(*light, darkCapExtrudeDist))) - { - flags |= SRF_INCLUDE_DARK_CAP; - } - else if (!(flags & SRF_EXTRUDE_TO_INFINITY) && - camera->isVisible(caster->getDarkCapBounds(*light, darkCapExtrudeDist))) - { - flags |= SRF_INCLUDE_DARK_CAP; - } - - } - - if(extrudeInSoftware) // convert to flag - flags |= SRF_EXTRUDE_IN_SOFTWARE; - - // Get shadow renderables - const ShadowRenderableList& shadowRenderables = caster->getShadowVolumeRenderableList( - light, mShadowIndexBuffer, mShadowIndexBufferUsedSize, extrudeDist, flags); - - // Render a shadow volume here - // - if we have 2-sided stencil, one render with no culling - // - otherwise, 2 renders, one with each culling method and invert the ops - setShadowVolumeStencilState(false, zfailAlgo, stencil2sided); - renderShadowVolumeObjects(shadowRenderables, mShadowStencilPass, &lightList, flags, - false, zfailAlgo, stencil2sided); - if (!stencil2sided) - { - // Second pass - setShadowVolumeStencilState(true, zfailAlgo, false); - renderShadowVolumeObjects(shadowRenderables, mShadowStencilPass, &lightList, flags, - true, zfailAlgo, false); - } - - // Do we need to render a debug shadow marker? - if (mDebugShadows) - { - // reset stencil & colour ops - mDestRenderSystem->setStencilState(StencilState()); - - auto shadowColour = mShadowColour; - mShadowColour = zfailAlgo ? ColourValue(0.7, 0.0, 0.2) : ColourValue(0.0, 0.7, 0.2); - mSceneManager->_setPass(mShadowDebugPass); - renderShadowVolumeObjects(shadowRenderables, mShadowDebugPass, &lightList, flags, - true, false, false); - mDestRenderSystem->setColourBlendState(disabled); - mDestRenderSystem->_setDepthBufferParams(true, false, CMPF_LESS); - mShadowColour = shadowColour; - } - } - - // revert stencil state - mDestRenderSystem->setStencilState(StencilState()); - - mDestRenderSystem->unbindGpuProgram(GPT_VERTEX_PROGRAM); - - if (scissored == CLIPPED_SOME) - { - // disable scissor test - mSceneManager->resetScissor(); - } - -} -//--------------------------------------------------------------------- -void SceneManager::ShadowRenderer::renderShadowVolumeObjects(const ShadowCaster::ShadowRenderableList& shadowRenderables, - Pass* pass, - const LightList *manualLightList, - unsigned long flags, - bool secondpass, bool zfail, bool twosided) -{ - // ----- SHADOW VOLUME LOOP ----- - // Render all shadow renderables with same stencil operations - for (ShadowRenderable* sr : shadowRenderables) - { - // omit hidden renderables - if (sr->isVisible()) - { - // render volume, including dark and (maybe) light caps - mSceneManager->renderSingleObject(sr, pass, false, false, manualLightList); - - // optionally render separate light cap - if (sr->isLightCapSeparate() && (flags & SRF_INCLUDE_LIGHT_CAP)) - { - ShadowRenderable* lightCap = sr->getLightCapRenderable(); - assert(lightCap && "Shadow renderable is missing a separate light cap renderable!"); - - // We must take care with light caps when we could 'see' the back facing - // triangles directly: - // 1. The front facing light caps must render as always fail depth - // check to avoid 'depth fighting'. - // 2. The back facing light caps must use normal depth function to - // avoid break the standard depth check - // - // TODO: - // 1. Separate light caps rendering doesn't need for the 'closed' - // mesh that never touch the near plane, because in this instance, - // we couldn't 'see' any back facing triangles directly. The - // 'closed' mesh must determinate by edge list builder. - // 2. There still exists 'depth fighting' bug with coplane triangles - // that has opposite facing. This usually occur when use two side - // material in the modeling tools and the model exporting tools - // exporting double triangles to represent this model. This bug - // can't fixed in GPU only, there must has extra work on edge list - // builder and shadow volume generater to fix it. - // - if (twosided) - { - // select back facing light caps to render - mDestRenderSystem->_setCullingMode(CULL_ANTICLOCKWISE); - mSceneManager->mPassCullingMode = CULL_ANTICLOCKWISE; - // use normal depth function for back facing light caps - mSceneManager->renderSingleObject(lightCap, pass, false, false, manualLightList); - - // select front facing light caps to render - mDestRenderSystem->_setCullingMode(CULL_CLOCKWISE); - mSceneManager->mPassCullingMode = CULL_CLOCKWISE; - // must always fail depth check for front facing light caps - mDestRenderSystem->_setDepthBufferParams(true, false, CMPF_ALWAYS_FAIL); - mSceneManager->renderSingleObject(lightCap, pass, false, false, manualLightList); - - // reset depth function - mDestRenderSystem->_setDepthBufferParams(true, false, CMPF_LESS); - // reset culling mode - mDestRenderSystem->_setCullingMode(CULL_NONE); - mSceneManager->mPassCullingMode = CULL_NONE; - } - else if ((secondpass || zfail) && !(secondpass && zfail)) - { - // use normal depth function for back facing light caps - mSceneManager->renderSingleObject(lightCap, pass, false, false, manualLightList); - } - else - { - // must always fail depth check for front facing light caps - mDestRenderSystem->_setDepthBufferParams(true, false, CMPF_ALWAYS_FAIL); - mSceneManager->renderSingleObject(lightCap, pass, false, false, manualLightList); - - // reset depth function - mDestRenderSystem->_setDepthBufferParams(true, false, CMPF_LESS); - } - } - } - } -} -//--------------------------------------------------------------------- -void SceneManager::ShadowRenderer::setShadowVolumeStencilState(bool secondpass, bool zfail, bool twosided) -{ - // Determinate the best stencil operation - StencilOperation incrOp, decrOp; - if (mDestRenderSystem->getCapabilities()->hasCapability(RSC_STENCIL_WRAP)) - { - incrOp = SOP_INCREMENT_WRAP; - decrOp = SOP_DECREMENT_WRAP; - } - else - { - incrOp = SOP_INCREMENT; - decrOp = SOP_DECREMENT; - } - - // First pass, do front faces if zpass - // Second pass, do back faces if zpass - // Invert if zfail - // this is to ensure we always increment before decrement - // When two-sided stencil, always pass front face stencil - // operation parameters and the inverse of them will happen - // for back faces - StencilState stencilState; - stencilState.enabled = true; - stencilState.compareOp = CMPF_ALWAYS_PASS; // always pass stencil check - stencilState.twoSidedOperation = twosided; - if ( !twosided && ((secondpass || zfail) && !(secondpass && zfail)) ) - { - mSceneManager->mPassCullingMode = twosided? CULL_NONE : CULL_ANTICLOCKWISE; - stencilState.depthFailOp = zfail ? incrOp : SOP_KEEP; // back face depth fail - stencilState.depthStencilPassOp = zfail ? SOP_KEEP : decrOp; // back face pass - } - else - { - mSceneManager->mPassCullingMode = twosided? CULL_NONE : CULL_CLOCKWISE; - stencilState.depthFailOp = zfail ? decrOp : SOP_KEEP; // front face depth fail - stencilState.depthStencilPassOp = zfail ? SOP_KEEP : incrOp; // front face pass - } - mDestRenderSystem->setStencilState(stencilState); - mDestRenderSystem->_setCullingMode(mSceneManager->mPassCullingMode); - -} -void SceneManager::ShadowRenderer::setShadowTextureCasterMaterial(const MaterialPtr& mat) -{ - if(!mat) { - mShadowTextureCustomCasterPass = 0; - return; - } - - mat->load(); - if (!mat->getBestTechnique()) - { - // unsupported - mShadowTextureCustomCasterPass = 0; - } - else - { - OgreAssert(!mat->getTechnique(0)->getPasses().empty(), "technique 0 has no passes"); - mShadowTextureCustomCasterPass = mat->getTechnique(0)->getPass(0); - } -} -//--------------------------------------------------------------------- -void SceneManager::ShadowRenderer::setShadowTextureReceiverMaterial(const MaterialPtr& mat) -{ - if(!mat) { - mShadowTextureCustomReceiverPass = 0; - return; - } - - mat->load(); - if (!mat->getBestTechnique()) - { - // unsupported - mShadowTextureCustomReceiverPass = 0; - } - else - { - OgreAssert(!mat->getTechnique(0)->getPasses().empty(), "technique 0 has no passes"); - mShadowTextureCustomReceiverPass = mat->getTechnique(0)->getPass(0); - } -} -//--------------------------------------------------------------------- -void SceneManager::ShadowRenderer::setShadowTechnique(ShadowTechnique technique) -{ - mShadowTechnique = technique; - if (mShadowTechnique & SHADOWDETAILTYPE_STENCIL) - { - // Firstly check that we have a stencil - // Otherwise forget it - if (!mDestRenderSystem->getCapabilities()->hasCapability(RSC_HWSTENCIL)) - { - LogManager::getSingleton().logWarning( - "Stencil shadows were requested, but this device does not " - "have a hardware stencil. Shadows disabled."); - mShadowTechnique = SHADOWTYPE_NONE; - } - else if (!mShadowIndexBuffer) - { - // Create an estimated sized shadow index buffer - mShadowIndexBuffer = HardwareBufferManager::getSingleton(). - createIndexBuffer(HardwareIndexBuffer::IT_16BIT, - mShadowIndexBufferSize, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE, - false); - // tell all meshes to prepare shadow volumes - MeshManager::getSingleton().setPrepareAllMeshesForShadowVolumes(true); - } - } - - if (mShadowTechnique == SHADOWTYPE_TEXTURE_MODULATIVE && !mSpotFadeTexture) - mSpotFadeTexture = TextureManager::getSingleton().load("spot_shadow_fade.dds", RGN_INTERNAL); - - if ((mShadowTechnique & SHADOWDETAILTYPE_TEXTURE) == 0) - { - // Destroy shadow textures to optimise resource usage - destroyShadowTextures(); - mSpotFadeTexture.reset(); - } - else - { - // assure no custom shadow matrix is used accidentally in case we switch - // from a custom shadow mapping type to a non-custom (uniform shadow mapping) - for ( Camera* texCam : mShadowTextureCameras) - { - texCam->setCustomViewMatrix(false); - texCam->setCustomProjectionMatrix(false); - } - } - - if(mShadowTechnique) - initShadowVolumeMaterials(); -} -//--------------------------------------------------------------------- -void SceneManager::ShadowRenderer::initShadowVolumeMaterials() -{ - /* This should have been set in the SceneManager constructor, but if you - created the SceneManager BEFORE the Root object, you will need to call - SceneManager::_setDestinationRenderSystem manually. - */ - OgreAssert( mDestRenderSystem, "no RenderSystem"); - - if (mShadowMaterialInitDone) - return; - - if (!mShadowDebugPass) - { - ShadowVolumeExtrudeProgram::initialise(); - MaterialPtr matDebug = MaterialManager::getSingleton().getByName("Ogre/Debug/ShadowVolumes"); - mShadowDebugPass = matDebug->getTechnique(0)->getPass(0); - msInfiniteExtrusionParams = mShadowDebugPass->getVertexProgramParameters(); - } - - if (!mShadowStencilPass) - { - MaterialPtr matStencil = MaterialManager::getSingleton().getByName("Ogre/StencilShadowVolumes"); - mShadowStencilPass = matStencil->getTechnique(0)->getPass(0); - msFiniteExtrusionParams = mShadowStencilPass->getVertexProgramParameters(); - } - - if (!mShadowModulativePass) - { - MaterialPtr matModStencil = MaterialManager::getSingleton().getByName("Ogre/StencilShadowModulationPass"); - matModStencil->load(); - mShadowModulativePass = matModStencil->getTechnique(0)->getPass(0); - } - - // Also init full screen quad while we're at it - if (!mFullScreenQuad) - { - mFullScreenQuad = mSceneManager->createScreenSpaceRect(); - } - - // Also init shadow caster material for texture shadows - if (!mShadowCasterPlainBlackPass) - { - MaterialPtr matPlainBlack = MaterialManager::getSingleton().getByName("Ogre/TextureShadowCaster"); - matPlainBlack->load(); - mShadowCasterPlainBlackPass = matPlainBlack->getTechnique(0)->getPass(0); - } - - if (!mShadowReceiverPass) - { - MaterialPtr matShadRec = MaterialManager::getSingleton().getByName("Ogre/TextureShadowReceiver", RGN_INTERNAL); - if (!matShadRec) - { - matShadRec = MaterialManager::getSingleton().create("Ogre/TextureShadowReceiver", RGN_INTERNAL); - mShadowReceiverPass = matShadRec->getTechnique(0)->getPass(0); - // Don't set lighting and blending modes here, depends on additive / modulative - TextureUnitState* t = mShadowReceiverPass->createTextureUnitState(); - t->setProjectiveTexturing(true, NULL); // will be set later, but the RTSS needs to know about this - } - else - { - mShadowReceiverPass = matShadRec->getTechnique(0)->getPass(0); - } - } - - mShadowMaterialInitDone = true; -} -const Pass* SceneManager::ShadowRenderer::deriveShadowCasterPass(const Pass* pass) -{ - Pass* retPass; - if (pass->getParent()->getShadowCasterMaterial()) - { - return pass->getParent()->getShadowCasterMaterial()->getBestTechnique()->getPass(0); - } - else - { - retPass = mShadowTextureCustomCasterPass ? - mShadowTextureCustomCasterPass : mShadowCasterPlainBlackPass; - } - - // Special case alpha-blended passes - if ((pass->getSourceBlendFactor() == SBF_SOURCE_ALPHA && - pass->getDestBlendFactor() == SBF_ONE_MINUS_SOURCE_ALPHA) - || pass->getAlphaRejectFunction() != CMPF_ALWAYS_PASS) - { - // Alpha blended passes must retain their transparency - retPass->setAlphaRejectSettings(pass->getAlphaRejectFunction(), - pass->getAlphaRejectValue()); - retPass->setSceneBlending(pass->getSourceBlendFactor(), pass->getDestBlendFactor()); - retPass->getParent()->getParent()->setTransparencyCastsShadows(true); - - // So we allow the texture units, but override the colour functions - // Copy texture state, shift up one since 0 is shadow texture - unsigned short origPassTUCount = pass->getNumTextureUnitStates(); - for (unsigned short t = 0; t < origPassTUCount; ++t) - { - TextureUnitState* tex; - if (retPass->getNumTextureUnitStates() <= t) - { - tex = retPass->createTextureUnitState(); - } - else - { - tex = retPass->getTextureUnitState(t); - } - // copy base state - (*tex) = *(pass->getTextureUnitState(t)); - // override colour function - tex->setColourOperationEx(LBX_SOURCE1, LBS_MANUAL, LBS_CURRENT, - mShadowTechnique & SHADOWDETAILTYPE_ADDITIVE ? ColourValue::Black : mShadowColour); - - } - // Remove any extras - while (retPass->getNumTextureUnitStates() > origPassTUCount) - { - retPass->removeTextureUnitState(origPassTUCount); - } - - } - else - { - // reset - retPass->setSceneBlending(SBT_REPLACE); - retPass->setAlphaRejectFunction(CMPF_ALWAYS_PASS); - while (retPass->getNumTextureUnitStates() > 0) - { - retPass->removeTextureUnitState(0); - } - } - - // give the RTSS a chance to generate a better technique - retPass->getParent()->getParent()->load(); - - Technique* btech = retPass->getParent()->getParent()->getBestTechnique(); - if( btech ) - { - retPass = btech->getPass(0); - } - - // Propagate culling modes - retPass->setCullingMode(pass->getCullingMode()); - retPass->setManualCullingMode(pass->getManualCullingMode()); - - return retPass; -} -//--------------------------------------------------------------------- -const Pass* SceneManager::ShadowRenderer::deriveShadowReceiverPass(const Pass* pass) -{ - if (pass->getParent()->getShadowReceiverMaterial()) - { - return pass->getParent()->getShadowReceiverMaterial()->getBestTechnique()->getPass(0); - } - - Pass* retPass = mShadowTextureCustomReceiverPass ? mShadowTextureCustomReceiverPass : mShadowReceiverPass; - - unsigned short keepTUCount; - // If additive, need lighting parameters & standard programs - if (mShadowTechnique & SHADOWDETAILTYPE_ADDITIVE) - { - retPass->setLightingEnabled(true); - retPass->setAmbient(pass->getAmbient()); - retPass->setSelfIllumination(pass->getSelfIllumination()); - retPass->setDiffuse(pass->getDiffuse()); - retPass->setSpecular(pass->getSpecular()); - retPass->setShininess(pass->getShininess()); - retPass->setLightMask(pass->getLightMask()); - - // We need to keep alpha rejection settings - retPass->setAlphaRejectSettings(pass->getAlphaRejectFunction(), - pass->getAlphaRejectValue()); - // Copy texture state, shift up one since 0 is shadow texture - unsigned short origPassTUCount = pass->getNumTextureUnitStates(); - for (unsigned short t = 0; t < origPassTUCount; ++t) - { - unsigned short targetIndex = t+1; - TextureUnitState* tex; - if (retPass->getNumTextureUnitStates() <= targetIndex) - { - tex = retPass->createTextureUnitState(); - } - else - { - tex = retPass->getTextureUnitState(targetIndex); - } - (*tex) = *(pass->getTextureUnitState(t)); - // If programmable, have to adjust the texcoord sets too - // D3D insists that texcoordsets match tex unit in programmable mode - if (retPass->hasVertexProgram()) - tex->setTextureCoordSet(targetIndex); - } - keepTUCount = origPassTUCount + 1; - }// additive lighting - else - { - // need to keep spotlight fade etc - keepTUCount = retPass->getNumTextureUnitStates(); - } - - // re-/set light iteration settings - retPass->setIteratePerLight(pass->getIteratePerLight(), pass->getRunOnlyForOneLightType(), - pass->getOnlyLightType()); - - // Remove any extra texture units - while (retPass->getNumTextureUnitStates() > keepTUCount) - { - retPass->removeTextureUnitState(keepTUCount); - } - - // give the RTSS a chance to generate a better technique - retPass->getParent()->getParent()->load(); - - Technique* btech = retPass->getParent()->getParent()->getBestTechnique(); - if( btech ) - { - retPass = btech->getPass(0); - } - - return retPass; -} - -const Pass* SceneManager::ShadowRenderer::deriveTextureShadowPass(const Pass* pass) -{ - if((mShadowTechnique & SHADOWDETAILTYPE_TEXTURE) == 0) - return pass; - - if (mSceneManager->_getCurrentRenderStage() == IRS_RENDER_TO_TEXTURE) - { - // Derive a special shadow caster pass from this one - return deriveShadowCasterPass(pass); - } - - if (mSceneManager->_getCurrentRenderStage() == IRS_RENDER_RECEIVER_PASS) - { - return deriveShadowReceiverPass(pass); - } - - return pass; -} - -//--------------------------------------------------------------------- -const VisibleObjectsBoundsInfo& -SceneManager::ShadowRenderer::getShadowCasterBoundsInfo( const Light* light, size_t iteration ) const -{ - static VisibleObjectsBoundsInfo nullBox; - - // find light - unsigned int foundCount = 0; - for (auto& m : mShadowCamLightMapping) - { - if (m.second == light ) - { - if (foundCount == iteration) - { - // search the camera-aab list for the texture cam - auto camIt = mSceneManager->mCamVisibleObjectsMap.find(m.first); - - if (camIt == mSceneManager->mCamVisibleObjectsMap.end()) - { - return nullBox; - } - else - { - return camIt->second; - } - } - else - { - // multiple shadow textures per light, keep searching - ++foundCount; - } - } - } - - // AAB not available - return nullBox; -} -//--------------------------------------------------------------------- -void SceneManager::ShadowRenderer::setShadowIndexBufferSize(size_t size) -{ - if (mShadowIndexBuffer && size != mShadowIndexBufferSize) - { - // re-create shadow buffer with new size - mShadowIndexBuffer = HardwareBufferManager::getSingleton(). - createIndexBuffer(HardwareIndexBuffer::IT_16BIT, - size, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE, - false); - } - mShadowIndexBufferSize = size; - mShadowIndexBufferUsedSize = 0; -} -//--------------------------------------------------------------------- -void SceneManager::ShadowRenderer::setShadowTextureConfig(size_t shadowIndex, unsigned short width, - unsigned short height, PixelFormat format, unsigned short fsaa, uint16 depthBufferPoolId ) -{ - ShadowTextureConfig conf; - conf.width = width; - conf.height = height; - conf.format = format; - conf.fsaa = fsaa; - conf.depthBufferPoolId = depthBufferPoolId; - - setShadowTextureConfig(shadowIndex, conf); - - -} -//--------------------------------------------------------------------- -void SceneManager::ShadowRenderer::setShadowTextureConfig(size_t shadowIndex, - const ShadowTextureConfig& config) -{ - if (shadowIndex >= mShadowTextureConfigList.size()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "shadowIndex out of bounds", - "SceneManager::setShadowTextureConfig"); - } - mShadowTextureConfigList[shadowIndex] = config; - - mShadowTextureConfigDirty = true; -} -//--------------------------------------------------------------------- -void SceneManager::ShadowRenderer::setShadowTextureSize(unsigned short size) -{ - // default all current - for (auto & i : mShadowTextureConfigList) - { - if (i.width != size || i.height != size) - { - i.width = i.height = size; - mShadowTextureConfigDirty = true; - } - } - -} -//--------------------------------------------------------------------- -void SceneManager::ShadowRenderer::setShadowTextureCount(size_t count) -{ - // Change size, any new items will need defaults - if (count != mShadowTextureConfigList.size()) - { - // if no entries yet, use the defaults - if (mShadowTextureConfigList.empty()) - { - mShadowTextureConfigList.resize(count); - } - else - { - // create new instances with the same settings as the last item in the list - mShadowTextureConfigList.resize(count, *mShadowTextureConfigList.rbegin()); - } - mShadowTextureConfigDirty = true; - } -} -//--------------------------------------------------------------------- -void SceneManager::ShadowRenderer::setShadowTexturePixelFormat(PixelFormat fmt) -{ - for (auto & i : mShadowTextureConfigList) - { - if (i.format != fmt) - { - i.format = fmt; - mShadowTextureConfigDirty = true; - } - } -} -void SceneManager::ShadowRenderer::setShadowTextureFSAA(unsigned short fsaa) -{ - for (auto & i : mShadowTextureConfigList) - { - if (i.fsaa != fsaa) - { - i.fsaa = fsaa; - mShadowTextureConfigDirty = true; - } - } -} -//--------------------------------------------------------------------- -void SceneManager::ShadowRenderer::setShadowTextureSettings(unsigned short size, - unsigned short count, PixelFormat fmt, unsigned short fsaa, uint16 depthBufferPoolId) -{ - setShadowTextureCount(count); - for (auto & i : mShadowTextureConfigList) - { - if (i.width != size || i.height != size || i.format != fmt || i.fsaa != fsaa) - { - i.width = i.height = size; - i.format = fmt; - i.fsaa = fsaa; - i.depthBufferPoolId = depthBufferPoolId; - mShadowTextureConfigDirty = true; - } - } -} -//--------------------------------------------------------------------- -const TexturePtr& SceneManager::ShadowRenderer::getShadowTexture(size_t shadowIndex) -{ - if (shadowIndex >= mShadowTextureConfigList.size()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "shadowIndex out of bounds", - "SceneManager::getShadowTexture"); - } - ensureShadowTexturesCreated(); - - return mShadowTextures[shadowIndex]; -} - -void SceneManager::ShadowRenderer::resolveShadowTexture(TextureUnitState* tu, size_t shadowIndex, size_t shadowTexUnitIndex) const -{ - Camera* cam = NULL; - TexturePtr shadowTex; - if (shadowIndex < mShadowTextures.size()) - { - shadowTex = mShadowTextures[shadowIndex]; - // Hook up projection frustum - cam = shadowTex->getBuffer()->getRenderTarget()->getViewport(0)->getCamera(); - // Enable projective texturing if fixed-function, but also need to - // disable it explicitly for program pipeline. - tu->setProjectiveTexturing(!tu->getParent()->hasVertexProgram(), cam); - } - else - { - // Use fallback 'null' shadow texture - // no projection since all uniform colour anyway - shadowTex = mNullShadowTexture; - tu->setProjectiveTexturing(false); - } - mSceneManager->mAutoParamDataSource->setTextureProjector(cam, shadowTexUnitIndex); - tu->_setTexturePtr(shadowTex); -} - -//--------------------------------------------------------------------- -bool ShadowCasterSceneQueryListener::queryResult(MovableObject* object) -{ - if (object->getCastShadows() && object->isVisible() && - mSceneMgr->isRenderQueueToBeProcessed(object->getRenderQueueGroup()) && - // objects need an edge list to cast shadows (shadow volumes only) - ((mSceneMgr->getShadowTechnique() & SHADOWDETAILTYPE_TEXTURE) || - ((mSceneMgr->getShadowTechnique() & SHADOWDETAILTYPE_STENCIL) && object->hasEdgeList()) - ) - ) - { - if (mFarDistSquared) - { - // Check object is within the shadow far distance - Real dist = object->getParentNode()->getSquaredViewDepth(mCamera); - Real radius = object->getBoundingRadiusScaled(); - if (dist - (radius * radius) > mFarDistSquared) - { - // skip, beyond max range - return true; - } - } - - // If the object is in the frustum, we can always see the shadow - if (mCamera->isVisible(object->getWorldBoundingBox())) - { - mCasterList->push_back(object); - return true; - } - - // Otherwise, object can only be casting a shadow into our view if - // the light is outside the frustum (or it's a directional light, - // which are always outside), and the object is intersecting - // on of the volumes formed between the edges of the frustum and the - // light - if (!mIsLightInFrustum || mLight->getType() == Light::LT_DIRECTIONAL) - { - // Iterate over volumes - PlaneBoundedVolumeList::const_iterator i, iend; - iend = mLightClipVolumeList->end(); - for (i = mLightClipVolumeList->begin(); i != iend; ++i) - { - if (i->intersects(object->getWorldBoundingBox())) - { - mCasterList->push_back(object); - return true; - } - - } - - } - } - return true; -} -//--------------------------------------------------------------------- -const SceneManager::ShadowRenderer::ShadowCasterList& -SceneManager::ShadowRenderer::findShadowCastersForLight(const Light* light, const Camera* camera) -{ - mShadowCasterList.clear(); - - if (light->getType() == Light::LT_DIRECTIONAL) - { - // Basic AABB query encompassing the frustum and the extrusion of it - AxisAlignedBox aabb; - const Vector3* corners = camera->getWorldSpaceCorners(); - Vector3 min, max; - Vector3 extrude = light->getDerivedDirection() * -mShadowDirLightExtrudeDist; - // do first corner - min = max = corners[0]; - min.makeFloor(corners[0] + extrude); - max.makeCeil(corners[0] + extrude); - for (size_t c = 1; c < 8; ++c) - { - min.makeFloor(corners[c]); - max.makeCeil(corners[c]); - min.makeFloor(corners[c] + extrude); - max.makeCeil(corners[c] + extrude); - } - aabb.setExtents(min, max); - - if (!mShadowCasterAABBQuery) - mShadowCasterAABBQuery.reset(mSceneManager->createAABBQuery(aabb)); - else - mShadowCasterAABBQuery->setBox(aabb); - // Execute, use callback - mShadowCasterQueryListener->prepare(false, - &(light->_getFrustumClipVolumes(camera)), - light, camera, &mShadowCasterList, light->getShadowFarDistanceSquared()); - mShadowCasterAABBQuery->execute(mShadowCasterQueryListener.get()); - - - } - else - { - Sphere s(light->getDerivedPosition(), light->getAttenuationRange()); - // eliminate early if camera cannot see light sphere - if (camera->isVisible(s)) - { - if (!mShadowCasterSphereQuery) - mShadowCasterSphereQuery.reset(mSceneManager->createSphereQuery(s)); - else - mShadowCasterSphereQuery->setSphere(s); - - // Determine if light is inside or outside the frustum - bool lightInFrustum = camera->isVisible(light->getDerivedPosition()); - const PlaneBoundedVolumeList* volList = 0; - if (!lightInFrustum) - { - // Only worth building an external volume list if - // light is outside the frustum - volList = &(light->_getFrustumClipVolumes(camera)); - } - - // Execute, use callback - mShadowCasterQueryListener->prepare(lightInFrustum, - volList, light, camera, &mShadowCasterList, light->getShadowFarDistanceSquared()); - mShadowCasterSphereQuery->execute(mShadowCasterQueryListener.get()); - - } - - } - - - return mShadowCasterList; -} -//--------------------------------------------------------------------- -void SceneManager::ShadowRenderer::fireShadowTexturesUpdated(size_t numberOfShadowTextures) -{ - ListenerList listenersCopy = mListeners; - - for (auto *l : listenersCopy) - { - l->shadowTexturesUpdated(numberOfShadowTextures); - } -} -//--------------------------------------------------------------------- -void SceneManager::ShadowRenderer::fireShadowTexturesPreCaster(Light* light, Camera* camera, size_t iteration) -{ - auto listenersCopy = mListeners; - for (auto l : listenersCopy) - { - l->shadowTextureCasterPreViewProj(light, camera, iteration); - } -} -//--------------------------------------------------------------------- -void SceneManager::ShadowRenderer::fireShadowTexturesPreReceiver(Light* light, Frustum* f) -{ - ListenerList listenersCopy = mListeners; - for (auto *l : listenersCopy) - { - l->shadowTextureReceiverPreViewProj(light, f); - } -} - -namespace -{ -/** Default sorting routine which sorts lights which cast shadows -to the front of a list, sub-sorting by distance. - -Since shadow textures are generated from lights based on the -frustum rather than individual objects, a shadow and camera-wise sort is -required to pick the best lights near the start of the list. Up to -the number of shadow textures will be generated from this. -*/ -struct lightsForShadowTextureLess -{ - bool operator()(const Light* l1, const Light* l2) const - { - if (l1 == l2) - return false; - - // sort shadow casting lights ahead of non-shadow casting - if (l1->getCastShadows() != l2->getCastShadows()) - { - return l1->getCastShadows(); - } - - // otherwise sort by distance (directional lights will have 0 here) - return l1->tempSquareDist < l2->tempSquareDist; - } -}; -} // namespace - -void SceneManager::ShadowRenderer::sortLightsAffectingFrustum(LightList& lightList) const -{ - if ((mShadowTechnique & SHADOWDETAILTYPE_TEXTURE) == 0) - return; - // Sort the lights if using texture shadows, since the first 'n' will be - // used to generate shadow textures and we should pick the most appropriate - - ListenerList listenersCopy = mListeners; // copy in case of listeners removing themselves - - // Allow a Listener to override light sorting - // Reverse iterate so last takes precedence - for (auto ri = listenersCopy.rbegin(); ri != listenersCopy.rend(); ++ri) - { - if((*ri)->sortLightsAffectingFrustum(lightList)) - return; - } - - // default sort (stable to preserve directional light ordering - std::stable_sort(lightList.begin(), lightList.end(), lightsForShadowTextureLess()); -} -} diff --git a/OgreMain/src/OgreShadowTextureManager.cpp b/OgreMain/src/OgreShadowTextureManager.cpp deleted file mode 100644 index e2db85bf78a..00000000000 --- a/OgreMain/src/OgreShadowTextureManager.cpp +++ /dev/null @@ -1,205 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE - -You may alternatively use this source under the terms of a specific version of -the OGRE Unrestricted License provided you have obtained such a license from -Torus Knot Software Ltd. --------------------------------------------------------------------------*/ -#include "OgreStableHeaders.h" -#include "OgreHardwarePixelBuffer.h" - -namespace Ogre -{ - //----------------------------------------------------------------------- - bool operator== ( const ShadowTextureConfig& lhs, const ShadowTextureConfig& rhs ) - { - if ( lhs.width != rhs.width || - lhs.height != rhs.height || - lhs.format != rhs.format ) - { - return false; - } - - return true; - } - //----------------------------------------------------------------------- - bool operator!= ( const ShadowTextureConfig& lhs, const ShadowTextureConfig& rhs ) - { - return !( lhs == rhs ); - } - //----------------------------------------------------------------------- - template<> ShadowTextureManager* Singleton::msSingleton = 0; - ShadowTextureManager* ShadowTextureManager::getSingletonPtr(void) - { - return msSingleton; - } - ShadowTextureManager& ShadowTextureManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //--------------------------------------------------------------------- - ShadowTextureManager::ShadowTextureManager() - : mCount(0) - { - - } - //--------------------------------------------------------------------- - ShadowTextureManager::~ShadowTextureManager() - { - clear(); - } - //--------------------------------------------------------------------- - void ShadowTextureManager::getShadowTextures(ShadowTextureConfigList& configList, - ShadowTextureList& listToPopulate) - { - listToPopulate.clear(); - - std::set usedTextures; - - for (ShadowTextureConfig& config : configList) - { - bool found = false; - for (auto & tex : mTextureList) - { - // Skip if already used this one - if (usedTextures.find(tex.get()) != usedTextures.end()) - continue; - - if (config.width == tex->getWidth() && config.height == tex->getHeight() - && config.format == tex->getFormat() && config.fsaa == tex->getFSAA()) - { - // Ok, a match - listToPopulate.push_back(tex); - usedTextures.insert(tex.get()); - found = true; - break; - } - } - if (!found) - { - // Create a new texture - static const String baseName = "Ogre/ShadowTexture"; - String targName = baseName + StringConverter::toString(mCount++); - TexturePtr shadowTex = TextureManager::getSingleton().createManual( - targName, - ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, - TEX_TYPE_2D, config.width, config.height, 0, config.format, - TU_RENDERTARGET, NULL, false, config.fsaa); - // Ensure texture loaded - shadowTex->load(); - - // update with actual format, if the requested format is not supported - config.format = shadowTex->getFormat(); - listToPopulate.push_back(shadowTex); - usedTextures.insert(shadowTex.get()); - mTextureList.push_back(shadowTex); - } - } - - } - //--------------------------------------------------------------------- - TexturePtr ShadowTextureManager::getNullShadowTexture(PixelFormat format) - { - for (auto & tex : mNullTextureList) - { - if (format == tex->getFormat()) - { - // Ok, a match - return tex; - } - } - - // not found, create a new one - // A 1x1 texture of the correct format, not a render target - static const String baseName = "Ogre/ShadowTextureNull"; - String targName = baseName + StringConverter::toString(mCount++); - TexturePtr shadowTex = TextureManager::getSingleton().createManual( - targName, - ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, - TEX_TYPE_2D, 1, 1, 0, format, TU_STATIC_WRITE_ONLY); - mNullTextureList.push_back(shadowTex); - - // lock & populate the texture based on format - if(PixelUtil::isDepth(format)) - return shadowTex; - - HardwareBufferLockGuard shadowTexLock(shadowTex->getBuffer(), HardwareBuffer::HBL_DISCARD); - const PixelBox& box = shadowTex->getBuffer()->getCurrentLock(); - - // set high-values across all bytes of the format - PixelUtil::packColour( 1.0f, 1.0f, 1.0f, 1.0f, shadowTex->getFormat(), box.data ); - - return shadowTex; - - } - //--------------------------------------------------------------------- - void ShadowTextureManager::clearUnused() - { - for (ShadowTextureList::iterator i = mTextureList.begin(); i != mTextureList.end(); ) - { - // Unreferenced if only this reference and the resource system - // Any cached shadow textures should be re-bound each frame dropping - // any old references - if ((*i).use_count() == ResourceGroupManager::RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS + 1) - { - TextureManager::getSingleton().remove((*i)->getHandle()); - i = mTextureList.erase(i); - } - else - { - ++i; - } - } - for (ShadowTextureList::iterator i = mNullTextureList.begin(); i != mNullTextureList.end(); ) - { - // Unreferenced if only this reference and the resource system - // Any cached shadow textures should be re-bound each frame dropping - // any old references - if ((*i).use_count() == ResourceGroupManager::RESOURCE_SYSTEM_NUM_REFERENCE_COUNTS + 1) - { - TextureManager::getSingleton().remove((*i)->getHandle()); - i = mNullTextureList.erase(i); - } - else - { - ++i; - } - } - - } - //--------------------------------------------------------------------- - void ShadowTextureManager::clear() - { - for (auto & i : mTextureList) - { - TextureManager::getSingleton().remove(i->getHandle()); - } - mTextureList.clear(); - - } - //--------------------------------------------------------------------- - -} - diff --git a/OgreMain/src/OgreShadowTextureManager.h b/OgreMain/src/OgreShadowTextureManager.h deleted file mode 100644 index 327648539f5..00000000000 --- a/OgreMain/src/OgreShadowTextureManager.h +++ /dev/null @@ -1,103 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) - -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE - -You may alternatively use this source under the terms of a specific version of -the OGRE Unrestricted License provided you have obtained such a license from -Torus Knot Software Ltd. --------------------------------------------------------------------------*/ -#ifndef __ShadowTextureManager_H__ -#define __ShadowTextureManager_H__ - -// Precompiler options -#include "OgrePrerequisites.h" -#include "OgreSingleton.h" -#include "OgrePixelFormat.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - - /** Class to manage the available shadow textures which may be shared between - many SceneManager instances if formats agree. - - The management of the list of shadow textures has been separated out into - a dedicated class to enable the clean management of shadow textures - across many scene manager instances. Where multiple scene managers are - used with shadow textures, the configuration of those shadows may or may - not be consistent - if it is, it is good to centrally manage the textures - so that creation and destruction responsibility is clear. - */ - class ShadowTextureManager : public Singleton, public ShadowDataAlloc - { - protected: - ShadowTextureList mTextureList; - ShadowTextureList mNullTextureList; - size_t mCount; - - public: - ShadowTextureManager(); - virtual ~ShadowTextureManager(); - - /** Populate an incoming list with shadow texture references as requested - in the configuration list. - */ - virtual void getShadowTextures(ShadowTextureConfigList& config, - ShadowTextureList& listToPopulate); - - /** Get an appropriately defined 'null' texture, i.e. one which will always - result in no shadows. - */ - virtual TexturePtr getNullShadowTexture(PixelFormat format); - - /** Remove any shadow textures that are no longer being referenced. - - This should be called fairly regularly since references may take a - little while to disappear in some cases (if referenced by materials) - */ - virtual void clearUnused(); - /** Dereference all the shadow textures kept in this class and remove them - from TextureManager; note that it is up to the SceneManagers to clear - their local references. - */ - void clear(); - - /// @copydoc Singleton::getSingleton() - static ShadowTextureManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static ShadowTextureManager* getSingletonPtr(void); - - }; - - /** @} */ - /** @} */ -} - -#endif - diff --git a/OgreMain/src/OgreShadowVolumeExtrudeProgram.cpp b/OgreMain/src/OgreShadowVolumeExtrudeProgram.cpp deleted file mode 100644 index 90900854c16..00000000000 --- a/OgreMain/src/OgreShadowVolumeExtrudeProgram.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreStableHeaders.h" -#include "OgreShadowVolumeExtrudeProgram.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreHighLevelGpuProgram.h" - -namespace { - enum Programs - { - // Point light extruder, infinite distance - POINT_LIGHT = 0, - // Directional light extruder, infinite distance - DIRECTIONAL_LIGHT, - // Point light extruder, finite distance - POINT_LIGHT_FINITE, - // Directional light extruder, finite distance - DIRECTIONAL_LIGHT_FINITE, - NUM_SHADOW_EXTRUDER_PROGRAMS - }; - - const char* programNames[NUM_SHADOW_EXTRUDER_PROGRAMS] = - { - "Ogre/ShadowExtrudePointLight", - "Ogre/ShadowExtrudeDirLight", - "Ogre/ShadowExtrudePointLightFinite", - "Ogre/ShadowExtrudeDirLightFinite" - }; -} - -namespace Ogre { - std::vector ShadowVolumeExtrudeProgram::mPrograms; - - void ShadowVolumeExtrudeProgram::initialise(void) - { - mPrograms.clear(); - - // load all programs - for (auto name : programNames) - { - auto vp = HighLevelGpuProgramManager::getSingleton().getByName(name, RGN_INTERNAL); - if (!vp) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - String(name) + " not found. Verify that you referenced the 'Media/Main' " - "folder in your resources.cfg"); - vp->load(); - mPrograms.push_back(vp); - } - } - //--------------------------------------------------------------------- - void ShadowVolumeExtrudeProgram::shutdown(void) - { - mPrograms.clear(); - } - //--------------------------------------------------------------------- - const GpuProgramPtr& ShadowVolumeExtrudeProgram::get(Light::LightTypes lightType, bool finite) - { - if (lightType == Light::LT_DIRECTIONAL) - { - return mPrograms[finite ? DIRECTIONAL_LIGHT_FINITE : DIRECTIONAL_LIGHT]; - } - else - { - return mPrograms[finite ? POINT_LIGHT_FINITE : POINT_LIGHT]; - } - } - -} diff --git a/OgreMain/src/OgreShadowVolumeExtrudeProgram.h b/OgreMain/src/OgreShadowVolumeExtrudeProgram.h deleted file mode 100644 index 502de8d3f92..00000000000 --- a/OgreMain/src/OgreShadowVolumeExtrudeProgram.h +++ /dev/null @@ -1,47 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __SHADOWVOLUMEEXTRUDEPROGRAM_H__ -#define __SHADOWVOLUMEEXTRUDEPROGRAM_H__ - -namespace Ogre { - class ShadowVolumeExtrudeProgram : public ShadowDataAlloc - { - private: - static std::vector mPrograms; - public: - /// Initialise the these vertex programs - static void initialise(void); - /// Shutdown & destroy the vertex programs - static void shutdown(void); - - static const GpuProgramPtr& get(Light::LightTypes lightType, bool finite); - }; -} - -#endif diff --git a/OgreMain/src/OgreSimpleRenderable.cpp b/OgreMain/src/OgreSimpleRenderable.cpp deleted file mode 100644 index 53c7f06d021..00000000000 --- a/OgreMain/src/OgreSimpleRenderable.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreRenderQueue.h" - -namespace Ogre { - - const String MOT_SIMPLE_RENDERABLE = "SimpleRenderable"; - - uint SimpleRenderable::msGenNameCount = 0; - - SimpleRenderable::SimpleRenderable() : SimpleRenderable(BLANKSTRING) - { - // Generate name - mName = StringUtil::format("SimpleRenderable%d", msGenNameCount++); - } - - SimpleRenderable::SimpleRenderable(const String& name) - : MovableObject(name) - , mTransform(Affine3::IDENTITY) - , mMaterial(MaterialManager::getSingleton().getDefaultMaterial()) - , mCamera(NULL) - { - } - - void SimpleRenderable::setMaterial( const MaterialPtr& mat ) - { - mMaterial = mat; - // Won't load twice anyway - mMaterial->load(); - } - - const MaterialPtr& SimpleRenderable::getMaterial(void) const - { - return mMaterial; - } - - void SimpleRenderable::getRenderOperation(RenderOperation& op) - { - op = mRenderOp; - } - - void SimpleRenderable::setRenderOperation( const RenderOperation& rend ) - { - mRenderOp = rend; - } - - void SimpleRenderable::setTransform( const Affine3& xform ) - { - mTransform = xform; - } - - void SimpleRenderable::getWorldTransforms( Matrix4* xform ) const - { - *xform = mParentNode->_getFullTransform() * mTransform; - } - - void SimpleRenderable::_notifyCurrentCamera(Camera* cam) - { - MovableObject::_notifyCurrentCamera(cam); - - mCamera = cam; - } - - void SimpleRenderable::setBoundingBox( const AxisAlignedBox& box ) - { - mBox = box; - } - - const AxisAlignedBox& SimpleRenderable::getBoundingBox(void) const - { - return mBox; - } - - void SimpleRenderable::_updateRenderQueue(RenderQueue* queue) - { - queue->addRenderable( this, mRenderQueueID, mRenderQueuePriority); - } - - void SimpleRenderable::visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables) - { - visitor->visit(this, 0, false); - } - - //----------------------------------------------------------------------- - const String& SimpleRenderable::getMovableType(void) const - { - return MOT_SIMPLE_RENDERABLE; - } - //----------------------------------------------------------------------- - const LightList& SimpleRenderable::getLights(void) const - { - // Use movable query lights - return queryLights(); - } - -} diff --git a/OgreMain/src/OgreSimpleSpline.cpp b/OgreMain/src/OgreSimpleSpline.cpp deleted file mode 100644 index efecf315f36..00000000000 --- a/OgreMain/src/OgreSimpleSpline.cpp +++ /dev/null @@ -1,265 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -namespace Ogre { - - //--------------------------------------------------------------------- - SimpleSpline::SimpleSpline() - { - // Set up matrix - // Hermite polynomial - mCoeffs[0][0] = 2; - mCoeffs[0][1] = -2; - mCoeffs[0][2] = 1; - mCoeffs[0][3] = 1; - mCoeffs[1][0] = -3; - mCoeffs[1][1] = 3; - mCoeffs[1][2] = -2; - mCoeffs[1][3] = -1; - mCoeffs[2][0] = 0; - mCoeffs[2][1] = 0; - mCoeffs[2][2] = 1; - mCoeffs[2][3] = 0; - mCoeffs[3][0] = 1; - mCoeffs[3][1] = 0; - mCoeffs[3][2] = 0; - mCoeffs[3][3] = 0; - - mAutoCalc = true; - } - //--------------------------------------------------------------------- - SimpleSpline::~SimpleSpline() - { - } - //--------------------------------------------------------------------- - void SimpleSpline::addPoint(const Vector3& p) - { - mPoints.push_back(p); - if (mAutoCalc) - { - recalcTangents(); - } - } - //--------------------------------------------------------------------- - Vector3 SimpleSpline::interpolate(Real t) const - { - // Currently assumes points are evenly spaced, will cause velocity - // change where this is not the case - // TODO: base on arclength? - - - // Work out which segment this is in - Real fSeg = t * (mPoints.size() - 1); - unsigned int segIdx = (unsigned int)fSeg; - // Apportion t - t = fSeg - segIdx; - - return interpolate(segIdx, t); - - } - //--------------------------------------------------------------------- - Vector3 SimpleSpline::interpolate(unsigned int fromIndex, Real t) const - { - // Bounds check - assert (fromIndex < mPoints.size() && - "fromIndex out of bounds"); - - if ((fromIndex + 1) == mPoints.size()) - { - // Duff request, cannot blend to nothing - // Just return source - return mPoints[fromIndex]; - - } - - // Fast special cases - if (t == 0.0f) - { - return mPoints[fromIndex]; - } - else if(t == 1.0f) - { - return mPoints[fromIndex + 1]; - } - - // Real interpolation - // Form a vector of powers of t - Real t2, t3; - t2 = t * t; - t3 = t2 * t; - Vector4 powers(t3, t2, t, 1); - - - // Algorithm is ret = powers * mCoeffs * Matrix4(point1, point2, tangent1, tangent2) - const Vector3& point1 = mPoints[fromIndex]; - const Vector3& point2 = mPoints[fromIndex+1]; - const Vector3& tan1 = mTangents[fromIndex]; - const Vector3& tan2 = mTangents[fromIndex+1]; - Matrix4 pt; - - pt[0][0] = point1.x; - pt[0][1] = point1.y; - pt[0][2] = point1.z; - pt[0][3] = 1.0f; - pt[1][0] = point2.x; - pt[1][1] = point2.y; - pt[1][2] = point2.z; - pt[1][3] = 1.0f; - pt[2][0] = tan1.x; - pt[2][1] = tan1.y; - pt[2][2] = tan1.z; - pt[2][3] = 1.0f; - pt[3][0] = tan2.x; - pt[3][1] = tan2.y; - pt[3][2] = tan2.z; - pt[3][3] = 1.0f; - - Vector4 ret = powers * mCoeffs * pt; - - - return Vector3(ret.x, ret.y, ret.z); - - - - - } - //--------------------------------------------------------------------- - void SimpleSpline::recalcTangents(void) - { - // Catmull-Rom approach - // - // tangent[i] = 0.5 * (point[i+1] - point[i-1]) - // - // Assume endpoint tangents are parallel with line with neighbour - - size_t i, numPoints; - bool isClosed; - - numPoints = mPoints.size(); - if (numPoints < 2) - { - // Can't do anything yet - return; - } - - // Closed or open? - if (mPoints[0] == mPoints[numPoints-1]) - { - isClosed = true; - } - else - { - isClosed = false; - } - - mTangents.resize(numPoints); - - - - for(i = 0; i < numPoints; ++i) - { - if (i ==0) - { - // Special case start - if (isClosed) - { - // Use numPoints-2 since numPoints-1 is the last point and == [0] - mTangents[i] = 0.5 * (mPoints[1] - mPoints[numPoints-2]); - } - else - { - mTangents[i] = 0.5 * (mPoints[1] - mPoints[0]); - } - } - else if (i == numPoints-1) - { - // Special case end - if (isClosed) - { - // Use same tangent as already calculated for [0] - mTangents[i] = mTangents[0]; - } - else - { - mTangents[i] = 0.5 * (mPoints[i] - mPoints[i-1]); - } - } - else - { - mTangents[i] = 0.5 * (mPoints[i+1] - mPoints[i-1]); - } - - } - - - - } - //--------------------------------------------------------------------- - const Vector3& SimpleSpline::getPoint(unsigned short index) const - { - assert (index < mPoints.size() && "Point index is out of bounds!!"); - - return mPoints[index]; - } - //--------------------------------------------------------------------- - unsigned short SimpleSpline::getNumPoints(void) const - { - return (unsigned short)mPoints.size(); - } - //--------------------------------------------------------------------- - void SimpleSpline::clear(void) - { - mPoints.clear(); - mTangents.clear(); - } - //--------------------------------------------------------------------- - void SimpleSpline::updatePoint(unsigned short index, const Vector3& value) - { - assert (index < mPoints.size() && "Point index is out of bounds!!"); - - mPoints[index] = value; - if (mAutoCalc) - { - recalcTangents(); - } - } - //--------------------------------------------------------------------- - void SimpleSpline::setAutoCalculate(bool autoCalc) - { - mAutoCalc = autoCalc; - } - - - - -} - - - - diff --git a/OgreMain/src/OgreSkeleton.cpp b/OgreMain/src/OgreSkeleton.cpp deleted file mode 100644 index cdd7a1924de..00000000000 --- a/OgreMain/src/OgreSkeleton.cpp +++ /dev/null @@ -1,971 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreAnimationState.h" -#include "OgreSkeletonManager.h" -#include "OgreSkeletonSerializer.h" -// Just for logging -#include "OgreAnimationTrack.h" -#include "OgreKeyFrame.h" - - -namespace Ogre { - - //--------------------------------------------------------------------- - Skeleton::Skeleton() - : Resource(), - mNextAutoHandle(0), - mBlendState(ANIMBLEND_AVERAGE), - mManualBonesDirty(false) - { - } - //--------------------------------------------------------------------- - Skeleton::Skeleton(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - : Resource(creator, name, handle, group, isManual, loader), - mNextAutoHandle(0), mBlendState(ANIMBLEND_AVERAGE) - // set animation blending to weighted, not cumulative - { - if (createParamDictionary("Skeleton")) - { - // no custom params - } - } - //--------------------------------------------------------------------- - Skeleton::~Skeleton() - { - // have to call this here reather than in Resource destructor - // since calling virtual methods in base destructors causes crash - unload(); - } - //--------------------------------------------------------------------- - void Skeleton::prepareImpl(void) - { - SkeletonSerializer serializer; - - if (getCreator()->getVerbose()) - LogManager::getSingleton().stream() << "Skeleton: Loading " << mName; - - DataStreamPtr stream = ResourceGroupManager::getSingleton().openResource(mName, mGroup, this); - - serializer.importSkeleton(stream, this); - - // Load any linked skeletons - for (auto& s : mLinkedSkeletonAnimSourceList) - { - s.pSkeleton = static_pointer_cast( - SkeletonManager::getSingleton().prepare(s.skeletonName, mGroup)); - } - } - //--------------------------------------------------------------------- - void Skeleton::unprepareImpl(void) - { - // destroy bones - for (auto *b : mBoneList) - { - OGRE_DELETE b; - } - mBoneList.clear(); - mBoneListByName.clear(); - mRootBones.clear(); - mManualBones.clear(); - mManualBonesDirty = false; - - // Destroy animations - for (auto& ai : mAnimationsList) - { - OGRE_DELETE ai.second; - } - mAnimationsList.clear(); - - // Remove all linked skeletons - mLinkedSkeletonAnimSourceList.clear(); - } - //--------------------------------------------------------------------- - Bone* Skeleton::createBone(void) - { - // use autohandle - return createBone(mNextAutoHandle++); - } - //--------------------------------------------------------------------- - Bone* Skeleton::createBone(const String& name) - { - return createBone(name, mNextAutoHandle++); - } - //--------------------------------------------------------------------- - Bone* Skeleton::createBone(unsigned short handle) - { - OgreAssert(handle < OGRE_MAX_NUM_BONES, "Exceeded the maximum number of bones per skeleton"); - // Check handle not used - if (handle < mBoneList.size() && mBoneList[handle] != NULL) - { - OGRE_EXCEPT( - Exception::ERR_DUPLICATE_ITEM, - "A bone with the handle " + StringConverter::toString(handle) + " already exists", - "Skeleton::createBone" ); - } - Bone* ret = OGRE_NEW Bone(handle, this); - assert(mBoneListByName.find(ret->getName()) == mBoneListByName.end()); - if (mBoneList.size() <= handle) - { - mBoneList.resize(handle+1); - } - mBoneList[handle] = ret; - mBoneListByName[ret->getName()] = ret; - return ret; - - } - //--------------------------------------------------------------------- - Bone* Skeleton::createBone(const String& name, unsigned short handle) - { - OgreAssert(handle < OGRE_MAX_NUM_BONES, "Exceeded the maximum number of bones per skeleton"); - // Check handle not used - if (handle < mBoneList.size() && mBoneList[handle] != NULL) - { - OGRE_EXCEPT( - Exception::ERR_DUPLICATE_ITEM, - "A bone with the handle " + StringConverter::toString(handle) + " already exists", - "Skeleton::createBone" ); - } - // Check name not used - if (mBoneListByName.find(name) != mBoneListByName.end()) - { - OGRE_EXCEPT( - Exception::ERR_DUPLICATE_ITEM, - "A bone with the name " + name + " already exists", - "Skeleton::createBone" ); - } - Bone* ret = OGRE_NEW Bone(name, handle, this); - if (mBoneList.size() <= handle) - { - mBoneList.resize(handle+1); - } - mBoneList[handle] = ret; - mBoneListByName[name] = ret; - return ret; - } - - const Skeleton::BoneList& Skeleton::getRootBones() const { - if (mRootBones.empty()) - { - deriveRootBone(); - } - - return mRootBones; - } - - //--------------------------------------------------------------------- - void Skeleton::setAnimationState(const AnimationStateSet& animSet) - { - /* - Algorithm: - 1. Reset all bone positions - 2. Iterate per AnimationState, if enabled get Animation and call Animation::apply - */ - - // Reset bones - reset(); - - Real weightFactor = 1.0f; - if (mBlendState == ANIMBLEND_AVERAGE) - { - // Derive total weights so we can rebalance if > 1.0f - Real totalWeights = 0.0f; - EnabledAnimationStateList::const_iterator animIt; - for(animIt = animSet.getEnabledAnimationStates().begin(); animIt != animSet.getEnabledAnimationStates().end(); ++animIt) - { - const AnimationState* animState = *animIt; - // Make sure we have an anim to match implementation - const LinkedSkeletonAnimationSource* linked = 0; - if (_getAnimationImpl(animState->getAnimationName(), &linked)) - { - totalWeights += animState->getWeight(); - } - } - - // Allow < 1.0f, allows fade out of all anims if required - if (totalWeights > 1.0f) - { - weightFactor = 1.0f / totalWeights; - } - } - - // Per enabled animation state - for(auto *animState : animSet.getEnabledAnimationStates()) - { - const LinkedSkeletonAnimationSource* linked = 0; - Animation* anim = _getAnimationImpl(animState->getAnimationName(), &linked); - // tolerate state entries for animations we're not aware of - if (anim) - { - if(animState->hasBlendMask()) - { - anim->apply(this, animState->getTimePosition(), animState->getWeight() * weightFactor, - animState->getBlendMask(), linked ? linked->scale : 1.0f); - } - else - { - anim->apply(this, animState->getTimePosition(), - animState->getWeight() * weightFactor, linked ? linked->scale : 1.0f); - } - } - } - - - } - //--------------------------------------------------------------------- - void Skeleton::setBindingPose(void) - { - // Update the derived transforms - _updateTransforms(); - - for (auto *b : mBoneList) - { - b->setBindingPose(); - } - } - //--------------------------------------------------------------------- - void Skeleton::reset(bool resetManualBones) - { - for (auto *b : mBoneList) - { - if(!b->isManuallyControlled() || resetManualBones) - b->reset(); - } - } - //--------------------------------------------------------------------- - Animation* Skeleton::createAnimation(const String& name, Real length) - { - // Check name not used - if (mAnimationsList.find(name) != mAnimationsList.end()) - { - OGRE_EXCEPT( - Exception::ERR_DUPLICATE_ITEM, - "An animation with the name " + name + " already exists", - "Skeleton::createAnimation"); - } - - Animation* ret = OGRE_NEW Animation(name, length); - ret->_notifyContainer(this); - - // Add to list - mAnimationsList[name] = ret; - - return ret; - - } - //--------------------------------------------------------------------- - Animation* Skeleton::getAnimation(const String& name, - const LinkedSkeletonAnimationSource** linker) const - { - Animation* ret = _getAnimationImpl(name, linker); - if (!ret) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "No animation entry found named " + name, - "Skeleton::getAnimation"); - } - - return ret; - } - //--------------------------------------------------------------------- - Animation* Skeleton::getAnimation(const String& name) const - { - return getAnimation(name, 0); - } - //--------------------------------------------------------------------- - bool Skeleton::hasAnimation(const String& name) const - { - return _getAnimationImpl(name) != 0; - } - //--------------------------------------------------------------------- - Animation* Skeleton::_getAnimationImpl(const String& name, - const LinkedSkeletonAnimationSource** linker) const - { - Animation* ret = 0; - AnimationList::const_iterator i = mAnimationsList.find(name); - - if (i == mAnimationsList.end()) - { - LinkedSkeletonAnimSourceList::const_iterator it; - for (it = mLinkedSkeletonAnimSourceList.begin(); - it != mLinkedSkeletonAnimSourceList.end() && !ret; ++it) - { - if (it->pSkeleton) - { - ret = it->pSkeleton->_getAnimationImpl(name); - if (ret && linker) - { - *linker = &(*it); - } - - } - } - - } - else - { - if (linker) - *linker = 0; - ret = i->second; - } - - return ret; - - } - //--------------------------------------------------------------------- - void Skeleton::removeAnimation(const String& name) - { - AnimationList::iterator i = mAnimationsList.find(name); - - if (i == mAnimationsList.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "No animation entry found named " + name, - "Skeleton::getAnimation"); - } - - OGRE_DELETE i->second; - - mAnimationsList.erase(i); - - } - //----------------------------------------------------------------------- - void Skeleton::_initAnimationState(AnimationStateSet* animSet) - { - animSet->removeAllAnimationStates(); - - for (auto& a : mAnimationsList) - { - Animation* anim = a.second; - // Create animation at time index 0, default params mean this has weight 1 and is disabled - const String& animName = anim->getName(); - animSet->createAnimationState(animName, 0.0, anim->getLength()); - } - - // Also iterate over linked animation - for (auto& li : mLinkedSkeletonAnimSourceList) - { - if (li.pSkeleton) - { - li.pSkeleton->_refreshAnimationState(animSet); - } - } - } - //----------------------------------------------------------------------- - void Skeleton::_refreshAnimationState(AnimationStateSet* animSet) - { - // Merge in any new animations - for (auto& a : mAnimationsList) - { - Animation* anim = a.second; - // Create animation at time index 0, default params mean this has weight 1 and is disabled - const String& animName = anim->getName(); - if (!animSet->hasAnimationState(animName)) - { - animSet->createAnimationState(animName, 0.0, anim->getLength()); - } - else - { - // Update length incase changed - AnimationState* animState = animSet->getAnimationState(animName); - animState->setLength(anim->getLength()); - animState->setTimePosition(std::min(anim->getLength(), animState->getTimePosition())); - } - } - // Also iterate over linked animation - for (auto& li : mLinkedSkeletonAnimSourceList) - { - if (li.pSkeleton) - { - li.pSkeleton->_refreshAnimationState(animSet); - } - } - } - //----------------------------------------------------------------------- - void Skeleton::_notifyManualBonesDirty(void) - { - mManualBonesDirty = true; - } - //----------------------------------------------------------------------- - void Skeleton::_notifyManualBoneStateChange(Bone* bone) - { - if (bone->isManuallyControlled()) - mManualBones.insert(bone); - else - mManualBones.erase(bone); - } - //----------------------------------------------------------------------- - unsigned short Skeleton::getNumBones(void) const - { - return (unsigned short)mBoneList.size(); - } - //----------------------------------------------------------------------- - void Skeleton::_getBoneMatrices(Affine3* pMatrices) - { - // Update derived transforms - _updateTransforms(); - - /* - Calculating the bone matrices - ----------------------------- - Now that we have the derived scaling factors, orientations & positions in the - Bone nodes, we have to compute the Matrix4 to apply to the vertices of a mesh. - Because any modification of a vertex has to be relative to the bone, we must - first reverse transform by the Bone's original derived position/orientation/scale, - then transform by the new derived position/orientation/scale. - Also note we combine scale as equivalent axes, no shearing. - */ - - for (auto *b : mBoneList) - { - b->_getOffsetTransform(*pMatrices); - pMatrices++; - } - - } - //--------------------------------------------------------------------- - unsigned short Skeleton::getNumAnimations(void) const - { - return (unsigned short)mAnimationsList.size(); - } - //--------------------------------------------------------------------- - Animation* Skeleton::getAnimation(unsigned short index) const - { - // If you hit this assert, then the index is out of bounds. - assert( index < mAnimationsList.size() ); - - AnimationList::const_iterator i = mAnimationsList.begin(); - - std::advance(i, index); - - return i->second; - } - //--------------------------------------------------------------------- - Bone* Skeleton::getBone(unsigned short handle) const - { - assert(handle < mBoneList.size() && "Index out of bounds"); - return mBoneList[handle]; - } - //--------------------------------------------------------------------- - Bone* Skeleton::getBone(const String& name) const - { - BoneListByName::const_iterator i = mBoneListByName.find(name); - - if (i == mBoneListByName.end()) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Bone named '" + name + "' not found.", - "Skeleton::getBone"); - } - - return i->second; - - } - //--------------------------------------------------------------------- - bool Skeleton::hasBone(const String& name) const - { - return mBoneListByName.find(name) != mBoneListByName.end(); - } - //--------------------------------------------------------------------- - void Skeleton::deriveRootBone(void) const - { - // Start at the first bone and work up - OgreAssert(!mBoneList.empty(), "Cannot derive root bone as this skeleton has no bones"); - - mRootBones.clear(); - - for (auto *b : mBoneList) - { - if (b->getParent() == 0) - { - // This is a root - mRootBones.push_back(b); - } - } - } - //--------------------------------------------------------------------- - std::ostream& operator<<(std::ostream& o, const Skeleton& s) - { - Quaternion q; - Radian angle; - Vector3 axis; - - o << "-= Debug output of skeleton " << s.mName << " =-" << std::endl << std::endl; - o << "== Bones ==" << std::endl; - o << "Number of bones: " << (unsigned int)s.mBoneList.size() << std::endl; - - for (auto *b : s.mBoneList) - { - o << "-- Bone " << b->getHandle() << " --" << std::endl; - o << "Position: " << b->getPosition(); - q = b->getOrientation(); - o << "Rotation: " << q; - q.ToAngleAxis(angle, axis); - o << " = " << angle.valueRadians() << " radians around axis " << axis << std::endl << std::endl; - } - - o << "== Animations ==" << std::endl; - o << "Number of animations: " << (unsigned int)s.mAnimationsList.size() << std::endl; - - for (auto& a : s.mAnimationsList) - { - Animation* anim = a.second; - - o << "-- Animation '" << anim->getName() << "' (length " << anim->getLength() << ") --" << std::endl; - o << "Number of tracks: " << anim->getNumNodeTracks() << std::endl; - - for (unsigned short ti = 0; ti < anim->getNumNodeTracks(); ++ti) - { - NodeAnimationTrack* track = anim->getNodeTrack(ti); - o << " -- AnimationTrack " << ti << " --" << std::endl; - o << " Affects bone: " << static_cast(track->getAssociatedNode())->getHandle() << std::endl; - o << " Number of keyframes: " << track->getNumKeyFrames() << std::endl; - - for (unsigned short ki = 0; ki < track->getNumKeyFrames(); ++ki) - { - TransformKeyFrame* key = track->getNodeKeyFrame(ki); - o << " -- KeyFrame " << ki << " --" << std::endl; - o << " Time index: " << key->getTime(); - o << " Translation: " << key->getTranslate() << std::endl; - q = key->getRotation(); - o << " Rotation: " << q; - q.ToAngleAxis(angle, axis); - o << " = " << angle.valueRadians() << " radians around axis " << axis << std::endl; - } - - } - } - return o; - } - //--------------------------------------------------------------------- - SkeletonAnimationBlendMode Skeleton::getBlendMode() const - { - return mBlendState; - } - //--------------------------------------------------------------------- - void Skeleton::setBlendMode(SkeletonAnimationBlendMode state) - { - mBlendState = state; - } - //--------------------------------------------------------------------- - Skeleton::BoneIterator Skeleton::getRootBoneIterator(void) - { - if (mRootBones.empty()) - { - deriveRootBone(); - } - return BoneIterator(mRootBones.begin(), mRootBones.end()); - } - //--------------------------------------------------------------------- - Skeleton::BoneIterator Skeleton::getBoneIterator(void) - { - return BoneIterator(mBoneList.begin(), mBoneList.end()); - } - //--------------------------------------------------------------------- - void Skeleton::_updateTransforms(void) - { - for (auto *b : mRootBones) - { - b->_update(true, false); - } - mManualBonesDirty = false; - } - //--------------------------------------------------------------------- - void Skeleton::optimiseAllAnimations(bool preservingIdentityNodeTracks) - { - if (!preservingIdentityNodeTracks) - { - Animation::TrackHandleList tracksToDestroy; - - // Assume all node tracks are identity - ushort numBones = getNumBones(); - for (ushort h = 0; h < numBones; ++h) - { - tracksToDestroy.insert(h); - } - - // Collect identity node tracks for all animations - for (auto& a : mAnimationsList) - { - a.second->_collectIdentityNodeTracks(tracksToDestroy); - } - - // Destroy identity node tracks - for (auto& a : mAnimationsList) - { - a.second->_destroyNodeTracks(tracksToDestroy); - } - } - - for (auto& a : mAnimationsList) - { - // Don't discard identity node tracks here - a.second->optimise(false); - } - } - //--------------------------------------------------------------------- - void Skeleton::addLinkedSkeletonAnimationSource(const String& skelName, - Real scale) - { - // Check not already linked - for (auto& l : mLinkedSkeletonAnimSourceList) - { - if (skelName == l.skeletonName) - return; // don't bother - } - - if (isPrepared() || isLoaded()) - { - // Load immediately - SkeletonPtr skelPtr = static_pointer_cast( - SkeletonManager::getSingleton().prepare(skelName, mGroup)); - mLinkedSkeletonAnimSourceList.push_back( - LinkedSkeletonAnimationSource(skelName, scale, skelPtr)); - - } - else - { - // Load later - mLinkedSkeletonAnimSourceList.push_back( - LinkedSkeletonAnimationSource(skelName, scale)); - } - - } - //--------------------------------------------------------------------- - void Skeleton::removeAllLinkedSkeletonAnimationSources(void) - { - mLinkedSkeletonAnimSourceList.clear(); - } - //--------------------------------------------------------------------- - Skeleton::LinkedSkeletonAnimSourceIterator - Skeleton::getLinkedSkeletonAnimationSourceIterator(void) const - { - return LinkedSkeletonAnimSourceIterator( - mLinkedSkeletonAnimSourceList.begin(), - mLinkedSkeletonAnimSourceList.end()); - } - //--------------------------------------------------------------------- - struct DeltaTransform - { - Vector3 translate; - Quaternion rotate; - Vector3 scale; - bool isIdentity; - }; - void Skeleton::_mergeSkeletonAnimations(const Skeleton* src, - const BoneHandleMap& boneHandleMap, - const StringVector& animations) - { - ushort handle; - - ushort numSrcBones = src->getNumBones(); - ushort numDstBones = this->getNumBones(); - - OgreAssert( - boneHandleMap.size() == numSrcBones, - "Number of bones in the bone handle map must equal to number of bones in the source skeleton"); - - bool existsMissingBone = false; - - // Check source skeleton structures compatible with ourself (that means - // identically bones with identical handles, and with same hierarchy, but - // not necessary to have same number of bones and bone names). - for (handle = 0; handle < numSrcBones; ++handle) - { - const Bone* srcBone = src->getBone(handle); - ushort dstHandle = boneHandleMap[handle]; - - // Does it exists in target skeleton? - if (dstHandle < numDstBones) - { - Bone* destBone = this->getBone(dstHandle); - - // Check both bones have identical parent, or both are root bone. - const Bone* srcParent = static_cast(srcBone->getParent()); - Bone* destParent = static_cast(destBone->getParent()); - if ((srcParent || destParent) && - (!srcParent || !destParent || - boneHandleMap[srcParent->getHandle()] != destParent->getHandle())) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Source skeleton incompatible with this skeleton: " - "difference hierarchy between bone '" + srcBone->getName() + - "' and '" + destBone->getName() + "'.", - "Skeleton::_mergeSkeletonAnimations"); - } - } - else - { - existsMissingBone = true; - } - } - - // Clone bones if need - if (existsMissingBone) - { - // Create missing bones - for (handle = 0; handle < numSrcBones; ++handle) - { - const Bone* srcBone = src->getBone(handle); - ushort dstHandle = boneHandleMap[handle]; - - // The bone is missing in target skeleton? - if (dstHandle >= numDstBones) - { - Bone* dstBone = this->createBone(srcBone->getName(), dstHandle); - // Sets initial transform - dstBone->setPosition(srcBone->getInitialPosition()); - dstBone->setOrientation(srcBone->getInitialOrientation()); - dstBone->setScale(srcBone->getInitialScale()); - dstBone->setInitialState(); - } - } - - // Link new bones to parent - for (handle = 0; handle < numSrcBones; ++handle) - { - const Bone* srcBone = src->getBone(handle); - ushort dstHandle = boneHandleMap[handle]; - - // Is new bone? - if (dstHandle >= numDstBones) - { - const Bone* srcParent = static_cast(srcBone->getParent()); - if (srcParent) - { - Bone* destParent = this->getBone(boneHandleMap[srcParent->getHandle()]); - Bone* dstBone = this->getBone(dstHandle); - destParent->addChild(dstBone); - } - } - } - - // Derive root bones in case it was changed - this->deriveRootBone(); - - // Reset binding pose for new bones - this->reset(true); - this->setBindingPose(); - } - - // - // We need to adapt animations from source to target skeleton, but since source - // and target skeleton bones bind transform might difference, so we need to alter - // keyframes in source to suit to target skeleton. - // - // For any given animation time, formula: - // - // LocalTransform = BindTransform * KeyFrame; - // DerivedTransform = ParentDerivedTransform * LocalTransform - // - // And all derived transforms should be keep identically after adapt to - // target skeleton, Then: - // - // DestDerivedTransform == SrcDerivedTransform - // DestParentDerivedTransform == SrcParentDerivedTransform - // ==> - // DestLocalTransform = SrcLocalTransform - // ==> - // DestBindTransform * DestKeyFrame = SrcBindTransform * SrcKeyFrame - // ==> - // DestKeyFrame = inverse(DestBindTransform) * SrcBindTransform * SrcKeyFrame - // - // We define (inverse(DestBindTransform) * SrcBindTransform) as 'delta-transform' here. - // - - // Calculate delta-transforms for all source bones. - std::vector deltaTransforms(numSrcBones); - for (handle = 0; handle < numSrcBones; ++handle) - { - const Bone* srcBone = src->getBone(handle); - DeltaTransform& deltaTransform = deltaTransforms[handle]; - ushort dstHandle = boneHandleMap[handle]; - - if (dstHandle < numDstBones) - { - // Common bone, calculate delta-transform - - Bone* dstBone = this->getBone(dstHandle); - - deltaTransform.translate = srcBone->getInitialPosition() - dstBone->getInitialPosition(); - deltaTransform.rotate = dstBone->getInitialOrientation().Inverse() * srcBone->getInitialOrientation(); - deltaTransform.scale = srcBone->getInitialScale() / dstBone->getInitialScale(); - - // Check whether or not delta-transform is identity - const Real tolerance = 1e-3f; - Vector3 axis; - Radian angle; - deltaTransform.rotate.ToAngleAxis(angle, axis); - deltaTransform.isIdentity = - deltaTransform.translate.positionEquals(Vector3::ZERO, tolerance) && - deltaTransform.scale.positionEquals(Vector3::UNIT_SCALE, tolerance) && - Math::RealEqual(angle.valueRadians(), 0.0f, tolerance); - } - else - { - // New bone, the delta-transform is identity - - deltaTransform.translate = Vector3::ZERO; - deltaTransform.rotate = Quaternion::IDENTITY; - deltaTransform.scale = Vector3::UNIT_SCALE; - deltaTransform.isIdentity = true; - } - } - - // Now copy animations - - ushort numAnimations; - if (animations.empty()) - numAnimations = src->getNumAnimations(); - else - numAnimations = static_cast(animations.size()); - for (ushort i = 0; i < numAnimations; ++i) - { - const Animation* srcAnimation; - if (animations.empty()) - { - // Get animation of source skeleton by the given index - srcAnimation = src->getAnimation(i); - } - else - { - // Get animation of source skeleton by the given name - const LinkedSkeletonAnimationSource* linker; - srcAnimation = src->_getAnimationImpl(animations[i], &linker); - if (!srcAnimation || linker) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "No animation entry found named " + animations[i], - "Skeleton::_mergeSkeletonAnimations"); - } - } - - // Create target animation - Animation* dstAnimation = this->createAnimation(srcAnimation->getName(), srcAnimation->getLength()); - - // Copy interpolation modes - dstAnimation->setInterpolationMode(srcAnimation->getInterpolationMode()); - dstAnimation->setRotationInterpolationMode(srcAnimation->getRotationInterpolationMode()); - - // Copy track for each bone - for (handle = 0; handle < numSrcBones; ++handle) - { - const DeltaTransform& deltaTransform = deltaTransforms[handle]; - ushort dstHandle = boneHandleMap[handle]; - - if (srcAnimation->hasNodeTrack(handle)) - { - // Clone track from source animation - - const NodeAnimationTrack* srcTrack = srcAnimation->getNodeTrack(handle); - NodeAnimationTrack* dstTrack = dstAnimation->createNodeTrack(dstHandle, this->getBone(dstHandle)); - dstTrack->setUseShortestRotationPath(srcTrack->getUseShortestRotationPath()); - - ushort numKeyFrames = srcTrack->getNumKeyFrames(); - for (ushort k = 0; k < numKeyFrames; ++k) - { - const TransformKeyFrame* srcKeyFrame = srcTrack->getNodeKeyFrame(k); - TransformKeyFrame* dstKeyFrame = dstTrack->createNodeKeyFrame(srcKeyFrame->getTime()); - - // Adjust keyframes to match target binding pose - if (deltaTransform.isIdentity) - { - dstKeyFrame->setTranslate(srcKeyFrame->getTranslate()); - dstKeyFrame->setRotation(srcKeyFrame->getRotation()); - dstKeyFrame->setScale(srcKeyFrame->getScale()); - } - else - { - dstKeyFrame->setTranslate(deltaTransform.translate + srcKeyFrame->getTranslate()); - dstKeyFrame->setRotation(deltaTransform.rotate * srcKeyFrame->getRotation()); - dstKeyFrame->setScale(deltaTransform.scale * srcKeyFrame->getScale()); - } - } - } - else if (!deltaTransform.isIdentity) - { - // Create 'static' track for this bone - - NodeAnimationTrack* dstTrack = dstAnimation->createNodeTrack(dstHandle, this->getBone(dstHandle)); - TransformKeyFrame* dstKeyFrame; - - dstKeyFrame = dstTrack->createNodeKeyFrame(0); - dstKeyFrame->setTranslate(deltaTransform.translate); - dstKeyFrame->setRotation(deltaTransform.rotate); - dstKeyFrame->setScale(deltaTransform.scale); - - dstKeyFrame = dstTrack->createNodeKeyFrame(dstAnimation->getLength()); - dstKeyFrame->setTranslate(deltaTransform.translate); - dstKeyFrame->setRotation(deltaTransform.rotate); - dstKeyFrame->setScale(deltaTransform.scale); - } - } - } - } - //--------------------------------------------------------------------- - void Skeleton::_buildMapBoneByHandle(const Skeleton* src, - BoneHandleMap& boneHandleMap) const - { - ushort numSrcBones = src->getNumBones(); - boneHandleMap.resize(numSrcBones); - - for (ushort handle = 0; handle < numSrcBones; ++handle) - { - boneHandleMap[handle] = handle; - } - } - //--------------------------------------------------------------------- - void Skeleton::_buildMapBoneByName(const Skeleton* src, - BoneHandleMap& boneHandleMap) const - { - ushort numSrcBones = src->getNumBones(); - boneHandleMap.resize(numSrcBones); - - ushort newBoneHandle = this->getNumBones(); - for (ushort handle = 0; handle < numSrcBones; ++handle) - { - const Bone* srcBone = src->getBone(handle); - BoneListByName::const_iterator i = this->mBoneListByName.find(srcBone->getName()); - if (i == mBoneListByName.end()) - boneHandleMap[handle] = newBoneHandle++; - else - boneHandleMap[handle] = i->second->getHandle(); - } - } - - size_t Skeleton::calculateSize(void) const - { - size_t memSize = sizeof(*this); - memSize += mBoneList.size() * sizeof(Bone); - memSize += mRootBones.size() * sizeof(Bone); - memSize += mBoneListByName.size() * (sizeof(String) + sizeof(Bone*)); - memSize += mAnimationsList.size() * (sizeof(String) + sizeof(Animation*)); - memSize += mManualBones.size() * sizeof(Bone*); - memSize += mLinkedSkeletonAnimSourceList.size() * sizeof(LinkedSkeletonAnimationSource); - - return memSize; - } -} diff --git a/OgreMain/src/OgreSkeletonInstance.cpp b/OgreMain/src/OgreSkeletonInstance.cpp deleted file mode 100644 index d75b3716641..00000000000 --- a/OgreMain/src/OgreSkeletonInstance.cpp +++ /dev/null @@ -1,251 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreSkeletonInstance.h" -#include "OgreTagPoint.h" - - -namespace Ogre { - //------------------------------------------------------------------------- - SkeletonInstance::SkeletonInstance(const SkeletonPtr& masterCopy) - : Skeleton() - , mSkeleton(masterCopy) - , mNextTagPointAutoHandle(0) - { - } - //------------------------------------------------------------------------- - SkeletonInstance::~SkeletonInstance() - { - // have to call this here rather than in Resource destructor - // since calling virtual methods in base destructors causes crash - // ...and calling it in Skeleton destructor does not unload - // SkeletonInstance since it has seized to be by then. - unload(); - } - //------------------------------------------------------------------------- - unsigned short SkeletonInstance::getNumAnimations(void) const - { - return mSkeleton->getNumAnimations(); - } - //------------------------------------------------------------------------- - Animation* SkeletonInstance::getAnimation(unsigned short index) const - { - return mSkeleton->getAnimation(index); - } - //------------------------------------------------------------------------- - Animation* SkeletonInstance::createAnimation(const String& name, Real length) - { - return mSkeleton->createAnimation(name, length); - } - //------------------------------------------------------------------------- - Animation* SkeletonInstance::getAnimation(const String& name, - const LinkedSkeletonAnimationSource** linker) const - { - return mSkeleton->getAnimation(name, linker); - } - //------------------------------------------------------------------------- - Animation* SkeletonInstance::_getAnimationImpl(const String& name, - const LinkedSkeletonAnimationSource** linker) const - { - return mSkeleton->_getAnimationImpl(name, linker); - } - //------------------------------------------------------------------------- - void SkeletonInstance::removeAnimation(const String& name) - { - mSkeleton->removeAnimation(name); - } - //------------------------------------------------------------------------- - void SkeletonInstance::addLinkedSkeletonAnimationSource(const String& skelName, - Real scale) - { - mSkeleton->addLinkedSkeletonAnimationSource(skelName, scale); - } - //------------------------------------------------------------------------- - void SkeletonInstance::removeAllLinkedSkeletonAnimationSources(void) - { - mSkeleton->removeAllLinkedSkeletonAnimationSources(); - } - //------------------------------------------------------------------------- - const Skeleton::LinkedSkeletonAnimSourceList& - SkeletonInstance::getLinkedSkeletonAnimationSources() const - { - return mSkeleton->getLinkedSkeletonAnimationSources(); - } - Skeleton::LinkedSkeletonAnimSourceIterator - SkeletonInstance::getLinkedSkeletonAnimationSourceIterator(void) const - { - return Skeleton::LinkedSkeletonAnimSourceIterator( - mSkeleton->getLinkedSkeletonAnimationSources().begin(), - mSkeleton->getLinkedSkeletonAnimationSources().end()); - } - //------------------------------------------------------------------------- - void SkeletonInstance::_initAnimationState(AnimationStateSet* animSet) - { - mSkeleton->_initAnimationState(animSet); - } - //------------------------------------------------------------------------- - void SkeletonInstance::_refreshAnimationState(AnimationStateSet* animSet) - { - mSkeleton->_refreshAnimationState(animSet); - } - //------------------------------------------------------------------------- - void SkeletonInstance::cloneBoneAndChildren(Bone* source, Bone* parent) - { - Bone* newBone; - if (source->getName().empty()) - { - newBone = createBone(source->getHandle()); - } - else - { - newBone = createBone(source->getName(), source->getHandle()); - } - if (parent == NULL) - { - mRootBones.push_back(newBone); - } - else - { - parent->addChild(newBone); - } - newBone->setOrientation(source->getOrientation()); - newBone->setPosition(source->getPosition()); - newBone->setScale(source->getScale()); - - // Process children - for (auto c : source->getChildren()) - { - cloneBoneAndChildren(static_cast(c), newBone); - } - } - //------------------------------------------------------------------------- - void SkeletonInstance::prepareImpl(void) - { - mNextAutoHandle = mSkeleton->mNextAutoHandle; - mNextTagPointAutoHandle = 0; - // construct self from master - mBlendState = mSkeleton->mBlendState; - // Copy bones - BoneList::const_iterator i; - for (i = mSkeleton->getRootBones().begin(); i != mSkeleton->getRootBones().end(); ++i) - { - Bone* b = *i; - cloneBoneAndChildren(b, 0); - b->_update(true, false); - } - setBindingPose(); - } - //------------------------------------------------------------------------- - void SkeletonInstance::unprepareImpl(void) - { - Skeleton::unprepareImpl(); - - // destroy TagPoints - for (TagPointList::const_iterator it = mActiveTagPoints.begin(); it != mActiveTagPoints.end(); ++it) - { - TagPoint* tagPoint = *it; - // Woohoo! The child object all the same attaching this skeleton instance, but is ok we can just - // ignore it: - // 1. The parent node of the tagPoint already deleted by Skeleton::unload(), nothing need to do now - // 2. And the child object relationship already detached by Entity::~Entity() - OGRE_DELETE tagPoint; - } - mActiveTagPoints.clear(); - for (TagPointList::const_iterator it2 = mFreeTagPoints.begin(); it2 != mFreeTagPoints.end(); ++it2) - { - TagPoint* tagPoint = *it2; - OGRE_DELETE tagPoint; - } - mFreeTagPoints.clear(); - } - - //------------------------------------------------------------------------- - TagPoint* SkeletonInstance::createTagPointOnBone(Bone* bone, - const Quaternion &offsetOrientation, - const Vector3 &offsetPosition) - { - TagPoint* ret; - if (mFreeTagPoints.empty()) { - ret = OGRE_NEW TagPoint(mNextTagPointAutoHandle++, this); - mActiveTagPoints.push_back(ret); - } else { - ret = mFreeTagPoints.front(); - mActiveTagPoints.splice( - mActiveTagPoints.end(), mFreeTagPoints, mFreeTagPoints.begin()); - // Initial some members ensure identically behavior, avoiding potential bug. - ret->setParentEntity(0); - ret->setChildObject(0); - ret->setInheritOrientation(true); - ret->setInheritScale(true); - ret->setInheritParentEntityOrientation(true); - ret->setInheritParentEntityScale(true); - } - - ret->setPosition(offsetPosition); - ret->setOrientation(offsetOrientation); - ret->setScale(Vector3::UNIT_SCALE); - ret->setBindingPose(); - bone->addChild(ret); - - return ret; - } - //------------------------------------------------------------------------- - void SkeletonInstance::freeTagPoint(TagPoint* tagPoint) - { - TagPointList::iterator it = - std::find(mActiveTagPoints.begin(), mActiveTagPoints.end(), tagPoint); - assert(it != mActiveTagPoints.end()); - if (it != mActiveTagPoints.end()) - { - if (tagPoint->getParent()) - tagPoint->getParent()->removeChild(tagPoint); - - mFreeTagPoints.splice(mFreeTagPoints.end(), mActiveTagPoints, it); - } - } - //------------------------------------------------------------------------- - const String& SkeletonInstance::getName(void) const - { - // delegate - return mSkeleton->getName(); - } - //------------------------------------------------------------------------- - ResourceHandle SkeletonInstance::getHandle(void) const - { - // delegate - return mSkeleton->getHandle(); - } - //------------------------------------------------------------------------- - const String& SkeletonInstance::getGroup(void) const - { - // delegate - return mSkeleton->getGroup(); - } - -} - diff --git a/OgreMain/src/OgreSkeletonManager.cpp b/OgreMain/src/OgreSkeletonManager.cpp deleted file mode 100644 index fc4df62ca48..00000000000 --- a/OgreMain/src/OgreSkeletonManager.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreSkeletonManager.h" - -namespace Ogre -{ - //----------------------------------------------------------------------- - template<> SkeletonManager* Singleton::msSingleton = 0; - SkeletonManager* SkeletonManager::getSingletonPtr(void) - { - return msSingleton; - } - SkeletonManager& SkeletonManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //----------------------------------------------------------------------- - SkeletonManager::SkeletonManager() - { - mLoadOrder = 300.0f; - mResourceType = "Skeleton"; - - ResourceGroupManager::getSingleton()._registerResourceManager(mResourceType, this); - } - //----------------------------------------------------------------------- - SkeletonPtr SkeletonManager::getByName(const String& name, const String& groupName) const - { - return static_pointer_cast(getResourceByName(name, groupName)); - } - //----------------------------------------------------------------------- - SkeletonPtr SkeletonManager::create (const String& name, const String& group, - bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams) - { - return static_pointer_cast(createResource(name,group,isManual,loader,createParams)); - } - //----------------------------------------------------------------------- - SkeletonManager::~SkeletonManager() - { - ResourceGroupManager::getSingleton()._unregisterResourceManager(mResourceType); - } - //----------------------------------------------------------------------- - Resource* SkeletonManager::createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams) - { - return OGRE_NEW Skeleton(this, name, handle, group, isManual, loader); - } - - - -} diff --git a/OgreMain/src/OgreSkeletonSerializer.cpp b/OgreMain/src/OgreSkeletonSerializer.cpp deleted file mode 100644 index 1875944aa68..00000000000 --- a/OgreMain/src/OgreSkeletonSerializer.cpp +++ /dev/null @@ -1,666 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreSkeletonFileFormat.h" -#include "OgreSkeletonSerializer.h" -#include "OgreAnimation.h" -#include "OgreAnimationTrack.h" -#include "OgreKeyFrame.h" - -namespace Ogre { - /// stream overhead = ID + size - const long SSTREAM_OVERHEAD_SIZE = sizeof(uint16) + sizeof(uint32); - const uint16 HEADER_STREAM_ID_EXT = 0x1000; - //--------------------------------------------------------------------- - SkeletonSerializer::SkeletonSerializer() - { - // Version number - // NB changed to include bone names in 1.1 - mVersion = "[Unknown]"; - } - - //--------------------------------------------------------------------- - void SkeletonSerializer::exportSkeleton(const Skeleton* pSkeleton, - const String& filename, SkeletonVersion ver, Endian endianMode) - { - DataStreamPtr stream = _openFileStream(filename, std::ios::binary | std::ios::out); - exportSkeleton(pSkeleton, stream, ver, endianMode); - - stream->close(); - } - //--------------------------------------------------------------------- - void SkeletonSerializer::exportSkeleton(const Skeleton* pSkeleton, - const DataStreamPtr& stream, SkeletonVersion ver, Endian endianMode) - { - setWorkingVersion(ver); - // Decide on endian mode - determineEndianness(endianMode); - - mStream = stream; - if (!stream->isWriteable()) - { - OGRE_EXCEPT(Exception::ERR_CANNOT_WRITE_TO_FILE, - "Unable to write to stream " + stream->getName(), - "SkeletonSerializer::exportSkeleton"); - } - - - writeFileHeader(); - - pushInnerChunk(mStream); - // Write main skeleton data - LogManager::getSingleton().logMessage("Exporting bones.."); - writeSkeleton(pSkeleton, ver); - LogManager::getSingleton().logMessage("Bones exported."); - - // Write all animations - unsigned short numAnims = pSkeleton->getNumAnimations(); - LogManager::getSingleton().stream() - << "Exporting animations, count=" << numAnims; - for (unsigned short i = 0; i < numAnims; ++i) - { - Animation* pAnim = pSkeleton->getAnimation(i); - LogManager::getSingleton().stream() - << "Exporting animation: " << pAnim->getName(); - writeAnimation(pSkeleton, pAnim, ver); - LogManager::getSingleton().logMessage("Animation exported."); - - } - - // Write links - for(const auto& link : pSkeleton->getLinkedSkeletonAnimationSources()) - { - writeSkeletonAnimationLink(pSkeleton, link); - } - popInnerChunk(stream); - } - //--------------------------------------------------------------------- - void SkeletonSerializer::importSkeleton(DataStreamPtr& stream, Skeleton* pSkel) - { - // Determine endianness (must be the first thing we do!) - determineEndianness(stream); - - // Check header - unsigned short headerID; - readShorts(stream, &headerID, 1); - if (headerID != HEADER_STREAM_ID_EXT) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "File header not found", - "SkeletonSerializer::importSkeleton"); - } - - // Read version - String ver = readString(stream); - if ((ver != "[Serializer_v1.10]") && - (ver != "[Serializer_v1.80]")) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Invalid file: version incompatible, file reports " + String(ver), - "SkeletonSerializer::importSkeleton"); - } - mVersion = ver; - - pushInnerChunk(stream); - unsigned short streamID = readChunk(stream); - - while(!stream->eof()) - { - switch (streamID) - { - case SKELETON_BLENDMODE: - { - // Optional blend mode - uint16 blendMode; - readShorts(stream, &blendMode, 1); - pSkel->setBlendMode(static_cast(blendMode)); - break; - } - case SKELETON_BONE: - readBone(stream, pSkel); - break; - case SKELETON_BONE_PARENT: - readBoneParent(stream, pSkel); - break; - case SKELETON_ANIMATION: - readAnimation(stream, pSkel); - break; - case SKELETON_ANIMATION_LINK: - readSkeletonAnimationLink(stream, pSkel); - break; - default: - break; - } - - streamID = readChunk(stream); - } - // Assume bones are stored in the binding pose - pSkel->setBindingPose(); - popInnerChunk(stream); - - } - - //--------------------------------------------------------------------- - void SkeletonSerializer::setWorkingVersion(SkeletonVersion ver) - { - if (ver == SKELETON_VERSION_1_0) - mVersion = "[Serializer_v1.10]"; - else mVersion = "[Serializer_v1.80]"; - } - //--------------------------------------------------------------------- - void SkeletonSerializer::writeSkeleton(const Skeleton* pSkel, SkeletonVersion ver) - { - - // Write blend mode - if ((int)ver > (int)SKELETON_VERSION_1_0) - { - writeChunkHeader(SKELETON_BLENDMODE, SSTREAM_OVERHEAD_SIZE + sizeof(unsigned short)); - uint16 blendMode = static_cast(pSkel->getBlendMode()); - writeShorts(&blendMode, 1); - } - - // Write each bone - unsigned short numBones = pSkel->getNumBones(); - unsigned short i; - for (i = 0; i < numBones; ++i) - { - Bone* pBone = pSkel->getBone(i); - writeBone(pSkel, pBone); - } - // Write parents - for (i = 0; i < numBones; ++i) - { - Bone* pBone = pSkel->getBone(i); - unsigned short handle = pBone->getHandle(); - Bone* pParent = static_cast(pBone->getParent()); - if (pParent != NULL) - { - writeBoneParent(pSkel, handle, pParent->getHandle()); - } - } - } - //--------------------------------------------------------------------- - void SkeletonSerializer::writeBone(const Skeleton* pSkel, const Bone* pBone) - { - writeChunkHeader(SKELETON_BONE, calcBoneSize(pSkel, pBone)); - - unsigned short handle = pBone->getHandle(); - // char* name - writeString(pBone->getName()); -#if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE - // Hack to fix chunk size validation: - mChunkSizeStack.back() += calcStringSize(pBone->getName()); -#endif - // unsigned short handle : handle of the bone, should be contiguous & start at 0 - writeShorts(&handle, 1); - // Vector3 position : position of this bone relative to parent - writeObject(pBone->getPosition()); - // Quaternion orientation : orientation of this bone relative to parent - writeObject(pBone->getOrientation()); - // Vector3 scale : scale of this bone relative to parent - if (pBone->getScale() != Vector3::UNIT_SCALE) - { - writeObject(pBone->getScale()); - } - } - //--------------------------------------------------------------------- - void SkeletonSerializer::writeBoneParent(const Skeleton* pSkel, - unsigned short boneId, unsigned short parentId) - { - writeChunkHeader(SKELETON_BONE_PARENT, calcBoneParentSize(pSkel)); - - // unsigned short handle : child bone - writeShorts(&boneId, 1); - // unsigned short parentHandle : parent bone - writeShorts(&parentId, 1); - - } - //--------------------------------------------------------------------- - void SkeletonSerializer::writeAnimation(const Skeleton* pSkel, - const Animation* anim, SkeletonVersion ver) - { - writeChunkHeader(SKELETON_ANIMATION, calcAnimationSize(pSkel, anim, ver)); - - // char* name : Name of the animation - writeString(anim->getName()); - // float length : Length of the animation in seconds - float len = anim->getLength(); - writeFloats(&len, 1); - pushInnerChunk(mStream); - { - if ((int)ver > (int)SKELETON_VERSION_1_0) - { - if (anim->getUseBaseKeyFrame()) - { - size_t size = SSTREAM_OVERHEAD_SIZE; - // char* baseAnimationName (including terminator) - size += calcStringSize(anim->getBaseKeyFrameAnimationName()); - // float baseKeyFrameTime - size += sizeof(float); - - writeChunkHeader(SKELETON_ANIMATION_BASEINFO, size); - - // char* baseAnimationName (blank for self) - writeString(anim->getBaseKeyFrameAnimationName()); - - // float baseKeyFrameTime - float t = (float)anim->getBaseKeyFrameTime(); - writeFloats(&t, 1); - } - } - - // Write all tracks - for (const auto& it : anim->_getNodeTrackList()) - { - writeAnimationTrack(pSkel, it.second); - } - } - popInnerChunk(mStream); - - } - //--------------------------------------------------------------------- - void SkeletonSerializer::writeAnimationTrack(const Skeleton* pSkel, - const NodeAnimationTrack* track) - { - writeChunkHeader(SKELETON_ANIMATION_TRACK, calcAnimationTrackSize(pSkel, track)); - - // unsigned short boneIndex : Index of bone to apply to - Bone* bone = static_cast(track->getAssociatedNode()); - unsigned short boneid = bone->getHandle(); - writeShorts(&boneid, 1); - pushInnerChunk(mStream); - // Write all keyframes - for (unsigned short i = 0; i < track->getNumKeyFrames(); ++i) - { - writeKeyFrame(pSkel, track->getNodeKeyFrame(i)); - } - popInnerChunk(mStream); - } - //--------------------------------------------------------------------- - void SkeletonSerializer::writeKeyFrame(const Skeleton* pSkel, - const TransformKeyFrame* key) - { - - writeChunkHeader(SKELETON_ANIMATION_TRACK_KEYFRAME, calcKeyFrameSize(pSkel, key)); - - // float time : The time position (seconds) - float time = key->getTime(); - writeFloats(&time, 1); - // Quaternion rotate : Rotation to apply at this keyframe - writeObject(key->getRotation()); - // Vector3 translate : Translation to apply at this keyframe - writeObject(key->getTranslate()); - // Vector3 scale : Scale to apply at this keyframe - if (key->getScale() != Vector3::UNIT_SCALE) - { - writeObject(key->getScale()); - } - } - //--------------------------------------------------------------------- - size_t SkeletonSerializer::calcBoneSize(const Skeleton* pSkel, - const Bone* pBone) - { - size_t size = calcBoneSizeWithoutScale(pSkel, pBone); - - // scale - if (pBone->getScale() != Vector3::UNIT_SCALE) - { - size += sizeof(float) * 3; - } - - return size; - } - //--------------------------------------------------------------------- - size_t SkeletonSerializer::calcBoneSizeWithoutScale(const Skeleton* pSkel, - const Bone* pBone) - { - size_t size = SSTREAM_OVERHEAD_SIZE; - - // TODO: Add this for next skeleton format! - // Currently it is broken, because to determine that we have scale, it will compare chunk size. - //size += calcStringSize(pBone->getName()); - - // handle - size += sizeof(unsigned short); - - // position - size += sizeof(float) * 3; - - // orientation - size += sizeof(float) * 4; - - return size; - } - //--------------------------------------------------------------------- - size_t SkeletonSerializer::calcBoneParentSize(const Skeleton* pSkel) - { - size_t size = SSTREAM_OVERHEAD_SIZE; - - // handle - size += sizeof(unsigned short); - - // parent handle - size += sizeof(unsigned short); - - return size; - } - //--------------------------------------------------------------------- - size_t SkeletonSerializer::calcAnimationSize(const Skeleton* pSkel, const Animation* pAnim, SkeletonVersion ver) - { - size_t size = SSTREAM_OVERHEAD_SIZE; - - // Name, including terminator - size += calcStringSize(pAnim->getName()); - // length - size += sizeof(float); - - if ((int)ver > (int)SKELETON_VERSION_1_0) - { - if (pAnim->getUseBaseKeyFrame()) - { - size += SSTREAM_OVERHEAD_SIZE; - // char* baseAnimationName (including terminator) - size += calcStringSize(pAnim->getBaseKeyFrameAnimationName()); - // float baseKeyFrameTime - size += sizeof(float); - } - } - - // Nested animation tracks - for (const auto& it : pAnim->_getNodeTrackList()) - { - size += calcAnimationTrackSize(pSkel, it.second); - } - - return size; - } - //--------------------------------------------------------------------- - size_t SkeletonSerializer::calcAnimationTrackSize(const Skeleton* pSkel, - const NodeAnimationTrack* pTrack) - { - size_t size = SSTREAM_OVERHEAD_SIZE; - - // unsigned short boneIndex : Index of bone to apply to - size += sizeof(unsigned short); - - // Nested keyframes - for (unsigned short i = 0; i < pTrack->getNumKeyFrames(); ++i) - { - size += calcKeyFrameSize(pSkel, pTrack->getNodeKeyFrame(i)); - } - - return size; - } - //--------------------------------------------------------------------- - size_t SkeletonSerializer::calcKeyFrameSize(const Skeleton* pSkel, - const TransformKeyFrame* pKey) - { - size_t size = calcKeyFrameSizeWithoutScale(pSkel, pKey); - - // Vector3 scale : Scale to apply at this keyframe - if (pKey->getScale() != Vector3::UNIT_SCALE) - { - size += sizeof(float) * 3; - } - - return size; - } - //--------------------------------------------------------------------- - size_t SkeletonSerializer::calcKeyFrameSizeWithoutScale(const Skeleton* pSkel, - const TransformKeyFrame* pKey) - { - size_t size = SSTREAM_OVERHEAD_SIZE; - - // float time : The time position (seconds) - size += sizeof(float); - // Quaternion rotate : Rotation to apply at this keyframe - size += sizeof(float) * 4; - // Vector3 translate : Translation to apply at this keyframe - size += sizeof(float) * 3; - - return size; - } - //--------------------------------------------------------------------- - void SkeletonSerializer::readBone(DataStreamPtr& stream, Skeleton* pSkel) - { - // char* name - String name = readString(stream); - // unsigned short handle : handle of the bone, should be contiguous & start at 0 - unsigned short handle; - readShorts(stream, &handle, 1); - - // Create new bone - Bone* pBone = pSkel->createBone(name, handle); - - // Vector3 position : position of this bone relative to parent - Vector3 pos; - readObject(stream, pos); - pBone->setPosition(pos); - // Quaternion orientation : orientation of this bone relative to parent - Quaternion q; - readObject(stream, q); - pBone->setOrientation(q); - -#if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE - // Hack to fix chunk size validation: - mChunkSizeStack.back() += calcStringSize(name); -#endif - // TODO: don't depend on mCurrentstreamLen in next skeleton format! - // Currently we use wrong chunk sizes, but we can't fix it, because we depend on mCurrentstreamLen - // Do we have scale? - if (mCurrentstreamLen > calcBoneSizeWithoutScale(pSkel, pBone)) - { - Vector3 scale; - readObject(stream, scale); - pBone->setScale(scale); - } - - } - //--------------------------------------------------------------------- - void SkeletonSerializer::readBoneParent(DataStreamPtr& stream, Skeleton* pSkel) - { - // All bones have been created by this point - Bone *child, *parent; - unsigned short childHandle, parentHandle; - - // unsigned short handle : child bone - readShorts(stream, &childHandle, 1); - // unsigned short parentHandle : parent bone - readShorts(stream, &parentHandle, 1); - - // Find bones - parent = pSkel->getBone(parentHandle); - child = pSkel->getBone(childHandle); - - // attach - parent->addChild(child); - - } - //--------------------------------------------------------------------- - void SkeletonSerializer::readAnimation(DataStreamPtr& stream, Skeleton* pSkel) - { - // char* name : Name of the animation - String name; - name = readString(stream); - // float length : Length of the animation in seconds - float len; - readFloats(stream, &len, 1); - - Animation *pAnim = pSkel->createAnimation(name, len); - // Read all tracks - if (!stream->eof()) - { - pushInnerChunk(stream); - unsigned short streamID = readChunk(stream); - // Optional base info is possible - if (streamID == SKELETON_ANIMATION_BASEINFO) - { - // char baseAnimationName - String baseAnimName = readString(stream); - // float baseKeyFrameTime - float baseKeyTime; - readFloats(stream, &baseKeyTime, 1); - - pAnim->setUseBaseKeyFrame(true, baseKeyTime, baseAnimName); - - if (!stream->eof()) - { - // Get next stream - streamID = readChunk(stream); - } - } - - while(streamID == SKELETON_ANIMATION_TRACK && !stream->eof()) - { - readAnimationTrack(stream, pAnim, pSkel); - - if (!stream->eof()) - { - // Get next stream - streamID = readChunk(stream); - } - } - if (!stream->eof()) - { - // Backpedal back to start of this stream if we've found a non-track - backpedalChunkHeader(stream); - } - popInnerChunk(stream); - } - } - //--------------------------------------------------------------------- - void SkeletonSerializer::readAnimationTrack(DataStreamPtr& stream, Animation* anim, - Skeleton* pSkel) - { - // unsigned short boneIndex : Index of bone to apply to - unsigned short boneHandle; - readShorts(stream, &boneHandle, 1); - - // Find bone - Bone *targetBone = pSkel->getBone(boneHandle); - - // Create track - NodeAnimationTrack* pTrack = anim->createNodeTrack(boneHandle, targetBone); - - // Keep looking for nested keyframes - if (!stream->eof()) - { - pushInnerChunk(stream); - unsigned short streamID = readChunk(stream); - while(streamID == SKELETON_ANIMATION_TRACK_KEYFRAME && !stream->eof()) - { - readKeyFrame(stream, pTrack, pSkel); - - if (!stream->eof()) - { - // Get next stream - streamID = readChunk(stream); - } - } - if (!stream->eof()) - { - // Backpedal back to start of this stream if we've found a non-keyframe - backpedalChunkHeader(stream); - } - popInnerChunk(stream); - } - - - } - //--------------------------------------------------------------------- - void SkeletonSerializer::readKeyFrame(DataStreamPtr& stream, NodeAnimationTrack* track, - Skeleton* pSkel) - { - // float time : The time position (seconds) - float time; - readFloats(stream, &time, 1); - - TransformKeyFrame *kf = track->createNodeKeyFrame(time); - - // Quaternion rotate : Rotation to apply at this keyframe - Quaternion rot; - readObject(stream, rot); - kf->setRotation(rot); - // Vector3 translate : Translation to apply at this keyframe - Vector3 trans; - readObject(stream, trans); - kf->setTranslate(trans); - // Do we have scale? - if (mCurrentstreamLen > calcKeyFrameSizeWithoutScale(pSkel, kf)) - { - Vector3 scale; - readObject(stream, scale); - kf->setScale(scale); - } - } - //--------------------------------------------------------------------- - void SkeletonSerializer::writeSkeletonAnimationLink(const Skeleton* pSkel, - const LinkedSkeletonAnimationSource& link) - { - writeChunkHeader(SKELETON_ANIMATION_LINK, - calcSkeletonAnimationLinkSize(pSkel, link)); - - // char* skeletonName - writeString(link.skeletonName); - // float scale - writeFloats(&(link.scale), 1); - - } - //--------------------------------------------------------------------- - size_t SkeletonSerializer::calcSkeletonAnimationLinkSize(const Skeleton* pSkel, - const LinkedSkeletonAnimationSource& link) - { - size_t size = SSTREAM_OVERHEAD_SIZE; - - // char* skeletonName - size += link.skeletonName.length() + 1; - // float scale - size += sizeof(float); - - return size; - - } - //--------------------------------------------------------------------- - void SkeletonSerializer::readSkeletonAnimationLink(DataStreamPtr& stream, - Skeleton* pSkel) - { - // char* skeletonName - String skelName = readString(stream); - // float scale - float scale; - readFloats(stream, &scale, 1); - - pSkel->addLinkedSkeletonAnimationSource(skelName, scale); - - } - - - -} - - diff --git a/OgreMain/src/OgreSkyRenderer.cpp b/OgreMain/src/OgreSkyRenderer.cpp deleted file mode 100644 index 07fcf593eec..00000000000 --- a/OgreMain/src/OgreSkyRenderer.cpp +++ /dev/null @@ -1,441 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include - -#include "OgreStableHeaders.h" - -#include "OgreEntity.h" -#include "OgreSubEntity.h" -#include "OgreViewport.h" - -namespace Ogre { -SceneManager::SkyRenderer::SkyRenderer(SceneManager* owner) - : mSceneManager(owner), mSceneNode(0), mEnabled(false) -{ -} - -void SceneManager::SkyRenderer::nodeDestroyed(const Node*) -{ - // Remove sky nodes since they've been deleted - mSceneNode = 0; - mEnabled = false; -} - -void SceneManager::SkyRenderer::setEnabled(bool enable) -{ - if(enable == mEnabled) return; - mEnabled = enable; - enable ? mSceneManager->addListener(this) : mSceneManager->removeListener(this); -} - -void SceneManager::SkyPlaneRenderer::setSkyPlane( - bool enable, - const Plane& plane, - const String& materialName, - Real gscale, - Real tiling, - uint8 renderQueue, - Real bow, - int xsegments, int ysegments, - const String& groupName) -{ - if (enable) - { - String meshName = mSceneManager->mName + "SkyPlane"; - mSkyPlane = plane; - - MaterialPtr m = MaterialManager::getSingleton().getByName(materialName, groupName); - if (!m) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Sky plane material '" + materialName + "' not found.", - "SceneManager::setSkyPlane"); - } - // Make sure the material doesn't update the depth buffer - m->setDepthWriteEnabled(false); - // Ensure loaded - m->load(); - - // Set up the plane - MeshPtr planeMesh = MeshManager::getSingleton().getByName(meshName, groupName); - if (planeMesh) - { - // Destroy the old one - MeshManager::getSingleton().remove(planeMesh); - } - - // Create up vector - Vector3 up = plane.normal.crossProduct(Vector3::UNIT_X); - if (up == Vector3::ZERO) - up = plane.normal.crossProduct(-Vector3::UNIT_Z); - - // Create skyplane - if( bow > 0 ) - { - // Build a curved skyplane - planeMesh = MeshManager::getSingleton().createCurvedPlane( - meshName, groupName, plane, gscale * 100, gscale * 100, gscale * bow * 100, - xsegments, ysegments, false, 1, tiling, tiling, up); - } - else - { - planeMesh = MeshManager::getSingleton().createPlane( - meshName, groupName, plane, gscale * 100, gscale * 100, xsegments, ysegments, false, - 1, tiling, tiling, up); - } - - // Create entity - if (mSkyPlaneEntity) - { - // destroy old one, do it by name for speed - mSceneManager->destroyEntity(meshName); - mSkyPlaneEntity = 0; - } - // Create, use the same name for mesh and entity - // manually construct as we don't want this to be destroyed on destroyAllMovableObjects - MovableObjectFactory* factory = Root::getSingleton().getMovableObjectFactory(MOT_ENTITY); - NameValuePairList params; - params["mesh"] = meshName; - mSkyPlaneEntity = static_cast(factory->createInstance(meshName, mSceneManager, ¶ms)); - mSkyPlaneEntity->setMaterialName(materialName, groupName); - mSkyPlaneEntity->setCastShadows(false); - mSkyPlaneEntity->setRenderQueueGroup(renderQueue); - - MovableObjectCollection* objectMap = mSceneManager->getMovableObjectCollection(MOT_ENTITY); - objectMap->map[meshName] = mSkyPlaneEntity; - - // Create node and attach - if (!mSceneNode) - { - mSceneNode = mSceneManager->createSceneNode(); - mSceneNode->setListener(this); - } - else - { - mSceneNode->detachAllObjects(); - } - mSceneNode->attachObject(mSkyPlaneEntity); - - } - setEnabled(enable); - mSkyPlaneGenParameters.skyPlaneBow = bow; - mSkyPlaneGenParameters.skyPlaneScale = gscale; - mSkyPlaneGenParameters.skyPlaneTiling = tiling; - mSkyPlaneGenParameters.skyPlaneXSegments = xsegments; - mSkyPlaneGenParameters.skyPlaneYSegments = ysegments; -} - -void SceneManager::SkyBoxRenderer::setSkyBox( - bool enable, - const String& materialName, - Real distance, - uint8 renderQueue, - const Quaternion& orientation, - const String& groupName) -{ - if (enable) - { - MaterialPtr m = MaterialManager::getSingleton().getByName(materialName, groupName); - if (!m) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Sky box material '" + materialName + "' not found.", - "SceneManager::setSkyBox"); - } - // Ensure loaded - m->load(); - - bool valid = m->getBestTechnique() && m->getBestTechnique()->getNumPasses(); - if(valid) - { - Pass* pass = m->getBestTechnique()->getPass(0); - valid = valid && pass->getNumTextureUnitStates() && - pass->getTextureUnitState(0)->getTextureType() == TEX_TYPE_CUBE_MAP; - } - - if (!valid) - { - LogManager::getSingleton().logWarning("skybox material " + materialName + - " is not supported, defaulting"); - m = MaterialManager::getSingleton().getDefaultSettings(); - } - - // Create node - if (!mSceneNode) - { - mSceneNode = mSceneManager->createSceneNode(); - mSceneNode->setListener(this); - } - - // Create object - if (!mSkyBoxObj) - { - mSkyBoxObj = std::make_unique("SkyBox"); - mSkyBoxObj->setCastShadows(false); - mSceneNode->attachObject(mSkyBoxObj.get()); - } - else - { - if (!mSkyBoxObj->isAttached()) - { - mSceneNode->attachObject(mSkyBoxObj.get()); - } - mSkyBoxObj->clear(); - } - - mSkyBoxObj->setRenderQueueGroup(renderQueue); - mSkyBoxObj->begin(materialName, RenderOperation::OT_TRIANGLE_STRIP, groupName); - - // rendering cube, only using 14 vertices - const Vector3 cube_strip[14] = { - {-1.f, 1.f, 1.f}, // Front-top-left - {1.f, 1.f, 1.f}, // Front-top-right - {-1.f, -1.f, 1.f}, // Front-bottom-left - {1.f, -1.f, 1.f}, // Front-bottom-right - {1.f, -1.f, -1.f}, // Back-bottom-right - {1.f, 1.f, 1.f}, // Front-top-right - {1.f, 1.f, -1.f}, // Back-top-right - {-1.f, 1.f, 1.f}, // Front-top-left - {-1.f, 1.f, -1.f}, // Back-top-left - {-1.f, -1.f, 1.f}, // Front-bottom-left - {-1.f, -1.f, -1.f}, // Back-bottom-left - {1.f, -1.f, -1.f}, // Back-bottom-right - {-1.f, 1.f, -1.f}, // Back-top-left - {1.f, 1.f, -1.f} // Back-top-right - }; - - for (const auto& vtx : cube_strip) - { - mSkyBoxObj->position(orientation * (vtx * distance)); - // Note UVs mirrored front/back - mSkyBoxObj->textureCoord(vtx.normalisedCopy() * Vector3(1, 1, -1)); - } - - mSkyBoxObj->end(); - } - setEnabled(enable); - mSkyBoxGenParameters.skyBoxDistance = distance; -} - -void SceneManager::SkyDomeRenderer::setSkyDome( - bool enable, - const String& materialName, - Real curvature, - Real tiling, - Real distance, - uint8 renderQueue, - const Quaternion& orientation, - int xsegments, int ysegments, int ySegmentsToKeep, - const String& groupName) -{ - if (enable) - { - MaterialPtr m = MaterialManager::getSingleton().getByName(materialName, groupName); - if (!m) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Sky dome material '" + materialName + "' not found.", - "SceneManager::setSkyDome"); - } - // Make sure the material doesn't update the depth buffer - m->setDepthWriteEnabled(false); - // Ensure loaded - m->load(); - - // Create node - if (!mSceneNode) - { - mSceneNode = mSceneManager->createSceneNode(); - mSceneNode->setListener(this); - } - else - { - mSceneNode->detachAllObjects(); - } - - // Set up the dome (5 planes) - for (int i = 0; i < 5; ++i) - { - MeshPtr planeMesh = createSkydomePlane((BoxPlane)i, curvature, - tiling, distance, orientation, xsegments, ysegments, - i!=BP_UP ? ySegmentsToKeep : -1, groupName); - - String entName = "SkyDomePlane" + StringConverter::toString(i); - - // Create entity - if (mSkyDomeEntity[i]) - { - // destroy old one, do it by name for speed - mSceneManager->destroyEntity(entName); - mSkyDomeEntity[i] = 0; - } - // construct manually so we don't have problems if destroyAllMovableObjects called - MovableObjectFactory* factory = Root::getSingleton().getMovableObjectFactory(MOT_ENTITY); - - NameValuePairList params; - params["mesh"] = planeMesh->getName(); - mSkyDomeEntity[i] = static_cast(factory->createInstance(entName, mSceneManager, ¶ms)); - mSkyDomeEntity[i]->setMaterialName(m->getName(), groupName); - mSkyDomeEntity[i]->setCastShadows(false); - mSkyDomeEntity[i]->setRenderQueueGroup(renderQueue); - - - MovableObjectCollection* objectMap = mSceneManager->getMovableObjectCollection(MOT_ENTITY); - objectMap->map[entName] = mSkyDomeEntity[i]; - - // Attach to node - mSceneNode->attachObject(mSkyDomeEntity[i]); - } // for each plane - - } - setEnabled(enable); - mSkyDomeGenParameters.skyDomeCurvature = curvature; - mSkyDomeGenParameters.skyDomeDistance = distance; - mSkyDomeGenParameters.skyDomeTiling = tiling; - mSkyDomeGenParameters.skyDomeXSegments = xsegments; - mSkyDomeGenParameters.skyDomeYSegments = ysegments; - mSkyDomeGenParameters.skyDomeYSegments_keep = ySegmentsToKeep; -} - -MeshPtr SceneManager::SkyDomeRenderer::createSkydomePlane( - BoxPlane bp, - Real curvature, - Real tiling, - Real distance, - const Quaternion& orientation, - int xsegments, int ysegments, int ysegments_keep, - const String& groupName) -{ - - Plane plane; - String meshName; - Vector3 up; - - meshName = mSceneManager->mName + "SkyDomePlane_"; - // Set up plane equation - plane.d = distance; - switch(bp) - { - case BP_FRONT: - plane.normal = Vector3::UNIT_Z; - up = Vector3::UNIT_Y; - meshName += "Front"; - break; - case BP_BACK: - plane.normal = -Vector3::UNIT_Z; - up = Vector3::UNIT_Y; - meshName += "Back"; - break; - case BP_LEFT: - plane.normal = Vector3::UNIT_X; - up = Vector3::UNIT_Y; - meshName += "Left"; - break; - case BP_RIGHT: - plane.normal = -Vector3::UNIT_X; - up = Vector3::UNIT_Y; - meshName += "Right"; - break; - case BP_UP: - plane.normal = -Vector3::UNIT_Y; - up = Vector3::UNIT_Z; - meshName += "Up"; - break; - case BP_DOWN: - // no down - return MeshPtr(); - } - // Modify by orientation - plane.normal = orientation * plane.normal; - up = orientation * up; - - // Check to see if existing plane - MeshManager& mm = MeshManager::getSingleton(); - MeshPtr planeMesh = mm.getByName(meshName, groupName); - if(planeMesh) - { - // destroy existing - mm.remove(planeMesh->getHandle()); - } - // Create new - Real planeSize = distance * 2; - planeMesh = mm.createCurvedIllusionPlane(meshName, groupName, plane, - planeSize, planeSize, curvature, - xsegments, ysegments, false, 1, tiling, tiling, up, - orientation, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY, HardwareBuffer::HBU_STATIC_WRITE_ONLY, - false, false, ysegments_keep); - - //planeMesh->_dumpContents(meshName); - - return planeMesh; - -} - -void SceneManager::SkyPlaneRenderer::_updateRenderQueue(RenderQueue* queue) -{ - if (mSkyPlaneEntity->isVisible()) - { - mSkyPlaneEntity->_updateRenderQueue(queue); - } -} - -void SceneManager::SkyBoxRenderer::_updateRenderQueue(RenderQueue* queue) -{ - if (mSkyBoxObj->isVisible()) - { - mSkyBoxObj->_updateRenderQueue(queue); - } -} - -void SceneManager::SkyDomeRenderer::_updateRenderQueue(RenderQueue* queue) -{ - for (uint plane = 0; plane < 5; ++plane) - { - if (!mSkyDomeEntity[plane]->isVisible()) continue; - - mSkyDomeEntity[plane]->_updateRenderQueue(queue); - } -} - -void SceneManager::SkyRenderer::postFindVisibleObjects(SceneManager* source, IlluminationRenderStage irs, - Viewport* vp) -{ - // Queue skies, if viewport seems it - if (!vp->getSkiesEnabled() || irs == IRS_RENDER_TO_TEXTURE) - return; - - if(!mEnabled || !mSceneNode) - return; - - // Update nodes - // Translate the box by the camera position (constant distance) - mSceneNode->setPosition(vp->getCamera()->getDerivedPosition()); - _updateRenderQueue(source->getRenderQueue()); -} -} diff --git a/OgreMain/src/OgreStableHeaders.h b/OgreMain/src/OgreStableHeaders.h deleted file mode 100644 index 9527b07791a..00000000000 --- a/OgreMain/src/OgreStableHeaders.h +++ /dev/null @@ -1,141 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -/* Stable headers which will be used for precompilation if the compiler - supports it. Add entries here when headers are unlikely to change. - NB: a change to any of these headers will result in a full rebuild, - so don't add things to this lightly. -*/ - -#ifndef __OgreStableHeaders__ -#define __OgreStableHeaders__ - -extern "C" { -# include -# include -} - -#include "OgreConfig.h" -#include "OgreExports.h" -#include "OgrePrerequisites.h" -#include "OgrePlatform.h" -#include "OgreStdHeaders.h" -#include - -#include "OgreAny.h" -#include "OgreArchive.h" -#include "OgreArchiveManager.h" -#include "OgreAxisAlignedBox.h" -#include "OgreBitwise.h" -#include "OgreBone.h" -#include "OgreCamera.h" -#include "OgreCodec.h" -#include "OgreColourValue.h" -#include "OgreCommon.h" -#include "OgreDataStream.h" -#include "OgreDefaultWorkQueue.h" -#include "OgreException.h" -#include "OgreFileSystem.h" -#include "OgreFrustum.h" -#include "OgreHardwareBufferManager.h" -#include "OgreLight.h" -#include "OgreLog.h" -#include "OgreLogManager.h" -#include "OgreManualObject.h" -#include "OgreMaterialManager.h" -#include "OgreMaterialSerializer.h" -#include "OgreMath.h" -#include "OgreMatrix3.h" -#include "OgreMatrix4.h" -#include "OgreMesh.h" -#include "OgreMeshManager.h" -#include "OgreMeshSerializer.h" -#include "OgreMovableObject.h" -#include "OgreNode.h" -#include "OgreParticleSystemManager.h" -#include "OgrePass.h" -#include "OgrePlane.h" -#include "OgrePlatformInformation.h" -#include "OgreProfiler.h" -#include "OgreQuaternion.h" -#include "OgreRadixSort.h" -#include "OgreRay.h" -#include "OgreRectangle2D.h" -#include "OgreBuiltinMovableFactories.h" -#include "OgreRenderSystem.h" -#include "OgreResourceGroupManager.h" -#include "OgreResource.h" -#include "OgreRoot.h" -#include "OgreShadowTextureManager.h" -#include "OgreSceneManager.h" -#include "OgreSceneNode.h" -#include "OgreScriptCompiler.h" -#include "OgreSerializer.h" -#include "OgreSharedPtr.h" -#include "OgreSimpleRenderable.h" -#include "OgreSimpleSpline.h" -#include "OgreSingleton.h" -#include "OgreSkeleton.h" -#include "OgreSphere.h" -#include "OgreStringConverter.h" -#include "OgreString.h" -#include "OgreStringInterface.h" -#include "OgreStringVector.h" -#include "OgreSubMesh.h" -#include "OgreTechnique.h" -#include "OgreTextureManager.h" -#include "Threading/OgreThreadHeaders.h" -#include "OgreUserObjectBindings.h" -#include "OgreVector.h" -#if OGRE_NO_ZIP_ARCHIVE == 0 -# include "OgreZip.h" -#endif - -#define FOURCC(c0, c1, c2, c3) (c0 | (c1 << 8) | (c2 << 16) | (c3 << 24)) - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -#define OGRE_IGNORE_DEPRECATED_BEGIN __pragma(warning(push)) \ - __pragma(warning(disable:4996)) -#define OGRE_IGNORE_DEPRECATED_END __pragma(warning(pop)) -#else -#define OGRE_IGNORE_DEPRECATED_BEGIN _Pragma("GCC diagnostic push") \ - _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") -#define OGRE_IGNORE_DEPRECATED_END _Pragma("GCC diagnostic pop") -#endif - -#ifndef OGRE_SERIALIZER_VALIDATE_CHUNKSIZE -#define OGRE_SERIALIZER_VALIDATE_CHUNKSIZE OGRE_DEBUG_MODE -#endif - -namespace Ogre -{ -void logMaterialNotFound(const String& name, const String& groupName, const String& destType, const String& destName, - LogMessageLevel lml = LML_CRITICAL); -} - -#endif diff --git a/OgreMain/src/OgreStaticGeometry.cpp b/OgreMain/src/OgreStaticGeometry.cpp deleted file mode 100644 index 1a117bd0fb0..00000000000 --- a/OgreMain/src/OgreStaticGeometry.cpp +++ /dev/null @@ -1,1590 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreStaticGeometry.h" -#include "OgreEntity.h" -#include "OgreEdgeListBuilder.h" -#include "OgreLodStrategy.h" -#include "OgreSubEntity.h" - -namespace Ogre { - - #define REGION_RANGE 1024 - #define REGION_HALF_RANGE 512 - #define REGION_MAX_INDEX 511 - #define REGION_MIN_INDEX -512 - - //-------------------------------------------------------------------------- - StaticGeometry::StaticGeometry(SceneManager* owner, const String& name): - mOwner(owner), - mName(name), - mUpperDistance(0.0f), - mSquaredUpperDistance(0.0f), - mCastShadows(false), - mRegionDimensions(Vector3(1000,1000,1000)), - mHalfRegionDimensions(Vector3(500,500,500)), - mOrigin(Vector3(0,0,0)), - mVisible(true), - mRenderQueueID(RENDER_QUEUE_MAIN), - mRenderQueueIDSet(false), - mVisibilityFlags(Ogre::MovableObject::getDefaultVisibilityFlags()) - { - } - //-------------------------------------------------------------------------- - StaticGeometry::~StaticGeometry() - { - reset(); - } - //-------------------------------------------------------------------------- - StaticGeometry::Region* StaticGeometry::getRegion(const AxisAlignedBox& bounds, - bool autoCreate) - { - if (bounds.isNull()) - return 0; - - // Get the region which has the largest overlapping volume - const Vector3 min = bounds.getMinimum(); - const Vector3 max = bounds.getMaximum(); - - // Get the min and max region indexes - ushort minx, miny, minz; - ushort maxx, maxy, maxz; - getRegionIndexes(min, minx, miny, minz); - getRegionIndexes(max, maxx, maxy, maxz); - Real maxVolume = 0.0f; - ushort finalx = 0, finaly = 0, finalz = 0; - for (ushort x = minx; x <= maxx; ++x) - { - for (ushort y = miny; y <= maxy; ++y) - { - for (ushort z = minz; z <= maxz; ++z) - { - Real vol = getVolumeIntersection(bounds, x, y, z); - if (vol > maxVolume) - { - maxVolume = vol; - finalx = x; - finaly = y; - finalz = z; - } - - } - } - } - - assert(maxVolume > 0.0f && - "Static geometry: Problem determining closest volume match!"); - - return getRegion(finalx, finaly, finalz, autoCreate); - - } - //-------------------------------------------------------------------------- - Real StaticGeometry::getVolumeIntersection(const AxisAlignedBox& box, - ushort x, ushort y, ushort z) - { - // Get bounds of indexed region - AxisAlignedBox regionBounds = getRegionBounds(x, y, z); - AxisAlignedBox intersectBox = regionBounds.intersection(box); - // return a 'volume' which ignores zero dimensions - // since we only use this for relative comparisons of the same bounds - // this will still be internally consistent - Vector3 boxdiff = box.getMaximum() - box.getMinimum(); - Vector3 intersectDiff = intersectBox.getMaximum() - intersectBox.getMinimum(); - - return (boxdiff.x == 0 ? 1 : intersectDiff.x) * - (boxdiff.y == 0 ? 1 : intersectDiff.y) * - (boxdiff.z == 0 ? 1 : intersectDiff.z); - - } - //-------------------------------------------------------------------------- - AxisAlignedBox StaticGeometry::getRegionBounds(ushort x, ushort y, ushort z) - { - Vector3 min( - ((Real)x - REGION_HALF_RANGE) * mRegionDimensions.x + mOrigin.x, - ((Real)y - REGION_HALF_RANGE) * mRegionDimensions.y + mOrigin.y, - ((Real)z - REGION_HALF_RANGE) * mRegionDimensions.z + mOrigin.z - ); - Vector3 max = min + mRegionDimensions; - return AxisAlignedBox(min, max); - } - //-------------------------------------------------------------------------- - Vector3 StaticGeometry::getRegionCentre(ushort x, ushort y, ushort z) - { - return Vector3( - ((Real)x - REGION_HALF_RANGE) * mRegionDimensions.x + mOrigin.x - + mHalfRegionDimensions.x, - ((Real)y - REGION_HALF_RANGE) * mRegionDimensions.y + mOrigin.y - + mHalfRegionDimensions.y, - ((Real)z - REGION_HALF_RANGE) * mRegionDimensions.z + mOrigin.z - + mHalfRegionDimensions.z - ); - } - //-------------------------------------------------------------------------- - StaticGeometry::Region* StaticGeometry::getRegion( - ushort x, ushort y, ushort z, bool autoCreate) - { - uint32 index = packIndex(x, y, z); - Region* ret = getRegion(index); - if (!ret && autoCreate) - { - // Make a name - StringStream str; - str << mName << ":" << index; - // Calculate the region centre - Vector3 centre = getRegionCentre(x, y, z); - ret = OGRE_NEW Region(this, str.str(), mOwner, index, centre); - mOwner->injectMovableObject(ret); - ret->setVisible(mVisible); - ret->setCastShadows(mCastShadows); - if (mRenderQueueIDSet) - { - ret->setRenderQueueGroup(mRenderQueueID); - } - mRegionMap[index] = ret; - } - return ret; - } - //-------------------------------------------------------------------------- - StaticGeometry::Region* StaticGeometry::getRegion(uint32 index) - { - RegionMap::iterator i = mRegionMap.find(index); - if (i != mRegionMap.end()) - { - return i->second; - } - else - { - return 0; - } - - } - //-------------------------------------------------------------------------- - void StaticGeometry::getRegionIndexes(const Vector3& point, - ushort& x, ushort& y, ushort& z) - { - // Scale the point into multiples of region and adjust for origin - Vector3 scaledPoint = (point - mOrigin) / mRegionDimensions; - - // Round down to 'bottom left' point which represents the cell index - int ix = Math::IFloor(scaledPoint.x); - int iy = Math::IFloor(scaledPoint.y); - int iz = Math::IFloor(scaledPoint.z); - - // Check bounds - if (ix < REGION_MIN_INDEX || ix > REGION_MAX_INDEX - || iy < REGION_MIN_INDEX || iy > REGION_MAX_INDEX - || iz < REGION_MIN_INDEX || iz > REGION_MAX_INDEX) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Point out of bounds", - "StaticGeometry::getRegionIndexes"); - } - // Adjust for the fact that we use unsigned values for simplicity - // (requires less faffing about for negatives give 10-bit packing - x = static_cast(ix + REGION_HALF_RANGE); - y = static_cast(iy + REGION_HALF_RANGE); - z = static_cast(iz + REGION_HALF_RANGE); - - - } - //-------------------------------------------------------------------------- - uint32 StaticGeometry::packIndex(ushort x, ushort y, ushort z) - { - return x + (y << 10) + (z << 20); - } - //-------------------------------------------------------------------------- - StaticGeometry::Region* StaticGeometry::getRegion(const Vector3& point, - bool autoCreate) - { - ushort x, y, z; - getRegionIndexes(point, x, y, z); - return getRegion(x, y, z, autoCreate); - } - //-------------------------------------------------------------------------- - AxisAlignedBox StaticGeometry::calculateBounds(VertexData* vertexData, - const Vector3& position, const Quaternion& orientation, - const Vector3& scale) - { - const VertexElement* posElem = - vertexData->vertexDeclaration->findElementBySemantic( - VES_POSITION); - HardwareVertexBufferSharedPtr vbuf = - vertexData->vertexBufferBinding->getBuffer(posElem->getSource()); - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_READ_ONLY); - unsigned char* vertex = static_cast(vbufLock.pData); - float* pFloat; - - Vector3 min = Vector3::ZERO, max = Vector3::UNIT_SCALE; - bool first = true; - - for(size_t j = 0; j < vertexData->vertexCount; ++j, vertex += vbuf->getVertexSize()) - { - posElem->baseVertexPointerToElement(vertex, &pFloat); - - Vector3 pt; - - pt.x = (*pFloat++); - pt.y = (*pFloat++); - pt.z = (*pFloat++); - // Transform to world (scale, rotate, translate) - pt = (orientation * (pt * scale)) + position; - if (first) - { - min = max = pt; - first = false; - } - else - { - min.makeFloor(pt); - max.makeCeil(pt); - } - - } - return AxisAlignedBox(min, max); - } - //-------------------------------------------------------------------------- - void StaticGeometry::addEntity(Entity* ent, const Vector3& position, - const Quaternion& orientation, const Vector3& scale) - { - const MeshPtr& msh = ent->getMesh(); - // Validate - if (msh->hasManualLodLevel()) - { - LogManager::getSingleton().logWarning("(StaticGeometry): Manual LOD is not supported. " - "Using only highest LOD level for mesh " + - msh->getName()); - } - - AxisAlignedBox sharedWorldBounds; - // queue this entities submeshes and choice of material - // also build the lists of geometry to be used for the source of lods - for (uint i = 0; i < ent->getNumSubEntities(); ++i) - { - SubEntity* se = ent->getSubEntity(i); - QueuedSubMesh* q = OGRE_NEW QueuedSubMesh(); - - // Get the geometry for this SubMesh - q->submesh = se->getSubMesh(); - q->material = se->getMaterial(); - q->geometryLodList = determineGeometry(q->submesh); - q->orientation = orientation; - q->position = position; - q->scale = scale; - // Determine the bounds based on the highest LOD - q->worldBounds = calculateBounds( - (*q->geometryLodList)[0].vertexData, - position, orientation, scale); - - mQueuedSubMeshes.push_back(q); - } - } - //-------------------------------------------------------------------------- - StaticGeometry::SubMeshLodGeometryLinkList* - StaticGeometry::determineGeometry(SubMesh* sm) - { - OgreAssert(sm->indexData->indexBuffer, "currently only works with indexed geometry"); - // First, determine if we've already seen this submesh before - SubMeshGeometryLookup::iterator i = - mSubMeshGeometryLookup.find(sm); - if (i != mSubMeshGeometryLookup.end()) - { - return i->second; - } - // Otherwise, we have to create a new one - SubMeshLodGeometryLinkList* lodList = OGRE_NEW_T(SubMeshLodGeometryLinkList, MEMCATEGORY_GEOMETRY)(); - mSubMeshGeometryLookup[sm] = lodList; - ushort numLods = sm->parent->hasManualLodLevel() ? 1 : - sm->parent->getNumLodLevels(); - lodList->resize(numLods); - for (ushort lod = 0; lod < numLods; ++lod) - { - SubMeshLodGeometryLink& geomLink = (*lodList)[lod]; - IndexData *lodIndexData; - if (lod == 0) - { - lodIndexData = sm->indexData; - } - else - { - lodIndexData = sm->mLodFaceList[lod - 1]; - } - // Can use the original mesh geometry? - if (sm->useSharedVertices) - { - if (sm->parent->getNumSubMeshes() == 1) - { - // Ok, this is actually our own anyway - geomLink.vertexData = sm->parent->sharedVertexData; - geomLink.indexData = lodIndexData; - } - else - { - // We have to split it - splitGeometry(sm->parent->sharedVertexData, - lodIndexData, &geomLink); - } - } - else - { - if (lod == 0) - { - // Ok, we can use the existing geometry; should be in full - // use by just this SubMesh - geomLink.vertexData = sm->vertexData; - geomLink.indexData = sm->indexData; - } - else - { - // We have to split it - splitGeometry(sm->vertexData, - lodIndexData, &geomLink); - } - } - assert (geomLink.vertexData->vertexStart == 0 && - "Cannot use vertexStart > 0 on indexed geometry due to " - "rendersystem incompatibilities - see the docs!"); - } - - - return lodList; - } - //-------------------------------------------------------------------------- - void StaticGeometry::splitGeometry(VertexData* vd, IndexData* id, - StaticGeometry::SubMeshLodGeometryLink* targetGeomLink) - { - // Firstly we need to scan to see how many vertices are being used - // and while we're at it, build the remap we can use later - bool use32bitIndexes = - id->indexBuffer->getType() == HardwareIndexBuffer::IT_32BIT; - IndexRemap indexRemap; - HardwareBufferLockGuard indexLock(id->indexBuffer, - id->indexStart * id->indexBuffer->getIndexSize(), - id->indexCount * id->indexBuffer->getIndexSize(), - HardwareBuffer::HBL_READ_ONLY); - if (use32bitIndexes) - { - buildIndexRemap(static_cast(indexLock.pData), id->indexCount, indexRemap); - } - else - { - buildIndexRemap(static_cast(indexLock.pData), id->indexCount, indexRemap); - } - indexLock.unlock(); - if (indexRemap.size() == vd->vertexCount) - { - // ha, complete usage after all - targetGeomLink->vertexData = vd; - targetGeomLink->indexData = id; - return; - } - - - // Create the new vertex data records - targetGeomLink->vertexData = vd->clone(false); - // Convenience - VertexData* newvd = targetGeomLink->vertexData; - //IndexData* newid = targetGeomLink->indexData; - // Update the vertex count - newvd->vertexCount = indexRemap.size(); - - size_t numvbufs = vd->vertexBufferBinding->getBufferCount(); - // Copy buffers from old to new - for (unsigned short b = 0; b < numvbufs; ++b) - { - // Lock old buffer - HardwareVertexBufferSharedPtr oldBuf = - vd->vertexBufferBinding->getBuffer(b); - // Create new buffer - HardwareVertexBufferSharedPtr newBuf = - HardwareBufferManager::getSingleton().createVertexBuffer( - oldBuf->getVertexSize(), - indexRemap.size(), - HardwareBuffer::HBU_STATIC); - // rebind - newvd->vertexBufferBinding->setBinding(b, newBuf); - - // Copy all the elements of the buffer across, by iterating over - // the IndexRemap which describes how to move the old vertices - // to the new ones. By nature of the map the remap is in order of - // indexes in the old buffer, but note that we're not guaranteed to - // address every vertex (which is kinda why we're here) - HardwareBufferLockGuard oldBufLock(oldBuf, HardwareBuffer::HBL_READ_ONLY); - HardwareBufferLockGuard newBufLock(newBuf, HardwareBuffer::HBL_DISCARD); - size_t vertexSize = oldBuf->getVertexSize(); - // Buffers should be the same size - assert (vertexSize == newBuf->getVertexSize()); - - for (auto & r : indexRemap) - { - assert (r.first < oldBuf->getNumVertices()); - assert (r.second < newBuf->getNumVertices()); - - uchar* pSrc = static_cast(oldBufLock.pData) + r.first * vertexSize; - uchar* pDst = static_cast(newBufLock.pData) + r.second * vertexSize; - memcpy(pDst, pSrc, vertexSize); - } - } - - // Now create a new index buffer - HardwareIndexBufferSharedPtr ibuf = - HardwareBufferManager::getSingleton().createIndexBuffer( - id->indexBuffer->getType(), id->indexCount, - HardwareBuffer::HBU_STATIC); - - HardwareBufferLockGuard srcIndexLock(id->indexBuffer, - id->indexStart * id->indexBuffer->getIndexSize(), - id->indexCount * id->indexBuffer->getIndexSize(), - HardwareBuffer::HBL_READ_ONLY); - HardwareBufferLockGuard dstIndexLock(ibuf, HardwareBuffer::HBL_DISCARD); - if (use32bitIndexes) - { - uint32 *pSrc32 = static_cast(srcIndexLock.pData); - uint32 *pDst32 = static_cast(dstIndexLock.pData); - remapIndexes(pSrc32, pDst32, indexRemap, id->indexCount); - } - else - { - uint16 *pSrc16 = static_cast(srcIndexLock.pData); - uint16 *pDst16 = static_cast(dstIndexLock.pData); - remapIndexes(pSrc16, pDst16, indexRemap, id->indexCount); - } - srcIndexLock.unlock(); - dstIndexLock.unlock(); - - targetGeomLink->indexData = OGRE_NEW IndexData(); - targetGeomLink->indexData->indexStart = 0; - targetGeomLink->indexData->indexCount = id->indexCount; - targetGeomLink->indexData->indexBuffer = ibuf; - - // Store optimised geometry for deallocation later - OptimisedSubMeshGeometry *optGeom = OGRE_NEW OptimisedSubMeshGeometry(); - optGeom->indexData = targetGeomLink->indexData; - optGeom->vertexData = targetGeomLink->vertexData; - mOptimisedSubMeshGeometryList.push_back(optGeom); - } - //-------------------------------------------------------------------------- - void StaticGeometry::addSceneNode(const SceneNode* node) - { - if(node->getCreator()->getRootSceneNode()->_getFullTransform() != Affine3::IDENTITY) - { - // otherwise it is applied twice - LogManager::getSingleton().logError("StaticGeometry - Root SceneNode transform must be IDENTITY"); - } - - for (auto mobj : node->getAttachedObjects()) - { - if (mobj->getMovableType() == MOT_ENTITY) - { - addEntity(static_cast(mobj), - node->_getDerivedPosition(), - node->_getDerivedOrientation(), - node->_getDerivedScale()); - } - } - // Iterate through all the child-nodes - for (auto c : node->getChildren()) - { - // Add this subnode and its children... - addSceneNode( static_cast(c) ); - } - } - //-------------------------------------------------------------------------- - void StaticGeometry::build(void) - { - // Make sure there's nothing from previous builds - destroy(); - - // Firstly allocate meshes to regions - for (auto qsm : mQueuedSubMeshes) - { - Region* region = getRegion(qsm->worldBounds, true); - region->assign(qsm); - } - bool stencilShadows = false; - if (mCastShadows && mOwner->isShadowTechniqueStencilBased()) - { - stencilShadows = true; - } - - // Now tell each region to build itself - for (auto & ri : mRegionMap) - { - ri.second->build(stencilShadows); - - // Set the visibility flags on these regions - ri.second->setVisibilityFlags(mVisibilityFlags); - } - - } - //-------------------------------------------------------------------------- - void StaticGeometry::destroy(void) - { - // delete the regions - for (auto & i : mRegionMap) - { - mOwner->extractMovableObject(i.second); - OGRE_DELETE i.second; - } - mRegionMap.clear(); - } - //-------------------------------------------------------------------------- - void StaticGeometry::reset(void) - { - destroy(); - for (auto m : mQueuedSubMeshes) - { - OGRE_DELETE m; - } - mQueuedSubMeshes.clear(); - // Delete precached geoemtry lists - for (SubMeshGeometryLookup::iterator l = mSubMeshGeometryLookup.begin(); - l != mSubMeshGeometryLookup.end(); ++l) - { - OGRE_DELETE_T(l->second, SubMeshLodGeometryLinkList, MEMCATEGORY_GEOMETRY); - } - mSubMeshGeometryLookup.clear(); - // Delete optimised geometry - for (auto o : mOptimisedSubMeshGeometryList) - { - OGRE_DELETE o; - } - mOptimisedSubMeshGeometryList.clear(); - - } - //-------------------------------------------------------------------------- - void StaticGeometry::setVisible(bool visible) - { - mVisible = visible; - // tell any existing regions - for (auto & ri : mRegionMap) - { - ri.second->setVisible(visible); - } - } - //-------------------------------------------------------------------------- - void StaticGeometry::setCastShadows(bool castShadows) - { - mCastShadows = castShadows; - // tell any existing regions - for (auto & ri : mRegionMap) - { - ri.second->setCastShadows(castShadows); - } - - } - //-------------------------------------------------------------------------- - void StaticGeometry::setRenderQueueGroup(uint8 queueID) - { - assert(queueID <= RENDER_QUEUE_MAX && "Render queue out of range!"); - mRenderQueueIDSet = true; - mRenderQueueID = queueID; - // tell any existing regions - for (auto & ri : mRegionMap) - { - ri.second->setRenderQueueGroup(queueID); - } - } - //-------------------------------------------------------------------------- - uint8 StaticGeometry::getRenderQueueGroup(void) const - { - return mRenderQueueID; - } - //-------------------------------------------------------------------------- - void StaticGeometry::setVisibilityFlags(uint32 flags) - { - mVisibilityFlags = flags; - for (RegionMap::const_iterator ri = mRegionMap.begin(); - ri != mRegionMap.end(); ++ri) - { - ri->second->setVisibilityFlags(flags); - } - } - //-------------------------------------------------------------------------- - uint32 StaticGeometry::getVisibilityFlags() const - { - if(mRegionMap.empty()) - return MovableObject::getDefaultVisibilityFlags(); - - RegionMap::const_iterator ri = mRegionMap.begin(); - return ri->second->getVisibilityFlags(); - } - //-------------------------------------------------------------------------- - std::ostream& operator<<(std::ostream& o, const StaticGeometry& g) - { - o << "Static Geometry Report for " << g.mName << std::endl; - o << "-------------------------------------------------" << std::endl; - o << "Number of queued submeshes: " << g.mQueuedSubMeshes.size() << std::endl; - o << "Number of regions: " << g.mRegionMap.size() << std::endl; - o << "Region dimensions: " << g.mRegionDimensions << std::endl; - o << "Origin: " << g.mOrigin << std::endl; - o << "Max distance: " << g.mUpperDistance << std::endl; - o << "Casts shadows?: " << g.mCastShadows << std::endl; - o << std::endl; - for (auto ri : g.mRegionMap) - { - o << *ri.second; - } - o << "-------------------------------------------------" << std::endl; - return o; - } - //--------------------------------------------------------------------- - void StaticGeometry::visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables) - { - for (RegionMap::const_iterator ri = mRegionMap.begin(); - ri != mRegionMap.end(); ++ri) - { - ri->second->visitRenderables(visitor, debugRenderables); - } - - } - //-------------------------------------------------------------------------- - StaticGeometry::RegionIterator StaticGeometry::getRegionIterator(void) - { - return RegionIterator(mRegionMap.begin(), mRegionMap.end()); - } - //-------------------------------------------------------------------------- - //-------------------------------------------------------------------------- - StaticGeometry::Region::Region(StaticGeometry* parent, const String& name, - SceneManager* mgr, uint32 regionID, const Vector3& centre) - : MovableObject(name), mParent(parent), - mRegionID(regionID), mCentre(centre), mBoundingRadius(0.0f), - mCurrentLod(0), mLodStrategy(0), mCamera(0), mSquaredViewDepth(0) - { - mManager = mgr; - } - //-------------------------------------------------------------------------- - StaticGeometry::Region::~Region() - { - if (mParentNode) - { - mManager->destroySceneNode(static_cast(mParentNode)); - mParentNode = 0; - } - // delete - for (auto & i : mLodBucketList) - { - OGRE_DELETE i; - } - mLodBucketList.clear(); - - // no need to delete queued meshes, these are managed in StaticGeometry - - } - //----------------------------------------------------------------------- - void StaticGeometry::Region::_releaseManualHardwareResources() - { - for (auto & i : mLodBucketList) - { - clearShadowRenderableList(i->getShadowRenderableList()); - } - } - //----------------------------------------------------------------------- - void StaticGeometry::Region::_restoreManualHardwareResources() - { - // shadow renderables are lazy initialized - } - //-------------------------------------------------------------------------- - uint32 StaticGeometry::Region::getTypeFlags(void) const - { - return SceneManager::STATICGEOMETRY_TYPE_MASK; - } - //-------------------------------------------------------------------------- - void StaticGeometry::Region::assign(QueuedSubMesh* qmesh) - { - mQueuedSubMeshes.push_back(qmesh); - - // Set/check LOD strategy - const LodStrategy *lodStrategy = qmesh->submesh->parent->getLodStrategy(); - if (mLodStrategy == 0) - { - mLodStrategy = lodStrategy; - - // First LOD mandatory, and always from base LOD value - mLodValues.push_back(mLodStrategy->getBaseValue()); - } - else - { - if (mLodStrategy != lodStrategy) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Lod strategies do not match", - "StaticGeometry::Region::assign"); - } - - // update LOD values - ushort lodLevels = qmesh->submesh->parent->getNumLodLevels(); - assert(qmesh->geometryLodList->size() == lodLevels); - - while(mLodValues.size() < lodLevels) - { - mLodValues.push_back(0.0f); - } - // Make sure LOD levels are max of all at the requested level - for (ushort lod = 1; lod < lodLevels; ++lod) - { - const MeshLodUsage& meshLod = - qmesh->submesh->parent->getLodLevel(lod); - mLodValues[lod] = std::max(mLodValues[lod], - meshLod.value); - } - - // update bounds - // Transform world bounds relative to our centre - AxisAlignedBox localBounds( - qmesh->worldBounds.getMinimum() - mCentre, - qmesh->worldBounds.getMaximum() - mCentre); - mAABB.merge(localBounds); - mBoundingRadius = Math::boundingRadiusFromAABB(mAABB); - - } - //-------------------------------------------------------------------------- - void StaticGeometry::Region::build(bool stencilShadows) - { - // Create a node - mManager->getRootSceneNode()->createChildSceneNode(mCentre)->attachObject(this); - // We need to create enough LOD buckets to deal with the highest LOD - // we encountered in all the meshes queued - for (ushort lod = 0; lod < mLodValues.size(); ++lod) - { - LODBucket* lodBucket = - OGRE_NEW LODBucket(this, lod, mLodValues[lod]); - mLodBucketList.push_back(lodBucket); - // Now iterate over the meshes and assign to LODs - // LOD bucket will pick the right LOD to use - QueuedSubMeshList::iterator qi, qiend; - qiend = mQueuedSubMeshes.end(); - for (qi = mQueuedSubMeshes.begin(); qi != qiend; ++qi) - { - lodBucket->assign(*qi, lod); - } - // now build - lodBucket->build(stencilShadows); - } - - - - } - //-------------------------------------------------------------------------- - const String& StaticGeometry::Region::getMovableType(void) const - { - return MOT_STATIC_GEOMETRY; - } - //-------------------------------------------------------------------------- - void StaticGeometry::Region::_notifyCurrentCamera(Camera* cam) - { - // Set camera - mCamera = cam; - - // Cache squared view depth for use by GeometryBucket - mSquaredViewDepth = mParentNode->getSquaredViewDepth(cam->getLodCamera()); - - // No LOD strategy set yet, skip (this indicates that there are no submeshes) - if (mLodStrategy == 0) - return; - - // Determine whether to still render - mBeyondFarDistance = false; - - Real renderingDist = mParent->getRenderingDistance(); - if (renderingDist > 0 && cam->getUseRenderingDistance()) - { - // Max distance to still render - Real maxDist = renderingDist + mBoundingRadius; - if (mSquaredViewDepth > Math::Sqr(maxDist)) - { - mBeyondFarDistance = true; - return; - } - } - - // Sanity check - assert(!mLodValues.empty()); - - // Calculate LOD value - Real lodValue = mLodStrategy->getValue(this, cam); - - // Store LOD value for this strategy - mLodValue = lodValue; - - // Get LOD index - mCurrentLod = mLodStrategy->getIndex(lodValue, mLodValues); - } - //-------------------------------------------------------------------------- - const AxisAlignedBox& StaticGeometry::Region::getBoundingBox(void) const - { - return mAABB; - } - //-------------------------------------------------------------------------- - Real StaticGeometry::Region::getBoundingRadius(void) const - { - return mBoundingRadius; - } - //-------------------------------------------------------------------------- - void StaticGeometry::Region::_updateRenderQueue(RenderQueue* queue) - { - mLodBucketList[mCurrentLod]->addRenderables(queue, mRenderQueueID, - mLodValue); - } - //--------------------------------------------------------------------- - void StaticGeometry::Region::visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables) - { - for (auto & i : mLodBucketList) - { - i->visitRenderables(visitor, debugRenderables); - } - - } - //-------------------------------------------------------------------------- - bool StaticGeometry::Region::isVisible(void) const - { - if(!mVisible || mBeyondFarDistance) - return false; - - SceneManager* sm = Root::getSingleton()._getCurrentSceneManager(); - if (sm && !(mVisibilityFlags & sm->_getCombinedVisibilityMask())) - return false; - - return true; - } - //-------------------------------------------------------------------------- - StaticGeometry::Region::LODIterator - StaticGeometry::Region::getLODIterator(void) - { - return LODIterator(mLodBucketList.begin(), mLodBucketList.end()); - } - //--------------------------------------------------------------------- - const ShadowRenderableList& StaticGeometry::Region::getShadowVolumeRenderableList( - const Light* light, const HardwareIndexBufferPtr& indexBuffer, size_t& indexBufferUsedSize, - float extrusionDistance, int flags) - { - // Calculate the object space light details - Vector4 lightPos = light->getAs4DVector(); - Affine3 world2Obj = mParentNode->_getFullTransform().inverse(); - lightPos = world2Obj * lightPos; - Matrix3 world2Obj3x3 = world2Obj.linear(); - extrusionDistance *= Math::Sqrt(std::min(std::min(world2Obj3x3.GetColumn(0).squaredLength(), world2Obj3x3.GetColumn(1).squaredLength()), world2Obj3x3.GetColumn(2).squaredLength())); - - // per-LOD shadow lists & edge data - mLodBucketList[mCurrentLod]->updateShadowRenderables(lightPos, indexBuffer, - extrusionDistance, flags); - - EdgeData* edgeList = mLodBucketList[mCurrentLod]->getEdgeList(); - ShadowRenderableList& shadowRendList = mLodBucketList[mCurrentLod]->getShadowRenderableList(); - - // Calc triangle light facing - updateEdgeListLightFacing(edgeList, lightPos); - - // Generate indexes and update renderables - generateShadowVolume(edgeList, indexBuffer, indexBufferUsedSize, light, shadowRendList, flags); - - return shadowRendList; - - } - //-------------------------------------------------------------------------- - EdgeData* StaticGeometry::Region::getEdgeList(void) - { - return mLodBucketList[mCurrentLod]->getEdgeList(); - } - //-------------------------------------------------------------------------- - std::ostream& operator<<(std::ostream& o, const StaticGeometry::Region& r) - { - o << "Region " << r.mRegionID << std::endl; - o << "--------------------------" << std::endl; - o << "Centre: " << r.mCentre << std::endl; - o << "Local AABB: " << r.mAABB << std::endl; - o << "Bounding radius: " << r.mBoundingRadius << std::endl; - o << "Number of LODs: " << r.mLodBucketList.size() << std::endl; - - for (auto i : r.mLodBucketList) - { - o << *i; - } - o << "--------------------------" << std::endl; - return o; - } - //-------------------------------------------------------------------------- - //-------------------------------------------------------------------------- - StaticGeometry::LODBucket::LODBucket(Region* parent, unsigned short lod, - Real lodValue) - : mParent(parent), mLod(lod), mLodValue(lodValue), mEdgeList(0) - , mVertexProgramInUse(false) - { - } - //-------------------------------------------------------------------------- - StaticGeometry::LODBucket::~LODBucket() - { - OGRE_DELETE mEdgeList; - ShadowCaster::clearShadowRenderableList(mShadowRenderables); - // delete - for (auto & i : mMaterialBucketMap) - { - OGRE_DELETE i.second; - } - mMaterialBucketMap.clear(); - for(auto & qi : mQueuedGeometryList) - { - OGRE_DELETE qi; - } - mQueuedGeometryList.clear(); - - // no need to delete queued meshes, these are managed in StaticGeometry - } - //-------------------------------------------------------------------------- - void StaticGeometry::LODBucket::assign(QueuedSubMesh* qmesh, ushort atLod) - { - QueuedGeometry* q = OGRE_NEW QueuedGeometry(); - mQueuedGeometryList.push_back(q); - q->position = qmesh->position; - q->orientation = qmesh->orientation; - q->scale = qmesh->scale; - if (qmesh->geometryLodList->size() > atLod) - { - // This submesh has enough lods, use the right one - q->geometry = &(*qmesh->geometryLodList)[atLod]; - } - else - { - // Not enough lods, use the lowest one we have - q->geometry = - &(*qmesh->geometryLodList)[qmesh->geometryLodList->size() - 1]; - } - // Locate a material bucket - MaterialBucket* mbucket = 0; - MaterialBucketMap::iterator m = - mMaterialBucketMap.find(qmesh->material->getName()); - if (m != mMaterialBucketMap.end()) - { - mbucket = m->second; - } - else - { - mbucket = OGRE_NEW MaterialBucket(this, qmesh->material); - mMaterialBucketMap[qmesh->material->getName()] = mbucket; - } - mbucket->assign(q); - } - //-------------------------------------------------------------------------- - void StaticGeometry::LODBucket::build(bool stencilShadows) - { - - EdgeListBuilder eb; - size_t vertexSet = 0; - - // Just pass this on to child buckets - for (auto & i : mMaterialBucketMap) - { - MaterialBucket* mat = i.second; - - mat->build(stencilShadows); - - if (stencilShadows) - { - // Check if we have vertex programs here - Technique* t = mat->getMaterial()->getBestTechnique(); - if (t) - { - Pass* p = t->getPass(0); - if (p) - { - if (p->hasVertexProgram()) - { - mVertexProgramInUse = true; - } - } - } - - for (GeometryBucket* geom : mat->getGeometryList()) - { - // Check we're dealing with 16-bit indexes here - // Since stencil shadows can only deal with 16-bit - // More than that and stencil is probably too CPU-heavy - // in any case - assert(geom->getIndexData()->indexBuffer->getType() - == HardwareIndexBuffer::IT_16BIT && - "Only 16-bit indexes allowed when using stencil shadows"); - eb.addVertexData(geom->getVertexData()); - eb.addIndexData(geom->getIndexData(), vertexSet++); - } - - } - } - - if (stencilShadows) - { - mEdgeList = eb.build(); - } - } - //-------------------------------------------------------------------------- - void StaticGeometry::LODBucket::addRenderables(RenderQueue* queue, - uint8 group, Real lodValue) - { - // Just pass this on to child buckets - MaterialBucketMap::iterator i, iend; - iend = mMaterialBucketMap.end(); - for (i = mMaterialBucketMap.begin(); i != iend; ++i) - { - i->second->addRenderables(queue, group, lodValue); - } - } - //-------------------------------------------------------------------------- - StaticGeometry::LODBucket::MaterialIterator - StaticGeometry::LODBucket::getMaterialIterator(void) - { - return MaterialIterator( - mMaterialBucketMap.begin(), mMaterialBucketMap.end()); - } - //-------------------------------------------------------------------------- - std::ostream& operator<<(std::ostream& o, const StaticGeometry::LODBucket& b) - { - o << "LOD Bucket " << b.mLod << std::endl; - o << "------------------" << std::endl; - o << "LOD Value: " << b.mLodValue << std::endl; - o << "Number of Materials: " << b.mMaterialBucketMap.size() << std::endl; - for (const auto & i : b.mMaterialBucketMap) - { - o << *i.second; - } - o << "------------------" << std::endl; - return o; - } - //--------------------------------------------------------------------- - void StaticGeometry::LODBucket::visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables) - { - for (MaterialBucketMap::const_iterator i = mMaterialBucketMap.begin(); - i != mMaterialBucketMap.end(); ++i) - { - i->second->visitRenderables(visitor, debugRenderables); - } - - } - //--------------------------------------------------------------------- - void StaticGeometry::LODBucket::updateShadowRenderables(const Vector4& lightPos, - const HardwareIndexBufferPtr& indexBuffer, - Real extrusionDistance, int flags) - { - assert(indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT && - "Only 16-bit indexes supported for now"); - - // We need to search the edge list for silhouette edges - OgreAssert(mEdgeList, "You enabled stencil shadows after the build process!"); - - // Init shadow renderable list if required - bool init = mShadowRenderables.empty(); - bool extrude = flags & SRF_EXTRUDE_IN_SOFTWARE; - - EdgeData::EdgeGroupList::iterator egi; - ShadowCaster::ShadowRenderableList::iterator si, siend; - if (init) - mShadowRenderables.resize(mEdgeList->edgeGroups.size()); - - siend = mShadowRenderables.end(); - egi = mEdgeList->edgeGroups.begin(); - for (si = mShadowRenderables.begin(); si != siend; ++si, ++egi) - { - if (init) - { - // Create a new renderable, create a separate light cap if - // we're using a vertex program (either for this model, or - // for extruding the shadow volume) since otherwise we can - // get depth-fighting on the light cap - - *si = OGRE_NEW ShadowRenderable(mParent, indexBuffer, egi->vertexData, - mVertexProgramInUse || !extrude); - } - // Extrude vertices in software if required - if (extrude) - { - mParent->extrudeVertices((*si)->getPositionBuffer(), egi->vertexData->vertexCount, lightPos, - extrusionDistance); - } - } - } - //-------------------------------------------------------------------------- - //-------------------------------------------------------------------------- - StaticGeometry::MaterialBucket::MaterialBucket(LODBucket* parent, - const MaterialPtr& material) - : mParent(parent) - , mMaterial(material) - , mTechnique(0) - { - } - //-------------------------------------------------------------------------- - StaticGeometry::MaterialBucket::~MaterialBucket() - { - // delete - for (auto & i : mGeometryBucketList) - { - OGRE_DELETE i; - } - mGeometryBucketList.clear(); - - // no need to delete queued meshes, these are managed in StaticGeometry - } - //-------------------------------------------------------------------------- - static uint32 getHash(StaticGeometry::SubMeshLodGeometryLink* geom) - { - // Formulate an identifying string for the geometry format - // Must take into account the vertex declaration and the index type - // Format is: - // Index type - // Vertex element (repeating) - // source - // semantic - // type - uint32 hash = HashCombine(0, geom->indexData->indexBuffer->getType()); - const auto& elemList = geom->vertexData->vertexDeclaration->getElements(); - for (const VertexElement& elem : elemList) - { - hash = HashCombine(hash, elem.getSource()); - hash = HashCombine(hash, elem.getSemantic()); - hash = HashCombine(hash, elem.getType()); - } - - return hash; - } - //-------------------------------------------------------------------------- - void StaticGeometry::MaterialBucket::assign(QueuedGeometry* qgeom) - { - // Look up any current geometry - uint32 hash = getHash(qgeom->geometry); - CurrentGeometryMap::iterator gi = mCurrentGeometryMap.find(hash); - bool newBucket = true; - if (gi != mCurrentGeometryMap.end()) - { - // Found existing geometry, try to assign - newBucket = !gi->second->assign(qgeom); - // Note that this bucket will be replaced as the 'current' - // for this hash string below since it's out of space - } - // Do we need to create a new one? - if (newBucket) - { - GeometryBucket* gbucket = - OGRE_NEW GeometryBucket(this, qgeom->geometry->vertexData, qgeom->geometry->indexData); - // Add to main list - mGeometryBucketList.push_back(gbucket); - // Also index in 'current' list - mCurrentGeometryMap[hash] = gbucket; - if (!gbucket->assign(qgeom)) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Somehow we couldn't fit the requested geometry even in a " - "brand new GeometryBucket!! Must be a bug, please report.", - "StaticGeometry::MaterialBucket::assign"); - } - } - } - //-------------------------------------------------------------------------- - void StaticGeometry::MaterialBucket::build(bool stencilShadows) - { - mTechnique = 0; - mMaterial->load(); - // tell the geometry buckets to build - for (auto gb : mGeometryBucketList) - { - gb->build(stencilShadows); - } - } - //-------------------------------------------------------------------------- - void StaticGeometry::MaterialBucket::addRenderables(RenderQueue* queue, - uint8 group, Real lodValue) - { - // Get region - Region *region = mParent->getParent(); - - // Get material LOD strategy - const LodStrategy *materialLodStrategy = mMaterial->getLodStrategy(); - - // If material strategy doesn't match, recompute LOD value with correct strategy - if (materialLodStrategy != region->mLodStrategy) - lodValue = materialLodStrategy->getValue(region, region->mCamera); - - // Determine the current material technique - mTechnique = mMaterial->getBestTechnique( - mMaterial->getLodIndex(lodValue)); - GeometryBucketList::iterator i, iend; - iend = mGeometryBucketList.end(); - for (i = mGeometryBucketList.begin(); i != iend; ++i) - { - queue->addRenderable(*i, group); - } - - } - void StaticGeometry::MaterialBucket::_setMaterial(const MaterialPtr& material) - { - OgreAssert(material, "NULL pointer"); - mMaterial = material; - mMaterial->load(); - } - //-------------------------------------------------------------------------- - StaticGeometry::MaterialBucket::GeometryIterator - StaticGeometry::MaterialBucket::getGeometryIterator(void) - { - return GeometryIterator( - mGeometryBucketList.begin(), mGeometryBucketList.end()); - } - //-------------------------------------------------------------------------- - std::ostream& operator<<(std::ostream& o, const StaticGeometry::MaterialBucket& b) - { - o << "Material Bucket " << b.getMaterialName() << std::endl; - o << "--------------------------------------------------" << std::endl; - o << "Geometry buckets: " << b.mGeometryBucketList.size() << std::endl; - for (auto i : b.mGeometryBucketList) - { - o << *i; - } - o << "--------------------------------------------------" << std::endl; - return o; - } - //--------------------------------------------------------------------- - void StaticGeometry::MaterialBucket::visitRenderables(Renderable::Visitor* visitor, - bool debugRenderables) - { - for (auto i : mGeometryBucketList) - { - visitor->visit(i, mParent->getLod(), false); - } - - } - //-------------------------------------------------------------------------- - //-------------------------------------------------------------------------- - StaticGeometry::GeometryBucket::GeometryBucket(MaterialBucket* parent, const VertexData* vData, - const IndexData* iData) - : Renderable(), mParent(parent) - { - // Clone the structure from the example - mVertexData = vData->clone(false); - mIndexData = iData->clone(false); - mVertexData->vertexCount = 0; - mVertexData->vertexStart = 0; - mIndexData->indexCount = 0; - mIndexData->indexStart = 0; - // Derive the max vertices - if (iData->indexBuffer->getType() == HardwareIndexBuffer::IT_32BIT) - { - mMaxVertexIndex = 0xFFFFFFFF; - } - else - { - mMaxVertexIndex = 0xFFFF; - } - - // Check to see if we have blend indices / blend weights - // remove them if so, they can try to blend non-existent bones! - const VertexElement* blendIndices = - mVertexData->vertexDeclaration->findElementBySemantic(VES_BLEND_INDICES); - const VertexElement* blendWeights = - mVertexData->vertexDeclaration->findElementBySemantic(VES_BLEND_WEIGHTS); - if (blendIndices && blendWeights) - { - assert(blendIndices->getSource() == blendWeights->getSource() - && "Blend indices and weights should be in the same buffer"); - // Get the source - ushort source = blendIndices->getSource(); - assert(blendIndices->getSize() + blendWeights->getSize() == - mVertexData->vertexBufferBinding->getBuffer(source)->getVertexSize() - && "Blend indices and blend buffers should have buffer to themselves!"); - // Unset the buffer - mVertexData->vertexBufferBinding->unsetBinding(source); - // Remove the elements - mVertexData->vertexDeclaration->removeElement(VES_BLEND_INDICES); - mVertexData->vertexDeclaration->removeElement(VES_BLEND_WEIGHTS); - // Close gaps in bindings for effective and safely - mVertexData->closeGapsInBindings(); - } - - - } - //-------------------------------------------------------------------------- - StaticGeometry::GeometryBucket::~GeometryBucket() - { - OGRE_DELETE mVertexData; - OGRE_DELETE mIndexData; - } - //-------------------------------------------------------------------------- - const MaterialPtr& StaticGeometry::GeometryBucket::getMaterial(void) const - { - return mParent->getMaterial(); - } - //-------------------------------------------------------------------------- - Technique* StaticGeometry::GeometryBucket::getTechnique(void) const - { - return mParent->getCurrentTechnique(); - } - //-------------------------------------------------------------------------- - void StaticGeometry::GeometryBucket::getRenderOperation(RenderOperation& op) - { - op.indexData = mIndexData; - op.operationType = RenderOperation::OT_TRIANGLE_LIST; - op.srcRenderable = this; - op.useIndexes = true; - op.vertexData = mVertexData; - } - //-------------------------------------------------------------------------- - void StaticGeometry::GeometryBucket::getWorldTransforms(Matrix4* xform) const - { - // Should be the identity transform, but lets allow transformation of the - // nodes the regions are attached to for kicks - *xform = mParent->getParent()->getParent()->_getParentNodeFullTransform(); - } - //-------------------------------------------------------------------------- - Real StaticGeometry::GeometryBucket::getSquaredViewDepth(const Camera* cam) const - { - const Region *region = mParent->getParent()->getParent(); - if (cam == region->mCamera) - return region->mSquaredViewDepth; - else - return region->getParentNode()->getSquaredViewDepth(cam->getLodCamera()); - } - //-------------------------------------------------------------------------- - const LightList& StaticGeometry::GeometryBucket::getLights(void) const - { - return mParent->getParent()->getParent()->queryLights(); - } - //-------------------------------------------------------------------------- - bool StaticGeometry::GeometryBucket::getCastsShadows(void) const - { - return mParent->getParent()->getParent()->getCastShadows(); - } - //-------------------------------------------------------------------------- - bool StaticGeometry::GeometryBucket::assign(QueuedGeometry* qgeom) - { - // Do we have enough space? - // -2 first to avoid overflow (-1 to adjust count to index, -1 to ensure - // no overflow at 32 bits and use >= instead of >) - if ((mVertexData->vertexCount - 2 + qgeom->geometry->vertexData->vertexCount) - >= mMaxVertexIndex) - { - return false; - } - - mQueuedGeometry.push_back(qgeom); - mVertexData->vertexCount += qgeom->geometry->vertexData->vertexCount; - mIndexData->indexCount += qgeom->geometry->indexData->indexCount; - - return true; - } - //-------------------------------------------------------------------------- - template - static void copyIndexes(const T* src, T* dst, size_t count, uint32 indexOffset) - { - if (indexOffset == 0) - { - memcpy(dst, src, sizeof(T) * count); - } - else - { - while(count--) - { - *dst++ = static_cast(*src++ + indexOffset); - } - } - } - void StaticGeometry::GeometryBucket::build(bool stencilShadows) - { - // Need to double the vertex count for the position buffer - // if we're doing stencil shadows - OgreAssert(!stencilShadows || mVertexData->vertexCount * 2 <= mMaxVertexIndex, - "Index range exceeded when using stencil shadows, consider reducing your region size or " - "reducing poly count"); - - // Ok, here's where we transfer the vertices and indexes to the shared - // buffers - // Shortcuts - VertexDeclaration* dcl = mVertexData->vertexDeclaration; - VertexBufferBinding* binds = mVertexData->vertexBufferBinding; - - // create index buffer, and lock - auto indexType = mIndexData->indexBuffer->getType(); - mIndexData->indexBuffer = HardwareBufferManager::getSingleton() - .createIndexBuffer(indexType, mIndexData->indexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - HardwareBufferLockGuard dstIndexLock(mIndexData->indexBuffer, HardwareBuffer::HBL_DISCARD); - uint32* p32Dest = static_cast(dstIndexLock.pData); - uint16* p16Dest = static_cast(dstIndexLock.pData); - // create all vertex buffers, and lock - ushort b; - - std::vector destBufferLocks; - std::vector bufferElements; - for (b = 0; b < binds->getBufferCount(); ++b) - { - HardwareVertexBufferSharedPtr vbuf = - HardwareBufferManager::getSingleton().createVertexBuffer( - dcl->getVertexSize(b), - mVertexData->vertexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - binds->setBinding(b, vbuf); - uchar* pLock = static_cast( - vbuf->lock(HardwareBuffer::HBL_DISCARD)); - destBufferLocks.push_back(pLock); - // Pre-cache vertex elements per buffer - bufferElements.push_back(dcl->findElementsBySource(b)); - } - - - // Iterate over the geometry items - uint32 indexOffset = 0; - QueuedGeometryList::iterator gi, giend; - giend = mQueuedGeometry.end(); - Vector3 regionCentre = mParent->getParent()->getParent()->getCentre(); - for (gi = mQueuedGeometry.begin(); gi != giend; ++gi) - { - QueuedGeometry* geom = *gi; - // Copy indexes across with offset - IndexData* srcIdxData = geom->geometry->indexData; - HardwareBufferLockGuard srcIdxLock(srcIdxData->indexBuffer, - srcIdxData->indexStart * srcIdxData->indexBuffer->getIndexSize(), - srcIdxData->indexCount * srcIdxData->indexBuffer->getIndexSize(), - HardwareBuffer::HBL_READ_ONLY); - if (indexType == HardwareIndexBuffer::IT_32BIT) - { - uint32* pSrc = static_cast(srcIdxLock.pData); - copyIndexes(pSrc, p32Dest, srcIdxData->indexCount, indexOffset); - p32Dest += srcIdxData->indexCount; - } - else - { - // Lock source indexes - uint16* pSrc = static_cast(srcIdxLock.pData); - copyIndexes(pSrc, p16Dest, srcIdxData->indexCount, indexOffset); - p16Dest += srcIdxData->indexCount; - } - srcIdxLock.unlock(); - - // Now deal with vertex buffers - // we can rely on buffer counts / formats being the same - VertexData* srcVData = geom->geometry->vertexData; - VertexBufferBinding* srcBinds = srcVData->vertexBufferBinding; - for (b = 0; b < binds->getBufferCount(); ++b) - { - // lock source - HardwareVertexBufferSharedPtr srcBuf = srcBinds->getBuffer(b); - HardwareBufferLockGuard srcBufLock(srcBuf, HardwareBuffer::HBL_READ_ONLY); - uchar* pSrcBase = static_cast(srcBufLock.pData); - // Get buffer lock pointer, we'll update this later - uchar* pDstBase = destBufferLocks[b]; - size_t bufInc = srcBuf->getVertexSize(); - - // Iterate over vertices - float *pSrcReal, *pDstReal; - Vector3 tmp; - for (size_t v = 0; v < srcVData->vertexCount; ++v) - { - // Iterate over vertex elements - VertexDeclaration::VertexElementList& elems = - bufferElements[b]; - VertexDeclaration::VertexElementList::iterator ei; - for (ei = elems.begin(); ei != elems.end(); ++ei) - { - VertexElement& elem = *ei; - elem.baseVertexPointerToElement(pSrcBase, &pSrcReal); - elem.baseVertexPointerToElement(pDstBase, &pDstReal); - switch (elem.getSemantic()) - { - case VES_POSITION: - tmp.x = *pSrcReal++; - tmp.y = *pSrcReal++; - tmp.z = *pSrcReal++; - // transform - tmp = (geom->orientation * (tmp * geom->scale)) + - geom->position; - // Adjust for region centre - tmp -= regionCentre; - *pDstReal++ = tmp.x; - *pDstReal++ = tmp.y; - *pDstReal++ = tmp.z; - break; - case VES_NORMAL: - case VES_TANGENT: - case VES_BINORMAL: - tmp.x = *pSrcReal++; - tmp.y = *pSrcReal++; - tmp.z = *pSrcReal++; - // scale (invert) - tmp = tmp / geom->scale; - tmp.normalise(); - // rotation - tmp = geom->orientation * tmp; - *pDstReal++ = tmp.x; - *pDstReal++ = tmp.y; - *pDstReal++ = tmp.z; - // copy parity for tangent. - if (elem.getType() == Ogre::VET_FLOAT4) - *pDstReal = *pSrcReal; - break; - default: - // just raw copy - memcpy(pDstReal, pSrcReal, - VertexElement::getTypeSize(elem.getType())); - break; - }; - - } - - // Increment both pointers - pDstBase += bufInc; - pSrcBase += bufInc; - - } - - // Update pointer - destBufferLocks[b] = pDstBase; - } - - indexOffset += geom->geometry->vertexData->vertexCount; - } - - // Unlock everything - dstIndexLock.unlock(); - for (b = 0; b < binds->getBufferCount(); ++b) - { - binds->getBuffer(b)->unlock(); - } - - if (stencilShadows) - { - mVertexData->prepareForShadowVolume(); - } - } - //-------------------------------------------------------------------------- - std::ostream& operator<<(std::ostream& o, const StaticGeometry::GeometryBucket& b) - { - o << "Geometry Bucket" << std::endl; - o << "---------------" << std::endl; - o << "Geometry items: " << b.mQueuedGeometry.size() << std::endl; - o << "Vertex count: " << b.mVertexData->vertexCount << std::endl; - o << "Index count: " << b.mIndexData->indexCount << std::endl; - o << "---------------" << std::endl; - return o; - } - //-------------------------------------------------------------------------- - const String MOT_STATIC_GEOMETRY = "StaticGeometry"; -} - diff --git a/OgreMain/src/OgreStreamSerialiser.cpp b/OgreMain/src/OgreStreamSerialiser.cpp deleted file mode 100644 index a634587bd40..00000000000 --- a/OgreMain/src/OgreStreamSerialiser.cpp +++ /dev/null @@ -1,870 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreStreamSerialiser.h" -#include "OgreDeflate.h" - -namespace Ogre -{ - /** General hash function, derived from here - http://www.azillionmonkeys.com/qed/hash.html - Original by Paul Hsieh - */ - static uint32 SuperFastHash (const char * data, int len, uint32 hashSoFar) - { -#if OGRE_ENDIAN == OGRE_ENDIAN_LITTLE -# define OGRE_GET16BITS(d) (*((const uint16 *) (d))) -#else - // Cast to uint16 in little endian means first byte is least significant - // replicate that here -# define OGRE_GET16BITS(d) (*((const uint8 *) (d)) + (*((const uint8 *) (d+1))<<8)) -#endif - uint32 hash; - int rem; - - if (hashSoFar) - hash = hashSoFar; - else - hash = len; - - if (len <= 0 || data == NULL) return 0; - - rem = len & 3; - len >>= 2; - - /* Main loop */ - for (;len > 0; len--) { - hash += OGRE_GET16BITS (data); - uint32 tmp = (OGRE_GET16BITS (data+2) << 11) ^ hash; - hash = (hash << 16) ^ tmp; - data += 2*sizeof (uint16); - hash += hash >> 11; - } - - /* Handle end cases */ - switch (rem) { - case 3: hash += OGRE_GET16BITS (data); - hash ^= hash << 16; - hash ^= data[sizeof (uint16)] << 18; - hash += hash >> 11; - break; - case 2: hash += OGRE_GET16BITS (data); - hash ^= hash << 11; - hash += hash >> 17; - break; - case 1: hash += *data; - hash ^= hash << 10; - hash += hash >> 1; - } - - /* Force "avalanching" of final 127 bits */ - hash ^= hash << 3; - hash += hash >> 5; - hash ^= hash << 4; - hash += hash >> 17; - hash ^= hash << 25; - hash += hash >> 6; - - return hash; -#undef OGRE_GET16BITS - } - - //--------------------------------------------------------------------- - uint32 StreamSerialiser::HEADER_ID = 0x00000001; - uint32 StreamSerialiser::REVERSE_HEADER_ID = 0x10000000; - uint32 StreamSerialiser::CHUNK_HEADER_SIZE = - sizeof(uint32) + // id - sizeof(uint16) + // version - sizeof(uint32) + // length - sizeof(uint32); // checksum - //--------------------------------------------------------------------- - StreamSerialiser::StreamSerialiser(const DataStreamPtr& stream, Endian endianMode, - bool autoHeader, RealStorageFormat realFormat) - : mStream(stream) - , mEndian(endianMode) - , mFlipEndian(false) - , mReadWriteHeader(autoHeader) - , mRealFormat(realFormat) - { - if (mEndian != ENDIAN_AUTO) - { -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - if (mEndian == ENDIAN_LITTLE) - mFlipEndian = true; -#else - if (mEndian == ENDIAN_BIG) - mFlipEndian = true; -#endif - - } - - OgreAssert(mStream, "Stream is null"); - } - //--------------------------------------------------------------------- - StreamSerialiser::~StreamSerialiser() - { - // really this should be empty if read/write was complete, but be tidy - if (!mChunkStack.empty()) - { - LogManager::getSingleton().stream(LML_WARNING) << - "Warning: stream " << mStream->getName() << " was not fully read / written; " << - mChunkStack.size() << " chunks remain unterminated."; - } - for (auto & i : mChunkStack) - delete i; - mChunkStack.clear(); - - } - //--------------------------------------------------------------------- - uint32 StreamSerialiser::makeIdentifier(const char (&code)[5]) - { - uint32 ret = 0; - for (size_t i = 0; i < 4; ++i) - { - ret += (code[i] << (i * 8)); - } - return ret; - - } - //--------------------------------------------------------------------- - uint32 StreamSerialiser::getCurrentChunkID() const - { - if (mChunkStack.empty()) - return 0; - else - return mChunkStack.back()->id; - } - //--------------------------------------------------------------------- - const StreamSerialiser::Chunk* StreamSerialiser::readChunkBegin() - { - // Have we figured out the endian mode yet? - if (mReadWriteHeader) - readHeader(); - - OgreAssert(mEndian != ENDIAN_AUTO, - "Endian mode has not been determined, did you disable header without setting?"); - - Chunk* chunk = readChunkImpl(); - mChunkStack.push_back(chunk); - - return chunk; - - } - //--------------------------------------------------------------------- - const StreamSerialiser::Chunk* StreamSerialiser::readChunkBegin( - uint32 id, uint16 maxVersion, const String& msg) - { - const Chunk* c = readChunkBegin(); - if (c->id != id) - { - // rewind - undoReadChunk(c->id); - return 0; - } - else if (c->version > maxVersion) - { - LogManager::getSingleton().stream(LML_CRITICAL) << "Error: " << msg - << " : Data version is " << c->version << " but this software can only read " - << "up to version " << maxVersion; - // skip - readChunkEnd(c->id); - return 0; - } - - return c; - - } - //--------------------------------------------------------------------- - void StreamSerialiser::undoReadChunk(uint32 id) - { - Chunk* c = popChunk(id); - - OgreAssert(mStream, "Stream is null"); - - mStream->seek(c->offset); - - OGRE_DELETE c; - - } - //--------------------------------------------------------------------- - uint32 StreamSerialiser::peekNextChunkID() - { - OgreAssert(mStream, "Stream is null"); - - if (eof()) - return 0; - - // Have we figured out the endian mode yet? - if (mReadWriteHeader) - readHeader(); - - OgreAssert(mEndian != ENDIAN_AUTO, - "Endian mode has not been determined, did you disable header without setting?"); - - size_t homePos = mStream->tell(); - uint32 ret; - read(&ret); - mStream->seek(homePos); - - return ret; - } - //--------------------------------------------------------------------- - void StreamSerialiser::readChunkEnd(uint32 id) - { - Chunk* c = popChunk(id); - - OgreAssert(mStream, "Stream is null"); - - // skip to the end of the chunk if we were not there already - // this lets us quite reading a chunk anywhere and have the read marker - // automatically skip to the next one - if (mStream->tell() < (c->offset + CHUNK_HEADER_SIZE + c->length)) - mStream->seek(c->offset + CHUNK_HEADER_SIZE + c->length); - - OGRE_DELETE c; - } - //--------------------------------------------------------------------- - bool StreamSerialiser::isEndOfChunk(uint32 id) - { - const Chunk* c = getCurrentChunk(); - assert(c->id == id); - return mStream->tell() == (c->offset + CHUNK_HEADER_SIZE + c->length); - } - //--------------------------------------------------------------------- - void StreamSerialiser::readHeader() - { - uint32 headerid; - size_t actually_read = mStream->read(&headerid, sizeof(uint32)); - // skip back - mStream->skip(0 - (long)actually_read); - // validate that this is a header chunk - if (headerid == REVERSE_HEADER_ID) - { - mFlipEndian = true; - } - else if (headerid == HEADER_ID) - { - mFlipEndian = false; - } - else - { - // no good - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, - "Cannot determine endian mode because header is missing", - "StreamSerialiser::readHeader"); - } - determineEndianness(); - - mReadWriteHeader = false; - - const Chunk* c = readChunkBegin(); - // endian should be flipped now - assert(c->id == HEADER_ID); - (void)c; // Silence warning - - // read real storage format - bool realIsDouble; - read(&realIsDouble); - mRealFormat = realIsDouble? REAL_DOUBLE : REAL_FLOAT; - - readChunkEnd(HEADER_ID); - - } - //--------------------------------------------------------------------- - void StreamSerialiser::determineEndianness() - { -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - if (mFlipEndian) - mEndian = ENDIAN_LITTLE; - else - mEndian = ENDIAN_BIG; -#else - if (mFlipEndian) - mEndian = ENDIAN_BIG; - else - mEndian = ENDIAN_LITTLE; -#endif - } - //--------------------------------------------------------------------- - const StreamSerialiser::Chunk* StreamSerialiser::getCurrentChunk() const - { - if (mChunkStack.empty()) - return 0; - else - return mChunkStack.back(); - } - //--------------------------------------------------------------------- - bool StreamSerialiser::eof() const - { - OgreAssert(mStream, "Stream is null"); - return mStream->eof(); - } - //--------------------------------------------------------------------- - void StreamSerialiser::checkStream(bool failOnEof, bool validateReadable, bool validateWriteable) const - { - OgreAssert(mStream, "Stream is null"); - - if (failOnEof && mStream->eof()) - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Invalid operation, end of file on stream"); - - if (validateReadable && !mStream->isReadable()) - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Invalid operation, file is not readable"); - - if (validateWriteable && !mStream->isWriteable()) - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Invalid operation, file is not writeable"); - } - //--------------------------------------------------------------------- - void StreamSerialiser::writeHeader() - { - if (mEndian == ENDIAN_AUTO) - determineEndianness(); - - // Header chunk has zero data size - writeChunkImpl(HEADER_ID, 1); - - // real format - bool realIsDouble = (mRealFormat == REAL_DOUBLE); - write(&realIsDouble); - - writeChunkEnd(HEADER_ID); - - mReadWriteHeader = false; - } - //--------------------------------------------------------------------- - void StreamSerialiser::writeChunkBegin(uint32 id, uint16 version /* = 1 */) - { - checkStream(false, false, true); - - if (mReadWriteHeader) - writeHeader(); - - OgreAssert(mEndian != ENDIAN_AUTO, - "Endian mode has not been determined, did you disable header without setting?"); - - writeChunkImpl(id, version); - - } - //--------------------------------------------------------------------- - void StreamSerialiser::writeChunkEnd(uint32 id) - { - checkStream(false, false, true); - - Chunk* c = popChunk(id); - - // update the sizes - size_t currPos = mStream->tell(); - c->length = static_cast(currPos - c->offset - CHUNK_HEADER_SIZE); - - // seek to 'length' position in stream for this chunk - // skip id (32) and version (16) - mStream->seek(c->offset + sizeof(uint32) + sizeof(uint16)); - write(&c->length); - // write updated checksum - uint32 checksum = calculateChecksum(c); - write(&checksum); - - // seek back to previous position - mStream->seek(currPos); - - OGRE_DELETE c; - - } - //--------------------------------------------------------------------- - size_t StreamSerialiser::getOffsetFromChunkStart() const - { - OgreAssert(mStream, "Stream is null"); - - if (mChunkStack.empty()) - { - return 0; - } - else - { - size_t pos = mStream->tell(); - size_t diff = pos - mChunkStack.back()->offset; - if(diff >= CHUNK_HEADER_SIZE) - return diff - CHUNK_HEADER_SIZE; - else - return 0; // not in a chunk? - - } - - } - //--------------------------------------------------------------------- - StreamSerialiser::Chunk* StreamSerialiser::readChunkImpl() - { - Chunk *chunk = OGRE_NEW Chunk(); - chunk->offset = static_cast(mStream->tell()); - read(&chunk->id); - read(&chunk->version); - read(&chunk->length); - - uint32 checksum; - read(&checksum); - - if (checksum != calculateChecksum(chunk)) - { - // no good, this is an invalid chunk - uint32 off = chunk->offset; - OGRE_DELETE chunk; - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, - "Corrupt chunk detected in stream " + mStream->getName() + " at byte " - + StringConverter::toString(off), - "StreamSerialiser::readChunkImpl"); - } - else - { - return chunk; - } - - - } - //--------------------------------------------------------------------- - void StreamSerialiser::writeChunkImpl(uint32 id, uint16 version) - { - Chunk* c = OGRE_NEW Chunk(); - c->id = id; - c->version = version; - c->offset = static_cast(mStream->tell()); - c->length = 0; - - mChunkStack.push_back(c); - - write(&c->id); - write(&c->version); - write(&c->length); - // write length again, this is just a placeholder for the checksum (to come later) - write(&c->length); - - } - //--------------------------------------------------------------------- - void StreamSerialiser::writeData(const void* buf, size_t size, size_t count) - { - checkStream(false, false, true); - - size_t totSize = size * count; - if (mFlipEndian) - { - void* pToWrite = OGRE_MALLOC(totSize, MEMCATEGORY_GENERAL); - memcpy(pToWrite, buf, totSize); - - Bitwise::bswapChunks(pToWrite, size, count); - mStream->write(pToWrite, totSize); - - OGRE_FREE(pToWrite, MEMCATEGORY_GENERAL); - } - else - { - mStream->write(buf, totSize); - } - - } - //--------------------------------------------------------------------- - void StreamSerialiser::write(const Vector2* vec, size_t count) - { - for (size_t i = 0; i < count; ++i, ++vec) - write(vec->ptr(), 2); - } - //--------------------------------------------------------------------- - void StreamSerialiser::write(const Vector3* vec, size_t count) - { - for (size_t i = 0; i < count; ++i, ++vec) - write(vec->ptr(), 3); - } - //--------------------------------------------------------------------- - void StreamSerialiser::write(const Vector4* vec, size_t count) - { - for (size_t i = 0; i < count; ++i, ++vec) - write(vec->ptr(), 4); - } - //--------------------------------------------------------------------- - void StreamSerialiser::write(const Quaternion* q, size_t count) - { - for (size_t i = 0; i < count; ++i, ++q) - write(q->ptr(), 4); - } - //--------------------------------------------------------------------- - void StreamSerialiser::write(const String* string) - { - // uint32 of size first, then (unterminated) string - uint32 len = static_cast(string->length()); - write(&len); - mStream->write(string->c_str(), len); - } - //--------------------------------------------------------------------- - void StreamSerialiser::write(const Matrix3* m, size_t count) - { - for (size_t i = 0; i < count; ++i, ++m) - write((*m)[0], 9); - } - //--------------------------------------------------------------------- - void StreamSerialiser::write(const Matrix4* m, size_t count) - { - for (size_t i = 0; i < count; ++i, ++m) - write((*m)[0], 12); - } - //--------------------------------------------------------------------- - void StreamSerialiser::write(const AxisAlignedBox* aabb, size_t count) - { - for (size_t i = 0; i < count; ++i, ++aabb) - { - bool infinite = aabb->isInfinite(); - write(&infinite); - write(&aabb->getMinimum()); - write(&aabb->getMaximum()); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::write(const Sphere* sphere, size_t count) - { - - for (size_t i = 0; i < count; ++i, ++sphere) - { - write(&sphere->getCenter()); - Real radius = sphere->getRadius(); - write(&radius); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::write(const Plane* plane, size_t count) - { - for (size_t i = 0; i < count; ++i, ++plane) - { - write(&plane->normal); - write(&plane->d); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::write(const Ray* ray, size_t count) - { - for (size_t i = 0; i < count; ++i, ++ray) - { - write(&ray->getOrigin()); - write(&ray->getDirection()); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::write(const Radian* rad, size_t count) - { - for (size_t i = 0; i < count; ++i, ++rad) - { - Real r = rad->valueRadians(); - write(&r); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::write(const Node* node, size_t count) - { - for (size_t i = 0; i < count; ++i, ++node) - { - write(&node->getPosition()); - write(&node->getOrientation()); - write(&node->getScale()); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::write(const bool* val, size_t count) - { - for (size_t i = 0; i < count; ++i, ++val) - { - char c = (*val)? 1 : 0; - write(&c); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::write(const Real* val, size_t count) - { -#if OGRE_DOUBLE_PRECISION - if (mRealFormat == REAL_DOUBLE) - writeData(val, sizeof(double), count); - else - writeDoublesAsFloats(val, count); -#else - if (mRealFormat == REAL_FLOAT) - writeData(val, sizeof(float), count); - else - writeFloatsAsDoubles(val, count); -#endif - } - //--------------------------------------------------------------------- - void StreamSerialiser::readData(void* buf, size_t size, size_t count) - { - checkStream(true, true, false); - - size_t totSize = size * count; - mStream->read(buf, totSize); - - if (mFlipEndian) - Bitwise::bswapChunks(buf, size, count); - - } - //--------------------------------------------------------------------- - void StreamSerialiser::read(Vector2* vec, size_t count) - { - for (size_t i = 0; i < count; ++i, ++vec) - { - read(vec->ptr(), 2); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::read(Vector3* vec, size_t count) - { - for (size_t i = 0; i < count; ++i, ++vec) - { - read(vec->ptr(), 3); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::read(Vector4* vec, size_t count) - { - for (size_t i = 0; i < count; ++i, ++vec) - { - read(vec->ptr(), 4); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::read(Quaternion* q, size_t count) - { - for (size_t i = 0; i < count; ++i, ++q) - { - read(q->ptr(), 4); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::read(Matrix3* m, size_t count) - { - for (size_t i = 0; i < count; ++i, ++m) - { - read((*m)[0], 9); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::read(Matrix4* m, size_t count) - { - for (size_t i = 0; i < count; ++i, ++m) - { - read((*m)[0], 12); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::read(String* string) - { - // String is stored as a uint32 character count, then string - uint32 len; - read(&len); - string->resize(len); - if (len) - read(&(*string->begin()), len); - } - //--------------------------------------------------------------------- - void StreamSerialiser::read(Real* val, size_t count) - { -#if OGRE_DOUBLE_PRECISION - if (mRealFormat == REAL_DOUBLE) - readData(val, sizeof(double), count); - else - readFloatsAsDoubles(val, count); -#else - if (mRealFormat == REAL_FLOAT) - readData(val, sizeof(float), count); - else - readDoublesAsFloats(val, count); -#endif - - } - //--------------------------------------------------------------------- - void StreamSerialiser::read(AxisAlignedBox* aabb, size_t count) - { - for (size_t i = 0; i < count; ++i, ++aabb) - { - bool infinite = false; - read(&infinite); - Vector3 tmpMin, tmpMax; - read(&tmpMin); - read(&tmpMax); - - if (infinite) - aabb->setInfinite(); - else - aabb->setExtents(tmpMin, tmpMax); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::read(Sphere* sphere, size_t count) - { - for (size_t i = 0; i < count; ++i, ++sphere) - { - Vector3 center; - Real radius; - read(¢er); - read(&radius); - sphere->setCenter(center); - sphere->setRadius(radius); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::read(Plane* plane, size_t count) - { - for (size_t i = 0; i < count; ++i, ++plane) - { - read(&plane->normal); - read(&plane->d); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::read(Ray* ray, size_t count) - { - for (size_t i = 0; i < count; ++i, ++ray) - { - Vector3 origin, dir; - read(&origin); - read(&dir); - ray->setOrigin(origin); - ray->setDirection(dir); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::read(Radian* angle, size_t count) - { - for (size_t i = 0; i < count; ++i, ++angle) - { - Real rads; - read(&rads); - *angle = Radian(rads); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::read(Node* node, size_t count) - { - for (size_t i = 0; i < count; ++i, ++node) - { - Vector3 pos, scale; - Quaternion orient; - read(&pos); - read(&orient); - read(&scale); - node->setPosition(pos); - node->setOrientation(orient); - node->setScale(scale); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::read(bool* val, size_t count) - { - for (size_t i = 0; i < count; ++i, ++val) - { - char c; - read(&c); - *val = (c == 1); - } - } - //--------------------------------------------------------------------- - void StreamSerialiser::writeFloatsAsDoubles(const float* val, size_t count) - { - double t = 0; - writeConverted(val, t, count); - } - //--------------------------------------------------------------------- - void StreamSerialiser::writeDoublesAsFloats(const double* val, size_t count) - { - float t = 0; - writeConverted(val, t, count); - } - //--------------------------------------------------------------------- - void StreamSerialiser::readFloatsAsDoubles(double* val, size_t count) - { - float t = 0; - readConverted(val, t, count); - } - //--------------------------------------------------------------------- - void StreamSerialiser::readDoublesAsFloats(float* val, size_t count) - { - double t = 0; - readConverted(val, t, count); - } - //--------------------------------------------------------------------- - uint32 StreamSerialiser::calculateChecksum(Chunk* c) - { - // Always calculate checksums in little endian to make sure they match - // Otherwise checksums for the same data on different endians will not match - uint32 id = c->id; - uint16 version = c->version; - uint32 length = c->length; -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - Bitwise::bswapBuffer(&id, sizeof(uint32)); - Bitwise::bswapBuffer(&version, sizeof(uint16)); - Bitwise::bswapBuffer(&length, sizeof(uint32)); -#endif - - // we cannot switch to murmur3 like everywhere else to allow loading legacy files - uint32 hashVal = SuperFastHash((const char*)&id, sizeof(uint32), 0); - hashVal = SuperFastHash((const char*)&version, sizeof(uint16), hashVal); - hashVal = SuperFastHash((const char*)&length, sizeof(uint32), hashVal); - - return hashVal; - } - //--------------------------------------------------------------------- - StreamSerialiser::Chunk* StreamSerialiser::popChunk(uint id) - { - OgreAssert(!mChunkStack.empty(), "No active chunk!"); - - const Chunk* chunk = mChunkStack.back(); - OgreAssert(chunk->id == id, "Incorrect chunk id!"); - - Chunk* c = mChunkStack.back(); - mChunkStack.pop_back(); - return c; - - } - void StreamSerialiser::startDeflate(size_t avail_in) - { -#if OGRE_NO_ZIP_ARCHIVE == 0 - OgreAssert( !mOriginalStream , "Don't start (un)compressing twice!" ); - DataStreamPtr deflateStream(OGRE_NEW DeflateStream(mStream,"",avail_in)); - mOriginalStream = mStream; - mStream = deflateStream; -#else - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, - "Ogre was not built with Zip file support!", "StreamSerialiser::startDeflate"); -#endif - } - void StreamSerialiser::stopDeflate() - { -#if OGRE_NO_ZIP_ARCHIVE == 0 - OgreAssert( mOriginalStream , "Must start (un)compressing first!" ); - mStream = mOriginalStream; - mOriginalStream.reset(); -#else - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, - "Ogre was not built with Zip file support!", "StreamSerialiser::stopDeflate"); -#endif - } -} - - diff --git a/OgreMain/src/OgreString.cpp b/OgreMain/src/OgreString.cpp deleted file mode 100644 index 43cc5aa126e..00000000000 --- a/OgreMain/src/OgreString.cpp +++ /dev/null @@ -1,514 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -// A quick define to overcome different names for the same function -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT -# define strnicmp _strnicmp -#else -# define strnicmp strncasecmp -#endif - -namespace Ogre { - const String& StringUtil::BLANK = BLANKSTRING; - - //----------------------------------------------------------------------- - void StringUtil::trim(String& str, bool left, bool right) - { - /* - size_t lspaces, rspaces, len = length(), i; - - lspaces = rspaces = 0; - - if( left ) - { - // Find spaces / tabs on the left - for( i = 0; - i < len && ( at(i) == ' ' || at(i) == '\t' || at(i) == '\r'); - ++lspaces, ++i ); - } - - if( right && lspaces < len ) - { - // Find spaces / tabs on the right - for( i = len - 1; - i >= 0 && ( at(i) == ' ' || at(i) == '\t' || at(i) == '\r'); - rspaces++, i-- ); - } - - *this = substr(lspaces, len-lspaces-rspaces); - */ - static const String delims = " \t\r\n"; - if(right) - str.erase(str.find_last_not_of(delims)+1); // trim right - if(left) - str.erase(0, str.find_first_not_of(delims)); // trim left - } - - //----------------------------------------------------------------------- - StringVector StringUtil::split( const String& str, const String& delims, unsigned int maxSplits, bool preserveDelims) - { - StringVector ret; - // Pre-allocate some space for performance - ret.reserve(maxSplits ? maxSplits+1 : 10); // 10 is guessed capacity for most case - - unsigned int numSplits = 0; - - // Use STL methods - size_t start, pos; - start = 0; - do - { - pos = str.find_first_of(delims, start); - if (pos == start) - { - // Do nothing - start = pos + 1; - } - else if (pos == String::npos || (maxSplits && numSplits == maxSplits)) - { - // Copy the rest of the string - ret.push_back( str.substr(start) ); - break; - } - else - { - // Copy up to delimiter - ret.push_back( str.substr(start, pos - start) ); - - if(preserveDelims) - { - // Sometimes there could be more than one delimiter in a row. - // Loop until we don't find any more delims - size_t delimStart = pos, delimPos; - delimPos = str.find_first_not_of(delims, delimStart); - if (delimPos == String::npos) - { - // Copy the rest of the string - ret.push_back( str.substr(delimStart) ); - } - else - { - ret.push_back( str.substr(delimStart, delimPos - delimStart) ); - } - } - - start = pos + 1; - } - // parse up to next real data - start = str.find_first_not_of(delims, start); - ++numSplits; - - } while (pos != String::npos); - - - - return ret; - } - //----------------------------------------------------------------------- - StringVector StringUtil::tokenise( const String& str, const String& singleDelims, const String& doubleDelims, unsigned int maxSplits) - { - StringVector ret; - // Pre-allocate some space for performance - ret.reserve(maxSplits ? maxSplits+1 : 10); // 10 is guessed capacity for most case - - unsigned int numSplits = 0; - String delims = singleDelims + doubleDelims; - - // Use STL methods - size_t start, pos; - char curDoubleDelim = 0; - start = 0; - do - { - if (curDoubleDelim != 0) - { - pos = str.find(curDoubleDelim, start); - } - else - { - pos = str.find_first_of(delims, start); - } - - if (pos == start) - { - char curDelim = str.at(pos); - if (doubleDelims.find_first_of(curDelim) != String::npos) - { - curDoubleDelim = curDelim; - } - // Do nothing - start = pos + 1; - } - else if (pos == String::npos || (maxSplits && numSplits == maxSplits)) - { - if (curDoubleDelim != 0) - { - //Missing closer. Warn or throw exception? - } - // Copy the rest of the string - ret.push_back( str.substr(start) ); - break; - } - else - { - if (curDoubleDelim != 0) - { - curDoubleDelim = 0; - } - - // Copy up to delimiter - ret.push_back( str.substr(start, pos - start) ); - start = pos + 1; - } - if (curDoubleDelim == 0) - { - // parse up to next real data - start = str.find_first_not_of(singleDelims, start); - } - - ++numSplits; - - } while (start != String::npos); - - return ret; - } - //----------------------------------------------------------------------- - void StringUtil::toLowerCase(String& str) - { - std::transform( - str.begin(), - str.end(), - str.begin(), - tolower); - } - - //----------------------------------------------------------------------- - void StringUtil::toUpperCase(String& str) - { - std::transform( - str.begin(), - str.end(), - str.begin(), - toupper); - } - //----------------------------------------------------------------------- - void StringUtil::toTitleCase(String& str) - { - String::iterator it = str.begin(); - *it = toupper(*it); - for (; it != str.end() - 1; it++) - { - if (*it == ' ') - { - *(it + 1) = toupper(*(it + 1)); - } - } - } - //----------------------------------------------------------------------- - bool StringUtil::startsWith(const String& str, const String& pattern, bool lowerCase) - { - if (pattern.empty()) - return false; - - if (lowerCase) - { - return strnicmp(str.c_str(), pattern.c_str(), pattern.size()) == 0; - } - - return strncmp(str.c_str(), pattern.c_str(), pattern.size()) == 0; - } - //----------------------------------------------------------------------- - bool StringUtil::endsWith(const String& str, const String& pattern, bool lowerCase) - { - if (pattern.empty()) - return false; - - size_t offset = str.size() - pattern.size(); - - if (lowerCase) - { - return strnicmp(str.c_str() + offset, pattern.c_str(), pattern.size()) == 0; - } - - return strncmp(str.c_str() + offset, pattern.c_str(), pattern.size()) == 0; - } - //----------------------------------------------------------------------- - String StringUtil::standardisePath(const String& init) - { - String path = init; - - std::replace( path.begin(), path.end(), '\\', '/' ); - if( path[path.length() - 1] != '/' ) - path += '/'; - - return path; - } - //----------------------------------------------------------------------- - String StringUtil::normalizeFilePath(const String& init, bool makeLowerCase) - { - const char* bufferSrc = init.c_str(); - int pathLen = (int)init.size(); - int indexSrc = 0; - int indexDst = 0; - int metaPathArea = 0; - - char reservedBuf[1024]; - char* bufferDst = reservedBuf; - bool isDestAllocated = false; - if (pathLen > 1023) - { - //if source path is to long ensure we don't do a buffer overrun by allocating some - //new memory - isDestAllocated = true; - bufferDst = new char[pathLen + 1]; - } - - //The outer loop loops over directories - while (indexSrc < pathLen) - { - if (indexSrc && ((bufferSrc[indexSrc] == '\\') || (bufferSrc[indexSrc] == '/'))) - { - //check if we have a directory delimiter if so skip it (we should already - //have written such a delimiter by this point - ++indexSrc; - continue; - } - else - { - //check if there is a directory to skip of type ".\" - if ((bufferSrc[indexSrc] == '.') && - ((bufferSrc[indexSrc + 1] == '\\') || (bufferSrc[indexSrc + 1] == '/'))) - { - indexSrc += 2; - continue; - } - - //check if there is a directory to skip of type "..\" - else if ((bufferSrc[indexSrc] == '.') && (bufferSrc[indexSrc + 1] == '.') && - ((bufferSrc[indexSrc + 2] == '\\') || (bufferSrc[indexSrc + 2] == '/'))) - { - if (indexDst > metaPathArea) - { - //skip a directory backward in the destination path - do { - --indexDst; - } - while ((indexDst > metaPathArea) && (bufferDst[indexDst - 1] != '/')); - indexSrc += 3; - continue; - } - else - { - //we are about to write "..\" to the destination buffer - //ensure we will not remove this in future "skip directories" - metaPathArea += 3; - } - } - } - - //transfer the current directory name from the source to the destination - while (indexSrc < pathLen) - { - char curChar = bufferSrc[indexSrc]; - if (makeLowerCase) curChar = tolower(curChar); - if ((curChar == '\\') || (curChar == '/')) curChar = '/'; - bufferDst[indexDst] = curChar; - ++indexDst; - ++indexSrc; - if (curChar == '/') break; - } - } - bufferDst[indexDst] = 0; - - String normalized(bufferDst); - if (isDestAllocated) - { - delete[] bufferDst; - } - - return normalized; - } - //----------------------------------------------------------------------- - void StringUtil::splitFilename(const String& qualifiedName, - String& outBasename, String& outPath) - { - String path = qualifiedName; - // Replace \ with / first - std::replace( path.begin(), path.end(), '\\', '/' ); - // split based on final / - size_t i = path.find_last_of('/'); - - if (i == String::npos) - { - outPath.clear(); - outBasename = qualifiedName; - } - else - { - outBasename = path.substr(i+1, path.size() - i - 1); - outPath = path.substr(0, i+1); - } - - } - //----------------------------------------------------------------------- - void StringUtil::splitBaseFilename(const Ogre::String& fullName, - Ogre::String& outBasename, Ogre::String& outExtention) - { - size_t i = fullName.find_last_of('.'); - if (i == Ogre::String::npos) - { - outExtention.clear(); - outBasename = fullName; - } - else - { - outExtention = fullName.substr(i+1); - outBasename = fullName.substr(0, i); - } - } - // ---------------------------------------------------------------------------------------------------------------------------------------------- - void StringUtil::splitFullFilename( const Ogre::String& qualifiedName, - Ogre::String& outBasename, Ogre::String& outExtention, Ogre::String& outPath ) - { - Ogre::String fullName; - splitFilename( qualifiedName, fullName, outPath ); - splitBaseFilename( fullName, outBasename, outExtention ); - } - //----------------------------------------------------------------------- - bool StringUtil::match(const String& str, const String& pattern, bool caseSensitive) - { - String tmpStr = str; - String tmpPattern = pattern; - if (!caseSensitive) - { - StringUtil::toLowerCase(tmpStr); - StringUtil::toLowerCase(tmpPattern); - } - - String::const_iterator strIt = tmpStr.begin(); - String::const_iterator patIt = tmpPattern.begin(); - String::const_iterator lastWildCardIt = tmpPattern.end(); - while (strIt != tmpStr.end() && patIt != tmpPattern.end()) - { - if (*patIt == '*') - { - lastWildCardIt = patIt; - // Skip over looking for next character - ++patIt; - if (patIt == tmpPattern.end()) - { - // Skip right to the end since * matches the entire rest of the string - strIt = tmpStr.end(); - } - else - { - // scan until we find next pattern character - while(strIt != tmpStr.end() && *strIt != *patIt) - ++strIt; - } - } - else - { - if (*patIt != *strIt) - { - if (lastWildCardIt != tmpPattern.end()) - { - // The last wildcard can match this incorrect sequence - // rewind pattern to wildcard and keep searching - patIt = lastWildCardIt; - lastWildCardIt = tmpPattern.end(); - } - else - { - // no wildwards left - return false; - } - } - else - { - ++patIt; - ++strIt; - } - } - - } - // If we reached the end of both the pattern and the string, we succeeded - if ((patIt == tmpPattern.end() || (*patIt == '*' && patIt + 1 == tmpPattern.end())) && strIt == tmpStr.end()) - { - return true; - } - else - { - return false; - } - - } - //----------------------------------------------------------------------- - const String StringUtil::replaceAll(const String& source, const String& replaceWhat, const String& replaceWithWhat) - { - String result = source; - String::size_type pos = 0; - while(1) - { - pos = result.find(replaceWhat,pos); - if (pos == String::npos) break; - result.replace(pos,replaceWhat.size(),replaceWithWhat); - pos += replaceWithWhat.size(); - } - return result; - } - - String StringUtil::format(const char* fmt, ...) - { - // try to use a stack buffer and fall back to heap for large strings - char sbuf[1024]; - size_t bsize = sizeof(sbuf); - std::vector hbuf; - char* pbuf = sbuf; - - while (true) - { - va_list va; - va_start(va, fmt); - int len = vsnprintf(pbuf, bsize, fmt, va); - va_end(va); - - OgreAssert(len >= 0, "Check format string for errors"); - if (size_t(len) >= bsize) - { - hbuf.resize(len + 1); - pbuf = hbuf.data(); - bsize = hbuf.size(); - continue; - } - pbuf[bsize - 1] = 0; - return String(pbuf, len); - } - } -} diff --git a/OgreMain/src/OgreStringConverter.cpp b/OgreMain/src/OgreStringConverter.cpp deleted file mode 100644 index bb89ac33a07..00000000000 --- a/OgreMain/src/OgreStringConverter.cpp +++ /dev/null @@ -1,398 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -// A quick define to overcome different names for the same function -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT -# define strtod_l _strtod_l -# define strtoul_l _strtoul_l -# define strtol_l _strtol_l -# define strtoull_l _strtoull_l -# define strtoll_l _strtoll_l -#endif - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN || \ - (OGRE_PLATFORM == OGRE_PLATFORM_LINUX && OGRE_NO_LOCALE_STRCONVERT == 1) -# define strtod_l(ptr, end, l) strtod(ptr, end) -# define strtoul_l(ptr, end, base, l) strtoul(ptr, end, base) -# define strtol_l(ptr, end, base, l) strtol(ptr, end, base) -# define strtoull_l(ptr, end, base, l) strtoull(ptr, end, base) -# define strtoll_l(ptr, end, base, l) strtoll(ptr, end, base) -#endif - -#if (OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT) && !defined(__MINGW32__) -# define LC_NUMERIC_MASK LC_NUMERIC -# define newlocale(cat, loc, base) _create_locale(cat, loc) -#endif - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN || defined(__MINGW32__) -# define newlocale(cat, loc, base) 0 -#endif - -#ifdef __MINGW32__ -#define _strtoull_l _strtoul_l -#define _strtoll_l _strtol_l -#endif - -namespace Ogre { - locale_t StringConverter::_numLocale = newlocale(LC_NUMERIC_MASK, OGRE_DEFAULT_LOCALE, NULL); - - template - String StringConverter::_toString(T val, uint16 width, char fill, std::ios::fmtflags flags) - { - StringStream stream; - stream.width(width); - stream.fill(fill); - if (flags & std::ios::basefield) { - stream.setf(flags, std::ios::basefield); - stream.setf((flags & ~std::ios::basefield) | std::ios::showbase); - } - else if (flags) - stream.setf(flags); - - stream << val; - - return stream.str(); - } - - //----------------------------------------------------------------------- - String StringConverter::toString(float val, unsigned short precision, - unsigned short width, char fill, std::ios::fmtflags flags) - { - StringStream stream; - stream.precision(precision); - stream.width(width); - stream.fill(fill); - if (flags) - stream.setf(flags); - stream << val; - return stream.str(); - } - - //----------------------------------------------------------------------- - String StringConverter::toString(double val, unsigned short precision, - unsigned short width, char fill, std::ios::fmtflags flags) - { - StringStream stream; - stream.precision(precision); - stream.width(width); - stream.fill(fill); - if (flags) - stream.setf(flags); - stream << val; - return stream.str(); - } - - //----------------------------------------------------------------------- - String StringConverter::toString(int32 val, - unsigned short width, char fill, std::ios::fmtflags flags) - { - return _toString(val, width, fill, flags); - } - //----------------------------------------------------------------------- - String StringConverter::toString(uint32 val, - unsigned short width, char fill, std::ios::fmtflags flags) - { - return _toString(val, width, fill, flags); - } - //----------------------------------------------------------------------- - String StringConverter::toString(unsigned long val, - unsigned short width, char fill, std::ios::fmtflags flags) - { - return _toString(val, width, fill, flags); - } - //----------------------------------------------------------------------- - String StringConverter::toString(unsigned long long val, - unsigned short width, char fill, std::ios::fmtflags flags) - { - return _toString(val, width, fill, flags); - } - //----------------------------------------------------------------------- - String StringConverter::toString(long val, - unsigned short width, char fill, std::ios::fmtflags flags) - { - return _toString(val, width, fill, flags); - } - //----------------------------------------------------------------------- - String StringConverter::toString(const Vector2& val) - { - StringStream stream; - stream << val.x << " " << val.y; - return stream.str(); - } - //----------------------------------------------------------------------- - String StringConverter::toString(const Vector3& val) - { - StringStream stream; - stream << val.x << " " << val.y << " " << val.z; - return stream.str(); - } - //----------------------------------------------------------------------- - String StringConverter::toString(const Vector4& val) - { - StringStream stream; - stream << val.x << " " << val.y << " " << val.z << " " << val.w; - return stream.str(); - } - //----------------------------------------------------------------------- - String StringConverter::toString(const Matrix3& val) - { - StringStream stream; - stream << val[0][0] << " " - << val[0][1] << " " - << val[0][2] << " " - << val[1][0] << " " - << val[1][1] << " " - << val[1][2] << " " - << val[2][0] << " " - << val[2][1] << " " - << val[2][2]; - return stream.str(); - } - //----------------------------------------------------------------------- - String StringConverter::toString(bool val, bool yesNo) - { - if (val) - { - if (yesNo) - { - return "yes"; - } - else - { - return "true"; - } - } - else - if (yesNo) - { - return "no"; - } - else - { - return "false"; - } - } - //----------------------------------------------------------------------- - String StringConverter::toString(const Matrix4& val) - { - StringStream stream; - stream << val[0][0] << " " - << val[0][1] << " " - << val[0][2] << " " - << val[0][3] << " " - << val[1][0] << " " - << val[1][1] << " " - << val[1][2] << " " - << val[1][3] << " " - << val[2][0] << " " - << val[2][1] << " " - << val[2][2] << " " - << val[2][3] << " " - << val[3][0] << " " - << val[3][1] << " " - << val[3][2] << " " - << val[3][3]; - return stream.str(); - } - //----------------------------------------------------------------------- - String StringConverter::toString(const Quaternion& val) - { - StringStream stream; - stream << val.w << " " << val.x << " " << val.y << " " << val.z; - return stream.str(); - } - //----------------------------------------------------------------------- - String StringConverter::toString(const ColourValue& val) - { - StringStream stream; - stream << val.r << " " << val.g << " " << val.b << " " << val.a; - return stream.str(); - } - //----------------------------------------------------------------------- - String StringConverter::toString(const StringVector& val) - { - StringStream stream; - StringVector::const_iterator i, iend, ibegin; - ibegin = val.begin(); - iend = val.end(); - for (i = ibegin; i != iend; ++i) - { - if (i != ibegin) - stream << " "; - - stream << *i; - } - return stream.str(); - } - - //----------------------------------------------------------------------- - template static bool assignValid(bool valid, const T& val, T& ret) - { - if (valid) - ret = val; - return valid; - } - - bool StringConverter::parse(const String& val, float& ret) - { - char* end; - auto tmp = (float)strtod_l(val.c_str(), &end, _numLocale); - return assignValid(val.c_str() != end, tmp, ret); - } - bool StringConverter::parse(const String& val, double& ret) - { - char* end; - auto tmp = strtod_l(val.c_str(), &end, _numLocale); - return assignValid(val.c_str() != end, tmp, ret); - } - //----------------------------------------------------------------------- - bool StringConverter::parse(const String& val, int32& ret) - { - char* end; - auto tmp = (int32)strtol_l(val.c_str(), &end, 0, _numLocale); - return assignValid(val.c_str() != end, tmp, ret); - } - //----------------------------------------------------------------------- - bool StringConverter::parse(const String& val, int64& ret) - { - char* end; - int64 tmp = strtoll_l(val.c_str(), &end, 0, _numLocale); - return assignValid(val.c_str() != end, tmp, ret); - } - //----------------------------------------------------------------------- - bool StringConverter::parse(const String& val, unsigned long& ret) - { - char* end; - unsigned long tmp = strtoull_l(val.c_str(), &end, 0, _numLocale); - return assignValid(val.c_str() != end, tmp, ret); - } - bool StringConverter::parse(const String& val, unsigned long long& ret) - { - char* end; - unsigned long long tmp = strtoull_l(val.c_str(), &end, 0, _numLocale); - return assignValid(val.c_str() != end, tmp, ret); - } - //----------------------------------------------------------------------- - bool StringConverter::parse(const String& val, uint32& ret) - { - char* end; - auto tmp = (uint32)strtoul_l(val.c_str(), &end, 0, _numLocale); - return assignValid(val.c_str() != end, tmp, ret); - } - bool StringConverter::parse(const String& val, bool& ret) - { - //FIXME Returns both parsed value and error in same value - ambiguous. - // Suggested alternatives: implement exception handling or make either - // error or parsed value a parameter. - if ((StringUtil::startsWith(val, "true") || StringUtil::startsWith(val, "yes") - || StringUtil::startsWith(val, "1") || StringUtil::startsWith(val, "on"))) - ret = true; - else if ((StringUtil::startsWith(val, "false") || StringUtil::startsWith(val, "no") - || StringUtil::startsWith(val, "0") || StringUtil::startsWith(val, "off"))) - ret = false; - else - return false; - - return true; - } - - static bool parseReals(const String& val, Real* dst, size_t n) - { - // Split on space - std::vector vec = StringUtil::split(val); - if(vec.size() != n) - return false; - - bool ret = true; - for(size_t i = 0; i < n; i++) - ret &= StringConverter::parse(vec[i], dst[i]); - return ret; - } - - //----------------------------------------------------------------------- - bool StringConverter::parse(const String& val, Vector2& ret) - { - return parseReals(val, ret.ptr(), 2); - } - //----------------------------------------------------------------------- - bool StringConverter::parse(const String& val, Vector3& ret) - { - return parseReals(val, ret.ptr(), 3); - } - //----------------------------------------------------------------------- - bool StringConverter::parse(const String& val, Vector4& ret) - { - return parseReals(val, ret.ptr(), 4); - } - //----------------------------------------------------------------------- - bool StringConverter::parse(const String& val, Matrix3& ret) - { - return parseReals(val, &ret[0][0], 9); - } - //----------------------------------------------------------------------- - bool StringConverter::parse(const String& val, Matrix4& ret) - { - return parseReals(val, &ret[0][0], 16); - } - //----------------------------------------------------------------------- - bool StringConverter::parse(const String& val, Quaternion& ret) - { - return parseReals(val, ret.ptr(), 4); - } - //----------------------------------------------------------------------- - bool StringConverter::parse(const String& val, ColourValue& ret) - { - // Split on space - std::vector vec = StringUtil::split(val); - - if (vec.size() == 4) - { - return parse(vec[0], ret.r) && parse(vec[1], ret.g) && parse(vec[2], ret.b) && - parse(vec[3], ret.a); - } - else if (vec.size() == 3) - { - ret.a = 1.0f; - return parse(vec[0], ret.r) && parse(vec[1], ret.g) && parse(vec[2], ret.b); - } - else - { - return false; - } - } - //----------------------------------------------------------------------- - bool StringConverter::isNumber(const String& val) - { - char* end; - strtod(val.c_str(), &end); - return end == (val.c_str() + val.size()); - } -} - - diff --git a/OgreMain/src/OgreStringInterface.cpp b/OgreMain/src/OgreStringInterface.cpp deleted file mode 100644 index 4f060222bbe..00000000000 --- a/OgreMain/src/OgreStringInterface.cpp +++ /dev/null @@ -1,172 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "Threading/OgreThreadHeaders.h" - -namespace Ogre { - OGRE_STATIC_MUTEX( msDictionaryMutex ); - /// Dictionary of parameters - static ParamDictionaryMap msDictionary; - - ParamDictionary::ParamDictionary() {} - ParamDictionary::~ParamDictionary() {} - - ParamCommand* ParamDictionary::getParamCommand(const String& name) - { - ParamCommandMap::iterator i = mParamCommands.find(name); - if (i != mParamCommands.end()) - { - return i->second; - } - else - { - return 0; - } - } - - const ParamCommand* ParamDictionary::getParamCommand(const String& name) const - { - ParamCommandMap::const_iterator i = mParamCommands.find(name); - if (i != mParamCommands.end()) - { - return i->second; - } - else - { - return 0; - } - } - - void ParamDictionary::addParameter(const String& name, ParamCommand* paramCmd) - { - mParamDefs.push_back(name); - mParamCommands[name] = paramCmd; - } - - bool StringInterface::createParamDictionary(const String& className) - { - OGRE_LOCK_MUTEX( msDictionaryMutex ); - - ParamDictionaryMap::iterator it = msDictionary.find(className); - - if ( it == msDictionary.end() ) - { - mParamDict = &msDictionary.insert( std::make_pair( className, ParamDictionary() ) ).first->second; - mParamDictName = className; - return true; - } - else - { - mParamDict = &it->second; - mParamDictName = className; - return false; - } - } - - const ParameterList& StringInterface::getParameters(void) const - { - static ParameterList emptyList; - - const ParamDictionary* dict = getParamDictionary(); - if (dict) - return dict->getParameters(); - else - return emptyList; - - } - - String StringInterface::getParameter(const String& name) const - { - // Get dictionary - const ParamDictionary* dict = getParamDictionary(); - - if (dict) - { - // Look up command object - const ParamCommand* cmd = dict->getParamCommand(name); - - if (cmd) - { - return cmd->doGet(this); - } - } - - // Fallback - return ""; - } - - bool StringInterface::setParameter(const String& name, const String& value) - { - // Get dictionary - ParamDictionary* dict = getParamDictionary(); - - if (dict) - { - // Look up command object - ParamCommand* cmd = dict->getParamCommand(name); - if (cmd) - { - cmd->doSet(this, value); - return true; - } - } - // Fallback - return false; - } - //----------------------------------------------------------------------- - void StringInterface::setParameterList(const NameValuePairList& paramList) - { - NameValuePairList::const_iterator i, iend; - iend = paramList.end(); - for (i = paramList.begin(); i != iend; ++i) - { - setParameter(i->first, i->second); - } - } - - void StringInterface::copyParametersTo(StringInterface* dest) const - { - // Get dictionary - if (const ParamDictionary* dict = getParamDictionary()) - { - // Iterate through own parameters - for (const auto& name : dict->mParamDefs) - { - dest->setParameter(name, getParameter(name)); - } - } - } - - //----------------------------------------------------------------------- - void StringInterface::cleanupDictionary () - { - OGRE_LOCK_MUTEX( msDictionaryMutex ); - - msDictionary.clear(); - } -} diff --git a/OgreMain/src/OgreSubEntity.cpp b/OgreMain/src/OgreSubEntity.cpp deleted file mode 100644 index e6e08048c85..00000000000 --- a/OgreMain/src/OgreSubEntity.cpp +++ /dev/null @@ -1,421 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreEntity.h" -#include "OgreSubEntity.h" - -namespace Ogre { - //----------------------------------------------------------------------- - SubEntity::SubEntity (Entity* parent, SubMesh* subMeshBasis) - : Renderable(), mParentEntity(parent), - mSubMesh(subMeshBasis), mCachedCamera(0) - { - mVisible = true; - mRenderQueueID = 0; - mRenderQueueIDSet = false; - mRenderQueuePrioritySet = false; - mSkelAnimVertexData = 0; - mVertexAnimationAppliedThisFrame = false; - mHardwarePoseCount = 0; - mIndexStart = 0; - mIndexEnd = 0; - setMaterial(MaterialManager::getSingleton().getDefaultMaterial()); - } - SubEntity::~SubEntity() = default; // ensure unique_ptr destructors are in cpp - //----------------------------------------------------------------------- - SubMesh* SubEntity::getSubMesh(void) - { - return mSubMesh; - } - //----------------------------------------------------------------------- - const String& SubEntity::getMaterialName(void) const - { - return mMaterialPtr ? mMaterialPtr->getName() : BLANKSTRING; - } - //----------------------------------------------------------------------- - void SubEntity::setMaterialName( const String& name, const String& groupName /* = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME */) - { - MaterialPtr material = MaterialManager::getSingleton().getByName(name, groupName); - - if( !material ) - { - logMaterialNotFound(name, groupName, "SubEntity of", mParentEntity->getName()); - material = MaterialManager::getSingleton().getDefaultMaterial(); - } - - setMaterial( material ); - } - //----------------------------------------------------------------------- - void SubEntity::setMaterial( const MaterialPtr& material ) - { - mMaterialPtr = material; - - if (!mMaterialPtr) - { - LogManager::getSingleton().logError("Can't assign nullptr material " - "to SubEntity of '" + mParentEntity->getName() + "'. Falling back to default"); - - mMaterialPtr = MaterialManager::getSingleton().getDefaultMaterial(); - } - - // Ensure new material loaded (will not load again if already loaded) - mMaterialPtr->load(); - - // tell parent to reconsider material vertex processing options - mParentEntity->reevaluateVertexProcessing(); - } - //----------------------------------------------------------------------- - void SubEntity::getRenderOperation(RenderOperation& op) - { - // Use LOD - mSubMesh->_getRenderOperation(op, mParentEntity->mMeshLodIndex); - // Deal with any vertex data overrides - op.vertexData = getVertexDataForBinding(); - - // If we use custom index position the client is responsible to set meaningful values - if(mIndexStart != mIndexEnd) - { - op.indexData->indexStart = mIndexStart; - op.indexData->indexCount = mIndexEnd; - } - } - //----------------------------------------------------------------------- - void SubEntity::setIndexDataStartIndex(size_t start_index) - { - if(start_index < mSubMesh->indexData->indexCount) - mIndexStart = start_index; - } - //----------------------------------------------------------------------- - size_t SubEntity::getIndexDataStartIndex() const - { - return mIndexStart; - } - //----------------------------------------------------------------------- - void SubEntity::setIndexDataEndIndex(size_t end_index) - { - if(end_index > 0 && end_index <= mSubMesh->indexData->indexCount) - mIndexEnd = end_index; - } - //----------------------------------------------------------------------- - size_t SubEntity::getIndexDataEndIndex() const - { - return mIndexEnd; - } - //----------------------------------------------------------------------- - void SubEntity::resetIndexDataStartEndIndex() - { - mIndexStart = 0; - mIndexEnd = 0; - } - //----------------------------------------------------------------------- - VertexData* SubEntity::getVertexDataForBinding(void) - { - if (mSubMesh->useSharedVertices) - { - return mParentEntity->getVertexDataForBinding(); - } - else - { - Entity::VertexDataBindChoice c = - mParentEntity->chooseVertexDataForBinding( - mSubMesh->getVertexAnimationType() != VAT_NONE); - switch(c) - { - case Entity::BIND_ORIGINAL: - return mSubMesh->vertexData; - case Entity::BIND_HARDWARE_MORPH: - return mHardwareVertexAnimVertexData.get(); - case Entity::BIND_SOFTWARE_MORPH: - return mSoftwareVertexAnimVertexData.get(); - case Entity::BIND_SOFTWARE_SKELETAL: - return mSkelAnimVertexData.get(); - }; - // keep compiler happy - return mSubMesh->vertexData; - - } - } - //----------------------------------------------------------------------- - void SubEntity::getWorldTransforms(Matrix4* xform) const - { - if (!mParentEntity->mNumBoneMatrices || - !mParentEntity->isHardwareAnimationEnabled()) - { - // No skeletal animation, or software skinning - *xform = mParentEntity->_getParentNodeFullTransform(); - } - else - { - // Hardware skinning, pass all actually used matrices - const Mesh::IndexMap& indexMap = mSubMesh->useSharedVertices ? - mSubMesh->parent->sharedBlendIndexToBoneIndexMap : mSubMesh->blendIndexToBoneIndexMap; - assert(indexMap.size() <= mParentEntity->mNumBoneMatrices); - - if (mParentEntity->_isSkeletonAnimated()) - { - // Bones, use cached matrices built when Entity::_updateRenderQueue was called - auto boneMatrices = MeshManager::getBonesUseObjectSpace() ? mParentEntity->mBoneMatrices - : mParentEntity->mBoneWorldMatrices; - assert(boneMatrices); - - if (MeshManager::getBonesUseObjectSpace()) - { - *xform++ = mParentEntity->_getParentNodeFullTransform(); - } - - for (auto idx : indexMap) - { - *xform++ = boneMatrices[idx]; - } - } - else - { - // All animations disabled, use parent entity world transform only - std::fill_n(xform, indexMap.size(), mParentEntity->_getParentNodeFullTransform()); - } - } - } - //----------------------------------------------------------------------- - unsigned short SubEntity::getNumWorldTransforms(void) const - { - if (!mParentEntity->mNumBoneMatrices || - !mParentEntity->isHardwareAnimationEnabled()) - { - // No skeletal animation, or software skinning - return 1; - } - else - { - // Hardware skinning, pass all actually used matrices - const Mesh::IndexMap& indexMap = mSubMesh->useSharedVertices ? - mSubMesh->parent->sharedBlendIndexToBoneIndexMap : mSubMesh->blendIndexToBoneIndexMap; - assert(indexMap.size() <= mParentEntity->mNumBoneMatrices); - - return uint16(indexMap.size()) + uint16(MeshManager::getBonesUseObjectSpace()); - } - } - //----------------------------------------------------------------------- - Real SubEntity::getSquaredViewDepth(const Camera* cam) const - { - // First of all, check the cached value - // NB this is manually invalidated by parent each _notifyCurrentCamera call - // Done this here rather than there since we only need this for transparent objects - if (mCachedCamera == cam) - return mCachedCameraDist; - - Node* n = mParentEntity->getParentNode(); - assert(n); - Real dist; - if (!mSubMesh->extremityPoints.empty()) - { - bool euclidean = cam->getSortMode() == SM_DISTANCE; - Vector3 zAxis = cam->getDerivedDirection(); - const Vector3 &cp = cam->getDerivedPosition(); - const Affine3 &l2w = mParentEntity->_getParentNodeFullTransform(); - dist = std::numeric_limits::infinity(); - for (const Vector3& v : mSubMesh->extremityPoints) - { - Vector3 diff = l2w * v - cp; - Real d = euclidean ? diff.squaredLength() : Math::Sqr(zAxis.dotProduct(diff)); - - dist = std::min(d, dist); - } - } - else - dist = n->getSquaredViewDepth(cam); - - mCachedCameraDist = dist; - mCachedCamera = cam; - - return dist; - } - //----------------------------------------------------------------------- - const LightList& SubEntity::getLights(void) const - { - return mParentEntity->queryLights(); - } - //----------------------------------------------------------------------- - void SubEntity::setVisible(bool visible) - { - mVisible = visible; - } - //----------------------------------------------------------------------- - void SubEntity::prepareTempBlendBuffers(void) - { - if (mSubMesh->useSharedVertices) - return; - - mSkelAnimVertexData.reset(); - mSoftwareVertexAnimVertexData.reset(); - mHardwareVertexAnimVertexData.reset(); - - if (!mSubMesh->useSharedVertices) - { - if (mSubMesh->getVertexAnimationType() != VAT_NONE) - { - // Create temporary vertex blend info - // Prepare temp vertex data if needed - // Clone without copying data, don't remove any blending info - // (since if we skeletally animate too, we need it) - mSoftwareVertexAnimVertexData.reset(mSubMesh->vertexData->clone(false)); - mTempVertexAnimInfo.extractFrom(mSoftwareVertexAnimVertexData.get()); - - // Also clone for hardware usage, don't remove blend info since we'll - // need it if we also hardware skeletally animate - mHardwareVertexAnimVertexData.reset(mSubMesh->vertexData->clone(false)); - } - - if (mParentEntity->hasSkeleton()) - { - // Create temporary vertex blend info - // Prepare temp vertex data if needed - // Clone without copying data, remove blending info - // (since blend is performed in software) - mSkelAnimVertexData.reset(mSubMesh->vertexData->_cloneRemovingBlendData()); - mTempSkelAnimInfo.extractFrom(mSkelAnimVertexData.get()); - } - } - } - //----------------------------------------------------------------------- - bool SubEntity::getCastsShadows(void) const - { - return mParentEntity->getCastShadows(); - } - //----------------------------------------------------------------------- - VertexData* SubEntity::_getSkelAnimVertexData(void) - { - assert (mSkelAnimVertexData && "Not software skinned or has no dedicated geometry!"); - return mSkelAnimVertexData.get(); - } - //----------------------------------------------------------------------- - VertexData* SubEntity::_getSoftwareVertexAnimVertexData(void) - { - assert (mSoftwareVertexAnimVertexData && "Not vertex animated or has no dedicated geometry!"); - return mSoftwareVertexAnimVertexData.get(); - } - //----------------------------------------------------------------------- - VertexData* SubEntity::_getHardwareVertexAnimVertexData(void) - { - assert (mHardwareVertexAnimVertexData && "Not vertex animated or has no dedicated geometry!"); - return mHardwareVertexAnimVertexData.get(); - } - //----------------------------------------------------------------------- - void SubEntity::_updateCustomGpuParameter( - const GpuProgramParameters::AutoConstantEntry& constantEntry, - GpuProgramParameters* params) const - { - if (constantEntry.paramType == GpuProgramParameters::ACT_ANIMATION_PARAMETRIC) - { - // Set up to 4 values, or up to limit of hardware animation entries - // Pack into 4-element constants offset based on constant data index - // If there are more than 4 entries, this will be called more than once - Vector4 val(0.0f,0.0f,0.0f,0.0f); - const auto& vd = mHardwareVertexAnimVertexData ? mHardwareVertexAnimVertexData : mParentEntity->mHardwareVertexAnimVertexData; - - size_t animIndex = constantEntry.data * 4; - for (size_t i = 0; i < 4 && - animIndex < vd->hwAnimationDataList.size(); - ++i, ++animIndex) - { - val[i] = - vd->hwAnimationDataList[animIndex].parametric; - } - // set the parametric morph value - params->_writeRawConstant(constantEntry.physicalIndex, val); - } - else - { - // default - return Renderable::_updateCustomGpuParameter(constantEntry, params); - } - } - //----------------------------------------------------------------------------- - void SubEntity::_markBuffersUnusedForAnimation(void) - { - mVertexAnimationAppliedThisFrame = false; - } - //----------------------------------------------------------------------------- - void SubEntity::_markBuffersUsedForAnimation(void) - { - mVertexAnimationAppliedThisFrame = true; - } - //----------------------------------------------------------------------------- - void SubEntity::_restoreBuffersForUnusedAnimation(bool hardwareAnimation) - { - // Rebind original positions if: - // We didn't apply any animation and - // We're morph animated (hardware binds keyframe, software is missing) - // or we're pose animated and software (hardware is fine, still bound) - if (mSubMesh->getVertexAnimationType() != VAT_NONE && - !mSubMesh->useSharedVertices && - !mVertexAnimationAppliedThisFrame && - (!hardwareAnimation || mSubMesh->getVertexAnimationType() == VAT_MORPH)) - { - // Note, VES_POSITION is specified here but if normals are included in animation - // then these will be re-bound too (buffers must be shared) - const VertexElement* srcPosElem = - mSubMesh->vertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); - HardwareVertexBufferSharedPtr srcBuf = - mSubMesh->vertexData->vertexBufferBinding->getBuffer( - srcPosElem->getSource()); - - // Bind to software - const VertexElement* destPosElem = - mSoftwareVertexAnimVertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); - mSoftwareVertexAnimVertexData->vertexBufferBinding->setBinding( - destPosElem->getSource(), srcBuf); - - } - - // rebind any missing hardware pose buffers - // Caused by not having any animations enabled, or keyframes which reference - // no poses - if (!mSubMesh->useSharedVertices && hardwareAnimation - && mSubMesh->getVertexAnimationType() == VAT_POSE) - { - mParentEntity->bindMissingHardwarePoseBuffers( - mSubMesh->vertexData, mHardwareVertexAnimVertexData.get()); - } - - } - //----------------------------------------------------------------------- - void SubEntity::setRenderQueueGroup(uint8 queueID) - { - mRenderQueueIDSet = true; - mRenderQueueID = queueID; - } - //----------------------------------------------------------------------- - void SubEntity::setRenderQueueGroupAndPriority(uint8 queueID, ushort priority) - { - setRenderQueueGroup(queueID); - mRenderQueuePrioritySet = true; - mRenderQueuePriority = priority; - } - //----------------------------------------------------------------------- -} diff --git a/OgreMain/src/OgreSubMesh.cpp b/OgreMain/src/OgreSubMesh.cpp deleted file mode 100644 index a1f1d7e5e7f..00000000000 --- a/OgreMain/src/OgreSubMesh.cpp +++ /dev/null @@ -1,400 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -namespace Ogre { - //----------------------------------------------------------------------- - SubMesh::SubMesh() - : vertexData(0) - , parent(0) - , useSharedVertices(true) - , operationType(RenderOperation::OT_TRIANGLE_LIST) - , mBoneAssignmentsOutOfDate(false) - , mVertexAnimationType(VAT_NONE) - , mVertexAnimationIncludesNormals(false) - , mBuildEdgesEnabled(true) - { - indexData = OGRE_NEW IndexData(); - } - //----------------------------------------------------------------------- - SubMesh::~SubMesh() - { - removeLodLevels(); - OGRE_DELETE vertexData; - OGRE_DELETE indexData; - } - - //----------------------------------------------------------------------- - void SubMesh::setMaterialName( const String& name, const String& groupName /* = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME */) - { - mMaterial = MaterialManager::getSingleton().getByName(name, groupName); - } - //----------------------------------------------------------------------- - const String& SubMesh::getMaterialName() const - { - return mMaterial ? mMaterial->getName() : BLANKSTRING; - } - //----------------------------------------------------------------------- - void SubMesh::_getRenderOperation(RenderOperation& ro, ushort lodIndex) - { - if (lodIndex > 0 && static_cast< size_t >( lodIndex - 1 ) < mLodFaceList.size()) - { - // lodIndex - 1 because we don't store full detail version in mLodFaceList - ro.indexData = mLodFaceList[lodIndex-1]; - } - else - { - ro.indexData = indexData; - } - ro.useIndexes = ro.indexData->indexCount != 0; - ro.operationType = operationType; - ro.vertexData = useSharedVertices? parent->sharedVertexData : vertexData; - - } - //----------------------------------------------------------------------- - void SubMesh::addBoneAssignment(const VertexBoneAssignment& vertBoneAssign) - { - OgreAssert(!useSharedVertices, - "This SubMesh uses shared geometry, you must assign bones to the Mesh, not the SubMesh"); - mBoneAssignments.emplace(vertBoneAssign.vertexIndex, vertBoneAssign); - mBoneAssignmentsOutOfDate = true; - } - //----------------------------------------------------------------------- - void SubMesh::clearBoneAssignments(void) - { - mBoneAssignments.clear(); - mBoneAssignmentsOutOfDate = true; - } - - //----------------------------------------------------------------------- - void SubMesh::_compileBoneAssignments(void) - { - unsigned short maxBones = - parent->_rationaliseBoneAssignments(vertexData->vertexCount, mBoneAssignments); - - if (maxBones != 0) - { - parent->compileBoneAssignments(mBoneAssignments, maxBones, - blendIndexToBoneIndexMap, vertexData); - } - - mBoneAssignmentsOutOfDate = false; - } - //--------------------------------------------------------------------- - SubMesh::BoneAssignmentIterator SubMesh::getBoneAssignmentIterator(void) - { - return BoneAssignmentIterator(mBoneAssignments.begin(), - mBoneAssignments.end()); - } - //--------------------------------------------------------------------- - void SubMesh::removeLodLevels(void) - { - LODFaceList::iterator lodi, lodend; - lodend = mLodFaceList.end(); - for (lodi = mLodFaceList.begin(); lodi != lodend; ++lodi) - { - OGRE_DELETE *lodi; - } - - mLodFaceList.clear(); - - } - //--------------------------------------------------------------------- - VertexAnimationType SubMesh::getVertexAnimationType(void) const - { - if(parent->_getAnimationTypesDirty()) - { - parent->_determineAnimationTypes(); - } - return mVertexAnimationType; - } - //--------------------------------------------------------------------- - /* To find as many points from different domains as we need, - * such that those domains are from different parts of the mesh, - * we implement a simplified Heckbert quantization algorithm. - * - * This struct is like AxisAlignedBox with some specialized methods - * for doing quantization. - */ - struct Cluster - { - Vector3 mMin, mMax; - std::set mIndices; - - Cluster () - { } - - bool empty () const - { - if (mIndices.empty ()) - return true; - if (mMin == mMax) - return true; - return false; - } - - float volume () const - { - return (mMax.x - mMin.x) * (mMax.y - mMin.y) * (mMax.z - mMin.z); - } - - void extend (float *v) - { - if (v [0] < mMin.x) mMin.x = v [0]; - if (v [1] < mMin.y) mMin.y = v [1]; - if (v [2] < mMin.z) mMin.z = v [2]; - if (v [0] > mMax.x) mMax.x = v [0]; - if (v [1] > mMax.y) mMax.y = v [1]; - if (v [2] > mMax.z) mMax.z = v [2]; - } - - void computeBBox (const VertexElement *poselem, uint8 *vdata, size_t vsz) - { - mMin.x = mMin.y = mMin.z = Math::POS_INFINITY; - mMax.x = mMax.y = mMax.z = Math::NEG_INFINITY; - - for (unsigned int idx : mIndices) - { - float *v; - poselem->baseVertexPointerToElement (vdata + idx * vsz, &v); - extend (v); - } - } - - Cluster split (int split_axis, const VertexElement *poselem, - uint8 *vdata, size_t vsz) - { - Real r = (mMin [split_axis] + mMax [split_axis]) * 0.5f; - Cluster newbox; - - // Separate all points that are inside the new bbox - for (std::set::iterator i = mIndices.begin (); - i != mIndices.end (); ) - { - float *v; - poselem->baseVertexPointerToElement (vdata + *i * vsz, &v); - if (v [split_axis] > r) - { - newbox.mIndices.insert (*i); - std::set::iterator x = i++; - mIndices.erase(x); - } - else - ++i; - } - - computeBBox (poselem, vdata, vsz); - newbox.computeBBox (poselem, vdata, vsz); - - return newbox; - } - }; - //--------------------------------------------------------------------- - void SubMesh::generateExtremes(size_t count) - { - extremityPoints.clear(); - - if (count == 0) - return; - - /* Currently this uses just one criteria: the points must be - * as far as possible from each other. This at least ensures - * that the extreme points characterise the submesh as - * detailed as it's possible. - */ - - VertexData *vert = useSharedVertices ? - parent->sharedVertexData : vertexData; - const VertexElement *poselem = vert->vertexDeclaration-> - findElementBySemantic (VES_POSITION); - HardwareVertexBufferSharedPtr vbuf = vert->vertexBufferBinding-> - getBuffer (poselem->getSource ()); - uint8 *vdata = (uint8 *)vbuf->lock (HardwareBuffer::HBL_READ_ONLY); - size_t vsz = vbuf->getVertexSize (); - - std::vector boxes; - boxes.reserve (count); - - // First of all, find min and max bounding box of the submesh - boxes.push_back (Cluster ()); - - if (indexData->indexCount > 0) - { - - uint elsz = indexData->indexBuffer->getType () == HardwareIndexBuffer::IT_32BIT ? - 4 : 2; - uint8 *idata = (uint8 *)indexData->indexBuffer->lock ( - indexData->indexStart * elsz, indexData->indexCount * elsz, - HardwareIndexBuffer::HBL_READ_ONLY); - - for (size_t i = 0; i < indexData->indexCount; i++) - { - int idx = (elsz == 2) ? ((uint16 *)idata) [i] : ((uint32 *)idata) [i]; - boxes [0].mIndices.insert (idx); - } - indexData->indexBuffer->unlock (); - - } - else - { - // just insert all indexes - for (size_t i = vertexData->vertexStart; i < vertexData->vertexCount; i++) - { - boxes [0].mIndices.insert (static_cast(i)); - } - - } - - boxes [0].computeBBox (poselem, vdata, vsz); - - // Remember the geometrical center of the submesh - Vector3 center = (boxes [0].mMax + boxes [0].mMin) * 0.5; - - // Ok, now loop until we have as many boxes, as we need extremes - while (boxes.size () < count) - { - // Find the largest box with more than one vertex :) - Cluster *split_box = NULL; - Real split_volume = -1; - for (auto & boxe : boxes) - { - if (boxe.empty ()) - continue; - Real v = boxe.volume (); - if (v > split_volume) - { - split_volume = v; - split_box = &boxe; - } - } - - // If we don't have what to split, break - if (!split_box) - break; - - // Find the coordinate axis to split the box into two - int split_axis = 0; - Real split_length = split_box->mMax.x - split_box->mMin.x; - for (int i = 1; i < 3; i++) - { - Real l = split_box->mMax [i] - split_box->mMin [i]; - if (l > split_length) - { - split_length = l; - split_axis = i; - } - } - - // Now split the box into halves - boxes.push_back (split_box->split (split_axis, poselem, vdata, vsz)); - } - - // Fine, now from every cluster choose the vertex that is most - // distant from the geometrical center and from other extremes. - for (const auto & boxe : boxes) - { - Real rating = 0; - Vector3 best_vertex; - - for (unsigned int i : boxe.mIndices) - { - float *v; - poselem->baseVertexPointerToElement (vdata + i * vsz, &v); - - Vector3 vv (v [0], v [1], v [2]); - Real r = (vv - center).squaredLength (); - - for (auto extremityPoint : extremityPoints) - r += (extremityPoint - vv).squaredLength (); - if (r > rating) - { - rating = r; - best_vertex = vv; - } - } - - if (rating > 0) - extremityPoints.push_back (best_vertex); - } - - vbuf->unlock (); - } - //--------------------------------------------------------------------- - void SubMesh::setBuildEdgesEnabled(bool b) - { - mBuildEdgesEnabled = b; - if(parent) - { - parent->freeEdgeList(); - parent->setAutoBuildEdgeLists(true); - } - } - //--------------------------------------------------------------------- - SubMesh * SubMesh::clone(const String& newName, Mesh *parentMesh) - { - // This is a bit like a copy constructor, but with the additional aspect of registering the clone with - // the MeshManager - - if(parentMesh == NULL) - parentMesh = parent; - - HardwareBufferManagerBase* bufferManager = parentMesh->getHardwareBufferManager(); - SubMesh* newSub = parentMesh->createSubMesh(newName); - - newSub->mMaterial = this->mMaterial; - newSub->operationType = this->operationType; - newSub->useSharedVertices = this->useSharedVertices; - newSub->extremityPoints = this->extremityPoints; - - if (!this->useSharedVertices) - { - // Copy unique vertex data - newSub->vertexData = this->vertexData->clone(true, bufferManager); - // Copy unique index map - newSub->blendIndexToBoneIndexMap = this->blendIndexToBoneIndexMap; - } - - // Copy index data - OGRE_DELETE newSub->indexData; - newSub->indexData = this->indexData->clone(true, bufferManager); - // Copy any bone assignments - newSub->mBoneAssignments = this->mBoneAssignments; - newSub->mBoneAssignmentsOutOfDate = this->mBoneAssignmentsOutOfDate; - - // Copy lod face lists - newSub->mLodFaceList.reserve(this->mLodFaceList.size()); - SubMesh::LODFaceList::const_iterator facei; - for (facei = this->mLodFaceList.begin(); facei != this->mLodFaceList.end(); ++facei) { - IndexData* newIndexData = (*facei)->clone(true, bufferManager); - newSub->mLodFaceList.push_back(newIndexData); - } - return newSub; - } -} - - diff --git a/OgreMain/src/OgreTagPoint.cpp b/OgreMain/src/OgreTagPoint.cpp deleted file mode 100644 index 296236dce7b..00000000000 --- a/OgreMain/src/OgreTagPoint.cpp +++ /dev/null @@ -1,163 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreTagPoint.h" -#include "OgreEntity.h" - - -namespace Ogre { - - //----------------------------------------------------------------------------- - TagPoint::TagPoint(unsigned short handle, Skeleton* creator) - : Bone(handle, creator) - , mInheritParentEntityOrientation(true) - , mInheritParentEntityScale(true) - , mParentEntity(0) - , mChildObject(0) - { - } - //----------------------------------------------------------------------------- - Entity *TagPoint::getParentEntity(void) const - { - return mParentEntity; - } - //----------------------------------------------------------------------------- - MovableObject* TagPoint::getChildObject(void) const - { - return mChildObject; - } - //----------------------------------------------------------------------------- - void TagPoint::setParentEntity(Entity *pEntity) - { - mParentEntity = pEntity; - } - //----------------------------------------------------------------------------- - void TagPoint::setChildObject(MovableObject *pObject) - { - mChildObject = pObject; - } - //----------------------------------------------------------------------------- - void TagPoint::setInheritParentEntityOrientation(bool inherit) - { - mInheritParentEntityOrientation = inherit; - needUpdate(); - } - //----------------------------------------------------------------------------- - bool TagPoint::getInheritParentEntityOrientation(void) const - { - return mInheritParentEntityOrientation; - } - //----------------------------------------------------------------------------- - void TagPoint::setInheritParentEntityScale(bool inherit) - { - mInheritParentEntityScale = inherit; - needUpdate(); - } - //----------------------------------------------------------------------------- - bool TagPoint::getInheritParentEntityScale(void) const - { - return mInheritParentEntityScale; - } - //----------------------------------------------------------------------------- - const Affine3& TagPoint::_getFullLocalTransform(void) const - { - return mFullLocalTransform; - } - //----------------------------------------------------------------------------- - const Affine3& TagPoint::getParentEntityTransform(void) const - { - - return mParentEntity->_getParentNodeFullTransform(); - } - //----------------------------------------------------------------------------- - void TagPoint::needUpdate(bool forceParentUpdate) - { - Bone::needUpdate(forceParentUpdate); - - // We need to tell parent entities node - if (mParentEntity) - { - Node* n = mParentEntity->getParentNode(); - if (n) - { - n->needUpdate(); - } - - } - - } - //----------------------------------------------------------------------------- - void TagPoint::updateFromParentImpl(void) const - { - // Call superclass - Bone::updateFromParentImpl(); - - // Save transform for local skeleton - mFullLocalTransform.makeTransform( - mDerivedPosition, - mDerivedScale, - mDerivedOrientation); - - // Include Entity transform - if (mParentEntity) - { - Node* entityParentNode = mParentEntity->getParentNode(); - if (entityParentNode) - { - // Note: orientation/scale inherits from parent node already take care with - // Bone::_updateFromParent, don't do that with parent entity transform. - - // Combine orientation with that of parent entity - const Quaternion& parentOrientation = entityParentNode->_getDerivedOrientation(); - if (mInheritParentEntityOrientation) - { - mDerivedOrientation = parentOrientation * mDerivedOrientation; - } - - // Incorporate parent entity scale - const Vector3& parentScale = entityParentNode->_getDerivedScale(); - if (mInheritParentEntityScale) - { - mDerivedScale *= parentScale; - } - - // Change position vector based on parent entity's orientation & scale - mDerivedPosition = parentOrientation * (parentScale * mDerivedPosition); - - // Add altered position vector to parent entity - mDerivedPosition += entityParentNode->_getDerivedPosition(); - } - } - - if (mChildObject) - { - mChildObject->_notifyMoved(); - } - } - -} diff --git a/OgreMain/src/OgreTangentSpaceCalc.cpp b/OgreMain/src/OgreTangentSpaceCalc.cpp deleted file mode 100644 index d83cfe06347..00000000000 --- a/OgreMain/src/OgreTangentSpaceCalc.cpp +++ /dev/null @@ -1,732 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreTangentSpaceCalc.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - TangentSpaceCalc::TangentSpaceCalc() - : mVData(0) - , mSplitMirrored(false) - , mSplitRotated(false) - , mStoreParityInW(false) - { - } - - //--------------------------------------------------------------------- - void TangentSpaceCalc::clear() - { - mIDataList.clear(); - mOpTypes.clear(); - mVData = 0; - } - //--------------------------------------------------------------------- - void TangentSpaceCalc::setVertexData(VertexData* v_in) - { - mVData = v_in; - } - //--------------------------------------------------------------------- - void TangentSpaceCalc::addIndexData(IndexData* i_in, RenderOperation::OperationType op) - { - if (op != RenderOperation::OT_TRIANGLE_FAN && - op != RenderOperation::OT_TRIANGLE_LIST && - op != RenderOperation::OT_TRIANGLE_STRIP) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Only indexed triangle (list, strip, fan) render operations are supported.", - "TangentSpaceCalc::addIndexData"); - - } - mIDataList.push_back(i_in); - mOpTypes.push_back(op); - } - //--------------------------------------------------------------------- - TangentSpaceCalc::Result TangentSpaceCalc::build(unsigned short sourceTexCoordSet) - { - Result res; - - // Pull out all the vertex components we'll need - populateVertexArray(sourceTexCoordSet); - - // Now process the faces and calculate / add their contributions - processFaces(res); - - // Now normalise & orthogonalise - normaliseVertices(); - - // Create new final geometry - // First extend existing buffers to cope with new vertices - extendBuffers(res.vertexSplits); - - // Alter indexes - remapIndexes(res); - - // Create / identify target & write tangents - insertTangents(res, VES_TANGENT, sourceTexCoordSet, 0); - - return res; - - - } - //--------------------------------------------------------------------- - void TangentSpaceCalc::extendBuffers(VertexSplits& vertexSplits) - { - if (!vertexSplits.empty()) - { - // ok, need to increase the vertex buffer size, and alter some indexes - - // vertex buffers first - VertexBufferBinding* newBindings = HardwareBufferManager::getSingleton().createVertexBufferBinding(); - const VertexBufferBinding::VertexBufferBindingMap& bindmap = - mVData->vertexBufferBinding->getBindings(); - for (const auto & i : bindmap) - { - HardwareVertexBufferSharedPtr srcbuf = i.second; - // Derive vertex count from buffer not vertex data, in case using - // the vertexStart option in vertex data - size_t newVertexCount = srcbuf->getNumVertices() + vertexSplits.size(); - // Create new buffer & bind - HardwareVertexBufferSharedPtr newBuf = - HardwareBufferManager::getSingleton().createVertexBuffer( - srcbuf->getVertexSize(), newVertexCount, srcbuf->getUsage(), - srcbuf->hasShadowBuffer()); - newBindings->setBinding(i.first, newBuf); - - // Copy existing contents (again, entire buffer, not just elements referenced) - newBuf->copyData(*(srcbuf.get()), 0, 0, srcbuf->getNumVertices() * srcbuf->getVertexSize(), true); - - // Split vertices, read / write from new buffer - HardwareBufferLockGuard newBufLock(newBuf, HardwareBuffer::HBL_NORMAL); - char* pBase = static_cast(newBufLock.pData); - for (auto & vertexSplit : vertexSplits) - { - const char* pSrcBase = pBase + vertexSplit.first * newBuf->getVertexSize(); - char* pDstBase = pBase + vertexSplit.second * newBuf->getVertexSize(); - memcpy(pDstBase, pSrcBase, newBuf->getVertexSize()); - } - } - - // Update vertex data - // Increase vertex count according to num splits - mVData->vertexCount += vertexSplits.size(); - // Flip bindings over to new buffers (old buffers released) - HardwareBufferManager::getSingleton().destroyVertexBufferBinding(mVData->vertexBufferBinding); - mVData->vertexBufferBinding = newBindings; - - // If vertex size requires 32bit index buffer - if (mVData->vertexCount > 65536) - { - for (auto idata : mIDataList) - { - // check index size - HardwareIndexBufferSharedPtr srcbuf = idata->indexBuffer; - if (srcbuf->getType() == HardwareIndexBuffer::IT_16BIT) - { - size_t indexCount = srcbuf->getNumIndexes(); - - // convert index buffer to 32bit. - HardwareIndexBufferSharedPtr newBuf = - HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_32BIT, indexCount, - srcbuf->getUsage(), srcbuf->hasShadowBuffer()); - - HardwareBufferLockGuard srcBufLock(srcbuf, HardwareBuffer::HBL_NORMAL); - HardwareBufferLockGuard newBufLock(newBuf, HardwareBuffer::HBL_NORMAL); - uint16* pSrcBase = static_cast(srcBufLock.pData); - uint32* pBase = static_cast(newBufLock.pData); - - size_t j = 0; - while (j < indexCount) - { - *pBase++ = *pSrcBase++; - ++j; - } - - // assign new index buffer. - idata->indexBuffer = newBuf; - } - } - } - } - - } - //--------------------------------------------------------------------- - void TangentSpaceCalc::remapIndexes(Result& res) - { - for (size_t i = 0; i < mIDataList.size(); ++i) - { - - IndexData* idata = mIDataList[i]; - // Now do index data - // no new buffer required, same size but some triangles remapped - HardwareBufferLockGuard indexLock(idata->indexBuffer, HardwareBuffer::HBL_NORMAL); - if (idata->indexBuffer->getType() == HardwareIndexBuffer::IT_32BIT) - { - remapIndexes(static_cast(indexLock.pData), i, res); - } - else - { - remapIndexes(static_cast(indexLock.pData), i, res); - } - } - - } - //--------------------------------------------------------------------- - void TangentSpaceCalc::normaliseVertices() - { - // Just run through our complete (possibly augmented) list of vertices - // Normalise the tangents & binormals - for (auto & v : mVertexArray) - { - v.tangent.normalise(); - v.binormal.normalise(); - - // Orthogonalise with the vertex normal since it's currently - // orthogonal with the face normals, but will be close to ortho - // Apply Gram-Schmidt orthogonalise - Vector3 temp = v.tangent; - v.tangent = temp - (v.norm * v.norm.dotProduct(temp)); - - temp = v.binormal; - v.binormal = temp - (v.norm * v.norm.dotProduct(temp)); - - // renormalize - v.tangent.normalise(); - v.binormal.normalise(); - - } - } - //--------------------------------------------------------------------- - void TangentSpaceCalc::processFaces(Result& result) - { - // Quick pre-check for triangle strips / fans - for (auto & opType : mOpTypes) - { - if (opType != RenderOperation::OT_TRIANGLE_LIST) - { - // Can't split strips / fans - setSplitMirrored(false); - setSplitRotated(false); - } - } - - for (size_t i = 0; i < mIDataList.size(); ++i) - { - IndexData* i_in = mIDataList[i]; - RenderOperation::OperationType opType = mOpTypes[i]; - - // Read data from buffers - HardwareIndexBufferSharedPtr ibuf = i_in->indexBuffer; - HardwareBufferLockGuard ibufLock(ibuf, HardwareBuffer::HBL_READ_ONLY); - uint16 *p16 = static_cast(ibufLock.pData) + i_in->indexStart; - uint32 *p32 = static_cast(ibufLock.pData) + i_in->indexStart; - bool isIT32 = ibuf->getType() == HardwareIndexBuffer::IT_32BIT; - - // current triangle - size_t vertInd[3] = { 0, 0, 0 }; - // loop through all faces to calculate the tangents and normals - size_t faceCount = opType == RenderOperation::OT_TRIANGLE_LIST ? - i_in->indexCount / 3 : i_in->indexCount - 2; - for (size_t f = 0; f < faceCount; ++f) - { - bool invertOrdering = false; - // Read 1 or 3 indexes depending on type - if (f == 0 || opType == RenderOperation::OT_TRIANGLE_LIST) - { - vertInd[0] = isIT32? *p32++ : *p16++; - vertInd[1] = isIT32? *p32++ : *p16++; - vertInd[2] = isIT32? *p32++ : *p16++; - } - else if (opType == RenderOperation::OT_TRIANGLE_FAN) - { - // Element 0 always remains the same - // Element 2 becomes element 1 - vertInd[1] = vertInd[2]; - // read new into element 2 - vertInd[2] = isIT32? *p32++ : *p16++; - } - else if (opType == RenderOperation::OT_TRIANGLE_STRIP) - { - // Shunt everything down one, but also invert the ordering on - // odd numbered triangles (== even numbered i's) - // we interpret front as anticlockwise all the time but strips alternate - if (f & 0x1) - { - // odd tris (index starts at 3, 5, 7) - invertOrdering = true; - } - vertInd[0] = vertInd[1]; - vertInd[1] = vertInd[2]; - vertInd[2] = isIT32? *p32++ : *p16++; - } - - // deal with strip inversion of winding - size_t localVertInd[3]; - localVertInd[0] = vertInd[0]; - if (invertOrdering) - { - localVertInd[1] = vertInd[2]; - localVertInd[2] = vertInd[1]; - } - else - { - localVertInd[1] = vertInd[1]; - localVertInd[2] = vertInd[2]; - } - - - // For each triangle - // Calculate tangent & binormal per triangle - // Note these are not normalised, are weighted by UV area - Vector3 faceTsU, faceTsV, faceNorm; - calculateFaceTangentSpace(localVertInd, faceTsU, faceTsV, faceNorm); - - // Skip invalid UV space triangles - if (faceTsU.isZeroLength() || faceTsV.isZeroLength()) - continue; - - addFaceTangentSpaceToVertices(i, f, localVertInd, faceTsU, faceTsV, faceNorm, result); - - } - } - - } - //--------------------------------------------------------------------- - void TangentSpaceCalc::addFaceTangentSpaceToVertices( - size_t indexSet, size_t faceIndex, size_t *localVertInd, - const Vector3& faceTsU, const Vector3& faceTsV, const Vector3& faceNorm, - Result& result) - { - // Calculate parity for this triangle - int faceParity = calculateParity(faceTsU, faceTsV, faceNorm); - // Now add these to each vertex referenced by the face - for (int v = 0; v < 3; ++v) - { - // index 0 is vertex we're calculating, 1 and 2 are the others - - // We want to re-weight these by the angle the face makes with the vertex - // in order to obtain tessellation-independent results - Real angleWeight = calculateAngleWeight(localVertInd[v], - localVertInd[(v+1)%3], localVertInd[(v+2)%3]); - - - VertexInfo* vertex = &(mVertexArray[localVertInd[v]]); - - // check parity (0 means not set) - // Locate parity-version of vertex index, or create if doesn't exist - // If parity-version of vertex index was different, record alteration - // in triangle remap - // in vertex split list - bool splitVertex = false; - size_t reusedOppositeParity = 0; - bool splitBecauseOfParity = false; - bool newVertex = false; - if (!vertex->parity) - { - // init - vertex->parity = faceParity; - newVertex = true; - } - if (mSplitMirrored) - { - if (!newVertex && faceParity != calculateParity(vertex->tangent, vertex->binormal, vertex->norm))//vertex->parity != faceParity) - { - // Check for existing alternative parity - if (vertex->oppositeParityIndex) - { - // Ok, have already split this vertex because of parity - // Use the same one again - reusedOppositeParity = vertex->oppositeParityIndex; - vertex = &(mVertexArray[reusedOppositeParity]); - } - else - { - splitVertex = true; - splitBecauseOfParity = true; - - LogManager::getSingleton().stream(LML_TRIVIAL) - << "TSC parity split - Vpar: " << vertex->parity - << " Fpar: " << faceParity - << " faceTsU: " << faceTsU - << " faceTsV: " << faceTsV - << " faceNorm: " << faceNorm - << " vertTsU:" << vertex->tangent - << " vertTsV:" << vertex->binormal - << " vertNorm:" << vertex->norm; - - } - } - } - - if (mSplitRotated) - { - - // deal with excessive tangent space rotations as well as mirroring - // same kind of split behaviour appropriate - if (!newVertex && !splitVertex) - { - // If more than 90 degrees, split - Vector3 uvCurrent = vertex->tangent + vertex->binormal; - - // project down to the plane (plane normal = face normal) - Vector3 vRotHalf = uvCurrent - faceNorm; - vRotHalf *= faceNorm.dotProduct(uvCurrent); - - if ((faceTsU + faceTsV).dotProduct(vRotHalf) < 0.0f) - { - splitVertex = true; - } - } - } - - if (splitVertex) - { - size_t newVertexIndex = mVertexArray.size(); - VertexSplit splitInfo(localVertInd[v], newVertexIndex); - result.vertexSplits.push_back(splitInfo); - // re-point opposite parity - if (splitBecauseOfParity) - { - vertex->oppositeParityIndex = newVertexIndex; - } - // copy old values but reset tangent space - VertexInfo locVertex = *vertex; - locVertex.tangent = Vector3::ZERO; - locVertex.binormal = Vector3::ZERO; - locVertex.parity = faceParity; - mVertexArray.push_back(locVertex); - result.indexesRemapped.push_back(IndexRemap(indexSet, faceIndex, splitInfo)); - - vertex = &(mVertexArray[newVertexIndex]); - - } - else if (reusedOppositeParity) - { - // didn't split again, but we do need to record the re-used remapping - VertexSplit splitInfo(localVertInd[v], reusedOppositeParity); - result.indexesRemapped.push_back(IndexRemap(indexSet, faceIndex, splitInfo)); - - } - - // Add weighted tangent & binormal - vertex->tangent += (faceTsU * angleWeight); - vertex->binormal += (faceTsV * angleWeight); - - - } - - } - //--------------------------------------------------------------------- - int TangentSpaceCalc::calculateParity(const Vector3& u, const Vector3& v, const Vector3& n) - { - // Note that this parity is the reverse of what you'd expect - this is - // because the 'V' texture coordinate is actually left handed - if (u.crossProduct(v).dotProduct(n) >= 0.0f) - return -1; - else - return 1; - - } - //--------------------------------------------------------------------- - void TangentSpaceCalc::calculateFaceTangentSpace(const size_t* vertInd, - Vector3& tsU, Vector3& tsV, Vector3& tsN) - { - const VertexInfo& v0 = mVertexArray[vertInd[0]]; - const VertexInfo& v1 = mVertexArray[vertInd[1]]; - const VertexInfo& v2 = mVertexArray[vertInd[2]]; - Vector2 deltaUV1 = v1.uv - v0.uv; - Vector2 deltaUV2 = v2.uv - v0.uv; - Vector3 deltaPos1 = v1.pos - v0.pos; - Vector3 deltaPos2 = v2.pos - v0.pos; - - // face normal - tsN = deltaPos1.crossProduct(deltaPos2); - tsN.normalise(); - - - Real uvarea = deltaUV1.crossProduct(deltaUV2) * 0.5f; - if (Math::RealEqual(uvarea, 0.0f)) - { - // no tangent, null uv area - tsU = tsV = Vector3::ZERO; - } - else - { - - // Normalise by uvarea - Real a = deltaUV2.y / uvarea; - Real b = -deltaUV1.y / uvarea; - Real c = -deltaUV2.x / uvarea; - Real d = deltaUV1.x / uvarea; - - tsU = (deltaPos1 * a) + (deltaPos2 * b); - tsU.normalise(); - - tsV = (deltaPos1 * c) + (deltaPos2 * d); - tsV.normalise(); - - Real abs_uvarea = Math::Abs(uvarea); - tsU *= abs_uvarea; - tsV *= abs_uvarea; - - // tangent (tsU) and binormal (tsV) are now weighted by uv area - - - } - - } - //--------------------------------------------------------------------- - Real TangentSpaceCalc::calculateAngleWeight(size_t vidx0, size_t vidx1, size_t vidx2) - { - const VertexInfo& v0 = mVertexArray[vidx0]; - const VertexInfo& v1 = mVertexArray[vidx1]; - const VertexInfo& v2 = mVertexArray[vidx2]; - - Vector3 diff0 = v1.pos - v0.pos; - Vector3 diff1 = v2.pos - v1.pos; - - // Weight is just the angle - larger == better - return diff0.angleBetween(diff1).valueRadians(); - - } - //--------------------------------------------------------------------- - void TangentSpaceCalc::populateVertexArray(unsigned short sourceTexCoordSet) - { - // Just pull data out into more friendly structures - VertexDeclaration *dcl = mVData->vertexDeclaration; - VertexBufferBinding *bind = mVData->vertexBufferBinding; - - // Get the incoming UV element - const auto* uvElem = dcl->findElementBySemantic(VES_TEXTURE_COORDINATES, sourceTexCoordSet); - - if (!uvElem || uvElem->getType() != VET_FLOAT2) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "No 2D texture coordinates with selected index, cannot calculate tangents"); - } - - // find a normal buffer - const auto* normElem = dcl->findElementBySemantic(VES_NORMAL); - if (!normElem) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "No vertex normals found, cannot calculate tangents"); - - HardwareVertexBufferSharedPtr uvBuf, posBuf, normBuf; - unsigned char *pUvBase, *pPosBase, *pNormBase; - size_t uvInc, posInc, normInc; - - uvBuf = bind->getBuffer(uvElem->getSource()); - pUvBase = static_cast( - uvBuf->lock(HardwareBuffer::HBL_READ_ONLY)); - uvInc = uvBuf->getVertexSize(); - // offset for vertex start - pUvBase += mVData->vertexStart * uvInc; - - // find position - const VertexElement *posElem = dcl->findElementBySemantic(VES_POSITION); - if (posElem->getSource() == uvElem->getSource()) - { - pPosBase = pUvBase; - posInc = uvInc; - } - else - { - // A different buffer - posBuf = bind->getBuffer(posElem->getSource()); - pPosBase = static_cast( - posBuf->lock(HardwareBuffer::HBL_READ_ONLY)); - posInc = posBuf->getVertexSize(); - // offset for vertex start - pPosBase += mVData->vertexStart * posInc; - } - - if (normElem->getSource() == uvElem->getSource()) - { - pNormBase = pUvBase; - normInc = uvInc; - } - else if (normElem->getSource() == posElem->getSource()) - { - // normals are in the same buffer as position - // this condition arises when an animated(skeleton) mesh is not built with - // an edge list buffer ie no shadows being used. - pNormBase = pPosBase; - normInc = posInc; - } - else - { - // A different buffer - normBuf = bind->getBuffer(normElem->getSource()); - pNormBase = static_cast( - normBuf->lock(HardwareBuffer::HBL_READ_ONLY)); - normInc = normBuf->getVertexSize(); - // offset for vertex start - pNormBase += mVData->vertexStart * normInc; - } - - // Preinitialise vertex info - mVertexArray.clear(); - mVertexArray.resize(mVData->vertexCount); - - float* pFloat; - VertexInfo* vInfo = &(mVertexArray[0]); - for (size_t v = 0; v < mVData->vertexCount; ++v, ++vInfo) - { - posElem->baseVertexPointerToElement(pPosBase, &pFloat); - vInfo->pos.x = *pFloat++; - vInfo->pos.y = *pFloat++; - vInfo->pos.z = *pFloat++; - pPosBase += posInc; - - normElem->baseVertexPointerToElement(pNormBase, &pFloat); - vInfo->norm.x = *pFloat++; - vInfo->norm.y = *pFloat++; - vInfo->norm.z = *pFloat++; - pNormBase += normInc; - - uvElem->baseVertexPointerToElement(pUvBase, &pFloat); - vInfo->uv.x = *pFloat++; - vInfo->uv.y = *pFloat++; - pUvBase += uvInc; - - - } - - // unlock buffers - uvBuf->unlock(); - if (posBuf) - { - posBuf->unlock(); - } - if (normBuf) - { - normBuf->unlock(); - } - - } - //--------------------------------------------------------------------- - void TangentSpaceCalc::insertTangents(Result& res, - VertexElementSemantic targetSemantic, unsigned short sourceTexCoordSet, - unsigned short index) - { - // Make a new tangents semantic or find an existing one - VertexDeclaration *vDecl = mVData->vertexDeclaration ; - VertexBufferBinding *vBind = mVData->vertexBufferBinding ; - - const VertexElement *tangentsElem = vDecl->findElementBySemantic(targetSemantic, index); - VertexElementType tangentsType = mStoreParityInW ? VET_FLOAT4 : VET_FLOAT3; - - OgreAssert(!tangentsElem || tangentsElem->getType() == tangentsType, - "Target semantic set already exists but is not of the right size, therefore cannot contain " - "tangents. You should delete this existing entry first"); - - HardwareVertexBufferSharedPtr targetBuffer, origBuffer; - unsigned char* pSrc = NULL; - - if (!tangentsElem) - { - // To be most efficient with our vertex streams, - // tack the new tangents onto the same buffer as the - // source texture coord set - const VertexElement* prevTexCoordElem = - mVData->vertexDeclaration->findElementBySemantic( - VES_TEXTURE_COORDINATES, sourceTexCoordSet); - if (!prevTexCoordElem) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Cannot locate the first texture coordinate element to " - "which to append the new tangents.", - "Mesh::orgagniseTangentsBuffer"); - } - // Find the buffer associated with this element - origBuffer = mVData->vertexBufferBinding->getBuffer( - prevTexCoordElem->getSource()); - // Now create a new buffer, which includes the previous contents - // plus extra space for the 3D coords - targetBuffer = HardwareBufferManager::getSingleton().createVertexBuffer( - origBuffer->getVertexSize() + VertexElement::getTypeSize(tangentsType), - origBuffer->getNumVertices(), - origBuffer->getUsage(), - origBuffer->hasShadowBuffer() ); - // Add the new element - tangentsElem = &(vDecl->addElement( - prevTexCoordElem->getSource(), - origBuffer->getVertexSize(), - tangentsType, - targetSemantic, - index)); - // Set up the source pointer - pSrc = static_cast( - origBuffer->lock(HardwareBuffer::HBL_READ_ONLY)); - // Rebind the new buffer - vBind->setBinding(prevTexCoordElem->getSource(), targetBuffer); - } - else - { - // space already there - origBuffer = mVData->vertexBufferBinding->getBuffer( - tangentsElem->getSource()); - targetBuffer = origBuffer; - } - - auto pDest = static_cast( - targetBuffer->lock(pSrc ? HardwareBuffer::HBL_DISCARD : HardwareBuffer::HBL_WRITE_ONLY)); - size_t origVertSize = origBuffer->getVertexSize(); - size_t newVertSize = targetBuffer->getVertexSize(); - for (size_t v = 0; v < origBuffer->getNumVertices(); ++v) - { - if (pSrc) - { - // Copy original vertex data as well - memcpy(pDest, pSrc, origVertSize); - pSrc += origVertSize; - } - // Write in the tangent - float* pTangent; - tangentsElem->baseVertexPointerToElement(pDest, &pTangent); - VertexInfo& vertInfo = mVertexArray[v]; - *pTangent++ = vertInfo.tangent.x; - *pTangent++ = vertInfo.tangent.y; - *pTangent++ = vertInfo.tangent.z; - if (mStoreParityInW) - *pTangent++ = (float)vertInfo.parity; - - // Next target vertex - pDest += newVertSize; - - } - targetBuffer->unlock(); - - if (pSrc) - { - origBuffer->unlock(); - } - } - -} diff --git a/OgreMain/src/OgreTechnique.cpp b/OgreMain/src/OgreTechnique.cpp deleted file mode 100644 index 7536912053d..00000000000 --- a/OgreMain/src/OgreTechnique.cpp +++ /dev/null @@ -1,1089 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreMaterial.h" - - -namespace Ogre { - //----------------------------------------------------------------------------- - Technique::Technique(Material* parent) - : mParent(parent), mIlluminationPassesCompilationPhase(IPS_NOT_COMPILED), mIsSupported(false), mLodIndex(0), mSchemeIndex(0) - { - // See above, defaults to unsupported until examined - } - //----------------------------------------------------------------------------- - Technique::Technique(Material* parent, const Technique& oth) - : mParent(parent), mLodIndex(0), mSchemeIndex(0) - { - // Copy using operator= - *this = oth; - } - //----------------------------------------------------------------------------- - Technique::~Technique() - { - removeAllPasses(); - clearIlluminationPasses(); - } - //----------------------------------------------------------------------------- - bool Technique::isSupported(void) const - { - return mIsSupported; - } - //----------------------------------------------------------------------------- - size_t Technique::calculateSize(void) const - { - size_t memSize = 0; - - // Tally up passes - for (auto *p : mPasses) - { - memSize += p->calculateSize(); - } - return memSize; - } - //----------------------------------------------------------------------------- - String Technique::_compile(bool autoManageTextureUnits) - { - StringStream errors; - - if(!Root::getSingleton().getRenderSystem()) { - errors << "NULL RenderSystem"; - } else { - mIsSupported = checkGPURules(errors) && checkHardwareSupport(autoManageTextureUnits, errors); - } - - // Compile for categorised illumination on demand - clearIlluminationPasses(); - mIlluminationPassesCompilationPhase = IPS_NOT_COMPILED; - - return errors.str(); - - } - //--------------------------------------------------------------------- - bool Technique::checkHardwareSupport(bool autoManageTextureUnits, StringStream& compileErrors) - { - // Go through each pass, checking requirements - Passes::iterator i; - unsigned short passNum = 0; - const RenderSystemCapabilities* caps = - Root::getSingleton().getRenderSystem()->getCapabilities(); - unsigned short numTexUnits = caps->getNumTextureUnits(); - for (i = mPasses.begin(); i != mPasses.end(); ++i, ++passNum) - { - Pass* currPass = *i; - // Adjust pass index - currPass->_notifyIndex(passNum); - - const char* err = 0; - - if(currPass->getLineWidth() != 1 && !caps->hasCapability(RSC_WIDE_LINES)) - err = "line_width > 1"; - else if(currPass->getPointSize() != 1 && !caps->hasCapability(RSC_POINT_SPRITES)) - err = "point_size > 1"; - - if(err) - { - compileErrors << "Pass " << passNum << ": " << err << " not supported by RenderSystem"; - return false; - } - - // Check a few fixed-function options in texture layers - size_t texUnit = 0; - for(const TextureUnitState* tex : currPass->getTextureUnitStates()) - { - if ((tex->getTextureType() == TEX_TYPE_3D) && !caps->hasCapability(RSC_TEXTURE_3D)) - err = "Volume"; - - if ((tex->getTextureType() == TEX_TYPE_2D_ARRAY) && !caps->hasCapability(RSC_TEXTURE_2D_ARRAY)) - err = "Array"; - - if (err) - { - // Fail - compileErrors << "Pass " << passNum << " Tex " << texUnit << ": " << err - << " textures not supported by RenderSystem"; - return false; - } - ++texUnit; - } - - // Check texture unit requirements - size_t numTexUnitsRequested = currPass->getNumTextureUnitStates(); - // Don't trust getNumTextureUnits for programmable - if(!currPass->hasFragmentProgram()) - { -#if defined(OGRE_PRETEND_TEXTURE_UNITS) && OGRE_PRETEND_TEXTURE_UNITS > 0 - numTexUnits = std::min(numTexUnits, OGRE_PRETEND_TEXTURE_UNITS); -#endif - if (numTexUnitsRequested > numTexUnits) - { - if (!autoManageTextureUnits) - { - // The user disabled auto pass split - compileErrors << "Pass " << passNum << - ": Too many texture units for the current hardware and no splitting allowed"; - return false; - } - else if (currPass->hasVertexProgram()) - { - // Can't do this one, and can't split a programmable pass - compileErrors << "Pass " << passNum << - ": Too many texture units for the current hardware and " - "cannot split programmable passes"; - return false; - } - } - - // We're ok on operations, now we need to check # texture units - - // Keep splitting this pass so long as units requested > gpu units - while (numTexUnitsRequested > numTexUnits) - { - // chop this pass into many passes - currPass = currPass->_split(numTexUnits); - numTexUnitsRequested = currPass->getNumTextureUnitStates(); - // Advance pass number - ++passNum; - // Reset iterator - i = mPasses.begin() + passNum; - // Move the new pass to the right place (will have been created - // at the end, may be other passes in between) - assert(mPasses.back() == currPass); - std::copy_backward(i, (mPasses.end() - 1), mPasses.end()); - *i = currPass; - // Adjust pass index - currPass->_notifyIndex(passNum); - } - } - - - - //Check compilation errors for all program types. - for (int t = 0; t < 6; t++) - { - GpuProgramType programType = GpuProgramType(t); - if (currPass->hasGpuProgram(programType)) - { - GpuProgramPtr program = currPass->getGpuProgram(programType); - if (!program->isSupported()) - { - compileErrors << "Pass " << passNum << - ": " << GpuProgram::getProgramTypeName(programType) + " program " << program->getName() - << " cannot be used - "; - if (program->hasCompileError() && program->getSource().empty()) - compileErrors << "resource not found"; - else if (program->hasCompileError()) - compileErrors << "compile error"; - else - compileErrors << "not supported"; - - return false; - } - } - } - } - // If we got this far, we're ok - return true; - } - //--------------------------------------------------------------------- - bool Technique::checkGPURules(StringStream& errors) - { - const RenderSystemCapabilities* caps = - Root::getSingleton().getRenderSystem()->getCapabilities(); - - StringStream includeRules; - bool includeRulesPresent = false; - bool includeRuleMatched = false; - - // Check vendors first - for (auto& r : mGPUVendorRules) - { - if (r.includeOrExclude == INCLUDE) - { - includeRulesPresent = true; - includeRules << caps->vendorToString(r.vendor) << " "; - if (r.vendor == caps->getVendor()) - includeRuleMatched = true; - } - else // EXCLUDE - { - if (r.vendor == caps->getVendor()) - { - errors << "Excluded GPU vendor: " << caps->vendorToString(r.vendor) - << std::endl; - return false; - } - - } - } - - if (includeRulesPresent && !includeRuleMatched) - { - errors << "Failed to match GPU vendor: " << includeRules.str( ) - << std::endl; - return false; - } - - // now check device names - includeRules.str(BLANKSTRING); - includeRulesPresent = false; - includeRuleMatched = false; - - for (auto& r : mGPUDeviceNameRules) - { - if (r.includeOrExclude == INCLUDE) - { - includeRulesPresent = true; - includeRules << r.devicePattern << " "; - if (StringUtil::match(caps->getDeviceName(), r.devicePattern, r.caseSensitive)) - includeRuleMatched = true; - } - else // EXCLUDE - { - if (StringUtil::match(caps->getDeviceName(), r.devicePattern, r.caseSensitive)) - { - errors << "Excluded GPU device: " << r.devicePattern - << std::endl; - return false; - } - - } - } - - if (includeRulesPresent && !includeRuleMatched) - { - errors << "Failed to match GPU device: " << includeRules.str( ) - << std::endl; - return false; - } - - // passed - return true; - } - //----------------------------------------------------------------------------- - Pass* Technique::createPass(void) - { - Pass* newPass = OGRE_NEW Pass(this, static_cast(mPasses.size())); - mPasses.push_back(newPass); - return newPass; - } - //----------------------------------------------------------------------------- - Pass* Technique::getPass(const String& name) const - { - // iterate through techniques to find a match - for (Pass *p : mPasses) { - if (p->getName() == name ) - return p; - } - - return (Pass *)0; - } - //----------------------------------------------------------------------------- - void Technique::removePass(unsigned short index) - { - assert(index < mPasses.size() && "Index out of bounds"); - Passes::iterator i = mPasses.begin() + index; - (*i)->queueForDeletion(); - i = mPasses.erase(i); - // Adjust passes index - for (; i != mPasses.end(); ++i, ++index) - { - (*i)->_notifyIndex(index); - } - } - //----------------------------------------------------------------------------- - void Technique::removeAllPasses(void) - { - for (auto *p : mPasses) - { - p->queueForDeletion(); - } - mPasses.clear(); - } - - //----------------------------------------------------------------------------- - bool Technique::movePass(const unsigned short sourceIndex, const unsigned short destinationIndex) - { - bool moveSuccessful = false; - - // don't move the pass if source == destination - if (sourceIndex == destinationIndex) return true; - - if( (sourceIndex < mPasses.size()) && (destinationIndex < mPasses.size())) - { - Passes::iterator i = mPasses.begin() + sourceIndex; - //Passes::iterator DestinationIterator = mPasses.begin() + destinationIndex; - - Pass* pass = (*i); - mPasses.erase(i); - - i = mPasses.begin() + destinationIndex; - - mPasses.insert(i, pass); - - // Adjust passes index - unsigned short beginIndex, endIndex; - if (destinationIndex > sourceIndex) - { - beginIndex = sourceIndex; - endIndex = destinationIndex; - } - else - { - beginIndex = destinationIndex; - endIndex = sourceIndex; - } - for (unsigned short index = beginIndex; index <= endIndex; ++index) - { - mPasses[index]->_notifyIndex(index); - } - moveSuccessful = true; - } - - return moveSuccessful; - } - - //----------------------------------------------------------------------------- - const Technique::PassIterator Technique::getPassIterator(void) - { - return PassIterator(mPasses.begin(), mPasses.end()); - } - //----------------------------------------------------------------------------- - Technique& Technique::operator=(const Technique& rhs) - { - if (this == &rhs) - return *this; - - mName = rhs.mName; - this->mIsSupported = rhs.mIsSupported; - this->mLodIndex = rhs.mLodIndex; - this->mSchemeIndex = rhs.mSchemeIndex; - this->mShadowCasterMaterial = rhs.mShadowCasterMaterial; - this->mShadowCasterMaterialName = rhs.mShadowCasterMaterialName; - this->mShadowReceiverMaterial = rhs.mShadowReceiverMaterial; - this->mShadowReceiverMaterialName = rhs.mShadowReceiverMaterialName; - this->mGPUVendorRules = rhs.mGPUVendorRules; - this->mGPUDeviceNameRules = rhs.mGPUDeviceNameRules; - - // copy passes - removeAllPasses(); - for (auto *rp : rhs.mPasses) - { - Pass* p = OGRE_NEW Pass(this, rp->getIndex(), *(rp)); - mPasses.push_back(p); - } - // Compile for categorised illumination on demand - clearIlluminationPasses(); - mIlluminationPassesCompilationPhase = IPS_NOT_COMPILED; - return *this; - } - //----------------------------------------------------------------------------- - bool Technique::isTransparent(void) const - { - if (mPasses.empty()) - { - return false; - } - else - { - // Base decision on the transparency of the first pass - return mPasses[0]->isTransparent(); - } - } - //----------------------------------------------------------------------------- - bool Technique::isTransparentSortingEnabled(void) const - { - if (mPasses.empty()) - { - return true; - } - else - { - // Base decision on the transparency of the first pass - return mPasses[0]->getTransparentSortingEnabled(); - } - } - //----------------------------------------------------------------------------- - bool Technique::isTransparentSortingForced(void) const - { - if (mPasses.empty()) - { - return false; - } - else - { - // Base decision on the first pass - return mPasses[0]->getTransparentSortingForced(); - } - } - //----------------------------------------------------------------------------- - bool Technique::isDepthWriteEnabled(void) const - { - if (mPasses.empty()) - { - return false; - } - else - { - // Base decision on the depth settings of the first pass - return mPasses[0]->getDepthWriteEnabled(); - } - } - //----------------------------------------------------------------------------- - bool Technique::isDepthCheckEnabled(void) const - { - if (mPasses.empty()) - { - return false; - } - else - { - // Base decision on the depth settings of the first pass - return mPasses[0]->getDepthCheckEnabled(); - } - } - //----------------------------------------------------------------------------- - bool Technique::hasColourWriteDisabled(void) const - { - if (mPasses.empty()) - { - return true; - } - else - { - // Base decision on the colour write settings of the first pass - return !mPasses[0]->getColourWriteEnabled(); - } - } - //----------------------------------------------------------------------------- - void Technique::_prepare(void) - { - assert (mIsSupported && "This technique is not supported"); - // Load each pass - for (auto *p : mPasses) - { - p->_prepare(); - } - - for (auto *i : mIlluminationPasses) - { - if(i->pass != i->originalPass) - i->pass->_prepare(); - } - } - //----------------------------------------------------------------------------- - void Technique::_unprepare(void) - { - // Unload each pass - for (auto *p : mPasses) - { - p->_unprepare(); - } - } - //----------------------------------------------------------------------------- - void Technique::_load(void) - { - // Load each pass - for (auto *p : mPasses) - { - p->_load(); - } - - for (auto *i : mIlluminationPasses) - { - if(i->pass != i->originalPass) - i->pass->_load(); - } - - if (!mShadowCasterMaterial && !mShadowCasterMaterialName.empty()) - { - // in case we could not get material as it wasn't yet parsed/existent at that time. - mShadowCasterMaterial = MaterialManager::getSingleton().getByName(mShadowCasterMaterialName); - } - - if (mShadowCasterMaterial && mShadowCasterMaterial.get() != getParent()) - { - mShadowCasterMaterial->load(); - } - - if(!mShadowReceiverMaterial && !mShadowReceiverMaterialName.empty()) - { - // in case we could not get material as it wasn't yet parsed/existent at that time. - mShadowReceiverMaterial = MaterialManager::getSingleton().getByName(mShadowReceiverMaterialName); - } - - if (mShadowReceiverMaterial && mShadowReceiverMaterial.get() != getParent()) - { - mShadowReceiverMaterial->load(); - } - } - //----------------------------------------------------------------------------- - void Technique::_unload(void) - { - // Unload each pass - for (auto *p : mPasses) - { - p->_unload(); - } - } - //----------------------------------------------------------------------------- - bool Technique::isLoaded(void) const - { - // Only supported technique will be loaded - return mParent->isLoaded() && mIsSupported; - } - //----------------------------------------------------------------------- - #define ALL_PASSES(fncall) for(auto p : mPasses) p->fncall - void Technique::setPointSize(Real ps) { ALL_PASSES(setPointSize(ps)); } - //----------------------------------------------------------------------- - void Technique::setAmbient(float red, float green, float blue) { setAmbient(ColourValue(red, green, blue)); } - //----------------------------------------------------------------------- - void Technique::setAmbient(const ColourValue& ambient) { ALL_PASSES(setAmbient(ambient)); } - //----------------------------------------------------------------------- - void Technique::setDiffuse(float red, float green, float blue, float alpha) - { - ALL_PASSES(setDiffuse(red, green, blue, alpha)); - } - //----------------------------------------------------------------------- - void Technique::setDiffuse(const ColourValue& diffuse) { setDiffuse(diffuse.r, diffuse.g, diffuse.b, diffuse.a); } - //----------------------------------------------------------------------- - void Technique::setSpecular(float red, float green, float blue, float alpha) - { - ALL_PASSES(setSpecular(red, green, blue, alpha)); - } - //----------------------------------------------------------------------- - void Technique::setSpecular(const ColourValue& specular) - { - setSpecular(specular.r, specular.g, specular.b, specular.a); - } - //----------------------------------------------------------------------- - void Technique::setShininess(Real val) { ALL_PASSES(setShininess(val)); } - //----------------------------------------------------------------------- - void Technique::setSelfIllumination(float red, float green, float blue) - { - setSelfIllumination(ColourValue(red, green, blue)); - } - //----------------------------------------------------------------------- - void Technique::setSelfIllumination(const ColourValue& selfIllum) { ALL_PASSES(setSelfIllumination(selfIllum)); } - //----------------------------------------------------------------------- - void Technique::setDepthCheckEnabled(bool enabled) { ALL_PASSES(setDepthCheckEnabled(enabled)); } - //----------------------------------------------------------------------- - void Technique::setDepthWriteEnabled(bool enabled) { ALL_PASSES(setDepthWriteEnabled(enabled)); } - //----------------------------------------------------------------------- - void Technique::setDepthFunction(CompareFunction func) { ALL_PASSES(setDepthFunction(func)); } - //----------------------------------------------------------------------- - void Technique::setColourWriteEnabled(bool enabled) { ALL_PASSES(setColourWriteEnabled(enabled)); } - //----------------------------------------------------------------------- - void Technique::setColourWriteEnabled(bool red, bool green, bool blue, bool alpha) - { - ALL_PASSES(setColourWriteEnabled(red, green, blue, alpha)); - } - //----------------------------------------------------------------------- - void Technique::setCullingMode(CullingMode mode) { ALL_PASSES(setCullingMode(mode)); } - //----------------------------------------------------------------------- - void Technique::setManualCullingMode(ManualCullingMode mode) { ALL_PASSES(setManualCullingMode(mode)); } - //----------------------------------------------------------------------- - void Technique::setLightingEnabled(bool enabled) { ALL_PASSES(setLightingEnabled(enabled)); } - //----------------------------------------------------------------------- - void Technique::setShadingMode(ShadeOptions mode) { ALL_PASSES(setShadingMode(mode)); } - //----------------------------------------------------------------------- - void Technique::setFog(bool overrideScene, FogMode mode, const ColourValue& colour, Real expDensity, - Real linearStart, Real linearEnd) - { - ALL_PASSES(setFog(overrideScene, mode, colour, expDensity, linearStart, linearEnd)); - } - //----------------------------------------------------------------------- - void Technique::setDepthBias(float constantBias, float slopeScaleBias) - { - ALL_PASSES(setDepthBias(constantBias, slopeScaleBias)); - } - //----------------------------------------------------------------------- - void Technique::setTextureFiltering(TextureFilterOptions filterType) - { - ALL_PASSES(setTextureFiltering(filterType)); - } - // -------------------------------------------------------------------- - void Technique::setTextureAnisotropy(unsigned int maxAniso) { ALL_PASSES(setTextureAnisotropy(maxAniso)); } - // -------------------------------------------------------------------- - void Technique::setSceneBlending(const SceneBlendType sbt) { ALL_PASSES(setSceneBlending(sbt)); } - // -------------------------------------------------------------------- - void Technique::setSeparateSceneBlending(const SceneBlendType sbt, const SceneBlendType sbta) - { - ALL_PASSES(setSeparateSceneBlending(sbt, sbta)); - } - // -------------------------------------------------------------------- - void Technique::setSceneBlending(const SceneBlendFactor sourceFactor, const SceneBlendFactor destFactor) - { - ALL_PASSES(setSceneBlending(sourceFactor, destFactor)); - } - // -------------------------------------------------------------------- - void Technique::setSeparateSceneBlending( const SceneBlendFactor sourceFactor, const SceneBlendFactor destFactor, const SceneBlendFactor sourceFactorAlpha, const SceneBlendFactor destFactorAlpha) - { - ALL_PASSES(setSeparateSceneBlending(sourceFactor, destFactor, sourceFactorAlpha, destFactorAlpha)); - } - #undef ALL_PASSES - - // -------------------------------------------------------------------- - void Technique::setName(const String& name) - { - mName = name; - } - - - //----------------------------------------------------------------------- - void Technique::_notifyNeedsRecompile(void) - { - // Disable require to recompile when splitting illumination passes - if (mIlluminationPassesCompilationPhase != IPS_COMPILE_DISABLED) - { - mParent->_notifyNeedsRecompile(); - } - } - //----------------------------------------------------------------------- - void Technique::setLodIndex(unsigned short index) - { - mLodIndex = index; - _notifyNeedsRecompile(); - } - //----------------------------------------------------------------------- - void Technique::setSchemeName(const String& schemeName) - { - mSchemeIndex = MaterialManager::getSingleton()._getSchemeIndex(schemeName); - _notifyNeedsRecompile(); - } - //----------------------------------------------------------------------- - const String& Technique::getSchemeName(void) const - { - return MaterialManager::getSingleton()._getSchemeName(mSchemeIndex); - } - //----------------------------------------------------------------------- - unsigned short Technique::_getSchemeIndex(void) const - { - return mSchemeIndex; - } - //--------------------------------------------------------------------- - bool Technique::checkManuallyOrganisedIlluminationPasses() - { - // first check whether all passes have manually assigned illumination - for (auto *p : mPasses) - { - if (p->getIlluminationStage() == IS_UNKNOWN) - return false; - } - - // ok, all manually controlled, so just use that - for (auto *p : mPasses) - { - IlluminationPass* iPass = OGRE_NEW IlluminationPass(); - iPass->destroyOnShutdown = false; - iPass->originalPass = iPass->pass = p; - iPass->stage = p->getIlluminationStage(); - mIlluminationPasses.push_back(iPass); - } - - return true; - } - //----------------------------------------------------------------------- - void Technique::_compileIlluminationPasses(void) - { - clearIlluminationPasses(); - - if (!checkManuallyOrganisedIlluminationPasses()) - { - // Build based on our own heuristics - - Passes::iterator i, iend; - iend = mPasses.end(); - i = mPasses.begin(); - - IlluminationStage iStage = IS_AMBIENT; - - bool haveAmbient = false; - while (i != iend) - { - IlluminationPass* iPass; - Pass* p = *i; - switch(iStage) - { - case IS_AMBIENT: - // Keep looking for ambient only - if (p->isAmbientOnly()) - { - // Add this pass wholesale - iPass = OGRE_NEW IlluminationPass(); - iPass->destroyOnShutdown = false; - iPass->originalPass = iPass->pass = p; - iPass->stage = iStage; - mIlluminationPasses.push_back(iPass); - haveAmbient = true; - // progress to next pass - ++i; - } - else - { - // Split off any ambient part - if (p->getAmbient() != ColourValue::Black || - p->getSelfIllumination() != ColourValue::Black || - p->getAlphaRejectFunction() != CMPF_ALWAYS_PASS) - { - // Copy existing pass - Pass* newPass = OGRE_NEW Pass(this, p->getIndex(), *p); - if (newPass->getAlphaRejectFunction() != CMPF_ALWAYS_PASS) - { - // Alpha rejection passes must retain their transparency, so - // we allow the texture units, but override the colour functions - for(auto *s : newPass->getTextureUnitStates()) - { - s->setColourOperationEx(LBX_SOURCE1, LBS_CURRENT); - } - } - else - { - // Remove any texture units - newPass->removeAllTextureUnitStates(); - } - // Remove any fragment program - if (newPass->hasFragmentProgram()) - newPass->setFragmentProgram(""); - // We have to leave vertex program alone (if any) and - // just trust that the author is using light bindings, which - // we will ensure there are none in the ambient pass - newPass->setDiffuse(0, 0, 0, newPass->getDiffuse().a); // Preserving alpha - newPass->setSpecular(ColourValue::Black); - - // Calculate hash value for new pass, because we are compiling - // illumination passes on demand, which will loss hash calculate - // before it add to render queue first time. - newPass->_recalculateHash(); - - iPass = OGRE_NEW IlluminationPass(); - iPass->destroyOnShutdown = true; - iPass->originalPass = p; - iPass->pass = newPass; - iPass->stage = iStage; - - mIlluminationPasses.push_back(iPass); - haveAmbient = true; - - } - - if (!haveAmbient) - { - // Make up a new basic pass - Pass* newPass = OGRE_NEW Pass(this, p->getIndex()); - newPass->setAmbient(ColourValue::Black); - newPass->setDiffuse(ColourValue::Black); - - // Calculate hash value for new pass, because we are compiling - // illumination passes on demand, which will loss hash calculate - // before it add to render queue first time. - newPass->_recalculateHash(); - - iPass = OGRE_NEW IlluminationPass(); - iPass->destroyOnShutdown = true; - iPass->originalPass = p; - iPass->pass = newPass; - iPass->stage = iStage; - mIlluminationPasses.push_back(iPass); - haveAmbient = true; - } - // This means we're done with ambients, progress to per-light - iStage = IS_PER_LIGHT; - } - break; - case IS_PER_LIGHT: - if (p->getIteratePerLight()) - { - // If this is per-light already, use it directly - iPass = OGRE_NEW IlluminationPass(); - iPass->destroyOnShutdown = false; - iPass->originalPass = iPass->pass = p; - iPass->stage = iStage; - mIlluminationPasses.push_back(iPass); - // progress to next pass - ++i; - } - else - { - // Split off per-light details (can only be done for one) - if (p->getLightingEnabled() && - (p->getDiffuse() != ColourValue::Black || - p->getSpecular() != ColourValue::Black)) - { - // Copy existing pass - Pass* newPass = OGRE_NEW Pass(this, p->getIndex(), *p); - if (newPass->getAlphaRejectFunction() != CMPF_ALWAYS_PASS) - { - // Alpha rejection passes must retain their transparency, so - // we allow the texture units, but override the colour functions - for(auto *s : newPass->getTextureUnitStates()) - { - s->setColourOperationEx(LBX_SOURCE1, LBS_CURRENT); - } - } - else - { - // remove texture units - newPass->removeAllTextureUnitStates(); - } - // remove fragment programs - if (newPass->hasFragmentProgram()) - newPass->setFragmentProgram(""); - // Cannot remove vertex program, have to assume that - // it will process diffuse lights, ambient will be turned off - newPass->setAmbient(ColourValue::Black); - newPass->setSelfIllumination(ColourValue::Black); - // must be additive - newPass->setSceneBlending(SBF_ONE, SBF_ONE); - - // Calculate hash value for new pass, because we are compiling - // illumination passes on demand, which will loss hash calculate - // before it add to render queue first time. - newPass->_recalculateHash(); - - iPass = OGRE_NEW IlluminationPass(); - iPass->destroyOnShutdown = true; - iPass->originalPass = p; - iPass->pass = newPass; - iPass->stage = iStage; - - mIlluminationPasses.push_back(iPass); - - } - // This means the end of per-light passes - iStage = IS_DECAL; - } - break; - case IS_DECAL: - // We just want a 'lighting off' pass to finish off - // and only if there are texture units - if (p->getNumTextureUnitStates() > 0) - { - if (!p->getLightingEnabled()) - { - // we assume this pass already combines as required with the scene - iPass = OGRE_NEW IlluminationPass(); - iPass->destroyOnShutdown = false; - iPass->originalPass = iPass->pass = p; - iPass->stage = iStage; - mIlluminationPasses.push_back(iPass); - } - else - { - // Copy the pass and tweak away the lighting parts - Pass* newPass = OGRE_NEW Pass(this, p->getIndex(), *p); - newPass->setAmbient(ColourValue::Black); - newPass->setDiffuse(0, 0, 0, newPass->getDiffuse().a); // Preserving alpha - newPass->setSpecular(ColourValue::Black); - newPass->setSelfIllumination(ColourValue::Black); - newPass->setLightingEnabled(false); - newPass->setIteratePerLight(false, false); - // modulate - newPass->setSceneBlending(SBF_DEST_COLOUR, SBF_ZERO); - - // Calculate hash value for new pass, because we are compiling - // illumination passes on demand, which will loss hash calculate - // before it add to render queue first time. - newPass->_recalculateHash(); - - // NB there is nothing we can do about vertex & fragment - // programs here, so people will just have to make their - // programs friendly-like if they want to use this technique - iPass = OGRE_NEW IlluminationPass(); - iPass->destroyOnShutdown = true; - iPass->originalPass = p; - iPass->pass = newPass; - iPass->stage = iStage; - mIlluminationPasses.push_back(iPass); - - } - } - ++i; // always increment on decal, since nothing more to do with this pass - - break; - case IS_UNKNOWN: - break; - } - } - } - - } - //----------------------------------------------------------------------- - void Technique::clearIlluminationPasses(void) - { - if(MaterialManager::getSingletonPtr()) - MaterialManager::getSingleton()._notifyBeforeIlluminationPassesCleared(this); - - for (auto *i : mIlluminationPasses) - { - if (i->destroyOnShutdown) - { - i->pass->queueForDeletion(); - } - OGRE_DELETE i; - } - mIlluminationPasses.clear(); - } - //----------------------------------------------------------------------- - const IlluminationPassList& - Technique::getIlluminationPasses(void) - { - IlluminationPassesState targetState = IPS_COMPILED; - if(mIlluminationPassesCompilationPhase != targetState - && mIlluminationPassesCompilationPhase != IPS_COMPILE_DISABLED) - { - // prevents parent->_notifyNeedsRecompile() call during compile - mIlluminationPassesCompilationPhase = IPS_COMPILE_DISABLED; - // Splitting the passes into illumination passes - _compileIlluminationPasses(); - // Post notification, so that technique owner can post-process created passes - if(MaterialManager::getSingletonPtr()) - MaterialManager::getSingleton()._notifyAfterIlluminationPassesCreated(this); - // Mark that illumination passes compilation finished - mIlluminationPassesCompilationPhase = targetState; - } - - return mIlluminationPasses; - } - //----------------------------------------------------------------------- - const String& Technique::getResourceGroup(void) const - { - return mParent->getGroup(); - } - //----------------------------------------------------------------------- - Ogre::MaterialPtr Technique::getShadowCasterMaterial() const - { - return mShadowCasterMaterial; - } - //----------------------------------------------------------------------- - void Technique::setShadowCasterMaterial(Ogre::MaterialPtr val) - { - if (!val) - { - mShadowCasterMaterial.reset(); - mShadowCasterMaterialName.clear(); - } - else - { - // shadow caster material should never receive shadows - val->setReceiveShadows(false); // should we warn if this is not set? - mShadowCasterMaterial = val; - mShadowCasterMaterialName = val->getName(); - } - } - //----------------------------------------------------------------------- - void Technique::setShadowCasterMaterial(const Ogre::String &name) - { - setShadowCasterMaterial(MaterialManager::getSingleton().getByName(name)); - // remember the name, even if it is not created yet - mShadowCasterMaterialName = name; - } - //----------------------------------------------------------------------- - Ogre::MaterialPtr Technique::getShadowReceiverMaterial() const - { - return mShadowReceiverMaterial; - } - //----------------------------------------------------------------------- - void Technique::setShadowReceiverMaterial(Ogre::MaterialPtr val) - { - if (!val) - { - mShadowReceiverMaterial.reset(); - mShadowReceiverMaterialName.clear(); - } - else - { - mShadowReceiverMaterial = val; - mShadowReceiverMaterialName = val->getName(); - } - } - //----------------------------------------------------------------------- - void Technique::setShadowReceiverMaterial(const Ogre::String &name) - { - mShadowReceiverMaterialName = name; - mShadowReceiverMaterial = MaterialManager::getSingleton().getByName(name); - } - //--------------------------------------------------------------------- - void Technique::addGPUVendorRule(GPUVendor vendor, Technique::IncludeOrExclude includeOrExclude) - { - addGPUVendorRule(GPUVendorRule(vendor, includeOrExclude)); - } - //--------------------------------------------------------------------- - void Technique::addGPUVendorRule(const Technique::GPUVendorRule& rule) - { - // remove duplicates - removeGPUVendorRule(rule.vendor); - mGPUVendorRules.push_back(rule); - } - //--------------------------------------------------------------------- - void Technique::removeGPUVendorRule(GPUVendor vendor) - { - for (GPUVendorRuleList::iterator i = mGPUVendorRules.begin(); i != mGPUVendorRules.end(); ) - { - if (i->vendor == vendor) - i = mGPUVendorRules.erase(i); - else - ++i; - } - } - //--------------------------------------------------------------------- - Technique::GPUVendorRuleIterator Technique::getGPUVendorRuleIterator() const - { - return GPUVendorRuleIterator(mGPUVendorRules.begin(), mGPUVendorRules.end()); - } - //--------------------------------------------------------------------- - void Technique::addGPUDeviceNameRule(const String& devicePattern, - Technique::IncludeOrExclude includeOrExclude, bool caseSensitive) - { - addGPUDeviceNameRule(GPUDeviceNameRule(devicePattern, includeOrExclude, caseSensitive)); - } - //--------------------------------------------------------------------- - void Technique::addGPUDeviceNameRule(const Technique::GPUDeviceNameRule& rule) - { - // remove duplicates - removeGPUDeviceNameRule(rule.devicePattern); - mGPUDeviceNameRules.push_back(rule); - } - //--------------------------------------------------------------------- - void Technique::removeGPUDeviceNameRule(const String& devicePattern) - { - for (GPUDeviceNameRuleList::iterator i = mGPUDeviceNameRules.begin(); i != mGPUDeviceNameRules.end(); ) - { - if (i->devicePattern == devicePattern) - i = mGPUDeviceNameRules.erase(i); - else - ++i; - } - } - //--------------------------------------------------------------------- - Technique::GPUDeviceNameRuleIterator Technique::getGPUDeviceNameRuleIterator() const - { - return GPUDeviceNameRuleIterator(mGPUDeviceNameRules.begin(), mGPUDeviceNameRules.end()); - } - //--------------------------------------------------------------------- -} diff --git a/OgreMain/src/OgreTexture.cpp b/OgreMain/src/OgreTexture.cpp deleted file mode 100644 index 7468105aded..00000000000 --- a/OgreMain/src/OgreTexture.cpp +++ /dev/null @@ -1,532 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreImage.h" -#include "OgreTexture.h" - -namespace Ogre { - static const char* CUBEMAP_SUFFIXES[] = {"_rt", "_lf", "_up", "_dn", "_fr", "_bk"}; - static const char* CUBEMAP_SUFFIXES_ALT[] = {"_px", "_nx", "_py", "_ny", "_pz", "_nz"}; - //-------------------------------------------------------------------------- - Texture::Texture(ResourceManager* creator, const String& name, - ResourceHandle handle, const String& group, bool isManual, - ManualResourceLoader* loader) - : Resource(creator, name, handle, group, isManual, loader), - // init defaults; can be overridden before load() - mHeight(512), - mWidth(512), - mDepth(1), - mNumRequestedMipmaps(0), - mNumMipmaps(0), - mGamma(1.0f), - mFSAA(0), - mFormat(PF_UNKNOWN), - mUsage(TU_DEFAULT), - mSrcFormat(PF_UNKNOWN), - mSrcWidth(0), - mSrcHeight(0), - mSrcDepth(0), - mTreatLuminanceAsAlpha(false), - mInternalResourcesCreated(false), - mMipmapsHardwareGenerated(false), - mHwGamma(false), - mTextureType(TEX_TYPE_2D), - mDesiredIntegerBitDepth(0), - mDesiredFloatBitDepth(0), - mDesiredFormat(PF_UNKNOWN) - { - if (createParamDictionary("Texture")) - { - // Define the parameters that have to be present to load - // from a generic source; actually there are none, since when - // predeclaring, you use a texture file which includes all the - // information required. - } - - // Set some defaults for default load path - if (TextureManager::getSingletonPtr()) - { - TextureManager& tmgr = TextureManager::getSingleton(); - setNumMipmaps(tmgr.getDefaultNumMipmaps()); - setDesiredBitDepths(tmgr.getPreferredIntegerBitDepth(), tmgr.getPreferredFloatBitDepth()); - } - - - } - //-------------------------------------------------------------------------- - void Texture::loadRawData( DataStreamPtr& stream, - ushort uWidth, ushort uHeight, PixelFormat eFormat) - { - Image img; - img.loadRawData(stream, uWidth, uHeight, 1, eFormat); - loadImage(img); - } - //-------------------------------------------------------------------------- - void Texture::loadImage( const Image &img ) - { - OgreAssert(img.getSize(), "cannot load empty image"); - LoadingState old = mLoadingState.load(); - - // Scope lock for actual loading - try - { - OGRE_LOCK_AUTO_MUTEX; - _loadImages({&img}); - } - catch (...) - { - // Reset loading in-progress flag in case failed for some reason - mLoadingState.store(old); - // Re-throw - throw; - } - - // Notify manager - if(getCreator()) - getCreator()->_notifyResourceLoaded(this); - - // No deferred loading events since this method is not called in background - } - //-------------------------------------------------------------------------- - void Texture::setFormat(PixelFormat pf) - { - mFormat = pf; - mDesiredFormat = pf; - } - //-------------------------------------------------------------------------- - bool Texture::hasAlpha(void) const - { - return PixelUtil::hasAlpha(mFormat); - } - //-------------------------------------------------------------------------- - void Texture::setDesiredIntegerBitDepth(ushort bits) - { - mDesiredIntegerBitDepth = bits; - } - //-------------------------------------------------------------------------- - ushort Texture::getDesiredIntegerBitDepth(void) const - { - return mDesiredIntegerBitDepth; - } - //-------------------------------------------------------------------------- - void Texture::setDesiredFloatBitDepth(ushort bits) - { - mDesiredFloatBitDepth = bits; - } - //-------------------------------------------------------------------------- - ushort Texture::getDesiredFloatBitDepth(void) const - { - return mDesiredFloatBitDepth; - } - //-------------------------------------------------------------------------- - void Texture::setDesiredBitDepths(ushort integerBits, ushort floatBits) - { - mDesiredIntegerBitDepth = integerBits; - mDesiredFloatBitDepth = floatBits; - } - //-------------------------------------------------------------------------- - void Texture::setTreatLuminanceAsAlpha(bool asAlpha) - { - mTreatLuminanceAsAlpha = asAlpha; - } - //-------------------------------------------------------------------------- - size_t Texture::calculateSize(void) const - { - return getNumFaces() * PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat); - } - //-------------------------------------------------------------------------- - uint32 Texture::getNumFaces(void) const - { - return getTextureType() == TEX_TYPE_CUBE_MAP ? 6 : 1; - } - //-------------------------------------------------------------------------- - void Texture::_loadImages( const ConstImagePtrList& images ) - { - OgreAssert(!images.empty(), "Cannot load empty vector of images"); - - // Set desired texture size and properties from images[0] - mSrcWidth = mWidth = images[0]->getWidth(); - mSrcHeight = mHeight = images[0]->getHeight(); - mSrcDepth = mDepth = images[0]->getDepth(); - mSrcFormat = images[0]->getFormat(); - - if(!mLayerNames.empty() && mTextureType != TEX_TYPE_CUBE_MAP) - mDepth = uint32(mLayerNames.size()); - - if(mTreatLuminanceAsAlpha && mSrcFormat == PF_L8) - mDesiredFormat = PF_A8; - - if (mDesiredFormat != PF_UNKNOWN) - { - // If have desired format, use it - mFormat = mDesiredFormat; - } - else - { - // Get the format according with desired bit depth - mFormat = PixelUtil::getFormatForBitDepths(mSrcFormat, mDesiredIntegerBitDepth, mDesiredFloatBitDepth); - } - - // The custom mipmaps in the image clamp the request - uint32 imageMips = images[0]->getNumMipmaps(); - - if(imageMips > 0) - { - mNumMipmaps = mNumRequestedMipmaps = std::min(mNumRequestedMipmaps, imageMips); - // Disable flag for auto mip generation - mUsage &= ~TU_AUTOMIPMAP; - } - - // Create the texture - createInternalResources(); - // Check if we're loading one image with multiple faces - // or a vector of images representing the faces - uint32 faces; - bool multiImage; // Load from multiple images? - if(images.size() > 1) - { - faces = uint32(images.size()); - multiImage = true; - } - else - { - faces = images[0]->getNumFaces(); - multiImage = false; - } - - // Check whether number of faces in images exceeds number of faces - // in this texture. If so, clamp it. - if(faces > getNumFaces()) - faces = getNumFaces(); - - if (TextureManager::getSingleton().getVerbose()) { - // Say what we're doing - Log::Stream str = LogManager::getSingleton().stream(); - str << "Texture '" << mName << "': Loading " << faces << " faces" - << "(" << PixelUtil::getFormatName(images[0]->getFormat()) << "," - << images[0]->getWidth() << "x" << images[0]->getHeight() << "x" - << images[0]->getDepth() << ")"; - if (!(mMipmapsHardwareGenerated && mNumMipmaps == 0)) - { - str << " with " << mNumMipmaps; - if(mUsage & TU_AUTOMIPMAP) - { - if (mMipmapsHardwareGenerated) - str << " hardware"; - - str << " generated mipmaps"; - } - else - { - str << " custom mipmaps"; - } - if(multiImage) - str << " from multiple Images."; - else - str << " from Image."; - } - - // Print data about first destination surface - const auto& buf = getBuffer(0, 0); - str << " Internal format is " << PixelUtil::getFormatName(buf->getFormat()) << "," - << buf->getWidth() << "x" << buf->getHeight() << "x" << buf->getDepth() << "."; - } - - // Main loading loop - // imageMips == 0 if the image has no custom mipmaps, otherwise contains the number of custom mips - for(uint32 mip = 0; mip <= std::min(mNumMipmaps, imageMips); ++mip) - { - for(uint32 i = 0; i < std::max(faces, uint32(images.size())); ++i) - { - PixelBox src; - size_t face = (mDepth == 1) ? i : 0; // depth = 1, then cubemap face else 3d/ array layer - - auto buffer = getBuffer(face, mip); - Box dst(0, 0, 0, buffer->getWidth(), buffer->getHeight(), buffer->getDepth()); - - if(multiImage) - { - // Load from multiple images - src = images[i]->getPixelBox(0, mip); - // set dst layer - if(mDepth > 1) - { - dst.front = i; - dst.back = i + 1; - } - } - else - { - // Load from faces of images[0] - src = images[0]->getPixelBox(i, mip); - } - - if(mGamma != 1.0f) { - // Apply gamma correction - // Do not overwrite original image but do gamma correction in temporary buffer - Image tmp(src.format, src.getWidth(), getHeight(), src.getDepth()); - PixelBox corrected = tmp.getPixelBox(); - PixelUtil::bulkPixelConversion(src, corrected); - - Image::applyGamma(corrected.data, mGamma, tmp.getSize(), tmp.getBPP()); - - // Destination: entire texture. blitFromMemory does the scaling to - // a power of two for us when needed - buffer->blitFromMemory(corrected, dst); - } - else - { - // Destination: entire texture. blitFromMemory does the scaling to - // a power of two for us when needed - buffer->blitFromMemory(src, dst); - } - - } - } - // Update size (the final size, not including temp space) - mSize = getNumFaces() * PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat); - - } - //----------------------------------------------------------------------------- - uint32 Texture::getMaxMipmaps() const { - // see ARB_texture_non_power_of_two - return Bitwise::mostSignificantBitSet(std::max(mWidth, std::max(mHeight, mDepth))); - } - void Texture::createInternalResources(void) - { - if (!mInternalResourcesCreated) - { - // Check requested number of mipmaps - mNumMipmaps = std::min(mNumMipmaps, getMaxMipmaps()); - - createInternalResourcesImpl(); - mInternalResourcesCreated = true; - - // this is also public API, so update state accordingly - if(!isLoading()) - { - if(mIsManual && mLoader) - mLoader->loadResource(this); - - mLoadingState.store(LOADSTATE_LOADED); - _fireLoadingComplete(); - } - } - } - //----------------------------------------------------------------------------- - void Texture::freeInternalResources(void) - { - if (mInternalResourcesCreated) - { - mSurfaceList.clear(); - freeInternalResourcesImpl(); - mInternalResourcesCreated = false; - - // this is also public API, so update state accordingly - if(mLoadingState.load() != LOADSTATE_UNLOADING) - { - mLoadingState.store(LOADSTATE_UNLOADED); - _fireUnloadingComplete(); - } - } - } - //----------------------------------------------------------------------------- - void Texture::unloadImpl(void) - { - freeInternalResources(); - } - //----------------------------------------------------------------------------- - void Texture::copyToTexture( TexturePtr& target ) - { - OgreAssert(target->getNumFaces() == getNumFaces(), "Texture types must match"); - size_t numMips = std::min(getNumMipmaps(), target->getNumMipmaps()); - if((mUsage & TU_AUTOMIPMAP) || (target->getUsage()&TU_AUTOMIPMAP)) - numMips = 0; - for(unsigned int face=0; facegetBuffer(face, mip)->blit(getBuffer(face, mip)); - } - } - } - const HardwarePixelBufferSharedPtr& Texture::getBuffer(size_t face, size_t mipmap) - { - OgreAssert(face < getNumFaces(), "out of range"); - OgreAssert(mipmap <= mNumMipmaps, "out of range"); - - size_t idx = face * (mNumMipmaps + 1) + mipmap; - assert(idx < mSurfaceList.size()); - return mSurfaceList[idx]; - } - - //--------------------------------------------------------------------- - void Texture::convertToImage(Image& destImage, bool includeMipMaps) - { - uint32 numMips = includeMipMaps? getNumMipmaps() : 0; - destImage.create(getFormat(), getWidth(), getHeight(), getDepth(), getNumFaces(), numMips); - - for (uint32 face = 0; face < getNumFaces(); ++face) - { - for (uint32 mip = 0; mip < numMips; ++mip) - { - getBuffer(face, mip)->blitToMemory(destImage.getPixelBox(face, mip)); - } - } - } - - //-------------------------------------------------------------------------- - void Texture::getCustomAttribute(const String&, void*) - { - } - - void Texture::readImage(LoadedImages& imgs, const String& name, const String& ext, bool haveNPOT) - { - DataStreamPtr dstream = ResourceGroupManager::getSingleton().openResource(name, mGroup, this); - - imgs.push_back(Image()); - Image& img = imgs.back(); - img.load(dstream, ext); - - if( haveNPOT ) - return; - - // Scale to nearest power of 2 - uint32 w = Bitwise::firstPO2From(img.getWidth()); - uint32 h = Bitwise::firstPO2From(img.getHeight()); - if((img.getWidth() != w) || (img.getHeight() != h)) - img.resize(w, h); - } - - void Texture::prepareImpl(void) - { - if (mUsage & TU_RENDERTARGET) - return; - - const RenderSystemCapabilities* renderCaps = - Root::getSingleton().getRenderSystem()->getCapabilities(); - - bool haveNPOT = renderCaps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES) || - (renderCaps->getNonPOW2TexturesLimited() && mNumMipmaps == 0); - - String baseName, ext; - StringUtil::splitBaseFilename(mName, baseName, ext); - - LoadedImages loadedImages; - - try - { - if(mLayerNames.empty()) - { - readImage(loadedImages, mName, ext, haveNPOT); - - // If this is a volumetric texture set the texture type flag accordingly. - // If this is a cube map, set the texture type flag accordingly. - if (loadedImages[0].hasFlag(IF_CUBEMAP)) - mTextureType = TEX_TYPE_CUBE_MAP; - // If this is a volumetric texture set the texture type flag accordingly. - if (loadedImages[0].getDepth() > 1 && mTextureType != TEX_TYPE_2D_ARRAY) - mTextureType = TEX_TYPE_3D; - } - } - catch(const FileNotFoundException&) - { - if(mTextureType == TEX_TYPE_CUBE_MAP) - { - mLayerNames.resize(6); - for (size_t i = 0; i < 6; i++) - mLayerNames[i] = StringUtil::format("%s%s.%s", baseName.c_str(), CUBEMAP_SUFFIXES[i], ext.c_str()); - - if(!ResourceGroupManager::getSingleton().resourceExistsInAnyGroup(mLayerNames[0])) - { - // assume alternative naming convention - for (size_t i = 0; i < 6; i++) - mLayerNames[i] = - StringUtil::format("%s%s.%s", baseName.c_str(), CUBEMAP_SUFFIXES_ALT[i], ext.c_str()); - } - } - else if (mTextureType == TEX_TYPE_2D_ARRAY) - { // ignore - } - else - throw; // rethrow - } - - // read sub-images - for(const String& name : mLayerNames) - { - StringUtil::splitBaseFilename(name, baseName, ext); - readImage(loadedImages, name, ext, haveNPOT); - } - - // If compressed and 0 custom mipmap, disable auto mip generation and - // disable software mipmap creation. - // Not supported by GLES. - if (PixelUtil::isCompressed(loadedImages[0].getFormat()) && - !renderCaps->hasCapability(RSC_AUTOMIPMAP_COMPRESSED) && loadedImages[0].getNumMipmaps() == 0) - { - mNumMipmaps = mNumRequestedMipmaps = 0; - // Disable flag for auto mip generation - mUsage &= ~TU_AUTOMIPMAP; - } - - // avoid copying Image data - std::swap(mLoadedImages, loadedImages); - } - - void Texture::unprepareImpl() - { - mLoadedImages.clear(); - } - - void Texture::loadImpl() - { - if (mUsage & TU_RENDERTARGET) - { - createInternalResources(); - return; - } - - LoadedImages loadedImages; - // Now the only copy is on the stack and will be cleaned in case of - // exceptions being thrown from _loadImages - std::swap(loadedImages, mLoadedImages); - - // Call internal _loadImages, not loadImage since that's external and - // will determine load status etc again - ConstImagePtrList imagePtrs; - - for (auto& img : loadedImages) - { - imagePtrs.push_back(&img); - } - - _loadImages(imagePtrs); - } -} diff --git a/OgreMain/src/OgreTextureManager.cpp b/OgreMain/src/OgreTextureManager.cpp deleted file mode 100644 index 001cbd0992d..00000000000 --- a/OgreMain/src/OgreTextureManager.cpp +++ /dev/null @@ -1,367 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgrePixelFormat.h" - -namespace Ogre { - //----------------------------------------------------------------------- - template<> TextureManager* Singleton::msSingleton = 0; - TextureManager* TextureManager::getSingletonPtr(void) - { - return msSingleton; - } - TextureManager& TextureManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //----------------------------------------------------------------------- - TextureManager::TextureManager(void) - : mPreferredIntegerBitDepth(0) - , mPreferredFloatBitDepth(0) - , mDefaultNumMipmaps(MIP_UNLIMITED) - { - mResourceType = "Texture"; - mLoadOrder = 75.0f; - - // Subclasses should register (when this is fully constructed) - } - //----------------------------------------------------------------------- - TextureManager::~TextureManager() - { - // subclasses should unregister with resource group manager - - } - SamplerPtr TextureManager::createSampler(const String& name) - { - SamplerPtr ret = _createSamplerImpl(); - if(!name.empty()) - { - if (mNamedSamplers.find(name) != mNamedSamplers.end()) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Sampler '" + name + "' already exists"); - mNamedSamplers[name] = ret; - } - return ret; - } - - /// retrieve an named sampler - const SamplerPtr& TextureManager::getSampler(const String& name) const - { - static SamplerPtr nullPtr; - auto it = mNamedSamplers.find(name); - if(it == mNamedSamplers.end()) - return nullPtr; - return it->second; - } - //----------------------------------------------------------------------- - TexturePtr TextureManager::getByName(const String& name, const String& groupName) const - { - return static_pointer_cast(getResourceByName(name, groupName)); - } - //----------------------------------------------------------------------- - TexturePtr TextureManager::create (const String& name, const String& group, - bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams) - { - return static_pointer_cast(createResource(name,group,isManual,loader,createParams)); - } - //----------------------------------------------------------------------- - TextureManager::ResourceCreateOrRetrieveResult TextureManager::createOrRetrieve( - const String &name, const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams, TextureType texType, int numMipmaps, Real gamma, - bool isAlpha, PixelFormat desiredFormat, bool hwGamma) - { - ResourceCreateOrRetrieveResult res = - Ogre::ResourceManager::createOrRetrieve(name, group, isManual, loader, createParams); - // Was it created? - if(res.second) - { - TexturePtr tex = static_pointer_cast(res.first); - tex->setTextureType(texType); - tex->setNumMipmaps((numMipmaps == MIP_DEFAULT)? mDefaultNumMipmaps : - static_cast(numMipmaps)); - tex->setGamma(gamma); - OGRE_IGNORE_DEPRECATED_BEGIN - tex->setTreatLuminanceAsAlpha(isAlpha); - OGRE_IGNORE_DEPRECATED_END - tex->setFormat(desiredFormat); - tex->setHardwareGammaEnabled(hwGamma); - } - return res; - } - //----------------------------------------------------------------------- - TexturePtr TextureManager::prepare(const String &name, const String& group, TextureType texType, - int numMipmaps, Real gamma, bool isAlpha, - PixelFormat desiredFormat, bool hwGamma) - { - ResourceCreateOrRetrieveResult res = - createOrRetrieve(name,group,false,0,0,texType,numMipmaps,gamma,isAlpha,desiredFormat,hwGamma); - TexturePtr tex = static_pointer_cast(res.first); - tex->prepare(); - return tex; - } - //----------------------------------------------------------------------- - TexturePtr TextureManager::load(const String& name, const String& group, TextureType texType, - int numMipmaps, Real gamma, bool isAlpha, PixelFormat desiredFormat, - bool hwGamma) - { - auto res = createOrRetrieve(name, group, false, 0, 0, texType, numMipmaps, gamma, isAlpha, - desiredFormat, hwGamma); - TexturePtr tex = static_pointer_cast(res.first); - tex->load(); - return tex; - } - TexturePtr TextureManager::load(const String& name, const String& group, TextureType texType, - int numMipmaps, Real gamma, PixelFormat desiredFormat, bool hwGamma) - { - auto res = createOrRetrieve(name, group, false, 0, 0, texType, numMipmaps, gamma, false, - desiredFormat, hwGamma); - TexturePtr tex = static_pointer_cast(res.first); - tex->load(); - return tex; - } - //----------------------------------------------------------------------- - TexturePtr TextureManager::loadImage( const String &name, const String& group, - const Image &img, TextureType texType, int numMipmaps, Real gamma, bool isAlpha, - PixelFormat desiredFormat, bool hwGamma) - { - TexturePtr tex = create(name, group, true); - - tex->setTextureType(texType); - tex->setNumMipmaps((numMipmaps == MIP_DEFAULT)? mDefaultNumMipmaps : - static_cast(numMipmaps)); - tex->setGamma(gamma); - OGRE_IGNORE_DEPRECATED_BEGIN - tex->setTreatLuminanceAsAlpha(isAlpha); - OGRE_IGNORE_DEPRECATED_END - tex->setFormat(desiredFormat); - tex->setHardwareGammaEnabled(hwGamma); - tex->loadImage(img); - - return tex; - } - //----------------------------------------------------------------------- - TexturePtr TextureManager::loadRawData(const String &name, const String& group, - DataStreamPtr& stream, ushort uWidth, ushort uHeight, - PixelFormat format, TextureType texType, - int numMipmaps, Real gamma, bool hwGamma) - { - TexturePtr tex = create(name, group, true); - - tex->setTextureType(texType); - tex->setNumMipmaps((numMipmaps == MIP_DEFAULT)? mDefaultNumMipmaps : - static_cast(numMipmaps)); - tex->setGamma(gamma); - tex->setHardwareGammaEnabled(hwGamma); - tex->loadRawData(stream, uWidth, uHeight, format); - - return tex; - } - //----------------------------------------------------------------------- - TexturePtr TextureManager::createManual(const String & name, const String& group, - TextureType texType, uint width, uint height, uint depth, int numMipmaps, - PixelFormat format, int usage, ManualResourceLoader* loader, bool hwGamma, - uint fsaa, const String& fsaaHint) - { - TexturePtr ret; - - OgreAssert(width && height && depth, "total size of texture must not be zero"); - - // Check for texture support - const auto caps = Root::getSingleton().getRenderSystem()->getCapabilities(); - if (((texType == TEX_TYPE_3D) && !caps->hasCapability(RSC_TEXTURE_3D)) || - ((texType == TEX_TYPE_2D_ARRAY) && !caps->hasCapability(RSC_TEXTURE_2D_ARRAY))) - return ret; - - ret = create(name, group, true, loader); - - if(!ret) - return ret; - - ret->setTextureType(texType); - ret->setWidth(width); - ret->setHeight(height); - ret->setDepth(depth); - ret->setNumMipmaps((numMipmaps == MIP_DEFAULT)? mDefaultNumMipmaps : - static_cast(numMipmaps)); - ret->setFormat(format); - ret->setUsage(usage); - ret->setHardwareGammaEnabled(hwGamma); - ret->setFSAA(fsaa, fsaaHint); - ret->createInternalResources(); - return ret; - } - //----------------------------------------------------------------------- - void TextureManager::setPreferredIntegerBitDepth(ushort bits, bool reloadTextures) - { - mPreferredIntegerBitDepth = bits; - - if (reloadTextures) - { - // Iterate through all textures - for (auto & r : mResources) - { - Texture* texture = static_cast(r.second.get()); - // Reload loaded and reloadable texture only - if (texture->isLoaded() && texture->isReloadable()) - { - texture->unload(); - texture->setDesiredIntegerBitDepth(bits); - texture->load(); - } - else - { - texture->setDesiredIntegerBitDepth(bits); - } - } - } - } - //----------------------------------------------------------------------- - ushort TextureManager::getPreferredIntegerBitDepth(void) const - { - return mPreferredIntegerBitDepth; - } - //----------------------------------------------------------------------- - void TextureManager::setPreferredFloatBitDepth(ushort bits, bool reloadTextures) - { - mPreferredFloatBitDepth = bits; - - if (reloadTextures) - { - // Iterate through all textures - for (auto & r : mResources) - { - Texture* texture = static_cast(r.second.get()); - // Reload loaded and reloadable texture only - if (texture->isLoaded() && texture->isReloadable()) - { - texture->unload(); - texture->setDesiredFloatBitDepth(bits); - texture->load(); - } - else - { - texture->setDesiredFloatBitDepth(bits); - } - } - } - } - //----------------------------------------------------------------------- - ushort TextureManager::getPreferredFloatBitDepth(void) const - { - return mPreferredFloatBitDepth; - } - //----------------------------------------------------------------------- - void TextureManager::setPreferredBitDepths(ushort integerBits, ushort floatBits, bool reloadTextures) - { - mPreferredIntegerBitDepth = integerBits; - mPreferredFloatBitDepth = floatBits; - - if (reloadTextures) - { - // Iterate through all textures - for (auto & r : mResources) - { - Texture* texture = static_cast(r.second.get()); - // Reload loaded and reloadable texture only - if (texture->isLoaded() && texture->isReloadable()) - { - texture->unload(); - texture->setDesiredBitDepths(integerBits, floatBits); - texture->load(); - } - else - { - texture->setDesiredBitDepths(integerBits, floatBits); - } - } - } - } - //----------------------------------------------------------------------- - void TextureManager::setDefaultNumMipmaps( uint32 num ) - { - mDefaultNumMipmaps = num; - } - //----------------------------------------------------------------------- - bool TextureManager::isFormatSupported(TextureType ttype, PixelFormat format, int usage) - { - return getNativeFormat(ttype, format, usage) == format; - } - //----------------------------------------------------------------------- - bool TextureManager::isEquivalentFormatSupported(TextureType ttype, PixelFormat format, int usage) - { - PixelFormat supportedFormat = getNativeFormat(ttype, format, usage); - - // Assume that same or greater number of bits means quality not degraded - return PixelUtil::getNumElemBits(supportedFormat) >= PixelUtil::getNumElemBits(format); - - } - - bool TextureManager::isHardwareFilteringSupported(TextureType ttype, PixelFormat format, - int usage, bool preciseFormatOnly) - { - if (format == PF_UNKNOWN) - return false; - - // Check native format - if (preciseFormatOnly && !isFormatSupported(ttype, format, usage)) - return false; - - return true; - } - - const TexturePtr& TextureManager::_getWarningTexture() - { - if(mWarningTexture) - return mWarningTexture; - - // Generate warning texture - Image pixels(PF_R5G6B5, 8, 8); - - // Yellow/black stripes - const ColourValue black(0, 0, 0), yellow(1, 1, 0); - for (uint32 y = 0; y < pixels.getHeight(); ++y) - { - for (uint32 x = 0; x < pixels.getWidth(); ++x) - { - pixels.setColourAt((((x + y) % 8) < 4) ? black : yellow, x, y, 0); - } - } - - mWarningTexture = loadImage("Warning", RGN_INTERNAL, pixels); - - return mWarningTexture; - } - - const SamplerPtr& TextureManager::getDefaultSampler() - { - if(!mDefaultSampler) - mDefaultSampler = createSampler(); - - return mDefaultSampler; - } -} diff --git a/OgreMain/src/OgreTextureUnitState.cpp b/OgreMain/src/OgreTextureUnitState.cpp deleted file mode 100644 index 5fb71254f91..00000000000 --- a/OgreMain/src/OgreTextureUnitState.cpp +++ /dev/null @@ -1,1270 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#include "OgreTextureUnitState.h" -#include "OgreControllerManager.h" -#include "OgreTextureManager.h" -#include "OgreHardwarePixelBuffer.h" - -namespace Ogre { - // allow operation without hardware support - static SamplerPtr DUMMY_SAMPLER = std::make_shared(); - - Sampler::Sampler() - : mBorderColour(ColourValue::Black) - , mMaxAniso(1) - , mMipmapBias(0) - , mMinFilter(FO_LINEAR) - , mMagFilter(FO_LINEAR) - , mMipFilter(FO_POINT) - , mCompareFunc(CMPF_GREATER_EQUAL) - , mCompareEnabled(false) - , mDirty(true) - { - setAddressingMode(TAM_WRAP); - } - Sampler::~Sampler() {} - //----------------------------------------------------------------------- - void Sampler::setAddressingMode(const UVWAddressingMode& uvw) - { - mAddressMode = uvw; - mDirty = true; - } - - //----------------------------------------------------------------------- - void Sampler::setFiltering(TextureFilterOptions filterType) - { - switch (filterType) - { - case TFO_NONE: - setFiltering(FO_POINT, FO_POINT, FO_NONE); - break; - case TFO_BILINEAR: - setFiltering(FO_LINEAR, FO_LINEAR, FO_POINT); - break; - case TFO_TRILINEAR: - setFiltering(FO_LINEAR, FO_LINEAR, FO_LINEAR); - break; - case TFO_ANISOTROPIC: - setFiltering(FO_ANISOTROPIC, FO_ANISOTROPIC, FO_LINEAR); - break; - } - } - //----------------------------------------------------------------------- - void Sampler::setFiltering(FilterType ft, FilterOptions fo) - { - switch (ft) - { - case FT_MIN: - mMinFilter = fo; - break; - case FT_MAG: - mMagFilter = fo; - break; - case FT_MIP: - mMipFilter = fo; - break; - } - mDirty = true; - } - //----------------------------------------------------------------------- - void Sampler::setFiltering(FilterOptions minFilter, FilterOptions magFilter, FilterOptions mipFilter) - { - mMinFilter = minFilter; - mMagFilter = magFilter; - mMipFilter = mipFilter; - mDirty = true; - } - //----------------------------------------------------------------------- - FilterOptions Sampler::getFiltering(FilterType ft) const - { - switch (ft) - { - case FT_MIN: - return mMinFilter; - case FT_MAG: - return mMagFilter; - case FT_MIP: - return mMipFilter; - } - // to keep compiler happy - return mMinFilter; - } - //----------------------------------------------------------------------- - TextureUnitState::TextureUnitState(Pass* parent) - : mCurrentFrame(0) - , mAnimDuration(0) - , mUnorderedAccessMipLevel(-1) - , mGamma(1) - , mUMod(0) - , mVMod(0) - , mUScale(1) - , mVScale(1) - , mRotate(0) - , mTexModMatrix(Matrix4::IDENTITY) - , mContentType(CONTENT_NAMED) - , mTextureLoadFailed(false) - , mRecalcTexMatrix(false) - , mTextureCoordSetIndex(0) - , mFramePtrs(1) - , mSampler(TextureManager::getSingletonPtr() ? TextureManager::getSingleton().getDefaultSampler() : DUMMY_SAMPLER) - , mParent(parent) - , mAnimController(0) - { - mColourBlendMode.blendType = LBT_COLOUR; - mAlphaBlendMode.operation = LBX_MODULATE; - mAlphaBlendMode.blendType = LBT_ALPHA; - mAlphaBlendMode.source1 = LBS_TEXTURE; - mAlphaBlendMode.source2 = LBS_CURRENT; - setColourOperation(LBO_MODULATE); - - if( Pass::getHashFunction() == Pass::getBuiltinHashFunction( Pass::MIN_TEXTURE_CHANGE ) ) - { - mParent->_dirtyHash(); - } - - } - - //----------------------------------------------------------------------- - TextureUnitState::TextureUnitState(Pass* parent, const TextureUnitState& oth ) - { - mParent = parent; - mAnimController = 0; - *this = oth; - } - - //----------------------------------------------------------------------- - TextureUnitState::TextureUnitState( Pass* parent, const String& texName, uint8 texCoordSet) - : TextureUnitState(parent) - { - setTextureName(texName); - setTextureCoordSet(texCoordSet); - } - //----------------------------------------------------------------------- - TextureUnitState::~TextureUnitState() - { - // Unload ensure all controllers destroyed - _unload(); - } - //----------------------------------------------------------------------- - TextureUnitState & TextureUnitState::operator = ( - const TextureUnitState &oth ) - { - if (this == &oth) - return *this; - - assert(mAnimController == 0); - removeAllEffects(); - - // copy basic members (int's, real's) - memcpy( (uchar*)this, &oth, (const uchar *)(&oth.mFramePtrs) - (const uchar *)(&oth) ); - // copy complex members - mFramePtrs = oth.mFramePtrs; - mSampler = oth.mSampler; - mName = oth.mName; - mEffects = oth.mEffects; - - mCompositorRefName = oth.mCompositorRefName; - mCompositorRefTexName = oth.mCompositorRefTexName; - // Can't sharing controllers with other TUS, reset to null to avoid potential bug. - for (auto & e : mEffects) - { - e.second.controller = 0; - } - - // Load immediately if Material loaded - if (isLoaded()) - { - _load(); - } - - // Tell parent to recalculate hash - if( Pass::getHashFunction() == Pass::getBuiltinHashFunction( Pass::MIN_TEXTURE_CHANGE ) ) - { - mParent->_dirtyHash(); - } - - return *this; - } - //----------------------------------------------------------------------- - const String& TextureUnitState::getTextureName(void) const - { - // Return name of current frame - if (mCurrentFrame < mFramePtrs.size() && mFramePtrs[mCurrentFrame]) - return mFramePtrs[mCurrentFrame]->getName(); - else - return BLANKSTRING; - } - //----------------------------------------------------------------------- - void TextureUnitState::setTextureName( const String& name) - { - if(TexturePtr tex = retrieveTexture(name)) - setTexture(tex); - } - - void TextureUnitState::setTextureName( const String& name, TextureType texType) - { - TexturePtr tex = retrieveTexture(name); - - if(!tex) - return; - - tex->setTextureType(texType); - setTexture(tex); - } - //----------------------------------------------------------------------- - void TextureUnitState::setTexture( const TexturePtr& texPtr) - { - if (!texPtr) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Texture Pointer is empty.", - "TextureUnitState::setTexture"); - } - - setContentType(CONTENT_NAMED); - mTextureLoadFailed = false; - - if (texPtr->getTextureType() == TEX_TYPE_EXTERNAL_OES) - { - setTextureAddressingMode( TAM_CLAMP ); - setTextureFiltering(FT_MIP, FO_NONE); - } - - mFramePtrs.resize(1); - mFramePtrs[0] = texPtr; - - mCurrentFrame = 0; - - // Load immediately ? - if (isLoaded()) - { - _load(); // reload - } - // Tell parent to recalculate hash - if( Pass::getHashFunction() == Pass::getBuiltinHashFunction( Pass::MIN_TEXTURE_CHANGE ) ) - { - mParent->_dirtyHash(); - } - } - //----------------------------------------------------------------------- - void TextureUnitState::setContentType(TextureUnitState::ContentType ct) - { - mContentType = ct; - } - //----------------------------------------------------------------------- - TextureUnitState::ContentType TextureUnitState::getContentType(void) const - { - return mContentType; - } - //----------------------------------------------------------------------- - TextureType TextureUnitState::getTextureType(void) const - { - return !mFramePtrs[0] ? TEX_TYPE_2D : mFramePtrs[0]->getTextureType(); - } - - //----------------------------------------------------------------------- - void TextureUnitState::setFrameTextureName(const String& name, unsigned int frameNumber) - { - mTextureLoadFailed = false; - OgreAssert(frameNumber < mFramePtrs.size(), "out of range"); - - mFramePtrs[frameNumber] = retrieveTexture(name); - - if (isLoaded()) - { - _load(); // reload - } - // Tell parent to recalculate hash - if( Pass::getHashFunction() == Pass::getBuiltinHashFunction( Pass::MIN_TEXTURE_CHANGE ) ) - { - mParent->_dirtyHash(); - } - } - - //----------------------------------------------------------------------- - void TextureUnitState::addFrameTextureName(const String& name) - { - setContentType(CONTENT_NAMED); - mTextureLoadFailed = false; - - mFramePtrs.push_back(retrieveTexture(name)); - - // Load immediately if Material loaded - if (isLoaded()) - { - _load(); - } - // Tell parent to recalculate hash - if( Pass::getHashFunction() == Pass::getBuiltinHashFunction( Pass::MIN_TEXTURE_CHANGE ) ) - { - mParent->_dirtyHash(); - } - } - - //----------------------------------------------------------------------- - void TextureUnitState::deleteFrameTextureName(const size_t frameNumber) - { - mTextureLoadFailed = false; - OgreAssert(frameNumber < mFramePtrs.size(), "out of range"); - mFramePtrs.erase(mFramePtrs.begin() + frameNumber); - - if (isLoaded()) - { - _load(); - } - // Tell parent to recalculate hash - if( Pass::getHashFunction() == Pass::getBuiltinHashFunction( Pass::MIN_TEXTURE_CHANGE ) ) - { - mParent->_dirtyHash(); - } - } - - void TextureUnitState::setCubicTextureName(const String* const names, bool forUVW) - { - setLayerArrayNames(TEX_TYPE_CUBE_MAP, std::vector(names, names + 6)); - } - - //----------------------------------------------------------------------- - void TextureUnitState::setAnimatedTextureName( const String& name, size_t numFrames, Real duration) - { - String baseName, ext; - StringUtil::splitBaseFilename(name, baseName, ext); - - std::vector names(numFrames); - for (uint32 i = 0; i < names.size(); ++i) - { - names[i] = StringUtil::format("%s_%u.%s", baseName.c_str(), i, ext.c_str()); - } - - setAnimatedTextureName(names, duration); - } - //----------------------------------------------------------------------- - void TextureUnitState::setAnimatedTextureName(const String* const names, size_t numFrames, Real duration) - { - setContentType(CONTENT_NAMED); - mTextureLoadFailed = false; - - // resize pointers, but don't populate until needed - mFramePtrs.resize(numFrames); - mAnimDuration = duration; - mCurrentFrame = 0; - - for (unsigned int i = 0; i < mFramePtrs.size(); ++i) - { - mFramePtrs[i] = retrieveTexture(names[i]); - } - - // Load immediately if Material loaded - if (isLoaded()) - { - _load(); - } - // Tell parent to recalculate hash - if( Pass::getHashFunction() == Pass::getBuiltinHashFunction( Pass::MIN_TEXTURE_CHANGE ) ) - { - mParent->_dirtyHash(); - } - } - void TextureUnitState::setLayerArrayNames(TextureType type, const std::vector& names) - { - OgreAssert(!names.empty(), "array layers empty"); - - const char* typeName; - switch(type) - { - case TEX_TYPE_CUBE_MAP: - typeName = "Cube"; - break; - case TEX_TYPE_2D_ARRAY: - typeName = "Array"; - break; - case TEX_TYPE_3D: - typeName = "Volume"; - break; - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "arrays not possible for this texture type"); - return; - } - - // use hash to auto-name the texture - uint32 hash = 0; - for(const String& name : names) - hash = FastHash(name.data(), name.size(), hash); - - auto tex = retrieveTexture(StringUtil::format("%sTex_%x", typeName, hash)); - tex->setTextureType(type); - tex->setLayerNames(names); - setTexture(tex); - } - - //----------------------------------------------------------------------- - std::pair TextureUnitState::getTextureDimensions(unsigned int frame) const - { - - TexturePtr tex = _getTexturePtr(frame); - if (!tex) - OGRE_EXCEPT( Exception::ERR_ITEM_NOT_FOUND, "Could not find texture " + StringConverter::toString(frame), - "TextureUnitState::getTextureDimensions" ); - - return {tex->getWidth(), tex->getHeight()}; - } - //----------------------------------------------------------------------- - void TextureUnitState::setCurrentFrame(unsigned int frameNumber) - { - OgreAssert(frameNumber < mFramePtrs.size(), "out of range"); - mCurrentFrame = frameNumber; - // this will affect the hash - if( Pass::getHashFunction() == Pass::getBuiltinHashFunction( Pass::MIN_TEXTURE_CHANGE ) ) - { - mParent->_dirtyHash(); - } - } - //----------------------------------------------------------------------- - unsigned int TextureUnitState::getCurrentFrame(void) const - { - return mCurrentFrame; - } - //----------------------------------------------------------------------- - unsigned int TextureUnitState::getNumFrames(void) const - { - return (unsigned int)mFramePtrs.size(); - } - //----------------------------------------------------------------------- - const String& TextureUnitState::getFrameTextureName(unsigned int frameNumber) const - { - OgreAssert(frameNumber < mFramePtrs.size(), "out of range"); - - return mFramePtrs[0] ? mFramePtrs[frameNumber]->getName() : BLANKSTRING; - } - //----------------------------------------------------------------------- - void TextureUnitState::setDesiredFormat(PixelFormat desiredFormat) - { - OgreAssert(mFramePtrs[0], "frame must not be blank"); - for(auto& frame : mFramePtrs) - frame->setFormat(desiredFormat); - } - //----------------------------------------------------------------------- - PixelFormat TextureUnitState::getDesiredFormat(void) const - { - return !mFramePtrs[0] ? PF_UNKNOWN : mFramePtrs[0]->getDesiredFormat(); - } - //----------------------------------------------------------------------- - void TextureUnitState::setNumMipmaps(int numMipmaps) - { - OgreAssert(mFramePtrs[0], "frame must not be blank"); - for (auto& frame : mFramePtrs) - frame->setNumMipmaps(numMipmaps == MIP_DEFAULT - ? TextureManager::getSingleton().getDefaultNumMipmaps() - : numMipmaps); - } - //----------------------------------------------------------------------- - int TextureUnitState::getNumMipmaps(void) const - { - return !mFramePtrs[0] ? int(MIP_DEFAULT) : mFramePtrs[0]->getNumMipmaps(); - } - //----------------------------------------------------------------------- - void TextureUnitState::setIsAlpha(bool isAlpha) - { - OgreAssert(mFramePtrs[0], "frame must not be blank"); - OGRE_IGNORE_DEPRECATED_BEGIN - for(auto& frame : mFramePtrs) - frame->setTreatLuminanceAsAlpha(isAlpha); - OGRE_IGNORE_DEPRECATED_END - } - float TextureUnitState::getGamma() const - { - return !mFramePtrs[0] ? 1.0f : mFramePtrs[0]->getGamma(); - } - void TextureUnitState::setGamma(float gamma) - { - OgreAssert(mFramePtrs[0], "frame must not be blank"); - for(auto& frame : mFramePtrs) - frame->setGamma(gamma); - } - //----------------------------------------------------------------------- - void TextureUnitState::setHardwareGammaEnabled(bool g) - { - OgreAssert(mFramePtrs[0], "frame must not be blank"); - for(auto& frame : mFramePtrs) - frame->setHardwareGammaEnabled(g); - } - //----------------------------------------------------------------------- - bool TextureUnitState::isHardwareGammaEnabled() const - { - return mFramePtrs[0] && mFramePtrs[0]->isHardwareGammaEnabled(); - } - //----------------------------------------------------------------------- - uint8 TextureUnitState::getTextureCoordSet(void) const - { - return mTextureCoordSetIndex; - } - //----------------------------------------------------------------------- - void TextureUnitState::setTextureCoordSet(uint8 set) - { - mTextureCoordSetIndex = set; - } - //----------------------------------------------------------------------- - void TextureUnitState::setColourOperationEx(LayerBlendOperationEx op, - LayerBlendSource source1, - LayerBlendSource source2, - const ColourValue& arg1, - const ColourValue& arg2, - Real manualBlend) - { - mColourBlendMode.operation = op; - mColourBlendMode.source1 = source1; - mColourBlendMode.source2 = source2; - mColourBlendMode.colourArg1 = arg1; - mColourBlendMode.colourArg2 = arg2; - mColourBlendMode.factor = manualBlend; - } - //----------------------------------------------------------------------- - void TextureUnitState::setColourOperation(LayerBlendOperation op) - { - // Set up the multitexture and multipass blending operations - switch (op) - { - case LBO_REPLACE: - setColourOperationEx(LBX_SOURCE1, LBS_TEXTURE, LBS_CURRENT); - setColourOpMultipassFallback(SBF_ONE, SBF_ZERO); - break; - case LBO_ADD: - setColourOperationEx(LBX_ADD, LBS_TEXTURE, LBS_CURRENT); - setColourOpMultipassFallback(SBF_ONE, SBF_ONE); - break; - case LBO_MODULATE: - setColourOperationEx(LBX_MODULATE, LBS_TEXTURE, LBS_CURRENT); - setColourOpMultipassFallback(SBF_DEST_COLOUR, SBF_ZERO); - break; - case LBO_ALPHA_BLEND: - setColourOperationEx(LBX_BLEND_TEXTURE_ALPHA, LBS_TEXTURE, LBS_CURRENT); - setColourOpMultipassFallback(SBF_SOURCE_ALPHA, SBF_ONE_MINUS_SOURCE_ALPHA); - break; - } - - - } - //----------------------------------------------------------------------- - void TextureUnitState::setColourOpMultipassFallback(SceneBlendFactor sourceFactor, SceneBlendFactor destFactor) - { - mColourBlendFallbackSrc = sourceFactor; - mColourBlendFallbackDest = destFactor; - } - //----------------------------------------------------------------------- - void TextureUnitState::setAlphaOperation(LayerBlendOperationEx op, - LayerBlendSource source1, - LayerBlendSource source2, - Real arg1, - Real arg2, - Real manualBlend) - { - mAlphaBlendMode.operation = op; - mAlphaBlendMode.source1 = source1; - mAlphaBlendMode.source2 = source2; - mAlphaBlendMode.alphaArg1 = arg1; - mAlphaBlendMode.alphaArg2 = arg2; - mAlphaBlendMode.factor = manualBlend; - } - //----------------------------------------------------------------------- - void TextureUnitState::addEffect(TextureEffect& effect) - { - // Ensure controller pointer is null - effect.controller = 0; - - if (effect.type == ET_ENVIRONMENT_MAP - || effect.type == ET_UVSCROLL - || effect.type == ET_USCROLL - || effect.type == ET_VSCROLL - || effect.type == ET_ROTATE - || effect.type == ET_PROJECTIVE_TEXTURE) - { - // Replace - must be unique - // Search for existing effect of this type - EffectMap::iterator i = mEffects.find(effect.type); - if (i != mEffects.end()) - { - // Destroy old effect controller if exist - if (i->second.controller) - { - ControllerManager::getSingleton().destroyController(i->second.controller); - } - - mEffects.erase(i); - } - } - - if (isLoaded()) - { - // Create controller - createEffectController(effect); - } - - // Record new effect - mEffects.emplace(effect.type, effect); - - } - //----------------------------------------------------------------------- - void TextureUnitState::removeAllEffects(void) - { - // Iterate over effects to remove controllers - EffectMap::iterator i, iend; - iend = mEffects.end(); - for (i = mEffects.begin(); i != iend; ++i) - { - if (i->second.controller) - { - ControllerManager::getSingleton().destroyController(i->second.controller); - } - } - - mEffects.clear(); - } - - //----------------------------------------------------------------------- - bool TextureUnitState::isBlank(void) const - { - return !mFramePtrs[0] || mTextureLoadFailed; - } - - //----------------------------------------------------------------------- - SceneBlendFactor TextureUnitState::getColourBlendFallbackSrc(void) const - { - return mColourBlendFallbackSrc; - } - //----------------------------------------------------------------------- - SceneBlendFactor TextureUnitState::getColourBlendFallbackDest(void) const - { - return mColourBlendFallbackDest; - } - //----------------------------------------------------------------------- - const LayerBlendModeEx& TextureUnitState::getColourBlendMode(void) const - { - return mColourBlendMode; - } - //----------------------------------------------------------------------- - const LayerBlendModeEx& TextureUnitState::getAlphaBlendMode(void) const - { - return mAlphaBlendMode; - } - //----------------------------------------------------------------------- - void TextureUnitState::setEnvironmentMap(bool enable, EnvMapType envMapType) - { - if (enable) - { - TextureEffect eff; - eff.type = ET_ENVIRONMENT_MAP; - - eff.subtype = envMapType; - addEffect(eff); - } - else - { - removeEffect(ET_ENVIRONMENT_MAP); - } - } - //----------------------------------------------------------------------- - void TextureUnitState::removeEffect(TextureEffectType type) - { - // Get range of items matching this effect - std::pair< EffectMap::iterator, EffectMap::iterator > remPair = - mEffects.equal_range( type ); - // Remove controllers - for (EffectMap::iterator i = remPair.first; i != remPair.second; ++i) - { - if (i->second.controller) - { - ControllerManager::getSingleton().destroyController(i->second.controller); - } - } - // Erase - mEffects.erase( remPair.first, remPair.second ); - } - //----------------------------------------------------------------------- - void TextureUnitState::setBlank(void) - { - mFramePtrs.clear(); - mFramePtrs.push_back(TexturePtr()); // insert nullptr to show warning tex - } - //----------------------------------------------------------------------- - void TextureUnitState::setTextureTransform(const Matrix4& xform) - { - mTexModMatrix = xform; - mRecalcTexMatrix = false; - } - //----------------------------------------------------------------------- - void TextureUnitState::setTextureScroll(Real u, Real v) - { - mUMod = u; - mVMod = v; - mRecalcTexMatrix = true; - } - //----------------------------------------------------------------------- - void TextureUnitState::setTextureScale(Real uScale, Real vScale) - { - mUScale = uScale; - mVScale = vScale; - mRecalcTexMatrix = true; - } - //----------------------------------------------------------------------- - void TextureUnitState::setTextureRotate(const Radian& angle) - { - mRotate = angle; - mRecalcTexMatrix = true; - } - //----------------------------------------------------------------------- - const Matrix4& TextureUnitState::getTextureTransform() const - { - if (mRecalcTexMatrix) - recalcTextureMatrix(); - return mTexModMatrix; - - } - //----------------------------------------------------------------------- - void TextureUnitState::recalcTextureMatrix() const - { - // Assumption: 2D texture coords - // that would make this Affine2(Matrix3), but we lack such a class - // Matrix3 is horribly unoptimized ATM - Affine3 xform = Affine3::IDENTITY; - - if (mUScale != 1 || mVScale != 1) - { - // Offset to center of texture - xform[0][0] = 1/mUScale; - xform[1][1] = 1/mVScale; - // Skip matrix concat since first matrix update - xform[0][3] = (-0.5f * xform[0][0]) + 0.5f; - xform[1][3] = (-0.5f * xform[1][1]) + 0.5f; - } - - if (mUMod || mVMod) - { - xform = Affine3::getTrans(mUMod, mVMod, 0) * xform; - } - - if (mRotate != Radian(0)) - { - Affine3 rot = Affine3::IDENTITY; - Radian theta ( mRotate ); - Real cosTheta = Math::Cos(theta); - Real sinTheta = Math::Sin(theta); - - rot[0][0] = cosTheta; - rot[0][1] = -sinTheta; - rot[1][0] = sinTheta; - rot[1][1] = cosTheta; - // Offset center of rotation to center of texture - rot[0][3] = 0.5f + ( (-0.5f * cosTheta) - (-0.5f * sinTheta) ); - rot[1][3] = 0.5f + ( (-0.5f * sinTheta) + (-0.5f * cosTheta) ); - - xform = rot * xform; - } - - mTexModMatrix = xform; - mRecalcTexMatrix = false; - - } - //----------------------------------------------------------------------- - void TextureUnitState::setTextureUScroll(Real value) - { - mUMod = value; - mRecalcTexMatrix = true; - } - //----------------------------------------------------------------------- - void TextureUnitState::setTextureVScroll(Real value) - { - mVMod = value; - mRecalcTexMatrix = true; - } - //----------------------------------------------------------------------- - void TextureUnitState::setTextureUScale(Real value) - { - mUScale = value; - mRecalcTexMatrix = true; - } - //----------------------------------------------------------------------- - void TextureUnitState::setTextureVScale(Real value) - { - mVScale = value; - mRecalcTexMatrix = true; - } - //----------------------------------------------------------------------- - void TextureUnitState::setScrollAnimation(Real uSpeed, Real vSpeed) - { - // Remove existing effects - removeEffect(ET_UVSCROLL); - removeEffect(ET_USCROLL); - removeEffect(ET_VSCROLL); - - // don't create an effect if the speeds are both 0 - if(uSpeed == 0.0f && vSpeed == 0.0f) - { - return; - } - - // Create new effect - TextureEffect eff; - if(uSpeed == vSpeed) - { - eff.type = ET_UVSCROLL; - eff.arg1 = uSpeed; - addEffect(eff); - } - else - { - if(uSpeed) - { - eff.type = ET_USCROLL; - eff.arg1 = uSpeed; - addEffect(eff); - } - if(vSpeed) - { - eff.type = ET_VSCROLL; - eff.arg1 = vSpeed; - addEffect(eff); - } - } - } - //----------------------------------------------------------------------- - void TextureUnitState::setRotateAnimation(Real speed) - { - // Remove existing effect - removeEffect(ET_ROTATE); - // don't create an effect if the speed is 0 - if(speed == 0.0f) - { - return; - } - // Create new effect - TextureEffect eff; - eff.type = ET_ROTATE; - eff.arg1 = speed; - addEffect(eff); - } - //----------------------------------------------------------------------- - void TextureUnitState::setTransformAnimation(TextureTransformType ttype, - WaveformType waveType, Real base, Real frequency, Real phase, Real amplitude) - { - // Remove existing effect - // note, only remove for subtype, not entire ET_TRANSFORM - // otherwise we won't be able to combine subtypes - // Get range of items matching this effect - for (EffectMap::iterator i = mEffects.begin(); i != mEffects.end(); ++i) - { - if (i->second.type == ET_TRANSFORM && i->second.subtype == ttype) - { - if (i->second.controller) - { - ControllerManager::getSingleton().destroyController(i->second.controller); - } - mEffects.erase(i); - - // should only be one, so jump out - break; - } - } - - // don't create an effect if the given values are all 0 - if(base == 0.0f && phase == 0.0f && frequency == 0.0f && amplitude == 0.0f) - { - return; - } - // Create new effect - TextureEffect eff; - eff.type = ET_TRANSFORM; - eff.subtype = ttype; - eff.waveType = waveType; - eff.base = base; - eff.frequency = frequency; - eff.phase = phase; - eff.amplitude = amplitude; - addEffect(eff); - } - //----------------------------------------------------------------------- - void TextureUnitState::_prepare(void) - { - // Unload first - //_unload(); - - // Load textures - for (unsigned int i = 0; i < mFramePtrs.size(); ++i) - { - ensurePrepared(i); - } - } - //----------------------------------------------------------------------- - void TextureUnitState::_load(void) - { - - // Load textures - for (unsigned int i = 0; i < mFramePtrs.size(); ++i) - { - ensureLoaded(i); - } - // Animation controller - if (mAnimDuration != 0) - { - createAnimController(); - } - // Effect controllers - for (auto & e : mEffects) - { - createEffectController(e.second); - } - - } - //----------------------------------------------------------------------- - const TexturePtr& TextureUnitState::_getTexturePtr(void) const - { - return _getTexturePtr(mCurrentFrame); - } - //----------------------------------------------------------------------- - const TexturePtr& TextureUnitState::_getTexturePtr(size_t frame) const - { - if (frame < mFramePtrs.size()) - { - if (mContentType == CONTENT_NAMED) - { - ensureLoaded(frame); - } - - return mFramePtrs[frame]; - } - - // Silent fail with empty texture for internal method - static TexturePtr nullTexPtr; - return nullTexPtr; - } - //----------------------------------------------------------------------- - void TextureUnitState::_setTexturePtr(const TexturePtr& texptr) - { - _setTexturePtr(texptr, mCurrentFrame); - } - //----------------------------------------------------------------------- - void TextureUnitState::_setTexturePtr(const TexturePtr& texptr, size_t frame) - { - assert(frame < mFramePtrs.size()); - mFramePtrs[frame] = texptr; - } - //----------------------------------------------------------------------- - TexturePtr TextureUnitState::retrieveTexture(const String& name) { - TextureManager::ResourceCreateOrRetrieveResult res; - res = TextureManager::getSingleton().createOrRetrieve(name, mParent->getResourceGroup()); - return static_pointer_cast(res.first); - } - //----------------------------------------------------------------------- - bool TextureUnitState::checkTexCalcSettings(const TexturePtr& tex) const - { - if(mContentType != TextureUnitState::CONTENT_NAMED) - return true; // can only check normal textures - - String err; - auto texCalc = _deriveTexCoordCalcMethod(); - if ((texCalc == TEXCALC_ENVIRONMENT_MAP_PLANAR || texCalc == TEXCALC_ENVIRONMENT_MAP) && - getTextureType() != TEX_TYPE_2D) - { - err = "env_map setting requires a 2d texture"; - } - else if ((texCalc == TEXCALC_ENVIRONMENT_MAP_NORMAL || texCalc == TEXCALC_ENVIRONMENT_MAP_REFLECTION) && - getTextureType() != TEX_TYPE_CUBE_MAP) - { - err = "env_map setting requires a cubic texture"; - } - if(err.empty()) - return true; - - String msg = err+", but '"+tex->getName()+"' is not. Texture layer will be blank"; - LogManager::getSingleton().logError(msg); - mTextureLoadFailed = true; - return false; - } - void TextureUnitState::ensurePrepared(size_t frame) const - { - const TexturePtr& tex = mFramePtrs[frame]; - if (!tex || mTextureLoadFailed || !checkTexCalcSettings(tex)) - return; - - tex->setGamma(mGamma); - - try { - tex->prepare(); - } - catch (Exception& e) - { - String msg = "preparing texture '" + tex->getName() + - "'. Texture layer will be blank: " + e.getDescription(); - LogManager::getSingleton().logError(msg); - mTextureLoadFailed = true; - } - } - //----------------------------------------------------------------------- - void TextureUnitState::ensureLoaded(size_t frame) const - { - const TexturePtr& tex = mFramePtrs[frame]; - if (!tex || mTextureLoadFailed || !checkTexCalcSettings(tex)) - return; - - tex->setGamma(mGamma); - - if(mUnorderedAccessMipLevel > -1) - tex->setUsage(HBU_GPU_ONLY | TU_UNORDERED_ACCESS); - - try { - tex->load(); - } - catch (Exception& e) - { - String msg = "loading texture '" + tex->getName() + - "'. Texture layer will be blank: " + e.getDescription(); - LogManager::getSingleton().logError(msg); - mTextureLoadFailed = true; - } - } - //----------------------------------------------------------------------- - void TextureUnitState::createAnimController(void) - { - if (mAnimController) - { - ControllerManager::getSingleton().destroyController(mAnimController); - mAnimController = 0; - } - mAnimController = ControllerManager::getSingleton().createTextureAnimator(this, mAnimDuration); - - } - //----------------------------------------------------------------------- - void TextureUnitState::createEffectController(TextureEffect& effect) - { - if (effect.controller) - { - ControllerManager::getSingleton().destroyController(effect.controller); - effect.controller = 0; - } - ControllerManager& cMgr = ControllerManager::getSingleton(); - switch (effect.type) - { - case ET_UVSCROLL: - effect.controller = cMgr.createTextureUVScroller(this, effect.arg1); - break; - case ET_USCROLL: - effect.controller = cMgr.createTextureUScroller(this, effect.arg1); - break; - case ET_VSCROLL: - effect.controller = cMgr.createTextureVScroller(this, effect.arg1); - break; - case ET_ROTATE: - effect.controller = cMgr.createTextureRotater(this, effect.arg1); - break; - case ET_TRANSFORM: - effect.controller = cMgr.createTextureWaveTransformer(this, (TextureUnitState::TextureTransformType)effect.subtype, effect.waveType, effect.base, - effect.frequency, effect.phase, effect.amplitude); - break; - case ET_ENVIRONMENT_MAP: - break; - default: - break; - } - } - //----------------------------------------------------------------------- - Real TextureUnitState::getTextureUScroll(void) const - { - return mUMod; - } - - //----------------------------------------------------------------------- - Real TextureUnitState::getTextureVScroll(void) const - { - return mVMod; - } - - //----------------------------------------------------------------------- - Real TextureUnitState::getTextureUScale(void) const - { - return mUScale; - } - - //----------------------------------------------------------------------- - Real TextureUnitState::getTextureVScale(void) const - { - return mVScale; - } - - //----------------------------------------------------------------------- - const Radian& TextureUnitState::getTextureRotate(void) const - { - return mRotate; - } - - //----------------------------------------------------------------------- - Real TextureUnitState::getAnimationDuration(void) const - { - return mAnimDuration; - } - - //----------------------------------------------------------------------- - const TextureUnitState::EffectMap& TextureUnitState::getEffects(void) const - { - return mEffects; - } - //----------------------------------------------------------------------- - void TextureUnitState::_unprepare(void) - { - // don't unload textures. may be used elsewhere - } - //----------------------------------------------------------------------- - void TextureUnitState::_unload(void) - { - // Destroy animation controller - if (mAnimController) - { - ControllerManager::getSingleton().destroyController(mAnimController); - mAnimController = 0; - } - - // Destroy effect controllers - for (auto & e : mEffects) - { - if (e.second.controller) - { - ControllerManager::getSingleton().destroyController(e.second.controller); - e.second.controller = 0; - } - } - - // don't unload named textures. may be used elsewhere - // drop references on managed textures, however - if(mContentType != CONTENT_NAMED) - mFramePtrs[0].reset(); - } - //----------------------------------------------------------------------------- - bool TextureUnitState::isLoaded(void) const - { - return mParent->isLoaded(); - } - //----------------------------------------------------------------------- - void TextureUnitState::_notifyNeedsRecompile(void) - { - mParent->_notifyNeedsRecompile(); - } - //----------------------------------------------------------------------- - void TextureUnitState::setProjectiveTexturing(bool enable, - const Frustum* projectionSettings) - { - if (enable) - { - TextureEffect eff; - eff.type = ET_PROJECTIVE_TEXTURE; - eff.frustum = projectionSettings; - addEffect(eff); - } - else - { - removeEffect(ET_PROJECTIVE_TEXTURE); - } - - } - //----------------------------------------------------------------------- - void TextureUnitState::setName(const String& name) - { - mName = name; - } - //----------------------------------------------------------------------------- - void TextureUnitState::_notifyParent(Pass* parent) - { - mParent = parent; - } - //----------------------------------------------------------------------------- - void TextureUnitState::setCompositorReference(const String& compositorName, const String& textureName, uint32 mrtIndex) - { - mCompositorRefName = compositorName; - mCompositorRefTexName = textureName; - mCompositorRefMrtIndex = mrtIndex; - } - //----------------------------------------------------------------------- - size_t TextureUnitState::calculateSize(void) const - { - size_t memSize = sizeof(*this); - memSize += mFramePtrs.size() * sizeof(TexturePtr); - memSize += mEffects.size() * sizeof(TextureEffect); - return memSize; - } - - bool TextureUnitState::isDefaultFiltering() const { - return mSampler == TextureManager::getSingleton().getDefaultSampler(); - } - - const SamplerPtr& TextureUnitState::_getLocalSampler() - { - if(isDefaultFiltering()) - mSampler = TextureManager::getSingleton().createSampler(); - - return mSampler; - } - - TexCoordCalcMethod TextureUnitState::_deriveTexCoordCalcMethod() const - { - TexCoordCalcMethod texCoordCalcMethod = TEXCALC_NONE; - for (const auto& effi : mEffects) - { - switch (effi.second.type) - { - case ET_ENVIRONMENT_MAP: - if (effi.second.subtype == ENV_CURVED) - { - texCoordCalcMethod = TEXCALC_ENVIRONMENT_MAP; - } - else if (effi.second.subtype == ENV_PLANAR) - { - texCoordCalcMethod = TEXCALC_ENVIRONMENT_MAP_PLANAR; - } - else if (effi.second.subtype == ENV_REFLECTION) - { - texCoordCalcMethod = TEXCALC_ENVIRONMENT_MAP_REFLECTION; - } - else if (effi.second.subtype == ENV_NORMAL) - { - texCoordCalcMethod = TEXCALC_ENVIRONMENT_MAP_NORMAL; - } - break; - case ET_UVSCROLL: - case ET_USCROLL: - case ET_VSCROLL: - case ET_ROTATE: - case ET_TRANSFORM: - break; - case ET_PROJECTIVE_TEXTURE: - texCoordCalcMethod = TEXCALC_PROJECTIVE_TEXTURE; - break; - } - } - - return texCoordCalcMethod; - } -} diff --git a/OgreMain/src/OgreTimer.cpp b/OgreMain/src/OgreTimer.cpp deleted file mode 100644 index 0df20b7e28f..00000000000 --- a/OgreMain/src/OgreTimer.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreTimer.h" - -using namespace std::chrono; - -namespace Ogre { - -//--------------------------------------------------------------------------------// -Timer::Timer() -{ - reset(); -} - -//--------------------------------------------------------------------------------// -void Timer::reset() -{ - zeroClock = clock(); - start = steady_clock::now(); -} - -//--------------------------------------------------------------------------------// -uint64_t Timer::getMilliseconds() -{ - auto now = steady_clock::now(); - return duration_cast(now - start).count(); -} - -//--------------------------------------------------------------------------------// -uint64_t Timer::getMicroseconds() -{ - auto now = steady_clock::now(); - return duration_cast(now - start).count(); -} - -//-- Common Across All Timers ----------------------------------------------------// -uint64_t Timer::getMillisecondsCPU() -{ - clock_t newClock = clock(); - return (uint64_t)((float)(newClock-zeroClock) / ((float)CLOCKS_PER_SEC/1000.0)) ; -} - -//-- Common Across All Timers ----------------------------------------------------// -uint64_t Timer::getMicrosecondsCPU() -{ - clock_t newClock = clock(); - return (uint64_t)((float)(newClock-zeroClock) / ((float)CLOCKS_PER_SEC/1000000.0)) ; -} - -} diff --git a/OgreMain/src/OgreUnifiedHighLevelGpuProgram.cpp b/OgreMain/src/OgreUnifiedHighLevelGpuProgram.cpp deleted file mode 100644 index ad21d7c04f1..00000000000 --- a/OgreMain/src/OgreUnifiedHighLevelGpuProgram.cpp +++ /dev/null @@ -1,427 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreUnifiedHighLevelGpuProgram.h" -#include "OgreGpuProgramManager.h" - -namespace Ogre -{ - //----------------------------------------------------------------------- - /// Command object for setting delegate (can set more than once) - class CmdDelegate : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - static CmdDelegate msCmdDelegate; - static const String sLanguage = "unified"; - - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - UnifiedHighLevelGpuProgram::UnifiedHighLevelGpuProgram( - ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - :GpuProgram(creator, name, handle, group, isManual, loader) - { - if (createParamDictionary("UnifiedHighLevelGpuProgram")) - { - setupBaseParamDictionary(); - - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter(ParameterDef("delegate", - "Additional delegate programs containing implementations.", - PT_STRING),&msCmdDelegate); - } - - } - //----------------------------------------------------------------------- - UnifiedHighLevelGpuProgram::~UnifiedHighLevelGpuProgram() - { - - } - //----------------------------------------------------------------------- - void UnifiedHighLevelGpuProgram::chooseDelegate() const - { - OGRE_LOCK_AUTO_MUTEX; - - mChosenDelegate.reset(); - - for (const String& dn : mDelegateNames) - { - GpuProgramPtr deleg = GpuProgramManager::getSingleton().getByName(dn, mGroup); - - //recheck with auto resource group - if (!deleg) - deleg = GpuProgramManager::getSingleton().getByName(dn, RGN_AUTODETECT); - - // Silently ignore missing links - if(!deleg || (!deleg->isSupported() && !deleg->hasCompileError())) - continue; - - if (deleg->getType() != getType()) - { - LogManager::getSingleton().logError("unified program '" + getName() + - "' delegating to program with different type '" + dn + "'"); - continue; - } - - mChosenDelegate = deleg; - break; - } - } - //----------------------------------------------------------------------- - const GpuProgramPtr& UnifiedHighLevelGpuProgram::_getDelegate() const - { - if (!mChosenDelegate) - { - chooseDelegate(); - } - return mChosenDelegate; - } - //----------------------------------------------------------------------- - void UnifiedHighLevelGpuProgram::addDelegateProgram(const String& name) - { - OGRE_LOCK_AUTO_MUTEX; - - mDelegateNames.push_back(name); - - // reset chosen delegate - mChosenDelegate.reset(); - - } - //----------------------------------------------------------------------- - void UnifiedHighLevelGpuProgram::clearDelegatePrograms() - { - OGRE_LOCK_AUTO_MUTEX; - - mDelegateNames.clear(); - mChosenDelegate.reset(); - - } - //----------------------------------------------------------------------------- - size_t UnifiedHighLevelGpuProgram::calculateSize(void) const - { - size_t memSize = 0; - - memSize += GpuProgram::calculateSize(); - - // Delegate Names - for (StringVector::const_iterator i = mDelegateNames.begin(); i != mDelegateNames.end(); ++i) - memSize += (*i).size() * sizeof(char); - - return memSize; - } - //----------------------------------------------------------------------- - const String& UnifiedHighLevelGpuProgram::getLanguage(void) const - { - return sLanguage; - } - //----------------------------------------------------------------------- - GpuProgramParametersSharedPtr UnifiedHighLevelGpuProgram::createParameters(void) - { - if (isSupported()) - { - return _getDelegate()->createParameters(); - } - else - { - // return a default set - GpuProgramParametersSharedPtr params = GpuProgramManager::getSingleton().createParameters(); - // avoid any errors on parameter names that don't exist - params->setIgnoreMissingParams(true); - return params; - } - } - //----------------------------------------------------------------------- - GpuProgram* UnifiedHighLevelGpuProgram::_getBindingDelegate(void) - { - if (_getDelegate()) - return _getDelegate()->_getBindingDelegate(); - else - return 0; - } - //----------------------------------------------------------------------- - bool UnifiedHighLevelGpuProgram::isSupported(void) const - { - // Supported if one of the delegates is - return _getDelegate() && _getDelegate()->isSupported(); - } - //----------------------------------------------------------------------- - bool UnifiedHighLevelGpuProgram::isSkeletalAnimationIncluded(void) const - { - if (_getDelegate()) - return _getDelegate()->isSkeletalAnimationIncluded(); - else - return false; - } - //----------------------------------------------------------------------- - bool UnifiedHighLevelGpuProgram::isMorphAnimationIncluded(void) const - { - if (_getDelegate()) - return _getDelegate()->isMorphAnimationIncluded(); - else - return false; - } - //----------------------------------------------------------------------- - bool UnifiedHighLevelGpuProgram::isPoseAnimationIncluded(void) const - { - if (_getDelegate()) - return _getDelegate()->isPoseAnimationIncluded(); - else - return false; - } - //----------------------------------------------------------------------- - ushort UnifiedHighLevelGpuProgram::getNumberOfPosesIncluded(void) const - { - if (_getDelegate()) - return _getDelegate()->getNumberOfPosesIncluded(); - else - return 0; - } - //----------------------------------------------------------------------- - bool UnifiedHighLevelGpuProgram::isVertexTextureFetchRequired(void) const - { - if (_getDelegate()) - return _getDelegate()->isVertexTextureFetchRequired(); - else - return false; - } - //----------------------------------------------------------------------- - const GpuProgramParametersPtr& UnifiedHighLevelGpuProgram::getDefaultParameters(void) - { - if (_getDelegate()) - return _getDelegate()->getDefaultParameters(); - - static GpuProgramParametersSharedPtr nullPtr; - return nullPtr; - } - //----------------------------------------------------------------------- - bool UnifiedHighLevelGpuProgram::hasDefaultParameters(void) const - { - if (_getDelegate()) - return _getDelegate()->hasDefaultParameters(); - else - return false; - } - //----------------------------------------------------------------------- - bool UnifiedHighLevelGpuProgram::getPassSurfaceAndLightStates(void) const - { - if (_getDelegate()) - return _getDelegate()->getPassSurfaceAndLightStates(); - else - return GpuProgram::getPassSurfaceAndLightStates(); - } - //--------------------------------------------------------------------- - bool UnifiedHighLevelGpuProgram::getPassFogStates(void) const - { - if (_getDelegate()) - return _getDelegate()->getPassFogStates(); - else - return GpuProgram::getPassFogStates(); - } - //--------------------------------------------------------------------- - bool UnifiedHighLevelGpuProgram::getPassTransformStates(void) const - { - if (_getDelegate()) - return _getDelegate()->getPassTransformStates(); - else - return GpuProgram::getPassTransformStates(); - - } - //----------------------------------------------------------------------- - bool UnifiedHighLevelGpuProgram::hasCompileError(void) const - { - if (!_getDelegate()) - { - return false; - } - else - { - return _getDelegate()->hasCompileError(); - } - } - //----------------------------------------------------------------------- - void UnifiedHighLevelGpuProgram::resetCompileError(void) - { - if (_getDelegate()) - _getDelegate()->resetCompileError(); - } - //----------------------------------------------------------------------- - void UnifiedHighLevelGpuProgram::load(bool backgroundThread) - { - if (_getDelegate()) - _getDelegate()->load(backgroundThread); - } - //----------------------------------------------------------------------- - void UnifiedHighLevelGpuProgram::reload(LoadingFlags flags) - { - if (_getDelegate()) - _getDelegate()->reload(flags); - } - //----------------------------------------------------------------------- - bool UnifiedHighLevelGpuProgram::isReloadable(void) const - { - if (_getDelegate()) - return _getDelegate()->isReloadable(); - else - return true; - } - //----------------------------------------------------------------------- - void UnifiedHighLevelGpuProgram::unload(void) - { - if (_getDelegate()) - _getDelegate()->unload(); - } - //----------------------------------------------------------------------- - bool UnifiedHighLevelGpuProgram::isLoaded(void) const - { - if (_getDelegate()) - return _getDelegate()->isLoaded(); - else - return false; - } - //----------------------------------------------------------------------- - bool UnifiedHighLevelGpuProgram::isLoading() const - { - if (_getDelegate()) - return _getDelegate()->isLoading(); - else - return false; - } - //----------------------------------------------------------------------- - Resource::LoadingState UnifiedHighLevelGpuProgram::getLoadingState() const - { - if (_getDelegate()) - return _getDelegate()->getLoadingState(); - else - return Resource::LOADSTATE_UNLOADED; - } - //----------------------------------------------------------------------- - size_t UnifiedHighLevelGpuProgram::getSize(void) const - { - if (_getDelegate()) - return _getDelegate()->getSize(); - else - return 0; - } - //----------------------------------------------------------------------- - void UnifiedHighLevelGpuProgram::touch(void) - { - if (_getDelegate()) - _getDelegate()->touch(); - } - //----------------------------------------------------------------------- - bool UnifiedHighLevelGpuProgram::isBackgroundLoaded(void) const - { - if (_getDelegate()) - return _getDelegate()->isBackgroundLoaded(); - else - return false; - } - //----------------------------------------------------------------------- - void UnifiedHighLevelGpuProgram::setBackgroundLoaded(bool bl) - { - if (_getDelegate()) - _getDelegate()->setBackgroundLoaded(bl); - } - //----------------------------------------------------------------------- - void UnifiedHighLevelGpuProgram::escalateLoading() - { - if (_getDelegate()) - _getDelegate()->escalateLoading(); - } - //----------------------------------------------------------------------- - void UnifiedHighLevelGpuProgram::addListener(Resource::Listener* lis) - { - if (_getDelegate()) - _getDelegate()->addListener(lis); - } - //----------------------------------------------------------------------- - void UnifiedHighLevelGpuProgram::removeListener(Resource::Listener* lis) - { - if (_getDelegate()) - _getDelegate()->removeListener(lis); - } - //----------------------------------------------------------------------- - void UnifiedHighLevelGpuProgram::createLowLevelImpl(void) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, - "This method should never get called!", - "UnifiedHighLevelGpuProgram::createLowLevelImpl"); - } - //----------------------------------------------------------------------- - void UnifiedHighLevelGpuProgram::unloadHighLevelImpl(void) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, - "This method should never get called!", - "UnifiedHighLevelGpuProgram::unloadHighLevelImpl"); - } - //----------------------------------------------------------------------- - void UnifiedHighLevelGpuProgram::loadFromSource(void) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, - "This method should never get called!", - "UnifiedHighLevelGpuProgram::loadFromSource"); - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String CmdDelegate::doGet(const void* target) const - { - // Can't do this (not one delegate), shouldn't matter - return BLANKSTRING; - } - //----------------------------------------------------------------------- - void CmdDelegate::doSet(void* target, const String& val) - { - static_cast(target)->addDelegateProgram(val); - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - UnifiedHighLevelGpuProgramFactory::UnifiedHighLevelGpuProgramFactory() - { - } - //----------------------------------------------------------------------- - UnifiedHighLevelGpuProgramFactory::~UnifiedHighLevelGpuProgramFactory() - { - } - //----------------------------------------------------------------------- - const String& UnifiedHighLevelGpuProgramFactory::getLanguage(void) const - { - return sLanguage; - } - //----------------------------------------------------------------------- - GpuProgram* UnifiedHighLevelGpuProgramFactory::create(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - { - return OGRE_NEW UnifiedHighLevelGpuProgram(creator, name, handle, group, isManual, loader); - } -} - diff --git a/OgreMain/src/OgreUnifiedHighLevelGpuProgram.h b/OgreMain/src/OgreUnifiedHighLevelGpuProgram.h deleted file mode 100644 index f6622cdd87f..00000000000 --- a/OgreMain/src/OgreUnifiedHighLevelGpuProgram.h +++ /dev/null @@ -1,174 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __UnifiedHighLevelGpuProgram_H__ -#define __UnifiedHighLevelGpuProgram_H__ - -#include "OgrePrerequisites.h" -#include "OgreGpuProgram.h" -#include "OgreGpuProgramManager.h" -#include "OgreHeaderPrefix.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - /** Specialisation of HighLevelGpuProgram which just delegates its implementation - to one other GpuProgram, allowing a single program definition - to represent one supported program from a number of options - - Whilst you can use Technique to implement several ways to render an object - depending on hardware support, if the only reason to need multiple paths is - because of the shader language supported, this can be - cumbersome. For example you might want to implement the same shader - in HLSL and GLSL for portability but apart from the implementation detail, - the shaders do the same thing and take the same parameters. If the materials - in question are complex, duplicating the techniques just to switch language - is not optimal, so instead you can define high-level programs with a - syntax of 'unified', and list the actual implementations in order of - preference via repeated use of the 'delegate' parameter, which just points - at another program name. The first one which has a supported syntax - will be used. - */ - class UnifiedHighLevelGpuProgram final : public GpuProgram - { - /// Ordered list of potential delegates - StringVector mDelegateNames; - /// The chosen delegate - mutable GpuProgramPtr mChosenDelegate; - - /// Choose the delegate to use - void chooseDelegate() const; - - void createLowLevelImpl(void); - void unloadHighLevelImpl(void); - void loadFromSource(void) override; - - void unloadImpl() override { resetCompileError(); } - public: - /** Constructor, should be used only by factory classes. */ - UnifiedHighLevelGpuProgram(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual = false, ManualResourceLoader* loader = 0); - ~UnifiedHighLevelGpuProgram(); - - size_t calculateSize(void) const override; - - /** Adds a new delegate program to the list. - - Delegates are tested in order so earlier ones are preferred. - */ - void addDelegateProgram(const String& name); - - /// Remove all delegate programs - void clearDelegatePrograms(); - - /// Get the chosen delegate - const GpuProgramPtr& _getDelegate() const; - - /** @copydoc GpuProgram::getLanguage */ - const String& getLanguage(void) const override; - - /** Creates a new parameters object compatible with this program definition. - - Unlike low-level assembly programs, parameters objects are specific to the - program and therefore must be created from it rather than by the - HighLevelGpuProgramManager. This method creates a new instance of a parameters - object containing the definition of the parameters this program understands. - */ - GpuProgramParametersSharedPtr createParameters(void) override; - /** @copydoc GpuProgram::_getBindingDelegate */ - GpuProgram* _getBindingDelegate(void) override; - - // All the following methods must delegate to the implementation - - /** @copydoc GpuProgram::isSupported */ - bool isSupported(void) const override; - - const String& getSource(void) const override - { - return _getDelegate() ? _getDelegate()->getSource() : BLANKSTRING; - } - - /** @copydoc GpuProgram::isSkeletalAnimationIncluded */ - bool isSkeletalAnimationIncluded(void) const override; - - bool isMorphAnimationIncluded(void) const override; - - bool isPoseAnimationIncluded(void) const override; - ushort getNumberOfPosesIncluded(void) const override; - - bool isVertexTextureFetchRequired(void) const override; - const GpuProgramParametersPtr& getDefaultParameters(void) override; - bool hasDefaultParameters(void) const override; - bool getPassSurfaceAndLightStates(void) const override; - bool getPassFogStates(void) const override; - bool getPassTransformStates(void) const override; - bool hasCompileError(void) const override; - void resetCompileError(void) override; - - void load(bool backgroundThread = false) override; - void reload(LoadingFlags flags = LF_DEFAULT) override; - bool isReloadable(void) const; - bool isLoaded(void) const; - bool isLoading() const; - LoadingState getLoadingState() const; - void unload(void) override; - size_t getSize(void) const; - void touch(void) override; - bool isBackgroundLoaded(void) const; - void setBackgroundLoaded(bool bl); - void escalateLoading() override; - void addListener(Listener* lis) override; - void removeListener(Listener* lis) override; - - }; - - /** Factory class for Unified programs. */ - class UnifiedHighLevelGpuProgramFactory : public GpuProgramFactory - { - public: - UnifiedHighLevelGpuProgramFactory(); - ~UnifiedHighLevelGpuProgramFactory(); - /// Get the name of the language this factory creates programs for - const String& getLanguage(void) const override; - GpuProgram* create(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) override; - }; - - /** @} */ - /** @} */ - -} - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/OgreMain/src/OgreUserObjectBindings.cpp b/OgreMain/src/OgreUserObjectBindings.cpp deleted file mode 100644 index 9f332aea178..00000000000 --- a/OgreMain/src/OgreUserObjectBindings.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include - -#include "OgreStableHeaders.h" - -namespace Ogre { - static Any emptyAny; - - //-------------------------------------------------------------------------- - UserObjectBindings::UserObjectBindings(const UserObjectBindings& other) - { - if (other.mAttributes) - mAttributes = std::make_unique(*other.mAttributes); - } - - UserObjectBindings& UserObjectBindings::swap(UserObjectBindings& rhs) - { - std::swap(mAttributes, rhs.mAttributes); - return *this; - } - - UserObjectBindings& UserObjectBindings::operator=(const UserObjectBindings& rhs) - { - UserObjectBindings(rhs).swap(*this); - return *this; - } - - //----------------------------------------------------------------------- - void UserObjectBindings::setUserAny( const Any& anything ) - { - // Allocate attributes on demand. - if (!mAttributes) - mAttributes = std::make_unique(); - - mAttributes->mKeylessAny = anything; - } - - //----------------------------------------------------------------------- - const Any& UserObjectBindings::getUserAny() const - { - // Allocate attributes on demand. - if (!mAttributes) - return emptyAny; - - return mAttributes->mKeylessAny; - } - - //----------------------------------------------------------------------- - void UserObjectBindings::setUserAny(const String& key, const Any& anything) - { - // Allocate attributes on demand. - if (!mAttributes) - mAttributes = std::make_unique(); - - // Case map doesn't exists. - if (!mAttributes->mUserObjectsMap) - mAttributes->mUserObjectsMap = std::make_unique(); - - (*mAttributes->mUserObjectsMap)[key] = anything; - } - - //----------------------------------------------------------------------- - const Any& UserObjectBindings::getUserAny(const String& key) const - { - if (!mAttributes) - return emptyAny; - - // Case map doesn't exists. - if (!mAttributes->mUserObjectsMap) - return emptyAny; - - UserObjectsMapConstIterator it = mAttributes->mUserObjectsMap->find(key); - - // Case user data found. - if (it != mAttributes->mUserObjectsMap->end()) - { - return it->second; - } - - return emptyAny; - } - - //----------------------------------------------------------------------- - void UserObjectBindings::eraseUserAny(const String& key) - { - // Case attributes and map allocated. - if (mAttributes && mAttributes->mUserObjectsMap) - { - UserObjectsMapIterator it = mAttributes->mUserObjectsMap->find(key); - - // Case object found -> erase it from the map. - if (it != mAttributes->mUserObjectsMap->end()) - { - mAttributes->mUserObjectsMap->erase(it); - } - } - } - - //----------------------------------------------------------------------- - void UserObjectBindings::clear() - { - mAttributes.reset(); - } -} diff --git a/OgreMain/src/OgreVector.cpp b/OgreMain/src/OgreVector.cpp deleted file mode 100644 index dac929319ab..00000000000 --- a/OgreMain/src/OgreVector.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -namespace Ogre -{ -const Vector2 VectorBase<2, Real>::ZERO( 0 ); -const Vector2 VectorBase<2, Real>::UNIT_X( 1, 0); -const Vector2 VectorBase<2, Real>::UNIT_Y( 0, 1); -const Vector2 VectorBase<2, Real>::NEGATIVE_UNIT_X( -1, 0); -const Vector2 VectorBase<2, Real>::NEGATIVE_UNIT_Y( 0, -1); -const Vector2 VectorBase<2, Real>::UNIT_SCALE( 1 ); - -const Vector3 VectorBase<3, Real>::ZERO( 0 ); -const Vector3 VectorBase<3, Real>::UNIT_X( 1, 0, 0 ); -const Vector3 VectorBase<3, Real>::UNIT_Y( 0, 1, 0 ); -const Vector3 VectorBase<3, Real>::UNIT_Z( 0, 0, 1 ); -const Vector3 VectorBase<3, Real>::NEGATIVE_UNIT_X( -1, 0, 0 ); -const Vector3 VectorBase<3, Real>::NEGATIVE_UNIT_Y( 0, -1, 0 ); -const Vector3 VectorBase<3, Real>::NEGATIVE_UNIT_Z( 0, 0, -1 ); -const Vector3 VectorBase<3, Real>::UNIT_SCALE( 1 ); - -const Vector4 VectorBase<4, Real>::ZERO( 0 ); -} diff --git a/OgreMain/src/OgreVertexIndexData.cpp b/OgreMain/src/OgreVertexIndexData.cpp deleted file mode 100644 index 7560eaca107..00000000000 --- a/OgreMain/src/OgreVertexIndexData.cpp +++ /dev/null @@ -1,1016 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreVertexIndexData.h" -#include "OgreHardwareVertexBuffer.h" - -#define INT10_MAX ((1 << 9) - 1) - -namespace Ogre { - static void swapPackedRB(uint32* ptr) - { - auto cptr = (uint8*)ptr; - std::swap(cptr[0], cptr[2]); - } - - struct int_10_10_10_2 - { - int32_t x : 10; - int32_t y : 10; - int32_t z : 10; - int32_t w : 2; - }; - - template - static void pack_10_10_10_2(uint8* pDst, uint8* pSrc, int elemOffset) - { - float* pFloat = (float*)(pSrc + elemOffset); - int_10_10_10_2 packed = {int(INT10_MAX * pFloat[0]), int(INT10_MAX * pFloat[1]), int(INT10_MAX * pFloat[2]), 1}; - if(INCLUDE_W) - packed.w = int(pFloat[3]); - memcpy(pDst + elemOffset, &packed, sizeof(int_10_10_10_2)); - } - - template - static void unpack_10_10_10_2(uint8* pDst, uint8* pSrc, int elemOffset) - { - int_10_10_10_2* pPacked = (int_10_10_10_2*)(pSrc + elemOffset); - float* pFloat = (float*)(pDst + elemOffset); - - pFloat[0] = float(pPacked->x) / INT10_MAX; - pFloat[1] = float(pPacked->y) / INT10_MAX; - pFloat[2] = float(pPacked->z) / INT10_MAX; - if(INCLUDE_W) - pFloat[3] = pPacked->w; - } - - static void copy_float3(uint8* pDst, uint8* pSrc, int elemOffset) - { - memcpy(pDst, pSrc + elemOffset, sizeof(float) * 3); - } - - static void spliceElement(const VertexElement* elem, const HardwareVertexBufferPtr& srcBuf, uint8* pDst, - uint8* pElemDst, uint32 newElemSize, void (*elemConvert)(uint8*, uint8*, int)) - { - auto vertexSize = srcBuf->getVertexSize(); - auto numVerts = srcBuf->getNumVertices(); - - auto elemSize = elem->getSize(); - auto elemOffset = elem->getOffset(); - - auto postVertexOffset = elemOffset + elemSize; - auto postVertexSize = vertexSize - postVertexOffset; - - auto elemDstSize = pDst == pElemDst ? newElemSize : 0; - size_t newVertexSize = vertexSize - elemSize + elemDstSize; - auto elemDstStep = pDst == pElemDst ? newVertexSize : newElemSize; - - HardwareBufferLockGuard srcLock(srcBuf, HardwareBuffer::HBL_READ_ONLY); - uint8* pSrc = static_cast(srcLock.pData); - - for (uint32 v = 0; v < numVerts; ++v) - { - // copy and convert element from vertex - elemConvert(pElemDst, pSrc, elemOffset); - pElemDst += elemDstStep; - - // copy over other data - if (elemOffset) - memcpy(pDst, pSrc, elemOffset); - if (postVertexSize) - memcpy(pDst + elemOffset + elemDstSize, pSrc + postVertexOffset, postVertexSize); - - pSrc += vertexSize; - pDst += newVertexSize; - } - } - - static void updateVertexDeclaration(VertexDeclaration* decl, const VertexElement* elem, VertexElementType newType, uint16 newSource) - { - auto elemSize = elem->getSize(); - auto oldElemOffset = elem->getOffset(); - auto newElemOffset = oldElemOffset; - - auto newElemSize = VertexElement::getTypeSize(newType); - auto oldSource = elem->getSource(); - - if(newSource != oldSource) - { - newElemOffset = 0; - newElemSize = 0; - } - - uint16 idx = 0; - for (const auto& e : decl->getElements()) - { - if (&e == elem) - { - // Modify element - decl->modifyElement(idx, newSource, newElemOffset, newType, elem->getSemantic()); - } - else if (e.getSource() == oldSource && e.getOffset() > oldElemOffset) - { - // shift elements after this one - decl->modifyElement(idx, e.getSource(), e.getOffset() - elemSize + newElemSize, e.getType(), - e.getSemantic(), e.getIndex()); - } - idx++; - } - } - - //----------------------------------------------------------------------- - VertexData::VertexData(HardwareBufferManagerBase* mgr) - { - mMgr = mgr ? mgr : HardwareBufferManager::getSingletonPtr(); - vertexBufferBinding = mMgr->createVertexBufferBinding(); - vertexDeclaration = mMgr->createVertexDeclaration(); - mDeleteDclBinding = true; - vertexCount = 0; - vertexStart = 0; - hwAnimDataItemsUsed = 0; - - } - //--------------------------------------------------------------------- - VertexData::VertexData(VertexDeclaration* dcl, VertexBufferBinding* bind) - { - // this is a fallback rather than actively used - mMgr = HardwareBufferManager::getSingletonPtr(); - vertexDeclaration = dcl; - vertexBufferBinding = bind; - mDeleteDclBinding = false; - vertexCount = 0; - vertexStart = 0; - hwAnimDataItemsUsed = 0; - } - //----------------------------------------------------------------------- - VertexData::~VertexData() - { - if (mDeleteDclBinding) - { - mMgr->destroyVertexBufferBinding(vertexBufferBinding); - mMgr->destroyVertexDeclaration(vertexDeclaration); - } - } - //----------------------------------------------------------------------- - VertexData* VertexData::clone(bool copyData, HardwareBufferManagerBase* mgr) const - { - HardwareBufferManagerBase* pManager = mgr ? mgr : mMgr; - - VertexData* dest = OGRE_NEW VertexData(mgr); - - // Copy vertex buffers in turn - const VertexBufferBinding::VertexBufferBindingMap& bindings = - this->vertexBufferBinding->getBindings(); - VertexBufferBinding::VertexBufferBindingMap::const_iterator vbi, vbend; - vbend = bindings.end(); - for (vbi = bindings.begin(); vbi != vbend; ++vbi) - { - HardwareVertexBufferSharedPtr srcbuf = vbi->second; - HardwareVertexBufferSharedPtr dstBuf; - if (copyData) - { - // create new buffer with the same settings - dstBuf = pManager->createVertexBuffer( - srcbuf->getVertexSize(), srcbuf->getNumVertices(), srcbuf->getUsage(), - srcbuf->hasShadowBuffer()); - - // copy data - dstBuf->copyData(*srcbuf, 0, 0, srcbuf->getSizeInBytes(), true); - } - else - { - // don't copy, point at existing buffer - dstBuf = srcbuf; - } - - // Copy binding - dest->vertexBufferBinding->setBinding(vbi->first, dstBuf); - } - - // Basic vertex info - dest->vertexStart = this->vertexStart; - dest->vertexCount = this->vertexCount; - // Copy elements - const VertexDeclaration::VertexElementList elems = - this->vertexDeclaration->getElements(); - VertexDeclaration::VertexElementList::const_iterator ei, eiend; - eiend = elems.end(); - for (ei = elems.begin(); ei != eiend; ++ei) - { - dest->vertexDeclaration->addElement( - ei->getSource(), - ei->getOffset(), - ei->getType(), - ei->getSemantic(), - ei->getIndex() ); - } - - // Copy reference to hardware shadow buffer, no matter whether copy data or not - dest->hardwareShadowVolWBuffer = hardwareShadowVolWBuffer; - - // copy anim data - dest->hwAnimationDataList = hwAnimationDataList; - dest->hwAnimDataItemsUsed = hwAnimDataItemsUsed; - - - return dest; - } - - void VertexData::convertVertexElement(VertexElementSemantic semantic, VertexElementType dstType) - { - auto elem = vertexDeclaration->findElementBySemantic(semantic); - - if (!elem || VertexElement::getBaseType(elem->getType()) == VertexElement::getBaseType(dstType)) - return; // nothing to do - - auto srcType = elem->getType(); - auto vbuf = vertexBufferBinding->getBuffer(elem->getSource()); - - size_t newElemSize = VertexElement::getTypeSize(dstType); - size_t newVertexSize = vbuf->getVertexSize() - elem->getSize() + newElemSize; - auto newVBuf = vbuf->getManager()->createVertexBuffer(newVertexSize, vbuf->getNumVertices(), vbuf->getUsage(), - vbuf->hasShadowBuffer()); - - { - HardwareBufferLockGuard dst(newVBuf, HardwareBuffer::HBL_DISCARD); - auto pDst = static_cast(dst.pData); - - if(dstType == VET_INT_10_10_10_2_NORM) - { - if(srcType == VET_FLOAT3) - spliceElement(elem, vbuf, pDst, pDst, newElemSize, pack_10_10_10_2); - else - { - OgreAssert(srcType == VET_FLOAT4, "unsupported conversion"); - spliceElement(elem, vbuf, pDst, pDst, newElemSize, pack_10_10_10_2); - } - } - else if(dstType == VET_FLOAT3) - { - OgreAssert(srcType == VET_INT_10_10_10_2_NORM, "unsupported conversion"); - spliceElement(elem, vbuf, pDst, pDst, newElemSize, unpack_10_10_10_2); - } - else if(dstType == VET_FLOAT4) - { - OgreAssert(srcType == VET_INT_10_10_10_2_NORM, "unsupported conversion"); - spliceElement(elem, vbuf, pDst, pDst, newElemSize, unpack_10_10_10_2); - } - else - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "unsupported dstType"); - } - } - - // Bind the new buffer - vertexBufferBinding->setBinding(elem->getSource(), newVBuf); - updateVertexDeclaration(vertexDeclaration, elem, dstType, elem->getSource()); - } - //----------------------------------------------------------------------- - void VertexData::prepareForShadowVolume(void) - { - /* NOTE - I would dearly, dearly love to just use a 4D position buffer in order to - store the extra 'w' value I need to differentiate between extruded and - non-extruded sections of the buffer, so that vertex programs could use that. - Hey, it works fine for GL. However, D3D9 in it's infinite stupidity, does not - support 4d position vertices in the fixed-function pipeline. If you use them, - you just see nothing. Since we can't know whether the application is going to use - fixed function or vertex programs, we have to stick to 3d position vertices and - store the 'w' in a separate 1D texture coordinate buffer, which is only used - when rendering the shadow. - */ - - // Look for a position element - const VertexElement* posElem = vertexDeclaration->findElementBySemantic(VES_POSITION); - if (!posElem) - return; - - // Upfront, lets check whether we have vertex program capability - bool useVertexPrograms = Root::getSingleton().getRenderSystem() != 0; - - auto vbuf = vertexBufferBinding->getBuffer(posElem->getSource()); - - // Are there other elements in the buffer except for the position? - // We need to create another buffer to contain the remaining elements - // Most drivers don't like gaps in the declaration, and in any case it's waste - HardwareVertexBufferPtr newRemainderBuffer; - if (vbuf->getVertexSize() > posElem->getSize()) - { - newRemainderBuffer = vbuf->getManager()->createVertexBuffer( - vbuf->getVertexSize() - posElem->getSize(), vbuf->getNumVertices(), vbuf->getUsage(), - vbuf->hasShadowBuffer()); - } - // Allocate new position buffer, will be FLOAT3 and 2x the size - size_t oldVertexCount = vbuf->getNumVertices(); - size_t newVertexCount = oldVertexCount * 2; - auto newPosBuffer = vbuf->getManager()->createVertexBuffer( - VertexElement::getTypeSize(VET_FLOAT3), newVertexCount, vbuf->getUsage(), vbuf->hasShadowBuffer()); - - // Point first destination pointer at the start of the new position buffer, - // the other one half way along - auto pDest = static_cast(newPosBuffer->lock(HardwareBuffer::HBL_DISCARD)); - auto pDest2 = pDest + oldVertexCount * 3; - - if (newRemainderBuffer) - { - // Basically we just memcpy the vertex excluding the position - HardwareBufferLockGuard destRemLock(newRemainderBuffer, HardwareBuffer::HBL_DISCARD); - spliceElement(posElem, vbuf, (uint8*)destRemLock.pData, (uint8*)pDest, posElem->getSize(), copy_float3); - } - else - { - // Unshared buffer, can block copy the whole thing - vbuf->readData(0, vbuf->getSizeInBytes(), pDest); - } - - memcpy(pDest2, pDest, oldVertexCount * 3 * sizeof(float)); - - newPosBuffer->unlock(); - - // At this stage, he original vertex buffer is going to be destroyed - // So we should force the deallocation of any temporary copies - vbuf->getManager()->_forceReleaseBufferCopies(vbuf); - - if (useVertexPrograms) - { - // Now it's time to set up the w buffer - hardwareShadowVolWBuffer = - vbuf->getManager()->createVertexBuffer(sizeof(float), newVertexCount, HBU_GPU_ONLY, false); - // Fill the first half with 1.0, second half with 0.0 - pDest = static_cast(hardwareShadowVolWBuffer->lock(HardwareBuffer::HBL_DISCARD)); - for (size_t v = 0; v < oldVertexCount; ++v) - { - *pDest++ = 1.0f; - } - // Fill the second half with 0.0 - memset(pDest, 0, sizeof(float) * oldVertexCount); - hardwareShadowVolWBuffer->unlock(); - } - - auto newPosBufferSource = posElem->getSource(); - if (newRemainderBuffer) - { - // Get the a new buffer binding index - newPosBufferSource= vertexBufferBinding->getNextIndex(); - // Re-bind the old index to the remainder buffer - vertexBufferBinding->setBinding(posElem->getSource(), newRemainderBuffer); - } - - // Bind the new position buffer - vertexBufferBinding->setBinding(newPosBufferSource, newPosBuffer); - - // Now, alter the vertex declaration to change the position source - // and the offsets of elements using the same buffer - // Note that we don't change vertexCount, because the other buffer(s) are still the same - // size after all - updateVertexDeclaration(vertexDeclaration, posElem, VET_FLOAT3, newPosBufferSource); - } - //----------------------------------------------------------------------- - void VertexData::reorganiseBuffers(VertexDeclaration* newDeclaration, const BufferUsageList& bufferUsages, - HardwareBufferManagerBase* mgr) - { - HardwareBufferManagerBase* pManager = mgr ? mgr : mMgr; - // Firstly, close up any gaps in the buffer sources which might have arisen - newDeclaration->closeGapsInSource(); - - // Build up a list of both old and new elements in each buffer - std::vector oldBufferLocks; - std::vector oldBufferVertexSizes; - std::vector newBufferLocks; - std::vector newBufferVertexSizes; - VertexBufferBinding* newBinding = pManager->createVertexBufferBinding(); - const auto& oldBindingMap = vertexBufferBinding->getBindings(); - VertexBufferBinding::VertexBufferBindingMap::const_iterator itBinding; - - // Pre-allocate old buffer locks - if (!oldBindingMap.empty()) - { - size_t count = oldBindingMap.rbegin()->first + 1; - oldBufferLocks.resize(count); - oldBufferVertexSizes.resize(count); - } - - bool useShadowBuffer = false; - - // Lock all the old buffers for reading - for (const auto& it : oldBindingMap) - { - assert(it.second->getNumVertices() >= vertexCount); - - oldBufferVertexSizes[it.first] = it.second->getVertexSize(); - oldBufferLocks[it.first] = (uint8*)it.second->lock(HardwareBuffer::HBL_READ_ONLY); - - useShadowBuffer |= it.second->hasShadowBuffer(); - } - - // Create new buffers and lock all for writing - uint16 buf = 0; - while (!newDeclaration->findElementsBySource(buf).empty()) - { - size_t vertexSize = newDeclaration->getVertexSize(buf); - - auto vbuf = pManager->createVertexBuffer(vertexSize, vertexCount, bufferUsages[buf], useShadowBuffer); - newBinding->setBinding(buf, vbuf); - - newBufferVertexSizes.push_back(vertexSize); - newBufferLocks.push_back((uint8*)vbuf->lock(HardwareBuffer::HBL_DISCARD)); - buf++; - } - - // Map from new to old elements - std::map newToOldElementMap; - const auto& newElemList = newDeclaration->getElements(); - for (const auto& newElem : newElemList) - { - // Find corresponding old element - auto oldElem = vertexDeclaration->findElementBySemantic(newElem.getSemantic(), newElem.getIndex()); - if (!oldElem) - { - // Error, cannot create new elements with this method - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Element not found in old vertex declaration"); - } - newToOldElementMap[&newElem] = oldElem; - } - // Now iterate over the new buffers, pulling data out of the old ones - // For each vertex - for (size_t v = 0; v < vertexCount; ++v) - { - // For each (new) element - for (const auto& newElem : newElemList) - { - const VertexElement* oldElem = newToOldElementMap[&newElem]; - auto oldBufferNo = oldElem->getSource(); - auto newBufferNo = newElem.getSource(); - auto pSrc = oldBufferLocks[oldBufferNo] + v * oldBufferVertexSizes[oldBufferNo]; - auto pDst = newBufferLocks[newBufferNo] + v * newBufferVertexSizes[newBufferNo]; - memcpy(pDst + newElem.getOffset(), pSrc + oldElem->getOffset(), newElem.getSize()); - } - } - - // Unlock all buffers - for (const auto& it : oldBindingMap) - { - it.second->unlock(); - } - for (buf = 0; buf < newBinding->getBufferCount(); ++buf) - { - newBinding->getBuffer(buf)->unlock(); - } - - // Delete old binding & declaration - if (mDeleteDclBinding) - { - pManager->destroyVertexBufferBinding(vertexBufferBinding); - pManager->destroyVertexDeclaration(vertexDeclaration); - } - - // Assign new binding and declaration - vertexDeclaration = newDeclaration; - vertexBufferBinding = newBinding; - // after this is complete, new manager should be used - mMgr = pManager; - mDeleteDclBinding = true; // because we created these through a manager - - } - //----------------------------------------------------------------------- - void VertexData::reorganiseBuffers(VertexDeclaration* newDeclaration, HardwareBufferManagerBase* mgr) - { - // Derive the buffer usages from looking at where the source has come - // from - BufferUsageList usages; - for (unsigned short b = 0; b <= newDeclaration->getMaxSource(); ++b) - { - VertexDeclaration::VertexElementList destElems = newDeclaration->findElementsBySource(b); - // Initialise with most restrictive version - uint8 final = HBU_GPU_ONLY; - for (VertexElement& destelem : destElems) - { - // get source - const VertexElement* srcelem = - vertexDeclaration->findElementBySemantic( - destelem.getSemantic(), destelem.getIndex()); - // get buffer - HardwareVertexBufferSharedPtr srcbuf = - vertexBufferBinding->getBuffer(srcelem->getSource()); - // improve flexibility only - if (srcbuf->getUsage() & HBU_CPU_ONLY) - { - // remove static - final &= ~HBU_GPU_TO_CPU; - // add dynamic - final |= HBU_CPU_ONLY; - } - if (!(srcbuf->getUsage() & HBU_DETAIL_WRITE_ONLY)) - { - // remove write only - final &= ~HBU_DETAIL_WRITE_ONLY; - } - } - usages.push_back(static_cast(final)); - } - // Call specific method - reorganiseBuffers(newDeclaration, usages, mgr); - - } - //----------------------------------------------------------------------- - void VertexData::closeGapsInBindings(void) - { - if (!vertexBufferBinding->hasGaps()) - return; - - // Check for error first - const VertexDeclaration::VertexElementList& allelems = - vertexDeclaration->getElements(); - for (auto& e : allelems) - { - if (!vertexBufferBinding->isBufferBound(e.getSource())) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "No buffer is bound to that element source.", - "VertexData::closeGapsInBindings"); - } - } - - // Close gaps in the vertex buffer bindings - VertexBufferBinding::BindingIndexMap bindingIndexMap; - vertexBufferBinding->closeGaps(bindingIndexMap); - - // Modify vertex elements to reference to new buffer index - unsigned short elemIndex = 0; - for (auto ai = allelems.begin(); ai != allelems.end(); ++ai, ++elemIndex) - { - const VertexElement& elem = *ai; - VertexBufferBinding::BindingIndexMap::const_iterator it = - bindingIndexMap.find(elem.getSource()); - assert(it != bindingIndexMap.end()); - ushort targetSource = it->second; - if (elem.getSource() != targetSource) - { - vertexDeclaration->modifyElement(elemIndex, - targetSource, elem.getOffset(), elem.getType(), - elem.getSemantic(), elem.getIndex()); - } - } - } - //----------------------------------------------------------------------- - void VertexData::removeUnusedBuffers(void) - { - std::set usedBuffers; - - // Collect used buffers - const VertexDeclaration::VertexElementList& allelems = - vertexDeclaration->getElements(); - for (auto& e : allelems) - { - usedBuffers.insert(e.getSource()); - } - - // Unset unused buffer bindings - ushort count = vertexBufferBinding->getLastBoundIndex(); - for (ushort index = 0; index < count; ++index) - { - if (usedBuffers.find(index) == usedBuffers.end() && - vertexBufferBinding->isBufferBound(index)) - { - vertexBufferBinding->unsetBinding(index); - } - } - - // Close gaps - closeGapsInBindings(); - } - //----------------------------------------------------------------------- - void VertexData::convertPackedColour(VertexElementType, VertexElementType destType) - { - OgreAssert(destType == VET_UBYTE4_NORM, "Not supported"); - - const VertexBufferBinding::VertexBufferBindingMap& bindMap = - vertexBufferBinding->getBindings(); - for (auto& m : bindMap) - { - const auto& elems = - vertexDeclaration->findElementsBySource(m.first); - bool conversionNeeded = false; - for (auto& e : elems) - { - if (e.getType() == _DETAIL_SWAP_RB) - { - conversionNeeded = true; - } - } - - if (conversionNeeded) - { - void* pBase = m.second->lock(HardwareBuffer::HBL_NORMAL); - - for (size_t v = 0; v < m.second->getNumVertices(); ++v) - { - - for (auto& e : elems) - { - if (e.getType() == _DETAIL_SWAP_RB) - { - uint32* pRGBA; - e.baseVertexPointerToElement(pBase, &pRGBA); - swapPackedRB(pRGBA); - } - } - pBase = static_cast( - static_cast(pBase) + m.second->getVertexSize()); - } - m.second->unlock(); - - // Modify the elements to reflect the changed type - const VertexDeclaration::VertexElementList& allelems = - vertexDeclaration->getElements(); - unsigned short elemIndex = 0; - for (auto& e : allelems) - { - if (e.getType() == _DETAIL_SWAP_RB) - { - vertexDeclaration->modifyElement(elemIndex, - e.getSource(), e.getOffset(), destType, - e.getSemantic(), e.getIndex()); - } - ++elemIndex; - } - } - } // each buffer - } - //----------------------------------------------------------------------- - ushort VertexData::allocateHardwareAnimationElements(ushort count, bool animateNormals) - { - // Find first free texture coord set - unsigned short texCoord = vertexDeclaration->getNextFreeTextureCoordinate(); - unsigned short freeCount = (ushort)(OGRE_MAX_TEXTURE_COORD_SETS - texCoord); - if (animateNormals) - // we need 2x the texture coords, round down - freeCount /= 2; - - unsigned short supportedCount = std::min(freeCount, count); - - // Increase to correct size - for (size_t c = hwAnimationDataList.size(); c < supportedCount; ++c) - { - // Create a new 3D texture coordinate set - HardwareAnimationData data; - data.targetBufferIndex = vertexBufferBinding->getNextIndex(); - vertexDeclaration->addElement(data.targetBufferIndex, 0, VET_FLOAT3, VES_TEXTURE_COORDINATES, texCoord++); - if (animateNormals) - vertexDeclaration->addElement(data.targetBufferIndex, sizeof(float)*3, VET_FLOAT3, VES_TEXTURE_COORDINATES, texCoord++); - - hwAnimationDataList.push_back(data); - // Vertex buffer will not be bound yet, we expect this to be done by the - // caller when it becomes appropriate (e.g. through a VertexAnimationTrack) - } - - return supportedCount; - } - VertexData* VertexData::_cloneRemovingBlendData() const - { - // Clone without copying data - VertexData* ret = clone(false); - bool removeIndices = Root::getSingleton().isBlendIndicesGpuRedundant(); - bool removeWeights = Root::getSingleton().isBlendWeightsGpuRedundant(); - - unsigned short safeSource = 0xFFFF; - auto blendIndexElem = vertexDeclaration->findElementBySemantic(VES_BLEND_INDICES); - if (blendIndexElem && removeIndices) - { - //save the source in order to prevent the next stage from unbinding it. - safeSource = blendIndexElem->getSource(); - // Remove buffer reference - ret->vertexBufferBinding->unsetBinding(blendIndexElem->getSource()); - } - - // Remove blend weights - const VertexElement* blendWeightElem = vertexDeclaration->findElementBySemantic(VES_BLEND_WEIGHTS); - if (removeWeights && blendWeightElem && blendWeightElem->getSource() != safeSource) - { - // Remove buffer reference - ret->vertexBufferBinding->unsetBinding(blendWeightElem->getSource()); - } - - // remove elements from declaration - if (removeIndices) - ret->vertexDeclaration->removeElement(VES_BLEND_INDICES); - if (removeWeights) - ret->vertexDeclaration->removeElement(VES_BLEND_WEIGHTS); - - // Close gaps in bindings for effective and safely - if (removeWeights || removeIndices) - ret->closeGapsInBindings(); - - return ret; - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - IndexData::IndexData() - { - indexCount = 0; - indexStart = 0; - - } - //----------------------------------------------------------------------- - IndexData::~IndexData() - { - } - //----------------------------------------------------------------------- - IndexData* IndexData::clone(bool copyData, HardwareBufferManagerBase* mgr) const - { - HardwareBufferManagerBase* pManager = mgr ? mgr : HardwareBufferManager::getSingletonPtr(); - IndexData* dest = OGRE_NEW IndexData(); - if (indexBuffer.get()) - { - if (copyData) - { - dest->indexBuffer = pManager->createIndexBuffer(indexBuffer->getType(), indexBuffer->getNumIndexes(), - indexBuffer->getUsage(), indexBuffer->hasShadowBuffer()); - dest->indexBuffer->copyData(*indexBuffer, 0, 0, indexBuffer->getSizeInBytes(), true); - } - else - { - dest->indexBuffer = indexBuffer; - } - } - dest->indexCount = indexCount; - dest->indexStart = indexStart; - return dest; - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - // Local Utility class for vertex cache optimizer - class Triangle - { - public: - enum EdgeMatchType { - AB, BC, CA, ANY, NONE - }; - - uint32 a, b, c; - - inline Triangle() - { - } - - inline Triangle( uint32 ta, uint32 tb, uint32 tc ) - : a( ta ), b( tb ), c( tc ) - { - } - - inline Triangle( uint32 t[3] ) - : a( t[0] ), b( t[1] ), c( t[2] ) - { - } - - inline Triangle( const Triangle& t ) - : a( t.a ), b( t.b ), c( t.c ) - { - } - - inline Triangle& operator=(const Triangle& rhs) { - a = rhs.a; - b = rhs.b; - c = rhs.c; - return *this; - } - - inline bool sharesEdge(const Triangle& t) const - { - return( (a == t.a && b == t.c) || - (a == t.b && b == t.a) || - (a == t.c && b == t.b) || - (b == t.a && c == t.c) || - (b == t.b && c == t.a) || - (b == t.c && c == t.b) || - (c == t.a && a == t.c) || - (c == t.b && a == t.a) || - (c == t.c && a == t.b) ); - } - - inline bool sharesEdge(const uint32 ea, const uint32 eb, const Triangle& t) const - { - return( (ea == t.a && eb == t.c) || - (ea == t.b && eb == t.a) || - (ea == t.c && eb == t.b) ); - } - - inline bool sharesEdge(const EdgeMatchType edge, const Triangle& t) const - { - if (edge == AB) - return sharesEdge(a, b, t); - else if (edge == BC) - return sharesEdge(b, c, t); - else if (edge == CA) - return sharesEdge(c, a, t); - else - return (edge == ANY) == sharesEdge(t); - } - - inline EdgeMatchType endoSharedEdge(const Triangle& t) const - { - if (sharesEdge(a, b, t)) return AB; - if (sharesEdge(b, c, t)) return BC; - if (sharesEdge(c, a, t)) return CA; - return NONE; - } - - inline EdgeMatchType exoSharedEdge(const Triangle& t) const - { - return t.endoSharedEdge(*this); - } - - inline void shiftClockwise() - { - uint32 t = a; - a = c; - c = b; - b = t; - } - - inline void shiftCounterClockwise() - { - uint32 t = a; - a = b; - b = c; - c = t; - } - }; - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - void IndexData::optimiseVertexCacheTriList(void) - { - if (indexBuffer->isLocked()) return; - - void *buffer = indexBuffer->lock(HardwareBuffer::HBL_NORMAL); - - Triangle* triangles; - - size_t nIndexes = indexCount; - size_t nTriangles = nIndexes / 3; - size_t i, j; - uint16 *source = 0; - - if (indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT) - { - triangles = OGRE_ALLOC_T(Triangle, nTriangles, MEMCATEGORY_GEOMETRY); - source = (uint16 *)buffer; - uint32 *dest = (uint32 *)triangles; - for (i = 0; i < nIndexes; ++i) dest[i] = source[i]; - } - else - triangles = static_cast(buffer); - - // sort triangles based on shared edges - uint32 *destlist = OGRE_ALLOC_T(uint32, nTriangles, MEMCATEGORY_GEOMETRY); - unsigned char *visited = OGRE_ALLOC_T(unsigned char, nTriangles, MEMCATEGORY_GEOMETRY); - - for (i = 0; i < nTriangles; ++i) visited[i] = 0; - - uint32 start = 0, ti = 0, destcount = 0; - - bool found = false; - for (i = 0; i < nTriangles; ++i) - { - if (found) - found = false; - else - { - while (visited[start++]); - ti = start - 1; - } - - destlist[destcount++] = ti; - visited[ti] = 1; - - for (j = start; j < nTriangles; ++j) - { - if (visited[j]) continue; - - if (triangles[ti].sharesEdge(triangles[j])) - { - found = true; - ti = static_cast(j); - break; - } - } - } - - if (indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT) - { - // reorder the indexbuffer - j = 0; - for (i = 0; i < nTriangles; ++i) - { - Triangle *t = &triangles[destlist[i]]; - if(source) - { - source[j++] = (uint16)t->a; - source[j++] = (uint16)t->b; - source[j++] = (uint16)t->c; - } - } - OGRE_FREE(triangles, MEMCATEGORY_GEOMETRY); - } - else - { - uint32 *reflist = OGRE_ALLOC_T(uint32, nTriangles, MEMCATEGORY_GEOMETRY); - - // fill the referencebuffer - for (i = 0; i < nTriangles; ++i) - reflist[destlist[i]] = static_cast(i); - - // reorder the indexbuffer - for (i = 0; i < nTriangles; ++i) - { - j = destlist[i]; - if (i == j) continue; // do not move triangle - - // swap triangles - - Triangle t = triangles[i]; - triangles[i] = triangles[j]; - triangles[j] = t; - - // change reference - destlist[reflist[i]] = static_cast(j); - // destlist[i] = i; // not needed, it will not be used - } - - OGRE_FREE(reflist, MEMCATEGORY_GEOMETRY); - } - - OGRE_FREE(destlist, MEMCATEGORY_GEOMETRY); - OGRE_FREE(visited, MEMCATEGORY_GEOMETRY); - - indexBuffer->unlock(); - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - void VertexCacheProfiler::profile(const HardwareIndexBufferSharedPtr& indexBuffer) - { - if (indexBuffer->isLocked()) return; - - uint16 *shortbuffer = (uint16 *)indexBuffer->lock(HardwareBuffer::HBL_READ_ONLY); - - if (indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT) - for (unsigned int i = 0; i < indexBuffer->getNumIndexes(); ++i) - inCache(shortbuffer[i]); - else - { - uint32 *buffer = (uint32 *)shortbuffer; - for (unsigned int i = 0; i < indexBuffer->getNumIndexes(); ++i) - inCache(buffer[i]); - } - - indexBuffer->unlock(); - } - - //----------------------------------------------------------------------- - bool VertexCacheProfiler::inCache(unsigned int index) - { - for (unsigned int i = 0; i < buffersize; ++i) - { - if (index == cache[i]) - { - hit++; - return true; - } - } - - miss++; - cache[tail++] = index; - tail %= size; - - if (buffersize < size) buffersize++; - - return false; - } - - -} diff --git a/OgreMain/src/OgreViewport.cpp b/OgreMain/src/OgreViewport.cpp deleted file mode 100644 index 7f9319c7c97..00000000000 --- a/OgreMain/src/OgreViewport.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreViewport.h" -#include "OgreRenderTarget.h" - -namespace Ogre { - //--------------------------------------------------------------------- - Viewport::Viewport(Camera* cam, RenderTarget* target, float left, float top, float width, float height, int ZOrder) - : mCamera(cam) - , mTarget(target) - , mRelRect(left, top, left + width, top + height) - // Actual dimensions will update later - , mZOrder(ZOrder) - , mBackColour(ColourValue::Black) - , mDepthClearValue(1) - , mClearEveryFrame(true) - , mClearBuffers(FBT_COLOUR | FBT_DEPTH) - , mUpdated(false) - , mShowOverlays(true) - , mShowSkies(true) - , mShowShadows(true) - , mVisibilityMask(0xFFFFFFFF) - , mMaterialSchemeName(MaterialManager::DEFAULT_SCHEME_NAME) - , mIsAutoUpdated(true) - , mColourBuffer(CBT_BACK) - { -#if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID - LogManager::getSingleton().stream(LML_TRIVIAL) - << "Creating viewport on target '" << target->getName() << "'" - << ", rendering from camera '" << (cam != 0 ? cam->getName() : "NULL") << "'" - << ", relative dimensions " << mRelRect - << " Z-order: " << ZOrder; -#endif - - // Set the default material scheme - RenderSystem* rs = Root::getSingleton().getRenderSystem(); - mMaterialSchemeName = rs->_getDefaultViewportMaterialScheme(); - - // Calculate actual dimensions - _updateDimensions(); - - // notify camera - if(cam) cam->_notifyViewport(this); - } - //--------------------------------------------------------------------- - Viewport::~Viewport() - { - ListenerList listenersCopy; - std::swap(mListeners, listenersCopy); - for (auto *l : listenersCopy) - { - l->viewportDestroyed(this); - } - - RenderSystem* rs = Root::getSingleton().getRenderSystem(); - if ((rs) && (rs->_getViewport() == this)) - { - rs->_setViewport(NULL); - } - } - //--------------------------------------------------------------------- - bool Viewport::_isUpdated(void) const - { - return mUpdated; - } - //--------------------------------------------------------------------- - void Viewport::_clearUpdatedFlag(void) - { - mUpdated = false; - } - //--------------------------------------------------------------------- - void Viewport::_updateDimensions(void) - { - Real height = (Real) mTarget->getHeight(); - Real width = (Real) mTarget->getWidth(); - - mActRect = Rect(mRelRect.left * width, mRelRect.top * height, mRelRect.right * width, mRelRect.bottom * height); - - // This will check if the cameras getAutoAspectRatio() property is set. - // If it's true its aspect ratio is fit to the current viewport - // If it's false the camera remains unchanged. - // This allows cameras to be used to render to many viewports, - // which can have their own dimensions and aspect ratios. - - if (mCamera) - { - if (mCamera->getAutoAspectRatio()) - mCamera->setAspectRatio((float)mActRect.width() / (float)mActRect.height()); - } - - LogManager::getSingleton().stream(LML_TRIVIAL) - << "Viewport for camera '" << (mCamera ? mCamera->getName() : "NULL") << "'" - << ", actual dimensions " << mActRect; - - mUpdated = true; - - for (auto *l : mListeners) - { - l->viewportDimensionsChanged(this); - } - } - //--------------------------------------------------------------------- - void Viewport::setDimensions(float left, float top, float width, float height) - { - mRelRect = FloatRect(left, top, left + width, top + height); - _updateDimensions(); - } - //--------------------------------------------------------------------- - void Viewport::update(void) - { - if (mCamera) - { - if (mCamera->getViewport() != this) - mCamera->_notifyViewport(this); - - // Tell Camera to render into me - mCamera->_renderScene(this); - } - } - //--------------------------------------------------------------------- - void Viewport::setClearEveryFrame(bool inClear, unsigned int inBuffers) - { - mClearEveryFrame = inClear; - mClearBuffers = inClear ? inBuffers : 0; - } - //--------------------------------------------------------------------- - void Viewport::clear(uint32 buffers, const ColourValue& col, float depth, uint16 stencil) - { - RenderSystem* rs = Root::getSingleton().getRenderSystem(); - if (rs) - { - Viewport* currentvp = rs->_getViewport(); - if (currentvp && currentvp == this) - rs->clearFrameBuffer(buffers, col, depth, stencil); - else - { - rs->_setViewport(this); - rs->clearFrameBuffer(buffers, col, depth, stencil); - rs->_setViewport(currentvp); - } - } - } - //--------------------------------------------------------------------- - void Viewport::getActualDimensions(int &left, int&top, int &width, int &height) const - { - left = mActRect.left; - top = mActRect.top; - width = mActRect.width(); - height = mActRect.height(); - } - //--------------------------------------------------------------------- - unsigned int Viewport::_getNumRenderedFaces(void) const - { - return mCamera ? mCamera->_getNumRenderedFaces() : 0; - } - //--------------------------------------------------------------------- - unsigned int Viewport::_getNumRenderedBatches(void) const - { - return mCamera ? mCamera->_getNumRenderedBatches() : 0; - } - //--------------------------------------------------------------------- - void Viewport::setCamera(Camera* cam) - { - if (cam != NULL && mCamera != NULL && mCamera->getViewport() == this) - { - mCamera->_notifyViewport(NULL); - } - - mCamera = cam; - if (cam) - { - // update aspect ratio of new camera if needed. - if (cam->getAutoAspectRatio()) - { - cam->setAspectRatio((float)mActRect.width() / (float)mActRect.height()); - } - cam->_notifyViewport(this); - } - - for (auto *l : mListeners) - { - l->viewportCameraChanged(this); - } - } - //----------------------------------------------------------------------- - void Viewport::addListener(Listener* l) - { - if (std::find(mListeners.begin(), mListeners.end(), l) == mListeners.end()) - mListeners.push_back(l); - } - //----------------------------------------------------------------------- - void Viewport::removeListener(Listener* l) - { - ListenerList::iterator i = std::find(mListeners.begin(), mListeners.end(), l); - if (i != mListeners.end()) - mListeners.erase(i); - } -} diff --git a/OgreMain/src/OgreWireBoundingBox.cpp b/OgreMain/src/OgreWireBoundingBox.cpp deleted file mode 100644 index 2a2e7c9a1f6..00000000000 --- a/OgreMain/src/OgreWireBoundingBox.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreWireBoundingBox.h" - -namespace Ogre { - #define POSITION_BINDING 0 - - WireBoundingBox::WireBoundingBox() - : SimpleRenderable() - { - _initWireBoundingBox(); - } - - WireBoundingBox::WireBoundingBox(const String& name) - : SimpleRenderable(name) - { - _initWireBoundingBox(); - } - - void WireBoundingBox::_initWireBoundingBox() - { - mRenderOp.vertexData = OGRE_NEW VertexData(); - - mRenderOp.indexData = 0; - mRenderOp.vertexData->vertexCount = 24; - mRenderOp.vertexData->vertexStart = 0; - mRenderOp.operationType = RenderOperation::OT_LINE_LIST; - mRenderOp.useIndexes = false; - mRenderOp.useGlobalInstancing = false; - - VertexDeclaration* decl = mRenderOp.vertexData->vertexDeclaration; - VertexBufferBinding* bind = mRenderOp.vertexData->vertexBufferBinding; - - decl->addElement(POSITION_BINDING, 0, VET_FLOAT3, VES_POSITION); - - - HardwareVertexBufferSharedPtr vbuf = - HardwareBufferManager::getSingleton().createVertexBuffer( - decl->getVertexSize(POSITION_BINDING), - mRenderOp.vertexData->vertexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - // Bind buffer - bind->setBinding(POSITION_BINDING, vbuf); - - // set basic white material - mMaterial = MaterialManager::getSingleton().getDefaultMaterial(false); - mMaterial->load(); - } - - WireBoundingBox::~WireBoundingBox() - { - OGRE_DELETE mRenderOp.vertexData; - } - - void WireBoundingBox::setupBoundingBox(const AxisAlignedBox& aabb) - { - // init the vertices to the aabb - setupBoundingBoxVertices(aabb); - - // setup the bounding box of this SimpleRenderable - setBoundingBox(aabb); - - } - - // Override this method to prevent parent transforms (rotation,translation,scale) - void WireBoundingBox::getWorldTransforms( Matrix4* xform ) const - { - // return identity matrix to prevent parent transforms - *xform = Matrix4::IDENTITY; - } - //----------------------------------------------------------------------- - void WireBoundingBox::setupBoundingBoxVertices(const AxisAlignedBox& aab) { - - Vector3 vmax = aab.getMaximum(); - Vector3 vmin = aab.getMinimum(); - - Real sqLen = std::max(vmax.squaredLength(), vmin.squaredLength()); - mRadius = Math::Sqrt(sqLen); - - - - - Real maxx = vmax.x; - Real maxy = vmax.y; - Real maxz = vmax.z; - - Real minx = vmin.x; - Real miny = vmin.y; - Real minz = vmin.z; - - // fill in the Vertex buffer: 12 lines with 2 endpoints each make up a box - HardwareVertexBufferSharedPtr vbuf = - mRenderOp.vertexData->vertexBufferBinding->getBuffer(POSITION_BINDING); - - HardwareBufferLockGuard vbufLock(vbuf, HardwareBuffer::HBL_DISCARD); - float* pPos = static_cast(vbufLock.pData); - - // line 0 - *pPos++ = minx; - *pPos++ = miny; - *pPos++ = minz; - *pPos++ = maxx; - *pPos++ = miny; - *pPos++ = minz; - // line 1 - *pPos++ = minx; - *pPos++ = miny; - *pPos++ = minz; - *pPos++ = minx; - *pPos++ = miny; - *pPos++ = maxz; - // line 2 - *pPos++ = minx; - *pPos++ = miny; - *pPos++ = minz; - *pPos++ = minx; - *pPos++ = maxy; - *pPos++ = minz; - // line 3 - *pPos++ = minx; - *pPos++ = maxy; - *pPos++ = minz; - *pPos++ = minx; - *pPos++ = maxy; - *pPos++ = maxz; - // line 4 - *pPos++ = minx; - *pPos++ = maxy; - *pPos++ = minz; - *pPos++ = maxx; - *pPos++ = maxy; - *pPos++ = minz; - // line 5 - *pPos++ = maxx; - *pPos++ = miny; - *pPos++ = minz; - *pPos++ = maxx; - *pPos++ = miny; - *pPos++ = maxz; - // line 6 - *pPos++ = maxx; - *pPos++ = miny; - *pPos++ = minz; - *pPos++ = maxx; - *pPos++ = maxy; - *pPos++ = minz; - // line 7 - *pPos++ = minx; - *pPos++ = maxy; - *pPos++ = maxz; - *pPos++ = maxx; - *pPos++ = maxy; - *pPos++ = maxz; - // line 8 - *pPos++ = minx; - *pPos++ = maxy; - *pPos++ = maxz; - *pPos++ = minx; - *pPos++ = miny; - *pPos++ = maxz; - // line 9 - *pPos++ = maxx; - *pPos++ = maxy; - *pPos++ = minz; - *pPos++ = maxx; - *pPos++ = maxy; - *pPos++ = maxz; - // line 10 - *pPos++ = maxx; - *pPos++ = miny; - *pPos++ = maxz; - *pPos++ = maxx; - *pPos++ = maxy; - *pPos++ = maxz; - // line 11 - *pPos++ = minx; - *pPos++ = miny; - *pPos++ = maxz; - *pPos++ = maxx; - *pPos++ = miny; - *pPos++ = maxz; - } - - //----------------------------------------------------------------------- - Real WireBoundingBox::getSquaredViewDepth(const Camera* cam) const - { - return (cam->getDerivedPosition() - mBox.getCenter()).squaredLength(); - } - - - -} - diff --git a/OgreMain/src/OgreWorkQueue.cpp b/OgreMain/src/OgreWorkQueue.cpp deleted file mode 100644 index 2bf51b57fba..00000000000 --- a/OgreMain/src/OgreWorkQueue.cpp +++ /dev/null @@ -1,197 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" -#include "OgreWorkQueue.h" -#include "OgreTimer.h" - -namespace Ogre { - void WorkQueue::processMainThreadTasks() - { - OGRE_IGNORE_DEPRECATED_BEGIN - processResponses(); - OGRE_IGNORE_DEPRECATED_END - } - //--------------------------------------------------------------------- - WorkQueue::Request::Request(uint16 channel, uint16 rtype, const Any& rData, uint8 retry, RequestID rid) - : mChannel(channel), mType(rtype), mData(rData), mRetryCount(retry), mID(rid), mAborted(false) - { - - } - //--------------------------------------------------------------------- - WorkQueue::Request::~Request() - { - - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - WorkQueue::Response::Response(const Request* rq, bool success, const Any& data, const String& msg) - : mRequest(rq), mSuccess(success), mMessages(msg), mData(data) - { - - } - //--------------------------------------------------------------------- - WorkQueue::Response::~Response() - { - OGRE_DELETE mRequest; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - DefaultWorkQueueBase::DefaultWorkQueueBase(const String& name) - : mName(name) - , mWorkerThreadCount(1) - , mWorkerRenderSystemAccess(false) - , mIsRunning(false) - , mResposeTimeLimitMS(10) - , mPaused(false) - , mAcceptRequests(true) - , mShuttingDown(false) - { - } - //--------------------------------------------------------------------- - const String& DefaultWorkQueueBase::getName() const - { - return mName; - } - //--------------------------------------------------------------------- - size_t DefaultWorkQueueBase::getWorkerThreadCount() const - { - return mWorkerThreadCount; - } - //--------------------------------------------------------------------- - void DefaultWorkQueueBase::setWorkerThreadCount(size_t c) - { - mWorkerThreadCount = c; - } - //--------------------------------------------------------------------- - bool DefaultWorkQueueBase::getWorkersCanAccessRenderSystem() const - { - return mWorkerRenderSystemAccess; - } - //--------------------------------------------------------------------- - void DefaultWorkQueueBase::setWorkersCanAccessRenderSystem(bool access) - { - mWorkerRenderSystemAccess = access; - } - //--------------------------------------------------------------------- - DefaultWorkQueueBase::~DefaultWorkQueueBase() - { - //shutdown(); // can't call here; abstract function - } - void DefaultWorkQueueBase::addMainThreadTask(std::function task) - { - if (!mAcceptRequests || mShuttingDown) - return; - OGRE_WQ_LOCK_MUTEX(mResponseMutex); - mMainThreadTasks.push_back(task); - } - //--------------------------------------------------------------------- - void DefaultWorkQueueBase::addTask(std::function task) - { - OGRE_WQ_LOCK_MUTEX(mRequestMutex); - if (!mAcceptRequests || mShuttingDown) - return; - -#if OGRE_THREAD_SUPPORT - mTasks.push_back(task); - notifyWorkers(); -#else - task(); // no threading, just run it -#endif - LogManager::getSingleton().stream(LML_TRIVIAL) - << "DefaultWorkQueueBase('" << mName << "') - QUEUED(thread:" << OGRE_THREAD_CURRENT_ID << ")"; - } - //--------------------------------------------------------------------- - void DefaultWorkQueueBase::setPaused(bool pause) - { - OGRE_WQ_LOCK_MUTEX(mRequestMutex); - - mPaused = pause; - } - //--------------------------------------------------------------------- - bool DefaultWorkQueueBase::isPaused() const - { - return mPaused; - } - //--------------------------------------------------------------------- - void DefaultWorkQueueBase::setRequestsAccepted(bool accept) - { - OGRE_WQ_LOCK_MUTEX(mRequestMutex); - - mAcceptRequests = accept; - } - //--------------------------------------------------------------------- - bool DefaultWorkQueueBase::getRequestsAccepted() const - { - return mAcceptRequests; - } - //--------------------------------------------------------------------- - void DefaultWorkQueueBase::_processNextRequest() - { - std::function task; - { - // scoped to only lock while retrieving the next request - OGRE_WQ_LOCK_MUTEX(mRequestMutex); - if (mTasks.empty()) - return; - LogManager::getSingleton().stream(LML_TRIVIAL) - << "DefaultWorkQueueBase('" << mName << "') - PROCESS_TASK(thread:" << OGRE_THREAD_CURRENT_ID - << ")"; - task = std::move(mTasks.front()); - mTasks.pop_front(); - } - task(); - } - //--------------------------------------------------------------------- - void DefaultWorkQueueBase::processMainThreadTasks() - { - unsigned long msStart = Root::getSingleton().getTimer()->getMilliseconds(); - unsigned long msCurrent = 0; - - // keep going until we run out of responses or out of time - while(!mMainThreadTasks.empty()) - { - std::function task; - { - OGRE_WQ_LOCK_MUTEX(mResponseMutex); - LogManager::getSingleton().stream(LML_TRIVIAL) - << "DefaultWorkQueueBase('" << mName << "') - PROCESS_MAIN_TASK"; - task = std::move(mMainThreadTasks.front()); - mMainThreadTasks.pop_front(); - } - task(); - - // time limit - if (mResposeTimeLimitMS) - { - msCurrent = Root::getSingleton().getTimer()->getMilliseconds(); - if (msCurrent - msStart > mResposeTimeLimitMS) - break; - } - } - } -} diff --git a/OgreMain/src/OgreZip.cpp b/OgreMain/src/OgreZip.cpp deleted file mode 100644 index d97f23d4a8f..00000000000 --- a/OgreMain/src/OgreZip.cpp +++ /dev/null @@ -1,399 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreStableHeaders.h" - -#if OGRE_NO_ZIP_ARCHIVE == 0 -#include - -namespace Ogre { -namespace { - class ZipArchive : public Archive - { - protected: - /// Handle to root zip file - zip_t* mZipFile; - MemoryDataStreamPtr mBuffer; - /// File list (since zziplib seems to only allow scanning of dir tree once) - FileInfoList mFileList; - OGRE_AUTO_MUTEX; - public: - ZipArchive(const String& name, const String& archType, const uint8* externBuf = 0, size_t externBufSz = 0); - ~ZipArchive(); - /// @copydoc Archive::isCaseSensitive - bool isCaseSensitive(void) const override { return OGRE_RESOURCEMANAGER_STRICT != 0; } - - /// @copydoc Archive::load - void load() override; - /// @copydoc Archive::unload - void unload() final override; - - /// @copydoc Archive::open - DataStreamPtr open(const String& filename, bool readOnly = true) const override; - - /// @copydoc Archive::create - DataStreamPtr create(const String& filename) override; - - /// @copydoc Archive::remove - void remove(const String& filename) override; - - /// @copydoc Archive::list - StringVectorPtr list(bool recursive = true, bool dirs = false) const override; - - /// @copydoc Archive::listFileInfo - FileInfoListPtr listFileInfo(bool recursive = true, bool dirs = false) const override; - - /// @copydoc Archive::find - StringVectorPtr find(const String& pattern, bool recursive = true, - bool dirs = false) const override; - - /// @copydoc Archive::findFileInfo - FileInfoListPtr findFileInfo(const String& pattern, bool recursive = true, - bool dirs = false) const override; - - /// @copydoc Archive::exists - bool exists(const String& filename) const override; - - /// @copydoc Archive::getModifiedTime - time_t getModifiedTime(const String& filename) const override; - }; -} - //----------------------------------------------------------------------- - ZipArchive::ZipArchive(const String& name, const String& archType, const uint8* externBuf, size_t externBufSz) - : Archive(name, archType), mZipFile(0) - { - if(externBuf) - mBuffer.reset(new MemoryDataStream(const_cast(externBuf), externBufSz)); - } - //----------------------------------------------------------------------- - ZipArchive::~ZipArchive() - { - unload(); - } - //----------------------------------------------------------------------- - void ZipArchive::load() - { - OGRE_LOCK_AUTO_MUTEX; - if (!mZipFile) - { - if(!mBuffer) - mBuffer.reset(new MemoryDataStream(_openFileStream(mName, std::ios::binary))); - - mZipFile = zip_stream_open((const char*)mBuffer->getPtr(), mBuffer->size(), 0, 'r'); - - // Cache names - int n = zip_entries_total(mZipFile); - for (int i = 0; i < n; ++i) { - FileInfo info; - info.archive = this; - - zip_entry_openbyindex(mZipFile, i); - - info.filename = zip_entry_name(mZipFile); - // Get basename / path - StringUtil::splitFilename(info.filename, info.basename, info.path); - - // Get sizes - info.uncompressedSize = zip_entry_size(mZipFile); - info.compressedSize = zip_entry_comp_size(mZipFile); - - if (zip_entry_isdir(mZipFile)) - { - info.filename = info.filename.substr(0, info.filename.length() - 1); - StringUtil::splitFilename(info.filename, info.basename, info.path); - // Set compressed size to -1 for folders; anyway nobody will check - // the compressed size of a folder, and if he does, its useless anyway - info.compressedSize = size_t(-1); - } -#if !OGRE_RESOURCEMANAGER_STRICT - else - { - info.filename = info.basename; - } -#endif - zip_entry_close(mZipFile); - mFileList.push_back(info); - } - } - } - //----------------------------------------------------------------------- - void ZipArchive::unload() - { - OGRE_LOCK_AUTO_MUTEX; - if (mZipFile) - { - zip_close(mZipFile); - mZipFile = 0; - mFileList.clear(); - mBuffer.reset(); - } - - } - //----------------------------------------------------------------------- - DataStreamPtr ZipArchive::open(const String& filename, bool readOnly) const - { - // zip is not threadsafe - OGRE_LOCK_AUTO_MUTEX; - String lookUpFileName = filename; - - bool open = zip_entry_open(mZipFile, lookUpFileName.c_str(), OGRE_RESOURCEMANAGER_STRICT) == 0; -#if !OGRE_RESOURCEMANAGER_STRICT - if (!open) // Try if we find the file - { - String basename, path; - StringUtil::splitFilename(lookUpFileName, basename, path); - const FileInfoListPtr fileNfo = findFileInfo(basename, true); - if (fileNfo->size() == 1) // If there are more files with the same do not open anyone - { - Ogre::FileInfo info = fileNfo->at(0); - lookUpFileName = info.path + info.basename; - open = zip_entry_open(mZipFile, lookUpFileName.c_str(), OGRE_RESOURCEMANAGER_STRICT) == 0; - } - } -#endif - - if (!open) - { - OGRE_EXCEPT(Exception::ERR_FILE_NOT_FOUND, "could not open "+lookUpFileName); - } - - // Construct & return stream - auto ret = std::make_shared(lookUpFileName, zip_entry_size(mZipFile)); - - if(zip_entry_noallocread(mZipFile, ret->getPtr(), ret->size()) < 0) - OGRE_EXCEPT(Exception::ERR_FILE_NOT_FOUND, "could not read "+lookUpFileName); - zip_entry_close(mZipFile); - - return ret; - } - //--------------------------------------------------------------------- - DataStreamPtr ZipArchive::create(const String& filename) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Modification of zipped archives is not implemented"); - } - //--------------------------------------------------------------------- - void ZipArchive::remove(const String& filename) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Modification of zipped archives is not implemented"); - } - //----------------------------------------------------------------------- - StringVectorPtr ZipArchive::list(bool recursive, bool dirs) const - { - OGRE_LOCK_AUTO_MUTEX; - auto ret = std::make_shared(); - - for (auto& f : mFileList) - if ((dirs == (f.compressedSize == size_t (-1))) && - (recursive || f.path.empty())) - ret->push_back(f.filename); - - return ret; - } - //----------------------------------------------------------------------- - FileInfoListPtr ZipArchive::listFileInfo(bool recursive, bool dirs) const - { - OGRE_LOCK_AUTO_MUTEX; - auto ret = std::make_shared(); - for (auto& f : mFileList) - if ((dirs == (f.compressedSize == size_t (-1))) && - (recursive || f.path.empty())) - ret->push_back(f); - - return ret; - } - //----------------------------------------------------------------------- - StringVectorPtr ZipArchive::find(const String& pattern, bool recursive, bool dirs) const - { - OGRE_LOCK_AUTO_MUTEX; - auto ret = std::make_shared(); - // If pattern contains a directory name, do a full match - bool full_match = (pattern.find ('/') != String::npos) || - (pattern.find ('\\') != String::npos); - bool wildCard = pattern.find('*') != String::npos; - - for (auto& f : mFileList) - if ((dirs == (f.compressedSize == size_t (-1))) && - (recursive || full_match || wildCard)) - // Check basename matches pattern (zip is case insensitive) - if (StringUtil::match(full_match ? f.filename : f.basename, pattern, false)) - ret->push_back(f.filename); - - return ret; - } - //----------------------------------------------------------------------- - FileInfoListPtr ZipArchive::findFileInfo(const String& pattern, - bool recursive, bool dirs) const - { - OGRE_LOCK_AUTO_MUTEX; - auto ret = std::make_shared(); - // If pattern contains a directory name, do a full match - bool full_match = (pattern.find ('/') != String::npos) || - (pattern.find ('\\') != String::npos); - bool wildCard = pattern.find('*') != String::npos; - - for (auto& f : mFileList) - if ((dirs == (f.compressedSize == size_t (-1))) && - (recursive || full_match || wildCard)) - // Check name matches pattern (zip is case insensitive) - if (StringUtil::match(full_match ? f.filename : f.basename, pattern, false)) - ret->push_back(f); - - return ret; - } - //----------------------------------------------------------------------- - bool ZipArchive::exists(const String& filename) const - { - OGRE_LOCK_AUTO_MUTEX; - String cleanName = filename; -#if !OGRE_RESOURCEMANAGER_STRICT - if(filename.rfind('/') != String::npos) - { - StringVector tokens = StringUtil::split(filename, "/"); - cleanName = tokens[tokens.size() - 1]; - } -#endif - - return std::find_if(mFileList.begin(), mFileList.end(), [&cleanName](const Ogre::FileInfo& fi) { - return fi.filename == cleanName; - }) != mFileList.end(); - } - //--------------------------------------------------------------------- - time_t ZipArchive::getModifiedTime(const String& filename) const - { - // Zziplib doesn't yet support getting the modification time of individual files - // so just check the mod time of the zip itself - struct stat tagStat; - bool ret = (stat(mName.c_str(), &tagStat) == 0); - - if (ret) - { - return tagStat.st_mtime; - } - else - { - return 0; - } - - } - //----------------------------------------------------------------------- - // ZipArchiveFactory - //----------------------------------------------------------------------- - Archive *ZipArchiveFactory::createInstance( const String& name, bool readOnly ) - { - if(!readOnly) - return NULL; - - return OGRE_NEW ZipArchive(name, getType()); - } - //----------------------------------------------------------------------- - const String& ZipArchiveFactory::getType(void) const - { - static String name = "Zip"; - return name; - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - // EmbeddedZipArchiveFactory - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - /// a struct to hold embedded file data - struct EmbeddedFileData - { - const uint8 * fileData; - size_t fileSize; - size_t curPos; - bool isFileOpened; - EmbeddedZipArchiveFactory::DecryptEmbeddedZipFileFunc decryptFunc; - }; - //----------------------------------------------------------------------- - /// A type for a map between the file names to file index - typedef std::map EmbbedFileDataList; - - namespace { - /// A static list to store the embedded files data - EmbbedFileDataList *gEmbeddedFileDataList; - } // namespace { - //----------------------------------------------------------------------- - EmbeddedZipArchiveFactory::EmbeddedZipArchiveFactory() {} - EmbeddedZipArchiveFactory::~EmbeddedZipArchiveFactory() {} - //----------------------------------------------------------------------- - Archive *EmbeddedZipArchiveFactory::createInstance( const String& name, bool readOnly ) - { - auto it = gEmbeddedFileDataList->find(name); - if(it == gEmbeddedFileDataList->end()) - return NULL; - - // TODO: decryptFunc - - return new ZipArchive(name, getType(), it->second.fileData, it->second.fileSize); - } - void EmbeddedZipArchiveFactory::destroyInstance(Archive* ptr) - { - removeEmbbeddedFile(ptr->getName()); - ZipArchiveFactory::destroyInstance(ptr); - } - //----------------------------------------------------------------------- - const String& EmbeddedZipArchiveFactory::getType(void) const - { - static String name = "EmbeddedZip"; - return name; - } - //----------------------------------------------------------------------- - void EmbeddedZipArchiveFactory::addEmbbeddedFile(const String& name, const uint8 * fileData, - size_t fileSize, DecryptEmbeddedZipFileFunc decryptFunc) - { - static bool needToInit = true; - if(needToInit) - { - needToInit = false; - - // we can't be sure when global variables get initialized - // meaning it is possible our list has not been init when this - // function is being called. The solution is to use local - // static members in this function an init the pointers for the - // global here. We know for use that the local static variables - // are create in this stage. - static EmbbedFileDataList sEmbbedFileDataList; - gEmbeddedFileDataList = &sEmbbedFileDataList; - } - - EmbeddedFileData newEmbeddedFileData; - newEmbeddedFileData.curPos = 0; - newEmbeddedFileData.isFileOpened = false; - newEmbeddedFileData.fileData = fileData; - newEmbeddedFileData.fileSize = fileSize; - newEmbeddedFileData.decryptFunc = decryptFunc; - gEmbeddedFileDataList->emplace(name, newEmbeddedFileData); - } - //----------------------------------------------------------------------- - void EmbeddedZipArchiveFactory::removeEmbbeddedFile( const String& name ) - { - gEmbeddedFileDataList->erase(name); - } -} - -#endif diff --git a/OgreMain/src/SSE2NEON.h b/OgreMain/src/SSE2NEON.h deleted file mode 100644 index 08047aedda5..00000000000 --- a/OgreMain/src/SSE2NEON.h +++ /dev/null @@ -1,1713 +0,0 @@ -#ifndef SSE2NEON_H -#define SSE2NEON_H - -// This header file provides a simple API translation layer -// between SSE intrinsics to their corresponding ARM NEON versions -// -// This header file does not (yet) translate *all* of the SSE intrinsics. -// Since this is in support of a specific porting effort, I have only -// included the intrinsics I needed to get my port to work. -// -// Questions/Comments/Feedback send to: jratcliffscarab@gmail.com -// -// If you want to improve or add to this project, send me an -// email and I will probably approve your access to the depot. -// -// Project is located here: -// -// https://github.com/jratcliff63367/sse2neon -// -// Show your appreciation for open source by sending me a bitcoin tip to the following -// address. -// -// TipJar: 1PzgWDSyq4pmdAXRH8SPUtta4SWGrt4B1p : -// https://blockchain.info/address/1PzgWDSyq4pmdAXRH8SPUtta4SWGrt4B1p -// -// -// Contributors to this project are: -// -// John W. Ratcliff : jratcliffscarab@gmail.com -// Brandon Rowlett : browlett@nvidia.com -// Ken Fast : kfast@gdeb.com -// Eric van Beurden : evanbeurden@nvidia.com -// Alexander Potylitsin : apotylitsin@nvidia.com -// -// -// ********************************************************************************************************************* -// apoty: March 17, 2017 -// Current version was changed in most to fix issues and potential issues. -// All unit tests were rewritten as a part of forge lib project to cover all implemented functions. -// ********************************************************************************************************************* -// Release notes for January 20, 2017 version: -// -// The unit tests have been refactored. They no longer assert on an error, instead they return a pass/fail condition -// The unit-tests now test 10,000 random float and int values against each intrinsic. -// -// SSE2NEON now supports 95 SSE intrinsics. 39 of them have formal unit tests which have been implemented and -// fully tested on NEON/ARM. The remaining 56 still need unit tests implemented. -// -// A struct is now defined in this header file called 'SIMDVec' which can be used by applications which -// attempt to access the contents of an _m128 struct directly. It is important to note that accessing the __m128 -// struct directly is bad coding practice by Microsoft: @see: https://msdn.microsoft.com/en-us/library/ayeb3ayc.aspx -// -// However, some legacy source code may try to access the contents of an __m128 struct directly so the developer -// can use the SIMDVec as an alias for it. Any casting must be done manually by the developer, as you cannot -// cast or otherwise alias the base NEON data type for intrinsic operations. -// -// A bug was found with the _mm_shuffle_ps intrinsic. If the shuffle permutation was not one of the ones with -// a custom/unique implementation causing it to fall through to the default shuffle implementation it was failing -// to return the correct value. This is now fixed. -// -// A bug was found with the _mm_cvtps_epi32 intrinsic. This converts floating point values to integers. -// It was not honoring the correct rounding mode. In SSE the default rounding mode when converting from float to int -// is to use 'round to even' otherwise known as 'bankers rounding'. ARMv7 did not support this feature but ARMv8 does. -// As it stands today, this header file assumes ARMv8. If you are trying to target really old ARM devices, you may get -// a build error. -// -// Support for a number of new intrinsics was added, however, none of them yet have unit-tests to 100% confirm they are -// producing the correct results on NEON. These unit tests will be added as soon as possible. -// -// Here is the list of new instrinsics which have been added: -// -// _mm_cvtss_f32 : extracts the lower order floating point value from the parameter -// _mm_add_ss : adds the scalar single - precision floating point values of a and b -// _mm_div_ps : Divides the four single - precision, floating - point values of a and b. -// _mm_div_ss : Divides the scalar single - precision floating point value of a by b. -// _mm_sqrt_ss : Computes the approximation of the square root of the scalar single - precision floating point value of in. -// _mm_rsqrt_ps : Computes the approximations of the reciprocal square roots of the four single - precision floating point values of in. -// _mm_comilt_ss : Compares the lower single - precision floating point scalar values of a and b using a less than operation -// _mm_comigt_ss : Compares the lower single - precision floating point scalar values of a and b using a greater than operation. -// _mm_comile_ss : Compares the lower single - precision floating point scalar values of a and b using a less than or equal operation. -// _mm_comige_ss : Compares the lower single - precision floating point scalar values of a and b using a greater than or equal operation. -// _mm_comieq_ss : Compares the lower single - precision floating point scalar values of a and b using an equality operation. -// _mm_comineq_s : Compares the lower single - precision floating point scalar values of a and b using an inequality operation -// _mm_unpackhi_epi8 : Interleaves the upper 8 signed or unsigned 8 - bit integers in a with the upper 8 signed or unsigned 8 - bit integers in b. -// _mm_unpackhi_epi16: Interleaves the upper 4 signed or unsigned 16 - bit integers in a with the upper 4 signed or unsigned 16 - bit integers in b. -// -// ********************************************************************************************************************* -/* -** The MIT license: -** -** Permission is hereby granted, free of charge, to any person obtaining a copy -** of this software and associated documentation files (the "Software"), to deal -** in the Software without restriction, including without limitation the rights -** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -** copies of the Software, and to permit persons to whom the Software is furnished -** to do so, subject to the following conditions: -** -** The above copyright notice and this permission notice shall be included in all -** copies or substantial portions of the Software. - -** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -** WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -** CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ - -#define ENABLE_CPP_VERSION 0 - -#if defined(__GNUC__) || defined(__clang__) -# pragma push_macro("FORCE_INLINE") -# pragma push_macro("ALIGN_STRUCT") -# define FORCE_INLINE static inline __attribute__((always_inline)) -# define ALIGN_STRUCT(x) __attribute__((aligned(x))) -#else -# error "Macro name collisions may happens with unknown compiler" -# define FORCE_INLINE static inline -# define ALIGN_STRUCT(x) __declspec(align(x)) -#endif - -#include -#include "arm_neon.h" - - -/*******************************************************/ -/* MACRO for shuffle parameter for _mm_shuffle_ps(). */ -/* Argument fp3 is a digit[0123] that represents the fp*/ -/* from argument "b" of mm_shuffle_ps that will be */ -/* placed in fp3 of result. fp2 is the same for fp2 in */ -/* result. fp1 is a digit[0123] that represents the fp */ -/* from argument "a" of mm_shuffle_ps that will be */ -/* places in fp1 of result. fp0 is the same for fp0 of */ -/* result */ -/*******************************************************/ -#define _MM_SHUFFLE(fp3,fp2,fp1,fp0) \ - (((fp3) << 6) | ((fp2) << 4) | ((fp1) << 2) | ((fp0))) - -/* indicate immediate constant argument in a given range */ -#define __constrange(a,b) \ - const - -typedef float32x4_t __m128; -typedef int32x4_t __m128i; - -typedef float32x2_t __m64; - - -// ****************************************** -// type-safe casting between types -// ****************************************** - -#define vreinterpretq_m128_f16(x) \ - vreinterpretq_f32_f16(x) - -#define vreinterpretq_m128_f32(x) \ - (x) - -#define vreinterpretq_m128_f64(x) \ - vreinterpretq_f32_f64(x) - - -#define vreinterpretq_m128_u8(x) \ - vreinterpretq_f32_u8(x) - -#define vreinterpretq_m128_u16(x) \ - vreinterpretq_f32_u16(x) - -#define vreinterpretq_m128_u32(x) \ - vreinterpretq_f32_u32(x) - -#define vreinterpretq_m128_u64(x) \ - vreinterpretq_f32_u64(x) - - -#define vreinterpretq_m128_s8(x) \ - vreinterpretq_f32_s8(x) - -#define vreinterpretq_m128_s16(x) \ - vreinterpretq_f32_s16(x) - -#define vreinterpretq_m128_s32(x) \ - vreinterpretq_f32_s32(x) - -#define vreinterpretq_m128_s64(x) \ - vreinterpretq_f32_s64(x) - - -#define vreinterpretq_f16_m128(x) \ - vreinterpretq_f16_f32(x) - -#define vreinterpretq_f32_m128(x) \ - (x) - -#define vreinterpretq_f64_m128(x) \ - vreinterpretq_f64_f32(x) - - -#define vreinterpretq_u8_m128(x) \ - vreinterpretq_u8_f32(x) - -#define vreinterpretq_u16_m128(x) \ - vreinterpretq_u16_f32(x) - -#define vreinterpretq_u32_m128(x) \ - vreinterpretq_u32_f32(x) - -#define vreinterpretq_u64_m128(x) \ - vreinterpretq_u64_f32(x) - - -#define vreinterpretq_s8_m128(x) \ - vreinterpretq_s8_f32(x) - -#define vreinterpretq_s16_m128(x) \ - vreinterpretq_s16_f32(x) - -#define vreinterpretq_s32_m128(x) \ - vreinterpretq_s32_f32(x) - -#define vreinterpretq_s64_m128(x) \ - vreinterpretq_s64_f32(x) - - -#define vreinterpretq_m128i_s8(x) \ - vreinterpretq_s32_s8(x) - -#define vreinterpretq_m128i_s16(x) \ - vreinterpretq_s32_s16(x) - -#define vreinterpretq_m128i_s32(x) \ - (x) - -#define vreinterpretq_m128i_s64(x) \ - vreinterpretq_s32_s64(x) - - -#define vreinterpretq_m128i_u8(x) \ - vreinterpretq_s32_u8(x) - -#define vreinterpretq_m128i_u16(x) \ - vreinterpretq_s32_u16(x) - -#define vreinterpretq_m128i_u32(x) \ - vreinterpretq_s32_u32(x) - -#define vreinterpretq_m128i_u64(x) \ - vreinterpretq_s32_u64(x) - - -#define vreinterpretq_s8_m128i(x) \ - vreinterpretq_s8_s32(x) - -#define vreinterpretq_s16_m128i(x) \ - vreinterpretq_s16_s32(x) - -#define vreinterpretq_s32_m128i(x) \ - (x) - -#define vreinterpretq_s64_m128i(x) \ - vreinterpretq_s64_s32(x) - - -#define vreinterpretq_u8_m128i(x) \ - vreinterpretq_u8_s32(x) - -#define vreinterpretq_u16_m128i(x) \ - vreinterpretq_u16_s32(x) - -#define vreinterpretq_u32_m128i(x) \ - vreinterpretq_u32_s32(x) - -#define vreinterpretq_u64_m128i(x) \ - vreinterpretq_u64_s32(x) - - -// union intended to allow direct access to an __m128 variable using the names that the MSVC -// compiler provides. This union should really only be used when trying to access the members -// of the vector as integer values. GCC/clang allow native access to the float members through -// a simple array access operator (in C since 4.6, in C++ since 4.8). -// -// Ideally direct accesses to SIMD vectors should not be used since it can cause a performance -// hit. If it really is needed however, the original __m128 variable can be aliased with a -// pointer to this union and used to access individual components. The use of this union should -// be hidden behind a macro that is used throughout the codebase to access the members instead -// of always declaring this type of variable. -typedef union ALIGN_STRUCT(16) SIMDVec -{ - float m128_f32[4]; // as floats - do not to use this. Added for convenience. - int8_t m128_i8[16]; // as signed 8-bit integers. - int16_t m128_i16[8]; // as signed 16-bit integers. - int32_t m128_i32[4]; // as signed 32-bit integers. - int64_t m128_i64[2]; // as signed 64-bit integers. - uint8_t m128_u8[16]; // as unsigned 8-bit integers. - uint16_t m128_u16[8]; // as unsigned 16-bit integers. - uint32_t m128_u32[4]; // as unsigned 32-bit integers. - uint64_t m128_u64[2]; // as unsigned 64-bit integers. -} SIMDVec; - - -// ****************************************** -// Set/get methods -// ****************************************** - -// extracts the lower order floating point value from the parameter : https://msdn.microsoft.com/en-us/library/bb514059%28v=vs.120%29.aspx?f=255&MSPPError=-2147217396 -FORCE_INLINE float _mm_cvtss_f32(__m128 a) -{ - return vgetq_lane_f32(vreinterpretq_f32_m128(a), 0); -} - -// Sets the 128-bit value to zero https://msdn.microsoft.com/en-us/library/vstudio/ys7dw0kh(v=vs.100).aspx -FORCE_INLINE __m128i _mm_setzero_si128() -{ - return vreinterpretq_m128i_s32(vdupq_n_s32(0)); -} - -// Clears the four single-precision, floating-point values. https://msdn.microsoft.com/en-us/library/vstudio/tk1t2tbz(v=vs.100).aspx -FORCE_INLINE __m128 _mm_setzero_ps(void) -{ - return vreinterpretq_m128_f32(vdupq_n_f32(0)); -} - -// Sets the four single-precision, floating-point values to w. https://msdn.microsoft.com/en-us/library/vstudio/2x1se8ha(v=vs.100).aspx -FORCE_INLINE __m128 _mm_set1_ps(float _w) -{ - return vreinterpretq_m128_f32(vdupq_n_f32(_w)); -} - -// Sets the four single-precision, floating-point values to w. https://msdn.microsoft.com/en-us/library/vstudio/2x1se8ha(v=vs.100).aspx -FORCE_INLINE __m128 _mm_set_ps1(float _w) -{ - return vreinterpretq_m128_f32(vdupq_n_f32(_w)); -} - -// Sets the four single-precision, floating-point values to the four inputs. https://msdn.microsoft.com/en-us/library/vstudio/afh0zf75(v=vs.100).aspx -FORCE_INLINE __m128 _mm_set_ps(float w, float z, float y, float x) -{ - float __attribute__((aligned(16))) data[4] = { x, y, z, w }; - return vreinterpretq_m128_f32(vld1q_f32(data)); -} - -// Sets the four single-precision, floating-point values to the four inputs in reverse order. https://msdn.microsoft.com/en-us/library/vstudio/d2172ct3(v=vs.100).aspx -FORCE_INLINE __m128 _mm_setr_ps(float w, float z , float y , float x ) -{ - float __attribute__ ((aligned (16))) data[4] = { w, z, y, x }; - return vreinterpretq_m128_f32(vld1q_f32(data)); -} - - -//added by hasindu -//Sets the 4 signed 32-bit integer values in reverse order https://technet.microsoft.com/en-us/library/security/27yb3ee5(v=vs.90).aspx -FORCE_INLINE __m128i _mm_setr_epi32(int i3, int i2, int i1, int i0) -{ - int32_t __attribute__((aligned(16))) data[4] = { i3, i2, i1, i0 }; - return vreinterpretq_m128i_s32(vld1q_s32(data)); -} - -//following added by hasindu -//Sets the 16 signed 8-bit integer values to b.https://msdn.microsoft.com/en-us/library/6e14xhyf(v=vs.100).aspx -FORCE_INLINE __m128i _mm_set1_epi8(char w) -{ - return vreinterpretq_m128i_s8(vdupq_n_s8(w)); -} - - -//following added by hasindu -//Sets the 8 signed 16-bit integer values to w. https://msdn.microsoft.com/en-us/library/k0ya3x0e(v=vs.90).aspx -FORCE_INLINE __m128i _mm_set1_epi16(short w) -{ - return vreinterpretq_m128i_s16(vdupq_n_s16(w)); -} - -//following added by hasindu -//Sets the 8 signed 16-bit integer values. https://msdn.microsoft.com/en-au/library/3e0fek84(v=vs.90).aspx -FORCE_INLINE __m128i _mm_set_epi16(short i7, short i6, short i5, short i4, short i3, short i2, short i1, short i0) -{ - int16_t __attribute__((aligned(16))) data[8] = { i0, i1, i2, i3, i4, i5, i6, i7 }; - return vreinterpretq_m128i_s16(vld1q_s16(data)); -} - - -// Sets the 4 signed 32-bit integer values to i. https://msdn.microsoft.com/en-us/library/vstudio/h4xscxat(v=vs.100).aspx -FORCE_INLINE __m128i _mm_set1_epi32(int _i) -{ - return vreinterpretq_m128i_s32(vdupq_n_s32(_i)); -} - -// Sets the 4 signed 32-bit integer values. https://msdn.microsoft.com/en-us/library/vstudio/019beekt(v=vs.100).aspx -FORCE_INLINE __m128i _mm_set_epi32(int i3, int i2, int i1, int i0) -{ - int32_t __attribute__((aligned(16))) data[4] = { i0, i1, i2, i3 }; - return vreinterpretq_m128i_s32(vld1q_s32(data)); -} - -// Stores four single-precision, floating-point values. https://msdn.microsoft.com/en-us/library/vstudio/s3h4ay6y(v=vs.100).aspx -FORCE_INLINE void _mm_store_ps(float *p, __m128 a) -{ - vst1q_f32(p, vreinterpretq_f32_m128(a)); -} - -// Stores four single-precision, floating-point values. https://msdn.microsoft.com/en-us/library/44e30x22(v=vs.100).aspx -FORCE_INLINE void _mm_storeu_ps(float *p, __m128 a) -{ - vst1q_f32(p, vreinterpretq_f32_m128(a)); -} - -// Stores four 32-bit integer values as (as a __m128i value) at the address p. https://msdn.microsoft.com/en-us/library/vstudio/edk11s13(v=vs.100).aspx -FORCE_INLINE void _mm_store_si128(__m128i *p, __m128i a) -{ - vst1q_s32((int32_t*) p, vreinterpretq_s32_m128i(a)); -} - -//added by hasindu (verify this for requirement of alignment) -// Stores four 32-bit integer values as (as a __m128i value) at the address p. https://msdn.microsoft.com/en-us/library/vstudio/edk11s13(v=vs.100).aspx -FORCE_INLINE void _mm_storeu_si128(__m128i *p, __m128i a) -{ - vst1q_s32((int32_t*) p, vreinterpretq_s32_m128i(a)); -} - -// Stores the lower single - precision, floating - point value. https://msdn.microsoft.com/en-us/library/tzz10fbx(v=vs.100).aspx -FORCE_INLINE void _mm_store_ss(float *p, __m128 a) -{ - vst1q_lane_f32(p, vreinterpretq_f32_m128(a), 0); -} - -// Reads the lower 64 bits of b and stores them into the lower 64 bits of a. https://msdn.microsoft.com/en-us/library/hhwf428f%28v=vs.90%29.aspx -FORCE_INLINE void _mm_storel_epi64(__m128i* a, __m128i b) -{ - uint64x1_t hi = vget_high_u64(vreinterpretq_u64_m128i(*a)); - uint64x1_t lo = vget_low_u64(vreinterpretq_u64_m128i(b)); - *a = vreinterpretq_m128i_u64(vcombine_u64(lo, hi)); -} - -// Stores the lower two single-precision floating point values of a to the address p. https://msdn.microsoft.com/en-us/library/h54t98ks(v=vs.90).aspx -FORCE_INLINE void _mm_storel_pi(__m64* p, __m128 a) -{ - *p = vget_low_f32(a); -} - -// Loads a single single-precision, floating-point value, copying it into all four words https://msdn.microsoft.com/en-us/library/vstudio/5cdkf716(v=vs.100).aspx -FORCE_INLINE __m128 _mm_load1_ps(const float * p) -{ - return vreinterpretq_m128_f32(vld1q_dup_f32(p)); -} -#define _mm_load_ps1 _mm_load1_ps - -// Sets the lower two single-precision, floating-point values with 64 -// bits of data loaded from the address p; the upper two values are passed -// through from a. https://msdn.microsoft.com/en-us/library/s57cyak2(v=vs.100).aspx -FORCE_INLINE __m128 _mm_loadl_pi(__m128 a,__m64 const *b) - { - return vreinterpretq_m128_f32(vcombine_f32(vld1_f32((const float32_t*)b),vget_high_f32(a))); - } - -// Loads four single-precision, floating-point values. https://msdn.microsoft.com/en-us/library/vstudio/zzd50xxt(v=vs.100).aspx -FORCE_INLINE __m128 _mm_load_ps(const float * p) -{ - return vreinterpretq_m128_f32(vld1q_f32(p)); -} - -// Loads four single-precision, floating-point values. https://msdn.microsoft.com/en-us/library/x1b16s7z%28v=vs.90%29.aspx -FORCE_INLINE __m128 _mm_loadu_ps(const float * p) -{ - // for neon, alignment doesn't matter, so _mm_load_ps and _mm_loadu_ps are equivalent for neon - return vreinterpretq_m128_f32(vld1q_f32(p)); -} - -// Loads an single - precision, floating - point value into the low word and clears the upper three words. https://msdn.microsoft.com/en-us/library/548bb9h4%28v=vs.90%29.aspx -FORCE_INLINE __m128 _mm_load_ss(const float * p) -{ - return vreinterpretq_m128_f32(vsetq_lane_f32(*p, vdupq_n_f32(0), 0)); -} - - -// ****************************************** -// Logic/Binary operations -// ****************************************** - -// Compares for inequality. https://msdn.microsoft.com/en-us/library/sf44thbx(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cmpneq_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_u32( vmvnq_u32( vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)) ) ); -} - -// Computes the bitwise AND-NOT of the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/68h7wd02(v=vs.100).aspx -FORCE_INLINE __m128 _mm_andnot_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_s32( vbicq_s32(vreinterpretq_s32_m128(b), vreinterpretq_s32_m128(a)) ); // *NOTE* argument swap -} - -// Computes the bitwise AND of the 128-bit value in b and the bitwise NOT of the 128-bit value in a. https://msdn.microsoft.com/en-us/library/vstudio/1beaceh8(v=vs.100).aspx -FORCE_INLINE __m128i _mm_andnot_si128(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s32( vbicq_s32(vreinterpretq_s32_m128i(b), vreinterpretq_s32_m128i(a)) ); // *NOTE* argument swap -} - -// Computes the bitwise AND of the 128-bit value in a and the 128-bit value in b. https://msdn.microsoft.com/en-us/library/vstudio/6d1txsa8(v=vs.100).aspx -FORCE_INLINE __m128i _mm_and_si128(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s32( vandq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b)) ); -} - -// Computes the bitwise AND of the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/73ck1xc5(v=vs.100).aspx -FORCE_INLINE __m128 _mm_and_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_s32( vandq_s32(vreinterpretq_s32_m128(a), vreinterpretq_s32_m128(b)) ); -} - -// Computes the bitwise OR of the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/7ctdsyy0(v=vs.100).aspx -FORCE_INLINE __m128 _mm_or_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_s32( vorrq_s32(vreinterpretq_s32_m128(a), vreinterpretq_s32_m128(b)) ); -} - -// Computes bitwise EXOR (exclusive-or) of the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/ss6k3wk8(v=vs.100).aspx -FORCE_INLINE __m128 _mm_xor_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_s32( veorq_s32(vreinterpretq_s32_m128(a), vreinterpretq_s32_m128(b)) ); -} - -// Computes the bitwise OR of the 128-bit value in a and the 128-bit value in b. https://msdn.microsoft.com/en-us/library/vstudio/ew8ty0db(v=vs.100).aspx -FORCE_INLINE __m128i _mm_or_si128(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s32( vorrq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b)) ); -} - -// Computes the bitwise XOR of the 128-bit value in a and the 128-bit value in b. https://msdn.microsoft.com/en-us/library/fzt08www(v=vs.100).aspx -FORCE_INLINE __m128i _mm_xor_si128(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s32( veorq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b)) ); -} - -// NEON does not provide this method -// Creates a 4-bit mask from the most significant bits of the four single-precision, floating-point values. https://msdn.microsoft.com/en-us/library/vstudio/4490ys29(v=vs.100).aspx -FORCE_INLINE int _mm_movemask_ps(__m128 a) -{ -#if ENABLE_CPP_VERSION // I am not yet convinced that the NEON version is faster than the C version of this - uint32x4_t &ia = *(uint32x4_t *)&a; - return (ia[0] >> 31) | ((ia[1] >> 30) & 2) | ((ia[2] >> 29) & 4) | ((ia[3] >> 28) & 8); -#else - static const uint32x4_t movemask = { 1, 2, 4, 8 }; - static const uint32x4_t highbit = { 0x80000000, 0x80000000, 0x80000000, 0x80000000 }; - uint32x4_t t0 = vreinterpretq_u32_m128(a); - uint32x4_t t1 = vtstq_u32(t0, highbit); - uint32x4_t t2 = vandq_u32(t1, movemask); - uint32x2_t t3 = vorr_u32(vget_low_u32(t2), vget_high_u32(t2)); - return vget_lane_u32(t3, 0) | vget_lane_u32(t3, 1); -#endif -} - -// Takes the upper 64 bits of a and places it in the low end of the result -// Takes the lower 64 bits of b and places it into the high end of the result. -FORCE_INLINE __m128 _mm_shuffle_ps_1032(__m128 a, __m128 b) -{ - float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a)); - float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_f32(vcombine_f32(a32, b10)); -} - -// takes the lower two 32-bit values from a and swaps them and places in high end of result -// takes the higher two 32 bit values from b and swaps them and places in low end of result. -FORCE_INLINE __m128 _mm_shuffle_ps_2301(__m128 a, __m128 b) -{ - float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); - float32x2_t b23 = vrev64_f32(vget_high_f32(vreinterpretq_f32_m128(b))); - return vreinterpretq_m128_f32(vcombine_f32(a01, b23)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_0321(__m128 a, __m128 b) -{ - float32x2_t a21 = vget_high_f32(vextq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a), 3)); - float32x2_t b03 = vget_low_f32(vextq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b), 3)); - return vreinterpretq_m128_f32(vcombine_f32(a21, b03)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_2103(__m128 a, __m128 b) -{ - float32x2_t a03 = vget_low_f32(vextq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a), 3)); - float32x2_t b21 = vget_high_f32(vextq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b), 3)); - return vreinterpretq_m128_f32(vcombine_f32(a03, b21)); -} - -FORCE_INLINE __m128 _mm_movelh_ps(__m128 a, __m128 b) -{ - float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); - float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_f32(vcombine_f32(a10, b10)); -} - -FORCE_INLINE __m128 _mm_movehl_ps(__m128 a, __m128 b) -{ - float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a)); - float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_f32(vcombine_f32(b32, a32)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_1001(__m128 a, __m128 b) -{ - float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); - float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_f32(vcombine_f32(a01, b10)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_0101(__m128 a, __m128 b) -{ - float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); - float32x2_t b01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(b))); - return vreinterpretq_m128_f32(vcombine_f32(a01, b01)); -} - -// keeps the low 64 bits of b in the low and puts the high 64 bits of a in the high -FORCE_INLINE __m128 _mm_shuffle_ps_3210(__m128 a, __m128 b) -{ - float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); - float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_f32(vcombine_f32(a10, b32)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_0011(__m128 a, __m128 b) -{ - float32x2_t a11 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(a)), 1); - float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); - return vreinterpretq_m128_f32(vcombine_f32(a11, b00)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_0022(__m128 a, __m128 b) -{ - float32x2_t a22 = vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(a)), 0); - float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); - return vreinterpretq_m128_f32(vcombine_f32(a22, b00)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_2200(__m128 a, __m128 b) -{ - float32x2_t a00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(a)), 0); - float32x2_t b22 = vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(b)), 0); - return vreinterpretq_m128_f32(vcombine_f32(a00, b22)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_3202(__m128 a, __m128 b) -{ - float32_t a0 = vgetq_lane_f32(vreinterpretq_f32_m128(a), 0); - float32x2_t a22 = vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(a)), 0); - float32x2_t a02 = vset_lane_f32(a0, a22, 1); /* apoty: TODO: use vzip ?*/ - float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_f32(vcombine_f32(a02, b32)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_1133(__m128 a, __m128 b) -{ - float32x2_t a33 = vdup_lane_f32(vget_high_f32(vreinterpretq_f32_m128(a)), 1); - float32x2_t b11 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 1); - return vreinterpretq_m128_f32(vcombine_f32(a33, b11)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_2010(__m128 a, __m128 b) -{ - float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); - float32_t b2 = vgetq_lane_f32(vreinterpretq_f32_m128(b), 2); - float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); - float32x2_t b20 = vset_lane_f32(b2, b00, 1); - return vreinterpretq_m128_f32(vcombine_f32(a10, b20)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_2001(__m128 a, __m128 b) -{ - float32x2_t a01 = vrev64_f32(vget_low_f32(vreinterpretq_f32_m128(a))); - float32_t b2 = vgetq_lane_f32(b, 2); - float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); - float32x2_t b20 = vset_lane_f32(b2, b00, 1); - return vreinterpretq_m128_f32(vcombine_f32(a01, b20)); -} - -FORCE_INLINE __m128 _mm_shuffle_ps_2032(__m128 a, __m128 b) -{ - float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a)); - float32_t b2 = vgetq_lane_f32(b, 2); - float32x2_t b00 = vdup_lane_f32(vget_low_f32(vreinterpretq_f32_m128(b)), 0); - float32x2_t b20 = vset_lane_f32(b2, b00, 1); - return vreinterpretq_m128_f32(vcombine_f32(a32, b20)); -} - -// NEON does not support a general purpose permute intrinsic -// Currently I am not sure whether the C implementation is faster or slower than the NEON version. -// Note, this has to be expanded as a template because the shuffle value must be an immediate value. -// The same is true on SSE as well. -// Selects four specific single-precision, floating-point values from a and b, based on the mask i. https://msdn.microsoft.com/en-us/library/vstudio/5f0858x0(v=vs.100).aspx -#if ENABLE_CPP_VERSION // I am not convinced that the NEON version is faster than the C version yet. -FORCE_INLINE __m128 _mm_shuffle_ps_default(__m128 a, __m128 b, __constrange(0,255) int imm) -{ - __m128 ret; - ret[0] = a[imm & 0x3]; - ret[1] = a[(imm >> 2) & 0x3]; - ret[2] = b[(imm >> 4) & 0x03]; - ret[3] = b[(imm >> 6) & 0x03]; - return ret; -} -#else -#define _mm_shuffle_ps_default(a, b, imm) \ -({ \ - float32x4_t ret_; \ - ret_ = vmovq_n_f32(vgetq_lane_f32(vreinterpretq_f32_m128(a), (imm) & 0x3)); \ - ret_ = vsetq_lane_f32(vgetq_lane_f32(vreinterpretq_f32_m128(a), ((imm) >> 2) & 0x3), ret_, 1); \ - ret_ = vsetq_lane_f32(vgetq_lane_f32(vreinterpretq_f32_m128(b), ((imm) >> 4) & 0x3), ret_, 2); \ - ret_ = vsetq_lane_f32(vgetq_lane_f32(vreinterpretq_f32_m128(b), ((imm) >> 6) & 0x3), ret_, 3); \ - vreinterpretq_m128_f32(ret_); \ -}) -#endif - -//FORCE_INLINE __m128 _mm_shuffle_ps(__m128 a, __m128 b, __constrange(0,255) int imm) -#define _mm_shuffle_ps(a, b, imm) \ -({ \ - __m128 ret; \ - switch (imm) \ - { \ - case _MM_SHUFFLE(1, 0, 3, 2): ret = _mm_shuffle_ps_1032((a), (b)); break; \ - case _MM_SHUFFLE(2, 3, 0, 1): ret = _mm_shuffle_ps_2301((a), (b)); break; \ - case _MM_SHUFFLE(0, 3, 2, 1): ret = _mm_shuffle_ps_0321((a), (b)); break; \ - case _MM_SHUFFLE(2, 1, 0, 3): ret = _mm_shuffle_ps_2103((a), (b)); break; \ - case _MM_SHUFFLE(1, 0, 1, 0): ret = _mm_movelh_ps ((a), (b)); break; \ - case _MM_SHUFFLE(1, 0, 0, 1): ret = _mm_shuffle_ps_1001((a), (b)); break; \ - case _MM_SHUFFLE(0, 1, 0, 1): ret = _mm_shuffle_ps_0101((a), (b)); break; \ - case _MM_SHUFFLE(3, 2, 1, 0): ret = _mm_shuffle_ps_3210((a), (b)); break; \ - case _MM_SHUFFLE(0, 0, 1, 1): ret = _mm_shuffle_ps_0011((a), (b)); break; \ - case _MM_SHUFFLE(0, 0, 2, 2): ret = _mm_shuffle_ps_0022((a), (b)); break; \ - case _MM_SHUFFLE(2, 2, 0, 0): ret = _mm_shuffle_ps_2200((a), (b)); break; \ - case _MM_SHUFFLE(3, 2, 0, 2): ret = _mm_shuffle_ps_3202((a), (b)); break; \ - case _MM_SHUFFLE(3, 2, 3, 2): ret = _mm_movehl_ps ((b), (a)); break; \ - case _MM_SHUFFLE(1, 1, 3, 3): ret = _mm_shuffle_ps_1133((a), (b)); break; \ - case _MM_SHUFFLE(2, 0, 1, 0): ret = _mm_shuffle_ps_2010((a), (b)); break; \ - case _MM_SHUFFLE(2, 0, 0, 1): ret = _mm_shuffle_ps_2001((a), (b)); break; \ - case _MM_SHUFFLE(2, 0, 3, 2): ret = _mm_shuffle_ps_2032((a), (b)); break; \ - default: ret = _mm_shuffle_ps_default((a), (b), (imm)); break; \ - } \ - ret; \ -}) - -// Takes the upper 64 bits of a and places it in the low end of the result -// Takes the lower 64 bits of a and places it into the high end of the result. -FORCE_INLINE __m128i _mm_shuffle_epi_1032(__m128i a) -{ - int32x2_t a32 = vget_high_s32(vreinterpretq_s32_m128i(a)); - int32x2_t a10 = vget_low_s32(vreinterpretq_s32_m128i(a)); - return vreinterpretq_m128i_s32(vcombine_s32(a32, a10)); -} - -// takes the lower two 32-bit values from a and swaps them and places in low end of result -// takes the higher two 32 bit values from a and swaps them and places in high end of result. -FORCE_INLINE __m128i _mm_shuffle_epi_2301(__m128i a) -{ - int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); - int32x2_t a23 = vrev64_s32(vget_high_s32(vreinterpretq_s32_m128i(a))); - return vreinterpretq_m128i_s32(vcombine_s32(a01, a23)); -} - -// rotates the least significant 32 bits into the most signficant 32 bits, and shifts the rest down -FORCE_INLINE __m128i _mm_shuffle_epi_0321(__m128i a) -{ - return vreinterpretq_m128i_s32(vextq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(a), 1)); -} - -// rotates the most significant 32 bits into the least signficant 32 bits, and shifts the rest up -FORCE_INLINE __m128i _mm_shuffle_epi_2103(__m128i a) -{ - return vreinterpretq_m128i_s32(vextq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(a), 3)); -} - -// gets the lower 64 bits of a, and places it in the upper 64 bits -// gets the lower 64 bits of a and places it in the lower 64 bits -FORCE_INLINE __m128i _mm_shuffle_epi_1010(__m128i a) -{ - int32x2_t a10 = vget_low_s32(vreinterpretq_s32_m128i(a)); - return vreinterpretq_m128i_s32(vcombine_s32(a10, a10)); -} - -// gets the lower 64 bits of a, swaps the 0 and 1 elements, and places it in the lower 64 bits -// gets the lower 64 bits of a, and places it in the upper 64 bits -FORCE_INLINE __m128i _mm_shuffle_epi_1001(__m128i a) -{ - int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); - int32x2_t a10 = vget_low_s32(vreinterpretq_s32_m128i(a)); - return vreinterpretq_m128i_s32(vcombine_s32(a01, a10)); -} - -// gets the lower 64 bits of a, swaps the 0 and 1 elements and places it in the upper 64 bits -// gets the lower 64 bits of a, swaps the 0 and 1 elements, and places it in the lower 64 bits -FORCE_INLINE __m128i _mm_shuffle_epi_0101(__m128i a) -{ - int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); - return vreinterpretq_m128i_s32(vcombine_s32(a01, a01)); -} - -FORCE_INLINE __m128i _mm_shuffle_epi_2211(__m128i a) -{ - int32x2_t a11 = vdup_lane_s32(vget_low_s32(vreinterpretq_s32_m128i(a)), 1); - int32x2_t a22 = vdup_lane_s32(vget_high_s32(vreinterpretq_s32_m128i(a)), 0); - return vreinterpretq_m128i_s32(vcombine_s32(a11, a22)); -} - -FORCE_INLINE __m128i _mm_shuffle_epi_0122(__m128i a) -{ - int32x2_t a22 = vdup_lane_s32(vget_high_s32(vreinterpretq_s32_m128i(a)), 0); - int32x2_t a01 = vrev64_s32(vget_low_s32(vreinterpretq_s32_m128i(a))); - return vreinterpretq_m128i_s32(vcombine_s32(a22, a01)); -} - -FORCE_INLINE __m128i _mm_shuffle_epi_3332(__m128i a) -{ - int32x2_t a32 = vget_high_s32(vreinterpretq_s32_m128i(a)); - int32x2_t a33 = vdup_lane_s32(vget_high_s32(vreinterpretq_s32_m128i(a)), 1); - return vreinterpretq_m128i_s32(vcombine_s32(a32, a33)); -} - -//FORCE_INLINE __m128i _mm_shuffle_epi32_default(__m128i a, __constrange(0,255) int imm) -#if ENABLE_CPP_VERSION -FORCE_INLINE __m128i _mm_shuffle_epi32_default(__m128i a, __constrange(0,255) int imm) -{ - __m128i ret; - ret[0] = a[imm & 0x3]; - ret[1] = a[(imm >> 2) & 0x3]; - ret[2] = a[(imm >> 4) & 0x03]; - ret[3] = a[(imm >> 6) & 0x03]; - return ret; -} -#else -#define _mm_shuffle_epi32_default(a, imm) \ -({ \ - int32x4_t ret; \ - ret = vmovq_n_s32(vgetq_lane_s32(vreinterpretq_s32_m128i(a), (imm) & 0x3)); \ - ret = vsetq_lane_s32(vgetq_lane_s32(vreinterpretq_s32_m128i(a), ((imm) >> 2) & 0x3), ret, 1); \ - ret = vsetq_lane_s32(vgetq_lane_s32(vreinterpretq_s32_m128i(a), ((imm) >> 4) & 0x3), ret, 2); \ - ret = vsetq_lane_s32(vgetq_lane_s32(vreinterpretq_s32_m128i(a), ((imm) >> 6) & 0x3), ret, 3); \ - vreinterpretq_m128i_s32(ret); \ -}) -#endif - -//FORCE_INLINE __m128i _mm_shuffle_epi32_splat(__m128i a, __constrange(0,255) int imm) -#if defined(__aarch64__) -#define _mm_shuffle_epi32_splat(a, imm) \ -({ \ - vreinterpretq_m128i_s32(vdupq_laneq_s32(vreinterpretq_s32_m128i(a), (imm))); \ -}) -#else -#define _mm_shuffle_epi32_splat(a, imm) \ -({ \ - vreinterpretq_m128i_s32(vdupq_n_s32(vgetq_lane_s32(vreinterpretq_s32_m128i(a), (imm)))); \ -}) -#endif - -// Shuffles the 4 signed or unsigned 32-bit integers in a as specified by imm. https://msdn.microsoft.com/en-us/library/56f67xbk%28v=vs.90%29.aspx -//FORCE_INLINE __m128i _mm_shuffle_epi32(__m128i a, __constrange(0,255) int imm) -#define _mm_shuffle_epi32(a, imm) \ -({ \ - __m128i ret; \ - switch (imm) \ - { \ - case _MM_SHUFFLE(1, 0, 3, 2): ret = _mm_shuffle_epi_1032((a)); break; \ - case _MM_SHUFFLE(2, 3, 0, 1): ret = _mm_shuffle_epi_2301((a)); break; \ - case _MM_SHUFFLE(0, 3, 2, 1): ret = _mm_shuffle_epi_0321((a)); break; \ - case _MM_SHUFFLE(2, 1, 0, 3): ret = _mm_shuffle_epi_2103((a)); break; \ - case _MM_SHUFFLE(1, 0, 1, 0): ret = _mm_shuffle_epi_1010((a)); break; \ - case _MM_SHUFFLE(1, 0, 0, 1): ret = _mm_shuffle_epi_1001((a)); break; \ - case _MM_SHUFFLE(0, 1, 0, 1): ret = _mm_shuffle_epi_0101((a)); break; \ - case _MM_SHUFFLE(2, 2, 1, 1): ret = _mm_shuffle_epi_2211((a)); break; \ - case _MM_SHUFFLE(0, 1, 2, 2): ret = _mm_shuffle_epi_0122((a)); break; \ - case _MM_SHUFFLE(3, 3, 3, 2): ret = _mm_shuffle_epi_3332((a)); break; \ - case _MM_SHUFFLE(0, 0, 0, 0): ret = _mm_shuffle_epi32_splat((a),0); break; \ - case _MM_SHUFFLE(1, 1, 1, 1): ret = _mm_shuffle_epi32_splat((a),1); break; \ - case _MM_SHUFFLE(2, 2, 2, 2): ret = _mm_shuffle_epi32_splat((a),2); break; \ - case _MM_SHUFFLE(3, 3, 3, 3): ret = _mm_shuffle_epi32_splat((a),3); break; \ - default: ret = _mm_shuffle_epi32_default((a), (imm)); break; \ - } \ - ret; \ -}) - -// Shuffles the upper 4 signed or unsigned 16 - bit integers in a as specified by imm. https://msdn.microsoft.com/en-us/library/13ywktbs(v=vs.100).aspx -//FORCE_INLINE __m128i _mm_shufflehi_epi16_function(__m128i a, __constrange(0,255) int imm) -#define _mm_shufflehi_epi16_function(a, imm) \ -({ \ - int16x8_t ret = vreinterpretq_s16_s32(a); \ - int16x4_t highBits = vget_high_s16(ret); \ - ret = vsetq_lane_s16(vget_lane_s16(highBits, (imm) & 0x3), ret, 4); \ - ret = vsetq_lane_s16(vget_lane_s16(highBits, ((imm) >> 2) & 0x3), ret, 5); \ - ret = vsetq_lane_s16(vget_lane_s16(highBits, ((imm) >> 4) & 0x3), ret, 6); \ - ret = vsetq_lane_s16(vget_lane_s16(highBits, ((imm) >> 6) & 0x3), ret, 7); \ - vreinterpretq_s32_s16(ret); \ -}) - -//FORCE_INLINE __m128i _mm_shufflehi_epi16(__m128i a, __constrange(0,255) int imm) -#define _mm_shufflehi_epi16(a, imm) \ - _mm_shufflehi_epi16_function((a), (imm)) - - -//added by hasindu -//Shifts the 8 signed or unsigned 16-bit integers in a left by count bits while shifting in zeros. https://msdn.microsoft.com/en-us/library/es73bcsy(v=vs.90).aspx -#define _mm_slli_epi16(a, imm) \ -({ \ - __m128i ret; \ - if ((imm) <= 0) {\ - ret = a; \ - } \ - else if ((imm) > 31) { \ - ret = _mm_setzero_si128(); \ - } \ - else { \ - ret = vreinterpretq_m128i_s16(vshlq_n_s16(vreinterpretq_s16_m128i(a), (imm))); \ - } \ - ret; \ -}) - - - -// Shifts the 4 signed or unsigned 32-bit integers in a left by count bits while shifting in zeros. : https://msdn.microsoft.com/en-us/library/z2k3bbtb%28v=vs.90%29.aspx -//FORCE_INLINE __m128i _mm_slli_epi32(__m128i a, __constrange(0,255) int imm) -#define _mm_slli_epi32(a, imm) \ -({ \ - __m128i ret; \ - if ((imm) <= 0) {\ - ret = a; \ - } \ - else if ((imm) > 31) { \ - ret = _mm_setzero_si128(); \ - } \ - else { \ - ret = vreinterpretq_m128i_s32(vshlq_n_s32(vreinterpretq_s32_m128i(a), (imm))); \ - } \ - ret; \ -}) - - -//added by hasindu -// Shifts the 8 signed or unsigned 16-bit integers in a right by count bits while shifting in zeros. -//https://msdn.microsoft.com/en-us/library/6tcwd38t(v=vs.90).aspx -#define _mm_srli_epi16(a, imm) \ -({ \ - __m128i ret; \ - if ((imm) <= 0) { \ - ret = a; \ - } \ - else if ((imm)> 31) { \ - ret = _mm_setzero_si128(); \ - } \ - else { \ - ret = vreinterpretq_m128i_u16(vshrq_n_u16(vreinterpretq_u16_m128i(a), (imm))); \ - } \ - ret; \ -}) - - -//Shifts the 4 signed or unsigned 32-bit integers in a right by count bits while shifting in zeros. https://msdn.microsoft.com/en-us/library/w486zcfa(v=vs.100).aspx -//FORCE_INLINE __m128i _mm_srli_epi32(__m128i a, __constrange(0,255) int imm) -#define _mm_srli_epi32(a, imm) \ -({ \ - __m128i ret; \ - if ((imm) <= 0) { \ - ret = a; \ - } \ - else if ((imm)> 31) { \ - ret = _mm_setzero_si128(); \ - } \ - else { \ - ret = vreinterpretq_m128i_u32(vshrq_n_u32(vreinterpretq_u32_m128i(a), (imm))); \ - } \ - ret; \ -}) - -// Shifts the 4 signed 32 - bit integers in a right by count bits while shifting in the sign bit. https://msdn.microsoft.com/en-us/library/z1939387(v=vs.100).aspx -//FORCE_INLINE __m128i _mm_srai_epi32(__m128i a, __constrange(0,255) int imm) -#define _mm_srai_epi32(a, imm) \ -({ \ - __m128i ret; \ - if ((imm) <= 0) { \ - ret = a; \ - } \ - else if ((imm) > 31) { \ - ret = vreinterpretq_m128i_s32(vshrq_n_s32(vreinterpretq_s32_m128i(a), 16)); \ - ret = vreinterpretq_m128i_s32(vshrq_n_s32(vreinterpretq_s32_m128i(ret), 16)); \ - } \ - else { \ - ret = vreinterpretq_m128i_s32(vshrq_n_s32(vreinterpretq_s32_m128i(a), (imm))); \ - } \ - ret; \ -}) - -// Shifts the 128 - bit value in a right by imm bytes while shifting in zeros.imm must be an immediate. https://msdn.microsoft.com/en-us/library/305w28yz(v=vs.100).aspx -//FORCE_INLINE _mm_srli_si128(__m128i a, __constrange(0,255) int imm) -#define _mm_srli_si128(a, imm) \ -({ \ - __m128i ret; \ - if ((imm) <= 0) { \ - ret = a; \ - } \ - else if ((imm) > 15) { \ - ret = _mm_setzero_si128(); \ - } \ - else { \ - ret = vreinterpretq_m128i_s8(vextq_s8(vreinterpretq_s8_m128i(a), vdupq_n_s8(0), (imm))); \ - } \ - ret; \ -}) - -// Shifts the 128-bit value in a left by imm bytes while shifting in zeros. imm must be an immediate. https://msdn.microsoft.com/en-us/library/34d3k2kt(v=vs.100).aspx -//FORCE_INLINE __m128i _mm_slli_si128(__m128i a, __constrange(0,255) int imm) -#define _mm_slli_si128(a, imm) \ -({ \ - __m128i ret; \ - if ((imm) <= 0) { \ - ret = a; \ - } \ - else if ((imm) > 15) { \ - ret = _mm_setzero_si128(); \ - } \ - else { \ - ret = vreinterpretq_m128i_s8(vextq_s8(vdupq_n_s8(0), vreinterpretq_s8_m128i(a), 16 - (imm))); \ - } \ - ret; \ -}) - -// NEON does not provide a version of this function, here is an article about some ways to repro the results. -// http://stackoverflow.com/questions/11870910/sse-mm-movemask-epi8-equivalent-method-for-arm-neon -// Creates a 16-bit mask from the most significant bits of the 16 signed or unsigned 8-bit integers in a and zero extends the upper bits. https://msdn.microsoft.com/en-us/library/vstudio/s090c8fk(v=vs.100).aspx -FORCE_INLINE int _mm_movemask_epi8(__m128i _a) -{ - uint8x16_t input = vreinterpretq_u8_m128i(_a); - static const int8_t __attribute__((aligned(16))) xr[8] = { -7, -6, -5, -4, -3, -2, -1, 0 }; - uint8x8_t mask_and = vdup_n_u8(0x80); - int8x8_t mask_shift = vld1_s8(xr); - - uint8x8_t lo = vget_low_u8(input); - uint8x8_t hi = vget_high_u8(input); - - lo = vand_u8(lo, mask_and); - lo = vshl_u8(lo, mask_shift); - - hi = vand_u8(hi, mask_and); - hi = vshl_u8(hi, mask_shift); - - lo = vpadd_u8(lo, lo); - lo = vpadd_u8(lo, lo); - lo = vpadd_u8(lo, lo); - - hi = vpadd_u8(hi, hi); - hi = vpadd_u8(hi, hi); - hi = vpadd_u8(hi, hi); - - return ((hi[0] << 8) | (lo[0] & 0xFF)); -} - - -// ****************************************** -// Math operations -// ****************************************** - -// Subtracts the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/1zad2k61(v=vs.100).aspx -FORCE_INLINE __m128 _mm_sub_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_f32(vsubq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -// Subtracts the 4 signed or unsigned 32-bit integers of b from the 4 signed or unsigned 32-bit integers of a. https://msdn.microsoft.com/en-us/library/vstudio/fhh866h0(v=vs.100).aspx -FORCE_INLINE __m128i _mm_sub_epi32(__m128i a, __m128i b) -{ - return vreinterpretq_m128_f32(vsubq_s32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -FORCE_INLINE __m128i _mm_sub_epi16(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s16(vsubq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); -} - -//added by hasindu -FORCE_INLINE __m128i _mm_sub_epi8(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s8(vsubq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); -} - -//added by hasindu -//Subtracts the 8 unsigned 16-bit integers of bfrom the 8 unsigned 16-bit integers of a and saturates.. https://technet.microsoft.com/en-us/subscriptions/index/f44y0s19(v=vs.90).aspx -FORCE_INLINE __m128i _mm_subs_epu16(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_u16(vqsubq_u16(vreinterpretq_u16_m128i(a), vreinterpretq_u16_m128i(b))); -} - -//added by hasindu -//Subtracts the 16 unsigned 8-bit integers of b from the 16 unsigned 8-bit integers of a and saturates.. https://technet.microsoft.com/en-us/subscriptions/yadkxc18(v=vs.90) -FORCE_INLINE __m128i _mm_subs_epu8(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_u8(vqsubq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b))); -} - -// Adds the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/c9848chc(v=vs.100).aspx -FORCE_INLINE __m128 _mm_add_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_f32(vaddq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -// adds the scalar single-precision floating point values of a and b. https://msdn.microsoft.com/en-us/library/be94x2y6(v=vs.100).aspx -FORCE_INLINE __m128 _mm_add_ss(__m128 a, __m128 b) -{ - float32_t b0 = vgetq_lane_f32(vreinterpretq_f32_m128(b), 0); - float32x4_t value = vsetq_lane_f32(b0, vdupq_n_f32(0), 0); - //the upper values in the result must be the remnants of . - return vreinterpretq_m128_f32(vaddq_f32(a, value)); -} - -// Adds the 4 signed or unsigned 32-bit integers in a to the 4 signed or unsigned 32-bit integers in b. https://msdn.microsoft.com/en-us/library/vstudio/09xs4fkk(v=vs.100).aspx -FORCE_INLINE __m128i _mm_add_epi32(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s32(vaddq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); -} - -// Adds the 8 signed or unsigned 16-bit integers in a to the 8 signed or unsigned 16-bit integers in b. https://msdn.microsoft.com/en-us/library/fceha5k4(v=vs.100).aspx -FORCE_INLINE __m128i _mm_add_epi16(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s16(vaddq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); -} - -//added by hasindu -// Adds the 16 signed or unsigned 8-bit integers in a to the 16 signed or unsigned 8-bit integers in b. https://technet.microsoft.com/en-us/subscriptions/yc7tcyzs(v=vs.90) -FORCE_INLINE __m128i _mm_add_epi8(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s8(vaddq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); -} - -//added by hasindu -// Adds the 8 signed 16-bit integers in a to the 8 signed 16-bit integers in b and saturates. https://msdn.microsoft.com/en-us/library/1a306ef8(v=vs.100).aspx -FORCE_INLINE __m128i _mm_adds_epi16(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s16(vqaddq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); -} - -//added by hasindu -//Adds the 16 unsigned 8-bit integers in a to the 16 unsigned 8-bit integers in b and saturates.. https://msdn.microsoft.com/en-us/library/9hahyddy(v=vs.100).aspx -FORCE_INLINE __m128i _mm_adds_epu8(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_u8(vqaddq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b))); -} - - -// Multiplies the 8 signed or unsigned 16-bit integers from a by the 8 signed or unsigned 16-bit integers from b. https://msdn.microsoft.com/en-us/library/vstudio/9ks1472s(v=vs.100).aspx -FORCE_INLINE __m128i _mm_mullo_epi16(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s16(vmulq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); -} - -// Multiplies the 4 signed or unsigned 32-bit integers from a by the 4 signed or unsigned 32-bit integers from b. https://msdn.microsoft.com/en-us/library/vstudio/bb531409(v=vs.100).aspx -FORCE_INLINE __m128i _mm_mullo_epi32(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s32(vmulq_s32(vreinterpretq_s32_m128i(a),vreinterpretq_s32_m128i(b))); -} - -// Multiplies the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/22kbk6t9(v=vs.100).aspx -FORCE_INLINE __m128 _mm_mul_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_f32(vmulq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -// Divides the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/edaw8147(v=vs.100).aspx -FORCE_INLINE __m128 _mm_div_ps(__m128 a, __m128 b) -{ - float32x4_t recip0 = vrecpeq_f32(vreinterpretq_f32_m128(b)); - float32x4_t recip1 = vmulq_f32(recip0, vrecpsq_f32(recip0, vreinterpretq_f32_m128(b))); - return vreinterpretq_m128_f32(vmulq_f32(vreinterpretq_f32_m128(a), recip1)); -} - -// Divides the scalar single-precision floating point value of a by b. https://msdn.microsoft.com/en-us/library/4y73xa49(v=vs.100).aspx -FORCE_INLINE __m128 _mm_div_ss(__m128 a, __m128 b) -{ - float32_t value = vgetq_lane_f32(vreinterpretq_f32_m128(_mm_div_ps(a, b)), 0); - return vreinterpretq_m128_f32(vsetq_lane_f32(value, vreinterpretq_f32_m128(a), 0)); -} - -// This version does additional iterations to improve accuracy. Between 1 and 4 recommended. -// Computes the approximations of reciprocals of the four single-precision, floating-point values of a. https://msdn.microsoft.com/en-us/library/vstudio/796k1tty(v=vs.100).aspx -FORCE_INLINE __m128 recipq_newton(__m128 in, int n) -{ - int i; - float32x4_t recip = vrecpeq_f32(vreinterpretq_f32_m128(in)); - for (i = 0; i < n; ++i) - { - recip = vmulq_f32(recip, vrecpsq_f32(recip, vreinterpretq_f32_m128(in))); - } - return vreinterpretq_m128_f32(recip); -} - -// Computes the approximations of reciprocals of the four single-precision, floating-point values of a. https://msdn.microsoft.com/en-us/library/vstudio/796k1tty(v=vs.100).aspx -FORCE_INLINE __m128 _mm_rcp_ps(__m128 in) -{ - float32x4_t recip = vrecpeq_f32(vreinterpretq_f32_m128(in)); - recip = vmulq_f32(recip, vrecpsq_f32(recip, vreinterpretq_f32_m128(in))); - return vreinterpretq_m128_f32(recip); -} - -// Computes the approximations of square roots of the four single-precision, floating-point values of a. First computes reciprocal square roots and then reciprocals of the four values. https://msdn.microsoft.com/en-us/library/vstudio/8z67bwwk(v=vs.100).aspx -FORCE_INLINE __m128 _mm_sqrt_ps(__m128 in) -{ - float32x4_t recipsq = vrsqrteq_f32(vreinterpretq_f32_m128(in)); - float32x4_t sq = vrecpeq_f32(recipsq); - // ??? use step versions of both sqrt and recip for better accuracy? - return vreinterpretq_m128_f32(sq); -} - -// Computes the approximation of the square root of the scalar single-precision floating point value of in. https://msdn.microsoft.com/en-us/library/ahfsc22d(v=vs.100).aspx -FORCE_INLINE __m128 _mm_sqrt_ss(__m128 in) -{ - float32_t value = vgetq_lane_f32(vreinterpretq_f32_m128(_mm_sqrt_ps(in)), 0); - return vreinterpretq_m128_f32(vsetq_lane_f32(value, vreinterpretq_f32_m128(in), 0)); -} - -// Computes the approximations of the reciprocal square roots of the four single-precision floating point values of in. https://msdn.microsoft.com/en-us/library/22hfsh53(v=vs.100).aspx -FORCE_INLINE __m128 _mm_rsqrt_ps(__m128 in) -{ - return vreinterpretq_m128_f32(vrsqrteq_f32(vreinterpretq_f32_m128(in))); -} - -// Computes the maximums of the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/ff5d607a(v=vs.100).aspx -FORCE_INLINE __m128 _mm_max_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_f32(vmaxq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -// Computes the minima of the four single-precision, floating-point values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/wh13kadz(v=vs.100).aspx -FORCE_INLINE __m128 _mm_min_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_f32(vminq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -// Computes the maximum of the two lower scalar single-precision floating point values of a and b. https://msdn.microsoft.com/en-us/library/s6db5esz(v=vs.100).aspx -FORCE_INLINE __m128 _mm_max_ss(__m128 a, __m128 b) -{ - float32_t value = vgetq_lane_f32(vmaxq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)), 0); - return vreinterpretq_m128_f32(vsetq_lane_f32(value, vreinterpretq_f32_m128(a), 0)); -} - -// Computes the minimum of the two lower scalar single-precision floating point values of a and b. https://msdn.microsoft.com/en-us/library/0a9y7xaa(v=vs.100).aspx -FORCE_INLINE __m128 _mm_min_ss(__m128 a, __m128 b) -{ - float32_t value = vgetq_lane_f32(vminq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)), 0); - return vreinterpretq_m128_f32(vsetq_lane_f32(value, vreinterpretq_f32_m128(a), 0)); -} - -//added by hasindu -//Computes the pairwise maxima of the 16 unsigned 8-bit integers from a and the 16 unsigned 8-bit integers from b. https://msdn.microsoft.com/en-us/library/st6634za(v=vs.100).aspx -FORCE_INLINE __m128i _mm_max_epu8(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_u8(vmaxq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b))); -} - -//added by hasindu -//Computes the pairwise minima of the 16 unsigned 8-bit integers from a and the 16 unsigned 8-bit integers from b. https://msdn.microsoft.com/ko-kr/library/17k8cf58(v=vs.100).aspxx -FORCE_INLINE __m128i _mm_min_epu8(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_u8(vminq_u8(vreinterpretq_u8_m128i(a), vreinterpretq_u8_m128i(b))); -} - - -// Computes the pairwise minima of the 8 signed 16-bit integers from a and the 8 signed 16-bit integers from b. https://msdn.microsoft.com/en-us/library/vstudio/6te997ew(v=vs.100).aspx -FORCE_INLINE __m128i _mm_min_epi16(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s16(vminq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); -} - -//added by hasindu -//Computes the pairwise maxima of the 8 signed 16-bit integers from a and the 8 signed 16-bit integers from b. https://msdn.microsoft.com/en-us/LIBRary/3x060h7c(v=vs.100).aspx -FORCE_INLINE __m128i _mm_max_epi16(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s16(vmaxq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); -} - - -// epi versions of min/max -// Computes the pariwise maximums of the four signed 32-bit integer values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/bb514055(v=vs.100).aspx -FORCE_INLINE __m128i _mm_max_epi32(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s32(vmaxq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); -} - -// Computes the pariwise minima of the four signed 32-bit integer values of a and b. https://msdn.microsoft.com/en-us/library/vstudio/bb531476(v=vs.100).aspx -FORCE_INLINE __m128i _mm_min_epi32(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s32(vminq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); -} - -// Multiplies the 8 signed 16-bit integers from a by the 8 signed 16-bit integers from b. https://msdn.microsoft.com/en-us/library/vstudio/59hddw1d(v=vs.100).aspx -FORCE_INLINE __m128i _mm_mulhi_epi16(__m128i a, __m128i b) -{ - /* apoty: issue with large values because of result saturation */ - //int16x8_t ret = vqdmulhq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b)); /* =2*a*b */ - //return vreinterpretq_m128i_s16(vshrq_n_s16(ret, 1)); - int16x4_t a3210 = vget_low_s16(vreinterpretq_s16_m128i(a)); - int16x4_t b3210 = vget_low_s16(vreinterpretq_s16_m128i(b)); - int32x4_t ab3210 = vmull_s16(a3210, b3210); /* 3333222211110000 */ - int16x4_t a7654 = vget_high_s16(vreinterpretq_s16_m128i(a)); - int16x4_t b7654 = vget_high_s16(vreinterpretq_s16_m128i(b)); - int32x4_t ab7654 = vmull_s16(a7654, b7654); /* 7777666655554444 */ - uint16x8x2_t r = vuzpq_u16(vreinterpretq_u16_s32(ab3210), vreinterpretq_u16_s32(ab7654)); - return vreinterpretq_m128i_u16(r.val[1]); -} - -// Computes pairwise add of each argument as single-precision, floating-point values a and b. -//https://msdn.microsoft.com/en-us/library/yd9wecaa.aspx -FORCE_INLINE __m128 _mm_hadd_ps(__m128 a, __m128 b ) -{ -#if defined(__aarch64__) - return vreinterpretq_m128_f32(vpaddq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); //AArch64 -#else - float32x2_t a10 = vget_low_f32(vreinterpretq_f32_m128(a)); - float32x2_t a32 = vget_high_f32(vreinterpretq_f32_m128(a)); - float32x2_t b10 = vget_low_f32(vreinterpretq_f32_m128(b)); - float32x2_t b32 = vget_high_f32(vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_f32(vcombine_f32(vpadd_f32(a10, a32), vpadd_f32(b10, b32))); -#endif -} - -// ****************************************** -// Compare operations -// ****************************************** - -// Compares for less than https://msdn.microsoft.com/en-us/library/vstudio/f330yhc8(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cmplt_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_u32(vcltq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -// Compares for greater than. https://msdn.microsoft.com/en-us/library/vstudio/11dy102s(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cmpgt_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_u32(vcgtq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -// Compares for greater than or equal. https://msdn.microsoft.com/en-us/library/vstudio/fs813y2t(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cmpge_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_u32(vcgeq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -// Compares for less than or equal. https://msdn.microsoft.com/en-us/library/vstudio/1s75w83z(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cmple_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_u32(vcleq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - -// Compares for equality. https://msdn.microsoft.com/en-us/library/vstudio/36aectz5(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cmpeq_ps(__m128 a, __m128 b) -{ - return vreinterpretq_m128_u32(vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); -} - - -//added by hasindu -//Compares the 16 signed or unsigned 8-bit integers in a and the 16 signed or unsigned 8-bit integers in b for equality. https://msdn.microsoft.com/en-us/library/windows/desktop/bz5xk21a(v=vs.90).aspx -FORCE_INLINE __m128i _mm_cmpeq_epi8 (__m128i a, __m128i b) -{ - return vreinterpretq_m128i_u8(vceqq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); -} - -//added by hasindu -//Compares the 8 signed or unsigned 16-bit integers in a and the 8 signed or unsigned 16-bit integers in b for equality. -//https://msdn.microsoft.com/en-us/library/2ay060te(v=vs.100).aspx -FORCE_INLINE __m128i _mm_cmpeq_epi16 (__m128i a, __m128i b) -{ - return vreinterpretq_m128i_u16(vceqq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); -} - -//added by hasindu -//Compares the 16 signed 8-bit integers in a and the 16 signed 8-bit integers in b for lesser than. https://msdn.microsoft.com/en-us/library/windows/desktop/9s46csht(v=vs.90).aspx -FORCE_INLINE __m128i _mm_cmplt_epi8 (__m128i a, __m128i b) -{ - return vreinterpretq_m128i_u8(vcltq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); -} - - -//added by hasindu -//Compares the 16 signed 8-bit integers in a and the 16 signed 8-bit integers in b for greater than. https://msdn.microsoft.com/zh-tw/library/wf45zt2b(v=vs.100).aspx -FORCE_INLINE __m128i _mm_cmpgt_epi8 (__m128i a, __m128i b) -{ - return vreinterpretq_m128i_u8(vcgtq_s8(vreinterpretq_s8_m128i(a), vreinterpretq_s8_m128i(b))); -} - -//added by hasindu -//Compares the 8 signed 16-bit integers in a and the 8 signed 16-bit integers in b for greater than. https://technet.microsoft.com/en-us/library/xd43yfsa(v=vs.100).aspx -FORCE_INLINE __m128i _mm_cmpgt_epi16 (__m128i a, __m128i b) -{ - return vreinterpretq_m128i_u16(vcgtq_s16(vreinterpretq_s16_m128i(a), vreinterpretq_s16_m128i(b))); -} - - -// Compares the 4 signed 32-bit integers in a and the 4 signed 32-bit integers in b for less than. https://msdn.microsoft.com/en-us/library/vstudio/4ak0bf5d(v=vs.100).aspx -FORCE_INLINE __m128i _mm_cmplt_epi32(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_u32(vcltq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); -} - -// Compares the 4 signed 32-bit integers in a and the 4 signed 32-bit integers in b for greater than. https://msdn.microsoft.com/en-us/library/vstudio/1s9f2z0y(v=vs.100).aspx -FORCE_INLINE __m128i _mm_cmpgt_epi32(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_u32(vcgtq_s32(vreinterpretq_s32_m128i(a), vreinterpretq_s32_m128i(b))); -} - -// Compares the four 32-bit floats in a and b to check if any values are NaN. Ordered compare between each value returns true for "orderable" and false for "not orderable" (NaN). https://msdn.microsoft.com/en-us/library/vstudio/0h9w00fx(v=vs.100).aspx -// see also: -// http://stackoverflow.com/questions/8627331/what-does-ordered-unordered-comparison-mean -// http://stackoverflow.com/questions/29349621/neon-isnanval-intrinsics -FORCE_INLINE __m128 _mm_cmpord_ps(__m128 a, __m128 b ) -{ - // Note: NEON does not have ordered compare builtin - // Need to compare a eq a and b eq b to check for NaN - // Do AND of results to get final - uint32x4_t ceqaa = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t ceqbb = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - return vreinterpretq_m128_u32(vandq_u32(ceqaa, ceqbb)); -} - -// Compares the lower single-precision floating point scalar values of a and b using a less than operation. : https://msdn.microsoft.com/en-us/library/2kwe606b(v=vs.90).aspx -// Important note!! The documentation on MSDN is incorrect! If either of the values is a NAN the docs say you will get a one, but in fact, it will return a zero!! -FORCE_INLINE int _mm_comilt_ss(__m128 a, __m128 b) -{ - uint32x4_t a_not_nan = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t b_not_nan = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); - uint32x4_t a_lt_b = vcltq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); - return (vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_lt_b), 0) != 0) ? 1 : 0; -} - -// Compares the lower single-precision floating point scalar values of a and b using a greater than operation. : https://msdn.microsoft.com/en-us/library/b0738e0t(v=vs.100).aspx -FORCE_INLINE int _mm_comigt_ss(__m128 a, __m128 b) -{ - //return vgetq_lane_u32(vcgtq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)), 0); - uint32x4_t a_not_nan = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t b_not_nan = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); - uint32x4_t a_gt_b = vcgtq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); - return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_gt_b), 0) != 0) ? 1 : 0; -} - -// Compares the lower single-precision floating point scalar values of a and b using a less than or equal operation. : https://msdn.microsoft.com/en-us/library/1w4t7c57(v=vs.90).aspx -FORCE_INLINE int _mm_comile_ss(__m128 a, __m128 b) -{ - //return vgetq_lane_u32(vcleq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)), 0); - uint32x4_t a_not_nan = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t b_not_nan = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); - uint32x4_t a_le_b = vcleq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); - return (vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_le_b), 0) != 0) ? 1 : 0; -} - -// Compares the lower single-precision floating point scalar values of a and b using a greater than or equal operation. : https://msdn.microsoft.com/en-us/library/8t80des6(v=vs.100).aspx -FORCE_INLINE int _mm_comige_ss(__m128 a, __m128 b) -{ - //return vgetq_lane_u32(vcgeq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)), 0); - uint32x4_t a_not_nan = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t b_not_nan = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); - uint32x4_t a_ge_b = vcgeq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); - return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_ge_b), 0) != 0) ? 1 : 0; -} - -// Compares the lower single-precision floating point scalar values of a and b using an equality operation. : https://msdn.microsoft.com/en-us/library/93yx2h2b(v=vs.100).aspx -FORCE_INLINE int _mm_comieq_ss(__m128 a, __m128 b) -{ - //return vgetq_lane_u32(vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)), 0); - uint32x4_t a_not_nan = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t b_not_nan = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - uint32x4_t a_or_b_nan = vmvnq_u32(vandq_u32(a_not_nan, b_not_nan)); - uint32x4_t a_eq_b = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)); - return (vgetq_lane_u32(vorrq_u32(a_or_b_nan, a_eq_b), 0) != 0) ? 1 : 0; -} - -// Compares the lower single-precision floating point scalar values of a and b using an inequality operation. : https://msdn.microsoft.com/en-us/library/bafh5e0a(v=vs.90).aspx -FORCE_INLINE int _mm_comineq_ss(__m128 a, __m128 b) -{ - //return !vgetq_lane_u32(vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b)), 0); - uint32x4_t a_not_nan = vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(a)); - uint32x4_t b_not_nan = vceqq_f32(vreinterpretq_f32_m128(b), vreinterpretq_f32_m128(b)); - uint32x4_t a_and_b_not_nan = vandq_u32(a_not_nan, b_not_nan); - uint32x4_t a_neq_b = vmvnq_u32(vceqq_f32(vreinterpretq_f32_m128(a), vreinterpretq_f32_m128(b))); - return (vgetq_lane_u32(vandq_u32(a_and_b_not_nan, a_neq_b), 0) != 0) ? 1 : 0; -} - -// according to the documentation, these intrinsics behave the same as the non-'u' versions. We'll just alias them here. -#define _mm_ucomilt_ss _mm_comilt_ss -#define _mm_ucomile_ss _mm_comile_ss -#define _mm_ucomigt_ss _mm_comigt_ss -#define _mm_ucomige_ss _mm_comige_ss -#define _mm_ucomieq_ss _mm_comieq_ss -#define _mm_ucomineq_ss _mm_comineq_ss - -// ****************************************** -// Conversions -// ****************************************** - -// Converts the four single-precision, floating-point values of a to signed 32-bit integer values using truncate. https://msdn.microsoft.com/en-us/library/vstudio/1h005y6x(v=vs.100).aspx -FORCE_INLINE __m128i _mm_cvttps_epi32(__m128 a) -{ - return vreinterpretq_m128i_s32(vcvtq_s32_f32(vreinterpretq_f32_m128(a))); -} - -// Converts the four signed 32-bit integer values of a to single-precision, floating-point values https://msdn.microsoft.com/en-us/library/vstudio/36bwxcx5(v=vs.100).aspx -FORCE_INLINE __m128 _mm_cvtepi32_ps(__m128i a) -{ - return vreinterpretq_m128_f32(vcvtq_f32_s32(vreinterpretq_s32_m128i(a))); -} - -// Converts the four unsigned 8-bit integers in the lower 32 bits to four unsigned 32-bit integers. https://msdn.microsoft.com/en-us/library/bb531467%28v=vs.100%29.aspx -FORCE_INLINE __m128i _mm_cvtepu8_epi32(__m128i a) -{ - uint8x16_t u8x16 = vreinterpretq_u8_s32(a); /* xxxx xxxx xxxx DCBA */ - uint16x8_t u16x8 = vmovl_u8(vget_low_u8(u8x16)); /* 0x0x 0x0x 0D0C 0B0A */ - uint32x4_t u32x4 = vmovl_u16(vget_low_u16(u16x8)); /* 000D 000C 000B 000A */ - return vreinterpretq_s32_u32(u32x4); -} - -// Converts the four signed 16-bit integers in the lower 64 bits to four signed 32-bit integers. https://msdn.microsoft.com/en-us/library/bb514079%28v=vs.100%29.aspx -FORCE_INLINE __m128i _mm_cvtepi16_epi32(__m128i a) -{ - return vreinterpretq_m128i_s32(vmovl_s16(vget_low_s16(vreinterpretq_s16_m128i(a)))); -} - -// Converts the four single-precision, floating-point values of a to signed 32-bit integer values. https://msdn.microsoft.com/en-us/library/vstudio/xdc42k5e(v=vs.100).aspx -// *NOTE*. The default rounding mode on SSE is 'round to even', which ArmV7 does not support! -// It is supported on ARMv8 however. -FORCE_INLINE __m128i _mm_cvtps_epi32(__m128 a) -{ -#if defined(__aarch64__) - return vcvtnq_s32_f32(a); -#else - uint32x4_t signmask = vdupq_n_u32(0x80000000); - float32x4_t half = vbslq_f32(signmask, vreinterpretq_f32_m128(a), vdupq_n_f32(0.5f)); /* +/- 0.5 */ - int32x4_t r_normal = vcvtq_s32_f32(vaddq_f32(vreinterpretq_f32_m128(a), half)); /* round to integer: [a + 0.5]*/ - int32x4_t r_trunc = vcvtq_s32_f32(vreinterpretq_f32_m128(a)); /* truncate to integer: [a] */ - int32x4_t plusone = vreinterpretq_s32_u32(vshrq_n_u32(vreinterpretq_u32_s32(vnegq_s32(r_trunc)), 31)); /* 1 or 0 */ - int32x4_t r_even = vbicq_s32(vaddq_s32(r_trunc, plusone), vdupq_n_s32(1)); /* ([a] + {0,1}) & ~1 */ - float32x4_t delta = vsubq_f32(vreinterpretq_f32_m128(a), vcvtq_f32_s32(r_trunc)); /* compute delta: delta = (a - [a]) */ - uint32x4_t is_delta_half = vceqq_f32(delta, half); /* delta == +/- 0.5 */ - return vreinterpretq_m128i_s32(vbslq_s32(is_delta_half, r_even, r_normal)); -#endif -} - -// Moves the least significant 32 bits of a to a 32-bit integer. https://msdn.microsoft.com/en-us/library/5z7a9642%28v=vs.90%29.aspx -FORCE_INLINE int _mm_cvtsi128_si32(__m128i a) -{ - return vgetq_lane_s32(vreinterpretq_s32_m128i(a), 0); -} - -// Moves 32-bit integer a to the least significant 32 bits of an __m128 object, zero extending the upper bits. https://msdn.microsoft.com/en-us/library/ct3539ha%28v=vs.90%29.aspx -FORCE_INLINE __m128i _mm_cvtsi32_si128(int a) -{ - return vreinterpretq_m128i_s32(vsetq_lane_s32(a, vdupq_n_s32(0), 0)); -} - - -// Applies a type cast to reinterpret four 32-bit floating point values passed in as a 128-bit parameter as packed 32-bit integers. https://msdn.microsoft.com/en-us/library/bb514099.aspx -FORCE_INLINE __m128i _mm_castps_si128(__m128 a) -{ - return vreinterpretq_m128i_s32(vreinterpretq_s32_m128(a)); -} - -// Applies a type cast to reinterpret four 32-bit integers passed in as a 128-bit parameter as packed 32-bit floating point values. https://msdn.microsoft.com/en-us/library/bb514029.aspx -FORCE_INLINE __m128 _mm_castsi128_ps(__m128i a) -{ - return vreinterpretq_m128_s32(vreinterpretq_s32_m128i(a)); -} - -// Loads 128-bit value. : https://msdn.microsoft.com/en-us/library/atzzad1h(v=vs.80).aspx -FORCE_INLINE __m128i _mm_load_si128(const __m128i *p) -{ - return vreinterpretq_m128i_s32(vld1q_s32((const int32_t *)p)); -} - -//added by hasindu (verify this for requirement of alignment) -// Loads 128-bit value. : https://msdn.microsoft.com/zh-cn/library/f4k12ae8(v=vs.90).aspx -FORCE_INLINE __m128i _mm_loadu_si128(const __m128i *p) -{ - return vreinterpretq_m128i_s32(vld1q_s32((const int32_t *)p)); -} - - -// ****************************************** -// Miscellaneous Operations -// ****************************************** - -// Packs the 16 signed 16-bit integers from a and b into 8-bit integers and saturates. https://msdn.microsoft.com/en-us/library/k4y4f7w5%28v=vs.90%29.aspx -FORCE_INLINE __m128i _mm_packs_epi16(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s8(vcombine_s8(vqmovn_s16(vreinterpretq_s16_m128i(a)), vqmovn_s16(vreinterpretq_s16_m128i(b)))); -} - -// Packs the 16 signed 16 - bit integers from a and b into 8 - bit unsigned integers and saturates. https://msdn.microsoft.com/en-us/library/07ad1wx4(v=vs.100).aspx -FORCE_INLINE __m128i _mm_packus_epi16(const __m128i a, const __m128i b) -{ - return vreinterpretq_m128i_u8(vcombine_u8(vqmovun_s16(vreinterpretq_s16_m128i(a)), vqmovun_s16(vreinterpretq_s16_m128i(b)))); -} - -// Packs the 8 signed 32-bit integers from a and b into signed 16-bit integers and saturates. https://msdn.microsoft.com/en-us/library/393t56f9%28v=vs.90%29.aspx -FORCE_INLINE __m128i _mm_packs_epi32(__m128i a, __m128i b) -{ - return vreinterpretq_m128i_s16(vcombine_s16(vqmovn_s32(vreinterpretq_s32_m128i(a)), vqmovn_s32(vreinterpretq_s32_m128i(b)))); -} - -// Interleaves the lower 8 signed or unsigned 8-bit integers in a with the lower 8 signed or unsigned 8-bit integers in b. https://msdn.microsoft.com/en-us/library/xf7k860c%28v=vs.90%29.aspx -FORCE_INLINE __m128i _mm_unpacklo_epi8(__m128i a, __m128i b) -{ - int8x8_t a1 = vreinterpret_s8_s16(vget_low_s16(vreinterpretq_s16_m128i(a))); - int8x8_t b1 = vreinterpret_s8_s16(vget_low_s16(vreinterpretq_s16_m128i(b))); - int8x8x2_t result = vzip_s8(a1, b1); - return vreinterpretq_m128i_s8(vcombine_s8(result.val[0], result.val[1])); -} - -// Interleaves the lower 4 signed or unsigned 16-bit integers in a with the lower 4 signed or unsigned 16-bit integers in b. https://msdn.microsoft.com/en-us/library/btxb17bw%28v=vs.90%29.aspx -FORCE_INLINE __m128i _mm_unpacklo_epi16(__m128i a, __m128i b) -{ - int16x4_t a1 = vget_low_s16(vreinterpretq_s16_m128i(a)); - int16x4_t b1 = vget_low_s16(vreinterpretq_s16_m128i(b)); - int16x4x2_t result = vzip_s16(a1, b1); - return vreinterpretq_m128i_s16(vcombine_s16(result.val[0], result.val[1])); -} - -// Interleaves the lower 2 signed or unsigned 32 - bit integers in a with the lower 2 signed or unsigned 32 - bit integers in b. https://msdn.microsoft.com/en-us/library/x8atst9d(v=vs.100).aspx -FORCE_INLINE __m128i _mm_unpacklo_epi32(__m128i a, __m128i b) -{ - int32x2_t a1 = vget_low_s32(vreinterpretq_s32_m128i(a)); - int32x2_t b1 = vget_low_s32(vreinterpretq_s32_m128i(b)); - int32x2x2_t result = vzip_s32(a1, b1); - return vreinterpretq_m128i_s32(vcombine_s32(result.val[0], result.val[1])); -} - -// Selects and interleaves the lower two single-precision, floating-point values from a and b. https://msdn.microsoft.com/en-us/library/25st103b%28v=vs.90%29.aspx -FORCE_INLINE __m128 _mm_unpacklo_ps(__m128 a, __m128 b) -{ - float32x2_t a1 = vget_low_f32(vreinterpretq_f32_m128(a)); - float32x2_t b1 = vget_low_f32(vreinterpretq_f32_m128(b)); - float32x2x2_t result = vzip_f32(a1, b1); - return vreinterpretq_m128_f32(vcombine_f32(result.val[0], result.val[1])); -} - -// Selects and interleaves the upper two single-precision, floating-point values from a and b. https://msdn.microsoft.com/en-us/library/skccxx7d%28v=vs.90%29.aspx -FORCE_INLINE __m128 _mm_unpackhi_ps(__m128 a, __m128 b) -{ - float32x2_t a1 = vget_high_f32(vreinterpretq_f32_m128(a)); - float32x2_t b1 = vget_high_f32(vreinterpretq_f32_m128(b)); - float32x2x2_t result = vzip_f32(a1, b1); - return vreinterpretq_m128_f32(vcombine_f32(result.val[0], result.val[1])); -} - -// Interleaves the upper 8 signed or unsigned 8-bit integers in a with the upper 8 signed or unsigned 8-bit integers in b. https://msdn.microsoft.com/en-us/library/t5h7783k(v=vs.100).aspx -FORCE_INLINE __m128i _mm_unpackhi_epi8(__m128i a, __m128i b) -{ - int8x8_t a1 = vreinterpret_s8_s16(vget_high_s16(vreinterpretq_s16_m128i(a))); - int8x8_t b1 = vreinterpret_s8_s16(vget_high_s16(vreinterpretq_s16_m128i(b))); - int8x8x2_t result = vzip_s8(a1, b1); - return vreinterpretq_m128i_s8(vcombine_s8(result.val[0], result.val[1])); -} - -// Interleaves the upper 4 signed or unsigned 16-bit integers in a with the upper 4 signed or unsigned 16-bit integers in b. https://msdn.microsoft.com/en-us/library/03196cz7(v=vs.100).aspx -FORCE_INLINE __m128i _mm_unpackhi_epi16(__m128i a, __m128i b) -{ - int16x4_t a1 = vget_high_s16(vreinterpretq_s16_m128i(a)); - int16x4_t b1 = vget_high_s16(vreinterpretq_s16_m128i(b)); - int16x4x2_t result = vzip_s16(a1, b1); - return vreinterpretq_m128i_s16(vcombine_s16(result.val[0], result.val[1])); -} - -// Interleaves the upper 2 signed or unsigned 32-bit integers in a with the upper 2 signed or unsigned 32-bit integers in b. https://msdn.microsoft.com/en-us/library/65sa7cbs(v=vs.100).aspx -FORCE_INLINE __m128i _mm_unpackhi_epi32(__m128i a, __m128i b) -{ - int32x2_t a1 = vget_high_s32(vreinterpretq_s32_m128i(a)); - int32x2_t b1 = vget_high_s32(vreinterpretq_s32_m128i(b)); - int32x2x2_t result = vzip_s32(a1, b1); - return vreinterpretq_m128i_s32(vcombine_s32(result.val[0], result.val[1])); -} - -// Extracts the selected signed or unsigned 16-bit integer from a and zero extends. https://msdn.microsoft.com/en-us/library/6dceta0c(v=vs.100).aspx -//FORCE_INLINE int _mm_extract_epi16(__m128i a, __constrange(0,8) int imm) -#define _mm_extract_epi16(a, imm) \ -({ \ - (vgetq_lane_s16(vreinterpretq_s16_m128i(a), (imm)) & 0x0000ffffUL); \ -}) - -// Inserts the least significant 16 bits of b into the selected 16-bit integer of a. https://msdn.microsoft.com/en-us/library/kaze8hz1%28v=vs.100%29.aspx -//FORCE_INLINE __m128i _mm_insert_epi16(__m128i a, const int b, __constrange(0,8) int imm) -#define _mm_insert_epi16(a, b, imm) \ -({ \ - vreinterpretq_m128i_s16(vsetq_lane_s16((b), vreinterpretq_s16_m128i(a), (imm))); \ -}) - -// ****************************************** -// Streaming Extensions -// ****************************************** - -// Guarantees that every preceding store is globally visible before any subsequent store. https://msdn.microsoft.com/en-us/library/5h2w73d1%28v=vs.90%29.aspx -FORCE_INLINE void _mm_sfence(void) -{ - __sync_synchronize(); -} - -// Stores the data in a to the address p without polluting the caches. If the cache line containing address p is already in the cache, the cache will be updated.Address p must be 16 - byte aligned. https://msdn.microsoft.com/en-us/library/ba08y07y%28v=vs.90%29.aspx -FORCE_INLINE void _mm_stream_si128(__m128i *p, __m128i a) -{ - *p = a; -} - -// Cache line containing p is flushed and invalidated from all caches in the coherency domain. : https://msdn.microsoft.com/en-us/library/ba08y07y(v=vs.100).aspx -FORCE_INLINE void _mm_clflush(void const*p) -{ - // no corollary for Neon? -} - -#if defined(__GNUC__) || defined(__clang__) -# pragma pop_macro("ALIGN_STRUCT") -# pragma pop_macro("FORCE_INLINE") -#endif - -#endif diff --git a/OgreMain/src/WIN32/OgreFileSystemLayer.cpp b/OgreMain/src/WIN32/OgreFileSystemLayer.cpp deleted file mode 100644 index 0ada83fe165..00000000000 --- a/OgreMain/src/WIN32/OgreFileSystemLayer.cpp +++ /dev/null @@ -1,188 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#include "OgreStableHeaders.h" -#include "OgreFileSystemLayer.h" -#define WIN32_LEAN_AND_MEAN -#include -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 -# include -#endif -#include -#include - -namespace Ogre -{ - static bool widePathToOgreString(String& dest, const WCHAR* wpath) - { - // need to convert to narrow (OEM or ANSI) codepage so that fstream can use it - // properly on international systems. -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - // Note, that on legacy CRT versions codepage for narrow CRT file functions can be changed using - // SetFileApisANSI/OEM, but on modern runtimes narrow pathes are always widened using ANSI codepage. - // We suppose that on such runtimes file APIs codepage is left in default, ANSI state. - UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP; -#elif OGRE_PLATFORM == OGRE_PLATFORM_WINRT - // Runtime is modern, narrow calls are widened inside CRT using CP_ACP codepage. - UINT codepage = CP_ACP; -#endif - const int wlength = static_cast(wcslen(wpath)); - const int length = WideCharToMultiByte(codepage, 0 /* Use default flags */, wpath, wlength, NULL, 0, NULL, NULL); - if(length <= 0) - { - dest.clear(); - return false; - } - - // success - dest.resize(length); - WideCharToMultiByte(codepage, 0 /* Use default flags */, wpath, wlength, &dest[0], (int)dest.size(), NULL, NULL); - return true; - } - - static String getModulePath(bool dllpath) - { - HMODULE hm = NULL; - - // get path of this DLL - if (dllpath && !GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | - GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, - (LPCSTR)&getModulePath, &hm)) - { - return ""; - } - - DWORD bufsize = 256; - char* resolved = 0; - do - { - char* buf = OGRE_ALLOC_T(char, bufsize, Ogre::MEMCATEGORY_GENERAL); - DWORD retval = GetModuleFileName(hm, buf, bufsize); - if (retval == 0) - { - // failed - OGRE_FREE(buf, Ogre::MEMCATEGORY_GENERAL); - break; - } - - if (retval < bufsize) - { - // operation was successful. - resolved = buf; - } - else - { - // buffer was too small, grow buffer and try again - OGRE_FREE(buf, Ogre::MEMCATEGORY_GENERAL); - bufsize <<= 1; - } - } while (!resolved); - - String ret = resolved; - OGRE_FREE(resolved, Ogre::MEMCATEGORY_GENERAL); - - // need to strip the module filename from the path - String::size_type pos = ret.rfind('\\'); - if (pos != String::npos) - ret.erase(pos); - - return ret; - } - - String FileSystemLayer::resolveBundlePath(String path) - { - return path; - } - void FileSystemLayer::getConfigPaths() - { -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - // try to determine the application's path - String appPath = getModulePath(false); -#elif OGRE_PLATFORM == OGRE_PLATFORM_WINRT - Ogre::String appPath; - widePathToOgreString(appPath, Windows::ApplicationModel::Package::Current->InstalledLocation->Path->Data()); -#endif - - // use application path as config search path - if (!appPath.empty()) - mConfigPaths.push_back(appPath + '\\'); -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - // look relative to the DLL according to PIP structure - mConfigPaths.push_back(StringUtil::normalizeFilePath(getModulePath(true)+"/../../../bin/")); -#endif - } - //--------------------------------------------------------------------- - void FileSystemLayer::prepareUserHome(const Ogre::String& subdir) - { - // fill mHomePath -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - WCHAR wpath[MAX_PATH]; - if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PERSONAL|CSIDL_FLAG_CREATE, NULL, 0, wpath))) - widePathToOgreString(mHomePath, wpath); -#elif OGRE_PLATFORM == OGRE_PLATFORM_WINRT - widePathToOgreString(mHomePath, Windows::Storage::ApplicationData::Current->LocalFolder->Path->Data()); -#endif - - if(!mHomePath.empty()) - { - mHomePath += '\\' + subdir + '\\'; - // create release subdir - if (!createDirectory(mHomePath)) - { - // couldn't create directory, fall back to current working dir - mHomePath.clear(); - } - } - } - //--------------------------------------------------------------------- - bool FileSystemLayer::fileExists(const Ogre::String& path) - { - return _access(path.c_str(), 04) == 0; // Use CRT API rather than GetFileAttributesExA to pass Windows Store validation - } - //--------------------------------------------------------------------- - bool FileSystemLayer::createDirectory(const Ogre::String& path) - { - return !_mkdir(path.c_str()) || errno == EEXIST; // Use CRT API rather than CreateDirectoryA to pass Windows Store validation - } - //--------------------------------------------------------------------- - bool FileSystemLayer::removeDirectory(const Ogre::String& path) - { - return !_rmdir(path.c_str()) || errno == ENOENT; // Use CRT API to pass Windows Store validation - } - //--------------------------------------------------------------------- - bool FileSystemLayer::removeFile(const Ogre::String& path) - { - return !_unlink(path.c_str()) || errno == ENOENT; // Use CRT API to pass Windows Store validation - } - //--------------------------------------------------------------------- - bool FileSystemLayer::renameFile(const Ogre::String& oldname, const Ogre::String& newname) - { - if(fileExists(oldname) && fileExists(newname)) - removeFile(newname); - return !rename(oldname.c_str(), newname.c_str()); // Use CRT API to pass Windows Store validation - } -} diff --git a/OgreMain/src/iOS/OgreFileSystemLayer.mm b/OgreMain/src/iOS/OgreFileSystemLayer.mm deleted file mode 100644 index 84776eb91b2..00000000000 --- a/OgreMain/src/iOS/OgreFileSystemLayer.mm +++ /dev/null @@ -1,90 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#include "OgreFileSystemLayer.h" -#include "macUtils.h" -#import -#import - -namespace Ogre -{ - String FileSystemLayer::resolveBundlePath(String path) - { - if(!path.empty() && path[0] != '/') // only adjust relative dirs - path = macBundlePath() + "/" + path; - - return path; - } - - void FileSystemLayer::getConfigPaths() - { - mConfigPaths.push_back(Ogre::iOSDocumentsDirectory() + "/"); - mConfigPaths.push_back(Ogre::macBundlePath() + "/"); - } - //--------------------------------------------------------------------- - void FileSystemLayer::prepareUserHome(const Ogre::String& subdir) - { - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); - - mHomePath = Ogre::String([[paths objectAtIndex:0] cStringUsingEncoding:NSASCIIStringEncoding]) + "/"; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::fileExists(const Ogre::String& path) - { - return access(path.c_str(), R_OK) == 0; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::createDirectory(const Ogre::String& path) - { - NSString *directoryPath = [NSString stringWithCString:path.c_str() encoding:NSUTF8StringEncoding]; - NSError *error; - - if (![[NSFileManager defaultManager] createDirectoryAtPath:directoryPath - withIntermediateDirectories:NO - attributes:nil - error:&error]) - { - return false; - } - return true; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::removeDirectory(const Ogre::String& path) - { - return false; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::removeFile(const Ogre::String& path) - { - return false; - } - //--------------------------------------------------------------------- - bool FileSystemLayer::renameFile(const Ogre::String& oldname, const Ogre::String& newname) - { - return false; - } -} diff --git a/OgreMain/src/iOS/macUtils.h b/OgreMain/src/iOS/macUtils.h deleted file mode 100644 index d113de2791d..00000000000 --- a/OgreMain/src/iOS/macUtils.h +++ /dev/null @@ -1,38 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include -#include "OgrePrerequisites.h" - -namespace Ogre { - void* mac_loadDylib(const char* name); - String macCachePath(); - String macBundlePath(void); - String macTempFileName(void); - String iOSDocumentsDirectory(void); -} diff --git a/OgreMain/src/iOS/macUtils.mm b/OgreMain/src/iOS/macUtils.mm deleted file mode 100644 index c915615d54c..00000000000 --- a/OgreMain/src/iOS/macUtils.mm +++ /dev/null @@ -1,92 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include -#include - -#include "OgreString.h" -#include "macUtils.h" - -namespace Ogre { - - // Basically a dummy function. Dynamic libraries aren't supported on iOS - void* mac_loadDylib(const char* name) - { - return NULL; - } - - String macTempFileName() - { - NSString *tempFilePath; - NSFileManager *fileManager = [NSFileManager defaultManager]; - for (;;) { - NSString *baseName = [NSString stringWithFormat:@"tmp-%x", arc4random()]; - tempFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:baseName]; - if (![fileManager fileExistsAtPath:tempFilePath]) - break; - } - return String([tempFilePath cStringUsingEncoding:NSASCIIStringEncoding]); - } - - String macBundlePath() - { - char path[PATH_MAX]; - CFBundleRef mainBundle = CFBundleGetMainBundle(); - assert(mainBundle); - - CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle); - assert(mainBundleURL); - - CFStringRef cfStringRef = CFURLCopyFileSystemPath( mainBundleURL, kCFURLPOSIXPathStyle); - assert(cfStringRef); - - CFStringGetCString(cfStringRef, path, PATH_MAX, kCFStringEncodingASCII); - - CFRelease(mainBundleURL); - CFRelease(cfStringRef); - - return String(path); - } - - String iOSDocumentsDirectory() - { - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); - NSString *documentsDirectory = [paths objectAtIndex:0]; - - return String([documentsDirectory cStringUsingEncoding:NSASCIIStringEncoding]); - } - - String macCachePath() - { - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); - NSString *cachesDirectory = [paths objectAtIndex:0]; - - return [[cachesDirectory stringByAppendingString:@"/"] cStringUsingEncoding:NSASCIIStringEncoding]; - } - -} diff --git a/OgreMain/src/zip/miniz.h b/OgreMain/src/zip/miniz.h deleted file mode 100644 index 88a5ae8f888..00000000000 --- a/OgreMain/src/zip/miniz.h +++ /dev/null @@ -1,9959 +0,0 @@ -#define MINIZ_EXPORT -/* miniz.c 2.2.0 - public domain deflate/inflate, zlib-subset, ZIP - reading/writing/appending, PNG writing See "unlicense" statement at the end - of this file. Rich Geldreich , last updated Oct. 13, - 2013 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: - http://www.ietf.org/rfc/rfc1951.txt - - Most API's defined in miniz.c are optional. For example, to disable the - archive related functions just define MINIZ_NO_ARCHIVE_APIS, or to get rid of - all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). - - * Low-level Deflate/Inflate implementation notes: - - Compression: Use the "tdefl" API's. The compressor supports raw, static, - and dynamic blocks, lazy or greedy parsing, match length filtering, RLE-only, - and Huffman-only streams. It performs and compresses approximately as well as - zlib. - - Decompression: Use the "tinfl" API's. The entire decompressor is - implemented as a single function coroutine: see tinfl_decompress(). It - supports decompression into a 32KB (or larger power of 2) wrapping buffer, or - into a memory block large enough to hold the entire file. - - The low-level tdefl/tinfl API's do not make any use of dynamic memory - allocation. - - * zlib-style API notes: - - miniz.c implements a fairly large subset of zlib. There's enough - functionality present for it to be a drop-in zlib replacement in many apps: - The z_stream struct, optional memory allocation callbacks - deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound - inflateInit/inflateInit2/inflate/inflateReset/inflateEnd - compress, compress2, compressBound, uncompress - CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly - routines. Supports raw deflate streams or standard zlib streams with adler-32 - checking. - - Limitations: - The callback API's are not implemented yet. No support for gzip headers or - zlib static dictionaries. I've tried to closely emulate zlib's various - flavors of stream flushing and return status codes, but there are no - guarantees that miniz.c pulls this off perfectly. - - * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, - originally written by Alex Evans. Supports 1-4 bytes/pixel images. - - * ZIP archive API notes: - - The ZIP archive API's where designed with simplicity and efficiency in - mind, with just enough abstraction to get the job done with minimal fuss. - There are simple API's to retrieve file information, read files from existing - archives, create new archives, append new files to existing archives, or - clone archive data from one archive to another. It supports archives located - in memory or the heap, on disk (using stdio.h), or you can specify custom - file read/write callbacks. - - - Archive reading: Just call this function to read a single file from a - disk archive: - - void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const - char *pArchive_name, size_t *pSize, mz_uint zip_flags); - - For more complex cases, use the "mz_zip_reader" functions. Upon opening an - archive, the entire central directory is located and read as-is into memory, - and subsequent file access only occurs when reading individual files. - - - Archives file scanning: The simple way is to use this function to scan a - loaded archive for a specific file: - - int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, - const char *pComment, mz_uint flags); - - The locate operation can optionally check file comments too, which (as one - example) can be used to identify multiple versions of the same file in an - archive. This function uses a simple linear search through the central - directory, so it's not very fast. - - Alternately, you can iterate through all the files in an archive (using - mz_zip_reader_get_num_files()) and retrieve detailed info on each file by - calling mz_zip_reader_file_stat(). - - - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer - immediately writes compressed file data to disk and builds an exact image of - the central directory in memory. The central directory image is written all - at once at the end of the archive file when the archive is finalized. - - The archive writer can optionally align each file's local header and file - data to any power of 2 alignment, which can be useful when the archive will - be read from optical media. Also, the writer supports placing arbitrary data - blobs at the very beginning of ZIP archives. Archives written using either - feature are still readable by any ZIP tool. - - - Archive appending: The simple way to add a single file to an archive is - to call this function: - - mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, - const char *pArchive_name, const void *pBuf, size_t buf_size, const void - *pComment, mz_uint16 comment_size, mz_uint level_and_flags); - - The archive will be created if it doesn't already exist, otherwise it'll be - appended to. Note the appending is done in-place and is not an atomic - operation, so if something goes wrong during the operation it's possible the - archive could be left without a central directory (although the local file - headers and file data will be fine, so the archive will be recoverable). - - For more complex archive modification scenarios: - 1. The safest way is to use a mz_zip_reader to read the existing archive, - cloning only those bits you want to preserve into a new archive using using - the mz_zip_writer_add_from_zip_reader() function (which compiles the - compressed file data as-is). When you're done, delete the old archive and - rename the newly written archive, and you're done. This is safe but requires - a bunch of temporary disk space or heap memory. - - 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using - mz_zip_writer_init_from_reader(), append new files as needed, then finalize - the archive which will write an updated central directory to the original - archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() - does.) There's a possibility that the archive's central directory could be - lost with this method if anything goes wrong, though. - - - ZIP archive support limitations: - No spanning support. Extraction functions can only handle unencrypted, - stored or deflated files. Requires streams capable of seeking. - - * This is a header file library, like stb_image.c. To get only a header file, - either cut and paste the below header, or create miniz.h, #define - MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. - - * Important: For best perf. be sure to customize the below macros for your - target platform: #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define - MINIZ_LITTLE_ENDIAN 1 #define MINIZ_HAS_64BIT_REGISTERS 1 - - * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before - including miniz.c to ensure miniz uses the 64-bit variants: fopen64(), - stat64(), etc. Otherwise you won't be able to process large files (i.e. - 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). -*/ -#pragma once - -/* Defines to completely disable specific portions of miniz.c: - If all macros here are defined the only functionality remaining will be - CRC-32, adler-32, tinfl, and tdefl. */ - -/* Define MINIZ_NO_STDIO to disable all usage and any functions which rely on - * stdio for file I/O. */ -/*#define MINIZ_NO_STDIO */ - -/* If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able - * to get the current time, or */ -/* get/set file times, and the C run-time funcs that get/set times won't be - * called. */ -/* The current downside is the times written to your archives will be from 1979. - */ -/*#define MINIZ_NO_TIME */ - -/* Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. */ -/*#define MINIZ_NO_ARCHIVE_APIS */ - -/* Define MINIZ_NO_ARCHIVE_WRITING_APIS to disable all writing related ZIP - * archive API's. */ -/*#define MINIZ_NO_ARCHIVE_WRITING_APIS */ - -/* Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression - * API's. */ -/*#define MINIZ_NO_ZLIB_APIS */ - -/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent - * conflicts against stock zlib. */ -/*#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ - -/* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. - Note if MINIZ_NO_MALLOC is defined then the user must always provide custom - user alloc/free/realloc callbacks to the zlib and archive API's, and a few - stand-alone helper API's which don't provide custom user functions (such as - tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. - */ -/*#define MINIZ_NO_MALLOC */ - -#if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) -/* TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc - * on Linux */ -#define MINIZ_NO_TIME -#endif - -#include - -#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) -#include -#endif - -#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \ - defined(__i386) || defined(__i486__) || defined(__i486) || \ - defined(i386) || defined(__ia64__) || defined(__x86_64__) -/* MINIZ_X86_OR_X64_CPU is only used to help set the below macros. */ -#define MINIZ_X86_OR_X64_CPU 1 -#else -#define MINIZ_X86_OR_X64_CPU 0 -#endif - -#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU -/* Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. */ -#define MINIZ_LITTLE_ENDIAN 1 -#else -#define MINIZ_LITTLE_ENDIAN 0 -#endif - -/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES only if not set */ -#if !defined(MINIZ_USE_UNALIGNED_LOADS_AND_STORES) -#if MINIZ_X86_OR_X64_CPU -/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient - * integer loads and stores from unaligned addresses. */ -#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 -#define MINIZ_UNALIGNED_USE_MEMCPY -#else -#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 -#endif -#endif - -#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \ - defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \ - defined(__x86_64__) -/* Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are - * reasonably fast (and don't involve compiler generated calls to helper - * functions). */ -#define MINIZ_HAS_64BIT_REGISTERS 1 -#else -#define MINIZ_HAS_64BIT_REGISTERS 0 -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/* ------------------- zlib-style API Definitions. */ - -/* For more compatibility with zlib, miniz.c uses unsigned long for some - * parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! */ -typedef unsigned long mz_ulong; - -/* mz_free() internally uses the MZ_FREE() macro (which by default calls free() - * unless you've modified the MZ_MALLOC macro) to release a block allocated from - * the heap. */ -MINIZ_EXPORT void mz_free(void *p); - -#define MZ_ADLER32_INIT (1) -/* mz_adler32() returns the initial adler-32 value to use when called with - * ptr==NULL. */ -MINIZ_EXPORT mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, - size_t buf_len); - -#define MZ_CRC32_INIT (0) -/* mz_crc32() returns the initial CRC-32 value to use when called with - * ptr==NULL. */ -MINIZ_EXPORT mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, - size_t buf_len); - -/* Compression strategies. */ -enum { - MZ_DEFAULT_STRATEGY = 0, - MZ_FILTERED = 1, - MZ_HUFFMAN_ONLY = 2, - MZ_RLE = 3, - MZ_FIXED = 4 -}; - -/* Method */ -#define MZ_DEFLATED 8 - -/* Heap allocation callbacks. -Note that mz_alloc_func parameter types purposely differ from zlib's: items/size -is size_t, not unsigned long. */ -typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); -typedef void (*mz_free_func)(void *opaque, void *address); -typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, - size_t size); - -/* Compression levels: 0-9 are the standard zlib-style levels, 10 is best - * possible compression (not zlib compatible, and may be very slow), - * MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. */ -enum { - MZ_NO_COMPRESSION = 0, - MZ_BEST_SPEED = 1, - MZ_BEST_COMPRESSION = 9, - MZ_UBER_COMPRESSION = 10, - MZ_DEFAULT_LEVEL = 6, - MZ_DEFAULT_COMPRESSION = -1 -}; - -#define MZ_VERSION "10.2.0" -#define MZ_VERNUM 0xA100 -#define MZ_VER_MAJOR 10 -#define MZ_VER_MINOR 2 -#define MZ_VER_REVISION 0 -#define MZ_VER_SUBREVISION 0 - -#ifndef MINIZ_NO_ZLIB_APIS - -/* Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The - * other values are for advanced use (refer to the zlib docs). */ -enum { - MZ_NO_FLUSH = 0, - MZ_PARTIAL_FLUSH = 1, - MZ_SYNC_FLUSH = 2, - MZ_FULL_FLUSH = 3, - MZ_FINISH = 4, - MZ_BLOCK = 5 -}; - -/* Return status codes. MZ_PARAM_ERROR is non-standard. */ -enum { - MZ_OK = 0, - MZ_STREAM_END = 1, - MZ_NEED_DICT = 2, - MZ_ERRNO = -1, - MZ_STREAM_ERROR = -2, - MZ_DATA_ERROR = -3, - MZ_MEM_ERROR = -4, - MZ_BUF_ERROR = -5, - MZ_VERSION_ERROR = -6, - MZ_PARAM_ERROR = -10000 -}; - -/* Window bits */ -#define MZ_DEFAULT_WINDOW_BITS 15 - -struct mz_internal_state; - -/* Compression/decompression stream struct. */ -typedef struct mz_stream_s { - const unsigned char *next_in; /* pointer to next byte to read */ - unsigned int avail_in; /* number of bytes available at next_in */ - mz_ulong total_in; /* total number of bytes consumed so far */ - - unsigned char *next_out; /* pointer to next byte to write */ - unsigned int avail_out; /* number of bytes that can be written to next_out */ - mz_ulong total_out; /* total number of bytes produced so far */ - - char *msg; /* error msg (unused) */ - struct mz_internal_state - *state; /* internal state, allocated by zalloc/zfree */ - - mz_alloc_func - zalloc; /* optional heap allocation function (defaults to malloc) */ - mz_free_func zfree; /* optional heap free function (defaults to free) */ - void *opaque; /* heap alloc function user pointer */ - - int data_type; /* data_type (unused) */ - mz_ulong adler; /* adler32 of the source or uncompressed data */ - mz_ulong reserved; /* not used */ -} mz_stream; - -typedef mz_stream *mz_streamp; - -/* Returns the version string of miniz.c. */ -MINIZ_EXPORT const char *mz_version(void); - -/* mz_deflateInit() initializes a compressor with default options: */ -/* Parameters: */ -/* pStream must point to an initialized mz_stream struct. */ -/* level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. */ -/* level 1 enables a specially optimized compression function that's been - * optimized purely for performance, not ratio. */ -/* (This special func. is currently only enabled when - * MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) */ -/* Return values: */ -/* MZ_OK on success. */ -/* MZ_STREAM_ERROR if the stream is bogus. */ -/* MZ_PARAM_ERROR if the input parameters are bogus. */ -/* MZ_MEM_ERROR on out of memory. */ -MINIZ_EXPORT int mz_deflateInit(mz_streamp pStream, int level); - -/* mz_deflateInit2() is like mz_deflate(), except with more control: */ -/* Additional parameters: */ -/* method must be MZ_DEFLATED */ -/* window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with - * zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no - * header or footer) */ -/* mem_level must be between [1, 9] (it's checked but ignored by miniz.c) */ -MINIZ_EXPORT int mz_deflateInit2(mz_streamp pStream, int level, int method, - int window_bits, int mem_level, int strategy); - -/* Quickly resets a compressor without having to reallocate anything. Same as - * calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). */ -MINIZ_EXPORT int mz_deflateReset(mz_streamp pStream); - -/* mz_deflate() compresses the input to output, consuming as much of the input - * and producing as much output as possible. */ -/* Parameters: */ -/* pStream is the stream to read from and write to. You must initialize/update - * the next_in, avail_in, next_out, and avail_out members. */ -/* flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or - * MZ_FINISH. */ -/* Return values: */ -/* MZ_OK on success (when flushing, or if more input is needed but not - * available, and/or there's more output to be written but the output buffer is - * full). */ -/* MZ_STREAM_END if all input has been consumed and all output bytes have been - * written. Don't call mz_deflate() on the stream anymore. */ -/* MZ_STREAM_ERROR if the stream is bogus. */ -/* MZ_PARAM_ERROR if one of the parameters is invalid. */ -/* MZ_BUF_ERROR if no forward progress is possible because the input and/or - * output buffers are empty. (Fill up the input buffer or free up some output - * space and try again.) */ -MINIZ_EXPORT int mz_deflate(mz_streamp pStream, int flush); - -/* mz_deflateEnd() deinitializes a compressor: */ -/* Return values: */ -/* MZ_OK on success. */ -/* MZ_STREAM_ERROR if the stream is bogus. */ -MINIZ_EXPORT int mz_deflateEnd(mz_streamp pStream); - -/* mz_deflateBound() returns a (very) conservative upper bound on the amount of - * data that could be generated by deflate(), assuming flush is set to only - * MZ_NO_FLUSH or MZ_FINISH. */ -MINIZ_EXPORT mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); - -/* Single-call compression functions mz_compress() and mz_compress2(): */ -/* Returns MZ_OK on success, or one of the error codes from mz_deflate() on - * failure. */ -MINIZ_EXPORT int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, - const unsigned char *pSource, mz_ulong source_len); -MINIZ_EXPORT int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, - const unsigned char *pSource, mz_ulong source_len, - int level); - -/* mz_compressBound() returns a (very) conservative upper bound on the amount of - * data that could be generated by calling mz_compress(). */ -MINIZ_EXPORT mz_ulong mz_compressBound(mz_ulong source_len); - -/* Initializes a decompressor. */ -MINIZ_EXPORT int mz_inflateInit(mz_streamp pStream); - -/* mz_inflateInit2() is like mz_inflateInit() with an additional option that - * controls the window size and whether or not the stream has been wrapped with - * a zlib header/footer: */ -/* window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or - * -MZ_DEFAULT_WINDOW_BITS (raw deflate). */ -MINIZ_EXPORT int mz_inflateInit2(mz_streamp pStream, int window_bits); - -/* Quickly resets a compressor without having to reallocate anything. Same as - * calling mz_inflateEnd() followed by mz_inflateInit()/mz_inflateInit2(). */ -MINIZ_EXPORT int mz_inflateReset(mz_streamp pStream); - -/* Decompresses the input stream to the output, consuming only as much of the - * input as needed, and writing as much to the output as possible. */ -/* Parameters: */ -/* pStream is the stream to read from and write to. You must initialize/update - * the next_in, avail_in, next_out, and avail_out members. */ -/* flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. */ -/* On the first call, if flush is MZ_FINISH it's assumed the input and output - * buffers are both sized large enough to decompress the entire stream in a - * single call (this is slightly faster). */ -/* MZ_FINISH implies that there are no more source bytes available beside - * what's already in the input buffer, and that the output buffer is large - * enough to hold the rest of the decompressed data. */ -/* Return values: */ -/* MZ_OK on success. Either more input is needed but not available, and/or - * there's more output to be written but the output buffer is full. */ -/* MZ_STREAM_END if all needed input has been consumed and all output bytes - * have been written. For zlib streams, the adler-32 of the decompressed data - * has also been verified. */ -/* MZ_STREAM_ERROR if the stream is bogus. */ -/* MZ_DATA_ERROR if the deflate stream is invalid. */ -/* MZ_PARAM_ERROR if one of the parameters is invalid. */ -/* MZ_BUF_ERROR if no forward progress is possible because the input buffer is - * empty but the inflater needs more input to continue, or if the output buffer - * is not large enough. Call mz_inflate() again */ -/* with more input data, or with more room in the output buffer (except when - * using single call decompression, described above). */ -MINIZ_EXPORT int mz_inflate(mz_streamp pStream, int flush); - -/* Deinitializes a decompressor. */ -MINIZ_EXPORT int mz_inflateEnd(mz_streamp pStream); - -/* Single-call decompression. */ -/* Returns MZ_OK on success, or one of the error codes from mz_inflate() on - * failure. */ -MINIZ_EXPORT int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, - const unsigned char *pSource, - mz_ulong source_len); -MINIZ_EXPORT int mz_uncompress2(unsigned char *pDest, mz_ulong *pDest_len, - const unsigned char *pSource, - mz_ulong *pSource_len); - -/* Returns a string description of the specified error code, or NULL if the - * error code is invalid. */ -MINIZ_EXPORT const char *mz_error(int err); - -/* Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used - * as a drop-in replacement for the subset of zlib that miniz.c supports. */ -/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you - * use zlib in the same project. */ -#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES -typedef unsigned char Byte; -typedef unsigned int uInt; -typedef mz_ulong uLong; -typedef Byte Bytef; -typedef uInt uIntf; -typedef char charf; -typedef int intf; -typedef void *voidpf; -typedef uLong uLongf; -typedef void *voidp; -typedef void *const voidpc; -#define Z_NULL 0 -#define Z_NO_FLUSH MZ_NO_FLUSH -#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH -#define Z_SYNC_FLUSH MZ_SYNC_FLUSH -#define Z_FULL_FLUSH MZ_FULL_FLUSH -#define Z_FINISH MZ_FINISH -#define Z_BLOCK MZ_BLOCK -#define Z_OK MZ_OK -#define Z_STREAM_END MZ_STREAM_END -#define Z_NEED_DICT MZ_NEED_DICT -#define Z_ERRNO MZ_ERRNO -#define Z_STREAM_ERROR MZ_STREAM_ERROR -#define Z_DATA_ERROR MZ_DATA_ERROR -#define Z_MEM_ERROR MZ_MEM_ERROR -#define Z_BUF_ERROR MZ_BUF_ERROR -#define Z_VERSION_ERROR MZ_VERSION_ERROR -#define Z_PARAM_ERROR MZ_PARAM_ERROR -#define Z_NO_COMPRESSION MZ_NO_COMPRESSION -#define Z_BEST_SPEED MZ_BEST_SPEED -#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION -#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION -#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY -#define Z_FILTERED MZ_FILTERED -#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY -#define Z_RLE MZ_RLE -#define Z_FIXED MZ_FIXED -#define Z_DEFLATED MZ_DEFLATED -#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS -#define alloc_func mz_alloc_func -#define free_func mz_free_func -#define internal_state mz_internal_state -#define z_stream mz_stream -#define deflateInit mz_deflateInit -#define deflateInit2 mz_deflateInit2 -#define deflateReset mz_deflateReset -#define deflate mz_deflate -#define deflateEnd mz_deflateEnd -#define deflateBound mz_deflateBound -#define compress mz_compress -#define compress2 mz_compress2 -#define compressBound mz_compressBound -#define inflateInit mz_inflateInit -#define inflateInit2 mz_inflateInit2 -#define inflateReset mz_inflateReset -#define inflate mz_inflate -#define inflateEnd mz_inflateEnd -#define uncompress mz_uncompress -#define uncompress2 mz_uncompress2 -#define crc32 mz_crc32 -#define adler32 mz_adler32 -#define MAX_WBITS 15 -#define MAX_MEM_LEVEL 9 -#define zError mz_error -#define ZLIB_VERSION MZ_VERSION -#define ZLIB_VERNUM MZ_VERNUM -#define ZLIB_VER_MAJOR MZ_VER_MAJOR -#define ZLIB_VER_MINOR MZ_VER_MINOR -#define ZLIB_VER_REVISION MZ_VER_REVISION -#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION -#define zlibVersion mz_version -#define zlib_version mz_version() -#endif /* #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ - -#endif /* MINIZ_NO_ZLIB_APIS */ - -#ifdef __cplusplus -} -#endif - -#pragma once -#include -#include -#include -#include - -/* ------------------- Types and macros */ -typedef unsigned char mz_uint8; -typedef signed short mz_int16; -typedef unsigned short mz_uint16; -typedef unsigned int mz_uint32; -typedef unsigned int mz_uint; -typedef int64_t mz_int64; -typedef uint64_t mz_uint64; -typedef int mz_bool; - -#define MZ_FALSE (0) -#define MZ_TRUE (1) - -/* Works around MSVC's spammy "warning C4127: conditional expression is - * constant" message. */ -#ifdef _MSC_VER -#define MZ_MACRO_END while (0, 0) -#else -#define MZ_MACRO_END while (0) -#endif - -#ifdef MINIZ_NO_STDIO -#define MZ_FILE void * -#else -#include -#define MZ_FILE FILE -#endif /* #ifdef MINIZ_NO_STDIO */ - -#ifdef MINIZ_NO_TIME -typedef struct mz_dummy_time_t_tag { - int m_dummy; -} mz_dummy_time_t; -#define MZ_TIME_T mz_dummy_time_t -#else -#define MZ_TIME_T time_t -#endif - -#define MZ_ASSERT(x) assert(x) - -#ifdef MINIZ_NO_MALLOC -#define MZ_MALLOC(x) NULL -#define MZ_FREE(x) (void)x, ((void)0) -#define MZ_REALLOC(p, x) NULL -#else -#define MZ_MALLOC(x) malloc(x) -#define MZ_FREE(x) free(x) -#define MZ_REALLOC(p, x) realloc(p, x) -#endif - -#define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) -#define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) -#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN -#define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) -#define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) -#else -#define MZ_READ_LE16(p) \ - ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ - ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) -#define MZ_READ_LE32(p) \ - ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ - ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \ - ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | \ - ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) -#endif - -#define MZ_READ_LE64(p) \ - (((mz_uint64)MZ_READ_LE32(p)) | \ - (((mz_uint64)MZ_READ_LE32((const mz_uint8 *)(p) + sizeof(mz_uint32))) \ - << 32U)) - -#ifdef _MSC_VER -#define MZ_FORCEINLINE __forceinline -#elif defined(__GNUC__) -#define MZ_FORCEINLINE __inline__ __attribute__((__always_inline__)) -#else -#define MZ_FORCEINLINE inline -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -extern MINIZ_EXPORT void *miniz_def_alloc_func(void *opaque, size_t items, - size_t size); -extern MINIZ_EXPORT void miniz_def_free_func(void *opaque, void *address); -extern MINIZ_EXPORT void *miniz_def_realloc_func(void *opaque, void *address, - size_t items, size_t size); - -#define MZ_UINT16_MAX (0xFFFFU) -#define MZ_UINT32_MAX (0xFFFFFFFFU) - -#ifdef __cplusplus -} -#endif -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif -/* ------------------- Low-level Compression API Definitions */ - -/* Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly - * slower, and raw/dynamic blocks will be output more frequently). */ -#define TDEFL_LESS_MEMORY 0 - -/* tdefl_init() compression flags logically OR'd together (low 12 bits contain - * the max. number of probes per dictionary search): */ -/* TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes - * per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap - * compression), 4095=Huffman+LZ (slowest/best compression). */ -enum { - TDEFL_HUFFMAN_ONLY = 0, - TDEFL_DEFAULT_MAX_PROBES = 128, - TDEFL_MAX_PROBES_MASK = 0xFFF -}; - -/* TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before - * the deflate data, and the Adler-32 of the source data at the end. Otherwise, - * you'll get raw deflate data. */ -/* TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even - * when not writing zlib headers). */ -/* TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more - * efficient lazy parsing. */ -/* TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's - * initialization time to the minimum, but the output may vary from run to run - * given the same input (depending on the contents of memory). */ -/* TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) - */ -/* TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. */ -/* TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. */ -/* TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. */ -/* The low 12 bits are reserved to control the max # of hash probes per - * dictionary lookup (see TDEFL_MAX_PROBES_MASK). */ -enum { - TDEFL_WRITE_ZLIB_HEADER = 0x01000, - TDEFL_COMPUTE_ADLER32 = 0x02000, - TDEFL_GREEDY_PARSING_FLAG = 0x04000, - TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, - TDEFL_RLE_MATCHES = 0x10000, - TDEFL_FILTER_MATCHES = 0x20000, - TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, - TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 -}; - -/* High level compression functions: */ -/* tdefl_compress_mem_to_heap() compresses a block in memory to a heap block - * allocated via malloc(). */ -/* On entry: */ -/* pSrc_buf, src_buf_len: Pointer and size of source block to compress. */ -/* flags: The max match finder probes (default is 128) logically OR'd against - * the above flags. Higher probes are slower but improve compression. */ -/* On return: */ -/* Function returns a pointer to the compressed data, or NULL on failure. */ -/* *pOut_len will be set to the compressed data's size, which could be larger - * than src_buf_len on uncompressible data. */ -/* The caller must free() the returned block when it's no longer needed. */ -MINIZ_EXPORT void *tdefl_compress_mem_to_heap(const void *pSrc_buf, - size_t src_buf_len, - size_t *pOut_len, int flags); - -/* tdefl_compress_mem_to_mem() compresses a block in memory to another block in - * memory. */ -/* Returns 0 on failure. */ -MINIZ_EXPORT size_t tdefl_compress_mem_to_mem(void *pOut_buf, - size_t out_buf_len, - const void *pSrc_buf, - size_t src_buf_len, int flags); - -/* Compresses an image to a compressed PNG file in memory. */ -/* On entry: */ -/* pImage, w, h, and num_chans describe the image to compress. num_chans may be - * 1, 2, 3, or 4. */ -/* The image pitch in bytes per scanline will be w*num_chans. The leftmost - * pixel on the top scanline is stored first in memory. */ -/* level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, - * MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL */ -/* If flip is true, the image will be flipped on the Y axis (useful for OpenGL - * apps). */ -/* On return: */ -/* Function returns a pointer to the compressed data, or NULL on failure. */ -/* *pLen_out will be set to the size of the PNG image file. */ -/* The caller must mz_free() the returned heap block (which will typically be - * larger than *pLen_out) when it's no longer needed. */ -MINIZ_EXPORT void * -tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, - int num_chans, size_t *pLen_out, - mz_uint level, mz_bool flip); -MINIZ_EXPORT void *tdefl_write_image_to_png_file_in_memory(const void *pImage, - int w, int h, - int num_chans, - size_t *pLen_out); - -/* Output stream interface. The compressor uses this interface to write - * compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. */ -typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, - void *pUser); - -/* tdefl_compress_mem_to_output() compresses a block to an output stream. The - * above helpers use this function internally. */ -MINIZ_EXPORT mz_bool tdefl_compress_mem_to_output( - const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, - void *pPut_buf_user, int flags); - -enum { - TDEFL_MAX_HUFF_TABLES = 3, - TDEFL_MAX_HUFF_SYMBOLS_0 = 288, - TDEFL_MAX_HUFF_SYMBOLS_1 = 32, - TDEFL_MAX_HUFF_SYMBOLS_2 = 19, - TDEFL_LZ_DICT_SIZE = 32768, - TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, - TDEFL_MIN_MATCH_LEN = 3, - TDEFL_MAX_MATCH_LEN = 258 -}; - -/* TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed - * output block (using static/fixed Huffman codes). */ -#if TDEFL_LESS_MEMORY -enum { - TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, - TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, - TDEFL_MAX_HUFF_SYMBOLS = 288, - TDEFL_LZ_HASH_BITS = 12, - TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, - TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, - TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS -}; -#else -enum { - TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, - TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, - TDEFL_MAX_HUFF_SYMBOLS = 288, - TDEFL_LZ_HASH_BITS = 15, - TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, - TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, - TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS -}; -#endif - -/* The low-level tdefl functions below may be used directly if the above helper - * functions aren't flexible enough. The low-level functions don't make any heap - * allocations, unlike the above helper functions. */ -typedef enum { - TDEFL_STATUS_BAD_PARAM = -2, - TDEFL_STATUS_PUT_BUF_FAILED = -1, - TDEFL_STATUS_OKAY = 0, - TDEFL_STATUS_DONE = 1 -} tdefl_status; - -/* Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums */ -typedef enum { - TDEFL_NO_FLUSH = 0, - TDEFL_SYNC_FLUSH = 2, - TDEFL_FULL_FLUSH = 3, - TDEFL_FINISH = 4 -} tdefl_flush; - -/* tdefl's compression state structure. */ -typedef struct { - tdefl_put_buf_func_ptr m_pPut_buf_func; - void *m_pPut_buf_user; - mz_uint m_flags, m_max_probes[2]; - int m_greedy_parsing; - mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; - mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; - mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, - m_bit_buffer; - mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, - m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, - m_wants_to_finish; - tdefl_status m_prev_return_status; - const void *m_pIn_buf; - void *m_pOut_buf; - size_t *m_pIn_buf_size, *m_pOut_buf_size; - tdefl_flush m_flush; - const mz_uint8 *m_pSrc; - size_t m_src_buf_left, m_out_buf_ofs; - mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; - mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; - mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; - mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; - mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; - mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; - mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; - mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; -} tdefl_compressor; - -/* Initializes the compressor. */ -/* There is no corresponding deinit() function because the tdefl API's do not - * dynamically allocate memory. */ -/* pBut_buf_func: If NULL, output data will be supplied to the specified - * callback. In this case, the user should call the tdefl_compress_buffer() API - * for compression. */ -/* If pBut_buf_func is NULL the user should always call the tdefl_compress() - * API. */ -/* flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, - * etc.) */ -MINIZ_EXPORT tdefl_status tdefl_init(tdefl_compressor *d, - tdefl_put_buf_func_ptr pPut_buf_func, - void *pPut_buf_user, int flags); - -/* Compresses a block of data, consuming as much of the specified input buffer - * as possible, and writing as much compressed data to the specified output - * buffer as possible. */ -MINIZ_EXPORT tdefl_status tdefl_compress(tdefl_compressor *d, - const void *pIn_buf, - size_t *pIn_buf_size, void *pOut_buf, - size_t *pOut_buf_size, - tdefl_flush flush); - -/* tdefl_compress_buffer() is only usable when the tdefl_init() is called with a - * non-NULL tdefl_put_buf_func_ptr. */ -/* tdefl_compress_buffer() always consumes the entire input buffer. */ -MINIZ_EXPORT tdefl_status tdefl_compress_buffer(tdefl_compressor *d, - const void *pIn_buf, - size_t in_buf_size, - tdefl_flush flush); - -MINIZ_EXPORT tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); -MINIZ_EXPORT mz_uint32 tdefl_get_adler32(tdefl_compressor *d); - -/* Create tdefl_compress() flags given zlib-style compression parameters. */ -/* level may range from [0,10] (where 10 is absolute max compression, but may be - * much slower on some files) */ -/* window_bits may be -15 (raw deflate) or 15 (zlib) */ -/* strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, - * MZ_RLE, or MZ_FIXED */ -MINIZ_EXPORT mz_uint tdefl_create_comp_flags_from_zip_params(int level, - int window_bits, - int strategy); - -#ifndef MINIZ_NO_MALLOC -/* Allocate the tdefl_compressor structure in C so that */ -/* non-C language bindings to tdefl_ API don't need to worry about */ -/* structure size and allocation mechanism. */ -MINIZ_EXPORT tdefl_compressor *tdefl_compressor_alloc(void); -MINIZ_EXPORT void tdefl_compressor_free(tdefl_compressor *pComp); -#endif - -#ifdef __cplusplus -} -#endif -#pragma once - -/* ------------------- Low-level Decompression API Definitions */ - -#ifdef __cplusplus -extern "C" { -#endif -/* Decompression flags used by tinfl_decompress(). */ -/* TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and - * ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the - * input is a raw deflate stream. */ -/* TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available - * beyond the end of the supplied input buffer. If clear, the input buffer - * contains all remaining input. */ -/* TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large - * enough to hold the entire decompressed stream. If clear, the output buffer is - * at least the size of the dictionary (typically 32KB). */ -/* TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the - * decompressed bytes. */ -enum { - TINFL_FLAG_PARSE_ZLIB_HEADER = 1, - TINFL_FLAG_HAS_MORE_INPUT = 2, - TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, - TINFL_FLAG_COMPUTE_ADLER32 = 8 -}; - -/* High level decompression functions: */ -/* tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block - * allocated via malloc(). */ -/* On entry: */ -/* pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data - * to decompress. */ -/* On return: */ -/* Function returns a pointer to the decompressed data, or NULL on failure. */ -/* *pOut_len will be set to the decompressed data's size, which could be larger - * than src_buf_len on uncompressible data. */ -/* The caller must call mz_free() on the returned block when it's no longer - * needed. */ -MINIZ_EXPORT void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, - size_t src_buf_len, - size_t *pOut_len, int flags); - -/* tinfl_decompress_mem_to_mem() decompresses a block in memory to another block - * in memory. */ -/* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes - * written on success. */ -#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) -MINIZ_EXPORT size_t tinfl_decompress_mem_to_mem(void *pOut_buf, - size_t out_buf_len, - const void *pSrc_buf, - size_t src_buf_len, int flags); - -/* tinfl_decompress_mem_to_callback() decompresses a block in memory to an - * internal 32KB buffer, and a user provided callback function will be called to - * flush the buffer. */ -/* Returns 1 on success or 0 on failure. */ -typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); -MINIZ_EXPORT int -tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, - tinfl_put_buf_func_ptr pPut_buf_func, - void *pPut_buf_user, int flags); - -struct tinfl_decompressor_tag; -typedef struct tinfl_decompressor_tag tinfl_decompressor; - -#ifndef MINIZ_NO_MALLOC -/* Allocate the tinfl_decompressor structure in C so that */ -/* non-C language bindings to tinfl_ API don't need to worry about */ -/* structure size and allocation mechanism. */ -MINIZ_EXPORT tinfl_decompressor *tinfl_decompressor_alloc(void); -MINIZ_EXPORT void tinfl_decompressor_free(tinfl_decompressor *pDecomp); -#endif - -/* Max size of LZ dictionary. */ -#define TINFL_LZ_DICT_SIZE 32768 - -/* Return status. */ -typedef enum { - /* This flags indicates the inflator needs 1 or more input bytes to make - forward progress, but the caller is indicating that no more are available. - The compressed data */ - /* is probably corrupted. If you call the inflator again with more bytes it'll - try to continue processing the input but this is a BAD sign (either the - data is corrupted or you called it incorrectly). */ - /* If you call it again with no input you'll just get - TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again. */ - TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4, - - /* This flag indicates that one or more of the input parameters was obviously - bogus. (You can try calling it again, but if you get this error the calling - code is wrong.) */ - TINFL_STATUS_BAD_PARAM = -3, - - /* This flags indicate the inflator is finished but the adler32 check of the - uncompressed data didn't match. If you call it again it'll return - TINFL_STATUS_DONE. */ - TINFL_STATUS_ADLER32_MISMATCH = -2, - - /* This flags indicate the inflator has somehow failed (bad code, corrupted - input, etc.). If you call it again without resetting via tinfl_init() it - it'll just keep on returning the same status failure code. */ - TINFL_STATUS_FAILED = -1, - - /* Any status code less than TINFL_STATUS_DONE must indicate a failure. */ - - /* This flag indicates the inflator has returned every byte of uncompressed - data that it can, has consumed every byte that it needed, has successfully - reached the end of the deflate stream, and */ - /* if zlib headers and adler32 checking enabled that it has successfully - checked the uncompressed data's adler32. If you call it again you'll just - get TINFL_STATUS_DONE over and over again. */ - TINFL_STATUS_DONE = 0, - - /* This flag indicates the inflator MUST have more input data (even 1 byte) - before it can make any more forward progress, or you need to clear the - TINFL_FLAG_HAS_MORE_INPUT */ - /* flag on the next call if you don't have any more source data. If the source - data was somehow corrupted it's also possible (but unlikely) for the - inflator to keep on demanding input to */ - /* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */ - TINFL_STATUS_NEEDS_MORE_INPUT = 1, - - /* This flag indicates the inflator definitely has 1 or more bytes of - uncompressed data available, but it cannot write this data into the output - buffer. */ - /* Note if the source compressed data was corrupted it's possible for the - inflator to return a lot of uncompressed data to the caller. I've been - assuming you know how much uncompressed data to expect */ - /* (either exact or worst case) and will stop calling the inflator and fail - after receiving too much. In pure streaming scenarios where you have no - idea how many bytes to expect this may not be possible */ - /* so I may need to add some code to address this. */ - TINFL_STATUS_HAS_MORE_OUTPUT = 2 -} tinfl_status; - -/* Initializes the decompressor to its initial state. */ -#define tinfl_init(r) \ - do { \ - (r)->m_state = 0; \ - } \ - MZ_MACRO_END -#define tinfl_get_adler32(r) (r)->m_check_adler32 - -/* Main low-level decompressor coroutine function. This is the only function - * actually needed for decompression. All the other functions are just - * high-level helpers for improved usability. */ -/* This is a universal API, i.e. it can be used as a building block to build any - * desired higher level decompression API. In the limit case, it can be called - * once per every byte input or output. */ -MINIZ_EXPORT tinfl_status tinfl_decompress( - tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, - mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, - const mz_uint32 decomp_flags); - -/* Internal/private bits follow. */ -enum { - TINFL_MAX_HUFF_TABLES = 3, - TINFL_MAX_HUFF_SYMBOLS_0 = 288, - TINFL_MAX_HUFF_SYMBOLS_1 = 32, - TINFL_MAX_HUFF_SYMBOLS_2 = 19, - TINFL_FAST_LOOKUP_BITS = 10, - TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS -}; - -typedef struct { - mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; - mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], - m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; -} tinfl_huff_table; - -#if MINIZ_HAS_64BIT_REGISTERS -#define TINFL_USE_64BIT_BITBUF 1 -#else -#define TINFL_USE_64BIT_BITBUF 0 -#endif - -#if TINFL_USE_64BIT_BITBUF -typedef mz_uint64 tinfl_bit_buf_t; -#define TINFL_BITBUF_SIZE (64) -#else -typedef mz_uint32 tinfl_bit_buf_t; -#define TINFL_BITBUF_SIZE (32) -#endif - -struct tinfl_decompressor_tag { - mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, - m_check_adler32, m_dist, m_counter, m_num_extra, - m_table_sizes[TINFL_MAX_HUFF_TABLES]; - tinfl_bit_buf_t m_bit_buf; - size_t m_dist_from_out_buf_start; - tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; - mz_uint8 m_raw_header[4], - m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; -}; - -#ifdef __cplusplus -} -#endif - -#pragma once - -/* ------------------- ZIP archive reading/writing */ - -#ifndef MINIZ_NO_ARCHIVE_APIS - -#ifdef __cplusplus -extern "C" { -#endif - -enum { - /* Note: These enums can be reduced as needed to save memory or stack space - - they are pretty conservative. */ - MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, - MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 512, - MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 512 -}; - -typedef struct { - /* Central directory file index. */ - mz_uint32 m_file_index; - - /* Byte offset of this entry in the archive's central directory. Note we - * currently only support up to UINT_MAX or less bytes in the central dir. */ - mz_uint64 m_central_dir_ofs; - - /* These fields are copied directly from the zip's central dir. */ - mz_uint16 m_version_made_by; - mz_uint16 m_version_needed; - mz_uint16 m_bit_flag; - mz_uint16 m_method; - -#ifndef MINIZ_NO_TIME - MZ_TIME_T m_time; -#endif - - /* CRC-32 of uncompressed data. */ - mz_uint32 m_crc32; - - /* File's compressed size. */ - mz_uint64 m_comp_size; - - /* File's uncompressed size. Note, I've seen some old archives where directory - * entries had 512 bytes for their uncompressed sizes, but when you try to - * unpack them you actually get 0 bytes. */ - mz_uint64 m_uncomp_size; - - /* Zip internal and external file attributes. */ - mz_uint16 m_internal_attr; - mz_uint32 m_external_attr; - - /* Entry's local header file offset in bytes. */ - mz_uint64 m_local_header_ofs; - - /* Size of comment in bytes. */ - mz_uint32 m_comment_size; - - /* MZ_TRUE if the entry appears to be a directory. */ - mz_bool m_is_directory; - - /* MZ_TRUE if the entry uses encryption/strong encryption (which miniz_zip - * doesn't support) */ - mz_bool m_is_encrypted; - - /* MZ_TRUE if the file is not encrypted, a patch file, and if it uses a - * compression method we support. */ - mz_bool m_is_supported; - - /* Filename. If string ends in '/' it's a subdirectory entry. */ - /* Guaranteed to be zero terminated, may be truncated to fit. */ - char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; - - /* Comment field. */ - /* Guaranteed to be zero terminated, may be truncated to fit. */ - char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; - -} mz_zip_archive_file_stat; - -typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, - void *pBuf, size_t n); -typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, - const void *pBuf, size_t n); -typedef mz_bool (*mz_file_needs_keepalive)(void *pOpaque); - -struct mz_zip_internal_state_tag; -typedef struct mz_zip_internal_state_tag mz_zip_internal_state; - -typedef enum { - MZ_ZIP_MODE_INVALID = 0, - MZ_ZIP_MODE_READING = 1, - MZ_ZIP_MODE_WRITING = 2, - MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 -} mz_zip_mode; - -typedef enum { - MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, - MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, - MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, - MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800, - MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG = - 0x1000, /* if enabled, mz_zip_reader_locate_file() will be called on each - file as its validated to ensure the func finds the file in the - central dir (intended for testing) */ - MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY = - 0x2000, /* validate the local headers, but don't decompress the entire - file and check the crc32 */ - MZ_ZIP_FLAG_WRITE_ZIP64 = - 0x4000, /* always use the zip64 file format, instead of the original zip - file format with automatic switch to zip64. Use as flags - parameter with mz_zip_writer_init*_v2 */ - MZ_ZIP_FLAG_WRITE_ALLOW_READING = 0x8000, - MZ_ZIP_FLAG_ASCII_FILENAME = 0x10000, - /*After adding a compressed file, seek back - to local file header and set the correct sizes*/ - MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE = 0x20000 -} mz_zip_flags; - -typedef enum { - MZ_ZIP_TYPE_INVALID = 0, - MZ_ZIP_TYPE_USER, - MZ_ZIP_TYPE_MEMORY, - MZ_ZIP_TYPE_HEAP, - MZ_ZIP_TYPE_FILE, - MZ_ZIP_TYPE_CFILE, - MZ_ZIP_TOTAL_TYPES -} mz_zip_type; - -/* miniz error codes. Be sure to update mz_zip_get_error_string() if you add or - * modify this enum. */ -typedef enum { - MZ_ZIP_NO_ERROR = 0, - MZ_ZIP_UNDEFINED_ERROR, - MZ_ZIP_TOO_MANY_FILES, - MZ_ZIP_FILE_TOO_LARGE, - MZ_ZIP_UNSUPPORTED_METHOD, - MZ_ZIP_UNSUPPORTED_ENCRYPTION, - MZ_ZIP_UNSUPPORTED_FEATURE, - MZ_ZIP_FAILED_FINDING_CENTRAL_DIR, - MZ_ZIP_NOT_AN_ARCHIVE, - MZ_ZIP_INVALID_HEADER_OR_CORRUPTED, - MZ_ZIP_UNSUPPORTED_MULTIDISK, - MZ_ZIP_DECOMPRESSION_FAILED, - MZ_ZIP_COMPRESSION_FAILED, - MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE, - MZ_ZIP_CRC_CHECK_FAILED, - MZ_ZIP_UNSUPPORTED_CDIR_SIZE, - MZ_ZIP_ALLOC_FAILED, - MZ_ZIP_FILE_OPEN_FAILED, - MZ_ZIP_FILE_CREATE_FAILED, - MZ_ZIP_FILE_WRITE_FAILED, - MZ_ZIP_FILE_READ_FAILED, - MZ_ZIP_FILE_CLOSE_FAILED, - MZ_ZIP_FILE_SEEK_FAILED, - MZ_ZIP_FILE_STAT_FAILED, - MZ_ZIP_INVALID_PARAMETER, - MZ_ZIP_INVALID_FILENAME, - MZ_ZIP_BUF_TOO_SMALL, - MZ_ZIP_INTERNAL_ERROR, - MZ_ZIP_FILE_NOT_FOUND, - MZ_ZIP_ARCHIVE_TOO_LARGE, - MZ_ZIP_VALIDATION_FAILED, - MZ_ZIP_WRITE_CALLBACK_FAILED, - MZ_ZIP_TOTAL_ERRORS -} mz_zip_error; - -typedef struct { - mz_uint64 m_archive_size; - mz_uint64 m_central_directory_file_ofs; - - /* We only support up to UINT32_MAX files in zip64 mode. */ - mz_uint32 m_total_files; - mz_zip_mode m_zip_mode; - mz_zip_type m_zip_type; - mz_zip_error m_last_error; - - mz_uint64 m_file_offset_alignment; - - mz_alloc_func m_pAlloc; - mz_free_func m_pFree; - mz_realloc_func m_pRealloc; - void *m_pAlloc_opaque; - - mz_file_read_func m_pRead; - mz_file_write_func m_pWrite; - mz_file_needs_keepalive m_pNeeds_keepalive; - void *m_pIO_opaque; - - mz_zip_internal_state *m_pState; - -} mz_zip_archive; - -typedef struct { - mz_zip_archive *pZip; - mz_uint flags; - - int status; -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - mz_uint file_crc32; -#endif - mz_uint64 read_buf_size, read_buf_ofs, read_buf_avail, comp_remaining, - out_buf_ofs, cur_file_ofs; - mz_zip_archive_file_stat file_stat; - void *pRead_buf; - void *pWrite_buf; - - size_t out_blk_remain; - - tinfl_decompressor inflator; - -} mz_zip_reader_extract_iter_state; - -/* -------- ZIP reading */ - -/* Inits a ZIP archive reader. */ -/* These functions read and validate the archive's central directory. */ -MINIZ_EXPORT mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, - mz_uint flags); - -MINIZ_EXPORT mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, - const void *pMem, size_t size, - mz_uint flags); - -#ifndef MINIZ_NO_STDIO -/* Read a archive from a disk file. */ -/* file_start_ofs is the file offset where the archive actually begins, or 0. */ -/* actual_archive_size is the true total size of the archive, which may be - * smaller than the file's actual size on disk. If zero the entire file is - * treated as the archive. */ -MINIZ_EXPORT mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, - const char *pFilename, - mz_uint32 flags); -MINIZ_EXPORT mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, - const char *pFilename, - mz_uint flags, - mz_uint64 file_start_ofs, - mz_uint64 archive_size); - -/* Read an archive from an already opened FILE, beginning at the current file - * position. */ -/* The archive is assumed to be archive_size bytes long. If archive_size is 0, - * then the entire rest of the file is assumed to contain the archive. */ -/* The FILE will NOT be closed when mz_zip_reader_end() is called. */ -MINIZ_EXPORT mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, - MZ_FILE *pFile, - mz_uint64 archive_size, - mz_uint flags); -#endif - -/* Ends archive reading, freeing all allocations, and closing the input archive - * file if mz_zip_reader_init_file() was used. */ -MINIZ_EXPORT mz_bool mz_zip_reader_end(mz_zip_archive *pZip); - -/* -------- ZIP reading or writing */ - -/* Clears a mz_zip_archive struct to all zeros. */ -/* Important: This must be done before passing the struct to any mz_zip - * functions. */ -MINIZ_EXPORT void mz_zip_zero_struct(mz_zip_archive *pZip); - -MINIZ_EXPORT mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip); -MINIZ_EXPORT mz_zip_type mz_zip_get_type(mz_zip_archive *pZip); - -/* Returns the total number of files in the archive. */ -MINIZ_EXPORT mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); - -MINIZ_EXPORT mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip); -MINIZ_EXPORT mz_uint64 -mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip); -MINIZ_EXPORT MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip); - -/* Reads n bytes of raw archive data, starting at file offset file_ofs, to pBuf. - */ -MINIZ_EXPORT size_t mz_zip_read_archive_data(mz_zip_archive *pZip, - mz_uint64 file_ofs, void *pBuf, - size_t n); - -/* All mz_zip funcs set the m_last_error field in the mz_zip_archive struct. - * These functions retrieve/manipulate this field. */ -/* Note that the m_last_error functionality is not thread safe. */ -MINIZ_EXPORT mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, - mz_zip_error err_num); -MINIZ_EXPORT mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip); -MINIZ_EXPORT mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip); -MINIZ_EXPORT mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip); -MINIZ_EXPORT const char *mz_zip_get_error_string(mz_zip_error mz_err); - -/* MZ_TRUE if the archive file entry is a directory entry. */ -MINIZ_EXPORT mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, - mz_uint file_index); - -/* MZ_TRUE if the file is encrypted/strong encrypted. */ -MINIZ_EXPORT mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, - mz_uint file_index); - -/* MZ_TRUE if the compression method is supported, and the file is not - * encrypted, and the file is not a compressed patch file. */ -MINIZ_EXPORT mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, - mz_uint file_index); - -/* Retrieves the filename of an archive file entry. */ -/* Returns the number of bytes written to pFilename, or if filename_buf_size is - * 0 this function returns the number of bytes needed to fully store the - * filename. */ -MINIZ_EXPORT mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, - mz_uint file_index, - char *pFilename, - mz_uint filename_buf_size); - -/* Attempts to locates a file in the archive's central directory. */ -/* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */ -/* Returns -1 if the file cannot be found. */ -MINIZ_EXPORT int mz_zip_reader_locate_file(mz_zip_archive *pZip, - const char *pName, - const char *pComment, mz_uint flags); -MINIZ_EXPORT mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, - const char *pName, - const char *pComment, - mz_uint flags, - mz_uint32 *file_index); - -/* Returns detailed information about an archive file entry. */ -MINIZ_EXPORT mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, - mz_uint file_index, - mz_zip_archive_file_stat *pStat); - -/* MZ_TRUE if the file is in zip64 format. */ -/* A file is considered zip64 if it contained a zip64 end of central directory - * marker, or if it contained any zip64 extended file information fields in the - * central directory. */ -MINIZ_EXPORT mz_bool mz_zip_is_zip64(mz_zip_archive *pZip); - -/* Returns the total central directory size in bytes. */ -/* The current max supported size is <= MZ_UINT32_MAX. */ -MINIZ_EXPORT size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip); - -/* Extracts a archive file to a memory buffer using no memory allocation. */ -/* There must be at least enough room on the stack to store the inflator's state - * (~34KB or so). */ -MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_mem_no_alloc( - mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, - mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); -MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( - mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, - mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); - -/* Extracts a archive file to a memory buffer. */ -MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, - mz_uint file_index, - void *pBuf, size_t buf_size, - mz_uint flags); -MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, - const char *pFilename, - void *pBuf, - size_t buf_size, - mz_uint flags); - -/* Extracts a archive file to a dynamically allocated heap buffer. */ -/* The memory will be allocated via the mz_zip_archive's alloc/realloc - * functions. */ -/* Returns NULL and sets the last error on failure. */ -MINIZ_EXPORT void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, - mz_uint file_index, - size_t *pSize, mz_uint flags); -MINIZ_EXPORT void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, - const char *pFilename, - size_t *pSize, - mz_uint flags); - -/* Extracts a archive file using a callback function to output the file's data. - */ -MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_callback( - mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, - void *pOpaque, mz_uint flags); -MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_callback( - mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, - void *pOpaque, mz_uint flags); - -/* Extract a file iteratively */ -MINIZ_EXPORT mz_zip_reader_extract_iter_state * -mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, - mz_uint flags); -MINIZ_EXPORT mz_zip_reader_extract_iter_state * -mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, - mz_uint flags); -MINIZ_EXPORT size_t mz_zip_reader_extract_iter_read( - mz_zip_reader_extract_iter_state *pState, void *pvBuf, size_t buf_size); -MINIZ_EXPORT mz_bool -mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state *pState); - -#ifndef MINIZ_NO_STDIO -/* Extracts a archive file to a disk file and sets its last accessed and - * modified times. */ -/* This function only extracts files, not archive directory records. */ -MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, - mz_uint file_index, - const char *pDst_filename, - mz_uint flags); -MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_file( - mz_zip_archive *pZip, const char *pArchive_filename, - const char *pDst_filename, mz_uint flags); - -/* Extracts a archive file starting at the current position in the destination - * FILE stream. */ -MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, - mz_uint file_index, - MZ_FILE *File, - mz_uint flags); -MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_cfile( - mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, - mz_uint flags); -#endif - -#if 0 -/* TODO */ - typedef void *mz_zip_streaming_extract_state_ptr; - mz_zip_streaming_extract_state_ptr mz_zip_streaming_extract_begin(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); - uint64_t mz_zip_streaming_extract_get_size(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); - uint64_t mz_zip_streaming_extract_get_cur_ofs(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); - mz_bool mz_zip_streaming_extract_seek(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, uint64_t new_ofs); - size_t mz_zip_streaming_extract_read(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, void *pBuf, size_t buf_size); - mz_bool mz_zip_streaming_extract_end(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); -#endif - -/* This function compares the archive's local headers, the optional local zip64 - * extended information block, and the optional descriptor following the - * compressed data vs. the data in the central directory. */ -/* It also validates that each file can be successfully uncompressed unless the - * MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY is specified. */ -MINIZ_EXPORT mz_bool mz_zip_validate_file(mz_zip_archive *pZip, - mz_uint file_index, mz_uint flags); - -/* Validates an entire archive by calling mz_zip_validate_file() on each file. - */ -MINIZ_EXPORT mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, - mz_uint flags); - -/* Misc utils/helpers, valid for ZIP reading or writing */ -MINIZ_EXPORT mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, - mz_uint flags, - mz_zip_error *pErr); -MINIZ_EXPORT mz_bool mz_zip_validate_file_archive(const char *pFilename, - mz_uint flags, - mz_zip_error *pErr); - -/* Universal end function - calls either mz_zip_reader_end() or - * mz_zip_writer_end(). */ -MINIZ_EXPORT mz_bool mz_zip_end(mz_zip_archive *pZip); - -/* -------- ZIP writing */ - -#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS - -/* Inits a ZIP archive writer. */ -/*Set pZip->m_pWrite (and pZip->m_pIO_opaque) before calling mz_zip_writer_init - * or mz_zip_writer_init_v2*/ -/*The output is streamable, i.e. file_ofs in mz_file_write_func always increases - * only by n*/ -MINIZ_EXPORT mz_bool mz_zip_writer_init(mz_zip_archive *pZip, - mz_uint64 existing_size); -MINIZ_EXPORT mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, - mz_uint64 existing_size, - mz_uint flags); - -MINIZ_EXPORT mz_bool mz_zip_writer_init_heap( - mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, - size_t initial_allocation_size); -MINIZ_EXPORT mz_bool mz_zip_writer_init_heap_v2( - mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, - size_t initial_allocation_size, mz_uint flags); - -#ifndef MINIZ_NO_STDIO -MINIZ_EXPORT mz_bool -mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, - mz_uint64 size_to_reserve_at_beginning); -MINIZ_EXPORT mz_bool mz_zip_writer_init_file_v2( - mz_zip_archive *pZip, const char *pFilename, - mz_uint64 size_to_reserve_at_beginning, mz_uint flags); -MINIZ_EXPORT mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, - MZ_FILE *pFile, mz_uint flags); -#endif - -/* Converts a ZIP archive reader object into a writer object, to allow efficient - * in-place file appends to occur on an existing archive. */ -/* For archives opened using mz_zip_reader_init_file, pFilename must be the - * archive's filename so it can be reopened for writing. If the file can't be - * reopened, mz_zip_reader_end() will be called. */ -/* For archives opened using mz_zip_reader_init_mem, the memory block must be - * growable using the realloc callback (which defaults to realloc unless you've - * overridden it). */ -/* Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's - * user provided m_pWrite function cannot be NULL. */ -/* Note: In-place archive modification is not recommended unless you know what - * you're doing, because if execution stops or something goes wrong before */ -/* the archive is finalized the file's central directory will be hosed. */ -MINIZ_EXPORT mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, - const char *pFilename); -MINIZ_EXPORT mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, - const char *pFilename, - mz_uint flags); - -/* Adds the contents of a memory buffer to an archive. These functions record - * the current local time into the archive. */ -/* To add a directory entry, call this method with an archive name ending in a - * forwardslash with an empty buffer. */ -/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, - * MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or - * just set to MZ_DEFAULT_COMPRESSION. */ -MINIZ_EXPORT mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, - const char *pArchive_name, - const void *pBuf, size_t buf_size, - mz_uint level_and_flags); - -/* Like mz_zip_writer_add_mem(), except you can specify a file comment field, - * and optionally supply the function with already compressed data. */ -/* uncomp_size/uncomp_crc32 are only used if the MZ_ZIP_FLAG_COMPRESSED_DATA - * flag is specified. */ -MINIZ_EXPORT mz_bool mz_zip_writer_add_mem_ex( - mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, - size_t buf_size, const void *pComment, mz_uint16 comment_size, - mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); - -MINIZ_EXPORT mz_bool mz_zip_writer_add_mem_ex_v2( - mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, - size_t buf_size, const void *pComment, mz_uint16 comment_size, - mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, - MZ_TIME_T *last_modified, const char *user_extra_data_local, - mz_uint user_extra_data_local_len, const char *user_extra_data_central, - mz_uint user_extra_data_central_len); - -/* Adds the contents of a file to an archive. This function also records the - * disk file's modified time into the archive. */ -/* File data is supplied via a read callback function. User - * mz_zip_writer_add_(c)file to add a file directly.*/ -MINIZ_EXPORT mz_bool mz_zip_writer_add_read_buf_callback( - mz_zip_archive *pZip, const char *pArchive_name, - mz_file_read_func read_callback, void *callback_opaque, mz_uint64 max_size, - const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, - mz_uint level_and_flags, mz_uint32 ext_attributes, - const char *user_extra_data_local, mz_uint user_extra_data_local_len, - const char *user_extra_data_central, mz_uint user_extra_data_central_len); - -#ifndef MINIZ_NO_STDIO -/* Adds the contents of a disk file to an archive. This function also records - * the disk file's modified time into the archive. */ -/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, - * MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or - * just set to MZ_DEFAULT_COMPRESSION. */ -MINIZ_EXPORT mz_bool mz_zip_writer_add_file( - mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, - const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, - mz_uint32 ext_attributes); - -/* Like mz_zip_writer_add_file(), except the file data is read from the - * specified FILE stream. */ -MINIZ_EXPORT mz_bool mz_zip_writer_add_cfile( - mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, - mz_uint64 max_size, const MZ_TIME_T *pFile_time, const void *pComment, - mz_uint16 comment_size, mz_uint level_and_flags, mz_uint32 ext_attributes, - const char *user_extra_data_local, mz_uint user_extra_data_local_len, - const char *user_extra_data_central, mz_uint user_extra_data_central_len); -#endif - -/* Adds a file to an archive by fully cloning the data from another archive. */ -/* This function fully clones the source file's compressed data (no - * recompression), along with its full filename, extra data (it may add or - * modify the zip64 local header extra data field), and the optional descriptor - * following the compressed data. */ -MINIZ_EXPORT mz_bool mz_zip_writer_add_from_zip_reader( - mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index); - -/* Finalizes the archive by writing the central directory records followed by - * the end of central directory record. */ -/* After an archive is finalized, the only valid call on the mz_zip_archive - * struct is mz_zip_writer_end(). */ -/* An archive must be manually finalized by calling this function for it to be - * valid. */ -MINIZ_EXPORT mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); - -/* Finalizes a heap archive, returning a poiner to the heap block and its size. - */ -/* The heap block will be allocated using the mz_zip_archive's alloc/realloc - * callbacks. */ -MINIZ_EXPORT mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, - void **ppBuf, - size_t *pSize); - -/* Ends archive writing, freeing all allocations, and closing the output file if - * mz_zip_writer_init_file() was used. */ -/* Note for the archive to be valid, it *must* have been finalized before ending - * (this function will not do it for you). */ -MINIZ_EXPORT mz_bool mz_zip_writer_end(mz_zip_archive *pZip); - -/* -------- Misc. high-level helper functions: */ - -/* mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) - * appends a memory blob to a ZIP archive. */ -/* Note this is NOT a fully safe operation. If it crashes or dies in some way - * your archive can be left in a screwed up state (without a central directory). - */ -/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, - * MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or - * just set to MZ_DEFAULT_COMPRESSION. */ -/* TODO: Perhaps add an option to leave the existing central dir in place in - * case the add dies? We could then truncate the file (so the old central dir - * would be at the end) if something goes wrong. */ -MINIZ_EXPORT mz_bool mz_zip_add_mem_to_archive_file_in_place( - const char *pZip_filename, const char *pArchive_name, const void *pBuf, - size_t buf_size, const void *pComment, mz_uint16 comment_size, - mz_uint level_and_flags); -MINIZ_EXPORT mz_bool mz_zip_add_mem_to_archive_file_in_place_v2( - const char *pZip_filename, const char *pArchive_name, const void *pBuf, - size_t buf_size, const void *pComment, mz_uint16 comment_size, - mz_uint level_and_flags, mz_zip_error *pErr); - -/* Reads a single file from an archive into a heap block. */ -/* If pComment is not NULL, only the file with the specified comment will be - * extracted. */ -/* Returns NULL on failure. */ -MINIZ_EXPORT void * -mz_zip_extract_archive_file_to_heap(const char *pZip_filename, - const char *pArchive_name, size_t *pSize, - mz_uint flags); -MINIZ_EXPORT void *mz_zip_extract_archive_file_to_heap_v2( - const char *pZip_filename, const char *pArchive_name, const char *pComment, - size_t *pSize, mz_uint flags, mz_zip_error *pErr); - -#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ - -#ifdef __cplusplus -} -#endif - -#endif /* MINIZ_NO_ARCHIVE_APIS */ - -#ifndef MINIZ_HEADER_FILE_ONLY -/************************************************************************** - * - * Copyright 2013-2014 RAD Game Tools and Valve Software - * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC - * All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - **************************************************************************/ - -typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; -typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; -typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; - -#ifdef __cplusplus -extern "C" { -#endif - -/* ------------------- zlib-style API's */ - -mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) { - mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); - size_t block_len = buf_len % 5552; - if (!ptr) - return MZ_ADLER32_INIT; - while (buf_len) { - for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { - s1 += ptr[0], s2 += s1; - s1 += ptr[1], s2 += s1; - s1 += ptr[2], s2 += s1; - s1 += ptr[3], s2 += s1; - s1 += ptr[4], s2 += s1; - s1 += ptr[5], s2 += s1; - s1 += ptr[6], s2 += s1; - s1 += ptr[7], s2 += s1; - } - for (; i < block_len; ++i) - s1 += *ptr++, s2 += s1; - s1 %= 65521U, s2 %= 65521U; - buf_len -= block_len; - block_len = 5552; - } - return (s2 << 16) + s1; -} - -/* Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C - * implementation that balances processor cache usage against speed": - * http://www.geocities.com/malbrain/ */ -#if 0 - mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) - { - static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, - 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; - mz_uint32 crcu32 = (mz_uint32)crc; - if (!ptr) - return MZ_CRC32_INIT; - crcu32 = ~crcu32; - while (buf_len--) - { - mz_uint8 b = *ptr++; - crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; - crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; - } - return ~crcu32; - } -#elif defined(USE_EXTERNAL_MZCRC) -/* If USE_EXTERNAL_CRC is defined, an external module will export the - * mz_crc32() symbol for us to use, e.g. an SSE-accelerated version. - * Depending on the impl, it may be necessary to ~ the input/output crc values. - */ -mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len); -#else -/* Faster, but larger CPU cache footprint. - */ -mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) { - static const mz_uint32 s_crc_table[256] = { - 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, - 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, - 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, - 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, - 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, - 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, - 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, - 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, - 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, - 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, - 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, - 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, - 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, - 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, - 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, - 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, - 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, - 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, - 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, - 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, - 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, - 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, - 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, - 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, - 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, - 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, - 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, - 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, - 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, - 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, - 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, - 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, - 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, - 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, - 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, - 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, - 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, - 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, - 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, - 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, - 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, - 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, - 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D}; - - mz_uint32 crc32 = (mz_uint32)crc ^ 0xFFFFFFFF; - const mz_uint8 *pByte_buf = (const mz_uint8 *)ptr; - - while (buf_len >= 4) { - crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; - crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[1]) & 0xFF]; - crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[2]) & 0xFF]; - crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[3]) & 0xFF]; - pByte_buf += 4; - buf_len -= 4; - } - - while (buf_len) { - crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; - ++pByte_buf; - --buf_len; - } - - return ~crc32; -} -#endif - -void mz_free(void *p) { MZ_FREE(p); } - -MINIZ_EXPORT void *miniz_def_alloc_func(void *opaque, size_t items, - size_t size) { - (void)opaque, (void)items, (void)size; - return MZ_MALLOC(items * size); -} -MINIZ_EXPORT void miniz_def_free_func(void *opaque, void *address) { - (void)opaque, (void)address; - MZ_FREE(address); -} -MINIZ_EXPORT void *miniz_def_realloc_func(void *opaque, void *address, - size_t items, size_t size) { - (void)opaque, (void)address, (void)items, (void)size; - return MZ_REALLOC(address, items * size); -} - -const char *mz_version(void) { return MZ_VERSION; } - -#ifndef MINIZ_NO_ZLIB_APIS - -int mz_deflateInit(mz_streamp pStream, int level) { - return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, - MZ_DEFAULT_STRATEGY); -} - -int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, - int mem_level, int strategy) { - tdefl_compressor *pComp; - mz_uint comp_flags = - TDEFL_COMPUTE_ADLER32 | - tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); - - if (!pStream) - return MZ_STREAM_ERROR; - if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || - ((window_bits != MZ_DEFAULT_WINDOW_BITS) && - (-window_bits != MZ_DEFAULT_WINDOW_BITS))) - return MZ_PARAM_ERROR; - - pStream->data_type = 0; - pStream->adler = MZ_ADLER32_INIT; - pStream->msg = NULL; - pStream->reserved = 0; - pStream->total_in = 0; - pStream->total_out = 0; - if (!pStream->zalloc) - pStream->zalloc = miniz_def_alloc_func; - if (!pStream->zfree) - pStream->zfree = miniz_def_free_func; - - pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, - sizeof(tdefl_compressor)); - if (!pComp) - return MZ_MEM_ERROR; - - pStream->state = (struct mz_internal_state *)pComp; - - if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) { - mz_deflateEnd(pStream); - return MZ_PARAM_ERROR; - } - - return MZ_OK; -} - -int mz_deflateReset(mz_streamp pStream) { - if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || - (!pStream->zfree)) - return MZ_STREAM_ERROR; - pStream->total_in = pStream->total_out = 0; - tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, - ((tdefl_compressor *)pStream->state)->m_flags); - return MZ_OK; -} - -int mz_deflate(mz_streamp pStream, int flush) { - size_t in_bytes, out_bytes; - mz_ulong orig_total_in, orig_total_out; - int mz_status = MZ_OK; - - if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || - (!pStream->next_out)) - return MZ_STREAM_ERROR; - if (!pStream->avail_out) - return MZ_BUF_ERROR; - - if (flush == MZ_PARTIAL_FLUSH) - flush = MZ_SYNC_FLUSH; - - if (((tdefl_compressor *)pStream->state)->m_prev_return_status == - TDEFL_STATUS_DONE) - return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; - - orig_total_in = pStream->total_in; - orig_total_out = pStream->total_out; - for (;;) { - tdefl_status defl_status; - in_bytes = pStream->avail_in; - out_bytes = pStream->avail_out; - - defl_status = tdefl_compress((tdefl_compressor *)pStream->state, - pStream->next_in, &in_bytes, pStream->next_out, - &out_bytes, (tdefl_flush)flush); - pStream->next_in += (mz_uint)in_bytes; - pStream->avail_in -= (mz_uint)in_bytes; - pStream->total_in += (mz_uint)in_bytes; - pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); - - pStream->next_out += (mz_uint)out_bytes; - pStream->avail_out -= (mz_uint)out_bytes; - pStream->total_out += (mz_uint)out_bytes; - - if (defl_status < 0) { - mz_status = MZ_STREAM_ERROR; - break; - } else if (defl_status == TDEFL_STATUS_DONE) { - mz_status = MZ_STREAM_END; - break; - } else if (!pStream->avail_out) - break; - else if ((!pStream->avail_in) && (flush != MZ_FINISH)) { - if ((flush) || (pStream->total_in != orig_total_in) || - (pStream->total_out != orig_total_out)) - break; - return MZ_BUF_ERROR; /* Can't make forward progress without some input. - */ - } - } - return mz_status; -} - -int mz_deflateEnd(mz_streamp pStream) { - if (!pStream) - return MZ_STREAM_ERROR; - if (pStream->state) { - pStream->zfree(pStream->opaque, pStream->state); - pStream->state = NULL; - } - return MZ_OK; -} - -mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) { - (void)pStream; - /* This is really over conservative. (And lame, but it's actually pretty - * tricky to compute a true upper bound given the way tdefl's blocking works.) - */ - return MZ_MAX(128 + (source_len * 110) / 100, - 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); -} - -int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, - const unsigned char *pSource, mz_ulong source_len, int level) { - int status; - mz_stream stream; - memset(&stream, 0, sizeof(stream)); - - /* In case mz_ulong is 64-bits (argh I hate longs). */ - if ((source_len | *pDest_len) > 0xFFFFFFFFU) - return MZ_PARAM_ERROR; - - stream.next_in = pSource; - stream.avail_in = (mz_uint32)source_len; - stream.next_out = pDest; - stream.avail_out = (mz_uint32)*pDest_len; - - status = mz_deflateInit(&stream, level); - if (status != MZ_OK) - return status; - - status = mz_deflate(&stream, MZ_FINISH); - if (status != MZ_STREAM_END) { - mz_deflateEnd(&stream); - return (status == MZ_OK) ? MZ_BUF_ERROR : status; - } - - *pDest_len = stream.total_out; - return mz_deflateEnd(&stream); -} - -int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, - const unsigned char *pSource, mz_ulong source_len) { - return mz_compress2(pDest, pDest_len, pSource, source_len, - MZ_DEFAULT_COMPRESSION); -} - -mz_ulong mz_compressBound(mz_ulong source_len) { - return mz_deflateBound(NULL, source_len); -} - -typedef struct { - tinfl_decompressor m_decomp; - mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; - int m_window_bits; - mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; - tinfl_status m_last_status; -} inflate_state; - -int mz_inflateInit2(mz_streamp pStream, int window_bits) { - inflate_state *pDecomp; - if (!pStream) - return MZ_STREAM_ERROR; - if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && - (-window_bits != MZ_DEFAULT_WINDOW_BITS)) - return MZ_PARAM_ERROR; - - pStream->data_type = 0; - pStream->adler = 0; - pStream->msg = NULL; - pStream->total_in = 0; - pStream->total_out = 0; - pStream->reserved = 0; - if (!pStream->zalloc) - pStream->zalloc = miniz_def_alloc_func; - if (!pStream->zfree) - pStream->zfree = miniz_def_free_func; - - pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, - sizeof(inflate_state)); - if (!pDecomp) - return MZ_MEM_ERROR; - - pStream->state = (struct mz_internal_state *)pDecomp; - - tinfl_init(&pDecomp->m_decomp); - pDecomp->m_dict_ofs = 0; - pDecomp->m_dict_avail = 0; - pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; - pDecomp->m_first_call = 1; - pDecomp->m_has_flushed = 0; - pDecomp->m_window_bits = window_bits; - - return MZ_OK; -} - -int mz_inflateInit(mz_streamp pStream) { - return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); -} - -int mz_inflateReset(mz_streamp pStream) { - inflate_state *pDecomp; - if (!pStream) - return MZ_STREAM_ERROR; - - pStream->data_type = 0; - pStream->adler = 0; - pStream->msg = NULL; - pStream->total_in = 0; - pStream->total_out = 0; - pStream->reserved = 0; - - pDecomp = (inflate_state *)pStream->state; - - tinfl_init(&pDecomp->m_decomp); - pDecomp->m_dict_ofs = 0; - pDecomp->m_dict_avail = 0; - pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; - pDecomp->m_first_call = 1; - pDecomp->m_has_flushed = 0; - /* pDecomp->m_window_bits = window_bits */; - - return MZ_OK; -} - -int mz_inflate(mz_streamp pStream, int flush) { - inflate_state *pState; - mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; - size_t in_bytes, out_bytes, orig_avail_in; - tinfl_status status; - - if ((!pStream) || (!pStream->state)) - return MZ_STREAM_ERROR; - if (flush == MZ_PARTIAL_FLUSH) - flush = MZ_SYNC_FLUSH; - if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) - return MZ_STREAM_ERROR; - - pState = (inflate_state *)pStream->state; - if (pState->m_window_bits > 0) - decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; - orig_avail_in = pStream->avail_in; - - first_call = pState->m_first_call; - pState->m_first_call = 0; - if (pState->m_last_status < 0) - return MZ_DATA_ERROR; - - if (pState->m_has_flushed && (flush != MZ_FINISH)) - return MZ_STREAM_ERROR; - pState->m_has_flushed |= (flush == MZ_FINISH); - - if ((flush == MZ_FINISH) && (first_call)) { - /* MZ_FINISH on the first call implies that the input and output buffers are - * large enough to hold the entire compressed/decompressed file. */ - decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; - in_bytes = pStream->avail_in; - out_bytes = pStream->avail_out; - status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, - pStream->next_out, pStream->next_out, &out_bytes, - decomp_flags); - pState->m_last_status = status; - pStream->next_in += (mz_uint)in_bytes; - pStream->avail_in -= (mz_uint)in_bytes; - pStream->total_in += (mz_uint)in_bytes; - pStream->adler = tinfl_get_adler32(&pState->m_decomp); - pStream->next_out += (mz_uint)out_bytes; - pStream->avail_out -= (mz_uint)out_bytes; - pStream->total_out += (mz_uint)out_bytes; - - if (status < 0) - return MZ_DATA_ERROR; - else if (status != TINFL_STATUS_DONE) { - pState->m_last_status = TINFL_STATUS_FAILED; - return MZ_BUF_ERROR; - } - return MZ_STREAM_END; - } - /* flush != MZ_FINISH then we must assume there's more input. */ - if (flush != MZ_FINISH) - decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; - - if (pState->m_dict_avail) { - n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); - memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); - pStream->next_out += n; - pStream->avail_out -= n; - pStream->total_out += n; - pState->m_dict_avail -= n; - pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); - return ((pState->m_last_status == TINFL_STATUS_DONE) && - (!pState->m_dict_avail)) - ? MZ_STREAM_END - : MZ_OK; - } - - for (;;) { - in_bytes = pStream->avail_in; - out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; - - status = tinfl_decompress( - &pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, - pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); - pState->m_last_status = status; - - pStream->next_in += (mz_uint)in_bytes; - pStream->avail_in -= (mz_uint)in_bytes; - pStream->total_in += (mz_uint)in_bytes; - pStream->adler = tinfl_get_adler32(&pState->m_decomp); - - pState->m_dict_avail = (mz_uint)out_bytes; - - n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); - memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); - pStream->next_out += n; - pStream->avail_out -= n; - pStream->total_out += n; - pState->m_dict_avail -= n; - pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); - - if (status < 0) - return MZ_DATA_ERROR; /* Stream is corrupted (there could be some - uncompressed data left in the output dictionary - - oh well). */ - else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) - return MZ_BUF_ERROR; /* Signal caller that we can't make forward progress - without supplying more input or by setting flush - to MZ_FINISH. */ - else if (flush == MZ_FINISH) { - /* The output buffer MUST be large to hold the remaining uncompressed data - * when flush==MZ_FINISH. */ - if (status == TINFL_STATUS_DONE) - return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; - /* status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's - * at least 1 more byte on the way. If there's no more room left in the - * output buffer then something is wrong. */ - else if (!pStream->avail_out) - return MZ_BUF_ERROR; - } else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || - (!pStream->avail_out) || (pState->m_dict_avail)) - break; - } - - return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) - ? MZ_STREAM_END - : MZ_OK; -} - -int mz_inflateEnd(mz_streamp pStream) { - if (!pStream) - return MZ_STREAM_ERROR; - if (pStream->state) { - pStream->zfree(pStream->opaque, pStream->state); - pStream->state = NULL; - } - return MZ_OK; -} -int mz_uncompress2(unsigned char *pDest, mz_ulong *pDest_len, - const unsigned char *pSource, mz_ulong *pSource_len) { - mz_stream stream; - int status; - memset(&stream, 0, sizeof(stream)); - - /* In case mz_ulong is 64-bits (argh I hate longs). */ - if ((*pSource_len | *pDest_len) > 0xFFFFFFFFU) - return MZ_PARAM_ERROR; - - stream.next_in = pSource; - stream.avail_in = (mz_uint32)*pSource_len; - stream.next_out = pDest; - stream.avail_out = (mz_uint32)*pDest_len; - - status = mz_inflateInit(&stream); - if (status != MZ_OK) - return status; - - status = mz_inflate(&stream, MZ_FINISH); - *pSource_len = *pSource_len - stream.avail_in; - if (status != MZ_STREAM_END) { - mz_inflateEnd(&stream); - return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR - : status; - } - *pDest_len = stream.total_out; - - return mz_inflateEnd(&stream); -} - -int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, - const unsigned char *pSource, mz_ulong source_len) { - return mz_uncompress2(pDest, pDest_len, pSource, &source_len); -} - -const char *mz_error(int err) { - static struct { - int m_err; - const char *m_pDesc; - } s_error_descs[] = {{MZ_OK, ""}, - {MZ_STREAM_END, "stream end"}, - {MZ_NEED_DICT, "need dictionary"}, - {MZ_ERRNO, "file error"}, - {MZ_STREAM_ERROR, "stream error"}, - {MZ_DATA_ERROR, "data error"}, - {MZ_MEM_ERROR, "out of memory"}, - {MZ_BUF_ERROR, "buf error"}, - {MZ_VERSION_ERROR, "version error"}, - {MZ_PARAM_ERROR, "parameter error"}}; - mz_uint i; - for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) - if (s_error_descs[i].m_err == err) - return s_error_descs[i].m_pDesc; - return NULL; -} - -#endif /*MINIZ_NO_ZLIB_APIS */ - -#ifdef __cplusplus -} -#endif - -/* - This is free and unencumbered software released into the public domain. - - Anyone is free to copy, modify, publish, use, compile, sell, or - distribute this software, either in source code form or as a compiled - binary, for any purpose, commercial or non-commercial, and by any - means. - - In jurisdictions that recognize copyright laws, the author or authors - of this software dedicate any and all copyright interest in the - software to the public domain. We make this dedication for the benefit - of the public at large and to the detriment of our heirs and - successors. We intend this dedication to be an overt act of - relinquishment in perpetuity of all present and future rights to this - software under copyright law. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. - - For more information, please refer to -*/ -/************************************************************************** - * - * Copyright 2013-2014 RAD Game Tools and Valve Software - * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC - * All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - **************************************************************************/ - -#ifdef __cplusplus -extern "C" { -#endif - -/* ------------------- Low-level Compression (independent from all decompression - * API's) */ - -/* Purposely making these tables static for faster init and thread safety. */ -static const mz_uint16 s_tdefl_len_sym[256] = { - 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, - 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, - 272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, - 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, - 276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, - 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, - 278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279, - 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, - 280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281, - 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, - 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282, - 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, - 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283, - 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, - 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284, - 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, - 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, - 285}; - -static const mz_uint8 s_tdefl_len_extra[256] = { - 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0}; - -static const mz_uint8 s_tdefl_small_dist_sym[512] = { - 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, - 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, - 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, - 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, - 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, - 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, - 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, - 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, - 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, - 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, - 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, - 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, - 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, - 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, - 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, - 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, - 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, - 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, - 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, - 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17}; - -static const mz_uint8 s_tdefl_small_dist_extra[512] = { - 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, - 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, - 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, - 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, - 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, - 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}; - -static const mz_uint8 s_tdefl_large_dist_sym[128] = { - 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, - 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, - 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, - 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, - 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, - 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, - 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29}; - -static const mz_uint8 s_tdefl_large_dist_extra[128] = { - 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, - 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, - 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, - 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, - 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, - 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, - 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13}; - -/* Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted - * values. */ -typedef struct { - mz_uint16 m_key, m_sym_index; -} tdefl_sym_freq; -static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, - tdefl_sym_freq *pSyms0, - tdefl_sym_freq *pSyms1) { - mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; - tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; - MZ_CLEAR_OBJ(hist); - for (i = 0; i < num_syms; i++) { - mz_uint freq = pSyms0[i].m_key; - hist[freq & 0xFF]++; - hist[256 + ((freq >> 8) & 0xFF)]++; - } - while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) - total_passes--; - for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) { - const mz_uint32 *pHist = &hist[pass << 8]; - mz_uint offsets[256], cur_ofs = 0; - for (i = 0; i < 256; i++) { - offsets[i] = cur_ofs; - cur_ofs += pHist[i]; - } - for (i = 0; i < num_syms; i++) - pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = - pCur_syms[i]; - { - tdefl_sym_freq *t = pCur_syms; - pCur_syms = pNew_syms; - pNew_syms = t; - } - } - return pCur_syms; -} - -/* tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, - * alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. */ -static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) { - int root, leaf, next, avbl, used, dpth; - if (n == 0) - return; - else if (n == 1) { - A[0].m_key = 1; - return; - } - A[0].m_key += A[1].m_key; - root = 0; - leaf = 2; - for (next = 1; next < n - 1; next++) { - if (leaf >= n || A[root].m_key < A[leaf].m_key) { - A[next].m_key = A[root].m_key; - A[root++].m_key = (mz_uint16)next; - } else - A[next].m_key = A[leaf++].m_key; - if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) { - A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); - A[root++].m_key = (mz_uint16)next; - } else - A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); - } - A[n - 2].m_key = 0; - for (next = n - 3; next >= 0; next--) - A[next].m_key = A[A[next].m_key].m_key + 1; - avbl = 1; - used = dpth = 0; - root = n - 2; - next = n - 1; - while (avbl > 0) { - while (root >= 0 && (int)A[root].m_key == dpth) { - used++; - root--; - } - while (avbl > used) { - A[next--].m_key = (mz_uint16)(dpth); - avbl--; - } - avbl = 2 * used; - dpth++; - used = 0; - } -} - -/* Limits canonical Huffman code table's max code size. */ -enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; -static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, - int code_list_len, - int max_code_size) { - int i; - mz_uint32 total = 0; - if (code_list_len <= 1) - return; - for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) - pNum_codes[max_code_size] += pNum_codes[i]; - for (i = max_code_size; i > 0; i--) - total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); - while (total != (1UL << max_code_size)) { - pNum_codes[max_code_size]--; - for (i = max_code_size - 1; i > 0; i--) - if (pNum_codes[i]) { - pNum_codes[i]--; - pNum_codes[i + 1] += 2; - break; - } - total--; - } -} - -static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, - int table_len, int code_size_limit, - int static_table) { - int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; - mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; - MZ_CLEAR_OBJ(num_codes); - if (static_table) { - for (i = 0; i < table_len; i++) - num_codes[d->m_huff_code_sizes[table_num][i]]++; - } else { - tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], - *pSyms; - int num_used_syms = 0; - const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; - for (i = 0; i < table_len; i++) - if (pSym_count[i]) { - syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; - syms0[num_used_syms++].m_sym_index = (mz_uint16)i; - } - - pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); - tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); - - for (i = 0; i < num_used_syms; i++) - num_codes[pSyms[i].m_key]++; - - tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, - code_size_limit); - - MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); - MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); - for (i = 1, j = num_used_syms; i <= code_size_limit; i++) - for (l = num_codes[i]; l > 0; l--) - d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); - } - - next_code[1] = 0; - for (j = 0, i = 2; i <= code_size_limit; i++) - next_code[i] = j = ((j + num_codes[i - 1]) << 1); - - for (i = 0; i < table_len; i++) { - mz_uint rev_code = 0, code, code_size; - if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) - continue; - code = next_code[code_size]++; - for (l = code_size; l > 0; l--, code >>= 1) - rev_code = (rev_code << 1) | (code & 1); - d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; - } -} - -#define TDEFL_PUT_BITS(b, l) \ - do { \ - mz_uint bits = b; \ - mz_uint len = l; \ - MZ_ASSERT(bits <= ((1U << len) - 1U)); \ - d->m_bit_buffer |= (bits << d->m_bits_in); \ - d->m_bits_in += len; \ - while (d->m_bits_in >= 8) { \ - if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ - *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ - d->m_bit_buffer >>= 8; \ - d->m_bits_in -= 8; \ - } \ - } \ - MZ_MACRO_END - -#define TDEFL_RLE_PREV_CODE_SIZE() \ - { \ - if (rle_repeat_count) { \ - if (rle_repeat_count < 3) { \ - d->m_huff_count[2][prev_code_size] = \ - (mz_uint16)(d->m_huff_count[2][prev_code_size] + \ - rle_repeat_count); \ - while (rle_repeat_count--) \ - packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ - } else { \ - d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \ - packed_code_sizes[num_packed_code_sizes++] = 16; \ - packed_code_sizes[num_packed_code_sizes++] = \ - (mz_uint8)(rle_repeat_count - 3); \ - } \ - rle_repeat_count = 0; \ - } \ - } - -#define TDEFL_RLE_ZERO_CODE_SIZE() \ - { \ - if (rle_z_count) { \ - if (rle_z_count < 3) { \ - d->m_huff_count[2][0] = \ - (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \ - while (rle_z_count--) \ - packed_code_sizes[num_packed_code_sizes++] = 0; \ - } else if (rle_z_count <= 10) { \ - d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \ - packed_code_sizes[num_packed_code_sizes++] = 17; \ - packed_code_sizes[num_packed_code_sizes++] = \ - (mz_uint8)(rle_z_count - 3); \ - } else { \ - d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \ - packed_code_sizes[num_packed_code_sizes++] = 18; \ - packed_code_sizes[num_packed_code_sizes++] = \ - (mz_uint8)(rle_z_count - 11); \ - } \ - rle_z_count = 0; \ - } \ - } - -static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { - 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - -static void tdefl_start_dynamic_block(tdefl_compressor *d) { - int num_lit_codes, num_dist_codes, num_bit_lengths; - mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, - rle_repeat_count, packed_code_sizes_index; - mz_uint8 - code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], - packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], - prev_code_size = 0xFF; - - d->m_huff_count[0][256] = 1; - - tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); - tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); - - for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) - if (d->m_huff_code_sizes[0][num_lit_codes - 1]) - break; - for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) - if (d->m_huff_code_sizes[1][num_dist_codes - 1]) - break; - - memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); - memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], - num_dist_codes); - total_code_sizes_to_pack = num_lit_codes + num_dist_codes; - num_packed_code_sizes = 0; - rle_z_count = 0; - rle_repeat_count = 0; - - memset(&d->m_huff_count[2][0], 0, - sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); - for (i = 0; i < total_code_sizes_to_pack; i++) { - mz_uint8 code_size = code_sizes_to_pack[i]; - if (!code_size) { - TDEFL_RLE_PREV_CODE_SIZE(); - if (++rle_z_count == 138) { - TDEFL_RLE_ZERO_CODE_SIZE(); - } - } else { - TDEFL_RLE_ZERO_CODE_SIZE(); - if (code_size != prev_code_size) { - TDEFL_RLE_PREV_CODE_SIZE(); - d->m_huff_count[2][code_size] = - (mz_uint16)(d->m_huff_count[2][code_size] + 1); - packed_code_sizes[num_packed_code_sizes++] = code_size; - } else if (++rle_repeat_count == 6) { - TDEFL_RLE_PREV_CODE_SIZE(); - } - } - prev_code_size = code_size; - } - if (rle_repeat_count) { - TDEFL_RLE_PREV_CODE_SIZE(); - } else { - TDEFL_RLE_ZERO_CODE_SIZE(); - } - - tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); - - TDEFL_PUT_BITS(2, 2); - - TDEFL_PUT_BITS(num_lit_codes - 257, 5); - TDEFL_PUT_BITS(num_dist_codes - 1, 5); - - for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) - if (d->m_huff_code_sizes - [2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) - break; - num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); - TDEFL_PUT_BITS(num_bit_lengths - 4, 4); - for (i = 0; (int)i < num_bit_lengths; i++) - TDEFL_PUT_BITS( - d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); - - for (packed_code_sizes_index = 0; - packed_code_sizes_index < num_packed_code_sizes;) { - mz_uint code = packed_code_sizes[packed_code_sizes_index++]; - MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); - TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); - if (code >= 16) - TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], - "\02\03\07"[code - 16]); - } -} - -static void tdefl_start_static_block(tdefl_compressor *d) { - mz_uint i; - mz_uint8 *p = &d->m_huff_code_sizes[0][0]; - - for (i = 0; i <= 143; ++i) - *p++ = 8; - for (; i <= 255; ++i) - *p++ = 9; - for (; i <= 279; ++i) - *p++ = 7; - for (; i <= 287; ++i) - *p++ = 8; - - memset(d->m_huff_code_sizes[1], 5, 32); - - tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); - tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); - - TDEFL_PUT_BITS(1, 2); -} - -static const mz_uint mz_bitmasks[17] = { - 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, - 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF}; - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \ - MINIZ_HAS_64BIT_REGISTERS -static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { - mz_uint flags; - mz_uint8 *pLZ_codes; - mz_uint8 *pOutput_buf = d->m_pOutput_buf; - mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; - mz_uint64 bit_buffer = d->m_bit_buffer; - mz_uint bits_in = d->m_bits_in; - -#define TDEFL_PUT_BITS_FAST(b, l) \ - { \ - bit_buffer |= (((mz_uint64)(b)) << bits_in); \ - bits_in += (l); \ - } - - flags = 1; - for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; - flags >>= 1) { - if (flags == 1) - flags = *pLZ_codes++ | 0x100; - - if (flags & 1) { - mz_uint s0, s1, n0, n1, sym, num_extra_bits; - mz_uint match_len = pLZ_codes[0], - match_dist = *(const mz_uint16 *)(pLZ_codes + 1); - pLZ_codes += 3; - - MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], - d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); - TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], - s_tdefl_len_extra[match_len]); - - /* This sequence coaxes MSVC into using cmov's vs. jmp's. */ - s0 = s_tdefl_small_dist_sym[match_dist & 511]; - n0 = s_tdefl_small_dist_extra[match_dist & 511]; - s1 = s_tdefl_large_dist_sym[match_dist >> 8]; - n1 = s_tdefl_large_dist_extra[match_dist >> 8]; - sym = (match_dist < 512) ? s0 : s1; - num_extra_bits = (match_dist < 512) ? n0 : n1; - - MZ_ASSERT(d->m_huff_code_sizes[1][sym]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], - d->m_huff_code_sizes[1][sym]); - TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], - num_extra_bits); - } else { - mz_uint lit = *pLZ_codes++; - MZ_ASSERT(d->m_huff_code_sizes[0][lit]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], - d->m_huff_code_sizes[0][lit]); - - if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { - flags >>= 1; - lit = *pLZ_codes++; - MZ_ASSERT(d->m_huff_code_sizes[0][lit]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], - d->m_huff_code_sizes[0][lit]); - - if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { - flags >>= 1; - lit = *pLZ_codes++; - MZ_ASSERT(d->m_huff_code_sizes[0][lit]); - TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], - d->m_huff_code_sizes[0][lit]); - } - } - } - - if (pOutput_buf >= d->m_pOutput_buf_end) - return MZ_FALSE; - - *(mz_uint64 *)pOutput_buf = bit_buffer; - pOutput_buf += (bits_in >> 3); - bit_buffer >>= (bits_in & ~7); - bits_in &= 7; - } - -#undef TDEFL_PUT_BITS_FAST - - d->m_pOutput_buf = pOutput_buf; - d->m_bits_in = 0; - d->m_bit_buffer = 0; - - while (bits_in) { - mz_uint32 n = MZ_MIN(bits_in, 16); - TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); - bit_buffer >>= n; - bits_in -= n; - } - - TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); - - return (d->m_pOutput_buf < d->m_pOutput_buf_end); -} -#else -static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { - mz_uint flags; - mz_uint8 *pLZ_codes; - - flags = 1; - for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; - flags >>= 1) { - if (flags == 1) - flags = *pLZ_codes++ | 0x100; - if (flags & 1) { - mz_uint sym, num_extra_bits; - mz_uint match_len = pLZ_codes[0], - match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); - pLZ_codes += 3; - - MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); - TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], - d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); - TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], - s_tdefl_len_extra[match_len]); - - if (match_dist < 512) { - sym = s_tdefl_small_dist_sym[match_dist]; - num_extra_bits = s_tdefl_small_dist_extra[match_dist]; - } else { - sym = s_tdefl_large_dist_sym[match_dist >> 8]; - num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; - } - MZ_ASSERT(d->m_huff_code_sizes[1][sym]); - TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); - TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); - } else { - mz_uint lit = *pLZ_codes++; - MZ_ASSERT(d->m_huff_code_sizes[0][lit]); - TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); - } - } - - TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); - - return (d->m_pOutput_buf < d->m_pOutput_buf_end); -} -#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \ - MINIZ_HAS_64BIT_REGISTERS */ - -static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) { - if (static_block) - tdefl_start_static_block(d); - else - tdefl_start_dynamic_block(d); - return tdefl_compress_lz_codes(d); -} - -static int tdefl_flush_block(tdefl_compressor *d, int flush) { - mz_uint saved_bit_buf, saved_bits_in; - mz_uint8 *pSaved_output_buf; - mz_bool comp_block_succeeded = MZ_FALSE; - int n, use_raw_block = - ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && - (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; - mz_uint8 *pOutput_buf_start = - ((d->m_pPut_buf_func == NULL) && - ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) - ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) - : d->m_output_buf; - - d->m_pOutput_buf = pOutput_buf_start; - d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; - - MZ_ASSERT(!d->m_output_flush_remaining); - d->m_output_flush_ofs = 0; - d->m_output_flush_remaining = 0; - - *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); - d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); - - if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) { - TDEFL_PUT_BITS(0x78, 8); - TDEFL_PUT_BITS(0x01, 8); - } - - TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); - - pSaved_output_buf = d->m_pOutput_buf; - saved_bit_buf = d->m_bit_buffer; - saved_bits_in = d->m_bits_in; - - if (!use_raw_block) - comp_block_succeeded = - tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || - (d->m_total_lz_bytes < 48)); - - /* If the block gets expanded, forget the current contents of the output - * buffer and send a raw block instead. */ - if (((use_raw_block) || - ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= - d->m_total_lz_bytes))) && - ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) { - mz_uint i; - d->m_pOutput_buf = pSaved_output_buf; - d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; - TDEFL_PUT_BITS(0, 2); - if (d->m_bits_in) { - TDEFL_PUT_BITS(0, 8 - d->m_bits_in); - } - for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) { - TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); - } - for (i = 0; i < d->m_total_lz_bytes; ++i) { - TDEFL_PUT_BITS( - d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], - 8); - } - } - /* Check for the extremely unlikely (if not impossible) case of the compressed - block not fitting into the output buffer when using dynamic codes. */ - else if (!comp_block_succeeded) { - d->m_pOutput_buf = pSaved_output_buf; - d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; - tdefl_compress_block(d, MZ_TRUE); - } - - if (flush) { - if (flush == TDEFL_FINISH) { - if (d->m_bits_in) { - TDEFL_PUT_BITS(0, 8 - d->m_bits_in); - } - if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { - mz_uint i, a = d->m_adler32; - for (i = 0; i < 4; i++) { - TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); - a <<= 8; - } - } - } else { - mz_uint i, z = 0; - TDEFL_PUT_BITS(0, 3); - if (d->m_bits_in) { - TDEFL_PUT_BITS(0, 8 - d->m_bits_in); - } - for (i = 2; i; --i, z ^= 0xFFFF) { - TDEFL_PUT_BITS(z & 0xFFFF, 16); - } - } - } - - MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); - - memset(&d->m_huff_count[0][0], 0, - sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); - memset(&d->m_huff_count[1][0], 0, - sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); - - d->m_pLZ_code_buf = d->m_lz_code_buf + 1; - d->m_pLZ_flags = d->m_lz_code_buf; - d->m_num_flags_left = 8; - d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; - d->m_total_lz_bytes = 0; - d->m_block_index++; - - if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) { - if (d->m_pPut_buf_func) { - *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; - if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) - return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); - } else if (pOutput_buf_start == d->m_output_buf) { - int bytes_to_copy = (int)MZ_MIN( - (size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); - memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, - bytes_to_copy); - d->m_out_buf_ofs += bytes_to_copy; - if ((n -= bytes_to_copy) != 0) { - d->m_output_flush_ofs = bytes_to_copy; - d->m_output_flush_remaining = n; - } - } else { - d->m_out_buf_ofs += n; - } - } - - return d->m_output_flush_remaining; -} - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES -#ifdef MINIZ_UNALIGNED_USE_MEMCPY -static mz_uint16 TDEFL_READ_UNALIGNED_WORD(const mz_uint8 *p) { - mz_uint16 ret; - memcpy(&ret, p, sizeof(mz_uint16)); - return ret; -} -static mz_uint16 TDEFL_READ_UNALIGNED_WORD2(const mz_uint16 *p) { - mz_uint16 ret; - memcpy(&ret, p, sizeof(mz_uint16)); - return ret; -} -#else -#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p) -#define TDEFL_READ_UNALIGNED_WORD2(p) *(const mz_uint16 *)(p) -#endif -static MZ_FORCEINLINE void -tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, - mz_uint max_match_len, mz_uint *pMatch_dist, - mz_uint *pMatch_len) { - mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, - match_len = *pMatch_len, probe_pos = pos, next_probe_pos, - probe_len; - mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; - const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q; - mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), - s01 = TDEFL_READ_UNALIGNED_WORD2(s); - MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); - if (max_match_len <= match_len) - return; - for (;;) { - for (;;) { - if (--num_probes_left == 0) - return; -#define TDEFL_PROBE \ - next_probe_pos = d->m_next[probe_pos]; \ - if ((!next_probe_pos) || \ - ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ - return; \ - probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ - if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ - break; - TDEFL_PROBE; - TDEFL_PROBE; - TDEFL_PROBE; - } - if (!dist) - break; - q = (const mz_uint16 *)(d->m_dict + probe_pos); - if (TDEFL_READ_UNALIGNED_WORD2(q) != s01) - continue; - p = s; - probe_len = 32; - do { - } while ( - (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && - (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && - (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && - (TDEFL_READ_UNALIGNED_WORD2(++p) == TDEFL_READ_UNALIGNED_WORD2(++q)) && - (--probe_len > 0)); - if (!probe_len) { - *pMatch_dist = dist; - *pMatch_len = MZ_MIN(max_match_len, (mz_uint)TDEFL_MAX_MATCH_LEN); - break; - } else if ((probe_len = ((mz_uint)(p - s) * 2) + - (mz_uint)(*(const mz_uint8 *)p == - *(const mz_uint8 *)q)) > match_len) { - *pMatch_dist = dist; - if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == - max_match_len) - break; - c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); - } - } -} -#else -static MZ_FORCEINLINE void -tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, - mz_uint max_match_len, mz_uint *pMatch_dist, - mz_uint *pMatch_len) { - mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, - match_len = *pMatch_len, probe_pos = pos, next_probe_pos, - probe_len; - mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; - const mz_uint8 *s = d->m_dict + pos, *p, *q; - mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; - MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); - if (max_match_len <= match_len) - return; - for (;;) { - for (;;) { - if (--num_probes_left == 0) - return; -#define TDEFL_PROBE \ - next_probe_pos = d->m_next[probe_pos]; \ - if ((!next_probe_pos) || \ - ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ - return; \ - probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ - if ((d->m_dict[probe_pos + match_len] == c0) && \ - (d->m_dict[probe_pos + match_len - 1] == c1)) \ - break; - TDEFL_PROBE; - TDEFL_PROBE; - TDEFL_PROBE; - } - if (!dist) - break; - p = s; - q = d->m_dict + probe_pos; - for (probe_len = 0; probe_len < max_match_len; probe_len++) - if (*p++ != *q++) - break; - if (probe_len > match_len) { - *pMatch_dist = dist; - if ((*pMatch_len = match_len = probe_len) == max_match_len) - return; - c0 = d->m_dict[pos + match_len]; - c1 = d->m_dict[pos + match_len - 1]; - } - } -} -#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES */ - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN -#ifdef MINIZ_UNALIGNED_USE_MEMCPY -static mz_uint32 TDEFL_READ_UNALIGNED_WORD32(const mz_uint8 *p) { - mz_uint32 ret; - memcpy(&ret, p, sizeof(mz_uint32)); - return ret; -} -#else -#define TDEFL_READ_UNALIGNED_WORD32(p) *(const mz_uint32 *)(p) -#endif -static mz_bool tdefl_compress_fast(tdefl_compressor *d) { - /* Faster, minimally featured LZRW1-style match+parse loop with better - * register utilization. Intended for applications where raw throughput is - * valued more highly than ratio. */ - mz_uint lookahead_pos = d->m_lookahead_pos, - lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, - total_lz_bytes = d->m_total_lz_bytes, - num_flags_left = d->m_num_flags_left; - mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; - mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; - - while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) { - const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; - mz_uint dst_pos = - (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; - mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( - d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); - d->m_src_buf_left -= num_bytes_to_process; - lookahead_size += num_bytes_to_process; - - while (num_bytes_to_process) { - mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); - memcpy(d->m_dict + dst_pos, d->m_pSrc, n); - if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) - memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, - MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); - d->m_pSrc += n; - dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; - num_bytes_to_process -= n; - } - - dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); - if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) - break; - - while (lookahead_size >= 4) { - mz_uint cur_match_dist, cur_match_len = 1; - mz_uint8 *pCur_dict = d->m_dict + cur_pos; - mz_uint first_trigram = TDEFL_READ_UNALIGNED_WORD32(pCur_dict) & 0xFFFFFF; - mz_uint hash = - (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & - TDEFL_LEVEL1_HASH_SIZE_MASK; - mz_uint probe_pos = d->m_hash[hash]; - d->m_hash[hash] = (mz_uint16)lookahead_pos; - - if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= - dict_size) && - ((TDEFL_READ_UNALIGNED_WORD32( - d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & - 0xFFFFFF) == first_trigram)) { - const mz_uint16 *p = (const mz_uint16 *)pCur_dict; - const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); - mz_uint32 probe_len = 32; - do { - } while ((TDEFL_READ_UNALIGNED_WORD2(++p) == - TDEFL_READ_UNALIGNED_WORD2(++q)) && - (TDEFL_READ_UNALIGNED_WORD2(++p) == - TDEFL_READ_UNALIGNED_WORD2(++q)) && - (TDEFL_READ_UNALIGNED_WORD2(++p) == - TDEFL_READ_UNALIGNED_WORD2(++q)) && - (TDEFL_READ_UNALIGNED_WORD2(++p) == - TDEFL_READ_UNALIGNED_WORD2(++q)) && - (--probe_len > 0)); - cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + - (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); - if (!probe_len) - cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; - - if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || - ((cur_match_len == TDEFL_MIN_MATCH_LEN) && - (cur_match_dist >= 8U * 1024U))) { - cur_match_len = 1; - *pLZ_code_buf++ = (mz_uint8)first_trigram; - *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); - d->m_huff_count[0][(mz_uint8)first_trigram]++; - } else { - mz_uint32 s0, s1; - cur_match_len = MZ_MIN(cur_match_len, lookahead_size); - - MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && - (cur_match_dist >= 1) && - (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); - - cur_match_dist--; - - pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); -#ifdef MINIZ_UNALIGNED_USE_MEMCPY - memcpy(&pLZ_code_buf[1], &cur_match_dist, sizeof(cur_match_dist)); -#else - *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; -#endif - pLZ_code_buf += 3; - *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); - - s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; - s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; - d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; - - d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - - TDEFL_MIN_MATCH_LEN]]++; - } - } else { - *pLZ_code_buf++ = (mz_uint8)first_trigram; - *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); - d->m_huff_count[0][(mz_uint8)first_trigram]++; - } - - if (--num_flags_left == 0) { - num_flags_left = 8; - pLZ_flags = pLZ_code_buf++; - } - - total_lz_bytes += cur_match_len; - lookahead_pos += cur_match_len; - dict_size = - MZ_MIN(dict_size + cur_match_len, (mz_uint)TDEFL_LZ_DICT_SIZE); - cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; - MZ_ASSERT(lookahead_size >= cur_match_len); - lookahead_size -= cur_match_len; - - if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { - int n; - d->m_lookahead_pos = lookahead_pos; - d->m_lookahead_size = lookahead_size; - d->m_dict_size = dict_size; - d->m_total_lz_bytes = total_lz_bytes; - d->m_pLZ_code_buf = pLZ_code_buf; - d->m_pLZ_flags = pLZ_flags; - d->m_num_flags_left = num_flags_left; - if ((n = tdefl_flush_block(d, 0)) != 0) - return (n < 0) ? MZ_FALSE : MZ_TRUE; - total_lz_bytes = d->m_total_lz_bytes; - pLZ_code_buf = d->m_pLZ_code_buf; - pLZ_flags = d->m_pLZ_flags; - num_flags_left = d->m_num_flags_left; - } - } - - while (lookahead_size) { - mz_uint8 lit = d->m_dict[cur_pos]; - - total_lz_bytes++; - *pLZ_code_buf++ = lit; - *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); - if (--num_flags_left == 0) { - num_flags_left = 8; - pLZ_flags = pLZ_code_buf++; - } - - d->m_huff_count[0][lit]++; - - lookahead_pos++; - dict_size = MZ_MIN(dict_size + 1, (mz_uint)TDEFL_LZ_DICT_SIZE); - cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; - lookahead_size--; - - if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { - int n; - d->m_lookahead_pos = lookahead_pos; - d->m_lookahead_size = lookahead_size; - d->m_dict_size = dict_size; - d->m_total_lz_bytes = total_lz_bytes; - d->m_pLZ_code_buf = pLZ_code_buf; - d->m_pLZ_flags = pLZ_flags; - d->m_num_flags_left = num_flags_left; - if ((n = tdefl_flush_block(d, 0)) != 0) - return (n < 0) ? MZ_FALSE : MZ_TRUE; - total_lz_bytes = d->m_total_lz_bytes; - pLZ_code_buf = d->m_pLZ_code_buf; - pLZ_flags = d->m_pLZ_flags; - num_flags_left = d->m_num_flags_left; - } - } - } - - d->m_lookahead_pos = lookahead_pos; - d->m_lookahead_size = lookahead_size; - d->m_dict_size = dict_size; - d->m_total_lz_bytes = total_lz_bytes; - d->m_pLZ_code_buf = pLZ_code_buf; - d->m_pLZ_flags = pLZ_flags; - d->m_num_flags_left = num_flags_left; - return MZ_TRUE; -} -#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ - -static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, - mz_uint8 lit) { - d->m_total_lz_bytes++; - *d->m_pLZ_code_buf++ = lit; - *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); - if (--d->m_num_flags_left == 0) { - d->m_num_flags_left = 8; - d->m_pLZ_flags = d->m_pLZ_code_buf++; - } - d->m_huff_count[0][lit]++; -} - -static MZ_FORCEINLINE void -tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) { - mz_uint32 s0, s1; - - MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && - (match_dist <= TDEFL_LZ_DICT_SIZE)); - - d->m_total_lz_bytes += match_len; - - d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); - - match_dist -= 1; - d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); - d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); - d->m_pLZ_code_buf += 3; - - *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); - if (--d->m_num_flags_left == 0) { - d->m_num_flags_left = 8; - d->m_pLZ_flags = d->m_pLZ_code_buf++; - } - - s0 = s_tdefl_small_dist_sym[match_dist & 511]; - s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; - d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; - d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; -} - -static mz_bool tdefl_compress_normal(tdefl_compressor *d) { - const mz_uint8 *pSrc = d->m_pSrc; - size_t src_buf_left = d->m_src_buf_left; - tdefl_flush flush = d->m_flush; - - while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) { - mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; - /* Update dictionary and hash chains. Keeps the lookahead size equal to - * TDEFL_MAX_MATCH_LEN. */ - if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) { - mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & - TDEFL_LZ_DICT_SIZE_MASK, - ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; - mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] - << TDEFL_LZ_HASH_SHIFT) ^ - d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; - mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( - src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); - const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; - src_buf_left -= num_bytes_to_process; - d->m_lookahead_size += num_bytes_to_process; - while (pSrc != pSrc_end) { - mz_uint8 c = *pSrc++; - d->m_dict[dst_pos] = c; - if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) - d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; - hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); - d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; - d->m_hash[hash] = (mz_uint16)(ins_pos); - dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; - ins_pos++; - } - } else { - while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) { - mz_uint8 c = *pSrc++; - mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & - TDEFL_LZ_DICT_SIZE_MASK; - src_buf_left--; - d->m_dict[dst_pos] = c; - if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) - d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; - if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) { - mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; - mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] - << (TDEFL_LZ_HASH_SHIFT * 2)) ^ - (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] - << TDEFL_LZ_HASH_SHIFT) ^ - c) & - (TDEFL_LZ_HASH_SIZE - 1); - d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; - d->m_hash[hash] = (mz_uint16)(ins_pos); - } - } - } - d->m_dict_size = - MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); - if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) - break; - - /* Simple lazy/greedy parsing state machine. */ - len_to_move = 1; - cur_match_dist = 0; - cur_match_len = - d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); - cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; - if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) { - if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) { - mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; - cur_match_len = 0; - while (cur_match_len < d->m_lookahead_size) { - if (d->m_dict[cur_pos + cur_match_len] != c) - break; - cur_match_len++; - } - if (cur_match_len < TDEFL_MIN_MATCH_LEN) - cur_match_len = 0; - else - cur_match_dist = 1; - } - } else { - tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, - d->m_lookahead_size, &cur_match_dist, &cur_match_len); - } - if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && - (cur_match_dist >= 8U * 1024U)) || - (cur_pos == cur_match_dist) || - ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) { - cur_match_dist = cur_match_len = 0; - } - if (d->m_saved_match_len) { - if (cur_match_len > d->m_saved_match_len) { - tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); - if (cur_match_len >= 128) { - tdefl_record_match(d, cur_match_len, cur_match_dist); - d->m_saved_match_len = 0; - len_to_move = cur_match_len; - } else { - d->m_saved_lit = d->m_dict[cur_pos]; - d->m_saved_match_dist = cur_match_dist; - d->m_saved_match_len = cur_match_len; - } - } else { - tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); - len_to_move = d->m_saved_match_len - 1; - d->m_saved_match_len = 0; - } - } else if (!cur_match_dist) - tdefl_record_literal(d, - d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); - else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || - (cur_match_len >= 128)) { - tdefl_record_match(d, cur_match_len, cur_match_dist); - len_to_move = cur_match_len; - } else { - d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; - d->m_saved_match_dist = cur_match_dist; - d->m_saved_match_len = cur_match_len; - } - /* Move the lookahead forward by len_to_move bytes. */ - d->m_lookahead_pos += len_to_move; - MZ_ASSERT(d->m_lookahead_size >= len_to_move); - d->m_lookahead_size -= len_to_move; - d->m_dict_size = - MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE); - /* Check if it's time to flush the current LZ codes to the internal output - * buffer. */ - if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || - ((d->m_total_lz_bytes > 31 * 1024) && - (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= - d->m_total_lz_bytes) || - (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) { - int n; - d->m_pSrc = pSrc; - d->m_src_buf_left = src_buf_left; - if ((n = tdefl_flush_block(d, 0)) != 0) - return (n < 0) ? MZ_FALSE : MZ_TRUE; - } - } - - d->m_pSrc = pSrc; - d->m_src_buf_left = src_buf_left; - return MZ_TRUE; -} - -static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) { - if (d->m_pIn_buf_size) { - *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; - } - - if (d->m_pOut_buf_size) { - size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, - d->m_output_flush_remaining); - memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, - d->m_output_buf + d->m_output_flush_ofs, n); - d->m_output_flush_ofs += (mz_uint)n; - d->m_output_flush_remaining -= (mz_uint)n; - d->m_out_buf_ofs += n; - - *d->m_pOut_buf_size = d->m_out_buf_ofs; - } - - return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE - : TDEFL_STATUS_OKAY; -} - -tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, - size_t *pIn_buf_size, void *pOut_buf, - size_t *pOut_buf_size, tdefl_flush flush) { - if (!d) { - if (pIn_buf_size) - *pIn_buf_size = 0; - if (pOut_buf_size) - *pOut_buf_size = 0; - return TDEFL_STATUS_BAD_PARAM; - } - - d->m_pIn_buf = pIn_buf; - d->m_pIn_buf_size = pIn_buf_size; - d->m_pOut_buf = pOut_buf; - d->m_pOut_buf_size = pOut_buf_size; - d->m_pSrc = (const mz_uint8 *)(pIn_buf); - d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; - d->m_out_buf_ofs = 0; - d->m_flush = flush; - - if (((d->m_pPut_buf_func != NULL) == - ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || - (d->m_prev_return_status != TDEFL_STATUS_OKAY) || - (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || - (pIn_buf_size && *pIn_buf_size && !pIn_buf) || - (pOut_buf_size && *pOut_buf_size && !pOut_buf)) { - if (pIn_buf_size) - *pIn_buf_size = 0; - if (pOut_buf_size) - *pOut_buf_size = 0; - return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); - } - d->m_wants_to_finish |= (flush == TDEFL_FINISH); - - if ((d->m_output_flush_remaining) || (d->m_finished)) - return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); - -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN - if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && - ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && - ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | - TDEFL_RLE_MATCHES)) == 0)) { - if (!tdefl_compress_fast(d)) - return d->m_prev_return_status; - } else -#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ - { - if (!tdefl_compress_normal(d)) - return d->m_prev_return_status; - } - - if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && - (pIn_buf)) - d->m_adler32 = - (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, - d->m_pSrc - (const mz_uint8 *)pIn_buf); - - if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && - (!d->m_output_flush_remaining)) { - if (tdefl_flush_block(d, flush) < 0) - return d->m_prev_return_status; - d->m_finished = (flush == TDEFL_FINISH); - if (flush == TDEFL_FULL_FLUSH) { - MZ_CLEAR_OBJ(d->m_hash); - MZ_CLEAR_OBJ(d->m_next); - d->m_dict_size = 0; - } - } - - return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); -} - -tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, - size_t in_buf_size, tdefl_flush flush) { - MZ_ASSERT(d->m_pPut_buf_func); - return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); -} - -tdefl_status tdefl_init(tdefl_compressor *d, - tdefl_put_buf_func_ptr pPut_buf_func, - void *pPut_buf_user, int flags) { - d->m_pPut_buf_func = pPut_buf_func; - d->m_pPut_buf_user = pPut_buf_user; - d->m_flags = (mz_uint)(flags); - d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; - d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; - d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; - if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) - MZ_CLEAR_OBJ(d->m_hash); - d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = - d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; - d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = - d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; - d->m_pLZ_code_buf = d->m_lz_code_buf + 1; - d->m_pLZ_flags = d->m_lz_code_buf; - *d->m_pLZ_flags = 0; - d->m_num_flags_left = 8; - d->m_pOutput_buf = d->m_output_buf; - d->m_pOutput_buf_end = d->m_output_buf; - d->m_prev_return_status = TDEFL_STATUS_OKAY; - d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; - d->m_adler32 = 1; - d->m_pIn_buf = NULL; - d->m_pOut_buf = NULL; - d->m_pIn_buf_size = NULL; - d->m_pOut_buf_size = NULL; - d->m_flush = TDEFL_NO_FLUSH; - d->m_pSrc = NULL; - d->m_src_buf_left = 0; - d->m_out_buf_ofs = 0; - if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) - MZ_CLEAR_OBJ(d->m_dict); - memset(&d->m_huff_count[0][0], 0, - sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); - memset(&d->m_huff_count[1][0], 0, - sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); - return TDEFL_STATUS_OKAY; -} - -tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) { - return d->m_prev_return_status; -} - -mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; } - -mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, - tdefl_put_buf_func_ptr pPut_buf_func, - void *pPut_buf_user, int flags) { - tdefl_compressor *pComp; - mz_bool succeeded; - if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) - return MZ_FALSE; - pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); - if (!pComp) - return MZ_FALSE; - succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == - TDEFL_STATUS_OKAY); - succeeded = - succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == - TDEFL_STATUS_DONE); - MZ_FREE(pComp); - return succeeded; -} - -typedef struct { - size_t m_size, m_capacity; - mz_uint8 *m_pBuf; - mz_bool m_expandable; -} tdefl_output_buffer; - -static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, - void *pUser) { - tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; - size_t new_size = p->m_size + len; - if (new_size > p->m_capacity) { - size_t new_capacity = p->m_capacity; - mz_uint8 *pNew_buf; - if (!p->m_expandable) - return MZ_FALSE; - do { - new_capacity = MZ_MAX(128U, new_capacity << 1U); - } while (new_size > new_capacity); - pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity); - if (!pNew_buf) - return MZ_FALSE; - p->m_pBuf = pNew_buf; - p->m_capacity = new_capacity; - } - memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len); - p->m_size = new_size; - return MZ_TRUE; -} - -void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, - size_t *pOut_len, int flags) { - tdefl_output_buffer out_buf; - MZ_CLEAR_OBJ(out_buf); - if (!pOut_len) - return MZ_FALSE; - else - *pOut_len = 0; - out_buf.m_expandable = MZ_TRUE; - if (!tdefl_compress_mem_to_output( - pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) - return NULL; - *pOut_len = out_buf.m_size; - return out_buf.m_pBuf; -} - -size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, - const void *pSrc_buf, size_t src_buf_len, - int flags) { - tdefl_output_buffer out_buf; - MZ_CLEAR_OBJ(out_buf); - if (!pOut_buf) - return 0; - out_buf.m_pBuf = (mz_uint8 *)pOut_buf; - out_buf.m_capacity = out_buf_len; - if (!tdefl_compress_mem_to_output( - pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) - return 0; - return out_buf.m_size; -} - -static const mz_uint s_tdefl_num_probes[11] = {0, 1, 6, 32, 16, 32, - 128, 256, 512, 768, 1500}; - -/* level may actually range from [0,10] (10 is a "hidden" max level, where we - * want a bit more compression and it's fine if throughput to fall off a cliff - * on some files). */ -mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, - int strategy) { - mz_uint comp_flags = - s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | - ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); - if (window_bits > 0) - comp_flags |= TDEFL_WRITE_ZLIB_HEADER; - - if (!level) - comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; - else if (strategy == MZ_FILTERED) - comp_flags |= TDEFL_FILTER_MATCHES; - else if (strategy == MZ_HUFFMAN_ONLY) - comp_flags &= ~TDEFL_MAX_PROBES_MASK; - else if (strategy == MZ_FIXED) - comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; - else if (strategy == MZ_RLE) - comp_flags |= TDEFL_RLE_MATCHES; - - return comp_flags; -} - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4204) /* nonstandard extension used : non-constant \ - aggregate initializer (also supported by \ - GNU C and C99, so no big deal) */ -#endif - -/* Simple PNG writer function by Alex Evans, 2011. Released into the public - domain: https://gist.github.com/908299, more context at - http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. - This is actually a modification of Alex's original code so PNG files generated - by this function pass pngcheck. */ -void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, - int h, int num_chans, - size_t *pLen_out, - mz_uint level, mz_bool flip) { - /* Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was - * defined. */ - static const mz_uint s_tdefl_png_num_probes[11] = { - 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500}; - tdefl_compressor *pComp = - (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); - tdefl_output_buffer out_buf; - int i, bpl = w * num_chans, y, z; - mz_uint32 c; - *pLen_out = 0; - if (!pComp) - return NULL; - MZ_CLEAR_OBJ(out_buf); - out_buf.m_expandable = MZ_TRUE; - out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); - if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) { - MZ_FREE(pComp); - return NULL; - } - /* write dummy header */ - for (z = 41; z; --z) - tdefl_output_buffer_putter(&z, 1, &out_buf); - /* compress image data */ - tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, - s_tdefl_png_num_probes[MZ_MIN(10, level)] | - TDEFL_WRITE_ZLIB_HEADER); - for (y = 0; y < h; ++y) { - tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); - tdefl_compress_buffer(pComp, - (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, - bpl, TDEFL_NO_FLUSH); - } - if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != - TDEFL_STATUS_DONE) { - MZ_FREE(pComp); - MZ_FREE(out_buf.m_pBuf); - return NULL; - } - /* write real header */ - *pLen_out = out_buf.m_size - 41; - { - static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06}; - mz_uint8 pnghdr[41] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, - 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x49, 0x44, 0x41, 0x54}; - pnghdr[18] = (mz_uint8)(w >> 8); - pnghdr[19] = (mz_uint8)w; - pnghdr[22] = (mz_uint8)(h >> 8); - pnghdr[23] = (mz_uint8)h; - pnghdr[25] = chans[num_chans]; - pnghdr[33] = (mz_uint8)(*pLen_out >> 24); - pnghdr[34] = (mz_uint8)(*pLen_out >> 16); - pnghdr[35] = (mz_uint8)(*pLen_out >> 8); - pnghdr[36] = (mz_uint8)*pLen_out; - c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); - for (i = 0; i < 4; ++i, c <<= 8) - ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); - memcpy(out_buf.m_pBuf, pnghdr, 41); - } - /* write footer (IDAT CRC-32, followed by IEND chunk) */ - if (!tdefl_output_buffer_putter( - "\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { - *pLen_out = 0; - MZ_FREE(pComp); - MZ_FREE(out_buf.m_pBuf); - return NULL; - } - c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, - *pLen_out + 4); - for (i = 0; i < 4; ++i, c <<= 8) - (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); - /* compute final size of file, grab compressed data buffer and return */ - *pLen_out += 57; - MZ_FREE(pComp); - return out_buf.m_pBuf; -} -void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, - int num_chans, size_t *pLen_out) { - /* Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we - * can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's - * where #defined out) */ - return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, - pLen_out, 6, MZ_FALSE); -} - -#ifndef MINIZ_NO_MALLOC -/* Allocate the tdefl_compressor and tinfl_decompressor structures in C so that - */ -/* non-C language bindings to tdefL_ and tinfl_ API don't need to worry about */ -/* structure size and allocation mechanism. */ -tdefl_compressor *tdefl_compressor_alloc() { - return (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); -} - -void tdefl_compressor_free(tdefl_compressor *pComp) { MZ_FREE(pComp); } -#endif - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -#ifdef __cplusplus -} -#endif -/************************************************************************** - * - * Copyright 2013-2014 RAD Game Tools and Valve Software - * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC - * All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - **************************************************************************/ - -#ifdef __cplusplus -extern "C" { -#endif - -/* ------------------- Low-level Decompression (completely independent from all - * compression API's) */ - -#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) -#define TINFL_MEMSET(p, c, l) memset(p, c, l) - -#define TINFL_CR_BEGIN \ - switch (r->m_state) { \ - case 0: -#define TINFL_CR_RETURN(state_index, result) \ - do { \ - status = result; \ - r->m_state = state_index; \ - goto common_exit; \ - case state_index:; \ - } \ - MZ_MACRO_END -#define TINFL_CR_RETURN_FOREVER(state_index, result) \ - do { \ - for (;;) { \ - TINFL_CR_RETURN(state_index, result); \ - } \ - } \ - MZ_MACRO_END -#define TINFL_CR_FINISH } - -#define TINFL_GET_BYTE(state_index, c) \ - do { \ - while (pIn_buf_cur >= pIn_buf_end) { \ - TINFL_CR_RETURN(state_index, \ - (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) \ - ? TINFL_STATUS_NEEDS_MORE_INPUT \ - : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); \ - } \ - c = *pIn_buf_cur++; \ - } \ - MZ_MACRO_END - -#define TINFL_NEED_BITS(state_index, n) \ - do { \ - mz_uint c; \ - TINFL_GET_BYTE(state_index, c); \ - bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ - num_bits += 8; \ - } while (num_bits < (mz_uint)(n)) -#define TINFL_SKIP_BITS(state_index, n) \ - do { \ - if (num_bits < (mz_uint)(n)) { \ - TINFL_NEED_BITS(state_index, n); \ - } \ - bit_buf >>= (n); \ - num_bits -= (n); \ - } \ - MZ_MACRO_END -#define TINFL_GET_BITS(state_index, b, n) \ - do { \ - if (num_bits < (mz_uint)(n)) { \ - TINFL_NEED_BITS(state_index, n); \ - } \ - b = bit_buf & ((1 << (n)) - 1); \ - bit_buf >>= (n); \ - num_bits -= (n); \ - } \ - MZ_MACRO_END - -/* TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes - * remaining in the input buffer falls below 2. */ -/* It reads just enough bytes from the input stream that are needed to decode - * the next Huffman code (and absolutely no more). It works by trying to fully - * decode a */ -/* Huffman code by using whatever bits are currently present in the bit buffer. - * If this fails, it reads another byte, and tries again until it succeeds or - * until the */ -/* bit buffer contains >=15 bits (deflate's max. Huffman code size). */ -#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ - do { \ - temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ - if (temp >= 0) { \ - code_len = temp >> 9; \ - if ((code_len) && (num_bits >= code_len)) \ - break; \ - } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ - code_len = TINFL_FAST_LOOKUP_BITS; \ - do { \ - temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ - } while ((temp < 0) && (num_bits >= (code_len + 1))); \ - if (temp >= 0) \ - break; \ - } \ - TINFL_GET_BYTE(state_index, c); \ - bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ - num_bits += 8; \ - } while (num_bits < 15); - -/* TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex - * than you would initially expect because the zlib API expects the decompressor - * to never read */ -/* beyond the final byte of the deflate stream. (In other words, when this macro - * wants to read another byte from the input, it REALLY needs another byte in - * order to fully */ -/* decode the next Huffman code.) Handling this properly is particularly - * important on raw deflate (non-zlib) streams, which aren't followed by a byte - * aligned adler-32. */ -/* The slow path is only executed at the very end of the input buffer. */ -/* v1.16: The original macro handled the case at the very end of the passed-in - * input buffer, but we also need to handle the case where the user passes in - * 1+zillion bytes */ -/* following the deflate data and our non-conservative read-ahead path won't - * kick in here on this code. This is much trickier. */ -#define TINFL_HUFF_DECODE(state_index, sym, pHuff) \ - do { \ - int temp; \ - mz_uint code_len, c; \ - if (num_bits < 15) { \ - if ((pIn_buf_end - pIn_buf_cur) < 2) { \ - TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ - } else { \ - bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | \ - (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \ - pIn_buf_cur += 2; \ - num_bits += 16; \ - } \ - } \ - if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= \ - 0) \ - code_len = temp >> 9, temp &= 511; \ - else { \ - code_len = TINFL_FAST_LOOKUP_BITS; \ - do { \ - temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ - } while (temp < 0); \ - } \ - sym = temp; \ - bit_buf >>= code_len; \ - num_bits -= code_len; \ - } \ - MZ_MACRO_END - -tinfl_status tinfl_decompress(tinfl_decompressor *r, - const mz_uint8 *pIn_buf_next, - size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, - mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, - const mz_uint32 decomp_flags) { - static const int s_length_base[31] = { - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; - static const int s_length_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, - 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, - 4, 4, 5, 5, 5, 5, 0, 0, 0}; - static const int s_dist_base[32] = { - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, - 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, - 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0}; - static const int s_dist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, - 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, - 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; - static const mz_uint8 s_length_dezigzag[19] = { - 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - static const int s_min_table_sizes[3] = {257, 1, 4}; - - tinfl_status status = TINFL_STATUS_FAILED; - mz_uint32 num_bits, dist, counter, num_extra; - tinfl_bit_buf_t bit_buf; - const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = - pIn_buf_next + *pIn_buf_size; - mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = - pOut_buf_next + *pOut_buf_size; - size_t out_buf_size_mask = - (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) - ? (size_t)-1 - : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, - dist_from_out_buf_start; - - /* Ensure the output buffer's size is a power of 2, unless the output buffer - * is large enough to hold the entire output file (in which case it doesn't - * matter). */ - if (((out_buf_size_mask + 1) & out_buf_size_mask) || - (pOut_buf_next < pOut_buf_start)) { - *pIn_buf_size = *pOut_buf_size = 0; - return TINFL_STATUS_BAD_PARAM; - } - - num_bits = r->m_num_bits; - bit_buf = r->m_bit_buf; - dist = r->m_dist; - counter = r->m_counter; - num_extra = r->m_num_extra; - dist_from_out_buf_start = r->m_dist_from_out_buf_start; - TINFL_CR_BEGIN - - bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; - r->m_z_adler32 = r->m_check_adler32 = 1; - if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { - TINFL_GET_BYTE(1, r->m_zhdr0); - TINFL_GET_BYTE(2, r->m_zhdr1); - counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || - (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); - if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) - counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || - ((out_buf_size_mask + 1) < - (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); - if (counter) { - TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); - } - } - - do { - TINFL_GET_BITS(3, r->m_final, 3); - r->m_type = r->m_final >> 1; - if (r->m_type == 0) { - TINFL_SKIP_BITS(5, num_bits & 7); - for (counter = 0; counter < 4; ++counter) { - if (num_bits) - TINFL_GET_BITS(6, r->m_raw_header[counter], 8); - else - TINFL_GET_BYTE(7, r->m_raw_header[counter]); - } - if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != - (mz_uint)(0xFFFF ^ - (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { - TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); - } - while ((counter) && (num_bits)) { - TINFL_GET_BITS(51, dist, 8); - while (pOut_buf_cur >= pOut_buf_end) { - TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); - } - *pOut_buf_cur++ = (mz_uint8)dist; - counter--; - } - while (counter) { - size_t n; - while (pOut_buf_cur >= pOut_buf_end) { - TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); - } - while (pIn_buf_cur >= pIn_buf_end) { - TINFL_CR_RETURN(38, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) - ? TINFL_STATUS_NEEDS_MORE_INPUT - : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); - } - n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), - (size_t)(pIn_buf_end - pIn_buf_cur)), - counter); - TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); - pIn_buf_cur += n; - pOut_buf_cur += n; - counter -= (mz_uint)n; - } - } else if (r->m_type == 3) { - TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); - } else { - if (r->m_type == 1) { - mz_uint8 *p = r->m_tables[0].m_code_size; - mz_uint i; - r->m_table_sizes[0] = 288; - r->m_table_sizes[1] = 32; - TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); - for (i = 0; i <= 143; ++i) - *p++ = 8; - for (; i <= 255; ++i) - *p++ = 9; - for (; i <= 279; ++i) - *p++ = 7; - for (; i <= 287; ++i) - *p++ = 8; - } else { - for (counter = 0; counter < 3; counter++) { - TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); - r->m_table_sizes[counter] += s_min_table_sizes[counter]; - } - MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); - for (counter = 0; counter < r->m_table_sizes[2]; counter++) { - mz_uint s; - TINFL_GET_BITS(14, s, 3); - r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; - } - r->m_table_sizes[2] = 19; - } - for (; (int)r->m_type >= 0; r->m_type--) { - int tree_next, tree_cur; - tinfl_huff_table *pTable; - mz_uint i, j, used_syms, total, sym_index, next_code[17], - total_syms[16]; - pTable = &r->m_tables[r->m_type]; - MZ_CLEAR_OBJ(total_syms); - MZ_CLEAR_OBJ(pTable->m_look_up); - MZ_CLEAR_OBJ(pTable->m_tree); - for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) - total_syms[pTable->m_code_size[i]]++; - used_syms = 0, total = 0; - next_code[0] = next_code[1] = 0; - for (i = 1; i <= 15; ++i) { - used_syms += total_syms[i]; - next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); - } - if ((65536 != total) && (used_syms > 1)) { - TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); - } - for (tree_next = -1, sym_index = 0; - sym_index < r->m_table_sizes[r->m_type]; ++sym_index) { - mz_uint rev_code = 0, l, cur_code, - code_size = pTable->m_code_size[sym_index]; - - if (!code_size) - continue; - cur_code = next_code[code_size]++; - for (l = code_size; l > 0; l--, cur_code >>= 1) - rev_code = (rev_code << 1) | (cur_code & 1); - if (code_size <= TINFL_FAST_LOOKUP_BITS) { - mz_int16 k = (mz_int16)((code_size << 9) | sym_index); - while (rev_code < TINFL_FAST_LOOKUP_SIZE) { - pTable->m_look_up[rev_code] = k; - rev_code += (1 << code_size); - } - continue; - } - if (0 == - (tree_cur = pTable->m_look_up[rev_code & - (TINFL_FAST_LOOKUP_SIZE - 1)])) { - pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = - (mz_int16)tree_next; - tree_cur = tree_next; - tree_next -= 2; - } - rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); - for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) { - tree_cur -= ((rev_code >>= 1) & 1); - if (!pTable->m_tree[-tree_cur - 1]) { - pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; - tree_cur = tree_next; - tree_next -= 2; - } else - tree_cur = pTable->m_tree[-tree_cur - 1]; - } - tree_cur -= ((rev_code >>= 1) & 1); - (void)rev_code; // unused - pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; - } - if (r->m_type == 2) { - for (counter = 0; - counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) { - mz_uint s; - TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); - if (dist < 16) { - r->m_len_codes[counter++] = (mz_uint8)dist; - continue; - } - if ((dist == 16) && (!counter)) { - TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); - } - num_extra = "\02\03\07"[dist - 16]; - TINFL_GET_BITS(18, s, num_extra); - s += "\03\03\013"[dist - 16]; - TINFL_MEMSET(r->m_len_codes + counter, - (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); - counter += s; - } - if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) { - TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); - } - TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, - r->m_table_sizes[0]); - TINFL_MEMCPY(r->m_tables[1].m_code_size, - r->m_len_codes + r->m_table_sizes[0], - r->m_table_sizes[1]); - } - } - for (;;) { - mz_uint8 *pSrc; - for (;;) { - if (((pIn_buf_end - pIn_buf_cur) < 4) || - ((pOut_buf_end - pOut_buf_cur) < 2)) { - TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); - if (counter >= 256) - break; - while (pOut_buf_cur >= pOut_buf_end) { - TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); - } - *pOut_buf_cur++ = (mz_uint8)counter; - } else { - int sym2; - mz_uint code_len; -#if TINFL_USE_64BIT_BITBUF - if (num_bits < 30) { - bit_buf |= - (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); - pIn_buf_cur += 4; - num_bits += 32; - } -#else - if (num_bits < 15) { - bit_buf |= - (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); - pIn_buf_cur += 2; - num_bits += 16; - } -#endif - if ((sym2 = - r->m_tables[0] - .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= - 0) - code_len = sym2 >> 9; - else { - code_len = TINFL_FAST_LOOKUP_BITS; - do { - sym2 = r->m_tables[0] - .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; - } while (sym2 < 0); - } - counter = sym2; - bit_buf >>= code_len; - num_bits -= code_len; - if (counter & 256) - break; - -#if !TINFL_USE_64BIT_BITBUF - if (num_bits < 15) { - bit_buf |= - (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); - pIn_buf_cur += 2; - num_bits += 16; - } -#endif - if ((sym2 = - r->m_tables[0] - .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= - 0) - code_len = sym2 >> 9; - else { - code_len = TINFL_FAST_LOOKUP_BITS; - do { - sym2 = r->m_tables[0] - .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; - } while (sym2 < 0); - } - bit_buf >>= code_len; - num_bits -= code_len; - - pOut_buf_cur[0] = (mz_uint8)counter; - if (sym2 & 256) { - pOut_buf_cur++; - counter = sym2; - break; - } - pOut_buf_cur[1] = (mz_uint8)sym2; - pOut_buf_cur += 2; - } - } - if ((counter &= 511) == 256) - break; - - num_extra = s_length_extra[counter - 257]; - counter = s_length_base[counter - 257]; - if (num_extra) { - mz_uint extra_bits; - TINFL_GET_BITS(25, extra_bits, num_extra); - counter += extra_bits; - } - - TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); - num_extra = s_dist_extra[dist]; - dist = s_dist_base[dist]; - if (num_extra) { - mz_uint extra_bits; - TINFL_GET_BITS(27, extra_bits, num_extra); - dist += extra_bits; - } - - dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; - if ((dist == 0 || dist > dist_from_out_buf_start || - dist_from_out_buf_start == 0) && - (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) { - TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); - } - - pSrc = pOut_buf_start + - ((dist_from_out_buf_start - dist) & out_buf_size_mask); - - if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) { - while (counter--) { - while (pOut_buf_cur >= pOut_buf_end) { - TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); - } - *pOut_buf_cur++ = - pOut_buf_start[(dist_from_out_buf_start++ - dist) & - out_buf_size_mask]; - } - continue; - } -#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES - else if ((counter >= 9) && (counter <= dist)) { - const mz_uint8 *pSrc_end = pSrc + (counter & ~7); - do { -#ifdef MINIZ_UNALIGNED_USE_MEMCPY - memcpy(pOut_buf_cur, pSrc, sizeof(mz_uint32) * 2); -#else - ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; - ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; -#endif - pOut_buf_cur += 8; - } while ((pSrc += 8) < pSrc_end); - if ((counter &= 7) < 3) { - if (counter) { - pOut_buf_cur[0] = pSrc[0]; - if (counter > 1) - pOut_buf_cur[1] = pSrc[1]; - pOut_buf_cur += counter; - } - continue; - } - } -#endif - while (counter > 2) { - pOut_buf_cur[0] = pSrc[0]; - pOut_buf_cur[1] = pSrc[1]; - pOut_buf_cur[2] = pSrc[2]; - pOut_buf_cur += 3; - pSrc += 3; - counter -= 3; - } - if (counter > 0) { - pOut_buf_cur[0] = pSrc[0]; - if (counter > 1) - pOut_buf_cur[1] = pSrc[1]; - pOut_buf_cur += counter; - } - } - } - } while (!(r->m_final & 1)); - - /* Ensure byte alignment and put back any bytes from the bitbuf if we've - * looked ahead too far on gzip, or other Deflate streams followed by - * arbitrary data. */ - /* I'm being super conservative here. A number of simplifications can be made - * to the byte alignment part, and the Adler32 check shouldn't ever need to - * worry about reading from the bitbuf now. */ - TINFL_SKIP_BITS(32, num_bits & 7); - while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) { - --pIn_buf_cur; - num_bits -= 8; - } - bit_buf &= (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1); - MZ_ASSERT(!num_bits); /* if this assert fires then we've read beyond the end - of non-deflate/zlib streams with following data (such - as gzip streams). */ - - if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { - for (counter = 0; counter < 4; ++counter) { - mz_uint s; - if (num_bits) - TINFL_GET_BITS(41, s, 8); - else - TINFL_GET_BYTE(42, s); - r->m_z_adler32 = (r->m_z_adler32 << 8) | s; - } - } - TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); - - TINFL_CR_FINISH - -common_exit: - /* As long as we aren't telling the caller that we NEED more input to make - * forward progress: */ - /* Put back any bytes from the bitbuf in case we've looked ahead too far on - * gzip, or other Deflate streams followed by arbitrary data. */ - /* We need to be very careful here to NOT push back any bytes we definitely - * know we need to make forward progress, though, or we'll lock the caller up - * into an inf loop. */ - if ((status != TINFL_STATUS_NEEDS_MORE_INPUT) && - (status != TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS)) { - while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) { - --pIn_buf_cur; - num_bits -= 8; - } - } - r->m_num_bits = num_bits; - r->m_bit_buf = - bit_buf & (tinfl_bit_buf_t)((((mz_uint64)1) << num_bits) - (mz_uint64)1); - r->m_dist = dist; - r->m_counter = counter; - r->m_num_extra = num_extra; - r->m_dist_from_out_buf_start = dist_from_out_buf_start; - *pIn_buf_size = pIn_buf_cur - pIn_buf_next; - *pOut_buf_size = pOut_buf_cur - pOut_buf_next; - if ((decomp_flags & - (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && - (status >= 0)) { - const mz_uint8 *ptr = pOut_buf_next; - size_t buf_len = *pOut_buf_size; - mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, - s2 = r->m_check_adler32 >> 16; - size_t block_len = buf_len % 5552; - while (buf_len) { - for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { - s1 += ptr[0], s2 += s1; - s1 += ptr[1], s2 += s1; - s1 += ptr[2], s2 += s1; - s1 += ptr[3], s2 += s1; - s1 += ptr[4], s2 += s1; - s1 += ptr[5], s2 += s1; - s1 += ptr[6], s2 += s1; - s1 += ptr[7], s2 += s1; - } - for (; i < block_len; ++i) - s1 += *ptr++, s2 += s1; - s1 %= 65521U, s2 %= 65521U; - buf_len -= block_len; - block_len = 5552; - } - r->m_check_adler32 = (s2 << 16) + s1; - if ((status == TINFL_STATUS_DONE) && - (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && - (r->m_check_adler32 != r->m_z_adler32)) - status = TINFL_STATUS_ADLER32_MISMATCH; - } - return status; -} - -/* Higher level helper functions. */ -void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, - size_t *pOut_len, int flags) { - tinfl_decompressor decomp; - void *pBuf = NULL, *pNew_buf; - size_t src_buf_ofs = 0, out_buf_capacity = 0; - *pOut_len = 0; - tinfl_init(&decomp); - for (;;) { - size_t src_buf_size = src_buf_len - src_buf_ofs, - dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; - tinfl_status status = tinfl_decompress( - &decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, - (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, - &dst_buf_size, - (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | - TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); - if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) { - MZ_FREE(pBuf); - *pOut_len = 0; - return NULL; - } - src_buf_ofs += src_buf_size; - *pOut_len += dst_buf_size; - if (status == TINFL_STATUS_DONE) - break; - new_out_buf_capacity = out_buf_capacity * 2; - if (new_out_buf_capacity < 128) - new_out_buf_capacity = 128; - pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); - if (!pNew_buf) { - MZ_FREE(pBuf); - *pOut_len = 0; - return NULL; - } - pBuf = pNew_buf; - out_buf_capacity = new_out_buf_capacity; - } - return pBuf; -} - -size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, - const void *pSrc_buf, size_t src_buf_len, - int flags) { - tinfl_decompressor decomp; - tinfl_status status; - tinfl_init(&decomp); - status = - tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, - (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, - (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | - TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); - return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED - : out_buf_len; -} - -int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, - tinfl_put_buf_func_ptr pPut_buf_func, - void *pPut_buf_user, int flags) { - int result = 0; - tinfl_decompressor decomp; - mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); - size_t in_buf_ofs = 0, dict_ofs = 0; - if (!pDict) - return TINFL_STATUS_FAILED; - tinfl_init(&decomp); - for (;;) { - size_t in_buf_size = *pIn_buf_size - in_buf_ofs, - dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; - tinfl_status status = - tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, - &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, - (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | - TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); - in_buf_ofs += in_buf_size; - if ((dst_buf_size) && - (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) - break; - if (status != TINFL_STATUS_HAS_MORE_OUTPUT) { - result = (status == TINFL_STATUS_DONE); - break; - } - dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); - } - MZ_FREE(pDict); - *pIn_buf_size = in_buf_ofs; - return result; -} - -#ifndef MINIZ_NO_MALLOC -tinfl_decompressor *tinfl_decompressor_alloc() { - tinfl_decompressor *pDecomp = - (tinfl_decompressor *)MZ_MALLOC(sizeof(tinfl_decompressor)); - if (pDecomp) - tinfl_init(pDecomp); - return pDecomp; -} - -void tinfl_decompressor_free(tinfl_decompressor *pDecomp) { MZ_FREE(pDecomp); } -#endif - -#ifdef __cplusplus -} -#endif -/************************************************************************** - * - * Copyright 2013-2014 RAD Game Tools and Valve Software - * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC - * Copyright 2016 Martin Raiber - * All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - **************************************************************************/ - -#ifndef MINIZ_NO_ARCHIVE_APIS - -#ifdef __cplusplus -extern "C" { -#endif - -/* ------------------- .ZIP archive reading */ - -#ifdef MINIZ_NO_STDIO -#define MZ_FILE void * -#else -#include - -#if defined(_MSC_VER) -#include -#ifndef MINIZ_NO_TIME -#include -#endif -static wchar_t *str2wstr(const char *str) { - size_t len = strlen(str) + 1; - wchar_t *wstr = (wchar_t *)malloc(len * sizeof(wchar_t)); - MultiByteToWideChar(CP_UTF8, 0, str, (int)(len * sizeof(char)), wstr, - (int)len); - return wstr; -} - -static FILE *mz_fopen(const char *pFilename, const char *pMode) { - FILE *pFile = NULL; - wchar_t *wFilename = str2wstr(pFilename); - wchar_t *wMode = str2wstr(pMode); - - _wfopen_s(&pFile, wFilename, wMode); - - free(wFilename); - free(wMode); - - return pFile; -} - -static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) { - FILE *pFile = NULL; - int res = 0; - - wchar_t *wPath = str2wstr(pPath); - wchar_t *wMode = str2wstr(pMode); - - res = _wfreopen_s(&pFile, wPath, wMode, pStream); - - free(wPath); - free(wMode); - - if (res) { - return NULL; - } - - return pFile; -} - -static int mz_stat(const char *pPath, struct _stat64 *buffer) { - wchar_t *wPath = str2wstr(pPath); - int res = _wstat64(wPath, buffer); - - free(wPath); - - return res; -} - -static int mz_mkdir(const char *pDirname) { - wchar_t *wDirname = str2wstr(pDirname); - int res = _wmkdir(wDirname); - - free(wDirname); - - return res; -} - -#define MZ_FOPEN mz_fopen -#define MZ_FCLOSE fclose -#define MZ_FREAD fread -#define MZ_FWRITE fwrite -#define MZ_FTELL64 _ftelli64 -#define MZ_FSEEK64 _fseeki64 -#define MZ_FILE_STAT_STRUCT _stat64 -#define MZ_FILE_STAT mz_stat -#define MZ_FFLUSH fflush -#define MZ_FREOPEN mz_freopen -#define MZ_DELETE_FILE remove -#define MZ_MKDIR(d) mz_mkdir(d) - - -#elif defined(__MINGW32__) || defined(__MINGW64__) -#include -#ifndef MINIZ_NO_TIME -#include -#endif - -#define MZ_FOPEN(f, m) fopen(f, m) -#define MZ_FCLOSE fclose -#define MZ_FREAD fread -#define MZ_FWRITE fwrite -#define MZ_FTELL64 ftell -#define MZ_FSEEK64 fseek -#define MZ_FILE_STAT_STRUCT stat -#define MZ_FILE_STAT stat -#define MZ_FFLUSH fflush -#define MZ_FREOPEN(f, m, s) freopen(f, m, s) -#define MZ_DELETE_FILE remove -#define MZ_MKDIR(d) _mkdir(d) - -#elif defined(__TINYC__) -#ifndef MINIZ_NO_TIME -#include -#endif - -#define MZ_FOPEN(f, m) fopen(f, m) -#define MZ_FCLOSE fclose -#define MZ_FREAD fread -#define MZ_FWRITE fwrite -#define MZ_FTELL64 ftell -#define MZ_FSEEK64 fseek -#define MZ_FILE_STAT_STRUCT stat -#define MZ_FILE_STAT stat -#define MZ_FFLUSH fflush -#define MZ_FREOPEN(f, m, s) freopen(f, m, s) -#define MZ_DELETE_FILE remove -#define MZ_MKDIR(d) mkdir(d, 0755) - -#elif defined(__USE_LARGEFILE64) /* gcc, clang */ -#ifndef MINIZ_NO_TIME -#include -#endif - -#define MZ_FOPEN(f, m) fopen64(f, m) -#define MZ_FCLOSE fclose -#define MZ_FREAD fread -#define MZ_FWRITE fwrite -#define MZ_FTELL64 ftello64 -#define MZ_FSEEK64 fseeko64 -#define MZ_FILE_STAT_STRUCT stat64 -#define MZ_FILE_STAT stat64 -#define MZ_FFLUSH fflush -#define MZ_FREOPEN(p, m, s) freopen64(p, m, s) -#define MZ_DELETE_FILE remove -#define MZ_MKDIR(d) mkdir(d, 0755) - -#elif defined(__APPLE__) -#ifndef MINIZ_NO_TIME -#include -#endif - -#define MZ_FOPEN(f, m) fopen(f, m) -#define MZ_FCLOSE fclose -#define MZ_FREAD fread -#define MZ_FWRITE fwrite -#define MZ_FTELL64 ftello -#define MZ_FSEEK64 fseeko -#define MZ_FILE_STAT_STRUCT stat -#define MZ_FILE_STAT stat -#define MZ_FFLUSH fflush -#define MZ_FREOPEN(p, m, s) freopen(p, m, s) -#define MZ_DELETE_FILE remove -#define MZ_MKDIR(d) mkdir(d, 0755) - -#else -#pragma message( \ - "Using fopen, ftello, fseeko, stat() etc. path for file I/O - this path may not support large files.") -#ifndef MINIZ_NO_TIME -#include -#endif - -#define MZ_FOPEN(f, m) fopen(f, m) -#define MZ_FCLOSE fclose -#define MZ_FREAD fread -#define MZ_FWRITE fwrite -#ifdef __STRICT_ANSI__ -#define MZ_FTELL64 ftell -#define MZ_FSEEK64 fseek -#else -#define MZ_FTELL64 ftello -#define MZ_FSEEK64 fseeko -#endif -#define MZ_FILE_STAT_STRUCT stat -#define MZ_FILE_STAT stat -#define MZ_FFLUSH fflush -#define MZ_FREOPEN(f, m, s) freopen(f, m, s) -#define MZ_DELETE_FILE remove -#define MZ_MKDIR(d) mkdir(d, 0755) - -#endif /* #ifdef _MSC_VER */ -#endif /* #ifdef MINIZ_NO_STDIO */ - -#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) - -/* Various ZIP archive enums. To completely avoid cross platform compiler - * alignment and platform endian issues, miniz.c doesn't use structs for any of - * this stuff. */ -enum { - /* ZIP archive identifiers and record sizes */ - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, - MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, - MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, - MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, - - /* ZIP64 archive identifier and record sizes */ - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06064b50, - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG = 0x07064b50, - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE = 56, - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE = 20, - MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID = 0x0001, - MZ_ZIP_DATA_DESCRIPTOR_ID = 0x08074b50, - MZ_ZIP_DATA_DESCRIPTER_SIZE64 = 24, - MZ_ZIP_DATA_DESCRIPTER_SIZE32 = 16, - - /* Central directory header record offsets */ - MZ_ZIP_CDH_SIG_OFS = 0, - MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, - MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, - MZ_ZIP_CDH_BIT_FLAG_OFS = 8, - MZ_ZIP_CDH_METHOD_OFS = 10, - MZ_ZIP_CDH_FILE_TIME_OFS = 12, - MZ_ZIP_CDH_FILE_DATE_OFS = 14, - MZ_ZIP_CDH_CRC32_OFS = 16, - MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, - MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, - MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, - MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, - MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, - MZ_ZIP_CDH_DISK_START_OFS = 34, - MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, - MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, - MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, - - /* Local directory header offsets */ - MZ_ZIP_LDH_SIG_OFS = 0, - MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, - MZ_ZIP_LDH_BIT_FLAG_OFS = 6, - MZ_ZIP_LDH_METHOD_OFS = 8, - MZ_ZIP_LDH_FILE_TIME_OFS = 10, - MZ_ZIP_LDH_FILE_DATE_OFS = 12, - MZ_ZIP_LDH_CRC32_OFS = 14, - MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, - MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, - MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, - MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, - MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR = 1 << 3, - - /* End of central directory offsets */ - MZ_ZIP_ECDH_SIG_OFS = 0, - MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, - MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, - MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, - MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, - MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, - MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, - MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, - - /* ZIP64 End of central directory locator offsets */ - MZ_ZIP64_ECDL_SIG_OFS = 0, /* 4 bytes */ - MZ_ZIP64_ECDL_NUM_DISK_CDIR_OFS = 4, /* 4 bytes */ - MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS = 8, /* 8 bytes */ - MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS = 16, /* 4 bytes */ - - /* ZIP64 End of central directory header offsets */ - MZ_ZIP64_ECDH_SIG_OFS = 0, /* 4 bytes */ - MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS = 4, /* 8 bytes */ - MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS = 12, /* 2 bytes */ - MZ_ZIP64_ECDH_VERSION_NEEDED_OFS = 14, /* 2 bytes */ - MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS = 16, /* 4 bytes */ - MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS = 20, /* 4 bytes */ - MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 24, /* 8 bytes */ - MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS = 32, /* 8 bytes */ - MZ_ZIP64_ECDH_CDIR_SIZE_OFS = 40, /* 8 bytes */ - MZ_ZIP64_ECDH_CDIR_OFS_OFS = 48, /* 8 bytes */ - MZ_ZIP_VERSION_MADE_BY_DOS_FILESYSTEM_ID = 0, - MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG = 0x10, - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED = 1, - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG = 32, - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION = 64, - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED = 8192, - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8 = 1 << 11 -}; - -typedef struct { - void *m_p; - size_t m_size, m_capacity; - mz_uint m_element_size; -} mz_zip_array; - -struct mz_zip_internal_state_tag { - mz_zip_array m_central_dir; - mz_zip_array m_central_dir_offsets; - mz_zip_array m_sorted_central_dir_offsets; - - /* The flags passed in when the archive is initially opened. */ - uint32_t m_init_flags; - - /* MZ_TRUE if the archive has a zip64 end of central directory headers, etc. - */ - mz_bool m_zip64; - - /* MZ_TRUE if we found zip64 extended info in the central directory (m_zip64 - * will also be slammed to true too, even if we didn't find a zip64 end of - * central dir header, etc.) */ - mz_bool m_zip64_has_extended_info_fields; - - /* These fields are used by the file, FILE, memory, and memory/heap read/write - * helpers. */ - MZ_FILE *m_pFile; - mz_uint64 m_file_archive_start_ofs; - - void *m_pMem; - size_t m_mem_size; - size_t m_mem_capacity; -}; - -#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) \ - (array_ptr)->m_element_size = element_size - -#if defined(DEBUG) || defined(_DEBUG) -static MZ_FORCEINLINE mz_uint -mz_zip_array_range_check(const mz_zip_array *pArray, mz_uint index) { - MZ_ASSERT(index < pArray->m_size); - return index; -} -#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \ - ((element_type *)((array_ptr) \ - ->m_p))[mz_zip_array_range_check(array_ptr, index)] -#else -#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \ - ((element_type *)((array_ptr)->m_p))[index] -#endif - -static MZ_FORCEINLINE void mz_zip_array_init(mz_zip_array *pArray, - mz_uint32 element_size) { - memset(pArray, 0, sizeof(mz_zip_array)); - pArray->m_element_size = element_size; -} - -static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, - mz_zip_array *pArray) { - pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); - memset(pArray, 0, sizeof(mz_zip_array)); -} - -static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, - mz_zip_array *pArray, - size_t min_new_capacity, - mz_uint growing) { - void *pNew_p; - size_t new_capacity = min_new_capacity; - MZ_ASSERT(pArray->m_element_size); - if (pArray->m_capacity >= min_new_capacity) - return MZ_TRUE; - if (growing) { - new_capacity = MZ_MAX(1, pArray->m_capacity); - while (new_capacity < min_new_capacity) - new_capacity *= 2; - } - if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, - pArray->m_element_size, new_capacity))) - return MZ_FALSE; - pArray->m_p = pNew_p; - pArray->m_capacity = new_capacity; - return MZ_TRUE; -} - -static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, - mz_zip_array *pArray, - size_t new_capacity, - mz_uint growing) { - if (new_capacity > pArray->m_capacity) { - if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) - return MZ_FALSE; - } - return MZ_TRUE; -} - -static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, - mz_zip_array *pArray, - size_t new_size, - mz_uint growing) { - if (new_size > pArray->m_capacity) { - if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) - return MZ_FALSE; - } - pArray->m_size = new_size; - return MZ_TRUE; -} - -static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, - mz_zip_array *pArray, - size_t n) { - return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); -} - -static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, - mz_zip_array *pArray, - const void *pElements, - size_t n) { - size_t orig_size = pArray->m_size; - if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) - return MZ_FALSE; - if (n > 0) - memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, - pElements, n * pArray->m_element_size); - return MZ_TRUE; -} - -#ifndef MINIZ_NO_TIME -static MZ_TIME_T mz_zip_dos_to_time_t(int dos_time, int dos_date) { - struct tm tm; - memset(&tm, 0, sizeof(tm)); - tm.tm_isdst = -1; - tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; - tm.tm_mon = ((dos_date >> 5) & 15) - 1; - tm.tm_mday = dos_date & 31; - tm.tm_hour = (dos_time >> 11) & 31; - tm.tm_min = (dos_time >> 5) & 63; - tm.tm_sec = (dos_time << 1) & 62; - return mktime(&tm); -} - -#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS -static void mz_zip_time_t_to_dos_time(MZ_TIME_T time, mz_uint16 *pDOS_time, - mz_uint16 *pDOS_date) { -#ifdef _MSC_VER - struct tm tm_struct; - struct tm *tm = &tm_struct; - errno_t err = localtime_s(tm, &time); - if (err) { - *pDOS_date = 0; - *pDOS_time = 0; - return; - } -#else - struct tm *tm = localtime(&time); -#endif /* #ifdef _MSC_VER */ - - *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + - ((tm->tm_sec) >> 1)); - *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + - ((tm->tm_mon + 1) << 5) + tm->tm_mday); -} -#endif /* MINIZ_NO_ARCHIVE_WRITING_APIS */ - -#ifndef MINIZ_NO_STDIO -#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS -static mz_bool mz_zip_get_file_modified_time(const char *pFilename, - MZ_TIME_T *pTime) { - struct MZ_FILE_STAT_STRUCT file_stat; - - /* On Linux with x86 glibc, this call will fail on large files (I think >= - * 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. */ - if (MZ_FILE_STAT(pFilename, &file_stat) != 0) - return MZ_FALSE; - - *pTime = file_stat.st_mtime; - - return MZ_TRUE; -} -#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS*/ - -static mz_bool mz_zip_set_file_times(const char *pFilename, - MZ_TIME_T access_time, - MZ_TIME_T modified_time) { - struct utimbuf t; - - memset(&t, 0, sizeof(t)); - t.actime = access_time; - t.modtime = modified_time; - - return !utime(pFilename, &t); -} -#endif /* #ifndef MINIZ_NO_STDIO */ -#endif /* #ifndef MINIZ_NO_TIME */ - -static MZ_FORCEINLINE mz_bool mz_zip_set_error(mz_zip_archive *pZip, - mz_zip_error err_num) { - if (pZip) - pZip->m_last_error = err_num; - return MZ_FALSE; -} - -static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, - mz_uint flags) { - (void)flags; - if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (!pZip->m_pAlloc) - pZip->m_pAlloc = miniz_def_alloc_func; - if (!pZip->m_pFree) - pZip->m_pFree = miniz_def_free_func; - if (!pZip->m_pRealloc) - pZip->m_pRealloc = miniz_def_realloc_func; - - pZip->m_archive_size = 0; - pZip->m_central_directory_file_ofs = 0; - pZip->m_total_files = 0; - pZip->m_last_error = MZ_ZIP_NO_ERROR; - - if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc( - pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, - sizeof(mz_uint8)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, - sizeof(mz_uint32)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, - sizeof(mz_uint32)); - pZip->m_pState->m_init_flags = flags; - pZip->m_pState->m_zip64 = MZ_FALSE; - pZip->m_pState->m_zip64_has_extended_info_fields = MZ_FALSE; - - pZip->m_zip_mode = MZ_ZIP_MODE_READING; - - return MZ_TRUE; -} - -static MZ_FORCEINLINE mz_bool -mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, - const mz_zip_array *pCentral_dir_offsets, - mz_uint l_index, mz_uint r_index) { - const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT( - pCentral_dir_array, mz_uint8, - MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, - l_index)), - *pE; - const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT( - pCentral_dir_array, mz_uint8, - MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); - mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), - r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); - mz_uint8 l = 0, r = 0; - pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; - pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; - pE = pL + MZ_MIN(l_len, r_len); - while (pL < pE) { - if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) - break; - pL++; - pR++; - } - return (pL == pE) ? (l_len < r_len) : (l < r); -} - -#define MZ_SWAP_UINT32(a, b) \ - do { \ - mz_uint32 t = a; \ - a = b; \ - b = t; \ - } \ - MZ_MACRO_END - -/* Heap sort of lowercased filenames, used to help accelerate plain central - * directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), - * but it could allocate memory.) */ -static void -mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) { - mz_zip_internal_state *pState = pZip->m_pState; - const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; - const mz_zip_array *pCentral_dir = &pState->m_central_dir; - mz_uint32 *pIndices; - mz_uint32 start, end; - const mz_uint32 size = pZip->m_total_files; - - if (size <= 1U) - return; - - pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, - mz_uint32, 0); - - start = (size - 2U) >> 1U; - for (;;) { - mz_uint64 child, root = start; - for (;;) { - if ((child = (root << 1U) + 1U) >= size) - break; - child += (((child + 1U) < size) && - (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, - pIndices[child], - pIndices[child + 1U]))); - if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, - pIndices[root], pIndices[child])) - break; - MZ_SWAP_UINT32(pIndices[root], pIndices[child]); - root = child; - } - if (!start) - break; - start--; - } - - end = size - 1; - while (end > 0) { - mz_uint64 child, root = 0; - MZ_SWAP_UINT32(pIndices[end], pIndices[0]); - for (;;) { - if ((child = (root << 1U) + 1U) >= end) - break; - child += - (((child + 1U) < end) && - mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, - pIndices[child], pIndices[child + 1U])); - if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, - pIndices[root], pIndices[child])) - break; - MZ_SWAP_UINT32(pIndices[root], pIndices[child]); - root = child; - } - end--; - } -} - -static mz_bool mz_zip_reader_locate_header_sig(mz_zip_archive *pZip, - mz_uint32 record_sig, - mz_uint32 record_size, - mz_int64 *pOfs) { - mz_int64 cur_file_ofs; - mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; - mz_uint8 *pBuf = (mz_uint8 *)buf_u32; - - /* Basic sanity checks - reject files which are too small */ - if (pZip->m_archive_size < record_size) - return MZ_FALSE; - - /* Find the record by scanning the file from the end towards the beginning. */ - cur_file_ofs = - MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); - for (;;) { - int i, - n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); - - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) - return MZ_FALSE; - - for (i = n - 4; i >= 0; --i) { - mz_uint s = MZ_READ_LE32(pBuf + i); - if (s == record_sig) { - if ((pZip->m_archive_size - (cur_file_ofs + i)) >= record_size) - break; - } - } - - if (i >= 0) { - cur_file_ofs += i; - break; - } - - /* Give up if we've searched the entire file, or we've gone back "too far" - * (~64kb) */ - if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= - (MZ_UINT16_MAX + record_size))) - return MZ_FALSE; - - cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); - } - - *pOfs = cur_file_ofs; - return MZ_TRUE; -} - -static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, - mz_uint flags) { - mz_uint cdir_size = 0, cdir_entries_on_this_disk = 0, num_this_disk = 0, - cdir_disk_index = 0; - mz_uint64 cdir_ofs = 0; - mz_int64 cur_file_ofs = 0; - const mz_uint8 *p; - - mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; - mz_uint8 *pBuf = (mz_uint8 *)buf_u32; - mz_bool sort_central_dir = - ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); - mz_uint32 zip64_end_of_central_dir_locator_u32 - [(MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + sizeof(mz_uint32) - 1) / - sizeof(mz_uint32)]; - mz_uint8 *pZip64_locator = (mz_uint8 *)zip64_end_of_central_dir_locator_u32; - - mz_uint32 zip64_end_of_central_dir_header_u32 - [(MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / - sizeof(mz_uint32)]; - mz_uint8 *pZip64_end_of_central_dir = - (mz_uint8 *)zip64_end_of_central_dir_header_u32; - - mz_uint64 zip64_end_of_central_dir_ofs = 0; - - /* Basic sanity checks - reject files which are too small, and check the first - * 4 bytes of the file to make sure a local header is there. */ - if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); - - if (!mz_zip_reader_locate_header_sig( - pZip, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG, - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE, &cur_file_ofs)) - return mz_zip_set_error(pZip, MZ_ZIP_FAILED_FINDING_CENTRAL_DIR); - - /* Read and verify the end of central directory record. */ - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - - if (MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) - return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); - - if (cur_file_ofs >= (MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) { - if (pZip->m_pRead(pZip->m_pIO_opaque, - cur_file_ofs - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE, - pZip64_locator, - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) == - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) { - if (MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_SIG_OFS) == - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG) { - zip64_end_of_central_dir_ofs = MZ_READ_LE64( - pZip64_locator + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS); - if (zip64_end_of_central_dir_ofs > - (pZip->m_archive_size - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) - return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); - - if (pZip->m_pRead(pZip->m_pIO_opaque, zip64_end_of_central_dir_ofs, - pZip64_end_of_central_dir, - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) == - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) { - if (MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIG_OFS) == - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG) { - pZip->m_pState->m_zip64 = MZ_TRUE; - } - } - } - } - } - - pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS); - cdir_entries_on_this_disk = - MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); - num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); - cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); - cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS); - cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); - - if (pZip->m_pState->m_zip64) { - mz_uint32 zip64_total_num_of_disks = - MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS); - mz_uint64 zip64_cdir_total_entries = MZ_READ_LE64( - pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS); - mz_uint64 zip64_cdir_total_entries_on_this_disk = MZ_READ_LE64( - pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); - mz_uint64 zip64_size_of_end_of_central_dir_record = MZ_READ_LE64( - pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS); - mz_uint64 zip64_size_of_central_directory = - MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_SIZE_OFS); - - if (zip64_size_of_end_of_central_dir_record < - (MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - 12)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - if (zip64_total_num_of_disks != 1U) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); - - /* Check for miniz's practical limits */ - if (zip64_cdir_total_entries > MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - - pZip->m_total_files = (mz_uint32)zip64_cdir_total_entries; - - if (zip64_cdir_total_entries_on_this_disk > MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - - cdir_entries_on_this_disk = - (mz_uint32)zip64_cdir_total_entries_on_this_disk; - - /* Check for miniz's current practical limits (sorry, this should be enough - * for millions of files) */ - if (zip64_size_of_central_directory > MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); - - cdir_size = (mz_uint32)zip64_size_of_central_directory; - - num_this_disk = MZ_READ_LE32(pZip64_end_of_central_dir + - MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS); - - cdir_disk_index = MZ_READ_LE32(pZip64_end_of_central_dir + - MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS); - - cdir_ofs = - MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_OFS_OFS); - } - - if (pZip->m_total_files != cdir_entries_on_this_disk) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); - - if (((num_this_disk | cdir_disk_index) != 0) && - ((num_this_disk != 1) || (cdir_disk_index != 1))) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); - - if (cdir_size < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - pZip->m_central_directory_file_ofs = cdir_ofs; - - if (pZip->m_total_files) { - mz_uint i, n; - /* Read the entire central directory into a heap block, and allocate another - * heap block to hold the unsorted central dir file record offsets, and - * possibly another to hold the sorted indices. */ - if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, - MZ_FALSE)) || - (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, - pZip->m_total_files, MZ_FALSE))) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - if (sort_central_dir) { - if (!mz_zip_array_resize(pZip, - &pZip->m_pState->m_sorted_central_dir_offsets, - pZip->m_total_files, MZ_FALSE)) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, - pZip->m_pState->m_central_dir.m_p, - cdir_size) != cdir_size) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - - /* Now create an index into the central directory file records, do some - * basic sanity checking on each record */ - p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; - for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) { - mz_uint total_header_size, disk_index, bit_flags, filename_size, - ext_data_size; - mz_uint64 comp_size, decomp_size, local_header_ofs; - - if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || - (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, - i) = - (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); - - if (sort_central_dir) - MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, - mz_uint32, i) = i; - - comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); - decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); - local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); - filename_size = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); - ext_data_size = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); - - if ((!pZip->m_pState->m_zip64_has_extended_info_fields) && - (ext_data_size) && - (MZ_MAX(MZ_MAX(comp_size, decomp_size), local_header_ofs) == - MZ_UINT32_MAX)) { - /* Attempt to find zip64 extended information field in the entry's extra - * data */ - mz_uint32 extra_size_remaining = ext_data_size; - - if (extra_size_remaining) { - const mz_uint8 *pExtra_data; - void *buf = NULL; - - if (MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + ext_data_size > - n) { - buf = MZ_MALLOC(ext_data_size); - if (buf == NULL) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - if (pZip->m_pRead(pZip->m_pIO_opaque, - cdir_ofs + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + - filename_size, - buf, ext_data_size) != ext_data_size) { - MZ_FREE(buf); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - } - - pExtra_data = (mz_uint8 *)buf; - } else { - pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size; - } - - do { - mz_uint32 field_id; - mz_uint32 field_data_size; - - if (extra_size_remaining < (sizeof(mz_uint16) * 2)) { - MZ_FREE(buf); - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - } - - field_id = MZ_READ_LE16(pExtra_data); - field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); - - if ((field_data_size + sizeof(mz_uint16) * 2) > - extra_size_remaining) { - MZ_FREE(buf); - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - } - - if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { - /* Ok, the archive didn't have any zip64 headers but it uses a - * zip64 extended information field so mark it as zip64 anyway - * (this can occur with infozip's zip util when it reads - * compresses files from stdin). */ - pZip->m_pState->m_zip64 = MZ_TRUE; - pZip->m_pState->m_zip64_has_extended_info_fields = MZ_TRUE; - break; - } - - pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; - extra_size_remaining = - extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; - } while (extra_size_remaining); - - MZ_FREE(buf); - } - } - - /* I've seen archives that aren't marked as zip64 that uses zip64 ext - * data, argh */ - if ((comp_size != MZ_UINT32_MAX) && (decomp_size != MZ_UINT32_MAX)) { - if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && - (decomp_size != comp_size)) || - (decomp_size && !comp_size)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - } - - disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); - if ((disk_index == MZ_UINT16_MAX) || - ((disk_index != num_this_disk) && (disk_index != 1))) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); - - if (comp_size != MZ_UINT32_MAX) { - if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + - MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - } - - bit_flags = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); - if (bit_flags & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); - - if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + - MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + - MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + - MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > - n) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - n -= total_header_size; - p += total_header_size; - } - } - - if (sort_central_dir) - mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); - - return MZ_TRUE; -} - -void mz_zip_zero_struct(mz_zip_archive *pZip) { - if (pZip) - MZ_CLEAR_OBJ(*pZip); -} - -static mz_bool mz_zip_reader_end_internal(mz_zip_archive *pZip, - mz_bool set_last_error) { - mz_bool status = MZ_TRUE; - - if (!pZip) - return MZ_FALSE; - - if ((!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || - (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) { - if (set_last_error) - pZip->m_last_error = MZ_ZIP_INVALID_PARAMETER; - - return MZ_FALSE; - } - - if (pZip->m_pState) { - mz_zip_internal_state *pState = pZip->m_pState; - pZip->m_pState = NULL; - - mz_zip_array_clear(pZip, &pState->m_central_dir); - mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); - mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); - -#ifndef MINIZ_NO_STDIO - if (pState->m_pFile) { - if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) { - if (MZ_FCLOSE(pState->m_pFile) == EOF) { - if (set_last_error) - pZip->m_last_error = MZ_ZIP_FILE_CLOSE_FAILED; - status = MZ_FALSE; - } - } - pState->m_pFile = NULL; - } -#endif /* #ifndef MINIZ_NO_STDIO */ - - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - } - pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; - - return status; -} - -mz_bool mz_zip_reader_end(mz_zip_archive *pZip) { - return mz_zip_reader_end_internal(pZip, MZ_TRUE); -} -mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, - mz_uint flags) { - if ((!pZip) || (!pZip->m_pRead)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (!mz_zip_reader_init_internal(pZip, flags)) - return MZ_FALSE; - - pZip->m_zip_type = MZ_ZIP_TYPE_USER; - pZip->m_archive_size = size; - - if (!mz_zip_reader_read_central_dir(pZip, flags)) { - mz_zip_reader_end_internal(pZip, MZ_FALSE); - return MZ_FALSE; - } - - return MZ_TRUE; -} - -static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, - void *pBuf, size_t n) { - mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; - size_t s = (file_ofs >= pZip->m_archive_size) - ? 0 - : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); - memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); - return s; -} - -mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, - size_t size, mz_uint flags) { - if (!pMem) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); - - if (!mz_zip_reader_init_internal(pZip, flags)) - return MZ_FALSE; - - pZip->m_zip_type = MZ_ZIP_TYPE_MEMORY; - pZip->m_archive_size = size; - pZip->m_pRead = mz_zip_mem_read_func; - pZip->m_pIO_opaque = pZip; - pZip->m_pNeeds_keepalive = NULL; - -#ifdef __cplusplus - pZip->m_pState->m_pMem = const_cast(pMem); -#else - pZip->m_pState->m_pMem = (void *)pMem; -#endif - - pZip->m_pState->m_mem_size = size; - - if (!mz_zip_reader_read_central_dir(pZip, flags)) { - mz_zip_reader_end_internal(pZip, MZ_FALSE); - return MZ_FALSE; - } - - return MZ_TRUE; -} - -#ifndef MINIZ_NO_STDIO -static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, - void *pBuf, size_t n) { - mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; - mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); - - file_ofs += pZip->m_pState->m_file_archive_start_ofs; - - if (((mz_int64)file_ofs < 0) || - (((cur_ofs != (mz_int64)file_ofs)) && - (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) - return 0; - - return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); -} - -mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, - mz_uint32 flags) { - return mz_zip_reader_init_file_v2(pZip, pFilename, flags, 0, 0); -} - -mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, - mz_uint flags, mz_uint64 file_start_ofs, - mz_uint64 archive_size) { - mz_uint64 file_size; - MZ_FILE *pFile; - - if ((!pZip) || (!pFilename) || - ((archive_size) && - (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - pFile = MZ_FOPEN(pFilename, "rb"); - if (!pFile) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); - - file_size = archive_size; - if (!file_size) { - if (MZ_FSEEK64(pFile, 0, SEEK_END)) { - MZ_FCLOSE(pFile); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); - } - - file_size = MZ_FTELL64(pFile); - } - - /* TODO: Better sanity check archive_size and the # of actual remaining bytes - */ - - if (file_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) { - MZ_FCLOSE(pFile); - return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); - } - - if (!mz_zip_reader_init_internal(pZip, flags)) { - MZ_FCLOSE(pFile); - return MZ_FALSE; - } - - pZip->m_zip_type = MZ_ZIP_TYPE_FILE; - pZip->m_pRead = mz_zip_file_read_func; - pZip->m_pIO_opaque = pZip; - pZip->m_pState->m_pFile = pFile; - pZip->m_archive_size = file_size; - pZip->m_pState->m_file_archive_start_ofs = file_start_ofs; - - if (!mz_zip_reader_read_central_dir(pZip, flags)) { - mz_zip_reader_end_internal(pZip, MZ_FALSE); - return MZ_FALSE; - } - - return MZ_TRUE; -} - -mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, - mz_uint64 archive_size, mz_uint flags) { - mz_uint64 cur_file_ofs; - - if ((!pZip) || (!pFile)) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); - - cur_file_ofs = MZ_FTELL64(pFile); - - if (!archive_size) { - if (MZ_FSEEK64(pFile, 0, SEEK_END)) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); - - archive_size = MZ_FTELL64(pFile) - cur_file_ofs; - - if (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); - } - - if (!mz_zip_reader_init_internal(pZip, flags)) - return MZ_FALSE; - - pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; - pZip->m_pRead = mz_zip_file_read_func; - - pZip->m_pIO_opaque = pZip; - pZip->m_pState->m_pFile = pFile; - pZip->m_archive_size = archive_size; - pZip->m_pState->m_file_archive_start_ofs = cur_file_ofs; - - if (!mz_zip_reader_read_central_dir(pZip, flags)) { - mz_zip_reader_end_internal(pZip, MZ_FALSE); - return MZ_FALSE; - } - - return MZ_TRUE; -} - -#endif /* #ifndef MINIZ_NO_STDIO */ - -static MZ_FORCEINLINE const mz_uint8 *mz_zip_get_cdh(mz_zip_archive *pZip, - mz_uint file_index) { - if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files)) - return NULL; - return &MZ_ZIP_ARRAY_ELEMENT( - &pZip->m_pState->m_central_dir, mz_uint8, - MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, - file_index)); -} - -mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, - mz_uint file_index) { - mz_uint m_bit_flag; - const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); - if (!p) { - mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - return MZ_FALSE; - } - - m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); - return (m_bit_flag & - (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) != 0; -} - -mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, - mz_uint file_index) { - mz_uint bit_flag; - mz_uint method; - - const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); - if (!p) { - mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - return MZ_FALSE; - } - - method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); - bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); - - if ((method != 0) && (method != MZ_DEFLATED)) { - mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); - return MZ_FALSE; - } - - if (bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) { - mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); - return MZ_FALSE; - } - - if (bit_flag & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG) { - mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); - return MZ_FALSE; - } - - return MZ_TRUE; -} - -mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, - mz_uint file_index) { - mz_uint filename_len, attribute_mapping_id, external_attr; - const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); - if (!p) { - mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - return MZ_FALSE; - } - - filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); - if (filename_len) { - if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') - return MZ_TRUE; - } - - /* Bugfix: This code was also checking if the internal attribute was non-zero, - * which wasn't correct. */ - /* Most/all zip writers (hopefully) set DOS file/directory attributes in the - * low 16-bits, so check for the DOS directory flag and ignore the source OS - * ID in the created by field. */ - /* FIXME: Remove this check? Is it necessary - we already check the filename. - */ - attribute_mapping_id = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS) >> 8; - (void)attribute_mapping_id; - - external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); - if ((external_attr & MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG) != 0) { - return MZ_TRUE; - } - - return MZ_FALSE; -} - -static mz_bool mz_zip_file_stat_internal(mz_zip_archive *pZip, - mz_uint file_index, - const mz_uint8 *pCentral_dir_header, - mz_zip_archive_file_stat *pStat, - mz_bool *pFound_zip64_extra_data) { - mz_uint n; - const mz_uint8 *p = pCentral_dir_header; - - if (pFound_zip64_extra_data) - *pFound_zip64_extra_data = MZ_FALSE; - - if ((!p) || (!pStat)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - /* Extract fields from the central directory record. */ - pStat->m_file_index = file_index; - pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT( - &pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); - pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); - pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); - pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); - pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); -#ifndef MINIZ_NO_TIME - pStat->m_time = - mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), - MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); -#endif - pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); - pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); - pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); - pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); - pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); - pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); - - /* Copy as much of the filename and comment as possible. */ - n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); - n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); - memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); - pStat->m_filename[n] = '\0'; - - n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); - n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); - pStat->m_comment_size = n; - memcpy(pStat->m_comment, - p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + - MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + - MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), - n); - pStat->m_comment[n] = '\0'; - - /* Set some flags for convienance */ - pStat->m_is_directory = mz_zip_reader_is_file_a_directory(pZip, file_index); - pStat->m_is_encrypted = mz_zip_reader_is_file_encrypted(pZip, file_index); - pStat->m_is_supported = mz_zip_reader_is_file_supported(pZip, file_index); - - /* See if we need to read any zip64 extended information fields. */ - /* Confusingly, these zip64 fields can be present even on non-zip64 archives - * (Debian zip on a huge files from stdin piped to stdout creates them). */ - if (MZ_MAX(MZ_MAX(pStat->m_comp_size, pStat->m_uncomp_size), - pStat->m_local_header_ofs) == MZ_UINT32_MAX) { - /* Attempt to find zip64 extended information field in the entry's extra - * data */ - mz_uint32 extra_size_remaining = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); - - if (extra_size_remaining) { - const mz_uint8 *pExtra_data = - p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + - MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); - - do { - mz_uint32 field_id; - mz_uint32 field_data_size; - - if (extra_size_remaining < (sizeof(mz_uint16) * 2)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - field_id = MZ_READ_LE16(pExtra_data); - field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); - - if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { - const mz_uint8 *pField_data = pExtra_data + sizeof(mz_uint16) * 2; - mz_uint32 field_data_remaining = field_data_size; - - if (pFound_zip64_extra_data) - *pFound_zip64_extra_data = MZ_TRUE; - - if (pStat->m_uncomp_size == MZ_UINT32_MAX) { - if (field_data_remaining < sizeof(mz_uint64)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - pStat->m_uncomp_size = MZ_READ_LE64(pField_data); - pField_data += sizeof(mz_uint64); - field_data_remaining -= sizeof(mz_uint64); - } - - if (pStat->m_comp_size == MZ_UINT32_MAX) { - if (field_data_remaining < sizeof(mz_uint64)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - pStat->m_comp_size = MZ_READ_LE64(pField_data); - pField_data += sizeof(mz_uint64); - field_data_remaining -= sizeof(mz_uint64); - } - - if (pStat->m_local_header_ofs == MZ_UINT32_MAX) { - if (field_data_remaining < sizeof(mz_uint64)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - pStat->m_local_header_ofs = MZ_READ_LE64(pField_data); - pField_data += sizeof(mz_uint64); - (void)pField_data; // unused - - field_data_remaining -= sizeof(mz_uint64); - (void)field_data_remaining; // unused - } - - break; - } - - pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; - extra_size_remaining = - extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; - } while (extra_size_remaining); - } - } - - return MZ_TRUE; -} - -static MZ_FORCEINLINE mz_bool mz_zip_string_equal(const char *pA, - const char *pB, mz_uint len, - mz_uint flags) { - mz_uint i; - if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) - return 0 == memcmp(pA, pB, len); - for (i = 0; i < len; ++i) - if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) - return MZ_FALSE; - return MZ_TRUE; -} - -static MZ_FORCEINLINE int -mz_zip_filename_compare(const mz_zip_array *pCentral_dir_array, - const mz_zip_array *pCentral_dir_offsets, - mz_uint l_index, const char *pR, mz_uint r_len) { - const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT( - pCentral_dir_array, mz_uint8, - MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, - l_index)), - *pE; - mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); - mz_uint8 l = 0, r = 0; - pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; - pE = pL + MZ_MIN(l_len, r_len); - while (pL < pE) { - if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) - break; - pL++; - pR++; - } - return (pL == pE) ? (int)(l_len - r_len) : (l - r); -} - -static mz_bool mz_zip_locate_file_binary_search(mz_zip_archive *pZip, - const char *pFilename, - mz_uint32 *pIndex) { - mz_zip_internal_state *pState = pZip->m_pState; - const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; - const mz_zip_array *pCentral_dir = &pState->m_central_dir; - mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT( - &pState->m_sorted_central_dir_offsets, mz_uint32, 0); - const uint32_t size = pZip->m_total_files; - const mz_uint filename_len = (mz_uint)strlen(pFilename); - - if (pIndex) - *pIndex = 0; - - if (size) { - /* yes I could use uint32_t's, but then we would have to add some special - * case checks in the loop, argh, and */ - /* honestly the major expense here on 32-bit CPU's will still be the - * filename compare */ - mz_int64 l = 0, h = (mz_int64)size - 1; - - while (l <= h) { - mz_int64 m = l + ((h - l) >> 1); - uint32_t file_index = pIndices[(uint32_t)m]; - - int comp = mz_zip_filename_compare(pCentral_dir, pCentral_dir_offsets, - file_index, pFilename, filename_len); - if (!comp) { - if (pIndex) - *pIndex = file_index; - return MZ_TRUE; - } else if (comp < 0) - l = m + 1; - else - h = m - 1; - } - } - - return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); -} - -int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, - const char *pComment, mz_uint flags) { - mz_uint32 index; - if (!mz_zip_reader_locate_file_v2(pZip, pName, pComment, flags, &index)) - return -1; - else - return (int)index; -} - -mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, - const char *pComment, mz_uint flags, - mz_uint32 *pIndex) { - mz_uint file_index; - size_t name_len, comment_len; - - if (pIndex) - *pIndex = 0; - - if ((!pZip) || (!pZip->m_pState) || (!pName)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - /* See if we can use a binary search */ - if (((pZip->m_pState->m_init_flags & - MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) && - (pZip->m_zip_mode == MZ_ZIP_MODE_READING) && - ((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && - (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) { - return mz_zip_locate_file_binary_search(pZip, pName, pIndex); - } - - /* Locate the entry by scanning the entire central directory */ - name_len = strlen(pName); - if (name_len > MZ_UINT16_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - comment_len = pComment ? strlen(pComment) : 0; - if (comment_len > MZ_UINT16_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - for (file_index = 0; file_index < pZip->m_total_files; file_index++) { - const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT( - &pZip->m_pState->m_central_dir, mz_uint8, - MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, - file_index)); - mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); - const char *pFilename = - (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; - if (filename_len < name_len) - continue; - if (comment_len) { - mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), - file_comment_len = - MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); - const char *pFile_comment = pFilename + filename_len + file_extra_len; - if ((file_comment_len != comment_len) || - (!mz_zip_string_equal(pComment, pFile_comment, file_comment_len, - flags))) - continue; - } - if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) { - int ofs = filename_len - 1; - do { - if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || - (pFilename[ofs] == ':')) - break; - } while (--ofs >= 0); - ofs++; - pFilename += ofs; - filename_len -= ofs; - } - if ((filename_len == name_len) && - (mz_zip_string_equal(pName, pFilename, filename_len, flags))) { - if (pIndex) - *pIndex = file_index; - return MZ_TRUE; - } - } - - return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); -} - -mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, - mz_uint file_index, void *pBuf, - size_t buf_size, mz_uint flags, - void *pUser_read_buf, - size_t user_read_buf_size) { - int status = TINFL_STATUS_DONE; - mz_uint64 needed_size, cur_file_ofs, comp_remaining, - out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; - mz_zip_archive_file_stat file_stat; - void *pRead_buf; - mz_uint32 - local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / - sizeof(mz_uint32)]; - mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; - tinfl_decompressor inflator; - - if ((!pZip) || (!pZip->m_pState) || ((buf_size) && (!pBuf)) || - ((user_read_buf_size) && (!pUser_read_buf)) || (!pZip->m_pRead)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) - return MZ_FALSE; - - /* A directory or zero length file */ - if (file_stat.m_is_directory || (!file_stat.m_comp_size)) - return MZ_TRUE; - - /* Encryption and patch files are not supported. */ - if (file_stat.m_bit_flag & - (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); - - /* This function only supports decompressing stored and deflate. */ - if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && - (file_stat.m_method != MZ_DEFLATED)) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); - - /* Ensure supplied output buffer is large enough. */ - needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size - : file_stat.m_uncomp_size; - if (buf_size < needed_size) - return mz_zip_set_error(pZip, MZ_ZIP_BUF_TOO_SMALL); - - /* Read and parse the local directory entry. */ - cur_file_ofs = file_stat.m_local_header_ofs; - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - - if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + - MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + - MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); - if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { - /* The file is stored or the caller has requested the compressed data. */ - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, - (size_t)needed_size) != needed_size) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) == 0) { - if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, - (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) - return mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); - } -#endif - - return MZ_TRUE; - } - - /* Decompress the file either directly from memory or from a file input - * buffer. */ - tinfl_init(&inflator); - - if (pZip->m_pState->m_pMem) { - /* Read directly from the archive in memory. */ - pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; - read_buf_size = read_buf_avail = file_stat.m_comp_size; - comp_remaining = 0; - } else if (pUser_read_buf) { - /* Use a user provided read buffer. */ - if (!user_read_buf_size) - return MZ_FALSE; - pRead_buf = (mz_uint8 *)pUser_read_buf; - read_buf_size = user_read_buf_size; - read_buf_avail = 0; - comp_remaining = file_stat.m_comp_size; - } else { - /* Temporarily allocate a read buffer. */ - read_buf_size = - MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); - if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) - return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - - if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, - (size_t)read_buf_size))) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - read_buf_avail = 0; - comp_remaining = file_stat.m_comp_size; - } - - do { - /* The size_t cast here should be OK because we've verified that the output - * buffer is >= file_stat.m_uncomp_size above */ - size_t in_buf_size, - out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); - if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { - read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, - (size_t)read_buf_avail) != read_buf_avail) { - status = TINFL_STATUS_FAILED; - mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); - break; - } - cur_file_ofs += read_buf_avail; - comp_remaining -= read_buf_avail; - read_buf_ofs = 0; - } - in_buf_size = (size_t)read_buf_avail; - status = tinfl_decompress( - &inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, - (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, - TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | - (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); - read_buf_avail -= in_buf_size; - read_buf_ofs += in_buf_size; - out_buf_ofs += out_buf_size; - } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); - - if (status == TINFL_STATUS_DONE) { - /* Make sure the entire file was decompressed, and check its CRC. */ - if (out_buf_ofs != file_stat.m_uncomp_size) { - mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); - status = TINFL_STATUS_FAILED; - } -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - else if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, - (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) { - mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); - status = TINFL_STATUS_FAILED; - } -#endif - } - - if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - - return status == TINFL_STATUS_DONE; -} - -mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( - mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, - mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { - mz_uint32 file_index; - if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) - return MZ_FALSE; - return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, - flags, pUser_read_buf, - user_read_buf_size); -} - -mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, - void *pBuf, size_t buf_size, - mz_uint flags) { - return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, - flags, NULL, 0); -} - -mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, - const char *pFilename, void *pBuf, - size_t buf_size, mz_uint flags) { - return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, - buf_size, flags, NULL, 0); -} - -void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, - size_t *pSize, mz_uint flags) { - mz_uint64 comp_size, uncomp_size, alloc_size; - const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); - void *pBuf; - - if (pSize) - *pSize = 0; - - if (!p) { - mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - return NULL; - } - - comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); - uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); - - alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; - if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) { - mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - return NULL; - } - - if (NULL == - (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) { - mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - return NULL; - } - - if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, - flags)) { - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - return NULL; - } - - if (pSize) - *pSize = (size_t)alloc_size; - return pBuf; -} - -void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, - const char *pFilename, size_t *pSize, - mz_uint flags) { - mz_uint32 file_index; - if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, - &file_index)) { - if (pSize) - *pSize = 0; - return MZ_FALSE; - } - return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); -} - -mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, - mz_uint file_index, - mz_file_write_func pCallback, - void *pOpaque, mz_uint flags) { - int status = TINFL_STATUS_DONE; -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - mz_uint file_crc32 = MZ_CRC32_INIT; -#endif - mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, - out_buf_ofs = 0, cur_file_ofs; - mz_zip_archive_file_stat file_stat; - void *pRead_buf = NULL; - void *pWrite_buf = NULL; - mz_uint32 - local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / - sizeof(mz_uint32)]; - mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; - - if ((!pZip) || (!pZip->m_pState) || (!pCallback) || (!pZip->m_pRead)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) - return MZ_FALSE; - - /* A directory or zero length file */ - if (file_stat.m_is_directory || (!file_stat.m_comp_size)) - return MZ_TRUE; - - /* Encryption and patch files are not supported. */ - if (file_stat.m_bit_flag & - (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); - - /* This function only supports decompressing stored and deflate. */ - if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && - (file_stat.m_method != MZ_DEFLATED)) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); - - /* Read and do some minimal validation of the local directory entry (this - * doesn't crack the zip64 stuff, which we already have from the central dir) - */ - cur_file_ofs = file_stat.m_local_header_ofs; - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - - if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + - MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + - MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); - if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - /* Decompress the file either directly from memory or from a file input - * buffer. */ - if (pZip->m_pState->m_pMem) { - pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; - read_buf_size = read_buf_avail = file_stat.m_comp_size; - comp_remaining = 0; - } else { - read_buf_size = - MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); - if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, - (size_t)read_buf_size))) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - read_buf_avail = 0; - comp_remaining = file_stat.m_comp_size; - } - - if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { - /* The file is stored or the caller has requested the compressed data. */ - if (pZip->m_pState->m_pMem) { - if (((sizeof(size_t) == sizeof(mz_uint32))) && - (file_stat.m_comp_size > MZ_UINT32_MAX)) - return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - - if (pCallback(pOpaque, out_buf_ofs, pRead_buf, - (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) { - mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); - status = TINFL_STATUS_FAILED; - } else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - file_crc32 = - (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, - (size_t)file_stat.m_comp_size); -#endif - } - - cur_file_ofs += file_stat.m_comp_size; - out_buf_ofs += file_stat.m_comp_size; - comp_remaining = 0; - } else { - while (comp_remaining) { - read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, - (size_t)read_buf_avail) != read_buf_avail) { - mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - status = TINFL_STATUS_FAILED; - break; - } - -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { - file_crc32 = (mz_uint32)mz_crc32( - file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); - } -#endif - - if (pCallback(pOpaque, out_buf_ofs, pRead_buf, - (size_t)read_buf_avail) != read_buf_avail) { - mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); - status = TINFL_STATUS_FAILED; - break; - } - - cur_file_ofs += read_buf_avail; - out_buf_ofs += read_buf_avail; - comp_remaining -= read_buf_avail; - } - } - } else { - tinfl_decompressor inflator; - tinfl_init(&inflator); - - if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, - TINFL_LZ_DICT_SIZE))) { - mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - status = TINFL_STATUS_FAILED; - } else { - do { - mz_uint8 *pWrite_buf_cur = - (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); - size_t in_buf_size, - out_buf_size = - TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); - if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { - read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, - (size_t)read_buf_avail) != read_buf_avail) { - mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - status = TINFL_STATUS_FAILED; - break; - } - cur_file_ofs += read_buf_avail; - comp_remaining -= read_buf_avail; - read_buf_ofs = 0; - } - - in_buf_size = (size_t)read_buf_avail; - status = tinfl_decompress( - &inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, - (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, - comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); - read_buf_avail -= in_buf_size; - read_buf_ofs += in_buf_size; - - if (out_buf_size) { - if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != - out_buf_size) { - mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); - status = TINFL_STATUS_FAILED; - break; - } - -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - file_crc32 = - (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); -#endif - if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) { - mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); - status = TINFL_STATUS_FAILED; - break; - } - } - } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || - (status == TINFL_STATUS_HAS_MORE_OUTPUT)); - } - } - - if ((status == TINFL_STATUS_DONE) && - (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) { - /* Make sure the entire file was decompressed, and check its CRC. */ - if (out_buf_ofs != file_stat.m_uncomp_size) { - mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); - status = TINFL_STATUS_FAILED; - } -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - else if (file_crc32 != file_stat.m_crc32) { - mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); - status = TINFL_STATUS_FAILED; - } -#endif - } - - if (!pZip->m_pState->m_pMem) - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - - if (pWrite_buf) - pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); - - return status == TINFL_STATUS_DONE; -} - -mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, - const char *pFilename, - mz_file_write_func pCallback, - void *pOpaque, mz_uint flags) { - mz_uint32 file_index; - if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) - return MZ_FALSE; - - return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, - flags); -} - -mz_zip_reader_extract_iter_state * -mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, - mz_uint flags) { - mz_zip_reader_extract_iter_state *pState; - mz_uint32 - local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / - sizeof(mz_uint32)]; - mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; - - /* Argument sanity check */ - if ((!pZip) || (!pZip->m_pState)) - return NULL; - - /* Allocate an iterator status structure */ - pState = (mz_zip_reader_extract_iter_state *)pZip->m_pAlloc( - pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_reader_extract_iter_state)); - if (!pState) { - mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - return NULL; - } - - /* Fetch file details */ - if (!mz_zip_reader_file_stat(pZip, file_index, &pState->file_stat)) { - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - return NULL; - } - - /* Encryption and patch files are not supported. */ - if (pState->file_stat.m_bit_flag & - (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | - MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) { - mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - return NULL; - } - - /* This function only supports decompressing stored and deflate. */ - if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && - (pState->file_stat.m_method != 0) && - (pState->file_stat.m_method != MZ_DEFLATED)) { - mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - return NULL; - } - - /* Init state - save args */ - pState->pZip = pZip; - pState->flags = flags; - - /* Init state - reset variables to defaults */ - pState->status = TINFL_STATUS_DONE; -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - pState->file_crc32 = MZ_CRC32_INIT; -#endif - pState->read_buf_ofs = 0; - pState->out_buf_ofs = 0; - pState->pRead_buf = NULL; - pState->pWrite_buf = NULL; - pState->out_blk_remain = 0; - - /* Read and parse the local directory entry. */ - pState->cur_file_ofs = pState->file_stat.m_local_header_ofs; - if (pZip->m_pRead(pZip->m_pIO_opaque, pState->cur_file_ofs, pLocal_header, - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) { - mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - return NULL; - } - - if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) { - mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - return NULL; - } - - pState->cur_file_ofs += - MZ_ZIP_LOCAL_DIR_HEADER_SIZE + - MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + - MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); - if ((pState->cur_file_ofs + pState->file_stat.m_comp_size) > - pZip->m_archive_size) { - mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - return NULL; - } - - /* Decompress the file either directly from memory or from a file input - * buffer. */ - if (pZip->m_pState->m_pMem) { - pState->pRead_buf = - (mz_uint8 *)pZip->m_pState->m_pMem + pState->cur_file_ofs; - pState->read_buf_size = pState->read_buf_avail = - pState->file_stat.m_comp_size; - pState->comp_remaining = pState->file_stat.m_comp_size; - } else { - if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || - (!pState->file_stat.m_method))) { - /* Decompression required, therefore intermediate read buffer required */ - pState->read_buf_size = MZ_MIN(pState->file_stat.m_comp_size, - (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); - if (NULL == - (pState->pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, - (size_t)pState->read_buf_size))) { - mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - return NULL; - } - } else { - /* Decompression not required - we will be reading directly into user - * buffer, no temp buf required */ - pState->read_buf_size = 0; - } - pState->read_buf_avail = 0; - pState->comp_remaining = pState->file_stat.m_comp_size; - } - - if (!((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || - (!pState->file_stat.m_method))) { - /* Decompression required, init decompressor */ - tinfl_init(&pState->inflator); - - /* Allocate write buffer */ - if (NULL == (pState->pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, - TINFL_LZ_DICT_SIZE))) { - mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - if (pState->pRead_buf) - pZip->m_pFree(pZip->m_pAlloc_opaque, pState->pRead_buf); - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - return NULL; - } - } - - return pState; -} - -mz_zip_reader_extract_iter_state * -mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, - mz_uint flags) { - mz_uint32 file_index; - - /* Locate file index by name */ - if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) - return NULL; - - /* Construct iterator */ - return mz_zip_reader_extract_iter_new(pZip, file_index, flags); -} - -size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state *pState, - void *pvBuf, size_t buf_size) { - size_t copied_to_caller = 0; - - /* Argument sanity check */ - if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState) || (!pvBuf)) - return 0; - - if ((pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || - (!pState->file_stat.m_method)) { - /* The file is stored or the caller has requested the compressed data, calc - * amount to return. */ - copied_to_caller = (size_t)MZ_MIN(buf_size, pState->comp_remaining); - - /* Zip is in memory....or requires reading from a file? */ - if (pState->pZip->m_pState->m_pMem) { - /* Copy data to caller's buffer */ - memcpy(pvBuf, pState->pRead_buf, copied_to_caller); - pState->pRead_buf = ((mz_uint8 *)pState->pRead_buf) + copied_to_caller; - } else { - /* Read directly into caller's buffer */ - if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, - pState->cur_file_ofs, pvBuf, - copied_to_caller) != copied_to_caller) { - /* Failed to read all that was asked for, flag failure and alert user */ - mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED); - pState->status = TINFL_STATUS_FAILED; - copied_to_caller = 0; - } - } - -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - /* Compute CRC if not returning compressed data only */ - if (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) - pState->file_crc32 = (mz_uint32)mz_crc32( - pState->file_crc32, (const mz_uint8 *)pvBuf, copied_to_caller); -#endif - - /* Advance offsets, dec counters */ - pState->cur_file_ofs += copied_to_caller; - pState->out_buf_ofs += copied_to_caller; - pState->comp_remaining -= copied_to_caller; - } else { - do { - /* Calc ptr to write buffer - given current output pos and block size */ - mz_uint8 *pWrite_buf_cur = - (mz_uint8 *)pState->pWrite_buf + - (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); - - /* Calc max output size - given current output pos and block size */ - size_t in_buf_size, - out_buf_size = TINFL_LZ_DICT_SIZE - - (pState->out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); - - if (!pState->out_blk_remain) { - /* Read more data from file if none available (and reading from file) */ - if ((!pState->read_buf_avail) && (!pState->pZip->m_pState->m_pMem)) { - /* Calc read size */ - pState->read_buf_avail = - MZ_MIN(pState->read_buf_size, pState->comp_remaining); - if (pState->pZip->m_pRead(pState->pZip->m_pIO_opaque, - pState->cur_file_ofs, pState->pRead_buf, - (size_t)pState->read_buf_avail) != - pState->read_buf_avail) { - mz_zip_set_error(pState->pZip, MZ_ZIP_FILE_READ_FAILED); - pState->status = TINFL_STATUS_FAILED; - break; - } - - /* Advance offsets, dec counters */ - pState->cur_file_ofs += pState->read_buf_avail; - pState->comp_remaining -= pState->read_buf_avail; - pState->read_buf_ofs = 0; - } - - /* Perform decompression */ - in_buf_size = (size_t)pState->read_buf_avail; - pState->status = tinfl_decompress( - &pState->inflator, - (const mz_uint8 *)pState->pRead_buf + pState->read_buf_ofs, - &in_buf_size, (mz_uint8 *)pState->pWrite_buf, pWrite_buf_cur, - &out_buf_size, - pState->comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); - pState->read_buf_avail -= in_buf_size; - pState->read_buf_ofs += in_buf_size; - - /* Update current output block size remaining */ - pState->out_blk_remain = out_buf_size; - } - - if (pState->out_blk_remain) { - /* Calc amount to return. */ - size_t to_copy = - MZ_MIN((buf_size - copied_to_caller), pState->out_blk_remain); - - /* Copy data to caller's buffer */ - memcpy((uint8_t *)pvBuf + copied_to_caller, pWrite_buf_cur, to_copy); - -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - /* Perform CRC */ - pState->file_crc32 = - (mz_uint32)mz_crc32(pState->file_crc32, pWrite_buf_cur, to_copy); -#endif - - /* Decrement data consumed from block */ - pState->out_blk_remain -= to_copy; - - /* Inc output offset, while performing sanity check */ - if ((pState->out_buf_ofs += to_copy) > - pState->file_stat.m_uncomp_size) { - mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED); - pState->status = TINFL_STATUS_FAILED; - break; - } - - /* Increment counter of data copied to caller */ - copied_to_caller += to_copy; - } - } while ((copied_to_caller < buf_size) && - ((pState->status == TINFL_STATUS_NEEDS_MORE_INPUT) || - (pState->status == TINFL_STATUS_HAS_MORE_OUTPUT))); - } - - /* Return how many bytes were copied into user buffer */ - return copied_to_caller; -} - -mz_bool -mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state *pState) { - int status; - - /* Argument sanity check */ - if ((!pState) || (!pState->pZip) || (!pState->pZip->m_pState)) - return MZ_FALSE; - - /* Was decompression completed and requested? */ - if ((pState->status == TINFL_STATUS_DONE) && - (!(pState->flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) { - /* Make sure the entire file was decompressed, and check its CRC. */ - if (pState->out_buf_ofs != pState->file_stat.m_uncomp_size) { - mz_zip_set_error(pState->pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); - pState->status = TINFL_STATUS_FAILED; - } -#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - else if (pState->file_crc32 != pState->file_stat.m_crc32) { - mz_zip_set_error(pState->pZip, MZ_ZIP_DECOMPRESSION_FAILED); - pState->status = TINFL_STATUS_FAILED; - } -#endif - } - - /* Free buffers */ - if (!pState->pZip->m_pState->m_pMem) - pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pRead_buf); - if (pState->pWrite_buf) - pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState->pWrite_buf); - - /* Save status */ - status = pState->status; - - /* Free context */ - pState->pZip->m_pFree(pState->pZip->m_pAlloc_opaque, pState); - - return status == TINFL_STATUS_DONE; -} - -#ifndef MINIZ_NO_STDIO -static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, - const void *pBuf, size_t n) { - (void)ofs; - - return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque); -} - -mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, - const char *pDst_filename, - mz_uint flags) { - mz_bool status; - mz_zip_archive_file_stat file_stat; - MZ_FILE *pFile; - - if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) - return MZ_FALSE; - - if (file_stat.m_is_directory || (!file_stat.m_is_supported)) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); - - pFile = MZ_FOPEN(pDst_filename, "wb"); - if (!pFile) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); - - status = mz_zip_reader_extract_to_callback( - pZip, file_index, mz_zip_file_write_callback, pFile, flags); - - if (MZ_FCLOSE(pFile) == EOF) { - if (status) - mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); - - status = MZ_FALSE; - } - -#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) - if (status) - mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); -#endif - - return status; -} - -mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, - const char *pArchive_filename, - const char *pDst_filename, - mz_uint flags) { - mz_uint32 file_index; - if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, - &file_index)) - return MZ_FALSE; - - return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); -} - -mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, - MZ_FILE *pFile, mz_uint flags) { - mz_zip_archive_file_stat file_stat; - - if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) - return MZ_FALSE; - - if (file_stat.m_is_directory || (!file_stat.m_is_supported)) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); - - return mz_zip_reader_extract_to_callback( - pZip, file_index, mz_zip_file_write_callback, pFile, flags); -} - -mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, - const char *pArchive_filename, - MZ_FILE *pFile, mz_uint flags) { - mz_uint32 file_index; - if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, - &file_index)) - return MZ_FALSE; - - return mz_zip_reader_extract_to_cfile(pZip, file_index, pFile, flags); -} -#endif /* #ifndef MINIZ_NO_STDIO */ - -static size_t mz_zip_compute_crc32_callback(void *pOpaque, mz_uint64 file_ofs, - const void *pBuf, size_t n) { - mz_uint32 *p = (mz_uint32 *)pOpaque; - (void)file_ofs; - *p = (mz_uint32)mz_crc32(*p, (const mz_uint8 *)pBuf, n); - return n; -} - -mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, - mz_uint flags) { - mz_zip_archive_file_stat file_stat; - mz_zip_internal_state *pState; - const mz_uint8 *pCentral_dir_header; - mz_bool found_zip64_ext_data_in_cdir = MZ_FALSE; - mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; - mz_uint32 - local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / - sizeof(mz_uint32)]; - mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; - mz_uint64 local_header_ofs = 0; - mz_uint32 local_header_filename_len, local_header_extra_len, - local_header_crc32; - mz_uint64 local_header_comp_size, local_header_uncomp_size; - mz_uint32 uncomp_crc32 = MZ_CRC32_INIT; - mz_bool has_data_descriptor; - mz_uint32 local_header_bit_flags; - - mz_zip_array file_data_array; - mz_zip_array_init(&file_data_array, 1); - - if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || - (!pZip->m_pRead)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (file_index > pZip->m_total_files) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - pState = pZip->m_pState; - - pCentral_dir_header = mz_zip_get_cdh(pZip, file_index); - - if (!mz_zip_file_stat_internal(pZip, file_index, pCentral_dir_header, - &file_stat, &found_zip64_ext_data_in_cdir)) - return MZ_FALSE; - - /* A directory or zero length file */ - if (file_stat.m_is_directory || (!file_stat.m_uncomp_size)) - return MZ_TRUE; - - /* Encryption and patch files are not supported. */ - if (file_stat.m_is_encrypted) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); - - /* This function only supports stored and deflate. */ - if ((file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); - - if (!file_stat.m_is_supported) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); - - /* Read and parse the local directory entry. */ - local_header_ofs = file_stat.m_local_header_ofs; - if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs, pLocal_header, - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - - if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - local_header_filename_len = - MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); - local_header_extra_len = - MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); - local_header_comp_size = - MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); - local_header_uncomp_size = - MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); - local_header_crc32 = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_CRC32_OFS); - local_header_bit_flags = - MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); - has_data_descriptor = (local_header_bit_flags & 8) != 0; - - if (local_header_filename_len != strlen(file_stat.m_filename)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - if ((local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + - local_header_filename_len + local_header_extra_len + - file_stat.m_comp_size) > pZip->m_archive_size) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - if (!mz_zip_array_resize( - pZip, &file_data_array, - MZ_MAX(local_header_filename_len, local_header_extra_len), - MZ_FALSE)) { - mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - goto handle_failure; - } - - if (local_header_filename_len) { - if (pZip->m_pRead(pZip->m_pIO_opaque, - local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE, - file_data_array.m_p, - local_header_filename_len) != local_header_filename_len) { - mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - goto handle_failure; - } - - /* I've seen 1 archive that had the same pathname, but used backslashes in - * the local dir and forward slashes in the central dir. Do we care about - * this? For now, this case will fail validation. */ - if (memcmp(file_stat.m_filename, file_data_array.m_p, - local_header_filename_len) != 0) { - mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); - goto handle_failure; - } - } - - if ((local_header_extra_len) && - ((local_header_comp_size == MZ_UINT32_MAX) || - (local_header_uncomp_size == MZ_UINT32_MAX))) { - mz_uint32 extra_size_remaining = local_header_extra_len; - const mz_uint8 *pExtra_data = (const mz_uint8 *)file_data_array.m_p; - - if (pZip->m_pRead(pZip->m_pIO_opaque, - local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + - local_header_filename_len, - file_data_array.m_p, - local_header_extra_len) != local_header_extra_len) { - mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - goto handle_failure; - } - - do { - mz_uint32 field_id, field_data_size, field_total_size; - - if (extra_size_remaining < (sizeof(mz_uint16) * 2)) { - mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - goto handle_failure; - } - - field_id = MZ_READ_LE16(pExtra_data); - field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); - field_total_size = field_data_size + sizeof(mz_uint16) * 2; - - if (field_total_size > extra_size_remaining) { - mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - goto handle_failure; - } - - if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { - const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); - - if (field_data_size < sizeof(mz_uint64) * 2) { - mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - goto handle_failure; - } - - local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); - local_header_comp_size = - MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64)); - - found_zip64_ext_data_in_ldir = MZ_TRUE; - break; - } - - pExtra_data += field_total_size; - extra_size_remaining -= field_total_size; - } while (extra_size_remaining); - } - - /* TODO: parse local header extra data when local_header_comp_size is - * 0xFFFFFFFF! (big_descriptor.zip) */ - /* I've seen zips in the wild with the data descriptor bit set, but proper - * local header values and bogus data descriptors */ - if ((has_data_descriptor) && (!local_header_comp_size) && - (!local_header_crc32)) { - mz_uint8 descriptor_buf[32]; - mz_bool has_id; - const mz_uint8 *pSrc; - mz_uint32 file_crc32; - mz_uint64 comp_size = 0, uncomp_size = 0; - - mz_uint32 num_descriptor_uint32s = - ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) ? 6 : 4; - - if (pZip->m_pRead(pZip->m_pIO_opaque, - local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + - local_header_filename_len + local_header_extra_len + - file_stat.m_comp_size, - descriptor_buf, - sizeof(mz_uint32) * num_descriptor_uint32s) != - (sizeof(mz_uint32) * num_descriptor_uint32s)) { - mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - goto handle_failure; - } - - has_id = (MZ_READ_LE32(descriptor_buf) == MZ_ZIP_DATA_DESCRIPTOR_ID); - pSrc = has_id ? (descriptor_buf + sizeof(mz_uint32)) : descriptor_buf; - - file_crc32 = MZ_READ_LE32(pSrc); - - if ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) { - comp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32)); - uncomp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32) + sizeof(mz_uint64)); - } else { - comp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32)); - uncomp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32) + sizeof(mz_uint32)); - } - - if ((file_crc32 != file_stat.m_crc32) || - (comp_size != file_stat.m_comp_size) || - (uncomp_size != file_stat.m_uncomp_size)) { - mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); - goto handle_failure; - } - } else { - if ((local_header_crc32 != file_stat.m_crc32) || - (local_header_comp_size != file_stat.m_comp_size) || - (local_header_uncomp_size != file_stat.m_uncomp_size)) { - mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); - goto handle_failure; - } - } - - mz_zip_array_clear(pZip, &file_data_array); - - if ((flags & MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY) == 0) { - if (!mz_zip_reader_extract_to_callback( - pZip, file_index, mz_zip_compute_crc32_callback, &uncomp_crc32, 0)) - return MZ_FALSE; - - /* 1 more check to be sure, although the extract checks too. */ - if (uncomp_crc32 != file_stat.m_crc32) { - mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); - return MZ_FALSE; - } - } - - return MZ_TRUE; - -handle_failure: - mz_zip_array_clear(pZip, &file_data_array); - return MZ_FALSE; -} - -mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags) { - mz_zip_internal_state *pState; - uint32_t i; - - if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || - (!pZip->m_pRead)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - pState = pZip->m_pState; - - /* Basic sanity checks */ - if (!pState->m_zip64) { - if (pZip->m_total_files > MZ_UINT16_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - - if (pZip->m_archive_size > MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - } else { - if (pZip->m_total_files >= MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - - if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - } - - for (i = 0; i < pZip->m_total_files; i++) { - if (MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG & flags) { - mz_uint32 found_index; - mz_zip_archive_file_stat stat; - - if (!mz_zip_reader_file_stat(pZip, i, &stat)) - return MZ_FALSE; - - if (!mz_zip_reader_locate_file_v2(pZip, stat.m_filename, NULL, 0, - &found_index)) - return MZ_FALSE; - - /* This check can fail if there are duplicate filenames in the archive - * (which we don't check for when writing - that's up to the user) */ - if (found_index != i) - return mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); - } - - if (!mz_zip_validate_file(pZip, i, flags)) - return MZ_FALSE; - } - - return MZ_TRUE; -} - -mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, - mz_uint flags, mz_zip_error *pErr) { - mz_bool success = MZ_TRUE; - mz_zip_archive zip; - mz_zip_error actual_err = MZ_ZIP_NO_ERROR; - - if ((!pMem) || (!size)) { - if (pErr) - *pErr = MZ_ZIP_INVALID_PARAMETER; - return MZ_FALSE; - } - - mz_zip_zero_struct(&zip); - - if (!mz_zip_reader_init_mem(&zip, pMem, size, flags)) { - if (pErr) - *pErr = zip.m_last_error; - return MZ_FALSE; - } - - if (!mz_zip_validate_archive(&zip, flags)) { - actual_err = zip.m_last_error; - success = MZ_FALSE; - } - - if (!mz_zip_reader_end_internal(&zip, success)) { - if (!actual_err) - actual_err = zip.m_last_error; - success = MZ_FALSE; - } - - if (pErr) - *pErr = actual_err; - - return success; -} - -#ifndef MINIZ_NO_STDIO -mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, - mz_zip_error *pErr) { - mz_bool success = MZ_TRUE; - mz_zip_archive zip; - mz_zip_error actual_err = MZ_ZIP_NO_ERROR; - - if (!pFilename) { - if (pErr) - *pErr = MZ_ZIP_INVALID_PARAMETER; - return MZ_FALSE; - } - - mz_zip_zero_struct(&zip); - - if (!mz_zip_reader_init_file_v2(&zip, pFilename, flags, 0, 0)) { - if (pErr) - *pErr = zip.m_last_error; - return MZ_FALSE; - } - - if (!mz_zip_validate_archive(&zip, flags)) { - actual_err = zip.m_last_error; - success = MZ_FALSE; - } - - if (!mz_zip_reader_end_internal(&zip, success)) { - if (!actual_err) - actual_err = zip.m_last_error; - success = MZ_FALSE; - } - - if (pErr) - *pErr = actual_err; - - return success; -} -#endif /* #ifndef MINIZ_NO_STDIO */ - -/* ------------------- .ZIP archive writing */ - -#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS - -static MZ_FORCEINLINE void mz_write_le16(mz_uint8 *p, mz_uint16 v) { - p[0] = (mz_uint8)v; - p[1] = (mz_uint8)(v >> 8); -} -static MZ_FORCEINLINE void mz_write_le32(mz_uint8 *p, mz_uint32 v) { - p[0] = (mz_uint8)v; - p[1] = (mz_uint8)(v >> 8); - p[2] = (mz_uint8)(v >> 16); - p[3] = (mz_uint8)(v >> 24); -} -static MZ_FORCEINLINE void mz_write_le64(mz_uint8 *p, mz_uint64 v) { - mz_write_le32(p, (mz_uint32)v); - mz_write_le32(p + sizeof(mz_uint32), (mz_uint32)(v >> 32)); -} - -#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) -#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) -#define MZ_WRITE_LE64(p, v) mz_write_le64((mz_uint8 *)(p), (mz_uint64)(v)) - -static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, - const void *pBuf, size_t n) { - mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; - mz_zip_internal_state *pState = pZip->m_pState; - mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); - - if (!n) - return 0; - - /* An allocation this big is likely to just fail on 32-bit systems, so don't - * even go there. */ - if ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)) { - mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); - return 0; - } - - if (new_size > pState->m_mem_capacity) { - void *pNew_block; - size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); - - while (new_capacity < new_size) - new_capacity *= 2; - - if (NULL == (pNew_block = pZip->m_pRealloc( - pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) { - mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - return 0; - } - - pState->m_pMem = pNew_block; - pState->m_mem_capacity = new_capacity; - } - memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); - pState->m_mem_size = (size_t)new_size; - return n; -} - -static mz_bool mz_zip_writer_end_internal(mz_zip_archive *pZip, - mz_bool set_last_error) { - mz_zip_internal_state *pState; - mz_bool status = MZ_TRUE; - - if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || - ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && - (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) { - if (set_last_error) - mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - return MZ_FALSE; - } - - pState = pZip->m_pState; - pZip->m_pState = NULL; - mz_zip_array_clear(pZip, &pState->m_central_dir); - mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); - mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); - -#ifndef MINIZ_NO_STDIO - if (pState->m_pFile) { - if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) { - if (MZ_FCLOSE(pState->m_pFile) == EOF) { - if (set_last_error) - mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); - status = MZ_FALSE; - } - } - - pState->m_pFile = NULL; - } -#endif /* #ifndef MINIZ_NO_STDIO */ - - if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) { - pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); - pState->m_pMem = NULL; - } - - pZip->m_pFree(pZip->m_pAlloc_opaque, pState); - pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; - return status; -} - -mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, - mz_uint flags) { - mz_bool zip64 = (flags & MZ_ZIP_FLAG_WRITE_ZIP64) != 0; - - if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || - (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) { - if (!pZip->m_pRead) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - } - - if (pZip->m_file_offset_alignment) { - /* Ensure user specified file offset alignment is a power of 2. */ - if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - } - - if (!pZip->m_pAlloc) - pZip->m_pAlloc = miniz_def_alloc_func; - if (!pZip->m_pFree) - pZip->m_pFree = miniz_def_free_func; - if (!pZip->m_pRealloc) - pZip->m_pRealloc = miniz_def_realloc_func; - - pZip->m_archive_size = existing_size; - pZip->m_central_directory_file_ofs = 0; - pZip->m_total_files = 0; - - if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc( - pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); - - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, - sizeof(mz_uint8)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, - sizeof(mz_uint32)); - MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, - sizeof(mz_uint32)); - - pZip->m_pState->m_zip64 = zip64; - pZip->m_pState->m_zip64_has_extended_info_fields = zip64; - - pZip->m_zip_type = MZ_ZIP_TYPE_USER; - pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; - - return MZ_TRUE; -} - -mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) { - return mz_zip_writer_init_v2(pZip, existing_size, 0); -} - -mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, - size_t size_to_reserve_at_beginning, - size_t initial_allocation_size, - mz_uint flags) { - pZip->m_pWrite = mz_zip_heap_write_func; - pZip->m_pNeeds_keepalive = NULL; - - if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) - pZip->m_pRead = mz_zip_mem_read_func; - - pZip->m_pIO_opaque = pZip; - - if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) - return MZ_FALSE; - - pZip->m_zip_type = MZ_ZIP_TYPE_HEAP; - - if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, - size_to_reserve_at_beginning))) { - if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc( - pZip->m_pAlloc_opaque, 1, initial_allocation_size))) { - mz_zip_writer_end_internal(pZip, MZ_FALSE); - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - pZip->m_pState->m_mem_capacity = initial_allocation_size; - } - - return MZ_TRUE; -} - -mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, - size_t size_to_reserve_at_beginning, - size_t initial_allocation_size) { - return mz_zip_writer_init_heap_v2(pZip, size_to_reserve_at_beginning, - initial_allocation_size, 0); -} - -#ifndef MINIZ_NO_STDIO -static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, - const void *pBuf, size_t n) { - mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; - mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); - - file_ofs += pZip->m_pState->m_file_archive_start_ofs; - - if (((mz_int64)file_ofs < 0) || - (((cur_ofs != (mz_int64)file_ofs)) && - (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) { - mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); - return 0; - } - - return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); -} - -mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, - mz_uint64 size_to_reserve_at_beginning) { - return mz_zip_writer_init_file_v2(pZip, pFilename, - size_to_reserve_at_beginning, 0); -} - -mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, - mz_uint64 size_to_reserve_at_beginning, - mz_uint flags) { - MZ_FILE *pFile; - - pZip->m_pWrite = mz_zip_file_write_func; - pZip->m_pNeeds_keepalive = NULL; - - if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) - pZip->m_pRead = mz_zip_file_read_func; - - pZip->m_pIO_opaque = pZip; - - if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) - return MZ_FALSE; - - if (NULL == (pFile = MZ_FOPEN( - pFilename, - (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) ? "w+b" : "wb"))) { - mz_zip_writer_end(pZip); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); - } - - pZip->m_pState->m_pFile = pFile; - pZip->m_zip_type = MZ_ZIP_TYPE_FILE; - - if (size_to_reserve_at_beginning) { - mz_uint64 cur_ofs = 0; - char buf[4096]; - - MZ_CLEAR_OBJ(buf); - - do { - size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) { - mz_zip_writer_end(pZip); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - cur_ofs += n; - size_to_reserve_at_beginning -= n; - } while (size_to_reserve_at_beginning); - } - - return MZ_TRUE; -} - -mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, - mz_uint flags) { - pZip->m_pWrite = mz_zip_file_write_func; - pZip->m_pNeeds_keepalive = NULL; - - if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) - pZip->m_pRead = mz_zip_file_read_func; - - pZip->m_pIO_opaque = pZip; - - if (!mz_zip_writer_init_v2(pZip, 0, flags)) - return MZ_FALSE; - - pZip->m_pState->m_pFile = pFile; - pZip->m_pState->m_file_archive_start_ofs = - MZ_FTELL64(pZip->m_pState->m_pFile); - pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; - - return MZ_TRUE; -} -#endif /* #ifndef MINIZ_NO_STDIO */ - -mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, - const char *pFilename, - mz_uint flags) { - mz_zip_internal_state *pState; - - if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (flags & MZ_ZIP_FLAG_WRITE_ZIP64) { - /* We don't support converting a non-zip64 file to zip64 - this seems like - * more trouble than it's worth. (What about the existing 32-bit data - * descriptors that could follow the compressed data?) */ - if (!pZip->m_pState->m_zip64) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - } - - /* No sense in trying to write to an archive that's already at the support max - * size */ - if (pZip->m_pState->m_zip64) { - if (pZip->m_total_files == MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - } else { - if (pZip->m_total_files == MZ_UINT16_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - - if ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); - } - - pState = pZip->m_pState; - - if (pState->m_pFile) { -#ifdef MINIZ_NO_STDIO - (void)pFilename; - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); -#else - if (pZip->m_pIO_opaque != pZip) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) { - if (!pFilename) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - /* Archive is being read from stdio and was originally opened only for - * reading. Try to reopen as writable. */ - if (NULL == - (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) { - /* The mz_zip_archive is now in a bogus state because pState->m_pFile is - * NULL, so just close it. */ - mz_zip_reader_end_internal(pZip, MZ_FALSE); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); - } - } - - pZip->m_pWrite = mz_zip_file_write_func; - pZip->m_pNeeds_keepalive = NULL; -#endif /* #ifdef MINIZ_NO_STDIO */ - } else if (pState->m_pMem) { - /* Archive lives in a memory block. Assume it's from the heap that we can - * resize using the realloc callback. */ - if (pZip->m_pIO_opaque != pZip) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - pState->m_mem_capacity = pState->m_mem_size; - pZip->m_pWrite = mz_zip_heap_write_func; - pZip->m_pNeeds_keepalive = NULL; - } - /* Archive is being read via a user provided read function - make sure the - user has specified a write function too. */ - else if (!pZip->m_pWrite) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - /* Start writing new files at the archive's current central directory - * location. */ - /* TODO: We could add a flag that lets the user start writing immediately - * AFTER the existing central dir - this would be safer. */ - pZip->m_archive_size = pZip->m_central_directory_file_ofs; - pZip->m_central_directory_file_ofs = 0; - - /* Clear the sorted central dir offsets, they aren't useful or maintained now. - */ - /* Even though we're now in write mode, files can still be extracted and - * verified, but file locates will be slow. */ - /* TODO: We could easily maintain the sorted central directory offsets. */ - mz_zip_array_clear(pZip, &pZip->m_pState->m_sorted_central_dir_offsets); - - pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; - - return MZ_TRUE; -} - -mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, - const char *pFilename) { - return mz_zip_writer_init_from_reader_v2(pZip, pFilename, 0); -} - -/* TODO: pArchive_name is a terrible name here! */ -mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, - const void *pBuf, size_t buf_size, - mz_uint level_and_flags) { - return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, - level_and_flags, 0, 0); -} - -typedef struct { - mz_zip_archive *m_pZip; - mz_uint64 m_cur_archive_file_ofs; - mz_uint64 m_comp_size; -} mz_zip_writer_add_state; - -static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, - void *pUser) { - mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; - if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, - pState->m_cur_archive_file_ofs, pBuf, - len) != len) - return MZ_FALSE; - - pState->m_cur_archive_file_ofs += len; - pState->m_comp_size += len; - return MZ_TRUE; -} - -#define MZ_ZIP64_MAX_LOCAL_EXTRA_FIELD_SIZE \ - (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 2) -#define MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE \ - (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 3) -static mz_uint32 -mz_zip_writer_create_zip64_extra_data(mz_uint8 *pBuf, mz_uint64 *pUncomp_size, - mz_uint64 *pComp_size, - mz_uint64 *pLocal_header_ofs) { - mz_uint8 *pDst = pBuf; - mz_uint32 field_size = 0; - - MZ_WRITE_LE16(pDst + 0, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); - MZ_WRITE_LE16(pDst + 2, 0); - pDst += sizeof(mz_uint16) * 2; - - if (pUncomp_size) { - MZ_WRITE_LE64(pDst, *pUncomp_size); - pDst += sizeof(mz_uint64); - field_size += sizeof(mz_uint64); - } - - if (pComp_size) { - MZ_WRITE_LE64(pDst, *pComp_size); - pDst += sizeof(mz_uint64); - field_size += sizeof(mz_uint64); - } - - if (pLocal_header_ofs) { - MZ_WRITE_LE64(pDst, *pLocal_header_ofs); - pDst += sizeof(mz_uint64); - field_size += sizeof(mz_uint64); - } - - MZ_WRITE_LE16(pBuf + 2, field_size); - - return (mz_uint32)(pDst - pBuf); -} - -static mz_bool mz_zip_writer_create_local_dir_header( - mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, - mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, - mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, - mz_uint16 dos_time, mz_uint16 dos_date) { - (void)pZip; - memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); - MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); - MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); - MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, - MZ_MIN(comp_size, MZ_UINT32_MAX)); - MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, - MZ_MIN(uncomp_size, MZ_UINT32_MAX)); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); - MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); - return MZ_TRUE; -} - -static mz_bool mz_zip_writer_create_central_dir_header( - mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, - mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, - mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, - mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, - mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { - (void)pZip; - memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); - MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); - MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); - MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, - MZ_MIN(comp_size, MZ_UINT32_MAX)); - MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, - MZ_MIN(uncomp_size, MZ_UINT32_MAX)); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); - MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); - MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); - MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, - MZ_MIN(local_header_ofs, MZ_UINT32_MAX)); - return MZ_TRUE; -} - -static mz_bool mz_zip_writer_add_to_central_dir( - mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, - const void *pExtra, mz_uint16 extra_size, const void *pComment, - mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, - mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, - mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, - mz_uint32 ext_attributes, const char *user_extra_data, - mz_uint user_extra_data_len) { - mz_zip_internal_state *pState = pZip->m_pState; - mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; - size_t orig_central_dir_size = pState->m_central_dir.m_size; - mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; - - if (!pZip->m_pState->m_zip64) { - if (local_header_ofs > 0xFFFFFFFF) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); - } - - /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ - if (((mz_uint64)pState->m_central_dir.m_size + - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + - user_extra_data_len + comment_size) >= MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); - - if (!mz_zip_writer_create_central_dir_header( - pZip, central_dir_header, filename_size, - (mz_uint16)(extra_size + user_extra_data_len), comment_size, - uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, - dos_date, local_header_ofs, ext_attributes)) - return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - - if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || - (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, - filename_size)) || - (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, - extra_size)) || - (!mz_zip_array_push_back(pZip, &pState->m_central_dir, user_extra_data, - user_extra_data_len)) || - (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, - comment_size)) || - (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, - ¢ral_dir_ofs, 1))) { - /* Try to resize the central directory array back into its original state. - */ - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, - MZ_FALSE); - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - return MZ_TRUE; -} - -static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) { - /* Basic ZIP archive filename validity checks: Valid filenames cannot start - * with a forward slash, cannot contain a drive letter, and cannot use - * DOS-style backward slashes. */ - if (*pArchive_name == '/') - return MZ_FALSE; - - /* Making sure the name does not contain drive letters or DOS style backward - * slashes is the responsibility of the program using miniz*/ - - return MZ_TRUE; -} - -static mz_uint -mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) { - mz_uint32 n; - if (!pZip->m_file_offset_alignment) - return 0; - n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); - return (mz_uint)((pZip->m_file_offset_alignment - n) & - (pZip->m_file_offset_alignment - 1)); -} - -static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, - mz_uint64 cur_file_ofs, mz_uint32 n) { - char buf[4096]; - memset(buf, 0, MZ_MIN(sizeof(buf), n)); - while (n) { - mz_uint32 s = MZ_MIN(sizeof(buf), n); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_file_ofs += s; - n -= s; - } - return MZ_TRUE; -} - -mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, - const char *pArchive_name, const void *pBuf, - size_t buf_size, const void *pComment, - mz_uint16 comment_size, - mz_uint level_and_flags, mz_uint64 uncomp_size, - mz_uint32 uncomp_crc32) { - return mz_zip_writer_add_mem_ex_v2( - pZip, pArchive_name, pBuf, buf_size, pComment, comment_size, - level_and_flags, uncomp_size, uncomp_crc32, NULL, NULL, 0, NULL, 0); -} - -mz_bool mz_zip_writer_add_mem_ex_v2( - mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, - size_t buf_size, const void *pComment, mz_uint16 comment_size, - mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, - MZ_TIME_T *last_modified, const char *user_extra_data, - mz_uint user_extra_data_len, const char *user_extra_data_central, - mz_uint user_extra_data_central_len) { - mz_uint16 method = 0, dos_time = 0, dos_date = 0; - mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; - mz_uint64 local_dir_header_ofs = pZip->m_archive_size, - cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; - size_t archive_name_size; - mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; - tdefl_compressor *pComp = NULL; - mz_bool store_data_uncompressed; - mz_zip_internal_state *pState; - mz_uint8 *pExtra_data = NULL; - mz_uint32 extra_size = 0; - mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; - mz_uint16 bit_flags = 0; - - if ((int)level_and_flags < 0) - level_and_flags = MZ_DEFAULT_LEVEL; - - if (uncomp_size || - (buf_size && !(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) - bit_flags |= MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; - - if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME)) - bit_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; - - level = level_and_flags & 0xF; - store_data_uncompressed = - ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); - - if ((!pZip) || (!pZip->m_pState) || - (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || - (!pArchive_name) || ((comment_size) && (!pComment)) || - (level > MZ_UBER_COMPRESSION)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - pState = pZip->m_pState; - - if (pState->m_zip64) { - if (pZip->m_total_files == MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - } else { - if (pZip->m_total_files == MZ_UINT16_MAX) { - pState->m_zip64 = MZ_TRUE; - /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ - } - if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) { - pState->m_zip64 = MZ_TRUE; - /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ - } - } - - if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (!mz_zip_writer_validate_archive_name(pArchive_name)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); - -#ifndef MINIZ_NO_TIME - if (last_modified != NULL) { - mz_zip_time_t_to_dos_time(*last_modified, &dos_time, &dos_date); - } else { - MZ_TIME_T cur_time; - time(&cur_time); - mz_zip_time_t_to_dos_time(cur_time, &dos_time, &dos_date); - } -#endif /* #ifndef MINIZ_NO_TIME */ - - if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { - uncomp_crc32 = - (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size); - uncomp_size = buf_size; - if (uncomp_size <= 3) { - level = 0; - store_data_uncompressed = MZ_TRUE; - } - } - - archive_name_size = strlen(pArchive_name); - if (archive_name_size > MZ_UINT16_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); - - num_alignment_padding_bytes = - mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); - - /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ - if (((mz_uint64)pState->m_central_dir.m_size + - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + - MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); - - if (!pState->m_zip64) { - /* Bail early if the archive would obviously become too large */ - if ((pZip->m_archive_size + num_alignment_padding_bytes + - MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + - user_extra_data_len + pState->m_central_dir.m_size + - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + user_extra_data_central_len + - MZ_ZIP_DATA_DESCRIPTER_SIZE32) > 0xFFFFFFFF) { - pState->m_zip64 = MZ_TRUE; - /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ - } - } - - if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) { - /* Set DOS Subdirectory attribute bit. */ - ext_attributes |= MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG; - - /* Subdirectories cannot contain data. */ - if ((buf_size) || (uncomp_size)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - } - - /* Try to do any allocations before writing to the archive, so if an - * allocation fails the file remains unmodified. (A good idea if we're doing - * an in-place modification.) */ - if ((!mz_zip_array_ensure_room( - pZip, &pState->m_central_dir, - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + - (pState->m_zip64 ? MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE : 0))) || - (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - if ((!store_data_uncompressed) && (buf_size)) { - if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc( - pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, - num_alignment_padding_bytes)) { - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - return MZ_FALSE; - } - - local_dir_header_ofs += num_alignment_padding_bytes; - if (pZip->m_file_offset_alignment) { - MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == - 0); - } - cur_archive_file_ofs += num_alignment_padding_bytes; - - MZ_CLEAR_OBJ(local_dir_header); - - if (!store_data_uncompressed || - (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { - method = MZ_DEFLATED; - } - - if (pState->m_zip64) { - if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) { - pExtra_data = extra_data; - extra_size = mz_zip_writer_create_zip64_extra_data( - extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, - (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, - (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs - : NULL); - } - - if (!mz_zip_writer_create_local_dir_header( - pZip, local_dir_header, (mz_uint16)archive_name_size, - (mz_uint16)(extra_size + user_extra_data_len), 0, 0, 0, method, - bit_flags, dos_time, dos_date)) - return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, - local_dir_header, - sizeof(local_dir_header)) != sizeof(local_dir_header)) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_archive_file_ofs += sizeof(local_dir_header); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, - archive_name_size) != archive_name_size) { - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - cur_archive_file_ofs += archive_name_size; - - if (pExtra_data != NULL) { - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, - extra_size) != extra_size) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_archive_file_ofs += extra_size; - } - } else { - if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - if (!mz_zip_writer_create_local_dir_header( - pZip, local_dir_header, (mz_uint16)archive_name_size, - (mz_uint16)user_extra_data_len, 0, 0, 0, method, bit_flags, - dos_time, dos_date)) - return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, - local_dir_header, - sizeof(local_dir_header)) != sizeof(local_dir_header)) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_archive_file_ofs += sizeof(local_dir_header); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, - archive_name_size) != archive_name_size) { - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - cur_archive_file_ofs += archive_name_size; - } - - if (user_extra_data_len > 0) { - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, - user_extra_data, - user_extra_data_len) != user_extra_data_len) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_archive_file_ofs += user_extra_data_len; - } - - if (store_data_uncompressed) { - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, - buf_size) != buf_size) { - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - - cur_archive_file_ofs += buf_size; - comp_size = buf_size; - } else if (buf_size) { - mz_zip_writer_add_state state; - - state.m_pZip = pZip; - state.m_cur_archive_file_ofs = cur_archive_file_ofs; - state.m_comp_size = 0; - - if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, - tdefl_create_comp_flags_from_zip_params( - level, -15, MZ_DEFAULT_STRATEGY)) != - TDEFL_STATUS_OKAY) || - (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != - TDEFL_STATUS_DONE)) { - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - return mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); - } - - comp_size = state.m_comp_size; - cur_archive_file_ofs = state.m_cur_archive_file_ofs; - } - - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - pComp = NULL; - - if (uncomp_size) { - mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; - mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; - - MZ_ASSERT(bit_flags & MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR); - - MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); - MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); - if (pExtra_data == NULL) { - if (comp_size > MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - - MZ_WRITE_LE32(local_dir_footer + 8, comp_size); - MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); - } else { - MZ_WRITE_LE64(local_dir_footer + 8, comp_size); - MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); - local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; - } - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, - local_dir_footer, - local_dir_footer_size) != local_dir_footer_size) - return MZ_FALSE; - - cur_archive_file_ofs += local_dir_footer_size; - } - - if (pExtra_data != NULL) { - extra_size = mz_zip_writer_create_zip64_extra_data( - extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, - (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, - (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); - } - - if (!mz_zip_writer_add_to_central_dir( - pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, - (mz_uint16)extra_size, pComment, comment_size, uncomp_size, comp_size, - uncomp_crc32, method, bit_flags, dos_time, dos_date, - local_dir_header_ofs, ext_attributes, user_extra_data_central, - user_extra_data_central_len)) - return MZ_FALSE; - - pZip->m_total_files++; - pZip->m_archive_size = cur_archive_file_ofs; - - return MZ_TRUE; -} - -mz_bool mz_zip_writer_add_read_buf_callback( - mz_zip_archive *pZip, const char *pArchive_name, - mz_file_read_func read_callback, void *callback_opaque, mz_uint64 max_size, - const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, - mz_uint level_and_flags, mz_uint32 ext_attributes, - const char *user_extra_data, mz_uint user_extra_data_len, - const char *user_extra_data_central, mz_uint user_extra_data_central_len) { - mz_uint16 gen_flags = (level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE) - ? 0 - : MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; - mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; - mz_uint16 method = 0, dos_time = 0, dos_date = 0; - mz_uint64 local_dir_header_ofs, cur_archive_file_ofs = pZip->m_archive_size, - uncomp_size = 0, comp_size = 0; - size_t archive_name_size; - mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; - mz_uint8 *pExtra_data = NULL; - mz_uint32 extra_size = 0; - mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; - mz_zip_internal_state *pState; - mz_uint64 file_ofs = 0, cur_archive_header_file_ofs; - - if (!(level_and_flags & MZ_ZIP_FLAG_ASCII_FILENAME)) - gen_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; - - if ((int)level_and_flags < 0) - level_and_flags = MZ_DEFAULT_LEVEL; - level = level_and_flags & 0xF; - - /* Sanity checks */ - if ((!pZip) || (!pZip->m_pState) || - (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || - ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - pState = pZip->m_pState; - - if ((!pState->m_zip64) && (max_size > MZ_UINT32_MAX)) { - /* Source file is too large for non-zip64 */ - /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ - pState->m_zip64 = MZ_TRUE; - } - - /* We could support this, but why? */ - if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (!mz_zip_writer_validate_archive_name(pArchive_name)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); - - if (pState->m_zip64) { - if (pZip->m_total_files == MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - } else { - if (pZip->m_total_files == MZ_UINT16_MAX) { - pState->m_zip64 = MZ_TRUE; - /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ - } - } - - archive_name_size = strlen(pArchive_name); - if (archive_name_size > MZ_UINT16_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); - - num_alignment_padding_bytes = - mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); - - /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ - if (((mz_uint64)pState->m_central_dir.m_size + - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + - MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); - - if (!pState->m_zip64) { - /* Bail early if the archive would obviously become too large */ - if ((pZip->m_archive_size + num_alignment_padding_bytes + - MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + - user_extra_data_len + pState->m_central_dir.m_size + - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 1024 + - MZ_ZIP_DATA_DESCRIPTER_SIZE32 + user_extra_data_central_len) > - 0xFFFFFFFF) { - pState->m_zip64 = MZ_TRUE; - /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ - } - } - -#ifndef MINIZ_NO_TIME - if (pFile_time) { - mz_zip_time_t_to_dos_time(*pFile_time, &dos_time, &dos_date); - } -#endif - - if (max_size <= 3) - level = 0; - - if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, - num_alignment_padding_bytes)) { - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - - cur_archive_file_ofs += num_alignment_padding_bytes; - local_dir_header_ofs = cur_archive_file_ofs; - - if (pZip->m_file_offset_alignment) { - MZ_ASSERT((cur_archive_file_ofs & (pZip->m_file_offset_alignment - 1)) == - 0); - } - - if (max_size && level) { - method = MZ_DEFLATED; - } - - MZ_CLEAR_OBJ(local_dir_header); - if (pState->m_zip64) { - if (max_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) { - pExtra_data = extra_data; - if (level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE) - extra_size = mz_zip_writer_create_zip64_extra_data( - extra_data, (max_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, - (max_size >= MZ_UINT32_MAX) ? &comp_size : NULL, - (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs - : NULL); - else - extra_size = mz_zip_writer_create_zip64_extra_data( - extra_data, NULL, NULL, - (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs - : NULL); - } - - if (!mz_zip_writer_create_local_dir_header( - pZip, local_dir_header, (mz_uint16)archive_name_size, - (mz_uint16)(extra_size + user_extra_data_len), 0, 0, 0, method, - gen_flags, dos_time, dos_date)) - return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, - local_dir_header, - sizeof(local_dir_header)) != sizeof(local_dir_header)) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_archive_file_ofs += sizeof(local_dir_header); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, - archive_name_size) != archive_name_size) { - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - - cur_archive_file_ofs += archive_name_size; - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, - extra_size) != extra_size) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_archive_file_ofs += extra_size; - } else { - if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - if (!mz_zip_writer_create_local_dir_header( - pZip, local_dir_header, (mz_uint16)archive_name_size, - (mz_uint16)user_extra_data_len, 0, 0, 0, method, gen_flags, - dos_time, dos_date)) - return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, - local_dir_header, - sizeof(local_dir_header)) != sizeof(local_dir_header)) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_archive_file_ofs += sizeof(local_dir_header); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, - archive_name_size) != archive_name_size) { - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - - cur_archive_file_ofs += archive_name_size; - } - - if (user_extra_data_len > 0) { - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, - user_extra_data, - user_extra_data_len) != user_extra_data_len) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_archive_file_ofs += user_extra_data_len; - } - - if (max_size) { - void *pRead_buf = - pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); - if (!pRead_buf) { - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - if (!level) { - while (1) { - size_t n = read_callback(callback_opaque, file_ofs, pRead_buf, - MZ_ZIP_MAX_IO_BUF_SIZE); - if (n == 0) - break; - - if ((n > MZ_ZIP_MAX_IO_BUF_SIZE) || (file_ofs + n > max_size)) { - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - } - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, - n) != n) { - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - file_ofs += n; - uncomp_crc32 = - (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); - cur_archive_file_ofs += n; - } - uncomp_size = file_ofs; - comp_size = uncomp_size; - } else { - mz_bool result = MZ_FALSE; - mz_zip_writer_add_state state; - tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc( - pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); - if (!pComp) { - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - state.m_pZip = pZip; - state.m_cur_archive_file_ofs = cur_archive_file_ofs; - state.m_comp_size = 0; - - if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, - tdefl_create_comp_flags_from_zip_params( - level, -15, MZ_DEFAULT_STRATEGY)) != - TDEFL_STATUS_OKAY) { - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - } - - for (;;) { - tdefl_status status; - tdefl_flush flush = TDEFL_NO_FLUSH; - - size_t n = read_callback(callback_opaque, file_ofs, pRead_buf, - MZ_ZIP_MAX_IO_BUF_SIZE); - if ((n > MZ_ZIP_MAX_IO_BUF_SIZE) || (file_ofs + n > max_size)) { - mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - break; - } - - file_ofs += n; - uncomp_crc32 = - (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); - - if (pZip->m_pNeeds_keepalive != NULL && - pZip->m_pNeeds_keepalive(pZip->m_pIO_opaque)) - flush = TDEFL_FULL_FLUSH; - - if (n == 0) - flush = TDEFL_FINISH; - - status = tdefl_compress_buffer(pComp, pRead_buf, n, flush); - if (status == TDEFL_STATUS_DONE) { - result = MZ_TRUE; - break; - } else if (status != TDEFL_STATUS_OKAY) { - mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); - break; - } - } - - pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - - if (!result) { - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - return MZ_FALSE; - } - - uncomp_size = file_ofs; - comp_size = state.m_comp_size; - cur_archive_file_ofs = state.m_cur_archive_file_ofs; - } - - pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - } - - if (!(level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE)) { - mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; - mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; - - MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); - MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); - if (pExtra_data == NULL) { - if (comp_size > MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - - MZ_WRITE_LE32(local_dir_footer + 8, comp_size); - MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); - } else { - MZ_WRITE_LE64(local_dir_footer + 8, comp_size); - MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); - local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; - } - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, - local_dir_footer, - local_dir_footer_size) != local_dir_footer_size) - return MZ_FALSE; - - cur_archive_file_ofs += local_dir_footer_size; - } - - if (level_and_flags & MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE) { - if (pExtra_data != NULL) { - extra_size = mz_zip_writer_create_zip64_extra_data( - extra_data, (max_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, - (max_size >= MZ_UINT32_MAX) ? &comp_size : NULL, - (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs - : NULL); - } - - if (!mz_zip_writer_create_local_dir_header( - pZip, local_dir_header, (mz_uint16)archive_name_size, - (mz_uint16)(extra_size + user_extra_data_len), - (max_size >= MZ_UINT32_MAX) ? MZ_UINT32_MAX : uncomp_size, - (max_size >= MZ_UINT32_MAX) ? MZ_UINT32_MAX : comp_size, - uncomp_crc32, method, gen_flags, dos_time, dos_date)) - return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - - cur_archive_header_file_ofs = local_dir_header_ofs; - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_header_file_ofs, - local_dir_header, - sizeof(local_dir_header)) != sizeof(local_dir_header)) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - if (pExtra_data != NULL) { - cur_archive_header_file_ofs += sizeof(local_dir_header); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_header_file_ofs, - pArchive_name, - archive_name_size) != archive_name_size) { - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - - cur_archive_header_file_ofs += archive_name_size; - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_header_file_ofs, - extra_data, extra_size) != extra_size) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_archive_header_file_ofs += extra_size; - } - } - - if (pExtra_data != NULL) { - extra_size = mz_zip_writer_create_zip64_extra_data( - extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, - (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, - (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); - } - - if (!mz_zip_writer_add_to_central_dir( - pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, - (mz_uint16)extra_size, pComment, comment_size, uncomp_size, comp_size, - uncomp_crc32, method, gen_flags, dos_time, dos_date, - local_dir_header_ofs, ext_attributes, user_extra_data_central, - user_extra_data_central_len)) - return MZ_FALSE; - - pZip->m_total_files++; - pZip->m_archive_size = cur_archive_file_ofs; - - return MZ_TRUE; -} - -#ifndef MINIZ_NO_STDIO - -static size_t mz_file_read_func_stdio(void *pOpaque, mz_uint64 file_ofs, - void *pBuf, size_t n) { - MZ_FILE *pSrc_file = (MZ_FILE *)pOpaque; - mz_int64 cur_ofs = MZ_FTELL64(pSrc_file); - - if (((mz_int64)file_ofs < 0) || - (((cur_ofs != (mz_int64)file_ofs)) && - (MZ_FSEEK64(pSrc_file, (mz_int64)file_ofs, SEEK_SET)))) - return 0; - - return MZ_FREAD(pBuf, 1, n, pSrc_file); -} - -mz_bool mz_zip_writer_add_cfile( - mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, - mz_uint64 max_size, const MZ_TIME_T *pFile_time, const void *pComment, - mz_uint16 comment_size, mz_uint level_and_flags, mz_uint32 ext_attributes, - const char *user_extra_data, mz_uint user_extra_data_len, - const char *user_extra_data_central, mz_uint user_extra_data_central_len) { - return mz_zip_writer_add_read_buf_callback( - pZip, pArchive_name, mz_file_read_func_stdio, pSrc_file, max_size, - pFile_time, pComment, comment_size, level_and_flags, ext_attributes, - user_extra_data, user_extra_data_len, user_extra_data_central, - user_extra_data_central_len); -} - -mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, - const char *pSrc_filename, const void *pComment, - mz_uint16 comment_size, mz_uint level_and_flags, - mz_uint32 ext_attributes) { - MZ_FILE *pSrc_file = NULL; - mz_uint64 uncomp_size = 0; - MZ_TIME_T file_modified_time; - MZ_TIME_T *pFile_time = NULL; - mz_bool status; - - memset(&file_modified_time, 0, sizeof(file_modified_time)); - -#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) - pFile_time = &file_modified_time; - if (!mz_zip_get_file_modified_time(pSrc_filename, &file_modified_time)) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_STAT_FAILED); -#endif - - pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); - if (!pSrc_file) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); - - MZ_FSEEK64(pSrc_file, 0, SEEK_END); - uncomp_size = MZ_FTELL64(pSrc_file); - MZ_FSEEK64(pSrc_file, 0, SEEK_SET); - - status = mz_zip_writer_add_cfile( - pZip, pArchive_name, pSrc_file, uncomp_size, pFile_time, pComment, - comment_size, level_and_flags, ext_attributes, NULL, 0, NULL, 0); - - MZ_FCLOSE(pSrc_file); - - return status; -} -#endif /* #ifndef MINIZ_NO_STDIO */ - -static mz_bool mz_zip_writer_update_zip64_extension_block( - mz_zip_array *pNew_ext, mz_zip_archive *pZip, const mz_uint8 *pExt, - uint32_t ext_len, mz_uint64 *pComp_size, mz_uint64 *pUncomp_size, - mz_uint64 *pLocal_header_ofs, mz_uint32 *pDisk_start) { - /* + 64 should be enough for any new zip64 data */ - if (!mz_zip_array_reserve(pZip, pNew_ext, ext_len + 64, MZ_FALSE)) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - mz_zip_array_resize(pZip, pNew_ext, 0, MZ_FALSE); - - if ((pUncomp_size) || (pComp_size) || (pLocal_header_ofs) || (pDisk_start)) { - mz_uint8 new_ext_block[64]; - mz_uint8 *pDst = new_ext_block; - mz_write_le16(pDst, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); - mz_write_le16(pDst + sizeof(mz_uint16), 0); - pDst += sizeof(mz_uint16) * 2; - - if (pUncomp_size) { - mz_write_le64(pDst, *pUncomp_size); - pDst += sizeof(mz_uint64); - } - - if (pComp_size) { - mz_write_le64(pDst, *pComp_size); - pDst += sizeof(mz_uint64); - } - - if (pLocal_header_ofs) { - mz_write_le64(pDst, *pLocal_header_ofs); - pDst += sizeof(mz_uint64); - } - - if (pDisk_start) { - mz_write_le32(pDst, *pDisk_start); - pDst += sizeof(mz_uint32); - } - - mz_write_le16(new_ext_block + sizeof(mz_uint16), - (mz_uint16)((pDst - new_ext_block) - sizeof(mz_uint16) * 2)); - - if (!mz_zip_array_push_back(pZip, pNew_ext, new_ext_block, - pDst - new_ext_block)) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - if ((pExt) && (ext_len)) { - mz_uint32 extra_size_remaining = ext_len; - const mz_uint8 *pExtra_data = pExt; - - do { - mz_uint32 field_id, field_data_size, field_total_size; - - if (extra_size_remaining < (sizeof(mz_uint16) * 2)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - field_id = MZ_READ_LE16(pExtra_data); - field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); - field_total_size = field_data_size + sizeof(mz_uint16) * 2; - - if (field_total_size > extra_size_remaining) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - if (field_id != MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { - if (!mz_zip_array_push_back(pZip, pNew_ext, pExtra_data, - field_total_size)) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - pExtra_data += field_total_size; - extra_size_remaining -= field_total_size; - } while (extra_size_remaining); - } - - return MZ_TRUE; -} - -/* TODO: This func is now pretty freakin complex due to zip64, split it up? */ -mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, - mz_zip_archive *pSource_zip, - mz_uint src_file_index) { - mz_uint n, bit_flags, num_alignment_padding_bytes, - src_central_dir_following_data_size; - mz_uint64 src_archive_bytes_remaining, local_dir_header_ofs; - mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; - mz_uint32 - local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / - sizeof(mz_uint32)]; - mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; - mz_uint8 new_central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; - size_t orig_central_dir_size; - mz_zip_internal_state *pState; - void *pBuf; - const mz_uint8 *pSrc_central_header; - mz_zip_archive_file_stat src_file_stat; - mz_uint32 src_filename_len, src_comment_len, src_ext_len; - mz_uint32 local_header_filename_size, local_header_extra_len; - mz_uint64 local_header_comp_size, local_header_uncomp_size; - mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; - - /* Sanity checks */ - if ((!pZip) || (!pZip->m_pState) || - (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pSource_zip->m_pRead)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - pState = pZip->m_pState; - - /* Don't support copying files from zip64 archives to non-zip64, even though - * in some cases this is possible */ - if ((pSource_zip->m_pState->m_zip64) && (!pZip->m_pState->m_zip64)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - /* Get pointer to the source central dir header and crack it */ - if (NULL == - (pSrc_central_header = mz_zip_get_cdh(pSource_zip, src_file_index))) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_SIG_OFS) != - MZ_ZIP_CENTRAL_DIR_HEADER_SIG) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - src_filename_len = - MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS); - src_comment_len = - MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); - src_ext_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS); - src_central_dir_following_data_size = - src_filename_len + src_ext_len + src_comment_len; - - /* TODO: We don't support central dir's >= MZ_UINT32_MAX bytes right now (+32 - * fudge factor in case we need to add more extra data) */ - if ((pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + - src_central_dir_following_data_size + 32) >= MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); - - num_alignment_padding_bytes = - mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); - - if (!pState->m_zip64) { - if (pZip->m_total_files == MZ_UINT16_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - } else { - /* TODO: Our zip64 support still has some 32-bit limits that may not be - * worth fixing. */ - if (pZip->m_total_files == MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - } - - if (!mz_zip_file_stat_internal(pSource_zip, src_file_index, - pSrc_central_header, &src_file_stat, NULL)) - return MZ_FALSE; - - cur_src_file_ofs = src_file_stat.m_local_header_ofs; - cur_dst_file_ofs = pZip->m_archive_size; - - /* Read the source archive's local dir header */ - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, - pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - - if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - - cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; - - /* Compute the total size we need to copy (filename+extra data+compressed - * data) */ - local_header_filename_size = - MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); - local_header_extra_len = - MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); - local_header_comp_size = - MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); - local_header_uncomp_size = - MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); - src_archive_bytes_remaining = local_header_filename_size + - local_header_extra_len + - src_file_stat.m_comp_size; - - /* Try to find a zip64 extended information field */ - if ((local_header_extra_len) && - ((local_header_comp_size == MZ_UINT32_MAX) || - (local_header_uncomp_size == MZ_UINT32_MAX))) { - mz_zip_array file_data_array; - const mz_uint8 *pExtra_data; - mz_uint32 extra_size_remaining = local_header_extra_len; - - mz_zip_array_init(&file_data_array, 1); - if (!mz_zip_array_resize(pZip, &file_data_array, local_header_extra_len, - MZ_FALSE)) { - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, - src_file_stat.m_local_header_ofs + - MZ_ZIP_LOCAL_DIR_HEADER_SIZE + - local_header_filename_size, - file_data_array.m_p, local_header_extra_len) != - local_header_extra_len) { - mz_zip_array_clear(pZip, &file_data_array); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - } - - pExtra_data = (const mz_uint8 *)file_data_array.m_p; - - do { - mz_uint32 field_id, field_data_size, field_total_size; - - if (extra_size_remaining < (sizeof(mz_uint16) * 2)) { - mz_zip_array_clear(pZip, &file_data_array); - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - } - - field_id = MZ_READ_LE16(pExtra_data); - field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); - field_total_size = field_data_size + sizeof(mz_uint16) * 2; - - if (field_total_size > extra_size_remaining) { - mz_zip_array_clear(pZip, &file_data_array); - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - } - - if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { - const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); - - if (field_data_size < sizeof(mz_uint64) * 2) { - mz_zip_array_clear(pZip, &file_data_array); - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - } - - local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); - local_header_comp_size = MZ_READ_LE64( - pSrc_field_data + - sizeof(mz_uint64)); /* may be 0 if there's a descriptor */ - - found_zip64_ext_data_in_ldir = MZ_TRUE; - break; - } - - pExtra_data += field_total_size; - extra_size_remaining -= field_total_size; - } while (extra_size_remaining); - - mz_zip_array_clear(pZip, &file_data_array); - } - - if (!pState->m_zip64) { - /* Try to detect if the new archive will most likely wind up too big and - * bail early (+(sizeof(mz_uint32) * 4) is for the optional descriptor which - * could be present, +64 is a fudge factor). */ - /* We also check when the archive is finalized so this doesn't need to be - * perfect. */ - mz_uint64 approx_new_archive_size = - cur_dst_file_ofs + num_alignment_padding_bytes + - MZ_ZIP_LOCAL_DIR_HEADER_SIZE + src_archive_bytes_remaining + - (sizeof(mz_uint32) * 4) + pState->m_central_dir.m_size + - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 64; - - if (approx_new_archive_size >= MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - } - - /* Write dest archive padding */ - if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, - num_alignment_padding_bytes)) - return MZ_FALSE; - - cur_dst_file_ofs += num_alignment_padding_bytes; - - local_dir_header_ofs = cur_dst_file_ofs; - if (pZip->m_file_offset_alignment) { - MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == - 0); - } - - /* The original zip's local header+ext block doesn't change, even with zip64, - * so we can just copy it over to the dest zip */ - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != - MZ_ZIP_LOCAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; - - /* Copy over the source archive bytes to the dest archive, also ensure we have - * enough buf space to handle optional data descriptor */ - if (NULL == (pBuf = pZip->m_pAlloc( - pZip->m_pAlloc_opaque, 1, - (size_t)MZ_MAX(32U, MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, - src_archive_bytes_remaining))))) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - while (src_archive_bytes_remaining) { - n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, - src_archive_bytes_remaining); - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, - n) != n) { - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - } - cur_src_file_ofs += n; - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - cur_dst_file_ofs += n; - - src_archive_bytes_remaining -= n; - } - - /* Now deal with the optional data descriptor */ - bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); - if (bit_flags & 8) { - /* Copy data descriptor */ - if ((pSource_zip->m_pState->m_zip64) || (found_zip64_ext_data_in_ldir)) { - /* src is zip64, dest must be zip64 */ - - /* name uint32_t's */ - /* id 1 (optional in zip64?) */ - /* crc 1 */ - /* comp_size 2 */ - /* uncomp_size 2 */ - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, - pBuf, (sizeof(mz_uint32) * 6)) != - (sizeof(mz_uint32) * 6)) { - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - } - - n = sizeof(mz_uint32) * - ((MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID) ? 6 : 5); - } else { - /* src is NOT zip64 */ - mz_bool has_id; - - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, - pBuf, sizeof(mz_uint32) * 4) != - sizeof(mz_uint32) * 4) { - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - } - - has_id = (MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID); - - if (pZip->m_pState->m_zip64) { - /* dest is zip64, so upgrade the data descriptor */ - const mz_uint32 *pSrc_descriptor = - (const mz_uint32 *)((const mz_uint8 *)pBuf + - (has_id ? sizeof(mz_uint32) : 0)); - const mz_uint32 src_crc32 = pSrc_descriptor[0]; - const mz_uint64 src_comp_size = pSrc_descriptor[1]; - const mz_uint64 src_uncomp_size = pSrc_descriptor[2]; - - mz_write_le32((mz_uint8 *)pBuf, MZ_ZIP_DATA_DESCRIPTOR_ID); - mz_write_le32((mz_uint8 *)pBuf + sizeof(mz_uint32) * 1, src_crc32); - mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 2, src_comp_size); - mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 4, - src_uncomp_size); - - n = sizeof(mz_uint32) * 6; - } else { - /* dest is NOT zip64, just copy it as-is */ - n = sizeof(mz_uint32) * (has_id ? 4 : 3); - } - } - - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - } - - cur_src_file_ofs += n; - cur_dst_file_ofs += n; - } - pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); - - /* Finally, add the new central dir header */ - orig_central_dir_size = pState->m_central_dir.m_size; - - memcpy(new_central_header, pSrc_central_header, - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); - - if (pState->m_zip64) { - /* This is the painful part: We need to write a new central dir header + ext - * block with updated zip64 fields, and ensure the old fields (if any) are - * not included. */ - const mz_uint8 *pSrc_ext = - pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len; - mz_zip_array new_ext_block; - - mz_zip_array_init(&new_ext_block, sizeof(mz_uint8)); - - MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, - MZ_UINT32_MAX); - MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, - MZ_UINT32_MAX); - MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, - MZ_UINT32_MAX); - - if (!mz_zip_writer_update_zip64_extension_block( - &new_ext_block, pZip, pSrc_ext, src_ext_len, - &src_file_stat.m_comp_size, &src_file_stat.m_uncomp_size, - &local_dir_header_ofs, NULL)) { - mz_zip_array_clear(pZip, &new_ext_block); - return MZ_FALSE; - } - - MZ_WRITE_LE16(new_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS, - new_ext_block.m_size); - - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, - new_central_header, - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) { - mz_zip_array_clear(pZip, &new_ext_block); - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, - pSrc_central_header + - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, - src_filename_len)) { - mz_zip_array_clear(pZip, &new_ext_block); - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, - MZ_FALSE); - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_ext_block.m_p, - new_ext_block.m_size)) { - mz_zip_array_clear(pZip, &new_ext_block); - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, - MZ_FALSE); - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, - pSrc_central_header + - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + - src_filename_len + src_ext_len, - src_comment_len)) { - mz_zip_array_clear(pZip, &new_ext_block); - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, - MZ_FALSE); - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - mz_zip_array_clear(pZip, &new_ext_block); - } else { - /* sanity checks */ - if (cur_dst_file_ofs > MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - - if (local_dir_header_ofs >= MZ_UINT32_MAX) - return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - - MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, - local_dir_header_ofs); - - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, - new_central_header, - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, - pSrc_central_header + - MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, - src_central_dir_following_data_size)) { - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, - MZ_FALSE); - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - } - - /* This shouldn't trigger unless we screwed up during the initial sanity - * checks */ - if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) { - /* TODO: Support central dirs >= 32-bits in size */ - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, - MZ_FALSE); - return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); - } - - n = (mz_uint32)orig_central_dir_size; - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) { - mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, - MZ_FALSE); - return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - } - - pZip->m_total_files++; - pZip->m_archive_size = cur_dst_file_ofs; - - return MZ_TRUE; -} - -mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) { - mz_zip_internal_state *pState; - mz_uint64 central_dir_ofs, central_dir_size; - mz_uint8 hdr[256]; - - if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - pState = pZip->m_pState; - - if (pState->m_zip64) { - if ((pZip->m_total_files > MZ_UINT32_MAX) || - (pState->m_central_dir.m_size >= MZ_UINT32_MAX)) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - } else { - if ((pZip->m_total_files > MZ_UINT16_MAX) || - ((pZip->m_archive_size + pState->m_central_dir.m_size + - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX)) - return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - } - - central_dir_ofs = 0; - central_dir_size = 0; - if (pZip->m_total_files) { - /* Write central directory */ - central_dir_ofs = pZip->m_archive_size; - central_dir_size = pState->m_central_dir.m_size; - pZip->m_central_directory_file_ofs = central_dir_ofs; - if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, - pState->m_central_dir.m_p, - (size_t)central_dir_size) != central_dir_size) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - pZip->m_archive_size += central_dir_size; - } - - if (pState->m_zip64) { - /* Write zip64 end of central directory header */ - mz_uint64 rel_ofs_to_zip64_ecdr = pZip->m_archive_size; - - MZ_CLEAR_OBJ(hdr); - MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDH_SIG_OFS, - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG); - MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS, - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - sizeof(mz_uint32) - - sizeof(mz_uint64)); - MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS, - 0x031E); /* TODO: always Unix */ - MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_NEEDED_OFS, 0x002D); - MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, - pZip->m_total_files); - MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS, - pZip->m_total_files); - MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_SIZE_OFS, central_dir_size); - MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_OFS_OFS, central_dir_ofs); - if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) != - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE; - - /* Write zip64 end of central directory locator */ - MZ_CLEAR_OBJ(hdr); - MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_SIG_OFS, - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG); - MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS, - rel_ofs_to_zip64_ecdr); - MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS, 1); - if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) != - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - - pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE; - } - - /* Write end of central directory record */ - MZ_CLEAR_OBJ(hdr); - MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); - MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, - MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); - MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, - MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); - MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, - MZ_MIN(MZ_UINT32_MAX, central_dir_size)); - MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, - MZ_MIN(MZ_UINT32_MAX, central_dir_ofs)); - - if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != - MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); - -#ifndef MINIZ_NO_STDIO - if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) - return mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); -#endif /* #ifndef MINIZ_NO_STDIO */ - - pZip->m_archive_size += MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE; - - pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; - return MZ_TRUE; -} - -mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, - size_t *pSize) { - if ((!ppBuf) || (!pSize)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - *ppBuf = NULL; - *pSize = 0; - - if ((!pZip) || (!pZip->m_pState)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (pZip->m_pWrite != mz_zip_heap_write_func) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - if (!mz_zip_writer_finalize_archive(pZip)) - return MZ_FALSE; - - *ppBuf = pZip->m_pState->m_pMem; - *pSize = pZip->m_pState->m_mem_size; - pZip->m_pState->m_pMem = NULL; - pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; - - return MZ_TRUE; -} - -mz_bool mz_zip_writer_end(mz_zip_archive *pZip) { - return mz_zip_writer_end_internal(pZip, MZ_TRUE); -} - -#ifndef MINIZ_NO_STDIO -mz_bool mz_zip_add_mem_to_archive_file_in_place( - const char *pZip_filename, const char *pArchive_name, const void *pBuf, - size_t buf_size, const void *pComment, mz_uint16 comment_size, - mz_uint level_and_flags) { - return mz_zip_add_mem_to_archive_file_in_place_v2( - pZip_filename, pArchive_name, pBuf, buf_size, pComment, comment_size, - level_and_flags, NULL); -} - -mz_bool mz_zip_add_mem_to_archive_file_in_place_v2( - const char *pZip_filename, const char *pArchive_name, const void *pBuf, - size_t buf_size, const void *pComment, mz_uint16 comment_size, - mz_uint level_and_flags, mz_zip_error *pErr) { - mz_bool status, created_new_archive = MZ_FALSE; - mz_zip_archive zip_archive; - struct MZ_FILE_STAT_STRUCT file_stat; - mz_zip_error actual_err = MZ_ZIP_NO_ERROR; - - mz_zip_zero_struct(&zip_archive); - if ((int)level_and_flags < 0) - level_and_flags = MZ_DEFAULT_LEVEL; - - if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || - ((comment_size) && (!pComment)) || - ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) { - if (pErr) - *pErr = MZ_ZIP_INVALID_PARAMETER; - return MZ_FALSE; - } - - if (!mz_zip_writer_validate_archive_name(pArchive_name)) { - if (pErr) - *pErr = MZ_ZIP_INVALID_FILENAME; - return MZ_FALSE; - } - - /* Important: The regular non-64 bit version of stat() can fail here if the - * file is very large, which could cause the archive to be overwritten. */ - /* So be sure to compile with _LARGEFILE64_SOURCE 1 */ - if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) { - /* Create a new archive. */ - if (!mz_zip_writer_init_file_v2(&zip_archive, pZip_filename, 0, - level_and_flags)) { - if (pErr) - *pErr = zip_archive.m_last_error; - return MZ_FALSE; - } - - created_new_archive = MZ_TRUE; - } else { - /* Append to an existing archive. */ - if (!mz_zip_reader_init_file_v2( - &zip_archive, pZip_filename, - level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, - 0)) { - if (pErr) - *pErr = zip_archive.m_last_error; - return MZ_FALSE; - } - - if (!mz_zip_writer_init_from_reader_v2(&zip_archive, pZip_filename, - level_and_flags)) { - if (pErr) - *pErr = zip_archive.m_last_error; - - mz_zip_reader_end_internal(&zip_archive, MZ_FALSE); - - return MZ_FALSE; - } - } - - status = - mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, - pComment, comment_size, level_and_flags, 0, 0); - actual_err = zip_archive.m_last_error; - - /* Always finalize, even if adding failed for some reason, so we have a valid - * central directory. (This may not always succeed, but we can try.) */ - if (!mz_zip_writer_finalize_archive(&zip_archive)) { - if (!actual_err) - actual_err = zip_archive.m_last_error; - - status = MZ_FALSE; - } - - if (!mz_zip_writer_end_internal(&zip_archive, status)) { - if (!actual_err) - actual_err = zip_archive.m_last_error; - - status = MZ_FALSE; - } - - if ((!status) && (created_new_archive)) { - /* It's a new archive and something went wrong, so just delete it. */ - int ignoredStatus = MZ_DELETE_FILE(pZip_filename); - (void)ignoredStatus; - } - - if (pErr) - *pErr = actual_err; - - return status; -} - -void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, - const char *pArchive_name, - const char *pComment, - size_t *pSize, mz_uint flags, - mz_zip_error *pErr) { - mz_uint32 file_index; - mz_zip_archive zip_archive; - void *p = NULL; - - if (pSize) - *pSize = 0; - - if ((!pZip_filename) || (!pArchive_name)) { - if (pErr) - *pErr = MZ_ZIP_INVALID_PARAMETER; - - return NULL; - } - - mz_zip_zero_struct(&zip_archive); - if (!mz_zip_reader_init_file_v2( - &zip_archive, pZip_filename, - flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) { - if (pErr) - *pErr = zip_archive.m_last_error; - - return NULL; - } - - if (mz_zip_reader_locate_file_v2(&zip_archive, pArchive_name, pComment, flags, - &file_index)) { - p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); - } - - mz_zip_reader_end_internal(&zip_archive, p != NULL); - - if (pErr) - *pErr = zip_archive.m_last_error; - - return p; -} - -void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, - const char *pArchive_name, - size_t *pSize, mz_uint flags) { - return mz_zip_extract_archive_file_to_heap_v2(pZip_filename, pArchive_name, - NULL, pSize, flags, NULL); -} - -#endif /* #ifndef MINIZ_NO_STDIO */ - -#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ - -/* ------------------- Misc utils */ - -mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip) { - return pZip ? pZip->m_zip_mode : MZ_ZIP_MODE_INVALID; -} - -mz_zip_type mz_zip_get_type(mz_zip_archive *pZip) { - return pZip ? pZip->m_zip_type : MZ_ZIP_TYPE_INVALID; -} - -mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num) { - mz_zip_error prev_err; - - if (!pZip) - return MZ_ZIP_INVALID_PARAMETER; - - prev_err = pZip->m_last_error; - - pZip->m_last_error = err_num; - return prev_err; -} - -mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip) { - if (!pZip) - return MZ_ZIP_INVALID_PARAMETER; - - return pZip->m_last_error; -} - -mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip) { - return mz_zip_set_last_error(pZip, MZ_ZIP_NO_ERROR); -} - -mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip) { - mz_zip_error prev_err; - - if (!pZip) - return MZ_ZIP_INVALID_PARAMETER; - - prev_err = pZip->m_last_error; - - pZip->m_last_error = MZ_ZIP_NO_ERROR; - return prev_err; -} - -const char *mz_zip_get_error_string(mz_zip_error mz_err) { - switch (mz_err) { - case MZ_ZIP_NO_ERROR: - return "no error"; - case MZ_ZIP_UNDEFINED_ERROR: - return "undefined error"; - case MZ_ZIP_TOO_MANY_FILES: - return "too many files"; - case MZ_ZIP_FILE_TOO_LARGE: - return "file too large"; - case MZ_ZIP_UNSUPPORTED_METHOD: - return "unsupported method"; - case MZ_ZIP_UNSUPPORTED_ENCRYPTION: - return "unsupported encryption"; - case MZ_ZIP_UNSUPPORTED_FEATURE: - return "unsupported feature"; - case MZ_ZIP_FAILED_FINDING_CENTRAL_DIR: - return "failed finding central directory"; - case MZ_ZIP_NOT_AN_ARCHIVE: - return "not a ZIP archive"; - case MZ_ZIP_INVALID_HEADER_OR_CORRUPTED: - return "invalid header or archive is corrupted"; - case MZ_ZIP_UNSUPPORTED_MULTIDISK: - return "unsupported multidisk archive"; - case MZ_ZIP_DECOMPRESSION_FAILED: - return "decompression failed or archive is corrupted"; - case MZ_ZIP_COMPRESSION_FAILED: - return "compression failed"; - case MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE: - return "unexpected decompressed size"; - case MZ_ZIP_CRC_CHECK_FAILED: - return "CRC-32 check failed"; - case MZ_ZIP_UNSUPPORTED_CDIR_SIZE: - return "unsupported central directory size"; - case MZ_ZIP_ALLOC_FAILED: - return "allocation failed"; - case MZ_ZIP_FILE_OPEN_FAILED: - return "file open failed"; - case MZ_ZIP_FILE_CREATE_FAILED: - return "file create failed"; - case MZ_ZIP_FILE_WRITE_FAILED: - return "file write failed"; - case MZ_ZIP_FILE_READ_FAILED: - return "file read failed"; - case MZ_ZIP_FILE_CLOSE_FAILED: - return "file close failed"; - case MZ_ZIP_FILE_SEEK_FAILED: - return "file seek failed"; - case MZ_ZIP_FILE_STAT_FAILED: - return "file stat failed"; - case MZ_ZIP_INVALID_PARAMETER: - return "invalid parameter"; - case MZ_ZIP_INVALID_FILENAME: - return "invalid filename"; - case MZ_ZIP_BUF_TOO_SMALL: - return "buffer too small"; - case MZ_ZIP_INTERNAL_ERROR: - return "internal error"; - case MZ_ZIP_FILE_NOT_FOUND: - return "file not found"; - case MZ_ZIP_ARCHIVE_TOO_LARGE: - return "archive is too large"; - case MZ_ZIP_VALIDATION_FAILED: - return "validation failed"; - case MZ_ZIP_WRITE_CALLBACK_FAILED: - return "write calledback failed"; - default: - break; - } - - return "unknown error"; -} - -/* Note: Just because the archive is not zip64 doesn't necessarily mean it - * doesn't have Zip64 extended information extra field, argh. */ -mz_bool mz_zip_is_zip64(mz_zip_archive *pZip) { - if ((!pZip) || (!pZip->m_pState)) - return MZ_FALSE; - - return pZip->m_pState->m_zip64; -} - -size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip) { - if ((!pZip) || (!pZip->m_pState)) - return 0; - - return pZip->m_pState->m_central_dir.m_size; -} - -mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) { - return pZip ? pZip->m_total_files : 0; -} - -mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip) { - if (!pZip) - return 0; - return pZip->m_archive_size; -} - -mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip) { - if ((!pZip) || (!pZip->m_pState)) - return 0; - return pZip->m_pState->m_file_archive_start_ofs; -} - -MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip) { - if ((!pZip) || (!pZip->m_pState)) - return 0; - return pZip->m_pState->m_pFile; -} - -size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, - void *pBuf, size_t n) { - if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pZip->m_pRead)) - return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - - return pZip->m_pRead(pZip->m_pIO_opaque, file_ofs, pBuf, n); -} - -mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, - char *pFilename, mz_uint filename_buf_size) { - mz_uint n; - const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); - if (!p) { - if (filename_buf_size) - pFilename[0] = '\0'; - mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - return 0; - } - n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); - if (filename_buf_size) { - n = MZ_MIN(n, filename_buf_size - 1); - memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); - pFilename[n] = '\0'; - } - return n + 1; -} - -mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, - mz_zip_archive_file_stat *pStat) { - return mz_zip_file_stat_internal( - pZip, file_index, mz_zip_get_cdh(pZip, file_index), pStat, NULL); -} - -mz_bool mz_zip_end(mz_zip_archive *pZip) { - if (!pZip) - return MZ_FALSE; - - if (pZip->m_zip_mode == MZ_ZIP_MODE_READING) - return mz_zip_reader_end(pZip); -#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS - else if ((pZip->m_zip_mode == MZ_ZIP_MODE_WRITING) || - (pZip->m_zip_mode == MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)) - return mz_zip_writer_end(pZip); -#endif - - return MZ_FALSE; -} - -#ifdef __cplusplus -} -#endif - -#endif /*#ifndef MINIZ_NO_ARCHIVE_APIS*/ -#endif // MINIZ_HEADER_FILE_ONLY \ No newline at end of file diff --git a/OgreMain/src/zip/zip.c b/OgreMain/src/zip/zip.c deleted file mode 100644 index 0b213d631e8..00000000000 --- a/OgreMain/src/zip/zip.c +++ /dev/null @@ -1,1626 +0,0 @@ -/* - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ -#define __STDC_WANT_LIB_EXT1__ 1 - -#include -#include -#include - -#if defined(_WIN32) || defined(__WIN32__) || defined(_MSC_VER) || \ - defined(__MINGW32__) -/* Win32, DOS, MSVC, MSVS */ -#include - -#define STRCLONE(STR) ((STR) ? _strdup(STR) : NULL) -#define HAS_DEVICE(P) \ - ((((P)[0] >= 'A' && (P)[0] <= 'Z') || ((P)[0] >= 'a' && (P)[0] <= 'z')) && \ - (P)[1] == ':') -#define FILESYSTEM_PREFIX_LEN(P) (HAS_DEVICE(P) ? 2 : 0) - -#else - -#include // needed for symlink() -#define STRCLONE(STR) ((STR) ? strdup(STR) : NULL) - -#endif - -#ifdef __MINGW32__ -#include -#include -#endif - -#include "miniz.h" -#include "zip.h" - -#ifdef _MSC_VER -#include - -#define ftruncate(fd, sz) (-(_chsize_s((fd), (sz)) != 0)) -#define fileno _fileno -#endif - -#ifndef HAS_DEVICE -#define HAS_DEVICE(P) 0 -#endif - -#ifndef FILESYSTEM_PREFIX_LEN -#define FILESYSTEM_PREFIX_LEN(P) 0 -#endif - -#ifndef ISSLASH -#define ISSLASH(C) ((C) == '/' || (C) == '\\') -#endif - -#define CLEANUP(ptr) \ - do { \ - if (ptr) { \ - free((void *)ptr); \ - ptr = NULL; \ - } \ - } while (0) - -struct zip_entry_t { - int index; - char *name; - mz_uint64 uncomp_size; - mz_uint64 comp_size; - mz_uint32 uncomp_crc32; - mz_uint64 offset; - mz_uint8 header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; - mz_uint64 header_offset; - mz_uint16 method; - mz_zip_writer_add_state state; - tdefl_compressor comp; - mz_uint32 external_attr; - time_t m_time; -}; - -struct zip_t { - mz_zip_archive archive; - mz_uint level; - struct zip_entry_t entry; -}; - -enum zip_modify_t { - MZ_KEEP = 0, - MZ_DELETE = 1, - MZ_MOVE = 2, -}; - -struct zip_entry_mark_t { - int file_index; - enum zip_modify_t type; - mz_uint64 m_local_header_ofs; - size_t lf_length; -}; - -static const char *const zip_errlist[30] = { - NULL, - "not initialized\0", - "invalid entry name\0", - "entry not found\0", - "invalid zip mode\0", - "invalid compression level\0", - "no zip 64 support\0", - "memset error\0", - "cannot write data to entry\0", - "cannot initialize tdefl compressor\0", - "invalid index\0", - "header not found\0", - "cannot flush tdefl buffer\0", - "cannot write entry header\0", - "cannot create entry header\0", - "cannot write to central dir\0", - "cannot open file\0", - "invalid entry type\0", - "extracting data using no memory allocation\0", - "file not found\0", - "no permission\0", - "out of memory\0", - "invalid zip archive name\0", - "make dir error\0", - "symlink error\0", - "close archive error\0", - "capacity size too small\0", - "fseek error\0", - "fread error\0", - "fwrite error\0", -}; - -const char *zip_strerror(int errnum) { - errnum = -errnum; - if (errnum <= 0 || errnum >= 30) { - return NULL; - } - - return zip_errlist[errnum]; -} - -static const char *zip_basename(const char *name) { - char const *p; - char const *base = name += FILESYSTEM_PREFIX_LEN(name); - int all_slashes = 1; - - for (p = name; *p; p++) { - if (ISSLASH(*p)) - base = p + 1; - else - all_slashes = 0; - } - - /* If NAME is all slashes, arrange to return `/'. */ - if (*base == '\0' && ISSLASH(*name) && all_slashes) - --base; - - return base; -} - -static int zip_mkpath(char *path) { - char *p; - char npath[MAX_PATH + 1]; - int len = 0; - int has_device = HAS_DEVICE(path); - - memset(npath, 0, MAX_PATH + 1); - if (has_device) { - // only on windows - npath[0] = path[0]; - npath[1] = path[1]; - len = 2; - } - for (p = path + len; *p && len < MAX_PATH; p++) { - if (ISSLASH(*p) && ((!has_device && len > 0) || (has_device && len > 2))) { -#if defined(_WIN32) || defined(__WIN32__) || defined(_MSC_VER) || \ - defined(__MINGW32__) -#else - if ('\\' == *p) { - *p = '/'; - } -#endif - - if (MZ_MKDIR(npath) == -1) { - if (errno != EEXIST) { - return ZIP_EMKDIR; - } - } - } - npath[len++] = *p; - } - - return 0; -} - -static char *zip_strrpl(const char *str, size_t n, char oldchar, char newchar) { - char c; - size_t i; - char *rpl = (char *)calloc((1 + n), sizeof(char)); - char *begin = rpl; - if (!rpl) { - return NULL; - } - - for (i = 0; (i < n) && (c = *str++); ++i) { - if (c == oldchar) { - c = newchar; - } - *rpl++ = c; - } - - return begin; -} - -static char *zip_name_normalize(char *name, char *const nname, size_t len) { - size_t offn = 0; - size_t offnn = 0, ncpy = 0; - - if (name == NULL || nname == NULL || len <= 0) { - return NULL; - } - // skip trailing '/' - while (ISSLASH(*name)) - name++; - - for (; offn < len; offn++) { - if (ISSLASH(name[offn])) { - if (ncpy > 0 && strcmp(&nname[offnn], ".\0") && - strcmp(&nname[offnn], "..\0")) { - offnn += ncpy; - nname[offnn++] = name[offn]; // append '/' - } - ncpy = 0; - } else { - nname[offnn + ncpy] = name[offn]; - ncpy++; - } - } - - // at the end, extra check what we've already copied - if (ncpy == 0 || !strcmp(&nname[offnn], ".\0") || - !strcmp(&nname[offnn], "..\0")) { - nname[offnn] = 0; - } - return nname; -} - -static mz_bool zip_name_match(const char *name1, const char *name2) { - size_t len2 = strlen(name2); - char *nname2 = zip_strrpl(name2, len2, '\\', '/'); - if (!nname2) { - return MZ_FALSE; - } - - mz_bool res = (strcmp(name1, nname2) == 0) ? MZ_TRUE : MZ_FALSE; - CLEANUP(nname2); - return res; -} - -static int zip_archive_truncate(mz_zip_archive *pzip) { - mz_zip_internal_state *pState = pzip->m_pState; - mz_uint64 file_size = pzip->m_archive_size; - if ((pzip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) { - return 0; - } - if (pzip->m_zip_mode == MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED) { - if (pState->m_pFile) { - int fd = fileno(pState->m_pFile); - return ftruncate(fd, file_size); - } - } - return 0; -} - -static int zip_archive_extract(mz_zip_archive *zip_archive, const char *dir, - int (*on_extract)(const char *filename, - void *arg), - void *arg) { - int err = 0; - mz_uint i, n; - char path[MAX_PATH + 1]; - char symlink_to[MAX_PATH + 1]; - mz_zip_archive_file_stat info; - size_t dirlen = 0; - mz_uint32 xattr = 0; - - memset(path, 0, sizeof(path)); - memset(symlink_to, 0, sizeof(symlink_to)); - - dirlen = strlen(dir); - if (dirlen + 1 > MAX_PATH) { - return ZIP_EINVENTNAME; - } - - memset((void *)&info, 0, sizeof(mz_zip_archive_file_stat)); - -#if defined(_MSC_VER) - strcpy_s(path, MAX_PATH, dir); -#else - strcpy(path, dir); -#endif - - if (!ISSLASH(path[dirlen - 1])) { -#if defined(_WIN32) || defined(__WIN32__) - path[dirlen] = '\\'; -#else - path[dirlen] = '/'; -#endif - ++dirlen; - } - - // Get and print information about each file in the archive. - n = mz_zip_reader_get_num_files(zip_archive); - for (i = 0; i < n; ++i) { - if (!mz_zip_reader_file_stat(zip_archive, i, &info)) { - // Cannot get information about zip archive; - err = ZIP_ENOENT; - goto out; - } - - if (!zip_name_normalize(info.m_filename, info.m_filename, - strlen(info.m_filename))) { - // Cannot normalize file name; - err = ZIP_EINVENTNAME; - goto out; - } -#if defined(_MSC_VER) - strncpy_s(&path[dirlen], MAX_PATH - dirlen, info.m_filename, - MAX_PATH - dirlen); -#else - strncpy(&path[dirlen], info.m_filename, MAX_PATH - dirlen); -#endif - err = zip_mkpath(path); - if (err < 0) { - // Cannot make a path - goto out; - } - - if ((((info.m_version_made_by >> 8) == 3) || - ((info.m_version_made_by >> 8) == - 19)) // if zip is produced on Unix or macOS (3 and 19 from - // section 4.4.2.2 of zip standard) - && info.m_external_attr & - (0x20 << 24)) { // and has sym link attribute (0x80 is file, 0x40 - // is directory) -#if defined(_WIN32) || defined(__WIN32__) || defined(_MSC_VER) || \ - defined(__MINGW32__) -#else - if (info.m_uncomp_size > MAX_PATH || - !mz_zip_reader_extract_to_mem_no_alloc(zip_archive, i, symlink_to, - MAX_PATH, 0, NULL, 0)) { - err = ZIP_EMEMNOALLOC; - goto out; - } - symlink_to[info.m_uncomp_size] = '\0'; - if (symlink(symlink_to, path) != 0) { - err = ZIP_ESYMLINK; - goto out; - } -#endif - } else { - if (!mz_zip_reader_is_file_a_directory(zip_archive, i)) { - if (!mz_zip_reader_extract_to_file(zip_archive, i, path, 0)) { - // Cannot extract zip archive to file - err = ZIP_ENOFILE; - goto out; - } - } - -#if defined(_MSC_VER) - (void)xattr; // unused -#else - xattr = (info.m_external_attr >> 16) & 0xFFFF; - if (xattr > 0) { - if (chmod(path, (mode_t)xattr) < 0) { - err = ZIP_ENOPERM; - goto out; - } - } -#endif - } - - if (on_extract) { - if (on_extract(path, arg) < 0) { - goto out; - } - } - } - -out: - // Close the archive, freeing any resources it was using - if (!mz_zip_reader_end(zip_archive)) { - // Cannot end zip reader - err = ZIP_ECLSZIP; - } - return err; -} - -static inline void zip_archive_finalize(mz_zip_archive *pzip) { - mz_zip_writer_finalize_archive(pzip); - zip_archive_truncate(pzip); -} - -static ssize_t zip_entry_mark(struct zip_t *zip, - struct zip_entry_mark_t *entry_mark, int n, - char *const entries[], const size_t len) { - int i = 0; - ssize_t err = 0; - if (!zip || !entry_mark || !entries) { - return ZIP_ENOINIT; - } - - mz_zip_archive_file_stat file_stat; - mz_uint64 d_pos = ~0UL; - for (i = 0; i < n; ++i) { - if ((err = zip_entry_openbyindex(zip, i))) { - return (ssize_t)err; - } - - mz_bool name_matches = MZ_FALSE; - for (int j = 0; j < (const int)len; ++j) { - if (zip_name_match(zip->entry.name, entries[j])) { - name_matches = MZ_TRUE; - break; - } - } - if (name_matches) { - entry_mark[i].type = MZ_DELETE; - } else { - entry_mark[i].type = MZ_KEEP; - } - - if (!mz_zip_reader_file_stat(&zip->archive, i, &file_stat)) { - return ZIP_ENOENT; - } - - zip_entry_close(zip); - - entry_mark[i].m_local_header_ofs = file_stat.m_local_header_ofs; - entry_mark[i].file_index = -1; - entry_mark[i].lf_length = 0; - if ((entry_mark[i].type) == MZ_DELETE && - (d_pos > entry_mark[i].m_local_header_ofs)) { - d_pos = entry_mark[i].m_local_header_ofs; - } - } - - for (i = 0; i < n; ++i) { - if ((entry_mark[i].m_local_header_ofs > d_pos) && - (entry_mark[i].type != MZ_DELETE)) { - entry_mark[i].type = MZ_MOVE; - } - } - return err; -} - -static int zip_index_next(mz_uint64 *local_header_ofs_array, int cur_index) { - int new_index = 0; - for (int i = cur_index - 1; i >= 0; --i) { - if (local_header_ofs_array[cur_index] > local_header_ofs_array[i]) { - new_index = i + 1; - return new_index; - } - } - return new_index; -} - -static int zip_sort(mz_uint64 *local_header_ofs_array, int cur_index) { - int nxt_index = zip_index_next(local_header_ofs_array, cur_index); - - if (nxt_index != cur_index) { - mz_uint64 temp = local_header_ofs_array[cur_index]; - for (int i = cur_index; i > nxt_index; i--) { - local_header_ofs_array[i] = local_header_ofs_array[i - 1]; - } - local_header_ofs_array[nxt_index] = temp; - } - return nxt_index; -} - -static int zip_index_update(struct zip_entry_mark_t *entry_mark, int last_index, - int nxt_index) { - for (int j = 0; j < last_index; j++) { - if (entry_mark[j].file_index >= nxt_index) { - entry_mark[j].file_index += 1; - } - } - entry_mark[nxt_index].file_index = last_index; - return 0; -} - -static int zip_entry_finalize(struct zip_t *zip, - struct zip_entry_mark_t *entry_mark, - const int n) { - - int i = 0; - mz_uint64 *local_header_ofs_array = (mz_uint64 *)calloc(n, sizeof(mz_uint64)); - if (!local_header_ofs_array) { - return ZIP_EOOMEM; - } - - for (i = 0; i < n; ++i) { - local_header_ofs_array[i] = entry_mark[i].m_local_header_ofs; - int index = zip_sort(local_header_ofs_array, i); - - if (index != i) { - zip_index_update(entry_mark, i, index); - } - entry_mark[i].file_index = index; - } - - size_t *length = (size_t *)calloc(n, sizeof(size_t)); - if (!length) { - CLEANUP(local_header_ofs_array); - return ZIP_EOOMEM; - } - for (i = 0; i < n - 1; i++) { - length[i] = - (size_t)(local_header_ofs_array[i + 1] - local_header_ofs_array[i]); - } - length[n - 1] = - (size_t)(zip->archive.m_archive_size - local_header_ofs_array[n - 1]); - - for (i = 0; i < n; i++) { - entry_mark[i].lf_length = length[entry_mark[i].file_index]; - } - - CLEANUP(length); - CLEANUP(local_header_ofs_array); - return 0; -} - -static ssize_t zip_entry_set(struct zip_t *zip, - struct zip_entry_mark_t *entry_mark, int n, - char *const entries[], const size_t len) { - ssize_t err = 0; - - if ((err = zip_entry_mark(zip, entry_mark, n, entries, len)) < 0) { - return err; - } - if ((err = zip_entry_finalize(zip, entry_mark, n)) < 0) { - return err; - } - return 0; -} - -static ssize_t zip_file_move(MZ_FILE *m_pFile, const mz_uint64 to, - const mz_uint64 from, const size_t length, - mz_uint8 *move_buf, const size_t capacity_size) { - if (length > capacity_size) { - return ZIP_ECAPSIZE; - } - if (MZ_FSEEK64(m_pFile, from, SEEK_SET)) { - MZ_FCLOSE(m_pFile); - return ZIP_EFSEEK; - } - - if (fread(move_buf, 1, length, m_pFile) != length) { - MZ_FCLOSE(m_pFile); - return ZIP_EFREAD; - } - if (MZ_FSEEK64(m_pFile, to, SEEK_SET)) { - MZ_FCLOSE(m_pFile); - return ZIP_EFSEEK; - } - if (fwrite(move_buf, 1, length, m_pFile) != length) { - MZ_FCLOSE(m_pFile); - return ZIP_EFWRITE; - } - return (ssize_t)length; -} - -static ssize_t zip_files_move(MZ_FILE *m_pFile, mz_uint64 writen_num, - mz_uint64 read_num, size_t length) { - ssize_t n = 0; - const size_t page_size = 1 << 12; // 4K - mz_uint8 *move_buf = (mz_uint8 *)calloc(1, page_size); - if (!move_buf) { - return ZIP_EOOMEM; - } - - ssize_t moved_length = 0; - ssize_t move_count = 0; - while ((mz_int64)length > 0) { - move_count = (length >= page_size) ? page_size : length; - n = zip_file_move(m_pFile, writen_num, read_num, move_count, move_buf, - page_size); - if (n < 0) { - moved_length = n; - goto cleanup; - } - - if (n != move_count) { - goto cleanup; - } - - writen_num += move_count; - read_num += move_count; - length -= move_count; - moved_length += move_count; - } - -cleanup: - CLEANUP(move_buf); - return moved_length; -} - -static int zip_central_dir_move(mz_zip_internal_state *pState, int begin, - int end, int entry_num) { - if (begin == entry_num) { - return 0; - } - - size_t l_size = 0; - size_t r_size = 0; - mz_uint32 d_size = 0; - mz_uint8 *next = NULL; - mz_uint8 *deleted = &MZ_ZIP_ARRAY_ELEMENT( - &pState->m_central_dir, mz_uint8, - MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, mz_uint32, begin)); - l_size = (size_t)(deleted - (mz_uint8 *)(pState->m_central_dir.m_p)); - if (end == entry_num) { - r_size = 0; - } else { - next = &MZ_ZIP_ARRAY_ELEMENT( - &pState->m_central_dir, mz_uint8, - MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, mz_uint32, end)); - r_size = pState->m_central_dir.m_size - - (mz_uint32)(next - (mz_uint8 *)(pState->m_central_dir.m_p)); - d_size = (mz_uint32)(next - deleted); - } - - if (l_size == 0) { - memmove(pState->m_central_dir.m_p, next, r_size); - pState->m_central_dir.m_p = MZ_REALLOC(pState->m_central_dir.m_p, r_size); - for (int i = end; i < entry_num; i++) { - MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, mz_uint32, i) -= - d_size; - } - } - - if (l_size * r_size != 0) { - memmove(deleted, next, r_size); - for (int i = end; i < entry_num; i++) { - MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, mz_uint32, i) -= - d_size; - } - } - - pState->m_central_dir.m_size = l_size + r_size; - return 0; -} - -static int zip_central_dir_delete(mz_zip_internal_state *pState, - int *deleted_entry_index_array, - int entry_num) { - int i = 0; - int begin = 0; - int end = 0; - int d_num = 0; - while (i < entry_num) { - while ((!deleted_entry_index_array[i]) && (i < entry_num)) { - i++; - } - begin = i; - - while ((deleted_entry_index_array[i]) && (i < entry_num)) { - i++; - } - end = i; - zip_central_dir_move(pState, begin, end, entry_num); - } - - i = 0; - while (i < entry_num) { - while ((!deleted_entry_index_array[i]) && (i < entry_num)) { - i++; - } - begin = i; - if (begin == entry_num) { - break; - } - while ((deleted_entry_index_array[i]) && (i < entry_num)) { - i++; - } - end = i; - int k = 0; - for (int j = end; j < entry_num; j++) { - MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, mz_uint32, - begin + k) = - (mz_uint32)MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, - mz_uint32, j); - k++; - } - d_num += end - begin; - } - - pState->m_central_dir_offsets.m_size = - sizeof(mz_uint32) * (entry_num - d_num); - return 0; -} - -static ssize_t zip_entries_delete_mark(struct zip_t *zip, - struct zip_entry_mark_t *entry_mark, - int entry_num) { - mz_uint64 writen_num = 0; - mz_uint64 read_num = 0; - size_t deleted_length = 0; - size_t move_length = 0; - int i = 0; - size_t deleted_entry_num = 0; - ssize_t n = 0; - - mz_bool *deleted_entry_flag_array = - (mz_bool *)calloc(entry_num, sizeof(mz_bool)); - if (deleted_entry_flag_array == NULL) { - return ZIP_EOOMEM; - } - - mz_zip_internal_state *pState = zip->archive.m_pState; - zip->archive.m_zip_mode = MZ_ZIP_MODE_WRITING; - - if (MZ_FSEEK64(pState->m_pFile, 0, SEEK_SET)) { - CLEANUP(deleted_entry_flag_array); - return ZIP_ENOENT; - } - - while (i < entry_num) { - while ((entry_mark[i].type == MZ_KEEP) && (i < entry_num)) { - writen_num += entry_mark[i].lf_length; - read_num = writen_num; - i++; - } - - while ((entry_mark[i].type == MZ_DELETE) && (i < entry_num)) { - deleted_entry_flag_array[i] = MZ_TRUE; - read_num += entry_mark[i].lf_length; - deleted_length += entry_mark[i].lf_length; - i++; - deleted_entry_num++; - } - - while ((entry_mark[i].type == MZ_MOVE) && (i < entry_num)) { - move_length += entry_mark[i].lf_length; - mz_uint8 *p = &MZ_ZIP_ARRAY_ELEMENT( - &pState->m_central_dir, mz_uint8, - MZ_ZIP_ARRAY_ELEMENT(&pState->m_central_dir_offsets, mz_uint32, i)); - if (!p) { - CLEANUP(deleted_entry_flag_array); - return ZIP_ENOENT; - } - mz_uint32 offset = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); - offset -= (mz_uint32)deleted_length; - MZ_WRITE_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS, offset); - i++; - } - - n = zip_files_move(pState->m_pFile, writen_num, read_num, move_length); - if (n != (ssize_t)move_length) { - CLEANUP(deleted_entry_flag_array); - return n; - } - writen_num += move_length; - read_num += move_length; - } - - zip->archive.m_archive_size -= (mz_uint64)deleted_length; - zip->archive.m_total_files = - (mz_uint32)entry_num - (mz_uint32)deleted_entry_num; - - zip_central_dir_delete(pState, deleted_entry_flag_array, entry_num); - CLEANUP(deleted_entry_flag_array); - - return (ssize_t)deleted_entry_num; -} - -struct zip_t *zip_open(const char *zipname, int level, char mode) { - struct zip_t *zip = NULL; - - if (!zipname || strlen(zipname) < 1) { - // zip_t archive name is empty or NULL - goto cleanup; - } - - if (level < 0) - level = MZ_DEFAULT_LEVEL; - if ((level & 0xF) > MZ_UBER_COMPRESSION) { - // Wrong compression level - goto cleanup; - } - - zip = (struct zip_t *)calloc((size_t)1, sizeof(struct zip_t)); - if (!zip) - goto cleanup; - - zip->level = (mz_uint)level; - switch (mode) { - case 'w': - // Create a new archive. - if (!mz_zip_writer_init_file(&(zip->archive), zipname, 0)) { - // Cannot initialize zip_archive writer - goto cleanup; - } - break; - - case 'r': - case 'a': - case 'd': - if (!mz_zip_reader_init_file( - &(zip->archive), zipname, - zip->level | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) { - // An archive file does not exist or cannot initialize - // zip_archive reader - goto cleanup; - } - if ((mode == 'a' || mode == 'd') && - !mz_zip_writer_init_from_reader(&(zip->archive), zipname)) { - mz_zip_reader_end(&(zip->archive)); - goto cleanup; - } - break; - - default: - goto cleanup; - } - - return zip; - -cleanup: - CLEANUP(zip); - return NULL; -} - -void zip_close(struct zip_t *zip) { - if (zip) { - // Always finalize, even if adding failed for some reason, so we have a - // valid central directory. - mz_zip_writer_finalize_archive(&(zip->archive)); - zip_archive_truncate(&(zip->archive)); - mz_zip_writer_end(&(zip->archive)); - mz_zip_reader_end(&(zip->archive)); - - CLEANUP(zip); - } -} - -int zip_is64(struct zip_t *zip) { - if (!zip || !zip->archive.m_pState) { - // zip_t handler or zip state is not initialized - return ZIP_ENOINIT; - } - - return (int)zip->archive.m_pState->m_zip64; -} - -int zip_entry_open(struct zip_t *zip, const char *entryname, int case_sensitive) { - size_t entrylen = 0; - mz_zip_archive *pzip = NULL; - mz_uint num_alignment_padding_bytes, level; - mz_zip_archive_file_stat stats; - int err = 0; - - if (!zip) { - return ZIP_ENOINIT; - } - - if (!entryname) { - return ZIP_EINVENTNAME; - } - - entrylen = strlen(entryname); - if (entrylen == 0) { - return ZIP_EINVENTNAME; - } - - /* - .ZIP File Format Specification Version: 6.3.3 - - 4.4.17.1 The name of the file, with optional relative path. - The path stored MUST not contain a drive or - device letter, or a leading slash. All slashes - MUST be forward slashes '/' as opposed to - backwards slashes '\' for compatibility with Amiga - and UNIX file systems etc. If input came from standard - input, there is no file name field. - */ - if (zip->entry.name) { - CLEANUP(zip->entry.name); - } - zip->entry.name = zip_strrpl(entryname, entrylen, '\\', '/'); - if (!zip->entry.name) { - // Cannot parse zip entry name - return ZIP_EINVENTNAME; - } - - pzip = &(zip->archive); - if (pzip->m_zip_mode == MZ_ZIP_MODE_READING) { - zip->entry.index = - mz_zip_reader_locate_file(pzip, zip->entry.name, NULL, case_sensitive ? MZ_ZIP_FLAG_CASE_SENSITIVE : 0); - if (zip->entry.index < 0) { - err = ZIP_ENOENT; - goto cleanup; - } - - if (!mz_zip_reader_file_stat(pzip, (mz_uint)zip->entry.index, &stats)) { - err = ZIP_ENOENT; - goto cleanup; - } - - zip->entry.comp_size = stats.m_comp_size; - zip->entry.uncomp_size = stats.m_uncomp_size; - zip->entry.uncomp_crc32 = stats.m_crc32; - zip->entry.offset = stats.m_central_dir_ofs; - zip->entry.header_offset = stats.m_local_header_ofs; - zip->entry.method = stats.m_method; - zip->entry.external_attr = stats.m_external_attr; -#ifndef MINIZ_NO_TIME - zip->entry.m_time = stats.m_time; -#endif - - return 0; - } - - zip->entry.index = (int)zip->archive.m_total_files; - zip->entry.comp_size = 0; - zip->entry.uncomp_size = 0; - zip->entry.uncomp_crc32 = MZ_CRC32_INIT; - zip->entry.offset = zip->archive.m_archive_size; - zip->entry.header_offset = zip->archive.m_archive_size; - memset(zip->entry.header, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE * sizeof(mz_uint8)); - zip->entry.method = 0; - - // UNIX or APPLE -#if MZ_PLATFORM == 3 || MZ_PLATFORM == 19 - // regular file with rw-r--r-- persmissions - zip->entry.external_attr = (mz_uint32)(0100644) << 16; -#else - zip->entry.external_attr = 0; -#endif - - num_alignment_padding_bytes = - mz_zip_writer_compute_padding_needed_for_file_alignment(pzip); - - if (!pzip->m_pState || (pzip->m_zip_mode != MZ_ZIP_MODE_WRITING)) { - // Invalid zip mode - err = ZIP_EINVMODE; - goto cleanup; - } - if (zip->level & MZ_ZIP_FLAG_COMPRESSED_DATA) { - // Invalid zip compression level - err = ZIP_EINVLVL; - goto cleanup; - } - // no zip64 support yet - if ((pzip->m_total_files == 0xFFFF) || - ((pzip->m_archive_size + num_alignment_padding_bytes + - MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + - entrylen) > 0xFFFFFFFF)) { - // No zip64 support yet - err = ZIP_ENOSUP64; - goto cleanup; - } - if (!mz_zip_writer_write_zeros(pzip, zip->entry.offset, - num_alignment_padding_bytes + - sizeof(zip->entry.header))) { - // Cannot memset zip entry header - err = ZIP_EMEMSET; - goto cleanup; - } - - zip->entry.header_offset += num_alignment_padding_bytes; - if (pzip->m_file_offset_alignment) { - MZ_ASSERT( - (zip->entry.header_offset & (pzip->m_file_offset_alignment - 1)) == 0); - } - zip->entry.offset += num_alignment_padding_bytes + sizeof(zip->entry.header); - - if (pzip->m_pWrite(pzip->m_pIO_opaque, zip->entry.offset, zip->entry.name, - entrylen) != entrylen) { - // Cannot write data to zip entry - err = ZIP_EWRTENT; - goto cleanup; - } - - zip->entry.offset += entrylen; - level = zip->level & 0xF; - if (level) { - zip->entry.state.m_pZip = pzip; - zip->entry.state.m_cur_archive_file_ofs = zip->entry.offset; - zip->entry.state.m_comp_size = 0; - - if (tdefl_init(&(zip->entry.comp), mz_zip_writer_add_put_buf_callback, - &(zip->entry.state), - (int)tdefl_create_comp_flags_from_zip_params( - (int)level, -15, MZ_DEFAULT_STRATEGY)) != - TDEFL_STATUS_OKAY) { - // Cannot initialize the zip compressor - err = ZIP_ETDEFLINIT; - goto cleanup; - } - } - - zip->entry.m_time = time(NULL); - - return 0; - -cleanup: - CLEANUP(zip->entry.name); - return err; -} - -int zip_entry_openbyindex(struct zip_t *zip, int index) { - mz_zip_archive *pZip = NULL; - mz_zip_archive_file_stat stats; - mz_uint namelen; - const mz_uint8 *pHeader; - const char *pFilename; - - if (!zip) { - // zip_t handler is not initialized - return ZIP_ENOINIT; - } - - pZip = &(zip->archive); - if (pZip->m_zip_mode != MZ_ZIP_MODE_READING) { - // open by index requires readonly mode - return ZIP_EINVMODE; - } - - if (index < 0 || (mz_uint)index >= pZip->m_total_files) { - // index out of range - return ZIP_EINVIDX; - } - - if (!(pHeader = &MZ_ZIP_ARRAY_ELEMENT( - &pZip->m_pState->m_central_dir, mz_uint8, - MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, - mz_uint32, index)))) { - // cannot find header in central directory - return ZIP_ENOHDR; - } - - namelen = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); - pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; - - /* - .ZIP File Format Specification Version: 6.3.3 - - 4.4.17.1 The name of the file, with optional relative path. - The path stored MUST not contain a drive or - device letter, or a leading slash. All slashes - MUST be forward slashes '/' as opposed to - backwards slashes '\' for compatibility with Amiga - and UNIX file systems etc. If input came from standard - input, there is no file name field. - */ - if (zip->entry.name) { - CLEANUP(zip->entry.name); - } - zip->entry.name = zip_strrpl(pFilename, namelen, '\\', '/'); - if (!zip->entry.name) { - // local entry name is NULL - return ZIP_EINVENTNAME; - } - - if (!mz_zip_reader_file_stat(pZip, (mz_uint)index, &stats)) { - return ZIP_ENOENT; - } - - zip->entry.index = index; - zip->entry.comp_size = stats.m_comp_size; - zip->entry.uncomp_size = stats.m_uncomp_size; - zip->entry.uncomp_crc32 = stats.m_crc32; - zip->entry.offset = stats.m_central_dir_ofs; - zip->entry.header_offset = stats.m_local_header_ofs; - zip->entry.method = stats.m_method; - zip->entry.external_attr = stats.m_external_attr; -#ifndef MINIZ_NO_TIME - zip->entry.m_time = stats.m_time; -#endif - - return 0; -} - -int zip_entry_close(struct zip_t *zip) { - mz_zip_archive *pzip = NULL; - mz_uint level; - tdefl_status done; - mz_uint16 entrylen; - mz_uint16 dos_time = 0, dos_date = 0; - int err = 0; - - if (!zip) { - // zip_t handler is not initialized - err = ZIP_ENOINIT; - goto cleanup; - } - - pzip = &(zip->archive); - if (pzip->m_zip_mode == MZ_ZIP_MODE_READING) { - goto cleanup; - } - - level = zip->level & 0xF; - if (level) { - done = tdefl_compress_buffer(&(zip->entry.comp), "", 0, TDEFL_FINISH); - if (done != TDEFL_STATUS_DONE && done != TDEFL_STATUS_OKAY) { - // Cannot flush compressed buffer - err = ZIP_ETDEFLBUF; - goto cleanup; - } - zip->entry.comp_size = zip->entry.state.m_comp_size; - zip->entry.offset = zip->entry.state.m_cur_archive_file_ofs; - zip->entry.method = MZ_DEFLATED; - } - - entrylen = (mz_uint16)strlen(zip->entry.name); - if ((zip->entry.comp_size > 0xFFFFFFFF) || (zip->entry.offset > 0xFFFFFFFF)) { - // No zip64 support, yet - err = ZIP_ENOSUP64; - goto cleanup; - } - -#ifndef MINIZ_NO_TIME - mz_zip_time_t_to_dos_time(zip->entry.m_time, &dos_time, &dos_date); -#endif - - if (!mz_zip_writer_create_local_dir_header( - pzip, zip->entry.header, entrylen, 0, zip->entry.uncomp_size, - zip->entry.comp_size, zip->entry.uncomp_crc32, zip->entry.method, 0, - dos_time, dos_date)) { - // Cannot create zip entry header - err = ZIP_ECRTHDR; - goto cleanup; - } - - if (pzip->m_pWrite(pzip->m_pIO_opaque, zip->entry.header_offset, - zip->entry.header, - sizeof(zip->entry.header)) != sizeof(zip->entry.header)) { - // Cannot write zip entry header - err = ZIP_EWRTHDR; - goto cleanup; - } - - if (!mz_zip_writer_add_to_central_dir( - pzip, zip->entry.name, entrylen, NULL, 0, "", 0, - zip->entry.uncomp_size, zip->entry.comp_size, zip->entry.uncomp_crc32, - zip->entry.method, 0, dos_time, dos_date, zip->entry.header_offset, - zip->entry.external_attr, NULL, 0)) { - // Cannot write to zip central dir - err = ZIP_EWRTDIR; - goto cleanup; - } - - pzip->m_total_files++; - pzip->m_archive_size = zip->entry.offset; - -cleanup: - if (zip) { - zip->entry.m_time = 0; - CLEANUP(zip->entry.name); - } - return err; -} - -const char *zip_entry_name(struct zip_t *zip) { - if (!zip) { - // zip_t handler is not initialized - return NULL; - } - - return zip->entry.name; -} - -int zip_entry_index(struct zip_t *zip) { - if (!zip) { - // zip_t handler is not initialized - return ZIP_ENOINIT; - } - - return zip->entry.index; -} - -int zip_entry_isdir(struct zip_t *zip) { - if (!zip) { - // zip_t handler is not initialized - return ZIP_ENOINIT; - } - - if (zip->entry.index < 0) { - // zip entry is not opened - return ZIP_EINVIDX; - } - - return (int)mz_zip_reader_is_file_a_directory(&zip->archive, - (mz_uint)zip->entry.index); -} - -unsigned long long zip_entry_size(struct zip_t *zip) { - return zip ? zip->entry.uncomp_size : 0; -} - -unsigned long long zip_entry_comp_size(struct zip_t *zip) { - return zip ? zip->entry.comp_size : 0; -} - -unsigned int zip_entry_crc32(struct zip_t *zip) { - return zip ? zip->entry.uncomp_crc32 : 0; -} - -int zip_entry_write(struct zip_t *zip, const void *buf, size_t bufsize) { - mz_uint level; - mz_zip_archive *pzip = NULL; - tdefl_status status; - - if (!zip) { - // zip_t handler is not initialized - return ZIP_ENOINIT; - } - - pzip = &(zip->archive); - if (buf && bufsize > 0) { - zip->entry.uncomp_size += bufsize; - zip->entry.uncomp_crc32 = (mz_uint32)mz_crc32( - zip->entry.uncomp_crc32, (const mz_uint8 *)buf, bufsize); - - level = zip->level & 0xF; - if (!level) { - if ((pzip->m_pWrite(pzip->m_pIO_opaque, zip->entry.offset, buf, - bufsize) != bufsize)) { - // Cannot write buffer - return ZIP_EWRTENT; - } - zip->entry.offset += bufsize; - zip->entry.comp_size += bufsize; - } else { - status = tdefl_compress_buffer(&(zip->entry.comp), buf, bufsize, - TDEFL_NO_FLUSH); - if (status != TDEFL_STATUS_DONE && status != TDEFL_STATUS_OKAY) { - // Cannot compress buffer - return ZIP_ETDEFLBUF; - } - } - } - - return 0; -} - -int zip_entry_fwrite(struct zip_t *zip, const char *filename) { - int err = 0; - size_t n = 0; - MZ_FILE *stream = NULL; - mz_uint8 buf[MZ_ZIP_MAX_IO_BUF_SIZE]; - struct MZ_FILE_STAT_STRUCT file_stat; - - if (!zip) { - // zip_t handler is not initialized - return ZIP_ENOINIT; - } - - memset(buf, 0, MZ_ZIP_MAX_IO_BUF_SIZE); - memset((void *)&file_stat, 0, sizeof(struct MZ_FILE_STAT_STRUCT)); - if (MZ_FILE_STAT(filename, &file_stat) != 0) { - // problem getting information - check errno - return ZIP_ENOENT; - } - - if ((file_stat.st_mode & 0200) == 0) { - // MS-DOS read-only attribute - zip->entry.external_attr |= 0x01; - } - zip->entry.external_attr |= (mz_uint32)((file_stat.st_mode & 0xFFFF) << 16); - zip->entry.m_time = file_stat.st_mtime; - - if (!(stream = MZ_FOPEN(filename, "rb"))) { - // Cannot open filename - return ZIP_EOPNFILE; - } - - while ((n = fread(buf, sizeof(mz_uint8), MZ_ZIP_MAX_IO_BUF_SIZE, stream)) > - 0) { - if (zip_entry_write(zip, buf, n) < 0) { - err = ZIP_EWRTENT; - break; - } - } - fclose(stream); - - return err; -} - -ssize_t zip_entry_read(struct zip_t *zip, void **buf, size_t *bufsize) { - mz_zip_archive *pzip = NULL; - mz_uint idx; - size_t size = 0; - - if (!zip) { - // zip_t handler is not initialized - return (ssize_t)ZIP_ENOINIT; - } - - pzip = &(zip->archive); - if (pzip->m_zip_mode != MZ_ZIP_MODE_READING || zip->entry.index < 0) { - // the entry is not found or we do not have read access - return (ssize_t)ZIP_ENOENT; - } - - idx = (mz_uint)zip->entry.index; - if (mz_zip_reader_is_file_a_directory(pzip, idx)) { - // the entry is a directory - return (ssize_t)ZIP_EINVENTTYPE; - } - - *buf = mz_zip_reader_extract_to_heap(pzip, idx, &size, 0); - if (*buf && bufsize) { - *bufsize = size; - } - return (ssize_t)size; -} - -ssize_t zip_entry_noallocread(struct zip_t *zip, void *buf, size_t bufsize) { - mz_zip_archive *pzip = NULL; - - if (!zip) { - // zip_t handler is not initialized - return (ssize_t)ZIP_ENOINIT; - } - - pzip = &(zip->archive); - if (pzip->m_zip_mode != MZ_ZIP_MODE_READING || zip->entry.index < 0) { - // the entry is not found or we do not have read access - return (ssize_t)ZIP_ENOENT; - } - - if (!mz_zip_reader_extract_to_mem_no_alloc(pzip, (mz_uint)zip->entry.index, - buf, bufsize, 0, NULL, 0)) { - return (ssize_t)ZIP_EMEMNOALLOC; - } - - return (ssize_t)zip->entry.uncomp_size; -} - -int zip_entry_fread(struct zip_t *zip, const char *filename) { - mz_zip_archive *pzip = NULL; - mz_uint idx; - mz_uint32 xattr = 0; - mz_zip_archive_file_stat info; - - if (!zip) { - // zip_t handler is not initialized - return ZIP_ENOINIT; - } - - memset((void *)&info, 0, sizeof(mz_zip_archive_file_stat)); - pzip = &(zip->archive); - if (pzip->m_zip_mode != MZ_ZIP_MODE_READING || zip->entry.index < 0) { - // the entry is not found or we do not have read access - return ZIP_ENOENT; - } - - idx = (mz_uint)zip->entry.index; - if (mz_zip_reader_is_file_a_directory(pzip, idx)) { - // the entry is a directory - return ZIP_EINVENTTYPE; - } - - if (!mz_zip_reader_extract_to_file(pzip, idx, filename, 0)) { - return ZIP_ENOFILE; - } - -#if defined(_MSC_VER) - (void)xattr; // unused -#else - if (!mz_zip_reader_file_stat(pzip, idx, &info)) { - // Cannot get information about zip archive; - return ZIP_ENOFILE; - } - - xattr = (info.m_external_attr >> 16) & 0xFFFF; - if (xattr > 0) { - if (chmod(filename, (mode_t)xattr) < 0) { - return ZIP_ENOPERM; - } - } -#endif - - return 0; -} - -int zip_entry_extract(struct zip_t *zip, - size_t (*on_extract)(void *arg, uint64_t offset, - const void *buf, size_t bufsize), - void *arg) { - mz_zip_archive *pzip = NULL; - mz_uint idx; - - if (!zip) { - // zip_t handler is not initialized - return ZIP_ENOINIT; - } - - pzip = &(zip->archive); - if (pzip->m_zip_mode != MZ_ZIP_MODE_READING || zip->entry.index < 0) { - // the entry is not found or we do not have read access - return ZIP_ENOENT; - } - - idx = (mz_uint)zip->entry.index; - return (mz_zip_reader_extract_to_callback(pzip, idx, on_extract, arg, 0)) - ? 0 - : ZIP_EINVIDX; -} - -ssize_t zip_entries_total(struct zip_t *zip) { - if (!zip) { - // zip_t handler is not initialized - return ZIP_ENOINIT; - } - - return (ssize_t)zip->archive.m_total_files; -} - -ssize_t zip_entries_delete(struct zip_t *zip, char *const entries[], - size_t len) { - ssize_t n = 0; - ssize_t err = 0; - struct zip_entry_mark_t *entry_mark = NULL; - - if (zip == NULL || (entries == NULL && len != 0)) { - return ZIP_ENOINIT; - } - - if (entries == NULL && len == 0) { - return 0; - } - - n = zip_entries_total(zip); - - entry_mark = (struct zip_entry_mark_t *)calloc( - (size_t)n, sizeof(struct zip_entry_mark_t)); - if (!entry_mark) { - return ZIP_EOOMEM; - } - - zip->archive.m_zip_mode = MZ_ZIP_MODE_READING; - - err = zip_entry_set(zip, entry_mark, (int)n, entries, len); - if (err < 0) { - CLEANUP(entry_mark); - return err; - } - - err = zip_entries_delete_mark(zip, entry_mark, (int)n); - CLEANUP(entry_mark); - return err; -} - -int zip_stream_extract(const char *stream, size_t size, const char *dir, - int (*on_extract)(const char *filename, void *arg), - void *arg) { - mz_zip_archive zip_archive; - if (!stream || !dir) { - // Cannot parse zip archive stream - return ZIP_ENOINIT; - } - if (!memset(&zip_archive, 0, sizeof(mz_zip_archive))) { - // Cannot memset zip archive - return ZIP_EMEMSET; - } - if (!mz_zip_reader_init_mem(&zip_archive, stream, size, 0)) { - // Cannot initialize zip_archive reader - return ZIP_ENOINIT; - } - - return zip_archive_extract(&zip_archive, dir, on_extract, arg); -} - -struct zip_t *zip_stream_open(const char *stream, size_t size, int level, - char mode) { - struct zip_t *zip = (struct zip_t *)calloc((size_t)1, sizeof(struct zip_t)); - if (!zip) { - return NULL; - } - - if (level < 0) { - level = MZ_DEFAULT_LEVEL; - } - if ((level & 0xF) > MZ_UBER_COMPRESSION) { - // Wrong compression level - goto cleanup; - } - zip->level = (mz_uint)level; - - if ((stream != NULL) && (size > 0) && (mode == 'r')) { - if (!mz_zip_reader_init_mem(&(zip->archive), stream, size, 0)) { - goto cleanup; - } - } else if ((stream == NULL) && (size == 0) && (mode == 'w')) { - // Create a new archive. - if (!mz_zip_writer_init_heap(&(zip->archive), 0, 1024)) { - // Cannot initialize zip_archive writer - goto cleanup; - } - } else { - goto cleanup; - } - return zip; - -cleanup: - CLEANUP(zip); - return NULL; -} - -ssize_t zip_stream_copy(struct zip_t *zip, void **buf, size_t *bufsize) { - size_t n; - - if (!zip) { - return (ssize_t)ZIP_ENOINIT; - } - zip_archive_finalize(&(zip->archive)); - - n = (size_t)zip->archive.m_archive_size; - if (bufsize != NULL) { - *bufsize = n; - } - - *buf = calloc(sizeof(unsigned char), n); - memcpy(*buf, zip->archive.m_pState->m_pMem, n); - - return (ssize_t)n; -} - -void zip_stream_close(struct zip_t *zip) { - if (zip) { - mz_zip_writer_end(&(zip->archive)); - mz_zip_reader_end(&(zip->archive)); - CLEANUP(zip); - } -} - -int zip_create(const char *zipname, const char *filenames[], size_t len) { - int err = 0; - size_t i; - mz_zip_archive zip_archive; - struct MZ_FILE_STAT_STRUCT file_stat; - mz_uint32 ext_attributes = 0; - - if (!zipname || strlen(zipname) < 1) { - // zip_t archive name is empty or NULL - return ZIP_EINVZIPNAME; - } - - // Create a new archive. - if (!memset(&(zip_archive), 0, sizeof(zip_archive))) { - // Cannot memset zip archive - return ZIP_EMEMSET; - } - - if (!mz_zip_writer_init_file(&zip_archive, zipname, 0)) { - // Cannot initialize zip_archive writer - return ZIP_ENOINIT; - } - - if (!memset((void *)&file_stat, 0, sizeof(struct MZ_FILE_STAT_STRUCT))) { - return ZIP_EMEMSET; - } - - for (i = 0; i < len; ++i) { - const char *name = filenames[i]; - if (!name) { - err = ZIP_EINVENTNAME; - break; - } - - if (MZ_FILE_STAT(name, &file_stat) != 0) { - // problem getting information - check errno - err = ZIP_ENOFILE; - break; - } - - if ((file_stat.st_mode & 0200) == 0) { - // MS-DOS read-only attribute - ext_attributes |= 0x01; - } - ext_attributes |= (mz_uint32)((file_stat.st_mode & 0xFFFF) << 16); - - if (!mz_zip_writer_add_file(&zip_archive, zip_basename(name), name, "", 0, - ZIP_DEFAULT_COMPRESSION_LEVEL, - ext_attributes)) { - // Cannot add file to zip_archive - err = ZIP_ENOFILE; - break; - } - } - - mz_zip_writer_finalize_archive(&zip_archive); - mz_zip_writer_end(&zip_archive); - return err; -} - -int zip_extract(const char *zipname, const char *dir, - int (*on_extract)(const char *filename, void *arg), void *arg) { - mz_zip_archive zip_archive; - - if (!zipname || !dir) { - // Cannot parse zip archive name - return ZIP_EINVZIPNAME; - } - - if (!memset(&zip_archive, 0, sizeof(mz_zip_archive))) { - // Cannot memset zip archive - return ZIP_EMEMSET; - } - - // Now try to open the archive. - if (!mz_zip_reader_init_file(&zip_archive, zipname, 0)) { - // Cannot initialize zip_archive reader - return ZIP_ENOINIT; - } - - return zip_archive_extract(&zip_archive, dir, on_extract, arg); -} diff --git a/OgreMain/src/zip/zip.h b/OgreMain/src/zip/zip.h deleted file mode 100644 index dbcbc0441dd..00000000000 --- a/OgreMain/src/zip/zip.h +++ /dev/null @@ -1,443 +0,0 @@ -/* - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ - -#pragma once -#ifndef ZIP_H -#define ZIP_H - -#include -#include -#include - -#ifndef ZIP_SHARED -#define ZIP_EXPORT -#else -#ifdef _WIN32 -#ifdef ZIP_BUILD_SHARED -#define ZIP_EXPORT __declspec(dllexport) -#else -#define ZIP_EXPORT __declspec(dllimport) -#endif -#else -#define ZIP_EXPORT __attribute__((visibility("default"))) -#endif -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#if !defined(_POSIX_C_SOURCE) && defined(_MSC_VER) -// 64-bit Windows is the only mainstream platform -// where sizeof(long) != sizeof(void*) -#ifdef _WIN64 -typedef long long ssize_t; /* byte count or error */ -#else -typedef long ssize_t; /* byte count or error */ -#endif -#endif - -#ifndef MAX_PATH -#define MAX_PATH 32767 /* # chars in a path name including NULL */ -#endif - -/** - * @mainpage - * - * Documenation for @ref zip. - */ - -/** - * @addtogroup zip - * @{ - */ - -/** - * Default zip compression level. - */ -#define ZIP_DEFAULT_COMPRESSION_LEVEL 6 - -/** - * Error codes - */ -#define ZIP_ENOINIT -1 // not initialized -#define ZIP_EINVENTNAME -2 // invalid entry name -#define ZIP_ENOENT -3 // entry not found -#define ZIP_EINVMODE -4 // invalid zip mode -#define ZIP_EINVLVL -5 // invalid compression level -#define ZIP_ENOSUP64 -6 // no zip 64 support -#define ZIP_EMEMSET -7 // memset error -#define ZIP_EWRTENT -8 // cannot write data to entry -#define ZIP_ETDEFLINIT -9 // cannot initialize tdefl compressor -#define ZIP_EINVIDX -10 // invalid index -#define ZIP_ENOHDR -11 // header not found -#define ZIP_ETDEFLBUF -12 // cannot flush tdefl buffer -#define ZIP_ECRTHDR -13 // cannot create entry header -#define ZIP_EWRTHDR -14 // cannot write entry header -#define ZIP_EWRTDIR -15 // cannot write to central dir -#define ZIP_EOPNFILE -16 // cannot open file -#define ZIP_EINVENTTYPE -17 // invalid entry type -#define ZIP_EMEMNOALLOC -18 // extracting data using no memory allocation -#define ZIP_ENOFILE -19 // file not found -#define ZIP_ENOPERM -20 // no permission -#define ZIP_EOOMEM -21 // out of memory -#define ZIP_EINVZIPNAME -22 // invalid zip archive name -#define ZIP_EMKDIR -23 // make dir error -#define ZIP_ESYMLINK -24 // symlink error -#define ZIP_ECLSZIP -25 // close archive error -#define ZIP_ECAPSIZE -26 // capacity size too small -#define ZIP_EFSEEK -27 // fseek error -#define ZIP_EFREAD -28 // fread error -#define ZIP_EFWRITE -29 // fwrite error - -/** - * Looks up the error message string coresponding to an error number. - * @param errnum error number - * @return error message string coresponding to errnum or NULL if error is not - * found. - */ -extern ZIP_EXPORT const char *zip_strerror(int errnum); - -/** - * @struct zip_t - * - * This data structure is used throughout the library to represent zip archive - - * forward declaration. - */ -struct zip_t; - -/** - * Opens zip archive with compression level using the given mode. - * - * @param zipname zip archive file name. - * @param level compression level (0-9 are the standard zlib-style levels). - * @param mode file access mode. - * - 'r': opens a file for reading/extracting (the file must exists). - * - 'w': creates an empty file for writing. - * - 'a': appends to an existing archive. - * - * @return the zip archive handler or NULL on error - */ -extern ZIP_EXPORT struct zip_t *zip_open(const char *zipname, int level, - char mode); - -/** - * Closes the zip archive, releases resources - always finalize. - * - * @param zip zip archive handler. - */ -extern ZIP_EXPORT void zip_close(struct zip_t *zip); - -/** - * Determines if the archive has a zip64 end of central directory headers. - * - * @param zip zip archive handler. - * - * @return the return code - 1 (true), 0 (false), negative number (< 0) on - * error. - */ -extern ZIP_EXPORT int zip_is64(struct zip_t *zip); - -/** - * Opens an entry by name in the zip archive. - * - * For zip archive opened in 'w' or 'a' mode the function will append - * a new entry. In readonly mode the function tries to locate the entry - * in global dictionary. - * - * @param zip zip archive handler. - * @param entryname an entry name in local dictionary. - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -extern ZIP_EXPORT int zip_entry_open(struct zip_t *zip, const char *entryname, int case_sensitive); - -/** - * Opens a new entry by index in the zip archive. - * - * This function is only valid if zip archive was opened in 'r' (readonly) mode. - * - * @param zip zip archive handler. - * @param index index in local dictionary. - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -extern ZIP_EXPORT int zip_entry_openbyindex(struct zip_t *zip, int index); - -/** - * Closes a zip entry, flushes buffer and releases resources. - * - * @param zip zip archive handler. - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -extern ZIP_EXPORT int zip_entry_close(struct zip_t *zip); - -/** - * Returns a local name of the current zip entry. - * - * The main difference between user's entry name and local entry name - * is optional relative path. - * Following .ZIP File Format Specification - the path stored MUST not contain - * a drive or device letter, or a leading slash. - * All slashes MUST be forward slashes '/' as opposed to backwards slashes '\' - * for compatibility with Amiga and UNIX file systems etc. - * - * @param zip: zip archive handler. - * - * @return the pointer to the current zip entry name, or NULL on error. - */ -extern ZIP_EXPORT const char *zip_entry_name(struct zip_t *zip); - -/** - * Returns an index of the current zip entry. - * - * @param zip zip archive handler. - * - * @return the index on success, negative number (< 0) on error. - */ -extern ZIP_EXPORT int zip_entry_index(struct zip_t *zip); - -/** - * Determines if the current zip entry is a directory entry. - * - * @param zip zip archive handler. - * - * @return the return code - 1 (true), 0 (false), negative number (< 0) on - * error. - */ -extern ZIP_EXPORT int zip_entry_isdir(struct zip_t *zip); - -/** - * Returns the uncompressed size of the current zip entry. - * - * @param zip zip archive handler. - * - * @return the uncompressed size in bytes. - */ -extern ZIP_EXPORT unsigned long long zip_entry_size(struct zip_t *zip); - -/** - * Returns the compressed size of the current zip entry. - * - * @param zip zip archive handler. - * - * @return the compressed size in bytes. - */ -extern unsigned long long zip_entry_comp_size(struct zip_t *zip); - -/** - * Returns CRC-32 checksum of the current zip entry. - * - * @param zip zip archive handler. - * - * @return the CRC-32 checksum. - */ -extern ZIP_EXPORT unsigned int zip_entry_crc32(struct zip_t *zip); - -/** - * Compresses an input buffer for the current zip entry. - * - * @param zip zip archive handler. - * @param buf input buffer. - * @param bufsize input buffer size (in bytes). - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -extern ZIP_EXPORT int zip_entry_write(struct zip_t *zip, const void *buf, - size_t bufsize); - -/** - * Compresses a file for the current zip entry. - * - * @param zip zip archive handler. - * @param filename input file. - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -extern ZIP_EXPORT int zip_entry_fwrite(struct zip_t *zip, const char *filename); - -/** - * Extracts the current zip entry into output buffer. - * - * The function allocates sufficient memory for a output buffer. - * - * @param zip zip archive handler. - * @param buf output buffer. - * @param bufsize output buffer size (in bytes). - * - * @note remember to release memory allocated for a output buffer. - * for large entries, please take a look at zip_entry_extract function. - * - * @return the return code - the number of bytes actually read on success. - * Otherwise a negative number (< 0) on error. - */ -extern ZIP_EXPORT ssize_t zip_entry_read(struct zip_t *zip, void **buf, - size_t *bufsize); - -/** - * Extracts the current zip entry into a memory buffer using no memory - * allocation. - * - * @param zip zip archive handler. - * @param buf preallocated output buffer. - * @param bufsize output buffer size (in bytes). - * - * @note ensure supplied output buffer is large enough. - * zip_entry_size function (returns uncompressed size for the current - * entry) can be handy to estimate how big buffer is needed. - * For large entries, please take a look at zip_entry_extract function. - * - * @return the return code - the number of bytes actually read on success. - * Otherwise a negative number (< 0) on error (e.g. bufsize is not large - * enough). - */ -extern ZIP_EXPORT ssize_t zip_entry_noallocread(struct zip_t *zip, void *buf, - size_t bufsize); - -/** - * Extracts the current zip entry into output file. - * - * @param zip zip archive handler. - * @param filename output file. - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -extern ZIP_EXPORT int zip_entry_fread(struct zip_t *zip, const char *filename); - -/** - * Extracts the current zip entry using a callback function (on_extract). - * - * @param zip zip archive handler. - * @param on_extract callback function. - * @param arg opaque pointer (optional argument, which you can pass to the - * on_extract callback) - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -extern ZIP_EXPORT int -zip_entry_extract(struct zip_t *zip, - size_t (*on_extract)(void *arg, uint64_t offset, - const void *data, size_t size), - void *arg); - -/** - * Returns the number of all entries (files and directories) in the zip archive. - * - * @param zip zip archive handler. - * - * @return the return code - the number of entries on success, negative number - * (< 0) on error. - */ -extern ZIP_EXPORT ssize_t zip_entries_total(struct zip_t *zip); - -/** - * Deletes zip archive entries. - * - * @param zip zip archive handler. - * @param entries array of zip archive entries to be deleted. - * @param len the number of entries to be deleted. - * @return the number of deleted entries, or negative number (< 0) on error. - */ -extern ZIP_EXPORT ssize_t zip_entries_delete(struct zip_t *zip, - char *const entries[], size_t len); - -/** - * Extracts a zip archive stream into directory. - * - * If on_extract is not NULL, the callback will be called after - * successfully extracted each zip entry. - * Returning a negative value from the callback will cause abort and return an - * error. The last argument (void *arg) is optional, which you can use to pass - * data to the on_extract callback. - * - * @param stream zip archive stream. - * @param size stream size. - * @param dir output directory. - * @param on_extract on extract callback. - * @param arg opaque pointer. - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -extern ZIP_EXPORT int -zip_stream_extract(const char *stream, size_t size, const char *dir, - int (*on_extract)(const char *filename, void *arg), - void *arg); - -/** - * Opens zip archive stream into memory. - * - * @param stream zip archive stream. - * @param size stream size. - * - * @return the zip archive handler or NULL on error - */ -extern ZIP_EXPORT struct zip_t *zip_stream_open(const char *stream, size_t size, - int level, char mode); - -/** - * Copy zip archive stream output buffer. - * - * @param zip zip archive handler. - * @param buf output buffer. User should free buf. - * @param bufsize output buffer size (in bytes). - * - * @return copy size - */ -extern ZIP_EXPORT ssize_t zip_stream_copy(struct zip_t *zip, void **buf, - size_t *bufsize); - -/** - * Close zip archive releases resources. - * - * @param zip zip archive handler. - * - * @return - */ -extern ZIP_EXPORT void zip_stream_close(struct zip_t *zip); - -/** - * Creates a new archive and puts files into a single zip archive. - * - * @param zipname zip archive file. - * @param filenames input files. - * @param len: number of input files. - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -extern ZIP_EXPORT int zip_create(const char *zipname, const char *filenames[], - size_t len); - -/** - * Extracts a zip archive file into directory. - * - * If on_extract_entry is not NULL, the callback will be called after - * successfully extracted each zip entry. - * Returning a negative value from the callback will cause abort and return an - * error. The last argument (void *arg) is optional, which you can use to pass - * data to the on_extract_entry callback. - * - * @param zipname zip archive file. - * @param dir output directory. - * @param on_extract_entry on extract callback. - * @param arg opaque pointer. - * - * @return the return code - 0 on success, negative number (< 0) on error. - */ -extern ZIP_EXPORT int zip_extract(const char *zipname, const char *dir, - int (*on_extract_entry)(const char *filename, - void *arg), - void *arg); -/** @} */ -#ifdef __cplusplus -} -#endif - -#endif diff --git a/Other/VC7_AppWizard.msi b/Other/VC7_AppWizard.msi deleted file mode 100644 index afe279b5a48..00000000000 Binary files a/Other/VC7_AppWizard.msi and /dev/null differ diff --git a/Other/add_crlf.py b/Other/add_crlf.py deleted file mode 100644 index 26641a4c4b5..00000000000 --- a/Other/add_crlf.py +++ /dev/null @@ -1,44 +0,0 @@ -import sys -import os -import getopt -import string - -def fnParse( arg, dirname, files ): - for file in files: - for ext in arg: - if file.rfind( ext, len(file)-len(ext), len(file) ) != -1 and not os.path.isdir( dirname + "/" + file ): - fo = open( dirname + "/" + file, "rb" ) - lines = fo.read() - if not '\0' in lines and lines[len(lines)-1] != '\n': - newlines = lines + '\n' - fo.close() - fo = open( dirname + "/" + file, "wb" ) - fo.write(newlines) - print "File " + dirname + "/" + file + " was changed." - fo.close() - -def fnHelp(): - helpstr = """ -This nifty little program adds a CR/LF at the end of every -file with the given extension within the directory tree -from where it was called (i.e. recurses in sub-directories). - -Syntax: - add_crlf [ext1] [ext2] [...] - -Extensions are given in the form: - .cpp .h .txt (no asterisk at the beginning) - -Copyright (c) 2002 by Adrian Cearnau (cearny@cearny.ro) -Any use, commercial or not, is allowed -""" - print helpstr - -if len(sys.argv) < 2: - fnHelp() -else: - exts = sys.argv[1].split() - currdir = os.getcwd() - os.path.walk( currdir, fnParse, exts ) - #print "\nTotally", num_files, "files were patched\n" - print "done" \ No newline at end of file diff --git a/Other/ogre_header.png b/Other/ogre_header.png deleted file mode 100644 index ea86af803fb..00000000000 Binary files a/Other/ogre_header.png and /dev/null differ diff --git a/Other/ogre_header.svg b/Other/ogre_header.svg deleted file mode 100644 index 4aeb019cf8c..00000000000 --- a/Other/ogre_header.svg +++ /dev/null @@ -1,122 +0,0 @@ - - - - - - - - - - image/svg+xml - - - - - - Pierre Fontaine - - - https://forums.ogre3d.org/viewtopic.php?f=4&t=84127&start=75#p524164 - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Other/ogre_logo.svg b/Other/ogre_logo.svg deleted file mode 100755 index 67569898ebb..00000000000 --- a/Other/ogre_logo.svg +++ /dev/null @@ -1,552 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1.8 - - - - diff --git a/Other/rem_endspc.py b/Other/rem_endspc.py deleted file mode 100644 index 6c0aa9b66c2..00000000000 --- a/Other/rem_endspc.py +++ /dev/null @@ -1,60 +0,0 @@ -#! /usr/bin/env python - -import sys -import os -import getopt -import string -import re - -def fnParse( arg, dirname, files ): - for file in files: - for ext in arg: - if file.rfind( ext, len(file)-len(ext), len(file) ) != -1 and not os.path.isdir( dirname + "/" + file ): - print "Parsing file " + dirname + "/" + file + "..." - fo = open( dirname + "/" + file, "r" ) - lines = fo.readlines() - fo.close() - fo = open( dirname + "/" + file, "r" ) - newlines = fo.readlines() - changed = 0 - for i in range(0, len(newlines) - 1): - newlines[i] = re.sub( "[ \t]+$", "", newlines[i] ) - changed = 1 - if changed == 1: - backup = open( dirname + "/" + file + "~", "w" ) - backup.writelines( lines ) - backup.close() - - fo.close() - fo = open( dirname + "/" + file, "w" ) - fo.writelines( newlines ) - - print "File " + dirname + "/" + file + " was changed." - fo.close() - -def fnHelp(): - helpstr = """ -This program deletes all the 'dangling' spaces at the end -of all the lines in all the files with the passed extensions -within the directory tree from whose root it was called -(i.e. recurses into sub-directories) - -Syntax: - rem_endspc [ext1] [ext2] [...] - -Extensions are given in the form: - .cpp .h .txt (no asterisk at the beginning) - -Copyright (c) 2002 by Adrian Cearnau (cearny@cearny.ro) -Any use, commercial or not, is allowed -""" - print helpstr - -if len(sys.argv) < 2: - fnHelp() -else: - exts = sys.argv[1].split() - currdir = os.getcwd() - os.path.walk( currdir, fnParse, exts ) - #print "\nTotally", num_files, "files were patched\n" - print "done" \ No newline at end of file diff --git a/Other/screenshots/bullet.webp b/Other/screenshots/bullet.webp deleted file mode 100644 index cbd1ec37030..00000000000 Binary files a/Other/screenshots/bullet.webp and /dev/null differ diff --git a/Other/screenshots/bumpmap.webp b/Other/screenshots/bumpmap.webp deleted file mode 100644 index c8cd9e84409..00000000000 Binary files a/Other/screenshots/bumpmap.webp and /dev/null differ diff --git a/Other/screenshots/compositor.jpg b/Other/screenshots/compositor.jpg deleted file mode 100644 index b3fbe73788e..00000000000 Binary files a/Other/screenshots/compositor.jpg and /dev/null differ diff --git a/Other/screenshots/imgui.jpg b/Other/screenshots/imgui.jpg deleted file mode 100644 index 7da4824628b..00000000000 Binary files a/Other/screenshots/imgui.jpg and /dev/null differ diff --git a/Other/screenshots/particle.jpg b/Other/screenshots/particle.jpg deleted file mode 100644 index 1edb8173153..00000000000 Binary files a/Other/screenshots/particle.jpg and /dev/null differ diff --git a/Other/screenshots/pbr.webp b/Other/screenshots/pbr.webp deleted file mode 100644 index 8a1f306e9cc..00000000000 Binary files a/Other/screenshots/pbr.webp and /dev/null differ diff --git a/Other/screenshots/shadows.jpg b/Other/screenshots/shadows.jpg deleted file mode 100644 index a5092198cfa..00000000000 Binary files a/Other/screenshots/shadows.jpg and /dev/null differ diff --git a/Other/screenshots/skeletal.jpg b/Other/screenshots/skeletal.jpg deleted file mode 100644 index a68cd815d20..00000000000 Binary files a/Other/screenshots/skeletal.jpg and /dev/null differ diff --git a/Other/screenshots/terrain.jpg b/Other/screenshots/terrain.jpg deleted file mode 100644 index 0e9b53fd33d..00000000000 Binary files a/Other/screenshots/terrain.jpg and /dev/null differ diff --git a/Other/screenshots/volume.jpg b/Other/screenshots/volume.jpg deleted file mode 100644 index 4618976ef59..00000000000 Binary files a/Other/screenshots/volume.jpg and /dev/null differ diff --git a/Other/tab2spc.py b/Other/tab2spc.py deleted file mode 100644 index 17366fb13e4..00000000000 --- a/Other/tab2spc.py +++ /dev/null @@ -1,56 +0,0 @@ -#! /usr/bin/env python - -import sys -import os -import getopt -import string -import re - -def fnParse( arg, dirname, files ): - for file in files: - for ext in arg: - if file.rfind( ext, len(file)-len(ext), len(file) ) != -1 and not os.path.isdir( dirname + "/" + file ): - fo = open( dirname + "/" + file, "rb" ) - lines = fo.read() - if not '\0' in lines: - newlines = re.sub( "\t", globals()['spaces'], lines ) - if newlines != lines: - backup = open( dirname + "/" + file + "~", "wb" ) - backup.write( lines ) - backup.close() - - fo.close() - fo = open( dirname + "/" + file, "wb" ) - fo.write(newlines) - - print "File " + dirname + "/" + file + " was changed." - fo.close() - -def fnHelp(): - helpstr = """ -This program transforms all the TAB characters in all -the files with the given extension from the directory -tree into the given number of spaces. - -Syntax: - tab2spc [num_spaces] [ext1] [ext2] [...] - -Extensions are given in the form: - .cpp .h .txt (no asterisk at the beginning) - -Copyright (c) 2002 by Adrian Cearnau (cearny@cearny.ro) -Any use, commercial or not, is allowed -""" - print helpstr - -if len(sys.argv) != 3: - fnHelp() -else: - spaces = "" - for i in range( 0, int(sys.argv[1]) ): - spaces = spaces + ' ' - exts = sys.argv[2].split() - currdir = os.getcwd() - os.path.walk( currdir, fnParse, exts ) - #print "\nTotally", num_files, "files were patched\n" - print "done" \ No newline at end of file diff --git a/PlugIns/Assimp/CMakeLists.txt b/PlugIns/Assimp/CMakeLists.txt deleted file mode 100644 index 3dc686ae3d6..00000000000 --- a/PlugIns/Assimp/CMakeLists.txt +++ /dev/null @@ -1,19 +0,0 @@ -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES ${PROJECT_BINARY_DIR}/include/OgreAssimpExports.h) - -add_library(Codec_Assimp ${OGRE_LIB_TYPE} ${HEADER_FILES} src/AssimpLoader.cpp) -target_include_directories(Codec_Assimp PUBLIC - "$" - $) -target_link_libraries(Codec_Assimp PUBLIC OgreMain fix::assimp) - -if(OGRE_BUILD_COMPONENT_RTSHADERSYSTEM) - target_link_libraries(Codec_Assimp PUBLIC OgreRTShaderSystem) -endif() - -ogre_config_framework(Codec_Assimp) -ogre_config_plugin(Codec_Assimp) -generate_export_header(Codec_Assimp - EXPORT_MACRO_NAME _OgreAssimpExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreAssimpExports.h) -install(FILES ${HEADER_FILES} DESTINATION include/OGRE/Plugins/Assimp) diff --git a/PlugIns/Assimp/include/OgreAssimpLoader.h b/PlugIns/Assimp/include/OgreAssimpLoader.h deleted file mode 100644 index b631ee570e1..00000000000 --- a/PlugIns/Assimp/include/OgreAssimpLoader.h +++ /dev/null @@ -1,155 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of - _ - ___ __ _ _ __ ___ __ _ ___ ___(_)_ __ ___ _ __ - / _ \ / _` | '__/ _ \/ _` / __/ __| | '_ ` _ \| '_ \ -| (_) | (_| | | | __/ (_| \__ \__ \ | | | | | | |_) | - \___/ \__, |_| \___|\__,_|___/___/_|_| |_| |_| .__/ - |___/ |_| - -For the latest info, see https://bitbucket.org/jacmoe/ogreassimp - -Copyright (c) 2011 Jacob 'jacmoe' Moen - -Licensed under the MIT license: - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __AssimpLoader_h__ -#define __AssimpLoader_h__ - -#include -#include -#include - -struct aiScene; -struct aiNode; -struct aiBone; -struct aiMesh; -struct aiMaterial; -struct aiAnimation; - -template class aiMatrix4x4t; -typedef aiMatrix4x4t aiMatrix4x4; - -namespace Assimp -{ -class Importer; -} - -namespace Ogre -{ - -/** \addtogroup Plugins Plugins -* @{ -*/ -/** \defgroup AssimpCodec AssimpCodec -* %Codec for loading geometry using the [Open-Asset-Importer](https://github.com/assimp/assimp) -* @{ -*/ -class _OgreAssimpExport AssimpLoader -{ -public: - enum LoaderParams - { - // 3ds max exports the animation over a longer time frame than the animation actually plays for - // this is a fix for that - LP_CUT_ANIMATION_WHERE_NO_FURTHER_CHANGE = 1 << 0, - - // Quiet mode - don't output anything - LP_QUIET_MODE = 1 << 1 - }; - - struct Options - { - float animationSpeedModifier; - int params; - int postProcessSteps; - String customAnimationName; - float maxEdgeAngle; - - Options() : animationSpeedModifier(1), params(0), postProcessSteps(0), maxEdgeAngle(30) {} - }; - - AssimpLoader(); - virtual ~AssimpLoader(); - - bool load(const String& source, Mesh* mesh, SkeletonPtr& skeletonPtr, - const Options& options = Options()); - - bool load(const DataStreamPtr& source, Mesh* mesh, SkeletonPtr& skeletonPtr, - const Options& options = Options()); - -private: - bool _load(const char* name, Assimp::Importer& importer, Mesh* mesh, SkeletonPtr& skeletonPtr, - const Options& options); - bool createSubMesh(const String& name, int index, const aiNode* pNode, const aiMesh* mesh, - const MaterialPtr& matptr, Mesh* mMesh, AxisAlignedBox& mAAB); - void grabNodeNamesFromNode(const aiScene* mScene, const aiNode* pNode); - void grabBoneNamesFromNode(const aiScene* mScene, const aiNode* pNode); - void computeNodesDerivedTransform(const aiScene* mScene, const aiNode* pNode, - const aiMatrix4x4& accTransform); - void createBonesFromNode(const aiScene* mScene, const aiNode* pNode); - void createBoneHiearchy(const aiScene* mScene, const aiNode* pNode); - void loadDataFromNode(const aiScene* mScene, const aiNode* pNode, Mesh* mesh); - void markAllChildNodesAsNeeded(const aiNode* pNode); - void flagNodeAsNeeded(const char* name); - bool isNodeNeeded(const char* name); - void parseAnimation(const aiScene* mScene, int index, aiAnimation* anim); - typedef std::map boneMapType; - boneMapType boneMap; - // aiNode* mSkeletonRootNode; - int mLoaderParams; - - String mCustomAnimationName; - - typedef std::map BoneNodeMap; - BoneNodeMap mBoneNodesByName; - - typedef std::map BoneMap; - BoneMap mBonesByName; - - typedef std::map NodeTransformMap; - NodeTransformMap mNodeDerivedTransformByName; - - SkeletonPtr mSkeleton; - - static int msBoneCount; - - bool mQuietMode; - Real mTicksPerSecond; - Real mAnimationSpeedModifier; -}; - -class _OgreAssimpExport AssimpPlugin : public Plugin -{ -public: - const String& getName() const override; - void install() override; - void uninstall() override; - void initialise() override {} - void shutdown() override {} -}; -/** @} */ -/** @} */ -} // namespace Ogre - -#endif // __AssimpLoader_h__ diff --git a/PlugIns/Assimp/src/AssimpLoader.cpp b/PlugIns/Assimp/src/AssimpLoader.cpp deleted file mode 100644 index 0003a9b30c3..00000000000 --- a/PlugIns/Assimp/src/AssimpLoader.cpp +++ /dev/null @@ -1,1426 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of - _ - ___ __ _ _ __ ___ __ _ ___ ___(_)_ __ ___ _ __ - / _ \ / _` | '__/ _ \/ _` / __/ __| | '_ ` _ \| '_ \ -| (_) | (_| | | | __/ (_| \__ \__ \ | | | | | | |_) | - \___/ \__, |_| \___|\__,_|___/___/_|_| |_| |_| .__/ - |___/ |_| - -Copyright (c) 2011 Jacob 'jacmoe' Moen - -Licensed under the MIT license: - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreAssimpLoader.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM -#include -#endif - -namespace Ogre -{ - -namespace -{ -struct OgreLogStream : public Assimp::LogStream -{ - LogMessageLevel _lml; - OgreLogStream(LogMessageLevel lml) : _lml(lml) {} - - void write(const char* message) override - { - String msg(message); - StringUtil::trim(msg); - LogManager::getSingleton().logMessage("Assimp: " + msg, _lml); - } -}; - -struct OgreIOStream : public Assimp::IOStream -{ - DataStreamPtr stream; - - OgreIOStream(const DataStreamPtr& _stream) : stream(_stream) {} - - size_t Read(void* pvBuffer, size_t pSize, size_t pCount) override - { - size_t bytes = stream->read(pvBuffer, pSize * pCount); - return bytes / pSize; - } - size_t Tell() const override { return stream->tell(); } - size_t FileSize() const override { return stream->size(); } - - size_t Write(const void* pvBuffer, size_t pSize, size_t pCount) override { return 0; } - aiReturn Seek(size_t pOffset, aiOrigin pOrigin) override - { - if (pOrigin != aiOrigin_SET) - return AI_FAILURE; - - stream->seek(pOffset); - return AI_SUCCESS; - } - void Flush() override {} -}; - -struct OgreIOSystem : public Assimp::IOSystem -{ - DataStreamPtr source; - std::vector streams; - String _group; - - OgreIOSystem(const DataStreamPtr& _source, const String& group) : source(_source), _group(group) {} - - bool Exists(const char* pFile) const override - { - String file = StringUtil::normalizeFilePath(pFile, false); - if (file == source->getName()) - return true; - return ResourceGroupManager::getSingleton().resourceExists(_group, file); - } - char getOsSeparator() const override { return '/'; } - - Assimp::IOStream* Open(const char* pFile, const char* pMode) override - { - String file = StringUtil::normalizeFilePath(pFile, false); - DataStreamPtr res; - if (file == source->getName()) - { - res = source; - // glTF2 importer wants to open files multiple times - // while this is not fully correct, this makes it happy - source->seek(0); - } - if (!res) - res = ResourceGroupManager::getSingleton().openResource(file, _group, NULL, false); - - if (res) - { - streams.emplace_back(new OgreIOStream(res)); - return streams.back(); - } - return NULL; - } - void Close(Assimp::IOStream* pFile) override - { - auto it = std::find(streams.begin(), streams.end(), pFile); - if (it != streams.end()) - { - delete pFile; - streams.erase(it); - } - } -}; - -/** translation, rotation, scale */ -typedef std::tuple KeyframeData; -typedef std::map KeyframesMap; - -template -void GetInterpolationIterators(KeyframesMap& keyframes, KeyframesMap::iterator it, - KeyframesMap::reverse_iterator& front, KeyframesMap::iterator& back) -{ - front = KeyframesMap::reverse_iterator(it); - - front++; - for (; front != keyframes.rend(); front++) - { - if (std::get<_i>(front->second) != NULL) - { - break; - } - } - - back = it; - back++; - for (; back != keyframes.end(); back++) - { - if (std::get<_i>(back->second) != NULL) - { - break; - } - } -} - -aiVector3D getTranslate(aiNodeAnim* node_anim, KeyframesMap& keyframes, KeyframesMap::iterator it, - Real ticksPerSecond) -{ - aiVectorKey* translateKey = std::get<0>(it->second); - aiVector3D vect; - if (translateKey) - { - vect = translateKey->mValue; - } - else - { - KeyframesMap::reverse_iterator front; - KeyframesMap::iterator back; - - GetInterpolationIterators<0>(keyframes, it, front, back); - - KeyframesMap::reverse_iterator rend = keyframes.rend(); - KeyframesMap::iterator end = keyframes.end(); - aiVectorKey* frontKey = NULL; - aiVectorKey* backKey = NULL; - - if (front != rend) - frontKey = std::get<0>(front->second); - - if (back != end) - backKey = std::get<0>(back->second); - - // got 2 keys can interpolate - if (frontKey && backKey) - { - float prop = - (float)(((double)it->first - frontKey->mTime) / (backKey->mTime - frontKey->mTime)); - prop /= ticksPerSecond; - vect = Math::lerp(frontKey->mValue, backKey->mValue, prop); - } - - else if (frontKey) - { - vect = frontKey->mValue; - } - else if (backKey) - { - vect = backKey->mValue; - } - } - - return vect; -} - -aiQuaternion getRotate(aiNodeAnim* node_anim, KeyframesMap& keyframes, KeyframesMap::iterator it, - Real ticksPerSecond) -{ - aiQuatKey* rotationKey = std::get<1>(it->second); - aiQuaternion rot; - if (rotationKey) - { - rot = rotationKey->mValue; - } - else - { - KeyframesMap::reverse_iterator front; - KeyframesMap::iterator back; - - GetInterpolationIterators<1>(keyframes, it, front, back); - - KeyframesMap::reverse_iterator rend = keyframes.rend(); - KeyframesMap::iterator end = keyframes.end(); - aiQuatKey* frontKey = NULL; - aiQuatKey* backKey = NULL; - - if (front != rend) - frontKey = std::get<1>(front->second); - - if (back != end) - backKey = std::get<1>(back->second); - - // got 2 keys can interpolate - if (frontKey && backKey) - { - float prop = - (float)(((double)it->first - frontKey->mTime) / (backKey->mTime - frontKey->mTime)); - prop /= ticksPerSecond; - aiQuaternion::Interpolate(rot, frontKey->mValue, backKey->mValue, prop); - } - - else if (frontKey) - { - rot = frontKey->mValue; - } - else if (backKey) - { - rot = backKey->mValue; - } - } - - return rot; -} - -aiVector3D getScale(aiNodeAnim* node_anim, KeyframesMap& keyframes, KeyframesMap::iterator it, - Real ticksPerSecond) -{ - aiVectorKey* scaleKey = std::get<2>(it->second); - aiVector3D vect(1, 1, 1); - if (scaleKey) - { - vect = scaleKey->mValue; - } - else - { - KeyframesMap::reverse_iterator front; - KeyframesMap::iterator back; - - GetInterpolationIterators<2>(keyframes, it, front, back); - - KeyframesMap::reverse_iterator rend = keyframes.rend(); - KeyframesMap::iterator end = keyframes.end(); - aiVectorKey* frontKey = NULL; - aiVectorKey* backKey = NULL; - - if (front != rend) - frontKey = std::get<2>(front->second); - - if (back != end) - backKey = std::get<2>(back->second); - - // got 2 keys can interpolate - if (frontKey && backKey) - { - float prop = - (float)(((double)it->first - frontKey->mTime) / (backKey->mTime - frontKey->mTime)); - prop /= ticksPerSecond; - vect = Math::lerp(frontKey->mValue, backKey->mValue, prop); - } - - else if (frontKey) - { - vect = frontKey->mValue; - } - else if (backKey) - { - vect = backKey->mValue; - } - } - - return vect; -} - -String ReplaceSpaces(const String& s) -{ - String res(s); - replace(res.begin(), res.end(), ' ', '_'); - - return res; -} -} // namespace - -int AssimpLoader::msBoneCount = 0; - -AssimpLoader::AssimpLoader() -{ - Assimp::DefaultLogger::create(""); - Assimp::DefaultLogger::get()->attachStream(new OgreLogStream(LML_NORMAL), ~Assimp::DefaultLogger::Err); - Assimp::DefaultLogger::get()->attachStream(new OgreLogStream(LML_CRITICAL), Assimp::DefaultLogger::Err); -} - -AssimpLoader::~AssimpLoader() {} - -bool AssimpLoader::load(const DataStreamPtr& source, Mesh* mesh, SkeletonPtr& skeletonPtr, - const Options& options) -{ - Assimp::Importer importer; - importer.SetIOHandler(new OgreIOSystem(source, mesh->getGroup())); - _load(source->getName().c_str(), importer, mesh, skeletonPtr, options); - return true; -} - -bool AssimpLoader::load(const String& source, Mesh* mesh, SkeletonPtr& skeletonPtr, - const AssimpLoader::Options& options) -{ - Assimp::Importer importer; - _load(source.c_str(), importer, mesh, skeletonPtr, options); - return true; -} - -bool AssimpLoader::_load(const char* name, Assimp::Importer& importer, Mesh* mesh, SkeletonPtr& skeletonPtr, - const Options& options) -{ - uint32 flags = aiProcessPreset_TargetRealtime_Fast | aiProcess_TransformUVCoords | aiProcess_FlipUVs; - flags &= ~(aiProcess_JoinIdenticalVertices | aiProcess_CalcTangentSpace); // optimize for fast loading - - flags |= options.postProcessSteps; - - if((flags & (aiProcess_GenSmoothNormals | aiProcess_GenNormals)) != aiProcess_GenNormals) - flags &= ~aiProcess_GenNormals; // prefer smooth normals - - importer.SetPropertyFloat("PP_GSN_MAX_SMOOTHING_ANGLE", options.maxEdgeAngle); - const aiScene* scene = importer.ReadFile(name, flags); - - // If the import failed, report it - if (!scene) - { - LogManager::getSingleton().logError("Assimp failed - " + String(importer.GetErrorString())); - return false; - } - - mAnimationSpeedModifier = options.animationSpeedModifier; - mLoaderParams = options.params; - mQuietMode = mLoaderParams & LP_QUIET_MODE; - mCustomAnimationName = options.customAnimationName; - mNodeDerivedTransformByName.clear(); - - String basename, extension; - StringUtil::splitBaseFilename(mesh->getName(), basename, extension); - - grabNodeNamesFromNode(scene, scene->mRootNode); - grabBoneNamesFromNode(scene, scene->mRootNode); - - computeNodesDerivedTransform(scene, scene->mRootNode, scene->mRootNode->mTransformation); - - if (mBonesByName.size()) - { - mSkeleton = SkeletonManager::getSingleton().create(basename + ".skeleton", RGN_DEFAULT, true); - - msBoneCount = 0; - createBonesFromNode(scene, scene->mRootNode); - msBoneCount = 0; - createBoneHiearchy(scene, scene->mRootNode); - - if (scene->HasAnimations()) - { - for (unsigned int i = 0; i < scene->mNumAnimations; ++i) - { - parseAnimation(scene, i, scene->mAnimations[i]); - } - } - } - - // Create embedded textures - for (unsigned int i = 0; i < scene->mNumTextures; ++i) - { - const aiTexture* tex = scene->mTextures[i]; - auto texname = - StringUtil::format("%s%s.%s", mesh->getName().c_str(), tex->mFilename.C_Str(), tex->achFormatHint); - if (TextureManager::getSingleton().resourceExists(texname, mesh->getGroup())) - continue; - - Image img; - if(tex->mHeight == 0) - { - auto stream = std::make_shared(tex->pcData, tex->mWidth, false); - try - { - img.load(stream, tex->achFormatHint); - } - catch (Exception& e) - { - LogManager::getSingleton().logError("Could not load embedded image - " + e.getDescription()); - continue; - } - } - else - { - img.loadDynamicImage((uchar*)tex->pcData, tex->mWidth, tex->mHeight, PF_A8R8G8B8); - } - - TextureManager::getSingleton().loadImage(texname, mesh->getGroup(), img); - } - - loadDataFromNode(scene, scene->mRootNode, mesh); - - Assimp::DefaultLogger::kill(); - - if (mSkeleton) - { - - if (!mQuietMode) - { - LogManager::getSingleton().logMessage("Root bone: " + mSkeleton->getRootBones()[0]->getName()); - } - - skeletonPtr = mSkeleton; - mesh->setSkeletonName(mSkeleton->getName()); - } - - for (auto sm : mesh->getSubMeshes()) - { - if (!sm->useSharedVertices) - { - - VertexDeclaration* newDcl = sm->vertexData->vertexDeclaration->getAutoOrganisedDeclaration( - mesh->hasSkeleton(), mesh->hasVertexAnimation(), false); - - if (*newDcl != *(sm->vertexData->vertexDeclaration)) - { - sm->vertexData->reorganiseBuffers(newDcl); - } - } - } - - // clean up - mBonesByName.clear(); - mBoneNodesByName.clear(); - boneMap.clear(); - mSkeleton.reset(); - - mCustomAnimationName = ""; - - return true; -} - -void AssimpLoader::parseAnimation(const aiScene* mScene, int index, aiAnimation* anim) -{ - // DefBonePose a matrix that represents the local bone transform (can build from Ogre bone components) - // PoseToKey a matrix representing the keyframe translation - // What assimp stores aiNodeAnim IS the decomposed form of the transform (DefBonePose * PoseToKey) - // To get PoseToKey which is what Ogre needs we'ed have to build the transform from components in - // aiNodeAnim and then DefBonePose.Inverse() * aiNodeAnim(generated transform) will be the right - // transform - - String animName; - if (mCustomAnimationName != "") - { - animName = mCustomAnimationName; - if (index >= 1) - { - animName += StringConverter::toString(index); - } - } - else - { - animName = String(anim->mName.data); - } - if (animName.length() < 1) - { - animName = "Animation" + StringConverter::toString(index); - } - - if (!mQuietMode) - { - LogManager::getSingleton().logMessage("Animation name = '" + animName + "'"); - LogManager::getSingleton().logMessage("duration = " + - StringConverter::toString(Real(anim->mDuration))); - LogManager::getSingleton().logMessage("tick/sec = " + - StringConverter::toString(Real(anim->mTicksPerSecond))); - LogManager::getSingleton().logMessage("channels = " + - StringConverter::toString(anim->mNumChannels)); - } - Animation* animation; - mTicksPerSecond = (Real)((0 == anim->mTicksPerSecond) ? 24 : anim->mTicksPerSecond); - mTicksPerSecond *= mAnimationSpeedModifier; - - Real cutTime = 0.0; - if (mLoaderParams & LP_CUT_ANIMATION_WHERE_NO_FURTHER_CHANGE) - { - for (int i = 1; i < (int)anim->mNumChannels; i++) - { - aiNodeAnim* node_anim = anim->mChannels[i]; - - // times of the equality check - Real timePos = 0.0; - Real timeRot = 0.0; - - for (unsigned int j = 1; j < node_anim->mNumPositionKeys; j++) - { - if (node_anim->mPositionKeys[j] != node_anim->mPositionKeys[j - 1]) - { - timePos = (Real)node_anim->mPositionKeys[j].mTime; - timePos /= mTicksPerSecond; - } - } - - for (unsigned int j = 1; j < node_anim->mNumRotationKeys; j++) - { - if (node_anim->mRotationKeys[j] != node_anim->mRotationKeys[j - 1]) - { - timeRot = (Real)node_anim->mRotationKeys[j].mTime; - timeRot /= mTicksPerSecond; - } - } - - if (timePos > cutTime) - { - cutTime = timePos; - } - if (timeRot > cutTime) - { - cutTime = timeRot; - } - } - - animation = mSkeleton->createAnimation(String(animName), cutTime); - } - else - { - cutTime = Math::POS_INFINITY; - animation = mSkeleton->createAnimation(String(animName), Real(anim->mDuration / mTicksPerSecond)); - } - - animation->setInterpolationMode(Animation::IM_LINEAR); // FIXME: Is this always true? - - if (!mQuietMode) - { - LogManager::getSingleton().logMessage("Cut Time " + StringConverter::toString(cutTime)); - } - - for (int i = 0; i < (int)anim->mNumChannels; i++) - { - TransformKeyFrame* keyframe; - - aiNodeAnim* node_anim = anim->mChannels[i]; - if (!mQuietMode) - { - LogManager::getSingleton().logMessage("Channel " + StringConverter::toString(i)); - LogManager::getSingleton().logMessage("affecting node: " + String(node_anim->mNodeName.data)); - // LogManager::getSingleton().logMessage("position keys: " + - // StringConverter::toString(node_anim->mNumPositionKeys)); - // LogManager::getSingleton().logMessage("rotation keys: " + - // StringConverter::toString(node_anim->mNumRotationKeys)); - // LogManager::getSingleton().logMessage("scaling keys: " + - // StringConverter::toString(node_anim->mNumScalingKeys)); - } - - String boneName = String(node_anim->mNodeName.data); - - if (mSkeleton->hasBone(boneName)) - { - Bone* bone = mSkeleton->getBone(boneName); - Affine3 defBonePoseInv; - defBonePoseInv.makeInverseTransform(bone->getPosition(), bone->getScale(), - bone->getOrientation()); - - NodeAnimationTrack* track = animation->createNodeTrack(bone->getHandle(), bone); - - // Ogre needs translate rotate and scale for each keyframe in the track - KeyframesMap keyframes; - - for (unsigned int j = 0; j < node_anim->mNumPositionKeys; j++) - { - keyframes[(Real)node_anim->mPositionKeys[j].mTime / mTicksPerSecond] = - KeyframeData(&(node_anim->mPositionKeys[j]), NULL, NULL); - } - - for (unsigned int j = 0; j < node_anim->mNumRotationKeys; j++) - { - KeyframesMap::iterator it = - keyframes.find((Real)node_anim->mRotationKeys[j].mTime / mTicksPerSecond); - if (it != keyframes.end()) - { - std::get<1>(it->second) = &(node_anim->mRotationKeys[j]); - } - else - { - keyframes[(Real)node_anim->mRotationKeys[j].mTime / mTicksPerSecond] = - KeyframeData(NULL, &(node_anim->mRotationKeys[j]), NULL); - } - } - - for (unsigned int j = 0; j < node_anim->mNumScalingKeys; j++) - { - KeyframesMap::iterator it = - keyframes.find((Real)node_anim->mScalingKeys[j].mTime / mTicksPerSecond); - if (it != keyframes.end()) - { - std::get<2>(it->second) = &(node_anim->mScalingKeys[j]); - } - else - { - keyframes[(Real)node_anim->mRotationKeys[j].mTime / mTicksPerSecond] = - KeyframeData(NULL, NULL, &(node_anim->mScalingKeys[j])); - } - } - - KeyframesMap::iterator it = keyframes.begin(); - KeyframesMap::iterator it_end = keyframes.end(); - for (; it != it_end; ++it) - { - if (it->first < cutTime) // or should it be <= - { - aiVector3D aiTrans = getTranslate(node_anim, keyframes, it, mTicksPerSecond); - - Vector3 trans(aiTrans.x, aiTrans.y, aiTrans.z); - - aiQuaternion aiRot = getRotate(node_anim, keyframes, it, mTicksPerSecond); - Quaternion rot(aiRot.w, aiRot.x, aiRot.y, aiRot.z); - - aiVector3D aiScale = getScale(node_anim, keyframes, it, mTicksPerSecond); - Vector3 scale(aiScale.x, aiScale.y, aiScale.z); - - Vector3 transCopy = trans; - - Affine3 fullTransform; - fullTransform.makeTransform(trans, scale, rot); - - Affine3 poseTokey = defBonePoseInv * fullTransform; - poseTokey.decomposition(trans, scale, rot); - - keyframe = track->createNodeKeyFrame(Real(it->first)); - - // weirdness with the root bone, But this seems to work - if (mSkeleton->getRootBones()[0]->getName() == boneName) - { - trans = transCopy - bone->getPosition(); - } - - keyframe->setTranslate(trans); - keyframe->setRotation(rot); - keyframe->setScale(scale); - } - } - - } // if bone exists - - } // loop through channels - - mSkeleton->optimiseAllAnimations(); -} - -void AssimpLoader::markAllChildNodesAsNeeded(const aiNode* pNode) -{ - flagNodeAsNeeded(pNode->mName.data); - // Traverse all child nodes of the current node instance - for (unsigned int childIdx = 0; childIdx < pNode->mNumChildren; ++childIdx) - { - const aiNode* pChildNode = pNode->mChildren[childIdx]; - markAllChildNodesAsNeeded(pChildNode); - } -} - -void AssimpLoader::grabNodeNamesFromNode(const aiScene* mScene, const aiNode* pNode) -{ - boneMap.emplace(String(pNode->mName.data), false); - mBoneNodesByName[pNode->mName.data] = pNode; - if (!mQuietMode) - { - LogManager::getSingleton().logMessage("Node " + String(pNode->mName.data) + " found."); - } - - // Traverse all child nodes of the current node instance - for (unsigned int childIdx = 0; childIdx < pNode->mNumChildren; ++childIdx) - { - const aiNode* pChildNode = pNode->mChildren[childIdx]; - grabNodeNamesFromNode(mScene, pChildNode); - } -} - -void AssimpLoader::computeNodesDerivedTransform(const aiScene* mScene, const aiNode* pNode, - const aiMatrix4x4& accTransform) -{ - if (mNodeDerivedTransformByName.find(pNode->mName.data) == mNodeDerivedTransformByName.end()) - { - mNodeDerivedTransformByName[pNode->mName.data] = Affine3(accTransform[0]); - } - for (unsigned int childIdx = 0; childIdx < pNode->mNumChildren; ++childIdx) - { - const aiNode* pChildNode = pNode->mChildren[childIdx]; - computeNodesDerivedTransform(mScene, pChildNode, accTransform * pChildNode->mTransformation); - } -} - -void AssimpLoader::createBonesFromNode(const aiScene* mScene, const aiNode* pNode) -{ - if (isNodeNeeded(pNode->mName.data)) - { - Bone* bone = mSkeleton->createBone(String(pNode->mName.data), msBoneCount); - - aiQuaternion rot; - aiVector3D pos; - aiVector3D scale; - - const aiMatrix4x4& aiM = pNode->mTransformation; - - if (!aiM.IsIdentity()) - { - aiM.Decompose(scale, rot, pos); - bone->setPosition(pos.x, pos.y, pos.z); - bone->setOrientation(rot.w, rot.x, rot.y, rot.z); - } - - if (!mQuietMode) - { - LogManager::getSingleton().logMessage(StringConverter::toString(msBoneCount) + - ") Creating bone '" + String(pNode->mName.data) + "'"); - } - msBoneCount++; - } - // Traverse all child nodes of the current node instance - for (unsigned int childIdx = 0; childIdx < pNode->mNumChildren; ++childIdx) - { - const aiNode* pChildNode = pNode->mChildren[childIdx]; - createBonesFromNode(mScene, pChildNode); - } -} - -void AssimpLoader::createBoneHiearchy(const aiScene* mScene, const aiNode* pNode) -{ - if (isNodeNeeded(pNode->mName.data)) - { - Bone* parent = 0; - Bone* child = 0; - if (pNode->mParent) - { - if (mSkeleton->hasBone(pNode->mParent->mName.data)) - { - parent = mSkeleton->getBone(pNode->mParent->mName.data); - } - } - if (mSkeleton->hasBone(pNode->mName.data)) - { - child = mSkeleton->getBone(pNode->mName.data); - } - if (parent && child) - { - parent->addChild(child); - } - } - // Traverse all child nodes of the current node instance - for (unsigned int childIdx = 0; childIdx < pNode->mNumChildren; childIdx++) - { - const aiNode* pChildNode = pNode->mChildren[childIdx]; - createBoneHiearchy(mScene, pChildNode); - } -} - -void AssimpLoader::flagNodeAsNeeded(const char* name) -{ - boneMapType::iterator iter = boneMap.find(String(name)); - if (iter != boneMap.end()) - { - iter->second = true; - } -} - -bool AssimpLoader::isNodeNeeded(const char* name) -{ - boneMapType::iterator iter = boneMap.find(String(name)); - if (iter != boneMap.end()) - { - return iter->second; - } - return false; -} - -void AssimpLoader::grabBoneNamesFromNode(const aiScene* mScene, const aiNode* pNode) -{ - if (pNode->mNumMeshes > 0) - { - for (unsigned int idx = 0; idx < pNode->mNumMeshes; ++idx) - { - aiMesh* pAIMesh = mScene->mMeshes[pNode->mMeshes[idx]]; - - if (pAIMesh->HasBones()) - { - for (uint32 i = 0; i < pAIMesh->mNumBones; ++i) - { - aiBone* pAIBone = pAIMesh->mBones[i]; - if (NULL != pAIBone) - { - mBonesByName[pAIBone->mName.data] = pAIBone; - - if (!mQuietMode) - { - LogManager::getSingleton().logMessage( - StringConverter::toString(i) + - ") REAL BONE with name : " + String(pAIBone->mName.data)); - } - - // flag this node and all parents of this node as needed, until we reach the node - // holding the mesh, or the parent. - aiNode* node = mScene->mRootNode->FindNode(pAIBone->mName.data); - while (node) - { - if (node->mName == pNode->mName) - { - flagNodeAsNeeded(node->mName.data); - break; - } - if (node->mName == pNode->mParent->mName) - { - flagNodeAsNeeded(node->mName.data); - break; - } - - // Not a root node, flag this as needed and continue to the parent - flagNodeAsNeeded(node->mName.data); - node = node->mParent; - } - - // Flag all children of this node as needed - node = mScene->mRootNode->FindNode(pAIBone->mName.data); - markAllChildNodesAsNeeded(node); - - } // if we have a valid bone - } // loop over bones - } // if this mesh has bones - } // loop over meshes - } // if this node has meshes - - // Traverse all child nodes of the current node instance - for (unsigned int childIdx = 0; childIdx < pNode->mNumChildren; childIdx++) - { - const aiNode* pChildNode = pNode->mChildren[childIdx]; - grabBoneNamesFromNode(mScene, pChildNode); - } -} - -static bool getTextureName(const aiMaterial* mat, aiTextureType type, const aiScene* scene, const String& meshName, - String& basename) -{ - aiString path; - String outPath; - if (mat->GetTexture(type, 0, &path) == AI_SUCCESS) - { - const aiTexture* tex = scene->GetEmbeddedTexture(path.C_Str()); - if(tex) - { - basename = StringUtil::format("%s%s.%.8s", meshName.c_str(), tex->mFilename.C_Str(), tex->achFormatHint); - return true; - } - - StringUtil::splitFilename(String(path.data), basename, outPath); - return true; - } - return false; -} - -static MaterialPtr createMaterial(const aiMaterial* mat, const Ogre::String &group, const String& meshName, const aiScene* scene, bool verbose) -{ - static int dummyMatCount = 0; - - MaterialManager* omatMgr = MaterialManager::getSingletonPtr(); - enum aiTextureType type = aiTextureType_DIFFUSE; - static aiString path; - unsigned int uvindex = 0; // the texture uv index channel - - aiString szPath; - if (AI_SUCCESS == aiGetMaterialString(mat, AI_MATKEY_NAME, &szPath)) - { - if (verbose) - { - LogManager::getSingleton().logMessage("Using aiGetMaterialString : Name " + - String(szPath.data)); - } - } - - String matName = meshName; - if(szPath.length) - { - matName += String(szPath.data); - matName = ReplaceSpaces(matName); - } - else - { - matName += StringUtil::format("dummyMat%d", dummyMatCount++); - } - - auto status = omatMgr->createOrRetrieve(matName, group); - auto omat = static_pointer_cast(status.first); - - if (!status.second) - return omat; - - if (verbose) - { - LogManager::getSingleton().logMessage("Creating " + matName); - } - - // ambient - aiColor4D clr(1.0f, 1.0f, 1.0f, 1.0); - // Ambient is usually way too low! FIX ME! - if (mat->GetTexture(type, 0, &path) != AI_SUCCESS) - aiGetMaterialColor(mat, AI_MATKEY_COLOR_AMBIENT, &clr); - omat->setAmbient(clr.r, clr.g, clr.b); - - // diffuse - clr = aiColor4D(1.0f, 1.0f, 1.0f, 1.0f); - if (AI_SUCCESS == aiGetMaterialColor(mat, AI_MATKEY_COLOR_DIFFUSE, &clr)) - { - omat->setDiffuse(clr.r, clr.g, clr.b, clr.a); - } - - // specular - clr = aiColor4D(1.0f, 1.0f, 1.0f, 1.0f); - if (AI_SUCCESS == aiGetMaterialColor(mat, AI_MATKEY_COLOR_SPECULAR, &clr)) - { - omat->setSpecular(clr.r, clr.g, clr.b, clr.a); - } - - // emissive - clr = aiColor4D(1.0f, 1.0f, 1.0f, 1.0f); - if (AI_SUCCESS == aiGetMaterialColor(mat, AI_MATKEY_COLOR_EMISSIVE, &clr)) - { - omat->setSelfIllumination(clr.r, clr.g, clr.b); - } - - float fShininess; - if (AI_SUCCESS == aiGetMaterialFloat(mat, AI_MATKEY_SHININESS, &fShininess)) - { - omat->setShininess(Real(fShininess)); - } - - int shade = aiShadingMode_NoShading; - if (AI_SUCCESS == mat->Get(AI_MATKEY_SHADING_MODEL, shade) && shade != aiShadingMode_NoShading) - { - switch (shade) - { - case aiShadingMode_Phong: // Phong shading mode was added to opengl and directx years ago to be - // ready for gpus to support it (in fixed function pipeline), but no gpus - // ever did, so it has never done anything. From directx 10 onwards it was - // removed again. - case aiShadingMode_Gouraud: - omat->setShadingMode(SO_GOURAUD); - break; - case aiShadingMode_Flat: - omat->setShadingMode(SO_FLAT); - break; - default: - break; - } - } - - String basename; - if (getTextureName(mat, type, scene, meshName, basename)) - { - if (verbose) - { - LogManager::getSingleton().logMessage("Found texture " + basename + " for channel " + - StringConverter::toString(uvindex)); - } - omat->getTechnique(0)->getPass(0)->createTextureUnitState(basename); - } - - if (getTextureName(mat, aiTextureType_EMISSIVE, scene, meshName, basename)) - { - if (verbose) - { - LogManager::getSingleton().logMessage("Found emissive map: " + basename); - } - auto tus = omat->getTechnique(0)->getPass(0)->createTextureUnitState(basename); - tus->setColourOperation(LBO_ADD); - omat->setSelfIllumination(0, 0, 0); // assimp assumes emissive is modulated, whereas Ogre adds up - } - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - auto shaderGen = RTShader::ShaderGenerator::getSingletonPtr(); - - if(!shaderGen) - return omat; - - if (getTextureName(mat, aiTextureType_NORMALS, scene, meshName, basename)) - { - if (verbose) - { - LogManager::getSingleton().logMessage("Found normal map: " + basename); - } - - auto tus = omat->getTechnique(0)->getPass(0)->createTextureUnitState(basename); - - // mark as normal map - shaderGen->_markNonFFP(tus); - uint16 texureIdx = tus->getParent()->getNumTextureUnitStates() - 1; - - shaderGen->createShaderBasedTechnique(omat->getTechnique(0), MSN_SHADERGEN); - auto rs = shaderGen->getRenderState(MSN_SHADERGEN, *omat, 0); - auto srs = shaderGen->createSubRenderState("NormalMap"); - - srs->setParameter("texture_index", std::to_string(texureIdx)); - rs->addTemplateSubRenderState(srs); - } - - if (getTextureName(mat, aiTextureType_UNKNOWN, scene, meshName, basename)) - { - if (verbose) - { - LogManager::getSingleton().logMessage("Found metal roughness map: " + basename); - } - - shaderGen->createShaderBasedTechnique(omat->getTechnique(0), MSN_SHADERGEN); - auto rs = shaderGen->getRenderState(MSN_SHADERGEN, *omat, 0); - auto srs = shaderGen->createSubRenderState("CookTorranceLighting"); - - srs->setParameter("texture", basename); - rs->addTemplateSubRenderState(srs); - - srs = shaderGen->createSubRenderState("FFP_Texturing"); - srs->setParameter("late_add_blend", "true"); - rs->addTemplateSubRenderState(srs); - } -#endif - - return omat; -} - -bool AssimpLoader::createSubMesh(const String& name, int index, const aiNode* pNode, const aiMesh* mesh, - const MaterialPtr& matptr, Mesh* mMesh, AxisAlignedBox& mAAB) -{ - // if animated all submeshes must have bone weights - if (mBonesByName.size() && !mesh->HasBones()) - { - if (!mQuietMode) - { - LogManager::getSingleton().logMessage("Skipping Mesh " + String(mesh->mName.data) + - "with no bone weights"); - } - return false; - } - - // now begin the object definition - // We create a submesh per material - SubMesh* submesh = mMesh->createSubMesh(name + StringConverter::toString(index)); - - // prime pointers to vertex related data - aiVector3D* vec = mesh->mVertices; - aiVector3D* norm = mesh->mNormals; - aiVector3D* uv = mesh->mTextureCoords[0]; - aiVector3D* tang = mesh->mTangents; - aiColor4D *col = mesh->mColors[0]; - - // We must create the vertex data, indicating how many vertices there will be - submesh->createVertexData(); - submesh->vertexData->vertexStart = 0; - submesh->vertexData->vertexCount = mesh->mNumVertices; - - switch(mesh->mPrimitiveTypes) - { - default: - case aiPrimitiveType_TRIANGLE: - submesh->operationType = RenderOperation::OT_TRIANGLE_LIST; - break; - case aiPrimitiveType_LINE: - submesh->operationType = RenderOperation::OT_LINE_LIST; - break; - case aiPrimitiveType_POINT: - submesh->operationType = RenderOperation::OT_POINT_LIST; - break; - } - - // We must now declare what the vertex data contains - VertexDeclaration* declaration = submesh->vertexData->vertexDeclaration; - static const unsigned short source = 0; - size_t offset = 0; - offset += declaration->addElement(source, offset, VET_FLOAT3, VES_POSITION).getSize(); - - if (!mQuietMode) - { - LogManager::getSingleton().logMessage(StringUtil::format("%d vertices", mesh->mNumVertices)); - } - if (norm) - { - if (!mQuietMode) - { - LogManager::getSingleton().logMessage(StringUtil::format("%d normals", mesh->mNumVertices)); - } - offset += declaration->addElement(source, offset, VET_FLOAT3, VES_NORMAL).getSize(); - } - - if (uv) - { - if (!mQuietMode) - { - LogManager::getSingleton().logMessage(StringUtil::format("%d uvs", mesh->mNumVertices)); - } - offset += declaration->addElement(source, offset, VET_FLOAT2, VES_TEXTURE_COORDINATES).getSize(); - } - - if (tang) - { - if (!mQuietMode) - { - LogManager::getSingleton().logMessage(StringUtil::format("%d tangents", mesh->mNumVertices)); - } - offset += declaration->addElement(source, offset, VET_FLOAT3, VES_TANGENT).getSize(); - } - - if (col) - { - matptr->getTechnique(0)->getPass(0)->setVertexColourTracking(TVC_DIFFUSE); - if (!mQuietMode) - { - LogManager::getSingleton().logMessage(StringUtil::format("%d colours", mesh->mNumVertices)); - } - offset += declaration->addElement(source, offset, VET_UBYTE4_NORM, VES_DIFFUSE).getSize(); - } - - // Finally we set a material to the submesh - submesh->setMaterial(matptr); - - // We create the hardware vertex buffer - HardwareVertexBufferSharedPtr vbuffer = HardwareBufferManager::getSingleton().createVertexBuffer( - declaration->getVertexSize(source), // == offset - submesh->vertexData->vertexCount, // == nbVertices - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - Affine3 aiM = mNodeDerivedTransformByName.find(pNode->mName.data)->second; - - Matrix3 normalMatrix = aiM.linear().inverse().transpose(); - - // Now we get access to the buffer to fill it. During so we record the bounding box. - float* vdata = static_cast(vbuffer->lock(HardwareBuffer::HBL_DISCARD)); - for (size_t i = 0; i < mesh->mNumVertices; ++i) - { - // Position - Vector3 vect(vec->x, vec->y, vec->z); - vect = aiM * vect; - - /* - if(NULL != mSkeletonRootNode) - { - vect *= mSkeletonRootNode->mTransformation; - } - */ - - *vdata++ = vect.x; - *vdata++ = vect.y; - *vdata++ = vect.z; - mAAB.merge(vect); - vec++; - - // Normal - if (norm) - { - vect = normalMatrix * Vector3(norm->x, norm->y, norm->z); - vect.normalise(); - - *vdata++ = vect.x; - *vdata++ = vect.y; - *vdata++ = vect.z; - norm++; - } - - // uvs - if (uv) - { - *vdata++ = uv->x; - *vdata++ = uv->y; - uv++; - } - - if(tang) - { - *vdata++ = tang->x; - *vdata++ = tang->y; - *vdata++ = tang->z; - tang++; - } - - if (col) - { - PixelUtil::packColour(col->r, col->g, col->b, col->a, PF_BYTE_RGBA, vdata++); - col++; - } - } - - vbuffer->unlock(); - submesh->vertexData->vertexBufferBinding->setBinding(source, vbuffer); - - // set bone weigths - if (mesh->HasBones()) - { - for (uint32 i = 0; i < mesh->mNumBones; i++) - { - aiBone* pAIBone = mesh->mBones[i]; - if (NULL != pAIBone) - { - String bname = pAIBone->mName.data; - for (uint32 weightIdx = 0; weightIdx < pAIBone->mNumWeights; weightIdx++) - { - aiVertexWeight aiWeight = pAIBone->mWeights[weightIdx]; - - VertexBoneAssignment vba; - vba.vertexIndex = aiWeight.mVertexId; - vba.boneIndex = mSkeleton->getBone(bname)->getHandle(); - vba.weight = aiWeight.mWeight; - - submesh->addBoneAssignment(vba); - } - } - } - } // if mesh has bones - - if(mesh->mNumFaces == 0) - return true; - - if (!mQuietMode) - { - LogManager::getSingleton().logMessage(StringConverter::toString(mesh->mNumFaces) + " faces"); - } - - aiFace* faces = mesh->mFaces; - int faceSz = mesh->mPrimitiveTypes == aiPrimitiveType_LINE ? 2 : 3; - - // Creates the index data - submesh->indexData->indexStart = 0; - submesh->indexData->indexCount = mesh->mNumFaces * faceSz; - - if (mesh->mNumVertices >= 65536) // 32 bit index buffer - { - submesh->indexData->indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_32BIT, submesh->indexData->indexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - uint32* indexData = - static_cast(submesh->indexData->indexBuffer->lock(HardwareBuffer::HBL_DISCARD)); - - for (size_t i = 0; i < mesh->mNumFaces; ++i) - { - for(int j = 0; j < faceSz; j++) - *indexData++ = faces->mIndices[j]; - - faces++; - } - } - else // 16 bit index buffer - { - submesh->indexData->indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, submesh->indexData->indexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - uint16* indexData = - static_cast(submesh->indexData->indexBuffer->lock(HardwareBuffer::HBL_DISCARD)); - - for (size_t i = 0; i < mesh->mNumFaces; ++i) - { - for(int j = 0; j < faceSz; j++) - *indexData++ = faces->mIndices[j]; - - faces++; - } - } - - submesh->indexData->indexBuffer->unlock(); - - return true; -} - -void AssimpLoader::loadDataFromNode(const aiScene* mScene, const aiNode* pNode, Mesh* mesh) -{ - if (pNode->mNumMeshes > 0) - { - AxisAlignedBox mAAB = mesh->getBounds(); - - for (unsigned int idx = 0; idx < pNode->mNumMeshes; ++idx) - { - aiMesh* pAIMesh = mScene->mMeshes[pNode->mMeshes[idx]]; - if (!mQuietMode) - { - LogManager::getSingleton().logMessage("SubMesh " + StringConverter::toString(idx) + - " for mesh '" + String(pNode->mName.data) + "'"); - } - - // Create a material instance for the mesh. - const aiMaterial* pAIMaterial = mScene->mMaterials[pAIMesh->mMaterialIndex]; - MaterialPtr matptr = createMaterial(pAIMaterial, mesh->getGroup(), mesh->getName(), mScene, !mQuietMode); - createSubMesh(pNode->mName.data, idx, pNode, pAIMesh, matptr, mesh, mAAB); - } - - // We must indicate the bounding box - mesh->_setBounds(mAAB); - mesh->_setBoundingSphereRadius((mAAB.getMaximum() - mAAB.getMinimum()).length() / 2); - } - - // Traverse all child nodes of the current node instance - for (unsigned int childIdx = 0; childIdx < pNode->mNumChildren; childIdx++) - { - const aiNode* pChildNode = pNode->mChildren[childIdx]; - loadDataFromNode(mScene, pChildNode, mesh); - } -} - -static std::vector > registeredCodecs; -struct AssimpCodec : public Codec -{ - String mType; - - AssimpCodec(const String& type) : mType(type) {} - - String magicNumberToFileExt(const char* magicNumberPtr, size_t maxbytes) const override { return ""; } - String getType() const override { return mType; } - void decode(const DataStreamPtr& input, const Any& output) const override - { - Mesh* dst = any_cast(output); - - AssimpLoader::Options opts; - opts.params = AssimpLoader::LP_QUIET_MODE; - SkeletonPtr skeleton; - AssimpLoader loader; - loader.load(input, dst, skeleton, opts); - } - - static void startup() - { - String version = StringUtil::format("Assimp - %d.%d.%d - Open-Asset-Importer", aiGetVersionMajor(), - aiGetVersionMinor(), aiGetVersionRevision()); - LogManager::getSingleton().logMessage(version); - - String extensions; - Assimp::Importer tmp; - tmp.GetExtensionList(extensions); - - String blacklist[] = {"mesh", "mesh.xml", "raw", "mdc", "bsp"}; - auto stream = LogManager::getSingleton().stream(); - stream << "Supported formats:"; - // Register codecs - for (const auto& dotext : StringUtil::split(extensions, ";")) - { - String ext = dotext.substr(2); - if (std::find(begin(blacklist), std::end(blacklist), ext) != std::end(blacklist)) - continue; - - stream << " " << ext; - Codec* codec = new AssimpCodec(ext); - registeredCodecs.push_back(std::unique_ptr(codec)); - Codec::registerCodec(codec); - } - - stream << "\n"; - } - static void shutdown() - { - for (const auto& c : registeredCodecs) - Codec::unregisterCodec(c.get()); - registeredCodecs.clear(); - } -}; - -const String& AssimpPlugin::getName() const -{ - static String name = "Assimp"; - return name; -} -void AssimpPlugin::install() -{ - AssimpCodec::startup(); -} -void AssimpPlugin::uninstall() -{ - AssimpCodec::shutdown(); -} -#ifndef OGRE_STATIC_LIB -extern "C" void _OgreAssimpExport dllStartPlugin(); -extern "C" void _OgreAssimpExport dllStopPlugin(); - -extern "C" void _OgreAssimpExport dllStartPlugin() -{ - AssimpCodec::startup(); -} -extern "C" void _OgreAssimpExport dllStopPlugin() -{ - AssimpCodec::shutdown(); -} -#endif -} // namespace Ogre diff --git a/PlugIns/BSPSceneManager/CMakeLists.txt b/PlugIns/BSPSceneManager/CMakeLists.txt deleted file mode 100644 index b7487349823..00000000000 --- a/PlugIns/BSPSceneManager/CMakeLists.txt +++ /dev/null @@ -1,30 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure BSP SceneManager build - -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES ${PROJECT_BINARY_DIR}/include/OgreBspPrerequisites.h) -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") - -add_library(Plugin_BSPSceneManager ${OGRE_LIB_TYPE} ${HEADER_FILES} ${SOURCE_FILES}) -target_link_libraries(Plugin_BSPSceneManager OgreMain) -generate_export_header(Plugin_BSPSceneManager - EXPORT_MACRO_NAME _OgreBspPluginExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreBspPrerequisites.h) - -target_include_directories(Plugin_BSPSceneManager PUBLIC - "$" - $) - -ogre_config_framework(Plugin_BSPSceneManager) - -install(FILES ${HEADER_FILES} DESTINATION include/OGRE/Plugins/BSPSceneManager) - -ogre_config_plugin(Plugin_BSPSceneManager) diff --git a/PlugIns/BSPSceneManager/include/OgreBspLevel.h b/PlugIns/BSPSceneManager/include/OgreBspLevel.h deleted file mode 100644 index 46079bcbbbe..00000000000 --- a/PlugIns/BSPSceneManager/include/OgreBspLevel.h +++ /dev/null @@ -1,265 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _BspLevel_H__ -#define _BspLevel_H__ - -#include "OgreBspPrerequisites.h" -#include "OgreResource.h" -#include "OgreStaticFaceGroup.h" -#include "OgreSceneManager.h" -#include "OgreBspNode.h" -#include "OgreHardwareBufferManager.h" -#include "OgreDefaultHardwareBufferManager.h" -#include "OgreQuake3Level.h" - - -namespace Ogre { - /** \addtogroup Plugins Plugins - * @{ - */ - /** \defgroup BSPSceneManager BSPSceneManager - * Binary Space Parition (BSP) based indoor level scene manager - * @{ - */ - - /** Holds all the data associated with a Binary Space Parition - (BSP) based indoor level. - The data used here is populated by loading level files via - the BspLevelManager::load method, although application users - are more likely to call SceneManager::setWorldGeometry which will - automatically arrange the loading of the level. Note that this assumes - that you have asked for an indoor-specialised SceneManager (specify - ST_INDOOR when calling Root::getSceneManager). - Ogre currently only supports loading from Quake3 Arena level files, - although any source that can be converted into this classes structure - could also be used. The Quake3 level load process is in a different - class called Quake3Level to keep the specifics separate. - */ - class BspLevel : public Resource, public Renderable - { - friend class BspSceneManager; - - using Resource::load; - public: - /** Default constructor - used by BspResourceManager (do not call directly) */ - BspLevel(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual = false, ManualResourceLoader* loader = 0); - ~BspLevel(); - - /** Determines if one leaf node is visible from another. */ - bool isLeafVisible(const BspNode* from, const BspNode* to) const; - - /** Returns a pointer to the root node (BspNode) of the BSP tree. */ - const BspNode* getRootNode(void); - - /** Walks the entire BSP tree and returns the leaf - which contains the given point. - */ - BspNode* findLeaf(const Vector3& point) const; - - /** Ensures that the MovableObject is attached to the right leaves of the - BSP tree. - */ - void _notifyObjectMoved(const MovableObject* mov, - const Vector3& pos); - /** Internal method, makes sure an object is removed from the leaves when detached from a node. */ - void _notifyObjectDetached(const MovableObject* mov); - /** Gets a pointer to the start of the leaf nodes. */ - BspNode* getLeafStart(void) {return &mRootNode[mLeafStart]; } - /** Gets the number of leaf nodes */ - int getNumLeaves(void) const { return mNumLeaves; } - - /** Calculate the number of loading stages required for a given level */ - static size_t calculateLoadingStages(const String& levelName); - /** Calculate the number of loading stages required for a given level */ - static size_t calculateLoadingStages(DataStreamPtr& stream); - - /** Load direct from stream */ - void load(const DataStreamPtr& stream); - - /** Is sky enabled? */ - bool isSkyEnabled(void) const; - /** Get Sky material name */ - const String& getSkyMaterialName(void) const; - /** Get sky curvature */ - Real getSkyCurvature(void) const; - - void getRenderOperation(RenderOperation &op) override - { - op = mRenderOp; - } - - void getWorldTransforms(Matrix4* xform) const override - { - *xform = Matrix4::IDENTITY; - } - - Real getSquaredViewDepth(const Camera *cam) const override - { - // always visible - return -1; - } - - const LightList& getLights() const override - { - static LightList lights; - return lights; - } - - const MaterialPtr& getMaterial(void) const override - { - static MaterialPtr nullPtr; - return nullPtr; - } - - /** Utility class just to enable queueing of patches */ - protected: - /** Caches a face group for imminent rendering. */ - uint32 cacheGeometry(uint32* pIndexes, const StaticFaceGroup* faceGroup); - bool cacheGeometry(const std::vector& materialFaceGroup); - - /** @copydoc Resource::loadImpl. */ - void loadImpl(void) override; - /** @copydoc Resource::unloadImpl. */ - void unloadImpl(void) override; - /** @copydoc Resource::calculateSize. */ - size_t calculateSize(void) const override; - /** Pointer to the root node of the BSP tree; - This pointer actually has a dual purpose; to avoid allocating lots of small chunks of - memory, the BspLevel actually allocates all nodes required through this pointer. So this - pointer is the handle for the allocation of memory for all nodes. It also happens to point - to the root node, since the first one in the memory chunk is the root node. - */ - BspNode* mRootNode; - int mNumNodes; - int mNumLeaves; - int mNumBrushes; - int mLeafStart; /// The index at which leaf nodes begin - - /** Vertex format for fixed geometry. - Note that in this case vertex components (position, normal, texture coords etc) - are held interleaved in the same buffer. However, the format here is different from - the format used by Quake because older Direct3d drivers like the vertex elements - to be in a particular order within the buffer. See VertexDeclaration for full - details of this marvellous(not) feature. - */ - struct BspVertex - { - float position[3]; - float normal[3]; - int colour; - float texcoords[2]; - float lightmap[2]; - }; - - /// Vertex data holding all the data for the level, but able to render parts of it - RenderOperation mRenderOp; - - /** Array of indexes into the mFaceGroups array. This buffer is organised - by leaf node so leaves can just use contiguous chunks of it and - get repointed to the actual entries in mFaceGroups. */ - int* mLeafFaceGroups; - int mNumLeafFaceGroups; - - /** Array of face groups, indexed into by contents of mLeafFaceGroups. */ - StaticFaceGroup* mFaceGroups; - int mNumFaceGroups; - - /// Indexes for the whole level, will be copied to the real indexdata per frame - HardwareIndexBufferSharedPtr mIndexes; - - /// Brushes as used for collision, main memory is here - BspNode::Brush *mBrushes; - - /** Vector of player start points */ - std::vector mPlayerStarts; - - /** Internal utility function for loading data from Quake3. */ - void loadQuake3Level(const Quake3Level& q3lvl); - /** Internal lookup table to determine visibility between leaves. - Leaf nodes are assigned to 'clusters' of nodes, which are used to group nodes together for - visibility testing. This data holds a lookup table which is used to determine if one cluster of leaves - is visible from another cluster. Whilst it would be possible to expand all this out so that - each node had a list of pointers to other visible nodes, this would be very expensive in terms - of storage (using the cluster method there is a table which is 1-bit squared per cluster, rounded - up to the nearest byte obviously, which uses far less space than 4-bytes per linked node per source - node). Of course the limitation here is that you have to each leaf in turn to determine if it is visible - rather than just following a list, but since this is only done once per frame this is not such a big - overhead. - Each row in the table is a 'from' cluster, with each bit in the row corresponding to a 'to' cluster, - both ordered based on cluster index. A 0 in the bit indicates the 'to' cluster is not visible from the - 'from' cluster, whilst a 1 indicates it is. - As many will notice, this is lifted directly from the Quake implementation of PVS. - */ - struct VisData - { - unsigned char *tableData; - int numClusters; /// Number of clusters, therefore number of rows - int rowLength; /// Length in bytes of each row (num clusters / 8 rounded up) - }; - - VisData mVisData; - - - /** Internal method for parsing chosen entities. */ - void loadEntities(const Quake3Level& q3lvl); - - typedef std::map > MovableToNodeMap; - /// Map for locating the nodes a movable is currently a member of - MovableToNodeMap mMovableToNodeMap; - - void tagNodesWithMovable(BspNode* node, const MovableObject* mov, const Vector3& pos); - - /// Storage of patches - typedef std::map PatchMap; - PatchMap mPatches; - /// Total number of vertices required for all patches - size_t mPatchVertexCount; - /// Total number of indexes required for all patches - size_t mPatchIndexCount; - /// Sky enabled? - bool mSkyEnabled; - /// Sky material - String mSkyMaterial; - /// Sky details - Real mSkyCurvature; - - - void initQuake3Patches(const Quake3Level & q3lvl, VertexDeclaration* decl); - void buildQuake3Patches(size_t vertOffset, size_t indexOffset); - - void quakeVertexToBspVertex(const bsp_vertex_t* src, BspVertex* dest); - - - }; - typedef SharedPtr BspLevelPtr; - /** @} */ - /** @} */ -} - -#endif diff --git a/PlugIns/BSPSceneManager/include/OgreBspNode.h b/PlugIns/BSPSceneManager/include/OgreBspNode.h deleted file mode 100644 index e1ed0d2a3a4..00000000000 --- a/PlugIns/BSPSceneManager/include/OgreBspNode.h +++ /dev/null @@ -1,266 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _BspNode_H__ -#define _BspNode_H__ - -#include "OgreBspPrerequisites.h" -#include "OgrePlane.h" -#include "OgreAxisAlignedBox.h" -#include "OgreSceneQuery.h" - -namespace Ogre { - class BspLevel; - - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup BSPSceneManager - * @{ - */ - - /** This type can be used by collaborating applications & SceneManagers to - agree on the type of world geometry to be returned from queries. Not all - these types will be supported by all SceneManagers; once the application - has decided which SceneManager specialisation to use, it is expected that - it will know which type of world geometry abstraction is available to it. - */ - enum WorldFragmentType { - /// Return no world geometry hits at all - WFT_NONE, - /// Return pointers to convex plane-bounded regions - WFT_PLANE_BOUNDED_REGION, - /// Return a single intersection point (typically RaySceneQuery only) - WFT_SINGLE_INTERSECTION, - /// Custom geometry as defined by the SceneManager - WFT_CUSTOM_GEOMETRY, - /// General RenderOperation structure - WFT_RENDER_OPERATION - }; - - /** Represents part of the world geometry that is a result of a SceneQuery. - - Since world geometry is normally vast and sprawling, we need a way of - retrieving parts of it based on a query. That is what this struct is for; - note there are potentially as many data structures for world geometry as there - are SceneManagers, however this structure includes a few common abstractions as - well as a more general format. - @par - The type of world fragment that is returned from a query depends on the - SceneManager, and the option set using SceneQuery::setWorldFragmentType. - You can see what fragment types are supported on the query in question by - calling SceneQuery::getSupportedWorldFragmentTypes(). - */ - struct WorldFragment { - /// The type of this world fragment - WorldFragmentType fragmentType; - /// Single intersection point, only applicable for WFT_SINGLE_INTERSECTION - Vector3 singleIntersection; - /// Planes bounding a convex region, only applicable for WFT_PLANE_BOUNDED_REGION - std::vector* planes; - /// Custom geometry block, only applicable for WFT_CUSTOM_GEOMETRY - void* geometry; - /// General render operation structure, fallback if nothing else is available - RenderOperation* renderOp; - }; - - /** Encapsulates a node in a BSP tree. - A BSP tree represents space partitioned by planes . The space which is - partitioned is either the world (in the case of the root node) or the space derived - from their parent node. Each node can have elements which are in front or behind it, which are - it's children and these elements can either be further subdivided by planes, - or they can be undivided spaces or 'leaf nodes' - these are the nodes which actually contain - objects and world geometry.The leaves of the tree are the stopping point of any tree walking algorithm, - both for rendering and collision detection etc. - Ogre chooses not to represent splitting nodes and leaves as separate structures, but to merge the two for simplicity - of the walking algorithm. If a node is a leaf, the isLeaf() method returns true and both getFront() and - getBack() return null pointers. If the node is a partitioning plane isLeaf() returns false and getFront() - and getBack() will return the corresponding BspNode objects. - */ - class BspNode : public NodeAlloc - { - friend class BspLevel; - - public: - /** Constructor, only to be used by BspLevel. */ - BspNode(BspLevel* owner, bool isLeaf); - - BspNode(); - ~BspNode(); - - /** Returns true if this node is a leaf (i.e. contains geometry) or false if it is a splitting plane. - A BspNode can either be a splitting plane (the typical representation of a BSP node) or an undivided - region contining geometry (a leaf node). Ogre represents both using the same class for simplicity - of tree walking. However it is important that you use this method to determine which type you are dealing - with, since certain methods are only supported with one of the subtypes. Details are given in the individual methods. - Note that I could have represented splitting / leaf nodes as a class hierarchy but the - virtual methods / run-time type identification would have a performance hit, and it would not make the - code much (any?) simpler anyway. I think this is a fair trade-off in this case. - */ - bool isLeaf(void) const; - - /** Returns a pointer to a BspNode containing the subspace on the positive side of the splitting plane. - This method should only be called on a splitting node, i.e. where isLeaf() returns false. Calling this - method on a leaf node will throw an exception. - */ - BspNode* getFront(void) const; - - /** Returns a pointer to a BspNode containing the subspace on the negative side of the splitting plane. - This method should only be called on a splitting node, i.e. where isLeaf() returns false. Calling this - method on a leaf node will throw an exception. - */ - BspNode* getBack(void) const; - - /** Determines which side of the splitting plane a worldspace point is. - This method should only be called on a splitting node, i.e. where isLeaf() returns false. Calling this - method on a leaf node will throw an exception. - */ - Plane::Side getSide (const Vector3& point) const; - - /** Gets the next node down in the tree, with the intention of - locating the leaf containing the given point. - This method should only be called on a splitting node, i.e. where isLeaf() returns false. Calling this - method on a leaf node will throw an exception. - */ - BspNode* getNextNode(const Vector3& point) const; - - - /** Returns details of the plane which is used to subdivide the space of his node's children. - This method should only be called on a splitting node, i.e. where isLeaf() returns false. Calling this - method on a leaf node will throw an exception. - */ - const Plane& getSplitPlane(void) const; - - /** Returns the axis-aligned box which contains this node if it is a leaf. - This method should only be called on a leaf node. It returns a box which can be used in calls like - Camera::isVisible to determine if the leaf node is visible in the view. - */ - const AxisAlignedBox& getBoundingBox(void) const; - - /** Returns the number of faces contained in this leaf node. - Should only be called on a leaf node. - */ - int getNumFaceGroups(void) const; - /** Returns the index to the face group index list for this leaf node. - The contents of this buffer is a list of indexes which point to the - actual face groups held in a central buffer in the BspLevel class (in - actual fact for efficiency the indexes themselves are also held in a single - buffer in BspLevel too). The reason for this indirection is that the buffer - of indexes to face groups is organised in chunks relative to nodes, whilst the - main buffer of face groups may not be. - Should only be called on a leaf node. - */ - int getFaceGroupStart(void) const; - - /** Determines if the passed in node (must also be a leaf) is visible from this leaf. - Must only be called on a leaf node, and the parameter must also be a leaf node. If - this method returns true, then the leaf passed in is visible from this leaf. - Note that internally this uses the Potentially Visible Set (PVS) which is precalculated - and stored with the BSP level. - */ - bool isLeafVisible(const BspNode* leaf) const; - - friend std::ostream& operator<< (std::ostream& o, BspNode& n); - - /// Internal method for telling the node that a movable intersects it - void _addMovable(const MovableObject* mov); - - /// Internal method for telling the node that a movable no longer intersects it - void _removeMovable(const MovableObject* mov); - - /// Gets the signed distance to the dividing plane - Real getDistance(const Vector3& pos) const; - - typedef std::set IntersectingObjectSet; - - struct Brush - { - std::vector planes; - SceneQuery::WorldFragment fragment; /// For query reporting - }; - typedef std::vector NodeBrushList; /// Main brush memory held on level - - /** Get the list of solid Brushes for this node. - @remarks Only applicable for leaf nodes. - */ - const NodeBrushList& getSolidBrushes(void) const; - protected: - BspLevel* mOwner; /// Back-reference to containing level - bool mIsLeaf; - - // Node-only members - /** The plane which splits space in a non-leaf node. - Note that nodes do not allocate the memory for other nodes - for simplicity and bulk-allocation - of memory the BspLevel is responsible for assigning enough memory for all nodes in one go. - */ - Plane mSplitPlane; - /** Pointer to the node in front of this non-leaf node. */ - BspNode* mFront; - /** Pointer to the node behind this non-leaf node. */ - BspNode* mBack; - - // Leaf-only members - /** The cluster number of this leaf. - Leaf nodes are assigned to 'clusters' of nodes, which are used to group nodes together for - visibility testing. There is a lookup table which is used to determine if one cluster of leaves - is visible from another cluster. Whilst it would be possible to expand all this out so that - each node had a list of pointers to other visible nodes, this would be very expensive in terms - of storage (using the cluster method there is a table which is 1-bit squared per cluster, rounded - up to the nearest byte obviously, which uses far less space than 4-bytes per linked node per source - node). Of course the limitation here is that you have to each leaf in turn to determine if it is visible - rather than just following a list, but since this is only done once per frame this is not such a big - overhead. - */ - int mVisCluster; - - /** The axis-aligned box which bounds node if it is a leaf. */ - AxisAlignedBox mBounds; - /** Number of face groups in this node if it is a leaf. */ - int mNumFaceGroups; - /** Index to the part of the main leaf facegroup index buffer(held in BspLevel) for this leaf. - This leaf uses mNumFaceGroups from this pointer onwards. From here you use the index - in this buffer to look up the actual face. - Note that again for simplicity and bulk memory allocation the face - group list itself is allocated by the BspLevel for all nodes, and each leaf node is given a section of it to - work on. This saves lots of small memory allocations / deallocations which limits memory fragmentation. - */ - int mFaceGroupStart; - - IntersectingObjectSet mMovables; - - NodeBrushList mSolidBrushes; - public: - const IntersectingObjectSet& getObjects(void) const { return mMovables; } - - - }; - /** @} */ - /** @} */ - -} - -#endif diff --git a/PlugIns/BSPSceneManager/include/OgreBspSceneManager.h b/PlugIns/BSPSceneManager/include/OgreBspSceneManager.h deleted file mode 100644 index ab14b0779ef..00000000000 --- a/PlugIns/BSPSceneManager/include/OgreBspSceneManager.h +++ /dev/null @@ -1,342 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __BspSceneManager_H__ -#define __BspSceneManager_H__ - - -#include "OgreBspPrerequisites.h" -#include "OgreSceneManager.h" -#include "OgreStaticFaceGroup.h" -#include "OgreRenderOperation.h" -#include "OgreBspLevel.h" -#include - - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup BSPSceneManager - * @{ - */ - - /** Specialisation of the SceneManager class to deal with indoor scenes - based on a BSP tree. - This class refines the behaviour of the default SceneManager to manage - a scene whose bulk of geometry is made up of an indoor environment which - is organised by a Binary Space Partition (BSP) tree. - A BSP tree progressively subdivides the space using planes which are the nodes of the tree. - At some point we stop subdividing and everything in the remaining space is part of a 'leaf' which - contains a number of polygons. Typically we traverse the tree to locate the leaf in which a - point in space is (say the camera origin) and work from there. A second structure, the - Potentially Visible Set, tells us which other leaves can been seen from this - leaf, and we test their bounding boxes against the camera frustum to see which - we need to draw. Leaves are also a good place to start for collision detection since - they divide the level into discrete areas for testing. - This BSP and PVS technique has been made famous by engines such as Quake and Unreal. Ogre - provides support for loading Quake3 level files to populate your world through this class, - by calling the BspSceneManager::setWorldGeometry. Note that this interface is made - available at the top level of the SceneManager class so you don't have to write your code - specifically for this class - just call Root::getSceneManager passing a SceneType of ST_INTERIOR - and in the current implementation you will get a BspSceneManager silently disguised as a - standard SceneManager. - */ - class BspSceneManager : public SceneManager - { - /** Comparator for material map, for sorting materials into render order (e.g. transparent last). - */ - struct materialLess - { - bool operator()(const Material* x, const Material* y) const - { - // If x transparent and y not, x > y (since x has to overlap y) - if (x->isTransparent() && !y->isTransparent()) - { - return false; - } - // If y is transparent and x not, x < y - else if (!x->isTransparent() && y->isTransparent()) - { - return true; - } - else - { - // Otherwise don't care (both transparent or both solid) - // Just arbitrarily use pointer - return x < y; - } - } - }; - - /// World geometry - BspLevelPtr mLevel; - - // State variables for rendering WIP - // Set of face groups (by index) already included - typedef std::set FaceGroupSet; - FaceGroupSet mFaceGroupSet; - // Material -> face group hashmap - typedef std::map, materialLess > MaterialFaceGroupMap; - MaterialFaceGroupMap mMatFaceGroupMap; - - // Debugging features - bool mShowNodeAABs; - RenderOperation mAABGeometry; - - /** Walks the BSP tree looking for the node which the camera - is in, and tags any geometry which is in a visible leaf for - later processing. - @param camera Pointer to the viewpoint. - @return The BSP node the camera was found in, for info. - */ - BspNode* walkTree(Camera* camera, VisibleObjectsBoundsInfo* visibleBounds, bool onlyShadowCasters); - /** Tags geometry in the leaf specified for later rendering. */ - void processVisibleLeaf(BspNode* leaf, Camera* cam, - VisibleObjectsBoundsInfo* visibleBounds, bool onlyShadowCasters); - - /** Adds a bounding box to draw if turned on. */ - void addBoundingBox(const AxisAlignedBox& aab, bool visible); - - /** Renders the static level geometry tagged in walkTree. */ - void renderStaticGeometry(void); - - /** @copydoc SceneManager::clearScene */ - void clearScene(void) override; - - // Overridden so we can manually render world geometry - bool fireRenderQueueEnded(uint8 id, const String& invocation) override; - - typedef std::set MovablesForRendering; - MovablesForRendering mMovablesForRendering; - - public: - BspSceneManager(const String& name); - ~BspSceneManager(); - - - /// @copydoc SceneManager::getTypeName - const String& getTypeName(void) const override; - - /** Specialised from SceneManager to support Quake3 bsp files. */ - void setWorldGeometry(const String& filename) override; - - /** Specialised from SceneManager to support Quake3 bsp files. */ - size_t estimateWorldGeometry(const String& filename) override; - - /** Specialised from SceneManager to support Quake3 bsp files. */ - void setWorldGeometry(DataStreamPtr& stream, - const String& typeName = BLANKSTRING) override; - - /** Specialised from SceneManager to support Quake3 bsp files. */ - size_t estimateWorldGeometry(DataStreamPtr& stream, - const String& typeName = BLANKSTRING) override; - - /** Tells the manager whether to draw the axis-aligned boxes that surround - nodes in the Bsp tree. For debugging purposes. - */ - void showNodeBoxes(bool show); - - /** Specialised to suggest viewpoints. */ - ViewPoint getSuggestedViewpoint(bool random = false) override; - - const BspLevelPtr& getLevel(void) {return mLevel; } - - void setLevel(const BspLevelPtr& level); - - /** Overridden from SceneManager. */ - void _findVisibleObjects(Camera* cam, VisibleObjectsBoundsInfo* visibleBounds, - bool onlyShadowCasters) override; - - /** Creates a specialized BspSceneNode */ - SceneNode * createSceneNodeImpl ( void ) override; - /** Creates a specialized BspSceneNode */ - SceneNode * createSceneNodeImpl ( const String &name ) override; - - /** Internal method for tagging BspNodes with objects which intersect them. */ - void _notifyObjectMoved(const MovableObject* mov, const Vector3& pos); - /** Internal method for notifying the level that an object has been detached from a node */ - void _notifyObjectDetached(const MovableObject* mov); - - /* Creates an AxisAlignedBoxSceneQuery for this scene manager. - - This method creates a new instance of a query object for this scene manager, - for an axis aligned box region. See SceneQuery and AxisAlignedBoxSceneQuery - for full details. - @par - The instance returned from this method must be destroyed by calling - SceneManager::destroyQuery when it is no longer required. - @param box Details of the box which describes the region for this query. - @param mask The query mask to apply to this query; can be used to filter out - certain objects; see SceneQuery for details. - */ - /* - virtual AxisAlignedBoxSceneQuery* - createAABBQuery(const AxisAlignedBox& box, uint32 mask = 0xFFFFFFFF); - */ - /* Creates a SphereSceneQuery for this scene manager. - - This method creates a new instance of a query object for this scene manager, - for a spherical region. See SceneQuery and SphereSceneQuery - for full details. - @par - The instance returned from this method must be destroyed by calling - SceneManager::destroyQuery when it is no longer required. - @param sphere Details of the sphere which describes the region for this query. - @param mask The query mask to apply to this query; can be used to filter out - certain objects; see SceneQuery for details. - */ - /* - virtual SphereSceneQuery* - createSphereQuery(const Sphere& sphere, uint32 mask = 0xFFFFFFFF); - */ - /** Creates a RaySceneQuery for this scene manager. - - This method creates a new instance of a query object for this scene manager, - looking for objects which fall along a ray. See SceneQuery and RaySceneQuery - for full details. - @par - The instance returned from this method must be destroyed by calling - SceneManager::destroyQuery when it is no longer required. - @param ray Details of the ray which describes the region for this query. - @param mask The query mask to apply to this query; can be used to filter out - certain objects; see SceneQuery for details. - */ - RaySceneQuery* - createRayQuery(const Ray& ray, uint32 mask = 0xFFFFFFFF) override; - /** Creates an IntersectionSceneQuery for this scene manager. - - This method creates a new instance of a query object for locating - intersecting objects. See SceneQuery and IntersectionSceneQuery - for full details. - @par - The instance returned from this method must be destroyed by calling - SceneManager::destroyQuery when it is no longer required. - @param mask The query mask to apply to this query; can be used to filter out - certain objects; see SceneQuery for details. - */ - IntersectionSceneQuery* - createIntersectionQuery(uint32 mask = 0xFFFFFFFF) override; - - }; - - /** BSP specialisation of IntersectionSceneQuery */ - class BspIntersectionSceneQuery : public DefaultIntersectionSceneQuery - { - std::set mSupportedWorldFragments; - WorldFragmentType mWorldFragmentType; - public: - BspIntersectionSceneQuery(SceneManager* creator); - - /** See IntersectionSceneQuery. */ - void execute(IntersectionSceneQueryListener* listener) override; - - /** Tells the query what kind of world geometry to return from queries; - often the full renderable geometry is not what is needed. - - The application receiving the world geometry is expected to know - what to do with it; inevitably this means that the application must - have knowledge of at least some of the structures - used by the custom SceneManager. - @par - The default setting is WFT_NONE. - */ - void setWorldFragmentType(enum WorldFragmentType wft) - { - // Check supported - OgreAssert(mSupportedWorldFragments.find(wft) != mSupportedWorldFragments.end(), - "This world fragment type is not supported."); - mWorldFragmentType = wft; - } - - /** Gets the current world fragment types to be returned from the query. */ - WorldFragmentType getWorldFragmentType(void) const { return mWorldFragmentType; } - - /** Returns the types of world fragments this query supports. */ - const std::set* getSupportedWorldFragmentTypes() const { return &mSupportedWorldFragments; } - }; - - /** BSP specialisation of RaySceneQuery */ - class BspRaySceneQuery : public DefaultRaySceneQuery - { - std::set mSupportedWorldFragments; - WorldFragmentType mWorldFragmentType; - public: - BspRaySceneQuery(SceneManager* creator); - ~BspRaySceneQuery(); - - /// @copydoc BspIntersectionSceneQuery::setWorldFragmentType - void setWorldFragmentType(enum WorldFragmentType wft) - { - // Check supported - OgreAssert(mSupportedWorldFragments.find(wft) != mSupportedWorldFragments.end(), - "This world fragment type is not supported."); - mWorldFragmentType = wft; - } - - /// @copydoc BspIntersectionSceneQuery::getWorldFragmentType - WorldFragmentType getWorldFragmentType(void) const { return mWorldFragmentType; } - - /// @copydoc BspIntersectionSceneQuery::getSupportedWorldFragmentTypes - const std::set* getSupportedWorldFragmentTypes() const { return &mSupportedWorldFragments; } - - /** See RaySceneQuery. */ - void execute(RaySceneQueryListener* listener) override; - protected: - /// Set for eliminating duplicates since objects can be in > 1 node - std::set mObjsThisQuery; - /// list of the last single intersection world fragments (derived) - std::vector mSingleIntersections; - - void clearTemporaries(void); - /** Internal processing of a single node. - @return true if we should continue tracing, false otherwise - */ - bool processNode(const BspNode* node, const Ray& tracingRay, RaySceneQueryListener* listener, - Real maxDistance = Math::POS_INFINITY, Real traceDistance = 0.0f); - /** Internal processing of a single leaf. - @return true if we should continue tracing, false otherwise - */ - bool processLeaf(const BspNode* node, const Ray& tracingRay, RaySceneQueryListener* listener, - Real maxDistance = Math::POS_INFINITY, Real traceDistance = 0.0f); - - }; - - /// Factory for BspSceneManager - class BspSceneManagerFactory : public SceneManagerFactory - { - public: - /// Factory type name - static const String FACTORY_TYPE_NAME; - SceneManager* createInstance(const String& instanceName) override; - const String& getTypeName(void) const override { return FACTORY_TYPE_NAME; } - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/PlugIns/BSPSceneManager/include/OgreBspSceneManagerPlugin.h b/PlugIns/BSPSceneManager/include/OgreBspSceneManagerPlugin.h deleted file mode 100644 index 264a8091ae1..00000000000 --- a/PlugIns/BSPSceneManager/include/OgreBspSceneManagerPlugin.h +++ /dev/null @@ -1,67 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __BspSceneManagerPlugin_H__ -#define __BspSceneManagerPlugin_H__ - -#include "OgrePlugin.h" -#include "OgreBspSceneManager.h" - -namespace Ogre -{ - class Quake3ShaderManager; - - /** Plugin instance for BSPSceneManager */ - class _OgreBspPluginExport BspSceneManagerPlugin : public Plugin - { - public: - BspSceneManagerPlugin(); - ~BspSceneManagerPlugin(); - - - /// @copydoc Plugin::getName - const String& getName() const override; - - /// @copydoc Plugin::install - void install() override; - - /// @copydoc Plugin::initialise - void initialise() override; - - /// @copydoc Plugin::shutdown - void shutdown() override; - - /// @copydoc Plugin::uninstall - void uninstall() override; - protected: - BspSceneManagerFactory* mBspFactory; - Quake3ShaderManager* mShaderMgr; - std::unique_ptr mCodec; - }; -} - -#endif diff --git a/PlugIns/BSPSceneManager/include/OgreBspSceneNode.h b/PlugIns/BSPSceneManager/include/OgreBspSceneNode.h deleted file mode 100644 index d030bd2656b..00000000000 --- a/PlugIns/BSPSceneManager/include/OgreBspSceneNode.h +++ /dev/null @@ -1,84 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __BSPSCENENODE_H__ -#define __BSPSCENENODE_H__ - -#include "OgreBspPrerequisites.h" -#include "OgreSceneNode.h" - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup BSPSceneManager - * @{ - */ - /** Specialisation of SceneNode for the BspSceneManager. - - This specialisation of SceneNode is to enable information about the - leaf node in which any attached objects are held is stored for - use in the visibility determination. - @par - Do not confuse this class with BspNode, which reflects nodes in the - BSP tree itself. This class is just like a regular SceneNode, except that - it should be locating BspNode leaf elements which objects should be included - in. Note that because objects are movable, and thus may very well be overlapping - the boundaries of more than one leaf, that it is possible that an object attached - to one BspSceneNode may actually be associated with more than one BspNode. - */ - class BspSceneNode : public SceneNode - { - protected: - void setInSceneGraph(bool inGraph) override; - public: - BspSceneNode(SceneManager* creator) : SceneNode(creator) {} - BspSceneNode(SceneManager* creator, const String& name) - : SceneNode(creator, name) {} - /// Overridden from Node - void _update(bool updateChildren, bool parentHasChanged) override; - /** Detaches the indexed object from this scene node. - - Detaches by index, see the alternate version to detach by name. Object indexes - may change as other objects are added / removed. - */ - MovableObject* detachObject(unsigned short index) override; - - /** Detaches the named object from this node and returns a pointer to it. */ - MovableObject* detachObject(const String& name) override; - - /** Detaches all objects attached to this node. - */ - void detachAllObjects(void) override; - - - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/PlugIns/BSPSceneManager/include/OgreQuake3Level.h b/PlugIns/BSPSceneManager/include/OgreQuake3Level.h deleted file mode 100644 index 84015b700b0..00000000000 --- a/PlugIns/BSPSceneManager/include/OgreQuake3Level.h +++ /dev/null @@ -1,174 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __Quake3Level_H__ -#define __Quake3Level_H__ - -#include "OgreBspPrerequisites.h" -#include "OgreQuake3Types.h" -#include "OgreDataStream.h" - - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup BSPSceneManager - * @{ - */ - /** Support for loading and extracting data from a Quake3 level file. - This class implements the required methods for opening Quake3 level files - and extracting the pertinent data within. Ogre supports BSP based levels - through it's own BspLevel class, which is not specific to any file format, - so this class is here to source that data from the Quake3 format. - Quake3 levels include far more than just data for rendering - typically the - leaves of the tree are used for rendering, and brushes, - are used to define convex hulls made of planes for collision detection. There are also - entities which define non-visual elements like player start - points, triggers etc and models which are used for movable - scenery like doors and platforms. Shaders meanwhile are textures - with extra effects and 'content flags' indicating special properties like - water or lava. - I will try to support as much of this as I can in Ogre, but I won't duplicate - the structure or necessarily use the same terminology. Quake3 is designed for a very specific - purpose and code structure, whereas Ogre is designed to be more flexible, - so for example I'm likely to separate game-related properties like surface flags - from the generics of materials in my implementation. - This is a utility class only - a single call to loadFromChunk should be - enough. You should not expect the state of this object to be consistent - between calls, since it uses pointers to memory which may no longer - be valid after the original call. This is why it has no accessor methods - for reading it's internal state. - */ - class Quake3Level : public ResourceAlloc - { - public: - Quake3Level(); - - /** Load just the header information from a Quake3 file. - - This method loads just the header information from the - Quake3 file, in order to estimate the loading time. - */ - void loadHeaderFromStream(DataStreamPtr& inStream); - - /** Reads Quake3 bsp data from a stream as read from the file. - Since ResourceManagers generally locate data in a variety of - places they typically manipulate them as a chunk of data, rather than - a file pointer since this is unsupported through compressed archives. - Quake3 files are made up of a header (which contains version info and - a table of the contents) and 17 'lumps' i.e. sections of data, - the offsets to which are kept in the table of contents. The 17 types - are predefined (You can find them in OgreQuake3Types.h) - - @param inStream Stream containing Quake3 data - */ - void loadFromStream(const DataStreamPtr& inStream); - - /* Extracts the embedded lightmap texture data and loads them as textures. - Calling this method makes the lightmap texture data embedded in - the .bsp file available to the renderer. Lightmaps are extracted - and loaded as Texture objects (subclass specific to RenderSystem - subclass) and are named "@lightmap1", "@lightmap2" etc. - */ - void extractLightmaps(void) const; - - /** Utility function read the header and set up pointers. */ - void initialise(bool headerOnly = false); - /** Utility function read the header and set up counters. */ - void initialiseCounts(void); - /** Utility function read the header and set up pointers. */ - void initialisePointers(void); - - /** Utility function to return a pointer to a lump. */ - void* getLump(int lumpType); - int getLumpSize(int lumpType); - - /** Debug method. */ - void dumpContents(void); - - // Internal storage - // This is ALL temporary. Don't rely on it being static - MemoryDataStreamPtr mChunk; - - // NB no brushes, fog or local lightvolumes yet - bsp_header_t* mHeader; - unsigned char* mLumpStart; - - int* mElements; // vertex indexes for faces - int mNumElements; - - void* mEntities; - int mNumEntities; - - bsp_model_t* mModels; - int mNumModels; - - bsp_node_t* mNodes; - int mNumNodes; - - bsp_leaf_t* mLeaves; - int mNumLeaves; - - int* mLeafFaces; // Indexes to face groups by leaf - int mNumLeafFaces; - - bsp_plane_t* mPlanes; - int mNumPlanes; - - bsp_face_t* mFaces; // Groups of faces - int mNumFaces; - - bsp_vertex_t* mVertices; - int mNumVertices; - - bsp_shader_t* mShaders; - int mNumShaders; - - unsigned char* mLightmaps; - int mNumLightmaps; - - bsp_vis_t* mVis; - - bsp_brush_t* mBrushes; - int mNumBrushes; - - bsp_brushside_t* mBrushSides; - int mNumBrushSides; - - int* mLeafBrushes; // Groups of indexes to brushes by leaf - int mNumLeafBrushes; - - - - }; - /** @} */ - /** @} */ -} - - -#endif diff --git a/PlugIns/BSPSceneManager/include/OgreQuake3Shader.h b/PlugIns/BSPSceneManager/include/OgreQuake3Shader.h deleted file mode 100644 index c7ceb8cb876..00000000000 --- a/PlugIns/BSPSceneManager/include/OgreQuake3Shader.h +++ /dev/null @@ -1,126 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __QUAKE3SHADER_H__ -#define __QUAKE3SHADER_H__ - -#include "OgreResource.h" -#include "OgreBspPrerequisites.h" -#include "OgreQuake3Types.h" -#include "OgreCommon.h" -#include "OgreColourValue.h" -#include "OgreBlendMode.h" -#include "OgreTextureUnitState.h" - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup BSPSceneManager - * @{ - */ - - /** Class for recording Quake3 shaders. - This is a temporary holding area since shaders are actually converted into - Material objects for use in the engine proper. However, because we have to read - in shader definitions en masse (because they are stored in shared .shader files) - without knowing which will actually be used, we store their definitions here - temporarily since their instantiations as Materials would use precious resources - because of the automatic loading of textures etc. - */ - class Quake3Shader : public ResourceAlloc - { - protected: - String getAlternateName(const String& texName); - String mName; - - public: - - /** Default constructor - used by Quake3ShaderManager (do not call directly) */ - Quake3Shader(const String& name); - ~Quake3Shader(); - - /** Creates this shader as an OGRE material. - Creates a new material based on this shaders settings. - Material name shader#lightmap. - */ - MaterialPtr createAsMaterial(int lightmapNumber); - - struct Pass { - unsigned int flags; - String textureName; - TexGen texGen; - // Multitexture blend - LayerBlendOperation blend; - // Multipass blends (Quake3 only supports multipass?? Surely not?) - SceneBlendFactor blendSrc; - SceneBlendFactor blendDest; - bool customBlend; - CompareFunction depthFunc; - TextureAddressingMode addressMode; - // TODO - alphaFunc - GenFunc rgbGenFunc; - WaveType rgbGenWave; - Real rgbGenParams[4]; // base, amplitude, phase, frequency - Real tcModScale[2]; - Real tcModRotate; - Real tcModScroll[2]; - Real tcModTransform[6]; - bool tcModTurbOn; - Real tcModTurb[4]; - WaveType tcModStretchWave; - Real tcModStretchParams[4]; // base, amplitude, phase, frequency - CompareFunction alphaFunc; - unsigned char alphaVal; - - Real animFps; - unsigned int animNumFrames; - String frames[32]; - }; - - unsigned int flags; - int numPasses; - typedef std::vector PassList; - PassList pass; - bool farbox; // Skybox - String farboxName; - bool skyDome; - Real cloudHeight; // Skydome - DeformFunc deformFunc; - Real deformParams[5]; - ManualCullingMode cullMode; - - bool fog; - ColourValue fogColour; - Real fogDistance; - - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/PlugIns/BSPSceneManager/include/OgreQuake3ShaderManager.h b/PlugIns/BSPSceneManager/include/OgreQuake3ShaderManager.h deleted file mode 100644 index 5d8e7b81114..00000000000 --- a/PlugIns/BSPSceneManager/include/OgreQuake3ShaderManager.h +++ /dev/null @@ -1,103 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __QUAKE3SHADERMANAGER_H__ -#define __QUAKE3SHADERMANAGER_H__ - -#include "OgreBspPrerequisites.h" -#include "OgreSingleton.h" -#include "OgreResourceManager.h" -#include "OgreQuake3Shader.h" -#include "OgreBlendMode.h" - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup BSPSceneManager - * @{ - */ - - /** Class for managing Quake3 custom shaders. - Quake3 uses .shader files to define custom shaders, or Materials in Ogre-speak. - When a surface texture is mentioned in a level file, it includes no file extension - meaning that it can either be a standard texture image (+lightmap) if there is only a .jpg or .tga - file, or it may refer to a custom shader if a shader with that name is included in one of the .shader - files in the scripts/ folder. Because there are multiple shaders per file you have to parse all the - .shader files available to know if there is a custom shader available. This class is designed to parse - all the .shader files available and save their settings for future use. - I choose not to set up Material instances for shaders found since they may or may not be used by a level, - so it would be very wasteful to set up Materials since they load texture images for each layer (apart from the - lightmap). Once the usage of a shader is confirmed, a full Material instance can be set up from it. - Because this is a subclass of ScriptLoader, any files mentioned will be searched for in any path or - archive added to the ResourceGroupManager::WORLD_GROUP_NAME group. See ResourceGroupManager for details. - */ - class Quake3ShaderManager : public ScriptLoader, public Singleton, public ResourceAlloc - { - protected: - void parseNewShaderPass(DataStreamPtr& stream, Quake3Shader* pShader); - void parseShaderAttrib( const String& line, Quake3Shader* pShader); - void parseShaderPassAttrib( const String& line, Quake3Shader* pShader, Quake3Shader::Pass* pPass); - SceneBlendFactor convertBlendFunc( const String& q3func); - - typedef std::map Quake3ShaderMap; - Quake3ShaderMap mShaderMap; - StringVector mScriptPatterns; - - - public: - Quake3ShaderManager(); - virtual ~Quake3ShaderManager(); - - /** @copydoc ScriptLoader::getScriptPatterns */ - const StringVector& getScriptPatterns(void) const override; - - /** @copydoc ScriptLoader::parseScript */ - void parseScript(DataStreamPtr& stream, const String& groupName) override; - - /** @copydoc ScriptLoader::getLoadingOrder */ - Real getLoadingOrder(void) const override; - - /** Create implementation. */ - Quake3Shader* create(const String& name); - /** Clear all the current shaders */ - void clear(void); - /** Retrieve a Quake3Shader by name */ - Quake3Shader* getByName(const String& name); - - /// @copydoc Singleton::getSingleton() - static Quake3ShaderManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static Quake3ShaderManager* getSingletonPtr(void); - - - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/PlugIns/BSPSceneManager/include/OgreQuake3Types.h b/PlugIns/BSPSceneManager/include/OgreQuake3Types.h deleted file mode 100644 index 2e4b7c00883..00000000000 --- a/PlugIns/BSPSceneManager/include/OgreQuake3Types.h +++ /dev/null @@ -1,250 +0,0 @@ -// Quake 3 data definitions -// Copyright (C) 1999-2000 Id Software, Inc. -// -// This file must be identical in the quake and utils directories - -// contents flags are separate bits -// a given brush can contribute multiple content bits - -// these definitions also need to be in q_shared.h! -#ifndef __Quake3Types_H__ -#define __Quake3Types_H__ - - -#define BSP_HEADER_ID (*(int*)"IBSP") -#define BSP_HEADER_VER (46) - -#define BSP_ENTITIES_LUMP (0) -#define BSP_SHADERS_LUMP (1) -#define BSP_PLANES_LUMP (2) -#define BSP_NODES_LUMP (3) -#define BSP_LEAVES_LUMP (4) -#define BSP_LFACES_LUMP (5) -#define BSP_LBRUSHES_LUMP (6) -#define BSP_MODELS_LUMP (7) -#define BSP_BRUSH_LUMP (8) -#define BSP_BRUSHSIDES_LUMP (9) -#define BSP_VERTICES_LUMP (10) -#define BSP_ELEMENTS_LUMP (11) -#define BSP_FOG_LUMP (12) -#define BSP_FACES_LUMP (13) -#define BSP_LIGHTMAPS_LUMP (14) -#define BSP_LIGHTVOLS_LUMP (15) -#define BSP_VISIBILITY_LUMP (16) - -#define BSP_LIGHTMAP_BANKSIZE (128*128*3) - - -#define CONTENTS_SOLID 1 // an eye is never valid in a solid -#define CONTENTS_LAVA 8 -#define CONTENTS_SLIME 16 -#define CONTENTS_WATER 32 -#define CONTENTS_FOG 64 - -#define CONTENTS_AREAPORTAL 0x8000 - -#define CONTENTS_PLAYERCLIP 0x10000 -#define CONTENTS_MONSTERCLIP 0x20000 -//bot specific contents types -#define CONTENTS_TELEPORTER 0x40000 -#define CONTENTS_JUMPPAD 0x80000 -#define CONTENTS_CLUSTERPORTAL 0x100000 -#define CONTENTS_DONOTENTER 0x200000 - -#define CONTENTS_ORIGIN 0x1000000 // removed before bsping an entity - -#define CONTENTS_BODY 0x2000000 // should never be on a brush, only in game -#define CONTENTS_CORPSE 0x4000000 -#define CONTENTS_DETAIL 0x8000000 // brushes not used for the bsp -#define CONTENTS_STRUCTURAL 0x10000000 // brushes used for the bsp -#define CONTENTS_TRANSLUCENT 0x20000000 // don't consume surface fragments inside -#define CONTENTS_TRIGGER 0x40000000 -#define CONTENTS_NODROP 0x80000000 // don't leave bodies or items (death fog, lava) - -#define SURF_NODAMAGE 0x1 // never give falling damage -#define SURF_SLICK 0x2 // effects game physics -#define SURF_SKY 0x4 // lighting from environment map -#define SURF_LADDER 0x8 -#define SURF_NOIMPACT 0x10 // don't make missile explosions -#define SURF_NOMARKS 0x20 // don't leave missile marks -#define SURF_FLESH 0x40 // make flesh sounds and effects -#define SURF_NODRAW 0x80 // don't generate a drawsurface at all -#define SURF_HINT 0x100 // make a primary bsp splitter -#define SURF_SKIP 0x200 // completely ignore, allowing non-closed brushes -#define SURF_NOLIGHTMAP 0x400 // surface doesn't need a lightmap -#define SURF_POINTLIGHT 0x800 // generate lighting info at vertexes -#define SURF_METALSTEPS 0x1000 // clanking footsteps -#define SURF_NOSTEPS 0x2000 // no footstep sounds -#define SURF_NONSOLID 0x4000 // don't collide against curves with this set -#define SURF_LIGHTFILTER 0x8000 // act as a light filter during q3map -light -#define SURF_ALPHASHADOW 0x10000 // do per-pixel light shadow casting in q3map -#define SURF_NODLIGHT 0x20000 // don't dlight even if solid (solid lava, skies) - -/* Shader flags */ -enum -{ - SHADER_NOCULL = 1 << 0, - SHADER_TRANSPARENT = 1 << 1, - SHADER_DEPTHWRITE = 1 << 2, - SHADER_SKY = 1 << 3, - SHADER_NOMIPMAPS = 1 << 4, - SHADER_NEEDCOLOURS = 1 << 5, - SHADER_DEFORMVERTS = 1 << 6 -}; - -/* Shaderpass flags */ -enum -{ - SHADER_LIGHTMAP = 1 << 0, - SHADER_BLEND = 1 << 1, - SHADER_ALPHAFUNC = 1 << 3, - SHADER_TCMOD = 1 << 4, - SHADER_ANIMMAP = 1 << 5, - SHADER_TCGEN_ENV = 1 << 6 -}; - -/* Transform functions */ -enum WaveType -{ - SHADER_FUNC_NONE = 0, - SHADER_FUNC_SIN = 1, - SHADER_FUNC_TRIANGLE = 2, - SHADER_FUNC_SQUARE = 3, - SHADER_FUNC_SAWTOOTH = 4, - SHADER_FUNC_INVERSESAWTOOTH = 5 -}; - -/* *Gen functions */ -enum GenFunc -{ - SHADER_GEN_IDENTITY = 0, - SHADER_GEN_WAVE = 1, - SHADER_GEN_VERTEX = 2 -}; - -enum TexGen -{ - TEXGEN_BASE = 0, // Coord set 0 - TEXGEN_LIGHTMAP = 1, // Coord set 1 - TEXGEN_ENVIRONMENT = 2 // Neither, generated -}; - -enum DeformFunc -{ - DEFORM_FUNC_NONE = 0, - DEFORM_FUNC_BULGE = 1, - DEFORM_FUNC_WAVE = 2, - DEFORM_FUNC_NORMAL = 3, - DEFORM_FUNC_MOVE = 4, - DEFORM_FUNC_AUTOSPRITE = 5, - DEFORM_FUNC_AUTOSPRITE2 = 6 - -}; -///////////////////////////////////////////////////////// -// -// bsp contents -// - -struct bsp_plane_t { - float normal[3]; - float dist; -}; - -struct bsp_model_t { - float bbox[6]; - int face_start; - int face_count; - int brush_start; - int brush_count; -}; - -struct bsp_node_t { - int plane; // dividing plane - //int children[2]; // left and right nodes, - // negative are leaves - int front; - int back; - int bbox[6]; -}; - -struct bsp_leaf_t { - int cluster; // visibility cluster number - int area; - int bbox[6]; - int face_start; - int face_count; - int brush_start; - int brush_count; -}; - -#define BSP_FACETYPE_NORMAL (1) -#define BSP_FACETYPE_PATCH (2) -#define BSP_FACETYPE_MESH (3) -#define BSP_FACETYPE_FLARE (4) - -struct bsp_face_t { - int shader; // shader ref - int unknown; - int type; // face type - int vert_start; - int vert_count; - int elem_start; - int elem_count; - int lm_texture; // lightmap - int lm_offset[2]; - int lm_size[2]; - float org[3]; // facetype_normal only - float bbox[6]; // facetype_patch only - float normal[3]; // facetype_normal only - int mesh_cp[2]; // patch control point dims -}; - -struct bsp_shader_t { - char name[64]; - int surface_flags; - int content_flags; -}; - -struct bsp_vertex_t { - float point[3]; - float texture[2]; - float lightmap[2]; - float normal[3]; - int color; -}; - -struct bsp_vis_t { - int cluster_count; - int row_size; - unsigned char data[1]; -}; - -// OGRE additions -struct bsp_lump_entry_t { - int offset; - int size; -}; -struct bsp_header_t { - char magic[4]; - int version; - bsp_lump_entry_t lumps[17]; -}; - -// -// Brushes sides in BSP tree -// -struct bsp_brushside_t { - int planenum; - int content; // ??shader?? -}; - - -// -// Brushes in BSP tree -// -struct bsp_brush_t { - int firstside; - int numsides; - int shaderIndex; -}; -#endif diff --git a/PlugIns/BSPSceneManager/include/OgreStaticFaceGroup.h b/PlugIns/BSPSceneManager/include/OgreStaticFaceGroup.h deleted file mode 100644 index dac67a1344f..00000000000 --- a/PlugIns/BSPSceneManager/include/OgreStaticFaceGroup.h +++ /dev/null @@ -1,141 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __StaticFaceGroup_H__ -#define __StaticFaceGroup_H__ - -#include "OgrePrerequisites.h" - -#include "OgrePlane.h" -#include "OgrePatchSurface.h" - -namespace Ogre { - - /** \addtogroup Core - * @{ - */ - /** \addtogroup Scene - * @{ - */ - /** A type of face group, i.e. face list of procedural etc */ - enum FaceGroupType { - FGT_FACE_LIST, - FGT_PATCH, - FGT_UNKNOWN - }; - - /** Collects a group of static i.e. immovable faces together which have common - properties like the material they use, the plane they lie on. - - Whilst for discrete geometry (i.e. movable objects) groups of faces are - held in the SubMesh class, for immovable objects like scenery there - needs to ba little more flexibility in the grouping since the group is - likely to be a small part of a huge set of geometry. In addition, because - the faces are unmoving certain optimisations can be performed, e.g. - precalculating a world-coordinate bounding box and normal. - @par - Exactly how this class is used depends on the format of the large - static geometry used in the level. An example would be the use of this - class in the BspNode class for indoor levels. - For flexibility and efficiency, it is not assumed that this class holds - details of the vertices itself, or in fact that it holds the vertex indices - itself. Everything is manipulated via pointers so if you want this - class to point into a block of geometry data it can. - */ - struct StaticFaceGroup { - // Type of face group. - FaceGroupType fType; - - /// Is this a sky surface? - bool isSky; - - /** Index into a buffer containing vertex definitions. Because we're - dealing with subsets of large levels this is likely to be part-way - through a huge vertex buffer. */ - int vertexStart; - - /** The range of vertices in the buffer this facegroup references. - This is really for copying purposes only, so that we know which - subset of vertices to copy from our large-level buffer into the rendering buffer. - */ - int numVertices; - - /** Index into a buffer containing vertex indices. This buffer - may be individual to this group or shared for memory allocation - efficiency.The vertex indexes are relative the the mVertexStart pointer, - not to the start of the large-level buffer, allowing simple reindexing - when copying data into rendering buffers. - This is only applicable to FGT_FACE_LIST face group types. - */ - int elementStart; - - /** The number of vertex indices. - This is only applicable to FGT_FACE_LIST face group types. - */ - int numElements; - - /** Handle to material used by this group. - Note the use of the material handle rather than the material - name - this is for efficiency since there will be many of these. - */ - ResourceHandle materialHandle; - - Plane plane; - - /// Patch surface (only applicable when fType = FGT_PATCH) - PatchSurface* patchSurf; - - - friend std::ostream& operator<<(std::ostream& o, const StaticFaceGroup& s) - { - o << "StaticFaceGroup("; - if (s.fType == FGT_FACE_LIST) - { - o << "faceList, numVertices=" << s.numVertices << ", vertexStart=" << s.vertexStart; - o << ", numElements=" << s.numElements << ", elementStart=" << s.elementStart; - o << ", normal=" << s.plane.normal; - } - else if (s.fType == FGT_PATCH) - { - o << "bezierPatch, numVertices=" << s.numVertices << ", vertexStart=" << s.vertexStart; - // TODO - } - - o << ", materialHandle=" << s.materialHandle; - o << ")"; - - return o; - } - - - }; - /** @} */ - /** @} */ - -} // namespace - -#endif diff --git a/PlugIns/BSPSceneManager/src/OgreBspLevel.cpp b/PlugIns/BSPSceneManager/src/OgreBspLevel.cpp deleted file mode 100644 index 17b2b815032..00000000000 --- a/PlugIns/BSPSceneManager/src/OgreBspLevel.cpp +++ /dev/null @@ -1,1081 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreBspLevel.h" -#include "OgreException.h" -#include "OgreMaterial.h" -#include "OgreMaterialManager.h" -#include "OgreMovableObject.h" -#include "OgreSceneManager.h" -#include "OgrePatchSurface.h" -#include "OgreQuake3ShaderManager.h" -#include "OgreQuake3Shader.h" -#include "OgreMath.h" -#include "OgreStringVector.h" -#include "OgreStringConverter.h" -#include "OgreLogManager.h" -#include "OgreTechnique.h" -#include "OgrePass.h" -#include "OgreTextureUnitState.h" -#include "OgreResourceGroupManager.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreBspSceneManager.h" - -namespace Ogre { - - #define NUM_FACES_PER_PROGRESS_REPORT 100 - #define NUM_NODES_PER_PROGRESS_REPORT 50 - #define NUM_LEAVES_PER_PROGRESS_REPORT 50 - #define NUM_BRUSHES_PER_PROGRESS_REPORT 50 - - //----------------------------------------------------------------------- - BspLevel::BspLevel(ResourceManager* creator, const String& name, - ResourceHandle handle, const String& group, bool isManual, - ManualResourceLoader* loader) - : Resource(creator, name, handle, group, isManual, loader), - mRootNode(0), - mLeafFaceGroups(0), - mFaceGroups(0), - mBrushes(0), - mSkyEnabled(false) - { - mVisData.tableData = 0; - - if (createParamDictionary("BspLevel")) - { - // nothing - } - } - - //----------------------------------------------------------------------- - BspLevel::~BspLevel() - { - // have to call this here reather than in Resource destructor - // since calling virtual methods in base destructors causes crash - unload(); - - } - - //----------------------------------------------------------------------- - void BspLevel::loadImpl() - { - mSkyEnabled = false; - - // Use Quake3 file loader - Quake3Level q3; - DataStreamPtr stream = - ResourceGroupManager::getSingleton().openResource(mName, - ResourceGroupManager::getSingleton().getWorldResourceGroupName()); - - q3.loadFromStream(stream); - - loadQuake3Level(q3); - - } - //----------------------------------------------------------------------- - bool BspLevel::isSkyEnabled(void) const - { - return mSkyEnabled; - } - //----------------------------------------------------------------------- - const String& BspLevel::getSkyMaterialName(void) const - { - return mSkyMaterial; - } - //----------------------------------------------------------------------- - Real BspLevel::getSkyCurvature(void) const - { - return mSkyCurvature; - } - //----------------------------------------------------------------------- - void BspLevel::load(const DataStreamPtr& stream) - { - // Use Quake3 file loader - Quake3Level q3; - q3.loadFromStream(stream); - - loadQuake3Level(q3); - - } - //----------------------------------------------------------------------- - void BspLevel::unloadImpl() - { - if (mRenderOp.vertexData) - OGRE_DELETE mRenderOp.vertexData; - mIndexes.reset(); - if (mFaceGroups) - OGRE_DELETE_ARRAY_T(mFaceGroups, StaticFaceGroup, (size_t)mNumFaceGroups, MEMCATEGORY_GEOMETRY); - if (mLeafFaceGroups) - OGRE_FREE(mLeafFaceGroups, MEMCATEGORY_GEOMETRY); - if (mRootNode) - OGRE_DELETE [] mRootNode; - if (mVisData.tableData) - OGRE_FREE(mVisData.tableData, MEMCATEGORY_GEOMETRY); - if (mBrushes) - OGRE_DELETE_ARRAY_T(mBrushes, Brush, (size_t)mNumBrushes, MEMCATEGORY_GEOMETRY); - - // no need to delete index buffer, will be handled by shared pointer - OGRE_DELETE mRenderOp.indexData; - mRenderOp.indexData = 0; - mRenderOp.vertexData = 0; - mRootNode = 0; - mFaceGroups = 0; - mLeafFaceGroups = 0; - mBrushes = 0; - mVisData.tableData = 0; - for (PatchMap::iterator pi = mPatches.begin(); pi != mPatches.end(); ++pi) - { - OGRE_DELETE pi->second; - } - mPatches.clear(); - } - //----------------------------------------------------------------------- - size_t BspLevel::calculateLoadingStages(const String& levelName) - { - DataStreamPtr stream = - ResourceGroupManager::getSingleton().openResource(levelName, - ResourceGroupManager::getSingleton().getWorldResourceGroupName()); - return calculateLoadingStages(stream); - } - //----------------------------------------------------------------------- - size_t BspLevel::calculateLoadingStages(DataStreamPtr& stream) - { - Quake3Level q3; - - // Load header only - q3.loadHeaderFromStream(stream); - - // Ok, count up the things that we will report - size_t stages = 0; - - // loadEntities (1 stage) - ++stages; - // extractLightmaps (external, 1 stage) - ++stages; - // initQuake3Patches - ++stages; - // vertex setup - ++stages; - // face setup - ++stages; - // patch building - ++stages; - // material setup - // this is not strictly based on load, since we only know the number - // of faces, not the number of materials - // raise one event for every 50 faces, plus one at the end - stages += (q3.mNumFaces / NUM_FACES_PER_PROGRESS_REPORT) + 1; - // node setup - stages += (q3.mNumNodes / NUM_NODES_PER_PROGRESS_REPORT) + 1; - // brush setup - stages += (q3.mNumBrushes / NUM_BRUSHES_PER_PROGRESS_REPORT) + 1; - // leaf setup - stages += (q3.mNumLeaves / NUM_LEAVES_PER_PROGRESS_REPORT) + 1; - // vis - ++stages; - - return stages; - - } - //----------------------------------------------------------------------- - void BspLevel::loadQuake3Level(const Quake3Level& q3lvl) - { - MaterialManager& mm = MaterialManager::getSingleton(); - ResourceGroupManager& rgm = ResourceGroupManager::getSingleton(); - - rgm._notifyCustomStageStarted("Parsing entities"); - loadEntities(q3lvl); - rgm._notifyCustomStageEnded(); - - // Extract lightmaps into textures - rgm._notifyCustomStageStarted("Extracting lightmaps"); - q3lvl.extractLightmaps(); - rgm._notifyCustomStageEnded(); - - //----------------------------------------------------------------------- - // Vertices - //----------------------------------------------------------------------- - // Allocate memory for vertices & copy - mRenderOp.vertexData = OGRE_NEW VertexData(); - - /// Create vertex declaration - VertexDeclaration* decl = mRenderOp.vertexData->vertexDeclaration; - size_t offset = 0; - offset += decl->addElement(0, offset, VET_FLOAT3, VES_POSITION).getSize(); - offset += decl->addElement(0, offset, VET_FLOAT3, VES_NORMAL).getSize(); - offset += decl->addElement(0, offset, VET_COLOUR, VES_DIFFUSE).getSize(); - offset += decl->addElement(0, offset, VET_FLOAT2, VES_TEXTURE_COORDINATES, 0).getSize(); - decl->addElement(0, offset, VET_FLOAT2, VES_TEXTURE_COORDINATES, 1); - - // Build initial patches - we need to know how big the vertex buffer needs to be - // to accommodate the subdivision - rgm._notifyCustomStageStarted("Initialising patches"); - initQuake3Patches(q3lvl, decl); - rgm._notifyCustomStageEnded(); - - /// Create the vertex buffer, allow space for patches - rgm._notifyCustomStageStarted("Setting up vertex data"); - HardwareVertexBufferSharedPtr vbuf = HardwareBufferManager::getSingleton() - .createVertexBuffer( - sizeof(BspVertex), - q3lvl.mNumVertices + mPatchVertexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - //COPY static vertex data - Note that we can't just block-copy the vertex data because we have to reorder - // our vertex elements; this is to ensure compatibility with older cards when using - // hardware vertex buffers - Direct3D requires that the buffer format maps onto a - // FVF in those older drivers. - // Lock just the non-patch area for now - BspVertex* pVert = static_cast( - vbuf->lock(0, q3lvl.mNumVertices * sizeof(BspVertex), HardwareBuffer::HBL_DISCARD) ); - // Keep another base pointer for use later in patch building - for (int v = 0; v < q3lvl.mNumVertices; ++v) - { - quakeVertexToBspVertex(&q3lvl.mVertices[v], pVert++); - } - vbuf->unlock(); - // Setup binding - mRenderOp.vertexData->vertexBufferBinding->setBinding(0, vbuf); - // Set other data - mRenderOp.vertexData->vertexStart = 0; - mRenderOp.vertexData->vertexCount = q3lvl.mNumVertices + mPatchVertexCount; - rgm._notifyCustomStageEnded(); - - //----------------------------------------------------------------------- - // Faces - // -------- - rgm._notifyCustomStageStarted("Setting up face data"); - mNumLeafFaceGroups = q3lvl.mNumLeafFaces; - mLeafFaceGroups = OGRE_ALLOC_T(int, mNumLeafFaceGroups, MEMCATEGORY_GEOMETRY); - memcpy(mLeafFaceGroups, q3lvl.mLeafFaces, sizeof(int)*mNumLeafFaceGroups); - mNumFaceGroups = q3lvl.mNumFaces; - mFaceGroups = OGRE_NEW_ARRAY_T(StaticFaceGroup, mNumFaceGroups, MEMCATEGORY_GEOMETRY); - // Set up index buffer - // NB Quake3 indexes are 32-bit - // Copy the indexes into a software area for staging - size_t numIndexes = q3lvl.mNumElements + mPatchIndexCount; - // Create an index buffer manually in system memory, allow space for patches - mIndexes = std::make_shared(nullptr, HardwareIndexBuffer::IT_32BIT, numIndexes, - new DefaultHardwareBuffer(numIndexes * sizeof(int))); - // Write main indexes - mIndexes->writeData(0, sizeof(unsigned int) * q3lvl.mNumElements, q3lvl.mElements, true); - // create actual hardware index buffer - // Create enough index space to render whole level, index data is per-frame - mRenderOp.indexData = OGRE_NEW IndexData(); - mRenderOp.indexData->indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_32BIT, numIndexes, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE); - rgm._notifyCustomStageEnded(); - - // now build patch information - rgm._notifyCustomStageStarted("Building patches"); - buildQuake3Patches(q3lvl.mNumVertices, q3lvl.mNumElements); - rgm._notifyCustomStageEnded(); - - //----------------------------------------------------------------------- - // Create materials for shaders - //----------------------------------------------------------------------- - // NB this only works for the 'default' shaders for now - // i.e. those that don't have a .shader script and thus default - // to just texture + lightmap - // TODO: pre-parse all .shader files and create lookup for next stage (use ROGL shader_file_t) - - // Material names are shadername#lightmapnumber - // This is because I like to define materials up front completely - // rather than combine lightmap and shader dynamically (it's - // more generic). It results in more materials, but they're small - // beer anyway. Texture duplication is prevented by infrastructure. - // To do this I actually need to parse the faces since they have the - // shader/lightmap combo (lightmap number is not in the shader since - // it can be used with multiple lightmaps) - String shaderName; - int face; - face = q3lvl.mNumFaces; - ResourceHandle matHandle; - String meshName; - - String resourceGroup = ResourceGroupManager::getSingleton().getWorldResourceGroupName(); - size_t progressCountdown = NUM_FACES_PER_PROGRESS_REPORT; - size_t progressCount = 0; - - while(face--) - { - // Progress reporting - if (progressCountdown == NUM_FACES_PER_PROGRESS_REPORT) - { - ++progressCount; - StringStream str; - str << "Loading materials (phase " << progressCount << ")"; - rgm._notifyCustomStageStarted(str.str()); - } - else if (progressCountdown == 0) - { - // stage report - rgm._notifyCustomStageEnded(); - progressCountdown = NUM_FACES_PER_PROGRESS_REPORT + 1; - - } - - // Check to see if existing material - // Format shader#lightmap - int shadIdx = q3lvl.mFaces[face].shader; - StringStream tmp; - tmp << q3lvl.mShaders[shadIdx].name << "#" << q3lvl.mFaces[face].lm_texture; - shaderName = tmp.str(); - - MaterialPtr shadMat = MaterialManager::getSingleton().getByName(shaderName); - if (!shadMat) - { - // Build new material - - // Colour layer - // NB no extension in Q3A(doh), have to try shader, .jpg, .tga - String tryName = q3lvl.mShaders[shadIdx].name; - // Try shader first - Quake3Shader* pShad = Quake3ShaderManager::getSingleton().getByName(tryName); - if (pShad) - { - shadMat = pShad->createAsMaterial(q3lvl.mFaces[face].lm_texture); - // Do skydome (use this material) - if (pShad->skyDome) - { - mSkyEnabled = true; - mSkyMaterial = shadMat->getName(); - mSkyCurvature = 20 - (pShad->cloudHeight / 256 * 18); - } - } - else - { - // No shader script, try default type texture - shadMat = mm.create(shaderName, resourceGroup); - Pass *shadPass = shadMat->getTechnique(0)->getPass(0); - // Try jpg - TextureUnitState* tex = 0; - if (ResourceGroupManager::getSingleton().resourceExists(resourceGroup, tryName + ".jpg")) - { - tex = shadPass->createTextureUnitState(tryName + ".jpg"); - } - else if (ResourceGroupManager::getSingleton().resourceExists(resourceGroup, tryName + ".tga")) - { - tex = shadPass->createTextureUnitState(tryName + ".tga"); - } - - if (tex) - { - // Set replace on all first layer textures for now - tex->setColourOperation(LBO_REPLACE); - tex->setTextureAddressingMode(TextureUnitState::TAM_WRAP); - } - - if (q3lvl.mFaces[face].lm_texture >= 0) - { - // Add lightmap, additive blending - StringStream lightmapName; - lightmapName << "@lightmap" << q3lvl.mFaces[face].lm_texture; - tex = shadPass->createTextureUnitState(lightmapName.str()); - // Blend - tex->setColourOperation(LBO_MODULATE); - // Use 2nd texture co-ordinate set - tex->setTextureCoordSet(1); - // Clamp - tex->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); - - } - // Set culling mode to none - shadMat->setCullingMode(CULL_NONE); - // No dynamic lighting - shadMat->setLightingEnabled(false); - - } - } - matHandle = shadMat->getHandle(); - shadMat->load(); - - // Copy face data - StaticFaceGroup* dest = &mFaceGroups[face]; - bsp_face_t* src = &q3lvl.mFaces[face]; - - if (q3lvl.mShaders[src->shader].surface_flags & SURF_SKY) - { - dest->isSky = true; - } - else - { - dest->isSky = false; - } - - - dest->materialHandle = matHandle; - dest->elementStart = src->elem_start; - dest->numElements = src->elem_count; - dest->numVertices = src->vert_count; - dest->vertexStart = src->vert_start; - if (src->type == BSP_FACETYPE_NORMAL) - { - dest->fType = FGT_FACE_LIST; - // Assign plane - dest->plane.normal = Vector3(src->normal[0], src->normal[1], src->normal[2]); - dest->plane.d = -dest->plane.normal.dotProduct( - Vector3(src->org[0], src->org[1], src->org[2])); - - // Don't rebase indexes here - Quake3 re-uses some indexes for multiple vertex - // groups eg repeating small details have the same relative vertex data but - // use the same index data. - - } - else if (src->type == BSP_FACETYPE_PATCH) - { - // Seems to be some crap in the Q3 level where vertex count = 0 or num control points = 0? - if (dest->numVertices == 0 || src->mesh_cp[0] == 0) - { - dest->fType = FGT_UNKNOWN; - } - else - { - - // Set up patch surface - dest->fType = FGT_PATCH; - - // Locate the patch we already built - PatchMap::iterator p = mPatches.find(face); - if (p == mPatches.end()) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Patch not found from previous built state", - "BspLevel::loadQuake3Level"); - } - - dest->patchSurf = p->second; - - } - - - } - else if (src->type == BSP_FACETYPE_MESH) - { - dest->fType = FGT_FACE_LIST; - // Assign plane - dest->plane.normal = Vector3(src->normal[0], src->normal[1], src->normal[2]); - dest->plane.d = -dest->plane.normal.dotProduct( - Vector3(src->org[0], src->org[1], src->org[2])); - } - else - { - LogManager::getSingleton().logError("Unknown Face Type"); - } - - // progress reporting - --progressCountdown; - - } - // final stage report - rgm._notifyCustomStageEnded(); - - //----------------------------------------------------------------------- - // Nodes - //----------------------------------------------------------------------- - // Allocate memory for all nodes (leaves and splitters) - mNumNodes = q3lvl.mNumNodes + q3lvl.mNumLeaves; - mNumLeaves = q3lvl.mNumLeaves; - mLeafStart = q3lvl.mNumNodes; - mRootNode = OGRE_NEW BspNode[mNumNodes]; - int i; - // Convert nodes - // In our array, first q3lvl.mNumNodes are non-leaf, others are leaves - progressCountdown = NUM_NODES_PER_PROGRESS_REPORT; - progressCount = 0; - - for (i = 0; i < q3lvl.mNumNodes; ++i) - { - // Progress reporting - if (progressCountdown == NUM_NODES_PER_PROGRESS_REPORT) - { - ++progressCount; - StringStream str; - str << "Loading nodes (phase " << progressCount << ")"; - rgm._notifyCustomStageStarted(str.str()); - } - else if (progressCountdown == 0) - { - // stage report - rgm._notifyCustomStageEnded(); - progressCountdown = NUM_NODES_PER_PROGRESS_REPORT + 1; - - } - - BspNode* node = &mRootNode[i]; - bsp_node_t* q3node = &q3lvl.mNodes[i]; - - // Set non-leaf - node->mIsLeaf = false; - // Set owner - node->mOwner = this; - // Set plane - node->mSplitPlane.normal.x = q3lvl.mPlanes[q3node->plane].normal[0]; - node->mSplitPlane.normal.y = q3lvl.mPlanes[q3node->plane].normal[1]; - node->mSplitPlane.normal.z = q3lvl.mPlanes[q3node->plane].normal[2]; - node->mSplitPlane.d = -q3lvl.mPlanes[q3node->plane].dist; - // Set bounding box - node->mBounds.setMinimum(Vector3(&q3node->bbox[0])); - node->mBounds.setMaximum(Vector3(&q3node->bbox[3])); - // Set back pointer - // Negative indexes in Quake3 mean leaves - if (q3node->back < 0) - { - // Points to leaf, offset to leaf start and negate index - node->mBack = &mRootNode[mLeafStart + (~(q3node->back))]; - - } - else - { - // Points to node - node->mBack = &mRootNode[q3node->back]; - } - // Set front pointer - // Negative indexes in Quake3 mean leaves - if (q3node->front < 0) - { - // Points to leaf, offset to leaf start and negate index - node->mFront = &mRootNode[mLeafStart + (~(q3node->front))]; - - } - else - { - // Points to node - node->mFront = &mRootNode[q3node->front]; - } - - --progressCountdown; - - - } - // final stage report - rgm._notifyCustomStageEnded(); - - //----------------------------------------------------------------------- - // Brushes - //----------------------------------------------------------------------- - // Reserve enough memory for all brushes, solid or not (need to maintain indexes) - mNumBrushes = q3lvl.mNumBrushes; - mBrushes = OGRE_NEW_ARRAY_T(BspNode::Brush, mNumBrushes, MEMCATEGORY_GEOMETRY); - progressCountdown = NUM_BRUSHES_PER_PROGRESS_REPORT; - progressCount = 0; - - for (i = 0; i < q3lvl.mNumBrushes; ++i) - { - // Progress reporting - if (progressCountdown == NUM_BRUSHES_PER_PROGRESS_REPORT) - { - ++progressCount; - StringStream str; - str << "Loading brushes (phase " << progressCount << ")"; - rgm._notifyCustomStageStarted(str.str()); - } - else if (progressCountdown == 0) - { - // stage report - rgm._notifyCustomStageEnded(); - progressCountdown = NUM_BRUSHES_PER_PROGRESS_REPORT + 1; - - } - bsp_brush_t* q3brush = &q3lvl.mBrushes[i]; - - // Create a new OGRE brush - BspNode::Brush *pBrush = &(mBrushes[i]); - int brushSideIdx, numBrushSides; - numBrushSides = q3brush->numsides; - brushSideIdx = q3brush->firstside; - // Iterate over the sides and create plane for each - while (numBrushSides--) - { - bsp_brushside_t* q3brushside = &q3lvl.mBrushSides[brushSideIdx]; - bsp_plane_t* q3brushplane = &q3lvl.mPlanes[q3brushside->planenum]; - // Notice how we normally invert Q3A plane distances, but here we do not - // Because we want plane normals pointing out of solid brushes, not in - Plane brushSide( - Vector3( - q3brushplane->normal[0], - q3brushplane->normal[1], - q3brushplane->normal[2]), - q3brushplane->dist); - pBrush->planes.push_back(brushSide); - ++brushSideIdx; - } - // Build world fragment - pBrush->fragment.fragmentType = WFT_PLANE_BOUNDED_REGION; - pBrush->fragment.planes = &(pBrush->planes); - - --progressCountdown; - - } - // final stage report - rgm._notifyCustomStageEnded(); - - - - //----------------------------------------------------------------------- - // Leaves - //----------------------------------------------------------------------- - progressCountdown = NUM_LEAVES_PER_PROGRESS_REPORT; - progressCount = 0; - for (i = 0; i < q3lvl.mNumLeaves; ++i) - { - // Progress reporting - if (progressCountdown == NUM_LEAVES_PER_PROGRESS_REPORT) - { - ++progressCount; - StringStream str; - str << "Loading leaves (phase " << progressCount << ")"; - rgm._notifyCustomStageStarted(str.str()); - } - else if (progressCountdown == 0) - { - // stage report - rgm._notifyCustomStageEnded(); - progressCountdown = NUM_LEAVES_PER_PROGRESS_REPORT + 1; - - } - BspNode* node = &mRootNode[i + mLeafStart]; - bsp_leaf_t* q3leaf = &q3lvl.mLeaves[i]; - - // Set leaf - node->mIsLeaf = true; - // Set owner - node->mOwner = this; - // Set bounding box - node->mBounds.setMinimum(Vector3(&q3leaf->bbox[0])); - node->mBounds.setMaximum(Vector3(&q3leaf->bbox[3])); - // Set faces - node->mFaceGroupStart = q3leaf->face_start; - node->mNumFaceGroups = q3leaf->face_count; - - node->mVisCluster = q3leaf->cluster; - - // Load Brushes for this leaf - int brushIdx, brushCount, realBrushIdx; - brushCount = q3leaf->brush_count; - brushIdx = q3leaf->brush_start; - - while(brushCount--) - { - realBrushIdx = q3lvl.mLeafBrushes[brushIdx]; - bsp_brush_t* q3brush = &q3lvl.mBrushes[realBrushIdx]; - // Only load solid ones, we don't care about any other types - // Shader determines this - bsp_shader_t* brushShader = &q3lvl.mShaders[q3brush->shaderIndex]; - if (brushShader->content_flags & CONTENTS_SOLID) - { - // Get brush - BspNode::Brush *pBrush = &(mBrushes[realBrushIdx]); - assert(pBrush->fragment.fragmentType == WFT_PLANE_BOUNDED_REGION); - // Assign node pointer - node->mSolidBrushes.push_back(pBrush); - } - ++brushIdx; - } - - --progressCountdown; - - } - // final stage report - rgm._notifyCustomStageEnded(); - - - - // Vis - just copy - // final stage report - rgm._notifyCustomStageStarted("Copying Vis data"); - mVisData.numClusters = q3lvl.mVis->cluster_count; - mVisData.rowLength = q3lvl.mVis->row_size; - mVisData.tableData = OGRE_ALLOC_T(unsigned char, q3lvl.mVis->row_size * q3lvl.mVis->cluster_count, MEMCATEGORY_GEOMETRY); - memcpy(mVisData.tableData, q3lvl.mVis->data, q3lvl.mVis->row_size * q3lvl.mVis->cluster_count); - rgm._notifyCustomStageEnded(); - - - - } - //----------------------------------------------------------------------- - unsigned int BspLevel::cacheGeometry(uint32* pIndexes, const StaticFaceGroup* faceGroup) - { - // Skip sky always - if (faceGroup->isSky) - return 0; - - size_t idxStart, numIdx, vertexStart; - - if (faceGroup->fType == FGT_FACE_LIST) - { - idxStart = faceGroup->elementStart; - numIdx = faceGroup->numElements; - vertexStart = faceGroup->vertexStart; - } - else if (faceGroup->fType == FGT_PATCH) - { - - idxStart = faceGroup->patchSurf->getIndexOffset(); - numIdx = faceGroup->patchSurf->getCurrentIndexCount(); - vertexStart = faceGroup->patchSurf->getVertexOffset(); - } - else - { - // Unsupported face type - return 0; - } - - // Copy index data - unsigned int* pSrc = static_cast(mIndexes->lock( - idxStart * sizeof(unsigned int), numIdx * sizeof(unsigned int), HardwareBuffer::HBL_READ_ONLY)); - // Offset the indexes here - // we have to do this now rather than up-front because the - // indexes are sometimes reused to address different vertex chunks - for (size_t elem = 0; elem < numIdx; ++elem) - { - *pIndexes++ = *pSrc++ + static_cast(vertexStart); - } - mIndexes->unlock(); - - // return number of elements - return static_cast(numIdx); - } - bool BspLevel::cacheGeometry(const std::vector& materialFaceGroups) - { - // Empty existing cache - mRenderOp.indexData->indexCount = 0; - // lock index buffer ready to receive data - uint32* pIdx = - static_cast(mRenderOp.indexData->indexBuffer->lock(HardwareBuffer::HBL_DISCARD)); - for (auto faceGroup : materialFaceGroups) - { - // Cache each - unsigned int numelems = cacheGeometry(pIdx, faceGroup); - mRenderOp.indexData->indexCount += numelems; - pIdx += numelems; - } - // Unlock the buffer - mRenderOp.indexData->indexBuffer->unlock(); - - // Skip if no faces to process (we're not doing flare types yet) - return mRenderOp.indexData->indexCount != 0; - } - - //----------------------------------------------------------------------- - void BspLevel::initQuake3Patches(const Quake3Level & q3lvl, VertexDeclaration* decl) - { - int face; - - mPatchVertexCount = 0; - mPatchIndexCount = 0; - - // We're just building the patch here to get a hold on the size of the mesh - // although we'll reuse this information later - face = q3lvl.mNumFaces; - while (face--) - { - - bsp_face_t* src = &q3lvl.mFaces[face]; - - if (src->type == BSP_FACETYPE_PATCH) - { - // Seems to be some crap in the Q3 level where vertex count = 0 or num control points = 0? - if (src->vert_count == 0 || src->mesh_cp[0] == 0) - { - continue; - } - PatchSurface* ps = OGRE_NEW PatchSurface(); - // Set up control points & format - // Reuse the vertex declaration - // Copy control points into a buffer so we can convert their format - BspVertex* pControlPoints = OGRE_ALLOC_T(BspVertex, src->vert_count, MEMCATEGORY_GEOMETRY); - bsp_vertex_t* pSrc = q3lvl.mVertices + src->vert_start; - for (int v = 0; v < src->vert_count; ++v) - { - quakeVertexToBspVertex(pSrc++, &pControlPoints[v]); - } - // Define the surface, but don't build it yet (no vertex / index buffer) - ps->defineSurface( - pControlPoints, - decl, - src->mesh_cp[0], - src->mesh_cp[1], - PatchSurface::PST_BEZIER); - // Get stats - mPatchVertexCount += ps->getRequiredVertexCount(); - mPatchIndexCount += ps->getRequiredIndexCount(); - - // Save the surface for later - mPatches[face] = ps; - } - - - } - - } - //----------------------------------------------------------------------- - void BspLevel::buildQuake3Patches(size_t vertOffset, size_t indexOffset) - { - // Loop through the patches - PatchMap::iterator i, iend; - iend = mPatches.end(); - - size_t currVertOffset = vertOffset; - size_t currIndexOffset = indexOffset; - - HardwareVertexBufferSharedPtr vbuf = mRenderOp.vertexData->vertexBufferBinding->getBuffer(0); - - for (i = mPatches.begin(); i != iend; ++i) - { - PatchSurface* ps = i->second; - - ps->build(vbuf, currVertOffset, mIndexes, currIndexOffset); - - // No need for control points anymore - BspVertex* pCP = static_cast(ps->getControlPointBuffer()); - OGRE_FREE(pCP, MEMCATEGORY_GEOMETRY); - ps->notifyControlPointBufferDeallocated(); - - currVertOffset += ps->getRequiredVertexCount(); - currIndexOffset += ps->getRequiredIndexCount(); - - } - } - //----------------------------------------------------------------------- - bool BspLevel::isLeafVisible(const BspNode* from, const BspNode* to) const - { - if (to->mVisCluster == -1) - return false; - if (from->mVisCluster == -1) - // Camera outside world? - return true; - - - if (!from->isLeaf() || !to->isLeaf()) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Both nodes must be leaf nodes for visibility testing.", - "BspLevel::isLeafVisible"); - - // Use PVS to determine visibility - - /* - // In wordier terms, the fairly cryptic (but fast) version is doing this: - // Could make it a macro for even more speed? - - // Row offset = from cluster number * row size - int offset = from->mVisCluster*mVisData.rowLength; - - // Column offset (in bytes) = to cluster number divided by 8 (since 8 bits per bytes) - offset += to->mVisCluster >> 3; - - // Get the right bit within the byte, i.e. bitwise 'and' with bit at remainder position - int result = *(mVisData.tableData + offset) & (1 << (to->mVisCluster & 7)); - - return (result != 0); - */ - - //return ((*(mVisData.tableData + from->mVisCluster * mVisData.rowLength + - // ((to->mVisCluster)>>3)) & (1 << ((to->mVisCluster) & 7))) != 0); - - return (*(mVisData.tableData + from->mVisCluster*mVisData.rowLength + - ((to->mVisCluster)>>3)) & (1 << ((to->mVisCluster) & 7))) != 0; - - } - //----------------------------------------------------------------------- - const BspNode* BspLevel::getRootNode(void) - { - return mRootNode; - } - //----------------------------------------------------------------------- - BspNode* BspLevel::findLeaf(const Vector3& point) const - { - BspNode* node = mRootNode; - - while (!node->isLeaf()) - { - node = node->getNextNode(point); - } - - return node; - - } - //----------------------------------------------------------------------- - void BspLevel::loadEntities(const Quake3Level& q3lvl) - { - char* strEnt; - String line; - StringVector vecparams; - Vector3 origin = Vector3::ZERO; - Radian angle ( 0 ); - size_t pos; - char* lineend; - bool isPlayerStart; - - isPlayerStart = false; - strEnt = (char*)q3lvl.mEntities; - - lineend = strchr(strEnt, '\n'); - while (lineend != 0) - { - *lineend = '\0'; - line = strEnt; - strEnt = lineend+1; - StringUtil::trim(line); - if (line.length() > 0) - { - StringUtil::toLowerCase(line); - // Remove quotes - while( ( pos = line.find('\"',0) ) != String::npos ) - { - line = line.substr(0,pos) + line.substr(pos+1,line.length()-(pos+1)); - } - vecparams = StringUtil::split(line); - StringVector::iterator params = vecparams.begin(); - - if (params[0] == "origin") - { - origin.x = static_cast(atof(params[1].c_str())); - origin.y = static_cast(atof(params[2].c_str())); - origin.z = static_cast(atof(params[3].c_str())); - } - if (params[0] == "angle") - { - angle = Degree(static_cast(atof(params[1].c_str()))); - } - if (params[0] == "classname" && params[1] == "info_player_deathmatch") - { - isPlayerStart = true; - } - if (params[0] == "}") - { - if (isPlayerStart) - { - // Save player start - ViewPoint vp; - vp.position = origin; - vp.orientation.FromAngleAxis(angle, Vector3::UNIT_Z); - mPlayerStarts.push_back(vp); - } - isPlayerStart = false; - } - } - - lineend = strchr(strEnt, '\n'); - } - - - } - //----------------------------------------------------------------------- - void BspLevel::_notifyObjectMoved(const MovableObject* mov, - const Vector3& pos) - { - - // Locate any current nodes the object is supposed to be attached to - MovableToNodeMap::iterator i = mMovableToNodeMap.find(mov); - if (i != mMovableToNodeMap.end()) - { - std::list::iterator nodeit, nodeitend; - nodeitend = i->second.end(); - for (nodeit = i->second.begin(); nodeit != nodeitend; ++nodeit) - { - // Tell each node - (*nodeit)->_removeMovable(mov); - } - // Clear the existing list of nodes because we'll reevaluate it - i->second.clear(); - } - - tagNodesWithMovable(mRootNode, mov, pos); - } - //----------------------------------------------------------------------- - void BspLevel::tagNodesWithMovable(BspNode* node, const MovableObject* mov, - const Vector3& pos) - { - if (node->isLeaf()) - { - // Add to movable->node map - // Insert all the time, will get current if already there - std::pair p = mMovableToNodeMap.emplace(mov, std::list()); - - p.first->second.push_back(node); - - // Add movable to node - node->_addMovable(mov); - - } - else - { - // Find distance to dividing plane - Real dist = node->getDistance(pos); - if (Math::Abs(dist) < mov->getBoundingRadius()) - { - // Bounding sphere crosses the plane, do both - tagNodesWithMovable(node->getBack(), mov, pos); - tagNodesWithMovable(node->getFront(), mov, pos); - } - else if (dist < 0) - { //----------------------------------------------------------------------- - - // Do back - tagNodesWithMovable(node->getBack(), mov, pos); - } - else - { - // Do front - tagNodesWithMovable(node->getFront(), mov, pos); - } - } - } - //----------------------------------------------------------------------- - void BspLevel::_notifyObjectDetached(const MovableObject* mov) - { - // Locate any current nodes the object is supposed to be attached to - MovableToNodeMap::iterator i = mMovableToNodeMap.find(mov); - if (i != mMovableToNodeMap.end()) - { - std::list::iterator nodeit, nodeitend; - nodeitend = i->second.end(); - for (nodeit = i->second.begin(); nodeit != nodeitend; ++nodeit) - { - // Tell each node - (*nodeit)->_removeMovable(mov); - } - // delete the entry for this MovableObject - mMovableToNodeMap.erase(i); - } - } - //----------------------------------------------------------------------- - void BspLevel::quakeVertexToBspVertex(const bsp_vertex_t* src, BspVertex* dest) - { - memcpy(dest->position, src->point, sizeof(float) * 3); - memcpy(dest->normal, src->normal, sizeof(float) * 3); - dest->colour = src->color; - dest->texcoords[0] = src->texture[0]; - dest->texcoords[1] = src->texture[1]; - dest->lightmap[0] = src->lightmap[0]; - dest->lightmap[1] = src->lightmap[1]; - } - //----------------------------------------------------------------------- - size_t BspLevel::calculateSize(void) const - { - return 0; // TODO - } -} diff --git a/PlugIns/BSPSceneManager/src/OgreBspNode.cpp b/PlugIns/BSPSceneManager/src/OgreBspNode.cpp deleted file mode 100644 index cc313e669e8..00000000000 --- a/PlugIns/BSPSceneManager/src/OgreBspNode.cpp +++ /dev/null @@ -1,204 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreBspNode.h" -#include "OgreBspLevel.h" -#include "OgreException.h" -#include "OgreLogManager.h" - -namespace Ogre { - - //----------------------------------------------------------------------- - BspNode::BspNode(BspLevel* owner, bool inIsLeaf) - { - mOwner = owner; - mIsLeaf = inIsLeaf; - } - - //----------------------------------------------------------------------- - BspNode::BspNode() - { - } - //----------------------------------------------------------------------- - BspNode::~BspNode() - { - } - - //----------------------------------------------------------------------- - bool BspNode::isLeaf(void) const - { - return mIsLeaf; - } - - //----------------------------------------------------------------------- - BspNode* BspNode::getFront(void) const - { - if (mIsLeaf) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "This method is not valid on a leaf node.", - "BspNode::getFront"); - return mFront; - } - - //----------------------------------------------------------------------- - BspNode* BspNode::getBack(void) const - { - if (mIsLeaf) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "This method is not valid on a leaf node.", - "BspNode::getBack"); - return mBack; - } - - //----------------------------------------------------------------------- - const Plane& BspNode::getSplitPlane(void) const - { - if (mIsLeaf) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "This method is not valid on a leaf node.", - "BspNode::getSplitPlane"); - - return mSplitPlane; - - } - - //----------------------------------------------------------------------- - const AxisAlignedBox& BspNode::getBoundingBox(void) const - { - if (!mIsLeaf) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "This method is only valid on a leaf node.", - "BspNode::getBoundingBox"); - return mBounds; - - } - - //----------------------------------------------------------------------- - int BspNode::getNumFaceGroups(void) const - { - if (!mIsLeaf) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "This method is only valid on a leaf node.", - "BspNode::getNumFaces"); - return mNumFaceGroups; - } - - //----------------------------------------------------------------------- - int BspNode::getFaceGroupStart(void) const - { - if (!mIsLeaf) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "This method is only valid on a leaf node.", - "BspNode::getFaces"); - return mFaceGroupStart; - } - - //----------------------------------------------------------------------- - bool BspNode::isLeafVisible(const BspNode* leaf) const - { - return mOwner->isLeafVisible(this, leaf); - } - //----------------------------------------------------------------------- - Plane::Side BspNode::getSide (const Vector3& point) const - { - if (mIsLeaf) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "This method is not valid on a leaf node.", - "BspNode::getSide"); - - return mSplitPlane.getSide(point); - - } - //----------------------------------------------------------------------- - BspNode* BspNode::getNextNode(const Vector3& point) const - { - - if (mIsLeaf) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "This method is not valid on a leaf node.", - "BspNode::getNextNode"); - - Plane::Side sd = getSide(point); - if (sd == Plane::NEGATIVE_SIDE) - { - //LogManager::getSingleton().logMessage("back"); - return getBack(); - } - else - { - //LogManager::getSingleton().logMessage("front"); - return getFront(); - } - - - - } - //----------------------------------------------------------------------- - void BspNode::_addMovable(const MovableObject* mov) - { - mMovables.insert(mov); - } - //----------------------------------------------------------------------- - void BspNode::_removeMovable(const MovableObject* mov) - { - mMovables.erase(mov); - } - //----------------------------------------------------------------------- - Real BspNode::getDistance(const Vector3& pos) const - { - if (mIsLeaf) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "This method is not valid on a leaf node.", - "BspNode::getSide"); - - return mSplitPlane.getDistance(pos); - - } - //----------------------------------------------------------------------- - const BspNode::NodeBrushList& BspNode::getSolidBrushes(void) const - { - return mSolidBrushes; - } - //----------------------------------------------------------------------- - std::ostream& operator<< (std::ostream& o, BspNode& n) - { - o << "BspNode("; - if (n.mIsLeaf) - { - o << "leaf, bbox=" << n.mBounds << ", cluster=" << n.mVisCluster; - o << ", faceGrps=" << n.mNumFaceGroups << ", faceStart=" << n.mFaceGroupStart << ")"; - } - else - { - o << "splitter, plane=" << n.mSplitPlane << ")"; - } - return o; - - } - -} diff --git a/PlugIns/BSPSceneManager/src/OgreBspSceneManager.cpp b/PlugIns/BSPSceneManager/src/OgreBspSceneManager.cpp deleted file mode 100644 index 7f443aa1314..00000000000 --- a/PlugIns/BSPSceneManager/src/OgreBspSceneManager.cpp +++ /dev/null @@ -1,789 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreBspSceneManager.h" -#include "OgreBspNode.h" -#include "OgreException.h" -#include "OgreRenderSystem.h" -#include "OgreCamera.h" -#include "OgreMaterial.h" -#include "OgrePatchSurface.h" -#include "OgreMesh.h" -#include "OgreSubMesh.h" -#include "OgreMath.h" -#include "OgreControllerManager.h" -#include "OgreLogManager.h" -#include "OgreBspSceneNode.h" -#include "OgreStringConverter.h" -#include "OgreLogManager.h" -#include "OgreTechnique.h" -#include "OgrePass.h" -#include "OgreMaterialManager.h" -#include "OgreCodec.h" -#include "OgreRoot.h" - -#include - -namespace Ogre { - - //----------------------------------------------------------------------- - BspSceneManager::BspSceneManager(const String& name) - : SceneManager(name) - { - // Set features for debugging render - mShowNodeAABs = false; - - mLevel.reset(); - - } - //----------------------------------------------------------------------- - const String& BspSceneManager::getTypeName(void) const - { - return BspSceneManagerFactory::FACTORY_TYPE_NAME; - } - //----------------------------------------------------------------------- - BspSceneManager::~BspSceneManager() {} - //----------------------------------------------------------------------- - size_t BspSceneManager::estimateWorldGeometry(const String& filename) - { - return BspLevel::calculateLoadingStages(filename); - - } - //----------------------------------------------------------------------- - size_t BspSceneManager::estimateWorldGeometry(DataStreamPtr& stream, - const String& typeName) - { - return BspLevel::calculateLoadingStages(stream); - - } - //----------------------------------------------------------------------- - void BspSceneManager::setWorldGeometry(const String& filename) - { - auto stream = Root::openFileStream( - filename, ResourceGroupManager::getSingleton().getWorldResourceGroupName()); - setWorldGeometry(stream); - } - //----------------------------------------------------------------------- - void BspSceneManager::setWorldGeometry(DataStreamPtr& stream, - const String& typeName) - { - Codec::getCodec("bsp")->decode(stream, getRootSceneNode()); - } - - void BspSceneManager::setLevel(const BspLevelPtr& level) - { - mLevel = level; - - if(!mLevel) - return; - - if (mLevel->isSkyEnabled()) - { - // Quake3 is always aligned with Z upwards - Quaternion q; - q.FromAngleAxis(Radian(Math::HALF_PI), Vector3::UNIT_X); - // Also draw last, and make close to camera (far clip plane is shorter) - setSkyDome(true, mLevel->getSkyMaterialName(), - mLevel->getSkyCurvature(), 12, 2000, false, q); - } - else - { - setSkyDome(false, BLANKSTRING); - } - } - //----------------------------------------------------------------------- - void BspSceneManager::_findVisibleObjects(Camera* cam, - VisibleObjectsBoundsInfo* visibleBounds, bool onlyShadowCasters) - { - // Clear unique list of movables for this frame - mMovablesForRendering.clear(); - - // Assemble an AAB on the fly which contains the scene elements visible - // by the camera. - CamVisibleObjectsMap::iterator findIt = mCamVisibleObjectsMap.find( cam ); - - // Walk the tree, tag static geometry, return camera's node (for info only) - // Movables are now added to the render queue in processVisibleLeaf - walkTree(cam, &(findIt->second), onlyShadowCasters); - } - //--------------------------------------------------------------------- - bool BspSceneManager::fireRenderQueueEnded(uint8 id, const String& invocation) - { - bool repeat = SceneManager::fireRenderQueueEnded(id, invocation); - // Trigger level render just after skies - // can't trigger on mWorldGeometryRenderQueue because we're not queueing there - if (id == RENDER_QUEUE_SKIES_EARLY) - { - renderStaticGeometry(); - } - return repeat; - - } - //----------------------------------------------------------------------- - void BspSceneManager::renderStaticGeometry(void) - { - // Check we should be rendering - if (!isRenderQueueToBeProcessed(getWorldGeometryRenderQueue())) - return; - - // For each material in turn, cache rendering data & render - MaterialFaceGroupMap::const_iterator mati; - for (mati = mMatFaceGroupMap.begin(); mati != mMatFaceGroupMap.end(); ++mati) - { - // Get Material - Material* thisMaterial = mati->first; - thisMaterial->touch(); - - // Skip if no faces to process (we're not doing flare types yet) - if (!mLevel->cacheGeometry(mati->second)) - continue; - - const Technique::Passes& passes = thisMaterial->getBestTechnique ()->getPasses(); - for (size_t p = 0; p < passes.size(); p++) - { - _injectRenderWithPass(passes[p], mLevel.get()); - } - - - } // for each material - - /* - if (mShowNodeAABs) - { - mDestRenderSystem->_render(mAABGeometry); - } - */ - } - //----------------------------------------------------------------------- - // REMOVE THIS CRAP - //----------------------------------------------------------------------- - // Temp debug lines - bool firstTime = true; - std::ofstream of; - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - BspNode* BspSceneManager::walkTree(Camera* camera, - VisibleObjectsBoundsInfo *visibleBounds, bool onlyShadowCasters) - { - if (!mLevel) return 0; - - // Locate the leaf node where the camera is located - BspNode* cameraNode = mLevel->findLeaf(camera->getDerivedPosition()); - - mMatFaceGroupMap.clear(); - mFaceGroupSet.clear(); - - // Scan through all the other leaf nodes looking for visibles - int i = mLevel->mNumNodes - mLevel->mLeafStart; - BspNode* nd = mLevel->mRootNode + mLevel->mLeafStart; - - /* - if (firstTime) - { - camera->getViewMatrix(); // Force update view before report - of.open("BspSceneManager.log"); - of << *camera << std::endl; - of << "Camera Node: " << *cameraNode << std::endl; - of << "Vertex Data: " << std::endl; - for (int testi = 0; testi < mLevel->mNumVertices; ++testi) - { - of << " " << testi << ": pos(" << - mLevel->mVertices[testi].position[0] << ", " << - mLevel->mVertices[testi].position[1] << ", " << mLevel->mVertices[testi].position[2] << ")" << - " uv(" << mLevel->mVertices[testi].texcoords[0] << ", " << mLevel->mVertices[testi].texcoords[1] << ")" << - " lm(" << mLevel->mVertices[testi].lightmap[0] << ", " << mLevel->mVertices[testi].lightmap[1] << ")" << std::endl; - } - of << "Element data:" << std::endl; - for (testi = 0; testi < mLevel->mNumElements; ++testi) - { - of << " " << testi << ": " << mLevel->mElements[testi] << std::endl; - - } - } - */ - - while (i--) - { - if (mLevel->isLeafVisible(cameraNode, nd)) - { - - // Visible according to PVS, check bounding box against frustum - FrustumPlane plane; - if (camera->isVisible(nd->getBoundingBox(), &plane)) - { - //if (firstTime) - //{ - // of << "Visible Node: " << *nd << std::endl; - //} - processVisibleLeaf(nd, camera, visibleBounds, onlyShadowCasters); - if (mShowNodeAABs) - addBoundingBox(nd->getBoundingBox(), true); - } - } - nd++; - } - - - // TEST - //if (firstTime) - //{ - // of.close(); - // firstTime = false; - //} - return cameraNode; - - } - //----------------------------------------------------------------------- - void BspSceneManager::processVisibleLeaf(BspNode* leaf, Camera* cam, - VisibleObjectsBoundsInfo* visibleBounds, bool onlyShadowCasters) - { - MaterialPtr pMat; - // Skip world geometry if we're only supposed to process shadow casters - // World is pre-lit - if (!onlyShadowCasters) - { - // Parse the leaf node's faces, add face groups to material map - int numGroups = leaf->getNumFaceGroups(); - int idx = leaf->getFaceGroupStart(); - - while (numGroups--) - { - int realIndex = mLevel->mLeafFaceGroups[idx++]; - // Check not already included - if (mFaceGroupSet.find(realIndex) != mFaceGroupSet.end()) - continue; - StaticFaceGroup* faceGroup = mLevel->mFaceGroups + realIndex; - // Get Material pointer by handle - pMat = static_pointer_cast(MaterialManager::getSingleton().getByHandle(faceGroup->materialHandle)); - assert (pMat); - // Check normal (manual culling) - ManualCullingMode cullMode = pMat->getTechnique(0)->getPass(0)->getManualCullingMode(); - if (cullMode != MANUAL_CULL_NONE) - { - Real dist = faceGroup->plane.getDistance(cam->getDerivedPosition()); - if ( (dist < 0 && cullMode == MANUAL_CULL_BACK) || - (dist > 0 && cullMode == MANUAL_CULL_FRONT) ) - continue; // skip - } - mFaceGroupSet.insert(realIndex); - // Try to insert, will find existing if already there - std::pair matgrpi; - matgrpi = mMatFaceGroupMap.emplace(pMat.get(), std::vector()); - // Whatever happened, matgrpi.first is map iterator - // Need to get second part of that to get vector - matgrpi.first->second.push_back(faceGroup); - - //if (firstTime) - //{ - // of << " Emitting faceGroup: index=" << realIndex << ", " << *faceGroup << std::endl; - //} - } - } - - // Add movables to render queue, provided it hasn't been seen already - const BspNode::IntersectingObjectSet& objects = leaf->getObjects(); - BspNode::IntersectingObjectSet::const_iterator oi, oiend; - oiend = objects.end(); - for (oi = objects.begin(); oi != oiend; ++oi) - { - if (mMovablesForRendering.find(*oi) == mMovablesForRendering.end()) - { - // It hasn't been seen yet - MovableObject *mov = const_cast(*oi); // hacky - - getRenderQueue()->processVisibleObject(mov, cam, onlyShadowCasters, visibleBounds); - - } - } - - - } - //----------------------------------------------------------------------- - void BspSceneManager::showNodeBoxes(bool show) - { - mShowNodeAABs = show; - } - //----------------------------------------------------------------------- - void BspSceneManager::addBoundingBox(const AxisAlignedBox& aab, bool visible) - { - /* - unsigned long visibleColour; - unsigned long nonVisibleColour; - Root& r = Root::getSingleton(); - - r.convertColourValue(ColourValue::White, &visibleColour); - r.convertColourValue(ColourValue::Blue, &nonVisibleColour); - if (mShowNodeAABs) - { - // Add set of lines - float* pVertices = (float*)mAABGeometry.pVertices + (mAABGeometry.numVertices*3); - unsigned short* pIndexes = mAABGeometry.pIndexes + mAABGeometry.numIndexes; - unsigned long* pColours = (unsigned long*)mAABGeometry.pDiffuseColour + mAABGeometry.numVertices; - - const Vector3* pCorner = aab.getAllCorners(); - - int i; - for (i = 0; i < 8; ++i) - { - *pVertices++ = pCorner->x; - *pVertices++ = pCorner->y; - *pVertices++ = pCorner->z; - pCorner++; - - if (visible) - { - *pColours++ = visibleColour; - } - else - { - *pColours++ = nonVisibleColour; - } - - } - - *pIndexes++ = 0 + mAABGeometry.numVertices; - *pIndexes++ = 1 + mAABGeometry.numVertices; - *pIndexes++ = 1 + mAABGeometry.numVertices; - *pIndexes++ = 2 + mAABGeometry.numVertices; - *pIndexes++ = 2 + mAABGeometry.numVertices; - *pIndexes++ = 3 + mAABGeometry.numVertices; - *pIndexes++ = 3 + mAABGeometry.numVertices; - *pIndexes++ = 1 + mAABGeometry.numVertices; - *pIndexes++ = 4 + mAABGeometry.numVertices; - *pIndexes++ = 5 + mAABGeometry.numVertices; - *pIndexes++ = 5 + mAABGeometry.numVertices; - *pIndexes++ = 6 + mAABGeometry.numVertices; - *pIndexes++ = 6 + mAABGeometry.numVertices; - *pIndexes++ = 7 + mAABGeometry.numVertices; - *pIndexes++ = 7 + mAABGeometry.numVertices; - *pIndexes++ = 4 + mAABGeometry.numVertices; - *pIndexes++ = 1 + mAABGeometry.numVertices; - *pIndexes++ = 5 + mAABGeometry.numVertices; - *pIndexes++ = 2 + mAABGeometry.numVertices; - *pIndexes++ = 4 + mAABGeometry.numVertices; - *pIndexes++ = 0 + mAABGeometry.numVertices; - *pIndexes++ = 6 + mAABGeometry.numVertices; - *pIndexes++ = 3 + mAABGeometry.numVertices; - *pIndexes++ = 7 + mAABGeometry.numVertices; - - - mAABGeometry.numVertices += 8; - mAABGeometry.numIndexes += 24; - - - } - */ - - } - //----------------------------------------------------------------------- - ViewPoint BspSceneManager::getSuggestedViewpoint(bool random) - { - if (!mLevel || mLevel->mPlayerStarts.empty()) - { - // No level, use default - return SceneManager::getSuggestedViewpoint(random); - } - else - { - if (random) - { - size_t idx = (size_t)( Math::UnitRandom() * mLevel->mPlayerStarts.size() ); - return mLevel->mPlayerStarts[idx]; - } - else - { - return mLevel->mPlayerStarts[0]; - } - - - } - - } - //----------------------------------------------------------------------- - SceneNode * BspSceneManager::createSceneNodeImpl( void ) - { - return OGRE_NEW BspSceneNode( this ); - } - //----------------------------------------------------------------------- - SceneNode * BspSceneManager::createSceneNodeImpl( const String &name ) - { - return OGRE_NEW BspSceneNode( this, name ); - } - //----------------------------------------------------------------------- - void BspSceneManager::_notifyObjectMoved(const MovableObject* mov, - const Vector3& pos) - { - if (mLevel) - { - mLevel->_notifyObjectMoved(mov, pos); - } - } - //----------------------------------------------------------------------- - void BspSceneManager::_notifyObjectDetached(const MovableObject* mov) - { - if (mLevel) - { - mLevel->_notifyObjectDetached(mov); - } - } - //----------------------------------------------------------------------- - void BspSceneManager::clearScene(void) - { - SceneManager::clearScene(); - // Clear level - mLevel.reset(); - } - //----------------------------------------------------------------------- - /* - AxisAlignedBoxSceneQuery* BspSceneManager:: - createAABBQuery(const AxisAlignedBox& box, unsigned long mask) - { - // TODO - return NULL; - } - //----------------------------------------------------------------------- - SphereSceneQuery* BspSceneManager:: - createSphereQuery(const Sphere& sphere, unsigned long mask) - { - // TODO - return NULL; - } - */ - //----------------------------------------------------------------------- - RaySceneQuery* BspSceneManager:: - createRayQuery(const Ray& ray, uint32 mask) - { - BspRaySceneQuery* q = OGRE_NEW BspRaySceneQuery(this); - q->setRay(ray); - q->setQueryMask(mask); - return q; - } - //----------------------------------------------------------------------- - IntersectionSceneQuery* BspSceneManager:: - createIntersectionQuery(uint32 mask) - { - BspIntersectionSceneQuery* q = OGRE_NEW BspIntersectionSceneQuery(this); - q->setQueryMask(mask); - return q; - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - BspIntersectionSceneQuery::BspIntersectionSceneQuery(SceneManager* creator) - : DefaultIntersectionSceneQuery(creator), mWorldFragmentType(WFT_NONE) - { - mSupportedWorldFragments.insert(WFT_NONE); - // Add bounds fragment type - mSupportedWorldFragments.insert(WFT_PLANE_BOUNDED_REGION); - } - void BspIntersectionSceneQuery::execute(IntersectionSceneQueryListener* listener) - { - /* - Go through each leaf node in BspLevel and check movables against each other and world - Issue: some movable-movable intersections could be reported twice if 2 movables - overlap 2 leaves? - */ - const BspLevelPtr& lvl = ((BspSceneManager*)mParentSceneMgr)->getLevel(); - if (!lvl) return; - - BspNode* leaf = lvl->getLeafStart(); - int numLeaves = lvl->getNumLeaves(); - - while (numLeaves--) - { - const BspNode::IntersectingObjectSet& objects = leaf->getObjects(); - int numObjects = (int)objects.size(); - - BspNode::IntersectingObjectSet::const_iterator a, b, theEnd; - theEnd = objects.end(); - a = objects.begin(); - for (int oi = 0; oi < numObjects; ++oi, ++a) - { - const MovableObject* aObj = *a; - // Skip this object if collision not enabled - if (!(aObj->getQueryFlags() & mQueryMask) || - !(aObj->getTypeFlags() & mQueryTypeMask) || - !aObj->isInScene()) - continue; - - if (oi < (numObjects-1)) - { - // Check object against others in this node - b = a; - for (++b; b != theEnd; ++b) - { - const MovableObject* bObj = *b; - // Apply mask to b (both must pass) - if ((bObj->getQueryFlags() & mQueryMask) && - (bObj->getTypeFlags() & mQueryTypeMask) && - bObj->isInScene()) - { - const AxisAlignedBox& box1 = aObj->getWorldBoundingBox(); - const AxisAlignedBox& box2 = bObj->getWorldBoundingBox(); - - if (box1.intersects(box2)) - { - if (!listener->queryResult(const_cast(aObj), - const_cast(bObj))) - return; - } - } - } - } - // Check object against brushes - if (mQueryTypeMask & SceneManager::WORLD_GEOMETRY_TYPE_MASK) - { - const BspNode::NodeBrushList& brushes = leaf->getSolidBrushes(); - BspNode::NodeBrushList::const_iterator bi, biend; - biend = brushes.end(); - Real radius = aObj->getBoundingRadius(); - const Vector3& pos = aObj->getParentNode()->_getDerivedPosition(); - - for (bi = brushes.begin(); bi != biend; ++bi) - { - std::vector::const_iterator planeit, planeitend; - planeitend = (*bi)->planes.end(); - bool brushIntersect = true; // Assume intersecting for now - - for (planeit = (*bi)->planes.begin(); planeit != planeitend; ++planeit) - { - Real dist = planeit->getDistance(pos); - if (dist > radius) - { - // Definitely excluded - brushIntersect = false; - break; - } - } - if (brushIntersect) - { - // report this brush as it's WorldFragment - assert((*bi)->fragment.fragmentType == WFT_PLANE_BOUNDED_REGION); - if (!listener->queryResult(const_cast(aObj), - const_cast(&((*bi)->fragment)))) - return; - } - - } - } - - - } - - ++leaf; - } - - - - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - BspRaySceneQuery::BspRaySceneQuery(SceneManager* creator) - :DefaultRaySceneQuery(creator), mWorldFragmentType(WFT_NONE) - { - // Add supported fragment types - mSupportedWorldFragments.insert(WFT_NONE); - mSupportedWorldFragments.insert(WFT_SINGLE_INTERSECTION); - mSupportedWorldFragments.insert(WFT_PLANE_BOUNDED_REGION); - } - //----------------------------------------------------------------------- - void BspRaySceneQuery::execute(RaySceneQueryListener* listener) - { - clearTemporaries(); - BspLevelPtr lvl = static_cast(mParentSceneMgr)->getLevel(); - if (lvl) - { - processNode( - lvl->getRootNode(), - mRay, listener); - } - } - //----------------------------------------------------------------------- - BspRaySceneQuery::~BspRaySceneQuery() - { - clearTemporaries(); - } - //----------------------------------------------------------------------- - void BspRaySceneQuery::clearTemporaries(void) - { - mObjsThisQuery.clear(); - std::vector::iterator i; - for (i = mSingleIntersections.begin(); i != mSingleIntersections.end(); ++i) - { - OGRE_FREE(*i, MEMCATEGORY_SCENE_CONTROL); - } - mSingleIntersections.clear(); - } - //----------------------------------------------------------------------- - bool BspRaySceneQuery::processNode(const BspNode* node, const Ray& tracingRay, - RaySceneQueryListener* listener, Real maxDistance, Real traceDistance) - { - if (node->isLeaf()) - { - return processLeaf(node, tracingRay, listener, maxDistance, traceDistance); - } - - bool res = true; - std::pair result = tracingRay.intersects(node->getSplitPlane()); - if (result.first && result.second < maxDistance) - { - // Crosses the split plane, need to perform 2 queries - // Calculate split point ray - Vector3 splitPoint = tracingRay.getOrigin() - + tracingRay.getDirection() * result.second; - Ray splitRay(splitPoint, tracingRay.getDirection()); - - if (node->getSide(tracingRay.getOrigin()) == Plane::NEGATIVE_SIDE) - { - // Intersects from -ve side, so do back then front - res = processNode( - node->getBack(), tracingRay, listener, result.second, traceDistance); - if (!res) return res; - - res = processNode( - node->getFront(), splitRay, listener, - maxDistance - result.second, - traceDistance + result.second); - } - else - { - // Intersects from +ve side, so do front then back - res = processNode(node->getFront(), tracingRay, listener, - result.second, traceDistance); - if (!res) return res; - res = processNode(node->getBack(), splitRay, listener, - maxDistance - result.second, - traceDistance + result.second); - } - } - else - { - // Does not cross the splitting plane, just cascade down one side - res = processNode(node->getNextNode(tracingRay.getOrigin()), - tracingRay, listener, maxDistance, traceDistance); - } - - return res; - } - //----------------------------------------------------------------------- - bool BspRaySceneQuery::processLeaf(const BspNode* leaf, const Ray& tracingRay, - RaySceneQueryListener* listener, Real maxDistance, Real traceDistance) - { - const BspNode::IntersectingObjectSet& objects = leaf->getObjects(); - - BspNode::IntersectingObjectSet::const_iterator i, iend; - iend = objects.end(); - //Check ray against objects - for(i = objects.begin(); i != iend; ++i) - { - // cast away constness, constness of node is nothing to do with objects - MovableObject* obj = const_cast(*i); - // Skip this object if not enabled - if(!(obj->getQueryFlags() & mQueryMask) || - !((obj->getTypeFlags() & mQueryTypeMask))) - continue; - - // check we haven't reported this one already - // (objects can be intersecting more than one node) - if (mObjsThisQuery.find(obj) != mObjsThisQuery.end()) - continue; - - //Test object as bounding box - std::pair result = - tracingRay.intersects(obj->getWorldBoundingBox()); - // if the result came back positive and intersection point is inside - // the node, fire the event handler - if(result.first && result.second <= maxDistance) - { - if (!listener->queryResult(obj, result.second + traceDistance)) - return false; - } - } - - - // Check ray against brushes - if (mQueryTypeMask & SceneManager::WORLD_GEOMETRY_TYPE_MASK) - { - const BspNode::NodeBrushList& brushList = leaf->getSolidBrushes(); - BspNode::NodeBrushList::const_iterator bi, biend; - biend = brushList.end(); - bool intersectedBrush = false; - for (bi = brushList.begin(); bi != biend; ++bi) - { - BspNode::Brush* brush = *bi; - - - std::pair result = Math::intersects(tracingRay, brush->planes, true); - // if the result came back positive and intersection point is inside - // the node, check if this brush is closer - if(result.first && result.second <= maxDistance) - { - intersectedBrush = true; - if(mWorldFragmentType == WFT_SINGLE_INTERSECTION) - { - // We're interested in a single intersection - // Have to create these - SceneQuery::WorldFragment* wf = OGRE_ALLOC_T(SceneQuery::WorldFragment, 1, MEMCATEGORY_SCENE_CONTROL); - wf->fragmentType = WFT_SINGLE_INTERSECTION; - wf->singleIntersection = tracingRay.getPoint(result.second); - // save this so we can clean up later - mSingleIntersections.push_back(wf); - if (!listener->queryResult(wf, result.second + traceDistance)) - return false; - } - else if (mWorldFragmentType == WFT_PLANE_BOUNDED_REGION) - { - // We want the whole bounded volume - assert((*bi)->fragment.fragmentType == WFT_PLANE_BOUNDED_REGION); - if (!listener->queryResult(const_cast(&(brush->fragment)), - result.second + traceDistance)) - return false; - - } - } - } - if (intersectedBrush) - { - return false; // stop here - } - } - - return true; - - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - const String BspSceneManagerFactory::FACTORY_TYPE_NAME = "BspSceneManager"; - //----------------------------------------------------------------------- - SceneManager* BspSceneManagerFactory::createInstance( - const String& instanceName) - { - return OGRE_NEW BspSceneManager(instanceName); - } - -} - diff --git a/PlugIns/BSPSceneManager/src/OgreBspSceneManagerDll.cpp b/PlugIns/BSPSceneManager/src/OgreBspSceneManagerDll.cpp deleted file mode 100644 index cee0273bd23..00000000000 --- a/PlugIns/BSPSceneManager/src/OgreBspSceneManagerDll.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreRoot.h" -#include "OgreBspSceneManagerPlugin.h" - -//----------------------------------------------------------------------- -#ifndef OGRE_STATIC_LIB -static Ogre::BspSceneManagerPlugin* bspPlugin; - -extern "C" void _OgreBspPluginExport dllStartPlugin(void); -extern "C" void _OgreBspPluginExport dllStopPlugin(void); - -extern "C" void _OgreBspPluginExport dllStartPlugin(void) -{ - // Create new scene manager - bspPlugin = OGRE_NEW Ogre::BspSceneManagerPlugin(); - - // Register - Ogre::Root::getSingleton().installPlugin(bspPlugin); - - -} -extern "C" void _OgreBspPluginExport dllStopPlugin(void) -{ - Ogre::Root::getSingleton().uninstallPlugin(bspPlugin); - OGRE_DELETE bspPlugin; -} -#endif diff --git a/PlugIns/BSPSceneManager/src/OgreBspSceneManagerPlugin.cpp b/PlugIns/BSPSceneManager/src/OgreBspSceneManagerPlugin.cpp deleted file mode 100644 index 1aafcc9bb12..00000000000 --- a/PlugIns/BSPSceneManager/src/OgreBspSceneManagerPlugin.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreBspSceneManagerPlugin.h" -#include "OgreRoot.h" -#include "OgreCodec.h" -#include "OgreQuake3ShaderManager.h" - -namespace Ogre -{ -namespace { - struct BspSceneCodec : public Codec - { - String magicNumberToFileExt(const char* magicNumberPtr, size_t maxbytes) const override { return ""; } - String getType() const override { return "bsp"; } - void decode(const DataStreamPtr& stream, const Any& output) const override - { - auto group = ResourceGroupManager::getSingleton().getWorldResourceGroupName(); - auto rootNode = any_cast(output); - BspSceneManager* mgr = dynamic_cast(rootNode->getCreator()); - - OgreAssert(mgr, "only loading into a BspSceneManager supported"); - OgreAssert(mgr->getRootSceneNode() == rootNode, "BspCodec only supports loading into RootSceneNode"); - - mgr->setLevel(BspLevelPtr()); // clear - - auto bspLevel = std::make_shared(nullptr, "bsplevel", 0, group, false, nullptr); - bspLevel->load(stream); - - mgr->setLevel(bspLevel); - } - }; -} - const String sPluginName = "BSP Scene Manager"; - //--------------------------------------------------------------------- - BspSceneManagerPlugin::BspSceneManagerPlugin() : mBspFactory(0) {} - BspSceneManagerPlugin::~BspSceneManagerPlugin() {} - //--------------------------------------------------------------------- - const String& BspSceneManagerPlugin::getName() const - { - return sPluginName; - } - //--------------------------------------------------------------------- - void BspSceneManagerPlugin::install() - { - // Create new scene manager - mBspFactory = OGRE_NEW BspSceneManagerFactory(); - - } - //--------------------------------------------------------------------- - void BspSceneManagerPlugin::initialise() - { - // Register (factory not dependent on rsys resources) - Root::getSingleton().addSceneManagerFactory(mBspFactory); - - // Also create related shader manager (singleton managed) - mShaderMgr = OGRE_NEW Quake3ShaderManager(); - - mCodec.reset(new BspSceneCodec()); - Codec::registerCodec(mCodec.get()); - } - //--------------------------------------------------------------------- - void BspSceneManagerPlugin::shutdown() - { - // Unregister SM factory - Root::getSingleton().removeSceneManagerFactory(mBspFactory); - - Codec::unregisterCodec(mCodec.get()); - mCodec.reset(); - - OGRE_DELETE mShaderMgr; - } - //--------------------------------------------------------------------- - void BspSceneManagerPlugin::uninstall() - { - - OGRE_DELETE mBspFactory; - mBspFactory = 0; - - } - - -} diff --git a/PlugIns/BSPSceneManager/src/OgreBspSceneNode.cpp b/PlugIns/BSPSceneManager/src/OgreBspSceneNode.cpp deleted file mode 100644 index fcb841fa084..00000000000 --- a/PlugIns/BSPSceneManager/src/OgreBspSceneNode.cpp +++ /dev/null @@ -1,109 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreBspSceneNode.h" -#include "OgreBspSceneManager.h" - -namespace Ogre { - - - void BspSceneNode::_update(bool updateChildren, bool parentHasChanged) - { - bool checkMovables = false; - - if (mNeedParentUpdate || parentHasChanged) - { - // This means we've moved - checkMovables = true; - } - - // Call superclass - SceneNode::_update(updateChildren, parentHasChanged); - - if (checkMovables) - { - // Check membership of attached objects - for (auto mov : getAttachedObjects()) - { - static_cast(getCreator())->_notifyObjectMoved( - mov, this->_getDerivedPosition()); - } - } - - } - //------------------------------------------------------------------------- - MovableObject* BspSceneNode::detachObject(unsigned short index) - { - MovableObject* ret = SceneNode::detachObject(index); - static_cast(getCreator())->_notifyObjectDetached(ret); - return ret; - - } - //------------------------------------------------------------------------- - MovableObject* BspSceneNode::detachObject(const String& name) - { - MovableObject* ret = SceneNode::detachObject(name); - static_cast(getCreator())->_notifyObjectDetached(ret); - return ret; - } - //------------------------------------------------------------------------- - void BspSceneNode::detachAllObjects(void) - { - for (auto o : getAttachedObjects()) - { - static_cast(getCreator()) - ->_notifyObjectDetached(o); - } - SceneNode::detachAllObjects(); - } - //------------------------------------------------------------------------- - void BspSceneNode::setInSceneGraph(bool inGraph) - { - if (isInSceneGraph() != inGraph) - { - for (auto o : getAttachedObjects()) - { - if (!inGraph) - { - // Equivalent to detaching - static_cast(getCreator())->_notifyObjectDetached(o); - } - else - { - // move deals with re-adding - static_cast(getCreator()) - ->_notifyObjectMoved(o, this->_getDerivedPosition()); - } - } - } - mIsInSceneGraph = inGraph; - } - -} - - - diff --git a/PlugIns/BSPSceneManager/src/OgreQuake3Level.cpp b/PlugIns/BSPSceneManager/src/OgreQuake3Level.cpp deleted file mode 100644 index 4b780910ba0..00000000000 --- a/PlugIns/BSPSceneManager/src/OgreQuake3Level.cpp +++ /dev/null @@ -1,261 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreQuake3Level.h" - -#include -#include "OgreLogManager.h" -#include "OgreTextureManager.h" - -namespace Ogre { - - //----------------------------------------------------------------------- - Quake3Level::Quake3Level() - { - - } - //----------------------------------------------------------------------- - void Quake3Level::loadHeaderFromStream(DataStreamPtr& inStream) - { - // Load just the header - mChunk = std::make_shared(sizeof(bsp_header_t)); - inStream->read(mChunk->getPtr(), sizeof(bsp_header_t)); - // Grab all the counts, header only - initialise(true); - } - //----------------------------------------------------------------------- - void Quake3Level::loadFromStream(const DataStreamPtr& stream) - { - mChunk = std::make_shared(stream); - initialise(); - -#if OGRE_DEBUG_MODE - dumpContents(); -#endif - - - } - -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - //----------------------------------------------------------------------- - // byte swapping functions - static void SwapFourBytes(uint32* dw) - { - uint32 tmp; - tmp = (*dw & 0x000000FF); - tmp = ((*dw & 0x0000FF00) >> 0x08) | (tmp << 0x08); - tmp = ((*dw & 0x00FF0000) >> 0x10) | (tmp << 0x08); - tmp = ((*dw & 0xFF000000) >> 0x18) | (tmp << 0x08); - memcpy (dw, &tmp, sizeof(uint32)); - } - //----------------------------------------------------------------------- - static void SwapFourBytesGrup (uint32* src, int size) - { - uint32* ptr = (uint32*)src; - int i; - for (i = 0; i < size/4; ++i) { - SwapFourBytes (&ptr[i]); - } - } -#endif - //----------------------------------------------------------------------- - void Quake3Level::initialise(bool headerOnly) - { - mHeader = (bsp_header_t*)mChunk->getPtr(); - - // Header counts - initialiseCounts(); - // Data pointers - if (headerOnly) - { - mLumpStart = 0; - } - else - { - mLumpStart = ((unsigned char*)mHeader) + sizeof(mHeader); - initialisePointers(); - } - - -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - // swap header - SwapFourBytes ((uint32*)&mHeader->version); -#endif - } - //----------------------------------------------------------------------- - void Quake3Level::initialiseCounts(void) - { - mNumEntities = getLumpSize(BSP_ENTITIES_LUMP); - mNumElements = getLumpSize(BSP_ELEMENTS_LUMP) / sizeof(int); - mNumFaces = getLumpSize(BSP_FACES_LUMP) / sizeof(bsp_face_t); - mNumLeafFaces = getLumpSize(BSP_LFACES_LUMP) / sizeof(int); - mNumLeaves = getLumpSize(BSP_LEAVES_LUMP) / sizeof(bsp_leaf_t); - mNumLightmaps = getLumpSize(BSP_LIGHTMAPS_LUMP)/BSP_LIGHTMAP_BANKSIZE; - mNumModels = getLumpSize(BSP_MODELS_LUMP) / sizeof(bsp_model_t); - mNumNodes = getLumpSize(BSP_NODES_LUMP) / sizeof(bsp_node_t); - mNumPlanes = getLumpSize(BSP_PLANES_LUMP)/sizeof(bsp_plane_t); - mNumShaders = getLumpSize(BSP_SHADERS_LUMP)/sizeof(bsp_shader_t); - mNumVertices = getLumpSize(BSP_VERTICES_LUMP)/sizeof(bsp_vertex_t); - mNumLeafBrushes = getLumpSize(BSP_LBRUSHES_LUMP)/sizeof(int); - mNumBrushes = getLumpSize(BSP_BRUSH_LUMP)/sizeof(bsp_brush_t); - mNumBrushSides = getLumpSize(BSP_BRUSHSIDES_LUMP)/sizeof(bsp_brushside_t); - } - //----------------------------------------------------------------------- - void Quake3Level::initialisePointers(void) - { - mEntities = (unsigned char*)getLump(BSP_ENTITIES_LUMP); - mElements = (int*)getLump(BSP_ELEMENTS_LUMP); - mFaces = (bsp_face_t*)getLump(BSP_FACES_LUMP); - mLeafFaces = (int*)getLump(BSP_LFACES_LUMP); - mLeaves = (bsp_leaf_t*)getLump(BSP_LEAVES_LUMP); - mLightmaps = (unsigned char*)getLump(BSP_LIGHTMAPS_LUMP); - mModels = (bsp_model_t*)getLump(BSP_MODELS_LUMP); - mNodes = (bsp_node_t*)getLump(BSP_NODES_LUMP); - mPlanes = (bsp_plane_t*) getLump(BSP_PLANES_LUMP); - mShaders = (bsp_shader_t*) getLump(BSP_SHADERS_LUMP); - mVis = (bsp_vis_t*)getLump(BSP_VISIBILITY_LUMP); - mVertices = (bsp_vertex_t*) getLump(BSP_VERTICES_LUMP); - mLeafBrushes = (int*)getLump(BSP_LBRUSHES_LUMP); - mBrushes = (bsp_brush_t*) getLump(BSP_BRUSH_LUMP); - mBrushSides = (bsp_brushside_t*) getLump(BSP_BRUSHSIDES_LUMP); -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - SwapFourBytesGrup ((uint32*)mElements, mNumElements*sizeof(int)); - SwapFourBytesGrup ((uint32*)mFaces, mNumFaces*sizeof(bsp_face_t)); - SwapFourBytesGrup ((uint32*)mLeafFaces, mNumLeafFaces*sizeof(int)); - SwapFourBytesGrup ((uint32*)mLeaves, mNumLeaves*sizeof(bsp_leaf_t)); - SwapFourBytesGrup ((uint32*)mModels, mNumModels*sizeof(bsp_model_t)); - SwapFourBytesGrup ((uint32*)mNodes, mNumNodes*sizeof(bsp_node_t)); - SwapFourBytesGrup ((uint32*)mPlanes, mNumPlanes*sizeof(bsp_plane_t)); - for (int i=0; i < mNumShaders; ++i) { - SwapFourBytes((uint32*)&mShaders[i].surface_flags); - SwapFourBytes((uint32*)&mShaders[i].content_flags); - } - SwapFourBytes((uint32*)&mVis->cluster_count); - SwapFourBytes((uint32*)&mVis->row_size); - SwapFourBytesGrup ((uint32*)mVertices, mNumVertices*sizeof(bsp_vertex_t)); - SwapFourBytesGrup ((uint32*)mLeafBrushes, mNumLeafBrushes*sizeof(int)); - SwapFourBytesGrup ((uint32*)mBrushes, mNumBrushes*sizeof(bsp_brush_t)); - SwapFourBytesGrup ((uint32*)mBrushSides, mNumBrushSides*sizeof(bsp_brushside_t)); -#endif - } - //----------------------------------------------------------------------- - void* Quake3Level::getLump(int lumpType) - { - if (mLumpStart) - { - -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - // swap lump offset - SwapFourBytes ((uint32*)&mHeader->lumps[lumpType].offset); -#endif - return (unsigned char*)mHeader + mHeader->lumps[lumpType].offset; - } - else - { - return 0; - } - } - //----------------------------------------------------------------------- - int Quake3Level::getLumpSize(int lumpType) - { - -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - // swap lump size - SwapFourBytes ((uint32*)&mHeader->lumps[lumpType].size); -#endif - return mHeader->lumps[lumpType].size; - } - //----------------------------------------------------------------------- - void Quake3Level::dumpContents(void) - { - std::ofstream of; - of.open("Quake3Level.log"); - - - of << "Quake3 level statistics" << std::endl; - of << "-----------------------" << std::endl; - of << "Entities : " << mNumEntities << std::endl; - of << "Faces : " << mNumFaces << std::endl; - of << "Leaf Faces : " << mNumLeafFaces << std::endl; - of << "Leaves : " << mNumLeaves << std::endl; - of << "Lightmaps : " << mNumLightmaps << std::endl; - of << "Elements : " << mNumElements << std::endl; - of << "Models : " << mNumModels << std::endl; - of << "Nodes : " << mNumNodes << std::endl; - of << "Planes : " << mNumPlanes << std::endl; - of << "Shaders : " << mNumShaders << std::endl; - of << "Vertices : " << mNumVertices << std::endl; - of << "Vis Clusters : " << mVis->cluster_count << std::endl; - - of << std::endl; - of << "-= Shaders =-"; - of << std::endl; - for (int i = 0; i < mNumShaders; ++i) - { - of << "Shader " << i << ": " << mShaders[i].name << std::endl; - } - - of << std::endl; - of << "-= Entities =-"; - of << std::endl; - char* strEnt = strtok((char*)mEntities, "\0"); - while (strEnt != 0) - { - of << strEnt << std::endl; - strEnt = strtok(0, "\0"); - } - - - - - of.close(); - } - //----------------------------------------------------------------------- - void Quake3Level::extractLightmaps(void) const - { - // Lightmaps are always 128x128x24 (RGB) - unsigned char* pLightmap = mLightmaps; - for (int i = 0; i < mNumLightmaps; ++i) - { - StringStream name; - name << "@lightmap" << i; - - // Load, no mipmaps, brighten by factor 2.5 - DataStreamPtr stream(OGRE_NEW MemoryDataStream(pLightmap, 128 * 128 * 3, false)); - Image img; - img.loadRawData( stream, 128, 128, 1, PF_BYTE_RGB ); - TextureManager::getSingleton().loadImage( name.str(), - ResourceGroupManager::getSingleton().getWorldResourceGroupName(), img, TEX_TYPE_2D, 0, 4.0f ); - pLightmap += BSP_LIGHTMAP_BANKSIZE; - } - - - } - //----------------------------------------------------------------------- - - -} diff --git a/PlugIns/BSPSceneManager/src/OgreQuake3Shader.cpp b/PlugIns/BSPSceneManager/src/OgreQuake3Shader.cpp deleted file mode 100644 index 460781b9758..00000000000 --- a/PlugIns/BSPSceneManager/src/OgreQuake3Shader.cpp +++ /dev/null @@ -1,279 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreQuake3Shader.h" -#include "OgreSceneManager.h" -#include "OgreMaterial.h" -#include "OgreTechnique.h" -#include "OgrePass.h" -#include "OgreTextureUnitState.h" -#include "OgreMath.h" -#include "OgreLogManager.h" -#include "OgreTextureManager.h" -#include "OgreRoot.h" -#include "OgreMaterialManager.h" - -namespace Ogre { - - - //----------------------------------------------------------------------- - Quake3Shader::Quake3Shader(const String& name) - { - mName = name; - numPasses = 0; - deformFunc = DEFORM_FUNC_NONE; - farbox = false; - skyDome = false; - flags = 0; - fog = false; - cullMode = MANUAL_CULL_BACK; - - } - //----------------------------------------------------------------------- - Quake3Shader::~Quake3Shader() - { - } - //----------------------------------------------------------------------- - MaterialPtr Quake3Shader::createAsMaterial(int lightmapNumber) - { - String matName; - StringStream str; - String resourceGroup = ResourceGroupManager::getSingleton().getWorldResourceGroupName(); - - str << mName << "#" << lightmapNumber; - matName = str.str(); - - MaterialPtr mat = MaterialManager::getSingleton().create(matName, - resourceGroup); - Ogre::Pass* ogrePass = mat->getTechnique(0)->getPass(0); - - LogManager::getSingleton().logMessage("Using Q3 shader " + mName, LML_TRIVIAL); - for (int p = 0; p < numPasses; ++p) - { - TextureUnitState* t; - // Create basic texture - if (pass[p].textureName == "$lightmap") - { - StringStream str2; - str2 << "@lightmap" << lightmapNumber; - t = ogrePass->createTextureUnitState(str2.str()); - } - // Animated texture support - else if (pass[p].animNumFrames > 0) - { - Real sequenceTime = pass[p].animNumFrames / pass[p].animFps; - /* Pre-load textures - We need to know if each one was loaded OK since extensions may change for each - Quake3 can still include alternate extension filenames e.g. jpg instead of tga - Pain in the arse - have to check for each frame as letters.tga for example - is different per frame! - */ - for (unsigned int alt = 0; alt < pass[p].animNumFrames; ++alt) - { - if (!ResourceGroupManager::getSingleton().resourceExists( - resourceGroup, pass[p].frames[alt])) - { - // Try alternate extension - pass[p].frames[alt] = getAlternateName(pass[p].frames[alt]); - if (!ResourceGroupManager::getSingleton().resourceExists( - resourceGroup, pass[p].frames[alt])) - { - // stuffed - no texture - continue; - } - } - - } - - t = ogrePass->createTextureUnitState(""); - t->setAnimatedTextureName(pass[p].frames, pass[p].animNumFrames, sequenceTime); - - } - else - { - // Quake3 can still include alternate extension filenames e.g. jpg instead of tga - // Pain in the arse - have to check for failure - if (!ResourceGroupManager::getSingleton().resourceExists( - resourceGroup, pass[p].textureName)) - { - // Try alternate extension - pass[p].textureName = getAlternateName(pass[p].textureName); - if (!ResourceGroupManager::getSingleton().resourceExists( - resourceGroup, pass[p].textureName)) - { - // stuffed - no texture - continue; - } - } - t = ogrePass->createTextureUnitState(pass[p].textureName); - } - // Blending - if (p == 0) - { - // scene blend - mat->setSceneBlending(pass[p].blendSrc, pass[p].blendDest); - if (mat->isTransparent()) - mat->setDepthWriteEnabled(false); - - t->setColourOperation(LBO_REPLACE); - // Alpha mode - ogrePass->setAlphaRejectSettings( - pass[p].alphaFunc, pass[p].alphaVal); - } - else - { - if (pass[p].customBlend) - { - // Fallback for now - t->setColourOperation(LBO_MODULATE); - } - else - { - // simple layer blend - t->setColourOperation(pass[p].blend); - } - // Alpha mode, prefer 'most alphary' - CompareFunction currFunc = ogrePass->getAlphaRejectFunction(); - unsigned char currVal = ogrePass->getAlphaRejectValue(); - if (pass[p].alphaFunc > currFunc || - (pass[p].alphaFunc == currFunc && pass[p].alphaVal < currVal)) - { - ogrePass->setAlphaRejectSettings( - pass[p].alphaFunc, pass[p].alphaVal); - } - } - // Tex coords - if (pass[p].texGen == TEXGEN_BASE) - { - t->setTextureCoordSet(0); - } - else if (pass[p].texGen == TEXGEN_LIGHTMAP) - { - t->setTextureCoordSet(1); - } - else if (pass[p].texGen == TEXGEN_ENVIRONMENT) - { - t->setEnvironmentMap(true, TextureUnitState::ENV_CURVED); - } - // Tex mod - // Scale - t->setTextureUScale(pass[p].tcModScale[0]); - t->setTextureVScale(pass[p].tcModScale[1]); - // Procedural mods - // Custom - don't use mod if generating environment - // Because I do env a different way it look horrible - if (pass[p].texGen != TEXGEN_ENVIRONMENT) - { - if (pass[p].tcModRotate) - { - t->setRotateAnimation(pass[p].tcModRotate); - } - if (pass[p].tcModScroll[0] || pass[p].tcModScroll[1]) - { - if (pass[p].tcModTurbOn) - { - // Turbulent scroll - if (pass[p].tcModScroll[0]) - { - t->setTransformAnimation(TextureUnitState::TT_TRANSLATE_U, WFT_SINE, - pass[p].tcModTurb[0], pass[p].tcModTurb[3], pass[p].tcModTurb[2], pass[p].tcModTurb[1]); - } - if (pass[p].tcModScroll[1]) - { - t->setTransformAnimation(TextureUnitState::TT_TRANSLATE_V, WFT_SINE, - pass[p].tcModTurb[0], pass[p].tcModTurb[3], pass[p].tcModTurb[2], pass[p].tcModTurb[1]); - } - } - else - { - // Constant scroll - t->setScrollAnimation(pass[p].tcModScroll[0], pass[p].tcModScroll[1]); - } - } - if (pass[p].tcModStretchWave != SHADER_FUNC_NONE) - { - WaveformType wft = WFT_SINE; - switch(pass[p].tcModStretchWave) - { - case SHADER_FUNC_SIN: - wft = WFT_SINE; - break; - case SHADER_FUNC_TRIANGLE: - wft = WFT_TRIANGLE; - break; - case SHADER_FUNC_SQUARE: - wft = WFT_SQUARE; - break; - case SHADER_FUNC_SAWTOOTH: - wft = WFT_SAWTOOTH; - break; - case SHADER_FUNC_INVERSESAWTOOTH: - wft = WFT_INVERSE_SAWTOOTH; - break; - default: - break; - } - // Create wave-based stretcher - t->setTransformAnimation(TextureUnitState::TT_SCALE_U, wft, pass[p].tcModStretchParams[3], - pass[p].tcModStretchParams[0], pass[p].tcModStretchParams[2], pass[p].tcModStretchParams[1]); - t->setTransformAnimation(TextureUnitState::TT_SCALE_V, wft, pass[p].tcModStretchParams[3], - pass[p].tcModStretchParams[0], pass[p].tcModStretchParams[2], pass[p].tcModStretchParams[1]); - } - } - // Address mode - t->setTextureAddressingMode(pass[p].addressMode); - - //assert(!t->isBlank()); - - - } - // Do farbox (create new material) - - // Set culling mode and lighting to defaults - mat->setCullingMode(CULL_NONE); - mat->setManualCullingMode(cullMode); - mat->setLightingEnabled(false); - mat->load(); - return mat; - } - String Quake3Shader::getAlternateName(const String& texName) - { - // Get alternative JPG to TGA and vice versa - String ext, base; - StringUtil::splitBaseFilename(texName, base, ext); - if (StringUtil::endsWith(ext, "jpg")) - { - return base + ".tga"; - } - else - { - return base + ".jpg"; - } - - } -} diff --git a/PlugIns/BSPSceneManager/src/OgreQuake3ShaderManager.cpp b/PlugIns/BSPSceneManager/src/OgreQuake3ShaderManager.cpp deleted file mode 100644 index 5952810893d..00000000000 --- a/PlugIns/BSPSceneManager/src/OgreQuake3ShaderManager.cpp +++ /dev/null @@ -1,511 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreQuake3ShaderManager.h" -#include "OgreQuake3Shader.h" -#include "OgreStringVector.h" -#include "OgreException.h" - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -// we do lots of conversions here, casting them all is tedious & cluttered, we know what we're doing -# pragma warning (disable : 4244) -#endif - -namespace Ogre { - - //----------------------------------------------------------------------- - template<> Quake3ShaderManager *Singleton::msSingleton = 0; - Quake3ShaderManager* Quake3ShaderManager::getSingletonPtr(void) - { - return msSingleton; - } - Quake3ShaderManager& Quake3ShaderManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //----------------------------------------------------------------------- - - //----------------------------------------------------------------------- - Quake3ShaderManager::Quake3ShaderManager() - { - mScriptPatterns.push_back("*.shader"); - ResourceGroupManager::getSingleton()._registerScriptLoader(this); - } - //----------------------------------------------------------------------- - Quake3ShaderManager::~Quake3ShaderManager() - { - // delete all shaders - clear(); - ResourceGroupManager::getSingleton()._unregisterScriptLoader(this); - } - //----------------------------------------------------------------------- - const StringVector& Quake3ShaderManager::getScriptPatterns(void) const - { - return mScriptPatterns; - } - //----------------------------------------------------------------------- - Real Quake3ShaderManager::getLoadingOrder(void) const - { - return 110.0f; - } - //----------------------------------------------------------------------- - void Quake3ShaderManager::clear(void) - { - for (auto & i : mShaderMap) - { - OGRE_DELETE i.second; - } - mShaderMap.clear(); - } - //----------------------------------------------------------------------- - Quake3Shader* Quake3ShaderManager::getByName(const String& name) - { - Quake3ShaderMap::iterator i = mShaderMap.find(name); - if (i == mShaderMap.end()) - { - return 0; - } - return i->second; - } - //----------------------------------------------------------------------- - void Quake3ShaderManager::parseScript(DataStreamPtr& stream, const String& group) - { - String line; - Quake3Shader* pShader; - char tempBuf[512]; - - pShader = 0; - bool dummy = false; - - while(!stream->eof()) - { - line = stream->getLine(); - // Ignore comments & blanks - if (!(line.length() == 0 || line.substr(0,2) == "//")) - { - if (pShader == 0) - { - // No current shader - if (getByName(line) == 0) - { - dummy = false; - } - else - { - // Defined before, parse but ignore - // Q3A has duplicates in shaders, doh - dummy = true; - } - - // So first valid data should be a shader name - pShader = create(line); - // Skip to and over next { - stream->readLine(tempBuf, 511, "{"); - } - else - { - // Already in a shader - if (line == "}") - { - // Finished shader - if (dummy && pShader) - { - OGRE_DELETE pShader; - } - pShader = 0; - } - else if (line == "{") - { - // new pass - parseNewShaderPass(stream, pShader); - - } - else - { - // Attribute - StringUtil::toLowerCase(line); - parseShaderAttrib(line, pShader); - } - - } - - } - - - } - - } - //----------------------------------------------------------------------- - Quake3Shader* Quake3ShaderManager::create( const String& name) - { - // Gah, Q3A shader scripts include some duplicates - grr - Quake3Shader* s = OGRE_NEW Quake3Shader(name); - if (mShaderMap.find(name) == mShaderMap.end()) - { - mShaderMap[name] = s; - } - else - { - // deliberately ignore, will get parsed again but will not be used - } - return s; - } - //----------------------------------------------------------------------- - void Quake3ShaderManager::parseNewShaderPass(DataStreamPtr& stream, Quake3Shader* pShader) - { - String line; - int passIdx; - - passIdx = pShader->numPasses; - pShader->numPasses++; - pShader->pass.resize(pShader->numPasses); - - // Default pass details - pShader->pass[passIdx].animNumFrames = 0; - pShader->pass[passIdx].blend = LBO_REPLACE; - pShader->pass[passIdx].blendDest = SBF_ZERO; - pShader->pass[passIdx].blendSrc = SBF_ONE; - pShader->pass[passIdx].depthFunc = CMPF_LESS_EQUAL; - pShader->pass[passIdx].flags = 0; - pShader->pass[passIdx].rgbGenFunc = SHADER_GEN_IDENTITY; - pShader->pass[passIdx].tcModRotate = 0; - pShader->pass[passIdx].tcModScale[0] = pShader->pass[passIdx].tcModScale[1] = 1.0; - pShader->pass[passIdx].tcModScroll[0] = pShader->pass[passIdx].tcModScroll[1] = 0; - pShader->pass[passIdx].tcModStretchWave = SHADER_FUNC_NONE; - pShader->pass[passIdx].tcModTransform[0] = pShader->pass[passIdx].tcModTransform[1] = 0; - pShader->pass[passIdx].tcModTurbOn = false; - pShader->pass[passIdx].tcModTurb[0] = pShader->pass[passIdx].tcModTurb[1] = - pShader->pass[passIdx].tcModTurb[2] = pShader->pass[passIdx].tcModTurb[3] = 0; - pShader->pass[passIdx].texGen = TEXGEN_BASE; - pShader->pass[passIdx].addressMode = TextureUnitState::TAM_WRAP; - pShader->pass[passIdx].customBlend = false; - pShader->pass[passIdx].alphaVal = 0; - pShader->pass[passIdx].alphaFunc = CMPF_ALWAYS_PASS; - - while (!stream->eof()) - { - line = stream->getLine(); - // Ignore comments & blanks - if (line.length() != 0 && line.substr(0,2) != "//") - { - if (line == "}") - { - // end of shader - return; - } - else - { - parseShaderPassAttrib(line, pShader, &pShader->pass[passIdx]); - } - } - - - } - } - //----------------------------------------------------------------------- - void Quake3ShaderManager::parseShaderAttrib( const String& line, Quake3Shader* pShader) - { - StringVector vecparams; - - vecparams = StringUtil::split(line, " \t"); - StringVector::iterator params = vecparams.begin(); - - if (params[0] == "skyparms") - { - if (params[1] != "-") - { - pShader->farbox = true; - pShader->farboxName = params[1]; - } - if (params[2] != "-") - { - pShader->skyDome = true; - pShader->cloudHeight = atof(params[2].c_str()); - } - // nearbox not supported - } - else if (params[0] == "cull") - { - if (params[1] == "disable" || params[1] == "none") - { - pShader->cullMode = MANUAL_CULL_NONE; - } - else if (params[1] == "front") - { - pShader->cullMode = MANUAL_CULL_FRONT; - } - else if (params[1] == "back") - { - pShader->cullMode = MANUAL_CULL_BACK; - } - } - else if (params[0] == "deformvertexes") - { - // TODO - } - else if (params[0] == "fogparms") - { - Real r,g,b; - r = atof(params[1].c_str()); - g = atof(params[2].c_str()); - b = atof(params[3].c_str()); - pShader->fog = true; - pShader->fogColour = ColourValue(r,g,b); - pShader->fogDistance = atof(params[4].c_str()); - - } - } - //----------------------------------------------------------------------- - void Quake3ShaderManager::parseShaderPassAttrib( const String& line, Quake3Shader* pShader, Quake3Shader::Pass* pPass) - { - StringVector vecparams; - - vecparams = StringUtil::split(line, " \t"); - StringVector::iterator params = vecparams.begin(); - - StringUtil::toLowerCase(params[0]); - if (params[0] != "map" && params[0] != "clampmap" && params[0] != "animmap") - { - // lower case all except textures - for (size_t i = 1; i < vecparams.size(); ++i) - StringUtil::toLowerCase(params[i]); - } - - - // MAP - if (params[0] == "map") - { - pPass->textureName = params[1]; - StringUtil::toLowerCase(params[1]); - if (params[1] == "$lightmap") - pPass->texGen = TEXGEN_LIGHTMAP; - } - // CLAMPMAP - if (params[0] == "clampmap") - { - pPass->textureName = params[1]; - StringUtil::toLowerCase(params[1]); - if (params[1] == "$lightmap") - pPass->texGen = TEXGEN_LIGHTMAP; - pPass->addressMode = TextureUnitState::TAM_CLAMP; - } - // ANIMMAP - else if (params[0] == "animmap") - { - pPass->animFps = atof(params[1].c_str()); - pPass->animNumFrames = static_cast( vecparams.size() - 2 ); - for (unsigned int frame = 0; frame < pPass->animNumFrames; ++frame) - { - pPass->frames[frame] = params[frame+2]; - } - } - // BLENDFUNC - else if (params[0] == "blendfunc") - { - if (params[1] == "add" || params[1] == "gl_add") - { - pPass->blend = LBO_ADD; - pPass->blendDest = SBF_ONE; - pPass->blendSrc = SBF_ONE; - } - else if (params[1] == "filter" || params[1] == "gl_filter") - { - pPass->blend = LBO_MODULATE; - pPass->blendDest = SBF_ZERO; - pPass->blendSrc = SBF_DEST_COLOUR; - } - else if (params[1] == "blend" || params[1] == "gl_blend") - { - pPass->blend = LBO_ALPHA_BLEND; - pPass->blendDest = SBF_ONE_MINUS_SOURCE_ALPHA; - pPass->blendSrc = SBF_SOURCE_ALPHA; - } - else - { - // Manual blend - pPass->blendSrc = convertBlendFunc(params[1]); - pPass->blendDest = convertBlendFunc(params[2]); - // Detect common blends - if (pPass->blendSrc == SBF_ONE && pPass->blendDest == SBF_ZERO) - pPass->blend = LBO_REPLACE; - else if (pPass->blendSrc == SBF_ONE && pPass->blendDest == SBF_ONE) - pPass->blend = LBO_ADD; - else if ((pPass->blendSrc == SBF_ZERO && pPass->blendDest == SBF_SOURCE_COLOUR) || - (pPass->blendSrc == SBF_DEST_COLOUR && pPass->blendDest == SBF_ZERO)) - pPass->blend = LBO_MODULATE; - else if (pPass->blendSrc == SBF_SOURCE_ALPHA && pPass->blendDest == SBF_ONE_MINUS_SOURCE_ALPHA) - pPass->blend = LBO_ALPHA_BLEND; - else - pPass->customBlend = true; - - - // NB other custom blends might not work due to OGRE trying to use multitexture over multipass - } - } - // RGBGEN - else if (params[0] == "rgbgen") - { - // TODO - } - // ALPHAGEN - else if (params[0] == "alphagen") - { - // TODO - } - // TCGEN - else if (params[0] == "tcgen") - { - if (params[1] == "base") - { - pPass->texGen = TEXGEN_BASE; - } - else if (params[1] == "lightmap") - { - pPass->texGen = TEXGEN_LIGHTMAP; - } - else if (params[1] == "environment") - { - pPass->texGen = TEXGEN_ENVIRONMENT; - } - } - // TCMOD - else if (params[0] == "tcmod") - { - if (params[1] == "rotate") - { - pPass->tcModRotate = -atof(params[2].c_str()) / 360; // +ve is clockwise degrees in Q3 shader, anticlockwise complete rotations in Ogre - } - else if (params[1] == "scroll") - { - pPass->tcModScroll[0] = atof(params[2].c_str()); - pPass->tcModScroll[1] = atof(params[3].c_str()); - } - else if (params[1] == "scale") - { - pPass->tcModScale[0] = atof(params[2].c_str()); - pPass->tcModScale[1] = atof(params[3].c_str()); - } - else if (params[1] == "stretch") - { - if (params[2] == "sin") - pPass->tcModStretchWave = SHADER_FUNC_SIN; - else if (params[2] == "triangle") - pPass->tcModStretchWave = SHADER_FUNC_TRIANGLE; - else if (params[2] == "square") - pPass->tcModStretchWave = SHADER_FUNC_SQUARE; - else if (params[2] == "sawtooth") - pPass->tcModStretchWave = SHADER_FUNC_SAWTOOTH; - else if (params[2] == "inversesawtooth") - pPass->tcModStretchWave = SHADER_FUNC_INVERSESAWTOOTH; - - pPass->tcModStretchParams[0] = atof(params[3].c_str()); - pPass->tcModStretchParams[1] = atof(params[4].c_str()); - pPass->tcModStretchParams[2] = atof(params[5].c_str()); - pPass->tcModStretchParams[3] = atof(params[6].c_str()); - - } - } - // TURB - else if (params[0] == "turb") - { - pPass->tcModTurbOn = true; - pPass->tcModTurb[0] = atof(params[2].c_str()); - pPass->tcModTurb[1] = atof(params[3].c_str()); - pPass->tcModTurb[2] = atof(params[4].c_str()); - pPass->tcModTurb[3] = atof(params[5].c_str()); - } - // DEPTHFUNC - else if (params[0] == "depthfunc") - { - // TODO - } - // DEPTHWRITE - else if (params[0] == "depthwrite") - { - // TODO - } - // ALPHAFUNC - else if (params[0] == "alphafunc") - { - if (params[1] == "gt0") - { - pPass->alphaVal = 0; - pPass->alphaFunc = CMPF_GREATER; - } - else if (params[1] == "ge128") - { - pPass->alphaVal = 128; - pPass->alphaFunc = CMPF_GREATER_EQUAL; - } - else if (params[1] == "lt128") - { - pPass->alphaVal = 128; - pPass->alphaFunc = CMPF_LESS; - } - } - - - - } - //----------------------------------------------------------------------- - SceneBlendFactor Quake3ShaderManager::convertBlendFunc( const String& q3func) - { - if (q3func == "gl_one") - { - return SBF_ONE; - } - else if (q3func == "gl_zero") - { - return SBF_ZERO; - } - else if (q3func == "gl_dst_color") - { - return SBF_DEST_COLOUR; - } - else if (q3func == "gl_src_color") - { - return SBF_SOURCE_COLOUR; - } - else if (q3func == "gl_one_minus_dst_color") - { - return SBF_ONE_MINUS_DEST_COLOUR; - } - else if (q3func == "gl_src_alpha") - { - return SBF_SOURCE_ALPHA; - } - else if (q3func == "gl_one_minus_src_alpha") - { - return SBF_ONE_MINUS_SOURCE_ALPHA; - } - - // Default if unrecognised - return SBF_ONE; - - } - -} diff --git a/PlugIns/CMakeLists.txt b/PlugIns/CMakeLists.txt deleted file mode 100644 index 2569da71f9d..00000000000 --- a/PlugIns/CMakeLists.txt +++ /dev/null @@ -1,65 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure Plugins build - -if (OGRE_BUILD_PLUGIN_OCTREE) - add_subdirectory(OctreeSceneManager) -endif (OGRE_BUILD_PLUGIN_OCTREE) - -if (OGRE_BUILD_PLUGIN_BSP) - add_subdirectory(BSPSceneManager) -endif (OGRE_BUILD_PLUGIN_BSP) - -if (OGRE_BUILD_PLUGIN_CG) - if (NOT Cg_FOUND) - message(STATUS "Could not find dependency: Cg") - message(STATUS "Skipping Plugin_CgProgramManager") - set(OGRE_BUILD_PLUGIN_CG 0) - else (NOT Cg_FOUND) - add_subdirectory(CgProgramManager) - endif (NOT Cg_FOUND) -endif (OGRE_BUILD_PLUGIN_CG) - -if (OGRE_BUILD_PLUGIN_EXRCODEC) - add_subdirectory(EXRCodec) -endif (OGRE_BUILD_PLUGIN_EXRCODEC) - -if(OGRE_BUILD_PLUGIN_STBI) - add_subdirectory(STBICodec) -endif() - -if(OGRE_BUILD_PLUGIN_FREEIMAGE) - add_subdirectory(FreeImageCodec) -endif() - -if (OGRE_BUILD_PLUGIN_PFX) - add_subdirectory(ParticleFX) -endif (OGRE_BUILD_PLUGIN_PFX) - -if (OGRE_BUILD_PLUGIN_PCZ) - add_subdirectory(PCZSceneManager) - add_subdirectory(OctreeZone) -endif (OGRE_BUILD_PLUGIN_PCZ) - -if (OGRE_BUILD_PLUGIN_DOT_SCENE) - add_subdirectory(DotScene) -endif () - -if (OGRE_BUILD_PLUGIN_ASSIMP) - add_subdirectory(Assimp) -endif () - -if (OGRE_BUILD_PLUGIN_GLSLANG) - add_subdirectory(GLSLang) -endif() - -if (OGRE_BUILD_PLUGIN_RSIMAGE) - add_subdirectory(RsImageCodec) -endif() \ No newline at end of file diff --git a/PlugIns/CgProgramManager/CMakeLists.txt b/PlugIns/CgProgramManager/CMakeLists.txt deleted file mode 100644 index 9f1e9c08b35..00000000000 --- a/PlugIns/CgProgramManager/CMakeLists.txt +++ /dev/null @@ -1,27 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure CgProgramManager build - -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") - -add_definitions(-DOGRE_CGPLUGIN_EXPORTS ${OGRE_VISIBILITY_FLAGS}) - -add_library(Plugin_CgProgramManager ${OGRE_LIB_TYPE} ${HEADER_FILES} ${SOURCE_FILES}) -target_link_libraries(Plugin_CgProgramManager OgreMain ${Cg_LIBRARIES}) -target_include_directories(Plugin_CgProgramManager PUBLIC - "$" - $ - PRIVATE ${Cg_INCLUDE_DIRS}) - -ogre_config_framework(Plugin_CgProgramManager) - -ogre_config_plugin(Plugin_CgProgramManager) -install(FILES ${HEADER_FILES} DESTINATION include/OGRE/Plugins/CgProgramManager) diff --git a/PlugIns/CgProgramManager/include/OgreCgFxScriptLoader.h b/PlugIns/CgProgramManager/include/OgreCgFxScriptLoader.h deleted file mode 100644 index aab07609937..00000000000 --- a/PlugIns/CgProgramManager/include/OgreCgFxScriptLoader.h +++ /dev/null @@ -1,1520 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __CgFxScriptLoader_H__ -#define __CgFxScriptLoader_H__ - -#include "OgrePrerequisites.h" -#include "OgreSingleton.h" -#include "OgreStringVector.h" -#include "OgreScriptLoader.h" -#include "OgreCgPrerequisites.h" -#include "OgreTexture.h" -#include "OgreTextureUnitState.h" -#include "OgreGpuProgram.h" - -namespace Ogre { - /** \addtogroup Plugins Plugins - * @{ - */ - /** \defgroup CgProgramManager CgProgramManager - * Specialisation of HighLevelGpuProgram to provide support for nVidia's CG language. - * @{ - */ - - /** Manages Overlay objects, parsing them from .overlay files and - storing a lookup library of them. Alo manages the creation of - OverlayContainers and OverlayElements, used for non-interactive 2D - elements such as HUDs. - */ - class CgFxScriptLoader : public Singleton, public ScriptLoader, public ScriptCompilerAlloc - { - public: - protected: - /** We want to comply to FXCompositor - this list is the enum FXComposer.Core.FXSemanticID - that existing in C:\\Program Files\\NVIDIA Corporation\\FX Composer 2.5\\FXComposer.Core.dll - if you reference if from managed project you can see the list. - description is from C:\\Program Files\\NVIDIA Corporation\\FX Composer 2.5\\Plugins\\scene\\render\\Data\\fxmapping.xml (open with a text editor and not with the browser) - and from C:\\Program Files\\NVIDIA Corporation\\FX Composer 2.5\\FXComposer.Core.xml - */ - enum FXSemanticID - { - FXS_NONE, - FXS_UNKNOWN, - FXS_POSITION, // desc="A position vector." datatypes="float3" - FXS_DIRECTION, // desc="A direction vector." datatypes="float3" - FXS_COLOR, - FXS_DIFFUSE, // desc="Color value to be used as the diffuse color. The fourth channel represents diffuse alpha." datatypes="float4,float3,texture" - FXS_SPECULAR, // desc="Color value to be used as the specular color. The fourth channel represents specular alpha." datatypes="float4,float3,texture" - FXS_AMBIENT, // desc="Color value to be used as the ambient color. The fourth channel represents ambient alpha." datatypes="float4,float3,texture" - FXS_EMISSION, - FXS_EMISSIVE, // desc="Color value to be used as the emissive color. The fourth channel represents emissive alpha." datatypes="float4,float3,texture" - FXS_SPECULARPOWER, // desc="Power to use for the specular exponent." datatypes="float,float3,float4" - FXS_REFRACTION, // desc="A refraction map that give the coefficents to determine the norma for an environment map lookup" datatypes="texture" - FXS_OPACITY, // desc="Opacity of the object." datatypes="texture" - FXS_ENVIRONMENT, // desc="An environment map." datatypes="texture" - FXS_ENVIRONMENTNORMAL, // name="environmentnormal" desc="An environment normal map." datatypes="texture" - FXS_NORMAL, // desc="Normal for the element or texture" datatypes="texture" - FXS_HEIGHT, // desc="Height for the element when using bump mapping." datatypes="texture" - FXS_ATTENUATION, // desc="Light attenuation." datatypes="float3" - FXS_RENDERCOLORTARGET, // desc="Defines the texture as the render target of a pass in the effect." datatypes="texture" - FXS_RENDERDEPTHSTENCILTARGET, // desc="Defines the texture as the render target of a pass in the effect." datatypes="texture" - FXS_VIEWPORTPIXELSIZE, // desc="Size of the viewport in pixels" datatypes="float2" - FXS_CAMERAPOSITION, // desc="Viewer position in world space (replaced by position with space=view annotation)." datatypes="float3" - FXS_TIME, // desc="The current time (see units annotation for scale)." datatypes="float" - FXS_ELAPSEDTIME, // desc="The time between adjacent frames (see units annotation for scale)." datatypes="float" - FXS_ANIMATIONTIME, - FXS_ANIMATIONTICK, - FXS_MOUSEPOSITION, // desc="The mouse position on screen (x,y,time)" datatypes="float3" - FXS_LEFTMOUSEDOWN, // desc="The left mouse down state, and its position at that time ( x, y, isdown, timedown)" datatypes="float4" - FXS_WORLD, // desc="world-inverse matrix." datatypes="matrix" - FXS_VIEW, // desc="view matrix." datatypes="matrix" - FXS_PROJECTION, // desc="projection matrix." datatypes="matrix" - FXS_WORLDTRANSPOSE, // desc="world-transpose matrix." datatypes="matrix" - FXS_VIEWTRANSPOSE, // name="worldviewtranspose" desc="world-view-transpose matrix." datatypes="matrix" - FXS_PROJECTIONTRANSPOSE, // name="viewprojectiontranspose" desc="view-projection-transpose matrix." datatypes="matrix" - FXS_WORLDVIEW, // desc="world-view matrix." datatypes="matrix" - FXS_WORLDVIEWPROJECTION, // desc="world-view-projection matrix." datatypes="matrix" - FXS_WORLDINVERSE, //desc="world-inverse matrix." datatypes="matrix" - FXS_VIEWINVERSE, // desc="view-inverse matrix." datatypes="matrix" - FXS_PROJECTIONINVERSE, // desc="projection-inverse matrix." datatypes="matrix" - FXS_WORLDINVERSETRANSPOSE, // desc="world-inverse-transpose matrix." datatypes="matrix" - FXS_VIEWINVERSETRANSPOSE, // desc="view-inverse-transpose matrix." datatypes="matrix" - FXS_PROJECTIONINVERSETRANSPOSE, // desc="projection-inverse-transpose matrix." datatypes="matrix" - FXS_WORLDVIEWINVERSE, // desc="world-view-inverse matrix." datatypes="matrix" - FXS_WORLDVIEWTRANSPOSE, // desc="world-view-transpose matrix." datatypes="matrix" - FXS_WORLDVIEWINVERSETRANSPOSE, // desc="world-view-inverse-transpose matrix." datatypes="matrix" - FXS_WORLDVIEWPROJECTIONINVERSE, // desc="world-view-projection-inverse matrix." datatypes="matrix" - FXS_WORLDVIEWPROJECTIONTRANSPOSE, - FXS_WORLDVIEWPROJECTIONINVERSETRANSPOSE, // name="worldviewprojectioninversetranspose" desc="world-view-projection-inverse-transpose matrix." datatypes="matrix" - FXS_VIEWPROJECTION, // desc="view-projection matrix." datatypes="matrix" - FXS_VIEWPROJECTIONTRANSPOSE, // desc="view-projection-transpose matrix." datatypes="matrix" - FXS_VIEWPROJECTIONINVERSE, // desc="world-view-projection-inverse matrix." datatypes="matrix" - FXS_VIEWPROJECTIONINVERSETRANSPOSE, // desc="world-view-projection-inverse-transpose matrix." datatypes="matrix" - FXS_FXCOMPOSER_RESETPULSE, // desc="A pulsed boolean, reset on window resize or from the FX Composer user interface." datatypes="bool" - FXS_STANDARDSGLOBAL, // desc="Standards version and global annotations" datatypes="float" - FXS_UNITSSCALE, // desc="Defines the modeling proportions to the current unit/space." datatypes="float" - FXS_POWER, // Power factor - FXS_DIFFUSEMAP, // A diffuse texture map - FXS_SPECULARMAP, // A specular texture map - FXS_ENVMAP, // An env map - FXS_LIGHTPOSITION, // light position - FXS_TRANSFORM, // A transform - FXS_USER, // User Semantics - Semantics Remapper Special - FXS_CONSTANTATTENUATION, - FXS_LINEARATTENUATION, - FXS_QUADRATICATTENUATION, - FXS_FALLOFFANGLE, - FXS_FALLOFFEXPONENT, - FXS_BOUNDINGRADIUS - }; - - enum GlobalStateType - { - GST_UNKNOWN, - GST_ALPHABLENDENABLE, //AlphaBlendEnable - GST_ALPHAFUNC, //AlphaFunc - GST_ALPHAREF, //AlphaRef - GST_BLENDOP, //BlendOp - GST_BLENDEQUATION, //BlendEquation - GST_BLENDFUNC, //BlendFunc - GST_BLENDFUNCSEPARATE, //BlendFuncSeparate - GST_BLENDEQUATIONSEPARATE, //BlendEquationSeparate - GST_BLENDCOLOR, //BlendColor - GST_CLEARCOLOR, //ClearColor - GST_CLEARSTENCIL, //ClearStencil - GST_CLEARDEPTH, //ClearDepth - GST_CLIPPLANE, //ClipPlane - GST_CLIPPLANEENABLE, //ClipPlaneEnable - GST_COLORWRITEENABLE, //ColorWriteEnable - GST_COLORMASK, //ColorMask - GST_COLORVERTEX, //ColorVertex - GST_COLORMATERIAL, //ColorMaterial - GST_COLORMATRIX, //ColorMatrix - GST_COLORTRANSFORM, //ColorTransform - GST_CULLFACE, //CullFace - GST_CULLMODE, //CullMode - GST_DEPTHBOUNDS, //DepthBounds - GST_DEPTHBIAS, //DepthBias - GST_DESTBLEND, //DestBlend - GST_DEPTHFUNC, //DepthFunc - GST_ZFUNC, //ZFunc - GST_DEPTHMASK, //DepthMask - GST_ZWRITEENABLE, //ZWriteEnable - GST_DEPTHRANGE, //DepthRange - GST_FOGDISTANCEMODE, //FogDistanceMode - GST_FOGMODE, //FogMode - GST_FOGTABLEMODE, //FogTableMode - GST_INDEXEDVERTEXBLENDENABLE, //IndexedVertexBlendEnable - GST_FOGDENSITY, //FogDensity - GST_FOGSTART, //FogStart - GST_FOGEND, //FogEnd - GST_FOGCOLOR, //FogColor - GST_FRAGMENTENVPARAMETER, //FragmentEnvParameter - GST_FRAGMENTLOCALPARAMETER, //FragmentLocalParameter - GST_FOGCOORDSRC, //FogCoordSrc - GST_FOGVERTEXMODE, //FogVertexMode - GST_FRONTFACE, //FrontFace - GST_LIGHTMODELAMBIENT, //LightModelAmbient - GST_AMBIENT, //Ambient - GST_LIGHTINGENABLE, //LightingEnable - GST_LIGHTENABLE, //LightEnable - GST_LIGHTAMBIENT, //LightAmbient - GST_LIGHTCONSTANTATTENUATION, //LightConstantAttenuation - GST_LIGHTATTENUATION0, //LightAttenuation0 - GST_LIGHTDIFFUSE, //LightDiffuse - GST_LIGHTLINEARATTENUATION, //LightLinearAttenuation - GST_LIGHTATTENUATION1, //LightAttenuation1 - GST_LIGHTPOSITION, //LightPosition - GST_LIGHTQUADRATICATTENUATION, //LightQuadraticAttenuation - GST_LIGHTATTENUATION2, //LightAttenuation2 - GST_LIGHTSPECULAR, //LightSpecular - GST_LIGHTSPOTCUTOFF, //LightSpotCutoff - GST_LIGHTFALLOFF, //LightFalloff - GST_LIGHTSPOTDIRECTION, //LightSpotDirection - GST_LIGHTDIRECTION, //LightDirection - GST_LIGHTSPOTEXPONENT, //LightSpotExponent - GST_LIGHTPHI, //LightPhi - GST_LIGHTRANGE, //LightRange - GST_LIGHTTHETA, //LightTheta - GST_LIGHTTYPE, //LightType - GST_LOCALVIEWER, //LocalViewer - GST_MULTISAMPLEANTIALIAS, //MultiSampleAntialias - GST_MULTISAMPLEMASK, //MultiSampleMask - GST_PATCHSEGMENTS, //PatchSegments - GST_POINTSCALE_A, //PointScale_A - GST_POINTSCALE_B, //PointScale_B - GST_POINTSCALE_C, //PointScale_C - GST_POINTSCALEENABLE, //PointScaleEnable - GST_RANGEFOGENABLE, //RangeFogEnable - GST_SPECULARENABLE, //SpecularEnable - GST_TWEENFACTOR, //TweenFactor - GST_VERTEXBLEND, //VertexBlend - GST_AMBIENTMATERIALSOURCE, //AmbientMaterialSource - GST_DIFFUSEMATERIALSOURCE, //DiffuseMaterialSource - GST_EMISSIVEMATERIALSOURCE, //EmissiveMaterialSource - GST_SPECULARMATERIALSOURCE, //SpecularMaterialSource - GST_CLIPPING, //Clipping - GST_LIGHTMODELCOLORCONTROL, //LightModelColorControl - GST_LINESTIPPLE, //LineStipple - GST_LINEWIDTH, //LineWidth - GST_LOGICOP, //LogicOp - GST_MATERIALAMBIENT, //MaterialAmbient - GST_MATERIALDIFFUSE, //MaterialDiffuse - GST_MATERIALEMISSION, //MaterialEmission - GST_MATERIALEMISSIVE, //MaterialEmissive - GST_MATERIALSHININESS, //MaterialShininess - GST_MATERIALPOWER, //MaterialPower - GST_MATERIALSPECULAR, //MaterialSpecular - GST_MODELVIEWMATRIX, //ModelViewMatrix - GST_MODELVIEWTRANSFORM, //ModelViewTransform - GST_VIEWTRANSFORM, //ViewTransform - GST_WORLDTRANSFORM, //WorldTransform - GST_POINTDISTANCEATTENUATION, //PointDistanceAttenuation - GST_POINTFADETHRESHOLDSIZE, //PointFadeThresholdSize - GST_POINTSIZE, //PointSize - GST_POINTSIZEMIN, //PointSizeMin - GST_POINTSIZEMAX, //PointSizeMax - GST_POINTSPRITECOORDORIGIN, //PointSpriteCoordOrigin - GST_POINTSPRITECOORDREPLACE, //PointSpriteCoordReplace - GST_POINTSPRITERMODE, //PointSpriteRMode - GST_POLYGONMODE, //PolygonMode - GST_FILLMODE, //FillMode - GST_LASTPIXEL, //LastPixel - GST_POLYGONOFFSET, //PolygonOffset - GST_PROJECTIONMATRIX, //ProjectionMatrix - GST_PROJECTIONTRANSFORM, //ProjectionTransform - GST_SCISSOR, //Scissor - GST_SHADEMODEL, //ShadeModel - GST_SHADEMODE, //ShadeMode - GST_SLOPSCALEDEPTHBIAS, //SlopScaleDepthBias - GST_SRCBLEND, //SrcBlend - GST_STENCILFUNC, //StencilFunc - GST_STENCILMASK, //StencilMask - GST_STENCILPASS, //StencilPass - GST_STENCILREF, //StencilRef - GST_STENCILWRITEMASK, //StencilWriteMask - GST_STENCILZFAIL, //StencilZFail - GST_TEXTUREFACTOR, //TextureFactor - GST_STENCILOP, //StencilOp - GST_STENCILFUNCSEPARATE, //StencilFuncSeparate - GST_STENCILMASKSEPARATE, //StencilMaskSeparate - GST_STENCILOPSEPARATE, //StencilOpSeparate - GST_TEXGENSMODE, //TexGenSMode - GST_TEXGENSOBJECTPLANE, //TexGenSObjectPlane - GST_TEXGENSEYEPLANE, //TexGenSEyePlane - GST_TEXGENTMODE, //TexGenTMode - GST_TEXGENTOBJECTPLANE, //TexGenTObjectPlane - GST_TEXGENTEYEPLANE, //TexGenTEyePlane - GST_TEXGENRMODE, //TexGenRMode - GST_TEXGENROBJECTPLANE, //TexGenRObjectPlane - GST_TEXGENREYEPLANE, //TexGenREyePlane - GST_TEXGENQMODE, //TexGenQMode - GST_TEXGENQOBJECTPLANE, //TexGenQObjectPlane - GST_TEXGENQEYEPLANE, //TexGenQEyePlane - GST_TEXTUREENVCOLOR, //TextureEnvColor - GST_TEXTUREENVMODE, //TextureEnvMode - GST_TEXTURE1D, //Texture1D - GST_TEXTURE2D, //Texture2D - GST_TEXTURE3D, //Texture3D - GST_TEXTURERECTANGLE, //TextureRectangle - GST_TEXTURECUBEMAP, //TextureCubeMap - GST_TEXTURE1DENABLE, //Texture1DEnable - GST_TEXTURE2DENABLE, //Texture2DEnable - GST_TEXTURE3DENABLE, //Texture3DEnable - GST_TEXTURERECTANGLEENABLE, //TextureRectangleEnable - GST_TEXTURECUBEMAPENABLE, //TextureCubeMapEnable - GST_TEXTURETRANSFORM, //TextureTransform - GST_TEXTUREMATRIX, //TextureMatrix - GST_VERTEXENVPARAMETER, //VertexEnvParameter - GST_VERTEXLOCALPARAMETER, //VertexLocalParameter - GST_ALPHATESTENABLE, //AlphaTestEnable - GST_AUTONORMALENABLE, //AutoNormalEnable - GST_BLENDENABLE, //BlendEnable - GST_COLORLOGICOPENABLE, //ColorLogicOpEnable - GST_CULLFACEENABLE, //CullFaceEnable - GST_DEPTHBOUNDSENABLE, //DepthBoundsEnable - GST_DEPTHCLAMPENABLE, //DepthClampEnable - GST_DEPTHTESTENABLE, //DepthTestEnable - GST_ZENABLE, //ZEnable - GST_DITHERENABLE, //DitherEnable - GST_FOGENABLE, //FogEnable - GST_LIGHTMODELLOCALVIEWERENABLE, //LightModelLocalViewerEnable - GST_LIGHTMODELTWOSIDEENABLE, //LightModelTwoSideEnable - GST_LINESMOOTHENABLE, //LineSmoothEnable - GST_LINESTIPPLEENABLE, //LineStippleEnable - GST_LOGICOPENABLE, //LogicOpEnable - GST_MULTISAMPLEENABLE, //MultisampleEnable - GST_NORMALIZEENABLE, //NormalizeEnable - GST_POINTSMOOTHENABLE, //PointSmoothEnable - GST_POINTSPRITEENABLE, //PointSpriteEnable - GST_POLYGONOFFSETFILLENABLE, //PolygonOffsetFillEnable - GST_POLYGONOFFSETLINEENABLE, //PolygonOffsetLineEnable - GST_POLYGONOFFSETPOINTENABLE, //PolygonOffsetPointEnable - GST_POLYGONSMOOTHENABLE, //PolygonSmoothEnable - GST_POLYGONSTIPPLEENABLE, //PolygonStippleEnable - GST_RESCALENORMALENABLE, //RescaleNormalEnable - GST_SAMPLEALPHATOCOVERAGEENABLE, //SampleAlphaToCoverageEnable - GST_SAMPLEALPHATOONEENABLE, //SampleAlphaToOneEnable - GST_SAMPLECOVERAGEENABLE, //SampleCoverageEnable - GST_SCISSORTESTENABLE, //ScissorTestEnable - GST_STENCILTESTENABLE, //StencilTestEnable - GST_STENCILENABLE, //StencilEnable - GST_STENCILTESTTWOSIDEENABLE, //StencilTestTwoSideEnable - GST_STENCILFAIL, //StencilFail - GST_TEXGENSENABLE, //TexGenSEnable - GST_TEXGENTENABLE, //TexGenTEnable - GST_TEXGENRENABLE, //TexGenREnable - GST_TEXGENQENABLE, //TexGenQEnable - GST_WRAP0, //Wrap0 - GST_WRAP1, //Wrap1 - GST_WRAP2, //Wrap2 - GST_WRAP3, //Wrap3 - GST_WRAP4, //Wrap4 - GST_WRAP5, //Wrap5 - GST_WRAP6, //Wrap6 - GST_WRAP7, //Wrap7 - GST_WRAP8, //Wrap8 - GST_WRAP9, //Wrap9 - GST_WRAP10, //Wrap10 - GST_WRAP11, //Wrap11 - GST_WRAP12, //Wrap12 - GST_WRAP13, //Wrap13 - GST_WRAP14, //Wrap14 - GST_WRAP15, //Wrap15 - GST_VERTEXPROGRAMPOINTSIZEENABLE, //VertexProgramPointSizeEnable - GST_VERTEXPROGRAMTWOSIDEENABLE, //VertexProgramTwoSideEnable - GST_GEOMETRYPROGRAM, //GeometryProgram - GST_VERTEXPROGRAM, //VertexProgram - GST_FRAGMENTPROGRAM, //FragmentProgram - GST_VERTEXSHADER, //VertexShader - GST_PIXELSHADER, //PixelShader - GST_ALPHAOP, //AlphaOp - GST_ALPHAARG0, //AlphaArg0 - GST_ALPHAARG1, //AlphaArg1 - GST_ALPHAARG2, //AlphaArg2 - GST_COLORARG0, //ColorArg0 - GST_COLORARG1, //ColorArg1 - GST_COLORARG2, //ColorArg2 - GST_COLOROP, //ColorOp - GST_BUMPENVLSCALE, //BumpEnvLScale - GST_BUMPENVLOFFSET, //BumpEnvLOffset - GST_BUMPENVMAT00, //BumpEnvMat00 - GST_BUMPENVMAT01, //BumpEnvMat01 - GST_BUMPENVMAT10, //BumpEnvMat10 - GST_BUMPENVMAT11, //BumpEnvMat11 - GST_RESULTARG, //ResultArg - GST_TEXCOORDINDEX, //TexCoordIndex - GST_TEXTURETRANSFORMFLAGS, //TextureTransformFlags - GST_TWOSIDEDSTENCILMODE, // TwoSidedStencilMode - GST_SEPARATEALPHABLENDENABLE, // SeparateAlphaBlendEnable - GST_NORMALIZENORMALS, // NormalizeNormals - GST_LIGHTING, // Lighting - GST_PIXELSHADERCONSTANTB, // PixelShaderConstantB - GST_VERTEXSHADERCONSTANTB, // VertexShaderConstantB - GST_COLORWRITEENABLE1, // ColorWriteEnable1 - GST_COLORWRITEENABLE2, // ColorWriteEnable2 - GST_COLORWRITEENABLE3, // ColorWriteEnable3 - GST_PIXELSHADERCONSTANT1, // PixelShaderConstant1 - GST_VERTEXSHADERCONSTANT1, // VertexShaderConstant1 - GST_PIXELSHADERCONSTANTF, // PixelShaderConstantF - GST_VERTEXSHADERCONSTANTF, // VertexShaderConstantF - GST_PIXELSHADERCONSTANT2, // PixelShaderConstant2 - GST_VERTEXSHADERCONSTANT2, // VertexShaderConstant2 - GST_PIXELSHADERCONSTANT3, // PixelShaderConstant3 - GST_VERTEXSHADERCONSTANT3, // VertexShaderConstant3 - GST_PIXELSHADERCONSTANT, // PixelShaderConstant - GST_VERTEXSHADERCONSTANT, // VertexShaderConstant - GST_PIXELSHADERCONSTANT4, // PixelShaderConstant4 - GST_VERTEXSHADERCONSTANT4, // VertexShaderConstant4 - GST_PIXELSHADERCONSTANTI, // PixelShaderConstantI - GST_VERTEXSHADERCONSTANTI, // VertexShaderConstantI - GST_SAMPLER, // Sampler - GST_TEXTURE, // Texture - - GST_ADDRESSU, // AddressU - GST_ADDRESSV, // AddressV - GST_ADDRESSW, // AddressW - GST_BORDERCOLOR, // BorderColor - GST_MAXANISOTROPY, // MaxAnisotropy - GST_MAXMIPLEVEL, // MaxMipLevel - GST_MINFILTER, // MinFilter - GST_MAGFILTER, // MagFilter - GST_MIPFILTER, // MipFilter - GST_MIPMAPLODBIAS, // MipMapLodBias - GST_BLENDOPALPHA, // BlendOpAlpha - GST_SRCBLENDALPHA, // SrcBlendAlpha - GST_DESTBLENDALPHA, // DestBlendAlpha - - - GST_COUNT - }; -#define GST_FIRST (GlobalStateType) (GST_UNKNOWN + (GlobalStateType)1) - - enum SamplerStateType - { - SST_UNKNOWN, - SST_TEXTURE, // Texture - SST_ADDRESSU, // AddressU - SST_ADDRESSV, // AddressV - SST_ADDRESSW, // AddressW - SST_WRAPS, // WrapS - SST_WRAPT, // WrapT - SST_WRAPR, // WrapR - SST_MIPFILTER, // MipFilter - SST_MIPMAPLODBIAS, // MipMapLodBias - SST_LODBIAS, // LODBias - SST_SRGBTEXTURE, // SRGBTexture - SST_MINFILTER, // MinFilter - SST_MAGFILTER, // MagFilter - SST_BORDERCOLOR, // BorderColor - SST_MINMIPLEVEL, // MinMipLevel - SST_MAXMIPLEVEL, // MaxMipLevel - SST_MAXANISOTROPY, // MaxAnisotropy - SST_DEPTHMODE, // DepthMode - SST_COMPAREMODE, // CompareMode - SST_COMPAREFUNC, // CompareFunc - SST_GENERATEMIPMAP, // GenerateMipmap - SST_COUNT - }; - -#define SST_FIRST (SamplerStateType) (SST_UNKNOWN + (SamplerStateType)1) - - // some simple types to make working with CGstateassignment easier - - struct Vector1b - { - bool x; - Vector1b(); - Vector1b( bool iX ); - Vector1b( CGstateassignment cgStateAssignment ); - operator bool() const; - }; - - struct Vector2b - { - bool x, y; - Vector2b(); - Vector2b( bool iX, bool iY , bool iZ, bool iW ); - Vector2b( CGstateassignment cgStateAssignment ); - }; - - struct Vector3b - { - bool x, y, z; - Vector3b(); - Vector3b( bool iX, bool iY , bool iZ, bool iW ); - Vector3b( CGstateassignment cgStateAssignment ); - }; - - struct Vector4b - { - bool x, y, z, w; - Vector4b(); - Vector4b( bool iX, bool iY , bool iZ, bool iW ); - Vector4b( CGstateassignment cgStateAssignment ); - }; - - struct Vector1i - { - int x; - Vector1i(); - Vector1i( int iX ); - Vector1i( CGstateassignment cgStateAssignment ); - operator int() const; - - }; - - struct Vector2i - { - int x, y; - Vector2i(); - Vector2i( int iX, int iY ); - Vector2i( CGstateassignment cgStateAssignment ); - }; - - struct Vector3i - { - int x, y, z; - Vector3i(); - Vector3i( int iX, int iY, int iZ ); - Vector3i( CGstateassignment cgStateAssignment ); - }; - - - struct Vector4i - { - int x, y, z, w; - Vector4i(); - Vector4i( int iX, int iY, int iZ, int iW ); - Vector4i( CGstateassignment cgStateAssignment ); - }; - - - struct Vector1f - { - float x; - Vector1f(); - Vector1f( float iX, float iY, float iZ ); - Vector1f( CGstateassignment cgStateAssignment ); - operator float() const; - }; - - - struct Vector2f - { - float x, y; - Vector2f(); - Vector2f( float iX, float iY, float iZ ); - Vector2f( CGstateassignment cgStateAssignment ); - }; - - - struct Vector3f - { - float x, y, z; - Vector3f(); - Vector3f( float iX, float iY, float iZ ); - Vector3f( CGstateassignment cgStateAssignment ); - }; - - struct Vector4f - { - float x, y, z, w; - Vector4f(); - Vector4f( float iX, float iY, float iZ, float iW ); - Vector4f( CGstateassignment cgStateAssignment ); - }; - - - - // simple types end - - - class CgStateListener : public GeneralAllocatedObject - { - protected: - CGstate mCgState; - CGtype mCgType; - CGcontext mCgContext; - - static CGbool cgCallBackSet( CGstateassignment cgStateAssignment ); - static CGbool cgCallBackReset( CGstateassignment cgStateAssignment ); - static CGbool cgCallBackValidate( CGstateassignment cgStateAssignment ); - - virtual CGstatecallback getCgCallBackSet(); - virtual CGstatecallback getCgCallBackReset(); - virtual CGstatecallback getCgCallBackValidate(); - - virtual void createState() = 0; - void addStateEnumerant( int value, const char *name ); - - CGparameter getCgParameter( CGstateassignment cgStateAssignment ); - - - public: - CgStateListener( CGtype cgType ); - virtual ~CgStateListener(); - virtual void init(); - CGstate getCgState() const; - }; - - typedef std::vector CgStateListenerVector; - - class CgGlobalStateListener : public CgStateListener - { - protected: - const GlobalStateType mGlobalStateType; - void createState() override; - public: - CgGlobalStateListener( const GlobalStateType globalStateType, CGtype cgType ); - virtual ~CgGlobalStateListener(); - - virtual void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ); - }; - /// Bool - class CgBoolGlobalStateListener : public CgGlobalStateListener - { - protected: - const Vector1b getValue( CGstateassignment cgStateAssignment ); - public: - CgBoolGlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// Bool4 - class CgBool4GlobalStateListener : public CgGlobalStateListener - { - protected: - const Vector4b getValue( CGstateassignment cgStateAssignment ); - public: - CgBool4GlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// Float - class CgFloatGlobalStateListener : public CgGlobalStateListener - { - protected: - const Vector1f getValue( CGstateassignment cgStateAssignment ); - public: - CgFloatGlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// Float2 - class CgFloat2GlobalStateListener : public CgGlobalStateListener - { - protected: - const Vector2f getValue( CGstateassignment cgStateAssignment ); - public: - CgFloat2GlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// Float3 - class CgFloat3GlobalStateListener : public CgGlobalStateListener - { - protected: - const Vector3f getValue( CGstateassignment cgStateAssignment ); - public: - CgFloat3GlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// Float4 - class CgFloat4GlobalStateListener : public CgGlobalStateListener - { - protected: - const Vector4f getValue( CGstateassignment cgStateAssignment ); - public: - CgFloat4GlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// Float4x2 - class CgFloat4x2GlobalStateListener : public CgGlobalStateListener - { - public: - CgFloat4x2GlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// Float4x3 - class CgFloat4x3GlobalStateListener : public CgGlobalStateListener - { - public: - CgFloat4x3GlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// Float4x4 - class CgFloat4x4GlobalStateListener : public CgGlobalStateListener - { - public: - CgFloat4x4GlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// Int - class CgIntGlobalStateListener : public CgGlobalStateListener - { - protected: - const Vector1i getValue( CGstateassignment cgStateAssignment ); - public: - CgIntGlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// Int2 - class CgInt2GlobalStateListener : public CgGlobalStateListener - { - protected: - const Vector2i getValue( CGstateassignment cgStateAssignment ); - public: - CgInt2GlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// Int3 - class CgInt3GlobalStateListener : public CgGlobalStateListener - { - protected: - const Vector3i getValue( CGstateassignment cgStateAssignment ); - public: - CgInt3GlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// Int4 - class CgInt4GlobalStateListener : public CgGlobalStateListener - { - protected: - const Vector4i getValue( CGstateassignment cgStateAssignment ); - public: - CgInt4GlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// Sampler - class CgSamplerGlobalStateListener : public CgGlobalStateListener - { - public: - CgSamplerGlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// Sampler2 - class CgSampler2GlobalStateListener : public CgGlobalStateListener - { - public: - CgSampler2GlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// Sampler3 - class CgSampler3GlobalStateListener : public CgGlobalStateListener - { - public: - CgSampler3GlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// SamplerCube - class CgSamplerCubeGlobalStateListener : public CgGlobalStateListener - { - public: - CgSamplerCubeGlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// SamplerRect - class CgSamplerRectGlobalStateListener : public CgGlobalStateListener - { - public: - CgSamplerRectGlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// Texture - class CgTextureGlobalStateListener : public CgGlobalStateListener - { - public: - CgTextureGlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// Program - class CgProgramGlobalStateListener : public CgGlobalStateListener - { - public: - CgProgramGlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - - /// BlendEquation - class CgBlendEquationGlobalStateListener : public CgIntGlobalStateListener - { - protected: - enum BlendEquationType - { - BET_FUNCADD, // FuncAdd - BET_FUNCSUBTRACT, // FuncSubtract - BET_MIN, // Min - BET_MAX, // Max - BET_LOGICOP // LogicOp - }; - void createState() override; - public: - CgBlendEquationGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// DepthFunc - class CgDepthFuncGlobalStateListener : public CgIntGlobalStateListener - { - protected: - enum DepthFuncType - { - DFT_NEVER, // Never - DFT_LESS, // Less - DFT_LEQUAL, // LEqual - DFT_EQUAL, // Equal - DFT_GREATER, // Greater - DFT_NOTEQUAL, // NotEqual - DFT_GEQUAL, // GEqual - DFT_ALWAYS // Always - }; - void createState() override; - public: - CgDepthFuncGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// FogDistanceMode - class CgFogDistanceModeGlobalStateListener : public CgIntGlobalStateListener - { - protected: - enum FogDistanceModeType - { - FDMT_EYERADIAL, // EyeRadial - FDMT_EYEPLANE, // EyePlane - FDMT_EYEPLANEABSOLUTE // EyePlaneAbsolute - }; - void createState() override; - public: - CgFogDistanceModeGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// FogMode - class CgFogModeGlobalStateListener : public CgIntGlobalStateListener - { - protected: - enum FogModeType - { - FMT_LINEAR, // Linear - FMT_EXP, // Exp - FMT_EXP2 // Exp2 - }; - void createState() override; - public: - CgFogModeGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - - /// LightModelColorControl - class CgLightModelColorControlGlobalStateListener : public CgIntGlobalStateListener - { - protected: - enum LightModelColorControlType - { - LMCCT_SINGLECOLOR, // SingleColor - LMCCT_SEPARATESPECULAR // SeparateSpecular - }; - void createState() override; - public: - CgLightModelColorControlGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// LogicOp - class CgLogicOpGlobalStateListener : public CgIntGlobalStateListener - { - protected: - enum LogicOpType - { - LOT_CLEAR, // Clear - LOT_AND, // And - LOT_ANDREVERSE, // AndReverse - LOT_COPY, // Copy - LOT_ANDINVERTED, // AndInverted - LOT_NOOP, // Noop - LOT_XOR, // Xor - LOT_OR, // Or, - LOT_NOR, // Nor - LOT_EQUIV, // Equiv - LOT_INVERT, // Invert - LOT_ORREVERSE, // OrReverse - LOT_COPYINVERTED, // CopyInverted - LOT_NAND, // Nand - LOT_SET // Set - }; - void createState() override; - public: - CgLogicOpGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// PointSpriteCoordOrigin - class CgPointSpriteCoordOriginGlobalStateListener : public CgIntGlobalStateListener - { - protected: - enum PointSpriteCoordOriginType - { - PSCOT_LOWERLEFT, // LowerLeft - PSCOT_UPPERLEFT // UpperLeft - }; - void createState() override; - public: - CgPointSpriteCoordOriginGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// PointSpriteRMode - class CgPointSpriteRModeGlobalStateListener : public CgIntGlobalStateListener - { - protected: - enum PointSpriteRModeType - { - PSRMT_ZERO, // Zero - PSRMT_R, // R - PSRMT_S // S - }; - void createState() override; - public: - CgPointSpriteRModeGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// ShadeModel - class CgShadeModelGlobalStateListener : public CgIntGlobalStateListener - { - protected: - enum ShadeModelType - { - SMT_FLAT, // Flat - SMT_SMOOTH // Smooth - }; - void createState() override; - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - public: - CgShadeModelGlobalStateListener(); - }; - /// TexGenMode - class CgTexGenModeGlobalStateListener : public CgIntGlobalStateListener - { - protected: - enum TexGenModeType - { - TGMT_OBJECTLINEAR, // ObjectLinear - TGMT_EYELINEAR, // EyeLinear - TGMT_SPHEREMAP, // SphereMap - TGMT_REFLECTIONMAP, // ReflectionMap - TGMT_NORMALMAP // NormalMap - }; - void createState() override; - public: - CgTexGenModeGlobalStateListener( const GlobalStateType globalStateType ); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// TextureEnvMode - class CgTextureEnvModeGlobalStateListener : public CgIntGlobalStateListener - { - protected: - enum TextureEnvModeType - { - BET_MODULATE, // Modulate - BET_DECAL, // Decal - BET_BLEND, // Blend - BET_REPLACE, // Replace - BET_ADD // Add - }; - void createState() override; - public: - CgTextureEnvModeGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// MinFilter - class CgMinFilterGlobalStateListener : public CgIntGlobalStateListener - { - protected: - enum MinFilterType - { - MFT_NEAREST, // Nearest - MFT_LINEAR, // Linear - MFT_LINEARMIPMAPNEAREST, // LinearMipMapNearest - MFT_NEARESTMIPMAPNEAREST, // NearestMipMapNearest - MFT_NEARESTMIPMAPLINEAR, // NearestMipMapLinear - MFT_LINEARMIPMAPLINEAR // LinearMipMapLinear - }; - void createState() override; - public: - CgMinFilterGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// MagFilter - class CgMagFilterGlobalStateListener : public CgIntGlobalStateListener - { - protected: - enum MagFilterType - { - MFT_NEAREST, // Nearest - MFT_LINEAR // Linear - }; - void createState() override; - public: - CgMagFilterGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// FrontFace - class CgFrontFaceGlobalStateListener : public CgIntGlobalStateListener - { - protected: - enum FrontFaceType - { - FFT_CW, // CW - FFT_CCW // CCW - }; - void createState() override; - public: - CgFrontFaceGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// CullFaceGlobal - CullFace - class CgCullFaceGlobalStateListener : public CgIntGlobalStateListener - { - protected: - enum CullFaceType - { - CFT_FRONT, // Front - CFT_BACK, // Back - CFT_FRONTANDBACK // FrontAndBack - }; - void createState() override; - public: - CgCullFaceGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - /// FogCoordSrcGlobal - FogCoordSrc - class CgFogCoordSrcGlobalStateListener : public CgIntGlobalStateListener - { - protected: - enum FogCoordSrcType - { - FCST_FRAGMENTDEPTH, // FragmentDepth - FCST_FOGCOORD // FogCoord - }; - void createState() override; - public: - CgFogCoordSrcGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - - // AlphaFuncGlobal - float2 - reference then value - class CgAlphaFuncGlobalStateListener : public CgFloat2GlobalStateListener - { - protected: - enum AlphaFuncType - { - AFT_NEVER, // Never - AFT_LESS, // Less - AFT_LEQUAL, // LEqual - AFT_EQUAL, // Equal - AFT_GREATER, // Greater - AFT_NOTEQUAL, // NotEqual - AFT_GEQUAL, // GEqual - AFT_ALWAYS // Always - }; - void createState() override; - public: - CgAlphaFuncGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - - // BlendFuncGlobal - Int2 - src_factor, dst_factor - class CgBlendFuncGlobalStateListener : public CgInt2GlobalStateListener - { - protected: - enum BlendFuncType - { - BF_ZERO, // Zero - BF_ONE, // One - BF_DESTCOLOR, // DestColor - BF_ONEMINUSDESTCOLOR, // OneMinusDestColor - BF_SRCALPHA, // SrcAlpha - BF_ONEMINUSSRCALPHA, // OneMinusSrcAlpha - BF_DSTALPHA, // DstAlpha - BF_ONEMINUSDSTALPHA, // OneMinusDstAlpha - BF_SRCALPHASATURATE, // SrcAlphaSaturate - BF_SRCCOLOR, // SrcColor - BF_ONEMINUSSRCCOLOR, // OneMinusSrcColor - BF_CONSTANTCOLOR, // ConstantColor - BF_ONEMINUSCONSTANTCOLOR, // OneMinusConstantColor - BF_CONSTANTALPHA, // ConstantAlpha - BF_ONEMINUSCONSTANTALPHA // OneMinusConstantAlpha - }; - void createState() override; - public: - CgBlendFuncGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - - - // BlendFuncSeparate - int4 (rgb_src, rgb_dst, a_src, a_dst) - class CgBlendFuncSeparateGlobalStateListener : public CgInt4GlobalStateListener - { - protected: - enum BlendFuncSeparateType - { - BFST_ZERO, // Zero - BFST_ONE, // One - BFST_DESTCOLOR, // DestColor - BFST_ONEMINUSDESTCOLOR, // OneMinusDestColor - BFST_SRCALPHA, // SrcAlpha - BFST_ONEMINUSSRCALPHA, // OneMinusSrcAlpha - BFST_DSTALPHA, // DstAlpha - BFST_ONEMINUSDSTALPHA, // OneMinusDstAlpha - BFST_SRCALPHASATURATE, // SrcAlphaSaturate - BFST_SRCCOLOR, // SrcColor - BFST_ONEMINUSSRCCOLOR, // OneMinusSrcColor - BFST_CONSTANTCOLOR, // ConstantColor - BFST_ONEMINUSCONSTANTCOLOR, // OneMinusConstantColor - BFST_CONSTANTALPHA, // ConstantAlpha - BFST_ONEMINUSCONSTANTALPHA // OneMinusConstantAlpha - }; - void createState() override; - public: - CgBlendFuncSeparateGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - - // BlendEquationSeparate - int2 (rgb,alpha) - class CgBlendEquationSeparateGlobalStateListener : public CgInt2GlobalStateListener - { - protected: - enum BlendEquationSeparateType - { - BEST_FUNCADD, // FuncAdd - BEST_FUNCSUBTRACT, // FuncSubtract - BEST_MIN, // Min - BEST_MAX, // Max - BEST_LOGICOP // LogicOp - }; - void createState() override; - public: - CgBlendEquationSeparateGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - - - // int2 - class CgColorMaterialGlobalStateListener : public CgInt2GlobalStateListener - { - protected: - enum ColorMaterialType - { - CMT_FRONT, // Front - CMT_BACK, // Back - CMT_FRONTANDBACK, // FrontAndBack - CMT_EMISSION, // Emission - CMT_AMBIENT, // Ambient - CMT_DIFFUSE, // Diffuse - CMT_SPECULAR, // Specular - CMT_AMBIENTANDDIFFUSE // AmbientAndDiffuse - }; - void createState() override; - public: - CgColorMaterialGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - - // int2 - class CgPolygonModeGlobalStateListener : public CgInt2GlobalStateListener - { - protected: - enum PolygonModeType - { - PMT_FRONT, // Front - PMT_BACK, // Back - PMT_FRONTANDBACK, // FrontAndBack - PMT_POINT, // Point - PMT_LINE, // Line - PMT_FILL // Fill - }; - void createState() override; - public: - CgPolygonModeGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - - // int3 - class CgStencilFuncGlobalStateListener : public CgInt3GlobalStateListener - { - protected: - enum StencilFuncType - { - SFT_NEVER, // Never - SFT_LESS, // Less - SFT_LEQUAL, // LEqual - SFT_EQUAL, // Equal - SFT_GREATER, // Greater - SFT_NOTEQUAL, // NotEqual - SFT_GEQUAL, // GEqual - SFT_ALWAYS // Always - }; - void createState() override; - public: - CgStencilFuncGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - - // int3 - class CgStencilOpGlobalStateListener : public CgInt3GlobalStateListener - { - protected: - enum StencilOpType - { - SOT_KEEP, // Keep - SOT_ZERO, // Zero - SOT_REPLACE, // Replace - SOT_INCR, // Incr - SOT_DECR, // Decr - SOT_INVERT, // Invert - SOT_INCRWRAP, // IncrWrap - SOT_DECRWRAP // DecrWrap - }; - void createState() override; - public: - CgStencilOpGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - - // int4 - class CgStencilFuncSeparateGlobalStateListener : public CgInt4GlobalStateListener - { - protected: - enum StencilFuncSeparateType - { - SFST_FRONT, // Front - SFST_BACK, // Back - SFST_FRONTANDBACK, // FrontAndBack - SFST_NEVER, // Never - SFST_LESS, // Less - SFST_LEQUAL, // LEqual - SFST_EQUAL, // Equal - SFST_GREATER, // Greater - SFST_NOTEQUAL, // NotEqual - SFST_GEQUAL, // GEqual - SFST_ALWAYS // Always - }; - void createState() override; - public: - CgStencilFuncSeparateGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - - // int2 - class CgStencilMaskSeparateGlobalStateListener : public CgInt2GlobalStateListener - { - protected: - enum StencilMaskSeparateType - { - BET_FRONT, // Front - BET_BACK, // Back - BET_FRONTANDBACK // FrontAndBack - }; - void createState() override; - public: - CgStencilMaskSeparateGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - - // int4 - class CgStencilOpSeparateGlobalStateListener : public CgInt4GlobalStateListener - { - protected: - enum StencilOpSeparateType - { - BET_KEEP, // Keep - BET_ZERO, // Zero - BET_REPLACE, // Replace - BET_INCR, // Incr - BET_DECR, // Decr - BET_INVERT, // Invert - BET_INCRWRAP, // IncrWrap - BET_DECRWRAP // DecrWrap - }; - void createState() override; - public: - CgStencilOpSeparateGlobalStateListener(); - void updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) override; - }; - - - class CgSamplerStateListener : public CgStateListener - { - protected: - SamplerStateType mSamplerStateType; - void createState() override; - public: - CgSamplerStateListener( const SamplerStateType samplerStateType, CGtype cgType ); - virtual ~CgSamplerStateListener(); - - virtual void upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ); - }; - /// Int - class CgIntSamplerStateListener : public CgSamplerStateListener - { - protected: - const Vector1i getValue( CGstateassignment cgStateAssignment ); - public: - CgIntSamplerStateListener( const SamplerStateType samplerStateType ); - void upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) override; - }; - /// Bool - class CgBoolSamplerStateListener : public CgSamplerStateListener - { - public: - CgBoolSamplerStateListener( const SamplerStateType samplerStateType ); - void upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) override; - }; - /// Float - class CgFloatSamplerStateListener : public CgSamplerStateListener - { - public: - CgFloatSamplerStateListener( const SamplerStateType samplerStateType ); - void upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) override; - }; - /// Float4 - class CgFloat4SamplerStateListener : public CgSamplerStateListener - { - public: - CgFloat4SamplerStateListener( const SamplerStateType samplerStateType ); - void upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) override; - }; - /// Texture - class CgTextureSamplerStateListener : public CgSamplerStateListener - { - protected: - TextureType parseTextureType( CGparameter cgParameter, TextureUnitState * ogreTextureUnitState ); - void parseTextureName( CGparameter cgParameter, TextureUnitState * ogreTextureUnitState ); - public: - CgTextureSamplerStateListener(const SamplerStateType samplerStateType); - void upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) override; - - }; - - // Wrap = TextureAddressingMode - class CgWrapSamplerStateListener : public CgIntSamplerStateListener - { - protected: - enum WarpType - { - WT_REPEAT, // Repeat - WT_CLAMP, // Clamp - WT_CLAMPTOEDGE, // ClampToEdge - WT_CLAMPTOBORDER, // ClampToBorder - WT_MIRROREDREPEAT, // MirroredRepeat - WT_MIRRORCLAMP, // MirrorClamp - WT_MIRRORCLAMPTOEDGE, // MirrorClampToEdge - WT_MIRRORCLAMPTOBORDER // MirrorClampToBorder - }; - void createState() override; - TextureAddressingMode getOgreTextureAddressingMode( CGstateassignment cgStateAssignment ); - public: - CgWrapSamplerStateListener(const SamplerStateType samplerStateType); - void upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) override; - }; - /// CompareMode - class CgCompareModeSamplerStateListener : public CgIntSamplerStateListener - { - protected: - enum CompareModeType - { - CMT_NONE, // None - CMT_COMPARERTOTEXTURE // CompareRToTexture - }; - void createState() override; - public: - CgCompareModeSamplerStateListener(); - void upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) override; - }; - /// CompareFunc - class CgCompareFuncSamplerStateListener : public CgIntSamplerStateListener - { - protected: - enum CompareFuncType - { - CFT_NEVER, // Never - CFT_LESS, // Less - CFT_LEQUAL, // LEqual - CFT_EQUAL, // Equal - CFT_GREATER, // Greater - CFT_NOTEQUAL // NotEqual - }; - void createState() override; - public: - CgCompareFuncSamplerStateListener(); - void upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) override; - }; - /// DepthMode - class CgDepthModeSamplerStateListener : public CgIntSamplerStateListener - { - protected: - enum DepthModeType - { - DMT_ALPHA, // Alpha - DMT_INTENSITY, // Intensity - DMT_LUMINANCE // Luminance - }; - void createState() override; - public: - CgDepthModeSamplerStateListener(); - void upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) override; - }; - /// MinFilter - class CgMinFilterSamplerStateListener : public CgIntSamplerStateListener - { - protected: - enum MinFilterType - { - MINFT_NEAREST, // Nearest - MINFT_LINEAR, // Linear - MINFT_LINEARMIPMAPNEAREST, // LinearMipMapNearest - MINFT_NEARESTMIPMAPNEAREST, // NearestMipMapNearest - MINFT_NEARESTMIPMAPLINEAR, // NearestMipMapLinear - MINFT_LINEARMIPMAPLINEAR // LinearMipMapLinear - }; - - void createState() override; - public: - CgMinFilterSamplerStateListener(); - void upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) override; - }; - /// MagFilter - class CgMagFilterSamplerStateListener : public CgIntSamplerStateListener - { - protected: - enum MagFilterType - { - MAGFT_NEAREST, // Nearest - MAGFT_LINEAR // Linear - - }; - - void createState() override; - public: - CgMagFilterSamplerStateListener(); - void upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) override; - }; - /// MipFilter - class CgMipFilterSamplerStateListener : public CgIntSamplerStateListener - { - protected: - enum MipFilterType - { - MIPFT_NONE = 0, // filtering disabled (valid for mip filter only) - MIPFT_POINT = 1, // nearest - MIPFT_LINEAR = 2, // linear interpolation - MIPFT_ANISOTROPIC = 3, // anisotropic - MIPFT_PYRAMIDALQUAD = 6, // 4-sample tent - MIPFT_GAUSSIANQUAD = 7 // 4-sample gaussian - - }; - - void createState() override; - public: - CgMipFilterSamplerStateListener(); - void upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) override; - }; - /// TextureAddress - class CgTextureAddressSamplerStateListener : public CgIntSamplerStateListener - { - protected: - enum TextureAddressType - { - TAT_WRAP = 1, // Wrap - TAT_MIRROR, // Mirror - TAT_CLAMP, // Clamp - TAT_BORDER, // Border - TAT_MIRRORONCE // MirrorOnce - }; - - void createState() override; - public: - CgTextureAddressSamplerStateListener( const SamplerStateType samplerStateType ); - void upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) override; - }; - - typedef std::map CgGlobalStateToListenerMap; - typedef std::map CgSamplerStateToListenerMap; - - CgGlobalStateToListenerMap mCgGlobalStateToListenerMap; - CgSamplerStateToListenerMap mCgSamplerStateToListenerMap; - CgStateListenerVector mCgStateListenerVector; - CgStateListenerVector mCgSamplerStateListenerVector; - - StringVector mScriptPatterns; // for getScriptPatterns(void) - - CGcontext mCgContext; - CGcontext getCgContext() const; - - - void parseCgEffect( CGeffect cgEffect, MaterialPtr ogreMaterial ); - void parseCgEffectTechniques( CGeffect cgEffect, MaterialPtr ogreMaterial ); - void parseCgTechnique( CGtechnique cgTechnique, Technique * ogreTechnique ); - void parseCgPass( CGpass cgPass, Pass * ogrePass ); - void parseSamplerParameters(CGpass cgPass, Pass * ogrePass); - - void parsePassStateAssignments( CGpass cgPass, Pass * ogrePass ); - void parseCgProgram( CGpass cgPass, Pass * ogrePass, const GpuProgramType ogreProgramType ); - void parseCgProgramParameters( CGpass cgPass, GpuProgramParametersSharedPtr ogreProgramParameters ); - void parseCgProgramParameter( CGparameter cgParameter, GpuProgramParametersSharedPtr ogreProgramParameters, const String& ogreParamName ); - void parseTextureUnitState( CGstateassignment cgStateAssignment, TextureUnitState * ogreTextureUnitState ); - - void parseFloatCgProgramParameter( CGtype cgParamType, CGparameter cgParameter, GpuProgramParametersSharedPtr ogreProgramParameters, const String& ogreParamName ); - void parseIntCgProgramParameter( CGtype cgParamType, CGparameter cgParameter, GpuProgramParametersSharedPtr ogreProgramParameters, const String& ogreParamName ); - bool parseAutoConstantParam( CGparameter cgParameter, GpuProgramParametersSharedPtr ogreProgramParameters, const String& ogreParamName ); - bool cgSemanticToOgreAutoConstantType( const char * cgParamSemantic, const char * uiNameValue, GpuProgramParameters::AutoConstantType & ogreAutoConstantType, size_t & extraInfo ); - FXSemanticID cgSemanticStringToType( const char * cgParamSemantic ); - - void buildStateNameStringToTypeMap(); - - const char * getGlobalStateNameTypeToString( const GlobalStateType cgStateName ); - const char * getSamplerStateNameTypeToString( const SamplerStateType cgStateName ); - CgGlobalStateListener * createCgGlobalStateListener( const GlobalStateType type ); - CgSamplerStateListener * createCgSamplerStateListener( const SamplerStateType type ); - - public: - CgFxScriptLoader(); - virtual ~CgFxScriptLoader(); - - /// @copydoc ScriptLoader::getScriptPatterns - const StringVector& getScriptPatterns(void) const override; - /// @copydoc ScriptLoader::parseScript - void parseScript( DataStreamPtr& stream, const String& groupName ) override; - - /// @copydoc ScriptLoader::getLoadingOrder - Real getLoadingOrder(void) const override; - - /// @copydoc Singleton::getSingleton() - static CgFxScriptLoader& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static CgFxScriptLoader* getSingletonPtr(void); - private: - - }; - /** @} */ - /** @} */ -} // namespace Ogre - -#endif diff --git a/PlugIns/CgProgramManager/include/OgreCgPlugin.h b/PlugIns/CgProgramManager/include/OgreCgPlugin.h deleted file mode 100644 index ced36c42d67..00000000000 --- a/PlugIns/CgProgramManager/include/OgreCgPlugin.h +++ /dev/null @@ -1,66 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __CgPlugin_H__ -#define __CgPlugin_H__ - -#include "OgrePlugin.h" -#include "OgreCgPrerequisites.h" - -namespace Ogre -{ - class CgProgramFactory; - - /** Plugin instance for Cg Program Manager */ - class _OgreCgPluginExport CgPlugin : public Plugin - { - public: - CgPlugin(); - - - /// @copydoc Plugin::getName - const String& getName() const override; - - /// @copydoc Plugin::install - void install() override; - - /// @copydoc Plugin::initialise - void initialise() override; - - /// @copydoc Plugin::shutdown - void shutdown() override; - - /// @copydoc Plugin::uninstall - void uninstall() override; - protected: - CgProgramFactory* mCgProgramFactory; - - - }; -} - -#endif diff --git a/PlugIns/CgProgramManager/include/OgreCgPrerequisites.h b/PlugIns/CgProgramManager/include/OgreCgPrerequisites.h deleted file mode 100644 index b886bc4ef17..00000000000 --- a/PlugIns/CgProgramManager/include/OgreCgPrerequisites.h +++ /dev/null @@ -1,63 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __CgPrerequisites_H__ -#define __CgPrerequisites_H__ - -#include "OgreException.h" -#include - - -namespace Ogre { - - /** Utility function, checks Cg for errors, throw exception if detected. - @param ogreMethod Ogre method name, as Class::method - @param errorTextPrefix The text to prefix the Cg error text with - @param context - */ - void checkForCgError(const String& ogreMethod, const String& errorTextPrefix, CGcontext context); - - -#if (OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT) && !defined(__MINGW32__) && !defined(OGRE_STATIC_LIB) -# ifdef OGRE_CGPLUGIN_EXPORTS -# define _OgreCgPluginExport __declspec(dllexport) -# else -# if defined( __MINGW32__ ) -# define _OgreCgPluginExport -# else -# define _OgreCgPluginExport __declspec(dllimport) -# endif -# endif -#elif defined ( OGRE_GCC_VISIBILITY ) -# define _OgreCgPluginExport __attribute__ ((visibility("default"))) -#else -# define _OgreCgPluginExport -#endif // OGRE_WIN32 - -} - -#endif diff --git a/PlugIns/CgProgramManager/include/OgreCgProgram.h b/PlugIns/CgProgramManager/include/OgreCgProgram.h deleted file mode 100644 index cea0c65a5e8..00000000000 --- a/PlugIns/CgProgramManager/include/OgreCgProgram.h +++ /dev/null @@ -1,166 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __CgProgram_H__ -#define __CgProgram_H__ - -#include "OgreCgPrerequisites.h" -#include "OgreHighLevelGpuProgram.h" -#include "OgreStringVector.h" - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup CgProgramManager - * @{ - */ - /** Specialisation of HighLevelGpuProgram to provide support for nVidia's CG language. - - Cg can be used to compile common, high-level, C-like code down to assembler - language for both GL and Direct3D, for multiple graphics cards. You must - supply a list of profiles which your program must support using - setProfiles() before the program is loaded in order for this to work. The - program will then negotiate with the renderer to compile the appropriate program - for the API and graphics card capabilities. - */ - class CgProgram : public HighLevelGpuProgram - { - public: - /// Command object for setting profiles - class CmdProfiles : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Command object for setting compilation arguments - class CmdArgs : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - protected: - - static CmdProfiles msCmdProfiles; - static CmdArgs msCmdArgs; - - /// The CG context to use, passed in by factory - CGcontext mCgContext; - /** Internal load implementation, must be implemented by subclasses. - */ - void loadFromSource(void) override; - /** Internal method for creating an appropriate low-level program from this - high-level program, must be implemented by subclasses. */ - void createLowLevelImpl(void) override; - /// Internal unload implementation, must be implemented by subclasses - void unloadHighLevelImpl(void) override; - /// Populate the passed parameters with name->index map, must be overridden - void buildConstantDefinitions() override; - - /// Load the high-level part in a thread-safe way, required for delegate functionality - void loadHighLevelSafe(); - - /// Recurse down structures getting data on parameters - void recurseParams(CGparameter param, size_t contextArraySize = 1); - /// Turn a Cg type into a GpuConstantType and number of elements - void mapTypeAndElementSize(CGtype cgType, bool isRegisterCombiner, GpuConstantDefinition& def) const; - - StringVector mProfiles; - String mSelectedProfile; - String mProgramString; - CGprofile mSelectedCgProfile; - // Unfortunately Cg uses char** for arguments - bleh - // This is a null-terminated list of char* (each null terminated) - char** mCgArguments; - - GpuConstantDefinitionMap mParametersMap; - size_t mParametersMapSizeAsBuffer; - std::map mSamplerRegisterMap; - CGenum mInputOp, mOutputOp; - - /// Internal method which works out which profile to use for this program - void selectProfile(void); - /// Internal method which merges manual and automatic compile arguments - void buildArgs(void); - /// Releases memory for the horrible Cg char** - void freeCgArgs(void); - - void getMicrocodeFromCache(uint32 id); - void compileMicrocode(void); - void addMicrocodeToCache(uint32 id); - - private: - HighLevelGpuProgramPtr mDelegate; - String getHighLevelLanguage() const; - String getHighLevelTarget() const; - void fixHighLevelOutput(String& hlSource); - - - public: - CgProgram(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - CGcontext context); - ~CgProgram(); - - /** Sets the entry point for this program ie the first method called. */ - void setEntryPoint(const String& entryPoint) { mEntryPoint = entryPoint; } - /** Gets the entry point defined for this program. */ - const String& getEntryPoint(void) const { return mEntryPoint; } - /** Sets the Cg profiles which can be supported by the program. */ - void setProfiles(const StringVector& profiles); - /** Gets the Cg profiles which can be supported by the program. */ - const StringVector& getProfiles(void) const { return mProfiles; } - /// Overridden from GpuProgram - bool isSupported(void) const override; - /// Overridden from GpuProgram - const String& getLanguage(void) const override; - - GpuProgramParametersSharedPtr createParameters() override; - GpuProgram* _getBindingDelegate() override; - - bool isSkeletalAnimationIncluded(void) const override; - bool isMorphAnimationIncluded(void) const override; - bool isPoseAnimationIncluded(void) const override; - bool isVertexTextureFetchRequired(void) const override; - const GpuProgramParametersPtr& getDefaultParameters(void) override; - bool hasDefaultParameters(void) const override; - bool getPassSurfaceAndLightStates(void) const override; - bool getPassFogStates(void) const override; - bool getPassTransformStates(void) const override; - bool hasCompileError(void) const override; - void resetCompileError(void) override; - size_t getSize(void) const; - void touch(void) override; - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/PlugIns/CgProgramManager/include/OgreCgProgramFactory.h b/PlugIns/CgProgramManager/include/OgreCgProgramFactory.h deleted file mode 100644 index 954f6f019dc..00000000000 --- a/PlugIns/CgProgramManager/include/OgreCgProgramFactory.h +++ /dev/null @@ -1,61 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __CgProgramFactory_H__ -#define __CgProgramFactory_H__ - -#include "OgreCgPrerequisites.h" -#include "OgreHighLevelGpuProgramManager.h" - -namespace Ogre -{ - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup CgProgramManager - * @{ - */ - /** Factory class for Cg programs. */ - class CgProgramFactory : public HighLevelGpuProgramFactory - { - protected: - CGcontext mCgContext; - static String sLanguageName; - public: - CgProgramFactory(); - ~CgProgramFactory(); - /// Get the name of the language this factory creates programs for - const String& getLanguage(void) const override; - GpuProgram* create(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) override; - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/PlugIns/CgProgramManager/src/OgreCgFxScriptLoader.cpp b/PlugIns/CgProgramManager/src/OgreCgFxScriptLoader.cpp deleted file mode 100644 index 8418eaa1533..00000000000 --- a/PlugIns/CgProgramManager/src/OgreCgFxScriptLoader.cpp +++ /dev/null @@ -1,4331 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreCgFxScriptLoader.h" -#include "OgreResourceGroupManager.h" -#include "OgreMaterialManager.h" -#include "OgreTechnique.h" -#include "OgrePass.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreCgProgram.h" - -#include - -namespace Ogre { - - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector1b::Vector1b() : x(false) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector1b::Vector1b( bool iX ) : x( iX ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector1b::Vector1b( CGstateassignment cgStateAssignment ) : x( false ) - { - int nValsDummy[1]; - const CGbool * values; - values = cgGetBoolStateAssignmentValues(cgStateAssignment, nValsDummy); - assert(nValsDummy[0] == 1); - -#if ( OGRE_COMPILER == OGRE_COMPILER_MSVC ) -#pragma warning(push) -#pragma warning(disable: 4800) // warning C4800: 'const CGbool' : forcing value to bool 'true' or 'false' (performance warning) -#endif - x = static_cast(values[0]); -#if ( OGRE_COMPILER == OGRE_COMPILER_MSVC ) -#pragma warning(pop) -#endif - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector1b::operator bool() const - { - return x; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector2b::Vector2b() : x( false ), y( false ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector2b::Vector2b( bool iX, bool iY , bool iZ, bool iW ) : x( iX ), y( iY ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector2b::Vector2b( CGstateassignment cgStateAssignment ) : x( false ), y( false ) - { - int nValsDummy[1]; - const CGbool * values; - values = cgGetBoolStateAssignmentValues(cgStateAssignment, nValsDummy); - assert(nValsDummy[0] == 2); - -#if ( OGRE_COMPILER == OGRE_COMPILER_MSVC ) -#pragma warning(push) -#pragma warning(disable: 4800) // warning C4800: 'const CGbool' : forcing value to bool 'true' or 'false' (performance warning) -#endif - x = static_cast(values[0]); - y = static_cast(values[1]); -#if ( OGRE_COMPILER == OGRE_COMPILER_MSVC ) -#pragma warning(pop) -#endif - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //-------------------------------------------------------------------- - CgFxScriptLoader::Vector3b::Vector3b() : x( false ), y( false ), z( false ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector3b::Vector3b( bool iX, bool iY , bool iZ, bool iW ) : x( iX ), y( iY ), z( iZ ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector3b::Vector3b( CGstateassignment cgStateAssignment ) : x( false ), y( false ), z( false ) - { - int nValsDummy[1]; - const CGbool * values; - values = cgGetBoolStateAssignmentValues(cgStateAssignment, nValsDummy); - assert(nValsDummy[0] == 3); - -#if ( OGRE_COMPILER == OGRE_COMPILER_MSVC ) -#pragma warning(push) -#pragma warning(disable: 4800) // warning C4800: 'const CGbool' : forcing value to bool 'true' or 'false' (performance warning) -#endif - x = static_cast(values[0]); - y = static_cast(values[1]); - z = static_cast(values[2]); -#if ( OGRE_COMPILER == OGRE_COMPILER_MSVC ) -#pragma warning(pop) -#endif - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector4b::Vector4b() : x( false ), y( false ), z( false ), w( false ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector4b::Vector4b( bool iX, bool iY , bool iZ, bool iW ) : x( iX ), y( iY ), z( iZ ), w( iW ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector4b::Vector4b( CGstateassignment cgStateAssignment ) : x( false ), y( false ), z( false ), w( false ) - { - int nValsDummy[1]; - const CGbool * values; - values = cgGetBoolStateAssignmentValues(cgStateAssignment, nValsDummy); - assert(nValsDummy[0] == 4); - -#if ( OGRE_COMPILER == OGRE_COMPILER_MSVC ) -#pragma warning(push) -#pragma warning(disable: 4800) // warning C4800: 'const CGbool' : forcing value to bool 'true' or 'false' (performance warning) -#endif - x = static_cast(values[0]); - y = static_cast(values[1]); - z = static_cast(values[2]); - w = static_cast(values[3]); -#if ( OGRE_COMPILER == OGRE_COMPILER_MSVC ) -#pragma warning(pop) -#endif - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector1i::Vector1i() : x( 0 ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector1i::Vector1i( int iX ) : x( iX ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector1i::Vector1i( CGstateassignment cgStateAssignment ) : x( 0 ) - { - int nValsDummy[1]; - const int * values; - values = cgGetIntStateAssignmentValues(cgStateAssignment, nValsDummy); - assert( nValsDummy[0] == 1); - - x = values[0]; - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector1i::operator int() const - { - return x; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector2i::Vector2i() : x( 0 ), y( 0 ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector2i::Vector2i( int iX, int iY ) : x( iX ), y( iY ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector2i::Vector2i( CGstateassignment cgStateAssignment ) : x( 0 ), y( 0 ) - { - int nValsDummy[1]; - const int * values; - values = cgGetIntStateAssignmentValues(cgStateAssignment, nValsDummy); - assert( nValsDummy[0] == 2); - - x = values[0]; - y = values[1]; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector3i::Vector3i() : x( 0 ), y( 0 ), z( 0 ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector3i::Vector3i( int iX, int iY, int iZ ) : x( iX ), y( iY ) , z( iZ ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector3i::Vector3i( CGstateassignment cgStateAssignment ) : x( 0 ), y( 0 ), z( 0 ) - { - int nValsDummy[1]; - const int * values; - values = cgGetIntStateAssignmentValues(cgStateAssignment, nValsDummy); - assert( nValsDummy[0] == 3); - - x = values[0]; - y = values[1]; - z = values[2]; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector4i::Vector4i() : x( 0 ), y( 0 ), z( 0 ), w( 0 ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector4i::Vector4i( int iX, int iY, int iZ, int iW ) : x( iX ), y( iY ), z( iZ ), w( iW ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector4i::Vector4i( CGstateassignment cgStateAssignment ) : x( 0 ), y( 0 ), z( 0 ), w( 0 ) - { - int nValsDummy[1]; - const int * values; - values = cgGetIntStateAssignmentValues(cgStateAssignment, nValsDummy); - assert( nValsDummy[0] == 4 ); - - x = values[0]; - y = values[1]; - z = values[2]; - w = values[3]; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector1f::Vector1f() : x( 0.0f ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector1f::Vector1f( float iX, float iY, float iZ ) : x( iX ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector1f::Vector1f( CGstateassignment cgStateAssignment ) : x( 0.0f ) - { - int nValsDummy[1]; - const float * values; - values = cgGetFloatStateAssignmentValues(cgStateAssignment, nValsDummy); - assert( nValsDummy[0] == 1 ); - - x = values[0]; - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector1f::operator float() const - { - return x; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector2f::Vector2f() : x( 0.0f ), y( 0.0f ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector2f::Vector2f( float iX, float iY, float iZ ) : x( iX ), y( iY ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector2f::Vector2f( CGstateassignment cgStateAssignment ) : x( 0.0f ), y( 0.0f ) - { - int nValsDummy[1]; - const float * values; - values = cgGetFloatStateAssignmentValues(cgStateAssignment, nValsDummy); - assert( nValsDummy[0] == 2 ); - - x = values[0]; - y = values[1]; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector3f::Vector3f() : x( 0.0f ), y( 0.0f ), z( 0.0f ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector3f::Vector3f( float iX, float iY, float iZ ) : x( iX ), y( iY ), z( iZ ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector3f::Vector3f( CGstateassignment cgStateAssignment ) : x( 0.0f ), y( 0.0f ), z( 0.0f ) - { - int nValsDummy[1]; - const float * values; - values = cgGetFloatStateAssignmentValues(cgStateAssignment, nValsDummy); - assert( nValsDummy[0] == 3 ); - - x = values[0]; - y = values[1]; - z = values[2]; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector4f::Vector4f() : x( 0.0f ), y( 0.0f ), z( 0.0f ), w( 0.0f ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector4f::Vector4f( float iX, float iY, float iZ, float iW ) : x( iX ), y( iY ), z( iZ ), w( iW ) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::Vector4f::Vector4f( CGstateassignment cgStateAssignment ) : x( 0.0f ), y( 0.0f ), z( 0.0f ), w( 0.0f ) - { - int nValsDummy[1]; - const float * values; - values = cgGetFloatStateAssignmentValues(cgStateAssignment, nValsDummy); - assert( nValsDummy[0] == 4 ); - - x = values[0]; - y = values[1]; - z = values[2]; - w = values[3]; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgStateListener::CgStateListener(CGtype cgType) - : mCgState(0), - mCgType(cgType), - mCgContext(CgFxScriptLoader::getSingleton().getCgContext()) - - - { - } - //--------------------------------------------------------------------- - CgFxScriptLoader::CgStateListener::~CgStateListener() - { - - } - //--------------------------------------------------------------------- - CGbool CgFxScriptLoader::CgStateListener::cgCallBackSet( const CGstateassignment cgStateAssignment ) - { - return CG_TRUE; - } - //--------------------------------------------------------------------- - CGbool CgFxScriptLoader::CgStateListener::cgCallBackReset( CGstateassignment cgStateAssignment ) - { - return CG_TRUE; - } - //--------------------------------------------------------------------- - CGbool CgFxScriptLoader::CgStateListener::cgCallBackValidate( CGstateassignment cgStateAssignment ) - { - return CG_TRUE; - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgStateListener::init() - { - createState(); - checkForCgError("CgFxScriptLoader::CgStateListener::init", - "Unable to Set create State: ", mCgContext); - - cgSetStateCallbacks( mCgState, getCgCallBackSet(), getCgCallBackReset(), getCgCallBackValidate() ); - checkForCgError("CgFxScriptLoader::CgStateListener::init", - "Unable to Set State Callbacks: ", mCgContext); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgStateListener::addStateEnumerant( int value, const char *name ) - { - cgAddStateEnumerant(mCgState, name, value); - - checkForCgError("CgFxScriptLoader::CgMinFilterSamplerStateListener::createState", - "Unable to Add State Enumerants: ", mCgContext); - - } - //--------------------------------------------------------------------- - CGstatecallback CgFxScriptLoader::CgStateListener::getCgCallBackSet() - { - return cgCallBackSet; - } - //--------------------------------------------------------------------- - CGstatecallback CgFxScriptLoader::CgStateListener::getCgCallBackReset() - { - return cgCallBackReset; - } - //--------------------------------------------------------------------- - CGstatecallback CgFxScriptLoader::CgStateListener::getCgCallBackValidate() - { - return cgCallBackValidate; - } - //--------------------------------------------------------------------- - CGstate CgFxScriptLoader::CgStateListener::getCgState() const - { - return mCgState; - } - //--------------------------------------------------------------------- - CGparameter CgFxScriptLoader::CgStateListener::getCgParameter( CGstateassignment cgStateAssignment ) - { - return cgGetTextureStateAssignmentValue(cgStateAssignment); - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgGlobalStateListener::CgGlobalStateListener( const GlobalStateType globalStateType, CGtype cgType ) - : CgStateListener(cgType), - mGlobalStateType(globalStateType) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::CgGlobalStateListener::~CgGlobalStateListener() - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgGlobalStateListener::createState() - { - const char * typeNameAsString = CgFxScriptLoader::getSingleton().getGlobalStateNameTypeToString(mGlobalStateType); - mCgState = cgCreateState( mCgContext, typeNameAsString, mCgType ); - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - // todo - error - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgBoolGlobalStateListener::CgBoolGlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener(globalStateType, CG_BOOL) - { - - } - //--------------------------------------------------------------------- - const CgFxScriptLoader::Vector1b CgFxScriptLoader::CgBoolGlobalStateListener::getValue( CGstateassignment cgStateAssignment ) - { - return Vector1b(cgStateAssignment); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgBoolGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - const bool value = getValue(cgStateAssignment); - switch( mGlobalStateType ) - { - case GST_ALPHABLENDENABLE: - break; - case GST_COLORVERTEX: - break; - case GST_DEPTHMASK: - break; - case GST_ZWRITEENABLE: - break; - case GST_INDEXEDVERTEXBLENDENABLE: - break; - case GST_LIGHTINGENABLE: - break; - case GST_LIGHTENABLE: - case GST_LIGHTING: - ogrePass->setLightingEnabled(value); - break; - case GST_LOCALVIEWER: - break; - case GST_MULTISAMPLEANTIALIAS: - break; - case GST_POINTSCALEENABLE: - break; - case GST_RANGEFOGENABLE: - break; - case GST_SPECULARENABLE: - break; - case GST_CLIPPING: - break; - case GST_POINTSPRITECOORDREPLACE: - break; - case GST_LASTPIXEL: - break; - case GST_TEXTURE1DENABLE: - break; - case GST_TEXTURE2DENABLE: - break; - case GST_TEXTURE3DENABLE: - break; - case GST_TEXTURERECTANGLEENABLE: - break; - case GST_TEXTURECUBEMAPENABLE: - break; - case GST_ALPHATESTENABLE: - break; - case GST_AUTONORMALENABLE: - break; - case GST_BLENDENABLE: - break; - case GST_COLORLOGICOPENABLE: - break; - case GST_CULLFACEENABLE: - break; - case GST_DEPTHBOUNDSENABLE: - break; - case GST_DEPTHCLAMPENABLE: - break; - case GST_DEPTHTESTENABLE: - break; - case GST_ZENABLE: - ogrePass->setDepthCheckEnabled(value); - break; - case GST_DITHERENABLE: - break; - case GST_FOGENABLE: - break; - case GST_LIGHTMODELLOCALVIEWERENABLE: - break; - case GST_LIGHTMODELTWOSIDEENABLE: - break; - case GST_LINESMOOTHENABLE: - break; - case GST_LINESTIPPLEENABLE: - break; - case GST_LOGICOPENABLE: - break; - case GST_MULTISAMPLEENABLE: - break; - case GST_NORMALIZEENABLE: - break; - case GST_NORMALIZENORMALS: - break; - case GST_POINTSMOOTHENABLE: - break; - case GST_POINTSPRITEENABLE: - break; - case GST_POLYGONOFFSETFILLENABLE: - break; - case GST_POLYGONOFFSETLINEENABLE: - break; - case GST_POLYGONOFFSETPOINTENABLE: - break; - case GST_POLYGONSMOOTHENABLE: - break; - case GST_POLYGONSTIPPLEENABLE: - break; - case GST_RESCALENORMALENABLE: - break; - case GST_SAMPLEALPHATOCOVERAGEENABLE: - break; - case GST_SAMPLEALPHATOONEENABLE: - break; - case GST_SAMPLECOVERAGEENABLE: - break; - case GST_SCISSORTESTENABLE: - break; - case GST_STENCILTESTENABLE: - break; - case GST_STENCILENABLE: - break; - case GST_STENCILTESTTWOSIDEENABLE: - break; - case GST_TEXGENSENABLE: - break; - case GST_TEXGENTENABLE: - break; - case GST_TEXGENRENABLE: - break; - case GST_TEXGENQENABLE: - break; - case GST_TWOSIDEDSTENCILMODE: - break; - case GST_SEPARATEALPHABLENDENABLE: - break; - case GST_VERTEXPROGRAMPOINTSIZEENABLE: - break; - case GST_VERTEXPROGRAMTWOSIDEENABLE: - break; - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgBool4GlobalStateListener::CgBool4GlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener(globalStateType, CG_BOOL4) - { - - } - //--------------------------------------------------------------------- - const CgFxScriptLoader::Vector4b CgFxScriptLoader::CgBool4GlobalStateListener::getValue( CGstateassignment cgStateAssignment ) - { - return Vector4b( cgStateAssignment ); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgBool4GlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( mGlobalStateType ) - { - case GST_COLORWRITEENABLE: - case GST_COLORMASK: - case GST_PIXELSHADERCONSTANTB: - case GST_VERTEXSHADERCONSTANTB: - case GST_COLORWRITEENABLE1: - case GST_COLORWRITEENABLE2: - case GST_COLORWRITEENABLE3: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgFloatGlobalStateListener::CgFloatGlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener(globalStateType, CG_FLOAT) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgFloatGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( mGlobalStateType ) - { - case GST_ALPHAREF: - case GST_CLEARDEPTH: - case GST_DEPTHBIAS: - case GST_FOGDENSITY: - case GST_FOGSTART: - case GST_FOGEND: - case GST_LIGHTCONSTANTATTENUATION: - case GST_LIGHTATTENUATION0: - case GST_LIGHTLINEARATTENUATION: - case GST_LIGHTATTENUATION1: - case GST_LIGHTQUADRATICATTENUATION: - case GST_LIGHTATTENUATION2: - case GST_LIGHTSPOTCUTOFF: - case GST_LIGHTFALLOFF: - case GST_LIGHTPHI: - case GST_LIGHTRANGE: - case GST_LIGHTTHETA: - case GST_PATCHSEGMENTS: - case GST_POINTSCALE_A: - case GST_POINTSCALE_B: - case GST_POINTSCALE_C: - case GST_TWEENFACTOR: - case GST_LINEWIDTH: - case GST_MATERIALSHININESS: - case GST_MATERIALPOWER: - case GST_POINTFADETHRESHOLDSIZE: - case GST_POINTSIZE: - case GST_POINTSIZEMIN: - case GST_POINTSIZEMAX: - case GST_SLOPSCALEDEPTHBIAS: - case GST_BUMPENVLSCALE: - case GST_BUMPENVLOFFSET: - case GST_BUMPENVMAT00: - case GST_BUMPENVMAT01: - case GST_BUMPENVMAT10: - case GST_BUMPENVMAT11: - case GST_LIGHTSPOTEXPONENT: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - const CgFxScriptLoader::Vector1f CgFxScriptLoader::CgFloatGlobalStateListener::getValue( CGstateassignment cgStateAssignment ) - { - return Vector1f( cgStateAssignment ); - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgFloat2GlobalStateListener::CgFloat2GlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener(globalStateType, CG_FLOAT2) - { - - } - //--------------------------------------------------------------------- - const CgFxScriptLoader::Vector2f CgFxScriptLoader::CgFloat2GlobalStateListener::getValue( CGstateassignment cgStateAssignment ) - { - return Vector2f( cgStateAssignment ); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgFloat2GlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( mGlobalStateType ) - { - case GST_DEPTHBOUNDS: - case GST_DEPTHRANGE: - case GST_POLYGONOFFSET: - case GST_MAXANISOTROPY: - case GST_MAXMIPLEVEL: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgFloat3GlobalStateListener::CgFloat3GlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener(globalStateType, CG_FLOAT3) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgFloat3GlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( mGlobalStateType ) - { - case GST_POINTDISTANCEATTENUATION: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - const CgFxScriptLoader::Vector3f CgFxScriptLoader::CgFloat3GlobalStateListener::getValue( CGstateassignment cgStateAssignment ) - { - return Vector3f( cgStateAssignment ); - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgFloat4GlobalStateListener::CgFloat4GlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener(globalStateType, CG_FLOAT4) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgFloat4GlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( mGlobalStateType ) - { - case GST_BLENDCOLOR: - case GST_CLEARCOLOR: - case GST_CLIPPLANE: - case GST_FOGCOLOR: - case GST_FRAGMENTENVPARAMETER: - case GST_FRAGMENTLOCALPARAMETER: - case GST_LIGHTMODELAMBIENT: - case GST_AMBIENT: - case GST_LIGHTAMBIENT: - case GST_LIGHTDIFFUSE: - case GST_LIGHTPOSITION: - case GST_LIGHTSPECULAR: - case GST_LIGHTSPOTDIRECTION: - case GST_LIGHTDIRECTION: - case GST_MATERIALAMBIENT: - case GST_MATERIALDIFFUSE: - case GST_MATERIALEMISSION: - case GST_MATERIALEMISSIVE: - case GST_MATERIALSPECULAR: - case GST_TEXGENSOBJECTPLANE: - case GST_TEXGENSEYEPLANE: - case GST_TEXGENTOBJECTPLANE: - case GST_TEXGENTEYEPLANE: - case GST_TEXGENROBJECTPLANE: - case GST_TEXGENREYEPLANE: - case GST_TEXGENQOBJECTPLANE: - case GST_TEXGENQEYEPLANE: - case GST_TEXTUREENVCOLOR: - case GST_VERTEXENVPARAMETER: - case GST_VERTEXLOCALPARAMETER: - case GST_PIXELSHADERCONSTANT1: - case GST_VERTEXSHADERCONSTANT1: - case GST_PIXELSHADERCONSTANTF: - case GST_VERTEXSHADERCONSTANTF: - case GST_BORDERCOLOR: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - const CgFxScriptLoader::Vector4f CgFxScriptLoader::CgFloat4GlobalStateListener::getValue( CGstateassignment cgStateAssignment ) - { - return Vector4f( cgStateAssignment ); - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgFloat4x2GlobalStateListener::CgFloat4x2GlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener(globalStateType, CG_FLOAT4x2) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgFloat4x2GlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( mGlobalStateType ) - { - case GST_PIXELSHADERCONSTANT2: - case GST_VERTEXSHADERCONSTANT2: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgFloat4x3GlobalStateListener::CgFloat4x3GlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener(globalStateType, CG_FLOAT4x3) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgFloat4x3GlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( mGlobalStateType ) - { - case GST_PIXELSHADERCONSTANT3: - case GST_VERTEXSHADERCONSTANT3: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgFloat4x4GlobalStateListener::CgFloat4x4GlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener(globalStateType, CG_FLOAT4x4) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgFloat4x4GlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( mGlobalStateType ) - { - case GST_COLORMATRIX: - case GST_COLORTRANSFORM: - case GST_MODELVIEWMATRIX: - case GST_MODELVIEWTRANSFORM: - case GST_VIEWTRANSFORM: - case GST_WORLDTRANSFORM: - case GST_PROJECTIONMATRIX: - case GST_PROJECTIONTRANSFORM: - case GST_TEXTURETRANSFORM: - case GST_TEXTUREMATRIX: - case GST_PIXELSHADERCONSTANT: - case GST_VERTEXSHADERCONSTANT: - case GST_PIXELSHADERCONSTANT4: - case GST_VERTEXSHADERCONSTANT4: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgIntGlobalStateListener::CgIntGlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener(globalStateType, CG_INT) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgIntGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( mGlobalStateType ) - { - case GST_BLENDOP: - case GST_CLEARSTENCIL: - case GST_CLIPPLANEENABLE: - case GST_CULLMODE: - case GST_ZFUNC: - case GST_FOGTABLEMODE: - case GST_FOGVERTEXMODE: - case GST_LIGHTTYPE: - case GST_MULTISAMPLEMASK: - case GST_AMBIENTMATERIALSOURCE: - case GST_DIFFUSEMATERIALSOURCE: - case GST_EMISSIVEMATERIALSOURCE: - case GST_SPECULARMATERIALSOURCE: - case GST_VERTEXBLEND: - case GST_DESTBLEND: - case GST_SRCBLEND: - case GST_STENCILMASK: - case GST_STENCILPASS: - case GST_STENCILREF: - case GST_STENCILWRITEMASK: - case GST_STENCILZFAIL: - case GST_TEXTUREFACTOR: - case GST_STENCILFAIL: - case GST_WRAP0: - case GST_WRAP1: - case GST_WRAP2: - case GST_WRAP3: - case GST_WRAP4: - case GST_WRAP5: - case GST_WRAP6: - case GST_WRAP7: - case GST_WRAP8: - case GST_WRAP9: - case GST_WRAP10: - case GST_WRAP11: - case GST_WRAP12: - case GST_WRAP13: - case GST_WRAP14: - case GST_WRAP15: - case GST_ADDRESSU: - case GST_ADDRESSV: - case GST_ADDRESSW: - case GST_MIPMAPLODBIAS: - case GST_BLENDOPALPHA: - case GST_SRCBLENDALPHA: - case GST_DESTBLENDALPHA: - case GST_ALPHAOP: - case GST_COLOROP: - case GST_ALPHAARG0: - case GST_ALPHAARG1: - case GST_ALPHAARG2: - case GST_COLORARG0: - case GST_COLORARG1: - case GST_COLORARG2: - case GST_RESULTARG: - case GST_TEXCOORDINDEX: - case GST_TEXTURETRANSFORMFLAGS: - case GST_MIPFILTER: // todo - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - const CgFxScriptLoader::Vector1i CgFxScriptLoader::CgIntGlobalStateListener::getValue( CGstateassignment cgStateAssignment ) - { - return Vector1i(cgStateAssignment); - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgInt2GlobalStateListener::CgInt2GlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener(globalStateType, CG_INT2) - { - - } - //--------------------------------------------------------------------- - const CgFxScriptLoader::Vector2i CgFxScriptLoader::CgInt2GlobalStateListener::getValue( CGstateassignment cgStateAssignment ) - { - return Vector2i(cgStateAssignment); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgInt2GlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( mGlobalStateType ) - { - case GST_LINESTIPPLE: - case GST_FILLMODE: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgInt3GlobalStateListener::CgInt3GlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener(globalStateType, CG_INT3) - { - - } - //--------------------------------------------------------------------- - const CgFxScriptLoader::Vector3i CgFxScriptLoader::CgInt3GlobalStateListener::getValue( CGstateassignment cgStateAssignment ) - { - return Vector3i(cgStateAssignment); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgInt3GlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - // todo - error - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgInt4GlobalStateListener::CgInt4GlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener(globalStateType, CG_INT4) - { - - } - //--------------------------------------------------------------------- - const CgFxScriptLoader::Vector4i CgFxScriptLoader::CgInt4GlobalStateListener::getValue( CGstateassignment cgStateAssignment ) - { - return Vector4i(cgStateAssignment); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgInt4GlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( mGlobalStateType ) - { - case GST_SCISSOR: - case GST_PIXELSHADERCONSTANTI: - case GST_VERTEXSHADERCONSTANTI: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgSamplerGlobalStateListener::CgSamplerGlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener(globalStateType, CG_SAMPLER) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgSamplerGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( mGlobalStateType ) - { - case GST_SAMPLER: - case GST_TEXTURE1D: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgSampler2GlobalStateListener::CgSampler2GlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener(globalStateType, CG_SAMPLER2D) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgSampler2GlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( mGlobalStateType ) - { - case GST_TEXTURE2D: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgSampler3GlobalStateListener::CgSampler3GlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener( globalStateType, CG_SAMPLER3D ) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgSampler3GlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( mGlobalStateType ) - { - case GST_TEXTURE3D: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgSamplerCubeGlobalStateListener::CgSamplerCubeGlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener(globalStateType, CG_SAMPLERCUBE) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgSamplerCubeGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( mGlobalStateType ) - { - case GST_TEXTURECUBEMAP: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgSamplerRectGlobalStateListener::CgSamplerRectGlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener(globalStateType, CG_SAMPLERRECT) - { - - } - - void CgFxScriptLoader::CgSamplerRectGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( mGlobalStateType ) - { - case GST_TEXTURERECTANGLE: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgTextureGlobalStateListener::CgTextureGlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener(globalStateType, CG_TEXTURE) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgTextureGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( mGlobalStateType ) - { - case GST_TEXTURE: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgProgramGlobalStateListener::CgProgramGlobalStateListener( const GlobalStateType globalStateType ) - : CgGlobalStateListener(globalStateType, CG_PROGRAM_TYPE) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgProgramGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( mGlobalStateType ) - { - case GST_GEOMETRYPROGRAM: - case GST_VERTEXPROGRAM: - case GST_VERTEXSHADER: - case GST_FRAGMENTPROGRAM: - case GST_PIXELSHADER: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgBlendEquationGlobalStateListener::CgBlendEquationGlobalStateListener() - : CgIntGlobalStateListener(GST_BLENDEQUATION) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgBlendEquationGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)BET_FUNCADD , "FuncAdd"); - addStateEnumerant((int)BET_FUNCSUBTRACT , "FuncSubtract"); - addStateEnumerant((int)BET_MIN , "Min"); - addStateEnumerant((int)BET_MAX , "Max"); - addStateEnumerant((int)BET_LOGICOP ,"LogicOp"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgBlendEquationGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case BET_FUNCADD: // FuncAdd - case BET_FUNCSUBTRACT: // FuncSubtract - case BET_MIN: // Min - case BET_MAX: // Max - case BET_LOGICOP: // LogicOp - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgDepthFuncGlobalStateListener::CgDepthFuncGlobalStateListener() - : CgIntGlobalStateListener(GST_DEPTHFUNC) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgDepthFuncGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)DFT_NEVER , "Never"); - addStateEnumerant((int)DFT_LESS , "Less"); - addStateEnumerant((int)DFT_LEQUAL , "LEqual"); - addStateEnumerant((int)DFT_EQUAL , "Equal"); - addStateEnumerant((int)DFT_GREATER , "Greater"); - addStateEnumerant((int)DFT_NOTEQUAL , "NotEqual"); - addStateEnumerant((int)DFT_GEQUAL , "GEqual"); - addStateEnumerant((int)DFT_ALWAYS , "Always"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgDepthFuncGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case DFT_NEVER: // Never - case DFT_LESS: // Less - case DFT_LEQUAL: // LEqual - case DFT_EQUAL: // Equal - case DFT_GREATER: // Greater - case DFT_NOTEQUAL: // NotEqual - case DFT_GEQUAL: // GEqual - case DFT_ALWAYS : // Always - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgFogDistanceModeGlobalStateListener::CgFogDistanceModeGlobalStateListener() - : CgIntGlobalStateListener(GST_FOGDISTANCEMODE) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgFogDistanceModeGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)FDMT_EYERADIAL , "EyeRadial"); - addStateEnumerant((int)FDMT_EYEPLANE , "EyePlane"); - addStateEnumerant((int)FDMT_EYEPLANEABSOLUTE , "EyePlaneAbsolute"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgFogDistanceModeGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case FDMT_EYERADIAL: // EyeRadial - case FDMT_EYEPLANE: // EyePlane - case FDMT_EYEPLANEABSOLUTE: // EyePlaneAbsolute - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgFogModeGlobalStateListener::CgFogModeGlobalStateListener() - : CgIntGlobalStateListener(GST_FOGMODE) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgFogModeGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)FMT_LINEAR , "Linear"); - addStateEnumerant((int)FMT_EXP , "Exp"); - addStateEnumerant((int)FMT_EXP2 , "Exp2"); - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgFogModeGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case FMT_LINEAR: // Linear - case FMT_EXP: // Exp - case FMT_EXP2: // Exp2 - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgLightModelColorControlGlobalStateListener::CgLightModelColorControlGlobalStateListener() - : CgIntGlobalStateListener(GST_LIGHTMODELCOLORCONTROL) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgLightModelColorControlGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)LMCCT_SINGLECOLOR , "SingleColor"); - addStateEnumerant((int)LMCCT_SEPARATESPECULAR , "SeparateSpecular"); - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgLightModelColorControlGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case LMCCT_SINGLECOLOR: // SingleColor - case LMCCT_SEPARATESPECULAR: // SeparateSpecular - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgLogicOpGlobalStateListener::CgLogicOpGlobalStateListener() - : CgIntGlobalStateListener(GST_LOGICOP) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgLogicOpGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)LOT_CLEAR , "Clear"); - addStateEnumerant((int)LOT_AND , "And"); - addStateEnumerant((int)LOT_ANDREVERSE , "AndReverse"); - addStateEnumerant((int)LOT_COPY , "Copy"); - addStateEnumerant((int)LOT_ANDINVERTED , "AndInverted"); - addStateEnumerant((int)LOT_NOOP , "Noop"); - addStateEnumerant((int)LOT_XOR , "Xor"); - addStateEnumerant((int)LOT_OR , "Or"); - addStateEnumerant((int)LOT_NOR , "Nor"); - addStateEnumerant((int)LOT_EQUIV , "Equiv"); - addStateEnumerant((int)LOT_INVERT , "Invert"); - addStateEnumerant((int)LOT_ORREVERSE , "OrReverse"); - addStateEnumerant((int)LOT_COPYINVERTED , "CopyInverted"); - addStateEnumerant((int)LOT_NAND , "Nand"); - addStateEnumerant((int)LOT_SET , "Set"); - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgLogicOpGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case LOT_CLEAR: // Clear - case LOT_AND: // And - case LOT_ANDREVERSE: // AndReverse - case LOT_COPY: // Copy - case LOT_ANDINVERTED: // AndInverted - case LOT_NOOP: // Noop - case LOT_XOR: // Xor - case LOT_OR: // Or, - case LOT_NOR: // Nor - case LOT_EQUIV: // Equiv - case LOT_INVERT: // Invert - case LOT_ORREVERSE: // OrReverse - case LOT_COPYINVERTED: // CopyInverted - case LOT_NAND: // Nand - case LOT_SET: // Set - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgPointSpriteCoordOriginGlobalStateListener::CgPointSpriteCoordOriginGlobalStateListener() - : CgIntGlobalStateListener(GST_POINTSPRITECOORDORIGIN) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgPointSpriteCoordOriginGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)PSCOT_LOWERLEFT , "LowerLeft"); - addStateEnumerant((int)PSCOT_UPPERLEFT , "UpperLeft"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgPointSpriteCoordOriginGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case PSCOT_LOWERLEFT: // LowerLeft - case PSCOT_UPPERLEFT: // UpperLeft - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgPointSpriteRModeGlobalStateListener::CgPointSpriteRModeGlobalStateListener() - : CgIntGlobalStateListener(GST_POINTSPRITERMODE) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgPointSpriteRModeGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)PSRMT_ZERO , "Zero"); - addStateEnumerant((int)PSRMT_R , "R"); - addStateEnumerant((int)PSRMT_S , "S"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgPointSpriteRModeGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case PSRMT_ZERO: // Zero - case PSRMT_R: // R - case PSRMT_S: // S - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - - CgFxScriptLoader::CgShadeModelGlobalStateListener::CgShadeModelGlobalStateListener() - : CgIntGlobalStateListener(GST_SHADEMODEL) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgShadeModelGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)SMT_FLAT , "Flat"); - addStateEnumerant((int)SMT_SMOOTH , "Smooth"); - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgShadeModelGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case SMT_FLAT: // Flat - case SMT_SMOOTH: // Smooth - default: - // todo - error - break; - } - - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgTexGenModeGlobalStateListener::CgTexGenModeGlobalStateListener(const GlobalStateType globalStateType) - : CgIntGlobalStateListener(globalStateType) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgTexGenModeGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)TGMT_OBJECTLINEAR, "ObjectLinear"); - addStateEnumerant((int)TGMT_EYELINEAR, "EyeLinear"); - addStateEnumerant((int)TGMT_SPHEREMAP, "SphereMap"); - addStateEnumerant((int)TGMT_REFLECTIONMAP, "ReflectionMap"); - addStateEnumerant((int)TGMT_NORMALMAP, "NormalMap"); - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgTexGenModeGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case TGMT_OBJECTLINEAR: // ObjectLinear - case TGMT_EYELINEAR: // EyeLinear - case TGMT_SPHEREMAP: // SphereMap - case TGMT_REFLECTIONMAP: // ReflectionMap - case TGMT_NORMALMAP: // NormalMap - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgTextureEnvModeGlobalStateListener::CgTextureEnvModeGlobalStateListener() - : CgIntGlobalStateListener(GST_TEXTUREENVMODE) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgTextureEnvModeGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)BET_MODULATE, "Modulate"); - addStateEnumerant((int)BET_DECAL, "Decal"); - addStateEnumerant((int)BET_BLEND, "Blend"); - addStateEnumerant((int)BET_REPLACE, "Replace"); - addStateEnumerant((int)BET_ADD, "Add"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgTextureEnvModeGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case BET_MODULATE: // Modulate - case BET_DECAL: // Decal - case BET_BLEND: // Blend - case BET_REPLACE: // Replace - case BET_ADD: // Add - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgMinFilterGlobalStateListener::CgMinFilterGlobalStateListener() - : CgIntGlobalStateListener(GST_MINFILTER) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgMinFilterGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)MFT_NEAREST, "Nearest"); - addStateEnumerant((int)MFT_LINEAR, "Linear"); - addStateEnumerant((int)MFT_LINEARMIPMAPNEAREST, "LinearMipMapNearest"); - addStateEnumerant((int)MFT_NEARESTMIPMAPNEAREST, "NearestMipMapNearest"); - addStateEnumerant((int)MFT_NEARESTMIPMAPLINEAR, "NearestMipMapLinear"); - addStateEnumerant((int)MFT_LINEARMIPMAPLINEAR, "LinearMipMapLinear"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgMinFilterGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case MFT_NEAREST: // Nearest - case MFT_LINEAR: // Linear - case MFT_LINEARMIPMAPNEAREST: // LinearMipMapNearest - case MFT_NEARESTMIPMAPNEAREST: // NearestMipMapNearest - case MFT_NEARESTMIPMAPLINEAR: // NearestMipMapLinear - case MFT_LINEARMIPMAPLINEAR: // LinearMipMapLinear - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgMagFilterGlobalStateListener::CgMagFilterGlobalStateListener() - : CgIntGlobalStateListener(GST_MAGFILTER) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgMagFilterGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)MFT_NEAREST, "Nearest"); - addStateEnumerant((int)MFT_LINEAR, "Linear"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgMagFilterGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case MFT_NEAREST: // Nearest - case MFT_LINEAR: // Linear - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgFrontFaceGlobalStateListener::CgFrontFaceGlobalStateListener() - : CgIntGlobalStateListener(GST_FRONTFACE) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgFrontFaceGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)FFT_CW, "CW"); - addStateEnumerant((int)FFT_CCW, "CCW"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgFrontFaceGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case FFT_CW: // CW - case FFT_CCW: // CCW - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgCullFaceGlobalStateListener::CgCullFaceGlobalStateListener() - : CgIntGlobalStateListener(GST_CULLFACE) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgCullFaceGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)CFT_FRONT, "Front"); - addStateEnumerant((int)CFT_BACK, "Back"); - addStateEnumerant((int)CFT_FRONTANDBACK, "FrontAndBack"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgCullFaceGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case CFT_FRONT: // Front - case CFT_BACK: // Back - case CFT_FRONTANDBACK: // FrontAndBack - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgFogCoordSrcGlobalStateListener::CgFogCoordSrcGlobalStateListener() - : CgIntGlobalStateListener(GST_FOGCOORDSRC) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgFogCoordSrcGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)FCST_FRAGMENTDEPTH, "FragmentDepth"); - addStateEnumerant((int)FCST_FOGCOORD, "FogCoord"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgFogCoordSrcGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case FCST_FRAGMENTDEPTH: // FragmentDepth - case FCST_FOGCOORD: // FogCoord - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgAlphaFuncGlobalStateListener::CgAlphaFuncGlobalStateListener() - : CgFloat2GlobalStateListener(GST_ALPHAFUNC) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgAlphaFuncGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)AFT_NEVER, "Never"); - addStateEnumerant((int)AFT_LESS, "Less"); - addStateEnumerant((int)AFT_LEQUAL, "LEqual"); - addStateEnumerant((int)AFT_EQUAL, "Equal"); - addStateEnumerant((int)AFT_GREATER, "Greater"); - addStateEnumerant((int)AFT_NOTEQUAL, "NotEqual"); - addStateEnumerant((int)AFT_GEQUAL, "GEqual"); - addStateEnumerant((int)AFT_ALWAYS, "Always"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgAlphaFuncGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( static_cast(getValue(cgStateAssignment).x) ) - { - case AFT_NEVER: // Never - case AFT_LESS: // Less - case AFT_LEQUAL: // LEqual - case AFT_EQUAL: // Equal - case AFT_GREATER: // Greater - case AFT_NOTEQUAL: // NotEqual - case AFT_GEQUAL: // GEqual - case AFT_ALWAYS: // Always - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgBlendFuncGlobalStateListener::CgBlendFuncGlobalStateListener() - : CgInt2GlobalStateListener(GST_BLENDFUNC) - { - - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgBlendFuncGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)BF_ZERO, "Zero"); - addStateEnumerant((int)BF_ONE, "One"); - addStateEnumerant((int)BF_DESTCOLOR, "DestColor"); - addStateEnumerant((int)BF_ONEMINUSDESTCOLOR, "OneMinusDestColor"); - addStateEnumerant((int)BF_SRCALPHA, "SrcAlpha"); - addStateEnumerant((int)BF_ONEMINUSSRCALPHA, "OneMinusSrcAlpha"); - addStateEnumerant((int)BF_DSTALPHA, "DstAlpha"); - addStateEnumerant((int)BF_ONEMINUSDSTALPHA, "OneMinusDstAlpha"); - addStateEnumerant((int)BF_SRCALPHASATURATE, "SrcAlphaSaturate"); - addStateEnumerant((int)BF_SRCCOLOR, "SrcColor"); - addStateEnumerant((int)BF_ONEMINUSSRCCOLOR, "OneMinusSrcColor"); - addStateEnumerant((int)BF_CONSTANTCOLOR, "ConstantColor"); - addStateEnumerant((int)BF_ONEMINUSCONSTANTCOLOR, "OneMinusConstantColor"); - addStateEnumerant((int)BF_CONSTANTALPHA, "ConstantAlpha"); - addStateEnumerant((int)BF_ONEMINUSCONSTANTALPHA, "OneMinusConstantAlpha"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgBlendFuncGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment).x ) - { - case BF_ZERO: // Zero - case BF_ONE: // One - case BF_DESTCOLOR: // DestColor - case BF_ONEMINUSDESTCOLOR: // OneMinusDestColor - case BF_SRCALPHA: // SrcAlpha - case BF_ONEMINUSSRCALPHA: // OneMinusSrcAlpha - case BF_DSTALPHA: // DstAlpha - case BF_ONEMINUSDSTALPHA: // OneMinusDstAlpha - case BF_SRCALPHASATURATE: // SrcAlphaSaturate - case BF_SRCCOLOR: // SrcColor - case BF_ONEMINUSSRCCOLOR: // OneMinusSrcColor - case BF_CONSTANTCOLOR: // ConstantColor - case BF_ONEMINUSCONSTANTCOLOR: // OneMinusConstantColor - case BF_CONSTANTALPHA: // ConstantAlpha - case BF_ONEMINUSCONSTANTALPHA: // OneMinusConstantAlpha - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgBlendFuncSeparateGlobalStateListener::CgBlendFuncSeparateGlobalStateListener() - : CgInt4GlobalStateListener(GST_BLENDFUNCSEPARATE) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgBlendFuncSeparateGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)BFST_ZERO, "Zero"); - addStateEnumerant((int)BFST_ONE, "One"); - addStateEnumerant((int)BFST_DESTCOLOR, "DestColor"); - addStateEnumerant((int)BFST_ONEMINUSDESTCOLOR, "OneMinusDestColor"); - addStateEnumerant((int)BFST_SRCALPHA, "SrcAlpha"); - addStateEnumerant((int)BFST_ONEMINUSSRCALPHA, "OneMinusSrcAlpha"); - addStateEnumerant((int)BFST_DSTALPHA, "DstAlpha"); - addStateEnumerant((int)BFST_ONEMINUSDSTALPHA, "OneMinusDstAlpha"); - addStateEnumerant((int)BFST_SRCALPHASATURATE, "SrcAlphaSaturate"); - addStateEnumerant((int)BFST_SRCCOLOR, "SrcColor"); - addStateEnumerant((int)BFST_ONEMINUSSRCCOLOR, "OneMinusSrcColor"); - addStateEnumerant((int)BFST_CONSTANTCOLOR, "ConstantColor"); - addStateEnumerant((int)BFST_ONEMINUSCONSTANTCOLOR, "OneMinusConstantColor"); - addStateEnumerant((int)BFST_CONSTANTALPHA, "ConstantAlpha"); - addStateEnumerant((int)BFST_ONEMINUSCONSTANTALPHA, "OneMinusConstantAlpha"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgBlendFuncSeparateGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment).x ) - { - case BFST_ZERO: // Zero - case BFST_ONE: // One - case BFST_DESTCOLOR: // DestColor - case BFST_ONEMINUSDESTCOLOR: // OneMinusDestColor - case BFST_SRCALPHA: // SrcAlpha - case BFST_ONEMINUSSRCALPHA: // OneMinusSrcAlpha - case BFST_DSTALPHA: // DstAlpha - case BFST_ONEMINUSDSTALPHA: // OneMinusDstAlpha - case BFST_SRCALPHASATURATE: // SrcAlphaSaturate - case BFST_SRCCOLOR: // SrcColor - case BFST_ONEMINUSSRCCOLOR: // OneMinusSrcColor - case BFST_CONSTANTCOLOR: // ConstantColor - case BFST_ONEMINUSCONSTANTCOLOR: // OneMinusConstantColor - case BFST_CONSTANTALPHA: // ConstantAlpha - case BFST_ONEMINUSCONSTANTALPHA: // OneMinusConstantAlpha - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgBlendEquationSeparateGlobalStateListener::CgBlendEquationSeparateGlobalStateListener() - : CgInt2GlobalStateListener(GST_BLENDEQUATIONSEPARATE) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgBlendEquationSeparateGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)BEST_FUNCADD, "FuncAdd"); - addStateEnumerant((int)BEST_FUNCSUBTRACT, "FuncSubtract"); - addStateEnumerant((int)BEST_MIN, "Min"); - addStateEnumerant((int)BEST_MAX, "Max"); - addStateEnumerant((int)BEST_LOGICOP, "LogicOp"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgBlendEquationSeparateGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment).x ) - { - case BEST_FUNCADD: // FuncAdd - case BEST_FUNCSUBTRACT: // FuncSubtract - case BEST_MIN: // Min - case BEST_MAX: // Max - case BEST_LOGICOP: // LogicOp - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgColorMaterialGlobalStateListener::CgColorMaterialGlobalStateListener() - : CgInt2GlobalStateListener(GST_COLORMATERIAL) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgColorMaterialGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)CMT_FRONT, "Front"); - addStateEnumerant((int)CMT_BACK, "Back"); - addStateEnumerant((int)CMT_FRONTANDBACK, "FrontAndBack"); - addStateEnumerant((int)CMT_EMISSION, "Emission"); - addStateEnumerant((int)CMT_AMBIENT, "Ambient"); - addStateEnumerant((int)CMT_DIFFUSE, "Diffuse"); - addStateEnumerant((int)CMT_SPECULAR, "Specular"); - addStateEnumerant((int)CMT_AMBIENTANDDIFFUSE, "AmbientAndDiffuse"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgColorMaterialGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment).x ) - { - case CMT_FRONT: // Front - case CMT_BACK: // Back - case CMT_FRONTANDBACK: // FrontAndBack - case CMT_EMISSION: // Emission - case CMT_AMBIENT: // Ambient - case CMT_DIFFUSE: // Diffuse - case CMT_SPECULAR: // Specular - case CMT_AMBIENTANDDIFFUSE: // AmbientAndDiffuse - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgPolygonModeGlobalStateListener::CgPolygonModeGlobalStateListener() - : CgInt2GlobalStateListener(GST_POLYGONMODE) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgPolygonModeGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - - addStateEnumerant((int)PMT_FRONT, "Front"); - addStateEnumerant((int)PMT_BACK, "Back"); - addStateEnumerant((int)PMT_FRONTANDBACK, "FrontAndBack"); - addStateEnumerant((int)PMT_POINT, "Point"); - addStateEnumerant((int)PMT_LINE, "Line"); - addStateEnumerant((int)PMT_FILL, "Fill"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgPolygonModeGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment).x ) - { - case PMT_FRONT: // Front - case PMT_BACK: // Back - case PMT_FRONTANDBACK: // FrontAndBack - case PMT_POINT: // Point - case PMT_LINE: // Line - case PMT_FILL: // Fill - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgStencilFuncGlobalStateListener::CgStencilFuncGlobalStateListener() - : CgInt3GlobalStateListener(GST_STENCILFUNC) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgStencilFuncGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - addStateEnumerant((int)SFT_NEVER, "Never"); - addStateEnumerant((int)SFT_LESS, "Less"); - addStateEnumerant((int)SFT_LEQUAL, "LEqual"); - addStateEnumerant((int)SFT_EQUAL, "Equal"); - addStateEnumerant((int)SFT_GREATER, "Greater"); - addStateEnumerant((int)SFT_NOTEQUAL, "NotEqual"); - addStateEnumerant((int)SFT_GEQUAL, "GEqual"); - addStateEnumerant((int)SFT_ALWAYS, "Always"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgStencilFuncGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment).x ) - { - case SFT_NEVER: // Never - case SFT_LESS: // Less - case SFT_LEQUAL: // LEqual - case SFT_EQUAL: // Equal - case SFT_GREATER: // Greater - case SFT_NOTEQUAL: // NotEqual - case SFT_GEQUAL: // GEqual - case SFT_ALWAYS: // Always - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgStencilOpGlobalStateListener::CgStencilOpGlobalStateListener() - : CgInt3GlobalStateListener(GST_STENCILOP) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgStencilOpGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - addStateEnumerant((int)SOT_KEEP, "Keep"); - addStateEnumerant((int)SOT_ZERO, "Zero"); - addStateEnumerant((int)SOT_REPLACE, "Replace"); - addStateEnumerant((int)SOT_INCR, "Incr"); - addStateEnumerant((int)SOT_DECR, "Decr"); - addStateEnumerant((int)SOT_INVERT, "Invert"); - addStateEnumerant((int)SOT_INCRWRAP, "IncrWrap"); - addStateEnumerant((int)SOT_DECRWRAP, "DecrWrap"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgStencilOpGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment).x ) - { - case SOT_KEEP: // Keep - case SOT_ZERO: // Zero - case SOT_REPLACE: // Replace - case SOT_INCR: // Incr - case SOT_DECR: // Decr - case SOT_INVERT: // Invert - case SOT_INCRWRAP: // IncrWrap - case SOT_DECRWRAP: // DecrWrap - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgStencilFuncSeparateGlobalStateListener::CgStencilFuncSeparateGlobalStateListener() - : CgInt4GlobalStateListener(GST_STENCILFUNCSEPARATE) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgStencilFuncSeparateGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - addStateEnumerant((int)SFST_FRONT, "Front"); - addStateEnumerant((int)SFST_BACK, "Back"); - addStateEnumerant((int)SFST_FRONTANDBACK, "FrontAndBack"); - addStateEnumerant((int)SFST_NEVER, "Never"); - addStateEnumerant((int)SFST_LESS, "Less"); - addStateEnumerant((int)SFST_LEQUAL, "LEqual"); - addStateEnumerant((int)SFST_EQUAL, "Equal"); - addStateEnumerant((int)SFST_GREATER, "Greater"); - addStateEnumerant((int)SFST_NOTEQUAL, "NotEqual"); - addStateEnumerant((int)SFST_GEQUAL, "GEqual"); - addStateEnumerant((int)SFST_ALWAYS, "Always"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgStencilFuncSeparateGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment).x ) - { - case SFST_FRONT: // Front - case SFST_BACK: // Back - case SFST_FRONTANDBACK: // FrontAndBack - case SFST_NEVER: // Never - case SFST_LESS: // Less - case SFST_LEQUAL: // LEqual - case SFST_EQUAL: // Equal - case SFST_GREATER: // Greater - case SFST_NOTEQUAL: // NotEqual - case SFST_GEQUAL: // GEqual - case SFST_ALWAYS: // Always - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgStencilMaskSeparateGlobalStateListener::CgStencilMaskSeparateGlobalStateListener() - : CgInt2GlobalStateListener(GST_STENCILMASKSEPARATE) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgStencilMaskSeparateGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - addStateEnumerant((int)BET_FRONT, "Front"); - addStateEnumerant((int)BET_BACK, "Back"); - addStateEnumerant((int)BET_FRONTANDBACK, "FrontAndBack"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgStencilMaskSeparateGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment).x ) - { - case BET_FRONT: // Front - case BET_BACK: // Back - case BET_FRONTANDBACK: // FrontAndBack - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgStencilOpSeparateGlobalStateListener::CgStencilOpSeparateGlobalStateListener() - : CgInt4GlobalStateListener(GST_STENCILOPSEPARATE) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgStencilOpSeparateGlobalStateListener::createState() - { - CgGlobalStateListener::createState(); - addStateEnumerant((int)BET_KEEP, "Keep"); - addStateEnumerant((int)BET_ZERO, "Zero"); - addStateEnumerant((int)BET_REPLACE, "Replace"); - addStateEnumerant((int)BET_INCR, "Incr"); - addStateEnumerant((int)BET_DECR, "Decr"); - addStateEnumerant((int)BET_INVERT, "Invert"); - addStateEnumerant((int)BET_INCRWRAP, "IncrWrap"); - addStateEnumerant((int)BET_DECRWRAP, "DecrWrap"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgStencilOpSeparateGlobalStateListener::updatePass( Pass * ogrePass, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment).x ) - { - case BET_KEEP: // Keep - case BET_ZERO: // Zero - case BET_REPLACE: // Replace - case BET_INCR: // Incr - case BET_DECR: // Decr - case BET_INVERT: // Invert - case BET_INCRWRAP: // IncrWrap - case BET_DECRWRAP: // DecrWrap - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgSamplerStateListener::CgSamplerStateListener( SamplerStateType samplerStateType, CGtype cgType ) - :CgStateListener(cgType), - mSamplerStateType(samplerStateType) - { - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::CgSamplerStateListener::~CgSamplerStateListener() - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgSamplerStateListener::createState() - { - const char * typeNameAsString = CgFxScriptLoader::getSingleton().getSamplerStateNameTypeToString(mSamplerStateType); - mCgState = cgCreateSamplerState( mCgContext, typeNameAsString, mCgType ); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgSamplerStateListener::upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) - { - - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgIntSamplerStateListener::CgIntSamplerStateListener(const SamplerStateType samplerStateType) - : CgSamplerStateListener(samplerStateType, CG_INT) - { - - } - //--------------------------------------------------------------------- - const CgFxScriptLoader::Vector1i CgFxScriptLoader::CgIntSamplerStateListener::getValue( CGstateassignment cgStateAssignment ) - { - return Vector1i(cgStateAssignment); - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgIntSamplerStateListener::upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) - { - - // todo - error - - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgBoolSamplerStateListener::CgBoolSamplerStateListener( const SamplerStateType samplerStateType ) - : CgSamplerStateListener(samplerStateType, CG_BOOL) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgBoolSamplerStateListener::upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) - { - switch( mSamplerStateType ) - { - case SST_GENERATEMIPMAP: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgFloatSamplerStateListener::CgFloatSamplerStateListener( const SamplerStateType samplerStateType ) - : CgSamplerStateListener(samplerStateType, CG_FLOAT) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgFloatSamplerStateListener::upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) - { - switch( mSamplerStateType ) - { - case SST_MIPMAPLODBIAS: - case SST_LODBIAS: - case SST_MAXMIPLEVEL: - case SST_MAXANISOTROPY: - case SST_MINMIPLEVEL: - case SST_SRGBTEXTURE: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgFloat4SamplerStateListener::CgFloat4SamplerStateListener( const SamplerStateType samplerStateType ) - : CgSamplerStateListener(samplerStateType, CG_FLOAT4) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgFloat4SamplerStateListener::upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) - { - switch( mSamplerStateType ) - { - case SST_BORDERCOLOR: - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgTextureSamplerStateListener::CgTextureSamplerStateListener( const SamplerStateType samplerStateType ) - : CgSamplerStateListener(samplerStateType, CG_TEXTURE) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgTextureSamplerStateListener::upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) - { - parseTextureName(getCgParameter(cgStateAssignment), ogreTextureUnitState); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgTextureSamplerStateListener::parseTextureName( CGparameter cgParameter, TextureUnitState * ogreTextureUnitState ) - { - CGannotation cgAnnotation = cgGetNamedParameterAnnotation(cgParameter, "ResourceName"); - if (cgAnnotation && cgGetAnnotationType(cgAnnotation) == CG_STRING) - { - const char * textureName = cgGetStringAnnotationValue(cgAnnotation); - if (textureName) - { - ogreTextureUnitState->setTextureName(textureName, parseTextureType(cgParameter, ogreTextureUnitState)); - } - } - } - //--------------------------------------------------------------------- - TextureType CgFxScriptLoader::CgTextureSamplerStateListener::parseTextureType( CGparameter cgParameter, TextureUnitState * ogreTextureUnitState ) - { - CGannotation cgAnnotation = cgGetNamedParameterAnnotation(cgParameter, "ResourceType"); - if (cgAnnotation && cgGetAnnotationType(cgAnnotation) == CG_STRING) - { - String textureType = cgGetStringAnnotationValue(cgAnnotation); - StringUtil::toLowerCase(textureType); - if ("1d" == textureType) - { - return TEX_TYPE_1D; - } - if ("2d" == textureType) - { - return TEX_TYPE_2D; - } - if ("3d" == textureType) - { - return TEX_TYPE_3D; - } - if ("cube" == textureType) - { - return TEX_TYPE_CUBE_MAP; - } - } - return TEX_TYPE_2D; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgWrapSamplerStateListener::CgWrapSamplerStateListener( const SamplerStateType samplerStateType ) - : CgIntSamplerStateListener(samplerStateType) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgWrapSamplerStateListener::createState() - { - CgSamplerStateListener::createState(); - - addStateEnumerant((int)WT_REPEAT , "Repeat"); - addStateEnumerant((int)WT_CLAMP , "Clamp"); - addStateEnumerant((int)WT_CLAMPTOEDGE , "ClampToEdge"); - addStateEnumerant((int)WT_CLAMPTOBORDER , "ClampToBorder"); - addStateEnumerant((int)WT_MIRROREDREPEAT , "MirroredRepeat"); - addStateEnumerant((int)WT_MIRRORCLAMP , "MirrorClamp"); - addStateEnumerant((int)WT_MIRRORCLAMPTOEDGE , "MirrorClampToEdge"); - addStateEnumerant((int)WT_MIRRORCLAMPTOBORDER , "MirrorClampToBorder"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgWrapSamplerStateListener::upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) - { - TextureAddressingMode ogreTextureAddressingMode = TextureUnitState::TAM_WRAP; - ogreTextureAddressingMode = getOgreTextureAddressingMode(cgStateAssignment); - - Sampler::UVWAddressingMode ogreUVWAddressingMode = ogreTextureUnitState->getTextureAddressingMode(); - - switch( mSamplerStateType ) - { - case SST_WRAPS: - ogreUVWAddressingMode.u = ogreTextureAddressingMode; - break; - case SST_WRAPT: - ogreUVWAddressingMode.v = ogreTextureAddressingMode; - break; - case SST_WRAPR: - ogreUVWAddressingMode.w = ogreTextureAddressingMode; - break; - default: - // todo - error - break; - } - ogreTextureUnitState->setTextureAddressingMode( ogreUVWAddressingMode ); - - } - //--------------------------------------------------------------------- - TextureAddressingMode CgFxScriptLoader::CgWrapSamplerStateListener::getOgreTextureAddressingMode( CGstateassignment cgStateAssignment ) - { - TextureAddressingMode ogreTextureAddressingMode = TextureUnitState::TAM_WRAP; - switch( getValue( cgStateAssignment ) ) - { - case WT_REPEAT: // Repeat - ogreTextureAddressingMode = TextureUnitState::TAM_WRAP; - break; - case WT_CLAMP: // Clamp - ogreTextureAddressingMode = TextureUnitState::TAM_CLAMP; - break; - case WT_CLAMPTOEDGE: // ClampToEdge - ogreTextureAddressingMode = TextureUnitState::TAM_CLAMP; - break; - case WT_CLAMPTOBORDER: // ClampToBorder - ogreTextureAddressingMode = TextureUnitState::TAM_BORDER; - break; - case WT_MIRROREDREPEAT: // MirroredRepeat - ogreTextureAddressingMode = TextureUnitState::TAM_MIRROR; - break; - case WT_MIRRORCLAMP: // MirrorClamp - ogreTextureAddressingMode = TextureUnitState::TAM_MIRROR; - break; - case WT_MIRRORCLAMPTOEDGE: // MirrorClampToEdge - ogreTextureAddressingMode = TextureUnitState::TAM_MIRROR; - break; - case WT_MIRRORCLAMPTOBORDER: // MirrorClampToBorder - ogreTextureAddressingMode = TextureUnitState::TAM_MIRROR; - break; - default: - // todo - error - ogreTextureAddressingMode = TextureUnitState::TAM_WRAP; - break; - } - return ogreTextureAddressingMode; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgCompareModeSamplerStateListener::CgCompareModeSamplerStateListener() - : CgIntSamplerStateListener(SST_COMPAREMODE) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgCompareModeSamplerStateListener::createState() - { - CgSamplerStateListener::createState(); - - addStateEnumerant((int)CMT_NONE , "None"); - addStateEnumerant((int)CMT_COMPARERTOTEXTURE , "CompareRToTexture"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgCompareModeSamplerStateListener::upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case CMT_NONE: // None - case CMT_COMPARERTOTEXTURE: // CompareRToTexture - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgCompareFuncSamplerStateListener::CgCompareFuncSamplerStateListener( ) - : CgIntSamplerStateListener(SST_COMPAREFUNC) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgCompareFuncSamplerStateListener::createState() - { - CgSamplerStateListener::createState(); - - addStateEnumerant((int)CFT_NEVER , "Never"); - addStateEnumerant((int)CFT_LESS , "Less"); - addStateEnumerant((int)CFT_LEQUAL , "LEqual"); - addStateEnumerant((int)CFT_EQUAL , "Equal"); - addStateEnumerant((int)CFT_GREATER , "Greater"); - addStateEnumerant((int)CFT_NOTEQUAL , "NotEqual"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgCompareFuncSamplerStateListener::upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case CFT_NEVER: // Never - case CFT_LESS: // Less - case CFT_LEQUAL: // LEqual - case CFT_EQUAL: // Equal - case CFT_GREATER: // Greater - case CFT_NOTEQUAL: // NotEqual - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgDepthModeSamplerStateListener::CgDepthModeSamplerStateListener() - : CgIntSamplerStateListener(SST_DEPTHMODE) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgDepthModeSamplerStateListener::createState() - { - CgSamplerStateListener::createState(); - - addStateEnumerant((int)DMT_ALPHA , "Alpha"); - addStateEnumerant((int)DMT_INTENSITY , "Intensity"); - addStateEnumerant((int)DMT_LUMINANCE , "Luminance"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgDepthModeSamplerStateListener::upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case DMT_ALPHA: // Alpha - case DMT_INTENSITY: // Intensity - case DMT_LUMINANCE: // Luminance - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgMinFilterSamplerStateListener::CgMinFilterSamplerStateListener() - : CgIntSamplerStateListener(SST_MINFILTER) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgMinFilterSamplerStateListener::createState() - { - CgSamplerStateListener::createState(); - - addStateEnumerant((int)MINFT_NEAREST , "Nearest"); - addStateEnumerant((int)MINFT_LINEAR , "Linear"); - addStateEnumerant((int)MINFT_LINEARMIPMAPNEAREST , "LinearMipMapNearest"); - addStateEnumerant((int)MINFT_NEARESTMIPMAPNEAREST , "NearestMipMapNearest"); - addStateEnumerant((int)MINFT_NEARESTMIPMAPLINEAR , "NearestMipMapLinear"); - addStateEnumerant((int)MINFT_LINEARMIPMAPLINEAR , "LinearMipMapLinear"); - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgMinFilterSamplerStateListener::upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case MINFT_NEAREST: // Nearest - case MINFT_LINEAR: // Linear - case MINFT_LINEARMIPMAPNEAREST: // LinearMipMapNearest - case MINFT_NEARESTMIPMAPNEAREST: // NearestMipMapNearest - case MINFT_NEARESTMIPMAPLINEAR: // NearestMipMapLinear - case MINFT_LINEARMIPMAPLINEAR: // LinearMipMapLinear - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgMagFilterSamplerStateListener::CgMagFilterSamplerStateListener() - : CgIntSamplerStateListener(SST_MAGFILTER) - { - CgSamplerStateListener::createState(); - - addStateEnumerant((int)MAGFT_NEAREST, "Nearest"); - addStateEnumerant((int)MAGFT_LINEAR , "Linear"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgMagFilterSamplerStateListener::createState() - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgMagFilterSamplerStateListener::upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case MAGFT_NEAREST: // Nearest - case MAGFT_LINEAR: // Linear - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgMipFilterSamplerStateListener::CgMipFilterSamplerStateListener() - : CgIntSamplerStateListener(SST_MIPFILTER) - { - CgSamplerStateListener::createState(); - - addStateEnumerant((int)MIPFT_NONE , "None"); - addStateEnumerant((int)MIPFT_POINT , "Point"); - addStateEnumerant((int)MIPFT_LINEAR , "Linear"); - addStateEnumerant((int)MIPFT_ANISOTROPIC , "Nisotropic"); - addStateEnumerant((int)MIPFT_PYRAMIDALQUAD , "PyramidalQuad"); - addStateEnumerant((int)MIPFT_GAUSSIANQUAD , "GaussianQuad"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgMipFilterSamplerStateListener::createState() - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgMipFilterSamplerStateListener::upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) - { - switch( getValue(cgStateAssignment) ) - { - case MIPFT_NONE: // filtering disabled (valid for mip filter only) - case MIPFT_POINT: // nearest - case MIPFT_LINEAR: // linear interpolation - case MIPFT_ANISOTROPIC: // anisotropic - case MIPFT_PYRAMIDALQUAD: // 4-sample tent - case MIPFT_GAUSSIANQUAD: // 4-sample gaussian - default: - // todo - error - break; - } - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - CgFxScriptLoader::CgTextureAddressSamplerStateListener::CgTextureAddressSamplerStateListener( const SamplerStateType samplerStateType ) - : CgIntSamplerStateListener(samplerStateType) - { - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgTextureAddressSamplerStateListener::createState() - { - CgSamplerStateListener::createState(); - - addStateEnumerant((int)TAT_WRAP, "Wrap"); - addStateEnumerant((int)TAT_MIRROR, "Mirror"); - addStateEnumerant((int)TAT_CLAMP, "Clamp"); - addStateEnumerant((int)TAT_BORDER, "Border"); - addStateEnumerant((int)TAT_MIRRORONCE, "MirrorOnce"); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::CgTextureAddressSamplerStateListener::upateTextureUnitState( TextureUnitState * ogreTextureUnitState, CGstateassignment cgStateAssignment ) - { - switch( mSamplerStateType ) - { - case SST_ADDRESSU: - case SST_ADDRESSV: - case SST_ADDRESSW: - default: - // todo - error - break; - } - - switch( getValue(cgStateAssignment) ) - { - case TAT_WRAP: // Wrap - case TAT_MIRROR: // Mirror - case TAT_CLAMP: // Clamp - case TAT_BORDER: // Border - case TAT_MIRRORONCE: // MirrorOnce - default: - // todo - error - break; - } - - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - template<> CgFxScriptLoader *Singleton::msSingleton = 0; - CgFxScriptLoader* CgFxScriptLoader::getSingletonPtr(void) - { - return msSingleton; - } - CgFxScriptLoader& CgFxScriptLoader::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //--------------------------------------------------------------------- - CgFxScriptLoader::CgFxScriptLoader() - { - mCgContext = cgCreateContext(); - - mCgStateListenerVector.resize(GST_COUNT); - for (int i = GST_FIRST ; i < GST_COUNT ; i++) - { - const GlobalStateType type = static_cast(i); - CgGlobalStateListener * newState = createCgGlobalStateListener(type); - mCgStateListenerVector[i] = newState; - mCgStateListenerVector[i]->init(); - mCgGlobalStateToListenerMap[mCgStateListenerVector[i]->getCgState()] = newState; - } - - mCgSamplerStateListenerVector.resize(SST_COUNT); - for (int i = SST_FIRST ; i < SST_COUNT ; i++) - { - const SamplerStateType type = static_cast(i); - CgSamplerStateListener * newState = createCgSamplerStateListener(type); - mCgSamplerStateListenerVector[i] = newState; - mCgSamplerStateListenerVector[i]->init(); - mCgSamplerStateToListenerMap[mCgSamplerStateListenerVector[i]->getCgState()] = newState; - - } - - - - // Scripting is supported by this manager - mScriptPatterns.push_back("*.cgfx"); - ResourceGroupManager::getSingleton()._registerScriptLoader(this); - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::~CgFxScriptLoader() - { - for (size_t i = 0 ; i < mCgStateListenerVector.size() ; i++) - { - OGRE_DELETE mCgStateListenerVector[i]; - } - - for (size_t i = 0 ; i < mCgSamplerStateListenerVector.size() ; i++) - { - OGRE_DELETE mCgSamplerStateListenerVector[i]; - } - - - cgDestroyContext(mCgContext); - - // Unregister with resource group manager - ResourceGroupManager::getSingleton()._unregisterScriptLoader(this); - } - //--------------------------------------------------------------------- - CGcontext CgFxScriptLoader::getCgContext() const - { - return mCgContext; - } - //--------------------------------------------------------------------- - const StringVector& CgFxScriptLoader::getScriptPatterns(void) const - { - return mScriptPatterns; - } - //--------------------------------------------------------------------- - Real CgFxScriptLoader::getLoadingOrder(void) const - { - // before the normal material manager - so a normal material can inherits from a cgfx material - return 99.0f; - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::parseScript( DataStreamPtr& stream, const String& groupName ) - { - String streamAsString = stream->getAsString(); - - MaterialPtr ogreMaterial = MaterialManager::getSingleton().create(stream->getName(), groupName); - - String sourceToUse = HighLevelGpuProgram::_resolveIncludes(streamAsString, ogreMaterial.get(), stream->getName(), true); - - CGeffect cgEffect = cgCreateEffect(mCgContext, sourceToUse.c_str(), NULL); - checkForCgError("CgFxScriptLoader::parseScript", - "Unable to Create cg Effect: ", mCgContext); - - ogreMaterial->removeAllTechniques(); - parseCgEffect(cgEffect, ogreMaterial); - - cgDestroyEffect(cgEffect); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::parseCgEffect( CGeffect cgEffect, MaterialPtr ogreMaterial ) - { - parseCgEffectTechniques(cgEffect, ogreMaterial); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::parseCgEffectTechniques( CGeffect cgEffect, MaterialPtr ogreMaterial ) - { - CGtechnique cgTechnique = cgGetFirstTechnique(cgEffect); - while (cgTechnique) - { - Technique * ogreTechnique = ogreMaterial->createTechnique(); - - const char * cgTechniqueName = cgGetTechniqueName(cgTechnique); - if (cgTechniqueName) - { - ogreTechnique->setName(cgTechniqueName); - } - - ogreTechnique->removeAllPasses(); - - parseCgTechnique(cgTechnique, ogreTechnique); - - cgTechnique = cgGetNextTechnique(cgTechnique); - } - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::parseCgTechnique( CGtechnique cgTechnique, Technique * ogreTechnique ) - { - CGpass cgPass = cgGetFirstPass(cgTechnique); - while (cgPass) - { - - Pass * ogrePass = ogreTechnique->createPass(); - const char * cgPassName = cgGetPassName(cgPass); - if (cgPassName) - { - ogrePass->setName(cgPassName); - } - - parseCgPass(cgPass, ogrePass); - parseSamplerParameters(cgPass, ogrePass); - - cgPass = cgGetNextPass(cgPass); - } - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::parseCgPass( CGpass cgPass, Pass * ogrePass ) - { - parseCgProgram(cgPass, ogrePass, GPT_VERTEX_PROGRAM); - parseCgProgram(cgPass, ogrePass, GPT_FRAGMENT_PROGRAM); - - - parsePassStateAssignments(cgPass, ogrePass); - - - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::parseCgProgram( CGpass cgPass, Pass * ogrePass, const GpuProgramType ogreProgramType ) - { - const char *stateName = NULL; - switch(ogreProgramType) - { - case GPT_VERTEX_PROGRAM: - stateName = "VertexProgram"; - break; - case GPT_FRAGMENT_PROGRAM: - stateName = "FragmentProgram"; - break; - case GPT_GEOMETRY_PROGRAM: - stateName = "GeometryProgram"; - break; - case GPT_COMPUTE_PROGRAM: - case GPT_DOMAIN_PROGRAM: - case GPT_HULL_PROGRAM: - break; - } - CGstateassignment cgStateAssignment = cgGetNamedStateAssignment(cgPass, stateName); - if (!cgStateAssignment) - { - switch(ogreProgramType) - { - case GPT_VERTEX_PROGRAM: - stateName = "VertexShader"; - break; - case GPT_FRAGMENT_PROGRAM: - stateName = "PixelShader"; - break; - case GPT_GEOMETRY_PROGRAM: - stateName = "GeometryShader"; - break; - case GPT_COMPUTE_PROGRAM: - case GPT_DOMAIN_PROGRAM: - case GPT_HULL_PROGRAM: - break; - } - - cgStateAssignment = cgGetNamedStateAssignment(cgPass, stateName); - if (!cgStateAssignment) - { - return; - } - } - - - - CGprogram cgProgram = cgGetProgramStateAssignmentValue(cgStateAssignment); - - CGparameter cgParameter = cgGetFirstParameter(cgProgram, CG_PROGRAM); - while (cgParameter) - { - String paramName = cgGetParameterName(cgParameter); - cgParameter = cgGetNextParameter(cgParameter); - } - - - const char * source = cgGetProgramString(cgProgram, CG_PROGRAM_SOURCE); - const char * entry = cgGetProgramString(cgProgram, CG_PROGRAM_ENTRY); - const char * profile = cgGetProgramString(cgProgram, CG_PROGRAM_PROFILE); - - // The name is all the path to this shader combined with the entry point and profile so it will be unique. - StringStream programName; - programName << ogrePass->getParent()->getParent()->getName() << "|"; // Material - programName << entry << "|"; // entry - programName << profile << "|"; // profile - programName << (ogrePass->getParent()->getParent()->getNumTechniques() - 1) << "-"; // Technique number - programName << ogrePass->getParent()->getName() << "|"; // Technique - programName << (ogrePass->getParent()->getNumPasses() - 1) << "-"; // Pass number - programName << ogrePass->getName(); // Pass - - String ProgramNameAsString = programName.str(); - - HighLevelGpuProgramPtr ogreProgram = - HighLevelGpuProgramManager::getSingleton(). - createProgram(ProgramNameAsString, - ogrePass->getParent()->getParent()->getGroup(), - "cg", - ogreProgramType); - - ogreProgram->setSource(source); - ogreProgram->setParameter("entry_point", entry); - ogreProgram->setParameter("profiles", profile); - - //ogreProgram->load(); - if (ogreProgram->isSupported()) - { - - ogreProgram->load(); - ogreProgram->createParameters(); - - GpuProgramParametersSharedPtr ogreProgramParameters = ogreProgram->getDefaultParameters(); - parseCgProgramParameters(cgPass, ogreProgramParameters); - - switch(ogreProgramType) - { - case GPT_VERTEX_PROGRAM: - ogrePass->setVertexProgram(ogreProgram->getName()); - break; - case GPT_FRAGMENT_PROGRAM: - ogrePass->setFragmentProgram(ogreProgram->getName()); - break; - case GPT_GEOMETRY_PROGRAM: - ogrePass->setGeometryProgram(ogreProgram->getName()); - break; - case GPT_DOMAIN_PROGRAM: - case GPT_COMPUTE_PROGRAM: - case GPT_HULL_PROGRAM: - break; - } - - } - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::parseCgProgramParameters( CGpass cgPass, GpuProgramParametersSharedPtr ogreProgramParameters ) - { - CGeffect cgEffect = cgGetTechniqueEffect(cgGetPassTechnique(cgPass)); - - for(auto& it : ogreProgramParameters->getConstantDefinitions().map) - { - // get the constant definition - const String& ogreParamName =it.first; - - CGparameter cgParameter = cgGetNamedEffectParameter(cgEffect, ogreParamName.c_str()); - // try to find it without case - if (!cgParameter) - { - CGparameter cgParameterToFind = cgGetFirstEffectParameter(cgEffect); - String ogreParamNameLower = ogreParamName; - Ogre::StringUtil::toLowerCase(ogreParamNameLower); - - while (cgParameterToFind) - { - String cgParamNameLower = cgGetParameterName(cgParameterToFind); - Ogre::StringUtil::toLowerCase(cgParamNameLower); - - if (cgParamNameLower == ogreParamNameLower) - { - cgParameter = cgParameterToFind; - break; - } - - cgParameterToFind = cgGetNextParameter(cgParameterToFind); - } - - } - if (cgParameter) - { - parseCgProgramParameter(cgParameter, ogreProgramParameters, ogreParamName); - } - else - { - // todo - some kind of error - } - } - - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::parseCgProgramParameter( CGparameter cgParameter, GpuProgramParametersSharedPtr ogreProgramParameters, const String& ogreParamName ) - { - - bool isAutoConstant = - parseAutoConstantParam(cgParameter, - ogreProgramParameters, - ogreParamName); - - if (!isAutoConstant) - { - - CGtype cgParamType = cgGetParameterType(cgParameter); - CGtype cgParameterBaseType = cgGetParameterBaseType(cgParameter); - - switch(cgParameterBaseType) - { - case CG_FLOAT: - parseFloatCgProgramParameter(cgParamType, cgParameter, ogreProgramParameters, ogreParamName); - break; - case CG_INT: - parseIntCgProgramParameter(cgParamType, cgParameter, ogreProgramParameters, ogreParamName); - break; - case CG_BOOL: - // todo - break; - case CG_FIXED: - // todo - break; - case CG_HALF: - // todo - break; - default: - // todo error - break; - - } - } - - } - //--------------------------------------------------------------------- - CgFxScriptLoader::FXSemanticID CgFxScriptLoader::cgSemanticStringToType( const char * cgParamSemantic ) - { - String sem = cgParamSemantic; - Ogre::StringUtil::toLowerCase(sem); - - if ("none" == sem) return FXS_NONE; - if ("unknown" == sem) return FXS_UNKNOWN; - if ("position" == sem) return FXS_POSITION; - if ("direction" == sem) return FXS_DIRECTION; - if ("color" == sem) return FXS_COLOR; - if ("diffuse" == sem) return FXS_DIFFUSE; - if ("specular" == sem) return FXS_SPECULAR; - if ("ambient" == sem) return FXS_AMBIENT; - if ("emission" == sem) return FXS_EMISSION; - if ("emissive" == sem) return FXS_EMISSIVE; - if ("specularpower" == sem) return FXS_SPECULARPOWER; - if ("refraction" == sem) return FXS_REFRACTION; - if ("opacity" == sem) return FXS_OPACITY; - if ("environment" == sem) return FXS_ENVIRONMENT; - if ("environmentnormal" == sem) return FXS_ENVIRONMENTNORMAL; - if ("normal" == sem) return FXS_NORMAL; - if ("height" == sem) return FXS_HEIGHT; - if ("attenuation" == sem) return FXS_ATTENUATION; - if ("rendercolortarget" == sem) return FXS_RENDERCOLORTARGET; - if ("renderdepthstenciltarget" == sem) return FXS_RENDERDEPTHSTENCILTARGET; - if ("viewportpixelsize" == sem) return FXS_VIEWPORTPIXELSIZE; - if ("cameraposition" == sem) return FXS_CAMERAPOSITION; - if ("time" == sem) return FXS_TIME; - if ("elapsedtime" == sem) return FXS_ELAPSEDTIME; - if ("animationtime" == sem) return FXS_ANIMATIONTIME; - if ("animationtick" == sem) return FXS_ANIMATIONTICK; - if ("mouseposition" == sem) return FXS_MOUSEPOSITION; - if ("leftmousedown" == sem) return FXS_LEFTMOUSEDOWN; - if ("world" == sem) return FXS_WORLD; - if ("view" == sem) return FXS_VIEW; - if ("projection" == sem) return FXS_PROJECTION; - if ("worldtranspose" == sem) return FXS_WORLDTRANSPOSE; - if ("viewtranspose" == sem) return FXS_VIEWTRANSPOSE; - if ("projectiontranspose" == sem) return FXS_PROJECTIONTRANSPOSE; - if ("worldview" == sem) return FXS_WORLDVIEW; - if ("worldviewprojection" == sem) return FXS_WORLDVIEWPROJECTION; - if ("worldinverse" == sem) return FXS_WORLDINVERSE; - if ("viewinverse" == sem) return FXS_VIEWINVERSE; - if ("projectioninverse" == sem) return FXS_PROJECTIONINVERSE; - if ("worldinversetranspose" == sem) return FXS_WORLDINVERSETRANSPOSE; - if ("viewinversetranspose" == sem) return FXS_VIEWINVERSETRANSPOSE; - if ("projectioninversetranspose" == sem) return FXS_PROJECTIONINVERSETRANSPOSE; - if ("worldviewinverse" == sem) return FXS_WORLDVIEWINVERSE; - if ("worldviewtranspose" == sem) return FXS_WORLDVIEWTRANSPOSE; - if ("worldviewinversetranspose" == sem) return FXS_WORLDVIEWINVERSETRANSPOSE; - if ("worldviewprojectioninverse" == sem) return FXS_WORLDVIEWPROJECTIONINVERSE; - if ("worldviewprojectiontranspose" == sem) return FXS_WORLDVIEWPROJECTIONTRANSPOSE; - if ("worldviewprojectioninversetranspose" == sem) return FXS_WORLDVIEWPROJECTIONINVERSETRANSPOSE; - if ("viewprojection" == sem) return FXS_VIEWPROJECTION; - if ("viewprojectiontranspose" == sem) return FXS_VIEWPROJECTIONTRANSPOSE; - if ("viewprojectioninverse" == sem) return FXS_VIEWPROJECTIONINVERSE; - if ("viewprojectioninversetranspose" == sem) return FXS_VIEWPROJECTIONINVERSETRANSPOSE; - if ("fxcomposer_resetpulse" == sem) return FXS_FXCOMPOSER_RESETPULSE; - if ("standardsglobal" == sem) return FXS_STANDARDSGLOBAL; - if ("unitsscale" == sem) return FXS_UNITSSCALE; - if ("power" == sem) return FXS_POWER; - if ("diffusemap" == sem) return FXS_DIFFUSEMAP; - if ("specularmap" == sem) return FXS_SPECULARMAP; - if ("envmap" == sem) return FXS_ENVMAP; - if ("lightposition" == sem) return FXS_LIGHTPOSITION; - if ("transform" == sem) return FXS_TRANSFORM; - if ("user" == sem) return FXS_USER; - if ("constantattenuation" == sem) return FXS_CONSTANTATTENUATION; - if ("linearattenuation" == sem) return FXS_LINEARATTENUATION; - if ("quadraticattenuation" == sem) return FXS_QUADRATICATTENUATION; - if ("falloffangle" == sem) return FXS_FALLOFFANGLE; - if ("falloffexponent" == sem) return FXS_FALLOFFEXPONENT; - if ("boundingradius" == sem) return FXS_BOUNDINGRADIUS; - - return FXS_UNKNOWN; - } - //--------------------------------------------------------------------- - const char * CgFxScriptLoader::getGlobalStateNameTypeToString( const GlobalStateType cgStateName ) - { - switch(cgStateName) - { - case GST_ALPHABLENDENABLE: return "AlphaBlendEnable"; - case GST_ALPHAFUNC: return "AlphaFunc"; - case GST_ALPHAREF: return "AlphaRef"; - case GST_BLENDOP: return "BlendOp"; - case GST_BLENDEQUATION: return "BlendEquation"; - case GST_BLENDFUNC: return "BlendFunc"; - case GST_BLENDFUNCSEPARATE: return "BlendFuncSeparate"; - case GST_BLENDEQUATIONSEPARATE: return "BlendEquationSeparate"; - case GST_BLENDCOLOR: return "BlendColor"; - case GST_CLEARCOLOR: return "ClearColor"; - case GST_CLEARSTENCIL: return "ClearStencil"; - case GST_CLEARDEPTH: return "ClearDepth"; - case GST_CLIPPLANE: return "ClipPlane"; - case GST_CLIPPLANEENABLE: return "ClipPlaneEnable"; - case GST_COLORWRITEENABLE: return "ColorWriteEnable"; - case GST_COLORMASK: return "ColorMask"; - case GST_COLORVERTEX: return "ColorVertex"; - case GST_COLORMATERIAL: return "ColorMaterial"; - case GST_COLORMATRIX: return "ColorMatrix"; - case GST_COLORTRANSFORM: return "ColorTransform"; - case GST_CULLFACE: return "CullFace"; - case GST_CULLMODE: return "CullMode"; - case GST_DEPTHBOUNDS: return "DepthBounds"; - case GST_DEPTHBIAS: return "DepthBias"; - case GST_DESTBLEND: return "DestBlend"; - case GST_DEPTHFUNC: return "DepthFunc"; - case GST_ZFUNC: return "ZFunc"; - case GST_DEPTHMASK: return "DepthMask"; - case GST_ZWRITEENABLE: return "ZWriteEnable"; - case GST_DEPTHRANGE: return "DepthRange"; - case GST_FOGDISTANCEMODE: return "FogDistanceMode"; - case GST_FOGMODE: return "FogMode"; - case GST_FOGTABLEMODE: return "FogTableMode"; - case GST_INDEXEDVERTEXBLENDENABLE: return "IndexedVertexBlendEnable"; - case GST_FOGDENSITY: return "FogDensity"; - case GST_FOGSTART: return "FogStart"; - case GST_FOGEND: return "FogEnd"; - case GST_FOGCOLOR: return "FogColor"; - case GST_FRAGMENTENVPARAMETER: return "FragmentEnvParameter"; - case GST_FRAGMENTLOCALPARAMETER: return "FragmentLocalParameter"; - case GST_FOGCOORDSRC: return "FogCoordSrc"; - case GST_FOGVERTEXMODE: return "FogVertexMode"; - case GST_FRONTFACE: return "FrontFace"; - case GST_LIGHTMODELAMBIENT: return "LightModelAmbient"; - case GST_AMBIENT: return "Ambient"; - case GST_LIGHTINGENABLE: return "LightingEnable"; - case GST_LIGHTENABLE: return "LightEnable"; - case GST_LIGHTAMBIENT: return "LightAmbient"; - case GST_LIGHTCONSTANTATTENUATION: return "LightConstantAttenuation"; - case GST_LIGHTATTENUATION0: return "LightAttenuation0"; - case GST_LIGHTDIFFUSE: return "LightDiffuse"; - case GST_LIGHTLINEARATTENUATION: return "LightLinearAttenuation"; - case GST_LIGHTATTENUATION1: return "LightAttenuation1"; - case GST_LIGHTPOSITION: return "LightPosition"; - case GST_LIGHTQUADRATICATTENUATION: return "LightQuadraticAttenuation"; - case GST_LIGHTATTENUATION2: return "LightAttenuation2"; - case GST_LIGHTSPECULAR: return "LightSpecular"; - case GST_LIGHTSPOTCUTOFF: return "LightSpotCutoff"; - case GST_LIGHTFALLOFF: return "LightFalloff"; - case GST_LIGHTSPOTDIRECTION: return "LightSpotDirection"; - case GST_LIGHTDIRECTION: return "LightDirection"; - case GST_LIGHTSPOTEXPONENT: return "LightSpotExponent"; - case GST_LIGHTPHI: return "LightPhi"; - case GST_LIGHTRANGE: return "LightRange"; - case GST_LIGHTTHETA: return "LightTheta"; - case GST_LIGHTTYPE: return "LightType"; - case GST_LOCALVIEWER: return "LocalViewer"; - case GST_MULTISAMPLEANTIALIAS: return "MultiSampleAntialias"; - case GST_MULTISAMPLEMASK: return "MultiSampleMask"; - case GST_PATCHSEGMENTS: return "PatchSegments"; - case GST_POINTSCALE_A: return "PointScale_A"; - case GST_POINTSCALE_B: return "PointScale_B"; - case GST_POINTSCALE_C: return "PointScale_C"; - case GST_POINTSCALEENABLE: return "PointScaleEnable"; - case GST_RANGEFOGENABLE: return "RangeFogEnable"; - case GST_SPECULARENABLE: return "SpecularEnable"; - case GST_TWEENFACTOR: return "TweenFactor"; - case GST_VERTEXBLEND: return "VertexBlend"; - case GST_AMBIENTMATERIALSOURCE: return "AmbientMaterialSource"; - case GST_DIFFUSEMATERIALSOURCE: return "DiffuseMaterialSource"; - case GST_EMISSIVEMATERIALSOURCE: return "EmissiveMaterialSource"; - case GST_SPECULARMATERIALSOURCE: return "SpecularMaterialSource"; - case GST_CLIPPING: return "Clipping"; - case GST_LIGHTMODELCOLORCONTROL: return "LightModelColorControl"; - case GST_LINESTIPPLE: return "LineStipple"; - case GST_LINEWIDTH: return "LineWidth"; - case GST_LOGICOP: return "LogicOp"; - case GST_MATERIALAMBIENT: return "MaterialAmbient"; - case GST_MATERIALDIFFUSE: return "MaterialDiffuse"; - case GST_MATERIALEMISSION: return "MaterialEmission"; - case GST_MATERIALEMISSIVE: return "MaterialEmissive"; - case GST_MATERIALSHININESS: return "MaterialShininess"; - case GST_MATERIALPOWER: return "MaterialPower"; - case GST_MATERIALSPECULAR: return "MaterialSpecular"; - case GST_MODELVIEWMATRIX: return "ModelViewMatrix"; - case GST_MODELVIEWTRANSFORM: return "ModelViewTransform"; - case GST_VIEWTRANSFORM: return "ViewTransform"; - case GST_WORLDTRANSFORM: return "WorldTransform"; - case GST_POINTDISTANCEATTENUATION: return "PointDistanceAttenuation"; - case GST_POINTFADETHRESHOLDSIZE: return "PointFadeThresholdSize"; - case GST_POINTSIZE: return "PointSize"; - case GST_POINTSIZEMIN: return "PointSizeMin"; - case GST_POINTSIZEMAX: return "PointSizeMax"; - case GST_POINTSPRITECOORDORIGIN: return "PointSpriteCoordOrigin"; - case GST_POINTSPRITECOORDREPLACE: return "PointSpriteCoordReplace"; - case GST_POINTSPRITERMODE: return "PointSpriteRMode"; - case GST_POLYGONMODE: return "PolygonMode"; - case GST_FILLMODE: return "FillMode"; - case GST_LASTPIXEL: return "LastPixel"; - case GST_POLYGONOFFSET: return "PolygonOffset"; - case GST_PROJECTIONMATRIX: return "ProjectionMatrix"; - case GST_PROJECTIONTRANSFORM: return "ProjectionTransform"; - case GST_SCISSOR: return "Scissor"; - case GST_SHADEMODEL: return "ShadeModel"; - case GST_SHADEMODE: return "ShadeMode"; - case GST_SLOPSCALEDEPTHBIAS: return "SlopScaleDepthBias"; - case GST_SRCBLEND: return "SrcBlend"; - case GST_STENCILFUNC: return "StencilFunc"; - case GST_STENCILMASK: return "StencilMask"; - case GST_STENCILPASS: return "StencilPass"; - case GST_STENCILREF: return "StencilRef"; - case GST_STENCILWRITEMASK: return "StencilWriteMask"; - case GST_STENCILZFAIL: return "StencilZFail"; - case GST_TEXTUREFACTOR: return "TextureFactor"; - case GST_STENCILOP: return "StencilOp"; - case GST_STENCILFUNCSEPARATE: return "StencilFuncSeparate"; - case GST_STENCILMASKSEPARATE: return "StencilMaskSeparate"; - case GST_STENCILOPSEPARATE: return "StencilOpSeparate"; - case GST_TEXGENSMODE: return "TexGenSMode"; - case GST_TEXGENSOBJECTPLANE: return "TexGenSObjectPlane"; - case GST_TEXGENSEYEPLANE: return "TexGenSEyePlane"; - case GST_TEXGENTMODE: return "TexGenTMode"; - case GST_TEXGENTOBJECTPLANE: return "TexGenTObjectPlane"; - case GST_TEXGENTEYEPLANE: return "TexGenTEyePlane"; - case GST_TEXGENRMODE: return "TexGenRMode"; - case GST_TEXGENROBJECTPLANE: return "TexGenRObjectPlane"; - case GST_TEXGENREYEPLANE: return "TexGenREyePlane"; - case GST_TEXGENQMODE: return "TexGenQMode"; - case GST_TEXGENQOBJECTPLANE: return "TexGenQObjectPlane"; - case GST_TEXGENQEYEPLANE: return "TexGenQEyePlane"; - case GST_TEXTUREENVCOLOR: return "TextureEnvColor"; - case GST_TEXTUREENVMODE: return "TextureEnvMode"; - case GST_TEXTURE1D: return "Texture1D"; - case GST_TEXTURE2D: return "Texture2D"; - case GST_TEXTURE3D: return "Texture3D"; - case GST_TEXTURERECTANGLE: return "TextureRectangle"; - case GST_TEXTURECUBEMAP: return "TextureCubeMap"; - case GST_TEXTURE1DENABLE: return "Texture1DEnable"; - case GST_TEXTURE2DENABLE: return "Texture2DEnable"; - case GST_TEXTURE3DENABLE: return "Texture3DEnable"; - case GST_TEXTURERECTANGLEENABLE: return "TextureRectangleEnable"; - case GST_TEXTURECUBEMAPENABLE: return "TextureCubeMapEnable"; - case GST_TEXTURETRANSFORM: return "TextureTransform"; - case GST_TEXTUREMATRIX: return "TextureMatrix"; - case GST_VERTEXENVPARAMETER: return "VertexEnvParameter"; - case GST_VERTEXLOCALPARAMETER: return "VertexLocalParameter"; - case GST_ALPHATESTENABLE: return "AlphaTestEnable"; - case GST_AUTONORMALENABLE: return "AutoNormalEnable"; - case GST_BLENDENABLE: return "BlendEnable"; - case GST_COLORLOGICOPENABLE: return "ColorLogicOpEnable"; - case GST_CULLFACEENABLE: return "CullFaceEnable"; - case GST_DEPTHBOUNDSENABLE: return "DepthBoundsEnable"; - case GST_DEPTHCLAMPENABLE: return "DepthClampEnable"; - case GST_DEPTHTESTENABLE: return "DepthTestEnable"; - case GST_ZENABLE: return "ZEnable"; - case GST_DITHERENABLE: return "DitherEnable"; - case GST_FOGENABLE: return "FogEnable"; - case GST_LIGHTMODELLOCALVIEWERENABLE: return "LightModelLocalViewerEnable"; - case GST_LIGHTMODELTWOSIDEENABLE: return "LightModelTwoSideEnable"; - case GST_LINESMOOTHENABLE: return "LineSmoothEnable"; - case GST_LINESTIPPLEENABLE: return "LineStippleEnable"; - case GST_LOGICOPENABLE: return "LogicOpEnable"; - case GST_MULTISAMPLEENABLE: return "MultisampleEnable"; - case GST_NORMALIZEENABLE: return "NormalizeEnable"; - case GST_POINTSMOOTHENABLE: return "PointSmoothEnable"; - case GST_POINTSPRITEENABLE: return "PointSpriteEnable"; - case GST_POLYGONOFFSETFILLENABLE: return "PolygonOffsetFillEnable"; - case GST_POLYGONOFFSETLINEENABLE: return "PolygonOffsetLineEnable"; - case GST_POLYGONOFFSETPOINTENABLE: return "PolygonOffsetPointEnable"; - case GST_POLYGONSMOOTHENABLE: return "PolygonSmoothEnable"; - case GST_POLYGONSTIPPLEENABLE: return "PolygonStippleEnable"; - case GST_RESCALENORMALENABLE: return "RescaleNormalEnable"; - case GST_SAMPLEALPHATOCOVERAGEENABLE: return "SampleAlphaToCoverageEnable"; - case GST_SAMPLEALPHATOONEENABLE: return "SampleAlphaToOneEnable"; - case GST_SAMPLECOVERAGEENABLE: return "SampleCoverageEnable"; - case GST_SCISSORTESTENABLE: return "ScissorTestEnable"; - case GST_STENCILTESTENABLE: return "StencilTestEnable"; - case GST_STENCILENABLE: return "StencilEnable"; - case GST_STENCILTESTTWOSIDEENABLE: return "StencilTestTwoSideEnable"; - case GST_STENCILFAIL: return "StencilFail"; - case GST_TEXGENSENABLE: return "TexGenSEnable"; - case GST_TEXGENTENABLE: return "TexGenTEnable"; - case GST_TEXGENRENABLE: return "TexGenREnable"; - case GST_TEXGENQENABLE: return "TexGenQEnable"; - case GST_WRAP0: return "Wrap0"; - case GST_WRAP1: return "Wrap1"; - case GST_WRAP2: return "Wrap2"; - case GST_WRAP3: return "Wrap3"; - case GST_WRAP4: return "Wrap4"; - case GST_WRAP5: return "Wrap5"; - case GST_WRAP6: return "Wrap6"; - case GST_WRAP7: return "Wrap7"; - case GST_WRAP8: return "Wrap8"; - case GST_WRAP9: return "Wrap9"; - case GST_WRAP10: return "Wrap10"; - case GST_WRAP11: return "Wrap11"; - case GST_WRAP12: return "Wrap12"; - case GST_WRAP13: return "Wrap13"; - case GST_WRAP14: return "Wrap14"; - case GST_WRAP15: return "Wrap15"; - case GST_VERTEXPROGRAMPOINTSIZEENABLE: return "VertexProgramPointSizeEnable"; - case GST_VERTEXPROGRAMTWOSIDEENABLE: return "VertexProgramTwoSideEnable"; - case GST_GEOMETRYPROGRAM: return "GeometryProgram"; - case GST_VERTEXPROGRAM: return "VertexProgram"; - case GST_FRAGMENTPROGRAM: return "FragmentProgram"; - case GST_VERTEXSHADER: return "VertexShader"; - case GST_PIXELSHADER: return "PixelShader"; - case GST_ALPHAOP: return "AlphaOp"; - case GST_ALPHAARG0: return "AlphaArg0"; - case GST_ALPHAARG1: return "AlphaArg1"; - case GST_ALPHAARG2: return "AlphaArg2"; - case GST_COLORARG0: return "ColorArg0"; - case GST_COLORARG1: return "ColorArg1"; - case GST_COLORARG2: return "ColorArg2"; - case GST_COLOROP: return "ColorOp"; - case GST_BUMPENVLSCALE: return "BumpEnvLScale"; - case GST_BUMPENVLOFFSET: return "BumpEnvLOffset"; - case GST_BUMPENVMAT00: return "BumpEnvMat00"; - case GST_BUMPENVMAT01: return "BumpEnvMat01"; - case GST_BUMPENVMAT10: return "BumpEnvMat10"; - case GST_BUMPENVMAT11: return "BumpEnvMat11"; - case GST_RESULTARG: return "ResultArg"; - case GST_TEXCOORDINDEX: return "TexCoordIndex"; - case GST_TEXTURETRANSFORMFLAGS: return "TextureTransformFlags"; - case GST_TWOSIDEDSTENCILMODE: return "TwoSidedStencilMode"; - case GST_SEPARATEALPHABLENDENABLE: return "SeparateAlphaBlendEnable"; - case GST_NORMALIZENORMALS: return "NormalizeNormals"; - case GST_LIGHTING: return "Lighting"; - case GST_PIXELSHADERCONSTANTB: return "PixelShaderConstantB"; - case GST_VERTEXSHADERCONSTANTB: return "VertexShaderConstantB"; - case GST_COLORWRITEENABLE1: return "ColorWriteEnable1"; - case GST_COLORWRITEENABLE2: return "ColorWriteEnable2"; - case GST_COLORWRITEENABLE3: return "ColorWriteEnable3"; - case GST_PIXELSHADERCONSTANT1: return "PixelShaderConstant1"; - case GST_VERTEXSHADERCONSTANT1: return "VertexShaderConstant1"; - case GST_PIXELSHADERCONSTANTF: return "PixelShaderConstantF"; - case GST_VERTEXSHADERCONSTANTF: return "VertexShaderConstantF"; - case GST_PIXELSHADERCONSTANT2: return "PixelShaderConstant2"; - case GST_VERTEXSHADERCONSTANT2: return "VertexShaderConstant2"; - case GST_PIXELSHADERCONSTANT3: return "PixelShaderConstant3"; - case GST_VERTEXSHADERCONSTANT3: return "VertexShaderConstant3"; - case GST_PIXELSHADERCONSTANT: return "PixelShaderConstant"; - case GST_VERTEXSHADERCONSTANT: return "VertexShaderConstant"; - case GST_PIXELSHADERCONSTANT4: return "PixelShaderConstant4"; - case GST_VERTEXSHADERCONSTANT4: return "VertexShaderConstant4"; - case GST_PIXELSHADERCONSTANTI: return "PixelShaderConstantI"; - case GST_VERTEXSHADERCONSTANTI: return "VertexShaderConstantI"; - case GST_SAMPLER: return "Sampler"; - case GST_TEXTURE: return "Texture"; - case GST_ADDRESSU: return "AddressU"; - case GST_ADDRESSV: return "AddressV"; - case GST_ADDRESSW: return "AddressW"; - case GST_BORDERCOLOR: return "BorderColor"; - case GST_MAXANISOTROPY: return "MaxAnisotropy"; - case GST_MAXMIPLEVEL: return "MaxMipLevel"; - case GST_MINFILTER: return "MinFilter"; - case GST_MAGFILTER: return "MagFilter"; - case GST_MIPFILTER: return "MipFilter"; - case GST_MIPMAPLODBIAS: return "MipMapLodBias"; - case GST_BLENDOPALPHA: return "BlendOpAlpha"; - case GST_SRCBLENDALPHA: return "SrcBlendAlpha"; - case GST_DESTBLENDALPHA: return "DestBlendAlpha"; - - case GST_UNKNOWN: - default: - return "unknown"; - } - - } - //--------------------------------------------------------------------- - const char * CgFxScriptLoader::getSamplerStateNameTypeToString( const SamplerStateType cgStateName ) - { - switch(cgStateName) - { - case SST_TEXTURE: return "Texture"; - case SST_ADDRESSU: return "AddressU"; - case SST_ADDRESSV: return "AddressV"; - case SST_ADDRESSW: return "AddressW"; - case SST_WRAPS: return "WrapS"; - case SST_WRAPT: return "WrapT"; - case SST_WRAPR: return "WrapR"; - case SST_MIPFILTER: return "MipFilter"; - case SST_MIPMAPLODBIAS: return "MipMapLodBias"; - case SST_LODBIAS: return "LODBias"; - case SST_SRGBTEXTURE: return "SRGBTexture"; - case SST_MINFILTER: return "MinFilter"; - case SST_MAGFILTER: return "MagFilter"; - case SST_BORDERCOLOR: return "BorderColor"; - case SST_MINMIPLEVEL: return "MinMipLevel"; - case SST_MAXMIPLEVEL: return "MaxMipLevel"; - case SST_MAXANISOTROPY: return "MaxAnisotropy"; - case SST_DEPTHMODE: return "DepthMode"; - case SST_COMPAREMODE: return "CompareMode"; - case SST_COMPAREFUNC: return "CompareFunc"; - case SST_GENERATEMIPMAP: return "GenerateMipmap"; - case SST_UNKNOWN: - default: - return "unknown"; - } - - } - //--------------------------------------------------------------------- - bool CgFxScriptLoader::cgSemanticToOgreAutoConstantType( const char * cgParamSemantic, const char * uiNameValue, GpuProgramParameters::AutoConstantType & ogreAutoConstantType, size_t & extraInfo ) - { - extraInfo = 0; - - FXSemanticID cgFXSemanticID = cgSemanticStringToType(cgParamSemantic); - switch(cgFXSemanticID) - { - case FXS_NONE: - return false; - case FXS_COLOR: - // todo - add to ogre - return false; - case FXS_DIFFUSE: - ogreAutoConstantType = GpuProgramParameters::ACT_SURFACE_DIFFUSE_COLOUR; - return true; - case FXS_SPECULAR: - ogreAutoConstantType = GpuProgramParameters::ACT_SURFACE_SPECULAR_COLOUR; - return true; - case FXS_AMBIENT: - ogreAutoConstantType = GpuProgramParameters::ACT_SURFACE_AMBIENT_COLOUR; - return true; - case FXS_EMISSION: - // todo - add to ogre - return false; - case FXS_EMISSIVE: - ogreAutoConstantType = GpuProgramParameters::ACT_SURFACE_EMISSIVE_COLOUR; - return true; - case FXS_SPECULARPOWER: - // todo - add to ogre - return false; - case FXS_REFRACTION: - // todo - add to ogre - return false; - case FXS_OPACITY: - // todo - add to ogre - return false; - case FXS_ENVIRONMENT: - // todo - add to ogre - return false; - case FXS_ENVIRONMENTNORMAL: - // todo - add to ogre - return false; - case FXS_NORMAL: - // todo - add to ogre - return false; - case FXS_HEIGHT: - // todo - add to ogre - return false; - case FXS_ATTENUATION: - // todo - in ogre ACT_LIGHT_ATTENUATION is float4 and we need float3 here - return false; - case FXS_RENDERCOLORTARGET: - // todo - add to ogre - return false; - case FXS_RENDERDEPTHSTENCILTARGET: - // todo - add to ogre - return false; - case FXS_VIEWPORTPIXELSIZE: - // todo - add to ogre - return false; - case FXS_CAMERAPOSITION: - ogreAutoConstantType = GpuProgramParameters::ACT_CAMERA_POSITION; - return true; - case FXS_TIME: - // todo - possibly this value is has the wrong units... - ogreAutoConstantType = GpuProgramParameters::ACT_TIME; - return true; - case FXS_ELAPSEDTIME: - // todo - possibly this value is has the wrong units... - ogreAutoConstantType = GpuProgramParameters::ACT_FRAME_TIME; - return true; - case FXS_ANIMATIONTIME: - // todo - add to ogre - return false; - case FXS_ANIMATIONTICK: - // todo - add to ogre - return false; - case FXS_MOUSEPOSITION: - // todo - add to ogre - return false; - case FXS_LEFTMOUSEDOWN: - // todo - add to ogre - return false; - case FXS_WORLD: - ogreAutoConstantType = GpuProgramParameters::ACT_WORLD_MATRIX; - return true; - case FXS_VIEW: - ogreAutoConstantType = GpuProgramParameters::ACT_VIEW_MATRIX; - return true; - case FXS_PROJECTION: - ogreAutoConstantType = GpuProgramParameters::ACT_PROJECTION_MATRIX; - return true; - case FXS_WORLDTRANSPOSE: - ogreAutoConstantType = GpuProgramParameters::ACT_TRANSPOSE_WORLD_MATRIX; - return true; - case FXS_VIEWTRANSPOSE: - ogreAutoConstantType = GpuProgramParameters::ACT_TRANSPOSE_VIEW_MATRIX; - return true; - case FXS_PROJECTIONTRANSPOSE: - ogreAutoConstantType = GpuProgramParameters::ACT_TRANSPOSE_PROJECTION_MATRIX; - return true; - case FXS_WORLDVIEW: - ogreAutoConstantType = GpuProgramParameters::ACT_WORLDVIEW_MATRIX; - return true; - case FXS_WORLDVIEWPROJECTION: - ogreAutoConstantType = GpuProgramParameters::ACT_WORLDVIEWPROJ_MATRIX; - return true; - case FXS_WORLDINVERSE: - ogreAutoConstantType = GpuProgramParameters::ACT_INVERSE_WORLD_MATRIX; - return true; - case FXS_VIEWINVERSE: - ogreAutoConstantType = GpuProgramParameters::ACT_INVERSE_VIEW_MATRIX; - return true; - case FXS_PROJECTIONINVERSE: - ogreAutoConstantType = GpuProgramParameters::ACT_INVERSE_PROJECTION_MATRIX; - return true; - case FXS_WORLDINVERSETRANSPOSE: - ogreAutoConstantType = GpuProgramParameters::ACT_INVERSE_TRANSPOSE_WORLD_MATRIX; - return true; - case FXS_VIEWINVERSETRANSPOSE: - ogreAutoConstantType = GpuProgramParameters::ACT_INVERSE_TRANSPOSE_VIEW_MATRIX; - return true; - case FXS_PROJECTIONINVERSETRANSPOSE: - ogreAutoConstantType = GpuProgramParameters::ACT_INVERSE_TRANSPOSE_PROJECTION_MATRIX; - return true; - case FXS_WORLDVIEWINVERSE: - ogreAutoConstantType = GpuProgramParameters::ACT_INVERSE_WORLDVIEW_MATRIX; - return true; - case FXS_WORLDVIEWTRANSPOSE: - ogreAutoConstantType = GpuProgramParameters::ACT_TRANSPOSE_WORLDVIEW_MATRIX; - return true; - case FXS_WORLDVIEWINVERSETRANSPOSE: - ogreAutoConstantType = GpuProgramParameters::ACT_INVERSE_TRANSPOSE_WORLDVIEW_MATRIX; - return true; - case FXS_WORLDVIEWPROJECTIONINVERSE: - ogreAutoConstantType = GpuProgramParameters::ACT_INVERSE_WORLDVIEWPROJ_MATRIX; - return true; - case FXS_WORLDVIEWPROJECTIONTRANSPOSE: - ogreAutoConstantType = GpuProgramParameters::ACT_TRANSPOSE_WORLDVIEWPROJ_MATRIX; - return true; - case FXS_WORLDVIEWPROJECTIONINVERSETRANSPOSE: - ogreAutoConstantType = GpuProgramParameters::ACT_INVERSE_TRANSPOSE_WORLDVIEWPROJ_MATRIX; - return true; - case FXS_VIEWPROJECTION: - ogreAutoConstantType = GpuProgramParameters::ACT_VIEWPROJ_MATRIX; - return true; - case FXS_VIEWPROJECTIONTRANSPOSE: - ogreAutoConstantType = GpuProgramParameters::ACT_TRANSPOSE_VIEWPROJ_MATRIX; - return true; - case FXS_VIEWPROJECTIONINVERSE: - ogreAutoConstantType = GpuProgramParameters::ACT_INVERSE_VIEWPROJ_MATRIX; - return true; - case FXS_VIEWPROJECTIONINVERSETRANSPOSE: - ogreAutoConstantType = GpuProgramParameters::ACT_INVERSE_TRANSPOSE_VIEWPROJ_MATRIX; - return true; - case FXS_FXCOMPOSER_RESETPULSE: - // todo - add to ogre - return false; - case FXS_STANDARDSGLOBAL: - // todo - add to ogre - return false; - case FXS_UNITSSCALE: - // todo - add to ogre - return false; - case FXS_POWER: - // todo - add to ogre - return false; - case FXS_DIFFUSEMAP: - // todo - add to ogre - return false; - case FXS_SPECULARMAP: - // todo - add to ogre - return false; - case FXS_ENVMAP: - // todo - add to ogre - return false; - case FXS_LIGHTPOSITION: - // todo - ACT_LIGHT_POSITION - return false; - case FXS_TRANSFORM: - // todo - add to ogre - return false; - case FXS_USER: - // todo - add to ogre - return false; - case FXS_CONSTANTATTENUATION: - // todo - add to ogre - return false; - case FXS_LINEARATTENUATION: - // todo - add to ogre - return false; - case FXS_QUADRATICATTENUATION: - // todo - add to ogre - return false; - case FXS_FALLOFFANGLE: - // todo - add to ogre - return false; - case FXS_FALLOFFEXPONENT: - // todo - add to ogre - return false; - case FXS_BOUNDINGRADIUS: - // todo - add to ogre - return false; - case FXS_POSITION: - case FXS_DIRECTION: - case FXS_UNKNOWN: - if (uiNameValue) - { - String uiNameValueAsString(uiNameValue); - String theWordLight = "Light"; - if (StringUtil::startsWith(uiNameValueAsString, theWordLight, false)) - { - size_t firstSpacePos = uiNameValueAsString.find(' '); - if (firstSpacePos > 0) - { - String lightNumberAsString = uiNameValueAsString.substr(theWordLight.size(), firstSpacePos - theWordLight.size()); - - size_t lightNumber = StringConverter::parseInt(lightNumberAsString); - extraInfo = lightNumber; - - String colorPart = uiNameValueAsString.substr(firstSpacePos + 1); - if ( colorPart == "Color" ) // float4 - { - ogreAutoConstantType = GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR; - return true; - } - if ( colorPart == "Intensity" ) // float - { - ogreAutoConstantType = GpuProgramParameters::ACT_LIGHT_POWER_SCALE; - return true; - } - if ( colorPart == "Light_position" ) // float3 - { - ogreAutoConstantType = GpuProgramParameters::ACT_LIGHT_POSITION; - return true; - } - if ( colorPart == "Light_direction" ) // float3 - { - ogreAutoConstantType = GpuProgramParameters::ACT_LIGHT_DIRECTION; - return true; - } - if ( colorPart == "Distance Falloff Exponent" ) // float - { - //ogreAutoConstantType = todo: add to GpuProgramParameters; - return false; - } - if ( colorPart == "Distance Falloff Start" ) // float - { - //ogreAutoConstantType = todo: add to GpuProgramParameters; - return false; - } - if ( colorPart == "Light1 Distance Falloff Limit" ) // float - { - //ogreAutoConstantType = todo: add to GpuProgramParameters; - return false; - } - if ( colorPart == "Distance Scale" ) // float - { - //ogreAutoConstantType = todo: add to GpuProgramParameters; - return false; - } - if ( colorPart == "Spread Inner" ) // float - { - //ogreAutoConstantType = todo: add to GpuProgramParameters; - return false; - } - if ( colorPart == "Spread Falloff" ) // float - { - //ogreAutoConstantType = todo: add to GpuProgramParameters; - return false; - } - if ( colorPart == "Light_spread_cos" ) // float - { - //ogreAutoConstantType = todo: add to GpuProgramParameters; - return false; - } - } - - } - else // some other light params - { - if ( uiNameValueAsString == "Diffuse Scalar" ) // float - { - //ogreAutoConstantType = todo: add to GpuProgramParameters; - return false; - } - if ( uiNameValueAsString == "Specular Color" ) // float4 - { - ogreAutoConstantType = GpuProgramParameters::ACT_SURFACE_SPECULAR_COLOUR; - return true; - } - if ( uiNameValueAsString == "Specular Scalar" ) // float - { - //ogreAutoConstantType = todo: add to GpuProgramParameters; - return false; - } - if ( uiNameValueAsString == "Specular Shininess" ) // float - { - //ogreAutoConstantType = todo: add to GpuProgramParameters; - return false; - } - } - } - return false; - default: - return false; - } - - } - - //--------------------------------------------------------------------- - bool CgFxScriptLoader::parseAutoConstantParam( CGparameter cgParameter, GpuProgramParametersSharedPtr ogreProgramParameters, const String& ogreParamName ) - { - const char * cgParamSemantic = cgGetParameterSemantic(cgParameter); - CGannotation parameterAnnotation = cgGetFirstParameterAnnotation(cgParameter); - const char * uiNameValue = 0; - while(parameterAnnotation) - { - const char * annotationName = cgGetAnnotationName(parameterAnnotation); - if( strcmp("UIName", annotationName) == 0 ) - { - uiNameValue = cgGetStringAnnotationValue(parameterAnnotation); - } - parameterAnnotation = cgGetNextAnnotation(parameterAnnotation); - } - - bool isAutoConstant = false; - if (cgParamSemantic) - { - GpuProgramParameters::AutoConstantType ogreAutoConstantType; - size_t extraInfo = 0; - bool autoConstantTypeFound = cgSemanticToOgreAutoConstantType(cgParamSemantic, uiNameValue, ogreAutoConstantType, extraInfo); - if (autoConstantTypeFound) - { - isAutoConstant = true; - } - else - { - // todo - an error? - } - if (isAutoConstant) - { - ogreProgramParameters->setNamedAutoConstant(ogreParamName, ogreAutoConstantType, extraInfo); - } - } - return isAutoConstant; - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::parseFloatCgProgramParameter( CGtype cgParamType, CGparameter cgParameter, GpuProgramParametersSharedPtr ogreProgramParameters, const String& ogreParamName ) - { - float cgParamValue[4*4] = { - 0.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 0.0f - }; - int paramSize = 0; - switch(cgParamType) - { - case CG_FLOAT: - paramSize = 1; - break; - case CG_FLOAT2: - paramSize = 2; - break; - case CG_FLOAT3: - paramSize = 3; - break; - case CG_FLOAT4: - paramSize = 4; - break; - case CG_FLOAT1x1: - paramSize = 1*1; - break; - case CG_FLOAT1x2: - paramSize = 1*2; - break; - case CG_FLOAT1x3: - paramSize = 1*3; - break; - case CG_FLOAT1x4: - paramSize = 1*4; - break; - case CG_FLOAT2x1: - paramSize = 2*1; - break; - case CG_FLOAT2x2: - paramSize = 2*2; - break; - case CG_FLOAT2x3: - paramSize = 2*3; - break; - case CG_FLOAT2x4: - paramSize = 2*4; - break; - case CG_FLOAT3x1: - paramSize = 3*1; - break; - case CG_FLOAT3x2: - paramSize = 3*2; - break; - case CG_FLOAT3x3: - paramSize = 3*3; - break; - case CG_FLOAT3x4: - paramSize = 3*4; - break; - case CG_FLOAT4x1: - paramSize = 4*1; - break; - case CG_FLOAT4x2: - paramSize = 4*2; - break; - case CG_FLOAT4x3: - paramSize = 4*3; - break; - case CG_FLOAT4x4: - paramSize = 4*4; - break; - default: - // todo error - break; - } - cgGetParameterValuefc(cgParameter, paramSize, cgParamValue); - ogreProgramParameters->setNamedConstant(ogreParamName, cgParamValue, 1, paramSize); - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::parseIntCgProgramParameter( CGtype cgParamType, CGparameter cgParameter, GpuProgramParametersSharedPtr ogreProgramParameters, const String& ogreParamName ) - { - int cgParamValue[4*4] = { - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0 - }; - int paramSize = 0; - switch(cgParamType) - { - case CG_INT: - paramSize = 1; - break; - case CG_INT2: - paramSize = 2; - break; - case CG_INT3: - paramSize = 3; - break; - case CG_INT4: - paramSize = 4; - break; - case CG_INT1x1: - paramSize = 1*1; - break; - case CG_INT1x2: - paramSize = 1*2; - break; - case CG_INT1x3: - paramSize = 1*3; - break; - case CG_INT1x4: - paramSize = 1*4; - break; - case CG_INT2x1: - paramSize = 2*1; - break; - case CG_INT2x2: - paramSize = 2*2; - break; - case CG_INT2x3: - paramSize = 2*3; - break; - case CG_INT2x4: - paramSize = 2*4; - break; - case CG_INT3x1: - paramSize = 3*1; - break; - case CG_INT3x2: - paramSize = 3*2; - break; - case CG_INT3x3: - paramSize = 3*3; - break; - case CG_INT3x4: - paramSize = 3*4; - break; - case CG_INT4x1: - paramSize = 4*1; - break; - case CG_INT4x2: - paramSize = 4*2; - break; - case CG_INT4x3: - paramSize = 4*3; - break; - case CG_INT4x4: - paramSize = 4*4; - break; - default: - // todo error - break; - } - cgGetParameterValueic(cgParameter, paramSize, cgParamValue); - ogreProgramParameters->setNamedConstant(ogreParamName, cgParamValue, 1, paramSize); - } - //--------------------------------------------------------------------- - Ogre::CgFxScriptLoader::CgSamplerStateListener * CgFxScriptLoader::createCgSamplerStateListener( const SamplerStateType type ) - { - switch(type) - { - case SST_ADDRESSU: - case SST_ADDRESSV: - case SST_ADDRESSW: - return OGRE_NEW CgTextureAddressSamplerStateListener(type); - case SST_WRAPS: - case SST_WRAPT: - case SST_WRAPR: - return OGRE_NEW CgWrapSamplerStateListener(type); - case SST_BORDERCOLOR: - return OGRE_NEW CgFloat4SamplerStateListener(type); - case SST_COMPAREMODE: - return OGRE_NEW CgCompareModeSamplerStateListener(); - case SST_COMPAREFUNC: - return OGRE_NEW CgCompareFuncSamplerStateListener(); - case SST_DEPTHMODE: - return OGRE_NEW CgDepthModeSamplerStateListener(); - case SST_GENERATEMIPMAP: - return OGRE_NEW CgBoolSamplerStateListener(type); - case SST_MIPMAPLODBIAS: - case SST_LODBIAS: - case SST_MAXMIPLEVEL: - case SST_MAXANISOTROPY: - case SST_MINMIPLEVEL: - case SST_SRGBTEXTURE: - return OGRE_NEW CgFloatSamplerStateListener(type); - case SST_MINFILTER: - return OGRE_NEW CgMinFilterSamplerStateListener(); - case SST_MAGFILTER: - return OGRE_NEW CgMagFilterSamplerStateListener(); - case SST_TEXTURE: - return OGRE_NEW CgTextureSamplerStateListener(type); - case SST_MIPFILTER: - return OGRE_NEW CgMipFilterSamplerStateListener(); - default: - // TODO - this is an error.... - return OGRE_NEW CgSamplerStateListener(type, CG_STRING); - } - } - //--------------------------------------------------------------------- - Ogre::CgFxScriptLoader::CgGlobalStateListener * CgFxScriptLoader::createCgGlobalStateListener( const GlobalStateType type ) - { - switch(type) - { - case GST_ALPHABLENDENABLE: - case GST_COLORVERTEX: - case GST_DEPTHMASK: - case GST_ZWRITEENABLE: - case GST_INDEXEDVERTEXBLENDENABLE: - case GST_LIGHTINGENABLE: - case GST_LIGHTING: - case GST_LIGHTENABLE: - case GST_LOCALVIEWER: - case GST_MULTISAMPLEANTIALIAS: - case GST_POINTSCALEENABLE: - case GST_RANGEFOGENABLE: - case GST_SPECULARENABLE: - case GST_CLIPPING: - case GST_POINTSPRITECOORDREPLACE: - case GST_LASTPIXEL: - case GST_TEXTURE1DENABLE: - case GST_TEXTURE2DENABLE: - case GST_TEXTURE3DENABLE: - case GST_TEXTURERECTANGLEENABLE: - case GST_TEXTURECUBEMAPENABLE: - case GST_ALPHATESTENABLE: - case GST_AUTONORMALENABLE: - case GST_BLENDENABLE: - case GST_COLORLOGICOPENABLE: - case GST_CULLFACEENABLE: - case GST_DEPTHBOUNDSENABLE: - case GST_DEPTHCLAMPENABLE: - case GST_DEPTHTESTENABLE: - case GST_ZENABLE: - case GST_DITHERENABLE: - case GST_FOGENABLE: - case GST_LIGHTMODELLOCALVIEWERENABLE: - case GST_LIGHTMODELTWOSIDEENABLE: - case GST_LINESMOOTHENABLE: - case GST_LINESTIPPLEENABLE: - case GST_LOGICOPENABLE: - case GST_MULTISAMPLEENABLE: - case GST_NORMALIZEENABLE: - case GST_NORMALIZENORMALS: - case GST_POINTSMOOTHENABLE: - case GST_POINTSPRITEENABLE: - case GST_POLYGONOFFSETFILLENABLE: - case GST_POLYGONOFFSETLINEENABLE: - case GST_POLYGONOFFSETPOINTENABLE: - case GST_POLYGONSMOOTHENABLE: - case GST_POLYGONSTIPPLEENABLE: - case GST_RESCALENORMALENABLE: - case GST_SAMPLEALPHATOCOVERAGEENABLE: - case GST_SAMPLEALPHATOONEENABLE: - case GST_SAMPLECOVERAGEENABLE: - case GST_SCISSORTESTENABLE: - case GST_STENCILTESTENABLE: - case GST_STENCILENABLE: - case GST_STENCILTESTTWOSIDEENABLE: - case GST_TEXGENSENABLE: - case GST_TEXGENTENABLE: - case GST_TEXGENRENABLE: - case GST_TEXGENQENABLE: - case GST_TWOSIDEDSTENCILMODE: - case GST_SEPARATEALPHABLENDENABLE: - case GST_VERTEXPROGRAMPOINTSIZEENABLE: - case GST_VERTEXPROGRAMTWOSIDEENABLE: - return OGRE_NEW CgBoolGlobalStateListener(type); - case GST_COLORWRITEENABLE: - case GST_COLORMASK: - case GST_PIXELSHADERCONSTANTB: - case GST_VERTEXSHADERCONSTANTB: - case GST_COLORWRITEENABLE1: - case GST_COLORWRITEENABLE2: - case GST_COLORWRITEENABLE3: - return OGRE_NEW CgBool4GlobalStateListener(type); - case GST_ALPHAREF: - case GST_CLEARDEPTH: - case GST_DEPTHBIAS: - case GST_FOGDENSITY: - case GST_FOGSTART: - case GST_FOGEND: - case GST_LIGHTCONSTANTATTENUATION: - case GST_LIGHTATTENUATION0: - case GST_LIGHTLINEARATTENUATION: - case GST_LIGHTATTENUATION1: - case GST_LIGHTQUADRATICATTENUATION: - case GST_LIGHTATTENUATION2: - case GST_LIGHTSPOTCUTOFF: - case GST_LIGHTFALLOFF: - case GST_LIGHTPHI: - case GST_LIGHTRANGE: - case GST_LIGHTTHETA: - case GST_PATCHSEGMENTS: - case GST_POINTSCALE_A: - case GST_POINTSCALE_B: - case GST_POINTSCALE_C: - case GST_TWEENFACTOR: - case GST_LINEWIDTH: - case GST_MATERIALSHININESS: - case GST_MATERIALPOWER: - case GST_POINTFADETHRESHOLDSIZE: - case GST_POINTSIZE: - case GST_POINTSIZEMIN: - case GST_POINTSIZEMAX: - case GST_SLOPSCALEDEPTHBIAS: - case GST_BUMPENVLSCALE: - case GST_BUMPENVLOFFSET: - case GST_BUMPENVMAT00: - case GST_BUMPENVMAT01: - case GST_BUMPENVMAT10: - case GST_BUMPENVMAT11: - case GST_LIGHTSPOTEXPONENT: - return OGRE_NEW CgFloatGlobalStateListener(type); - case GST_DEPTHBOUNDS: - case GST_DEPTHRANGE: - case GST_POLYGONOFFSET: - case GST_MAXANISOTROPY: - case GST_MAXMIPLEVEL: - return OGRE_NEW CgFloat2GlobalStateListener(type); - case GST_POINTDISTANCEATTENUATION: - return OGRE_NEW CgFloat3GlobalStateListener(type); - case GST_BLENDCOLOR: - case GST_CLEARCOLOR: - case GST_CLIPPLANE: - case GST_FOGCOLOR: - case GST_FRAGMENTENVPARAMETER: - case GST_FRAGMENTLOCALPARAMETER: - case GST_LIGHTMODELAMBIENT: - case GST_AMBIENT: - case GST_LIGHTAMBIENT: - case GST_LIGHTDIFFUSE: - case GST_LIGHTPOSITION: - case GST_LIGHTSPECULAR: - case GST_LIGHTSPOTDIRECTION: - case GST_LIGHTDIRECTION: - case GST_MATERIALAMBIENT: - case GST_MATERIALDIFFUSE: - case GST_MATERIALEMISSION: - case GST_MATERIALEMISSIVE: - case GST_MATERIALSPECULAR: - case GST_TEXGENSOBJECTPLANE: - case GST_TEXGENSEYEPLANE: - case GST_TEXGENTOBJECTPLANE: - case GST_TEXGENTEYEPLANE: - case GST_TEXGENROBJECTPLANE: - case GST_TEXGENREYEPLANE: - case GST_TEXGENQOBJECTPLANE: - case GST_TEXGENQEYEPLANE: - case GST_TEXTUREENVCOLOR: - case GST_VERTEXENVPARAMETER: - case GST_VERTEXLOCALPARAMETER: - case GST_PIXELSHADERCONSTANT1: - case GST_VERTEXSHADERCONSTANT1: - case GST_PIXELSHADERCONSTANTF: - case GST_VERTEXSHADERCONSTANTF: - case GST_BORDERCOLOR: - return OGRE_NEW CgFloat4GlobalStateListener(type); - case GST_PIXELSHADERCONSTANT2: - case GST_VERTEXSHADERCONSTANT2: - return OGRE_NEW CgFloat4x2GlobalStateListener(type); - case GST_PIXELSHADERCONSTANT3: - case GST_VERTEXSHADERCONSTANT3: - return OGRE_NEW CgFloat4x3GlobalStateListener(type); - case GST_COLORMATRIX: - case GST_COLORTRANSFORM: - case GST_MODELVIEWMATRIX: - case GST_MODELVIEWTRANSFORM: - case GST_VIEWTRANSFORM: - case GST_WORLDTRANSFORM: - case GST_PROJECTIONMATRIX: - case GST_PROJECTIONTRANSFORM: - case GST_TEXTURETRANSFORM: - case GST_TEXTUREMATRIX: - case GST_PIXELSHADERCONSTANT: - case GST_VERTEXSHADERCONSTANT: - case GST_PIXELSHADERCONSTANT4: - case GST_VERTEXSHADERCONSTANT4: - return OGRE_NEW CgFloat4x4GlobalStateListener(type); - case GST_LINESTIPPLE: - case GST_FILLMODE: - return OGRE_NEW CgInt2GlobalStateListener(type); - case GST_SCISSOR: - case GST_PIXELSHADERCONSTANTI: - case GST_VERTEXSHADERCONSTANTI: - return OGRE_NEW CgInt4GlobalStateListener(type); - case GST_SAMPLER: - case GST_TEXTURE1D: - return OGRE_NEW CgSamplerGlobalStateListener(type); - case GST_TEXTURE2D: - return OGRE_NEW CgSampler2GlobalStateListener(type); - case GST_TEXTURE3D: - return OGRE_NEW CgSampler3GlobalStateListener(type); - case GST_TEXTURECUBEMAP: - return OGRE_NEW CgSamplerCubeGlobalStateListener(type); - case GST_TEXTURERECTANGLE: - return OGRE_NEW CgSamplerRectGlobalStateListener(type); - case GST_TEXTURE: - return OGRE_NEW CgTextureGlobalStateListener(type); - case GST_GEOMETRYPROGRAM: - case GST_VERTEXPROGRAM: - case GST_FRAGMENTPROGRAM: - case GST_VERTEXSHADER: - case GST_PIXELSHADER: - return OGRE_NEW CgProgramGlobalStateListener(type); - case GST_BLENDOP: - case GST_CLEARSTENCIL: - case GST_CLIPPLANEENABLE: - case GST_CULLMODE: - case GST_ZFUNC: - case GST_FOGTABLEMODE: - case GST_FOGVERTEXMODE: - case GST_LIGHTTYPE: - case GST_MULTISAMPLEMASK: - case GST_AMBIENTMATERIALSOURCE: - case GST_DIFFUSEMATERIALSOURCE: - case GST_EMISSIVEMATERIALSOURCE: - case GST_SPECULARMATERIALSOURCE: - case GST_VERTEXBLEND: - case GST_DESTBLEND: - case GST_SRCBLEND: - case GST_STENCILMASK: - case GST_STENCILPASS: - case GST_STENCILREF: - case GST_STENCILWRITEMASK: - case GST_STENCILZFAIL: - case GST_TEXTUREFACTOR: - case GST_STENCILFAIL: - case GST_WRAP0: - case GST_WRAP1: - case GST_WRAP2: - case GST_WRAP3: - case GST_WRAP4: - case GST_WRAP5: - case GST_WRAP6: - case GST_WRAP7: - case GST_WRAP8: - case GST_WRAP9: - case GST_WRAP10: - case GST_WRAP11: - case GST_WRAP12: - case GST_WRAP13: - case GST_WRAP14: - case GST_WRAP15: - case GST_ADDRESSU: - case GST_ADDRESSV: - case GST_ADDRESSW: - case GST_MIPMAPLODBIAS: - case GST_BLENDOPALPHA: - case GST_SRCBLENDALPHA: - case GST_DESTBLENDALPHA: - case GST_ALPHAOP: - case GST_COLOROP: - case GST_ALPHAARG0: - case GST_ALPHAARG1: - case GST_ALPHAARG2: - case GST_COLORARG0: - case GST_COLORARG1: - case GST_COLORARG2: - case GST_RESULTARG: - case GST_TEXCOORDINDEX: - case GST_TEXTURETRANSFORMFLAGS: - case GST_MIPFILTER: // todo - return OGRE_NEW CgIntGlobalStateListener(type); - case GST_BLENDEQUATION: - return OGRE_NEW CgBlendEquationGlobalStateListener(); - case GST_DEPTHFUNC: - return OGRE_NEW CgDepthFuncGlobalStateListener(); - case GST_FOGDISTANCEMODE: - return OGRE_NEW CgFogDistanceModeGlobalStateListener(); - case GST_FOGMODE: - return OGRE_NEW CgFogModeGlobalStateListener(); - case GST_LIGHTMODELCOLORCONTROL: - return OGRE_NEW CgLightModelColorControlGlobalStateListener(); - case GST_LOGICOP: - return OGRE_NEW CgLogicOpGlobalStateListener(); - case GST_POINTSPRITECOORDORIGIN: - return OGRE_NEW CgPointSpriteCoordOriginGlobalStateListener(); - case GST_POINTSPRITERMODE: - return OGRE_NEW CgPointSpriteRModeGlobalStateListener(); - case GST_SHADEMODEL: - case GST_SHADEMODE: - return OGRE_NEW CgShadeModelGlobalStateListener(); - case GST_TEXGENSMODE: - case GST_TEXGENTMODE: - case GST_TEXGENRMODE: - case GST_TEXGENQMODE: - return OGRE_NEW CgTexGenModeGlobalStateListener(type); - case GST_TEXTUREENVMODE: - return OGRE_NEW CgTextureEnvModeGlobalStateListener(); - case GST_MINFILTER: - return OGRE_NEW CgMinFilterGlobalStateListener(); - case GST_MAGFILTER: - return OGRE_NEW CgMagFilterGlobalStateListener(); - case GST_FRONTFACE: - return OGRE_NEW CgFrontFaceGlobalStateListener(); - case GST_CULLFACE: - return OGRE_NEW CgCullFaceGlobalStateListener(); - case GST_FOGCOORDSRC: - return OGRE_NEW CgFogCoordSrcGlobalStateListener(); - case GST_ALPHAFUNC: - return OGRE_NEW CgAlphaFuncGlobalStateListener(); - case GST_BLENDFUNC: - return OGRE_NEW CgBlendFuncGlobalStateListener(); - case GST_BLENDFUNCSEPARATE: - return OGRE_NEW CgBlendFuncSeparateGlobalStateListener(); - case GST_BLENDEQUATIONSEPARATE: - return OGRE_NEW CgBlendEquationSeparateGlobalStateListener(); - case GST_COLORMATERIAL: - return OGRE_NEW CgColorMaterialGlobalStateListener(); - case GST_POLYGONMODE: - return OGRE_NEW CgPolygonModeGlobalStateListener(); - case GST_STENCILFUNC: - return OGRE_NEW CgStencilFuncGlobalStateListener(); - case GST_STENCILOP: - return OGRE_NEW CgStencilOpGlobalStateListener(); - case GST_STENCILFUNCSEPARATE: - return OGRE_NEW CgStencilFuncSeparateGlobalStateListener(); - case GST_STENCILMASKSEPARATE: - return OGRE_NEW CgStencilMaskSeparateGlobalStateListener(); - case GST_STENCILOPSEPARATE: - return OGRE_NEW CgStencilOpSeparateGlobalStateListener(); - default: - // TODO - this is an error.... - return OGRE_NEW CgGlobalStateListener(type, CG_STRING); - } - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::parsePassStateAssignments( CGpass cgPass, Pass * ogrePass ) - { - CGstateassignment cgStateAssignment = cgGetFirstStateAssignment(cgPass); - while (cgStateAssignment) - { - CGstate cgState = cgGetStateAssignmentState(cgStateAssignment); - CgGlobalStateToListenerMap::iterator stateIter = mCgGlobalStateToListenerMap.find(cgState); - if (stateIter != mCgGlobalStateToListenerMap.end()) - { - stateIter->second->updatePass(ogrePass, cgStateAssignment); - } - - cgStateAssignment = cgGetNextStateAssignment(cgStateAssignment); - } - } - //--------------------------------------------------------------------- - void CgFxScriptLoader::parseTextureUnitState( CGstateassignment cgStateAssignment, TextureUnitState * ogreTextureUnitState ) - { - CGstate cgState = cgGetSamplerStateAssignmentState(cgStateAssignment); - - checkForCgError("CgFxScriptLoader::parseTextureUnitState", - "Unable to Get State Assignment State: ", mCgContext); - - CgSamplerStateToListenerMap::iterator samplerStateIter = mCgSamplerStateToListenerMap.find(cgState); - if (samplerStateIter != mCgSamplerStateToListenerMap.end()) - { - samplerStateIter->second->upateTextureUnitState(ogreTextureUnitState, cgStateAssignment); - } - } - - void CgFxScriptLoader::parseSamplerParameters(CGpass cgPass, Pass * ogrePass) - { - CGeffect cgEffect = cgGetTechniqueEffect(cgGetPassTechnique(cgPass)); - CGparameter cgParameter = cgGetFirstEffectParameter(cgEffect); - while (cgParameter) - { - if (cgGetParameterClass(cgParameter) == CG_PARAMETERCLASS_SAMPLER) - { - CGstateassignment cgStateAssignment = cgGetFirstSamplerStateAssignment(cgParameter); - - if (cgStateAssignment) - { - TextureUnitState * ogreTextureUnitState = ogrePass->createTextureUnitState(); - - while(cgStateAssignment) - { - if(cgIsStateAssignment(cgStateAssignment)) - { - parseTextureUnitState(cgStateAssignment, ogreTextureUnitState); - } - - cgStateAssignment = cgGetNextStateAssignment(cgStateAssignment); - } - - } - } - - cgParameter = cgGetNextParameter(cgParameter); - } - - } -} diff --git a/PlugIns/CgProgramManager/src/OgreCgPlugin.cpp b/PlugIns/CgProgramManager/src/OgreCgPlugin.cpp deleted file mode 100644 index ab58065f9d9..00000000000 --- a/PlugIns/CgProgramManager/src/OgreCgPlugin.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreCgPlugin.h" -#include "OgreRoot.h" -#include "OgreHighLevelGpuProgram.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreCgFxScriptLoader.h" -#include "OgreCgProgramFactory.h" -#include "OgreLogManager.h" - -namespace Ogre -{ - const String sPluginName = "Cg Program Manager"; - //--------------------------------------------------------------------- - CgPlugin::CgPlugin() - :mCgProgramFactory(0) - { - - } - //--------------------------------------------------------------------- - const String& CgPlugin::getName() const - { - return sPluginName; - } - //--------------------------------------------------------------------- - void CgPlugin::install() - { - } - //--------------------------------------------------------------------- - void CgPlugin::initialise() - { - // Check for gles2 by the glsles factory (this plugin is not supported on embedded systems for now) - if (HighLevelGpuProgramManager::getSingleton().isLanguageSupported("glsles") == false) - - { - // Create new factory - mCgProgramFactory = OGRE_NEW CgProgramFactory(); - - // Register - HighLevelGpuProgramManager::getSingleton().addFactory(mCgProgramFactory); - - OGRE_NEW CgFxScriptLoader(); - } - } - //--------------------------------------------------------------------- - void CgPlugin::shutdown() - { - // nothing to do - } - //--------------------------------------------------------------------- - void CgPlugin::uninstall() - { - if (mCgProgramFactory) - { - OGRE_DELETE CgFxScriptLoader::getSingletonPtr(); - - // Remove from manager safely - if (HighLevelGpuProgramManager::getSingletonPtr()) - HighLevelGpuProgramManager::getSingleton().removeFactory(mCgProgramFactory); - OGRE_DELETE mCgProgramFactory; - mCgProgramFactory = 0; - } - } -} diff --git a/PlugIns/CgProgramManager/src/OgreCgProgram.cpp b/PlugIns/CgProgramManager/src/OgreCgProgram.cpp deleted file mode 100644 index 6da83df40ac..00000000000 --- a/PlugIns/CgProgramManager/src/OgreCgProgram.cpp +++ /dev/null @@ -1,1264 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreCgProgram.h" -#include "OgreGpuProgramManager.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreStringConverter.h" -#include "OgreLogManager.h" -#include - -namespace Ogre { - //----------------------------------------------------------------------- - CgProgram::CmdProfiles CgProgram::msCmdProfiles; - CgProgram::CmdArgs CgProgram::msCmdArgs; - //----------------------------------------------------------------------- - void CgProgram::selectProfile(void) - { - static const String specialCgProfiles[] = {"hlslv", "hlslf", "glslv", "glslf", "glslg"}; - static const size_t specialCgProfilesCount = sizeof(specialCgProfiles)/sizeof(String); - static const String* specialCgProfilesEnd = specialCgProfiles + specialCgProfilesCount; - - mSelectedProfile.clear(); - mSelectedCgProfile = CG_PROFILE_UNKNOWN; - - StringVector::iterator i, iend; - iend = mProfiles.end(); - GpuProgramManager& gpuMgr = GpuProgramManager::getSingleton(); - bool useDelegate = false; - - for (i = mProfiles.begin(); i != iend; ++i) - { - bool syntaxSupported = gpuMgr.isSyntaxSupported(*i); - if (!syntaxSupported && find(specialCgProfiles, specialCgProfilesEnd, *i) != specialCgProfilesEnd) - { - // Cg has some "special" profiles which don't have direct equivalents - // in the GpuProgramManager's supported syntaxes. - // For now, the following works - if (gpuMgr.isSyntaxSupported(i->substr(0, 4))) - { - syntaxSupported = true; - useDelegate = true; - } - - } - - if (syntaxSupported) - { - mSelectedProfile = *i; - String selectedProfileForFind = mSelectedProfile; - if(StringUtil::startsWith(mSelectedProfile,"vs_4_0_", true)) - { - selectedProfileForFind = "vs_4_0"; - } - if(StringUtil::startsWith(mSelectedProfile,"ps_4_0_", true)) - { - selectedProfileForFind = "ps_4_0"; - } - mSelectedCgProfile = cgGetProfile(selectedProfileForFind.c_str()); - // Check for errors - checkForCgError("CgProgram::selectProfile", - "Unable to find CG profile enum for program " + mName + ": ", mCgContext); - - // do we need a delegate? - if (useDelegate && !mDelegate) - { - mDelegate = - HighLevelGpuProgramManager::getSingleton().createProgram( - mName+"/Delegate", mGroup, getHighLevelLanguage(), mType); - mDelegate->setParameter("target", getHighLevelTarget()); - mDelegate->setParameter("entry_point", "main"); - // HLSL/GLSL output uses row major matrices, so need to tell Ogre that - mDelegate->setParameter("column_major_matrices", "false"); - // HLSL output requires backwards compatibility to be enabled - mDelegate->setParameter("backwards_compatibility", "true"); - } - else if (!useDelegate && mDelegate) - { - ResourcePtr rs (mDelegate); - HighLevelGpuProgramManager::getSingleton().remove(rs); - mDelegate.reset(); - } - - break; - } - } - } - //----------------------------------------------------------------------- - void CgProgram::buildArgs(void) - { - StringVector args; - if (!mPreprocessorDefines.empty()) - args = StringUtil::split(mPreprocessorDefines); - - StringVector::const_iterator i; - if (mSelectedCgProfile == CG_PROFILE_VS_1_1) - { - // Need the 'dcls' argument whenever we use this profile - // otherwise compilation of the assembler will fail - bool dclsFound = false; - for (i = args.begin(); i != args.end(); ++i) - { - if (*i == "dcls") - { - dclsFound = true; - break; - } - } - if (!dclsFound) - { - args.push_back("-profileopts"); - args.push_back("dcls"); - } - } - args.push_back("-DOGRE_CG"); - if (getType() == GPT_VERTEX_PROGRAM) - args.push_back("-DOGRE_VERTEX_SHADER"); - - // Now split args into that god-awful char** that Cg insists on - freeCgArgs(); - mCgArguments = OGRE_ALLOC_T(char*, args.size() + 1, MEMCATEGORY_RESOURCE); - int index = 0; - for (i = args.begin(); i != args.end(); ++i, ++index) - { - mCgArguments[index] = OGRE_ALLOC_T(char, i->length() + 1, MEMCATEGORY_RESOURCE); - strcpy(mCgArguments[index], i->c_str()); - } - // Null terminate list - mCgArguments[index] = 0; - - - } - //----------------------------------------------------------------------- - void CgProgram::freeCgArgs(void) - { - if (mCgArguments) - { - size_t index = 0; - char* current = mCgArguments[index]; - while (current) - { - OGRE_FREE(current, MEMCATEGORY_RESOURCE); - mCgArguments[index] = 0; - current = mCgArguments[++index]; - } - OGRE_FREE(mCgArguments, MEMCATEGORY_RESOURCE); - mCgArguments = 0; - } - } - //----------------------------------------------------------------------- - void CgProgram::loadFromSource(void) - { - selectProfile(); - - // need to differentiate between target profiles - // also HLSL and Cg shaders sources are identical - uint32 hash = HashCombine(0, mSelectedCgProfile); - hash = _getHash(hash); - - if ( GpuProgramManager::getSingleton().isMicrocodeAvailableInCache(hash) ) - { - getMicrocodeFromCache(hash); - } - else - { - compileMicrocode(); - - if ( GpuProgramManager::getSingleton().getSaveMicrocodesToCache()) - { - addMicrocodeToCache(hash); - } - } - - if (mDelegate) - { - mDelegate->setSource(mProgramString); - - if (mSelectedCgProfile == CG_PROFILE_GLSLG) - { - // need to set input and output operations - if (mInputOp == CG_POINT) - { - mDelegate->setParameter("input_operation_type", "point_list"); - } - else if (mInputOp == CG_LINE) - { - mDelegate->setParameter("input_operation_type", "line_strip"); - } - else if (mInputOp == CG_LINE_ADJ) - { - mDelegate->setParameter("input_operation_type", "line_strip_adj"); - } - else if (mInputOp == CG_TRIANGLE) - { - mDelegate->setParameter("input_operation_type", "triangle_strip"); - } - else if (mInputOp == CG_TRIANGLE_ADJ) - { - mDelegate->setParameter("input_operation_type", "triangle_strip_adj"); - } - - if (mOutputOp == CG_POINT_OUT) - mDelegate->setParameter("output_operation_type", "point_list"); - else if (mOutputOp == CG_LINE_OUT) - mDelegate->setParameter("output_operation_type", "line_strip"); - else if (mOutputOp == CG_TRIANGLE_OUT) - mDelegate->setParameter("output_operation_type", "triangle_strip"); - } - if (getHighLevelLanguage() == "glsl") - { - // for GLSL, also ensure we explicitly bind samplers to their register - // otherwise, GLSL will assign them in the order first used, which is - // not what we want. - GpuProgramParametersSharedPtr params = mDelegate->getDefaultParameters(); - for (std::map::iterator i = mSamplerRegisterMap.begin(); i != mSamplerRegisterMap.end(); ++i) - params->setNamedConstant(i->first, i->second); - } - mDelegate->load(); - } - } - //----------------------------------------------------------------------- - void CgProgram::getMicrocodeFromCache(uint32 id) - { - GpuProgramManager::Microcode cacheMicrocode = - GpuProgramManager::getSingleton().getMicrocodeFromCache(id); - - cacheMicrocode->seek(0); - - // get size of string - size_t programStringSize = 0; - cacheMicrocode->read(&programStringSize, sizeof(size_t)); - - // get microcode - mProgramString.resize(programStringSize); - cacheMicrocode->read(&mProgramString[0], programStringSize); - - // get size of param map - size_t parametersMapSize = 0; - cacheMicrocode->read(¶metersMapSize, sizeof(size_t)); - - // get params - for(size_t i = 0 ; i < parametersMapSize ; i++) - { - String paramName; - size_t stringSize = 0; - GpuConstantDefinition def; - - // get string size - cacheMicrocode->read(&stringSize, sizeof(size_t)); - - // get string - paramName.resize(stringSize); - cacheMicrocode->read(¶mName[0], stringSize); - - // get def - cacheMicrocode->read( &def, sizeof(GpuConstantDefinition)); - - mParametersMap.emplace(paramName, def); - } - - if (mDelegate) - { - // get sampler register mapping - size_t samplerMapSize = 0; - cacheMicrocode->read(&samplerMapSize, sizeof(size_t)); - for (size_t i = 0; i < samplerMapSize; ++i) - { - String paramName; - size_t stringSize = 0; - int reg = -1; - - cacheMicrocode->read(&stringSize, sizeof(size_t)); - paramName.resize(stringSize); - cacheMicrocode->read(¶mName[0], stringSize); - cacheMicrocode->read(®, sizeof(int)); - } - - // get input/output operations type - cacheMicrocode->read(&mInputOp, sizeof(CGenum)); - cacheMicrocode->read(&mOutputOp, sizeof(CGenum)); - } - - } - //----------------------------------------------------------------------- - void CgProgram::compileMicrocode(void) - { - // Create Cg Program - - /// Program handle - CGprogram cgProgram; - - if (mSelectedCgProfile == CG_PROFILE_UNKNOWN) - { - LogManager::getSingleton().logMessage( - "Attempted to load Cg program '" + mName + "', but no supported " - "profile was found. "); - return; - } - buildArgs(); - // deal with includes - String sourceToUse = _resolveIncludes(mSource, this, mFilename, true); - - cgProgram = cgCreateProgram(mCgContext, CG_SOURCE, sourceToUse.c_str(), - mSelectedCgProfile, mEntryPoint.c_str(), const_cast(mCgArguments)); - - // Test - //LogManager::getSingleton().logMessage(cgGetProgramString(mCgProgram, CG_COMPILED_PROGRAM)); - - // Check for errors - checkForCgError("CgProgram::compileMicrocode", - "Unable to compile Cg program " + mName + ": ", mCgContext); - - CGerror error = cgGetError(); - if (error == CG_NO_ERROR) - { - // get program string (result of cg compile) - mProgramString = cgGetProgramString(cgProgram, CG_COMPILED_PROGRAM); - checkForCgError("CgProgram::compileMicrocode", - "Unable to retrieve program code for Cg program " + mName + ": ", mCgContext); - - // get params - mParametersMap.clear(); - mParametersMapSizeAsBuffer = 0; - mSamplerRegisterMap.clear(); - recurseParams(cgGetFirstParameter(cgProgram, CG_PROGRAM)); - recurseParams(cgGetFirstParameter(cgProgram, CG_GLOBAL)); - - if (mDelegate) - { - // Delegating to HLSL or GLSL, need to clean up Cg's output - fixHighLevelOutput(mProgramString); - if (mSelectedCgProfile == CG_PROFILE_GLSLG) - { - // need to determine input and output operations - mInputOp = cgGetProgramInput(cgProgram); - mOutputOp = cgGetProgramOutput(cgProgram); - } - } - - // Unload Cg Program - we don't need it anymore - cgDestroyProgram(cgProgram); - //checkForCgError("CgProgram::unloadImpl", - // "Error while unloading Cg program " + mName + ": ", - // mCgContext); - cgProgram = 0; - } - - - } - //----------------------------------------------------------------------- - void CgProgram::addMicrocodeToCache(uint32 id) - { - size_t programStringSize = mProgramString.size(); - uint32 sizeOfMicrocode = static_cast( - sizeof(size_t) + // size of mProgramString - programStringSize + // microcode - mProgramString - sizeof(size_t) + // size of param map - mParametersMapSizeAsBuffer); - - // create microcode - auto newMicrocode = GpuProgramManager::createMicrocode(sizeOfMicrocode); - - newMicrocode->seek(0); - - // save size of string - newMicrocode->write(&programStringSize, sizeof(size_t)); - - // save microcode - newMicrocode->write(&mProgramString[0], programStringSize); - - // save size of param map - size_t parametersMapSize = mParametersMap.size(); - newMicrocode->write(¶metersMapSize, sizeof(size_t)); - - // save params - GpuConstantDefinitionMap::const_iterator iter = mParametersMap.begin(); - GpuConstantDefinitionMap::const_iterator iterE = mParametersMap.end(); - for (; iter != iterE ; iter++) - { - const String & paramName = iter->first; - const GpuConstantDefinition & def = iter->second; - - // save string size - size_t stringSize = paramName.size(); - newMicrocode->write(&stringSize, sizeof(size_t)); - - // save string - newMicrocode->write(¶mName[0], stringSize); - - // save def - newMicrocode->write(&def, sizeof(GpuConstantDefinition)); - } - - if (mDelegate) - { - // save additional info required for delegating - size_t samplerMapSize = mSamplerRegisterMap.size(); - newMicrocode->write(&samplerMapSize, sizeof(size_t)); - - // save sampler register mapping - std::map::const_iterator sampRegister = mSamplerRegisterMap.begin(); - std::map::const_iterator sampRegisterE = mSamplerRegisterMap.end(); - for (; sampRegister != sampRegisterE; ++sampRegister) - { - const String& paramName = sampRegister->first; - int reg = sampRegister->second; - - size_t stringSize = paramName.size(); - newMicrocode->write(&stringSize, sizeof(size_t)); - newMicrocode->write(paramName.data(), stringSize); - newMicrocode->write(®, sizeof(int)); - } - - // save input/output operations type - newMicrocode->write(&mInputOp, sizeof(CGenum)); - newMicrocode->write(&mOutputOp, sizeof(CGenum)); - } - - // add to the microcode to the cache - GpuProgramManager::getSingleton().addMicrocodeToCache(id, newMicrocode); - } - //----------------------------------------------------------------------- - void CgProgram::createLowLevelImpl(void) - { - if (mDelegate) - return; - - // ignore any previous error - if (mSelectedCgProfile != CG_PROFILE_UNKNOWN && !mCompileError) - { - - if ( false -// the hlsl 4 profiles are only supported in OGRE from CG 2.2 -#if(CG_VERSION_NUM >= 2200) - || mSelectedCgProfile == CG_PROFILE_VS_4_0 - || mSelectedCgProfile == CG_PROFILE_PS_4_0 -#endif -#if(CG_VERSION_NUM >= 3000) - || mSelectedCgProfile == CG_PROFILE_VS_5_0 - || mSelectedCgProfile == CG_PROFILE_PS_5_0 - || mSelectedCgProfile == CG_PROFILE_DS_5_0 - || mSelectedCgProfile == CG_PROFILE_HS_5_0 -#endif - ) - { - // Create a high-level program, give it the same name as us - HighLevelGpuProgramManager::getSingleton().remove(mName, mGroup); - HighLevelGpuProgramPtr vp = - HighLevelGpuProgramManager::getSingleton().createProgram( - mName, mGroup, "hlsl", mType); - vp->setSource(mProgramString); - vp->setParameter("target", mSelectedProfile); - vp->setParameter("entry_point", "main"); - - vp->load(); - - mAssemblerProgram = vp; - } - else - { - // Create a low-level program, give it the same name as us - mAssemblerProgram = - GpuProgramManager::getSingleton().createProgramFromString( - mName+"/Delegate", - mGroup, - mProgramString, - mType, - mSelectedProfile); - } - } - } - //----------------------------------------------------------------------- - String CgProgram::getHighLevelLanguage() const - { - switch (mSelectedCgProfile) - { - case CG_PROFILE_GLSLF: - case CG_PROFILE_GLSLV: - case CG_PROFILE_GLSLG: - case CG_PROFILE_GLSLC: - return "glsl"; - case CG_PROFILE_HLSLF: - case CG_PROFILE_HLSLV: - return "hlsl"; - default: - return "unknown"; - } - } - //----------------------------------------------------------------------- - String CgProgram::getHighLevelTarget() const - { - // HLSL delegates need a target to compile to. - // Return value for GLSL delegates is ignored. - GpuProgramManager* gpuMgr = GpuProgramManager::getSingletonPtr(); - - if (mSelectedCgProfile == CG_PROFILE_HLSLF) - { - static const String fpProfiles[] = { -#if(CG_VERSION_NUM >= 3000) - "ps_5_0", -#endif -#if(CG_VERSION_NUM >= 2200) - "ps_4_0", -#endif - "ps_3_0", "ps_2_x", "ps_2_0", "ps_1_4", "ps_1_3", "ps_1_2", "ps_1_1"}; - static const size_t numFpProfiles = sizeof(fpProfiles)/sizeof(String); - // find the highest profile available - for (size_t i = 0; i < numFpProfiles; ++i) - { - if (gpuMgr->isSyntaxSupported(fpProfiles[i])) - return fpProfiles[i]; - } - } - else if (mSelectedCgProfile == CG_PROFILE_HLSLV) - { - static const String vpProfiles[] = { -#if(CG_VERSION_NUM >= 3000) - "vs_5_0", -#endif -#if(CG_VERSION_NUM >= 2200) - "vs_4_0", -#endif - "vs_3_0", "vs_2_x", "vs_2_0", "vs_1_4", "vs_1_3", "vs_1_2", "vs_1_1"}; - static const size_t numVpProfiles = sizeof(vpProfiles)/sizeof(String); - // find the highest profile available - for (size_t i = 0; i < numVpProfiles; ++i) - { - if (gpuMgr->isSyntaxSupported(vpProfiles[i])) - return vpProfiles[i]; - } - } - - return "unknown"; - } - //----------------------------------------------------------------------- - struct HighLevelOutputFixer - { - const String& source; - const GpuConstantDefinitionMap& paramMap; - const std::map samplerMap; - bool glsl; - String output; - std::map paramNameMap; - String::size_type start; - struct ReplacementMark - { - String::size_type pos, len; - String replaceWith; - bool operator<(const ReplacementMark& o) const { return pos < o.pos; } - }; - std::vector replacements; - - HighLevelOutputFixer(const String& src, const GpuConstantDefinitionMap& params, - const std::map& samplers, bool isGLSL) - : source(src), paramMap(params), samplerMap(samplers), glsl(isGLSL), start(0) - { - findNameMappings(); - replaceParameterNames(); - buildOutput(); - } - - void findNameMappings() - { - String::size_type cur = 0, end = 0; - while (cur < source.size()) - { - // look for a comment line describing a parameter name mapping - // comment format: //var type parameter : [something] : new name : [something] : [something] - cur = source.find("//var", cur); - if (cur == String::npos) - break; - end = source.find('\n', cur); - std::vector cols = StringUtil::split(source.substr(cur, end-cur), ":"); - cur = end; - if (cols.size() < 3) - continue; - std::vector def = StringUtil::split(cols[0], "[ "); - if (def.size() < 3) - continue; - StringUtil::trim(cols[2]); - std::vector repl = StringUtil::split(cols[2], "[ "); - String oldName = def[2]; - String newName = repl[0]; - StringUtil::trim(oldName); - StringUtil::trim(newName); - if (newName.empty() || newName[0] != '_') - continue; - // if that name is present in our lists, mark in name translation map - GpuConstantDefinitionMap::const_iterator it = paramMap.find(oldName); - if (it != paramMap.end() || samplerMap.find(oldName) != samplerMap.end()) - { - LogManager::getSingleton().stream() << "Replacing parameter name: " << newName << " -> " << oldName; - paramNameMap.insert(std::make_pair(oldName, newName)); - } - } - // end now points at the end of the last comment, so we can strip anything before - start = (end == String::npos ? end : end+1); - } - - void replaceParameterNames() - { - for (GpuConstantDefinitionMap::const_iterator it = paramMap.begin(); it != paramMap.end(); ++it) - { - const String& oldName = it->first; - std::map::const_iterator pi = paramNameMap.find(oldName); - if (pi != paramNameMap.end()) - { - const String& newName = pi->second; - String::size_type beg = start; - // do we need to replace the definition of the parameter? (GLSL only) - if (glsl) - { - if(it->second.arraySize > 1) - LogManager::getSingleton().logWarning("Incomplete Cg-GLSL mapping - '"+oldName+"' is an mat array"); - else if (it->second.constType == GCT_MATRIX_2X2) - beg = findAndMark("uniform vec2 "+newName+"[2]", "uniform mat2 "+oldName, beg); - else if (it->second.constType == GCT_MATRIX_3X3) - beg = findAndMark("uniform vec3 "+newName+"[3]", "uniform mat3 "+oldName, beg); - else if (it->second.constType == GCT_MATRIX_4X4) - beg = findAndMark("uniform vec4 "+newName+"[4]", "uniform mat4 "+oldName, beg); - else if (it->second.constType == GCT_MATRIX_2X3) - beg = findAndMark("uniform vec3 "+newName+"[2]", "uniform mat2x3 "+oldName, beg); - else if (it->second.constType == GCT_MATRIX_2X4) - beg = findAndMark("uniform vec4 "+newName+"[2]", "uniform mat2x4 "+oldName, beg); - else if (it->second.constType == GCT_MATRIX_3X2) - beg = findAndMark("uniform vec2 "+newName+"[3]", "uniform mat3x2 "+oldName, beg); - else if (it->second.constType == GCT_MATRIX_3X4) - beg = findAndMark("uniform vec4 "+newName+"[3]", "uniform mat3x4 "+oldName, beg); - else if (it->second.constType == GCT_MATRIX_4X2) - beg = findAndMark("uniform vec2 "+newName+"[4]", "uniform mat4x2 "+oldName, beg); - else if (it->second.constType == GCT_MATRIX_4X3) - beg = findAndMark("uniform vec3 "+newName+"[4]", "uniform mat4x3 "+oldName, beg); - } - - // mark all occurrences of the parameter name for replacement - findAndMark(newName, oldName, beg); - } - } - - for (std::map::const_iterator it = samplerMap.begin(); it != samplerMap.end(); ++it) - { - const String& oldName = it->first; - std::map::const_iterator pi = paramNameMap.find(oldName); - if (pi != paramNameMap.end()) - { - const String& newName = pi->second; - findAndMark(newName, oldName, start); - } - } - } - - String::size_type findAndMark(const String& search, const String& replaceWith, String::size_type cur) - { - ReplacementMark mark; - mark.pos = String::npos; - mark.len = search.size(); - mark.replaceWith = replaceWith; - while (cur < source.size()) - { - cur = source.find(search, cur); - if (cur == String::npos) - break; - mark.pos = cur; - cur += search.size(); - // check if previous or following character continue an identifier - // in that case, skip this occurrence as it's part of a longer identifier - if (mark.pos > 0) - { - char c = source[mark.pos-1]; - if (c == '_' || std::isalnum(c)) - continue; - } - if (mark.pos+1 < search.size()) - { - char c = source[mark.pos+1]; - if (c == '_' || std::isalnum(c)) - continue; - } - replacements.push_back(mark); - } - if (mark.pos != String::npos) - return mark.pos + search.size(); - else - return String::npos; - } - - void buildOutput() - { - // sort replacements in order of occurrence - std::sort(replacements.begin(), replacements.end()); - String::size_type cur = start; - for (std::vector::iterator it = replacements.begin(); it != replacements.end(); ++it) - { - ReplacementMark& mark = *it; - if (mark.pos > cur) - output.append(source, cur, mark.pos-cur); - output.append(mark.replaceWith); - cur = mark.pos+mark.len; - } - if (cur < source.size()) - output.append(source, cur, String::npos); - } - }; - //----------------------------------------------------------------------- - void CgProgram::fixHighLevelOutput(String& hlSource) - { - // Cg chooses to change parameter names when translating to another - // high level language, possibly to avoid clashes with reserved keywords. - // We need to revert that, otherwise Ogre parameter mappings fail. - // Cg logs its renamings in the comments at the beginning of the - // processed source file. We can get them from there. - // We'll also get rid of those comments to trim down source code size. -#if OGRE_DEBUG_MODE || 1 - LogManager::getSingleton().stream() << "Cg high level output for " << getName() << ":\n" << hlSource; -#endif - hlSource = HighLevelOutputFixer(hlSource, mParametersMap, mSamplerRegisterMap, - mSelectedCgProfile == CG_PROFILE_GLSLV || mSelectedCgProfile == CG_PROFILE_GLSLF || - mSelectedCgProfile == CG_PROFILE_GLSLG).output; -#if OGRE_DEBUG_MODE || 1 - LogManager::getSingleton().stream() << "Cleaned high level output for " << getName() << ":\n" << hlSource; -#endif - } - - - //----------------------------------------------------------------------- - void CgProgram::loadHighLevelSafe() - { - safePrepare(); - OGRE_LOCK_AUTO_MUTEX; - if (this->isSupported()) - loadHighLevel(); - } - //----------------------------------------------------------------------- - GpuProgramParametersSharedPtr CgProgram::createParameters() - { - loadHighLevelSafe(); - if (mDelegate) - return mDelegate->createParameters(); - else - return HighLevelGpuProgram::createParameters(); - } - //----------------------------------------------------------------------- - GpuProgram* CgProgram::_getBindingDelegate() - { - if (mDelegate) - return mDelegate->_getBindingDelegate(); - else - return HighLevelGpuProgram::_getBindingDelegate(); - } - //----------------------------------------------------------------------- - bool CgProgram::isSkeletalAnimationIncluded(void) const - { - if (mDelegate) - return mDelegate->isSkeletalAnimationIncluded(); - else - return HighLevelGpuProgram::isSkeletalAnimationIncluded(); - } - //----------------------------------------------------------------------- - bool CgProgram::isMorphAnimationIncluded(void) const - { - if (mDelegate) - return mDelegate->isMorphAnimationIncluded(); - else - return HighLevelGpuProgram::isMorphAnimationIncluded(); - } - //----------------------------------------------------------------------- - bool CgProgram::isPoseAnimationIncluded(void) const - { - if (mDelegate) - return mDelegate->isPoseAnimationIncluded(); - else - return HighLevelGpuProgram::isPoseAnimationIncluded(); - } - //----------------------------------------------------------------------- - bool CgProgram::isVertexTextureFetchRequired(void) const - { - if (mDelegate) - return mDelegate->isVertexTextureFetchRequired(); - else - return HighLevelGpuProgram::isVertexTextureFetchRequired(); - } - //----------------------------------------------------------------------- - const GpuProgramParametersPtr& CgProgram::getDefaultParameters(void) - { - loadHighLevelSafe(); - if (mDelegate) - return mDelegate->getDefaultParameters(); - else - return HighLevelGpuProgram::getDefaultParameters(); - } - //----------------------------------------------------------------------- - bool CgProgram::hasDefaultParameters(void) const - { - if (mDelegate) - return mDelegate->hasDefaultParameters(); - else - return HighLevelGpuProgram::hasDefaultParameters(); - } - //----------------------------------------------------------------------- - bool CgProgram::getPassSurfaceAndLightStates(void) const - { - if (mDelegate) - return mDelegate->getPassSurfaceAndLightStates(); - else - return HighLevelGpuProgram::getPassSurfaceAndLightStates(); - } - //----------------------------------------------------------------------- - bool CgProgram::getPassFogStates(void) const - { - if (mDelegate) - return mDelegate->getPassFogStates(); - else - return HighLevelGpuProgram::getPassFogStates(); - } - //----------------------------------------------------------------------- - bool CgProgram::getPassTransformStates(void) const - { - if (mDelegate) - return mDelegate->getPassTransformStates(); - else - { - return true; /* CG uses MVP matrix when -posinv argument passed */ - } - } - //----------------------------------------------------------------------- - bool CgProgram::hasCompileError(void) const - { - if (mDelegate) - return mDelegate->hasCompileError(); - else - return HighLevelGpuProgram::hasCompileError(); - } - //----------------------------------------------------------------------- - void CgProgram::resetCompileError(void) - { - if (mDelegate) - mDelegate->resetCompileError(); - else - HighLevelGpuProgram::resetCompileError(); - } - //----------------------------------------------------------------------- - size_t CgProgram::getSize() const - { - if (mDelegate) - return mDelegate->getSize(); - else - return HighLevelGpuProgram::getSize(); - } - //----------------------------------------------------------------------- - void CgProgram::touch() - { - if (mDelegate) - mDelegate->touch(); - else - HighLevelGpuProgram::touch(); - } - - - //----------------------------------------------------------------------- - void CgProgram::unloadHighLevelImpl(void) - { - if (mDelegate) - { - mDelegate->getCreator()->remove(mDelegate); - mDelegate.reset(); - } - } - //----------------------------------------------------------------------- - void CgProgram::buildConstantDefinitions() - { - // Derive parameter names from Cg - createParameterMappingStructures(true); - - if ( mProgramString.empty() ) - return; - - mConstantDefs->bufferSize = mLogicalToPhysical->bufferSize; - - GpuConstantDefinitionMap::const_iterator iter = mParametersMap.begin(); - GpuConstantDefinitionMap::const_iterator iterE = mParametersMap.end(); - for (; iter != iterE ; iter++) - { - GpuConstantDefinition def = iter->second; - - mConstantDefs->map.emplace(iter->first, iter->second); - - // Record logical / physical mapping - OGRE_LOCK_MUTEX(mLogicalToPhysical->mutex); - mLogicalToPhysical->map.emplace(def.logicalIndex, - GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, GPV_GLOBAL, def.isFloat() ? BCT_FLOAT: BCT_INT)); - mLogicalToPhysical->bufferSize += def.arraySize * def.elementSize; - } - } - //--------------------------------------------------------------------- - void CgProgram::recurseParams(CGparameter parameter, size_t contextArraySize) - { - while (parameter != 0) - { - // Look for uniform parameters only - // Don't bother enumerating unused parameters, especially since they will - // be optimised out and therefore not in the indexed versions - CGtype paramType = cgGetParameterType(parameter); - - if (cgGetParameterVariability(parameter) == CG_UNIFORM && - paramType != CG_SAMPLER1D && - paramType != CG_SAMPLER2D && - paramType != CG_SAMPLER3D && - paramType != CG_SAMPLERCUBE && - paramType != CG_SAMPLERRECT && - cgGetParameterDirection(parameter) != CG_OUT && - cgIsParameterReferenced(parameter)) - { - int arraySize; - - switch(paramType) - { - case CG_STRUCT: - recurseParams(cgGetFirstStructParameter(parameter)); - break; - case CG_ARRAY: - // Support only 1-dimensional arrays - arraySize = cgGetArraySize(parameter, 0); - recurseParams(cgGetArrayParameter(parameter, 0), (size_t)arraySize); - break; - default: - // Normal path (leaf) - String paramName = cgGetParameterName(parameter); - size_t logicalIndex = cgGetParameterResourceIndex(parameter); - - // Get the parameter resource, to calculate the physical index - CGresource res = cgGetParameterResource(parameter); - bool isRegisterCombiner = false; - size_t regCombinerPhysicalIndex = 0; - switch (res) - { - case CG_COMBINER_STAGE_CONST0: - // register combiner, const 0 - // the index relates to the texture stage; store this as (stage * 2) + 0 - regCombinerPhysicalIndex = logicalIndex * 2; - isRegisterCombiner = true; - break; - case CG_COMBINER_STAGE_CONST1: - // register combiner, const 1 - // the index relates to the texture stage; store this as (stage * 2) + 1 - regCombinerPhysicalIndex = (logicalIndex * 2) + 1; - isRegisterCombiner = true; - break; - default: - // normal constant - break; - } - - // Trim the '[0]' suffix if it exists, we will add our own indexing later - if (StringUtil::endsWith(paramName, "[0]", false)) - { - paramName.erase(paramName.size() - 3); - } - - - GpuConstantDefinition def; - def.arraySize = contextArraySize; - mapTypeAndElementSize(paramType, isRegisterCombiner, def); - - if (def.constType == GCT_UNKNOWN) - { - LogManager::getSingleton().logMessage( - "Problem parsing the following Cg Uniform: '" - + paramName + "' in file " + mName); - // next uniform - parameter = cgGetNextParameter(parameter); - continue; - } - if (isRegisterCombiner) - { - def.physicalIndex = regCombinerPhysicalIndex; - } - else - { - // base position on existing buffer contents - def.physicalIndex = mLogicalToPhysical->bufferSize*4; - } - - def.logicalIndex = logicalIndex; - if( mParametersMap.find(paramName) == mParametersMap.end()) - { - mParametersMap.emplace(paramName, def); - mParametersMapSizeAsBuffer += sizeof(size_t); - mParametersMapSizeAsBuffer += paramName.size(); - mParametersMapSizeAsBuffer += sizeof(GpuConstantDefinition); - } - - // Record logical / physical mapping - OGRE_LOCK_MUTEX(mLogicalToPhysical->mutex); - mLogicalToPhysical->map.emplace(def.logicalIndex, - GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, GPV_GLOBAL, def.isFloat() ? BCT_FLOAT : BCT_INT)); - mLogicalToPhysical->bufferSize += def.arraySize * def.elementSize; - - break; - } - } - - // now handle uniform samplers. This is needed to fix their register positions - // if delegating to a GLSL shader. - if (mDelegate && cgGetParameterVariability(parameter) == CG_UNIFORM && ( - paramType == CG_SAMPLER1D || - paramType == CG_SAMPLER2D || - paramType == CG_SAMPLER3D || - paramType == CG_SAMPLERCUBE || - paramType == CG_SAMPLERRECT) && - cgGetParameterDirection(parameter) != CG_OUT && - cgIsParameterReferenced(parameter)) - { - String paramName = cgGetParameterName(parameter); - CGresource res = cgGetParameterResource(parameter); - int pos = -1; - switch (res) - { - case CG_TEXUNIT0: pos = 0; break; - case CG_TEXUNIT1: pos = 1; break; - case CG_TEXUNIT2: pos = 2; break; - case CG_TEXUNIT3: pos = 3; break; - case CG_TEXUNIT4: pos = 4; break; - case CG_TEXUNIT5: pos = 5; break; - case CG_TEXUNIT6: pos = 6; break; - case CG_TEXUNIT7: pos = 7; break; - case CG_TEXUNIT8: pos = 8; break; - case CG_TEXUNIT9: pos = 9; break; - case CG_TEXUNIT10: pos = 10; break; - case CG_TEXUNIT11: pos = 11; break; - case CG_TEXUNIT12: pos = 12; break; - case CG_TEXUNIT13: pos = 13; break; - case CG_TEXUNIT14: pos = 14; break; - case CG_TEXUNIT15: pos = 15; break; -#if(CG_VERSION_NUM >= 3000) - case CG_TEXUNIT16: pos = 16; break; - case CG_TEXUNIT17: pos = 17; break; - case CG_TEXUNIT18: pos = 18; break; - case CG_TEXUNIT19: pos = 19; break; - case CG_TEXUNIT20: pos = 20; break; - case CG_TEXUNIT21: pos = 21; break; - case CG_TEXUNIT22: pos = 22; break; - case CG_TEXUNIT23: pos = 23; break; - case CG_TEXUNIT24: pos = 24; break; - case CG_TEXUNIT25: pos = 25; break; - case CG_TEXUNIT26: pos = 26; break; - case CG_TEXUNIT27: pos = 27; break; - case CG_TEXUNIT28: pos = 28; break; - case CG_TEXUNIT29: pos = 29; break; - case CG_TEXUNIT30: pos = 30; break; - case CG_TEXUNIT31: pos = 31; break; -#endif - default: - break; - } - if (pos != -1) - { - mSamplerRegisterMap.insert(std::make_pair(paramName, pos)); - } - } - - // Get next - parameter = cgGetNextParameter(parameter); - } - - - } - //----------------------------------------------------------------------- - void CgProgram::mapTypeAndElementSize(CGtype cgType, bool isRegisterCombiner, - GpuConstantDefinition& def) const - { - if (isRegisterCombiner) - { - // register combiners are the only single-float entries in our buffer - def.constType = GCT_FLOAT1; - def.elementSize = 1; - } - else - { - switch(cgType) - { - case CG_FLOAT: - case CG_FLOAT1: - case CG_HALF: - case CG_HALF1: - def.constType = GCT_FLOAT1; - break; - case CG_FLOAT2: - case CG_HALF2: - def.constType = GCT_FLOAT2; - break; - case CG_FLOAT3: - case CG_HALF3: - def.constType = GCT_FLOAT3; - break; - case CG_FLOAT4: - case CG_HALF4: - def.constType = GCT_FLOAT4; - break; - case CG_FLOAT2x2: - case CG_HALF2x2: - def.constType = GCT_MATRIX_2X2; - break; - case CG_FLOAT2x3: - case CG_HALF2x3: - def.constType = GCT_MATRIX_2X3; - break; - case CG_FLOAT2x4: - case CG_HALF2x4: - def.constType = GCT_MATRIX_2X4; - break; - case CG_FLOAT3x2: - case CG_HALF3x2: - def.constType = GCT_MATRIX_3X2; - break; - case CG_FLOAT3x3: - case CG_HALF3x3: - def.constType = GCT_MATRIX_3X3; - break; - case CG_FLOAT3x4: - case CG_HALF3x4: - def.constType = GCT_MATRIX_3X4; - break; - case CG_FLOAT4x2: - case CG_HALF4x2: - def.constType = GCT_MATRIX_4X2; - break; - case CG_FLOAT4x3: - case CG_HALF4x3: - def.constType = GCT_MATRIX_4X3; - break; - case CG_FLOAT4x4: - case CG_HALF4x4: - def.constType = GCT_MATRIX_4X4; - break; - case CG_INT: - case CG_INT1: - def.constType = GCT_INT1; - break; - case CG_INT2: - def.constType = GCT_INT2; - break; - case CG_INT3: - def.constType = GCT_INT3; - break; - case CG_INT4: - def.constType = GCT_INT4; - break; - default: - def.constType = GCT_UNKNOWN; - break; - } - // Cg pads - def.elementSize = GpuConstantDefinition::getElementSize(def.constType, true); - } - } - //----------------------------------------------------------------------- - CgProgram::CgProgram(ResourceManager* creator, const String& name, - ResourceHandle handle, const String& group, bool isManual, - ManualResourceLoader* loader, CGcontext context) - : HighLevelGpuProgram(creator, name, handle, group, isManual, loader), - mCgContext(context), - mSelectedCgProfile(CG_PROFILE_UNKNOWN), mCgArguments(0), mParametersMapSizeAsBuffer(0) - { - if (createParamDictionary("CgProgram")) - { - setupBaseParamDictionary(); - - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter(ParameterDef("profiles", - "Space-separated list of Cg profiles supported by this profile.", - PT_STRING),&msCmdProfiles); - dict->addParameter(ParameterDef("compile_arguments", - "A string of compilation arguments to pass to the Cg compiler.", - PT_STRING),&msCmdArgs); - } - - } - //----------------------------------------------------------------------- - CgProgram::~CgProgram() - { - freeCgArgs(); - // have to call this here reather than in Resource destructor - // since calling virtual methods in base destructors causes crash - if (isLoaded()) - { - unload(); - } - else - { - unloadHighLevel(); - } - } - //----------------------------------------------------------------------- - bool CgProgram::isSupported(void) const - { - if (mDelegate) - return mDelegate->isSupported(); - - if (mCompileError || !isRequiredCapabilitiesSupported()) - return false; - - return mSelectedCgProfile != CG_PROFILE_UNKNOWN; - } - //----------------------------------------------------------------------- - void CgProgram::setProfiles(const StringVector& profiles) - { - mProfiles = profiles; - selectProfile(); - } - - //----------------------------------------------------------------------- - const String& CgProgram::getLanguage(void) const - { - static const String language = "cg"; - - return language; - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String CgProgram::CmdProfiles::doGet(const void *target) const - { - return StringConverter::toString( - static_cast(target)->getProfiles() ); - } - void CgProgram::CmdProfiles::doSet(void *target, const String& val) - { - static_cast(target)->setProfiles(StringUtil::split(val)); - } - //----------------------------------------------------------------------- - String CgProgram::CmdArgs::doGet(const void *target) const - { - return static_cast(target)->getPreprocessorDefines(); - } - void CgProgram::CmdArgs::doSet(void *target, const String& val) - { - static_cast(target)->setPreprocessorDefines(val); - } - -} diff --git a/PlugIns/CgProgramManager/src/OgreCgProgramFactory.cpp b/PlugIns/CgProgramManager/src/OgreCgProgramFactory.cpp deleted file mode 100644 index 4403fdc5da8..00000000000 --- a/PlugIns/CgProgramManager/src/OgreCgProgramFactory.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreCgProgramFactory.h" -#include "OgreCgProgram.h" - -namespace Ogre { - //----------------------------------------------------------------------- - String CgProgramFactory::sLanguageName = "cg"; - //----------------------------------------------------------------------- - CgProgramFactory::CgProgramFactory() - { - mCgContext = cgCreateContext(); - // Check for errors - checkForCgError("CgProgramFactory::CgProgramFactory", - "Unable to create initial Cg context: ", mCgContext); - } - //----------------------------------------------------------------------- - CgProgramFactory::~CgProgramFactory() - { - cgDestroyContext(mCgContext); - // Check for errors - checkForCgError("CgProgramFactory::~CgProgramFactory", - "Unable to destroy Cg context: ", mCgContext); - } - //----------------------------------------------------------------------- - const String& CgProgramFactory::getLanguage(void) const - { - return sLanguageName; - } - //----------------------------------------------------------------------- - GpuProgram* CgProgramFactory::create(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - { - return OGRE_NEW CgProgram(creator, name, handle, group, isManual, loader, mCgContext); - } -} diff --git a/PlugIns/CgProgramManager/src/OgreCgProgramManagerDll.cpp b/PlugIns/CgProgramManager/src/OgreCgProgramManagerDll.cpp deleted file mode 100644 index 92371efa795..00000000000 --- a/PlugIns/CgProgramManager/src/OgreCgProgramManagerDll.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreCgPrerequisites.h" -#include "OgreCgPlugin.h" -#include "OgreRoot.h" - -namespace Ogre { - -#ifndef OGRE_STATIC_LIB - extern "C" void _OgreCgPluginExport dllStartPlugin(void); - extern "C" void _OgreCgPluginExport dllStopPlugin(void); - - static CgPlugin* cgPlugin; - //----------------------------------------------------------------------- - extern "C" void _OgreCgPluginExport dllStartPlugin(void) - { - // Create new plugin - cgPlugin = OGRE_NEW CgPlugin(); - - // Register - Root::getSingleton().installPlugin(cgPlugin); - - - } - extern "C" void _OgreCgPluginExport dllStopPlugin(void) - { - Root::getSingleton().uninstallPlugin(cgPlugin); - OGRE_DELETE cgPlugin; - } -#endif - - void checkForCgError(const String& ogreMethod, const String& errorTextPrefix, CGcontext context) - { - CGerror error = cgGetError(); - if (error != CG_NO_ERROR) - { - String msg = errorTextPrefix + cgGetErrorString(error); - - if (error == CG_COMPILER_ERROR) - { - // Get listing with full compile errors - msg = msg + "\n" + cgGetLastListing(context); - } - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, msg, ogreMethod); - } - } - -} diff --git a/PlugIns/DotScene/CMakeLists.txt b/PlugIns/DotScene/CMakeLists.txt deleted file mode 100644 index ffc2622c4dc..00000000000 --- a/PlugIns/DotScene/CMakeLists.txt +++ /dev/null @@ -1,18 +0,0 @@ -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES ${PROJECT_BINARY_DIR}/include/OgreDotScenePluginExports.h) - -add_library(Plugin_DotScene ${OGRE_LIB_TYPE} ${HEADER_FILES} src/DotSceneLoader.cpp) -target_include_directories(Plugin_DotScene PUBLIC - "$" - $) -target_link_libraries(Plugin_DotScene PUBLIC OgreMain PRIVATE pugixml) -if(OGRE_BUILD_COMPONENT_TERRAIN) - target_link_libraries(Plugin_DotScene PUBLIC OgreTerrain) -endif() - -ogre_config_framework(Plugin_DotScene) -ogre_config_plugin(Plugin_DotScene) -generate_export_header(Plugin_DotScene - EXPORT_MACRO_NAME _OgreDotScenePluginExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreDotScenePluginExports.h) -install(FILES ${HEADER_FILES} DESTINATION include/OGRE/Plugins/DotScene) \ No newline at end of file diff --git a/PlugIns/DotScene/README.md b/PlugIns/DotScene/README.md deleted file mode 100644 index 63046e21b99..00000000000 --- a/PlugIns/DotScene/README.md +++ /dev/null @@ -1,125 +0,0 @@ -# DotScene Overview {#dotscene_overview} - -DotScene (aka .scene) is just a standardized XML file format. - -This file format is meant to be used to set up a scene or scene-part. It is useful for any type of application/ game. Editors can export to .scene format, and apps can load the format. - -Besides Ogre, the [jMonkeyEngine](http://jmonkeyengine.org/) also supports loading .scene files. - -@tableofcontents - -## What is DotScene? -DotScene file does not contain any mesh data, texture data, etc. It just contains elements that describe a scene. - -A simple .scene file example: -```xml - - - - - - - - - - - - - - - - - - -``` - -## User Data - -To add logic properties to the scene you can use the `` node as following: - -```xml - - - - - - -``` - -On the C++ side, these are acessible via e.g. -```cpp -Ogre::SceneManager* mSceneMgr = ...; -mSceneMgr->getEntity("Cube")->getUserObjectBindings().getUserAny("mass"); -``` - -## How to use DotScene -To use DotScene it has to be loaded as another OGRE Plugin. - -In `plugins.cfg`, add the following line: -```ini -Plugin=Plugin_DotScene -``` - -The Plugin will be then automatically used when you call `SceneNode::loadChildren()` like -```cpp -Ogre::SceneNode* attachmentNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - -// Set the desired resource group first and then load the Scene -Ogre::ResourceGroupManager::getSingleton().setWorldResourceGroupName("MyGroup"); -attachmentNode->loadChildren("myScene.scene"); -``` - -If there is a TerrainGroup defined in the .scene file, you can get it by: -```cpp -attachmentNode->getUserObjectBindings().getUserAny("TerrainGroup"); -``` -The type is `std::shared_ptr`, hence `attachmentNode` owns it and will take it down on destruction. - -## Instancing -The DotScene Plugin can process the static / instanced attributes of the Entity definition to add them to the scene as either Static Geometry or Instanced meshes. - -@see @ref WhatIsInstancing -@see @ref tut_StaticGeom - -### Static Geometry -If your scene has entities with the *static* property then the name referenced by the property is interpreted by the plugin as the name of the Static Geometry Group -For example: -```xml - -``` - -The plugin requires that the Static Geometry group or instance is created before loading the Scene and built afterwards. -Continuing with the example above, supose you created a scene with entities belonging to the "Foliage" group. - -```cpp -// Create the StaticGeometry -Ogre::StaticGeometry* sg = mSceneMgr->createStaticGeometry("Foliage"); - -attachmentNode->loadChildren("myScene.scene"); - -// Build the StaticGeometry after loading the Scene -sg->build(); -``` - -Any configuration for the StaticGeometry should be done before the `build()` call. - -### Instance Manager -If your scene has entities with the *instanced* property then the name referenced by the property is interpreted by the plugin as the name of the Instance Manager -For example: -```xml - -``` - -The plugin requires that the Instance Manager is created before loading the Scene. -Continuing with the example above, supose you created a scene with entities that you want to create with the "Foliage" Instance Manager. - -@note Be aware that only the first submesh of the mesh is taken into account, if you have an Entity with many submeshes only the first one will be shown. - -```cpp -// Create the InstanceManager -Ogre::InstanceManager* im = mSceneMgr->createInstanceManager("Foliage", "Cube.mesh", "MyGroup", Ogre::InstanceManager::ShaderBased, 80, Ogre::IM_USEALL); - -attachmentNode->loadChildren("myScene.scene"); -``` - -Any configuration for the InstanceManager should be done before calling `loadChildren()` diff --git a/PlugIns/DotScene/include/OgreDotSceneLoader.h b/PlugIns/DotScene/include/OgreDotSceneLoader.h deleted file mode 100644 index b8b58aefe57..00000000000 --- a/PlugIns/DotScene/include/OgreDotSceneLoader.h +++ /dev/null @@ -1,96 +0,0 @@ -#ifndef DOT_SCENELOADER_H -#define DOT_SCENELOADER_H - -// Includes -#include -#include -#include -#include -#include -#include -#include - -namespace pugi -{ -class xml_node; -} - -// Forward declarations -namespace Ogre -{ -class SceneManager; -class SceneNode; - -/** \addtogroup Plugins Plugins -* @{ -*/ -/** \defgroup DotSceneCodec DotSceneCodec - * - * %Codec for loading and saving the SceneNode hierarchy in .scene files. - * @{ - */ -class _OgreDotScenePluginExport DotSceneLoader -{ -public: - DotSceneLoader(); - virtual ~DotSceneLoader(); - - void load(Ogre::DataStreamPtr& stream, const Ogre::String& groupName, Ogre::SceneNode* rootNode); - - void exportScene(SceneNode* rootNode, const String& outFileName); - - const Ogre::ColourValue& getBackgroundColour() { return mBackgroundColour; } - -protected: - void writeNode(pugi::xml_node& parentXML, const SceneNode* node); - void processScene(pugi::xml_node& XMLRoot); - - void processNodes(pugi::xml_node& XMLNode); - void processExternals(pugi::xml_node& XMLNode); - void processEnvironment(pugi::xml_node& XMLNode); - void processTerrainGroup(pugi::xml_node& XMLNode); - void processBlendmaps(pugi::xml_node& XMLNode); - void processUserData(pugi::xml_node& XMLNode, Ogre::UserObjectBindings& userData); - void processLight(pugi::xml_node& XMLNode, Ogre::SceneNode* pParent = 0); - void processCamera(pugi::xml_node& XMLNode, Ogre::SceneNode* pParent = 0); - - void processNode(pugi::xml_node& XMLNode, Ogre::SceneNode* pParent = 0); - void processLookTarget(pugi::xml_node& XMLNode, Ogre::SceneNode* pParent); - void processTrackTarget(pugi::xml_node& XMLNode, Ogre::SceneNode* pParent); - void processEntity(pugi::xml_node& XMLNode, Ogre::SceneNode* pParent); - void processParticleSystem(pugi::xml_node& XMLNode, Ogre::SceneNode* pParent); - void processBillboardSet(pugi::xml_node& XMLNode, Ogre::SceneNode* pParent); - void processPlane(pugi::xml_node& XMLNode, Ogre::SceneNode* pParent); - void processNodeAnimations(pugi::xml_node& XMLNode, Ogre::SceneNode* pParent); - void processNodeAnimation(pugi::xml_node& XMLNode, Ogre::SceneNode* pParent); - void processKeyframe(pugi::xml_node& XMLNode, Ogre::NodeAnimationTrack* pTrack); - - void processFog(pugi::xml_node& XMLNode); - void processSkyBox(pugi::xml_node& XMLNode); - void processSkyDome(pugi::xml_node& XMLNode); - void processSkyPlane(pugi::xml_node& XMLNode); - - void processLightRange(pugi::xml_node& XMLNode, Ogre::Light* pLight); - void processLightAttenuation(pugi::xml_node& XMLNode, Ogre::Light* pLight); - - Ogre::SceneManager* mSceneMgr; - Ogre::SceneNode* mAttachNode; - Ogre::String m_sGroupName; - Ogre::ColourValue mBackgroundColour; -}; - -class _OgreDotScenePluginExport DotScenePlugin : public Plugin -{ - const String& getName() const override; - - void install() override {} - void initialise() override; - void shutdown() override; - void uninstall() override {} -private: - Codec* mCodec; -}; -/** @} */ -/** @} */ -} // namespace Ogre -#endif // DOT_SCENELOADER_H diff --git a/PlugIns/DotScene/misc/dotscene.dtd b/PlugIns/DotScene/misc/dotscene.dtd deleted file mode 100644 index bf967aa09c7..00000000000 --- a/PlugIns/DotScene/misc/dotscene.dtd +++ /dev/null @@ -1,297 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/PlugIns/DotScene/misc/example.scene b/PlugIns/DotScene/misc/example.scene deleted file mode 100644 index e599d615103..00000000000 --- a/PlugIns/DotScene/misc/example.scene +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/PlugIns/DotScene/misc/validate.py b/PlugIns/DotScene/misc/validate.py deleted file mode 100755 index 1d7452e8512..00000000000 --- a/PlugIns/DotScene/misc/validate.py +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/python3 - -import sys -from lxml import etree - -dtd = etree.DTD(sys.path[0]+"/dotscene.dtd") -root = etree.parse(sys.argv[1]) - -if dtd.validate(root): - print("validation successful") -else: - print(dtd.error_log.filter_from_errors()) \ No newline at end of file diff --git a/PlugIns/DotScene/src/DotSceneLoader.cpp b/PlugIns/DotScene/src/DotSceneLoader.cpp deleted file mode 100644 index 809986d52a6..00000000000 --- a/PlugIns/DotScene/src/DotSceneLoader.cpp +++ /dev/null @@ -1,1135 +0,0 @@ -#include -#include -#include - -#ifdef OGRE_BUILD_COMPONENT_TERRAIN -#include -#include -#endif - -#include - -using namespace Ogre; - -#ifndef OGRE_BUILD_COMPONENT_TERRAIN -namespace Ogre { - class TerrainGroup {}; // appease unique_ptr destructor -} -#endif - -namespace -{ -String getAttrib(const pugi::xml_node& XMLNode, const String& attrib, const String& defaultValue = "") -{ - if (auto anode = XMLNode.attribute(attrib.c_str())) - return anode.value(); - else - return defaultValue; -} - -Real getAttribReal(const pugi::xml_node& XMLNode, const String& attrib, Real defaultValue = 0) -{ - if (auto anode = XMLNode.attribute(attrib.c_str())) - return StringConverter::parseReal(anode.value()); - else - return defaultValue; -} - -bool getAttribBool(const pugi::xml_node& XMLNode, const String& attrib, bool defaultValue = false) -{ - if (auto anode = XMLNode.attribute(attrib.c_str())) - return anode.as_bool(); - else - return defaultValue; - - return false; -} - -Vector3 parseVector3(const pugi::xml_node& XMLNode) -{ - return Vector3(StringConverter::parseReal(XMLNode.attribute("x").value()), - StringConverter::parseReal(XMLNode.attribute("y").value()), - StringConverter::parseReal(XMLNode.attribute("z").value())); -} - -Quaternion parseQuaternion(const pugi::xml_node& XMLNode) -{ - //! @todo Fix this crap! - - Quaternion orientation; - - if (XMLNode.attribute("qw")) - { - orientation.w = StringConverter::parseReal(XMLNode.attribute("qw").value()); - orientation.x = StringConverter::parseReal(XMLNode.attribute("qx").value()); - orientation.y = StringConverter::parseReal(XMLNode.attribute("qy").value()); - orientation.z = StringConverter::parseReal(XMLNode.attribute("qz").value()); - } - else if (XMLNode.attribute("axisX")) - { - Vector3 axis; - axis.x = StringConverter::parseReal(XMLNode.attribute("axisX").value()); - axis.y = StringConverter::parseReal(XMLNode.attribute("axisY").value()); - axis.z = StringConverter::parseReal(XMLNode.attribute("axisZ").value()); - Real angle = StringConverter::parseReal(XMLNode.attribute("angle").value()); - - orientation.FromAngleAxis(Radian(angle), axis); - } - else if (XMLNode.attribute("angleX")) - { - Matrix3 rot; - rot.FromEulerAnglesXYZ(StringConverter::parseAngle(XMLNode.attribute("angleX").value()), - StringConverter::parseAngle(XMLNode.attribute("angleY").value()), - StringConverter::parseAngle(XMLNode.attribute("angleZ").value())); - orientation.FromRotationMatrix(rot); - } - else if (XMLNode.attribute("x")) - { - orientation.x = StringConverter::parseReal(XMLNode.attribute("x").value()); - orientation.y = StringConverter::parseReal(XMLNode.attribute("y").value()); - orientation.z = StringConverter::parseReal(XMLNode.attribute("z").value()); - orientation.w = StringConverter::parseReal(XMLNode.attribute("w").value()); - } - else if (XMLNode.attribute("w")) - { - orientation.w = StringConverter::parseReal(XMLNode.attribute("w").value()); - orientation.x = StringConverter::parseReal(XMLNode.attribute("x").value()); - orientation.y = StringConverter::parseReal(XMLNode.attribute("y").value()); - orientation.z = StringConverter::parseReal(XMLNode.attribute("z").value()); - } - - return orientation; -} - -ColourValue parseColour(pugi::xml_node& XMLNode) -{ - return ColourValue(StringConverter::parseReal(XMLNode.attribute("r").value()), - StringConverter::parseReal(XMLNode.attribute("g").value()), - StringConverter::parseReal(XMLNode.attribute("b").value()), - XMLNode.attribute("a") != NULL ? StringConverter::parseReal(XMLNode.attribute("a").value()) : 1); -} - -struct DotSceneCodec : public Codec -{ - String magicNumberToFileExt(const char* magicNumberPtr, size_t maxbytes) const override { return ""; } - String getType() const override { return "scene"; } - void decode(const DataStreamPtr& stream, const Any& output) const override - { - DataStreamPtr _stream(stream); - DotSceneLoader loader; - loader.load(_stream, ResourceGroupManager::getSingleton().getWorldResourceGroupName(), - any_cast(output)); - } - - void encodeToFile(const Any& input, const String& outFileName) const override - { - DotSceneLoader loader; - loader.exportScene(any_cast(input), outFileName); - } -}; - -} // namespace - -DotSceneLoader::DotSceneLoader() : mSceneMgr(0), mBackgroundColour(ColourValue::Black) {} - -DotSceneLoader::~DotSceneLoader() {} - -void DotSceneLoader::load(DataStreamPtr& stream, const String& groupName, SceneNode* rootNode) -{ - m_sGroupName = groupName; - mSceneMgr = rootNode->getCreator(); - - pugi::xml_document XMLDoc; // character type defaults to char - - auto result = XMLDoc.load_buffer(stream->getAsString().c_str(), stream->size()); - if (!result) - { - LogManager::getSingleton().logError("DotSceneLoader - " + String(result.description())); - return; - } - - // Grab the scene node - auto XMLRoot = XMLDoc.child("scene"); - - // Validate the File - if (!XMLRoot.attribute("formatVersion")) - { - LogManager::getSingleton().logError("DotSceneLoader - Invalid .scene File. Missing "); - return; - } - - // figure out where to attach any nodes we create - mAttachNode = rootNode; - - // Process the scene - processScene(XMLRoot); -} - -void DotSceneLoader::processScene(pugi::xml_node& XMLRoot) -{ - // Process the scene parameters - String version = getAttrib(XMLRoot, "formatVersion", "unknown"); - - String message = "[DotSceneLoader] Parsing dotScene file with version " + version; - if (XMLRoot.attribute("sceneManager")) - message += ", scene manager " + String(XMLRoot.attribute("sceneManager").value()); - if (XMLRoot.attribute("minOgreVersion")) - message += ", min. Ogre version " + String(XMLRoot.attribute("minOgreVersion").value()); - if (XMLRoot.attribute("author")) - message += ", author " + String(XMLRoot.attribute("author").value()); - - LogManager::getSingleton().logMessage(message); - - // Process environment (?) - if (auto pElement = XMLRoot.child("environment")) - processEnvironment(pElement); - - // Process nodes (?) - if (auto pElement = XMLRoot.child("nodes")) - processNodes(pElement); - - // Process externals (?) - if (auto pElement = XMLRoot.child("externals")) - processExternals(pElement); - - // Process userDataReference (?) - if (auto pElement = XMLRoot.child("userData")) - processUserData(pElement, mAttachNode->getUserObjectBindings()); - - // Process light (?) - if (auto pElement = XMLRoot.child("light")) - processLight(pElement); - - // Process camera (?) - if (auto pElement = XMLRoot.child("camera")) - processCamera(pElement); - - // Process terrain (?) - if (auto pElement = XMLRoot.child("terrainGroup")) - processTerrainGroup(pElement); -} - -void DotSceneLoader::processNodes(pugi::xml_node& XMLNode) -{ - LogManager::getSingleton().logMessage("[DotSceneLoader] Processing Nodes...", LML_TRIVIAL); - - // Process node (*) - for (auto pElement : XMLNode.children("node")) - { - processNode(pElement); - } - - // Process position (?) - if (auto pElement = XMLNode.child("position")) - { - mAttachNode->setPosition(parseVector3(pElement)); - mAttachNode->setInitialState(); - } - - // Process rotation (?) - if (auto pElement = XMLNode.child("rotation")) - { - mAttachNode->setOrientation(parseQuaternion(pElement)); - mAttachNode->setInitialState(); - } - - // Process scale (?) - if (auto pElement = XMLNode.child("scale")) - { - mAttachNode->setScale(parseVector3(pElement)); - mAttachNode->setInitialState(); - } -} - -void DotSceneLoader::processExternals(pugi::xml_node& XMLNode) -{ - //! @todo Implement this -} - -void DotSceneLoader::processEnvironment(pugi::xml_node& XMLNode) -{ - LogManager::getSingleton().logMessage("[DotSceneLoader] Processing Environment...", LML_TRIVIAL); - - // Process camera (?) - if (auto pElement = XMLNode.child("camera")) - processCamera(pElement); - - // Process fog (?) - if (auto pElement = XMLNode.child("fog")) - processFog(pElement); - - // Process skyBox (?) - if (auto pElement = XMLNode.child("skyBox")) - processSkyBox(pElement); - - // Process skyDome (?) - if (auto pElement = XMLNode.child("skyDome")) - processSkyDome(pElement); - - // Process skyPlane (?) - if (auto pElement = XMLNode.child("skyPlane")) - processSkyPlane(pElement); - - // Process colourAmbient (?) - if (auto pElement = XMLNode.child("colourAmbient")) - mSceneMgr->setAmbientLight(parseColour(pElement)); - - // Process colourBackground (?) - if (auto pElement = XMLNode.child("colourBackground")) - mBackgroundColour = parseColour(pElement); -} - -void DotSceneLoader::processTerrainGroup(pugi::xml_node& XMLNode) -{ -#ifdef OGRE_BUILD_COMPONENT_TERRAIN - LogManager::getSingleton().logMessage("[DotSceneLoader] Processing Terrain Group...", LML_TRIVIAL); - - Real worldSize = getAttribReal(XMLNode, "worldSize"); - int mapSize = StringConverter::parseInt(XMLNode.attribute("size").value()); - int compositeMapDistance = StringConverter::parseInt(XMLNode.attribute("tuningCompositeMapDistance").value()); - int maxPixelError = StringConverter::parseInt(XMLNode.attribute("tuningMaxPixelError").value()); - - auto terrainGlobalOptions = TerrainGlobalOptions::getSingletonPtr(); - OgreAssert(terrainGlobalOptions, "TerrainGlobalOptions not available"); - - terrainGlobalOptions->setMaxPixelError((Real)maxPixelError); - terrainGlobalOptions->setCompositeMapDistance((Real)compositeMapDistance); - - auto terrainGroup = std::make_shared(mSceneMgr, Terrain::ALIGN_X_Z, mapSize, worldSize); - terrainGroup->setOrigin(Vector3::ZERO); - terrainGroup->setResourceGroup(m_sGroupName); - - // Process terrain pages (*) - for (auto pPageElement : XMLNode.children("terrain")) - { - int pageX = StringConverter::parseInt(pPageElement.attribute("x").value()); - int pageY = StringConverter::parseInt(pPageElement.attribute("y").value()); - - terrainGroup->defineTerrain(pageX, pageY, pPageElement.attribute("dataFile").value()); - } - terrainGroup->loadAllTerrains(true); - - terrainGroup->freeTemporaryResources(); - - mAttachNode->getUserObjectBindings().setUserAny("TerrainGroup", terrainGroup); -#else - OGRE_EXCEPT(Exception::ERR_INVALID_CALL, "recompile with Terrain component"); -#endif -} - -void DotSceneLoader::processLight(pugi::xml_node& XMLNode, SceneNode* pParent) -{ - // Process attributes - String name = getAttrib(XMLNode, "name"); - - LogManager::getSingleton().logMessage("[DotSceneLoader] Processing Light: " + name, LML_TRIVIAL); - - // Create the light - Light* pLight = mSceneMgr->createLight(name); - if (pParent) - pParent->attachObject(pLight); - - String sValue = getAttrib(XMLNode, "type"); - if (sValue == "point") - pLight->setType(Light::LT_POINT); - else if (sValue == "directional") - pLight->setType(Light::LT_DIRECTIONAL); - else if (sValue == "spot") - pLight->setType(Light::LT_SPOTLIGHT); - else if (sValue == "radPoint") - pLight->setType(Light::LT_POINT); - - pLight->setVisible(getAttribBool(XMLNode, "visible", true)); - pLight->setCastShadows(getAttribBool(XMLNode, "castShadows", true)); - pLight->setPowerScale(getAttribReal(XMLNode, "powerScale", 1.0)); - - // Process colourDiffuse (?) - if (auto pElement = XMLNode.child("colourDiffuse")) - pLight->setDiffuseColour(parseColour(pElement)); - - // Process colourSpecular (?) - if (auto pElement = XMLNode.child("colourSpecular")) - pLight->setSpecularColour(parseColour(pElement)); - - if (sValue != "directional") - { - // Process lightRange (?) - if (auto pElement = XMLNode.child("lightRange")) - processLightRange(pElement, pLight); - - // Process lightAttenuation (?) - if (auto pElement = XMLNode.child("lightAttenuation")) - processLightAttenuation(pElement, pLight); - } - // Process userDataReference (?) - if (auto pElement = XMLNode.child("userData")) - processUserData(pElement, pLight->getUserObjectBindings()); -} - -void DotSceneLoader::processCamera(pugi::xml_node& XMLNode, SceneNode* pParent) -{ - // Process attributes - String name = getAttrib(XMLNode, "name"); - - LogManager::getSingleton().logMessage("[DotSceneLoader] Processing Camera: " + name, LML_TRIVIAL); - - // Real fov = getAttribReal(XMLNode, "fov", 45); - Real aspectRatio = getAttribReal(XMLNode, "aspectRatio", 1.3333); - String projectionType = getAttrib(XMLNode, "projectionType", "perspective"); - - // Create the camera - Camera* pCamera = mSceneMgr->createCamera(name); - - // construct a scenenode is no parent - if (!pParent) - pParent = mAttachNode->createChildSceneNode(name); - - pParent->attachObject(pCamera); - - // Set the field-of-view - //! @todo Is this always in degrees? - // pCamera->setFOVy(Degree(fov)); - - // Set the aspect ratio - pCamera->setAspectRatio(aspectRatio); - - // Set the projection type - if (projectionType == "perspective") - pCamera->setProjectionType(PT_PERSPECTIVE); - else if (projectionType == "orthographic") - pCamera->setProjectionType(PT_ORTHOGRAPHIC); - - // Process clipping (?) - if (auto pElement = XMLNode.child("clipping")) - { - Real nearDist = getAttribReal(pElement, "near"); - pCamera->setNearClipDistance(nearDist); - - Real farDist = getAttribReal(pElement, "far"); - pCamera->setFarClipDistance(farDist); - } - - // Process userDataReference (?) - if (auto pElement = XMLNode.child("userData")) - processUserData(pElement, static_cast(pCamera)->getUserObjectBindings()); -} - -void DotSceneLoader::processNode(pugi::xml_node& XMLNode, SceneNode* pParent) -{ - // Construct the node's name - String name = getAttrib(XMLNode, "name"); - - LogManager::getSingleton().logMessage("[DotSceneLoader] Processing Node: " + name, LML_TRIVIAL); - - // Create the scene node - SceneNode* pNode; - if (name.empty()) - { - // Let Ogre choose the name - if (pParent) - pNode = pParent->createChildSceneNode(); - else - pNode = mAttachNode->createChildSceneNode(); - } - else - { - // Provide the name - if (pParent) - pNode = pParent->createChildSceneNode(name); - else - pNode = mAttachNode->createChildSceneNode(name); - } - - // Process other attributes - - // Process position (?) - if (auto pElement = XMLNode.child("position")) - { - pNode->setPosition(parseVector3(pElement)); - pNode->setInitialState(); - } - - // Process rotation (?) - if (auto pElement = XMLNode.child("rotation")) - { - pNode->setOrientation(parseQuaternion(pElement)); - pNode->setInitialState(); - } - - // Process scale (?) - if (auto pElement = XMLNode.child("scale")) - { - pNode->setScale(parseVector3(pElement)); - pNode->setInitialState(); - } - - // Process lookTarget (?) - if (auto pElement = XMLNode.child("lookTarget")) - processLookTarget(pElement, pNode); - - // Process trackTarget (?) - if (auto pElement = XMLNode.child("trackTarget")) - processTrackTarget(pElement, pNode); - - // Process node (*) - for (auto pElement : XMLNode.children("node")) - { - processNode(pElement, pNode); - } - - // Process entity (*) - for (auto pElement : XMLNode.children("entity")) - { - processEntity(pElement, pNode); - } - - // Process light (*) - for (auto pElement : XMLNode.children("light")) - { - processLight(pElement, pNode); - } - - // Process camera (*) - for (auto pElement : XMLNode.children("camera")) - { - processCamera(pElement, pNode); - } - - // Process particleSystem (*) - for (auto pElement : XMLNode.children("particleSystem")) - { - processParticleSystem(pElement, pNode); - } - - // Process billboardSet (*) - for (auto pElement : XMLNode.children("billboardSet")) - { - processBillboardSet(pElement, pNode); - } - - // Process plane (*) - for (auto pElement : XMLNode.children("plane")) - { - processPlane(pElement, pNode); - } - - // Process userDataReference (?) - if (auto pElement = XMLNode.child("userData")) - processUserData(pElement, pNode->getUserObjectBindings()); - - // Process node animations (?) - if (auto pElement = XMLNode.child("animations")) - processNodeAnimations(pElement, pNode); -} - -void DotSceneLoader::processLookTarget(pugi::xml_node& XMLNode, SceneNode* pParent) -{ - //! @todo Is this correct? Cause I don't have a clue actually - - // Process attributes - String nodeName = getAttrib(XMLNode, "nodeName"); - - LogManager::getSingleton().logMessage("[DotSceneLoader] Processing Look Target, nodeName: " + nodeName, LML_TRIVIAL); - - Node::TransformSpace relativeTo = Node::TS_PARENT; - String sValue = getAttrib(XMLNode, "relativeTo"); - if (sValue == "local") - relativeTo = Node::TS_LOCAL; - else if (sValue == "parent") - relativeTo = Node::TS_PARENT; - else if (sValue == "world") - relativeTo = Node::TS_WORLD; - - // Process position (?) - Vector3 position; - if (auto pElement = XMLNode.child("position")) - position = parseVector3(pElement); - - // Process localDirection (?) - Vector3 localDirection = Vector3::NEGATIVE_UNIT_Z; - if (auto pElement = XMLNode.child("localDirection")) - localDirection = parseVector3(pElement); - - // Setup the look target - try - { - if (!nodeName.empty()) - { - SceneNode* pLookNode = mSceneMgr->getSceneNode(nodeName); - position = pLookNode->_getDerivedPosition(); - } - - pParent->lookAt(position, relativeTo, localDirection); - } - catch (const Exception& e) - { - LogManager::getSingleton().logError("DotSceneLoader - " + e.getDescription()); - } -} - -void DotSceneLoader::processTrackTarget(pugi::xml_node& XMLNode, SceneNode* pParent) -{ - // Process attributes - String nodeName = getAttrib(XMLNode, "nodeName"); - - LogManager::getSingleton().logMessage("[DotSceneLoader] Processing Track Target, nodeName: " + nodeName, LML_TRIVIAL); - - // Process localDirection (?) - Vector3 localDirection = Vector3::NEGATIVE_UNIT_Z; - if (auto pElement = XMLNode.child("localDirection")) - localDirection = parseVector3(pElement); - - // Process offset (?) - Vector3 offset = Vector3::ZERO; - if (auto pElement = XMLNode.child("offset")) - offset = parseVector3(pElement); - - // Setup the track target - try - { - SceneNode* pTrackNode = mSceneMgr->getSceneNode(nodeName); - pParent->setAutoTracking(true, pTrackNode, localDirection, offset); - } - catch (const Exception& e) - { - LogManager::getSingleton().logError("DotSceneLoader - " + e.getDescription()); - } -} - -void DotSceneLoader::processEntity(pugi::xml_node& XMLNode, SceneNode* pParent) -{ - // Process attributes - String name = getAttrib(XMLNode, "name"); - - LogManager::getSingleton().logMessage("[DotSceneLoader] Processing Entity: " + name, LML_TRIVIAL); - - String meshFile = getAttrib(XMLNode, "meshFile"); - String staticGeometry = getAttrib(XMLNode, "static"); - String instancedManager = getAttrib(XMLNode, "instanced"); - String material = getAttrib(XMLNode, "material"); - bool castShadows = getAttribBool(XMLNode, "castShadows", true); - bool visible = getAttribBool(XMLNode, "visible", true); - - // Create the entity - MovableObject* pEntity = 0; - - try - { - // If the Entity is instanced then the creation path is different - if (!instancedManager.empty()) - { - LogManager::getSingleton().logMessage("[DotSceneLoader] Adding entity: " + name + " to Instance Manager: " + instancedManager, LML_TRIVIAL); - - // Load the Mesh to get the material name of the first submesh - Ogre::MeshPtr mesh = MeshManager::getSingletonPtr()->load(meshFile, m_sGroupName); - - // Get the material name of the entity - if(!material.empty()) - pEntity = mSceneMgr->createInstancedEntity(material, instancedManager); - else - pEntity = mSceneMgr->createInstancedEntity(mesh->getSubMesh(0)->getMaterialName(), instancedManager); - - pParent->attachObject(static_cast(pEntity)); - } - else - { - pEntity = mSceneMgr->createEntity(name, meshFile, m_sGroupName); - - static_cast(pEntity)->setCastShadows(castShadows); - static_cast(pEntity)->setVisible(visible); - - if (!material.empty()) - static_cast(pEntity)->setMaterialName(material); - - // If the Entity belongs to a Static Geometry group then it doesn't get attached to a node - // * TODO * : Clean up nodes without attached entities or children nodes? (should be done afterwards if the hierarchy is being processed) - if (!staticGeometry.empty()) - { - LogManager::getSingleton().logMessage("[DotSceneLoader] Adding entity: " + name + " to Static Group: " + staticGeometry, LML_TRIVIAL); - mSceneMgr->getStaticGeometry(staticGeometry)->addEntity(static_cast(pEntity), pParent->_getDerivedPosition(), pParent->_getDerivedOrientation(), pParent->_getDerivedScale()); - } - else - { - LogManager::getSingleton().logMessage("[DotSceneLoader] pParent->attachObject(): " + name, LML_TRIVIAL); - pParent->attachObject(static_cast(pEntity)); - } - } - } - catch (const Exception& e) - { - LogManager::getSingleton().logError("DotSceneLoader - " + e.getDescription()); - return; - } - - // Process userDataReference (?) - if (auto pElement = XMLNode.child("userData")) - processUserData(pElement, pEntity->getUserObjectBindings()); -} - -void DotSceneLoader::processParticleSystem(pugi::xml_node& XMLNode, SceneNode* pParent) -{ - // Process attributes - String name = getAttrib(XMLNode, "name"); - - LogManager::getSingleton().logMessage("[DotSceneLoader] Processing Particle System: " + name, LML_TRIVIAL); - - String templateName = getAttrib(XMLNode, "template"); - - if (templateName.empty()) - templateName = getAttrib(XMLNode, "file"); // compatibility with old scenes - - // Create the particle system - try - { - ParticleSystem* pParticles = mSceneMgr->createParticleSystem(name, templateName); - pParent->attachObject(pParticles); - } - catch (const Exception& e) - { - LogManager::getSingleton().logError("DotSceneLoader - " + e.getDescription()); - } -} - -void DotSceneLoader::processBillboardSet(pugi::xml_node& XMLNode, SceneNode* pParent) -{ - //! @todo Implement this -} - -void DotSceneLoader::processPlane(pugi::xml_node& XMLNode, SceneNode* pParent) -{ - String name = getAttrib(XMLNode, "name"); - - LogManager::getSingleton().logMessage("[DotSceneLoader] Processing Plane: " + name, LML_TRIVIAL); - - Real distance = getAttribReal(XMLNode, "distance"); - Real width = getAttribReal(XMLNode, "width"); - Real height = getAttribReal(XMLNode, "height"); - int xSegments = StringConverter::parseInt(getAttrib(XMLNode, "xSegments")); - int ySegments = StringConverter::parseInt(getAttrib(XMLNode, "ySegments")); - int numTexCoordSets = StringConverter::parseInt(getAttrib(XMLNode, "numTexCoordSets")); - Real uTile = getAttribReal(XMLNode, "uTile"); - Real vTile = getAttribReal(XMLNode, "vTile"); - String material = getAttrib(XMLNode, "material"); - bool hasNormals = getAttribBool(XMLNode, "hasNormals"); - Vector3 normal = parseVector3(XMLNode.child("normal")); - Vector3 up = parseVector3(XMLNode.child("upVector")); - - Plane plane(normal, distance); - MeshPtr res = - MeshManager::getSingletonPtr()->createPlane(name + "mesh", m_sGroupName, plane, width, height, xSegments, - ySegments, hasNormals, numTexCoordSets, uTile, vTile, up); - Entity* ent = mSceneMgr->createEntity(name, name + "mesh"); - - ent->setMaterialName(material); - - pParent->attachObject(ent); -} - -void DotSceneLoader::processFog(pugi::xml_node& XMLNode) -{ - LogManager::getSingleton().logMessage("[DotSceneLoader] Processing Fog...", LML_TRIVIAL); - - // Process attributes - Real expDensity = getAttribReal(XMLNode, "density", 0.001); - Real linearStart = getAttribReal(XMLNode, "start", 0.0); - Real linearEnd = getAttribReal(XMLNode, "end", 1.0); - - FogMode mode = FOG_NONE; - String sMode = getAttrib(XMLNode, "mode"); - if (sMode == "none") - mode = FOG_NONE; - else if (sMode == "exp") - mode = FOG_EXP; - else if (sMode == "exp2") - mode = FOG_EXP2; - else if (sMode == "linear") - mode = FOG_LINEAR; - else - mode = (FogMode)StringConverter::parseInt(sMode); - - // Process colourDiffuse (?) - ColourValue colourDiffuse = ColourValue::White; - - if (auto pElement = XMLNode.child("colour")) - colourDiffuse = parseColour(pElement); - - // Setup the fog - mSceneMgr->setFog(mode, colourDiffuse, expDensity, linearStart, linearEnd); -} - -void DotSceneLoader::processSkyBox(pugi::xml_node& XMLNode) -{ - LogManager::getSingleton().logMessage("[DotSceneLoader] Processing SkyBox...", LML_TRIVIAL); - - // Process attributes - String material = getAttrib(XMLNode, "material", "BaseWhite"); - Real distance = getAttribReal(XMLNode, "distance", 5000); - bool drawFirst = getAttribBool(XMLNode, "drawFirst", true); - bool active = getAttribBool(XMLNode, "active", false); - if (!active) - return; - - // Process rotation (?) - Quaternion rotation = Quaternion::IDENTITY; - - if (auto pElement = XMLNode.child("rotation")) - rotation = parseQuaternion(pElement); - - // Setup the sky box - mSceneMgr->setSkyBox(true, material, distance, drawFirst, rotation, m_sGroupName); -} - -void DotSceneLoader::processSkyDome(pugi::xml_node& XMLNode) -{ - LogManager::getSingleton().logMessage("[DotSceneLoader] Processing SkyDome...", LML_TRIVIAL); - - // Process attributes - String material = XMLNode.attribute("material").value(); - Real curvature = getAttribReal(XMLNode, "curvature", 10); - Real tiling = getAttribReal(XMLNode, "tiling", 8); - Real distance = getAttribReal(XMLNode, "distance", 4000); - bool drawFirst = getAttribBool(XMLNode, "drawFirst", true); - bool active = getAttribBool(XMLNode, "active", false); - if (!active) - return; - - // Process rotation (?) - Quaternion rotation = Quaternion::IDENTITY; - if (auto pElement = XMLNode.child("rotation")) - rotation = parseQuaternion(pElement); - - // Setup the sky dome - mSceneMgr->setSkyDome(true, material, curvature, tiling, distance, drawFirst, rotation, 16, 16, -1, m_sGroupName); -} - -void DotSceneLoader::processSkyPlane(pugi::xml_node& XMLNode) -{ - LogManager::getSingleton().logMessage("[DotSceneLoader] Processing SkyPlane...", LML_TRIVIAL); - - // Process attributes - String material = getAttrib(XMLNode, "material"); - Real planeX = getAttribReal(XMLNode, "planeX", 0); - Real planeY = getAttribReal(XMLNode, "planeY", -1); - Real planeZ = getAttribReal(XMLNode, "planeZ", 0); - Real planeD = getAttribReal(XMLNode, "planeD", 5000); - Real scale = getAttribReal(XMLNode, "scale", 1000); - Real bow = getAttribReal(XMLNode, "bow", 0); - Real tiling = getAttribReal(XMLNode, "tiling", 10); - bool drawFirst = getAttribBool(XMLNode, "drawFirst", true); - - // Setup the sky plane - Plane plane; - plane.normal = Vector3(planeX, planeY, planeZ); - plane.d = planeD; - mSceneMgr->setSkyPlane(true, plane, material, scale, tiling, drawFirst, bow, 1, 1, m_sGroupName); -} - -void DotSceneLoader::processLightRange(pugi::xml_node& XMLNode, Light* pLight) -{ - // Process attributes - Real inner = getAttribReal(XMLNode, "inner"); - Real outer = getAttribReal(XMLNode, "outer"); - Real falloff = getAttribReal(XMLNode, "falloff", 1.0); - - // Setup the light range - pLight->setSpotlightRange(Radian(inner), Radian(outer), falloff); -} - -void DotSceneLoader::processLightAttenuation(pugi::xml_node& XMLNode, Light* pLight) -{ - // Process attributes - Real range = getAttribReal(XMLNode, "range"); - Real constant = getAttribReal(XMLNode, "constant"); - Real linear = getAttribReal(XMLNode, "linear"); - Real quadratic = getAttribReal(XMLNode, "quadratic"); - - // Setup the light attenuation - pLight->setAttenuation(range, constant, linear, quadratic); -} - -void DotSceneLoader::processUserData(pugi::xml_node& XMLNode, UserObjectBindings& userData) -{ - // Process node (*) - for (auto pElement : XMLNode.children("property")) - { - String name = getAttrib(pElement, "name"); - String type = getAttrib(pElement, "type"); - String data = getAttrib(pElement, "data"); - - Any value; - if (type == "bool") - value = StringConverter::parseBool(data); - else if (type == "float") - value = StringConverter::parseReal(data); - else if (type == "int") - value = StringConverter::parseInt(data); - else - value = data; - - userData.setUserAny(name, value); - } -} - -void DotSceneLoader::processNodeAnimations(pugi::xml_node& XMLNode, SceneNode* pParent) -{ - LogManager::getSingleton().logMessage("[DotSceneLoader] Processing Node Animations for SceneNode: " + pParent->getName(), LML_TRIVIAL); - - // Process node animations (*) - for (auto pElement : XMLNode.children("animation")) - { - processNodeAnimation(pElement, pParent); - } -} - -void DotSceneLoader::processNodeAnimation(pugi::xml_node& XMLNode, SceneNode* pParent) -{ - // Process node animation (*) - - // Construct the animation name - String name = getAttrib(XMLNode, "name"); - - LogManager::getSingleton().logMessage("[DotSceneLoader] Processing Node Animation: " + name, LML_TRIVIAL); - - Real length = getAttribReal(XMLNode, "length"); - - Animation* anim = mSceneMgr->createAnimation(name, length); - - bool enable = getAttribBool(XMLNode, "enable", false); - bool loop = getAttribBool(XMLNode, "loop", false); - - String interpolationMode = getAttrib(XMLNode, "interpolationMode"); - - if (interpolationMode == "linear") - anim->setInterpolationMode(Animation::IM_LINEAR); - else if (interpolationMode == "spline") - anim->setInterpolationMode(Animation::IM_SPLINE); - else - LogManager::getSingleton().logError("DotSceneLoader - Invalid interpolationMode: " + interpolationMode); - - String rotationInterpolationMode = getAttrib(XMLNode, "rotationInterpolationMode"); - - if (rotationInterpolationMode == "linear") - anim->setRotationInterpolationMode(Animation::RIM_LINEAR); - else if (rotationInterpolationMode == "spherical") - anim->setRotationInterpolationMode(Animation::RIM_SPHERICAL); - else - LogManager::getSingleton().logError("DotSceneLoader - Invalid rotationInterpolationMode: " + rotationInterpolationMode); - - // create a track to animate the camera's node - NodeAnimationTrack* track = anim->createNodeTrack(0, pParent); - - // Process keyframes (*) - for (auto pElement : XMLNode.children("keyframe")) - { - processKeyframe(pElement, track); - } - - // create a new animation state to track this - auto animState = mSceneMgr->createAnimationState(name); - animState->setEnabled(enable); - animState->setLoop(loop); -} - -void DotSceneLoader::processKeyframe(pugi::xml_node& XMLNode, NodeAnimationTrack* pTrack) -{ - // Process node animation keyframe (*) - Real time = getAttribReal(XMLNode, "time"); - - LogManager::getSingleton().logMessage("[DotSceneLoader] Processing Keyframe: " + StringConverter::toString(time), LML_TRIVIAL); - - auto keyframe = pTrack->createNodeKeyFrame(time); - - // Process translation (?) - if (auto pElement = XMLNode.child("position")) { - Vector3 translation = parseVector3(pElement); - keyframe->setTranslate(translation); - } - - // Process rotation (?) - //Quaternion rotation = Quaternion::IDENTITY; - if (auto pElement = XMLNode.child("rotation")) { - Quaternion rotation = parseQuaternion(pElement); - keyframe->setRotation(rotation); - } - - // Process scale (?) - //Vector3 scale = parseVector3(XMLNode.child("scale")); - if (auto pElement = XMLNode.child("scale")) { - Vector3 scale = parseVector3(pElement); - keyframe->setScale(scale); - } -} - -void DotSceneLoader::exportScene(SceneNode* rootNode, const String& outFileName) -{ - pugi::xml_document XMLDoc; // character type defaults to char - auto comment = XMLDoc.append_child(pugi::node_comment); - comment.set_value(StringUtil::format(" exporter: Plugin_DotScene %d.%d.%d ", OGRE_VERSION_MAJOR, - OGRE_VERSION_MINOR, OGRE_VERSION_PATCH) - .c_str()); - auto scene = XMLDoc.append_child("scene"); - scene.append_attribute("formatVersion") = "1.1"; - scene.append_attribute("sceneManager") = rootNode->getCreator()->getTypeName().c_str(); - - auto nodes = scene.append_child("nodes"); - - for(auto c : rootNode->getChildren()) - writeNode(nodes, static_cast(c)); - - //writeNode(nodes, rootNode); - - XMLDoc.save_file(outFileName.c_str()); -} - -static void write(pugi::xml_node& node, const Vector3& v) -{ - node.append_attribute("x") = StringConverter::toString(v.x).c_str(); - node.append_attribute("y") = StringConverter::toString(v.y).c_str(); - node.append_attribute("z") = StringConverter::toString(v.z).c_str(); -} - -static void write(pugi::xml_node& node, const ColourValue& c) -{ - node.append_attribute("r") = StringConverter::toString(c.r).c_str(); - node.append_attribute("g") = StringConverter::toString(c.g).c_str(); - node.append_attribute("b") = StringConverter::toString(c.b).c_str(); - node.append_attribute("a") = StringConverter::toString(c.a).c_str(); -} - -void DotSceneLoader::writeNode(pugi::xml_node& parentXML, const SceneNode* n) -{ - auto nodeXML = parentXML.append_child("node"); - if(!n->getName().empty()) - nodeXML.append_attribute("name") = n->getName().c_str(); - - auto pos = nodeXML.append_child("position"); - write(pos, n->getPosition()); - - auto scale = nodeXML.append_child("scale"); - write(scale, n->getScale()); - - auto rot = nodeXML.append_child("rotation"); - rot.append_attribute("qw") = StringConverter::toString(n->getOrientation().w).c_str(); - rot.append_attribute("qx") = StringConverter::toString(n->getOrientation().x).c_str(); - rot.append_attribute("qy") = StringConverter::toString(n->getOrientation().y).c_str(); - rot.append_attribute("qz") = StringConverter::toString(n->getOrientation().z).c_str(); - - for(auto mo : n->getAttachedObjects()) - { - if(auto c = dynamic_cast(mo)) - { - auto camera = nodeXML.append_child("camera"); - camera.append_attribute("name") = c->getName().c_str(); - auto clipping = camera.append_child("clipping"); - clipping.append_attribute("near") = StringConverter::toString(c->getNearClipDistance()).c_str(); - clipping.append_attribute("far") = StringConverter::toString(c->getFarClipDistance()).c_str(); - continue; - } - - if (auto l = dynamic_cast(mo)) - { - auto light = nodeXML.append_child("light"); - light.append_attribute("name") = l->getName().c_str(); - light.append_attribute("castShadows") = StringConverter::toString(l->getCastShadows()).c_str(); - - if(!l->isVisible()) - light.append_attribute("visible") = "false"; - - auto diffuse = light.append_child("colourDiffuse"); - write(diffuse, l->getDiffuseColour()); - auto specular = light.append_child("colourSpecular"); - write(specular, l->getSpecularColour()); - switch (l->getType()) - { - case Light::LT_POINT: - light.append_attribute("type") = "point"; - break; - case Light::LT_DIRECTIONAL: - light.append_attribute("type") = "directional"; - break; - case Light::LT_SPOTLIGHT: - light.append_attribute("type") = "spot"; - break; - case Light::LT_RECTLIGHT: - light.append_attribute("type") = "rect"; - break; - } - - if(l->getType() != Light::LT_DIRECTIONAL) - { - auto range = light.append_child("lightRange"); - range.append_attribute("inner") = - StringConverter::toString(l->getSpotlightInnerAngle()).c_str(); - range.append_attribute("outer") = - StringConverter::toString(l->getSpotlightOuterAngle()).c_str(); - range.append_attribute("falloff") = - StringConverter::toString(l->getSpotlightFalloff()).c_str(); - auto atten = light.append_child("lightAttenuation"); - atten.append_attribute("range") = - StringConverter::toString(l->getAttenuationRange()).c_str(); - atten.append_attribute("constant") = - StringConverter::toString(l->getAttenuationConstant()).c_str(); - atten.append_attribute("linear") = - StringConverter::toString(l->getAttenuationLinear()).c_str(); - atten.append_attribute("quadratic") = - StringConverter::toString(l->getAttenuationQuadric()).c_str(); - } - - continue; - } - - if(auto e = dynamic_cast(mo)) - { - auto entity = nodeXML.append_child("entity"); - entity.append_attribute("name") = e->getName().c_str(); - entity.append_attribute("meshFile") = e->getMesh()->getName().c_str(); - - if(!e->isVisible()) - entity.append_attribute("visible") = "false"; - - // Heuristic: assume first submesh is representative - auto sub0mat = e->getSubEntity(0)->getMaterial(); - if(sub0mat != e->getMesh()->getSubMesh(0)->getMaterial()) - entity.append_attribute("material") = sub0mat->getName().c_str(); - continue; - } - - LogManager::getSingleton().logWarning("DotSceneLoader - unsupported MovableType " + - mo->getMovableType()); - } - - // recurse - for(auto c : n->getChildren()) - writeNode(nodeXML, static_cast(c)); -} - -const Ogre::String& DotScenePlugin::getName() const { - static Ogre::String name = "DotScene Loader"; - return name; -} - -void DotScenePlugin::initialise() { - mCodec = new DotSceneCodec(); - Codec::registerCodec(mCodec); -} - -void DotScenePlugin::shutdown() { - Codec::unregisterCodec(mCodec); - delete mCodec; -} - -#ifndef OGRE_STATIC_LIB - extern "C" _OgreDotScenePluginExport void dllStartPlugin(); - extern "C" _OgreDotScenePluginExport void dllStopPlugin(); - - static DotScenePlugin plugin; - - extern "C" _OgreDotScenePluginExport void dllStartPlugin() - { - Ogre::Root::getSingleton().installPlugin(&plugin); - } - extern "C" _OgreDotScenePluginExport void dllStopPlugin() - { - Ogre::Root::getSingleton().uninstallPlugin(&plugin); - } -#endif diff --git a/PlugIns/EXRCodec/CMakeLists.txt b/PlugIns/EXRCodec/CMakeLists.txt deleted file mode 100644 index e9c936a51ae..00000000000 --- a/PlugIns/EXRCodec/CMakeLists.txt +++ /dev/null @@ -1,26 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES ${PROJECT_BINARY_DIR}/include/OgreEXRCodecExports.h) -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") - -add_library(Codec_EXR ${OGRE_LIB_TYPE} ${HEADER_FILES} ${SOURCE_FILES}) -target_link_libraries(Codec_EXR OgreMain ${OPENEXR_LIBRARIES}) -target_include_directories(Codec_EXR PUBLIC - "$" - $) -target_include_directories(Codec_EXR SYSTEM PRIVATE "${OPENEXR_INCLUDE_DIR}/OpenEXR") - -ogre_config_framework(Codec_EXR) -ogre_config_plugin(Codec_EXR) -generate_export_header(Codec_EXR - EXPORT_MACRO_NAME _OgreEXRPluginExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreEXRCodecExports.h) -install(FILES ${HEADER_FILES} DESTINATION include/OGRE/Plugins/EXRCodec) diff --git a/PlugIns/EXRCodec/include/OgreEXRCodec.h b/PlugIns/EXRCodec/include/OgreEXRCodec.h deleted file mode 100644 index 7d4971316eb..00000000000 --- a/PlugIns/EXRCodec/include/OgreEXRCodec.h +++ /dev/null @@ -1,55 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _EXRImageCodec_H__ -#define _EXRImageCodec_H__ - -#include "OgreImageCodec.h" - -namespace Ogre { - /** \addtogroup Plugins Plugins - * @{ - */ - /** \defgroup EXRCodec EXRCodec - * %Codec specialized in loading high dynamic range .exr images using [OpenEXR](https://www.openexr.com/). - * @{ - */ - class EXRCodec : public ImageCodec - { - public: - EXRCodec(); - virtual ~EXRCodec(); - - void decode(const DataStreamPtr& input, const Any& output) const override; - String magicNumberToFileExt(const char* magicNumberPtr, size_t maxbytes) const override; - String getType() const override; - }; - /** @} */ - /** @} */ -} // namespace - -#endif diff --git a/PlugIns/EXRCodec/src/O_IStream.cpp b/PlugIns/EXRCodec/src/O_IStream.cpp deleted file mode 100644 index eba9ac74f74..00000000000 --- a/PlugIns/EXRCodec/src/O_IStream.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "O_IStream.h" -#include -using namespace Imf; - - -namespace Ogre { - -bool O_IStream::read(char c[], int n) { - size_t s = _stream.read(c, n); - if(s != size_t(n)) - throw Iex::InputExc ("Unexpected end of file."); - return _stream.eof(); -} - -uint64_t O_IStream::tellg() { - return _stream.getCurrentPtr() - _stream.getPtr(); -} - -void O_IStream::seekg(uint64_t pos) { - _stream.seek(pos); -} - -void O_IStream::clear() { - /* Clear error flags -- there are no error flags */ -} - - -}; diff --git a/PlugIns/EXRCodec/src/O_IStream.h b/PlugIns/EXRCodec/src/O_IStream.h deleted file mode 100644 index 202065ffa5c..00000000000 --- a/PlugIns/EXRCodec/src/O_IStream.h +++ /dev/null @@ -1,59 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _O_IStream_H__ -#define _O_IStream_H__ - -#include "OgreDataStream.h" -#include -#include - - -namespace Ogre { - -/** - * Adapter class for feeding OGRE data chunks as input to Imf. - */ -class O_IStream: public Imf::IStream -{ -public: - - O_IStream(MemoryDataStream& stream, const char file_name[]): - IStream (file_name), _stream(stream) {} - - bool read (char c[], int n) override; - uint64_t tellg () override; - void seekg (uint64_t pos) override; - void clear () override; - -private: - MemoryDataStream& _stream; -}; - -}; - -#endif diff --git a/PlugIns/EXRCodec/src/OgreEXRCodec.cpp b/PlugIns/EXRCodec/src/OgreEXRCodec.cpp deleted file mode 100644 index efd4b32de5a..00000000000 --- a/PlugIns/EXRCodec/src/OgreEXRCodec.cpp +++ /dev/null @@ -1,157 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreRoot.h" -#include "OgreLogManager.h" -#include "OgreImage.h" -#include "OgreException.h" -#include "OgreEXRCodecExports.h" - -#include "OgreEXRCodec.h" - -#include "O_IStream.h" - -#include -#include -#include -#include -#include -#include -#include - -using namespace Imath; -using namespace Imf; - -namespace Ogre { - -EXRCodec::EXRCodec() -{ - LogManager::getSingleton().logMessage("EXRCodec initialised"); -} -EXRCodec::~EXRCodec() -{ - LogManager::getSingleton().logMessage("EXRCodec deinitialised"); -} - -void EXRCodec::decode(const DataStreamPtr& input, const Any& output) const -{ - Image* image = any_cast(output); - - try { - // Make a mutable clone of input to be able to change file pointer - MemoryDataStream myIn(input); - - // Now we can simulate an OpenEXR file with that - O_IStream str(myIn, "SomeChunk.exr"); - InputFile file(str); - - Box2i dw = file.header().dataWindow(); - int width = dw.max.x - dw.min.x + 1; - int height = dw.max.y - dw.min.y + 1; - int components = 3; - - // Alpha channel present? - const ChannelList &channels = file.header().channels(); - if(channels.findChannel("A")) - components = 4; - - auto format = components==3 ? PF_FLOAT32_RGB : PF_FLOAT32_RGBA; - - // Allocate memory - image->create(format, width, height); - - // Construct frame buffer - uchar *pixels = image->getData(); - FrameBuffer frameBuffer; - frameBuffer.insert("R", // name - Slice (PixelType::FLOAT, // type - ((char *) pixels)+0, // base - 4 * components, // xStride - 4 * components * width)); // yStride - frameBuffer.insert("G", // name - Slice (PixelType::FLOAT, // type - ((char *) pixels)+4, // base - 4 * components, // xStride - 4 * components * width)); // yStride - frameBuffer.insert("B", // name - Slice (PixelType::FLOAT, // type - ((char *) pixels)+8, // base - 4 * components, // xStride - 4 * components * width)); // yStride - if(components==4) { - frameBuffer.insert("A", // name - Slice (PixelType::FLOAT, // type - ((char *) pixels)+12, // base - 4 * components, // xStride - 4 * components * width)); // yStride - } - - file.setFrameBuffer (frameBuffer); - file.readPixels (dw.min.y, dw.max.y); - } catch (const std::exception &exc) { - throw(Exception(Exception::ERR_INTERNAL_ERROR, - "OpenEXR Error", - exc.what())); - } -} - -String EXRCodec::getType() const -{ - return "exr"; -} - -String EXRCodec::magicNumberToFileExt(const char* magicNumberPtr, size_t maxbytes) const -{ - // look for OpenEXR magic number - if (maxbytes >= 4 - && magicNumberPtr[0] == 0x76 - && magicNumberPtr[1] == 0x2f - && magicNumberPtr[2] == 0x31 - && magicNumberPtr[3] == 0x01) - return "exr"; - - return ""; -} - -#ifndef OGRE_STATIC_LIB -static Codec *mEXRCodec; - -extern "C" _OgreEXRPluginExport void dllStartPlugin(); -extern "C" _OgreEXRPluginExport void dllStopPlugin(); - -extern "C" _OgreEXRPluginExport void dllStartPlugin() -{ - mEXRCodec = new EXRCodec; - Codec::registerCodec( mEXRCodec ); -} -extern "C" _OgreEXRPluginExport void dllStopPlugin() -{ - Codec::unregisterCodec( mEXRCodec ); - delete mEXRCodec; -} -#endif -} diff --git a/PlugIns/FreeImageCodec/CMakeLists.txt b/PlugIns/FreeImageCodec/CMakeLists.txt deleted file mode 100644 index 1721957cdc5..00000000000 --- a/PlugIns/FreeImageCodec/CMakeLists.txt +++ /dev/null @@ -1,32 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES ${PROJECT_BINARY_DIR}/include/OgreFreeImageCodecExports.h) -set(SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreFreeImageCodec.cpp") - -add_definitions(-DFREEIMAGE_LIB) -add_library(Codec_FreeImage ${OGRE_LIB_TYPE} ${HEADER_FILES} ${SOURCES}) -target_link_libraries(Codec_FreeImage PUBLIC OgreMain ${FreeImage_LIBRARIES}) -target_include_directories(Codec_FreeImage PUBLIC - "$" - $ - PRIVATE "${FreeImage_INCLUDE_DIR}") - -if (MINGW) - # may need winsock htons functions for FreeImage - target_link_libraries(Codec_FreeImage PRIVATE ws2_32) -endif () - -ogre_config_framework(Codec_FreeImage) -ogre_config_plugin(Codec_FreeImage) -generate_export_header(Codec_FreeImage - EXPORT_MACRO_NAME _OgreFreeImageCodecExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreFreeImageCodecExports.h) -install(FILES ${HEADER_FILES} DESTINATION include/OGRE/Plugins/FreeImageCodec) diff --git a/PlugIns/FreeImageCodec/include/OgreFreeImageCodec.h b/PlugIns/FreeImageCodec/include/OgreFreeImageCodec.h deleted file mode 100644 index f8db02e354e..00000000000 --- a/PlugIns/FreeImageCodec/include/OgreFreeImageCodec.h +++ /dev/null @@ -1,85 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _FreeImageCodec_H__ -#define _FreeImageCodec_H__ - -#include "OgreFreeImageCodecExports.h" - -#include "OgreImageCodec.h" -#include "OgrePlugin.h" - -// Forward-declaration to avoid external dependency on FreeImage -struct FIBITMAP; - -namespace Ogre { - - /** \addtogroup Plugins Plugins - * @{ - */ - /** \defgroup FreeImageCodec FreeImageCodec - * %Codec for loading generic image formats (e.g. jpg, png) using [FreeImage](https://freeimage.sourceforge.io/) - * - * This Codec is well-suited for files that are outside of your control. This merely wraps the original libraries, - * so all format variants are supported and security-vulnerabilities are mitigated. - * The downside that all external dependencies are required and there might be superfluous pixel conversions. - * @{ - */ - class FreeImageCodec : public ImageCodec - { - private: - String mType; - unsigned int mFreeImageType; - - typedef std::list RegisteredCodecList; - static RegisteredCodecList msCodecList; - - /** Common encoding routine. */ - FIBITMAP* encodeBitmap(Image* image) const; - - public: - FreeImageCodec(const String &type, unsigned int fiType); - virtual ~FreeImageCodec() { } - - DataStreamPtr encode(const Any& input) const override; - void encodeToFile(const Any& input, const String& outFileName) const override; - void decode(const DataStreamPtr& input, const Any& output) const override; - - String getType() const override; - String magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const override; - - /// Static method to startup FreeImage and register the FreeImage codecs - _OgreFreeImageCodecExport static void startup(void); - /// Static method to shutdown FreeImage and unregister the FreeImage codecs - _OgreFreeImageCodecExport static void shutdown(void); - }; - /** @} */ - /** @} */ - -} // namespace - -#endif diff --git a/PlugIns/FreeImageCodec/src/OgreFreeImageCodec.cpp b/PlugIns/FreeImageCodec/src/OgreFreeImageCodec.cpp deleted file mode 100644 index deb5cf358d0..00000000000 --- a/PlugIns/FreeImageCodec/src/OgreFreeImageCodec.cpp +++ /dev/null @@ -1,590 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreFreeImageCodec.h" - -#include - -#include "OgreLogManager.h" -#include "OgreDataStream.h" -#include "OgreImage.h" - -// freeimage 3.9.1~3.11.0 interoperability fix -#ifndef FREEIMAGE_COLORORDER -// we have freeimage 3.9.1, define these symbols in such way as 3.9.1 really work (do not use 3.11.0 definition, as color order was changed between these two versions on Apple systems) -#define FREEIMAGE_COLORORDER_BGR 0 -#define FREEIMAGE_COLORORDER_RGB 1 -#if defined(FREEIMAGE_BIGENDIAN) -#define FREEIMAGE_COLORORDER FREEIMAGE_COLORORDER_RGB -#else -#define FREEIMAGE_COLORORDER FREEIMAGE_COLORORDER_BGR -#endif -#endif - -namespace Ogre { - - FreeImageCodec::RegisteredCodecList FreeImageCodec::msCodecList; - //--------------------------------------------------------------------- - static void FreeImageLoadErrorHandler(FREE_IMAGE_FORMAT fif, const char *message) - { - // Callback method as required by FreeImage to report problems - const char* typeName = FreeImage_GetFormatFromFIF(fif); - if (typeName) - { - LogManager::getSingleton().stream() - << "FreeImage error: '" << message << "' when loading format " - << typeName; - } - else - { - LogManager::getSingleton().stream() - << "FreeImage error: '" << message << "'"; - } - - } - //--------------------------------------------------------------------- - void FreeImageCodec::startup(void) - { - FreeImage_Initialise(false); - - LogManager::getSingleton().logMessage( - LML_NORMAL, - "FreeImage version: " + String(FreeImage_GetVersion())); - LogManager::getSingleton().logMessage( - LML_NORMAL, - FreeImage_GetCopyrightMessage()); - - // Register codecs - StringStream strExt; - strExt << "Supported formats: "; - bool first = true; - for (int i = 0; i < FreeImage_GetFIFCount(); ++i) - { - - // Skip DDS codec since FreeImage does not have the option - // to keep DXT data compressed, we'll use our own codec - if ((FREE_IMAGE_FORMAT)i == FIF_DDS) - continue; - - String exts(FreeImage_GetFIFExtensionList((FREE_IMAGE_FORMAT)i)); - if (!first) - { - strExt << ","; - } - first = false; - strExt << exts; - - // Pull off individual formats (separated by comma by FI) - StringVector extsVector = StringUtil::split(exts, ","); - for (auto & v : extsVector) - { - // FreeImage 3.13 lists many formats twice: once under their own codec and - // once under the "RAW" codec, which is listed last. Avoid letting the RAW override - // the dedicated codec! - if (!Codec::isCodecRegistered(v)) - { - ImageCodec* codec = OGRE_NEW FreeImageCodec(v, i); - msCodecList.push_back(codec); - Codec::registerCodec(codec); - } - } - } - LogManager::getSingleton().logMessage( - LML_NORMAL, - strExt.str()); - - // Set error handler - FreeImage_SetOutputMessage(FreeImageLoadErrorHandler); - - - - - } - //--------------------------------------------------------------------- - void FreeImageCodec::shutdown(void) - { - FreeImage_DeInitialise(); - - for (auto & i : msCodecList) - { - Codec::unregisterCodec(i); - OGRE_DELETE i; - } - msCodecList.clear(); - - } - //--------------------------------------------------------------------- - FreeImageCodec::FreeImageCodec(const String &type, unsigned int fiType): - mType(type), - mFreeImageType(fiType) - { - } - //--------------------------------------------------------------------- - FIBITMAP* FreeImageCodec::encodeBitmap(Image* image) const - { - FIBITMAP* ret = 0; - - PixelBox src = image->getPixelBox(); - - // The required format, which will adjust to the format - // actually supported by FreeImage. - PixelFormat requiredFormat = image->getFormat(); - - // determine the settings - FREE_IMAGE_TYPE imageType; - PixelFormat determiningFormat = image->getFormat(); - - switch(determiningFormat) - { - case PF_R5G6B5: - case PF_B5G6R5: - case PF_R8G8B8: - case PF_B8G8R8: - case PF_A8R8G8B8: - case PF_X8R8G8B8: - case PF_A8B8G8R8: - case PF_X8B8G8R8: - case PF_B8G8R8A8: - case PF_R8G8B8A8: - case PF_BYTE_LA: - case PF_R3G3B2: - case PF_A4R4G4B4: - case PF_A1R5G5B5: - case PF_A2R10G10B10: - case PF_A2B10G10R10: - // I'd like to be able to use r/g/b masks to get FreeImage to load the data - // in it's existing format, but that doesn't work, FreeImage needs to have - // data in RGB[A] (big endian) and BGR[A] (little endian), always. - if (PixelUtil::hasAlpha(determiningFormat)) - { -#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_RGB - requiredFormat = PF_BYTE_RGBA; -#else - requiredFormat = PF_BYTE_BGRA; -#endif - } - else - { -#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_RGB - requiredFormat = PF_BYTE_RGB; -#else - requiredFormat = PF_BYTE_BGR; -#endif - } - // fall through - case PF_L8: - case PF_A8: - imageType = FIT_BITMAP; - break; - - case PF_L16: - imageType = FIT_UINT16; - break; - - case PF_SHORT_GR: - requiredFormat = PF_SHORT_RGB; - // fall through - case PF_SHORT_RGB: - imageType = FIT_RGB16; - break; - - case PF_SHORT_RGBA: - imageType = FIT_RGBA16; - break; - - case PF_FLOAT16_R: - requiredFormat = PF_FLOAT32_R; - // fall through - case PF_FLOAT32_R: - imageType = FIT_FLOAT; - break; - - case PF_FLOAT16_GR: - case PF_FLOAT16_RGB: - case PF_FLOAT32_GR: - requiredFormat = PF_FLOAT32_RGB; - // fall through - case PF_FLOAT32_RGB: - imageType = FIT_RGBF; - break; - - case PF_FLOAT16_RGBA: - requiredFormat = PF_FLOAT32_RGBA; - // fall through - case PF_FLOAT32_RGBA: - imageType = FIT_RGBAF; - break; - - default: - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Invalid image format", "FreeImageCodec::encode"); - }; - - // Check support for this image type & bit depth - if (!FreeImage_FIFSupportsExportType((FREE_IMAGE_FORMAT)mFreeImageType, imageType) || - !FreeImage_FIFSupportsExportBPP((FREE_IMAGE_FORMAT)mFreeImageType, (int)PixelUtil::getNumElemBits(requiredFormat))) - { - // Ok, need to allocate a fallback - // Only deal with RGBA -> RGB for now - switch (requiredFormat) - { - case PF_BYTE_RGBA: - requiredFormat = PF_BYTE_RGB; - break; - case PF_BYTE_BGRA: - requiredFormat = PF_BYTE_BGR; - break; - default: - break; - }; - - } - - bool conversionRequired = false; - - unsigned char* srcData = image->getData(); - - // Check BPP - unsigned bpp = static_cast(PixelUtil::getNumElemBits(requiredFormat)); - if (!FreeImage_FIFSupportsExportBPP((FREE_IMAGE_FORMAT)mFreeImageType, (int)bpp)) - { - if (bpp == 32 && image->getHasAlpha() && FreeImage_FIFSupportsExportBPP((FREE_IMAGE_FORMAT)mFreeImageType, 24)) - { - // drop to 24 bit (lose alpha) -#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_RGB - requiredFormat = PF_BYTE_RGB; -#else - requiredFormat = PF_BYTE_BGR; -#endif - bpp = 24; - } - else if (bpp == 128 && image->getHasAlpha() && FreeImage_FIFSupportsExportBPP((FREE_IMAGE_FORMAT)mFreeImageType, 96)) - { - // drop to 96-bit floating point - requiredFormat = PF_FLOAT32_RGB; - } - } - - PixelBox convBox(image->getPixelBox(), requiredFormat); - if (requiredFormat != image->getFormat()) - { - conversionRequired = true; - // Allocate memory - convBox.data = OGRE_ALLOC_T(uchar, convBox.getConsecutiveSize(), MEMCATEGORY_GENERAL); - // perform conversion and reassign source - PixelBox newSrc = image->getPixelBox(); - PixelUtil::bulkPixelConversion(newSrc, convBox); - srcData = convBox.data; - } - - - ret = FreeImage_AllocateT( - imageType, - static_cast(image->getWidth()), - static_cast(image->getHeight()), - bpp); - - if (!ret) - { - if (conversionRequired) - OGRE_FREE(convBox.data, MEMCATEGORY_GENERAL); - - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "FreeImage_AllocateT failed - possibly out of memory. "); - } - - if (requiredFormat == PF_L8 || requiredFormat == PF_A8) - { - // Must explicitly tell FreeImage that this is greyscale by setting - // a "grey" palette (otherwise it will save as a normal RGB - // palettized image). - FIBITMAP *tmp = FreeImage_ConvertToGreyscale(ret); - FreeImage_Unload(ret); - ret = tmp; - } - - size_t dstPitch = FreeImage_GetPitch(ret); - size_t srcPitch = image->getWidth() * PixelUtil::getNumElemBytes(requiredFormat); - - - // Copy data, invert scanlines and respect FreeImage pitch - uchar* pDst = FreeImage_GetBits(ret); - for (size_t y = 0; y < image->getHeight(); ++y) - { - uchar* pSrc = srcData + (image->getHeight() - y - 1) * srcPitch; - memcpy(pDst, pSrc, srcPitch); - pDst += dstPitch; - } - - if (conversionRequired) - { - // delete temporary conversion area - OGRE_FREE(convBox.data, MEMCATEGORY_GENERAL); - } - - return ret; - } - //--------------------------------------------------------------------- - DataStreamPtr FreeImageCodec::encode(const Any& input) const - { - FIBITMAP* fiBitmap = encodeBitmap(any_cast(input)); - - // open memory chunk allocated by FreeImage - FIMEMORY* mem = FreeImage_OpenMemory(); - // write data into memory - FreeImage_SaveToMemory((FREE_IMAGE_FORMAT)mFreeImageType, fiBitmap, mem); - // Grab data information - BYTE* data; - DWORD size; - FreeImage_AcquireMemory(mem, &data, &size); - // Copy data into our own buffer - // Because we're asking MemoryDataStream to free this, must create in a compatible way - BYTE* ourData = OGRE_ALLOC_T(BYTE, size, MEMCATEGORY_GENERAL); - memcpy(ourData, data, size); - // Wrap data in stream, tell it to free on close - DataStreamPtr outstream(OGRE_NEW MemoryDataStream(ourData, size, true)); - // Now free FreeImage memory buffers - FreeImage_CloseMemory(mem); - // Unload bitmap - FreeImage_Unload(fiBitmap); - - return outstream; - - - } - //--------------------------------------------------------------------- - void FreeImageCodec::encodeToFile(const Any& input, const String& outFileName) const - { - FIBITMAP* fiBitmap = encodeBitmap(any_cast(input)); - - FreeImage_Save((FREE_IMAGE_FORMAT)mFreeImageType, fiBitmap, outFileName.c_str()); - FreeImage_Unload(fiBitmap); - } - //--------------------------------------------------------------------- - void FreeImageCodec::decode(const DataStreamPtr& input, const Any& output) const - { - Image* image = any_cast(output); - - // Buffer stream into memory (TODO: override IO functions instead?) - MemoryDataStream memStream(input, true); - - FIMEMORY* fiMem = - FreeImage_OpenMemory(memStream.getPtr(), static_cast(memStream.size())); - - FIBITMAP* fiBitmap = FreeImage_LoadFromMemory( - (FREE_IMAGE_FORMAT)mFreeImageType, fiMem); - if (!fiBitmap) - { - FreeImage_CloseMemory(fiMem); - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Error decoding image", - "FreeImageCodec::decode"); - } - - // Must derive format first, this may perform conversions - PixelFormat format = PF_UNKNOWN; - - FREE_IMAGE_TYPE imageType = FreeImage_GetImageType(fiBitmap); - FREE_IMAGE_COLOR_TYPE colourType = FreeImage_GetColorType(fiBitmap); - unsigned bpp = FreeImage_GetBPP(fiBitmap); - - switch(imageType) - { - case FIT_UNKNOWN: - case FIT_COMPLEX: - case FIT_UINT32: - case FIT_INT32: - case FIT_DOUBLE: - default: - FreeImage_CloseMemory(fiMem); - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Unknown or unsupported image format", - "FreeImageCodec::decode"); - - break; - case FIT_BITMAP: - // Standard image type - // Perform any colour conversions for greyscale - if (colourType == FIC_MINISWHITE || colourType == FIC_MINISBLACK) - { - FIBITMAP* newBitmap = FreeImage_ConvertToGreyscale(fiBitmap); - // free old bitmap and replace - FreeImage_Unload(fiBitmap); - fiBitmap = newBitmap; - // get new formats - bpp = FreeImage_GetBPP(fiBitmap); - } - // Perform any colour conversions for RGB - else if (bpp < 8 || colourType == FIC_PALETTE || colourType == FIC_CMYK) - { - FIBITMAP* newBitmap = NULL; - if (FreeImage_IsTransparent(fiBitmap)) - { - // convert to 32 bit to preserve the transparency - // (the alpha byte will be 0 if pixel is transparent) - newBitmap = FreeImage_ConvertTo32Bits(fiBitmap); - } - else - { - // no transparency - only 3 bytes are needed - newBitmap = FreeImage_ConvertTo24Bits(fiBitmap); - } - - // free old bitmap and replace - FreeImage_Unload(fiBitmap); - fiBitmap = newBitmap; - // get new formats - bpp = FreeImage_GetBPP(fiBitmap); - } - - // by this stage, 8-bit is greyscale, 16/24/32 bit are RGB[A] - switch(bpp) - { - case 8: - format = PF_L8; - break; - case 16: - // Determine 555 or 565 from green mask - // cannot be 16-bit greyscale since that's FIT_UINT16 - if(FreeImage_GetGreenMask(fiBitmap) == FI16_565_GREEN_MASK) - { - format = PF_R5G6B5; - } - else - { - // FreeImage doesn't support 4444 format so must be 1555 - format = PF_A1R5G5B5; - } - break; - case 24: - // FreeImage differs per platform - // PF_BYTE_BGR[A] for little endian (== PF_ARGB native) - // PF_BYTE_RGB[A] for big endian (== PF_RGBA native) -#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_RGB - format = PF_BYTE_RGB; -#else - format = PF_BYTE_BGR; -#endif - break; - case 32: -#if FREEIMAGE_COLORORDER == FREEIMAGE_COLORORDER_RGB - format = PF_BYTE_RGBA; -#else - format = PF_BYTE_BGRA; -#endif - break; - - - }; - break; - case FIT_UINT16: - case FIT_INT16: - // 16-bit greyscale - format = PF_L16; - break; - case FIT_FLOAT: - // Single-component floating point data - format = PF_FLOAT32_R; - break; - case FIT_RGB16: - format = PF_SHORT_RGB; - break; - case FIT_RGBA16: - format = PF_SHORT_RGBA; - break; - case FIT_RGBF: - format = PF_FLOAT32_RGB; - break; - case FIT_RGBAF: - format = PF_FLOAT32_RGBA; - break; - - - }; - - unsigned char* srcData = FreeImage_GetBits(fiBitmap); - unsigned srcPitch = FreeImage_GetPitch(fiBitmap); - - // only 2D formats handled by this codec - // no mipmaps in non-DDS - image->create(format, FreeImage_GetWidth(fiBitmap), FreeImage_GetHeight(fiBitmap)); - - // Final data - invert image and trim pitch at the same time - size_t dstPitch = image->getRowSpan(); - - uchar* pDst = image->getData(); - for (size_t y = 0; y < image->getHeight(); ++y) - { - uchar* pSrc = srcData + (image->getHeight() - y - 1) * srcPitch; - memcpy(pDst, pSrc, dstPitch); - pDst += dstPitch; - } - - - FreeImage_Unload(fiBitmap); - FreeImage_CloseMemory(fiMem); - } - //--------------------------------------------------------------------- - String FreeImageCodec::getType() const - { - return mType; - } - //--------------------------------------------------------------------- - String FreeImageCodec::magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const - { - FIMEMORY* fiMem = - FreeImage_OpenMemory((BYTE*)const_cast(magicNumberPtr), static_cast(maxbytes)); - - FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(fiMem, (int)maxbytes); - FreeImage_CloseMemory(fiMem); - - if (fif != FIF_UNKNOWN) - { - String ext(FreeImage_GetFormatFromFIF(fif)); - StringUtil::toLowerCase(ext); - return ext; - } - else - { - return BLANKSTRING; - } - } - -#ifndef OGRE_STATIC_LIB - extern "C" void _OgreFreeImageCodecExport dllStartPlugin(); - extern "C" void _OgreFreeImageCodecExport dllStopPlugin(); - - extern "C" void _OgreFreeImageCodecExport dllStartPlugin() - { - FreeImageCodec::startup(); - } - extern "C" void _OgreFreeImageCodecExport dllStopPlugin() - { - FreeImageCodec::shutdown(); - } -#endif -} diff --git a/PlugIns/GLSLang/CMakeLists.txt b/PlugIns/GLSLang/CMakeLists.txt deleted file mode 100644 index 49665ad0d5f..00000000000 --- a/PlugIns/GLSLang/CMakeLists.txt +++ /dev/null @@ -1,34 +0,0 @@ -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES ${PROJECT_BINARY_DIR}/include/OgreGLSLangProgramManagerExports.h) - -add_library(Plugin_GLSLangProgramManager ${OGRE_LIB_TYPE} ${HEADER_FILES} src/OgreGLSLang.cpp) -target_include_directories(Plugin_GLSLangProgramManager PUBLIC - "$" - $) - -if(ANDROID) - target_include_directories(Plugin_GLSLangProgramManager SYSTEM PRIVATE - ${ANDROID_NDK}/sources/third_party/shaderc/third_party/glslang - ${ANDROID_NDK}/sources/third_party/shaderc/third_party/) - target_link_libraries(Plugin_GLSLangProgramManager PUBLIC OgreMain - ${ANDROID_NDK}/sources/third_party/shaderc/libs/c++_static/${ANDROID_ABI}/libshaderc.a) -elseif(DEFINED ENV{VULKAN_SDK}) - message(STATUS "Using VULKAN_SDK: $ENV{VULKAN_SDK}") - target_include_directories(Plugin_GLSLangProgramManager SYSTEM PRIVATE $ENV{VULKAN_SDK}/include) - target_link_directories(Plugin_GLSLangProgramManager PUBLIC $ENV{VULKAN_SDK}/lib) - target_link_libraries(Plugin_GLSLangProgramManager PUBLIC OgreMain shaderc_combined) -else() - set(GLSLANG_LIBS glslang HLSL OSDependent OGLCompiler SPIRV SPIRV-Tools-opt SPIRV-Tools) - find_library(GLSLANG_MI MachineIndependent) - if(GLSLANG_MI) - set(GLSLANG_LIBS ${GLSLANG_MI} ${GLSLANG_LIBS}) - endif() - target_link_libraries(Plugin_GLSLangProgramManager PUBLIC OgreMain ${GLSLANG_LIBS}) -endif() - -ogre_config_framework(Plugin_GLSLangProgramManager) -ogre_config_plugin(Plugin_GLSLangProgramManager) -generate_export_header(Plugin_GLSLangProgramManager - EXPORT_MACRO_NAME _OgreGLSLangProgramManagerExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreGLSLangProgramManagerExports.h) -install(FILES ${HEADER_FILES} DESTINATION include/OGRE/Plugins/GLSLang) \ No newline at end of file diff --git a/PlugIns/GLSLang/include/OgreGLSLangProgramManager.h b/PlugIns/GLSLang/include/OgreGLSLangProgramManager.h deleted file mode 100644 index f344c3de432..00000000000 --- a/PlugIns/GLSLang/include/OgreGLSLangProgramManager.h +++ /dev/null @@ -1,80 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#ifndef __GLSLangProgram_H__ -#define __GLSLangProgram_H__ - -#include -#include "OgreHighLevelGpuProgram.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgrePlugin.h" - -namespace Ogre -{ -/** \addtogroup Plugins - * @{ - */ -/** \defgroup GLSLangProgramManager GLSLangProgramManager - * GLslang can be used to compile common, high-level GLSL/ HLSL code down to SPIRV assembler - * language for both GL and Vulkan. - * @{ - */ -/** Specialisation of HighLevelGpuProgram to provide support for the GLSLang compiler by Khronos. - - The program will negotiate with the renderer to compile the appropriate program - for the API and graphics card capabilities. -*/ -class GLSLangProgram : public HighLevelGpuProgram -{ - void createLowLevelImpl() override; - void unloadHighLevelImpl() override; - void loadFromSource() override; - void buildConstantDefinitions() override; - void prepareImpl() override; - - std::vector mAssembly; -public: - GLSLangProgram(ResourceManager* creator, const String& name, ResourceHandle handle, const String& group, - bool isManual, ManualResourceLoader* loader); - ~GLSLangProgram(); - const String& getLanguage(void) const override; - - bool isSupported() const override; -}; - -/** Factory class for GLSLang programs. */ -class GLSLangProgramFactory : public HighLevelGpuProgramFactory -{ -public: - GLSLangProgramFactory(); - ~GLSLangProgramFactory(); - /// Get the name of the language this factory creates programs for - const String& getLanguage(void) const override; - GpuProgram* create(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) override; -}; - -/** Plugin instance for Cg Program Manager */ -class _OgreGLSLangProgramManagerExport GLSLangPlugin : public Plugin -{ -public: - const String& getName() const override; - - void install() override; - - void initialise() override; - - void shutdown() override; - - void uninstall() override; - -protected: - std::unique_ptr mProgramFactory; -}; -/** @} */ -/** @} */ -} // namespace Ogre - -#endif diff --git a/PlugIns/GLSLang/src/OgreGLSLang.cpp b/PlugIns/GLSLang/src/OgreGLSLang.cpp deleted file mode 100644 index 8e3449c7879..00000000000 --- a/PlugIns/GLSLang/src/OgreGLSLang.cpp +++ /dev/null @@ -1,497 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#include "OgreGLSLangProgramManager.h" -#include "OgreRoot.h" - -#include "OgreLogManager.h" - -#include -#include -#include "gl_types.h" - -namespace -{ -TBuiltInResource DefaultTBuiltInResource = { - /* .MaxLights = */ 32, - /* .MaxClipPlanes = */ 6, - /* .MaxTextureUnits = */ 32, - /* .MaxTextureCoords = */ 32, - /* .MaxVertexAttribs = */ 64, - /* .MaxVertexUniformComponents = */ 4096, - /* .MaxVaryingFloats = */ 64, - /* .MaxVertexTextureImageUnits = */ 32, - /* .MaxCombinedTextureImageUnits = */ 80, - /* .MaxTextureImageUnits = */ 32, - /* .MaxFragmentUniformComponents = */ 4096, - /* .MaxDrawBuffers = */ 32, - /* .MaxVertexUniformVectors = */ 128, - /* .MaxVaryingVectors = */ 8, - /* .MaxFragmentUniformVectors = */ 16, - /* .MaxVertexOutputVectors = */ 16, - /* .MaxFragmentInputVectors = */ 15, - /* .MinProgramTexelOffset = */ -8, - /* .MaxProgramTexelOffset = */ 7, - /* .MaxClipDistances = */ 8, - /* .MaxComputeWorkGroupCountX = */ 65535, - /* .MaxComputeWorkGroupCountY = */ 65535, - /* .MaxComputeWorkGroupCountZ = */ 65535, - /* .MaxComputeWorkGroupSizeX = */ 1024, - /* .MaxComputeWorkGroupSizeY = */ 1024, - /* .MaxComputeWorkGroupSizeZ = */ 64, - /* .MaxComputeUniformComponents = */ 1024, - /* .MaxComputeTextureImageUnits = */ 16, - /* .MaxComputeImageUniforms = */ 8, - /* .MaxComputeAtomicCounters = */ 8, - /* .MaxComputeAtomicCounterBuffers = */ 1, - /* .MaxVaryingComponents = */ 60, - /* .MaxVertexOutputComponents = */ 64, - /* .MaxGeometryInputComponents = */ 64, - /* .MaxGeometryOutputComponents = */ 128, - /* .MaxFragmentInputComponents = */ 128, - /* .MaxImageUnits = */ 8, - /* .MaxCombinedImageUnitsAndFragmentOutputs = */ 8, - /* .MaxCombinedShaderOutputResources = */ 8, - /* .MaxImageSamples = */ 0, - /* .MaxVertexImageUniforms = */ 0, - /* .MaxTessControlImageUniforms = */ 0, - /* .MaxTessEvaluationImageUniforms = */ 0, - /* .MaxGeometryImageUniforms = */ 0, - /* .MaxFragmentImageUniforms = */ 8, - /* .MaxCombinedImageUniforms = */ 8, - /* .MaxGeometryTextureImageUnits = */ 16, - /* .MaxGeometryOutputVertices = */ 256, - /* .MaxGeometryTotalOutputComponents = */ 1024, - /* .MaxGeometryUniformComponents = */ 1024, - /* .MaxGeometryVaryingComponents = */ 64, - /* .MaxTessControlInputComponents = */ 128, - /* .MaxTessControlOutputComponents = */ 128, - /* .MaxTessControlTextureImageUnits = */ 16, - /* .MaxTessControlUniformComponents = */ 1024, - /* .MaxTessControlTotalOutputComponents = */ 4096, - /* .MaxTessEvaluationInputComponents = */ 128, - /* .MaxTessEvaluationOutputComponents = */ 128, - /* .MaxTessEvaluationTextureImageUnits = */ 16, - /* .MaxTessEvaluationUniformComponents = */ 1024, - /* .MaxTessPatchComponents = */ 120, - /* .MaxPatchVertices = */ 32, - /* .MaxTessGenLevel = */ 64, - /* .MaxViewports = */ 16, - /* .MaxVertexAtomicCounters = */ 0, - /* .MaxTessControlAtomicCounters = */ 0, - /* .MaxTessEvaluationAtomicCounters = */ 0, - /* .MaxGeometryAtomicCounters = */ 0, - /* .MaxFragmentAtomicCounters = */ 8, - /* .MaxCombinedAtomicCounters = */ 8, - /* .MaxAtomicCounterBindings = */ 1, - /* .MaxVertexAtomicCounterBuffers = */ 0, - /* .MaxTessControlAtomicCounterBuffers = */ 0, - /* .MaxTessEvaluationAtomicCounterBuffers = */ 0, - /* .MaxGeometryAtomicCounterBuffers = */ 0, - /* .MaxFragmentAtomicCounterBuffers = */ 1, - /* .MaxCombinedAtomicCounterBuffers = */ 1, - /* .MaxAtomicCounterBufferSize = */ 16384, - /* .MaxTransformFeedbackBuffers = */ 4, - /* .MaxTransformFeedbackInterleavedComponents = */ 64, - /* .MaxCullDistances = */ 8, - /* .MaxCombinedClipAndCullDistances = */ 8, - /* .MaxSamples = */ 4, - /* .maxMeshOutputVerticesNV = */ 256, - /* .maxMeshOutputPrimitivesNV = */ 512, - /* .maxMeshWorkGroupSizeX_NV = */ 32, - /* .maxMeshWorkGroupSizeY_NV = */ 1, - /* .maxMeshWorkGroupSizeZ_NV = */ 1, - /* .maxTaskWorkGroupSizeX_NV = */ 32, - /* .maxTaskWorkGroupSizeY_NV = */ 1, - /* .maxTaskWorkGroupSizeZ_NV = */ 1, - /* .maxMeshViewCountNV = */ 4, - /* .maxDualSourceDrawBuffersEXT = 1,*/ - /* .limits = memset below*/ - }; -} - -namespace Ogre -{ -/// Convert GL uniform size and type to OGRE constant types -static GpuConstantType mapToGCT(int gltype) -{ - switch (gltype) - { - case GL_FLOAT: - return GCT_FLOAT1; - case GL_FLOAT_VEC2: - return GCT_FLOAT2; - case GL_FLOAT_VEC3: - return GCT_FLOAT3; - case GL_FLOAT_VEC4: - return GCT_FLOAT4; - case GL_IMAGE_1D: //TODO should be its own type? - case GL_SAMPLER_1D: - case GL_SAMPLER_1D_ARRAY: - case GL_INT_SAMPLER_1D: - case GL_INT_SAMPLER_1D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_1D: - case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: - // need to record samplers for GLSL - return GCT_SAMPLER1D; - case GL_IMAGE_2D: //TODO should be its own type? - case GL_IMAGE_2D_RECT: - case GL_SAMPLER_2D: - case GL_SAMPLER_2D_RECT: // TODO: Move these to a new type?? - case GL_INT_SAMPLER_2D_RECT: - case GL_UNSIGNED_INT_SAMPLER_2D_RECT: - case GL_SAMPLER_2D_ARRAY: - case GL_INT_SAMPLER_2D: - case GL_INT_SAMPLER_2D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D: - case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: - return GCT_SAMPLER2D; - case GL_IMAGE_3D: //TODO should be its own type? - case GL_SAMPLER_3D: - case GL_INT_SAMPLER_3D: - case GL_UNSIGNED_INT_SAMPLER_3D: - return GCT_SAMPLER3D; - case GL_SAMPLER_CUBE: - case GL_SAMPLER_CUBE_SHADOW: - case GL_INT_SAMPLER_CUBE: - case GL_UNSIGNED_INT_SAMPLER_CUBE: - return GCT_SAMPLERCUBE; - case GL_SAMPLER_1D_SHADOW: - case GL_SAMPLER_1D_ARRAY_SHADOW: - return GCT_SAMPLER1DSHADOW; - case GL_SAMPLER_2D_SHADOW: - case GL_SAMPLER_2D_RECT_SHADOW: - case GL_SAMPLER_2D_ARRAY_SHADOW: - return GCT_SAMPLER2DSHADOW; - case GL_INT: - return GCT_INT1; - case GL_INT_VEC2: - return GCT_INT2; - case GL_INT_VEC3: - return GCT_INT3; - case GL_INT_VEC4: - return GCT_INT4; - case GL_FLOAT_MAT2: - return GCT_MATRIX_2X2; - case GL_FLOAT_MAT3: - return GCT_MATRIX_3X3; - case GL_FLOAT_MAT4: - return GCT_MATRIX_4X4; - case GL_FLOAT_MAT2x3: - return GCT_MATRIX_2X3; - case GL_FLOAT_MAT3x2: - return GCT_MATRIX_3X2; - case GL_FLOAT_MAT2x4: - return GCT_MATRIX_2X4; - case GL_FLOAT_MAT4x2: - return GCT_MATRIX_4X2; - case GL_FLOAT_MAT3x4: - return GCT_MATRIX_3X4; - case GL_FLOAT_MAT4x3: - return GCT_MATRIX_4X3; - case GL_DOUBLE: - return GCT_DOUBLE1; - case GL_DOUBLE_VEC2: - return GCT_DOUBLE2; - case GL_DOUBLE_VEC3: - return GCT_DOUBLE3; - case GL_DOUBLE_VEC4: - return GCT_DOUBLE4; - case GL_DOUBLE_MAT2: - return GCT_MATRIX_DOUBLE_2X2; - case GL_DOUBLE_MAT3: - return GCT_MATRIX_DOUBLE_3X3; - case GL_DOUBLE_MAT4: - return GCT_MATRIX_DOUBLE_4X4; - case GL_DOUBLE_MAT2x3: - return GCT_MATRIX_DOUBLE_2X3; - case GL_DOUBLE_MAT3x2: - return GCT_MATRIX_DOUBLE_3X2; - case GL_DOUBLE_MAT2x4: - return GCT_MATRIX_DOUBLE_2X4; - case GL_DOUBLE_MAT4x2: - return GCT_MATRIX_DOUBLE_4X2; - case GL_DOUBLE_MAT3x4: - return GCT_MATRIX_DOUBLE_3X4; - case GL_DOUBLE_MAT4x3: - return GCT_MATRIX_DOUBLE_4X3; - case GL_UNSIGNED_INT: - case GL_UNSIGNED_INT_ATOMIC_COUNTER: //TODO should be its own type? - return GCT_UINT1; - case GL_UNSIGNED_INT_VEC2: - return GCT_UINT2; - case GL_UNSIGNED_INT_VEC3: - return GCT_UINT3; - case GL_UNSIGNED_INT_VEC4: - return GCT_UINT4; - case GL_BOOL: - return GCT_BOOL1; - case GL_BOOL_VEC2: - return GCT_BOOL2; - case GL_BOOL_VEC3: - return GCT_BOOL3; - case GL_BOOL_VEC4: - return GCT_BOOL4; - default: - return GCT_UNKNOWN; - } -} - -//----------------------------------------------------------------------- -static String sLanguageName = "glslang"; - -static EShLanguage getShLanguage(GpuProgramType type) -{ - switch (type) - { - // clang-format off - case GPT_VERTEX_PROGRAM: return EShLangVertex; - case GPT_FRAGMENT_PROGRAM: return EShLangFragment; - case GPT_GEOMETRY_PROGRAM: return EShLangGeometry; - case GPT_HULL_PROGRAM: return EShLangTessControl; - case GPT_DOMAIN_PROGRAM: return EShLangTessEvaluation; - case GPT_COMPUTE_PROGRAM: return EShLangCompute; - // clang-format on - } - - return EShLangFragment; -} - -GLSLangProgram::GLSLangProgram(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - : HighLevelGpuProgram(creator, name, handle, group, isManual, loader) -{ - if (createParamDictionary("glslangProgram")) - { - setupBaseParamDictionary(); - memset(&DefaultTBuiltInResource.limits, 1, sizeof(TLimits)); - } -} - -GLSLangProgram::~GLSLangProgram() -{ - unload(); -} - -const String& GLSLangProgram::getLanguage(void) const -{ - return sLanguageName; -} - -bool GLSLangProgram::isSupported() const -{ bool ret = !mCompileError; - if(mSyntaxCode != "glslang") // in case this is provided by user - ret = ret && GpuProgramManager::isSyntaxSupported(mSyntaxCode); - return ret; -} - -void GLSLangProgram::createLowLevelImpl() -{ - if (mCompileError) - return; - - mAssemblerProgram = - GpuProgramManager::getSingleton().createProgram(mName + "/Delegate", mGroup, mSyntaxCode, mType); - String assemblyStr((char*)mAssembly.data(), mAssembly.size() * sizeof(uint32)); - mAssemblerProgram->setSource(assemblyStr); - mAssembly.clear(); // delegate stores the data now -} -void GLSLangProgram::unloadHighLevelImpl() {} - -void GLSLangProgram::prepareImpl() -{ - HighLevelGpuProgram::prepareImpl(); - - if (mSyntaxCode == "glslang") - { - // find actual syntax code - for(auto lang : {"gl_spirv", "spirv"}) - { - if(GpuProgramManager::isSyntaxSupported(lang)) - { - mSyntaxCode = lang; - break; - } - } - } - - auto stage = getShLanguage(mType); - glslang::TShader shader(stage); - - String defines = appendBuiltinDefines(mPreprocessorDefines); - String preamble = "#extension GL_GOOGLE_cpp_style_line_directive: enable\n"; - - if(mSyntaxCode == "spirv") - preamble += "#define VULKAN 100\n"; - - for (auto def : parseDefines(defines)) - { - preamble += StringUtil::format("#define %s %s\n", def.first, def.second); - } - shader.setPreamble(preamble.c_str()); - - mSource = _resolveIncludes(mSource, this, mFilename, true); - const char* source = mSource.c_str(); - const char* name = mFilename.empty() ? NULL : mFilename.c_str(); - - shader.setStringsWithLengthsAndNames(&source, NULL, &name, 1); - shader.setEntryPoint("main"); - shader.setSourceEntryPoint(mEntryPoint.c_str()); - if(mSyntaxCode == "gl_spirv") - shader.setEnvClient(glslang::EShClientOpenGL, glslang::EShTargetOpenGL_450); - else if(mSyntaxCode == "spirv") - shader.setEnvClient(glslang::EShClientVulkan, glslang::EShTargetVulkan_1_0); - - // minimal version is 430 for explicit uniform location, but we use latest to get all features - if (!shader.parse(&DefaultTBuiltInResource, 460, false, EShMsgSpvRules)) - { - LogManager::getSingleton().logError("GLSLang compilation failed for " + mName + ":\n" + - shader.getInfoLog()); - mCompileError = true; - return; - } - - glslang::TProgram program; - program.addShader(&shader); - - if (!program.link(EShMsgSpvRules)) - { - LogManager::getSingleton().logError("GLSLang linking failed for " + mName + ":\n" + - program.getInfoLog()); - mCompileError = true; - return; - } - - auto intermediate = program.getIntermediate(stage); - glslang::SpvOptions opts; - glslang::GlslangToSpv(*intermediate, mAssembly, &opts); - - getConstantDefinitions(); - program.buildReflection(); - - int nuniforms = program.getNumLiveUniformVariables(); - int blockIdx = -1; - for(int i = 0; i < nuniforms; i++) - { - auto utype = program.getUniformTType(i); - if(utype->isOpaque()) - continue; - - blockIdx = program.getUniformBlockIndex(i); - auto isUBO = blockIdx != -1; - auto uoffset = program.getUniformBufferOffset(i); - - GpuConstantDefinition def; - def.logicalIndex = isUBO ? uoffset : utype->getQualifier().layoutLocation; - def.arraySize = program.getUniformArraySize(i); - def.physicalIndex = isUBO ? uoffset : mConstantDefs->bufferSize * 4; - def.constType = mapToGCT(program.getUniformType(i)); - bool doPadding = isUBO && GpuConstantDefinition::getElementSize(def.constType, false) > 1; - def.elementSize = GpuConstantDefinition::getElementSize(def.constType, doPadding); - - mConstantDefs->bufferSize += def.arraySize * def.elementSize; - mConstantDefs->map.emplace(program.getUniformName(i), def); - - if(!isUBO) - { - // also allow index based referencing - GpuLogicalIndexUse use; - use.physicalIndex = def.physicalIndex; - use.currentSize = def.arraySize * def.elementSize; - mLogicalToPhysical->map.emplace(def.logicalIndex, use); - } - } - - if (blockIdx != -1) - { - mConstantDefs->bufferSize = program.getUniformBlockSize(blockIdx) / 4; - mLogicalToPhysical.reset(); - } -} - -void GLSLangProgram::loadFromSource() {} -void GLSLangProgram::buildConstantDefinitions() {} - -//----------------------------------------------------------------------- -GLSLangProgramFactory::GLSLangProgramFactory() -{ - glslang::InitializeProcess(); -} -//----------------------------------------------------------------------- -GLSLangProgramFactory::~GLSLangProgramFactory() -{ - glslang::FinalizeProcess(); -} -//----------------------------------------------------------------------- -const String& GLSLangProgramFactory::getLanguage(void) const -{ - return sLanguageName; -} -//----------------------------------------------------------------------- -GpuProgram* GLSLangProgramFactory::create(ResourceManager* creator, const String& name, - ResourceHandle handle, const String& group, bool isManual, - ManualResourceLoader* loader) -{ - return OGRE_NEW GLSLangProgram(creator, name, handle, group, isManual, loader); -} -const String& GLSLangPlugin::getName() const -{ - static String sPluginName = "GLSLang Program Manager"; - return sPluginName; -} -//--------------------------------------------------------------------- -void GLSLangPlugin::install() {} -//--------------------------------------------------------------------- -void GLSLangPlugin::initialise() -{ - if (!GpuProgramManager::isSyntaxSupported("gl_spirv") && !GpuProgramManager::isSyntaxSupported("spirv")) - return; - - // Create new factory - mProgramFactory.reset(new GLSLangProgramFactory()); - - // Register - GpuProgramManager::getSingleton().addFactory(mProgramFactory.get()); -} -//--------------------------------------------------------------------- -void GLSLangPlugin::shutdown() -{ - // nothing to do -} -//--------------------------------------------------------------------- -void GLSLangPlugin::uninstall() -{ - if (mProgramFactory) - { - - // Remove from manager safely - if (GpuProgramManager::getSingletonPtr()) - GpuProgramManager::getSingleton().removeFactory(mProgramFactory.get()); - mProgramFactory.reset(); - } -} - -#ifndef OGRE_STATIC_LIB -extern "C" void _OgreGLSLangProgramManagerExport dllStartPlugin(void); -extern "C" void _OgreGLSLangProgramManagerExport dllStopPlugin(void); - -static Plugin* glslangPlugin; -//----------------------------------------------------------------------- -extern "C" void _OgreGLSLangProgramManagerExport dllStartPlugin(void) -{ - // Create new plugin - glslangPlugin = OGRE_NEW GLSLangPlugin(); - - // Register - Root::getSingleton().installPlugin(glslangPlugin); -} -extern "C" void _OgreGLSLangProgramManagerExport dllStopPlugin(void) -{ - Root::getSingleton().uninstallPlugin(glslangPlugin); - OGRE_DELETE glslangPlugin; -} -#endif - -} // namespace Ogre diff --git a/PlugIns/GLSLang/src/gl_types.h b/PlugIns/GLSLang/src/gl_types.h deleted file mode 100644 index b6f613bcedc..00000000000 --- a/PlugIns/GLSLang/src/gl_types.h +++ /dev/null @@ -1,210 +0,0 @@ -/* -** Copyright (c) 2013 The Khronos Group Inc. -** -** Permission is hereby granted, free of charge, to any person obtaining a -** copy of this software and/or associated documentation files (the -** "Materials"), to deal in the Materials without restriction, including -** without limitation the rights to use, copy, modify, merge, publish, -** distribute, sublicense, and/or sell copies of the Materials, and to -** permit persons to whom the Materials are furnished to do so, subject to -** the following conditions: -** -** The above copyright notice and this permission notice shall be included -** in all copies or substantial portions of the Materials. -** -** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. -*/ - -#pragma once - -#define GL_FLOAT 0x1406 -#define GL_FLOAT_VEC2 0x8B50 -#define GL_FLOAT_VEC3 0x8B51 -#define GL_FLOAT_VEC4 0x8B52 - -#define GL_DOUBLE 0x140A -#define GL_DOUBLE_VEC2 0x8FFC -#define GL_DOUBLE_VEC3 0x8FFD -#define GL_DOUBLE_VEC4 0x8FFE - -#define GL_INT 0x1404 -#define GL_INT_VEC2 0x8B53 -#define GL_INT_VEC3 0x8B54 -#define GL_INT_VEC4 0x8B55 - -#define GL_UNSIGNED_INT 0x1405 -#define GL_UNSIGNED_INT_VEC2 0x8DC6 -#define GL_UNSIGNED_INT_VEC3 0x8DC7 -#define GL_UNSIGNED_INT_VEC4 0x8DC8 - -#define GL_INT64_ARB 0x140E -#define GL_INT64_VEC2_ARB 0x8FE9 -#define GL_INT64_VEC3_ARB 0x8FEA -#define GL_INT64_VEC4_ARB 0x8FEB - -#define GL_UNSIGNED_INT64_ARB 0x140F -#define GL_UNSIGNED_INT64_VEC2_ARB 0x8FE5 -#define GL_UNSIGNED_INT64_VEC3_ARB 0x8FE6 -#define GL_UNSIGNED_INT64_VEC4_ARB 0x8FE7 - -#define GL_BOOL 0x8B56 -#define GL_BOOL_VEC2 0x8B57 -#define GL_BOOL_VEC3 0x8B58 -#define GL_BOOL_VEC4 0x8B59 - -#define GL_FLOAT_MAT2 0x8B5A -#define GL_FLOAT_MAT3 0x8B5B -#define GL_FLOAT_MAT4 0x8B5C -#define GL_FLOAT_MAT2x3 0x8B65 -#define GL_FLOAT_MAT2x4 0x8B66 -#define GL_FLOAT_MAT3x2 0x8B67 -#define GL_FLOAT_MAT3x4 0x8B68 -#define GL_FLOAT_MAT4x2 0x8B69 -#define GL_FLOAT_MAT4x3 0x8B6A - -#define GL_DOUBLE_MAT2 0x8F46 -#define GL_DOUBLE_MAT3 0x8F47 -#define GL_DOUBLE_MAT4 0x8F48 -#define GL_DOUBLE_MAT2x3 0x8F49 -#define GL_DOUBLE_MAT2x4 0x8F4A -#define GL_DOUBLE_MAT3x2 0x8F4B -#define GL_DOUBLE_MAT3x4 0x8F4C -#define GL_DOUBLE_MAT4x2 0x8F4D -#define GL_DOUBLE_MAT4x3 0x8F4E - -// Those constants are borrowed from extension NV_gpu_shader5 -#define GL_FLOAT16_NV 0x8FF8 -#define GL_FLOAT16_VEC2_NV 0x8FF9 -#define GL_FLOAT16_VEC3_NV 0x8FFA -#define GL_FLOAT16_VEC4_NV 0x8FFB - -#define GL_FLOAT16_MAT2_AMD 0x91C5 -#define GL_FLOAT16_MAT3_AMD 0x91C6 -#define GL_FLOAT16_MAT4_AMD 0x91C7 -#define GL_FLOAT16_MAT2x3_AMD 0x91C8 -#define GL_FLOAT16_MAT2x4_AMD 0x91C9 -#define GL_FLOAT16_MAT3x2_AMD 0x91CA -#define GL_FLOAT16_MAT3x4_AMD 0x91CB -#define GL_FLOAT16_MAT4x2_AMD 0x91CC -#define GL_FLOAT16_MAT4x3_AMD 0x91CD - -#define GL_SAMPLER_1D 0x8B5D -#define GL_SAMPLER_2D 0x8B5E -#define GL_SAMPLER_3D 0x8B5F -#define GL_SAMPLER_CUBE 0x8B60 -#define GL_SAMPLER_BUFFER 0x8DC2 -#define GL_SAMPLER_1D_ARRAY 0x8DC0 -#define GL_SAMPLER_2D_ARRAY 0x8DC1 -#define GL_SAMPLER_1D_ARRAY_SHADOW 0x8DC3 -#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 -#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 -#define GL_SAMPLER_1D_SHADOW 0x8B61 -#define GL_SAMPLER_2D_SHADOW 0x8B62 -#define GL_SAMPLER_2D_RECT 0x8B63 -#define GL_SAMPLER_2D_RECT_SHADOW 0x8B64 -#define GL_SAMPLER_2D_MULTISAMPLE 0x9108 -#define GL_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910B -#define GL_SAMPLER_CUBE_MAP_ARRAY 0x900C -#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW 0x900D -#define GL_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900C -#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_ARB 0x900D - -#define GL_FLOAT16_SAMPLER_1D_AMD 0x91CE -#define GL_FLOAT16_SAMPLER_2D_AMD 0x91CF -#define GL_FLOAT16_SAMPLER_3D_AMD 0x91D0 -#define GL_FLOAT16_SAMPLER_CUBE_AMD 0x91D1 -#define GL_FLOAT16_SAMPLER_2D_RECT_AMD 0x91D2 -#define GL_FLOAT16_SAMPLER_1D_ARRAY_AMD 0x91D3 -#define GL_FLOAT16_SAMPLER_2D_ARRAY_AMD 0x91D4 -#define GL_FLOAT16_SAMPLER_CUBE_MAP_ARRAY_AMD 0x91D5 -#define GL_FLOAT16_SAMPLER_BUFFER_AMD 0x91D6 -#define GL_FLOAT16_SAMPLER_2D_MULTISAMPLE_AMD 0x91D7 -#define GL_FLOAT16_SAMPLER_2D_MULTISAMPLE_ARRAY_AMD 0x91D8 - -#define GL_FLOAT16_SAMPLER_1D_SHADOW_AMD 0x91D9 -#define GL_FLOAT16_SAMPLER_2D_SHADOW_AMD 0x91DA -#define GL_FLOAT16_SAMPLER_2D_RECT_SHADOW_AMD 0x91DB -#define GL_FLOAT16_SAMPLER_1D_ARRAY_SHADOW_AMD 0x91DC -#define GL_FLOAT16_SAMPLER_2D_ARRAY_SHADOW_AMD 0x91DD -#define GL_FLOAT16_SAMPLER_CUBE_SHADOW_AMD 0x91DE -#define GL_FLOAT16_SAMPLER_CUBE_MAP_ARRAY_SHADOW_AMD 0x91DF - -#define GL_FLOAT16_IMAGE_1D_AMD 0x91E0 -#define GL_FLOAT16_IMAGE_2D_AMD 0x91E1 -#define GL_FLOAT16_IMAGE_3D_AMD 0x91E2 -#define GL_FLOAT16_IMAGE_2D_RECT_AMD 0x91E3 -#define GL_FLOAT16_IMAGE_CUBE_AMD 0x91E4 -#define GL_FLOAT16_IMAGE_1D_ARRAY_AMD 0x91E5 -#define GL_FLOAT16_IMAGE_2D_ARRAY_AMD 0x91E6 -#define GL_FLOAT16_IMAGE_CUBE_MAP_ARRAY_AMD 0x91E7 -#define GL_FLOAT16_IMAGE_BUFFER_AMD 0x91E8 -#define GL_FLOAT16_IMAGE_2D_MULTISAMPLE_AMD 0x91E9 -#define GL_FLOAT16_IMAGE_2D_MULTISAMPLE_ARRAY_AMD 0x91EA - -#define GL_INT_SAMPLER_1D 0x8DC9 -#define GL_INT_SAMPLER_2D 0x8DCA -#define GL_INT_SAMPLER_3D 0x8DCB -#define GL_INT_SAMPLER_CUBE 0x8DCC -#define GL_INT_SAMPLER_1D_ARRAY 0x8DCE -#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF -#define GL_INT_SAMPLER_2D_RECT 0x8DCD -#define GL_INT_SAMPLER_BUFFER 0x8DD0 -#define GL_INT_SAMPLER_2D_MULTISAMPLE 0x9109 -#define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910C -#define GL_INT_SAMPLER_CUBE_MAP_ARRAY 0x900E -#define GL_INT_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900E - -#define GL_UNSIGNED_INT_SAMPLER_1D 0x8DD1 -#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 -#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 -#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 -#define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY 0x8DD6 -#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 -#define GL_UNSIGNED_INT_SAMPLER_2D_RECT 0x8DD5 -#define GL_UNSIGNED_INT_SAMPLER_BUFFER 0x8DD8 -#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910D -#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY 0x900F -#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900F -#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A - -#define GL_IMAGE_1D 0x904C -#define GL_IMAGE_2D 0x904D -#define GL_IMAGE_3D 0x904E -#define GL_IMAGE_2D_RECT 0x904F -#define GL_IMAGE_CUBE 0x9050 -#define GL_IMAGE_BUFFER 0x9051 -#define GL_IMAGE_1D_ARRAY 0x9052 -#define GL_IMAGE_2D_ARRAY 0x9053 -#define GL_IMAGE_CUBE_MAP_ARRAY 0x9054 -#define GL_IMAGE_2D_MULTISAMPLE 0x9055 -#define GL_IMAGE_2D_MULTISAMPLE_ARRAY 0x9056 -#define GL_INT_IMAGE_1D 0x9057 -#define GL_INT_IMAGE_2D 0x9058 -#define GL_INT_IMAGE_3D 0x9059 -#define GL_INT_IMAGE_2D_RECT 0x905A -#define GL_INT_IMAGE_CUBE 0x905B -#define GL_INT_IMAGE_BUFFER 0x905C -#define GL_INT_IMAGE_1D_ARRAY 0x905D -#define GL_INT_IMAGE_2D_ARRAY 0x905E -#define GL_INT_IMAGE_CUBE_MAP_ARRAY 0x905F -#define GL_INT_IMAGE_2D_MULTISAMPLE 0x9060 -#define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x9061 -#define GL_UNSIGNED_INT_IMAGE_1D 0x9062 -#define GL_UNSIGNED_INT_IMAGE_2D 0x9063 -#define GL_UNSIGNED_INT_IMAGE_3D 0x9064 -#define GL_UNSIGNED_INT_IMAGE_2D_RECT 0x9065 -#define GL_UNSIGNED_INT_IMAGE_CUBE 0x9066 -#define GL_UNSIGNED_INT_IMAGE_BUFFER 0x9067 -#define GL_UNSIGNED_INT_IMAGE_1D_ARRAY 0x9068 -#define GL_UNSIGNED_INT_IMAGE_2D_ARRAY 0x9069 -#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY 0x906A -#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE 0x906B -#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x906C - -#define GL_UNSIGNED_INT_ATOMIC_COUNTER 0x92DB diff --git a/PlugIns/OctreeSceneManager/CMakeLists.txt b/PlugIns/OctreeSceneManager/CMakeLists.txt deleted file mode 100644 index 5a207df6f60..00000000000 --- a/PlugIns/OctreeSceneManager/CMakeLists.txt +++ /dev/null @@ -1,28 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure Octree SceneManager build - -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES ${PROJECT_BINARY_DIR}/include/OgreOctreePrerequisites.h) -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") - -add_library(Plugin_OctreeSceneManager ${OGRE_LIB_TYPE} ${HEADER_FILES} ${SOURCE_FILES}) -target_link_libraries(Plugin_OctreeSceneManager OgreMain) -target_include_directories(Plugin_OctreeSceneManager PUBLIC - "$" - $) - -generate_export_header(Plugin_OctreeSceneManager - EXPORT_MACRO_NAME _OgreOctreePluginExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreOctreePrerequisites.h) - -ogre_config_framework(Plugin_OctreeSceneManager) -ogre_config_plugin(Plugin_OctreeSceneManager) -install(FILES ${HEADER_FILES} DESTINATION include/OGRE/Plugins/OctreeSceneManager) diff --git a/PlugIns/OctreeSceneManager/include/OgreOctree.h b/PlugIns/OctreeSceneManager/include/OgreOctree.h deleted file mode 100644 index 49221e28401..00000000000 --- a/PlugIns/OctreeSceneManager/include/OgreOctree.h +++ /dev/null @@ -1,168 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -/*************************************************************************** -octree.h - description -------------------- -begin : Mon Sep 30 2002 -copyright : (C) 2002 by Jon Anderson -email : janders@users.sf.net - -***************************************************************************/ - -#ifndef OCTREE_H -#define OCTREE_H - -#include "OgreAxisAlignedBox.h" - -#include - -namespace Ogre -{ -/** \addtogroup Plugins Plugins -* @{ -*/ -/** \defgroup Octree OctreeSceneManager -* Octree datastructure for managing scene nodes. -* @{ -*/ -class OctreeNode; - -/** Octree datastructure for managing scene nodes. - -This is a loose octree implementation, meaning that each -octant child of the octree actually overlaps it's siblings by a factor -of .5. This guarantees that any thing that is half the size of the parent will -fit completely into a child, with no splitting necessary. -*/ - -class Octree : public NodeAlloc -{ -public: - Octree( Octree * p ); - ~Octree(); - - /** Adds an Octree scene node to this octree level. - - This is called by the OctreeSceneManager after - it has determined the correct Octree to insert the node into. - */ - void _addNode( OctreeNode * ); - - /** Removes an Octree scene node to this octree level. - */ - void _removeNode( OctreeNode * ); - - /** Returns the number of scene nodes attached to this octree - */ - int numNodes() - { - return mNumNodes; - }; - - /** The bounding box of the octree - - This is used for octant index determination and rendering, but not culling - */ - AxisAlignedBox mBox; - WireBoundingBox* mWireBoundingBox; - - /** Creates the wire frame bounding box for this octant - */ - WireBoundingBox* getWireBoundingBox(); - - /** Vector containing the dimensions of this octree / 2 - */ - Vector3 mHalfSize; - - /** 3D array of children of this octree. - - Children are dynamically created as needed when nodes are inserted in the Octree. - If, later, all the nodes are removed from the child, it is still kept around. - */ - Octree * mChildren[ 2 ][ 2 ][ 2 ]; - - /** Determines if this octree is twice as big as the given box. - - This method is used by the OctreeSceneManager to determine if the given - box will fit into a child of this octree. - */ - bool _isTwiceSize( const AxisAlignedBox &box ) const; - - /** Returns the appropriate indexes for the child of this octree into which the box will fit. - - This is used by the OctreeSceneManager to determine which child to traverse next when - finding the appropriate octree to insert the box. Since it is a loose octree, only the - center of the box is checked to determine the octant. - */ - void _getChildIndexes( const AxisAlignedBox &, int *x, int *y, int *z ) const; - - /** Creates the AxisAlignedBox used for culling this octree. - - Since it's a loose octree, the culling bounds can be different than the actual bounds of the octree. - */ - void _getCullBounds( AxisAlignedBox * ) const; - - - typedef std::vector< OctreeNode * > NodeList; - /** Public list of SceneNodes attached to this particular octree - */ - NodeList mNodes; - -protected: - - /** Increments the overall node count of this octree and all its parents - */ - inline void _ref() - { - mNumNodes++; - - if ( mParent != 0 ) mParent -> _ref(); - }; - - /** Decrements the overall node count of this octree and all its parents - */ - inline void _unref() - { - mNumNodes--; - - if ( mParent != 0 ) mParent -> _unref(); - }; - - ///number of SceneNodes in this octree and all its children. - int mNumNodes; - - ///parent octree - Octree * mParent; - -}; -/** @} */ -/** @} */ -} -#endif - - diff --git a/PlugIns/OctreeSceneManager/include/OgreOctreeCamera.h b/PlugIns/OctreeSceneManager/include/OgreOctreeCamera.h deleted file mode 100644 index c479161f84f..00000000000 --- a/PlugIns/OctreeSceneManager/include/OgreOctreeCamera.h +++ /dev/null @@ -1,90 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -/*************************************************************************** -octreecamera.h - description -------------------- -begin : Fri Sep 27 2002 -copyright : (C) 2002 by Jon Anderson -email : janders@users.sf.net - -***************************************************************************/ - -#ifndef OCTREECAMERA_H -#define OCTREECAMERA_H - -#include "OgreCamera.h" -#include "OgreOctreePrerequisites.h" - -/** -*@author Jon Anderson -*/ - -namespace Ogre -{ -/** \addtogroup Plugins Plugins -* @{ -*/ -/** \addtogroup Octree OctreeSceneManager -* Octree datastructure for managing scene nodes. -* @{ -*/ -/** Specialized viewpoint from which an Octree can be rendered. - -This class contains several specializations of the Ogre::Camera class. It -implements the getRenderOperation method in order to return displayable geometry -for debugging purposes. It also implements a visibility function that is more granular -than the default. -*/ - -class _OgreOctreePluginExport OctreeCamera : public Camera -{ -public: - - /** Visibility types */ - enum Visibility - { - NONE, - PARTIAL, - FULL - }; - - /* Standard constructor */ - OctreeCamera( const String& name, SceneManager* sm ); - /* Standard destructor */ - ~OctreeCamera(); - - /** Returns the visibility of the box - */ - OctreeCamera::Visibility getVisibility( const AxisAlignedBox &bound ); - -}; -/** @} */ -/** @} */ -} - -#endif diff --git a/PlugIns/OctreeSceneManager/include/OgreOctreeNode.h b/PlugIns/OctreeSceneManager/include/OgreOctreeNode.h deleted file mode 100644 index 2a584435b24..00000000000 --- a/PlugIns/OctreeSceneManager/include/OgreOctreeNode.h +++ /dev/null @@ -1,154 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -/*************************************************************************** -octreenode.h - description -------------------- -begin : Fri Sep 27 2002 -copyright : (C) 2002 by Jon Anderson -email : janders@users.sf.net - -***************************************************************************/ - -#ifndef OCTREENODE_H -#define OCTREENODE_H - -#include "OgreSceneNode.h" - -#include "OgreOctreePrerequisites.h" -#include "OgreOctree.h" - -namespace Ogre -{ -/** \addtogroup Plugins Plugins -* @{ -*/ -/** \addtogroup Octree OctreeSceneManager -* Octree datastructure for managing scene nodes. -* @{ -*/ -/** Specialized SceneNode that is customized for working within an Octree. Each node -* maintains its own bounding box, rather than merging it with all the children. -* -*/ - -class _OgreOctreePluginExport OctreeNode : public SceneNode -{ -public: - /** Standard constructor */ - OctreeNode( SceneManager* creator ); - /** Standard constructor */ - OctreeNode( SceneManager* creator, const String& name ); - /** Standard destructor */ - ~OctreeNode(); - - /** Overridden from Node to remove any reference to octants */ - Node * removeChild( unsigned short index ) override; - - /** Overridden from Node to remove any reference to octants */ - Node * removeChild( const String & name ) override; - - /** Overridden from Node to remove any reference to octants */ - Node * removeChild( Node* child) override; - - /** Overridden from Node to remove any reference to octants */ - void removeAllChildren(void) override; - - /** Returns the Octree in which this OctreeNode resides - */ - Octree * getOctant() - { - return mOctant; - }; - - /** Sets the Octree in which this OctreeNode resides - */ - void setOctant( Octree *o ) - { - mOctant = o; - }; - - /** Determines if the center of this node is within the given box - */ - bool _isIn( AxisAlignedBox &box ); - - /** Adds all the attached scenenodes to the render queue - */ - virtual void _addToRenderQueue( Camera* cam, RenderQueue * q, bool onlyShadowCasters, - VisibleObjectsBoundsInfo* visibleBounds); - - /** Sets up the LegacyRenderOperation for rendering this scene node as geometry. - - This will render the scenenode as a bounding box. - */ - virtual void getRenderOperation( RenderOperation& op ); - - /** Returns the local bounding box of this OctreeNode. - - This is used to render the bounding box, rather then the global. - */ - AxisAlignedBox & _getLocalAABB() - { - return mLocalAABB; - }; - - - - -protected: - - /** Internal method for updating the bounds for this OctreeNode. - - This method determines the bounds solely from the attached objects, not - any children. If the node has changed its bounds, it is removed from its - current octree, and reinserted into the tree. - */ - void _updateBounds( void ) override; - - void _removeNodeAndChildren( ); - - /// Local bounding box - AxisAlignedBox mLocalAABB; - - ///Octree this node is attached to. - Octree *mOctant; - - /// Preallocated corners for rendering - Real mCorners[ 24 ]; - /// Shared colors for rendering - static unsigned long mColors[ 8 ]; - /// Shared indexes for rendering - static unsigned short mIndexes[ 24 ]; - - -}; -/** @} */ -/** @} */ -} - - -#endif diff --git a/PlugIns/OctreeSceneManager/include/OgreOctreePlugin.h b/PlugIns/OctreeSceneManager/include/OgreOctreePlugin.h deleted file mode 100644 index d0a1ddc1017..00000000000 --- a/PlugIns/OctreeSceneManager/include/OgreOctreePlugin.h +++ /dev/null @@ -1,65 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OctreePlugin_H__ -#define __OctreePlugin_H__ - -#include "OgrePlugin.h" -#include "OgreOctreePrerequisites.h" - -namespace Ogre -{ - class OctreeSceneManagerFactory; - - /** Plugin instance for Octree Manager */ - class _OgreOctreePluginExport OctreePlugin : public Plugin - { - public: - OctreePlugin(); - - - /// @copydoc Plugin::getName - const String& getName() const override; - - /// @copydoc Plugin::install - void install() override; - - /// @copydoc Plugin::initialise - void initialise() override; - - /// @copydoc Plugin::shutdown - void shutdown() override; - - /// @copydoc Plugin::uninstall - void uninstall() override; - protected: - OctreeSceneManagerFactory* mOctreeSMFactory; - - }; -} - -#endif diff --git a/PlugIns/OctreeSceneManager/include/OgreOctreeSceneManager.h b/PlugIns/OctreeSceneManager/include/OgreOctreeSceneManager.h deleted file mode 100644 index 87fa5c23cf2..00000000000 --- a/PlugIns/OctreeSceneManager/include/OgreOctreeSceneManager.h +++ /dev/null @@ -1,229 +0,0 @@ -/*************************************************************************** -octreescenemanager.h - description -------------------- -begin : Fri Sep 27 2002 -copyright : (C) 2002 by Jon Anderson -email : janders@users.sf.net -***************************************************************************/ - -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef OCTREESCENEMANAGER_H -#define OCTREESCENEMANAGER_H - -#include "OgreOctreePrerequisites.h" -#include "OgreSceneManager.h" - -#include -#include - -#include "OgreOctree.h" - - -namespace Ogre -{ -/** \addtogroup Plugins Plugins -* @{ -*/ -/** \addtogroup Octree OctreeSceneManager -* Octree datastructure for managing scene nodes. -* @{ -*/ -class OctreeNode; -class OctreeCamera; - -typedef std::list< WireBoundingBox * > BoxList; -typedef std::list< unsigned long > ColorList; - -/** Specialized SceneManager that divides the geometry into an octree in order to facilitate spatial queries. -*/ - -class _OgreOctreePluginExport OctreeSceneManager : public SceneManager -{ - friend class OctreeIntersectionSceneQuery; - friend class OctreeRaySceneQuery; - friend class OctreeSphereSceneQuery; - friend class OctreeAxisAlignedBoxSceneQuery; - friend class OctreePlaneBoundedVolumeListSceneQuery; - -public: - static int intersect_call; - /** Standard Constructor. Initializes the octree to -10000,-10000,-10000 to 10000,10000,10000 with a depth of 8. */ - OctreeSceneManager(const String& name); - /** Standard Constructor */ - OctreeSceneManager(const String& name, AxisAlignedBox &box, int max_depth ); - /** Standard destructor */ - ~OctreeSceneManager(); - - /// @copydoc SceneManager::getTypeName - const String& getTypeName(void) const override; - - /** Initializes the manager to the given box and depth. - */ - void init( AxisAlignedBox &box, int d ); - - /** Creates a specialized OctreeNode */ - SceneNode * createSceneNodeImpl ( void ) override; - /** Creates a specialized OctreeNode */ - SceneNode * createSceneNodeImpl ( const String &name ) override; - /** Creates a specialized OctreeCamera */ - Camera * createCamera( const String &name ) override; - - /** Deletes a scene node */ - void destroySceneNode( const String &name ) override; - - - - /** Does nothing more */ - void _updateSceneGraph( Camera * cam ) override; - /** Recurses through the octree determining which nodes are visible. */ - void _findVisibleObjects ( Camera * cam, - VisibleObjectsBoundsInfo* visibleBounds, bool onlyShadowCasters ) override; - - /** Walks through the octree, adding any visible objects to the render queue. - - If any octant in the octree if completely within the view frustum, - all subchildren are automatically added with no visibility tests. - */ - void walkOctree( OctreeCamera *, RenderQueue *, Octree *, - VisibleObjectsBoundsInfo* visibleBounds, bool foundvisible, - bool onlyShadowCasters); - - /** Checks the given OctreeNode, and determines if it needs to be moved - * to a different octant. - */ - void _updateOctreeNode( OctreeNode * ); - /** Removes the given octree node */ - void _removeOctreeNode( OctreeNode * ); - /** Adds the Octree Node, starting at the given octree, and recursing at max to the specified depth. - */ - void _addOctreeNode( OctreeNode *, Octree *octree, int depth = 0 ); - - /** Recurses the octree, adding any nodes intersecting with the box into the given list. - It ignores the exclude scene node. - */ - void findNodesIn( const AxisAlignedBox &box, std::list< SceneNode * > &list, SceneNode *exclude = 0 ); - - /** Recurses the octree, adding any nodes intersecting with the sphere into the given list. - It ignores the exclude scene node. - */ - void findNodesIn( const Sphere &sphere, std::list< SceneNode * > &list, SceneNode *exclude = 0 ); - - /** Recurses the octree, adding any nodes intersecting with the volume into the given list. - It ignores the exclude scene node. - */ - void findNodesIn( const PlaneBoundedVolume &volume, std::list< SceneNode * > &list, SceneNode *exclude=0 ); - - /** Recurses the octree, adding any nodes intersecting with the ray into the given list. - It ignores the exclude scene node. - */ - void findNodesIn( const Ray &ray, std::list< SceneNode * > &list, SceneNode *exclude=0 ); - - /** Sets the box visibility flag */ - void setShowBoxes( bool b ) - { - mShowBoxes = b; - }; - - /** Resizes the octree to the given size */ - void resize( const AxisAlignedBox &box ); - - /** Sets the given option for the SceneManager - - Options are: - "Size", AxisAlignedBox *; - "Depth", int *; - "ShowOctree", bool *; - */ - - bool setOption( const String &, const void * ) override; - /** Gets the given option for the Scene Manager. - - See setOption - */ - bool getOption( const String &, void * ) override; - - bool getOptionValues( const String & key, StringVector &refValueList ) override; - bool getOptionKeys( StringVector &refKeys ) override; - /** Overridden from SceneManager */ - void clearScene(void) override; - - AxisAlignedBoxSceneQuery* createAABBQuery(const AxisAlignedBox& box, uint32 mask) override; - SphereSceneQuery* createSphereQuery(const Sphere& sphere, uint32 mask) override; - PlaneBoundedVolumeListSceneQuery* createPlaneBoundedVolumeQuery(const PlaneBoundedVolumeList& volumes, uint32 mask) override; - RaySceneQuery* createRayQuery(const Ray& ray, uint32 mask) override; - IntersectionSceneQuery* createIntersectionQuery(uint32 mask) override; - -protected: - - - Octree::NodeList mVisible; - - /// The root octree - Octree *mOctree; - - /// List of boxes to be rendered - BoxList mBoxes; - - /// Number of rendered objs - int mNumObjects; - - /// Max depth for the tree - int mMaxDepth; - /// Size of the octree - AxisAlignedBox mBox; - - /// Boxes visibility flag - bool mShowBoxes; - - Real mCorners[ 24 ]; - static unsigned long mColors[ 8 ]; - static unsigned short mIndexes[ 24 ]; - - Matrix4 mScaleFactor; - -}; - -/// Factory for OctreeSceneManager -class OctreeSceneManagerFactory : public SceneManagerFactory -{ -public: - /// Factory type name - static const String FACTORY_TYPE_NAME; - SceneManager* createInstance(const String& instanceName) override; - const String& getTypeName(void) const override { return FACTORY_TYPE_NAME; } -}; - - -/** @} */ -/** @} */ -} - -#endif - diff --git a/PlugIns/OctreeSceneManager/include/OgreOctreeSceneQuery.h b/PlugIns/OctreeSceneManager/include/OgreOctreeSceneQuery.h deleted file mode 100644 index 8d953547f82..00000000000 --- a/PlugIns/OctreeSceneManager/include/OgreOctreeSceneQuery.h +++ /dev/null @@ -1,105 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -/*************************************************************************** -OgreOctreeSceneQuery.h - description -------------------- -begin : Tues July 20, 2004 -copyright : (C) 2004 by Jon Anderson -email : janders@users.sf.net -***************************************************************************/ - -#ifndef OCTREESCENEQUERY_H -#define OCTREESCENEQUERY_H - -#include "OgreOctreePrerequisites.h" -#include "OgreSceneManager.h" - - -namespace Ogre -{ -/** \addtogroup Plugins Plugins -* @{ -*/ -/** \addtogroup Octree OctreeSceneManager -* Octree datastructure for managing scene nodes. -* @{ -*/ -/** Octree implementation of IntersectionSceneQuery. */ -class _OgreOctreePluginExport OctreeIntersectionSceneQuery : public DefaultIntersectionSceneQuery -{ -public: - OctreeIntersectionSceneQuery(SceneManager* creator); - ~OctreeIntersectionSceneQuery(); - - void execute(IntersectionSceneQueryListener* listener) override; -}; - -/** Octree implementation of RaySceneQuery. */ -class _OgreOctreePluginExport OctreeRaySceneQuery : public DefaultRaySceneQuery -{ -public: - OctreeRaySceneQuery(SceneManager* creator); - ~OctreeRaySceneQuery(); - - void execute(RaySceneQueryListener* listener) override; -}; -/** Octree implementation of SphereSceneQuery. */ -class _OgreOctreePluginExport OctreeSphereSceneQuery : public DefaultSphereSceneQuery -{ -public: - OctreeSphereSceneQuery(SceneManager* creator); - ~OctreeSphereSceneQuery(); - - void execute(SceneQueryListener* listener) override; -}; -/** Octree implementation of PlaneBoundedVolumeListSceneQuery. */ -class _OgreOctreePluginExport OctreePlaneBoundedVolumeListSceneQuery : public DefaultPlaneBoundedVolumeListSceneQuery -{ -public: - OctreePlaneBoundedVolumeListSceneQuery(SceneManager* creator); - ~OctreePlaneBoundedVolumeListSceneQuery(); - - void execute(SceneQueryListener* listener) override; -}; -/** Octree implementation of AxisAlignedBoxSceneQuery. */ -class _OgreOctreePluginExport OctreeAxisAlignedBoxSceneQuery : public DefaultAxisAlignedBoxSceneQuery -{ -public: - OctreeAxisAlignedBoxSceneQuery(SceneManager* creator); - ~OctreeAxisAlignedBoxSceneQuery(); - - void execute(SceneQueryListener* listener) override; -}; - -/** @} */ -/** @} */ -} - -#endif - - diff --git a/PlugIns/OctreeSceneManager/src/OgreOctree.cpp b/PlugIns/OctreeSceneManager/src/OgreOctree.cpp deleted file mode 100644 index 14527d9622d..00000000000 --- a/PlugIns/OctreeSceneManager/src/OgreOctree.cpp +++ /dev/null @@ -1,160 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -/*************************************************************************** -octree.cpp - description -------------------- -begin : Mon Sep 30 2002 -copyright : (C) 2002 by Jon Anderson -email : janders@users.sf.net - -***************************************************************************/ - -#include "OgreOctree.h" -#include "OgreOctreeNode.h" -#include "OgreWireBoundingBox.h" - -namespace Ogre -{ - -/** Returns true is the box will fit in a child. -*/ -bool Octree::_isTwiceSize( const AxisAlignedBox &box ) const -{ - // infinite boxes never fit in a child - always root node - if (box.isInfinite()) - return false; - - Vector3 halfMBoxSize = mBox.getHalfSize(); - Vector3 boxSize = box.getSize(); - return ((boxSize.x <= halfMBoxSize.x) && (boxSize.y <= halfMBoxSize.y) && (boxSize.z <= halfMBoxSize.z)); - -} - -/** It's assumed the the given box has already been proven to fit into -* a child. Since it's a loose octree, only the centers need to be -* compared to find the appropriate node. -*/ -void Octree::_getChildIndexes( const AxisAlignedBox &box, int *x, int *y, int *z ) const -{ - Vector3 center = mBox.getMaximum().midPoint( mBox.getMinimum() ); - - Vector3 ncenter = box.getMaximum().midPoint( box.getMinimum() ); - - if ( ncenter.x > center.x ) - * x = 1; - else - *x = 0; - - if ( ncenter.y > center.y ) - * y = 1; - else - *y = 0; - - if ( ncenter.z > center.z ) - * z = 1; - else - *z = 0; - -} - -Octree::Octree( Octree * parent ) - : mWireBoundingBox(0), - mHalfSize( 0, 0, 0 ) -{ - //initialize all children to null. - for ( int i = 0; i < 2; i++ ) - { - for ( int j = 0; j < 2; j++ ) - { - for ( int k = 0; k < 2; k++ ) - { - mChildren[ i ][ j ][ k ] = 0; - } - } - } - - mParent = parent; - mNumNodes = 0; -} - -Octree::~Octree() -{ - //initialize all children to null. - for ( int i = 0; i < 2; i++ ) - { - for ( int j = 0; j < 2; j++ ) - { - for ( int k = 0; k < 2; k++ ) - { - if ( mChildren[ i ][ j ][ k ] != 0 ) - OGRE_DELETE mChildren[ i ][ j ][ k ]; - } - } - } - - if(mWireBoundingBox) - OGRE_DELETE mWireBoundingBox; - - mParent = 0; -} - -void Octree::_addNode( OctreeNode * n ) -{ - mNodes.push_back( n ); - n -> setOctant( this ); - - //update total counts. - _ref(); - -} - -void Octree::_removeNode( OctreeNode * n ) -{ - mNodes.erase( std::find( mNodes.begin(), mNodes.end(), n ) ); - n -> setOctant( 0 ); - - //update total counts. - _unref(); -} - -void Octree::_getCullBounds( AxisAlignedBox *b ) const -{ - b -> setExtents( mBox.getMinimum() - mHalfSize, mBox.getMaximum() + mHalfSize ); -} - -WireBoundingBox* Octree::getWireBoundingBox() -{ - // Create a WireBoundingBox if needed - if(mWireBoundingBox == 0) - mWireBoundingBox = OGRE_NEW WireBoundingBox(); - - mWireBoundingBox->setupBoundingBox(mBox); - return mWireBoundingBox; -} - -} diff --git a/PlugIns/OctreeSceneManager/src/OgreOctreeCamera.cpp b/PlugIns/OctreeSceneManager/src/OgreOctreeCamera.cpp deleted file mode 100644 index 313d629ac4d..00000000000 --- a/PlugIns/OctreeSceneManager/src/OgreOctreeCamera.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -/*************************************************************************** -octreecamera.cpp - description -------------------- -begin : Fri Sep 27 2002 -copyright : (C) 2002 by Jon Anderson -email : janders@users.sf.net - -***************************************************************************/ -#include "OgreAxisAlignedBox.h" -#include "OgreOctreeCamera.h" - -namespace Ogre -{ -OctreeCamera::OctreeCamera( const String& name, SceneManager* sm ) : Camera( name, sm ) -{ - -} - -OctreeCamera::~OctreeCamera() -{ -} - -OctreeCamera::Visibility OctreeCamera::getVisibility( const AxisAlignedBox &bound ) -{ - - // Null boxes always invisible - if ( bound.isNull() ) - return NONE; - - // Get centre of the box - Vector3 centre = bound.getCenter(); - // Get the half-size of the box - Vector3 halfSize = bound.getHalfSize(); - - bool all_inside = true; - - for ( uchar plane = 0; plane < 6; ++plane ) - { - - // Skip far plane if infinite view frustum - if (plane == FRUSTUM_PLANE_FAR && mFarDist == 0) - continue; - - // This updates frustum planes and deals with cull frustum - Plane::Side side = getFrustumPlane(plane).getSide(centre, halfSize); - if(side == Plane::NEGATIVE_SIDE) return NONE; - // We can't return now as the box could be later on the negative side of a plane. - if(side == Plane::BOTH_SIDE) - all_inside = false; - } - - if ( all_inside ) - return FULL; - else - return PARTIAL; - -} - -} - - - - diff --git a/PlugIns/OctreeSceneManager/src/OgreOctreeNode.cpp b/PlugIns/OctreeSceneManager/src/OgreOctreeNode.cpp deleted file mode 100644 index c323f502c73..00000000000 --- a/PlugIns/OctreeSceneManager/src/OgreOctreeNode.cpp +++ /dev/null @@ -1,205 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -/*************************************************************************** -octreenode.cpp - description -------------------- -begin : Fri Sep 27 2002 -copyright : (C) 2002 by Jon Anderson -email : janders@users.sf.net - -***************************************************************************/ - -#include "OgreOctreeNode.h" -#include "OgreOctreeSceneManager.h" - -namespace Ogre -{ -unsigned long green = 0xFFFFFFFF; - -unsigned short OctreeNode::mIndexes[ 24 ] = {0, 1, 1, 2, 2, 3, 3, 0, //back - 0, 6, 6, 5, 5, 1, //left - 3, 7, 7, 4, 4, 2, //right - 6, 7, 5, 4 }; //front -unsigned long OctreeNode::mColors[ 8 ] = {green, green, green, green, green, green, green, green }; - -OctreeNode::OctreeNode( SceneManager* creator ) : SceneNode( creator ) -{ - mOctant = 0; -} - -OctreeNode::OctreeNode( SceneManager* creator, const String& name ) : SceneNode( creator, name ) -{ - mOctant = 0; -} - -OctreeNode::~OctreeNode() -{} -void OctreeNode::_removeNodeAndChildren( ) -{ - static_cast< OctreeSceneManager * > ( getCreator() ) -> _removeOctreeNode( this ); - //remove all the children nodes as well from the octree. - ChildNodeMap::iterator it = mChildren.begin(); - while( it != mChildren.end() ) - { - static_cast( *it ) -> _removeNodeAndChildren(); - ++it; - } -} -Node * OctreeNode::removeChild( unsigned short index ) -{ - OctreeNode *on = static_cast( SceneNode::removeChild( index ) ); - on -> _removeNodeAndChildren(); - return on; -} -Node * OctreeNode::removeChild( Node* child ) -{ - OctreeNode *on = static_cast( SceneNode::removeChild( child ) ); - on -> _removeNodeAndChildren(); - return on; -} -void OctreeNode::removeAllChildren() -{ - ChildNodeMap::iterator i, iend; - iend = mChildren.end(); - for (i = mChildren.begin(); i != iend; ++i) - { - OctreeNode* on = static_cast(*i); - on->setParent(0); - on->_removeNodeAndChildren(); - } - mChildren.clear(); - mChildrenToUpdate.clear(); - -} - -Node * OctreeNode::removeChild( const String & name ) -{ - OctreeNode *on = static_cast< OctreeNode * >( SceneNode::removeChild( name ) ); - on -> _removeNodeAndChildren( ); - return on; -} - -//same as SceneNode, only it doesn't care about children... -void OctreeNode::_updateBounds( void ) -{ - mWorldAABB.setNull(); - mLocalAABB.setNull(); - - // Update bounds from own attached objects - for ( auto o : getAttachedObjects() ) - { - // Get local bounds of object - mLocalAABB.merge( o->getBoundingBox() ); - mWorldAABB.merge( o->getWorldBoundingBox(true) ); - } - - - //update the OctreeSceneManager that things might have moved. - // if it hasn't been added to the octree, add it, and if has moved - // enough to leave it's current node, we'll update it. - if ( !_getWorldAABB().isNull() && isInSceneGraph() ) - { - static_cast < OctreeSceneManager * > ( getCreator() ) -> _updateOctreeNode( this ); - } - -} - -/** Since we are loose, only check the center. -*/ -bool OctreeNode::_isIn( AxisAlignedBox &box ) -{ - // Always fail if not in the scene graph or box is null - if (!isInSceneGraph() || box.isNull()) return false; - - // Always succeed if AABB is infinite - if (box.isInfinite()) - return true; - - Vector3 center = _getWorldAABB().getMaximum().midPoint( _getWorldAABB().getMinimum() ); - - Vector3 bmin = box.getMinimum(); - Vector3 bmax = box.getMaximum(); - - bool centre = ( bmax > center && bmin < center ); - if (!centre) - return false; - - // Even if covering the centre line, need to make sure this BB is not large - // enough to require being moved up into parent. When added, bboxes would - // end up in parent due to cascade but when updating need to deal with - // bbox growing too large for this child - Vector3 octreeSize = bmax - bmin; - Vector3 nodeSize = _getWorldAABB().getMaximum() - _getWorldAABB().getMinimum(); - return nodeSize < octreeSize; - -} - -/** Adds the attached objects of this OctreeScene node into the queue. */ -void OctreeNode::_addToRenderQueue( Camera* cam, RenderQueue *queue, - bool onlyShadowCasters, VisibleObjectsBoundsInfo* visibleBounds ) -{ - for ( auto mo : getAttachedObjects() ) - { - queue->processVisibleObject(mo, cam, onlyShadowCasters, visibleBounds); - } -} - - -void OctreeNode::getRenderOperation( RenderOperation& rend ) -{ - - /* TODO - rend.useIndexes = true; - rend.numTextureCoordSets = 0; // no textures - rend.vertexOptions = LegacyRenderOperation::VO_DIFFUSE_COLOURS; - rend.operationType = LegacyRenderOperation::OT_LINE_LIST; - rend.numVertices = 8; - rend.numIndexes = 24; - - rend.pVertices = mCorners; - rend.pIndexes = mIndexes; - rend.pDiffuseColour = mColors; - - const Vector3 * corners = _getLocalAABB().getAllCorners(); - - int index = 0; - - for ( int i = 0; i < 8; i++ ) - { - rend.pVertices[ index ] = corners[ i ].x; - index++; - rend.pVertices[ index ] = corners[ i ].y; - index++; - rend.pVertices[ index ] = corners[ i ].z; - index++; - } - */ - - -} -} diff --git a/PlugIns/OctreeSceneManager/src/OgreOctreePlugin.cpp b/PlugIns/OctreeSceneManager/src/OgreOctreePlugin.cpp deleted file mode 100644 index 91b61548008..00000000000 --- a/PlugIns/OctreeSceneManager/src/OgreOctreePlugin.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreOctreePlugin.h" -#include "OgreRoot.h" -#include "OgreOctreeSceneManager.h" - -namespace Ogre -{ - const String sPluginName = "Octree Scene Manager"; - //--------------------------------------------------------------------- - OctreePlugin::OctreePlugin() - :mOctreeSMFactory(0) - { - - } - //--------------------------------------------------------------------- - const String& OctreePlugin::getName() const - { - return sPluginName; - } - //--------------------------------------------------------------------- - void OctreePlugin::install() - { - // Create objects - mOctreeSMFactory = OGRE_NEW OctreeSceneManagerFactory(); - - } - //--------------------------------------------------------------------- - void OctreePlugin::initialise() - { - // Register - Root::getSingleton().addSceneManagerFactory(mOctreeSMFactory); - } - //--------------------------------------------------------------------- - void OctreePlugin::shutdown() - { - // Unregister - Root::getSingleton().removeSceneManagerFactory(mOctreeSMFactory); - } - //--------------------------------------------------------------------- - void OctreePlugin::uninstall() - { - // destroy - OGRE_DELETE mOctreeSMFactory; - mOctreeSMFactory = 0; - - - } - - -} diff --git a/PlugIns/OctreeSceneManager/src/OgreOctreeSceneManager.cpp b/PlugIns/OctreeSceneManager/src/OgreOctreeSceneManager.cpp deleted file mode 100644 index f746f4401c5..00000000000 --- a/PlugIns/OctreeSceneManager/src/OgreOctreeSceneManager.cpp +++ /dev/null @@ -1,1117 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -/*************************************************************************** -octreescenemanager.cpp - description -------------------- -begin : Fri Sep 27 2002 -copyright : (C) 2002 by Jon Anderson -email : janders@users.sf.net - -***************************************************************************/ - -#include "OgreOctreeSceneManager.h" -#include "OgreOctreeSceneQuery.h" -#include "OgreOctreeNode.h" -#include "OgreOctreeCamera.h" -#include "OgreWireBoundingBox.h" - -namespace Ogre -{ -enum Intersection -{ - OUTSIDE=0, - INSIDE=1, - INTERSECT=2 -}; -int OctreeSceneManager::intersect_call = 0; - -static Intersection intersect( const Ray &one, const AxisAlignedBox &two ) -{ - OctreeSceneManager::intersect_call++; - // Null box? - if (two.isNull()) return OUTSIDE; - // Infinite box? - if (two.isInfinite()) return INTERSECT; - - bool inside = true; - const Vector3& twoMin = two.getMinimum(); - const Vector3& twoMax = two.getMaximum(); - Vector3 origin = one.getOrigin(); - Vector3 dir = one.getDirection(); - - Vector3 maxT(-1, -1, -1); - - int i = 0; - for(i=0; i<3; i++ ) - { - if( origin[i] < twoMin[i] ) - { - inside = false; - if( dir[i] > 0 ) - { - maxT[i] = (twoMin[i] - origin[i])/ dir[i]; - } - } - else if( origin[i] > twoMax[i] ) - { - inside = false; - if( dir[i] < 0 ) - { - maxT[i] = (twoMax[i] - origin[i]) / dir[i]; - } - } - } - - if( inside ) - { - return INTERSECT; - } - int whichPlane = 0; - if( maxT[1] > maxT[whichPlane]) - whichPlane = 1; - if( maxT[2] > maxT[whichPlane]) - whichPlane = 2; - - if( ((int)maxT[whichPlane]) & 0x80000000 ) - { - return OUTSIDE; - } - for(i=0; i<3; i++ ) - { - if( i!= whichPlane ) - { - float f = origin[i] + maxT[whichPlane] * dir[i]; - if ( f < (twoMin[i] - 0.00001f) || - f > (twoMax[i] +0.00001f ) ) - { - return OUTSIDE; - } - } - } - - return INTERSECT; - -} - - -/** Checks how the second box intersects with the first. -*/ -static Intersection intersect( const PlaneBoundedVolume &one, const AxisAlignedBox &two ) -{ - OctreeSceneManager::intersect_call++; - // Null box? - if (two.isNull()) return OUTSIDE; - // Infinite box? - if (two.isInfinite()) return INTERSECT; - - // Get centre of the box - Vector3 centre = two.getCenter(); - // Get the half-size of the box - Vector3 halfSize = two.getHalfSize(); - - // For each plane, see if all points are on the negative side - // If so, object is not visible. - // If one or more are, it's partial. - // If all aren't, full - bool all_inside = true; - PlaneList::const_iterator i, iend; - iend = one.planes.end(); - for (i = one.planes.begin(); i != iend; ++i) - { - const Plane& plane = *i; - - Plane::Side side = plane.getSide(centre, halfSize); - if(side == one.outside) - return OUTSIDE; - if(side == Plane::BOTH_SIDE) - all_inside = false; - } - - if ( all_inside ) - return INSIDE; - else - return INTERSECT; - -} - - -/** Checks how the second box intersects with the first. -*/ -static Intersection intersect( const AxisAlignedBox &one, const AxisAlignedBox &two ) -{ - OctreeSceneManager::intersect_call++; - // Null box? - if (one.isNull() || two.isNull()) return OUTSIDE; - if (one.isInfinite()) return INSIDE; - if (two.isInfinite()) return INTERSECT; - - - const Vector3& insideMin = two.getMinimum(); - const Vector3& insideMax = two.getMaximum(); - - const Vector3& outsideMin = one.getMinimum(); - const Vector3& outsideMax = one.getMaximum(); - - if ( insideMax.x < outsideMin.x || - insideMax.y < outsideMin.y || - insideMax.z < outsideMin.z || - insideMin.x > outsideMax.x || - insideMin.y > outsideMax.y || - insideMin.z > outsideMax.z ) - { - return OUTSIDE; - } - - bool full = ( insideMin.x > outsideMin.x && - insideMin.y > outsideMin.y && - insideMin.z > outsideMin.z && - insideMax.x < outsideMax.x && - insideMax.y < outsideMax.y && - insideMax.z < outsideMax.z ); - - if ( full ) - return INSIDE; - else - return INTERSECT; - -} - -/** Checks how the box intersects with the sphere. -*/ -static Intersection intersect( const Sphere &one, const AxisAlignedBox &two ) -{ - OctreeSceneManager::intersect_call++; - // Null box? - if (two.isNull()) return OUTSIDE; - if (two.isInfinite()) return INTERSECT; - - float sradius = one.getRadius(); - - sradius *= sradius; - - Vector3 scenter = one.getCenter(); - - const Vector3& twoMin = two.getMinimum(); - const Vector3& twoMax = two.getMaximum(); - - float s, d = 0; - - Vector3 mndistance = ( twoMin - scenter ); - Vector3 mxdistance = ( twoMax - scenter ); - - if ( mndistance.squaredLength() < sradius && - mxdistance.squaredLength() < sradius ) - { - return INSIDE; - } - - //find the square of the distance - //from the sphere to the box - for ( int i = 0 ; i < 3 ; i++ ) - { - if ( scenter[ i ] < twoMin[ i ] ) - { - s = scenter[ i ] - twoMin[ i ]; - d += s * s; - } - - else if ( scenter[ i ] > twoMax[ i ] ) - { - s = scenter[ i ] - twoMax[ i ]; - d += s * s; - } - - } - - bool partial = ( d <= sradius ); - - if ( !partial ) - { - return OUTSIDE; - } - - else - { - return INTERSECT; - } - - -} - -unsigned long white = 0xFFFFFFFF; - -unsigned short OctreeSceneManager::mIndexes[ 24 ] = {0, 1, 1, 2, 2, 3, 3, 0, //back - 0, 6, 6, 5, 5, 1, //left - 3, 7, 7, 4, 4, 2, //right - 6, 7, 5, 4 }; //front -unsigned long OctreeSceneManager::mColors[ 8 ] = {white, white, white, white, white, white, white, white }; - - -OctreeSceneManager::OctreeSceneManager(const String& name) : SceneManager(name) -{ - AxisAlignedBox b( -10000, -10000, -10000, 10000, 10000, 10000 ); - int depth = 8; - mOctree = 0; - init( b, depth ); -} - -OctreeSceneManager::OctreeSceneManager(const String& name, AxisAlignedBox &box, int max_depth ) -: SceneManager(name) -{ - mOctree = 0; - init( box, max_depth ); -} - -const String& OctreeSceneManager::getTypeName(void) const -{ - return OctreeSceneManagerFactory::FACTORY_TYPE_NAME; -} - -void OctreeSceneManager::init( AxisAlignedBox &box, int depth ) -{ - - if ( mOctree != 0 ) - OGRE_DELETE mOctree; - - mOctree = OGRE_NEW Octree( 0 ); - - mMaxDepth = depth; - mBox = box; - - mOctree -> mBox = box; - - Vector3 min = box.getMinimum(); - - Vector3 max = box.getMaximum(); - - mOctree -> mHalfSize = ( max - min ) / 2; - - - mShowBoxes = false; - - mNumObjects = 0; - - Vector3 v( 1.5, 1.5, 1.5 ); - - mScaleFactor.setScale( v ); - - - - // setDisplaySceneNodes( true ); - // setShowBoxes( true ); - - // - //mSceneRoot isn't put into the octree since it has no volume. - -} - -OctreeSceneManager::~OctreeSceneManager() -{ - - if ( mOctree ) - { - OGRE_DELETE mOctree; - mOctree = 0; - } -} - -Camera * OctreeSceneManager::createCamera( const String &name ) -{ - // Check name not used - if (mCameras.find(name) != mCameras.end()) - { - OGRE_EXCEPT( - Exception::ERR_DUPLICATE_ITEM, - "A camera with the name " + name + " already exists", - "OctreeSceneManager::createCamera" ); - } - - Camera * c = OGRE_NEW OctreeCamera( name, this ); - mCameras.emplace(name, c); - - // create visible bounds aab map entry - mCamVisibleObjectsMap[c] = VisibleObjectsBoundsInfo(); - - return c; -} - -void OctreeSceneManager::destroySceneNode( const String &name ) -{ - OctreeNode * on = static_cast < OctreeNode* > ( getSceneNode( name ) ); - - if ( on != 0 ) - _removeOctreeNode( on ); - - SceneManager::destroySceneNode( name ); -} - -bool OctreeSceneManager::getOptionValues( const String & key, StringVector &refValueList ) -{ - return SceneManager::getOptionValues( key, refValueList ); -} - -bool OctreeSceneManager::getOptionKeys( StringVector & refKeys ) -{ - SceneManager::getOptionKeys( refKeys ); - refKeys.push_back( "Size" ); - refKeys.push_back( "ShowOctree" ); - refKeys.push_back( "Depth" ); - - return true; -} - - -void OctreeSceneManager::_updateOctreeNode( OctreeNode * onode ) -{ - const AxisAlignedBox& box = onode -> _getWorldAABB(); - - if ( box.isNull() ) - return ; - - // Skip if octree has been destroyed (shutdown conditions) - if (!mOctree) - return; - - if ( onode -> getOctant() == 0 ) - { - //if outside the octree, force into the root node. - if ( ! onode -> _isIn( mOctree -> mBox ) ) - mOctree->_addNode( onode ); - else - _addOctreeNode( onode, mOctree ); - return ; - } - - if ( ! onode -> _isIn( onode -> getOctant() -> mBox ) ) - { - _removeOctreeNode( onode ); - - //if outside the octree, force into the root node. - if ( ! onode -> _isIn( mOctree -> mBox ) ) - mOctree->_addNode( onode ); - else - _addOctreeNode( onode, mOctree ); - } -} - -/** Only removes the node from the octree. It leaves the octree, even if it's empty. -*/ -void OctreeSceneManager::_removeOctreeNode( OctreeNode * n ) -{ - // Skip if octree has been destroyed (shutdown conditions) - if (!mOctree) - return; - - Octree * oct = n -> getOctant(); - - if ( oct ) - { - oct -> _removeNode( n ); - } - - n->setOctant(0); -} - - -void OctreeSceneManager::_addOctreeNode( OctreeNode * n, Octree *octant, int depth ) -{ - - // Skip if octree has been destroyed (shutdown conditions) - if (!mOctree) - return; - - const AxisAlignedBox& bx = n -> _getWorldAABB(); - - - //if the octree is twice as big as the scene node, - //we will add it to a child. - if ( ( depth < mMaxDepth ) && octant -> _isTwiceSize( bx ) ) - { - int x, y, z; - octant -> _getChildIndexes( bx, &x, &y, &z ); - - if ( octant -> mChildren[ x ][ y ][ z ] == 0 ) - { - octant -> mChildren[ x ][ y ][ z ] = OGRE_NEW Octree( octant ); - const Vector3& octantMin = octant -> mBox.getMinimum(); - const Vector3& octantMax = octant -> mBox.getMaximum(); - Vector3 min, max; - - if ( x == 0 ) - { - min.x = octantMin.x; - max.x = ( octantMin.x + octantMax.x ) / 2; - } - - else - { - min.x = ( octantMin.x + octantMax.x ) / 2; - max.x = octantMax.x; - } - - if ( y == 0 ) - { - min.y = octantMin.y; - max.y = ( octantMin.y + octantMax.y ) / 2; - } - - else - { - min.y = ( octantMin.y + octantMax.y ) / 2; - max.y = octantMax.y; - } - - if ( z == 0 ) - { - min.z = octantMin.z; - max.z = ( octantMin.z + octantMax.z ) / 2; - } - - else - { - min.z = ( octantMin.z + octantMax.z ) / 2; - max.z = octantMax.z; - } - - octant -> mChildren[ x ][ y ][ z ] -> mBox.setExtents( min, max ); - octant -> mChildren[ x ][ y ][ z ] -> mHalfSize = ( max - min ) / 2; - } - - _addOctreeNode( n, octant -> mChildren[ x ][ y ][ z ], ++depth ); - - } - - else - { - octant -> _addNode( n ); - } -} - - -SceneNode * OctreeSceneManager::createSceneNodeImpl( void ) -{ - return OGRE_NEW OctreeNode( this ); -} - -SceneNode * OctreeSceneManager::createSceneNodeImpl( const String &name ) -{ - return OGRE_NEW OctreeNode( this, name ); -} - -void OctreeSceneManager::_updateSceneGraph( Camera * cam ) -{ - SceneManager::_updateSceneGraph( cam ); -} - -void OctreeSceneManager::_findVisibleObjects(Camera * cam, - VisibleObjectsBoundsInfo* visibleBounds, bool onlyShadowCasters ) -{ - - getRenderQueue()->clear(); - mBoxes.clear(); - mVisible.clear(); - - mNumObjects = 0; - - //walk the octree, adding all visible Octreenodes nodes to the render queue. - walkOctree( static_cast < OctreeCamera * > ( cam ), getRenderQueue(), mOctree, - visibleBounds, false, onlyShadowCasters ); - - // Show the octree boxes & cull camera if required - if ( mShowBoxes ) - { - for ( BoxList::iterator it = mBoxes.begin(); it != mBoxes.end(); ++it ) - { - getRenderQueue()->addRenderable(*it); - } - } -} - -void OctreeSceneManager::walkOctree( OctreeCamera *camera, RenderQueue *queue, - Octree *octant, VisibleObjectsBoundsInfo* visibleBounds, - bool foundvisible, bool onlyShadowCasters ) -{ - - //return immediately if nothing is in the node. - if ( octant -> numNodes() == 0 ) - return ; - - OctreeCamera::Visibility v = OctreeCamera::NONE; - - if ( foundvisible ) - { - v = OctreeCamera::FULL; - } - - else if ( octant == mOctree ) - { - v = OctreeCamera::PARTIAL; - } - - else - { - AxisAlignedBox box; - octant -> _getCullBounds( &box ); - v = camera -> getVisibility( box ); - } - - - // if the octant is visible, or if it's the root node... - if ( v != OctreeCamera::NONE ) - { - - //Add stuff to be rendered; - Octree::NodeList::iterator it = octant -> mNodes.begin(); - - if ( mShowBoxes ) - { - mBoxes.push_back( octant->getWireBoundingBox() ); - } - - bool vis = true; - - while ( it != octant -> mNodes.end() ) - { - OctreeNode * sn = *it; - - // if this octree is partially visible, manually cull all - // scene nodes attached directly to this level. - - if ( v == OctreeCamera::PARTIAL ) - vis = camera -> isVisible( sn -> _getWorldAABB() ); - - if ( vis ) - { - - mNumObjects++; - sn -> _addToRenderQueue(camera, queue, onlyShadowCasters, visibleBounds ); - - mVisible.push_back( sn ); - - if (getDebugDrawer()) - getDebugDrawer()->drawSceneNode(sn); - } - - ++it; - } - - Octree* child; - bool childfoundvisible = (v == OctreeCamera::FULL); - if ( (child = octant -> mChildren[ 0 ][ 0 ][ 0 ]) != 0 ) - walkOctree( camera, queue, child, visibleBounds, childfoundvisible, onlyShadowCasters ); - - if ( (child = octant -> mChildren[ 1 ][ 0 ][ 0 ]) != 0 ) - walkOctree( camera, queue, child, visibleBounds, childfoundvisible, onlyShadowCasters ); - - if ( (child = octant -> mChildren[ 0 ][ 1 ][ 0 ]) != 0 ) - walkOctree( camera, queue, child, visibleBounds, childfoundvisible, onlyShadowCasters ); - - if ( (child = octant -> mChildren[ 1 ][ 1 ][ 0 ]) != 0 ) - walkOctree( camera, queue, child, visibleBounds, childfoundvisible, onlyShadowCasters ); - - if ( (child = octant -> mChildren[ 0 ][ 0 ][ 1 ]) != 0 ) - walkOctree( camera, queue, child, visibleBounds, childfoundvisible, onlyShadowCasters ); - - if ( (child = octant -> mChildren[ 1 ][ 0 ][ 1 ]) != 0 ) - walkOctree( camera, queue, child, visibleBounds, childfoundvisible, onlyShadowCasters ); - - if ( (child = octant -> mChildren[ 0 ][ 1 ][ 1 ]) != 0 ) - walkOctree( camera, queue, child, visibleBounds, childfoundvisible, onlyShadowCasters ); - - if ( (child = octant -> mChildren[ 1 ][ 1 ][ 1 ]) != 0 ) - walkOctree( camera, queue, child, visibleBounds, childfoundvisible, onlyShadowCasters ); - - } - -} - -// --- non template versions -static void _findNodes( const AxisAlignedBox &t, std::list< SceneNode * > &list, SceneNode *exclude, bool full, Octree *octant ) -{ - - if ( !full ) - { - AxisAlignedBox obox; - octant -> _getCullBounds( &obox ); - - Intersection isect = intersect( t, obox ); - - if ( isect == OUTSIDE ) - return ; - - full = ( isect == INSIDE ); - } - - - Octree::NodeList::iterator it = octant -> mNodes.begin(); - - while ( it != octant -> mNodes.end() ) - { - OctreeNode * on = ( *it ); - - if ( on != exclude ) - { - if ( full ) - { - list.push_back( on ); - } - - else - { - Intersection nsect = intersect( t, on -> _getWorldAABB() ); - - if ( nsect != OUTSIDE ) - { - list.push_back( on ); - } - } - - } - - ++it; - } - - Octree* child; - - if ( (child=octant -> mChildren[ 0 ][ 0 ][ 0 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 1 ][ 0 ][ 0 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 0 ][ 1 ][ 0 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 1 ][ 1 ][ 0 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 0 ][ 0 ][ 1 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 1 ][ 0 ][ 1 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 0 ][ 1 ][ 1 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 1 ][ 1 ][ 1 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - -} - -static void _findNodes( const Sphere &t, std::list< SceneNode * > &list, SceneNode *exclude, bool full, Octree *octant ) -{ - - if ( !full ) - { - AxisAlignedBox obox; - octant -> _getCullBounds( &obox ); - - Intersection isect = intersect( t, obox ); - - if ( isect == OUTSIDE ) - return ; - - full = ( isect == INSIDE ); - } - - - Octree::NodeList::iterator it = octant -> mNodes.begin(); - - while ( it != octant -> mNodes.end() ) - { - OctreeNode * on = ( *it ); - - if ( on != exclude ) - { - if ( full ) - { - list.push_back( on ); - } - - else - { - Intersection nsect = intersect( t, on -> _getWorldAABB() ); - - if ( nsect != OUTSIDE ) - { - list.push_back( on ); - } - } - - } - - ++it; - } - - Octree* child; - - if ( (child=octant -> mChildren[ 0 ][ 0 ][ 0 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 1 ][ 0 ][ 0 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 0 ][ 1 ][ 0 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 1 ][ 1 ][ 0 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 0 ][ 0 ][ 1 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 1 ][ 0 ][ 1 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 0 ][ 1 ][ 1 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 1 ][ 1 ][ 1 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - -} - - -static void _findNodes( const PlaneBoundedVolume &t, std::list< SceneNode * > &list, SceneNode *exclude, bool full, Octree *octant ) -{ - - if ( !full ) - { - AxisAlignedBox obox; - octant -> _getCullBounds( &obox ); - - Intersection isect = intersect( t, obox ); - - if ( isect == OUTSIDE ) - return ; - - full = ( isect == INSIDE ); - } - - - Octree::NodeList::iterator it = octant -> mNodes.begin(); - - while ( it != octant -> mNodes.end() ) - { - OctreeNode * on = ( *it ); - - if ( on != exclude ) - { - if ( full ) - { - list.push_back( on ); - } - - else - { - Intersection nsect = intersect( t, on -> _getWorldAABB() ); - - if ( nsect != OUTSIDE ) - { - list.push_back( on ); - } - } - - } - - ++it; - } - - Octree* child; - - if ( (child=octant -> mChildren[ 0 ][ 0 ][ 0 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 1 ][ 0 ][ 0 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 0 ][ 1 ][ 0 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 1 ][ 1 ][ 0 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 0 ][ 0 ][ 1 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 1 ][ 0 ][ 1 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 0 ][ 1 ][ 1 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 1 ][ 1 ][ 1 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - -} - -static void _findNodes( const Ray &t, std::list< SceneNode * > &list, SceneNode *exclude, bool full, Octree *octant ) -{ - - if ( !full ) - { - AxisAlignedBox obox; - octant -> _getCullBounds( &obox ); - - Intersection isect = intersect( t, obox ); - - if ( isect == OUTSIDE ) - return ; - - full = ( isect == INSIDE ); - } - - - Octree::NodeList::iterator it = octant -> mNodes.begin(); - - while ( it != octant -> mNodes.end() ) - { - OctreeNode * on = ( *it ); - - if ( on != exclude ) - { - if ( full ) - { - list.push_back( on ); - } - - else - { - Intersection nsect = intersect( t, on -> _getWorldAABB() ); - - if ( nsect != OUTSIDE ) - { - list.push_back( on ); - } - } - - } - - ++it; - } - - Octree* child; - - if ( (child=octant -> mChildren[ 0 ][ 0 ][ 0 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 1 ][ 0 ][ 0 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 0 ][ 1 ][ 0 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 1 ][ 1 ][ 0 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 0 ][ 0 ][ 1 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 1 ][ 0 ][ 1 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 0 ][ 1 ][ 1 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - - if ( (child=octant -> mChildren[ 1 ][ 1 ][ 1 ]) != 0 ) - _findNodes( t, list, exclude, full, child ); - -} - -void OctreeSceneManager::findNodesIn( const AxisAlignedBox &box, std::list< SceneNode * > &list, SceneNode *exclude ) -{ - _findNodes( box, list, exclude, false, mOctree ); -} - -void OctreeSceneManager::findNodesIn( const Sphere &sphere, std::list< SceneNode * > &list, SceneNode *exclude ) -{ - _findNodes( sphere, list, exclude, false, mOctree ); -} - -void OctreeSceneManager::findNodesIn( const PlaneBoundedVolume &volume, std::list< SceneNode * > &list, SceneNode *exclude ) -{ - _findNodes( volume, list, exclude, false, mOctree ); -} - -void OctreeSceneManager::findNodesIn( const Ray &r, std::list< SceneNode * > &list, SceneNode *exclude ) -{ - _findNodes( r, list, exclude, false, mOctree ); -} - -void OctreeSceneManager::resize( const AxisAlignedBox &box ) -{ - std::list< SceneNode * > nodes; - std::list< SceneNode * > ::iterator it; - - _findNodes( mOctree->mBox, nodes, 0, true, mOctree ); - - OGRE_DELETE mOctree; - - mOctree = OGRE_NEW Octree( 0 ); - mOctree->mBox = box; - - const Vector3 &min = box.getMinimum(); - const Vector3 &max = box.getMaximum(); - mOctree->mHalfSize = ( max - min ) * 0.5f; - - it = nodes.begin(); - - while ( it != nodes.end() ) - { - OctreeNode * on = static_cast < OctreeNode * > ( *it ); - on -> setOctant( 0 ); - _updateOctreeNode( on ); - ++it; - } - -} - -bool OctreeSceneManager::setOption( const String & key, const void * val ) -{ - if ( key == "Size" ) - { - resize( * static_cast < const AxisAlignedBox * > ( val ) ); - return true; - } - - else if ( key == "Depth" ) - { - mMaxDepth = * static_cast < const int * > ( val ); - // copy the box since resize will delete mOctree and reference won't work - AxisAlignedBox box = mOctree->mBox; - resize(box); - return true; - } - - else if ( key == "ShowOctree" ) - { - mShowBoxes = * static_cast < const bool * > ( val ); - return true; - } - - - return SceneManager::setOption( key, val ); - - -} - -bool OctreeSceneManager::getOption( const String & key, void *val ) -{ - if ( key == "Size" ) - { - AxisAlignedBox * b = static_cast < AxisAlignedBox * > ( val ); - b -> setExtents( mOctree->mBox.getMinimum(), mOctree->mBox.getMaximum() ); - return true; - } - - else if ( key == "Depth" ) - { - * static_cast < int * > ( val ) = mMaxDepth; - return true; - } - - else if ( key == "ShowOctree" ) - { - - * static_cast < bool * > ( val ) = mShowBoxes; - return true; - } - - - return SceneManager::getOption( key, val ); - -} - -void OctreeSceneManager::clearScene(void) -{ - SceneManager::clearScene(); - init(mBox, mMaxDepth); - -} - -//--------------------------------------------------------------------- -AxisAlignedBoxSceneQuery* -OctreeSceneManager::createAABBQuery(const AxisAlignedBox& box, uint32 mask) -{ - OctreeAxisAlignedBoxSceneQuery* q = OGRE_NEW OctreeAxisAlignedBoxSceneQuery(this); - q->setBox(box); - q->setQueryMask(mask); - return q; -} -//--------------------------------------------------------------------- -SphereSceneQuery* -OctreeSceneManager::createSphereQuery(const Sphere& sphere, uint32 mask) -{ - OctreeSphereSceneQuery* q = OGRE_NEW OctreeSphereSceneQuery(this); - q->setSphere(sphere); - q->setQueryMask(mask); - return q; -} -//--------------------------------------------------------------------- -PlaneBoundedVolumeListSceneQuery* -OctreeSceneManager::createPlaneBoundedVolumeQuery(const PlaneBoundedVolumeList& volumes, - uint32 mask) -{ - OctreePlaneBoundedVolumeListSceneQuery* q = OGRE_NEW OctreePlaneBoundedVolumeListSceneQuery(this); - q->setVolumes(volumes); - q->setQueryMask(mask); - return q; -} - -//--------------------------------------------------------------------- -RaySceneQuery* -OctreeSceneManager::createRayQuery(const Ray& ray, uint32 mask) -{ - OctreeRaySceneQuery* q = OGRE_NEW OctreeRaySceneQuery(this); - q->setRay(ray); - q->setQueryMask(mask); - return q; -} -//--------------------------------------------------------------------- -IntersectionSceneQuery* -OctreeSceneManager::createIntersectionQuery(uint32 mask) -{ - - // Octree implementation performs WORSE for < 500 objects - // TODO: optimise it so it's better in all cases - //OctreeIntersectionSceneQuery* q = OGRE_NEW OctreeIntersectionSceneQuery(this); - DefaultIntersectionSceneQuery* q = OGRE_NEW DefaultIntersectionSceneQuery(this); - q->setQueryMask(mask); - return q; -} -//----------------------------------------------------------------------- -const String OctreeSceneManagerFactory::FACTORY_TYPE_NAME = "OctreeSceneManager"; -//----------------------------------------------------------------------- -SceneManager* OctreeSceneManagerFactory::createInstance( - const String& instanceName) -{ - return OGRE_NEW OctreeSceneManager(instanceName); -} - -} diff --git a/PlugIns/OctreeSceneManager/src/OgreOctreeSceneManagerDll.cpp b/PlugIns/OctreeSceneManager/src/OgreOctreeSceneManagerDll.cpp deleted file mode 100644 index 437842d7ad1..00000000000 --- a/PlugIns/OctreeSceneManager/src/OgreOctreeSceneManagerDll.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreOctreePrerequisites.h" -#include "OgreRoot.h" -#include "OgreOctreePlugin.h" - -#ifndef OGRE_STATIC_LIB - -namespace Ogre -{ -extern "C" void _OgreOctreePluginExport dllStartPlugin(void); -extern "C" void _OgreOctreePluginExport dllStopPlugin(void); - -static OctreePlugin* octreePlugin; - -extern "C" void _OgreOctreePluginExport dllStartPlugin( void ) -{ - // Create new scene manager - octreePlugin = OGRE_NEW OctreePlugin(); - - // Register - Root::getSingleton().installPlugin(octreePlugin); - -} -extern "C" void _OgreOctreePluginExport dllStopPlugin( void ) -{ - Root::getSingleton().uninstallPlugin(octreePlugin); - OGRE_DELETE octreePlugin; -} -} - -#endif diff --git a/PlugIns/OctreeSceneManager/src/OgreOctreeSceneQuery.cpp b/PlugIns/OctreeSceneManager/src/OgreOctreeSceneQuery.cpp deleted file mode 100644 index 44c2890f19c..00000000000 --- a/PlugIns/OctreeSceneManager/src/OgreOctreeSceneQuery.cpp +++ /dev/null @@ -1,323 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -/*************************************************************************** -OgreOctreeSceneQuery.cpp - description -------------------- -begin : Tues July 20, 2004 -copyright : (C) 2004by Jon Anderson -email : janders@users.sf.net - - - -***************************************************************************/ - -#include "OgreOctreeSceneQuery.h" -#include "OgreRoot.h" -#include "OgreSceneNode.h" -#include "OgreOctreeSceneManager.h" -#include "OgreEntity.h" - -namespace Ogre -{ - -//--------------------------------------------------------------------- -OctreeIntersectionSceneQuery::OctreeIntersectionSceneQuery(SceneManager* creator) - : DefaultIntersectionSceneQuery(creator) -{ - -} -//--------------------------------------------------------------------- -OctreeIntersectionSceneQuery::~OctreeIntersectionSceneQuery() -{} -//--------------------------------------------------------------------- -void OctreeIntersectionSceneQuery::execute(IntersectionSceneQueryListener* listener) -{ - typedef std::pair MovablePair; - typedef std::set - < std::pair > MovableSet; - - MovableSet set; - - // Iterate over all movable types - for(const auto& factIt : Root::getSingleton().getMovableObjectFactories()) - { - for (const auto& it : mParentSceneMgr->getMovableObjects(factIt.first)) - { - - MovableObject * e = it.second; - - std::list< SceneNode * > list; - //find the nodes that intersect the AAB - static_cast( mParentSceneMgr ) -> findNodesIn( e->getWorldBoundingBox(), list, 0 ); - //grab all moveables from the node that intersect... - std::list< SceneNode * >::iterator nit = list.begin(); - while( nit != list.end() ) - { - for (auto m : (*nit)->getAttachedObjects()) - { - if( m != e && - set.find( MovablePair(e,m)) == set.end() && - set.find( MovablePair(m,e)) == set.end() && - (m->getQueryFlags() & mQueryMask) && - (m->getTypeFlags() & mQueryTypeMask) && - m->isInScene() && - e->getWorldBoundingBox().intersects( m->getWorldBoundingBox() ) ) - { - listener -> queryResult( e, m ); - // deal with attached objects, since they are not directly attached to nodes - if (m->getMovableType() == MOT_ENTITY) - { - Entity* e2 = static_cast(m); - for(auto c : e2->getAttachedObjects()) - { - if (c->getQueryFlags() & mQueryMask && - e->getWorldBoundingBox().intersects( c->getWorldBoundingBox() )) - { - listener->queryResult(e, c); - } - } - } - } - set.insert( MovablePair(e,m) ); - - } - ++nit; - } - - } - } -} -/** Creates a custom Octree AAB query */ -OctreeAxisAlignedBoxSceneQuery::OctreeAxisAlignedBoxSceneQuery(SceneManager* creator) - : DefaultAxisAlignedBoxSceneQuery(creator) -{ -} -/** Deletes the custom Octree query */ -OctreeAxisAlignedBoxSceneQuery::~OctreeAxisAlignedBoxSceneQuery() -{} - -/** Finds any entities that intersect the AAB for the query. */ -void OctreeAxisAlignedBoxSceneQuery::execute(SceneQueryListener* listener) -{ - std::list< SceneNode * > _list; - //find the nodes that intersect the AAB - static_cast( mParentSceneMgr ) -> findNodesIn( mAABB, _list, 0 ); - - //grab all moveables from the node that intersect... - std::list< SceneNode * >::iterator it = _list.begin(); - while( it != _list.end() ) - { - for (auto m : (*it)->getAttachedObjects()) - { - if( (m->getQueryFlags() & mQueryMask) && - (m->getTypeFlags() & mQueryTypeMask) && - m->isInScene() && - mAABB.intersects( m->getWorldBoundingBox() ) ) - { - listener -> queryResult( m ); - // deal with attached objects, since they are not directly attached to nodes - if (m->getMovableType() == MOT_ENTITY) - { - Entity* e = static_cast(m); - for (auto c : e->getAttachedObjects()) - { - if (c->getQueryFlags() & mQueryMask) - { - listener->queryResult(c); - } - } - } - } - - } - - ++it; - } - -} -//--------------------------------------------------------------------- -OctreeRaySceneQuery:: -OctreeRaySceneQuery(SceneManager* creator) : DefaultRaySceneQuery(creator) -{ -} -//--------------------------------------------------------------------- -OctreeRaySceneQuery::~OctreeRaySceneQuery() -{} -//--------------------------------------------------------------------- -void OctreeRaySceneQuery::execute(RaySceneQueryListener* listener) -{ - std::list< SceneNode * > _list; - //find the nodes that intersect the AAB - static_cast( mParentSceneMgr ) -> findNodesIn( mRay, _list, 0 ); - - //grab all moveables from the node that intersect... - std::list< SceneNode * >::iterator it = _list.begin(); - while( it != _list.end() ) - { - for (auto m : (*it)->getAttachedObjects()) - { - if( (m->getQueryFlags() & mQueryMask) && - (m->getTypeFlags() & mQueryTypeMask) && m->isInScene() ) - { - std::pair result = mRay.intersects(m->getWorldBoundingBox()); - - if( result.first ) - { - listener -> queryResult( m, result.second ); - // deal with attached objects, since they are not directly attached to nodes - if (m->getMovableType() == MOT_ENTITY) - { - Entity* e = static_cast(m); - for(auto c : e->getAttachedObjects()) - { - if (c->getQueryFlags() & mQueryMask) - { - result = mRay.intersects(c->getWorldBoundingBox()); - if (result.first) - { - listener->queryResult(c, result.second); - } - } - } - } - } - } - } - - ++it; - } - -} - - -//--------------------------------------------------------------------- -OctreeSphereSceneQuery:: -OctreeSphereSceneQuery(SceneManager* creator) : DefaultSphereSceneQuery(creator) -{ -} -//--------------------------------------------------------------------- -OctreeSphereSceneQuery::~OctreeSphereSceneQuery() -{} -//--------------------------------------------------------------------- -void OctreeSphereSceneQuery::execute(SceneQueryListener* listener) -{ - std::list< SceneNode * > _list; - //find the nodes that intersect the AAB - static_cast( mParentSceneMgr ) -> findNodesIn( mSphere, _list, 0 ); - - //grab all moveables from the node that intersect... - std::list< SceneNode * >::iterator it = _list.begin(); - while( it != _list.end() ) - { - for (auto m : (*it)->getAttachedObjects()) - { - if( (m->getQueryFlags() & mQueryMask) && - (m->getTypeFlags() & mQueryTypeMask) && - m->isInScene() && - mSphere.intersects( m->getWorldBoundingBox() ) ) - { - listener -> queryResult( m ); - // deal with attached objects, since they are not directly attached to nodes - if (m->getMovableType() == MOT_ENTITY) - { - Entity* e = static_cast(m); - for(auto c : e->getAttachedObjects()) - { - if (c->getQueryFlags() & mQueryMask && - mSphere.intersects( c->getWorldBoundingBox())) - { - listener->queryResult(c); - } - } - } - } - } - - ++it; - } -} -//--------------------------------------------------------------------- -OctreePlaneBoundedVolumeListSceneQuery:: -OctreePlaneBoundedVolumeListSceneQuery(SceneManager* creator) - : DefaultPlaneBoundedVolumeListSceneQuery(creator) -{ - -} -//--------------------------------------------------------------------- -OctreePlaneBoundedVolumeListSceneQuery::~OctreePlaneBoundedVolumeListSceneQuery() -{} -//--------------------------------------------------------------------- -void OctreePlaneBoundedVolumeListSceneQuery::execute(SceneQueryListener* listener) -{ - std::set checkedSceneNodes; - - PlaneBoundedVolumeList::iterator pi, piend; - piend = mVolumes.end(); - for (pi = mVolumes.begin(); pi != piend; ++pi) - { - std::list< SceneNode * > _list; - //find the nodes that intersect the AAB - static_cast( mParentSceneMgr ) -> findNodesIn( *pi, _list, 0 ); - - //grab all moveables from the node that intersect... - std::list< SceneNode * >::iterator it, itend; - itend = _list.end(); - for (it = _list.begin(); it != itend; ++it) - { - // avoid double-check same scene node - if (!checkedSceneNodes.insert(*it).second) - continue; - for (auto m : (*it)->getAttachedObjects()) - { - if( (m->getQueryFlags() & mQueryMask) && - (m->getTypeFlags() & mQueryTypeMask) && - m->isInScene() && - (*pi).intersects( m->getWorldBoundingBox() ) ) - { - listener -> queryResult( m ); - // deal with attached objects, since they are not directly attached to nodes - if (m->getMovableType() == MOT_ENTITY) - { - Entity* e = static_cast(m); - for(auto c : e->getAttachedObjects()) - { - if (c->getQueryFlags() & mQueryMask && - (*pi).intersects( c->getWorldBoundingBox())) - { - listener->queryResult(c); - } - } - } - } - } - } - }//for -} - - -} diff --git a/PlugIns/OctreeZone/CMakeLists.txt b/PlugIns/OctreeZone/CMakeLists.txt deleted file mode 100644 index d2efbe3392d..00000000000 --- a/PlugIns/OctreeZone/CMakeLists.txt +++ /dev/null @@ -1,29 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure OctreeZone SceneManager build - -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES ${PROJECT_BINARY_DIR}/include/OgreOctreeZonePrerequisites.h) -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") - -add_library(Plugin_OctreeZone ${OGRE_LIB_TYPE} ${HEADER_FILES} ${SOURCE_FILES}) -target_link_libraries(Plugin_OctreeZone PUBLIC OgreMain Plugin_PCZSceneManager) -target_include_directories(Plugin_OctreeZone PUBLIC - "$" - $) - -generate_export_header(Plugin_OctreeZone - EXPORT_MACRO_NAME _OgreOctreeZonePluginExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreOctreeZonePrerequisites.h) - -ogre_config_framework(Plugin_OctreeZone) - -ogre_config_plugin(Plugin_OctreeZone) -install(FILES ${HEADER_FILES} DESTINATION include/OGRE/Plugins/OctreeZone) diff --git a/PlugIns/OctreeZone/include/OgreOctreeZone.h b/PlugIns/OctreeZone/include/OgreOctreeZone.h deleted file mode 100644 index 1de8a3d871c..00000000000 --- a/PlugIns/OctreeZone/include/OgreOctreeZone.h +++ /dev/null @@ -1,268 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -OctreeZone.h - Portal Connected Zone (OctreeZone) header file. - -OctreeZones are a type of PCZone. Octree Zones partition their space into -Octants. For details on Zones in general, see PCZone.h/cpp. ------------------------------------------------------------------------------ -begin : Mon Apr 16 2007 -author : Eric Cha -email : ericc@xenopi.com -Code Style Update : ------------------------------------------------------------------------------ -*/ - -#ifndef OCTREEZONE_H -#define OCTREEZONE_H - -#include "OgreOctreeZonePrerequisites.h" -#include "OgrePCZone.h" -#include "OgrePCZoneFactory.h" - -namespace Ogre -{ - /** \addtogroup Plugins Plugins - * @{ - */ - /** \defgroup OctreeZone OctreeZone - * Octree version of PCZone - * @{ - */ - /** Octree version of PCZone - */ - class Octree; - class OctreeZoneData; - - class _OgreOctreeZonePluginExport OctreeZone : public PCZone - { - public: - OctreeZone( PCZSceneManager *, const String& ); - virtual ~OctreeZone(); - - /** Set the enclosure node for this OctreeZone - */ - void setEnclosureNode(PCZSceneNode *) override; - - /** Adds an SceneNode to this OctreeZone. - - The PCZSceneManager calls this function to add a node - to the zone. - */ - void _addNode( PCZSceneNode * ) override; - - /** Removes all references to a SceneNode from this Zone. - */ - void removeNode( PCZSceneNode * ) override; - - /** Remove all nodes from the node reference list and clear it - */ - void _clearNodeLists(short nodeListTypes) override; - - /** Indicates whether or not this zone requires zone-specific data for - * each scene node - */ - bool requiresZoneSpecificNodeData(void) override; - - /** Create zone specific data for a node - */ - void createNodeZoneData(PCZSceneNode *) override; - - /** (recursive) Check the given node against all portals in the zone - */ - void _checkNodeAgainstPortals(PCZSceneNode *, Portal * ) override; - - /** (recursive) Check the given light against all portals in the zone - */ - void _checkLightAgainstPortals(PCZLight *, - unsigned long, - PCZFrustum *, - Portal*) override; - - /** Update the zone data for each portal - */ - void updatePortalsZoneData(void) override; - - /** Mark nodes dirty base on moving portals. */ - void dirtyNodeByMovingPortals(void) override; - - /** Update a node's home zone */ - PCZone * updateNodeHomeZone(PCZSceneNode * pczsn, bool allowBackTouces) override; - - /** Find and add visible objects to the render queue. - - Starts with objects in the zone and proceeds through visible portals - This is a recursive call (the main call should be to _findVisibleObjects) - */ - void findVisibleNodes(PCZCamera *, - NodeList & visibleNodeList, - RenderQueue * queue, - VisibleObjectsBoundsInfo* visibleBounds, - bool onlyShadowCasters, - bool displayNodes, - bool showBoundingBoxes) override; - - /** Functions for finding Nodes that intersect various shapes */ - void _findNodes(const AxisAlignedBox &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude) override; - void _findNodes(const Sphere &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude ) override; - void _findNodes(const PlaneBoundedVolume &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude ) override; - void _findNodes(const Ray &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude ) override; - - /** Sets the given option for the Zone - - Options are: - "Size", AxisAlignedBox *; - "Depth", int *; - "ShowOctree", bool *; - */ - bool setOption( const String &, const void * ) override; - - /** Called when the scene manager creates a camera because - some zone managers (like TerrainZone) need the camera info. - */ - void notifyCameraCreated( Camera* c ) override; - - /** Called by PCZSM during setWorldGeometryRenderQueue() */ - void notifyWorldGeometryRenderQueue(uint8 qid) override; - - /** Called when a _renderScene is called in the SceneManager */ - void notifyBeginRenderScene(void) override; - - /** Called by PCZSM during setZoneGeometry() */ - void setZoneGeometry(const String &filename, PCZSceneNode * parentNode) override; - - /** Get the world coordinate aabb of the zone */ - void getAABB(AxisAlignedBox &) override; - - /// Init function carried over from OctreeSceneManager - void init(AxisAlignedBox &box, int depth); - /** Resizes the octree to the given size */ - void resize( const AxisAlignedBox &box ); - /** Checks the given OctreeNode, and determines if it needs to be moved - * to a different octant. - */ - void updateNodeOctant( OctreeZoneData * zoneData ); - /** Removes the node from the octree it is in */ - void removeNodeFromOctree( PCZSceneNode * ); - /** Adds the Octree Node, starting at the given octree, and recursing at max to the specified depth. - */ - void addNodeToOctree( PCZSceneNode *, Octree *octree, int depth = 0 ); - - - protected: - /** Walks through the octree, adding any visible objects to the render queue. - - If any octant in the octree if completely within the view frustum, - all subchildren are automatically added with no visibility tests. - */ - void walkOctree( PCZCamera *, - NodeList &, - RenderQueue *, - Octree *, - VisibleObjectsBoundsInfo* visibleBounds, - bool foundvisible, - bool onlyShadowCasters, - bool displayNodes, - bool showBoundingBoxes); - - protected: - /// The root octree - Octree *mOctree; - /// Max depth for the tree - int mMaxDepth; - /// Size of the octree - AxisAlignedBox mBox; - }; - - class _OgreOctreeZonePluginExport OctreeZoneData : public ZoneData - { - public: - /** Standard Constructor */ - OctreeZoneData(PCZSceneNode *, PCZone * ); - /** Standard destructor */ - ~OctreeZoneData(); - /** Update data */ - void update(void) override; - - /** Returns the Octree in which this OctreeNode resides - */ - Octree * getOctant() - { - return mOctant; - }; - /** Sets the Octree in which this OctreeNode resides - */ - void setOctant( Octree *o ) - { - mOctant = o; - }; - bool _isIn( AxisAlignedBox &box ); - - public: - /// Octree this node is attached to. - Octree * mOctant; - /// Octree-specific world bounding box (only includes attached objects, not children) - AxisAlignedBox mOctreeWorldAABB; - }; - - /// Factory for OctreeZone - class OctreeZoneFactory : public PCZoneFactory - { - public: - OctreeZoneFactory(); - virtual ~OctreeZoneFactory(); - - bool supportsPCZoneType(const String& zoneType) override; - PCZone* createPCZone(PCZSceneManager * pczsm, const String& zoneName) override; - }; - /** @} */ - /** @} */ -} - -#endif - - - diff --git a/PlugIns/OctreeZone/include/OgreOctreeZoneOctree.h b/PlugIns/OctreeZone/include/OgreOctreeZoneOctree.h deleted file mode 100644 index 8c1a1db9084..00000000000 --- a/PlugIns/OctreeZone/include/OgreOctreeZoneOctree.h +++ /dev/null @@ -1,206 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -OgreOctree.h - description ------------------------------------------------------------------------------ -begin : Mon Sep 30 2002 -copyright : (C) 2002 by Jon Anderson -email : janders@users.sf.net - -Modified slightly for use with PCZSceneManager Octree Zones by Eric Cha - ------------------------------------------------------------------------------ -*/ - -#ifndef OCTREE_H -#define OCTREE_H - -#include "OgreAxisAlignedBox.h" - -#include - -namespace Ogre -{ -/** \addtogroup Plugins -* @{ -*/ -/** \addtogroup OctreeZone -* @{ - */ -class PCZSceneNode; -class PCZone; - -typedef std::set< PCZSceneNode * > PCZSceneNodeList; - - -/** Octree datastructure for managing scene nodes. - -This is a loose octree implementation, meaning that each -octant child of the octree actually overlaps it's siblings by a factor -of .5. This guarantees that any thing that is half the size of the parent will -fit completely into a child, with no splitting necessary. -*/ - -class Octree : public SceneCtlAllocatedObject -{ -public: - Octree( PCZone * zone, Octree * p ); - ~Octree(); - - /** Adds an PCZscene node to this octree level. - - This is called by the OctreeZone after - it has determined the correct Octree to insert the node into. - */ - void _addNode( PCZSceneNode * ); - - /** Removes an PCZscene node to this octree level. - */ - void _removeNode( PCZSceneNode * ); - - /** Returns the number of scene nodes attached to this octree - */ - int numNodes() - { - return mNumNodes; - }; - - /** The bounding box of the octree - - This is used for octant index determination and rendering, but not culling - */ - AxisAlignedBox mBox; - WireBoundingBox* mWireBoundingBox; - - /** Creates the wire frame bounding box for this octant - */ - WireBoundingBox* getWireBoundingBox(); - - /** Vector containing the dimensions of this octree / 2 - */ - Vector3 mHalfSize; - - /** 3D array of children of this octree. - - Children are dynamically created as needed when nodes are inserted in the Octree. - If, later, all the nodes are removed from the child, it is still kept around. - */ - Octree * mChildren[ 2 ][ 2 ][ 2 ]; - - /** Determines if this octree is twice as big as the given box. - - This method is used by the OctreeSceneManager to determine if the given - box will fit into a child of this octree. - */ - bool _isTwiceSize( const AxisAlignedBox &box ) const; - - /** Returns the appropriate indexes for the child of this octree into which the box will fit. - - This is used by the OctreeSceneManager to determine which child to traverse next when - finding the appropriate octree to insert the box. Since it is a loose octree, only the - center of the box is checked to determine the octant. - */ - void _getChildIndexes( const AxisAlignedBox &, int *x, int *y, int *z ) const; - - /** Creates the AxisAlignedBox used for culling this octree. - - Since it's a loose octree, the culling bounds can be different than the actual bounds of the octree. - */ - void _getCullBounds( AxisAlignedBox * ) const; - - /* Recurse through the Octree to find the scene nodes which intersect an aab - */ - void _findNodes(const AxisAlignedBox &t, - PCZSceneNodeList &list, - PCZSceneNode *exclude, - bool includeVisitors, - bool full ); - - /* Recurse through the Octree to find the scene nodes which intersect a ray - */ - void _findNodes(const Ray &t, - PCZSceneNodeList &list, - PCZSceneNode *exclude, - bool includeVisitors, - bool full ); - - /* Recurse through the Octree to find the scene nodes which intersect a sphere - */ - void _findNodes(const Sphere &t, - PCZSceneNodeList &list, - PCZSceneNode *exclude, - bool includeVisitors, - bool full ); - - /* Recurse through the Octree to find the scene nodes which intersect a PBV - */ - void _findNodes(const PlaneBoundedVolume &t, - PCZSceneNodeList &list, - PCZSceneNode *exclude, - bool includeVisitors, - bool full ); - - /** Public list of SceneNodes attached to this particular octree - */ - PCZSceneNodeList mNodes; - - /* Zone that this octree is in */ - PCZone * mZone; - -protected: - - /** Increments the overall node count of this octree and all its parents - */ - inline void _ref() - { - mNumNodes++; - - if ( mParent != 0 ) mParent -> _ref(); - }; - - /** Decrements the overall node count of this octree and all its parents - */ - inline void _unref() - { - mNumNodes--; - - if ( mParent != 0 ) mParent -> _unref(); - }; - - ///number of SceneNodes in this octree and all its children. - int mNumNodes; - - ///parent octree - Octree * mParent; - -}; -/** @} */ -/** @} */ -} - -#endif - - diff --git a/PlugIns/OctreeZone/include/OgreOctreeZonePlugin.h b/PlugIns/OctreeZone/include/OgreOctreeZonePlugin.h deleted file mode 100644 index 645c5eae499..00000000000 --- a/PlugIns/OctreeZone/include/OgreOctreeZonePlugin.h +++ /dev/null @@ -1,72 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -OgreOctreeZonePlugin.h - Octree Zone Plugin class for PCZSceneManager - ------------------------------------------------------------------------------ -begin : Mon Apr 16 2007 -author : Eric Cha -email : ericc@xenopi.com -Code Style Update : ------------------------------------------------------------------------------ -*/ - -#ifndef OCTREEZONE_PLUGIN_H -#define OCTREEZONE_PLUGIN_H - -#include "OgrePlugin.h" - -namespace Ogre -{ - class OctreeZoneFactory; - - /** Plugin instance for OctreeZone */ - class OctreeZonePlugin : public Plugin - { - public: - OctreeZonePlugin(); - - /// @copydoc Plugin::getName - const String& getName() const override; - - /// @copydoc Plugin::install - void install() override; - - /// @copydoc Plugin::initialise - void initialise() override; - - /// @copydoc Plugin::shutdown - void shutdown() override; - - /// @copydoc Plugin::uninstall - void uninstall() override; - protected: - OctreeZoneFactory* mOctreeZoneFactory; - - }; -} - -#endif diff --git a/PlugIns/OctreeZone/src/OgreOctreeZone.cpp b/PlugIns/OctreeZone/src/OgreOctreeZone.cpp deleted file mode 100644 index a4eb94cca9b..00000000000 --- a/PlugIns/OctreeZone/src/OgreOctreeZone.cpp +++ /dev/null @@ -1,1321 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -OctreeZone.cpp - Octree Zone implementation ------------------------------------------------------------------------------ -begin : Tue Feb 20 2007 -author : Eric Cha -email : ericc@xenopi.com - ------------------------------------------------------------------------------ -*/ - -#include "OgreOctreeZone.h" -#include "OgreSceneNode.h" -#include "OgreAntiPortal.h" -#include "OgrePortal.h" -#include "OgreEntity.h" -#include "OgreOctreeZoneOctree.h" -#include "OgrePCZCamera.h" -#include "OgrePCZLight.h" -#include "OgrePCZSceneNode.h" -#include "OgrePCZSceneManager.h" - -namespace Ogre -{ - OctreeZone::OctreeZone( PCZSceneManager * creator, const String& name ) - : PCZone(creator, name) - { - mZoneTypeName = "ZoneType_Octree"; - // init octree - AxisAlignedBox b( -10000, -10000, -10000, 10000, 10000, 10000 ); - int depth = 8; - mOctree = 0; - init( b, depth ); - } - - OctreeZone::~OctreeZone() - { - // portals & nodelist are deleted in PCZone destructor. - - // delete octree - if ( mOctree ) - { - OGRE_DELETE mOctree; - mOctree = 0; - } - } - - /** Set the enclosure node for this OctreeZone - */ - void OctreeZone::setEnclosureNode(PCZSceneNode * node) - { - mEnclosureNode = node; - if (node) - { - // anchor the node to this zone - node->anchorToHomeZone(this); - // make sure node world bounds are up to date - node->_updateBounds(); - // resize the octree to the same size as the enclosure node bounding box - resize(node->_getWorldAABB()); - } - } - - // this call adds the given node to either the zone's list - // of nodes at home in the zone, or to the list of visiting nodes - // NOTE: The list is decided by the node's homeZone value, so - // that must be set correctly before calling this function. - void OctreeZone::_addNode( PCZSceneNode * n ) - { - if (n->getHomeZone() == this) - { - // add a reference to this node in the "nodes at home in this zone" list - mHomeNodeList.insert( n ); - } - else - { - // add a reference to this node in the "nodes visiting this zone" list - mVisitorNodeList.insert( n ); - } - } - - void OctreeZone::removeNode( PCZSceneNode * n ) - { - if ( n != 0 ) - { - removeNodeFromOctree( n ); - - if (n->getHomeZone() == this) - { - mHomeNodeList.erase( n ); - - } - else - { - mVisitorNodeList.erase( n ); - } - } - } - - /** Remove all nodes from the node reference list and clear it - */ - void OctreeZone::_clearNodeLists(short nodeListTypes) - { - if (nodeListTypes & HOME_NODE_LIST) - { - PCZSceneNodeList::iterator it = mHomeNodeList.begin(); - while( it != mHomeNodeList.end()) - { - PCZSceneNode * sn = *it; - removeNodeFromOctree( sn ); - ++it; - } - mHomeNodeList.clear(); - } - if (nodeListTypes & VISITOR_NODE_LIST) - { - PCZSceneNodeList::iterator it = mVisitorNodeList.begin(); - while( it != mVisitorNodeList.end()) - { - PCZSceneNode * sn = *it; - removeNodeFromOctree( sn ); - ++it; - } - mVisitorNodeList.clear(); - } - } - - /** Indicates whether or not this zone requires zone-specific data for - * each scene node - */ - bool OctreeZone::requiresZoneSpecificNodeData(void) - { - // Octree Zones have zone specific node data - return true; - } - - /** create zone specific data for a node - */ - void OctreeZone::createNodeZoneData(PCZSceneNode * node) - { - OctreeZoneData * ozd = OGRE_NEW OctreeZoneData(node, this); - if (ozd) - { - node->setZoneData(this, ozd); - } - } - - /* Recursively check for intersection of the given scene node - * with zone portals. If the node touches a portal, then the - * connected zone is assumed to be touched. The zone adds - * the node to its node list and the node adds the zone to - * its visiting zone list. - * - * NOTE: This function assumes that the home zone of the node - * is correct. The function "_updateHomeZone" in PCZSceneManager - * takes care of this and should have been called before - * this function. - */ - - void OctreeZone::_checkNodeAgainstPortals(PCZSceneNode * pczsn, Portal * ignorePortal) - { - if (pczsn == mEnclosureNode || - pczsn->allowedToVisit() == false) - { - // don't do any checking of enclosure node versus portals - return; - } - - PCZone * connectedZone; - for ( PortalList::iterator it = mPortals.begin(); it != mPortals.end(); ++it ) - { - Portal * p = *it; - //Check if the portal intersects the node - if (p != ignorePortal && p->intersects(pczsn) != Portal::NO_INTERSECT) - { - // node is touching this portal - connectedZone = p->getTargetZone(); - // add zone to the nodes visiting zone list unless it is the home zone of the node - if (connectedZone != pczsn->getHomeZone() && - !pczsn->isVisitingZone(connectedZone)) - { - pczsn->addZoneToVisitingZonesMap(connectedZone); - // tell the connected zone that the node is visiting it - connectedZone->_addNode(pczsn); - //recurse into the connected zone - connectedZone->_checkNodeAgainstPortals(pczsn, p->getTargetPortal()); - } - } - } - } - - /** (recursive) check the given light against all portals in the zone - * NOTE: This is the default implementation, which doesn't take advantage - * of any zone-specific optimizations for checking portal visibility - */ - void OctreeZone::_checkLightAgainstPortals(PCZLight *light, - unsigned long frameCount, - PCZFrustum *portalFrustum, - Portal * ignorePortal) - { - for ( PortalList::iterator it = mPortals.begin(); it != mPortals.end(); ++it ) - { - Portal * p = *it; - if (p != ignorePortal) - { - // calculate the direction vector from light to portal - Vector3 lightToPortal = p->getDerivedCP() - light->getDerivedPosition(); - if (portalFrustum->isVisible(p)) - { - // portal is facing the light, but some light types need to - // check illumination radius too. - PCZone * targetZone = p->getTargetZone(); - switch(light->getType()) - { - case Light::LT_POINT: - // point lights - just check if within illumination range - if (lightToPortal.length() <= light->getAttenuationRange()) - { - // if portal is quad portal it must be pointing towards the light - if ((p->getType() == Portal::PORTAL_TYPE_QUAD && lightToPortal.dotProduct(p->getDerivedDirection()) < 0.0) || - (p->getType() != Portal::PORTAL_TYPE_QUAD)) - { - if (!light->affectsZone(targetZone)) - { - light->addZoneToAffectedZonesList(targetZone); - if (targetZone->getLastVisibleFrame() == frameCount) - { - light->setAffectsVisibleZone(true); - } - // set culling frustum from the portal - portalFrustum->addPortalCullingPlanes(p); - // recurse into the target zone of the portal - p->getTargetZone()->_checkLightAgainstPortals(light, - frameCount, - portalFrustum, - p->getTargetPortal()); - // remove the planes added by this portal - portalFrustum->removePortalCullingPlanes(p); - } - } - } - break; - case Light::LT_DIRECTIONAL: - // directionals have infinite range, so just make sure - // the direction is facing the portal - if (lightToPortal.dotProduct(light->getDerivedDirection()) >= 0.0) - { - // if portal is quad portal it must be pointing towards the light - if ((p->getType() == Portal::PORTAL_TYPE_QUAD && lightToPortal.dotProduct(p->getDerivedDirection()) < 0.0) || - (p->getType() != Portal::PORTAL_TYPE_QUAD)) - { - if (!light->affectsZone(targetZone)) - { - light->addZoneToAffectedZonesList(targetZone); - if (targetZone->getLastVisibleFrame() == frameCount) - { - light->setAffectsVisibleZone(true); - } - // set culling frustum from the portal - portalFrustum->addPortalCullingPlanes(p); - // recurse into the target zone of the portal - p->getTargetZone()->_checkLightAgainstPortals(light, - frameCount, - portalFrustum, - p->getTargetPortal()); - // remove the planes added by this portal - portalFrustum->removePortalCullingPlanes(p); - } - } - } - break; - case Light::LT_RECTLIGHT: - case Light::LT_SPOTLIGHT: - // spotlights - just check if within illumination range - // Technically, we should check if the portal is within - // the cone of illumination, but for now, we'll leave that - // as a future optimisation. - if (lightToPortal.length() <= light->getAttenuationRange()) - { - // if portal is quad portal it must be pointing towards the light - if ((p->getType() == Portal::PORTAL_TYPE_QUAD && lightToPortal.dotProduct(p->getDerivedDirection()) < 0.0) || - (p->getType() != Portal::PORTAL_TYPE_QUAD)) - { - if (!light->affectsZone(targetZone)) - { - light->addZoneToAffectedZonesList(targetZone); - if (targetZone->getLastVisibleFrame() == frameCount) - { - light->setAffectsVisibleZone(true); - } - // set culling frustum from the portal - portalFrustum->addPortalCullingPlanes(p); - // recurse into the target zone of the portal - p->getTargetZone()->_checkLightAgainstPortals(light, - frameCount, - portalFrustum, - p->getTargetPortal()); - // remove the planes added by this portal - portalFrustum->removePortalCullingPlanes(p); - } - } - } - break; - } - } - } - } - } - - /** Update the zone data for the portals in the zone - * NOTE: All portal spatial data must be up-to-date before calling this routine. - */ - void OctreeZone::updatePortalsZoneData(void) - { - PortalList transferPortalList; - AntiPortalList transferAntiPortalList; - // check each portal to see if it's intersecting another portal of smaller size - for ( PortalList::iterator it = mPortals.begin(); it != mPortals.end(); ++it ) - { - Portal * p = *it; - bool portalNeedUpdate = p->needUpdate(); - - Real pRadius = p->getDerivedRadius(); - - // First we check against portals in the SAME zone (and only if they have a - // target zone different from the home zone) - // Here we check only against portals that moved and of smaller size. - - // We do not need to check portal againts previous portals - // since it would have been already checked. - // Hence we start with the next portal after the current portal. - PortalList::iterator it2 = it; - for ( ++it2; it2 != mPortals.end(); ++it2 ) - { - Portal * p2 = (*it2); - - // Skip portal if it doesn't need updating. - // If both portals are not moving, then there's no need to check between them. - if (!portalNeedUpdate && !p2->needUpdate()) continue; - - // Skip portal if it's not pointing to another zone. - if (p2->getTargetZone() == this) continue; - - // Skip portal if it's pointing to the same target zone as this portal points to - if (p2->getTargetZone() == p->getTargetZone()) continue; - - if (pRadius > p2->getDerivedRadius()) - { - // Portal#1 is bigger than Portal#2, check for crossing - if (p2->getCurrentHomeZone() != p->getTargetZone() && p2->crossedPortal(p)) - { - // portal#2 crossed portal#1 - flag portal#2 to be moved to portal#1's target zone - p2->setNewHomeZone(p->getTargetZone()); - transferPortalList.push_back(p2); - } - } - else if (pRadius < p2->getDerivedRadius()) - { - // Portal #2 is bigger than Portal #1, check for crossing - if (p->getCurrentHomeZone() != p2->getTargetZone() && p->crossedPortal(p2)) - { - // portal#1 crossed portal#2 - flag portal#1 to be moved to portal#2's target zone - p->setNewHomeZone(p2->getTargetZone()); - transferPortalList.push_back(p); - continue; - } - } - } - - // Secondly we check againts the antiportals of this zone. - for (AntiPortalList::iterator ait = mAntiPortals.begin(); ait != mAntiPortals.end(); ++ait) - { - AntiPortal* ap = (*ait); - - // Skip portal if it doesn't need updating. - // If both portals are not moving, then there's no need to check between them. - if (!portalNeedUpdate && !ap->needUpdate()) continue; - - // only check for crossing if AntiPortal smaller than portal. - if (pRadius > ap->getDerivedRadius()) - { - // Portal#1 is bigger than AntiPortal, check for crossing - if (ap->crossedPortal(p)) - { - // AntiPortal crossed Portal#1 - flag AntiPortal to be moved to Portal#1's target zone - ap->setNewHomeZone(p->getTargetZone()); - transferAntiPortalList.push_back(ap); - } - } - } - - // Skip portal if it doesn't need updating. - if (!portalNeedUpdate) continue; - - // Thirdly we check against portals in the target zone (and only if that target - // zone is different from the home zone) - PCZone * tzone = p->getTargetZone(); - if (tzone != this) - { - for ( PortalList::iterator it3 = tzone->mPortals.begin(); it3 != tzone->mPortals.end(); ++it3 ) - { - Portal * p3 = (*it3); - // only check against bigger regular portals - if (pRadius < p3->getDerivedRadius()) - { - // Portal#3 is bigger than Portal#1, check for crossing - if (p->getCurrentHomeZone() != p3->getTargetZone() && p->crossedPortal(p3)) - { - // Portal#1 crossed Portal#3 - switch target zones for Portal#1 - p->setTargetZone(p3->getTargetZone()); - break; - } - } - } - } - } - // transfer any portals to new zones that have been flagged - for ( PortalList::iterator it = transferPortalList.begin(); it != transferPortalList.end(); ++it ) - { - Portal * p = *it; - if (p->getNewHomeZone() != 0) - { - _removePortal(p); - p->getNewHomeZone()->_addPortal(p); - p->setNewHomeZone(0); - } - } - // transfer any anti portals to new zones that have been flagged - for (AntiPortalList::iterator it = transferAntiPortalList.begin(); it != transferAntiPortalList.end(); ++it) - { - AntiPortal* p = *it; - if (p->getNewHomeZone() != 0) - { - _removeAntiPortal(p); - p->getNewHomeZone()->_addAntiPortal(p); - p->setNewHomeZone(0); - } - } - } - - /** Mark nodes dirty base on moving portals. */ - void OctreeZone::dirtyNodeByMovingPortals(void) - { - // Octree zone is a space partitioned zone. - // Hence we can smartly grab nodes of interest and flag them. - for ( PortalList::iterator it = mPortals.begin(); it != mPortals.end(); ++it ) - { - Portal* p = *it; - if (p->needUpdate()) - { - PCZSceneNodeList nodeList; - mOctree->_findNodes(p->getAAB(), nodeList, NULL, true, false); - PCZSceneNodeList::iterator i = nodeList.begin(); - while ( i != nodeList.end() ) - { - (*i)->setMoved(true); - ++i; - } - } - } - } - - /* The following function checks if a node has left it's current home zone. - * This is done by checking each portal in the zone. If the node has crossed - * the portal, then the current zone is no longer the home zone of the node. The - * function then recurses into the connected zones. Once a zone is found where - * the node does NOT cross out through a portal, that zone is the new home zone. - NOTE: For this function to work, the node must start out in the proper zone to - begin with! - */ - PCZone* OctreeZone::updateNodeHomeZone( PCZSceneNode * pczsn, bool allowBackTouches ) - { - // default to newHomeZone being the current home zone - PCZone * newHomeZone = pczsn->getHomeZone(); - - // Check all portals of the start zone for crossings! - Portal* portal; - PortalList::iterator pi, piend; - piend = mPortals.end(); - for (pi = mPortals.begin(); pi != piend; pi++) - { - portal = *pi; - - Portal::PortalIntersectResult pir = portal->intersects(pczsn); - switch (pir) - { - default: - case Portal::NO_INTERSECT: // node does not intersect portal - do nothing - case Portal::INTERSECT_NO_CROSS:// node intersects but does not cross portal - do nothing - break; - case Portal::INTERSECT_BACK_NO_CROSS:// node intersects but on the back of the portal - if (allowBackTouches) - { - // node is on wrong side of the portal - fix if we're allowing backside touches - if (portal->getTargetZone() != this && - portal->getTargetZone() != pczsn->getHomeZone()) - { - // set the home zone of the node to the target zone of the portal - pczsn->setHomeZone(portal->getTargetZone()); - // continue checking for portal crossings in the new zone - newHomeZone = portal->getTargetZone()->updateNodeHomeZone(pczsn, false); - } - } - break; - case Portal::INTERSECT_CROSS: - // node intersects and crosses the portal - recurse into that zone as new home zone - if (portal->getTargetZone() != this && - portal->getTargetZone() != pczsn->getHomeZone()) - { - // set the home zone of the node to the target zone of the portal - pczsn->setHomeZone(portal->getTargetZone()); - // continue checking for portal crossings in the new zone - newHomeZone = portal->getTargetZone()->updateNodeHomeZone(pczsn, true); - } - break; - } - } - - // return the new home zone - return newHomeZone; - - } - - /* - // Recursively walk the zones, adding all visible SceneNodes to the list of visible nodes. - */ - void OctreeZone::findVisibleNodes(PCZCamera *camera, - NodeList & visibleNodeList, - RenderQueue * queue, - VisibleObjectsBoundsInfo* visibleBounds, - bool onlyShadowCasters, - bool displayNodes, - bool showBoundingBoxes) - { - - //return immediately if nothing is in the zone. - if (mHomeNodeList.empty() && - mVisitorNodeList.empty() && - mPortals.empty()) - return ; - - // Else, the zone is automatically assumed to be visible since either - // it is the camera the zone is in, or it was reached because - // a connecting portal was deemed visible to the camera. - - // enable sky if called to do so for this zone - if (mHasSky) - { - // enable sky - mPCZSM->enableSky(true); - } - - // Recursively find visible nodes in the zone - walkOctree(camera, - visibleNodeList, - queue, - mOctree, - visibleBounds, - false, - onlyShadowCasters, - displayNodes, - showBoundingBoxes); - - // Here we merge both portal and antiportal visible to the camera into one list. - // Then we sort them in the order from nearest to furthest from camera. - PortalBaseList sortedPortalList; - for (AntiPortalList::iterator iter = mAntiPortals.begin(); iter != mAntiPortals.end(); ++iter) - { - AntiPortal* portal = *iter; - if (camera->isVisible(portal)) - { - sortedPortalList.push_back(portal); - } - } - for (PortalList::iterator iter = mPortals.begin(); iter != mPortals.end(); ++iter) - { - Portal* portal = *iter; - if (camera->isVisible(portal)) - { - sortedPortalList.push_back(portal); - } - } - const Vector3& cameraOrigin(camera->getDerivedPosition()); - std::sort(sortedPortalList.begin(), sortedPortalList.end(), - PortalSortDistance(cameraOrigin)); - - // create a standalone frustum for anti portal use. - // we're doing this instead of using camera because we don't need - // to do camera frustum check again. - PCZFrustum antiPortalFrustum; - antiPortalFrustum.setOrigin(cameraOrigin); - antiPortalFrustum.setProjectionType(camera->getProjectionType()); - - // now we do culling check and remove hidden portals. - // whenever we get a portal in the main loop, we can be sure that it is not - // occluded by AntiPortal. So we do traversal right there and then. - // This is because the portal list has been sorted. - size_t sortedPortalListCount = sortedPortalList.size(); - for (size_t i = 0; i < sortedPortalListCount; ++i) - { - PortalBase* portalBase = sortedPortalList[i]; - if (!portalBase) continue; // skip removed portal. - - if (portalBase->getTypeFlags() == PortalFactory::FACTORY_TYPE_FLAG) - { - Portal* portal = static_cast(portalBase); - // portal is visible. Add the portal as extra culling planes to camera - int planes_added = camera->addPortalCullingPlanes(portal); - // tell target zone it's visible this frame - portal->getTargetZone()->setLastVisibleFrame(mLastVisibleFrame); - portal->getTargetZone()->setLastVisibleFromCamera(camera); - // recurse into the connected zone - portal->getTargetZone()->findVisibleNodes(camera, - visibleNodeList, - queue, - visibleBounds, - onlyShadowCasters, - displayNodes, - showBoundingBoxes); - if (planes_added > 0) - { - // Then remove the extra culling planes added before going to the next portal in the list. - camera->removePortalCullingPlanes(portal); - } - } - else if (i < sortedPortalListCount) // skip antiportal test if it is the last item in the list. - { - // this is an anti portal. So we use it to test preceding portals in the list. - AntiPortal* antiPortal = static_cast(portalBase); - int planes_added = antiPortalFrustum.addPortalCullingPlanes(antiPortal); - - for (size_t j = i + 1; j < sortedPortalListCount; ++j) - { - PortalBase* otherPortal = sortedPortalList[j]; - // Since this is an antiportal, we are doing the inverse of the test. - // Here if the portal is fully visible in the anti portal fustrum, it means it's hidden. - if (otherPortal && antiPortalFrustum.isFullyVisible(otherPortal)) - sortedPortalList[j] = NULL; - } - - if (planes_added > 0) - { - // Then remove the extra culling planes added before going to the next portal in the list. - antiPortalFrustum.removePortalCullingPlanes(antiPortal); - } - } - } - } - - void OctreeZone::walkOctree(PCZCamera *camera, - NodeList & visibleNodeList, - RenderQueue *queue, - Octree *octant, - VisibleObjectsBoundsInfo* visibleBounds, - bool foundvisible, - bool onlyShadowCasters, - bool displayNodes, - bool showBoundingBoxes) - { - - //return immediately if nothing is in the node. - if ( octant -> numNodes() == 0 ) - return ; - - PCZCamera::Visibility v = PCZCamera::NONE; - - if ( foundvisible ) - { - v = PCZCamera::FULL; - } - - else if ( octant == mOctree ) - { - v = PCZCamera::PARTIAL; - } - - else - { - AxisAlignedBox box; - octant -> _getCullBounds( &box ); - v = camera -> getVisibility( box ); - } - - - // if the octant is visible, or if it's the root node... - if ( v != PCZCamera::NONE ) - { - //Add stuff to be rendered; - PCZSceneNodeList::iterator it = octant -> mNodes.begin(); - - bool vis = true; - - while ( it != octant -> mNodes.end() ) - { - PCZSceneNode * sn = *it; - // if the scene node is already visible, then we can skip it - if (sn->getLastVisibleFrame() != mLastVisibleFrame || - sn->getLastVisibleFromCamera() != camera) - { - // if this octree is partially visible, manually cull all - // scene nodes attached directly to this level. - if ( v == PCZCamera::PARTIAL ) - { - vis = camera -> isVisible( sn -> _getWorldAABB() ); - } - if ( vis ) - { - // add the node to the render queue - sn -> _addToRenderQueue(camera, queue, onlyShadowCasters, visibleBounds ); - // add it to the list of visible nodes - visibleNodeList.push_back( sn ); - // if we are displaying nodes, add the node renderable to the queue - if ( mPCZSM->getDebugDrawer() ) - { - mPCZSM->getDebugDrawer()->drawSceneNode(sn); - } - // flag the node as being visible this frame - sn->setLastVisibleFrame(mLastVisibleFrame); - sn->setLastVisibleFromCamera(camera); - } - } - ++it; - } - - Octree* child; - bool childfoundvisible = (v == PCZCamera::FULL); - if ( (child = octant -> mChildren[ 0 ][ 0 ][ 0 ]) != 0 ) - walkOctree( camera, visibleNodeList, queue, child, visibleBounds, childfoundvisible, onlyShadowCasters, displayNodes, showBoundingBoxes ); - - if ( (child = octant -> mChildren[ 1 ][ 0 ][ 0 ]) != 0 ) - walkOctree( camera, visibleNodeList, queue, child, visibleBounds, childfoundvisible, onlyShadowCasters, displayNodes, showBoundingBoxes ); - - if ( (child = octant -> mChildren[ 0 ][ 1 ][ 0 ]) != 0 ) - walkOctree( camera, visibleNodeList, queue, child, visibleBounds, childfoundvisible, onlyShadowCasters, displayNodes, showBoundingBoxes ); - - if ( (child = octant -> mChildren[ 1 ][ 1 ][ 0 ]) != 0 ) - walkOctree( camera, visibleNodeList, queue, child, visibleBounds, childfoundvisible, onlyShadowCasters, displayNodes, showBoundingBoxes ); - - if ( (child = octant -> mChildren[ 0 ][ 0 ][ 1 ]) != 0 ) - walkOctree( camera, visibleNodeList, queue, child, visibleBounds, childfoundvisible, onlyShadowCasters, displayNodes, showBoundingBoxes ); - - if ( (child = octant -> mChildren[ 1 ][ 0 ][ 1 ]) != 0 ) - walkOctree( camera, visibleNodeList, queue, child, visibleBounds, childfoundvisible, onlyShadowCasters, displayNodes, showBoundingBoxes ); - - if ( (child = octant -> mChildren[ 0 ][ 1 ][ 1 ]) != 0 ) - walkOctree( camera, visibleNodeList, queue, child, visibleBounds, childfoundvisible, onlyShadowCasters, displayNodes, showBoundingBoxes ); - - if ( (child = octant -> mChildren[ 1 ][ 1 ][ 1 ]) != 0 ) - walkOctree( camera, visibleNodeList, queue, child, visibleBounds, childfoundvisible, onlyShadowCasters, displayNodes, showBoundingBoxes ); - - } - } - - // --- find nodes which intersect various types of BV's --- - - void OctreeZone::_findNodes(const AxisAlignedBox &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude ) - { - // if this zone has an enclosure, check against the enclosure AABB first - if (mEnclosureNode) - { - if (!mEnclosureNode->_getWorldAABB().intersects(t)) - { - // AABB of zone does not intersect t, just return. - return; - } - } - - // use the Octree to more efficiently find nodes intersecting the aab - mOctree->_findNodes(t, list, exclude, includeVisitors, false); - - // if asked to, recurse through portals - if (recurseThruPortals) - { - PortalList::iterator pit = mPortals.begin(); - while ( pit != mPortals.end() ) - { - Portal * portal = *pit; - // check portal versus boundign box - if (portal->intersects(t)) - { - // make sure portal hasn't already been recursed through - PortalList::iterator pit2 = std::find(visitedPortals.begin(), visitedPortals.end(), portal); - if (pit2 == visitedPortals.end()) - { - // save portal to the visitedPortals list - visitedPortals.push_front(portal); - // recurse into the connected zone - portal->getTargetZone()->_findNodes(t, - list, - visitedPortals, - includeVisitors, - recurseThruPortals, - exclude); - } - } - pit++; - } - } - - } - - void OctreeZone::_findNodes(const Sphere &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude ) - { - // if this zone has an enclosure, check against the enclosure AABB first - if (mEnclosureNode) - { - if (!mEnclosureNode->_getWorldAABB().intersects(t)) - { - // AABB of zone does not intersect t, just return. - return; - } - } - - // use the Octree to more efficiently find nodes intersecting the sphere - mOctree->_findNodes(t, list, exclude, includeVisitors, false); - - // if asked to, recurse through portals - if (recurseThruPortals) - { - PortalList::iterator pit = mPortals.begin(); - while ( pit != mPortals.end() ) - { - Portal * portal = *pit; - // check portal versus boundign box - if (portal->intersects(t)) - { - // make sure portal hasn't already been recursed through - PortalList::iterator pit2 = std::find(visitedPortals.begin(), visitedPortals.end(), portal); - if (pit2 == visitedPortals.end()) - { - // save portal to the visitedPortals list - visitedPortals.push_front(portal); - // recurse into the connected zone - portal->getTargetZone()->_findNodes(t, - list, - visitedPortals, - includeVisitors, - recurseThruPortals, - exclude); - } - } - pit++; - } - } - - } - - void OctreeZone::_findNodes(const PlaneBoundedVolume &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude) - { - // if this zone has an enclosure, check against the enclosure AABB first - if (mEnclosureNode) - { - if (!t.intersects(mEnclosureNode->_getWorldAABB())) - { - // AABB of zone does not intersect t, just return. - return; - } - } - - // use the Octree to more efficiently find nodes intersecting the plane bounded volume - mOctree->_findNodes(t, list, exclude, includeVisitors, false); - - // if asked to, recurse through portals - if (recurseThruPortals) - { - PortalList::iterator pit = mPortals.begin(); - while ( pit != mPortals.end() ) - { - Portal * portal = *pit; - // check portal versus boundign box - if (portal->intersects(t)) - { - // make sure portal hasn't already been recursed through - PortalList::iterator pit2 = std::find(visitedPortals.begin(), visitedPortals.end(), portal); - if (pit2 == visitedPortals.end()) - { - // save portal to the visitedPortals list - visitedPortals.push_front(portal); - // recurse into the connected zone - portal->getTargetZone()->_findNodes(t, - list, - visitedPortals, - includeVisitors, - recurseThruPortals, - exclude); - } - } - pit++; - } - } - - } - - void OctreeZone::_findNodes(const Ray &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude ) - { - // if this zone has an enclosure, check against the enclosure AABB first - if (mEnclosureNode) - { - std::pair nsect = t.intersects(mEnclosureNode->_getWorldAABB()); - if (!nsect.first) - { - // AABB of zone does not intersect t, just return. - return; - } - } - - // use the Octree to more efficiently find nodes intersecting the ray - mOctree->_findNodes(t, list, exclude, includeVisitors, false); - - // if asked to, recurse through portals - if (recurseThruPortals) - { - PortalList::iterator pit = mPortals.begin(); - while ( pit != mPortals.end() ) - { - Portal * portal = *pit; - // check portal versus boundign box - if (portal->intersects(t)) - { - // make sure portal hasn't already been recursed through - PortalList::iterator pit2 = std::find(visitedPortals.begin(), visitedPortals.end(), portal); - if (pit2 == visitedPortals.end()) - { - // save portal to the visitedPortals list - visitedPortals.push_front(portal); - // recurse into the connected zone - portal->getTargetZone()->_findNodes(t, - list, - visitedPortals, - includeVisitors, - recurseThruPortals, - exclude); - } - } - pit++; - } - } - } - - /** called when the scene manager creates a camera because - some zone managers (like TerrainZone) need the camera info. - */ - void OctreeZone::notifyCameraCreated( Camera* c ) - { - } - //------------------------------------------------------------------------- - void OctreeZone::notifyWorldGeometryRenderQueue(uint8 qid) - { - } - //------------------------------------------------------------------------- - void OctreeZone::notifyBeginRenderScene(void) - { - } - //------------------------------------------------------------------------- - void OctreeZone::setZoneGeometry(const String &filename, PCZSceneNode * parentNode) - { - String entityName, nodeName; - entityName = this->getName() + "_entity"; - nodeName = this->getName() + "_Node"; - Entity *ent = mPCZSM->createEntity(entityName , filename ); - // create a node for the entity - PCZSceneNode * node; - node = (PCZSceneNode*)(parentNode->createChildSceneNode(nodeName)); - // attach the entity to the node - node->attachObject(ent); - // set the node as the enclosure node - setEnclosureNode(node); - } - //------------------------------------------------------------------------- - void OctreeZone::getAABB(AxisAlignedBox & aabb) - { - // get the Octree bounding box - aabb = mOctree->mBox; - } - //------------------------------------------------------------------------- - void OctreeZone::init(AxisAlignedBox &box, int depth) - { - if ( mOctree != 0 ) - OGRE_DELETE mOctree; - - mOctree = OGRE_NEW Octree( this, 0 ); - - mMaxDepth = depth; - mBox = box; - - mOctree -> mBox = box; - - Vector3 min = box.getMinimum(); - - Vector3 max = box.getMaximum(); - - mOctree -> mHalfSize = ( max - min ) / 2; - } - - void OctreeZone::resize( const AxisAlignedBox &box ) - { - // delete the octree - OGRE_DELETE mOctree; - // create a new octree - mOctree = OGRE_NEW Octree( this, 0 ); - // set the octree bounding box - mOctree->mBox = box; - const Vector3 &min = box.getMinimum(); - const Vector3 &max = box.getMaximum(); - mOctree->mHalfSize = ( max - min ) * 0.5f; - - OctreeZoneData * ozd; - PCZSceneNodeList::iterator it = mHomeNodeList.begin(); - while ( it != mHomeNodeList.end() ) - { - PCZSceneNode * on = ( *it ); - ozd = (OctreeZoneData*)(on->getZoneData(this)); - ozd -> setOctant( 0 ); - updateNodeOctant( ozd ); - ++it; - } - - it = mVisitorNodeList.begin(); - while ( it != mVisitorNodeList.end() ) - { - PCZSceneNode * on = ( *it ); - ozd = (OctreeZoneData*)(on->getZoneData(this)); - ozd -> setOctant( 0 ); - updateNodeOctant( ozd ); - ++it; - } - - } - bool OctreeZone::setOption( const String & key, const void * val ) - { - if ( key == "Size" ) - { - resize( * static_cast < const AxisAlignedBox * > ( val ) ); - return true; - } - - else if ( key == "Depth" ) - { - mMaxDepth = * static_cast < const int * > ( val ); - // copy the box since resize will delete mOctree and reference won't work - AxisAlignedBox box = mOctree->mBox; - resize(box); - return true; - } - -/* else if ( key == "ShowOctree" ) - { - mShowBoxes = * static_cast < const bool * > ( val ); - return true; - }*/ - return false; - } - - void OctreeZone::updateNodeOctant( OctreeZoneData * zoneData ) - { - const AxisAlignedBox& box = zoneData -> mOctreeWorldAABB; - - if ( box.isNull() ) - return ; - - // Skip if octree has been destroyed (shutdown conditions) - if (!mOctree) - return; - - PCZSceneNode* node = zoneData->mAssociatedNode; - if ( zoneData->getOctant() == 0 ) - { - //if outside the octree, force into the root node. - if ( ! zoneData->_isIn( mOctree -> mBox ) ) - mOctree->_addNode( node ); - else - addNodeToOctree( node, mOctree ); - return ; - } - - if ( ! zoneData->_isIn( zoneData->getOctant()->mBox ) ) - { - - //if outside the octree, force into the root node. - if ( !zoneData->_isIn( mOctree -> mBox ) ) - { - // skip if it's already in the root node. - if (((OctreeZoneData*)node->getZoneData(this))->getOctant() == mOctree) - return; - - removeNodeFromOctree( node ); - mOctree->_addNode( node ); - } - else - addNodeToOctree( node, mOctree ); - } - } - - /** Only removes the node from the octree. It leaves the octree, even if it's empty. - */ - void OctreeZone::removeNodeFromOctree( PCZSceneNode * n ) - { - // Skip if octree has been destroyed (shutdown conditions) - if (!mOctree) - return; - - Octree * oct = ((OctreeZoneData*)n->getZoneData(this)) -> getOctant(); - - if ( oct ) - { - oct -> _removeNode( n ); - } - - ((OctreeZoneData*)n->getZoneData(this))->setOctant(0); - } - - - void OctreeZone::addNodeToOctree( PCZSceneNode * n, Octree *octant, int depth ) - { - - // Skip if octree has been destroyed (shutdown conditions) - if (!mOctree) - return; - - const AxisAlignedBox& bx = n -> _getWorldAABB(); - - - //if the octree is twice as big as the scene node, - //we will add it to a child. - if ( ( depth < mMaxDepth ) && octant -> _isTwiceSize( bx ) ) - { - int x, y, z; - octant -> _getChildIndexes( bx, &x, &y, &z ); - - if ( octant -> mChildren[ x ][ y ][ z ] == 0 ) - { - octant -> mChildren[ x ][ y ][ z ] = OGRE_NEW Octree( this, octant ); - const Vector3& octantMin = octant -> mBox.getMinimum(); - const Vector3& octantMax = octant -> mBox.getMaximum(); - Vector3 min, max; - - if ( x == 0 ) - { - min.x = octantMin.x; - max.x = ( octantMin.x + octantMax.x ) / 2; - } - - else - { - min.x = ( octantMin.x + octantMax.x ) / 2; - max.x = octantMax.x; - } - - if ( y == 0 ) - { - min.y = octantMin.y; - max.y = ( octantMin.y + octantMax.y ) / 2; - } - - else - { - min.y = ( octantMin.y + octantMax.y ) / 2; - max.y = octantMax.y; - } - - if ( z == 0 ) - { - min.z = octantMin.z; - max.z = ( octantMin.z + octantMax.z ) / 2; - } - - else - { - min.z = ( octantMin.z + octantMax.z ) / 2; - max.z = octantMax.z; - } - - octant -> mChildren[ x ][ y ][ z ] -> mBox.setExtents( min, max ); - octant -> mChildren[ x ][ y ][ z ] -> mHalfSize = ( max - min ) / 2; - } - - addNodeToOctree( n, octant -> mChildren[ x ][ y ][ z ], ++depth ); - - } - else - { - if (((OctreeZoneData*)n->getZoneData(this))->getOctant() == octant) - return; - - removeNodeFromOctree( n ); - octant -> _addNode( n ); - } - } - - /***********************************************************************\ - OctreeZoneData - OctreeZone-specific Data structure for Scene Nodes - ************************************************************************/ - - OctreeZoneData::OctreeZoneData(PCZSceneNode * node, PCZone * zone) - : ZoneData(node, zone) - { - mOctant = 0; - } - - OctreeZoneData::~OctreeZoneData() - { - } - - /* Update the octreezone specific data for a node */ - void OctreeZoneData::update(void) - { - mOctreeWorldAABB.setNull(); - - // need to use object iterator here. - for (auto m : mAssociatedNode->getAttachedObjects()) - { - // merge world bounds of object - mOctreeWorldAABB.merge( m->getWorldBoundingBox(true) ); - } - - - // update the Octant for the node because things might have moved. - // if it hasn't been added to the octree, add it, and if has moved - // enough to leave it's current node, we'll update it. - if ( ! mOctreeWorldAABB.isNull() ) - { - static_cast < OctreeZone * > ( mAssociatedZone ) -> updateNodeOctant( this ); - } - } - - /** Since we are loose, only check the center. - */ - bool OctreeZoneData::_isIn( AxisAlignedBox &box ) - { - // Always fail if not in the scene graph or box is null - if (!mAssociatedNode->isInSceneGraph() || box.isNull()) return false; - - // Always succeed if AABB is infinite - if (box.isInfinite()) - return true; - - Vector3 center = mAssociatedNode->_getWorldAABB().getMaximum().midPoint( mAssociatedNode->_getWorldAABB().getMinimum() ); - - Vector3 bmin = box.getMinimum(); - Vector3 bmax = box.getMaximum(); - - bool centre = ( bmax > center && bmin < center ); - if (!centre) - return false; - - // Even if covering the centre line, need to make sure this BB is not large - // enough to require being moved up into parent. When added, bboxes would - // end up in parent due to cascade but when updating need to deal with - // bbox growing too large for this child - Vector3 octreeSize = bmax - bmin; - Vector3 nodeSize = mAssociatedNode->_getWorldAABB().getMaximum() - mAssociatedNode->_getWorldAABB().getMinimum(); - return nodeSize < octreeSize; - } - - //------------------------------------------------------------------------- - // OctreeZoneFactory functions - //String octreeZoneString = String("ZoneType_Octree"); - OctreeZoneFactory::OctreeZoneFactory() : PCZoneFactory("ZoneType_Octree") - { - } - OctreeZoneFactory::~OctreeZoneFactory() - { - } - bool OctreeZoneFactory::supportsPCZoneType(const String& zoneType) - { - if (mFactoryTypeName == zoneType) - { - return true; - } - return false; - } - PCZone* OctreeZoneFactory::createPCZone(PCZSceneManager * pczsm, const String& zoneName) - { - return OGRE_NEW OctreeZone(pczsm, zoneName); - } - -} diff --git a/PlugIns/OctreeZone/src/OgreOctreeZoneDll.cpp b/PlugIns/OctreeZone/src/OgreOctreeZoneDll.cpp deleted file mode 100644 index 242f4f0a46c..00000000000 --- a/PlugIns/OctreeZone/src/OgreOctreeZoneDll.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -OgreOctreeZoneSceneManagerDll.cpp - description ------------------------------------------------------------------------------ -begin : Wed Feb 21 2007 -author : Eric Cha -email : ericc@xenopi.com ------------------------------------------------------------------------------ -*/ - -#include "OgreOctreeZonePrerequisites.h" -#include "OgreRoot.h" -#include "OgreOctreeZonePlugin.h" - -#ifndef OGRE_STATIC_LIB - -namespace Ogre -{ - static OctreeZonePlugin* OZPlugin; - extern "C" void _OgreOctreeZonePluginExport dllStartPlugin(void); - extern "C" void _OgreOctreeZonePluginExport dllStopPlugin(void); - - extern "C" void _OgreOctreeZonePluginExport dllStartPlugin( void ) - { - // Create new scene manager - OZPlugin = OGRE_NEW OctreeZonePlugin(); - - // Register - Root::getSingleton().installPlugin(OZPlugin); - - } - extern "C" void _OgreOctreeZonePluginExport dllStopPlugin( void ) - { - Root::getSingleton().uninstallPlugin(OZPlugin); - OGRE_DELETE OZPlugin; - } -} - -#endif diff --git a/PlugIns/OctreeZone/src/OgreOctreeZoneOctree.cpp b/PlugIns/OctreeZone/src/OgreOctreeZoneOctree.cpp deleted file mode 100644 index 87ca7ea93d1..00000000000 --- a/PlugIns/OctreeZone/src/OgreOctreeZoneOctree.cpp +++ /dev/null @@ -1,692 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -octree.cpp - Slightly modified version of Octree.cpp from TerrainSM. - ------------------------------------------------------------------------------ -begin : Mon Sep 30 2002 -copyright : (C) 2002 by Jon Anderson -email : janders@users.sf.net - -Modified to use with PCZones 2007 by Eric Cha ------------------------------------------------------------------------------ -*/ - -#include "OgreOctreeZoneOctree.h" -#include "OgrePCZSceneNode.h" -#include "OgreOctreeZone.h" -#include "OgreRay.h" -#include "OgreWireBoundingBox.h" - -namespace Ogre -{ - namespace { - /* INTERSECTION UTILITY FUNCTIONS ***/ - - enum Intersection - { - OUTSIDE=0, - INSIDE=1, - INTERSECT=2 - }; - - Intersection intersect( const Ray &one, const AxisAlignedBox &two ) - { - // Null box? - if (two.isNull()) return OUTSIDE; - // Infinite box? - if (two.isInfinite()) return INTERSECT; - - bool inside = true; - const Vector3& twoMin = two.getMinimum(); - const Vector3& twoMax = two.getMaximum(); - Vector3 origin = one.getOrigin(); - Vector3 dir = one.getDirection(); - - Vector3 maxT(-1, -1, -1); - - int i = 0; - for(i=0; i<3; i++ ) - { - if( origin[i] < twoMin[i] ) - { - inside = false; - if( dir[i] > 0 ) - { - maxT[i] = (twoMin[i] - origin[i])/ dir[i]; - } - } - else if( origin[i] > twoMax[i] ) - { - inside = false; - if( dir[i] < 0 ) - { - maxT[i] = (twoMax[i] - origin[i]) / dir[i]; - } - } - } - - if( inside ) - { - return INTERSECT; - } - int whichPlane = 0; - if( maxT[1] > maxT[whichPlane]) - whichPlane = 1; - if( maxT[2] > maxT[whichPlane]) - whichPlane = 2; - - if( ((int)maxT[whichPlane]) & 0x80000000 ) - { - return OUTSIDE; - } - for(i=0; i<3; i++ ) - { - if( i!= whichPlane ) - { - float f = origin[i] + maxT[whichPlane] * dir[i]; - if ( f < (twoMin[i] - 0.00001f) || - f > (twoMax[i] +0.00001f ) ) - { - return OUTSIDE; - } - } - } - - return INTERSECT; - - } - - - /** Checks how the axis aligned box intersects with the plane bounded volume - */ - Intersection intersect( const PlaneBoundedVolume &one, const AxisAlignedBox &two ) - { - // Null box? - if (two.isNull()) return OUTSIDE; - // Infinite box? - if (two.isInfinite()) return INTERSECT; - - // Get centre of the box - Vector3 centre = two.getCenter(); - // Get the half-size of the box - Vector3 halfSize = two.getHalfSize(); - - // For each plane, see if all points are on the negative side - // If so, object is not visible. - // If one or more are, it's partial. - // If all aren't, full - bool all_inside = true; - PlaneList::const_iterator i, iend; - iend = one.planes.end(); - for (i = one.planes.begin(); i != iend; ++i) - { - const Plane& plane = *i; - - Plane::Side side = plane.getSide(centre, halfSize); - if(side == one.outside) - return OUTSIDE; - if(side == Plane::BOTH_SIDE) - all_inside = false; - } - - if ( all_inside ) - return INSIDE; - else - return INTERSECT; - - } - - - /** Checks how the second box intersects with the first. - */ - Intersection intersect( const AxisAlignedBox &one, const AxisAlignedBox &two ) - { - // Null box? - if (one.isNull() || two.isNull()) return OUTSIDE; - if (one.isInfinite()) return INSIDE; - if (two.isInfinite()) return INTERSECT; - - - const Vector3& insideMin = two.getMinimum(); - const Vector3& insideMax = two.getMaximum(); - - const Vector3& outsideMin = one.getMinimum(); - const Vector3& outsideMax = one.getMaximum(); - - if ( insideMax.x < outsideMin.x || - insideMax.y < outsideMin.y || - insideMax.z < outsideMin.z || - insideMin.x > outsideMax.x || - insideMin.y > outsideMax.y || - insideMin.z > outsideMax.z ) - { - return OUTSIDE; - } - - bool full = ( insideMin.x > outsideMin.x && - insideMin.y > outsideMin.y && - insideMin.z > outsideMin.z && - insideMax.x < outsideMax.x && - insideMax.y < outsideMax.y && - insideMax.z < outsideMax.z ); - - if ( full ) - return INSIDE; - else - return INTERSECT; - - } - - /** Checks how the box intersects with the sphere. - */ - Intersection intersect( const Sphere &one, const AxisAlignedBox &two ) - { - // Null box? - if (two.isNull()) return OUTSIDE; - if (two.isInfinite()) return INTERSECT; - - float sradius = one.getRadius(); - - sradius *= sradius; - - Vector3 scenter = one.getCenter(); - - const Vector3& twoMin = two.getMinimum(); - const Vector3& twoMax = two.getMaximum(); - - float s, d = 0; - - Vector3 mndistance = ( twoMin - scenter ); - Vector3 mxdistance = ( twoMax - scenter ); - - if ( mndistance.squaredLength() < sradius && - mxdistance.squaredLength() < sradius ) - { - return INSIDE; - } - - //find the square of the distance - //from the sphere to the box - for ( int i = 0 ; i < 3 ; i++ ) - { - if ( scenter[ i ] < twoMin[ i ] ) - { - s = scenter[ i ] - twoMin[ i ]; - d += s * s; - } - - else if ( scenter[ i ] > twoMax[ i ] ) - { - s = scenter[ i ] - twoMax[ i ]; - d += s * s; - } - - } - - bool partial = ( d <= sradius ); - - if ( !partial ) - { - return OUTSIDE; - } - - else - { - return INTERSECT; - } - - - } - } - /***************************************************/ - - /** Returns true is the box will fit in a child. - */ - bool Octree::_isTwiceSize( const AxisAlignedBox &box ) const - { - // infinite boxes never fit in a child - always root node - if (box.isInfinite()) - return false; - - Vector3 halfMBoxSize = mBox.getHalfSize(); - Vector3 boxSize = box.getSize(); - return ((boxSize.x <= halfMBoxSize.x) && (boxSize.y <= halfMBoxSize.y) && (boxSize.z <= halfMBoxSize.z)); - - } - - /** It's assumed the the given box has already been proven to fit into - * a child. Since it's a loose octree, only the centers need to be - * compared to find the appropriate node. - */ - void Octree::_getChildIndexes( const AxisAlignedBox &box, int *x, int *y, int *z ) const - { - Vector3 center = mBox.getMaximum().midPoint( mBox.getMinimum() ); - - Vector3 ncenter = box.getMaximum().midPoint( box.getMinimum() ); - - if ( ncenter.x > center.x ) - * x = 1; - else - *x = 0; - - if ( ncenter.y > center.y ) - * y = 1; - else - *y = 0; - - if ( ncenter.z > center.z ) - * z = 1; - else - *z = 0; - - } - - Octree::Octree(PCZone * oz, Octree * parent ) - : mWireBoundingBox(0), - mHalfSize( 0, 0, 0 ) - { - //initialize all children to null. - for ( int i = 0; i < 2; i++ ) - { - for ( int j = 0; j < 2; j++ ) - { - for ( int k = 0; k < 2; k++ ) - { - mChildren[ i ][ j ][ k ] = 0; - } - } - } - mZone = oz; - mParent = parent; - mNumNodes = 0; - } - - Octree::~Octree() - { - //initialize all children to null. - for ( int i = 0; i < 2; i++ ) - { - for ( int j = 0; j < 2; j++ ) - { - for ( int k = 0; k < 2; k++ ) - { - if ( mChildren[ i ][ j ][ k ] != 0 ) - OGRE_DELETE mChildren[ i ][ j ][ k ]; - } - } - } - - if(mWireBoundingBox) - OGRE_DELETE mWireBoundingBox; - - mParent = 0; - } - - void Octree::_addNode( PCZSceneNode * n ) - { - mNodes.insert(n); - ((OctreeZoneData*)n ->getZoneData(mZone))->setOctant( this ); - - //update total counts. - _ref(); - - } - - void Octree::_removeNode( PCZSceneNode * n ) - { - mNodes.erase(n); - ((OctreeZoneData*)n ->getZoneData(mZone))->setOctant( 0 ); - - //update total counts. - _unref(); - } - - void Octree::_getCullBounds( AxisAlignedBox *b ) const - { - b -> setExtents( mBox.getMinimum() - mHalfSize, mBox.getMaximum() + mHalfSize ); - } - - WireBoundingBox* Octree::getWireBoundingBox() - { - // Create a WireBoundingBox if needed - if(mWireBoundingBox == 0) - mWireBoundingBox = OGRE_NEW WireBoundingBox(); - - mWireBoundingBox->setupBoundingBox(mBox); - return mWireBoundingBox; - } - - void Octree::_findNodes(const AxisAlignedBox &t, - PCZSceneNodeList &list, - PCZSceneNode *exclude, - bool includeVisitors, - bool full ) - { - if ( !full ) - { - AxisAlignedBox obox; - _getCullBounds( &obox ); - - Intersection isect = intersect( t, obox ); - - if ( isect == OUTSIDE ) - return ; - - full = ( isect == INSIDE ); - } - - - PCZSceneNodeList::iterator it = mNodes.begin(); - - while ( it != mNodes.end() ) - { - PCZSceneNode * on = ( *it ); - - if ( on != exclude && (on->getHomeZone() == mZone || includeVisitors )) - { - if ( full ) - { - // make sure the node isn't already on the list - list.insert( on ); - } - - else - { - Intersection nsect = intersect( t, on -> _getWorldAABB() ); - - if ( nsect != OUTSIDE ) - { - // make sure the node isn't already on the list - list.insert( on ); - } - } - - } - ++it; - } - - Octree* child; - - if ( (child=mChildren[ 0 ][ 0 ][ 0 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 1 ][ 0 ][ 0 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 0 ][ 1 ][ 0 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 1 ][ 1 ][ 0 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 0 ][ 0 ][ 1 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 1 ][ 0 ][ 1 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 0 ][ 1 ][ 1 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 1 ][ 1 ][ 1 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - } - - void Octree::_findNodes(const Ray &t, - PCZSceneNodeList &list, - PCZSceneNode *exclude, - bool includeVisitors, - bool full ) - { - if ( !full ) - { - AxisAlignedBox obox; - _getCullBounds( &obox ); - - Intersection isect = intersect( t, obox ); - - if ( isect == OUTSIDE ) - return ; - - full = ( isect == INSIDE ); - } - - - PCZSceneNodeList::iterator it = mNodes.begin(); - - while ( it != mNodes.end() ) - { - PCZSceneNode * on = ( *it ); - - if ( on != exclude && (on->getHomeZone() == mZone || includeVisitors )) - { - if ( full ) - { - // make sure the node isn't already on the list - list.insert( on ); - } - - else - { - Intersection nsect = intersect( t, on -> _getWorldAABB() ); - - if ( nsect != OUTSIDE ) - { - // make sure the node isn't already on the list - list.insert( on ); - } - } - - } - ++it; - } - - Octree* child; - - if ( (child=mChildren[ 0 ][ 0 ][ 0 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 1 ][ 0 ][ 0 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 0 ][ 1 ][ 0 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 1 ][ 1 ][ 0 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 0 ][ 0 ][ 1 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 1 ][ 0 ][ 1 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 0 ][ 1 ][ 1 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 1 ][ 1 ][ 1 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - } - - void Octree::_findNodes(const Sphere &t, - PCZSceneNodeList &list, - PCZSceneNode *exclude, - bool includeVisitors, - bool full ) - { - if ( !full ) - { - AxisAlignedBox obox; - _getCullBounds( &obox ); - - Intersection isect = intersect( t, obox ); - - if ( isect == OUTSIDE ) - return ; - - full = ( isect == INSIDE ); - } - - - PCZSceneNodeList::iterator it = mNodes.begin(); - - while ( it != mNodes.end() ) - { - PCZSceneNode * on = ( *it ); - - if ( on != exclude && (on->getHomeZone() == mZone || includeVisitors )) - { - if ( full ) - { - // make sure the node isn't already on the list - list.insert( on ); - } - - else - { - Intersection nsect = intersect( t, on -> _getWorldAABB() ); - - if ( nsect != OUTSIDE ) - { - // make sure the node isn't already on the list - list.insert( on ); - } - } - - } - ++it; - } - - Octree* child; - - if ( (child=mChildren[ 0 ][ 0 ][ 0 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 1 ][ 0 ][ 0 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 0 ][ 1 ][ 0 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 1 ][ 1 ][ 0 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 0 ][ 0 ][ 1 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 1 ][ 0 ][ 1 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 0 ][ 1 ][ 1 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 1 ][ 1 ][ 1 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - } - - - void Octree::_findNodes(const PlaneBoundedVolume &t, - PCZSceneNodeList &list, - PCZSceneNode *exclude, - bool includeVisitors, - bool full ) - { - if ( !full ) - { - AxisAlignedBox obox; - _getCullBounds( &obox ); - - Intersection isect = intersect( t, obox ); - - if ( isect == OUTSIDE ) - return ; - - full = ( isect == INSIDE ); - } - - - PCZSceneNodeList::iterator it = mNodes.begin(); - - while ( it != mNodes.end() ) - { - PCZSceneNode * on = ( *it ); - - if ( on != exclude && (on->getHomeZone() == mZone || includeVisitors )) - { - if ( full ) - { - // make sure the node isn't already on the list - list.insert( on ); - } - - else - { - Intersection nsect = intersect( t, on -> _getWorldAABB() ); - - if ( nsect != OUTSIDE ) - { - // make sure the node isn't already on the list - list.insert( on ); - } - } - - } - ++it; - } - - Octree* child; - - if ( (child=mChildren[ 0 ][ 0 ][ 0 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 1 ][ 0 ][ 0 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 0 ][ 1 ][ 0 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 1 ][ 1 ][ 0 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 0 ][ 0 ][ 1 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 1 ][ 0 ][ 1 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 0 ][ 1 ][ 1 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - if ( (child=mChildren[ 1 ][ 1 ][ 1 ]) != 0 ) - child->_findNodes( t, list, exclude, includeVisitors, full ); - - } - -} diff --git a/PlugIns/OctreeZone/src/OgreOctreeZonePlugin.cpp b/PlugIns/OctreeZone/src/OgreOctreeZonePlugin.cpp deleted file mode 100644 index 66f81f5c6d3..00000000000 --- a/PlugIns/OctreeZone/src/OgreOctreeZonePlugin.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -OgreOctreeZonePlugin.cpp - Octree Zone Plugin class for PCZSceneManager - ------------------------------------------------------------------------------ -begin : Mon Apr 16 2007 -author : Eric Cha -email : ericc@xenopi.com -Code Style Update : ------------------------------------------------------------------------------ -*/ - -#include "OgreOctreeZonePlugin.h" -#include "OgrePCZoneFactory.h" -#include "OgreOctreeZone.h" - -namespace Ogre -{ - const String sPluginName = "Octree Zone Factory"; - //--------------------------------------------------------------------- - OctreeZonePlugin::OctreeZonePlugin() - :mOctreeZoneFactory(0) - { - - } - //--------------------------------------------------------------------- - const String& OctreeZonePlugin::getName() const - { - return sPluginName; - } - //--------------------------------------------------------------------- - void OctreeZonePlugin::install() - { - // Create objects - mOctreeZoneFactory = OGRE_NEW OctreeZoneFactory(); - } - //--------------------------------------------------------------------- - void OctreeZonePlugin::initialise() - { - // Register - PCZoneFactoryManager & pczfm = PCZoneFactoryManager::getSingleton(); - pczfm.registerPCZoneFactory(mOctreeZoneFactory); - } - //--------------------------------------------------------------------- - void OctreeZonePlugin::shutdown() - { - // Unregister - PCZoneFactoryManager & pczfm = PCZoneFactoryManager::getSingleton(); - pczfm.unregisterPCZoneFactory(mOctreeZoneFactory); - } - //--------------------------------------------------------------------- - void OctreeZonePlugin::uninstall() - { - // destroy - OGRE_DELETE mOctreeZoneFactory; - mOctreeZoneFactory = 0; - } - - -} diff --git a/PlugIns/PCZSceneManager/CMakeLists.txt b/PlugIns/PCZSceneManager/CMakeLists.txt deleted file mode 100644 index 30b3a9387e2..00000000000 --- a/PlugIns/PCZSceneManager/CMakeLists.txt +++ /dev/null @@ -1,28 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure PCZ SceneManager build - -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES ${PROJECT_BINARY_DIR}/include/OgrePCZPrerequisites.h) -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") - -add_library(Plugin_PCZSceneManager ${OGRE_LIB_TYPE} ${HEADER_FILES} ${SOURCE_FILES}) -target_link_libraries(Plugin_PCZSceneManager OgreMain) -target_include_directories(Plugin_PCZSceneManager PUBLIC - "$" - $) - -generate_export_header(Plugin_PCZSceneManager - EXPORT_MACRO_NAME _OgrePCZPluginExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgrePCZPrerequisites.h) - -ogre_config_framework(Plugin_PCZSceneManager) -ogre_config_plugin(Plugin_PCZSceneManager) -install(FILES ${HEADER_FILES} DESTINATION include/OGRE/Plugins/PCZSceneManager) diff --git a/PlugIns/PCZSceneManager/docs/changelog.txt b/PlugIns/PCZSceneManager/docs/changelog.txt deleted file mode 100644 index 8bcd94187d7..00000000000 --- a/PlugIns/PCZSceneManager/docs/changelog.txt +++ /dev/null @@ -1,36 +0,0 @@ -UPDATES: -------------- -* (3/17/09) Added support for Antiportals (thanks Lf3thn4d!), fixed PCZTestApp bug and added example Antiportals. -* (12/19/08) Changed line endings to Windows CR/LF standard in OgreOctreeZone.cpp & OgreDefaultZone.cpp -* (12/19/08) Initial coding for anti-portals has started. It is not functional yet, so don't use it. -* (12/19/08) Portals no longer cross over other portals if they both lead to the same zone (this was put in to fix a rare bug - which was causing portals which were "close" to each other to cause inadvertent portal transfers. -* (12/16/08) PCZSceneNode::createChildSceneNode() no longer automatically anchors the new child node if the parent is anchored. -* (12/16/08) You can un-anchor PCZSceneNodes from Zones by calling PCZSceneNode::anchorToZone(0). -* (12/3/08) Moved this list of updates to it's own file (changelog.txt) -* (12/2/08) Numerous Optimizations (thanks Lf3thn4d) - - Update only nodes that moved - - Update only portals that moved - - Update nodes that are within interest of moving portals - - MAJOR CHANGE: Made portal a movable object so that it can track movement - - Optimized portal update code (Less useless check) - - Don't clear visiting node each frame but let updating nodes remove themselves from visiting zones File - -* (11/11/08) PCZFrustum treats infinite bounds as always visible and zero bounds as always invisible (Thanks Fish). -* (10/17/08) PCZoneFactory eats a const String &, so code has been updated to use PCZoneFactory("ZoneType_Default") - instead of PCZoneFactory (String("ZoneType_Default")). -* (10/26/08) PCZSM now zeroes out the SkyBoxObj, SkyPlane, and SkyDome pointers when clearScene() is called. -* (5/8/08) if a scene node is anchored to a zone, then child scene nodes created from that - scene node (via SceneNode::createChildSceneNode()) are also anchored to the same zone. -* (4/24/08) Portals can now be closed & opened (see Portal::close() and Portal::open()). - Closing a portal prevents scene traversal through the portal and also prevents - scene nodes from crossing the portal. -* (4/24/08) Infinite Recursion bug for scene traversal FIXED. This was fixed by adding an - additional culling plane drawn from the actual plane of quad portals. The infinite recursion - bug occurred in situations where a viewer was outside a building, could look straight through - the building back to the outside, and then into another building similarly set up. This - situation is still VERY bad from a performance standpoint, but at least it doesn't crash. -* (03/18/08) The PCZFrustum now uses a Culling Plane Reservoir which eliminates the constant memory - allocations/de-allocations for PCPlanes during the culling process. -* (03/25/08) Light zones now only update affected list when portals move or lights move (Thanks Aulcard) -* (03/25/08) PCZSceneNodes now only save old spatial data when they move (Thanks Aulcard) \ No newline at end of file diff --git a/PlugIns/PCZSceneManager/docs/readme.md b/PlugIns/PCZSceneManager/docs/readme.md deleted file mode 100644 index 7e9bd05e21f..00000000000 --- a/PlugIns/PCZSceneManager/docs/readme.md +++ /dev/null @@ -1,178 +0,0 @@ -# Using the PCZ Scene Manager {#pczscenemanager} - -The Portal-Connected-Zone Scene Manager (PCZSM) is a plugin for Ogre3D which allows traversal of -a scene which is non-homogeneous in structure. Specifically, the PCZSM uses -"Zones" which have their own hierarchy. Zones are connected to other zones -by "Portals" which can be envisioned as 4-point convex planar polygons (or -Spheres or AAB's). - -@tableofcontents - -This document gives basic information on the usage of the PCZSceneManager. -It is not complete, and will change & expand as needed. Note that as of -this writing, the PCZSM has not undergone very extensive testing, nor is -it optimized very much. Assistance in these two areas would be greatly -appreciated. - -@note For an example of PCZSM usage, see the PCZTestApp Sample. It -is probably a lot easier to understand than trying to figure it all out -from this. - -## LOADING & INITIALIZATION - -The PCZSM is loaded just like any other Scene Manager plugin. Included in -the standard PCZSM plugin is the "default" zone. If the user wishes to -utilize the OctreeZone or TerrainZone, the "Plugin_OctreeZone" should be -loaded *after* the PCZSM plugin is loaded. - -Before using the PCZSM, the PCZSceneManager::init(zoneType) function should be called. -During intialization, the user specifies what type of zone (ZoneType_Default, -ZoneType_OCtree, ZoneType_Terrain) the PCZSM should use for the default zone. -The default zone is the zone where entities are placed if they are not -specified to be in other zones. - -## CREATING ZONES - -Once the PCZSM has been initialized, the user can proceed with creating -zones (PCZSceneManager::createZone(zoneType, zoneName)). Zones can be -anything from the outdoors (i.e. a Terrain) to a room in a building, or -a tunnel in a dungeon. Zones can be of any size or shape, and can move. - -NOTE: In the PCZSM, sky rendering (domes, boxes, planes) is associated -with a specific zone. For example, if the user has a building on a terrain, -the sky could be associated with the terrain (i.e. the "outdoors") using -the function PCZSceneManager::setSkyZone(zone). This tells the PCZSM to -only draw the sky when the designated zone is visible. (i.e. only draw -the sky when the 'outdoor' zone is visible). Usually, the Sky should be -associated with the default zone (which is usually used as the "all -encompassing exterior zone"). - -## CREATING PORTALS - -Once the user has created a zone (in addition to the default zone), -they can create portals to attach two zones together. - -To create a portal, the user just calls PCZSceneManager::createPortal(). -NOTE: The user should NOT just instantiate a portal manually (i.e. portal = new Portal) -because the clean up of portals is handled by the scene manager directly. -Instantiating portals using the C++ 'new' command will result in memory leaks -and errors if the scene is destroyed and recreated. - -To destroy a portal use PCZSceneManager::destroyPortal(Portal *p) or -PCZSceneManager::destroyPortal(String & portalName). - - -Then set the portal corner points, attaches it to a node, and then adds it -to the zone (see PCZTestApp -> RoomObject.cpp -> createPortals() function). - -NOTE: Portals currently only connect different zones. The user can't -connect portals to the same zone yet (i.e. no teleporters). This functionality -could be added later. - -Portals can be "closed" (and opened) by calling Portal::setEnable(false) -(and Portal::setEnable(false)). Disabling a portal prevents the scene manager from traversing -through the portal and also prevents scenenodes & ray queries from crossing the portal. -Basically, it turns a portal "off". Disabling an antiportal (see note below about -Creating antiportals) prevents the antiportal from blocking scene traversal through -regular portals. - -Portals can take 3 different forms: quad portals, AAB portals, -and Sphere portals. AAB and Sphere portals do not add any culling planes to the -frustum, and just serve to serve as enclosures for zones which aren't naturally -surrounded by geometry. They function a little different than traditional quad -portals in that they are volumetric, instead of planar (crossing is determined -by going from "inside" to "outside" or vice versa). - -Quad Portals require 4 corner points which are co-planar and form a polygon which -is convex. Quad Portal corners are specified in right-handed counter- -clockwise winding order so that the norm of the portal would be facing -the viewer. - -AAB Portals require 2 corner points (minimum & maximum corners) and form an axis- -aligned box around the zone. IMPORTANT: The AAB portals that are associated with -a node require a node which has the correct size AAB (node->_getWorldAABB()). - -Sphere Portals require 2 corner points (center point, and point on the surface of -the sphere). - -The "direction" norm of AAB and Sphere portals is specified as either -Vector3::UNIT_NEGATIVE_Z or Vector3::UNIT_Z. The first corresponds to a portal -with norm facing 'inward' and the latter corresponds to a portal with norm facing -'outward'. - -NOTE regarding Portal Norms: The Norm of a portal should always point away from the -zone the portal leads to. Another way to think of this is a node will only cross -a portal if it crosses the portal traveling opposite direction of the norm). - -Portals also (currently) require a "matching" portal for proper -scene traversal. In other words, portals always exist in pairs - one in -each zone connected and co-existing in the same location, but facing in -opposite directions. - -It is REQUIRED that a portal be associated with a scene node. Use Portal::setNode() -to associate the portal with a scene node. Once the portal is associated with a -scene node, it will move with the scene node (including rotations or translations). -Because of this, it is also highly recommended (although not required) that -the node a portal is associated with be located at the center of the portal. - -Once all portals in the scene have been created, the user can either manually -assign their zone targets (i.e. the zone which they connect to) or they can -call PCZSceneManager::connectPortalsToTargetZonesByLocation() to do it -automatically. Note that this function requires all portals to have a matching -portal in the target zone. - -## ANTIPORTALS - -Antiportals are a new feature (thanks to Lf3thn4d). Antiportals prevent traversal of -portals located behind them (as viewed from the camera). They are created and manipulated -the same as regular portals (except you don't need to create them in pairs, since they -block scene traversal to other zones instead of connecting them). Only Quad Antiportals -are supported. - -To Create an antiportal, it's very similar to regular portals. All you need to do is call -PCZSceneManager::createAntiPortal("name of the antiportal"), set the corner values, -attach it to a node, and add it to the proper zone. - -## CREATING OBJECTS/ENTITIES - -Once the zones and portals have been created, the user can create objects/entities. -The user should use SceneManager::createSceneNode() to create all scene nodes. - -NOTE: ALL OBJECTS *MUST* BE ATTACHED TO SCENENODES!!! Unlike the other SM's -available in Ogre3d, the PCZSM relies on Scene Nodes to determine zone -locality of all entities - including cameras and lights. Consequently, -when a camera (or light) is created, the user should also attach the camera -(or light) to a scene node and use that node to manipulate the object. - -SceneNodes can be assigned (by the user) to a zone upon creation of the -SceneNode. Use the functions "PCZSceneNode::setHomeZone(PCZone * zone)" followed -by "PCZone::_addNode(PCZSceneNode * node)" to do this. - -If the user doesn't do this, the PCZSM will try to figure out which zone the -node belongs in using volumetric testing, but since there are situations when -this can fail, it is highly recommended that the user does so explicitly instead -of relying on the SM to figure it out. Note that this only has to be done when -adding a node to the scene. Once the node is in the proper zone, the SM will -handle moving it to other zones as necessary. - -NOTE: In order for the automatic zone assignment function to work, zones must -have an "enclosure" object/node assigned to them (using the "PCZone::setEnclosureNode() -function). The enclosure node (or more specifically, the object attached to it) -supplies the axis-aligned bounding box that determines the bounds of the zone. -So for example, the enclosure node/object for a room would be the model of the -walls, ceiling, and floor (assuming they are all modeled as one object or at least -all attached to the same node). See the PCZTestApp for an example. - -## SCENE QUERIES - -I have implemented Scene Query functions for Default & Octree Zones. In general, -they are used the same way as Scene Queries for any other Scene Manager, with -one difference. The user must specify the "start zone" for any scene query -using XXXSceneQuery::setStartZone(zone) where "XXX" is Ray, Sphere, AxisAlignedBox, etc. - -## KNOWN BUGS - -* Light traversal is not quite correct. In order to avoid infinite recursion, I had to - put in a hack which can potentially result in lighting not traversing into some zones properly. - It will probably not be noticeable in most situations, but could potentially show up in - very complex portal/zone setups. diff --git a/PlugIns/PCZSceneManager/docs/todo.txt b/PlugIns/PCZSceneManager/docs/todo.txt deleted file mode 100644 index 1dc80060094..00000000000 --- a/PlugIns/PCZSceneManager/docs/todo.txt +++ /dev/null @@ -1,33 +0,0 @@ - -This file contains a list of todo items for the PCZSceneManager plugin. -Some items are specific, some are not, it's just a list to keep notes for myself. - - -KNOWN BUGS: -------------- -* Light traversal is not quite correct. In order to avoid infinite recursion, I had to - put in a hack which can potentially result in light not traversing into some zones properly. - It will probably not be noticeable in most situations, but could potentially show up in - very complex portal/zone setups. -* Deleting a Zone and then recreating will cause problems if PCZSceneNodes are still referencing the original deleted zone - -TODO: -------------- -* If a Zone is deleted, scan all the SceneNodes and remove matching ZoneData -* PCZTestApp (and all PCZSM apps?) currently requires linking to the PCZ import library - it shouldn't. -* PCZ .dll does not load (init) properly unless it's in the same directory as the executable. -* Allow portals to connect to the same zone they are in -* Test function to prevent scenenodes from crossing portals which they won't fit through -* More testing - - -OPTIMIZATIONS (todo): ---------------------- -* OctreeZone - utilize octree when determining portal visibility (currently does - separate check not accelerated by octree) for both cameras and light frustums). -* Add scissor rects for portals which are fully visible (i.e. all 4 sides) -* TerrainZoneRenderable has a function for intersecting segments. Maybe (?) able to - use my Ogre::Segment class instead of Ray? - - - diff --git a/PlugIns/PCZSceneManager/include/OgreAntiPortal.h b/PlugIns/PCZSceneManager/include/OgreAntiPortal.h deleted file mode 100644 index eee46a38a63..00000000000 --- a/PlugIns/PCZSceneManager/include/OgreAntiPortal.h +++ /dev/null @@ -1,71 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef ANTIPORTAL_H -#define ANTIPORTAL_H - -#include "OgrePortalBase.h" - -namespace Ogre -{ - /** AntiPortal datastructure for occlusion culling. */ - class _OgrePCZPluginExport AntiPortal : public PortalBase - { - public: - AntiPortal(const String &name, const PORTAL_TYPE type = PORTAL_TYPE_QUAD); - virtual ~AntiPortal(); - - /** @copydoc MovableObject::getMovableType */ - const String& getMovableType() const override; - - }; - - /** Factory object for creating AntiPortal instances */ - class _OgrePCZPluginExport AntiPortalFactory : public PortalBaseFactory - { - protected: - MovableObject* createInstanceImpl(const String& name, const NameValuePairList* params) override; - public: - AntiPortalFactory() {} - ~AntiPortalFactory() {} - - static String FACTORY_TYPE_NAME; - static unsigned long FACTORY_TYPE_FLAG; - - const String& getType() const override - { return FACTORY_TYPE_NAME; } - - /** Return true here as we want to get a unique type flag. */ - bool requestTypeFlags() const override - { return true; } - - }; - -} - -#endif diff --git a/PlugIns/PCZSceneManager/include/OgreCapsule.h b/PlugIns/PCZSceneManager/include/OgreCapsule.h deleted file mode 100644 index 505ad9c6df7..00000000000 --- a/PlugIns/PCZSceneManager/include/OgreCapsule.h +++ /dev/null @@ -1,70 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef CAPSULE_H -#define CAPSULE_H - -#include "OgreSegment.h" - -namespace Ogre -{ - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup PCZSceneManager - * @{ - */ - /** 3D Line-Swept-Sphere class for intersection testing in Ogre3D - Some algorithms based off code from the Wild Magic library by Dave Eberly - */ - class Capsule - { - public: - // construction - Capsule (); // uninitialized - Capsule (const Segment&, Real); - - // set values - void set(const Vector3& newOrigin, const Vector3& newEnd, Real newRadius); - void setOrigin(const Vector3& newOrigin); - void setEndPoint(const Vector3& newEndpoint); - void setRadius(Real newRadius); - - // intersection tests - bool intersects(const Capsule&) const; - bool intersects(const Segment&) const; - - // defining members - Segment mSegment; - Real mRadius; - }; - /** @} */ - /** @} */ -} - -#endif //CAPSULE3_H diff --git a/PlugIns/PCZSceneManager/include/OgreDefaultZone.h b/PlugIns/PCZSceneManager/include/OgreDefaultZone.h deleted file mode 100644 index a43dfda24ea..00000000000 --- a/PlugIns/PCZSceneManager/include/OgreDefaultZone.h +++ /dev/null @@ -1,148 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef DEFAULTZONE_H -#define DEFAULTZONE_H - -#include "OgrePCZone.h" - -namespace Ogre -{ - class PCZFrustum; - struct VisibleObjectsBoundsInfo; - - class _OgrePCZPluginExport DefaultZone : public PCZone - { - public: - DefaultZone( PCZSceneManager *, const String& ); - ~DefaultZone(); - - /** Set the enclosure node for this Zone - */ - void setEnclosureNode(PCZSceneNode *) override; - - /** Adds an SceneNode to this Zone. - - The PCZSceneManager calls this function to add a node - to the zone. - */ - void _addNode( PCZSceneNode * ) override; - - /** Removes all references to a SceneNode from this Zone. - */ - void removeNode( PCZSceneNode * ) override; - - /** Indicates whether or not this zone requires zone-specific data for - * each scene node - */ - bool requiresZoneSpecificNodeData(void) override; - - /** (recursive) check the given node against all portals in the zone - */ - void _checkNodeAgainstPortals(PCZSceneNode *, Portal * ) override; - - /** (recursive) check the given light against all portals in the zone - */ - void _checkLightAgainstPortals(PCZLight *, - unsigned long, - PCZFrustum *, - Portal *) override; - - /* Update the zone data for each portal - */ - void updatePortalsZoneData(void) override; - - /** Mark nodes dirty base on moving portals. */ - void dirtyNodeByMovingPortals(void) override; - - /* Update a node's home zone */ - PCZone * updateNodeHomeZone(PCZSceneNode * pczsn, bool allowBackTouces) override; - - /** Find and add visible objects to the render queue. - - Starts with objects in the zone and proceeds through visible portals - This is a recursive call (the main call should be to _findVisibleObjects) - */ - void findVisibleNodes(PCZCamera *, - NodeList & visibleNodeList, - RenderQueue * queue, - VisibleObjectsBoundsInfo* visibleBounds, - bool onlyShadowCasters, - bool displayNodes, - bool showBoundingBoxes) override; - - /* Functions for finding Nodes that intersect various shapes */ - void _findNodes( const AxisAlignedBox &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude) override; - void _findNodes( const Sphere &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude ) override; - void _findNodes( const PlaneBoundedVolume &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude ) override; - void _findNodes( const Ray &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude ) override; - - /** Sets the options for the Zone */ - bool setOption( const String &, const void * ) override; - - /** called when the scene manager creates a camera because - some zone managers (like TerrainZone) need the camera info. - */ - void notifyCameraCreated( Camera* c ) override; - /* called by PCZSM during setWorldGeometryRenderQueue() */ - void notifyWorldGeometryRenderQueue(uint8 qid) override; - /* Called when a _renderScene is called in the SceneManager */ - void notifyBeginRenderScene(void) override; - /* called by PCZSM during setZoneGeometry() */ - void setZoneGeometry(const String &filename, PCZSceneNode * parentNode) override; - - protected: - - }; - -} - -#endif - - - diff --git a/PlugIns/PCZSceneManager/include/OgrePCPlane.h b/PlugIns/PCZSceneManager/include/OgrePCPlane.h deleted file mode 100644 index 57f9bac9f23..00000000000 --- a/PlugIns/PCZSceneManager/include/OgrePCPlane.h +++ /dev/null @@ -1,94 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef PC_PLANE_H -#define PC_PLANE_H - -#include "OgrePlane.h" -#include "OgrePCZPrerequisites.h" - -namespace Ogre -{ - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup PCZSceneManager - * @{ - */ - class PortalBase; - - /** Portal Culling Plane - - Specialized Plane that is customized for working with the PCZSceneManager. - Each Plane has a pointer to the Portal which was used to create it - Portal Culling Planes are created from one side of a portal and the - origin of a camera. - */ - class _OgrePCZPluginExport PCPlane : public Plane - { - public: - /** Standard constructor */ - PCPlane(); - /** Alternative constructor */ - PCPlane (const Plane & plane); - /** Alternative constructor */ - PCPlane (const Vector3& rkNormal, const Vector3& rkPoint); - /** Alternative constructor */ - PCPlane (const Vector3& rkPoint0, const Vector3& rkPoint1, const Vector3& rkPoint2); - /** Copy from an Ogre Plane */ - void setFromOgrePlane(Plane & ogrePlane); - - /** Standard destructor */ - ~PCPlane(); - - /** Returns the Portal that was used to create this plane - */ - PortalBase* getPortal() - { - return mPortal; - }; - - /** Sets the Portal that was used to create this plane - */ - void setPortal(PortalBase* o) - { - mPortal = o; - }; - - - protected: - - ///Portal used to create this plane. - PortalBase *mPortal; - }; - /** @} */ - /** @} */ -} - - -#endif diff --git a/PlugIns/PCZSceneManager/include/OgrePCZCamera.h b/PlugIns/PCZSceneManager/include/OgrePCZCamera.h deleted file mode 100644 index 752bc46a686..00000000000 --- a/PlugIns/PCZSceneManager/include/OgrePCZCamera.h +++ /dev/null @@ -1,110 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef PCZCAMERA_H -#define PCZCAMERA_H - -#include "OgreCamera.h" -#include "OgrePCZFrustum.h" -#include "OgrePCZPrerequisites.h" - -namespace Ogre -{ - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup PCZSceneManager - * @{ - */ - #define MAX_EXTRA_CULLING_PLANES 40 - - class PCZone; - - /** Specialized viewpoint from which an PCZone Scene can be rendered. - */ - - class _OgrePCZPluginExport PCZCamera : public Camera - { - using Camera::isVisible; - public: - /** Visibility types */ - enum Visibility - { - NONE, - PARTIAL, - FULL - }; - - /* Standard constructor */ - PCZCamera( const String& name, SceneManager* sm ); - /* Standard destructor */ - ~PCZCamera(); - - /** Overridden: Retrieves the local axis-aligned bounding box for this object. - - This bounding box is in local coordinates. - */ - const AxisAlignedBox& getBoundingBox(void) const override; - - /* Overridden isVisible function for aabb */ - bool isVisible( const AxisAlignedBox &bound, FrustumPlane *culledBy=0) const override; - - /* isVisible() function for portals */ - bool isVisible(PortalBase* portal, FrustumPlane* culledBy = 0) const; - - /** Returns the visibility of the box - */ - bool isVisibile( const AxisAlignedBox &bound ); - - /** Returns the detailed visibility of the box - */ - PCZCamera::Visibility getVisibility( const AxisAlignedBox &bound ); - - /// Sets the type of projection to use (orthographic or perspective). - void setProjectionType(ProjectionType pt) override; - - /* Update function (currently used for making sure the origin stuff for the - extra culling frustum is up to date */ - void update(void); - - /** Calculate extra culling planes from portal and camera - origin and add to list of extra culling planes */ - int addPortalCullingPlanes(PortalBase* portal); - /// Remove extra culling planes created from the given portal - void removePortalCullingPlanes(PortalBase* portal); - /// Remove all extra culling planes - void removeAllExtraCullingPlanes(void); - protected: - AxisAlignedBox mBox; - PCZFrustum mExtraCullingFrustum; - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/PlugIns/PCZSceneManager/include/OgrePCZFrustum.h b/PlugIns/PCZSceneManager/include/OgrePCZFrustum.h deleted file mode 100644 index f5f9fe767d0..00000000000 --- a/PlugIns/PCZSceneManager/include/OgrePCZFrustum.h +++ /dev/null @@ -1,134 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef PCZ_FRUSTUM_H -#define PCZ_FRUSTUM_H - -#include "OgrePCZPrerequisites.h" -#include "OgreFrustum.h" - -namespace Ogre -{ - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup PCZSceneManager - * @{ - */ - class PortalBase; - class PCPlane; - - typedef std::list< PCPlane * > PCPlaneList; - - /** Specialized frustum shaped culling volume that has culling planes created from portals - - This isn't really a traditional "frustum", but more a collection of - extra culling planes used by the PCZ Scene Manager for supplementing - the camera culling and light zone culling by creating extra culling - planes from visible portals. Since portals are 4 sided, the extra - culling planes tend to form frustums (pyramids) but nothing in the - code really assumes that the culling planes are frustums. They are - just treated as planes. - - The "originPlane" is a culling plane which passes through the origin - point specified. It is used to cull portals which are close to, but - behind the camera view. (the nature of the culling routine doesn't - give correct results if you just use the "near" plane of the standard - camera frustum (unless that near plane distance is 0.0, but that is - highly not recommended for other reasons having to do with having a - legal view frustum). - */ - class _OgrePCZPluginExport PCZFrustum - { - public: - // visibility types - enum Visibility - { - NONE, - PARTIAL, - FULL - }; - - /** Standard constructor */ - PCZFrustum(); - /** Standard destructor */ - ~PCZFrustum(); - - /* isVisible function for aabb */ - bool isVisible( const AxisAlignedBox &bound) const; - /* isVisible function for sphere */ - bool isVisible( const Sphere &bound) const; - /* isVisible() function for portals */ - bool isVisible(const PortalBase* portal) const; - /* special function that returns true only when aabb fully fits inside the frustum. */ - bool isFullyVisible(const AxisAlignedBox& bound) const; - /* special function that returns true only when sphere fully fits inside the frustum. */ - bool isFullyVisible(const Sphere& bound) const; - /* special function that returns true only when portal fully fits inside the frustum. */ - bool isFullyVisible(const PortalBase* portal) const; - /* more detailed check for visibility of an AABB */ - PCZFrustum::Visibility getVisibility(const AxisAlignedBox & bound); - - /** Calculate culling planes from portal and Frustum - origin and add to list of culling planes */ - int addPortalCullingPlanes(PortalBase* portal); - /// Remove culling planes created from the given portal - void removePortalCullingPlanes(PortalBase* portal); - /// Remove all culling planes - void removeAllCullingPlanes(void); - /// Set the origin value - void setOrigin(const Vector3 & newOrigin) {mOrigin = newOrigin;} - /// Set the origin plane - void setOriginPlane(const Vector3 &rkNormal, const Vector3 &rkPoint); - /// Tell the frustum whether or not to use the originplane - void setUseOriginPlane(bool yesno) {mUseOriginPlane = yesno;} - /// Get an unused PCPlane from the CullingPlane Reservoir - PCPlane * getUnusedCullingPlane(void); - - /// Set the projection type of this PCZFrustum. - inline void setProjectionType(ProjectionType projType) - { mProjType = projType; } - /// Get the projection type of this PCZFrustum. - inline ProjectionType getProjectionType() const - { return mProjType; } - - protected: - Vector3 mOrigin; - Plane mOriginPlane; - bool mUseOriginPlane; - PCPlaneList mActiveCullingPlanes; - PCPlaneList mCullingPlaneReservoir; - ProjectionType mProjType; - - }; - /** @} */ - /** @} */ -} - - -#endif diff --git a/PlugIns/PCZSceneManager/include/OgrePCZLight.h b/PlugIns/PCZSceneManager/include/OgrePCZLight.h deleted file mode 100644 index 86c82780d3b..00000000000 --- a/PlugIns/PCZSceneManager/include/OgrePCZLight.h +++ /dev/null @@ -1,135 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef PCZLIGHT_H -#define PCZLIGHT_H - -#include "OgreLight.h" -#include "OgrePCZPrerequisites.h" - -namespace Ogre -{ - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup PCZSceneManager - * @{ - */ - class PCZone; - - typedef std::list ZoneList; - - /** Specialized version of Ogre::Light which caches which zones the light affects - */ - - class _OgrePCZPluginExport PCZLight : public Light - { - public: - /** Default constructor (for Python mainly). - */ - PCZLight(); - - /** Normal constructor. Should not be called directly, but rather the SceneManager::createLight method should be used. - */ - PCZLight(const String& name); - - /** Standard destructor. - */ - ~PCZLight(); - - /** Overridden from MovableObject */ - const String& getMovableType(void) const override; - - /** Clear the affectedZonesList - */ - void clearAffectedZones(void); - - /** Manually add a zone to the zones affected list - */ - void addZoneToAffectedZonesList(PCZone * zone); - - /** Check if a zone is in the list of zones affected by the light - */ - bool affectsZone(PCZone * zone); - - /** @return Flag indicating if the light affects a zone which is visible - * in the current frame - */ - bool affectsVisibleZone(void) {return mAffectsVisibleZone;} - - /** Marks a light as affecting a visible zone */ - void setAffectsVisibleZone(bool affects) { mAffectsVisibleZone = affects; } - - /** Update the list of zones the light affects - */ - void updateZones(PCZone * defaultZone, unsigned long frameCount); - - /// Manually remove a zone from the affected list - void removeZoneFromAffectedZonesList(PCZone * zone); - - /// MovableObject notified when SceneNode changes - void _notifyMoved(void) override; - - /// Clear update flag - void clearNeedsUpdate(void) { mNeedsUpdate = false; } - - /// Get status of need for update. this checks all affected zones - bool getNeedsUpdate(void); - - protected: - /** Flag indicating if any of the zones in the affectedZonesList is - * visible in the current frame - */ - bool mAffectsVisibleZone; - - /** List of PCZones which are affected by the light - */ - ZoneList affectedZonesList; - - /// Flag recording if light has moved, therefore affected list needs updating - bool mNeedsUpdate; - }; - - /** Factory object for creating PCZLight instances */ - class _OgrePCZPluginExport PCZLightFactory : public MovableObjectFactory - { - protected: - MovableObject* createInstanceImpl( const String& name, const NameValuePairList* params) override; - public: - PCZLightFactory() {} - ~PCZLightFactory() {} - - static String FACTORY_TYPE_NAME; - - const String& getType(void) const override; - }; - /** @} */ - /** @} */ - -} // Namespace -#endif diff --git a/PlugIns/PCZSceneManager/include/OgrePCZPlugin.h b/PlugIns/PCZSceneManager/include/OgrePCZPlugin.h deleted file mode 100644 index 26c7002926a..00000000000 --- a/PlugIns/PCZSceneManager/include/OgrePCZPlugin.h +++ /dev/null @@ -1,71 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef PCZPLUGIN_H -#define PCZPLUGIN_H - -#include "OgrePlugin.h" - -namespace Ogre -{ - class PCZSceneManagerFactory; - class PCZoneFactoryManager; - class PCZLightFactory; - class PortalFactory; - class AntiPortalFactory; - - /** Plugin instance for PCZ Manager */ - class PCZPlugin : public Plugin - { - public: - PCZPlugin(); - - /// @copydoc Plugin::getName - const String& getName() const override; - - /// @copydoc Plugin::install - void install() override; - - /// @copydoc Plugin::initialise - void initialise() override; - - /// @copydoc Plugin::shutdown - void shutdown() override; - - /// @copydoc Plugin::uninstall - void uninstall() override; - protected: - PCZSceneManagerFactory* mPCZSMFactory; - PCZoneFactoryManager* mPCZoneFactoryManager; - PCZLightFactory* mPCZLightFactory; - PortalFactory* mPortalFactory; - AntiPortalFactory* mAntiPortalFactory; - }; -} - -#endif diff --git a/PlugIns/PCZSceneManager/include/OgrePCZSceneManager.h b/PlugIns/PCZSceneManager/include/OgrePCZSceneManager.h deleted file mode 100644 index b6624f343e5..00000000000 --- a/PlugIns/PCZSceneManager/include/OgrePCZSceneManager.h +++ /dev/null @@ -1,380 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef PCZ_SCENEMANAGER_H -#define PCZ_SCENEMANAGER_H - -#include "OgrePCZPrerequisites.h" -#include "OgreSceneManager.h" -#include "OgrePCZone.h" - -namespace Ogre -{ - /** \addtogroup Plugins Plugins - * @{ - */ - /** \defgroup PCZSceneManager PCZSceneManager - * SceneManager that uses Portal-Connected-Zones to divide the scene spatially - * @{ - */ - class PCZoneFactoryManager; - class PortalBase; - - typedef std::vector NodeList; - typedef std::list BoxList; - - /** Specialized SceneManager that uses Portal-Connected-Zones to divide the scene spatially. - */ - - class _OgrePCZPluginExport PCZSceneManager : public SceneManager, public ShadowTextureListener - { - friend class PCZIntersectionSceneQuery; - friend class PCZRaySceneQuery; - friend class PCZSphereSceneQuery; - friend class PCZAxisAlignedBoxSceneQuery; - friend class PCZPlaneBoundedVolumeListSceneQuery; - - public: - /** Standard Constructor. */ - PCZSceneManager(const String& name); - /** Standard destructor */ - ~PCZSceneManager(); - - /// @copydoc SceneManager::getTypeName - const String& getTypeName(void) const override; - - /** Initializes the manager - */ - void init(const String &defaultZoneTypeName, - const String &filename = "none"); - - /** Create a new portal instance - */ - Portal* createPortal(const String& name, PortalBase::PORTAL_TYPE type = PortalBase::PORTAL_TYPE_QUAD); - - /** Delete a portal instance by pointer - */ - void destroyPortal(Portal * p); - - /** Delete a portal instance by name - */ - void destroyPortal(const String & portalName); - - /** Create a new anti portal instance */ - AntiPortal* createAntiPortal(const String& name, PortalBase::PORTAL_TYPE type = PortalBase::PORTAL_TYPE_QUAD); - - /** Delete a anti portal instance by pointer */ - void destroyAntiPortal(AntiPortal * p); - - /** Delete a anti portal instance by name */ - void destroyAntiPortal(const String& portalName); - - /** Create a zone from a file (type of file - * depends on the zone type - */ - PCZone * createZoneFromFile(const String &zoneTypeName, - const String &zoneName, - PCZSceneNode * parentNode, - const String & filename); - - /** Set the "main" geometry of the zone */ - virtual void setZoneGeometry(const String & zoneName, - PCZSceneNode * parentNode, - const String &filename); - - SceneNode* createSceneNodeImpl(void) override; - SceneNode* createSceneNodeImpl(const String& name) override; - /** Creates a specialized PCZCamera */ - Camera * createCamera( const String &name ) override; - - /** Deletes a scene node by name & corresponding PCZSceneNode */ - void destroySceneNode( const String &name ) override; - - /** Deletes a scene node & corresponding PCZSceneNode */ - void destroySceneNode(SceneNode* sn) override; - - /** Overridden to clean up zones - */ - void clearScene(void) override; - - /** Overridden from SceneManager */ - void setWorldGeometryRenderQueue(uint8 qid); - - /// Overridden from basic scene manager - void _renderScene(Camera *cam, Viewport *vp, bool includeOverlays) override; - - /** Enable/disable sky rendering */ - void enableSky(bool); - - /** Set the zone which contains the sky node */ - void setSkyZone(PCZone * zone); - - /** Update Scene Graph (does several things now) */ - void _updateSceneGraph( Camera * cam ) override; - - /** Recurses through the PCZTree determining which nodes are visible. */ - void _findVisibleObjects ( Camera * cam, - VisibleObjectsBoundsInfo* visibleBounds, bool onlyShadowCasters ) override; - - /** Creates a light for use in the scene. - - Lights can either be in a fixed position and independent of the - scene graph, or they can be attached to SceneNodes so they derive - their position from the parent node. Either way, they are created - using this method so that the SceneManager manages their - existence. - @param - name The name of the new light, to identify it later. - */ - Light* createLight(const String& name) override; - - /** Returns a pointer to the named Light which has previously been added to the scene. - @note Throws an exception if the named instance does not exist - */ - Light* getLight(const String& name) const override; - - /** Returns whether a light with the given name exists. - */ - bool hasLight(const String& name) const override; - - /** Removes the named light from the scene and destroys it. - - Any pointers held to this light after calling this method will be invalid. - */ - void destroyLight(const String& name) override; - - /** Removes and destroys all lights in the scene. - */ - void destroyAllLights(void) override; - - /** Check/Update the zone data for every portal in the scene. - * Essentially, this routine checks each portal for intersections - * with other portals and updates if a crossing occurs - */ - void _updatePortalZoneData(void); - - /** Mark nodes dirty for every zone with moving portal in the scene */ - void _dirtyNodeByMovingPortals(void); - - /** Update the PCZSceneNodes - */ - void _updatePCZSceneNodes(void); - - /** Calculate which zones are affected by each light - */ - void _calcZonesAffectedByLights(Camera * cam); - - /* Attempt to automatically connect unconnected portals to proper target zones - * by looking for matching portals in other zones which are at the same location - */ - void connectPortalsToTargetZonesByLocation(void); - - /** Checks the given SceneNode, and determines if it needs to be moved - * to a different PCZone or be added to the visitors list of other PCZone(s). - */ - void _updatePCZSceneNode( PCZSceneNode * ); - - /** Removes the given PCZSceneNode */ - void removeSceneNode( SceneNode * ); - - /** add a PCZSceneNode to the scene by putting it in a zone - * NOTE: This zone will be the scene node's home zone - */ - void addPCZSceneNode(PCZSceneNode * sn, PCZone * zone); - - /** Create a zone with the given name */ - PCZone * createZone(const String& zoneType, const String& instanceName); - - /** Destroy an existing zone within the scene */ - void destroyZone(PCZone* zone, bool destroySceneNodes); - - /** Make sure the home zone for the PCZSceneNode is up-to-date - */ - void _updateHomeZone( PCZSceneNode *, bool ); - - /// Find the smallest zone which contains the point - PCZone * findZoneForPoint(Vector3 & point); - - /// Create any zone-specific data necessary for all zones for the given node - void createZoneSpecificNodeData(PCZSceneNode *); - - /// Create any zone-specific data necessary for all nodes for the given zone - void createZoneSpecificNodeData(PCZone *); - - /// Set the home zone for a scene node - void setNodeHomeZone(SceneNode *, PCZone *); - - /** Recurses the scene, adding any nodes intersecting with the box into the given list. - It ignores the exclude scene node. - */ - void findNodesIn( const AxisAlignedBox &box, - PCZSceneNodeList &list, - PCZone * startZone, - PCZSceneNode *exclude = 0 ); - - /** Recurses the scene, adding any nodes intersecting with the sphere into the given list. - It will start in the start SceneNode if given, otherwise, it will start at the root node. - */ - void findNodesIn( const Sphere &sphere, - PCZSceneNodeList &list, - PCZone * startZone, - PCZSceneNode *start = 0 ); - - /** Recurses the PCZTree, adding any nodes intersecting with the volume into the given list. - It will start in the start SceneNode if given, otherwise, it will start at the root node. - */ - void findNodesIn( const PlaneBoundedVolume &volume, - PCZSceneNodeList &list, - PCZone * startZone, - PCZSceneNode *start=0 ); - - /** Recurses the scene, starting in the given startZone, adding any nodes intersecting with - the ray into the given list. - It will start in the start SceneNode if given, otherwise, it will start at the root node. - */ - void findNodesIn( const Ray &ray, - PCZSceneNodeList &list, - PCZone * startZone, - PCZSceneNode *start=0 ); - - /** Get the default zone */ - PCZone * getDefaultZone(void) - { - return mDefaultZone; - } - - /** Get a zone by name */ - PCZone * getZoneByName(const String & zoneName); - - /** Sets the portal visibility flag */ - void setShowPortals( bool b ) - { - mShowPortals = b; - }; - - /** Sets the given option for the SceneManager - - Options are: - "ShowPortals", bool *; - "ShowBoundingBoxes", bool *; - */ - bool setOption( const String &, const void * ) override; - /** Gets the given option for the Scene Manager. - - See setOption - */ - bool getOption( const String &, void * ) override; - - bool getOptionValues( const String & key, StringVector &refValueList ) override; - bool getOptionKeys( StringVector &refKeys ) override; - - /** Overridden from SceneManager */ - AxisAlignedBoxSceneQuery* createAABBQuery(const AxisAlignedBox& box, uint32 mask = 0xFFFFFFFF) override; - SphereSceneQuery* createSphereQuery(const Sphere& sphere, uint32 mask = 0xFFFFFFFF) override; - PlaneBoundedVolumeListSceneQuery* createPlaneBoundedVolumeQuery(const PlaneBoundedVolumeList& volumes, uint32 mask = 0xFFFFFFFF) override; - RaySceneQuery* createRayQuery(const Ray& ray, uint32 mask = 0xFFFFFFFF) override; - IntersectionSceneQuery* createIntersectionQuery(uint32 mask = 0xFFFFFFFF) override; - - /// ZoneMap iterator for read-only access to the zonemap - typedef MapIterator ZoneIterator; - ZoneIterator getZoneIterator(void) {return ZoneIterator(mZones.begin(), mZones.end());} - - /// Clear portal update flag from all zones - void _clearAllZonesPortalUpdateFlag(void); - - /// @see SceneManager::prepareShadowTextures. - void prepareShadowTextures(Camera* cam, Viewport* vp, const LightList* lightList = 0) override; - - protected: - /// Type of default zone to be used - String mDefaultZoneTypeName; - - /// Name of data file for default zone - String mDefaultZoneFileName; - - /// List of visible nodes since last _findVisibleObjects() - NodeList mVisible; - - /// Camera of last _findVisibleObjects() - Camera* mLastActiveCamera; - - /// The root PCZone; - PCZone *mDefaultZone; - - /// The list of all PCZones - ZoneMap mZones; - - /// Master list of Portals in the world (includes all portals) - PortalList mPortals; - - /// Master list of AntiPortals in the world. - AntiPortalList mAntiPortals; - - /// Portals visibility flag - bool mShowPortals; - - /// Frame counter used in visibility determination - unsigned long mFrameCount; - - /// ZoneFactoryManager instance - PCZoneFactoryManager * mZoneFactoryManager; - - /// The zone of the active camera (for shadow texture casting use); - PCZone* mActiveCameraZone; - - /** Internal method for locating a list of lights which could be affecting the frustum. - - Custom scene managers are encouraged to override this method to make use of their - scene partitioning scheme to more efficiently locate lights, and to eliminate lights - which may be occluded by word geometry. - */ - void findLightsAffectingFrustum(const Camera* camera) override; - /// Internal method for creating shadow textures (texture-based shadows) - void ensureShadowTexturesCreated() override; - /// Internal method for firing the pre caster texture shadows event - void shadowTextureCasterPreViewProj(Light* light, Camera* camera, size_t iteration) override; - }; - - /// Factory for PCZSceneManager - class PCZSceneManagerFactory : public SceneManagerFactory - { - public: - /// Factory type name - static const String FACTORY_TYPE_NAME; - SceneManager* createInstance(const String& instanceName) override; - const String& getTypeName(void) const override { return FACTORY_TYPE_NAME; } - }; - - - /** @} */ - /** @} */ -} - -#endif - - diff --git a/PlugIns/PCZSceneManager/include/OgrePCZSceneNode.h b/PlugIns/PCZSceneManager/include/OgrePCZSceneNode.h deleted file mode 100644 index 80b30927d5c..00000000000 --- a/PlugIns/PCZSceneManager/include/OgrePCZSceneNode.h +++ /dev/null @@ -1,122 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef PCZ_SCENE_NODE_H -#define PCZ_SCENE_NODE_H - -#include "OgrePCZPrerequisites.h" -#include "OgreSceneNode.h" -#include "OgreSceneManager.h" - -namespace Ogre -{ - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup PCZSceneManager - * @{ - */ - // forward declarations - class PCZone; - class ZoneData; - class PCZCamera; - typedef std::map ZoneMap; - typedef std::map ZoneDataMap; - - /** - The PCZSceneNode is an extension used to store zone information and provide - additional functionality for a given Ogre::SceneNode. A PCZSceneNode contains - a pointer to the home zone for the node and a list of all zones being visited by - the node. The PCZSceneManager contains a STD::MAP of PCZSceneNodes which are - keyed by the name of each node (each PCZSceneNode has an identical name to the - scene node which it is associated with). This allows quick lookup of - a given scenenode's PCZSceneNode by the scene manager. - */ - class _OgrePCZPluginExport PCZSceneNode : public SceneNode - { - public: - /** Standard constructor */ - PCZSceneNode( SceneManager* creator ); - /** Standard constructor */ - PCZSceneNode( SceneManager* creator, const String& name ); - /** Standard destructor */ - ~PCZSceneNode(); - void _update(bool updateChildren, bool parentHasChanged) override; - void updateFromParentImpl() const override; - - SceneNode* createChildSceneNode(const Vector3& translate = Vector3::ZERO, - const Quaternion& rotate = Quaternion::IDENTITY) override; - SceneNode* createChildSceneNode(const String& name, const Vector3& translate = Vector3::ZERO, - const Quaternion& rotate = Quaternion::IDENTITY) override; - - PCZone* getHomeZone(void); - void setHomeZone(PCZone * zone); - void anchorToHomeZone(PCZone * zone); - bool isAnchored(void) {return mAnchored;} - void allowToVisit(bool yesno) {mAllowedToVisit = yesno;} - bool allowedToVisit(void) {return mAllowedToVisit;} - void addZoneToVisitingZonesMap(PCZone * zone); - void clearVisitingZonesMap(void); - void clearNodeFromVisitedZones( void ); - void removeReferencesToZone(PCZone * zone); - bool isVisitingZone(PCZone * zone); - void _addToRenderQueue( Camera* cam, - RenderQueue *queue, - bool onlyShadowCasters, - VisibleObjectsBoundsInfo* visibleBounds ); - void savePrevPosition(void); - Vector3& getPrevPosition(void) {return mPrevPosition;} - unsigned long getLastVisibleFrame(void) {return mLastVisibleFrame;} - void setLastVisibleFrame(unsigned long newLVF) {mLastVisibleFrame = newLVF;} - void setLastVisibleFromCamera(PCZCamera * camera) {mLastVisibleFromCamera = camera;} - PCZCamera* getLastVisibleFromCamera() {return mLastVisibleFromCamera;} - void setZoneData(PCZone * zone, ZoneData * zoneData); - ZoneData* getZoneData(PCZone * zone); - void updateZoneData(void); - void enable(bool yesno) {mEnabled = yesno;} - bool isEnabled(void) {return mEnabled;} - bool isMoved(void) {return mMoved;} - void setMoved(bool value) {mMoved = value;} - protected: - mutable Vector3 mNewPosition; - PCZone * mHomeZone; - bool mAnchored; - bool mAllowedToVisit; - ZoneMap mVisitingZones; - mutable Vector3 mPrevPosition; - unsigned long mLastVisibleFrame; - PCZCamera* mLastVisibleFromCamera; - ZoneDataMap mZoneData; - bool mEnabled; - mutable bool mMoved; - }; - /** @} */ - /** @} */ -} - -#endif // PCZ_SCENE_NODE_H diff --git a/PlugIns/PCZSceneManager/include/OgrePCZSceneQuery.h b/PlugIns/PCZSceneManager/include/OgrePCZSceneQuery.h deleted file mode 100644 index cdbf64c7a1f..00000000000 --- a/PlugIns/PCZSceneManager/include/OgrePCZSceneQuery.h +++ /dev/null @@ -1,127 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef PCZSCENEQUERY_H -#define PCZSCENEQUERY_H - -#include "OgreSceneManager.h" -#include "OgrePCZPrerequisites.h" - -namespace Ogre -{ - class PCZone; - - /** PCZ implementation of IntersectionSceneQuery. */ - class _OgrePCZPluginExport PCZIntersectionSceneQuery : public DefaultIntersectionSceneQuery - { - public: - PCZIntersectionSceneQuery(SceneManager* creator); - ~PCZIntersectionSceneQuery(); - - /** See IntersectionSceneQuery. */ - void execute(IntersectionSceneQueryListener* listener) override; - }; - /** PCZ implementation of AxisAlignedBoxSceneQuery. */ - class _OgrePCZPluginExport PCZAxisAlignedBoxSceneQuery : public DefaultAxisAlignedBoxSceneQuery - { - public: - PCZAxisAlignedBoxSceneQuery(SceneManager* creator); - ~PCZAxisAlignedBoxSceneQuery(); - - /** See RaySceneQuery. */ - void execute(SceneQueryListener* listener) override; - - /** set the zone to start the scene query */ - void setStartZone(PCZone * startZone) {mStartZone = startZone;} - /** set node to exclude from query */ - void setExcludeNode(SceneNode * excludeNode) {mExcludeNode = excludeNode;} - protected: - PCZone * mStartZone; - SceneNode * mExcludeNode; - }; - /** PCZ implementation of RaySceneQuery. */ - class _OgrePCZPluginExport PCZRaySceneQuery : public DefaultRaySceneQuery - { - public: - PCZRaySceneQuery(SceneManager* creator); - ~PCZRaySceneQuery(); - - /** See RayScenQuery. */ - void execute(RaySceneQueryListener* listener) override; - - /** set the zone to start the scene query */ - void setStartZone(PCZone * startZone) {mStartZone = startZone;} - /** set node to exclude from query */ - void setExcludeNode(SceneNode * excludeNode) {mExcludeNode = excludeNode;} - protected: - PCZone * mStartZone; - SceneNode * mExcludeNode; - }; - /** PCZ implementation of SphereSceneQuery. */ - class _OgrePCZPluginExport PCZSphereSceneQuery : public DefaultSphereSceneQuery - { - public: - PCZSphereSceneQuery(SceneManager* creator); - ~PCZSphereSceneQuery(); - - /** See SceneQuery. */ - void execute(SceneQueryListener* listener) override; - - /** set the zone to start the scene query */ - void setStartZone(PCZone * startZone) {mStartZone = startZone;} - /** set node to exclude from query */ - void setExcludeNode(SceneNode * excludeNode) {mExcludeNode = excludeNode;} - protected: - PCZone * mStartZone; - SceneNode * mExcludeNode; - }; - /** PCZ implementation of PlaneBoundedVolumeListSceneQuery. */ - class _OgrePCZPluginExport PCZPlaneBoundedVolumeListSceneQuery : public DefaultPlaneBoundedVolumeListSceneQuery - { - public: - PCZPlaneBoundedVolumeListSceneQuery(SceneManager* creator); - ~PCZPlaneBoundedVolumeListSceneQuery(); - - /** See SceneQuery. */ - void execute(SceneQueryListener* listener) override; - - /** set the zone to start the scene query */ - void setStartZone(PCZone * startZone) {mStartZone = startZone;} - /** set node to exclude from query */ - void setExcludeNode(SceneNode * excludeNode) {mExcludeNode = excludeNode;} - protected: - PCZone * mStartZone; - SceneNode * mExcludeNode; - }; - - -} - -#endif - - diff --git a/PlugIns/PCZSceneManager/include/OgrePCZone.h b/PlugIns/PCZSceneManager/include/OgrePCZone.h deleted file mode 100644 index fe3789082f1..00000000000 --- a/PlugIns/PCZSceneManager/include/OgrePCZone.h +++ /dev/null @@ -1,315 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef PCZONE_H -#define PCZONE_H - -#include "OgrePCZPrerequisites.h" -#include "OgrePortalBase.h" - -namespace Ogre -{ - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup PCZSceneManager - * @{ - */ - class Portal; - class AntiPortal; - class PCZSceneNode; - class PCZSceneManager; - class PCZLight; - class PCZone; - class PCZCamera; - class PCZFrustum; - struct VisibleObjectsBoundsInfo; - - typedef std::map ZoneMap; - typedef std::list PCZoneList; - typedef std::list PortalList; - typedef std::list AntiPortalList; - typedef std::vector PortalBaseList; - typedef std::vector NodeList; - typedef std::set< PCZSceneNode * > PCZSceneNodeList; - typedef std::map SceneNodeList; - - /** Portal-Connected Zone datastructure for managing scene nodes. - - Portal Connected Zones are spatial constructs for partitioning space into cross - connected zones. Each zone is connected to other zones using Portal nodes. - - Zones contain references to nodes which touch them. However, zones do not - care how nodes are arranged hierarchically. Whether or not a node is - referenced as being part of a zone is entirely determined by the user or - by the node crossing a portal into or out-of the zone. - - Nodes can be referenced by several zones at once, but only one zone is - considered the "home" zone of the node. Home zone is determined by location - of the centerpoint of the node. Nodes can "touch" other zones if the node - BV intersects a portal (this is also called "visiting" a zone). Nodes keep - a pointer to their home zone and a list of references to zones they are - "visiting". - */ - - class _OgrePCZPluginExport PCZone : public SceneCtlAllocatedObject - { - public: - - enum NODE_LIST_TYPE - { - HOME_NODE_LIST = 1, - VISITOR_NODE_LIST = 2 - }; - - PCZone( PCZSceneManager *, const String& ); - virtual ~PCZone(); - - /// @return The zone type name (ex: "ZoneType_Terrain") - const String& getZoneTypeName() const { return mZoneTypeName; } - - /// @return the name of the zone - const String& getName(void) const { return mName; } - - /** Get a pointer to the enclosure node for this PCZone - */ - SceneNode * getEnclosureNode(void) {return mEnclosureNode;} - - /** If sky should be drawn with this zone - */ - void setHasSky(bool yesno) {mHasSky = yesno;} - - /** @return Whether or not this zone has sky - */ - bool hasSky(void) {return mHasSky;} - - /** Set the lastVisibleFrame counter */ - void setLastVisibleFrame(unsigned long frameCount) {mLastVisibleFrame = frameCount;} - - /** Get the lastVisibleFrame counter value */ - unsigned long getLastVisibleFrame(void) {return mLastVisibleFrame;} - - /** Set the lastVisibleFromCamera pointer */ - void setLastVisibleFromCamera(PCZCamera * camera) {mLastVisibleFromCamera = camera;} - - /** Get the lastVisibleFromCamera pointer */ - PCZCamera* getLastVisibleFromCamera() {return mLastVisibleFromCamera;} - - public: - /** Set the enclosure node for this PCZone - */ - virtual void setEnclosureNode(PCZSceneNode *) = 0; - - /** Adds an SceneNode to this PCZone. - - The PCZSceneManager calls this function to add a node - to the zone. Home or Visitor list is selected based on the node's home zone - */ - virtual void _addNode( PCZSceneNode * ) = 0; - - /** Removes all references to a SceneNode from this PCZone. - */ - virtual void removeNode( PCZSceneNode * ) = 0; - - /** Remove all nodes from the node reference list and clear it - */ - virtual void _clearNodeLists(short nodeListTypes); - - /** Indicates whether or not this zone requires zone-specific data for - * each scene node - */ - virtual bool requiresZoneSpecificNodeData(void) = 0; - - /** Create zone specific data for a node - */ - virtual void createNodeZoneData(PCZSceneNode *); - - /** Find a matching portal (for connecting portals) - */ - virtual Portal * findMatchingPortal(Portal *); - - /** Add a portal to the zone */ - virtual void _addPortal(Portal* newPortal); - - /** Remove a portal from the zone */ - virtual void _removePortal(Portal* removePortal); - - /** Add an anti portal to the zone */ - virtual void _addAntiPortal(AntiPortal* newAntiPortal); - - /** Remove an anti portal from the zone */ - virtual void _removeAntiPortal(AntiPortal* removeAntiPortal); - - /** (recursive) Check the given node against all portals in the zone - */ - virtual void _checkNodeAgainstPortals(PCZSceneNode *, Portal * ) = 0; - - /** (recursive) Check the given light against all portals in the zone - */ - virtual void _checkLightAgainstPortals(PCZLight *, - unsigned long, - PCZFrustum *, - Portal *) = 0; - - /** Update the zone data for each portal - */ - virtual void updatePortalsZoneData(void) = 0; - - /** Mark nodes dirty base on moving portals. */ - virtual void dirtyNodeByMovingPortals(void) = 0; - - /** Update a node's home zone */ - virtual PCZone * updateNodeHomeZone(PCZSceneNode * pczsn, bool allowBackTouces) = 0; - - /** Find and add visible objects to the render queue. - - Starts with objects in the zone and proceeds through visible portals - This is a recursive call (the main call should be to _findVisibleObjects) - */ - virtual void findVisibleNodes(PCZCamera *, - NodeList & visibleNodeList, - RenderQueue * queue, - VisibleObjectsBoundsInfo* visibleBounds, - bool onlyShadowCasters, - bool displayNodes, - bool showBoundingBoxes) = 0; - - /* Functions for finding Nodes that intersect various shapes */ - virtual void _findNodes( const AxisAlignedBox &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude) = 0; - virtual void _findNodes( const Sphere &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude ) = 0; - virtual void _findNodes( const PlaneBoundedVolume &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude ) = 0; - virtual void _findNodes( const Ray &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude ) = 0; - - /** Sets the options for the Zone */ - virtual bool setOption( const String &, const void * ) = 0; - /** Called when the scene manager creates a camera in order to store the first camera created as the primary - one, for determining error metrics and the 'home' terrain page. - */ - virtual void notifyCameraCreated( Camera* c ) = 0; - /** Called by PCZSM during setWorldGeometryRenderQueue() */ - virtual void notifyWorldGeometryRenderQueue(uint8 qid) = 0; - /** Called when a _renderScene is called in the SceneManager */ - virtual void notifyBeginRenderScene(void) = 0; - /** Called by PCZSM during setZoneGeometry() */ - virtual void setZoneGeometry(const String &filename, PCZSceneNode * parentNode) = 0; - /** Get the world coordinate aabb of the zone */ - virtual void getAABB(AxisAlignedBox &); - void setPortalsUpdated(bool updated) { mPortalsUpdated = updated; } - bool getPortalsUpdated(void) { return mPortalsUpdated; } - /** Get & set the user data */ - void * getUserData(void) {return mUserData;} - void setUserData(void * userData) {mUserData = userData;} - /** List of Portals which this zone contains (each portal leads to another zone) - */ - PortalList mPortals; - AntiPortalList mAntiPortals; - /// Pointer to the pcz scene manager that created this zone - PCZSceneManager * mPCZSM; - - protected: - /** Binary predicate for portal <-> camera distance sorting. */ - struct PortalSortDistance - { - const Vector3& cameraPosition; - PortalSortDistance(const Vector3& inCameraPosition) : cameraPosition(inCameraPosition) - { } - - bool operator()(const PortalBase* p1, const PortalBase* p2) const - { - Real depth1 = p1->getDerivedCP().squaredDistance(cameraPosition); - Real depth2 = p2->getDerivedCP().squaredDistance(cameraPosition); - return (depth1 < depth2); - } - }; - - /// Name of the zone (must be unique) - String mName; - /// Zone type name - String mZoneTypeName; - /// Frame counter for visibility - unsigned long mLastVisibleFrame; - /// Last camera which this zone was visible to - PCZCamera * mLastVisibleFromCamera; - /// Flag determining whether or not this zone has sky in it. - bool mHasSky; - /// SceneNode which corresponds to the enclosure for this zone - SceneNode * mEnclosureNode; - /// List of SceneNodes contained in this particular PCZone - PCZSceneNodeList mHomeNodeList; - /// List of SceneNodes visiting this particular PCZone - PCZSceneNodeList mVisitorNodeList; - /// Flag recording whether any portals in this zone have moved - bool mPortalsUpdated; - /** User defined data pointer - NOT allocated or deallocated by the zone! - you must clean it up yourself! */ - void * mUserData; - - }; - - class _OgrePCZPluginExport ZoneData : public SceneCtlAllocatedObject - { - public: - /** Standard Constructor */ - ZoneData(PCZSceneNode *, PCZone * ); - /** Standard destructor */ - virtual ~ZoneData(); - /** Update data if necessary */ - virtual void update(void); - public: - PCZone * mAssociatedZone; - PCZSceneNode * mAssociatedNode; - - }; - /** @} */ - /** @} */ -} - -#endif - - - diff --git a/PlugIns/PCZSceneManager/include/OgrePCZoneFactory.h b/PlugIns/PCZSceneManager/include/OgrePCZoneFactory.h deleted file mode 100644 index fed53084f12..00000000000 --- a/PlugIns/PCZSceneManager/include/OgrePCZoneFactory.h +++ /dev/null @@ -1,92 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef PCZONE_FACTORY_H -#define PCZONE_FACTORY_H - -#include "OgrePCZPrerequisites.h" -#include "OgreSingleton.h" -#include "OgreIteratorWrapper.h" - -namespace Ogre -{ - class PCZSceneManager; - class PCZone; - - /// Factory for PCZones - class _OgrePCZPluginExport PCZoneFactory : public SceneCtlAllocatedObject - { - public: - PCZoneFactory(const String & typeName); - virtual ~PCZoneFactory(); - virtual bool supportsPCZoneType(const String& zoneType) = 0; - virtual PCZone* createPCZone(PCZSceneManager * pczsm, const String& zoneName) = 0; - const String& getFactoryTypeName() const { return mFactoryTypeName; } - /// Factory type name - String mFactoryTypeName; - }; - - // Factory for default zone - class _OgrePCZPluginExport DefaultZoneFactory : public PCZoneFactory - { - public: - DefaultZoneFactory(); - virtual ~DefaultZoneFactory(); - bool supportsPCZoneType(const String& zoneType) override; - PCZone* createPCZone(PCZSceneManager * pczsm, const String& zoneName) override; - }; - - // PCZoneFactory manager class - class _OgrePCZPluginExport PCZoneFactoryManager : public Singleton, public SceneCtlAllocatedObject - { - public: - PCZoneFactoryManager(); - ~PCZoneFactoryManager(); - void registerPCZoneFactory(PCZoneFactory* factory); - void unregisterPCZoneFactory(PCZoneFactory* factory); - PCZone* createPCZone(PCZSceneManager * pczsm, - const String& zoneType, - const String& zoneName); - /// @copydoc Singleton::getSingleton() - static PCZoneFactoryManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static PCZoneFactoryManager* getSingletonPtr(void); - /* PCZoneFactory Iterator - for querying what types of PCZone - factories are available */ - typedef std::map PCZoneFactoryMap; - typedef MapIterator PCZoneFactoryIterator; - /** Return an iterator over the PCZone factories currently registered */ - PCZoneFactoryIterator getPCZoneFactoryIterator(void); - - protected: - PCZoneFactoryMap mPCZoneFactories; - DefaultZoneFactory mDefaultFactory; - }; -} - -#endif diff --git a/PlugIns/PCZSceneManager/include/OgrePortal.h b/PlugIns/PCZSceneManager/include/OgrePortal.h deleted file mode 100644 index a72e10b6274..00000000000 --- a/PlugIns/PCZSceneManager/include/OgrePortal.h +++ /dev/null @@ -1,99 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef PORTAL_H -#define PORTAL_H - -#include "OgrePortalBase.h" - -namespace Ogre -{ - /** Portal datastructure for connecting zones. - - Portals are special constructs which which are used to connect - two Zones in a PCZScene. Portals are defined by 4 coplanr - corners and a direction. Portals are contained within Zones and - are essentially "one way" connectors. Objects and entities can - use them to travel to other Zones, but to return, there must be - a corresponding Portal which connects back to the original zone - from the new zone. - */ - class _OgrePCZPluginExport Portal : public PortalBase - { - public: - Portal(const String &name, const PORTAL_TYPE type = PORTAL_TYPE_QUAD); - virtual ~Portal(); - - void setTargetZone(PCZone* zone); - /** Set the target portal pointer */ - void setTargetPortal(Portal* portal); - - /** Get the Zone the Portal connects to */ - PCZone* getTargetZone() {return mTargetZone;} - /** Get the connected portal (if any) */ - Portal* getTargetPortal() {return mTargetPortal;} - - /** @copydoc MovableObject::getMovableType */ - const String& getMovableType() const override; - - protected: - ///connected Zone - PCZone* mTargetZone; - /** Matching Portal in the target zone (usually in same world space - as this portal, but pointing the opposite direction) - */ - Portal* mTargetPortal; - }; - - /** Factory object for creating Portal instances */ - class _OgrePCZPluginExport PortalFactory : public PortalBaseFactory - { - protected: - MovableObject* createInstanceImpl(const String& name, const NameValuePairList* params) override; - public: - PortalFactory() {} - ~PortalFactory() {} - - static String FACTORY_TYPE_NAME; - static unsigned long FACTORY_TYPE_FLAG; - - const String& getType() const override - { return FACTORY_TYPE_NAME; } - - /** Return true here as we want to get a unique type flag. */ - bool requestTypeFlags() const override - { return true; } - - }; - -} - -#endif - - - diff --git a/PlugIns/PCZSceneManager/include/OgrePortalBase.h b/PlugIns/PCZSceneManager/include/OgrePortalBase.h deleted file mode 100644 index ef9d1662dab..00000000000 --- a/PlugIns/PCZSceneManager/include/OgrePortalBase.h +++ /dev/null @@ -1,303 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef PORTALBASE_H -#define PORTALBASE_H - -#include "OgrePCZPrerequisites.h" -#include "OgreMovableObject.h" -#include "OgreAxisAlignedBox.h" -#include "OgreCapsule.h" -#include "OgreSphere.h" - -namespace Ogre -{ - class PCZSceneNode; - class PCZone; - - /** PortalBase - Base class to Portal and AntiPortal classes. */ - class _OgrePCZPluginExport PortalBase : public MovableObject - { - public: - enum PORTAL_TYPE - { - PORTAL_TYPE_QUAD, - PORTAL_TYPE_AABB, - PORTAL_TYPE_SPHERE - }; - - /** Constructor. */ - PortalBase(const String& name, const PORTAL_TYPE type = PORTAL_TYPE_QUAD); - - /** Destructor. */ - virtual ~PortalBase(); - - /** Retrieves the axis-aligned bounding box for this object in world coordinates. */ - const AxisAlignedBox& getWorldBoundingBox(bool derive = false) const override; - /** Retrieves the worldspace bounding sphere for this object. */ - const Sphere& getWorldBoundingSphere(bool derive = false) const override; - - /** Set the SceneNode the Portal is associated with */ - void setNode(SceneNode* sn); - /** Set the current home zone of the portal */ - void setCurrentHomeZone(PCZone* zone); - /** Set the zone this portal should be moved to */ - void setNewHomeZone(PCZone* zone); - - /** Set the local coordinates of one of the portal corners */ - void setCorner(int index, const Vector3& point); - /** Set the local coordinates of all of the portal corners */ - void setCorners(const Vector3* corners); - /** Set the "inward/outward norm" direction of AAB or SPHERE portals - NOTE: UNIT_Z = "outward" norm, NEGATIVE_UNIT_Z = "inward" norm - NOTE: Remember, Portal norms always point towards the zone they are "in". - */ - void setDirection(const Vector3 &d) - { - switch (mType) - { - default: - case PORTAL_TYPE_QUAD: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Cannot setDirection on a Quad type portal", - "Portal::setDirection"); - break; - case PORTAL_TYPE_AABB: - case PORTAL_TYPE_SPHERE: - if (d != Vector3::UNIT_Z && - d != Vector3::NEGATIVE_UNIT_Z) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Valid parameters are Vector3::UNIT_Z or Vector3::NEGATIVE_UNIT_Z", - "Portal::setDirection"); - return; - } - mDirection = d; - break; - } - } - /** Calculate the local direction and radius of the portal */ - void calcDirectionAndRadius() const; - - /** Get the type of portal */ - PORTAL_TYPE getType() const {return mType;} - /** Retrieve the radius of the portal in world coordinates */ - Real getDerivedRadius() const - { return mDerivedRadius; } - - /** Get the Zone the Portal is currently "in" */ - PCZone* getCurrentHomeZone() - { return mCurrentHomeZone; } - /** Get the Zone the Portal should be moved to */ - PCZone* getNewHomeZone() - { return mNewHomeZone; } - - /** Get the coordinates of one of the portal corners in local space */ - const Vector3& getCorner(int index) const - { return mCorners[index]; } - /** Get the direction vector of the portal in local space */ - const Vector3& getDirection() const - { return mDirection; } - - /** Get the derived (world) coordinates of one of the portal corners */ - const Vector3& getDerivedCorner(int index) const - { return mDerivedCorners[index]; } - /** Get the direction of the portal in world coordinates */ - const Vector3& getDerivedDirection() const - { return mDerivedDirection; } - /** Get the position (centerpoint) of the portal in world coordinates */ - const Vector3& getDerivedCP() const - { return mDerivedCP; } - /** Get the sphere centered on the derived CP of the portal in world coordinates */ - const Sphere& getDerivedSphere() const - { return mDerivedSphere; } - /** Get the portal plane in world coordinates */ - const Plane& getDerivedPlane() const - { return mDerivedPlane; } - - /** Get the previous position (centerpoint) of the portal in world coordinates */ - const Vector3& getPrevDerivedCP() const - { return mPrevDerivedCP; } - /** Get the previous portal plane in world coordinates */ - const Plane& getPrevDerivedPlane() const - { return mPrevDerivedPlane; } - - /** Update the derived values */ - void updateDerivedValues() const; - /** Adjust the portal so that it is centered and oriented on the given node */ - void adjustNodeToMatch(SceneNode* node); - /** enable the portal */ - void setEnabled(bool value) - { mEnabled = value; } - /** Check if portal is enabled */ - bool getEnabled() const {return mEnabled;} - - - enum PortalIntersectResult - { - NO_INTERSECT, - INTERSECT_NO_CROSS, - INTERSECT_BACK_NO_CROSS, - INTERSECT_CROSS - }; - /** Check if portal intersects an aab */ - bool intersects(const AxisAlignedBox& aab); - - /** Check if portal intersects an sphere */ - bool intersects(const Sphere& sphere); - - /** Check if portal intersects a plane bounded volume */ - bool intersects(const PlaneBoundedVolume& pbv); - - /** Check if portal intersects a ray */ - bool intersects(const Ray& ray); - - /** Check for intersection between portal & scenenode (also determines - * if scenenode crosses over portal - */ - PortalIntersectResult intersects(PCZSceneNode* sn); - - /** Check if portal crossed over portal */ - bool crossedPortal(const PortalBase* otherPortal); - /** Check if portal touches another portal */ - bool closeTo(const PortalBase* otherPortal); - - /** @copydoc MovableObject::getBoundingBox */ - const AxisAlignedBox& getBoundingBox() const override; - - /** @copydoc MovableObject::getBoundingRadius */ - Real getBoundingRadius() const override; - - /** @copydoc MovableObject::_updateRenderQueue */ - void _updateRenderQueue(RenderQueue* queue) override - { /* Draw debug info if needed? */ } - - /** @copydoc MovableObject::visitRenderables */ - void visitRenderables(Renderable::Visitor* visitor, bool debugRenderables = false) override - { } - - /** Called when scene node moved. */ - void _notifyMoved() override - { - updateDerivedValues(); - mWasMoved = true; - } - - /** Called when attached to a scene node. */ - void _notifyAttached(Node* parent, bool isTagPoint = false) override - { - MovableObject::_notifyAttached(parent, isTagPoint); - mDerivedUpToDate = false; - } - - /** Returns true if portal needs update. */ - bool needUpdate(); - - /** Returns an updated capsule of the portal for intersection test. */ - const Capsule& getCapsule() const; - - /** Returns an updated AAB of the portal for intersection test. */ - const AxisAlignedBox& getAAB(); - - protected: - // Type of portal (quad, aabb, or sphere) - PORTAL_TYPE mType; - /// Zone this portal is currently owned by (in) - PCZone * mCurrentHomeZone; - /// Zone to transfer this portal to - PCZone * mNewHomeZone; - /// Corners of the portal - coordinates are relative to the sceneNode - // NOTE: there are 4 corners if the portal is a quad type - // there are 2 corners if the portal is an AABB type - // there are 2 corners if the portal is a sphere type (center and point on sphere) - Vector3 * mCorners; - /// Direction ("Norm") of the portal - - // NOTE: For a Quad portal, determined by the 1st 3 corners. - // NOTE: For AABB & SPHERE portals, we only have "inward" or "outward" cases. - // To indicate "outward", the Direction is UNIT_Z - // to indicate "inward", the Direction is NEGATIVE_UNIT_Z - mutable Vector3 mDirection; - /// Radius of the sphere enclosing the portal - // NOTE: For aabb portals, this value is the distance from the center of the aab to a corner - mutable Real mRadius; - /// Local Centerpoint of the portal - mutable Vector3 mLocalCP; - /// Derived (world coordinates) Corners of the portal - // NOTE: there are 4 corners if the portal is a quad type - // there are 2 corners if the portal is an AABB type (min corner & max corner) - // there are 2 corners if the portal is a sphere type (center and point on sphere) - Vector3 * mDerivedCorners; - /// Derived (world coordinates) direction of the portal - // NOTE: Only applicable for a Quad portal - mutable Vector3 mDerivedDirection; - /// Derived (world coordinates) radius of the sphere enclosing the portal - mutable Real mDerivedRadius; - /// Derived (world coordinates) of portal (center point) - mutable Vector3 mDerivedCP; - /// Sphere of the portal centered on the derived CP - mutable Sphere mDerivedSphere; - /// Derived (world coordinates) Plane of the portal - // NOTE: Only applicable for a Quad portal - mutable Plane mDerivedPlane; - /// Previous frame portal cp (in world coordinates) - mutable Vector3 mPrevDerivedCP; - /// Previous frame derived plane - // NOTE: Only applicable for a Quad portal - mutable Plane mPrevDerivedPlane; - /// Flag indicating whether or not local values are up-to-date - mutable bool mLocalsUpToDate; - /// Flag indicating whether or not derived values are up-to-date - mutable bool mDerivedUpToDate; - /// Previous world transform - mutable Affine3 mPrevWorldTransform; - /// Flag defining if portal is enabled or disabled. - bool mEnabled; - /// Cache of portal's capsule. - mutable Capsule mPortalCapsule; - /// Cache of portal's AAB that contains the bound of portal movement. - mutable AxisAlignedBox mPortalAAB; - /// Cache of portal's previous AAB. - mutable AxisAlignedBox mPrevPortalAAB; - /// Cache of portal's local AAB. - mutable AxisAlignedBox mLocalPortalAAB; - /// Defined if portal was moved previously. - mutable bool mWasMoved; - }; - - /** Factory object for creating Portal instances */ - class _OgrePCZPluginExport PortalBaseFactory : public MovableObjectFactory - { - protected: - /** Get the portal type from name value pair. */ - PortalBase::PORTAL_TYPE getPortalType(const NameValuePairList* params); - - }; - -} - -#endif diff --git a/PlugIns/PCZSceneManager/include/OgreSegment.h b/PlugIns/PCZSceneManager/include/OgreSegment.h deleted file mode 100644 index 0848d62350a..00000000000 --- a/PlugIns/PCZSceneManager/include/OgreSegment.h +++ /dev/null @@ -1,77 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef SEGMENT_H -#define SEGMENT_H - -#include "OgreVector.h" - -namespace Ogre -{ - class Capsule; - - /** 3D Line Segment class for intersection testing in Ogre3D - - Some algorithms based off code from the Wild Magic library by Dave Eberly - */ - class Segment - { - public: - // The segment is represented as P+t*D, where P is the segment origin, - // D is a unit-length direction vector and |t| <= e. The value e is - // referred to as the extent of the segment. The end points of the - // segment are P-e*D and P+e*D. The user must ensure that the direction - // vector is unit-length. The representation for a segment is analogous - // to that for an oriented bounding box. P is the center, D is the - // axis direction, and e is the extent. - - - // construction - Segment (); // uninitialized - Segment (const Vector3&, const Vector3&, Real); - - // set values - void set(const Vector3& newOrigin, const Vector3& newEnd); - void setOrigin(const Vector3& newOrigin); - void setEndPoint(const Vector3& newEndpoint); - - // functions to calculate distance to another segment - Real distance(const Segment& otherSegment) const; - Real squaredDistance(const Segment& otherSegment) const; - - // intersect check between segment & capsule - bool intersects(const Capsule&) const; - - // defining variables - Vector3 mOrigin; - Vector3 mDirection; - Real mExtent; - }; -} - -#endif //SEGMENT_H diff --git a/PlugIns/PCZSceneManager/src/OgreAntiPortal.cpp b/PlugIns/PCZSceneManager/src/OgreAntiPortal.cpp deleted file mode 100644 index 27ebbbf2b08..00000000000 --- a/PlugIns/PCZSceneManager/src/OgreAntiPortal.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -AntiPortal.cpp - - -*/ - -#include "OgreAntiPortal.h" - -using namespace Ogre; - -AntiPortal::AntiPortal(const String& name, const PORTAL_TYPE type) - : PortalBase(name, type) -{ -} - -AntiPortal::~AntiPortal() -{ -} - -/** @copydoc MovableObject::getMovableType. */ -const String& AntiPortal::getMovableType() const -{ - return AntiPortalFactory::FACTORY_TYPE_NAME; -} - -//----------------------------------------------------------------------- -String AntiPortalFactory::FACTORY_TYPE_NAME = "AntiPortal"; -unsigned long AntiPortalFactory::FACTORY_TYPE_FLAG = 0xFFFFFFFF; -//----------------------------------------------------------------------- - -MovableObject* AntiPortalFactory::createInstanceImpl(const String& name, const NameValuePairList* params) -{ - return OGRE_NEW AntiPortal(name, getPortalType(params)); -} \ No newline at end of file diff --git a/PlugIns/PCZSceneManager/src/OgreCapsule.cpp b/PlugIns/PCZSceneManager/src/OgreCapsule.cpp deleted file mode 100644 index 5aa2f5c9dc1..00000000000 --- a/PlugIns/PCZSceneManager/src/OgreCapsule.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -OgreCapsule.cpp - 3D Line-Swept-Sphere class for intersection testing in Ogre3D -Some algorithms based off code from the Wild Magic library by Dave Eberly ------------------------------------------------------------------------------ -begin : Mon Apr 02 2007 -author : Eric Cha -email : ericc@xenopi.com ------------------------------------------------------------------------------ -*/ - -#include "OgreCapsule.h" - -using namespace Ogre; - -//---------------------------------------------------------------------------- - -Capsule::Capsule() -{ - // uninitialized -} -//---------------------------------------------------------------------------- -Capsule::Capsule(const Segment& segment, Real radius) - : mSegment(segment), - mRadius(radius) -{ -} -//---------------------------------------------------------------------------- -void Capsule::set(const Vector3& newOrigin, const Vector3& newEnd, Real newRadius) -{ - mSegment.set(newOrigin, newEnd); - mRadius = newRadius; -} -//---------------------------------------------------------------------------- -void Capsule::setOrigin(const Vector3& newOrigin) -{ - mSegment.mOrigin = newOrigin; -} -//---------------------------------------------------------------------------- -void Capsule::setEndPoint(const Vector3& newEndpoint) -{ - mSegment.setEndPoint(newEndpoint); -} -//---------------------------------------------------------------------------- -void Capsule::setRadius(Real newRadius) -{ - mRadius = newRadius; -} -//---------------------------------------------------------------------------- -bool Capsule::intersects(const Capsule& otherCapsule) const -{ - Real fDistance = mSegment.distance(otherCapsule.mSegment); - Real fRSum = mRadius + otherCapsule.mRadius; - return fDistance <= fRSum; -} -//---------------------------------------------------------------------------- -bool Capsule::intersects(const Segment& segment) const -{ - Real fDist = segment.distance(mSegment); - return fDist <= mRadius; -} -//---------------------------------------------------------------------------- diff --git a/PlugIns/PCZSceneManager/src/OgreDefaultZone.cpp b/PlugIns/PCZSceneManager/src/OgreDefaultZone.cpp deleted file mode 100644 index bc1c154a126..00000000000 --- a/PlugIns/PCZSceneManager/src/OgreDefaultZone.cpp +++ /dev/null @@ -1,1076 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -DefaultZone.cpp - Default PCZone implementation ------------------------------------------------------------------------------ -begin : Tue Feb 20 2007 -author : Eric Cha -email : ericc@xenopi.com - ------------------------------------------------------------------------------ -*/ - -#include "OgreDefaultZone.h" -#include "OgreSceneNode.h" -#include "OgreAntiPortal.h" -#include "OgrePortal.h" -#include "OgreEntity.h" -#include "OgrePCZSceneNode.h" -#include "OgrePCZSceneManager.h" -#include "OgrePCZLight.h" -#include "OgrePCZCamera.h" - -namespace Ogre -{ - - DefaultZone::DefaultZone( PCZSceneManager * creator, const String& name ) - : PCZone(creator, name) - { - mZoneTypeName = "ZoneType_Default"; - } - - DefaultZone::~DefaultZone() - { - } - - /** Set the enclosure node for this Zone - */ - void DefaultZone::setEnclosureNode(PCZSceneNode * node) - { - mEnclosureNode = node; - // anchor the node to this zone - node->anchorToHomeZone(this); - } - - // this call adds the given node to either the zone's list - // of nodes at home in the zone, or to the list of visiting nodes - // NOTE: The list is decided by the node's homeZone value, so - // that must be set correctly before calling this function. - void DefaultZone::_addNode( PCZSceneNode * n ) - { - if (n->getHomeZone() == this) - { - // add a reference to this node in the "nodes at home in this zone" list - mHomeNodeList.insert( n ); - } - else - { - // add a reference to this node in the "nodes visiting this zone" list - mVisitorNodeList.insert( n ); - } - } - - void DefaultZone::removeNode( PCZSceneNode * n ) - { - if (n->getHomeZone() == this) - { - mHomeNodeList.erase( n ); - } - else - { - mVisitorNodeList.erase( n ); - } - } - - /** Indicates whether or not this zone requires zone-specific data for - * each scene node - */ - bool DefaultZone::requiresZoneSpecificNodeData(void) - { - // regular DefaultZones don't require any zone specific node data - return false; - } - - /* Recursively check for intersection of the given scene node - * with zone portals. If the node touches a portal, then the - * connected zone is assumed to be touched. The zone adds - * the node to its node list and the node adds the zone to - * its visiting zone list. - * - * NOTE: This function assumes that the home zone of the node - * is correct. The function "_updateHomeZone" in PCZSceneManager - * takes care of this and should have been called before - * this function. - */ - - void DefaultZone::_checkNodeAgainstPortals(PCZSceneNode * pczsn, Portal * ignorePortal) - { - if (pczsn == mEnclosureNode || - pczsn->allowedToVisit() == false) - { - // don't do any checking of enclosure node versus portals - return; - } - - PCZone * connectedZone; - for (auto p : mPortals) - { - //Check if the portal intersects the node - if (p != ignorePortal && - p->intersects(pczsn) != Portal::NO_INTERSECT) - { - // node is touching this portal - connectedZone = p->getTargetZone(); - // add zone to the nodes visiting zone list unless it is the home zone of the node - if (connectedZone != pczsn->getHomeZone() && - !pczsn->isVisitingZone(connectedZone)) - { - pczsn->addZoneToVisitingZonesMap(connectedZone); - // tell the connected zone that the node is visiting it - connectedZone->_addNode(pczsn); - //recurse into the connected zone - connectedZone->_checkNodeAgainstPortals(pczsn, p->getTargetPortal()); - } - } - } - } - - /** (recursive) check the given light against all portals in the zone - * NOTE: This is the default implementation, which doesn't take advantage - * of any zone-specific optimizations for checking portal visibility - */ - void DefaultZone::_checkLightAgainstPortals(PCZLight *light, - unsigned long frameCount, - PCZFrustum *portalFrustum, - Portal * ignorePortal) - { - for (auto p : mPortals) - { - if (p != ignorePortal) - { - // calculate the direction vector from light to portal - Vector3 lightToPortal = p->getDerivedCP() - light->getDerivedPosition(); - if (portalFrustum->isVisible(p)) - { - // portal is facing the light, but some light types need to - // check illumination radius too. - PCZone * targetZone = p->getTargetZone(); - switch(light->getType()) - { - case Light::LT_POINT: - // point lights - just check if within illumination range - if (lightToPortal.length() <= light->getAttenuationRange()) - { - // if portal is quad portal it must be pointing towards the light - if ((p->getType() == Portal::PORTAL_TYPE_QUAD && lightToPortal.dotProduct(p->getDerivedDirection()) < 0.0) || - (p->getType() != Portal::PORTAL_TYPE_QUAD)) - { - if (!light->affectsZone(targetZone)) - { - light->addZoneToAffectedZonesList(targetZone); - if (targetZone->getLastVisibleFrame() == frameCount) - { - light->setAffectsVisibleZone(true); - } - // set culling frustum from the portal - portalFrustum->addPortalCullingPlanes(p); - // recurse into the target zone of the portal - p->getTargetZone()->_checkLightAgainstPortals(light, - frameCount, - portalFrustum, - p->getTargetPortal()); - // remove the planes added by this portal - portalFrustum->removePortalCullingPlanes(p); - } - } - } - break; - case Light::LT_DIRECTIONAL: - // directionals have infinite range, so just make sure - // the direction is facing the portal - if (lightToPortal.dotProduct(light->getDerivedDirection()) >= 0.0) - { - // if portal is quad portal it must be pointing towards the light - if ((p->getType() == Portal::PORTAL_TYPE_QUAD && lightToPortal.dotProduct(p->getDerivedDirection()) < 0.0) || - (p->getType() != Portal::PORTAL_TYPE_QUAD)) - { - if (!light->affectsZone(targetZone)) - { - light->addZoneToAffectedZonesList(targetZone); - if (targetZone->getLastVisibleFrame() == frameCount) - { - light->setAffectsVisibleZone(true); - } - // set culling frustum from the portal - portalFrustum->addPortalCullingPlanes(p); - // recurse into the target zone of the portal - p->getTargetZone()->_checkLightAgainstPortals(light, - frameCount, - portalFrustum, - p->getTargetPortal()); - // remove the planes added by this portal - portalFrustum->removePortalCullingPlanes(p); - } - } - } - break; - case Light::LT_RECTLIGHT: - case Light::LT_SPOTLIGHT: - // spotlights - just check if within illumination range - // Technically, we should check if the portal is within - // the cone of illumination, but for now, we'll leave that - // as a future optimisation. - if (lightToPortal.length() <= light->getAttenuationRange()) - { - // if portal is quad portal it must be pointing towards the light - if ((p->getType() == Portal::PORTAL_TYPE_QUAD && lightToPortal.dotProduct(p->getDerivedDirection()) < 0.0) || - (p->getType() != Portal::PORTAL_TYPE_QUAD)) - { - if (!light->affectsZone(targetZone)) - { - light->addZoneToAffectedZonesList(targetZone); - if (targetZone->getLastVisibleFrame() == frameCount) - { - light->setAffectsVisibleZone(true); - } - // set culling frustum from the portal - portalFrustum->addPortalCullingPlanes(p); - // recurse into the target zone of the portal - p->getTargetZone()->_checkLightAgainstPortals(light, - frameCount, - portalFrustum, - p->getTargetPortal()); - // remove the planes added by this portal - portalFrustum->removePortalCullingPlanes(p); - } - } - } - break; - } - } - } - } - } - - /** Update the zone data for the portals in the zone - * NOTE: All portal spatial data must be up-to-date before calling this routine. - */ - void DefaultZone::updatePortalsZoneData(void) - { - PortalList transferPortalList; - AntiPortalList transferAntiPortalList; - // check each portal to see if it's intersecting another portal of smaller size - for ( PortalList::iterator it = mPortals.begin(); it != mPortals.end(); ++it ) - { - Portal * p = *it; - bool portalNeedUpdate = p->needUpdate(); - - Real pRadius = p->getDerivedRadius(); - - // First we check against portals in the SAME zone (and only if they have a - // target zone different from the home zone) - // Here we check only against portals that moved and of smaller size. - - // We do not need to check portal againts previous portals - // since it would have been already checked. - // Hence we start with the next portal after the current portal. - PortalList::iterator it2 = it; - for ( ++it2; it2 != mPortals.end(); ++it2 ) - { - Portal * p2 = (*it2); - - // Skip portal if it doesn't need updating. - // If both portals are not moving, then there's no need to check between them. - if (!portalNeedUpdate && !p2->needUpdate()) continue; - - // Skip portal if it's not pointing to another zone. - if (p2->getTargetZone() == this) continue; - - // Skip portal if it's pointing to the same target zone as this portal points to - if (p2->getTargetZone() == p->getTargetZone()) continue; - - if (pRadius > p2->getDerivedRadius()) - { - // Portal#1 is bigger than Portal#2, check for crossing - if (p2->getCurrentHomeZone() != p->getTargetZone() && p2->crossedPortal(p)) - { - // portal#2 crossed portal#1 - flag portal#2 to be moved to portal#1's target zone - p2->setNewHomeZone(p->getTargetZone()); - transferPortalList.push_back(p2); - } - } - else if (pRadius < p2->getDerivedRadius()) - { - // Portal #2 is bigger than Portal #1, check for crossing - if (p->getCurrentHomeZone() != p2->getTargetZone() && p->crossedPortal(p2)) - { - // portal#1 crossed portal#2 - flag portal#1 to be moved to portal#2's target zone - p->setNewHomeZone(p2->getTargetZone()); - transferPortalList.push_back(p); - continue; - } - } - } - - // Secondly we check againts the antiportals of this zone. - for (auto ap : mAntiPortals) - { - // Skip portal if it doesn't need updating. - // If both portals are not moving, then there's no need to check between them. - if (!portalNeedUpdate && !ap->needUpdate()) continue; - - // only check for crossing if AntiPortal smaller than portal. - if (pRadius > ap->getDerivedRadius()) - { - // Portal#1 is bigger than AntiPortal, check for crossing - if (ap->crossedPortal(p)) - { - // AntiPortal crossed Portal#1 - flag AntiPortal to be moved to Portal#1's target zone - ap->setNewHomeZone(p->getTargetZone()); - transferAntiPortalList.push_back(ap); - } - } - } - - // Skip portal if it doesn't need updating. - if (!portalNeedUpdate) continue; - - // Thirdly we check against portals in the target zone (and only if that target - // zone is different from the home zone) - PCZone * tzone = p->getTargetZone(); - if (tzone != this) - { - for (auto p3 : tzone->mPortals) - { - // only check against bigger regular portals - if (pRadius < p3->getDerivedRadius()) - { - // Portal#3 is bigger than Portal#1, check for crossing - if (p->getCurrentHomeZone() != p3->getTargetZone() && p->crossedPortal(p3)) - { - // Portal#1 crossed Portal#3 - switch target zones for Portal#1 - p->setTargetZone(p3->getTargetZone()); - break; - } - } - } - } - } - // transfer any portals to new zones that have been flagged - for (auto p : transferPortalList) - { - if (p->getNewHomeZone() != 0) - { - _removePortal(p); - p->getNewHomeZone()->_addPortal(p); - p->setNewHomeZone(0); - } - } - // transfer any anti portals to new zones that have been flagged - for (auto p : transferAntiPortalList) - { - if (p->getNewHomeZone() != 0) - { - _removeAntiPortal(p); - p->getNewHomeZone()->_addAntiPortal(p); - p->setNewHomeZone(0); - } - } - } - - /** Mark nodes dirty base on moving portals. */ - void DefaultZone::dirtyNodeByMovingPortals(void) - { - // default zone has no space partitioning algo. - // So it's impracticle to do any AABB to find node of interest by portals. - // Hence for this case, we just mark all nodes as dirty as long as there's - // any moving portal within the zone. - for (auto & mPortal : mPortals) - { - if (mPortal->needUpdate()) - { - // Mark all home nodes. - PCZSceneNodeList::iterator it2 = mHomeNodeList.begin(); - while ( it2 != mHomeNodeList.end() ) - { - (*it2)->setMoved(true); - ++it2; - } - - // Mark all visitor nodes. - it2 = mVisitorNodeList.begin(); - while ( it2 != mVisitorNodeList.end() ) - { - (*it2)->setMoved(true); - ++it2; - } - return; - } - } - } - - /* The following function checks if a node has left it's current home zone. - * This is done by checking each portal in the zone. If the node has crossed - * the portal, then the current zone is no longer the home zone of the node. The - * function then recurses into the connected zones. Once a zone is found where - * the node does NOT cross out through a portal, that zone is the new home zone. - NOTE: For this function to work, the node must start out in the proper zone to - begin with! - */ - PCZone* DefaultZone::updateNodeHomeZone( PCZSceneNode * pczsn, bool allowBackTouches ) - { - // default to newHomeZone being the current home zone - PCZone * newHomeZone = pczsn->getHomeZone(); - - // Check all portals of the start zone for crossings! - Portal* portal; - PortalList::iterator pi, piend; - piend = mPortals.end(); - for (pi = mPortals.begin(); pi != piend; pi++) - { - portal = *pi; - - Portal::PortalIntersectResult pir = portal->intersects(pczsn); - switch (pir) - { - default: - case Portal::NO_INTERSECT: // node does not intersect portal - do nothing - case Portal::INTERSECT_NO_CROSS:// node intersects but does not cross portal - do nothing - break; - case Portal::INTERSECT_BACK_NO_CROSS:// node intersects but on the back of the portal - if (allowBackTouches) - { - // node is on wrong side of the portal - fix if we're allowing backside touches - if (portal->getTargetZone() != this && - portal->getTargetZone() != pczsn->getHomeZone()) - { - // set the home zone of the node to the target zone of the portal - pczsn->setHomeZone(portal->getTargetZone()); - // continue checking for portal crossings in the new zone - newHomeZone = portal->getTargetZone()->updateNodeHomeZone(pczsn, false); - } - } - break; - case Portal::INTERSECT_CROSS: - // node intersects and crosses the portal - recurse into that zone as new home zone - if (portal->getTargetZone() != this && - portal->getTargetZone() != pczsn->getHomeZone()) - { - // set the home zone of the node to the target zone of the portal - pczsn->setHomeZone(portal->getTargetZone()); - // continue checking for portal crossings in the new zone - newHomeZone = portal->getTargetZone()->updateNodeHomeZone(pczsn, true); - } - break; - } - } - - // return the new home zone - return newHomeZone; - - } - - /* - // Recursively walk the zones, adding all visible SceneNodes to the list of visible nodes. - */ - void DefaultZone::findVisibleNodes(PCZCamera *camera, - NodeList & visibleNodeList, - RenderQueue * queue, - VisibleObjectsBoundsInfo* visibleBounds, - bool onlyShadowCasters, - bool displayNodes, - bool showBoundingBoxes) - { - - //return immediately if nothing is in the zone. - if (mHomeNodeList.empty() && - mVisitorNodeList.empty() && - mPortals.empty()) - return ; - - // Else, the zone is automatically assumed to be visible since either - // it is the camera the zone is in, or it was reached because - // a connecting portal was deemed visible to the camera. - - // enable sky if called to do so for this zone - if (mHasSky) - { - // enable sky - mPCZSM->enableSky(true); - } - - // find visible nodes at home in the zone - bool vis; - PCZSceneNodeList::iterator it = mHomeNodeList.begin(); - while ( it != mHomeNodeList.end() ) - { - PCZSceneNode * pczsn = *it; - // if the scene node is already visible, then we can skip it - if (pczsn->getLastVisibleFrame() != mLastVisibleFrame || - pczsn->getLastVisibleFromCamera() != camera) - { - // for a scene node, check visibility using AABB - vis = camera ->isVisible( pczsn -> _getWorldAABB() ); - if ( vis ) - { - // add it to the list of visible nodes - visibleNodeList.push_back( pczsn ); - // add the node to the render queue - pczsn -> _addToRenderQueue(camera, queue, onlyShadowCasters, visibleBounds ); - // if we are displaying nodes, add the node renderable to the queue - if (mPCZSM->getDebugDrawer()) - { - mPCZSM->getDebugDrawer()->drawSceneNode(pczsn); - } - // flag the node as being visible this frame - pczsn->setLastVisibleFrame(mLastVisibleFrame); - pczsn->setLastVisibleFromCamera(camera); - } - } - ++it; - } - // find visible visitor nodes - it = mVisitorNodeList.begin(); - while ( it != mVisitorNodeList.end() ) - { - PCZSceneNode * pczsn = *it; - // if the scene node is already visible, then we can skip it - if (pczsn->getLastVisibleFrame() != mLastVisibleFrame || - pczsn->getLastVisibleFromCamera() != camera) - { - // for a scene node, check visibility using AABB - vis = camera ->isVisible( pczsn -> _getWorldAABB() ); - if ( vis ) - { - // add it to the list of visible nodes - visibleNodeList.push_back( pczsn ); - // add the node to the render queue - pczsn->_addToRenderQueue(camera, queue, onlyShadowCasters, visibleBounds ); - // if we are displaying nodes, add the node renderable to the queue - if (mPCZSM->getDebugDrawer()) - { - mPCZSM->getDebugDrawer()->drawSceneNode(pczsn); - } - // flag the node as being visible this frame - pczsn->setLastVisibleFrame(mLastVisibleFrame); - pczsn->setLastVisibleFromCamera(camera); - } - } - ++it; - } - - // Here we merge both portal and antiportal visible to the camera into one list. - // Then we sort them in the order from nearest to furthest from camera. - PortalBaseList sortedPortalList; - for (auto portal : mAntiPortals) - { - if (camera->isVisible(portal)) - { - sortedPortalList.push_back(portal); - } - } - for (auto portal : mPortals) - { - if (camera->isVisible(portal)) - { - sortedPortalList.push_back(portal); - } - } - const Vector3& cameraOrigin(camera->getDerivedPosition()); - std::sort(sortedPortalList.begin(), sortedPortalList.end(), - PortalSortDistance(cameraOrigin)); - - // create a standalone frustum for anti portal use. - // we're doing this instead of using camera because we don't need - // to do camera frustum check again. - PCZFrustum antiPortalFrustum; - antiPortalFrustum.setOrigin(cameraOrigin); - antiPortalFrustum.setProjectionType(camera->getProjectionType()); - - // now we do culling check and remove hidden portals. - // whenever we get a portal in the main loop, we can be sure that it is not - // occluded by AntiPortal. So we do traversal right there and then. - // This is because the portal list has been sorted. - size_t sortedPortalListCount = sortedPortalList.size(); - for (size_t i = 0; i < sortedPortalListCount; ++i) - { - PortalBase* portalBase = sortedPortalList[i]; - if (!portalBase) continue; // skip removed portal. - - if (portalBase->getTypeFlags() == PortalFactory::FACTORY_TYPE_FLAG) - { - Portal* portal = static_cast(portalBase); - // portal is visible. Add the portal as extra culling planes to camera - int planes_added = camera->addPortalCullingPlanes(portal); - // tell target zone it's visible this frame - portal->getTargetZone()->setLastVisibleFrame(mLastVisibleFrame); - portal->getTargetZone()->setLastVisibleFromCamera(camera); - // recurse into the connected zone - portal->getTargetZone()->findVisibleNodes(camera, - visibleNodeList, - queue, - visibleBounds, - onlyShadowCasters, - displayNodes, - showBoundingBoxes); - if (planes_added > 0) - { - // Then remove the extra culling planes added before going to the next portal in the list. - camera->removePortalCullingPlanes(portal); - } - } - else if (i < sortedPortalListCount) // skip antiportal test if it is the last item in the list. - { - // this is an anti portal. So we use it to test preceding portals in the list. - AntiPortal* antiPortal = static_cast(portalBase); - int planes_added = antiPortalFrustum.addPortalCullingPlanes(antiPortal); - - for (size_t j = i + 1; j < sortedPortalListCount; ++j) - { - PortalBase* otherPortal = sortedPortalList[j]; - // Since this is an antiportal, we are doing the inverse of the test. - // Here if the portal is fully visible in the anti portal fustrum, it means it's hidden. - if (otherPortal && antiPortalFrustum.isFullyVisible(otherPortal)) - sortedPortalList[j] = NULL; - } - - if (planes_added > 0) - { - // Then remove the extra culling planes added before going to the next portal in the list. - antiPortalFrustum.removePortalCullingPlanes(antiPortal); - } - } - } - } - - // --- find nodes which intersect various types of BV's --- - void DefaultZone::_findNodes( const AxisAlignedBox &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude ) - { - // if this zone has an enclosure, check against the enclosure AABB first - if (mEnclosureNode) - { - if (!mEnclosureNode->_getWorldAABB().intersects(t)) - { - // AABB of zone does not intersect t, just return. - return; - } - } - - // check nodes at home in this zone - PCZSceneNodeList::iterator it = mHomeNodeList.begin(); - while ( it != mHomeNodeList.end() ) - { - PCZSceneNode * pczsn = *it; - if ( pczsn != exclude ) - { - // make sure node is not already in the list (might have been added in another - // zone it was visiting) - PCZSceneNodeList::iterator it2 = list.find(pczsn); - if (it2 == list.end()) - { - bool nsect = t.intersects( pczsn -> _getWorldAABB() ); - if ( nsect ) - { - list.insert( pczsn ); - } - } - } - ++it; - } - - if (includeVisitors) - { - // check visitor nodes - PCZSceneNodeList::iterator iter = mVisitorNodeList.begin(); - while ( iter != mVisitorNodeList.end() ) - { - PCZSceneNode * pczsn = *iter; - if ( pczsn != exclude ) - { - // make sure node is not already in the list (might have been added in another - // zone it was visiting) - PCZSceneNodeList::iterator it2 = list.find(pczsn); - if (it2 == list.end()) - { - bool nsect = t.intersects( pczsn -> _getWorldAABB() ); - if ( nsect ) - { - list.insert( pczsn ); - } - } - } - ++iter; - } - } - - // if asked to, recurse through portals - if (recurseThruPortals) - { - PortalList::iterator pit = mPortals.begin(); - while ( pit != mPortals.end() ) - { - Portal * portal = *pit; - // check portal versus bounding box - if (portal->intersects(t)) - { - // make sure portal hasn't already been recursed through - PortalList::iterator pit2 = std::find(visitedPortals.begin(), visitedPortals.end(), portal); - if (pit2 == visitedPortals.end()) - { - // save portal to the visitedPortals list - visitedPortals.push_front(portal); - // recurse into the connected zone - portal->getTargetZone()->_findNodes(t, - list, - visitedPortals, - includeVisitors, - recurseThruPortals, - exclude); - } - } - pit++; - } - } - } - - void DefaultZone::_findNodes(const Sphere &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude ) - { - // if this zone has an enclosure, check against the enclosure AABB first - if (mEnclosureNode) - { - if (!mEnclosureNode->_getWorldAABB().intersects(t)) - { - // AABB of zone does not intersect t, just return. - return; - } - } - - // check nodes at home in this zone - PCZSceneNodeList::iterator it = mHomeNodeList.begin(); - while ( it != mHomeNodeList.end() ) - { - PCZSceneNode * pczsn = *it; - if ( pczsn != exclude ) - { - // make sure node is not already in the list (might have been added in another - // zone it was visiting) - PCZSceneNodeList::iterator it2 = list.find(pczsn); - if (it2 == list.end()) - { - bool nsect = t.intersects( pczsn -> _getWorldAABB() ); - if ( nsect ) - { - list.insert( pczsn ); - } - } - } - ++it; - } - - if (includeVisitors) - { - // check visitor nodes - PCZSceneNodeList::iterator iter = mVisitorNodeList.begin(); - while ( iter != mVisitorNodeList.end() ) - { - PCZSceneNode * pczsn = *iter; - if ( pczsn != exclude ) - { - // make sure node is not already in the list (might have been added in another - // zone it was visiting) - PCZSceneNodeList::iterator it2 = list.find(pczsn); - if (it2 == list.end()) - { - bool nsect = t.intersects( pczsn -> _getWorldAABB() ); - if ( nsect ) - { - list.insert( pczsn ); - } - } - } - ++iter; - } - } - - // if asked to, recurse through portals - if (recurseThruPortals) - { - PortalList::iterator pit = mPortals.begin(); - while ( pit != mPortals.end() ) - { - Portal * portal = *pit; - // check portal versus boundign box - if (portal->intersects(t)) - { - // make sure portal hasn't already been recursed through - PortalList::iterator pit2 = std::find(visitedPortals.begin(), visitedPortals.end(), portal); - if (pit2 == visitedPortals.end()) - { - // save portal to the visitedPortals list - visitedPortals.push_front(portal); - // recurse into the connected zone - portal->getTargetZone()->_findNodes(t, - list, - visitedPortals, - includeVisitors, - recurseThruPortals, - exclude); - } - } - pit++; - } - } - - } - - void DefaultZone::_findNodes( const PlaneBoundedVolume &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude) - { - // if this zone has an enclosure, check against the enclosure AABB first - if (mEnclosureNode) - { - if (!t.intersects(mEnclosureNode->_getWorldAABB())) - { - // AABB of zone does not intersect t, just return. - return; - } - } - - // check nodes at home in this zone - PCZSceneNodeList::iterator it = mHomeNodeList.begin(); - while ( it != mHomeNodeList.end() ) - { - PCZSceneNode * pczsn = *it; - if ( pczsn != exclude ) - { - // make sure node is not already in the list (might have been added in another - // zone it was visiting) - PCZSceneNodeList::iterator it2 = list.find(pczsn); - if (it2 == list.end()) - { - bool nsect = t.intersects( pczsn -> _getWorldAABB() ); - if ( nsect ) - { - list.insert( pczsn ); - } - } - } - ++it; - } - - if (includeVisitors) - { - // check visitor nodes - PCZSceneNodeList::iterator iter = mVisitorNodeList.begin(); - while ( iter != mVisitorNodeList.end() ) - { - PCZSceneNode * pczsn = *iter; - if ( pczsn != exclude ) - { - // make sure node is not already in the list (might have been added in another - // zone it was visiting) - PCZSceneNodeList::iterator it2 = list.find(pczsn); - if (it2 == list.end()) - { - bool nsect = t.intersects( pczsn -> _getWorldAABB() ); - if ( nsect ) - { - list.insert( pczsn ); - } - } - } - ++iter; - } - } - - // if asked to, recurse through portals - if (recurseThruPortals) - { - PortalList::iterator pit = mPortals.begin(); - while ( pit != mPortals.end() ) - { - Portal * portal = *pit; - // check portal versus boundign box - if (portal->intersects(t)) - { - // make sure portal hasn't already been recursed through - PortalList::iterator pit2 = std::find(visitedPortals.begin(), visitedPortals.end(), portal); - if (pit2 == visitedPortals.end()) - { - // save portal to the visitedPortals list - visitedPortals.push_front(portal); - // recurse into the connected zone - portal->getTargetZone()->_findNodes(t, - list, - visitedPortals, - includeVisitors, - recurseThruPortals, - exclude); - } - } - pit++; - } - } - - } - - void DefaultZone::_findNodes( const Ray &t, - PCZSceneNodeList &list, - PortalList &visitedPortals, - bool includeVisitors, - bool recurseThruPortals, - PCZSceneNode *exclude ) - { - // if this zone has an enclosure, check against the enclosure AABB first - if (mEnclosureNode) - { - std::pair nsect = t.intersects(mEnclosureNode->_getWorldAABB()); - if (!nsect.first) - { - // AABB of zone does not intersect t, just return. - return; - } - } - - // check nodes at home in this zone - PCZSceneNodeList::iterator it = mHomeNodeList.begin(); - while ( it != mHomeNodeList.end() ) - { - PCZSceneNode * pczsn = *it; - if ( pczsn != exclude ) - { - // make sure node is not already in the list (might have been added in another - // zone it was visiting) - PCZSceneNodeList::iterator it2 = list.find(pczsn); - if (it2 == list.end()) - { - std::pair nsect = t.intersects( pczsn -> _getWorldAABB() ); - if ( nsect.first ) - { - list.insert( pczsn ); - } - } - } - ++it; - } - - if (includeVisitors) - { - // check visitor nodes - PCZSceneNodeList::iterator iter = mVisitorNodeList.begin(); - while ( iter != mVisitorNodeList.end() ) - { - PCZSceneNode * pczsn = *iter; - if ( pczsn != exclude ) - { - // make sure node is not already in the list (might have been added in another - // zone it was visiting) - PCZSceneNodeList::iterator it2 = list.find(pczsn); - if (it2 == list.end()) - { - std::pair nsect = t.intersects( pczsn -> _getWorldAABB() ); - if ( nsect.first ) - { - list.insert( pczsn ); - } - } - } - ++iter; - } - } - - // if asked to, recurse through portals - if (recurseThruPortals) - { - PortalList::iterator pit = mPortals.begin(); - while ( pit != mPortals.end() ) - { - Portal * portal = *pit; - // check portal versus bounding box - if (portal->intersects(t)) - { - // make sure portal hasn't already been recursed through - PortalList::iterator pit2 = std::find(visitedPortals.begin(), visitedPortals.end(), portal); - if (pit2 == visitedPortals.end()) - { - // save portal to the visitedPortals list - visitedPortals.push_front(portal); - // recurse into the connected zone - portal->getTargetZone()->_findNodes(t, - list, - visitedPortals, - includeVisitors, - recurseThruPortals, - exclude); - } - } - pit++; - } - } - - } - - /* Set option for the zone */ - bool DefaultZone::setOption( const String &name, const void *value ) - { - return false; - } - - /** called when the scene manager creates a camera because - some zone managers (like TerrainZone) need the camera info. - */ - void DefaultZone::notifyCameraCreated( Camera* c ) - { - } - //------------------------------------------------------------------------- - void DefaultZone::notifyWorldGeometryRenderQueue(uint8 qid) - { - } - //------------------------------------------------------------------------- - void DefaultZone::notifyBeginRenderScene(void) - { - } - //------------------------------------------------------------------------- - void DefaultZone::setZoneGeometry(const String &filename, PCZSceneNode * parentNode) - { - String entityName, nodeName; - entityName = this->getName() + "_entity"; - nodeName = this->getName() + "_Node"; - Entity *ent = mPCZSM->createEntity(entityName , filename ); - // create a node for the entity - PCZSceneNode * node; - node = (PCZSceneNode*)(parentNode->createChildSceneNode(nodeName)); - // attach the entity to the node - node->attachObject(ent); - // set the node as the enclosure node - setEnclosureNode(node); - } - -} diff --git a/PlugIns/PCZSceneManager/src/OgrePCPlane.cpp b/PlugIns/PCZSceneManager/src/OgrePCPlane.cpp deleted file mode 100644 index 00d3f3985be..00000000000 --- a/PlugIns/PCZSceneManager/src/OgrePCPlane.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -OgrePCPlane.cpp - description ------------------------------------------------------------------------------ -begin : Tue Feb 27 2007 -author : Eric Cha -email : ericc@xenopi.com ------------------------------------------------------------------------------ -*/ - -#include "OgrePCPlane.h" - -namespace Ogre -{ - - PCPlane::PCPlane() : Plane() - { - mPortal = 0; - } - PCPlane::PCPlane(const Plane & plane) - : Plane(plane) - { - mPortal = 0; - } - PCPlane::PCPlane(const Vector3& rkNormal, const Vector3& rkPoint) - : Plane(rkNormal, rkPoint) - { - mPortal = 0; - } - PCPlane::PCPlane(const Vector3& rkPoint0, const Vector3& rkPoint1,const Vector3& rkPoint2) - : Plane(rkPoint0, rkPoint1, rkPoint2) - { - mPortal = 0; - } - void PCPlane::setFromOgrePlane(Plane & ogrePlane) - { - d = ogrePlane.d; - normal = ogrePlane.normal; - mPortal = 0; - } - - PCPlane::~PCPlane() - { - mPortal = 0; - } - -} diff --git a/PlugIns/PCZSceneManager/src/OgrePCZCamera.cpp b/PlugIns/PCZSceneManager/src/OgrePCZCamera.cpp deleted file mode 100644 index 76e66dd4c23..00000000000 --- a/PlugIns/PCZSceneManager/src/OgrePCZCamera.cpp +++ /dev/null @@ -1,316 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -PCZCamera.cpp - description ------------------------------------------------------------------------------ -begin : Wed Feb 21 2007 -author : Eric Cha -email : ericc@xenopi.com ------------------------------------------------------------------------------ -*/ - -#include "OgreAxisAlignedBox.h" -#include "OgrePCZCamera.h" -#include "OgrePCZFrustum.h" -#include "OgrePortal.h" - -namespace Ogre -{ - PCZCamera::PCZCamera( const String& name, SceneManager* sm ) : Camera( name, sm ) - { - mBox.setExtents(-0.1, -0.1, -0.1, 0.1, 0.1, 0.1); - mExtraCullingFrustum.setUseOriginPlane(true); - } - - PCZCamera::~PCZCamera() - { - } - - const AxisAlignedBox& PCZCamera::getBoundingBox(void) const - { - return mBox; - } - - // this version checks against extra culling planes - bool PCZCamera::isVisible( const AxisAlignedBox &bound, FrustumPlane *culledBy) const - { - // Null boxes always invisible - if ( bound.isNull() ) - return false; - - // Make any pending updates to the calculated frustum planes - updateFrustumPlanes(); - - // check extra culling planes - bool extraResults; - extraResults = mExtraCullingFrustum.isVisible(bound); - if (!extraResults) - { - return false; - } - - // check "regular" camera frustum - bool regcamresults = Camera::isVisible(bound, culledBy); - - if (!regcamresults) - { - // culled by regular culling planes - return regcamresults; - } - - - return true; - } - - /* A 'more detailed' check for visibility of an AAB. This function returns - none, partial, or full for visibility of the box. This is useful for - stuff like Octree leaf culling */ - PCZCamera::Visibility PCZCamera::getVisibility( const AxisAlignedBox &bound ) - { - - // Null boxes always invisible - if ( bound.isNull() ) - return NONE; - - // Get centre of the box - Vector3 centre = bound.getCenter(); - // Get the half-size of the box - Vector3 halfSize = bound.getHalfSize(); - - bool all_inside = true; - - for ( int plane = 0; plane < 6; ++plane ) - { - - // Skip far plane if infinite view frustum - if (plane == FRUSTUM_PLANE_FAR && mFarDist == 0) - continue; - - // This updates frustum planes and deals with cull frustum - Plane::Side side = getFrustumPlane(plane).getSide(centre, halfSize); - if(side == Plane::NEGATIVE_SIDE) return NONE; - // We can't return now as the box could be later on the negative side of a plane. - if(side == Plane::BOTH_SIDE) - all_inside = false; - } - - switch(mExtraCullingFrustum.getVisibility(bound)) - { - case PCZFrustum::NONE: - return NONE; - case PCZFrustum::PARTIAL: - return PARTIAL; - case PCZFrustum::FULL: - break; - } - - if ( all_inside ) - return FULL; - else - return PARTIAL; - - } - - /* isVisible() function for portals */ - // NOTE: Everything needs to be updated spatially before this function is - // called including portal corners, frustum planes, etc. - bool PCZCamera::isVisible(PortalBase* portal, FrustumPlane* culledBy) const - { - // if portal isn't enabled, it's not visible - if (!portal->getEnabled()) return false; - - // check the extra frustum first - if (!mExtraCullingFrustum.isVisible(portal)) - { - return false; - } - - // if portal is of type AABB or Sphere, then use simple bound check against planes - if (portal->getType() == PortalBase::PORTAL_TYPE_AABB) - { - AxisAlignedBox aabb; - aabb.setExtents(portal->getDerivedCorner(0), portal->getDerivedCorner(1)); - return Camera::isVisible(aabb, culledBy); - } - else if (portal->getType() == PortalBase::PORTAL_TYPE_SPHERE) - { - return Camera::isVisible(portal->getDerivedSphere(), culledBy); - } - - // only do this check if it's a portal. (anti portal doesn't care about facing) - if (portal->getTypeFlags() == PortalFactory::FACTORY_TYPE_FLAG) - { - // check if the portal norm is facing the camera - Vector3 cameraToPortal = portal->getDerivedCP() - getDerivedPosition(); - Vector3 portalDirection = portal->getDerivedDirection(); - Real dotProduct = cameraToPortal.dotProduct(portalDirection); - if ( dotProduct > 0 ) - { - // portal is faced away from camera - return false; - } - } - - // check against regular frustum planes - bool visible_flag; - if (getCullingFrustum()) - { - // For each frustum plane, see if all points are on the negative side - // If so, object is not visible - // NOTE: We skip the NEAR plane (plane #0) because Portals need to - // be visible no matter how close you get to them. - - for (int plane = 1; plane < 6; ++plane) - { - // set the visible flag to false - visible_flag = false; - // Skip far plane if infinite view frustum - if (plane == FRUSTUM_PLANE_FAR && mFarDist == 0) - continue; - - // we have to check each corner of the portal - for (int corner = 0; corner < 4; corner++) - { - Plane::Side side = getCullingFrustum()->getFrustumPlane(plane).getSide(portal->getDerivedCorner(corner)); - if (side != Plane::NEGATIVE_SIDE) - { - visible_flag = true; - break; - } - } - // if the visible_flag is still false, then this plane - // culled all the portal points - if (visible_flag == false) - { - // ALL corners on negative side therefore out of view - if (culledBy) - *culledBy = (FrustumPlane)plane; - return false; - } - } - } - else - { - // Make any pending updates to the calculated frustum planes - Frustum::updateFrustumPlanes(); - - // For each frustum plane, see if all points are on the negative side - // If so, object is not visible - // NOTE: We skip the NEAR plane (plane #0) because Portals need to - // be visible no matter how close you get to them. - // BUGBUG: This can cause a false positive situation when a portal is - // behind the camera but close. This could be fixed by having another - // culling plane at the camera location with normal same as camera direction. - for (int plane = 1; plane < 6; ++plane) - { - // set the visible flag to false - visible_flag = false; - // Skip far plane if infinite view frustum - if (plane == FRUSTUM_PLANE_FAR && mFarDist == 0) - continue; - - // we have to check each corner of the portal - for (int corner = 0; corner < 4; corner++) - { - Plane::Side side = mFrustumPlanes[plane].getSide(portal->getDerivedCorner(corner)); - if (side != Plane::NEGATIVE_SIDE) - { - visible_flag = true; - break; - } - } - // if the visible_flag is still false, then this plane - // culled all the portal points - if (visible_flag == false) - { - // ALL corners on negative side therefore out of view - if (culledBy) - *culledBy = (FrustumPlane)plane; - return false; - } - } - } - // no plane culled all the portal points and the norm - // was facing the camera, so this portal is visible - return true; - } - - /// Sets the type of projection to use (orthographic or perspective). - void PCZCamera::setProjectionType(ProjectionType pt) - { - mExtraCullingFrustum.setProjectionType(pt); - Camera::setProjectionType(pt); - } - - /* Update function (currently used for making sure the origin stuff for the - extra culling frustum is up to date */ - void PCZCamera::update(void) - { - // make sure the extra culling frustum origin stuff is up to date - if (mProjType == PT_PERSPECTIVE) - //if (!mCustomViewMatrix) - { - mExtraCullingFrustum.setUseOriginPlane(true); - mExtraCullingFrustum.setOrigin(getDerivedPosition()); - mExtraCullingFrustum.setOriginPlane(getDerivedDirection(), getDerivedPosition()); - } - else - { - // In ortho mode, we don't want to cull things behind camera. - // This helps for back casting which is useful for texture shadow projection on directional light. - mExtraCullingFrustum.setUseOriginPlane(false); - } - } - - // calculate extra culling planes from portal and camera - // origin and add to list of extra culling planes - // NOTE: returns 0 if portal was completely culled by existing planes - // returns > 0 if culling planes are added (# is planes added) - int PCZCamera::addPortalCullingPlanes(PortalBase* portal) - { - // add the extra culling planes from the portal - return mExtraCullingFrustum.addPortalCullingPlanes(portal); - } - - // remove extra culling planes created from the given portal - // NOTE: This should only be used during visibility traversal (backing out of a recursion) - void PCZCamera::removePortalCullingPlanes(PortalBase* portal) - { - mExtraCullingFrustum.removePortalCullingPlanes(portal); - } - - // remove all extra culling planes - void PCZCamera::removeAllExtraCullingPlanes(void) - { - mExtraCullingFrustum.removeAllCullingPlanes(); - } - -} - - - - - diff --git a/PlugIns/PCZSceneManager/src/OgrePCZFrustum.cpp b/PlugIns/PCZSceneManager/src/OgrePCZFrustum.cpp deleted file mode 100644 index 560bdb164bc..00000000000 --- a/PlugIns/PCZSceneManager/src/OgrePCZFrustum.cpp +++ /dev/null @@ -1,667 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -OgrePCZFrustum.cpp - PCZ Supplemental culling Frustum - -This isn't really a traditional "frustum", but more a collection of -extra culling planes used by the PCZ Scene Manager for supplementing -the camera culling and light zone culling by creating extra culling -planes from visible portals. Since portals are 4 sided, the extra -culling planes tend to form frustums (pyramids) but nothing in the -code really assumes that the culling planes are frustums. They are -just treated as planes. - -The "originPlane" is a culling plane which passes through the origin -point specified. It is used to cull portals which are close to, but -behind the camera view. (the nature of the culling routine doesn't -give correct results if you just use the "near" plane of the standard -camera frustum (unless that near plane distance is 0.0, but that is -highly not recommended for other reasons having to do with having a -legal view frustum). - ------------------------------------------------------------------------------ -begin : Tue May 29 2007 -author : Eric Cha -email : ericc@xenopi.com ------------------------------------------------------------------------------ -*/ - -#include "OgrePCZFrustum.h" -#include "OgrePCPlane.h" -#include "OgreAntiPortal.h" -#include "OgrePortal.h" - -namespace Ogre -{ - - PCZFrustum::PCZFrustum() : - mUseOriginPlane(false), mProjType(PT_PERSPECTIVE) - { } - - PCZFrustum::~PCZFrustum() - { - removeAllCullingPlanes(); - // clear out the culling plane reservoir - PCPlaneList::iterator pit = mCullingPlaneReservoir.begin(); - while ( pit != mCullingPlaneReservoir.end() ) - { - PCPlane * plane = *pit; - // go to next entry - pit++; - //delete the entry in the list - OGRE_DELETE_T(plane, PCPlane, MEMCATEGORY_SCENE_CONTROL); - } - mCullingPlaneReservoir.clear(); - } - - bool PCZFrustum::isVisible( const AxisAlignedBox & bound) const - { - // Null boxes are always invisible - if (bound.isNull()) return false; - - // Infinite boxes are always visible - if (bound.isInfinite()) return true; - - // Get centre of the box - Vector3 centre = bound.getCenter(); - // Get the half-size of the box - Vector3 halfSize = bound.getHalfSize(); - - // Check originplane if told to - if (mUseOriginPlane) - { - Plane::Side side = mOriginPlane.getSide(centre, halfSize); - if (side == Plane::NEGATIVE_SIDE) - { - return false; - } - } - - // For each extra active culling plane, see if the entire aabb is on the negative side - // If so, object is not visible - PCPlaneList::const_iterator pit = mActiveCullingPlanes.begin(); - while ( pit != mActiveCullingPlanes.end() ) - { - PCPlane * plane = *pit; - Plane::Side xside = plane->getSide(centre, halfSize); - if (xside == Plane::NEGATIVE_SIDE) - { - return false; - } - pit++; - } - return true; - } - - bool PCZFrustum::isVisible( const Sphere & bound) const - { - // Check originplane if told to - if (mUseOriginPlane) - { - Plane::Side side = mOriginPlane.getSide(bound.getCenter()); - if (side == Plane::NEGATIVE_SIDE) - { - Real dist = mOriginPlane.getDistance(bound.getCenter()); - if (dist > bound.getRadius()) - { - return false; - } - } - } - - // For each extra active culling plane, see if the entire sphere is on the negative side - // If so, object is not visible - PCPlaneList::const_iterator pit = mActiveCullingPlanes.begin(); - while ( pit != mActiveCullingPlanes.end() ) - { - PCPlane * plane = *pit; - Plane::Side xside = plane->getSide(bound.getCenter()); - if (xside == Plane::NEGATIVE_SIDE) - { - Real dist = plane->getDistance(bound.getCenter()); - if (dist > bound.getRadius()) - { - return false; - } - } - pit++; - } - return true; - } - - /* isVisible() function for portals */ - // NOTE: Everything needs to be updated spatially before this function is - // called including portal corners, frustum planes, etc. - bool PCZFrustum::isVisible(const PortalBase* portal) const - { - // if portal isn't enabled, it's not visible - if (!portal->getEnabled()) return false; - - // if the frustum has no planes, just return true - if (mActiveCullingPlanes.empty()) - { - return true; - } - // check if this portal is already in the list of active culling planes (avoid - // infinite recursion case) - PCPlaneList::const_iterator pit = mActiveCullingPlanes.begin(); - while ( pit != mActiveCullingPlanes.end() ) - { - PCPlane * plane = *pit; - if (plane->getPortal() == portal) - { - return false; - } - pit++; - } - // if portal is of type AABB or Sphere, then use simple bound check against planes - if (portal->getType() == PortalBase::PORTAL_TYPE_AABB) - { - AxisAlignedBox aabb; - aabb.setExtents(portal->getDerivedCorner(0), portal->getDerivedCorner(1)); - return isVisible(aabb); - } - else if (portal->getType() == PortalBase::PORTAL_TYPE_SPHERE) - { - return isVisible(portal->getDerivedSphere()); - } - - // only do this check if it's a portal. (anti portal doesn't care about facing) - if (portal->getTypeFlags() == PortalFactory::FACTORY_TYPE_FLAG) - { - // check if the portal norm is facing the frustum - Vector3 frustumToPortal = portal->getDerivedCP() - mOrigin; - Vector3 portalDirection = portal->getDerivedDirection(); - Real dotProduct = frustumToPortal.dotProduct(portalDirection); - if ( dotProduct > 0 ) - { - // portal is faced away from Frustum - return false; - } - } - - // check against frustum culling planes - bool visible_flag; - - // Check originPlane if told to - if (mUseOriginPlane) - { - // set the visible flag to false - visible_flag = false; - // we have to check each corner of the portal - for (int corner = 0; corner < 4; corner++) - { - Plane::Side side = mOriginPlane.getSide(portal->getDerivedCorner(corner)); - if (side != Plane::NEGATIVE_SIDE) - { - visible_flag = true; - break; - } - } - // if the visible_flag is still false, then the origin plane - // culled all the portal points - if (visible_flag == false) - { - // ALL corners on negative side therefore out of view - return false; - } - } - - // For each active culling plane, see if all portal points are on the negative - // side. If so, the portal is not visible - pit = mActiveCullingPlanes.begin(); - while ( pit != mActiveCullingPlanes.end() ) - { - PCPlane * plane = *pit; - // set the visible flag to false - visible_flag = false; - // we have to check each corner of the portal - for (int corner = 0; corner < 4; corner++) - { - Plane::Side side =plane->getSide(portal->getDerivedCorner(corner)); - if (side != Plane::NEGATIVE_SIDE) - { - visible_flag = true; - break; - } - } - // if the visible_flag is still false, then this plane - // culled all the portal points - if (visible_flag == false) - { - // ALL corners on negative side therefore out of view - return false; - } - pit++; - } - // no plane culled all the portal points and the norm - // was facing the frustum, so this portal is visible - return true; - - } - - /* special function that returns true only when aabb fully fits inside the frustum. */ - bool PCZFrustum::isFullyVisible(const AxisAlignedBox& bound) const - { - // Null boxes are always invisible - if (bound.isNull()) return false; - - // Infinite boxes are never fully visible - if (bound.isInfinite()) return false; - - // Get centre of the box - Vector3 centre = bound.getCenter(); - // Get the half-size of the box - Vector3 halfSize = bound.getHalfSize(); - - // Check originplane if told to - if (mUseOriginPlane) - { - Plane::Side side = mOriginPlane.getSide(centre, halfSize); - if (side != Plane::POSITIVE_SIDE) return false; - } - - // For each extra active culling plane, - // see if the aabb is not on the positive side - // If so, object is not fully visible - PCPlaneList::const_iterator pit = mActiveCullingPlanes.begin(); - while ( pit != mActiveCullingPlanes.end() ) - { - PCPlane * plane = *pit; - Plane::Side xside = plane->getSide(centre, halfSize); - if (xside != Plane::POSITIVE_SIDE) - { - return false; - } - pit++; - } - return true; - } - - /* special function that returns true only when sphere fully fits inside the frustum. */ - bool PCZFrustum::isFullyVisible(const Sphere& bound) const - { - // Check originplane if told to - if (mUseOriginPlane) - { - if (mOriginPlane.getDistance(bound.getCenter()) <= bound.getRadius() || - mOriginPlane.getSide(bound.getCenter()) != Plane::POSITIVE_SIDE) - { - return false; - } - } - - // For each extra active culling plane, - // see if the sphere is not on the positive side - // If so, object is not fully visible - PCPlaneList::const_iterator pit = mActiveCullingPlanes.begin(); - while ( pit != mActiveCullingPlanes.end() ) - { - PCPlane* plane = *pit; - - if (plane->getDistance(bound.getCenter()) <= bound.getRadius() || - plane->getSide(bound.getCenter()) != Plane::POSITIVE_SIDE) - { - return false; - } - - pit++; - } - return true; - } - - /* special function that returns true only when portal fully fits inside the frustum. */ - bool PCZFrustum::isFullyVisible(const PortalBase* portal) const - { - // if portal isn't enabled, it's not visible - if (!portal->getEnabled()) return false; - - // if the frustum has no planes, just return true - if (mActiveCullingPlanes.empty()) - { - return true; - } - // check if this portal is already in the list of active culling planes (avoid - // infinite recursion case) - PCPlaneList::const_iterator pit = mActiveCullingPlanes.begin(); - while ( pit != mActiveCullingPlanes.end() ) - { - PCPlane * plane = *pit; - if (plane->getPortal() == portal) - { - return false; - } - pit++; - } - // if portal is of type AABB or Sphere, then use simple bound check against planes - if (portal->getType() == PortalBase::PORTAL_TYPE_AABB) - { - AxisAlignedBox aabb; - aabb.setExtents(portal->getDerivedCorner(0), portal->getDerivedCorner(1)); - return isFullyVisible(aabb); - } - else if (portal->getType() == PortalBase::PORTAL_TYPE_SPHERE) - { - return isFullyVisible(portal->getDerivedSphere()); - } - - // only do this check if it's a portal. (anti portal doesn't care about facing) - if (portal->getTypeFlags() == PortalFactory::FACTORY_TYPE_FLAG) - { - // check if the portal norm is facing the frustum - Vector3 frustumToPortal = portal->getDerivedCP() - mOrigin; - Vector3 portalDirection = portal->getDerivedDirection(); - Real dotProduct = frustumToPortal.dotProduct(portalDirection); - if ( dotProduct > 0 ) - { - // portal is faced away from Frustum - return false; - } - } - - // Check originPlane if told to - if (mUseOriginPlane) - { - // we have to check each corner of the portal - for (int corner = 0; corner < 4; corner++) - { - Plane::Side side = mOriginPlane.getSide(portal->getDerivedCorner(corner)); - if (side == Plane::NEGATIVE_SIDE) return false; - } - } - - // For each active culling plane, see if any portal points are on the negative - // side. If so, the portal is not fully visible - pit = mActiveCullingPlanes.begin(); - while ( pit != mActiveCullingPlanes.end() ) - { - PCPlane * plane = *pit; - // we have to check each corner of the portal - for (int corner = 0; corner < 4; corner++) - { - Plane::Side side =plane->getSide(portal->getDerivedCorner(corner)); - if (side == Plane::NEGATIVE_SIDE) return false; - } - pit++; - } - // no plane culled all the portal points and the norm - // was facing the frustum, so this portal is fully visible - return true; - } - - /* A 'more detailed' check for visibility of an AAB. This function returns - none, partial, or full for visibility of the box. This is useful for - stuff like Octree leaf culling */ - PCZFrustum::Visibility PCZFrustum::getVisibility( const AxisAlignedBox &bound ) - { - - // Null boxes always invisible - if ( bound.isNull() ) - return NONE; - - // Get centre of the box - Vector3 centre = bound.getCenter(); - // Get the half-size of the box - Vector3 halfSize = bound.getHalfSize(); - - bool all_inside = true; - - // Check originplane if told to - if (mUseOriginPlane) - { - Plane::Side side = mOriginPlane.getSide(centre, halfSize); - if (side == Plane::NEGATIVE_SIDE) - { - return NONE; - } - // We can't return now as the box could be later on the negative side of another plane. - if(side == Plane::BOTH_SIDE) - { - all_inside = false; - } - } - - // For each active culling plane, see if the entire aabb is on the negative side - // If so, object is not visible - PCPlaneList::iterator pit = mActiveCullingPlanes.begin(); - while ( pit != mActiveCullingPlanes.end() ) - { - PCPlane * plane = *pit; - Plane::Side xside = plane->getSide(centre, halfSize); - if(xside == Plane::NEGATIVE_SIDE) - { - return NONE; - } - // We can't return now as the box could be later on the negative side of a plane. - if(xside == Plane::BOTH_SIDE) - { - all_inside = false; - break; - } - pit++; - } - - if ( all_inside ) - return FULL; - else - return PARTIAL; - - } - - // calculate culling planes from portal and frustum - // origin and add to list of culling planes - // NOTE: returns 0 if portal was completely culled by existing planes - // returns > 0 if culling planes are added (# is planes added) - int PCZFrustum::addPortalCullingPlanes(PortalBase* portal) - { - int addedcullingplanes = 0; - - // If portal is of type aabb or sphere, add a plane which is same as frustum - // origin plane (ie. redundant). We do this because we need the plane as a flag - // to prevent infinite recursion - if (portal->getType() == PortalBase::PORTAL_TYPE_AABB || - portal->getType() == PortalBase::PORTAL_TYPE_SPHERE) - { - PCPlane * newPlane = getUnusedCullingPlane(); - newPlane->setFromOgrePlane(mOriginPlane); - newPlane->setPortal(portal); - mActiveCullingPlanes.push_front(newPlane); - addedcullingplanes++; - return addedcullingplanes; - } - - // only do this check if it's an anti portal since it's double facing. - bool flipPlane = false; - if (portal->getTypeFlags() == AntiPortalFactory::FACTORY_TYPE_FLAG) - { - // check if the portal norm is facing the frustum - Vector3 frustumToPortal = portal->getDerivedCP() - mOrigin; - Vector3 portalDirection = portal->getDerivedDirection(); - Real dotProduct = frustumToPortal.dotProduct(portalDirection); - - // it's facing away from the frustum. Flip the planes. - if (dotProduct > 0) flipPlane = true; - } - - // For portal Quads: Up to 4 planes can be added by the sides of a portal quad. - // Each plane is created from 2 corners (world space) of the portal and the - // frustum origin (world space). - int i,j; - Plane::Side pt0_side, pt1_side; - bool visible; - PCPlaneList::iterator pit; - for (i=0;i<4;i++) - { - // first check if both corners are outside of one of the existing planes - j = i+1; - if (j > 3) - { - j = 0; - } - visible = true; - pit = mActiveCullingPlanes.begin(); - while ( pit != mActiveCullingPlanes.end() ) - { - PCPlane * plane = *pit; - pt0_side = plane->getSide(portal->getDerivedCorner(i)); - pt1_side = plane->getSide(portal->getDerivedCorner(j)); - if (pt0_side == Plane::NEGATIVE_SIDE && - pt1_side == Plane::NEGATIVE_SIDE) - { - // the portal edge was actually completely culled by one of culling planes - visible = false; - break; - } - pit++; - } - if (visible) - { - // add the plane created from the two portal corner points and the frustum location - // to the culling plane - PCPlane * newPlane = getUnusedCullingPlane(); - if (mProjType == PT_ORTHOGRAPHIC) // use camera direction if projection is orthographic. - { - if (flipPlane) - { - newPlane->redefine(portal->getDerivedCorner(j) + mOriginPlane.normal, - portal->getDerivedCorner(i), portal->getDerivedCorner(j)); - } - else - { - newPlane->redefine(portal->getDerivedCorner(j) + mOriginPlane.normal, - portal->getDerivedCorner(j), portal->getDerivedCorner(i)); - } - } - else - { - if (flipPlane) - { - newPlane->redefine(mOrigin, - portal->getDerivedCorner(i), - portal->getDerivedCorner(j)); - } - else - { - newPlane->redefine(mOrigin, - portal->getDerivedCorner(j), - portal->getDerivedCorner(i)); - } - } - newPlane->setPortal(portal); - mActiveCullingPlanes.push_front(newPlane); - addedcullingplanes++; - } - } - // if we added ANY planes from the quad portal, we should add the plane of the - // portal itself as an additional culling plane. - if (addedcullingplanes > 0) - { - PCPlane * newPlane = getUnusedCullingPlane(); - - if (flipPlane) - { - newPlane->redefine( - portal->getDerivedCorner(2), - portal->getDerivedCorner(0), - portal->getDerivedCorner(1)); - } - else - { - newPlane->redefine( - portal->getDerivedCorner(2), - portal->getDerivedCorner(1), - portal->getDerivedCorner(0)); - } - - newPlane->setPortal(portal); - mActiveCullingPlanes.push_back(newPlane); - addedcullingplanes++; - } - return addedcullingplanes; - } - - // remove culling planes created from the given portal - void PCZFrustum::removePortalCullingPlanes(PortalBase* portal) - { - PCPlaneList::iterator pit = mActiveCullingPlanes.begin(); - while ( pit != mActiveCullingPlanes.end() ) - { - PCPlane * plane = *pit; - if (plane->getPortal() == portal) - { - // put the plane back in the reservoir - mCullingPlaneReservoir.push_front(plane); - // erase the entry from the active culling plane list - pit = mActiveCullingPlanes.erase(pit); - } - else - { - pit++; - } - } - - } - - // remove all active extra culling planes - // NOTE: Does not change the use of the originPlane! - void PCZFrustum::removeAllCullingPlanes(void) - { - PCPlaneList::iterator pit = mActiveCullingPlanes.begin(); - while ( pit != mActiveCullingPlanes.end() ) - { - PCPlane * plane = *pit; - // put the plane back in the reservoir - mCullingPlaneReservoir.push_front(plane); - // go to next entry - pit++; - } - mActiveCullingPlanes.clear(); - } - - // set the origin plane - void PCZFrustum::setOriginPlane(const Vector3 &rkNormal, const Vector3 &rkPoint) - { - mOriginPlane.redefine(rkNormal, rkPoint); - } - - // get an unused PCPlane from the CullingPlane Reservoir - // note that this removes the PCPlane from the reservoir! - PCPlane * PCZFrustum::getUnusedCullingPlane(void) - { - PCPlane * plane = 0; - if (mCullingPlaneReservoir.size() > 0) - { - PCPlaneList::iterator pit = mCullingPlaneReservoir.begin(); - plane = *pit; - mCullingPlaneReservoir.erase(pit); - return plane; - } - // no available planes! create one - plane = OGRE_NEW_T(PCPlane, MEMCATEGORY_SCENE_CONTROL); - return plane; - } - -} diff --git a/PlugIns/PCZSceneManager/src/OgrePCZLight.cpp b/PlugIns/PCZSceneManager/src/OgrePCZLight.cpp deleted file mode 100644 index 64b5d3be0a5..00000000000 --- a/PlugIns/PCZSceneManager/src/OgrePCZLight.cpp +++ /dev/null @@ -1,191 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -PCZLight.cpp - description ------------------------------------------------------------------------------ -begin : Wed May 23 2007 -author : Eric Cha -email : ericc@xenopi.com -Code Style Update : ------------------------------------------------------------------------------ -*/ - -#include "OgrePCZLight.h" -#include "OgrePCZone.h" // need for testing affected zone -#include "OgrePCZSceneNode.h" -#include "OgrePCZFrustum.h" - -namespace Ogre -{ - //----------------------------------------------------------------------- - PCZLight::PCZLight() : Light() - { - mNeedsUpdate = true; // need to update the first time, regardless of attachment or movement - } - //----------------------------------------------------------------------- - PCZLight::PCZLight(const String& name) : Light(name) - { - mNeedsUpdate = true; // need to update the first time, regardless of attachment or movement - } - //----------------------------------------------------------------------- - PCZLight::~PCZLight() - { - affectedZonesList.clear(); - } - //----------------------------------------------------------------------- - const String& PCZLight::getMovableType(void) const - { - return PCZLightFactory::FACTORY_TYPE_NAME; - } - //----------------------------------------------------------------------- - /** Clear the affectedZonesList - */ - void PCZLight::clearAffectedZones(void) - { - affectedZonesList.clear(); - } - //----------------------------------------------------------------------- - /** Add a zone to the zones affected list - */ - void PCZLight::addZoneToAffectedZonesList(PCZone * zone) - { - affectedZonesList.push_back(zone); - } - //----------------------------------------------------------------------- - /** check if a zone is in the list of zones affected by the light - */ - bool PCZLight::affectsZone(PCZone * zone) - { - ZoneList::iterator it = std::find(affectedZonesList.begin(), affectedZonesList.end(), zone); - if (it == affectedZonesList.end()) - { - // not in the affectedZonesList - return false; - } - return true; - } - //----------------------------------------------------------------------- - void PCZLight::updateZones(PCZone * defaultZone, unsigned long frameCount) - { - //update the zones this light affects - PCZone * homeZone; - affectedZonesList.clear(); - mAffectsVisibleZone = false; - PCZSceneNode * sn = (PCZSceneNode*)(this->getParentSceneNode()); - if (sn) - { - // start with the zone the light is in - homeZone = sn->getHomeZone(); - if (homeZone) - { - affectedZonesList.push_back(homeZone); - if (homeZone->getLastVisibleFrame() == frameCount) - { - mAffectsVisibleZone = true; - } - } - else - { - // error - scene node has no homezone! - // just say it affects the default zone and leave it at that. - affectedZonesList.push_back(defaultZone); - if (defaultZone->getLastVisibleFrame() == frameCount) - { - mAffectsVisibleZone = true; - } - return; - } - } - else - { - // ERROR! not connected to a scene node, - // just say it affects the default zone and leave it at that. - affectedZonesList.push_back(defaultZone); - if (defaultZone->getLastVisibleFrame() == frameCount) - { - mAffectsVisibleZone = true; - } - return; - } - - // now check visibility of each portal in the home zone. If visible to - // the light then add the target zone of the portal to the list of - // affected zones and recurse into the target zone - static PCZFrustum portalFrustum; - Vector3 v = getDerivedPosition(); - portalFrustum.setOrigin(v); - homeZone->_checkLightAgainstPortals(this, frameCount, &portalFrustum, 0); - } - //----------------------------------------------------------------------- - void PCZLight::removeZoneFromAffectedZonesList(PCZone * zone) - { - ZoneList::iterator it = std::find(affectedZonesList.begin(), affectedZonesList.end(), zone); - - if (it != affectedZonesList.end()) - { - affectedZonesList.erase( it ); // zone is in list, erase it. - } - } - //----------------------------------------------------------------------- - void PCZLight::_notifyMoved(void) - { - Light::_notifyMoved(); // inform ogre Light of movement - - mNeedsUpdate = true; // set need update flag - } - //----------------------------------------------------------------------- - bool PCZLight::getNeedsUpdate(void) - { - if(mNeedsUpdate) // if this light has moved, return true immediately - return true; - - // if any zones affected by this light have updated portals, then this light needs updating too - for (auto & iter : affectedZonesList) - { - if(iter->getPortalsUpdated()) return true; // return immediately to prevent further iterating - } - - return false; // light hasn't moved, and no zones have updated portals. no light update. - } - - - //----------------------------------------------------------------------- - String PCZLightFactory::FACTORY_TYPE_NAME = "PCZLight"; - //----------------------------------------------------------------------- - const String& PCZLightFactory::getType(void) const - { - return FACTORY_TYPE_NAME; - } - //----------------------------------------------------------------------- - MovableObject* PCZLightFactory::createInstanceImpl( const String& name, - const NameValuePairList* params) - { - - return OGRE_NEW PCZLight(name); - - } - -} // Namespace diff --git a/PlugIns/PCZSceneManager/src/OgrePCZPlugin.cpp b/PlugIns/PCZSceneManager/src/OgrePCZPlugin.cpp deleted file mode 100644 index ce4cd7cb394..00000000000 --- a/PlugIns/PCZSceneManager/src/OgrePCZPlugin.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -OgrePCZPlugin.cpp - Portal Connected Zone Scene Manager Plugin class ------------------------------------------------------------------------------ -begin : Mon Feb 19 2007 -author : Eric Cha -email : ericc@xenopi.com -Code Style Update : ------------------------------------------------------------------------------ -*/ - -#include "OgrePCZPlugin.h" -#include "OgrePCZSceneManager.h" -#include "OgrePortal.h" -#include "OgreAntiPortal.h" -#include "OgrePCZLight.h" -#include "OgrePCZoneFactory.h" -#include "OgreRoot.h" - -namespace Ogre -{ - const String sPluginName = "Portal Connected Zone Scene Manager"; - //--------------------------------------------------------------------- - PCZPlugin::PCZPlugin() - :mPCZSMFactory(0) - { - } - //--------------------------------------------------------------------- - const String& PCZPlugin::getName() const - { - return sPluginName; - } - //--------------------------------------------------------------------- - void PCZPlugin::install() - { - // Create objects - mPCZSMFactory = OGRE_NEW PCZSceneManagerFactory(); - mPCZoneFactoryManager = OGRE_NEW PCZoneFactoryManager(); - mPCZLightFactory = OGRE_NEW PCZLightFactory(); - mPortalFactory = OGRE_NEW PortalFactory(); - mAntiPortalFactory = OGRE_NEW AntiPortalFactory(); - } - //--------------------------------------------------------------------- - void PCZPlugin::initialise() - { - // Register - Root::getSingleton().addSceneManagerFactory(mPCZSMFactory); - Root::getSingleton().addMovableObjectFactory(mPCZLightFactory); - Root::getSingleton().addMovableObjectFactory(mPortalFactory); - Root::getSingleton().addMovableObjectFactory(mAntiPortalFactory); - - // set type flags to static member variable for fast access. - PortalFactory::FACTORY_TYPE_FLAG = mPortalFactory->getTypeFlags(); - AntiPortalFactory::FACTORY_TYPE_FLAG = mAntiPortalFactory->getTypeFlags(); - } - //--------------------------------------------------------------------- - void PCZPlugin::shutdown() - { - // Unregister - Root::getSingleton().removeSceneManagerFactory(mPCZSMFactory); - Root::getSingleton().removeMovableObjectFactory(mPCZLightFactory); - Root::getSingleton().removeMovableObjectFactory(mPortalFactory); - Root::getSingleton().removeMovableObjectFactory(mAntiPortalFactory); - } - //--------------------------------------------------------------------- - void PCZPlugin::uninstall() - { - // destroy - OGRE_DELETE mPCZSMFactory; - mPCZSMFactory = 0; - OGRE_DELETE mPCZoneFactoryManager; - mPCZoneFactoryManager = 0; - OGRE_DELETE mPCZLightFactory; - mPCZLightFactory = 0; - OGRE_DELETE mPortalFactory; - mPortalFactory = 0; - OGRE_DELETE mAntiPortalFactory; - mAntiPortalFactory = 0; - } - - -} diff --git a/PlugIns/PCZSceneManager/src/OgrePCZSceneManager.cpp b/PlugIns/PCZSceneManager/src/OgrePCZSceneManager.cpp deleted file mode 100644 index e42914a06a6..00000000000 --- a/PlugIns/PCZSceneManager/src/OgrePCZSceneManager.cpp +++ /dev/null @@ -1,1349 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -PCZSceneManager.cpp - description ------------------------------------------------------------------------------ -begin : Mon Feb 19 2007 -author : Eric Cha -email : ericc@xenopi.com ------------------------------------------------------------------------------ -*/ - -#include "OgrePCZSceneManager.h" -#include "OgrePCZSceneQuery.h" -#include "OgrePCZSceneNode.h" -#include "OgrePCZone.h" -#include "OgrePCZCamera.h" -#include "OgrePCZLight.h" -#include "OgrePCZoneFactory.h" -#include "OgreAntiPortal.h" -#include "OgrePortal.h" -#include "OgreLogManager.h" -#include "OgreRoot.h" - -namespace Ogre -{ - PCZSceneManager::PCZSceneManager(const String& name) : - SceneManager(name), - mDefaultZoneTypeName("ZoneType_Default"), - mDefaultZoneFileName("none"), - mLastActiveCamera(0), - mDefaultZone(0), - mShowPortals(false), - mZoneFactoryManager(0), - mActiveCameraZone(0) - { - addShadowTextureListener(this); - } - - PCZSceneManager::~PCZSceneManager() - { - // we don't delete the root scene node here because the - // base scene manager class does that. - - // delete ALL portals - Portal * p; - PortalList::iterator i = mPortals.begin(); - for (i = mPortals.begin(); i != mPortals.end(); i++) - { - p = *i; - OGRE_DELETE p; - } - mPortals.clear(); - - // delete all the zones - for (ZoneMap::iterator j = mZones.begin(); - j != mZones.end(); ++j) - { - OGRE_DELETE j->second; - } - mZones.clear(); - mDefaultZone = 0; - } - - const String& PCZSceneManager::getTypeName(void) const - { - return PCZSceneManagerFactory::FACTORY_TYPE_NAME; - } - - void PCZSceneManager::init( const String &defaultZoneTypeName, - const String &filename) - { - - // delete ALL portals - Portal * p; - PortalList::iterator i = mPortals.begin(); - for (i = mPortals.begin(); i != mPortals.end(); i++) - { - p = *i; - OGRE_DELETE p; - } - mPortals.clear(); - - // delete all the zones - for (ZoneMap::iterator j = mZones.begin(); - j != mZones.end(); ++j) - { - OGRE_DELETE j->second; - } - mZones.clear(); - - mFrameCount = 0; - - mDefaultZoneTypeName = defaultZoneTypeName; - mDefaultZoneFileName = filename; - - // create a new default zone - mZoneFactoryManager = PCZoneFactoryManager::getSingletonPtr(); - mDefaultZone = createZoneFromFile(mDefaultZoneTypeName, "Default_Zone", (PCZSceneNode*)getRootSceneNode(), mDefaultZoneFileName); - } - - // Create a portal instance - Portal* PCZSceneManager::createPortal(const String& name, PortalBase::PORTAL_TYPE type) - { - Portal* newPortal = OGRE_NEW Portal(name, type); - newPortal->_notifyCreator(Root::getSingleton().getMovableObjectFactory("Portal")); - newPortal->_notifyManager(this); - mPortals.push_front(newPortal); - return newPortal; - } - - // delete a portal instance by pointer - void PCZSceneManager::destroyPortal(Portal * p) - { - // remove the portal from it's target portal - Portal * targetPortal = p->getTargetPortal(); - if (targetPortal) - { - targetPortal->setTargetPortal(0); // the targetPortal will still have targetZone value, but targetPortal will be invalid - } - // remove the Portal from it's home zone - PCZone * homeZone = p->getCurrentHomeZone(); - if (homeZone) - { - // inform zone of portal change. Do here since PCZone is abstract - homeZone->setPortalsUpdated(true); - homeZone->_removePortal(p); - } - - // remove the portal from the master portal list - PortalList::iterator it = std::find( mPortals.begin(), mPortals.end(), p ); - if (it != mPortals.end()) - { - mPortals.erase(it); - } - // delete the portal instance - OGRE_DELETE p; - } - - // delete a portal instance by pointer - void PCZSceneManager::destroyPortal(const String & portalName) - { - // find the portal from the master portal list - Portal * p; - Portal * thePortal = 0; - PortalList::iterator it = mPortals.begin(); - while (it != mPortals.end()) - { - p = *it; - if (p->getName() == portalName) - { - thePortal = p; - // erase entry in the master list - mPortals.erase(it); - break; - } - it++; - } - if (thePortal) - { - // remove the portal from it's target portal - Portal * targetPortal = thePortal->getTargetPortal(); - if (targetPortal) - { - targetPortal->setTargetPortal(0); // the targetPortal will still have targetZone value, but targetPortal will be invalid - } - // remove the Portal from it's home zone - PCZone * homeZone = thePortal->getCurrentHomeZone(); - if (homeZone) - { - // inform zone of portal change - homeZone->setPortalsUpdated(true); - homeZone->_removePortal(thePortal); - } - - // delete the portal instance - OGRE_DELETE thePortal; - } - } - - /** Create a new anti portal instance */ - AntiPortal* PCZSceneManager::createAntiPortal(const String& name, PortalBase::PORTAL_TYPE type) - { - AntiPortal* newAntiPortal = OGRE_NEW AntiPortal(name, type); - newAntiPortal->_notifyCreator(Root::getSingleton().getMovableObjectFactory("AntiPortal")); - newAntiPortal->_notifyManager(this); - mAntiPortals.push_front(newAntiPortal); - return newAntiPortal; - } - - /** Delete a anti portal instance by pointer */ - void PCZSceneManager::destroyAntiPortal(AntiPortal * p) - { - // remove the Portal from it's home zone - PCZone* homeZone = p->getCurrentHomeZone(); - if (homeZone) - { - // inform zone of portal change. Do here since PCZone is abstract - homeZone->setPortalsUpdated(true); - homeZone->_removeAntiPortal(p); - } - - // remove the portal from the master portal list - AntiPortalList::iterator it = std::find(mAntiPortals.begin(), mAntiPortals.end(), p); - if (it != mAntiPortals.end()) mAntiPortals.erase(it); - - // delete the portal instance - OGRE_DELETE p; - } - - /** Delete a anti portal instance by name */ - void PCZSceneManager::destroyAntiPortal(const String& portalName) - { - // find the anti portal from the master portal list - AntiPortal* p; - AntiPortal* thePortal = 0; - AntiPortalList::iterator it = mAntiPortals.begin(); - while (it != mAntiPortals.end()) - { - p = *it; - if (p->getName() == portalName) - { - thePortal = p; - // erase entry in the master list - mAntiPortals.erase(it); - break; - } - it++; - } - if (thePortal) - { - // remove the Portal from it's home zone - PCZone* homeZone = thePortal->getCurrentHomeZone(); - if (homeZone) - { - // inform zone of portal change - homeZone->setPortalsUpdated(true); - homeZone->_removeAntiPortal(thePortal); - } - - // delete the portal instance - OGRE_DELETE thePortal; - } - } - - /** Create a zone from a file (type of file - * depends on the zone type - * ZoneType_Default uses an Ogre Model (.mesh) file - * ZoneType_Octree uses an Ogre Model (.mesh) file - * ZoneType_Terrain uses a Terrain.CFG file - */ - PCZone * PCZSceneManager::createZoneFromFile(const String &zoneTypeName, - const String &zoneName, - PCZSceneNode * parentNode, - const String &filename) - { - PCZone * newZone; - - // create a new default zone - newZone = mZoneFactoryManager->createPCZone(this, zoneTypeName, zoneName); - // add to the global list of zones - mZones[newZone->getName()] = newZone; - if (filename != "none") - { - // set the zone geometry - newZone->setZoneGeometry(filename, parentNode); - } - - return newZone; - } - - /* Get a zone by name */ - PCZone * PCZSceneManager::getZoneByName(const String & zoneName) - { - ZoneMap::iterator i; - PCZone * zone; - i = mZones.find(zoneName); - if (i != mZones.end()) - { - zone = i->second; - return zone; - } - return 0; // couldn't find the zone - } - - void PCZSceneManager::setZoneGeometry(const String & zoneName, - PCZSceneNode * parentNode, - const String & filename) - { - ZoneMap::iterator i; - PCZone * zone; - i = mZones.find(zoneName); - if (i != mZones.end()) - { - zone = i->second; - zone->setZoneGeometry( filename, parentNode ); - return; - } - - } - - SceneNode* PCZSceneManager::createSceneNodeImpl(void) - { - auto ret = new PCZSceneNode(this); - // create any zone-specific data necessary - createZoneSpecificNodeData(ret); - return ret; - } - - SceneNode* PCZSceneManager::createSceneNodeImpl(const String& name) - { - auto ret = new PCZSceneNode(this, name); - // create any zone-specific data necessary - createZoneSpecificNodeData(ret); - return ret; - } - - // Create a camera for the scene - Camera * PCZSceneManager::createCamera( const String &name ) - { - // Check name not used - if (mCameras.find(name) != mCameras.end()) - { - OGRE_EXCEPT( - Exception::ERR_DUPLICATE_ITEM, - "A camera with the name " + name + " already exists", - "PCZSceneManager::createCamera" ); - } - - Camera * c = OGRE_NEW PCZCamera( name, this ); - mCameras.emplace(name, c); - - // create visible bounds aab map entry - mCamVisibleObjectsMap[c] = VisibleObjectsBoundsInfo(); - - // tell all the zones about the new camera - ZoneMap::iterator i; - PCZone * zone; - for (i = mZones.begin(); i != mZones.end(); i++) - { - zone = i->second; - zone->notifyCameraCreated( c ); - } - - return c; - } - - // Destroy a Scene Node by name. - void PCZSceneManager::destroySceneNode( const String &name ) - { - SceneNode * on = ( getSceneNode( name ) ); - - if ( on != 0 ) - { - // destroy the node - destroySceneNode( on ); - } - } - - // Destroy a scene node - void PCZSceneManager::destroySceneNode(SceneNode* sn) - { - if ( sn != 0 ) - { - // remove references to the node from zones - removeSceneNode( sn ); - - // destroy the node - SceneManager::destroySceneNode( sn ); - } - } - - //----------------------------------------------------------------------- - void PCZSceneManager::clearScene(void) - { - SceneManager::clearScene(); - - // delete all the zones - for (ZoneMap::iterator j = mZones.begin(); - j != mZones.end(); ++j) - { - OGRE_DELETE j->second; - } - mZones.clear(); - mDefaultZone = 0; - - // re-initialize - init(mDefaultZoneTypeName, mDefaultZoneFileName); - } - - /** Overridden from SceneManager */ - void PCZSceneManager::setWorldGeometryRenderQueue(uint8 qid) - { - // tell all the zones about the new WorldGeometryRenderQueue - ZoneMap::iterator i; - PCZone * zone; - for (i = mZones.begin(); i != mZones.end(); i++) - { - zone = i->second; - zone->notifyWorldGeometryRenderQueue( qid ); - } - // call the regular scene manager version - SceneManager::setWorldGeometryRenderQueue(qid); - - } - /** Overridden from SceneManager */ - void PCZSceneManager::_renderScene(Camera* cam, Viewport *vp, bool includeOverlays) - { - // notify all the zones that a scene render is starting - ZoneMap::iterator i; - PCZone * zone; - for (i = mZones.begin(); i != mZones.end(); i++) - { - zone = i->second; - zone->notifyBeginRenderScene(); - } - - // do the regular _renderScene - SceneManager::_renderScene(cam, vp, includeOverlays); - } - - /* enable/disable sky rendering */ - void PCZSceneManager::enableSky(bool onoff) - { - if (getSkyBoxNode()) - { - setSkyBoxEnabled(onoff); - } - else if (getSkyDomeNode()) - { - setSkyDomeEnabled(onoff); - } - else if (getSkyPlaneNode()) - { - setSkyPlaneEnabled(onoff); - } - } - - /* Set the zone which contains the sky node */ - void PCZSceneManager::setSkyZone(PCZone * zone) - { - if (zone == 0) - { - // if no zone specified, use default zone - zone = mDefaultZone; - } - if (auto node = (PCZSceneNode*)getSkyBoxNode()) - { - node->setHomeZone(zone); - node->anchorToHomeZone(zone); - zone->setHasSky(true); - } - if (auto node = (PCZSceneNode*)getSkyDomeNode()) - { - node->setHomeZone(zone); - node->anchorToHomeZone(zone); - zone->setHasSky(true); - } - if (auto node = (PCZSceneNode*)getSkyPlaneNode()) - { - node->setHomeZone(zone); - node->anchorToHomeZone(zone); - zone->setHasSky(true); - } - - } - - //----------------------------------------------------------------------- - // THIS IS THE MAIN LOOP OF THE MANAGER - //----------------------------------------------------------------------- - /* _updateSceneGraph does several things now: - 1) standard scene graph update (transform all nodes in the node tree) - 2) update the spatial data for all zones (& portals in the zones) - 3) Update the PCZSNMap entry for every scene node - */ - void PCZSceneManager::_updateSceneGraph( Camera * cam ) - { - // First do the standard scene graph update - SceneManager::_updateSceneGraph( cam ); - // check for portal zone-related changes (portals intersecting other portals) - _updatePortalZoneData(); - // mark nodes dirty base on portals that changed. - _dirtyNodeByMovingPortals(); - // update all scene nodes - _updatePCZSceneNodes(); - // calculate zones affected by each light - _calcZonesAffectedByLights(cam); - // clear update flags at end so user triggered updated are - // not cleared prematurely - _clearAllZonesPortalUpdateFlag(); - } - - /** Update the zone data for every zone portal in the scene */ - - void PCZSceneManager::_updatePortalZoneData(void) - { - PCZone * zone; - ZoneMap::iterator zit = mZones.begin(); - - while ( zit != mZones.end() ) - { - zone = zit->second; - // this callchecks for portal zone changes & applies zone data changes as necessary - zone->updatePortalsZoneData(); - // proceed to next zone in the list - ++zit; - } - } - - /** Mark nodes dirty for every zone with moving portal in the scene */ - void PCZSceneManager::_dirtyNodeByMovingPortals(void) - { - PCZone * zone; - ZoneMap::iterator zit = mZones.begin(); - - while ( zit != mZones.end() ) - { - zone = zit->second; - // this call mark nodes dirty base on moving portals - zone->dirtyNodeByMovingPortals(); - // proceed to next zone in the list - ++zit; - } - } - - /* Update all PCZSceneNodes. - */ - void PCZSceneManager::_updatePCZSceneNodes(void) - { - SceneNodeList::iterator it = mSceneNodes.begin(); - PCZSceneNode * pczsn; - - while ( it != mSceneNodes.end() ) - { - pczsn = (PCZSceneNode*)*it; - if (pczsn->isMoved() && pczsn->isEnabled()) - { - // Update a single entry - _updatePCZSceneNode(pczsn); - - // reset moved state. - pczsn->setMoved(false); - } - // proceed to next entry in the list - ++it; - } - } - - /* - */ - void PCZSceneManager::_calcZonesAffectedByLights(Camera * cam) - { - MovableObjectCollection* lights = - getMovableObjectCollection(PCZLightFactory::FACTORY_TYPE_NAME); - { - OGRE_LOCK_MUTEX(lights->mutex); - - MovableObjectIterator it(lights->map.begin(), lights->map.end()); - - while(it.hasMoreElements()) - { - PCZLight* l = static_cast(it.getNext()); - if(l->getNeedsUpdate()) - { - // only update if necessary - l->updateZones(((PCZSceneNode*)(cam->getParentSceneNode()))->getHomeZone(), mFrameCount); - } - // clear update flag - l->clearNeedsUpdate(); - } - } - } - - //----------------------------------------------------------------------- - // Update all the zone info for a given node. This function - // makes sure the home zone of the node is correct, and references - // to any zones it is visiting are added and a reference to the - // node is added to the visitor lists of any zone it is visiting. - // - void PCZSceneManager::_updatePCZSceneNode( PCZSceneNode * pczsn ) - { - // Skip if root Zone has been destroyed (shutdown conditions) - if (!mDefaultZone) - return; - - // Skip if the node is the sceneroot node - if (pczsn == getRootSceneNode()) - return; - - // clear all references to visiting zones - pczsn->clearNodeFromVisitedZones(); - - // Find the current home zone of the node associated with the pczsn entry. - _updateHomeZone( pczsn, false ); - - /* The following function does the following: - * 1) Check all portals in the home zone - if the node is touching the portal - * then add the node to the connected zone as a visitor - * 2) Recurse into visited zones in case the node spans several zones - */ - // (recursively) check each portal of home zone to see if the node is touching - if (pczsn->getHomeZone() && - pczsn->allowedToVisit() == true) - { - pczsn->getHomeZone()->_checkNodeAgainstPortals(pczsn, 0); - } - - // update zone-specific data for the node for any zones that require it - pczsn->updateZoneData(); - } - - /** Removes all references to the node from every zone in the scene. - */ - void PCZSceneManager::removeSceneNode( SceneNode * sn ) - { - // Skip if mDefaultZone has been destroyed (shutdown conditions) - if (!mDefaultZone) - return; - - PCZSceneNode * pczsn = (PCZSceneNode*)sn; - - // clear all references to the node in visited zones - pczsn->clearNodeFromVisitedZones(); - - // tell the node it's not in a zone - pczsn->setHomeZone(0); - } - - // Set the home zone for a node - void PCZSceneManager::addPCZSceneNode(PCZSceneNode * sn, PCZone * homeZone) - { - // set the home zone - sn->setHomeZone(homeZone); - // add the node - homeZone->_addNode(sn); - } - - //----------------------------------------------------------------------- - /* Create a zone with the given name and parent zone */ - PCZone * PCZSceneManager::createZone(const String& zoneType, const String& instanceName) - { - if (mZones.find(instanceName) != mZones.end()) - { - OGRE_EXCEPT( - Exception::ERR_DUPLICATE_ITEM, - "A zone with the name " + instanceName + " already exists", - "PCZSceneManager::createZone" ); - } - PCZone * newZone = mZoneFactoryManager->createPCZone(this, zoneType, instanceName); - if (newZone) - { - // add to the global list of zones - mZones[instanceName] = newZone; - - if (newZone->requiresZoneSpecificNodeData()) - { - createZoneSpecificNodeData(newZone); - } - } - return newZone; - } - - /* destroy an existing zone within the scene */ - /* if destroySceneNodes is true, then all nodes which have the destroyed - zone as their homezone are desroyed too. If destroySceneNodes is false - then all scene nodes which have the zone as their homezone will have - their homezone pointer set to 0, which will allow them to be re-assigned - either by the user or via the automatic re-assignment routine */ - void PCZSceneManager::destroyZone(PCZone* zone, bool destroySceneNodes) - { - // need to remove this zone from all lights affected zones list, - // otherwise next frame _calcZonesAffectedByLights will call PCZLight::getNeedsUpdate() - // which will try to access the zone pointer and will cause an access violation - MovableObjectCollection* lights = - getMovableObjectCollection(PCZLightFactory::FACTORY_TYPE_NAME); - { - OGRE_LOCK_MUTEX(lights->mutex); // Is locking necessary in destroyZone? I don't know.. - - MovableObjectIterator it(lights->map.begin(), lights->map.end()); - - while(it.hasMoreElements()) - { - PCZLight* l = static_cast(it.getNext()); - if(l) - { - // no need to check, this function does that anyway. if exists, is erased. - l->removeZoneFromAffectedZonesList(zone); - } - } - } - // if not destroying scene nodes, then make sure any nodes who have - // this zone as homezone are set to have 0 for a homezone - for (SceneNodeList::iterator i = mSceneNodes.begin(); - i != mSceneNodes.end(); ++i) - { - PCZSceneNode * pczsn = (PCZSceneNode*)*i; - if (!destroySceneNodes) - { - if (pczsn->getHomeZone() == zone) - { - pczsn->setHomeZone(0); - } - } - // reset all node visitor lists - // note, it might be more efficient to only do this to nodes which - // are actually visiting the zone being destroyed, but visitor lists - // get cleared every frame anyway, so it's not THAT big a deal. - pczsn->clearNodeFromVisitedZones(); - } - - ZoneMap::iterator it; - it = mZones.find(zone->getName()); - if (it != mZones.end()) - { - mZones.erase(zone->getName()); - } - OGRE_DELETE zone; - } - - /* The following function checks if a node has left it's current home zone. - * This is done by checking each portal in the zone. If the node has crossed - * the portal, then the current zone is no longer the home zone of the node. The - * function then recurses into the connected zones. Once a zone is found where - * the node does NOT cross out through a portal, that zone is the new home zone. - * When this function is done, the node should have the correct home zone already - * set. A pointer is returned to this zone as well. - * - * NOTE: If the node does not have a home zone when this function is called on it, - * the function will do its best to find the proper zone for the node using - * bounding box volume testing. This CAN fail to find the correct zone in - * some scenarios, so it is best for the user to EXPLICITLY set the home - * zone of the node when the node is added to the scene using - * PCZSceneNode::setHomeZone() - */ - void PCZSceneManager::_updateHomeZone( PCZSceneNode * pczsn, bool allowBackTouches ) - { - // Skip if root PCZoneTree has been destroyed (shutdown conditions) - if (!mDefaultZone) - return; - - PCZone * startzone; - PCZone * newHomeZone; - - // start with current home zone of the node - startzone = pczsn->getHomeZone(); - - if (startzone) - { - if (!pczsn->isAnchored()) - { - newHomeZone = startzone->updateNodeHomeZone(pczsn, false); - } - else - { - newHomeZone = startzone; - } - - if (newHomeZone != startzone) - { - // add the node to the home zone - newHomeZone->_addNode(pczsn); - } - } - else - { - // the node hasn't had it's home zone set yet, so do our best to - // find the home zone using volume testing. - Vector3 nodeCenter = pczsn->_getDerivedPosition(); - PCZone * bestZone = findZoneForPoint(nodeCenter); - // set the best zone as the node's home zone - pczsn->setHomeZone(bestZone); - // add the node to the zone - bestZone->_addNode(pczsn); - } - - return; - - } - - /* Find the best (smallest) zone that contains a point - */ - PCZone * PCZSceneManager::findZoneForPoint(Vector3 & point) - { - PCZone * zone; - PCZone * bestZone = mDefaultZone; - Real bestVolume = Ogre::Math::POS_INFINITY; - - ZoneMap::iterator zit = mZones.begin(); - - while ( zit != mZones.end() ) - { - zone = zit->second; - AxisAlignedBox aabb; - zone->getAABB(aabb); - SceneNode * enclosureNode = zone->getEnclosureNode(); - if (enclosureNode != 0) - { - // since this is the "local" AABB, add in world translation of the enclosure node - aabb.setMinimum(aabb.getMinimum() + enclosureNode->_getDerivedPosition()); - aabb.setMaximum(aabb.getMaximum() + enclosureNode->_getDerivedPosition()); - } - if (aabb.contains(point)) - { - if (aabb.volume() < bestVolume) - { - // this zone is "smaller" than the current best zone, so make it - // the new best zone - bestZone = zone; - bestVolume = aabb.volume(); - } - } - // proceed to next zone in the list - ++zit; - } - return bestZone; - } - - // create any zone-specific data necessary for all zones for the given node - void PCZSceneManager::createZoneSpecificNodeData(PCZSceneNode * node) - { - ZoneMap::iterator i; - PCZone * zone; - for (i = mZones.begin(); i != mZones.end(); i++) - { - zone = i->second; - if (zone->requiresZoneSpecificNodeData()) - { - zone->createNodeZoneData(node); - } - } - } - - // create any zone-specific data necessary for all nodes for the given zone - void PCZSceneManager::createZoneSpecificNodeData(PCZone * zone) - { - SceneNodeList::iterator it = mSceneNodes.begin(); - PCZSceneNode * pczsn; - if (zone->requiresZoneSpecificNodeData()) - { - while ( it != mSceneNodes.end() ) - { - pczsn = (PCZSceneNode*)*it; - // create zone specific data for the node - zone->createNodeZoneData(pczsn); - // proceed to next entry in the list - ++it; - } - } - } - - // set the home zone for a scene node - void PCZSceneManager::setNodeHomeZone(SceneNode *node, PCZone *zone) - { - // cast the Ogre::SceneNode to a PCZSceneNode - PCZSceneNode * pczsn = (PCZSceneNode*)node; - pczsn->setHomeZone(zone); - } - - //----------------------------------------------------------------------- - Light* PCZSceneManager::createLight(const String& name) - { - return static_cast( - createMovableObject(name, PCZLightFactory::FACTORY_TYPE_NAME)); - } - //----------------------------------------------------------------------- - Light* PCZSceneManager::getLight(const String& name) const - { - return static_cast( - getMovableObject(name, PCZLightFactory::FACTORY_TYPE_NAME)); - } - //----------------------------------------------------------------------- - bool PCZSceneManager::hasLight(const String& name) const - { - return hasMovableObject(name, PCZLightFactory::FACTORY_TYPE_NAME); - } - //----------------------------------------------------------------------- - void PCZSceneManager::destroyLight(const String& name) - { - destroyMovableObject(name, PCZLightFactory::FACTORY_TYPE_NAME); - } - //----------------------------------------------------------------------- - void PCZSceneManager::destroyAllLights(void) - { - destroyAllMovableObjectsByType(PCZLightFactory::FACTORY_TYPE_NAME); - } - //--------------------------------------------------------------------- - void PCZSceneManager::findLightsAffectingFrustum(const Camera* camera) - { - // Similar to the basic SceneManager, we iterate through - // lights to see which ones affect the frustum. However, - // since we have camera & lights partitioned by zones, - // we can check only those lights which either affect the - // zone the camera is in, or affect zones which are visible to - // the camera - - MovableObjectCollection* lights = - getMovableObjectCollection(PCZLightFactory::FACTORY_TYPE_NAME); - - - { - OGRE_LOCK_MUTEX(lights->mutex); - - // Pre-allocate memory - mTestLightInfos.clear(); - mTestLightInfos.reserve(lights->map.size()); - - MovableObjectIterator it(lights->map.begin(), lights->map.end()); - - while(it.hasMoreElements()) - { - PCZLight* l = static_cast(it.getNext()); - if (l->isVisible() && - l->affectsVisibleZone()) - { - LightInfo lightInfo; - lightInfo.light = l; - lightInfo.type = l->getType(); - if (lightInfo.type == Light::LT_DIRECTIONAL) - { - // Always visible - lightInfo.position = Vector3::ZERO; - lightInfo.range = 0; - mTestLightInfos.push_back(lightInfo); - } - else - { - // NB treating spotlight as point for simplicity - // Just see if the lights attenuation range is within the frustum - lightInfo.range = l->getAttenuationRange(); - lightInfo.position = l->getDerivedPosition(); - Sphere sphere(lightInfo.position, lightInfo.range); - if (camera->isVisible(sphere)) - { - mTestLightInfos.push_back(lightInfo); - } - } - } - } - } // release lock on lights collection - - updateCachedLightInfos(camera); - } - //--------------------------------------------------------------------- - void PCZSceneManager::ensureShadowTexturesCreated() - { - SceneManager::ensureShadowTexturesCreated(); - if (!isShadowTextureConfigDirty()) return; - - for (auto cam : getShadowTextureCameras()) - { - auto node = (PCZSceneNode*)cam->getParentSceneNode(); - addPCZSceneNode(node, mDefaultZone); - } - } - //--------------------------------------------------------------------- - void PCZSceneManager::shadowTextureCasterPreViewProj(Light* light, Camera* camera, size_t iteration) - { - PCZSceneNode* camNode = (PCZSceneNode*)camera->getParentSceneNode(); - - if (light->getType() == Light::LT_DIRECTIONAL) - { - if (camNode->getHomeZone() != mActiveCameraZone) - addPCZSceneNode(camNode, mActiveCameraZone); - } - else - { - PCZSceneNode* lightNode = (PCZSceneNode*)light->getParentSceneNode(); - assert(lightNode); - PCZone* lightZone = lightNode->getHomeZone(); - if (camNode->getHomeZone() != lightZone) - addPCZSceneNode(camNode, lightZone); - } - } - - /* Attempt to automatically connect unconnected portals to proper target zones - * by looking for matching portals in other zones which are at the same location - */ - void PCZSceneManager::connectPortalsToTargetZonesByLocation(void) - { - // go through every zone to find portals - ZoneMap::iterator i, iend; - PCZone* zone; - iend = mZones.end(); - bool foundMatch; - for (i = mZones.begin(); i != iend; i++) - { - zone = i->second; - // go through all the portals in the zone - Portal* portal; - PortalList::iterator pi, piend; - piend = zone->mPortals.end(); - for (pi = zone->mPortals.begin(); pi != piend; pi++) - { - portal = *pi; - //portal->updateDerivedValues(); - if (portal->getTargetZone() == 0) - { - // this is a portal without a connected zone - look for - // a matching portal in another zone - PCZone* zone2; - ZoneMap::iterator j= mZones.begin(); - foundMatch = false; - while (!foundMatch && j != mZones.end()) - { - zone2 = j->second; - if (zone2 != zone) // make sure we don't look in the same zone - { - Portal * portal2 = zone2->findMatchingPortal(portal); - if (portal2) - { - // found a match! - Ogre::LogManager::getSingletonPtr()->logMessage("Connecting portal "+portal->getName()+" to portal "+portal2->getName()); - foundMatch = true; - portal->setTargetZone(zone2); - portal->setTargetPortal(portal2); - portal2->setTargetZone(zone); - portal2->setTargetPortal(portal); - } - } - j++; - } - if (foundMatch == false) - { - // error, didn't find a matching portal! - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Could not find matching portal for portal " + portal->getName(), - "PCZSceneManager::connectPortalsToTargetZonesByLocation"); - - } - } - } - } - } - - // main visibility determination & render queue filling routine - // over-ridden from base/default scene manager. This is *the* - // main call. - void PCZSceneManager::_findVisibleObjects(Camera* cam, - VisibleObjectsBoundsInfo* visibleBounds, - bool onlyShadowCasters) - { - // clear the render queue - getRenderQueue()->clear(); - - // if we are re-rendering the scene again with the same camera, we can just use the cache. - // this helps post processing compositors. - unsigned long frameCount = Root::getSingleton().getNextFrameNumber(); - if (mLastActiveCamera == cam && mFrameCount == frameCount) - { - RenderQueue* queue = getRenderQueue(); - size_t count = mVisible.size(); - for (size_t i = 0; i < count; ++i) - { - ((PCZSceneNode*)mVisible[i])->_addToRenderQueue( - cam, queue, onlyShadowCasters, visibleBounds); - } - return; - } - - // increment the visibility frame counter - mFrameCount = frameCount; - mLastActiveCamera = cam; - - // clear the list of visible nodes - mVisible.clear(); - - // turn off sky - enableSky(false); - - // remove all extra culling planes - ((PCZCamera*)cam)->removeAllExtraCullingPlanes(); - - // update the camera - ((PCZCamera*)cam)->update(); - - // get the home zone of the camera - PCZone* cameraHomeZone = ((PCZSceneNode*)(cam->getParentSceneNode()))->getHomeZone(); - - // walk the zones, starting from the camera home zone, - // adding all visible scene nodes to the mVisibles list - cameraHomeZone->setLastVisibleFrame(mFrameCount); - cameraHomeZone->findVisibleNodes((PCZCamera*)cam, - mVisible, - getRenderQueue(), - visibleBounds, - onlyShadowCasters, - getDisplaySceneNodes(), - getShowBoundingBoxes()); - } - - void PCZSceneManager::findNodesIn( const AxisAlignedBox &box, - PCZSceneNodeList &list, - PCZone * startZone, - PCZSceneNode *exclude ) - { - PortalList visitedPortals; - if (startZone) - { - // start in startzone, and recurse through portals if necessary - startZone->_findNodes(box, list, visitedPortals, true, true, exclude); - } - else - { - // no start zone specified, so check all zones - ZoneMap::iterator i; - PCZone * zone; - for (i = mZones.begin(); i != mZones.end(); i++) - { - zone = i->second; - zone->_findNodes( box, list, visitedPortals, false, false, exclude ); - } - } - } - - void PCZSceneManager::findNodesIn( const Sphere &sphere, - PCZSceneNodeList &list, - PCZone * startZone, - PCZSceneNode *exclude ) - { - PortalList visitedPortals; - if (startZone) - { - // start in startzone, and recurse through portals if necessary - startZone->_findNodes(sphere, list, visitedPortals, true, true, exclude); - } - else - { - // no start zone specified, so check all zones - ZoneMap::iterator i; - PCZone * zone; - for (i = mZones.begin(); i != mZones.end(); i++) - { - zone = i->second; - zone->_findNodes( sphere, list, visitedPortals, false, false, exclude ); - } - } - } - - void PCZSceneManager::findNodesIn( const PlaneBoundedVolume &volume, - PCZSceneNodeList &list, - PCZone * startZone, - PCZSceneNode *exclude ) - { - PortalList visitedPortals; - if (startZone) - { - // start in startzone, and recurse through portals if necessary - startZone->_findNodes(volume, list, visitedPortals, true, true, exclude); - } - else - { - // no start zone specified, so check all zones - ZoneMap::iterator i; - PCZone * zone; - for (i = mZones.begin(); i != mZones.end(); i++) - { - zone = i->second; - zone->_findNodes( volume, list, visitedPortals, false, false, exclude ); - } - } - } - - void PCZSceneManager::findNodesIn( const Ray &r, - PCZSceneNodeList &list, - PCZone * startZone, - PCZSceneNode *exclude ) - { - PortalList visitedPortals; - if (startZone) - { - // start in startzone, and recurse through portals if necessary - startZone->_findNodes(r, list, visitedPortals, true, true, exclude); - } - else - { - ZoneMap::iterator i; - PCZone * zone; - for (i = mZones.begin(); i != mZones.end(); i++) - { - zone = i->second; - zone->_findNodes( r, list, visitedPortals, false, false, exclude ); - } - } - } - - // get the current value of a scene manager option - bool PCZSceneManager::getOptionValues( const String & key, StringVector &refValueList ) - { - return SceneManager::getOptionValues( key, refValueList ); - } - - // get option keys (base along with PCZ-specific) - bool PCZSceneManager::getOptionKeys( StringVector & refKeys ) - { - SceneManager::getOptionKeys( refKeys ); - refKeys.push_back( "ShowBoundingBoxes" ); - refKeys.push_back( "ShowPortals" ); - - return true; - } - - bool PCZSceneManager::setOption( const String & key, const void * val ) - { - if ( key == "ShowBoundingBoxes" ) - { - showBoundingBoxes(* static_cast < const bool * > ( val )); - return true; - } - - else if ( key == "ShowPortals" ) - { - mShowPortals = * static_cast < const bool * > ( val ); - return true; - } - // send option to each zone - ZoneMap::iterator i; - PCZone * zone; - for (i = mZones.begin(); i != mZones.end(); i++) - { - zone = i->second; - if (zone->setOption(key, val ) == true) - { - return true; - } - } - - // try regular scenemanager option - return SceneManager::setOption( key, val ); - - - } - - bool PCZSceneManager::getOption( const String & key, void *val ) - { - if ( key == "ShowBoundingBoxes" ) - { - - * static_cast < bool * > ( val ) = getShowBoundingBoxes(); - return true; - } - if ( key == "ShowPortals" ) - { - - * static_cast < bool * > ( val ) = mShowPortals; - return true; - } - return SceneManager::getOption( key, val ); - - } - - //--------------------------------------------------------------------- - AxisAlignedBoxSceneQuery* - PCZSceneManager::createAABBQuery(const AxisAlignedBox& box, uint32 mask) - { - PCZAxisAlignedBoxSceneQuery* q = OGRE_NEW PCZAxisAlignedBoxSceneQuery(this); - q->setBox(box); - q->setQueryMask(mask); - return q; - } - //--------------------------------------------------------------------- - SphereSceneQuery* - PCZSceneManager::createSphereQuery(const Sphere& sphere, uint32 mask) - { - PCZSphereSceneQuery* q = OGRE_NEW PCZSphereSceneQuery(this); - q->setSphere(sphere); - q->setQueryMask(mask); - return q; - } - //--------------------------------------------------------------------- - PlaneBoundedVolumeListSceneQuery* - PCZSceneManager::createPlaneBoundedVolumeQuery(const PlaneBoundedVolumeList& volumes, - uint32 mask) - { - PCZPlaneBoundedVolumeListSceneQuery* q = OGRE_NEW PCZPlaneBoundedVolumeListSceneQuery(this); - q->setVolumes(volumes); - q->setQueryMask(mask); - return q; - } - - //--------------------------------------------------------------------- - RaySceneQuery* - PCZSceneManager::createRayQuery(const Ray& ray, uint32 mask) - { - PCZRaySceneQuery* q = OGRE_NEW PCZRaySceneQuery(this); - q->setRay(ray); - q->setQueryMask(mask); - return q; - } - //--------------------------------------------------------------------- - IntersectionSceneQuery* - PCZSceneManager::createIntersectionQuery(uint32 mask) - { - - PCZIntersectionSceneQuery* q = OGRE_NEW PCZIntersectionSceneQuery(this); - q->setQueryMask(mask); - return q; - } - //--------------------------------------------------------------------- - // clear portal update flag from all zones - void PCZSceneManager::_clearAllZonesPortalUpdateFlag(void) - { - ZoneMap::iterator zoneIterator = mZones.begin(); - - while ( zoneIterator != mZones.end() ) - { - (zoneIterator->second)->setPortalsUpdated(false); - zoneIterator++; - } - } - //--------------------------------------------------------------------- - /// See SceneManager::prepareShadowTextures. - void PCZSceneManager::prepareShadowTextures(Camera* cam, Viewport* vp, const LightList* lightList) - { - mActiveCameraZone = ((PCZSceneNode*)cam->getParentSceneNode())->getHomeZone(); - SceneManager::prepareShadowTextures(cam, vp); - } - - //----------------------------------------------------------------------- - const String PCZSceneManagerFactory::FACTORY_TYPE_NAME = "PCZSceneManager"; - //----------------------------------------------------------------------- - SceneManager* PCZSceneManagerFactory::createInstance( - const String& instanceName) - { - return OGRE_NEW PCZSceneManager(instanceName); - } - -} diff --git a/PlugIns/PCZSceneManager/src/OgrePCZSceneManagerDll.cpp b/PlugIns/PCZSceneManager/src/OgrePCZSceneManagerDll.cpp deleted file mode 100644 index 803a406e8b6..00000000000 --- a/PlugIns/PCZSceneManager/src/OgrePCZSceneManagerDll.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -OgrePCZSceneManagerDll.cpp - description ------------------------------------------------------------------------------ -begin : Wed Feb 21 2007 -author : Eric Cha -email : ericc@xenopi.com ------------------------------------------------------------------------------ -*/ - -#include "OgrePCZPrerequisites.h" -#include "OgreRoot.h" -#include "OgrePCZPlugin.h" - -#ifndef OGRE_STATIC_LIB - -namespace Ogre -{ - static PCZPlugin* pczPlugin; - extern "C" void _OgrePCZPluginExport dllStartPlugin(void); - extern "C" void _OgrePCZPluginExport dllStopPlugin(void); - - extern "C" void _OgrePCZPluginExport dllStartPlugin( void ) - { - // Create new scene manager - pczPlugin = OGRE_NEW PCZPlugin(); - - // Register - Root::getSingleton().installPlugin(pczPlugin); - - } - extern "C" void _OgrePCZPluginExport dllStopPlugin( void ) - { - Root::getSingleton().uninstallPlugin(pczPlugin); - OGRE_DELETE pczPlugin; - } -} - -#endif diff --git a/PlugIns/PCZSceneManager/src/OgrePCZSceneNode.cpp b/PlugIns/PCZSceneManager/src/OgrePCZSceneNode.cpp deleted file mode 100644 index b0e908e0b51..00000000000 --- a/PlugIns/PCZSceneManager/src/OgrePCZSceneNode.cpp +++ /dev/null @@ -1,297 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -PCZSceneNode.cpp - PCZ-specific version of SceneNode - -The PCZSceneNode is an extension used to store zone information and provide -additional functionality for a given Ogre::SceneNode. A PCZSceneNode contains a -pointer to the home zone for the node and a list of all zones being visited by -the node. The PCZSceneManager contains a STD::MAP of PCZSceneNodes which are -keyed by the name of each node. This allows quick lookup of -a given scenenode's PCZSceneNode by the scene manager. - ------------------------------------------------------------------------------ -begin : Sat Mar 24 2007 -author : Eric Cha -email : ericc@xenopi.com -TODO : None known ------------------------------------------------------------------------------ -*/ - -#include "OgrePCZSceneNode.h" -#include "OgreSceneNode.h" -#include "OgrePCZone.h" - -namespace Ogre -{ - PCZSceneNode::PCZSceneNode( SceneManager* creator ) - : SceneNode( creator ), - mHomeZone(0), - mAnchored(false), - mAllowedToVisit(true), - mLastVisibleFrame(0), - mLastVisibleFromCamera(0), - mEnabled(true), - mMoved(false) - { - } - - PCZSceneNode::PCZSceneNode( SceneManager* creator, const String& name ) - : SceneNode( creator, name ), - mHomeZone(0), - mAnchored(false), - mAllowedToVisit(true), - mLastVisibleFrame(0), - mLastVisibleFromCamera(0), - mEnabled(true), - mMoved(false) - { - } - - PCZSceneNode::~PCZSceneNode() - { - // clear visiting zones list - mVisitingZones.clear(); - - // delete zone data - ZoneData* zoneData; - ZoneDataMap::iterator it = mZoneData.begin(); - - while ( it != mZoneData.end() ) - { - zoneData = it->second; - OGRE_DELETE zoneData; - ++it; - } - mZoneData.clear(); - } - void PCZSceneNode::_update(bool updateChildren, bool parentHasChanged) - { - Node::_update(updateChildren, parentHasChanged); - if (getParent()) _updateBounds(); // skip bound update if it's root scene node. Saves a lot of CPU. - - mPrevPosition = mNewPosition; - mNewPosition = mDerivedPosition; - } - void PCZSceneNode::updateFromParentImpl() const - { - SceneNode::updateFromParentImpl(); - mMoved = true; - } - //----------------------------------------------------------------------- - SceneNode* PCZSceneNode::createChildSceneNode(const Vector3& inTranslate, - const Quaternion& inRotate) - { - PCZSceneNode * childSceneNode = (PCZSceneNode*)(this->createChild(inTranslate, inRotate)); - if (mHomeZone) - { - childSceneNode->setHomeZone(mHomeZone); - mHomeZone->_addNode(childSceneNode); - } - return static_cast(childSceneNode); - } - //----------------------------------------------------------------------- - SceneNode* PCZSceneNode::createChildSceneNode(const String& name, const Vector3& inTranslate, - const Quaternion& inRotate) - { - PCZSceneNode * childSceneNode = (PCZSceneNode*)(this->createChild(name, inTranslate, inRotate)); - if (mHomeZone) - { - childSceneNode->setHomeZone(mHomeZone); - mHomeZone->_addNode(childSceneNode); - } - return static_cast(childSceneNode); - } - - PCZone* PCZSceneNode::getHomeZone(void) - { - return mHomeZone; - } - void PCZSceneNode::setHomeZone(PCZone * zone) - { - // if the new home zone is different than the current, remove - // the node from the current home zone's list of home nodes first - if (zone != mHomeZone && mHomeZone) - { - mHomeZone->removeNode(this); - } - mHomeZone = zone; - } - void PCZSceneNode::anchorToHomeZone(PCZone * zone) - { - mHomeZone = zone; - if (zone) - { - mAnchored = true; - } - else - { - mAnchored = false; - } - } - void PCZSceneNode::addZoneToVisitingZonesMap(PCZone * zone) - { - mVisitingZones[zone->getName()] = zone; - } - void PCZSceneNode::clearVisitingZonesMap(void) - { - mVisitingZones.clear(); - } - /* The following function does the following: - * 1) Remove references to the node from zones the node is visiting - * 2) Clear the node's list of zones it is visiting - */ - void PCZSceneNode::clearNodeFromVisitedZones( void ) - { - if (mVisitingZones.size() > 0) - { - // first go through the list of zones this node is visiting - // and remove references to this node - PCZone* zone; - ZoneMap::iterator it = mVisitingZones.begin(); - - while ( it != mVisitingZones.end() ) - { - zone = it->second; - zone->removeNode(this); - ++it; - } - - // second, clear the visiting zones list - mVisitingZones.clear(); - - } - } - - /* Remove all references that the node has to the given zone - */ - void PCZSceneNode::removeReferencesToZone(PCZone * zone) - { - if (mHomeZone == zone) - { - mHomeZone = 0; - } - // search the map of visiting zones and remove - ZoneMap::iterator i; - i = mVisitingZones.find(zone->getName()); - if (i != mVisitingZones.end()) - { - mVisitingZones.erase(i); - } - } - - /* returns true if zone is in the node's visiting zones map - false otherwise. - */ - bool PCZSceneNode::isVisitingZone(PCZone * zone) - { - ZoneMap::iterator i; - i = mVisitingZones.find(zone->getName()); - if (i != mVisitingZones.end()) - { - return true; - } - return false; - } - - /** Adds the attached objects of this PCZSceneNode into the queue. */ - void PCZSceneNode::_addToRenderQueue( Camera* cam, - RenderQueue *queue, - bool onlyShadowCasters, - VisibleObjectsBoundsInfo* visibleBounds ) - { - for ( auto mo : getAttachedObjects() ) - { - mo->_notifyCurrentCamera(cam); - if ( mo->isVisible() && - (!onlyShadowCasters || mo->getCastShadows())) - { - mo -> _updateRenderQueue( queue ); - - if (visibleBounds) - { - visibleBounds->merge(mo->getWorldBoundingBox(true), - mo->getWorldBoundingSphere(true), - cam); - } - } - } - } - - /** Save the node's current position as the previous position - */ - void PCZSceneNode::savePrevPosition(void) - { - mPrevPosition = _getDerivedPosition(); - } - - void PCZSceneNode::setZoneData(PCZone * zone, ZoneData * zoneData) - { - - // first make sure that the data doesn't already exist - if (mZoneData.find(zone->getName()) != mZoneData.end()) - { - OGRE_EXCEPT( - Exception::ERR_DUPLICATE_ITEM, - "A ZoneData associated with zone " + zone->getName() + " already exists", - "PCZSceneNode::setZoneData" ); - } - mZoneData[zone->getName()] = zoneData; - } - - // get zone data for this node for given zone - // NOTE: This routine assumes that the zone data is present! - ZoneData* PCZSceneNode::getZoneData(PCZone * zone) - { - return mZoneData[zone->getName()]; - } - - // update zone-specific data for any zone that the node is touching - void PCZSceneNode::updateZoneData(void) - { - ZoneData* zoneData; - PCZone * zone; - // make sure home zone data is updated - zone = mHomeZone; - if (zone->requiresZoneSpecificNodeData()) - { - zoneData = getZoneData(zone); - zoneData->update(); - } - // update zone data for any zones visited - ZoneMap::iterator it = mVisitingZones.begin(); - while ( it != mVisitingZones.end() ) - { - zone = it->second; - if (zone->requiresZoneSpecificNodeData()) - { - zoneData = getZoneData(zone); - zoneData->update(); - } - ++it; - } - } -} diff --git a/PlugIns/PCZSceneManager/src/OgrePCZSceneQuery.cpp b/PlugIns/PCZSceneManager/src/OgrePCZSceneQuery.cpp deleted file mode 100644 index a582e2b855e..00000000000 --- a/PlugIns/PCZSceneManager/src/OgrePCZSceneQuery.cpp +++ /dev/null @@ -1,334 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -OgrePCZSceneQuery.cpp - Scene Query implementations for PCZSceneManager ------------------------------------------------------------------------------ -begin : Wed Feb 21, 2007 -author : Eric Cha -email : ericc@xenopi.com -current TODO's : none known ------------------------------------------------------------------------------ -*/ - -#include "OgreRoot.h" - -#include "OgrePCZSceneQuery.h" -#include "OgrePCZSceneManager.h" -#include "OgrePCZSceneNode.h" -#include "OgreEntity.h" - -namespace Ogre -{ - - //--------------------------------------------------------------------- - PCZIntersectionSceneQuery::PCZIntersectionSceneQuery(SceneManager* creator) - : DefaultIntersectionSceneQuery(creator) - { - - } - //--------------------------------------------------------------------- - PCZIntersectionSceneQuery::~PCZIntersectionSceneQuery() - {} - //--------------------------------------------------------------------- - void PCZIntersectionSceneQuery::execute(IntersectionSceneQueryListener* listener) - { - typedef std::pair MovablePair; - typedef std::set - < std::pair > MovableSet; - - MovableSet set; - - // Iterate over all movable types - for(const auto& factIt : Root::getSingleton().getMovableObjectFactories()) - { - for (const auto& it : mParentSceneMgr->getMovableObjects(factIt.first)) - { - - MovableObject * e = it.second; - PCZone * zone = ((PCZSceneNode*)(e->getParentSceneNode()))->getHomeZone(); - PCZSceneNodeList list; - //find the nodes that intersect the AAB - static_cast( mParentSceneMgr ) -> findNodesIn( e->getWorldBoundingBox(), list, zone, 0 ); - //grab all moveables from the node that intersect... - PCZSceneNodeList::iterator nit = list.begin(); - while( nit != list.end() ) - { - for (auto m : (*nit)->getAttachedObjects()) - { - if( m != e && - set.find( MovablePair(e,m)) == set.end() && - set.find( MovablePair(m,e)) == set.end() && - (m->getQueryFlags() & mQueryMask) && - (m->getTypeFlags() & mQueryTypeMask) && - m->isInScene() && - e->getWorldBoundingBox().intersects( m->getWorldBoundingBox() ) ) - { - listener -> queryResult( e, m ); - // deal with attached objects, since they are not directly attached to nodes - if (m->getMovableType() == MOT_ENTITY) - { - Entity* e2 = static_cast(m); - for (auto c : e2->getAttachedObjects()) - { - if (c->getQueryFlags() & mQueryMask && - e->getWorldBoundingBox().intersects( c->getWorldBoundingBox() )) - { - listener->queryResult(e, c); - } - } - } - } - set.insert( MovablePair(e,m) ); - - } - ++nit; - } - } - } - } - /** Creates a custom PCZ AAB query */ - PCZAxisAlignedBoxSceneQuery::PCZAxisAlignedBoxSceneQuery(SceneManager* creator) - : DefaultAxisAlignedBoxSceneQuery(creator) - { - mStartZone = 0; - mExcludeNode = 0; - } - /** Deletes the custom PCZ query */ - PCZAxisAlignedBoxSceneQuery::~PCZAxisAlignedBoxSceneQuery() - {} - - /** Finds any entities that intersect the AAB for the query. */ - void PCZAxisAlignedBoxSceneQuery::execute(SceneQueryListener* listener) - { - PCZSceneNodeList list; - //find the nodes that intersect the AAB - static_cast( mParentSceneMgr ) -> findNodesIn( mAABB, list, mStartZone, (PCZSceneNode*)mExcludeNode ); - - //grab all moveables from the node that intersect... - PCZSceneNodeList::iterator it = list.begin(); - while( it != list.end() ) - { - for (auto m : (*it)->getAttachedObjects()) - { - if( (m->getQueryFlags() & mQueryMask) && - (m->getTypeFlags() & mQueryTypeMask) && - m->isInScene() && - mAABB.intersects( m->getWorldBoundingBox() ) ) - { - listener -> queryResult( m ); - // deal with attached objects, since they are not directly attached to nodes - if (m->getMovableType() == MOT_ENTITY) - { - Entity* e = static_cast(m); - for (auto c : e->getAttachedObjects()) - { - if (c->getQueryFlags() & mQueryMask) - { - listener->queryResult(c); - } - } - } - } - - } - ++it; - } - // reset startzone and exclude node - mStartZone = 0; - mExcludeNode = 0; - } - //--------------------------------------------------------------------- - PCZRaySceneQuery:: - PCZRaySceneQuery(SceneManager* creator) : DefaultRaySceneQuery(creator) - { - mStartZone = 0; - mExcludeNode = 0; - } - //--------------------------------------------------------------------- - PCZRaySceneQuery::~PCZRaySceneQuery() - {} - //--------------------------------------------------------------------- - void PCZRaySceneQuery::execute(RaySceneQueryListener* listener) - { - PCZSceneNodeList list; - //find the nodes that intersect the Ray - static_cast( mParentSceneMgr ) -> findNodesIn( mRay, list, mStartZone, (PCZSceneNode*)mExcludeNode ); - - //grab all moveables from the node that intersect... - PCZSceneNodeList::iterator it = list.begin(); - while( it != list.end() ) - { - for (auto m : (*it)->getAttachedObjects()) - { - if( (m->getQueryFlags() & mQueryMask) && - (m->getTypeFlags() & mQueryTypeMask) && m->isInScene() ) - { - std::pair result = mRay.intersects(m->getWorldBoundingBox()); - - if( result.first ) - { - listener -> queryResult( m, result.second ); - // deal with attached objects, since they are not directly attached to nodes - if (m->getMovableType() == MOT_ENTITY) - { - Entity* e = static_cast(m); - for (auto c : e->getAttachedObjects()) - { - if (c->getQueryFlags() & mQueryMask) - { - result = mRay.intersects(c->getWorldBoundingBox()); - if (result.first) - { - listener->queryResult(c, result.second); - } - } - } - } - } - } - } - ++it; - } - // reset startzone and exclude node - mStartZone = 0; - mExcludeNode = 0; - } - - - //--------------------------------------------------------------------- - PCZSphereSceneQuery:: - PCZSphereSceneQuery(SceneManager* creator) : DefaultSphereSceneQuery(creator) - { - mStartZone = 0; - mExcludeNode = 0; - } - //--------------------------------------------------------------------- - PCZSphereSceneQuery::~PCZSphereSceneQuery() - {} - //--------------------------------------------------------------------- - void PCZSphereSceneQuery::execute(SceneQueryListener* listener) - { - PCZSceneNodeList list; - //find the nodes that intersect the Sphere - static_cast( mParentSceneMgr ) -> findNodesIn( mSphere, list, mStartZone, (PCZSceneNode*)mExcludeNode ); - - //grab all moveables from the node that intersect... - PCZSceneNodeList::iterator it = list.begin(); - while( it != list.end() ) - { - for (auto m : (*it)->getAttachedObjects()) - { - if( (m->getQueryFlags() & mQueryMask) && - (m->getTypeFlags() & mQueryTypeMask) && - m->isInScene() && - mSphere.intersects( m->getWorldBoundingBox() ) ) - { - listener -> queryResult( m ); - // deal with attached objects, since they are not directly attached to nodes - if (m->getMovableType() == MOT_ENTITY) - { - Entity* e = static_cast(m); - for (auto c : e->getAttachedObjects()) - { - if (c->getQueryFlags() & mQueryMask && - mSphere.intersects( c->getWorldBoundingBox())) - { - listener->queryResult(c); - } - } - } - } - } - ++it; - } - // reset startzone and exclude node - mStartZone = 0; - mExcludeNode = 0; - } - //--------------------------------------------------------------------- - PCZPlaneBoundedVolumeListSceneQuery:: - PCZPlaneBoundedVolumeListSceneQuery(SceneManager* creator) - : DefaultPlaneBoundedVolumeListSceneQuery(creator) - { - mStartZone = 0; - mExcludeNode = 0; - } - //--------------------------------------------------------------------- - PCZPlaneBoundedVolumeListSceneQuery::~PCZPlaneBoundedVolumeListSceneQuery() - {} - //--------------------------------------------------------------------- - void PCZPlaneBoundedVolumeListSceneQuery::execute(SceneQueryListener* listener) - { - std::set checkedSceneNodes; - - PlaneBoundedVolumeList::iterator pi, piend; - piend = mVolumes.end(); - for (pi = mVolumes.begin(); pi != piend; ++pi) - { - PCZSceneNodeList list; - //find the nodes that intersect the Plane bounded Volume - static_cast( mParentSceneMgr ) -> findNodesIn( *pi, list, mStartZone, (PCZSceneNode*)mExcludeNode ); - - //grab all moveables from the node that intersect... - PCZSceneNodeList::iterator it, itend; - itend = list.end(); - for (it = list.begin(); it != itend; ++it) - { - // avoid double-check same scene node - if (!checkedSceneNodes.insert(*it).second) - continue; - for (auto m : (*it)->getAttachedObjects()) - { - if( (m->getQueryFlags() & mQueryMask) && - (m->getTypeFlags() & mQueryTypeMask) && - m->isInScene() && - (*pi).intersects( m->getWorldBoundingBox() ) ) - { - listener -> queryResult( m ); - // deal with attached objects, since they are not directly attached to nodes - if (m->getMovableType() == MOT_ENTITY) - { - Entity* e = static_cast(m); - for (auto c : e->getAttachedObjects()) - { - if (c->getQueryFlags() & mQueryMask && - (*pi).intersects( c->getWorldBoundingBox())) - { - listener->queryResult(c); - } - } - } - } - } - } - }//for - // reset startzone and exclude node - mStartZone = 0; - mExcludeNode = 0; - } - - -} diff --git a/PlugIns/PCZSceneManager/src/OgrePCZone.cpp b/PlugIns/PCZSceneManager/src/OgrePCZone.cpp deleted file mode 100644 index 66a13af16d5..00000000000 --- a/PlugIns/PCZSceneManager/src/OgrePCZone.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -PCZone.cpp - description ------------------------------------------------------------------------------ -begin : Tue Feb 20 2007 -author : Eric Cha -email : ericc@xenopi.com ------------------------------------------------------------------------------ -*/ - -#include "OgrePCZone.h" -#include "OgreSceneNode.h" -#include "OgreAntiPortal.h" -#include "OgrePortal.h" - -namespace Ogre -{ - - PCZone::PCZone( PCZSceneManager * creator, const String& name ) - { - mLastVisibleFrame = 0; - mLastVisibleFromCamera = 0; - mName = name; - mZoneTypeName = "ZoneType_Undefined"; - mEnclosureNode = 0; - mPCZSM = creator; - mHasSky = false; - } - - PCZone::~PCZone() - { - } - - /** Remove all nodes from the node reference list and clear it - */ - void PCZone::_clearNodeLists(short type) - { - if (type & HOME_NODE_LIST) - { - mHomeNodeList.clear(); - } - if (type & VISITOR_NODE_LIST) - { - mVisitorNodeList.clear(); - } - } - - Portal * PCZone::findMatchingPortal(Portal * portal) - { - // look through all the portals in zone2 for a match - Portal* portal2; - PortalList::iterator pi2, piend2; - piend2 = mPortals.end(); - for (pi2 = mPortals.begin(); pi2 != piend2; pi2++) - { - portal2 = *pi2; - //portal2->updateDerivedValues(); - if (portal2->getTargetZone() == 0 && portal2->closeTo(portal) && - portal2->getDerivedDirection().dotProduct(portal->getDerivedDirection()) < -0.9) - { - // found a match! - return portal2; - } - } - // no match - return 0; - } - - - /* Add a portal to the zone */ - void PCZone::_addPortal(Portal * newPortal) - { - if (newPortal) - { - // make sure portal is unique (at least in this zone) - PortalList::iterator it = std::find(mPortals.begin(), mPortals.end(), newPortal); - if (it != mPortals.end()) - { - OGRE_EXCEPT( - Exception::ERR_DUPLICATE_ITEM, - "A portal with the name " + newPortal->getName() + " already exists", - "PCZone::_addPortal" ); - } - - // add portal to portals list - mPortals.push_back(newPortal); - - // tell the portal which zone it's currently in - newPortal->setCurrentHomeZone(this); - } - } - - /* Remove a portal from the zone (does not erase the portal object, just removes reference) */ - void PCZone::_removePortal(Portal * removePortal) - { - if (removePortal) - { - PortalList::iterator it = std::find(mPortals.begin(), mPortals.end(), removePortal); - if(it != mPortals.end()) - mPortals.erase(it); - } - } - - /* Add an anti portal to the zone */ - void PCZone::_addAntiPortal(AntiPortal* newAntiPortal) - { - if (newAntiPortal) - { - // make sure portal is unique (at least in this zone) - AntiPortalList::iterator it = std::find(mAntiPortals.begin(), mAntiPortals.end(), newAntiPortal); - if (it != mAntiPortals.end()) - { - OGRE_EXCEPT( - Exception::ERR_DUPLICATE_ITEM, - "An anti portal with the name " + newAntiPortal->getName() + " already exists", - "PCZone::_addAntiPortal" ); - } - - // add portal to portals list - mAntiPortals.push_back(newAntiPortal); - - // tell the portal which zone it's currently in - newAntiPortal->setCurrentHomeZone(this); - } - } - - /* Remove an anti portal from the zone */ - void PCZone::_removeAntiPortal(AntiPortal* removeAntiPortal) - { - if (removeAntiPortal) - { - AntiPortalList::iterator it = std::find(mAntiPortals.begin(), mAntiPortals.end(), removeAntiPortal); - if(it != mAntiPortals.end()) - mAntiPortals.erase(it); - } - } - - /* create node specific zone data if necessary - */ - void PCZone::createNodeZoneData(PCZSceneNode *) - { - } - - /* get the aabb of the zone - default implementation - uses the enclosure node, but there are other perhaps - better ways - */ - void PCZone::getAABB(AxisAlignedBox & aabb) - { - // if there is no node, just return a null box - if (mEnclosureNode == 0) - { - aabb.setNull(); - } - else - { - aabb = mEnclosureNode->_getWorldAABB(); - // since this is the "local" AABB, subtract out any translations - aabb.setMinimum(aabb.getMinimum() - mEnclosureNode->_getDerivedPosition()); - aabb.setMaximum(aabb.getMaximum() - mEnclosureNode->_getDerivedPosition()); - } - return; - } - - /***********************************************************************\ - ZoneData - Zone-specific Data structure for Scene Nodes - ************************************************************************/ - - ZoneData::ZoneData(PCZSceneNode * node, PCZone * zone) - { - mAssociatedZone = zone; - mAssociatedNode = node; - } - - ZoneData::~ZoneData() - { - } - - void ZoneData::update(void) - { - } -} diff --git a/PlugIns/PCZSceneManager/src/OgrePCZoneFactory.cpp b/PlugIns/PCZSceneManager/src/OgrePCZoneFactory.cpp deleted file mode 100644 index 3238c1a92a9..00000000000 --- a/PlugIns/PCZSceneManager/src/OgrePCZoneFactory.cpp +++ /dev/null @@ -1,142 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -OgrePCZoneFactory.cpp - PCZone Factory & Factory Manager - ------------------------------------------------------------------------------ -begin : Mon Apr 16 2007 -author : Eric Cha -email : ericc@xenopi.com -Code Style Update : ------------------------------------------------------------------------------ -*/ - -#include "OgrePCZoneFactory.h" -#include "OgreDefaultZone.h" -#include "OgreLogManager.h" - -namespace Ogre -{ - //------------------------------------------------------------------------- - // PCZoneFactory functions - PCZoneFactory::PCZoneFactory(const String & typeName) : mFactoryTypeName(typeName) - { - } - PCZoneFactory::~PCZoneFactory() - { - } - //------------------------------------------------------------------------- - // DefaultZoneFactory functions - //String defaultString = String("ZoneType_Default"); - DefaultZoneFactory::DefaultZoneFactory() : PCZoneFactory("ZoneType_Default") - { - } - DefaultZoneFactory::~DefaultZoneFactory() - { - } - bool DefaultZoneFactory::supportsPCZoneType(const String& zoneType) - { - if (mFactoryTypeName == zoneType) - { - return true; - } - return false; - } - PCZone* DefaultZoneFactory::createPCZone(PCZSceneManager * pczsm, const String& zoneName) - { - return OGRE_NEW DefaultZone(pczsm, zoneName); - } - //------------------------------------------------------------------------- - // PCZoneFactoryManager functions - template<> PCZoneFactoryManager* Singleton::msSingleton = 0; - PCZoneFactoryManager* PCZoneFactoryManager::getSingletonPtr(void) - { - return msSingleton; - } - PCZoneFactoryManager& PCZoneFactoryManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - PCZoneFactoryManager::PCZoneFactoryManager() - { - registerPCZoneFactory(&mDefaultFactory); - } - PCZoneFactoryManager::~PCZoneFactoryManager() - { - } - - void PCZoneFactoryManager::registerPCZoneFactory(PCZoneFactory* factory) - { - String name = factory->getFactoryTypeName(); - mPCZoneFactories[name] = factory; - LogManager::getSingleton().logMessage("PCZone Factory Type '" + name + "' registered"); - } - void PCZoneFactoryManager::unregisterPCZoneFactory(PCZoneFactory* factory) - { - if (factory) - { - //find and remove factory from mPCZoneFactories - // Note that this does not free the factory from memory, just removes from the factory manager - const String& name = factory->getFactoryTypeName(); - PCZoneFactoryMap::iterator zi = mPCZoneFactories.find(name); - if (zi != mPCZoneFactories.end()) - { - mPCZoneFactories.erase( mPCZoneFactories.find( name ) ); - LogManager::getSingleton().logMessage("PCZone Factory Type '" + name + "' unregistered"); - } - } - } - PCZone* PCZoneFactoryManager::createPCZone(PCZSceneManager * pczsm, - const String& zoneType, - const String& zoneName) - { - //find a factory that supports this zone type and then call createPCZone() on it - PCZone * inst = 0; - for(PCZoneFactoryMap::iterator i = mPCZoneFactories.begin(); i != mPCZoneFactories.end(); ++i) - { - if (i->second->supportsPCZoneType(zoneType)) - { - // use this factory - inst = i->second->createPCZone(pczsm, zoneName); - } - } - if (!inst) - { - // Error! - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "No factory found for zone of type '" + zoneType + "'", - "PCZoneFactoryManager::createPCZone"); - } - return inst; - } - //----------------------------------------------------------------------- - PCZoneFactoryManager::PCZoneFactoryIterator - PCZoneFactoryManager::getPCZoneFactoryIterator(void) - { - return PCZoneFactoryIterator(mPCZoneFactories.begin(), mPCZoneFactories.end()); - } -} - diff --git a/PlugIns/PCZSceneManager/src/OgrePortal.cpp b/PlugIns/PCZSceneManager/src/OgrePortal.cpp deleted file mode 100644 index 7cf4d224c53..00000000000 --- a/PlugIns/PCZSceneManager/src/OgrePortal.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -Portal.cpp - ------------------------------------------------------------------------------ -begin : Tue Feb 20 2007 -author : Eric Cha -email : ericc@xenopi.com -current TODO's : none known ------------------------------------------------------------------------------ -*/ - -#include "OgrePortal.h" - -using namespace Ogre; - -Portal::Portal(const String& name, const PORTAL_TYPE type) - : PortalBase(name, type), - mTargetZone(0), - mTargetPortal(0) -{ -} - -Portal::~Portal() -{ -} - -// Set the 1st Zone the Portal connects to -void Portal::setTargetZone(PCZone* zone) -{ - mTargetZone = zone; -} - -// Set the Portal the Portal connects to -void Portal::setTargetPortal(Portal* portal) -{ - mTargetPortal = portal; -} - -/** @copydoc MovableObject::getMovableType. */ -const String& Portal::getMovableType() const -{ - return PortalFactory::FACTORY_TYPE_NAME; -} - -//----------------------------------------------------------------------- -String PortalFactory::FACTORY_TYPE_NAME = "Portal"; -unsigned long PortalFactory::FACTORY_TYPE_FLAG = 0xFFFFFFFF; -//----------------------------------------------------------------------- - -MovableObject* PortalFactory::createInstanceImpl(const String& name, const NameValuePairList* params) -{ - return OGRE_NEW Portal(name, getPortalType(params)); -} \ No newline at end of file diff --git a/PlugIns/PCZSceneManager/src/OgrePortalBase.cpp b/PlugIns/PCZSceneManager/src/OgrePortalBase.cpp deleted file mode 100644 index 0fd20c42d2b..00000000000 --- a/PlugIns/PCZSceneManager/src/OgrePortalBase.cpp +++ /dev/null @@ -1,977 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -PortalBase.cpp - - -*/ - -#include "OgrePortalBase.h" -#include "OgreRay.h" -#include "OgrePCZone.h" // need access to real zone class -#include "OgrePCZSceneNode.h" - -using namespace Ogre; - -PortalBase::PortalBase(const String& name, const PORTAL_TYPE type) - : MovableObject(name), - mType(type), - mCurrentHomeZone(0), - mNewHomeZone(0), - mDirection(Vector3::UNIT_Z), - mRadius(0.0), - mLocalsUpToDate(false), - mDerivedUpToDate(false), - // set prevWorldTransform to a zero'd out matrix - mPrevWorldTransform(Affine3::ZERO), - // default to enabled - mEnabled(true), - mWasMoved(true) -{ - switch (mType) - { - default: - case PORTAL_TYPE_QUAD: - mCorners = OGRE_ALLOC_T(Vector3, 4, MEMCATEGORY_SCENE_CONTROL); - mDerivedCorners = OGRE_ALLOC_T(Vector3, 4, MEMCATEGORY_SCENE_CONTROL); - break; - case PORTAL_TYPE_AABB: - mCorners = OGRE_ALLOC_T(Vector3, 2, MEMCATEGORY_SCENE_CONTROL); - mDerivedCorners = OGRE_ALLOC_T(Vector3, 2, MEMCATEGORY_SCENE_CONTROL); - break; - case PORTAL_TYPE_SPHERE: - mCorners = OGRE_ALLOC_T(Vector3, 2, MEMCATEGORY_SCENE_CONTROL); - mDerivedCorners = OGRE_ALLOC_T(Vector3, 2, MEMCATEGORY_SCENE_CONTROL); - break; - } -} - -PortalBase::~PortalBase() -{ - if (mCorners) - OGRE_FREE(mCorners, MEMCATEGORY_SCENE_CONTROL); - mCorners = 0; - if (mDerivedCorners) - OGRE_FREE(mDerivedCorners, MEMCATEGORY_SCENE_CONTROL); - mDerivedCorners = 0; -} - -const AxisAlignedBox& PortalBase::getWorldBoundingBox(bool derive) const -{ -// if (derive) -// { -// updateDerivedValues(); -// } - - return mPortalAAB; -} - -const Sphere& PortalBase::getWorldBoundingSphere(bool derive) const -{ -// if (derive) -// { -// updateDerivedValues(); -// } - - return mDerivedSphere; -} - -// Set the SceneNode the Portal is associated with -void PortalBase::setNode(SceneNode* sn) -{ - if (mParentNode) ((SceneNode*)mParentNode)->detachObject(this); - if (sn) sn->attachObject(this); -} -// Set the zone this portal is in. -void PortalBase::setCurrentHomeZone(PCZone* zone) -{ - // do this here since more than one function calls setCurrentHomeZone - // also _addPortal is abstract, so easier to do it here. - if(zone) - { - // inform old zone of portal change. - if(mCurrentHomeZone) - { - mCurrentHomeZone->setPortalsUpdated(true); - } - zone->setPortalsUpdated(true); // inform new zone of portal change - } - mCurrentHomeZone = zone; -} - -// Set the zone this portal should be moved to -void PortalBase::setNewHomeZone(PCZone* zone) -{ - mNewHomeZone = zone; -} - -// Set the local coordinates of one of the portal corners -void PortalBase::setCorner(int index, const Vector3& point) -{ - mCorners[index] = point; - mLocalsUpToDate = false; - mDerivedUpToDate = false; -} -/** Set the local coordinates of all of the portal corners -*/ -// NOTE: there are 4 corners if the portal is a quad type -// there are 2 corners if the portal is an AABB type (min corner & max corner) -// there are 2 corners if the portal is a sphere type (center and point on sphere) -void PortalBase::setCorners(const Vector3* corners) -{ - switch (mType) - { - default: - case PORTAL_TYPE_QUAD: - mCorners[0] = corners[0]; - mCorners[1] = corners[1]; - mCorners[2] = corners[2]; - mCorners[3] = corners[3]; - break; - case PORTAL_TYPE_AABB: - mCorners[0] = corners[0]; // minimum corner - mCorners[1] = corners[1]; // maximum corner (opposite from min corner) - break; - case PORTAL_TYPE_SPHERE: - mCorners[0] = corners[0]; // center point - mCorners[1] = corners[1]; // point on sphere surface - break; - } - mLocalsUpToDate = false; - mDerivedUpToDate = false; -} - -// calculate the local direction of the portal from the corners -void PortalBase::calcDirectionAndRadius(void) const -{ - Vector3 radiusVector; - - // for AAB building. - Vector3 min(Math::POS_INFINITY, Math::POS_INFINITY, Math::POS_INFINITY); - Vector3 max(Math::NEG_INFINITY, Math::NEG_INFINITY, Math::NEG_INFINITY); - - switch (mType) - { - default: - case PORTAL_TYPE_QUAD: - mDirection = Math::calculateBasicFaceNormal(mCorners[0], mCorners[1], mCorners[2]); - // calculate local cp - mLocalCP = Vector3::ZERO; - for (int i=0;i<4;i++) - { - mLocalCP += mCorners[i]; - - min.makeFloor(mCorners[i]); - max.makeCeil(mCorners[i]); - } - mLocalCP *= 0.25f; - // then calculate radius - radiusVector = mCorners[0] - mLocalCP; - mRadius = radiusVector.length(); - break; - case PORTAL_TYPE_AABB: - // "direction" is is either pointed inward or outward and is set by user, not calculated. - // calculate local cp - mLocalCP = Vector3::ZERO; - for (int i=0;i<2;i++) - { - mLocalCP += mCorners[i]; - } - mLocalCP *= 0.5f; - // for radius, use distance from corner to center point - // this gives the radius of a sphere that encapsulates the aabb - radiusVector = mCorners[0] - mLocalCP; - mRadius = radiusVector.length(); - - min = mCorners[0]; - max = mCorners[1]; - break; - case PORTAL_TYPE_SPHERE: - // "direction" is is either pointed inward or outward and is set by user, not calculated. - // local CP is same as corner point 0 - mLocalCP = mCorners[0]; - // since corner1 is point on sphere, radius is simply corner1 - center point - radiusVector = mCorners[1] - mLocalCP; - mRadius = radiusVector.length(); - - min = mLocalCP - mRadius; - max = mLocalCP + mRadius; - break; - } - mLocalPortalAAB.setExtents(min, max); - // locals are now up to date - mLocalsUpToDate = true; -} - -// Calculate the local bounding sphere of the portal from the corner points -Real PortalBase::getBoundingRadius( void ) const -{ - if (!mLocalsUpToDate) - { - calcDirectionAndRadius(); - } - return mRadius; -} -// Update (Calculate) the world spatial values -void PortalBase::updateDerivedValues(void) const -{ - // make sure local values are up to date - if (!mLocalsUpToDate) - { - calcDirectionAndRadius(); - } - int numCorners = 4; - if (mType == PORTAL_TYPE_AABB) - numCorners = 2; - else if (mType == PORTAL_TYPE_SPHERE) - numCorners = 2; - - // calculate derived values - if (mParentNode) - { - if(mCurrentHomeZone) - { - // inform home zone that a portal has been updated - mCurrentHomeZone->setPortalsUpdated(true); - } - // save world transform - Affine3 transform = mParentNode->_getFullTransform(); - // save off the current DerivedCP - mPrevDerivedCP = mDerivedCP; - mDerivedCP = transform * mLocalCP; - mDerivedSphere.setCenter(mDerivedCP); - mDerivedRadius = getBoundingRadiusScaled(); - mDerivedSphere.setRadius(mDerivedRadius); - - switch(mType) - { - case PORTAL_TYPE_QUAD: - for (int i=0;i_getWorldAABB(); - //aabb.transform(mParentNode->_getFullTransform()); - mDerivedCorners[0] = aabb.getMinimum(); - mDerivedCorners[1] = aabb.getMaximum(); - mDerivedDirection = mDirection; - } - break; - case PORTAL_TYPE_SPHERE: - { - mDerivedCorners[0] = mDerivedCP; - mDerivedCorners[1] = transform * mCorners[1]; - mDerivedDirection = mDirection; - } - break; - } - if (mPrevWorldTransform != Affine3::ZERO) - { - // save previous calc'd plane - mPrevDerivedPlane = mDerivedPlane; - // calc new plane - mDerivedPlane = Ogre::Plane(mDerivedDirection, mDerivedCP); - // only update prevWorldTransform if did not move - // we need to add this conditional to ensure that - // the portal fully updates when it changes position. - if (mPrevDerivedPlane == mDerivedPlane && - mPrevDerivedCP == mDerivedCP) - { - mPrevWorldTransform = transform; - } - mPrevDerivedCP = mDerivedCP; - } - else - { - // calc new plane - mDerivedPlane = Ogre::Plane(mDerivedDirection, mDerivedCP); - // this is first time, so there is no previous, so prev = current. - mPrevDerivedPlane = mDerivedPlane; - mPrevDerivedCP = mDerivedCP; - mPrevWorldTransform = Affine3::IDENTITY; - mPrevWorldTransform = transform; - } - } - else // no associated node, so just use the local values as derived values - { - if (mPrevWorldTransform != Affine3::ZERO) - { - // save off the current DerivedCP - mPrevDerivedCP = mDerivedCP; - mDerivedCP = mLocalCP; - mDerivedSphere.setCenter(mDerivedCP); - mDerivedRadius = mRadius; - mDerivedSphere.setRadius(mDerivedRadius); - for (int i=0;isetPortalsUpdated(true); - } - // this is the first time the derived CP has been calculated, so there - // is no "previous" value, so set previous = current. - mDerivedCP = mLocalCP; - mPrevDerivedCP = mDerivedCP; - mDerivedSphere.setCenter(mDerivedCP); - mDerivedRadius = mRadius; - mDerivedSphere.setRadius(mDerivedRadius); - for (int i=0;isetPosition(mLocalCP); - - // move the corner points to be relative to the node - int numCorners = 4; - if (mType == PORTAL_TYPE_AABB) - numCorners = 2; - else if (mType == PORTAL_TYPE_SPHERE) - numCorners = 2; - - for (i=0;isetOrientation(q); - } - - // set the node as the portal's associated node - setNode(node); - - return; -} - -// Check if a portal intersects an AABB -// NOTE: This check is not exact. -bool PortalBase::intersects(const AxisAlignedBox& aab) -{ - // Only check if portal is enabled - if (mEnabled) - { - switch(mType) - { - case PORTAL_TYPE_QUAD: - // since ogre doesn't have built in support for a quad, just check - // if the box intersects both the sphere of the portal and the plane - // this can result in false positives, but they will be minimal - if (!aab.intersects(mDerivedSphere)) - { - return false; - } - if (aab.intersects(mDerivedPlane)) - { - return true; - } - break; - case PORTAL_TYPE_AABB: - { - // aab to aab check - AxisAlignedBox aabb; - aabb.setExtents(mDerivedCorners[0], mDerivedCorners[1]); - return (aab.intersects(aabb)); - } - case PORTAL_TYPE_SPHERE: - // aab to sphere check - return (aab.intersects(mDerivedSphere)); - } - } - return false; -} - -// Check if a portal intersects a sphere -// NOTE: This check is not exact. -bool PortalBase::intersects(const Sphere& sphere) -{ - // Only check if portal is enabled - if (mEnabled) - { - switch(mType) - { - case PORTAL_TYPE_QUAD: - // since ogre doesn't have built in support for a quad, just check - // if the sphere intersects both the sphere of the portal and the plane - // this can result in false positives, but they will be minimal - if (!sphere.intersects(mDerivedSphere)) - { - return false; - } - if (sphere.intersects(mDerivedPlane)) - { - return true; - } - break; - case PORTAL_TYPE_AABB: - { - // aab to aab check - AxisAlignedBox aabb; - aabb.setExtents(mDerivedCorners[0], mDerivedCorners[1]); - return (aabb.intersects(sphere)); - } - case PORTAL_TYPE_SPHERE: - return (mDerivedSphere.intersects(sphere)); - } - } - return false; -} - -// Check if a portal intersects a plane bounded volume -// NOTE: This check is not exact. -// NOTE: UNTESTED as of 5/30/07 (EC) -bool PortalBase::intersects(const PlaneBoundedVolume& pbv) -{ - // Only check if portal is enabled - if (mEnabled) - { - switch(mType) - { - case PORTAL_TYPE_QUAD: - { - // first check sphere of the portal - if (!pbv.intersects(mDerivedSphere)) - { - return false; - } - // if the portal corners are all outside one of the planes of the pbv, - // then the portal does not intersect the pbv. (this can result in - // some false positives, but it's the best I can do for now) - PlaneList::const_iterator it = pbv.planes.begin(); - while (it != pbv.planes.end()) - { - const Plane& plane = *it; - // check if all 4 corners of the portal are on negative side of the pbv - bool allOutside = true; - for (int i=0;i<4;i++) - { - if (plane.getSide(mDerivedCorners[i]) != pbv.outside) - { - allOutside = false; - } - } - if (allOutside) - { - return false; - } - it++; - }; - } - break; - case PORTAL_TYPE_AABB: - { - AxisAlignedBox aabb; - aabb.setExtents(mDerivedCorners[0], mDerivedCorners[1]); - if (!pbv.intersects(aabb)) - { - return false; - } - } - break; - case PORTAL_TYPE_SPHERE: - if (!pbv.intersects(mDerivedSphere)) - { - return false; - } - break; - } - } - return false; -} - -// Check if a portal intersects a ray -// NOTE: Kinda using my own invented routine here for quad portals... Better do a lot of testing! -bool PortalBase::intersects(const Ray& ray ) -{ - // Only check if portal is enabled - if (mEnabled) - { - if (mType == PORTAL_TYPE_QUAD) - { - // since ogre doesn't have built in support for a quad, I'm going to first - // find the intersection point (if any) of the ray and the portal plane. Then - // using the intersection point, I take the cross product of each side of the portal - // (0,1,intersect), (1,2, intersect), (2,3, intersect), and (3,0,intersect). If - // all 4 cross products have vectors pointing in the same direction, then the - // intersection point is within the portal, otherwise it is outside. - - std::pair result = ray.intersects(mDerivedPlane); - - if (result.first == true) - { - // the ray intersects the plane, now walk around the edges - Vector3 isect = ray.getPoint(result.second); - Vector3 cross, vect1, vect2; - Vector3 cross2, vect3, vect4; - vect1 = mDerivedCorners[1] - mDerivedCorners[0]; - vect2 = isect - mDerivedCorners[0]; - cross = vect1.crossProduct(vect2); - vect3 = mDerivedCorners[2] - mDerivedCorners[1]; - vect4 = isect - mDerivedCorners[1]; - cross2 = vect3.crossProduct(vect4); - if (cross.dotProduct(cross2) < 0) - { - return false; - } - vect1 = mDerivedCorners[3] - mDerivedCorners[2]; - vect2 = isect - mDerivedCorners[2]; - cross = vect1.crossProduct(vect2); - if (cross.dotProduct(cross2) < 0) - { - return false; - } - vect1 = mDerivedCorners[0] - mDerivedCorners[3]; - vect2 = isect - mDerivedCorners[3]; - cross = vect1.crossProduct(vect2); - if (cross.dotProduct(cross2) < 0) - { - return false; - } - // all cross products pointing same way, so intersect - // must be on the inside of the portal! - return true; - } - - return false; - } - else if (mType == PORTAL_TYPE_AABB) - { - AxisAlignedBox aabb; - aabb.setExtents(mDerivedCorners[0], mDerivedCorners[1]); - std::pair result = ray.intersects(aabb); - return result.first; - } - else // sphere - { - std::pair result = ray.intersects(mDerivedSphere); - return result.first; - } - } - return false; -} - - - -/* Test if a scene node intersected a portal during the last time delta - * (from last frame time to current frame time). This function checks - * if the node "crossed over" the portal also. -*/ -PortalBase::PortalIntersectResult PortalBase::intersects(PCZSceneNode* pczsn) -{ - // Only check if portal is enabled - if (mEnabled) - { - if (pczsn == mParentNode) - { - // ignore the scene node if it is the node the portal is associated with - return PortalBase::NO_INTERSECT; - } - // most complicated case - if the portal is a quad: - if (mType == PORTAL_TYPE_QUAD) - { - // the node is modelled as a line segment (prevPostion to currentPosition) - // intersection test is then between the capsule and the line segment. - Segment nodeSegment; - nodeSegment.set(pczsn->getPrevPosition(), pczsn->_getDerivedPosition()); - - // we model the portal as a line swept sphere (mPrevDerivedCP to mDerivedCP). - if (getCapsule().intersects(nodeSegment)) - { - // the portal intersected the node at some time from last frame to this frame. - // Now check if node "crossed" the portal - // a crossing occurs if the "side" of the final position of the node compared - // to the final position of the portal is negative AND the initial position - // of the node compared to the initial position of the portal is non-negative - if (mDerivedPlane.getSide(pczsn->_getDerivedPosition()) == Plane::NEGATIVE_SIDE && - mPrevDerivedPlane.getSide(pczsn->getPrevPosition()) != Plane::NEGATIVE_SIDE) - { - // safety check - make sure the node has at least one dimension which is - // small enough to fit through the portal! (avoid the "elephant fitting - // through a mouse hole" case) - Vector3 nodeHalfVector = pczsn->_getWorldAABB().getHalfSize(); - Vector3 portalBox = Vector3(mDerivedRadius, mDerivedRadius, mDerivedRadius); - portalBox.makeFloor(nodeHalfVector); - if (portalBox.x < mDerivedRadius) - { - // crossing occurred! - return PortalBase::INTERSECT_CROSS; - } - } - } - // there was no crossing of the portal by the node, but it might be touching - // the portal. We check for this by checking the bounding box of the node vs. - // the sphere of the portal - if (mDerivedSphere.intersects(pczsn->_getWorldAABB()) && - mDerivedPlane.getSide(pczsn->_getWorldAABB()) == Plane::BOTH_SIDE ) - { - // intersection but no crossing - // note this means that the node is CURRENTLY touching the portal. - if (mDerivedPlane.getSide(pczsn->_getDerivedPosition()) != Plane::NEGATIVE_SIDE) - { - // the node is on the positive (front) or exactly on the CP of the portal - return PortalBase::INTERSECT_NO_CROSS; - } - else - { - // the node is on the negative (back) side of the portal - it might be in the wrong zone! - return PortalBase::INTERSECT_BACK_NO_CROSS; - } - } - // no intersection CURRENTLY. (there might have been an intersection - // during the time between last frame and this frame, but it wasn't a portal - // crossing, and it isn't touching anymore, so it doesn't matter. - return PortalBase::NO_INTERSECT; - } - else if (mType == PORTAL_TYPE_AABB) - { - // for aabb's we check if the center point went from being inside to being outside - // the aabb (or vice versa) for crossing. - AxisAlignedBox aabb; - aabb.setExtents(mDerivedCorners[0], mDerivedCorners[1]); - //bool previousInside = aabb.contains(pczsn->getPrevPosition()); - bool currentInside = aabb.contains(pczsn->_getDerivedPosition()); - if (mDirection == Vector3::UNIT_Z) - { - // portal norm is "outward" pointing, look for going from outside to inside - //if (previousInside == false && - if (currentInside == true) - { - return PortalBase::INTERSECT_CROSS; - } - } - else - { - // portal norm is "inward" pointing, look for going from inside to outside - //if (previousInside == true && - if (currentInside == false) - { - return PortalBase::INTERSECT_CROSS; - } - } - // doesn't cross, but might be touching. This is a little tricky because we only - // care if the node aab is NOT fully contained in the portal aabb because we consider - // the surface of the portal aabb the actual 'portal'. First, check to see if the - // aab of the node intersects the aabb portal - if (aabb.intersects(pczsn->_getWorldAABB())) - { - // now check if the intersection between the two is not the same as the - // full node aabb, if so, then this means that the node is not fully "contained" - // which is what we are looking for. - AxisAlignedBox overlap = aabb.intersection(pczsn->_getWorldAABB()); - if (overlap != pczsn->_getWorldAABB()) - { - return PortalBase::INTERSECT_NO_CROSS; - } - } - return PortalBase::NO_INTERSECT; - } - else - { - // for spheres we check if the center point went from being inside to being outside - // the sphere surface (or vice versa) for crossing. - //Real previousDistance2 = mPrevDerivedCP.squaredDistance(pczsn->getPrevPosition()); - Real currentDistance2 = mDerivedCP.squaredDistance(pczsn->_getDerivedPosition()); - Real mDerivedRadius2 = mDerivedRadius * mDerivedRadius; - if (mDirection == Vector3::UNIT_Z) - { - // portal norm is "outward" pointing, look for going from outside to inside - //if (previousDistance2 >= mDerivedRadius2 && - if (currentDistance2 < mDerivedRadius2) - { - return PortalBase::INTERSECT_CROSS; - } - } - else - { - // portal norm is "inward" pointing, look for going from inside to outside - //if (previousDistance2 < mDerivedRadius2 && - if (currentDistance2 >= mDerivedRadius2) - { - return PortalBase::INTERSECT_CROSS; - } - } - // no crossing, but might be touching - check distance - if (Math::Sqrt(Math::Abs(mDerivedRadius2 - currentDistance2)) <= mDerivedRadius) - { - return PortalBase::INTERSECT_NO_CROSS; - } - return PortalBase::NO_INTERSECT; - } - } - return PortalBase::NO_INTERSECT; -} - -/** check if portal crossed over portal */ -bool PortalBase::crossedPortal(const PortalBase* otherPortal) -{ - // Only check if portal is open and is not an antiportal - if (otherPortal->getEnabled()) - { - // we model both portals as line swept spheres (mPrevDerivedCP to mDerivedCP). - // intersection test is then between the capsules. - // BUGBUG! This routine needs to check for case where one or both objects - // don't move - resulting in simple sphere tests - // BUGBUG! If one (or both) portals are aabb's this is REALLY not accurate. - const Capsule& otherPortalCapsule(otherPortal->getCapsule()); - if (getCapsule().intersects(otherPortalCapsule)) - { - // the portal intersected the other portal at some time from last frame to this frame. - // Now check if this portal "crossed" the other portal - switch (otherPortal->getType()) - { - case PORTAL_TYPE_QUAD: - // a crossing occurs if the "side" of the final position of this portal compared - // to the final position of the other portal is negative AND the initial position - // of this portal compared to the initial position of the other portal is non-negative - // NOTE: This function assumes that this portal is the smaller portal potentially crossing - // over the otherPortal which is larger. - if (otherPortal->getDerivedPlane().getSide(mDerivedCP) == Plane::NEGATIVE_SIDE && - otherPortal->getPrevDerivedPlane().getSide(mPrevDerivedCP) != Plane::NEGATIVE_SIDE) - { - // crossing occurred! - return true; - } - break; - case PORTAL_TYPE_AABB: - { - // for aabb's we check if the center point went from being inside to being outside - // the aabb (or vice versa) for crossing. - AxisAlignedBox aabb; - aabb.setExtents(otherPortal->getDerivedCorner(0), otherPortal->getDerivedCorner(1)); - //bool previousInside = aabb.contains(mPrevDerivedCP); - bool currentInside = aabb.contains(mDerivedCP); - if (otherPortal->getDerivedDirection() == Vector3::UNIT_Z) - { - // portal norm is "outward" pointing, look for going from outside to inside - //if (previousInside == false && - if (currentInside == true) - { - return true; - } - } - else - { - // portal norm is "inward" pointing, look for going from inside to outside - //if (previousInside == true && - if (currentInside == false) - { - return true; - } - } - } - break; - case PORTAL_TYPE_SPHERE: - { - // for spheres we check if the center point went from being inside to being outside - // the sphere surface (or vice versa) for crossing. - //Real previousDistance2 = mPrevDerivedCP.squaredDistance(otherPortal->getPrevDerivedCP()); - Real currentDistance2 = mDerivedCP.squaredDistance(otherPortal->getDerivedCP()); - Real mDerivedRadius2 = Math::Sqr(otherPortal->getDerivedRadius()); - if (otherPortal->getDerivedDirection() == Vector3::UNIT_Z) - { - // portal norm is "outward" pointing, look for going from outside to inside - //if (previousDistance2 >= mDerivedRadius2 && - if (currentDistance2 < mDerivedRadius2) - { - return true; - } - } - else - { - // portal norm is "inward" pointing, look for going from inside to outside - //if (previousDistance2 < mDerivedRadius2 && - if (currentDistance2 >= mDerivedRadius2) - { - return true; - } - } - } - break; - } - } - } - // there was no crossing of the portal by this portal. It might be touching - // the other portal (but we don't care currently) or the other - // portal might be an antiportal (crossing not possible) or the - // other portal might be closed. - return false; -} - -/** check if portal touches another portal */ -bool PortalBase::closeTo(const PortalBase* otherPortal) -{ - // only portals of the same type can be "close to" each other. - if (mType != otherPortal->getType()) - { - return false; - } - bool close = false; - switch(mType) - { - default: - case PORTAL_TYPE_QUAD: - { - // quad portals must be within 1/4 sphere of each other - Sphere quarterSphere1 = mDerivedSphere; - quarterSphere1.setRadius(quarterSphere1.getRadius()*0.25f); - Sphere quarterSphere2 = otherPortal->getDerivedSphere(); - quarterSphere2.setRadius(quarterSphere2.getRadius()*0.25f); - close = quarterSphere1.intersects(quarterSphere2); - } - break; - case PORTAL_TYPE_AABB: - // NOTE: AABB's must match perfectly - if (mDerivedCP == otherPortal->getDerivedCP() && - mCorners[0] == otherPortal->getCorner(0) && - mCorners[1] == otherPortal->getCorner(1)) - { - close = true; - } - break; - case PORTAL_TYPE_SPHERE: - // NOTE: Spheres must match perfectly - if (mDerivedCP == otherPortal->getDerivedCP() && - mDerivedRadius == otherPortal->getDerivedRadius()) - { - close = true; - } - break; - } - return close; -} - - -/** @copydoc MovableObject::getBoundingBox. */ -const AxisAlignedBox& PortalBase::getBoundingBox() const -{ - if (!mLocalsUpToDate) - { - calcDirectionAndRadius(); - } - return mLocalPortalAAB; -} - -bool PortalBase::needUpdate() -{ - PCZSceneNode* pczNode = (PCZSceneNode*)mParentNode; - return (!mLocalsUpToDate || (pczNode && pczNode->isMoved())); -} - -/** Returns an updated capsule of the portal for intersection test. */ -const Capsule& PortalBase::getCapsule() const -{ - PCZSceneNode* pczNode = (PCZSceneNode*)mParentNode; - bool justStoppedMoving = mWasMoved && (pczNode && !pczNode->isMoved()); - if (!mDerivedUpToDate || justStoppedMoving) - { - updateDerivedValues(); - mWasMoved = false; - } - return mPortalCapsule; -} - -/** Returns an updated AAB of the portal for intersection test. */ -const AxisAlignedBox& PortalBase::getAAB() -{ - PCZSceneNode* pczNode = (PCZSceneNode*)mParentNode; - bool justStoppedMoving = mWasMoved && (pczNode && !pczNode->isMoved()); - if (!mDerivedUpToDate || justStoppedMoving) - { - updateDerivedValues(); - mWasMoved = false; - } - - return mPortalAAB; -} - -/** get the portal type from name value pair. */ -PortalBase::PORTAL_TYPE PortalBaseFactory::getPortalType(const NameValuePairList* params) -{ - if (params) - { - NameValuePairList::const_iterator ni = params->find("type"); - if (ni != params->end()) - { - if (ni->second == "Quad") return PortalBase::PORTAL_TYPE_QUAD; - else if (ni->second == "AABB") return PortalBase::PORTAL_TYPE_AABB; - else if (ni->second == "Sphere") return PortalBase::PORTAL_TYPE_SPHERE; - } - } - - return PortalBase::PORTAL_TYPE_QUAD; -} diff --git a/PlugIns/PCZSceneManager/src/OgreSegment.cpp b/PlugIns/PCZSceneManager/src/OgreSegment.cpp deleted file mode 100644 index f0eca5b605c..00000000000 --- a/PlugIns/PCZSceneManager/src/OgreSegment.cpp +++ /dev/null @@ -1,414 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -OgreSegment.cpp - 3D Line Segment class for intersection testing in Ogre3D -Some algorithms based off code from the Wild Magic library by Dave Eberly ------------------------------------------------------------------------------ -begin : Mon Apr 02 2007 -author : Eric Cha -email : ericc@xenopi.com -Code Style Update : ------------------------------------------------------------------------------ -*/ - -#include "OgreSegment.h" -#include "OgreCapsule.h" - -using namespace Ogre; - -const Real PARALLEL_TOLERANCE = 0.0001; - -//---------------------------------------------------------------------------- -Segment::Segment () -{ - // uninitialized -} -//---------------------------------------------------------------------------- -Segment::Segment (const Vector3& origin, - const Vector3& direction, - Real extent) - : - mOrigin(origin), - mDirection(direction), - mExtent(extent) -{ -} -//---------------------------------------------------------------------------- -void Segment::set(const Vector3& newOrigin, const Vector3& newEnd) -{ - mOrigin = newOrigin; - // calc the direction vector - mDirection = newEnd - mOrigin; - mExtent = mDirection.normalise(); -} -//---------------------------------------------------------------------------- -void Segment::setOrigin(const Vector3& newOrigin) -{ - mOrigin = newOrigin; -} -//---------------------------------------------------------------------------- -void Segment::setEndPoint(const Vector3& newEnd) -{ - // calc the direction vector - mDirection = newEnd - mOrigin; - mExtent = mDirection.normalise(); -} -//---------------------------------------------------------------------------- -Real Segment::distance(const Segment& otherSegment) const -{ - Real fSqrDist = squaredDistance(otherSegment); - return Ogre::Math::Sqrt(fSqrDist); -} -//---------------------------------------------------------------------------- -Real Segment::squaredDistance(const Segment& otherSegment) const -{ - Vector3 kDiff = mOrigin - otherSegment.mOrigin; - Real fA01 = -mDirection.dotProduct(otherSegment.mDirection); - Real fB0 = kDiff.dotProduct(mDirection); - Real fB1 = -kDiff.dotProduct(otherSegment.mDirection); - Real fC = kDiff.squaredLength(); - Real fDet = Math::Abs((Real)1.0 - fA01*fA01); - Real fS0, fS1, fSqrDist, fExtDet0, fExtDet1, fTmpS0, fTmpS1; - - if (fDet >= PARALLEL_TOLERANCE) - { - // segments are not parallel - fS0 = fA01*fB1-fB0; - fS1 = fA01*fB0-fB1; - fExtDet0 = mExtent*fDet; - fExtDet1 = otherSegment.mExtent*fDet; - - if (fS0 >= -fExtDet0) - { - if (fS0 <= fExtDet0) - { - if (fS1 >= -fExtDet1) - { - if (fS1 <= fExtDet1) // region 0 (interior) - { - // minimum at two interior points of 3D lines - Real fInvDet = ((Real)1.0)/fDet; - fS0 *= fInvDet; - fS1 *= fInvDet; - fSqrDist = fS0*(fS0+fA01*fS1+((Real)2.0)*fB0) + - fS1*(fA01*fS0+fS1+((Real)2.0)*fB1)+fC; - } - else // region 3 (side) - { - fS1 = otherSegment.mExtent; - fTmpS0 = -(fA01*fS1+fB0); - if (fTmpS0 < -mExtent) - { - fS0 = -mExtent; - fSqrDist = fS0*(fS0-((Real)2.0)*fTmpS0) + - fS1*(fS1+((Real)2.0)*fB1)+fC; - } - else if (fTmpS0 <= mExtent) - { - fS0 = fTmpS0; - fSqrDist = -fS0*fS0+fS1*(fS1+((Real)2.0)*fB1)+fC; - } - else - { - fS0 = mExtent; - fSqrDist = fS0*(fS0-((Real)2.0)*fTmpS0) + - fS1*(fS1+((Real)2.0)*fB1)+fC; - } - } - } - else // region 7 (side) - { - fS1 = -otherSegment.mExtent; - fTmpS0 = -(fA01*fS1+fB0); - if (fTmpS0 < -mExtent) - { - fS0 = -mExtent; - fSqrDist = fS0*(fS0-((Real)2.0)*fTmpS0) + - fS1*(fS1+((Real)2.0)*fB1)+fC; - } - else if (fTmpS0 <= mExtent) - { - fS0 = fTmpS0; - fSqrDist = -fS0*fS0+fS1*(fS1+((Real)2.0)*fB1)+fC; - } - else - { - fS0 = mExtent; - fSqrDist = fS0*(fS0-((Real)2.0)*fTmpS0) + - fS1*(fS1+((Real)2.0)*fB1)+fC; - } - } - } - else - { - if (fS1 >= -fExtDet1) - { - if (fS1 <= fExtDet1) // region 1 (side) - { - fS0 = mExtent; - fTmpS1 = -(fA01*fS0+fB1); - if (fTmpS1 < -otherSegment.mExtent) - { - fS1 = -otherSegment.mExtent; - fSqrDist = fS1*(fS1-((Real)2.0)*fTmpS1) + - fS0*(fS0+((Real)2.0)*fB0)+fC; - } - else if (fTmpS1 <= otherSegment.mExtent) - { - fS1 = fTmpS1; - fSqrDist = -fS1*fS1+fS0*(fS0+((Real)2.0)*fB0)+fC; - } - else - { - fS1 = otherSegment.mExtent; - fSqrDist = fS1*(fS1-((Real)2.0)*fTmpS1) + - fS0*(fS0+((Real)2.0)*fB0)+fC; - } - } - else // region 2 (corner) - { - fS1 = otherSegment.mExtent; - fTmpS0 = -(fA01*fS1+fB0); - if (fTmpS0 < -mExtent) - { - fS0 = -mExtent; - fSqrDist = fS0*(fS0-((Real)2.0)*fTmpS0) + - fS1*(fS1+((Real)2.0)*fB1)+fC; - } - else if (fTmpS0 <= mExtent) - { - fS0 = fTmpS0; - fSqrDist = -fS0*fS0+fS1*(fS1+((Real)2.0)*fB1)+fC; - } - else - { - fS0 = mExtent; - fTmpS1 = -(fA01*fS0+fB1); - if (fTmpS1 < -otherSegment.mExtent) - { - fS1 = -otherSegment.mExtent; - fSqrDist = fS1*(fS1-((Real)2.0)*fTmpS1) + - fS0*(fS0+((Real)2.0)*fB0)+fC; - } - else if (fTmpS1 <= otherSegment.mExtent) - { - fS1 = fTmpS1; - fSqrDist = -fS1*fS1+fS0*(fS0+((Real)2.0)*fB0) - + fC; - } - else - { - fS1 = otherSegment.mExtent; - fSqrDist = fS1*(fS1-((Real)2.0)*fTmpS1) + - fS0*(fS0+((Real)2.0)*fB0)+fC; - } - } - } - } - else // region 8 (corner) - { - fS1 = -otherSegment.mExtent; - fTmpS0 = -(fA01*fS1+fB0); - if (fTmpS0 < -mExtent) - { - fS0 = -mExtent; - fSqrDist = fS0*(fS0-((Real)2.0)*fTmpS0) + - fS1*(fS1+((Real)2.0)*fB1)+fC; - } - else if (fTmpS0 <= mExtent) - { - fS0 = fTmpS0; - fSqrDist = -fS0*fS0+fS1*(fS1+((Real)2.0)*fB1)+fC; - } - else - { - fS0 = mExtent; - fTmpS1 = -(fA01*fS0+fB1); - if (fTmpS1 > otherSegment.mExtent) - { - fS1 = otherSegment.mExtent; - fSqrDist = fS1*(fS1-((Real)2.0)*fTmpS1) + - fS0*(fS0+((Real)2.0)*fB0)+fC; - } - else if (fTmpS1 >= -otherSegment.mExtent) - { - fS1 = fTmpS1; - fSqrDist = -fS1*fS1+fS0*(fS0+((Real)2.0)*fB0) - + fC; - } - else - { - fS1 = -otherSegment.mExtent; - fSqrDist = fS1*(fS1-((Real)2.0)*fTmpS1) + - fS0*(fS0+((Real)2.0)*fB0)+fC; - } - } - } - } - } - else - { - if (fS1 >= -fExtDet1) - { - if (fS1 <= fExtDet1) // region 5 (side) - { - fS0 = -mExtent; - fTmpS1 = -(fA01*fS0+fB1); - if (fTmpS1 < -otherSegment.mExtent) - { - fS1 = -otherSegment.mExtent; - fSqrDist = fS1*(fS1-((Real)2.0)*fTmpS1) + - fS0*(fS0+((Real)2.0)*fB0)+fC; - } - else if (fTmpS1 <= otherSegment.mExtent) - { - fS1 = fTmpS1; - fSqrDist = -fS1*fS1+fS0*(fS0+((Real)2.0)*fB0)+fC; - } - else - { - fS1 = otherSegment.mExtent; - fSqrDist = fS1*(fS1-((Real)2.0)*fTmpS1) + - fS0*(fS0+((Real)2.0)*fB0)+fC; - } - } - else // region 4 (corner) - { - fS1 = otherSegment.mExtent; - fTmpS0 = -(fA01*fS1+fB0); - if (fTmpS0 > mExtent) - { - fS0 = mExtent; - fSqrDist = fS0*(fS0-((Real)2.0)*fTmpS0) + - fS1*(fS1+((Real)2.0)*fB1)+fC; - } - else if (fTmpS0 >= -mExtent) - { - fS0 = fTmpS0; - fSqrDist = -fS0*fS0+fS1*(fS1+((Real)2.0)*fB1)+fC; - } - else - { - fS0 = -mExtent; - fTmpS1 = -(fA01*fS0+fB1); - if (fTmpS1 < -otherSegment.mExtent) - { - fS1 = -otherSegment.mExtent; - fSqrDist = fS1*(fS1-((Real)2.0)*fTmpS1) + - fS0*(fS0+((Real)2.0)*fB0)+fC; - } - else if (fTmpS1 <= otherSegment.mExtent) - { - fS1 = fTmpS1; - fSqrDist = -fS1*fS1+fS0*(fS0+((Real)2.0)*fB0) - + fC; - } - else - { - fS1 = otherSegment.mExtent; - fSqrDist = fS1*(fS1-((Real)2.0)*fTmpS1) + - fS0*(fS0+((Real)2.0)*fB0)+fC; - } - } - } - } - else // region 6 (corner) - { - fS1 = -otherSegment.mExtent; - fTmpS0 = -(fA01*fS1+fB0); - if (fTmpS0 > mExtent) - { - fS0 = mExtent; - fSqrDist = fS0*(fS0-((Real)2.0)*fTmpS0) + - fS1*(fS1+((Real)2.0)*fB1)+fC; - } - else if (fTmpS0 >= -mExtent) - { - fS0 = fTmpS0; - fSqrDist = -fS0*fS0+fS1*(fS1+((Real)2.0)*fB1)+fC; - } - else - { - fS0 = -mExtent; - fTmpS1 = -(fA01*fS0+fB1); - if (fTmpS1 < -otherSegment.mExtent) - { - fS1 = -otherSegment.mExtent; - fSqrDist = fS1*(fS1-((Real)2.0)*fTmpS1) + - fS0*(fS0+((Real)2.0)*fB0)+fC; - } - else if (fTmpS1 <= otherSegment.mExtent) - { - fS1 = fTmpS1; - fSqrDist = -fS1*fS1+fS0*(fS0+((Real)2.0)*fB0) - + fC; - } - else - { - fS1 = otherSegment.mExtent; - fSqrDist = fS1*(fS1-((Real)2.0)*fTmpS1) + - fS0*(fS0+((Real)2.0)*fB0)+fC; - } - } - } - } - } - else - { - // The segments are parallel. The average b0 term is designed to - // ensure symmetry of the function. That is, dist(seg0,seg1) and - // dist(seg1,seg0) should produce the same number. - Real fE0pE1 = mExtent + otherSegment.mExtent; - Real fSign = (fA01 > (Real)0.0 ? (Real)-1.0 : (Real)1.0); - Real fB0Avr = ((Real)0.5)*(fB0 - fSign*fB1); - Real fLambda = -fB0Avr; - if (fLambda < -fE0pE1) - { - fLambda = -fE0pE1; - } - else if (fLambda > fE0pE1) - { - fLambda = fE0pE1; - } - -// fS1 = -fSign*fLambda*otherSegment.mExtent/fE0pE1; -// fS0 = fLambda + fSign*fS1; - fSqrDist = fLambda*(fLambda + ((Real)2.0)*fB0Avr) + fC; - } - // we don't need the following stuff - it's for calculating closest point -// mClosestPoint0 = mOrigin + fS0*mDirection; -// mClosestPoint1 = otherSegment.mOrigin + fS1*otherSegment.mDirection; -// mSegment0Parameter = fS0; -// mSegment1Parameter = fS1; - return Math::Abs(fSqrDist); -} - -//---------------------------------------------------------------------------- -bool Segment::intersects(const Capsule &capsule) const -{ - Real fDist = distance(capsule.mSegment); - return fDist <= capsule.mRadius; -} diff --git a/PlugIns/ParticleFX/CMakeLists.txt b/PlugIns/ParticleFX/CMakeLists.txt deleted file mode 100644 index 808effa28c1..00000000000 --- a/PlugIns/ParticleFX/CMakeLists.txt +++ /dev/null @@ -1,30 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure BSP SceneManager build - -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES ${PROJECT_BINARY_DIR}/include/OgreParticleFXPrerequisites.h) -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") - -add_library(Plugin_ParticleFX ${OGRE_LIB_TYPE} ${HEADER_FILES} ${SOURCE_FILES}) -target_link_libraries(Plugin_ParticleFX OgreMain) - -target_include_directories(Plugin_ParticleFX PUBLIC - "$" - $) - -generate_export_header(Plugin_ParticleFX - EXPORT_MACRO_NAME _OgreParticleFXExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreParticleFXPrerequisites.h) - -ogre_config_framework(Plugin_ParticleFX) - -ogre_config_plugin(Plugin_ParticleFX) -install(FILES ${HEADER_FILES} DESTINATION include/OGRE/Plugins/ParticleFX) diff --git a/PlugIns/ParticleFX/include/OgreAreaEmitter.h b/PlugIns/ParticleFX/include/OgreAreaEmitter.h deleted file mode 100644 index 8946f33951e..00000000000 --- a/PlugIns/ParticleFX/include/OgreAreaEmitter.h +++ /dev/null @@ -1,144 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __AreaEmitter_H__ -#define __AreaEmitter_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleEmitter.h" - -namespace Ogre { - - /** \addtogroup Plugins Plugins - * @{ - */ - /** \defgroup ParticleFX ParticleFX - * Provides Emmiter and Affector implementations for ParticleSystem - * @{ - */ - - /** Particle emitter which emits particles randomly from points inside - an area (box, sphere, ellipsoid whatever subclasses choose to be). - - This is an empty superclass and needs to be subclassed. Basic particle - emitter emits particles from/in an (unspecified) area. The - initial direction of these particles can either be a single direction - (i.e. a line), a random scattering inside a cone, or a random - scattering in all directions, depending the 'angle' parameter, which - is the angle across which to scatter the particles either side of the - base direction of the emitter. - */ - class AreaEmitter : public ParticleEmitter - { - public: - /** Command object for area emitter size (see ParamCommand).*/ - class CmdWidth : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for area emitter size (see ParamCommand).*/ - class CmdHeight : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for area emitter size (see ParamCommand).*/ - class CmdDepth : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - - AreaEmitter(ParticleSystem* psys) : ParticleEmitter(psys) {} - - /** Overloaded to update the trans. matrix */ - void setDirection( const Vector3& direction ) override; - - /** Sets the size of the area from which particles are emitted. - @param - size Vector describing the size of the area. The area extends - around the center point by half the x, y and z components of - this vector. The box is aligned such that it's local Z axis points - along it's direction (see setDirection) - */ - void setSize(const Vector3& size); - - /** Sets the size of the area from which particles are emitted. - @param x,y,z - Individual axis lengths describing the size of the area. The area - extends around the center point by half the x, y and z components - of this vector. The box is aligned such that it's local Z axis - points along it's direction (see setDirection) - */ - void setSize(Real x, Real y, Real z); - - /** Sets the width (local x size) of the emitter. */ - void setWidth(Real width); - /** Gets the width (local x size) of the emitter. */ - Real getWidth(void) const; - /** Sets the height (local y size) of the emitter. */ - void setHeight(Real Height); - /** Gets the height (local y size) of the emitter. */ - Real getHeight(void) const; - /** Sets the depth (local y size) of the emitter. */ - void setDepth(Real Depth); - /** Gets the depth (local y size) of the emitter. */ - Real getDepth(void) const; - - protected: - /// Size of the area - Vector3 mSize; - - /// Local axes, not normalised, their magnitude reflects area size - Vector3 mXRange, mYRange, mZRange; - - /// Internal method for generating the area axes - void genAreaAxes(void); - /** Internal for initializing some defaults and parameters - @return True if custom parameters need initialising - */ - bool initDefaults(const String& mType); - - /// Command objects - static CmdWidth msWidthCmd; - static CmdHeight msHeightCmd; - static CmdDepth msDepthCmd; - - - - }; - /** @} */ - /** @} */ -} - -#endif - diff --git a/PlugIns/ParticleFX/include/OgreBoxEmitter.h b/PlugIns/ParticleFX/include/OgreBoxEmitter.h deleted file mode 100644 index a907a4bcd8e..00000000000 --- a/PlugIns/ParticleFX/include/OgreBoxEmitter.h +++ /dev/null @@ -1,60 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __BoxEmitter_H__ -#define __BoxEmitter_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreAreaEmitter.h" - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup ParticleFX - * @{ - */ - - /** This emitter emits particles from a random location within a 3-dimensional box. - */ - class BoxEmitter : public AreaEmitter - { - public: - - BoxEmitter(ParticleSystem* psys); - - void _initParticle(Particle* pParticle) override; - - protected: - - }; - /** @} */ - /** @} */ -} - -#endif - diff --git a/PlugIns/ParticleFX/include/OgreColourFaderAffector.h b/PlugIns/ParticleFX/include/OgreColourFaderAffector.h deleted file mode 100644 index 396dde3bbb0..00000000000 --- a/PlugIns/ParticleFX/include/OgreColourFaderAffector.h +++ /dev/null @@ -1,152 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ColourFaderAffector_H__ -#define __ColourFaderAffector_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffector.h" -#include "OgreStringInterface.h" - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup ParticleFX - * @{ - */ - - /** This affector modifies the colour of particles in flight. - */ - class ColourFaderAffector : public ParticleAffector - { - public: - - /** Command object for red adjust (see ParamCommand).*/ - class CmdRedAdjust : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Command object for green adjust (see ParamCommand).*/ - class CmdGreenAdjust : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Command object for blue adjust (see ParamCommand).*/ - class CmdBlueAdjust : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Command object for alpha adjust (see ParamCommand).*/ - class CmdAlphaAdjust : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - - /** Default constructor. */ - ColourFaderAffector(ParticleSystem* psys); - - void _affectParticles(ParticleSystem* pSystem, Real timeElapsed) override; - - /** Sets the colour adjustment to be made per second to particles. - @param red, green, blue, alpha - Sets the adjustment to be made to each of the colour components per second. These - values will be added to the colour of all particles every second, scaled over each frame - for a smooth adjustment. - */ - void setAdjust(float red, float green, float blue, float alpha = 0.0); - /** Sets the red adjustment to be made per second to particles. - @param red - The adjustment to be made to the colour component per second. This - value will be added to the colour of all particles every second, scaled over each frame - for a smooth adjustment. - */ - void setRedAdjust(float red); - - /** Gets the red adjustment to be made per second to particles. */ - float getRedAdjust(void) const; - - /** Sets the green adjustment to be made per second to particles. - @param green - The adjustment to be made to the colour component per second. This - value will be added to the colour of all particles every second, scaled over each frame - for a smooth adjustment. - */ - void setGreenAdjust(float green); - /** Gets the green adjustment to be made per second to particles. */ - float getGreenAdjust(void) const; - /** Sets the blue adjustment to be made per second to particles. - @param blue - The adjustment to be made to the colour component per second. This - value will be added to the colour of all particles every second, scaled over each frame - for a smooth adjustment. - */ - void setBlueAdjust(float blue); - /** Gets the blue adjustment to be made per second to particles. */ - float getBlueAdjust(void) const; - - /** Sets the alpha adjustment to be made per second to particles. - @param alpha - The adjustment to be made to the colour component per second. This - value will be added to the colour of all particles every second, scaled over each frame - for a smooth adjustment. - */ - void setAlphaAdjust(float alpha); - /** Gets the alpha adjustment to be made per second to particles. */ - float getAlphaAdjust(void) const; - - static CmdRedAdjust msRedCmd; - static CmdGreenAdjust msGreenCmd; - static CmdBlueAdjust msBlueCmd; - static CmdAlphaAdjust msAlphaCmd; - - protected: - float mRedAdj; - float mGreenAdj; - float mBlueAdj; - float mAlphaAdj; - }; - - /** @} */ - /** @} */ -} - - -#endif - diff --git a/PlugIns/ParticleFX/include/OgreColourFaderAffector2.h b/PlugIns/ParticleFX/include/OgreColourFaderAffector2.h deleted file mode 100644 index 7971a27765e..00000000000 --- a/PlugIns/ParticleFX/include/OgreColourFaderAffector2.h +++ /dev/null @@ -1,209 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ColourFaderAffector2_H__ -#define __ColourFaderAffector2_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffector.h" -#include "OgreStringInterface.h" - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup ParticleFX - * @{ - */ - - class ColourFaderAffector2 : public ParticleAffector - { - public: - - /** Command object for red adjust (see ParamCommand).*/ - class CmdRedAdjust1 : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Command object for green adjust (see ParamCommand).*/ - class CmdGreenAdjust1 : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Command object for blue adjust (see ParamCommand).*/ - class CmdBlueAdjust1 : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Command object for alpha adjust (see ParamCommand).*/ - class CmdAlphaAdjust1 : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Command object for red adjust (see ParamCommand).*/ - class CmdRedAdjust2 : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Command object for green adjust (see ParamCommand).*/ - class CmdGreenAdjust2 : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Command object for blue adjust (see ParamCommand).*/ - class CmdBlueAdjust2 : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Command object for alpha adjust (see ParamCommand).*/ - class CmdAlphaAdjust2 : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Command object for alpha adjust (see ParamCommand).*/ - class CmdStateChange : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - - /** Default constructor. */ - ColourFaderAffector2(ParticleSystem* psys); - - void _affectParticles(ParticleSystem* pSystem, Real timeElapsed) override; - - /** Sets the colour adjustment to be made per second to particles. - @param red, green, blue, alpha - Sets the adjustment to be made to each of the colour components per second. These - values will be added to the colour of all particles every second, scaled over each frame - for a smooth adjustment. - */ - void setAdjust1(float red, float green, float blue, float alpha = 0.0); - void setAdjust2(float red, float green, float blue, float alpha = 0.0); - /** Sets the red adjustment to be made per second to particles. - @param red - The adjustment to be made to the colour component per second. This - value will be added to the colour of all particles every second, scaled over each frame - for a smooth adjustment. - */ - void setRedAdjust1(float red); - void setRedAdjust2(float red); - - /** Gets the red adjustment to be made per second to particles. */ - float getRedAdjust1(void) const; - float getRedAdjust2(void) const; - - /** Sets the green adjustment to be made per second to particles. - @param green - The adjustment to be made to the colour component per second. This - value will be added to the colour of all particles every second, scaled over each frame - for a smooth adjustment. - */ - void setGreenAdjust1(float green); - void setGreenAdjust2(float green); - /** Gets the green adjustment to be made per second to particles. */ - float getGreenAdjust1(void) const; - float getGreenAdjust2(void) const; - /** Sets the blue adjustment to be made per second to particles. - @param blue - The adjustment to be made to the colour component per second. This - value will be added to the colour of all particles every second, scaled over each frame - for a smooth adjustment. - */ - void setBlueAdjust1(float blue); - void setBlueAdjust2(float blue); - /** Gets the blue adjustment to be made per second to particles. */ - float getBlueAdjust1(void) const; - float getBlueAdjust2(void) const; - - /** Sets the alpha adjustment to be made per second to particles. - @param alpha - The adjustment to be made to the colour component per second. This - value will be added to the colour of all particles every second, scaled over each frame - for a smooth adjustment. - */ - void setAlphaAdjust1(float alpha); - void setAlphaAdjust2(float alpha); - /** Gets the alpha adjustment to be made per second to particles. */ - float getAlphaAdjust1(void) const; - float getAlphaAdjust2(void) const; - - - void setStateChange(Real NewValue ); - Real getStateChange(void) const; - - static CmdRedAdjust1 msRedCmd1; - static CmdRedAdjust2 msRedCmd2; - static CmdGreenAdjust1 msGreenCmd1; - static CmdGreenAdjust2 msGreenCmd2; - static CmdBlueAdjust1 msBlueCmd1; - static CmdBlueAdjust2 msBlueCmd2; - static CmdAlphaAdjust1 msAlphaCmd1; - static CmdAlphaAdjust2 msAlphaCmd2; - static CmdStateChange msStateCmd; - - protected: - float mRedAdj1, mRedAdj2; - float mGreenAdj1, mGreenAdj2; - float mBlueAdj1, mBlueAdj2; - float mAlphaAdj1, mAlphaAdj2; - Real StateChangeVal; - }; - - /** @} */ - /** @} */ -} - - -#endif - diff --git a/PlugIns/ParticleFX/include/OgreColourImageAffector.h b/PlugIns/ParticleFX/include/OgreColourImageAffector.h deleted file mode 100644 index c7ccb731f00..00000000000 --- a/PlugIns/ParticleFX/include/OgreColourImageAffector.h +++ /dev/null @@ -1,78 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ColourImageAffector_H__ -#define __ColourImageAffector_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffector.h" -#include "OgreStringInterface.h" -#include "OgreColourValue.h" -#include "OgreImage.h" - -namespace Ogre { - - - class ColourImageAffector : public ParticleAffector - { - public: - /** Command object for red adjust (see ParamCommand).*/ - class CmdImageAdjust : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Default constructor. */ - ColourImageAffector(ParticleSystem* psys); - - void _initParticle(Particle* pParticle) override; - - void _affectParticles(ParticleSystem* pSystem, Real timeElapsed) override; - - void setImageAdjust(String name); - String getImageAdjust(void) const; - - - static CmdImageAdjust msImageCmd; - - protected: - Image mColourImage; - bool mColourImageLoaded; - String mColourImageName; - - /** Internal method to load the image */ - void _loadImage(void); - }; - - -} - - -#endif - diff --git a/PlugIns/ParticleFX/include/OgreColourInterpolatorAffector.h b/PlugIns/ParticleFX/include/OgreColourInterpolatorAffector.h deleted file mode 100644 index 4f2bb6bc7ae..00000000000 --- a/PlugIns/ParticleFX/include/OgreColourInterpolatorAffector.h +++ /dev/null @@ -1,96 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ColourInterpolatorAffector_H__ -#define __ColourInterpolatorAffector_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffector.h" -#include "OgreStringInterface.h" -#include "OgreColourValue.h" - -namespace Ogre { - - - class ColourInterpolatorAffector : public ParticleAffector - { - public: - // this is something of a hack.. - // needs to be replaced with something more.. - // ..elegant - enum { MAX_STAGES = 6 }; - - - /** Command object for red adjust (see ParamCommand).*/ - class CmdColourAdjust : public ParamCommand - { - public: - size_t mIndex; - - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Command object for red adjust (see ParamCommand).*/ - class CmdTimeAdjust : public ParamCommand - { - public: - size_t mIndex; - - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Default constructor. */ - ColourInterpolatorAffector(ParticleSystem* psys); - - void _affectParticles(ParticleSystem* pSystem, Real timeElapsed) override; - - void setColourAdjust(size_t index, ColourValue colour); - ColourValue getColourAdjust(size_t index) const; - - void setTimeAdjust(size_t index, Real time); - Real getTimeAdjust(size_t index) const; - - - static CmdColourAdjust msColourCmd[MAX_STAGES]; - static CmdTimeAdjust msTimeCmd[MAX_STAGES]; - - void _initParticle(Particle* pParticle) override; - - protected: - ColourValue mColourAdj[MAX_STAGES]; - Real mTimeAdj[MAX_STAGES]; - - }; -} - - -#endif - diff --git a/PlugIns/ParticleFX/include/OgreCylinderEmitter.h b/PlugIns/ParticleFX/include/OgreCylinderEmitter.h deleted file mode 100644 index 65873d2f1b9..00000000000 --- a/PlugIns/ParticleFX/include/OgreCylinderEmitter.h +++ /dev/null @@ -1,58 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -// Original author: Tels , released as public domain - -#ifndef __CylinderEmitter_H__ -#define __CylinderEmitter_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreAreaEmitter.h" - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup ParticleFX - * @{ - */ - /** This emitter emits particles in a random direction from within a cylinder area, where the cylinder is oriented along the Z-axis. - */ - class CylinderEmitter : public AreaEmitter - { - public: - /** See AreaEmitter. */ - CylinderEmitter(ParticleSystem* psys); - - void _initParticle(Particle* pParticle) override; - }; - /** @} */ - /** @} */ -} - -#endif - diff --git a/PlugIns/ParticleFX/include/OgreDeflectorPlaneAffector.h b/PlugIns/ParticleFX/include/OgreDeflectorPlaneAffector.h deleted file mode 100644 index 12ac7ca804b..00000000000 --- a/PlugIns/ParticleFX/include/OgreDeflectorPlaneAffector.h +++ /dev/null @@ -1,113 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __DeflectorPlaneAffector_H__ -#define __DeflectorPlaneAffector_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffector.h" -#include "OgreVector.h" - - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup ParticleFX - * @{ - */ - /** This affector defines a plane which deflects particles which collide with it. - */ - class DeflectorPlaneAffector : public ParticleAffector - { - public: - /** Command object for plane point (see ParamCommand).*/ - class CmdPlanePoint : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Command object for plane normal (see ParamCommand).*/ - class CmdPlaneNormal : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Command object for bounce (see ParamCommand).*/ - class CmdBounce : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /// Default constructor - DeflectorPlaneAffector(ParticleSystem* psys); - - void _affectParticles(ParticleSystem* pSystem, Real timeElapsed) override; - - /** Sets the plane point of the deflector plane. */ - void setPlanePoint(const Vector3& pos); - - /** Gets the plane point of the deflector plane. */ - Vector3 getPlanePoint(void) const; - - /** Sets the plane normal of the deflector plane. */ - void setPlaneNormal(const Vector3& normal); - - /** Gets the plane normal of the deflector plane. */ - Vector3 getPlaneNormal(void) const; - - /** Sets the bounce value of the deflection. */ - void setBounce(Real bounce); - - /** Gets the bounce value of the deflection. */ - Real getBounce(void) const; - - /// Command objects - static CmdPlanePoint msPlanePointCmd; - static CmdPlaneNormal msPlaneNormalCmd; - static CmdBounce msBounceCmd; - - protected: - /// deflector plane point - Vector3 mPlanePoint; - /// deflector plane normal vector - Vector3 mPlaneNormal; - - /// bounce factor (0.5 means 50 percent) - Real mBounce; - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/PlugIns/ParticleFX/include/OgreDirectionRandomiserAffector.h b/PlugIns/ParticleFX/include/OgreDirectionRandomiserAffector.h deleted file mode 100644 index c796bc1dc3d..00000000000 --- a/PlugIns/ParticleFX/include/OgreDirectionRandomiserAffector.h +++ /dev/null @@ -1,106 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __DirectionRandomiserAffector_H__ -#define __DirectionRandomiserAffector_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffector.h" -#include "OgreVector.h" - - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup ParticleFX - * @{ - */ - /** This affector applies randomness to the movement of the particles. - */ - class DirectionRandomiserAffector : public ParticleAffector - { - public: - /** Command object for randomness (see ParamCommand).*/ - class CmdRandomness : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Command object for scope (see ParamCommand).*/ - class CmdScope : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Command object for keep_velocity (see ParamCommand).*/ - class CmdKeepVelocity : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /// Default constructor - DirectionRandomiserAffector(ParticleSystem* psys); - - void _affectParticles(ParticleSystem* pSystem, Real timeElapsed) override; - - - /** The amount of randomness to introduce in each axial direction. */ - void setRandomness(Real force); - /** The percentage of particles affected in each run of the affector. */ - void setScope(Real force); - /** Determines whether the velocity of particles is unchanged. */ - void setKeepVelocity(bool keepVelocity); - - /** Gets the randomness to apply to the particles in a system. */ - Real getRandomness(void) const; - /** Gets the scope (percentage of particles which are randomised). */ - Real getScope(void) const; - /** Gets flag which detemines whether particle speed is changed. */ - bool getKeepVelocity(void) const; - - /// Command objects - static CmdRandomness msRandomnessCmd; - static CmdScope msScopeCmd; - static CmdKeepVelocity msKeepVelocityCmd; - - protected: - Real mRandomness; - Real mScope; - bool mKeepVelocity; - - }; - -} - -#endif diff --git a/PlugIns/ParticleFX/include/OgreEllipsoidEmitter.h b/PlugIns/ParticleFX/include/OgreEllipsoidEmitter.h deleted file mode 100644 index af4b31dcad9..00000000000 --- a/PlugIns/ParticleFX/include/OgreEllipsoidEmitter.h +++ /dev/null @@ -1,57 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -// Original author: Tels , released as public domain -#ifndef __EllipsoidEmitter_H__ -#define __EllipsoidEmitter_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreAreaEmitter.h" - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup ParticleFX - * @{ - */ - /** Particle emitter which emits particles randomly from points inside an ellipsoid. - */ - class EllipsoidEmitter : public AreaEmitter - { - public: - /** See AreaEmitter. */ - EllipsoidEmitter(ParticleSystem* psys); - - void _initParticle(Particle* pParticle) override; - }; - /** @} */ - /** @} */ -} - -#endif - diff --git a/PlugIns/ParticleFX/include/OgreHollowEllipsoidEmitter.h b/PlugIns/ParticleFX/include/OgreHollowEllipsoidEmitter.h deleted file mode 100644 index 4a181a17bb5..00000000000 --- a/PlugIns/ParticleFX/include/OgreHollowEllipsoidEmitter.h +++ /dev/null @@ -1,124 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -// Original author: Tels , released as public domain -#ifndef __HollowEllipsoidEmitter_H__ -#define __HollowEllipsoidEmitter_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreEllipsoidEmitter.h" - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup ParticleFX - * @{ - */ - /** Particle emitter which emits particles randomly from points inside a hollow ellipsoid. - */ - class HollowEllipsoidEmitter : public EllipsoidEmitter - { - public: - /** Command object for inner size (see ParamCommand).*/ - class CmdInnerX : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for inner size (see ParamCommand).*/ - class CmdInnerY : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for inner size (see ParamCommand).*/ - class CmdInnerZ : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - // See AreaEmitter - - HollowEllipsoidEmitter(ParticleSystem* psys); - - void _initParticle(Particle* pParticle) override; - - /** Sets the size of the clear space inside the area from where NO particles are emitted. - @param x,y,z - Parametric values describing the proportion of the shape which is hollow in each direction. - @note The values are fractions of the 'outer' dimensions; E.g. 0 is solid, 0.5 is half-hollow etc - */ - void setInnerSize(Real x, Real y, Real z); - - /** Sets the x component of the area inside the ellipsoid which doesn't emit particles. - @param x - Parametric value describing the proportion of the shape which is hollow in this direction. - @note The values are fractions of the 'outer' dimensions; E.g. 0 is solid, 0.5 is half-hollow etc - */ - void setInnerSizeX(Real x); - /** Sets the y component of the area inside the ellipsoid which doesn't emit particles. - @param y - Parametric value describing the proportion of the shape which is hollow in this direction. - @note The values are fractions of the 'outer' dimensions; E.g. 0 is solid, 0.5 is half-hollow etc - */ - void setInnerSizeY(Real y); - /** Sets the z component of the area inside the ellipsoid which doesn't emit particles. - @param z - Parametric value describing the proportion of the shape which is hollow in this direction. - @note The values are fractions of the 'outer' dimensions; E.g. 0 is solid, 0.5 is half-hollow etc - */ - void setInnerSizeZ(Real z); - /** Gets the x component of the area inside the ellipsoid which doesn't emit particles. */ - Real getInnerSizeX(void) const; - /** Gets the y component of the area inside the ellipsoid which doesn't emit particles. */ - Real getInnerSizeY(void) const; - /** Gets the z component of the area inside the ellipsoid which doesn't emit particles. */ - Real getInnerSizeZ(void) const; - - protected: - /// @see ParticleEmitter - - /// Size of 'clear' center area (> 0 and < 1.0) - Vector3 mInnerSize; - - static CmdInnerX msCmdInnerX; - static CmdInnerY msCmdInnerY; - static CmdInnerZ msCmdInnerZ; - - - - }; - /** @} */ - /** @} */ -} - -#endif - diff --git a/PlugIns/ParticleFX/include/OgreLinearForceAffector.h b/PlugIns/ParticleFX/include/OgreLinearForceAffector.h deleted file mode 100644 index 1de759c3ca4..00000000000 --- a/PlugIns/ParticleFX/include/OgreLinearForceAffector.h +++ /dev/null @@ -1,124 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __LinearForceAffector_H__ -#define __LinearForceAffector_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffector.h" -#include "OgreVector.h" - - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup ParticleFX - * @{ - */ - /** This affector applies a force vector to all particles to modify their trajectory. Can be used for gravity, wind, or any other linear force. - - This force can be applied in 2 ways: by taking the average of the particle's current momentum and the - force vector, or by adding the force vector to the current particle's momentum. - @par - The former approach is self-stabilising i.e. once a particle's momentum - is equal to the force vector, no further change is made to it's momentum. It also results in - a non-linear acceleration of particles. - The latter approach is simpler and applies a constant acceleration to particles. However, - it is not self-stabilising and can lead to perpetually increasing particle velocities. - You choose the approach by calling the setForceApplication method. - */ - class LinearForceAffector : public ParticleAffector - { - public: - /** Command object for force vector (see ParamCommand).*/ - class CmdForceVector : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Command object for force application (see ParamCommand).*/ - class CmdForceApp : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /// Choice of how to apply the force vector to particles - enum ForceApplication - { - /// Take the average of the force vector and the particle momentum - FA_AVERAGE, - /// Add the force vector to the particle momentum - FA_ADD - }; - /// Default constructor - LinearForceAffector(ParticleSystem* psys); - - void _affectParticles(ParticleSystem* pSystem, Real timeElapsed) override; - - - /** Sets the force vector to apply to the particles in a system. */ - void setForceVector(const Vector3& force); - - /** Gets the force vector to apply to the particles in a system. */ - Vector3 getForceVector(void) const; - - /** Sets how the force vector is applied to a particle. - - The default is FA_ADD. - @param fa A member of the ForceApplication enum. - */ - void setForceApplication(ForceApplication fa); - - /** Retrieves how the force vector is applied to a particle. - @return A member of the ForceApplication enum. - */ - ForceApplication getForceApplication(void) const; - - /// Command objects - static CmdForceVector msForceVectorCmd; - static CmdForceApp msForceAppCmd; - - protected: - /// Force vector - Vector3 mForceVector; - - /// How to apply force - ForceApplication mForceApplication; - - }; - - /** @} */ - /** @} */ -} - - -#endif - diff --git a/PlugIns/ParticleFX/include/OgreParticleFXPlugin.h b/PlugIns/ParticleFX/include/OgreParticleFXPlugin.h deleted file mode 100644 index 4fe6aceba6f..00000000000 --- a/PlugIns/ParticleFX/include/OgreParticleFXPlugin.h +++ /dev/null @@ -1,67 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ParticleFXPlugin_H__ -#define __ParticleFXPlugin_H__ - -#include "OgrePlugin.h" -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffectorFactory.h" -#include "OgreParticleEmitterFactory.h" - -namespace Ogre -{ - - /** Plugin instance for ParticleFX Manager */ - class _OgreParticleFXExport ParticleFXPlugin : public Plugin - { - public: - ParticleFXPlugin(); - - - /// @copydoc Plugin::getName - const String& getName() const override; - - /// @copydoc Plugin::install - void install() override; - - /// @copydoc Plugin::initialise - void initialise() override; - - /// @copydoc Plugin::shutdown - void shutdown() override; - - /// @copydoc Plugin::uninstall - void uninstall() override; - protected: - std::vector mEmitterFactories; - std::vector mAffectorFactories; - - }; -} - -#endif diff --git a/PlugIns/ParticleFX/include/OgrePointEmitter.h b/PlugIns/ParticleFX/include/OgrePointEmitter.h deleted file mode 100644 index 670354cc567..00000000000 --- a/PlugIns/ParticleFX/include/OgrePointEmitter.h +++ /dev/null @@ -1,59 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __PointEmitter_H__ -#define __PointEmitter_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleEmitter.h" - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup ParticleFX - * @{ - */ - /** This emitter emits particles from a single point, which is it’s position. - - The initial direction of these particles can either be a single direction (i.e. a line), - a random scattering inside a cone, or a random scattering in all directions, - depending the 'angle' parameter, which is the angle across which to scatter the - particles either side of the base direction of the emitter. - */ - class PointEmitter : public ParticleEmitter - { - public: - PointEmitter(ParticleSystem* psys); - - void _initParticle(Particle* pParticle) override; - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/PlugIns/ParticleFX/include/OgreRingEmitter.h b/PlugIns/ParticleFX/include/OgreRingEmitter.h deleted file mode 100644 index d9f84432a5b..00000000000 --- a/PlugIns/ParticleFX/include/OgreRingEmitter.h +++ /dev/null @@ -1,118 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -// Original author: Tels , released as public domain -#ifndef __RingEmitter_H__ -#define __RingEmitter_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreAreaEmitter.h" -#include "OgreMath.h" - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup ParticleFX - * @{ - */ - - /** Particle emitter which emits particles randomly from points inside a ring (e.g. a tube). - - This particle emitter emits particles from a ring-shaped area. - The initial direction of these particles can either be a single - direction (i.e. a line), a random scattering inside a cone, or a random - scattering in all directions, depending the 'angle' parameter, which - is the angle across which to scatter the particles either side of the - base direction of the emitter. - */ - class RingEmitter : public AreaEmitter - { - public: - /// @see AreaEmitter - /** Command object for inner size (see ParamCommand).*/ - class CmdInnerX : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - /** Command object for inner size (see ParamCommand).*/ - class CmdInnerY : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - RingEmitter(ParticleSystem* psys); - - /// @see ParticleEmitter - void _initParticle(Particle* pParticle) override; - - /** Sets the size of the clear space inside the area from where NO particles are emitted. - @param x, y - Parametric values describing the proportion of the shape which is hollow in each direction. - E.g. 0 is solid, 0.5 is half-hollow etc - */ - void setInnerSize(Real x, Real y); - - /** Sets the x component of the area inside the ellipsoid which doesn't emit particles. - @param x - Parametric value describing the proportion of the shape which is hollow in this direction. - E.g. 0 is solid, 0.5 is half-hollow etc - */ - void setInnerSizeX(Real x); - /** Sets the y component of the area inside the ellipsoid which doesn't emit particles. - @param y - Parametric value describing the proportion of the shape which is hollow in this direction. - E.g. 0 is solid, 0.5 is half-hollow etc - */ - void setInnerSizeY(Real y); - /** Gets the x component of the area inside the ellipsoid which doesn't emit particles. */ - Real getInnerSizeX(void) const; - /** Gets the y component of the area inside the ellipsoid which doesn't emit particles. */ - Real getInnerSizeY(void) const; - - protected: - /// @see ParticleEmitter - static CmdInnerX msCmdInnerX; - static CmdInnerY msCmdInnerY; - - /// Size of 'clear' center area (> 0 and < 1.0) - Real mInnerSizex; - Real mInnerSizey; - - - - }; - /** @} */ - /** @} */ -} - -#endif - diff --git a/PlugIns/ParticleFX/include/OgreRotationAffector.h b/PlugIns/ParticleFX/include/OgreRotationAffector.h deleted file mode 100644 index 3fc35a94111..00000000000 --- a/PlugIns/ParticleFX/include/OgreRotationAffector.h +++ /dev/null @@ -1,132 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __RotationAffector_H__ -#define __RotationAffector_H__ - -#include "OgreMath.h" -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffector.h" -#include "OgreStringInterface.h" - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup ParticleFX - * @{ - */ - - /** This affector rotates particles in flight. - */ - class RotationAffector : public ParticleAffector - { - public: - /// Command object for particle emitter - see ParamCommand - class CmdRotationSpeedRangeStart : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /// Command object for particle emitter - see ParamCommand - class CmdRotationSpeedRangeEnd : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /// Command object for particle emitter - see ParamCommand - class CmdRotationRangeStart : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /// Command object for particle emitter - see ParamCommand - class CmdRotationRangeEnd : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Default constructor. */ - RotationAffector(ParticleSystem* psys); - - void _initParticle(Particle* pParticle) override; - - void _affectParticles(ParticleSystem* pSystem, Real timeElapsed) override; - - - - /** Sets the minimum rotation speed of particles to be emitted. */ - void setRotationSpeedRangeStart(const Radian& angle); - /** Sets the maximum rotation speed of particles to be emitted. */ - void setRotationSpeedRangeEnd(const Radian& angle); - /** Gets the minimum rotation speed of particles to be emitted. */ - const Radian& getRotationSpeedRangeStart(void) const; - /** Gets the maximum rotation speed of particles to be emitted. */ - const Radian& getRotationSpeedRangeEnd(void) const; - - - /** Sets the minimum rotation angle of particles to be emitted. */ - void setRotationRangeStart(const Radian& angle); - /** Sets the maximum rotation angle of particles to be emitted. */ - void setRotationRangeEnd(const Radian& angle); - /** Gets the minimum rotation of particles to be emitted. */ - const Radian& getRotationRangeStart(void) const; - /** Gets the maximum rotation of particles to be emitted. */ - const Radian& getRotationRangeEnd(void) const; - - static CmdRotationSpeedRangeStart msRotationSpeedRangeStartCmd; - static CmdRotationSpeedRangeEnd msRotationSpeedRangeEndCmd; - static CmdRotationRangeStart msRotationRangeStartCmd; - static CmdRotationRangeEnd msRotationRangeEndCmd; - - protected: - /// Initial rotation speed of particles (range start) - Radian mRotationSpeedRangeStart; - /// Initial rotation speed of particles (range end) - Radian mRotationSpeedRangeEnd; - /// Initial rotation angle of particles (range start) - Radian mRotationRangeStart; - /// Initial rotation angle of particles (range end) - Radian mRotationRangeEnd; - - }; - - /** @} */ - /** @} */ -} - - -#endif - diff --git a/PlugIns/ParticleFX/include/OgreScaleAffector.h b/PlugIns/ParticleFX/include/OgreScaleAffector.h deleted file mode 100644 index 78968eafc24..00000000000 --- a/PlugIns/ParticleFX/include/OgreScaleAffector.h +++ /dev/null @@ -1,90 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ScaleAffector_H__ -#define __ScaleAffector_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffector.h" -#include "OgreStringInterface.h" - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup ParticleFX - * @{ - */ - - /** This affector scales particles in flight. - */ - class ScaleAffector : public ParticleAffector - { - public: - - /** Command object for scale adjust (see ParamCommand).*/ - class CmdScaleAdjust : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - /** Default constructor. */ - ScaleAffector(ParticleSystem* psys); - - void _initParticle(Particle* pParticle) override; - void _affectParticles(ParticleSystem* pSystem, Real timeElapsed) override; - - /** Sets the scale adjustment to be made per second to particles. - @param rate - Sets the adjustment to be made to the x and y scale components per second. These - values will be added to the scale of all particles every second, scaled over each frame - for a smooth adjustment. - */ - void setAdjust( Real rate ); - - /** Gets the scale adjustment to be made per second to particles. */ - Real getAdjust(void) const; - - const Vector2& getScaleRange() const { return mScaleRange; } - void setScaleRange(const Vector2& range) { mScaleRange = range; } - - static CmdScaleAdjust msScaleCmd; - - protected: - float mScaleAdj; - Vector2 mScaleRange; - }; - - /** @} */ - /** @} */ -} - - -#endif - diff --git a/PlugIns/ParticleFX/include/OgreTextureAnimatorAffector.h b/PlugIns/ParticleFX/include/OgreTextureAnimatorAffector.h deleted file mode 100644 index 937caa55d45..00000000000 --- a/PlugIns/ParticleFX/include/OgreTextureAnimatorAffector.h +++ /dev/null @@ -1,76 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT -#ifndef __TextureAnimatorAffector_H__ -#define __TextureAnimatorAffector_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffector.h" -#include "OgreStringInterface.h" -#include "OgreParticleAffectorFactory.h" - -namespace Ogre { - /** \addtogroup Plugins - * @{ - */ - /** \addtogroup ParticleFX - * @{ - */ - - /** This affector makes it possible to have an animated texture for each individual particle. - */ - class TextureAnimatorAffector : public ParticleAffector - { - public: - TextureAnimatorAffector(ParticleSystem* psys); - - void _affectParticles(ParticleSystem* pSystem, Real timeElapsed) override; - - void _initParticle(Particle* pParticle) override; - - /** Sets the texcoord index at which the animation should start - * - * default: 0 - */ - void setTexcoordStart(uint8 start) { mTexcoordStart = start; } - uint8 getTexcoordStart(void) const { return mTexcoordStart; } - - /** Sets the number of texcoords to use. - * @note you must set this one and start + count must not exceed the number of frames in the sprite sheet - */ - void setTexcoordCount(uint8 count) { mTexcoordCount = count; } - uint8 getTexcoordCount(void) const { return mTexcoordCount; } - /** The length of time it takes to display the whole animation sequence, in seconds. - * - * If set to 0 (default) the duration equals the particle time to live. Using a different value here, - * you can play back the animation faster (looping) or slower. - * When negative, the animation is disabled. This is useful to just pick a random sprite (see below) and keep it. - */ - void setDuration(float duration) { mDuration = duration; } - float getDuration(void) const { return mDuration; } - - /** Start animation at random frame in the texture sheet. Useful to randomly phase the animation between particles. - */ - void useRandomStartOffset(float enable) { mRandomStartOffset = enable; } - float isRandomStartOffset(void) const { return mRandomStartOffset; } - protected: - bool mRandomStartOffset; - uint8 mTexcoordStart; - uint8 mTexcoordCount; - float mDuration; - }; - - /** Factory class for TextureAnimatorAffector. */ - class TextureAnimatorAffectorFactory : public ParticleAffectorFactory - { - String getName() const override { return "TextureAnimator"; } - - ParticleAffector* createAffector(ParticleSystem* psys) override { return new TextureAnimatorAffector(psys); } - }; - - /** @} */ - /** @} */ -} - -#endif diff --git a/PlugIns/ParticleFX/src/OgreAreaEmitter.cpp b/PlugIns/ParticleFX/src/OgreAreaEmitter.cpp deleted file mode 100644 index a1cbcf8c92d..00000000000 --- a/PlugIns/ParticleFX/src/OgreAreaEmitter.cpp +++ /dev/null @@ -1,180 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -// Original author: Tels , released as public domain -#include "OgreAreaEmitter.h" -#include "OgreParticle.h" -#include "OgreQuaternion.h" -#include "OgreException.h" -#include "OgreStringConverter.h" - - - -namespace Ogre { - - // Instatiate statics - AreaEmitter::CmdWidth AreaEmitter::msWidthCmd; - AreaEmitter::CmdHeight AreaEmitter::msHeightCmd; - AreaEmitter::CmdDepth AreaEmitter::msDepthCmd; - - //----------------------------------------------------------------------- - bool AreaEmitter::initDefaults(const String& t) - { - // called by the constructor as initDefaults("Type") - - // Defaults - mDirection = Vector3::UNIT_Z; - mUp = Vector3::UNIT_Y; - setSize(100,100,100); - mType = t; - - // Set up parameters - if (createParamDictionary(mType + "Emitter")) - { - - addBaseParameters(); - ParamDictionary* dict = getParamDictionary(); - - // Custom params - dict->addParameter(ParameterDef("width", - "Width of the shape in world coordinates.", - PT_REAL),&msWidthCmd); - dict->addParameter(ParameterDef("height", - "Height of the shape in world coordinates.", - PT_REAL),&msHeightCmd); - dict->addParameter(ParameterDef("depth", - "Depth of the shape in world coordinates.", - PT_REAL),&msDepthCmd); - return true; - - } - return false; - } - //----------------------------------------------------------------------- - void AreaEmitter::setDirection( const Vector3& inDirection ) - { - ParticleEmitter::setDirection( inDirection ); - - // Update the ranges - genAreaAxes(); - } - //----------------------------------------------------------------------- - void AreaEmitter::setSize(const Vector3& size) - { - mSize = size; - genAreaAxes(); - } - //----------------------------------------------------------------------- - void AreaEmitter::setSize(Real x, Real y, Real z) - { - mSize.x = x; - mSize.y = y; - mSize.z = z; - genAreaAxes(); - } - //----------------------------------------------------------------------- - void AreaEmitter::setWidth(Real width) - { - mSize.x = width; - genAreaAxes(); - } - //----------------------------------------------------------------------- - Real AreaEmitter::getWidth(void) const - { - return mSize.x; - } - //----------------------------------------------------------------------- - void AreaEmitter::setHeight(Real height) - { - mSize.y = height; - genAreaAxes(); - } - //----------------------------------------------------------------------- - Real AreaEmitter::getHeight(void) const - { - return mSize.y; - } - //----------------------------------------------------------------------- - void AreaEmitter::setDepth(Real depth) - { - mSize.z = depth; - genAreaAxes(); - } - //----------------------------------------------------------------------- - Real AreaEmitter::getDepth(void) const - { - return mSize.z; - } - //----------------------------------------------------------------------- - void AreaEmitter::genAreaAxes(void) - { - Vector3 mLeft = mUp.crossProduct(mDirection); - - mXRange = mLeft * (mSize.x * 0.5f); - mYRange = mUp * (mSize.y * 0.5f); - mZRange = mDirection * (mSize.z * 0.5f); - } - - //----------------------------------------------------------------------- - // Command objects - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String AreaEmitter::CmdWidth::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getWidth() ); - } - void AreaEmitter::CmdWidth::doSet(void* target, const String& val) - { - static_cast(target)->setWidth(StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String AreaEmitter::CmdHeight::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getHeight() ); - } - void AreaEmitter::CmdHeight::doSet(void* target, const String& val) - { - static_cast(target)->setHeight(StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String AreaEmitter::CmdDepth::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getDepth() ); - } - void AreaEmitter::CmdDepth::doSet(void* target, const String& val) - { - static_cast(target)->setDepth(StringConverter::parseReal(val)); - } - - - -} - - diff --git a/PlugIns/ParticleFX/src/OgreBoxEmitter.cpp b/PlugIns/ParticleFX/src/OgreBoxEmitter.cpp deleted file mode 100644 index 844ecd3fb13..00000000000 --- a/PlugIns/ParticleFX/src/OgreBoxEmitter.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreBoxEmitter.h" -#include "OgreParticle.h" -#include "OgreException.h" -#include "OgreStringConverter.h" - - - -namespace Ogre { - - - //----------------------------------------------------------------------- - BoxEmitter::BoxEmitter(ParticleSystem* psys) - : AreaEmitter(psys) - { - initDefaults("Box"); - } - //----------------------------------------------------------------------- - void BoxEmitter::_initParticle(Particle* pParticle) - { - Vector3 xOff, yOff, zOff; - - // Call superclass - ParticleEmitter::_initParticle(pParticle); - - xOff = Math::SymmetricRandom() * mXRange; - yOff = Math::SymmetricRandom() * mYRange; - zOff = Math::SymmetricRandom() * mZRange; - - pParticle->mPosition = mPosition + xOff + yOff + zOff; - - - // Generate complex data by reference - genEmissionColour(pParticle->mColour); - genEmissionDirection( pParticle->mPosition, pParticle->mDirection ); - genEmissionVelocity(pParticle->mDirection); - - // Generate simpler data - pParticle->mTimeToLive = pParticle->mTotalTimeToLive = genEmissionTTL(); - - } - - -} - - diff --git a/PlugIns/ParticleFX/src/OgreBoxEmitterFactory.h b/PlugIns/ParticleFX/src/OgreBoxEmitterFactory.h deleted file mode 100644 index ff45ade7216..00000000000 --- a/PlugIns/ParticleFX/src/OgreBoxEmitterFactory.h +++ /dev/null @@ -1,55 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __BoxEmitterFactory_H__ -#define __BoxEmitterFactory_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleEmitterFactory.h" -#include "OgreBoxEmitter.h" - - -namespace Ogre { - - /** Factory class for particle emitter of type "Box". - - Creates instances of BoxEmitter to be used in particle systems. - */ - class BoxEmitterFactory : public ParticleEmitterFactory - { - protected: - - public: - String getName() const override { return "Box"; } - - ParticleEmitter* createEmitter(ParticleSystem* psys) override { return new BoxEmitter(psys); } - }; - -} - -#endif - diff --git a/PlugIns/ParticleFX/src/OgreColourFaderAffector.cpp b/PlugIns/ParticleFX/src/OgreColourFaderAffector.cpp deleted file mode 100644 index 2ff7e032062..00000000000 --- a/PlugIns/ParticleFX/src/OgreColourFaderAffector.cpp +++ /dev/null @@ -1,181 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreColourFaderAffector.h" -#include "OgreParticleSystem.h" -#include "OgreStringConverter.h" -#include "OgreParticle.h" - - -namespace Ogre { - - // init statics - ColourFaderAffector::CmdRedAdjust ColourFaderAffector::msRedCmd; - ColourFaderAffector::CmdGreenAdjust ColourFaderAffector::msGreenCmd; - ColourFaderAffector::CmdBlueAdjust ColourFaderAffector::msBlueCmd; - ColourFaderAffector::CmdAlphaAdjust ColourFaderAffector::msAlphaCmd; - - //----------------------------------------------------------------------- - ColourFaderAffector::ColourFaderAffector(ParticleSystem* psys) : ParticleAffector(psys) - { - mRedAdj = mGreenAdj = mBlueAdj = mAlphaAdj = 0; - mType = "ColourFader"; - - // Init parameters - if (createParamDictionary("ColourFaderAffector")) - { - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter(ParameterDef("red", - "The amount by which to adjust the red component of particles per second.", - PT_REAL), &msRedCmd); - dict->addParameter(ParameterDef("green", - "The amount by which to adjust the green component of particles per second.", - PT_REAL), &msGreenCmd); - dict->addParameter(ParameterDef("blue", - "The amount by which to adjust the blue component of particles per second.", - PT_REAL), &msBlueCmd); - dict->addParameter(ParameterDef("alpha", - "The amount by which to adjust the alpha component of particles per second.", - PT_REAL), &msAlphaCmd); - - - } - } - //----------------------------------------------------------------------- - void ColourFaderAffector::_affectParticles(ParticleSystem* pSystem, Real timeElapsed) - { - // Scale adjustments by time - auto dc = ColourValue(mRedAdj, mGreenAdj, mBlueAdj, mAlphaAdj) * timeElapsed; - - for (auto p : pSystem->_getActiveParticles()) - { - p->mColour = (ColourValue((uchar*)&p->mColour) + dc).saturateCopy().getAsBYTE(); - } - } - //----------------------------------------------------------------------- - void ColourFaderAffector::setAdjust(float red, float green, float blue, float alpha) - { - mRedAdj = red; - mGreenAdj = green; - mBlueAdj = blue; - mAlphaAdj = alpha; - } - //----------------------------------------------------------------------- - void ColourFaderAffector::setRedAdjust(float red) - { - mRedAdj = red; - } - //----------------------------------------------------------------------- - float ColourFaderAffector::getRedAdjust(void) const - { - return mRedAdj; - } - //----------------------------------------------------------------------- - void ColourFaderAffector::setGreenAdjust(float green) - { - mGreenAdj = green; - } - //----------------------------------------------------------------------- - float ColourFaderAffector::getGreenAdjust(void) const - { - return mGreenAdj; - } - //----------------------------------------------------------------------- - void ColourFaderAffector::setBlueAdjust(float blue) - { - mBlueAdj = blue; - } - //----------------------------------------------------------------------- - float ColourFaderAffector::getBlueAdjust(void) const - { - return mBlueAdj; - } - //----------------------------------------------------------------------- - void ColourFaderAffector::setAlphaAdjust(float alpha) - { - mAlphaAdj = alpha; - } - //----------------------------------------------------------------------- - float ColourFaderAffector::getAlphaAdjust(void) const - { - return mAlphaAdj; - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - // Command objects - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String ColourFaderAffector::CmdRedAdjust::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getRedAdjust() ); - } - void ColourFaderAffector::CmdRedAdjust::doSet(void* target, const String& val) - { - static_cast(target)->setRedAdjust( - StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String ColourFaderAffector::CmdGreenAdjust::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getGreenAdjust() ); - } - void ColourFaderAffector::CmdGreenAdjust::doSet(void* target, const String& val) - { - static_cast(target)->setGreenAdjust( - StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String ColourFaderAffector::CmdBlueAdjust::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getBlueAdjust() ); - } - void ColourFaderAffector::CmdBlueAdjust::doSet(void* target, const String& val) - { - static_cast(target)->setBlueAdjust( - StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String ColourFaderAffector::CmdAlphaAdjust::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getAlphaAdjust() ); - } - void ColourFaderAffector::CmdAlphaAdjust::doSet(void* target, const String& val) - { - static_cast(target)->setAlphaAdjust( - StringConverter::parseReal(val)); - } - -} - - - diff --git a/PlugIns/ParticleFX/src/OgreColourFaderAffector2.cpp b/PlugIns/ParticleFX/src/OgreColourFaderAffector2.cpp deleted file mode 100644 index 37a2d4652b3..00000000000 --- a/PlugIns/ParticleFX/src/OgreColourFaderAffector2.cpp +++ /dev/null @@ -1,324 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreColourFaderAffector2.h" -#include "OgreParticleSystem.h" -#include "OgreStringConverter.h" -#include "OgreParticle.h" - - -namespace Ogre { - - // init statics - // Phase 1 - ColourFaderAffector2::CmdRedAdjust1 ColourFaderAffector2::msRedCmd1; - ColourFaderAffector2::CmdGreenAdjust1 ColourFaderAffector2::msGreenCmd1; - ColourFaderAffector2::CmdBlueAdjust1 ColourFaderAffector2::msBlueCmd1; - ColourFaderAffector2::CmdAlphaAdjust1 ColourFaderAffector2::msAlphaCmd1; - - // Phase 2 - ColourFaderAffector2::CmdRedAdjust2 ColourFaderAffector2::msRedCmd2; - ColourFaderAffector2::CmdGreenAdjust2 ColourFaderAffector2::msGreenCmd2; - ColourFaderAffector2::CmdBlueAdjust2 ColourFaderAffector2::msBlueCmd2; - ColourFaderAffector2::CmdAlphaAdjust2 ColourFaderAffector2::msAlphaCmd2; - - ColourFaderAffector2::CmdStateChange ColourFaderAffector2::msStateCmd; - - - //----------------------------------------------------------------------- - ColourFaderAffector2::ColourFaderAffector2(ParticleSystem* psys) : ParticleAffector(psys) - { - mRedAdj1 = mGreenAdj1 = mBlueAdj1 = mAlphaAdj1 = 0; - mRedAdj2 = mGreenAdj2 = mBlueAdj2 = mAlphaAdj2 = 0; - mType = "ColourFader2"; - StateChangeVal = 1; // Switch when there is 1 second left on the TTL - - // Init parameters - if (createParamDictionary("ColourFaderAffector2")) - { - ParamDictionary* dict = getParamDictionary(); - - // Phase 1 - dict->addParameter(ParameterDef("red1", - "The amount by which to adjust the red component of particles per second.", - PT_REAL), &msRedCmd1); - dict->addParameter(ParameterDef("green1", - "The amount by which to adjust the green component of particles per second.", - PT_REAL), &msGreenCmd1); - dict->addParameter(ParameterDef("blue1", - "The amount by which to adjust the blue component of particles per second.", - PT_REAL), &msBlueCmd1); - dict->addParameter(ParameterDef("alpha1", - "The amount by which to adjust the alpha component of particles per second.", - PT_REAL), &msAlphaCmd1); - - // Phase 2 - dict->addParameter(ParameterDef("red2", - "The amount by which to adjust the red component of particles per second.", - PT_REAL), &msRedCmd2); - dict->addParameter(ParameterDef("green2", - "The amount by which to adjust the green component of particles per second.", - PT_REAL), &msGreenCmd2); - dict->addParameter(ParameterDef("blue2", - "The amount by which to adjust the blue component of particles per second.", - PT_REAL), &msBlueCmd2); - dict->addParameter(ParameterDef("alpha2", - "The amount by which to adjust the alpha component of particles per second.", - PT_REAL), &msAlphaCmd2); - - // State Change Value - dict->addParameter(ParameterDef("state_change", - "When the particle has this much time to live left, it will switch to state 2.", - PT_REAL), &msStateCmd); - - } - } - //----------------------------------------------------------------------- - void ColourFaderAffector2::_affectParticles(ParticleSystem* pSystem, Real timeElapsed) - { - // Scale adjustments by time - auto dc1 = ColourValue(mRedAdj1, mGreenAdj1, mBlueAdj1, mAlphaAdj1) * timeElapsed; - auto dc2 = ColourValue(mRedAdj2, mGreenAdj2, mBlueAdj2, mAlphaAdj2) * timeElapsed; - - for (auto p : pSystem->_getActiveParticles()) - { - p->mColour = (ColourValue((uchar*)&p->mColour) + (p->mTimeToLive > StateChangeVal ? dc1 : dc2)) - .saturateCopy() - .getAsBYTE(); - } - } - //----------------------------------------------------------------------- - void ColourFaderAffector2::setAdjust1(float red, float green, float blue, float alpha) - { - mRedAdj1 = red; - mGreenAdj1 = green; - mBlueAdj1 = blue; - mAlphaAdj1 = alpha; - } - //----------------------------------------------------------------------- - void ColourFaderAffector2::setAdjust2(float red, float green, float blue, float alpha) - { - mRedAdj2 = red; - mGreenAdj2 = green; - mBlueAdj2 = blue; - mAlphaAdj2 = alpha; - } - - //----------------------------------------------------------------------- - void ColourFaderAffector2::setRedAdjust1(float red) - { - mRedAdj1 = red; - } - //----------------------------------------------------------------------- - void ColourFaderAffector2::setRedAdjust2(float red) - { - mRedAdj2 = red; - } - //----------------------------------------------------------------------- - float ColourFaderAffector2::getRedAdjust1(void) const - { - return mRedAdj1; - } - //----------------------------------------------------------------------- - float ColourFaderAffector2::getRedAdjust2(void) const - { - return mRedAdj2; - } - //----------------------------------------------------------------------- - void ColourFaderAffector2::setGreenAdjust1(float green) - { - mGreenAdj1 = green; - } - //----------------------------------------------------------------------- - void ColourFaderAffector2::setGreenAdjust2(float green) - { - mGreenAdj2 = green; - } - //----------------------------------------------------------------------- - float ColourFaderAffector2::getGreenAdjust1(void) const - { - return mGreenAdj1; - } - //----------------------------------------------------------------------- - float ColourFaderAffector2::getGreenAdjust2(void) const - { - return mGreenAdj2; - } - //----------------------------------------------------------------------- - void ColourFaderAffector2::setBlueAdjust1(float blue) - { - mBlueAdj1 = blue; - } - //----------------------------------------------------------------------- - void ColourFaderAffector2::setBlueAdjust2(float blue) - { - mBlueAdj2 = blue; - } - //----------------------------------------------------------------------- - float ColourFaderAffector2::getBlueAdjust1(void) const - { - return mBlueAdj1; - } - //----------------------------------------------------------------------- - float ColourFaderAffector2::getBlueAdjust2(void) const - { - return mBlueAdj2; - } - //----------------------------------------------------------------------- - void ColourFaderAffector2::setAlphaAdjust1(float alpha) - { - mAlphaAdj1 = alpha; - } - //----------------------------------------------------------------------- - void ColourFaderAffector2::setAlphaAdjust2(float alpha) - { - mAlphaAdj2 = alpha; - } - //----------------------------------------------------------------------- - float ColourFaderAffector2::getAlphaAdjust1(void) const - { - return mAlphaAdj1; - } - //----------------------------------------------------------------------- - float ColourFaderAffector2::getAlphaAdjust2(void) const - { - return mAlphaAdj2; - } - //----------------------------------------------------------------------- - void ColourFaderAffector2::setStateChange(Real NewValue) - { - StateChangeVal = NewValue; - } - //----------------------------------------------------------------------- - Real ColourFaderAffector2::getStateChange(void) const - { - return StateChangeVal; - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - // Command objects - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String ColourFaderAffector2::CmdRedAdjust1::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getRedAdjust1() ); - } - void ColourFaderAffector2::CmdRedAdjust1::doSet(void* target, const String& val) - { - static_cast(target)->setRedAdjust1( - StringConverter::parseReal(val)); - } - String ColourFaderAffector2::CmdRedAdjust2::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getRedAdjust2() ); - } - void ColourFaderAffector2::CmdRedAdjust2::doSet(void* target, const String& val) - { - static_cast(target)->setRedAdjust2( - StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String ColourFaderAffector2::CmdGreenAdjust1::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getGreenAdjust1() ); - } - void ColourFaderAffector2::CmdGreenAdjust1::doSet(void* target, const String& val) - { - static_cast(target)->setGreenAdjust1( - StringConverter::parseReal(val)); - } - String ColourFaderAffector2::CmdGreenAdjust2::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getGreenAdjust2() ); - } - void ColourFaderAffector2::CmdGreenAdjust2::doSet(void* target, const String& val) - { - static_cast(target)->setGreenAdjust2( - StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String ColourFaderAffector2::CmdBlueAdjust1::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getBlueAdjust1() ); - } - void ColourFaderAffector2::CmdBlueAdjust1::doSet(void* target, const String& val) - { - static_cast(target)->setBlueAdjust1( - StringConverter::parseReal(val)); - } - String ColourFaderAffector2::CmdBlueAdjust2::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getBlueAdjust2() ); - } - void ColourFaderAffector2::CmdBlueAdjust2::doSet(void* target, const String& val) - { - static_cast(target)->setBlueAdjust2( - StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String ColourFaderAffector2::CmdAlphaAdjust1::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getAlphaAdjust1() ); - } - void ColourFaderAffector2::CmdAlphaAdjust1::doSet(void* target, const String& val) - { - static_cast(target)->setAlphaAdjust1( - StringConverter::parseReal(val)); - } - String ColourFaderAffector2::CmdAlphaAdjust2::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getAlphaAdjust2() ); - } - void ColourFaderAffector2::CmdAlphaAdjust2::doSet(void* target, const String& val) - { - static_cast(target)->setAlphaAdjust2( - StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String ColourFaderAffector2::CmdStateChange::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getStateChange() ); - } - void ColourFaderAffector2::CmdStateChange::doSet(void* target, const String& val) - { - static_cast(target)->setStateChange( - StringConverter::parseReal(val)); - } -} - - - diff --git a/PlugIns/ParticleFX/src/OgreColourFaderAffectorFactory.h b/PlugIns/ParticleFX/src/OgreColourFaderAffectorFactory.h deleted file mode 100644 index c3dc7dfb1b3..00000000000 --- a/PlugIns/ParticleFX/src/OgreColourFaderAffectorFactory.h +++ /dev/null @@ -1,49 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ColourFaderAffectorFactory_H__ -#define __ColourFaderAffectorFactory_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffectorFactory.h" -#include "OgreColourFaderAffector.h" - -namespace Ogre { - - /** Factory class for ColourFaderAffector. */ - class ColourFaderAffectorFactory : public ParticleAffectorFactory - { - String getName() const override { return "ColourFader"; } - - ParticleAffector* createAffector(ParticleSystem* psys) override { return new ColourFaderAffector(psys); } - }; - - -} - -#endif - diff --git a/PlugIns/ParticleFX/src/OgreColourFaderAffectorFactory2.h b/PlugIns/ParticleFX/src/OgreColourFaderAffectorFactory2.h deleted file mode 100644 index 4b32c5eb5a2..00000000000 --- a/PlugIns/ParticleFX/src/OgreColourFaderAffectorFactory2.h +++ /dev/null @@ -1,49 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ColourFaderAffectorFactory2_H__ -#define __ColourFaderAffectorFactory2_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffectorFactory.h" -#include "OgreColourFaderAffector2.h" - -namespace Ogre { - - /** Factory class for ColourFaderAffector. */ - class ColourFaderAffectorFactory2 : public ParticleAffectorFactory - { - String getName() const override { return "ColourFader2"; } - - ParticleAffector* createAffector(ParticleSystem* psys) override { return new ColourFaderAffector2(psys); } - }; - - -} - -#endif - diff --git a/PlugIns/ParticleFX/src/OgreColourImageAffector.cpp b/PlugIns/ParticleFX/src/OgreColourImageAffector.cpp deleted file mode 100644 index 92d7d852b93..00000000000 --- a/PlugIns/ParticleFX/src/OgreColourImageAffector.cpp +++ /dev/null @@ -1,155 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreColourImageAffector.h" -#include "OgreParticleSystem.h" -#include "OgreStringConverter.h" -#include "OgreParticle.h" -#include "OgreException.h" -#include "OgreResourceGroupManager.h" - -namespace Ogre { - - // init statics - ColourImageAffector::CmdImageAdjust ColourImageAffector::msImageCmd; - - //----------------------------------------------------------------------- - ColourImageAffector::ColourImageAffector(ParticleSystem* psys) - :ParticleAffector(psys), mColourImageLoaded(false) - { - mType = "ColourImage"; - - // Init parameters - if (createParamDictionary("ColourImageAffector")) - { - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter(ParameterDef("image", "image where the colours come from", PT_STRING), &msImageCmd); - } - } - //----------------------------------------------------------------------- - void ColourImageAffector::_initParticle(Particle* pParticle) - { - if (!mColourImageLoaded) - { - _loadImage(); - } - - pParticle->mColour = mColourImage.getColourAt(0, 0, 0).getAsBYTE(); - - } - //----------------------------------------------------------------------- - void ColourImageAffector::_affectParticles(ParticleSystem* pSystem, Real timeElapsed) - { - if (!mColourImageLoaded) - { - _loadImage(); - } - - int width = (int)mColourImage.getWidth() - 1; - - for (auto p : pSystem->_getActiveParticles()) - { - const Real life_time = p->mTotalTimeToLive; - Real particle_time = 1.0f - (p->mTimeToLive / life_time); - - if (particle_time > 1.0f) - particle_time = 1.0f; - if (particle_time < 0.0f) - particle_time = 0.0f; - - const Real float_index = particle_time * width; - const int index = (int)float_index; - - if(index < 0) - { - p->mColour = mColourImage.getColourAt(0, 0, 0).getAsBYTE(); - } - else if(index >= width) - { - p->mColour = mColourImage.getColourAt(width, 0, 0).getAsBYTE(); - } - else - { - // Linear interpolation - const Real fract = float_index - (Real)index; - - ColourValue from=mColourImage.getColourAt(index, 0, 0), - to=mColourImage.getColourAt(index+1, 0, 0); - - p->mColour = Math::lerp(from, to, fract).getAsBYTE(); - } - } - } - - //----------------------------------------------------------------------- - void ColourImageAffector::setImageAdjust(String name) - { - mColourImageName = name; - mColourImageLoaded = false; - } - //----------------------------------------------------------------------- - void ColourImageAffector::_loadImage(void) - { - mColourImage.load(mColourImageName, mParent->getResourceGroupName()); - - PixelFormat format = mColourImage.getFormat(); - - if ( !PixelUtil::isAccessible(format) ) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Error: Image is not accessible (rgba) image.", - "ColourImageAffector::_loadImage" ); - } - - mColourImageLoaded = true; - } - //----------------------------------------------------------------------- - String ColourImageAffector::getImageAdjust(void) const - { - return mColourImageName; - } - - - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - // Command objects - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String ColourImageAffector::CmdImageAdjust::doGet(const void* target) const - { - return static_cast(target)->getImageAdjust(); - } - void ColourImageAffector::CmdImageAdjust::doSet(void* target, const String& val) - { - static_cast(target)->setImageAdjust(val); - } - -} - - - diff --git a/PlugIns/ParticleFX/src/OgreColourImageAffectorFactory.h b/PlugIns/ParticleFX/src/OgreColourImageAffectorFactory.h deleted file mode 100644 index 38e33812103..00000000000 --- a/PlugIns/ParticleFX/src/OgreColourImageAffectorFactory.h +++ /dev/null @@ -1,49 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ColourImageAffectorFactory_H__ -#define __ColourImageAffectorFactory_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffectorFactory.h" -#include "OgreColourImageAffector.h" - -namespace Ogre { - - /** Factory class for ColourImageAffector. */ - class ColourImageAffectorFactory : public ParticleAffectorFactory - { - String getName() const override { return "ColourImage"; } - - ParticleAffector* createAffector(ParticleSystem* psys) override { return new ColourImageAffector(psys); } - }; - - -} - -#endif - diff --git a/PlugIns/ParticleFX/src/OgreColourInterpolatorAffector.cpp b/PlugIns/ParticleFX/src/OgreColourInterpolatorAffector.cpp deleted file mode 100644 index 78c6ce1de2c..00000000000 --- a/PlugIns/ParticleFX/src/OgreColourInterpolatorAffector.cpp +++ /dev/null @@ -1,161 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreColourInterpolatorAffector.h" -#include "OgreParticleSystem.h" -#include "OgreStringConverter.h" -#include "OgreParticle.h" - - -namespace Ogre { - - // init statics - ColourInterpolatorAffector::CmdColourAdjust ColourInterpolatorAffector::msColourCmd[MAX_STAGES]; - ColourInterpolatorAffector::CmdTimeAdjust ColourInterpolatorAffector::msTimeCmd[MAX_STAGES]; - - //----------------------------------------------------------------------- - ColourInterpolatorAffector::ColourInterpolatorAffector(ParticleSystem* psys) - : ParticleAffector(psys) - { - for (int i=0;iaddParameter(StringUtil::format("colour%d", i), &msColourCmd[i]); - dict->addParameter(StringUtil::format("time%d", i), &msTimeCmd[i]); - } - } - } - //----------------------------------------------------------------------- - void ColourInterpolatorAffector::_affectParticles(ParticleSystem* pSystem, Real timeElapsed) - { - for (auto p : pSystem->_getActiveParticles()) - { - const Real life_time = p->mTotalTimeToLive; - Real particle_time = 1.0f - (p->mTimeToLive / life_time); - - if (particle_time <= mTimeAdj[0]) - { - p->mColour = mColourAdj[0].getAsBYTE(); - } else - if (particle_time >= mTimeAdj[MAX_STAGES - 1]) - { - p->mColour = mColourAdj[MAX_STAGES-1].getAsBYTE(); - } else - { - for (int i=0;i= mTimeAdj[i] && particle_time < mTimeAdj[i + 1]) - { - particle_time -= mTimeAdj[i]; - particle_time /= (mTimeAdj[i+1]-mTimeAdj[i]); - - p->mColour = Math::lerp(mColourAdj[i], mColourAdj[i+1], particle_time).getAsBYTE(); - break; - } - } - } - } - } - - //----------------------------------------------------------------------- - void ColourInterpolatorAffector::setColourAdjust(size_t index, ColourValue colour) - { - mColourAdj[index] = colour; - } - //----------------------------------------------------------------------- - ColourValue ColourInterpolatorAffector::getColourAdjust(size_t index) const - { - return mColourAdj[index]; - } - - //----------------------------------------------------------------------- - void ColourInterpolatorAffector::_initParticle(Particle* pParticle) - { - pParticle->mColour = mColourAdj[0].getAsBYTE(); - } - - //----------------------------------------------------------------------- - void ColourInterpolatorAffector::setTimeAdjust(size_t index, Real time) - { - mTimeAdj[index] = time; - } - //----------------------------------------------------------------------- - Real ColourInterpolatorAffector::getTimeAdjust(size_t index) const - { - return mTimeAdj[index]; - } - - - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - // Command objects - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String ColourInterpolatorAffector::CmdColourAdjust::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getColourAdjust(mIndex) ); - } - void ColourInterpolatorAffector::CmdColourAdjust::doSet(void* target, const String& val) - { - static_cast(target)->setColourAdjust(mIndex, - StringConverter::parseColourValue(val)); - } - //----------------------------------------------------------------------- - String ColourInterpolatorAffector::CmdTimeAdjust::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getTimeAdjust(mIndex) ); - } - void ColourInterpolatorAffector::CmdTimeAdjust::doSet(void* target, const String& val) - { - static_cast(target)->setTimeAdjust(mIndex, - StringConverter::parseReal(val)); - } - -} - - - diff --git a/PlugIns/ParticleFX/src/OgreColourInterpolatorAffectorFactory.h b/PlugIns/ParticleFX/src/OgreColourInterpolatorAffectorFactory.h deleted file mode 100644 index d38bb876fb3..00000000000 --- a/PlugIns/ParticleFX/src/OgreColourInterpolatorAffectorFactory.h +++ /dev/null @@ -1,49 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ColourInterpolatorAffectorFactory_H__ -#define __ColourInterpolatorAffectorFactory_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffectorFactory.h" -#include "OgreColourInterpolatorAffector.h" - -namespace Ogre { - - /** Factory class for ColourInterpolatorAffector. */ - class ColourInterpolatorAffectorFactory : public ParticleAffectorFactory - { - String getName() const override { return "ColourInterpolator"; } - - ParticleAffector* createAffector(ParticleSystem* psys) override { return new ColourInterpolatorAffector(psys); } - }; - - -} - -#endif - diff --git a/PlugIns/ParticleFX/src/OgreCylinderEmitter.cpp b/PlugIns/ParticleFX/src/OgreCylinderEmitter.cpp deleted file mode 100644 index afcbd23c7c3..00000000000 --- a/PlugIns/ParticleFX/src/OgreCylinderEmitter.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -// Original author: Tels , released as public domain -#include "OgreCylinderEmitter.h" -#include "OgreParticle.h" -#include "OgreQuaternion.h" -#include "OgreException.h" -#include "OgreStringConverter.h" - - -/* Implements an Emitter whose emitting points all lie inside a cylinder. -*/ - -namespace Ogre { - - - //----------------------------------------------------------------------- - CylinderEmitter::CylinderEmitter(ParticleSystem* psys) - : AreaEmitter(psys) - { - initDefaults("Cylinder"); - } - //----------------------------------------------------------------------- - void CylinderEmitter::_initParticle(Particle* pParticle) - { - Real x, y, z; - - // Call superclass - AreaEmitter::_initParticle(pParticle); - - // First we create a random point inside a bounding cylinder with a - // radius and height of 1 (this is easy to do). The distance of the - // point from 0,0,0 must be <= 1 (== 1 means on the surface and we - // count this as inside, too). - - while (true) - { -/* ClearSpace not yet implemeted - -*/ - // three random values for one random point in 3D space - x = Math::SymmetricRandom(); - y = Math::SymmetricRandom(); - z = Math::SymmetricRandom(); - - // the distance of x,y from 0,0 is sqrt(x*x+y*y), but - // as usual we can omit the sqrt(), since sqrt(1) == 1 and we - // use the 1 as boundary. z is not taken into account, since - // all values in the z-direction are inside the cylinder: - if ( x*x + y*y <= 1) - { - break; // found one valid point inside - } - } - - // scale the found point to the cylinder's size and move it - // relatively to the center of the emitter point - - pParticle->mPosition = mPosition + - + x * mXRange + y * mYRange + z * mZRange; - - // Generate complex data by reference - genEmissionColour(pParticle->mColour); - genEmissionDirection( pParticle->mPosition, pParticle->mDirection ); - genEmissionVelocity(pParticle->mDirection); - - // Generate simpler data - pParticle->mTimeToLive = pParticle->mTotalTimeToLive = genEmissionTTL(); - - } - -} - - diff --git a/PlugIns/ParticleFX/src/OgreCylinderEmitterFactory.h b/PlugIns/ParticleFX/src/OgreCylinderEmitterFactory.h deleted file mode 100644 index 67919cda907..00000000000 --- a/PlugIns/ParticleFX/src/OgreCylinderEmitterFactory.h +++ /dev/null @@ -1,56 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -// Original author: Tels , released as public domain -#ifndef __CylinderEmitterFactory_H__ -#define __CylinderEmitterFactory_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleEmitterFactory.h" -#include "OgreCylinderEmitter.h" - - -namespace Ogre { - - /** Factory class for particle emitter of type "Cylinder". - - Creates instances of CylinderEmitter to be used in particle systems. - */ - class CylinderEmitterFactory : public ParticleEmitterFactory - { - protected: - - public: - String getName() const override { return "Cylinder"; } - - ParticleEmitter* createEmitter(ParticleSystem* psys) override { return new CylinderEmitter(psys); } - }; - -} - -#endif - diff --git a/PlugIns/ParticleFX/src/OgreDeflectorPlaneAffector.cpp b/PlugIns/ParticleFX/src/OgreDeflectorPlaneAffector.cpp deleted file mode 100644 index 3229bcb3d90..00000000000 --- a/PlugIns/ParticleFX/src/OgreDeflectorPlaneAffector.cpp +++ /dev/null @@ -1,161 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreDeflectorPlaneAffector.h" -#include "OgreParticleSystem.h" -#include "OgreParticle.h" -#include "OgreStringConverter.h" - - -namespace Ogre { - - // Instantiate statics - DeflectorPlaneAffector::CmdPlanePoint DeflectorPlaneAffector::msPlanePointCmd; - DeflectorPlaneAffector::CmdPlaneNormal DeflectorPlaneAffector::msPlaneNormalCmd; - DeflectorPlaneAffector::CmdBounce DeflectorPlaneAffector::msBounceCmd; - - //----------------------------------------------------------------------- - DeflectorPlaneAffector::DeflectorPlaneAffector(ParticleSystem* psys) - : ParticleAffector(psys), mPlanePoint(Vector3::ZERO), mPlaneNormal(Vector3::UNIT_Y), mBounce(1.0) - { - mType = "DeflectorPlane"; - - // Set up parameters - if (createParamDictionary("DeflectorPlaneAffector")) - { - addBaseParameters(); - // Add extra parameters - ParamDictionary* dict = getParamDictionary(); - dict->addParameter(ParameterDef("plane_point", - "A point on the deflector plane. Together with the normal vector it defines the plane.", - PT_VECTOR3), &msPlanePointCmd); - dict->addParameter(ParameterDef("plane_normal", - "The normal vector of the deflector plane. Together with the point it defines the plane.", - PT_VECTOR3), &msPlaneNormalCmd); - dict->addParameter(ParameterDef("bounce", - "The amount of bouncing when a particle is deflected. 0 means no deflection and 1 stands for 100 percent reflection.", - PT_REAL), &msBounceCmd); - } - } - //----------------------------------------------------------------------- - void DeflectorPlaneAffector::_affectParticles(ParticleSystem* pSystem, Real timeElapsed) - { - // precalculate distance of plane from origin - Real planeDistance = - mPlaneNormal.dotProduct(mPlanePoint) / Math::Sqrt(mPlaneNormal.dotProduct(mPlaneNormal)); - Vector3 directionPart; - - for (auto p : pSystem->_getActiveParticles()) - { - Vector3 direction(p->mDirection * timeElapsed); - if (mPlaneNormal.dotProduct(p->mPosition + direction) + planeDistance <= 0.0) - { - Real a = mPlaneNormal.dotProduct(p->mPosition) + planeDistance; - if (a > 0.0) - { - // for intersection point - directionPart = direction * (- a / direction.dotProduct( mPlaneNormal )); - // set new position - p->mPosition = (p->mPosition + ( directionPart )) + (((directionPart) - direction) * mBounce); - - // reflect direction vector - p->mDirection = (p->mDirection - (2.0f * p->mDirection.dotProduct( mPlaneNormal ) * mPlaneNormal)) * mBounce; - } - } - } - } - //----------------------------------------------------------------------- - void DeflectorPlaneAffector::setPlanePoint(const Vector3& pos) - { - mPlanePoint = pos; - } - //----------------------------------------------------------------------- - void DeflectorPlaneAffector::setPlaneNormal(const Vector3& normal) - { - mPlaneNormal = normal; - } - //----------------------------------------------------------------------- - void DeflectorPlaneAffector::setBounce(Real bounce) - { - mBounce = bounce; - } - - //----------------------------------------------------------------------- - Vector3 DeflectorPlaneAffector::getPlanePoint(void) const - { - return mPlanePoint; - } - //----------------------------------------------------------------------- - Vector3 DeflectorPlaneAffector::getPlaneNormal(void) const - { - return mPlaneNormal; - } - //----------------------------------------------------------------------- - Real DeflectorPlaneAffector::getBounce(void) const - { - return mBounce; - } - - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - // Command objects - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String DeflectorPlaneAffector::CmdPlanePoint::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getPlanePoint() ); - } - void DeflectorPlaneAffector::CmdPlanePoint::doSet(void* target, const String& val) - { - static_cast(target)->setPlanePoint( - StringConverter::parseVector3(val)); - } - //----------------------------------------------------------------------- - String DeflectorPlaneAffector::CmdPlaneNormal::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getPlaneNormal() ); - } - void DeflectorPlaneAffector::CmdPlaneNormal::doSet(void* target, const String& val) - { - static_cast(target)->setPlaneNormal( - StringConverter::parseVector3(val)); - } - //----------------------------------------------------------------------- - String DeflectorPlaneAffector::CmdBounce::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getBounce() ); - - } - void DeflectorPlaneAffector::CmdBounce::doSet(void* target, const String& val) - { - static_cast(target)->setBounce( - StringConverter::parseReal(val)); - } - -} diff --git a/PlugIns/ParticleFX/src/OgreDeflectorPlaneAffectorFactory.h b/PlugIns/ParticleFX/src/OgreDeflectorPlaneAffectorFactory.h deleted file mode 100644 index 435255f3fa0..00000000000 --- a/PlugIns/ParticleFX/src/OgreDeflectorPlaneAffectorFactory.h +++ /dev/null @@ -1,49 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __DeflectorPlaneAffectorFactory_H__ -#define __DeflectorPlaneAffectorFactory_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffectorFactory.h" -#include "OgreDeflectorPlaneAffector.h" - -namespace Ogre { - - /** Factory class for DeflectorPlaneAffector. */ - class DeflectorPlaneAffectorFactory : public ParticleAffectorFactory - { - String getName() const override { return "DeflectorPlane"; } - - ParticleAffector* createAffector(ParticleSystem* psys) override { return new DeflectorPlaneAffector(psys); } - }; - - -} - -#endif - diff --git a/PlugIns/ParticleFX/src/OgreDirectionRandomiserAffector.cpp b/PlugIns/ParticleFX/src/OgreDirectionRandomiserAffector.cpp deleted file mode 100644 index a45dad77315..00000000000 --- a/PlugIns/ParticleFX/src/OgreDirectionRandomiserAffector.cpp +++ /dev/null @@ -1,162 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreDirectionRandomiserAffector.h" -#include "OgreParticleSystem.h" -#include "OgreParticle.h" -#include "OgreStringConverter.h" - - -namespace Ogre { - - // Instantiate statics - DirectionRandomiserAffector::CmdRandomness DirectionRandomiserAffector::msRandomnessCmd; - DirectionRandomiserAffector::CmdScope DirectionRandomiserAffector::msScopeCmd; - DirectionRandomiserAffector::CmdKeepVelocity DirectionRandomiserAffector::msKeepVelocityCmd; - - //----------------------------------------------------------------------- - DirectionRandomiserAffector::DirectionRandomiserAffector(ParticleSystem* psys) - : ParticleAffector(psys) - { - mType = "DirectionRandomiser"; - - // defaults - mRandomness = 1.0; - mScope = 1.0; - mKeepVelocity = false; - - // Set up parameters - if (createParamDictionary("DirectionRandomiserAffector")) - { - addBaseParameters(); - // Add extra parameters - ParamDictionary* dict = getParamDictionary(); - dict->addParameter(ParameterDef("randomness", - "The amount of randomness (chaos) to apply to the particle movement.", - PT_REAL), &msRandomnessCmd); - dict->addParameter(ParameterDef("scope", - "The percentage of particles which is affected.", - PT_REAL), &msScopeCmd); - dict->addParameter(ParameterDef("keep_velocity", - "Determines whether the velocity of the particles is changed.", - PT_BOOL), &msKeepVelocityCmd); - } - } - //----------------------------------------------------------------------- - void DirectionRandomiserAffector::_affectParticles(ParticleSystem* pSystem, Real timeElapsed) - { - Real length = 0; - - for (auto p : pSystem->_getActiveParticles()) - { - if (mScope > Math::UnitRandom()) - { - if (!p->mDirection.isZeroLength()) - { - if (mKeepVelocity) - { - length = p->mDirection.length(); - } - - p->mDirection += Vector3(Math::RangeRandom(-mRandomness, mRandomness) * timeElapsed, - Math::RangeRandom(-mRandomness, mRandomness) * timeElapsed, - Math::RangeRandom(-mRandomness, mRandomness) * timeElapsed); - - if (mKeepVelocity) - { - p->mDirection *= length / p->mDirection.length(); - } - } - } - } - } - //----------------------------------------------------------------------- - void DirectionRandomiserAffector::setRandomness(Real force) - { - mRandomness = force; - } - //----------------------------------------------------------------------- - void DirectionRandomiserAffector::setScope(Real scope) - { - mScope = scope; - } - //----------------------------------------------------------------------- - void DirectionRandomiserAffector::setKeepVelocity(bool keepVelocity) - { - mKeepVelocity = keepVelocity; - } - //----------------------------------------------------------------------- - Real DirectionRandomiserAffector::getRandomness(void) const - { - return mRandomness; - } - //----------------------------------------------------------------------- - Real DirectionRandomiserAffector::getScope(void) const - { - return mScope; - } - //----------------------------------------------------------------------- - bool DirectionRandomiserAffector::getKeepVelocity(void) const - { - return mKeepVelocity; - } - - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - // Command objects - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String DirectionRandomiserAffector::CmdRandomness::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getRandomness() ); - } - void DirectionRandomiserAffector::CmdRandomness::doSet(void* target, const String& val) - { - static_cast(target)->setRandomness(StringConverter::parseReal(val)); - } - - String DirectionRandomiserAffector::CmdScope::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getScope() ); - } - void DirectionRandomiserAffector::CmdScope::doSet(void* target, const String& val) - { - static_cast(target)->setScope(StringConverter::parseReal(val)); - } - String DirectionRandomiserAffector::CmdKeepVelocity::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getKeepVelocity() ); - } - void DirectionRandomiserAffector::CmdKeepVelocity::doSet(void* target, const String& val) - { - static_cast(target)->setKeepVelocity(StringConverter::parseBool(val)); - } - -} diff --git a/PlugIns/ParticleFX/src/OgreDirectionRandomiserAffectorFactory.h b/PlugIns/ParticleFX/src/OgreDirectionRandomiserAffectorFactory.h deleted file mode 100644 index b79ddd826f5..00000000000 --- a/PlugIns/ParticleFX/src/OgreDirectionRandomiserAffectorFactory.h +++ /dev/null @@ -1,50 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __DirectionRandomiserAffectorFactory_H__ -#define __DirectionRandomiserAffectorFactory_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffectorFactory.h" -#include "OgreDirectionRandomiserAffector.h" - -namespace Ogre { - - /** Factory class for DirectionRandomiserAffector. */ - class DirectionRandomiserAffectorFactory : public ParticleAffectorFactory - { - String getName() const override { return "DirectionRandomiser"; } - - ParticleAffector* createAffector(ParticleSystem* psys) override - { - return new DirectionRandomiserAffector(psys); - } - }; - -} - -#endif diff --git a/PlugIns/ParticleFX/src/OgreEllipsoidEmitter.cpp b/PlugIns/ParticleFX/src/OgreEllipsoidEmitter.cpp deleted file mode 100644 index 5e3642921df..00000000000 --- a/PlugIns/ParticleFX/src/OgreEllipsoidEmitter.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -// Original author: Tels , released as public domain -#include "OgreEllipsoidEmitter.h" -#include "OgreParticle.h" -#include "OgreException.h" -#include "OgreStringConverter.h" - - -/* Implements an Emitter whose emitting points all lie inside an ellipsoid. - See for mathematical details. - - If the lengths of two axes of an ellipsoid are the same, the figure is - called a 'spheroid' (depending on whether c < a or c > a, an 'oblate - spheroid' or 'prolate spheroid', respectively), and if all three are the - same, it is a 'sphere' (ball). -*/ - -namespace Ogre { - - - //----------------------------------------------------------------------- - EllipsoidEmitter::EllipsoidEmitter(ParticleSystem* psys) - : AreaEmitter(psys) - { - initDefaults("Ellipsoid"); - } - //----------------------------------------------------------------------- - void EllipsoidEmitter::_initParticle(Particle* pParticle) - { - Real x, y, z; - - // Call superclass - AreaEmitter::_initParticle(pParticle); - // First we create a random point inside a bounding sphere with a - // radius of 1 (this is easy to do). The distance of the point from - // 0,0,0 must be <= 1 (== 1 means on the surface and we count this as - // inside, too). - - while (true) - { - // three random values for one random point in 3D space - - x = Math::SymmetricRandom(); - y = Math::SymmetricRandom(); - z = Math::SymmetricRandom(); - - // the distance of x,y,z from 0,0,0 is sqrt(x*x+y*y+z*z), but - // as usual we can omit the sqrt(), since sqrt(1) == 1 and we - // use the 1 as boundary: - if ( x*x + y*y + z*z <= 1) - { - break; // found one valid point inside - } - } - - // scale the found point to the ellipsoid's size and move it - // relatively to the center of the emitter point - - pParticle->mPosition = mPosition + - + x * mXRange + y * mYRange + z * mZRange; - - // Generate complex data by reference - genEmissionColour(pParticle->mColour); - genEmissionDirection( pParticle->mPosition, pParticle->mDirection ); - genEmissionVelocity(pParticle->mDirection); - - // Generate simpler data - pParticle->mTimeToLive = pParticle->mTotalTimeToLive = genEmissionTTL(); - - } - -} - - diff --git a/PlugIns/ParticleFX/src/OgreEllipsoidEmitterFactory.h b/PlugIns/ParticleFX/src/OgreEllipsoidEmitterFactory.h deleted file mode 100644 index 8adbd3711a1..00000000000 --- a/PlugIns/ParticleFX/src/OgreEllipsoidEmitterFactory.h +++ /dev/null @@ -1,60 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -// Original author: Tels , released as public domain -#ifndef __EllipsoidEmitterFactory_H__ -#define __EllipsoidEmitterFactory_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleEmitterFactory.h" -#include "OgreEllipsoidEmitter.h" - - -namespace Ogre { - - /** Factory class for particle emitter of type "Ellipsoid". - - Creates instances of EllipsoidEmitter to be used in particle systems. - */ - class EllipsoidEmitterFactory : public ParticleEmitterFactory - { - protected: - - public: - String getName() const override { return "Ellipsoid"; } - - ParticleEmitter* createEmitter(ParticleSystem* psys) override - { - return new EllipsoidEmitter(psys); - } - - }; - -} - -#endif - diff --git a/PlugIns/ParticleFX/src/OgreHollowEllipsoidEmitter.cpp b/PlugIns/ParticleFX/src/OgreHollowEllipsoidEmitter.cpp deleted file mode 100644 index dcc55fce821..00000000000 --- a/PlugIns/ParticleFX/src/OgreHollowEllipsoidEmitter.cpp +++ /dev/null @@ -1,200 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -// Original author: Tels , released as public domain -#include "OgreHollowEllipsoidEmitter.h" -#include "OgreParticle.h" -#include "OgreException.h" -#include "OgreStringConverter.h" -#include "OgreMath.h" - -/* Implements an Emitter whose emitting points all lie inside an ellipsoid. - See for mathematical details. - - If the lengths of two axes of an ellipsoid are the same, the figure is - called a 'spheroid' (depending on whether c < a or c > a, an 'oblate - spheroid' or 'prolate spheroid', respectively), and if all three are the - same, it is a 'sphere' (ball). -*/ - -namespace Ogre { - - HollowEllipsoidEmitter::CmdInnerX HollowEllipsoidEmitter::msCmdInnerX; - HollowEllipsoidEmitter::CmdInnerY HollowEllipsoidEmitter::msCmdInnerY; - HollowEllipsoidEmitter::CmdInnerZ HollowEllipsoidEmitter::msCmdInnerZ; - - - //----------------------------------------------------------------------- - HollowEllipsoidEmitter::HollowEllipsoidEmitter(ParticleSystem* psys) - : EllipsoidEmitter(psys) - { - if (initDefaults("HollowEllipsoid")) - { - // Add custom parameters - ParamDictionary* pDict = getParamDictionary(); - - pDict->addParameter(ParameterDef("inner_width", "Parametric value describing the proportion of the " - "shape which is hollow.", PT_REAL), &msCmdInnerX); - pDict->addParameter(ParameterDef("inner_height", "Parametric value describing the proportion of the " - "shape which is hollow.", PT_REAL), &msCmdInnerY); - pDict->addParameter(ParameterDef("inner_depth", "Parametric value describing the proportion of the " - "shape which is hollow.", PT_REAL), &msCmdInnerZ); - } - // default is half empty - setInnerSize(0.5,0.5,0.5); - } - //----------------------------------------------------------------------- - void HollowEllipsoidEmitter::_initParticle(Particle* pParticle) - { - Real a, b, c, x, y, z; - - // Init dimensions - ParticleEmitter::_initParticle(pParticle); - - // create two random angles alpha and beta - // with these two angles, we are able to select any point on an - // ellipsoid's surface - Radian alpha ( Math::RangeRandom(0,Math::TWO_PI) ); - Radian beta ( Math::RangeRandom(0,Math::PI) ); - - // create three random radius values that are bigger than the inner - // size, but smaller/equal than/to the outer size 1.0 (inner size is - // between 0 and 1) - a = Math::RangeRandom(mInnerSize.x,1.0); - b = Math::RangeRandom(mInnerSize.y,1.0); - c = Math::RangeRandom(mInnerSize.z,1.0); - - // with a,b,c we have defined a random ellipsoid between the inner - // ellipsoid and the outer sphere (radius 1.0) - // with alpha and beta we select on point on this random ellipsoid - // and calculate the 3D coordinates of this point - Real sinbeta ( Math::Sin(beta) ); - x = a * Math::Cos(alpha) * sinbeta; - y = b * Math::Sin(alpha) * sinbeta; - z = c * Math::Cos(beta); - - // scale the found point to the ellipsoid's size and move it - // relatively to the center of the emitter point - - pParticle->mPosition = mPosition + - + x * mXRange + y * mYRange + z * mZRange; - - // Generate complex data by reference - genEmissionColour(pParticle->mColour); - genEmissionDirection( pParticle->mPosition, pParticle->mDirection ); - genEmissionVelocity(pParticle->mDirection); - - // Generate simpler data - pParticle->mTimeToLive = pParticle->mTotalTimeToLive = genEmissionTTL(); - - } - //----------------------------------------------------------------------- - void HollowEllipsoidEmitter::setInnerSize(Real x, Real y, Real z) - { - assert((x > 0) && (x < 1.0) && - (y > 0) && (y < 1.0) && - (z > 0) && (z < 1.0)); - - mInnerSize.x = x; - mInnerSize.y = y; - mInnerSize.z = z; - } - //----------------------------------------------------------------------- - void HollowEllipsoidEmitter::setInnerSizeX(Real x) - { - assert(x > 0 && x < 1.0); - - mInnerSize.x = x; - } - //----------------------------------------------------------------------- - void HollowEllipsoidEmitter::setInnerSizeY(Real y) - { - assert(y > 0 && y < 1.0); - - mInnerSize.y = y; - } - //----------------------------------------------------------------------- - void HollowEllipsoidEmitter::setInnerSizeZ(Real z) - { - assert(z > 0 && z < 1.0); - - mInnerSize.z = z; - } - //----------------------------------------------------------------------- - Real HollowEllipsoidEmitter::getInnerSizeX(void) const - { - return mInnerSize.x; - } - //----------------------------------------------------------------------- - Real HollowEllipsoidEmitter::getInnerSizeY(void) const - { - return mInnerSize.y; - } - //----------------------------------------------------------------------- - Real HollowEllipsoidEmitter::getInnerSizeZ(void) const - { - return mInnerSize.z; - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - // Command objects - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String HollowEllipsoidEmitter::CmdInnerX::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getInnerSizeX() ); - } - void HollowEllipsoidEmitter::CmdInnerX::doSet(void* target, const String& val) - { - static_cast(target)->setInnerSizeX(StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String HollowEllipsoidEmitter::CmdInnerY::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getInnerSizeY() ); - } - void HollowEllipsoidEmitter::CmdInnerY::doSet(void* target, const String& val) - { - static_cast(target)->setInnerSizeY(StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String HollowEllipsoidEmitter::CmdInnerZ::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getInnerSizeZ() ); - } - void HollowEllipsoidEmitter::CmdInnerZ::doSet(void* target, const String& val) - { - static_cast(target)->setInnerSizeZ(StringConverter::parseReal(val)); - } - - -} - - diff --git a/PlugIns/ParticleFX/src/OgreHollowEllipsoidEmitterFactory.h b/PlugIns/ParticleFX/src/OgreHollowEllipsoidEmitterFactory.h deleted file mode 100644 index 33d0800f747..00000000000 --- a/PlugIns/ParticleFX/src/OgreHollowEllipsoidEmitterFactory.h +++ /dev/null @@ -1,56 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -// Original author: Tels , released as public domain -#ifndef __HollowEllipsoidEmitterFactory_H__ -#define __HollowEllipsoidEmitterFactory_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleEmitterFactory.h" -#include "OgreHollowEllipsoidEmitter.h" - - -namespace Ogre { - - /** Factory class for particle emitter of type "HollowEllipsoid". - - Creates instances of HollowEllipsoidEmitter to be used in particle systems. - */ - class HollowEllipsoidEmitterFactory : public ParticleEmitterFactory - { - protected: - - public: - String getName() const override { return "HollowEllipsoid"; } - - ParticleEmitter* createEmitter(ParticleSystem* psys) override { return new HollowEllipsoidEmitter(psys); } - }; - -} - -#endif - diff --git a/PlugIns/ParticleFX/src/OgreLinearForceAffector.cpp b/PlugIns/ParticleFX/src/OgreLinearForceAffector.cpp deleted file mode 100644 index 204bf07742a..00000000000 --- a/PlugIns/ParticleFX/src/OgreLinearForceAffector.cpp +++ /dev/null @@ -1,159 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreLinearForceAffector.h" -#include "OgreParticleSystem.h" -#include "OgreParticle.h" -#include "OgreStringConverter.h" - - -namespace Ogre { - - // Instantiate statics - LinearForceAffector::CmdForceVector LinearForceAffector::msForceVectorCmd; - LinearForceAffector::CmdForceApp LinearForceAffector::msForceAppCmd; - - - //----------------------------------------------------------------------- - LinearForceAffector::LinearForceAffector(ParticleSystem* psys) - :ParticleAffector(psys) - { - mType = "LinearForce"; - - // Default to gravity-like - mForceApplication = FA_ADD; - mForceVector.x = mForceVector.z = 0; - mForceVector.y = -100; - - // Set up parameters - if (createParamDictionary("LinearForceAffector")) - { - addBaseParameters(); - // Add extra parameters - ParamDictionary* dict = getParamDictionary(); - dict->addParameter(ParameterDef("force_vector", - "The vector representing the force to apply.", - PT_VECTOR3),&msForceVectorCmd); - dict->addParameter(ParameterDef("force_application", - "How to apply the force vector to particles.", - PT_STRING),&msForceAppCmd); - - } - - } - //----------------------------------------------------------------------- - void LinearForceAffector::_affectParticles(ParticleSystem* pSystem, Real timeElapsed) - { - Vector3 scaledVector = Vector3::ZERO; - - // Precalc scaled force for optimisation - if (mForceApplication == FA_ADD) - { - // Scale force by time - scaledVector = mForceVector * timeElapsed; - } - - for (auto p : pSystem->_getActiveParticles()) - { - if (mForceApplication == FA_ADD) - { - p->mDirection += scaledVector; - } - else // FA_AVERAGE - { - p->mDirection = (p->mDirection + mForceVector) / 2; - } - } - - } - //----------------------------------------------------------------------- - void LinearForceAffector::setForceVector(const Vector3& force) - { - mForceVector = force; - } - //----------------------------------------------------------------------- - void LinearForceAffector::setForceApplication(ForceApplication fa) - { - mForceApplication = fa; - } - //----------------------------------------------------------------------- - Vector3 LinearForceAffector::getForceVector(void) const - { - return mForceVector; - } - //----------------------------------------------------------------------- - LinearForceAffector::ForceApplication LinearForceAffector::getForceApplication(void) const - { - return mForceApplication; - } - - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - // Command objects - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String LinearForceAffector::CmdForceVector::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getForceVector() ); - } - void LinearForceAffector::CmdForceVector::doSet(void* target, const String& val) - { - static_cast(target)->setForceVector( - StringConverter::parseVector3(val)); - } - //----------------------------------------------------------------------- - String LinearForceAffector::CmdForceApp::doGet(const void* target) const - { - ForceApplication app = static_cast(target)->getForceApplication(); - switch(app) - { - case LinearForceAffector::FA_AVERAGE: - return "average"; - break; - case LinearForceAffector::FA_ADD: - return "add"; - break; - } - // Compiler nicety - return ""; - } - void LinearForceAffector::CmdForceApp::doSet(void* target, const String& val) - { - if (val == "average") - { - static_cast(target)->setForceApplication(FA_AVERAGE); - } - else if (val == "add") - { - static_cast(target)->setForceApplication(FA_ADD); - } - } - - -} - diff --git a/PlugIns/ParticleFX/src/OgreLinearForceAffectorFactory.h b/PlugIns/ParticleFX/src/OgreLinearForceAffectorFactory.h deleted file mode 100644 index e3d0e8151fc..00000000000 --- a/PlugIns/ParticleFX/src/OgreLinearForceAffectorFactory.h +++ /dev/null @@ -1,49 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __LinearForceAffectorFactory_H__ -#define __LinearForceAffectorFactory_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffectorFactory.h" -#include "OgreLinearForceAffector.h" - -namespace Ogre { - - /** Factory class for LinearForceAffector. */ - class LinearForceAffectorFactory : public ParticleAffectorFactory - { - String getName() const override { return "LinearForce"; } - - ParticleAffector* createAffector(ParticleSystem* psys) override { return new LinearForceAffector(psys); } - }; - - -} - -#endif - diff --git a/PlugIns/ParticleFX/src/OgreParticleFX.cpp b/PlugIns/ParticleFX/src/OgreParticleFX.cpp deleted file mode 100644 index 0e86ebb4123..00000000000 --- a/PlugIns/ParticleFX/src/OgreParticleFX.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreParticleFXPrerequisites.h" -#include "OgreRoot.h" -#include "OgreParticleFXPlugin.h" - -#ifndef OGRE_STATIC_LIB - -namespace Ogre { - - static ParticleFXPlugin* plugin; - extern "C" void _OgreParticleFXExport dllStartPlugin(void); - extern "C" void _OgreParticleFXExport dllStopPlugin(void); - - //----------------------------------------------------------------------- - extern "C" void _OgreParticleFXExport dllStartPlugin(void) - { - plugin = OGRE_NEW ParticleFXPlugin(); - Root::getSingleton().installPlugin(plugin); - } - - //----------------------------------------------------------------------- - extern "C" void _OgreParticleFXExport dllStopPlugin(void) - { - Root::getSingleton().uninstallPlugin(plugin); - OGRE_DELETE plugin; - - } - - -} - -#endif diff --git a/PlugIns/ParticleFX/src/OgreParticleFXPlugin.cpp b/PlugIns/ParticleFX/src/OgreParticleFXPlugin.cpp deleted file mode 100644 index 93d35e7f863..00000000000 --- a/PlugIns/ParticleFX/src/OgreParticleFXPlugin.cpp +++ /dev/null @@ -1,184 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreParticleFXPlugin.h" -#include "OgreRoot.h" -#include "OgreParticleSystemManager.h" - -#include "OgrePointEmitterFactory.h" -#include "OgreBoxEmitterFactory.h" -#include "OgreEllipsoidEmitterFactory.h" -#include "OgreHollowEllipsoidEmitterFactory.h" -#include "OgreRingEmitterFactory.h" -#include "OgreCylinderEmitterFactory.h" -#include "OgreLinearForceAffectorFactory.h" -#include "OgreColourFaderAffectorFactory.h" -#include "OgreColourFaderAffectorFactory2.h" -#include "OgreColourImageAffectorFactory.h" -#include "OgreColourInterpolatorAffectorFactory.h" -#include "OgreScaleAffectorFactory.h" -#include "OgreRotationAffectorFactory.h" -#include "OgreDirectionRandomiserAffectorFactory.h" -#include "OgreDeflectorPlaneAffectorFactory.h" -#include "OgreTextureAnimatorAffector.h" - -namespace Ogre -{ - const String sPluginName = "ParticleFX"; - //--------------------------------------------------------------------- - ParticleFXPlugin::ParticleFXPlugin() - { - - } - //--------------------------------------------------------------------- - const String& ParticleFXPlugin::getName() const - { - return sPluginName; - } - //--------------------------------------------------------------------- - void ParticleFXPlugin::install() - { - // -- Create all new particle emitter factories -- - ParticleEmitterFactory* pEmitFact; - - // PointEmitter - pEmitFact = OGRE_NEW PointEmitterFactory(); - ParticleSystemManager::getSingleton().addEmitterFactory(pEmitFact); - mEmitterFactories.push_back(pEmitFact); - - // BoxEmitter - pEmitFact = OGRE_NEW BoxEmitterFactory(); - ParticleSystemManager::getSingleton().addEmitterFactory(pEmitFact); - mEmitterFactories.push_back(pEmitFact); - - // EllipsoidEmitter - pEmitFact = OGRE_NEW EllipsoidEmitterFactory(); - ParticleSystemManager::getSingleton().addEmitterFactory(pEmitFact); - mEmitterFactories.push_back(pEmitFact); - - // CylinderEmitter - pEmitFact = OGRE_NEW CylinderEmitterFactory(); - ParticleSystemManager::getSingleton().addEmitterFactory(pEmitFact); - mEmitterFactories.push_back(pEmitFact); - - // RingEmitter - pEmitFact = OGRE_NEW RingEmitterFactory(); - ParticleSystemManager::getSingleton().addEmitterFactory(pEmitFact); - mEmitterFactories.push_back(pEmitFact); - - // HollowEllipsoidEmitter - pEmitFact = OGRE_NEW HollowEllipsoidEmitterFactory(); - ParticleSystemManager::getSingleton().addEmitterFactory(pEmitFact); - mEmitterFactories.push_back(pEmitFact); - - // -- Create all new particle affector factories -- - ParticleAffectorFactory* pAffFact; - - // LinearForceAffector - pAffFact = OGRE_NEW LinearForceAffectorFactory(); - ParticleSystemManager::getSingleton().addAffectorFactory(pAffFact); - mAffectorFactories.push_back(pAffFact); - - // ColourFaderAffector - pAffFact = OGRE_NEW ColourFaderAffectorFactory(); - ParticleSystemManager::getSingleton().addAffectorFactory(pAffFact); - mAffectorFactories.push_back(pAffFact); - - // ColourFaderAffector2 - pAffFact = OGRE_NEW ColourFaderAffectorFactory2(); - ParticleSystemManager::getSingleton().addAffectorFactory(pAffFact); - mAffectorFactories.push_back(pAffFact); - - // ColourImageAffector - pAffFact = OGRE_NEW ColourImageAffectorFactory(); - ParticleSystemManager::getSingleton().addAffectorFactory(pAffFact); - mAffectorFactories.push_back(pAffFact); - - // ColourInterpolatorAffector - pAffFact = OGRE_NEW ColourInterpolatorAffectorFactory(); - ParticleSystemManager::getSingleton().addAffectorFactory(pAffFact); - mAffectorFactories.push_back(pAffFact); - - // ScaleAffector - pAffFact = OGRE_NEW ScaleAffectorFactory(); - ParticleSystemManager::getSingleton().addAffectorFactory(pAffFact); - mAffectorFactories.push_back(pAffFact); - - // RotationAffector - pAffFact = OGRE_NEW RotationAffectorFactory(); - ParticleSystemManager::getSingleton().addAffectorFactory(pAffFact); - mAffectorFactories.push_back(pAffFact); - - - // DirectionRandomiserAffector - pAffFact = OGRE_NEW DirectionRandomiserAffectorFactory(); - ParticleSystemManager::getSingleton().addAffectorFactory(pAffFact); - mAffectorFactories.push_back(pAffFact); - - // DeflectorPlaneAffector - pAffFact = OGRE_NEW DeflectorPlaneAffectorFactory(); - ParticleSystemManager::getSingleton().addAffectorFactory(pAffFact); - mAffectorFactories.push_back(pAffFact); - - // TextureAnimatorAffector - pAffFact = OGRE_NEW TextureAnimatorAffectorFactory(); - ParticleSystemManager::getSingleton().addAffectorFactory(pAffFact); - mAffectorFactories.push_back(pAffFact); - } - //--------------------------------------------------------------------- - void ParticleFXPlugin::initialise() - { - // nothing to do - } - //--------------------------------------------------------------------- - void ParticleFXPlugin::shutdown() - { - // nothing to do - } - //--------------------------------------------------------------------- - void ParticleFXPlugin::uninstall() - { - // destroy - std::vector::iterator ei; - std::vector::iterator ai; - - for (ei = mEmitterFactories.begin(); ei != mEmitterFactories.end(); ++ei) - { - OGRE_DELETE (*ei); - } - - for (ai = mAffectorFactories.begin(); ai != mAffectorFactories.end(); ++ai) - { - OGRE_DELETE (*ai); - } - - - } - - -} diff --git a/PlugIns/ParticleFX/src/OgrePointEmitter.cpp b/PlugIns/ParticleFX/src/OgrePointEmitter.cpp deleted file mode 100644 index 9043bcd8c78..00000000000 --- a/PlugIns/ParticleFX/src/OgrePointEmitter.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgrePointEmitter.h" -#include "OgreParticle.h" - - - -namespace Ogre { - - //----------------------------------------------------------------------- - PointEmitter::PointEmitter(ParticleSystem* psys) - :ParticleEmitter(psys) - { - mType = "Point"; - // Set up parameters - if (createParamDictionary("PointEmitter")) - { - addBaseParameters(); - } - // No custom parameters - } - //----------------------------------------------------------------------- - void PointEmitter::_initParticle(Particle* pParticle) - { - // Very simple emitter, uses default implementations with no modification - - // Call superclass - ParticleEmitter::_initParticle(pParticle); - - // Point emitter emits from own position - pParticle->mPosition = mPosition; - - // Generate complex data by reference - genEmissionColour(pParticle->mColour); - genEmissionDirection( pParticle->mPosition, pParticle->mDirection ); - genEmissionVelocity(pParticle->mDirection); - - // Generate simpler data - pParticle->mTimeToLive = pParticle->mTotalTimeToLive = genEmissionTTL(); - - } -} - - diff --git a/PlugIns/ParticleFX/src/OgrePointEmitterFactory.h b/PlugIns/ParticleFX/src/OgrePointEmitterFactory.h deleted file mode 100644 index af5250f8c7b..00000000000 --- a/PlugIns/ParticleFX/src/OgrePointEmitterFactory.h +++ /dev/null @@ -1,55 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __PointEmitterFactory_H__ -#define __PointEmitterFactory_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleEmitterFactory.h" -#include "OgrePointEmitter.h" - - -namespace Ogre { - - /** Factory class for particle emitter of type "Point". - - Creates instances of PointEmitter to be used in particle systems. - */ - class PointEmitterFactory : public ParticleEmitterFactory - { - protected: - - public: - String getName() const override { return "Point"; } - - ParticleEmitter* createEmitter(ParticleSystem* psys) override { return new PointEmitter(psys); } - }; - -} - -#endif - diff --git a/PlugIns/ParticleFX/src/OgreRingEmitter.cpp b/PlugIns/ParticleFX/src/OgreRingEmitter.cpp deleted file mode 100644 index 5e65759d878..00000000000 --- a/PlugIns/ParticleFX/src/OgreRingEmitter.cpp +++ /dev/null @@ -1,160 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -// Original author: Tels , released as public domain -#include "OgreRingEmitter.h" -#include "OgreParticle.h" -#include "OgreException.h" -#include "OgreStringConverter.h" - - -/* Implements an Emitter whose emitting points all lie inside a ring. -*/ - -namespace Ogre { - - RingEmitter::CmdInnerX RingEmitter::msCmdInnerX; - RingEmitter::CmdInnerY RingEmitter::msCmdInnerY; - - //----------------------------------------------------------------------- - RingEmitter::RingEmitter(ParticleSystem* psys) - : AreaEmitter(psys) - { - if (initDefaults("Ring")) - { - // Add custom parameters - ParamDictionary* pDict = getParamDictionary(); - - pDict->addParameter(ParameterDef("inner_width", "Parametric value describing the proportion of the " - "shape which is hollow.", PT_REAL), &msCmdInnerX); - pDict->addParameter(ParameterDef("inner_height", "Parametric value describing the proportion of the " - "shape which is hollow.", PT_REAL), &msCmdInnerY); - } - // default is half empty - setInnerSize(0.5,0.5); - } - //----------------------------------------------------------------------- - void RingEmitter::_initParticle(Particle* pParticle) - { - Real a, b, x, y, z; - - // Call superclass - AreaEmitter::_initParticle(pParticle); - // create a random angle from 0 .. PI*2 - Radian alpha ( Math::RangeRandom(0,Math::TWO_PI) ); - - // create two random radius values that are bigger than the inner size - a = Math::RangeRandom(mInnerSizex,1.0); - b = Math::RangeRandom(mInnerSizey,1.0); - - // with a and b we have defined a random ellipse inside the inner - // ellipse and the outer circle (radius 1.0) - // with alpha, and a and b we select a random point on this ellipse - // and calculate it's coordinates - x = a * Math::Sin(alpha); - y = b * Math::Cos(alpha); - // the height is simple -1 to 1 - z = Math::SymmetricRandom(); - - // scale the found point to the ring's size and move it - // relatively to the center of the emitter point - - pParticle->mPosition = mPosition + - + x * mXRange + y * mYRange + z * mZRange; - - // Generate complex data by reference - genEmissionColour(pParticle->mColour); - genEmissionDirection( pParticle->mPosition, pParticle->mDirection ); - genEmissionVelocity(pParticle->mDirection); - - // Generate simpler data - pParticle->mTimeToLive = pParticle->mTotalTimeToLive = genEmissionTTL(); - - } - //----------------------------------------------------------------------- - void RingEmitter::setInnerSize(Real x, Real y) - { - // TODO: should really throw some exception - if ((x > 0) && (x < 1.0) && - (y > 0) && (y < 1.0)) - { - mInnerSizex = x; - mInnerSizey = y; - } - } - //----------------------------------------------------------------------- - void RingEmitter::setInnerSizeX(Real x) - { - assert(x > 0 && x < 1.0); - - mInnerSizex = x; - } - //----------------------------------------------------------------------- - void RingEmitter::setInnerSizeY(Real y) - { - assert(y > 0 && y < 1.0); - - mInnerSizey = y; - } - //----------------------------------------------------------------------- - Real RingEmitter::getInnerSizeX(void) const - { - return mInnerSizex; - } - //----------------------------------------------------------------------- - Real RingEmitter::getInnerSizeY(void) const - { - return mInnerSizey; - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - // Command objects - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String RingEmitter::CmdInnerX::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getInnerSizeX() ); - } - void RingEmitter::CmdInnerX::doSet(void* target, const String& val) - { - static_cast(target)->setInnerSizeX(StringConverter::parseReal(val)); - } - //----------------------------------------------------------------------- - String RingEmitter::CmdInnerY::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getInnerSizeY() ); - } - void RingEmitter::CmdInnerY::doSet(void* target, const String& val) - { - static_cast(target)->setInnerSizeY(StringConverter::parseReal(val)); - } - -} - - diff --git a/PlugIns/ParticleFX/src/OgreRingEmitterFactory.h b/PlugIns/ParticleFX/src/OgreRingEmitterFactory.h deleted file mode 100644 index d299990289e..00000000000 --- a/PlugIns/ParticleFX/src/OgreRingEmitterFactory.h +++ /dev/null @@ -1,56 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -// Original author: Tels , released as public domain -#ifndef __RingEmitterFactory_H__ -#define __RingEmitterFactory_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleEmitterFactory.h" -#include "OgreRingEmitter.h" - - -namespace Ogre { - - /** Factory class for particle emitter of type "Ring". - - Creates instances of RingEmitter to be used in particle systems. - */ - class RingEmitterFactory : public ParticleEmitterFactory - { - protected: - - public: - String getName() const override { return "Ring"; } - - ParticleEmitter* createEmitter(ParticleSystem* psys) override { return new RingEmitter(psys); } - }; - -} - -#endif - diff --git a/PlugIns/ParticleFX/src/OgreRotationAffector.cpp b/PlugIns/ParticleFX/src/OgreRotationAffector.cpp deleted file mode 100644 index 149fe8b03f0..00000000000 --- a/PlugIns/ParticleFX/src/OgreRotationAffector.cpp +++ /dev/null @@ -1,195 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreRotationAffector.h" -#include "OgreParticleSystem.h" -#include "OgreStringConverter.h" -#include "OgreParticle.h" - - -namespace Ogre { - - // init statics - RotationAffector::CmdRotationSpeedRangeStart RotationAffector::msRotationSpeedRangeStartCmd; - RotationAffector::CmdRotationSpeedRangeEnd RotationAffector::msRotationSpeedRangeEndCmd; - RotationAffector::CmdRotationRangeStart RotationAffector::msRotationRangeStartCmd; - RotationAffector::CmdRotationRangeEnd RotationAffector::msRotationRangeEndCmd; - - //----------------------------------------------------------------------- - RotationAffector::RotationAffector(ParticleSystem* psys) : - ParticleAffector(psys), - mRotationSpeedRangeStart(0), - mRotationSpeedRangeEnd(0), - mRotationRangeStart(0), - mRotationRangeEnd(0) - { - mType = "Rotator"; - - // Init parameters - if (createParamDictionary("RotationAffector")) - { - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter(ParameterDef("rotation_speed_range_start", - "The start of a range of rotation speed to be assigned to emitted particles.", PT_REAL), - &msRotationSpeedRangeStartCmd); - - dict->addParameter(ParameterDef("rotation_speed_range_end", - "The end of a range of rotation speed to be assigned to emitted particles.", PT_REAL), - &msRotationSpeedRangeEndCmd); - - dict->addParameter(ParameterDef("rotation_range_start", - "The start of a range of rotation angles to be assigned to emitted particles.", PT_REAL), - &msRotationRangeStartCmd); - - dict->addParameter(ParameterDef("rotation_range_end", - "The end of a range of rotation angles to be assigned to emitted particles.", PT_REAL), - &msRotationRangeEndCmd); - } - } - - //----------------------------------------------------------------------- - void RotationAffector::_initParticle(Particle* pParticle) - { - pParticle->setRotation( - mRotationRangeStart + - (Math::UnitRandom() * - (mRotationRangeEnd - mRotationRangeStart))); - pParticle->mRotationSpeed = - mRotationSpeedRangeStart + - (Math::UnitRandom() * - (mRotationSpeedRangeEnd - mRotationSpeedRangeStart)); - - } - //----------------------------------------------------------------------- - void RotationAffector::_affectParticles(ParticleSystem* pSystem, Real timeElapsed) - { - Real ds; - - // Rotation adjustments by time - ds = timeElapsed; - - Radian NewRotation; - - for (auto p : pSystem->_getActiveParticles()) - { - NewRotation = p->mRotation + (ds * p->mRotationSpeed); - p->setRotation( NewRotation ); - } - - } - //----------------------------------------------------------------------- - const Radian& RotationAffector::getRotationSpeedRangeStart(void) const - { - return mRotationSpeedRangeStart; - } - //----------------------------------------------------------------------- - const Radian& RotationAffector::getRotationSpeedRangeEnd(void) const - { - return mRotationSpeedRangeEnd; - } - //----------------------------------------------------------------------- - void RotationAffector::setRotationSpeedRangeStart(const Radian& val) - { - mRotationSpeedRangeStart = val; - } - //----------------------------------------------------------------------- - void RotationAffector::setRotationSpeedRangeEnd(const Radian& val ) - { - mRotationSpeedRangeEnd = val; - } - //----------------------------------------------------------------------- - const Radian& RotationAffector::getRotationRangeStart(void) const - { - return mRotationRangeStart; - } - //----------------------------------------------------------------------- - const Radian& RotationAffector::getRotationRangeEnd(void) const - { - return mRotationRangeEnd; - } - //----------------------------------------------------------------------- - void RotationAffector::setRotationRangeStart(const Radian& val) - { - mRotationRangeStart = val; - } - //----------------------------------------------------------------------- - void RotationAffector::setRotationRangeEnd(const Radian& val ) - { - mRotationRangeEnd = val; - } - //----------------------------------------------------------------------- - - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - // Command objects - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String RotationAffector::CmdRotationSpeedRangeEnd::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getRotationSpeedRangeEnd() ); - } - void RotationAffector::CmdRotationSpeedRangeEnd::doSet(void* target, const String& val) - { - static_cast(target)->setRotationSpeedRangeEnd(StringConverter::parseAngle(val)); - } - //----------------------------------------------------------------------- - String RotationAffector::CmdRotationSpeedRangeStart::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getRotationSpeedRangeStart() ); - } - void RotationAffector::CmdRotationSpeedRangeStart::doSet(void* target, const String& val) - { - static_cast(target)->setRotationSpeedRangeStart(StringConverter::parseAngle(val)); - } - - //----------------------------------------------------------------------- - String RotationAffector::CmdRotationRangeEnd::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getRotationRangeEnd() ); - } - void RotationAffector::CmdRotationRangeEnd::doSet(void* target, const String& val) - { - static_cast(target)->setRotationRangeEnd(StringConverter::parseAngle(val)); - } - //----------------------------------------------------------------------- - String RotationAffector::CmdRotationRangeStart::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getRotationRangeStart() ); - } - void RotationAffector::CmdRotationRangeStart::doSet(void* target, const String& val) - { - static_cast(target)->setRotationRangeStart(StringConverter::parseAngle(val)); - } -} - - - diff --git a/PlugIns/ParticleFX/src/OgreRotationAffectorFactory.h b/PlugIns/ParticleFX/src/OgreRotationAffectorFactory.h deleted file mode 100644 index f5755f1fe96..00000000000 --- a/PlugIns/ParticleFX/src/OgreRotationAffectorFactory.h +++ /dev/null @@ -1,49 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __RotationAffectorFactory_H__ -#define __RotationAffectorFactory_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffectorFactory.h" -#include "OgreRotationAffector.h" - -namespace Ogre { - - /** Factory class for RotationAffector. */ - class RotationAffectorFactory : public ParticleAffectorFactory - { - String getName() const override { return "Rotator"; } - - ParticleAffector* createAffector(ParticleSystem* psys) override { return new RotationAffector(psys); } - }; - - -} - -#endif - diff --git a/PlugIns/ParticleFX/src/OgreScaleAffector.cpp b/PlugIns/ParticleFX/src/OgreScaleAffector.cpp deleted file mode 100644 index ca72944679d..00000000000 --- a/PlugIns/ParticleFX/src/OgreScaleAffector.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreScaleAffector.h" -#include "OgreParticleSystem.h" -#include "OgreStringConverter.h" -#include "OgreParticle.h" - - -namespace Ogre { - - // init statics - ScaleAffector::CmdScaleAdjust ScaleAffector::msScaleCmd; - - static SimpleParamCommand - msScaleRangeCmd; - - //----------------------------------------------------------------------- - ScaleAffector::ScaleAffector(ParticleSystem* psys) - :ParticleAffector(psys), mScaleRange(Vector2::UNIT_SCALE) - { - mScaleAdj = 0; - mType = "Scaler"; - - // Init parameters - if (createParamDictionary("ScaleAffector")) - { - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter("rate", &msScaleCmd); - dict->addParameter("scale_range", &msScaleRangeCmd); - } - } - //----------------------------------------------------------------------- - void ScaleAffector::_initParticle(Particle* p) - { - float w = p->getOwnWidth(); - float h = p->getOwnHeight(); - float s = Math::RangeRandom(mScaleRange[0], mScaleRange[1]); - p->setDimensions(s * w, s * h); - } - //----------------------------------------------------------------------- - void ScaleAffector::_affectParticles(ParticleSystem* pSystem, Real timeElapsed) - { - // Scale adjustments by time - float ds = mScaleAdj * timeElapsed; - - for (auto p : pSystem->_getActiveParticles()) - { - float w = std::max(0.0f, p->getOwnWidth() + ds); - float h = std::max(0.0f, p->getOwnHeight() + ds); - p->setDimensions(w, h); - } - } - //----------------------------------------------------------------------- - void ScaleAffector::setAdjust( Real rate ) - { - mScaleAdj = rate; - } - //----------------------------------------------------------------------- - Real ScaleAffector::getAdjust(void) const - { - return mScaleAdj; - } - //----------------------------------------------------------------------- - - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - // Command objects - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String ScaleAffector::CmdScaleAdjust::doGet(const void* target) const - { - return StringConverter::toString( - static_cast(target)->getAdjust() ); - } - void ScaleAffector::CmdScaleAdjust::doSet(void* target, const String& val) - { - static_cast(target)->setAdjust( - StringConverter::parseReal(val)); - } - -} - - - diff --git a/PlugIns/ParticleFX/src/OgreScaleAffectorFactory.h b/PlugIns/ParticleFX/src/OgreScaleAffectorFactory.h deleted file mode 100644 index 99b0afdb831..00000000000 --- a/PlugIns/ParticleFX/src/OgreScaleAffectorFactory.h +++ /dev/null @@ -1,49 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __ScaleAffectorFactory_H__ -#define __ScaleAffectorFactory_H__ - -#include "OgreParticleFXPrerequisites.h" -#include "OgreParticleAffectorFactory.h" -#include "OgreScaleAffector.h" - -namespace Ogre { - - /** Factory class for ScaleAffector. */ - class ScaleAffectorFactory : public ParticleAffectorFactory - { - String getName() const override { return "Scaler"; } - - ParticleAffector* createAffector(ParticleSystem* psys) override { return new ScaleAffector(psys); } - }; - - -} - -#endif - diff --git a/PlugIns/ParticleFX/src/OgreTextureAnimatorAffector.cpp b/PlugIns/ParticleFX/src/OgreTextureAnimatorAffector.cpp deleted file mode 100644 index 63e72912c98..00000000000 --- a/PlugIns/ParticleFX/src/OgreTextureAnimatorAffector.cpp +++ /dev/null @@ -1,118 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT -#include "OgreTextureAnimatorAffector.h" -#include "OgreParticleSystem.h" -#include "OgreStringConverter.h" -#include "OgreParticle.h" - - -namespace Ogre { - -class CmdStart : public ParamCommand -{ -public: - String doGet(const void* target) const override - { - return StringConverter::toString( - static_cast(target)->getTexcoordStart()); - } - void doSet(void* target, const String& val) override - { - static_cast(target)->setTexcoordStart(StringConverter::parseInt(val)); - } -}; -class CmdCount : public ParamCommand -{ -public: - String doGet(const void* target) const override - { - return StringConverter::toString( - static_cast(target)->getTexcoordCount()); - } - void doSet(void* target, const String& val) override - { - static_cast(target)->setTexcoordCount(StringConverter::parseInt(val)); - } -}; -class CmdDuration : public ParamCommand -{ -public: - String doGet(const void* target) const override - { - return StringConverter::toString( - static_cast(target)->getDuration()); - } - void doSet(void* target, const String& val) override - { - static_cast(target)->setDuration(StringConverter::parseReal(val)); - } -}; -class CmdOffset : public ParamCommand -{ -public: - String doGet(const void* target) const override - { - return StringConverter::toString( - static_cast(target)->isRandomStartOffset()); - } - void doSet(void* target, const String& val) override - { - static_cast(target)->useRandomStartOffset(StringConverter::parseBool(val)); - } -}; - - // init statics - static CmdStart msStartCmd; - static CmdCount msCountCmd; - static CmdDuration msDurationCmd; - static CmdOffset msOffset; - - //----------------------------------------------------------------------- - TextureAnimatorAffector::TextureAnimatorAffector(ParticleSystem* psys) : ParticleAffector(psys) - { - mTexcoordStart = mTexcoordCount = mDuration = 0; - mRandomStartOffset = false; - mType = "TextureAnimator"; - - // Init parameters - if (createParamDictionary("TextureAnimatorAffector")) - { - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter(ParameterDef("texcoord_start", "", PT_INT), &msStartCmd); - dict->addParameter(ParameterDef("texcoord_count", "", PT_INT), &msCountCmd); - dict->addParameter(ParameterDef("duration", "", PT_REAL), &msDurationCmd); - dict->addParameter(ParameterDef("random_offset", "", PT_BOOL), &msOffset); - } - } - //----------------------------------------------------------------------- - void TextureAnimatorAffector::_initParticle(Particle* pParticle) - { - pParticle->mTexcoordIndex = 0; - - if (!mRandomStartOffset) - return; - - pParticle->mRandomTexcoordOffset = Math::UnitRandom() * mTexcoordCount; - pParticle->mTexcoordIndex = pParticle->mRandomTexcoordOffset; - } - - void TextureAnimatorAffector::_affectParticles(ParticleSystem* pSystem, Real timeElapsed) - { - // special case: randomly pick one cell in sprite-sheet - if(mDuration < 0) - return; - - for (auto p : pSystem->_getActiveParticles()) - { - float particle_time = 1.0f - (p->mTimeToLive / p->mTotalTimeToLive); - - float speed = mDuration ? (p->mTotalTimeToLive / mDuration) : 1.0f; - uint8 idx = uint8(particle_time * speed * mTexcoordCount + p->mRandomTexcoordOffset) % mTexcoordCount; - - p->mTexcoordIndex = idx + mTexcoordStart; - } - } -} diff --git a/PlugIns/RsImageCodec/CMakeLists.txt b/PlugIns/RsImageCodec/CMakeLists.txt deleted file mode 100644 index ecb4fd16c0e..00000000000 --- a/PlugIns/RsImageCodec/CMakeLists.txt +++ /dev/null @@ -1,43 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES ${PROJECT_BINARY_DIR}/include/OgreRsImageCodecExports.h) -set(SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreRsImageCodec.cpp") - -if(MSVC) - set(RS_LIBNAME "rsimage.lib") -else() - set(RS_LIBNAME "librsimage.a") -endif() -set(RS_LIB_PATH "${CMAKE_BINARY_DIR}/rs/release/${RS_LIBNAME}") - -add_custom_target(rsimage - COMMAND cargo build --release --target-dir=${CMAKE_BINARY_DIR}/rs/ - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/src - BYPRODUCTS "${RS_LIB_PATH}") - -add_library(Codec_RsImage ${OGRE_LIB_TYPE} ${HEADER_FILES} ${SOURCES}) -add_dependencies(Codec_RsImage rsimage) -target_link_libraries(Codec_RsImage PUBLIC OgreMain PRIVATE ${RS_LIB_PATH} ${CMAKE_DL_LIBS}) - -if(MSVC) - target_link_libraries(Codec_RsImage PRIVATE wsock32 ws2_32 bcrypt userenv Ntdll) -endif() - -target_include_directories(Codec_RsImage PUBLIC - "$" - $) - -ogre_config_framework(Codec_RsImage) -ogre_config_plugin(Codec_RsImage) -generate_export_header(Codec_RsImage - EXPORT_MACRO_NAME _OgreRsImageCodecExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreRsImageCodecExports.h) -install(FILES ${HEADER_FILES} DESTINATION include/OGRE/Plugins/RsImageCodec) diff --git a/PlugIns/RsImageCodec/include/OgreRsImageCodec.h b/PlugIns/RsImageCodec/include/OgreRsImageCodec.h deleted file mode 100644 index 930fdc1bd3e..00000000000 --- a/PlugIns/RsImageCodec/include/OgreRsImageCodec.h +++ /dev/null @@ -1,50 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#pragma once - -#include "OgreRsImageCodecExports.h" -#include "OgreImageCodec.h" -#include "OgrePlugin.h" - -namespace Ogre { - - /** \addtogroup Plugins Plugins - * @{ - */ - /** \defgroup RsImageCodec RsImageCodec - * %Codec for loading generic image formats (e.g. jpg, png) using image-rs - * - * This Codec is ideal for files, that you are not in control of. The Rust implementation is robust against malformed files. - * @{ - */ - class RsImageCodec : public ImageCodec - { - private: - String mType; - - typedef std::list RegisteredCodecList; - static RegisteredCodecList msCodecList; - - public: - RsImageCodec(const String &type); - virtual ~RsImageCodec() { } - - DataStreamPtr encode(const Any& input) const override; - void encodeToFile(const Any& input, const String& outFileName) const override; - void decode(const DataStreamPtr& input, const Any& output) const override; - - String getType() const override; - String magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const override; - - /// Static method to startup and register the codecs - _OgreRsImageCodecExport static void startup(void); - /// Static method to shutdown and unregister the codecs - _OgreRsImageCodecExport static void shutdown(void); - }; - /** @} */ - /** @} */ - -} // namespace Ogre \ No newline at end of file diff --git a/PlugIns/RsImageCodec/src/Cargo.toml b/PlugIns/RsImageCodec/src/Cargo.toml deleted file mode 100644 index 8c2d4d8b544..00000000000 --- a/PlugIns/RsImageCodec/src/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "rsimage" -version = "13.6.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -image = "0.24.7" - -[lib] -crate-type = ["staticlib"] -path = "rsimage.rs" \ No newline at end of file diff --git a/PlugIns/RsImageCodec/src/OgreRsImageCodec.cpp b/PlugIns/RsImageCodec/src/OgreRsImageCodec.cpp deleted file mode 100644 index 6510597d90e..00000000000 --- a/PlugIns/RsImageCodec/src/OgreRsImageCodec.cpp +++ /dev/null @@ -1,197 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#include "OgreRsImageCodec.h" -#include "OgreLogManager.h" -#include "OgreDataStream.h" -#include "OgreImage.h" - -enum ColorType -{ - /// Pixel is 8-bit luminance - L8, - /// Pixel is 8-bit luminance with an alpha channel - La8, - /// Pixel contains 8-bit R, G and B channels - Rgb8, - /// Pixel is 8-bit RGB with an alpha channel - Rgba8, - /// Pixel is 16-bit luminance - L16, - /// Pixel is 16-bit luminance with an alpha channel - La16, - /// Pixel is 16-bit RGB - Rgb16, - /// Pixel is 16-bit RGBA - Rgba16, - /// Pixel is 32-bit float RGB - Rgb32F, - /// Pixel is 32-bit float RGBA - Rgba32F -}; - -extern "C" -{ - void rs_image_decode(const char* buf, size_t len, const char* ext, uint32_t* w, uint32_t* h, ColorType* t, - uint8_t** out, size_t* out_len); - void rs_image_encode(uint8_t* buf, size_t len, uint32_t w, uint32_t h, ColorType t, const char* ext, uint8_t** out, - size_t* out_len); - void rs_vec_free(uint8_t* ptr, size_t len); -} - -namespace Ogre -{ - -RsImageCodec::RegisteredCodecList RsImageCodec::msCodecList; -//--------------------------------------------------------------------- -void RsImageCodec::startup(void) -{ - // Register codecs - String exts = "jpeg,jpg,png,bmp,gif,tiff,tga,exr"; - StringVector extsVector = StringUtil::split(exts, ","); - for (auto& v : extsVector) - { - ImageCodec* codec = OGRE_NEW RsImageCodec(v); - msCodecList.push_back(codec); - Codec::registerCodec(codec); - } - - LogManager::getSingleton().logMessage("image-rs loader - supported formats: " + exts); -} -//--------------------------------------------------------------------- -void RsImageCodec::shutdown(void) -{ - for (auto& i : msCodecList) - { - Codec::unregisterCodec(i); - OGRE_DELETE i; - } - msCodecList.clear(); -} -//--------------------------------------------------------------------- -RsImageCodec::RsImageCodec(const String& type) : mType(type) {} -//--------------------------------------------------------------------- -DataStreamPtr RsImageCodec::encode(const Any& input) const -{ - Image* image = any_cast(input); - PixelFormat format = image->getFormat(); - uchar* inputData = image->getData(); - - ColorType t; - - switch (format) - { - case PF_BYTE_L: - t = L8; - break; - case PF_BYTE_LA: - t = La8; - break; - case PF_BYTE_RGB: - t = Rgb8; - break; - case PF_BYTE_RGBA: - t = Rgba8; - break; - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Unsupported image format"); - break; - } - - size_t len; - uchar* data = NULL; - - rs_image_encode(inputData, image->getSize(), image->getWidth(), image->getHeight(), t, mType.c_str(), &data, &len); - - if (!data) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Error encoding image"); - } - - auto stream = std::make_shared(len); - memcpy(stream->getPtr(), data, len); // avoid messing with rust memory allocator - rs_vec_free(data, len); - - return stream; -} -//--------------------------------------------------------------------- -void RsImageCodec::encodeToFile(const Any& input, const String& outFileName) const -{ -#if OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN - MemoryDataStreamPtr data = static_pointer_cast(encode(input)); - std::ofstream f(outFileName.c_str(), std::ios::out | std::ios::binary); - - if (!f.is_open()) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "could not open file " + outFileName); - } - - f.write((char*)data->getPtr(), data->size()); -#endif -} -//--------------------------------------------------------------------- -void RsImageCodec::decode(const DataStreamPtr& input, const Any& output) const -{ - auto image = any_cast(output); - String contents = input->getAsString(); - - uint width, height; - ColorType t; - uchar* pixelData = NULL; - size_t dataLen; - - rs_image_decode(contents.data(), contents.size(), mType.c_str(), &width, &height, &t, &pixelData, &dataLen); - - if (!pixelData) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Error decoding image"); - } - - PixelFormat format = PF_UNKNOWN; - switch (t) - { - case L8: - format = PF_BYTE_L; - break; - case La8: - format = PF_BYTE_LA; - break; - case Rgb8: - format = PF_BYTE_RGB; - break; - case Rgba8: - format = PF_BYTE_RGBA; - break; - case L16: - format = PF_L16; - break; - case Rgb32F: - format = PF_FLOAT32_RGB; - break; - case Rgba32F: - format = PF_FLOAT32_RGBA; - break; - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Unsupported image format"); - break; - } - - image->create(format, width, height); - memcpy(image->getData(), pixelData, dataLen); // avoid messing with rust memory allocator - rs_vec_free(pixelData, dataLen); -} -//--------------------------------------------------------------------- -String RsImageCodec::getType() const { return mType; } -//--------------------------------------------------------------------- -String RsImageCodec::magicNumberToFileExt(const char* magicNumberPtr, size_t maxbytes) const { return BLANKSTRING; } - -#ifndef OGRE_STATIC_LIB -extern "C" void _OgreRsImageCodecExport dllStartPlugin(); -extern "C" void _OgreRsImageCodecExport dllStopPlugin(); - -extern "C" void _OgreRsImageCodecExport dllStartPlugin() { RsImageCodec::startup(); } -extern "C" void _OgreRsImageCodecExport dllStopPlugin() { RsImageCodec::shutdown(); } -#endif -} // namespace Ogre diff --git a/PlugIns/RsImageCodec/src/rsimage.rs b/PlugIns/RsImageCodec/src/rsimage.rs deleted file mode 100644 index 5a3623ba885..00000000000 --- a/PlugIns/RsImageCodec/src/rsimage.rs +++ /dev/null @@ -1,80 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -use std::ffi::CStr; -use std::os::raw::c_char; -use std::io::Cursor; -use std::slice; - -#[no_mangle] -pub extern "C" fn rs_image_decode( - input: *const u8, - input_length: usize, - ext: *const c_char, - width: *mut u32, - height: *mut u32, - colortype: *mut u32, - data: *mut *mut u8, - data_len: *mut usize, -) { - let slice = unsafe { slice::from_raw_parts(input, input_length) }; - - let ext_str = unsafe { CStr::from_ptr(ext).to_str().unwrap() }; - let format = image::ImageFormat::from_extension(ext_str).unwrap(); - - let img = image::load_from_memory_with_format(slice, format).unwrap(); - - unsafe { - *width = img.width(); - *height = img.height(); - *colortype = img.color() as u32; - } - - let mut bytes = img.into_bytes(); - unsafe { - *data = bytes.as_mut_ptr(); - *data_len = bytes.len(); - } - std::mem::forget(bytes); -} - -#[no_mangle] -pub extern "C" fn rs_image_encode( - input: *const u8, - input_length: usize, - width: u32, - height: u32, - t: u32, - ext: *const c_char, - data: *mut *mut u8, - data_len: *mut usize, -) { - let color = match t { - 0 => image::ColorType::L8, - 1 => image::ColorType::La8, - 2 => image::ColorType::Rgb8, - 3 => image::ColorType::Rgba8, - _ => return, - }; - let slice = unsafe { slice::from_raw_parts(input, input_length) }; - - let ext_str = unsafe { CStr::from_ptr(ext).to_str().unwrap() }; - let format = image::ImageFormat::from_extension(ext_str).unwrap(); - - let mut buf = Cursor::new(Vec::new()); - - image::write_buffer_with_format(&mut buf, slice, width, height, color, format).unwrap(); - let mut bytes = buf.into_inner(); - unsafe { - *data = bytes.as_mut_ptr(); - *data_len = bytes.len(); - } - std::mem::forget(bytes); -} - -#[no_mangle] -pub unsafe extern "C" fn rs_vec_free(ptr: *mut u8, len: usize) { - Vec::from_raw_parts(ptr, len, len); -} diff --git a/PlugIns/STBICodec/CMakeLists.txt b/PlugIns/STBICodec/CMakeLists.txt deleted file mode 100644 index 10283f51e26..00000000000 --- a/PlugIns/STBICodec/CMakeLists.txt +++ /dev/null @@ -1,41 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES ${PROJECT_BINARY_DIR}/include/OgreSTBICodecExports.h) -set(SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/src/OgreSTBICodec.cpp") - -if(UNIX) - set_source_files_properties(src/OgreSTBICodec.cpp PROPERTIES - COMPILE_FLAGS "-Wno-cast-qual -Wno-unused-function -Wno-missing-declarations -Wno-type-limits") -endif() - -add_library(Codec_STBI ${OGRE_LIB_TYPE} ${HEADER_FILES} ${SOURCES}) -target_link_libraries(Codec_STBI PUBLIC OgreMain) - -target_include_directories(Codec_STBI PUBLIC - "$" - $) - -if(CMAKE_COMPILER_IS_GNUCXX) - # workaround gcc5 bug on Ubuntu 16.04 regarding __builtin_cpu_supports - target_link_libraries(Codec_STBI PRIVATE gcc) -endif() - -if(ZLIB_FOUND) - target_compile_definitions(Codec_STBI PRIVATE HAVE_ZLIB) - target_link_libraries(Codec_STBI PRIVATE ZLIB::ZLIB) -endif() - -ogre_config_framework(Codec_STBI) -ogre_config_plugin(Codec_STBI) -generate_export_header(Codec_STBI - EXPORT_MACRO_NAME _OgreSTBICodecExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreSTBICodecExports.h) -install(FILES ${HEADER_FILES} DESTINATION include/OGRE/Plugins/STBICodec) diff --git a/PlugIns/STBICodec/include/OgreSTBICodec.h b/PlugIns/STBICodec/include/OgreSTBICodec.h deleted file mode 100644 index 10fb688a560..00000000000 --- a/PlugIns/STBICodec/include/OgreSTBICodec.h +++ /dev/null @@ -1,76 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __STBICodec_H__ -#define __STBICodec_H__ - -#include "OgreSTBICodecExports.h" -#include "OgreImageCodec.h" -#include "OgrePlugin.h" - -namespace Ogre { - - /** \addtogroup Plugins Plugins - * @{ - */ - /** \defgroup STBIImageCodec STBIImageCodec - * %Codec for loading generic image formats (e.g. jpg, png) using [stb_image](https://github.com/nothings/stb) - * - * This Codec is ideal for files, that you are in control of. There are no external dependencies and no superfluous pixel conversions. - * The downside is that not all format variants are supported and the code is more vulnerable to malicious files. - * @{ - */ - class STBIImageCodec : public ImageCodec - { - private: - String mType; - - typedef std::list RegisteredCodecList; - static RegisteredCodecList msCodecList; - - public: - STBIImageCodec(const String &type); - virtual ~STBIImageCodec() { } - - DataStreamPtr encode(const Any& input) const override; - void encodeToFile(const Any& input, const String& outFileName) const override; - void decode(const DataStreamPtr& input, const Any& output) const override; - - String getType() const override; - String magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const override; - - /// Static method to startup and register the codecs - _OgreSTBICodecExport static void startup(void); - /// Static method to shutdown and unregister the codecs - _OgreSTBICodecExport static void shutdown(void); - }; - /** @} */ - /** @} */ - -} // namespace - -#endif diff --git a/PlugIns/STBICodec/src/OgreSTBICodec.cpp b/PlugIns/STBICodec/src/OgreSTBICodec.cpp deleted file mode 100644 index f89e9a16c29..00000000000 --- a/PlugIns/STBICodec/src/OgreSTBICodec.cpp +++ /dev/null @@ -1,230 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreSTBICodec.h" -#include "OgreLogManager.h" -#include "OgreDataStream.h" -#include "OgreImage.h" - -#include "OgrePlatformInformation.h" - -#if __OGRE_HAVE_NEON -#define STBI_NEON -#endif - -#define STBI_NO_STDIO -#define STB_IMAGE_IMPLEMENTATION -#define STB_IMAGE_STATIC -#include "stbi/stb_image.h" - -#ifdef HAVE_ZLIB -#include -static Ogre::uchar* custom_zlib_compress(Ogre::uchar* data, int data_len, int* out_len, int /*quality*/) -{ - unsigned long destLen = compressBound(data_len); - Ogre::uchar* dest = (Ogre::uchar*)malloc(destLen); - int ret = compress(dest, &destLen, data, data_len); // use default quality - if (ret != Z_OK) - { - free(dest); - OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR, "compress failed"); - } - - *out_len = destLen; - return dest; -} -#define STBIW_ZLIB_COMPRESS custom_zlib_compress -#endif - -#define STB_IMAGE_WRITE_IMPLEMENTATION -#define STBI_WRITE_NO_STDIO -#include "stbi/stb_image_write.h" - -namespace Ogre { - - STBIImageCodec::RegisteredCodecList STBIImageCodec::msCodecList; - //--------------------------------------------------------------------- - void STBIImageCodec::startup(void) - { - stbi_convert_iphone_png_to_rgb(1); - stbi_set_unpremultiply_on_load(1); - - LogManager::getSingleton().logMessage("stb_image - v2.28 - public domain image loader"); - - // Register codecs - String exts = "jpeg,jpg,png,bmp,psd,tga,gif,pic,ppm,pgm,hdr"; - StringVector extsVector = StringUtil::split(exts, ","); - for (auto & v : extsVector) - { - ImageCodec* codec = OGRE_NEW STBIImageCodec(v); - msCodecList.push_back(codec); - Codec::registerCodec(codec); - } - - LogManager::getSingleton().logMessage("Supported formats: " + exts); - } - //--------------------------------------------------------------------- - void STBIImageCodec::shutdown(void) - { - for (auto & i : msCodecList) - { - Codec::unregisterCodec(i); - OGRE_DELETE i; - } - msCodecList.clear(); - } - //--------------------------------------------------------------------- - STBIImageCodec::STBIImageCodec(const String &type): - mType(type) - { - } - //--------------------------------------------------------------------- - DataStreamPtr STBIImageCodec::encode(const Any& input) const - { - if(mType != "png") { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, - "currently only encoding to PNG supported", - "STBIImageCodec::encode" ) ; - } - - Image* image = any_cast(input); - PixelFormat format = image->getFormat(); - uchar* inputData = image->getData(); - - // Convert image data to ABGR format for STBI (unless it's already compatible) - uchar* tempData = 0; - if(format != Ogre::PF_A8B8G8R8 && format != PF_B8G8R8 && format != PF_BYTE_LA && - format != PF_L8 && format != PF_R8) - { - format = Ogre::PF_A8B8G8R8; - size_t tempDataSize = image->getSize(); - tempData = OGRE_ALLOC_T(unsigned char, tempDataSize, Ogre::MEMCATEGORY_GENERAL); - Ogre::PixelBox pbOut(image->getPixelBox(), format, tempData); - PixelUtil::bulkPixelConversion(image->getPixelBox(), pbOut); - - inputData = tempData; - } - - // Save to PNG - int channels = PixelUtil::getComponentCount(format); - int len; - uchar* data = stbi_write_png_to_mem(inputData, image->getRowSpan(), image->getWidth(), image->getHeight(), channels, &len); - - if(tempData) - { - OGRE_FREE(tempData, MEMCATEGORY_GENERAL); - } - - if (!data) { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Error encoding image: " + String(stbi_failure_reason()), - "STBIImageCodec::encode"); - } - - return DataStreamPtr(new MemoryDataStream(data, len, true)); - } - //--------------------------------------------------------------------- - void STBIImageCodec::encodeToFile(const Any& input, const String& outFileName) const - { -#if OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN - MemoryDataStreamPtr data = static_pointer_cast(encode(input)); - std::ofstream f(outFileName.c_str(), std::ios::out | std::ios::binary); - - if (!f.is_open()) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "could not open file " + outFileName); - } - - f.write((char*)data->getPtr(), data->size()); -#endif - } - //--------------------------------------------------------------------- - void STBIImageCodec::decode(const DataStreamPtr& input, const Any& output) const - { - auto image = any_cast(output); - String contents = input->getAsString(); - - int width, height, components; - stbi_uc* pixelData = stbi_load_from_memory((const uchar*)contents.data(), - static_cast(contents.size()), &width, &height, &components, 0); - - if (!pixelData) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Error decoding image: " + String(stbi_failure_reason()), - "STBIImageCodec::decode"); - } - - PixelFormat format = PF_UNKNOWN; - switch( components ) - { - case 1: - format = PF_BYTE_L; - break; - case 2: - format = PF_BYTE_LA; - break; - case 3: - format = PF_BYTE_RGB; - break; - case 4: - format = PF_BYTE_RGBA; - break; - default: - stbi_image_free(pixelData); - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Only 1..4 channels supported"); - break; - } - - image->loadDynamicImage(pixelData, width, height, 1, format, true); - } - //--------------------------------------------------------------------- - String STBIImageCodec::getType() const - { - return mType; - } - //--------------------------------------------------------------------- - String STBIImageCodec::magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const - { - return BLANKSTRING; - } - -#ifndef OGRE_STATIC_LIB - extern "C" void _OgreSTBICodecExport dllStartPlugin(); - extern "C" void _OgreSTBICodecExport dllStopPlugin(); - - extern "C" void _OgreSTBICodecExport dllStartPlugin() - { - STBIImageCodec::startup(); - } - extern "C" void _OgreSTBICodecExport dllStopPlugin() - { - STBIImageCodec::shutdown(); - } -#endif -} diff --git a/PlugIns/STBICodec/src/stbi/stb_image.h b/PlugIns/STBICodec/src/stbi/stb_image.h deleted file mode 100644 index 5e807a0a6e7..00000000000 --- a/PlugIns/STBICodec/src/stbi/stb_image.h +++ /dev/null @@ -1,7987 +0,0 @@ -/* stb_image - v2.28 - public domain image loader - http://nothings.org/stb - no warranty implied; use at your own risk - - Do this: - #define STB_IMAGE_IMPLEMENTATION - before you include this file in *one* C or C++ file to create the implementation. - - // i.e. it should look like this: - #include ... - #include ... - #include ... - #define STB_IMAGE_IMPLEMENTATION - #include "stb_image.h" - - You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. - And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free - - - QUICK NOTES: - Primarily of interest to game developers and other people who can - avoid problematic images and only need the trivial interface - - JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) - PNG 1/2/4/8/16-bit-per-channel - - TGA (not sure what subset, if a subset) - BMP non-1bpp, non-RLE - PSD (composited view only, no extra channels, 8/16 bit-per-channel) - - GIF (*comp always reports as 4-channel) - HDR (radiance rgbE format) - PIC (Softimage PIC) - PNM (PPM and PGM binary only) - - Animated GIF still needs a proper API, but here's one way to do it: - http://gist.github.com/urraka/685d9a6340b26b830d49 - - - decode from memory or through FILE (define STBI_NO_STDIO to remove code) - - decode from arbitrary I/O callbacks - - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON) - - Full documentation under "DOCUMENTATION" below. - - -LICENSE - - See end of file for license information. - -RECENT REVISION HISTORY: - - 2.28 (2023-01-29) many error fixes, security errors, just tons of stuff - 2.27 (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes - 2.26 (2020-07-13) many minor fixes - 2.25 (2020-02-02) fix warnings - 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically - 2.23 (2019-08-11) fix clang static analysis warning - 2.22 (2019-03-04) gif fixes, fix warnings - 2.21 (2019-02-25) fix typo in comment - 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs - 2.19 (2018-02-11) fix warning - 2.18 (2018-01-30) fix warnings - 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings - 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes - 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC - 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs - 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes - 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes - 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 - RGB-format JPEG; remove white matting in PSD; - allocate large structures on the stack; - correct channel count for PNG & BMP - 2.10 (2016-01-22) avoid warning introduced in 2.09 - 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED - - See end of file for full revision history. - - - ============================ Contributors ========================= - - Image formats Extensions, features - Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) - Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) - Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) - Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) - Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) - Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) - Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) - github:urraka (animated gif) Junggon Kim (PNM comments) - Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA) - socks-the-fox (16-bit PNG) - Jeremy Sawicki (handle all ImageNet JPGs) - Optimizations & bugfixes Mikhail Morozov (1-bit BMP) - Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query) - Arseny Kapoulkine Simon Breuss (16-bit PNM) - John-Mark Allen - Carmelo J Fdez-Aguera - - Bug & warning fixes - Marc LeBlanc David Woo Guillaume George Martins Mozeiko - Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski - Phil Jordan Dave Moore Roy Eltham - Hayaki Saito Nathan Reed Won Chun - Luke Graham Johan Duparc Nick Verigakis the Horde3D community - Thomas Ruf Ronny Chevalier github:rlyeh - Janez Zemva John Bartholomew Michal Cichon github:romigrou - Jonathan Blow Ken Hamada Tero Hanninen github:svdijk - Eugene Golushkov Laurent Gomila Cort Stratton github:snagar - Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex - Cass Everitt Ryamond Barbiero github:grim210 - Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw - Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus - Josh Tobin Neil Bickford Matthew Gregan github:poppolopoppo - Julian Raschke Gregory Mullen Christian Floisand github:darealshinji - Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007 - Brad Weinberger Matvey Cherevko github:mosra - Luca Sas Alexander Veselov Zack Middleton [reserved] - Ryan C. Gordon [reserved] [reserved] - DO NOT ADD YOUR NAME HERE - - Jacko Dirks - - To add your name to the credits, pick a random blank space in the middle and fill it. - 80% of merge conflicts on stb PRs are due to people adding their name at the end - of the credits. -*/ - -#ifndef STBI_INCLUDE_STB_IMAGE_H -#define STBI_INCLUDE_STB_IMAGE_H - -// DOCUMENTATION -// -// Limitations: -// - no 12-bit-per-channel JPEG -// - no JPEGs with arithmetic coding -// - GIF always returns *comp=4 -// -// Basic usage (see HDR discussion below for HDR usage): -// int x,y,n; -// unsigned char *data = stbi_load(filename, &x, &y, &n, 0); -// // ... process data if not NULL ... -// // ... x = width, y = height, n = # 8-bit components per pixel ... -// // ... replace '0' with '1'..'4' to force that many components per pixel -// // ... but 'n' will always be the number that it would have been if you said 0 -// stbi_image_free(data); -// -// Standard parameters: -// int *x -- outputs image width in pixels -// int *y -- outputs image height in pixels -// int *channels_in_file -- outputs # of image components in image file -// int desired_channels -- if non-zero, # of image components requested in result -// -// The return value from an image loader is an 'unsigned char *' which points -// to the pixel data, or NULL on an allocation failure or if the image is -// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels, -// with each pixel consisting of N interleaved 8-bit components; the first -// pixel pointed to is top-left-most in the image. There is no padding between -// image scanlines or between pixels, regardless of format. The number of -// components N is 'desired_channels' if desired_channels is non-zero, or -// *channels_in_file otherwise. If desired_channels is non-zero, -// *channels_in_file has the number of components that _would_ have been -// output otherwise. E.g. if you set desired_channels to 4, you will always -// get RGBA output, but you can check *channels_in_file to see if it's trivially -// opaque because e.g. there were only 3 channels in the source image. -// -// An output image with N components has the following components interleaved -// in this order in each pixel: -// -// N=#comp components -// 1 grey -// 2 grey, alpha -// 3 red, green, blue -// 4 red, green, blue, alpha -// -// If image loading fails for any reason, the return value will be NULL, -// and *x, *y, *channels_in_file will be unchanged. The function -// stbi_failure_reason() can be queried for an extremely brief, end-user -// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS -// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly -// more user-friendly ones. -// -// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. -// -// To query the width, height and component count of an image without having to -// decode the full file, you can use the stbi_info family of functions: -// -// int x,y,n,ok; -// ok = stbi_info(filename, &x, &y, &n); -// // returns ok=1 and sets x, y, n if image is a supported format, -// // 0 otherwise. -// -// Note that stb_image pervasively uses ints in its public API for sizes, -// including sizes of memory buffers. This is now part of the API and thus -// hard to change without causing breakage. As a result, the various image -// loaders all have certain limits on image size; these differ somewhat -// by format but generally boil down to either just under 2GB or just under -// 1GB. When the decoded image would be larger than this, stb_image decoding -// will fail. -// -// Additionally, stb_image will reject image files that have any of their -// dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS, -// which defaults to 2**24 = 16777216 pixels. Due to the above memory limit, -// the only way to have an image with such dimensions load correctly -// is for it to have a rather extreme aspect ratio. Either way, the -// assumption here is that such larger images are likely to be malformed -// or malicious. If you do need to load an image with individual dimensions -// larger than that, and it still fits in the overall size limit, you can -// #define STBI_MAX_DIMENSIONS on your own to be something larger. -// -// =========================================================================== -// -// UNICODE: -// -// If compiling for Windows and you wish to use Unicode filenames, compile -// with -// #define STBI_WINDOWS_UTF8 -// and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert -// Windows wchar_t filenames to utf8. -// -// =========================================================================== -// -// Philosophy -// -// stb libraries are designed with the following priorities: -// -// 1. easy to use -// 2. easy to maintain -// 3. good performance -// -// Sometimes I let "good performance" creep up in priority over "easy to maintain", -// and for best performance I may provide less-easy-to-use APIs that give higher -// performance, in addition to the easy-to-use ones. Nevertheless, it's important -// to keep in mind that from the standpoint of you, a client of this library, -// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all. -// -// Some secondary priorities arise directly from the first two, some of which -// provide more explicit reasons why performance can't be emphasized. -// -// - Portable ("ease of use") -// - Small source code footprint ("easy to maintain") -// - No dependencies ("ease of use") -// -// =========================================================================== -// -// I/O callbacks -// -// I/O callbacks allow you to read from arbitrary sources, like packaged -// files or some other source. Data read from callbacks are processed -// through a small internal buffer (currently 128 bytes) to try to reduce -// overhead. -// -// The three functions you must define are "read" (reads some bytes of data), -// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). -// -// =========================================================================== -// -// SIMD support -// -// The JPEG decoder will try to automatically use SIMD kernels on x86 when -// supported by the compiler. For ARM Neon support, you must explicitly -// request it. -// -// (The old do-it-yourself SIMD API is no longer supported in the current -// code.) -// -// On x86, SSE2 will automatically be used when available based on a run-time -// test; if not, the generic C versions are used as a fall-back. On ARM targets, -// the typical path is to have separate builds for NEON and non-NEON devices -// (at least this is true for iOS and Android). Therefore, the NEON support is -// toggled by a build flag: define STBI_NEON to get NEON loops. -// -// If for some reason you do not want to use any of SIMD code, or if -// you have issues compiling it, you can disable it entirely by -// defining STBI_NO_SIMD. -// -// =========================================================================== -// -// HDR image support (disable by defining STBI_NO_HDR) -// -// stb_image supports loading HDR images in general, and currently the Radiance -// .HDR file format specifically. You can still load any file through the existing -// interface; if you attempt to load an HDR file, it will be automatically remapped -// to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; -// both of these constants can be reconfigured through this interface: -// -// stbi_hdr_to_ldr_gamma(2.2f); -// stbi_hdr_to_ldr_scale(1.0f); -// -// (note, do not use _inverse_ constants; stbi_image will invert them -// appropriately). -// -// Additionally, there is a new, parallel interface for loading files as -// (linear) floats to preserve the full dynamic range: -// -// float *data = stbi_loadf(filename, &x, &y, &n, 0); -// -// If you load LDR images through this interface, those images will -// be promoted to floating point values, run through the inverse of -// constants corresponding to the above: -// -// stbi_ldr_to_hdr_scale(1.0f); -// stbi_ldr_to_hdr_gamma(2.2f); -// -// Finally, given a filename (or an open file or memory block--see header -// file for details) containing image data, you can query for the "most -// appropriate" interface to use (that is, whether the image is HDR or -// not), using: -// -// stbi_is_hdr(char *filename); -// -// =========================================================================== -// -// iPhone PNG support: -// -// We optionally support converting iPhone-formatted PNGs (which store -// premultiplied BGRA) back to RGB, even though they're internally encoded -// differently. To enable this conversion, call -// stbi_convert_iphone_png_to_rgb(1). -// -// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per -// pixel to remove any premultiplied alpha *only* if the image file explicitly -// says there's premultiplied data (currently only happens in iPhone images, -// and only if iPhone convert-to-rgb processing is on). -// -// =========================================================================== -// -// ADDITIONAL CONFIGURATION -// -// - You can suppress implementation of any of the decoders to reduce -// your code footprint by #defining one or more of the following -// symbols before creating the implementation. -// -// STBI_NO_JPEG -// STBI_NO_PNG -// STBI_NO_BMP -// STBI_NO_PSD -// STBI_NO_TGA -// STBI_NO_GIF -// STBI_NO_HDR -// STBI_NO_PIC -// STBI_NO_PNM (.ppm and .pgm) -// -// - You can request *only* certain decoders and suppress all other ones -// (this will be more forward-compatible, as addition of new decoders -// doesn't require you to disable them explicitly): -// -// STBI_ONLY_JPEG -// STBI_ONLY_PNG -// STBI_ONLY_BMP -// STBI_ONLY_PSD -// STBI_ONLY_TGA -// STBI_ONLY_GIF -// STBI_ONLY_HDR -// STBI_ONLY_PIC -// STBI_ONLY_PNM (.ppm and .pgm) -// -// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still -// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB -// -// - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater -// than that size (in either width or height) without further processing. -// This is to let programs in the wild set an upper bound to prevent -// denial-of-service attacks on untrusted data, as one could generate a -// valid image of gigantic dimensions and force stb_image to allocate a -// huge block of memory and spend disproportionate time decoding it. By -// default this is set to (1 << 24), which is 16777216, but that's still -// very big. - -#ifndef STBI_NO_STDIO -#include -#endif // STBI_NO_STDIO - -#define STBI_VERSION 1 - -enum -{ - STBI_default = 0, // only used for desired_channels - - STBI_grey = 1, - STBI_grey_alpha = 2, - STBI_rgb = 3, - STBI_rgb_alpha = 4 -}; - -#include -typedef unsigned char stbi_uc; -typedef unsigned short stbi_us; - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef STBIDEF -#ifdef STB_IMAGE_STATIC -#define STBIDEF static -#else -#define STBIDEF extern -#endif -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// PRIMARY API - works on images of any type -// - -// -// load image by filename, open file, or memory buffer -// - -typedef struct -{ - int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read - void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative - int (*eof) (void *user); // returns nonzero if we are at end of file/data -} stbi_io_callbacks; - -//////////////////////////////////// -// -// 8-bits-per-channel interface -// - -STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels); -STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels); - -#ifndef STBI_NO_STDIO -STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); -STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); -// for stbi_load_from_file, file pointer is left pointing immediately after image -#endif - -#ifndef STBI_NO_GIF -STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp); -#endif - -#ifdef STBI_WINDOWS_UTF8 -STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); -#endif - -//////////////////////////////////// -// -// 16-bits-per-channel interface -// - -STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); -STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); - -#ifndef STBI_NO_STDIO -STBIDEF stbi_us *stbi_load_16 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); -STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); -#endif - -//////////////////////////////////// -// -// float-per-channel interface -// -#ifndef STBI_NO_LINEAR - STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); - STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); - - #ifndef STBI_NO_STDIO - STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); - STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); - #endif -#endif - -#ifndef STBI_NO_HDR - STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); - STBIDEF void stbi_hdr_to_ldr_scale(float scale); -#endif // STBI_NO_HDR - -#ifndef STBI_NO_LINEAR - STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); - STBIDEF void stbi_ldr_to_hdr_scale(float scale); -#endif // STBI_NO_LINEAR - -// stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR -STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); -STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); -#ifndef STBI_NO_STDIO -STBIDEF int stbi_is_hdr (char const *filename); -STBIDEF int stbi_is_hdr_from_file(FILE *f); -#endif // STBI_NO_STDIO - - -// get a VERY brief reason for failure -// on most compilers (and ALL modern mainstream compilers) this is threadsafe -STBIDEF const char *stbi_failure_reason (void); - -// free the loaded image -- this is just free() -STBIDEF void stbi_image_free (void *retval_from_stbi_load); - -// get image dimensions & components without fully decoding -STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); -STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); -STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len); -STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user); - -#ifndef STBI_NO_STDIO -STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); -STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); -STBIDEF int stbi_is_16_bit (char const *filename); -STBIDEF int stbi_is_16_bit_from_file(FILE *f); -#endif - - - -// for image formats that explicitly notate that they have premultiplied alpha, -// we just return the colors as stored in the file. set this flag to force -// unpremultiplication. results are undefined if the unpremultiply overflow. -STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); - -// indicate whether we should process iphone images back to canonical format, -// or just pass them through "as-is" -STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); - -// flip the image vertically, so the first pixel in the output array is the bottom left -STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); - -// as above, but only applies to images loaded on the thread that calls the function -// this function is only available if your compiler supports thread-local variables; -// calling it will fail to link if your compiler doesn't -STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply); -STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert); -STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip); - -// ZLIB client - used by PNG, available for other purposes - -STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); -STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header); -STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); -STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); - -STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); -STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); - - -#ifdef __cplusplus -} -#endif - -// -// -//// end header file ///////////////////////////////////////////////////// -#endif // STBI_INCLUDE_STB_IMAGE_H - -#ifdef STB_IMAGE_IMPLEMENTATION - -#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ - || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ - || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ - || defined(STBI_ONLY_ZLIB) - #ifndef STBI_ONLY_JPEG - #define STBI_NO_JPEG - #endif - #ifndef STBI_ONLY_PNG - #define STBI_NO_PNG - #endif - #ifndef STBI_ONLY_BMP - #define STBI_NO_BMP - #endif - #ifndef STBI_ONLY_PSD - #define STBI_NO_PSD - #endif - #ifndef STBI_ONLY_TGA - #define STBI_NO_TGA - #endif - #ifndef STBI_ONLY_GIF - #define STBI_NO_GIF - #endif - #ifndef STBI_ONLY_HDR - #define STBI_NO_HDR - #endif - #ifndef STBI_ONLY_PIC - #define STBI_NO_PIC - #endif - #ifndef STBI_ONLY_PNM - #define STBI_NO_PNM - #endif -#endif - -#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) -#define STBI_NO_ZLIB -#endif - - -#include -#include // ptrdiff_t on osx -#include -#include -#include - -#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) -#include // ldexp, pow -#endif - -#ifndef STBI_NO_STDIO -#include -#endif - -#ifndef STBI_ASSERT -#include -#define STBI_ASSERT(x) assert(x) -#endif - -#ifdef __cplusplus -#define STBI_EXTERN extern "C" -#else -#define STBI_EXTERN extern -#endif - - -#ifndef _MSC_VER - #ifdef __cplusplus - #define stbi_inline inline - #else - #define stbi_inline - #endif -#else - #define stbi_inline __forceinline -#endif - -#ifndef STBI_NO_THREAD_LOCALS - #if defined(__cplusplus) && __cplusplus >= 201103L - #define STBI_THREAD_LOCAL thread_local - #elif defined(__GNUC__) && __GNUC__ < 5 - #define STBI_THREAD_LOCAL __thread - #elif defined(_MSC_VER) - #define STBI_THREAD_LOCAL __declspec(thread) - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) - #define STBI_THREAD_LOCAL _Thread_local - #endif - - #ifndef STBI_THREAD_LOCAL - #if defined(__GNUC__) - #define STBI_THREAD_LOCAL __thread - #endif - #endif -#endif - -#if defined(_MSC_VER) || defined(__SYMBIAN32__) -typedef unsigned short stbi__uint16; -typedef signed short stbi__int16; -typedef unsigned int stbi__uint32; -typedef signed int stbi__int32; -#else -#include -typedef uint16_t stbi__uint16; -typedef int16_t stbi__int16; -typedef uint32_t stbi__uint32; -typedef int32_t stbi__int32; -#endif - -// should produce compiler error if size is wrong -typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; - -#ifdef _MSC_VER -#define STBI_NOTUSED(v) (void)(v) -#else -#define STBI_NOTUSED(v) (void)sizeof(v) -#endif - -#ifdef _MSC_VER -#define STBI_HAS_LROTL -#endif - -#ifdef STBI_HAS_LROTL - #define stbi_lrot(x,y) _lrotl(x,y) -#else - #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (-(y) & 31))) -#endif - -#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) -// ok -#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) -// ok -#else -#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." -#endif - -#ifndef STBI_MALLOC -#define STBI_MALLOC(sz) malloc(sz) -#define STBI_REALLOC(p,newsz) realloc(p,newsz) -#define STBI_FREE(p) free(p) -#endif - -#ifndef STBI_REALLOC_SIZED -#define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz) -#endif - -// x86/x64 detection -#if defined(__x86_64__) || defined(_M_X64) -#define STBI__X64_TARGET -#elif defined(__i386) || defined(_M_IX86) -#define STBI__X86_TARGET -#endif - -#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) -// gcc doesn't support sse2 intrinsics unless you compile with -msse2, -// which in turn means it gets to use SSE2 everywhere. This is unfortunate, -// but previous attempts to provide the SSE2 functions with runtime -// detection caused numerous issues. The way architecture extensions are -// exposed in GCC/Clang is, sadly, not really suited for one-file libs. -// New behavior: if compiled with -msse2, we use SSE2 without any -// detection; if not, we don't use it at all. -#define STBI_NO_SIMD -#endif - -#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) -// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET -// -// 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the -// Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant. -// As a result, enabling SSE2 on 32-bit MinGW is dangerous when not -// simultaneously enabling "-mstackrealign". -// -// See https://github.com/nothings/stb/issues/81 for more information. -// -// So default to no SSE2 on 32-bit MinGW. If you've read this far and added -// -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2. -#define STBI_NO_SIMD -#endif - -#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) -#define STBI_SSE2 -#include - -#ifdef _MSC_VER - -#if _MSC_VER >= 1400 // not VC6 -#include // __cpuid -static int stbi__cpuid3(void) -{ - int info[4]; - __cpuid(info,1); - return info[3]; -} -#else -static int stbi__cpuid3(void) -{ - int res; - __asm { - mov eax,1 - cpuid - mov res,edx - } - return res; -} -#endif - -#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name - -#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) -static int stbi__sse2_available(void) -{ - int info3 = stbi__cpuid3(); - return ((info3 >> 26) & 1) != 0; -} -#endif - -#else // assume GCC-style if not VC++ -#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) - -#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) -static int stbi__sse2_available(void) -{ - // If we're even attempting to compile this on GCC/Clang, that means - // -msse2 is on, which means the compiler is allowed to use SSE2 - // instructions at will, and so are we. - return 1; -} -#endif - -#endif -#endif - -// ARM NEON -#if defined(STBI_NO_SIMD) && defined(STBI_NEON) -#undef STBI_NEON -#endif - -#ifdef STBI_NEON -#include -#ifdef _MSC_VER -#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name -#else -#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) -#endif -#endif - -#ifndef STBI_SIMD_ALIGN -#define STBI_SIMD_ALIGN(type, name) type name -#endif - -#ifndef STBI_MAX_DIMENSIONS -#define STBI_MAX_DIMENSIONS (1 << 24) -#endif - -/////////////////////////////////////////////// -// -// stbi__context struct and start_xxx functions - -// stbi__context structure is our basic context used by all images, so it -// contains all the IO context, plus some basic image information -typedef struct -{ - stbi__uint32 img_x, img_y; - int img_n, img_out_n; - - stbi_io_callbacks io; - void *io_user_data; - - int read_from_callbacks; - int buflen; - stbi_uc buffer_start[128]; - int callback_already_read; - - stbi_uc *img_buffer, *img_buffer_end; - stbi_uc *img_buffer_original, *img_buffer_original_end; -} stbi__context; - - -static void stbi__refill_buffer(stbi__context *s); - -// initialize a memory-decode context -static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) -{ - s->io.read = NULL; - s->read_from_callbacks = 0; - s->callback_already_read = 0; - s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer; - s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len; -} - -// initialize a callback-based context -static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user) -{ - s->io = *c; - s->io_user_data = user; - s->buflen = sizeof(s->buffer_start); - s->read_from_callbacks = 1; - s->callback_already_read = 0; - s->img_buffer = s->img_buffer_original = s->buffer_start; - stbi__refill_buffer(s); - s->img_buffer_original_end = s->img_buffer_end; -} - -#ifndef STBI_NO_STDIO - -static int stbi__stdio_read(void *user, char *data, int size) -{ - return (int) fread(data,1,size,(FILE*) user); -} - -static void stbi__stdio_skip(void *user, int n) -{ - int ch; - fseek((FILE*) user, n, SEEK_CUR); - ch = fgetc((FILE*) user); /* have to read a byte to reset feof()'s flag */ - if (ch != EOF) { - ungetc(ch, (FILE *) user); /* push byte back onto stream if valid. */ - } -} - -static int stbi__stdio_eof(void *user) -{ - return feof((FILE*) user) || ferror((FILE *) user); -} - -static stbi_io_callbacks stbi__stdio_callbacks = -{ - stbi__stdio_read, - stbi__stdio_skip, - stbi__stdio_eof, -}; - -static void stbi__start_file(stbi__context *s, FILE *f) -{ - stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f); -} - -//static void stop_file(stbi__context *s) { } - -#endif // !STBI_NO_STDIO - -static void stbi__rewind(stbi__context *s) -{ - // conceptually rewind SHOULD rewind to the beginning of the stream, - // but we just rewind to the beginning of the initial buffer, because - // we only use it after doing 'test', which only ever looks at at most 92 bytes - s->img_buffer = s->img_buffer_original; - s->img_buffer_end = s->img_buffer_original_end; -} - -enum -{ - STBI_ORDER_RGB, - STBI_ORDER_BGR -}; - -typedef struct -{ - int bits_per_channel; - int num_channels; - int channel_order; -} stbi__result_info; - -#ifndef STBI_NO_JPEG -static int stbi__jpeg_test(stbi__context *s); -static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); -#endif - -#ifndef STBI_NO_PNG -static int stbi__png_test(stbi__context *s); -static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); -static int stbi__png_is16(stbi__context *s); -#endif - -#ifndef STBI_NO_BMP -static int stbi__bmp_test(stbi__context *s); -static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); -#endif - -#ifndef STBI_NO_TGA -static int stbi__tga_test(stbi__context *s); -static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); -#endif - -#ifndef STBI_NO_PSD -static int stbi__psd_test(stbi__context *s); -static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc); -static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); -static int stbi__psd_is16(stbi__context *s); -#endif - -#ifndef STBI_NO_HDR -static int stbi__hdr_test(stbi__context *s); -static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); -#endif - -#ifndef STBI_NO_PIC -static int stbi__pic_test(stbi__context *s); -static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); -#endif - -#ifndef STBI_NO_GIF -static int stbi__gif_test(stbi__context *s); -static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp); -static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); -#endif - -#ifndef STBI_NO_PNM -static int stbi__pnm_test(stbi__context *s); -static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); -static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); -static int stbi__pnm_is16(stbi__context *s); -#endif - -static -#ifdef STBI_THREAD_LOCAL -STBI_THREAD_LOCAL -#endif -const char *stbi__g_failure_reason; - -STBIDEF const char *stbi_failure_reason(void) -{ - return stbi__g_failure_reason; -} - -#ifndef STBI_NO_FAILURE_STRINGS -static int stbi__err(const char *str) -{ - stbi__g_failure_reason = str; - return 0; -} -#endif - -static void *stbi__malloc(size_t size) -{ - return STBI_MALLOC(size); -} - -// stb_image uses ints pervasively, including for offset calculations. -// therefore the largest decoded image size we can support with the -// current code, even on 64-bit targets, is INT_MAX. this is not a -// significant limitation for the intended use case. -// -// we do, however, need to make sure our size calculations don't -// overflow. hence a few helper functions for size calculations that -// multiply integers together, making sure that they're non-negative -// and no overflow occurs. - -// return 1 if the sum is valid, 0 on overflow. -// negative terms are considered invalid. -static int stbi__addsizes_valid(int a, int b) -{ - if (b < 0) return 0; - // now 0 <= b <= INT_MAX, hence also - // 0 <= INT_MAX - b <= INTMAX. - // And "a + b <= INT_MAX" (which might overflow) is the - // same as a <= INT_MAX - b (no overflow) - return a <= INT_MAX - b; -} - -// returns 1 if the product is valid, 0 on overflow. -// negative factors are considered invalid. -static int stbi__mul2sizes_valid(int a, int b) -{ - if (a < 0 || b < 0) return 0; - if (b == 0) return 1; // mul-by-0 is always safe - // portable way to check for no overflows in a*b - return a <= INT_MAX/b; -} - -#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) -// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow -static int stbi__mad2sizes_valid(int a, int b, int add) -{ - return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add); -} -#endif - -// returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow -static int stbi__mad3sizes_valid(int a, int b, int c, int add) -{ - return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && - stbi__addsizes_valid(a*b*c, add); -} - -// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow -#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) -static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) -{ - return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && - stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add); -} -#endif - -#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) -// mallocs with size overflow checking -static void *stbi__malloc_mad2(int a, int b, int add) -{ - if (!stbi__mad2sizes_valid(a, b, add)) return NULL; - return stbi__malloc(a*b + add); -} -#endif - -static void *stbi__malloc_mad3(int a, int b, int c, int add) -{ - if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; - return stbi__malloc(a*b*c + add); -} - -#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) -static void *stbi__malloc_mad4(int a, int b, int c, int d, int add) -{ - if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; - return stbi__malloc(a*b*c*d + add); -} -#endif - -// returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 inclusive), 0 on overflow. -static int stbi__addints_valid(int a, int b) -{ - if ((a >= 0) != (b >= 0)) return 1; // a and b have different signs, so no overflow - if (a < 0 && b < 0) return a >= INT_MIN - b; // same as a + b >= INT_MIN; INT_MIN - b cannot overflow since b < 0. - return a <= INT_MAX - b; -} - -// returns 1 if the product of two signed shorts is valid, 0 on overflow. -static int stbi__mul2shorts_valid(short a, short b) -{ - if (b == 0 || b == -1) return 1; // multiplication by 0 is always 0; check for -1 so SHRT_MIN/b doesn't overflow - if ((a >= 0) == (b >= 0)) return a <= SHRT_MAX/b; // product is positive, so similar to mul2sizes_valid - if (b < 0) return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN - return a >= SHRT_MIN / b; -} - -// stbi__err - error -// stbi__errpf - error returning pointer to float -// stbi__errpuc - error returning pointer to unsigned char - -#ifdef STBI_NO_FAILURE_STRINGS - #define stbi__err(x,y) 0 -#elif defined(STBI_FAILURE_USERMSG) - #define stbi__err(x,y) stbi__err(y) -#else - #define stbi__err(x,y) stbi__err(x) -#endif - -#define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL)) -#define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL)) - -STBIDEF void stbi_image_free(void *retval_from_stbi_load) -{ - STBI_FREE(retval_from_stbi_load); -} - -#ifndef STBI_NO_LINEAR -static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); -#endif - -#ifndef STBI_NO_HDR -static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); -#endif - -static int stbi__vertically_flip_on_load_global = 0; - -STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) -{ - stbi__vertically_flip_on_load_global = flag_true_if_should_flip; -} - -#ifndef STBI_THREAD_LOCAL -#define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global -#else -static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set; - -STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) -{ - stbi__vertically_flip_on_load_local = flag_true_if_should_flip; - stbi__vertically_flip_on_load_set = 1; -} - -#define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \ - ? stbi__vertically_flip_on_load_local \ - : stbi__vertically_flip_on_load_global) -#endif // STBI_THREAD_LOCAL - -static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) -{ - memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields - ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed - ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order - ri->num_channels = 0; - - // test the formats with a very explicit header first (at least a FOURCC - // or distinctive magic number first) - #ifndef STBI_NO_PNG - if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri); - #endif - #ifndef STBI_NO_BMP - if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri); - #endif - #ifndef STBI_NO_GIF - if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri); - #endif - #ifndef STBI_NO_PSD - if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc); - #else - STBI_NOTUSED(bpc); - #endif - #ifndef STBI_NO_PIC - if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri); - #endif - - // then the formats that can end up attempting to load with just 1 or 2 - // bytes matching expectations; these are prone to false positives, so - // try them later - #ifndef STBI_NO_JPEG - if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri); - #endif - #ifndef STBI_NO_PNM - if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri); - #endif - - #ifndef STBI_NO_HDR - if (stbi__hdr_test(s)) { - float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri); - return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); - } - #endif - - #ifndef STBI_NO_TGA - // test tga last because it's a crappy test! - if (stbi__tga_test(s)) - return stbi__tga_load(s,x,y,comp,req_comp, ri); - #endif - - return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); -} - -static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels) -{ - int i; - int img_len = w * h * channels; - stbi_uc *reduced; - - reduced = (stbi_uc *) stbi__malloc(img_len); - if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); - - for (i = 0; i < img_len; ++i) - reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling - - STBI_FREE(orig); - return reduced; -} - -static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels) -{ - int i; - int img_len = w * h * channels; - stbi__uint16 *enlarged; - - enlarged = (stbi__uint16 *) stbi__malloc(img_len*2); - if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); - - for (i = 0; i < img_len; ++i) - enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff - - STBI_FREE(orig); - return enlarged; -} - -static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) -{ - int row; - size_t bytes_per_row = (size_t)w * bytes_per_pixel; - stbi_uc temp[2048]; - stbi_uc *bytes = (stbi_uc *)image; - - for (row = 0; row < (h>>1); row++) { - stbi_uc *row0 = bytes + row*bytes_per_row; - stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row; - // swap row0 with row1 - size_t bytes_left = bytes_per_row; - while (bytes_left) { - size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); - memcpy(temp, row0, bytes_copy); - memcpy(row0, row1, bytes_copy); - memcpy(row1, temp, bytes_copy); - row0 += bytes_copy; - row1 += bytes_copy; - bytes_left -= bytes_copy; - } - } -} - -#ifndef STBI_NO_GIF -static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel) -{ - int slice; - int slice_size = w * h * bytes_per_pixel; - - stbi_uc *bytes = (stbi_uc *)image; - for (slice = 0; slice < z; ++slice) { - stbi__vertical_flip(bytes, w, h, bytes_per_pixel); - bytes += slice_size; - } -} -#endif - -static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) -{ - stbi__result_info ri; - void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); - - if (result == NULL) - return NULL; - - // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. - STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); - - if (ri.bits_per_channel != 8) { - result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp); - ri.bits_per_channel = 8; - } - - // @TODO: move stbi__convert_format to here - - if (stbi__vertically_flip_on_load) { - int channels = req_comp ? req_comp : *comp; - stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); - } - - return (unsigned char *) result; -} - -static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) -{ - stbi__result_info ri; - void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); - - if (result == NULL) - return NULL; - - // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. - STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); - - if (ri.bits_per_channel != 16) { - result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp); - ri.bits_per_channel = 16; - } - - // @TODO: move stbi__convert_format16 to here - // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision - - if (stbi__vertically_flip_on_load) { - int channels = req_comp ? req_comp : *comp; - stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); - } - - return (stbi__uint16 *) result; -} - -#if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR) -static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) -{ - if (stbi__vertically_flip_on_load && result != NULL) { - int channels = req_comp ? req_comp : *comp; - stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); - } -} -#endif - -#ifndef STBI_NO_STDIO - -#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) -STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); -STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); -#endif - -#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) -STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) -{ - return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); -} -#endif - -static FILE *stbi__fopen(char const *filename, char const *mode) -{ - FILE *f; -#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) - wchar_t wMode[64]; - wchar_t wFilename[1024]; - if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename))) - return 0; - - if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode))) - return 0; - -#if defined(_MSC_VER) && _MSC_VER >= 1400 - if (0 != _wfopen_s(&f, wFilename, wMode)) - f = 0; -#else - f = _wfopen(wFilename, wMode); -#endif - -#elif defined(_MSC_VER) && _MSC_VER >= 1400 - if (0 != fopen_s(&f, filename, mode)) - f=0; -#else - f = fopen(filename, mode); -#endif - return f; -} - - -STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) -{ - FILE *f = stbi__fopen(filename, "rb"); - unsigned char *result; - if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); - result = stbi_load_from_file(f,x,y,comp,req_comp); - fclose(f); - return result; -} - -STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) -{ - unsigned char *result; - stbi__context s; - stbi__start_file(&s,f); - result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); - if (result) { - // need to 'unget' all the characters in the IO buffer - fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); - } - return result; -} - -STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp) -{ - stbi__uint16 *result; - stbi__context s; - stbi__start_file(&s,f); - result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp); - if (result) { - // need to 'unget' all the characters in the IO buffer - fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); - } - return result; -} - -STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp) -{ - FILE *f = stbi__fopen(filename, "rb"); - stbi__uint16 *result; - if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file"); - result = stbi_load_from_file_16(f,x,y,comp,req_comp); - fclose(f); - return result; -} - - -#endif //!STBI_NO_STDIO - -STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels) -{ - stbi__context s; - stbi__start_mem(&s,buffer,len); - return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); -} - -STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels) -{ - stbi__context s; - stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); - return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); -} - -STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) -{ - stbi__context s; - stbi__start_mem(&s,buffer,len); - return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); -} - -STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) -{ - stbi__context s; - stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); - return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); -} - -#ifndef STBI_NO_GIF -STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp) -{ - unsigned char *result; - stbi__context s; - stbi__start_mem(&s,buffer,len); - - result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); - if (stbi__vertically_flip_on_load) { - stbi__vertical_flip_slices( result, *x, *y, *z, *comp ); - } - - return result; -} -#endif - -#ifndef STBI_NO_LINEAR -static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) -{ - unsigned char *data; - #ifndef STBI_NO_HDR - if (stbi__hdr_test(s)) { - stbi__result_info ri; - float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri); - if (hdr_data) - stbi__float_postprocess(hdr_data,x,y,comp,req_comp); - return hdr_data; - } - #endif - data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); - if (data) - return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); - return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); -} - -STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) -{ - stbi__context s; - stbi__start_mem(&s,buffer,len); - return stbi__loadf_main(&s,x,y,comp,req_comp); -} - -STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) -{ - stbi__context s; - stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); - return stbi__loadf_main(&s,x,y,comp,req_comp); -} - -#ifndef STBI_NO_STDIO -STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) -{ - float *result; - FILE *f = stbi__fopen(filename, "rb"); - if (!f) return stbi__errpf("can't fopen", "Unable to open file"); - result = stbi_loadf_from_file(f,x,y,comp,req_comp); - fclose(f); - return result; -} - -STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) -{ - stbi__context s; - stbi__start_file(&s,f); - return stbi__loadf_main(&s,x,y,comp,req_comp); -} -#endif // !STBI_NO_STDIO - -#endif // !STBI_NO_LINEAR - -// these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is -// defined, for API simplicity; if STBI_NO_LINEAR is defined, it always -// reports false! - -STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) -{ - #ifndef STBI_NO_HDR - stbi__context s; - stbi__start_mem(&s,buffer,len); - return stbi__hdr_test(&s); - #else - STBI_NOTUSED(buffer); - STBI_NOTUSED(len); - return 0; - #endif -} - -#ifndef STBI_NO_STDIO -STBIDEF int stbi_is_hdr (char const *filename) -{ - FILE *f = stbi__fopen(filename, "rb"); - int result=0; - if (f) { - result = stbi_is_hdr_from_file(f); - fclose(f); - } - return result; -} - -STBIDEF int stbi_is_hdr_from_file(FILE *f) -{ - #ifndef STBI_NO_HDR - long pos = ftell(f); - int res; - stbi__context s; - stbi__start_file(&s,f); - res = stbi__hdr_test(&s); - fseek(f, pos, SEEK_SET); - return res; - #else - STBI_NOTUSED(f); - return 0; - #endif -} -#endif // !STBI_NO_STDIO - -STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) -{ - #ifndef STBI_NO_HDR - stbi__context s; - stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); - return stbi__hdr_test(&s); - #else - STBI_NOTUSED(clbk); - STBI_NOTUSED(user); - return 0; - #endif -} - -#ifndef STBI_NO_LINEAR -static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f; - -STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } -STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } -#endif - -static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; - -STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; } -STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; } - - -////////////////////////////////////////////////////////////////////////////// -// -// Common code used by all image loaders -// - -enum -{ - STBI__SCAN_load=0, - STBI__SCAN_type, - STBI__SCAN_header -}; - -static void stbi__refill_buffer(stbi__context *s) -{ - int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); - s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original); - if (n == 0) { - // at end of file, treat same as if from memory, but need to handle case - // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file - s->read_from_callbacks = 0; - s->img_buffer = s->buffer_start; - s->img_buffer_end = s->buffer_start+1; - *s->img_buffer = 0; - } else { - s->img_buffer = s->buffer_start; - s->img_buffer_end = s->buffer_start + n; - } -} - -stbi_inline static stbi_uc stbi__get8(stbi__context *s) -{ - if (s->img_buffer < s->img_buffer_end) - return *s->img_buffer++; - if (s->read_from_callbacks) { - stbi__refill_buffer(s); - return *s->img_buffer++; - } - return 0; -} - -#if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) -// nothing -#else -stbi_inline static int stbi__at_eof(stbi__context *s) -{ - if (s->io.read) { - if (!(s->io.eof)(s->io_user_data)) return 0; - // if feof() is true, check if buffer = end - // special case: we've only got the special 0 character at the end - if (s->read_from_callbacks == 0) return 1; - } - - return s->img_buffer >= s->img_buffer_end; -} -#endif - -#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) -// nothing -#else -static void stbi__skip(stbi__context *s, int n) -{ - if (n == 0) return; // already there! - if (n < 0) { - s->img_buffer = s->img_buffer_end; - return; - } - if (s->io.read) { - int blen = (int) (s->img_buffer_end - s->img_buffer); - if (blen < n) { - s->img_buffer = s->img_buffer_end; - (s->io.skip)(s->io_user_data, n - blen); - return; - } - } - s->img_buffer += n; -} -#endif - -#if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM) -// nothing -#else -static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) -{ - if (s->io.read) { - int blen = (int) (s->img_buffer_end - s->img_buffer); - if (blen < n) { - int res, count; - - memcpy(buffer, s->img_buffer, blen); - - count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen); - res = (count == (n-blen)); - s->img_buffer = s->img_buffer_end; - return res; - } - } - - if (s->img_buffer+n <= s->img_buffer_end) { - memcpy(buffer, s->img_buffer, n); - s->img_buffer += n; - return 1; - } else - return 0; -} -#endif - -#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) -// nothing -#else -static int stbi__get16be(stbi__context *s) -{ - int z = stbi__get8(s); - return (z << 8) + stbi__get8(s); -} -#endif - -#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) -// nothing -#else -static stbi__uint32 stbi__get32be(stbi__context *s) -{ - stbi__uint32 z = stbi__get16be(s); - return (z << 16) + stbi__get16be(s); -} -#endif - -#if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) -// nothing -#else -static int stbi__get16le(stbi__context *s) -{ - int z = stbi__get8(s); - return z + (stbi__get8(s) << 8); -} -#endif - -#ifndef STBI_NO_BMP -static stbi__uint32 stbi__get32le(stbi__context *s) -{ - stbi__uint32 z = stbi__get16le(s); - z += (stbi__uint32)stbi__get16le(s) << 16; - return z; -} -#endif - -#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings - -#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) -// nothing -#else -////////////////////////////////////////////////////////////////////////////// -// -// generic converter from built-in img_n to req_comp -// individual types do this automatically as much as possible (e.g. jpeg -// does all cases internally since it needs to colorspace convert anyway, -// and it never has alpha, so very few cases ). png can automatically -// interleave an alpha=255 channel, but falls back to this for other cases -// -// assume data buffer is malloced, so malloc a new one and free that one -// only failure mode is malloc failing - -static stbi_uc stbi__compute_y(int r, int g, int b) -{ - return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8); -} -#endif - -#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) -// nothing -#else -static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) -{ - int i,j; - unsigned char *good; - - if (req_comp == img_n) return data; - STBI_ASSERT(req_comp >= 1 && req_comp <= 4); - - good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0); - if (good == NULL) { - STBI_FREE(data); - return stbi__errpuc("outofmem", "Out of memory"); - } - - for (j=0; j < (int) y; ++j) { - unsigned char *src = data + j * x * img_n ; - unsigned char *dest = good + j * x * req_comp; - - #define STBI__COMBO(a,b) ((a)*8+(b)) - #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) - // convert source image with img_n components to one with req_comp components; - // avoid switch per pixel, so use switch per scanline and massive macros - switch (STBI__COMBO(img_n, req_comp)) { - STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255; } break; - STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; - STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255; } break; - STBI__CASE(2,1) { dest[0]=src[0]; } break; - STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; - STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; - STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255; } break; - STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; - STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255; } break; - STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; - STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break; - STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; - default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion"); - } - #undef STBI__CASE - } - - STBI_FREE(data); - return good; -} -#endif - -#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) -// nothing -#else -static stbi__uint16 stbi__compute_y_16(int r, int g, int b) -{ - return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8); -} -#endif - -#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) -// nothing -#else -static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y) -{ - int i,j; - stbi__uint16 *good; - - if (req_comp == img_n) return data; - STBI_ASSERT(req_comp >= 1 && req_comp <= 4); - - good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2); - if (good == NULL) { - STBI_FREE(data); - return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); - } - - for (j=0; j < (int) y; ++j) { - stbi__uint16 *src = data + j * x * img_n ; - stbi__uint16 *dest = good + j * x * req_comp; - - #define STBI__COMBO(a,b) ((a)*8+(b)) - #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) - // convert source image with img_n components to one with req_comp components; - // avoid switch per pixel, so use switch per scanline and massive macros - switch (STBI__COMBO(img_n, req_comp)) { - STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff; } break; - STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; - STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff; } break; - STBI__CASE(2,1) { dest[0]=src[0]; } break; - STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; - STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; - STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff; } break; - STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; - STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break; - STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; - STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break; - STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; - default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc("unsupported", "Unsupported format conversion"); - } - #undef STBI__CASE - } - - STBI_FREE(data); - return good; -} -#endif - -#ifndef STBI_NO_LINEAR -static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) -{ - int i,k,n; - float *output; - if (!data) return NULL; - output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0); - if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } - // compute number of non-alpha components - if (comp & 1) n = comp; else n = comp-1; - for (i=0; i < x*y; ++i) { - for (k=0; k < n; ++k) { - output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale); - } - } - if (n < comp) { - for (i=0; i < x*y; ++i) { - output[i*comp + n] = data[i*comp + n]/255.0f; - } - } - STBI_FREE(data); - return output; -} -#endif - -#ifndef STBI_NO_HDR -#define stbi__float2int(x) ((int) (x)) -static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) -{ - int i,k,n; - stbi_uc *output; - if (!data) return NULL; - output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0); - if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } - // compute number of non-alpha components - if (comp & 1) n = comp; else n = comp-1; - for (i=0; i < x*y; ++i) { - for (k=0; k < n; ++k) { - float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; - if (z < 0) z = 0; - if (z > 255) z = 255; - output[i*comp + k] = (stbi_uc) stbi__float2int(z); - } - if (k < comp) { - float z = data[i*comp+k] * 255 + 0.5f; - if (z < 0) z = 0; - if (z > 255) z = 255; - output[i*comp + k] = (stbi_uc) stbi__float2int(z); - } - } - STBI_FREE(data); - return output; -} -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// "baseline" JPEG/JFIF decoder -// -// simple implementation -// - doesn't support delayed output of y-dimension -// - simple interface (only one output format: 8-bit interleaved RGB) -// - doesn't try to recover corrupt jpegs -// - doesn't allow partial loading, loading multiple at once -// - still fast on x86 (copying globals into locals doesn't help x86) -// - allocates lots of intermediate memory (full size of all components) -// - non-interleaved case requires this anyway -// - allows good upsampling (see next) -// high-quality -// - upsampled channels are bilinearly interpolated, even across blocks -// - quality integer IDCT derived from IJG's 'slow' -// performance -// - fast huffman; reasonable integer IDCT -// - some SIMD kernels for common paths on targets with SSE2/NEON -// - uses a lot of intermediate memory, could cache poorly - -#ifndef STBI_NO_JPEG - -// huffman decoding acceleration -#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache - -typedef struct -{ - stbi_uc fast[1 << FAST_BITS]; - // weirdly, repacking this into AoS is a 10% speed loss, instead of a win - stbi__uint16 code[256]; - stbi_uc values[256]; - stbi_uc size[257]; - unsigned int maxcode[18]; - int delta[17]; // old 'firstsymbol' - old 'firstcode' -} stbi__huffman; - -typedef struct -{ - stbi__context *s; - stbi__huffman huff_dc[4]; - stbi__huffman huff_ac[4]; - stbi__uint16 dequant[4][64]; - stbi__int16 fast_ac[4][1 << FAST_BITS]; - -// sizes for components, interleaved MCUs - int img_h_max, img_v_max; - int img_mcu_x, img_mcu_y; - int img_mcu_w, img_mcu_h; - -// definition of jpeg image component - struct - { - int id; - int h,v; - int tq; - int hd,ha; - int dc_pred; - - int x,y,w2,h2; - stbi_uc *data; - void *raw_data, *raw_coeff; - stbi_uc *linebuf; - short *coeff; // progressive only - int coeff_w, coeff_h; // number of 8x8 coefficient blocks - } img_comp[4]; - - stbi__uint32 code_buffer; // jpeg entropy-coded buffer - int code_bits; // number of valid bits - unsigned char marker; // marker seen while filling entropy buffer - int nomore; // flag if we saw a marker so must stop - - int progressive; - int spec_start; - int spec_end; - int succ_high; - int succ_low; - int eob_run; - int jfif; - int app14_color_transform; // Adobe APP14 tag - int rgb; - - int scan_n, order[4]; - int restart_interval, todo; - -// kernels - void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]); - void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step); - stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs); -} stbi__jpeg; - -static int stbi__build_huffman(stbi__huffman *h, int *count) -{ - int i,j,k=0; - unsigned int code; - // build size list for each symbol (from JPEG spec) - for (i=0; i < 16; ++i) { - for (j=0; j < count[i]; ++j) { - h->size[k++] = (stbi_uc) (i+1); - if(k >= 257) return stbi__err("bad size list","Corrupt JPEG"); - } - } - h->size[k] = 0; - - // compute actual symbols (from jpeg spec) - code = 0; - k = 0; - for(j=1; j <= 16; ++j) { - // compute delta to add to code to compute symbol id - h->delta[j] = k - code; - if (h->size[k] == j) { - while (h->size[k] == j) - h->code[k++] = (stbi__uint16) (code++); - if (code-1 >= (1u << j)) return stbi__err("bad code lengths","Corrupt JPEG"); - } - // compute largest code + 1 for this size, preshifted as needed later - h->maxcode[j] = code << (16-j); - code <<= 1; - } - h->maxcode[j] = 0xffffffff; - - // build non-spec acceleration table; 255 is flag for not-accelerated - memset(h->fast, 255, 1 << FAST_BITS); - for (i=0; i < k; ++i) { - int s = h->size[i]; - if (s <= FAST_BITS) { - int c = h->code[i] << (FAST_BITS-s); - int m = 1 << (FAST_BITS-s); - for (j=0; j < m; ++j) { - h->fast[c+j] = (stbi_uc) i; - } - } - } - return 1; -} - -// build a table that decodes both magnitude and value of small ACs in -// one go. -static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) -{ - int i; - for (i=0; i < (1 << FAST_BITS); ++i) { - stbi_uc fast = h->fast[i]; - fast_ac[i] = 0; - if (fast < 255) { - int rs = h->values[fast]; - int run = (rs >> 4) & 15; - int magbits = rs & 15; - int len = h->size[fast]; - - if (magbits && len + magbits <= FAST_BITS) { - // magnitude code followed by receive_extend code - int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); - int m = 1 << (magbits - 1); - if (k < m) k += (~0U << magbits) + 1; - // if the result is small enough, we can fit it in fast_ac table - if (k >= -128 && k <= 127) - fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits)); - } - } - } -} - -static void stbi__grow_buffer_unsafe(stbi__jpeg *j) -{ - do { - unsigned int b = j->nomore ? 0 : stbi__get8(j->s); - if (b == 0xff) { - int c = stbi__get8(j->s); - while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes - if (c != 0) { - j->marker = (unsigned char) c; - j->nomore = 1; - return; - } - } - j->code_buffer |= b << (24 - j->code_bits); - j->code_bits += 8; - } while (j->code_bits <= 24); -} - -// (1 << n) - 1 -static const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; - -// decode a jpeg huffman value from the bitstream -stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) -{ - unsigned int temp; - int c,k; - - if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); - - // look at the top FAST_BITS and determine what symbol ID it is, - // if the code is <= FAST_BITS - c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); - k = h->fast[c]; - if (k < 255) { - int s = h->size[k]; - if (s > j->code_bits) - return -1; - j->code_buffer <<= s; - j->code_bits -= s; - return h->values[k]; - } - - // naive test is to shift the code_buffer down so k bits are - // valid, then test against maxcode. To speed this up, we've - // preshifted maxcode left so that it has (16-k) 0s at the - // end; in other words, regardless of the number of bits, it - // wants to be compared against something shifted to have 16; - // that way we don't need to shift inside the loop. - temp = j->code_buffer >> 16; - for (k=FAST_BITS+1 ; ; ++k) - if (temp < h->maxcode[k]) - break; - if (k == 17) { - // error! code not found - j->code_bits -= 16; - return -1; - } - - if (k > j->code_bits) - return -1; - - // convert the huffman code to the symbol id - c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; - if(c < 0 || c >= 256) // symbol id out of bounds! - return -1; - STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); - - // convert the id to a symbol - j->code_bits -= k; - j->code_buffer <<= k; - return h->values[c]; -} - -// bias[n] = (-1<code_bits < n) stbi__grow_buffer_unsafe(j); - if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing - - sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative) - k = stbi_lrot(j->code_buffer, n); - j->code_buffer = k & ~stbi__bmask[n]; - k &= stbi__bmask[n]; - j->code_bits -= n; - return k + (stbi__jbias[n] & (sgn - 1)); -} - -// get some unsigned bits -stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) -{ - unsigned int k; - if (j->code_bits < n) stbi__grow_buffer_unsafe(j); - if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing - k = stbi_lrot(j->code_buffer, n); - j->code_buffer = k & ~stbi__bmask[n]; - k &= stbi__bmask[n]; - j->code_bits -= n; - return k; -} - -stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) -{ - unsigned int k; - if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); - if (j->code_bits < 1) return 0; // ran out of bits from stream, return 0s intead of continuing - k = j->code_buffer; - j->code_buffer <<= 1; - --j->code_bits; - return k & 0x80000000; -} - -// given a value that's at position X in the zigzag stream, -// where does it appear in the 8x8 matrix coded as row-major? -static const stbi_uc stbi__jpeg_dezigzag[64+15] = -{ - 0, 1, 8, 16, 9, 2, 3, 10, - 17, 24, 32, 25, 18, 11, 4, 5, - 12, 19, 26, 33, 40, 48, 41, 34, - 27, 20, 13, 6, 7, 14, 21, 28, - 35, 42, 49, 56, 57, 50, 43, 36, - 29, 22, 15, 23, 30, 37, 44, 51, - 58, 59, 52, 45, 38, 31, 39, 46, - 53, 60, 61, 54, 47, 55, 62, 63, - // let corrupt input sample past end - 63, 63, 63, 63, 63, 63, 63, 63, - 63, 63, 63, 63, 63, 63, 63 -}; - -// decode one 64-entry block-- -static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant) -{ - int diff,dc,k; - int t; - - if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); - t = stbi__jpeg_huff_decode(j, hdc); - if (t < 0 || t > 15) return stbi__err("bad huffman code","Corrupt JPEG"); - - // 0 all the ac values now so we can do it 32-bits at a time - memset(data,0,64*sizeof(data[0])); - - diff = t ? stbi__extend_receive(j, t) : 0; - if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta","Corrupt JPEG"); - dc = j->img_comp[b].dc_pred + diff; - j->img_comp[b].dc_pred = dc; - if (!stbi__mul2shorts_valid(dc, dequant[0])) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); - data[0] = (short) (dc * dequant[0]); - - // decode AC components, see JPEG spec - k = 1; - do { - unsigned int zig; - int c,r,s; - if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); - c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); - r = fac[c]; - if (r) { // fast-AC path - k += (r >> 4) & 15; // run - s = r & 15; // combined length - if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); - j->code_buffer <<= s; - j->code_bits -= s; - // decode into unzigzag'd location - zig = stbi__jpeg_dezigzag[k++]; - data[zig] = (short) ((r >> 8) * dequant[zig]); - } else { - int rs = stbi__jpeg_huff_decode(j, hac); - if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); - s = rs & 15; - r = rs >> 4; - if (s == 0) { - if (rs != 0xf0) break; // end block - k += 16; - } else { - k += r; - // decode into unzigzag'd location - zig = stbi__jpeg_dezigzag[k++]; - data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]); - } - } - } while (k < 64); - return 1; -} - -static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b) -{ - int diff,dc; - int t; - if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); - - if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); - - if (j->succ_high == 0) { - // first scan for DC coefficient, must be first - memset(data,0,64*sizeof(data[0])); // 0 all the ac values now - t = stbi__jpeg_huff_decode(j, hdc); - if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); - diff = t ? stbi__extend_receive(j, t) : 0; - - if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta", "Corrupt JPEG"); - dc = j->img_comp[b].dc_pred + diff; - j->img_comp[b].dc_pred = dc; - if (!stbi__mul2shorts_valid(dc, 1 << j->succ_low)) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); - data[0] = (short) (dc * (1 << j->succ_low)); - } else { - // refinement scan for DC coefficient - if (stbi__jpeg_get_bit(j)) - data[0] += (short) (1 << j->succ_low); - } - return 1; -} - -// @OPTIMIZE: store non-zigzagged during the decode passes, -// and only de-zigzag when dequantizing -static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac) -{ - int k; - if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); - - if (j->succ_high == 0) { - int shift = j->succ_low; - - if (j->eob_run) { - --j->eob_run; - return 1; - } - - k = j->spec_start; - do { - unsigned int zig; - int c,r,s; - if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); - c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); - r = fac[c]; - if (r) { // fast-AC path - k += (r >> 4) & 15; // run - s = r & 15; // combined length - if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); - j->code_buffer <<= s; - j->code_bits -= s; - zig = stbi__jpeg_dezigzag[k++]; - data[zig] = (short) ((r >> 8) * (1 << shift)); - } else { - int rs = stbi__jpeg_huff_decode(j, hac); - if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); - s = rs & 15; - r = rs >> 4; - if (s == 0) { - if (r < 15) { - j->eob_run = (1 << r); - if (r) - j->eob_run += stbi__jpeg_get_bits(j, r); - --j->eob_run; - break; - } - k += 16; - } else { - k += r; - zig = stbi__jpeg_dezigzag[k++]; - data[zig] = (short) (stbi__extend_receive(j,s) * (1 << shift)); - } - } - } while (k <= j->spec_end); - } else { - // refinement scan for these AC coefficients - - short bit = (short) (1 << j->succ_low); - - if (j->eob_run) { - --j->eob_run; - for (k = j->spec_start; k <= j->spec_end; ++k) { - short *p = &data[stbi__jpeg_dezigzag[k]]; - if (*p != 0) - if (stbi__jpeg_get_bit(j)) - if ((*p & bit)==0) { - if (*p > 0) - *p += bit; - else - *p -= bit; - } - } - } else { - k = j->spec_start; - do { - int r,s; - int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh - if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); - s = rs & 15; - r = rs >> 4; - if (s == 0) { - if (r < 15) { - j->eob_run = (1 << r) - 1; - if (r) - j->eob_run += stbi__jpeg_get_bits(j, r); - r = 64; // force end of block - } else { - // r=15 s=0 should write 16 0s, so we just do - // a run of 15 0s and then write s (which is 0), - // so we don't have to do anything special here - } - } else { - if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); - // sign bit - if (stbi__jpeg_get_bit(j)) - s = bit; - else - s = -bit; - } - - // advance by r - while (k <= j->spec_end) { - short *p = &data[stbi__jpeg_dezigzag[k++]]; - if (*p != 0) { - if (stbi__jpeg_get_bit(j)) - if ((*p & bit)==0) { - if (*p > 0) - *p += bit; - else - *p -= bit; - } - } else { - if (r == 0) { - *p = (short) s; - break; - } - --r; - } - } - } while (k <= j->spec_end); - } - } - return 1; -} - -// take a -128..127 value and stbi__clamp it and convert to 0..255 -stbi_inline static stbi_uc stbi__clamp(int x) -{ - // trick to use a single test to catch both cases - if ((unsigned int) x > 255) { - if (x < 0) return 0; - if (x > 255) return 255; - } - return (stbi_uc) x; -} - -#define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) -#define stbi__fsh(x) ((x) * 4096) - -// derived from jidctint -- DCT_ISLOW -#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ - int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ - p2 = s2; \ - p3 = s6; \ - p1 = (p2+p3) * stbi__f2f(0.5411961f); \ - t2 = p1 + p3*stbi__f2f(-1.847759065f); \ - t3 = p1 + p2*stbi__f2f( 0.765366865f); \ - p2 = s0; \ - p3 = s4; \ - t0 = stbi__fsh(p2+p3); \ - t1 = stbi__fsh(p2-p3); \ - x0 = t0+t3; \ - x3 = t0-t3; \ - x1 = t1+t2; \ - x2 = t1-t2; \ - t0 = s7; \ - t1 = s5; \ - t2 = s3; \ - t3 = s1; \ - p3 = t0+t2; \ - p4 = t1+t3; \ - p1 = t0+t3; \ - p2 = t1+t2; \ - p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ - t0 = t0*stbi__f2f( 0.298631336f); \ - t1 = t1*stbi__f2f( 2.053119869f); \ - t2 = t2*stbi__f2f( 3.072711026f); \ - t3 = t3*stbi__f2f( 1.501321110f); \ - p1 = p5 + p1*stbi__f2f(-0.899976223f); \ - p2 = p5 + p2*stbi__f2f(-2.562915447f); \ - p3 = p3*stbi__f2f(-1.961570560f); \ - p4 = p4*stbi__f2f(-0.390180644f); \ - t3 += p1+p4; \ - t2 += p2+p3; \ - t1 += p2+p4; \ - t0 += p1+p3; - -static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) -{ - int i,val[64],*v=val; - stbi_uc *o; - short *d = data; - - // columns - for (i=0; i < 8; ++i,++d, ++v) { - // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing - if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 - && d[40]==0 && d[48]==0 && d[56]==0) { - // no shortcut 0 seconds - // (1|2|3|4|5|6|7)==0 0 seconds - // all separate -0.047 seconds - // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds - int dcterm = d[0]*4; - v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; - } else { - STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56]) - // constants scaled things up by 1<<12; let's bring them back - // down, but keep 2 extra bits of precision - x0 += 512; x1 += 512; x2 += 512; x3 += 512; - v[ 0] = (x0+t3) >> 10; - v[56] = (x0-t3) >> 10; - v[ 8] = (x1+t2) >> 10; - v[48] = (x1-t2) >> 10; - v[16] = (x2+t1) >> 10; - v[40] = (x2-t1) >> 10; - v[24] = (x3+t0) >> 10; - v[32] = (x3-t0) >> 10; - } - } - - for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { - // no fast case since the first 1D IDCT spread components out - STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) - // constants scaled things up by 1<<12, plus we had 1<<2 from first - // loop, plus horizontal and vertical each scale by sqrt(8) so together - // we've got an extra 1<<3, so 1<<17 total we need to remove. - // so we want to round that, which means adding 0.5 * 1<<17, - // aka 65536. Also, we'll end up with -128 to 127 that we want - // to encode as 0..255 by adding 128, so we'll add that before the shift - x0 += 65536 + (128<<17); - x1 += 65536 + (128<<17); - x2 += 65536 + (128<<17); - x3 += 65536 + (128<<17); - // tried computing the shifts into temps, or'ing the temps to see - // if any were out of range, but that was slower - o[0] = stbi__clamp((x0+t3) >> 17); - o[7] = stbi__clamp((x0-t3) >> 17); - o[1] = stbi__clamp((x1+t2) >> 17); - o[6] = stbi__clamp((x1-t2) >> 17); - o[2] = stbi__clamp((x2+t1) >> 17); - o[5] = stbi__clamp((x2-t1) >> 17); - o[3] = stbi__clamp((x3+t0) >> 17); - o[4] = stbi__clamp((x3-t0) >> 17); - } -} - -#ifdef STBI_SSE2 -// sse2 integer IDCT. not the fastest possible implementation but it -// produces bit-identical results to the generic C version so it's -// fully "transparent". -static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) -{ - // This is constructed to match our regular (generic) integer IDCT exactly. - __m128i row0, row1, row2, row3, row4, row5, row6, row7; - __m128i tmp; - - // dot product constant: even elems=x, odd elems=y - #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y)) - - // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) - // out(1) = c1[even]*x + c1[odd]*y - #define dct_rot(out0,out1, x,y,c0,c1) \ - __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \ - __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \ - __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ - __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ - __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ - __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) - - // out = in << 12 (in 16-bit, out 32-bit) - #define dct_widen(out, in) \ - __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ - __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) - - // wide add - #define dct_wadd(out, a, b) \ - __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ - __m128i out##_h = _mm_add_epi32(a##_h, b##_h) - - // wide sub - #define dct_wsub(out, a, b) \ - __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ - __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) - - // butterfly a/b, add bias, then shift by "s" and pack - #define dct_bfly32o(out0, out1, a,b,bias,s) \ - { \ - __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ - __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ - dct_wadd(sum, abiased, b); \ - dct_wsub(dif, abiased, b); \ - out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ - out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ - } - - // 8-bit interleave step (for transposes) - #define dct_interleave8(a, b) \ - tmp = a; \ - a = _mm_unpacklo_epi8(a, b); \ - b = _mm_unpackhi_epi8(tmp, b) - - // 16-bit interleave step (for transposes) - #define dct_interleave16(a, b) \ - tmp = a; \ - a = _mm_unpacklo_epi16(a, b); \ - b = _mm_unpackhi_epi16(tmp, b) - - #define dct_pass(bias,shift) \ - { \ - /* even part */ \ - dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \ - __m128i sum04 = _mm_add_epi16(row0, row4); \ - __m128i dif04 = _mm_sub_epi16(row0, row4); \ - dct_widen(t0e, sum04); \ - dct_widen(t1e, dif04); \ - dct_wadd(x0, t0e, t3e); \ - dct_wsub(x3, t0e, t3e); \ - dct_wadd(x1, t1e, t2e); \ - dct_wsub(x2, t1e, t2e); \ - /* odd part */ \ - dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \ - dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \ - __m128i sum17 = _mm_add_epi16(row1, row7); \ - __m128i sum35 = _mm_add_epi16(row3, row5); \ - dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \ - dct_wadd(x4, y0o, y4o); \ - dct_wadd(x5, y1o, y5o); \ - dct_wadd(x6, y2o, y5o); \ - dct_wadd(x7, y3o, y4o); \ - dct_bfly32o(row0,row7, x0,x7,bias,shift); \ - dct_bfly32o(row1,row6, x1,x6,bias,shift); \ - dct_bfly32o(row2,row5, x2,x5,bias,shift); \ - dct_bfly32o(row3,row4, x3,x4,bias,shift); \ - } - - __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); - __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f)); - __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f)); - __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); - __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f)); - __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f)); - __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f)); - __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f)); - - // rounding biases in column/row passes, see stbi__idct_block for explanation. - __m128i bias_0 = _mm_set1_epi32(512); - __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17)); - - // load - row0 = _mm_load_si128((const __m128i *) (data + 0*8)); - row1 = _mm_load_si128((const __m128i *) (data + 1*8)); - row2 = _mm_load_si128((const __m128i *) (data + 2*8)); - row3 = _mm_load_si128((const __m128i *) (data + 3*8)); - row4 = _mm_load_si128((const __m128i *) (data + 4*8)); - row5 = _mm_load_si128((const __m128i *) (data + 5*8)); - row6 = _mm_load_si128((const __m128i *) (data + 6*8)); - row7 = _mm_load_si128((const __m128i *) (data + 7*8)); - - // column pass - dct_pass(bias_0, 10); - - { - // 16bit 8x8 transpose pass 1 - dct_interleave16(row0, row4); - dct_interleave16(row1, row5); - dct_interleave16(row2, row6); - dct_interleave16(row3, row7); - - // transpose pass 2 - dct_interleave16(row0, row2); - dct_interleave16(row1, row3); - dct_interleave16(row4, row6); - dct_interleave16(row5, row7); - - // transpose pass 3 - dct_interleave16(row0, row1); - dct_interleave16(row2, row3); - dct_interleave16(row4, row5); - dct_interleave16(row6, row7); - } - - // row pass - dct_pass(bias_1, 17); - - { - // pack - __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 - __m128i p1 = _mm_packus_epi16(row2, row3); - __m128i p2 = _mm_packus_epi16(row4, row5); - __m128i p3 = _mm_packus_epi16(row6, row7); - - // 8bit 8x8 transpose pass 1 - dct_interleave8(p0, p2); // a0e0a1e1... - dct_interleave8(p1, p3); // c0g0c1g1... - - // transpose pass 2 - dct_interleave8(p0, p1); // a0c0e0g0... - dct_interleave8(p2, p3); // b0d0f0h0... - - // transpose pass 3 - dct_interleave8(p0, p2); // a0b0c0d0... - dct_interleave8(p1, p3); // a4b4c4d4... - - // store - _mm_storel_epi64((__m128i *) out, p0); out += out_stride; - _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride; - _mm_storel_epi64((__m128i *) out, p2); out += out_stride; - _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride; - _mm_storel_epi64((__m128i *) out, p1); out += out_stride; - _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride; - _mm_storel_epi64((__m128i *) out, p3); out += out_stride; - _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e)); - } - -#undef dct_const -#undef dct_rot -#undef dct_widen -#undef dct_wadd -#undef dct_wsub -#undef dct_bfly32o -#undef dct_interleave8 -#undef dct_interleave16 -#undef dct_pass -} - -#endif // STBI_SSE2 - -#ifdef STBI_NEON - -// NEON integer IDCT. should produce bit-identical -// results to the generic C version. -static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) -{ - int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; - - int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); - int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); - int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f)); - int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f)); - int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); - int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); - int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); - int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); - int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f)); - int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f)); - int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f)); - int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f)); - -#define dct_long_mul(out, inq, coeff) \ - int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ - int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) - -#define dct_long_mac(out, acc, inq, coeff) \ - int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ - int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) - -#define dct_widen(out, inq) \ - int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ - int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) - -// wide add -#define dct_wadd(out, a, b) \ - int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ - int32x4_t out##_h = vaddq_s32(a##_h, b##_h) - -// wide sub -#define dct_wsub(out, a, b) \ - int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ - int32x4_t out##_h = vsubq_s32(a##_h, b##_h) - -// butterfly a/b, then shift using "shiftop" by "s" and pack -#define dct_bfly32o(out0,out1, a,b,shiftop,s) \ - { \ - dct_wadd(sum, a, b); \ - dct_wsub(dif, a, b); \ - out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ - out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ - } - -#define dct_pass(shiftop, shift) \ - { \ - /* even part */ \ - int16x8_t sum26 = vaddq_s16(row2, row6); \ - dct_long_mul(p1e, sum26, rot0_0); \ - dct_long_mac(t2e, p1e, row6, rot0_1); \ - dct_long_mac(t3e, p1e, row2, rot0_2); \ - int16x8_t sum04 = vaddq_s16(row0, row4); \ - int16x8_t dif04 = vsubq_s16(row0, row4); \ - dct_widen(t0e, sum04); \ - dct_widen(t1e, dif04); \ - dct_wadd(x0, t0e, t3e); \ - dct_wsub(x3, t0e, t3e); \ - dct_wadd(x1, t1e, t2e); \ - dct_wsub(x2, t1e, t2e); \ - /* odd part */ \ - int16x8_t sum15 = vaddq_s16(row1, row5); \ - int16x8_t sum17 = vaddq_s16(row1, row7); \ - int16x8_t sum35 = vaddq_s16(row3, row5); \ - int16x8_t sum37 = vaddq_s16(row3, row7); \ - int16x8_t sumodd = vaddq_s16(sum17, sum35); \ - dct_long_mul(p5o, sumodd, rot1_0); \ - dct_long_mac(p1o, p5o, sum17, rot1_1); \ - dct_long_mac(p2o, p5o, sum35, rot1_2); \ - dct_long_mul(p3o, sum37, rot2_0); \ - dct_long_mul(p4o, sum15, rot2_1); \ - dct_wadd(sump13o, p1o, p3o); \ - dct_wadd(sump24o, p2o, p4o); \ - dct_wadd(sump23o, p2o, p3o); \ - dct_wadd(sump14o, p1o, p4o); \ - dct_long_mac(x4, sump13o, row7, rot3_0); \ - dct_long_mac(x5, sump24o, row5, rot3_1); \ - dct_long_mac(x6, sump23o, row3, rot3_2); \ - dct_long_mac(x7, sump14o, row1, rot3_3); \ - dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \ - dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \ - dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \ - dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \ - } - - // load - row0 = vld1q_s16(data + 0*8); - row1 = vld1q_s16(data + 1*8); - row2 = vld1q_s16(data + 2*8); - row3 = vld1q_s16(data + 3*8); - row4 = vld1q_s16(data + 4*8); - row5 = vld1q_s16(data + 5*8); - row6 = vld1q_s16(data + 6*8); - row7 = vld1q_s16(data + 7*8); - - // add DC bias - row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); - - // column pass - dct_pass(vrshrn_n_s32, 10); - - // 16bit 8x8 transpose - { -// these three map to a single VTRN.16, VTRN.32, and VSWP, respectively. -// whether compilers actually get this is another story, sadly. -#define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; } -#define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); } -#define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); } - - // pass 1 - dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 - dct_trn16(row2, row3); - dct_trn16(row4, row5); - dct_trn16(row6, row7); - - // pass 2 - dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 - dct_trn32(row1, row3); - dct_trn32(row4, row6); - dct_trn32(row5, row7); - - // pass 3 - dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 - dct_trn64(row1, row5); - dct_trn64(row2, row6); - dct_trn64(row3, row7); - -#undef dct_trn16 -#undef dct_trn32 -#undef dct_trn64 - } - - // row pass - // vrshrn_n_s32 only supports shifts up to 16, we need - // 17. so do a non-rounding shift of 16 first then follow - // up with a rounding shift by 1. - dct_pass(vshrn_n_s32, 16); - - { - // pack and round - uint8x8_t p0 = vqrshrun_n_s16(row0, 1); - uint8x8_t p1 = vqrshrun_n_s16(row1, 1); - uint8x8_t p2 = vqrshrun_n_s16(row2, 1); - uint8x8_t p3 = vqrshrun_n_s16(row3, 1); - uint8x8_t p4 = vqrshrun_n_s16(row4, 1); - uint8x8_t p5 = vqrshrun_n_s16(row5, 1); - uint8x8_t p6 = vqrshrun_n_s16(row6, 1); - uint8x8_t p7 = vqrshrun_n_s16(row7, 1); - - // again, these can translate into one instruction, but often don't. -#define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; } -#define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); } -#define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); } - - // sadly can't use interleaved stores here since we only write - // 8 bytes to each scan line! - - // 8x8 8-bit transpose pass 1 - dct_trn8_8(p0, p1); - dct_trn8_8(p2, p3); - dct_trn8_8(p4, p5); - dct_trn8_8(p6, p7); - - // pass 2 - dct_trn8_16(p0, p2); - dct_trn8_16(p1, p3); - dct_trn8_16(p4, p6); - dct_trn8_16(p5, p7); - - // pass 3 - dct_trn8_32(p0, p4); - dct_trn8_32(p1, p5); - dct_trn8_32(p2, p6); - dct_trn8_32(p3, p7); - - // store - vst1_u8(out, p0); out += out_stride; - vst1_u8(out, p1); out += out_stride; - vst1_u8(out, p2); out += out_stride; - vst1_u8(out, p3); out += out_stride; - vst1_u8(out, p4); out += out_stride; - vst1_u8(out, p5); out += out_stride; - vst1_u8(out, p6); out += out_stride; - vst1_u8(out, p7); - -#undef dct_trn8_8 -#undef dct_trn8_16 -#undef dct_trn8_32 - } - -#undef dct_long_mul -#undef dct_long_mac -#undef dct_widen -#undef dct_wadd -#undef dct_wsub -#undef dct_bfly32o -#undef dct_pass -} - -#endif // STBI_NEON - -#define STBI__MARKER_none 0xff -// if there's a pending marker from the entropy stream, return that -// otherwise, fetch from the stream and get a marker. if there's no -// marker, return 0xff, which is never a valid marker value -static stbi_uc stbi__get_marker(stbi__jpeg *j) -{ - stbi_uc x; - if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } - x = stbi__get8(j->s); - if (x != 0xff) return STBI__MARKER_none; - while (x == 0xff) - x = stbi__get8(j->s); // consume repeated 0xff fill bytes - return x; -} - -// in each scan, we'll have scan_n components, and the order -// of the components is specified by order[] -#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) - -// after a restart interval, stbi__jpeg_reset the entropy decoder and -// the dc prediction -static void stbi__jpeg_reset(stbi__jpeg *j) -{ - j->code_bits = 0; - j->code_buffer = 0; - j->nomore = 0; - j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0; - j->marker = STBI__MARKER_none; - j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; - j->eob_run = 0; - // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, - // since we don't even allow 1<<30 pixels -} - -static int stbi__parse_entropy_coded_data(stbi__jpeg *z) -{ - stbi__jpeg_reset(z); - if (!z->progressive) { - if (z->scan_n == 1) { - int i,j; - STBI_SIMD_ALIGN(short, data[64]); - int n = z->order[0]; - // non-interleaved data, we just need to process one block at a time, - // in trivial scanline order - // number of blocks to do just depends on how many actual "pixels" this - // component has, independent of interleaved MCU blocking and such - int w = (z->img_comp[n].x+7) >> 3; - int h = (z->img_comp[n].y+7) >> 3; - for (j=0; j < h; ++j) { - for (i=0; i < w; ++i) { - int ha = z->img_comp[n].ha; - if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; - z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); - // every data block is an MCU, so countdown the restart interval - if (--z->todo <= 0) { - if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); - // if it's NOT a restart, then just bail, so we get corrupt data - // rather than no data - if (!STBI__RESTART(z->marker)) return 1; - stbi__jpeg_reset(z); - } - } - } - return 1; - } else { // interleaved - int i,j,k,x,y; - STBI_SIMD_ALIGN(short, data[64]); - for (j=0; j < z->img_mcu_y; ++j) { - for (i=0; i < z->img_mcu_x; ++i) { - // scan an interleaved mcu... process scan_n components in order - for (k=0; k < z->scan_n; ++k) { - int n = z->order[k]; - // scan out an mcu's worth of this component; that's just determined - // by the basic H and V specified for the component - for (y=0; y < z->img_comp[n].v; ++y) { - for (x=0; x < z->img_comp[n].h; ++x) { - int x2 = (i*z->img_comp[n].h + x)*8; - int y2 = (j*z->img_comp[n].v + y)*8; - int ha = z->img_comp[n].ha; - if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; - z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data); - } - } - } - // after all interleaved components, that's an interleaved MCU, - // so now count down the restart interval - if (--z->todo <= 0) { - if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); - if (!STBI__RESTART(z->marker)) return 1; - stbi__jpeg_reset(z); - } - } - } - return 1; - } - } else { - if (z->scan_n == 1) { - int i,j; - int n = z->order[0]; - // non-interleaved data, we just need to process one block at a time, - // in trivial scanline order - // number of blocks to do just depends on how many actual "pixels" this - // component has, independent of interleaved MCU blocking and such - int w = (z->img_comp[n].x+7) >> 3; - int h = (z->img_comp[n].y+7) >> 3; - for (j=0; j < h; ++j) { - for (i=0; i < w; ++i) { - short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); - if (z->spec_start == 0) { - if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) - return 0; - } else { - int ha = z->img_comp[n].ha; - if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) - return 0; - } - // every data block is an MCU, so countdown the restart interval - if (--z->todo <= 0) { - if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); - if (!STBI__RESTART(z->marker)) return 1; - stbi__jpeg_reset(z); - } - } - } - return 1; - } else { // interleaved - int i,j,k,x,y; - for (j=0; j < z->img_mcu_y; ++j) { - for (i=0; i < z->img_mcu_x; ++i) { - // scan an interleaved mcu... process scan_n components in order - for (k=0; k < z->scan_n; ++k) { - int n = z->order[k]; - // scan out an mcu's worth of this component; that's just determined - // by the basic H and V specified for the component - for (y=0; y < z->img_comp[n].v; ++y) { - for (x=0; x < z->img_comp[n].h; ++x) { - int x2 = (i*z->img_comp[n].h + x); - int y2 = (j*z->img_comp[n].v + y); - short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); - if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) - return 0; - } - } - } - // after all interleaved components, that's an interleaved MCU, - // so now count down the restart interval - if (--z->todo <= 0) { - if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); - if (!STBI__RESTART(z->marker)) return 1; - stbi__jpeg_reset(z); - } - } - } - return 1; - } - } -} - -static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant) -{ - int i; - for (i=0; i < 64; ++i) - data[i] *= dequant[i]; -} - -static void stbi__jpeg_finish(stbi__jpeg *z) -{ - if (z->progressive) { - // dequantize and idct the data - int i,j,n; - for (n=0; n < z->s->img_n; ++n) { - int w = (z->img_comp[n].x+7) >> 3; - int h = (z->img_comp[n].y+7) >> 3; - for (j=0; j < h; ++j) { - for (i=0; i < w; ++i) { - short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); - stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); - z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); - } - } - } - } -} - -static int stbi__process_marker(stbi__jpeg *z, int m) -{ - int L; - switch (m) { - case STBI__MARKER_none: // no marker found - return stbi__err("expected marker","Corrupt JPEG"); - - case 0xDD: // DRI - specify restart interval - if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG"); - z->restart_interval = stbi__get16be(z->s); - return 1; - - case 0xDB: // DQT - define quantization table - L = stbi__get16be(z->s)-2; - while (L > 0) { - int q = stbi__get8(z->s); - int p = q >> 4, sixteen = (p != 0); - int t = q & 15,i; - if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG"); - if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG"); - - for (i=0; i < 64; ++i) - z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s)); - L -= (sixteen ? 129 : 65); - } - return L==0; - - case 0xC4: // DHT - define huffman table - L = stbi__get16be(z->s)-2; - while (L > 0) { - stbi_uc *v; - int sizes[16],i,n=0; - int q = stbi__get8(z->s); - int tc = q >> 4; - int th = q & 15; - if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG"); - for (i=0; i < 16; ++i) { - sizes[i] = stbi__get8(z->s); - n += sizes[i]; - } - if(n > 256) return stbi__err("bad DHT header","Corrupt JPEG"); // Loop over i < n would write past end of values! - L -= 17; - if (tc == 0) { - if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0; - v = z->huff_dc[th].values; - } else { - if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0; - v = z->huff_ac[th].values; - } - for (i=0; i < n; ++i) - v[i] = stbi__get8(z->s); - if (tc != 0) - stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); - L -= n; - } - return L==0; - } - - // check for comment block or APP blocks - if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { - L = stbi__get16be(z->s); - if (L < 2) { - if (m == 0xFE) - return stbi__err("bad COM len","Corrupt JPEG"); - else - return stbi__err("bad APP len","Corrupt JPEG"); - } - L -= 2; - - if (m == 0xE0 && L >= 5) { // JFIF APP0 segment - static const unsigned char tag[5] = {'J','F','I','F','\0'}; - int ok = 1; - int i; - for (i=0; i < 5; ++i) - if (stbi__get8(z->s) != tag[i]) - ok = 0; - L -= 5; - if (ok) - z->jfif = 1; - } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment - static const unsigned char tag[6] = {'A','d','o','b','e','\0'}; - int ok = 1; - int i; - for (i=0; i < 6; ++i) - if (stbi__get8(z->s) != tag[i]) - ok = 0; - L -= 6; - if (ok) { - stbi__get8(z->s); // version - stbi__get16be(z->s); // flags0 - stbi__get16be(z->s); // flags1 - z->app14_color_transform = stbi__get8(z->s); // color transform - L -= 6; - } - } - - stbi__skip(z->s, L); - return 1; - } - - return stbi__err("unknown marker","Corrupt JPEG"); -} - -// after we see SOS -static int stbi__process_scan_header(stbi__jpeg *z) -{ - int i; - int Ls = stbi__get16be(z->s); - z->scan_n = stbi__get8(z->s); - if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG"); - if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG"); - for (i=0; i < z->scan_n; ++i) { - int id = stbi__get8(z->s), which; - int q = stbi__get8(z->s); - for (which = 0; which < z->s->img_n; ++which) - if (z->img_comp[which].id == id) - break; - if (which == z->s->img_n) return 0; // no match - z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG"); - z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG"); - z->order[i] = which; - } - - { - int aa; - z->spec_start = stbi__get8(z->s); - z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 - aa = stbi__get8(z->s); - z->succ_high = (aa >> 4); - z->succ_low = (aa & 15); - if (z->progressive) { - if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13) - return stbi__err("bad SOS", "Corrupt JPEG"); - } else { - if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG"); - if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG"); - z->spec_end = 63; - } - } - - return 1; -} - -static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why) -{ - int i; - for (i=0; i < ncomp; ++i) { - if (z->img_comp[i].raw_data) { - STBI_FREE(z->img_comp[i].raw_data); - z->img_comp[i].raw_data = NULL; - z->img_comp[i].data = NULL; - } - if (z->img_comp[i].raw_coeff) { - STBI_FREE(z->img_comp[i].raw_coeff); - z->img_comp[i].raw_coeff = 0; - z->img_comp[i].coeff = 0; - } - if (z->img_comp[i].linebuf) { - STBI_FREE(z->img_comp[i].linebuf); - z->img_comp[i].linebuf = NULL; - } - } - return why; -} - -static int stbi__process_frame_header(stbi__jpeg *z, int scan) -{ - stbi__context *s = z->s; - int Lf,p,i,q, h_max=1,v_max=1,c; - Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG - p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline - s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG - s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires - if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); - if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); - c = stbi__get8(s); - if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG"); - s->img_n = c; - for (i=0; i < c; ++i) { - z->img_comp[i].data = NULL; - z->img_comp[i].linebuf = NULL; - } - - if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG"); - - z->rgb = 0; - for (i=0; i < s->img_n; ++i) { - static const unsigned char rgb[3] = { 'R', 'G', 'B' }; - z->img_comp[i].id = stbi__get8(s); - if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) - ++z->rgb; - q = stbi__get8(s); - z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG"); - z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG"); - z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG"); - } - - if (scan != STBI__SCAN_load) return 1; - - if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode"); - - for (i=0; i < s->img_n; ++i) { - if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; - if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; - } - - // check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios - // and I've never seen a non-corrupted JPEG file actually use them - for (i=0; i < s->img_n; ++i) { - if (h_max % z->img_comp[i].h != 0) return stbi__err("bad H","Corrupt JPEG"); - if (v_max % z->img_comp[i].v != 0) return stbi__err("bad V","Corrupt JPEG"); - } - - // compute interleaved mcu info - z->img_h_max = h_max; - z->img_v_max = v_max; - z->img_mcu_w = h_max * 8; - z->img_mcu_h = v_max * 8; - // these sizes can't be more than 17 bits - z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; - z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; - - for (i=0; i < s->img_n; ++i) { - // number of effective pixels (e.g. for non-interleaved MCU) - z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max; - z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max; - // to simplify generation, we'll allocate enough memory to decode - // the bogus oversized data from using interleaved MCUs and their - // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't - // discard the extra data until colorspace conversion - // - // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier) - // so these muls can't overflow with 32-bit ints (which we require) - z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; - z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; - z->img_comp[i].coeff = 0; - z->img_comp[i].raw_coeff = 0; - z->img_comp[i].linebuf = NULL; - z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); - if (z->img_comp[i].raw_data == NULL) - return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); - // align blocks for idct using mmx/sse - z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); - if (z->progressive) { - // w2, h2 are multiples of 8 (see above) - z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; - z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; - z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); - if (z->img_comp[i].raw_coeff == NULL) - return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); - z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); - } - } - - return 1; -} - -// use comparisons since in some cases we handle more than one case (e.g. SOF) -#define stbi__DNL(x) ((x) == 0xdc) -#define stbi__SOI(x) ((x) == 0xd8) -#define stbi__EOI(x) ((x) == 0xd9) -#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) -#define stbi__SOS(x) ((x) == 0xda) - -#define stbi__SOF_progressive(x) ((x) == 0xc2) - -static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) -{ - int m; - z->jfif = 0; - z->app14_color_transform = -1; // valid values are 0,1,2 - z->marker = STBI__MARKER_none; // initialize cached marker to empty - m = stbi__get_marker(z); - if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG"); - if (scan == STBI__SCAN_type) return 1; - m = stbi__get_marker(z); - while (!stbi__SOF(m)) { - if (!stbi__process_marker(z,m)) return 0; - m = stbi__get_marker(z); - while (m == STBI__MARKER_none) { - // some files have extra padding after their blocks, so ok, we'll scan - if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); - m = stbi__get_marker(z); - } - } - z->progressive = stbi__SOF_progressive(m); - if (!stbi__process_frame_header(z, scan)) return 0; - return 1; -} - -static int stbi__skip_jpeg_junk_at_end(stbi__jpeg *j) -{ - // some JPEGs have junk at end, skip over it but if we find what looks - // like a valid marker, resume there - while (!stbi__at_eof(j->s)) { - int x = stbi__get8(j->s); - while (x == 255) { // might be a marker - if (stbi__at_eof(j->s)) return STBI__MARKER_none; - x = stbi__get8(j->s); - if (x != 0x00 && x != 0xff) { - // not a stuffed zero or lead-in to another marker, looks - // like an actual marker, return it - return x; - } - // stuffed zero has x=0 now which ends the loop, meaning we go - // back to regular scan loop. - // repeated 0xff keeps trying to read the next byte of the marker. - } - } - return STBI__MARKER_none; -} - -// decode image to YCbCr format -static int stbi__decode_jpeg_image(stbi__jpeg *j) -{ - int m; - for (m = 0; m < 4; m++) { - j->img_comp[m].raw_data = NULL; - j->img_comp[m].raw_coeff = NULL; - } - j->restart_interval = 0; - if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; - m = stbi__get_marker(j); - while (!stbi__EOI(m)) { - if (stbi__SOS(m)) { - if (!stbi__process_scan_header(j)) return 0; - if (!stbi__parse_entropy_coded_data(j)) return 0; - if (j->marker == STBI__MARKER_none ) { - j->marker = stbi__skip_jpeg_junk_at_end(j); - // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 - } - m = stbi__get_marker(j); - if (STBI__RESTART(m)) - m = stbi__get_marker(j); - } else if (stbi__DNL(m)) { - int Ld = stbi__get16be(j->s); - stbi__uint32 NL = stbi__get16be(j->s); - if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); - if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); - m = stbi__get_marker(j); - } else { - if (!stbi__process_marker(j, m)) return 1; - m = stbi__get_marker(j); - } - } - if (j->progressive) - stbi__jpeg_finish(j); - return 1; -} - -// static jfif-centered resampling (across block boundaries) - -typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1, - int w, int hs); - -#define stbi__div4(x) ((stbi_uc) ((x) >> 2)) - -static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) -{ - STBI_NOTUSED(out); - STBI_NOTUSED(in_far); - STBI_NOTUSED(w); - STBI_NOTUSED(hs); - return in_near; -} - -static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) -{ - // need to generate two samples vertically for every one in input - int i; - STBI_NOTUSED(hs); - for (i=0; i < w; ++i) - out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2); - return out; -} - -static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) -{ - // need to generate two samples horizontally for every one in input - int i; - stbi_uc *input = in_near; - - if (w == 1) { - // if only one sample, can't do any interpolation - out[0] = out[1] = input[0]; - return out; - } - - out[0] = input[0]; - out[1] = stbi__div4(input[0]*3 + input[1] + 2); - for (i=1; i < w-1; ++i) { - int n = 3*input[i]+2; - out[i*2+0] = stbi__div4(n+input[i-1]); - out[i*2+1] = stbi__div4(n+input[i+1]); - } - out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2); - out[i*2+1] = input[w-1]; - - STBI_NOTUSED(in_far); - STBI_NOTUSED(hs); - - return out; -} - -#define stbi__div16(x) ((stbi_uc) ((x) >> 4)) - -static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) -{ - // need to generate 2x2 samples for every one in input - int i,t0,t1; - if (w == 1) { - out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); - return out; - } - - t1 = 3*in_near[0] + in_far[0]; - out[0] = stbi__div4(t1+2); - for (i=1; i < w; ++i) { - t0 = t1; - t1 = 3*in_near[i]+in_far[i]; - out[i*2-1] = stbi__div16(3*t0 + t1 + 8); - out[i*2 ] = stbi__div16(3*t1 + t0 + 8); - } - out[w*2-1] = stbi__div4(t1+2); - - STBI_NOTUSED(hs); - - return out; -} - -#if defined(STBI_SSE2) || defined(STBI_NEON) -static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) -{ - // need to generate 2x2 samples for every one in input - int i=0,t0,t1; - - if (w == 1) { - out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); - return out; - } - - t1 = 3*in_near[0] + in_far[0]; - // process groups of 8 pixels for as long as we can. - // note we can't handle the last pixel in a row in this loop - // because we need to handle the filter boundary conditions. - for (; i < ((w-1) & ~7); i += 8) { -#if defined(STBI_SSE2) - // load and perform the vertical filtering pass - // this uses 3*x + y = 4*x + (y - x) - __m128i zero = _mm_setzero_si128(); - __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i)); - __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i)); - __m128i farw = _mm_unpacklo_epi8(farb, zero); - __m128i nearw = _mm_unpacklo_epi8(nearb, zero); - __m128i diff = _mm_sub_epi16(farw, nearw); - __m128i nears = _mm_slli_epi16(nearw, 2); - __m128i curr = _mm_add_epi16(nears, diff); // current row - - // horizontal filter works the same based on shifted vers of current - // row. "prev" is current row shifted right by 1 pixel; we need to - // insert the previous pixel value (from t1). - // "next" is current row shifted left by 1 pixel, with first pixel - // of next block of 8 pixels added in. - __m128i prv0 = _mm_slli_si128(curr, 2); - __m128i nxt0 = _mm_srli_si128(curr, 2); - __m128i prev = _mm_insert_epi16(prv0, t1, 0); - __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7); - - // horizontal filter, polyphase implementation since it's convenient: - // even pixels = 3*cur + prev = cur*4 + (prev - cur) - // odd pixels = 3*cur + next = cur*4 + (next - cur) - // note the shared term. - __m128i bias = _mm_set1_epi16(8); - __m128i curs = _mm_slli_epi16(curr, 2); - __m128i prvd = _mm_sub_epi16(prev, curr); - __m128i nxtd = _mm_sub_epi16(next, curr); - __m128i curb = _mm_add_epi16(curs, bias); - __m128i even = _mm_add_epi16(prvd, curb); - __m128i odd = _mm_add_epi16(nxtd, curb); - - // interleave even and odd pixels, then undo scaling. - __m128i int0 = _mm_unpacklo_epi16(even, odd); - __m128i int1 = _mm_unpackhi_epi16(even, odd); - __m128i de0 = _mm_srli_epi16(int0, 4); - __m128i de1 = _mm_srli_epi16(int1, 4); - - // pack and write output - __m128i outv = _mm_packus_epi16(de0, de1); - _mm_storeu_si128((__m128i *) (out + i*2), outv); -#elif defined(STBI_NEON) - // load and perform the vertical filtering pass - // this uses 3*x + y = 4*x + (y - x) - uint8x8_t farb = vld1_u8(in_far + i); - uint8x8_t nearb = vld1_u8(in_near + i); - int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); - int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); - int16x8_t curr = vaddq_s16(nears, diff); // current row - - // horizontal filter works the same based on shifted vers of current - // row. "prev" is current row shifted right by 1 pixel; we need to - // insert the previous pixel value (from t1). - // "next" is current row shifted left by 1 pixel, with first pixel - // of next block of 8 pixels added in. - int16x8_t prv0 = vextq_s16(curr, curr, 7); - int16x8_t nxt0 = vextq_s16(curr, curr, 1); - int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); - int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7); - - // horizontal filter, polyphase implementation since it's convenient: - // even pixels = 3*cur + prev = cur*4 + (prev - cur) - // odd pixels = 3*cur + next = cur*4 + (next - cur) - // note the shared term. - int16x8_t curs = vshlq_n_s16(curr, 2); - int16x8_t prvd = vsubq_s16(prev, curr); - int16x8_t nxtd = vsubq_s16(next, curr); - int16x8_t even = vaddq_s16(curs, prvd); - int16x8_t odd = vaddq_s16(curs, nxtd); - - // undo scaling and round, then store with even/odd phases interleaved - uint8x8x2_t o; - o.val[0] = vqrshrun_n_s16(even, 4); - o.val[1] = vqrshrun_n_s16(odd, 4); - vst2_u8(out + i*2, o); -#endif - - // "previous" value for next iter - t1 = 3*in_near[i+7] + in_far[i+7]; - } - - t0 = t1; - t1 = 3*in_near[i] + in_far[i]; - out[i*2] = stbi__div16(3*t1 + t0 + 8); - - for (++i; i < w; ++i) { - t0 = t1; - t1 = 3*in_near[i]+in_far[i]; - out[i*2-1] = stbi__div16(3*t0 + t1 + 8); - out[i*2 ] = stbi__div16(3*t1 + t0 + 8); - } - out[w*2-1] = stbi__div4(t1+2); - - STBI_NOTUSED(hs); - - return out; -} -#endif - -static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) -{ - // resample with nearest-neighbor - int i,j; - STBI_NOTUSED(in_far); - for (i=0; i < w; ++i) - for (j=0; j < hs; ++j) - out[i*hs+j] = in_near[i]; - return out; -} - -// this is a reduced-precision calculation of YCbCr-to-RGB introduced -// to make sure the code produces the same results in both SIMD and scalar -#define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) -static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) -{ - int i; - for (i=0; i < count; ++i) { - int y_fixed = (y[i] << 20) + (1<<19); // rounding - int r,g,b; - int cr = pcr[i] - 128; - int cb = pcb[i] - 128; - r = y_fixed + cr* stbi__float2fixed(1.40200f); - g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); - b = y_fixed + cb* stbi__float2fixed(1.77200f); - r >>= 20; - g >>= 20; - b >>= 20; - if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } - if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } - if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } - out[0] = (stbi_uc)r; - out[1] = (stbi_uc)g; - out[2] = (stbi_uc)b; - out[3] = 255; - out += step; - } -} - -#if defined(STBI_SSE2) || defined(STBI_NEON) -static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) -{ - int i = 0; - -#ifdef STBI_SSE2 - // step == 3 is pretty ugly on the final interleave, and i'm not convinced - // it's useful in practice (you wouldn't use it for textures, for example). - // so just accelerate step == 4 case. - if (step == 4) { - // this is a fairly straightforward implementation and not super-optimized. - __m128i signflip = _mm_set1_epi8(-0x80); - __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f)); - __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f)); - __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f)); - __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f)); - __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128); - __m128i xw = _mm_set1_epi16(255); // alpha channel - - for (; i+7 < count; i += 8) { - // load - __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i)); - __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i)); - __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i)); - __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 - __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 - - // unpack to short (and left-shift cr, cb by 8) - __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); - __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); - __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); - - // color transform - __m128i yws = _mm_srli_epi16(yw, 4); - __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); - __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); - __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); - __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); - __m128i rws = _mm_add_epi16(cr0, yws); - __m128i gwt = _mm_add_epi16(cb0, yws); - __m128i bws = _mm_add_epi16(yws, cb1); - __m128i gws = _mm_add_epi16(gwt, cr1); - - // descale - __m128i rw = _mm_srai_epi16(rws, 4); - __m128i bw = _mm_srai_epi16(bws, 4); - __m128i gw = _mm_srai_epi16(gws, 4); - - // back to byte, set up for transpose - __m128i brb = _mm_packus_epi16(rw, bw); - __m128i gxb = _mm_packus_epi16(gw, xw); - - // transpose to interleave channels - __m128i t0 = _mm_unpacklo_epi8(brb, gxb); - __m128i t1 = _mm_unpackhi_epi8(brb, gxb); - __m128i o0 = _mm_unpacklo_epi16(t0, t1); - __m128i o1 = _mm_unpackhi_epi16(t0, t1); - - // store - _mm_storeu_si128((__m128i *) (out + 0), o0); - _mm_storeu_si128((__m128i *) (out + 16), o1); - out += 32; - } - } -#endif - -#ifdef STBI_NEON - // in this version, step=3 support would be easy to add. but is there demand? - if (step == 4) { - // this is a fairly straightforward implementation and not super-optimized. - uint8x8_t signflip = vdup_n_u8(0x80); - int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f)); - int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f)); - int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f)); - int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f)); - - for (; i+7 < count; i += 8) { - // load - uint8x8_t y_bytes = vld1_u8(y + i); - uint8x8_t cr_bytes = vld1_u8(pcr + i); - uint8x8_t cb_bytes = vld1_u8(pcb + i); - int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); - int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); - - // expand to s16 - int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); - int16x8_t crw = vshll_n_s8(cr_biased, 7); - int16x8_t cbw = vshll_n_s8(cb_biased, 7); - - // color transform - int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); - int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); - int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); - int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); - int16x8_t rws = vaddq_s16(yws, cr0); - int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); - int16x8_t bws = vaddq_s16(yws, cb1); - - // undo scaling, round, convert to byte - uint8x8x4_t o; - o.val[0] = vqrshrun_n_s16(rws, 4); - o.val[1] = vqrshrun_n_s16(gws, 4); - o.val[2] = vqrshrun_n_s16(bws, 4); - o.val[3] = vdup_n_u8(255); - - // store, interleaving r/g/b/a - vst4_u8(out, o); - out += 8*4; - } - } -#endif - - for (; i < count; ++i) { - int y_fixed = (y[i] << 20) + (1<<19); // rounding - int r,g,b; - int cr = pcr[i] - 128; - int cb = pcb[i] - 128; - r = y_fixed + cr* stbi__float2fixed(1.40200f); - g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); - b = y_fixed + cb* stbi__float2fixed(1.77200f); - r >>= 20; - g >>= 20; - b >>= 20; - if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } - if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } - if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } - out[0] = (stbi_uc)r; - out[1] = (stbi_uc)g; - out[2] = (stbi_uc)b; - out[3] = 255; - out += step; - } -} -#endif - -// set up the kernels -static void stbi__setup_jpeg(stbi__jpeg *j) -{ - j->idct_block_kernel = stbi__idct_block; - j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; - j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; - -#ifdef STBI_SSE2 - if (stbi__sse2_available()) { - j->idct_block_kernel = stbi__idct_simd; - j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; - j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; - } -#endif - -#ifdef STBI_NEON - j->idct_block_kernel = stbi__idct_simd; - j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; - j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; -#endif -} - -// clean up the temporary component buffers -static void stbi__cleanup_jpeg(stbi__jpeg *j) -{ - stbi__free_jpeg_components(j, j->s->img_n, 0); -} - -typedef struct -{ - resample_row_func resample; - stbi_uc *line0,*line1; - int hs,vs; // expansion factor in each axis - int w_lores; // horizontal pixels pre-expansion - int ystep; // how far through vertical expansion we are - int ypos; // which pre-expansion row we're on -} stbi__resample; - -// fast 0..255 * 0..255 => 0..255 rounded multiplication -static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) -{ - unsigned int t = x*y + 128; - return (stbi_uc) ((t + (t >>8)) >> 8); -} - -static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) -{ - int n, decode_n, is_rgb; - z->s->img_n = 0; // make stbi__cleanup_jpeg safe - - // validate req_comp - if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); - - // load a jpeg image from whichever source, but leave in YCbCr format - if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } - - // determine actual number of components to generate - n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; - - is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); - - if (z->s->img_n == 3 && n < 3 && !is_rgb) - decode_n = 1; - else - decode_n = z->s->img_n; - - // nothing to do if no components requested; check this now to avoid - // accessing uninitialized coutput[0] later - if (decode_n <= 0) { stbi__cleanup_jpeg(z); return NULL; } - - // resample and color-convert - { - int k; - unsigned int i,j; - stbi_uc *output; - stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL }; - - stbi__resample res_comp[4]; - - for (k=0; k < decode_n; ++k) { - stbi__resample *r = &res_comp[k]; - - // allocate line buffer big enough for upsampling off the edges - // with upsample factor of 4 - z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3); - if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } - - r->hs = z->img_h_max / z->img_comp[k].h; - r->vs = z->img_v_max / z->img_comp[k].v; - r->ystep = r->vs >> 1; - r->w_lores = (z->s->img_x + r->hs-1) / r->hs; - r->ypos = 0; - r->line0 = r->line1 = z->img_comp[k].data; - - if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; - else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; - else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; - else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; - else r->resample = stbi__resample_row_generic; - } - - // can't error after this so, this is safe - output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); - if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } - - // now go ahead and resample - for (j=0; j < z->s->img_y; ++j) { - stbi_uc *out = output + n * z->s->img_x * j; - for (k=0; k < decode_n; ++k) { - stbi__resample *r = &res_comp[k]; - int y_bot = r->ystep >= (r->vs >> 1); - coutput[k] = r->resample(z->img_comp[k].linebuf, - y_bot ? r->line1 : r->line0, - y_bot ? r->line0 : r->line1, - r->w_lores, r->hs); - if (++r->ystep >= r->vs) { - r->ystep = 0; - r->line0 = r->line1; - if (++r->ypos < z->img_comp[k].y) - r->line1 += z->img_comp[k].w2; - } - } - if (n >= 3) { - stbi_uc *y = coutput[0]; - if (z->s->img_n == 3) { - if (is_rgb) { - for (i=0; i < z->s->img_x; ++i) { - out[0] = y[i]; - out[1] = coutput[1][i]; - out[2] = coutput[2][i]; - out[3] = 255; - out += n; - } - } else { - z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); - } - } else if (z->s->img_n == 4) { - if (z->app14_color_transform == 0) { // CMYK - for (i=0; i < z->s->img_x; ++i) { - stbi_uc m = coutput[3][i]; - out[0] = stbi__blinn_8x8(coutput[0][i], m); - out[1] = stbi__blinn_8x8(coutput[1][i], m); - out[2] = stbi__blinn_8x8(coutput[2][i], m); - out[3] = 255; - out += n; - } - } else if (z->app14_color_transform == 2) { // YCCK - z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); - for (i=0; i < z->s->img_x; ++i) { - stbi_uc m = coutput[3][i]; - out[0] = stbi__blinn_8x8(255 - out[0], m); - out[1] = stbi__blinn_8x8(255 - out[1], m); - out[2] = stbi__blinn_8x8(255 - out[2], m); - out += n; - } - } else { // YCbCr + alpha? Ignore the fourth channel for now - z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); - } - } else - for (i=0; i < z->s->img_x; ++i) { - out[0] = out[1] = out[2] = y[i]; - out[3] = 255; // not used if n==3 - out += n; - } - } else { - if (is_rgb) { - if (n == 1) - for (i=0; i < z->s->img_x; ++i) - *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); - else { - for (i=0; i < z->s->img_x; ++i, out += 2) { - out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); - out[1] = 255; - } - } - } else if (z->s->img_n == 4 && z->app14_color_transform == 0) { - for (i=0; i < z->s->img_x; ++i) { - stbi_uc m = coutput[3][i]; - stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); - stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); - stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); - out[0] = stbi__compute_y(r, g, b); - out[1] = 255; - out += n; - } - } else if (z->s->img_n == 4 && z->app14_color_transform == 2) { - for (i=0; i < z->s->img_x; ++i) { - out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); - out[1] = 255; - out += n; - } - } else { - stbi_uc *y = coutput[0]; - if (n == 1) - for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; - else - for (i=0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; } - } - } - } - stbi__cleanup_jpeg(z); - *out_x = z->s->img_x; - *out_y = z->s->img_y; - if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output - return output; - } -} - -static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - unsigned char* result; - stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg)); - if (!j) return stbi__errpuc("outofmem", "Out of memory"); - memset(j, 0, sizeof(stbi__jpeg)); - STBI_NOTUSED(ri); - j->s = s; - stbi__setup_jpeg(j); - result = load_jpeg_image(j, x,y,comp,req_comp); - STBI_FREE(j); - return result; -} - -static int stbi__jpeg_test(stbi__context *s) -{ - int r; - stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); - if (!j) return stbi__err("outofmem", "Out of memory"); - memset(j, 0, sizeof(stbi__jpeg)); - j->s = s; - stbi__setup_jpeg(j); - r = stbi__decode_jpeg_header(j, STBI__SCAN_type); - stbi__rewind(s); - STBI_FREE(j); - return r; -} - -static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) -{ - if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { - stbi__rewind( j->s ); - return 0; - } - if (x) *x = j->s->img_x; - if (y) *y = j->s->img_y; - if (comp) *comp = j->s->img_n >= 3 ? 3 : 1; - return 1; -} - -static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) -{ - int result; - stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg))); - if (!j) return stbi__err("outofmem", "Out of memory"); - memset(j, 0, sizeof(stbi__jpeg)); - j->s = s; - result = stbi__jpeg_info_raw(j, x, y, comp); - STBI_FREE(j); - return result; -} -#endif - -// public domain zlib decode v0.2 Sean Barrett 2006-11-18 -// simple implementation -// - all input must be provided in an upfront buffer -// - all output is written to a single output buffer (can malloc/realloc) -// performance -// - fast huffman - -#ifndef STBI_NO_ZLIB - -// fast-way is faster to check than jpeg huffman, but slow way is slower -#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables -#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) -#define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet - -// zlib-style huffman encoding -// (jpegs packs from left, zlib from right, so can't share code) -typedef struct -{ - stbi__uint16 fast[1 << STBI__ZFAST_BITS]; - stbi__uint16 firstcode[16]; - int maxcode[17]; - stbi__uint16 firstsymbol[16]; - stbi_uc size[STBI__ZNSYMS]; - stbi__uint16 value[STBI__ZNSYMS]; -} stbi__zhuffman; - -stbi_inline static int stbi__bitreverse16(int n) -{ - n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); - n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); - n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); - n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); - return n; -} - -stbi_inline static int stbi__bit_reverse(int v, int bits) -{ - STBI_ASSERT(bits <= 16); - // to bit reverse n bits, reverse 16 and shift - // e.g. 11 bits, bit reverse and shift away 5 - return stbi__bitreverse16(v) >> (16-bits); -} - -static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num) -{ - int i,k=0; - int code, next_code[16], sizes[17]; - - // DEFLATE spec for generating codes - memset(sizes, 0, sizeof(sizes)); - memset(z->fast, 0, sizeof(z->fast)); - for (i=0; i < num; ++i) - ++sizes[sizelist[i]]; - sizes[0] = 0; - for (i=1; i < 16; ++i) - if (sizes[i] > (1 << i)) - return stbi__err("bad sizes", "Corrupt PNG"); - code = 0; - for (i=1; i < 16; ++i) { - next_code[i] = code; - z->firstcode[i] = (stbi__uint16) code; - z->firstsymbol[i] = (stbi__uint16) k; - code = (code + sizes[i]); - if (sizes[i]) - if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG"); - z->maxcode[i] = code << (16-i); // preshift for inner loop - code <<= 1; - k += sizes[i]; - } - z->maxcode[16] = 0x10000; // sentinel - for (i=0; i < num; ++i) { - int s = sizelist[i]; - if (s) { - int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; - stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i); - z->size [c] = (stbi_uc ) s; - z->value[c] = (stbi__uint16) i; - if (s <= STBI__ZFAST_BITS) { - int j = stbi__bit_reverse(next_code[s],s); - while (j < (1 << STBI__ZFAST_BITS)) { - z->fast[j] = fastv; - j += (1 << s); - } - } - ++next_code[s]; - } - } - return 1; -} - -// zlib-from-memory implementation for PNG reading -// because PNG allows splitting the zlib stream arbitrarily, -// and it's annoying structurally to have PNG call ZLIB call PNG, -// we require PNG read all the IDATs and combine them into a single -// memory buffer - -typedef struct -{ - stbi_uc *zbuffer, *zbuffer_end; - int num_bits; - stbi__uint32 code_buffer; - - char *zout; - char *zout_start; - char *zout_end; - int z_expandable; - - stbi__zhuffman z_length, z_distance; -} stbi__zbuf; - -stbi_inline static int stbi__zeof(stbi__zbuf *z) -{ - return (z->zbuffer >= z->zbuffer_end); -} - -stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) -{ - return stbi__zeof(z) ? 0 : *z->zbuffer++; -} - -static void stbi__fill_bits(stbi__zbuf *z) -{ - do { - if (z->code_buffer >= (1U << z->num_bits)) { - z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */ - return; - } - z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits; - z->num_bits += 8; - } while (z->num_bits <= 24); -} - -stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n) -{ - unsigned int k; - if (z->num_bits < n) stbi__fill_bits(z); - k = z->code_buffer & ((1 << n) - 1); - z->code_buffer >>= n; - z->num_bits -= n; - return k; -} - -static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) -{ - int b,s,k; - // not resolved by fast table, so compute it the slow way - // use jpeg approach, which requires MSbits at top - k = stbi__bit_reverse(a->code_buffer, 16); - for (s=STBI__ZFAST_BITS+1; ; ++s) - if (k < z->maxcode[s]) - break; - if (s >= 16) return -1; // invalid code! - // code size is s, so: - b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; - if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere! - if (z->size[b] != s) return -1; // was originally an assert, but report failure instead. - a->code_buffer >>= s; - a->num_bits -= s; - return z->value[b]; -} - -stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) -{ - int b,s; - if (a->num_bits < 16) { - if (stbi__zeof(a)) { - return -1; /* report error for unexpected end of data. */ - } - stbi__fill_bits(a); - } - b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; - if (b) { - s = b >> 9; - a->code_buffer >>= s; - a->num_bits -= s; - return b & 511; - } - return stbi__zhuffman_decode_slowpath(a, z); -} - -static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes -{ - char *q; - unsigned int cur, limit, old_limit; - z->zout = zout; - if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); - cur = (unsigned int) (z->zout - z->zout_start); - limit = old_limit = (unsigned) (z->zout_end - z->zout_start); - if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory"); - while (cur + n > limit) { - if(limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory"); - limit *= 2; - } - q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); - STBI_NOTUSED(old_limit); - if (q == NULL) return stbi__err("outofmem", "Out of memory"); - z->zout_start = q; - z->zout = q + cur; - z->zout_end = q + limit; - return 1; -} - -static const int stbi__zlength_base[31] = { - 3,4,5,6,7,8,9,10,11,13, - 15,17,19,23,27,31,35,43,51,59, - 67,83,99,115,131,163,195,227,258,0,0 }; - -static const int stbi__zlength_extra[31]= -{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; - -static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, -257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; - -static const int stbi__zdist_extra[32] = -{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; - -static int stbi__parse_huffman_block(stbi__zbuf *a) -{ - char *zout = a->zout; - for(;;) { - int z = stbi__zhuffman_decode(a, &a->z_length); - if (z < 256) { - if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes - if (zout >= a->zout_end) { - if (!stbi__zexpand(a, zout, 1)) return 0; - zout = a->zout; - } - *zout++ = (char) z; - } else { - stbi_uc *p; - int len,dist; - if (z == 256) { - a->zout = zout; - return 1; - } - if (z >= 286) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data - z -= 257; - len = stbi__zlength_base[z]; - if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); - z = stbi__zhuffman_decode(a, &a->z_distance); - if (z < 0 || z >= 30) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data - dist = stbi__zdist_base[z]; - if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); - if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG"); - if (zout + len > a->zout_end) { - if (!stbi__zexpand(a, zout, len)) return 0; - zout = a->zout; - } - p = (stbi_uc *) (zout - dist); - if (dist == 1) { // run of one byte; common in images. - stbi_uc v = *p; - if (len) { do *zout++ = v; while (--len); } - } else { - if (len) { do *zout++ = *p++; while (--len); } - } - } - } -} - -static int stbi__compute_huffman_codes(stbi__zbuf *a) -{ - static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; - stbi__zhuffman z_codelength; - stbi_uc lencodes[286+32+137];//padding for maximum single op - stbi_uc codelength_sizes[19]; - int i,n; - - int hlit = stbi__zreceive(a,5) + 257; - int hdist = stbi__zreceive(a,5) + 1; - int hclen = stbi__zreceive(a,4) + 4; - int ntot = hlit + hdist; - - memset(codelength_sizes, 0, sizeof(codelength_sizes)); - for (i=0; i < hclen; ++i) { - int s = stbi__zreceive(a,3); - codelength_sizes[length_dezigzag[i]] = (stbi_uc) s; - } - if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; - - n = 0; - while (n < ntot) { - int c = stbi__zhuffman_decode(a, &z_codelength); - if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); - if (c < 16) - lencodes[n++] = (stbi_uc) c; - else { - stbi_uc fill = 0; - if (c == 16) { - c = stbi__zreceive(a,2)+3; - if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); - fill = lencodes[n-1]; - } else if (c == 17) { - c = stbi__zreceive(a,3)+3; - } else if (c == 18) { - c = stbi__zreceive(a,7)+11; - } else { - return stbi__err("bad codelengths", "Corrupt PNG"); - } - if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); - memset(lencodes+n, fill, c); - n += c; - } - } - if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG"); - if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; - if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; - return 1; -} - -static int stbi__parse_uncompressed_block(stbi__zbuf *a) -{ - stbi_uc header[4]; - int len,nlen,k; - if (a->num_bits & 7) - stbi__zreceive(a, a->num_bits & 7); // discard - // drain the bit-packed data into header - k = 0; - while (a->num_bits > 0) { - header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check - a->code_buffer >>= 8; - a->num_bits -= 8; - } - if (a->num_bits < 0) return stbi__err("zlib corrupt","Corrupt PNG"); - // now fill header the normal way - while (k < 4) - header[k++] = stbi__zget8(a); - len = header[1] * 256 + header[0]; - nlen = header[3] * 256 + header[2]; - if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG"); - if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG"); - if (a->zout + len > a->zout_end) - if (!stbi__zexpand(a, a->zout, len)) return 0; - memcpy(a->zout, a->zbuffer, len); - a->zbuffer += len; - a->zout += len; - return 1; -} - -static int stbi__parse_zlib_header(stbi__zbuf *a) -{ - int cmf = stbi__zget8(a); - int cm = cmf & 15; - /* int cinfo = cmf >> 4; */ - int flg = stbi__zget8(a); - if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec - if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec - if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png - if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png - // window = 1 << (8 + cinfo)... but who cares, we fully buffer output - return 1; -} - -static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] = -{ - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, - 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, - 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, - 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, - 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, - 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8 -}; -static const stbi_uc stbi__zdefault_distance[32] = -{ - 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 -}; -/* -Init algorithm: -{ - int i; // use <= to match clearly with spec - for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; - for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9; - for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7; - for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8; - - for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; -} -*/ - -static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) -{ - int final, type; - if (parse_header) - if (!stbi__parse_zlib_header(a)) return 0; - a->num_bits = 0; - a->code_buffer = 0; - do { - final = stbi__zreceive(a,1); - type = stbi__zreceive(a,2); - if (type == 0) { - if (!stbi__parse_uncompressed_block(a)) return 0; - } else if (type == 3) { - return 0; - } else { - if (type == 1) { - // use fixed code lengths - if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , STBI__ZNSYMS)) return 0; - if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; - } else { - if (!stbi__compute_huffman_codes(a)) return 0; - } - if (!stbi__parse_huffman_block(a)) return 0; - } - } while (!final); - return 1; -} - -static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header) -{ - a->zout_start = obuf; - a->zout = obuf; - a->zout_end = obuf + olen; - a->z_expandable = exp; - - return stbi__parse_zlib(a, parse_header); -} - -STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) -{ - stbi__zbuf a; - char *p = (char *) stbi__malloc(initial_size); - if (p == NULL) return NULL; - a.zbuffer = (stbi_uc *) buffer; - a.zbuffer_end = (stbi_uc *) buffer + len; - if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { - if (outlen) *outlen = (int) (a.zout - a.zout_start); - return a.zout_start; - } else { - STBI_FREE(a.zout_start); - return NULL; - } -} - -STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) -{ - return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); -} - -STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) -{ - stbi__zbuf a; - char *p = (char *) stbi__malloc(initial_size); - if (p == NULL) return NULL; - a.zbuffer = (stbi_uc *) buffer; - a.zbuffer_end = (stbi_uc *) buffer + len; - if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { - if (outlen) *outlen = (int) (a.zout - a.zout_start); - return a.zout_start; - } else { - STBI_FREE(a.zout_start); - return NULL; - } -} - -STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) -{ - stbi__zbuf a; - a.zbuffer = (stbi_uc *) ibuffer; - a.zbuffer_end = (stbi_uc *) ibuffer + ilen; - if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) - return (int) (a.zout - a.zout_start); - else - return -1; -} - -STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) -{ - stbi__zbuf a; - char *p = (char *) stbi__malloc(16384); - if (p == NULL) return NULL; - a.zbuffer = (stbi_uc *) buffer; - a.zbuffer_end = (stbi_uc *) buffer+len; - if (stbi__do_zlib(&a, p, 16384, 1, 0)) { - if (outlen) *outlen = (int) (a.zout - a.zout_start); - return a.zout_start; - } else { - STBI_FREE(a.zout_start); - return NULL; - } -} - -STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) -{ - stbi__zbuf a; - a.zbuffer = (stbi_uc *) ibuffer; - a.zbuffer_end = (stbi_uc *) ibuffer + ilen; - if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) - return (int) (a.zout - a.zout_start); - else - return -1; -} -#endif - -// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 -// simple implementation -// - only 8-bit samples -// - no CRC checking -// - allocates lots of intermediate memory -// - avoids problem of streaming data between subsystems -// - avoids explicit window management -// performance -// - uses stb_zlib, a PD zlib implementation with fast huffman decoding - -#ifndef STBI_NO_PNG -typedef struct -{ - stbi__uint32 length; - stbi__uint32 type; -} stbi__pngchunk; - -static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) -{ - stbi__pngchunk c; - c.length = stbi__get32be(s); - c.type = stbi__get32be(s); - return c; -} - -static int stbi__check_png_header(stbi__context *s) -{ - static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; - int i; - for (i=0; i < 8; ++i) - if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG"); - return 1; -} - -typedef struct -{ - stbi__context *s; - stbi_uc *idata, *expanded, *out; - int depth; -} stbi__png; - - -enum { - STBI__F_none=0, - STBI__F_sub=1, - STBI__F_up=2, - STBI__F_avg=3, - STBI__F_paeth=4, - // synthetic filters used for first scanline to avoid needing a dummy row of 0s - STBI__F_avg_first, - STBI__F_paeth_first -}; - -static stbi_uc first_row_filter[5] = -{ - STBI__F_none, - STBI__F_sub, - STBI__F_none, - STBI__F_avg_first, - STBI__F_paeth_first -}; - -static int stbi__paeth(int a, int b, int c) -{ - int p = a + b - c; - int pa = abs(p-a); - int pb = abs(p-b); - int pc = abs(p-c); - if (pa <= pb && pa <= pc) return a; - if (pb <= pc) return b; - return c; -} - -static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; - -// create the png data from post-deflated data -static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) -{ - int bytes = (depth == 16? 2 : 1); - stbi__context *s = a->s; - stbi__uint32 i,j,stride = x*out_n*bytes; - stbi__uint32 img_len, img_width_bytes; - int k; - int img_n = s->img_n; // copy it into a local for later - - int output_bytes = out_n*bytes; - int filter_bytes = img_n*bytes; - int width = x; - - STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1); - a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into - if (!a->out) return stbi__err("outofmem", "Out of memory"); - - if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG"); - img_width_bytes = (((img_n * x * depth) + 7) >> 3); - img_len = (img_width_bytes + 1) * y; - - // we used to check for exact match between raw_len and img_len on non-interlaced PNGs, - // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros), - // so just check for raw_len < img_len always. - if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); - - for (j=0; j < y; ++j) { - stbi_uc *cur = a->out + stride*j; - stbi_uc *prior; - int filter = *raw++; - - if (filter > 4) - return stbi__err("invalid filter","Corrupt PNG"); - - if (depth < 8) { - if (img_width_bytes > x) return stbi__err("invalid width","Corrupt PNG"); - cur += x*out_n - img_width_bytes; // store output to the rightmost img_len bytes, so we can decode in place - filter_bytes = 1; - width = img_width_bytes; - } - prior = cur - stride; // bugfix: need to compute this after 'cur +=' computation above - - // if first row, use special filter that doesn't sample previous row - if (j == 0) filter = first_row_filter[filter]; - - // handle first byte explicitly - for (k=0; k < filter_bytes; ++k) { - switch (filter) { - case STBI__F_none : cur[k] = raw[k]; break; - case STBI__F_sub : cur[k] = raw[k]; break; - case STBI__F_up : cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; - case STBI__F_avg : cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1)); break; - case STBI__F_paeth : cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(0,prior[k],0)); break; - case STBI__F_avg_first : cur[k] = raw[k]; break; - case STBI__F_paeth_first: cur[k] = raw[k]; break; - } - } - - if (depth == 8) { - if (img_n != out_n) - cur[img_n] = 255; // first pixel - raw += img_n; - cur += out_n; - prior += out_n; - } else if (depth == 16) { - if (img_n != out_n) { - cur[filter_bytes] = 255; // first pixel top byte - cur[filter_bytes+1] = 255; // first pixel bottom byte - } - raw += filter_bytes; - cur += output_bytes; - prior += output_bytes; - } else { - raw += 1; - cur += 1; - prior += 1; - } - - // this is a little gross, so that we don't switch per-pixel or per-component - if (depth < 8 || img_n == out_n) { - int nk = (width - 1)*filter_bytes; - #define STBI__CASE(f) \ - case f: \ - for (k=0; k < nk; ++k) - switch (filter) { - // "none" filter turns into a memcpy here; make that explicit. - case STBI__F_none: memcpy(cur, raw, nk); break; - STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); } break; - STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; - STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); } break; - STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); } break; - STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); } break; - STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); } break; - } - #undef STBI__CASE - raw += nk; - } else { - STBI_ASSERT(img_n+1 == out_n); - #define STBI__CASE(f) \ - case f: \ - for (i=x-1; i >= 1; --i, cur[filter_bytes]=255,raw+=filter_bytes,cur+=output_bytes,prior+=output_bytes) \ - for (k=0; k < filter_bytes; ++k) - switch (filter) { - STBI__CASE(STBI__F_none) { cur[k] = raw[k]; } break; - STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k- output_bytes]); } break; - STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; - STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k- output_bytes])>>1)); } break; - STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],prior[k],prior[k- output_bytes])); } break; - STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k- output_bytes] >> 1)); } break; - STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],0,0)); } break; - } - #undef STBI__CASE - - // the loop above sets the high byte of the pixels' alpha, but for - // 16 bit png files we also need the low byte set. we'll do that here. - if (depth == 16) { - cur = a->out + stride*j; // start at the beginning of the row again - for (i=0; i < x; ++i,cur+=output_bytes) { - cur[filter_bytes+1] = 255; - } - } - } - } - - // we make a separate pass to expand bits to pixels; for performance, - // this could run two scanlines behind the above code, so it won't - // intefere with filtering but will still be in the cache. - if (depth < 8) { - for (j=0; j < y; ++j) { - stbi_uc *cur = a->out + stride*j; - stbi_uc *in = a->out + stride*j + x*out_n - img_width_bytes; - // unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common 8-bit path optimal at minimal cost for 1/2/4-bit - // png guarante byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop - stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range - - // note that the final byte might overshoot and write more data than desired. - // we can allocate enough data that this never writes out of memory, but it - // could also overwrite the next scanline. can it overwrite non-empty data - // on the next scanline? yes, consider 1-pixel-wide scanlines with 1-bit-per-pixel. - // so we need to explicitly clamp the final ones - - if (depth == 4) { - for (k=x*img_n; k >= 2; k-=2, ++in) { - *cur++ = scale * ((*in >> 4) ); - *cur++ = scale * ((*in ) & 0x0f); - } - if (k > 0) *cur++ = scale * ((*in >> 4) ); - } else if (depth == 2) { - for (k=x*img_n; k >= 4; k-=4, ++in) { - *cur++ = scale * ((*in >> 6) ); - *cur++ = scale * ((*in >> 4) & 0x03); - *cur++ = scale * ((*in >> 2) & 0x03); - *cur++ = scale * ((*in ) & 0x03); - } - if (k > 0) *cur++ = scale * ((*in >> 6) ); - if (k > 1) *cur++ = scale * ((*in >> 4) & 0x03); - if (k > 2) *cur++ = scale * ((*in >> 2) & 0x03); - } else if (depth == 1) { - for (k=x*img_n; k >= 8; k-=8, ++in) { - *cur++ = scale * ((*in >> 7) ); - *cur++ = scale * ((*in >> 6) & 0x01); - *cur++ = scale * ((*in >> 5) & 0x01); - *cur++ = scale * ((*in >> 4) & 0x01); - *cur++ = scale * ((*in >> 3) & 0x01); - *cur++ = scale * ((*in >> 2) & 0x01); - *cur++ = scale * ((*in >> 1) & 0x01); - *cur++ = scale * ((*in ) & 0x01); - } - if (k > 0) *cur++ = scale * ((*in >> 7) ); - if (k > 1) *cur++ = scale * ((*in >> 6) & 0x01); - if (k > 2) *cur++ = scale * ((*in >> 5) & 0x01); - if (k > 3) *cur++ = scale * ((*in >> 4) & 0x01); - if (k > 4) *cur++ = scale * ((*in >> 3) & 0x01); - if (k > 5) *cur++ = scale * ((*in >> 2) & 0x01); - if (k > 6) *cur++ = scale * ((*in >> 1) & 0x01); - } - if (img_n != out_n) { - int q; - // insert alpha = 255 - cur = a->out + stride*j; - if (img_n == 1) { - for (q=x-1; q >= 0; --q) { - cur[q*2+1] = 255; - cur[q*2+0] = cur[q]; - } - } else { - STBI_ASSERT(img_n == 3); - for (q=x-1; q >= 0; --q) { - cur[q*4+3] = 255; - cur[q*4+2] = cur[q*3+2]; - cur[q*4+1] = cur[q*3+1]; - cur[q*4+0] = cur[q*3+0]; - } - } - } - } - } else if (depth == 16) { - // force the image data from big-endian to platform-native. - // this is done in a separate pass due to the decoding relying - // on the data being untouched, but could probably be done - // per-line during decode if care is taken. - stbi_uc *cur = a->out; - stbi__uint16 *cur16 = (stbi__uint16*)cur; - - for(i=0; i < x*y*out_n; ++i,cur16++,cur+=2) { - *cur16 = (cur[0] << 8) | cur[1]; - } - } - - return 1; -} - -static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) -{ - int bytes = (depth == 16 ? 2 : 1); - int out_bytes = out_n * bytes; - stbi_uc *final; - int p; - if (!interlaced) - return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); - - // de-interlacing - final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); - if (!final) return stbi__err("outofmem", "Out of memory"); - for (p=0; p < 7; ++p) { - int xorig[] = { 0,4,0,2,0,1,0 }; - int yorig[] = { 0,0,4,0,2,0,1 }; - int xspc[] = { 8,8,4,4,2,2,1 }; - int yspc[] = { 8,8,8,4,4,2,2 }; - int i,j,x,y; - // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 - x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p]; - y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p]; - if (x && y) { - stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; - if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { - STBI_FREE(final); - return 0; - } - for (j=0; j < y; ++j) { - for (i=0; i < x; ++i) { - int out_y = j*yspc[p]+yorig[p]; - int out_x = i*xspc[p]+xorig[p]; - memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes, - a->out + (j*x+i)*out_bytes, out_bytes); - } - } - STBI_FREE(a->out); - image_data += img_len; - image_data_len -= img_len; - } - } - a->out = final; - - return 1; -} - -static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) -{ - stbi__context *s = z->s; - stbi__uint32 i, pixel_count = s->img_x * s->img_y; - stbi_uc *p = z->out; - - // compute color-based transparency, assuming we've - // already got 255 as the alpha value in the output - STBI_ASSERT(out_n == 2 || out_n == 4); - - if (out_n == 2) { - for (i=0; i < pixel_count; ++i) { - p[1] = (p[0] == tc[0] ? 0 : 255); - p += 2; - } - } else { - for (i=0; i < pixel_count; ++i) { - if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) - p[3] = 0; - p += 4; - } - } - return 1; -} - -static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n) -{ - stbi__context *s = z->s; - stbi__uint32 i, pixel_count = s->img_x * s->img_y; - stbi__uint16 *p = (stbi__uint16*) z->out; - - // compute color-based transparency, assuming we've - // already got 65535 as the alpha value in the output - STBI_ASSERT(out_n == 2 || out_n == 4); - - if (out_n == 2) { - for (i = 0; i < pixel_count; ++i) { - p[1] = (p[0] == tc[0] ? 0 : 65535); - p += 2; - } - } else { - for (i = 0; i < pixel_count; ++i) { - if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) - p[3] = 0; - p += 4; - } - } - return 1; -} - -static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) -{ - stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; - stbi_uc *p, *temp_out, *orig = a->out; - - p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0); - if (p == NULL) return stbi__err("outofmem", "Out of memory"); - - // between here and free(out) below, exitting would leak - temp_out = p; - - if (pal_img_n == 3) { - for (i=0; i < pixel_count; ++i) { - int n = orig[i]*4; - p[0] = palette[n ]; - p[1] = palette[n+1]; - p[2] = palette[n+2]; - p += 3; - } - } else { - for (i=0; i < pixel_count; ++i) { - int n = orig[i]*4; - p[0] = palette[n ]; - p[1] = palette[n+1]; - p[2] = palette[n+2]; - p[3] = palette[n+3]; - p += 4; - } - } - STBI_FREE(a->out); - a->out = temp_out; - - STBI_NOTUSED(len); - - return 1; -} - -static int stbi__unpremultiply_on_load_global = 0; -static int stbi__de_iphone_flag_global = 0; - -STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) -{ - stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply; -} - -STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) -{ - stbi__de_iphone_flag_global = flag_true_if_should_convert; -} - -#ifndef STBI_THREAD_LOCAL -#define stbi__unpremultiply_on_load stbi__unpremultiply_on_load_global -#define stbi__de_iphone_flag stbi__de_iphone_flag_global -#else -static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set; -static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set; - -STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply) -{ - stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply; - stbi__unpremultiply_on_load_set = 1; -} - -STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert) -{ - stbi__de_iphone_flag_local = flag_true_if_should_convert; - stbi__de_iphone_flag_set = 1; -} - -#define stbi__unpremultiply_on_load (stbi__unpremultiply_on_load_set \ - ? stbi__unpremultiply_on_load_local \ - : stbi__unpremultiply_on_load_global) -#define stbi__de_iphone_flag (stbi__de_iphone_flag_set \ - ? stbi__de_iphone_flag_local \ - : stbi__de_iphone_flag_global) -#endif // STBI_THREAD_LOCAL - -static void stbi__de_iphone(stbi__png *z) -{ - stbi__context *s = z->s; - stbi__uint32 i, pixel_count = s->img_x * s->img_y; - stbi_uc *p = z->out; - - if (s->img_out_n == 3) { // convert bgr to rgb - for (i=0; i < pixel_count; ++i) { - stbi_uc t = p[0]; - p[0] = p[2]; - p[2] = t; - p += 3; - } - } else { - STBI_ASSERT(s->img_out_n == 4); - if (stbi__unpremultiply_on_load) { - // convert bgr to rgb and unpremultiply - for (i=0; i < pixel_count; ++i) { - stbi_uc a = p[3]; - stbi_uc t = p[0]; - if (a) { - stbi_uc half = a / 2; - p[0] = (p[2] * 255 + half) / a; - p[1] = (p[1] * 255 + half) / a; - p[2] = ( t * 255 + half) / a; - } else { - p[0] = p[2]; - p[2] = t; - } - p += 4; - } - } else { - // convert bgr to rgb - for (i=0; i < pixel_count; ++i) { - stbi_uc t = p[0]; - p[0] = p[2]; - p[2] = t; - p += 4; - } - } - } -} - -#define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d)) - -static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) -{ - stbi_uc palette[1024], pal_img_n=0; - stbi_uc has_trans=0, tc[3]={0}; - stbi__uint16 tc16[3]; - stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0; - int first=1,k,interlace=0, color=0, is_iphone=0; - stbi__context *s = z->s; - - z->expanded = NULL; - z->idata = NULL; - z->out = NULL; - - if (!stbi__check_png_header(s)) return 0; - - if (scan == STBI__SCAN_type) return 1; - - for (;;) { - stbi__pngchunk c = stbi__get_chunk_header(s); - switch (c.type) { - case STBI__PNG_TYPE('C','g','B','I'): - is_iphone = 1; - stbi__skip(s, c.length); - break; - case STBI__PNG_TYPE('I','H','D','R'): { - int comp,filter; - if (!first) return stbi__err("multiple IHDR","Corrupt PNG"); - first = 0; - if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG"); - s->img_x = stbi__get32be(s); - s->img_y = stbi__get32be(s); - if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); - if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); - z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only"); - color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG"); - if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG"); - if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG"); - comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG"); - filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG"); - interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG"); - if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG"); - if (!pal_img_n) { - s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); - if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); - } else { - // if paletted, then pal_n is our final components, and - // img_n is # components to decompress/filter. - s->img_n = 1; - if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG"); - } - // even with SCAN_header, have to scan to see if we have a tRNS - break; - } - - case STBI__PNG_TYPE('P','L','T','E'): { - if (first) return stbi__err("first not IHDR", "Corrupt PNG"); - if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG"); - pal_len = c.length / 3; - if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG"); - for (i=0; i < pal_len; ++i) { - palette[i*4+0] = stbi__get8(s); - palette[i*4+1] = stbi__get8(s); - palette[i*4+2] = stbi__get8(s); - palette[i*4+3] = 255; - } - break; - } - - case STBI__PNG_TYPE('t','R','N','S'): { - if (first) return stbi__err("first not IHDR", "Corrupt PNG"); - if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG"); - if (pal_img_n) { - if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } - if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG"); - if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG"); - pal_img_n = 4; - for (i=0; i < c.length; ++i) - palette[i*4+3] = stbi__get8(s); - } else { - if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG"); - if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG"); - has_trans = 1; - // non-paletted with tRNS = constant alpha. if header-scanning, we can stop now. - if (scan == STBI__SCAN_header) { ++s->img_n; return 1; } - if (z->depth == 16) { - for (k = 0; k < s->img_n; ++k) tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is - } else { - for (k = 0; k < s->img_n; ++k) tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger - } - } - break; - } - - case STBI__PNG_TYPE('I','D','A','T'): { - if (first) return stbi__err("first not IHDR", "Corrupt PNG"); - if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG"); - if (scan == STBI__SCAN_header) { - // header scan definitely stops at first IDAT - if (pal_img_n) - s->img_n = pal_img_n; - return 1; - } - if (c.length > (1u << 30)) return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes"); - if ((int)(ioff + c.length) < (int)ioff) return 0; - if (ioff + c.length > idata_limit) { - stbi__uint32 idata_limit_old = idata_limit; - stbi_uc *p; - if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; - while (ioff + c.length > idata_limit) - idata_limit *= 2; - STBI_NOTUSED(idata_limit_old); - p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); - z->idata = p; - } - if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG"); - ioff += c.length; - break; - } - - case STBI__PNG_TYPE('I','E','N','D'): { - stbi__uint32 raw_len, bpl; - if (first) return stbi__err("first not IHDR", "Corrupt PNG"); - if (scan != STBI__SCAN_load) return 1; - if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG"); - // initial guess for decoded data size to avoid unnecessary reallocs - bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component - raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; - z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); - if (z->expanded == NULL) return 0; // zlib should set error - STBI_FREE(z->idata); z->idata = NULL; - if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans) - s->img_out_n = s->img_n+1; - else - s->img_out_n = s->img_n; - if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0; - if (has_trans) { - if (z->depth == 16) { - if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; - } else { - if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; - } - } - if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) - stbi__de_iphone(z); - if (pal_img_n) { - // pal_img_n == 3 or 4 - s->img_n = pal_img_n; // record the actual colors we had - s->img_out_n = pal_img_n; - if (req_comp >= 3) s->img_out_n = req_comp; - if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) - return 0; - } else if (has_trans) { - // non-paletted image with tRNS -> source image has (constant) alpha - ++s->img_n; - } - STBI_FREE(z->expanded); z->expanded = NULL; - // end of PNG chunk, read and skip CRC - stbi__get32be(s); - return 1; - } - - default: - // if critical, fail - if (first) return stbi__err("first not IHDR", "Corrupt PNG"); - if ((c.type & (1 << 29)) == 0) { - #ifndef STBI_NO_FAILURE_STRINGS - // not threadsafe - static char invalid_chunk[] = "XXXX PNG chunk not known"; - invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); - invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); - invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); - invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); - #endif - return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); - } - stbi__skip(s, c.length); - break; - } - // end of PNG chunk, read and skip CRC - stbi__get32be(s); - } -} - -static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri) -{ - void *result=NULL; - if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); - if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { - if (p->depth <= 8) - ri->bits_per_channel = 8; - else if (p->depth == 16) - ri->bits_per_channel = 16; - else - return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth"); - result = p->out; - p->out = NULL; - if (req_comp && req_comp != p->s->img_out_n) { - if (ri->bits_per_channel == 8) - result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); - else - result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); - p->s->img_out_n = req_comp; - if (result == NULL) return result; - } - *x = p->s->img_x; - *y = p->s->img_y; - if (n) *n = p->s->img_n; - } - STBI_FREE(p->out); p->out = NULL; - STBI_FREE(p->expanded); p->expanded = NULL; - STBI_FREE(p->idata); p->idata = NULL; - - return result; -} - -static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - stbi__png p; - p.s = s; - return stbi__do_png(&p, x,y,comp,req_comp, ri); -} - -static int stbi__png_test(stbi__context *s) -{ - int r; - r = stbi__check_png_header(s); - stbi__rewind(s); - return r; -} - -static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) -{ - if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { - stbi__rewind( p->s ); - return 0; - } - if (x) *x = p->s->img_x; - if (y) *y = p->s->img_y; - if (comp) *comp = p->s->img_n; - return 1; -} - -static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) -{ - stbi__png p; - p.s = s; - return stbi__png_info_raw(&p, x, y, comp); -} - -static int stbi__png_is16(stbi__context *s) -{ - stbi__png p; - p.s = s; - if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) - return 0; - if (p.depth != 16) { - stbi__rewind(p.s); - return 0; - } - return 1; -} -#endif - -// Microsoft/Windows BMP image - -#ifndef STBI_NO_BMP -static int stbi__bmp_test_raw(stbi__context *s) -{ - int r; - int sz; - if (stbi__get8(s) != 'B') return 0; - if (stbi__get8(s) != 'M') return 0; - stbi__get32le(s); // discard filesize - stbi__get16le(s); // discard reserved - stbi__get16le(s); // discard reserved - stbi__get32le(s); // discard data offset - sz = stbi__get32le(s); - r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); - return r; -} - -static int stbi__bmp_test(stbi__context *s) -{ - int r = stbi__bmp_test_raw(s); - stbi__rewind(s); - return r; -} - - -// returns 0..31 for the highest set bit -static int stbi__high_bit(unsigned int z) -{ - int n=0; - if (z == 0) return -1; - if (z >= 0x10000) { n += 16; z >>= 16; } - if (z >= 0x00100) { n += 8; z >>= 8; } - if (z >= 0x00010) { n += 4; z >>= 4; } - if (z >= 0x00004) { n += 2; z >>= 2; } - if (z >= 0x00002) { n += 1;/* >>= 1;*/ } - return n; -} - -static int stbi__bitcount(unsigned int a) -{ - a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 - a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 - a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits - a = (a + (a >> 8)); // max 16 per 8 bits - a = (a + (a >> 16)); // max 32 per 8 bits - return a & 0xff; -} - -// extract an arbitrarily-aligned N-bit value (N=bits) -// from v, and then make it 8-bits long and fractionally -// extend it to full full range. -static int stbi__shiftsigned(unsigned int v, int shift, int bits) -{ - static unsigned int mul_table[9] = { - 0, - 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/, - 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/, - }; - static unsigned int shift_table[9] = { - 0, 0,0,1,0,2,4,6,0, - }; - if (shift < 0) - v <<= -shift; - else - v >>= shift; - STBI_ASSERT(v < 256); - v >>= (8-bits); - STBI_ASSERT(bits >= 0 && bits <= 8); - return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits]; -} - -typedef struct -{ - int bpp, offset, hsz; - unsigned int mr,mg,mb,ma, all_a; - int extra_read; -} stbi__bmp_data; - -static int stbi__bmp_set_mask_defaults(stbi__bmp_data *info, int compress) -{ - // BI_BITFIELDS specifies masks explicitly, don't override - if (compress == 3) - return 1; - - if (compress == 0) { - if (info->bpp == 16) { - info->mr = 31u << 10; - info->mg = 31u << 5; - info->mb = 31u << 0; - } else if (info->bpp == 32) { - info->mr = 0xffu << 16; - info->mg = 0xffu << 8; - info->mb = 0xffu << 0; - info->ma = 0xffu << 24; - info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 - } else { - // otherwise, use defaults, which is all-0 - info->mr = info->mg = info->mb = info->ma = 0; - } - return 1; - } - return 0; // error -} - -static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) -{ - int hsz; - if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); - stbi__get32le(s); // discard filesize - stbi__get16le(s); // discard reserved - stbi__get16le(s); // discard reserved - info->offset = stbi__get32le(s); - info->hsz = hsz = stbi__get32le(s); - info->mr = info->mg = info->mb = info->ma = 0; - info->extra_read = 14; - - if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP"); - - if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); - if (hsz == 12) { - s->img_x = stbi__get16le(s); - s->img_y = stbi__get16le(s); - } else { - s->img_x = stbi__get32le(s); - s->img_y = stbi__get32le(s); - } - if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); - info->bpp = stbi__get16le(s); - if (hsz != 12) { - int compress = stbi__get32le(s); - if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); - if (compress >= 4) return stbi__errpuc("BMP JPEG/PNG", "BMP type not supported: unsupported compression"); // this includes PNG/JPEG modes - if (compress == 3 && info->bpp != 16 && info->bpp != 32) return stbi__errpuc("bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel - stbi__get32le(s); // discard sizeof - stbi__get32le(s); // discard hres - stbi__get32le(s); // discard vres - stbi__get32le(s); // discard colorsused - stbi__get32le(s); // discard max important - if (hsz == 40 || hsz == 56) { - if (hsz == 56) { - stbi__get32le(s); - stbi__get32le(s); - stbi__get32le(s); - stbi__get32le(s); - } - if (info->bpp == 16 || info->bpp == 32) { - if (compress == 0) { - stbi__bmp_set_mask_defaults(info, compress); - } else if (compress == 3) { - info->mr = stbi__get32le(s); - info->mg = stbi__get32le(s); - info->mb = stbi__get32le(s); - info->extra_read += 12; - // not documented, but generated by photoshop and handled by mspaint - if (info->mr == info->mg && info->mg == info->mb) { - // ?!?!? - return stbi__errpuc("bad BMP", "bad BMP"); - } - } else - return stbi__errpuc("bad BMP", "bad BMP"); - } - } else { - // V4/V5 header - int i; - if (hsz != 108 && hsz != 124) - return stbi__errpuc("bad BMP", "bad BMP"); - info->mr = stbi__get32le(s); - info->mg = stbi__get32le(s); - info->mb = stbi__get32le(s); - info->ma = stbi__get32le(s); - if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs - stbi__bmp_set_mask_defaults(info, compress); - stbi__get32le(s); // discard color space - for (i=0; i < 12; ++i) - stbi__get32le(s); // discard color space parameters - if (hsz == 124) { - stbi__get32le(s); // discard rendering intent - stbi__get32le(s); // discard offset of profile data - stbi__get32le(s); // discard size of profile data - stbi__get32le(s); // discard reserved - } - } - } - return (void *) 1; -} - - -static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - stbi_uc *out; - unsigned int mr=0,mg=0,mb=0,ma=0, all_a; - stbi_uc pal[256][4]; - int psize=0,i,j,width; - int flip_vertically, pad, target; - stbi__bmp_data info; - STBI_NOTUSED(ri); - - info.all_a = 255; - if (stbi__bmp_parse_header(s, &info) == NULL) - return NULL; // error code already set - - flip_vertically = ((int) s->img_y) > 0; - s->img_y = abs((int) s->img_y); - - if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - - mr = info.mr; - mg = info.mg; - mb = info.mb; - ma = info.ma; - all_a = info.all_a; - - if (info.hsz == 12) { - if (info.bpp < 24) - psize = (info.offset - info.extra_read - 24) / 3; - } else { - if (info.bpp < 16) - psize = (info.offset - info.extra_read - info.hsz) >> 2; - } - if (psize == 0) { - // accept some number of extra bytes after the header, but if the offset points either to before - // the header ends or implies a large amount of extra data, reject the file as malformed - int bytes_read_so_far = s->callback_already_read + (int)(s->img_buffer - s->img_buffer_original); - int header_limit = 1024; // max we actually read is below 256 bytes currently. - int extra_data_limit = 256*4; // what ordinarily goes here is a palette; 256 entries*4 bytes is its max size. - if (bytes_read_so_far <= 0 || bytes_read_so_far > header_limit) { - return stbi__errpuc("bad header", "Corrupt BMP"); - } - // we established that bytes_read_so_far is positive and sensible. - // the first half of this test rejects offsets that are either too small positives, or - // negative, and guarantees that info.offset >= bytes_read_so_far > 0. this in turn - // ensures the number computed in the second half of the test can't overflow. - if (info.offset < bytes_read_so_far || info.offset - bytes_read_so_far > extra_data_limit) { - return stbi__errpuc("bad offset", "Corrupt BMP"); - } else { - stbi__skip(s, info.offset - bytes_read_so_far); - } - } - - if (info.bpp == 24 && ma == 0xff000000) - s->img_n = 3; - else - s->img_n = ma ? 4 : 3; - if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 - target = req_comp; - else - target = s->img_n; // if they want monochrome, we'll post-convert - - // sanity-check size - if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) - return stbi__errpuc("too large", "Corrupt BMP"); - - out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0); - if (!out) return stbi__errpuc("outofmem", "Out of memory"); - if (info.bpp < 16) { - int z=0; - if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } - for (i=0; i < psize; ++i) { - pal[i][2] = stbi__get8(s); - pal[i][1] = stbi__get8(s); - pal[i][0] = stbi__get8(s); - if (info.hsz != 12) stbi__get8(s); - pal[i][3] = 255; - } - stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); - if (info.bpp == 1) width = (s->img_x + 7) >> 3; - else if (info.bpp == 4) width = (s->img_x + 1) >> 1; - else if (info.bpp == 8) width = s->img_x; - else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } - pad = (-width)&3; - if (info.bpp == 1) { - for (j=0; j < (int) s->img_y; ++j) { - int bit_offset = 7, v = stbi__get8(s); - for (i=0; i < (int) s->img_x; ++i) { - int color = (v>>bit_offset)&0x1; - out[z++] = pal[color][0]; - out[z++] = pal[color][1]; - out[z++] = pal[color][2]; - if (target == 4) out[z++] = 255; - if (i+1 == (int) s->img_x) break; - if((--bit_offset) < 0) { - bit_offset = 7; - v = stbi__get8(s); - } - } - stbi__skip(s, pad); - } - } else { - for (j=0; j < (int) s->img_y; ++j) { - for (i=0; i < (int) s->img_x; i += 2) { - int v=stbi__get8(s),v2=0; - if (info.bpp == 4) { - v2 = v & 15; - v >>= 4; - } - out[z++] = pal[v][0]; - out[z++] = pal[v][1]; - out[z++] = pal[v][2]; - if (target == 4) out[z++] = 255; - if (i+1 == (int) s->img_x) break; - v = (info.bpp == 8) ? stbi__get8(s) : v2; - out[z++] = pal[v][0]; - out[z++] = pal[v][1]; - out[z++] = pal[v][2]; - if (target == 4) out[z++] = 255; - } - stbi__skip(s, pad); - } - } - } else { - int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; - int z = 0; - int easy=0; - stbi__skip(s, info.offset - info.extra_read - info.hsz); - if (info.bpp == 24) width = 3 * s->img_x; - else if (info.bpp == 16) width = 2*s->img_x; - else /* bpp = 32 and pad = 0 */ width=0; - pad = (-width) & 3; - if (info.bpp == 24) { - easy = 1; - } else if (info.bpp == 32) { - if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) - easy = 2; - } - if (!easy) { - if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } - // right shift amt to put high bit in position #7 - rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr); - gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg); - bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb); - ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma); - if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } - } - for (j=0; j < (int) s->img_y; ++j) { - if (easy) { - for (i=0; i < (int) s->img_x; ++i) { - unsigned char a; - out[z+2] = stbi__get8(s); - out[z+1] = stbi__get8(s); - out[z+0] = stbi__get8(s); - z += 3; - a = (easy == 2 ? stbi__get8(s) : 255); - all_a |= a; - if (target == 4) out[z++] = a; - } - } else { - int bpp = info.bpp; - for (i=0; i < (int) s->img_x; ++i) { - stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s)); - unsigned int a; - out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); - out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); - out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); - a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); - all_a |= a; - if (target == 4) out[z++] = STBI__BYTECAST(a); - } - } - stbi__skip(s, pad); - } - } - - // if alpha channel is all 0s, replace with all 255s - if (target == 4 && all_a == 0) - for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4) - out[i] = 255; - - if (flip_vertically) { - stbi_uc t; - for (j=0; j < (int) s->img_y>>1; ++j) { - stbi_uc *p1 = out + j *s->img_x*target; - stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; - for (i=0; i < (int) s->img_x*target; ++i) { - t = p1[i]; p1[i] = p2[i]; p2[i] = t; - } - } - } - - if (req_comp && req_comp != target) { - out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); - if (out == NULL) return out; // stbi__convert_format frees input on failure - } - - *x = s->img_x; - *y = s->img_y; - if (comp) *comp = s->img_n; - return out; -} -#endif - -// Targa Truevision - TGA -// by Jonathan Dummer -#ifndef STBI_NO_TGA -// returns STBI_rgb or whatever, 0 on error -static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) -{ - // only RGB or RGBA (incl. 16bit) or grey allowed - if (is_rgb16) *is_rgb16 = 0; - switch(bits_per_pixel) { - case 8: return STBI_grey; - case 16: if(is_grey) return STBI_grey_alpha; - // fallthrough - case 15: if(is_rgb16) *is_rgb16 = 1; - return STBI_rgb; - case 24: // fallthrough - case 32: return bits_per_pixel/8; - default: return 0; - } -} - -static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) -{ - int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; - int sz, tga_colormap_type; - stbi__get8(s); // discard Offset - tga_colormap_type = stbi__get8(s); // colormap type - if( tga_colormap_type > 1 ) { - stbi__rewind(s); - return 0; // only RGB or indexed allowed - } - tga_image_type = stbi__get8(s); // image type - if ( tga_colormap_type == 1 ) { // colormapped (paletted) image - if (tga_image_type != 1 && tga_image_type != 9) { - stbi__rewind(s); - return 0; - } - stbi__skip(s,4); // skip index of first colormap entry and number of entries - sz = stbi__get8(s); // check bits per palette color entry - if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) { - stbi__rewind(s); - return 0; - } - stbi__skip(s,4); // skip image x and y origin - tga_colormap_bpp = sz; - } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE - if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) { - stbi__rewind(s); - return 0; // only RGB or grey allowed, +/- RLE - } - stbi__skip(s,9); // skip colormap specification and image x/y origin - tga_colormap_bpp = 0; - } - tga_w = stbi__get16le(s); - if( tga_w < 1 ) { - stbi__rewind(s); - return 0; // test width - } - tga_h = stbi__get16le(s); - if( tga_h < 1 ) { - stbi__rewind(s); - return 0; // test height - } - tga_bits_per_pixel = stbi__get8(s); // bits per pixel - stbi__get8(s); // ignore alpha bits - if (tga_colormap_bpp != 0) { - if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { - // when using a colormap, tga_bits_per_pixel is the size of the indexes - // I don't think anything but 8 or 16bit indexes makes sense - stbi__rewind(s); - return 0; - } - tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); - } else { - tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); - } - if(!tga_comp) { - stbi__rewind(s); - return 0; - } - if (x) *x = tga_w; - if (y) *y = tga_h; - if (comp) *comp = tga_comp; - return 1; // seems to have passed everything -} - -static int stbi__tga_test(stbi__context *s) -{ - int res = 0; - int sz, tga_color_type; - stbi__get8(s); // discard Offset - tga_color_type = stbi__get8(s); // color type - if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed - sz = stbi__get8(s); // image type - if ( tga_color_type == 1 ) { // colormapped (paletted) image - if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 - stbi__skip(s,4); // skip index of first colormap entry and number of entries - sz = stbi__get8(s); // check bits per palette color entry - if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; - stbi__skip(s,4); // skip image x and y origin - } else { // "normal" image w/o colormap - if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE - stbi__skip(s,9); // skip colormap specification and image x/y origin - } - if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width - if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height - sz = stbi__get8(s); // bits per pixel - if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index - if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; - - res = 1; // if we got this far, everything's good and we can return 1 instead of 0 - -errorEnd: - stbi__rewind(s); - return res; -} - -// read 16bit value and convert to 24bit RGB -static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) -{ - stbi__uint16 px = (stbi__uint16)stbi__get16le(s); - stbi__uint16 fiveBitMask = 31; - // we have 3 channels with 5bits each - int r = (px >> 10) & fiveBitMask; - int g = (px >> 5) & fiveBitMask; - int b = px & fiveBitMask; - // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later - out[0] = (stbi_uc)((r * 255)/31); - out[1] = (stbi_uc)((g * 255)/31); - out[2] = (stbi_uc)((b * 255)/31); - - // some people claim that the most significant bit might be used for alpha - // (possibly if an alpha-bit is set in the "image descriptor byte") - // but that only made 16bit test images completely translucent.. - // so let's treat all 15 and 16bit TGAs as RGB with no alpha. -} - -static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - // read in the TGA header stuff - int tga_offset = stbi__get8(s); - int tga_indexed = stbi__get8(s); - int tga_image_type = stbi__get8(s); - int tga_is_RLE = 0; - int tga_palette_start = stbi__get16le(s); - int tga_palette_len = stbi__get16le(s); - int tga_palette_bits = stbi__get8(s); - int tga_x_origin = stbi__get16le(s); - int tga_y_origin = stbi__get16le(s); - int tga_width = stbi__get16le(s); - int tga_height = stbi__get16le(s); - int tga_bits_per_pixel = stbi__get8(s); - int tga_comp, tga_rgb16=0; - int tga_inverted = stbi__get8(s); - // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) - // image data - unsigned char *tga_data; - unsigned char *tga_palette = NULL; - int i, j; - unsigned char raw_data[4] = {0}; - int RLE_count = 0; - int RLE_repeating = 0; - int read_next_pixel = 1; - STBI_NOTUSED(ri); - STBI_NOTUSED(tga_x_origin); // @TODO - STBI_NOTUSED(tga_y_origin); // @TODO - - if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - - // do a tiny bit of precessing - if ( tga_image_type >= 8 ) - { - tga_image_type -= 8; - tga_is_RLE = 1; - } - tga_inverted = 1 - ((tga_inverted >> 5) & 1); - - // If I'm paletted, then I'll use the number of bits from the palette - if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); - else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); - - if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency - return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); - - // tga info - *x = tga_width; - *y = tga_height; - if (comp) *comp = tga_comp; - - if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) - return stbi__errpuc("too large", "Corrupt TGA"); - - tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); - if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); - - // skip to the data's starting position (offset usually = 0) - stbi__skip(s, tga_offset ); - - if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) { - for (i=0; i < tga_height; ++i) { - int row = tga_inverted ? tga_height -i - 1 : i; - stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; - stbi__getn(s, tga_row, tga_width * tga_comp); - } - } else { - // do I need to load a palette? - if ( tga_indexed) - { - if (tga_palette_len == 0) { /* you have to have at least one entry! */ - STBI_FREE(tga_data); - return stbi__errpuc("bad palette", "Corrupt TGA"); - } - - // any data to skip? (offset usually = 0) - stbi__skip(s, tga_palette_start ); - // load the palette - tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); - if (!tga_palette) { - STBI_FREE(tga_data); - return stbi__errpuc("outofmem", "Out of memory"); - } - if (tga_rgb16) { - stbi_uc *pal_entry = tga_palette; - STBI_ASSERT(tga_comp == STBI_rgb); - for (i=0; i < tga_palette_len; ++i) { - stbi__tga_read_rgb16(s, pal_entry); - pal_entry += tga_comp; - } - } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { - STBI_FREE(tga_data); - STBI_FREE(tga_palette); - return stbi__errpuc("bad palette", "Corrupt TGA"); - } - } - // load the data - for (i=0; i < tga_width * tga_height; ++i) - { - // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? - if ( tga_is_RLE ) - { - if ( RLE_count == 0 ) - { - // yep, get the next byte as a RLE command - int RLE_cmd = stbi__get8(s); - RLE_count = 1 + (RLE_cmd & 127); - RLE_repeating = RLE_cmd >> 7; - read_next_pixel = 1; - } else if ( !RLE_repeating ) - { - read_next_pixel = 1; - } - } else - { - read_next_pixel = 1; - } - // OK, if I need to read a pixel, do it now - if ( read_next_pixel ) - { - // load however much data we did have - if ( tga_indexed ) - { - // read in index, then perform the lookup - int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); - if ( pal_idx >= tga_palette_len ) { - // invalid index - pal_idx = 0; - } - pal_idx *= tga_comp; - for (j = 0; j < tga_comp; ++j) { - raw_data[j] = tga_palette[pal_idx+j]; - } - } else if(tga_rgb16) { - STBI_ASSERT(tga_comp == STBI_rgb); - stbi__tga_read_rgb16(s, raw_data); - } else { - // read in the data raw - for (j = 0; j < tga_comp; ++j) { - raw_data[j] = stbi__get8(s); - } - } - // clear the reading flag for the next pixel - read_next_pixel = 0; - } // end of reading a pixel - - // copy data - for (j = 0; j < tga_comp; ++j) - tga_data[i*tga_comp+j] = raw_data[j]; - - // in case we're in RLE mode, keep counting down - --RLE_count; - } - // do I need to invert the image? - if ( tga_inverted ) - { - for (j = 0; j*2 < tga_height; ++j) - { - int index1 = j * tga_width * tga_comp; - int index2 = (tga_height - 1 - j) * tga_width * tga_comp; - for (i = tga_width * tga_comp; i > 0; --i) - { - unsigned char temp = tga_data[index1]; - tga_data[index1] = tga_data[index2]; - tga_data[index2] = temp; - ++index1; - ++index2; - } - } - } - // clear my palette, if I had one - if ( tga_palette != NULL ) - { - STBI_FREE( tga_palette ); - } - } - - // swap RGB - if the source data was RGB16, it already is in the right order - if (tga_comp >= 3 && !tga_rgb16) - { - unsigned char* tga_pixel = tga_data; - for (i=0; i < tga_width * tga_height; ++i) - { - unsigned char temp = tga_pixel[0]; - tga_pixel[0] = tga_pixel[2]; - tga_pixel[2] = temp; - tga_pixel += tga_comp; - } - } - - // convert to target component count - if (req_comp && req_comp != tga_comp) - tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); - - // the things I do to get rid of an error message, and yet keep - // Microsoft's C compilers happy... [8^( - tga_palette_start = tga_palette_len = tga_palette_bits = - tga_x_origin = tga_y_origin = 0; - STBI_NOTUSED(tga_palette_start); - // OK, done - return tga_data; -} -#endif - -// ************************************************************************************************* -// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB - -#ifndef STBI_NO_PSD -static int stbi__psd_test(stbi__context *s) -{ - int r = (stbi__get32be(s) == 0x38425053); - stbi__rewind(s); - return r; -} - -static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount) -{ - int count, nleft, len; - - count = 0; - while ((nleft = pixelCount - count) > 0) { - len = stbi__get8(s); - if (len == 128) { - // No-op. - } else if (len < 128) { - // Copy next len+1 bytes literally. - len++; - if (len > nleft) return 0; // corrupt data - count += len; - while (len) { - *p = stbi__get8(s); - p += 4; - len--; - } - } else if (len > 128) { - stbi_uc val; - // Next -len+1 bytes in the dest are replicated from next source byte. - // (Interpret len as a negative 8-bit int.) - len = 257 - len; - if (len > nleft) return 0; // corrupt data - val = stbi__get8(s); - count += len; - while (len) { - *p = val; - p += 4; - len--; - } - } - } - - return 1; -} - -static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) -{ - int pixelCount; - int channelCount, compression; - int channel, i; - int bitdepth; - int w,h; - stbi_uc *out; - STBI_NOTUSED(ri); - - // Check identifier - if (stbi__get32be(s) != 0x38425053) // "8BPS" - return stbi__errpuc("not PSD", "Corrupt PSD image"); - - // Check file type version. - if (stbi__get16be(s) != 1) - return stbi__errpuc("wrong version", "Unsupported version of PSD image"); - - // Skip 6 reserved bytes. - stbi__skip(s, 6 ); - - // Read the number of channels (R, G, B, A, etc). - channelCount = stbi__get16be(s); - if (channelCount < 0 || channelCount > 16) - return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); - - // Read the rows and columns of the image. - h = stbi__get32be(s); - w = stbi__get32be(s); - - if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - - // Make sure the depth is 8 bits. - bitdepth = stbi__get16be(s); - if (bitdepth != 8 && bitdepth != 16) - return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); - - // Make sure the color mode is RGB. - // Valid options are: - // 0: Bitmap - // 1: Grayscale - // 2: Indexed color - // 3: RGB color - // 4: CMYK color - // 7: Multichannel - // 8: Duotone - // 9: Lab color - if (stbi__get16be(s) != 3) - return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); - - // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) - stbi__skip(s,stbi__get32be(s) ); - - // Skip the image resources. (resolution, pen tool paths, etc) - stbi__skip(s, stbi__get32be(s) ); - - // Skip the reserved data. - stbi__skip(s, stbi__get32be(s) ); - - // Find out if the data is compressed. - // Known values: - // 0: no compression - // 1: RLE compressed - compression = stbi__get16be(s); - if (compression > 1) - return stbi__errpuc("bad compression", "PSD has an unknown compression format"); - - // Check size - if (!stbi__mad3sizes_valid(4, w, h, 0)) - return stbi__errpuc("too large", "Corrupt PSD"); - - // Create the destination image. - - if (!compression && bitdepth == 16 && bpc == 16) { - out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0); - ri->bits_per_channel = 16; - } else - out = (stbi_uc *) stbi__malloc(4 * w*h); - - if (!out) return stbi__errpuc("outofmem", "Out of memory"); - pixelCount = w*h; - - // Initialize the data to zero. - //memset( out, 0, pixelCount * 4 ); - - // Finally, the image data. - if (compression) { - // RLE as used by .PSD and .TIFF - // Loop until you get the number of unpacked bytes you are expecting: - // Read the next source byte into n. - // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. - // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. - // Else if n is 128, noop. - // Endloop - - // The RLE-compressed data is preceded by a 2-byte data count for each row in the data, - // which we're going to just skip. - stbi__skip(s, h * channelCount * 2 ); - - // Read the RLE data by channel. - for (channel = 0; channel < 4; channel++) { - stbi_uc *p; - - p = out+channel; - if (channel >= channelCount) { - // Fill this channel with default data. - for (i = 0; i < pixelCount; i++, p += 4) - *p = (channel == 3 ? 255 : 0); - } else { - // Read the RLE data. - if (!stbi__psd_decode_rle(s, p, pixelCount)) { - STBI_FREE(out); - return stbi__errpuc("corrupt", "bad RLE data"); - } - } - } - - } else { - // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) - // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image. - - // Read the data by channel. - for (channel = 0; channel < 4; channel++) { - if (channel >= channelCount) { - // Fill this channel with default data. - if (bitdepth == 16 && bpc == 16) { - stbi__uint16 *q = ((stbi__uint16 *) out) + channel; - stbi__uint16 val = channel == 3 ? 65535 : 0; - for (i = 0; i < pixelCount; i++, q += 4) - *q = val; - } else { - stbi_uc *p = out+channel; - stbi_uc val = channel == 3 ? 255 : 0; - for (i = 0; i < pixelCount; i++, p += 4) - *p = val; - } - } else { - if (ri->bits_per_channel == 16) { // output bpc - stbi__uint16 *q = ((stbi__uint16 *) out) + channel; - for (i = 0; i < pixelCount; i++, q += 4) - *q = (stbi__uint16) stbi__get16be(s); - } else { - stbi_uc *p = out+channel; - if (bitdepth == 16) { // input bpc - for (i = 0; i < pixelCount; i++, p += 4) - *p = (stbi_uc) (stbi__get16be(s) >> 8); - } else { - for (i = 0; i < pixelCount; i++, p += 4) - *p = stbi__get8(s); - } - } - } - } - } - - // remove weird white matte from PSD - if (channelCount >= 4) { - if (ri->bits_per_channel == 16) { - for (i=0; i < w*h; ++i) { - stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i; - if (pixel[3] != 0 && pixel[3] != 65535) { - float a = pixel[3] / 65535.0f; - float ra = 1.0f / a; - float inv_a = 65535.0f * (1 - ra); - pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a); - pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a); - pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a); - } - } - } else { - for (i=0; i < w*h; ++i) { - unsigned char *pixel = out + 4*i; - if (pixel[3] != 0 && pixel[3] != 255) { - float a = pixel[3] / 255.0f; - float ra = 1.0f / a; - float inv_a = 255.0f * (1 - ra); - pixel[0] = (unsigned char) (pixel[0]*ra + inv_a); - pixel[1] = (unsigned char) (pixel[1]*ra + inv_a); - pixel[2] = (unsigned char) (pixel[2]*ra + inv_a); - } - } - } - } - - // convert to desired output format - if (req_comp && req_comp != 4) { - if (ri->bits_per_channel == 16) - out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h); - else - out = stbi__convert_format(out, 4, req_comp, w, h); - if (out == NULL) return out; // stbi__convert_format frees input on failure - } - - if (comp) *comp = 4; - *y = h; - *x = w; - - return out; -} -#endif - -// ************************************************************************************************* -// Softimage PIC loader -// by Tom Seddon -// -// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format -// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ - -#ifndef STBI_NO_PIC -static int stbi__pic_is4(stbi__context *s,const char *str) -{ - int i; - for (i=0; i<4; ++i) - if (stbi__get8(s) != (stbi_uc)str[i]) - return 0; - - return 1; -} - -static int stbi__pic_test_core(stbi__context *s) -{ - int i; - - if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) - return 0; - - for(i=0;i<84;++i) - stbi__get8(s); - - if (!stbi__pic_is4(s,"PICT")) - return 0; - - return 1; -} - -typedef struct -{ - stbi_uc size,type,channel; -} stbi__pic_packet; - -static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest) -{ - int mask=0x80, i; - - for (i=0; i<4; ++i, mask>>=1) { - if (channel & mask) { - if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short"); - dest[i]=stbi__get8(s); - } - } - - return dest; -} - -static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src) -{ - int mask=0x80,i; - - for (i=0;i<4; ++i, mask>>=1) - if (channel&mask) - dest[i]=src[i]; -} - -static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result) -{ - int act_comp=0,num_packets=0,y,chained; - stbi__pic_packet packets[10]; - - // this will (should...) cater for even some bizarre stuff like having data - // for the same channel in multiple packets. - do { - stbi__pic_packet *packet; - - if (num_packets==sizeof(packets)/sizeof(packets[0])) - return stbi__errpuc("bad format","too many packets"); - - packet = &packets[num_packets++]; - - chained = stbi__get8(s); - packet->size = stbi__get8(s); - packet->type = stbi__get8(s); - packet->channel = stbi__get8(s); - - act_comp |= packet->channel; - - if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)"); - if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp"); - } while (chained); - - *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? - - for(y=0; ytype) { - default: - return stbi__errpuc("bad format","packet has bad compression type"); - - case 0: {//uncompressed - int x; - - for(x=0;xchannel,dest)) - return 0; - break; - } - - case 1://Pure RLE - { - int left=width, i; - - while (left>0) { - stbi_uc count,value[4]; - - count=stbi__get8(s); - if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)"); - - if (count > left) - count = (stbi_uc) left; - - if (!stbi__readval(s,packet->channel,value)) return 0; - - for(i=0; ichannel,dest,value); - left -= count; - } - } - break; - - case 2: {//Mixed RLE - int left=width; - while (left>0) { - int count = stbi__get8(s), i; - if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)"); - - if (count >= 128) { // Repeated - stbi_uc value[4]; - - if (count==128) - count = stbi__get16be(s); - else - count -= 127; - if (count > left) - return stbi__errpuc("bad file","scanline overrun"); - - if (!stbi__readval(s,packet->channel,value)) - return 0; - - for(i=0;ichannel,dest,value); - } else { // Raw - ++count; - if (count>left) return stbi__errpuc("bad file","scanline overrun"); - - for(i=0;ichannel,dest)) - return 0; - } - left-=count; - } - break; - } - } - } - } - - return result; -} - -static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri) -{ - stbi_uc *result; - int i, x,y, internal_comp; - STBI_NOTUSED(ri); - - if (!comp) comp = &internal_comp; - - for (i=0; i<92; ++i) - stbi__get8(s); - - x = stbi__get16be(s); - y = stbi__get16be(s); - - if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - - if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)"); - if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); - - stbi__get32be(s); //skip `ratio' - stbi__get16be(s); //skip `fields' - stbi__get16be(s); //skip `pad' - - // intermediate buffer is RGBA - result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0); - if (!result) return stbi__errpuc("outofmem", "Out of memory"); - memset(result, 0xff, x*y*4); - - if (!stbi__pic_load_core(s,x,y,comp, result)) { - STBI_FREE(result); - result=0; - } - *px = x; - *py = y; - if (req_comp == 0) req_comp = *comp; - result=stbi__convert_format(result,4,req_comp,x,y); - - return result; -} - -static int stbi__pic_test(stbi__context *s) -{ - int r = stbi__pic_test_core(s); - stbi__rewind(s); - return r; -} -#endif - -// ************************************************************************************************* -// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb - -#ifndef STBI_NO_GIF -typedef struct -{ - stbi__int16 prefix; - stbi_uc first; - stbi_uc suffix; -} stbi__gif_lzw; - -typedef struct -{ - int w,h; - stbi_uc *out; // output buffer (always 4 components) - stbi_uc *background; // The current "background" as far as a gif is concerned - stbi_uc *history; - int flags, bgindex, ratio, transparent, eflags; - stbi_uc pal[256][4]; - stbi_uc lpal[256][4]; - stbi__gif_lzw codes[8192]; - stbi_uc *color_table; - int parse, step; - int lflags; - int start_x, start_y; - int max_x, max_y; - int cur_x, cur_y; - int line_size; - int delay; -} stbi__gif; - -static int stbi__gif_test_raw(stbi__context *s) -{ - int sz; - if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; - sz = stbi__get8(s); - if (sz != '9' && sz != '7') return 0; - if (stbi__get8(s) != 'a') return 0; - return 1; -} - -static int stbi__gif_test(stbi__context *s) -{ - int r = stbi__gif_test_raw(s); - stbi__rewind(s); - return r; -} - -static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp) -{ - int i; - for (i=0; i < num_entries; ++i) { - pal[i][2] = stbi__get8(s); - pal[i][1] = stbi__get8(s); - pal[i][0] = stbi__get8(s); - pal[i][3] = transp == i ? 0 : 255; - } -} - -static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info) -{ - stbi_uc version; - if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') - return stbi__err("not GIF", "Corrupt GIF"); - - version = stbi__get8(s); - if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); - if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); - - stbi__g_failure_reason = ""; - g->w = stbi__get16le(s); - g->h = stbi__get16le(s); - g->flags = stbi__get8(s); - g->bgindex = stbi__get8(s); - g->ratio = stbi__get8(s); - g->transparent = -1; - - if (g->w > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); - if (g->h > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); - - if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments - - if (is_info) return 1; - - if (g->flags & 0x80) - stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1); - - return 1; -} - -static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) -{ - stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif)); - if (!g) return stbi__err("outofmem", "Out of memory"); - if (!stbi__gif_header(s, g, comp, 1)) { - STBI_FREE(g); - stbi__rewind( s ); - return 0; - } - if (x) *x = g->w; - if (y) *y = g->h; - STBI_FREE(g); - return 1; -} - -static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) -{ - stbi_uc *p, *c; - int idx; - - // recurse to decode the prefixes, since the linked-list is backwards, - // and working backwards through an interleaved image would be nasty - if (g->codes[code].prefix >= 0) - stbi__out_gif_code(g, g->codes[code].prefix); - - if (g->cur_y >= g->max_y) return; - - idx = g->cur_x + g->cur_y; - p = &g->out[idx]; - g->history[idx / 4] = 1; - - c = &g->color_table[g->codes[code].suffix * 4]; - if (c[3] > 128) { // don't render transparent pixels; - p[0] = c[2]; - p[1] = c[1]; - p[2] = c[0]; - p[3] = c[3]; - } - g->cur_x += 4; - - if (g->cur_x >= g->max_x) { - g->cur_x = g->start_x; - g->cur_y += g->step; - - while (g->cur_y >= g->max_y && g->parse > 0) { - g->step = (1 << g->parse) * g->line_size; - g->cur_y = g->start_y + (g->step >> 1); - --g->parse; - } - } -} - -static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) -{ - stbi_uc lzw_cs; - stbi__int32 len, init_code; - stbi__uint32 first; - stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; - stbi__gif_lzw *p; - - lzw_cs = stbi__get8(s); - if (lzw_cs > 12) return NULL; - clear = 1 << lzw_cs; - first = 1; - codesize = lzw_cs + 1; - codemask = (1 << codesize) - 1; - bits = 0; - valid_bits = 0; - for (init_code = 0; init_code < clear; init_code++) { - g->codes[init_code].prefix = -1; - g->codes[init_code].first = (stbi_uc) init_code; - g->codes[init_code].suffix = (stbi_uc) init_code; - } - - // support no starting clear code - avail = clear+2; - oldcode = -1; - - len = 0; - for(;;) { - if (valid_bits < codesize) { - if (len == 0) { - len = stbi__get8(s); // start new block - if (len == 0) - return g->out; - } - --len; - bits |= (stbi__int32) stbi__get8(s) << valid_bits; - valid_bits += 8; - } else { - stbi__int32 code = bits & codemask; - bits >>= codesize; - valid_bits -= codesize; - // @OPTIMIZE: is there some way we can accelerate the non-clear path? - if (code == clear) { // clear code - codesize = lzw_cs + 1; - codemask = (1 << codesize) - 1; - avail = clear + 2; - oldcode = -1; - first = 0; - } else if (code == clear + 1) { // end of stream code - stbi__skip(s, len); - while ((len = stbi__get8(s)) > 0) - stbi__skip(s,len); - return g->out; - } else if (code <= avail) { - if (first) { - return stbi__errpuc("no clear code", "Corrupt GIF"); - } - - if (oldcode >= 0) { - p = &g->codes[avail++]; - if (avail > 8192) { - return stbi__errpuc("too many codes", "Corrupt GIF"); - } - - p->prefix = (stbi__int16) oldcode; - p->first = g->codes[oldcode].first; - p->suffix = (code == avail) ? p->first : g->codes[code].first; - } else if (code == avail) - return stbi__errpuc("illegal code in raster", "Corrupt GIF"); - - stbi__out_gif_code(g, (stbi__uint16) code); - - if ((avail & codemask) == 0 && avail <= 0x0FFF) { - codesize++; - codemask = (1 << codesize) - 1; - } - - oldcode = code; - } else { - return stbi__errpuc("illegal code in raster", "Corrupt GIF"); - } - } - } -} - -// this function is designed to support animated gifs, although stb_image doesn't support it -// two back is the image from two frames ago, used for a very specific disposal format -static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back) -{ - int dispose; - int first_frame; - int pi; - int pcount; - STBI_NOTUSED(req_comp); - - // on first frame, any non-written pixels get the background colour (non-transparent) - first_frame = 0; - if (g->out == 0) { - if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header - if (!stbi__mad3sizes_valid(4, g->w, g->h, 0)) - return stbi__errpuc("too large", "GIF image is too large"); - pcount = g->w * g->h; - g->out = (stbi_uc *) stbi__malloc(4 * pcount); - g->background = (stbi_uc *) stbi__malloc(4 * pcount); - g->history = (stbi_uc *) stbi__malloc(pcount); - if (!g->out || !g->background || !g->history) - return stbi__errpuc("outofmem", "Out of memory"); - - // image is treated as "transparent" at the start - ie, nothing overwrites the current background; - // background colour is only used for pixels that are not rendered first frame, after that "background" - // color refers to the color that was there the previous frame. - memset(g->out, 0x00, 4 * pcount); - memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent) - memset(g->history, 0x00, pcount); // pixels that were affected previous frame - first_frame = 1; - } else { - // second frame - how do we dispose of the previous one? - dispose = (g->eflags & 0x1C) >> 2; - pcount = g->w * g->h; - - if ((dispose == 3) && (two_back == 0)) { - dispose = 2; // if I don't have an image to revert back to, default to the old background - } - - if (dispose == 3) { // use previous graphic - for (pi = 0; pi < pcount; ++pi) { - if (g->history[pi]) { - memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 ); - } - } - } else if (dispose == 2) { - // restore what was changed last frame to background before that frame; - for (pi = 0; pi < pcount; ++pi) { - if (g->history[pi]) { - memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 ); - } - } - } else { - // This is a non-disposal case eithe way, so just - // leave the pixels as is, and they will become the new background - // 1: do not dispose - // 0: not specified. - } - - // background is what out is after the undoing of the previou frame; - memcpy( g->background, g->out, 4 * g->w * g->h ); - } - - // clear my history; - memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame - - for (;;) { - int tag = stbi__get8(s); - switch (tag) { - case 0x2C: /* Image Descriptor */ - { - stbi__int32 x, y, w, h; - stbi_uc *o; - - x = stbi__get16le(s); - y = stbi__get16le(s); - w = stbi__get16le(s); - h = stbi__get16le(s); - if (((x + w) > (g->w)) || ((y + h) > (g->h))) - return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); - - g->line_size = g->w * 4; - g->start_x = x * 4; - g->start_y = y * g->line_size; - g->max_x = g->start_x + w * 4; - g->max_y = g->start_y + h * g->line_size; - g->cur_x = g->start_x; - g->cur_y = g->start_y; - - // if the width of the specified rectangle is 0, that means - // we may not see *any* pixels or the image is malformed; - // to make sure this is caught, move the current y down to - // max_y (which is what out_gif_code checks). - if (w == 0) - g->cur_y = g->max_y; - - g->lflags = stbi__get8(s); - - if (g->lflags & 0x40) { - g->step = 8 * g->line_size; // first interlaced spacing - g->parse = 3; - } else { - g->step = g->line_size; - g->parse = 0; - } - - if (g->lflags & 0x80) { - stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); - g->color_table = (stbi_uc *) g->lpal; - } else if (g->flags & 0x80) { - g->color_table = (stbi_uc *) g->pal; - } else - return stbi__errpuc("missing color table", "Corrupt GIF"); - - o = stbi__process_gif_raster(s, g); - if (!o) return NULL; - - // if this was the first frame, - pcount = g->w * g->h; - if (first_frame && (g->bgindex > 0)) { - // if first frame, any pixel not drawn to gets the background color - for (pi = 0; pi < pcount; ++pi) { - if (g->history[pi] == 0) { - g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be; - memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 ); - } - } - } - - return o; - } - - case 0x21: // Comment Extension. - { - int len; - int ext = stbi__get8(s); - if (ext == 0xF9) { // Graphic Control Extension. - len = stbi__get8(s); - if (len == 4) { - g->eflags = stbi__get8(s); - g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths. - - // unset old transparent - if (g->transparent >= 0) { - g->pal[g->transparent][3] = 255; - } - if (g->eflags & 0x01) { - g->transparent = stbi__get8(s); - if (g->transparent >= 0) { - g->pal[g->transparent][3] = 0; - } - } else { - // don't need transparent - stbi__skip(s, 1); - g->transparent = -1; - } - } else { - stbi__skip(s, len); - break; - } - } - while ((len = stbi__get8(s)) != 0) { - stbi__skip(s, len); - } - break; - } - - case 0x3B: // gif stream termination code - return (stbi_uc *) s; // using '1' causes warning on some compilers - - default: - return stbi__errpuc("unknown code", "Corrupt GIF"); - } - } -} - -static void *stbi__load_gif_main_outofmem(stbi__gif *g, stbi_uc *out, int **delays) -{ - STBI_FREE(g->out); - STBI_FREE(g->history); - STBI_FREE(g->background); - - if (out) STBI_FREE(out); - if (delays && *delays) STBI_FREE(*delays); - return stbi__errpuc("outofmem", "Out of memory"); -} - -static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp) -{ - if (stbi__gif_test(s)) { - int layers = 0; - stbi_uc *u = 0; - stbi_uc *out = 0; - stbi_uc *two_back = 0; - stbi__gif g; - int stride; - int out_size = 0; - int delays_size = 0; - - STBI_NOTUSED(out_size); - STBI_NOTUSED(delays_size); - - memset(&g, 0, sizeof(g)); - if (delays) { - *delays = 0; - } - - do { - u = stbi__gif_load_next(s, &g, comp, req_comp, two_back); - if (u == (stbi_uc *) s) u = 0; // end of animated gif marker - - if (u) { - *x = g.w; - *y = g.h; - ++layers; - stride = g.w * g.h * 4; - - if (out) { - void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride ); - if (!tmp) - return stbi__load_gif_main_outofmem(&g, out, delays); - else { - out = (stbi_uc*) tmp; - out_size = layers * stride; - } - - if (delays) { - int *new_delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers ); - if (!new_delays) - return stbi__load_gif_main_outofmem(&g, out, delays); - *delays = new_delays; - delays_size = layers * sizeof(int); - } - } else { - out = (stbi_uc*)stbi__malloc( layers * stride ); - if (!out) - return stbi__load_gif_main_outofmem(&g, out, delays); - out_size = layers * stride; - if (delays) { - *delays = (int*) stbi__malloc( layers * sizeof(int) ); - if (!*delays) - return stbi__load_gif_main_outofmem(&g, out, delays); - delays_size = layers * sizeof(int); - } - } - memcpy( out + ((layers - 1) * stride), u, stride ); - if (layers >= 2) { - two_back = out - 2 * stride; - } - - if (delays) { - (*delays)[layers - 1U] = g.delay; - } - } - } while (u != 0); - - // free temp buffer; - STBI_FREE(g.out); - STBI_FREE(g.history); - STBI_FREE(g.background); - - // do the final conversion after loading everything; - if (req_comp && req_comp != 4) - out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h); - - *z = layers; - return out; - } else { - return stbi__errpuc("not GIF", "Image was not as a gif type."); - } -} - -static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - stbi_uc *u = 0; - stbi__gif g; - memset(&g, 0, sizeof(g)); - STBI_NOTUSED(ri); - - u = stbi__gif_load_next(s, &g, comp, req_comp, 0); - if (u == (stbi_uc *) s) u = 0; // end of animated gif marker - if (u) { - *x = g.w; - *y = g.h; - - // moved conversion to after successful load so that the same - // can be done for multiple frames. - if (req_comp && req_comp != 4) - u = stbi__convert_format(u, 4, req_comp, g.w, g.h); - } else if (g.out) { - // if there was an error and we allocated an image buffer, free it! - STBI_FREE(g.out); - } - - // free buffers needed for multiple frame loading; - STBI_FREE(g.history); - STBI_FREE(g.background); - - return u; -} - -static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) -{ - return stbi__gif_info_raw(s,x,y,comp); -} -#endif - -// ************************************************************************************************* -// Radiance RGBE HDR loader -// originally by Nicolas Schulz -#ifndef STBI_NO_HDR -static int stbi__hdr_test_core(stbi__context *s, const char *signature) -{ - int i; - for (i=0; signature[i]; ++i) - if (stbi__get8(s) != signature[i]) - return 0; - stbi__rewind(s); - return 1; -} - -static int stbi__hdr_test(stbi__context* s) -{ - int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); - stbi__rewind(s); - if(!r) { - r = stbi__hdr_test_core(s, "#?RGBE\n"); - stbi__rewind(s); - } - return r; -} - -#define STBI__HDR_BUFLEN 1024 -static char *stbi__hdr_gettoken(stbi__context *z, char *buffer) -{ - int len=0; - char c = '\0'; - - c = (char) stbi__get8(z); - - while (!stbi__at_eof(z) && c != '\n') { - buffer[len++] = c; - if (len == STBI__HDR_BUFLEN-1) { - // flush to end of line - while (!stbi__at_eof(z) && stbi__get8(z) != '\n') - ; - break; - } - c = (char) stbi__get8(z); - } - - buffer[len] = 0; - return buffer; -} - -static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) -{ - if ( input[3] != 0 ) { - float f1; - // Exponent - f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8)); - if (req_comp <= 2) - output[0] = (input[0] + input[1] + input[2]) * f1 / 3; - else { - output[0] = input[0] * f1; - output[1] = input[1] * f1; - output[2] = input[2] * f1; - } - if (req_comp == 2) output[1] = 1; - if (req_comp == 4) output[3] = 1; - } else { - switch (req_comp) { - case 4: output[3] = 1; /* fallthrough */ - case 3: output[0] = output[1] = output[2] = 0; - break; - case 2: output[1] = 1; /* fallthrough */ - case 1: output[0] = 0; - break; - } - } -} - -static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - char buffer[STBI__HDR_BUFLEN]; - char *token; - int valid = 0; - int width, height; - stbi_uc *scanline; - float *hdr_data; - int len; - unsigned char count, value; - int i, j, k, c1,c2, z; - const char *headerToken; - STBI_NOTUSED(ri); - - // Check identifier - headerToken = stbi__hdr_gettoken(s,buffer); - if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) - return stbi__errpf("not HDR", "Corrupt HDR image"); - - // Parse header - for(;;) { - token = stbi__hdr_gettoken(s,buffer); - if (token[0] == 0) break; - if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; - } - - if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); - - // Parse width and height - // can't use sscanf() if we're not using stdio! - token = stbi__hdr_gettoken(s,buffer); - if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); - token += 3; - height = (int) strtol(token, &token, 10); - while (*token == ' ') ++token; - if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); - token += 3; - width = (int) strtol(token, NULL, 10); - - if (height > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); - if (width > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); - - *x = width; - *y = height; - - if (comp) *comp = 3; - if (req_comp == 0) req_comp = 3; - - if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) - return stbi__errpf("too large", "HDR image is too large"); - - // Read data - hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); - if (!hdr_data) - return stbi__errpf("outofmem", "Out of memory"); - - // Load image data - // image data is stored as some number of sca - if ( width < 8 || width >= 32768) { - // Read flat data - for (j=0; j < height; ++j) { - for (i=0; i < width; ++i) { - stbi_uc rgbe[4]; - main_decode_loop: - stbi__getn(s, rgbe, 4); - stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); - } - } - } else { - // Read RLE-encoded data - scanline = NULL; - - for (j = 0; j < height; ++j) { - c1 = stbi__get8(s); - c2 = stbi__get8(s); - len = stbi__get8(s); - if (c1 != 2 || c2 != 2 || (len & 0x80)) { - // not run-length encoded, so we have to actually use THIS data as a decoded - // pixel (note this can't be a valid pixel--one of RGB must be >= 128) - stbi_uc rgbe[4]; - rgbe[0] = (stbi_uc) c1; - rgbe[1] = (stbi_uc) c2; - rgbe[2] = (stbi_uc) len; - rgbe[3] = (stbi_uc) stbi__get8(s); - stbi__hdr_convert(hdr_data, rgbe, req_comp); - i = 1; - j = 0; - STBI_FREE(scanline); - goto main_decode_loop; // yes, this makes no sense - } - len <<= 8; - len |= stbi__get8(s); - if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } - if (scanline == NULL) { - scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0); - if (!scanline) { - STBI_FREE(hdr_data); - return stbi__errpf("outofmem", "Out of memory"); - } - } - - for (k = 0; k < 4; ++k) { - int nleft; - i = 0; - while ((nleft = width - i) > 0) { - count = stbi__get8(s); - if (count > 128) { - // Run - value = stbi__get8(s); - count -= 128; - if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } - for (z = 0; z < count; ++z) - scanline[i++ * 4 + k] = value; - } else { - // Dump - if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } - for (z = 0; z < count; ++z) - scanline[i++ * 4 + k] = stbi__get8(s); - } - } - } - for (i=0; i < width; ++i) - stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); - } - if (scanline) - STBI_FREE(scanline); - } - - return hdr_data; -} - -static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) -{ - char buffer[STBI__HDR_BUFLEN]; - char *token; - int valid = 0; - int dummy; - - if (!x) x = &dummy; - if (!y) y = &dummy; - if (!comp) comp = &dummy; - - if (stbi__hdr_test(s) == 0) { - stbi__rewind( s ); - return 0; - } - - for(;;) { - token = stbi__hdr_gettoken(s,buffer); - if (token[0] == 0) break; - if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; - } - - if (!valid) { - stbi__rewind( s ); - return 0; - } - token = stbi__hdr_gettoken(s,buffer); - if (strncmp(token, "-Y ", 3)) { - stbi__rewind( s ); - return 0; - } - token += 3; - *y = (int) strtol(token, &token, 10); - while (*token == ' ') ++token; - if (strncmp(token, "+X ", 3)) { - stbi__rewind( s ); - return 0; - } - token += 3; - *x = (int) strtol(token, NULL, 10); - *comp = 3; - return 1; -} -#endif // STBI_NO_HDR - -#ifndef STBI_NO_BMP -static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) -{ - void *p; - stbi__bmp_data info; - - info.all_a = 255; - p = stbi__bmp_parse_header(s, &info); - if (p == NULL) { - stbi__rewind( s ); - return 0; - } - if (x) *x = s->img_x; - if (y) *y = s->img_y; - if (comp) { - if (info.bpp == 24 && info.ma == 0xff000000) - *comp = 3; - else - *comp = info.ma ? 4 : 3; - } - return 1; -} -#endif - -#ifndef STBI_NO_PSD -static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) -{ - int channelCount, dummy, depth; - if (!x) x = &dummy; - if (!y) y = &dummy; - if (!comp) comp = &dummy; - if (stbi__get32be(s) != 0x38425053) { - stbi__rewind( s ); - return 0; - } - if (stbi__get16be(s) != 1) { - stbi__rewind( s ); - return 0; - } - stbi__skip(s, 6); - channelCount = stbi__get16be(s); - if (channelCount < 0 || channelCount > 16) { - stbi__rewind( s ); - return 0; - } - *y = stbi__get32be(s); - *x = stbi__get32be(s); - depth = stbi__get16be(s); - if (depth != 8 && depth != 16) { - stbi__rewind( s ); - return 0; - } - if (stbi__get16be(s) != 3) { - stbi__rewind( s ); - return 0; - } - *comp = 4; - return 1; -} - -static int stbi__psd_is16(stbi__context *s) -{ - int channelCount, depth; - if (stbi__get32be(s) != 0x38425053) { - stbi__rewind( s ); - return 0; - } - if (stbi__get16be(s) != 1) { - stbi__rewind( s ); - return 0; - } - stbi__skip(s, 6); - channelCount = stbi__get16be(s); - if (channelCount < 0 || channelCount > 16) { - stbi__rewind( s ); - return 0; - } - STBI_NOTUSED(stbi__get32be(s)); - STBI_NOTUSED(stbi__get32be(s)); - depth = stbi__get16be(s); - if (depth != 16) { - stbi__rewind( s ); - return 0; - } - return 1; -} -#endif - -#ifndef STBI_NO_PIC -static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) -{ - int act_comp=0,num_packets=0,chained,dummy; - stbi__pic_packet packets[10]; - - if (!x) x = &dummy; - if (!y) y = &dummy; - if (!comp) comp = &dummy; - - if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) { - stbi__rewind(s); - return 0; - } - - stbi__skip(s, 88); - - *x = stbi__get16be(s); - *y = stbi__get16be(s); - if (stbi__at_eof(s)) { - stbi__rewind( s); - return 0; - } - if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) { - stbi__rewind( s ); - return 0; - } - - stbi__skip(s, 8); - - do { - stbi__pic_packet *packet; - - if (num_packets==sizeof(packets)/sizeof(packets[0])) - return 0; - - packet = &packets[num_packets++]; - chained = stbi__get8(s); - packet->size = stbi__get8(s); - packet->type = stbi__get8(s); - packet->channel = stbi__get8(s); - act_comp |= packet->channel; - - if (stbi__at_eof(s)) { - stbi__rewind( s ); - return 0; - } - if (packet->size != 8) { - stbi__rewind( s ); - return 0; - } - } while (chained); - - *comp = (act_comp & 0x10 ? 4 : 3); - - return 1; -} -#endif - -// ************************************************************************************************* -// Portable Gray Map and Portable Pixel Map loader -// by Ken Miller -// -// PGM: http://netpbm.sourceforge.net/doc/pgm.html -// PPM: http://netpbm.sourceforge.net/doc/ppm.html -// -// Known limitations: -// Does not support comments in the header section -// Does not support ASCII image data (formats P2 and P3) - -#ifndef STBI_NO_PNM - -static int stbi__pnm_test(stbi__context *s) -{ - char p, t; - p = (char) stbi__get8(s); - t = (char) stbi__get8(s); - if (p != 'P' || (t != '5' && t != '6')) { - stbi__rewind( s ); - return 0; - } - return 1; -} - -static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) -{ - stbi_uc *out; - STBI_NOTUSED(ri); - - ri->bits_per_channel = stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n); - if (ri->bits_per_channel == 0) - return 0; - - if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); - - *x = s->img_x; - *y = s->img_y; - if (comp) *comp = s->img_n; - - if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0)) - return stbi__errpuc("too large", "PNM too large"); - - out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0); - if (!out) return stbi__errpuc("outofmem", "Out of memory"); - if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) { - STBI_FREE(out); - return stbi__errpuc("bad PNM", "PNM file truncated"); - } - - if (req_comp && req_comp != s->img_n) { - if (ri->bits_per_channel == 16) { - out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, s->img_n, req_comp, s->img_x, s->img_y); - } else { - out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); - } - if (out == NULL) return out; // stbi__convert_format frees input on failure - } - return out; -} - -static int stbi__pnm_isspace(char c) -{ - return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; -} - -static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) -{ - for (;;) { - while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) - *c = (char) stbi__get8(s); - - if (stbi__at_eof(s) || *c != '#') - break; - - while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' ) - *c = (char) stbi__get8(s); - } -} - -static int stbi__pnm_isdigit(char c) -{ - return c >= '0' && c <= '9'; -} - -static int stbi__pnm_getinteger(stbi__context *s, char *c) -{ - int value = 0; - - while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { - value = value*10 + (*c - '0'); - *c = (char) stbi__get8(s); - if((value > 214748364) || (value == 214748364 && *c > '7')) - return stbi__err("integer parse overflow", "Parsing an integer in the PPM header overflowed a 32-bit int"); - } - - return value; -} - -static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) -{ - int maxv, dummy; - char c, p, t; - - if (!x) x = &dummy; - if (!y) y = &dummy; - if (!comp) comp = &dummy; - - stbi__rewind(s); - - // Get identifier - p = (char) stbi__get8(s); - t = (char) stbi__get8(s); - if (p != 'P' || (t != '5' && t != '6')) { - stbi__rewind(s); - return 0; - } - - *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm - - c = (char) stbi__get8(s); - stbi__pnm_skip_whitespace(s, &c); - - *x = stbi__pnm_getinteger(s, &c); // read width - if(*x == 0) - return stbi__err("invalid width", "PPM image header had zero or overflowing width"); - stbi__pnm_skip_whitespace(s, &c); - - *y = stbi__pnm_getinteger(s, &c); // read height - if (*y == 0) - return stbi__err("invalid width", "PPM image header had zero or overflowing width"); - stbi__pnm_skip_whitespace(s, &c); - - maxv = stbi__pnm_getinteger(s, &c); // read max value - if (maxv > 65535) - return stbi__err("max value > 65535", "PPM image supports only 8-bit and 16-bit images"); - else if (maxv > 255) - return 16; - else - return 8; -} - -static int stbi__pnm_is16(stbi__context *s) -{ - if (stbi__pnm_info(s, NULL, NULL, NULL) == 16) - return 1; - return 0; -} -#endif - -static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) -{ - #ifndef STBI_NO_JPEG - if (stbi__jpeg_info(s, x, y, comp)) return 1; - #endif - - #ifndef STBI_NO_PNG - if (stbi__png_info(s, x, y, comp)) return 1; - #endif - - #ifndef STBI_NO_GIF - if (stbi__gif_info(s, x, y, comp)) return 1; - #endif - - #ifndef STBI_NO_BMP - if (stbi__bmp_info(s, x, y, comp)) return 1; - #endif - - #ifndef STBI_NO_PSD - if (stbi__psd_info(s, x, y, comp)) return 1; - #endif - - #ifndef STBI_NO_PIC - if (stbi__pic_info(s, x, y, comp)) return 1; - #endif - - #ifndef STBI_NO_PNM - if (stbi__pnm_info(s, x, y, comp)) return 1; - #endif - - #ifndef STBI_NO_HDR - if (stbi__hdr_info(s, x, y, comp)) return 1; - #endif - - // test tga last because it's a crappy test! - #ifndef STBI_NO_TGA - if (stbi__tga_info(s, x, y, comp)) - return 1; - #endif - return stbi__err("unknown image type", "Image not of any known type, or corrupt"); -} - -static int stbi__is_16_main(stbi__context *s) -{ - #ifndef STBI_NO_PNG - if (stbi__png_is16(s)) return 1; - #endif - - #ifndef STBI_NO_PSD - if (stbi__psd_is16(s)) return 1; - #endif - - #ifndef STBI_NO_PNM - if (stbi__pnm_is16(s)) return 1; - #endif - return 0; -} - -#ifndef STBI_NO_STDIO -STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) -{ - FILE *f = stbi__fopen(filename, "rb"); - int result; - if (!f) return stbi__err("can't fopen", "Unable to open file"); - result = stbi_info_from_file(f, x, y, comp); - fclose(f); - return result; -} - -STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) -{ - int r; - stbi__context s; - long pos = ftell(f); - stbi__start_file(&s, f); - r = stbi__info_main(&s,x,y,comp); - fseek(f,pos,SEEK_SET); - return r; -} - -STBIDEF int stbi_is_16_bit(char const *filename) -{ - FILE *f = stbi__fopen(filename, "rb"); - int result; - if (!f) return stbi__err("can't fopen", "Unable to open file"); - result = stbi_is_16_bit_from_file(f); - fclose(f); - return result; -} - -STBIDEF int stbi_is_16_bit_from_file(FILE *f) -{ - int r; - stbi__context s; - long pos = ftell(f); - stbi__start_file(&s, f); - r = stbi__is_16_main(&s); - fseek(f,pos,SEEK_SET); - return r; -} -#endif // !STBI_NO_STDIO - -STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) -{ - stbi__context s; - stbi__start_mem(&s,buffer,len); - return stbi__info_main(&s,x,y,comp); -} - -STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) -{ - stbi__context s; - stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); - return stbi__info_main(&s,x,y,comp); -} - -STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len) -{ - stbi__context s; - stbi__start_mem(&s,buffer,len); - return stbi__is_16_main(&s); -} - -STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user) -{ - stbi__context s; - stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); - return stbi__is_16_main(&s); -} - -#endif // STB_IMAGE_IMPLEMENTATION - -/* - revision history: - 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs - 2.19 (2018-02-11) fix warning - 2.18 (2018-01-30) fix warnings - 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug - 1-bit BMP - *_is_16_bit api - avoid warnings - 2.16 (2017-07-23) all functions have 16-bit variants; - STBI_NO_STDIO works again; - compilation fixes; - fix rounding in unpremultiply; - optimize vertical flip; - disable raw_len validation; - documentation fixes - 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode; - warning fixes; disable run-time SSE detection on gcc; - uniform handling of optional "return" values; - thread-safe initialization of zlib tables - 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs - 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now - 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes - 2.11 (2016-04-02) allocate large structures on the stack - remove white matting for transparent PSD - fix reported channel count for PNG & BMP - re-enable SSE2 in non-gcc 64-bit - support RGB-formatted JPEG - read 16-bit PNGs (only as 8-bit) - 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED - 2.09 (2016-01-16) allow comments in PNM files - 16-bit-per-pixel TGA (not bit-per-component) - info() for TGA could break due to .hdr handling - info() for BMP to shares code instead of sloppy parse - can use STBI_REALLOC_SIZED if allocator doesn't support realloc - code cleanup - 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA - 2.07 (2015-09-13) fix compiler warnings - partial animated GIF support - limited 16-bpc PSD support - #ifdef unused functions - bug with < 92 byte PIC,PNM,HDR,TGA - 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value - 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning - 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit - 2.03 (2015-04-12) extra corruption checking (mmozeiko) - stbi_set_flip_vertically_on_load (nguillemot) - fix NEON support; fix mingw support - 2.02 (2015-01-19) fix incorrect assert, fix warning - 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2 - 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG - 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) - progressive JPEG (stb) - PGM/PPM support (Ken Miller) - STBI_MALLOC,STBI_REALLOC,STBI_FREE - GIF bugfix -- seemingly never worked - STBI_NO_*, STBI_ONLY_* - 1.48 (2014-12-14) fix incorrectly-named assert() - 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb) - optimize PNG (ryg) - fix bug in interlaced PNG with user-specified channel count (stb) - 1.46 (2014-08-26) - fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG - 1.45 (2014-08-16) - fix MSVC-ARM internal compiler error by wrapping malloc - 1.44 (2014-08-07) - various warning fixes from Ronny Chevalier - 1.43 (2014-07-15) - fix MSVC-only compiler problem in code changed in 1.42 - 1.42 (2014-07-09) - don't define _CRT_SECURE_NO_WARNINGS (affects user code) - fixes to stbi__cleanup_jpeg path - added STBI_ASSERT to avoid requiring assert.h - 1.41 (2014-06-25) - fix search&replace from 1.36 that messed up comments/error messages - 1.40 (2014-06-22) - fix gcc struct-initialization warning - 1.39 (2014-06-15) - fix to TGA optimization when req_comp != number of components in TGA; - fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) - add support for BMP version 5 (more ignored fields) - 1.38 (2014-06-06) - suppress MSVC warnings on integer casts truncating values - fix accidental rename of 'skip' field of I/O - 1.37 (2014-06-04) - remove duplicate typedef - 1.36 (2014-06-03) - convert to header file single-file library - if de-iphone isn't set, load iphone images color-swapped instead of returning NULL - 1.35 (2014-05-27) - various warnings - fix broken STBI_SIMD path - fix bug where stbi_load_from_file no longer left file pointer in correct place - fix broken non-easy path for 32-bit BMP (possibly never used) - TGA optimization by Arseny Kapoulkine - 1.34 (unknown) - use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case - 1.33 (2011-07-14) - make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements - 1.32 (2011-07-13) - support for "info" function for all supported filetypes (SpartanJ) - 1.31 (2011-06-20) - a few more leak fixes, bug in PNG handling (SpartanJ) - 1.30 (2011-06-11) - added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) - removed deprecated format-specific test/load functions - removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway - error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) - fix inefficiency in decoding 32-bit BMP (David Woo) - 1.29 (2010-08-16) - various warning fixes from Aurelien Pocheville - 1.28 (2010-08-01) - fix bug in GIF palette transparency (SpartanJ) - 1.27 (2010-08-01) - cast-to-stbi_uc to fix warnings - 1.26 (2010-07-24) - fix bug in file buffering for PNG reported by SpartanJ - 1.25 (2010-07-17) - refix trans_data warning (Won Chun) - 1.24 (2010-07-12) - perf improvements reading from files on platforms with lock-heavy fgetc() - minor perf improvements for jpeg - deprecated type-specific functions so we'll get feedback if they're needed - attempt to fix trans_data warning (Won Chun) - 1.23 fixed bug in iPhone support - 1.22 (2010-07-10) - removed image *writing* support - stbi_info support from Jetro Lauha - GIF support from Jean-Marc Lienher - iPhone PNG-extensions from James Brown - warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) - 1.21 fix use of 'stbi_uc' in header (reported by jon blow) - 1.20 added support for Softimage PIC, by Tom Seddon - 1.19 bug in interlaced PNG corruption check (found by ryg) - 1.18 (2008-08-02) - fix a threading bug (local mutable static) - 1.17 support interlaced PNG - 1.16 major bugfix - stbi__convert_format converted one too many pixels - 1.15 initialize some fields for thread safety - 1.14 fix threadsafe conversion bug - header-file-only version (#define STBI_HEADER_FILE_ONLY before including) - 1.13 threadsafe - 1.12 const qualifiers in the API - 1.11 Support installable IDCT, colorspace conversion routines - 1.10 Fixes for 64-bit (don't use "unsigned long") - optimized upsampling by Fabian "ryg" Giesen - 1.09 Fix format-conversion for PSD code (bad global variables!) - 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz - 1.07 attempt to fix C++ warning/errors again - 1.06 attempt to fix C++ warning/errors again - 1.05 fix TGA loading to return correct *comp and use good luminance calc - 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free - 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR - 1.02 support for (subset of) HDR files, float interface for preferred access to them - 1.01 fix bug: possible bug in handling right-side up bmps... not sure - fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all - 1.00 interface to zlib that skips zlib header - 0.99 correct handling of alpha in palette - 0.98 TGA loader by lonesock; dynamically add loaders (untested) - 0.97 jpeg errors on too large a file; also catch another malloc failure - 0.96 fix detection of invalid v value - particleman@mollyrocket forum - 0.95 during header scan, seek to markers in case of padding - 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same - 0.93 handle jpegtran output; verbose errors - 0.92 read 4,8,16,24,32-bit BMP files of several formats - 0.91 output 24-bit Windows 3.0 BMP files - 0.90 fix a few more warnings; bump version number to approach 1.0 - 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd - 0.60 fix compiling as c++ - 0.59 fix warnings: merge Dave Moore's -Wall fixes - 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian - 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available - 0.56 fix bug: zlib uncompressed mode len vs. nlen - 0.55 fix bug: restart_interval not initialized to 0 - 0.54 allow NULL for 'int *comp' - 0.53 fix bug in png 3->4; speedup png decoding - 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments - 0.51 obey req_comp requests, 1-component jpegs return as 1-component, - on 'test' only check type, not whether we support this variant - 0.50 (2006-11-19) - first released version -*/ - - -/* ------------------------------------------------------------------------------- -This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------- -ALTERNATIVE A - MIT License -Copyright (c) 2017 Sean Barrett -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. ------------------------------------------------------------------------------- -ALTERNATIVE B - Public Domain (www.unlicense.org) -This is free and unencumbered software released into the public domain. -Anyone is free to copy, modify, publish, use, compile, sell, or distribute this -software, either in source code form or as a compiled binary, for any purpose, -commercial or non-commercial, and by any means. -In jurisdictions that recognize copyright laws, the author or authors of this -software dedicate any and all copyright interest in the software to the public -domain. We make this dedication for the benefit of the public at large and to -the detriment of our heirs and successors. We intend this dedication to be an -overt act of relinquishment in perpetuity of all present and future rights to -this software under copyright law. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- -*/ diff --git a/PlugIns/STBICodec/src/stbi/stb_image_write.h b/PlugIns/STBICodec/src/stbi/stb_image_write.h deleted file mode 100644 index e4b32ed1bc3..00000000000 --- a/PlugIns/STBICodec/src/stbi/stb_image_write.h +++ /dev/null @@ -1,1724 +0,0 @@ -/* stb_image_write - v1.16 - public domain - http://nothings.org/stb - writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015 - no warranty implied; use at your own risk - - Before #including, - - #define STB_IMAGE_WRITE_IMPLEMENTATION - - in the file that you want to have the implementation. - - Will probably not work correctly with strict-aliasing optimizations. - -ABOUT: - - This header file is a library for writing images to C stdio or a callback. - - The PNG output is not optimal; it is 20-50% larger than the file - written by a decent optimizing implementation; though providing a custom - zlib compress function (see STBIW_ZLIB_COMPRESS) can mitigate that. - This library is designed for source code compactness and simplicity, - not optimal image file size or run-time performance. - -BUILDING: - - You can #define STBIW_ASSERT(x) before the #include to avoid using assert.h. - You can #define STBIW_MALLOC(), STBIW_REALLOC(), and STBIW_FREE() to replace - malloc,realloc,free. - You can #define STBIW_MEMMOVE() to replace memmove() - You can #define STBIW_ZLIB_COMPRESS to use a custom zlib-style compress function - for PNG compression (instead of the builtin one), it must have the following signature: - unsigned char * my_compress(unsigned char *data, int data_len, int *out_len, int quality); - The returned data will be freed with STBIW_FREE() (free() by default), - so it must be heap allocated with STBIW_MALLOC() (malloc() by default), - -UNICODE: - - If compiling for Windows and you wish to use Unicode filenames, compile - with - #define STBIW_WINDOWS_UTF8 - and pass utf8-encoded filenames. Call stbiw_convert_wchar_to_utf8 to convert - Windows wchar_t filenames to utf8. - -USAGE: - - There are five functions, one for each image file format: - - int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); - int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); - int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); - int stbi_write_jpg(char const *filename, int w, int h, int comp, const void *data, int quality); - int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); - - void stbi_flip_vertically_on_write(int flag); // flag is non-zero to flip data vertically - - There are also five equivalent functions that use an arbitrary write function. You are - expected to open/close your file-equivalent before and after calling these: - - int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); - int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); - int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); - int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); - int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality); - - where the callback is: - void stbi_write_func(void *context, void *data, int size); - - You can configure it with these global variables: - int stbi_write_tga_with_rle; // defaults to true; set to 0 to disable RLE - int stbi_write_png_compression_level; // defaults to 8; set to higher for more compression - int stbi_write_force_png_filter; // defaults to -1; set to 0..5 to force a filter mode - - - You can define STBI_WRITE_NO_STDIO to disable the file variant of these - functions, so the library will not use stdio.h at all. However, this will - also disable HDR writing, because it requires stdio for formatted output. - - Each function returns 0 on failure and non-0 on success. - - The functions create an image file defined by the parameters. The image - is a rectangle of pixels stored from left-to-right, top-to-bottom. - Each pixel contains 'comp' channels of data stored interleaved with 8-bits - per channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. (Y is - monochrome color.) The rectangle is 'w' pixels wide and 'h' pixels tall. - The *data pointer points to the first byte of the top-left-most pixel. - For PNG, "stride_in_bytes" is the distance in bytes from the first byte of - a row of pixels to the first byte of the next row of pixels. - - PNG creates output files with the same number of components as the input. - The BMP format expands Y to RGB in the file format and does not - output alpha. - - PNG supports writing rectangles of data even when the bytes storing rows of - data are not consecutive in memory (e.g. sub-rectangles of a larger image), - by supplying the stride between the beginning of adjacent rows. The other - formats do not. (Thus you cannot write a native-format BMP through the BMP - writer, both because it is in BGR order and because it may have padding - at the end of the line.) - - PNG allows you to set the deflate compression level by setting the global - variable 'stbi_write_png_compression_level' (it defaults to 8). - - HDR expects linear float data. Since the format is always 32-bit rgb(e) - data, alpha (if provided) is discarded, and for monochrome data it is - replicated across all three channels. - - TGA supports RLE or non-RLE compressed data. To use non-RLE-compressed - data, set the global variable 'stbi_write_tga_with_rle' to 0. - - JPEG does ignore alpha channels in input data; quality is between 1 and 100. - Higher quality looks better but results in a bigger image. - JPEG baseline (no JPEG progressive). - -CREDITS: - - - Sean Barrett - PNG/BMP/TGA - Baldur Karlsson - HDR - Jean-Sebastien Guay - TGA monochrome - Tim Kelsey - misc enhancements - Alan Hickman - TGA RLE - Emmanuel Julien - initial file IO callback implementation - Jon Olick - original jo_jpeg.cpp code - Daniel Gibson - integrate JPEG, allow external zlib - Aarni Koskela - allow choosing PNG filter - - bugfixes: - github:Chribba - Guillaume Chereau - github:jry2 - github:romigrou - Sergio Gonzalez - Jonas Karlsson - Filip Wasil - Thatcher Ulrich - github:poppolopoppo - Patrick Boettcher - github:xeekworx - Cap Petschulat - Simon Rodriguez - Ivan Tikhonov - github:ignotion - Adam Schackart - Andrew Kensler - -LICENSE - - See end of file for license information. - -*/ - -#ifndef INCLUDE_STB_IMAGE_WRITE_H -#define INCLUDE_STB_IMAGE_WRITE_H - -#include - -// if STB_IMAGE_WRITE_STATIC causes problems, try defining STBIWDEF to 'inline' or 'static inline' -#ifndef STBIWDEF -#ifdef STB_IMAGE_WRITE_STATIC -#define STBIWDEF static -#else -#ifdef __cplusplus -#define STBIWDEF extern "C" -#else -#define STBIWDEF extern -#endif -#endif -#endif - -#ifndef STB_IMAGE_WRITE_STATIC // C++ forbids static forward declarations -STBIWDEF int stbi_write_tga_with_rle; -STBIWDEF int stbi_write_png_compression_level; -STBIWDEF int stbi_write_force_png_filter; -#endif - -#ifndef STBI_WRITE_NO_STDIO -STBIWDEF int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); -STBIWDEF int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); -STBIWDEF int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); -STBIWDEF int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); -STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality); - -#ifdef STBIW_WINDOWS_UTF8 -STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); -#endif -#endif - -typedef void stbi_write_func(void *context, void *data, int size); - -STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); -STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); -STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); -STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); -STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality); - -STBIWDEF void stbi_flip_vertically_on_write(int flip_boolean); - -#endif//INCLUDE_STB_IMAGE_WRITE_H - -#ifdef STB_IMAGE_WRITE_IMPLEMENTATION - -#ifdef _WIN32 - #ifndef _CRT_SECURE_NO_WARNINGS - #define _CRT_SECURE_NO_WARNINGS - #endif - #ifndef _CRT_NONSTDC_NO_DEPRECATE - #define _CRT_NONSTDC_NO_DEPRECATE - #endif -#endif - -#ifndef STBI_WRITE_NO_STDIO -#include -#endif // STBI_WRITE_NO_STDIO - -#include -#include -#include -#include - -#if defined(STBIW_MALLOC) && defined(STBIW_FREE) && (defined(STBIW_REALLOC) || defined(STBIW_REALLOC_SIZED)) -// ok -#elif !defined(STBIW_MALLOC) && !defined(STBIW_FREE) && !defined(STBIW_REALLOC) && !defined(STBIW_REALLOC_SIZED) -// ok -#else -#error "Must define all or none of STBIW_MALLOC, STBIW_FREE, and STBIW_REALLOC (or STBIW_REALLOC_SIZED)." -#endif - -#ifndef STBIW_MALLOC -#define STBIW_MALLOC(sz) malloc(sz) -#define STBIW_REALLOC(p,newsz) realloc(p,newsz) -#define STBIW_FREE(p) free(p) -#endif - -#ifndef STBIW_REALLOC_SIZED -#define STBIW_REALLOC_SIZED(p,oldsz,newsz) STBIW_REALLOC(p,newsz) -#endif - - -#ifndef STBIW_MEMMOVE -#define STBIW_MEMMOVE(a,b,sz) memmove(a,b,sz) -#endif - - -#ifndef STBIW_ASSERT -#include -#define STBIW_ASSERT(x) assert(x) -#endif - -#define STBIW_UCHAR(x) (unsigned char) ((x) & 0xff) - -#ifdef STB_IMAGE_WRITE_STATIC -static int stbi_write_png_compression_level = 8; -static int stbi_write_tga_with_rle = 1; -static int stbi_write_force_png_filter = -1; -#else -int stbi_write_png_compression_level = 8; -int stbi_write_tga_with_rle = 1; -int stbi_write_force_png_filter = -1; -#endif - -static int stbi__flip_vertically_on_write = 0; - -STBIWDEF void stbi_flip_vertically_on_write(int flag) -{ - stbi__flip_vertically_on_write = flag; -} - -typedef struct -{ - stbi_write_func *func; - void *context; - unsigned char buffer[64]; - int buf_used; -} stbi__write_context; - -// initialize a callback-based context -static void stbi__start_write_callbacks(stbi__write_context *s, stbi_write_func *c, void *context) -{ - s->func = c; - s->context = context; -} - -#ifndef STBI_WRITE_NO_STDIO - -static void stbi__stdio_write(void *context, void *data, int size) -{ - fwrite(data,1,size,(FILE*) context); -} - -#if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8) -#ifdef __cplusplus -#define STBIW_EXTERN extern "C" -#else -#define STBIW_EXTERN extern -#endif -STBIW_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); -STBIW_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); - -STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) -{ - return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); -} -#endif - -static FILE *stbiw__fopen(char const *filename, char const *mode) -{ - FILE *f; -#if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8) - wchar_t wMode[64]; - wchar_t wFilename[1024]; - if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename))) - return 0; - - if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode))) - return 0; - -#if defined(_MSC_VER) && _MSC_VER >= 1400 - if (0 != _wfopen_s(&f, wFilename, wMode)) - f = 0; -#else - f = _wfopen(wFilename, wMode); -#endif - -#elif defined(_MSC_VER) && _MSC_VER >= 1400 - if (0 != fopen_s(&f, filename, mode)) - f=0; -#else - f = fopen(filename, mode); -#endif - return f; -} - -static int stbi__start_write_file(stbi__write_context *s, const char *filename) -{ - FILE *f = stbiw__fopen(filename, "wb"); - stbi__start_write_callbacks(s, stbi__stdio_write, (void *) f); - return f != NULL; -} - -static void stbi__end_write_file(stbi__write_context *s) -{ - fclose((FILE *)s->context); -} - -#endif // !STBI_WRITE_NO_STDIO - -typedef unsigned int stbiw_uint32; -typedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1]; - -static void stbiw__writefv(stbi__write_context *s, const char *fmt, va_list v) -{ - while (*fmt) { - switch (*fmt++) { - case ' ': break; - case '1': { unsigned char x = STBIW_UCHAR(va_arg(v, int)); - s->func(s->context,&x,1); - break; } - case '2': { int x = va_arg(v,int); - unsigned char b[2]; - b[0] = STBIW_UCHAR(x); - b[1] = STBIW_UCHAR(x>>8); - s->func(s->context,b,2); - break; } - case '4': { stbiw_uint32 x = va_arg(v,int); - unsigned char b[4]; - b[0]=STBIW_UCHAR(x); - b[1]=STBIW_UCHAR(x>>8); - b[2]=STBIW_UCHAR(x>>16); - b[3]=STBIW_UCHAR(x>>24); - s->func(s->context,b,4); - break; } - default: - STBIW_ASSERT(0); - return; - } - } -} - -static void stbiw__writef(stbi__write_context *s, const char *fmt, ...) -{ - va_list v; - va_start(v, fmt); - stbiw__writefv(s, fmt, v); - va_end(v); -} - -static void stbiw__write_flush(stbi__write_context *s) -{ - if (s->buf_used) { - s->func(s->context, &s->buffer, s->buf_used); - s->buf_used = 0; - } -} - -static void stbiw__putc(stbi__write_context *s, unsigned char c) -{ - s->func(s->context, &c, 1); -} - -static void stbiw__write1(stbi__write_context *s, unsigned char a) -{ - if ((size_t)s->buf_used + 1 > sizeof(s->buffer)) - stbiw__write_flush(s); - s->buffer[s->buf_used++] = a; -} - -static void stbiw__write3(stbi__write_context *s, unsigned char a, unsigned char b, unsigned char c) -{ - int n; - if ((size_t)s->buf_used + 3 > sizeof(s->buffer)) - stbiw__write_flush(s); - n = s->buf_used; - s->buf_used = n+3; - s->buffer[n+0] = a; - s->buffer[n+1] = b; - s->buffer[n+2] = c; -} - -static void stbiw__write_pixel(stbi__write_context *s, int rgb_dir, int comp, int write_alpha, int expand_mono, unsigned char *d) -{ - unsigned char bg[3] = { 255, 0, 255}, px[3]; - int k; - - if (write_alpha < 0) - stbiw__write1(s, d[comp - 1]); - - switch (comp) { - case 2: // 2 pixels = mono + alpha, alpha is written separately, so same as 1-channel case - case 1: - if (expand_mono) - stbiw__write3(s, d[0], d[0], d[0]); // monochrome bmp - else - stbiw__write1(s, d[0]); // monochrome TGA - break; - case 4: - if (!write_alpha) { - // composite against pink background - for (k = 0; k < 3; ++k) - px[k] = bg[k] + ((d[k] - bg[k]) * d[3]) / 255; - stbiw__write3(s, px[1 - rgb_dir], px[1], px[1 + rgb_dir]); - break; - } - /* FALLTHROUGH */ - case 3: - stbiw__write3(s, d[1 - rgb_dir], d[1], d[1 + rgb_dir]); - break; - } - if (write_alpha > 0) - stbiw__write1(s, d[comp - 1]); -} - -static void stbiw__write_pixels(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad, int expand_mono) -{ - stbiw_uint32 zero = 0; - int i,j, j_end; - - if (y <= 0) - return; - - if (stbi__flip_vertically_on_write) - vdir *= -1; - - if (vdir < 0) { - j_end = -1; j = y-1; - } else { - j_end = y; j = 0; - } - - for (; j != j_end; j += vdir) { - for (i=0; i < x; ++i) { - unsigned char *d = (unsigned char *) data + (j*x+i)*comp; - stbiw__write_pixel(s, rgb_dir, comp, write_alpha, expand_mono, d); - } - stbiw__write_flush(s); - s->func(s->context, &zero, scanline_pad); - } -} - -static int stbiw__outfile(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, int expand_mono, void *data, int alpha, int pad, const char *fmt, ...) -{ - if (y < 0 || x < 0) { - return 0; - } else { - va_list v; - va_start(v, fmt); - stbiw__writefv(s, fmt, v); - va_end(v); - stbiw__write_pixels(s,rgb_dir,vdir,x,y,comp,data,alpha,pad, expand_mono); - return 1; - } -} - -static int stbi_write_bmp_core(stbi__write_context *s, int x, int y, int comp, const void *data) -{ - if (comp != 4) { - // write RGB bitmap - int pad = (-x*3) & 3; - return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *) data,0,pad, - "11 4 22 4" "4 44 22 444444", - 'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header - 40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header - } else { - // RGBA bitmaps need a v4 header - // use BI_BITFIELDS mode with 32bpp and alpha mask - // (straight BI_RGB with alpha mask doesn't work in most readers) - return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *)data,1,0, - "11 4 22 4" "4 44 22 444444 4444 4 444 444 444 444", - 'B', 'M', 14+108+x*y*4, 0, 0, 14+108, // file header - 108, x,y, 1,32, 3,0,0,0,0,0, 0xff0000,0xff00,0xff,0xff000000u, 0, 0,0,0, 0,0,0, 0,0,0, 0,0,0); // bitmap V4 header - } -} - -STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) -{ - stbi__write_context s = { 0 }; - stbi__start_write_callbacks(&s, func, context); - return stbi_write_bmp_core(&s, x, y, comp, data); -} - -#ifndef STBI_WRITE_NO_STDIO -STBIWDEF int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data) -{ - stbi__write_context s = { 0 }; - if (stbi__start_write_file(&s,filename)) { - int r = stbi_write_bmp_core(&s, x, y, comp, data); - stbi__end_write_file(&s); - return r; - } else - return 0; -} -#endif //!STBI_WRITE_NO_STDIO - -static int stbi_write_tga_core(stbi__write_context *s, int x, int y, int comp, void *data) -{ - int has_alpha = (comp == 2 || comp == 4); - int colorbytes = has_alpha ? comp-1 : comp; - int format = colorbytes < 2 ? 3 : 2; // 3 color channels (RGB/RGBA) = 2, 1 color channel (Y/YA) = 3 - - if (y < 0 || x < 0) - return 0; - - if (!stbi_write_tga_with_rle) { - return stbiw__outfile(s, -1, -1, x, y, comp, 0, (void *) data, has_alpha, 0, - "111 221 2222 11", 0, 0, format, 0, 0, 0, 0, 0, x, y, (colorbytes + has_alpha) * 8, has_alpha * 8); - } else { - int i,j,k; - int jend, jdir; - - stbiw__writef(s, "111 221 2222 11", 0,0,format+8, 0,0,0, 0,0,x,y, (colorbytes + has_alpha) * 8, has_alpha * 8); - - if (stbi__flip_vertically_on_write) { - j = 0; - jend = y; - jdir = 1; - } else { - j = y-1; - jend = -1; - jdir = -1; - } - for (; j != jend; j += jdir) { - unsigned char *row = (unsigned char *) data + j * x * comp; - int len; - - for (i = 0; i < x; i += len) { - unsigned char *begin = row + i * comp; - int diff = 1; - len = 1; - - if (i < x - 1) { - ++len; - diff = memcmp(begin, row + (i + 1) * comp, comp); - if (diff) { - const unsigned char *prev = begin; - for (k = i + 2; k < x && len < 128; ++k) { - if (memcmp(prev, row + k * comp, comp)) { - prev += comp; - ++len; - } else { - --len; - break; - } - } - } else { - for (k = i + 2; k < x && len < 128; ++k) { - if (!memcmp(begin, row + k * comp, comp)) { - ++len; - } else { - break; - } - } - } - } - - if (diff) { - unsigned char header = STBIW_UCHAR(len - 1); - stbiw__write1(s, header); - for (k = 0; k < len; ++k) { - stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin + k * comp); - } - } else { - unsigned char header = STBIW_UCHAR(len - 129); - stbiw__write1(s, header); - stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin); - } - } - } - stbiw__write_flush(s); - } - return 1; -} - -STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) -{ - stbi__write_context s = { 0 }; - stbi__start_write_callbacks(&s, func, context); - return stbi_write_tga_core(&s, x, y, comp, (void *) data); -} - -#ifndef STBI_WRITE_NO_STDIO -STBIWDEF int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data) -{ - stbi__write_context s = { 0 }; - if (stbi__start_write_file(&s,filename)) { - int r = stbi_write_tga_core(&s, x, y, comp, (void *) data); - stbi__end_write_file(&s); - return r; - } else - return 0; -} -#endif - -// ************************************************************************************************* -// Radiance RGBE HDR writer -// by Baldur Karlsson - -#define stbiw__max(a, b) ((a) > (b) ? (a) : (b)) - -#ifndef STBI_WRITE_NO_STDIO - -static void stbiw__linear_to_rgbe(unsigned char *rgbe, float *linear) -{ - int exponent; - float maxcomp = stbiw__max(linear[0], stbiw__max(linear[1], linear[2])); - - if (maxcomp < 1e-32f) { - rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0; - } else { - float normalize = (float) frexp(maxcomp, &exponent) * 256.0f/maxcomp; - - rgbe[0] = (unsigned char)(linear[0] * normalize); - rgbe[1] = (unsigned char)(linear[1] * normalize); - rgbe[2] = (unsigned char)(linear[2] * normalize); - rgbe[3] = (unsigned char)(exponent + 128); - } -} - -static void stbiw__write_run_data(stbi__write_context *s, int length, unsigned char databyte) -{ - unsigned char lengthbyte = STBIW_UCHAR(length+128); - STBIW_ASSERT(length+128 <= 255); - s->func(s->context, &lengthbyte, 1); - s->func(s->context, &databyte, 1); -} - -static void stbiw__write_dump_data(stbi__write_context *s, int length, unsigned char *data) -{ - unsigned char lengthbyte = STBIW_UCHAR(length); - STBIW_ASSERT(length <= 128); // inconsistent with spec but consistent with official code - s->func(s->context, &lengthbyte, 1); - s->func(s->context, data, length); -} - -static void stbiw__write_hdr_scanline(stbi__write_context *s, int width, int ncomp, unsigned char *scratch, float *scanline) -{ - unsigned char scanlineheader[4] = { 2, 2, 0, 0 }; - unsigned char rgbe[4]; - float linear[3]; - int x; - - scanlineheader[2] = (width&0xff00)>>8; - scanlineheader[3] = (width&0x00ff); - - /* skip RLE for images too small or large */ - if (width < 8 || width >= 32768) { - for (x=0; x < width; x++) { - switch (ncomp) { - case 4: /* fallthrough */ - case 3: linear[2] = scanline[x*ncomp + 2]; - linear[1] = scanline[x*ncomp + 1]; - linear[0] = scanline[x*ncomp + 0]; - break; - default: - linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; - break; - } - stbiw__linear_to_rgbe(rgbe, linear); - s->func(s->context, rgbe, 4); - } - } else { - int c,r; - /* encode into scratch buffer */ - for (x=0; x < width; x++) { - switch(ncomp) { - case 4: /* fallthrough */ - case 3: linear[2] = scanline[x*ncomp + 2]; - linear[1] = scanline[x*ncomp + 1]; - linear[0] = scanline[x*ncomp + 0]; - break; - default: - linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; - break; - } - stbiw__linear_to_rgbe(rgbe, linear); - scratch[x + width*0] = rgbe[0]; - scratch[x + width*1] = rgbe[1]; - scratch[x + width*2] = rgbe[2]; - scratch[x + width*3] = rgbe[3]; - } - - s->func(s->context, scanlineheader, 4); - - /* RLE each component separately */ - for (c=0; c < 4; c++) { - unsigned char *comp = &scratch[width*c]; - - x = 0; - while (x < width) { - // find first run - r = x; - while (r+2 < width) { - if (comp[r] == comp[r+1] && comp[r] == comp[r+2]) - break; - ++r; - } - if (r+2 >= width) - r = width; - // dump up to first run - while (x < r) { - int len = r-x; - if (len > 128) len = 128; - stbiw__write_dump_data(s, len, &comp[x]); - x += len; - } - // if there's a run, output it - if (r+2 < width) { // same test as what we break out of in search loop, so only true if we break'd - // find next byte after run - while (r < width && comp[r] == comp[x]) - ++r; - // output run up to r - while (x < r) { - int len = r-x; - if (len > 127) len = 127; - stbiw__write_run_data(s, len, comp[x]); - x += len; - } - } - } - } - } -} - -static int stbi_write_hdr_core(stbi__write_context *s, int x, int y, int comp, float *data) -{ - if (y <= 0 || x <= 0 || data == NULL) - return 0; - else { - // Each component is stored separately. Allocate scratch space for full output scanline. - unsigned char *scratch = (unsigned char *) STBIW_MALLOC(x*4); - int i, len; - char buffer[128]; - char header[] = "#?RADIANCE\n# Written by stb_image_write.h\nFORMAT=32-bit_rle_rgbe\n"; - s->func(s->context, header, sizeof(header)-1); - -#ifdef __STDC_LIB_EXT1__ - len = sprintf_s(buffer, sizeof(buffer), "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); -#else - len = sprintf(buffer, "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); -#endif - s->func(s->context, buffer, len); - - for(i=0; i < y; i++) - stbiw__write_hdr_scanline(s, x, comp, scratch, data + comp*x*(stbi__flip_vertically_on_write ? y-1-i : i)); - STBIW_FREE(scratch); - return 1; - } -} - -STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const float *data) -{ - stbi__write_context s = { 0 }; - stbi__start_write_callbacks(&s, func, context); - return stbi_write_hdr_core(&s, x, y, comp, (float *) data); -} - -STBIWDEF int stbi_write_hdr(char const *filename, int x, int y, int comp, const float *data) -{ - stbi__write_context s = { 0 }; - if (stbi__start_write_file(&s,filename)) { - int r = stbi_write_hdr_core(&s, x, y, comp, (float *) data); - stbi__end_write_file(&s); - return r; - } else - return 0; -} -#endif // STBI_WRITE_NO_STDIO - - -////////////////////////////////////////////////////////////////////////////// -// -// PNG writer -// - -#ifndef STBIW_ZLIB_COMPRESS -// stretchy buffer; stbiw__sbpush() == vector<>::push_back() -- stbiw__sbcount() == vector<>::size() -#define stbiw__sbraw(a) ((int *) (void *) (a) - 2) -#define stbiw__sbm(a) stbiw__sbraw(a)[0] -#define stbiw__sbn(a) stbiw__sbraw(a)[1] - -#define stbiw__sbneedgrow(a,n) ((a)==0 || stbiw__sbn(a)+n >= stbiw__sbm(a)) -#define stbiw__sbmaybegrow(a,n) (stbiw__sbneedgrow(a,(n)) ? stbiw__sbgrow(a,n) : 0) -#define stbiw__sbgrow(a,n) stbiw__sbgrowf((void **) &(a), (n), sizeof(*(a))) - -#define stbiw__sbpush(a, v) (stbiw__sbmaybegrow(a,1), (a)[stbiw__sbn(a)++] = (v)) -#define stbiw__sbcount(a) ((a) ? stbiw__sbn(a) : 0) -#define stbiw__sbfree(a) ((a) ? STBIW_FREE(stbiw__sbraw(a)),0 : 0) - -static void *stbiw__sbgrowf(void **arr, int increment, int itemsize) -{ - int m = *arr ? 2*stbiw__sbm(*arr)+increment : increment+1; - void *p = STBIW_REALLOC_SIZED(*arr ? stbiw__sbraw(*arr) : 0, *arr ? (stbiw__sbm(*arr)*itemsize + sizeof(int)*2) : 0, itemsize * m + sizeof(int)*2); - STBIW_ASSERT(p); - if (p) { - if (!*arr) ((int *) p)[1] = 0; - *arr = (void *) ((int *) p + 2); - stbiw__sbm(*arr) = m; - } - return *arr; -} - -static unsigned char *stbiw__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount) -{ - while (*bitcount >= 8) { - stbiw__sbpush(data, STBIW_UCHAR(*bitbuffer)); - *bitbuffer >>= 8; - *bitcount -= 8; - } - return data; -} - -static int stbiw__zlib_bitrev(int code, int codebits) -{ - int res=0; - while (codebits--) { - res = (res << 1) | (code & 1); - code >>= 1; - } - return res; -} - -static unsigned int stbiw__zlib_countm(unsigned char *a, unsigned char *b, int limit) -{ - int i; - for (i=0; i < limit && i < 258; ++i) - if (a[i] != b[i]) break; - return i; -} - -static unsigned int stbiw__zhash(unsigned char *data) -{ - stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16); - hash ^= hash << 3; - hash += hash >> 5; - hash ^= hash << 4; - hash += hash >> 17; - hash ^= hash << 25; - hash += hash >> 6; - return hash; -} - -#define stbiw__zlib_flush() (out = stbiw__zlib_flushf(out, &bitbuf, &bitcount)) -#define stbiw__zlib_add(code,codebits) \ - (bitbuf |= (code) << bitcount, bitcount += (codebits), stbiw__zlib_flush()) -#define stbiw__zlib_huffa(b,c) stbiw__zlib_add(stbiw__zlib_bitrev(b,c),c) -// default huffman tables -#define stbiw__zlib_huff1(n) stbiw__zlib_huffa(0x30 + (n), 8) -#define stbiw__zlib_huff2(n) stbiw__zlib_huffa(0x190 + (n)-144, 9) -#define stbiw__zlib_huff3(n) stbiw__zlib_huffa(0 + (n)-256,7) -#define stbiw__zlib_huff4(n) stbiw__zlib_huffa(0xc0 + (n)-280,8) -#define stbiw__zlib_huff(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : (n) <= 255 ? stbiw__zlib_huff2(n) : (n) <= 279 ? stbiw__zlib_huff3(n) : stbiw__zlib_huff4(n)) -#define stbiw__zlib_huffb(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : stbiw__zlib_huff2(n)) - -#define stbiw__ZHASH 16384 - -#endif // STBIW_ZLIB_COMPRESS - -STBIWDEF unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality) -{ -#ifdef STBIW_ZLIB_COMPRESS - // user provided a zlib compress implementation, use that - return STBIW_ZLIB_COMPRESS(data, data_len, out_len, quality); -#else // use builtin - static unsigned short lengthc[] = { 3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258, 259 }; - static unsigned char lengtheb[]= { 0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; - static unsigned short distc[] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577, 32768 }; - static unsigned char disteb[] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 }; - unsigned int bitbuf=0; - int i,j, bitcount=0; - unsigned char *out = NULL; - unsigned char ***hash_table = (unsigned char***) STBIW_MALLOC(stbiw__ZHASH * sizeof(unsigned char**)); - if (hash_table == NULL) - return NULL; - if (quality < 5) quality = 5; - - stbiw__sbpush(out, 0x78); // DEFLATE 32K window - stbiw__sbpush(out, 0x5e); // FLEVEL = 1 - stbiw__zlib_add(1,1); // BFINAL = 1 - stbiw__zlib_add(1,2); // BTYPE = 1 -- fixed huffman - - for (i=0; i < stbiw__ZHASH; ++i) - hash_table[i] = NULL; - - i=0; - while (i < data_len-3) { - // hash next 3 bytes of data to be compressed - int h = stbiw__zhash(data+i)&(stbiw__ZHASH-1), best=3; - unsigned char *bestloc = 0; - unsigned char **hlist = hash_table[h]; - int n = stbiw__sbcount(hlist); - for (j=0; j < n; ++j) { - if (hlist[j]-data > i-32768) { // if entry lies within window - int d = stbiw__zlib_countm(hlist[j], data+i, data_len-i); - if (d >= best) { best=d; bestloc=hlist[j]; } - } - } - // when hash table entry is too long, delete half the entries - if (hash_table[h] && stbiw__sbn(hash_table[h]) == 2*quality) { - STBIW_MEMMOVE(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality); - stbiw__sbn(hash_table[h]) = quality; - } - stbiw__sbpush(hash_table[h],data+i); - - if (bestloc) { - // "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal - h = stbiw__zhash(data+i+1)&(stbiw__ZHASH-1); - hlist = hash_table[h]; - n = stbiw__sbcount(hlist); - for (j=0; j < n; ++j) { - if (hlist[j]-data > i-32767) { - int e = stbiw__zlib_countm(hlist[j], data+i+1, data_len-i-1); - if (e > best) { // if next match is better, bail on current match - bestloc = NULL; - break; - } - } - } - } - - if (bestloc) { - int d = (int) (data+i - bestloc); // distance back - STBIW_ASSERT(d <= 32767 && best <= 258); - for (j=0; best > lengthc[j+1]-1; ++j); - stbiw__zlib_huff(j+257); - if (lengtheb[j]) stbiw__zlib_add(best - lengthc[j], lengtheb[j]); - for (j=0; d > distc[j+1]-1; ++j); - stbiw__zlib_add(stbiw__zlib_bitrev(j,5),5); - if (disteb[j]) stbiw__zlib_add(d - distc[j], disteb[j]); - i += best; - } else { - stbiw__zlib_huffb(data[i]); - ++i; - } - } - // write out final bytes - for (;i < data_len; ++i) - stbiw__zlib_huffb(data[i]); - stbiw__zlib_huff(256); // end of block - // pad with 0 bits to byte boundary - while (bitcount) - stbiw__zlib_add(0,1); - - for (i=0; i < stbiw__ZHASH; ++i) - (void) stbiw__sbfree(hash_table[i]); - STBIW_FREE(hash_table); - - // store uncompressed instead if compression was worse - if (stbiw__sbn(out) > data_len + 2 + ((data_len+32766)/32767)*5) { - stbiw__sbn(out) = 2; // truncate to DEFLATE 32K window and FLEVEL = 1 - for (j = 0; j < data_len;) { - int blocklen = data_len - j; - if (blocklen > 32767) blocklen = 32767; - stbiw__sbpush(out, data_len - j == blocklen); // BFINAL = ?, BTYPE = 0 -- no compression - stbiw__sbpush(out, STBIW_UCHAR(blocklen)); // LEN - stbiw__sbpush(out, STBIW_UCHAR(blocklen >> 8)); - stbiw__sbpush(out, STBIW_UCHAR(~blocklen)); // NLEN - stbiw__sbpush(out, STBIW_UCHAR(~blocklen >> 8)); - memcpy(out+stbiw__sbn(out), data+j, blocklen); - stbiw__sbn(out) += blocklen; - j += blocklen; - } - } - - { - // compute adler32 on input - unsigned int s1=1, s2=0; - int blocklen = (int) (data_len % 5552); - j=0; - while (j < data_len) { - for (i=0; i < blocklen; ++i) { s1 += data[j+i]; s2 += s1; } - s1 %= 65521; s2 %= 65521; - j += blocklen; - blocklen = 5552; - } - stbiw__sbpush(out, STBIW_UCHAR(s2 >> 8)); - stbiw__sbpush(out, STBIW_UCHAR(s2)); - stbiw__sbpush(out, STBIW_UCHAR(s1 >> 8)); - stbiw__sbpush(out, STBIW_UCHAR(s1)); - } - *out_len = stbiw__sbn(out); - // make returned pointer freeable - STBIW_MEMMOVE(stbiw__sbraw(out), out, *out_len); - return (unsigned char *) stbiw__sbraw(out); -#endif // STBIW_ZLIB_COMPRESS -} - -static unsigned int stbiw__crc32(unsigned char *buffer, int len) -{ -#ifdef STBIW_CRC32 - return STBIW_CRC32(buffer, len); -#else - static unsigned int crc_table[256] = - { - 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, - 0x0eDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, - 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, - 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, - 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, - 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, - 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, - 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, - 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, - 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, - 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, - 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, - 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, - 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, - 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, - 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, - 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, - 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, - 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, - 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, - 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, - 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, - 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, - 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, - 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, - 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, - 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, - 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, - 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, - 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, - 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, - 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D - }; - - unsigned int crc = ~0u; - int i; - for (i=0; i < len; ++i) - crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)]; - return ~crc; -#endif -} - -#define stbiw__wpng4(o,a,b,c,d) ((o)[0]=STBIW_UCHAR(a),(o)[1]=STBIW_UCHAR(b),(o)[2]=STBIW_UCHAR(c),(o)[3]=STBIW_UCHAR(d),(o)+=4) -#define stbiw__wp32(data,v) stbiw__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v)); -#define stbiw__wptag(data,s) stbiw__wpng4(data, s[0],s[1],s[2],s[3]) - -static void stbiw__wpcrc(unsigned char **data, int len) -{ - unsigned int crc = stbiw__crc32(*data - len - 4, len+4); - stbiw__wp32(*data, crc); -} - -static unsigned char stbiw__paeth(int a, int b, int c) -{ - int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c); - if (pa <= pb && pa <= pc) return STBIW_UCHAR(a); - if (pb <= pc) return STBIW_UCHAR(b); - return STBIW_UCHAR(c); -} - -// @OPTIMIZE: provide an option that always forces left-predict or paeth predict -static void stbiw__encode_png_line(unsigned char *pixels, int stride_bytes, int width, int height, int y, int n, int filter_type, signed char *line_buffer) -{ - static int mapping[] = { 0,1,2,3,4 }; - static int firstmap[] = { 0,1,0,5,6 }; - int *mymap = (y != 0) ? mapping : firstmap; - int i; - int type = mymap[filter_type]; - unsigned char *z = pixels + stride_bytes * (stbi__flip_vertically_on_write ? height-1-y : y); - int signed_stride = stbi__flip_vertically_on_write ? -stride_bytes : stride_bytes; - - if (type==0) { - memcpy(line_buffer, z, width*n); - return; - } - - // first loop isn't optimized since it's just one pixel - for (i = 0; i < n; ++i) { - switch (type) { - case 1: line_buffer[i] = z[i]; break; - case 2: line_buffer[i] = z[i] - z[i-signed_stride]; break; - case 3: line_buffer[i] = z[i] - (z[i-signed_stride]>>1); break; - case 4: line_buffer[i] = (signed char) (z[i] - stbiw__paeth(0,z[i-signed_stride],0)); break; - case 5: line_buffer[i] = z[i]; break; - case 6: line_buffer[i] = z[i]; break; - } - } - switch (type) { - case 1: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-n]; break; - case 2: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-signed_stride]; break; - case 3: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - ((z[i-n] + z[i-signed_stride])>>1); break; - case 4: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], z[i-signed_stride], z[i-signed_stride-n]); break; - case 5: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - (z[i-n]>>1); break; - case 6: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], 0,0); break; - } -} - -STBIWDEF unsigned char *stbi_write_png_to_mem(const unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len) -{ - int force_filter = stbi_write_force_png_filter; - int ctype[5] = { -1, 0, 4, 2, 6 }; - unsigned char sig[8] = { 137,80,78,71,13,10,26,10 }; - unsigned char *out,*o, *filt, *zlib; - signed char *line_buffer; - int j,zlen; - - if (stride_bytes == 0) - stride_bytes = x * n; - - if (force_filter >= 5) { - force_filter = -1; - } - - filt = (unsigned char *) STBIW_MALLOC((x*n+1) * y); if (!filt) return 0; - line_buffer = (signed char *) STBIW_MALLOC(x * n); if (!line_buffer) { STBIW_FREE(filt); return 0; } - for (j=0; j < y; ++j) { - int filter_type; - if (force_filter > -1) { - filter_type = force_filter; - stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, force_filter, line_buffer); - } else { // Estimate the best filter by running through all of them: - int best_filter = 0, best_filter_val = 0x7fffffff, est, i; - for (filter_type = 0; filter_type < 5; filter_type++) { - stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, filter_type, line_buffer); - - // Estimate the entropy of the line using this filter; the less, the better. - est = 0; - for (i = 0; i < x*n; ++i) { - est += abs((signed char) line_buffer[i]); - } - if (est < best_filter_val) { - best_filter_val = est; - best_filter = filter_type; - } - } - if (filter_type != best_filter) { // If the last iteration already got us the best filter, don't redo it - stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, best_filter, line_buffer); - filter_type = best_filter; - } - } - // when we get here, filter_type contains the filter type, and line_buffer contains the data - filt[j*(x*n+1)] = (unsigned char) filter_type; - STBIW_MEMMOVE(filt+j*(x*n+1)+1, line_buffer, x*n); - } - STBIW_FREE(line_buffer); - zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, stbi_write_png_compression_level); - STBIW_FREE(filt); - if (!zlib) return 0; - - // each tag requires 12 bytes of overhead - out = (unsigned char *) STBIW_MALLOC(8 + 12+13 + 12+zlen + 12); - if (!out) return 0; - *out_len = 8 + 12+13 + 12+zlen + 12; - - o=out; - STBIW_MEMMOVE(o,sig,8); o+= 8; - stbiw__wp32(o, 13); // header length - stbiw__wptag(o, "IHDR"); - stbiw__wp32(o, x); - stbiw__wp32(o, y); - *o++ = 8; - *o++ = STBIW_UCHAR(ctype[n]); - *o++ = 0; - *o++ = 0; - *o++ = 0; - stbiw__wpcrc(&o,13); - - stbiw__wp32(o, zlen); - stbiw__wptag(o, "IDAT"); - STBIW_MEMMOVE(o, zlib, zlen); - o += zlen; - STBIW_FREE(zlib); - stbiw__wpcrc(&o, zlen); - - stbiw__wp32(o,0); - stbiw__wptag(o, "IEND"); - stbiw__wpcrc(&o,0); - - STBIW_ASSERT(o == out + *out_len); - - return out; -} - -#ifndef STBI_WRITE_NO_STDIO -STBIWDEF int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes) -{ - FILE *f; - int len; - unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len); - if (png == NULL) return 0; - - f = stbiw__fopen(filename, "wb"); - if (!f) { STBIW_FREE(png); return 0; } - fwrite(png, 1, len, f); - fclose(f); - STBIW_FREE(png); - return 1; -} -#endif - -STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int stride_bytes) -{ - int len; - unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len); - if (png == NULL) return 0; - func(context, png, len); - STBIW_FREE(png); - return 1; -} - - -/* *************************************************************************** - * - * JPEG writer - * - * This is based on Jon Olick's jo_jpeg.cpp: - * public domain Simple, Minimalistic JPEG writer - http://www.jonolick.com/code.html - */ - -static const unsigned char stbiw__jpg_ZigZag[] = { 0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18, - 24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63 }; - -static void stbiw__jpg_writeBits(stbi__write_context *s, int *bitBufP, int *bitCntP, const unsigned short *bs) { - int bitBuf = *bitBufP, bitCnt = *bitCntP; - bitCnt += bs[1]; - bitBuf |= bs[0] << (24 - bitCnt); - while(bitCnt >= 8) { - unsigned char c = (bitBuf >> 16) & 255; - stbiw__putc(s, c); - if(c == 255) { - stbiw__putc(s, 0); - } - bitBuf <<= 8; - bitCnt -= 8; - } - *bitBufP = bitBuf; - *bitCntP = bitCnt; -} - -static void stbiw__jpg_DCT(float *d0p, float *d1p, float *d2p, float *d3p, float *d4p, float *d5p, float *d6p, float *d7p) { - float d0 = *d0p, d1 = *d1p, d2 = *d2p, d3 = *d3p, d4 = *d4p, d5 = *d5p, d6 = *d6p, d7 = *d7p; - float z1, z2, z3, z4, z5, z11, z13; - - float tmp0 = d0 + d7; - float tmp7 = d0 - d7; - float tmp1 = d1 + d6; - float tmp6 = d1 - d6; - float tmp2 = d2 + d5; - float tmp5 = d2 - d5; - float tmp3 = d3 + d4; - float tmp4 = d3 - d4; - - // Even part - float tmp10 = tmp0 + tmp3; // phase 2 - float tmp13 = tmp0 - tmp3; - float tmp11 = tmp1 + tmp2; - float tmp12 = tmp1 - tmp2; - - d0 = tmp10 + tmp11; // phase 3 - d4 = tmp10 - tmp11; - - z1 = (tmp12 + tmp13) * 0.707106781f; // c4 - d2 = tmp13 + z1; // phase 5 - d6 = tmp13 - z1; - - // Odd part - tmp10 = tmp4 + tmp5; // phase 2 - tmp11 = tmp5 + tmp6; - tmp12 = tmp6 + tmp7; - - // The rotator is modified from fig 4-8 to avoid extra negations. - z5 = (tmp10 - tmp12) * 0.382683433f; // c6 - z2 = tmp10 * 0.541196100f + z5; // c2-c6 - z4 = tmp12 * 1.306562965f + z5; // c2+c6 - z3 = tmp11 * 0.707106781f; // c4 - - z11 = tmp7 + z3; // phase 5 - z13 = tmp7 - z3; - - *d5p = z13 + z2; // phase 6 - *d3p = z13 - z2; - *d1p = z11 + z4; - *d7p = z11 - z4; - - *d0p = d0; *d2p = d2; *d4p = d4; *d6p = d6; -} - -static void stbiw__jpg_calcBits(int val, unsigned short bits[2]) { - int tmp1 = val < 0 ? -val : val; - val = val < 0 ? val-1 : val; - bits[1] = 1; - while(tmp1 >>= 1) { - ++bits[1]; - } - bits[0] = val & ((1<0)&&(DU[end0pos]==0); --end0pos) { - } - // end0pos = first element in reverse order !=0 - if(end0pos == 0) { - stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); - return DU[0]; - } - for(i = 1; i <= end0pos; ++i) { - int startpos = i; - int nrzeroes; - unsigned short bits[2]; - for (; DU[i]==0 && i<=end0pos; ++i) { - } - nrzeroes = i-startpos; - if ( nrzeroes >= 16 ) { - int lng = nrzeroes>>4; - int nrmarker; - for (nrmarker=1; nrmarker <= lng; ++nrmarker) - stbiw__jpg_writeBits(s, bitBuf, bitCnt, M16zeroes); - nrzeroes &= 15; - } - stbiw__jpg_calcBits(DU[i], bits); - stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTAC[(nrzeroes<<4)+bits[1]]); - stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits); - } - if(end0pos != 63) { - stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); - } - return DU[0]; -} - -static int stbi_write_jpg_core(stbi__write_context *s, int width, int height, int comp, const void* data, int quality) { - // Constants that don't pollute global namespace - static const unsigned char std_dc_luminance_nrcodes[] = {0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0}; - static const unsigned char std_dc_luminance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; - static const unsigned char std_ac_luminance_nrcodes[] = {0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d}; - static const unsigned char std_ac_luminance_values[] = { - 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08, - 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28, - 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59, - 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89, - 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6, - 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2, - 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa - }; - static const unsigned char std_dc_chrominance_nrcodes[] = {0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0}; - static const unsigned char std_dc_chrominance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; - static const unsigned char std_ac_chrominance_nrcodes[] = {0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77}; - static const unsigned char std_ac_chrominance_values[] = { - 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91, - 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26, - 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58, - 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87, - 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4, - 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda, - 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa - }; - // Huffman tables - static const unsigned short YDC_HT[256][2] = { {0,2},{2,3},{3,3},{4,3},{5,3},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9}}; - static const unsigned short UVDC_HT[256][2] = { {0,2},{1,2},{2,2},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9},{1022,10},{2046,11}}; - static const unsigned short YAC_HT[256][2] = { - {10,4},{0,2},{1,2},{4,3},{11,4},{26,5},{120,7},{248,8},{1014,10},{65410,16},{65411,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {12,4},{27,5},{121,7},{502,9},{2038,11},{65412,16},{65413,16},{65414,16},{65415,16},{65416,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {28,5},{249,8},{1015,10},{4084,12},{65417,16},{65418,16},{65419,16},{65420,16},{65421,16},{65422,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {58,6},{503,9},{4085,12},{65423,16},{65424,16},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {59,6},{1016,10},{65430,16},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {122,7},{2039,11},{65438,16},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {123,7},{4086,12},{65446,16},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {250,8},{4087,12},{65454,16},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {504,9},{32704,15},{65462,16},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {505,9},{65470,16},{65471,16},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {506,9},{65479,16},{65480,16},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {1017,10},{65488,16},{65489,16},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {1018,10},{65497,16},{65498,16},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {2040,11},{65506,16},{65507,16},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {65515,16},{65516,16},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{0,0},{0,0},{0,0},{0,0},{0,0}, - {2041,11},{65525,16},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} - }; - static const unsigned short UVAC_HT[256][2] = { - {0,2},{1,2},{4,3},{10,4},{24,5},{25,5},{56,6},{120,7},{500,9},{1014,10},{4084,12},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {11,4},{57,6},{246,8},{501,9},{2038,11},{4085,12},{65416,16},{65417,16},{65418,16},{65419,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {26,5},{247,8},{1015,10},{4086,12},{32706,15},{65420,16},{65421,16},{65422,16},{65423,16},{65424,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {27,5},{248,8},{1016,10},{4087,12},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{65430,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {58,6},{502,9},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{65438,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {59,6},{1017,10},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{65446,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {121,7},{2039,11},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{65454,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {122,7},{2040,11},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{65462,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {249,8},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{65470,16},{65471,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {503,9},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{65479,16},{65480,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {504,9},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{65488,16},{65489,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {505,9},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{65497,16},{65498,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {506,9},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{65506,16},{65507,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {2041,11},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{65515,16},{65516,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {16352,14},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{65525,16},{0,0},{0,0},{0,0},{0,0},{0,0}, - {1018,10},{32707,15},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} - }; - static const int YQT[] = {16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22, - 37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99}; - static const int UVQT[] = {17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99, - 99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99}; - static const float aasf[] = { 1.0f * 2.828427125f, 1.387039845f * 2.828427125f, 1.306562965f * 2.828427125f, 1.175875602f * 2.828427125f, - 1.0f * 2.828427125f, 0.785694958f * 2.828427125f, 0.541196100f * 2.828427125f, 0.275899379f * 2.828427125f }; - - int row, col, i, k, subsample; - float fdtbl_Y[64], fdtbl_UV[64]; - unsigned char YTable[64], UVTable[64]; - - if(!data || !width || !height || comp > 4 || comp < 1) { - return 0; - } - - quality = quality ? quality : 90; - subsample = quality <= 90 ? 1 : 0; - quality = quality < 1 ? 1 : quality > 100 ? 100 : quality; - quality = quality < 50 ? 5000 / quality : 200 - quality * 2; - - for(i = 0; i < 64; ++i) { - int uvti, yti = (YQT[i]*quality+50)/100; - YTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (yti < 1 ? 1 : yti > 255 ? 255 : yti); - uvti = (UVQT[i]*quality+50)/100; - UVTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (uvti < 1 ? 1 : uvti > 255 ? 255 : uvti); - } - - for(row = 0, k = 0; row < 8; ++row) { - for(col = 0; col < 8; ++col, ++k) { - fdtbl_Y[k] = 1 / (YTable [stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); - fdtbl_UV[k] = 1 / (UVTable[stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); - } - } - - // Write Headers - { - static const unsigned char head0[] = { 0xFF,0xD8,0xFF,0xE0,0,0x10,'J','F','I','F',0,1,1,0,0,1,0,1,0,0,0xFF,0xDB,0,0x84,0 }; - static const unsigned char head2[] = { 0xFF,0xDA,0,0xC,3,1,0,2,0x11,3,0x11,0,0x3F,0 }; - const unsigned char head1[] = { 0xFF,0xC0,0,0x11,8,(unsigned char)(height>>8),STBIW_UCHAR(height),(unsigned char)(width>>8),STBIW_UCHAR(width), - 3,1,(unsigned char)(subsample?0x22:0x11),0,2,0x11,1,3,0x11,1,0xFF,0xC4,0x01,0xA2,0 }; - s->func(s->context, (void*)head0, sizeof(head0)); - s->func(s->context, (void*)YTable, sizeof(YTable)); - stbiw__putc(s, 1); - s->func(s->context, UVTable, sizeof(UVTable)); - s->func(s->context, (void*)head1, sizeof(head1)); - s->func(s->context, (void*)(std_dc_luminance_nrcodes+1), sizeof(std_dc_luminance_nrcodes)-1); - s->func(s->context, (void*)std_dc_luminance_values, sizeof(std_dc_luminance_values)); - stbiw__putc(s, 0x10); // HTYACinfo - s->func(s->context, (void*)(std_ac_luminance_nrcodes+1), sizeof(std_ac_luminance_nrcodes)-1); - s->func(s->context, (void*)std_ac_luminance_values, sizeof(std_ac_luminance_values)); - stbiw__putc(s, 1); // HTUDCinfo - s->func(s->context, (void*)(std_dc_chrominance_nrcodes+1), sizeof(std_dc_chrominance_nrcodes)-1); - s->func(s->context, (void*)std_dc_chrominance_values, sizeof(std_dc_chrominance_values)); - stbiw__putc(s, 0x11); // HTUACinfo - s->func(s->context, (void*)(std_ac_chrominance_nrcodes+1), sizeof(std_ac_chrominance_nrcodes)-1); - s->func(s->context, (void*)std_ac_chrominance_values, sizeof(std_ac_chrominance_values)); - s->func(s->context, (void*)head2, sizeof(head2)); - } - - // Encode 8x8 macroblocks - { - static const unsigned short fillBits[] = {0x7F, 7}; - int DCY=0, DCU=0, DCV=0; - int bitBuf=0, bitCnt=0; - // comp == 2 is grey+alpha (alpha is ignored) - int ofsG = comp > 2 ? 1 : 0, ofsB = comp > 2 ? 2 : 0; - const unsigned char *dataR = (const unsigned char *)data; - const unsigned char *dataG = dataR + ofsG; - const unsigned char *dataB = dataR + ofsB; - int x, y, pos; - if(subsample) { - for(y = 0; y < height; y += 16) { - for(x = 0; x < width; x += 16) { - float Y[256], U[256], V[256]; - for(row = y, pos = 0; row < y+16; ++row) { - // row >= height => use last input row - int clamped_row = (row < height) ? row : height - 1; - int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp; - for(col = x; col < x+16; ++col, ++pos) { - // if col >= width => use pixel from last input column - int p = base_p + ((col < width) ? col : (width-1))*comp; - float r = dataR[p], g = dataG[p], b = dataB[p]; - Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128; - U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b; - V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b; - } - } - DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+0, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); - DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+8, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); - DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+128, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); - DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+136, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); - - // subsample U,V - { - float subU[64], subV[64]; - int yy, xx; - for(yy = 0, pos = 0; yy < 8; ++yy) { - for(xx = 0; xx < 8; ++xx, ++pos) { - int j = yy*32+xx*2; - subU[pos] = (U[j+0] + U[j+1] + U[j+16] + U[j+17]) * 0.25f; - subV[pos] = (V[j+0] + V[j+1] + V[j+16] + V[j+17]) * 0.25f; - } - } - DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subU, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); - DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subV, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); - } - } - } - } else { - for(y = 0; y < height; y += 8) { - for(x = 0; x < width; x += 8) { - float Y[64], U[64], V[64]; - for(row = y, pos = 0; row < y+8; ++row) { - // row >= height => use last input row - int clamped_row = (row < height) ? row : height - 1; - int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp; - for(col = x; col < x+8; ++col, ++pos) { - // if col >= width => use pixel from last input column - int p = base_p + ((col < width) ? col : (width-1))*comp; - float r = dataR[p], g = dataG[p], b = dataB[p]; - Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128; - U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b; - V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b; - } - } - - DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y, 8, fdtbl_Y, DCY, YDC_HT, YAC_HT); - DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, U, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); - DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, V, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); - } - } - } - - // Do the bit alignment of the EOI marker - stbiw__jpg_writeBits(s, &bitBuf, &bitCnt, fillBits); - } - - // EOI - stbiw__putc(s, 0xFF); - stbiw__putc(s, 0xD9); - - return 1; -} - -STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality) -{ - stbi__write_context s = { 0 }; - stbi__start_write_callbacks(&s, func, context); - return stbi_write_jpg_core(&s, x, y, comp, (void *) data, quality); -} - - -#ifndef STBI_WRITE_NO_STDIO -STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality) -{ - stbi__write_context s = { 0 }; - if (stbi__start_write_file(&s,filename)) { - int r = stbi_write_jpg_core(&s, x, y, comp, data, quality); - stbi__end_write_file(&s); - return r; - } else - return 0; -} -#endif - -#endif // STB_IMAGE_WRITE_IMPLEMENTATION - -/* Revision history - 1.16 (2021-07-11) - make Deflate code emit uncompressed blocks when it would otherwise expand - support writing BMPs with alpha channel - 1.15 (2020-07-13) unknown - 1.14 (2020-02-02) updated JPEG writer to downsample chroma channels - 1.13 - 1.12 - 1.11 (2019-08-11) - - 1.10 (2019-02-07) - support utf8 filenames in Windows; fix warnings and platform ifdefs - 1.09 (2018-02-11) - fix typo in zlib quality API, improve STB_I_W_STATIC in C++ - 1.08 (2018-01-29) - add stbi__flip_vertically_on_write, external zlib, zlib quality, choose PNG filter - 1.07 (2017-07-24) - doc fix - 1.06 (2017-07-23) - writing JPEG (using Jon Olick's code) - 1.05 ??? - 1.04 (2017-03-03) - monochrome BMP expansion - 1.03 ??? - 1.02 (2016-04-02) - avoid allocating large structures on the stack - 1.01 (2016-01-16) - STBIW_REALLOC_SIZED: support allocators with no realloc support - avoid race-condition in crc initialization - minor compile issues - 1.00 (2015-09-14) - installable file IO function - 0.99 (2015-09-13) - warning fixes; TGA rle support - 0.98 (2015-04-08) - added STBIW_MALLOC, STBIW_ASSERT etc - 0.97 (2015-01-18) - fixed HDR asserts, rewrote HDR rle logic - 0.96 (2015-01-17) - add HDR output - fix monochrome BMP - 0.95 (2014-08-17) - add monochrome TGA output - 0.94 (2014-05-31) - rename private functions to avoid conflicts with stb_image.h - 0.93 (2014-05-27) - warning fixes - 0.92 (2010-08-01) - casts to unsigned char to fix warnings - 0.91 (2010-07-17) - first public release - 0.90 first internal release -*/ - -/* ------------------------------------------------------------------------------- -This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------- -ALTERNATIVE A - MIT License -Copyright (c) 2017 Sean Barrett -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. ------------------------------------------------------------------------------- -ALTERNATIVE B - Public Domain (www.unlicense.org) -This is free and unencumbered software released into the public domain. -Anyone is free to copy, modify, publish, use, compile, sell, or distribute this -software, either in source code form or as a compiled binary, for any purpose, -commercial or non-commercial, and by any means. -In jurisdictions that recognize copyright laws, the author or authors of this -software dedicate any and all copyright interest in the software to the public -domain. We make this dedication for the benefit of the public at large and to -the detriment of our heirs and successors. We intend this dedication to be an -overt act of relinquishment in perpetuity of all present and future rights to -this software under copyright law. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- -*/ diff --git a/README.md b/README.md deleted file mode 100644 index e203f8a18e0..00000000000 --- a/README.md +++ /dev/null @@ -1,89 +0,0 @@ -[![GitHub release](https://img.shields.io/github/release/ogrecave/ogre.svg)](https://github.com/OGRECave/ogre/releases/latest) -[![Downloads](https://static.pepy.tech/badge/ogre-python)](https://pepy.tech/project/ogre-python) -[![Join the chat at https://gitter.im/OGRECave/ogre](https://badges.gitter.im/OGRECave/ogre.svg)](https://gitter.im/OGRECave/ogre?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -[![Patreon](https://img.shields.io/badge/patreon-donate-blue.svg)](https://www.patreon.com/ogre1) - -![](Other/ogre_header.png) - -## Summary -**OGRE** (Object-Oriented Graphics Rendering Engine) is a -scene-oriented, flexible 3D engine written in C++ designed to make it -easier and more intuitive for developers to produce games and demos -utilising 3D hardware. The class library abstracts all the details of -using the underlying system libraries like Direct3D and OpenGL and -provides an interface based on world objects and other intuitive -classes. - -| Build | Status | -|-------|-----------------| -| Linux, OSX, Android, iOS | [![CI Build](https://github.com/OGRECave/ogre/workflows/CI%20Build/badge.svg?branch=master)](https://github.com/OGRECave/ogre/actions?query=branch%3Amaster) | -| MSVC | [![Build status](https://ci.appveyor.com/api/projects/status/kcki7y0n1ahrggdw/branch/master?svg=true)](https://ci.appveyor.com/project/paroj/ogre-bsrh7/branch/master) | - -## Index Of Contents -* [What's New?](Docs/14-Notes.md) -A summary of the new and altered features in this release. -* [Building the core OGRE libraries](https://ogrecave.github.io/ogre/api/latest/building-ogre.html) -If you're using the full source release, this will help you build it. If you're using a precompiled SDK then most of the work has already been done for you, and you should use the sample projects to see how to compile your own code against OGRE. -* [The OGRE Manual](https://ogrecave.github.io/ogre/api/latest/manual.html) -A high-level guide to the major parts of the engine and script reference. -* [API Reference](https://ogrecave.github.io/ogre/api/latest/) -The full OGRE API documentation, as generated from the (heavily!) commented source. -* [The OGRE Tutorials](https://ogrecave.github.io/ogre/api/latest/tutorials.html) -A gold mine of tutorials, tips and code snippets which will help you get up to speed with the engine. - -## Try it -* [Online Emscripten Demo](https://ogrecave.github.io/ogre/emscripten/) -* [Linux Snap Package](https://snapcraft.io/ogre) -* [Android App on F-Droid](https://f-droid.org/packages/org.ogre.browser/) - -## Features - -For an exhaustive list, see the [features page](http://www.ogre3d.org/about/features) and try our Sample Browser. For a quick overview see below - -| Integrated Bump and Offset Mapping | Integrated shadows | -|----|----| -| ![](Other/screenshots/bumpmap.webp) | ![](Other/screenshots/shadows.jpg) | - -| Physically Based Shading | Particle Effects | -|----|----| -| ![](Other/screenshots/pbr.webp) | ![](Other/screenshots/particle.jpg) | - -| HW & SW skeletal animation | Multi-layer Terrain | -|----|----| -| ![](Other/screenshots/skeletal.jpg) | ![](Other/screenshots/terrain.jpg) | - -| Automatic Rendertarget pipelining (Compositors) | Volume Rendering with CSG & Triplanar Texturing | -|----|----| -| ![](Other/screenshots/compositor.jpg) | ![](Other/screenshots/volume.jpg) | - -| [Dear ImGui](https://github.com/ocornut/imgui) | [Bullet Physics](https://pybullet.org/) Integration | -|----|----| -| ![](Other/screenshots/imgui.jpg) | ![](Other/screenshots/bullet.webp) | - -## Who is using it? - -**Open Source** -- [Stunt Rally - 3D Racing Game with Track Editor](https://stuntrally.tuxfamily.org/) -- [Rigs of Rods - Soft Body Physics Simulator](https://rigsofrods.org/) -- [Gazebo - Robot simulation](http://gazebosim.org/) -- [OpenCV OVIS visualization module](https://docs.opencv.org/master/d2/d17/group__ovis.html) -- [ROS 3D visualization tool](http://wiki.ros.org/rviz) -- [Surgical Image Toolkit](https://github.com/IRCAD/sight#applications) - -**Closed Source** -- [Hob](http://store.steampowered.com/app/404680/Hob/) -- [Torchlight II](http://store.steampowered.com/app/200710/Torchlight_II/) -- [Battlezone 98 Redux](http://store.steampowered.com/app/301650/Battlezone_98_Redux/) - -## Contributing -We welcome all contributions to OGRE, be that new -plugins, bugfixes, extensions, tutorials, documentation, example -applications, artwork or pretty much anything else! If you would like -to contribute to the development of OGRE, please create a [pull request](https://github.com/OGRECave/ogre/pulls). - -## Getting Support -Please use our [community support forums](http://forums.ogre3d.org/) if you need help or -think you may have found a bug. - -## Licensing -Please see the [full license documentation](Docs/License.md) for details. diff --git a/RenderSystems/CMakeLists.txt b/RenderSystems/CMakeLists.txt deleted file mode 100644 index 14b0ecbdc48..00000000000 --- a/RenderSystems/CMakeLists.txt +++ /dev/null @@ -1,76 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure RenderSystem build - -if (OGRE_BUILD_RENDERSYSTEM_D3D9) - if (NOT DirectX9_FOUND) - MESSAGE(STATUS "Could not find dependency: DirectX") - MESSAGE(STATUS "Skipping Direct3D9 rendersystem build") - set(OGRE_BUILD_RENDERSYSTEM_D3D9 0) - else () - add_subdirectory(Direct3D9) - endif () -endif () - -if (OGRE_BUILD_RENDERSYSTEM_D3D11) - if (NOT DirectX11_FOUND) - MESSAGE(STATUS "Could not find dependency: DirectX") - MESSAGE(STATUS "Skipping Direct3D11 rendersystem build") - set(OGRE_BUILD_RENDERSYSTEM_D3D11 0) - else () - add_subdirectory(Direct3D11) - endif () -endif () - -if (OGRE_BUILD_RENDERSYSTEM_GL OR OGRE_BUILD_RENDERSYSTEM_GL3PLUS OR OGRE_BUILD_RENDERSYSTEM_GLES2) - add_subdirectory(GLSupport) -endif() - -if (OGRE_BUILD_RENDERSYSTEM_GL) - if (NOT OPENGL_FOUND) - MESSAGE(STATUS "Could not find dependency: GL") - MESSAGE(STATUS "Skipping GL rendersystem build") - set(OGRE_BUILD_RENDERSYSTEM_GL 0) - else () - add_subdirectory(GL) - endif () -endif () - -if (OGRE_BUILD_RENDERSYSTEM_GL3PLUS) - if (NOT OPENGL_FOUND) - MESSAGE(STATUS "Could not find dependency: GL3Plus") - MESSAGE(STATUS "Skipping GL3Plus rendersystem build") - set(OGRE_BUILD_RENDERSYSTEM_GL3PLUS 0) - else () - add_subdirectory(GL3Plus) - endif () -endif () - -if (OGRE_BUILD_RENDERSYSTEM_GLES2) - if (NOT OPENGLES2_FOUND) - MESSAGE(STATUS "Could not find dependency: GLES2 ") - MESSAGE(STATUS "Skipping GLES2 rendersystem build") - set(OGRE_BUILD_RENDERSYSTEM_GLES2 0) - else () - add_subdirectory(GLES2) - endif() -endif() - -if (OGRE_BUILD_RENDERSYSTEM_METAL) - add_subdirectory(Metal) -endif() - -if (OGRE_BUILD_RENDERSYSTEM_TINY) - add_subdirectory(Tiny) -endif() - -if (OGRE_BUILD_RENDERSYSTEM_VULKAN) - add_subdirectory(Vulkan) -endif() diff --git a/RenderSystems/Direct3D11/CMakeLists.txt b/RenderSystems/Direct3D11/CMakeLists.txt deleted file mode 100644 index 3d77fe39d5a..00000000000 --- a/RenderSystems/Direct3D11/CMakeLists.txt +++ /dev/null @@ -1,59 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure Direct3D11 RenderSystem build - -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") - -if(OGRE_CONFIG_ENABLE_QUAD_BUFFER_STEREO) - include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include ${DirectX11_INCLUDE_DIR} ${AMDQBS_INCLUDE_DIR} ${NVAPI_INCLUDE_DIR}) - link_directories(${DirectX11_LIBRARY_DIR} ${NVAPI_LIBRARY_DIR}) -else() - include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include ${DirectX11_INCLUDE_DIR}) - link_directories(${DirectX11_LIBRARY_DIR}) -endif() - -add_definitions(-D_USRDLL) - -if(MINGW) - add_definitions(-DINITGUID -DD3D_COMPILER_VERSION=47) -endif() - -add_library(RenderSystem_Direct3D11 ${OGRE_LIB_TYPE} ${HEADER_FILES} ${SOURCE_FILES}) -target_link_libraries(RenderSystem_Direct3D11 - OgreMain - ${DirectX11_LIBRARIES} -) - -if(OGRE_PROFILING AND DirectX9_FOUND) - target_link_libraries(RenderSystem_Direct3D11 ${DirectX9_LIBRARY}) -endif() -if (MINGW) - target_link_libraries(RenderSystem_Direct3D11 psapi d3dcompiler) -endif () - -if(WINDOWS_STORE OR WINDOWS_PHONE) - set_target_properties(RenderSystem_Direct3D11 PROPERTIES VS_WINRT_COMPONENT "true") -endif() - -if (NOT OGRE_STATIC) - set_target_properties(RenderSystem_Direct3D11 PROPERTIES - COMPILE_DEFINITIONS OGRED3DENGINEDLL_EXPORTS - ) -endif () -if (OGRE_CONFIG_THREADS) - target_link_libraries(RenderSystem_Direct3D11 ${OGRE_THREAD_LIBRARIES}) -endif () -if(OGRE_CONFIG_ENABLE_QUAD_BUFFER_STEREO) - target_link_libraries(RenderSystem_Direct3D11 ${NVAPI_LIBRARIES}) -endif() - -ogre_config_plugin(RenderSystem_Direct3D11) -install(FILES ${HEADER_FILES} DESTINATION include/OGRE/RenderSystems/Direct3D11) diff --git a/RenderSystems/Direct3D11/include/OgreComPtr.h b/RenderSystems/Direct3D11/include/OgreComPtr.h deleted file mode 100644 index 7d59bbeef58..00000000000 --- a/RenderSystems/Direct3D11/include/OgreComPtr.h +++ /dev/null @@ -1,252 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ ------------------------------------------------------------------------------ -The MIT License (MIT) - -Copyright (c) 2015 Kenny Kerr - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. ------------------------------------------------------------------------------ - -This file was derived from ComPtr implementation made by Kenny Kerr for moderncpp -library http://moderncpp.com, design was described in MSDN magazine -February 2015 article "Windows with C++ - COM Smart Pointers Revisited" -https://msdn.microsoft.com/en-us/magazine/dn904668.aspx of the same author. - -Code was downgraded to C++ 98, and to more closely match Microsoft::Wrl::ComPtr, -which is actually what we want except licensing issues. - -'noexcept' was removed for performance reasons, to avoid extra try/catch block -generation that calls std::terminate. It was replaced with ASSUME_NOEXCEPT macro -that expands to VC++ specific non-compliant 'throw ()' that works like a hint and -does not call std::unexpected nor std::terminate. - -'explicit operator bool()' was replaced using SafeBool idiom - -ComPtr::GetAddressOf() behavior reverted to match Microsoft::Wrl::ComPtr and not -check that smart pointer is empty - this behavior is dangerous as it allows to modify -smart pointer internals, but it is preferred as many Direct3D11 samples expect it. - ------------------------------------------------------------------------------ -*/ -#ifndef __OgreComPtr_H__ -#define __OgreComPtr_H__ - -#include "OgreD3D11Prerequisites.h" -#include // for HRESULT - -#ifdef __MINGW32__ -typedef long HRESULT; -#endif - -#if !defined(ASSUME_NOEXCEPT) && defined( _MSC_VER ) -#define ASSUME_NOEXCEPT throw () // use non-compliant behavior of VC++ - compile as if exceptions are not possible, performing no run-time checks -#else -#define ASSUME_NOEXCEPT // don`t define it as 'noexcept' or compliant 'throw ()' or extra try/catch frame would be generated to call std::terminate/std::unexpected -#endif - -namespace Ogre -{ - /** \addtogroup RenderSystems - * @{ - */ - /** \addtogroup Direct3D11 - * @{ - */ - - // Helper to hide reference count management from user - template - class NoAddRefRelease : public T - { - unsigned long __stdcall AddRef(); - unsigned long __stdcall Release(); - }; - - template - class ComPtr - { - T* m_ptr; - - template friend class ComPtr; - - void InternalAddRef() const ASSUME_NOEXCEPT - { - if(m_ptr) - { - m_ptr->AddRef(); - } - } - - void InternalRelease() ASSUME_NOEXCEPT - { - if(T * temp = m_ptr) - { - m_ptr = 0; - temp->Release(); - } - } - - void InternalCopy(T * other) ASSUME_NOEXCEPT - { - if(m_ptr != other) - { - InternalRelease(); - m_ptr = other; - InternalAddRef(); - } - } - - public: - typedef T Type; - - public: - ComPtr() ASSUME_NOEXCEPT : m_ptr(0) {} - - template - ComPtr(U* other) ASSUME_NOEXCEPT : m_ptr(other) - { - InternalAddRef(); - } - - ComPtr(const ComPtr & other) ASSUME_NOEXCEPT : m_ptr(other.m_ptr) - { - InternalAddRef(); - } - - template - ComPtr(ComPtr const & other) ASSUME_NOEXCEPT : m_ptr(other.m_ptr) - { - InternalAddRef(); - } - - ~ComPtr() ASSUME_NOEXCEPT - { - InternalRelease(); - } - - ComPtr& operator=(T* other) ASSUME_NOEXCEPT - { - InternalCopy(other); - return *this; - } - - template - ComPtr& operator=(U* other) ASSUME_NOEXCEPT - { - InternalCopy(other); - return *this; - } - - ComPtr& operator=(const ComPtr& other) ASSUME_NOEXCEPT - { - InternalCopy(other.m_ptr); - return *this; - } - - template - ComPtr& operator=(const ComPtr& other) ASSUME_NOEXCEPT - { - InternalCopy(other.m_ptr); - return *this; - } - - void Swap(ComPtr& other) ASSUME_NOEXCEPT - { - T* temp = m_ptr; - m_ptr = other.m_ptr; - other.m_ptr = temp; - } - -#if __cplusplus >= 201103L || OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_COMP_VER >= 1800 - explicit operator bool() const ASSUME_NOEXCEPT - { - return 0 != m_ptr; - } -#else - struct SafeBoolHelper { int member; }; - typedef int SafeBoolHelper::* SafeBoolType; - operator SafeBoolType() const ASSUME_NOEXCEPT - { - return 0 != m_ptr ? &SafeBoolHelper::member : 0; - } -#endif - - T* Get() const ASSUME_NOEXCEPT - { - return m_ptr; - } - - NoAddRefRelease* operator->() const ASSUME_NOEXCEPT - { - return static_cast *>(m_ptr); - } - - T** GetAddressOf() ASSUME_NOEXCEPT - { - return &m_ptr; - } - - T** ReleaseAndGetAddressOf() ASSUME_NOEXCEPT - { - InternalRelease(); - return &m_ptr; - } - - T* Detach() ASSUME_NOEXCEPT - { - T* temp = m_ptr; - m_ptr = 0; - return temp; - } - - void Attach(T* other) ASSUME_NOEXCEPT - { - InternalRelease(); - m_ptr = other; - } - - void Reset() ASSUME_NOEXCEPT - { - InternalRelease(); - } - - template - HRESULT As(ComPtr *res) const ASSUME_NOEXCEPT - { - return m_ptr->QueryInterface(res->ReleaseAndGetAddressOf()); - } - - }; - - template void swap(ComPtr& a, ComPtr& b) { return a.Swap(b); } - - template bool operator==(const ComPtr& a, const ComPtr& b) ASSUME_NOEXCEPT { return a.Get() == b.Get(); } - template bool operator!=(const ComPtr& a, const ComPtr& b) ASSUME_NOEXCEPT { return a.Get() != b.Get(); } - template bool operator< (const ComPtr& a, const ComPtr& b) ASSUME_NOEXCEPT { return a.Get() < b.Get(); } - template bool operator> (const ComPtr& a, const ComPtr& b) ASSUME_NOEXCEPT { return a.Get() > b.Get(); } - template bool operator<=(const ComPtr& a, const ComPtr& b) ASSUME_NOEXCEPT { return a.Get() <= b.Get(); } - template bool operator>=(const ComPtr& a, const ComPtr& b) ASSUME_NOEXCEPT { return a.Get() >= b.Get(); } - - /** @} */ - /** @} */ -} -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11DepthBuffer.h b/RenderSystems/Direct3D11/include/OgreD3D11DepthBuffer.h deleted file mode 100644 index 1b0a6130a92..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11DepthBuffer.h +++ /dev/null @@ -1,58 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11DepthBuffer_H__ -#define __D3D11DepthBuffer_H__ - -#include "OgreD3D11Prerequisites.h" -#include "OgreDepthBuffer.h" - -namespace Ogre -{ - class _OgreD3D11Export D3D11DepthBuffer : public DepthBuffer - { - public: - D3D11DepthBuffer( uint16 poolId, D3D11RenderSystem *renderSystem, - ID3D11DepthStencilView *depthBufferView, - uint32 width, uint32 height, - uint32 fsaa, uint32 multiSampleQuality, bool isManual ); - ~D3D11DepthBuffer(); - - /// @copydoc DepthBuffer::isCompatible - virtual bool isCompatible( RenderTarget *renderTarget ) const; - - ID3D11DepthStencilView* getDepthStencilView() const; - /// internal method, gets called when the renderwindow was resized - void _resized(ID3D11DepthStencilView *depthBufferView, uint32 width, uint32 height); - - protected: - ID3D11DepthStencilView *mDepthStencilView; //aka. actual "DepthBuffer" - uint32 mMultiSampleQuality; - D3D11RenderSystem *mRenderSystem; - }; -} -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11Device.h b/RenderSystems/Direct3D11/include/OgreD3D11Device.h deleted file mode 100644 index 53d398e87df..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11Device.h +++ /dev/null @@ -1,107 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11DEVICE_H__ -#define __D3D11DEVICE_H__ - - -#include "OgreD3D11Prerequisites.h" - -namespace Ogre -{ - class _OgreD3D11Export D3D11Device - { - private: - ComPtr mD3D11Device; - ComPtr mImmediateContext; - ComPtr mClassLinkage; - ComPtr mInfoQueue; - LARGE_INTEGER mDriverVersion; - ComPtr mDXGIFactory; -#if OGRE_D3D11_PROFILING - ComPtr mPerf; -#endif - - D3D11Device(const D3D11Device& device); /* intentionally not implemented */ - const D3D11Device& operator=(D3D11Device& device); /* intentionally not implemented */ - - public: - D3D11Device(); - ~D3D11Device(); - - void ReleaseAll(); - void TransferOwnership(ID3D11DeviceN* device); - bool IsDeviceLost(); - - bool isNull() { return !mD3D11Device; } - ID3D11DeviceN* get() { return mD3D11Device.Get(); } - ID3D11DeviceContextN* GetImmediateContext() { return mImmediateContext.Get(); } - ID3D11ClassLinkage* GetClassLinkage() { return mClassLinkage.Get(); } - IDXGIFactoryN* GetDXGIFactory() { return mDXGIFactory.Get(); } - LARGE_INTEGER GetDriverVersion() { return mDriverVersion; } -#if OGRE_D3D11_PROFILING - ID3DUserDefinedAnnotation* GetProfiler() { return mPerf.Get(); } -#endif - - ID3D11DeviceN* operator->() const - { - assert(mD3D11Device); - if (D3D_NO_EXCEPTION != mExceptionsErrorLevel) - { - clearStoredErrorMessages(); - } - return mD3D11Device.Get(); - } - - void throwIfFailed(HRESULT hr, const char* desc, const char* src); - void throwIfFailed(const char* desc, const char* src) { throwIfFailed(NO_ERROR, desc, src); } - - String getErrorDescription(const HRESULT hr = NO_ERROR) const; - void clearStoredErrorMessages() const; - bool _getErrorsFromQueue() const; - - bool isError() const { return (D3D_NO_EXCEPTION == mExceptionsErrorLevel) ? false : _getErrorsFromQueue(); } - - enum eExceptionsErrorLevel - { - D3D_NO_EXCEPTION, - D3D_CORRUPTION, - D3D_ERROR, - D3D_WARNING, - D3D_INFO, - }; - - static eExceptionsErrorLevel mExceptionsErrorLevel; - static const eExceptionsErrorLevel getExceptionsErrorLevel(); - static void setExceptionsErrorLevel(const eExceptionsErrorLevel exceptionsErrorLevel); - static void setExceptionsErrorLevel(const Ogre::String& exceptionsErrorLevel); - - static D3D_FEATURE_LEVEL parseFeatureLevel(const Ogre::String& value, D3D_FEATURE_LEVEL fallback); - static D3D_DRIVER_TYPE parseDriverType(const Ogre::String& value, D3D_DRIVER_TYPE fallback = D3D_DRIVER_TYPE_HARDWARE); - }; -} -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11DeviceResource.h b/RenderSystems/Direct3D11/include/OgreD3D11DeviceResource.h deleted file mode 100644 index b87616fcab3..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11DeviceResource.h +++ /dev/null @@ -1,81 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2015 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11Resource_H__ -#define __D3D11Resource_H__ - -#include "OgreD3D11Prerequisites.h" - -namespace Ogre { - - /** Represents a Direct3D rendering resource. - Provide unified interface to handle various device states. - This class is intended to be used as protected base. - */ - class D3D11DeviceResource - { - public: - - // Called immediately after the Direct3D device has entered a removed state. - // This is the place to release device depended resources. - virtual void notifyDeviceLost(D3D11Device* device) = 0; - - // Called immediately after the Direct3D device has been reset. - // This is the place to create device depended resources. - virtual void notifyDeviceRestored(D3D11Device* device) = 0; - - protected: - D3D11DeviceResource(); - ~D3D11DeviceResource(); // protected and non-virtual - }; - - - /** Singleton that is used to propagate device state changed notifications. - This class is intended to be used as protected base. - */ - class D3D11DeviceResourceManager - { - public: - - void notifyResourceCreated(D3D11DeviceResource* deviceResource); - void notifyResourceDestroyed(D3D11DeviceResource* deviceResource); - - void notifyDeviceLost(D3D11Device* device); - void notifyDeviceRestored(D3D11Device* device); - - static D3D11DeviceResourceManager* get(); - - protected: - D3D11DeviceResourceManager(); - ~D3D11DeviceResourceManager(); // protected and non-virtual - - private: - std::vector mResources, mResourcesCopy; - }; - -} -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11Driver.h b/RenderSystems/Direct3D11/include/OgreD3D11Driver.h deleted file mode 100644 index 877667e3bca..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11Driver.h +++ /dev/null @@ -1,63 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11DRIVER_H__ -#define __D3D11DRIVER_H__ - -#include "OgreD3D11Prerequisites.h" -#include "OgreSharedPtr.h" - -namespace Ogre -{ - - class D3D11VideoModeList; - class D3D11VideoMode; - - class _OgreD3D11Export D3D11Driver - { - private: - ComPtr mDXGIAdapter; - DXGI_ADAPTER_DESC1 mAdapterIdentifier; - unsigned mSameNameAdapterIndex; - SharedPtr mVideoModeList; - - public: - // Constructors - D3D11Driver(); // Default - D3D11Driver( IDXGIAdapterN* pDXGIAdapter, const DXGI_ADAPTER_DESC1& desc, unsigned sameNameIndex); - ~D3D11Driver(); - - // Information accessors - String DriverDescription() const; - - // change the device - const DXGI_ADAPTER_DESC1& getAdapterIdentifier() const; - IDXGIAdapterN* getDeviceAdapter() const; - D3D11VideoModeList* getVideoModeList(); - }; -} -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11DriverList.h b/RenderSystems/Direct3D11/include/OgreD3D11DriverList.h deleted file mode 100644 index 2288a5521a0..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11DriverList.h +++ /dev/null @@ -1,56 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11DRIVERLIST_H__ -#define __D3D11DRIVERLIST_H__ - -#include "OgreD3D11Prerequisites.h" -#include "OgreSharedPtr.h" - -namespace Ogre -{ - class _OgreD3D11Export D3D11DriverList - { - public: - D3D11DriverList(); // does nothing, call refresh() to initialize - ~D3D11DriverList(); - - void refresh(); - void clear(); - - size_t count() const; /// does not include hidden drivers like NVPerfHUD - D3D11Driver* item( size_t index ); - D3D11Driver* item( const String &name ); - - D3D11Driver* findByName( const String &name ); // never fail but can return default driver if requested is not found - - private: - std::vector > mDriverList; - unsigned mHiddenDriversCount; - }; -} -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11HLSLProgram.h b/RenderSystems/Direct3D11/include/OgreD3D11HLSLProgram.h deleted file mode 100644 index 800efd175cb..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11HLSLProgram.h +++ /dev/null @@ -1,228 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11HLSLProgram_H__ -#define __D3D11HLSLProgram_H__ - -#include "OgreD3D11Prerequisites.h" -#include "OgreD3D11DeviceResource.h" -#include "OgreHighLevelGpuProgram.h" - - -namespace Ogre { - typedef std::vector MicroCode; - - /** Specialization of HighLevelGpuProgram to provide support for D3D11 - High-Level Shader Language (HLSL). - - Note that the syntax of D3D11 HLSL is identical to nVidia's Cg language, therefore - unless you know you will only ever be deploying on Direct3D, or you have some specific - reason for not wanting to use the Cg plugin, I suggest you use Cg instead since that - can produce programs for OpenGL too. - */ - class _OgreD3D11Export D3D11HLSLProgram - : public HighLevelGpuProgram - , protected D3D11DeviceResource - { - public: - /// Command object for setting target assembler - class CmdTarget : public ParamCommand - { - public: - String doGet(const void* target) const; - void doSet(void* target, const String& val); - }; - /// Command object for setting matrix packing in column-major order - class CmdColumnMajorMatrices : public ParamCommand - { - public: - String doGet(const void* target) const; - void doSet(void* target, const String& val); - }; - /// Command object for setting backwards compatibility - class CmdEnableBackwardsCompatibility : public ParamCommand - { - public: - String doGet(const void* target) const; - void doSet(void* target, const String& val); - }; - - typedef std::vector D3d11ShaderParameters; - protected: - - static CmdTarget msCmdTarget; - static CmdColumnMajorMatrices msCmdColumnMajorMatrices; - static CmdEnableBackwardsCompatibility msCmdEnableBackwardsCompatibility; - - void notifyDeviceLost(D3D11Device* device); - void notifyDeviceRestored(D3D11Device* device); - - /// noop - void createLowLevelImpl(void) override {} - /// Internal unload implementation, must be implemented by subclasses - void unloadHighLevelImpl(void) override; - void unprepareImpl() override; - - // Recursive utility method for populateParameterNames - void processParamElement(String prefix, String paramName, ID3D11ShaderReflectionType* varRefType); - - void populateDef(D3D11_SHADER_TYPE_DESC& d3dDesc, GpuConstantDefinition& def) const; - - bool mColumnMajorMatrices; - bool mEnableBackwardsCompatibility; - - MicroCode mMicroCode; - - D3D11Device & mDevice; - - ComPtr mVertexShader; - ComPtr mPixelShader; - ComPtr mGeometryShader; - ComPtr mDomainShader; - ComPtr mHullShader; - ComPtr mComputeShader; - - HardwareBufferPtr mDefaultBuffer; // for $Globals OR $Params - - // Make sure that objects have index and name, or some search will fail - typedef std::map BufferInfoMap; - BufferInfoMap mBufferInfoMap; - - // Map to store interface slot position. - // Number of interface slots is size of this map. - typedef std::map SlotMap; - typedef std::map::const_iterator SlotIterator; - SlotMap mSlotMap; - - typedef D3d11ShaderParameters::iterator D3d11ShaderParametersIter; - - - typedef std::vector D3d11ShaderVariables; - typedef D3d11ShaderVariables::iterator D3d11ShaderVariablesIter; - - struct GpuConstantDefinitionWithName : GpuConstantDefinition - { - String Name; - }; - typedef std::vector D3d11ShaderVariableSubparts; - typedef D3d11ShaderVariableSubparts::iterator D3d11ShaderVariableSubpartsIter; - - struct MemberTypeName - { - String Name; - }; - - std::vector mSerStrings; - - typedef std::vector D3d11ShaderBufferDescs; - typedef std::vector D3d11ShaderTypeDescs; - typedef std::vector InterfaceSlots; - typedef std::vector MemberTypeNames; - - UINT mConstantBufferSize; - UINT mConstantBufferNr; - UINT mNumSlots; - D3d11ShaderParameters mD3d11ShaderInputParameters; - D3d11ShaderParameters mD3d11ShaderOutputParameters; - D3d11ShaderVariables mD3d11ShaderVariables; - D3d11ShaderVariableSubparts mD3d11ShaderVariableSubparts; - D3d11ShaderBufferDescs mD3d11ShaderBufferDescs; - D3d11ShaderVariables mVarDescBuffer; - D3d11ShaderVariables mVarDescPointer; - D3d11ShaderTypeDescs mD3d11ShaderTypeDescs; - D3d11ShaderTypeDescs mMemberTypeDesc; - MemberTypeNames mMemberTypeName; - InterfaceSlots mInterfaceSlots; - - void analizeMicrocode(); - void getMicrocodeFromCache(uint32 id); - void compileMicrocode(void); - public: - D3D11HLSLProgram(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, D3D11Device & device); - ~D3D11HLSLProgram(); - - /** Sets the shader target to compile down to, e.g. 'vs_1_1'. */ - void setTarget(const String& target); - /** Gets the shader target to compile down to, e.g. 'vs_1_1'. */ - const String& getTarget(void) const { return mSyntaxCode; } - /** Gets the shader target promoted to the first compatible, e.g. 'vs_4_0' or 'ps_4_0' if backward compatibility is enabled. */ - const char* getCompatibleTarget(void) const; - - /** Sets whether matrix packing in column-major order. */ - void setColumnMajorMatrices(bool columnMajor) { mColumnMajorMatrices = columnMajor; } - /** Gets whether matrix packed in column-major order. */ - bool getColumnMajorMatrices(void) const { return mColumnMajorMatrices; } - /** Sets whether backwards compatibility is enabled. */ - void setEnableBackwardsCompatibility(bool enableBackwardsCompatibility) { mEnableBackwardsCompatibility = enableBackwardsCompatibility; } - /** Gets whether backwards compatibility is enabled. */ - bool getEnableBackwardsCompatibility(void) const { return mEnableBackwardsCompatibility; } - /// Overridden from GpuProgram - GpuProgramParametersSharedPtr createParameters(void); - /// Overridden from GpuProgram - const String& getLanguage(void) const; - - virtual void buildConstantDefinitions() override; - ID3D11VertexShader* getVertexShader(void) const; - ID3D11PixelShader* getPixelShader(void) const; - ID3D11GeometryShader* getGeometryShader(void) const; - ID3D11DomainShader* getDomainShader(void) const; - ID3D11HullShader* getHullShader(void) const; - ID3D11ComputeShader* getComputeShader(void) const; - const MicroCode & getMicroCode(void) const; - - std::vector getConstantBuffers(const GpuProgramParametersPtr& params); - - // Get slot for a specific interface - unsigned int getSubroutineSlot(const String& subroutineSlotName) const; - - void CreateVertexShader(); - void CreatePixelShader(); - void CreateGeometryShader(); - void CreateDomainShader(); - void CreateHullShader(); - void CreateComputeShader(); - - /// shortcut as we there is no low-level separation here - GpuProgram* _getBindingDelegate(void) { return this; } - - /** Internal load implementation, must be implemented by subclasses. - */ - void loadFromSource(void); - - void prepareImpl(); - - void reinterpretGSForStreamOut(void); - bool mReinterpretingGS; - - uint32 getNameForMicrocodeCache(); - - const D3d11ShaderParameters& getInputParams() const { return mD3d11ShaderInputParameters; } - }; -} - -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11HLSLProgramFactory.h b/RenderSystems/Direct3D11/include/OgreD3D11HLSLProgramFactory.h deleted file mode 100644 index 3e70e4b7b0b..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11HLSLProgramFactory.h +++ /dev/null @@ -1,54 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11HLSLProgramFactory_H__ -#define __D3D11HLSLProgramFactory_H__ - -#include "OgreD3D11Prerequisites.h" -#include "OgreHighLevelGpuProgramManager.h" - -namespace Ogre -{ - /** Factory class for D3D11 HLSL programs. */ - class _OgreD3D11Export D3D11HLSLProgramFactory : public HighLevelGpuProgramFactory - { - protected: - static String sLanguageName; - D3D11Device & mDevice; - public: - D3D11HLSLProgramFactory(D3D11Device & device); - ~D3D11HLSLProgramFactory(); - /// Get the name of the language this factory creates programs for - const String& getLanguage(void) const; - GpuProgram* create(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader); - - }; -} - -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11HardwareBuffer.h b/RenderSystems/Direct3D11/include/OgreD3D11HardwareBuffer.h deleted file mode 100644 index 5b8c6854b2f..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11HardwareBuffer.h +++ /dev/null @@ -1,90 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11HARDWAREBUFFER_H__ -#define __D3D11HARDWAREBUFFER_H__ - -#include "OgreD3D11Prerequisites.h" -#include "OgreHardwareBuffer.h" - -namespace Ogre { - - - /** Base implementation of a D3D11 buffer, dealing with all the common - aspects. - */ - class _OgreD3D11Export D3D11HardwareBuffer : public HardwareBuffer - { - public: - enum BufferType - { - VERTEX_BUFFER, - INDEX_BUFFER, - CONSTANT_BUFFER - }; - protected: - ComPtr mlpD3DBuffer; - bool mUseTempStagingBuffer; - BufferType mBufferType; - D3D11Device & mDevice; - D3D11_BUFFER_DESC mDesc; - - - - /** See HardwareBuffer. */ - void* lockImpl(size_t offset, size_t length, LockOptions options) override; - /** See HardwareBuffer. */ - void unlockImpl(void) override; - - public: - D3D11HardwareBuffer(BufferType btype, size_t sizeBytes, HardwareBuffer::Usage usage, - D3D11Device & device, bool useShadowBuffer, bool streamOut); - ~D3D11HardwareBuffer(); - /** See HardwareBuffer. */ - void readData(size_t offset, size_t length, void* pDest) override; - /** See HardwareBuffer. */ - void writeData(size_t offset, size_t length, const void* pSource, - bool discardWholeBuffer = false) override; - /** See HardwareBuffer. We perform a hardware copy here. */ - void copyData(HardwareBuffer& srcBuffer, size_t srcOffset, - size_t dstOffset, size_t length, bool discardWholeBuffer = false) override; - void copyDataImpl(HardwareBuffer& srcBuffer, size_t srcOffset, - size_t dstOffset, size_t length, bool discardWholeBuffer = false); - /// Updates the real buffer from the shadow buffer, if required - void _updateFromShadow(void) override; - - /// Get the D3D-specific buffer - ID3D11Buffer* getD3DBuffer(void) const { return mlpD3DBuffer.Get(); } - }; - - -} - - - -#endif - diff --git a/RenderSystems/Direct3D11/include/OgreD3D11HardwareBufferManager.h b/RenderSystems/Direct3D11/include/OgreD3D11HardwareBufferManager.h deleted file mode 100644 index 12513437354..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11HardwareBufferManager.h +++ /dev/null @@ -1,68 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11HARWAREBUFFERMANAGER_H__ -#define __D3D11HARWAREBUFFERMANAGER_H__ - -#include "OgreD3D11Prerequisites.h" -#include "OgreHardwareBufferManager.h" - -namespace Ogre { - - /** Implementation of HardwareBufferManager for D3D11. */ - class _OgreD3D11Export D3D11HardwareBufferManager : public HardwareBufferManager - { - protected: - D3D11Device & mlpD3DDevice; - - /// Internal method for creates a new vertex declaration, may be overridden by certain rendering APIs - VertexDeclaration* createVertexDeclarationImpl(void); - - public: - D3D11HardwareBufferManager(D3D11Device & device); - ~D3D11HardwareBufferManager(); - /// Creates a vertex buffer - HardwareVertexBufferSharedPtr - createVertexBuffer(size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer = false); - /// Creates a stream output vertex buffer - HardwareVertexBufferSharedPtr - createStreamOutputVertexBuffer(size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer = false); - /// Create a hardware vertex buffer - HardwareIndexBufferSharedPtr - createIndexBuffer(HardwareIndexBuffer::IndexType itype, size_t numIndexes, HardwareBuffer::Usage usage, bool useShadowBuffer = false); - /// @copydoc HardwareBufferManager::createRenderToVertexBuffer - RenderToVertexBufferSharedPtr createRenderToVertexBuffer(); - /// @copydoc HardwareBufferManager::createUniformBuffer - HardwareBufferPtr createUniformBuffer(size_t sizeBytes, HardwareBufferUsage usage = HBU_CPU_TO_GPU, - bool useShadowBuffer = false) override; - }; - - typedef D3D11HardwareBufferManager D3D11HardwareBufferManagerBase; -} - - -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11HardwareOcclusionQuery.h b/RenderSystems/Direct3D11/include/OgreD3D11HardwareOcclusionQuery.h deleted file mode 100644 index dbea8a89eb0..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11HardwareOcclusionQuery.h +++ /dev/null @@ -1,95 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef _D3D11HARWAREOCCLUSIONQUERY_H__ -#define _D3D11HARWAREOCCLUSIONQUERY_H__ - -#include "OgreD3D11Prerequisites.h" -#include "OgreHardwareOcclusionQuery.h" -#include "OgreD3D11Device.h" - -namespace Ogre { - - // If you use multiple rendering passes you can test only the first pass and all other passes don't have to be rendered - // if the first pass results has too few pixels visible. - - // Be sure to render all occluder first and whats out so the RenderQue don't switch places on - // the occluding objects and the tested objects because it thinks it's more effective.. - - /** - * This is a class that is the DirectX9 implementation of - * hardware occlusion testing. - * - * @author Lee Sandberg, email lee@abcmedia.se - * - * Updated on 12/7/2004 by Chris McGuirk - * Updated on 4/8/2005 by Tuan Kuranes email: tuan.kuranes@free.fr - */ - class _OgreD3D11Export D3D11HardwareOcclusionQuery : public HardwareOcclusionQuery - { - //---------------------------------------------------------------------- - // Public methods - //-- - public: - - /** - * Default object constructor - * - */ - D3D11HardwareOcclusionQuery( D3D11Device & device ); - - /** - * Object destructor - */ - ~D3D11HardwareOcclusionQuery(); - - //------------------------------------------------------------------ - // Occlusion query functions (see base class documentation for this) - //-- - - void beginOcclusionQuery(); - void endOcclusionQuery(); - bool pullOcclusionQuery( unsigned int* NumOfFragments); - unsigned int getLastQuerysPixelcount() { return mPixelCount; } - bool isStillOutstanding(void); - - - - //---------------------------------------------------------------------- - // private members - //-- - private: - ComPtr mQuery; - D3D11Device & mDevice; - }; - - -} - - -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11HardwarePixelBuffer.h b/RenderSystems/Direct3D11/include/OgreD3D11HardwarePixelBuffer.h deleted file mode 100644 index a9eed311130..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11HardwarePixelBuffer.h +++ /dev/null @@ -1,90 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11PIXELBUFFER_H__ -#define __D3D11PIXELBUFFER_H__ - -#include "OgreD3D11Prerequisites.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreD3D11Driver.h" - -struct ID3D11Resource; - -namespace Ogre { - - class _OgreD3D11Export D3D11HardwarePixelBuffer : public HardwarePixelBuffer - { - protected: - /// Lock a box - PixelBox lockImpl(const Box &lockBox, LockOptions options); - - /// Unlock a box - void unlockImpl(void); - - /// D3DDevice pointer - D3D11Device & mDevice; - - D3D11Texture * mParentTexture; - const UINT mFace; - const UINT mMipLevel; - - void createStagingBuffer(); - bool mUsingStagingBuffer; - ComPtr mStagingBuffer; - - void _map(ID3D11Resource *res, D3D11_MAP flags, PixelBox & box); - void _mapstagingbuffer(D3D11_MAP flags, PixelBox &box); - - void _unmap(ID3D11Resource *res); - void _unmapstagingbuffer(bool copyback = true); - public: - D3D11HardwarePixelBuffer(D3D11Texture * parentTexture, D3D11Device & device, UINT mipLevel, - size_t width, size_t height, size_t depth, UINT face, PixelFormat format, HardwareBuffer::Usage usage); - - /// @copydoc HardwarePixelBuffer::blit - void blit(const HardwarePixelBufferSharedPtr &src, const Box &srcBox, const Box &dstBox); - - /// @copydoc HardwarePixelBuffer::blitFromMemory - void blitFromMemory(const PixelBox &src, const Box &dstBox); - - /// @copydoc HardwarePixelBuffer::blitToMemory - void blitToMemory(const Box &srcBox, const PixelBox &dst); - - /// Internal function to update mipmaps on update of level 0 - void _genMipmaps(); - - - ~D3D11HardwarePixelBuffer(); - - D3D11Texture * getParentTexture() const; - - UINT getFace() const; - UINT getSubresourceIndex(size_t box_front) const; - D3D11_BOX getSubresourceBox(const Box &box) const; - }; -}; -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11Mappings.h b/RenderSystems/Direct3D11/include/OgreD3D11Mappings.h deleted file mode 100644 index 439c9c88585..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11Mappings.h +++ /dev/null @@ -1,96 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11MAPPINGS_H__ -#define __D3D11MAPPINGS_H__ - -#include "OgreD3D11Prerequisites.h" -#include "OgreTextureUnitState.h" -#include "OgreRenderSystem.h" -#include "OgreHardwareIndexBuffer.h" - -namespace Ogre -{ - class _OgreD3D11Export D3D11Mappings - { - public: - /// return a D3D11 equivalent for a Ogre TextureAddressingMode value - static D3D11_TEXTURE_ADDRESS_MODE get(TextureAddressingMode tam); - /// return a D3D11 equivalent for a Ogre SceneBlendFactor value - static D3D11_BLEND get(SceneBlendFactor sbf, bool forAlpha); - /// return a D3D11 equivalent for a Ogre SceneBlendOperation value - static D3D11_BLEND_OP get(SceneBlendOperation sbo); - /// return a D3D11 equivalent for a Ogre CompareFunction value - static D3D11_COMPARISON_FUNC get(CompareFunction cf); - /// return a D3D11 equivalent for a Ogre CillingMode value - static D3D11_CULL_MODE get(CullingMode cm, bool flip = false); - /// return a D3D11 equivalent for a Ogre PolygonMode value - static D3D11_FILL_MODE get(PolygonMode level); - /// return a D3D11 equivalent for a Ogre StencilOperation value - static D3D11_STENCIL_OP get(StencilOperation op, bool invert = false); - /// return a D3D11 state type for Ogre FilterOption min/mag/mip values - static D3D11_FILTER get(const FilterOptions minification, const FilterOptions magnification, const FilterOptions mips, const bool comparison = false); - /// Get lock options - static D3D11_MAP get(HardwareBuffer::LockOptions options, HardwareBuffer::Usage usage); - /// Get index type - static DXGI_FORMAT getFormat(HardwareIndexBuffer::IndexType itype); - /// Get vertex data type - static DXGI_FORMAT get(VertexElementType vType); - /// Get vertex semantic - static LPCSTR get(VertexElementSemantic sem); - static VertexElementSemantic get(LPCSTR sem); - - /// utility method, generates Ogre PixelBox using usual parameters and dataPtr/rowPitch/slicePitch from D3D11_MAPPED_SUBRESOURCE - static PixelBox getPixelBoxWithMapping(D3D11_BOX extents, DXGI_FORMAT pixelFormat, const D3D11_MAPPED_SUBRESOURCE& mapping); - /// utility method, applies dataPtr/rowPitch/slicePitch from D3D11_MAPPED_SUBRESOURCE to Ogre PixelBox - static void setPixelBoxMapping(PixelBox& box, const D3D11_MAPPED_SUBRESOURCE& mapping); - - /// utility method, convert D3D11 pixel format to Ogre pixel format - static PixelFormat _getPF(DXGI_FORMAT d3dPF); - /// utility method, convert Ogre pixel format to D3D11 pixel format - static DXGI_FORMAT _getPF(PixelFormat ogrePF); - /// utility method, optionally maps plain format to _SRGB counterparts - static DXGI_FORMAT _getGammaFormat(DXGI_FORMAT format, bool appendSRGB); - static bool _isBinaryCompressedFormat(DXGI_FORMAT d3dPF); - - static D3D11_USAGE _getUsage(HardwareBuffer::Usage usage); - static D3D11_USAGE _getUsage(TextureUsage usage) { return _getUsage(static_cast(usage)); } - static UINT _getAccessFlags(HardwareBuffer::Usage usage); - static UINT _getAccessFlags(TextureUsage usage) { return _getAccessFlags(static_cast(usage)); } - static bool _isDynamic(HardwareBuffer::Usage usage); - static bool _isDynamic(TextureUsage usage) { return _isDynamic(static_cast(usage)); } - - /// utility method, find closest Ogre pixel format that D3D11 can support - static PixelFormat _getClosestSupportedPF(PixelFormat ogrePF); - - static TextureType _getTexType(D3D11_SRV_DIMENSION type); - - static UINT _getTextureBindFlags(DXGI_FORMAT format, TextureUsage usage); - static UINT _getTextureMiscFlags(UINT bindflags, TextureType textype, TextureUsage usage); - }; -} -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11MultiRenderTarget.h b/RenderSystems/Direct3D11/include/OgreD3D11MultiRenderTarget.h deleted file mode 100644 index b81ef72038e..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11MultiRenderTarget.h +++ /dev/null @@ -1,64 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11MULTIRENDERTARGET_H__ -#define __D3D11MULTIRENDERTARGET_H__ - -#include "OgreD3D11Prerequisites.h" -#include "OgreD3D11RenderTarget.h" -#include "OgreRenderTexture.h" - -namespace Ogre { - class _OgreD3D11Export D3D11MultiRenderTarget : public MultiRenderTarget, - public D3D11RenderTarget - { - public: - D3D11MultiRenderTarget(const String &name); - ~D3D11MultiRenderTarget(); - - virtual void update(void); - - virtual uint getNumberOfViews() const; - virtual ID3D11Texture2D* getSurface(uint index = 0) const; - virtual ID3D11RenderTargetView* getRenderTargetView(uint index = 0) const; - - bool requiresTextureFlipping() const { return false; } - private: - ID3D11RenderTargetView* mRenderTargetViews[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; // Store views to accelerate bind - uint mNumberOfViews; // Store number of views to accelerate bind - - virtual void bindSurfaceImpl(size_t attachment, RenderTexture *target); - virtual void unbindSurfaceImpl(size_t attachment); - - /** Check surfaces and update RenderTarget extent */ - void checkAndUpdate(); - - Ogre::RenderTexture* mRenderTargets[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; - }; -}; - -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11Plugin.h b/RenderSystems/Direct3D11/include/OgreD3D11Plugin.h deleted file mode 100644 index 9c08b4a7453..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11Plugin.h +++ /dev/null @@ -1,63 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11Plugin_H__ -#define __D3D11Plugin_H__ - -#include "OgrePlugin.h" -#include "OgreD3D11RenderSystem.h" - -namespace Ogre -{ - - /** Plugin instance for D3D11 Manager */ - class _OgreD3D11Export D3D11Plugin : public Plugin - { - public: - D3D11Plugin(); - - - /// @copydoc Plugin::getName - const String& getName() const; - - /// @copydoc Plugin::install - void install(); - - /// @copydoc Plugin::initialise - void initialise(); - - /// @copydoc Plugin::shutdown - void shutdown(); - - /// @copydoc Plugin::uninstall - void uninstall(); - protected: - D3D11RenderSystem* mRenderSystem; - }; -} - -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11Prerequisites.h b/RenderSystems/Direct3D11/include/OgreD3D11Prerequisites.h deleted file mode 100644 index f13d76829ee..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11Prerequisites.h +++ /dev/null @@ -1,158 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11PREREQUISITES_H__ -#define __D3D11PREREQUISITES_H__ - - - -#include "OgrePrerequisites.h" -#include "OgreComPtr.h" // too much resource leaks were caused without it by throwing constructors - -#include "OgreException.h" - -#ifdef OGRE_EXCEPT_EX -#undef OGRE_EXCEPT_EX -#endif - -#define OGRE_EXCEPT_EX(code, num, desc, src) throw Ogre::D3D11RenderingAPIException(num, desc, src, __FILE__, __LINE__) - -#define OGRE_CHECK_DX_ERROR(dxcall) \ -{ \ - HRESULT hr = dxcall; \ - if (FAILED(hr) || mDevice.isError()) \ - { \ - String desc = mDevice.getErrorDescription(hr); \ - throw Ogre::D3D11RenderingAPIException(hr, desc, __FUNCTION__, __FILE__, __LINE__); \ - } \ -} - -// some D3D commonly used macros -#define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } -#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } } -#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } - -#if defined(_WIN32_WINNT_WIN8) // Win8 SDK required to compile, will work on Windows 8 and Platform Update for Windows 7 -#define OGRE_D3D11_PROFILING 1 -#endif - -#undef NOMINMAX -#define NOMINMAX // required to stop windows.h screwing up std::min definition -#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT || OGRE_D3D11_PROFILING -#include -#else -#include -#endif - -#if __OGRE_WINRT_PHONE_80 -# include -#else -# include -# include -#endif - - #include - -namespace Ogre -{ - // typedefs to work with Direct3D 11 or 11.1 as appropriate -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - typedef ID3D11Device ID3D11DeviceN; - typedef ID3D11DeviceContext ID3D11DeviceContextN; - typedef ID3D11RasterizerState ID3D11RasterizerStateN; - typedef IDXGIFactory1 IDXGIFactoryN; - typedef IDXGIAdapter1 IDXGIAdapterN; - typedef IDXGIDevice1 IDXGIDeviceN; - typedef IDXGISwapChain IDXGISwapChainN; - typedef DXGI_SWAP_CHAIN_DESC DXGI_SWAP_CHAIN_DESC_N; -#elif OGRE_PLATFORM == OGRE_PLATFORM_WINRT - typedef ID3D11Device1 ID3D11DeviceN; - typedef ID3D11DeviceContext1 ID3D11DeviceContextN; - typedef ID3D11RasterizerState1 ID3D11RasterizerStateN; - typedef IDXGIFactory2 IDXGIFactoryN; - typedef IDXGIAdapter1 IDXGIAdapterN; // we don`t need IDXGIAdapter2 functionality - typedef IDXGIDevice2 IDXGIDeviceN; - typedef IDXGISwapChain1 IDXGISwapChainN; - typedef DXGI_SWAP_CHAIN_DESC1 DXGI_SWAP_CHAIN_DESC_N; -#endif - - // Predefine classes - class D3D11RenderSystem; - class D3D11RenderWindowBase; - class D3D11Texture; - class D3D11TextureManager; - class D3D11DepthBuffer; - class D3D11Driver; - class D3D11DriverList; - class D3D11VideoMode; - class D3D11VideoModeList; - class GpuProgramManager; - class D3D11HardwareBufferManager; - class D3D11HardwareIndexBuffer; - class D3D11HLSLProgramFactory; - class D3D11HLSLProgram; - class D3D11VertexDeclaration; - class D3D11Device; - class D3D11HardwareBuffer; - class D3D11HardwarePixelBuffer; - class D3D11RenderTarget; - - typedef SharedPtr D3D11HLSLProgramPtr; - typedef SharedPtr D3D11TexturePtr; - - //------------------------------------------- - // Windows setttings - //------------------------------------------- -#if (OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT) && !defined(OGRE_STATIC_LIB) -# ifdef OGRED3DENGINEDLL_EXPORTS -# define _OgreD3D11Export __declspec(dllexport) -# else -# if defined( __MINGW32__ ) -# define _OgreD3D11Export -# else -# define _OgreD3D11Export __declspec(dllimport) -# endif -# endif -#else -# define _OgreD3D11Export -#endif // OGRE_WIN32 - - class _OgreD3D11Export D3D11RenderingAPIException : public RenderingAPIException - { - int hresult; - public: - D3D11RenderingAPIException(int hr, const String& inDescription, const String& inSource, const char* inFile, long inLine) - : RenderingAPIException(hr, inDescription, inSource, inFile, inLine), hresult(hr) { - StringStream ss; - ss << fullDesc << " HRESULT=0x" << std::hex << hresult; - fullDesc = ss.str(); - } - - int getHResult() const { return hresult; } - }; -} -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11RenderSystem.h b/RenderSystems/Direct3D11/include/OgreD3D11RenderSystem.h deleted file mode 100644 index 065ce7ceead..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11RenderSystem.h +++ /dev/null @@ -1,331 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11RENDERSYSTEM_H__ -#define __D3D11RENDERSYSTEM_H__ - -#include "OgreD3D11Prerequisites.h" -#include "OgreRenderSystem.h" -#include "OgreD3D11Device.h" -#include "OgreD3D11DeviceResource.h" -#include "OgreD3D11Driver.h" -#include "OgreD3D11Mappings.h" - -namespace Ogre -{ - /** \addtogroup RenderSystems RenderSystems - * @{ - */ - /** \defgroup Direct3D11 Direct3D11 - * Implementation of DirectX11 as a rendering system. - * @{ - */ - /// Enable recognizing SM2.0 HLSL shaders. - /// (the same shader code could be used by many RenderSystems, directly or via Cg) - #define SUPPORT_SM2_0_HLSL_SHADERS 1 - - class D3D11DriverList; - class D3D11Driver; - class D3D11StereoDriverBridge; - - /** - Implementation of DirectX11 as a rendering system. - */ - class _OgreD3D11Export D3D11RenderSystem - : public RenderSystem - , protected D3D11DeviceResourceManager - { - private: - friend class D3D11Sampler; - Ogre::String mDriverName; // it`s hint rather than hard requirement, could be ignored if empty or device removed - D3D_DRIVER_TYPE mDriverType; // should be XXX_HARDWARE, XXX_SOFTWARE or XXX_WARP, never XXX_UNKNOWN or XXX_NULL - D3D_FEATURE_LEVEL mFeatureLevel; - D3D_FEATURE_LEVEL mMinRequestedFeatureLevel; - D3D_FEATURE_LEVEL mMaxRequestedFeatureLevel; - - /// Direct3D rendering device - D3D11Device mDevice; - - /// List of D3D drivers installed (video cards) - D3D11DriverList* mDriverList; - /// Currently active driver - D3D11Driver mActiveD3DDriver; - /// NVPerfHUD allowed? - bool mUseNVPerfHUD; - int mSwitchingFullscreenCounter; // Are we switching from windowed to fullscreen - - ID3D11DeviceN* createD3D11Device(D3D11Driver* d3dDriver, D3D_DRIVER_TYPE driverType, - D3D_FEATURE_LEVEL minFL, D3D_FEATURE_LEVEL maxFL, D3D_FEATURE_LEVEL* pFeatureLevel); - - D3D11DriverList* getDirect3DDrivers(bool refreshList = false); - void refreshD3DSettings(void); - void refreshFSAAOptions(void); - - void freeDevice(void); - void createDevice(); - - D3D11HardwareBufferManager* mHardwareBufferManager; - D3D11HLSLProgramFactory* mHLSLProgramFactory; - - size_t mLastVertexSourceCount; - - /// Internal method for populating the capabilities structure - RenderSystemCapabilities* createRenderSystemCapabilities() const; - /** See RenderSystem definition */ - void initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary); - - void convertVertexShaderCaps(RenderSystemCapabilities* rsc) const; - void convertPixelShaderCaps(RenderSystemCapabilities* rsc) const; - void convertGeometryShaderCaps(RenderSystemCapabilities* rsc) const; - void convertHullShaderCaps(RenderSystemCapabilities* rsc) const; - void convertDomainShaderCaps(RenderSystemCapabilities* rsc) const; - void convertComputeShaderCaps(RenderSystemCapabilities* rsc) const; - - bool checkVertexTextureFormats(void); - void detachRenderTargetImpl(const String& name); - - D3D11_BLEND_DESC mBlendDesc; - bool mBlendDescChanged; - - D3D11_RASTERIZER_DESC mRasterizerDesc; - bool mRasterizerDescChanged; - - UINT mStencilRef; - D3D11_DEPTH_STENCIL_DESC mDepthStencilDesc; - bool mDepthStencilDescChanged; - - PolygonMode mPolygonMode; - - D3D11_RECT mScissorRect; - - bool mReadBackAsTexture; - - D3D11HLSLProgram* mBoundVertexProgram; - D3D11HLSLProgram* mBoundFragmentProgram; - D3D11HLSLProgram* mBoundGeometryProgram; - D3D11HLSLProgram* mBoundTessellationHullProgram; - D3D11HLSLProgram* mBoundTessellationDomainProgram; - D3D11HLSLProgram* mBoundComputeProgram; - - ComPtr mDSTResView; - ComPtr mBoundBlendState; - ComPtr mBoundRasterizer; - ComPtr mBoundDepthStencilState; - ComPtr mBoundSamplerStates[OGRE_MAX_TEXTURE_LAYERS]; - size_t mBoundSamplerStatesCount; - - ID3D11ShaderResourceView * mBoundTextures[OGRE_MAX_TEXTURE_LAYERS]; - size_t mBoundTexturesCount; - - // List of class instances per shader stage - ID3D11ClassInstance* mClassInstances[6][8]; - - // Number of class instances per shader stage - UINT mNumClassInstances[6]; - - // Store created shader subroutines, to prevent creation and destruction every frame - typedef std::map ClassInstanceMap; - typedef std::map::iterator ClassInstanceIterator; - ClassInstanceMap mInstanceMap; - - /// structure holding texture unit settings for every stage - struct sD3DTextureStageDesc - { - /// texture - D3D11Texture *pTex; - ID3D11SamplerState *pSampler; - bool used; - } mTexStageDesc[OGRE_MAX_TEXTURE_LAYERS]; - - size_t mLastTextureUnitState; - bool mSamplerStatesChanged; - - - - /// Primary window, the one used to create the device - D3D11RenderWindowBase* mPrimaryWindow; - - typedef std::vector SecondaryWindowList; - // List of additional windows after the first (swap chains) - SecondaryWindowList mSecondaryWindows; - - bool mRenderSystemWasInited; - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - D3D11StereoDriverBridge* mStereoDriver; -#endif - -#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT - Windows::Foundation::EventRegistrationToken suspendingToken, surfaceContentLostToken; -#endif - - protected: - /** - * With DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL flag render target views are unbound - * from us each Present(), and we need the way to reestablish connection. - */ - void _setRenderTargetViews(); - - public: - // constructor - D3D11RenderSystem( ); - - // destructor - ~D3D11RenderSystem(); - - - int getSwitchingFullscreenCounter() const { return mSwitchingFullscreenCounter; } - void addToSwitchingFullscreenCounter() { mSwitchingFullscreenCounter++; } - - void initRenderSystem(); - - virtual void initConfigOptions(void); - - // Overridden RenderSystem functions - String validateConfigOptions(void); - void _initialise() override; - /// @copydoc RenderSystem::_createRenderWindow - RenderWindow* _createRenderWindow(const String &name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams = 0); - /// @copydoc RenderSystem::_updateAllRenderTargets - virtual void _updateAllRenderTargets(bool swapBuffers = true); - /// @copydoc RenderSystem::_swapAllRenderTargetBuffers - virtual void _swapAllRenderTargetBuffers(); - - void fireDeviceEvent( D3D11Device* device, const String & name, D3D11RenderWindowBase* sendingWindow = NULL); - - /// @copydoc RenderSystem::createMultiRenderTarget - virtual MultiRenderTarget * createMultiRenderTarget(const String & name); - - virtual DepthBuffer* _createDepthBufferFor( RenderTarget *renderTarget ); - - /** - * This function is meant to add Depth Buffers to the pool that aren't released when the DepthBuffer - * is deleted. This is specially useful to put the Depth Buffer created along with the window's - * back buffer into the pool. All depth buffers introduced with this method go to POOL_DEFAULT - */ - DepthBuffer* _addManualDepthBuffer( ID3D11DepthStencilView *depthSurface, - uint32 width, uint32 height, uint32 fsaa, uint32 fsaaQuality ); - - /// Reverts _addManualDepthBuffer actions - void _removeManualDepthBuffer(DepthBuffer *depthBuffer); - /// @copydoc RenderSystem::detachRenderTarget - virtual RenderTarget * detachRenderTarget(const String &name); - - const String& getName(void) const; - - void getCustomAttribute(const String& name, void* pData); - // Low-level overridden members - /** - Specific options: - - | Key | Default | Description | - |-----|---------------|---------| - | Min Requested Feature Levels | 9.1 | Min D3D_FEATURE_LEVEL | - | Max Requested Feature Levels | 11.0 | Min D3D_FEATURE_LEVEL | - | Information Queue Exceptions Bottom Level | No information queue exceptions | Throw exception on message from validation layer | - | Driver type | Hardware | D3D_DRIVER_TYPE | - | Rendering Device | (default) | | - */ - void setConfigOption( const String &name, const String &value ); - void shutdown(); - void validateDevice(bool forceDeviceElection = false); - void handleDeviceLost(); - void destroyRenderTarget(const String& name); - void setStencilState(const StencilState& state) override; - - // Low-level overridden members, mainly for internal use - D3D11HLSLProgram* _getBoundVertexProgram() const; - D3D11HLSLProgram* _getBoundFragmentProgram() const; - D3D11HLSLProgram* _getBoundGeometryProgram() const; - D3D11HLSLProgram* _getBoundTessellationHullProgram() const; - D3D11HLSLProgram* _getBoundTessellationDomainProgram() const; - D3D11HLSLProgram* _getBoundComputeProgram() const; - void _setTexture(size_t unit, bool enabled, const TexturePtr &texPtr); - void _setSampler(size_t unit, Sampler& sampler); - void _setAlphaRejectSettings( CompareFunction func, unsigned char value, bool alphaToCoverage ); - void _setViewport( Viewport *vp ); - void _endFrame(void); - void _setCullingMode( CullingMode mode ); - void _setDepthClamp(bool enable); - void _setDepthBufferParams( bool depthTest = true, bool depthWrite = true, CompareFunction depthFunction = CMPF_LESS_EQUAL ); - void setColourBlendState(const ColourBlendState& state); - void _setDepthBias(float constantBias, float slopeScaleBias); - void _convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest, bool forGpuProgram = false); - void _setPolygonMode(PolygonMode level); - void setVertexDeclaration(VertexDeclaration* decl); - void setVertexDeclaration(VertexDeclaration* decl, VertexBufferBinding* binding); - void setVertexBufferBinding(VertexBufferBinding* binding); - void _dispatchCompute(const Vector3i& workgroupDim); - void _render(const RenderOperation& op); - - void bindGpuProgram(GpuProgram* prg); - - void unbindGpuProgram(GpuProgramType gptype); - - void bindGpuProgramParameters(GpuProgramType gptype, const GpuProgramParametersPtr& params, uint16 mask); - - void setScissorTest(bool enabled, const Rect& rect = Rect()); - void clearFrameBuffer(unsigned int buffers, - const ColourValue& colour = ColourValue::Black, - float depth = 1.0f, unsigned short stencil = 0); - HardwareOcclusionQuery* createHardwareOcclusionQuery(void); - Real getMinimumDepthInputValue(void); - Real getMaximumDepthInputValue(void); - - /** - * Set current render target to target, enabling its GL context if needed - */ - void _setRenderTarget(RenderTarget *target); - - void determineFSAASettings(uint fsaa, const String& fsaaHint, DXGI_FORMAT format, DXGI_SAMPLE_DESC* outFSAASettings); - - D3D11Device &_getDevice() { return mDevice; } - - - D3D_FEATURE_LEVEL _getFeatureLevel() const { return mFeatureLevel; } - - void setSubroutine(GpuProgramType gptype, unsigned int slotIndex, const String& subroutineName); - - void setSubroutine(GpuProgramType gptype, const String& slotName, const String& subroutineName); - - /// @copydoc RenderSystem::beginProfileEvent - virtual void beginProfileEvent( const String &eventName ); - - /// @copydoc RenderSystem::endProfileEvent - virtual void endProfileEvent( void ); - - /// @copydoc RenderSystem::markProfileEvent - virtual void markProfileEvent( const String &eventName ); - - /// @copydoc RenderSystem::setDrawBuffer - virtual bool setDrawBuffer(ColourBufferType colourBuffer); - }; - /** @} */ - /** @} */ -} -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11RenderTarget.h b/RenderSystems/Direct3D11/include/OgreD3D11RenderTarget.h deleted file mode 100644 index 1670a987466..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11RenderTarget.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef __D3D11RENDERTARGET_H__ -#define __D3D11RENDERTARGET_H__ - -#include "OgreD3D11Prerequisites.h" - -namespace Ogre -{ - class D3D11RenderTarget - { - public: - virtual ~D3D11RenderTarget() {} - - virtual uint getNumberOfViews() const = 0; - virtual ID3D11Texture2D* getSurface(uint index = 0) const = 0; - virtual ID3D11RenderTargetView* getRenderTargetView(uint index = 0) const = 0; - - protected: - D3D11RenderTarget() {} - }; - -} // namespace Ogre - -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11RenderToVertexBuffer.h b/RenderSystems/Direct3D11/include/OgreD3D11RenderToVertexBuffer.h deleted file mode 100644 index 20b570f1df9..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11RenderToVertexBuffer.h +++ /dev/null @@ -1,55 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11RenderToVertexBuffer_H__ -#define __D3D11RenderToVertexBuffer_H__ - -#include "OgreRenderToVertexBuffer.h" -#include "OgreD3D11Prerequisites.h" - -namespace Ogre { - class D3D11RenderToVertexBuffer : - public RenderToVertexBuffer - { - public: - D3D11RenderToVertexBuffer(D3D11Device & device, D3D11HardwareBufferManagerBase * bufManager); - virtual ~D3D11RenderToVertexBuffer(void); - - /** - Update the contents of this vertex buffer by rendering - */ - virtual void update(SceneManager* sceneMgr); - void reallocateBuffer(size_t index); - protected: - void setupGeometryShaderLinkageToStreamOut(Pass* pass); - - ID3D11GeometryShader* mpGeometryShader; - D3D11Device & mDevice; - D3D11HardwareBufferManagerBase * mBufManager; - }; -} -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11RenderWindow.h b/RenderSystems/Direct3D11/include/OgreD3D11RenderWindow.h deleted file mode 100644 index aa054d7c9c8..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11RenderWindow.h +++ /dev/null @@ -1,302 +0,0 @@ - -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11RENDERWINDOW_H__ -#define __D3D11RENDERWINDOW_H__ - -#include "OgreD3D11Prerequisites.h" -#include "OgreD3D11DeviceResource.h" -#include "OgreD3D11Mappings.h" -#include "OgreD3D11RenderTarget.h" -#include "OgreRenderWindow.h" - -#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT -#pragma warning( disable : 4451 ) // http://social.msdn.microsoft.com/Forums/en-US/winappswithnativecode/thread/314b5826-0a66-4307-abfe-87b8052c3c07/ - -# include -# if !__OGRE_WINRT_PHONE_80 -# include -# endif - -#endif - -namespace Ogre -{ - class _OgreD3D11Export D3D11RenderWindowBase - : public RenderWindow, public D3D11RenderTarget - , protected D3D11DeviceResource - { - public: - D3D11RenderWindowBase(D3D11Device& device); - ~D3D11RenderWindowBase(); - virtual void create(const String& name, unsigned widthPt, unsigned heightPt, bool fullScreen, const NameValuePairList *miscParams); - virtual void destroy(void); - - void resize(unsigned int width, unsigned int height) {} - /// @copydoc RenderTarget::setFSAA - virtual void setFSAA(uint fsaa, const String& fsaaHint) { mFSAA = fsaa; mFSAAHint = fsaaHint; resize(mWidth, mHeight); } - - bool isHidden() const { return mHidden; } - - virtual uint getNumberOfViews() const; - virtual ID3D11Texture2D* getSurface(uint index = 0) const; - virtual ID3D11RenderTargetView* getRenderTargetView(uint index = 0) const; - - void getCustomAttribute( const String& name, void* pData ); - /** Overridden - see RenderTarget. */ - virtual void copyContentsToMemory(const Box& src, const PixelBox &dst, FrameBuffer buffer); - bool requiresTextureFlipping() const { return false; } - - virtual bool _shouldRebindBackBuffer() { return false; } -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - /** Validate the type of stereo that is enabled for this window.*/ - void _validateStereo(); -#endif - - protected: - /** Overridden - see RenderTarget. */ - virtual void updateImpl(); - - virtual DXGI_FORMAT _getBasicFormat() { return DXGI_FORMAT_B8G8R8A8_UNORM; } // preferred since Win8 - DXGI_FORMAT _getRenderFormat() { return D3D11Mappings::_getGammaFormat(_getBasicFormat(), isHardwareGammaEnabled()); } - void _createSizeDependedD3DResources(); // assumes mpBackBuffer is already initialized - void _destroySizeDependedD3DResources(); - - ComPtr _queryDxgiDevice() { ComPtr res; _queryDxgiDeviceImpl(res.GetAddressOf()); return res; } - void _queryDxgiDeviceImpl(IDXGIDeviceN** dxgiDevice); // release after use - - void _updateViewportsDimensions(); - - protected: - D3D11Device & mDevice; // D3D11 driver - bool mIsExternal; // window not created by Ogre - bool mSizing; - bool mHidden; - - DXGI_SAMPLE_DESC mFSAAType; // Effective FSAA mode, limited by hardware capabilities - - // Window size depended resources - must be released before swapchain resize and recreated later - ComPtr mpBackBuffer; - ComPtr mpBackBufferNoMSAA; // optional, always holds up-to-date copy data from mpBackBuffer if not NULL - ComPtr mRenderTargetView; - ComPtr mDepthStencilView; - }; - - - class _OgreD3D11Export D3D11RenderWindowSwapChainBased - : public D3D11RenderWindowBase - { - public: - D3D11RenderWindowSwapChainBased(D3D11Device& device); - ~D3D11RenderWindowSwapChainBased() { destroy(); } - virtual void destroy(void); - - /// Get the swapchain details. - IDXGISwapChainN* _getSwapChain() { return mpSwapChain.Get(); } - DXGI_SWAP_CHAIN_DESC_N* _getSwapChainDescription(void) { return &mSwapChainDesc; } - virtual bool _shouldRebindBackBuffer() { return mUseFlipMode; } - - /// @copydoc RenderTarget::setFSAA - virtual void setFSAA(uint fsaa, const String& fsaaHint) { mFSAA = fsaa; mFSAAHint = fsaaHint; _changeBuffersFSAA(); } - - void setVSyncEnabled(bool vsync) { mVSync = vsync; } - bool isVSyncEnabled() const { return mVSync || mUseFlipMode; } - void setVSyncInterval(unsigned interval) { mVSyncInterval = interval; } - - void swapBuffers(); - void updateStats(void); - - protected: - void notifyDeviceLost(D3D11Device* device); - void notifyDeviceRestored(D3D11Device* device); - - DXGI_FORMAT _getSwapChainFormat() { return D3D11Mappings::_getGammaFormat(_getBasicFormat(), isHardwareGammaEnabled() && !mUseFlipMode); } - void _createSwapChain(); - virtual HRESULT _createSwapChainImpl(IDXGIDeviceN* pDXGIDevice) = 0; - void _destroySwapChain(); - void _changeBuffersFSAA(); - void _resizeSwapChainBuffers(unsigned width, unsigned height); - void _createSizeDependedD3DResources(); // obtains mpBackBuffer and optionally mpBackBufferNoMSAA, former can be from mpSwapChain or standalone - - int getVBlankMissCount(); - - protected: - // Pointer to swap chain - ComPtr mpSwapChain; - DXGI_SWAP_CHAIN_DESC_N mSwapChainDesc; - - bool mUseFlipMode; // Flag to determine if the swapchain flip model is enabled. Not supported before Win8.0, required for WinRT. - bool mVSync; // mVSync assumed to be true if mUseFlipMode - - DXGI_FRAME_STATISTICS mPreviousPresentStats; // We save the previous present stats - so we can detect a "vblank miss" - bool mPreviousPresentStatsIsValid; // Does mLastPresentStats data is valid (it isn't if when you start or resize the window) - uint mVBlankMissCount; // Number of times we missed the v sync blank - }; - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - - class _OgreD3D11Export D3D11RenderWindowHwnd - : public D3D11RenderWindowSwapChainBased - { - public: - D3D11RenderWindowHwnd(D3D11Device& device); - ~D3D11RenderWindowHwnd() { destroy(); } - virtual void create(const String& name, unsigned width, unsigned height, bool fullScreen, const NameValuePairList *miscParams); - virtual void destroy(void); - - bool isVisible() const; - void setHidden(bool hidden); - void reposition(int left, int top); - void resize(unsigned int width, unsigned int height); - void setFullscreen(bool fullScreen, unsigned int width, unsigned int height); - - // Method for dealing with resize / move & 3d library - void windowMovedOrResized(); - - HWND getWindowHandle() const { return mHWnd; } - DWORD getWindowStyle(bool fullScreen) const { return fullScreen ? mFullscreenWinStyle : mWindowedWinStyle; } - void getCustomAttribute( const String& name, void* pData ); - - void adjustWindow(unsigned int clientWidth, unsigned int clientHeight, unsigned int* winWidth, unsigned int* winHeight); - void updateWindowRect(); - void _beginUpdate(); - - protected: - void notifyDeviceRestored(D3D11Device* device); - - DXGI_FORMAT _getBasicFormat() { return DXGI_FORMAT_R8G8B8A8_UNORM; } // be compatible with pre-Win8 D3D11 - virtual HRESULT _createSwapChainImpl(IDXGIDeviceN* pDXGIDevice); - - /// Indicate that fullscreen / windowed switching has finished - void _finishSwitchingFullscreen(); - void setActive(bool state); - - protected: - HWND mHWnd; // Win32 window handle - DWORD mWindowedWinStyle; // Windowed mode window style flags. - DWORD mFullscreenWinStyle; // Fullscreen mode window style flags. - unsigned int mDesiredWidth; // Desired width after resizing - unsigned int mDesiredHeight; // Desired height after resizing - int mLastSwitchingFullscreenCounter;// the last value of the switching fullscreen counter when we switched - }; - -#endif - -#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT - - class _OgreD3D11Export D3D11RenderWindowCoreWindow - : public D3D11RenderWindowSwapChainBased - { - public: - D3D11RenderWindowCoreWindow(D3D11Device& device); - ~D3D11RenderWindowCoreWindow() { destroy(); } - - virtual float getViewPointToPixelScale(); - virtual void create(const String& name, unsigned widthPt, unsigned heightPt, bool fullScreen, const NameValuePairList *miscParams); - virtual void destroy(void); - - Windows::UI::Core::CoreWindow^ getCoreWindow() const { return mCoreWindow.Get(); } - - bool isVisible() const; - - // Method for dealing with resize / move & 3d library - void windowMovedOrResized(); - - protected: - virtual HRESULT _createSwapChainImpl(IDXGIDeviceN* pDXGIDevice); - - protected: - Platform::Agile mCoreWindow; - }; - -#if defined(_WIN32_WINNT_WINBLUE) && _WIN32_WINNT >= _WIN32_WINNT_WINBLUE - class _OgreD3D11Export D3D11RenderWindowSwapChainPanel - : public D3D11RenderWindowSwapChainBased - { - public: - D3D11RenderWindowSwapChainPanel(D3D11Device& device); - ~D3D11RenderWindowSwapChainPanel() { destroy(); } - - virtual float getViewPointToPixelScale(); - virtual void create(const String& name, unsigned widthPt, unsigned heightPt, bool fullScreen, const NameValuePairList *miscParams); - virtual void destroy(void); - - Windows::UI::Xaml::Controls::SwapChainPanel^ getSwapChainPanel() const { return mSwapChainPanel; } - - bool isVisible() const; - - // Method for dealing with resize / move & 3d library - void windowMovedOrResized(); - - protected: - virtual HRESULT _createSwapChainImpl(IDXGIDeviceN* pDXGIDevice); - HRESULT _compensateSwapChainCompositionScale(); - - protected: - Windows::UI::Xaml::Controls::SwapChainPanel^ mSwapChainPanel; - Windows::Foundation::Size mCompositionScale; - Windows::Foundation::EventRegistrationToken sizeChangedToken, compositionScaleChangedToken; - }; -#endif - -#if !__OGRE_WINRT_PHONE_80 - - class _OgreD3D11Export D3D11RenderWindowImageSource - : public D3D11RenderWindowBase - { - public: - D3D11RenderWindowImageSource(D3D11Device& device); - ~D3D11RenderWindowImageSource() { destroy(); } - virtual void create(const String& name, unsigned width, unsigned height, bool fullScreen, const NameValuePairList *miscParams); - virtual void destroy(void); - - virtual void resize(unsigned int width, unsigned int height); - virtual void update(bool swapBuffers = true); - virtual void swapBuffers(); - - virtual bool isVisible() const { return mImageSourceNative.Get() != NULL; } - - Windows::UI::Xaml::Media::ImageBrush^ getImageBrush() const { return mBrush; } - virtual void getCustomAttribute( const String& name, void* pData ); // "ImageBrush" -> Windows::UI::Xaml::Media::ImageBrush^ - - protected: - void notifyDeviceLost(D3D11Device* device); - void notifyDeviceRestored(D3D11Device* device); - void _createSizeDependedD3DResources(); // creates mpBackBuffer and optionally mpBackBufferNoMSAA - - protected: - Windows::UI::Xaml::Media::ImageBrush^ mBrush; // size independed - Windows::UI::Xaml::Media::Imaging::SurfaceImageSource^ mImageSource; // size depended, can be NULL - ComPtr mImageSourceNative; // size depended, can be NULL - }; -#endif // !__OGRE_WINRT_PHONE_80 - -#endif - -} -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11StereoDriverAMD.h b/RenderSystems/Direct3D11/include/OgreD3D11StereoDriverAMD.h deleted file mode 100644 index 4f1bc714aa7..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11StereoDriverAMD.h +++ /dev/null @@ -1,63 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreD3D11Prerequisites.h" - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 -#ifndef __D3D11StereoDriverAMD_H__ -#define __D3D11StereoDriverAMD_H__ - -#include "OgreD3D11StereoDriverImpl.h" -#include "AMDDxExtQbStereoApi.h" - -namespace Ogre { - - /** Virtual interface of the stereo driver*/ - class _OgreD3D11Export D3D11StereoDriverAMD : public D3D11StereoDriverImpl - { - // Interface - public: - D3D11StereoDriverAMD(); - virtual ~D3D11StereoDriverAMD(); - virtual bool addRenderWindow(D3D11RenderWindowBase* renderWindow); - virtual bool removeRenderWindow(const String& renderWindowName); - virtual bool isStereoEnabled(const String& renderWindowName); - virtual bool setDrawBuffer(ColourBufferType colourBuffer); - - protected: - typedef struct OgreStereoHandle - { - D3D11RenderWindowBase* renderWindow; - }; - - typedef std::map StereoHandleMap; - StereoHandleMap mStereoMap; - }; -} -#endif -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11StereoDriverBridge.h b/RenderSystems/Direct3D11/include/OgreD3D11StereoDriverBridge.h deleted file mode 100644 index cec032a8469..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11StereoDriverBridge.h +++ /dev/null @@ -1,66 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreD3D11Prerequisites.h" - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 -#ifndef __D3D11StereoDriverBridge_H__ -#define __D3D11StereoDriverBridge_H__ - -#include "OgreCommon.h" -#include "OgreSingleton.h" -#include "OgreD3D11RenderWindow.h" - -namespace Ogre { - - class D3D11StereoDriverImpl; - typedef bool StereoModeType; - - /** Bridge interface from the render system to the stereo driver. Loads the - correct driver and forwards the methods to the stereo driver implementation.*/ - class _OgreD3D11Export D3D11StereoDriverBridge : public Singleton, public StereoDriverAlloc - { - public: - D3D11StereoDriverBridge(StereoModeType stereoMode); - virtual ~D3D11StereoDriverBridge(); - static D3D11StereoDriverBridge& getSingleton(void); - static D3D11StereoDriverBridge* getSingletonPtr(void); - StereoModeType getStereoMode() const; - bool addRenderWindow(D3D11RenderWindowBase* renderWindow) const; - bool removeRenderWindow(const String& renderWindowName) const; - bool isStereoEnabled(const String& renderWindowName) const; - bool setDrawBuffer(const ColourBufferType colourBuffer) const; - - protected: - bool mIsNvapiInitialized; - D3D11StereoDriverImpl* mPimpl; - StereoModeType mStereoMode; - }; -} -#endif -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11StereoDriverImpl.h b/RenderSystems/Direct3D11/include/OgreD3D11StereoDriverImpl.h deleted file mode 100644 index 94845fbc82c..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11StereoDriverImpl.h +++ /dev/null @@ -1,54 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreD3D11Prerequisites.h" - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 -#ifndef __D3D11StereoDriverImpl_H__ -#define __D3D11StereoDriverImpl_H__ - -#include "OgreCommon.h" -#include "OgreD3D11RenderWindow.h" - -namespace Ogre { - - /** Virtual interface of the stereo driver */ - class _OgreD3D11Export D3D11StereoDriverImpl : public ResourceAlloc - { - public: - D3D11StereoDriverImpl() {} - virtual ~D3D11StereoDriverImpl() {} - virtual bool addRenderWindow(D3D11RenderWindowBase* renderWindow) = 0; - virtual bool removeRenderWindow(const String& renderWindowName) = 0; - virtual bool isStereoEnabled(const String& renderWindowName) = 0; - virtual bool setDrawBuffer(ColourBufferType colourBuffer) = 0; - }; -} -#endif -#endif - diff --git a/RenderSystems/Direct3D11/include/OgreD3D11StereoDriverNVIDIA.h b/RenderSystems/Direct3D11/include/OgreD3D11StereoDriverNVIDIA.h deleted file mode 100644 index d1b1bc3b20c..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11StereoDriverNVIDIA.h +++ /dev/null @@ -1,70 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreD3D11Prerequisites.h" - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 -#ifndef __D3D11StereoDriverNVIDIA_H__ -#define __D3D11StereoDriverNVIDIA_H__ - -#include "OgreD3D11StereoDriverImpl.h" -#include "OgreD3D11Device.h" -#include "nvapi.h" - -namespace Ogre { - - /** Interface of the NVIDIA stereo driver */ - class _OgreD3D11Export D3D11StereoDriverNVIDIA : public D3D11StereoDriverImpl - { - // Interface - public: - D3D11StereoDriverNVIDIA(); - virtual ~D3D11StereoDriverNVIDIA(); - virtual bool addRenderWindow(D3D11RenderWindowBase* renderWindow); - virtual bool removeRenderWindow(const String& renderWindowName); - virtual bool isStereoEnabled(const String& renderWindowName); - virtual bool setDrawBuffer(ColourBufferType colourBuffer); - - protected: - bool logErrorMessage(NvAPI_Status nvStatus); - - typedef struct OgreStereoHandle - { - D3D11RenderWindowBase* renderWindow; - StereoHandle nvapiStereoHandle; - NvU8 isStereoOn; - }; - - typedef std::map StereoHandleMap; - StereoHandleMap mStereoMap; - NvU8 mStereoEnabled; - }; -} -#endif -#endif - diff --git a/RenderSystems/Direct3D11/include/OgreD3D11Texture.h b/RenderSystems/Direct3D11/include/OgreD3D11Texture.h deleted file mode 100644 index 4a3bd9fe49d..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11Texture.h +++ /dev/null @@ -1,159 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11TEXTURE_H__ -#define __D3D11TEXTURE_H__ - -#include "OgreD3D11Prerequisites.h" -#include "OgreD3D11Device.h" -#include "OgreD3D11DeviceResource.h" -#include "OgreD3D11RenderTarget.h" -#include "OgreTexture.h" -#include "OgreRenderTexture.h" -#include "OgreSharedPtr.h" - -namespace Ogre { - /** Specialisation of Texture for D3D11 */ - class _OgreD3D11Export D3D11Texture - : public Texture - , protected D3D11DeviceResource - { - public: - /// constructor - D3D11Texture(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - D3D11Device & device); - /// destructor - ~D3D11Texture(); - - /// overridden from Texture - void copyToTexture(TexturePtr& target); - - ID3D11Resource *getTextureResource() { assert(mpTex); return mpTex.Get(); } - /// retrieves a pointer to the actual texture - ID3D11ShaderResourceView *getSrvView() { assert(mpShaderResourceView); return mpShaderResourceView.Get(); } - D3D11_SHADER_RESOURCE_VIEW_DESC getShaderResourceViewDesc() const { return mSRVDesc; } - - ID3D11Texture1D * GetTex1D() { return mp1DTex.Get(); }; - ID3D11Texture2D * GetTex2D() { return mp2DTex.Get(); }; - ID3D11Texture3D * GetTex3D() { return mp3DTex.Get(); }; - - bool HasAutoMipMapGenerationEnabled() const { return mAutoMipMapGeneration; } - - void createShaderAccessPoint(uint bindPoint, TextureAccess access = TA_READ_WRITE, - int mipmapLevel = 0, int textureArrayIndex = 0, - PixelFormat format = PF_UNKNOWN) override; - - ID3D11UnorderedAccessView* getUavView() const { return mpUnorderedAccessView.Get(); } - protected: - TextureUsage _getTextureUsage() { return static_cast(mUsage); } - - protected: - template - void _queryInterface(const ComPtr& from, ComPtr *to) - { - HRESULT hr = from.As(to); - - if(FAILED(hr) || mDevice.isError()) - { - this->unloadImpl(); - String errorDescription = mDevice.getErrorDescription(hr); - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, "Can't get base texture\nError Description:" + errorDescription, - "D3D11Texture::_queryInterface" ); - } - } - void _create1DResourceView(); - void _create2DResourceView(); - void _create3DResourceView(); - - /// internal method, create a blank normal 1D Dtexture - void _create1DTex(); - /// internal method, create a blank normal 2D texture - void _create2DTex(); - /// internal method, create a blank cube texture - void _create3DTex(); - - /// @copydoc Texture::createInternalResourcesImpl - void createInternalResourcesImpl(void); - /// free internal resources - void freeInternalResourcesImpl(void); - /// internal method, set Texture class final texture protected attributes - void _setFinalAttributes(unsigned long width, unsigned long height, unsigned long depth, PixelFormat format, UINT miscflags); - - /// internal method, create D3D11HardwarePixelBuffers for every face and - /// mipmap level. This method must be called after the D3D texture object was created - void _createSurfaceList(void); - - void notifyDeviceLost(D3D11Device* device); - void notifyDeviceRestored(D3D11Device* device); - - protected: - D3D11Device& mDevice; - - DXGI_FORMAT mD3DFormat; // Effective pixel format, already gamma corrected if requested - DXGI_SAMPLE_DESC mFSAAType; // Effective FSAA mode, limited by hardware capabilities - - // device depended resources - ComPtr mpTex; // actual texture - ComPtr mpShaderResourceView; - ComPtr mp1DTex; - ComPtr mp2DTex; - ComPtr mp3DTex; - - ComPtr mpUnorderedAccessView; - - D3D11_SHADER_RESOURCE_VIEW_DESC mSRVDesc; - bool mAutoMipMapGeneration; - }; - - /// RenderTexture implementation for D3D11 - class _OgreD3D11Export D3D11RenderTexture - : public RenderTexture, public D3D11RenderTarget - , protected D3D11DeviceResource - { - D3D11Device & mDevice; - ComPtr mRenderTargetView; - public: - D3D11RenderTexture(const String &name, D3D11HardwarePixelBuffer *buffer, uint32 zoffset, D3D11Device & device); - virtual ~D3D11RenderTexture(); - - void rebind(D3D11HardwarePixelBuffer *buffer); - - virtual uint getNumberOfViews() const; - virtual ID3D11Texture2D* getSurface(uint index = 0) const; - virtual ID3D11RenderTargetView* getRenderTargetView(uint index = 0) const; - - bool requiresTextureFlipping() const { return false; } - - protected: - void notifyDeviceLost(D3D11Device* device); - void notifyDeviceRestored(D3D11Device* device); - }; - -} - -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11TextureManager.h b/RenderSystems/Direct3D11/include/OgreD3D11TextureManager.h deleted file mode 100644 index 06c1b8e910e..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11TextureManager.h +++ /dev/null @@ -1,65 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11TEXTUREMANAGER_H__ -#define __D3D11TEXTUREMANAGER_H__ - -#include "OgreD3D11Prerequisites.h" -#include "OgreTextureManager.h" - -namespace Ogre -{ - class _OgreD3D11Export D3D11Sampler : public Sampler - { - public: - D3D11Sampler(D3D11Device & device) : mDevice(device) {} - ID3D11SamplerState* getState(); - private: - ComPtr mState; - D3D11Device & mDevice; - }; - - class _OgreD3D11Export D3D11TextureManager : public TextureManager - { - protected: - D3D11Device & mDevice; - /// @copydoc ResourceManager::createImpl - Resource* createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams); - - SamplerPtr _createSamplerImpl(); - - public: - D3D11TextureManager( D3D11Device & device ); - ~D3D11TextureManager(); - - /// @copydoc TextureManager::getNativeFormat - PixelFormat getNativeFormat(TextureType ttype, PixelFormat format, int usage); - }; -} -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11VertexDeclaration.h b/RenderSystems/Direct3D11/include/OgreD3D11VertexDeclaration.h deleted file mode 100644 index 2eb3cc710cf..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11VertexDeclaration.h +++ /dev/null @@ -1,73 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11VERTEXDECLARATION_H__ -#define __D3D11VERTEXDECLARATION_H__ - -#include "OgreD3D11Prerequisites.h" -#include "OgreD3D11DeviceResource.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreHighLevelGpuProgramManager.h" - -namespace Ogre { - - /** Specialisation of VertexDeclaration for D3D11 */ - class _OgreD3D11Export D3D11VertexDeclaration - : public VertexDeclaration - , protected D3D11DeviceResource - { - protected: - D3D11Device & mlpD3DDevice; - - typedef std::map> ShaderToILayoutMap; - typedef ShaderToILayoutMap::iterator ShaderToILayoutMapIterator; - typedef std::map> ShaderToInputDesc; - typedef ShaderToInputDesc::iterator ShaderToInputDescIterator; - - ShaderToInputDesc mD3delems; - - ShaderToILayoutMap mShaderToILayoutMap; - - /** Gets the D3D11-specific vertex declaration. */ - ID3D11InputLayout * getILayoutByShader(D3D11HLSLProgram* boundVertexProgram, VertexBufferBinding* binding); - D3D11_INPUT_ELEMENT_DESC * getD3DVertexDeclaration(D3D11HLSLProgram* boundVertexProgram, VertexBufferBinding* binding); - void clearCache(); - - void notifyDeviceLost(D3D11Device* device); - void notifyDeviceRestored(D3D11Device* device); - - void notifyChanged(); - public: - D3D11VertexDeclaration(D3D11Device & device); - ~D3D11VertexDeclaration(); - - void bindToShader(D3D11HLSLProgram* boundVertexProgram, VertexBufferBinding* binding); - }; - -} - -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11VideoMode.h b/RenderSystems/Direct3D11/include/OgreD3D11VideoMode.h deleted file mode 100644 index 359db77a964..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11VideoMode.h +++ /dev/null @@ -1,60 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11VIDEOMODE_H__ -#define __D3D11VIDEOMODE_H__ - -#include "OgreD3D11Prerequisites.h" - -namespace Ogre -{ - static unsigned int modeCount = 0; - - class _OgreD3D11Export D3D11VideoMode - { - private: - DXGI_OUTPUT_DESC mDisplayMode; - DXGI_MODE_DESC mModeDesc; - unsigned int modeNumber; - - public: - D3D11VideoMode(); - D3D11VideoMode( const D3D11VideoMode &ob ); - D3D11VideoMode( DXGI_OUTPUT_DESC d3ddm,DXGI_MODE_DESC ModeDesc ); - ~D3D11VideoMode(); - - unsigned int getWidth() const; - unsigned int getHeight() const; - DXGI_FORMAT getFormat() const; - DXGI_RATIONAL getRefreshRate() const; - DXGI_OUTPUT_DESC getDisplayMode() const; - DXGI_MODE_DESC getModeDesc() const; - void increaseRefreshRate(DXGI_RATIONAL rr); - String getDescription() const; - }; -} -#endif diff --git a/RenderSystems/Direct3D11/include/OgreD3D11VideoModeList.h b/RenderSystems/Direct3D11/include/OgreD3D11VideoModeList.h deleted file mode 100644 index 4f80714431e..00000000000 --- a/RenderSystems/Direct3D11/include/OgreD3D11VideoModeList.h +++ /dev/null @@ -1,48 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D11VIDEOMODELIST_H__ -#define __D3D11VIDEOMODELIST_H__ - -#include "OgreD3D11Prerequisites.h" - - -namespace Ogre -{ - class _OgreD3D11Export D3D11VideoModeList - { - std::vector mModeList; - - public: - D3D11VideoModeList(IDXGIAdapterN* pAdapter); - - size_t count(); - D3D11VideoMode* item( size_t index ); - D3D11VideoMode* item( const String &name ); - }; -} -#endif diff --git a/RenderSystems/Direct3D11/include/OgreMonitorInfo.h b/RenderSystems/Direct3D11/include/OgreMonitorInfo.h deleted file mode 100644 index 80f49ac4430..00000000000 --- a/RenderSystems/Direct3D11/include/OgreMonitorInfo.h +++ /dev/null @@ -1,31 +0,0 @@ -#ifndef __OGREMONITORINFO_H__ -#define __OGREMONITORINFO_H__ -#include "OgreD3D11Prerequisites.h" - -namespace Ogre -{ -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - class _OgreD3D11Export MonitorInfo - { - public : - MonitorInfo() : mCurrentMonitor(0) {} - void Refresh(); - - unsigned short getMonitorSequentialNumberFromHMonitor(HMONITOR hMonitor, bool allowRefresh = false); - unsigned short getMonitorSequentialNumberFromSwapChain(IDXGISwapChain* swapChain, bool allowRefresh = false); - - private: - typedef std::map MapMonitorToSequentialNumber; - MapMonitorToSequentialNumber mMapMonitors; - unsigned short mCurrentMonitor; - - static BOOL CALLBACK MonitorEnumProc( - _In_ HMONITOR hMonitor, - _In_ HDC hdcMonitor, - _In_ LPRECT lprcMonitor, - _In_ LPARAM dwData - ); - }; -#endif -} -#endif \ No newline at end of file diff --git a/RenderSystems/Direct3D11/include/OgreNsightChecker.h b/RenderSystems/Direct3D11/include/OgreNsightChecker.h deleted file mode 100644 index 5878fe37893..00000000000 --- a/RenderSystems/Direct3D11/include/OgreNsightChecker.h +++ /dev/null @@ -1,9 +0,0 @@ -#ifndef __NSIGHTCHECKER_H__ -#define __NSIGHTCHECKER_H__ - -namespace Ogre -{ - bool IsWorkingUnderNsight(); // caches result internally -} - -#endif diff --git a/RenderSystems/Direct3D11/src/OgreD3D11DepthBuffer.cpp b/RenderSystems/Direct3D11/src/OgreD3D11DepthBuffer.cpp deleted file mode 100644 index 85f5b978b2f..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11DepthBuffer.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11DepthBuffer.h" -#include "OgreD3D11HardwarePixelBuffer.h" -#include "OgreD3D11Texture.h" -#include "OgreD3D11Mappings.h" -#include "OgreD3D11RenderTarget.h" - -namespace Ogre -{ - D3D11DepthBuffer::D3D11DepthBuffer( uint16 poolId, D3D11RenderSystem *renderSystem, - ID3D11DepthStencilView *depthBufferView, - uint32 width, uint32 height, - uint32 fsaa, uint32 multiSampleQuality, bool isManual ) : - DepthBuffer( poolId, width, height, fsaa, isManual ), - mDepthStencilView( depthBufferView ), - mMultiSampleQuality( multiSampleQuality), - mRenderSystem(renderSystem) - { - } - - D3D11DepthBuffer::~D3D11DepthBuffer() - { - if( !mManual ) - mDepthStencilView->Release(); - mDepthStencilView = 0; - } - //--------------------------------------------------------------------- - bool D3D11DepthBuffer::isCompatible( RenderTarget *renderTarget ) const - { - D3D11_TEXTURE2D_DESC BBDesc; - - D3D11RenderTarget* d3d11RenderTarget = dynamic_cast(renderTarget); - if (!d3d11RenderTarget) - { - return false; - } - - ID3D11Texture2D* d3d11texture = d3d11RenderTarget->getSurface(); - if (!d3d11texture) - { - return false; - } - - d3d11texture->GetDesc(&BBDesc); - - //RenderSystem will determine if bitdepths match (i.e. 32 bit RT don't like 16 bit Depth) - //This is the same function used to create them. Note results are usually cached so this should - //be quick - - //TODO: Needs to check format too! - if( mFsaa == BBDesc.SampleDesc.Count && - mMultiSampleQuality == BBDesc.SampleDesc.Quality && - this->getWidth() == renderTarget->getWidth() && - this->getHeight() == renderTarget->getHeight() ) - { - return true; - } - - return false; - } - //--------------------------------------------------------------------- - ID3D11DepthStencilView* D3D11DepthBuffer::getDepthStencilView() const - { - return mDepthStencilView; - } - //--------------------------------------------------------------------- - void D3D11DepthBuffer::_resized(ID3D11DepthStencilView *depthBufferView, uint32 width, uint32 height) - { - mHeight = height; - mWidth = width; - - mDepthStencilView = depthBufferView; - } -} diff --git a/RenderSystems/Direct3D11/src/OgreD3D11Device.cpp b/RenderSystems/Direct3D11/src/OgreD3D11Device.cpp deleted file mode 100644 index 8131aa3e02f..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11Device.cpp +++ /dev/null @@ -1,329 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11Device.h" -#include "OgreException.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - D3D11Device::eExceptionsErrorLevel D3D11Device::mExceptionsErrorLevel = D3D11Device::D3D_NO_EXCEPTION; - //--------------------------------------------------------------------- - D3D11Device::D3D11Device() - { - mDriverVersion.QuadPart = 0; - } - //--------------------------------------------------------------------- - D3D11Device::~D3D11Device() - { - ReleaseAll(); - } - //--------------------------------------------------------------------- - void D3D11Device::ReleaseAll() - { - // Clear state - if (mImmediateContext) - { - mImmediateContext->ClearState(); - mImmediateContext->Flush(); - } -#if OGRE_D3D11_PROFILING - mPerf.Reset(); -#endif - mInfoQueue.Reset(); - mClassLinkage.Reset(); - mImmediateContext.Reset(); - mD3D11Device.Reset(); - mDXGIFactory.Reset(); - mDriverVersion.QuadPart = 0; - } - //--------------------------------------------------------------------- - void D3D11Device::TransferOwnership(ID3D11DeviceN* d3d11device) - { - assert(mD3D11Device.Get() != d3d11device); - ReleaseAll(); - - if (d3d11device) - { - HRESULT hr = S_OK; - - mD3D11Device.Attach(d3d11device); - - // get DXGI factory from device - ComPtr pDXGIDevice; - ComPtr pDXGIAdapter; - if(SUCCEEDED(mD3D11Device.As(&pDXGIDevice)) - && SUCCEEDED(pDXGIDevice->GetParent(__uuidof(IDXGIAdapterN), (void **)pDXGIAdapter.GetAddressOf()))) - { - pDXGIAdapter->GetParent(__uuidof(IDXGIFactoryN), (void **)mDXGIFactory.ReleaseAndGetAddressOf()); - - // We intentionally check for ID3D10Device support instead of ID3D11Device as CheckInterfaceSupport() is not supported for later. - // We hope, that there would be one UMD for both D3D10 and D3D11, or two different but with the same version number, - // or with different but correlated version numbers, so that blacklisting could be done with high confidence level. - if(FAILED(pDXGIAdapter->CheckInterfaceSupport(IID_ID3D10Device /* intentionally D3D10, not D3D11 */, &mDriverVersion))) - mDriverVersion.QuadPart = 0; - } - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - mD3D11Device->GetImmediateContext(mImmediateContext.ReleaseAndGetAddressOf()); -#elif OGRE_PLATFORM == OGRE_PLATFORM_WINRT - mD3D11Device->GetImmediateContext1(mImmediateContext.ReleaseAndGetAddressOf()); -#endif - -#if OGRE_D3D11_PROFILING - hr = mImmediateContext.As(&mPerf); - if(FAILED(hr) || !mPerf->GetStatus()) - mPerf.Reset(); -#endif - - hr = mD3D11Device.As(&mInfoQueue); - if (SUCCEEDED(hr)) - { - mInfoQueue->ClearStoredMessages(); - mInfoQueue->ClearRetrievalFilter(); - mInfoQueue->ClearStorageFilter(); - - D3D11_INFO_QUEUE_FILTER filter; - ZeroMemory(&filter, sizeof(D3D11_INFO_QUEUE_FILTER)); - std::vector severityList; - - switch(mExceptionsErrorLevel) - { - case D3D_NO_EXCEPTION: - severityList.push_back(D3D11_MESSAGE_SEVERITY_CORRUPTION); - case D3D_CORRUPTION: - severityList.push_back(D3D11_MESSAGE_SEVERITY_ERROR); - case D3D_ERROR: - severityList.push_back(D3D11_MESSAGE_SEVERITY_WARNING); - case D3D_WARNING: - case D3D_INFO: - severityList.push_back(D3D11_MESSAGE_SEVERITY_INFO); - default: - break; - } - - - if (severityList.size() > 0) - { - filter.DenyList.NumSeverities = severityList.size(); - filter.DenyList.pSeverityList = &severityList[0]; - } - - mInfoQueue->AddStorageFilterEntries(&filter); - mInfoQueue->AddRetrievalFilterEntries(&filter); - } - -#ifdef SUBROUTINES - // If feature level is 11, create class linkage - if (mD3D11Device->GetFeatureLevel() == D3D_FEATURE_LEVEL_11_0) - { - hr = mD3D11Device->CreateClassLinkage(mClassLinkage.ReleaseAndGetAddressOf()); - } -#endif - } - } - //--------------------------------------------------------------------- - void D3D11Device::throwIfFailed(HRESULT hr, const char* desc, const char* src) - { - if(FAILED(hr) || isError()) - { - String description = std::string(desc).append("\nError Description:").append(getErrorDescription(hr)); - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, description, src); - } - } - //--------------------------------------------------------------------- - String D3D11Device::getErrorDescription(const HRESULT lastResult /* = NO_ERROR */) const - { - if (!mD3D11Device) - { - return "NULL device"; - } - - if (D3D_NO_EXCEPTION == mExceptionsErrorLevel) - { - return "infoQ exceptions are turned off"; - } - - String res; - - switch (lastResult) - { - case NO_ERROR: - break; - case E_INVALIDARG: - res.append("invalid parameters were passed.\n"); - break; - default: - res = StringUtil::format("hr = 0x%08X\n", lastResult); - } - - if (mInfoQueue) - { - UINT64 numStoredMessages = mInfoQueue->GetNumStoredMessages(); - for (UINT64 i = 0 ; i < numStoredMessages ; i++ ) - { - // Get the size of the message - SIZE_T messageLength = 0; - mInfoQueue->GetMessage(i, NULL, &messageLength); - // Allocate space and get the message - D3D11_MESSAGE * pMessage = (D3D11_MESSAGE*)malloc(messageLength); - mInfoQueue->GetMessage(i, pMessage, &messageLength); - res = res + pMessage->pDescription + "\n"; - free(pMessage); - } - } - - return res; - } - //--------------------------------------------------------------------- - bool D3D11Device::_getErrorsFromQueue() const - { - if (mInfoQueue) - { - UINT64 numStoredMessages = mInfoQueue->GetNumStoredMessages(); - - if (D3D_INFO == mExceptionsErrorLevel && numStoredMessages > 0) - { - // if D3D_INFO we don't need to loop if the numStoredMessages > 0 - return true; - } - for (UINT64 i = 0 ; i < numStoredMessages ; i++ ) - { - // Get the size of the message - SIZE_T messageLength = 0; - mInfoQueue->GetMessage(i, NULL, &messageLength); - // Allocate space and get the message - D3D11_MESSAGE * pMessage = (D3D11_MESSAGE*)malloc(messageLength); - mInfoQueue->GetMessage(i, pMessage, &messageLength); - - bool res = false; - switch(pMessage->Severity) - { - case D3D11_MESSAGE_SEVERITY_CORRUPTION: - if (D3D_CORRUPTION == mExceptionsErrorLevel) - { - res = true; - } - break; - case D3D11_MESSAGE_SEVERITY_ERROR: - switch(mExceptionsErrorLevel) - { - case D3D_INFO: - case D3D_WARNING: - case D3D_ERROR: - res = true; - } - break; - case D3D11_MESSAGE_SEVERITY_WARNING: - switch(mExceptionsErrorLevel) - { - case D3D_INFO: - case D3D_WARNING: - res = true; - } - break; - } - - free(pMessage); - if (res) - { - // we don't need to loop anymore... - return true; - } - - } - - clearStoredErrorMessages(); - - return false; - - } - else - { - return false; - } - } - //--------------------------------------------------------------------- - void D3D11Device::clearStoredErrorMessages() const - { - if (mD3D11Device && D3D_NO_EXCEPTION != mExceptionsErrorLevel) - { - if (mInfoQueue) - { - mInfoQueue->ClearStoredMessages(); - } - } - } - //--------------------------------------------------------------------- - const D3D11Device::eExceptionsErrorLevel D3D11Device::getExceptionsErrorLevel() - { - return mExceptionsErrorLevel; - } - //--------------------------------------------------------------------- - void D3D11Device::setExceptionsErrorLevel( const eExceptionsErrorLevel exceptionsErrorLevel ) - { - mExceptionsErrorLevel = exceptionsErrorLevel; - } - //--------------------------------------------------------------------- - void D3D11Device::setExceptionsErrorLevel( const Ogre::String& exceptionsErrorLevel ) - { - eExceptionsErrorLevel onlyIfDebugMode = OGRE_DEBUG_MODE ? D3D11Device::D3D_ERROR : D3D11Device::D3D_NO_EXCEPTION; - if("No information queue exceptions" == exceptionsErrorLevel) setExceptionsErrorLevel(onlyIfDebugMode); - else if("Corruption" == exceptionsErrorLevel) setExceptionsErrorLevel(D3D11Device::D3D_CORRUPTION); - else if("Error" == exceptionsErrorLevel) setExceptionsErrorLevel(D3D11Device::D3D_ERROR); - else if("Warning" == exceptionsErrorLevel) setExceptionsErrorLevel(D3D11Device::D3D_WARNING); - else if("Info (exception on any message)" == exceptionsErrorLevel) setExceptionsErrorLevel(D3D11Device::D3D_INFO); - else setExceptionsErrorLevel(onlyIfDebugMode); - } - //--------------------------------------------------------------------- - D3D_FEATURE_LEVEL D3D11Device::parseFeatureLevel(const Ogre::String& value, D3D_FEATURE_LEVEL fallback) - { - if(value == "9.1") return D3D_FEATURE_LEVEL_9_1; - if(value == "9.2") return D3D_FEATURE_LEVEL_9_2; - if(value == "9.3") return D3D_FEATURE_LEVEL_9_3; - if(value == "10.0") return D3D_FEATURE_LEVEL_10_0; - if(value == "10.1") return D3D_FEATURE_LEVEL_10_1; - if(value == "11.0") return D3D_FEATURE_LEVEL_11_0; - return fallback; - } - //--------------------------------------------------------------------- - D3D_DRIVER_TYPE D3D11Device::parseDriverType(const Ogre::String& driverTypeName, D3D_DRIVER_TYPE fallback) - { - if("Hardware" == driverTypeName) return D3D_DRIVER_TYPE_HARDWARE; - if("Software" == driverTypeName) return D3D_DRIVER_TYPE_SOFTWARE; - if("Warp" == driverTypeName) return D3D_DRIVER_TYPE_WARP; - return fallback; - } - //--------------------------------------------------------------------- - bool D3D11Device::IsDeviceLost() - { - HRESULT hr = mD3D11Device->GetDeviceRemovedReason(); - if(FAILED(hr)) - return true; - return false; - } -} \ No newline at end of file diff --git a/RenderSystems/Direct3D11/src/OgreD3D11DeviceResource.cpp b/RenderSystems/Direct3D11/src/OgreD3D11DeviceResource.cpp deleted file mode 100644 index cfaded56e21..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11DeviceResource.cpp +++ /dev/null @@ -1,102 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2015 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11DeviceResource.h" - - -namespace Ogre -{ - D3D11DeviceResource::D3D11DeviceResource() - { - D3D11DeviceResourceManager::get()->notifyResourceCreated(this); - } - - D3D11DeviceResource::~D3D11DeviceResource() - { - D3D11DeviceResourceManager::get()->notifyResourceDestroyed(this); - } - - // ------------------------------------------------------------------------ - D3D11DeviceResourceManager* gs_D3D11DeviceResourceManager = NULL; - - D3D11DeviceResourceManager* D3D11DeviceResourceManager::get() - { - return gs_D3D11DeviceResourceManager; - } - - D3D11DeviceResourceManager::D3D11DeviceResourceManager() - { - assert(gs_D3D11DeviceResourceManager == NULL); - gs_D3D11DeviceResourceManager = this; - } - - D3D11DeviceResourceManager::~D3D11DeviceResourceManager() - { - OgreAssertDbg(mResources.empty(), - "Not all resources have been released! Are you holding on to a reference somewhere?"); - assert(gs_D3D11DeviceResourceManager == this); - gs_D3D11DeviceResourceManager = NULL; - } - - void D3D11DeviceResourceManager::notifyResourceCreated(D3D11DeviceResource* deviceResource) - { - assert(std::find(mResources.begin(), mResources.end(), deviceResource) == mResources.end()); - mResources.push_back(deviceResource); - } - - void D3D11DeviceResourceManager::notifyResourceDestroyed(D3D11DeviceResource* deviceResource) - { - std::vector::iterator it = std::find(mResources.begin(), mResources.end(), deviceResource); - assert(it != mResources.end()); - mResources.erase(it); - - std::vector::iterator itCopy = std::find(mResourcesCopy.begin(), mResourcesCopy.end(), deviceResource); - if(itCopy != mResourcesCopy.end()) - *itCopy = NULL; - } - - void D3D11DeviceResourceManager::notifyDeviceLost(D3D11Device* device) - { - assert(mResourcesCopy.empty()); // reentrancy is not expected nor supported - mResourcesCopy = mResources; - for(std::vector::iterator it = mResourcesCopy.begin(), it_end = mResourcesCopy.end(); it != it_end; ++it) - if(D3D11DeviceResource* deviceResource = *it) - deviceResource->notifyDeviceLost(device); - mResourcesCopy.clear(); - } - - void D3D11DeviceResourceManager::notifyDeviceRestored(D3D11Device* device) - { - assert(mResourcesCopy.empty()); // reentrancy is not expected nor supported - mResourcesCopy = mResources; - for(std::vector::iterator it = mResourcesCopy.begin(), it_end = mResourcesCopy.end(); it != it_end; ++it) - if(D3D11DeviceResource* deviceResource = *it) - deviceResource->notifyDeviceRestored(device); - mResourcesCopy.clear(); - } - -} diff --git a/RenderSystems/Direct3D11/src/OgreD3D11Driver.cpp b/RenderSystems/Direct3D11/src/OgreD3D11Driver.cpp deleted file mode 100644 index 6a9d1f1b28f..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11Driver.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11Driver.h" -#include "OgreD3D11VideoModeList.h" -#include "OgreD3D11VideoMode.h" -#include "OgreD3D11Device.h" -#include "OgreString.h" -#include "OgreStringConverter.h" - -#ifndef DXGI_ADAPTER_FLAG_SOFTWARE -#define DXGI_ADAPTER_FLAG_SOFTWARE 2 // unavailable in June 2010 SDK -#endif - -namespace Ogre -{ - //--------------------------------------------------------------------- - D3D11Driver::D3D11Driver() - { - ZeroMemory( &mAdapterIdentifier, sizeof(mAdapterIdentifier) ); - mSameNameAdapterIndex = 0; - } - //--------------------------------------------------------------------- - D3D11Driver::D3D11Driver(IDXGIAdapterN* pDXGIAdapter, const DXGI_ADAPTER_DESC1& desc, unsigned sameNameIndex) - { - mDXGIAdapter = pDXGIAdapter; - mAdapterIdentifier = desc; - mSameNameAdapterIndex = sameNameIndex; - } - //--------------------------------------------------------------------- - D3D11Driver::~D3D11Driver() - { - } - //--------------------------------------------------------------------- - String D3D11Driver::DriverDescription() const - { - char str[sizeof(mAdapterIdentifier.Description) + 1]; - wcstombs(str, mAdapterIdentifier.Description, sizeof(str) - 1); - str[sizeof(str) - 1] = '\0'; - String driverDescription=str; - StringUtil::trim(driverDescription); - if(mAdapterIdentifier.VendorId == 0x1414 && mAdapterIdentifier.DeviceId == 0x8c && (mAdapterIdentifier.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) - driverDescription += " (software)"; // It`s software only variation of "Microsoft Basic Render Driver", always present since Win8 - else if(mSameNameAdapterIndex != 0) - driverDescription += " (" + Ogre::StringConverter::toString(mSameNameAdapterIndex + 1) + ")"; - - return driverDescription; - } - //--------------------------------------------------------------------- - D3D11VideoModeList* D3D11Driver::getVideoModeList() - { - if(!mVideoModeList) - mVideoModeList = std::make_shared(getDeviceAdapter()); - - return mVideoModeList.get(); - } - //--------------------------------------------------------------------- - const DXGI_ADAPTER_DESC1& D3D11Driver::getAdapterIdentifier() const - { - return mAdapterIdentifier; - } - //--------------------------------------------------------------------- - IDXGIAdapterN* D3D11Driver::getDeviceAdapter() const - { - return mDXGIAdapter.Get(); - } - //--------------------------------------------------------------------- -} diff --git a/RenderSystems/Direct3D11/src/OgreD3D11DriverList.cpp b/RenderSystems/Direct3D11/src/OgreD3D11DriverList.cpp deleted file mode 100644 index 2274c6194ff..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11DriverList.cpp +++ /dev/null @@ -1,151 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11DriverList.h" -#include "OgreD3D11Device.h" -#include "OgreD3D11Driver.h" -#include "OgreException.h" -#include "OgreLogManager.h" - -namespace Ogre -{ - //----------------------------------------------------------------------- - D3D11DriverList::D3D11DriverList() - { - mHiddenDriversCount = 0; - } - //----------------------------------------------------------------------- - D3D11DriverList::~D3D11DriverList(void) - { - } - //----------------------------------------------------------------------- - void D3D11DriverList::clear() - { - mHiddenDriversCount = 0; - mDriverList.clear(); - } - //----------------------------------------------------------------------- - void D3D11DriverList::refresh() - { - clear(); - std::map sameNameCounter; - - LogManager::getSingleton().logMessage( "D3D11: Driver Detection Starts" ); - - // We need fresh IDXGIFactory to get fresh driver list - ComPtr pDXGIFactory; - HRESULT hr = CreateDXGIFactory1(__uuidof(IDXGIFactoryN), (void**)pDXGIFactory.GetAddressOf()); - if( FAILED(hr) ) - { - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Failed to create Direct3D11 DXGIFactory1", - "D3D11DriverList::refresh"); - } - - for( UINT iAdapter=0; ; iAdapter++ ) - { - ComPtr pDXGIAdapter; - HRESULT hr = pDXGIFactory->EnumAdapters1(iAdapter, pDXGIAdapter.GetAddressOf()); - if( DXGI_ERROR_NOT_FOUND == hr ) - { - hr = S_OK; - break; - } - if( FAILED(hr) ) - { - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Failed to enum adapters", - "D3D11DriverList::refresh"); - } - - DXGI_ADAPTER_DESC1 desc1 = {0}; - hr = pDXGIAdapter->GetDesc1(&desc1); - if( FAILED(hr) ) - { - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Failed to get adapter description", - "D3D11DriverList::refresh"); - } - - unsigned sameNameIndex = sameNameCounter[std::wstring(desc1.Description)]++; - - auto driver = std::make_shared(pDXGIAdapter.Get(), desc1, sameNameIndex); - - LogManager::getSingleton().logMessage("D3D11: \"" + driver->DriverDescription() + "\""); - - // we don't want NVIDIA PerfHUD in the list, so place it to the hidden part of drivers list - const bool isHidden = wcscmp(driver->getAdapterIdentifier().Description, L"NVIDIA PerfHUD") == 0; - if(isHidden) - { - mDriverList.push_back(driver); - ++mHiddenDriversCount; - } - else - { - mDriverList.insert(mDriverList.end() - mHiddenDriversCount, driver); - } - } - - LogManager::getSingleton().logMessage( "D3D11: Driver Detection Ends" ); - } - //----------------------------------------------------------------------- - size_t D3D11DriverList::count() const - { - return mDriverList.size() - mHiddenDriversCount; - } - //----------------------------------------------------------------------- - D3D11Driver* D3D11DriverList::item( size_t index ) - { - return mDriverList.at( index ).get(); - } - //----------------------------------------------------------------------- - D3D11Driver* D3D11DriverList::item( const String &name ) - { - for(std::vector >::iterator it = mDriverList.begin(), it_end = mDriverList.end(); it != mDriverList.end(); ++it) - { - if((*it)->DriverDescription() == name) - return (*it).get(); - } - - return NULL; - } - //----------------------------------------------------------------------- - D3D11Driver* D3D11DriverList::findByName(const String &name) - { - // return requested driver - if(!name.empty()) - if(D3D11Driver* driver = item(name)) - return driver; - - // return default driver - if(!mDriverList.empty()) - return mDriverList[0].get(); - - return NULL; - } - //----------------------------------------------------------------------- -} diff --git a/RenderSystems/Direct3D11/src/OgreD3D11EngineDll.cpp b/RenderSystems/Direct3D11/src/OgreD3D11EngineDll.cpp deleted file mode 100644 index 494f06524af..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11EngineDll.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreRoot.h" -#include "OgreD3D11Plugin.h" - -#ifndef OGRE_STATIC_LIB -namespace Ogre -{ - D3D11Plugin* plugin; - - extern "C" void _OgreD3D11Export dllStartPlugin(void) throw() - { - plugin = new D3D11Plugin(); - Root::getSingleton().installPlugin(plugin); - } - - extern "C" void _OgreD3D11Export dllStopPlugin(void) - { - Root::getSingleton().uninstallPlugin(plugin); - delete plugin; - } -} -#endif diff --git a/RenderSystems/Direct3D11/src/OgreD3D11HLSLProgram.cpp b/RenderSystems/Direct3D11/src/OgreD3D11HLSLProgram.cpp deleted file mode 100644 index edde3ef574f..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11HLSLProgram.cpp +++ /dev/null @@ -1,1713 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11HLSLProgram.h" -#include "OgreException.h" -#include "OgreRenderSystem.h" -#include "OgreD3D11Device.h" -#include "OgreRoot.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreD3D11Mappings.h" -#include "OgreGpuProgramManager.h" -#include "OgreHardwareBufferManager.h" -#include "OgreD3D11HardwareBuffer.h" -#include "OgreD3D11RenderSystem.h" -#include "OgreStringConverter.h" - -namespace Ogre { - //----------------------------------------------------------------------- - D3D11HLSLProgram::CmdTarget D3D11HLSLProgram::msCmdTarget; - D3D11HLSLProgram::CmdColumnMajorMatrices D3D11HLSLProgram::msCmdColumnMajorMatrices; - D3D11HLSLProgram::CmdEnableBackwardsCompatibility D3D11HLSLProgram::msCmdEnableBackwardsCompatibility; - //----------------------------------------------------------------------- - void D3D11HLSLProgram::notifyDeviceLost(D3D11Device* device) - { - if(mHighLevelLoaded) - unloadHighLevelImpl(); - } - //----------------------------------------------------------------------- - void D3D11HLSLProgram::notifyDeviceRestored(D3D11Device* device) - { - if(mHighLevelLoaded) - loadFromSource(); - } - //----------------------------------------------------------------------- - void D3D11HLSLProgram::prepareImpl() - { - HighLevelGpuProgram::prepareImpl(); - - mSyntaxCode = getCompatibleTarget(); - - uint32 hash = getNameForMicrocodeCache(); - if ( GpuProgramManager::getSingleton().isMicrocodeAvailableInCache(hash) ) - { - getMicrocodeFromCache(hash); - } - else - { - compileMicrocode(); - } - } - - void D3D11HLSLProgram::loadFromSource(void) - { - if(!mCompileError) - analizeMicrocode(); - } - //----------------------------------------------------------------------- - void D3D11HLSLProgram::getMicrocodeFromCache(uint32 id) - { - GpuProgramManager::Microcode cacheMicrocode = - GpuProgramManager::getSingleton().getMicrocodeFromCache(id); - - cacheMicrocode->seek(0); - -#define READ_START(curlist, memberType) { \ - uint16 listSize = (uint16)curlist.size(); \ - cacheMicrocode->read(&listSize, sizeof(uint16)); \ - if(listSize > 0){ \ - curlist.resize(listSize); \ - for(unsigned i = 0 ; i < curlist.size() ; i++){ \ - memberType & curItem = curlist[i]; - -#define READ_END }}} - -#define READ_UINT(member) { \ - uint32 tmpVal; \ - cacheMicrocode->read(&tmpVal, sizeof(uint32)); \ - curItem.member = tmpVal; \ - } - -#define READ_ENUM(member, enumType) { \ - uint32 tmpVal; \ - cacheMicrocode->read(&tmpVal, sizeof(uint32)); \ - curItem.member = (enumType)tmpVal; \ - } - -#define READ_BYTE(member) { \ - cacheMicrocode->read(&curItem.member, sizeof(BYTE)); \ - } - -#define READ_NAME(member) { \ - uint16 length = 0; \ - cacheMicrocode->read(&length, sizeof(uint16)); \ - curItem.member = ""; \ - if(length > 0) \ - { \ - String * inString = new String(); \ - inString->resize(length); \ - cacheMicrocode->read(&(*inString)[0], length); \ - mSerStrings.push_back(inString); \ - curItem.member = &(*inString)[0]; \ - } \ - } - -#define READ_NAME2(member) { \ - uint16 length = 0; \ - cacheMicrocode->read(&length, sizeof(uint16)); \ - if(length > 0) \ - { \ - curItem.member.resize(length); \ - cacheMicrocode->read(&(curItem.member[0]), length); \ - } \ - } - - uint32 microCodeSize = 0; - cacheMicrocode->read(µCodeSize, sizeof(uint32)); - mMicroCode.resize(microCodeSize); - cacheMicrocode->read(&mMicroCode[0], microCodeSize); - - cacheMicrocode->read(&mConstantBufferSize, sizeof(uint32)); - cacheMicrocode->read(&mConstantBufferNr, sizeof(uint32)); - cacheMicrocode->read(&mNumSlots, sizeof(uint32)); - - READ_START(mD3d11ShaderInputParameters, D3D11_SIGNATURE_PARAMETER_DESC) - READ_NAME(SemanticName) - READ_UINT(SemanticIndex) - READ_UINT(Register) - READ_ENUM(SystemValueType,D3D_NAME) - READ_ENUM(ComponentType, D3D_REGISTER_COMPONENT_TYPE) - READ_BYTE(Mask) - READ_BYTE(ReadWriteMask) - READ_UINT(Stream) -// READ_ENUM(MinPrecision, D3D_MIN_PRECISION) // not needed and doesn't exist in June 2010 SDK - READ_END - - READ_START(mD3d11ShaderOutputParameters, D3D11_SIGNATURE_PARAMETER_DESC) - READ_NAME(SemanticName) - READ_UINT(SemanticIndex) - READ_UINT(Register) - READ_ENUM(SystemValueType, D3D_NAME) - READ_ENUM(ComponentType, D3D_REGISTER_COMPONENT_TYPE) - READ_BYTE(Mask) - READ_BYTE(ReadWriteMask) - READ_UINT(Stream) -// READ_ENUM(MinPrecision, D3D_MIN_PRECISION) // not needed and doesn't exist in June 2010 SDK - READ_END - - READ_START(mD3d11ShaderVariables, D3D11_SHADER_VARIABLE_DESC) - READ_NAME(Name) - READ_UINT(StartOffset) - READ_UINT(Size) - READ_UINT(uFlags) - //todo DefaultValue - READ_UINT(StartTexture) - READ_UINT(TextureSize) - READ_UINT(StartSampler) - READ_UINT(SamplerSize) - READ_END - - READ_START(mD3d11ShaderVariableSubparts, GpuConstantDefinitionWithName) - READ_NAME2(Name) - READ_ENUM(constType, GpuConstantType) - READ_UINT(physicalIndex) - READ_UINT(logicalIndex) - READ_UINT(elementSize) - READ_UINT(arraySize) - READ_UINT(variability) - READ_END - - READ_START(mD3d11ShaderBufferDescs, D3D11_SHADER_BUFFER_DESC) - READ_NAME(Name) - READ_ENUM(Type, D3D_CBUFFER_TYPE) - READ_UINT(Variables) - READ_UINT(Size) - READ_UINT(uFlags) - READ_END - - READ_START(mVarDescBuffer, D3D11_SHADER_VARIABLE_DESC) - READ_NAME(Name) - READ_UINT(StartOffset) - READ_UINT(Size) - READ_UINT(uFlags) - //todo DefaultValue - READ_UINT(StartTexture) - READ_UINT(TextureSize) - READ_UINT(StartSampler) - READ_UINT(SamplerSize) - READ_END - - READ_START(mVarDescPointer, D3D11_SHADER_VARIABLE_DESC) - READ_NAME(Name) - READ_UINT(StartOffset) - READ_UINT(Size) - READ_UINT(uFlags) - //todo DefaultValue - READ_UINT(StartTexture) - READ_UINT(TextureSize) - READ_UINT(StartSampler) - READ_UINT(SamplerSize) - READ_END - - READ_START(mD3d11ShaderTypeDescs, D3D11_SHADER_TYPE_DESC) - READ_NAME(Name) - READ_ENUM(Type, D3D_SHADER_VARIABLE_TYPE) - READ_UINT(Rows) - READ_UINT(Columns) - READ_UINT(Elements) - READ_UINT(Members) - READ_UINT(Offset) - READ_END - - READ_START(mMemberTypeDesc, D3D11_SHADER_TYPE_DESC) - READ_NAME(Name) - READ_ENUM(Type, D3D_SHADER_VARIABLE_TYPE) - READ_UINT(Rows) - READ_UINT(Columns) - READ_UINT(Elements) - READ_UINT(Members) - READ_UINT(Offset) - READ_END - - READ_START(mMemberTypeName, MemberTypeName) - READ_NAME2(Name) - READ_END - - uint16 mInterfaceSlotsSize = 0; - cacheMicrocode->read(&mInterfaceSlotsSize, sizeof(uint16)); - if(mInterfaceSlotsSize > 0) - { - mInterfaceSlots.resize(mInterfaceSlotsSize); - cacheMicrocode->read(&mInterfaceSlots[0], mInterfaceSlotsSize * sizeof(UINT)); - } - } - //----------------------------------------------------------------------- - void D3D11HLSLProgram::compileMicrocode(void) - { - // If we are running from the cache, we should not be trying to compile/reflect on shaders. -#if defined(ENABLE_SHADERS_CACHE_LOAD) && (ENABLE_SHADERS_CACHE_LOAD == 1) - String message = "Cannot compile/reflect D3D11 shader: " + mName + " in shipping code\n"; - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, message, - "D3D11HLSLProgram::compileMicrocode"); -#else -#pragma comment(lib, "d3dcompiler.lib") - - String stringBuffer = appendBuiltinDefines(mPreprocessorDefines); - std::vector defines; - for(const auto& def : parseDefines(stringBuffer)) - { - defines.push_back({def.first, def.second}); - } - // Add NULL terminator - defines.push_back({0, 0}); - - UINT compileFlags=0; - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); -#if OGRE_DEBUG_MODE - compileFlags |= D3DCOMPILE_DEBUG; - // Skip optimization only if we have enough instruction slots (>=256) and not feature level 9 hardware - if (mSyntaxCode != "ps_2_0" && mSyntaxCode != "ps_4_0_level_9_1" && rsys->_getFeatureLevel() >= D3D_FEATURE_LEVEL_10_0) - compileFlags |= D3DCOMPILE_SKIP_OPTIMIZATION; -#else - compileFlags |= D3DCOMPILE_OPTIMIZATION_LEVEL3; -#endif - - if (mColumnMajorMatrices) - { - compileFlags |= D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR; - } - else - { - compileFlags |= D3DCOMPILE_PACK_MATRIX_ROW_MAJOR; - } - - if (mEnableBackwardsCompatibility) - { - compileFlags |= D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY; - } - - const char* target = mSyntaxCode.c_str(); - - ComPtr pMicroCode; - ComPtr errors; - - // handle includes - mSource = _resolveIncludes(mSource, this, mFilename, true); - - HRESULT hr = D3DCompile( - mSource.c_str(), // [in] Pointer to the shader in memory. - mSource.size(), // [in] Size of the shader in memory. - mFilename.c_str(), // [in] Optional. You can use this parameter for strings that specify error messages. - defines.data(), // [in] Optional. Pointer to a NULL-terminated array of macro definitions. See D3D_SHADER_MACRO. If not used, set this to NULL. - NULL, // [in] Optional. Pointer to an ID3DInclude Interface interface for handling include files. Setting this to NULL will cause a compile error if a shader contains a #include. - mEntryPoint.c_str(), // [in] Name of the shader-entrypoint function where shader execution begins. - target, // [in] A string that specifies the shader model; can be any profile in shader model 4 or higher. - compileFlags, // [in] Effect compile flags - no D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY at the first try... - NULL, // [in] Effect compile flags - pMicroCode.GetAddressOf(),// [out] A pointer to an ID3DBlob Interface which contains the compiled shader, as well as any embedded debug and symbol-table information. - errors.GetAddressOf() // [out] A pointer to an ID3DBlob Interface which contains a listing of errors and warnings that occurred during compilation. These errors and warnings are identical to the the debug output from a debugger. - ); - -#if 0 // this is how you disassemble - LPCSTR commentString = NULL; - ComPtr pIDisassembly; - const char* pDisassembly = NULL; - if( pMicroCode ) - { - D3DDisassemble( (UINT*) pMicroCode->GetBufferPointer(), - pMicroCode->GetBufferSize(), D3D_DISASM_ENABLE_COLOR_CODE, commentString, pIDisassembly.GetAddressOf() ); - } - - if (pIDisassembly) - { - pDisassembly = static_cast(pIDisassembly->GetBufferPointer()); - } -#endif - if (FAILED(hr)) - { - String message = "Cannot compile D3D11 high-level shader " + mName + " Errors:\n" + - static_cast(errors ? errors->GetBufferPointer() : ""); - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, message, - "D3D11HLSLProgram::compileMicrocode"); - } - else - { -#if OGRE_DEBUG_MODE - // Log warnings if any - const char* warnings = static_cast(errors ? errors->GetBufferPointer() : 0); - if(warnings && LogManager::getSingletonPtr()) - { - String message = "Warnings while compiling D3D11 high-level shader " + mName + ":\n" + warnings; - LogManager::getSingleton().logMessage(message, LML_NORMAL); - } -#endif - mMicroCode.resize(pMicroCode->GetBufferSize()); - memcpy(&mMicroCode[0], pMicroCode->GetBufferPointer(), pMicroCode->GetBufferSize()); - - // get the parameters and variables from the shader reflection - SIZE_T BytecodeLength = mMicroCode.size(); - ComPtr shaderReflection; - HRESULT hr = D3DReflect( (void*) &mMicroCode[0], BytecodeLength, - IID_ID3D11ShaderReflection, // can't do __uuidof(ID3D11ShaderReflection) here... - (void**)shaderReflection.GetAddressOf() ); - - if (FAILED(hr)) - { - String message = "Cannot reflect D3D11 high-level shader " + mName; - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, message, - "D3D11HLSLProgram::compileMicrocode"); - } - - D3D11_SHADER_DESC shaderDesc; - hr = shaderReflection->GetDesc( &shaderDesc ); - - if (FAILED(hr)) - { - String message = "Cannot get reflect info for D3D11 high-level shader " + mName; - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, message, - "D3D11HLSLProgram::compileMicrocode"); - } - - // get the input parameters - mD3d11ShaderInputParameters.resize(shaderDesc.InputParameters); - for (UINT i=0; iGetInputParameterDesc( i, &curParam); - String * name = new String(curParam.SemanticName); - mSerStrings.push_back(name); - curParam.SemanticName = &(*name)[0]; - } - - // get the output parameters - mD3d11ShaderOutputParameters.resize(shaderDesc.OutputParameters); - for (UINT i=0; iGetOutputParameterDesc( i, &curParam); - String * name = new String(curParam.SemanticName); - mSerStrings.push_back(name); - curParam.SemanticName = &(*name)[0]; - } - /* - if (shaderDesc.ConstantBuffers > 1) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Multi constant buffers are not supported for now.", - "D3D11HLSLProgram::compileMicrocode"); - }*/ - - mConstantBufferNr = shaderDesc.ConstantBuffers; - mNumSlots = shaderReflection->GetNumInterfaceSlots(); - - if (shaderDesc.ConstantBuffers > 0) - { - for (unsigned int v=0; v < shaderDesc.ConstantBuffers; v++) - { - ID3D11ShaderReflectionConstantBuffer* shaderReflectionConstantBuffer; - shaderReflectionConstantBuffer = shaderReflection->GetConstantBufferByIndex(v); - - D3D11_SHADER_BUFFER_DESC constantBufferDesc; - hr = shaderReflectionConstantBuffer->GetDesc(&constantBufferDesc); - if (FAILED(hr)) - { - String message = "Cannot reflect constant buffer of D3D11 high-level shader " + mName; - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, message, - "D3D11HLSLProgram::compileMicrocode"); - } - - String * name = new String(constantBufferDesc.Name); - mSerStrings.push_back(name); - constantBufferDesc.Name = &(*name)[0]; - mD3d11ShaderBufferDescs.push_back(constantBufferDesc); - - mConstantBufferSize += constantBufferDesc.Size; - if (v == 0) - mD3d11ShaderVariables.resize(constantBufferDesc.Variables); - else - mD3d11ShaderVariables.resize(mD3d11ShaderVariables.size() + constantBufferDesc.Variables); - - for(unsigned int i = 0; i < constantBufferDesc.Variables ; i++) - { - D3D11_SHADER_VARIABLE_DESC & curVar = mD3d11ShaderVariables[i]; - auto varRef = shaderReflectionConstantBuffer->GetVariableByIndex(i); - HRESULT hr = varRef->GetDesc(&curVar); - if (FAILED(hr)) - { - String message = "Cannot reflect constant buffer variable of D3D11 high-level shader " + mName; - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, message, - "D3D11HLSLProgram::compileMicrocode"); - } - - String * name = new String(curVar.Name); - mSerStrings.push_back(name); - curVar.Name = &(*name)[0]; - - // Recursively descend through the structure levels - if(v == 0) // but only for main buffer - processParamElement( "", *name, varRef->GetType()); - } - - switch (constantBufferDesc.Type) - { - case D3D_CT_INTERFACE_POINTERS: - { - for(UINT k = 0; k < constantBufferDesc.Variables; k++) - { - D3D11_SHADER_VARIABLE_DESC varDesc; - ID3D11ShaderReflectionVariable* var = shaderReflectionConstantBuffer->GetVariableByIndex(k); - var->GetDesc(&varDesc); - String * name = new String(varDesc.Name); - mSerStrings.push_back(name); - varDesc.Name = &(*name)[0]; - mVarDescPointer.push_back(varDesc); - mInterfaceSlots.push_back(var->GetInterfaceSlot(0)); - } - } - break; - case D3D_CT_CBUFFER: - case D3D_CT_TBUFFER: - { - for(unsigned int k = 0; k < constantBufferDesc.Variables ; k++) - { - D3D11_SHADER_VARIABLE_DESC varDesc; - ID3D11ShaderReflectionVariable* varRef = shaderReflectionConstantBuffer->GetVariableByIndex(k); - varRef->GetDesc(&varDesc); - String * name = new String(varDesc.Name); - mSerStrings.push_back(name); - varDesc.Name = &(*name)[0]; - mVarDescBuffer.push_back(varDesc); - - // Only parse if variable is used - if (varDesc.uFlags & D3D_SVF_USED) - { - D3D11_SHADER_TYPE_DESC varTypeDesc; - ID3D11ShaderReflectionType* varType = varRef->GetType(); - varType->GetDesc(&varTypeDesc); - if(varTypeDesc.Name) - { - String * name = new String(varTypeDesc.Name); - mSerStrings.push_back(name); - varTypeDesc.Name = &(*name)[0]; - } - - mD3d11ShaderTypeDescs.push_back(varTypeDesc); - - - if (varTypeDesc.Class == D3D_SVC_STRUCT) - { - const UINT parentOffset = varDesc.StartOffset; - for(UINT m = 0; m < varTypeDesc.Members; m++) - { - D3D11_SHADER_TYPE_DESC memberTypeDesc; - ID3D11ShaderReflectionType* memberType = varType->GetMemberTypeByIndex(m); - memberType->GetDesc(&memberTypeDesc); - - { - String * name = new String(memberTypeDesc.Name); - mSerStrings.push_back(name); - memberTypeDesc.Name = &(*name)[0]; - mMemberTypeDesc.push_back(memberTypeDesc); - } - { - mMemberTypeName.push_back({varType->GetMemberTypeName(m)}); - } - - } - } - } - } - } - } - } - } - - if ( GpuProgramManager::getSingleton().getSaveMicrocodesToCache() ) - { - -#define SIZE_OF_DATA_START(curlist, memberType) + sizeof(uint16) + curlist.size() * ( 0 -#define SIZE_OF_DATA_END ) - -#define SIZE_OF_DATA_UINT(member) + sizeof(uint32) -#define SIZE_OF_DATA_ENUM(member, memberType) SIZE_OF_DATA_UINT(member) - -#define SIZE_OF_DATA_BYTE(member) + sizeof(BYTE) - -#define SIZE_OF_DATA_NAME(member) // we get the size in GET_SIZE_OF_NAMES - so do nothing - -#define GET_SIZE_OF_NAMES(result, list, member) \ - uint32 result = 0; \ - { \ - for(unsigned i = 0 ; i < list.size() ; i++) \ - { \ - if (list[i].member != NULL) \ - result += strlen(list[i].member); \ - result += sizeof(uint16); \ - } \ - } - - GET_SIZE_OF_NAMES(inputNamesSize, mD3d11ShaderInputParameters, SemanticName); - GET_SIZE_OF_NAMES(outputNamesSize, mD3d11ShaderOutputParameters, SemanticName); - GET_SIZE_OF_NAMES(varNamesSize, mD3d11ShaderVariables, Name); - GET_SIZE_OF_NAMES(varSubpartSize, mD3d11ShaderVariableSubparts, Name.c_str()); - GET_SIZE_OF_NAMES(d3d11ShaderBufferDescsSize, mD3d11ShaderBufferDescs, Name); - GET_SIZE_OF_NAMES(varDescBufferSize, mVarDescBuffer, Name); - GET_SIZE_OF_NAMES(varDescPointerSize, mVarDescPointer, Name); - GET_SIZE_OF_NAMES(d3d11ShaderTypeDescsSize, mD3d11ShaderTypeDescs, Name); - GET_SIZE_OF_NAMES(memberTypeDescSize, mMemberTypeDesc, Name); - GET_SIZE_OF_NAMES(memberTypeNameSize, mMemberTypeName, Name.c_str()); - - int sizeOfData = sizeof(uint32) + mMicroCode.size() - + sizeof(uint32) // mConstantBufferSize - + sizeof(uint32) // mConstantBufferNr - + sizeof(uint32) // mNumSlots - SIZE_OF_DATA_START(mD3d11ShaderInputParameters, D3D11_SIGNATURE_PARAMETER_DESC) - SIZE_OF_DATA_NAME(SemanticName) - SIZE_OF_DATA_UINT(SemanticIndex) - SIZE_OF_DATA_UINT(Register) - SIZE_OF_DATA_ENUM(SystemValueType,D3D_NAME) - SIZE_OF_DATA_ENUM(ComponentType, D3D_REGISTER_COMPONENT_TYPE) - SIZE_OF_DATA_BYTE(Mask) - SIZE_OF_DATA_BYTE(ReadWriteMask) - SIZE_OF_DATA_UINT(Stream) -// SIZE_OF_DATA_ENUM(MinPrecision, D3D_MIN_PRECISION) // not needed and doesn't exist in June 2010 SDK - SIZE_OF_DATA_END - - SIZE_OF_DATA_START(mD3d11ShaderOutputParameters, D3D11_SIGNATURE_PARAMETER_DESC) - SIZE_OF_DATA_NAME(SemanticName) - SIZE_OF_DATA_UINT(SemanticIndex) - SIZE_OF_DATA_UINT(Register) - SIZE_OF_DATA_ENUM(SystemValueType, D3D_NAME) - SIZE_OF_DATA_ENUM(ComponentType, D3D_REGISTER_COMPONENT_TYPE) - SIZE_OF_DATA_BYTE(Mask) - SIZE_OF_DATA_BYTE(ReadWriteMask) - SIZE_OF_DATA_UINT(Stream) -// SIZE_OF_DATA_ENUM(MinPrecision, D3D_MIN_PRECISION) // not needed and doesn't exist in June 2010 SDK - SIZE_OF_DATA_END - - SIZE_OF_DATA_START(mD3d11ShaderVariables, D3D11_SHADER_VARIABLE_DESC) - SIZE_OF_DATA_NAME(Name) - SIZE_OF_DATA_UINT(StartOffset) - SIZE_OF_DATA_UINT(Size) - SIZE_OF_DATA_UINT(uFlags) - //todo DefaultValue - SIZE_OF_DATA_UINT(StartTexture) - SIZE_OF_DATA_UINT(TextureSize) - SIZE_OF_DATA_UINT(StartSampler) - SIZE_OF_DATA_UINT(SamplerSize) - SIZE_OF_DATA_END - - SIZE_OF_DATA_START(mD3d11ShaderVariableSubparts, GpuConstantDefinitionWithName) - SIZE_OF_DATA_NAME(Name) - SIZE_OF_DATA_ENUM(constType, GpuConstantType) - SIZE_OF_DATA_UINT(physicalIndex) - SIZE_OF_DATA_UINT(logicalIndex) - SIZE_OF_DATA_UINT(elementSize) - SIZE_OF_DATA_UINT(arraySize) - SIZE_OF_DATA_UINT(variability) - SIZE_OF_DATA_END - - SIZE_OF_DATA_START(mD3d11ShaderBufferDescs, D3D11_SHADER_BUFFER_DESC) - SIZE_OF_DATA_NAME(Name) - SIZE_OF_DATA_ENUM(Type, D3D_CBUFFER_TYPE) - SIZE_OF_DATA_UINT(Variables) - SIZE_OF_DATA_UINT(Size) - SIZE_OF_DATA_UINT(uFlags) - SIZE_OF_DATA_END - - SIZE_OF_DATA_START(mVarDescBuffer, D3D11_SHADER_VARIABLE_DESC) - SIZE_OF_DATA_NAME(Name) - SIZE_OF_DATA_UINT(StartOffset) - SIZE_OF_DATA_UINT(Size) - SIZE_OF_DATA_UINT(uFlags) - //todo DefaultValue - SIZE_OF_DATA_UINT(StartTexture) - SIZE_OF_DATA_UINT(TextureSize) - SIZE_OF_DATA_UINT(StartSampler) - SIZE_OF_DATA_UINT(SamplerSize) - SIZE_OF_DATA_END - - SIZE_OF_DATA_START(mVarDescPointer, D3D11_SHADER_VARIABLE_DESC) - SIZE_OF_DATA_NAME(Name) - SIZE_OF_DATA_UINT(StartOffset) - SIZE_OF_DATA_UINT(Size) - SIZE_OF_DATA_UINT(uFlags) - //todo DefaultValue - SIZE_OF_DATA_UINT(StartTexture) - SIZE_OF_DATA_UINT(TextureSize) - SIZE_OF_DATA_UINT(StartSampler) - SIZE_OF_DATA_UINT(SamplerSize) - SIZE_OF_DATA_END - - SIZE_OF_DATA_START(mD3d11ShaderTypeDescs, D3D11_SHADER_TYPE_DESC) - SIZE_OF_DATA_NAME(Name) - SIZE_OF_DATA_ENUM(Type, D3D_SHADER_VARIABLE_TYPE) - SIZE_OF_DATA_UINT(Rows) - SIZE_OF_DATA_UINT(Columns) - SIZE_OF_DATA_UINT(Elements) - SIZE_OF_DATA_UINT(Members) - SIZE_OF_DATA_UINT(Offset) - SIZE_OF_DATA_END - - SIZE_OF_DATA_START(mMemberTypeDesc, D3D11_SHADER_TYPE_DESC) - SIZE_OF_DATA_NAME(Name) - SIZE_OF_DATA_ENUM(Type, D3D_SHADER_VARIABLE_TYPE) - SIZE_OF_DATA_UINT(Rows) - SIZE_OF_DATA_UINT(Columns) - SIZE_OF_DATA_UINT(Elements) - SIZE_OF_DATA_UINT(Members) - SIZE_OF_DATA_UINT(Offset) - SIZE_OF_DATA_END - - SIZE_OF_DATA_START(mMemberTypeName, MemberTypeName) - SIZE_OF_DATA_NAME(Name) - SIZE_OF_DATA_END - - - + inputNamesSize - + outputNamesSize - + varNamesSize - + varSubpartSize - + d3d11ShaderBufferDescsSize - + varDescBufferSize - + varDescPointerSize - + d3d11ShaderTypeDescsSize - + memberTypeDescSize - + memberTypeNameSize - - + sizeof(uint16) + mInterfaceSlots.size() * sizeof(UINT) - ; - - - // create microcode - auto newMicrocode = GpuProgramManager::createMicrocode(sizeOfData); - - -#define WRITE_START(curlist, memberType) { \ - uint16 listSize = (uint16)curlist.size(); \ - newMicrocode->write(&listSize, sizeof(uint16)); \ - if(listSize > 0){ \ - for(unsigned i = 0 ; i < curlist.size() ; i++){ \ - memberType & curItem = curlist[i]; - -#define WRITE_END }}} - -#define WRITE_UINT(member) { \ - uint32 tmpVal; \ - tmpVal = (uint32)curItem.member; \ - newMicrocode->write(&tmpVal, sizeof(uint32)); \ - } - -#define WRITE_ENUM(member, memberType) WRITE_UINT(member) - -#define WRITE_BYTE(member) { \ - newMicrocode->write(&curItem.member, sizeof(BYTE)); \ - } - -#define WRITE_NAME(member) { \ - uint16 length = 0; \ - if(curItem.member != NULL) \ - length = (uint16)strlen(curItem.member); \ - newMicrocode->write(&length, sizeof(uint16)); \ - if(length != 0) \ - newMicrocode->write(curItem.member, length); \ - } - - uint32 microCodeSize = mMicroCode.size(); - newMicrocode->write(µCodeSize, sizeof(uint32)); - newMicrocode->write(&mMicroCode[0], microCodeSize); - - newMicrocode->write(&mConstantBufferSize, sizeof(uint32)); - newMicrocode->write(&mConstantBufferNr, sizeof(uint32)); - newMicrocode->write(&mNumSlots, sizeof(uint32)); - - WRITE_START(mD3d11ShaderInputParameters, D3D11_SIGNATURE_PARAMETER_DESC) - WRITE_NAME(SemanticName) - WRITE_UINT(SemanticIndex) - WRITE_UINT(Register) - WRITE_ENUM(SystemValueType,D3D_NAME) - WRITE_ENUM(ComponentType, D3D_REGISTER_COMPONENT_TYPE) - WRITE_BYTE(Mask) - WRITE_BYTE(ReadWriteMask) - WRITE_UINT(Stream) -// WRITE_ENUM(MinPrecision, D3D_MIN_PRECISION) // not needed and doesn't exist in June 2010 SDK - WRITE_END - - WRITE_START(mD3d11ShaderOutputParameters, D3D11_SIGNATURE_PARAMETER_DESC) - WRITE_NAME(SemanticName) - WRITE_UINT(SemanticIndex) - WRITE_UINT(Register) - WRITE_ENUM(SystemValueType, D3D_NAME) - WRITE_ENUM(ComponentType, D3D_REGISTER_COMPONENT_TYPE) - WRITE_BYTE(Mask) - WRITE_BYTE(ReadWriteMask) - WRITE_UINT(Stream) -// WRITE_ENUM(MinPrecision, D3D_MIN_PRECISION) // not needed and doesn't exist in June 2010 SDK - WRITE_END - - WRITE_START(mD3d11ShaderVariables, D3D11_SHADER_VARIABLE_DESC) - WRITE_NAME(Name) - WRITE_UINT(StartOffset) - WRITE_UINT(Size) - WRITE_UINT(uFlags) - //todo DefaultValue - WRITE_UINT(StartTexture) - WRITE_UINT(TextureSize) - WRITE_UINT(StartSampler) - WRITE_UINT(SamplerSize) - WRITE_END - - WRITE_START(mD3d11ShaderVariableSubparts, GpuConstantDefinitionWithName) - WRITE_NAME(Name.c_str()) - WRITE_ENUM(constType, GpuConstantType) - WRITE_UINT(physicalIndex) - WRITE_UINT(logicalIndex) - WRITE_UINT(elementSize) - WRITE_UINT(arraySize) - WRITE_UINT(variability) - WRITE_END - - WRITE_START(mD3d11ShaderBufferDescs, D3D11_SHADER_BUFFER_DESC) - WRITE_NAME(Name) - WRITE_ENUM(Type, D3D_CBUFFER_TYPE) - WRITE_UINT(Variables) - WRITE_UINT(Size) - WRITE_UINT(uFlags) - WRITE_END - - WRITE_START(mVarDescBuffer, D3D11_SHADER_VARIABLE_DESC) - WRITE_NAME(Name) - WRITE_UINT(StartOffset) - WRITE_UINT(Size) - WRITE_UINT(uFlags) - //todo DefaultValue - WRITE_UINT(StartTexture) - WRITE_UINT(TextureSize) - WRITE_UINT(StartSampler) - WRITE_UINT(SamplerSize) - WRITE_END - - WRITE_START(mVarDescPointer, D3D11_SHADER_VARIABLE_DESC) - WRITE_NAME(Name) - WRITE_UINT(StartOffset) - WRITE_UINT(Size) - WRITE_UINT(uFlags) - //todo DefaultValue - WRITE_UINT(StartTexture) - WRITE_UINT(TextureSize) - WRITE_UINT(StartSampler) - WRITE_UINT(SamplerSize) - WRITE_END - - WRITE_START(mD3d11ShaderTypeDescs, D3D11_SHADER_TYPE_DESC) - WRITE_NAME(Name) - WRITE_ENUM(Type, D3D_SHADER_VARIABLE_TYPE) - WRITE_UINT(Rows) - WRITE_UINT(Columns) - WRITE_UINT(Elements) - WRITE_UINT(Members) - WRITE_UINT(Offset) - WRITE_END - - WRITE_START(mMemberTypeDesc, D3D11_SHADER_TYPE_DESC) - WRITE_NAME(Name) - WRITE_ENUM(Type, D3D_SHADER_VARIABLE_TYPE) - WRITE_UINT(Rows) - WRITE_UINT(Columns) - WRITE_UINT(Elements) - WRITE_UINT(Members) - WRITE_UINT(Offset) - WRITE_END - - WRITE_START(mMemberTypeName, MemberTypeName) - WRITE_NAME(Name.c_str()) - WRITE_END - - uint16 mInterfaceSlotsSize = (uint16)mInterfaceSlots.size(); - newMicrocode->write(&mInterfaceSlotsSize, sizeof(uint16)); - if(mInterfaceSlotsSize > 0) - { - newMicrocode->write(&mInterfaceSlots[0], mInterfaceSlotsSize * sizeof(UINT)); - } - - - // add to the microcode to the cache - GpuProgramManager::getSingleton().addMicrocodeToCache(getNameForMicrocodeCache(), newMicrocode); - } - } -#endif // else defined(ENABLE_SHADERS_CACHE_LOAD) && (ENABLE_SHADERS_CACHE_LOAD == 1) - } - //----------------------------------------------------------------------- - void D3D11HLSLProgram::analizeMicrocode() - { - getConstantDefinitions(); - auto& params = *mConstantDefs; - - UINT bufferCount = 0; - UINT pointerCount = 0; - UINT typeCount = 0; - UINT memberCount = 0; - UINT interCount = 0; - UINT nameCount = 0; - - for(UINT b = 0; b < mConstantBufferNr; b++) - { - switch (mD3d11ShaderBufferDescs[b].Type) - { - // For this buffer type, all variables are interfaces, - // so just parse and store interface slots - case D3D_CT_INTERFACE_POINTERS: - { - for(UINT v = 0; v < mD3d11ShaderBufferDescs[b].Variables; v++) - { - interCount++; - pointerCount++; - // Only parse if is used - if (mVarDescPointer[pointerCount-1].uFlags & D3D_SVF_USED) - { - mSlotMap.insert(std::make_pair(mVarDescPointer[pointerCount-1].Name, mInterfaceSlots[interCount-1])); - - /* - D3D11_SHADER_TYPE_DESC typeDesc; - ID3D11ShaderReflectionType* varType = var->GetType(); - varType->GetDesc(&typeDesc); - - // Get all interface slots if inside an array - //unsigned int numInterface = varType->GetNumInterfaces(); - for(UINT ifs = 0; ifs < typeDesc.Elements; ifs++) - { - std::string name = varDesc.Name; - name += "["; - name += StringConverter::toString(ifs); - name += "]"; - mSlotMap.insert(std::make_pair(name, ifs)); - } - */ - } - } - } - break; - - // These buffers store variables and class instances, - // so parse all. - case D3D_CT_CBUFFER: - case D3D_CT_TBUFFER: - { - String cb_name = mD3d11ShaderBufferDescs[b].Name; - bool isDefault = false; - if(cb_name == "$Globals" || cb_name == "$Params" || cb_name == "OgreUniforms") - { - if(mDefaultBuffer) - LogManager::getSingleton().logError(mName+" - default cbuffer already exists. Ignoring "+cb_name); - else - { - mDefaultBuffer = HardwareBufferManager::getSingleton().createUniformBuffer(mD3d11ShaderBufferDescs[b].Size); - isDefault = true; - } - } - else - { - auto blockSharedParams = GpuProgramManager::getSingleton().getSharedParameters(cb_name); - - auto cbuffer = HardwareBufferManager::getSingleton().createUniformBuffer(mD3d11ShaderBufferDescs[b].Size); - blockSharedParams->_setHardwareBuffer(cbuffer); - mBufferInfoMap[cb_name] = b; - } - - if(!isDefault) - continue; // only record default buffer variables - - // Now, parse variables for this buffer - for(unsigned int i = 0; i < mD3d11ShaderBufferDescs[b].Variables ; i++) - { - // Only parse if variable is used - bufferCount++; - if (mVarDescBuffer[bufferCount-1].uFlags & D3D_SVF_USED) - { - typeCount++; - switch (mD3d11ShaderTypeDescs[typeCount-1].Class) - { - // Class instance variables - case D3D_SVC_STRUCT: - { - // Offset if relative to parent struct, so store offset - // of class instance, and add to offset of inner variables - const UINT parentOffset = mVarDescBuffer[bufferCount - 1].StartOffset; - for(UINT m = 0; m < mD3d11ShaderTypeDescs[typeCount-1].Members; m++) - { - String name = mVarDescBuffer[bufferCount-1].Name; - name += "."; - name += mMemberTypeName[nameCount++].Name; - - auto& def = params.map[name]; - /*newVar.size = mMemberTypeDesc[memberCount].Rows * mMemberTypeDesc[memberCount].Columns * - (mMemberTypeDesc[memberCount].Type == D3D_SVT_FLOAT || - mMemberTypeDesc[memberCount].Type == D3D_SVT_INT ? 4 : 1);*/ - def.physicalIndex = parentOffset + mMemberTypeDesc[memberCount].Offset; - memberCount++; - } - } - break; - - // scalar, vector or matrix variables - case D3D_SVC_SCALAR: - case D3D_SVC_VECTOR: - case D3D_SVC_MATRIX_ROWS: - case D3D_SVC_MATRIX_COLUMNS: - { - auto& name = mVarDescBuffer[bufferCount-1].Name; - params.map[name].physicalIndex = mVarDescBuffer[bufferCount-1].StartOffset; - } - break; - }; - - } - } - } - break; - } - } - - switch(mType) - { - case GPT_VERTEX_PROGRAM: - CreateVertexShader(); - break; - case GPT_FRAGMENT_PROGRAM: - CreatePixelShader(); - break; - case GPT_GEOMETRY_PROGRAM: - CreateGeometryShader(); - break; - case GPT_DOMAIN_PROGRAM: - CreateDomainShader(); - break; - case GPT_HULL_PROGRAM: - CreateHullShader(); - break; - case GPT_COMPUTE_PROGRAM: - CreateComputeShader(); - break; - } - } - //----------------------------------------------------------------------- - void D3D11HLSLProgram::unprepareImpl(void) - { - for(unsigned int i = 0 ; i < mSerStrings.size() ; i++) - { - delete mSerStrings[i]; - } - mSerStrings.clear(); - } - void D3D11HLSLProgram::unloadHighLevelImpl(void) - { - mSlotMap.clear(); - mBufferInfoMap.clear(); - - mVertexShader.Reset(); - mPixelShader.Reset(); - mGeometryShader.Reset(); - mDomainShader.Reset(); - mHullShader.Reset(); - mComputeShader.Reset(); - mDefaultBuffer.reset(); - - unprepareImpl(); - mD3d11ShaderInputParameters.clear(); - mD3d11ShaderOutputParameters.clear(); - mD3d11ShaderBufferDescs.clear(); - mD3d11ShaderVariables.clear(); - mD3d11ShaderVariableSubparts.clear(); - mVarDescBuffer.clear(); - mD3d11ShaderTypeDescs.clear(); - } - - //----------------------------------------------------------------------- - void D3D11HLSLProgram::buildConstantDefinitions() - { - createParameterMappingStructures(true); - - for(unsigned int i = 0 ; i < mD3d11ShaderVariableSubparts.size() ; i++) - { - GpuConstantDefinitionWithName def = mD3d11ShaderVariableSubparts[i]; - int paramIndex = def.logicalIndex; - GpuLogicalBufferStruct* currentBuffer = NULL; - size_t* currentBufferSize = NULL; - if (def.isFloat() || def.isInt() || def.isUnsignedInt()) - { - currentBuffer = mLogicalToPhysical.get(); - currentBufferSize = &mConstantDefs->bufferSize; - } - - if (currentBuffer != NULL && currentBufferSize != NULL) - { - def.physicalIndex = currentBuffer->bufferSize*4; - OGRE_LOCK_MUTEX(currentBuffer->mutex); - currentBuffer->map.emplace( - paramIndex, GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, GPV_GLOBAL, BCT_UNKNOWN)); - currentBuffer->bufferSize += def.arraySize * def.elementSize; - *currentBufferSize = currentBuffer->bufferSize; - } - else - { - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, - "Currently the only supported variables for Direct3D11 hlsl program are: 'float', 'int' and ' unsigned int'", - "D3D11HLSLProgram::getConstantBuffer"); - } - - mConstantDefs->map.emplace(def.Name, def); - } - } - //----------------------------------------------------------------------- - void D3D11HLSLProgram::processParamElement(String prefix, String paramName, ID3D11ShaderReflectionType* varRefType) - { - D3D11_SHADER_TYPE_DESC varRefTypeDesc; - HRESULT hr = varRefType->GetDesc(&varRefTypeDesc); - - // Since D3D HLSL doesn't deal with naming of array and struct parameters - // automatically, we have to do it by hand - if (FAILED(hr)) - { - OGRE_EXCEPT_EX(Exception::ERR_INTERNAL_ERROR, hr, - "Cannot retrieve constant description from HLSL program.", - "D3D11HLSLProgram::processParamElement"); - } - - // trim the odd '$' which appears at the start of the names in HLSL - if (paramName.at(0) == '$' || paramName.at(0) == '_') - paramName.erase(paramName.begin()); - - // Also trim the '[0]' suffix if it exists, we will add our own indexing later - if (StringUtil::endsWith(paramName, "[0]", false)) - { - paramName.erase(paramName.size() - 3); - } - - if (varRefTypeDesc.Class == D3D_SVC_STRUCT) - { - // work out a new prefix for nested members, if it's an array, we need an index - prefix = prefix + paramName + "."; - // Cascade into struct - for (unsigned int i = 0; i < varRefTypeDesc.Members; ++i) - { - processParamElement(prefix, varRefType->GetMemberTypeName(i), varRefType->GetMemberTypeByIndex(i)); - } - } - else - { - // Process params - if ( varRefTypeDesc.Type == D3D_SVT_FLOAT - || varRefTypeDesc.Type == D3D_SVT_INT - || varRefTypeDesc.Type == D3D_SVT_UINT - || varRefTypeDesc.Type == D3D_SVT_BOOL) - { - GpuConstantDefinitionWithName def; - def.Name = prefix + paramName; - - GpuConstantDefinitionWithName* prev_def = mD3d11ShaderVariableSubparts.empty() ? NULL : &mD3d11ShaderVariableSubparts.back(); - def.logicalIndex = prev_def ? prev_def->logicalIndex + prev_def->elementSize / 4 : 0; - - // populate type, array size & element size - populateDef(varRefTypeDesc, def); - - mD3d11ShaderVariableSubparts.push_back(def); - } - } - - } - //----------------------------------------------------------------------- - void D3D11HLSLProgram::populateDef(D3D11_SHADER_TYPE_DESC& d3dDesc, GpuConstantDefinition& def) const - { - def.arraySize = std::max(d3dDesc.Elements, 1); - switch(d3dDesc.Type) - { - case D3D10_SVT_INT: - switch(d3dDesc.Columns) - { - case 1: - def.constType = GCT_INT1; - break; - case 2: - def.constType = GCT_INT2; - break; - case 3: - def.constType = GCT_INT3; - break; - case 4: - def.constType = GCT_INT4; - break; - } // columns - break; - case D3D10_SVT_UINT: - switch (d3dDesc.Columns) - { - case 1: - def.constType = GCT_UINT1; - break; - case 2: - def.constType = GCT_UINT2; - break; - case 3: - def.constType = GCT_UINT3; - break; - case 4: - def.constType = GCT_UINT4; - break; - } // columns - break; - case D3D10_SVT_FLOAT: - switch(d3dDesc.Rows) - { - case 1: - switch(d3dDesc.Columns) - { - case 1: - def.constType = GCT_FLOAT1; - break; - case 2: - def.constType = GCT_FLOAT2; - break; - case 3: - def.constType = GCT_FLOAT3; - break; - case 4: - def.constType = GCT_FLOAT4; - break; - } // columns - break; - case 2: - switch(d3dDesc.Columns) - { - case 2: - def.constType = GCT_MATRIX_2X2; - break; - case 3: - def.constType = GCT_MATRIX_2X3; - break; - case 4: - def.constType = GCT_MATRIX_2X4; - break; - } // columns - break; - case 3: - switch(d3dDesc.Columns) - { - case 2: - def.constType = GCT_MATRIX_3X2; - break; - case 3: - def.constType = GCT_MATRIX_3X3; - break; - case 4: - def.constType = GCT_MATRIX_3X4; - break; - } // columns - break; - case 4: - switch(d3dDesc.Columns) - { - case 2: - def.constType = GCT_MATRIX_4X2; - break; - case 3: - def.constType = GCT_MATRIX_4X3; - break; - case 4: - def.constType = GCT_MATRIX_4X4; - break; - } // columns - break; - - } // rows - break; - - case D3D_SVT_INTERFACE_POINTER: - def.constType = GCT_SPECIALIZATION; - break; - - default: - // not mapping samplers, don't need to take the space - break; - }; - - // HLSL pads to 4 elements - def.elementSize = GpuConstantDefinition::getElementSize(def.constType, true); - - - } - //----------------------------------------------------------------------- - D3D11HLSLProgram::D3D11HLSLProgram(ResourceManager* creator, const String& name, - ResourceHandle handle, const String& group, bool isManual, - ManualResourceLoader* loader, D3D11Device & device) - : HighLevelGpuProgram(creator, name, handle, group, isManual, loader) - , mDevice(device), mConstantBufferSize(0) - , mColumnMajorMatrices(true), mEnableBackwardsCompatibility(false), mReinterpretingGS(false) - { -#if SUPPORT_SM2_0_HLSL_SHADERS == 1 - mEnableBackwardsCompatibility = true; -#endif - - if (createParamDictionary("D3D11HLSLProgram")) - { - setupBaseParamDictionary(); - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter(ParameterDef("target", - "Name of the assembler target to compile down to.", - PT_STRING),&msCmdTarget); - dict->addParameter(ParameterDef("column_major_matrices", - "Whether matrix packing in column-major order.", - PT_BOOL),&msCmdColumnMajorMatrices); - dict->addParameter(ParameterDef("enable_backwards_compatibility", - "enable backwards compatibility.", - PT_BOOL),&msCmdEnableBackwardsCompatibility); - } - - } - //----------------------------------------------------------------------- - D3D11HLSLProgram::~D3D11HLSLProgram() - { - mBufferInfoMap.clear(); - - // have to call this here rather than in Resource destructor - // since calling virtual methods in base destructors causes crash - if ( isLoaded() ) - { - unload(); - } - else - { - unloadHighLevel(); - } - } - //----------------------------------------------------------------------- - GpuProgramParametersSharedPtr D3D11HLSLProgram::createParameters(void) - { - // Call superclass - GpuProgramParametersSharedPtr params = HighLevelGpuProgram::createParameters(); - - // D3D HLSL uses column-major matrices - params->setTransposeMatrices(mColumnMajorMatrices); - - return params; - } - //----------------------------------------------------------------------- - void D3D11HLSLProgram::setTarget(const String& target) - { - mSyntaxCode = "hlsl"; - std::vector profiles = StringUtil::split(target, " "); - for(unsigned int i = 0 ; i < profiles.size() ; i++) - { - String & currentProfile = profiles[i]; - if(GpuProgramManager::getSingleton().isSyntaxSupported(currentProfile)) - { - mSyntaxCode = currentProfile; - break; - } - } - - if(mSyntaxCode == "hlsl") - { - LogManager::getSingleton().logMessage( - "Invalid target for D3D11 shader '" + mName + "' - '" + target + "'"); - return; - } - } - //----------------------------------------------------------------------- - const char* D3D11HLSLProgram::getCompatibleTarget(void) const - { - if(mSyntaxCode == "hlsl") - { - return mType == GPT_VERTEX_PROGRAM ? "vs_4_0_level_9_1" : "ps_4_0_level_9_1"; - } - - if(mEnableBackwardsCompatibility) - { - if(mSyntaxCode == "vs_2_0") return "vs_4_0_level_9_1"; - if(mSyntaxCode == "vs_2_a") return "vs_4_0_level_9_3"; - if(mSyntaxCode == "vs_3_0") return "vs_4_0"; - - if(mSyntaxCode == "ps_2_0") return "ps_4_0_level_9_1"; - if(mSyntaxCode == "ps_2_a") return "ps_4_0_level_9_3"; - if(mSyntaxCode == "ps_2_b") return "ps_4_0_level_9_3"; - if(mSyntaxCode == "ps_3_0") return "ps_4_0"; - } - - return mSyntaxCode.c_str(); - } - //----------------------------------------------------------------------- - const String& D3D11HLSLProgram::getLanguage(void) const - { - static const String language = "hlsl"; - - return language; - } - - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String D3D11HLSLProgram::CmdTarget::doGet(const void *target) const - { - return static_cast(target)->getTarget(); - } - void D3D11HLSLProgram::CmdTarget::doSet(void *target, const String& val) - { - static_cast(target)->setTarget(val); - } - //----------------------------------------------------------------------- - String D3D11HLSLProgram::CmdColumnMajorMatrices::doGet(const void *target) const - { - return StringConverter::toString(static_cast(target)->getColumnMajorMatrices()); - } - void D3D11HLSLProgram::CmdColumnMajorMatrices::doSet(void *target, const String& val) - { - static_cast(target)->setColumnMajorMatrices(StringConverter::parseBool(val)); - } - //----------------------------------------------------------------------- - String D3D11HLSLProgram::CmdEnableBackwardsCompatibility::doGet(const void *target) const - { - return StringConverter::toString(static_cast(target)->getEnableBackwardsCompatibility()); - } - void D3D11HLSLProgram::CmdEnableBackwardsCompatibility::doSet(void *target, const String& val) - { - static_cast(target)->setEnableBackwardsCompatibility(StringConverter::parseBool(val)); - } - //----------------------------------------------------------------------- - void D3D11HLSLProgram::CreateVertexShader() - { - if (isSupported()) - { - // Create the shader - HRESULT hr = mDevice->CreateVertexShader( - &mMicroCode[0], - mMicroCode.size(), - mDevice.GetClassLinkage(), - mVertexShader.ReleaseAndGetAddressOf()); - - assert(mVertexShader); - - if (FAILED(hr) || mDevice.isError()) - { - String errorDescription = mDevice.getErrorDescription(hr); - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Cannot create D3D11 vertex shader " + mName + " from microcode.\nError Description:" + errorDescription, - "D3D11HLSLProgram::CreateVertexShader"); - } - } - else - { - assert(false); - LogManager::getSingleton().logMessage( - "Unsupported D3D11 vertex shader '" + mName + "' was not loaded."); - } - } - - //----------------------------------------------------------------------- - void D3D11HLSLProgram::CreatePixelShader() - { - if (isSupported()) - { - // Create the shader - HRESULT hr = mDevice->CreatePixelShader( - &mMicroCode[0], - mMicroCode.size(), - mDevice.GetClassLinkage(), - mPixelShader.ReleaseAndGetAddressOf()); - - if (FAILED(hr) || mDevice.isError()) - { - String errorDescription = mDevice.getErrorDescription(hr); - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Cannot create D3D11 Pixel shader " + mName + " from microcode.\nError Description:" + errorDescription, - "D3D11HLSLProgram::CreatePixelShader"); - } - } - else - { - LogManager::getSingleton().logMessage( - "Unsupported D3D11 Pixel shader '" + mName + "' was not loaded."); - } - } - - void D3D11HLSLProgram::reinterpretGSForStreamOut(void) - { - assert(mGeometryShader); - unloadHighLevel(); - mReinterpretingGS = true; - prepareImpl(); - loadHighLevel(); - mReinterpretingGS = false; - } - - static unsigned int getComponentCount(BYTE mask) - { - unsigned int compCount = 0; - if (mask&1) - ++compCount; - if (mask&2) - ++compCount; - if (mask&4) - ++compCount; - if (mask&8) - ++compCount; - return compCount; - } - - //----------------------------------------------------------------------- - void D3D11HLSLProgram::CreateGeometryShader() - { - if (isSupported()) - { - HRESULT hr; - if (mReinterpretingGS) - { - std::vector soDeclarations; - int totalComp = 0; - for(D3D11_SIGNATURE_PARAMETER_DESC pDesc : mD3d11ShaderOutputParameters) - { - D3D11_SO_DECLARATION_ENTRY soDecl = {}; - - soDecl.SemanticName = pDesc.SemanticName; - soDecl.SemanticIndex= pDesc.SemanticIndex; - soDecl.ComponentCount = getComponentCount(pDesc.Mask); - - soDeclarations.push_back(soDecl); - - totalComp += soDecl.ComponentCount; - } - - // Create the shader - UINT bufferStrides[1] = {totalComp * UINT(sizeof(float))}; - hr = mDevice->CreateGeometryShaderWithStreamOutput( - &mMicroCode[0], - mMicroCode.size(), - soDeclarations.data(), - soDeclarations.size(), - bufferStrides, - 1, - D3D11_SO_NO_RASTERIZED_STREAM, - mDevice.GetClassLinkage(), - mGeometryShader.ReleaseAndGetAddressOf()); - } - else - { - // Create the shader - hr = mDevice->CreateGeometryShader( - &mMicroCode[0], - mMicroCode.size(), - mDevice.GetClassLinkage(), - mGeometryShader.ReleaseAndGetAddressOf()); - } - - - assert(mGeometryShader); - - if (FAILED(hr) || mDevice.isError()) - { - String errorDescription = mDevice.getErrorDescription(hr); - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Cannot create D3D11 Geometry shader " + mName + " from microcode.\nError Description:" + errorDescription, - "D3D11HLSLProgram::CreateGeometryShader"); - } - } - else - { - LogManager::getSingleton().logMessage( - "Unsupported D3D11 Geometry shader '" + mName + "' was not loaded."); - } - } - //----------------------------------------------------------------------- - void D3D11HLSLProgram::CreateHullShader() - { - if (isSupported()) - { - // Create the shader - HRESULT hr = mDevice->CreateHullShader( - &mMicroCode[0], - mMicroCode.size(), - mDevice.GetClassLinkage(), - mHullShader.ReleaseAndGetAddressOf()); - - if (FAILED(hr) || mDevice.isError()) - { - String errorDescription = mDevice.getErrorDescription(hr); - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Cannot create D3D11 Hull shader " + mName + " from microcode.\nError Description:" + errorDescription, - "D3D11HLSLProgram::CreateHullShader"); - } - } - else - { - LogManager::getSingleton().logMessage( - "Unsupported D3D11 Hull shader '" + mName + "' was not loaded."); - } - } - //----------------------------------------------------------------------- - void D3D11HLSLProgram::CreateDomainShader() - { - if (isSupported()) - { - // Create the shader - HRESULT hr = mDevice->CreateDomainShader( - &mMicroCode[0], - mMicroCode.size(), - mDevice.GetClassLinkage(), - mDomainShader.ReleaseAndGetAddressOf()); - - if (FAILED(hr) || mDevice.isError()) - { - String errorDescription = mDevice.getErrorDescription(hr); - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Cannot create D3D11 Domain shader " + mName + " from microcode.\nError Description:" + errorDescription, - "D3D11HLSLProgram::CreateDomainShader"); - } - } - else - { - LogManager::getSingleton().logMessage( - "Unsupported D3D11 Domain shader '" + mName + "' was not loaded."); - } - } - //----------------------------------------------------------------------- - void D3D11HLSLProgram::CreateComputeShader() - { - if (isSupported()) - { - // Create the shader - HRESULT hr = mDevice->CreateComputeShader( - &mMicroCode[0], - mMicroCode.size(), - mDevice.GetClassLinkage(), - mComputeShader.ReleaseAndGetAddressOf()); - - if (FAILED(hr) || mDevice.isError()) - { - String errorDescription = mDevice.getErrorDescription(hr); - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Cannot create D3D11 Compute shader " + mName + " from microcode.\nError Description:" + errorDescription, - "D3D11HLSLProgram::CreateComputeShader"); - } - } - else - { - LogManager::getSingleton().logMessage( - "Unsupported D3D11 Compute shader '" + mName + "' was not loaded."); - } - } - //----------------------------------------------------------------------------- - unsigned int D3D11HLSLProgram::getSubroutineSlot(const String& subroutineSlotName) const - { - SlotIterator it = mSlotMap.find(subroutineSlotName); - if (it == mSlotMap.end()) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Don't exist interface slot with name " + subroutineSlotName + " in shader " + mName, - "D3D11HLSLProgram::getInterfaceSlot"); - } - - return it->second; - } - //----------------------------------------------------------------------------- - std::vector D3D11HLSLProgram::getConstantBuffers(const GpuProgramParametersPtr& params) - { - std::vector buffers; - if(mDefaultBuffer) - { - OgreAssert(mDefaultBuffer->getSizeInBytes() <= params->getConstantList().size(), "unexpected buffer size"); - mDefaultBuffer->writeData(0, mDefaultBuffer->getSizeInBytes(), params->getConstantList().data(), true); - - buffers.push_back(static_cast(mDefaultBuffer.get())->getD3DBuffer()); - } - else - { - buffers.push_back(NULL); - } - - for (const auto& usage : params->getSharedParameters()) - { - if(const auto& buf = usage.getSharedParams()->_getHardwareBuffer()) - { - // hardware baked cbuffer - auto it = mBufferInfoMap.find(usage.getName()); - if(it == mBufferInfoMap.end()) - continue; // TODO: error? - - size_t slot = it->second; - buffers.resize(std::max(slot + 1, buffers.size())); - buffers[slot] = static_cast(buf.get())->getD3DBuffer(); - } - } - - return buffers; - } - //----------------------------------------------------------------------------- - ID3D11VertexShader* D3D11HLSLProgram::getVertexShader(void) const - { - assert(mType == GPT_VERTEX_PROGRAM); - assert(mVertexShader); - return mVertexShader.Get(); - } - //----------------------------------------------------------------------------- - ID3D11PixelShader* D3D11HLSLProgram::getPixelShader(void) const - { - assert(mType == GPT_FRAGMENT_PROGRAM); - assert(mPixelShader); - return mPixelShader.Get(); - } - //----------------------------------------------------------------------------- - ID3D11GeometryShader* D3D11HLSLProgram::getGeometryShader(void) const - { - assert(mType == GPT_GEOMETRY_PROGRAM); - assert(mGeometryShader); - return mGeometryShader.Get(); - } - //----------------------------------------------------------------------------- - ID3D11DomainShader* D3D11HLSLProgram::getDomainShader(void) const - { - assert(mType == GPT_DOMAIN_PROGRAM); - assert(mDomainShader); - return mDomainShader.Get(); - } - //----------------------------------------------------------------------------- - ID3D11HullShader* D3D11HLSLProgram::getHullShader(void) const - { - assert(mType == GPT_HULL_PROGRAM); - assert(mHullShader); - return mHullShader.Get(); - } - //----------------------------------------------------------------------------- - ID3D11ComputeShader* D3D11HLSLProgram::getComputeShader(void) const - { - assert(mType == GPT_COMPUTE_PROGRAM); - assert(mComputeShader); - return mComputeShader.Get(); - } - //----------------------------------------------------------------------------- - const MicroCode & D3D11HLSLProgram::getMicroCode(void) const - { - assert(mMicroCode.size() > 0); - return mMicroCode; - } - //----------------------------------------------------------------------------- - uint32 D3D11HLSLProgram::getNameForMicrocodeCache() - { - uint32 seed = FastHash(mSyntaxCode.c_str(), mSyntaxCode.size()); - return _getHash(seed); - } - - -} diff --git a/RenderSystems/Direct3D11/src/OgreD3D11HLSLProgramFactory.cpp b/RenderSystems/Direct3D11/src/OgreD3D11HLSLProgramFactory.cpp deleted file mode 100644 index cf0e255f8fd..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11HLSLProgramFactory.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreD3D11HLSLProgramFactory.h" -#include "OgreD3D11HLSLProgram.h" -#include "OgreD3D11Device.h" - -namespace Ogre { - //----------------------------------------------------------------------- - String D3D11HLSLProgramFactory::sLanguageName = "hlsl"; - //----------------------------------------------------------------------- - D3D11HLSLProgramFactory::D3D11HLSLProgramFactory(D3D11Device & device) : mDevice(device) - { - } - //----------------------------------------------------------------------- - D3D11HLSLProgramFactory::~D3D11HLSLProgramFactory() - { - } - //----------------------------------------------------------------------- - const String& D3D11HLSLProgramFactory::getLanguage(void) const - { - return sLanguageName; - } - //----------------------------------------------------------------------- - GpuProgram* D3D11HLSLProgramFactory::create(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - { - return new D3D11HLSLProgram(creator, name, handle, group, isManual, loader, mDevice); - } -} diff --git a/RenderSystems/Direct3D11/src/OgreD3D11HardwareBuffer.cpp b/RenderSystems/Direct3D11/src/OgreD3D11HardwareBuffer.cpp deleted file mode 100644 index b1f46eb80d9..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11HardwareBuffer.cpp +++ /dev/null @@ -1,264 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11HardwareBuffer.h" -#include "OgreD3D11Mappings.h" -#include "OgreD3D11Device.h" -#include "OgreException.h" -namespace Ogre { - - //--------------------------------------------------------------------- - D3D11HardwareBuffer::D3D11HardwareBuffer( - BufferType btype, size_t sizeBytes, - HardwareBuffer::Usage usage, D3D11Device & device, - bool useShadowBuffer, bool streamOut) - : HardwareBuffer(usage, useShadowBuffer), - mUseTempStagingBuffer(false), - mBufferType(btype), - mDevice(device) - { - mSizeInBytes = sizeBytes; - mDesc.ByteWidth = static_cast(sizeBytes); - mDesc.CPUAccessFlags = 0; - mDesc.MiscFlags = 0; - - if (usage == HBU_CPU_ONLY) - { - mDesc.Usage = D3D11_USAGE_STAGING; - //A D3D11_USAGE_STAGING Resource cannot be bound to any parts of the graphics pipeline, so therefore cannot have any BindFlags bits set. - mDesc.BindFlags = 0; - mDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ ;// A D3D11_USAGE_STAGING Resource must have at least one CPUAccessFlag bit set. - - } - else - { - mDesc.Usage = D3D11Mappings::_getUsage(mUsage); - mDesc.BindFlags = btype == VERTEX_BUFFER ? D3D11_BIND_VERTEX_BUFFER : - btype == INDEX_BUFFER ? D3D11_BIND_INDEX_BUFFER : - D3D11_BIND_CONSTANT_BUFFER; - } - // Better check of stream out flag - if (streamOut && btype != CONSTANT_BUFFER) - { - mDesc.BindFlags |= D3D11_BIND_STREAM_OUTPUT; - } - - if (usage == HBU_CPU_TO_GPU) - { - // We want to be able to map this buffer - mDesc.CPUAccessFlags |= D3D11_CPU_ACCESS_WRITE; - mDesc.Usage = D3D11_USAGE_DYNAMIC; - } - - // Note that in D3D11 you can only directly lock (map) a dynamic resource - // directly for writing. You can only map for read / write staging resources, - // which themselves cannot be used for input / output to the GPU. Thus - // for any locks except write locks on dynamic resources, we have to use - // temporary staging resources instead and use async copies. - - // TODO: we can explicitly initialise the buffer contents here if we like - // not doing this since OGRE doesn't support this model yet - OGRE_CHECK_DX_ERROR(device->CreateBuffer(&mDesc, NULL, mlpD3DBuffer.ReleaseAndGetAddressOf())); - - // Create shadow buffer - if (useShadowBuffer) - { - mShadowBuffer.reset(new D3D11HardwareBuffer(mBufferType, - mSizeInBytes, HBU_CPU_ONLY, mDevice, false, false)); - } - - } - //--------------------------------------------------------------------- - D3D11HardwareBuffer::~D3D11HardwareBuffer() {} - //--------------------------------------------------------------------- - void* D3D11HardwareBuffer::lockImpl(size_t offset, - size_t length, LockOptions options) - { - if (mUsage == HBU_CPU_ONLY || (mUsage & HardwareBuffer::HBU_DYNAMIC && - (options == HardwareBuffer::HBL_DISCARD || options == HardwareBuffer::HBL_NO_OVERWRITE))) - { - // Staging (system memory) buffers or dynamic, write-only buffers - // are the only case where we can lock directly - // We have no 'lock for writing' but discard + locking the entire - // buffer essentially means the same thing, especially since it's - // not possible to map part of a buffer in Dx11 - - // map directly - D3D11_MAP mapType; - switch(options) - { - case HBL_DISCARD: - // To use D3D11_MAP_WRITE_DISCARD resource must have been created with write access and dynamic usage. - mapType = mUsage == HBU_CPU_ONLY ? D3D11_MAP_WRITE : D3D11_MAP_WRITE_DISCARD; - break; - case HBL_NO_OVERWRITE: - // To use D3D11_MAP_WRITE_NO_OVERWRITE resource must have been created with write access. - // TODO: check (D3D11_USAGE_STAGING => D3D11_MAP_WRITE_NO_OVERWRITE) combo - it`s not forbidden by MSDN - mapType = mUsage == HBU_CPU_ONLY ? D3D11_MAP_WRITE : D3D11_MAP_WRITE_NO_OVERWRITE; - break; - case HBL_NORMAL: - mapType = (mDesc.CPUAccessFlags & D3D11_CPU_ACCESS_READ) ? D3D11_MAP_READ_WRITE : D3D11_MAP_WRITE; - break; - case HBL_READ_ONLY: - mapType = D3D11_MAP_READ; - break; - case HBL_WRITE_ONLY: - mapType = D3D11_MAP_WRITE; - break; - } - - void * pRet = NULL; - D3D11_MAPPED_SUBRESOURCE mappedSubResource; - mappedSubResource.pData = NULL; - OGRE_CHECK_DX_ERROR(mDevice.GetImmediateContext()->Map(mlpD3DBuffer.Get(), 0, mapType, 0, &mappedSubResource)); - - pRet = static_cast(static_cast(mappedSubResource.pData) + offset); - - return pRet; - - } - else - { - mIsLocked = false; // locking staging buffer instead - mUseTempStagingBuffer = true; - OgreAssertDbg(!mShadowBuffer, - "we should never arrive here, when already having a shadow buffer"); - // create temporary shadow buffer - mShadowBuffer.reset(new D3D11HardwareBuffer(mBufferType, - mSizeInBytes, HBU_CPU_ONLY, mDevice, false, false)); - - // schedule a copy to the staging - if (options != HBL_DISCARD) - mShadowBuffer->copyData(*this, offset, offset, length, true); - - // register whether we'll need to upload on unlock - mShadowUpdated = (options != HBL_READ_ONLY); - - return mShadowBuffer->lock(offset, length, options); - } - } - //--------------------------------------------------------------------- - void D3D11HardwareBuffer::unlockImpl(void) - { - OgreAssertDbg(!mUseTempStagingBuffer, "should be handled by _updateFromShadow"); - - // unmap - mDevice.GetImmediateContext()->Unmap(mlpD3DBuffer.Get(), 0); - } - //--------------------------------------------------------------------- - void D3D11HardwareBuffer::copyData(HardwareBuffer& srcBuffer, size_t srcOffset, - size_t dstOffset, size_t length, bool discardWholeBuffer) - { - if (mShadowBuffer) - { - mShadowBuffer->copyData(srcBuffer, srcOffset, dstOffset, length, discardWholeBuffer); - } - copyDataImpl(srcBuffer, srcOffset, dstOffset, length, discardWholeBuffer); - } - //--------------------------------------------------------------------- - void D3D11HardwareBuffer::copyDataImpl(HardwareBuffer& srcBuffer, size_t srcOffset, - size_t dstOffset, size_t length, bool discardWholeBuffer) - { - // If we're copying same-size buffers in their entirety... - if (srcOffset == 0 && dstOffset == 0 && - length == mSizeInBytes && mSizeInBytes == srcBuffer.getSizeInBytes()) - { - // schedule hardware buffer copy - mDevice.GetImmediateContext()->CopyResource(mlpD3DBuffer.Get(), static_cast(srcBuffer).getD3DBuffer()); - if (mDevice.isError()) - { - String errorDescription = mDevice.getErrorDescription(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Cannot copy D3D11 resource\nError Description:" + errorDescription, - "D3D11HardwareBuffer::copyData"); - } - } - else - { - // copy subregion - D3D11_BOX srcBox; - srcBox.left = (UINT)srcOffset; - srcBox.right = (UINT)srcOffset + length; - srcBox.top = 0; - srcBox.bottom = 1; - srcBox.front = 0; - srcBox.back = 1; - - mDevice.GetImmediateContext()->CopySubresourceRegion(mlpD3DBuffer.Get(), 0, (UINT)dstOffset, 0, 0, - static_cast(srcBuffer).getD3DBuffer(), 0, &srcBox); - if (mDevice.isError()) - { - String errorDescription = mDevice.getErrorDescription(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Cannot copy D3D11 subresource region\nError Description:" + errorDescription, - "D3D11HardwareBuffer::copyData"); - } - } - } - //--------------------------------------------------------------------- - void D3D11HardwareBuffer::_updateFromShadow(void) - { - if(mShadowBuffer && mShadowUpdated && !mSuppressHardwareUpdate) - { - bool discardWholeBuffer = mLockStart == 0 && mLockSize == mSizeInBytes; - copyDataImpl(*mShadowBuffer, mLockStart, mLockStart, mLockSize, discardWholeBuffer); - mShadowUpdated = false; - } - - if (mUseTempStagingBuffer) - { - // delete - mShadowBuffer.reset(); - mUseTempStagingBuffer = false; - } - } - //--------------------------------------------------------------------- - void D3D11HardwareBuffer::readData(size_t offset, size_t length, - void* pDest) - { - // There is no functional interface in D3D, just do via manual - // lock, copy & unlock - HardwareBufferLockGuard thisLock(this, offset, length, HardwareBuffer::HBL_READ_ONLY); - memcpy(pDest, thisLock.pData, length); - } - //--------------------------------------------------------------------- - void D3D11HardwareBuffer::writeData(size_t offset, size_t length, - const void* pSource, - bool discardWholeBuffer) - { - // There is no functional interface in D3D, just do via manual - // lock, copy & unlock - HardwareBufferLockGuard thisLock(this, offset, length, - discardWholeBuffer ? HardwareBuffer::HBL_DISCARD : HardwareBuffer::HBL_NORMAL); - memcpy(thisLock.pData, pSource, length); - - //What if we try UpdateSubresource - //mDevice.GetImmediateContext()->UpdateSubresource(mlpD3DBuffer.Get(), 0, NULL, pSource, offset, length); - } - //--------------------------------------------------------------------- - -} diff --git a/RenderSystems/Direct3D11/src/OgreD3D11HardwareBufferManager.cpp b/RenderSystems/Direct3D11/src/OgreD3D11HardwareBufferManager.cpp deleted file mode 100644 index 9eb8b1a0975..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11HardwareBufferManager.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11HardwareBufferManager.h" -#include "OgreD3D11HardwareBuffer.h" -#include "OgreD3D11VertexDeclaration.h" -#include "OgreD3D11RenderToVertexBuffer.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreD3D11Device.h" - -namespace Ogre { - //----------------------------------------------------------------------- - D3D11HardwareBufferManager::D3D11HardwareBufferManager(D3D11Device & device) - : mlpD3DDevice(device) - { - } - //----------------------------------------------------------------------- - D3D11HardwareBufferManager::~D3D11HardwareBufferManager() - { - destroyAllDeclarations(); - destroyAllBindings(); - } - //----------------------------------------------------------------------- - HardwareVertexBufferSharedPtr - D3D11HardwareBufferManager:: - createVertexBuffer(size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, - bool useShadowBuffer) - { - assert(numVerts > 0); - auto impl = new D3D11HardwareBuffer(D3D11HardwareBuffer::VERTEX_BUFFER, vertexSize * numVerts, usage, mlpD3DDevice, useShadowBuffer, false); - auto buf = std::make_shared(this, vertexSize, numVerts, impl); - { - OGRE_LOCK_MUTEX(mVertexBuffersMutex); - mVertexBuffers.insert(buf.get()); - } - return buf; - } - //----------------------------------------------------------------------- - HardwareVertexBufferSharedPtr - D3D11HardwareBufferManager:: - createStreamOutputVertexBuffer(size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, - bool useShadowBuffer) - { - assert(numVerts > 0); - - auto impl = new D3D11HardwareBuffer(D3D11HardwareBuffer::VERTEX_BUFFER, vertexSize * numVerts, usage, mlpD3DDevice, useShadowBuffer, true); - auto buf = std::make_shared(this, vertexSize, numVerts, impl); - { - OGRE_LOCK_MUTEX(mVertexBuffersMutex); - mVertexBuffers.insert(buf.get()); - } - return buf; - } - //----------------------------------------------------------------------- - HardwareIndexBufferSharedPtr - D3D11HardwareBufferManager:: - createIndexBuffer(HardwareIndexBuffer::IndexType itype, size_t numIndexes, - HardwareBuffer::Usage usage, bool useShadowBuffer) - { - assert(numIndexes > 0); - - auto indexSize = HardwareIndexBuffer::indexSize(itype); - auto impl = new D3D11HardwareBuffer(D3D11HardwareBuffer::INDEX_BUFFER, indexSize * numIndexes, usage, mlpD3DDevice, useShadowBuffer, false); - - return std::make_shared(this, itype, numIndexes, impl); - } - //----------------------------------------------------------------------- - RenderToVertexBufferSharedPtr - D3D11HardwareBufferManager::createRenderToVertexBuffer() - { - return RenderToVertexBufferSharedPtr(new D3D11RenderToVertexBuffer(mlpD3DDevice, this)); - } - //----------------------------------------------------------------------- - HardwareBufferPtr - D3D11HardwareBufferManager::createUniformBuffer(size_t sizeBytes, HardwareBufferUsage usage, bool useShadowBuffer) - { - assert(sizeBytes > 0); - return std::make_shared(D3D11HardwareBuffer::CONSTANT_BUFFER, - sizeBytes, usage, mlpD3DDevice, useShadowBuffer, false); - } - //----------------------------------------------------------------------- - VertexDeclaration* D3D11HardwareBufferManager::createVertexDeclarationImpl(void) - { - return new D3D11VertexDeclaration(mlpD3DDevice); - } -} diff --git a/RenderSystems/Direct3D11/src/OgreD3D11HardwareOcclusionQuery.cpp b/RenderSystems/Direct3D11/src/OgreD3D11HardwareOcclusionQuery.cpp deleted file mode 100644 index 993fc8036d5..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11HardwareOcclusionQuery.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11HardwareOcclusionQuery.h" -#include "OgreRenderSystemCapabilities.h" -#include "OgreException.h" -#include "OgreD3D11Device.h" -namespace Ogre { - - /** - * This is a class that is the DirectX9 implementation of - * hardware occlusion testing. - * - * @author Lee Sandberg - * - * Updated on 12/7/2004 by Chris McGuirk - * Updated on 4/8/2005 by Tuan Kuranes email: tuan.kuranes@free.fr - */ - - /** - * Default object constructor - */ - D3D11HardwareOcclusionQuery::D3D11HardwareOcclusionQuery( D3D11Device & device ) : - mDevice(device) - { - D3D11_QUERY_DESC queryDesc; - queryDesc.Query = D3D11_QUERY_OCCLUSION; - queryDesc.MiscFlags = 0; - // create the occlusion query - OGRE_CHECK_DX_ERROR(mDevice->CreateQuery(&queryDesc, mQuery.ReleaseAndGetAddressOf())); - } - - /** - * Object destructor - */ - D3D11HardwareOcclusionQuery::~D3D11HardwareOcclusionQuery() - { - } - - //------------------------------------------------------------------ - // Occlusion query functions (see base class documentation for this) - //-- - void D3D11HardwareOcclusionQuery::beginOcclusionQuery() - { - mDevice.GetImmediateContext()->Begin(mQuery.Get());//Issue(D3DISSUE_BEGIN); - mIsQueryResultStillOutstanding = true; - mPixelCount = 0; - } - - void D3D11HardwareOcclusionQuery::endOcclusionQuery() - { - mDevice.GetImmediateContext()->End(mQuery.Get());//Issue(D3DISSUE_END); - } - - //------------------------------------------------------------------ - bool D3D11HardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments ) - { - // in case you didn't check if query arrived and want the result now. - if (mIsQueryResultStillOutstanding) - { - // Loop until the data becomes available - UINT64 pixels; - const size_t dataSize = sizeof( UINT64 ); - while (1) - { - const HRESULT hr = mDevice.GetImmediateContext()->GetData(mQuery.Get(), (void *)&pixels, dataSize, 0);//D3DGETDATA_FLUSH - - if (hr == S_FALSE) - continue; - if (hr == S_OK) - { - mPixelCount = (unsigned)pixels; - *NumOfFragments = (unsigned)pixels; - break; - } - //in directx10 the device will never be lost - /* if (hr == D3DERR_DEVICELOST) - { - *NumOfFragments = 100000; - mPixelCount = 100000; - D3D11_QUERY_DESC queryDesc; - queryDesc.Query = D3D11_QUERY_OCCLUSION; - mDevice->CreateQuery(%queryDesc, mQuery.ReleaseAndGetAddressOf()); - break; - } - */ - } - mIsQueryResultStillOutstanding = false; - } - else - { - // we already stored result from last frames. - *NumOfFragments = mPixelCount; - } - return true; - } - //------------------------------------------------------------------ - bool D3D11HardwareOcclusionQuery::isStillOutstanding(void) - { - // in case you already asked for this query - if (!mIsQueryResultStillOutstanding) - return false; - - UINT64 pixels; - const HRESULT hr = mDevice.GetImmediateContext()->GetData(mQuery.Get(), (void *) &pixels, sizeof( UINT64 ), 0); - - if (hr == S_FALSE) - return true; - - /* if (hr == D3DERR_DEVICELOST) - { - mPixelCount = 100000; - D3D11_QUERY_DESC queryDesc; - queryDesc.Query = D3D11_QUERY_OCCLUSION; - mDevice->CreateQuery(&queryDesc, mQuery.ReleaseAndGetAddressOf()); - } - */ - mPixelCount = (unsigned)pixels; - mIsQueryResultStillOutstanding = false; - return false; - - } -} diff --git a/RenderSystems/Direct3D11/src/OgreD3D11HardwarePixelBuffer.cpp b/RenderSystems/Direct3D11/src/OgreD3D11HardwarePixelBuffer.cpp deleted file mode 100644 index d064e63501c..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11HardwarePixelBuffer.cpp +++ /dev/null @@ -1,522 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11HardwarePixelBuffer.h" -#include "OgreD3D11Texture.h" -#include "OgreD3D11Mappings.h" -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreBitwise.h" - -#include "OgreRoot.h" -#include "OgreRenderSystem.h" -#include "OgreD3D11Texture.h" -#include "OgreD3D11Device.h" -#include "OgreD3D11RenderSystem.h" - -#include - -namespace Ogre { - - namespace - { - const char* toString(TextureType textureType) - { - switch(textureType) - { - case TEX_TYPE_1D: return "1D texture"; - case TEX_TYPE_CUBE_MAP: return "cube map texture"; - case TEX_TYPE_2D: return "2D texture"; - case TEX_TYPE_2D_ARRAY: return "2D texture array"; - case TEX_TYPE_3D: return "3D texture"; - default: return "texture"; - } - } - } - - //----------------------------------------------------------------------------- - - D3D11HardwarePixelBuffer::D3D11HardwarePixelBuffer(D3D11Texture * parentTexture, D3D11Device & device, UINT mipLevel, - size_t width, size_t height, size_t depth, UINT face, PixelFormat format, HardwareBuffer::Usage usage): - HardwarePixelBuffer(width, height, depth, format, usage, false), - mParentTexture(parentTexture), - mDevice(device), - mFace(face), - mMipLevel(mipLevel) - { - if(mUsage & TU_RENDERTARGET) - { - // Create render target for each slice - mSliceTRT.reserve(mDepth); - for(size_t zoffset=0; zoffsetgetName(); - - RenderTexture *trt = new D3D11RenderTexture(name, this, zoffset, mDevice); - mSliceTRT.push_back(trt); - Root::getSingleton().getRenderSystem()->attachRenderTarget(*trt); - } - } - } - D3D11HardwarePixelBuffer::~D3D11HardwarePixelBuffer() - { - } - //----------------------------------------------------------------------------- - void D3D11HardwarePixelBuffer::_map(ID3D11Resource *res, D3D11_MAP flags, PixelBox & box) - { - assert(mLockedBox.getDepth() == 1 || mParentTexture->getTextureType() == TEX_TYPE_3D); - - D3D11_MAPPED_SUBRESOURCE pMappedResource = { 0 }; - UINT subresource = (res == mStagingBuffer.Get()) ? 0 : getSubresourceIndex(mLockedBox.front); - - HRESULT hr = mDevice.GetImmediateContext()->Map(res, subresource, flags, 0, &pMappedResource); - if(FAILED(hr) || mDevice.isError()) - { - String errorDescription; errorDescription - .append("D3D11 device cannot map ").append(toString(mParentTexture->getTextureType())) - .append("\nError Description:").append(mDevice.getErrorDescription(hr)); - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, errorDescription, "D3D11HardwarePixelBuffer::_map"); - } - - D3D11Mappings::setPixelBoxMapping(box, pMappedResource); - } - //----------------------------------------------------------------------------- - void D3D11HardwarePixelBuffer::_mapstagingbuffer(D3D11_MAP flags, PixelBox &box) - { - if(!mStagingBuffer) - createStagingBuffer(); - - if(flags == D3D11_MAP_READ_WRITE || flags == D3D11_MAP_READ) - { - D3D11_BOX boxDx11 = getSubresourceBox(mLockedBox); // both src and dest - UINT subresource = getSubresourceIndex(mLockedBox.front); - mDevice.GetImmediateContext()->CopySubresourceRegion( - mStagingBuffer.Get(), 0, boxDx11.left, boxDx11.top, boxDx11.front, - mParentTexture->getTextureResource(), subresource, &boxDx11); - } - else if(flags == D3D11_MAP_WRITE_DISCARD) - { - flags = D3D11_MAP_WRITE; // stagingbuffer doesn't support discarding - mCurrentLockOptions = HBL_WRITE_ONLY; - } - - _map(mStagingBuffer.Get(), flags, box); - } - //----------------------------------------------------------------------------- - PixelBox D3D11HardwarePixelBuffer::lockImpl(const Box &lockBox, LockOptions options) - { - // Check for misuse - if(mUsage & TU_RENDERTARGET) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "DirectX does not allow locking of or directly writing to RenderTargets. Use blitFromMemory if you need the contents.", - "D3D11HardwarePixelBuffer::lockImpl"); - - - - // Set extents and format - // Note that we do not carry over the left/top/front here, since the returned - // PixelBox will be re-based from the locking point onwards - PixelBox rval(lockBox.getWidth(), lockBox.getHeight(), lockBox.getDepth(), mFormat); - // Set locking flags according to options - D3D11_MAP flags = D3D11_MAP_WRITE_DISCARD ; - switch(options) - { - case HBL_NO_OVERWRITE: - flags = D3D11_MAP_WRITE_NO_OVERWRITE; - break; - case HBL_NORMAL: - flags = D3D11_MAP_READ_WRITE; - break; - case HBL_DISCARD: - flags = D3D11_MAP_WRITE_DISCARD; - break; - case HBL_READ_ONLY: - flags = D3D11_MAP_READ; - break; - case HBL_WRITE_ONLY: - flags = D3D11_MAP_WRITE; - break; - default: - break; - }; - - int usage = mUsage & 0xF; // drop TU_* flags - if(usage == HBU_GPU_ONLY || usage == HBU_GPU_TO_CPU || options == HBL_READ_ONLY || options == HBL_NORMAL) - _mapstagingbuffer(flags, rval); - else - _map(mParentTexture->getTextureResource(), flags, rval); - - // save without offset - mCurrentLock = rval; - - return rval; - } - //----------------------------------------------------------------------------- - void D3D11HardwarePixelBuffer::_unmap(ID3D11Resource *res) - { - UINT subresource = (res == mStagingBuffer.Get()) ? 0 : getSubresourceIndex(mLockedBox.front); - mDevice.GetImmediateContext()->Unmap(res, subresource); - - if (mDevice.isError()) - { - String errorDescription = mDevice.getErrorDescription(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "D3D11 device unmap resource\nError Description:" + errorDescription, - "D3D11HardwarePixelBuffer::_unmap"); - } - } - //----------------------------------------------------------------------------- - void D3D11HardwarePixelBuffer::_unmapstagingbuffer(bool copyback) - { - _unmap(mStagingBuffer.Get()); - - if(copyback) - { - D3D11_BOX boxDx11 = getSubresourceBox(mLockedBox); // both src and dest - UINT subresource = getSubresourceIndex(mLockedBox.front); - - mDevice.GetImmediateContext()->CopySubresourceRegion( - mParentTexture->getTextureResource(), subresource, boxDx11.left, boxDx11.top, boxDx11.front, - mStagingBuffer.Get(), 0, &boxDx11); - - mStagingBuffer.Reset(); - } - } - //----------------------------------------------------------------------------- - void D3D11HardwarePixelBuffer::unlockImpl(void) - { - int usage = mUsage & 0xF; // drop TU_* flags - if(usage == HBU_GPU_ONLY || usage == HBU_GPU_TO_CPU || mCurrentLockOptions == HBL_NORMAL || mCurrentLockOptions == HBL_READ_ONLY) - { - _unmapstagingbuffer(mCurrentLockOptions == HBL_NORMAL || mCurrentLockOptions == HBL_WRITE_ONLY); - } - else - _unmap(mParentTexture->getTextureResource()); - - _genMipmaps(); - } - //----------------------------------------------------------------------------- - void D3D11HardwarePixelBuffer::blit(const HardwarePixelBufferSharedPtr &src, const Box &srcBox, const Box &dstBox) - { - if (srcBox.getSize() != dstBox.getSize()) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "D3D11 device cannot copy a subresource - source and dest size are not the same and they have to be the same in DX11.", - "D3D11HardwarePixelBuffer::blit"); - } - - D3D11HardwarePixelBuffer * srcDx11 = static_cast(src.get()); - - // We should blit TEX_TYPE_2D_ARRAY with depth > 1 by iterating over subresources. - if (srcBox.getDepth() > 1 && - (mParentTexture->getTextureType() == TEX_TYPE_2D_ARRAY || srcDx11->mParentTexture->getTextureType() == TEX_TYPE_2D_ARRAY)) - { - Box srcSlice = srcBox, dstSlice = dstBox; - srcSlice.back = srcSlice.front + 1; - dstSlice.back = dstSlice.front + 1; - for(uint32 slice = srcBox.front; slice < srcBox.back; ++slice) - { - blit(src, srcSlice, dstSlice); // recursive call - ++srcSlice.front; ++srcSlice.back; - ++dstSlice.front; ++dstSlice.back; - } - return; - } - - // Do real work without extra checking - debug layer will catch erroneous parameters. - D3D11_BOX srcBoxDx11 = srcDx11->getSubresourceBox(srcBox); - UINT srcSubresource = srcDx11->getSubresourceIndex(srcBox.front); - D3D11_BOX dstBoxDx11 = getSubresourceBox(dstBox); - UINT dstSubresource = getSubresourceIndex(dstBox.front); - - mDevice.GetImmediateContext()->CopySubresourceRegion( - mParentTexture->getTextureResource(), dstSubresource, dstBoxDx11.left, dstBoxDx11.top, dstBoxDx11.front, - srcDx11->mParentTexture->getTextureResource(), srcSubresource, &srcBoxDx11); - - if(mDevice.isError()) - { - String errorDescription; errorDescription - .append("D3D11 device cannot copy to ").append(toString(mParentTexture->getTextureType())) - .append(" subresource region from ").append(toString(srcDx11->mParentTexture->getTextureType())) - .append("\nError Description:").append(mDevice.getErrorDescription()); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, errorDescription, "D3D11HardwarePixelBuffer::blit"); - } - - _genMipmaps(); - } - //----------------------------------------------------------------------------- - void D3D11HardwarePixelBuffer::blitFromMemory(const PixelBox &src, const Box &dst) - { - if (src.getSize() != dst.getSize()) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "D3D11 device cannot copy a subresource - source and dest size are not the same and they have to be the same in DX11.", - "D3D11HardwarePixelBuffer::blitFromMemory"); - } - - // convert to pixelbuffer's native format if necessary - if(src.format != mFormat) - { - std::vector buffer; - buffer.resize(PixelUtil::getMemorySize(src.getWidth(), src.getHeight(), src.getDepth(), mFormat)); - PixelBox converted = PixelBox(src.getWidth(), src.getHeight(), src.getDepth(), mFormat, buffer.data()); - PixelUtil::bulkPixelConversion(src, converted); - blitFromMemory(converted, dst); // recursive call - return; - } - - // We should blit TEX_TYPE_2D_ARRAY with depth > 1 by iterating over subresources. - if (src.getDepth() > 1 && mParentTexture->getTextureType() == TEX_TYPE_2D_ARRAY) - { - PixelBox srcSlice = src; - Box dstSlice = dst; - srcSlice.back = srcSlice.front + 1; - dstSlice.back = dstSlice.front + 1; - for(uint32 slice = src.front; slice < src.back; ++slice) - { - blitFromMemory(srcSlice, dstSlice); // recursive call - ++srcSlice.front; ++srcSlice.back; - ++dstSlice.front; ++dstSlice.back; - } - return; - } - - // Do the real work - if (mUsage & HBU_DYNAMIC) // i.e. UpdateSubresource can not be used - { - Ogre::PixelBox locked = lock(dst, HBL_DISCARD); - PixelUtil::bulkPixelConversion(src, locked); // compressed formats are handled using per slice granularity, pitches are honoured - unlock(); - } - else - { - D3D11_BOX dstBox = getSubresourceBox(dst); - UINT dstSubresource = getSubresourceIndex(dst.front); - UINT srcRowPitch = PixelUtil::getMemorySize(src.getWidth(), 1, 1, src.format); - UINT srcDepthPitch = PixelUtil::getMemorySize(src.getWidth(), src.getHeight(), 1, src.format); // H * rowPitch is invalid for compressed formats - - mDevice.GetImmediateContext()->UpdateSubresource( - mParentTexture->getTextureResource(), dstSubresource, &dstBox, - src.getTopLeftFrontPixelPtr(), srcRowPitch, srcDepthPitch); - } - - if(mDevice.isError()) - { - String errorDescription; errorDescription - .append("D3D11 device cannot update ").append(toString(mParentTexture->getTextureType())) - .append("\nError Description:").append(mDevice.getErrorDescription()); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, errorDescription, "D3D11HardwarePixelBuffer::blitFromMemory"); - } - - _genMipmaps(); - } - //----------------------------------------------------------------------------- - void D3D11HardwarePixelBuffer::blitToMemory(const Box &srcBox, const PixelBox &dst) - { - assert(srcBox.getDepth() == 1 && dst.getDepth() == 1); - - //This is a pointer to the texture we're trying to copy - //Only implemented for 2D at the moment... - ID3D11Texture2D *texture = mParentTexture->GetTex2D(); - HRESULT hr = texture ? S_OK : E_INVALIDARG; - mDevice.throwIfFailed(hr, "blitToMemory is implemented only for 2D textures", "D3D11HardwarePixelBuffer::blitToMemory"); - - // get the description of the texture - D3D11_TEXTURE2D_DESC desc = {0}; - texture->GetDesc( &desc ); - UINT srcSubresource = getSubresourceIndex(srcBox.front); // one face of cubemap, one item of array - D3D11_BOX srcBoxDx11 = getSubresourceBox(srcBox); - - // MSAA content must be resolved before being copied to a staging texture - ComPtr textureNoMSAA; - if(desc.SampleDesc.Count == 1) - { - textureNoMSAA = texture; - } - else - { - // Note - we create textureNoMSAA with all mip levels of parent texture (not good), but will resolve only required one. - desc.SampleDesc.Count = 1; - desc.SampleDesc.Quality = 0; - - hr = mDevice->CreateTexture2D(&desc, NULL, textureNoMSAA.ReleaseAndGetAddressOf()); - mDevice.throwIfFailed(hr, "Error creating texture without MSAA", "D3D11HardwarePixelBuffer::blitToMemory"); - - mDevice.GetImmediateContext()->ResolveSubresource(textureNoMSAA.Get(), srcSubresource, texture, srcSubresource, desc.Format); - mDevice.throwIfFailed("Error resolving MSAA subresource", "D3D11HardwarePixelBuffer::blitToMemory"); - } - - // Create the staging texture - ComPtr stagingTexture; - if(desc.Usage == D3D11_USAGE_STAGING && (desc.CPUAccessFlags & D3D11_CPU_ACCESS_READ)) - { - stagingTexture.Swap(textureNoMSAA); // Handle case where the source is already a staging texture we can use directly - } - else - { - desc.Usage = D3D11_USAGE_STAGING; - desc.BindFlags = 0; - desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; - desc.MiscFlags &= D3D11_RESOURCE_MISC_TEXTURECUBE; - hr = mDevice->CreateTexture2D(&desc, NULL, stagingTexture.ReleaseAndGetAddressOf()); - mDevice.throwIfFailed(hr, "Error creating staging texture", "D3D11HardwarePixelBuffer::blitToMemory"); - - // Copy our texture into the staging texture - mDevice.GetImmediateContext()->CopySubresourceRegion( - stagingTexture.Get(), srcSubresource, srcBoxDx11.left, srcBoxDx11.top, srcBoxDx11.front, - textureNoMSAA.Get(), srcSubresource, &srcBoxDx11); - mDevice.throwIfFailed("Error while copying to staging texture", "D3D11HardwarePixelBuffer::blitToMemory"); - } - - // Map the subresource of the staging texture - D3D11_MAPPED_SUBRESOURCE mapped = {0}; - hr = mDevice.GetImmediateContext()->Map(stagingTexture.Get(), srcSubresource, D3D11_MAP_READ, 0, &mapped); - mDevice.throwIfFailed(hr, "Error while mapping staging texture", "D3D11HardwarePixelBuffer::blitToMemory"); - - // Read the data out of the texture. - PixelBox locked = D3D11Mappings::getPixelBoxWithMapping(srcBoxDx11, desc.Format, mapped); - PixelUtil::bulkPixelConversion(locked, dst); - - // Release the staging texture - mDevice.GetImmediateContext()->Unmap(stagingTexture.Get(), srcSubresource); - } - - //----------------------------------------------------------------------------- - void D3D11HardwarePixelBuffer::_genMipmaps() - { - if(mParentTexture->HasAutoMipMapGenerationEnabled()) - { - ID3D11ShaderResourceView *pShaderResourceView = mParentTexture->getSrvView(); - ID3D11DeviceContextN * context = mDevice.GetImmediateContext(); - context->GenerateMips(pShaderResourceView); - if (mDevice.isError()) - { - String errorDescription = mDevice.getErrorDescription(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "D3D11 device cannot generate mips\nError Description:" + errorDescription, - "D3D11HardwarePixelBuffer::_genMipmaps"); - } - } - - } - //----------------------------------------------------------------------------- - D3D11Texture * D3D11HardwarePixelBuffer::getParentTexture() const - { - return mParentTexture; - } - //----------------------------------------------------------------------------- - UINT D3D11HardwarePixelBuffer::getSubresourceIndex(size_t box_front) const - { - switch(mParentTexture->getTextureType()) - { - case TEX_TYPE_CUBE_MAP: return D3D11CalcSubresource(mMipLevel, mFace, mParentTexture->getNumMipmaps() + 1); - case TEX_TYPE_2D_ARRAY: return D3D11CalcSubresource(mMipLevel, box_front, mParentTexture->getNumMipmaps() + 1); - } - return mMipLevel; - } - //----------------------------------------------------------------------------- - D3D11_BOX D3D11HardwarePixelBuffer::getSubresourceBox(const Box &inBox) const - { - // Ogre index Tex2DArray using Z component of the box, but Direct3D expect - // this index to be in subresource, and Z component should be sanitized - bool is2DArray = (mParentTexture->getTextureType() == TEX_TYPE_2D_ARRAY); - - D3D11_BOX res; - res.left = static_cast(inBox.left); - res.top = static_cast(inBox.top); - res.front = is2DArray ? 0 : static_cast(inBox.front); - res.right = static_cast(inBox.right); - res.bottom = static_cast(inBox.bottom); - res.back = is2DArray ? 1 : static_cast(inBox.back); - return res; - } - //----------------------------------------------------------------------------- - UINT D3D11HardwarePixelBuffer::getFace() const - { - return mFace; - } - //----------------------------------------------------------------------------- - void D3D11HardwarePixelBuffer::createStagingBuffer() - { - D3D11Texture *tex = static_cast(mParentTexture); - - switch (mParentTexture->getTextureType()) - { - case TEX_TYPE_1D: - { - D3D11_TEXTURE1D_DESC desc; - tex->GetTex1D()->GetDesc(&desc); - - desc.Width = mWidth; - desc.MipLevels = 0; - desc.BindFlags = 0; - desc.MiscFlags = 0; - desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ; - desc.Usage = D3D11_USAGE_STAGING; - - mDevice->CreateTexture1D(&desc, NULL, (ID3D11Texture1D**)mStagingBuffer.ReleaseAndGetAddressOf()); - } - break; - case TEX_TYPE_2D: - case TEX_TYPE_CUBE_MAP: - case TEX_TYPE_2D_ARRAY: - { - D3D11_TEXTURE2D_DESC desc; - tex->GetTex2D()->GetDesc(&desc); - - desc.Width = mWidth; - desc.Height = mHeight; - desc.MipLevels = 0; - desc.BindFlags = 0; - desc.MiscFlags = 0; - desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ; - desc.Usage = D3D11_USAGE_STAGING; - - mDevice->CreateTexture2D(&desc, NULL, (ID3D11Texture2D**)mStagingBuffer.ReleaseAndGetAddressOf()); - } - break; - case TEX_TYPE_3D: - { - D3D11_TEXTURE3D_DESC desc; - tex->GetTex3D()->GetDesc(&desc); - - desc.Width = mWidth; - desc.Height = mHeight; - desc.Depth = mDepth; - desc.MipLevels = 0; - desc.BindFlags = 0; - desc.MiscFlags = 0; - desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ; - desc.Usage = D3D11_USAGE_STAGING; - - mDevice->CreateTexture3D(&desc, NULL, (ID3D11Texture3D**)mStagingBuffer.ReleaseAndGetAddressOf()); - } - break; - } - } -}; diff --git a/RenderSystems/Direct3D11/src/OgreD3D11Mappings.cpp b/RenderSystems/Direct3D11/src/OgreD3D11Mappings.cpp deleted file mode 100644 index 430af2e2cac..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11Mappings.cpp +++ /dev/null @@ -1,775 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11Mappings.h" -#include "OgreD3D11RenderSystem.h" -#include "OgreRoot.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - D3D11_TEXTURE_ADDRESS_MODE D3D11Mappings::get(TextureAddressingMode tam) - { - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - if (rsys->_getFeatureLevel() == D3D_FEATURE_LEVEL_9_1) - return D3D11_TEXTURE_ADDRESS_WRAP; - - //return D3D11_TEXTURE_ADDRESS_WRAP; - switch( tam ) - { - case TextureUnitState::TAM_WRAP: - return D3D11_TEXTURE_ADDRESS_WRAP; - case TextureUnitState::TAM_MIRROR: - return D3D11_TEXTURE_ADDRESS_MIRROR; - case TextureUnitState::TAM_CLAMP: - return D3D11_TEXTURE_ADDRESS_CLAMP; - case TextureUnitState::TAM_BORDER: - return D3D11_TEXTURE_ADDRESS_BORDER; - } - return D3D11_TEXTURE_ADDRESS_WRAP; - } - //--------------------------------------------------------------------- - D3D11_BLEND D3D11Mappings::get(SceneBlendFactor sbf, bool forAlpha) - { - switch( sbf ) - { - case SBF_ONE: return D3D11_BLEND_ONE; - case SBF_ZERO: return D3D11_BLEND_ZERO; - case SBF_DEST_COLOUR: return forAlpha ? D3D11_BLEND_DEST_ALPHA : D3D11_BLEND_DEST_COLOR; - case SBF_SOURCE_COLOUR: return forAlpha ? D3D11_BLEND_SRC_ALPHA : D3D11_BLEND_SRC_COLOR; - case SBF_ONE_MINUS_DEST_COLOUR: return forAlpha ? D3D11_BLEND_INV_DEST_ALPHA : D3D11_BLEND_INV_DEST_COLOR; - case SBF_ONE_MINUS_SOURCE_COLOUR: return forAlpha ? D3D11_BLEND_INV_SRC_ALPHA : D3D11_BLEND_INV_SRC_COLOR; - case SBF_DEST_ALPHA: return D3D11_BLEND_DEST_ALPHA; - case SBF_SOURCE_ALPHA: return D3D11_BLEND_SRC_ALPHA; - case SBF_ONE_MINUS_DEST_ALPHA: return D3D11_BLEND_INV_DEST_ALPHA; - case SBF_ONE_MINUS_SOURCE_ALPHA: return D3D11_BLEND_INV_SRC_ALPHA; - } - return D3D11_BLEND_ZERO; - } - //--------------------------------------------------------------------- - D3D11_BLEND_OP D3D11Mappings::get(SceneBlendOperation sbo) - { - switch( sbo ) - { - case SBO_ADD: - return D3D11_BLEND_OP_ADD; - case SBO_SUBTRACT: - return D3D11_BLEND_OP_SUBTRACT; - case SBO_REVERSE_SUBTRACT: - return D3D11_BLEND_OP_REV_SUBTRACT; - case SBO_MIN: - return D3D11_BLEND_OP_MIN; - case SBO_MAX: - return D3D11_BLEND_OP_MAX; - } - return D3D11_BLEND_OP_ADD; - } - //--------------------------------------------------------------------- - D3D11_COMPARISON_FUNC D3D11Mappings::get(CompareFunction cf) - { - switch( cf ) - { - case CMPF_ALWAYS_FAIL: - return D3D11_COMPARISON_NEVER; - case CMPF_ALWAYS_PASS: - return D3D11_COMPARISON_ALWAYS; - case CMPF_LESS: - return D3D11_COMPARISON_LESS; - case CMPF_LESS_EQUAL: - return D3D11_COMPARISON_LESS_EQUAL; - case CMPF_EQUAL: - return D3D11_COMPARISON_EQUAL; - case CMPF_NOT_EQUAL: - return D3D11_COMPARISON_NOT_EQUAL; - case CMPF_GREATER_EQUAL: - return D3D11_COMPARISON_GREATER_EQUAL; - case CMPF_GREATER: - return D3D11_COMPARISON_GREATER; - }; - return D3D11_COMPARISON_ALWAYS; - } - //--------------------------------------------------------------------- - D3D11_CULL_MODE D3D11Mappings::get(CullingMode cm, bool flip) - { - switch( cm ) - { - case CULL_NONE: - return D3D11_CULL_NONE; - case CULL_CLOCKWISE: - return flip ? D3D11_CULL_FRONT : D3D11_CULL_BACK; - case CULL_ANTICLOCKWISE: - return flip ? D3D11_CULL_BACK : D3D11_CULL_FRONT; - } - return D3D11_CULL_NONE; - } - //--------------------------------------------------------------------- - D3D11_FILL_MODE D3D11Mappings::get(PolygonMode level) - { - switch(level) - { - case PM_POINTS: - return D3D11_FILL_SOLID; - case PM_WIREFRAME: - return D3D11_FILL_WIREFRAME; - case PM_SOLID: - return D3D11_FILL_SOLID; - } - return D3D11_FILL_SOLID; - } - //--------------------------------------------------------------------- - D3D11_STENCIL_OP D3D11Mappings::get(StencilOperation op, bool invert) - { - switch(op) - { - case SOP_KEEP: - return D3D11_STENCIL_OP_KEEP; - case SOP_ZERO: - return D3D11_STENCIL_OP_ZERO; - case SOP_REPLACE: - return D3D11_STENCIL_OP_REPLACE; - case SOP_INCREMENT: - return invert? D3D11_STENCIL_OP_DECR_SAT : D3D11_STENCIL_OP_INCR_SAT; - case SOP_DECREMENT: - return invert? D3D11_STENCIL_OP_INCR_SAT : D3D11_STENCIL_OP_DECR_SAT; - case SOP_INCREMENT_WRAP: - return invert? D3D11_STENCIL_OP_DECR : D3D11_STENCIL_OP_INCR; - case SOP_DECREMENT_WRAP: - return invert? D3D11_STENCIL_OP_INCR : D3D11_STENCIL_OP_DECR; - case SOP_INVERT: - return D3D11_STENCIL_OP_INVERT; - } - return D3D11_STENCIL_OP_KEEP; - } - //--------------------------------------------------------------------- - D3D11_FILTER D3D11Mappings::get(const FilterOptions min, const FilterOptions mag, const FilterOptions mip, const bool comparison) - { - // anisotropic means trilinear and anisotropic, handle this case early - if(min == FO_ANISOTROPIC || mag == FO_ANISOTROPIC || mip == FO_ANISOTROPIC) - return comparison ? D3D11_FILTER_COMPARISON_ANISOTROPIC : D3D11_FILTER_ANISOTROPIC; - - // FilterOptions::FO_NONE is not supported -#define MERGE_FOR_SWITCH(_comparison_, _min_ , _mag_, _mip_ ) ((_comparison_ ? 8 : 0) | (_min_ == FO_LINEAR ? 4 : 0) | (_mag_ == FO_LINEAR ? 2 : 0) | (_mip_ == FO_LINEAR ? 1 : 0)) - switch((MERGE_FOR_SWITCH(comparison, min, mag, mip))) - { - case MERGE_FOR_SWITCH(true, FO_POINT, FO_POINT, FO_POINT): - return D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT; - case MERGE_FOR_SWITCH(true, FO_POINT, FO_POINT, FO_LINEAR): - return D3D11_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR; - case MERGE_FOR_SWITCH(true, FO_POINT, FO_LINEAR, FO_POINT): - return D3D11_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT; - case MERGE_FOR_SWITCH(true, FO_POINT, FO_LINEAR, FO_LINEAR): - return D3D11_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR; - case MERGE_FOR_SWITCH(true, FO_LINEAR, FO_POINT, FO_POINT): - return D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT; - case MERGE_FOR_SWITCH(true, FO_LINEAR, FO_POINT, FO_LINEAR): - return D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR; - case MERGE_FOR_SWITCH(true, FO_LINEAR, FO_LINEAR, FO_POINT): - return D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT; - case MERGE_FOR_SWITCH(true, FO_LINEAR, FO_LINEAR, FO_LINEAR): - return D3D11_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR; - case MERGE_FOR_SWITCH(false, FO_POINT, FO_POINT, FO_POINT): - return D3D11_FILTER_MIN_MAG_MIP_POINT; - case MERGE_FOR_SWITCH(false, FO_POINT, FO_POINT, FO_LINEAR): - return D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR; - case MERGE_FOR_SWITCH(false, FO_POINT, FO_LINEAR, FO_POINT): - return D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT; - case MERGE_FOR_SWITCH(false, FO_POINT, FO_LINEAR, FO_LINEAR): - return D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR; - case MERGE_FOR_SWITCH(false, FO_LINEAR, FO_POINT, FO_POINT): - return D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT; - case MERGE_FOR_SWITCH(false, FO_LINEAR, FO_POINT, FO_LINEAR): - return D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR; - case MERGE_FOR_SWITCH(false, FO_LINEAR, FO_LINEAR, FO_POINT): - return D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT; - case MERGE_FOR_SWITCH(false, FO_LINEAR, FO_LINEAR, FO_LINEAR): - return D3D11_FILTER_MIN_MAG_MIP_LINEAR; - } -#undef MERGE_FOR_SWITCH - - return D3D11_FILTER_MIN_MAG_MIP_LINEAR; - } - //--------------------------------------------------------------------- - D3D11_MAP D3D11Mappings::get(HardwareBuffer::LockOptions options, HardwareBuffer::Usage usage) - { - D3D11_MAP ret = D3D11_MAP_READ_WRITE; - if (options == HardwareBuffer::HBL_DISCARD) - { - // D3D doesn't like discard or no_overwrite on non-dynamic buffers - if (usage & HardwareBuffer::HBU_DYNAMIC) - ret = D3D11_MAP_WRITE_DISCARD; - } - if (options == HardwareBuffer::HBL_READ_ONLY) - { - // D3D debug runtime doesn't like you locking managed buffers readonly - // when they were created with write-only (even though you CAN read - // from the software backed version) - if (!(usage & HBU_DETAIL_WRITE_ONLY)) - ret = D3D11_MAP_READ; - - } - if (options == HardwareBuffer::HBL_NO_OVERWRITE) - { - // D3D doesn't like discard or no_overwrite on non-dynamic buffers - if (usage & HardwareBuffer::HBU_DYNAMIC) - ret = D3D11_MAP_WRITE_NO_OVERWRITE; - } - - return ret; - } - //--------------------------------------------------------------------- - void D3D11Mappings::setPixelBoxMapping(PixelBox& box, const D3D11_MAPPED_SUBRESOURCE& mapping) - { - // The main issue - pitches D3D11 are in bytes, but Ogre stores them in elements, therefore conversion is required - size_t elemSize = PixelUtil::getNumElemBytes(box.format); - if(elemSize != 0) - { - assert(0 == mapping.RowPitch % elemSize); - assert(0 == mapping.DepthPitch % elemSize); - box.rowPitch = mapping.RowPitch / elemSize; - box.slicePitch = mapping.DepthPitch / elemSize; - } - else if(PixelUtil::isCompressed(box.format)) - { - box.rowPitch = box.getWidth(); - box.slicePitch = box.getWidth() * box.getHeight(); - } - else - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Invalid pixel format", "setPixelBoxMapping"); - } - box.data = (uchar*)mapping.pData; - } - //--------------------------------------------------------------------- - PixelBox D3D11Mappings::getPixelBoxWithMapping(D3D11_BOX extents, DXGI_FORMAT pixelFormat, const D3D11_MAPPED_SUBRESOURCE& mapping) - { - PixelBox box(Box(extents.left, extents.top, extents.front, extents.right, extents.bottom, extents.back), _getPF(pixelFormat)); - setPixelBoxMapping(box, mapping); - return box; - } - //--------------------------------------------------------------------- - DXGI_FORMAT D3D11Mappings::getFormat(HardwareIndexBuffer::IndexType itype) - { - return itype == HardwareIndexBuffer::IT_32BIT ? DXGI_FORMAT_R32_UINT : DXGI_FORMAT_R16_UINT; - } - //--------------------------------------------------------------------- - DXGI_FORMAT D3D11Mappings::get(VertexElementType vType) - { - switch (vType) - { - // Float32 - case VET_FLOAT1: - return DXGI_FORMAT_R32_FLOAT; - case VET_FLOAT2: - return DXGI_FORMAT_R32G32_FLOAT; - case VET_FLOAT3: - return DXGI_FORMAT_R32G32B32_FLOAT; - case VET_FLOAT4: - return DXGI_FORMAT_R32G32B32A32_FLOAT; - - // Signed short - case VET_SHORT1: - return DXGI_FORMAT_R16_SINT; - case VET_SHORT2: - return DXGI_FORMAT_R16G16_SINT; - case VET_SHORT4: - return DXGI_FORMAT_R16G16B16A16_SINT; - case VET_SHORT2_NORM: - return DXGI_FORMAT_R16G16_SNORM; - case VET_SHORT4_NORM: - return DXGI_FORMAT_R16G16B16A16_SNORM; - - // Unsigned short - case VET_USHORT1: - return DXGI_FORMAT_R16_UINT; - case VET_USHORT2: - return DXGI_FORMAT_R16G16_UINT; - case VET_USHORT4: - return DXGI_FORMAT_R16G16B16A16_UINT; - case VET_USHORT2_NORM: - return DXGI_FORMAT_R16G16_UNORM; - case VET_USHORT4_NORM: - return DXGI_FORMAT_R16G16B16A16_UNORM; - - // Signed int - case VET_INT1: - return DXGI_FORMAT_R32_SINT; - case VET_INT2: - return DXGI_FORMAT_R32G32_SINT; - case VET_INT3: - return DXGI_FORMAT_R32G32B32_SINT; - case VET_INT4: - return DXGI_FORMAT_R32G32B32A32_SINT; - - // Unsigned int - case VET_UINT1: - return DXGI_FORMAT_R32_UINT; - case VET_UINT2: - return DXGI_FORMAT_R32G32_UINT; - case VET_UINT3: - return DXGI_FORMAT_R32G32B32_UINT; - case VET_UINT4: - return DXGI_FORMAT_R32G32B32A32_UINT; - - case VET_BYTE4: - return DXGI_FORMAT_R8G8B8A8_SINT; - case VET_BYTE4_NORM: - return DXGI_FORMAT_R8G8B8A8_SNORM; - case VET_UBYTE4: - return DXGI_FORMAT_R8G8B8A8_UINT; - case VET_UBYTE4_NORM: - return DXGI_FORMAT_R8G8B8A8_UNORM; - } - // to keep compiler happy - return DXGI_FORMAT_R32G32B32_FLOAT; - } - //--------------------------------------------------------------------- - VertexElementSemantic D3D11Mappings::get(LPCSTR sem) - { - // todo - add to ogre - POSITIONT and PSIZE ("Transformed vertex position" and "Point size") - - if( strcmp(sem, "BLENDINDICES") == 0 ) - return VES_BLEND_INDICES; - if( strcmp(sem, "BLENDWEIGHT") == 0 ) - return VES_BLEND_WEIGHTS; - if( strcmp(sem, "COLOR") == 0 ) - return VES_DIFFUSE; -// if( strcmp(sem, "COLOR") == 0 ) -// return VES_SPECULAR; - if( strcmp(sem, "NORMAL") == 0 ) - return VES_NORMAL; - if( strcmp(sem, "POSITION") == 0 ) - return VES_POSITION; - if( strcmp(sem, "TEXCOORD") == 0 ) - return VES_TEXTURE_COORDINATES; - if( strcmp(sem, "BINORMAL") == 0 ) - return VES_BINORMAL; - if( strcmp(sem, "TANGENT") == 0 ) - return VES_TANGENT; - - // to keep compiler happy - return VES_POSITION; - } - //--------------------------------------------------------------------- - LPCSTR D3D11Mappings::get(VertexElementSemantic sem) - { - // todo - add to ogre - POSITIONT and PSIZE ("Transformed vertex position" and "Point size") - switch (sem) - { - case VES_BLEND_INDICES: - return "BLENDINDICES"; - case VES_BLEND_WEIGHTS: - return "BLENDWEIGHT"; - case VES_DIFFUSE: - return "COLOR"; // NB index will differentiate - case VES_SPECULAR: - return "COLOR"; // NB index will differentiate - case VES_NORMAL: - return "NORMAL"; - case VES_POSITION: - return "POSITION"; - case VES_TEXTURE_COORDINATES: - return "TEXCOORD"; - case VES_BINORMAL: - return "BINORMAL"; - case VES_TANGENT: - return "TANGENT"; - } - // to keep compiler happy - return ""; - } - //--------------------------------------------------------------------- - PixelFormat D3D11Mappings::_getPF(DXGI_FORMAT d3dPF) - { - switch(d3dPF) - { - case DXGI_FORMAT_UNKNOWN: return PF_UNKNOWN; - case DXGI_FORMAT_R32G32B32A32_TYPELESS: return PF_UNKNOWN; - case DXGI_FORMAT_R32G32B32A32_FLOAT: return PF_FLOAT32_RGBA; - case DXGI_FORMAT_R32G32B32A32_UINT: return PF_UNKNOWN; - case DXGI_FORMAT_R32G32B32A32_SINT: return PF_UNKNOWN; - case DXGI_FORMAT_R32G32B32_TYPELESS: return PF_UNKNOWN; - case DXGI_FORMAT_R32G32B32_FLOAT: return PF_FLOAT32_RGB; - case DXGI_FORMAT_R32G32B32_UINT: return PF_UNKNOWN; - case DXGI_FORMAT_R32G32B32_SINT: return PF_UNKNOWN; - case DXGI_FORMAT_R16G16B16A16_TYPELESS: return PF_UNKNOWN; - case DXGI_FORMAT_R16G16B16A16_FLOAT: return PF_FLOAT16_RGBA; - case DXGI_FORMAT_R16G16B16A16_UNORM: return PF_SHORT_RGBA; - case DXGI_FORMAT_R16G16B16A16_UINT: return PF_UNKNOWN; - case DXGI_FORMAT_R16G16B16A16_SNORM: return PF_UNKNOWN; - case DXGI_FORMAT_R16G16B16A16_SINT: return PF_UNKNOWN; - case DXGI_FORMAT_R32G32_TYPELESS: return PF_UNKNOWN; - case DXGI_FORMAT_R32G32_FLOAT: return PF_FLOAT32_GR; - case DXGI_FORMAT_R32G32_UINT: return PF_UNKNOWN; - case DXGI_FORMAT_R32G32_SINT: return PF_UNKNOWN; - case DXGI_FORMAT_R32G8X24_TYPELESS: return PF_UNKNOWN; - case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: return PF_UNKNOWN; - case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: return PF_UNKNOWN; - case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: return PF_UNKNOWN; - case DXGI_FORMAT_R10G10B10A2_TYPELESS: return PF_UNKNOWN; - case DXGI_FORMAT_R10G10B10A2_UNORM: return PF_A2B10G10R10; - case DXGI_FORMAT_R10G10B10A2_UINT: return PF_UNKNOWN; - case DXGI_FORMAT_R11G11B10_FLOAT: return PF_R11G11B10_FLOAT; - case DXGI_FORMAT_R8G8B8A8_TYPELESS: return PF_UNKNOWN; - case DXGI_FORMAT_R8G8B8A8_UNORM: return PF_A8B8G8R8; - case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return PF_A8B8G8R8; - case DXGI_FORMAT_R8G8B8A8_UINT: return PF_UNKNOWN; - case DXGI_FORMAT_R8G8B8A8_SNORM: return PF_UNKNOWN; - case DXGI_FORMAT_R8G8B8A8_SINT: return PF_UNKNOWN; - case DXGI_FORMAT_R16G16_TYPELESS: return PF_UNKNOWN; - case DXGI_FORMAT_R16G16_FLOAT: return PF_FLOAT16_GR; - case DXGI_FORMAT_R16G16_UNORM: return PF_SHORT_GR; - case DXGI_FORMAT_R16G16_UINT: return PF_UNKNOWN; - case DXGI_FORMAT_R16G16_SNORM: return PF_UNKNOWN; - case DXGI_FORMAT_R16G16_SINT: return PF_R16G16_SINT; - case DXGI_FORMAT_R32_TYPELESS: return PF_DEPTH32; - case DXGI_FORMAT_D32_FLOAT: return PF_DEPTH32F; - case DXGI_FORMAT_R32_FLOAT: return PF_FLOAT32_R; - case DXGI_FORMAT_R32_UINT: return PF_UNKNOWN; - case DXGI_FORMAT_R32_SINT: return PF_UNKNOWN; - case DXGI_FORMAT_R24G8_TYPELESS: return PF_UNKNOWN; - case DXGI_FORMAT_D24_UNORM_S8_UINT: return PF_DEPTH24_STENCIL8; - case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: return PF_UNKNOWN; - case DXGI_FORMAT_X24_TYPELESS_G8_UINT: return PF_UNKNOWN; - case DXGI_FORMAT_R8G8_TYPELESS: return PF_UNKNOWN; - case DXGI_FORMAT_R8G8_UNORM: return PF_UNKNOWN; - case DXGI_FORMAT_R8G8_UINT: return PF_UNKNOWN; - case DXGI_FORMAT_R8G8_SNORM: return PF_UNKNOWN; - case DXGI_FORMAT_R8G8_SINT: return PF_UNKNOWN; - case DXGI_FORMAT_R16_TYPELESS: return PF_UNKNOWN; - case DXGI_FORMAT_R16_FLOAT: return PF_FLOAT16_R; - case DXGI_FORMAT_D16_UNORM: return PF_DEPTH16; - case DXGI_FORMAT_R16_UNORM: return PF_L16; - case DXGI_FORMAT_R16_UINT: return PF_UNKNOWN; - case DXGI_FORMAT_R16_SNORM: return PF_UNKNOWN; - case DXGI_FORMAT_R16_SINT: return PF_UNKNOWN; - case DXGI_FORMAT_R8_TYPELESS: return PF_UNKNOWN; - case DXGI_FORMAT_R8_UNORM: return PF_R8; - case DXGI_FORMAT_R8_UINT: return PF_UNKNOWN; - case DXGI_FORMAT_R8_SNORM: return PF_UNKNOWN; - case DXGI_FORMAT_R8_SINT: return PF_UNKNOWN; - case DXGI_FORMAT_A8_UNORM: return PF_A8; - case DXGI_FORMAT_R1_UNORM: return PF_UNKNOWN; - case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: return PF_UNKNOWN; - case DXGI_FORMAT_R8G8_B8G8_UNORM: return PF_UNKNOWN; - case DXGI_FORMAT_G8R8_G8B8_UNORM: return PF_UNKNOWN; - case DXGI_FORMAT_BC1_TYPELESS: return PF_DXT1; - case DXGI_FORMAT_BC1_UNORM: return PF_DXT1; - case DXGI_FORMAT_BC1_UNORM_SRGB: return PF_DXT1; - case DXGI_FORMAT_BC2_TYPELESS: return PF_DXT3; - case DXGI_FORMAT_BC2_UNORM: return PF_DXT3; - case DXGI_FORMAT_BC2_UNORM_SRGB: return PF_DXT3; - case DXGI_FORMAT_BC3_TYPELESS: return PF_DXT5; - case DXGI_FORMAT_BC3_UNORM: return PF_DXT5; - case DXGI_FORMAT_BC3_UNORM_SRGB: return PF_DXT5; - case DXGI_FORMAT_BC4_TYPELESS: return PF_BC4_UNORM; - case DXGI_FORMAT_BC4_UNORM: return PF_BC4_UNORM; - case DXGI_FORMAT_BC4_SNORM: return PF_BC4_SNORM; - case DXGI_FORMAT_BC5_TYPELESS: return PF_BC5_UNORM; - case DXGI_FORMAT_BC5_UNORM: return PF_BC5_UNORM; - case DXGI_FORMAT_BC5_SNORM: return PF_BC5_SNORM; - case DXGI_FORMAT_B5G6R5_UNORM: return PF_R5G6B5; - case DXGI_FORMAT_B5G5R5A1_UNORM: return PF_A1R5G5B5; - case DXGI_FORMAT_B8G8R8A8_UNORM: return PF_A8R8G8B8; - case DXGI_FORMAT_B8G8R8X8_UNORM: return PF_X8R8G8B8; - case DXGI_FORMAT_BC6H_TYPELESS: return PF_BC6H_SF16; - case DXGI_FORMAT_BC6H_UF16: return PF_BC6H_UF16; - case DXGI_FORMAT_BC6H_SF16: return PF_BC6H_SF16; - case DXGI_FORMAT_BC7_TYPELESS: return PF_BC7_UNORM; - case DXGI_FORMAT_BC7_UNORM: return PF_BC7_UNORM; - case DXGI_FORMAT_BC7_UNORM_SRGB: return PF_BC7_UNORM; - -#if defined(_WIN32_WINNT_WIN8) && (_WIN32_WINNT >= _WIN32_WINNT_WIN8) && defined(DXGI_FORMAT_AYUV) - case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM:return PF_UNKNOWN; - case DXGI_FORMAT_B8G8R8A8_TYPELESS: return PF_UNKNOWN; - case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return PF_A8R8G8B8; - case DXGI_FORMAT_B8G8R8X8_TYPELESS: return PF_UNKNOWN; - case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: return PF_X8R8G8B8; - case DXGI_FORMAT_AYUV: return PF_UNKNOWN; - case DXGI_FORMAT_Y410: return PF_UNKNOWN; - case DXGI_FORMAT_Y416: return PF_UNKNOWN; - case DXGI_FORMAT_NV12: return PF_UNKNOWN; - case DXGI_FORMAT_P010: return PF_UNKNOWN; - case DXGI_FORMAT_P016: return PF_UNKNOWN; - case DXGI_FORMAT_420_OPAQUE: return PF_UNKNOWN; - case DXGI_FORMAT_YUY2: return PF_UNKNOWN; - case DXGI_FORMAT_Y210: return PF_UNKNOWN; - case DXGI_FORMAT_Y216: return PF_UNKNOWN; - case DXGI_FORMAT_NV11: return PF_UNKNOWN; - case DXGI_FORMAT_AI44: return PF_UNKNOWN; - case DXGI_FORMAT_IA44: return PF_UNKNOWN; - case DXGI_FORMAT_P8: return PF_UNKNOWN; - case DXGI_FORMAT_A8P8: return PF_UNKNOWN; - case DXGI_FORMAT_B4G4R4A4_UNORM: return PF_A4R4G4B4; -#endif - - default: return PF_UNKNOWN; - } - } - //--------------------------------------------------------------------- - DXGI_FORMAT D3D11Mappings::_getPF(PixelFormat ogrePF) - { - // PF_L8 maps to DXGI_FORMAT_R8_UNORM and grayscale textures became "redscale", without green and blue components. - // This can be fixed by shader modification, but here we can only convert PF_L8 to PF_A8B8G8R8 manually to fix the issue. - // Note, that you can use PF_R8 to explicitly request "redscale" behavior for grayscale textures, avoiding overhead. - switch(ogrePF) - { - case PF_R8: return DXGI_FORMAT_R8_UNORM; - case PF_L16: return DXGI_FORMAT_R16_UNORM; - case PF_A8: return DXGI_FORMAT_A8_UNORM; - case PF_BYTE_LA: return DXGI_FORMAT_UNKNOWN; - case PF_R3G3B2: return DXGI_FORMAT_UNKNOWN; - case PF_A1R5G5B5: return DXGI_FORMAT_UNKNOWN; - case PF_R5G6B5: return DXGI_FORMAT_UNKNOWN; - case PF_A4R4G4B4: return DXGI_FORMAT_UNKNOWN; - case PF_R8G8B8: return DXGI_FORMAT_UNKNOWN; - case PF_A8R8G8B8: return DXGI_FORMAT_B8G8R8A8_UNORM; - case PF_A8B8G8R8: return DXGI_FORMAT_R8G8B8A8_UNORM; - case PF_X8R8G8B8: return DXGI_FORMAT_B8G8R8X8_UNORM; - case PF_X8B8G8R8: return DXGI_FORMAT_UNKNOWN; - case PF_A2B10G10R10: return DXGI_FORMAT_R10G10B10A2_TYPELESS; - case PF_A2R10G10B10: return DXGI_FORMAT_UNKNOWN; - case PF_R11G11B10_FLOAT:return DXGI_FORMAT_R11G11B10_FLOAT; - case PF_FLOAT16_R: return DXGI_FORMAT_R16_FLOAT; - case PF_FLOAT16_GR: return DXGI_FORMAT_R16G16_FLOAT; - case PF_FLOAT16_RGBA: return DXGI_FORMAT_R16G16B16A16_FLOAT; - case PF_FLOAT32_R: return DXGI_FORMAT_R32_FLOAT; - case PF_FLOAT32_RGBA: return DXGI_FORMAT_R32G32B32A32_FLOAT; - case PF_SHORT_RGBA: return DXGI_FORMAT_R16G16B16A16_UNORM; - case PF_DXT1: return DXGI_FORMAT_BC1_UNORM; - case PF_DXT2: return DXGI_FORMAT_BC1_UNORM; - case PF_DXT3: return DXGI_FORMAT_BC2_UNORM; - case PF_DXT4: return DXGI_FORMAT_BC2_UNORM; - case PF_DXT5: return DXGI_FORMAT_BC3_UNORM; - case PF_BC4_SNORM: return DXGI_FORMAT_BC4_SNORM; - case PF_BC4_UNORM: return DXGI_FORMAT_BC4_UNORM; - case PF_BC5_SNORM: return DXGI_FORMAT_BC5_SNORM; - case PF_BC5_UNORM: return DXGI_FORMAT_BC5_UNORM; - case PF_BC6H_UF16: return DXGI_FORMAT_BC6H_UF16; - case PF_BC6H_SF16: return DXGI_FORMAT_BC6H_SF16; - case PF_BC7_UNORM: return DXGI_FORMAT_BC7_UNORM; - case PF_R16G16_SINT: return DXGI_FORMAT_R16G16_SINT; - case PF_FLOAT32_GR: return DXGI_FORMAT_R32G32_FLOAT; - case PF_DEPTH16: return DXGI_FORMAT_R32_TYPELESS; - case PF_DEPTH32: return DXGI_FORMAT_R32_TYPELESS; - case PF_DEPTH32F: return DXGI_FORMAT_R32_TYPELESS; - case PF_DEPTH24_STENCIL8: return DXGI_FORMAT_R24G8_TYPELESS; - default: return DXGI_FORMAT_UNKNOWN; - } - } - //--------------------------------------------------------------------- - DXGI_FORMAT D3D11Mappings::_getGammaFormat(DXGI_FORMAT format, bool appendSRGB) - { - if(appendSRGB) - { - switch(format) - { - case DXGI_FORMAT_R8G8B8A8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB; - case DXGI_FORMAT_B8G8R8A8_UNORM: return DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; - case DXGI_FORMAT_B8G8R8X8_UNORM: return DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; - case DXGI_FORMAT_BC1_UNORM: return DXGI_FORMAT_BC1_UNORM_SRGB; - case DXGI_FORMAT_BC2_UNORM: return DXGI_FORMAT_BC2_UNORM_SRGB; - case DXGI_FORMAT_BC3_UNORM: return DXGI_FORMAT_BC3_UNORM_SRGB; - case DXGI_FORMAT_BC7_UNORM: return DXGI_FORMAT_BC7_UNORM_SRGB; - } - } - return format; - } - //--------------------------------------------------------------------- - bool D3D11Mappings::_isBinaryCompressedFormat(DXGI_FORMAT d3dPF) - { - return - d3dPF == DXGI_FORMAT_BC1_TYPELESS || d3dPF == DXGI_FORMAT_BC1_UNORM || d3dPF == DXGI_FORMAT_BC1_UNORM_SRGB || - d3dPF == DXGI_FORMAT_BC2_TYPELESS || d3dPF == DXGI_FORMAT_BC2_UNORM || d3dPF == DXGI_FORMAT_BC2_UNORM_SRGB || - d3dPF == DXGI_FORMAT_BC3_TYPELESS || d3dPF == DXGI_FORMAT_BC3_UNORM || d3dPF == DXGI_FORMAT_BC3_UNORM_SRGB || - d3dPF == DXGI_FORMAT_BC4_TYPELESS || d3dPF == DXGI_FORMAT_BC4_UNORM || d3dPF == DXGI_FORMAT_BC4_SNORM || - d3dPF == DXGI_FORMAT_BC5_TYPELESS || d3dPF == DXGI_FORMAT_BC5_UNORM || d3dPF == DXGI_FORMAT_BC5_SNORM || -#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT - d3dPF == DXGI_FORMAT_BC6H_TYPELESS|| d3dPF == DXGI_FORMAT_BC6H_UF16 || d3dPF == DXGI_FORMAT_BC6H_SF16 || - d3dPF == DXGI_FORMAT_BC7_TYPELESS || d3dPF == DXGI_FORMAT_BC7_UNORM || d3dPF == DXGI_FORMAT_BC7_UNORM_SRGB || -#endif - 0; - } - //--------------------------------------------------------------------- - PixelFormat D3D11Mappings::_getClosestSupportedPF(PixelFormat ogrePF) - { - if (_getPF(ogrePF) != DXGI_FORMAT_UNKNOWN) - { - return ogrePF; - } - switch(ogrePF) - { - case PF_R8G8B8: - return PF_X8R8G8B8; - case PF_FLOAT16_RGB: - return PF_FLOAT16_RGBA; - case PF_FLOAT32_RGB: - return PF_FLOAT32_RGBA; - case PF_DEPTH16: - return PF_L16; - case PF_DEPTH24_STENCIL8: - case PF_DEPTH32: - case PF_DEPTH32F: - return PF_FLOAT32_R; - case PF_UNKNOWN: - default: - return PF_A8B8G8R8; - } - } - //--------------------------------------------------------------------- - D3D11_USAGE D3D11Mappings::_getUsage(HardwareBuffer::Usage usage) - { - return _isDynamic(usage) ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT; - } - //--------------------------------------------------------------------- - bool D3D11Mappings::_isDynamic(HardwareBuffer::Usage usage) - { - return (usage & HardwareBuffer::HBU_DYNAMIC) != 0; - } - //--------------------------------------------------------------------- - UINT D3D11Mappings::_getAccessFlags(HardwareBuffer::Usage usage) - { - return _isDynamic(usage) ? D3D11_CPU_ACCESS_WRITE : 0; - } - //--------------------------------------------------------------------- - TextureType D3D11Mappings::_getTexType(D3D11_SRV_DIMENSION type) - { - switch(type) - { - case D3D_SRV_DIMENSION_TEXTURE1D: - return TEX_TYPE_1D; - case D3D_SRV_DIMENSION_TEXTURE2D: - case D3D_SRV_DIMENSION_TEXTURE2DMS: - return TEX_TYPE_2D; - case D3D_SRV_DIMENSION_TEXTURE2DARRAY: - case D3D_SRV_DIMENSION_TEXTURE2DMSARRAY: - return TEX_TYPE_2D_ARRAY; - case D3D_SRV_DIMENSION_TEXTURE3D: - return TEX_TYPE_3D; - case D3D_SRV_DIMENSION_TEXTURECUBE: - return TEX_TYPE_CUBE_MAP; - default: - // unknown - return static_cast(0); - } - } - //--------------------------------------------------------------------- - UINT D3D11Mappings::_getTextureBindFlags(DXGI_FORMAT format, TextureUsage usage) - { - // We mark all textures as render target to be able to use GenerateMips() on it - // TODO: use DDSTextureLoader way of determining supported formats via CheckFormatSupport() & D3D11_FORMAT_SUPPORT_MIP_AUTOGEN - // TODO: explore DDSTextureLoader way of generating mips on temporary texture, to avoid D3D11_BIND_RENDER_TARGET flag injection - bool isRenderTarget = /*(usage & TU_RENDERTARGET) &&*/ !(usage & TU_DYNAMIC); - - // check for incompatible pixel formats - if(isRenderTarget) - { - switch (format) - { - case DXGI_FORMAT_R32G32B32A32_TYPELESS: - case DXGI_FORMAT_R32G32B32_TYPELESS: - case DXGI_FORMAT_R32G32B32_FLOAT: - case DXGI_FORMAT_R32G32B32_UINT: - case DXGI_FORMAT_R32G32B32_SINT: - case DXGI_FORMAT_R16G16B16A16_TYPELESS: - case DXGI_FORMAT_R32G32_TYPELESS: - case DXGI_FORMAT_R32G8X24_TYPELESS: - case DXGI_FORMAT_D32_FLOAT_S8X24_UINT: - case DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS: - case DXGI_FORMAT_X32_TYPELESS_G8X24_UINT: - case DXGI_FORMAT_R10G10B10A2_TYPELESS: - case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: - case DXGI_FORMAT_R8G8B8A8_TYPELESS: - case DXGI_FORMAT_R16G16_TYPELESS: - case DXGI_FORMAT_R32_TYPELESS: - case DXGI_FORMAT_D32_FLOAT: - case DXGI_FORMAT_R24G8_TYPELESS: - case DXGI_FORMAT_D24_UNORM_S8_UINT: - case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: - case DXGI_FORMAT_X24_TYPELESS_G8_UINT: - case DXGI_FORMAT_R8G8_TYPELESS: - case DXGI_FORMAT_R16_TYPELESS: - case DXGI_FORMAT_D16_UNORM: - case DXGI_FORMAT_R8_TYPELESS: - case DXGI_FORMAT_R9G9B9E5_SHAREDEXP: - case DXGI_FORMAT_R8G8_B8G8_UNORM: - case DXGI_FORMAT_G8R8_G8B8_UNORM: - case DXGI_FORMAT_BC1_TYPELESS: - case DXGI_FORMAT_BC1_UNORM: - case DXGI_FORMAT_BC1_UNORM_SRGB: - case DXGI_FORMAT_BC2_TYPELESS: - case DXGI_FORMAT_BC2_UNORM: - case DXGI_FORMAT_BC2_UNORM_SRGB: - case DXGI_FORMAT_BC3_TYPELESS: - case DXGI_FORMAT_BC3_UNORM: - case DXGI_FORMAT_BC3_UNORM_SRGB: - case DXGI_FORMAT_BC4_TYPELESS: - case DXGI_FORMAT_BC4_UNORM: - case DXGI_FORMAT_BC4_SNORM: - case DXGI_FORMAT_BC5_TYPELESS: - case DXGI_FORMAT_BC5_UNORM: - case DXGI_FORMAT_BC5_SNORM: - case DXGI_FORMAT_B8G8R8A8_TYPELESS: - case DXGI_FORMAT_B8G8R8X8_TYPELESS: - case DXGI_FORMAT_BC6H_TYPELESS: - case DXGI_FORMAT_BC6H_UF16: - case DXGI_FORMAT_BC6H_SF16: - case DXGI_FORMAT_BC7_TYPELESS: - case DXGI_FORMAT_BC7_UNORM: - case DXGI_FORMAT_BC7_UNORM_SRGB: - isRenderTarget = false; - } - } - - UINT retVal = 0; - if( !(usage & TU_NOT_SRV) ) - retVal |= D3D11_BIND_SHADER_RESOURCE; - - if( isRenderTarget ) - retVal |= D3D11_BIND_RENDER_TARGET; - - if( usage & TU_UNORDERED_ACCESS ) - retVal |= D3D11_BIND_UNORDERED_ACCESS; - - return retVal; - } - - UINT D3D11Mappings::_getTextureMiscFlags(UINT bindflags, TextureType textype, TextureUsage usage) - { - if(_isDynamic(usage)) - return 0; - - UINT flags = 0; - - if((bindflags & D3D11_BIND_SHADER_RESOURCE) && (bindflags & D3D11_BIND_RENDER_TARGET)) - flags |= D3D11_RESOURCE_MISC_GENERATE_MIPS; - - if(textype == TEX_TYPE_CUBE_MAP) - flags |= D3D11_RESOURCE_MISC_TEXTURECUBE; - - return flags; - } -} diff --git a/RenderSystems/Direct3D11/src/OgreD3D11MultiRenderTarget.cpp b/RenderSystems/Direct3D11/src/OgreD3D11MultiRenderTarget.cpp deleted file mode 100644 index d672abb0645..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11MultiRenderTarget.cpp +++ /dev/null @@ -1,142 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11MultiRenderTarget.h" -#include "OgreD3D11RenderSystem.h" -#include "OgreRoot.h" -#include "OgreD3D11Texture.h" -#include "OgreD3D11HardwarePixelBuffer.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - D3D11MultiRenderTarget::D3D11MultiRenderTarget(const String &name) : - //--------------------------------------------------------------------- - MultiRenderTarget(name), mNumberOfViews(0) - { - /// Clear targets - for(size_t x=0; x(target); - - /// Find first non-null target - int y; - for(y=0; ygetWidth() != target->getWidth() || - mRenderTargets[y]->getHeight() != target->getHeight()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "MultiRenderTarget surfaces are not of same size", - "D3D11MultiRenderTarget::bindSurface" - ); - } - } - - mRenderTargets[attachment] = target; - - if(PixelUtil::isDepth(target->suggestPixelFormat())) - { - attachDepthBuffer(target->getDepthBuffer()); - return; - } - - mRenderTargetViews[attachment] = - d3d11RenderTarget ? d3d11RenderTarget->getRenderTargetView() : NULL; - - if(mNumberOfViews < OGRE_MAX_MULTIPLE_RENDER_TARGETS) - mNumberOfViews++; - - checkAndUpdate(); - } - //--------------------------------------------------------------------- - void D3D11MultiRenderTarget::unbindSurfaceImpl(size_t attachment) - { - assert(attachment 0) - mNumberOfViews--; - - checkAndUpdate(); - } - //--------------------------------------------------------------------- - void D3D11MultiRenderTarget::update(void) - { - //D3D11RenderSystem* rs = static_cast(Root::getSingleton().getRenderSystem()); - - MultiRenderTarget::update(); - } - - uint D3D11MultiRenderTarget::getNumberOfViews() const { return mNumberOfViews; } - - ID3D11Texture2D* D3D11MultiRenderTarget::getSurface(uint index) const - { - D3D11RenderTarget* renderTarget = dynamic_cast(mRenderTargets[index]); - return renderTarget ? renderTarget->getSurface() : NULL; - } - - ID3D11RenderTargetView* D3D11MultiRenderTarget::getRenderTargetView(uint index) const - { - D3D11RenderTarget* renderTarget = dynamic_cast(mRenderTargets[index]); - return renderTarget ? renderTarget->getRenderTargetView() : NULL; - } - - void D3D11MultiRenderTarget::checkAndUpdate() - { - if(mRenderTargets[0]) - { - mWidth = static_cast(mRenderTargets[0]->getWidth()); - mHeight = static_cast(mRenderTargets[0]->getHeight()); - } - else - { - mWidth = 0; - mHeight = 0; - } - } - //--------------------------------------------------------------------- - - -} - diff --git a/RenderSystems/Direct3D11/src/OgreD3D11Plugin.cpp b/RenderSystems/Direct3D11/src/OgreD3D11Plugin.cpp deleted file mode 100644 index c43d0441d35..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11Plugin.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11Plugin.h" -#include "OgreRoot.h" - -namespace Ogre -{ - const String sPluginName = "D3D11 RenderSystem"; - //--------------------------------------------------------------------- - D3D11Plugin::D3D11Plugin() - : mRenderSystem(0) - { - - } - //--------------------------------------------------------------------- - const String& D3D11Plugin::getName() const - { - return sPluginName; - } - //--------------------------------------------------------------------- - void D3D11Plugin::install() - { - // Create the DirectX 11 rendering api - mRenderSystem = new D3D11RenderSystem(); - // Register the render system - Root::getSingleton().addRenderSystem( mRenderSystem ); - } - //--------------------------------------------------------------------- - void D3D11Plugin::initialise() - { - // nothing to do - } - //--------------------------------------------------------------------- - void D3D11Plugin::shutdown() - { - // nothing to do - } - //--------------------------------------------------------------------- - void D3D11Plugin::uninstall() - { - delete mRenderSystem; - mRenderSystem = 0; - } - - -} diff --git a/RenderSystems/Direct3D11/src/OgreD3D11RenderSystem.cpp b/RenderSystems/Direct3D11/src/OgreD3D11RenderSystem.cpp deleted file mode 100644 index 385034102be..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11RenderSystem.cpp +++ /dev/null @@ -1,2792 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11RenderSystem.h" -#include "OgreD3D11Prerequisites.h" -#include "OgreD3D11DriverList.h" -#include "OgreD3D11Driver.h" -#include "OgreD3D11VideoModeList.h" -#include "OgreD3D11VideoMode.h" -#include "OgreD3D11RenderWindow.h" -#include "OgreD3D11TextureManager.h" -#include "OgreD3D11Texture.h" -#include "OgreViewport.h" -#include "OgreLogManager.h" -#include "OgreMeshManager.h" -#include "OgreD3D11HardwareBufferManager.h" -#include "OgreD3D11HardwareBuffer.h" -#include "OgreD3D11VertexDeclaration.h" -#include "OgreGpuProgramManager.h" -#include "OgreD3D11HLSLProgramFactory.h" - -#include "OgreD3D11HardwareOcclusionQuery.h" -#include "OgreD3D11MultiRenderTarget.h" -#include "OgreD3D11HLSLProgram.h" - -#include "OgreD3D11DepthBuffer.h" -#include "OgreD3D11HardwarePixelBuffer.h" -#include "OgreD3D11RenderTarget.h" -#include "OgreException.h" -#include "OgreRoot.h" - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 -#include "OgreD3D11StereoDriverBridge.h" -#endif - - -#ifndef D3D_FL9_3_SIMULTANEOUS_RENDER_TARGET_COUNT -# define D3D_FL9_3_SIMULTANEOUS_RENDER_TARGET_COUNT 4 -#endif - -#ifndef D3D_FL9_1_SIMULTANEOUS_RENDER_TARGET_COUNT -# define D3D_FL9_1_SIMULTANEOUS_RENDER_TARGET_COUNT 1 -#endif -//--------------------------------------------------------------------- -#include -#include "OgreNsightChecker.h" - -#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT && defined(_WIN32_WINNT_WINBLUE) && _WIN32_WINNT >= _WIN32_WINNT_WINBLUE -#include // for IDXGIDevice3::Trim -#endif - -#define CHECK_DEVICE_ERROR(errmsg) \ -if (mDevice.isError()) \ -{ \ - String desc = mDevice.getErrorDescription(); \ - throw RenderingAPIException(0, "D3D11 device cannot " errmsg "\nError Description: "+desc, __FUNCTION__, __FILE__, __LINE__); \ -} - -namespace Ogre -{ - HRESULT WINAPI D3D11CreateDeviceN( - _In_opt_ IDXGIAdapter* pAdapter, - D3D_DRIVER_TYPE DriverType, - HMODULE Software, - UINT Flags, - const D3D_FEATURE_LEVEL* pFeatureLevels, - UINT FeatureLevels, - UINT SDKVersion, - _Out_ ID3D11DeviceN** ppDevice, - _Out_ D3D_FEATURE_LEVEL* pFeatureLevel, - _Out_ ID3D11DeviceContextN** ppImmediateContext ) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - return D3D11CreateDevice(pAdapter, DriverType, Software, Flags, pFeatureLevels, FeatureLevels, SDKVersion, ppDevice, pFeatureLevel, ppImmediateContext); - -#elif OGRE_PLATFORM == OGRE_PLATFORM_WINRT - ComPtr device; - ComPtr context; - ComPtr deviceN; - ComPtr contextN; - D3D_FEATURE_LEVEL featureLevel; - HRESULT mainHr, hr; - - mainHr = hr = D3D11CreateDevice(pAdapter, DriverType, Software, Flags, pFeatureLevels, FeatureLevels, SDKVersion, - (ppDevice ? device.GetAddressOf() : NULL), &featureLevel, (ppImmediateContext ? context.GetAddressOf() : NULL)); - if(FAILED(hr)) return hr; - - hr = device ? device.As(&deviceN) : S_OK; - if(FAILED(hr)) return hr; - - hr = context ? context.As(&contextN) : S_OK; - if(FAILED(hr)) return hr; - - if(ppDevice) *ppDevice = deviceN.Detach(); - if(pFeatureLevel) *pFeatureLevel = featureLevel; - if(ppImmediateContext) *ppImmediateContext = contextN.Detach(); - - return mainHr; -#endif - } - - //--------------------------------------------------------------------- - D3D11RenderSystem::D3D11RenderSystem() - : mDevice() -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - , mStereoDriver(NULL) -#endif -#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT - , suspendingToken() - , surfaceContentLostToken() -#endif - { - LogManager::getSingleton().logMessage( "D3D11: " + getName() + " created." ); - - mRenderSystemWasInited = false; - mSwitchingFullscreenCounter = 0; - mDriverType = D3D_DRIVER_TYPE_HARDWARE; - - initRenderSystem(); - - // set config options defaults - initConfigOptions(); - - // Clear class instance storage - memset(mClassInstances, 0, sizeof(mClassInstances)); - memset(mNumClassInstances, 0, sizeof(mNumClassInstances)); - - mEventNames.push_back("DeviceLost"); - mEventNames.push_back("DeviceRestored"); - -#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT -#if defined(_WIN32_WINNT_WINBLUE) && _WIN32_WINNT >= _WIN32_WINNT_WINBLUE - suspendingToken = (Windows::ApplicationModel::Core::CoreApplication::Suspending += - ref new Windows::Foundation::EventHandler([this](Platform::Object ^sender, Windows::ApplicationModel::SuspendingEventArgs ^e) - { - // Hints to the driver that the app is entering an idle state and that its memory can be used temporarily for other apps. - ComPtr pDXGIDevice; - if(mDevice.get() && SUCCEEDED(mDevice->QueryInterface(pDXGIDevice.GetAddressOf()))) - pDXGIDevice->Trim(); - })); - - surfaceContentLostToken = (Windows::Graphics::Display::DisplayInformation::DisplayContentsInvalidated += - ref new Windows::Foundation::TypedEventHandler( - [this](Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ arg) - { - LogManager::getSingleton().logMessage("D3D11: DisplayContentsInvalidated."); - validateDevice(true); - })); -#else // Win 8.0 - surfaceContentLostToken = (Windows::Graphics::Display::DisplayProperties::DisplayContentsInvalidated += - ref new Windows::Graphics::Display::DisplayPropertiesEventHandler([this](Platform::Object ^sender) - { - LogManager::getSingleton().logMessage("D3D11: DisplayContentsInvalidated."); - validateDevice(true); - })); -#endif -#endif - } - //--------------------------------------------------------------------- - D3D11RenderSystem::~D3D11RenderSystem() - { -#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT -#if defined(_WIN32_WINNT_WINBLUE) && _WIN32_WINNT >= _WIN32_WINNT_WINBLUE - Windows::ApplicationModel::Core::CoreApplication::Suspending -= suspendingToken; - Windows::Graphics::Display::DisplayInformation::DisplayContentsInvalidated -= surfaceContentLostToken; -#else // Win 8.0 - Windows::Graphics::Display::DisplayProperties::DisplayContentsInvalidated -= surfaceContentLostToken; -#endif -#endif - - shutdown(); - - // Deleting the HLSL program factory - if (mHLSLProgramFactory) - { - // Remove from manager safely - if (HighLevelGpuProgramManager::getSingletonPtr()) - HighLevelGpuProgramManager::getSingleton().removeFactory(mHLSLProgramFactory); - delete mHLSLProgramFactory; - mHLSLProgramFactory = 0; - } - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - // Stereo driver must be freed after device is created - D3D11StereoDriverBridge* stereoBridge = D3D11StereoDriverBridge::getSingletonPtr(); - OGRE_DELETE stereoBridge; -#endif - - LogManager::getSingleton().logMessage( "D3D11: " + getName() + " destroyed." ); - } - //--------------------------------------------------------------------- - const String& D3D11RenderSystem::getName() const - { - static String strName( "Direct3D11 Rendering Subsystem"); - return strName; - } - - //--------------------------------------------------------------------- - D3D11DriverList* D3D11RenderSystem::getDirect3DDrivers(bool refreshList /* = false*/) - { - if(!mDriverList) - mDriverList = new D3D11DriverList(); - - if(refreshList || mDriverList->count() == 0) - mDriverList->refresh(); - - return mDriverList; - } - //--------------------------------------------------------------------- - ID3D11DeviceN* D3D11RenderSystem::createD3D11Device(D3D11Driver* d3dDriver, D3D_DRIVER_TYPE driverType, - D3D_FEATURE_LEVEL minFL, D3D_FEATURE_LEVEL maxFL, D3D_FEATURE_LEVEL* pFeatureLevel) - { - IDXGIAdapterN* pAdapter = (d3dDriver && driverType == D3D_DRIVER_TYPE_HARDWARE) ? d3dDriver->getDeviceAdapter() : NULL; - - assert(driverType == D3D_DRIVER_TYPE_HARDWARE || driverType == D3D_DRIVER_TYPE_SOFTWARE || driverType == D3D_DRIVER_TYPE_WARP); - if(d3dDriver != NULL) - { - if(0 == wcscmp(d3dDriver->getAdapterIdentifier().Description, L"NVIDIA PerfHUD")) - driverType = D3D_DRIVER_TYPE_REFERENCE; - else - driverType = D3D_DRIVER_TYPE_UNKNOWN; - } - - // determine deviceFlags - UINT deviceFlags = 0; -#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT - // This flag is required in order to enable compatibility with Direct2D. - deviceFlags |= D3D11_CREATE_DEVICE_BGRA_SUPPORT; -#endif - - auto it = mOptions.find("Debug Layer"); - bool debugEnabled = false; - if (it != mOptions.end()) - { - debugEnabled = StringConverter::parseBool(it->second.currentValue); - } - - if(debugEnabled && !IsWorkingUnderNsight() && D3D11Device::D3D_NO_EXCEPTION != D3D11Device::getExceptionsErrorLevel()) - { - deviceFlags |= D3D11_CREATE_DEVICE_DEBUG; - } - if(!OGRE_THREAD_SUPPORT) - { - deviceFlags |= D3D11_CREATE_DEVICE_SINGLETHREADED; - } - - // determine feature levels - D3D_FEATURE_LEVEL requestedLevels[] = { -#if !__OGRE_WINRT_PHONE // Windows Phone support only FL 9.3, but simulator can create much more capable device, so restrict it artificially here -#if defined(_WIN32_WINNT_WIN8) && _WIN32_WINNT >= _WIN32_WINNT_WIN8 - D3D_FEATURE_LEVEL_11_1, -#endif - D3D_FEATURE_LEVEL_11_0, - D3D_FEATURE_LEVEL_10_1, - D3D_FEATURE_LEVEL_10_0, -#endif // !__OGRE_WINRT_PHONE - D3D_FEATURE_LEVEL_9_3, - D3D_FEATURE_LEVEL_9_2, - D3D_FEATURE_LEVEL_9_1 - }; - - D3D_FEATURE_LEVEL *pFirstFL = requestedLevels, *pLastFL = pFirstFL + ARRAYSIZE(requestedLevels) - 1; - for(unsigned int i = 0; i < ARRAYSIZE(requestedLevels); i++) - { - if(minFL == requestedLevels[i]) - pLastFL = &requestedLevels[i]; - if(maxFL == requestedLevels[i]) - pFirstFL = &requestedLevels[i]; - } - if(pLastFL < pFirstFL) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Requested min level feature is bigger the requested max level feature.", - "D3D11RenderSystem::initialise"); - } - - // create device - ID3D11DeviceN* device = NULL; - HRESULT hr = D3D11CreateDeviceN(pAdapter, driverType, NULL, deviceFlags, pFirstFL, pLastFL - pFirstFL + 1, D3D11_SDK_VERSION, &device, pFeatureLevel, 0); - - if(FAILED(hr) && 0 != (deviceFlags & D3D11_CREATE_DEVICE_DEBUG)) - { - StringStream error; - error << "Failed to create Direct3D11 device with debug layer (" << hr << ")\nRetrying without debug layer."; - Ogre::LogManager::getSingleton().logMessage(error.str()); - - // create device - second attempt, without debug layer - deviceFlags &= ~D3D11_CREATE_DEVICE_DEBUG; - hr = D3D11CreateDeviceN(pAdapter, driverType, NULL, deviceFlags, pFirstFL, pLastFL - pFirstFL + 1, D3D11_SDK_VERSION, &device, pFeatureLevel, 0); - } - if(FAILED(hr)) - { - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, "Failed to create Direct3D11 device", "D3D11RenderSystem::D3D11RenderSystem"); - } - return device; - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::initConfigOptions() - { - RenderSystem::initConfigOptions(); - - ConfigOption optDevice; - ConfigOption optVideoMode; - ConfigOption optAA; - ConfigOption optNVPerfHUD; - ConfigOption optMinFeatureLevels; - ConfigOption optMaxFeatureLevels; - ConfigOption optExceptionsErrorLevel; - ConfigOption optDriverType; - - optDevice.name = "Rendering Device"; - optDevice.currentValue = "(default)"; - optDevice.possibleValues.push_back("(default)"); - D3D11DriverList* driverList = getDirect3DDrivers(); - for( unsigned j=0; j < driverList->count(); j++ ) - { - D3D11Driver* driver = driverList->item(j); - optDevice.possibleValues.push_back( driver->DriverDescription() ); - } - optDevice.immutable = false; - - optVideoMode.name = "Video Mode"; - optVideoMode.currentValue = "800 x 600 @ 32-bit colour"; - optVideoMode.immutable = false; - - optAA.name = "FSAA"; - optAA.immutable = false; - optAA.possibleValues.push_back( "None" ); - optAA.currentValue = "None"; - - optNVPerfHUD.currentValue = "No"; - optNVPerfHUD.immutable = false; - optNVPerfHUD.name = "Allow NVPerfHUD"; - optNVPerfHUD.possibleValues.push_back( "Yes" ); - optNVPerfHUD.possibleValues.push_back( "No" ); - - // min feature level - optMinFeatureLevels; - optMinFeatureLevels.name = "Min Requested Feature Levels"; - optMinFeatureLevels.possibleValues.push_back("9.1"); - optMinFeatureLevels.possibleValues.push_back("9.3"); - optMinFeatureLevels.possibleValues.push_back("10.0"); - optMinFeatureLevels.possibleValues.push_back("10.1"); - optMinFeatureLevels.possibleValues.push_back("11.0"); - - optMinFeatureLevels.currentValue = "9.1"; - optMinFeatureLevels.immutable = false; - - - // max feature level - optMaxFeatureLevels; - optMaxFeatureLevels.name = "Max Requested Feature Levels"; - optMaxFeatureLevels.possibleValues.push_back("9.1"); - -#if __OGRE_WINRT_PHONE_80 - optMaxFeatureLevels.possibleValues.push_back("9.2"); - optMaxFeatureLevels.possibleValues.push_back("9.3"); - optMaxFeatureLevels.currentValue = "9.3"; -#elif __OGRE_WINRT_PHONE || __OGRE_WINRT_STORE - optMaxFeatureLevels.possibleValues.push_back("9.3"); - optMaxFeatureLevels.possibleValues.push_back("10.0"); - optMaxFeatureLevels.possibleValues.push_back("10.1"); - optMaxFeatureLevels.possibleValues.push_back("11.0"); - optMaxFeatureLevels.possibleValues.push_back("11.1"); - optMaxFeatureLevels.currentValue = "11.1"; -#else - optMaxFeatureLevels.possibleValues.push_back("9.3"); - optMaxFeatureLevels.possibleValues.push_back("10.0"); - optMaxFeatureLevels.possibleValues.push_back("10.1"); - optMaxFeatureLevels.possibleValues.push_back("11.0"); - optMaxFeatureLevels.currentValue = "11.0"; -#endif - - optMaxFeatureLevels.immutable = false; - - // Exceptions Error Level - optExceptionsErrorLevel.name = "Information Queue Exceptions Bottom Level"; - optExceptionsErrorLevel.possibleValues.push_back("No information queue exceptions"); - optExceptionsErrorLevel.possibleValues.push_back("Corruption"); - optExceptionsErrorLevel.possibleValues.push_back("Error"); - optExceptionsErrorLevel.possibleValues.push_back("Warning"); - optExceptionsErrorLevel.possibleValues.push_back("Info (exception on any message)"); -#if OGRE_DEBUG_MODE - optExceptionsErrorLevel.currentValue = "Info (exception on any message)"; -#else - optExceptionsErrorLevel.currentValue = "No information queue exceptions"; -#endif - optExceptionsErrorLevel.immutable = false; - - - // Driver type - optDriverType.name = "Driver type"; - optDriverType.possibleValues.push_back("Hardware"); - optDriverType.possibleValues.push_back("Software"); - optDriverType.possibleValues.push_back("Warp"); - optDriverType.currentValue = "Hardware"; - optDriverType.immutable = false; - - mOptions[optDevice.name] = optDevice; - mOptions[optVideoMode.name] = optVideoMode; - mOptions[optAA.name] = optAA; - mOptions[optNVPerfHUD.name] = optNVPerfHUD; - mOptions[optMinFeatureLevels.name] = optMinFeatureLevels; - mOptions[optMaxFeatureLevels.name] = optMaxFeatureLevels; - mOptions[optExceptionsErrorLevel.name] = optExceptionsErrorLevel; - mOptions[optDriverType.name] = optDriverType; - - ConfigOption opt; - opt.name = "Reversed Z-Buffer"; - opt.possibleValues = {"No", "Yes"}; - opt.currentValue = opt.possibleValues[0]; - opt.immutable = false; - - mOptions[opt.name] = opt; - - opt.name = "Debug Layer"; - opt.possibleValues = {"Off", "On"}; - opt.currentValue = opt.possibleValues[0]; - opt.immutable = false; - - mOptions[opt.name] = opt; - - refreshD3DSettings(); - - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::refreshD3DSettings() - { - ConfigOption* optVideoMode; - D3D11VideoMode* videoMode; - - ConfigOptionMap::iterator opt = mOptions.find( "Rendering Device" ); - if( opt != mOptions.end() ) - { - D3D11Driver *driver = getDirect3DDrivers()->findByName(opt->second.currentValue); - if (driver) - { - opt = mOptions.find( "Video Mode" ); - optVideoMode = &opt->second; - optVideoMode->possibleValues.clear(); - // get vide modes for this device - for( unsigned k=0; k < driver->getVideoModeList()->count(); k++ ) - { - videoMode = driver->getVideoModeList()->item( k ); - optVideoMode->possibleValues.push_back( videoMode->getDescription() ); - } - - // Reset video mode to default if previous doesn't avail in new possible values - StringVector::const_iterator itValue = - std::find(optVideoMode->possibleValues.begin(), - optVideoMode->possibleValues.end(), - optVideoMode->currentValue); - if (itValue == optVideoMode->possibleValues.end()) - { - optVideoMode->currentValue = "800 x 600 @ 32-bit colour"; - } - - // Also refresh FSAA options - refreshFSAAOptions(); - } - } - - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::setConfigOption( const String &name, const String &value ) - { - initRenderSystem(); - - LogManager::getSingleton().stream() - << "D3D11: RenderSystem Option: " << name << " = " << value; - - bool viewModeChanged = false; - - // Find option - ConfigOptionMap::iterator it = mOptions.find( name ); - - // Update - if( it != mOptions.end() ) - it->second.currentValue = value; - else - { - StringStream str; - str << "Option named '" << name << "' does not exist."; - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, str.str(), "D3D11RenderSystem::setConfigOption" ); - } - - // Refresh other options if D3DDriver changed - if( name == "Rendering Device" ) - refreshD3DSettings(); - - if( name == "Full Screen" ) - { - // Video mode is applicable - it = mOptions.find( "Video Mode" ); - if (it->second.currentValue.empty()) - { - it->second.currentValue = "800 x 600 @ 32-bit colour"; - viewModeChanged = true; - } - } - - if( name == "Min Requested Feature Levels" ) - { - mMinRequestedFeatureLevel = D3D11Device::parseFeatureLevel(value, D3D_FEATURE_LEVEL_9_1); - } - - if( name == "Max Requested Feature Levels" ) - { -#if defined(_WIN32_WINNT_WIN8) && _WIN32_WINNT >= _WIN32_WINNT_WIN8 - mMaxRequestedFeatureLevel = D3D11Device::parseFeatureLevel(value, D3D_FEATURE_LEVEL_11_1); -#else - mMaxRequestedFeatureLevel = D3D11Device::parseFeatureLevel(value, D3D_FEATURE_LEVEL_11_0); -#endif - } - - if(name == "Reversed Z-Buffer") - mIsReverseDepthBufferEnabled = StringConverter::parseBool(value); - - if( name == "Allow NVPerfHUD" ) - { - if (value == "Yes") - mUseNVPerfHUD = true; - else - mUseNVPerfHUD = false; - } - - if (viewModeChanged || name == "Video Mode") - { - refreshFSAAOptions(); - } - - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::refreshFSAAOptions(void) - { - - ConfigOptionMap::iterator it = mOptions.find( "FSAA" ); - ConfigOption* optFSAA = &it->second; - optFSAA->possibleValues.clear(); - - it = mOptions.find("Rendering Device"); - D3D11Driver *driver = getDirect3DDrivers()->findByName(it->second.currentValue); - if (driver) - { - it = mOptions.find("Video Mode"); - ComPtr device; - device.Attach(createD3D11Device(driver, mDriverType, mMinRequestedFeatureLevel, mMaxRequestedFeatureLevel, NULL)); - D3D11VideoMode* videoMode = driver->getVideoModeList()->item(it->second.currentValue); // Could be NULL if working over RDP/Simulator - DXGI_FORMAT format = videoMode ? videoMode->getFormat() : DXGI_FORMAT_R8G8B8A8_UNORM; - UINT numLevels = 0; - // set maskable levels supported - for (unsigned int n = 1; n <= D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT; n++) - { - // new style enumeration, with AMD EQAA names. NVidia CSAA names are misleading - // see determineFSAASettings for references - if(n == 8 && SUCCEEDED(device->CheckMultisampleQualityLevels(format, 4, &numLevels)) && numLevels > 8) - optFSAA->possibleValues.push_back("4f8"); // 8x CSAA - if(n == 16 && SUCCEEDED(device->CheckMultisampleQualityLevels(format, 4, &numLevels)) && numLevels > 16) - optFSAA->possibleValues.push_back("4f16"); // 16x CSAA - if(n == 16 && SUCCEEDED(device->CheckMultisampleQualityLevels(format, 8, &numLevels)) && numLevels > 16) - optFSAA->possibleValues.push_back("8f16"); // 16xQ CSAA - if (SUCCEEDED(device->CheckMultisampleQualityLevels(format, n, &numLevels)) && numLevels > 0) - optFSAA->possibleValues.push_back(std::to_string(n)); // Nx MSAA - } - } - - if(optFSAA->possibleValues.empty()) - { - optFSAA->possibleValues.push_back("1"); // D3D11 does not distinguish between noMSAA and 1xMSAA - } - - // Reset FSAA to none if previous doesn't avail in new possible values - StringVector::const_iterator itValue = - std::find(optFSAA->possibleValues.begin(), - optFSAA->possibleValues.end(), - optFSAA->currentValue); - if (itValue == optFSAA->possibleValues.end()) - { - optFSAA->currentValue = optFSAA->possibleValues[0]; - } - - } - //--------------------------------------------------------------------- - String D3D11RenderSystem::validateConfigOptions() - { - ConfigOptionMap::iterator it; - - // check if video mode is selected - it = mOptions.find( "Video Mode" ); - if (it->second.currentValue.empty()) - return "A video mode must be selected."; - - it = mOptions.find( "Rendering Device" ); - String driverName = it->second.currentValue; - if(driverName != "(default)" && getDirect3DDrivers()->findByName(driverName)->DriverDescription() != driverName) - { - // Just pick default driver - setConfigOption("Rendering Device", "(default)"); - return "Requested rendering device could not be found, default would be used instead."; - } - - return BLANKSTRING; - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::_initialise() - { - // call superclass method - RenderSystem::_initialise(); - - LogManager::getSingleton().logMessage( "D3D11: Subsystem Initialising" ); - - if(IsWorkingUnderNsight()) - LogManager::getSingleton().logMessage( "D3D11: Nvidia Nsight found"); - - // Init using current settings - ConfigOptionMap::iterator opt = mOptions.find( "Rendering Device" ); - if( opt == mOptions.end() ) - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Can`t find requested Direct3D driver name!", "D3D11RenderSystem::initialise" ); - mDriverName = opt->second.currentValue; - - // Driver type - opt = mOptions.find( "Driver type" ); - if( opt == mOptions.end() ) - OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, "Can't find driver type!", "D3D11RenderSystem::initialise" ); - mDriverType = D3D11Device::parseDriverType(opt->second.currentValue); - - opt = mOptions.find( "Information Queue Exceptions Bottom Level" ); - if( opt == mOptions.end() ) - OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, "Can't find Information Queue Exceptions Bottom Level option!", "D3D11RenderSystem::initialise" ); - D3D11Device::setExceptionsErrorLevel(opt->second.currentValue); - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - // Stereo driver must be created before device is created - auto stereoMode = StringConverter::parseBool(mOptions["Frame Sequential Stereo"].currentValue); - D3D11StereoDriverBridge* stereoBridge = OGRE_NEW D3D11StereoDriverBridge(stereoMode); -#endif - - // create the device for the selected adapter - createDevice(); - - LogManager::getSingleton().logMessage("***************************************"); - LogManager::getSingleton().logMessage("*** D3D11: Subsystem Initialized OK ***"); - LogManager::getSingleton().logMessage("***************************************"); - - this->fireDeviceEvent(&mDevice, "DeviceCreated"); - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::shutdown() - { - RenderSystem::shutdown(); - - mRenderSystemWasInited = false; - - mPrimaryWindow = NULL; // primary window deleted by base class. - freeDevice(); - SAFE_DELETE( mDriverList ); - mActiveD3DDriver = D3D11Driver(); - mDevice.ReleaseAll(); - LogManager::getSingleton().logMessage("D3D11: Shutting down cleanly."); - SAFE_DELETE( mTextureManager ); - SAFE_DELETE( mHardwareBufferManager ); - } - //--------------------------------------------------------------------- - RenderWindow* D3D11RenderSystem::_createRenderWindow(const String &name, - unsigned int width, unsigned int height, bool fullScreen, - const NameValuePairList *miscParams) - { - RenderSystem::_createRenderWindow(name, width, height, fullScreen, miscParams); - - // Check we're not creating a secondary window when the primary - // was fullscreen - if (mPrimaryWindow && mPrimaryWindow->isFullScreen() && fullScreen == false) - { - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, - "Cannot create secondary windows not in full screen when the primary is full screen", - "D3D11RenderSystem::_createRenderWindow"); - } - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - D3D11RenderWindowBase* win = new D3D11RenderWindowHwnd(mDevice); -#elif OGRE_PLATFORM == OGRE_PLATFORM_WINRT - String windowType; - if(miscParams) - { - // Get variable-length params - NameValuePairList::const_iterator opt = miscParams->find("windowType"); - if(opt != miscParams->end()) - windowType = opt->second; - } - - D3D11RenderWindowBase* win = NULL; -#if !__OGRE_WINRT_PHONE_80 - if(win == NULL && windowType == "SurfaceImageSource") - win = new D3D11RenderWindowImageSource(mDevice); - if(win == NULL && windowType == "SwapChainPanel") - win = new D3D11RenderWindowSwapChainPanel(mDevice); -#endif // !__OGRE_WINRT_PHONE_80 - if(win == NULL) - win = new D3D11RenderWindowCoreWindow(mDevice); -#endif - win->create(name, width, height, fullScreen, miscParams); - - attachRenderTarget(*win); - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - // Must be called after device has been linked to window - D3D11StereoDriverBridge::getSingleton().addRenderWindow(win); - win->_validateStereo(); -#endif - - // If this is the first window, get the D3D device and create the texture manager - if (!mPrimaryWindow) - { - mPrimaryWindow = win; - win->getCustomAttribute("D3DDEVICE", &mDevice); - - // Create the texture manager for use by others - mTextureManager = new D3D11TextureManager(mDevice); - // Also create hardware buffer manager - mHardwareBufferManager = new D3D11HardwareBufferManager(mDevice); - - // create & register HLSL factory - if (mHLSLProgramFactory == NULL) - mHLSLProgramFactory = new D3D11HLSLProgramFactory(mDevice); - mRealCapabilities = createRenderSystemCapabilities(); - - mNativeShadingLanguageVersion = 4; - - // if we are using custom capabilities, then - // mCurrentCapabilities has already been loaded - if (!mUseCustomCapabilities) - mCurrentCapabilities = mRealCapabilities; - - fireEvent("RenderSystemCapabilitiesCreated"); - - initialiseFromRenderSystemCapabilities(mCurrentCapabilities, mPrimaryWindow); - - } - else - { - mSecondaryWindows.push_back(win); - } - - return win; - } - - //--------------------------------------------------------------------- - void D3D11RenderSystem::fireDeviceEvent(D3D11Device* device, const String & name, D3D11RenderWindowBase* sendingWindow /* = NULL */) - { - NameValuePairList params; - params["D3DDEVICE"] = StringConverter::toString((size_t)device->get()); - if(sendingWindow) - params["RenderWindow"] = StringConverter::toString((size_t)sendingWindow); - fireEvent(name, ¶ms); - } - //--------------------------------------------------------------------- - RenderSystemCapabilities* D3D11RenderSystem::createRenderSystemCapabilities() const - { - RenderSystemCapabilities* rsc = new RenderSystemCapabilities(); - rsc->setDriverVersion(mDriverVersion); - rsc->setDeviceName(mActiveD3DDriver.DriverDescription()); - rsc->setRenderSystemName(getName()); - - // Does NOT support fixed-function! - //rsc->setCapability(RSC_FIXED_FUNCTION); - - rsc->setCapability(RSC_HWSTENCIL); - - UINT formatSupport; - if(mFeatureLevel >= D3D_FEATURE_LEVEL_9_2 - || SUCCEEDED(mDevice->CheckFormatSupport(DXGI_FORMAT_R32_UINT, &formatSupport)) && 0 != (formatSupport & D3D11_FORMAT_SUPPORT_IA_INDEX_BUFFER)) - rsc->setCapability(RSC_32BIT_INDEX); - - // Set number of texture units, cap at OGRE_MAX_TEXTURE_LAYERS - rsc->setNumTextureUnits(OGRE_MAX_TEXTURE_LAYERS); - rsc->setNumVertexAttributes(D3D11_STANDARD_VERTEX_ELEMENT_COUNT); - rsc->setCapability(RSC_ANISOTROPY); - // Cube map - if (mFeatureLevel >= D3D_FEATURE_LEVEL_10_0) - { - rsc->setCapability(RSC_READ_BACK_AS_TEXTURE); - } - - // We always support compression, D3DX will decompress if device does not support - rsc->setCapability(RSC_TEXTURE_COMPRESSION); - rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT); - - if(mFeatureLevel >= D3D_FEATURE_LEVEL_10_0) - rsc->setCapability(RSC_TWO_SIDED_STENCIL); - - rsc->setCapability(RSC_STENCIL_WRAP); - rsc->setCapability(RSC_HWOCCLUSION); - rsc->setCapability(RSC_HWOCCLUSION_ASYNCHRONOUS); - - convertVertexShaderCaps(rsc); - convertPixelShaderCaps(rsc); - convertGeometryShaderCaps(rsc); - convertHullShaderCaps(rsc); - convertDomainShaderCaps(rsc); - convertComputeShaderCaps(rsc); - rsc->addShaderProfile("hlsl"); - - rsc->setCapability(RSC_USER_CLIP_PLANES); - - - rsc->setCapability(RSC_RTT_MAIN_DEPTHBUFFER_ATTACHABLE); - - - // Adapter details - const DXGI_ADAPTER_DESC1& adapterID = mActiveD3DDriver.getAdapterIdentifier(); - - switch(mDriverType) { - case D3D_DRIVER_TYPE_HARDWARE: - // determine vendor - // Full list of vendors here: http://www.pcidatabase.com/vendors.php?sort=id - switch(adapterID.VendorId) - { - case 0x10DE: - rsc->setVendor(GPU_NVIDIA); - break; - case 0x1002: - rsc->setVendor(GPU_AMD); - break; - case 0x163C: - case 0x8086: - rsc->setVendor(GPU_INTEL); - break; - default: - rsc->setVendor(GPU_UNKNOWN); - break; - }; - break; - case D3D_DRIVER_TYPE_SOFTWARE: - rsc->setVendor(GPU_MS_SOFTWARE); - break; - case D3D_DRIVER_TYPE_WARP: - rsc->setVendor(GPU_MS_WARP); - break; - default: - rsc->setVendor(GPU_UNKNOWN); - break; - } - - rsc->setCapability(RSC_DEPTH_CLAMP); - - rsc->setCapability(RSC_TEXTURE_3D); - rsc->setCapability(RSC_TEXTURE_2D_ARRAY); - if (mFeatureLevel >= D3D_FEATURE_LEVEL_10_0) - { - rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES); - rsc->setCapability(RSC_HWRENDER_TO_TEXTURE_3D); - rsc->setCapability(RSC_TEXTURE_1D); - rsc->setCapability(RSC_TEXTURE_COMPRESSION_BC6H_BC7); - } - - rsc->setCapability(RSC_HWRENDER_TO_TEXTURE); - rsc->setCapability(RSC_TEXTURE_FLOAT); - -#ifdef D3D_FEATURE_LEVEL_9_3 - int numMultiRenderTargets = (mFeatureLevel > D3D_FEATURE_LEVEL_9_3) ? D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT : // 8 - (mFeatureLevel == D3D_FEATURE_LEVEL_9_3) ? 4/*D3D_FL9_3_SIMULTANEOUS_RENDER_TARGET_COUNT*/ : // 4 - 1/*D3D_FL9_1_SIMULTANEOUS_RENDER_TARGET_COUNT*/; // 1 -#else - int numMultiRenderTargets = D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; // 8 -#endif - - rsc->setNumMultiRenderTargets(std::min(numMultiRenderTargets, (int)OGRE_MAX_MULTIPLE_RENDER_TARGETS)); - - rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH); - rsc->setNumVertexTextureUnits(4); - - rsc->setCapability(RSC_MIPMAP_LOD_BIAS); - - // actually irrelevant, but set - rsc->setCapability(RSC_PERSTAGECONSTANT); - - rsc->setCapability(RSC_VERTEX_BUFFER_INSTANCE_DATA); - rsc->setCapability(RSC_CAN_GET_COMPILED_SHADER_BUFFER); - - rsc->setCapability(RSC_PRIMITIVE_RESTART); - - return rsc; - - } - //----------------------------------------------------------------------- - void D3D11RenderSystem::initialiseFromRenderSystemCapabilities( - RenderSystemCapabilities* caps, RenderTarget* primary) - { - // add hlsl - HighLevelGpuProgramManager::getSingleton().addFactory(mHLSLProgramFactory); - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::convertVertexShaderCaps(RenderSystemCapabilities* rsc) const - { - if (mFeatureLevel >= D3D_FEATURE_LEVEL_9_1) - { - rsc->addShaderProfile("vs_4_0_level_9_1"); -#if SUPPORT_SM2_0_HLSL_SHADERS == 1 - rsc->addShaderProfile("vs_2_0"); -#endif - } - if (mFeatureLevel >= D3D_FEATURE_LEVEL_9_3) - { - rsc->addShaderProfile("vs_4_0_level_9_3"); -#if SUPPORT_SM2_0_HLSL_SHADERS == 1 - rsc->addShaderProfile("vs_2_a"); -#endif - } - if (mFeatureLevel >= D3D_FEATURE_LEVEL_10_0) - { - rsc->addShaderProfile("vs_4_0"); -#if SUPPORT_SM2_0_HLSL_SHADERS == 1 - rsc->addShaderProfile("vs_3_0"); -#endif - } - if (mFeatureLevel >= D3D_FEATURE_LEVEL_10_1) - { - rsc->addShaderProfile("vs_4_1"); - } - if (mFeatureLevel >= D3D_FEATURE_LEVEL_11_0) - { - rsc->addShaderProfile("vs_5_0"); - } - - rsc->setCapability(RSC_VERTEX_PROGRAM); - - // float params, always 4D - rsc->setVertexProgramConstantFloatCount(D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT); - - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::convertPixelShaderCaps(RenderSystemCapabilities* rsc) const - { - if (mFeatureLevel >= D3D_FEATURE_LEVEL_9_1) - { - rsc->addShaderProfile("ps_4_0_level_9_1"); -#if SUPPORT_SM2_0_HLSL_SHADERS == 1 - rsc->addShaderProfile("ps_2_0"); -#endif - } - if (mFeatureLevel >= D3D_FEATURE_LEVEL_9_3) - { - rsc->addShaderProfile("ps_4_0_level_9_3"); -#if SUPPORT_SM2_0_HLSL_SHADERS == 1 - rsc->addShaderProfile("ps_2_a"); - rsc->addShaderProfile("ps_2_b"); -#endif - } - if (mFeatureLevel >= D3D_FEATURE_LEVEL_10_0) - { - rsc->addShaderProfile("ps_4_0"); -#if SUPPORT_SM2_0_HLSL_SHADERS == 1 - rsc->addShaderProfile("ps_3_0"); -#endif - } - if (mFeatureLevel >= D3D_FEATURE_LEVEL_10_1) - { - rsc->addShaderProfile("ps_4_1"); - } - if (mFeatureLevel >= D3D_FEATURE_LEVEL_11_0) - { - rsc->addShaderProfile("ps_5_0"); - } - - // float params, always 4D - rsc->setFragmentProgramConstantFloatCount(D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT); - - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::convertHullShaderCaps(RenderSystemCapabilities* rsc) const - { - // Only for shader model 5.0 - if (mFeatureLevel >= D3D_FEATURE_LEVEL_11_0) - { - rsc->addShaderProfile("hs_5_0"); - - rsc->setCapability(RSC_TESSELLATION_HULL_PROGRAM); - - // float params, always 4D - rsc->setTessellationHullProgramConstantFloatCount(D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT); - } - - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::convertDomainShaderCaps(RenderSystemCapabilities* rsc) const - { - // Only for shader model 5.0 - if (mFeatureLevel >= D3D_FEATURE_LEVEL_11_0) - { - rsc->addShaderProfile("ds_5_0"); - - rsc->setCapability(RSC_TESSELLATION_DOMAIN_PROGRAM); - - // float params, always 4D - rsc->setTessellationDomainProgramConstantFloatCount(D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT); - } - - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::convertComputeShaderCaps(RenderSystemCapabilities* rsc) const - { - - if (mFeatureLevel >= D3D_FEATURE_LEVEL_10_0) - { - rsc->addShaderProfile("cs_4_0"); - rsc->setCapability(RSC_COMPUTE_PROGRAM); - } - if (mFeatureLevel >= D3D_FEATURE_LEVEL_10_1) - { - rsc->addShaderProfile("cs_4_1"); - } - if (mFeatureLevel >= D3D_FEATURE_LEVEL_11_0) - { - rsc->addShaderProfile("cs_5_0"); - } - - // float params, always 4D - rsc->setComputeProgramConstantFloatCount(D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT); - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::convertGeometryShaderCaps(RenderSystemCapabilities* rsc) const - { - if (mFeatureLevel >= D3D_FEATURE_LEVEL_10_0) - { - rsc->addShaderProfile("gs_4_0"); - rsc->setCapability(RSC_GEOMETRY_PROGRAM); - rsc->setCapability(RSC_HWRENDER_TO_VERTEX_BUFFER); - } - if (mFeatureLevel >= D3D_FEATURE_LEVEL_10_1) - { - rsc->addShaderProfile("gs_4_1"); - } - if (mFeatureLevel >= D3D_FEATURE_LEVEL_11_0) - { - rsc->addShaderProfile("gs_5_0"); - } - - rsc->setGeometryProgramConstantFloatCount(D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT); - rsc->setGeometryProgramNumOutputVertices(1024); - } - //----------------------------------------------------------------------- - bool D3D11RenderSystem::checkVertexTextureFormats(void) - { - return true; - } - //----------------------------------------------------------------------- - MultiRenderTarget * D3D11RenderSystem::createMultiRenderTarget(const String & name) - { - MultiRenderTarget *retval; - retval = new D3D11MultiRenderTarget(name); - attachRenderTarget(*retval); - - return retval; - } - //----------------------------------------------------------------------- - DepthBuffer* D3D11RenderSystem::_createDepthBufferFor( RenderTarget *renderTarget ) - { - // Get surface data (mainly to get MSAA data) - D3D11RenderTarget* d3d11RenderTarget = dynamic_cast(renderTarget); - ID3D11Texture2D* d3d11Texture = NULL; - if (d3d11RenderTarget) - { - d3d11Texture = d3d11RenderTarget->getSurface(); - } - - if (!d3d11Texture) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Invalid render target", - "D3D11RenderSystem::_createDepthBufferFor"); - } - - D3D11_TEXTURE2D_DESC BBDesc; - d3d11Texture->GetDesc(&BBDesc); - - // Create depth stencil texture - ComPtr pDepthStencil; - D3D11_TEXTURE2D_DESC descDepth; - - descDepth.Width = renderTarget->getWidth(); - descDepth.Height = renderTarget->getHeight(); - descDepth.MipLevels = 1; - descDepth.ArraySize = BBDesc.ArraySize; - - if ( mFeatureLevel < D3D_FEATURE_LEVEL_10_0) - descDepth.Format = isReverseDepthBufferEnabled() ? DXGI_FORMAT_D32_FLOAT : DXGI_FORMAT_D24_UNORM_S8_UINT; - else - descDepth.Format = isReverseDepthBufferEnabled() ? DXGI_FORMAT_R32_TYPELESS : DXGI_FORMAT_R24G8_TYPELESS; - - descDepth.SampleDesc.Count = BBDesc.SampleDesc.Count; - descDepth.SampleDesc.Quality = BBDesc.SampleDesc.Quality; - descDepth.Usage = D3D11_USAGE_DEFAULT; - descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL; - - // If we tell we want to use it as a Shader Resource when in MSAA, we will fail - // This is a recomandation from NVidia. - if(!mReadBackAsTexture && mFeatureLevel >= D3D_FEATURE_LEVEL_10_0 && BBDesc.SampleDesc.Count == 1) - descDepth.BindFlags |= D3D11_BIND_SHADER_RESOURCE; - - descDepth.CPUAccessFlags = 0; - descDepth.MiscFlags = 0; - - if (descDepth.ArraySize == 6) - { - descDepth.MiscFlags |= D3D11_RESOURCE_MISC_TEXTURECUBE; - } - - OGRE_CHECK_DX_ERROR( - mDevice->CreateTexture2D(&descDepth, NULL, pDepthStencil.ReleaseAndGetAddressOf())); - - // - // Create the View of the texture - // If MSAA is used, we cannot do this - // - if(!mReadBackAsTexture && mFeatureLevel >= D3D_FEATURE_LEVEL_10_0 && BBDesc.SampleDesc.Count == 1) - { - D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc; - viewDesc.Format = isReverseDepthBufferEnabled() ? DXGI_FORMAT_R32_FLOAT : DXGI_FORMAT_R24_UNORM_X8_TYPELESS; - viewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; - viewDesc.Texture2D.MostDetailedMip = 0; - viewDesc.Texture2D.MipLevels = 1; - OGRE_CHECK_DX_ERROR(mDevice->CreateShaderResourceView(pDepthStencil.Get(), &viewDesc, - mDSTResView.ReleaseAndGetAddressOf())); - } - - // Create the depth stencil view - ID3D11DepthStencilView *depthStencilView; - D3D11_DEPTH_STENCIL_VIEW_DESC descDSV; - ZeroMemory( &descDSV, sizeof(D3D11_DEPTH_STENCIL_VIEW_DESC) ); - - descDSV.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; - descDSV.ViewDimension = (BBDesc.SampleDesc.Count > 1) ? D3D11_DSV_DIMENSION_TEXTURE2DMS : D3D11_DSV_DIMENSION_TEXTURE2D; - descDSV.Flags = 0 /* D3D11_DSV_READ_ONLY_DEPTH | D3D11_DSV_READ_ONLY_STENCIL */; // TODO: Allows bind depth buffer as depth view AND texture simultaneously. - - if(isReverseDepthBufferEnabled()) - { - descDSV.Format = DXGI_FORMAT_D32_FLOAT; - } - // TODO: Decide how to expose this feature - descDSV.Texture2D.MipSlice = 0; - OGRE_CHECK_DX_ERROR( - mDevice->CreateDepthStencilView(pDepthStencil.Get(), &descDSV, &depthStencilView)); - - //Create the abstract container - D3D11DepthBuffer *newDepthBuffer = new D3D11DepthBuffer( DepthBuffer::POOL_DEFAULT, this, depthStencilView, - descDepth.Width, descDepth.Height, - descDepth.SampleDesc.Count, descDepth.SampleDesc.Quality, - false ); - - return newDepthBuffer; - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::_removeManualDepthBuffer(DepthBuffer *depthBuffer) - { - if(depthBuffer != NULL) - { - DepthBufferVec& pool = mDepthBufferPool[depthBuffer->getPoolId()]; - pool.erase(std::remove(pool.begin(), pool.end(), depthBuffer), pool.end()); - } - } - //--------------------------------------------------------------------- - DepthBuffer* D3D11RenderSystem::_addManualDepthBuffer( ID3D11DepthStencilView *depthSurface, - uint32 width, uint32 height, - uint32 fsaa, uint32 fsaaQuality ) - { - //If this depth buffer was already added, return that one - DepthBufferVec::const_iterator itor = mDepthBufferPool[DepthBuffer::POOL_DEFAULT].begin(); - DepthBufferVec::const_iterator end = mDepthBufferPool[DepthBuffer::POOL_DEFAULT].end(); - - while( itor != end ) - { - if( static_cast(*itor)->getDepthStencilView() == depthSurface ) - return *itor; - - ++itor; - } - - //Create a new container for it - D3D11DepthBuffer *newDepthBuffer = new D3D11DepthBuffer( DepthBuffer::POOL_DEFAULT, this, depthSurface, - width, height, fsaa, fsaaQuality, true ); - - //Add the 'main' depth buffer to the pool - mDepthBufferPool[newDepthBuffer->getPoolId()].push_back( newDepthBuffer ); - - return newDepthBuffer; - } - //--------------------------------------------------------------------- - RenderTarget* D3D11RenderSystem::detachRenderTarget(const String &name) - { - RenderTarget* target = RenderSystem::detachRenderTarget(name); - detachRenderTargetImpl(name); - return target; - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::detachRenderTargetImpl(const String& name) - { - // Check in specialized lists - if (mPrimaryWindow != NULL && mPrimaryWindow->getName() == name) - { - // We're destroying the primary window, so reset device and window - mPrimaryWindow = NULL; - } - else - { - // Check secondary windows - SecondaryWindowList::iterator sw; - for (sw = mSecondaryWindows.begin(); sw != mSecondaryWindows.end(); ++sw) - { - if ((*sw)->getName() == name) - { - mSecondaryWindows.erase(sw); - break; - } - } - } - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::destroyRenderTarget(const String& name) - { -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - D3D11StereoDriverBridge::getSingleton().removeRenderWindow(name); -#endif - - detachRenderTargetImpl(name); - - // Do the real removal - RenderSystem::destroyRenderTarget(name); - - // Did we destroy the primary? - if (!mPrimaryWindow) - { - // device is no longer valid, so free it all up - freeDevice(); - } - - } - //----------------------------------------------------------------------- - void D3D11RenderSystem::freeDevice(void) - { - if (!mDevice.isNull() && mCurrentCapabilities) - { - // Set all texture units to nothing to release texture surfaces - _disableTextureUnitsFrom(0); - // Unbind any vertex streams to avoid memory leaks - /*for (unsigned int i = 0; i < mLastVertexSourceCount; ++i) - { - HRESULT hr = mDevice->SetStreamSource(i, NULL, 0, 0); - } - */ - // Clean up depth stencil surfaces - mDevice.ReleaseAll(); - } - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::createDevice() - { - mDevice.ReleaseAll(); - - D3D11Driver* d3dDriver = getDirect3DDrivers(true)->findByName(mDriverName); - mActiveD3DDriver = *d3dDriver; // store copy of selected driver, so that it is not lost when drivers would be re-enumerated - LogManager::getSingleton().stream() << "D3D11: Requested \"" << mDriverName << "\", selected \"" << d3dDriver->DriverDescription() << "\""; - - if(D3D11Driver* nvPerfHudDriver = (mDriverType == D3D_DRIVER_TYPE_HARDWARE && mUseNVPerfHUD) ? getDirect3DDrivers()->item("NVIDIA PerfHUD") : NULL) - { - d3dDriver = nvPerfHudDriver; - LogManager::getSingleton().logMessage("D3D11: Actually \"NVIDIA PerfHUD\" is used"); - } - - ID3D11DeviceN * device = createD3D11Device(d3dDriver, mDriverType, mMinRequestedFeatureLevel, mMaxRequestedFeatureLevel, &mFeatureLevel); - mDevice.TransferOwnership(device); - - LogManager::getSingleton().stream() << "D3D11: Device Feature Level " << (mFeatureLevel >> 12) - << "." << ((mFeatureLevel >> 8) & 0xF); - - LARGE_INTEGER driverVersion = mDevice.GetDriverVersion(); - mDriverVersion.major = HIWORD(driverVersion.HighPart); - mDriverVersion.minor = LOWORD(driverVersion.HighPart); - mDriverVersion.release = HIWORD(driverVersion.LowPart); - mDriverVersion.build = LOWORD(driverVersion.LowPart); - } - //----------------------------------------------------------------------- - void D3D11RenderSystem::handleDeviceLost() - { - LogManager::getSingleton().logMessage("D3D11: Device was lost, recreating."); - - // release device depended resources - fireDeviceEvent(&mDevice, "DeviceLost"); - - for(auto& it : Root::getSingleton().getSceneManagers()) - it.second->_releaseManualHardwareResources(); - - notifyDeviceLost(&mDevice); - - // Release all automatic temporary buffers and free unused - // temporary buffers, so we doesn't need to recreate them, - // and they will reallocate on demand. - HardwareBufferManager::getSingleton()._releaseBufferCopies(true); - - // Cleanup depth stencils surfaces. - _cleanupDepthBuffers(); - - // recreate device - createDevice(); - - // recreate device depended resources - notifyDeviceRestored(&mDevice); - - MeshManager::getSingleton().reloadAll(Resource::LF_PRESERVE_STATE); - - for(auto& it : Root::getSingleton().getSceneManagers()) - it.second->_restoreManualHardwareResources(); - - // Invalidate active view port. - mActiveViewport = NULL; - - fireDeviceEvent(&mDevice, "DeviceRestored"); - - LogManager::getSingleton().logMessage("D3D11: Device was restored."); - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::validateDevice(bool forceDeviceElection) - { - if(mDevice.isNull()) - return; - - // The D3D Device is no longer valid if the elected adapter changes or if - // the device has been removed. - - bool anotherIsElected = false; - if(forceDeviceElection) - { - // elect new device - D3D11Driver* newDriver = getDirect3DDrivers(true)->findByName(mDriverName); - - // check by LUID - LUID newLUID = newDriver->getAdapterIdentifier().AdapterLuid; - LUID prevLUID = mActiveD3DDriver.getAdapterIdentifier().AdapterLuid; - anotherIsElected = (newLUID.LowPart != prevLUID.LowPart) || (newLUID.HighPart != prevLUID.HighPart); - } - - if(anotherIsElected || mDevice.IsDeviceLost()) - { - handleDeviceLost(); - } - } - //----------------------------------------------------------------------- - void D3D11RenderSystem::_updateAllRenderTargets(bool swapBuffers) - { - try - { - RenderSystem::_updateAllRenderTargets(swapBuffers); - } - catch(const D3D11RenderingAPIException& e) - { - if(e.getHResult() == DXGI_ERROR_DEVICE_REMOVED || e.getHResult() == DXGI_ERROR_DEVICE_RESET) - LogManager::getSingleton().logMessage("D3D11: Device was lost while rendering."); - else - throw; - } - } - //----------------------------------------------------------------------- - void D3D11RenderSystem::_swapAllRenderTargetBuffers() - { - try - { - RenderSystem::_swapAllRenderTargetBuffers(); - } - catch(const D3D11RenderingAPIException& e) - { - if(e.getHResult() == DXGI_ERROR_DEVICE_REMOVED || e.getHResult() == DXGI_ERROR_DEVICE_RESET) - LogManager::getSingleton().logMessage("D3D11: Device was lost while rendering."); - else - throw; - } - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::_convertProjectionMatrix(const Matrix4& matrix, - Matrix4& dest, bool forGpuProgram) - { - dest = matrix; - - if (mIsReverseDepthBufferEnabled) - { - // Convert depth range from [-1,+1] to [1,0] - dest[2][0] = (dest[2][0] - dest[3][0]) * -0.5f; - dest[2][1] = (dest[2][1] - dest[3][1]) * -0.5f; - dest[2][2] = (dest[2][2] - dest[3][2]) * -0.5f; - dest[2][3] = (dest[2][3] - dest[3][3]) * -0.5f; - } - else - { - // Convert depth range from [-1,+1] to [0,1] - dest[2][0] = (dest[2][0] + dest[3][0]) / 2; - dest[2][1] = (dest[2][1] + dest[3][1]) / 2; - dest[2][2] = (dest[2][2] + dest[3][2]) / 2; - dest[2][3] = (dest[2][3] + dest[3][3]) / 2; - } - - if (!forGpuProgram) - { - // Convert right-handed to left-handed - dest[0][2] = -dest[0][2]; - dest[1][2] = -dest[1][2]; - dest[2][2] = -dest[2][2]; - dest[3][2] = -dest[3][2]; - } - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::_setTexture( size_t stage, bool enabled, const TexturePtr& tex ) - { - if (enabled && tex && tex->getSize() > 0) - { - // note used - tex->touch(); - mTexStageDesc[stage].pTex = static_cast(tex.get()); - mTexStageDesc[stage].used = true; - - mLastTextureUnitState = stage+1; - } - else - { - mTexStageDesc[stage].used = false; - // now we now what's the last texture unit set - mLastTextureUnitState = std::min(mLastTextureUnitState,stage); - } - mSamplerStatesChanged = true; - } - void D3D11RenderSystem::_setSampler(size_t unit, Sampler& sampler) - { - mSamplerStatesChanged = true; - - mTexStageDesc[unit].pSampler = static_cast(sampler).getState(); - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::_setAlphaRejectSettings( CompareFunction func, unsigned char value, bool alphaToCoverage ) - { - mBlendDesc.AlphaToCoverageEnable = alphaToCoverage; - mBlendDescChanged = true; - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::_setCullingMode( CullingMode mode ) - { - mCullingMode = mode; - - mRasterizerDesc.CullMode = D3D11Mappings::get(mode); - mRasterizerDesc.FrontCounterClockwise = !flipFrontFace(); - mRasterizerDescChanged = true; - } - void D3D11RenderSystem::_setDepthClamp(bool enable) - { - mRasterizerDesc.DepthClipEnable = !enable; - mRasterizerDescChanged = true; - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::_setDepthBufferParams( bool depthTest, bool depthWrite, CompareFunction depthFunction ) - { - mDepthStencilDesc.DepthEnable = depthTest; - mDepthStencilDesc.DepthWriteMask = depthWrite ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO; - - if(isReverseDepthBufferEnabled()) - depthFunction = reverseCompareFunction(depthFunction); - mDepthStencilDesc.DepthFunc = D3D11Mappings::get(depthFunction); - mDepthStencilDescChanged = true; - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::_setDepthBias(float constantBias, float slopeScaleBias) - { - if(isReverseDepthBufferEnabled()) - { - slopeScaleBias *= -1; - constantBias *= -1; - } - - const float nearFarFactor = 10.0; - mRasterizerDesc.DepthBias = static_cast(-constantBias * nearFarFactor); - mRasterizerDesc.SlopeScaledDepthBias = -slopeScaleBias; - mRasterizerDescChanged = true; - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::setColourBlendState(const ColourBlendState& state) - { - // record this - mCurrentBlend = state; - - if (state.blendingEnabled()) - { - mBlendDesc.RenderTarget[0].BlendEnable = TRUE; - mBlendDesc.RenderTarget[0].SrcBlend = D3D11Mappings::get(state.sourceFactor, false); - mBlendDesc.RenderTarget[0].DestBlend = D3D11Mappings::get(state.destFactor, false); - mBlendDesc.RenderTarget[0].BlendOp = D3D11Mappings::get(state.operation) ; - mBlendDesc.RenderTarget[0].SrcBlendAlpha = D3D11Mappings::get(state.sourceFactorAlpha, true); - mBlendDesc.RenderTarget[0].DestBlendAlpha = D3D11Mappings::get(state.destFactorAlpha, true); - mBlendDesc.RenderTarget[0].BlendOpAlpha = D3D11Mappings::get(state.alphaOperation) ; - mBlendDesc.AlphaToCoverageEnable = false; - - mBlendDesc.RenderTarget[0].RenderTargetWriteMask = 0x0F; - } - else - { - mBlendDesc.RenderTarget[0].BlendEnable = FALSE; - } - - UINT8 val = 0; - if (state.writeR) - val |= D3D11_COLOR_WRITE_ENABLE_RED; - if (state.writeG) - val |= D3D11_COLOR_WRITE_ENABLE_GREEN; - if (state.writeB) - val |= D3D11_COLOR_WRITE_ENABLE_BLUE; - if (state.writeA) - val |= D3D11_COLOR_WRITE_ENABLE_ALPHA; - - mBlendDesc.RenderTarget[0].RenderTargetWriteMask = val; - - mBlendDescChanged = true; - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::_setPolygonMode(PolygonMode level) - { - if(mPolygonMode != level) - { - mPolygonMode = level; - mRasterizerDesc.FillMode = D3D11Mappings::get(mPolygonMode); - mRasterizerDescChanged = true; - } - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::setStencilState(const StencilState& state) - { - // We honor user intent in case of one sided operation, and carefully tweak it in case of two sided operations. - bool flipFront = state.twoSidedOperation; - bool flipBack = state.twoSidedOperation && !flipFront; - - mDepthStencilDesc.StencilEnable = state.enabled; - mStencilRef = state.referenceValue; - mDepthStencilDesc.StencilReadMask = state.compareMask; - mDepthStencilDesc.StencilWriteMask = state.writeMask; - - mDepthStencilDesc.FrontFace.StencilFailOp = D3D11Mappings::get(state.stencilFailOp, flipFront); - mDepthStencilDesc.BackFace.StencilFailOp = D3D11Mappings::get(state.stencilFailOp, flipBack); - - mDepthStencilDesc.FrontFace.StencilDepthFailOp = D3D11Mappings::get(state.depthFailOp, flipFront); - mDepthStencilDesc.BackFace.StencilDepthFailOp = D3D11Mappings::get(state.depthFailOp, flipBack); - - mDepthStencilDesc.FrontFace.StencilPassOp = D3D11Mappings::get(state.depthStencilPassOp, flipFront); - mDepthStencilDesc.BackFace.StencilPassOp = D3D11Mappings::get(state.depthStencilPassOp, flipBack); - - mDepthStencilDesc.FrontFace.StencilFunc = D3D11Mappings::get(state.compareOp); - mDepthStencilDesc.BackFace.StencilFunc = D3D11Mappings::get(state.compareOp); - mDepthStencilDescChanged = true; - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::_setRenderTarget(RenderTarget *target) - { - mActiveRenderTarget = target; - if (mActiveRenderTarget) - { - // we need to clear the state - mDevice.GetImmediateContext()->ClearState(); - CHECK_DEVICE_ERROR("Clear State"); - _setRenderTargetViews(); - } - } - - //--------------------------------------------------------------------- - void D3D11RenderSystem::_setRenderTargetViews() - { - RenderTarget* target = mActiveRenderTarget; - D3D11RenderTarget* d3d11RenderTarget = dynamic_cast(target); - - if (target && d3d11RenderTarget) - { - ID3D11RenderTargetView* pRTView[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; - memset(pRTView, 0, sizeof(pRTView)); - - uint numberOfViews = d3d11RenderTarget->getNumberOfViews(); - - for (uint i = 0; i < OGRE_MAX_MULTIPLE_RENDER_TARGETS; i++) - { - pRTView[i] = d3d11RenderTarget->getRenderTargetView(i); - if (!pRTView[i]) - { - break; - } - } - - //Retrieve depth buffer - D3D11DepthBuffer *depthBuffer = static_cast(target->getDepthBuffer()); - - if( target->getDepthBufferPool() != DepthBuffer::POOL_NO_DEPTH && !depthBuffer ) - { - //Depth is automatically managed and there is no depth buffer attached to this RT - //or the Current D3D device doesn't match the one this Depth buffer was created - setDepthBufferFor( target ); - } - - //Retrieve depth buffer again (it may have changed) - depthBuffer = static_cast(target->getDepthBuffer()); - - // now switch to the new render target - mDevice.GetImmediateContext()->OMSetRenderTargets( - numberOfViews, - pRTView, - depthBuffer ? depthBuffer->getDepthStencilView() : 0 ); - - CHECK_DEVICE_ERROR("set render target"); - } - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::_setViewport( Viewport *vp ) - { - if (!vp) - { - mActiveViewport = NULL; - _setRenderTarget(NULL); - } - else if( vp != mActiveViewport || vp->_isUpdated() ) - { - mActiveViewport = vp; - - // ok, it's different, time to set render target and viewport params - D3D11_VIEWPORT d3dvp; - - // Set render target - RenderTarget* target; - target = vp->getTarget(); - - _setRenderTarget(target); - _setCullingMode( mCullingMode ); - - // set viewport dimensions - d3dvp.TopLeftX = static_cast(vp->getActualLeft()); - d3dvp.TopLeftY = static_cast(vp->getActualTop()); - d3dvp.Width = static_cast(vp->getActualWidth()); - d3dvp.Height = static_cast(vp->getActualHeight()); - if (target->requiresTextureFlipping()) - { - // Convert "top-left" to "bottom-left" - d3dvp.TopLeftY = target->getHeight() - d3dvp.Height - d3dvp.TopLeftY; - } - - // Z-values from 0.0 to 1.0 (TODO: standardise with OpenGL) - d3dvp.MinDepth = 0.0f; - d3dvp.MaxDepth = 1.0f; - - mDevice.GetImmediateContext()->RSSetViewports(1, &d3dvp); - CHECK_DEVICE_ERROR("set viewports"); - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - D3D11RenderWindowBase* d3d11Window = dynamic_cast(target); - if(d3d11Window) - d3d11Window->_validateStereo(); -#endif - - vp->_clearUpdatedFlag(); - } - else - { - // if swapchain was created with DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL we need to reestablish render target views - D3D11RenderWindowBase* d3d11Window = dynamic_cast(vp->getTarget()); - if(d3d11Window && d3d11Window->_shouldRebindBackBuffer()) - _setRenderTargetViews(); - } - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::_endFrame() - { - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::setVertexDeclaration(VertexDeclaration* decl) - { - OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, - "Cannot directly call setVertexDeclaration in the d3d11 render system - cast then use 'setVertexDeclaration(VertexDeclaration* decl, VertexBufferBinding* binding)' .", - "D3D11RenderSystem::setVertexDeclaration" ); - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::setVertexDeclaration(VertexDeclaration* decl, VertexBufferBinding* binding) - { - D3D11VertexDeclaration* d3ddecl = - static_cast(decl); - - d3ddecl->bindToShader(mBoundVertexProgram, binding); - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::setVertexBufferBinding(VertexBufferBinding* binding) - { - // TODO: attempt to detect duplicates - const VertexBufferBinding::VertexBufferBindingMap& binds = binding->getBindings(); - VertexBufferBinding::VertexBufferBindingMap::const_iterator i, iend; - iend = binds.end(); - for (i = binds.begin(); i != iend; ++i) - { - const D3D11HardwareBuffer* d3d11buf = i->second->_getImpl(); - - UINT stride = static_cast(i->second->getVertexSize()); - UINT offset = 0; // no stream offset, this is handled in _render instead - UINT slot = static_cast(i->first); - ID3D11Buffer * pVertexBuffers = d3d11buf->getD3DBuffer(); - mDevice.GetImmediateContext()->IASetVertexBuffers( - slot, // The first input slot for binding. - 1, // The number of vertex buffers in the array. - &pVertexBuffers, - &stride, - &offset - ); - - CHECK_DEVICE_ERROR("set vertex buffers"); - } - - mLastVertexSourceCount = binds.size(); - } - - //--------------------------------------------------------------------- - // TODO: Move this class to the right place. - class D3D11RenderOperationState - { - public: - ComPtr mBlendState; - ComPtr mRasterizer; - ComPtr mDepthStencilState; - - ID3D11SamplerState* mSamplerStates[OGRE_MAX_TEXTURE_LAYERS]; - size_t mSamplerStatesCount; - - ID3D11ShaderResourceView * mTextures[OGRE_MAX_TEXTURE_LAYERS]; // note - not owning - size_t mTexturesCount; - - D3D11RenderOperationState() : mSamplerStatesCount(0), mTexturesCount(0) {} - ~D3D11RenderOperationState() {} - }; - - //--------------------------------------------------------------------- - void D3D11RenderSystem::_dispatchCompute(const Vector3i& workgroupDim) - { - mDevice.GetImmediateContext()->CSSetShader(mBoundComputeProgram->getComputeShader(), - mClassInstances[GPT_COMPUTE_PROGRAM], - mNumClassInstances[GPT_COMPUTE_PROGRAM]); - CHECK_DEVICE_ERROR("set compute shader"); - - ID3D11ShaderResourceView* nullSrv[] = { 0 }; - - ID3D11UnorderedAccessView* uavs[OGRE_MAX_TEXTURE_LAYERS] = {NULL}; - ID3D11ShaderResourceView * srvs[OGRE_MAX_TEXTURE_LAYERS] = {NULL}; - ID3D11SamplerState* samplers[OGRE_MAX_TEXTURE_LAYERS] = {NULL}; - - // samplers mapping - size_t numberOfSamplers = std::min(mLastTextureUnitState,(size_t)(OGRE_MAX_TEXTURE_LAYERS + 1)); - for (size_t n = 0; n < numberOfSamplers; n++) - { - if(!mTexStageDesc[n].used) - continue; - - if(mTexStageDesc[n].pTex->getUsage() & TU_UNORDERED_ACCESS) - uavs[n] = mTexStageDesc[n].pTex->getUavView(); - else - { - srvs[n] = mTexStageDesc[n].pTex->getSrvView(); - samplers[n] = mTexStageDesc[n].pSampler; - } - } - - if(mFeatureLevel >= D3D_FEATURE_LEVEL_11_0) - { - // unbind SRVs from other stages - mDevice.GetImmediateContext()->VSSetShaderResources(0, 1, nullSrv); - mDevice.GetImmediateContext()->PSSetShaderResources(0, 1, nullSrv); - mSamplerStatesChanged = true; - - mDevice.GetImmediateContext()->CSSetUnorderedAccessViews(0, static_cast(numberOfSamplers), uavs, NULL); - CHECK_DEVICE_ERROR("set compute UAVs"); - } - - if (mFeatureLevel >= D3D_FEATURE_LEVEL_10_0) - { - mDevice.GetImmediateContext()->CSSetSamplers(static_cast(0), static_cast(numberOfSamplers), samplers); - CHECK_DEVICE_ERROR("set compute shader samplers"); - mDevice.GetImmediateContext()->CSSetShaderResources(static_cast(0), static_cast(numberOfSamplers), srvs); - CHECK_DEVICE_ERROR("set compute shader resources"); - } - - // Bound unordered access views - mDevice.GetImmediateContext()->Dispatch(workgroupDim[0], workgroupDim[1], workgroupDim[2]); - - // unbind - ID3D11UnorderedAccessView* views[] = { 0 }; - mDevice.GetImmediateContext()->CSSetShaderResources( 0, 1, nullSrv ); - mDevice.GetImmediateContext()->CSSetUnorderedAccessViews( 0, 1, views, NULL ); - mDevice.GetImmediateContext()->CSSetShader( NULL, NULL, 0 ); - } - - void D3D11RenderSystem::_render(const RenderOperation& op) - { - - // Exit immediately if there is nothing to render - if (op.vertexData==0 || op.vertexData->vertexCount == 0) - { - return; - } - - size_t numberOfInstances = op.numberOfInstances; - - // Call super class - RenderSystem::_render(op); - - D3D11RenderOperationState stackOpState; - D3D11RenderOperationState * opState = &stackOpState; - - if(mBlendDescChanged) - { - mBlendDescChanged = false; - mBoundBlendState = 0; - - OGRE_CHECK_DX_ERROR( - mDevice->CreateBlendState(&mBlendDesc, opState->mBlendState.ReleaseAndGetAddressOf())); - } - else - { - opState->mBlendState = mBoundBlendState; - } - - if(mRasterizerDescChanged) - { - mRasterizerDescChanged=false; - mBoundRasterizer = 0; - - OGRE_CHECK_DX_ERROR(mDevice->CreateRasterizerState(&mRasterizerDesc, opState->mRasterizer.ReleaseAndGetAddressOf())); - } - else - { - opState->mRasterizer = mBoundRasterizer; - } - - if(mDepthStencilDescChanged) - { - mBoundDepthStencilState = 0; - mDepthStencilDescChanged=false; - - OGRE_CHECK_DX_ERROR(mDevice->CreateDepthStencilState(&mDepthStencilDesc, opState->mDepthStencilState.ReleaseAndGetAddressOf())); - } - else - { - opState->mDepthStencilState = mBoundDepthStencilState; - } - - if(mSamplerStatesChanged) - { - // samplers mapping - size_t numberOfSamplers = std::min(mLastTextureUnitState,(size_t)(OGRE_MAX_TEXTURE_LAYERS + 1)); - - opState->mSamplerStatesCount = numberOfSamplers; - opState->mTexturesCount = numberOfSamplers; - - for (size_t n = 0; n < numberOfSamplers; n++) - { - ID3D11SamplerState *sampler = NULL; - sD3DTextureStageDesc & stage = mTexStageDesc[n]; - opState->mSamplerStates[n] = stage.used ? stage.pSampler : NULL; - opState->mTextures[n] = stage.used ? stage.pTex->getSrvView() : NULL; - } - for (size_t n = opState->mTexturesCount; n < OGRE_MAX_TEXTURE_LAYERS; n++) - { - opState->mTextures[n] = NULL; - } - } - - if (opState->mBlendState != mBoundBlendState) - { - mBoundBlendState = opState->mBlendState ; - mDevice.GetImmediateContext()->OMSetBlendState(opState->mBlendState.Get(), 0, 0xffffffff); // TODO - find out where to get the parameters - CHECK_DEVICE_ERROR("set blend state"); - } - - if (opState->mRasterizer != mBoundRasterizer) - { - mBoundRasterizer = opState->mRasterizer ; - - mDevice.GetImmediateContext()->RSSetState(opState->mRasterizer.Get()); - CHECK_DEVICE_ERROR("set rasterizer state"); - } - - - if (opState->mDepthStencilState != mBoundDepthStencilState) - { - mBoundDepthStencilState = opState->mDepthStencilState ; - - mDevice.GetImmediateContext()->OMSetDepthStencilState(opState->mDepthStencilState.Get(), mStencilRef); - CHECK_DEVICE_ERROR("set depth stencil state"); - } - - if (mSamplerStatesChanged && opState->mSamplerStatesCount > 0 ) // if the NumSamplers is 0, the operation effectively does nothing. - { - mSamplerStatesChanged = false; // now it's time to set it to false - /// Pixel Shader binding - mDevice.GetImmediateContext()->PSSetSamplers(static_cast(0), static_cast(opState->mSamplerStatesCount), opState->mSamplerStates); - CHECK_DEVICE_ERROR("set pixel shader samplers"); - mDevice.GetImmediateContext()->PSSetShaderResources(static_cast(0), static_cast(opState->mTexturesCount), &opState->mTextures[0]); - CHECK_DEVICE_ERROR("set pixel shader resources"); - - /// Vertex Shader binding - if (mFeatureLevel >= D3D_FEATURE_LEVEL_10_0) - { - mDevice.GetImmediateContext()->VSSetSamplers(static_cast(0), static_cast(opState->mSamplerStatesCount), opState->mSamplerStates); - CHECK_DEVICE_ERROR("set vertex shader samplers"); - mDevice.GetImmediateContext()->VSSetShaderResources(static_cast(0), static_cast(opState->mTexturesCount), &opState->mTextures[0]); - CHECK_DEVICE_ERROR("set vertex shader resources"); - } - - /// Geometry Shader binding - if (mBoundGeometryProgram && mFeatureLevel >= D3D_FEATURE_LEVEL_10_0) - { - mDevice.GetImmediateContext()->GSSetSamplers(0, opState->mSamplerStatesCount, opState->mSamplerStates); - CHECK_DEVICE_ERROR("set geometry shader samplers"); - mDevice.GetImmediateContext()->GSSetShaderResources(0, opState->mTexturesCount, &opState->mTextures[0]); - CHECK_DEVICE_ERROR("set geometry shader resources"); - } - - /// Hull Shader binding - if (mBoundTessellationHullProgram && mFeatureLevel >= D3D_FEATURE_LEVEL_10_0) - { - mDevice.GetImmediateContext()->HSSetSamplers(static_cast(0), static_cast(opState->mSamplerStatesCount), opState->mSamplerStates); - CHECK_DEVICE_ERROR("set hull shader samplers"); - mDevice.GetImmediateContext()->HSSetShaderResources(static_cast(0), static_cast(opState->mTexturesCount), &opState->mTextures[0]); - CHECK_DEVICE_ERROR("set hull shader resources"); - } - - /// Domain Shader binding - if (mBoundTessellationDomainProgram && mFeatureLevel >= D3D_FEATURE_LEVEL_10_0) - { - mDevice.GetImmediateContext()->DSSetSamplers(static_cast(0), static_cast(opState->mSamplerStatesCount), opState->mSamplerStates); - CHECK_DEVICE_ERROR("set domain shader samplers"); - mDevice.GetImmediateContext()->DSSetShaderResources(static_cast(0), static_cast(opState->mTexturesCount), &opState->mTextures[0]); - CHECK_DEVICE_ERROR("set domain shader resources"); - } - } - - ComPtr pSOTarget; - // Mustn't bind a emulated vertex, pixel shader (see below), if we are rendering to a stream out buffer - mDevice.GetImmediateContext()->SOGetTargets(1, pSOTarget.GetAddressOf()); - - //check consistency of vertex-fragment shaders - if (!mBoundVertexProgram || - (!mBoundFragmentProgram && op.operationType != RenderOperation::OT_POINT_LIST && !pSOTarget ) - ) - { - - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Attempted to render to a D3D11 device without both vertex and fragment shaders there is no fixed pipeline in d3d11 - use the RTSS or write custom shaders.", - "D3D11RenderSystem::_render"); - } - - // Check consistency of tessellation shaders - if( (mBoundTessellationHullProgram && !mBoundTessellationDomainProgram) || - (!mBoundTessellationHullProgram && mBoundTessellationDomainProgram) ) - { - if (mBoundTessellationHullProgram && !mBoundTessellationDomainProgram) { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Attempted to use tessellation, but domain shader is missing", - "D3D11RenderSystem::_render"); - } - else { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Attempted to use tessellation, but hull shader is missing", - "D3D11RenderSystem::_render"); } - } - - CHECK_DEVICE_ERROR("set geometry shader to null"); - - // Defer program bind to here because we must bind shader class instances, - // and this can only be made in SetShader calls. - // Also, bind shader resources - if (mBoundVertexProgram) - { - mDevice.GetImmediateContext()->VSSetShader(mBoundVertexProgram->getVertexShader(), - mClassInstances[GPT_VERTEX_PROGRAM], - mNumClassInstances[GPT_VERTEX_PROGRAM]); - CHECK_DEVICE_ERROR("set vertex shader"); - } - if (mBoundFragmentProgram) - { - mDevice.GetImmediateContext()->PSSetShader(mBoundFragmentProgram->getPixelShader(), - mClassInstances[GPT_FRAGMENT_PROGRAM], - mNumClassInstances[GPT_FRAGMENT_PROGRAM]); - CHECK_DEVICE_ERROR("set pixel shader"); - } - if (mBoundGeometryProgram) - { - mDevice.GetImmediateContext()->GSSetShader(mBoundGeometryProgram->getGeometryShader(), - mClassInstances[GPT_GEOMETRY_PROGRAM], - mNumClassInstances[GPT_GEOMETRY_PROGRAM]); - CHECK_DEVICE_ERROR("set geometry shader"); - } - if (mBoundTessellationHullProgram) - { - mDevice.GetImmediateContext()->HSSetShader(mBoundTessellationHullProgram->getHullShader(), - mClassInstances[GPT_HULL_PROGRAM], - mNumClassInstances[GPT_HULL_PROGRAM]); - CHECK_DEVICE_ERROR("set hull shader"); - } - if (mBoundTessellationDomainProgram) - { - mDevice.GetImmediateContext()->DSSetShader(mBoundTessellationDomainProgram->getDomainShader(), - mClassInstances[GPT_DOMAIN_PROGRAM], - mNumClassInstances[GPT_DOMAIN_PROGRAM]); - CHECK_DEVICE_ERROR("set domain shader"); - } - - setVertexDeclaration(op.vertexData->vertexDeclaration, op.vertexData->vertexBufferBinding); - setVertexBufferBinding(op.vertexData->vertexBufferBinding); - - - // Determine rendering operation - D3D11_PRIMITIVE_TOPOLOGY primType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST; - DWORD primCount = 0; - - if(mBoundTessellationHullProgram && mBoundTessellationDomainProgram) - { - // useful primitives for tessellation - switch( op.operationType ) - { - case RenderOperation::OT_LINE_LIST: - primType = D3D11_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST; - primCount = (DWORD)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) / 2; - break; - - case RenderOperation::OT_LINE_STRIP: - primType = D3D11_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST; - primCount = (DWORD)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) - 1; - break; - - case RenderOperation::OT_TRIANGLE_LIST: - primType = D3D11_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST; - primCount = (DWORD)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) / 3; - break; - - case RenderOperation::OT_TRIANGLE_STRIP: - primType = D3D11_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST; - primCount = (DWORD)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) - 2; - break; - } - } - else - { - //rendering without tessellation. - int operationType = op.operationType; - if(mPolygonMode == PM_POINTS) - operationType = RenderOperation::OT_POINT_LIST; - - switch( operationType ) - { - case RenderOperation::OT_POINT_LIST: - primType = D3D11_PRIMITIVE_TOPOLOGY_POINTLIST; - primCount = (DWORD)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount); - break; - - case RenderOperation::OT_LINE_LIST: - primType = D3D11_PRIMITIVE_TOPOLOGY_LINELIST; - primCount = (DWORD)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) / 2; - break; - - case RenderOperation::OT_LINE_LIST_ADJ: - primType = D3D11_PRIMITIVE_TOPOLOGY_LINELIST_ADJ; - primCount = (DWORD)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) / 4; - break; - - case RenderOperation::OT_LINE_STRIP: - primType = D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP; - primCount = (DWORD)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) - 1; - break; - - case RenderOperation::OT_LINE_STRIP_ADJ: - primType = D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ; - primCount = (DWORD)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) - 2; - break; - - case RenderOperation::OT_TRIANGLE_LIST: - primType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST; - primCount = (DWORD)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) / 3; - break; - - case RenderOperation::OT_TRIANGLE_LIST_ADJ: - primType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ; - primCount = (DWORD)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) / 6; - break; - - case RenderOperation::OT_TRIANGLE_STRIP: - primType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; - primCount = (DWORD)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) - 2; - break; - - case RenderOperation::OT_TRIANGLE_STRIP_ADJ: - primType = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ; - primCount = (DWORD)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) / 2 - 2; - break; - - case RenderOperation::OT_TRIANGLE_FAN: - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error - DX11 render - no support for triangle fan (OT_TRIANGLE_FAN)", "D3D11RenderSystem::_render"); - primType = D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED; // todo - no TRIANGLE_FAN in DX 11 - primCount = (DWORD)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) - 2; - break; - } - } - - if (primCount) - { - // Issue the op - //HRESULT hr; - if( op.useIndexes ) - { - auto d3dBuf = op.indexData->indexBuffer->_getImpl(); - mDevice.GetImmediateContext()->IASetIndexBuffer( d3dBuf->getD3DBuffer(), D3D11Mappings::getFormat(op.indexData->indexBuffer->getType()), 0 ); - CHECK_DEVICE_ERROR("set index buffer"); - } - - mDevice.GetImmediateContext()->IASetPrimitiveTopology( primType ); - CHECK_DEVICE_ERROR("set primitive topology"); - - do - { - if(op.useIndexes) - { - if(numberOfInstances > 1) - { - mDevice.GetImmediateContext()->DrawIndexedInstanced( - static_cast(op.indexData->indexCount), - static_cast(numberOfInstances), - static_cast(op.indexData->indexStart), - static_cast(op.vertexData->vertexStart), - 0); - } - else - { - mDevice.GetImmediateContext()->DrawIndexed( - static_cast(op.indexData->indexCount), - static_cast(op.indexData->indexStart), - static_cast(op.vertexData->vertexStart)); - } - } - else // non indexed - { - if(op.vertexData->vertexCount == -1) // -1 is a sign to use DrawAuto - { - mDevice.GetImmediateContext()->DrawAuto(); - } - else if(numberOfInstances > 1) - { - mDevice.GetImmediateContext()->DrawInstanced( - static_cast(op.vertexData->vertexCount), - static_cast(numberOfInstances), - static_cast(op.vertexData->vertexStart), - 0); - } - else - { - mDevice.GetImmediateContext()->Draw( - static_cast(op.vertexData->vertexCount), - static_cast(op.vertexData->vertexStart)); - } - } - - if(mDevice.isError()) - { - String errorDescription = "D3D11 device cannot draw"; - if(!op.useIndexes && op.vertexData->vertexCount == -1) // -1 is a sign to use DrawAuto - errorDescription.append(" auto"); - else - errorDescription.append(op.useIndexes ? " indexed" : "").append(numberOfInstances > 1 ? " instanced" : ""); - errorDescription.append("\nError Description:").append(mDevice.getErrorDescription()); - errorDescription.append("\nActive OGRE shaders:") - .append(mBoundVertexProgram ? ("\nVS = " + mBoundVertexProgram->getName()).c_str() : "") - .append(mBoundTessellationHullProgram ? ("\nHS = " + mBoundTessellationHullProgram->getName()).c_str() : "") - .append(mBoundTessellationDomainProgram ? ("\nDS = " + mBoundTessellationDomainProgram->getName()).c_str() : "") - .append(mBoundGeometryProgram ? ("\nGS = " + mBoundGeometryProgram->getName()).c_str() : "") - .append(mBoundFragmentProgram ? ("\nFS = " + mBoundFragmentProgram->getName()).c_str() : "") - .append(mBoundComputeProgram ? ("\nCS = " + mBoundComputeProgram->getName()).c_str() : ""); - - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, errorDescription, "D3D11RenderSystem::_render"); - } - - }while(updatePassIterationRenderState()); - } - - - // Crashy : commented this, 99% sure it's useless but really time consuming - /*if (true) // for now - clear the render state - { - mDevice.GetImmediateContext()->OMSetBlendState(0, 0, 0xffffffff); - mDevice.GetImmediateContext()->RSSetState(0); - mDevice.GetImmediateContext()->OMSetDepthStencilState(0, 0); -// mDevice->PSSetSamplers(static_cast(0), static_cast(0), 0); - - // Clear class instance storage - memset(mClassInstances, 0, sizeof(mClassInstances)); - memset(mNumClassInstances, 0, sizeof(mNumClassInstances)); - }*/ - - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::bindGpuProgram(GpuProgram* prg) - { - if (!prg) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Null program bound.", - "D3D11RenderSystem::bindGpuProgram"); - } - - switch (prg->getType()) - { - case GPT_VERTEX_PROGRAM: - { - // get the shader - mBoundVertexProgram = static_cast(prg); - } - break; - case GPT_FRAGMENT_PROGRAM: - { - mBoundFragmentProgram = static_cast(prg); - } - break; - case GPT_GEOMETRY_PROGRAM: - { - mBoundGeometryProgram = static_cast(prg); - } - break; - case GPT_HULL_PROGRAM: - { - mBoundTessellationHullProgram = static_cast(prg); - } - break; - case GPT_DOMAIN_PROGRAM: - { - mBoundTessellationDomainProgram = static_cast(prg); - } - break; - case GPT_COMPUTE_PROGRAM: - { - mBoundComputeProgram = static_cast(prg); - } - break; - }; - - RenderSystem::bindGpuProgram(prg); - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::unbindGpuProgram(GpuProgramType gptype) - { - mActiveParameters[gptype].reset(); - switch(gptype) - { - case GPT_VERTEX_PROGRAM: - { - mBoundVertexProgram = NULL; - //mDevice->VSSetShader(NULL); - mDevice.GetImmediateContext()->VSSetShader(NULL, NULL, 0); - } - break; - case GPT_FRAGMENT_PROGRAM: - { - mBoundFragmentProgram = NULL; - //mDevice->PSSetShader(NULL); - mDevice.GetImmediateContext()->PSSetShader(NULL, NULL, 0); - } - - break; - case GPT_GEOMETRY_PROGRAM: - { - mBoundGeometryProgram = NULL; - mDevice.GetImmediateContext()->GSSetShader( NULL, NULL, 0 ); - } - break; - case GPT_HULL_PROGRAM: - { - mBoundTessellationHullProgram = NULL; - mDevice.GetImmediateContext()->HSSetShader( NULL, NULL, 0 ); - } - break; - case GPT_DOMAIN_PROGRAM: - { - mBoundTessellationDomainProgram = NULL; - mDevice.GetImmediateContext()->DSSetShader( NULL, NULL, 0 ); - } - break; - case GPT_COMPUTE_PROGRAM: - { - mBoundComputeProgram = NULL; - mDevice.GetImmediateContext()->CSSetShader( NULL, NULL, 0 ); - } - break; - default: - assert(false && "Undefined Program Type!"); - }; - RenderSystem::unbindGpuProgram(gptype); - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::bindGpuProgramParameters(GpuProgramType gptype, const GpuProgramParametersPtr& params, uint16 mask) - { - if (mask & (uint16)GPV_GLOBAL) - { - params->_updateSharedParams(); - } - - // Do everything here in Dx11, since deal with via buffers anyway so number of calls - // is actually the same whether we categorise the updates or not - switch(gptype) - { - case GPT_VERTEX_PROGRAM: - { - if (mBoundVertexProgram) - { - auto buffers = mBoundVertexProgram->getConstantBuffers(params); - mDevice.GetImmediateContext()->VSSetConstantBuffers( 0, buffers.size(), buffers.data()); - CHECK_DEVICE_ERROR("set vertex shader constant buffers"); - } - } - break; - case GPT_FRAGMENT_PROGRAM: - { - if (mBoundFragmentProgram) - { - auto buffers = mBoundFragmentProgram->getConstantBuffers(params); - mDevice.GetImmediateContext()->PSSetConstantBuffers( 0, buffers.size(), buffers.data()); - CHECK_DEVICE_ERROR("set fragment shader constant buffers"); - } - } - break; - case GPT_GEOMETRY_PROGRAM: - { - if (mBoundGeometryProgram) - { - auto buffers = mBoundGeometryProgram->getConstantBuffers(params); - mDevice.GetImmediateContext()->GSSetConstantBuffers( 0, buffers.size(), buffers.data()); - CHECK_DEVICE_ERROR("set Geometry shader constant buffers"); - } - } - break; - case GPT_HULL_PROGRAM: - { - if (mBoundTessellationHullProgram) - { - auto buffers = mBoundTessellationHullProgram->getConstantBuffers(params); - mDevice.GetImmediateContext()->HSSetConstantBuffers( 0, buffers.size(), buffers.data()); - CHECK_DEVICE_ERROR("set Hull shader constant buffers"); - } - } - break; - case GPT_DOMAIN_PROGRAM: - { - if (mBoundTessellationDomainProgram) - { - auto buffers = mBoundTessellationDomainProgram->getConstantBuffers(params); - mDevice.GetImmediateContext()->DSSetConstantBuffers( 0, buffers.size(), buffers.data()); - CHECK_DEVICE_ERROR("set Domain shader constant buffers"); - } - } - break; - case GPT_COMPUTE_PROGRAM: - { - if (mBoundComputeProgram) - { - auto buffers = mBoundComputeProgram->getConstantBuffers(params); - mDevice.GetImmediateContext()->CSSetConstantBuffers( 0, buffers.size(), buffers.data()); - CHECK_DEVICE_ERROR("set Compute shader constant buffers"); - } - } - break; - }; - -#ifdef SUBROUTINES - // Now, set class instances - std::map subroutineMap; - - for(auto it& : subroutineMap) - { - setSubroutine(gptype, it.first, it.second); - } -#endif - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::setSubroutine(GpuProgramType gptype, unsigned int slotIndex, const String& subroutineName) - { - ID3D11ClassInstance* instance = 0; - - ClassInstanceIterator it = mInstanceMap.find(subroutineName); - if (it == mInstanceMap.end()) - { - // try to get instance already created (must have at least one field) - HRESULT hr = mDevice.GetClassLinkage()->GetClassInstance(subroutineName.c_str(), 0, &instance); - if (FAILED(hr) || instance == 0) - { - // probably class don't have a field, try create a new - hr = mDevice.GetClassLinkage()->CreateClassInstance(subroutineName.c_str(), 0, 0, 0, 0, &instance); - if (FAILED(hr) || instance == 0) - { - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Shader subroutine with name " + subroutineName + " doesn't exist.", - "D3D11RenderSystem::setSubroutineName"); - } - } - - // Store class instance - mInstanceMap.insert(std::make_pair(subroutineName, instance)); - } - else - { - instance = it->second; - } - - // If already created, store class instance - mClassInstances[gptype][slotIndex] = instance; - mNumClassInstances[gptype] = mNumClassInstances[gptype] + 1; - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::setSubroutine(GpuProgramType gptype, const String& slotName, const String& subroutineName) - { - unsigned int slotIdx = 0; - switch(gptype) - { - case GPT_VERTEX_PROGRAM: - { - if (mBoundVertexProgram) - { - slotIdx = mBoundVertexProgram->getSubroutineSlot(slotName); - } - } - break; - case GPT_FRAGMENT_PROGRAM: - { - if (mBoundFragmentProgram) - { - slotIdx = mBoundFragmentProgram->getSubroutineSlot(slotName); - } - } - break; - case GPT_GEOMETRY_PROGRAM: - { - if (mBoundGeometryProgram) - { - slotIdx = mBoundGeometryProgram->getSubroutineSlot(slotName); - } - } - break; - case GPT_HULL_PROGRAM: - { - if (mBoundTessellationHullProgram) - { - slotIdx = mBoundTessellationHullProgram->getSubroutineSlot(slotName); - } - } - break; - case GPT_DOMAIN_PROGRAM: - { - if (mBoundTessellationDomainProgram) - { - slotIdx = mBoundTessellationDomainProgram->getSubroutineSlot(slotName); - } - } - break; - case GPT_COMPUTE_PROGRAM: - { - if (mBoundComputeProgram) - { - slotIdx = mBoundComputeProgram->getSubroutineSlot(slotName); - } - } - break; - }; - - // Set subroutine for slot - setSubroutine(gptype, slotIdx, subroutineName); - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::setScissorTest(bool enabled, const Rect& rect) - { - mRasterizerDesc.ScissorEnable = enabled; - mScissorRect.left = rect.left; - mScissorRect.top = rect.top; - mScissorRect.right = rect.right; - mScissorRect.bottom = rect.bottom; - - mDevice.GetImmediateContext()->RSSetScissorRects(1, &mScissorRect); - CHECK_DEVICE_ERROR("set scissor rects"); - mRasterizerDescChanged=true; - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::clearFrameBuffer(unsigned int buffers, - const ColourValue& colour, float depth, unsigned short stencil) - { - D3D11RenderTarget* d3d11RenderTarget = dynamic_cast(mActiveRenderTarget); - if (mActiveRenderTarget && d3d11RenderTarget) - { - ID3D11RenderTargetView* pRTView[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; - memset(pRTView, 0, sizeof(pRTView)); - - for (uint i = 0; i < OGRE_MAX_MULTIPLE_RENDER_TARGETS; i++) - { - pRTView[i] = d3d11RenderTarget->getRenderTargetView(i); - if (!pRTView[i]) - { - break; - } - } - - if (buffers & FBT_COLOUR) - { - // Clear all views - uint numberOfViews = d3d11RenderTarget->getNumberOfViews(); - for (uint i = 0; i < numberOfViews; ++i) - { - mDevice.GetImmediateContext()->ClearRenderTargetView(pRTView[i], colour.ptr()); - } - - } - UINT ClearFlags = 0; - if (buffers & FBT_DEPTH) - { - ClearFlags |= D3D11_CLEAR_DEPTH; - } - if (buffers & FBT_STENCIL) - { - ClearFlags |= D3D11_CLEAR_STENCIL; - } - - if (ClearFlags) - { - D3D11DepthBuffer *depthBuffer = static_cast(mActiveRenderTarget-> - getDepthBuffer()); - if( depthBuffer ) - { - if (isReverseDepthBufferEnabled()) - { - depth = 1.0f - 0.5f * (depth + 1.0f); - } - - mDevice.GetImmediateContext()->ClearDepthStencilView( - depthBuffer->getDepthStencilView(), - ClearFlags, depth, static_cast(stencil) ); - } - } - } - } - //--------------------------------------------------------------------- - HardwareOcclusionQuery* D3D11RenderSystem::createHardwareOcclusionQuery(void) - { - D3D11HardwareOcclusionQuery* ret = new D3D11HardwareOcclusionQuery (mDevice); - mHwOcclusionQueries.push_back(ret); - return ret; - } - //--------------------------------------------------------------------- - Real D3D11RenderSystem::getMinimumDepthInputValue(void) - { - // Range [0.0f, 1.0f] - return 0.0f; - } - //--------------------------------------------------------------------- - Real D3D11RenderSystem::getMaximumDepthInputValue(void) - { - // Range [0.0f, 1.0f] - // D3D inverts even identity view matrices, so maximum INPUT is -1.0 - return -1.0f; - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::determineFSAASettings(uint fsaa, const String& fsaaHint, - DXGI_FORMAT format, DXGI_SAMPLE_DESC* outFSAASettings) - { - // "4f8" -> hint = "f8" - bool useCSAA = !fsaaHint.empty() && fsaaHint.front() == 'f'; - uint32 quality = 0; - if(useCSAA) StringConverter::parse(fsaaHint.substr(1), quality); - - // NVIDIA, AMD - enable CSAA - // http://developer.download.nvidia.com/assets/gamedev/docs/CSAA_Tutorial.pdf - // http://developer.amd.com/wordpress/media/2012/10/EQAA%20Modes%20for%20AMD%20HD%206900%20Series%20Cards.pdf - - // Modes are sorted from high quality to low quality, CSAA aka EQAA are listed first - DXGI_SAMPLE_DESC presets[] = { - { 8, 16 }, // CSAA 16xQ, EQAA 8f16x - { 4, 16 }, // CSAA 16x, EQAA 4f16x - { 16, 0 }, // MSAA 16x - - { 12, 0 }, // MSAA 12x - - { 8, 8 }, // CSAA 8xQ - { 4, 8 }, // CSAA 8x, EQAA 4f8x - { 8, 0 }, // MSAA 8x - - { 6, 0 }, // MSAA 6x - { 4, 0 }, // MSAA 4x - { 2, 0 }, // MSAA 2x - { 1, 0 }, // MSAA 1x - { NULL }, - }; - - // Find matching AA mode - DXGI_SAMPLE_DESC* mode = presets; - for(; mode->Count != 0; ++mode) - { - bool tooHQ = (mode->Count > fsaa || mode->Quality > quality); - if(!tooHQ) - break; - } - - // Use first supported mode - for(; mode->Count != 0; ++mode) - { - UINT outQuality; - HRESULT hr = mDevice->CheckMultisampleQualityLevels(format, mode->Count, &outQuality); - - if(SUCCEEDED(hr) && outQuality > mode->Quality) - { - *outFSAASettings = *mode; - return; - } - } - - outFSAASettings->Count = 1; - outFSAASettings->Quality = 0; - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::initRenderSystem() - { - if (mRenderSystemWasInited) - { - return; - } - - mRenderSystemWasInited = true; - // set pointers to NULL - mDriverList = NULL; - mTextureManager = NULL; - mHardwareBufferManager = NULL; - mPrimaryWindow = NULL; - mMinRequestedFeatureLevel = D3D_FEATURE_LEVEL_9_1; -#if __OGRE_WINRT_PHONE // Windows Phone support only FL 9.3, but simulator can create much more capable device, so restrict it artificially here - mMaxRequestedFeatureLevel = D3D_FEATURE_LEVEL_9_3; -#elif defined(_WIN32_WINNT_WIN8) && _WIN32_WINNT >= _WIN32_WINNT_WIN8 - mMaxRequestedFeatureLevel = D3D_FEATURE_LEVEL_11_1; -#else - mMaxRequestedFeatureLevel = D3D_FEATURE_LEVEL_11_0; -#endif - mUseNVPerfHUD = false; - mHLSLProgramFactory = NULL; - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - OGRE_DELETE mStereoDriver; - mStereoDriver = NULL; -#endif - - mBoundVertexProgram = NULL; - mBoundFragmentProgram = NULL; - mBoundGeometryProgram = NULL; - mBoundTessellationHullProgram = NULL; - mBoundTessellationDomainProgram = NULL; - mBoundComputeProgram = NULL; - - ZeroMemory( &mBlendDesc, sizeof(mBlendDesc)); - - ZeroMemory( &mRasterizerDesc, sizeof(mRasterizerDesc)); - mRasterizerDesc.FrontCounterClockwise = true; - mRasterizerDesc.DepthClipEnable = true; - mRasterizerDesc.MultisampleEnable = true; - - - ZeroMemory( &mDepthStencilDesc, sizeof(mDepthStencilDesc)); - - ZeroMemory( &mDepthStencilDesc, sizeof(mDepthStencilDesc)); - ZeroMemory( &mScissorRect, sizeof(mScissorRect)); - - mPolygonMode = PM_SOLID; - mRasterizerDesc.FillMode = D3D11Mappings::get(mPolygonMode); - - //sets the modification trackers to true - mBlendDescChanged = true; - mRasterizerDescChanged = true; - mDepthStencilDescChanged = true; - mSamplerStatesChanged = true; - mLastTextureUnitState = 0; - - ZeroMemory(mTexStageDesc, OGRE_MAX_TEXTURE_LAYERS * sizeof(sD3DTextureStageDesc)); - - mLastVertexSourceCount = 0; - mReadBackAsTexture = false; - - ID3D11DeviceN * device = createD3D11Device(NULL, D3D_DRIVER_TYPE_HARDWARE, mMinRequestedFeatureLevel, mMaxRequestedFeatureLevel, 0); - mDevice.TransferOwnership(device); - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::getCustomAttribute(const String& name, void* pData) - { - if( name == "D3DDEVICE" ) - { - *(ID3D11DeviceN**)pData = mDevice.get(); - } - else - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Attribute not found: " + name, "RenderSystem::getCustomAttribute"); - } - } - //--------------------------------------------------------------------- - D3D11HLSLProgram* D3D11RenderSystem::_getBoundVertexProgram() const - { - return mBoundVertexProgram; - } - //--------------------------------------------------------------------- - D3D11HLSLProgram* D3D11RenderSystem::_getBoundFragmentProgram() const - { - return mBoundFragmentProgram; - } - //--------------------------------------------------------------------- - D3D11HLSLProgram* D3D11RenderSystem::_getBoundGeometryProgram() const - { - return mBoundGeometryProgram; - } - //--------------------------------------------------------------------- - D3D11HLSLProgram* D3D11RenderSystem::_getBoundTessellationHullProgram() const - { - return mBoundTessellationHullProgram; - } - //--------------------------------------------------------------------- - D3D11HLSLProgram* D3D11RenderSystem::_getBoundTessellationDomainProgram() const - { - return mBoundTessellationDomainProgram; - } - //--------------------------------------------------------------------- - D3D11HLSLProgram* D3D11RenderSystem::_getBoundComputeProgram() const - { - return mBoundComputeProgram; - } - //--------------------------------------------------------------------- - bool D3D11RenderSystem::setDrawBuffer(ColourBufferType colourBuffer) - { -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - return D3D11StereoDriverBridge::getSingleton().setDrawBuffer(colourBuffer); -#else - return false; -#endif - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::beginProfileEvent( const String &eventName ) - { -#if OGRE_D3D11_PROFILING - if(mDevice.GetProfiler()) - { - wchar_t wideName[256]; // Let avoid heap memory allocation if we are in profiling code. - bool wideNameOk = !eventName.empty() && 0 != MultiByteToWideChar(CP_ACP, 0, eventName.data(), eventName.length() + 1, wideName, ARRAYSIZE(wideName)); - mDevice.GetProfiler()->BeginEvent(wideNameOk ? wideName : L""); - } -#endif - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::endProfileEvent( void ) - { -#if OGRE_D3D11_PROFILING - if(mDevice.GetProfiler()) - mDevice.GetProfiler()->EndEvent(); -#endif - } - //--------------------------------------------------------------------- - void D3D11RenderSystem::markProfileEvent( const String &eventName ) - { -#if OGRE_D3D11_PROFILING - if(mDevice.GetProfiler()) - { - wchar_t wideName[256]; // Let avoid heap memory allocation if we are in profiling code. - bool wideNameOk = !eventName.empty() && 0 != MultiByteToWideChar(CP_ACP, 0, eventName.data(), eventName.length() + 1, wideName, ARRAYSIZE(wideName)); - mDevice.GetProfiler()->SetMarker(wideNameOk ? wideName : L""); - } -#endif - } -} diff --git a/RenderSystems/Direct3D11/src/OgreD3D11RenderToVertexBuffer.cpp b/RenderSystems/Direct3D11/src/OgreD3D11RenderToVertexBuffer.cpp deleted file mode 100644 index 6e8e0d04e2e..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11RenderToVertexBuffer.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11Device.h" -#include "OgreD3D11HardwareBufferManager.h" -#include "OgreD3D11RenderToVertexBuffer.h" -#include "OgreHardwareBufferManager.h" -#include "OgreD3D11HardwareBuffer.h" -#include "OgreRenderable.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" -#include "OgreD3D11RenderSystem.h" -#include "OgreD3D11HLSLProgram.h" - -namespace Ogre { - - D3D11RenderToVertexBuffer::D3D11RenderToVertexBuffer(D3D11Device & device, - D3D11HardwareBufferManagerBase * bufManager) - : mDevice(device) - , mBufManager(bufManager) - , mpGeometryShader(0) - { - mVertexBuffers[0].reset(); - mVertexBuffers[1].reset(); - } - - D3D11RenderToVertexBuffer::~D3D11RenderToVertexBuffer(void) - { - } - - void D3D11RenderToVertexBuffer::setupGeometryShaderLinkageToStreamOut(Pass* pass) - { - static bool done = false; - - if (done || !pass->hasGeometryProgram()) - return; - - const GpuProgramPtr& program = pass->getGeometryProgram(); - - D3D11HLSLProgram* dx11Program = static_cast(program->_getBindingDelegate()); - dx11Program->reinterpretGSForStreamOut(); - - done = true; - - } - void D3D11RenderToVertexBuffer::update(SceneManager* sceneMgr) - { - Ogre::Pass* r2vbPass = derivePass(sceneMgr); - - setupGeometryShaderLinkageToStreamOut(r2vbPass); - - size_t bufSize = mVertexData->vertexDeclaration->getVertexSize(0) * mMaxVertexCount; - if (!mVertexBuffers[0] || mVertexBuffers[0]->getSizeInBytes() != bufSize) - { - //Buffers don't match. Need to reallocate. - mResetRequested = true; - } - - RenderOperation renderOp; - auto targetBufferIndex = mTargetBufferIndex; - if (mResetRequested || mResetsEveryUpdate) - { - //Use source data to render to first buffer - mSourceRenderable->getRenderOperation(renderOp); - } - else - { - getRenderOperation(renderOp); - } - - if (!mVertexBuffers[targetBufferIndex] || - mVertexBuffers[targetBufferIndex]->getSizeInBytes() != bufSize) - { - reallocateBuffer(targetBufferIndex); - } - - RenderSystem* targetRenderSystem = Root::getSingleton().getRenderSystem(); - - //Draw the object - auto vertexBuffer = mVertexBuffers[targetBufferIndex]->_getImpl(); - - UINT offset[1] = { 0 }; - ID3D11Buffer* iBuffer[1]; - iBuffer[0] = vertexBuffer->getD3DBuffer(); - mDevice.GetImmediateContext()->SOSetTargets( 1, iBuffer, offset ); - // Remove fragment program - mDevice.GetImmediateContext()->PSSetShader(NULL, NULL, 0); - - targetRenderSystem->_render(renderOp); - - //Switch the vertex binding - mVertexData->vertexBufferBinding->unsetAllBindings(); - mVertexData->vertexBufferBinding->setBinding(0, mVertexBuffers[targetBufferIndex]); - mTargetBufferIndex = mTargetBufferIndex == 0 ? 1 : 0; - - // Remove stream output buffer - iBuffer[0]=NULL; - mDevice.GetImmediateContext()->SOSetTargets( 1, iBuffer, offset ); - //Clear the reset flag - mResetRequested = false; - - // Enable DrawAuto - mVertexData->vertexCount = -1; - } - //----------------------------------------------------------------------------- - void D3D11RenderToVertexBuffer::reallocateBuffer(size_t index) - { - assert(index == 0 || index == 1); - if (mVertexBuffers[index]) - { - mVertexBuffers[index].reset(); - } - - mVertexBuffers[index] = mBufManager->createStreamOutputVertexBuffer( - mVertexData->vertexDeclaration->getVertexSize(0), mMaxVertexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY - ); - } -} diff --git a/RenderSystems/Direct3D11/src/OgreD3D11RenderWindow.cpp b/RenderSystems/Direct3D11/src/OgreD3D11RenderWindow.cpp deleted file mode 100644 index 88bb3353c30..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11RenderWindow.cpp +++ /dev/null @@ -1,1741 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11RenderWindow.h" -#include "OgreException.h" -#include "OgreD3D11RenderSystem.h" -#include "OgreD3D11Driver.h" -#include "OgreRoot.h" -#include "OgreD3D11DepthBuffer.h" -#include "OgreD3D11Texture.h" -#include "OgreViewport.h" -#include "OgreLogManager.h" -#include "OgreHardwarePixelBuffer.h" -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 -#include "OgreD3D11StereoDriverBridge.h" -#endif -#include -#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT && defined(_WIN32_WINNT_WINBLUE) && _WIN32_WINNT >= _WIN32_WINNT_WINBLUE -#include // for IDXGISwapChain2::SetMatrixTransform used in D3D11RenderWindowSwapChainPanel -#endif - -#if defined(_WIN32_WINNT_WIN8) && _WIN32_WINNT >= _WIN32_WINNT_WIN8 -#include -#include -#endif - -#define OGRE_D3D11_WIN_CLASS_NAME "OgreD3D11Wnd" - -namespace Ogre -{ - //--------------------------------------------------------------------- - // class D3D11RenderWindowBase - //--------------------------------------------------------------------- -#pragma region D3D11RenderWindowBase - D3D11RenderWindowBase::D3D11RenderWindowBase(D3D11Device & device) - : mDevice(device) - { - mIsFullScreen = false; - mIsExternal = false; - mActive = false; - mSizing = false; - mHidden = false; - } - //--------------------------------------------------------------------- - D3D11RenderWindowBase::~D3D11RenderWindowBase() - { - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - rsys->fireDeviceEvent(&mDevice,"RenderWindowDestroyed",this); - - destroy(); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowBase::create(const String& name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams) - { - mFSAA = 0; - mFSAAHint = ""; - mFSAAType.Count = 1; - mFSAAType.Quality = 0; - - unsigned int colourDepth = 32; - bool depthBuffer = true; - - if(miscParams) - { - // Get variable-length params - NameValuePairList::const_iterator opt; - // hidden [parseBool] - opt = miscParams->find("hidden"); - if(opt != miscParams->end()) - mHidden = StringConverter::parseBool(opt->second); - // colourDepth - opt = miscParams->find("colourDepth"); - if(opt != miscParams->end()) - colourDepth = StringConverter::parseUnsignedInt(opt->second); - // depthBuffer [parseBool] - opt = miscParams->find("depthBuffer"); - if(opt != miscParams->end()) - depthBuffer = StringConverter::parseBool(opt->second); - // FSAA type - opt = miscParams->find("FSAA"); - if(opt != miscParams->end()) - mFSAA = StringConverter::parseUnsignedInt(opt->second); - // FSAA quality - opt = miscParams->find("FSAAHint"); - if(opt != miscParams->end()) - mFSAAHint = opt->second; - // sRGB? - opt = miscParams->find("gamma"); - if(opt != miscParams->end()) - mHwGamma = StringConverter::parseBool(opt->second); - } - - mName = name; - mDepthBufferPoolId = depthBuffer ? DepthBuffer::POOL_DEFAULT : DepthBuffer::POOL_NO_DEPTH; - mIsFullScreen = fullScreen; - - if(mIsFullScreen) - { - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - rsys->addToSwitchingFullscreenCounter(); - } - - mWidth = mHeight = mLeft = mTop = 0; - - mActive = true; - mClosed = false; - } - //--------------------------------------------------------------------- - void D3D11RenderWindowBase::_createSizeDependedD3DResources(void) - { - assert(mpBackBuffer && !mRenderTargetView && !mDepthStencilView); - - // get the backbuffer desc - D3D11_TEXTURE2D_DESC BBDesc; - mpBackBuffer->GetDesc( &BBDesc ); - - // mFSAA is an external request that may be even not supported by hardware, but mFSAAType should be always in sync with reality - assert(BBDesc.SampleDesc.Count == mFSAAType.Count && BBDesc.SampleDesc.Quality == mFSAAType.Quality); - - // create the render target view - D3D11_RENDER_TARGET_VIEW_DESC RTVDesc; - ZeroMemory( &RTVDesc, sizeof(RTVDesc) ); - - RTVDesc.Format = _getRenderFormat(); // if BB is from swapchain than RTV format can have extra _SRGB suffix not present in BB format - RTVDesc.ViewDimension = mFSAAType.Count > 1 ? D3D11_RTV_DIMENSION_TEXTURE2DMS : D3D11_RTV_DIMENSION_TEXTURE2D; - OGRE_CHECK_DX_ERROR(mDevice->CreateRenderTargetView(mpBackBuffer.Get(), &RTVDesc, - mRenderTargetView.ReleaseAndGetAddressOf())); - - if( mDepthBufferPoolId != DepthBuffer::POOL_NO_DEPTH ) - { - // Create depth stencil texture - ComPtr pDepthStencil; - D3D11_TEXTURE2D_DESC descDepth; - - descDepth.Width = BBDesc.Width; - descDepth.Height = BBDesc.Height; - descDepth.MipLevels = 1; - descDepth.ArraySize = 1; - descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; - descDepth.SampleDesc.Count = mFSAAType.Count; - descDepth.SampleDesc.Quality = mFSAAType.Quality; - descDepth.Usage = D3D11_USAGE_DEFAULT; - descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL; - descDepth.CPUAccessFlags = 0; - descDepth.MiscFlags = 0; - - OGRE_CHECK_DX_ERROR( - mDevice->CreateTexture2D(&descDepth, NULL, pDepthStencil.ReleaseAndGetAddressOf())); - - // Create the depth stencil view - D3D11_DEPTH_STENCIL_VIEW_DESC descDSV; - ZeroMemory( &descDSV, sizeof(D3D11_DEPTH_STENCIL_VIEW_DESC) ); - - descDSV.Format = descDepth.Format; - descDSV.ViewDimension = mFSAAType.Count > 1 ? D3D11_DSV_DIMENSION_TEXTURE2DMS : D3D11_DSV_DIMENSION_TEXTURE2D; - OGRE_CHECK_DX_ERROR(mDevice->CreateDepthStencilView( - pDepthStencil.Get(), &descDSV, mDepthStencilView.ReleaseAndGetAddressOf())); - - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - DepthBuffer *depthBuf = rsys->_addManualDepthBuffer( mDepthStencilView.Get(), mWidth, mHeight, - mFSAAType.Count, mFSAAType.Quality ); - - //Don't forget we want this window to use _this_ depth buffer - this->attachDepthBuffer( depthBuf ); - } - } - //--------------------------------------------------------------------- - void D3D11RenderWindowBase::_destroySizeDependedD3DResources() - { - mpBackBuffer.Reset(); - mpBackBufferNoMSAA.Reset(); - mRenderTargetView.Reset(); - - // delete manual depth buffer (depth buffer view non-owning wrapper) - DepthBuffer* depthBuf = this->getDepthBuffer(); - detachDepthBuffer(); - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - rsys->_removeManualDepthBuffer(depthBuf); - delete depthBuf; - - mDepthStencilView.Reset(); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowBase::destroy() - { - _destroySizeDependedD3DResources(); - - mActive = false; - mClosed = true; - } - //--------------------------------------------------------------------- - void D3D11RenderWindowBase::updateImpl() - { - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - rsys->validateDevice(); - - RenderWindow::updateImpl(); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowBase::_updateViewportsDimensions() - { - // Notify viewports of resize - ViewportList::iterator it = mViewportList.begin(); - while( it != mViewportList.end() ) - (*it++).second->_updateDimensions(); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowBase::_queryDxgiDeviceImpl(IDXGIDeviceN** dxgiDevice) - { - if (mDevice.isNull()) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "D3D11Device is NULL!", - "D3D11RenderWindowBase::_queryDxgiDevice"); - } - - OGRE_CHECK_DX_ERROR(mDevice->QueryInterface( __uuidof(IDXGIDeviceN), (void**)dxgiDevice )); - } - - uint D3D11RenderWindowBase::getNumberOfViews() const { return 1; } - - ID3D11Texture2D* D3D11RenderWindowBase::getSurface(uint index) const - { - return index == 0 ? mpBackBuffer.Get() : NULL; - } - - ID3D11RenderTargetView* D3D11RenderWindowBase::getRenderTargetView(uint index) const - { - return index == 0 ? mRenderTargetView.Get() : NULL; - } - - //--------------------------------------------------------------------- - void D3D11RenderWindowBase::getCustomAttribute( const String& name, void* pData ) - { - // Valid attributes and their equvalent native functions: - // D3DDEVICE : getD3DDevice - // WINDOW : getWindowHandle - - if (name == "D3DDEVICE") - { - *(ID3D11DeviceN**)pData = mDevice.get(); - } - else - { - RenderWindow::getCustomAttribute(name, pData); - } - } - //--------------------------------------------------------------------- - void D3D11RenderWindowBase::copyContentsToMemory(const Box& src, const PixelBox &dst, FrameBuffer buffer) - { - if(src.right > mWidth || src.bottom > mHeight || src.front != 0 || src.back != 1 - || dst.getWidth() != src.getWidth() || dst.getHeight() != src.getHeight() || dst.getDepth() != 1) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Invalid box.", "D3D11RenderWindowBase::copyContentsToMemory"); - } - - if(!mpBackBuffer) - return; - - // get the backbuffer desc - D3D11_TEXTURE2D_DESC BBDesc; - mpBackBuffer->GetDesc( &BBDesc ); - UINT srcSubresource = 0; - D3D11_BOX srcBoxDx11 = { src.left, src.top, 0, src.right, src.bottom, 1 }; - - // We need data from backbuffer without MSAA - ComPtr backbufferNoMSAA; - if(BBDesc.SampleDesc.Count == 1) - { - backbufferNoMSAA = mpBackBuffer; - } - else if(mpBackBufferNoMSAA) - { - backbufferNoMSAA = mpBackBufferNoMSAA; - mDevice.GetImmediateContext()->ResolveSubresource(backbufferNoMSAA.Get(), 0, mpBackBuffer.Get(), 0, BBDesc.Format); - mDevice.throwIfFailed("Error resolving MSAA subresource", "D3D11RenderWindowBase::copyContentsToMemory"); - } - else - { - D3D11_TEXTURE2D_DESC desc = BBDesc; - desc.SampleDesc.Count = 1; - desc.SampleDesc.Quality = 0; - desc.Usage = D3D11_USAGE_DEFAULT; - desc.BindFlags = 0; - desc.CPUAccessFlags = 0; - - HRESULT hr = mDevice->CreateTexture2D(&desc, NULL, backbufferNoMSAA.ReleaseAndGetAddressOf()); - mDevice.throwIfFailed(hr, "Error creating texture without MSAA", "D3D11RenderWindowBase::copyContentsToMemory"); - - mDevice.GetImmediateContext()->ResolveSubresource(backbufferNoMSAA.Get(), 0, mpBackBuffer.Get(), 0, BBDesc.Format); - mDevice.throwIfFailed("Error resolving MSAA subresource", "D3D11RenderWindowBase::copyContentsToMemory"); - } - - // change the parameters of the texture so we can read it - BBDesc.SampleDesc.Count = 1; - BBDesc.SampleDesc.Quality = 0; - BBDesc.Usage = D3D11_USAGE_STAGING; - BBDesc.BindFlags = 0; - BBDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; - - // Create the staging texture - ComPtr stagingTexture; - HRESULT hr = mDevice->CreateTexture2D(&BBDesc, NULL, stagingTexture.ReleaseAndGetAddressOf()); - mDevice.throwIfFailed(hr, "Error creating staging texture", "D3D11RenderWindowBase::copyContentsToMemory"); - - // Copy the back buffer into the staging texture - mDevice.GetImmediateContext()->CopySubresourceRegion( - stagingTexture.Get(), srcSubresource, srcBoxDx11.left, srcBoxDx11.top, srcBoxDx11.front, - backbufferNoMSAA.Get(), srcSubresource, &srcBoxDx11); - mDevice.throwIfFailed("Error while copying to staging texture", "D3D11RenderWindowBase::copyContentsToMemory"); - - // Map the subresource of the staging texture - D3D11_MAPPED_SUBRESOURCE mapped = {0}; - hr = mDevice.GetImmediateContext()->Map(stagingTexture.Get(), srcSubresource, D3D11_MAP_READ, 0, &mapped); - mDevice.throwIfFailed(hr, "Error while mapping staging texture", "D3D11RenderWindowBase::copyContentsToMemory"); - - // Read the data out of the texture - PixelBox locked = D3D11Mappings::getPixelBoxWithMapping(srcBoxDx11, BBDesc.Format, mapped); - PixelUtil::bulkPixelConversion(locked, dst); - - // Release the staging texture - mDevice.GetImmediateContext()->Unmap(stagingTexture.Get(), srcSubresource); - } - //--------------------------------------------------------------------- -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - void D3D11RenderWindowBase::_validateStereo() - { - mStereoEnabled = D3D11StereoDriverBridge::getSingleton().isStereoEnabled(this->getName()); - } -#endif -#pragma endregion - - //--------------------------------------------------------------------- - // class D3D11RenderWindowSwapChainBased - //--------------------------------------------------------------------- -#pragma region D3D11RenderWindowSwapChainBased - D3D11RenderWindowSwapChainBased::D3D11RenderWindowSwapChainBased(D3D11Device & device) - : D3D11RenderWindowBase(device) - { - ZeroMemory( &mSwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC_N) ); - mUseFlipMode = false; - mVSync = false; - mVSyncInterval = 1; - - memset(&mPreviousPresentStats, 0, sizeof(mPreviousPresentStats)); - mPreviousPresentStatsIsValid = false; - mVBlankMissCount = 0; - } - //--------------------------------------------------------------------- - void D3D11RenderWindowSwapChainBased::destroy() - { - _destroySwapChain(); - D3D11RenderWindowBase::destroy(); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowSwapChainBased::notifyDeviceLost(D3D11Device* device) - { - _destroySizeDependedD3DResources(); - _destroySwapChain(); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowSwapChainBased::notifyDeviceRestored(D3D11Device* device) - { - _createSwapChain(); - _createSizeDependedD3DResources(); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowSwapChainBased::_destroySwapChain() - { - if(mIsFullScreen && mpSwapChain) - mpSwapChain->SetFullscreenState(false, NULL); // get back from fullscreen - - mpSwapChain.Reset(); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowSwapChainBased::_createSwapChain(void) - { - ZeroMemory( &mSwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC_N) ); - - // here the mSwapChainDesc and mpSwapChain are initialized - OGRE_CHECK_DX_ERROR(_createSwapChainImpl(_queryDxgiDevice().Get())); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowSwapChainBased::_createSizeDependedD3DResources() - { - mpBackBuffer.Reset(); - mpBackBufferNoMSAA.Reset(); - - HRESULT hr = S_OK; - if(mUseFlipMode && mFSAAType.Count > 1) - { - // Swapchain does not support FSAA in FlipMode, therefore create separate back buffer with FSAA - // Swapchain(FSAA=0, SRGB=0) <-ResolveSubresource- Buffer(FSAA=4x, SRGB=0) <= RenderTargetView(FSAA=4x, SRGB=0) - D3D11_TEXTURE2D_DESC desc = { 0 }; - desc.Width = mWidth; - desc.Height = mHeight; - desc.MipLevels = 1; - desc.ArraySize = 1; - desc.Format = _getRenderFormat(); - desc.SampleDesc.Count = mFSAAType.Count; - desc.SampleDesc.Quality = mFSAAType.Quality; - desc.Usage = D3D11_USAGE_DEFAULT; - desc.BindFlags = D3D11_BIND_RENDER_TARGET; - desc.CPUAccessFlags = 0; - desc.MiscFlags = 0; - - hr = mDevice->CreateTexture2D(&desc, NULL, mpBackBuffer.ReleaseAndGetAddressOf()); - - if(SUCCEEDED(hr) && isHardwareGammaEnabled()) - { - // The worst possible combo, additional buffer needed - // Swapchain(FSAA=0, SRGB=0) <-CopyResource- Buffer2(FSAA=0, SRGB=1) <-ResolveSubresource- Buffer(FSAA=4x, SRGB=1) <= RenderTargetView(FSAA=4x, SRGB=1) - desc.SampleDesc.Count = 1; - desc.SampleDesc.Quality = 0; - - hr = mDevice->CreateTexture2D(&desc, NULL, mpBackBufferNoMSAA.ReleaseAndGetAddressOf()); - } - } - else - { - // Obtain back buffer from swapchain - hr = mpSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)mpBackBuffer.ReleaseAndGetAddressOf()); - } - - if(FAILED(hr)) - { - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Unable to Get Back Buffer for swap chain", - "D3D11RenderWindow::_createSizeDependedD3DResources"); - } - - // create all other size depended resources - D3D11RenderWindowBase::_createSizeDependedD3DResources(); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowSwapChainBased::_changeBuffersFSAA() - { - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - rsys->fireDeviceEvent(&mDevice,"RenderWindowBeforeResize",this); - - _destroySizeDependedD3DResources(); - - if(mUseFlipMode) - { - // swapchain is not multisampled in flip sequential mode, so we reuse it - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - rsys->determineFSAASettings(mFSAA, mFSAAHint, _getRenderFormat(), &mFSAAType); - } - else - { - _destroySwapChain(); - _createSwapChain(); - } - - _createSizeDependedD3DResources(); - - // Notify viewports of resize - _updateViewportsDimensions(); - rsys->fireDeviceEvent(&mDevice,"RenderWindowResized",this); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowSwapChainBased::_resizeSwapChainBuffers(unsigned width, unsigned height) - { - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - rsys->validateDevice(); - rsys->fireDeviceEvent(&mDevice,"RenderWindowBeforeResize",this); - - _destroySizeDependedD3DResources(); - - // Call flush before resize buffers to ensure destruction of resources. - // not doing so may result in 'Out of memory' exception. - mDevice.GetImmediateContext()->Flush(); - - // width and height can be zero to autodetect size, therefore do not rely on them - HRESULT hr = mpSwapChain->ResizeBuffers(mSwapChainDesc.BufferCount, width, height, _getSwapChainFormat(), 0); - if(hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) - { - rsys->handleDeviceLost(); - // Everything is set up now. Do not continue execution of this method. HandleDeviceLost will reenter this method - // and correctly set up the new device. - return; - } - else if(FAILED(hr)) - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, "Unable to resize swap chain", "D3D11RenderWindowSwapChainBased::_resizeSwapChainBuffers"); - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - mpSwapChain->GetDesc(&mSwapChainDesc); - mWidth = mSwapChainDesc.BufferDesc.Width; - mHeight = mSwapChainDesc.BufferDesc.Height; - mIsFullScreen = (0 == mSwapChainDesc.Windowed); // Alt-Enter together with SetWindowAssociation() can change this state -#elif OGRE_PLATFORM == OGRE_PLATFORM_WINRT - mpSwapChain->GetDesc1(&mSwapChainDesc); - mWidth = mSwapChainDesc.Width; - mHeight = mSwapChainDesc.Height; -#endif - - _createSizeDependedD3DResources(); - - // Notify viewports of resize - _updateViewportsDimensions(); - rsys->fireDeviceEvent(&mDevice,"RenderWindowResized",this); - } - - //--------------------------------------------------------------------- - void D3D11RenderWindowSwapChainBased::swapBuffers( ) - { - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - rsys->fireDeviceEvent(&mDevice,"BeforeDevicePresent",this); - - if( !mDevice.isNull() ) - { - // Step of resolving MSAA resource for swap chains in FlipSequentialMode should be done by application rather than by OS. - if(mUseFlipMode && mFSAAType.Count > 1) - { - ComPtr swapChainBackBuffer; - HRESULT hr = mpSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)swapChainBackBuffer.ReleaseAndGetAddressOf()); - if(FAILED(hr)) - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, "Error obtaining backbuffer", "D3D11RenderWindowSwapChainBased::swapBuffers"); - if(!isHardwareGammaEnabled()) - { - assert(_getRenderFormat() == _getSwapChainFormat()); - mDevice.GetImmediateContext()->ResolveSubresource(swapChainBackBuffer.Get(), 0, mpBackBuffer.Get(), 0, _getRenderFormat()); - } - else - { - assert(mpBackBufferNoMSAA); - mDevice.GetImmediateContext()->ResolveSubresource(mpBackBufferNoMSAA.Get(), 0, mpBackBuffer.Get(), 0, _getRenderFormat()); - mDevice.GetImmediateContext()->CopyResource(swapChainBackBuffer.Get(), mpBackBufferNoMSAA.Get()); - } - } - - // flip presentation model swap chains have another semantic for first parameter - UINT syncInterval = mUseFlipMode ? std::max(1U, mVSyncInterval) : (mVSync ? mVSyncInterval : 0); - HRESULT hr = mpSwapChain->Present(syncInterval, 0); - if( FAILED(hr) ) - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, "Error Presenting surfaces", "D3D11RenderWindowSwapChainBased::swapBuffers"); - } - } - //--------------------------------------------------------------------- - void D3D11RenderWindowSwapChainBased::updateStats( void ) - { - RenderTarget::updateStats(); - mStats.vBlankMissCount = getVBlankMissCount(); - } - //--------------------------------------------------------------------- - int D3D11RenderWindowSwapChainBased::getVBlankMissCount() - { - if (!(mIsFullScreen || (!mIsFullScreen && isVSyncEnabled() && mUseFlipMode == true && mFSAA == 0))) - { - return -1; - } - - DXGI_FRAME_STATISTICS currentPresentStats; - ZeroMemory(¤tPresentStats, sizeof(currentPresentStats)); - HRESULT hr = mpSwapChain->GetFrameStatistics(¤tPresentStats); - if(FAILED(hr) || currentPresentStats.PresentRefreshCount == 0) - { - mPreviousPresentStatsIsValid = false; - return -1; - } - else - { - if(mPreviousPresentStatsIsValid == true) - { - int currentVBlankMissCount = (currentPresentStats.PresentRefreshCount - mPreviousPresentStats.PresentRefreshCount) - - (currentPresentStats.PresentCount - mPreviousPresentStats.PresentCount); - mVBlankMissCount += std::max(0, currentVBlankMissCount); - } - mPreviousPresentStats = currentPresentStats; - mPreviousPresentStatsIsValid = true; - } - return mVBlankMissCount; - } - -#pragma endregion - - //--------------------------------------------------------------------- - // class D3D11RenderWindowHwnd - //--------------------------------------------------------------------- -#pragma region D3D11RenderWindowHwnd -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - D3D11RenderWindowHwnd::D3D11RenderWindowHwnd(D3D11Device & device) - : D3D11RenderWindowSwapChainBased(device) - { - mHWnd = 0; - mWindowedWinStyle = 0; - mFullscreenWinStyle = 0; - mDesiredWidth = 0; - mDesiredHeight = 0; - mLastSwitchingFullscreenCounter = 0; - } - //--------------------------------------------------------------------- - void D3D11RenderWindowHwnd::create(const String& name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams) - { - D3D11RenderWindowSwapChainBased::create(name, width, height, fullScreen, miscParams); - - WNDPROC windowProc = DefWindowProc; - HWND externalHandle = 0; - String title = name; - - unsigned int colourDepth = 32; - int left = INT_MAX; // Defaults to screen center - int top = INT_MAX; // Defaults to screen center - bool depthBuffer = true; - int monitorIndex = -1; //Default by detecting the adapter from left / top position - size_t fsaaSamples = 0; - String fsaaHint; - - String border = ""; - bool outerSize = false; - bool enableDoubleClick = false; - - if(miscParams) - { - // Get variable-length params - NameValuePairList::const_iterator opt; - // left (x) - opt = miscParams->find("left"); - if(opt != miscParams->end()) - left = StringConverter::parseInt(opt->second); - // top (y) - opt = miscParams->find("top"); - if(opt != miscParams->end()) - top = StringConverter::parseInt(opt->second); - // Window title - opt = miscParams->find("title"); - if(opt != miscParams->end()) - title = opt->second; - opt = miscParams->find("windowProc"); - if (opt != miscParams->end()) - windowProc = reinterpret_cast(StringConverter::parseSizeT(opt->second)); - // externalWindowHandle -> externalHandle - opt = miscParams->find("externalWindowHandle"); - if (opt == miscParams->end()) - opt = miscParams->find("parentWindowHandle"); - if(opt != miscParams->end()) - externalHandle = (HWND)StringConverter::parseSizeT(opt->second); - // window border style - opt = miscParams->find("border"); - if(opt != miscParams->end()) - border = opt->second; - // set outer dimensions? - opt = miscParams->find("outerDimensions"); - if(opt != miscParams->end()) - outerSize = StringConverter::parseBool(opt->second); - opt = miscParams->find("monitorIndex"); - if(opt != miscParams->end()) - monitorIndex = StringConverter::parseInt(opt->second); - -#if defined(_WIN32_WINNT_WIN8) && _WIN32_WINNT >= _WIN32_WINNT_WIN8 - // useFlipMode [parseBool] - opt = miscParams->find("useFlipMode"); - if(opt != miscParams->end()) - mUseFlipMode = IsWindows8OrGreater() && StringConverter::parseBool(opt->second); -#endif - // vsync [parseBool] - opt = miscParams->find("vsync"); - if(opt != miscParams->end()) - mVSync = StringConverter::parseBool(opt->second); - // vsyncInterval [parseUnsignedInt] - opt = miscParams->find("vsyncInterval"); - if(opt != miscParams->end()) - mVSyncInterval = StringConverter::parseUnsignedInt(opt->second); - - // enable double click messages - opt = miscParams->find("enableDoubleClick"); - if(opt != miscParams->end()) - enableDoubleClick = StringConverter::parseBool(opt->second); - - } - - mIsFullScreen = fullScreen; - - - // Destroy current window if any - if( mHWnd ) - destroy(); - - if (!externalHandle) - { - DWORD dwStyleEx = 0; - HMONITOR hMonitor = NULL; - MONITORINFO monitorInfo; - RECT rc; - if (hMonitor == NULL) - { - POINT windowAnchorPoint; - windowAnchorPoint.x = left; - windowAnchorPoint.y = top; - hMonitor = MonitorFromPoint(windowAnchorPoint, MONITOR_DEFAULTTONEAREST); - } - memset(&monitorInfo, 0, sizeof(MONITORINFO)); - monitorInfo.cbSize = sizeof(MONITORINFO); - GetMonitorInfo(hMonitor, &monitorInfo); - mFullscreenWinStyle = WS_CLIPCHILDREN | WS_POPUP; - mWindowedWinStyle = WS_CLIPCHILDREN; - if (!mHidden) - { - mFullscreenWinStyle |= WS_VISIBLE; - mWindowedWinStyle |= WS_VISIBLE; - } - if (border == "none") - mWindowedWinStyle |= WS_POPUP; - else if (border == "fixed") - mWindowedWinStyle |= WS_OVERLAPPED | WS_BORDER | WS_CAPTION | - WS_SYSMENU | WS_MINIMIZEBOX; - else - mWindowedWinStyle |= WS_OVERLAPPEDWINDOW; - unsigned int winWidth, winHeight; - winWidth = width; - winHeight = height; - if (left == INT_MAX || top == INT_MAX) - { - uint32 screenw = monitorInfo.rcWork.right - monitorInfo.rcWork.left; - uint32 screenh = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top; - uint32 outerw = (winWidth < screenw)? winWidth : screenw; - uint32 outerh = (winHeight < screenh)? winHeight : screenh; - if (left == INT_MAX) - left = monitorInfo.rcWork.left + (screenw - outerw) / 2; - else if (monitorIndex != -1) - left += monitorInfo.rcWork.left; - if (top == INT_MAX) - top = monitorInfo.rcWork.top + (screenh - outerh) / 2; - else if (monitorIndex != -1) - top += monitorInfo.rcWork.top; - } - else if (monitorIndex != -1) - { - left += monitorInfo.rcWork.left; - top += monitorInfo.rcWork.top; - } - mWidth = mDesiredWidth = width; - mHeight = mDesiredHeight = height; - mTop = top; - mLeft = left; - if (fullScreen) - { - dwStyleEx |= WS_EX_TOPMOST; - mTop = monitorInfo.rcMonitor.top; - mLeft = monitorInfo.rcMonitor.left; - } - else - { - adjustWindow(width, height, &winWidth, &winHeight); - if (!outerSize) - { - SetRect(&rc, 0, 0, mWidth, mHeight); - AdjustWindowRect(&rc, getWindowStyle(fullScreen), false); - mWidth = rc.right - rc.left; - mHeight = rc.bottom - rc.top; - if (mLeft < monitorInfo.rcWork.left) - mLeft = monitorInfo.rcWork.left; - if (mTop < monitorInfo.rcWork.top) - mTop = monitorInfo.rcWork.top; - if (static_cast(winWidth) > monitorInfo.rcWork.right - mLeft) - winWidth = monitorInfo.rcWork.right - mLeft; - if (static_cast(winHeight) > monitorInfo.rcWork.bottom - mTop) - winHeight = monitorInfo.rcWork.bottom - mTop; - } - } - UINT classStyle = 0; - if (enableDoubleClick) - classStyle |= CS_DBLCLKS; - - HINSTANCE hInst = NULL; - static TCHAR staticVar; - GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, &staticVar, &hInst); - - WNDCLASS wc = { classStyle, windowProc, 0, 0, hInst, - LoadIcon(0, IDI_APPLICATION), LoadCursor(NULL, IDC_ARROW), - (HBRUSH)GetStockObject(BLACK_BRUSH), 0, OGRE_D3D11_WIN_CLASS_NAME }; - RegisterClass(&wc); - mIsExternal = false; - mHWnd = CreateWindowEx(dwStyleEx, OGRE_D3D11_WIN_CLASS_NAME, title.c_str(), getWindowStyle(fullScreen), - mLeft, mTop, winWidth, winHeight, 0, 0, hInst, this); - } - else - { - mHWnd = externalHandle; - mIsExternal = true; - } - - - RECT rc; - // top and left represent outer window coordinates - GetWindowRect(mHWnd, &rc); - mTop = rc.top; - mLeft = rc.left; - // width and height represent interior drawable area - GetClientRect(mHWnd, &rc); - mWidth = rc.right; - mHeight = rc.bottom; - - LogManager::getSingleton().stream() - << "D3D11: Created D3D11 Rendering Window '" - << mName << "' : " << mWidth << "x" << mHeight; - - _createSwapChain(); - _createSizeDependedD3DResources(); - mDevice.GetDXGIFactory()->MakeWindowAssociation(mHWnd, NULL); - setHidden(mHidden); - - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - rsys->fireDeviceEvent(&mDevice,"RenderWindowCreated",this); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowHwnd::destroy() - { - D3D11RenderWindowSwapChainBased::destroy(); - - if (mHWnd && !mIsExternal) - { - DestroyWindow(mHWnd); - } - - mHWnd = NULL; - } - //--------------------------------------------------------------------- - void D3D11RenderWindowHwnd::notifyDeviceRestored(D3D11Device* device) - { - D3D11RenderWindowSwapChainBased::notifyDeviceRestored(device); - mDevice.GetDXGIFactory()->MakeWindowAssociation(mHWnd, NULL); - } - //--------------------------------------------------------------------- - HRESULT D3D11RenderWindowHwnd::_createSwapChainImpl(IDXGIDeviceN* pDXGIDevice) - { - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - rsys->determineFSAASettings(mFSAA, mFSAAHint, _getRenderFormat(), &mFSAAType); - - ZeroMemory(&mSwapChainDesc, sizeof(DXGI_SWAP_CHAIN_DESC_N)); - mSwapChainDesc.BufferDesc.Width = mWidth; - mSwapChainDesc.BufferDesc.Height = mHeight; - mSwapChainDesc.BufferDesc.Format = _getSwapChainFormat(); - - mSwapChainDesc.BufferDesc.RefreshRate.Numerator = 0; - mSwapChainDesc.BufferDesc.RefreshRate.Denominator = 0; - - mSwapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; - mSwapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; - -#if defined(_WIN32_WINNT_WIN8) && _WIN32_WINNT >= _WIN32_WINNT_WIN8 - if(mUseFlipMode) - { - mSwapChainDesc.SampleDesc.Count = 1; - mSwapChainDesc.SampleDesc.Quality = 0; - mSwapChainDesc.BufferCount = 2; -#if defined(_WIN32_WINNT_WIN10) // we want DXGI_SWAP_EFFECT_FLIP_DISCARD even if _WIN32_WINNT < _WIN32_WINNT_WIN10 but runtime is Win10 - mSwapChainDesc.SwapEffect = IsWindows10OrGreater() ? DXGI_SWAP_EFFECT_FLIP_DISCARD : DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; -#else - mSwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; -#endif - } - else -#endif - { - assert(!mUseFlipMode); - mSwapChainDesc.SampleDesc.Count = mFSAAType.Count; - mSwapChainDesc.SampleDesc.Quality = mFSAAType.Quality; - mSwapChainDesc.BufferCount = 1; - mSwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; - } - - mSwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; - mSwapChainDesc.OutputWindow = mHWnd; - mSwapChainDesc.Windowed = !mIsFullScreen; - mSwapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; - - if (!mVSync && !mIsFullScreen) - { - // NB not using vsync in windowed mode in D3D11 can cause jerking at low - // frame rates no matter what buffering modes are used (odd - perhaps a - // timer issue in D3D11 since GL doesn't suffer from this) - // low is < 200fps in this context - LogManager::getSingleton().logWarning( - "D3D11: disabling VSync in windowed mode can cause timing issues at lower " - "frame rates, turn VSync on if you observe this problem."); - } - - // Create swap chain - HRESULT hr = mDevice.GetDXGIFactory()->CreateSwapChain(pDXGIDevice, &mSwapChainDesc, mpSwapChain.ReleaseAndGetAddressOf()); - - return hr; - } - //--------------------------------------------------------------------- - bool D3D11RenderWindowHwnd::isVisible() const - { - HWND currentWindowHandle = mHWnd; - bool visible; - while ((visible = (IsIconic(currentWindowHandle) == false)) && - (GetWindowLong(currentWindowHandle, GWL_STYLE) & WS_CHILD) != 0) - { - currentWindowHandle = GetParent(currentWindowHandle); - } - return visible; - } - //--------------------------------------------------------------------- - void D3D11RenderWindowHwnd::setHidden(bool hidden) - { - mHidden = hidden; - if (!mIsExternal) - { - if (hidden) - ShowWindow(mHWnd, SW_HIDE); - else - ShowWindow(mHWnd, SW_SHOWNORMAL); - } - } - //--------------------------------------------------------------------- - void D3D11RenderWindowHwnd::reposition(int top, int left) - { - if (mHWnd && !mIsFullScreen) - { - SetWindowPos(mHWnd, 0, top, left, 0, 0, - SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); - } - } - //--------------------------------------------------------------------- - void D3D11RenderWindowHwnd::resize(unsigned int width, unsigned int height) - { - - if (!mIsExternal) - { - if (mHWnd && !mIsFullScreen) - { - unsigned int winWidth, winHeight; - adjustWindow(width, height, &winWidth, &winHeight); - SetWindowPos(mHWnd, 0, 0, 0, winWidth, winHeight, - SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE); - } - } - else - updateWindowRect(); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowHwnd::windowMovedOrResized() - { - if (!mHWnd || IsIconic(mHWnd) || !mpSwapChain) - return; - - updateWindowRect(); - - RECT rc; - // top and left represent outer window position - GetWindowRect(mHWnd, &rc); - mTop = rc.top; - mLeft = rc.left; - // width and height represent drawable area only - GetClientRect(mHWnd, &rc); - unsigned int width = rc.right - rc.left; - unsigned int height = rc.bottom - rc.top; - - if (width == 0) - width = 1; - if (height == 0) - height = 1; - - if (mWidth == width && mHeight == height) - return; - - _resizeSwapChainBuffers(width, height); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowHwnd::getCustomAttribute( const String& name, void* pData ) - { - // Valid attributes and their equvalent native functions: - // D3DDEVICE : getD3DDevice - // WINDOW : getWindowHandle - - if( name == "WINDOW" ) - { - HWND *pWnd = (HWND*)pData; - *pWnd = mHWnd; - return; - } - - D3D11RenderWindowSwapChainBased::getCustomAttribute(name, pData); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowHwnd::setFullscreen(bool fullScreen, unsigned int width, unsigned int height) - { - if (fullScreen != mIsFullScreen || width != mWidth || height != mHeight) - { - - if (fullScreen != mIsFullScreen) - { - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - rsys->addToSwitchingFullscreenCounter(); - } - - DWORD dwStyle = WS_VISIBLE | WS_CLIPCHILDREN; - - bool oldFullscreen = mIsFullScreen; - mIsFullScreen = fullScreen; - - if (fullScreen) - { - HMONITOR hMonitor = MonitorFromWindow(mHWnd, MONITOR_DEFAULTTONEAREST); - MONITORINFO monitorInfo; - memset(&monitorInfo, 0, sizeof(MONITORINFO)); - monitorInfo.cbSize = sizeof(MONITORINFO); - GetMonitorInfo(hMonitor, &monitorInfo); - mTop = monitorInfo.rcMonitor.top; - mLeft = monitorInfo.rcMonitor.left; - - // need different ordering here - - if (oldFullscreen) - { - // was previously fullscreen, just changing the resolution - SetWindowPos(mHWnd, HWND_TOPMOST, 0, 0, width, height, SWP_NOACTIVATE); - } - else - { - SetWindowPos(mHWnd, HWND_TOPMOST, 0, 0, width, height, SWP_NOACTIVATE); - SetWindowLong(mHWnd, GWL_STYLE, dwStyle); - SetWindowPos(mHWnd, 0, 0,0, 0,0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER); - } - } - else - { - unsigned int winWidth, winHeight; - winWidth = mWidth; - winHeight = mHeight; - adjustWindow(mWidth, mHeight, &winWidth, &winHeight); - SetWindowLong(mHWnd, GWL_STYLE, getWindowStyle(mIsFullScreen)); - SetWindowPos(mHWnd, HWND_NOTOPMOST, 0, 0, winWidth, winHeight, - SWP_DRAWFRAME | SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOACTIVATE); - updateWindowRect(); - } - - mSwapChainDesc.Windowed = !fullScreen; - mSwapChainDesc.BufferDesc.RefreshRate.Numerator = 0; - mSwapChainDesc.BufferDesc.RefreshRate.Denominator=0; - mSwapChainDesc.BufferDesc.Height = height; - mSwapChainDesc.BufferDesc.Width = width; - - if ((oldFullscreen && fullScreen) || mIsExternal) - { - // Notify viewports of resize - _updateViewportsDimensions(); - } - } - } - //--------------------------------------------------------------------- - void D3D11RenderWindowHwnd::adjustWindow(unsigned int clientWidth, unsigned int clientHeight, - unsigned int* winWidth, unsigned int* winHeight) - { - RECT rc; - SetRect(&rc, 0, 0, clientWidth, clientHeight); - AdjustWindowRect(&rc, getWindowStyle(mIsFullScreen), false); - *winWidth = rc.right - rc.left; - *winHeight = rc.bottom - rc.top; - } - - void D3D11RenderWindowHwnd::_finishSwitchingFullscreen() - { - if(mIsFullScreen) - { - // Need to reset the region on the window sometimes, when the - // windowed mode was constrained by desktop - HRGN hRgn = CreateRectRgn(0,0,mSwapChainDesc.BufferDesc.Width, mSwapChainDesc.BufferDesc.Height); - SetWindowRgn(mHWnd, hRgn, FALSE); - } - else - { - // When switching back to windowed mode, need to reset window size - // after device has been restored - if (mWidth != mDesiredWidth || - mHeight != mDesiredHeight) - { - mWidth = mDesiredWidth; - mHeight = mDesiredHeight; - } - unsigned int winWidth, winHeight; - adjustWindow(mWidth, mHeight, &winWidth, &winHeight); - HMONITOR hMonitor = MonitorFromWindow(mHWnd, MONITOR_DEFAULTTONEAREST); - MONITORINFO monitorInfo; - memset(&monitorInfo, 0, sizeof(MONITORINFO)); - monitorInfo.cbSize = sizeof(MONITORINFO); - GetMonitorInfo(hMonitor, &monitorInfo); - ULONG screenw = monitorInfo.rcWork.right - monitorInfo.rcWork.left; - ULONG screenh = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top; - int left = screenw > winWidth ? ((screenw - winWidth) / 2) : 0; - int top = screenh > winHeight ? ((screenh - winHeight) / 2) : 0; - SetWindowPos(mHWnd, HWND_NOTOPMOST, left, top, winWidth, winHeight, - SWP_DRAWFRAME | SWP_FRAMECHANGED | SWP_NOACTIVATE); - updateWindowRect(); - - - } - - DXGI_SWAP_CHAIN_DESC dsc; - ZeroMemory(&dsc, sizeof(dsc)); - mpSwapChain->GetDesc(&dsc); - if((dsc.Windowed != 0) == mIsFullScreen) - { - mpSwapChain->SetFullscreenState(mIsFullScreen, NULL); - } - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - mLastSwitchingFullscreenCounter = rsys->getSwitchingFullscreenCounter(); - - } - - void D3D11RenderWindowHwnd::updateWindowRect() - { - RECT rc; - BOOL result; - result = GetWindowRect(mHWnd, &rc); - if (result == FALSE) - { - mTop = 0; - mLeft = 0; - mWidth = 0; - mHeight = 0; - return; - } - mTop = rc.top; - mLeft = rc.left; - result = GetClientRect(mHWnd, &rc); - if (result == FALSE) - { - mTop = 0; - mLeft = 0; - mWidth = 0; - mHeight = 0; - return; - } - unsigned int width = rc.right - rc.left; - unsigned int height = rc.bottom - rc.top; - if (width != mWidth || height != mHeight) - { - mWidth = rc.right - rc.left; - mHeight = rc.bottom - rc.top; - _resizeSwapChainBuffers(mWidth, mHeight); - } - } - void D3D11RenderWindowHwnd::_beginUpdate() - { - if (mIsExternal) - { - updateWindowRect(); - } - if (mWidth == 0 || mHeight == 0) - { - return; - } - DXGI_SWAP_CHAIN_DESC dsc; - ZeroMemory(&dsc, sizeof(dsc)); - mpSwapChain->GetDesc(&dsc); - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - if(rsys->getSwitchingFullscreenCounter() > mLastSwitchingFullscreenCounter - || GetFocus() == mHWnd && ((dsc.Windowed != 0) == mIsFullScreen)) - { - _finishSwitchingFullscreen(); - } - RenderWindow::_beginUpdate(); - } - void D3D11RenderWindowHwnd::setActive(bool state) - { - if (mHWnd && mpSwapChain && mIsFullScreen && state) - { - DXGI_SWAP_CHAIN_DESC dsc; - ZeroMemory(&dsc, sizeof(dsc)); - mpSwapChain->GetDesc(&dsc); - if(dsc.Windowed) - { - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - rsys->addToSwitchingFullscreenCounter(); - } - - } - RenderWindow::setActive(state); - } -#endif -#pragma endregion - - //--------------------------------------------------------------------- - // class D3D11RenderWindowCoreWindow - //--------------------------------------------------------------------- -#pragma region D3D11RenderWindowCoreWindow -#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT - D3D11RenderWindowCoreWindow::D3D11RenderWindowCoreWindow(D3D11Device& device) - : D3D11RenderWindowSwapChainBased(device) - { - mUseFlipMode = true; - } - - float D3D11RenderWindowCoreWindow::getViewPointToPixelScale() - { -#if _WIN32_WINNT > _WIN32_WINNT_WIN8 - return Windows::Graphics::Display::DisplayInformation::GetForCurrentView()->LogicalDpi / 96; -#else - return Windows::Graphics::Display::DisplayProperties::LogicalDpi / 96; -#endif - } - - void D3D11RenderWindowCoreWindow::create(const String& name, unsigned int widthPt, unsigned int heightPt, - bool fullScreen, const NameValuePairList *miscParams) - { - D3D11RenderWindowSwapChainBased::create(name, widthPt, heightPt, fullScreen, miscParams); - - Windows::UI::Core::CoreWindow^ externalHandle = nullptr; - - if(miscParams) - { - // Get variable-length params - NameValuePairList::const_iterator opt; - // externalWindowHandle -> externalHandle - opt = miscParams->find("externalWindowHandle"); - if(opt != miscParams->end()) - externalHandle = reinterpret_cast((void*)StringConverter::parseSizeT(opt->second)); - else - externalHandle = Windows::UI::Core::CoreWindow::GetForCurrentThread(); - } - - // Reset current window if any - mCoreWindow = nullptr; - - if (!externalHandle) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "External window handle is not specified.", "D3D11RenderWindow::create" ); - } - else - { - mCoreWindow = externalHandle; - mIsExternal = true; - } - - float scale = getViewPointToPixelScale(); - Windows::Foundation::Rect rc = mCoreWindow->Bounds; - mLeft = (int)(rc.X * scale + 0.5f); - mTop = (int)(rc.Y * scale + 0.5f); - mWidth = (int)(rc.Width * scale + 0.5f); - mHeight = (int)(rc.Height * scale + 0.5f); - - LogManager::getSingleton().stream() << std::fixed << std::setprecision(1) - << "D3D11: Created D3D11 Rendering Window \"" << mName << "\", " << rc.Width << " x " << rc.Height - << ", with backing store " << mWidth << "x" << mHeight << " " - << "using content scaling factor " << scale; - - _createSwapChain(); - _createSizeDependedD3DResources(); - } - - //--------------------------------------------------------------------- - void D3D11RenderWindowCoreWindow::destroy() - { - D3D11RenderWindowSwapChainBased::destroy(); - - if (mCoreWindow.Get() && !mIsExternal) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Only external window handles are supported." - , "D3D11RenderWindow::destroy" ); - } - - mCoreWindow = nullptr; - } - //--------------------------------------------------------------------- - HRESULT D3D11RenderWindowCoreWindow::_createSwapChainImpl(IDXGIDeviceN* pDXGIDevice) - { -#if !__OGRE_WINRT_PHONE - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - rsys->determineFSAASettings(mFSAA, mFSAAHint, _getRenderFormat(), &mFSAAType); -#endif - - mSwapChainDesc.Width = 0; // Use automatic sizing. - mSwapChainDesc.Height = 0; - mSwapChainDesc.Format = _getSwapChainFormat(); - mSwapChainDesc.Stereo = false; - - assert(mUseFlipMode); // i.e. no FSAA for swapchain, but can be enabled in separate backbuffer - mSwapChainDesc.SampleDesc.Count = 1; - mSwapChainDesc.SampleDesc.Quality = 0; - - mSwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; -#if __OGRE_WINRT_PHONE_80 - mSwapChainDesc.BufferCount = 1; // WP8: One buffer. - mSwapChainDesc.Scaling = DXGI_SCALING_STRETCH; // WP8: Must be stretch scaling mode. - mSwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; // WP8: No swap effect. -#else - mSwapChainDesc.BufferCount = 2; // Use two buffers to enable flip effect. - mSwapChainDesc.Scaling = DXGI_SCALING_NONE; // Otherwise stretch would be used by default. - mSwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // MS recommends using this swap effect for all applications. -#endif - mSwapChainDesc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED; - - // Create swap chain - HRESULT hr = mDevice.GetDXGIFactory()->CreateSwapChainForCoreWindow(pDXGIDevice, reinterpret_cast(mCoreWindow.Get()), &mSwapChainDesc, NULL, mpSwapChain.ReleaseAndGetAddressOf()); - if (FAILED(hr)) - return hr; - - // Ensure that DXGI does not queue more than one frame at a time. This both reduces - // latency and ensures that the application will only render after each VSync, minimizing - // power consumption. - hr = pDXGIDevice->SetMaximumFrameLatency(1); - return hr; - } - //--------------------------------------------------------------------- - bool D3D11RenderWindowCoreWindow::isVisible() const - { - return (mCoreWindow.Get() && Windows::UI::Core::CoreWindow::GetForCurrentThread() == mCoreWindow.Get()); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowCoreWindow::windowMovedOrResized() - { - float scale = getViewPointToPixelScale(); - Windows::Foundation::Rect rc = mCoreWindow->Bounds; - mLeft = (int)(rc.X * scale + 0.5f); - mTop = (int)(rc.Y * scale + 0.5f); - mWidth = (int)(rc.Width * scale + 0.5f); - mHeight = (int)(rc.Height * scale + 0.5f); - - _resizeSwapChainBuffers(0, 0); // pass zero to autodetect size - } - -#endif -#pragma endregion - - //--------------------------------------------------------------------- - // class D3D11RenderWindowSwapChainPanel - //--------------------------------------------------------------------- -#pragma region D3D11RenderWindowSwapChainPanel -#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT && defined(_WIN32_WINNT_WINBLUE) && _WIN32_WINNT >= _WIN32_WINNT_WINBLUE - D3D11RenderWindowSwapChainPanel::D3D11RenderWindowSwapChainPanel(D3D11Device& device) - : D3D11RenderWindowSwapChainBased(device) - , mCompositionScale(1.0f, 1.0f) - { - mUseFlipMode = true; - } - - float D3D11RenderWindowSwapChainPanel::getViewPointToPixelScale() - { - return std::max(mCompositionScale.Width, mCompositionScale.Height); - } - - void D3D11RenderWindowSwapChainPanel::create(const String& name, unsigned int widthPt, unsigned int heightPt, - bool fullScreen, const NameValuePairList *miscParams) - { - D3D11RenderWindowSwapChainBased::create(name, widthPt, heightPt, fullScreen, miscParams); - - Windows::UI::Xaml::Controls::SwapChainPanel^ externalHandle = nullptr; - - if(miscParams) - { - // Get variable-length params - NameValuePairList::const_iterator opt; - // externalWindowHandle -> externalHandle - opt = miscParams->find("externalWindowHandle"); - if(opt != miscParams->end()) - externalHandle = reinterpret_cast((void*)StringConverter::parseSizeT(opt->second)); - } - - // Reset current control if any - mSwapChainPanel = nullptr; - - if (!externalHandle) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "External window handle is not specified.", "D3D11RenderWindow::create" ); - } - else - { - mSwapChainPanel = externalHandle; - mIsExternal = true; - - // subscribe to important notifications - compositionScaleChangedToken = (mSwapChainPanel->CompositionScaleChanged += - ref new Windows::Foundation::TypedEventHandler([this](Windows::UI::Xaml::Controls::SwapChainPanel^ sender, Platform::Object^ e) - { - windowMovedOrResized(); - })); - sizeChangedToken = (mSwapChainPanel->SizeChanged += - ref new Windows::UI::Xaml::SizeChangedEventHandler([this](Platform::Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e) - { - windowMovedOrResized(); - })); - } - - Windows::Foundation::Size sz = Windows::Foundation::Size(static_cast(mSwapChainPanel->ActualWidth), static_cast(mSwapChainPanel->ActualHeight)); - mCompositionScale = Windows::Foundation::Size(mSwapChainPanel->CompositionScaleX, mSwapChainPanel->CompositionScaleY); - mLeft = 0; - mTop = 0; - mWidth = (int)(sz.Width * mCompositionScale.Width + 0.5f); - mHeight = (int)(sz.Height * mCompositionScale.Height + 0.5f); - - // Prevent zero size DirectX content from being created. - mWidth = std::max(mWidth, 1U); - mHeight = std::max(mHeight, 1U); - - LogManager::getSingleton().stream() << std::fixed << std::setprecision(1) - << "D3D11: Created D3D11 SwapChainPanel Rendering Window \"" << mName << "\", " << sz.Width << " x " << sz.Height - << ", with backing store " << mWidth << "x" << mHeight << " " - << "using content scaling factor { " << mCompositionScale.Width << ", " << mCompositionScale.Height << " }"; - - _createSwapChain(); - _createSizeDependedD3DResources(); - } - - //--------------------------------------------------------------------- - void D3D11RenderWindowSwapChainPanel::destroy() - { - D3D11RenderWindowSwapChainBased::destroy(); - - if (mSwapChainPanel && !mIsExternal) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Only external window handles are supported." - , "D3D11RenderWindow::destroy" ); - } - mSwapChainPanel->CompositionScaleChanged -= compositionScaleChangedToken; compositionScaleChangedToken.Value = 0; - mSwapChainPanel->SizeChanged -= sizeChangedToken; sizeChangedToken.Value = 0; - mSwapChainPanel = nullptr; - } - //--------------------------------------------------------------------- - HRESULT D3D11RenderWindowSwapChainPanel::_createSwapChainImpl(IDXGIDeviceN* pDXGIDevice) - { -#if !__OGRE_WINRT_PHONE - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - rsys->determineFSAASettings(mFSAA, mFSAAHint, _getRenderFormat(), &mFSAAType); -#endif - - mSwapChainDesc.Width = mWidth; // Use automatic sizing. - mSwapChainDesc.Height = mHeight; - mSwapChainDesc.Format = _getSwapChainFormat(); - mSwapChainDesc.Stereo = false; - - assert(mUseFlipMode); // i.e. no FSAA for swapchain, but can be enabled in separate backbuffer - mSwapChainDesc.SampleDesc.Count = 1; - mSwapChainDesc.SampleDesc.Quality = 0; - - mSwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; - mSwapChainDesc.BufferCount = 2; // Use two buffers to enable flip effect. - mSwapChainDesc.Scaling = DXGI_SCALING_STRETCH; // Required for CreateSwapChainForComposition. - mSwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // MS recommends using this swap effect for all applications. - mSwapChainDesc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED; - - // Create swap chain - HRESULT hr = mDevice.GetDXGIFactory()->CreateSwapChainForComposition(pDXGIDevice, &mSwapChainDesc, NULL, mpSwapChain.ReleaseAndGetAddressOf()); - if (FAILED(hr)) - return hr; - - // Associate swap chain with SwapChainPanel - // Get backing native interface for SwapChainPanel - ComPtr panelNative; - hr = reinterpret_cast(mSwapChainPanel)->QueryInterface(IID_PPV_ARGS(panelNative.ReleaseAndGetAddressOf())); - if(FAILED(hr)) - return hr; - hr = panelNative->SetSwapChain(mpSwapChain.Get()); - if(FAILED(hr)) - return hr; - - // Ensure that DXGI does not queue more than one frame at a time. This both reduces - // latency and ensures that the application will only render after each VSync, minimizing - // power consumption. - hr = pDXGIDevice->SetMaximumFrameLatency(1); - if(FAILED(hr)) - return hr; - - hr = _compensateSwapChainCompositionScale(); - return hr; - } - //--------------------------------------------------------------------- - bool D3D11RenderWindowSwapChainPanel::isVisible() const - { - return (mSwapChainPanel && mSwapChainPanel->Visibility == Windows::UI::Xaml::Visibility::Visible); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowSwapChainPanel::windowMovedOrResized() - { - Windows::Foundation::Size sz = Windows::Foundation::Size(static_cast(mSwapChainPanel->ActualWidth), static_cast(mSwapChainPanel->ActualHeight)); - mCompositionScale = Windows::Foundation::Size(mSwapChainPanel->CompositionScaleX, mSwapChainPanel->CompositionScaleY); - mLeft = 0; - mTop = 0; - mWidth = (int)(sz.Width * mCompositionScale.Width + 0.5f); - mHeight = (int)(sz.Height * mCompositionScale.Height + 0.5f); - - // Prevent zero size DirectX content from being created. - mWidth = std::max(mWidth, 1U); - mHeight = std::max(mHeight, 1U); - - _resizeSwapChainBuffers(mWidth, mHeight); - - _compensateSwapChainCompositionScale(); - } - - HRESULT D3D11RenderWindowSwapChainPanel::_compensateSwapChainCompositionScale() - { - // Setup inverse scale on the swap chain - DXGI_MATRIX_3X2_F inverseScale = { 0 }; - inverseScale._11 = 1.0f / mCompositionScale.Width; - inverseScale._22 = 1.0f / mCompositionScale.Height; - ComPtr spSwapChain2; - HRESULT hr = mpSwapChain.As(&spSwapChain2); - if(FAILED(hr)) - return hr; - - hr = spSwapChain2->SetMatrixTransform(&inverseScale); - return hr; - } - -#endif -#pragma endregion - - //--------------------------------------------------------------------- - // class D3D11RenderWindowImageSource - //--------------------------------------------------------------------- -#pragma region D3D11RenderWindowImageSource -#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT && !__OGRE_WINRT_PHONE_80 - - D3D11RenderWindowImageSource::D3D11RenderWindowImageSource(D3D11Device& device) - : D3D11RenderWindowBase(device) - { - } - //--------------------------------------------------------------------- - void D3D11RenderWindowImageSource::create(const String& name, unsigned width, unsigned height, bool fullScreen, const NameValuePairList *miscParams) - { - D3D11RenderWindowBase::create(name, width, height, fullScreen, miscParams); - - mWidth = width; - mHeight = height; - - bool isOpaque = true; - if(miscParams) - { - // Get variable-length params - NameValuePairList::const_iterator opt; - // isOpaque - opt = miscParams->find("isOpaque"); - if(opt != miscParams->end()) - isOpaque = StringConverter::parseBool(opt->second); - } - - // create brush - // TODO: obtain from miscParams optional placeholder image and set inside the brush till first render??? - mBrush = ref new Windows::UI::Xaml::Media::ImageBrush; - - _createSizeDependedD3DResources(); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowImageSource::destroy(void) - { - D3D11RenderWindowBase::destroy(); - - mImageSourceNative.Reset(); - mImageSource = nullptr; - mBrush = nullptr; - } - //--------------------------------------------------------------------- - void D3D11RenderWindowImageSource::notifyDeviceLost(D3D11Device* device) - { - _destroySizeDependedD3DResources(); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowImageSource::notifyDeviceRestored(D3D11Device* device) - { - _createSizeDependedD3DResources(); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowImageSource::_createSizeDependedD3DResources() - { - mpBackBuffer.Reset(); - mpBackBufferNoMSAA.Reset(); - mImageSourceNative.Reset(); - - if(mWidth <= 0 || mHeight <= 0) - { - mImageSource = nullptr; - mBrush->ImageSource = nullptr; - return; - } - - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - rsys->determineFSAASettings(mFSAA, mFSAAHint, _getRenderFormat(), &mFSAAType); - - // create back buffer - ID3D11Texture2D - D3D11_TEXTURE2D_DESC desc = {0}; - desc.Width = mWidth; - desc.Height = mHeight; - desc.MipLevels = 1; - desc.ArraySize = 1; - desc.Format = _getRenderFormat(); - desc.SampleDesc.Count = mFSAAType.Count; - desc.SampleDesc.Quality = mFSAAType.Quality; - desc.Usage = D3D11_USAGE_DEFAULT; - desc.BindFlags = D3D11_BIND_RENDER_TARGET; - desc.CPUAccessFlags = 0; - desc.MiscFlags = 0; - - // Create back buffer, maybe with FSAA - HRESULT hr = mDevice->CreateTexture2D(&desc, NULL, mpBackBuffer.ReleaseAndGetAddressOf()); - if(FAILED(hr) && mFSAAType.Count > 1) - { - // Second chance - try without FSAA, keep mFSAAType synchronized. - LogManager::getSingleton().logMessage("Unable to Create MSAA Back Buffer, retry without MSAA support"); - desc.SampleDesc.Count = mFSAAType.Count = 1; - desc.SampleDesc.Quality = mFSAAType.Quality = 0; - hr = mDevice->CreateTexture2D(&desc, NULL, mpBackBuffer.ReleaseAndGetAddressOf()); - } - if( FAILED(hr) ) - { - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Unable to Create Back Buffer", - "D3D11RenderWindowImageSource::_createSizeDependedD3DResources"); - } - - // Create optional back buffer without FSAA if needed - if(mFSAAType.Count > 1) - { - desc.SampleDesc.Count = 1; - desc.SampleDesc.Quality = 0; - hr = mDevice->CreateTexture2D(&desc, NULL, mpBackBufferNoMSAA.ReleaseAndGetAddressOf()); - if( FAILED(hr) ) - { - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Unable to Create Back Buffer without MSAA", - "D3D11RenderWindowImageSource::_createSizeDependedD3DResources"); - } - } - - // create front buffer - SurfaceImageSource - mImageSource = ref new Windows::UI::Xaml::Media::Imaging::SurfaceImageSource(mWidth, mHeight, true); - reinterpret_cast(mImageSource)->QueryInterface(__uuidof(ISurfaceImageSourceNative), (void **)mImageSourceNative.ReleaseAndGetAddressOf()); - - // set DXGI device for the front buffer - mImageSourceNative->SetDevice(_queryDxgiDevice().Get()); - - // create all other size depended resources - D3D11RenderWindowBase::_createSizeDependedD3DResources(); - - mBrush->ImageSource = mImageSource; - } - //--------------------------------------------------------------------- - void D3D11RenderWindowImageSource::update(bool swapBuffers) - { - if(!mImageSourceNative) - return; - - D3D11RenderWindowBase::update(swapBuffers); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowImageSource::swapBuffers() - { - if(!mImageSourceNative) - return; - - ComPtr dxgiSurface; - RECT updateRect = { 0, 0, (LONG)mWidth, (LONG)mHeight }; - POINT offset = { 0, 0 }; - - HRESULT hr = mImageSourceNative->BeginDraw(updateRect, dxgiSurface.ReleaseAndGetAddressOf(), &offset); - if(hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) - return; - - if(FAILED(hr)) - { - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Unable to Get DXGI surface for SurfaceImageSource", - "D3D11RenderWindowImageSource::swapBuffers"); - } - - ComPtr destTexture; - hr = dxgiSurface.As(&destTexture); - if(FAILED(hr)) - { - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Unable to convert DXGI surface to D3D11 texture", - "D3D11RenderWindowImageSource::swapBuffers"); - } - - // resolve multi-sample texture into single-sample texture if needed - if(mpBackBufferNoMSAA) - { - mDevice.GetImmediateContext()->ResolveSubresource(mpBackBufferNoMSAA.Get(), 0, mpBackBuffer.Get(), 0, _getRenderFormat()); - mDevice.GetImmediateContext()->CopySubresourceRegion1(destTexture.Get(), 0, offset.x, offset.y, 0, mpBackBufferNoMSAA.Get(), 0, NULL, 0); - } - else - mDevice.GetImmediateContext()->CopySubresourceRegion1(destTexture.Get(), 0, offset.x, offset.y, 0, mpBackBuffer.Get(), 0, NULL, 0); - - hr = mImageSourceNative->EndDraw(); - if( FAILED(hr) ) - { - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Drawing into SurfaceImageSource failed", - "D3D11RenderWindowImageSource::swapBuffers"); - } - } - //--------------------------------------------------------------------- - void D3D11RenderWindowImageSource::resize(unsigned width, unsigned height) - { - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - rsys->validateDevice(); - - _destroySizeDependedD3DResources(); - - mWidth = width; - mHeight = height; - - _createSizeDependedD3DResources(); - - // Notify viewports of resize - _updateViewportsDimensions(); - } - //--------------------------------------------------------------------- - void D3D11RenderWindowImageSource::getCustomAttribute( const String& name, void* pData ) - { - if( name == "ImageBrush" ) - { - IUnknown** pUnk = (IUnknown **)pData; - *pUnk = reinterpret_cast(mBrush); - return; - } - - D3D11RenderWindowBase::getCustomAttribute(name, pData); - } -#endif // !__OGRE_WINRT_PHONE_80 -#pragma endregion -} diff --git a/RenderSystems/Direct3D11/src/OgreD3D11StereoDriverAMD.cpp b/RenderSystems/Direct3D11/src/OgreD3D11StereoDriverAMD.cpp deleted file mode 100644 index e7200d03e54..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11StereoDriverAMD.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreD3D11StereoDriverAMD.h" - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - -#include "OgreD3D11RenderWindow.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - D3D11StereoDriverAMD::D3D11StereoDriverAMD() - { - } - //--------------------------------------------------------------------- - D3D11StereoDriverAMD::~D3D11StereoDriverAMD() - { - } - //--------------------------------------------------------------------- - bool D3D11StereoDriverAMD::addRenderWindow(D3D11RenderWindowBase* renderWindow) - { - return false; - } - //--------------------------------------------------------------------- - bool D3D11StereoDriverAMD::removeRenderWindow(const String& renderWindowName) - { - return false; - } - //--------------------------------------------------------------------- - bool D3D11StereoDriverAMD::isStereoEnabled(const String& renderWindowName) - { - return false; - } - //--------------------------------------------------------------------- - bool D3D11StereoDriverAMD::setDrawBuffer(ColourBufferType colourBuffer) - { - return false; - } - //--------------------------------------------------------------------- -} -#endif diff --git a/RenderSystems/Direct3D11/src/OgreD3D11StereoDriverBridge.cpp b/RenderSystems/Direct3D11/src/OgreD3D11StereoDriverBridge.cpp deleted file mode 100644 index 2f22fb02142..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11StereoDriverBridge.cpp +++ /dev/null @@ -1,129 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreD3D11StereoDriverBridge.h" - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - -#include "OgreD3D11StereoDriverAMD.h" -#include "OgreD3D11StereoDriverNVIDIA.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - D3D11StereoDriverBridge::D3D11StereoDriverBridge(StereoModeType stereoMode) - { - mPimpl = NULL; - mIsNvapiInitialized = false; - mStereoMode = stereoMode; - - if (!mStereoMode) - return; - - NvAPI_Status nvStatus = NvAPI_Initialize(); - if (NVAPI_OK == nvStatus) - { - NvAPI_ShortString nvapiStatusMessage; - NvAPI_GetErrorMessage(nvStatus, nvapiStatusMessage); - mIsNvapiInitialized = true; - mPimpl = new D3D11StereoDriverNVIDIA(); - } - else - { - // Assume the AMD implementation, since the device must be created before verifying AMD QBS - mPimpl = new D3D11StereoDriverAMD(); - } - } - //--------------------------------------------------------------------- - D3D11StereoDriverBridge::~D3D11StereoDriverBridge() - { - if (NULL != mPimpl) - { - delete mPimpl; - mPimpl = NULL; - } - - if (mIsNvapiInitialized) - { - NvAPI_Status nvStatus = NvAPI_Unload(); - NvAPI_ShortString nvapiStatusMessage; - NvAPI_GetErrorMessage(nvStatus, nvapiStatusMessage); - } - } - //--------------------------------------------------------------------- - template<> D3D11StereoDriverBridge* Ogre::Singleton::msSingleton = 0; - D3D11StereoDriverBridge& D3D11StereoDriverBridge::getSingleton(void) - { - assert(msSingleton); - return (*msSingleton); - } - //--------------------------------------------------------------------- - D3D11StereoDriverBridge* D3D11StereoDriverBridge::getSingletonPtr(void) - { - return msSingleton; - } - //--------------------------------------------------------------------- - StereoModeType D3D11StereoDriverBridge::getStereoMode() const - { - return mStereoMode; - } - //--------------------------------------------------------------------- - bool D3D11StereoDriverBridge::addRenderWindow(D3D11RenderWindowBase* renderWindow) const - { - if (NULL != mPimpl) - return mPimpl->addRenderWindow(renderWindow); - - return false; - } - //--------------------------------------------------------------------- - bool D3D11StereoDriverBridge::removeRenderWindow(const String& name) const - { - if (NULL != mPimpl) - return mPimpl->removeRenderWindow(name); - - return false; - } - //--------------------------------------------------------------------- - bool D3D11StereoDriverBridge::isStereoEnabled(const String& renderWindowName) const - { - if (NULL != mPimpl) - return mPimpl->isStereoEnabled(renderWindowName); - - return false; - } - //--------------------------------------------------------------------- - bool D3D11StereoDriverBridge::setDrawBuffer(ColourBufferType colourBuffer) const - { - if (NULL != mPimpl) - return mPimpl->setDrawBuffer(colourBuffer); - - return false; - } - //--------------------------------------------------------------------- -} -#endif diff --git a/RenderSystems/Direct3D11/src/OgreD3D11StereoDriverNVIDIA.cpp b/RenderSystems/Direct3D11/src/OgreD3D11StereoDriverNVIDIA.cpp deleted file mode 100644 index c8d7d962c72..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11StereoDriverNVIDIA.cpp +++ /dev/null @@ -1,202 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreD3D11StereoDriverNVIDIA.h" - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - -#include "OgreD3D11RenderWindow.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - D3D11StereoDriverNVIDIA::D3D11StereoDriverNVIDIA() - { - mStereoMap.clear(); - - // Assume NVAPI is already initialized by caller and enable direct mode - NvAPI_Status nvStatus = NvAPI_Stereo_SetDriverMode(NVAPI_STEREO_DRIVER_MODE_DIRECT); - if (!logErrorMessage(nvStatus)) - return; - - // If stereo is not enabled, enable it - nvStatus = NvAPI_Stereo_IsEnabled(&mStereoEnabled); - if (!logErrorMessage(nvStatus)) - { - return; - } - else if (!mStereoEnabled) - { - nvStatus = NvAPI_Stereo_Enable(); - if (!logErrorMessage(nvStatus)) - return; - } - - // Verify stereo is now enabled - if (!mStereoEnabled) - { - nvStatus = NvAPI_Stereo_IsEnabled(&mStereoEnabled); - if (!logErrorMessage(nvStatus) || !mStereoEnabled) - return; - } - - logErrorMessage(nvStatus); - } - //--------------------------------------------------------------------- - D3D11StereoDriverNVIDIA::~D3D11StereoDriverNVIDIA() - { - StereoHandleMap::iterator i = mStereoMap.begin(); - while (i != mStereoMap.end()) - { - removeRenderWindow((*i).first); - i = mStereoMap.begin(); - } - } - //--------------------------------------------------------------------- - bool D3D11StereoDriverNVIDIA::addRenderWindow(D3D11RenderWindowBase* renderWindow) - { - // Initialize the stereo handle - OgreStereoHandle stereoHandle; - stereoHandle.renderWindow = renderWindow; - stereoHandle.nvapiStereoHandle = 0; - stereoHandle.isStereoOn = 0; - - // Create a new NVAPI stereo handle and verify it is activated - void* d3dDevice = NULL; - renderWindow->getCustomAttribute("D3DDEVICE", &d3dDevice); - - NvAPI_Status nvStatus = NvAPI_Stereo_CreateHandleFromIUnknown(static_cast(d3dDevice), &stereoHandle.nvapiStereoHandle); - if (logErrorMessage(nvStatus)) - nvStatus = NvAPI_Stereo_IsActivated(stereoHandle.nvapiStereoHandle, &stereoHandle.isStereoOn); - - logErrorMessage(nvStatus); - - // Add the stereo handle to the existing map - mStereoMap[stereoHandle.renderWindow->getName()] = stereoHandle; - - return true; - } - //--------------------------------------------------------------------- - bool D3D11StereoDriverNVIDIA::removeRenderWindow(const String& renderWindowName) - { - OgreStereoHandle stereoHandle = mStereoMap[renderWindowName]; - NvAPI_Status nvStatus = NvAPI_Stereo_DestroyHandle(stereoHandle.nvapiStereoHandle); - logErrorMessage(nvStatus); - mStereoMap.erase(renderWindowName); - - return true; - } - //--------------------------------------------------------------------- - bool D3D11StereoDriverNVIDIA::isStereoEnabled(const String& renderWindowName) - { - // Verify stereo is supported - if (!mStereoEnabled) - return false; - - // If stereo was lost for the handle, re-create the handle - OgreStereoHandle stereoHandle; - stereoHandle = mStereoMap[renderWindowName]; - NvU8 isStereoOn; - NvAPI_Status nvStatus = NvAPI_Stereo_IsActivated(stereoHandle.nvapiStereoHandle, &isStereoOn); - if (NVAPI_OK != nvStatus || !isStereoOn) - { - // If stereo was lost for the window, log the error message - if (stereoHandle.isStereoOn != isStereoOn) - { - stereoHandle.isStereoOn = isStereoOn; - logErrorMessage(nvStatus); - } - - void* d3dDevice = NULL; - stereoHandle.renderWindow->getCustomAttribute("D3DDEVICE", &d3dDevice); - - nvStatus = NvAPI_Stereo_DestroyHandle(stereoHandle.nvapiStereoHandle); - nvStatus = NvAPI_Stereo_CreateHandleFromIUnknown(static_cast(d3dDevice), &stereoHandle.nvapiStereoHandle); - if (NVAPI_OK != nvStatus) - return false; - } - - // Verify that stereo is activated for the handle - nvStatus = NvAPI_Stereo_IsActivated(stereoHandle.nvapiStereoHandle, &isStereoOn); - - // If stereo was enabled for the window, log the error message - if (stereoHandle.isStereoOn != isStereoOn) - { - stereoHandle.isStereoOn = isStereoOn; - logErrorMessage(nvStatus); - } - - return true; - } - //--------------------------------------------------------------------- - bool D3D11StereoDriverNVIDIA::setDrawBuffer(ColourBufferType colourBuffer) - { - NvAPI_Status nvStatus; - - // Set the active eye for all render windows that have stereo enabled - for (StereoHandleMap::iterator i = mStereoMap.begin(); i != mStereoMap.end(); ++i) - { - if ((*i).second.renderWindow->isStereoEnabled()) - { - switch (colourBuffer) - { - case CBT_BACK: - nvStatus = NvAPI_Stereo_SetActiveEye((*i).second.nvapiStereoHandle, NVAPI_STEREO_EYE_MONO); - break; - case CBT_BACK_LEFT: - nvStatus = NvAPI_Stereo_SetActiveEye((*i).second.nvapiStereoHandle, NVAPI_STEREO_EYE_LEFT); - break; - case CBT_BACK_RIGHT: - nvStatus = NvAPI_Stereo_SetActiveEye((*i).second.nvapiStereoHandle, NVAPI_STEREO_EYE_RIGHT); - break; - default: - return false; - } - - logErrorMessage(nvStatus); - } - } - - return true; - } - //--------------------------------------------------------------------- - bool D3D11StereoDriverNVIDIA::logErrorMessage(NvAPI_Status nvStatus) - { - if (NVAPI_OK != nvStatus) - { - NvAPI_ShortString nvapiStatusMessage; - NvAPI_GetErrorMessage(nvStatus, nvapiStatusMessage); - return false; - } - - return true; - } - //--------------------------------------------------------------------- -} - -#endif diff --git a/RenderSystems/Direct3D11/src/OgreD3D11Texture.cpp b/RenderSystems/Direct3D11/src/OgreD3D11Texture.cpp deleted file mode 100644 index 422b6873ace..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11Texture.cpp +++ /dev/null @@ -1,628 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11Texture.h" -#include "OgreD3D11HardwarePixelBuffer.h" -#include "OgreD3D11Mappings.h" -#include "OgreD3D11Device.h" -#include "OgreD3D11RenderSystem.h" -#include "OgreD3D11DepthBuffer.h" -#include "OgreRoot.h" -#include "OgreLogManager.h" -#include "OgreException.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - D3D11Texture::D3D11Texture(ResourceManager* creator, const String& name, - ResourceHandle handle, const String& group, bool isManual, - ManualResourceLoader* loader, D3D11Device & device) - :Texture(creator, name, handle, group, isManual, loader), - mDevice(device), - mAutoMipMapGeneration(false) - { - mFSAAType.Count = 1; - mFSAAType.Quality = 0; - } - //--------------------------------------------------------------------- - D3D11Texture::~D3D11Texture() - { - unload(); - } - //--------------------------------------------------------------------- - void D3D11Texture::notifyDeviceLost(D3D11Device* device) - { - unloadImpl(); - } - //--------------------------------------------------------------------- - void D3D11Texture::notifyDeviceRestored(D3D11Device* device) - { - if(isManuallyLoaded()) - { - preLoadImpl(); - createInternalResourcesImpl(); - if (mLoader != NULL) - mLoader->loadResource(this); - postLoadImpl(); - } - else - { - preLoadImpl(); - loadImpl(); - postLoadImpl(); - } - } - //--------------------------------------------------------------------- - void D3D11Texture::copyToTexture(TexturePtr& target) - { - // check if this & target are the same format and type - // blitting from or to cube textures is not supported yet - if (target->getUsage() != this->getUsage() || - target->getTextureType() != this->getTextureType()) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "Src. and dest. textures must be of same type and must have the same usage !!!", - "D3D11Texture::copyToTexture" ); - } - - - D3D11Texture *other; - // get the target - other = static_cast< D3D11Texture * >( target.get() ); - - mDevice.GetImmediateContext()->CopyResource(other->getTextureResource(), mpTex.Get()); - if (mDevice.isError()) - { - String errorDescription = mDevice.getErrorDescription(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "D3D11 device cannot copy resource\nError Description:" + errorDescription, - "D3D11Texture::copyToTexture"); - } - - } - //--------------------------------------------------------------------- - void D3D11Texture::freeInternalResourcesImpl() - { - mpTex.Reset(); - mpShaderResourceView.Reset(); - mpUnorderedAccessView.Reset(); - mp1DTex.Reset(); - mp2DTex.Reset(); - mp3DTex.Reset(); - } - - //--------------------------------------------------------------------- - void D3D11Texture::createInternalResourcesImpl(void) - { - // If mSrcWidth and mSrcHeight are zero, the requested extents have probably been set - // through setWidth and setHeight, which set mWidth and mHeight. Take those values. - if(mSrcWidth == 0 || mSrcHeight == 0) { - mSrcWidth = mWidth; - mSrcHeight = mHeight; - } - - mFormat = D3D11Mappings::_getClosestSupportedPF(mFormat); - - // Choose closest supported D3D format - mD3DFormat = D3D11Mappings::_getGammaFormat(D3D11Mappings::_getPF(mFormat), isHardwareGammaEnabled()); - - mFSAAType.Count = 1; - mFSAAType.Quality = 0; - if((mUsage & TU_RENDERTARGET) != 0 && (mUsage & TU_DYNAMIC) == 0) - { - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - // http://msdn.microsoft.com/en-us/library/windows/desktop/ff476150%28v=vs.85%29.aspx#ID3D11Device_CreateTexture2D - // 10Level9, When using D3D11_BIND_SHADER_RESOURCE, SampleDesc.Count must be 1. - if(rsys->_getFeatureLevel() >= D3D_FEATURE_LEVEL_10_0 || (mUsage & TU_NOT_SRV)) - rsys->determineFSAASettings(mFSAA, mFSAAHint, mD3DFormat, &mFSAAType); - } - - // load based on tex.type - switch (this->getTextureType()) - { - case TEX_TYPE_1D: - { - D3D11RenderSystem* rs = (D3D11RenderSystem*)Root::getSingleton().getRenderSystem(); - if(rs->_getFeatureLevel() >= D3D_FEATURE_LEVEL_10_0) - { - this->_create1DTex(); - break; // For Feature levels that do not support 1D textures, revert to creating a 2D texture. - } - } - case TEX_TYPE_2D: - case TEX_TYPE_CUBE_MAP: - case TEX_TYPE_2D_ARRAY: - this->_create2DTex(); - break; - case TEX_TYPE_3D: - this->_create3DTex(); - break; - default: - this->unloadImpl(); - OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, "Unknown texture type", "D3D11Texture::createInternalResources" ); - } - } - //--------------------------------------------------------------------- - void D3D11Texture::_create1DTex() - { - // we must have those defined here - assert(mSrcWidth > 0 || mSrcHeight > 0); - - // determine total number of mipmaps including main one (d3d11 convention) - UINT numMips = (mNumMipmaps == MIP_UNLIMITED || (1U << mNumMipmaps) > mSrcWidth) ? 0 : mNumMipmaps + 1; - - D3D11_TEXTURE1D_DESC desc; - desc.Width = static_cast(mSrcWidth); - desc.MipLevels = numMips; - desc.ArraySize = 1; - desc.Format = mD3DFormat; - desc.Usage = D3D11Mappings::_getUsage(_getTextureUsage()); - desc.BindFlags = D3D11Mappings::_getTextureBindFlags(mD3DFormat, _getTextureUsage()); - desc.CPUAccessFlags = D3D11Mappings::_getAccessFlags(_getTextureUsage()); - desc.MiscFlags = D3D11Mappings::_getTextureMiscFlags(desc.BindFlags, getTextureType(), _getTextureUsage()); - - // create the texture - HRESULT hr = mDevice->CreateTexture1D( - &desc, - NULL, - mp1DTex.ReleaseAndGetAddressOf()); // data pointer - // check result and except if failed - if (FAILED(hr) || mDevice.isError()) - { - this->unloadImpl(); - String errorDescription = mDevice.getErrorDescription(hr); - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Error creating texture\nError Description:" + errorDescription, - "D3D11Texture::_create1DTex" ); - } - - _queryInterface(mp1DTex, &mpTex); - _create1DResourceView(); - } - //--------------------------------------------------------------------- - void D3D11Texture::_create1DResourceView() - { - // set final tex. attributes from tex. description - // they may differ from the source image !!! - HRESULT hr; - D3D11_TEXTURE1D_DESC desc; - - // set final tex. attributes from tex. description - // they may differ from the source image !!! - mp1DTex->GetDesc(&desc); - mNumMipmaps = desc.MipLevels - 1; - - ZeroMemory( &mSRVDesc, sizeof(mSRVDesc) ); - mSRVDesc.Format = desc.Format; - mSRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D; - mSRVDesc.Texture1D.MipLevels = desc.MipLevels; - OGRE_CHECK_DX_ERROR( - (desc.BindFlags & D3D11_BIND_SHADER_RESOURCE) - ? mDevice->CreateShaderResourceView(mp1DTex.Get(), &mSRVDesc, - mpShaderResourceView.ReleaseAndGetAddressOf()) - : S_FALSE); - - this->_setFinalAttributes(desc.Width, 1, 1, D3D11Mappings::_getPF(desc.Format), desc.MiscFlags); - } - //--------------------------------------------------------------------- - inline bool IsPowerOfTwo(unsigned int n) { return ((n&(n-1))==0); } - //--------------------------------------------------------------------- - void D3D11Texture::_create2DTex() - { - // we must have those defined here - assert(mSrcWidth > 0 || mSrcHeight > 0); - - // determine total number of mipmaps including main one (d3d11 convention) - UINT numMips = (mNumMipmaps == MIP_UNLIMITED || (1U << mNumMipmaps) > std::max(mSrcWidth, mSrcHeight)) ? 0 : mNumMipmaps + 1; - if(D3D11Mappings::_isBinaryCompressedFormat(mD3DFormat) && numMips > 1) - numMips = std::max(1U, numMips - 2); - - D3D11_TEXTURE2D_DESC desc; - desc.Width = static_cast(mSrcWidth); - desc.Height = static_cast(mSrcHeight); - desc.MipLevels = numMips; - desc.ArraySize = mDepth == 0 ? 1 : mDepth; - desc.Format = mD3DFormat; - desc.SampleDesc = mFSAAType; - desc.Usage = D3D11Mappings::_getUsage(_getTextureUsage()); - desc.BindFlags = D3D11Mappings::_getTextureBindFlags(mD3DFormat, _getTextureUsage()); - desc.CPUAccessFlags = D3D11Mappings::_getAccessFlags(_getTextureUsage()); - desc.MiscFlags = D3D11Mappings::_getTextureMiscFlags(desc.BindFlags, getTextureType(), _getTextureUsage()); - - if (PixelUtil::isDepth(mFormat)) - { - desc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_DEPTH_STENCIL; - desc.Usage = D3D11_USAGE_DEFAULT; - desc.CPUAccessFlags = 0; - desc.MiscFlags = 0; - } - - if (this->getTextureType() == TEX_TYPE_CUBE_MAP) - { - desc.ArraySize = 6; - } - - D3D11RenderSystem* rs = (D3D11RenderSystem*)Root::getSingleton().getRenderSystem(); - if(rs->_getFeatureLevel() < D3D_FEATURE_LEVEL_10_0) - { - // http://msdn.microsoft.com/en-us/library/windows/desktop/ff476150%28v=vs.85%29.aspx#ID3D11Device_CreateTexture2D - // ...If MipCount > 1, Dimensions must be integral power of two... - if(!IsPowerOfTwo(desc.Width) || !IsPowerOfTwo(desc.Height)) - { - desc.MipLevels = 1; - } - -#if 0 - // there seems to be a Microsoft bug that crash if you do GenerateMips in a level less then D3D_FEATURE_LEVEL_10_0 - // is this still true or addressed by the code above? - desc.MipLevels = 1; -#endif - } - - // create the texture - HRESULT hr = mDevice->CreateTexture2D( - &desc, - NULL,// data pointer - mp2DTex.ReleaseAndGetAddressOf()); - // check result and except if failed - if (FAILED(hr) || mDevice.isError()) - { - this->unloadImpl(); - String errorDescription = mDevice.getErrorDescription(hr); - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Error creating texture\nError Description:" + errorDescription, - "D3D11Texture::_create2DTex" ); - } - - //set the base texture we'll use in the render system - _queryInterface(mp2DTex, &mpTex); - - _create2DResourceView(); - } - //---------------------------------------------------------------------------- - void D3D11Texture::_create2DResourceView() - { - // set final tex. attributes from tex. description - // they may differ from the source image !!! - HRESULT hr; - D3D11_TEXTURE2D_DESC desc; - mp2DTex->GetDesc(&desc); - mNumMipmaps = desc.MipLevels - 1; - - ZeroMemory( &mSRVDesc, sizeof(mSRVDesc) ); - mSRVDesc.Format = desc.Format == DXGI_FORMAT_R32_TYPELESS ? DXGI_FORMAT_R32_FLOAT : desc.Format; - - switch(this->getTextureType()) - { - case TEX_TYPE_CUBE_MAP: - mSRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE; - mSRVDesc.TextureCube.MipLevels = desc.MipLevels; - mSRVDesc.TextureCube.MostDetailedMip = 0; - break; - - case TEX_TYPE_2D_ARRAY: - if (mFSAAType.Count > 1) - { - mSRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY; - mSRVDesc.Texture2DMSArray.FirstArraySlice = 0; - mSRVDesc.Texture2DMSArray.ArraySize = desc.ArraySize; - } - else - { - mSRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY; - mSRVDesc.Texture2DArray.MostDetailedMip = 0; - mSRVDesc.Texture2DArray.MipLevels = desc.MipLevels; - mSRVDesc.Texture2DArray.FirstArraySlice = 0; - mSRVDesc.Texture2DArray.ArraySize = desc.ArraySize; - } - break; - - case TEX_TYPE_2D: - case TEX_TYPE_1D: // For Feature levels that do not support 1D textures, revert to creating a 2D texture. - if (mFSAAType.Count > 1) - { - mSRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DMS; - } - else - { - mSRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; - mSRVDesc.Texture2D.MostDetailedMip = 0; - mSRVDesc.Texture2D.MipLevels = desc.MipLevels; - } - break; - } - - OGRE_CHECK_DX_ERROR( - (desc.BindFlags & D3D11_BIND_SHADER_RESOURCE) - ? mDevice->CreateShaderResourceView(mp2DTex.Get(), &mSRVDesc, - mpShaderResourceView.ReleaseAndGetAddressOf()) - : S_FALSE); - - this->_setFinalAttributes(desc.Width, desc.Height, desc.ArraySize / getNumFaces(), D3D11Mappings::_getPF(desc.Format), desc.MiscFlags); - } - - void D3D11Texture::createShaderAccessPoint(uint bindPoint, TextureAccess access, int mipmapLevel, - int textureArrayIndex, PixelFormat format) - { - if(mpUnorderedAccessView) - return; - D3D11_UNORDERED_ACCESS_VIEW_DESC descUAV; - descUAV.Format = mD3DFormat; - descUAV.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D; - descUAV.Texture2D.MipSlice = static_cast( mipmapLevel ); - - mDevice->CreateUnorderedAccessView( mp2DTex.Get(), &descUAV, mpUnorderedAccessView.ReleaseAndGetAddressOf() ); - } - //--------------------------------------------------------------------- - void D3D11Texture::_create3DTex() - { - // we must have those defined here - assert(mWidth > 0 && mHeight > 0 && mDepth>0); - - // determine total number of mipmaps including main one (d3d11 convention) - UINT numMips = (mNumMipmaps == MIP_UNLIMITED || (1U << mNumMipmaps) > std::max(std::max(mSrcWidth, mSrcHeight), mDepth)) ? 0 : mNumMipmaps + 1; - - D3D11_TEXTURE3D_DESC desc; - desc.Width = static_cast(mSrcWidth); - desc.Height = static_cast(mSrcHeight); - desc.Depth = static_cast(mDepth); - desc.MipLevels = numMips; - desc.Format = mD3DFormat; - desc.Usage = D3D11Mappings::_getUsage(_getTextureUsage()); - desc.BindFlags = D3D11Mappings::_getTextureBindFlags(mD3DFormat, _getTextureUsage()); - - D3D11RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - if (rsys->_getFeatureLevel() < D3D_FEATURE_LEVEL_10_0) - desc.BindFlags &= ~D3D11_BIND_RENDER_TARGET; - - desc.CPUAccessFlags = D3D11Mappings::_getAccessFlags(_getTextureUsage()); - desc.MiscFlags = 0; - - // create the texture - HRESULT hr = mDevice->CreateTexture3D( - &desc, - NULL, - mp3DTex.ReleaseAndGetAddressOf()); // data pointer - // check result and except if failed - if (FAILED(hr) || mDevice.isError()) - { - this->unloadImpl(); - String errorDescription = mDevice.getErrorDescription(hr); - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Error creating texture\nError Description:" + errorDescription, - "D3D11Texture::_create3DTex" ); - } - - _queryInterface(mp3DTex, &mpTex); - _create3DResourceView(); - } - //------------------------------------------------------------------------------- - void D3D11Texture::_create3DResourceView() - { - // set final tex. attributes from tex. description - // they may differ from the source image !!! - HRESULT hr; - D3D11_TEXTURE3D_DESC desc; - mp3DTex->GetDesc(&desc); - mNumMipmaps = desc.MipLevels - 1; - - ZeroMemory( &mSRVDesc, sizeof(mSRVDesc) ); - mSRVDesc.Format = desc.Format; - mSRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D; - mSRVDesc.Texture3D.MostDetailedMip = 0; - mSRVDesc.Texture3D.MipLevels = desc.MipLevels; - OGRE_CHECK_DX_ERROR( - (desc.BindFlags & D3D11_BIND_SHADER_RESOURCE) - ? mDevice->CreateShaderResourceView(mp3DTex.Get(), &mSRVDesc, - mpShaderResourceView.ReleaseAndGetAddressOf()) - : S_FALSE); - - this->_setFinalAttributes(desc.Width, desc.Height, desc.Depth, D3D11Mappings::_getPF(desc.Format), desc.MiscFlags); - } - //------------------------------------------------------------------------------- - void D3D11Texture::_setFinalAttributes(unsigned long width, unsigned long height, - unsigned long depth, PixelFormat format, UINT miscflags) - { - // set target texture attributes - mHeight = height; - mWidth = width; - mDepth = depth; - mFormat = format; - mAutoMipMapGeneration = miscflags & D3D11_RESOURCE_MISC_GENERATE_MIPS; - - // Update size (the final size, including temp space because in consumed memory) - // this is needed in Resource class - mSize = calculateSize(); - - // say to the world what we are doing - if (mWidth != mSrcWidth || - mHeight != mSrcHeight) - { - LogManager::getSingleton().logMessage("D3D11: ***** Dimensions altered by the render system"); - LogManager::getSingleton().logMessage("D3D11: ***** Source image dimensions : " + StringConverter::toString(mSrcWidth) + "x" + StringConverter::toString(mSrcHeight)); - LogManager::getSingleton().logMessage("D3D11: ***** Texture dimensions : " + StringConverter::toString(mWidth) + "x" + StringConverter::toString(mHeight)); - } - - // Create list of subsurfaces for getBuffer() - _createSurfaceList(); - } - //--------------------------------------------------------------------- - void D3D11Texture::_createSurfaceList(void) - { - // Create new list of surfaces - mSurfaceList.clear(); - size_t depth = mDepth; - - for(size_t face=0; face 1) width /= 2; - if(height > 1) height /= 2; - if(depth > 1 && getTextureType() != TEX_TYPE_2D_ARRAY) depth /= 2; - } - } - } - //--------------------------------------------------------------------- - // D3D11RenderTexture - //--------------------------------------------------------------------- - void D3D11RenderTexture::rebind( D3D11HardwarePixelBuffer *buffer ) - { - mBuffer = buffer; - mWidth = (unsigned int) mBuffer->getWidth(); - mHeight = (unsigned int) mBuffer->getHeight(); - - ID3D11Resource * pBackBuffer = buffer->getParentTexture()->getTextureResource(); - - D3D11_RENDER_TARGET_VIEW_DESC RTVDesc; - ZeroMemory( &RTVDesc, sizeof(RTVDesc) ); - - RTVDesc.Format = buffer->getParentTexture()->getShaderResourceViewDesc().Format; - switch(buffer->getParentTexture()->getShaderResourceViewDesc().ViewDimension) - { - case D3D11_SRV_DIMENSION_BUFFER: - RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_BUFFER; - break; - case D3D11_SRV_DIMENSION_TEXTURE1D: - RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE1D; - break; - case D3D11_SRV_DIMENSION_TEXTURE1DARRAY: - RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE1DARRAY; - break; - case D3D11_SRV_DIMENSION_TEXTURECUBE: - RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY; - RTVDesc.Texture2DArray.FirstArraySlice = buffer->getFace(); - RTVDesc.Texture2DArray.ArraySize = 1; - break; - case D3D11_SRV_DIMENSION_TEXTURE2D: - RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; - break; - case D3D11_SRV_DIMENSION_TEXTURE2DARRAY: - RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY; - RTVDesc.Texture2DArray.FirstArraySlice = mZOffset; - RTVDesc.Texture2DArray.ArraySize = 1; - break; - case D3D11_SRV_DIMENSION_TEXTURE2DMS: - RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMS; - break; - case D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY: - RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY; - RTVDesc.Texture2DArray.FirstArraySlice = mZOffset; - RTVDesc.Texture2DArray.ArraySize = 1; - break; - case D3D11_SRV_DIMENSION_TEXTURE3D: - RTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE3D; - RTVDesc.Texture3D.FirstWSlice = mZOffset; - RTVDesc.Texture3D.WSize = 1; - break; - default: - assert(false); - } - - if (!PixelUtil::isDepth(mBuffer->getFormat())) - { - OGRE_CHECK_DX_ERROR(mDevice->CreateRenderTargetView(pBackBuffer, &RTVDesc, - mRenderTargetView.ReleaseAndGetAddressOf())); - return; - } - - // also create DSV for depth textures - D3D11_TEXTURE2D_DESC BBDesc; - getSurface()->GetDesc(&BBDesc); - - // Create the depth stencil view - D3D11_DEPTH_STENCIL_VIEW_DESC descDSV = {}; - descDSV.Format = DXGI_FORMAT_D32_FLOAT; - descDSV.ViewDimension = (BBDesc.SampleDesc.Count > 1) ? D3D11_DSV_DIMENSION_TEXTURE2DMS : D3D11_DSV_DIMENSION_TEXTURE2D; - descDSV.Flags = 0 /* D3D11_DSV_READ_ONLY_DEPTH | D3D11_DSV_READ_ONLY_STENCIL */; // TODO: Allows bind depth buffer as depth view AND texture simultaneously. - descDSV.Texture2D.MipSlice = 0; - - ID3D11DepthStencilView *depthStencilView; - OGRE_CHECK_DX_ERROR(mDevice->CreateDepthStencilView(pBackBuffer, &descDSV, &depthStencilView )); - - D3D11RenderSystem* rs = (D3D11RenderSystem*)Root::getSingleton().getRenderSystem(); - mDepthBuffer = - new D3D11DepthBuffer(DepthBuffer::POOL_NO_DEPTH, rs, depthStencilView, mWidth, mHeight, - BBDesc.SampleDesc.Count, BBDesc.SampleDesc.Quality, false); - mDepthBuffer->_notifyRenderTargetAttached(this); - } - - uint D3D11RenderTexture::getNumberOfViews() const { return PixelUtil::isDepth(mBuffer->getFormat()) ? 0 : 1; } - - ID3D11Texture2D* D3D11RenderTexture::getSurface(uint index) const - { - return index == 0 ? static_cast(mBuffer)->getParentTexture()->GetTex2D() - : NULL; - } - - ID3D11RenderTargetView* D3D11RenderTexture::getRenderTargetView(uint index) const - { - return index == 0 ? mRenderTargetView.Get() : NULL; - } - - D3D11RenderTexture::D3D11RenderTexture( const String &name, D3D11HardwarePixelBuffer *buffer, uint32 zoffset, D3D11Device & device ) - : RenderTexture(buffer, zoffset) - , mDevice(device) - { - mName = name; - rebind(buffer); - } - //--------------------------------------------------------------------- - D3D11RenderTexture::~D3D11RenderTexture() - { - if (mDepthBuffer && PixelUtil::isDepth (mBuffer->getFormat ())) - delete mDepthBuffer; - } - - //--------------------------------------------------------------------- - void D3D11RenderTexture::notifyDeviceLost(D3D11Device* device) - { - } - //--------------------------------------------------------------------- - void D3D11RenderTexture::notifyDeviceRestored(D3D11Device* device) - { - rebind(static_cast(mBuffer)); - } -} diff --git a/RenderSystems/Direct3D11/src/OgreD3D11TextureManager.cpp b/RenderSystems/Direct3D11/src/OgreD3D11TextureManager.cpp deleted file mode 100644 index d60970e041e..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11TextureManager.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11TextureManager.h" -#include "OgreD3D11Texture.h" -#include "OgreRoot.h" -#include "OgreLogManager.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreD3D11RenderSystem.h" -#include "OgreD3D11Device.h" - -namespace Ogre -{ - ID3D11SamplerState* D3D11Sampler::getState() - { - if(!mDirty) - return mState.Get(); - - D3D11_SAMPLER_DESC desc; - - desc.Filter = D3D11Mappings::get(mMinFilter, mMagFilter, mMipFilter, mCompareEnabled); - desc.MaxAnisotropy = mMaxAniso; - desc.MipLODBias = mMipmapBias; - desc.MinLOD = 0; - desc.MaxLOD = mMipFilter == FO_NONE ? 0 : D3D11_FLOAT32_MAX; - - bool reversedZ = Root::getSingleton().getRenderSystem()->isReverseDepthBufferEnabled(); - auto cmpFunc = mCompareFunc; - if(reversedZ) - cmpFunc = D3D11RenderSystem::reverseCompareFunction(cmpFunc); - desc.ComparisonFunc = D3D11Mappings::get(cmpFunc); - - desc.AddressU = D3D11Mappings::get(mAddressMode.u); - desc.AddressV = D3D11Mappings::get(mAddressMode.v); - desc.AddressW = D3D11Mappings::get(mAddressMode.w); - - if (mAddressMode.u == TAM_BORDER || mAddressMode.v == TAM_BORDER || mAddressMode.w == TAM_BORDER) - { - auto borderColour = - (reversedZ && mCompareEnabled) ? ColourValue::White - mBorderColour : mBorderColour; - memcpy(desc.BorderColor, borderColour.ptr(), sizeof(float)*4); - } - - OGRE_CHECK_DX_ERROR(mDevice->CreateSamplerState(&desc, mState.ReleaseAndGetAddressOf())); - - mDirty = false; - - return mState.Get(); - } - //--------------------------------------------------------------------- - D3D11TextureManager::D3D11TextureManager( D3D11Device & device ) : TextureManager(), mDevice (device) - { - if( mDevice.isNull()) - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Invalid Direct3DDevice passed", "D3D11TextureManager::D3D11TextureManager" ); - // register with group manager - ResourceGroupManager::getSingleton()._registerResourceManager(mResourceType, this); - } - //--------------------------------------------------------------------- - D3D11TextureManager::~D3D11TextureManager() - { - // unregister with group manager - ResourceGroupManager::getSingleton()._unregisterResourceManager(mResourceType); - - } - //--------------------------------------------------------------------- - Resource* D3D11TextureManager::createImpl(const String& name, - ResourceHandle handle, const String& group, bool isManual, - ManualResourceLoader* loader, const NameValuePairList* createParams) - { - return new D3D11Texture(this, name, handle, group, isManual, loader, mDevice); - } - SamplerPtr D3D11TextureManager::_createSamplerImpl() - { - return std::make_shared(mDevice); - } - //--------------------------------------------------------------------- - PixelFormat D3D11TextureManager::getNativeFormat(TextureType ttype, PixelFormat format, int usage) - { - // Basic filtering - DXGI_FORMAT d3dPF = D3D11Mappings::_getPF(D3D11Mappings::_getClosestSupportedPF(format)); - - return D3D11Mappings::_getPF(d3dPF); - } -} diff --git a/RenderSystems/Direct3D11/src/OgreD3D11VertexDeclaration.cpp b/RenderSystems/Direct3D11/src/OgreD3D11VertexDeclaration.cpp deleted file mode 100644 index a0b3f745459..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11VertexDeclaration.cpp +++ /dev/null @@ -1,183 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11VertexDeclaration.h" -#include "OgreD3D11Mappings.h" -#include "OgreD3D11HLSLProgram.h" -#include "OgreD3D11Device.h" - - -namespace Ogre { - - //----------------------------------------------------------------------- - D3D11VertexDeclaration::D3D11VertexDeclaration(D3D11Device & device) - : mlpD3DDevice(device) - { - } - //----------------------------------------------------------------------- - D3D11VertexDeclaration::~D3D11VertexDeclaration() - { - } - //----------------------------------------------------------------------- - void D3D11VertexDeclaration::notifyChanged() - { - clearCache(); - } - //----------------------------------------------------------------------- - void D3D11VertexDeclaration::notifyDeviceLost(D3D11Device* device) - { - clearCache(); - } - //----------------------------------------------------------------------- - void D3D11VertexDeclaration::notifyDeviceRestored(D3D11Device* device) - { - } - //----------------------------------------------------------------------- - void D3D11VertexDeclaration::clearCache() - { - mD3delems.clear(); - mShaderToILayoutMap.clear(); - } - //----------------------------------------------------------------------- - D3D11_INPUT_ELEMENT_DESC * D3D11VertexDeclaration::getD3DVertexDeclaration(D3D11HLSLProgram* boundVertexProgram, VertexBufferBinding* binding) - { - // Create D3D elements - if (mD3delems.find(boundVertexProgram) == mD3delems.end()) - { - std::vector D3delems; - - for (const D3D11_SIGNATURE_PARAMETER_DESC& inputDesc : boundVertexProgram->getInputParams()) - { - D3D11_INPUT_ELEMENT_DESC elem = {}; - for (const auto& e : mElementList) - { - LPCSTR semanticName = D3D11Mappings::get(e.getSemantic()); - if (strcmp(semanticName, inputDesc.SemanticName) == 0 && e.getIndex() == inputDesc.SemanticIndex) - { - elem.Format = D3D11Mappings::get(e.getType()); - elem.InputSlot = e.getSource(); - elem.AlignedByteOffset = static_cast(e.getOffset()); - break; - } - } - - if (elem.Format == DXGI_FORMAT_UNKNOWN) - { - OGRE_EXCEPT( - Exception::ERR_RENDERINGAPI_ERROR, - StringUtil::format("Vertex Shader %s consumes semantic %s%d but no such VertexElement provided", - boundVertexProgram->getName().c_str(), inputDesc.SemanticName, - inputDesc.SemanticIndex)); - } - - elem.SemanticName = inputDesc.SemanticName; - elem.SemanticIndex = inputDesc.SemanticIndex; - elem.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; - elem.InstanceDataStepRate = 0; - - auto foundIter = binding->getBindings().find(elem.InputSlot); - if ( foundIter != binding->getBindings().end() ) - { - HardwareVertexBufferSharedPtr bufAtSlot = foundIter->second; - if ( bufAtSlot->isInstanceData() ) - { - elem.InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA; - elem.InstanceDataStepRate = bufAtSlot->getInstanceDataStepRate(); - } - } - else - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Unable to found a bound vertex for a slot that is used in the vertex declaration." , - "D3D11VertexDeclaration::getD3DVertexDeclaration"); - - } - D3delems.push_back(elem); - } - - mD3delems[boundVertexProgram].swap(D3delems); - - } - - return mD3delems[boundVertexProgram].data(); - } - //----------------------------------------------------------------------- - ID3D11InputLayout* D3D11VertexDeclaration::getILayoutByShader(D3D11HLSLProgram* boundVertexProgram, VertexBufferBinding* binding) - { - ShaderToILayoutMapIterator foundIter = mShaderToILayoutMap.find(boundVertexProgram); - - ComPtr pVertexLayout; - - if (foundIter == mShaderToILayoutMap.end()) - { - // if not found - create - - DWORD dwShaderFlags = 0; - const MicroCode & vSBuf = boundVertexProgram->getMicroCode(); - - D3D11_INPUT_ELEMENT_DESC * pVertexDecl=getD3DVertexDeclaration(boundVertexProgram, binding); - - // bad bug tracing. see what will happen next. - //if (pVertexDecl->Format == DXGI_FORMAT_R16G16_SINT) - // pVertexDecl->Format = DXGI_FORMAT_R16G16_FLOAT; - HRESULT hr = mlpD3DDevice->CreateInputLayout( - pVertexDecl, - boundVertexProgram->getInputParams().size(), - &vSBuf[0], - vSBuf.size(), - pVertexLayout.ReleaseAndGetAddressOf() ); - - if (FAILED(hr)|| mlpD3DDevice.isError()) - { - String errorDescription = mlpD3DDevice.getErrorDescription(hr); - errorDescription += "\nBound shader name: " + boundVertexProgram->getName(); - - OGRE_EXCEPT_EX(Exception::ERR_RENDERINGAPI_ERROR, hr, - "Unable to set D3D11 vertex declaration" + errorDescription, - "D3D11VertexDeclaration::getILayoutByShader"); - } - - mShaderToILayoutMap[boundVertexProgram] = pVertexLayout; - - } - else - { - pVertexLayout = foundIter->second; - } - - return pVertexLayout.Get(); // lifetime is determined by map - } - //----------------------------------------------------------------------- - void D3D11VertexDeclaration::bindToShader(D3D11HLSLProgram* boundVertexProgram, VertexBufferBinding* binding) - { - // Set the input layout - ID3D11InputLayout* pVertexLayout = getILayoutByShader(boundVertexProgram, binding); - mlpD3DDevice.GetImmediateContext()->IASetInputLayout( pVertexLayout); - } -} - - diff --git a/RenderSystems/Direct3D11/src/OgreD3D11VideoMode.cpp b/RenderSystems/Direct3D11/src/OgreD3D11VideoMode.cpp deleted file mode 100644 index 265b0bbc434..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11VideoMode.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11VideoMode.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - String D3D11VideoMode::getDescription() const - { - unsigned int colourDepth = 16; - if( mModeDesc.Format == DXGI_FORMAT_R8G8B8A8_UNORM || - mModeDesc.Format == DXGI_FORMAT_R32G32B32A32_TYPELESS || - mModeDesc.Format == DXGI_FORMAT_R32G32B32A32_FLOAT || - mModeDesc.Format == DXGI_FORMAT_R32G32B32A32_UINT || - mModeDesc.Format == DXGI_FORMAT_R32G32B32A32_SINT || - mModeDesc.Format == DXGI_FORMAT_R32G32B32_TYPELESS || - mModeDesc.Format == DXGI_FORMAT_R32G32B32_FLOAT || - mModeDesc.Format == DXGI_FORMAT_R32G32B32_UINT || - mModeDesc.Format == DXGI_FORMAT_R32G32B32_SINT - ) - colourDepth = 32; - - return StringUtil::format("%d x %d @ %d-bit colour", mModeDesc.Width, mModeDesc.Height, colourDepth); - } - //--------------------------------------------------------------------- - unsigned int D3D11VideoMode::getWidth() const - { - return mModeDesc.Width; - } - //--------------------------------------------------------------------- - unsigned int D3D11VideoMode::getHeight() const - { - return mModeDesc.Height; - } - //--------------------------------------------------------------------- - DXGI_FORMAT D3D11VideoMode::getFormat() const - { - return mModeDesc.Format; - } - //--------------------------------------------------------------------- - DXGI_RATIONAL D3D11VideoMode::getRefreshRate() const - { - return mModeDesc.RefreshRate; - } - //--------------------------------------------------------------------- - DXGI_OUTPUT_DESC D3D11VideoMode::getDisplayMode() const - { - return mDisplayMode; - } - //--------------------------------------------------------------------- - DXGI_MODE_DESC D3D11VideoMode::getModeDesc() const - { - return mModeDesc; - } - //--------------------------------------------------------------------- - void D3D11VideoMode::increaseRefreshRate( DXGI_RATIONAL rr ) - { - mModeDesc.RefreshRate = rr; - } - //--------------------------------------------------------------------- - D3D11VideoMode::D3D11VideoMode( DXGI_OUTPUT_DESC d3ddm,DXGI_MODE_DESC ModeDesc ) - { - modeNumber = ++modeCount; mDisplayMode = d3ddm;mModeDesc=ModeDesc; - } - //--------------------------------------------------------------------- - D3D11VideoMode::D3D11VideoMode( const D3D11VideoMode &ob ) - { - modeNumber = ++modeCount; mDisplayMode = ob.mDisplayMode;mModeDesc=ob.mModeDesc; - } - //--------------------------------------------------------------------- - D3D11VideoMode::D3D11VideoMode() - { - modeNumber = ++modeCount; ZeroMemory( &mDisplayMode, sizeof(DXGI_OUTPUT_DESC) );ZeroMemory( &mModeDesc, sizeof(DXGI_MODE_DESC) ); - } - //--------------------------------------------------------------------- - D3D11VideoMode::~D3D11VideoMode() - { - modeCount--; - } - //--------------------------------------------------------------------- -} diff --git a/RenderSystems/Direct3D11/src/OgreD3D11VideoModeList.cpp b/RenderSystems/Direct3D11/src/OgreD3D11VideoModeList.cpp deleted file mode 100644 index c85549a24b3..00000000000 --- a/RenderSystems/Direct3D11/src/OgreD3D11VideoModeList.cpp +++ /dev/null @@ -1,156 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D11VideoModeList.h" -#include "OgreException.h" -#include "OgreD3D11Driver.h" -#include "OgreD3D11VideoMode.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - D3D11VideoModeList::D3D11VideoModeList(IDXGIAdapterN* pAdapter) - { - if( NULL == pAdapter) - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "pAdapter parameter is NULL", "D3D11VideoModeList::D3D11VideoModeList" ); - - for( int iOutput = 0; ; ++iOutput ) - { - //AIZTODO: one output for a single monitor ,to be handled for mulimon - ComPtr pOutput; - HRESULT hr = pAdapter->EnumOutputs( iOutput, pOutput.ReleaseAndGetAddressOf()); - if( DXGI_ERROR_NOT_FOUND == hr ) - break; - else if (FAILED(hr)) - { - break; //Something bad happened. - } - else //Success! - { - DXGI_OUTPUT_DESC OutputDesc; - pOutput->GetDesc(&OutputDesc); - - UINT NumModes = 0; - hr = pOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, - 0, - &NumModes, - NULL); - - // If working over a terminal session, for example using the Simulator for deployment/development, display modes cannot be obtained. - if (hr == DXGI_ERROR_NOT_CURRENTLY_AVAILABLE) - { - DXGI_MODE_DESC fullScreenMode; - fullScreenMode.Width = OutputDesc.DesktopCoordinates.right - OutputDesc.DesktopCoordinates.left; - fullScreenMode.Height = OutputDesc.DesktopCoordinates.bottom - OutputDesc.DesktopCoordinates.top; - fullScreenMode.RefreshRate.Numerator = 60; - fullScreenMode.RefreshRate.Denominator = 1; - fullScreenMode.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - fullScreenMode.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_PROGRESSIVE; - fullScreenMode.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; - - mModeList.push_back(D3D11VideoMode(OutputDesc, fullScreenMode)); - } - else if (hr == S_OK) - { - if (NumModes > 0) - { - // Create an array to store Display Mode information - std::vector modes; - modes.resize(NumModes); - - // Populate our array with information - hr = pOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, - 0, - &NumModes, - modes.data()); - - for (UINT m = 0; m < NumModes; m++) - { - DXGI_MODE_DESC displayMode = modes[m]; - // Filter out low-resolutions - if (displayMode.Width < 640 || displayMode.Height < 400) - continue; - - // Check to see if it is already in the list (to filter out refresh rates) - BOOL found = FALSE; - std::vector::iterator it; - for (it = mModeList.begin(); it != mModeList.end(); it++) - { - DXGI_OUTPUT_DESC oldOutput = it->getDisplayMode(); - DXGI_MODE_DESC oldDisp = it->getModeDesc(); - if (//oldOutput.Monitor==OutputDesc.Monitor && - oldDisp.Width == displayMode.Width && - oldDisp.Height == displayMode.Height// && - //oldDisp.Format == displayMode.Format - ) - { - // Check refresh rate and favour higher if poss - //if (oldDisp.RefreshRate < displayMode.RefreshRate) - // it->increaseRefreshRate(displayMode.RefreshRate); - found = TRUE; - break; - } - } - - if (!found) - mModeList.push_back(D3D11VideoMode(OutputDesc, displayMode)); - - } - } - } - } - } - } - //--------------------------------------------------------------------- - size_t D3D11VideoModeList::count() - { - return mModeList.size(); - } - //--------------------------------------------------------------------- - D3D11VideoMode* D3D11VideoModeList::item( size_t index ) - { - std::vector::iterator p = mModeList.begin(); - - return &p[index]; - } - //--------------------------------------------------------------------- - D3D11VideoMode* D3D11VideoModeList::item( const String &name ) - { - std::vector::iterator it = mModeList.begin(); - if (it == mModeList.end()) - return NULL; - - for (;it != mModeList.end(); ++it) - { - if (it->getDescription() == name) - return &(*it); - } - - return NULL; - } - //--------------------------------------------------------------------- -} diff --git a/RenderSystems/Direct3D11/src/OgreMonitorInfo.cpp b/RenderSystems/Direct3D11/src/OgreMonitorInfo.cpp deleted file mode 100644 index fb28d14c59f..00000000000 --- a/RenderSystems/Direct3D11/src/OgreMonitorInfo.cpp +++ /dev/null @@ -1,55 +0,0 @@ -#include "OgreMonitorInfo.h" -namespace Ogre -{ -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - - void Ogre::MonitorInfo::Refresh() - { - mMapMonitors.clear(); - mCurrentMonitor = 0; - EnumDisplayMonitors(NULL, NULL, MonitorEnumProc,(LPARAM)this); - } - - unsigned short Ogre::MonitorInfo::getMonitorSequentialNumberFromHMonitor( HMONITOR hMonitor, bool allowRefresh /*= false*/ ) - { - MapMonitorToSequentialNumber::const_iterator it = mMapMonitors.find(hMonitor); - bool found = it != mMapMonitors.end(); - if (!found && allowRefresh) - { - Refresh(); - it = mMapMonitors.find(hMonitor); - found = it != mMapMonitors.end(); - } - - if (found) - return it->second; - else - return -1; - } - - unsigned short Ogre::MonitorInfo::getMonitorSequentialNumberFromSwapChain(IDXGISwapChain* swapChain, bool allowRefresh /*= false*/) - { - IDXGIOutput* output; - int monitorSequencialNumber = -1; - if(swapChain != NULL) - { - HRESULT hr = swapChain->GetContainingOutput(&output); - if(hr == S_OK) - { - DXGI_OUTPUT_DESC desc; - output->GetDesc(&desc); - monitorSequencialNumber = getMonitorSequentialNumberFromHMonitor(desc.Monitor, allowRefresh); - } - } - return monitorSequencialNumber; - } - - BOOL CALLBACK MonitorInfo::MonitorEnumProc(_In_ HMONITOR hMonitor, _In_ HDC hdcMonitor, _In_ LPRECT lprcMonitor, _In_ LPARAM dwData) - { - MonitorInfo* _this = (MonitorInfo*)dwData; - _this->mMapMonitors.insert(std::make_pair(hMonitor, _this->mCurrentMonitor++)); - return true; - } - -#endif -} diff --git a/RenderSystems/Direct3D11/src/OgreNsightChecker.cpp b/RenderSystems/Direct3D11/src/OgreNsightChecker.cpp deleted file mode 100644 index 7a651475c00..00000000000 --- a/RenderSystems/Direct3D11/src/OgreNsightChecker.cpp +++ /dev/null @@ -1,145 +0,0 @@ -// GetParentProcID.cpp : Defines the entry point for the console application. -// - -#include "OgrePrerequisites.h" -#include "OgreNsightChecker.h" - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - -#include -#include -#include - -#pragma comment(lib,"Psapi.lib") - - -static BOOL WINAPI GetParentPID(PROCESSENTRY32& procentry) -{ - OSVERSIONINFO osver; - HINSTANCE hInstLib; - HANDLE hSnapShot; - BOOL bContinue; - - // ToolHelp Function Pointers. - HANDLE(WINAPI *lpfCreateToolhelp32Snapshot)(DWORD, DWORD); - BOOL(WINAPI *lpfProcess32First)(HANDLE, LPPROCESSENTRY32); - BOOL(WINAPI *lpfProcess32Next)(HANDLE, LPPROCESSENTRY32); - - // Check to see if were running under Windows95 or - // Windows NT. - osver.dwOSVersionInfoSize = sizeof(osver); - if (!GetVersionEx(&osver)) - { - return FALSE; - } - - if (osver.dwPlatformId != VER_PLATFORM_WIN32_NT) - { - return FALSE; - } - - hInstLib = LoadLibraryA("Kernel32.DLL"); - if (hInstLib == NULL) - { - return FALSE; - } - - // Get procedure addresses. - // We are linking to these functions of Kernel32 - // explicitly, because otherwise a module using - // this code would fail to load under Windows NT, - // which does not have the Toolhelp32 - // functions in the Kernel 32. - lpfCreateToolhelp32Snapshot = - (HANDLE(WINAPI *)(DWORD, DWORD)) - GetProcAddress(hInstLib, - "CreateToolhelp32Snapshot"); - lpfProcess32First = - (BOOL(WINAPI *)(HANDLE, LPPROCESSENTRY32)) - GetProcAddress(hInstLib, "Process32First"); - lpfProcess32Next = - (BOOL(WINAPI *)(HANDLE, LPPROCESSENTRY32)) - GetProcAddress(hInstLib, "Process32Next"); - if (lpfProcess32Next == NULL || - lpfProcess32First == NULL || - lpfCreateToolhelp32Snapshot == NULL) - { - FreeLibrary(hInstLib); - return FALSE; - } - - // Get a handle to a Toolhelp snapshot of the systems - // processes. - hSnapShot = lpfCreateToolhelp32Snapshot( - TH32CS_SNAPPROCESS, 0); - if (hSnapShot == INVALID_HANDLE_VALUE) - { - FreeLibrary(hInstLib); - return FALSE; - } - - // Get the first process' information. - memset((LPVOID)&procentry, 0, sizeof(PROCESSENTRY32)); - procentry.dwSize = sizeof(PROCESSENTRY32); - bContinue = lpfProcess32First(hSnapShot, &procentry); - DWORD pid = 0; - // While there are processes, keep looping. - DWORD crtpid = GetCurrentProcessId(); - while (bContinue) - { - if (crtpid == procentry.th32ProcessID) - pid = procentry.th32ParentProcessID; - - procentry.dwSize = sizeof(PROCESSENTRY32); - bContinue = !pid && lpfProcess32Next(hSnapShot, &procentry); - - }//while ends - - - // Free the library. - FreeLibrary(hInstLib); - - return pid ? TRUE : FALSE; -} - -static std::string GetProcessFileName(DWORD processID) -{ - char buffer[MAX_PATH] = ""; - - HANDLE hProcess = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID); - if (hProcess != NULL) - { - if(0 == GetProcessImageFileName(hProcess, buffer, ARRAYSIZE(buffer))) - buffer[0] = 0; - - CloseHandle(hProcess); - } - - return buffer; -} - -static bool IsWorkingUnderNsightImpl() -{ - PROCESSENTRY32 selfprocentry; - if(GetParentPID(selfprocentry)) - { - std::string parentFileName = GetProcessFileName(selfprocentry.th32ParentProcessID); - return parentFileName.find("Nsight.Monitor") != std::string::npos; - } - return false; -} - -#endif - -namespace Ogre -{ - bool IsWorkingUnderNsight() - { -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - static bool isWorkingUnderNsight = IsWorkingUnderNsightImpl(); - return isWorkingUnderNsight; -#else - return false; -#endif - } -} diff --git a/RenderSystems/Direct3D9/CMakeLists.txt b/RenderSystems/Direct3D9/CMakeLists.txt deleted file mode 100644 index 606a9f183c3..00000000000 --- a/RenderSystems/Direct3D9/CMakeLists.txt +++ /dev/null @@ -1,45 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure Direct3D9 RenderSystem build - -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") - -if (OGRE_CONFIG_ENABLE_QUAD_BUFFER_STEREO) - include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include ${DirectX9_INCLUDE_DIR} ${AMDQBS_INCLUDE_DIR} ${NVAPI_INCLUDE_DIR}) - link_directories(${DirectX9_LIBRARY_DIR} ${NVAPI_LIBRARY_DIR}) -else() - include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include ${DirectX9_INCLUDE_DIR}) - link_directories(${DirectX9_LIBRARY_DIR}) -endif() - -add_definitions(-D_USRDLL) - - -add_library(RenderSystem_Direct3D9 ${OGRE_LIB_TYPE} ${HEADER_FILES} ${SOURCE_FILES}) -target_link_libraries(RenderSystem_Direct3D9 - OgreMain - ${DirectX9_LIBRARIES} -) - -if (NOT OGRE_STATIC) - set_target_properties(RenderSystem_Direct3D9 PROPERTIES - COMPILE_DEFINITIONS OGRED3DENGINEDLL_EXPORTS - ) -endif () -if (OGRE_CONFIG_THREADS) - target_link_libraries(RenderSystem_Direct3D9 ${OGRE_THREAD_LIBRARIES}) -endif () -if(OGRE_CONFIG_ENABLE_QUAD_BUFFER_STEREO) - target_link_libraries(RenderSystem_Direct3D9 ${NVAPI_LIBRARIES}) -endif() - -ogre_config_plugin(RenderSystem_Direct3D9) -install(FILES ${HEADER_FILES} DESTINATION include/OGRE/RenderSystems/Direct3D9) diff --git a/RenderSystems/Direct3D9/include/OgreD3D9DepthBuffer.h b/RenderSystems/Direct3D9/include/OgreD3D9DepthBuffer.h deleted file mode 100644 index 46cec04ab97..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9DepthBuffer.h +++ /dev/null @@ -1,59 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9DEPTHBUFFER_H__ -#define __D3D9DEPTHBUFFER_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreDepthBuffer.h" - -namespace Ogre -{ - class D3D9DepthBuffer : public DepthBuffer - { - public: - D3D9DepthBuffer( uint16 poolId, D3D9RenderSystem *renderSystem, IDirect3DDevice9 *creator, - IDirect3DSurface9 *depthBufferSurf, - D3DFORMAT fmt, uint32 width, uint32 height, - uint32 fsaa, uint32 multiSampleQuality, bool isManual ); - ~D3D9DepthBuffer(); - - /// @copydoc DepthBuffer::isCompatible - virtual bool isCompatible( RenderTarget *renderTarget ) const; - - IDirect3DDevice9* getDeviceCreator() const; - IDirect3DSurface9* getDepthBufferSurface() const; - - protected: - IDirect3DSurface9 *mDepthBuffer; - IDirect3DDevice9 *mCreator; - uint32 mMultiSampleQuality; - D3DFORMAT mD3DFormat; - D3D9RenderSystem *mRenderSystem; - }; -} -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9Device.h b/RenderSystems/Direct3D9/include/OgreD3D9Device.h deleted file mode 100755 index 288623c1e79..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9Device.h +++ /dev/null @@ -1,158 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9Device_H__ -#define __D3D9Device_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreRenderTarget.h" - -namespace Ogre { - - class D3D9RenderWindow; - class D3D9DeviceManager; - - /** High level interface of Direct3D9 Device. - Provide useful methods for device handling. - */ - class _OgreD3D9Export D3D9Device : public ResourceAlloc - { - - // Interface. - public: - void attachRenderWindow (D3D9RenderWindow* renderWindow); - void detachRenderWindow (D3D9RenderWindow* renderWindow); - - bool acquire (); - - void release (); - void destroy (); - - bool isDeviceLost (); - IDirect3DDevice9* getD3D9Device (); - - UINT getAdapterNumber () const; - D3DDEVTYPE getDeviceType () const; - bool isMultihead () const; - bool isAutoDepthStencil () const; - bool isFullScreen () const; - - const D3DCAPS9& getD3D9DeviceCaps () const; - D3DFORMAT getBackBufferFormat () const; - - bool validate (D3D9RenderWindow* renderWindow); - void invalidate (D3D9RenderWindow* renderWindow); - - void present (D3D9RenderWindow* renderWindow); - - IDirect3DSurface9* getDepthBuffer (D3D9RenderWindow* renderWindow); - IDirect3DSurface9* getBackBuffer (D3D9RenderWindow* renderWindow); - - uint getRenderWindowCount () const; - D3D9RenderWindow* getRenderWindow (uint index); - uint getLastPresentFrame () const { return mLastPresentFrame; } - - void setAdapterOrdinalIndex (D3D9RenderWindow* renderWindow, uint adapterOrdinalInGroupIndex); - void copyContentsToMemory(D3D9RenderWindow* window, const Box& src, const PixelBox &dst, RenderTarget::FrameBuffer buffer); - void clearDeviceStreams (); - int getVBlankMissCount (D3D9RenderWindow* renderWindow); - - public: - D3D9Device (D3D9DeviceManager* deviceManager, - UINT adapterNumber, - HMONITOR hMonitor, - D3DDEVTYPE devType, - DWORD behaviorFlags); - ~D3D9Device (); - - protected: - D3D9DeviceManager* mDeviceManager; // The manager of this device instance. - IDirect3DDevice9* mDevice; // Will hold the device interface. - UINT mAdapterNumber; // The adapter that this device belongs to. - HMONITOR mMonitor; // The monitor that this device belongs to. - D3DDEVTYPE mDeviceType; // Device type. - static HWND msSharedFocusWindow; // The shared focus window in case of multiple full screen render windows. - HWND mFocusWindow; // The focus window this device attached to. - DWORD mBehaviorFlags; // The behavior of this device. - D3DPRESENT_PARAMETERS* mPresentationParams; // Presentation parameters which the device was created with. May be - // an array of presentation parameters in case of multi-head device. - UINT mPresentationParamsCount; // Number of presentation parameters elements. - D3DCAPS9 mD3D9DeviceCaps; // Device caps. - bool mD3D9DeviceCapsValid; // True if device caps initialized. - D3DDEVICE_CREATION_PARAMETERS mCreationParams; // Creation parameters. - uint mLastPresentFrame; // Last frame that this device present method called. - bool mDeviceLost; // True if device entered lost state. - D3DPRESENTSTATS mPreviousPresentStats; // We save the previous present stats - so we can detect a "vblank miss" - bool mPreviousPresentStatsIsValid; // Does mLastPresentStats data is valid (it isn't if when you start or resize the window) - uint mVBlankMissCount; // Number of times we missed the v sync blank - - struct RenderWindowResources - { - IDirect3DSwapChain9* swapChain; // Swap chain interface. - IDirect3DSwapChain9Ex * swapChain9Ex; // The 9Ex version of the chain is needed for the v synk blank stats - uint adapterOrdinalInGroupIndex; // Relative index of the render window in the group. - uint presentParametersIndex; // Index of present parameter in the shared array of the device. - IDirect3DSurface9* backBuffer; // The back buffer of the render window. - IDirect3DSurface9* depthBuffer; // The depth buffer of the render window. - D3DPRESENT_PARAMETERS presentParameters; // Present parameters of the render window. - bool acquired; // True if resources acquired. - }; - typedef std::map RenderWindowToResourcesMap; - typedef RenderWindowToResourcesMap::iterator RenderWindowToResourcesIterator; - - RenderWindowToResourcesMap mMapRenderWindowToResources; // Map between render window to resources. - - - protected: - RenderWindowToResourcesIterator getRenderWindowIterator (D3D9RenderWindow* renderWindow); - - bool acquire (D3D9RenderWindow* renderWindow); - bool reset (); - void updatePresentationParameters (); - void updateRenderWindowsIndices (); - - void createD3D9Device (); - void releaseD3D9Device (); - void releaseRenderWindowResources (RenderWindowResources* renderWindowResources); - void acquireRenderWindowResources (RenderWindowToResourcesIterator it); - void setupDeviceStates (); - void notifyDeviceLost (); - - void validateFocusWindow (); - void validateBackBufferSize (D3D9RenderWindow* renderWindow); - bool validateDisplayMonitor (D3D9RenderWindow* renderWindow); - bool validateDeviceState (D3D9RenderWindow* renderWindow); - bool isSwapChainWindow (D3D9RenderWindow* renderWindow); - D3D9RenderWindow* getPrimaryWindow (); - void setSharedWindowHandle (HWND hSharedHWND); - - private: - friend class D3D9DeviceManager; - friend class D3D9RenderSystem; - }; -} -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9DeviceManager.h b/RenderSystems/Direct3D9/include/OgreD3D9DeviceManager.h deleted file mode 100755 index 385af17b687..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9DeviceManager.h +++ /dev/null @@ -1,76 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9DeviceManager_H__ -#define __D3D9DeviceManager_H__ - -#include "OgreD3D9Prerequisites.h" - -namespace Ogre { - - class D3D9Device; - class D3D9RenderWindow; - - /** Device manager interface. - */ - class _OgreD3D9Export D3D9DeviceManager : public ResourceAlloc - { - - // Interface. - public: - void setActiveDevice (D3D9Device* device); - D3D9Device* getActiveDevice () {return mActiveDevice;} - void setActiveRenderTargetDevice (D3D9Device* device); - D3D9Device* getActiveRenderTargetDevice (); - UINT getDeviceCount (); - D3D9Device* getDevice (UINT index); - void linkRenderWindow (D3D9RenderWindow* renderWindow); - void destroyInactiveRenderDevices (); - void notifyOnDeviceDestroy (D3D9Device* device); - D3D9Device* getDeviceFromD3D9Device (IDirect3DDevice9* d3d9Device); - - public: - D3D9DeviceManager (); - ~D3D9DeviceManager (); - - protected: - typedef std::vector DeviceList; - typedef DeviceList::iterator DeviceIterator; - typedef DeviceList::const_iterator ConstDeviceIterator; - typedef std::vector D3D9RenderWindowList; - - protected: - D3D9Device* selectDevice (D3D9RenderWindow* renderWindow, D3D9RenderWindowList& renderWindowsGroup); - D3D9Driver* findDriver (D3D9RenderWindow* renderWindow); - - - DeviceList mRenderDevices; - D3D9Device* mActiveDevice; - D3D9Device* mActiveRenderWindowDevice; - }; -} -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9Driver.h b/RenderSystems/Direct3D9/include/OgreD3D9Driver.h deleted file mode 100644 index 4acb398074d..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9Driver.h +++ /dev/null @@ -1,80 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9DRIVER_H__ -#define __D3D9DRIVER_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreString.h" - -namespace Ogre -{ - - class D3D9VideoModeList; - class D3D9VideoMode; - - class _OgreD3D9Export D3D9Driver : public ResourceAlloc - { - - public: - // Constructors - D3D9Driver(); // Default - D3D9Driver( const D3D9Driver &ob ); // Copy - D3D9Driver( unsigned int adapterNumber, - const D3DCAPS9& deviceCaps, - const D3DADAPTER_IDENTIFIER9& adapterIdentifer, - const D3DDISPLAYMODE& desktopDisplayMode); - ~D3D9Driver(); - - - const D3DCAPS9& getD3D9DeviceCaps () const { return mD3D9DeviceCaps; } - String DriverName () const; - String DriverDescription () const; - - unsigned int getAdapterNumber () const { return mAdapterNumber; } - const D3DADAPTER_IDENTIFIER9& getAdapterIdentifier() const { return mAdapterIdentifier; } - const D3DDISPLAYMODE& getDesktopMode () const { return mDesktopDisplayMode; } - D3D9VideoModeList* getVideoModeList (); - - private: - // Adapter number. - unsigned int mAdapterNumber; - - // Device caps. - D3DCAPS9 mD3D9DeviceCaps; - - // Adapter identifier - D3DADAPTER_IDENTIFIER9 mAdapterIdentifier; - - // Desktop display mode. - D3DDISPLAYMODE mDesktopDisplayMode; - - // Video modes list. - D3D9VideoModeList* mVideoModeList; - }; -} -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9DriverList.h b/RenderSystems/Direct3D9/include/OgreD3D9DriverList.h deleted file mode 100644 index c72420f4104..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9DriverList.h +++ /dev/null @@ -1,52 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9DRIVERLIST_H__ -#define __D3D9DRIVERLIST_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreD3D9Driver.h" - -namespace Ogre -{ - class _OgreD3D9Export D3D9DriverList : public ResourceAlloc - { - private: - std::vector mDriverList; - - public: - D3D9DriverList(); - ~D3D9DriverList(); - - BOOL enumerate(); - size_t count() const; - D3D9Driver* item( size_t index ); - - D3D9Driver* item( const String &name ); - }; -} -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9GpuProgram.h b/RenderSystems/Direct3D9/include/OgreD3D9GpuProgram.h deleted file mode 100644 index 6891a08fbd2..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9GpuProgram.h +++ /dev/null @@ -1,134 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9GpuProgram_H_ -#define __D3D9GpuProgram_H_ - -// Precompiler options -#include "OgreD3D9Prerequisites.h" -#include "OgreGpuProgram.h" -#include "OgreD3D9Resource.h" - -#include - -namespace Ogre { - - /** Direct3D implementation of a few things common to low-level vertex & fragment programs. */ - class _OgreD3D9Export D3D9GpuProgram : public GpuProgram, public D3D9Resource - { - public: - /// Command object for setting matrix packing in column-major order - class CmdColumnMajorMatrices : public ParamCommand - { - public: - String doGet(const void* target) const; - void doSet(void* target, const String& val); - }; - /// Command object for getting/setting external micro code (void*) - class CmdExternalMicrocode : public ParamCommand - { - public: - String doGet(const void* target) const; - void doSet(void* target, const String& val); - }; - protected: - static CmdColumnMajorMatrices msCmdColumnMajorMatrices; - static CmdExternalMicrocode msCmdExternalMicrocode; - public: - D3D9GpuProgram(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader); - ~D3D9GpuProgram(); - - - /** Sets whether matrix packing in column-major order. */ - void setColumnMajorMatrices(bool columnMajor) { mColumnMajorMatrices = columnMajor; } - /** Gets whether matrix packed in column-major order. */ - bool getColumnMajorMatrices(void) const { return mColumnMajorMatrices; } - - /** Tells the program to load from some externally created microcode instead of a file or source. - */ - void setExternalMicrocode(const void* pMicrocode, size_t size); - /** Tells the program to load from some externally created microcode instead of a file or source. - - add ref count to pMicrocode when setting - */ - void setExternalMicrocode(ID3DXBuffer* pMicrocode); - /** Gets the external microcode buffer, if any. */ - LPD3DXBUFFER getExternalMicrocode(void); - - /// Gets the vertex shader - IDirect3DVertexShader9* getVertexShader(void); - - /// Gets the pixel shader - IDirect3DPixelShader9* getPixelShader(void); - - // Called immediately after the Direct3D device has been created. - virtual void notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device); - - // Called before the Direct3D device is going to be destroyed. - virtual void notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device); - - protected: - /** @copydoc Resource::loadImpl */ - void loadImpl(void); - /** Loads this program to specified device */ - void loadImpl(IDirect3DDevice9* d3d9Device); - /** Overridden from GpuProgram */ - void unloadImpl(void); - /** Overridden from GpuProgram */ - void loadFromSource(void); - /** Loads this program from source to specified device */ - void loadFromSource(IDirect3DDevice9* d3d9Device); - /** Loads this program from microcode, must be overridden by subclasses. */ - void loadFromMicrocode(IDirect3DDevice9* d3d9Device, ID3DXBuffer* microcode); - - - /** Creates a new parameters object compatible with this program definition. - - It is recommended that you use this method of creating parameters objects - rather than going direct to GpuProgramManager, because this method will - populate any implementation-specific extras (like named parameters) where - they are appropriate. - */ - virtual GpuProgramParametersSharedPtr createParameters(void); - protected: - bool mColumnMajorMatrices; - ID3DXBuffer* mExternalMicrocode; - - typedef std::map DeviceToShaderMap; - DeviceToShaderMap mMapDeviceToShader; - - void getMicrocodeFromCache( IDirect3DDevice9* d3d9Device, uint32 id ); - void compileMicrocode( IDirect3DDevice9* d3d9Device ); - }; - - typedef D3D9GpuProgram D3D9GpuFragmentProgram; - typedef D3D9GpuProgram D3D9GpuVertexProgram; -} - - -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9GpuProgramManager.h b/RenderSystems/Direct3D9/include/OgreD3D9GpuProgramManager.h deleted file mode 100644 index 6c3820ab379..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9GpuProgramManager.h +++ /dev/null @@ -1,47 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9GpuProgramManager_H__ -#define __D3D9GpuProgramManager_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreGpuProgramManager.h" - -namespace Ogre { - - class _OgreD3D9Export D3D9GpuProgramManager : public GpuProgramFactory - { - public: - static String currentLanguage; - const String& getLanguage(void) const override; - GpuProgram* create(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) override; - }; - -} - -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9HLSLProgram.h b/RenderSystems/Direct3D9/include/OgreD3D9HLSLProgram.h deleted file mode 100644 index 08e2b38eb0f..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9HLSLProgram.h +++ /dev/null @@ -1,188 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9HLSLProgram_H__ -#define __D3D9HLSLProgram_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreHighLevelGpuProgram.h" - -#include - -namespace Ogre { - /** Specialisation of HighLevelGpuProgram to provide support for D3D9 - High-Level Shader Language (HLSL). - - Note that the syntax of D3D9 HLSL is identical to nVidia's Cg language, therefore - unless you know you will only ever be deploying on Direct3D, or you have some specific - reason for not wanting to use the Cg plugin, I suggest you use Cg instead since that - can produce programs for OpenGL too. - */ - class _OgreD3D9Export D3D9HLSLProgram : public HighLevelGpuProgram - { - public: - /// Command object for setting target assembler - class CmdTarget : public ParamCommand - { - public: - String doGet(const void* target) const; - void doSet(void* target, const String& val); - }; - /// Command object for setting matrix packing in column-major order - class CmdColumnMajorMatrices : public ParamCommand - { - public: - String doGet(const void* target) const; - void doSet(void* target, const String& val); - }; - /// Command object for setting optimisation level - class CmdOptimisation : public ParamCommand - { - public: - String doGet(const void* target) const; - void doSet(void* target, const String& val); - }; - - /// Command object for getting/setting micro code - class CmdMicrocode : public ParamCommand - { - public: - String doGet(const void* target) const; - void doSet(void* target, const String& val); - }; - - /// Command object for getting/setting assembler code - class CmdAssemblerCode : public ParamCommand - { - public: - String doGet(const void* target) const; - void doSet(void* target, const String& val); - }; - - /// Command object for enabling backwards compatibility - class CmdBackwardsCompatibility : public ParamCommand - { - public: - String doGet(const void* target) const; - void doSet(void* target, const String& val); - }; - - protected: - - static CmdTarget msCmdTarget; - static CmdColumnMajorMatrices msCmdColumnMajorMatrices; - static CmdOptimisation msCmdOptimisation; - static CmdMicrocode msCmdMicrocode; - static CmdAssemblerCode msCmdAssemblerCode; - static CmdBackwardsCompatibility msCmdBackwardsCompatibility; - - void prepareImpl(); - void loadFromSource() {} // all done in prepare - /** Internal method for creating an appropriate low-level program from this - high-level program, must be implemented by subclasses. */ - void createLowLevelImpl(void); - /// Internal unload implementation, must be implemented by subclasses - void unloadHighLevelImpl(void); - /// Populate the passed parameters with name->index map, must be overridden - void buildConstantDefinitions() override; - - // Recursive utility method for buildParamNameMap - void processParamElement(LPD3DXCONSTANTTABLE pConstTable, D3DXHANDLE parent, String prefix, unsigned int index); - void populateDef(D3DXCONSTANT_DESC& d3dDesc, GpuConstantDefinition& def) const; - - bool mColumnMajorMatrices; - bool mBackwardsCompatibility; - - LPD3DXBUFFER mMicroCode; - - GpuConstantDefinitionMap mParametersMap; - size_t mParametersMapSizeAsBuffer; - - public: - LPD3DXBUFFER getMicroCode(); - public: - /// Shader optimisation level - enum OptimisationLevel - { - /// default - no optimisation in debug mode, OPT_1 in release mode - OPT_DEFAULT, - /// No optimisation - OPT_NONE, - /// Optimisation level 0 - OPT_0, - /// Optimisation level 1 - OPT_1, - /// Optimisation level 2 - OPT_2, - /// Optimisation level 3 - OPT_3 - }; - protected: - OptimisationLevel mOptimisationLevel; - - /** Gets the microcode from the microcode cache. */ - void getMicrocodeFromCache(uint32 id); - /** Compiles the microcode from the program source. */ - void compileMicrocode(void); - void addMicrocodeToCache(uint32 id); - public: - D3D9HLSLProgram(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader); - ~D3D9HLSLProgram(); - - /** Sets the entry point for this program ie the first method called. */ - void setEntryPoint(const String& entryPoint) { mEntryPoint = entryPoint; } - /** Gets the entry point defined for this program. */ - const String& getEntryPoint(void) const { return mEntryPoint; } - /** Sets the shader target to compile down to, e.g. 'vs_1_1'. */ - void setTarget(const String& target); - /** Gets the shader target to compile down to, e.g. 'vs_1_1'. */ - const String& getTarget(void) const; - /** Sets whether matrix packing in column-major order. */ - void setColumnMajorMatrices(bool columnMajor) { mColumnMajorMatrices = columnMajor; } - /** Gets whether matrix packed in column-major order. */ - bool getColumnMajorMatrices(void) const { return mColumnMajorMatrices; } - /** Sets whether backwards compatibility mode should be enabled. */ - void setBackwardsCompatibility(bool compat) { mBackwardsCompatibility = compat; } - /** Gets whether backwards compatibility mode should be enabled. */ - bool getBackwardsCompatibility(void) const { return mBackwardsCompatibility; } - /** Sets the optimisation level to use. - @param opt Optimisation level - */ - void setOptimisationLevel(OptimisationLevel opt) { mOptimisationLevel = opt; } - - /** Gets the optimisation level to use. */ - OptimisationLevel getOptimisationLevel() const { return mOptimisationLevel; } - - /// Overridden from GpuProgram - GpuProgramParametersSharedPtr createParameters(void); - /// Overridden from GpuProgram - const String& getLanguage(void) const; - }; -} - -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9HLSLProgramFactory.h b/RenderSystems/Direct3D9/include/OgreD3D9HLSLProgramFactory.h deleted file mode 100644 index 52ca9991a5f..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9HLSLProgramFactory.h +++ /dev/null @@ -1,52 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9HLSLProgramFactory_H__ -#define __D3D9HLSLProgramFactory_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreHighLevelGpuProgramManager.h" - -namespace Ogre -{ - /** Factory class for D3D9 HLSL programs. */ - class _OgreD3D9Export D3D9HLSLProgramFactory : public HighLevelGpuProgramFactory - { - protected: - static String sLanguageName; - public: - D3D9HLSLProgramFactory(); - ~D3D9HLSLProgramFactory(); - /// Get the name of the language this factory creates programs for - const String& getLanguage(void) const; - GpuProgram* create(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader); - }; -} - -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9HardwareBuffer.h b/RenderSystems/Direct3D9/include/OgreD3D9HardwareBuffer.h deleted file mode 100644 index 3de49a92050..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9HardwareBuffer.h +++ /dev/null @@ -1,112 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9HardwareBuffer_H__ -#define __D3D9HardwareBuffer_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreHardwareBuffer.h" -#include "OgreD3D9Resource.h" - -namespace Ogre { - - /// Specialisation of HardwareVertexBuffer for D3D9 - class _OgreD3D9Export D3D9HardwareBuffer : public HardwareBuffer, public D3D9Resource - { - - public: - D3D9HardwareBuffer(D3DFORMAT type, size_t sizeInBytes, Usage usage, - bool useShadowBuffer); - ~D3D9HardwareBuffer(); - /** See HardwareBuffer. */ - void readData(size_t offset, size_t length, void* pDest); - /** See HardwareBuffer. */ - void writeData(size_t offset, size_t length, const void* pSource, - bool discardWholeBuffer = false); - - // Called immediately after the Direct3D device has been created. - virtual void notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device); - - // Called before the Direct3D device is going to be destroyed. - virtual void notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device); - - // Called immediately after the Direct3D device has entered a lost state. - virtual void notifyOnDeviceLost(IDirect3DDevice9* d3d9Device); - - // Called immediately after the Direct3D device has been reset - virtual void notifyOnDeviceReset(IDirect3DDevice9* d3d9Device); - - // Create the actual vertex buffer. - void createBuffer(IDirect3DDevice9* d3d9Device, D3DPOOL ePool, bool updateNewBuffer); - - /// Get D3D9-specific resource - IDirect3DResource9* getD3D9Resource(void); - protected: - struct BufferResources - { - IDirect3DResource9* mBuffer; - bool mOutOfDate; - size_t mLockOffset; - size_t mLockLength; - LockOptions mLockOptions; - uint mLastUsedFrame; - }; - - protected: - /** See HardwareBuffer. */ - void* lockImpl(size_t offset, size_t length, LockOptions options); - - /** See HardwareBuffer. */ - void unlockImpl(void); - - /** Update the given buffer content.*/ - void updateBufferContent(BufferResources* bufferResources); - - // updates buffer resources from system memory buffer. - bool updateBufferResources(const char* systemMemoryBuffer, BufferResources* bufferResources); - - /** Internal buffer lock method. */ - char* _lockBuffer(BufferResources* bufferResources, size_t offset, size_t length); - - /** Internal buffer unlock method. */ - void _unlockBuffer(BufferResources* bufferResources); - - - protected: - typedef std::map DeviceToBufferResourcesMap; - typedef DeviceToBufferResourcesMap::iterator DeviceToBufferResourcesIterator; - - DeviceToBufferResourcesMap mMapDeviceToBufferResources; // Map between device to buffer resources. - D3DVERTEXBUFFER_DESC mBufferDesc; // Buffer description. - BufferResources* mSourceBuffer; // Source buffer resources when working with multiple devices. - char* mSourceLockedBytes; // Source buffer locked bytes. - D3DFORMAT mType; - }; - -} -#endif - diff --git a/RenderSystems/Direct3D9/include/OgreD3D9HardwareBufferManager.h b/RenderSystems/Direct3D9/include/OgreD3D9HardwareBufferManager.h deleted file mode 100644 index 144f2891aae..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9HardwareBufferManager.h +++ /dev/null @@ -1,61 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9HARWAREBUFFERMANAGER_H__ -#define __D3D9HARWAREBUFFERMANAGER_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreHardwareBufferManager.h" - -namespace Ogre { - - /** Implementation of HardwareBufferManager for D3D9. */ - class _OgreD3D9Export D3D9HardwareBufferManager : public HardwareBufferManager - { - bool mAutoHardwareBufferManagement; - VertexDeclaration* createVertexDeclarationImpl(void) override; - public: - /** - Set automatic hardware buffers management. - When enabled, an explicit system memory backup is created for buffers with no read caps - so in case of device lost/ device swaps - the content of the buffers can be restored from this copy. - The default is false in order to reduce system memory consumption. - */ - void setAutoHardwareBufferManagement(bool autoManagement) { mAutoHardwareBufferManagement = autoManagement; } - D3D9HardwareBufferManager(); - ~D3D9HardwareBufferManager(); - /// Creates a vertex buffer - HardwareVertexBufferSharedPtr - createVertexBuffer(size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer = false); - /// Create a hardware vertex buffer - HardwareIndexBufferSharedPtr - createIndexBuffer(HardwareIndexBuffer::IndexType itype, size_t numIndexes, HardwareBuffer::Usage usage, bool useShadowBuffer = false); - }; -} - - -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9HardwareOcclusionQuery.h b/RenderSystems/Direct3D9/include/OgreD3D9HardwareOcclusionQuery.h deleted file mode 100644 index 4e968b7d5e3..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9HardwareOcclusionQuery.h +++ /dev/null @@ -1,115 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef _D3D9HARWAREOCCLUSIONQUERY_H__ -#define _D3D9HARWAREOCCLUSIONQUERY_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreHardwareOcclusionQuery.h" -#include "OgreD3D9Resource.h" - - -namespace Ogre { - - // If you use multiple rendering passes you can test only the first pass and all other passes don't have to be rendered - // if the first pass results has too few pixels visible. - - // Be sure to render all occluder first and whats out so the RenderQue don't switch places on - // the occluding objects and the tested objects because it thinks it's more effective.. - - /** - * This is a class that is the DirectX9 implementation of - * hardware occlusion testing. - * - * @author Lee Sandberg, email lee@abcmedia.se - * - * Updated on 12/7/2004 by Chris McGuirk - * Updated on 4/8/2005 by Tuan Kuranes email: tuan.kuranes@free.fr - */ - class _OgreD3D9Export D3D9HardwareOcclusionQuery : public HardwareOcclusionQuery, public D3D9Resource - { - //---------------------------------------------------------------------- - // Public methods - //-- - public: - - /** - * Default object constructor - * - */ - D3D9HardwareOcclusionQuery(); - - /** - * Object destructor - */ - ~D3D9HardwareOcclusionQuery(); - - //------------------------------------------------------------------ - // Occlusion query functions (see base class documentation for this) - //-- - - void beginOcclusionQuery(); - void endOcclusionQuery(); - bool pullOcclusionQuery( unsigned int* NumOfFragments); - unsigned int getLastQuerysPixelcount(); - bool isStillOutstanding(void); - - // Called immediately after the Direct3D device has been created. - virtual void notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device); - - // Called before the Direct3D device is going to be destroyed. - virtual void notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device); - - // Called immediately after the Direct3D device has entered a lost state. - // This is the place to release non-managed resources. - virtual void notifyOnDeviceLost(IDirect3DDevice9* d3d9Device); - - // Called immediately after the Direct3D device has been reset. - // This is the place to create non-managed resources. - virtual void notifyOnDeviceReset(IDirect3DDevice9* d3d9Device); - - - private: - void createQuery(IDirect3DDevice9* d3d9Device); - void releaseQuery(IDirect3DDevice9* d3d9Device); - - //---------------------------------------------------------------------- - // private members - //-- - private: - typedef std::map DeviceToQueryMap; - typedef DeviceToQueryMap::iterator DeviceToQueryIterator; - - DeviceToQueryMap mMapDeviceToQuery; - }; - - -} - - -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9HardwarePixelBuffer.h b/RenderSystems/Direct3D9/include/OgreD3D9HardwarePixelBuffer.h deleted file mode 100644 index a30074e85e4..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9HardwarePixelBuffer.h +++ /dev/null @@ -1,166 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9PIXELBUFFER_H__ -#define __D3D9PIXELBUFFER_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreHardwarePixelBuffer.h" -#include "Threading/OgreThreadHeaders.h" - -namespace Ogre { - - class D3D9Texture; - class D3D9RenderTexture; - - class _OgreD3D9Export D3D9HardwarePixelBuffer: public HardwarePixelBuffer - { - protected: - struct BufferResources - { - /// Surface abstracted by this buffer - IDirect3DSurface9* surface; - /// AA Surface abstracted by this buffer - IDirect3DSurface9* fSAASurface; - /// Volume abstracted by this buffer - IDirect3DVolume9* volume; - /// Temporary surface in main memory if direct locking of mSurface is not possible - IDirect3DSurface9* tempSurface; - /// Temporary volume in main memory if direct locking of mVolume is not possible - IDirect3DVolume9* tempVolume; - /// Mip map texture. - IDirect3DBaseTexture9 *mipTex; - // for depth only RTTs - IDirect3DSurface9* nullSurface; - }; - - typedef std::map DeviceToBufferResourcesMap; - typedef DeviceToBufferResourcesMap::iterator DeviceToBufferResourcesIterator; - - BufferResources* createOrRetrieveResources(IDirect3DDevice9* d3d9Device); - - /// Map between device to buffer resources. - DeviceToBufferResourcesMap mMapDeviceToBufferResources; - - /// Mipmapping - bool mDoMipmapGen; - bool mHWMipmaps; - - // The owner texture if exists. - D3D9Texture* mOwnerTexture; - - // Device access mutex. - OGRE_STATIC_MUTEX(msDeviceAccessMutex); - - Image mStagingBuffer; - protected: - /// Lock a box - PixelBox lockImpl(const Box &lockBox, LockOptions options); - PixelBox lockBuffer(BufferResources* bufferResources, const Box &lockBox, DWORD flags); - - /// Unlock a box - void unlockImpl(void); - void unlockBuffer(BufferResources* bufferResources); - - BufferResources* getBufferResources(IDirect3DDevice9* d3d9Device); - - /// updates render texture. - void updateRenderTexture(bool writeGamma, uint fsaa, const String& srcName); - /// destroy render texture. - void destroyRenderTexture(); - - void blit(IDirect3DDevice9* d3d9Device, const HardwarePixelBufferSharedPtr &src, - const Box &srcBox, const Box &dstBox, - BufferResources* srcBufferResources, - BufferResources* dstBufferResources); - void blitFromMemory(const PixelBox &src, const Box &dstBox, BufferResources* dstBufferResources); - - void blitToMemory(const Box &srcBox, const PixelBox &dst, BufferResources* srcBufferResources, IDirect3DDevice9* d3d9Device); - - public: - D3D9HardwarePixelBuffer(HardwareBuffer::Usage usage, - D3D9Texture* ownerTexture); - ~D3D9HardwarePixelBuffer(); - - /// Call this to associate a D3D surface or volume with this pixel buffer - void bind(IDirect3DDevice9 *dev, IDirect3DSurface9 *mSurface, IDirect3DSurface9* fsaaSurface, - bool writeGamma, uint fsaa, const String& srcName, IDirect3DBaseTexture9 *mipTex); - void bind(IDirect3DDevice9 *dev, IDirect3DVolume9 *mVolume, IDirect3DBaseTexture9 *mipTex); - - /// @copydoc HardwarePixelBuffer::blit - void blit(const HardwarePixelBufferSharedPtr &src, const Box &srcBox, const Box &dstBox); - - /// @copydoc HardwarePixelBuffer::blitFromMemory - void blitFromMemory(const PixelBox &src, const Box &dstBox); - - /// @copydoc HardwarePixelBuffer::blitToMemory - void blitToMemory(const Box &srcBox, const PixelBox &dst); - - /// Internal function to update mipmaps on update of level 0 - void _genMipmaps(IDirect3DBaseTexture9* mipTex); - - /// Function to set mipmap generation - void _setMipmapping(bool doMipmapGen, bool HWMipmaps); - - - /// Get rendertarget for z slice - RenderTexture *getRenderTarget(size_t zoffset); - - /// Accessor for surface - IDirect3DSurface9* getSurface(IDirect3DDevice9* d3d9Device) - { - return createOrRetrieveResources(d3d9Device)->surface; - } - - /// Accessor for AA surface - IDirect3DSurface9* getFSAASurface(IDirect3DDevice9* d3d9Device) - { - return createOrRetrieveResources(d3d9Device)->fSAASurface; - } - - /// For depth-only targets - IDirect3DSurface9* getNullSurface(IDirect3DDevice9* d3d9Device) - { - return createOrRetrieveResources(d3d9Device)->nullSurface; - } - - /// Release surfaces held by this pixel buffer. - void releaseSurfaces(IDirect3DDevice9* d3d9Device); - - /// Destroy resources associated with the given device. - void destroyBufferResources(IDirect3DDevice9* d3d9Device); - - // Called when device state is changing. Access to any device should be locked. - // Relevant for multi thread application. - static void lockDeviceAccess(); - - // Called when device state change completed. Access to any device is allowed. - // Relevant for multi thread application. - static void unlockDeviceAccess(); - }; -}; -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9Mappings.h b/RenderSystems/Direct3D9/include/OgreD3D9Mappings.h deleted file mode 100644 index 549bd10322c..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9Mappings.h +++ /dev/null @@ -1,122 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9MAPPINGS_H__ -#define __D3D9MAPPINGS_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreCommon.h" -#include "OgreMaterial.h" -#include "OgreRenderSystem.h" -#include "OgreHardwareBuffer.h" -#include "OgreHardwareIndexBuffer.h" - -namespace Ogre -{ - class _OgreD3D9Export D3D9Mappings - { - public: - /// enum identifying D3D9 tex. types - enum eD3DTexType - { - /// standard texture - D3D_TEX_TYPE_NORMAL, - /// cube texture - D3D_TEX_TYPE_CUBE, - /// volume texture - D3D_TEX_TYPE_VOLUME, - /// just to have it... - D3D_TEX_TYPE_NONE - }; - - /// enum identifying D3D9 filter usage type - enum eD3DFilterUsage - { - /// min filter - D3D_FUSAGE_MIN, - /// mag filter - D3D_FUSAGE_MAG, - /// mip filter - D3D_FUSAGE_MIP - }; - - /// return a D3D9 equivalent for a Ogre ShadeOptions value - static DWORD get(ShadeOptions so); - /// return a D3D9 equivalent for a Ogre TexCoordCalsMethod value - static DWORD get(TexCoordCalcMethod m, const D3DCAPS9& caps); - /// return a D3D9 equivalent for a Ogre TextureAddressingMode value - static D3DTEXTUREADDRESS get(TextureAddressingMode tam, const D3DCAPS9& devCaps); - /// return a D3D9 equivalent for a Ogre LayerBlendType value - static D3DTEXTURESTAGESTATETYPE get(LayerBlendType lbt); - /// return a D3D9 equivalent for a Ogre LayerBlendOperationEx value - static DWORD get(LayerBlendOperationEx lbo, const D3DCAPS9& devCaps); - /// return a D3D9 equivalent for a Ogre LayerBlendSource value - static DWORD get(LayerBlendSource lbs, bool perStageConstants); - /// return a D3D9 equivalent for a Ogre SceneBlendFactor value - static D3DBLEND get(SceneBlendFactor sbf); - /// return a D3D9 equivalent for a Ogre SceneBlendOperation value - static D3DBLENDOP get(SceneBlendOperation sbo); - /// return a D3D9 equivalent for a Ogre CompareFunction value - static DWORD get(CompareFunction cf); - /// return a D3D9 equivalent for a Ogre CillingMode value - static DWORD get(CullingMode cm, bool flip); - /// return a D3D9 equivalent for a Ogre FogMode value - static D3DFOGMODE get(FogMode fm); - /// return a D3D9 equivalent for a Ogre PolygonMode value - static D3DFILLMODE get(PolygonMode level); - /// return a D3D9 equivalent for a Ogre StencilOperation value - static DWORD get(StencilOperation op, bool invert = false); - /// return a D3D9 state type for Ogre FilterType value - static D3DSAMPLERSTATETYPE get(FilterType ft); - /// return a D3D9 filter option for Ogre FilterType & FilterOption value - static DWORD get(FilterType ft, FilterOptions fo, const D3DCAPS9& devCaps, eD3DTexType texType); - /// return the D3DtexType equivalent of a Ogre tex. type - static eD3DTexType get(TextureType ogreTexType); - /// return the combination of D3DUSAGE values for Ogre buffer usage - static DWORD get(HardwareBuffer::Usage usage); - /// Get lock options - static DWORD get(HardwareBuffer::LockOptions options, HardwareBuffer::Usage usage); - /// Get index type - static D3DFORMAT get(HardwareIndexBuffer::IndexType itype); - /// Get vertex data type - static D3DDECLTYPE get(VertexElementType vType); - /// Get vertex semantic - static D3DDECLUSAGE get(VertexElementSemantic sem); - // Convert matrix to D3D style - static D3DMATRIX makeD3DXMatrix( const Matrix4& mat ); - // Convert matrix from D3D style - static Matrix4 convertD3DXMatrix( const D3DMATRIX& mat ); - - /// utility method, convert D3D9 pixel format to Ogre pixel format - static PixelFormat _getPF(D3DFORMAT d3dPF); - /// utility method, convert Ogre pixel format to D3D9 pixel format - static D3DFORMAT _getPF(PixelFormat ogrePF); - /// utility method, find closest Ogre pixel format that D3D9 can support - static PixelFormat _getClosestSupportedPF(PixelFormat ogrePF); - }; -} -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9MultiRenderTarget.h b/RenderSystems/Direct3D9/include/OgreD3D9MultiRenderTarget.h deleted file mode 100755 index ba79f6c9914..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9MultiRenderTarget.h +++ /dev/null @@ -1,63 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9MULTIRENDERTARGET_H__ -#define __D3D9MULTIRENDERTARGET_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreTexture.h" -#include "OgreRenderTexture.h" -#include "OgreImage.h" -#include "OgreException.h" -#include "OgreD3D9HardwarePixelBuffer.h" - -namespace Ogre { - class _OgreD3D9Export D3D9MultiRenderTarget : public MultiRenderTarget - { - public: - D3D9MultiRenderTarget(const String &name); - ~D3D9MultiRenderTarget(); - - virtual void update(bool swapBuffers); - - virtual void getCustomAttribute( const String& name, void *pData ); - - bool requiresTextureFlipping() const { return false; } - bool attachDepthBuffer( DepthBuffer *depthBuffer ) override; - private: - D3D9HardwarePixelBuffer *mRenderTargets[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; - virtual void bindSurfaceImpl(size_t attachment, RenderTexture *target); - virtual void unbindSurfaceImpl(size_t attachment); - - /** Check surfaces and update RenderTarget extent */ - void checkAndUpdate(); - - RenderTexture *mDepthTarget; - }; -}; - -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9Plugin.h b/RenderSystems/Direct3D9/include/OgreD3D9Plugin.h deleted file mode 100644 index 399b6ecadf7..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9Plugin.h +++ /dev/null @@ -1,63 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9Plugin_H__ -#define __D3D9Plugin_H__ - -#include "OgrePlugin.h" -#include "OgreD3D9RenderSystem.h" - -namespace Ogre -{ - - /** Plugin instance for D3D9 Manager */ - class _OgreD3D9Export D3D9Plugin : public Plugin - { - public: - D3D9Plugin(); - - - /// @copydoc Plugin::getName - const String& getName() const; - - /// @copydoc Plugin::install - void install(); - - /// @copydoc Plugin::initialise - void initialise(); - - /// @copydoc Plugin::shutdown - void shutdown(); - - /// @copydoc Plugin::uninstall - void uninstall(); - protected: - D3D9RenderSystem* mRenderSystem; - }; -} - -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9Prerequisites.h b/RenderSystems/Direct3D9/include/OgreD3D9Prerequisites.h deleted file mode 100644 index ffebe9175df..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9Prerequisites.h +++ /dev/null @@ -1,115 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9PREREQUISITES_H__ -#define __D3D9PREREQUISITES_H__ - -#include "OgrePrerequisites.h" - -#include "Threading/OgreThreadHeaders.h" - -#if OGRE_THREAD_SUPPORT == 1 || OGRE_THREAD_SUPPORT == 2 -# define OGRE_LOCK_RECURSIVE_MUTEX(name) name.lock(); -# define OGRE_UNLOCK_RECURSIVE_MUTEX(name) name.unlock(); -#else -# define OGRE_LOCK_RECURSIVE_MUTEX(name) -# define OGRE_UNLOCK_RECURSIVE_MUTEX(name) -#endif - -#if OGRE_THREAD_SUPPORT == 1 -# define D3D9_DEVICE_ACCESS_LOCK OGRE_LOCK_RECURSIVE_MUTEX(msDeviceAccessMutex); -# define D3D9_DEVICE_ACCESS_UNLOCK OGRE_UNLOCK_RECURSIVE_MUTEX(msDeviceAccessMutex); -# define D3D9_DEVICE_ACCESS_CRITICAL_SECTION OGRE_LOCK_MUTEX(msDeviceAccessMutex); -#else -# define D3D9_DEVICE_ACCESS_LOCK -# define D3D9_DEVICE_ACCESS_UNLOCK -# define D3D9_DEVICE_ACCESS_CRITICAL_SECTION -#endif - -// Define versions for if DirectX is in use (Win32 only) -#define DIRECT3D_VERSION 0x0900 - -// some D3D commonly used macros -#define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } -#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } } -#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } - -// enable extended d3d debug -#if OGRE_DEBUG_MODE -# define D3D_DEBUG_INFO -#endif - -#define WIN32_LEAN_AND_MEAN -#if !defined(NOMINMAX) && defined(_MSC_VER) -# define NOMINMAX // required to stop windows.h messing up std::min -#endif -#include - -namespace Ogre -{ - String DXGetErrorDescription(HRESULT hr); - - // Predefine classes - class D3D9DepthBuffer; - class D3D9RenderSystem; - class D3D9RenderWindow; - class D3D9Texture; - class D3D9TextureManager; - class D3D9Driver; - class D3D9DriverList; - class D3D9VideoMode; - class D3D9VideoModeList; - class D3D9GpuProgram; - class D3D9GpuProgramManager; - class D3D9HardwareBufferManager; - class D3D9HLSLProgramFactory; - class D3D9HLSLProgram; - class D3D9VertexDeclaration; - class D3D9Resource; - - typedef SharedPtr D3D9GpuProgramPtr; - typedef SharedPtr D3D9HLSLProgramPtr; - typedef SharedPtr D3D9TexturePtr; - - //------------------------------------------- - // Windows setttings - //------------------------------------------- -#if (OGRE_PLATFORM == OGRE_PLATFORM_WIN32) && !defined(OGRE_STATIC_LIB) -# ifdef OGRED3DENGINEDLL_EXPORTS -# define _OgreD3D9Export __declspec(dllexport) -# else -# if defined( __MINGW32__ ) -# define _OgreD3D9Export -# else -# define _OgreD3D9Export __declspec(dllimport) -# endif -# endif -#else -# define _OgreD3D9Export -#endif // OGRE_WIN32 -} -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9RenderSystem.h b/RenderSystems/Direct3D9/include/OgreD3D9RenderSystem.h deleted file mode 100644 index 32cc85bd867..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9RenderSystem.h +++ /dev/null @@ -1,393 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9RENDERSYSTEM_H__ -#define __D3D9RENDERSYSTEM_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreString.h" -#include "OgreStringConverter.h" -#include "OgreRenderSystem.h" -#include "OgreRenderSystemCapabilities.h" -#include "OgreD3D9Mappings.h" - -namespace Ogre -{ - /** \addtogroup RenderSystems RenderSystems - * @{ - */ - /** \defgroup Direct3D9 Direct3D9 - * Implementation of DirectX9 as a rendering system. - * @{ - */ -#define MAX_LIGHTS 8 - - class D3D9DriverList; - class D3D9Driver; - class D3D9Device; - class D3D9DeviceManager; - class D3D9ResourceManager; - class D3D9StereoDriverBridge; - - /** - Implementation of DirectX9 as a rendering system. - */ - class _OgreD3D9Export D3D9RenderSystem : public RenderSystem - { - public: - enum MultiheadUseType - { - mutAuto, - mutYes, - mutNo - }; - - private: - /// Direct3D - IDirect3D9* mD3D; - - /// instance - HINSTANCE mhInstance; - - /// List of D3D drivers installed (video cards) - D3D9DriverList* mDriverList; - /// Currently active driver - D3D9Driver* mActiveD3DDriver; - /// NVPerfHUD allowed? - bool mUseNVPerfHUD; - /// Per-stage constant support? (not in main caps since D3D specific & minor) - bool mPerStageConstantSupport; - /// Fast singleton access. - static D3D9RenderSystem* msD3D9RenderSystem; - /// Tells whether to attempt to initialize the system with DirectX 9Ex driver - /// Read more in http://msdn.microsoft.com/en-us/library/windows/desktop/ee890072(v=vs.85).aspx - bool mAllowDirectX9Ex; - /// Tells whether the system is initialized with DirectX 9Ex driver - /// Read more in http://msdn.microsoft.com/en-us/library/windows/desktop/ee890072(v=vs.85).aspx - bool mIsDirectX9Ex; - - bool mEnableFixedPipeline; - - bool mAutoHardwareBufferManagement; - - /// structure holding texture unit settings for every stage - struct sD3DTextureStageDesc - { - /// the type of the texture - D3D9Mappings::eD3DTexType texType; - /// which texCoordIndex to use - size_t coordIndex; - /// type of auto tex. calc. used - TexCoordCalcMethod autoTexCoordType; - /// Frustum, used if the above is projection - const Frustum *frustum; - /// texture - IDirect3DBaseTexture9 *pTex; - } mTexStageDesc[OGRE_MAX_TEXTURE_LAYERS]; - - /// Saved manual colour blends - ColourValue mManualBlendColours[OGRE_MAX_TEXTURE_LAYERS][2]; - - // Array of up to 8 lights, indexed as per API - // Note that a null value indicates a free slot - Light* mLights[MAX_LIGHTS]; - D3D9DriverList* getDirect3DDrivers(); - void refreshD3DSettings(); - void refreshFSAAOptions(); - - void setD3D9Light( size_t index, bool enabled); - - // state management methods, very primitive !!! - HRESULT __SetRenderState(D3DRENDERSTATETYPE state, DWORD value); - HRESULT __SetSamplerState(DWORD sampler, D3DSAMPLERSTATETYPE type, DWORD value); - HRESULT __SetTextureStageState(DWORD stage, D3DTEXTURESTAGESTATETYPE type, DWORD value); - - HRESULT __SetFloatRenderState(D3DRENDERSTATETYPE state, Real value) - { -#if OGRE_DOUBLE_PRECISION == 1 - float temp = static_cast(value); - return __SetRenderState(state, *((LPDWORD)(&temp))); -#else - return __SetRenderState(state, *((LPDWORD)(&value))); -#endif - } - - /// return anisotropy level - DWORD _getCurrentAnisotropy(size_t unit); - /// check if a FSAA is supported - bool _checkMultiSampleQuality(D3DMULTISAMPLE_TYPE type, DWORD *outQuality, D3DFORMAT format, UINT adapterNum, D3DDEVTYPE deviceType, BOOL fullScreen); - - D3D9HardwareBufferManager* mHardwareBufferManager; - D3D9GpuProgramManager* mGpuProgramManager; - D3D9HLSLProgramFactory* mHLSLProgramFactory; - D3D9ResourceManager* mResourceManager; - D3D9DeviceManager* mDeviceManager; - - size_t mLastVertexSourceCount; - - - /// Internal method for populating the capabilities structure - virtual RenderSystemCapabilities* createRenderSystemCapabilities() const; - RenderSystemCapabilities* updateRenderSystemCapabilities(D3D9RenderWindow* renderWindow); - - /** See RenderSystem definition */ - virtual void initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary); - - - void convertVertexShaderCaps(RenderSystemCapabilities* rsc); - void convertPixelShaderCaps(RenderSystemCapabilities* rsc) const; - bool checkVertexTextureFormats(D3D9RenderWindow* renderWindow) const; - void detachRenderTargetImpl(const String& name); - - std::unordered_map mCurrentLights; - /// Saved last view matrix - Matrix4 mViewMatrix; - - D3DMATRIX mDxViewMat, mDxProjMat, mDxWorldMat; - - typedef std::vector D3D9RenderWindowList; - // List of additional windows after the first (swap chains) - D3D9RenderWindowList mRenderWindows; - - /** Mapping of texture format -> DepthStencil. Used as cache by _getDepthStencilFormatFor - */ - typedef std::unordered_map DepthStencilHash; - DepthStencilHash mDepthStencilHash; - - MultiheadUseType mMultiheadUse; - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - D3D9StereoDriverBridge* mStereoDriver; -#endif - - protected: - void setClipPlanesImpl(const PlaneList& clipPlanes); - void setWorldMatrix( const Matrix4 &m ); - void setViewMatrix( const Matrix4 &m ); - void setProjectionMatrix( const Matrix4 &m ); - public: - // constructor - D3D9RenderSystem( HINSTANCE hInstance ); - // destructor - ~D3D9RenderSystem(); - - virtual void initConfigOptions(); - - const GpuProgramParametersPtr& getFixedFunctionParams(TrackVertexColourType tracking, FogMode fog); - void applyFixedFunctionParams(const GpuProgramParametersPtr& params, uint16 variabilityMask); - - // Overridden RenderSystem functions - String validateConfigOptions(); - void _initialise() override; - /// @copydoc RenderSystem::_createRenderWindow - RenderWindow* _createRenderWindow(const String &name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams = 0); - - /// @copydoc RenderSystem::_createDepthBufferFor - DepthBuffer* _createDepthBufferFor( RenderTarget *renderTarget ); - - /** - * This function is meant to add Depth Buffers to the pool that aren't released when the DepthBuffer - * is deleted. This is specially useful to put the Depth Buffer created along with the window's - * back buffer into the pool. All depth buffers introduced with this method go to POOL_DEFAULT - */ - DepthBuffer* _addManualDepthBuffer( IDirect3DDevice9* depthSurfaceDevice, IDirect3DSurface9 *surf ); - - /** - * This function does NOT override RenderSystem::_cleanupDepthBuffers(bool) functionality. - * On multi monitor setups, when a device becomes "inactive" (it has no RenderWindows; like - * when the window was moved from one monitor to another); the Device will be destroyed, - * meaning all it's depth buffers (auto & manual) should be removed from the pool, - * but only selectively removing those created by that D3D9Device. - * @param: - * Creator device to compare against. Shouldn't be null - */ - using RenderSystem::_cleanupDepthBuffers; - void _cleanupDepthBuffers( IDirect3DDevice9 *creator ); - - /** - * This function does NOT override RenderSystem::_cleanupDepthBuffers(bool) functionality. - * Manually created surfaces may be released arbitrarely without being pulled out from the pool - * (specially RenderWindows) this function takes care of that. - * @param manualSurface - * Depth buffer surface to compare against. Shouldn't be null - */ - void _cleanupDepthBuffers( IDirect3DSurface9 *manualSurface ); - - /** - * Set current render target to target, enabling its GL context if needed - */ - void _setRenderTarget(RenderTarget *target); - - /// @copydoc RenderSystem::createMultiRenderTarget - virtual MultiRenderTarget * createMultiRenderTarget(const String & name); - - /// @copydoc RenderSystem::detachRenderTarget - virtual RenderTarget * detachRenderTarget(const String &name); - - String getErrorDescription( long errorNumber ) const; - const String& getName() const; - - // Low-level overridden members - /** - Specific options: - - | Key | Default | Description | - |-----|---------------|---------| - | Allow DirectX9Ex | No | Use Direct3D 9Ex if possible | - | Multi device memory hint | Auto hardware buffers management | Automatically restore hardware buffers on device lost | - | Resource Creation Policy | - | See @ref D3D9ResourceCreationPolicy | - | Fixed Pipeline Enabled | true | Use fixed function units where possible. Disable to test migration to shader-only pipeline | - | Rendering Device | (default) | | - */ - void setConfigOption( const String &name, const String &value ); - void shutdown(); - void setAmbientLight( float r, float g, float b ); - void setShadingType( ShadeOptions so ); - void setLightingEnabled( bool enabled ); - void destroyRenderTarget(const String& name); - void setStencilState(const StencilState& state) override; - void setNormaliseNormals(bool normalise); - - // Low-level overridden members, mainly for internal use - void _useLights(unsigned short limit); - void _setSurfaceTracking( TrackVertexColourType tracking ); - void _setPointSpritesEnabled(bool enabled); - void _setPointParameters(bool attenuationEnabled, Real minSize, Real maxSize); - void _setTexture(size_t unit, bool enabled, const TexturePtr& texPtr); - void _setSampler(size_t unit, Sampler& sampler); - void _setTextureCoordSet( size_t unit, size_t index ); - void _setTextureCoordCalculation(size_t unit, TexCoordCalcMethod m, - const Frustum* frustum = 0); - void _setTextureBlendMode( size_t unit, const LayerBlendModeEx& bm ); - void _setTextureMatrix( size_t unit, const Matrix4 &xform ); - void _setAlphaRejectSettings( CompareFunction func, unsigned char value, bool alphaToCoverage ); - void _setViewport( Viewport *vp ); - void _beginFrame(); - void _endFrame(); - void _setCullingMode( CullingMode mode ); - void _setDepthBufferParams( bool depthTest = true, bool depthWrite = true, CompareFunction depthFunction = CMPF_LESS_EQUAL ); - void _setDepthBufferCheckEnabled( bool enabled = true ); - void setColourBlendState(const ColourBlendState& state); - void _setDepthBufferWriteEnabled(bool enabled = true); - void _setDepthBufferFunction( CompareFunction func = CMPF_LESS_EQUAL ); - void _setDepthBias(float constantBias, float slopeScaleBias); - void _setFog( FogMode mode); - void _convertProjectionMatrix(const Matrix4& matrix, - Matrix4& dest, bool forGpuProgram = false); - void _setPolygonMode(PolygonMode level); - void setVertexDeclaration(VertexDeclaration* decl); - void setVertexBufferBinding(VertexBufferBinding* binding, int numberOfInstances, bool indexesUsed); - void _render(const RenderOperation& op); - - void bindGpuProgram(GpuProgram* prg); - - void unbindGpuProgram(GpuProgramType gptype); - - void bindGpuProgramParameters(GpuProgramType gptype, - const GpuProgramParametersPtr& params, uint16 variabilityMask); - - void setScissorTest(bool enabled, const Rect& rect = Rect()); - void clearFrameBuffer(unsigned int buffers, - const ColourValue& colour = ColourValue::Black, - float depth = 1.0f, unsigned short stencil = 0); - void setClipPlane (ushort index, Real A, Real B, Real C, Real D); - void enableClipPlane (ushort index, bool enable); - HardwareOcclusionQuery* createHardwareOcclusionQuery(); - Real getHorizontalTexelOffset(); - Real getVerticalTexelOffset(); - Real getMinimumDepthInputValue(); - Real getMaximumDepthInputValue(); - - bool IsActiveDeviceLost(); - - /// Tells whether the system is initialized with DirectX 9Ex driver - /// Read more in http://msdn.microsoft.com/en-us/library/windows/desktop/ee890072(v=vs.85).aspx - static bool isDirectX9Ex() { return msD3D9RenderSystem->mIsDirectX9Ex; } - - static D3D9ResourceManager* getResourceManager(); - static D3D9DeviceManager* getDeviceManager(); - static IDirect3D9* getDirect3D9(); - static UINT getResourceCreationDeviceCount(); - static IDirect3DDevice9* getResourceCreationDevice(UINT index); - static IDirect3DDevice9* getActiveD3D9Device(); - static IDirect3DDevice9* getActiveD3D9DeviceIfExists(); - - uint32 getAdapterNumber(); - - /** Check which depthStencil formats can be used with a certain pixel format, - and return the best suited. - */ - D3DFORMAT _getDepthStencilFormatFor(D3DFORMAT fmt); - - /** Check whether or not filtering is supported for the precise texture format requested - with the given usage options. - */ - bool _checkTextureFilteringSupported(TextureType ttype, PixelFormat format, int usage); - - /// Take in some requested FSAA settings and output supported D3D settings - void determineFSAASettings(IDirect3DDevice9* d3d9Device, size_t fsaa, const String& fsaaHint, D3DFORMAT d3dPixelFormat, - bool fullScreen, D3DMULTISAMPLE_TYPE *outMultisampleType, DWORD *outMultisampleQuality); - - /// @copydoc RenderSystem::beginProfileEvent - virtual void beginProfileEvent( const String &eventName ); - - /// @copydoc RenderSystem::endProfileEvent - virtual void endProfileEvent( void ); - - /// @copydoc RenderSystem::markProfileEvent - virtual void markProfileEvent( const String &eventName ); - - /// Fires a device related event - void fireDeviceEvent( D3D9Device* device, const String & name ); - - /// Returns how multihead should be activated - MultiheadUseType getMultiheadUse() const { return mMultiheadUse; } - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - /// @copydoc RenderSystem::setDrawBuffer - virtual bool setDrawBuffer(ColourBufferType colourBuffer); - - /// Creates a bridge to the Direct3D stereo driver implementation - void createStereoDriver(const NameValuePairList* miscParams); -#endif - - protected: - /// Notify when a device has been lost. - void notifyOnDeviceLost(D3D9Device* device); - - /// Notify when a device has been reset. - void notifyOnDeviceReset(D3D9Device* device); - - private: - friend class D3D9Device; - friend class D3D9DeviceManager; - }; - /** @} */ - /** @} */ -} -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9RenderWindow.h b/RenderSystems/Direct3D9/include/OgreD3D9RenderWindow.h deleted file mode 100644 index 74fc6af77d1..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9RenderWindow.h +++ /dev/null @@ -1,147 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9RENDERWINDOW_H__ -#define __D3D9RENDERWINDOW_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreRenderWindow.h" -#include "OgreD3D9Device.h" - -namespace Ogre -{ - class _OgreD3D9Export D3D9RenderWindow : public RenderWindow - { - public: - /** Constructor. - @param instance The application instance - */ - D3D9RenderWindow (HINSTANCE instance); - ~D3D9RenderWindow (); - - void create (const String& name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams); - void setFullscreen (bool fullScreen, unsigned int width, unsigned int height); - void destroy (void); - bool isActive () const; - bool isVisible () const; - bool isVSync () const { return mVSync; } - bool isAA () const { return mFSAA != 0; } - bool isHidden () const { return mHidden; } - void setHidden (bool hidden); - void setVSyncEnabled (bool vsync); - bool isVSyncEnabled () const; - void setVSyncInterval (unsigned int interval); - void reposition (int left, int top); - void resize (unsigned int width, unsigned int height); - void swapBuffers (); - HWND getWindowHandle () const { return mHWnd; } - IDirect3DDevice9* getD3D9Device (); - D3D9Device* getDevice (); - void setDevice (D3D9Device* device); - - void getCustomAttribute (const String& name, void* pData); - - /** Overridden - see RenderTarget. - */ - PixelFormat suggestPixelFormat() const override; - void copyContentsToMemory (const Box& src, const PixelBox &dst, FrameBuffer buffer); - bool requiresTextureFlipping () const { return false; } - - // Method for dealing with resize / move & 3d library - void windowMovedOrResized (); - - /// Build the presentation parameters used with this window - void buildPresentParameters (D3DPRESENT_PARAMETERS* presentParams); - - - /// @copydoc RenderTarget::_beginUpdate - void _beginUpdate(); - - /// @copydoc RenderTarget::_updateViewport(Viewport* viewport, bool updateStatistics) - void _updateViewport(Viewport* viewport, bool updateStatistics = true); - - /// @copydoc RenderTarget::_endUpdate - void _endUpdate(); - - /// Accessor for render surface - IDirect3DSurface9* getRenderSurface(); - - /// Are we in the middle of switching between fullscreen and windowed - bool _getSwitchingFullscreen() const; - - /// Indicate that fullscreen / windowed switching has finished - void _finishSwitchingFullscreen(); - - /// Returns true if this window use depth buffer. - bool isDepthBuffered() const; - - /// Returns true if this window should use NV Perf HUD adapter. - bool isNvPerfHUDEnable() const; - - /** Validate the device for this window. */ - bool _validateDevice(); - - void adjustWindow(unsigned int clientWidth, unsigned int clientHeight, - unsigned int* winWidth, unsigned int* winHeight); - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - /** Validate the type of stereo that is enabled for this window.*/ - void _validateStereo(); -#endif - - protected: - /** Update the window rect. */ - void updateWindowRect(); - - /** Return the target window style depending on the fullscreen parameter. */ - DWORD getWindowStyle(bool fullScreen) const { if (fullScreen) return mFullscreenWinStyle; return mWindowedWinStyle; } - - // Overridden see RenderTarget - virtual void updateStats(void); - - protected: - HINSTANCE mInstance; // Process instance - D3D9Device* mDevice; // D3D9 device wrapper class. - bool mDeviceValid; // Device was validation succeeded. - HWND mHWnd; // Win32 Window handle - bool mIsExternal; // window not created by Ogre - bool mHidden; // True if this is hidden render window. - bool mSwitchingFullscreen; // Are we switching from fullscreen to windowed or vice versa - D3DMULTISAMPLE_TYPE mFSAAType; // AA type. - DWORD mFSAAQuality; // AA quality. - UINT mDisplayFrequency; // Display frequency. - bool mVSync; // Use vertical sync or not. - bool mUseNVPerfHUD; // Use NV Perf HUD. - DWORD mWindowedWinStyle; // Windowed mode window style flags. - DWORD mFullscreenWinStyle; // Fullscreen mode window style flags. - unsigned int mDesiredWidth; // Desired width after resizing - unsigned int mDesiredHeight; // Desired height after resizing - uint32 mColourDepth; - }; -} -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9Resource.h b/RenderSystems/Direct3D9/include/OgreD3D9Resource.h deleted file mode 100755 index 143becdb472..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9Resource.h +++ /dev/null @@ -1,77 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9Resource_H__ -#define __D3D9Resource_H__ - -#include "OgreD3D9Prerequisites.h" -#include "Threading/OgreThreadHeaders.h" - -namespace Ogre { - - /** Represents a Direct3D rendering resource. - Provide unified interface to - handle various device states. - */ - class _OgreD3D9Export D3D9Resource - { - - // Interface. - public: - - // Called immediately after the Direct3D device has been created. - virtual void notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device) {} - - // Called before the Direct3D device is going to be destroyed. - virtual void notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device) {} - - // Called immediately after the Direct3D device has entered a lost state. - // This is the place to release non-managed resources. - virtual void notifyOnDeviceLost(IDirect3DDevice9* d3d9Device) {} - - // Called immediately after the Direct3D device has been reset. - // This is the place to create non-managed resources. - virtual void notifyOnDeviceReset(IDirect3DDevice9* d3d9Device) {} - - // Called when device state is changing. Access to any device should be locked. - // Relevant for multi thread application. - static void lockDeviceAccess(); - - // Called when device state change completed. Access to any device is allowed. - // Relevant for multi thread application. - static void unlockDeviceAccess(); - - - public: - D3D9Resource (); - virtual ~D3D9Resource (); - - protected: - OGRE_STATIC_MUTEX(msDeviceAccessMutex); - }; -} -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9ResourceManager.h b/RenderSystems/Direct3D9/include/OgreD3D9ResourceManager.h deleted file mode 100755 index b88e64ddd94..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9ResourceManager.h +++ /dev/null @@ -1,113 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9ResourceManager_H__ -#define __D3D9ResourceManager_H__ - -#include "OgreD3D9Prerequisites.h" - -namespace Ogre { - - enum D3D9ResourceCreationPolicy - { - /// Creates the rendering resource on the current active device that needs it. - /// This policy should be used when video memory consumption should be minimized but - /// it might cause some performance issues when using loader resource thread since - /// a resource that was not created on specified device will be created on demand during - /// the rendering process and might cause the FPS to drop down. - RCP_CREATE_ON_ACTIVE_DEVICE, - - /// Create the rendering resource on every existing device. - /// This policy should be used when working intensively with a background loader thread. - /// In that case when multiple devices exist, the resource will be created on each device - /// and will be ready to use in the rendering thread. - /// The draw back can be some video memory waste in case that each device render different - /// scene and doesn't really need all the resources. - RCP_CREATE_ON_ALL_DEVICES - }; - - class _OgreD3D9Export D3D9ResourceManager : public ResourceAlloc - { - - // Interface. - public: - - // Called immediately after the Direct3D device has been created. - void notifyOnDeviceCreate (IDirect3DDevice9* d3d9Device); - - // Called before the Direct3D device is going to be destroyed. - void notifyOnDeviceDestroy (IDirect3DDevice9* d3d9Device); - - // Called immediately after the Direct3D device has entered a lost state. - void notifyOnDeviceLost (IDirect3DDevice9* d3d9Device); - - // Called immediately after the Direct3D device has been reset. - void notifyOnDeviceReset (IDirect3DDevice9* d3d9Device); - - // Called when device state is changing. Access to any device should be locked. - // Relevant for multi thread application. - void lockDeviceAccess (); - - // Called when device state change completed. Access to any device is allowed. - // Relevant for multi thread application. - void unlockDeviceAccess (); - - D3D9ResourceManager (); - ~D3D9ResourceManager (); - - void setCreationPolicy (D3D9ResourceCreationPolicy creationPolicy); - D3D9ResourceCreationPolicy getCreationPolicy () const; - - // Friends. - protected: - friend class D3D9Resource; - - // Types. - protected: - typedef std::set ResourceContainer; - typedef ResourceContainer::iterator ResourceContainerIterator; - - // Protected methods. - protected: - - // Called when new resource created. - void _notifyResourceCreated (D3D9Resource* pResource); - - // Called when resource is about to be destroyed. - void _notifyResourceDestroyed (D3D9Resource* pResource); - - - // Attributes. - protected: - OGRE_MUTEX(mResourcesMutex); - ResourceContainer mResources; - D3D9ResourceCreationPolicy mResourceCreationPolicy; - long mDeviceAccessLockCount; - }; -} - -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9StereoDriverAMD.h b/RenderSystems/Direct3D9/include/OgreD3D9StereoDriverAMD.h deleted file mode 100644 index 08c7560f637..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9StereoDriverAMD.h +++ /dev/null @@ -1,83 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreD3D9Prerequisites.h" - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 -#ifndef __D3D9StereoDriverAMD_H__ -#define __D3D9StereoDriverAMD_H__ - -#include "OgreD3D9RenderSystem.h" -#include "OgreD3D9StereoDriverImpl.h" -#include "OgreRenderTargetListener.h" -#include "AtiDx9Stereo.h" - -namespace Ogre { - - class D3D9RenderWindow; - - /** Virtual interface of the stereo driver*/ - class _OgreD3D9Export D3D9StereoDriverAMD : public D3D9StereoDriverImpl, public D3D9RenderSystem::Listener, public RenderTargetListener - { - // Interface - public: - D3D9StereoDriverAMD(); - virtual ~D3D9StereoDriverAMD(); - virtual bool addRenderWindow(D3D9RenderWindow* renderWindow); - virtual bool removeRenderWindow(const String& renderWindowName); - virtual bool isStereoEnabled(const String& renderWindowName); - virtual bool setDrawBuffer(ColourBufferType colourBuffer); - - protected: - // D3D9RenderSystem and RenderTarget Listener Events - virtual void eventOccurred(const String& eventName, const NameValuePairList* parameters = 0); - void deviceCreatedEvent(const NameValuePairList* parameters); - void deviceLostEvent(const NameValuePairList* parameters); - void afterDeviceResetEvent(const NameValuePairList* parameters); - void beforeDevicePresentEvent(const NameValuePairList* parameters); - void postViewportUpdate(const RenderTargetViewportEvent& evt); - - bool getPresentParamsAndVerifyStereoSettings(); - bool sendStereoCommand(ATIDX9STEREOCOMMAND stereoCommand, BYTE* outBuffer, DWORD outBufferSize, BYTE* inBuffer, DWORD inBufferSize); - void releaseResources(); - - typedef std::map RenderWindowMap; - RenderWindowMap mRenderWindowMap; - - bool mStereoEnabled; - DWORD mLineOffset; - IDirect3DDevice9* mDevice; - IDirect3DSurface9* mDriverComSurface; - IDirect3DSurface9* mStereoBuffer; - IDirect3DSurface9* mLeftBuffer; - IDirect3DSurface9* mRightBuffer; - D3DPRESENT_PARAMETERS mSwapChainPresentParameters; - }; -} -#endif -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9StereoDriverBridge.h b/RenderSystems/Direct3D9/include/OgreD3D9StereoDriverBridge.h deleted file mode 100644 index f98deefef27..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9StereoDriverBridge.h +++ /dev/null @@ -1,65 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreD3D9Prerequisites.h" - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 -#ifndef __D3D9StereoDriverBridge_H__ -#define __D3D9StereoDriverBridge_H__ - -#include "OgreCommon.h" -#include "OgreSingleton.h" - -namespace Ogre { - - class D3D9StereoDriverImpl; - typedef bool StereoModeType; - - /** Bridge interface from the render system to the stereo driver. Loads the - correct driver and forwards the methods to the stereo driver implementation.*/ - class _OgreD3D9Export D3D9StereoDriverBridge : public Singleton, public StereoDriverAlloc - { - public: - D3D9StereoDriverBridge(StereoModeType stereoMode); - virtual ~D3D9StereoDriverBridge(); - static D3D9StereoDriverBridge& getSingleton(void); - static D3D9StereoDriverBridge* getSingletonPtr(void); - StereoModeType getStereoMode() const; - bool addRenderWindow(D3D9RenderWindow* renderWindow) const; - bool removeRenderWindow(const String& renderWindowName) const; - bool isStereoEnabled(const String& renderWindowName) const; - bool setDrawBuffer(const ColourBufferType colourBuffer) const; - - protected: - bool mIsNvapiInitialized; - D3D9StereoDriverImpl* mPimpl; - StereoModeType mStereoMode; - }; -} -#endif -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9StereoDriverImpl.h b/RenderSystems/Direct3D9/include/OgreD3D9StereoDriverImpl.h deleted file mode 100644 index 14487969dbf..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9StereoDriverImpl.h +++ /dev/null @@ -1,52 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreD3D9Prerequisites.h" - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 -#ifndef __D3D9StereoDriverImpl_H__ -#define __D3D9StereoDriverImpl_H__ - -#include "OgreCommon.h" - -namespace Ogre { - - /** Virtual interface of the stereo driver */ - class _OgreD3D9Export D3D9StereoDriverImpl : public ResourceAlloc - { - public: - D3D9StereoDriverImpl() {} - virtual ~D3D9StereoDriverImpl() {} - virtual bool addRenderWindow(D3D9RenderWindow* renderWindow) = 0; - virtual bool removeRenderWindow(const String& renderWindowName) = 0; - virtual bool isStereoEnabled(const String& renderWindowName) = 0; - virtual bool setDrawBuffer(ColourBufferType colourBuffer) = 0; - }; -} -#endif -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9StereoDriverNVIDIA.h b/RenderSystems/Direct3D9/include/OgreD3D9StereoDriverNVIDIA.h deleted file mode 100644 index eee4a3b63d6..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9StereoDriverNVIDIA.h +++ /dev/null @@ -1,70 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreD3D9Prerequisites.h" - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 -#ifndef __D3D9StereoDriverNVIDIA_H__ -#define __D3D9StereoDriverNVIDIA_H__ - -#include "OgreD3D9StereoDriverImpl.h" -#include "nvapi.h" - -namespace Ogre { - - class D3D9RenderWindow; - - /** Interface of the NVIDIA stereo driver */ - class _OgreD3D9Export D3D9StereoDriverNVIDIA : public D3D9StereoDriverImpl - { - // Interface - public: - D3D9StereoDriverNVIDIA(); - virtual ~D3D9StereoDriverNVIDIA(); - virtual bool addRenderWindow(D3D9RenderWindow* renderWindow); - virtual bool removeRenderWindow(const String& renderWindowName); - virtual bool isStereoEnabled(const String& renderWindowName); - virtual bool setDrawBuffer(ColourBufferType colourBuffer); - - protected: - bool logErrorMessage(NvAPI_Status nvStatus); - - typedef struct OgreStereoHandle - { - D3D9RenderWindow* renderWindow; - StereoHandle nvapiStereoHandle; - NvU8 isStereoOn; - }; - - typedef std::map StereoHandleMap; - StereoHandleMap mStereoMap; - NvU8 mStereoEnabled; - }; -} -#endif -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9Texture.h b/RenderSystems/Direct3D9/include/OgreD3D9Texture.h deleted file mode 100644 index f15d026dcea..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9Texture.h +++ /dev/null @@ -1,190 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9TEXTURE_H__ -#define __D3D9TEXTURE_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreTexture.h" -#include "OgreRenderTexture.h" -#include "OgreImage.h" -#include "OgreException.h" -#include "OgreD3D9HardwarePixelBuffer.h" -#include "OgreD3D9Resource.h" - -namespace Ogre { - class _OgreD3D9Export D3D9Texture : public Texture, public D3D9Resource - { - protected: - - struct TextureResources - { - /// 1D/2D normal texture pointer - IDirect3DTexture9* pNormTex; - /// cubic texture pointer - IDirect3DCubeTexture9* pCubeTex; - /// Volume texture - IDirect3DVolumeTexture9* pVolumeTex; - /// actual texture pointer - IDirect3DBaseTexture9* pBaseTex; - /// Optional FSAA surface - IDirect3DSurface9* pFSAASurface; - }; - - typedef std::map DeviceToTextureResourcesMap; - typedef DeviceToTextureResourcesMap::iterator DeviceToTextureResourcesIterator; - - /// Map between device to texture resources. - DeviceToTextureResourcesMap mMapDeviceToTextureResources; - - /// The memory pool being used - D3DPOOL mD3DPool; - // Dynamic textures? - bool mDynamicTextures; - - /// Is hardware gamma supported (read)? - bool mHwGammaReadSupported; - /// Is hardware gamma supported (write)? - bool mHwGammaWriteSupported; - D3DMULTISAMPLE_TYPE mFSAAType; - DWORD mFSAAQuality; - - /// internal method, create a blank normal 1D/2D texture - void _createNormTex(IDirect3DDevice9* d3d9Device); - /// internal method, create a blank cube texture - void _createCubeTex(IDirect3DDevice9* d3d9Device); - /// internal method, create a blank cube texture - void _createVolumeTex(IDirect3DDevice9* d3d9Device); - - /// @copydoc Resource::calculateSize - size_t calculateSize(void) const; - /// @copydoc Texture::createInternalResourcesImpl - void createInternalResourcesImpl(void); - /// Creates this texture resources on the specified device. - void createInternalResourcesImpl(IDirect3DDevice9* d3d9Device); - /// free internal resources - void freeInternalResourcesImpl(void); - /// internal method, set Texture class final texture protected attributes - void _setFinalAttributes(IDirect3DDevice9* d3d9Device, TextureResources* textureResources, - unsigned long width, unsigned long height, unsigned long depth, PixelFormat format); - /// internal method, return the best by hardware supported filter method - D3DTEXTUREFILTERTYPE _getBestFilterMethod(IDirect3DDevice9* d3d9Device); - /// internal method, return true if the device/texture combination can use dynamic textures - bool _canUseDynamicTextures(IDirect3DDevice9* d3d9Device, DWORD srcUsage, D3DRESOURCETYPE srcType, D3DFORMAT srcFormat); - /// internal method, return true if the device/texture combination can auto gen. mip maps - bool _canAutoGenMipmaps(IDirect3DDevice9* d3d9Device, DWORD srcUsage, D3DRESOURCETYPE srcType, D3DFORMAT srcFormat); - /// internal method, return true if the device/texture combination can use hardware gamma - bool _canUseHardwareGammaCorrection(IDirect3DDevice9* d3d9Device, DWORD srcUsage, D3DRESOURCETYPE srcType, D3DFORMAT srcFormat, bool forwriting); - - /// internal method, create D3D9HardwarePixelBuffers for every face and - /// mipmap level. This method must be called after the D3D texture object was created - void _createSurfaceList(IDirect3DDevice9* d3d9Device, TextureResources* textureResources); - - /// overridden from Resource - void loadImpl(); - - /// gets the texture resources attached to the given device. - TextureResources* getTextureResources(IDirect3DDevice9* d3d9Device); - - /// allocates new texture resources structure attached to the given device. - TextureResources* allocateTextureResources(IDirect3DDevice9* d3d9Device); - - /// creates this texture resources according to the current settings. - void createTextureResources(IDirect3DDevice9* d3d9Device); - - /// frees the given texture resources. - void freeTextureResources(IDirect3DDevice9* d3d9Device, TextureResources* textureResources); - - void determinePool(); - - friend class D3D9HardwarePixelBuffer; - public: - /// constructor - D3D9Texture(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader); - /// destructor - ~D3D9Texture(); - - /// overridden from Texture - void copyToTexture( TexturePtr& target ); - - const HardwarePixelBufferSharedPtr& getBuffer(size_t face, size_t mipmap); - - /// retrieves a pointer to the actual texture - IDirect3DBaseTexture9 *getTexture(); - /// retrieves a pointer to the normal 1D/2D texture - IDirect3DTexture9 *getNormTexture(); - /// retrieves a pointer to the cube texture - IDirect3DCubeTexture9 *getCubeTexture(); - - /** Indicates whether the hardware gamma is actually enabled and supported. - - Because hardware gamma might not actually be supported, we need to - ignore it sometimes. Because D3D doesn't encode sRGB in the format but - as a sampler state, and we don't want to change the original requested - hardware gamma flag (e.g. serialisation) we need another indicator. - */ - bool isHardwareGammaReadToBeUsed() const { return mHwGamma && mHwGammaReadSupported; } - - /// Will this texture need to be in the default pool? - bool useDefaultPool(); - - // Called immediately after the Direct3D device has been created. - virtual void notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device); - - // Called before the Direct3D device is going to be destroyed. - virtual void notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device); - - // Called immediately after the Direct3D device has entered a lost state. - virtual void notifyOnDeviceLost(IDirect3DDevice9* d3d9Device); - - // Called immediately after the Direct3D device has been reset - virtual void notifyOnDeviceReset(IDirect3DDevice9* d3d9Device); - }; - - /// RenderTexture implementation for D3D9 - class _OgreD3D9Export D3D9RenderTexture : public RenderTexture - { - public: - D3D9RenderTexture(const String &name, D3D9HardwarePixelBuffer *buffer, bool writeGamma, uint fsaa); - ~D3D9RenderTexture() {} - - virtual void update(bool swap); - - virtual void getCustomAttribute( const String& name, void *pData ); - - bool requiresTextureFlipping() const { return false; } - - /// Override needed to deal with FSAA - void swapBuffers(); - - void _setDepthBuffer(DepthBuffer *depthBuffer) { mDepthBuffer = depthBuffer; } - }; - -} - -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9TextureManager.h b/RenderSystems/Direct3D9/include/OgreD3D9TextureManager.h deleted file mode 100644 index 2d478ab1025..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9TextureManager.h +++ /dev/null @@ -1,57 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9TEXTUREMANAGER_H__ -#define __D3D9TEXTUREMANAGER_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreTextureManager.h" - -namespace Ogre -{ - class _OgreD3D9Export D3D9TextureManager : public TextureManager - { - protected: - /// @copydoc ResourceManager::createImpl - Resource* createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams); - - public: - D3D9TextureManager(); - ~D3D9TextureManager(); - - - /// @copydoc TextureManager::getNativeFormat - PixelFormat getNativeFormat(TextureType ttype, PixelFormat format, int usage); - - /// @copydoc TextureManager::isHardwareFilteringSupported - bool isHardwareFilteringSupported(TextureType ttype, PixelFormat format, int usage, - bool preciseFormatOnly = false); - }; -} -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9VertexDeclaration.h b/RenderSystems/Direct3D9/include/OgreD3D9VertexDeclaration.h deleted file mode 100644 index 0a4e70c99c1..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9VertexDeclaration.h +++ /dev/null @@ -1,67 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9VERTEXDECLARATION_H__ -#define __D3D9VERTEXDECLARATION_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreD3D9Resource.h" - -namespace Ogre { - - /** Specialisation of VertexDeclaration for D3D9 */ - class _OgreD3D9Export D3D9VertexDeclaration : public VertexDeclaration, public D3D9Resource - { - - public: - D3D9VertexDeclaration(); - ~D3D9VertexDeclaration(); - - // Called immediately after the Direct3D device has been created. - virtual void notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device); - - // Called before the Direct3D device is going to be destroyed. - virtual void notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device); - - /** Gets the D3D9-specific vertex declaration. */ - IDirect3DVertexDeclaration9* getD3DVertexDeclaration(); - - protected: - void releaseDeclaration(); - void convertElement( const VertexElement & element, D3DVERTEXELEMENT9 & dxElement ); - void notifyChanged(); - protected: - typedef std::map DeviceToDeclarationMap; - typedef DeviceToDeclarationMap::iterator DeviceToDeclarationIterator; - - DeviceToDeclarationMap mMapDeviceToDeclaration; - }; - -} - -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9VideoMode.h b/RenderSystems/Direct3D9/include/OgreD3D9VideoMode.h deleted file mode 100644 index e2660c96224..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9VideoMode.h +++ /dev/null @@ -1,62 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9VIDEOMODE_H__ -#define __D3D9VIDEOMODE_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreString.h" - -namespace Ogre -{ - static unsigned int modeCount = 0; - - class _OgreD3D9Export D3D9VideoMode - { - private: - D3DDISPLAYMODE mDisplayMode; - unsigned int modeNumber; - - public: - D3D9VideoMode() { modeNumber = ++modeCount; ZeroMemory( &mDisplayMode, sizeof(D3DDISPLAYMODE) ); } - D3D9VideoMode( const D3D9VideoMode &ob ) { modeNumber = ++modeCount; mDisplayMode = ob.mDisplayMode; } - D3D9VideoMode( D3DDISPLAYMODE d3ddm ) { modeNumber = ++modeCount; mDisplayMode = d3ddm; } - ~D3D9VideoMode() - { - modeCount--; - } - - unsigned int getWidth() const { return mDisplayMode.Width; } - unsigned int getHeight() const { return mDisplayMode.Height; } - D3DFORMAT getFormat() const { return mDisplayMode.Format; } - unsigned int getRefreshRate() const { return mDisplayMode.RefreshRate; } - D3DDISPLAYMODE getDisplayMode() const { return mDisplayMode; } - void increaseRefreshRate(unsigned int rr) { mDisplayMode.RefreshRate = rr; } - String getDescription() const; - }; -} -#endif diff --git a/RenderSystems/Direct3D9/include/OgreD3D9VideoModeList.h b/RenderSystems/Direct3D9/include/OgreD3D9VideoModeList.h deleted file mode 100644 index f99651d88b7..00000000000 --- a/RenderSystems/Direct3D9/include/OgreD3D9VideoModeList.h +++ /dev/null @@ -1,55 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __D3D9VIDEOMODELIST_H__ -#define __D3D9VIDEOMODELIST_H__ - -#include "OgreD3D9Prerequisites.h" -#include "OgreD3D9Driver.h" -#include "OgreD3D9VideoMode.h" - -namespace Ogre -{ - class _OgreD3D9Export D3D9VideoModeList : public RenderSysAlloc - { - private: - D3D9Driver* mDriver; - std::vector mModeList; - - public: - D3D9VideoModeList( D3D9Driver* pDriver ); - ~D3D9VideoModeList(); - - BOOL enumerate(); - - D3D9VideoMode* item( size_t index ); - size_t count(); - - D3D9VideoMode* item( const String &name ); - }; -} -#endif diff --git a/RenderSystems/Direct3D9/src/OgreD3D9DepthBuffer.cpp b/RenderSystems/Direct3D9/src/OgreD3D9DepthBuffer.cpp deleted file mode 100644 index 0dbe56905a3..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9DepthBuffer.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9DepthBuffer.h" -#include "OgreD3D9RenderSystem.h" -#include "OgreRenderTarget.h" - -namespace Ogre -{ - D3D9DepthBuffer::D3D9DepthBuffer( uint16 poolId, D3D9RenderSystem *renderSystem, - IDirect3DDevice9 *creator, IDirect3DSurface9 *depthBufferSurf, - D3DFORMAT fmt, uint32 width, uint32 height, - uint32 fsaa, uint32 multiSampleQuality, bool isManual ) : - DepthBuffer( poolId, width, height, fsaa, isManual ), - mDepthBuffer( depthBufferSurf ), - mCreator( creator ), - mMultiSampleQuality( multiSampleQuality ), - mD3DFormat( fmt ), - mRenderSystem( renderSystem ) - { - } - - D3D9DepthBuffer::~D3D9DepthBuffer() - { - if( !mManual ) - mDepthBuffer->Release(); - mDepthBuffer = 0; - - mCreator = 0; - } - //--------------------------------------------------------------------- - bool D3D9DepthBuffer::isCompatible( RenderTarget *renderTarget ) const - { - IDirect3DSurface9* pBack[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; - memset( pBack, 0, sizeof(pBack) ); - renderTarget->getCustomAttribute( "DDBACKBUFFER", &pBack ); - if( !pBack[0] ) - return false; - - D3DSURFACE_DESC srfDesc; - if( SUCCEEDED(pBack[0]->GetDesc(&srfDesc)) ) - { - //RenderSystem will determine if bitdepths match (i.e. 32 bit RT don't like 16 bit Depth) - //This is the same function used to create them. Note results are usually cached so this should - //be quick - D3DFORMAT fmt = mRenderSystem->_getDepthStencilFormatFor( srfDesc.Format ); - IDirect3DDevice9 *activeDevice = mRenderSystem->getActiveD3D9Device(); - - if( mCreator == activeDevice && - fmt == mD3DFormat && - mFsaa == srfDesc.MultiSampleType && - mMultiSampleQuality == srfDesc.MultiSampleQuality && - this->getWidth() >= renderTarget->getWidth() && - this->getHeight() >= renderTarget->getHeight() ) - { - return true; - } - } - - return false; - } - //--------------------------------------------------------------------- - IDirect3DDevice9* D3D9DepthBuffer::getDeviceCreator() const - { - return mCreator; - } - //--------------------------------------------------------------------- - IDirect3DSurface9* D3D9DepthBuffer::getDepthBufferSurface() const - { - return mDepthBuffer; - } -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9Device.cpp b/RenderSystems/Direct3D9/src/OgreD3D9Device.cpp deleted file mode 100644 index 1fe4c0513e5..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9Device.cpp +++ /dev/null @@ -1,1569 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9Device.h" -#include "OgreD3D9DeviceManager.h" -#include "OgreD3D9Driver.h" -#include "OgreD3D9RenderSystem.h" -#include "OgreD3D9ResourceManager.h" -#include "OgreD3D9RenderWindow.h" -#include "OgreRoot.h" -#include "OgreLogManager.h" -#include "OgreHardwareBufferManager.h" - -namespace Ogre -{ - HWND D3D9Device::msSharedFocusWindow = NULL; - - //--------------------------------------------------------------------- - D3D9Device::D3D9Device(D3D9DeviceManager* deviceManager, - UINT adapterNumber, - HMONITOR hMonitor, - D3DDEVTYPE devType, - DWORD behaviorFlags) - { - mDeviceManager = deviceManager; - mDevice = NULL; - mAdapterNumber = adapterNumber; - mMonitor = hMonitor; - mDeviceType = devType; - mFocusWindow = NULL; - mBehaviorFlags = behaviorFlags; - mD3D9DeviceCapsValid = false; - mDeviceLost = false; - mPresentationParamsCount = 0; - mPresentationParams = NULL; - memset(&mD3D9DeviceCaps, 0, sizeof(mD3D9DeviceCaps)); - memset(&mCreationParams, 0, sizeof(mCreationParams)); - memset(&mPreviousPresentStats, 0, sizeof(mPreviousPresentStats)); - mPreviousPresentStatsIsValid = false; - mVBlankMissCount = 0; - } - - //--------------------------------------------------------------------- - D3D9Device::~D3D9Device() - { - - } - - //--------------------------------------------------------------------- - D3D9Device::RenderWindowToResourcesIterator D3D9Device::getRenderWindowIterator(D3D9RenderWindow* renderWindow) - { - RenderWindowToResourcesIterator it = mMapRenderWindowToResources.find(renderWindow); - - if (it == mMapRenderWindowToResources.end()) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Render window was not attached to this device !!", - "D3D9Device::getRenderWindowIterator" ); - } - - return it; - } - - - //--------------------------------------------------------------------- - void D3D9Device::attachRenderWindow(D3D9RenderWindow* renderWindow) - { - RenderWindowToResourcesIterator it = mMapRenderWindowToResources.find(renderWindow); - - if (it == mMapRenderWindowToResources.end()) - { - RenderWindowResources* renderWindowResources = OGRE_NEW_T(RenderWindowResources, MEMCATEGORY_RENDERSYS); - - memset(renderWindowResources, 0, sizeof(RenderWindowResources)); - renderWindowResources->adapterOrdinalInGroupIndex = 0; - renderWindowResources->acquired = false; - mMapRenderWindowToResources[renderWindow] = renderWindowResources; - } - updateRenderWindowsIndices(); - } - - //--------------------------------------------------------------------- - void D3D9Device::detachRenderWindow(D3D9RenderWindow* renderWindow) - { - RenderWindowToResourcesIterator it = mMapRenderWindowToResources.find(renderWindow); - - if (it != mMapRenderWindowToResources.end()) - { - // The focus window in which the d3d9 device created on is detached. - // resources must be acquired again. - if (mFocusWindow == renderWindow->getWindowHandle()) - { - mFocusWindow = NULL; - } - - // Case this is the shared focus window. - if (renderWindow->getWindowHandle() == msSharedFocusWindow) - setSharedWindowHandle(NULL); - - RenderWindowResources* renderWindowResources = it->second; - - releaseRenderWindowResources(renderWindowResources); - - OGRE_DELETE_T(renderWindowResources, RenderWindowResources, MEMCATEGORY_RENDERSYS); - - mMapRenderWindowToResources.erase(it); - } - updateRenderWindowsIndices(); - } - - //--------------------------------------------------------------------- - bool D3D9Device::acquire() - { - updatePresentationParameters(); - - bool resetDevice = false; - - // Create device if need to. - if (mDevice == NULL) - { - createD3D9Device(); - } - - // Case device already exists. - else - { - RenderWindowToResourcesIterator itPrimary = getRenderWindowIterator(getPrimaryWindow()); - - if (itPrimary->second->swapChain != NULL) - { - D3DPRESENT_PARAMETERS currentPresentParams; - HRESULT hr; - - hr = itPrimary->second->swapChain->GetPresentParameters(¤tPresentParams); - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "GetPresentParameters failed", - "D3D9RenderWindow::acquire"); - } - - // Desired parameters are different then current parameters. - // Possible scenario is that primary window resized and in the mean while another - // window attached to this device. - if (memcmp(¤tPresentParams, &mPresentationParams[0], sizeof(D3DPRESENT_PARAMETERS)) != 0) - { - resetDevice = true; - } - } - - // Make sure depth stencil is set to valid surface. It is going to be - // grabbed by the primary window using the GetDepthStencilSurface method. - if (resetDevice == false) - { - mDevice->SetDepthStencilSurface(itPrimary->second->depthBuffer); - } - - } - - // Reset device will update all render window resources. - if (resetDevice) - { - reset(); - } - - // No need to reset -> just acquire resources. - else - { - // Update resources of each window. - RenderWindowToResourcesIterator it = mMapRenderWindowToResources.begin(); - - while (it != mMapRenderWindowToResources.end()) - { - acquireRenderWindowResources(it); - ++it; - } - } - - return true; - } - - //--------------------------------------------------------------------- - void D3D9Device::release() - { - if (mDevice != NULL) - { - D3D9RenderSystem* renderSystem = static_cast(Root::getSingleton().getRenderSystem()); - - RenderWindowToResourcesIterator it = mMapRenderWindowToResources.begin(); - - while (it != mMapRenderWindowToResources.end()) - { - RenderWindowResources* renderWindowResources = it->second; - - releaseRenderWindowResources(renderWindowResources); - ++it; - } - - releaseD3D9Device(); - } - } - - //--------------------------------------------------------------------- - bool D3D9Device::acquire(D3D9RenderWindow* renderWindow) - { - RenderWindowToResourcesIterator it = getRenderWindowIterator(renderWindow); - - acquireRenderWindowResources(it); - - return true; - } - - //--------------------------------------------------------------------- - void D3D9Device::notifyDeviceLost() - { - // Case this device is already in lost state. - if (mDeviceLost) - return; - - // Case we just moved from valid state to lost state. - mDeviceLost = true; - - D3D9RenderSystem* renderSystem = static_cast(Root::getSingleton().getRenderSystem()); - - renderSystem->notifyOnDeviceLost(this); - } - - //--------------------------------------------------------------------- - IDirect3DSurface9* D3D9Device::getDepthBuffer(D3D9RenderWindow* renderWindow) - { - RenderWindowToResourcesIterator it = getRenderWindowIterator(renderWindow); - - return it->second->depthBuffer; - } - - //--------------------------------------------------------------------- - IDirect3DSurface9* D3D9Device::getBackBuffer(D3D9RenderWindow* renderWindow) - { - RenderWindowToResourcesIterator it = getRenderWindowIterator(renderWindow); - - return it->second->backBuffer; - } - - //--------------------------------------------------------------------- - uint D3D9Device::getRenderWindowCount() const - { - return static_cast(mMapRenderWindowToResources.size()); - } - - //--------------------------------------------------------------------- - D3D9RenderWindow* D3D9Device::getRenderWindow(uint index) - { - if (index >= mMapRenderWindowToResources.size()) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Index of render window is out of bounds!", - "D3D9RenderWindow::getRenderWindow"); - } - - RenderWindowToResourcesIterator it = mMapRenderWindowToResources.begin(); - - while (it != mMapRenderWindowToResources.end()) - { - if (index == 0) - break; - - --index; - ++it; - } - - return it->first; - } - - //--------------------------------------------------------------------- - void D3D9Device::setAdapterOrdinalIndex(D3D9RenderWindow* renderWindow, uint adapterOrdinalInGroupIndex) - { - RenderWindowToResourcesIterator it = getRenderWindowIterator(renderWindow); - - it->second->adapterOrdinalInGroupIndex = adapterOrdinalInGroupIndex; - - updateRenderWindowsIndices(); - } - - //--------------------------------------------------------------------- - void D3D9Device::destroy() - { - // Lock access to rendering device. - D3D9RenderSystem::getResourceManager()->lockDeviceAccess(); - - //Remove _all_ depth buffers created by this device - D3D9RenderSystem* renderSystem = static_cast(Root::getSingleton().getRenderSystem()); - renderSystem->_cleanupDepthBuffers( mDevice ); - - release(); - - RenderWindowToResourcesIterator it = mMapRenderWindowToResources.begin(); - - while (it != mMapRenderWindowToResources.end()) - { - if (it->first->getWindowHandle() == msSharedFocusWindow) - setSharedWindowHandle(NULL); - - OGRE_DELETE_T(it->second, RenderWindowResources, MEMCATEGORY_RENDERSYS); - ++it; - } - mMapRenderWindowToResources.clear(); - - // Reset dynamic attributes. - mFocusWindow = NULL; - mD3D9DeviceCapsValid = false; - - if (mPresentationParams != NULL) - { - OGRE_FREE (mPresentationParams, MEMCATEGORY_RENDERSYS); - mPresentationParams = NULL; - } - mPresentationParamsCount = 0; - - // Notify the device manager on this instance destruction. - mDeviceManager->notifyOnDeviceDestroy(this); - - // UnLock access to rendering device. - D3D9RenderSystem::getResourceManager()->unlockDeviceAccess(); - } - - //--------------------------------------------------------------------- - bool D3D9Device::isDeviceLost() - { - HRESULT hr; - - hr = mDevice->TestCooperativeLevel(); - - if (hr == D3DERR_DEVICELOST || - hr == D3DERR_DEVICENOTRESET) - { - return true; - } - - return false; - } - - //--------------------------------------------------------------------- - bool D3D9Device::reset() - { - HRESULT hr; - - // Check that device is in valid state for reset. - hr = mDevice->TestCooperativeLevel(); - if (hr == D3DERR_DEVICELOST || - hr == D3DERR_DRIVERINTERNALERROR) - { - return false; - } - - // Lock access to rendering device. - D3D9RenderSystem::getResourceManager()->lockDeviceAccess(); - - D3D9RenderSystem* renderSystem = static_cast(Root::getSingleton().getRenderSystem()); - - // Inform all resources that device lost. - D3D9RenderSystem::getResourceManager()->notifyOnDeviceLost(mDevice); - - // Notify all listener before device is rested - renderSystem->notifyOnDeviceLost(this); - - // Release all automatic temporary buffers and free unused - // temporary buffers, so we doesn't need to recreate them, - // and they will reallocate on demand. This save a lot of - // release/recreate of non-managed vertex buffers which - // wasn't need at all. - HardwareBufferManager::getSingleton()._releaseBufferCopies(true); - - - // Cleanup depth stencils surfaces. - renderSystem->_cleanupDepthBuffers(); - - updatePresentationParameters(); - - RenderWindowToResourcesIterator it = mMapRenderWindowToResources.begin(); - - while (it != mMapRenderWindowToResources.end()) - { - RenderWindowResources* renderWindowResources = it->second; - - releaseRenderWindowResources(renderWindowResources); - ++it; - } - - clearDeviceStreams(); - - renderSystem->fireDeviceEvent(this, "BeforeDeviceReset"); - - // Reset the device using the presentation parameters. - hr = mDevice->Reset(mPresentationParams); - - renderSystem->fireDeviceEvent(this, "AfterDeviceReset"); - - if (hr == D3DERR_DEVICELOST) - { - // UnLock access to rendering device. - D3D9RenderSystem::getResourceManager()->unlockDeviceAccess(); - - // Don't continue - return false; - } - else if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Cannot reset device!", - "D3D9RenderWindow::reset"); - } - - mDeviceLost = false; - - // Initialize device states. - setupDeviceStates(); - - // Update resources of each window. - it = mMapRenderWindowToResources.begin(); - - while (it != mMapRenderWindowToResources.end()) - { - acquireRenderWindowResources(it); - ++it; - } - - D3D9Device* pCurActiveDevice = mDeviceManager->getActiveDevice(); - - mDeviceManager->setActiveDevice(this); - - // Inform all resources that device has been reset. - D3D9RenderSystem::getResourceManager()->notifyOnDeviceReset(mDevice); - - mDeviceManager->setActiveDevice(pCurActiveDevice); - - renderSystem->notifyOnDeviceReset(this); - - // UnLock access to rendering device. - D3D9RenderSystem::getResourceManager()->unlockDeviceAccess(); - - return true; - } - - //--------------------------------------------------------------------- - bool D3D9Device::isAutoDepthStencil() const - { - const D3DPRESENT_PARAMETERS& primaryPresentationParams = mPresentationParams[0]; - - // Check if auto depth stencil can be used. - for (unsigned int i = 1; i < mPresentationParamsCount; i++) - { - // disable AutoDepthStencil if these parameters are not all the same. - if(primaryPresentationParams.BackBufferHeight != mPresentationParams[i].BackBufferHeight || - primaryPresentationParams.BackBufferWidth != mPresentationParams[i].BackBufferWidth || - primaryPresentationParams.BackBufferFormat != mPresentationParams[i].BackBufferFormat || - primaryPresentationParams.AutoDepthStencilFormat != mPresentationParams[i].AutoDepthStencilFormat || - primaryPresentationParams.MultiSampleQuality != mPresentationParams[i].MultiSampleQuality || - primaryPresentationParams.MultiSampleType != mPresentationParams[i].MultiSampleType) - { - return false; - } - } - - return true; - } - - //--------------------------------------------------------------------- - bool D3D9Device::isFullScreen() const - { - if (mPresentationParamsCount > 0 && mPresentationParams[0].Windowed == FALSE) - return true; - - return false; - } - - //--------------------------------------------------------------------- - const D3DCAPS9& D3D9Device::getD3D9DeviceCaps() const - { - if (mD3D9DeviceCapsValid == false) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Device caps are invalid!", - "D3D9Device::getD3D9DeviceCaps" ); - } - - return mD3D9DeviceCaps; - } - - //--------------------------------------------------------------------- - D3DFORMAT D3D9Device::getBackBufferFormat() const - { - if (mPresentationParams == NULL || mPresentationParamsCount == 0) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Presentation parameters are invalid!", - "D3D9Device::getBackBufferFormat" ); - } - - return mPresentationParams[0].BackBufferFormat; - } - - //--------------------------------------------------------------------- - IDirect3DDevice9* D3D9Device::getD3D9Device() - { - return mDevice; - } - - //--------------------------------------------------------------------- - void D3D9Device::updatePresentationParameters() - { - // Clear old presentation parameters. - if (mPresentationParams != NULL) - { - OGRE_FREE (mPresentationParams, MEMCATEGORY_RENDERSYS); - mPresentationParams = NULL; - } - mPresentationParamsCount = 0; - - if (mMapRenderWindowToResources.size() > 0) - { - mPresentationParams = OGRE_ALLOC_T(D3DPRESENT_PARAMETERS, mMapRenderWindowToResources.size(), MEMCATEGORY_RENDERSYS); - - RenderWindowToResourcesIterator it = mMapRenderWindowToResources.begin(); - - while (it != mMapRenderWindowToResources.end()) - { - D3D9RenderWindow* renderWindow = it->first; - RenderWindowResources* renderWindowResources = it->second; - - // Ask the render window to build it's own parameters. - renderWindow->buildPresentParameters(&renderWindowResources->presentParameters); - - - // Update shared focus window handle. - if (renderWindow->isFullScreen() && - renderWindowResources->presentParametersIndex == 0 && - msSharedFocusWindow == NULL) - setSharedWindowHandle(renderWindow->getWindowHandle()); - - // This is the primary window or a full screen window that is part of multi head device. - if (renderWindowResources->presentParametersIndex == 0 || - renderWindow->isFullScreen()) - { - mPresentationParams[renderWindowResources->presentParametersIndex] = renderWindowResources->presentParameters; - mPresentationParamsCount++; - } - - ++it; - } - } - - // Case we have to cancel auto depth stencil. - if (isMultihead() && isAutoDepthStencil() == false) - { - for(unsigned int i = 0; i < mPresentationParamsCount; i++) - { - mPresentationParams[i].EnableAutoDepthStencil = false; - } - } - } - - //--------------------------------------------------------------------- - UINT D3D9Device::getAdapterNumber() const - { - return mAdapterNumber; - } - - //--------------------------------------------------------------------- - D3DDEVTYPE D3D9Device::getDeviceType() const - { - return mDeviceType; - } - - //--------------------------------------------------------------------- - bool D3D9Device::isMultihead() const - { - RenderWindowToResourcesMap::const_iterator it = mMapRenderWindowToResources.begin(); - - while (it != mMapRenderWindowToResources.end()) - { - RenderWindowResources* renderWindowResources = it->second; - - if (renderWindowResources->adapterOrdinalInGroupIndex > 0 && - it->first->isFullScreen()) - { - return true; - } - - ++it; - } - - return false; - } - - //--------------------------------------------------------------------- - void D3D9Device::clearDeviceStreams() - { - D3D9RenderSystem* renderSystem = static_cast(Root::getSingleton().getRenderSystem()); - - // Set all texture units to nothing to release texture surfaces - for (DWORD stage = 0; stage < mD3D9DeviceCaps.MaxSimultaneousTextures; ++stage) - { - DWORD dwCurValue = D3DTOP_FORCE_DWORD; - HRESULT hr; - - hr = mDevice->SetTexture(stage, NULL); - if( hr != S_OK ) - { - String str = "Unable to disable texture '" + StringConverter::toString((unsigned int)stage) + "' in D3D9"; - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, str, "D3D9Device::clearDeviceStreams" ); - } - - mDevice->GetTextureStageState(static_cast(stage), D3DTSS_COLOROP, &dwCurValue); - - if (dwCurValue != D3DTOP_DISABLE) - { - hr = mDevice->SetTextureStageState(static_cast(stage), D3DTSS_COLOROP, D3DTOP_DISABLE); - if( hr != S_OK ) - { - String str = "Unable to disable texture '" + StringConverter::toString((unsigned)stage) + "' in D3D9"; - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, str, "D3D9Device::clearDeviceStreams" ); - } - } - - - // set stage desc. to defaults - renderSystem->mTexStageDesc[stage].pTex = 0; - renderSystem->mTexStageDesc[stage].autoTexCoordType = TEXCALC_NONE; - renderSystem->mTexStageDesc[stage].coordIndex = 0; - renderSystem->mTexStageDesc[stage].texType = D3D9Mappings::D3D_TEX_TYPE_NORMAL; - } - - // Unbind any vertex streams to avoid memory leaks - for (unsigned int i = 0; i < mD3D9DeviceCaps.MaxStreams; ++i) - { - mDevice->SetStreamSource(i, NULL, 0, 0); - } - } - - //--------------------------------------------------------------------- - void D3D9Device::createD3D9Device() - { - // Update focus window. - D3D9RenderWindow* primaryRenderWindow = getPrimaryWindow(); - - // Case we have to share the same focus window. - if (msSharedFocusWindow != NULL) - mFocusWindow = msSharedFocusWindow; - else - mFocusWindow = primaryRenderWindow->getWindowHandle(); - - IDirect3D9* pD3D9 = D3D9RenderSystem::getDirect3D9(); - HRESULT hr; - - - if (isMultihead()) - { - mBehaviorFlags |= D3DCREATE_ADAPTERGROUP_DEVICE; - } - else - { - mBehaviorFlags &= ~D3DCREATE_ADAPTERGROUP_DEVICE; - } - - if(mPresentationParams->SwapEffect == D3DSWAPEFFECT_FLIPEX) - { - mBehaviorFlags |= D3DCREATE_ENABLE_PRESENTSTATS; - } - - - // Try to create the device with hardware vertex processing. - mBehaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING; - hr = pD3D9->CreateDevice(mAdapterNumber, mDeviceType, mFocusWindow, - mBehaviorFlags, mPresentationParams, &mDevice); - - if (FAILED(hr)) - { - // Try a second time, may fail the first time due to back buffer count, - // which will be corrected down to 1 by the runtime - hr = pD3D9->CreateDevice(mAdapterNumber, mDeviceType, mFocusWindow, - mBehaviorFlags, mPresentationParams, &mDevice); - } - - // Case hardware vertex processing failed. - if( FAILED( hr ) ) - { - // Try to create the device with mixed vertex processing. - mBehaviorFlags &= ~D3DCREATE_HARDWARE_VERTEXPROCESSING; - mBehaviorFlags |= D3DCREATE_MIXED_VERTEXPROCESSING; - - hr = pD3D9->CreateDevice(mAdapterNumber, mDeviceType, mFocusWindow, - mBehaviorFlags, mPresentationParams, &mDevice); - } - - if( FAILED( hr ) ) - { - // try to create the device with software vertex processing. - mBehaviorFlags &= ~D3DCREATE_MIXED_VERTEXPROCESSING; - mBehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING; - hr = pD3D9->CreateDevice(mAdapterNumber, mDeviceType, mFocusWindow, - mBehaviorFlags, mPresentationParams, &mDevice); - } - - if ( FAILED( hr ) ) - { - // try reference device - mDeviceType = D3DDEVTYPE_REF; - hr = pD3D9->CreateDevice(mAdapterNumber, mDeviceType, mFocusWindow, - mBehaviorFlags, mPresentationParams, &mDevice); - - if ( FAILED( hr ) ) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Cannot create device!", - "D3D9Device::createD3D9Device" ); - } - } - - // Get current device caps. - hr = mDevice->GetDeviceCaps(&mD3D9DeviceCaps); - if( FAILED( hr ) ) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Cannot get device caps!", - "D3D9Device::createD3D9Device" ); - } - - // Get current creation parameters caps. - hr = mDevice->GetCreationParameters(&mCreationParams); - if ( FAILED(hr) ) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Error Get Creation Parameters", - "D3D9Device:createD3D9Device" ); - } - - mD3D9DeviceCapsValid = true; - - // Initialize device states. - setupDeviceStates(); - - // Lock access to rendering device. - D3D9RenderSystem::getResourceManager()->lockDeviceAccess(); - - D3D9Device* pCurActiveDevice = mDeviceManager->getActiveDevice(); - - mDeviceManager->setActiveDevice(this); - - // Inform all resources that new device created. - D3D9RenderSystem::getResourceManager()->notifyOnDeviceCreate(mDevice); - - mDeviceManager->setActiveDevice(pCurActiveDevice); - - D3D9RenderSystem* renderSystem = static_cast(Root::getSingleton().getRenderSystem()); - renderSystem->fireDeviceEvent(this, "DeviceCreated"); - - // UnLock access to rendering device. - D3D9RenderSystem::getResourceManager()->unlockDeviceAccess(); - } - - //--------------------------------------------------------------------- - void D3D9Device::releaseD3D9Device() - { - if (mDevice != NULL) - { - D3D9RenderSystem* renderSystem = static_cast(Root::getSingleton().getRenderSystem()); - renderSystem->fireDeviceEvent(this, "DeviceReleased"); - - // Lock access to rendering device. - D3D9RenderSystem::getResourceManager()->lockDeviceAccess(); - - D3D9Device* pCurActiveDevice = mDeviceManager->getActiveDevice(); - - mDeviceManager->setActiveDevice(this); - - // Inform all resources that device is going to be destroyed. - D3D9RenderSystem::getResourceManager()->notifyOnDeviceDestroy(mDevice); - - mDeviceManager->setActiveDevice(pCurActiveDevice); - - clearDeviceStreams(); - - // Release device. - SAFE_RELEASE(mDevice); - - // UnLock access to rendering device. - D3D9RenderSystem::getResourceManager()->unlockDeviceAccess(); - } - } - - //--------------------------------------------------------------------- - void D3D9Device::releaseRenderWindowResources(RenderWindowResources* renderWindowResources) - { - if( renderWindowResources->depthBuffer ) - { - D3D9RenderSystem* renderSystem = static_cast - (Root::getSingleton().getRenderSystem()); - renderSystem->_cleanupDepthBuffers( renderWindowResources->depthBuffer ); - } - - SAFE_RELEASE(renderWindowResources->backBuffer); - SAFE_RELEASE(renderWindowResources->depthBuffer); - SAFE_RELEASE(renderWindowResources->swapChain); - SAFE_RELEASE(renderWindowResources->swapChain9Ex); - renderWindowResources->acquired = false; - } - - //--------------------------------------------------------------------- - void D3D9Device::invalidate(D3D9RenderWindow* renderWindow) - { - RenderWindowToResourcesIterator it = getRenderWindowIterator(renderWindow); - - it->second->acquired = false; - } - - //--------------------------------------------------------------------- - bool D3D9Device::validate(D3D9RenderWindow* renderWindow) - { - // Validate that the render window should run on this device. - if (false == validateDisplayMonitor(renderWindow)) - return false; - - // Validate that this device created on the correct target focus window handle - validateFocusWindow(); - - // Validate that the render window dimensions matches to back buffer dimensions. - validateBackBufferSize(renderWindow); - - // Validate that this device is in valid rendering state. - if (false == validateDeviceState(renderWindow)) - return false; - - return true; - } - - //--------------------------------------------------------------------- - void D3D9Device::validateFocusWindow() - { - // Focus window changed -> device should be re-acquired. - if ((msSharedFocusWindow != NULL && mCreationParams.hFocusWindow != msSharedFocusWindow) || - (msSharedFocusWindow == NULL && mCreationParams.hFocusWindow != getPrimaryWindow()->getWindowHandle())) - { - // Lock access to rendering device. - D3D9RenderSystem::getResourceManager()->lockDeviceAccess(); - - release(); - acquire(); - - // UnLock access to rendering device. - D3D9RenderSystem::getResourceManager()->unlockDeviceAccess(); - } - } - - //--------------------------------------------------------------------- - bool D3D9Device::validateDeviceState(D3D9RenderWindow* renderWindow) - { - RenderWindowToResourcesIterator it = getRenderWindowIterator(renderWindow); - RenderWindowResources* renderWindowResources = it->second; - HRESULT hr; - - hr = mDevice->TestCooperativeLevel(); - - // Case device is not valid for rendering. - if (FAILED(hr)) - { - // device lost, and we can't reset - // can't do anything about it here, wait until we get - // D3DERR_DEVICENOTRESET; rendering calls will silently fail until - // then (except Present, but we ignore device lost there too) - if (hr == D3DERR_DEVICELOST) - { - releaseRenderWindowResources(renderWindowResources); - notifyDeviceLost(); - return false; - } - - // device lost, and we can reset - else if (hr == D3DERR_DEVICENOTRESET) - { - bool deviceRestored = reset(); - - // Device was not restored yet. - if (deviceRestored == false) - { - // Wait a while - Sleep(50); - return false; - } - } - } - - // Render window resources explicitly invalidated. (Resize or window mode switch) - if (renderWindowResources->acquired == false) - { - if (getPrimaryWindow() == renderWindow) - { - bool deviceRestored = reset(); - - // Device was not restored yet. - if (deviceRestored == false) - { - // Wait a while - Sleep(50); - return false; - } - } - else - { - acquire(renderWindow); - } - } - - return true; - } - - - //--------------------------------------------------------------------- - void D3D9Device::validateBackBufferSize(D3D9RenderWindow* renderWindow) - { - RenderWindowToResourcesIterator it = getRenderWindowIterator(renderWindow); - RenderWindowResources* renderWindowResources = it->second; - - - // Case size has been changed. - if (renderWindow->getWidth() != renderWindowResources->presentParameters.BackBufferWidth || - renderWindow->getHeight() != renderWindowResources->presentParameters.BackBufferHeight) - { - if (renderWindow->getWidth() > 0) - renderWindowResources->presentParameters.BackBufferWidth = renderWindow->getWidth(); - - if (renderWindow->getHeight() > 0) - renderWindowResources->presentParameters.BackBufferHeight = renderWindow->getHeight(); - - invalidate(renderWindow); - } - } - - //--------------------------------------------------------------------- - bool D3D9Device::validateDisplayMonitor(D3D9RenderWindow* renderWindow) - { - // Ignore full screen since it doesn't really move and it is possible - // that it created using multi-head adapter so for a subordinate the - // native monitor handle and this device handle will be different. - if (renderWindow->isFullScreen()) - return true; - - RenderWindowToResourcesIterator it = getRenderWindowIterator(renderWindow); - HMONITOR hRenderWindowMonitor = NULL; - - // Find the monitor this render window belongs to. - hRenderWindowMonitor = MonitorFromWindow(renderWindow->getWindowHandle(), MONITOR_DEFAULTTONULL); - - // This window doesn't intersect with any of the display monitor - if (hRenderWindowMonitor == NULL) - return false; - - - // Case this window changed monitor. - if (hRenderWindowMonitor != mMonitor) - { - // Lock access to rendering device. - D3D9RenderSystem::getResourceManager()->lockDeviceAccess(); - - mDeviceManager->linkRenderWindow(renderWindow); - - // UnLock access to rendering device. - D3D9RenderSystem::getResourceManager()->unlockDeviceAccess(); - - return false; - } - - return true; - } - - //--------------------------------------------------------------------- - void D3D9Device::present(D3D9RenderWindow* renderWindow) - { - RenderWindowToResourcesIterator it = getRenderWindowIterator(renderWindow); - RenderWindowResources* renderWindowResources = it->second; - - - // Skip present while current device state is invalid. - if (mDeviceLost || - renderWindowResources->acquired == false || - isDeviceLost()) - return; - - - HRESULT hr; - - D3D9RenderSystem* renderSystem = static_cast(Root::getSingleton().getRenderSystem()); - renderSystem->fireDeviceEvent(this, "BeforeDevicePresent"); - - if (isMultihead()) - { - // Only the master will call present method results in synchronized - // buffer swap for the rest of the implicit swap chain. - if (getPrimaryWindow() == renderWindow) - hr = mDevice->Present( NULL, NULL, NULL, NULL ); - else - hr = S_OK; - } - else - { - hr = renderWindowResources->swapChain->Present(NULL, NULL, NULL, NULL, 0); - } - - - if( D3DERR_DEVICELOST == hr) - { - releaseRenderWindowResources(renderWindowResources); - notifyDeviceLost(); - } - else if( FAILED(hr) ) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Error Presenting surfaces", - "D3D9Device::present" ); - } - else - mLastPresentFrame = Root::getSingleton().getNextFrameNumber(); - } - - //--------------------------------------------------------------------- - void D3D9Device::acquireRenderWindowResources(RenderWindowToResourcesIterator it) - { - RenderWindowResources* renderWindowResources = it->second; - D3D9RenderWindow* renderWindow = it->first; - - releaseRenderWindowResources(renderWindowResources); - - // Create additional swap chain - if (isSwapChainWindow(renderWindow) && !isMultihead()) - { - // Create swap chain - HRESULT hr = mDevice->CreateAdditionalSwapChain(&renderWindowResources->presentParameters, - &renderWindowResources->swapChain); - - if (FAILED(hr)) - { - // Try a second time, may fail the first time due to back buffer count, - // which will be corrected by the runtime - hr = mDevice->CreateAdditionalSwapChain(&renderWindowResources->presentParameters, - &renderWindowResources->swapChain); - } - - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Unable to create an additional swap chain", - "D3D9RenderWindow::acquireRenderWindowResources"); - } - - renderWindowResources->swapChain9Ex = NULL; - } - else - { - // The swap chain is already created by the device - HRESULT hr = mDevice->GetSwapChain(renderWindowResources->presentParametersIndex, - &renderWindowResources->swapChain); - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Unable to get the swap chain", - "D3D9RenderWindow::acquireRenderWindowResources"); - } - - renderWindowResources->swapChain9Ex = NULL; - } - - // Store references to buffers for convenience - renderWindowResources->swapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, - &renderWindowResources->backBuffer); - - // Additional swap chains need their own depth buffer - // to support resizing them - if (renderWindow->isDepthBuffered()) - { - // if multihead is enabled, depth buffer can be created automatically for - // all the adapters. if multihead is not enabled, depth buffer is just - // created for the main swap chain - if (isMultihead() && isAutoDepthStencil() || - isMultihead() == false && isSwapChainWindow(renderWindow) == false) - { - mDevice->GetDepthStencilSurface(&renderWindowResources->depthBuffer); - } - else - { - uint targetWidth = renderWindow->getWidth(); - uint targetHeight = renderWindow->getHeight(); - - if (targetWidth == 0) - targetWidth = 1; - - if (targetHeight == 0) - targetHeight = 1; - - HRESULT hr = mDevice->CreateDepthStencilSurface( - targetWidth, targetHeight, - renderWindowResources->presentParameters.AutoDepthStencilFormat, - renderWindowResources->presentParameters.MultiSampleType, - renderWindowResources->presentParameters.MultiSampleQuality, - (renderWindowResources->presentParameters.Flags & D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL), - &renderWindowResources->depthBuffer, NULL - ); - - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Unable to create a depth buffer for the swap chain", - "D3D9RenderWindow::acquireRenderWindowResources"); - } - - if (isSwapChainWindow(renderWindow) == false) - { - mDevice->SetDepthStencilSurface(renderWindowResources->depthBuffer); - } - } - - if (renderWindowResources->depthBuffer) - { - //Tell the RS we have a depth buffer we created it needs to add to the default pool - D3D9RenderSystem* renderSystem = static_cast(Root::getSingleton().getRenderSystem()); - DepthBuffer *depthBuf = renderSystem->_addManualDepthBuffer( mDevice, renderWindowResources->depthBuffer ); - - //Don't forget we want this window to use _this_ depth buffer - renderWindow->attachDepthBuffer( depthBuf ); - } - else - { - LogManager::getSingleton().logWarning("D3D9: Depth buffer could not be acquired."); - } - } - - renderWindowResources->acquired = true; - } - - //--------------------------------------------------------------------- - void D3D9Device::setupDeviceStates() - { - HRESULT hr = mDevice->SetRenderState(D3DRS_SPECULARENABLE, TRUE); - - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Unable to apply render state: D3DRS_SPECULARENABLE <- TRUE", - "D3D9Device::setupDeviceStates"); - } - } - - //--------------------------------------------------------------------- - bool D3D9Device::isSwapChainWindow(D3D9RenderWindow* renderWindow) - { - RenderWindowToResourcesIterator it = getRenderWindowIterator(renderWindow); - - if (it->second->presentParametersIndex == 0 || renderWindow->isFullScreen()) - return false; - - return true; - } - - //--------------------------------------------------------------------- - D3D9RenderWindow* D3D9Device::getPrimaryWindow() - { - RenderWindowToResourcesIterator it = mMapRenderWindowToResources.begin(); - - while (it != mMapRenderWindowToResources.end() && it->second->presentParametersIndex != 0) - ++it; - - assert(it != mMapRenderWindowToResources.end()); - - return it->first; - } - - //--------------------------------------------------------------------- - void D3D9Device::setSharedWindowHandle(HWND hSharedHWND) - { - if (hSharedHWND != msSharedFocusWindow) - msSharedFocusWindow = hSharedHWND; - } - - //--------------------------------------------------------------------- - void D3D9Device::updateRenderWindowsIndices() - { - // Update present parameters index attribute per render window. - if (isMultihead()) - { - RenderWindowToResourcesIterator it = mMapRenderWindowToResources.begin(); - - // Multi head device case - - // Present parameter index is based on adapter ordinal in group index. - while (it != mMapRenderWindowToResources.end()) - { - it->second->presentParametersIndex = it->second->adapterOrdinalInGroupIndex; - ++it; - } - } - else - { - // Single head device case - - // Just assign index in incremental order - - // NOTE: It suppose to cover both cases that possible here: - // 1. Single full screen window - only one allowed per device (this is not multi-head case). - // 2. Multiple window mode windows. - - uint nextPresParamIndex = 0; - - RenderWindowToResourcesIterator it; - D3D9RenderWindow* deviceFocusWindow = NULL; - - // In case a d3d9 device exists - try to keep the present parameters order - // so that the window that the device is focused on will stay the same and we - // will avoid device re-creation. - if (mDevice != NULL) - { - it = mMapRenderWindowToResources.begin(); - while (it != mMapRenderWindowToResources.end()) - { - //This "if" handles the common case of a single device - if (it->first->getWindowHandle() == mCreationParams.hFocusWindow) - { - deviceFocusWindow = it->first; - it->second->presentParametersIndex = nextPresParamIndex; - ++nextPresParamIndex; - break; - } - //This "if" handles multiple devices when a shared window is used - if ((it->second->presentParametersIndex == 0) && (it->second->acquired == true)) - { - deviceFocusWindow = it->first; - ++nextPresParamIndex; - } - ++it; - } - } - - - - it = mMapRenderWindowToResources.begin(); - while (it != mMapRenderWindowToResources.end()) - { - if (it->first != deviceFocusWindow) - { - it->second->presentParametersIndex = nextPresParamIndex; - ++nextPresParamIndex; - } - ++it; - } - } - } - //--------------------------------------------------------------------- - void D3D9Device::copyContentsToMemory(D3D9RenderWindow* renderWindow, - const Box& src, const PixelBox &dst, RenderTarget::FrameBuffer buffer) - { - RenderWindowToResourcesIterator it = getRenderWindowIterator(renderWindow); - RenderWindowResources* resources = it->second; - bool swapChain = isSwapChainWindow(renderWindow); - - if(src.right > renderWindow->getWidth() || src.bottom > renderWindow->getHeight() || src.front != 0 || src.back != 1 - || dst.getWidth() != src.getWidth() || dst.getHeight() != src.getHeight() || dst.getDepth() != 1) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Invalid box.", "D3D9Device::copyContentsToMemory"); - } - - HRESULT hr; - IDirect3DSurface9* pSurf = NULL; - IDirect3DSurface9* pTempSurf = NULL; - D3DSURFACE_DESC desc; - D3DLOCKED_RECT lockedRect; - - - if (buffer == RenderTarget::FB_AUTO) - { - //buffer = mIsFullScreen? FB_FRONT : FB_BACK; - buffer = RenderTarget::FB_BACK; - } - - if (buffer == RenderTarget::FB_FRONT) - { - D3DDISPLAYMODE dm; - - if (FAILED(hr = mDevice->GetDisplayMode(0, &dm))) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Can't get display mode: " + DXGetErrorDescription(hr), - "D3D9Device::copyContentsToMemory"); - } - - desc.Width = dm.Width; - desc.Height = dm.Height; - desc.Format = D3DFMT_A8R8G8B8; - if (FAILED(hr = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, - desc.Format, - D3DPOOL_SYSTEMMEM, - &pTempSurf, - 0))) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Can't create offscreen buffer: " + DXGetErrorDescription(hr), - "D3D9Device::copyContentsToMemory"); - } - - if (FAILED(hr = swapChain ? resources->swapChain->GetFrontBufferData(pTempSurf) : - mDevice->GetFrontBufferData(0, pTempSurf))) - { - SAFE_RELEASE(pTempSurf); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Can't get front buffer: " + DXGetErrorDescription(hr), - "D3D9Device::copyContentsToMemory"); - } - - if(renderWindow->isFullScreen()) - { - if ((src.left == 0) && (src.right == renderWindow->getWidth()) && (src.top == 0) && (src.bottom == renderWindow->getHeight())) - { - hr = pTempSurf->LockRect(&lockedRect, 0, D3DLOCK_READONLY | D3DLOCK_NOSYSLOCK); - } - else - { - RECT rect; - - rect.left = static_cast(src.left); - rect.right = static_cast(src.right); - rect.top = static_cast(src.top); - rect.bottom = static_cast(src.bottom); - - hr = pTempSurf->LockRect(&lockedRect, &rect, D3DLOCK_READONLY | D3DLOCK_NOSYSLOCK); - } - if (FAILED(hr)) - { - SAFE_RELEASE(pTempSurf); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Can't lock rect: " + DXGetErrorDescription(hr), - "D3D9Device::copyContentsToMemory"); - } - } - else - { - RECT srcRect; - //GetClientRect(mHWnd, &srcRect); - srcRect.left = static_cast(src.left); - srcRect.top = static_cast(src.top); - srcRect.right = static_cast(src.right); - srcRect.bottom = static_cast(src.bottom); - POINT point; - point.x = srcRect.left; - point.y = srcRect.top; - ClientToScreen(renderWindow->getWindowHandle(), &point); - srcRect.top = point.y; - srcRect.left = point.x; - srcRect.bottom += point.y; - srcRect.right += point.x; - - desc.Width = srcRect.right - srcRect.left; - desc.Height = srcRect.bottom - srcRect.top; - - if (FAILED(hr = pTempSurf->LockRect(&lockedRect, &srcRect, D3DLOCK_READONLY | D3DLOCK_NOSYSLOCK))) - { - SAFE_RELEASE(pTempSurf); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Can't lock rect: " + DXGetErrorDescription(hr), - "D3D9Device::copyContentsToMemory"); - } - } - } - else - { - SAFE_RELEASE(pSurf); - if(FAILED(hr = swapChain? resources->swapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &pSurf) : - mDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &pSurf))) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Can't get back buffer: " + DXGetErrorDescription(hr), - "D3D9Device::copyContentsToMemory"); - } - - if(FAILED(hr = pSurf->GetDesc(&desc))) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Can't get description: " + DXGetErrorDescription(hr), - "D3D9Device::copyContentsToMemory"); - } - - if (FAILED(hr = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, - desc.Format, - D3DPOOL_SYSTEMMEM, - &pTempSurf, - 0))) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Can't create offscreen surface: " + DXGetErrorDescription(hr), - "D3D9Device::copyContentsToMemory"); - } - - if (desc.MultiSampleType == D3DMULTISAMPLE_NONE) - { - if (FAILED(hr = mDevice->GetRenderTargetData(pSurf, pTempSurf))) - { - SAFE_RELEASE(pTempSurf); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Can't get render target data: " + DXGetErrorDescription(hr), - "D3D9Device::copyContentsToMemory"); - } - } - else - { - IDirect3DSurface9* pStretchSurf = 0; - - if (FAILED(hr = mDevice->CreateRenderTarget(desc.Width, desc.Height, - desc.Format, - D3DMULTISAMPLE_NONE, - 0, - false, - &pStretchSurf, - 0))) - { - SAFE_RELEASE(pTempSurf); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Can't create render target: " + DXGetErrorDescription(hr), - "D3D9Device::copyContentsToMemory"); - } - - if (FAILED(hr = mDevice->StretchRect(pSurf, 0, pStretchSurf, 0, D3DTEXF_NONE))) - { - SAFE_RELEASE(pTempSurf); - SAFE_RELEASE(pStretchSurf); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Can't stretch rect: " + DXGetErrorDescription(hr), - "D3D9Device::copyContentsToMemory"); - } - if (FAILED(hr = mDevice->GetRenderTargetData(pStretchSurf, pTempSurf))) - { - SAFE_RELEASE(pTempSurf); - SAFE_RELEASE(pStretchSurf); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Can't get render target data: " + DXGetErrorDescription(hr), - "D3D9Device::copyContentsToMemory"); - } - SAFE_RELEASE(pStretchSurf); - } - - if ((src.left == 0) && (src.right == renderWindow->getWidth()) && (src.top == 0) && (src.bottom == renderWindow->getHeight())) - { - hr = pTempSurf->LockRect(&lockedRect, 0, D3DLOCK_READONLY | D3DLOCK_NOSYSLOCK); - } - else - { - RECT rect; - - rect.left = static_cast(src.left); - rect.right = static_cast(src.right); - rect.top = static_cast(src.top); - rect.bottom = static_cast(src.bottom); - - hr = pTempSurf->LockRect(&lockedRect, &rect, D3DLOCK_READONLY | D3DLOCK_NOSYSLOCK); - } - if (FAILED(hr)) - { - SAFE_RELEASE(pTempSurf); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Can't lock rect: " + DXGetErrorDescription(hr), - "D3D9Device::copyContentsToMemory"); - } - } - - PixelFormat format = Ogre::D3D9Mappings::_getPF(desc.Format); - - if (format == PF_UNKNOWN) - { - SAFE_RELEASE(pTempSurf); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Unsupported format", "D3D9Device::copyContentsToMemory"); - } - - PixelBox srcBox(src.getWidth(), src.getHeight(), 1, format, lockedRect.pBits); - srcBox.rowPitch = lockedRect.Pitch / PixelUtil::getNumElemBytes(format); - srcBox.slicePitch = desc.Height * srcBox.rowPitch; - - PixelUtil::bulkPixelConversion(srcBox, dst); - - SAFE_RELEASE(pTempSurf); - SAFE_RELEASE(pSurf); - - - } - - int D3D9Device::getVBlankMissCount(D3D9RenderWindow* renderWindow) - { - // the stat only works with no AA, VSync and 9Ex. - if(renderWindow->isAA() || - renderWindow->isVSyncEnabled() == false || - D3D9RenderSystem::isDirectX9Ex() == false) - { - return -1; - } - - RenderWindowToResourcesIterator it = getRenderWindowIterator(renderWindow); - RenderWindowResources* renderWindowResources = it->second; - - // The 9Ex swap chain is set to NULL when we create the RenderWindowResources, now we need it - // to get the stats - so we try to get it from the original d3d9 swap chain by using - // COM's QueryInterface - if(renderWindowResources->swapChain9Ex == NULL) - { - if (FAILED(renderWindowResources->swapChain->QueryInterface(IID_IDirect3DSwapChain9Ex, (void**)&renderWindowResources->swapChain9Ex))) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Can't get Direct3DSwapChain9Ex from Direct3DSwapChain.", - "D3D9Device::getVBlankMissCount"); - } - } - - // Get Present Stats info for glitch detection - D3DPRESENTSTATS currentPresentStats; - ZeroMemory(¤tPresentStats, sizeof(currentPresentStats)); - // Obtain present statistics information for successfully displayed presents - HRESULT hr = renderWindowResources->swapChain9Ex->GetPresentStats(¤tPresentStats); - - // check if the call to GetPresentStats got us the stats - if(FAILED(hr) || currentPresentStats.PresentRefreshCount == 0) - { - mPreviousPresentStatsIsValid = false; - } - else - { - if(mPreviousPresentStatsIsValid == true) - { - // add the vblank misses since the last call to getVBlankMissCount - int currentVBlankMissCount = (currentPresentStats.PresentRefreshCount - mPreviousPresentStats.PresentRefreshCount) - - (currentPresentStats.PresentCount - mPreviousPresentStats.PresentCount); - - if(currentVBlankMissCount > 0) - { - mVBlankMissCount += currentVBlankMissCount; - } - } - - // save the current to be the next time previous - mPreviousPresentStats = currentPresentStats; - mPreviousPresentStatsIsValid = true; - } - - return mVBlankMissCount; - } -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9DeviceManager.cpp b/RenderSystems/Direct3D9/src/OgreD3D9DeviceManager.cpp deleted file mode 100644 index c517653d008..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9DeviceManager.cpp +++ /dev/null @@ -1,501 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9DeviceManager.h" -#include "OgreD3D9Device.h" -#include "OgreD3D9RenderSystem.h" -#include "OgreD3D9RenderWindow.h" -#include "OgreD3D9Driver.h" -#include "OgreD3D9DriverList.h" -#include "OgreRoot.h" -#include "OgreLogManager.h" - -namespace Ogre -{ - //--------------------------------------------------------------------- - D3D9DeviceManager::D3D9DeviceManager() - { - mActiveDevice = NULL; - mActiveRenderWindowDevice = NULL; - } - - //--------------------------------------------------------------------- - D3D9DeviceManager::~D3D9DeviceManager() - { - DeviceIterator itDevice = mRenderDevices.begin(); - while (mRenderDevices.size() > 0) - { - mRenderDevices[0]->destroy(); - } - - mActiveDevice = NULL; - mActiveRenderWindowDevice = NULL; - } - - //--------------------------------------------------------------------- - void D3D9DeviceManager::setActiveDevice(D3D9Device* device) - { - if (mActiveDevice != device) - { - mActiveDevice = device; - - D3D9RenderSystem* renderSystem = static_cast(Root::getSingleton().getRenderSystem()); - D3D9DriverList* driverList = renderSystem->getDirect3DDrivers(); - - // Update the active driver member. - for (uint i=0; i < driverList->count(); ++i) - { - D3D9Driver* currDriver = driverList->item(i); - if (currDriver->getAdapterNumber() == mActiveDevice->getAdapterNumber()) - { - renderSystem->mActiveD3DDriver = currDriver; - break; - } - } - - // Invalidate active view port. - renderSystem->mActiveViewport = NULL; - } - } - - //--------------------------------------------------------------------- - void D3D9DeviceManager::setActiveRenderTargetDevice(D3D9Device* device) - { - mActiveRenderWindowDevice = device; - if (mActiveRenderWindowDevice != NULL) - setActiveDevice(mActiveRenderWindowDevice); - } - - //--------------------------------------------------------------------- - D3D9Device* D3D9DeviceManager::getActiveRenderTargetDevice() - { - return mActiveRenderWindowDevice; - } - - //--------------------------------------------------------------------- - UINT D3D9DeviceManager::getDeviceCount() - { - return static_cast(mRenderDevices.size()); - } - - //--------------------------------------------------------------------- - D3D9Device* D3D9DeviceManager::getDevice(UINT index) - { - return mRenderDevices[index]; - } - - //--------------------------------------------------------------------- - void D3D9DeviceManager::linkRenderWindow(D3D9RenderWindow* renderWindow) - { - D3D9Device* renderDevice; - - // Detach from previous device. - renderDevice = renderWindow->getDevice(); - if (renderDevice != NULL) - renderDevice->detachRenderWindow(renderWindow); - - D3D9RenderWindowList renderWindowsGroup; - - // Select new device for this window. - renderDevice = selectDevice(renderWindow, renderWindowsGroup); - - // Link the windows group to the new device. - for (uint i = 0; i < renderWindowsGroup.size(); ++i) - { - D3D9RenderWindow* currWindow = renderWindowsGroup[i]; - - currWindow->setDevice(renderDevice); - renderDevice->attachRenderWindow(currWindow); - renderDevice->setAdapterOrdinalIndex(currWindow, i); - } - - renderDevice->acquire(); - if (mActiveDevice == NULL) - setActiveDevice(renderDevice); - } - - //--------------------------------------------------------------------- - D3D9Device* D3D9DeviceManager::selectDevice(D3D9RenderWindow* renderWindow, D3D9RenderWindowList& renderWindowsGroup) - { - D3D9RenderSystem* renderSystem = static_cast(Root::getSingleton().getRenderSystem()); - D3D9Device* renderDevice = NULL; - IDirect3D9* direct3D9 = D3D9RenderSystem::getDirect3D9(); - UINT nAdapterOrdinal = D3DADAPTER_DEFAULT; - D3DDEVTYPE devType = D3DDEVTYPE_HAL; - DWORD extraFlags = 0; - D3D9DriverList* driverList = renderSystem->getDirect3DDrivers(); - bool nvAdapterFound = false; - - - // Default group includes at least the given render window. - renderWindowsGroup.push_back(renderWindow); - - // Case we use nvidia performance HUD, override the device settings. - if (renderWindow->isNvPerfHUDEnable()) - { - // Look for 'NVIDIA NVPerfHUD' adapter (<= v4) - // or 'NVIDIA PerfHUD' (v5) - // If it is present, override default settings - for (UINT adapter=0; adapter < direct3D9->GetAdapterCount(); ++adapter) - { - D3D9Driver* currDriver = driverList->item(adapter); - const D3DADAPTER_IDENTIFIER9& currAdapterIdentifier = currDriver->getAdapterIdentifier(); - - if(strstr(currAdapterIdentifier.Description, "PerfHUD") != NULL) - { - renderDevice = NULL; - nAdapterOrdinal = adapter; - renderSystem->mActiveD3DDriver = currDriver; - devType = D3DDEVTYPE_REF; - nvAdapterFound = true; - break; - } - } - } - - // No special adapter should be used. - if (nvAdapterFound == false) - { - renderSystem->mActiveD3DDriver = findDriver(renderWindow); - nAdapterOrdinal = renderSystem->mActiveD3DDriver->getAdapterNumber(); - - bool bTryUsingMultiheadDevice = false; - - if (renderWindow->isFullScreen()) - { - bTryUsingMultiheadDevice = true; - if (renderSystem->getMultiheadUse() == D3D9RenderSystem::mutAuto) - { - OSVERSIONINFO osVersionInfo; - - osVersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); - - // Case version info failed -> assume we run on XP. - if (FALSE == GetVersionEx(&osVersionInfo)) - { - osVersionInfo.dwMajorVersion = 5; - } - - // XP and below - multi-head will cause artifacts when vsync is on. - if (osVersionInfo.dwMajorVersion <= 5 && renderWindow->isVSync()) - { - bTryUsingMultiheadDevice = false; - LogManager::getSingleton().logMessage("D3D9 : Multi head disabled. It causes horizontal line when used in XP + VSync combination"); - } - - // Vista and SP1 or SP2 - multi-head device can not be reset - it causes memory corruption. - if (osVersionInfo.dwMajorVersion == 6 && - (_stricmp(osVersionInfo.szCSDVersion, "Service Pack 1") == 0 || - _stricmp(osVersionInfo.szCSDVersion, "Service Pack 2") == 0)) - - { - bTryUsingMultiheadDevice = false; - LogManager::getSingleton().logMessage("D3D9 : Multi head disabled. It causes application run time crashes when used in Vista + SP 1 or 2 combination"); - } - } - else - { - bTryUsingMultiheadDevice = renderSystem->getMultiheadUse() == D3D9RenderSystem::mutYes ? true : false; - } - } - - - // Check if we can create a group of render windows - // on the same device using the multi-head feature. - if (bTryUsingMultiheadDevice) - { - const D3DCAPS9& targetAdapterCaps = renderSystem->mActiveD3DDriver->getD3D9DeviceCaps(); - D3DCAPS9 masterAdapterCaps; - - // Find the master device caps. - if (targetAdapterCaps.MasterAdapterOrdinal == targetAdapterCaps.AdapterOrdinal) - { - masterAdapterCaps = targetAdapterCaps; - } - else - { - for (uint i = 0; i < driverList->count(); ++i) - { - D3D9Driver* currDriver = driverList->item(i); - const D3DCAPS9& currDeviceCaps = currDriver->getD3D9DeviceCaps(); - - if (currDeviceCaps.AdapterOrdinal == targetAdapterCaps.MasterAdapterOrdinal) - { - masterAdapterCaps = currDeviceCaps; - break; - } - } - } - - // Case the master adapter can handle multiple adapters. - if (masterAdapterCaps.NumberOfAdaptersInGroup > 1) - { - // Create empty list of render windows composing this group. - renderWindowsGroup.resize(masterAdapterCaps.NumberOfAdaptersInGroup); - for (uint i = 0; i < renderWindowsGroup.size(); ++i) - renderWindowsGroup[i] = NULL; - - - // Assign the current render window to it's place in the group. - renderWindowsGroup[targetAdapterCaps.AdapterOrdinalInGroup] = renderWindow; - - - // For each existing window - check if it belongs to the group. - for (uint i = 0; i < renderSystem->mRenderWindows.size(); ++i) - { - D3D9RenderWindow* currRenderWindow = renderSystem->mRenderWindows[i]; - - if (currRenderWindow->isFullScreen()) - { - D3D9Driver* currDriver = findDriver(currRenderWindow); - const D3DCAPS9& currDeviceCaps = currDriver->getD3D9DeviceCaps(); - - if (currDeviceCaps.MasterAdapterOrdinal == masterAdapterCaps.AdapterOrdinal) - { - renderWindowsGroup[currDeviceCaps.AdapterOrdinalInGroup] = currRenderWindow; - break; - } - } - } - - bool bDeviceGroupFull = true; - - - // Check if render windows group is full and ready to be driven by - // the master device. - for (uint i = 0; i < renderWindowsGroup.size(); ++i) - { - // This group misses required window -> go back to default. - if (renderWindowsGroup[i] == NULL) - { - bDeviceGroupFull = false; - renderWindowsGroup.clear(); - renderWindowsGroup.push_back(renderWindow); - break; - } - } - - // Case device group is full -> we can use multi head device. - if (bDeviceGroupFull) - { - bool validateAllDevices = false; - - for (uint i = 0; i < renderWindowsGroup.size(); ++i) - { - D3D9RenderWindow* currRenderWindow = renderWindowsGroup[i]; - D3D9Device* currDevice = currRenderWindow->getDevice(); - - // This is the master window - if (i == 0) - { - // If master device exists - just release it. - if (currDevice != NULL) - { - renderDevice = currDevice; - renderDevice->release(); - } - } - - // This is subordinate window. - else - { - // If subordinate device exists - destroy it. - if (currDevice != NULL) - { - currDevice->destroy(); - validateAllDevices = true; - } - } - } - - // In case some device was destroyed - make sure all other devices are valid. - // A possible scenario is that full screen window has been destroyed and it's handle - // was used and the shared focus handle. All other devices used this handle and must be - // recreated using other handles otherwise create device will fail. - if (validateAllDevices) - { - for (uint i = 0; i < mRenderDevices.size(); ++i) - mRenderDevices[i]->validateFocusWindow(); - } - } - } - } - } - - - - // Do we want to preserve the FPU mode? Might be useful for scientific apps - auto options = renderSystem->getConfigOptions(); - auto opti = options.find("Floating-point mode"); - if (opti != options.end() && opti->second.currentValue == "Consistent") - extraFlags |= D3DCREATE_FPU_PRESERVE; - -#if OGRE_THREAD_SUPPORT == 1 - extraFlags |= D3DCREATE_MULTITHREADED; -#endif - - - // Try to find a matching device from current device list. - if (renderDevice == NULL) - { - for (uint i = 0; i < mRenderDevices.size(); ++i) - { - D3D9Device* currDevice = mRenderDevices[i]; - - if (currDevice->getAdapterNumber() == nAdapterOrdinal && - currDevice->getDeviceType() == devType && - currDevice->isFullScreen() == renderWindow->isFullScreen()) - { - renderDevice = currDevice; - break; - } - } - } - - // No matching device found -> try reference device type (might have been - // previously created as a fallback, but don't change devType because HAL - // should be preferred on creation) - if (renderDevice == NULL) - { - for (uint i = 0; i < mRenderDevices.size(); ++i) - { - D3D9Device* currDevice = mRenderDevices[i]; - - if (currDevice->getAdapterNumber() == nAdapterOrdinal && - currDevice->getDeviceType() == D3DDEVTYPE_REF) - { - renderDevice = currDevice; - break; - } - } - } - - - // No matching device found -> create new one. - if (renderDevice == NULL) - { - renderDevice = OGRE_NEW D3D9Device(this, nAdapterOrdinal, direct3D9->GetAdapterMonitor(nAdapterOrdinal), devType, extraFlags); - mRenderDevices.push_back(renderDevice); - if (mActiveDevice == NULL) - setActiveDevice(renderDevice); - } - - return renderDevice; - } - - //----------------------------------------------------------------------- - D3D9Driver* D3D9DeviceManager::findDriver(D3D9RenderWindow* renderWindow) - { - D3D9RenderSystem* renderSystem = static_cast(Root::getSingleton().getRenderSystem()); - IDirect3D9* direct3D9 = D3D9RenderSystem::getDirect3D9(); - UINT nAdapterOrdinal = D3DADAPTER_DEFAULT; - HMONITOR hRenderWindowMonitor = NULL; - D3D9DriverList* driverList = renderSystem->getDirect3DDrivers(); - - // Find the monitor this render window belongs to. - hRenderWindowMonitor = MonitorFromWindow(renderWindow->getWindowHandle(), MONITOR_DEFAULTTONEAREST); - - - // Find the matching driver using window monitor handle. - for (uint i = 0; i < driverList->count(); ++i) - { - D3D9Driver* currDriver = driverList->item(i); - HMONITOR hCurrAdpaterMonitor = direct3D9->GetAdapterMonitor(currDriver->getAdapterNumber()); - - if (hCurrAdpaterMonitor == hRenderWindowMonitor) - { - return currDriver; - } - } - - return NULL; - } - - //----------------------------------------------------------------------- - void D3D9DeviceManager::notifyOnDeviceDestroy(D3D9Device* device) - { - if (device != NULL) - { - if (device == mActiveDevice) - mActiveDevice = NULL; - - DeviceIterator itDevice = mRenderDevices.begin(); - while (itDevice != mRenderDevices.end()) - { - if (*itDevice == device) - { - OGRE_DELETE device; - mRenderDevices.erase(itDevice); - break; - } - ++itDevice; - } - - if (mActiveDevice == NULL) - { - DeviceIterator itDevice = mRenderDevices.begin(); - if (itDevice != mRenderDevices.end()) - mActiveDevice = (*itDevice); - } - } - } - - //--------------------------------------------------------------------- - D3D9Device* D3D9DeviceManager::getDeviceFromD3D9Device(IDirect3DDevice9* d3d9Device) - { - DeviceIterator itDevice = mRenderDevices.begin(); - while (itDevice != mRenderDevices.end()) - { - if ((*itDevice)->getD3D9Device() == d3d9Device) - { - return *itDevice; - } - ++itDevice; - } - - return NULL; - } - - //--------------------------------------------------------------------- - void D3D9DeviceManager::destroyInactiveRenderDevices() - { - DeviceIterator itDevice = mRenderDevices.begin(); - while (itDevice != mRenderDevices.end()) - { - if ((*itDevice)->getRenderWindowCount() == 0 && - (*itDevice)->getLastPresentFrame() + 1 < Root::getSingleton().getNextFrameNumber()) - { - if (*itDevice == mActiveRenderWindowDevice) - setActiveRenderTargetDevice(NULL); - (*itDevice)->destroy(); - break; - } - ++itDevice; - } - } - -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9Driver.cpp b/RenderSystems/Direct3D9/src/OgreD3D9Driver.cpp deleted file mode 100644 index 266b3a574e9..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9Driver.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9Driver.h" -#include "OgreD3D9VideoModeList.h" -#include "OgreD3D9VideoMode.h" - -#include - -namespace Ogre -{ - D3D9Driver::D3D9Driver() - { - mAdapterNumber = 0; - ZeroMemory( &mD3D9DeviceCaps, sizeof(mD3D9DeviceCaps) ); - ZeroMemory( &mAdapterIdentifier, sizeof(mAdapterIdentifier) ); - ZeroMemory( &mDesktopDisplayMode, sizeof(mDesktopDisplayMode) ); - mVideoModeList = NULL; - } - - D3D9Driver::D3D9Driver( const D3D9Driver &ob ) - { - mAdapterNumber = ob.mAdapterNumber; - mD3D9DeviceCaps = ob.mD3D9DeviceCaps; - mAdapterIdentifier = ob.mAdapterIdentifier; - mDesktopDisplayMode = ob.mDesktopDisplayMode; - mVideoModeList = NULL; - } - - D3D9Driver::D3D9Driver( unsigned int adapterNumber, - const D3DCAPS9& deviceCaps, - const D3DADAPTER_IDENTIFIER9& adapterIdentifier, - const D3DDISPLAYMODE& desktopDisplayMode ) - { - mAdapterNumber = adapterNumber; - mD3D9DeviceCaps = deviceCaps; - mAdapterIdentifier = adapterIdentifier; - mDesktopDisplayMode = desktopDisplayMode; - mVideoModeList = NULL; - } - - D3D9Driver::~D3D9Driver() - { - if (mVideoModeList != NULL) - { - OGRE_DELETE mVideoModeList; - mVideoModeList = NULL; - } - } - - String D3D9Driver::DriverName() const - { - return String(mAdapterIdentifier.Driver); - } - - String D3D9Driver::DriverDescription() const - { - StringStream str; - str << "Monitor-" << (mAdapterNumber+1) << "-" << mAdapterIdentifier.Description; - String driverDescription(str.str()); - StringUtil::trim(driverDescription); - - return driverDescription; - } - - D3D9VideoModeList* D3D9Driver::getVideoModeList() - { - if( !mVideoModeList ) - mVideoModeList = OGRE_NEW D3D9VideoModeList( this ); - - return mVideoModeList; - } -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9DriverList.cpp b/RenderSystems/Direct3D9/src/OgreD3D9DriverList.cpp deleted file mode 100644 index 07da63a8990..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9DriverList.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9DriverList.h" -#include "OgreLogManager.h" -#include "OgreException.h" -#include "OgreD3D9RenderSystem.h" - -namespace Ogre -{ - D3D9DriverList::D3D9DriverList() - { - enumerate(); - } - - D3D9DriverList::~D3D9DriverList(void) - { - mDriverList.clear(); - } - - BOOL D3D9DriverList::enumerate() - { - IDirect3D9* lpD3D9 = D3D9RenderSystem::getDirect3D9(); - - LogManager::getSingleton().logMessage( "D3D9: Driver Detection Starts" ); - for( UINT iAdapter=0; iAdapter < lpD3D9->GetAdapterCount(); ++iAdapter ) - { - D3DADAPTER_IDENTIFIER9 adapterIdentifier; - D3DDISPLAYMODE d3ddm; - D3DCAPS9 d3dcaps9; - - lpD3D9->GetAdapterIdentifier( iAdapter, 0, &adapterIdentifier ); - lpD3D9->GetAdapterDisplayMode( iAdapter, &d3ddm ); - lpD3D9->GetDeviceCaps( iAdapter, D3DDEVTYPE_HAL, &d3dcaps9 ); - - mDriverList.push_back( D3D9Driver( iAdapter, d3dcaps9, adapterIdentifier, d3ddm ) ); - } - - LogManager::getSingleton().logMessage( "D3D9: Driver Detection Ends" ); - - return TRUE; - } - - size_t D3D9DriverList::count() const - { - return mDriverList.size(); - } - - D3D9Driver* D3D9DriverList::item( size_t index ) - { - return &mDriverList.at( index ); - } - - D3D9Driver* D3D9DriverList::item( const String &name ) - { - std::vector::iterator it = mDriverList.begin(); - if (it == mDriverList.end()) - return NULL; - - for (;it != mDriverList.end(); ++it) - { - if (it->DriverDescription() == name) - return &(*it); - } - - return NULL; - } -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9EngineDll.cpp b/RenderSystems/Direct3D9/src/OgreD3D9EngineDll.cpp deleted file mode 100644 index aff3311d677..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9EngineDll.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreRoot.h" -#include "OgreD3D9Plugin.h" - -#ifndef OGRE_STATIC_LIB - -namespace Ogre -{ - D3D9Plugin* plugin; - - extern "C" void _OgreD3D9Export dllStartPlugin(void) throw() - { - plugin = OGRE_NEW D3D9Plugin(); - Root::getSingleton().installPlugin(plugin); - } - - extern "C" void _OgreD3D9Export dllStopPlugin(void) - { - Root::getSingleton().uninstallPlugin(plugin); - OGRE_DELETE plugin; - } -} -#endif \ No newline at end of file diff --git a/RenderSystems/Direct3D9/src/OgreD3D9GpuProgram.cpp b/RenderSystems/Direct3D9/src/OgreD3D9GpuProgram.cpp deleted file mode 100644 index 1db0c8b70a3..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9GpuProgram.cpp +++ /dev/null @@ -1,375 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9GpuProgram.h" -#include "OgreMatrix4.h" -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreD3D9Mappings.h" -#include "OgreResourceGroupManager.h" -#include "OgreD3D9RenderSystem.h" -#include "OgreGpuProgramManager.h" - -namespace Ogre { - - D3D9GpuProgram::CmdColumnMajorMatrices D3D9GpuProgram::msCmdColumnMajorMatrices; - D3D9GpuProgram::CmdExternalMicrocode D3D9GpuProgram::msCmdExternalMicrocode; - - //----------------------------------------------------------------------- - String D3D9GpuProgram::CmdColumnMajorMatrices::doGet(const void *target) const - { - return StringConverter::toString(static_cast(target)->getColumnMajorMatrices()); - } - void D3D9GpuProgram::CmdColumnMajorMatrices::doSet(void *target, const String& val) - { - static_cast(target)->setColumnMajorMatrices(StringConverter::parseBool(val)); - } - //----------------------------------------------------------------------- - String D3D9GpuProgram::CmdExternalMicrocode::doGet(const void *target) const - { - //D3D9GpuProgram* program=const_cast(static_cast(target)); - //LPD3DXBUFFER ptr=program->getExternalMicrocode(); - //nothing to do - return String(); - } - void D3D9GpuProgram::CmdExternalMicrocode::doSet(void *target, const String& val) - { - D3D9GpuProgram* program = const_cast(static_cast(target)); - const void* buffer = val.data(); - program->setExternalMicrocode(buffer, val.size()); - } - - //----------------------------------------------------------------------------- - D3D9GpuProgram::D3D9GpuProgram(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - : GpuProgram(creator, name, handle, group, isManual, loader), mExternalMicrocode(NULL), mColumnMajorMatrices(false) - { - if (createParamDictionary("D3D9GpuProgram")) - { - setupBaseParamDictionary(); - - ParamDictionary* dict = getParamDictionary(); - dict->addParameter(ParameterDef("column_major_matrices", - "Whether matrix packing in column-major order.", - PT_BOOL),&msCmdColumnMajorMatrices); - dict->addParameter(ParameterDef("external_micro_code", - "the cached external micro code data.", - PT_STRING),&msCmdExternalMicrocode); - } - } - - //----------------------------------------------------------------------------- - D3D9GpuProgram::~D3D9GpuProgram() - { - // have to call this here reather than in Resource destructor - // since calling virtual methods in base destructors causes crash - unload(); - } - - //----------------------------------------------------------------------------- - void D3D9GpuProgram::setExternalMicrocode(const void* pMicrocode, size_t size) - { - LPD3DXBUFFER pBuffer=0; - HRESULT hr=D3DXCreateBuffer(size, &pBuffer); - if(pBuffer) - { - memcpy(pBuffer->GetBufferPointer(), pMicrocode, size); - this->setExternalMicrocode(pBuffer); - SAFE_RELEASE(pBuffer); - } - } - //----------------------------------------------------------------------------- - void D3D9GpuProgram::setExternalMicrocode(ID3DXBuffer* pMicrocode) - { - SAFE_RELEASE(mExternalMicrocode); - mExternalMicrocode = pMicrocode; - if(mExternalMicrocode) - { - mExternalMicrocode->AddRef(); - } - } - //----------------------------------------------------------------------------- - LPD3DXBUFFER D3D9GpuProgram::getExternalMicrocode(void) - { - return mExternalMicrocode; - } - - //----------------------------------------------------------------------------- - void D3D9GpuProgram::loadImpl(void) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - for (uint i = 0; i < D3D9RenderSystem::getResourceCreationDeviceCount(); ++i) - { - IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getResourceCreationDevice(i); - - loadImpl(d3d9Device); - } - } - - //----------------------------------------------------------------------------- - void D3D9GpuProgram::loadImpl(IDirect3DDevice9* d3d9Device) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - if (mExternalMicrocode) - { - loadFromMicrocode(d3d9Device, mExternalMicrocode); - } - else - { - // Normal load-from-source approach - if (mLoadFromFile) - { - // find & load source code - DataStreamPtr stream = - ResourceGroupManager::getSingleton().openResource( - mFilename, mGroup, true, this); - mSource = stream->getAsString(); - } - - // Call polymorphic load - loadFromSource(d3d9Device); - } - } - //----------------------------------------------------------------------------- - void D3D9GpuProgram::loadFromSource(void) - { - loadFromSource(NULL); - } - //----------------------------------------------------------------------------- - void D3D9GpuProgram::loadFromSource( IDirect3DDevice9* d3d9Device ) - { - uint32 hash = _getHash(); - if ( GpuProgramManager::getSingleton().isMicrocodeAvailableInCache(hash) ) - { - getMicrocodeFromCache( d3d9Device, hash ); - } - else - { - compileMicrocode( d3d9Device ); - } - } - //----------------------------------------------------------------------- - void D3D9GpuProgram::getMicrocodeFromCache( IDirect3DDevice9* d3d9Device, uint32 id ) - { - GpuProgramManager::Microcode cacheMicrocode = - GpuProgramManager::getSingleton().getMicrocodeFromCache(id); - - LPD3DXBUFFER microcode; - HRESULT hr=D3DXCreateBuffer(cacheMicrocode->size(), µcode); - - if(microcode) - { - memcpy(microcode->GetBufferPointer(), cacheMicrocode->getPtr(), cacheMicrocode->size()); - } - - loadFromMicrocode(d3d9Device, microcode); - } - //----------------------------------------------------------------------- - void D3D9GpuProgram::compileMicrocode( IDirect3DDevice9* d3d9Device ) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - - // Populate compile flags - DWORD compileFlags = 0; - - // Create the shader - // Assemble source into microcode - LPD3DXBUFFER microcode; - LPD3DXBUFFER errors; - HRESULT hr = D3DXAssembleShader( - mSource.c_str(), - static_cast(mSource.length()), - NULL, // no #define support - NULL, // no #include support - compileFlags, // standard compile options - µcode, - &errors); - - if (FAILED(hr)) - { - String message = "Cannot assemble D3D9 shader " + mName + " Errors:\n" + - static_cast(errors->GetBufferPointer()); - errors->Release(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, message, - "D3D9GpuProgram::loadFromSource"); - } - else if ( GpuProgramManager::getSingleton().getSaveMicrocodesToCache() ) - { - // create microcode - auto newMicrocode = GpuProgramManager::createMicrocode(microcode->GetBufferSize()); - - // save microcode - memcpy(newMicrocode->getPtr(), microcode->GetBufferPointer(), microcode->GetBufferSize()); - - // add to the microcode to the cache - GpuProgramManager::getSingleton().addMicrocodeToCache(_getHash(), newMicrocode); - } - - loadFromMicrocode(d3d9Device, microcode); - - SAFE_RELEASE(microcode); - SAFE_RELEASE(errors); - } - //----------------------------------------------------------------------- - GpuProgramParametersSharedPtr D3D9GpuProgram::createParameters(void) - { - // Call superclass - GpuProgramParametersSharedPtr params = GpuProgram::createParameters(); - - // Need to transpose matrices if compiled with column-major matrices - params->setTransposeMatrices(mColumnMajorMatrices); - - return params; - } - - //----------------------------------------------------------------------------- - IDirect3DVertexShader9* D3D9GpuVertexProgram::getVertexShader( void ) - { - IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getActiveD3D9Device(); - - // Find the shader of this device. - auto it = mMapDeviceToShader.find(d3d9Device); - - // Shader was not found -> load it. - if (it == mMapDeviceToShader.end()) - { - loadImpl(d3d9Device); - it = mMapDeviceToShader.find(d3d9Device); - } - - return static_cast(it->second); - } - - //----------------------------------------------------------------------------- - void D3D9GpuProgram::loadFromMicrocode(IDirect3DDevice9* d3d9Device, ID3DXBuffer* microcode) - { - auto it = mMapDeviceToShader.find(d3d9Device); - - if (it != mMapDeviceToShader.end()) - { - if(mType == GPT_VERTEX_PROGRAM) - static_cast(it->second)->Release(); - else - static_cast(it->second)->Release(); - } - - if (isSupported()) - { - // Create the shader - IUnknown* pShader; - HRESULT hr; - - if (mType == GPT_VERTEX_PROGRAM) - hr = d3d9Device->CreateVertexShader(static_cast(microcode->GetBufferPointer()), - (IDirect3DVertexShader9**)&pShader); - else - hr = d3d9Device->CreatePixelShader(static_cast(microcode->GetBufferPointer()), - (IDirect3DPixelShader9**)&pShader); - - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Cannot create D3D9 shader " + mName + " from microcode."); - } - - mMapDeviceToShader[d3d9Device] = pShader; - } - else - { - LogManager::getSingleton().logMessage( - "Unsupported D3D9 shader '" + mName + "' was not loaded."); - - mMapDeviceToShader[d3d9Device] = NULL; - } - } - //----------------------------------------------------------------------------- - void D3D9GpuProgram::unloadImpl(void) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - auto it = mMapDeviceToShader.begin(); - - while (it != mMapDeviceToShader.end()) - { - if(mType == GPT_VERTEX_PROGRAM) - static_cast(it->second)->Release(); - else - static_cast(it->second)->Release(); - ++it; - } - mMapDeviceToShader.clear(); - SAFE_RELEASE(mExternalMicrocode); - } - //----------------------------------------------------------------------------- - void D3D9GpuProgram::notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device) - { - - } - - //----------------------------------------------------------------------------- - void D3D9GpuProgram::notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - // Find the shader of this device. - auto it = mMapDeviceToShader.find(d3d9Device); - - // Case shader found -> release it and erase from map. - if (it != mMapDeviceToShader.end()) - { - if(mType == GPT_VERTEX_PROGRAM) - static_cast(it->second)->Release(); - else - static_cast(it->second)->Release(); - mMapDeviceToShader.erase(it); - } - } - - //----------------------------------------------------------------------------- - IDirect3DPixelShader9* D3D9GpuProgram::getPixelShader() - { - IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getActiveD3D9Device(); - - // Find the shader of this device. - auto it = mMapDeviceToShader.find(d3d9Device); - - // Shader was not found -> load it. - if (it == mMapDeviceToShader.end()) - { - loadImpl(d3d9Device); - it = mMapDeviceToShader.find(d3d9Device); - } - - return static_cast(it->second); - } - //----------------------------------------------------------------------------- - -} - diff --git a/RenderSystems/Direct3D9/src/OgreD3D9GpuProgramManager.cpp b/RenderSystems/Direct3D9/src/OgreD3D9GpuProgramManager.cpp deleted file mode 100644 index 3d973e97582..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9GpuProgramManager.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9GpuProgramManager.h" -#include "OgreD3D9GpuProgram.h" -#include "OgreException.h" - -namespace Ogre { - //----------------------------------------------------------------------------- - String D3D9GpuProgramManager::currentLanguage = "vs_2_0"; - GpuProgram* D3D9GpuProgramManager::create(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - { - return OGRE_NEW D3D9GpuProgram(creator, name, handle, group, isManual, loader); - } - - const String& D3D9GpuProgramManager::getLanguage(void) const { - return currentLanguage; - } -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9HLSLProgram.cpp b/RenderSystems/Direct3D9/src/OgreD3D9HLSLProgram.cpp deleted file mode 100644 index c5ca8962fff..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9HLSLProgram.cpp +++ /dev/null @@ -1,726 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9HLSLProgram.h" -#include "OgreGpuProgramManager.h" -#include "OgreStringConverter.h" -#include "OgreD3D9GpuProgram.h" -#include "OgreLogManager.h" - -namespace Ogre { - //----------------------------------------------------------------------- - D3D9HLSLProgram::CmdTarget D3D9HLSLProgram::msCmdTarget; - D3D9HLSLProgram::CmdColumnMajorMatrices D3D9HLSLProgram::msCmdColumnMajorMatrices; - D3D9HLSLProgram::CmdOptimisation D3D9HLSLProgram::msCmdOptimisation; - D3D9HLSLProgram::CmdMicrocode D3D9HLSLProgram::msCmdMicrocode; - D3D9HLSLProgram::CmdAssemblerCode D3D9HLSLProgram::msCmdAssemblerCode; - D3D9HLSLProgram::CmdBackwardsCompatibility D3D9HLSLProgram::msCmdBackwardsCompatibility; - - //----------------------------------------------------------------------- - void D3D9HLSLProgram::prepareImpl() - { - HighLevelGpuProgram::prepareImpl(); - - mSyntaxCode = getTarget(); - uint32 seed = FastHash(mSyntaxCode.c_str(), mSyntaxCode.length()); - uint32 hash = _getHash(seed); - if ( GpuProgramManager::getSingleton().isMicrocodeAvailableInCache(hash) ) - { - getMicrocodeFromCache(hash); - } - else - { - compileMicrocode(); - - - if ( GpuProgramManager::getSingleton().getSaveMicrocodesToCache() ) - { - addMicrocodeToCache(hash); - } - } - } - //----------------------------------------------------------------------- - void D3D9HLSLProgram::getMicrocodeFromCache(uint32 id) - { - GpuProgramManager::Microcode cacheMicrocode = - GpuProgramManager::getSingleton().getMicrocodeFromCache(id); - - cacheMicrocode->seek(0); - - // get size the microcode - size_t microcodeSize = 0; - cacheMicrocode->read(µcodeSize, sizeof(size_t)); - - // get microcode - HRESULT hr=D3DXCreateBuffer(microcodeSize, &mMicroCode); - cacheMicrocode->read(mMicroCode->GetBufferPointer(), microcodeSize); - - // get size of param map - size_t parametersMapSize = 0; - cacheMicrocode->read(¶metersMapSize, sizeof(size_t)); - - // get params - for(size_t i = 0 ; i < parametersMapSize ; i++) - { - String paramName; - size_t stringSize = 0; - GpuConstantDefinition def; - - // get string size - cacheMicrocode->read(&stringSize, sizeof(size_t)); - - // get string - paramName.resize(stringSize); - cacheMicrocode->read(¶mName[0], stringSize); - - // get def - cacheMicrocode->read( &def, sizeof(GpuConstantDefinition)); - - mParametersMap.emplace(paramName, def); - - mLogicalToPhysical->bufferSize += def.elementSize * def.arraySize; - } - } - //----------------------------------------------------------------------- - const String& D3D9HLSLProgram::getTarget() const - { - if(mSyntaxCode == "hlsl") - { - static String vs_2_0 = "vs_2_0", ps_2_0 = "ps_2_0"; - return mType == GPT_VERTEX_PROGRAM ? vs_2_0 : ps_2_0; - } - - return mSyntaxCode; - } - - void D3D9HLSLProgram::compileMicrocode(void) - { - // Populate preprocessor defines - String stringBuffer; - std::vector defines; - const D3DXMACRO* pDefines = 0; - stringBuffer = appendBuiltinDefines(mPreprocessorDefines); - - for(const auto& def : parseDefines(stringBuffer)) - { - defines.push_back({def.first, def.second}); - } - - // Add NULL terminator - defines.push_back({0, 0}); - - pDefines = &defines[0]; - - // Populate compile flags - DWORD compileFlags = 0; - if (mColumnMajorMatrices) - compileFlags |= D3DXSHADER_PACKMATRIX_COLUMNMAJOR; - else - compileFlags |= D3DXSHADER_PACKMATRIX_ROWMAJOR; - if (mBackwardsCompatibility) - compileFlags |= D3DXSHADER_ENABLE_BACKWARDS_COMPATIBILITY; - -#if OGRE_DEBUG_MODE - compileFlags |= D3DXSHADER_DEBUG; -#endif - switch (mOptimisationLevel) - { - case OPT_DEFAULT: - compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL1; - break; - case OPT_NONE: - compileFlags |= D3DXSHADER_SKIPOPTIMIZATION; - break; - case OPT_0: - compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL0; - break; - case OPT_1: - compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL1; - break; - case OPT_2: - compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL2; - break; - case OPT_3: - compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL3; - break; - } - - - LPD3DXBUFFER errors = 0; - - // handle includes - mSource = _resolveIncludes(mSource, this, mFilename, true); - - LPD3DXCONSTANTTABLE pConstTable; - - // Compile & assemble into microcode - HRESULT hr = D3DXCompileShader( - mSource.c_str(), - static_cast(mSource.length()), - pDefines, - NULL, - mEntryPoint.c_str(), - mSyntaxCode.c_str(), - compileFlags, - &mMicroCode, - &errors, - &pConstTable); - - if (FAILED(hr)) - { - String message = "Cannot assemble D3D9 high-level shader " + mName; - - if( errors ) - { - message += String(" Errors:\n") + static_cast(errors->GetBufferPointer()); - errors->Release(); - } - - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, message); - } - else - { - - // Get contents of the constant table - D3DXCONSTANTTABLE_DESC desc; - HRESULT hr = pConstTable->GetDesc(&desc); - - createParameterMappingStructures(true); - - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Cannot retrieve constant descriptions from HLSL program"); - } - // Iterate over the constants - for (unsigned int i = 0; i < desc.Constants; ++i) - { - // Recursively descend through the structure levels - processParamElement(pConstTable, NULL, "", i); - } - - - SAFE_RELEASE(pConstTable); - } - } - //----------------------------------------------------------------------- - void D3D9HLSLProgram::addMicrocodeToCache(uint32 id) - { - // add to the microcode to the cache - size_t sizeOfBuffer = sizeof(size_t) + mMicroCode->GetBufferSize() + sizeof(size_t) + mParametersMapSizeAsBuffer; - - // create microcode - auto newMicrocode = GpuProgramManager::createMicrocode(sizeOfBuffer); - - // save size of microcode - size_t microcodeSize = mMicroCode->GetBufferSize(); - newMicrocode->write(µcodeSize, sizeof(size_t)); - - // save microcode - newMicrocode->write(mMicroCode->GetBufferPointer(), microcodeSize); - - - // save size of param map - size_t parametersMapSize = mParametersMap.size(); - newMicrocode->write(¶metersMapSize, sizeof(size_t)); - - // save params - GpuConstantDefinitionMap::const_iterator iter = mParametersMap.begin(); - GpuConstantDefinitionMap::const_iterator iterE = mParametersMap.end(); - for (; iter != iterE ; ++iter) - { - const String & paramName = iter->first; - const GpuConstantDefinition & def = iter->second; - - // save string size - size_t stringSize = paramName.size(); - newMicrocode->write(&stringSize, sizeof(size_t)); - - // save string - newMicrocode->write(¶mName[0], stringSize); - - // save def - newMicrocode->write(&def, sizeof(GpuConstantDefinition)); - } - - - // add to the microcode to the cache - GpuProgramManager::getSingleton().addMicrocodeToCache(id, newMicrocode); - } - //----------------------------------------------------------------------- - void D3D9HLSLProgram::createLowLevelImpl(void) - { - if (!mCompileError) - { - // Create a low-level program - mAssemblerProgram = - GpuProgramManager::getSingleton().createProgram( - mName+"/Delegate", - mGroup, - getTarget(), - mType); - mAssemblerProgram->setSource(""); - static_cast(mAssemblerProgram.get())->setExternalMicrocode(mMicroCode); - } - - } - //----------------------------------------------------------------------- - void D3D9HLSLProgram::unloadHighLevelImpl(void) - { - mParametersMap.clear(); - mParametersMapSizeAsBuffer = 0; - SAFE_RELEASE(mMicroCode); - } - //----------------------------------------------------------------------- - void D3D9HLSLProgram::buildConstantDefinitions() - { - mConstantDefs->bufferSize = mLogicalToPhysical->bufferSize; - - GpuConstantDefinitionMap::const_iterator iter = mParametersMap.begin(); - GpuConstantDefinitionMap::const_iterator iterE = mParametersMap.end(); - for (; iter != iterE ; ++iter) - { - GpuConstantDefinition def = iter->second; - - mConstantDefs->map.emplace(iter->first, iter->second); - - // Record logical / physical mapping - OGRE_LOCK_MUTEX(mLogicalToPhysical->mutex); - mLogicalToPhysical->map.emplace(def.logicalIndex, - GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, GPV_GLOBAL, def.isFloat() ? BCT_FLOAT : BCT_INT)); - } - - } - //----------------------------------------------------------------------- - void D3D9HLSLProgram::processParamElement(LPD3DXCONSTANTTABLE pConstTable, D3DXHANDLE parent, String prefix, - unsigned int index) - { - D3DXHANDLE hConstant = pConstTable->GetConstant(parent, index); - - // Since D3D HLSL doesn't deal with naming of array and struct parameters - // automatically, we have to do it by hand - - D3DXCONSTANT_DESC desc; - unsigned int numParams = 1; - HRESULT hr = pConstTable->GetConstantDesc(hConstant, &desc, &numParams); - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Cannot retrieve constant description from HLSL program.", - "D3D9HLSLProgram::processParamElement"); - } - - String paramName = desc.Name; - // trim the odd '$' which appears at the start of the names in HLSL - if (paramName.at(0) == '$') - paramName.erase(paramName.begin()); - - // Also trim the '[0]' suffix if it exists, we will add our own indexing later - if (StringUtil::endsWith(paramName, "[0]", false)) - { - paramName.erase(paramName.size() - 3); - } - - - if (desc.Class == D3DXPC_STRUCT) - { - // work out a new prefix for nested members, if it's an array, we need an index - prefix = prefix + paramName + "."; - // Cascade into struct - for (unsigned int i = 0; i < desc.StructMembers; ++i) - { - processParamElement(pConstTable, hConstant, prefix, i); - } - } - else - { - // Process params - if (desc.Type == D3DXPT_FLOAT || desc.Type == D3DXPT_INT || desc.Type == D3DXPT_BOOL) - { - size_t paramIndex = desc.RegisterIndex; - String name = prefix + paramName; - - GpuConstantDefinition def; - def.logicalIndex = paramIndex; - // populate type, array size & element size - populateDef(desc, def); - def.physicalIndex = mLogicalToPhysical->bufferSize*4; - OGRE_LOCK_MUTEX(mLogicalToPhysical->mutex); - mLogicalToPhysical->map.emplace(paramIndex, - GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, GPV_GLOBAL, def.isFloat() ? BCT_FLOAT : BCT_INT)); - mLogicalToPhysical->bufferSize += def.arraySize * def.elementSize; - - if( mParametersMap.find(name) == mParametersMap.end()) - { - mParametersMap.emplace(name, def); - mParametersMapSizeAsBuffer += sizeof(size_t); - mParametersMapSizeAsBuffer += name.size(); - mParametersMapSizeAsBuffer += sizeof(GpuConstantDefinition); - } - - } - } - - } - //----------------------------------------------------------------------- - void D3D9HLSLProgram::populateDef(D3DXCONSTANT_DESC& d3dDesc, GpuConstantDefinition& def) const - { - def.arraySize = d3dDesc.Elements; - switch(d3dDesc.Type) - { - case D3DXPT_INT: - switch(d3dDesc.Columns) - { - case 1: - def.constType = GCT_INT1; - break; - case 2: - def.constType = GCT_INT2; - break; - case 3: - def.constType = GCT_INT3; - break; - case 4: - def.constType = GCT_INT4; - break; - } // columns - break; - case D3DXPT_FLOAT: - switch(d3dDesc.Class) - { - case D3DXPC_MATRIX_COLUMNS: - case D3DXPC_MATRIX_ROWS: - { - int firstDim, secondDim; - firstDim = d3dDesc.RegisterCount / d3dDesc.Elements; - if (d3dDesc.Class == D3DXPC_MATRIX_ROWS) - { - secondDim = d3dDesc.Columns; - } - else - { - secondDim = d3dDesc.Rows; - } - switch(firstDim) - { - case 2: - switch(secondDim) - { - case 2: - def.constType = GCT_MATRIX_2X2; - def.elementSize = 8; // HLSL always packs - break; - case 3: - def.constType = GCT_MATRIX_2X3; - def.elementSize = 8; // HLSL always packs - break; - case 4: - def.constType = GCT_MATRIX_2X4; - def.elementSize = 8; - break; - } // columns - break; - case 3: - switch(secondDim) - { - case 2: - def.constType = GCT_MATRIX_3X2; - def.elementSize = 12; // HLSL always packs - break; - case 3: - def.constType = GCT_MATRIX_3X3; - def.elementSize = 12; // HLSL always packs - break; - case 4: - def.constType = GCT_MATRIX_3X4; - def.elementSize = 12; - break; - } // columns - break; - case 4: - switch(secondDim) - { - case 2: - def.constType = GCT_MATRIX_4X2; - def.elementSize = 16; // HLSL always packs - break; - case 3: - def.constType = GCT_MATRIX_4X3; - def.elementSize = 16; // HLSL always packs - break; - case 4: - def.constType = GCT_MATRIX_4X4; - def.elementSize = 16; - break; - } // secondDim - break; - - } // firstDim - } - break; - case D3DXPC_SCALAR: - case D3DXPC_VECTOR: - switch(d3dDesc.Columns) - { - case 1: - def.constType = GCT_FLOAT1; - break; - case 2: - def.constType = GCT_FLOAT2; - break; - case 3: - def.constType = GCT_FLOAT3; - break; - case 4: - def.constType = GCT_FLOAT4; - break; - } // columns - break; - } - default: - // not mapping samplers, don't need to take the space - break; - }; - - // D3D9 pads to 4 elements - def.elementSize = GpuConstantDefinition::getElementSize(def.constType, true); - - - } - - LPD3DXBUFFER D3D9HLSLProgram::getMicroCode() - { - return mMicroCode; - } - - //----------------------------------------------------------------------- - D3D9HLSLProgram::D3D9HLSLProgram(ResourceManager* creator, const String& name, - ResourceHandle handle, const String& group, bool isManual, - ManualResourceLoader* loader) - : HighLevelGpuProgram(creator, name, handle, group, isManual, loader) - , mColumnMajorMatrices(true) - , mBackwardsCompatibility(false) - , mMicroCode(NULL) - , mOptimisationLevel(OPT_DEFAULT) - , mParametersMapSizeAsBuffer(0) - { - if (createParamDictionary("D3D9HLSLProgram")) - { - setupBaseParamDictionary(); - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter(ParameterDef("target", - "Name of the assembler target to compile down to.", - PT_STRING),&msCmdTarget); - dict->addParameter(ParameterDef("column_major_matrices", - "Whether matrix packing in column-major order.", - PT_BOOL),&msCmdColumnMajorMatrices); - dict->addParameter(ParameterDef("optimisation_level", - "The optimisation level to use.", - PT_STRING),&msCmdOptimisation); - dict->addParameter(ParameterDef("micro_code", - "the micro code.", - PT_STRING),&msCmdMicrocode); - dict->addParameter(ParameterDef("assemble_code", - "the assemble code.", - PT_STRING),&msCmdAssemblerCode); - dict->addParameter(ParameterDef("backwards_compatibility", - "Enable backwards compatibility mode.", - PT_BOOL),&msCmdBackwardsCompatibility); - } - - } - //----------------------------------------------------------------------- - D3D9HLSLProgram::~D3D9HLSLProgram() - { - // have to call this here reather than in Resource destructor - // since calling virtual methods in base destructors causes crash - if (isLoaded()) - { - unload(); - } - else - { - unloadHighLevel(); - } - } - //----------------------------------------------------------------------- - GpuProgramParametersSharedPtr D3D9HLSLProgram::createParameters(void) - { - // Call superclass - GpuProgramParametersSharedPtr params = HighLevelGpuProgram::createParameters(); - - // Need to transpose matrices if compiled with column-major matrices - params->setTransposeMatrices(mColumnMajorMatrices); - - return params; - } - //----------------------------------------------------------------------- - void D3D9HLSLProgram::setTarget(const String& target) - { - std::vector profiles = StringUtil::split(target, " "); - - // find first supported format - for(unsigned int i = 0 ; i < profiles.size() ; i++) - { - String & currentProfile = profiles[i]; - if(GpuProgramManager::getSingleton().isSyntaxSupported(currentProfile)) - { - mSyntaxCode = currentProfile; - return; - } - } - - mSyntaxCode = profiles.front(); - } - - //----------------------------------------------------------------------- - const String& D3D9HLSLProgram::getLanguage(void) const - { - static const String language = "hlsl"; - - return language; - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - String D3D9HLSLProgram::CmdTarget::doGet(const void *target) const - { - return static_cast(target)->getTarget(); - } - void D3D9HLSLProgram::CmdTarget::doSet(void *target, const String& val) - { - static_cast(target)->setTarget(val); - } - //----------------------------------------------------------------------- - String D3D9HLSLProgram::CmdColumnMajorMatrices::doGet(const void *target) const - { - return StringConverter::toString(static_cast(target)->getColumnMajorMatrices()); - } - void D3D9HLSLProgram::CmdColumnMajorMatrices::doSet(void *target, const String& val) - { - static_cast(target)->setColumnMajorMatrices(StringConverter::parseBool(val)); - } - //----------------------------------------------------------------------- - String D3D9HLSLProgram::CmdBackwardsCompatibility::doGet(const void *target) const - { - return StringConverter::toString(static_cast(target)->getBackwardsCompatibility()); - } - void D3D9HLSLProgram::CmdBackwardsCompatibility::doSet(void *target, const String& val) - { - static_cast(target)->setBackwardsCompatibility(StringConverter::parseBool(val)); - } - //----------------------------------------------------------------------- - String D3D9HLSLProgram::CmdOptimisation::doGet(const void *target) const - { - switch(static_cast(target)->getOptimisationLevel()) - { - default: - case OPT_DEFAULT: - return "default"; - case OPT_NONE: - return "none"; - case OPT_0: - return "0"; - case OPT_1: - return "1"; - case OPT_2: - return "2"; - case OPT_3: - return "3"; - } - } - void D3D9HLSLProgram::CmdOptimisation::doSet(void *target, const String& val) - { - if (StringUtil::startsWith(val, "default", true)) - static_cast(target)->setOptimisationLevel(OPT_DEFAULT); - else if (StringUtil::startsWith(val, "none", true)) - static_cast(target)->setOptimisationLevel(OPT_NONE); - else if (StringUtil::startsWith(val, "0", true)) - static_cast(target)->setOptimisationLevel(OPT_0); - else if (StringUtil::startsWith(val, "1", true)) - static_cast(target)->setOptimisationLevel(OPT_1); - else if (StringUtil::startsWith(val, "2", true)) - static_cast(target)->setOptimisationLevel(OPT_2); - else if (StringUtil::startsWith(val, "3", true)) - static_cast(target)->setOptimisationLevel(OPT_3); - } - - //----------------------------------------------------------------------- - String D3D9HLSLProgram::CmdMicrocode::doGet(const void *target) const - { - D3D9HLSLProgram* program=const_cast(static_cast(target)); - LPD3DXBUFFER buffer=program->getMicroCode(); - if(buffer) - { - char* str =static_cast(buffer->GetBufferPointer()); - size_t size=static_cast(buffer->GetBufferSize()); - Ogre::String code; - code.assign(str,size); - return code; - } - else - { - return String(); - } - } - void D3D9HLSLProgram::CmdMicrocode::doSet(void *target, const String& val) - { - //nothing to do - //static_cast(target)->setColumnMajorMatrices(StringConverter::parseBool(val)); - } - //----------------------------------------------------------------------- - String D3D9HLSLProgram::CmdAssemblerCode::doGet(const void *target) const - { - D3D9HLSLProgram* program=const_cast(static_cast(target)); - LPD3DXBUFFER buffer=program->getMicroCode(); - if(buffer) - { - CONST DWORD* code =static_cast(buffer->GetBufferPointer()); - LPD3DXBUFFER pDisassembly=0; - HRESULT hr=D3DXDisassembleShader(code,FALSE,"// assemble code from D3D9HLSLProgram\n",&pDisassembly); - if(pDisassembly) - { - char* str =static_cast(pDisassembly->GetBufferPointer()); - size_t size=static_cast(pDisassembly->GetBufferSize()); - Ogre::String assemble_code; - assemble_code.assign(str,size); - pDisassembly->Release(); - return assemble_code; - } - return String(); - } - else - { - return String(); - } - } - void D3D9HLSLProgram::CmdAssemblerCode::doSet(void *target, const String& val) - { - //nothing to do - //static_cast(target)->setColumnMajorMatrices(StringConverter::parseBool(val)); - } -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9HLSLProgramFactory.cpp b/RenderSystems/Direct3D9/src/OgreD3D9HLSLProgramFactory.cpp deleted file mode 100644 index b89f79d3564..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9HLSLProgramFactory.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreD3D9HLSLProgramFactory.h" -#include "OgreString.h" -#include "OgreD3D9HLSLProgram.h" - -namespace Ogre { - //----------------------------------------------------------------------- - String D3D9HLSLProgramFactory::sLanguageName = "hlsl"; - //----------------------------------------------------------------------- - D3D9HLSLProgramFactory::D3D9HLSLProgramFactory() - { - } - //----------------------------------------------------------------------- - D3D9HLSLProgramFactory::~D3D9HLSLProgramFactory() - { - } - //----------------------------------------------------------------------- - const String& D3D9HLSLProgramFactory::getLanguage(void) const - { - return sLanguageName; - } - //----------------------------------------------------------------------- - GpuProgram* D3D9HLSLProgramFactory::create(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - { - return OGRE_NEW D3D9HLSLProgram(creator, name, handle, group, isManual, loader); - } -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9HardwareBuffer.cpp b/RenderSystems/Direct3D9/src/OgreD3D9HardwareBuffer.cpp deleted file mode 100644 index deafe944f4d..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9HardwareBuffer.cpp +++ /dev/null @@ -1,463 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9HardwareBuffer.h" -#include "OgreD3D9Mappings.h" -#include "OgreException.h" -#include "OgreD3D9HardwareBufferManager.h" -#include "OgreD3D9RenderSystem.h" -#include "OgreRoot.h" -#include "OgreD3D9Device.h" -#include "OgreD3D9ResourceManager.h" -#include "OgreDefaultHardwareBufferManager.h" - -namespace Ogre { - - //--------------------------------------------------------------------- - D3D9HardwareBuffer::D3D9HardwareBuffer(D3DFORMAT type, size_t sizeInBytes, - Usage usage, - bool useShadowBuffer) - : HardwareBuffer(usage, useShadowBuffer) - { - mType = type; - mSizeInBytes = sizeInBytes; - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - // Set the desired memory pool. - mBufferDesc.Pool = usage == HBU_CPU_ONLY ? D3DPOOL_SYSTEMMEM : D3DPOOL_DEFAULT; - - // Set source buffer to NULL. - mSourceBuffer = NULL; - mSourceLockedBytes = NULL; - - // Create buffer resource(s). - for (uint i = 0; i < D3D9RenderSystem::getResourceCreationDeviceCount(); ++i) - { - IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getResourceCreationDevice(i); - - createBuffer(d3d9Device, mBufferDesc.Pool, false); - } - - if (useShadowBuffer) - { - mShadowBuffer.reset(new DefaultHardwareBuffer(mSizeInBytes)); - } - } - //--------------------------------------------------------------------- - D3D9HardwareBuffer::~D3D9HardwareBuffer() - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - DeviceToBufferResourcesIterator it = mMapDeviceToBufferResources.begin(); - - while (it != mMapDeviceToBufferResources.end()) - { - SAFE_RELEASE(it->second->mBuffer); - if (it->second != NULL) - { - OGRE_FREE (it->second, MEMCATEGORY_RENDERSYS); - it->second = NULL; - } - ++it; - } - mMapDeviceToBufferResources.clear(); - } - //--------------------------------------------------------------------- - void* D3D9HardwareBuffer::lockImpl(size_t offset, - size_t length, LockOptions options) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - DeviceToBufferResourcesIterator it = mMapDeviceToBufferResources.begin(); - IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getActiveD3D9DeviceIfExists(); - - while (it != mMapDeviceToBufferResources.end()) - { - BufferResources* bufferResources = it->second; - - if (options != HBL_READ_ONLY) - bufferResources->mOutOfDate = true; - - // Case it is the first buffer lock in this frame. - if (bufferResources->mLockLength == 0) - { - if (offset < bufferResources->mLockOffset) - bufferResources->mLockOffset = offset; - if (length > bufferResources->mLockLength) - bufferResources->mLockLength = length; - } - - // Case buffer already locked in this frame. - else - { - size_t highPoint = std::max( offset + length, - bufferResources->mLockOffset + bufferResources->mLockLength ); - bufferResources->mLockOffset = std::min( bufferResources->mLockOffset, offset ); - bufferResources->mLockLength = highPoint - bufferResources->mLockOffset; - } - - bufferResources->mLockOptions = options; - - //We will switch the source buffer to the active d3d9device as we may decide to only update it during unlock - if (it->first == d3d9Device) - mSourceBuffer = it->second; - - ++it; - } - - // Lock the source buffer. - mSourceLockedBytes = _lockBuffer(mSourceBuffer, mSourceBuffer->mLockOffset, mSourceBuffer->mLockLength); - return mSourceLockedBytes; - } - //--------------------------------------------------------------------- - void D3D9HardwareBuffer::unlockImpl(void) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - //check if we can delay the update of secondary buffer resources - if (!mShadowBuffer) - { - DeviceToBufferResourcesIterator it = mMapDeviceToBufferResources.begin(); - uint nextFrameNumber = Root::getSingleton().getNextFrameNumber(); - - while (it != mMapDeviceToBufferResources.end()) - { - BufferResources* bufferResources = it->second; - - if (bufferResources->mOutOfDate && - bufferResources->mBuffer != NULL && - nextFrameNumber - bufferResources->mLastUsedFrame <= 1) - { - if (mSourceBuffer != bufferResources) - { - updateBufferResources(mSourceLockedBytes, bufferResources); - } - } - - ++it; - } - } - - _unlockBuffer(mSourceBuffer); - mSourceLockedBytes = NULL; - } - //--------------------------------------------------------------------- - void D3D9HardwareBuffer::readData(size_t offset, size_t length, - void* pDest) - { - // There is no functional interface in D3D, just do via manual - // lock, copy & unlock - void* pSrc = this->lock(offset, length, HardwareBuffer::HBL_READ_ONLY); - memcpy(pDest, pSrc, length); - this->unlock(); - - } - //--------------------------------------------------------------------- - void D3D9HardwareBuffer::writeData(size_t offset, size_t length, - const void* pSource, - bool discardWholeBuffer) - { - // There is no functional interface in D3D, just do via manual - // lock, copy & unlock - void* pDst = this->lock(offset, length, - discardWholeBuffer ? HardwareBuffer::HBL_DISCARD : HardwareBuffer::HBL_NORMAL); - memcpy(pDst, pSource, length); - this->unlock(); - } - //--------------------------------------------------------------------- - void D3D9HardwareBuffer::notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - if (D3D9RenderSystem::getResourceManager()->getCreationPolicy() == RCP_CREATE_ON_ALL_DEVICES) - createBuffer(d3d9Device, mBufferDesc.Pool, true); - } - //--------------------------------------------------------------------- - void D3D9HardwareBuffer::notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - DeviceToBufferResourcesIterator it = mMapDeviceToBufferResources.find(d3d9Device); - - if (it != mMapDeviceToBufferResources.end()) - { - // Case this is the source buffer. - if (it->second == mSourceBuffer) - { - mSourceBuffer = NULL; - } - - SAFE_RELEASE(it->second->mBuffer); - if (it->second != NULL) - { - OGRE_FREE (it->second, MEMCATEGORY_RENDERSYS); - it->second = NULL; - } - mMapDeviceToBufferResources.erase(it); - - // Case source buffer just destroyed -> switch to another one if exits. - if (mSourceBuffer == NULL && mMapDeviceToBufferResources.size() > 0) - { - mSourceBuffer = mMapDeviceToBufferResources.begin()->second; - } - } - } - //--------------------------------------------------------------------- - void D3D9HardwareBuffer::notifyOnDeviceLost(IDirect3DDevice9* d3d9Device) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - if (mBufferDesc.Pool == D3DPOOL_DEFAULT) - { - DeviceToBufferResourcesIterator it = mMapDeviceToBufferResources.find(d3d9Device); - - if (it != mMapDeviceToBufferResources.end()) - { - SAFE_RELEASE(it->second->mBuffer); - } - } - } - //--------------------------------------------------------------------- - void D3D9HardwareBuffer::notifyOnDeviceReset(IDirect3DDevice9* d3d9Device) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - if (mBufferDesc.Pool == D3DPOOL_DEFAULT) - { - createBuffer(d3d9Device, mBufferDesc.Pool, true); - } - } - //--------------------------------------------------------------------- - void D3D9HardwareBuffer::createBuffer(IDirect3DDevice9* d3d9Device, D3DPOOL ePool, bool updateNewBuffer) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - BufferResources* bufferResources; - HRESULT hr; - - DeviceToBufferResourcesIterator it; - - // Find the vertex buffer of this device. - it = mMapDeviceToBufferResources.find(d3d9Device); - if (it != mMapDeviceToBufferResources.end()) - { - bufferResources = it->second; - SAFE_RELEASE(bufferResources->mBuffer); - } - else - { - bufferResources = OGRE_ALLOC_T(BufferResources, 1, MEMCATEGORY_RENDERSYS); - mMapDeviceToBufferResources[d3d9Device] = bufferResources; - } - - bufferResources->mBuffer = NULL; - bufferResources->mOutOfDate = true; - bufferResources->mLockOffset = 0; - bufferResources->mLockLength = getSizeInBytes(); - bufferResources->mLockOptions = HBL_NORMAL; - bufferResources->mLastUsedFrame = Root::getSingleton().getNextFrameNumber(); - - if(mType == D3DFMT_VERTEXDATA) - { - // Create the vertex buffer - hr = d3d9Device->CreateVertexBuffer( - static_cast(mSizeInBytes), - D3D9Mappings::get(mUsage), - 0, // No FVF here, thank you. - ePool, - (IDirect3DVertexBuffer9**)&bufferResources->mBuffer, - NULL); - } - else{ - // Create the Index buffer - hr = d3d9Device->CreateIndexBuffer( - static_cast(mSizeInBytes), - D3D9Mappings::get(mUsage), - mType, - ePool, - (IDirect3DIndexBuffer9**)&bufferResources->mBuffer, - NULL); - } - - if (FAILED(hr)) - { - String msg = DXGetErrorDescription(hr); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Cannot restore D3D9 buffer: " + msg); - } - - if(mType == D3DFMT_VERTEXDATA) - { - hr = static_cast(bufferResources->mBuffer)->GetDesc(&mBufferDesc); - } - else - { - hr = static_cast(bufferResources->mBuffer)->GetDesc((D3DINDEXBUFFER_DESC*)&mBufferDesc); - } - if (FAILED(hr)) - { - String msg = DXGetErrorDescription(hr); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Cannot get D3D9 buffer desc: " + msg); - } - - // Update source buffer if need to. - if (mSourceBuffer == NULL) - { - mSourceBuffer = bufferResources; - } - - // This is a new buffer and source buffer exists we must update the content now - // to prevent situation where the source buffer will be destroyed and we won't be able to restore its content. - // This is except for during the creation process of the class when there is no data yet to update. - else if (updateNewBuffer) - { - updateBufferContent(bufferResources); - } - } - //--------------------------------------------------------------------- - IDirect3DResource9* D3D9HardwareBuffer::getD3D9Resource(void) - { - IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getActiveD3D9Device(); - DeviceToBufferResourcesIterator it; - - // Find the vertex buffer of this device. - it = mMapDeviceToBufferResources.find(d3d9Device); - - // Case vertex buffer was not found for the current device -> create it. - if (it == mMapDeviceToBufferResources.end() || it->second->mBuffer == NULL) - { - createBuffer(d3d9Device, mBufferDesc.Pool, true); - it = mMapDeviceToBufferResources.find(d3d9Device); - } - - // Make sure that the buffer content is updated. - updateBufferContent(it->second); - - it->second->mLastUsedFrame = Root::getSingleton().getNextFrameNumber(); - - return it->second->mBuffer; - } - - //--------------------------------------------------------------------- - void D3D9HardwareBuffer::updateBufferContent(BufferResources* bufferResources) - { - if (bufferResources->mOutOfDate) - { - if (mShadowBuffer != NULL) - { - const char* shadowData = (const char*)mShadowBuffer->lock(bufferResources->mLockOffset, bufferResources->mLockLength, HBL_NORMAL); - updateBufferResources(shadowData, bufferResources); - mShadowBuffer->unlock(); - } - else if (mSourceBuffer != bufferResources && (mUsage & HBU_DETAIL_WRITE_ONLY) == 0) - { - mSourceBuffer->mLockOptions = HBL_READ_ONLY; - mSourceLockedBytes = _lockBuffer(mSourceBuffer, bufferResources->mLockOffset, bufferResources->mLockLength); - updateBufferResources(mSourceLockedBytes, bufferResources); - _unlockBuffer(mSourceBuffer); - mSourceLockedBytes = NULL; - } - } - } - - //--------------------------------------------------------------------- - bool D3D9HardwareBuffer::updateBufferResources(const char* systemMemoryBuffer, - BufferResources* bufferResources) - { - assert(bufferResources != NULL); - assert(bufferResources->mBuffer != NULL); - assert(bufferResources->mOutOfDate); - - - char* dstBytes = _lockBuffer(bufferResources, bufferResources->mLockOffset, bufferResources->mLockLength); - memcpy(dstBytes, systemMemoryBuffer, bufferResources->mLockLength); - _unlockBuffer(bufferResources); - - return true; - } - - //--------------------------------------------------------------------- - char* D3D9HardwareBuffer::_lockBuffer(BufferResources* bufferResources, size_t offset, size_t length) - { - HRESULT hr; - char* pSourceBytes; - - - // Lock the buffer. - if(mType == D3DFMT_VERTEXDATA) - { - hr = static_cast(bufferResources->mBuffer)->Lock( - static_cast(offset), - static_cast(length), - (void**)&pSourceBytes, - D3D9Mappings::get(mSourceBuffer->mLockOptions, mUsage)); - } - else - { - hr = static_cast(bufferResources->mBuffer)->Lock( - static_cast(offset), - static_cast(length), - (void**)&pSourceBytes, - D3D9Mappings::get(mSourceBuffer->mLockOptions, mUsage)); - } - - if (FAILED(hr)) - { - String msg = DXGetErrorDescription(hr); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Cannot lock D3D9 buffer: " + msg); - } - - return pSourceBytes; - } - - //--------------------------------------------------------------------- - void D3D9HardwareBuffer::_unlockBuffer( BufferResources* bufferResources ) - { - HRESULT hr; - - // Unlock the buffer. - if(mType == D3DFMT_VERTEXDATA) - { - hr = static_cast(bufferResources->mBuffer)->Unlock(); - } - else - { - hr = static_cast(bufferResources->mBuffer)->Unlock(); - } - if (FAILED(hr)) - { - String msg = DXGetErrorDescription(hr); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Cannot unlock D3D9 buffer: " + msg); - } - - // Reset attributes. - bufferResources->mOutOfDate = false; - bufferResources->mLockOffset = mSizeInBytes; - bufferResources->mLockLength = 0; - bufferResources->mLockOptions = HBL_NORMAL; - - } -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9HardwareBufferManager.cpp b/RenderSystems/Direct3D9/src/OgreD3D9HardwareBufferManager.cpp deleted file mode 100644 index 03f2f9ab244..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9HardwareBufferManager.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9RenderSystem.h" -#include "OgreD3D9HardwareBufferManager.h" -#include "OgreD3D9HardwareBuffer.h" -#include "OgreD3D9VertexDeclaration.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreException.h" - -namespace Ogre { - //----------------------------------------------------------------------- - D3D9HardwareBufferManager::D3D9HardwareBufferManager() : mAutoHardwareBufferManagement(false) - { - } - //----------------------------------------------------------------------- - D3D9HardwareBufferManager::~D3D9HardwareBufferManager() - { - destroyAllDeclarations(); - destroyAllBindings(); - } - //----------------------------------------------------------------------- - HardwareVertexBufferSharedPtr - D3D9HardwareBufferManager:: - createVertexBuffer(size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, - bool useShadowBuffer) - { - assert (numVerts > 0); - // Allocate the system memory buffer for restoring after device lost. - useShadowBuffer = useShadowBuffer || ((usage & HBU_DETAIL_WRITE_ONLY) && mAutoHardwareBufferManagement); - - auto impl = new D3D9HardwareBuffer(D3DFMT_VERTEXDATA, vertexSize * numVerts, usage, useShadowBuffer); - auto buf = std::make_shared(this, vertexSize, numVerts, impl); - { - OGRE_LOCK_MUTEX(mVertexBuffersMutex); - mVertexBuffers.insert(buf.get()); - } - return buf; - } - //----------------------------------------------------------------------- - HardwareIndexBufferSharedPtr - D3D9HardwareBufferManager:: - createIndexBuffer(HardwareIndexBuffer::IndexType itype, size_t numIndexes, - HardwareBuffer::Usage usage, bool useShadowBuffer) - { - assert (numIndexes > 0); - // Allocate the system memory buffer for restoring after device lost. - useShadowBuffer = useShadowBuffer || ((usage & HBU_DETAIL_WRITE_ONLY) && mAutoHardwareBufferManagement); - - auto indexSize = HardwareIndexBuffer::indexSize(itype); - auto impl = new D3D9HardwareBuffer(D3D9Mappings::get(itype), indexSize * numIndexes, usage, useShadowBuffer); - - return std::make_shared(this, itype, numIndexes, impl); - } - //----------------------------------------------------------------------- - VertexDeclaration* D3D9HardwareBufferManager::createVertexDeclarationImpl(void) - { - return OGRE_NEW D3D9VertexDeclaration(); - } -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9HardwareOcclusionQuery.cpp b/RenderSystems/Direct3D9/src/OgreD3D9HardwareOcclusionQuery.cpp deleted file mode 100644 index c4a186de4c1..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9HardwareOcclusionQuery.cpp +++ /dev/null @@ -1,255 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9HardwareOcclusionQuery.h" -#include "OgreRenderSystemCapabilities.h" -#include "OgreException.h" -#include "OgreD3D9RenderSystem.h" - -namespace Ogre { - - /** - * This is a class that is the DirectX9 implementation of - * hardware occlusion testing. - * - * @author Lee Sandberg - * - * Updated on 12/7/2004 by Chris McGuirk - * Updated on 4/8/2005 by Tuan Kuranes email: tuan.kuranes@free.fr - */ - - /** - * Default object constructor - */ - D3D9HardwareOcclusionQuery::D3D9HardwareOcclusionQuery() - { - - } - - /** - * Object destructor - */ - D3D9HardwareOcclusionQuery::~D3D9HardwareOcclusionQuery() - { - DeviceToQueryIterator it = mMapDeviceToQuery.begin(); - - while (it != mMapDeviceToQuery.end()) - { - SAFE_RELEASE(it->second); - ++it; - } - mMapDeviceToQuery.clear(); - } - - //------------------------------------------------------------------ - // Occlusion query functions (see base class documentation for this) - //-- - void D3D9HardwareOcclusionQuery::beginOcclusionQuery() - { - IDirect3DDevice9* pCurDevice = D3D9RenderSystem::getActiveD3D9Device(); - DeviceToQueryIterator it = mMapDeviceToQuery.find(pCurDevice); - - // No resource exits for current device -> create it. - if (it == mMapDeviceToQuery.end() || it->second == NULL) - createQuery(pCurDevice); - - - // Grab the query of the current device. - IDirect3DQuery9* pOccQuery = mMapDeviceToQuery[pCurDevice]; - - - if (pOccQuery != NULL) - { - pOccQuery->Issue(D3DISSUE_BEGIN); - mIsQueryResultStillOutstanding = true; - mPixelCount = 0; - } - } - - void D3D9HardwareOcclusionQuery::endOcclusionQuery() - { - IDirect3DDevice9* pCurDevice = D3D9RenderSystem::getActiveD3D9Device(); - DeviceToQueryIterator it = mMapDeviceToQuery.find(pCurDevice); - - if (it == mMapDeviceToQuery.end()) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "End occlusion called without matching begin call !!", - "D3D9HardwareOcclusionQuery::endOcclusionQuery" ); - } - - IDirect3DQuery9* pOccQuery = mMapDeviceToQuery[pCurDevice]; - - if (pOccQuery != NULL) - pOccQuery->Issue(D3DISSUE_END); - } - - //------------------------------------------------------------------ - bool D3D9HardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments ) - { - IDirect3DDevice9* pCurDevice = D3D9RenderSystem::getActiveD3D9Device(); - DeviceToQueryIterator it = mMapDeviceToQuery.find(pCurDevice); - - if (it == mMapDeviceToQuery.end()) - return false; - - if (it->second == NULL) - return false; - - // in case you didn't check if query arrived and want the result now. - if (mIsQueryResultStillOutstanding) - { - // Loop until the data becomes available - DWORD pixels; - const size_t dataSize = sizeof( DWORD ); - while (1) - { - const HRESULT hr = it->second->GetData((void *)&pixels, dataSize, D3DGETDATA_FLUSH); - - if (hr == S_FALSE) - continue; - if (hr == S_OK) - { - mPixelCount = pixels; - *NumOfFragments = pixels; - break; - } - if (hr == D3DERR_DEVICELOST) - { - *NumOfFragments = 0; - mPixelCount = 0; - SAFE_RELEASE(it->second); - break; - } - } - mIsQueryResultStillOutstanding = false; - } - else - { - // we already stored result from last frames. - *NumOfFragments = mPixelCount; - } - return true; - } - - //------------------------------------------------------------------ - unsigned int D3D9HardwareOcclusionQuery::getLastQuerysPixelcount() - { - return mPixelCount; - } - - //------------------------------------------------------------------ - bool D3D9HardwareOcclusionQuery::isStillOutstanding(void) - { - // in case you already asked for this query - if (!mIsQueryResultStillOutstanding) - return false; - - IDirect3DDevice9* pCurDevice = D3D9RenderSystem::getActiveD3D9Device(); - DeviceToQueryIterator it = mMapDeviceToQuery.find(pCurDevice); - - if (it == mMapDeviceToQuery.end()) - return false; - - if (it->second == NULL) - return false; - - - DWORD pixels; - const HRESULT hr = it->second->GetData( (void *) &pixels, sizeof( DWORD ), 0); - - if (hr == S_FALSE) - return true; - - if (hr == D3DERR_DEVICELOST) - { - mPixelCount = 100000; - SAFE_RELEASE(it->second); - } - - mPixelCount = pixels; - mIsQueryResultStillOutstanding = false; - return false; - } - - //------------------------------------------------------------------ - void D3D9HardwareOcclusionQuery::notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device) - { - - } - - //------------------------------------------------------------------ - void D3D9HardwareOcclusionQuery::notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device) - { - releaseQuery(d3d9Device); - } - - //------------------------------------------------------------------ - void D3D9HardwareOcclusionQuery::notifyOnDeviceLost(IDirect3DDevice9* d3d9Device) - { - releaseQuery(d3d9Device); - } - - //------------------------------------------------------------------ - void D3D9HardwareOcclusionQuery::notifyOnDeviceReset(IDirect3DDevice9* d3d9Device) - { - - } - - //------------------------------------------------------------------ - void D3D9HardwareOcclusionQuery::createQuery(IDirect3DDevice9* d3d9Device) - { - HRESULT hr; - - // Check if query supported. - hr = d3d9Device->CreateQuery(D3DQUERYTYPE_OCCLUSION, NULL); - if (FAILED(hr)) - { - mMapDeviceToQuery[d3d9Device] = NULL; - return; - } - - // create the occlusion query. - IDirect3DQuery9* pCurQuery; - hr = d3d9Device->CreateQuery(D3DQUERYTYPE_OCCLUSION, &pCurQuery); - - mMapDeviceToQuery[d3d9Device] = pCurQuery; - } - - //------------------------------------------------------------------ - void D3D9HardwareOcclusionQuery::releaseQuery(IDirect3DDevice9* d3d9Device) - { - DeviceToQueryIterator it = mMapDeviceToQuery.find(d3d9Device); - - // Remove from query resource map. - if (it != mMapDeviceToQuery.end()) - { - SAFE_RELEASE(it->second); - mMapDeviceToQuery.erase(it); - } - } -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9HardwarePixelBuffer.cpp b/RenderSystems/Direct3D9/src/OgreD3D9HardwarePixelBuffer.cpp deleted file mode 100644 index 799329d4cfe..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9HardwarePixelBuffer.cpp +++ /dev/null @@ -1,1005 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9HardwarePixelBuffer.h" -#include "OgreD3D9Texture.h" -#include "OgreD3D9Mappings.h" -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreBitwise.h" -#include "OgreRoot.h" -#include "OgreD3D9RenderSystem.h" -#include "OgreD3D9DepthBuffer.h" - -#include - -#define D3DFMT_NULL (D3DFORMAT)MAKEFOURCC('N', 'U', 'L', 'L') - -namespace Ogre { - - OGRE_STATIC_MUTEX_INSTANCE(D3D9HardwarePixelBuffer::msDeviceAccessMutex); -//----------------------------------------------------------------------------- - -D3D9HardwarePixelBuffer::D3D9HardwarePixelBuffer(HardwareBuffer::Usage usage, - D3D9Texture* ownerTexture): - HardwarePixelBuffer(0, 0, 0, PF_UNKNOWN, usage, false), - mDoMipmapGen(false), mHWMipmaps(false), mOwnerTexture(ownerTexture) -{ -} -D3D9HardwarePixelBuffer::~D3D9HardwarePixelBuffer() -{ - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - destroyRenderTexture(); - - DeviceToBufferResourcesIterator it = mMapDeviceToBufferResources.begin(); - - while (it != mMapDeviceToBufferResources.end()) - { - SAFE_RELEASE(it->second->surface); - SAFE_RELEASE(it->second->volume); - if (it->second != NULL) - { - OGRE_FREE (it->second, MEMCATEGORY_RENDERSYS); - it->second = NULL; - } - DeviceToBufferResourcesIterator deadi = it++; - mMapDeviceToBufferResources.erase(deadi); - } -} -//----------------------------------------------------------------------------- -void D3D9HardwarePixelBuffer::bind(IDirect3DDevice9 *dev, IDirect3DSurface9 *surface, - IDirect3DSurface9* fsaaSurface, - bool writeGamma, uint fsaa, const String& srcName, - IDirect3DBaseTexture9 *mipTex) -{ - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - BufferResources* bufferResources = getBufferResources(dev); - bool isNewBuffer = false; - - if (bufferResources == NULL) - { - bufferResources = new BufferResources(); - mMapDeviceToBufferResources[dev] = bufferResources; - isNewBuffer = true; - } - - bufferResources->mipTex = mipTex; - bufferResources->surface = surface; - bufferResources->surface->AddRef(); - bufferResources->fSAASurface = fsaaSurface; - - D3DSURFACE_DESC desc; - if(surface->GetDesc(&desc) != D3D_OK) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Could not get surface information", - "D3D9HardwarePixelBuffer::D3D9HardwarePixelBuffer"); - - mWidth = desc.Width; - mHeight = desc.Height; - mDepth = 1; - mFormat = D3D9Mappings::_getPF(desc.Format); - // Default - mRowPitch = mWidth; - mSlicePitch = mHeight*mWidth; - mSizeInBytes = PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat); - - if(mUsage & TU_RENDERTARGET) - { - updateRenderTexture(writeGamma, fsaa, srcName); - if (PixelUtil::isDepth(mFormat)) - { - // create null colour surface - dev->CreateRenderTarget(desc.Width, desc.Height, D3DFMT_NULL, D3DMULTISAMPLE_NONE, 0, false, - &bufferResources->nullSurface, NULL); - - auto rs = (D3D9RenderSystem *)Root::getSingleton().getRenderSystem(); - auto rtt = static_cast(mSliceTRT.front()); - auto depthBuf = rs->_addManualDepthBuffer(dev, getSurface(dev)); - rtt->_setDepthBuffer(depthBuf); - depthBuf->_notifyRenderTargetAttached(rtt); - } - } - - if (isNewBuffer && mOwnerTexture->isLoaded() && mOwnerTexture->isManuallyLoaded()) - { - DeviceToBufferResourcesIterator it = mMapDeviceToBufferResources.begin(); - - while (it != mMapDeviceToBufferResources.end()) - { - if (it->second != bufferResources && - it->second->surface != NULL && - it->first->TestCooperativeLevel() == D3D_OK && - dev->TestCooperativeLevel() == D3D_OK) - { - Box fullBufferBox(0,0,0,mWidth,mHeight,mDepth); - PixelBox dstBox(fullBufferBox, mFormat); - - dstBox.data = (uchar*)OGRE_MALLOC (getSizeInBytes(), MEMCATEGORY_RESOURCE); - blitToMemory(fullBufferBox, dstBox, it->second, it->first); - blitFromMemory(dstBox, fullBufferBox, bufferResources); - OGRE_FREE(dstBox.data, MEMCATEGORY_RESOURCE); - break; - } - ++it; - } - } -} -//----------------------------------------------------------------------------- -void D3D9HardwarePixelBuffer::bind(IDirect3DDevice9 *dev, IDirect3DVolume9 *volume, IDirect3DBaseTexture9 *mipTex) -{ - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - BufferResources* bufferResources = getBufferResources(dev); - bool isNewBuffer = false; - - if (bufferResources == NULL) - { - bufferResources = new BufferResources(); - mMapDeviceToBufferResources[dev] = bufferResources; - isNewBuffer = true; - } - - bufferResources->mipTex = mipTex; - bufferResources->volume = volume; - bufferResources->volume->AddRef(); - - D3DVOLUME_DESC desc; - if(volume->GetDesc(&desc) != D3D_OK) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Could not get volume information", - "D3D9HardwarePixelBuffer::D3D9HardwarePixelBuffer"); - mWidth = desc.Width; - mHeight = desc.Height; - mDepth = desc.Depth; - mFormat = D3D9Mappings::_getPF(desc.Format); - // Default - mRowPitch = mWidth; - mSlicePitch = mHeight*mWidth; - mSizeInBytes = PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat); - - if (isNewBuffer && mOwnerTexture->isManuallyLoaded()) - { - DeviceToBufferResourcesIterator it = mMapDeviceToBufferResources.begin(); - - while (it != mMapDeviceToBufferResources.end()) - { - if (it->second != bufferResources && - it->second->volume != NULL && - it->first->TestCooperativeLevel() == D3D_OK && - dev->TestCooperativeLevel() == D3D_OK) - { - Box fullBufferBox(0,0,0,mWidth,mHeight,mDepth); - PixelBox dstBox(fullBufferBox, mFormat); - - dstBox.data = (uchar*)OGRE_MALLOC(getSizeInBytes(), MEMCATEGORY_RESOURCE); - blitToMemory(fullBufferBox, dstBox, it->second, it->first); - blitFromMemory(dstBox, fullBufferBox, bufferResources); - OGRE_FREE(dstBox.data, MEMCATEGORY_RESOURCE); - break; - } - ++it; - } - } -} - -//----------------------------------------------------------------------------- -D3D9HardwarePixelBuffer::BufferResources* D3D9HardwarePixelBuffer::getBufferResources(IDirect3DDevice9* d3d9Device) -{ - DeviceToBufferResourcesIterator it = mMapDeviceToBufferResources.find(d3d9Device); - - if (it != mMapDeviceToBufferResources.end()) - return it->second; - - return NULL; -} -//----------------------------------------------------------------------------- -void D3D9HardwarePixelBuffer::destroyBufferResources(IDirect3DDevice9* d3d9Device) -{ - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - DeviceToBufferResourcesIterator it = mMapDeviceToBufferResources.find(d3d9Device); - - if (it != mMapDeviceToBufferResources.end()) - { - SAFE_RELEASE(it->second->surface); - SAFE_RELEASE(it->second->nullSurface); - SAFE_RELEASE(it->second->volume); - if (it->second != NULL) - { - OGRE_FREE (it->second, MEMCATEGORY_RENDERSYS); - it->second = NULL; - } - mMapDeviceToBufferResources.erase(it); - } -} - -//----------------------------------------------------------------------------- -void D3D9HardwarePixelBuffer::lockDeviceAccess() -{ - D3D9_DEVICE_ACCESS_LOCK; -} - -//----------------------------------------------------------------------------- -void D3D9HardwarePixelBuffer::unlockDeviceAccess() -{ - D3D9_DEVICE_ACCESS_UNLOCK; -} - -//----------------------------------------------------------------------------- -// Util functions to convert a D3D locked box to a pixel box -void fromD3DLock(PixelBox &rval, const D3DLOCKED_RECT &lrect) -{ - size_t bpp = PixelUtil::getNumElemBytes(rval.format); - if (bpp != 0) - { - rval.rowPitch = lrect.Pitch / bpp; - rval.slicePitch = rval.rowPitch * rval.getHeight(); - assert((lrect.Pitch % bpp)==0); - } - else if (PixelUtil::isCompressed(rval.format)) - { - rval.rowPitch = rval.getWidth(); - rval.slicePitch = rval.getWidth() * rval.getHeight(); - } - else - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Invalid pixel format", "fromD3DLock"); - } - - rval.data = (uchar*)lrect.pBits; -} -void fromD3DLock(PixelBox &rval, const D3DLOCKED_BOX &lbox) -{ - size_t bpp = PixelUtil::getNumElemBytes(rval.format); - if (bpp != 0) - { - rval.rowPitch = lbox.RowPitch / bpp; - rval.slicePitch = lbox.SlicePitch / bpp; - assert((lbox.RowPitch % bpp)==0); - assert((lbox.SlicePitch % bpp)==0); - } - else if (PixelUtil::isCompressed(rval.format)) - { - rval.rowPitch = rval.getWidth(); - rval.slicePitch = rval.getWidth() * rval.getHeight(); - } - else - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Invalid pixel format", "fromD3DLock"); - } - rval.data = (uchar*)lbox.pBits; -} -// Convert Ogre integer Box to D3D rectangle -RECT toD3DRECT(const Box &lockBox) -{ - RECT prect; - assert(lockBox.getDepth() == 1); - prect.left = static_cast(lockBox.left); - prect.right = static_cast(lockBox.right); - prect.top = static_cast(lockBox.top); - prect.bottom = static_cast(lockBox.bottom); - return prect; -} -// Convert Ogre integer Box to D3D box -D3DBOX toD3DBOX(const Box &lockBox) -{ - D3DBOX pbox; - - pbox.Left = static_cast(lockBox.left); - pbox.Right = static_cast(lockBox.right); - pbox.Top = static_cast(lockBox.top); - pbox.Bottom = static_cast(lockBox.bottom); - pbox.Front = static_cast(lockBox.front); - pbox.Back = static_cast(lockBox.back); - return pbox; -} -// Convert Ogre pixelbox extent to D3D rectangle -RECT toD3DRECTExtent(const PixelBox &lockBox) -{ - RECT prect; - assert(lockBox.getDepth() == 1); - prect.left = 0; - prect.right = static_cast(lockBox.getWidth()); - prect.top = 0; - prect.bottom = static_cast(lockBox.getHeight()); - return prect; -} -// Convert Ogre pixelbox extent to D3D box -D3DBOX toD3DBOXExtent(const PixelBox &lockBox) -{ - D3DBOX pbox; - pbox.Left = 0; - pbox.Right = static_cast(lockBox.getWidth()); - pbox.Top = 0; - pbox.Bottom = static_cast(lockBox.getHeight()); - pbox.Front = 0; - pbox.Back = static_cast(lockBox.getDepth()); - return pbox; -} -//----------------------------------------------------------------------------- -PixelBox D3D9HardwarePixelBuffer::lockImpl(const Box &lockBox, LockOptions options) -{ - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - // Check for misuse - if(mUsage & TU_RENDERTARGET) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "DirectX does not allow locking of or directly writing to RenderTargets. Use blitFromMemory if you need the contents.", - "D3D9HardwarePixelBuffer::lockImpl"); - // Set locking flags according to options - DWORD flags = 0; - switch(options) - { - case HBL_DISCARD: - // D3D only likes D3DLOCK_DISCARD if you created the texture with D3DUSAGE_DYNAMIC - // debug runtime flags this up, could cause problems on some drivers - if (mUsage & HBU_DYNAMIC) - flags |= D3DLOCK_DISCARD; - break; - case HBL_READ_ONLY: - flags |= D3DLOCK_READONLY; - break; - default: - break; - }; - - if (mMapDeviceToBufferResources.size() == 0) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "There are no resources attached to this pixel buffer !!", - "D3D9HardwarePixelBuffer::lockImpl"); - } - - BufferResources* bufferResources = mMapDeviceToBufferResources.begin()->second; - - // Lock the source buffer. - return lockBuffer(bufferResources, lockBox, flags); -} - -//----------------------------------------------------------------------------- -Ogre::PixelBox D3D9HardwarePixelBuffer::lockBuffer(BufferResources* bufferResources, - const Box &lockBox, - DWORD flags) -{ - if((mUsage & TU_STATIC) && D3D9RenderSystem::isDirectX9Ex()) - { - mStagingBuffer.create(mFormat, lockBox.getWidth(), lockBox.getHeight(), lockBox.getDepth()); - if(mCurrentLockOptions == HBL_READ_ONLY || mCurrentLockOptions == HBL_NORMAL) - HardwarePixelBuffer::blitToMemory(mStagingBuffer.getPixelBox()); - return mStagingBuffer.getPixelBox(); - } - - // Set extents and format - // Note that we do not carry over the left/top/front here, since the returned - // PixelBox will be re-based from the locking point onwards - PixelBox rval(lockBox.getWidth(), lockBox.getHeight(), lockBox.getDepth(), mFormat); - - if (bufferResources->surface != NULL) - { - // Surface - D3DLOCKED_RECT lrect; // Filled in by D3D - HRESULT hr; - - if (lockBox.left == 0 && lockBox.top == 0 - && lockBox.right == mWidth && lockBox.bottom == mHeight) - { - // Lock whole surface - hr = bufferResources->surface->LockRect(&lrect, NULL, flags); - } - else - { - RECT prect = toD3DRECT(lockBox); // specify range to lock - hr = bufferResources->surface->LockRect(&lrect, &prect, flags); - } - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Surface locking failed", - "D3D9HardwarePixelBuffer::lockImpl"); - fromD3DLock(rval, lrect); - } - else if(bufferResources->volume) - { - // Volume - D3DLOCKED_BOX lbox; // Filled in by D3D - HRESULT hr; - - if (lockBox.left == 0 && lockBox.top == 0 && lockBox.front == 0 && - lockBox.right == mWidth && lockBox.bottom == mHeight && lockBox.back == mDepth) - { - hr = bufferResources->volume->LockBox(&lbox, NULL, flags); - } - else - { - D3DBOX pbox = toD3DBOX(lockBox); // specify range to lock - hr = bufferResources->volume->LockBox(&lbox, &pbox, flags); - } - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Volume locking failed", - "D3D9HardwarePixelBuffer::lockImpl"); - } - fromD3DLock(rval, lbox); - } - - - return rval; -} - -//----------------------------------------------------------------------------- -void D3D9HardwarePixelBuffer::unlockImpl(void) -{ - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - if (mMapDeviceToBufferResources.size() == 0) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "There are no resources attached to this pixel buffer !!", - "D3D9HardwarePixelBuffer::lockImpl"); - } - - DeviceToBufferResourcesIterator it; - - // 1. Update duplicates buffers. - it = mMapDeviceToBufferResources.begin(); - ++it; - while (it != mMapDeviceToBufferResources.end()) - { - if(mCurrentLockOptions == HBL_READ_ONLY) break; // not needed - - BufferResources* bufferResources = it->second; - - // Update duplicated buffer from the from the locked buffer content. - blitFromMemory(mCurrentLock, mLockedBox, bufferResources); - ++it; - } - - // 2. Unlock the locked buffer. - it = mMapDeviceToBufferResources.begin(); - unlockBuffer( it->second); - if(mDoMipmapGen) - _genMipmaps(it->second->mipTex); - - // in case we used this - mStagingBuffer.freeMemory(); -} - -//----------------------------------------------------------------------------- -void D3D9HardwarePixelBuffer::unlockBuffer(BufferResources* bufferResources) -{ - if(bufferResources->surface) - { - // Surface - bufferResources->surface->UnlockRect(); - } - else if(bufferResources->volume) - { - // Volume - bufferResources->volume->UnlockBox(); - } -} - -//----------------------------------------------------------------------------- -void D3D9HardwarePixelBuffer::blit(const HardwarePixelBufferSharedPtr &rsrc, - const Box &srcBox, - const Box &dstBox) -{ - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - D3D9HardwarePixelBuffer *src = static_cast(rsrc.get()); - DeviceToBufferResourcesIterator it = mMapDeviceToBufferResources.begin(); - - // Update all the buffer copies. - while (it != mMapDeviceToBufferResources.end()) - { - BufferResources* srcBufferResources = src->getBufferResources(it->first); - BufferResources* dstBufferResources = it->second; - - if (srcBufferResources == NULL) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "There are no matching resources attached to the source pixel buffer !!", - "D3D9HardwarePixelBuffer::blit"); - } - - blit(it->first, rsrc, srcBox, dstBox, srcBufferResources, dstBufferResources); - ++it; - } -} - -//----------------------------------------------------------------------------- -void D3D9HardwarePixelBuffer::blit(IDirect3DDevice9* d3d9Device, - const HardwarePixelBufferSharedPtr &rsrc, - const Box &srcBox, - const Box &dstBox, - BufferResources* srcBufferResources, - BufferResources* dstBufferResources) -{ - if(dstBufferResources->surface && srcBufferResources->surface) - { - // Surface-to-surface - RECT dsrcRect = toD3DRECT(srcBox); - RECT ddestRect = toD3DRECT(dstBox); - - D3DSURFACE_DESC srcDesc; - if(srcBufferResources->surface->GetDesc(&srcDesc) != D3D_OK) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Could not get surface information", - "D3D9HardwarePixelBuffer::blit"); - - // If we're blitting from a RTT, try GetRenderTargetData - // if we're going to try to use GetRenderTargetData, need to use system mem pool - bool tryGetRenderTargetData = false; - if ((srcDesc.Usage & D3DUSAGE_RENDERTARGET) != 0 - && srcDesc.MultiSampleType == D3DMULTISAMPLE_NONE) - { - - // Temp texture - IDirect3DTexture9 *tmptex; - IDirect3DSurface9 *tmpsurface; - - if(D3DXCreateTexture( - d3d9Device, - srcDesc.Width, srcDesc.Height, - 1, // 1 mip level ie topmost, generate no mipmaps - 0, srcDesc.Format, D3DPOOL_SYSTEMMEM, - &tmptex - ) != D3D_OK) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Create temporary texture failed", - "D3D9HardwarePixelBuffer::blit"); - } - if(tmptex->GetSurfaceLevel(0, &tmpsurface) != D3D_OK) - { - tmptex->Release(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Get surface level failed", - "D3D9HardwarePixelBuffer::blit"); - } - if(d3d9Device->GetRenderTargetData(srcBufferResources->surface, tmpsurface) == D3D_OK) - { - // Hey, it worked - // Copy from this surface instead - if(D3DXLoadSurfaceFromSurface( - dstBufferResources->surface, NULL, &ddestRect, - tmpsurface, NULL, &dsrcRect, - D3DX_DEFAULT, 0) != D3D_OK) - { - tmpsurface->Release(); - tmptex->Release(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "D3DXLoadSurfaceFromSurface failed", - "D3D9HardwarePixelBuffer::blit"); - } - tmpsurface->Release(); - tmptex->Release(); - return; - } - - } - - // Otherwise, try the normal method - - // D3DXLoadSurfaceFromSurface - if(D3DXLoadSurfaceFromSurface( - dstBufferResources->surface, NULL, &ddestRect, - srcBufferResources->surface, NULL, &dsrcRect, - D3DX_DEFAULT, 0) != D3D_OK) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "D3DXLoadSurfaceFromSurface failed", - "D3D9HardwarePixelBuffer::blit"); - } - } - else if(dstBufferResources->volume && srcBufferResources->volume) - { - // Volume-to-volume - D3DBOX dsrcBox = toD3DBOX(srcBox); - D3DBOX ddestBox = toD3DBOX(dstBox); - - // D3DXLoadVolumeFromVolume - if(D3DXLoadVolumeFromVolume( - dstBufferResources->volume, NULL, &ddestBox, - srcBufferResources->volume, NULL, &dsrcBox, - D3DX_DEFAULT, 0) != D3D_OK) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "D3DXLoadVolumeFromVolume failed", - "D3D9HardwarePixelBuffer::blit"); - } - } - else - { - // Software fallback - HardwarePixelBuffer::blit(rsrc, srcBox, dstBox); - } -} - -//----------------------------------------------------------------------------- -void D3D9HardwarePixelBuffer::blitFromMemory(const PixelBox &src, const Box &dstBox) -{ - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - DeviceToBufferResourcesIterator it = mMapDeviceToBufferResources.begin(); - - while (it != mMapDeviceToBufferResources.end()) - { - BufferResources* dstBufferResources = it->second; - - blitFromMemory(src, dstBox, dstBufferResources); - ++it; - } -} - -//----------------------------------------------------------------------------- -void D3D9HardwarePixelBuffer::blitFromMemory(const PixelBox &src, const Box &dstBox, BufferResources* dstBufferResources) -{ - // for scoped deletion of conversion buffer - MemoryDataStreamPtr buf; - PixelBox converted = src; - - // convert to pixelbuffer's native format if necessary - if (D3D9Mappings::_getPF(src.format) == D3DFMT_UNKNOWN) - { - buf.reset(OGRE_NEW MemoryDataStream( - PixelUtil::getMemorySize(src.getWidth(), src.getHeight(), src.getDepth(), - mFormat))); - converted = PixelBox(src.getWidth(), src.getHeight(), src.getDepth(), mFormat, buf->getPtr()); - PixelUtil::bulkPixelConversion(src, converted); - } - - size_t rowWidth; - if (PixelUtil::isCompressed(converted.format)) - { - // if the row doesn't divide by 4 - there is padding to 4 - if(converted.rowPitch % 4 > 0) - { - converted.rowPitch += 4 - converted.rowPitch % 4; - } - - // D3D wants the width of one row of cells in bytes - if (converted.format == PF_DXT1) - { - // 64 bits (8 bytes) per 4x4 block - rowWidth = (converted.rowPitch / 4) * 8; - } - else - { - // 128 bits (16 bytes) per 4x4 block - rowWidth = (converted.rowPitch / 4) * 16; - } - - } - else - { - rowWidth = converted.rowPitch * PixelUtil::getNumElemBytes(converted.format); - } - - if (dstBufferResources->surface) - { - RECT destRect, srcRect; - srcRect = toD3DRECT(converted); - destRect = toD3DRECT(dstBox); - - if(D3DXLoadSurfaceFromMemory(dstBufferResources->surface, NULL, &destRect, - converted.data, D3D9Mappings::_getPF(converted.format), - static_cast(rowWidth), - NULL, &srcRect, D3DX_DEFAULT, 0) != D3D_OK) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "D3DXLoadSurfaceFromMemory failed", - "D3D9HardwarePixelBuffer::blitFromMemory"); - } - } - else if (dstBufferResources->volume) - { - D3DBOX destBox, srcBox; - srcBox = toD3DBOX(converted); - destBox = toD3DBOX(dstBox); - size_t sliceWidth; - if (PixelUtil::isCompressed(converted.format)) - { - // D3D wants the width of one slice of cells in bytes - if (converted.format == PF_DXT1) - { - // 64 bits (8 bytes) per 4x4 block - sliceWidth = (converted.slicePitch / 16) * 8; - } - else - { - // 128 bits (16 bytes) per 4x4 block - sliceWidth = (converted.slicePitch / 16) * 16; - } - - } - else - { - sliceWidth = converted.slicePitch * PixelUtil::getNumElemBytes(converted.format); - } - - if(D3DXLoadVolumeFromMemory(dstBufferResources->volume, NULL, &destBox, - converted.data, D3D9Mappings::_getPF(converted.format), - static_cast(rowWidth), static_cast(sliceWidth), - NULL, &srcBox, D3DX_DEFAULT, 0) != D3D_OK) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "D3DXLoadSurfaceFromMemory failed", - "D3D9HardwarePixelBuffer::blitFromMemory"); - } - } - - if(mDoMipmapGen) - _genMipmaps(dstBufferResources->mipTex); - -} - -//----------------------------------------------------------------------------- -void D3D9HardwarePixelBuffer::blitToMemory(const Box &srcBox, const PixelBox &dst) -{ - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - DeviceToBufferResourcesIterator it = mMapDeviceToBufferResources.begin(); - BufferResources* bufferResources = it->second; - - blitToMemory(srcBox, dst, bufferResources, it->first); -} - -//----------------------------------------------------------------------------- -void D3D9HardwarePixelBuffer::blitToMemory(const Box &srcBox, const PixelBox &dst, - BufferResources* srcBufferResources, - IDirect3DDevice9* d3d9Device) -{ - // Decide on pixel format of temp surface - PixelFormat tmpFormat = mFormat; - if(D3D9Mappings::_getPF(dst.format) != D3DFMT_UNKNOWN) - { - tmpFormat = dst.format; - } - - if (srcBufferResources->surface) - { - assert(srcBox.getDepth() == 1 && dst.getDepth() == 1); - // Create temp texture - IDirect3DTexture9 *tmp; - IDirect3DSurface9 *surface; - - D3DSURFACE_DESC srcDesc; - if(srcBufferResources->surface->GetDesc(&srcDesc) != D3D_OK) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Could not get surface information", - "D3D9HardwarePixelBuffer::blitToMemory"); - - D3DPOOL temppool = D3DPOOL_SCRATCH; - // if we're going to try to use GetRenderTargetData, need to use system mem pool - bool tryGetRenderTargetData = false; - if (((srcDesc.Usage & D3DUSAGE_RENDERTARGET) != 0) && - (srcBox.getWidth() == dst.getWidth()) && (srcBox.getHeight() == dst.getHeight()) && - (srcBox.getWidth() == getWidth()) && (srcBox.getHeight() == getHeight()) && - (mFormat == tmpFormat)) - { - tryGetRenderTargetData = true; - temppool = D3DPOOL_SYSTEMMEM; - } - - if(D3DXCreateTexture( - d3d9Device, - static_cast(dst.getWidth()), static_cast(dst.getHeight()), - 1, // 1 mip level ie topmost, generate no mipmaps - 0, D3D9Mappings::_getPF(tmpFormat), temppool, - &tmp - ) != D3D_OK) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Create temporary texture failed", - "D3D9HardwarePixelBuffer::blitToMemory"); - } - if(tmp->GetSurfaceLevel(0, &surface) != D3D_OK) - { - tmp->Release(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Get surface level failed", - "D3D9HardwarePixelBuffer::blitToMemory"); - } - // Copy texture to this temp surface - RECT destRect, srcRect; - srcRect = toD3DRECT(srcBox); - destRect = toD3DRECTExtent(dst); - - // Get the real temp surface format - D3DSURFACE_DESC dstDesc; - if(surface->GetDesc(&dstDesc) != D3D_OK) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Could not get surface information", - "D3D9HardwarePixelBuffer::blitToMemory"); - tmpFormat = D3D9Mappings::_getPF(dstDesc.Format); - - // Use fast GetRenderTargetData if we are in its usage conditions - bool fastLoadSuccess = false; - if (tryGetRenderTargetData) - { - if(d3d9Device->GetRenderTargetData(srcBufferResources->surface, surface) == D3D_OK) - { - fastLoadSuccess = true; - } - } - if (!fastLoadSuccess) - { - if(D3DXLoadSurfaceFromSurface( - surface, NULL, &destRect, - srcBufferResources->surface, NULL, &srcRect, - D3DX_DEFAULT, 0) != D3D_OK) - { - surface->Release(); - tmp->Release(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "D3DXLoadSurfaceFromSurface failed", - "D3D9HardwarePixelBuffer::blitToMemory"); - } - } - - // Lock temp surface and copy it to memory - D3DLOCKED_RECT lrect; // Filled in by D3D - if(surface->LockRect(&lrect, NULL, D3DLOCK_READONLY) != D3D_OK) - { - surface->Release(); - tmp->Release(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "surface->LockRect", - "D3D9HardwarePixelBuffer::blitToMemory"); - } - // Copy it - PixelBox locked(dst.getWidth(), dst.getHeight(), dst.getDepth(), tmpFormat); - fromD3DLock(locked, lrect); - PixelUtil::bulkPixelConversion(locked, dst); - surface->UnlockRect(); - // Release temporary surface and texture - surface->Release(); - tmp->Release(); - } - else if (srcBufferResources->volume) - { - // Create temp texture - IDirect3DVolumeTexture9 *tmp; - IDirect3DVolume9 *surface; - - if(D3DXCreateVolumeTexture( - d3d9Device, - static_cast(dst.getWidth()), - static_cast(dst.getHeight()), - static_cast(dst.getDepth()), 0, - 0, D3D9Mappings::_getPF(tmpFormat), D3DPOOL_SCRATCH, - &tmp - ) != D3D_OK) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Create temporary texture failed", - "D3D9HardwarePixelBuffer::blitToMemory"); - } - if(tmp->GetVolumeLevel(0, &surface) != D3D_OK) - { - tmp->Release(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Get volume level failed", - "D3D9HardwarePixelBuffer::blitToMemory"); - } - // Volume - D3DBOX ddestBox, dsrcBox; - ddestBox = toD3DBOXExtent(dst); - dsrcBox = toD3DBOX(srcBox); - - if(D3DXLoadVolumeFromVolume( - surface, NULL, &ddestBox, - srcBufferResources->volume, NULL, &dsrcBox, - D3DX_DEFAULT, 0) != D3D_OK) - { - surface->Release(); - tmp->Release(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "D3DXLoadVolumeFromVolume failed", - "D3D9HardwarePixelBuffer::blitToMemory"); - } - // Lock temp surface and copy it to memory - D3DLOCKED_BOX lbox; // Filled in by D3D - if(surface->LockBox(&lbox, NULL, D3DLOCK_READONLY) != D3D_OK) - { - surface->Release(); - tmp->Release(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "surface->LockBox", - "D3D9HardwarePixelBuffer::blitToMemory"); - } - // Copy it - PixelBox locked(dst.getWidth(), dst.getHeight(), dst.getDepth(), tmpFormat); - fromD3DLock(locked, lbox); - PixelUtil::bulkPixelConversion(locked, dst); - surface->UnlockBox(); - // Release temporary surface and texture - surface->Release(); - tmp->Release(); - } -} - -//----------------------------------------------------------------------------- -void D3D9HardwarePixelBuffer::_genMipmaps(IDirect3DBaseTexture9* mipTex) -{ - assert(mipTex); - - // Mipmapping - if (mHWMipmaps) - { - // Hardware mipmaps - mipTex->GenerateMipSubLevels(); - } - else - { - // Software mipmaps - if( D3DXFilterTexture( mipTex, NULL, D3DX_DEFAULT, D3DX_DEFAULT ) != D3D_OK ) - { - OGRE_EXCEPT( Exception::ERR_RENDERINGAPI_ERROR, - "Failed to filter texture (generate mipmaps)", - "D3D9HardwarePixelBuffer::_genMipmaps" ); - } - } - -} -//----------------------------------------------------------------------------- -void D3D9HardwarePixelBuffer::_setMipmapping(bool doMipmapGen, - bool HWMipmaps) -{ - mDoMipmapGen = doMipmapGen; - mHWMipmaps = HWMipmaps; -} - -//----------------------------------------------------------------------------- -void D3D9HardwarePixelBuffer::releaseSurfaces(IDirect3DDevice9* d3d9Device) -{ - BufferResources* bufferResources = getBufferResources(d3d9Device); - - if (bufferResources != NULL) - { - SAFE_RELEASE(bufferResources->surface); - SAFE_RELEASE(bufferResources->nullSurface); - SAFE_RELEASE(bufferResources->volume); - } -} -//----------------------------------------------------------------------------- -D3D9HardwarePixelBuffer::BufferResources* -D3D9HardwarePixelBuffer::createOrRetrieveResources(IDirect3DDevice9* d3d9Device) -{ - BufferResources* bufferResources = getBufferResources(d3d9Device); - - if (bufferResources == NULL) - { - mOwnerTexture->createTextureResources(d3d9Device); - bufferResources = getBufferResources(d3d9Device); - } - - return bufferResources; -} -//----------------------------------------------------------------------------- -void D3D9HardwarePixelBuffer::updateRenderTexture(bool writeGamma, uint fsaa, const String& srcName) -{ - if (mSliceTRT.empty()) - { - String name; - name = "rtt/" +Ogre::StringConverter::toString((size_t)this) + "/" + srcName; - - mSliceTRT.push_back(OGRE_NEW D3D9RenderTexture(name, this, writeGamma, fsaa)); - Root::getSingleton().getRenderSystem()->attachRenderTarget(*mSliceTRT[0]); - } -} -//----------------------------------------------------------------------------- -void D3D9HardwarePixelBuffer::destroyRenderTexture() -{ - if (!mSliceTRT.empty()) - { - Root::getSingleton().getRenderSystem()->destroyRenderTarget(mSliceTRT[0]->getName()); - mSliceTRT.clear(); - } -} - -}; diff --git a/RenderSystems/Direct3D9/src/OgreD3D9Mappings.cpp b/RenderSystems/Direct3D9/src/OgreD3D9Mappings.cpp deleted file mode 100644 index df52d040b8b..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9Mappings.cpp +++ /dev/null @@ -1,761 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9Mappings.h" -#include "OgreString.h" -#include "OgreStringConverter.h" -#include "OgreLogManager.h" -#include "OgreException.h" - -#define D3DFMT_INTZ ( (D3DFORMAT)MAKEFOURCC('I', 'N', 'T', 'Z') ) - -namespace Ogre -{ - //--------------------------------------------------------------------- - DWORD D3D9Mappings::get(ShadeOptions so) - { - switch( so ) - { - case SO_FLAT: - return D3DSHADE_FLAT; - case SO_PHONG: - // phong is not supported in D3D9 - OGRE_FALLTHROUGH; - case SO_GOURAUD: - return D3DSHADE_GOURAUD; - } - return 0; - } - //--------------------------------------------------------------------- - DWORD D3D9Mappings::get(TexCoordCalcMethod m, const D3DCAPS9& caps) - { - switch( m ) - { - case TEXCALC_NONE: - return D3DTSS_TCI_PASSTHRU; - case TEXCALC_ENVIRONMENT_MAP_REFLECTION: - return D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR; - case TEXCALC_ENVIRONMENT_MAP_NORMAL: - return D3DTSS_TCI_CAMERASPACENORMAL; - case TEXCALC_ENVIRONMENT_MAP_PLANAR: - // should be D3DTSS_TCI_CAMERASPACEPOSITION, but it has been like this since v0.12 - case TEXCALC_ENVIRONMENT_MAP: - if (caps.VertexProcessingCaps & D3DVTXPCAPS_TEXGEN_SPHEREMAP) - { - // Use sphere map if available - return D3DTSS_TCI_SPHEREMAP; - } - else - { - // If not, fall back on camera space normal which isn't as good - return D3DTSS_TCI_CAMERASPACENORMAL; - } - case TEXCALC_PROJECTIVE_TEXTURE: - return D3DTSS_TCI_CAMERASPACEPOSITION; - } - return 0; - } - //--------------------------------------------------------------------- - D3DTEXTUREADDRESS D3D9Mappings::get(TextureAddressingMode tam, const D3DCAPS9& devCaps) - { - switch( tam ) - { - case TextureUnitState::TAM_WRAP: - return D3DTADDRESS_WRAP; - case TextureUnitState::TAM_MIRROR: - return D3DTADDRESS_MIRROR; - case TextureUnitState::TAM_CLAMP: - return D3DTADDRESS_CLAMP; - case TextureUnitState::TAM_BORDER: - if (devCaps.TextureAddressCaps & D3DPTADDRESSCAPS_BORDER) - return D3DTADDRESS_BORDER; - else - return D3DTADDRESS_CLAMP; - } - return D3DTADDRESS_FORCE_DWORD; - } - //--------------------------------------------------------------------- - D3DTEXTURESTAGESTATETYPE D3D9Mappings::get(LayerBlendType lbt) - { - switch( lbt ) - { - case LBT_COLOUR: - return D3DTSS_COLOROP; - case LBT_ALPHA: - return D3DTSS_ALPHAOP; - } - return D3DTSS_FORCE_DWORD; - } - //--------------------------------------------------------------------- - DWORD D3D9Mappings::get(LayerBlendSource lbs, bool perStageConstants) - { - switch( lbs ) - { - case LBS_CURRENT: - return D3DTA_CURRENT; - case LBS_TEXTURE: - return D3DTA_TEXTURE; - case LBS_DIFFUSE: - return D3DTA_DIFFUSE; - case LBS_SPECULAR: - return D3DTA_SPECULAR; - case LBS_MANUAL: - return perStageConstants ? D3DTA_CONSTANT : D3DTA_TFACTOR; - } - return 0; - } - //--------------------------------------------------------------------- - DWORD D3D9Mappings::get(LayerBlendOperationEx lbo, const D3DCAPS9& devCaps) - { - switch( lbo ) - { - case LBX_SOURCE1: - return D3DTOP_SELECTARG1; - case LBX_SOURCE2: - return D3DTOP_SELECTARG2; - case LBX_MODULATE: - return D3DTOP_MODULATE; - case LBX_MODULATE_X2: - return D3DTOP_MODULATE2X; - case LBX_MODULATE_X4: - return D3DTOP_MODULATE4X; - case LBX_ADD: - return D3DTOP_ADD; - case LBX_ADD_SIGNED: - return D3DTOP_ADDSIGNED; - case LBX_ADD_SMOOTH: - return D3DTOP_ADDSMOOTH; - case LBX_SUBTRACT: - return D3DTOP_SUBTRACT; - case LBX_BLEND_DIFFUSE_ALPHA: - return D3DTOP_BLENDDIFFUSEALPHA; - case LBX_BLEND_TEXTURE_ALPHA: - return D3DTOP_BLENDTEXTUREALPHA; - case LBX_BLEND_CURRENT_ALPHA: - return D3DTOP_BLENDCURRENTALPHA; - case LBX_BLEND_MANUAL: - return D3DTOP_BLENDFACTORALPHA; - case LBX_DOTPRODUCT: - if (devCaps.TextureOpCaps & D3DTEXOPCAPS_DOTPRODUCT3) - return D3DTOP_DOTPRODUCT3; - else - return D3DTOP_MODULATE; - case LBX_BLEND_DIFFUSE_COLOUR: - if (devCaps.TextureOpCaps & D3DTEXOPCAPS_LERP) - return D3DTOP_LERP; - else - return D3DTOP_MODULATE; - } - return 0; - } - //--------------------------------------------------------------------- - D3DBLEND D3D9Mappings::get(SceneBlendFactor sbf) - { - switch( sbf ) - { - case SBF_ONE: - return D3DBLEND_ONE; - case SBF_ZERO: - return D3DBLEND_ZERO; - case SBF_DEST_COLOUR: - return D3DBLEND_DESTCOLOR; - case SBF_SOURCE_COLOUR: - return D3DBLEND_SRCCOLOR; - case SBF_ONE_MINUS_DEST_COLOUR: - return D3DBLEND_INVDESTCOLOR; - case SBF_ONE_MINUS_SOURCE_COLOUR: - return D3DBLEND_INVSRCCOLOR; - case SBF_DEST_ALPHA: - return D3DBLEND_DESTALPHA; - case SBF_SOURCE_ALPHA: - return D3DBLEND_SRCALPHA; - case SBF_ONE_MINUS_DEST_ALPHA: - return D3DBLEND_INVDESTALPHA; - case SBF_ONE_MINUS_SOURCE_ALPHA: - return D3DBLEND_INVSRCALPHA; - } - return D3DBLEND_FORCE_DWORD; - } - //--------------------------------------------------------------------- - D3DBLENDOP D3D9Mappings::get(Ogre::SceneBlendOperation sbo) - { - switch(sbo) - { - case SBO_ADD: - return D3DBLENDOP_ADD; - case SBO_SUBTRACT: - return D3DBLENDOP_SUBTRACT; - case SBO_REVERSE_SUBTRACT: - return D3DBLENDOP_REVSUBTRACT; - case SBO_MIN: - return D3DBLENDOP_MIN; - case SBO_MAX: - return D3DBLENDOP_MAX; - } - - return D3DBLENDOP_FORCE_DWORD; - } - //--------------------------------------------------------------------- - DWORD D3D9Mappings::get(CompareFunction cf) - { - switch( cf ) - { - case CMPF_ALWAYS_FAIL: - return D3DCMP_NEVER; - case CMPF_ALWAYS_PASS: - return D3DCMP_ALWAYS; - case CMPF_LESS: - return D3DCMP_LESS; - case CMPF_LESS_EQUAL: - return D3DCMP_LESSEQUAL; - case CMPF_EQUAL: - return D3DCMP_EQUAL; - case CMPF_NOT_EQUAL: - return D3DCMP_NOTEQUAL; - case CMPF_GREATER_EQUAL: - return D3DCMP_GREATEREQUAL; - case CMPF_GREATER: - return D3DCMP_GREATER; - }; - return 0; - } - //--------------------------------------------------------------------- - DWORD D3D9Mappings::get(CullingMode cm, bool flip) - { - switch( cm ) - { - case CULL_NONE: - return D3DCULL_NONE; - case CULL_CLOCKWISE: - if( flip ) - return D3DCULL_CCW; - else - return D3DCULL_CW; - case CULL_ANTICLOCKWISE: - if( flip ) - return D3DCULL_CW; - else - return D3DCULL_CCW; - } - return 0; - } - //--------------------------------------------------------------------- - D3DFOGMODE D3D9Mappings::get(FogMode fm) - { - switch( fm ) - { - case FOG_EXP: - return D3DFOG_EXP; - case FOG_EXP2: - return D3DFOG_EXP2; - case FOG_LINEAR: - return D3DFOG_LINEAR; - } - return D3DFOG_FORCE_DWORD; - } - //--------------------------------------------------------------------- - D3DFILLMODE D3D9Mappings::get(PolygonMode level) - { - switch(level) - { - case PM_POINTS: - return D3DFILL_POINT; - case PM_WIREFRAME: - return D3DFILL_WIREFRAME; - case PM_SOLID: - return D3DFILL_SOLID; - } - return D3DFILL_FORCE_DWORD; - } - //--------------------------------------------------------------------- - DWORD D3D9Mappings::get(StencilOperation op, bool invert) - { - switch(op) - { - case SOP_KEEP: - return D3DSTENCILOP_KEEP; - case SOP_ZERO: - return D3DSTENCILOP_ZERO; - case SOP_REPLACE: - return D3DSTENCILOP_REPLACE; - case SOP_INCREMENT: - return invert? D3DSTENCILOP_DECRSAT : D3DSTENCILOP_INCRSAT; - case SOP_DECREMENT: - return invert? D3DSTENCILOP_INCRSAT : D3DSTENCILOP_DECRSAT; - case SOP_INCREMENT_WRAP: - return invert? D3DSTENCILOP_DECR : D3DSTENCILOP_INCR; - case SOP_DECREMENT_WRAP: - return invert? D3DSTENCILOP_INCR : D3DSTENCILOP_DECR; - case SOP_INVERT: - return D3DSTENCILOP_INVERT; - } - return 0; - } - //--------------------------------------------------------------------- - D3DSAMPLERSTATETYPE D3D9Mappings::get(FilterType ft) - { - switch (ft) - { - case FT_MIN: - return D3DSAMP_MINFILTER; - break; - case FT_MAG: - return D3DSAMP_MAGFILTER; - break; - case FT_MIP: - return D3DSAMP_MIPFILTER; - break; - } - - // to keep compiler happy - return D3DSAMP_MINFILTER; - } - //--------------------------------------------------------------------- - DWORD D3D9Mappings::get(FilterType ft, FilterOptions fo, const D3DCAPS9& devCaps, - eD3DTexType texType) - { - // Assume normal - DWORD capsType = devCaps.TextureFilterCaps; - - switch( texType ) - { - case D3D_TEX_TYPE_NORMAL: - capsType = devCaps.TextureFilterCaps; - break; - case D3D_TEX_TYPE_CUBE: - capsType = devCaps.CubeTextureFilterCaps; - break; - case D3D_TEX_TYPE_VOLUME: - capsType = devCaps.VolumeTextureFilterCaps; - break; - } - - switch (ft) - { - case FT_MIN: - switch( fo ) - { - // NOTE: Fall through if device doesn't support requested type - case FO_ANISOTROPIC: - if( capsType & D3DPTFILTERCAPS_MINFANISOTROPIC ) - { - return D3DTEXF_ANISOTROPIC; - break; - } - case FO_LINEAR: - if( capsType & D3DPTFILTERCAPS_MINFLINEAR ) - { - return D3DTEXF_LINEAR; - break; - } - case FO_POINT: - case FO_NONE: - return D3DTEXF_POINT; - break; - } - break; - case FT_MAG: - switch( fo ) - { - // NOTE: Fall through if device doesn't support requested type - case FO_ANISOTROPIC: - if( capsType & D3DPTFILTERCAPS_MAGFANISOTROPIC ) - { - return D3DTEXF_ANISOTROPIC; - break; - } - case FO_LINEAR: - if( capsType & D3DPTFILTERCAPS_MAGFLINEAR ) - { - return D3DTEXF_LINEAR; - break; - } - case FO_POINT: - case FO_NONE: - return D3DTEXF_POINT; - break; - } - break; - case FT_MIP: - switch( fo ) - { - case FO_ANISOTROPIC: - case FO_LINEAR: - if( capsType & D3DPTFILTERCAPS_MIPFLINEAR ) - { - return D3DTEXF_LINEAR; - break; - } - case FO_POINT: - if( capsType & D3DPTFILTERCAPS_MIPFPOINT ) - { - return D3DTEXF_POINT; - break; - } - case FO_NONE: - return D3DTEXF_NONE; - break; - } - break; - } - - // should never get here - return 0; - - } - //--------------------------------------------------------------------- - D3D9Mappings::eD3DTexType D3D9Mappings::get(TextureType ogreTexType) - { - switch( ogreTexType ) - { - case TEX_TYPE_1D : - case TEX_TYPE_2D : - return D3D9Mappings::D3D_TEX_TYPE_NORMAL; - case TEX_TYPE_CUBE_MAP : - return D3D9Mappings::D3D_TEX_TYPE_CUBE; - case TEX_TYPE_3D : - return D3D9Mappings::D3D_TEX_TYPE_VOLUME; - } - return D3D9Mappings::D3D_TEX_TYPE_NONE; - } - //--------------------------------------------------------------------- - DWORD D3D9Mappings::get(HardwareBuffer::Usage usage) - { - DWORD ret = 0; - if (usage & HardwareBuffer::HBU_DYNAMIC) - { - ret |= D3DUSAGE_DYNAMIC; - } - if (usage & HBU_DETAIL_WRITE_ONLY) - { - ret |= D3DUSAGE_WRITEONLY; - } - return ret; - } - //--------------------------------------------------------------------- - DWORD D3D9Mappings::get(HardwareBuffer::LockOptions options, HardwareBuffer::Usage usage) - { - DWORD ret = 0; - if (options == HardwareBuffer::HBL_DISCARD) - { - // D3D doesn't like discard or no_overwrite on non-dynamic buffers - if (usage & HardwareBuffer::HBU_DYNAMIC) - ret |= D3DLOCK_DISCARD; - } - if (options == HardwareBuffer::HBL_READ_ONLY) - { - // D3D debug runtime doesn't like you locking managed buffers readonly - // when they were created with write-only (even though you CAN read - // from the software backed version) - if (!(usage & HBU_DETAIL_WRITE_ONLY)) - ret |= D3DLOCK_READONLY; - - } - if (options == HardwareBuffer::HBL_NO_OVERWRITE) - { - // D3D doesn't like discard or no_overwrite on non-dynamic buffers - if (usage & HardwareBuffer::HBU_DYNAMIC) - ret |= D3DLOCK_NOOVERWRITE; - } - - return ret; - } - //--------------------------------------------------------------------- - D3DFORMAT D3D9Mappings::get(HardwareIndexBuffer::IndexType itype) - { - if (itype == HardwareIndexBuffer::IT_32BIT) - { - return D3DFMT_INDEX32; - } - else - { - return D3DFMT_INDEX16; - } - } - //--------------------------------------------------------------------- - D3DDECLTYPE D3D9Mappings::get(VertexElementType vType) - { - switch (vType) - { - case VET_FLOAT1: - return D3DDECLTYPE_FLOAT1; - case VET_FLOAT2: - return D3DDECLTYPE_FLOAT2; - case VET_FLOAT3: - return D3DDECLTYPE_FLOAT3; - case VET_FLOAT4: - return D3DDECLTYPE_FLOAT4; - case VET_SHORT2: - return D3DDECLTYPE_SHORT2; - case VET_SHORT4: - return D3DDECLTYPE_SHORT4; - case VET_UBYTE4: - return D3DDECLTYPE_UBYTE4; - case VET_UBYTE4_NORM: - // valid only with vertex shaders >= 2.0 - return D3DDECLTYPE_UBYTE4N; - case VET_SHORT2_NORM: - // valid only with vertex shaders >= 2.0 - return D3DDECLTYPE_SHORT2N; - case VET_SHORT4_NORM: - // valid only with vertex shaders >= 2.0 - return D3DDECLTYPE_SHORT4N; - case VET_USHORT2_NORM: - // valid only with vertex shaders >= 2.0 - return D3DDECLTYPE_USHORT2N; - case VET_USHORT4_NORM: - // valid only with vertex shaders >= 2.0 - return D3DDECLTYPE_USHORT4N; - } - // to keep compiler happy - return D3DDECLTYPE_FLOAT3; - } - //--------------------------------------------------------------------- - D3DDECLUSAGE D3D9Mappings::get(VertexElementSemantic sem) - { - switch (sem) - { - case VES_BLEND_INDICES: - return D3DDECLUSAGE_BLENDINDICES; - break; - case VES_BLEND_WEIGHTS: - return D3DDECLUSAGE_BLENDWEIGHT; - break; - case VES_DIFFUSE: - return D3DDECLUSAGE_COLOR; // NB index will differentiate - break; - case VES_SPECULAR: - return D3DDECLUSAGE_COLOR; // NB index will differentiate - break; - case VES_NORMAL: - return D3DDECLUSAGE_NORMAL; - break; - case VES_POSITION: - return D3DDECLUSAGE_POSITION; - break; - case VES_TEXTURE_COORDINATES: - return D3DDECLUSAGE_TEXCOORD; - break; - case VES_BINORMAL: - return D3DDECLUSAGE_BINORMAL; - break; - case VES_TANGENT: - return D3DDECLUSAGE_TANGENT; - break; - } - // to keep compiler happy - return D3DDECLUSAGE_POSITION; - } - //--------------------------------------------------------------------- - D3DMATRIX D3D9Mappings::makeD3DXMatrix( const Matrix4& mat ) - { - // Transpose matrix - // D3D9 uses row vectors i.e. V*M - // Ogre, OpenGL and everything else uses column vectors i.e. M*V - return D3DMATRIX{ - mat[0][0], mat[1][0], mat[2][0], mat[3][0], - mat[0][1], mat[1][1], mat[2][1], mat[3][1], - mat[0][2], mat[1][2], mat[2][2], mat[3][2], - mat[0][3], mat[1][3], mat[2][3], mat[3][3]}; - } - //--------------------------------------------------------------------- - Matrix4 D3D9Mappings::convertD3DXMatrix( const D3DMATRIX& mat ) - { - return Matrix4( - mat.m[0][0], mat.m[1][0], mat.m[2][0], mat.m[3][0], - mat.m[0][1], mat.m[1][1], mat.m[2][1], mat.m[3][1], - mat.m[0][2], mat.m[1][2], mat.m[2][2], mat.m[3][2], - mat.m[0][3], mat.m[1][3], mat.m[2][3], mat.m[3][3]); - } - /****************************************************************************************/ - PixelFormat D3D9Mappings::_getPF(D3DFORMAT d3dPF) - { - switch(d3dPF) - { - case D3DFMT_A8: - return PF_A8; - case D3DFMT_L8: - return PF_L8; - case D3DFMT_L16: - return PF_L16; - case D3DFMT_A8L8: - return PF_BYTE_LA; // Assume little endian here - case D3DFMT_R3G3B2: - return PF_R3G3B2; - case D3DFMT_A1R5G5B5: - return PF_A1R5G5B5; - case D3DFMT_A4R4G4B4: - return PF_A4R4G4B4; - case D3DFMT_R5G6B5: - return PF_R5G6B5; - case D3DFMT_R8G8B8: - return PF_R8G8B8; - case D3DFMT_X8R8G8B8: - return PF_X8R8G8B8; - case D3DFMT_A8R8G8B8: - return PF_A8R8G8B8; - case D3DFMT_X8B8G8R8: - return PF_X8B8G8R8; - case D3DFMT_A8B8G8R8: - return PF_A8B8G8R8; - case D3DFMT_A2R10G10B10: - return PF_A2R10G10B10; - case D3DFMT_A2B10G10R10: - return PF_A2B10G10R10; - case D3DFMT_R16F: - return PF_FLOAT16_R; - case D3DFMT_A16B16G16R16F: - return PF_FLOAT16_RGBA; - case D3DFMT_R32F: - return PF_FLOAT32_R; - case D3DFMT_G32R32F: - return PF_FLOAT32_GR; - case D3DFMT_A32B32G32R32F: - return PF_FLOAT32_RGBA; - case D3DFMT_G16R16F: - return PF_FLOAT16_GR; - case D3DFMT_A16B16G16R16: - return PF_SHORT_RGBA; - case D3DFMT_G16R16: - return PF_SHORT_GR; - case D3DFMT_DXT1: - return PF_DXT1; - case D3DFMT_DXT2: - return PF_DXT2; - case D3DFMT_DXT3: - return PF_DXT3; - case D3DFMT_DXT4: - return PF_DXT4; - case D3DFMT_DXT5: - return PF_DXT5; - case D3DFMT_INTZ: - return PF_DEPTH16; - default: - return PF_UNKNOWN; - } - } - /****************************************************************************************/ - D3DFORMAT D3D9Mappings::_getPF(PixelFormat ogrePF) - { - switch(ogrePF) - { - case PF_L8: - return D3DFMT_L8; - case PF_L16: - return D3DFMT_L16; - case PF_A8: - return D3DFMT_A8; - case PF_BYTE_LA: - return D3DFMT_A8L8; // Assume little endian here - case PF_R3G3B2: - return D3DFMT_R3G3B2; - case PF_A1R5G5B5: - return D3DFMT_A1R5G5B5; - case PF_R5G6B5: - return D3DFMT_R5G6B5; - case PF_A4R4G4B4: - return D3DFMT_A4R4G4B4; - case PF_R8G8B8: - return D3DFMT_R8G8B8; - case PF_A8R8G8B8: - return D3DFMT_A8R8G8B8; - case PF_A8B8G8R8: - return D3DFMT_A8B8G8R8; - case PF_X8R8G8B8: - return D3DFMT_X8R8G8B8; - case PF_X8B8G8R8: - return D3DFMT_X8B8G8R8; - case PF_A2B10G10R10: - return D3DFMT_A2B10G10R10; - case PF_A2R10G10B10: - return D3DFMT_A2R10G10B10; - case PF_FLOAT16_R: - return D3DFMT_R16F; - case PF_FLOAT16_GR: - return D3DFMT_G16R16F; - case PF_FLOAT16_RGBA: - return D3DFMT_A16B16G16R16F; - case PF_FLOAT32_R: - return D3DFMT_R32F; - case PF_FLOAT32_GR: - return D3DFMT_G32R32F; - case PF_FLOAT32_RGBA: - return D3DFMT_A32B32G32R32F; - case PF_SHORT_RGBA: - return D3DFMT_A16B16G16R16; - case PF_SHORT_GR: - return D3DFMT_G16R16; - case PF_DXT1: - return D3DFMT_DXT1; - case PF_DXT2: - return D3DFMT_DXT2; - case PF_DXT3: - return D3DFMT_DXT3; - case PF_DXT4: - return D3DFMT_DXT4; - case PF_DXT5: - return D3DFMT_DXT5; - case PF_DEPTH16: - return D3DFMT_INTZ; - case PF_UNKNOWN: - default: - return D3DFMT_UNKNOWN; - } - } - /****************************************************************************************/ - PixelFormat D3D9Mappings::_getClosestSupportedPF(PixelFormat ogrePF) - { - if (_getPF(ogrePF) != D3DFMT_UNKNOWN) - { - return ogrePF; - } - switch(ogrePF) - { - case PF_B5G6R5: - return PF_R5G6B5; - case PF_B8G8R8: - return PF_R8G8B8; - case PF_B8G8R8A8: - return PF_A8R8G8B8; - case PF_SHORT_RGB: - return PF_SHORT_RGBA; - case PF_FLOAT16_RGB: - return PF_FLOAT16_RGBA; - case PF_FLOAT32_RGB: - return PF_FLOAT32_RGBA; - case PF_DEPTH16: - return PF_L16; - case PF_DEPTH32: - case PF_DEPTH32F: - return PF_FLOAT32_R; - case PF_UNKNOWN: - default: - return PF_A8R8G8B8; - } - } - -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9MultiRenderTarget.cpp b/RenderSystems/Direct3D9/src/OgreD3D9MultiRenderTarget.cpp deleted file mode 100755 index 4a6e4fdfc79..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9MultiRenderTarget.cpp +++ /dev/null @@ -1,173 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9MultiRenderTarget.h" -#include "OgreD3D9HardwarePixelBuffer.h" -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreBitwise.h" -#include "OgreD3D9RenderSystem.h" -#include "OgreRoot.h" -#include "OgreD3D9Device.h" -#include "OgreD3D9DeviceManager.h" -#include "OgreDepthBuffer.h" - -namespace Ogre -{ - D3D9MultiRenderTarget::D3D9MultiRenderTarget(const String &name): - MultiRenderTarget(name), mDepthTarget(NULL) - { - /// Clear targets - for(size_t x=0; xgetCustomAttribute("BUFFER", &buffer); - assert(buffer); - - /// Find first non-null target - int y; - for(y=0; ygetWidth() != buffer->getWidth() || - mRenderTargets[y]->getHeight() != buffer->getHeight()) - { - OGRE_EXCEPT( - Exception::ERR_INVALIDPARAMS, - "MultiRenderTarget surfaces are not of same size", - "D3D9MultiRenderTarget::bindSurface"); - } - - if (Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_MRT_SAME_BIT_DEPTHS) - && (PixelUtil::getNumElemBits(mRenderTargets[y]->getFormat()) != - PixelUtil::getNumElemBits(buffer->getFormat()))) - { - OGRE_EXCEPT( - Exception::ERR_INVALIDPARAMS, - "MultiRenderTarget surfaces are not of same bit depth and hardware requires it", - "D3D9MultiRenderTarget::bindSurface" - ); - } - } - - if(PixelUtil::isDepth(target->suggestPixelFormat())) - { - mDepthTarget = target; - mDepthBufferPoolId = DepthBuffer::POOL_DEFAULT; // we want attachDepthBuffer to happen - return; - } - - mRenderTargets[attachment] = buffer; - checkAndUpdate(); - } - - bool D3D9MultiRenderTarget::attachDepthBuffer( DepthBuffer *depthBuffer ) - { - if(!mDepthTarget) - return MultiRenderTarget::attachDepthBuffer(depthBuffer); - - mDepthBuffer = mDepthTarget->getDepthBuffer(); - mDepthBuffer->_notifyRenderTargetAttached(this); - return true; - } - - void D3D9MultiRenderTarget::unbindSurfaceImpl(size_t attachment) - { - assert(attachmentgetActiveRenderTargetDevice(); - - if (currRenderWindowDevice != NULL) - { - if (currRenderWindowDevice->isDeviceLost() == false) - MultiRenderTarget::update(swapBuffers); - } - else - { - for (UINT i=0; i < deviceManager->getDeviceCount(); ++i) - { - D3D9Device* device = deviceManager->getDevice(i); - - if (device->isDeviceLost() == false) - { - deviceManager->setActiveRenderTargetDevice(device); - MultiRenderTarget::update(swapBuffers); - deviceManager->setActiveRenderTargetDevice(NULL); - } - } - } - } - - void D3D9MultiRenderTarget::getCustomAttribute(const String& name, void *pData) - { - if(name == "DDBACKBUFFER") - { - IDirect3DSurface9 ** pSurf = (IDirect3DSurface9 **)pData; - /// Transfer surfaces - for(size_t x=0; xgetSurface(D3D9RenderSystem::getActiveD3D9Device()); - } - } - } - - void D3D9MultiRenderTarget::checkAndUpdate() - { - if(mRenderTargets[0]) - { - mWidth = (unsigned int)mRenderTargets[0]->getWidth(); - mHeight = (unsigned int)mRenderTargets[0]->getHeight(); - } - else - { - mWidth = 0; - mHeight = 0; - } - } -} - diff --git a/RenderSystems/Direct3D9/src/OgreD3D9Plugin.cpp b/RenderSystems/Direct3D9/src/OgreD3D9Plugin.cpp deleted file mode 100644 index 72399e0e2f8..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9Plugin.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreD3D9Plugin.h" -#include "OgreRoot.h" - -namespace Ogre -{ - const String sPluginName = "D3D9 RenderSystem"; - //--------------------------------------------------------------------- - D3D9Plugin::D3D9Plugin() - : mRenderSystem(0) - { - - } - //--------------------------------------------------------------------- - const String& D3D9Plugin::getName() const - { - return sPluginName; - } - - //--------------------------------------------------------------------- - void D3D9Plugin::install() - { - // Create the DirectX 9 rendering api - HINSTANCE hInst = NULL; - #ifdef __MINGW32__ - #ifdef OGRE_STATIC_LIB - hInst = GetModuleHandle( NULL ); - #else - #if OGRE_DEBUG_MODE == 1 - hInst = GetModuleHandle("RenderSystem_Direct3D9_d.dll"); - #else - hInst = GetModuleHandle("RenderSystem_Direct3D9.dll"); - #endif - #endif - #else - static const TCHAR staticVar; - GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, &staticVar, &hInst); - #endif - - mRenderSystem = OGRE_NEW D3D9RenderSystem( hInst ); - // Register the render system - Root::getSingleton().addRenderSystem( mRenderSystem ); - } - //--------------------------------------------------------------------- - void D3D9Plugin::initialise() - { - // nothing to do - } - //--------------------------------------------------------------------- - void D3D9Plugin::shutdown() - { - // nothing to do - } - //--------------------------------------------------------------------- - void D3D9Plugin::uninstall() - { - if (mRenderSystem != NULL) - { - OGRE_DELETE mRenderSystem; - mRenderSystem = NULL; - } - } - - -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9RenderSystem.cpp b/RenderSystems/Direct3D9/src/OgreD3D9RenderSystem.cpp deleted file mode 100644 index c58440ea84e..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9RenderSystem.cpp +++ /dev/null @@ -1,3816 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9RenderSystem.h" -#include "OgreD3D9Prerequisites.h" -#include "OgreD3D9DriverList.h" -#include "OgreD3D9Driver.h" -#include "OgreD3D9VideoModeList.h" -#include "OgreD3D9VideoMode.h" -#include "OgreD3D9RenderWindow.h" -#include "OgreD3D9TextureManager.h" -#include "OgreD3D9Texture.h" -#include "OgreLogManager.h" -#include "OgreMath.h" -#include "OgreViewport.h" -#include "OgreD3D9HardwareBufferManager.h" -#include "OgreD3D9HardwareBuffer.h" -#include "OgreD3D9VertexDeclaration.h" -#include "OgreD3D9GpuProgram.h" -#include "OgreD3D9GpuProgramManager.h" -#include "OgreD3D9HLSLProgramFactory.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreD3D9HardwareOcclusionQuery.h" -#include "OgreFrustum.h" -#include "OgreD3D9MultiRenderTarget.h" -#include "OgreCompositorManager.h" -#include "OgreD3D9DeviceManager.h" -#include "OgreD3D9ResourceManager.h" -#include "OgreD3D9DepthBuffer.h" - -#include - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 -#include "OgreD3D9StereoDriverBridge.h" -#endif - -#define FLOAT2DWORD(f) *((DWORD*)&f) - -static DWORD getSamplerId(size_t unit) { return static_cast(unit); } - -namespace Ogre -{ - D3D9RenderSystem* D3D9RenderSystem::msD3D9RenderSystem = NULL; - - //--------------------------------------------------------------------- - D3D9RenderSystem::D3D9RenderSystem( HINSTANCE hInstance ) : - mMultiheadUse(mutAuto) - ,mAllowDirectX9Ex(false) - ,mIsDirectX9Ex(false) -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - ,mStereoDriver (NULL) -#endif - { - LogManager::getSingleton().logMessage( "D3D9 : " + getName() + " created." ); - - // update singleton access pointer. - msD3D9RenderSystem = this; - - // set the instance being passed - mhInstance = hInstance; - - // set pointers to NULL - mD3D = NULL; - mDriverList = NULL; - mActiveD3DDriver = NULL; - mTextureManager = NULL; - mHardwareBufferManager = NULL; - mGpuProgramManager = NULL; - mUseNVPerfHUD = false; - mHLSLProgramFactory = NULL; - mDeviceManager = NULL; - mPerStageConstantSupport = false; - mEnableFixedPipeline = true; - mAutoHardwareBufferManagement = false; - - for(int i = 0 ; i < OGRE_MAX_TEXTURE_LAYERS ; i++) - { - for(int j = 0 ; j < 2 ; j++) - { - mManualBlendColours[i][j] = ColourValue::ZERO; - } - - } - - // Create the resource manager. - mResourceManager = OGRE_NEW D3D9ResourceManager(); - - - // init lights - for(int i = 0; i < MAX_LIGHTS; i++ ) - mLights[i] = 0; - - // Create our Direct3D object - if( NULL == (mD3D = Direct3DCreate9(D3D_SDK_VERSION)) ) - OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, "Failed to create Direct3D9 object", "D3D9RenderSystem::D3D9RenderSystem" ); - - // set config options defaults - initConfigOptions(); - - // set stages desc. to defaults - for (size_t n = 0; n < OGRE_MAX_TEXTURE_LAYERS; n++) - { - mTexStageDesc[n].autoTexCoordType = TEXCALC_NONE; - mTexStageDesc[n].coordIndex = 0; - mTexStageDesc[n].texType = D3D9Mappings::D3D_TEX_TYPE_NORMAL; - mTexStageDesc[n].pTex = 0; - } - - mLastVertexSourceCount = 0; - - mCurrentLights.clear(); - - // Enumerate events - mEventNames.push_back("DeviceLost"); - mEventNames.push_back("DeviceRestored"); - } - - const GpuProgramParametersPtr& D3D9RenderSystem::getFixedFunctionParams(TrackVertexColourType tracking, - FogMode fog) - { - _setSurfaceTracking(tracking); - _setFog(fog); - - return mFixedFunctionParams; - } - - void D3D9RenderSystem::applyFixedFunctionParams(const GpuProgramParametersSharedPtr& params, uint16 mask) - { - D3DMATERIAL9 material; - D3DLIGHT9 d3dLight; - ZeroMemory(&d3dLight, sizeof(D3DLIGHT9)); - - // Autoconstant index is not a physical index - for (const auto& ac : params->getAutoConstants()) - { - // Only update needed slots - if (ac.variability & mask) - { - HRESULT hr = S_OK; - const float* ptr = params->getFloatPointer(ac.physicalIndex); - switch(ac.paramType) - { - case GpuProgramParameters::ACT_WORLD_MATRIX: - setWorldMatrix(Matrix4(ptr)); - break; - case GpuProgramParameters::ACT_VIEW_MATRIX: - setViewMatrix(Matrix4(ptr)); - break; - case GpuProgramParameters::ACT_PROJECTION_MATRIX: - setProjectionMatrix(Matrix4(ptr)); - break; - case GpuProgramParameters::ACT_SURFACE_AMBIENT_COLOUR: - material.Ambient = D3DCOLORVALUE{ ptr[0], ptr[1], ptr[2], ptr[3]}; - break; - case GpuProgramParameters::ACT_SURFACE_DIFFUSE_COLOUR: - material.Diffuse = D3DCOLORVALUE{ ptr[0], ptr[1], ptr[2], ptr[3]}; - break; - case GpuProgramParameters::ACT_SURFACE_SPECULAR_COLOUR: - material.Specular = D3DCOLORVALUE{ ptr[0], ptr[1], ptr[2], ptr[3]}; - break; - case GpuProgramParameters::ACT_SURFACE_EMISSIVE_COLOUR: - material.Emissive = D3DCOLORVALUE{ ptr[0], ptr[1], ptr[2], ptr[3]}; - break; - case GpuProgramParameters::ACT_SURFACE_SHININESS: - material.Power = ptr[0]; - - // last material param -> apply - hr = getActiveD3D9Device()->SetMaterial( &material ); - if( FAILED( hr ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting D3D material", "D3D9RenderSystem::applyFixedFunctionParams" ); - break; - case GpuProgramParameters::ACT_POINT_PARAMS: - { - float size = ptr[0]; - // detect attenuation - if(ptr[1] != 1.0f || ptr[2] != 0.0f || ptr[3] != 0.0f) - size /= mActiveViewport->getActualHeight(); // data source scales points by height - __SetFloatRenderState(D3DRS_POINTSIZE, size); - __SetFloatRenderState(D3DRS_POINTSCALE_A, ptr[1]); - __SetFloatRenderState(D3DRS_POINTSCALE_B, ptr[2]); - __SetFloatRenderState(D3DRS_POINTSCALE_C, ptr[3]); - break; - } - case GpuProgramParameters::ACT_FOG_PARAMS: - hr = __SetFloatRenderState( D3DRS_FOGDENSITY, ptr[0] ); - hr = __SetFloatRenderState( D3DRS_FOGSTART, ptr[1] ); - hr = __SetFloatRenderState( D3DRS_FOGEND, ptr[2] ); - break; - case GpuProgramParameters::ACT_FOG_COLOUR: - hr = __SetRenderState( D3DRS_FOGCOLOR, ColourValue(ptr[0], ptr[1], ptr[2], ptr[3]).getAsARGB()); - break; - case GpuProgramParameters::ACT_AMBIENT_LIGHT_COLOUR: - hr = __SetRenderState( D3DRS_AMBIENT, D3DCOLOR_COLORVALUE( ptr[0], ptr[1], ptr[2], 1.0f ) ); - break; - case GpuProgramParameters::ACT_LIGHT_POSITION: - d3dLight.Type = ptr[3] ? D3DLIGHT_POINT : D3DLIGHT_DIRECTIONAL; - d3dLight.Position = D3DVECTOR{ ptr[0], ptr[1], ptr[2] }; - break; - case GpuProgramParameters::ACT_LIGHT_DIRECTION: - d3dLight.Direction = D3DVECTOR{ ptr[0], ptr[1], ptr[2] }; - break; - case GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR: - d3dLight.Diffuse = D3DCOLORVALUE{ ptr[0], ptr[1], ptr[2], ptr[3] }; - break; - case GpuProgramParameters::ACT_LIGHT_SPECULAR_COLOUR: - d3dLight.Specular = D3DCOLORVALUE{ ptr[0], ptr[1], ptr[2], ptr[3] }; - break; - case GpuProgramParameters::ACT_LIGHT_ATTENUATION: - d3dLight.Range = ptr[0]; - d3dLight.Attenuation0 = ptr[1]; - d3dLight.Attenuation1 = ptr[2]; - d3dLight.Attenuation2 = ptr[3]; - break; - case GpuProgramParameters::ACT_SPOTLIGHT_PARAMS: - if(ptr[3]) d3dLight.Type = D3DLIGHT_SPOT; - d3dLight.Theta = std::acos(ptr[0])*2; - d3dLight.Phi = std::acos(ptr[1])*2; - d3dLight.Falloff = ptr[2]; - - // last light param -> apply - if( FAILED( hr = getActiveD3D9Device()->SetLight( static_cast(ac.data), &d3dLight ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to set light details", "D3D9RenderSystem::setD3D9Light" ); - - if( FAILED( hr = getActiveD3D9Device()->LightEnable( static_cast(ac.data), TRUE ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to enable light", "D3D9RenderSystem::setD3D9Light" ); - break; - default: - OgreAssert(false, "unknown autoconstant"); - break; - } - if( FAILED( hr ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting render state", "D3D9RenderSystem::applyFixedFunctionParams" ); - } - } - } - - //--------------------------------------------------------------------- - D3D9RenderSystem::~D3D9RenderSystem() - { - shutdown(); - - // Deleting the HLSL program factory - if (mHLSLProgramFactory) - { - // Remove from manager safely - if (HighLevelGpuProgramManager::getSingletonPtr()) - HighLevelGpuProgramManager::getSingleton().removeFactory(mHLSLProgramFactory); - OGRE_DELETE mHLSLProgramFactory; - mHLSLProgramFactory = 0; - } - - SAFE_RELEASE( mD3D ); - - if (mResourceManager != NULL) - { - OGRE_DELETE mResourceManager; - mResourceManager = NULL; - } - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - OGRE_DELETE mStereoDriver; - mStereoDriver = NULL; -#endif - - LogManager::getSingleton().logMessage( "D3D9 : " + getName() + " destroyed." ); - - msD3D9RenderSystem = NULL; - } - //--------------------------------------------------------------------- - const String& D3D9RenderSystem::getName() const - { - static String strName( "Direct3D9 Rendering Subsystem"); - return strName; - } - - D3D9DriverList* D3D9RenderSystem::getDirect3DDrivers() - { - if( !mDriverList ) - mDriverList = OGRE_NEW D3D9DriverList(); - - return mDriverList; - } - //--------------------------------------------------------------------- - bool D3D9RenderSystem::_checkMultiSampleQuality(D3DMULTISAMPLE_TYPE type, DWORD *outQuality, D3DFORMAT format, UINT adapterNum, D3DDEVTYPE deviceType, BOOL fullScreen) - { - HRESULT hr; - hr = mD3D->CheckDeviceMultiSampleType( - adapterNum, - deviceType, - format, - fullScreen, - type, - outQuality); - - if (SUCCEEDED(hr)) - return true; - else - return false; - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::initConfigOptions() - { - RenderSystem::initConfigOptions(); - - D3D9DriverList* driverList; - D3D9Driver* driver; - - ConfigOption optDevice; - ConfigOption optAllowDirectX9Ex; - ConfigOption optVideoMode; - ConfigOption optMultihead; - ConfigOption optAA; - ConfigOption optFPUMode; - ConfigOption optNVPerfHUD; - ConfigOption optResourceCeationPolicy; - ConfigOption optMultiDeviceMemHint; - ConfigOption optEnableFixedPipeline; - - driverList = this->getDirect3DDrivers(); - - optDevice.name = "Rendering Device"; - optDevice.currentValue.clear(); - optDevice.possibleValues.clear(); - optDevice.immutable = false; - - optAllowDirectX9Ex.name = "Allow DirectX9Ex"; - optAllowDirectX9Ex.possibleValues.push_back( "Yes" ); - optAllowDirectX9Ex.possibleValues.push_back( "No" ); - optAllowDirectX9Ex.currentValue = "No"; - optAllowDirectX9Ex.immutable = false; - - optVideoMode.name = "Video Mode"; - optVideoMode.currentValue = "800 x 600 @ 32-bit colour"; - optVideoMode.immutable = false; - - optMultihead.name = "Use Multihead"; - optMultihead.possibleValues.push_back( "Auto" ); - optMultihead.possibleValues.push_back( "Yes" ); - optMultihead.possibleValues.push_back( "No" ); - optMultihead.currentValue = "Auto"; - optMultihead.immutable = false; - - optResourceCeationPolicy.name = "Resource Creation Policy"; - optResourceCeationPolicy.possibleValues.push_back( "Create on all devices" ); - optResourceCeationPolicy.possibleValues.push_back( "Create on active device" ); - - if (mResourceManager->getCreationPolicy() == RCP_CREATE_ON_ACTIVE_DEVICE) - optResourceCeationPolicy.currentValue = "Create on active device"; - else if (mResourceManager->getCreationPolicy() == RCP_CREATE_ON_ALL_DEVICES) - optResourceCeationPolicy.currentValue = "Create on all devices"; - else - optResourceCeationPolicy.currentValue = "N/A"; - optResourceCeationPolicy.immutable = false; - - for( unsigned j=0; j < driverList->count(); j++ ) - { - driver = driverList->item(j); - optDevice.possibleValues.push_back( driver->DriverDescription() ); - // Make first one default - if( j==0 ) - optDevice.currentValue = driver->DriverDescription(); - } - - optAA.name = "FSAA"; - optAA.immutable = false; - optAA.possibleValues.push_back( "None" ); - optAA.currentValue = "None"; - - optFPUMode.name = "Floating-point mode"; -#if OGRE_DOUBLE_PRECISION - optFPUMode.currentValue = "Consistent"; -#else - optFPUMode.currentValue = "Fastest"; -#endif - optFPUMode.possibleValues.clear(); - optFPUMode.possibleValues.push_back("Fastest"); - optFPUMode.possibleValues.push_back("Consistent"); - optFPUMode.immutable = false; - - optNVPerfHUD.currentValue = "No"; - optNVPerfHUD.immutable = false; - optNVPerfHUD.name = "Allow NVPerfHUD"; - optNVPerfHUD.possibleValues.push_back( "Yes" ); - optNVPerfHUD.possibleValues.push_back( "No" ); - - // Multiple device memory usage hint. - optMultiDeviceMemHint.name = "Auto hardware buffer management"; - optMultiDeviceMemHint.possibleValues.push_back("Yes"); - optMultiDeviceMemHint.possibleValues.push_back("No"); - optMultiDeviceMemHint.currentValue = optMultiDeviceMemHint.possibleValues[0]; - optMultiDeviceMemHint.immutable = false; - - optEnableFixedPipeline.name = "Fixed Pipeline Enabled"; - optEnableFixedPipeline.possibleValues.push_back( "Yes" ); - optEnableFixedPipeline.possibleValues.push_back( "No" ); - optEnableFixedPipeline.currentValue = "Yes"; - optEnableFixedPipeline.immutable = false; - - mOptions[optDevice.name] = optDevice; - mOptions[optAllowDirectX9Ex.name] = optAllowDirectX9Ex; - mOptions[optVideoMode.name] = optVideoMode; - mOptions[optMultihead.name] = optMultihead; - mOptions[optAA.name] = optAA; - mOptions[optFPUMode.name] = optFPUMode; - mOptions[optNVPerfHUD.name] = optNVPerfHUD; - mOptions[optResourceCeationPolicy.name] = optResourceCeationPolicy; - mOptions[optMultiDeviceMemHint.name] = optMultiDeviceMemHint; - mOptions[optEnableFixedPipeline.name] = optEnableFixedPipeline; - - refreshD3DSettings(); - - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::refreshD3DSettings() - { - ConfigOption* optVideoMode; - D3D9Driver* driver = 0; - D3D9VideoMode* videoMode; - - ConfigOptionMap::iterator opt = mOptions.find( "Rendering Device" ); - if( opt != mOptions.end() ) - { - for( unsigned j=0; j < getDirect3DDrivers()->count(); j++ ) - { - D3D9Driver* curDriver = getDirect3DDrivers()->item(j); - if( curDriver->DriverDescription() == opt->second.currentValue ) - { - driver = curDriver; - break; - } - } - - if (driver) - { - opt = mOptions.find( "Video Mode" ); - optVideoMode = &opt->second; - optVideoMode->possibleValues.clear(); - // get vide modes for this device - for( unsigned k=0; k < driver->getVideoModeList()->count(); k++ ) - { - videoMode = driver->getVideoModeList()->item( k ); - optVideoMode->possibleValues.push_back( videoMode->getDescription() ); - } - - // Reset video mode to default if previous doesn't avail in new possible values - StringVector::const_iterator itValue = - std::find(optVideoMode->possibleValues.begin(), - optVideoMode->possibleValues.end(), - optVideoMode->currentValue); - if (itValue == optVideoMode->possibleValues.end()) - { - optVideoMode->currentValue = "800 x 600 @ 32-bit colour"; - } - - // Also refresh FSAA options - refreshFSAAOptions(); - } - } - - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::setConfigOption( const String &name, const String &value ) - { - - LogManager::getSingleton().stream() - << "D3D9 : RenderSystem Option: " << name << " = " << value; - - bool viewModeChanged = false; - - // Find option - ConfigOptionMap::iterator it = mOptions.find( name ); - - // Update - if( it != mOptions.end() ) - it->second.currentValue = value; - else - { - StringStream str; - str << "Option named '" << name << "' does not exist."; - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, str.str(), "D3D9RenderSystem::setConfigOption" ); - } - - // Refresh other options if D3DDriver changed - if( name == "Rendering Device" ) - refreshD3DSettings(); - - if ( name == "Allow DirectX9Ex" ) - { - if (value == "Yes") - mAllowDirectX9Ex = true; - else mAllowDirectX9Ex = false; - - // Create our Direct3D object - if (mAllowDirectX9Ex && !mIsDirectX9Ex) - { - SAFE_RELEASE(mD3D); - HMODULE hD3D = LoadLibrary(TEXT("d3d9.dll")); - if (hD3D) - { - typedef HRESULT (WINAPI *DIRECT3DCREATE9EXFUNCTION)(UINT, IDirect3D9Ex**); - DIRECT3DCREATE9EXFUNCTION pfnCreate9Ex = (DIRECT3DCREATE9EXFUNCTION)GetProcAddress(hD3D, "Direct3DCreate9Ex"); - if (pfnCreate9Ex) - { - IDirect3D9Ex* d3dEx = NULL; - (*pfnCreate9Ex)(D3D_SDK_VERSION, &d3dEx); - d3dEx->QueryInterface(__uuidof(IDirect3D9), reinterpret_cast(&mD3D)); - mIsDirectX9Ex = true; - } - FreeLibrary(hD3D); - } - } - if ((mD3D == NULL) || (!mAllowDirectX9Ex && mIsDirectX9Ex)) - { - if ( NULL == (mD3D = Direct3DCreate9(D3D_SDK_VERSION)) ) - OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, "Failed to create Direct3D9 object", "D3D9RenderSystem::D3D9RenderSystem" ); - } - } - - if( name == "Full Screen" ) - { - // Video mode is applicable - it = mOptions.find( "Video Mode" ); - if (it->second.currentValue.empty()) - { - it->second.currentValue = "800 x 600 @ 32-bit colour"; - viewModeChanged = true; - } - } - - if( name == "Use Multihead" ) - { - if (value == "Yes") - mMultiheadUse = mutYes; - else if (value == "No") - mMultiheadUse = mutNo; - else mMultiheadUse = mutAuto; - } - - if( name == "Allow NVPerfHUD" ) - { - if (value == "Yes") - mUseNVPerfHUD = true; - else - mUseNVPerfHUD = false; - } - - if (viewModeChanged || name == "Video Mode") - { - refreshFSAAOptions(); - } - - if (name == "Resource Creation Policy") - { - if (value == "Create on active device") - mResourceManager->setCreationPolicy(RCP_CREATE_ON_ACTIVE_DEVICE); - else if (value == "Create on all devices") - mResourceManager->setCreationPolicy(RCP_CREATE_ON_ALL_DEVICES); - } - - if (name == "Auto hardware buffer management") - { - StringConverter::parse(value, mAutoHardwareBufferManagement); - } - - if (name == "Fixed Pipeline Enabled") - { - if (value == "Yes") - { - mEnableFixedPipeline = true; - } - else - mEnableFixedPipeline = false; - } - - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::refreshFSAAOptions() - { - - ConfigOptionMap::iterator it = mOptions.find( "FSAA" ); - ConfigOption* optFSAA = &it->second; - optFSAA->possibleValues.clear(); - optFSAA->possibleValues.push_back("0"); - - it = mOptions.find("Rendering Device"); - D3D9Driver *driver = getDirect3DDrivers()->item(it->second.currentValue); - if (driver) - { - it = mOptions.find("Video Mode"); - D3D9VideoMode *videoMode = driver->getVideoModeList()->item(it->second.currentValue); - if (videoMode) - { - bool bOK; - - for (unsigned int n = (unsigned int)D3DMULTISAMPLE_2_SAMPLES; n <= (unsigned int)D3DMULTISAMPLE_16_SAMPLES; n++) - { - DWORD numLevels = 2; - bOK = this->_checkMultiSampleQuality( - (D3DMULTISAMPLE_TYPE)n, - &numLevels, - videoMode->getFormat(), - driver->getAdapterNumber(), - D3DDEVTYPE_HAL, - TRUE); - if (bOK) - { - // CSAA modes supported by both AMD and Nvidia - if (n == 8 && numLevels > 2) optFSAA->possibleValues.push_back("4f8"); - if (n == 16 && numLevels > 2) optFSAA->possibleValues.push_back("8f16"); - optFSAA->possibleValues.push_back(StringConverter::toString(n)); - } - } - - } - } - - // Reset FSAA to none if previous doesn't avail in new possible values - StringVector::const_iterator itValue = - std::find(optFSAA->possibleValues.begin(), - optFSAA->possibleValues.end(), - optFSAA->currentValue); - if (itValue == optFSAA->possibleValues.end()) - { - optFSAA->currentValue = "0"; - } - - } - //--------------------------------------------------------------------- - String D3D9RenderSystem::validateConfigOptions() - { - ConfigOptionMap::iterator it; - - // check if video mode is selected - it = mOptions.find( "Video Mode" ); - if (it->second.currentValue.empty()) - return "A video mode must be selected."; - - it = mOptions.find( "Rendering Device" ); - bool foundDriver = false; - D3D9DriverList* driverList = getDirect3DDrivers(); - for( ushort j=0; j < driverList->count(); j++ ) - { - if( driverList->item(j)->DriverDescription() == it->second.currentValue ) - { - foundDriver = true; - break; - } - } - - if (!foundDriver) - { - // Just pick the first driver - setConfigOption("Rendering Device", driverList->item(0)->DriverDescription()); - return "Your DirectX driver name has changed since the last time you ran OGRE; " - "the 'Rendering Device' has been changed."; - } - - return BLANKSTRING; - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_initialise() - { - // call superclass method - RenderSystem::_initialise(); - LogManager::getSingleton().logMessage( "D3D9 : Subsystem Initialising" ); - - // Init using current settings - mActiveD3DDriver = NULL; - ConfigOptionMap::iterator opt = mOptions.find( "Rendering Device" ); - for( uint j=0; j < getDirect3DDrivers()->count(); j++ ) - { - if( getDirect3DDrivers()->item(j)->DriverDescription() == opt->second.currentValue ) - { - mActiveD3DDriver = getDirect3DDrivers()->item(j); - break; - } - } - - if( !mActiveD3DDriver ) - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Problems finding requested Direct3D driver!", "D3D9RenderSystem::initialise" ); - - // get driver version - mDriverVersion.major = HIWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.HighPart); - mDriverVersion.minor = LOWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.HighPart); - mDriverVersion.release = HIWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.LowPart); - mDriverVersion.build = LOWORD(mActiveD3DDriver->getAdapterIdentifier().DriverVersion.LowPart); - - // Create the device manager. - mDeviceManager = OGRE_NEW D3D9DeviceManager(); - - // Create the texture manager for use by others - mTextureManager = OGRE_NEW D3D9TextureManager(); - - // Also create hardware buffer manager - mHardwareBufferManager = OGRE_NEW D3D9HardwareBufferManager(); - mHardwareBufferManager->setAutoHardwareBufferManagement(mAutoHardwareBufferManagement); - - // Create the GPU program manager - mGpuProgramManager = OGRE_NEW D3D9GpuProgramManager(); - - // Create & register HLSL factory - mHLSLProgramFactory = OGRE_NEW D3D9HLSLProgramFactory(); - - LogManager::getSingleton().logMessage("***************************************"); - LogManager::getSingleton().logMessage("*** D3D9 : Subsystem Initialised OK ***"); - LogManager::getSingleton().logMessage("***************************************"); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::shutdown() - { - RenderSystem::shutdown(); - - if (mDeviceManager != NULL) - { - OGRE_DELETE mDeviceManager; - mDeviceManager = NULL; - } - - if (mDriverList != NULL) - { - OGRE_DELETE mDriverList; - mDriverList = NULL; - } - mActiveD3DDriver = NULL; - - LogManager::getSingleton().logMessage("D3D9 : Shutting down cleanly."); - - if (mTextureManager != NULL) - { - OGRE_DELETE mTextureManager; - mTextureManager = NULL; - } - - if (mHardwareBufferManager != NULL) - { - OGRE_DELETE mHardwareBufferManager; - mHardwareBufferManager = NULL; - } - - if (mGpuProgramManager != NULL) - { - OGRE_DELETE mGpuProgramManager; - mGpuProgramManager = NULL; - } - } - //--------------------------------------------------------------------- - RenderWindow* D3D9RenderSystem::_createRenderWindow(const String &name, - unsigned int width, unsigned int height, bool fullScreen, - const NameValuePairList *miscParams) - { - RenderSystem::_createRenderWindow(name, width, height, fullScreen, miscParams); - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - // Stereo driver must be created before device is created - createStereoDriver(miscParams); -#endif - - D3D9RenderWindow* renderWindow = OGRE_NEW D3D9RenderWindow(mhInstance); - - renderWindow->create(name, width, height, fullScreen, miscParams); - - mResourceManager->lockDeviceAccess(); - - try - { - mDeviceManager->linkRenderWindow(renderWindow); - } - catch (const Ogre::RenderingAPIException&) - { - // after catching the exception, clean up - mResourceManager->unlockDeviceAccess(); - renderWindow->destroy(); - - // re-throw - throw; - } - - mResourceManager->unlockDeviceAccess(); - - mRenderWindows.push_back(renderWindow); - - updateRenderSystemCapabilities(renderWindow); - - attachRenderTarget( *renderWindow ); - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - // Must be called after device has been linked to window - D3D9StereoDriverBridge::getSingleton().addRenderWindow(renderWindow); - renderWindow->_validateStereo(); -#endif - - return renderWindow; - } - //--------------------------------------------------------------------- - RenderSystemCapabilities* D3D9RenderSystem::updateRenderSystemCapabilities(D3D9RenderWindow* renderWindow) - { - RenderSystemCapabilities* rsc = mRealCapabilities; - if (rsc == NULL) - rsc = OGRE_NEW RenderSystemCapabilities(); - - rsc->setCategoryRelevant(CAPS_CATEGORY_D3D9, true); - rsc->setDriverVersion(mDriverVersion); - rsc->setDeviceName(mActiveD3DDriver->DriverDescription()); - rsc->setRenderSystemName(getName()); - - if(mEnableFixedPipeline) - { - // Supports fixed-function - rsc->setCapability(RSC_FIXED_FUNCTION); - } - - - // Init caps to maximum. - rsc->setNumTextureUnits(OGRE_MAX_TEXTURE_LAYERS); - rsc->setNumVertexAttributes(14); // see D3DDECLUSAGE - rsc->setCapability(RSC_ANISOTROPY); - rsc->setCapability(RSC_TWO_SIDED_STENCIL); - rsc->setCapability(RSC_STENCIL_WRAP); - rsc->setCapability(RSC_HWOCCLUSION); - rsc->setCapability(RSC_USER_CLIP_PLANES); - rsc->setCapability(RSC_32BIT_INDEX); - rsc->setCapability(RSC_TEXTURE_1D); - rsc->setCapability(RSC_TEXTURE_3D); - rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES); - rsc->setNonPOW2TexturesLimited(false); - rsc->setNumMultiRenderTargets(OGRE_MAX_MULTIPLE_RENDER_TARGETS); - rsc->setCapability(RSC_POINT_SPRITES); - rsc->setMaxPointSize(2.19902e+012f); - rsc->setCapability(RSC_MIPMAP_LOD_BIAS); - rsc->setCapability(RSC_PERSTAGECONSTANT); - rsc->setCapability(RSC_HWSTENCIL); - rsc->setCapability(RSC_RTT_MAIN_DEPTHBUFFER_ATTACHABLE); - rsc->setCapability(RSC_RTT_DEPTHBUFFER_RESOLUTION_LESSEQUAL); - rsc->setCapability(RSC_VERTEX_BUFFER_INSTANCE_DATA); - rsc->setCapability(RSC_CAN_GET_COMPILED_SHADER_BUFFER); - rsc->setCapability(RSC_WBUFFER); - - for (uint i=0; i < mDeviceManager->getDeviceCount(); ++i) - { - D3D9Device* device = mDeviceManager->getDevice(i); - IDirect3DDevice9* d3d9Device = device->getD3D9Device(); - - IDirect3DSurface9* pSurf; - - - // Check for hardware stencil support - d3d9Device->GetDepthStencilSurface(&pSurf); - - if (pSurf != NULL) - { - D3DSURFACE_DESC surfDesc; - - pSurf->GetDesc(&surfDesc); - pSurf->Release(); - - if (surfDesc.Format != D3DFMT_D15S1 && - surfDesc.Format != D3DFMT_D24S8 && - surfDesc.Format != D3DFMT_D24X4S4 && - surfDesc.Format != D3DFMT_D24FS8) - rsc->unsetCapability(RSC_HWSTENCIL); - } - - // Check for hardware occlusion support - HRESULT hr = d3d9Device->CreateQuery(D3DQUERYTYPE_OCCLUSION, NULL); - - if (FAILED(hr)) - rsc->unsetCapability(RSC_HWOCCLUSION); - } - - // Update RS caps using the minimum value found in adapter list. - for (unsigned int i=0; i < mDriverList->count(); ++i) - { - D3D9Driver* pCurDriver = mDriverList->item(i); - const D3DCAPS9& rkCurCaps = pCurDriver->getD3D9DeviceCaps(); - - bool has_level_9_1 = true; - - // Check for Anisotropy. - if (rkCurCaps.MaxAnisotropy <= 1) - rsc->unsetCapability(RSC_ANISOTROPY); - - // Check Dot product 3. - if ((rkCurCaps.TextureOpCaps & D3DTEXOPCAPS_DOTPRODUCT3) == 0) - has_level_9_1 = false; - - // Scissor test - if ((rkCurCaps.RasterCaps & D3DPRASTERCAPS_SCISSORTEST) == 0) - has_level_9_1 = false; - - if ((rkCurCaps.RasterCaps & (D3DPRASTERCAPS_DEPTHBIAS | D3DPRASTERCAPS_SLOPESCALEDEPTHBIAS)) == 0) - has_level_9_1 = false; - - // Two-sided stencil - if ((rkCurCaps.StencilCaps & D3DSTENCILCAPS_TWOSIDED) == 0) - has_level_9_1 = false; - - // stencil wrap - if ((rkCurCaps.StencilCaps & D3DSTENCILCAPS_INCR) == 0 || - (rkCurCaps.StencilCaps & D3DSTENCILCAPS_DECR) == 0) - rsc->unsetCapability(RSC_STENCIL_WRAP); - - // User clip planes - if (rkCurCaps.MaxUserClipPlanes == 0) - rsc->unsetCapability(RSC_USER_CLIP_PLANES); - - // D3DFMT_INDEX32 type? - if (rkCurCaps.MaxVertexIndex <= 0xFFFF) - rsc->unsetCapability(RSC_32BIT_INDEX); - - // UBYTE4 type? - if ((rkCurCaps.DeclTypes & D3DDTCAPS_UBYTE4) == 0) - has_level_9_1 = false; - - // Check cube map support. - if ((rkCurCaps.TextureCaps & D3DPTEXTURECAPS_CUBEMAP) == 0) - has_level_9_1 = false; - - // 3D textures? - if ((rkCurCaps.TextureCaps & D3DPTEXTURECAPS_VOLUMEMAP) == 0) - rsc->unsetCapability(RSC_TEXTURE_3D); - - if (rkCurCaps.TextureCaps & D3DPTEXTURECAPS_POW2) - { - // Conditional support for non POW2 - if (rkCurCaps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL) - rsc->setNonPOW2TexturesLimited(true); - - // Only power of 2 supported. - else - rsc->unsetCapability(RSC_NON_POWER_OF_2_TEXTURES); - } - - // Number of render targets - if (rkCurCaps.NumSimultaneousRTs < rsc->getNumMultiRenderTargets()) - { - rsc->setNumMultiRenderTargets(std::min((ushort)rkCurCaps.NumSimultaneousRTs, (ushort)OGRE_MAX_MULTIPLE_RENDER_TARGETS)); - } - - if((rkCurCaps.PrimitiveMiscCaps & D3DPMISCCAPS_MRTINDEPENDENTBITDEPTHS) == 0) - { - rsc->setCapability(RSC_MRT_SAME_BIT_DEPTHS); - } - - // Point sprites - if (rkCurCaps.MaxPointSize <= 1.0f) - { - rsc->unsetCapability(RSC_POINT_SPRITES); - } - - // Take the minimum point size. - if (rkCurCaps.MaxPointSize < rsc->getMaxPointSize()) - rsc->setMaxPointSize(rkCurCaps.MaxPointSize); - - // Mipmap LOD biasing? - if ((rkCurCaps.RasterCaps & D3DPRASTERCAPS_MIPMAPLODBIAS) == 0) - rsc->unsetCapability(RSC_MIPMAP_LOD_BIAS); - - if((rkCurCaps.RasterCaps & D3DPRASTERCAPS_WBUFFER) == 0) - rsc->unsetCapability(RSC_WBUFFER); - - // Do we support per-stage src_manual constants? - // HACK - ATI drivers seem to be buggy and don't support per-stage constants properly? - // TODO: move this to RSC - if((rkCurCaps.PrimitiveMiscCaps & D3DPMISCCAPS_PERSTAGECONSTANT) == 0) - rsc->unsetCapability(RSC_PERSTAGECONSTANT); - - // Advanced blend operations? min max subtract rev - if((rkCurCaps.PrimitiveMiscCaps & D3DPMISCCAPS_BLENDOP) == 0) - has_level_9_1 = false; - - // see https://technet.microsoft.com/en-us/evalcenter/jj841213(v=vs.90) - if (!has_level_9_1) - LogManager::getSingleton().logError( - "D3D9 feature level 9.1 required, but at least one Capability is not supported"); - } - - // We always support compression, D3DX will decompress if device does not support - rsc->setCapability(RSC_TEXTURE_COMPRESSION); - rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT); - - convertVertexShaderCaps(rsc); - convertPixelShaderCaps(rsc); - - // Adapter details - const D3DADAPTER_IDENTIFIER9& adapterID = mActiveD3DDriver->getAdapterIdentifier(); - - // determine vendor - // Full list of vendors here: http://www.pcidatabase.com/vendors.php?sort=id - switch(adapterID.VendorId) - { - case 0x10DE: - rsc->setVendor(GPU_NVIDIA); - break; - case 0x1002: - rsc->setVendor(GPU_AMD); - break; - case 0x163C: - case 0x8086: - rsc->setVendor(GPU_INTEL); - break; - default: - rsc->setVendor(GPU_UNKNOWN); - break; - }; - - // We always support rendertextures bigger than the frame buffer - rsc->setCapability(RSC_HWRENDER_TO_TEXTURE); - - // Determine if any floating point texture format is supported - D3DFORMAT floatFormats[6] = {D3DFMT_R16F, D3DFMT_G16R16F, - D3DFMT_A16B16G16R16F, D3DFMT_R32F, D3DFMT_G32R32F, - D3DFMT_A32B32G32R32F}; - IDirect3DSurface9* bbSurf; - renderWindow->getCustomAttribute("DDBACKBUFFER", &bbSurf); - D3DSURFACE_DESC bbSurfDesc; - bbSurf->GetDesc(&bbSurfDesc); - - for (int i = 0; i < 6; ++i) - { - if (SUCCEEDED(mD3D->CheckDeviceFormat(mActiveD3DDriver->getAdapterNumber(), - D3DDEVTYPE_HAL, bbSurfDesc.Format, - 0, D3DRTYPE_TEXTURE, floatFormats[i]))) - { - rsc->setCapability(RSC_TEXTURE_FLOAT); - break; - } - - } - - - // TODO: make convertVertex/Fragment fill in rsc - // TODO: update the below line to use rsc - // Vertex textures - if (rsc->isShaderProfileSupported("vs_3_0")) - { - // Run through all the texture formats looking for any which support - // vertex texture fetching. Must have at least one! - // All ATI Radeon up to X1n00 say they support vs_3_0, - // but they support no texture formats for vertex texture fetch (cheaters!) - if (checkVertexTextureFormats(renderWindow)) - { - rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH); - // always 4 vertex texture units in vs_3_0, and never shared - rsc->setNumVertexTextureUnits(4); - } - } - else - { - //True HW Instancing is supported since Shader model 3.0 ATI has a nasty - //hack for enabling it in their SM 2.0 cards, but we don't (and won't) support it - rsc->unsetCapability( RSC_VERTEX_BUFFER_INSTANCE_DATA ); - } - - // Check alpha to coverage support - // this varies per vendor! But at least SM3 is required - if (rsc->isShaderProfileSupported("ps_3_0")) - { - // NVIDIA needs a separate check - if (rsc->getVendor() == GPU_NVIDIA) - { - if (mD3D->CheckDeviceFormat( - D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, D3DFMT_X8R8G8B8, 0,D3DRTYPE_SURFACE, - (D3DFORMAT)MAKEFOURCC('A', 'T', 'O', 'C')) == S_OK) - { - rsc->setCapability(RSC_ALPHA_TO_COVERAGE); - } - - } - else if (rsc->getVendor() == GPU_AMD) - { - // There is no check on ATI, we have to assume SM3 == support - rsc->setCapability(RSC_ALPHA_TO_COVERAGE); - } - - // no other cards have Dx9 hacks for alpha to coverage, as far as I know - } - - - if (mRealCapabilities == NULL) - { - mRealCapabilities = rsc; - mRealCapabilities->addShaderProfile("hlsl"); - - initFixedFunctionParams(); // create params - - // if we are using custom capabilities, then - // mCurrentCapabilities has already been loaded - if(!mUseCustomCapabilities) - mCurrentCapabilities = mRealCapabilities; - - fireEvent("RenderSystemCapabilitiesCreated"); - - initialiseFromRenderSystemCapabilities(mCurrentCapabilities, renderWindow); - } - - return rsc; - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::convertVertexShaderCaps(RenderSystemCapabilities* rsc) - { - ushort major = 0xFF; - ushort minor = 0xFF; - D3DCAPS9 minVSCaps; - - // Find the device with the lowest vertex shader caps. - for (unsigned int i=0; i < mDriverList->count(); ++i) - { - D3D9Driver* pCurDriver = mDriverList->item(i); - const D3DCAPS9& rkCurCaps = pCurDriver->getD3D9DeviceCaps(); - ushort currMajor = static_cast((rkCurCaps.VertexShaderVersion & 0x0000FF00) >> 8); - ushort currMinor = static_cast(rkCurCaps.VertexShaderVersion & 0x000000FF); - - if (currMajor < major) - { - major = currMajor; - minor = currMinor; - minVSCaps = rkCurCaps; - } - else if (currMajor == major && currMinor < minor) - { - minor = currMinor; - minVSCaps = rkCurCaps; - } - } - - // In case we didn't found any vertex shader support - // try the IDirect3DDevice9 caps instead of the IDirect3D9 - // software vertex processing is reported there - if (major == 0 && minor == 0) - { - IDirect3DDevice9* lpD3DDevice9 = getActiveD3D9Device(); - D3DCAPS9 d3dDeviceCaps9; - lpD3DDevice9->GetDeviceCaps(&d3dDeviceCaps9); - major = static_cast((d3dDeviceCaps9.VertexShaderVersion & 0x0000FF00) >> 8); - minor = static_cast(d3dDeviceCaps9.VertexShaderVersion & 0x000000FF); - } - - bool vs2a = false; - - // Special case detection for vs_2_x/a support - if (major >= 2) - { - if ((minVSCaps.VS20Caps.Caps & D3DVS20CAPS_PREDICATION) && - (minVSCaps.VS20Caps.DynamicFlowControlDepth > 0) && - (minVSCaps.VS20Caps.NumTemps >= 13)) - { - vs2a = true; - } - } - - // Populate max param count - switch (major) - { - case 1: - // No boolean params allowed - // No integer params allowed - // float params, always 4D - rsc->setVertexProgramConstantFloatCount(static_cast(minVSCaps.MaxVertexShaderConst)); - - break; - case 2: - // 16 boolean params allowed - // 16 integer params allowed, 4D - // float params, always 4D - rsc->setVertexProgramConstantFloatCount(static_cast(minVSCaps.MaxVertexShaderConst)); - break; - case 3: - // 16 boolean params allowed - // 16 integer params allowed, 4D - // float params, always 4D - rsc->setVertexProgramConstantFloatCount(static_cast(minVSCaps.MaxVertexShaderConst)); - break; - } - - // populate syntax codes in program manager (no breaks in this one so it falls through) - switch(major) - { - case 3: - rsc->addShaderProfile("vs_3_0"); - case 2: - if (vs2a) - rsc->addShaderProfile("vs_2_a"); - - rsc->addShaderProfile("vs_2_0"); - case 1: - rsc->addShaderProfile("vs_1_1"); - rsc->setCapability(RSC_VERTEX_PROGRAM); - } - - mNativeShadingLanguageVersion = major; - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::convertPixelShaderCaps(RenderSystemCapabilities* rsc) const - { - ushort major = 0xFF; - ushort minor = 0xFF; - D3DCAPS9 minPSCaps; - - // Find the device with the lowest pixel shader caps. - for (unsigned int i=0; i < mDriverList->count(); ++i) - { - D3D9Driver* pCurDriver = mDriverList->item(i); - const D3DCAPS9& currCaps = pCurDriver->getD3D9DeviceCaps(); - ushort currMajor = static_cast((currCaps.PixelShaderVersion & 0x0000FF00) >> 8); - ushort currMinor = static_cast(currCaps.PixelShaderVersion & 0x000000FF); - - if (currMajor < major) - { - major = currMajor; - minor = currMinor; - minPSCaps = currCaps; - } - else if (currMajor == major && currMinor < minor) - { - minor = currMinor; - minPSCaps = currCaps; - } - } - - bool ps2a = false; - bool ps2b = false; - - // Special case detection for ps_2_a/b support - if (major >= 2) - { - if ((minPSCaps.PS20Caps.Caps & D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT) && - (minPSCaps.PS20Caps.NumTemps >= 32)) - { - ps2b = true; - } - - if ((minPSCaps.PS20Caps.Caps & D3DPS20CAPS_NOTEXINSTRUCTIONLIMIT) && - (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_NODEPENDENTREADLIMIT) && - (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_ARBITRARYSWIZZLE) && - (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_GRADIENTINSTRUCTIONS) && - (minPSCaps.PS20Caps.Caps & D3DPS20CAPS_PREDICATION) && - (minPSCaps.PS20Caps.NumTemps >= 22)) - { - ps2a = true; - } - } - - switch (major) - { - case 1: - // no boolean params allowed - // no integer params allowed - // float params, always 4D - // NB in ps_1_x these are actually stored as fixed point values, - // but they are entered as floats - rsc->setFragmentProgramConstantFloatCount(8); - break; - case 2: - // 16 boolean params allowed - // 16 integer params allowed, 4D - // float params, always 4D - rsc->setFragmentProgramConstantFloatCount(32); - break; - case 3: - // 16 boolean params allowed - // 16 integer params allowed, 4D - // float params, always 4D - rsc->setFragmentProgramConstantFloatCount(224); - break; - } - - // populate syntax codes in program manager (no breaks in this one so it falls through) - switch(major) - { - case 3: - rsc->addShaderProfile("ps_3_0"); - case 2: - if (ps2a) - rsc->addShaderProfile("ps_2_a"); - if (ps2b) - rsc->addShaderProfile("ps_2_b"); - - rsc->addShaderProfile("ps_2_0"); - case 1: - if (major > 1 || minor >= 4) - rsc->addShaderProfile("ps_1_4"); - if (major > 1 || minor >= 3) - rsc->addShaderProfile("ps_1_3"); - if (major > 1 || minor >= 2) - rsc->addShaderProfile("ps_1_2"); - - rsc->addShaderProfile("ps_1_1"); - } - } - //----------------------------------------------------------------------- - bool D3D9RenderSystem::checkVertexTextureFormats(D3D9RenderWindow* renderWindow) const - { - bool anySupported = false; - - IDirect3DSurface9* bbSurf; - renderWindow->getCustomAttribute("DDBACKBUFFER", &bbSurf); - D3DSURFACE_DESC bbSurfDesc; - bbSurf->GetDesc(&bbSurfDesc); - - for (uint ipf = static_cast(PF_L8); ipf < static_cast(PF_COUNT); ++ipf) - { - PixelFormat pf = (PixelFormat)ipf; - D3DFORMAT fmt = D3D9Mappings::_getPF(pf); - - if (SUCCEEDED(mD3D->CheckDeviceFormat( - mActiveD3DDriver->getAdapterNumber(), D3DDEVTYPE_HAL, bbSurfDesc.Format, - D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, fmt))) - { - // cool, at least one supported - anySupported = true; - LogManager::getSingleton().stream() - << "D3D9: Vertex texture format supported - " - << PixelUtil::getFormatName(pf); - } - } - - return anySupported; - - } - //----------------------------------------------------------------------- - void D3D9RenderSystem::initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary) - { - for(const auto& lang : caps->getSupportedShaderProfiles()) - { - if (lang == "hlsl") - { - GpuProgramManager::getSingleton().addFactory(mHLSLProgramFactory); - } - else - { - D3D9GpuProgramManager::currentLanguage = lang; - GpuProgramManager::getSingleton().addFactory(mGpuProgramManager); - } - } - } - - //----------------------------------------------------------------------- - bool D3D9RenderSystem::_checkTextureFilteringSupported(TextureType ttype, PixelFormat format, int usage) - { - // Gets D3D format - D3DFORMAT d3dPF = D3D9Mappings::_getPF(format); - if (d3dPF == D3DFMT_UNKNOWN) - return false; - - for (uint i = 0; i < mDeviceManager->getDeviceCount(); ++i) - { - D3D9Device* currDevice = mDeviceManager->getDevice(i); - D3D9RenderWindow* currDevicePrimaryWindow = currDevice->getPrimaryWindow(); - IDirect3DSurface9* pSurface = currDevicePrimaryWindow->getRenderSurface(); - D3DSURFACE_DESC srfDesc; - - // Get surface desc - if (FAILED(pSurface->GetDesc(&srfDesc))) - return false; - - // Calculate usage - DWORD d3dusage = D3DUSAGE_QUERY_FILTER; - if (usage & TU_RENDERTARGET) - d3dusage |= D3DUSAGE_RENDERTARGET; - if (usage & TU_DYNAMIC) - d3dusage |= D3DUSAGE_DYNAMIC; - - // Detect resource type - D3DRESOURCETYPE rtype; - switch(ttype) - { - case TEX_TYPE_1D: - case TEX_TYPE_2D: - rtype = D3DRTYPE_TEXTURE; - break; - case TEX_TYPE_3D: - rtype = D3DRTYPE_VOLUMETEXTURE; - break; - case TEX_TYPE_CUBE_MAP: - rtype = D3DRTYPE_CUBETEXTURE; - break; - default: - return false; - } - - HRESULT hr = mD3D->CheckDeviceFormat( - currDevice->getAdapterNumber(), - currDevice->getDeviceType(), - srfDesc.Format, - d3dusage, - rtype, - d3dPF); - - if (FAILED(hr)) - return false; - } - - return true; - } - //----------------------------------------------------------------------- - MultiRenderTarget * D3D9RenderSystem::createMultiRenderTarget(const String & name) - { - MultiRenderTarget *retval; - retval = OGRE_NEW D3D9MultiRenderTarget(name); - attachRenderTarget(*retval); - - return retval; - } - //--------------------------------------------------------------------- - RenderTarget* D3D9RenderSystem::detachRenderTarget(const String &name) - { - RenderTarget* target = RenderSystem::detachRenderTarget(name); - detachRenderTargetImpl(name); - return target; - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::detachRenderTargetImpl(const String& name) - { - // Check render windows - D3D9RenderWindowList::iterator sw; - for (sw = mRenderWindows.begin(); sw != mRenderWindows.end(); ++sw) - { - if ((*sw)->getName() == name) - { - mRenderWindows.erase(sw); - break; - } - } - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::destroyRenderTarget(const String& name) - { -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - D3D9StereoDriverBridge::getSingleton().removeRenderWindow(name); -#endif - - detachRenderTargetImpl(name); - - // Do the real removal - RenderSystem::destroyRenderTarget(name); - } - //--------------------------------------------------------------------- - String D3D9RenderSystem::getErrorDescription( long errorNumber ) const - { - const String errMsg = DXGetErrorDescription( errorNumber ); - return errMsg; - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_convertProjectionMatrix(const Matrix4& matrix, - Matrix4& dest, bool forGpuProgram) - { - dest = matrix; - - // Convert depth range from [-1,+1] to [0,1] - dest[2][0] = (dest[2][0] + dest[3][0]) / 2; - dest[2][1] = (dest[2][1] + dest[3][1]) / 2; - dest[2][2] = (dest[2][2] + dest[3][2]) / 2; - dest[2][3] = (dest[2][3] + dest[3][3]) / 2; - - if (!forGpuProgram) - { - // Convert right-handed to left-handed - dest[0][2] = -dest[0][2]; - dest[1][2] = -dest[1][2]; - dest[2][2] = -dest[2][2]; - dest[3][2] = -dest[3][2]; - } - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::setAmbientLight( float r, float g, float b ) - { - HRESULT hr = __SetRenderState( D3DRS_AMBIENT, D3DCOLOR_COLORVALUE( r, g, b, 1.0f ) ); - if( FAILED( hr ) ) - OGRE_EXCEPT( Exception::ERR_RENDERINGAPI_ERROR, - "Failed to set render stat D3DRS_AMBIENT", "D3D9RenderSystem::setAmbientLight" ); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_useLights(unsigned short limit) - { - IDirect3DDevice9* activeDevice = getActiveD3D9Device(); - - if(mCurrentLights[activeDevice] == limit) - return; - - unsigned short num = 0; - for (; num < limit; ++num) - { - setD3D9Light(num, true); - } - // Disable extra lights - for (; num < mCurrentLights[activeDevice]; ++num) - { - setD3D9Light(num, false); - } - mCurrentLights[activeDevice] = limit; - - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::setShadingType( ShadeOptions so ) - { - HRESULT hr = __SetRenderState( D3DRS_SHADEMODE, D3D9Mappings::get(so) ); - if( FAILED( hr ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Failed to set render stat D3DRS_SHADEMODE", "D3D9RenderSystem::setShadingType" ); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::setLightingEnabled( bool enabled ) - { - HRESULT hr; - if( FAILED( hr = __SetRenderState( D3DRS_LIGHTING, enabled ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Failed to set render state D3DRS_LIGHTING", "D3D9RenderSystem::setLightingEnabled" ); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::setD3D9Light( size_t index, bool enabled) - { - setFFPLightParams(index, enabled); - HRESULT hr; - - if (!enabled) - { - if( FAILED( hr = getActiveD3D9Device()->LightEnable( static_cast(index), FALSE) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Unable to disable light", "D3D9RenderSystem::setD3D9Light" ); - } - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::setViewMatrix( const Matrix4 &m ) - { - // save latest view matrix - mViewMatrix = m; - mViewMatrix[2][0] = -mViewMatrix[2][0]; - mViewMatrix[2][1] = -mViewMatrix[2][1]; - mViewMatrix[2][2] = -mViewMatrix[2][2]; - mViewMatrix[2][3] = -mViewMatrix[2][3]; - - mDxViewMat = D3D9Mappings::makeD3DXMatrix( mViewMatrix ); - - HRESULT hr; - if( FAILED( hr = getActiveD3D9Device()->SetTransform( D3DTS_VIEW, &mDxViewMat ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Cannot set D3D9 view matrix"); - - // also mark clip planes dirty - if (!mClipPlanes.empty()) - mClipPlanesDirty = true; - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::setProjectionMatrix( const Matrix4 &m ) - { - // save latest matrix - mDxProjMat = D3D9Mappings::makeD3DXMatrix( m ); - - // Convert right-handed to left-handed - mDxProjMat._31 = -mDxProjMat._31; - mDxProjMat._32 = -mDxProjMat._32; - mDxProjMat._33 = -mDxProjMat._33; - mDxProjMat._34 = -mDxProjMat._34; - - HRESULT hr; - if( FAILED( hr = getActiveD3D9Device()->SetTransform( D3DTS_PROJECTION, &mDxProjMat ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Cannot set D3D9 projection matrix"); - - // also mark clip planes dirty - if (!mClipPlanes.empty()) - mClipPlanesDirty = true; - - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::setWorldMatrix( const Matrix4 &m ) - { - // save latest matrix - mDxWorldMat = D3D9Mappings::makeD3DXMatrix( m ); - - HRESULT hr; - if( FAILED( hr = getActiveD3D9Device()->SetTransform( D3DTS_WORLD, &mDxWorldMat ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Cannot set D3D9 world matrix"); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_setSurfaceTracking( TrackVertexColourType tracking ) - { - - if(tracking != TVC_NONE) - { - __SetRenderState(D3DRS_COLORVERTEX, TRUE); - __SetRenderState(D3DRS_AMBIENTMATERIALSOURCE, (tracking&TVC_AMBIENT)?D3DMCS_COLOR1:D3DMCS_MATERIAL); - __SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, (tracking&TVC_DIFFUSE)?D3DMCS_COLOR1:D3DMCS_MATERIAL); - __SetRenderState(D3DRS_SPECULARMATERIALSOURCE, (tracking&TVC_SPECULAR)?D3DMCS_COLOR1:D3DMCS_MATERIAL); - __SetRenderState(D3DRS_EMISSIVEMATERIALSOURCE, (tracking&TVC_EMISSIVE)?D3DMCS_COLOR1:D3DMCS_MATERIAL); - } - else - { - __SetRenderState(D3DRS_COLORVERTEX, FALSE); - } - - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_setPointParameters(bool attenuationEnabled, Real minSize, Real maxSize) - { - if(attenuationEnabled) - { - // scaling required - __SetRenderState(D3DRS_POINTSCALEENABLE, TRUE); - } - else - { - // no scaling required - __SetRenderState(D3DRS_POINTSCALEENABLE, FALSE); - } - - __SetFloatRenderState(D3DRS_POINTSIZE_MIN, minSize); - if (maxSize == 0.0f) - maxSize = mCurrentCapabilities->getMaxPointSize(); - __SetFloatRenderState(D3DRS_POINTSIZE_MAX, maxSize); - - - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_setPointSpritesEnabled(bool enabled) - { - if (enabled) - { - __SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE); - } - else - { - __SetRenderState(D3DRS_POINTSPRITEENABLE, FALSE); - } - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_setTexture( size_t stage, bool enabled, const TexturePtr& tex ) - { - HRESULT hr; - D3D9TexturePtr dt = static_pointer_cast(tex); - auto hasVTF = mCurrentCapabilities->hasCapability(RSC_VERTEX_TEXTURE_FETCH); - if (enabled && dt) - { - // note used - dt->touch(); - - IDirect3DBaseTexture9 *pTex = dt->getTexture(); - if (mTexStageDesc[stage].pTex != pTex) - { - hr = getActiveD3D9Device()->SetTexture(static_cast(stage), pTex); - if( hr != S_OK ) - { - String str = "Unable to set texture '" + tex->getName() + "' in D3D9"; - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, str, "D3D9RenderSystem::_setTexture" ); - } - - // set stage desc. - mTexStageDesc[stage].pTex = pTex; - mTexStageDesc[stage].texType = D3D9Mappings::get(dt->getTextureType()); - - // Set gamma now too - if (dt->isHardwareGammaReadToBeUsed()) - { - __SetSamplerState(getSamplerId(stage), D3DSAMP_SRGBTEXTURE, TRUE); - } - else - { - __SetSamplerState(getSamplerId(stage), D3DSAMP_SRGBTEXTURE, FALSE); - } - - if (hasVTF && stage < 4) - { - HRESULT hr = getActiveD3D9Device()->SetTexture(D3DVERTEXTEXTURESAMPLER0 + static_cast(stage), pTex); - if( hr != S_OK ) - { - String str = "Unable to set vertex texture '" + tex->getName() + "' in D3D9"; - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, str); - } - } - - } - } - else - { - if (mTexStageDesc[stage].pTex != 0) - { - hr = getActiveD3D9Device()->SetTexture(static_cast(stage), 0); - if( hr != S_OK ) - { - String str = "Unable to disable texture '" + StringConverter::toString(stage) + "' in D3D9"; - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, str, "D3D9RenderSystem::_setTexture" ); - } - - if (hasVTF && stage < 4) - { - HRESULT hr = getActiveD3D9Device()->SetTexture(D3DVERTEXTEXTURESAMPLER0 + static_cast(stage), 0); - if( hr != S_OK ) - { - String str = "Unable to disable vertex texture '" - + StringConverter::toString(stage) + "' in D3D9"; - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, str); - } - } - } - - hr = __SetTextureStageState(static_cast(stage), D3DTSS_COLOROP, D3DTOP_DISABLE); - if( hr != S_OK ) - { - String str = "Unable to disable texture '" + StringConverter::toString(stage) + "' in D3D9"; - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, str, "D3D9RenderSystem::_setTexture" ); - } - - // set stage desc. to defaults - mTexStageDesc[stage].pTex = 0; - mTexStageDesc[stage].autoTexCoordType = TEXCALC_NONE; - mTexStageDesc[stage].coordIndex = 0; - mTexStageDesc[stage].texType = D3D9Mappings::D3D_TEX_TYPE_NORMAL; - } - } - void D3D9RenderSystem::_setSampler(size_t unit, Sampler& sampler) - { - const Sampler::UVWAddressingMode& uvw = sampler.getAddressingMode(); - HRESULT hr; - DWORD samplerId = getSamplerId(unit); - const D3DCAPS9& caps = mDeviceManager->getActiveDevice()->getD3D9DeviceCaps(); - if( FAILED( hr = __SetSamplerState( samplerId, D3DSAMP_ADDRESSU, D3D9Mappings::get(uvw.u, caps) ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set texture addressing mode for U", "D3D9RenderSystem::_setSampler" ); - if( FAILED( hr = __SetSamplerState( samplerId, D3DSAMP_ADDRESSV, D3D9Mappings::get(uvw.v, caps) ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set texture addressing mode for V", "D3D9RenderSystem::_setSampler" ); - if( FAILED( hr = __SetSamplerState( samplerId, D3DSAMP_ADDRESSW, D3D9Mappings::get(uvw.w, caps) ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set texture addressing mode for W", "D3D9RenderSystem::_setSampler" ); - if( FAILED( hr = __SetSamplerState( samplerId, D3DSAMP_BORDERCOLOR, sampler.getBorderColour().getAsARGB()) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set texture border colour", "D3D9RenderSystem::_setSampler" ); - - __SetSamplerState( samplerId, D3DSAMP_MAXANISOTROPY, std::min(caps.MaxAnisotropy, sampler.getAnisotropy()) ); - - if (mCurrentCapabilities->hasCapability(RSC_MIPMAP_LOD_BIAS)) - { - // ugh - have to pass float data through DWORD with no conversion - float mipBias = sampler.getMipmapBias(); - hr = __SetSamplerState(samplerId, D3DSAMP_MIPMAPLODBIAS, *(DWORD*)&mipBias); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to set texture mipmap bias", - "D3D9RenderSystem::_setSampler"); - } - - D3D9Mappings::eD3DTexType texType = mTexStageDesc[unit].texType; - hr = __SetSamplerState(samplerId, D3D9Mappings::get(FT_MIN), - D3D9Mappings::get(FT_MIN, sampler.getFiltering(FT_MIN), caps, texType)); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set texture filter ", "D3D9RenderSystem::_setSampler"); - hr = __SetSamplerState(samplerId, D3D9Mappings::get(FT_MAG), - D3D9Mappings::get(FT_MAG, sampler.getFiltering(FT_MAG), caps, texType)); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set texture filter ", "D3D9RenderSystem::_setSampler"); - hr = __SetSamplerState(samplerId, D3D9Mappings::get(FT_MIP), - D3D9Mappings::get(FT_MIP, sampler.getFiltering(FT_MIP), caps, texType)); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set texture filter ", "D3D9RenderSystem::_setSampler"); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_setTextureCoordSet( size_t stage, size_t index ) - { - // if vertex shader is being used, stage and index must match - if (mProgramBound[GPT_VERTEX_PROGRAM]) - index = stage; - - HRESULT hr; - // Record settings - mTexStageDesc[stage].coordIndex = index; - - if (mProgramBound[GPT_VERTEX_PROGRAM]) - hr = __SetTextureStageState( static_cast(stage), D3DTSS_TEXCOORDINDEX, index ); - else - hr = __SetTextureStageState( static_cast(stage), D3DTSS_TEXCOORDINDEX, D3D9Mappings::get(mTexStageDesc[stage].autoTexCoordType, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps()) | index ); - if( FAILED( hr ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to set texture coord. set index", "D3D9RenderSystem::_setTextureCoordSet" ); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_setTextureCoordCalculation( size_t stage, TexCoordCalcMethod m, - const Frustum* frustum) - { - HRESULT hr; - // record the stage state - mTexStageDesc[stage].autoTexCoordType = m; - mTexStageDesc[stage].frustum = frustum; - - if (mProgramBound[GPT_VERTEX_PROGRAM]) - hr = __SetTextureStageState( static_cast(stage), D3DTSS_TEXCOORDINDEX, mTexStageDesc[stage].coordIndex ); - else - hr = __SetTextureStageState( static_cast(stage), D3DTSS_TEXCOORDINDEX, D3D9Mappings::get(m, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps()) | mTexStageDesc[stage].coordIndex ); - if(FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to set texture auto tex.coord. generation mode", "D3D9RenderSystem::_setTextureCoordCalculation" ); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_setTextureMatrix( size_t stage, const Matrix4& xForm ) - { - HRESULT hr; - Matrix4 newMat = xForm; // the matrix we'll apply after conv. to D3D format - // Cache texcoord calc method to register - TexCoordCalcMethod autoTexCoordType = mTexStageDesc[stage].autoTexCoordType; - - // if a vertex program is bound, we mustn't set texture transforms - if (mProgramBound[GPT_VERTEX_PROGRAM]) - { - hr = __SetTextureStageState( static_cast(stage), D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE ); - if( FAILED( hr ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to disable texture coordinate transform", "D3D9RenderSystem::_setTextureMatrix" ); - return; - } - - - if (autoTexCoordType == TEXCALC_ENVIRONMENT_MAP) - { - if (mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().VertexProcessingCaps & D3DVTXPCAPS_TEXGEN_SPHEREMAP) - { - /** Invert the texture for the spheremap */ - Matrix4 ogreMatEnvMap = Matrix4::IDENTITY; - // set env_map values - ogreMatEnvMap[1][1] = -1.0f; - // concatenate with the xForm - newMat = newMat.concatenate(ogreMatEnvMap); - } - else - { - /* If envmap is applied, but device doesn't support spheremap, - then we have to use texture transform to make the camera space normal - reference the envmap properly. This isn't exactly the same as spheremap - (it looks nasty on flat areas because the camera space normals are the same) - but it's the best approximation we have in the absence of a proper spheremap */ - // concatenate with the xForm - newMat = newMat.concatenate(Matrix4::CLIPSPACE2DTOIMAGESPACE); - } - } - - // If this is a cubic reflection, we need to modify using the view matrix - if (autoTexCoordType == TEXCALC_ENVIRONMENT_MAP_REFLECTION) - { - // Get transposed 3x3 - // We want to transpose since that will invert an orthonormal matrix ie rotation - Matrix4 ogreViewTransposed; - ogreViewTransposed[0][0] = mViewMatrix[0][0]; - ogreViewTransposed[0][1] = mViewMatrix[1][0]; - ogreViewTransposed[0][2] = mViewMatrix[2][0]; - ogreViewTransposed[0][3] = 0.0f; - - ogreViewTransposed[1][0] = mViewMatrix[0][1]; - ogreViewTransposed[1][1] = mViewMatrix[1][1]; - ogreViewTransposed[1][2] = mViewMatrix[2][1]; - ogreViewTransposed[1][3] = 0.0f; - - ogreViewTransposed[2][0] = mViewMatrix[0][2]; - ogreViewTransposed[2][1] = mViewMatrix[1][2]; - ogreViewTransposed[2][2] = mViewMatrix[2][2]; - ogreViewTransposed[2][3] = 0.0f; - - ogreViewTransposed[3][0] = 0.0f; - ogreViewTransposed[3][1] = 0.0f; - ogreViewTransposed[3][2] = 0.0f; - ogreViewTransposed[3][3] = 1.0f; - - newMat = newMat.concatenate(ogreViewTransposed); - } - - if (autoTexCoordType == TEXCALC_PROJECTIVE_TEXTURE) - { - // Derive camera space to projector space transform - // To do this, we need to undo the camera view matrix, then - // apply the projector view & projection matrices - newMat = mViewMatrix.inverse(); - if(mTexProjRelative) - { - Matrix4 viewMatrix; - mTexStageDesc[stage].frustum->calcViewMatrixRelative(mTexProjRelativeOrigin, viewMatrix); - newMat = viewMatrix * newMat; - } - else - { - newMat = mTexStageDesc[stage].frustum->getViewMatrix() * newMat; - } - newMat = mTexStageDesc[stage].frustum->getProjectionMatrix() * newMat; - newMat = Matrix4::CLIPSPACE2DTOIMAGESPACE * newMat; - newMat = xForm * newMat; - } - - // need this if texture is a cube map, to invert D3D's z coord - if (autoTexCoordType != TEXCALC_NONE && - autoTexCoordType != TEXCALC_PROJECTIVE_TEXTURE) - { - newMat[2][0] = -newMat[2][0]; - newMat[2][1] = -newMat[2][1]; - newMat[2][2] = -newMat[2][2]; - newMat[2][3] = -newMat[2][3]; - } - - // set the matrix if it's not the identity - if (newMat != Matrix4::IDENTITY) - { - // convert our matrix to D3D format - D3DMATRIX d3dMat = D3D9Mappings::makeD3DXMatrix(newMat); - - /* It's seems D3D automatically add a texture coordinate with value 1, - and fill up the remaining texture coordinates with 0 for the input - texture coordinates before pass to texture coordinate transformation. - - NOTE: It's difference with D3DDECLTYPE enumerated type expand in - DirectX SDK documentation! - - So we should prepare the texcoord transform, make the transformation - just like standardized vector expand, thus, fill w with value 1 and - others with 0. - */ - if (autoTexCoordType == TEXCALC_NONE) - { - /* FIXME: The actually input texture coordinate dimensions should - be determine by texture coordinate vertex element. Now, just trust - user supplied texture type matches texture coordinate vertex element. - */ - if (mTexStageDesc[stage].texType == D3D9Mappings::D3D_TEX_TYPE_NORMAL) - { - /* It's 2D input texture coordinate: - - texcoord in vertex buffer D3D expanded to We are adjusted to - --> --> - (u, v) (u, v, 1, 0) (u, v, 0, 1) - */ - std::swap(d3dMat._31, d3dMat._41); - std::swap(d3dMat._32, d3dMat._42); - std::swap(d3dMat._33, d3dMat._43); - std::swap(d3dMat._34, d3dMat._44); - } - } - else - { - // All texgen generate 3D input texture coordinates. - } - - // tell D3D the dimension of tex. coord. - int texCoordDim = D3DTTFF_COUNT2; - if (mTexStageDesc[stage].autoTexCoordType == TEXCALC_PROJECTIVE_TEXTURE) - { - /* We want texcoords (u, v, w, q) always get divided by q, but D3D - projected texcoords is divided by the last element (in the case of - 2D texcoord, is w). So we tweak the transform matrix, transform the - texcoords with w and q swapped: (u, v, q, w), and then D3D will - divide u, v by q. The w and q just ignored as it wasn't used by - rasterizer. - */ - switch (mTexStageDesc[stage].texType) - { - case D3D9Mappings::D3D_TEX_TYPE_NORMAL: - std::swap(d3dMat._13, d3dMat._14); - std::swap(d3dMat._23, d3dMat._24); - std::swap(d3dMat._33, d3dMat._34); - std::swap(d3dMat._43, d3dMat._44); - - texCoordDim = D3DTTFF_PROJECTED | D3DTTFF_COUNT3; - break; - - case D3D9Mappings::D3D_TEX_TYPE_CUBE: - case D3D9Mappings::D3D_TEX_TYPE_VOLUME: - // Yes, we support 3D projective texture. - texCoordDim = D3DTTFF_PROJECTED | D3DTTFF_COUNT4; - break; - } - } - else - { - switch (mTexStageDesc[stage].texType) - { - case D3D9Mappings::D3D_TEX_TYPE_NORMAL: - texCoordDim = D3DTTFF_COUNT2; - break; - case D3D9Mappings::D3D_TEX_TYPE_CUBE: - case D3D9Mappings::D3D_TEX_TYPE_VOLUME: - texCoordDim = D3DTTFF_COUNT3; - break; - } - } - - hr = __SetTextureStageState( static_cast(stage), D3DTSS_TEXTURETRANSFORMFLAGS, texCoordDim ); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to set texture coord. dimension", "D3D9RenderSystem::_setTextureMatrix" ); - - hr = getActiveD3D9Device()->SetTransform( (D3DTRANSFORMSTATETYPE)(D3DTS_TEXTURE0 + stage), &d3dMat ); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to set texture matrix", "D3D9RenderSystem::_setTextureMatrix" ); - } - else - { - // disable all of this - hr = __SetTextureStageState( static_cast(stage), D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE ); - if( FAILED( hr ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to disable texture coordinate transform", "D3D9RenderSystem::_setTextureMatrix" ); - - // Needless to sets texture transform here, it's never used at all - } - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_setTextureBlendMode( size_t stage, const LayerBlendModeEx& bm ) - { - HRESULT hr = S_OK; - D3DTEXTURESTAGESTATETYPE tss; - D3DCOLOR manualD3D; - - // choose type of blend. - if( bm.blendType == LBT_COLOUR ) - tss = D3DTSS_COLOROP; - else if( bm.blendType == LBT_ALPHA ) - tss = D3DTSS_ALPHAOP; - else - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Invalid blend type", "D3D9RenderSystem::_setTextureBlendMode"); - - // set manual factor if required by operation - if (bm.operation == LBX_BLEND_MANUAL) - { - hr = __SetRenderState( D3DRS_TEXTUREFACTOR, D3DCOLOR_COLORVALUE(0.0, 0.0, 0.0, bm.factor) ); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set manual factor", "D3D9RenderSystem::_setTextureBlendMode" ); - } - // set operation - hr = __SetTextureStageState( static_cast(stage), tss, D3D9Mappings::get(bm.operation, mDeviceManager->getActiveDevice()->getD3D9DeviceCaps()) ); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set operation", "D3D9RenderSystem::_setTextureBlendMode" ); - - // choose source 1 - if( bm.blendType == LBT_COLOUR ) - { - tss = D3DTSS_COLORARG1; - manualD3D = D3DCOLOR_COLORVALUE( bm.colourArg1.r, bm.colourArg1.g, bm.colourArg1.b, bm.colourArg1.a ); - mManualBlendColours[stage][0] = bm.colourArg1; - } - else if( bm.blendType == LBT_ALPHA ) - { - tss = D3DTSS_ALPHAARG1; - manualD3D = D3DCOLOR_COLORVALUE( mManualBlendColours[stage][0].r, - mManualBlendColours[stage][0].g, - mManualBlendColours[stage][0].b, bm.alphaArg1 ); - } - else - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Invalid blend type", "D3D9RenderSystem::_setTextureBlendMode"); - } - // Set manual factor if required - if (bm.source1 == LBS_MANUAL) - { - if (mCurrentCapabilities->hasCapability(RSC_PERSTAGECONSTANT)) - { - // Per-stage state - hr = __SetTextureStageState(static_cast(stage), D3DTSS_CONSTANT, manualD3D); - } - else - { - // Global state - hr = __SetRenderState( D3DRS_TEXTUREFACTOR, manualD3D ); - } - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set manual factor", "D3D9RenderSystem::_setTextureBlendMode" ); - } - // set source 1 - hr = __SetTextureStageState( static_cast(stage), tss, D3D9Mappings::get(bm.source1, mCurrentCapabilities->hasCapability(RSC_PERSTAGECONSTANT)) ); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set source1", "D3D9RenderSystem::_setTextureBlendMode" ); - - // choose source 2 - if( bm.blendType == LBT_COLOUR ) - { - tss = D3DTSS_COLORARG2; - manualD3D = D3DCOLOR_COLORVALUE( bm.colourArg2.r, bm.colourArg2.g, bm.colourArg2.b, bm.colourArg2.a ); - mManualBlendColours[stage][1] = bm.colourArg2; - } - else if( bm.blendType == LBT_ALPHA ) - { - tss = D3DTSS_ALPHAARG2; - manualD3D = D3DCOLOR_COLORVALUE( mManualBlendColours[stage][1].r, - mManualBlendColours[stage][1].g, - mManualBlendColours[stage][1].b, - bm.alphaArg2 ); - } - // Set manual factor if required - if (bm.source2 == LBS_MANUAL) - { - if (mCurrentCapabilities->hasCapability(RSC_PERSTAGECONSTANT)) - { - // Per-stage state - hr = __SetTextureStageState(static_cast(stage), D3DTSS_CONSTANT, manualD3D); - } - else - { - hr = __SetRenderState( D3DRS_TEXTUREFACTOR, manualD3D ); - } - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set manual factor", "D3D9RenderSystem::_setTextureBlendMode" ); - } - // Now set source 2 - hr = __SetTextureStageState( static_cast(stage), tss, D3D9Mappings::get(bm.source2, mCurrentCapabilities->hasCapability(RSC_PERSTAGECONSTANT)) ); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set source 2", "D3D9RenderSystem::_setTextureBlendMode" ); - - // Set interpolation factor if lerping - if (bm.operation == LBX_BLEND_DIFFUSE_COLOUR && - mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().TextureOpCaps & D3DTEXOPCAPS_LERP) - { - // choose source 0 (lerp factor) - if( bm.blendType == LBT_COLOUR ) - { - tss = D3DTSS_COLORARG0; - } - else if( bm.blendType == LBT_ALPHA ) - { - tss = D3DTSS_ALPHAARG0; - } - hr = __SetTextureStageState(static_cast(stage), tss, D3DTA_DIFFUSE); - - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set lerp source 0", - "D3D9RenderSystem::_setTextureBlendMode" ); - - } - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_setAlphaRejectSettings( CompareFunction func, unsigned char value, bool alphaToCoverage ) - { - HRESULT hr; - bool a2c = false; - static bool lasta2c = false; - - if (func != CMPF_ALWAYS_PASS) - { - if( FAILED( hr = __SetRenderState( D3DRS_ALPHATESTENABLE, TRUE ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to enable alpha testing", - "D3D9RenderSystem::_setAlphaRejectSettings" ); - - a2c = alphaToCoverage; - } - else - { - if( FAILED( hr = __SetRenderState( D3DRS_ALPHATESTENABLE, FALSE ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to disable alpha testing", - "D3D9RenderSystem::_setAlphaRejectSettings" ); - } - // Set always just be sure - if( FAILED( hr = __SetRenderState( D3DRS_ALPHAFUNC, D3D9Mappings::get(func) ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set alpha reject function", "D3D9RenderSystem::_setAlphaRejectSettings" ); - if( FAILED( hr = __SetRenderState( D3DRS_ALPHAREF, value ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set render state D3DRS_ALPHAREF", "D3D9RenderSystem::_setAlphaRejectSettings" ); - - // Alpha to coverage - if (getCapabilities()->hasCapability(RSC_ALPHA_TO_COVERAGE)) - { - // Vendor-specific hacks on renderstate, gotta love 'em - if (getCapabilities()->getVendor() == GPU_NVIDIA) - { - if (a2c) - { - if( FAILED( hr = __SetRenderState( D3DRS_ADAPTIVETESS_Y, (D3DFORMAT)MAKEFOURCC('A', 'T', 'O', 'C') ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set alpha to coverage option", "D3D9RenderSystem::_setAlphaRejectSettings" ); - } - else - { - if( FAILED( hr = __SetRenderState( D3DRS_ADAPTIVETESS_Y, D3DFMT_UNKNOWN ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set alpha to coverage option", "D3D9RenderSystem::_setAlphaRejectSettings" ); - } - - } - else if ((getCapabilities()->getVendor() == GPU_AMD)) - { - if (a2c) - { - if( FAILED( hr = __SetRenderState( D3DRS_POINTSIZE, MAKEFOURCC('A','2','M','1') ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set alpha to coverage option", "D3D9RenderSystem::_setAlphaRejectSettings" ); - } - else - { - // discovered this through trial and error, seems to work - if( FAILED( hr = __SetRenderState( D3DRS_POINTSIZE, MAKEFOURCC('A','2','M','0') ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set alpha to coverage option", "D3D9RenderSystem::_setAlphaRejectSettings" ); - } - } - // no hacks available for any other vendors? - lasta2c = a2c; - } - - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_setCullingMode( CullingMode mode ) - { - mCullingMode = mode; - HRESULT hr; - - if( FAILED (hr = __SetRenderState(D3DRS_CULLMODE, - D3D9Mappings::get(mode, flipFrontFace()))) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set culling mode", "D3D9RenderSystem::_setCullingMode" ); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_setDepthBufferParams( bool depthTest, bool depthWrite, CompareFunction depthFunction ) - { - _setDepthBufferCheckEnabled( depthTest ); - _setDepthBufferWriteEnabled( depthWrite ); - _setDepthBufferFunction( depthFunction ); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_setDepthBufferCheckEnabled( bool enabled ) - { - HRESULT hr; - - if( enabled ) - { - // If we have 16bit depth buffer enable w-buffering. - if((mActiveRenderTarget->suggestPixelFormat() == PF_R5G6B5) && mCurrentCapabilities->hasCapability(RSC_WBUFFER) ) - hr = __SetRenderState( D3DRS_ZENABLE, D3DZB_USEW ); - else - hr = __SetRenderState( D3DRS_ZENABLE, D3DZB_TRUE ); - } - else - hr = __SetRenderState( D3DRS_ZENABLE, D3DZB_FALSE ); - - if( FAILED( hr ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting depth buffer test state", "D3D9RenderSystem::_setDepthBufferCheckEnabled" ); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_setDepthBufferWriteEnabled( bool enabled ) - { - HRESULT hr; - - if( FAILED( hr = __SetRenderState( D3DRS_ZWRITEENABLE, enabled ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting depth buffer write state", "D3D9RenderSystem::_setDepthBufferWriteEnabled" ); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_setDepthBufferFunction( CompareFunction func ) - { - HRESULT hr; - if( FAILED( hr = __SetRenderState( D3DRS_ZFUNC, D3D9Mappings::get(func) ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting depth buffer test function", "D3D9RenderSystem::_setDepthBufferFunction" ); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_setDepthBias(float constantBias, float slopeScaleBias) - { - // Negate bias since D3D is backward - // D3D also expresses the constant bias as an absolute value, rather than - // relative to minimum depth unit, so scale to fit - constantBias = -constantBias / 250000.0f; - HRESULT hr = __SetRenderState(D3DRS_DEPTHBIAS, FLOAT2DWORD(constantBias)); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting constant depth bias", - "D3D9RenderSystem::_setDepthBias"); - - // Negate bias since D3D is backward - slopeScaleBias = -slopeScaleBias; - hr = __SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, FLOAT2DWORD(slopeScaleBias)); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting slope scale depth bias", - "D3D9RenderSystem::_setDepthBias"); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::setColourBlendState(const ColourBlendState& state) - { - HRESULT hr; - if (state.blendingEnabled()) - { - if (FAILED(hr = __SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE))) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set alpha blending option"); - if (FAILED(hr = __SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE))) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set separate alpha blending option"); - if( FAILED( hr = __SetRenderState( D3DRS_SRCBLEND, D3D9Mappings::get(state.sourceFactor) ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set source blend" ); - if( FAILED( hr = __SetRenderState( D3DRS_DESTBLEND, D3D9Mappings::get(state.destFactor) ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set destination blend" ); - if( FAILED( hr = __SetRenderState( D3DRS_SRCBLENDALPHA, D3D9Mappings::get(state.sourceFactorAlpha) ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set alpha source blend" ); - if( FAILED( hr = __SetRenderState( D3DRS_DESTBLENDALPHA, D3D9Mappings::get(state.destFactorAlpha) ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set alpha destination blend" ); - } - else - { - if (FAILED(hr = __SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE))) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set alpha blending option" ); - } - - if (FAILED(hr = __SetRenderState(D3DRS_BLENDOP, D3D9Mappings::get(state.operation)))) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set scene blending operation option"); - if (FAILED(hr = __SetRenderState(D3DRS_BLENDOPALPHA, D3D9Mappings::get(state.alphaOperation)))) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set alpha scene blending operation option"); - - DWORD val = 0; - if (state.writeR) - val |= D3DCOLORWRITEENABLE_RED; - if (state.writeG) - val |= D3DCOLORWRITEENABLE_GREEN; - if (state.writeB) - val |= D3DCOLORWRITEENABLE_BLUE; - if (state.writeA) - val |= D3DCOLORWRITEENABLE_ALPHA; - - if (FAILED(hr = __SetRenderState(D3DRS_COLORWRITEENABLE, val))) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting colour write enable flags"); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_setFog( FogMode mode) - { - HRESULT hr; - - D3DRENDERSTATETYPE fogType, fogTypeNot; - - if (mDeviceManager->getActiveDevice()->getD3D9DeviceCaps().RasterCaps & D3DPRASTERCAPS_FOGTABLE) - { - fogType = D3DRS_FOGTABLEMODE; - fogTypeNot = D3DRS_FOGVERTEXMODE; - } - else - { - fogType = D3DRS_FOGVERTEXMODE; - fogTypeNot = D3DRS_FOGTABLEMODE; - } - - if( mode == FOG_NONE) - { - // just disable - hr = __SetRenderState(fogType, D3DFOG_NONE ); - hr = __SetRenderState(D3DRS_FOGENABLE, FALSE); - - mFixedFunctionParams->clearAutoConstant(18); - mFixedFunctionParams->clearAutoConstant(19); - } - else - { - // Allow fog - hr = __SetRenderState( D3DRS_FOGENABLE, TRUE ); - hr = __SetRenderState( fogTypeNot, D3DFOG_NONE ); - hr = __SetRenderState( fogType, D3D9Mappings::get(mode) ); - - mFixedFunctionParams->setAutoConstant(18, GpuProgramParameters::ACT_FOG_PARAMS); - mFixedFunctionParams->setAutoConstant(19, GpuProgramParameters::ACT_FOG_COLOUR); - } - - if( FAILED( hr ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting render state", "D3D9RenderSystem::_setFog" ); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_setPolygonMode(PolygonMode level) - { - HRESULT hr = __SetRenderState(D3DRS_FILLMODE, D3D9Mappings::get(level)); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting polygon mode.", "D3D9RenderSystem::setPolygonMode"); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::setStencilState(const StencilState& state) - { - HRESULT hr; - bool flip; - - // Allow stencilling - hr = __SetRenderState(D3DRS_STENCILENABLE, state.enabled); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error enabling / disabling stencilling."); - - if(!state.enabled) - return; - - // 2-sided operation - if (state.twoSidedOperation) - { - hr = __SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting 2-sided stencil mode.", - "D3D9RenderSystem::setStencilBufferParams"); - // NB: We should always treat CCW as front face for consistent with default - // culling mode. Therefore, we must take care with two-sided stencil settings. - flip = (mInvertVertexWinding && mActiveRenderTarget->requiresTextureFlipping()) || - (!mInvertVertexWinding && !mActiveRenderTarget->requiresTextureFlipping()); - - // Set alternative versions of ops - // fail op - hr = __SetRenderState(D3DRS_CCW_STENCILFAIL, D3D9Mappings::get(state.stencilFailOp, !flip)); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting stencil fail operation (2-sided).", - "D3D9RenderSystem::setStencilBufferParams"); - - // depth fail op - hr = __SetRenderState(D3DRS_CCW_STENCILZFAIL, D3D9Mappings::get(state.depthFailOp, !flip)); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting stencil depth fail operation (2-sided).", - "D3D9RenderSystem::setStencilBufferParams"); - - // pass op - hr = __SetRenderState(D3DRS_CCW_STENCILPASS, D3D9Mappings::get(state.depthStencilPassOp, !flip)); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting stencil pass operation (2-sided).", - "D3D9RenderSystem::setStencilBufferParams"); - } - else - { - hr = __SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting 1-sided stencil mode.", - "D3D9RenderSystem::setStencilBufferParams"); - flip = false; - } - - // func - hr = __SetRenderState(D3DRS_STENCILFUNC, D3D9Mappings::get(state.compareOp)); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting stencil buffer test function.", - "D3D9RenderSystem::setStencilBufferParams"); - - // reference value - hr = __SetRenderState(D3DRS_STENCILREF, state.referenceValue); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting stencil buffer reference value.", - "D3D9RenderSystem::setStencilBufferParams"); - - // compare mask - hr = __SetRenderState(D3DRS_STENCILMASK, state.compareMask); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting stencil buffer compare mask.", - "D3D9RenderSystem::setStencilBufferParams"); - - // compare mask - hr = __SetRenderState(D3DRS_STENCILWRITEMASK, state.writeMask); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting stencil buffer write mask.", - "D3D9RenderSystem::setStencilBufferParams"); - - // fail op - hr = __SetRenderState(D3DRS_STENCILFAIL, D3D9Mappings::get(state.stencilFailOp, flip)); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting stencil fail operation.", - "D3D9RenderSystem::setStencilBufferParams"); - - // depth fail op - hr = __SetRenderState(D3DRS_STENCILZFAIL, D3D9Mappings::get(state.depthFailOp, flip)); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting stencil depth fail operation.", - "D3D9RenderSystem::setStencilBufferParams"); - - // pass op - hr = __SetRenderState(D3DRS_STENCILPASS, D3D9Mappings::get(state.depthStencilPassOp, flip)); - if (FAILED(hr)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error setting stencil pass operation.", - "D3D9RenderSystem::setStencilBufferParams"); - } - //--------------------------------------------------------------------- - DWORD D3D9RenderSystem::_getCurrentAnisotropy(size_t unit) - { - DWORD oldVal; - getActiveD3D9Device()->GetSamplerState(static_cast(unit), D3DSAMP_MAXANISOTROPY, &oldVal); - return oldVal; - } - //--------------------------------------------------------------------- - HRESULT D3D9RenderSystem::__SetRenderState(D3DRENDERSTATETYPE state, DWORD value) - { - HRESULT hr; - DWORD oldVal; - - if ( FAILED( hr = getActiveD3D9Device()->GetRenderState(state, &oldVal) ) ) - return hr; - if ( oldVal == value ) - return D3D_OK; - else - return getActiveD3D9Device()->SetRenderState(state, value); - } - //--------------------------------------------------------------------- - HRESULT D3D9RenderSystem::__SetSamplerState(DWORD sampler, D3DSAMPLERSTATETYPE type, DWORD value) - { - if(sampler < 4) - __SetSamplerState(sampler + D3DVERTEXTEXTURESAMPLER0, type, value); - - HRESULT hr; - DWORD oldVal; - - if ( FAILED( hr = getActiveD3D9Device()->GetSamplerState(sampler, type, &oldVal) ) ) - return hr; - if ( oldVal == value ) - return D3D_OK; - else - return getActiveD3D9Device()->SetSamplerState(sampler, type, value); - } - //--------------------------------------------------------------------- - HRESULT D3D9RenderSystem::__SetTextureStageState(DWORD stage, D3DTEXTURESTAGESTATETYPE type, DWORD value) - { - HRESULT hr; - DWORD oldVal; - - // can only set fixed-function texture stage state - if (mEnableFixedPipeline && stage < 8) - { - if ( FAILED( hr = getActiveD3D9Device()->GetTextureStageState(stage, type, &oldVal) ) ) - return hr; - if ( oldVal == value ) - return D3D_OK; - else - return getActiveD3D9Device()->SetTextureStageState(stage, type, value); - } - else - { - return D3D_OK; - } - } - //--------------------------------------------------------------------- - DepthBuffer* D3D9RenderSystem::_createDepthBufferFor( RenderTarget *renderTarget ) - { - IDirect3DSurface9* pBack[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; - memset (pBack, 0, sizeof(pBack) ); - renderTarget->getCustomAttribute( "DDBACKBUFFER", &pBack ); - if( !pBack[0] ) - return 0; - - D3DSURFACE_DESC srfDesc; - if( FAILED(pBack[0]->GetDesc(&srfDesc)) ) - { - OGRE_EXCEPT( Exception::ERR_RENDERINGAPI_ERROR, - "Failed to retrieve Surface Description from BackBuffer. RenderTarget: " + - renderTarget->getName(), - "D3D9RenderSystem::_createDepthBufferFor" ); - } - - //Find an appropiarte format for this depth buffer that best matches the RenderTarget's - D3DFORMAT dsfmt = _getDepthStencilFormatFor( srfDesc.Format ); - - //Create the depthstencil surface - IDirect3DSurface9 *depthBufferSurface = NULL; - IDirect3DDevice9* activeDevice = getActiveD3D9Device(); - HRESULT hr = activeDevice->CreateDepthStencilSurface( - srfDesc.Width, srfDesc.Height, dsfmt, - srfDesc.MultiSampleType, srfDesc.MultiSampleQuality, - TRUE, // discard true or false? - &depthBufferSurface, NULL); - if( FAILED(hr) ) - { - String msg = DXGetErrorDescription(hr); - OGRE_EXCEPT( Exception::ERR_RENDERINGAPI_ERROR, - "Error CreateDepthStencilSurface : " + msg, - "D3D9RenderSystem::_createDepthBufferFor" ); - } - - D3D9DepthBuffer *newDepthBuffer = OGRE_NEW D3D9DepthBuffer( DepthBuffer::POOL_DEFAULT, this, - activeDevice, depthBufferSurface, - dsfmt, srfDesc.Width, srfDesc.Height, - srfDesc.MultiSampleType, srfDesc.MultiSampleQuality, false ); - - return newDepthBuffer; - } - - //--------------------------------------------------------------------- - DepthBuffer* D3D9RenderSystem::_addManualDepthBuffer( IDirect3DDevice9* depthSurfaceDevice, IDirect3DSurface9 *depthSurface ) - { - //If this depth buffer was already added, return that one - DepthBufferVec::const_iterator itor = mDepthBufferPool[DepthBuffer::POOL_DEFAULT].begin(); - DepthBufferVec::const_iterator end = mDepthBufferPool[DepthBuffer::POOL_DEFAULT].end(); - - while( itor != end ) - { - if( static_cast(*itor)->getDepthBufferSurface() == depthSurface ) - return *itor; - - ++itor; - } - - //Nope, get the info about this depth buffer and create a new container fot it - D3DSURFACE_DESC dsDesc; - if( FAILED(depthSurface->GetDesc(&dsDesc)) ) - return 0; - - D3D9DepthBuffer *newDepthBuffer = OGRE_NEW D3D9DepthBuffer( DepthBuffer::POOL_DEFAULT, this, - depthSurfaceDevice, depthSurface, - dsDesc.Format, dsDesc.Width, dsDesc.Height, - dsDesc.MultiSampleType, dsDesc.MultiSampleQuality, true ); - - //Add the 'main' depth buffer to the pool - mDepthBufferPool[newDepthBuffer->getPoolId()].push_back( newDepthBuffer ); - - return newDepthBuffer; - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_cleanupDepthBuffers( IDirect3DDevice9 *creator ) - { - assert( creator ); - - DepthBufferMap::iterator itMap = mDepthBufferPool.begin(); - DepthBufferMap::iterator enMap = mDepthBufferPool.end(); - - while( itMap != enMap ) - { - DepthBufferVec::iterator itor = itMap->second.begin(); - DepthBufferVec::iterator end = itMap->second.end(); - - while( itor != end ) - { - //Only delete those who match the specified creator - if( static_cast(*itor)->getDeviceCreator() == creator ) - { - OGRE_DELETE *itor; - - //Erasing a vector invalidates iterators, we need to recalculate - //to avoid memory corruption and asserts. The new itor will point - //to the next iterator - const size_t idx = itor - itMap->second.begin(); - itMap->second.erase( itor ); //Erase - itor = itMap->second.begin() + idx; - end = itMap->second.end(); - } - else - ++itor; - } - - //Erase the pool if it's now empty. Note erasing from a map is - //valid while iterating through it - if( itMap->second.empty() ) - { - DepthBufferMap::iterator deadi = itMap++; - mDepthBufferPool.erase( deadi ); - } - else - ++itMap; - } - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_cleanupDepthBuffers( IDirect3DSurface9 *manualSurface ) - { - assert( manualSurface ); - - DepthBufferMap::iterator itMap = mDepthBufferPool.begin(); - DepthBufferMap::iterator enMap = mDepthBufferPool.end(); - - while( itMap != enMap ) - { - DepthBufferVec::iterator itor = itMap->second.begin(); - DepthBufferVec::iterator end = itMap->second.end(); - - while( itor != end ) - { - //Only delete those who match the specified surface - if( static_cast(*itor)->getDepthBufferSurface() == manualSurface ) - { - OGRE_DELETE *itor; - - //Erasing a vector invalidates iterators, we need to recalculate - //to avoid memory corruption and asserts. The new itor will point - //to the next iterator - const size_t idx = itor - itMap->second.begin(); - itMap->second.erase( itor ); //Erase - itor = itMap->second.begin() + idx; - end = itMap->second.end(); - } - else - ++itor; - } - - //Erase the pool if it's now empty. Note erasing from a map is - //valid while iterating through it - if( itMap->second.empty() ) - { - DepthBufferMap::iterator deadi = itMap++; - mDepthBufferPool.erase( deadi ); - } - else - ++itMap; - } - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_setRenderTarget(RenderTarget *target) - { - mActiveRenderTarget = target; - - if (mActiveRenderTarget) - { - HRESULT hr; - - // If this is called without going through RenderWindow::update, then - // the device will not have been set. Calling it twice is safe, the - // implementation ensures nothing happens if the same device is set twice - if (std::find(mRenderWindows.begin(), mRenderWindows.end(), target) != mRenderWindows.end()) - { - D3D9RenderWindow *window = static_cast(target); - mDeviceManager->setActiveRenderTargetDevice(window->getDevice()); - // also make sure we validate the device; if this never went - // through update() it won't be set - window->_validateDevice(); - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - window->_validateStereo(); -#endif - } - - // Retrieve render surfaces (up to OGRE_MAX_MULTIPLE_RENDER_TARGETS) - IDirect3DSurface9* pBack[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; - memset(pBack, 0, sizeof(pBack)); - target->getCustomAttribute( "DDBACKBUFFER", &pBack ); - if (!pBack[0]) - return; - - IDirect3DDevice9* activeDevice = getActiveD3D9Device(); - D3D9DepthBuffer *depthBuffer = static_cast(target->getDepthBuffer()); - - if( target->getDepthBufferPool() != DepthBuffer::POOL_NO_DEPTH && - (!depthBuffer || depthBuffer->getDeviceCreator() != activeDevice ) ) - { - //Depth is automatically managed and there is no depth buffer attached to this RT - //or the Current D3D device doesn't match the one this Depth buffer was created - setDepthBufferFor( target ); - - //Retrieve depth buffer again - depthBuffer = static_cast(target->getDepthBuffer()); - } - - if ((depthBuffer != NULL) && ( depthBuffer->getDeviceCreator() != activeDevice)) - { - OGRE_EXCEPT( Exception::ERR_RENDERINGAPI_ERROR, - "Can't use a depth buffer from a different device!", - "D3D9RenderSystem::_setRenderTarget" ); - } - - IDirect3DSurface9 *depthSurface = depthBuffer ? depthBuffer->getDepthBufferSurface() : NULL; - - // create the list of old render targets. - // The list of old render targets is needed so that we can avoid trying to bind a render target - // to a slot while it is already bound to another slot from before. Doing that would fail. - // - // NOTE: pOldRenderTargets[0] is NEVER set!!! - // We don't need it, so we don't waste time looking it up. - IDirect3DSurface9* pOldRenderTargets[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; - memset(pOldRenderTargets, 0, sizeof(pOldRenderTargets)); - uint maxRenderTargetCount = mCurrentCapabilities->getNumMultiRenderTargets(); - uint oldRenderTargetCount = 1; - for (uint i = 1; i < maxRenderTargetCount; ++i) - { - hr = activeDevice->GetRenderTarget(i, &pOldRenderTargets[ i ]); - if (hr == D3D_OK) - { - // GetRenderTarget bumps the reference count, so need to release to avoid a resource leak - pOldRenderTargets[ i ]->Release(); - oldRenderTargetCount = i + 1; - } - else if (hr == D3DERR_NOTFOUND) - { - // exit at the first "NOTFOUND" - // assumption: render targets must be contiguous - break; - } - else if (FAILED(hr)) - { - String msg = DXGetErrorDescription(hr); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to GetRenderTarget : " + msg, "D3D9RenderSystem::_setRenderTarget" ); - } - } - // Bind render targets - for (uint iRt = 0; iRt < maxRenderTargetCount; ++iRt) - { - IDirect3DSurface9* rt = pBack[ iRt ]; - // if new render target differs from what is already there, - if ( rt != pOldRenderTargets[ iRt ] ) // NOTE: always true when iRt == 0 - { - // check that the new render target isn't occupying a slot from before, and if it is, clear out the previous slot. - // Otherwise, we could end up trying to set the same render target in 2 different slots which will fail. - for (uint iOldRt = iRt + 1; iOldRt < oldRenderTargetCount; ++iOldRt) - { - // if it is (rare case), - if ( rt == pOldRenderTargets[ iOldRt ] ) - { - // clear it out of the old slot, so that we can successfully put it in its new slot - hr = activeDevice->SetRenderTarget( iOldRt, NULL ); - if (FAILED(hr)) - { - String msg = DXGetErrorDescription(hr); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to SetRenderTarget(NULL) : " + msg, "D3D9RenderSystem::_setRenderTarget" ); - } - } - } - hr = activeDevice->SetRenderTarget( iRt, rt ); - if (FAILED(hr)) - { - String msg = DXGetErrorDescription(hr); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to SetRenderTarget : " + msg, "D3D9RenderSystem::_setRenderTarget" ); - } - } - } - hr = activeDevice->SetDepthStencilSurface( depthSurface ); - if (FAILED(hr)) - { - String msg = DXGetErrorDescription(hr); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to setDepthStencil : " + msg, "D3D9RenderSystem::_setRenderTarget" ); - } - } - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_setViewport( Viewport *vp ) - { - if (!vp) - { - mActiveViewport = NULL; - _setRenderTarget(NULL); - } - else if( vp != mActiveViewport || vp->_isUpdated() ) - { - mActiveViewport = vp; - - // ok, it's different, time to set render target and viewport params - D3DVIEWPORT9 d3dvp; - HRESULT hr; - - // Set render target - RenderTarget* target = vp->getTarget(); - _setRenderTarget(target); - - //Reset the viewport after the render target has been set. If the device - //had been reset the viewport would have been set to NULL. - mActiveViewport = vp; - - _setCullingMode( mCullingMode ); - - // set viewport dimensions - d3dvp.X = vp->getActualLeft(); - d3dvp.Y = vp->getActualTop(); - d3dvp.Width = vp->getActualWidth(); - d3dvp.Height = vp->getActualHeight(); - if (target->requiresTextureFlipping()) - { - // Convert "top-left" to "bottom-left" - d3dvp.Y = target->getHeight() - d3dvp.Height - d3dvp.Y; - } - - // Z-values from 0.0 to 1.0 (TODO: standardise with OpenGL) - d3dvp.MinZ = 0.0f; - d3dvp.MaxZ = 1.0f; - - if( FAILED( hr = getActiveD3D9Device()->SetViewport( &d3dvp ) ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set viewport.", "D3D9RenderSystem::_setViewport" ); - - // Set sRGB write mode - __SetRenderState(D3DRS_SRGBWRITEENABLE, target->isHardwareGammaEnabled()); - - vp->_clearUpdatedFlag(); - } - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_beginFrame() - { - RenderSystem::_beginFrame(); - - HRESULT hr; - if( FAILED( hr = getActiveD3D9Device()->BeginScene() ) ) - { - String msg = DXGetErrorDescription(hr); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error beginning frame :" + msg, "D3D9RenderSystem::_beginFrame" ); - } - - mLastVertexSourceCount = 0; - - // Clear left overs of previous viewport. - // I.E: Viewport A can use 3 different textures and light states - // When trying to render viewport B these settings should be cleared, otherwise - // graphical artifacts might occur. - mDeviceManager->getActiveDevice()->clearDeviceStreams(); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_endFrame() - { - HRESULT hr; - if( FAILED( hr = getActiveD3D9Device()->EndScene() ) ) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error ending frame", "D3D9RenderSystem::_endFrame" ); - - mDeviceManager->destroyInactiveRenderDevices(); - } - void D3D9RenderSystem::setVertexDeclaration(VertexDeclaration* decl) - { - HRESULT hr; - - D3D9VertexDeclaration* d3ddecl = static_cast(decl); - - if (FAILED(hr = getActiveD3D9Device()->SetVertexDeclaration(d3ddecl->getD3DVertexDeclaration()))) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to set D3D9 vertex declaration", - "D3D9RenderSystem::setVertexDeclaration"); - } - - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::setVertexBufferBinding(VertexBufferBinding* binding, int numberOfInstances, bool indexesUsed) - { - /*if (!prg) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Null program bound.", - "D3D9RenderSystem::bindGpuProgram"); - }*/ - - HRESULT hr; - - // TODO: attempt to detect duplicates - const VertexBufferBinding::VertexBufferBindingMap& binds = binding->getBindings(); - VertexBufferBinding::VertexBufferBindingMap::const_iterator i, iend; - size_t source = 0; - iend = binds.end(); - for (i = binds.begin(); i != iend; ++i, ++source) - { - D3D9HardwareBuffer* d3d9buf = i->second->_getImpl(); - - // Unbind gap sources - for ( ; source < i->first; ++source) - { - hr = getActiveD3D9Device()->SetStreamSource(static_cast(source), NULL, 0, 0); - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to reset unused D3D9 stream source", - "D3D9RenderSystem::setVertexBufferBinding"); - } - } - - hr = getActiveD3D9Device()->SetStreamSource( - static_cast(source), - (IDirect3DVertexBuffer9*)d3d9buf->getD3D9Resource(), - 0, // no stream offset, this is handled in _render instead - static_cast(i->second->getVertexSize()) // stride - ); - - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to set D3D9 stream source for buffer binding", - "D3D9RenderSystem::setVertexBufferBinding"); - } - - // SetStreamSourceFreq - if ( numberOfInstances > 1 ) - { - if ( i->second->isInstanceData() ) - { - hr = getActiveD3D9Device()->SetStreamSourceFreq( static_cast(source), D3DSTREAMSOURCE_INSTANCEDATA | i->second->getInstanceDataStepRate() ); - } - else - { - if ( !indexesUsed ) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Instance data used without index data.", - "D3D9RenderSystem::setVertexBufferBinding"); - } - hr = getActiveD3D9Device()->SetStreamSourceFreq( static_cast(source), D3DSTREAMSOURCE_INDEXEDDATA | numberOfInstances ); - } - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to set D3D9 stream source Freq", - "D3D9RenderSystem::setVertexBufferBinding"); - } - } - else - { - hr = getActiveD3D9Device()->SetStreamSourceFreq( static_cast(source), 1 ); - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to reset unused D3D9 stream source Freq", - "D3D9RenderSystem::setVertexBufferBinding"); - } - } - - } - - // Unbind any unused sources - for (size_t unused = source; unused < mLastVertexSourceCount; ++unused) - { - - hr = getActiveD3D9Device()->SetStreamSource(static_cast(unused), NULL, 0, 0); - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to reset unused D3D9 stream source", - "D3D9RenderSystem::setVertexBufferBinding"); - } - - hr = getActiveD3D9Device()->SetStreamSourceFreq( static_cast(unused), 1 ); - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to reset unused D3D9 stream source Freq", - "D3D9RenderSystem::setVertexBufferBinding"); - } - - } - mLastVertexSourceCount = source; - - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::_render(const RenderOperation& op) - { - // Exit immediately if there is nothing to render - // This caused a problem on FireGL 8800 - if (op.vertexData->vertexCount == 0) - return; - - // Call super class - RenderSystem::_render(op); - - - if ( !mEnableFixedPipeline && !mRealCapabilities->hasCapability(RSC_FIXED_FUNCTION) - && - ( - ( !mProgramBound[GPT_VERTEX_PROGRAM] ) || - (!mProgramBound[GPT_FRAGMENT_PROGRAM] && op.operationType != RenderOperation::OT_POINT_LIST) - ) - ) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Attempted to render using the fixed pipeline when it is disabled.", - "D3D9RenderSystem::_render"); - } - - setVertexDeclaration(op.vertexData->vertexDeclaration); - setVertexBufferBinding(op.vertexData->vertexBufferBinding, op.numberOfInstances, op.useIndexes); - - // Determine rendering operation - D3DPRIMITIVETYPE primType = D3DPT_TRIANGLELIST; - DWORD primCount = 0; - switch( op.operationType ) - { - case RenderOperation::OT_POINT_LIST: - primType = D3DPT_POINTLIST; - primCount = static_cast(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount); - break; - - case RenderOperation::OT_LINE_LIST: - primType = D3DPT_LINELIST; - primCount = static_cast(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) / 2; - break; - - case RenderOperation::OT_LINE_STRIP: - primType = D3DPT_LINESTRIP; - primCount = static_cast(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) - 1; - break; - - case RenderOperation::OT_TRIANGLE_LIST: - primType = D3DPT_TRIANGLELIST; - primCount = static_cast(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) / 3; - break; - - case RenderOperation::OT_TRIANGLE_STRIP: - primType = D3DPT_TRIANGLESTRIP; - primCount = static_cast(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) - 2; - break; - - case RenderOperation::OT_TRIANGLE_FAN: - primType = D3DPT_TRIANGLEFAN; - primCount = static_cast(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) - 2; - break; - } - - if (!primCount) - return; - - // Issue the op - HRESULT hr; - if( op.useIndexes ) - { - D3D9HardwareBuffer* d3dIdxBuf = op.indexData->indexBuffer->_getImpl(); - hr = getActiveD3D9Device()->SetIndices( (IDirect3DIndexBuffer9*)d3dIdxBuf->getD3D9Resource() ); - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to set index buffer", "D3D9RenderSystem::_render" ); - } - - do - { - // do indexed draw operation - hr = getActiveD3D9Device()->DrawIndexedPrimitive( - primType, - static_cast(op.vertexData->vertexStart), - 0, // Min vertex index - assume we can go right down to 0 - static_cast(op.vertexData->vertexCount), - static_cast(op.indexData->indexStart), - static_cast(primCount) - ); - - } while (updatePassIterationRenderState()); - } - else - { - // nfz: gpu_iterate - do - { - // Unindexed, a little simpler! - hr = getActiveD3D9Device()->DrawPrimitive( - primType, - static_cast(op.vertexData->vertexStart), - static_cast(primCount) - ); - - } while (updatePassIterationRenderState()); - } - - if( FAILED( hr ) ) - { - String msg = DXGetErrorDescription(hr); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to DrawPrimitive : " + msg, "D3D9RenderSystem::_render" ); - } - - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::setNormaliseNormals(bool normalise) - { - __SetRenderState(D3DRS_NORMALIZENORMALS, - normalise ? TRUE : FALSE); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::bindGpuProgram(GpuProgram* prg) - { - if (!prg) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Null program bound.", - "D3D9RenderSystem::bindGpuProgram"); - } - - HRESULT hr; - switch (prg->getType()) - { - case GPT_VERTEX_PROGRAM: - hr = getActiveD3D9Device()->SetVertexShader( - static_cast(prg)->getVertexShader()); - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error calling SetVertexShader", "D3D9RenderSystem::bindGpuProgram"); - } - break; - case GPT_FRAGMENT_PROGRAM: - hr = getActiveD3D9Device()->SetPixelShader( - static_cast(prg)->getPixelShader()); - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error calling SetPixelShader", "D3D9RenderSystem::bindGpuProgram"); - } - // disable FFP fog, as it gets still applied even in presence of shader. Matching other render-systems here. - hr = __SetRenderState(D3DRS_FOGENABLE, FALSE); - break; - }; - - // Make sure texcoord index is equal to stage value, As SDK Doc suggests: - // "When rendering using vertex shaders, each stage's texture coordinate index must be set to its default value." - // This solves such an errors when working with the Debug runtime - - // "Direct3D9: (ERROR) :Stage 1 - Texture coordinate index in the stage must be equal to the stage index when programmable vertex pipeline is used". - for (unsigned int nStage=0; nStage < 8; ++nStage) - __SetTextureStageState(nStage, D3DTSS_TEXCOORDINDEX, nStage); - - RenderSystem::bindGpuProgram(prg); - - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::unbindGpuProgram(GpuProgramType gptype) - { - /*if (!prg) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Null program bound.", - "D3D9RenderSystem::bindGpuProgram"); - }*/ - mActiveParameters[gptype].reset(); - HRESULT hr; - switch(gptype) - { - case GPT_VERTEX_PROGRAM: - hr = getActiveD3D9Device()->SetVertexShader(NULL); - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error resetting SetVertexShader to NULL", - "D3D9RenderSystem::unbindGpuProgram"); - } - break; - case GPT_FRAGMENT_PROGRAM: - hr = getActiveD3D9Device()->SetPixelShader(NULL); - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error resetting SetPixelShader to NULL", - "D3D9RenderSystem::unbindGpuProgram"); - } - break; - }; - RenderSystem::unbindGpuProgram(gptype); - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::bindGpuProgramParameters(GpuProgramType gptype, - const GpuProgramParametersPtr& params, uint16 variability) - { - if (variability & (uint16)GPV_GLOBAL) - { - // D3D9 doesn't support shared constant buffers, so use copy routine - params->_copySharedParams(); - } - - HRESULT hr; - GpuLogicalBufferStructPtr floatLogical = params->getLogicalBufferStruct(); - - mActiveParameters[gptype] = params; - switch(gptype) - { - case GPT_VERTEX_PROGRAM: - { - OGRE_LOCK_MUTEX(floatLogical->mutex); - - for (GpuLogicalIndexUseMap::const_iterator i = floatLogical->map.begin(); - i != floatLogical->map.end(); ++i) - { - if (i->second.variability & variability) - { - size_t logicalIndex = i->first; - size_t slotCount = i->second.currentSize / 4; - assert (i->second.currentSize % 4 == 0 && "Should not have any " - "elements less than 4 wide for D3D9"); - - if(i->second.baseType == BCT_FLOAT) - { - const float* pFloat = params->getFloatPointer(i->second.physicalIndex); - hr = getActiveD3D9Device()->SetVertexShaderConstantF( - (UINT)logicalIndex, pFloat, (UINT)slotCount); - } - else - { - const int* pInt = params->getIntPointer(i->second.physicalIndex); - hr = getActiveD3D9Device()->SetVertexShaderConstantI( - static_cast(logicalIndex), pInt, static_cast(slotCount)); - } - - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Unable to upload vertex shader parameters"); - } - } - - } - } - break; - case GPT_FRAGMENT_PROGRAM: - { - OGRE_LOCK_MUTEX(floatLogical->mutex); - - for (GpuLogicalIndexUseMap::const_iterator i = floatLogical->map.begin(); - i != floatLogical->map.end(); ++i) - { - if (i->second.variability & variability) - { - size_t logicalIndex = i->first; - size_t slotCount = i->second.currentSize / 4; - assert (i->second.currentSize % 4 == 0 && "Should not have any " - "elements less than 4 wide for D3D9"); - - if(i->second.baseType == BCT_FLOAT) - { - const float* pFloat = params->getFloatPointer(i->second.physicalIndex); - hr = getActiveD3D9Device()->SetPixelShaderConstantF( - (UINT)logicalIndex, pFloat, (UINT)slotCount); - } - else - { - const int* pInt = params->getIntPointer(i->second.physicalIndex); - hr = getActiveD3D9Device()->SetPixelShaderConstantI( - static_cast(logicalIndex), pInt, static_cast(slotCount)); - } - - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Unable to upload pixel shader parameters"); - } - } - } - - } - break; - }; - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::setClipPlanesImpl(const PlaneList& clipPlanes) - { - size_t i; - size_t numClipPlanes; - D3DXPLANE dx9ClipPlane; - DWORD mask = 0; - HRESULT hr; - - numClipPlanes = clipPlanes.size(); - for (i = 0; i < numClipPlanes; ++i) - { - const Plane& plane = clipPlanes[i]; - - dx9ClipPlane.a = plane.normal.x; - dx9ClipPlane.b = plane.normal.y; - dx9ClipPlane.c = plane.normal.z; - dx9ClipPlane.d = plane.d; - - if (mProgramBound[GPT_VERTEX_PROGRAM]) - { - // programmable clips in clip space (ugh) - // must transform worldspace planes by view/proj - D3DXMATRIX xform; - D3DXMatrixMultiply(&xform, (D3DXMATRIX*)&mDxViewMat, (D3DXMATRIX*)&mDxProjMat); - D3DXMatrixInverse(&xform, NULL, &xform); - D3DXMatrixTranspose(&xform, &xform); - D3DXPlaneTransform(&dx9ClipPlane, &dx9ClipPlane, &xform); - } - - hr = getActiveD3D9Device()->SetClipPlane(static_cast(i), dx9ClipPlane); - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to set clip plane", - "D3D9RenderSystem::setClipPlanes"); - } - - mask |= (1 << i); - } - - hr = __SetRenderState(D3DRS_CLIPPLANEENABLE, mask); - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to set render state for clip planes", - "D3D9RenderSystem::setClipPlanes"); - } - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::setScissorTest(bool enabled, const Rect& _rect) - { - HRESULT hr; - if (enabled) - { - if (FAILED(hr = __SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE))) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to enable scissor rendering state; " + getErrorDescription(hr), - "D3D9RenderSystem::setScissorTest"); - } - RECT rect; - rect.left = _rect.left; - rect.top = _rect.top; - rect.bottom = _rect.bottom; - rect.right = _rect.right; - if (FAILED(hr = getActiveD3D9Device()->SetScissorRect(&rect))) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to set scissor rectangle; " + getErrorDescription(hr), - "D3D9RenderSystem::setScissorTest"); - } - } - else - { - if (FAILED(hr = __SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE))) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to disable scissor rendering state; " + getErrorDescription(hr), - "D3D9RenderSystem::setScissorTest"); - } - } - } - //--------------------------------------------------------------------- - void D3D9RenderSystem::clearFrameBuffer(unsigned int buffers, - const ColourValue& colour, float depth, unsigned short stencil) - { - DWORD flags = 0; - if (buffers & FBT_COLOUR) - { - flags |= D3DCLEAR_TARGET; - } - if (buffers & FBT_DEPTH) - { - flags |= D3DCLEAR_ZBUFFER; - } - // Only try to clear the stencil buffer if supported - if (buffers & FBT_STENCIL && mCurrentCapabilities->hasCapability(RSC_HWSTENCIL)) - { - flags |= D3DCLEAR_STENCIL; - } - HRESULT hr; - if( FAILED( hr = getActiveD3D9Device()->Clear( - 0, - NULL, - flags, - colour.getAsARGB(), - depth, - stencil ) ) ) - { - String msg = DXGetErrorDescription(hr); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error clearing frame buffer : " - + msg, "D3D9RenderSystem::clearFrameBuffer" ); - } - } - // ------------------------------------------------------------------ - void D3D9RenderSystem::setClipPlane (ushort index, Real A, Real B, Real C, Real D) - { - float plane[4] = { A, B, C, D }; - getActiveD3D9Device()->SetClipPlane (index, plane); - } - - // ------------------------------------------------------------------ - void D3D9RenderSystem::enableClipPlane (ushort index, bool enable) - { - DWORD prev; - getActiveD3D9Device()->GetRenderState(D3DRS_CLIPPLANEENABLE, &prev); - __SetRenderState(D3DRS_CLIPPLANEENABLE, enable? - (prev | (1 << index)) : (prev & ~(1 << index))); - } - //--------------------------------------------------------------------- - HardwareOcclusionQuery* D3D9RenderSystem::createHardwareOcclusionQuery() - { - D3D9HardwareOcclusionQuery* ret = OGRE_NEW D3D9HardwareOcclusionQuery(); - mHwOcclusionQueries.push_back(ret); - return ret; - } - //--------------------------------------------------------------------- - Real D3D9RenderSystem::getHorizontalTexelOffset() - { - // D3D considers the origin to be in the center of a pixel - return -0.5f; - } - //--------------------------------------------------------------------- - Real D3D9RenderSystem::getVerticalTexelOffset() - { - // D3D considers the origin to be in the center of a pixel - return -0.5f; - } - //--------------------------------------------------------------------- - Real D3D9RenderSystem::getMinimumDepthInputValue() - { - // Range [0.0f, 1.0f] - return 0.0f; - } - //--------------------------------------------------------------------- - Real D3D9RenderSystem::getMaximumDepthInputValue() - { - // Range [0.0f, 1.0f] - // D3D inverts even identity view matrices, so maximum INPUT is -1.0 - return -1.0f; - } - //--------------------------------------------------------------------- - IDirect3D9* D3D9RenderSystem::getDirect3D9() - { - IDirect3D9* pDirect3D9 = msD3D9RenderSystem->mD3D; - - if (pDirect3D9 == NULL) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "Direct3D9 interface is NULL !!!", - "D3D9RenderSystem::getDirect3D9" ); - } - - return pDirect3D9; - } - - //--------------------------------------------------------------------- - UINT D3D9RenderSystem::getResourceCreationDeviceCount() - { - D3D9ResourceCreationPolicy creationPolicy = msD3D9RenderSystem->mResourceManager->getCreationPolicy(); - - if (creationPolicy == RCP_CREATE_ON_ACTIVE_DEVICE) - { - return 1; - } - else if (creationPolicy == RCP_CREATE_ON_ALL_DEVICES) - { - return msD3D9RenderSystem->mDeviceManager->getDeviceCount(); - } - - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "Invalid resource creation policy !!!", - "D3D9RenderSystem::getResourceCreationDeviceCount" ); - - return 0; - } - - //--------------------------------------------------------------------- - IDirect3DDevice9* D3D9RenderSystem::getResourceCreationDevice(UINT index) - { - D3D9ResourceCreationPolicy creationPolicy = msD3D9RenderSystem->mResourceManager->getCreationPolicy(); - IDirect3DDevice9* d3d9Device = NULL; - - if (creationPolicy == RCP_CREATE_ON_ACTIVE_DEVICE) - { - d3d9Device = msD3D9RenderSystem->getActiveD3D9Device(); - } - else if (creationPolicy == RCP_CREATE_ON_ALL_DEVICES) - { - d3d9Device = msD3D9RenderSystem->mDeviceManager->getDevice(index)->getD3D9Device(); - } - else - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "Invalid resource creation policy !!!", - "D3D9RenderSystem::getResourceCreationDevice" ); - } - - return d3d9Device; - } - - //--------------------------------------------------------------------- - IDirect3DDevice9* D3D9RenderSystem::getActiveD3D9Device() - { - D3D9Device* activeDevice = msD3D9RenderSystem->mDeviceManager->getActiveDevice(); - IDirect3DDevice9* d3d9Device; - - d3d9Device = activeDevice->getD3D9Device(); - - if (d3d9Device == NULL) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "Current d3d9 device is NULL !!!", - "D3D9RenderSystem::getActiveD3D9Device" ); - } - - return d3d9Device; - } - - //--------------------------------------------------------------------- - IDirect3DDevice9* D3D9RenderSystem::getActiveD3D9DeviceIfExists() - { - D3D9Device* activeDevice = msD3D9RenderSystem->mDeviceManager->getActiveDevice(); - return activeDevice ? activeDevice->getD3D9Device() : NULL; - } - - uint D3D9RenderSystem::getAdapterNumber() - { - return mActiveD3DDriver->getAdapterNumber(); - } - - //--------------------------------------------------------------------- - // Formats to try, in decreasing order of preference - D3DFORMAT ddDepthStencilFormats[]={ - D3DFMT_D24FS8, - D3DFMT_D24S8, - D3DFMT_D24X4S4, - D3DFMT_D24X8, - D3DFMT_D15S1, - D3DFMT_D16, - D3DFMT_D32 - }; -#define NDSFORMATS (sizeof(ddDepthStencilFormats)/sizeof(D3DFORMAT)) - - D3DFORMAT D3D9RenderSystem::_getDepthStencilFormatFor(D3DFORMAT fmt) - { - /// Check if result is cached - DepthStencilHash::iterator i = mDepthStencilHash.find((unsigned int)fmt); - if(i != mDepthStencilHash.end()) - return i->second; - /// If not, probe with CheckDepthStencilMatch - D3DFORMAT dsfmt = D3DFMT_UNKNOWN; - - /// Get description of primary render target - D3D9Device* activeDevice = mDeviceManager->getActiveDevice(); - IDirect3DSurface9* mSurface = activeDevice->getPrimaryWindow()->getRenderSurface(); - D3DSURFACE_DESC srfDesc; - - if(mSurface && SUCCEEDED(mSurface->GetDesc(&srfDesc))) - { - /// Probe all depth stencil formats - /// Break on first one that matches - for(size_t x=0; xCheckDeviceFormat( - activeDevice->getAdapterNumber(), - activeDevice->getDeviceType(), - srfDesc.Format, - D3DUSAGE_DEPTHSTENCIL, - D3DRTYPE_SURFACE, - ddDepthStencilFormats[x]) != D3D_OK) - { - continue; - } - // Verify that the depth format is compatible - if(mD3D->CheckDepthStencilMatch( - activeDevice->getAdapterNumber(), - activeDevice->getDeviceType(), - srfDesc.Format, - fmt, ddDepthStencilFormats[x]) == D3D_OK) - { - dsfmt = ddDepthStencilFormats[x]; - break; - } - } - } - /// Cache result - mDepthStencilHash[(unsigned int)fmt] = dsfmt; - return dsfmt; - } - //--------------------------------------------------------------------- - D3D9ResourceManager* D3D9RenderSystem::getResourceManager() - { - return msD3D9RenderSystem->mResourceManager; - } - - //--------------------------------------------------------------------- - D3D9DeviceManager* D3D9RenderSystem::getDeviceManager() - { - return msD3D9RenderSystem->mDeviceManager; - } - - //--------------------------------------------------------------------- - RenderSystemCapabilities* D3D9RenderSystem::createRenderSystemCapabilities() const - { - return mRealCapabilities; - } - - //--------------------------------------------------------------------- - bool D3D9RenderSystem::IsActiveDeviceLost() - { - return D3D9RenderSystem::getDeviceManager()->getActiveDevice()->isDeviceLost(); - } - - //--------------------------------------------------------------------- - void D3D9RenderSystem::beginProfileEvent( const String &eventName ) - { - if( eventName.empty() ) - return; - - std::vector result(eventName.length() + 1, '\0'); - (void)MultiByteToWideChar(CP_ACP, 0, eventName.data(), eventName.length(), &result[0], result.size()); - (void)D3DPERF_BeginEvent(D3DCOLOR_ARGB(1, 0, 1, 0), &result[0]); - } - - //--------------------------------------------------------------------- - void D3D9RenderSystem::endProfileEvent( void ) - { - (void)D3DPERF_EndEvent(); - } - - //--------------------------------------------------------------------- - void D3D9RenderSystem::markProfileEvent( const String &eventName ) - { - if( eventName.empty() ) - return; - - std::vector result(eventName.length() + 1, '\0'); - (void)MultiByteToWideChar(CP_ACP, 0, eventName.data(), eventName.length(), &result[0], result.size()); - (void)D3DPERF_SetMarker(D3DCOLOR_ARGB(1, 0, 1, 0), &result[0]); - } - - //--------------------------------------------------------------------- - void D3D9RenderSystem::notifyOnDeviceLost(D3D9Device* device) - { - StringStream ss; - - ss << "D3D9 Device 0x[" << device->getD3D9Device() << "] entered lost state"; - LogManager::getSingleton().logMessage(ss.str()); - - fireDeviceEvent(device, "DeviceLost"); - - } - - //--------------------------------------------------------------------- - void D3D9RenderSystem::notifyOnDeviceReset(D3D9Device* device) - { - // Reset state attributes. - mProgramBound[GPT_VERTEX_PROGRAM] = false; - mProgramBound[GPT_FRAGMENT_PROGRAM] = false; - mLastVertexSourceCount = 0; - - - // Force all compositors to reconstruct their internal resources - // render textures will have been changed without their knowledge - CompositorManager::getSingleton()._reconstructAllCompositorResources(); - - // Restore previous active device. - - // Invalidate active view port. - mActiveViewport = NULL; - - StringStream ss; - - // Reset the texture stages, they will need to be rebound - for (size_t i = 0; i < OGRE_MAX_TEXTURE_LAYERS; ++i) - _setTexture(i, false, TexturePtr()); - - LogManager::getSingleton().logMessage("!!! Direct3D Device successfully restored."); - - ss << "D3D9 device: 0x[" << device->getD3D9Device() << "] was reset"; - LogManager::getSingleton().logMessage(ss.str()); - - fireDeviceEvent(device, "DeviceRestored"); - - } - - //--------------------------------------------------------------------- - void D3D9RenderSystem::determineFSAASettings(IDirect3DDevice9* d3d9Device, - size_t fsaa, const String& fsaaHint, D3DFORMAT d3dPixelFormat, - bool fullScreen, D3DMULTISAMPLE_TYPE *outMultisampleType, DWORD *outMultisampleQuality) - { - bool ok = false; - bool useCSAA = !fsaaHint.empty() && fsaaHint.front() == 'f'; - - D3D9DriverList* driverList = getDirect3DDrivers(); - D3D9Driver* deviceDriver = mActiveD3DDriver; - D3D9Device* device = mDeviceManager->getDeviceFromD3D9Device(d3d9Device); - - for (uint i = 0; i < driverList->count(); ++i) - { - D3D9Driver* currDriver = driverList->item(i); - - if (currDriver->getAdapterNumber() == device->getAdapterNumber()) - { - deviceDriver = currDriver; - break; - } - } - - // http://developer.download.nvidia.com/assets/gamedev/docs/CSAA_Tutorial.pdf - // http://developer.amd.com/wordpress/media/2012/10/EQAA%20Modes%20for%20AMD%20HD%206900%20Series%20Cards.pdf - // it would be tempting to use getCapabilities()->getVendor() == GPU_NVIDIA but - // if this is the first window, caps will not be initialised yet - if (deviceDriver->getAdapterIdentifier().VendorId != 0x10DE && - deviceDriver->getAdapterIdentifier().VendorId != 0x1002) - { - useCSAA = false; - } - - while (!ok) - { - // Deal with special cases - if (useCSAA) - { - switch(fsaa) - { - case 8: // 8f16 - *outMultisampleType = D3DMULTISAMPLE_8_SAMPLES; - *outMultisampleQuality = 2; - break; - case 4: // 4f8 - *outMultisampleType = D3DMULTISAMPLE_4_SAMPLES; - *outMultisampleQuality = 2; - break; - } - } - else // !CSAA - { - *outMultisampleType = (D3DMULTISAMPLE_TYPE)fsaa; - *outMultisampleQuality = 0; - } - - - HRESULT hr; - DWORD outQuality; - hr = mD3D->CheckDeviceMultiSampleType( - deviceDriver->getAdapterNumber(), - D3DDEVTYPE_HAL, - d3dPixelFormat, - fullScreen, - *outMultisampleType, - &outQuality); - - if (SUCCEEDED(hr) && - (!useCSAA || outQuality > *outMultisampleQuality)) - { - ok = true; - } - else - { - // downgrade - if (useCSAA) - { - useCSAA = false; - } - else - { - // drop samples - --fsaa; - - OgreAssert(fsaa > 0, "FSAA underflow: infinite loop (this should never happen)"); - - if (fsaa <= 1) - { - // ran out of options, no FSAA - fsaa = 0; - ok = true; - - *outMultisampleType = D3DMULTISAMPLE_NONE; - *outMultisampleQuality = 0; - } - } - } - - } // while !ok - } - - //--------------------------------------------------------------------- - void D3D9RenderSystem::fireDeviceEvent( D3D9Device* device, const String & name ) - { - NameValuePairList params; - params["D3DDEVICE"] = StringConverter::toString((size_t)device->getD3D9Device()); - params["DEVICE_ADAPTER_NUMBER"] = StringConverter::toString(device->getAdapterNumber()); - - fireEvent(name, ¶ms); - } - //--------------------------------------------------------------------- -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - void D3D9RenderSystem::createStereoDriver(const NameValuePairList* miscParams) - { - // Get the value used to create the render system. If none, get the parameter value used to create the window. - bool stereoMode = StringConverter::parseBool(mOptions["Frame Sequential Stereo"].currentValue); - if (!stereoMode) - { - NameValuePairList::const_iterator iter = miscParams->find("stereoMode"); - if (iter != miscParams->end()) - stereoMode = StringConverter::parseBool((*iter).second); - } - - // Always create the stereo bridge regardless of the mode - mStereoDriver = OGRE_NEW D3D9StereoDriverBridge(stereoMode); - } - //--------------------------------------------------------------------- - bool D3D9RenderSystem::setDrawBuffer(ColourBufferType colourBuffer) - { - return D3D9StereoDriverBridge::getSingleton().setDrawBuffer(colourBuffer); - } - //--------------------------------------------------------------------- -#endif -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9RenderWindow.cpp b/RenderSystems/Direct3D9/src/OgreD3D9RenderWindow.cpp deleted file mode 100644 index 89cdd9b739f..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9RenderWindow.cpp +++ /dev/null @@ -1,959 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9RenderWindow.h" -#include "OgreLogManager.h" -#include "OgreViewport.h" -#include "OgreException.h" -#include "OgreD3D9RenderSystem.h" -#include "OgreRenderSystem.h" -#include "OgreBitwise.h" -#include "OgreImageCodec.h" -#include "OgreStringConverter.h" -#include "OgreRoot.h" -#include "OgreD3D9DeviceManager.h" -#include "OgreDepthBuffer.h" - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 -#include "OgreD3D9StereoDriverBridge.h" -#endif - -namespace Ogre -{ - D3D9RenderWindow::D3D9RenderWindow(HINSTANCE instance) - : mInstance(instance) - { - mDevice = NULL; - mIsFullScreen = false; - mIsExternal = false; - mHWnd = 0; - mActive = false; - mHidden = false; - mSwitchingFullscreen = false; - mDisplayFrequency = 0; - mDeviceValid = false; - mUseNVPerfHUD = false; - mWindowedWinStyle = 0; - mFullscreenWinStyle = 0; - mDesiredWidth = 0; - mDesiredHeight = 0; - } - - D3D9RenderWindow::~D3D9RenderWindow() - { - destroy(); - } - - void D3D9RenderWindow::create(const String& name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams) - { - HINSTANCE hInst = mInstance; - - WNDPROC windowProc = DefWindowProc; - HWND externalHandle = 0; - mFSAAType = D3DMULTISAMPLE_NONE; - mFSAAQuality = 0; - mFSAA = 0; - mVSync = false; - mVSyncInterval = 1; - String title = name; - unsigned int colourDepth = 32; - int left = INT_MAX; // Defaults to screen center - int top = INT_MAX; // Defaults to screen center - bool depthBuffer = true; - String border = ""; - bool outerSize = false; - mUseNVPerfHUD = false; - size_t fsaaSamples = 0; - String fsaaHint; - bool enableDoubleClick = false; - - D3D9RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - int monitorIndex = rsys->getAdapterNumber(); // default to whatever was set in "Rendering Device" config option - - if(miscParams) - { - // Get variable-length params - NameValuePairList::const_iterator opt; - // left (x) - opt = miscParams->find("left"); - if(opt != miscParams->end()) - left = StringConverter::parseInt(opt->second); - // top (y) - opt = miscParams->find("top"); - if(opt != miscParams->end()) - top = StringConverter::parseInt(opt->second); - // Window title - opt = miscParams->find("title"); - if(opt != miscParams->end()) - title = opt->second; - opt = miscParams->find("windowProc"); - if (opt != miscParams->end()) - windowProc = reinterpret_cast(StringConverter::parseSizeT(opt->second)); - // externalWindowHandle -> externalHandle - opt = miscParams->find("externalWindowHandle"); - if (opt == miscParams->end()) - opt = miscParams->find("parentWindowHandle"); - if(opt != miscParams->end()) - externalHandle = (HWND)StringConverter::parseSizeT(opt->second); - // vsync [parseBool] - opt = miscParams->find("vsync"); - if(opt != miscParams->end()) - mVSync = StringConverter::parseBool(opt->second); - // hidden [parseBool] - opt = miscParams->find("hidden"); - if(opt != miscParams->end()) - mHidden = StringConverter::parseBool(opt->second); - // vsyncInterval [parseUnsignedInt] - opt = miscParams->find("vsyncInterval"); - if(opt != miscParams->end()) - mVSyncInterval = StringConverter::parseUnsignedInt(opt->second); - // displayFrequency - opt = miscParams->find("displayFrequency"); - if(opt != miscParams->end()) - mDisplayFrequency = StringConverter::parseUnsignedInt(opt->second); - // colourDepth - opt = miscParams->find("colourDepth"); - if(opt != miscParams->end()) - colourDepth = StringConverter::parseUnsignedInt(opt->second); - // depthBuffer [parseBool] - opt = miscParams->find("depthBuffer"); - if(opt != miscParams->end()) - depthBuffer = StringConverter::parseBool(opt->second); - // FSAA settings - opt = miscParams->find("FSAA"); - if(opt != miscParams->end()) - { - mFSAA = StringConverter::parseUnsignedInt(opt->second); - } - opt = miscParams->find("FSAAHint"); - if(opt != miscParams->end()) - { - mFSAAHint = opt->second; - } - - // window border style - opt = miscParams->find("border"); - if(opt != miscParams->end()) - border = opt->second; - // set outer dimensions? - opt = miscParams->find("outerDimensions"); - if(opt != miscParams->end()) - outerSize = StringConverter::parseBool(opt->second); - // NV perf HUD? - opt = miscParams->find("useNVPerfHUD"); - if(opt != miscParams->end()) - mUseNVPerfHUD = StringConverter::parseBool(opt->second); - // sRGB? - opt = miscParams->find("gamma"); - if(opt != miscParams->end()) - mHwGamma = StringConverter::parseBool(opt->second); - // monitor index - opt = miscParams->find("monitorIndex"); - if(opt != miscParams->end()) - monitorIndex = StringConverter::parseInt(opt->second); - opt = miscParams->find("show"); - if(opt != miscParams->end()) - mHidden = !StringConverter::parseBool(opt->second); - // enable double click messages - opt = miscParams->find("enableDoubleClick"); - if(opt != miscParams->end()) - enableDoubleClick = StringConverter::parseBool(opt->second); - - } - mIsFullScreen = fullScreen; - - // Destroy current window if any - if( mHWnd ) - destroy(); - - if (!externalHandle) - { - DWORD dwStyleEx = 0; - HMONITOR hMonitor = NULL; - MONITORINFO monitorInfo; - RECT rc; - - // If we specified which adapter we want to use - find it's monitor. - if (monitorIndex != -1) - { - IDirect3D9* direct3D9 = D3D9RenderSystem::getDirect3D9(); - - for (uint i=0; i < direct3D9->GetAdapterCount(); ++i) - { - if (i == monitorIndex) - { - hMonitor = direct3D9->GetAdapterMonitor(i); - break; - } - } - } - - // If we didn't specified the adapter index, or if it didn't find it - if (hMonitor == NULL) - { - POINT windowAnchorPoint; - - // Fill in anchor point. - windowAnchorPoint.x = left; - windowAnchorPoint.y = top; - - - // Get the nearest monitor to this window. - hMonitor = MonitorFromPoint(windowAnchorPoint, MONITOR_DEFAULTTONEAREST); - } - - // Get the target monitor info - memset(&monitorInfo, 0, sizeof(MONITORINFO)); - monitorInfo.cbSize = sizeof(MONITORINFO); - GetMonitorInfo(hMonitor, &monitorInfo); - - // Update window style flags. - mFullscreenWinStyle = WS_CLIPCHILDREN | WS_POPUP; - mWindowedWinStyle = WS_CLIPCHILDREN; - - if (!mHidden) - { - mFullscreenWinStyle |= WS_VISIBLE; - mWindowedWinStyle |= WS_VISIBLE; - } - - if (border == "none") - mWindowedWinStyle |= WS_POPUP; - else if (border == "fixed") - mWindowedWinStyle |= WS_OVERLAPPED | WS_BORDER | WS_CAPTION | - WS_SYSMENU | WS_MINIMIZEBOX; - else - mWindowedWinStyle |= WS_OVERLAPPEDWINDOW; - - unsigned int winWidth, winHeight; - winWidth = width; - winHeight = height; - - - // No specified top left -> Center the window in the middle of the monitor - if (left == INT_MAX || top == INT_MAX) - { - uint32 screenw = monitorInfo.rcWork.right - monitorInfo.rcWork.left; - uint32 screenh = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top; - - // clamp window dimensions to screen size - uint32 outerw = (winWidth < screenw)? winWidth : screenw; - uint32 outerh = (winHeight < screenh)? winHeight : screenh; - - if (left == INT_MAX) - left = monitorInfo.rcWork.left + (screenw - outerw) / 2; - else if (monitorIndex != -1) - left += monitorInfo.rcWork.left; - - if (top == INT_MAX) - top = monitorInfo.rcWork.top + (screenh - outerh) / 2; - else if (monitorIndex != -1) - top += monitorInfo.rcWork.top; - } - else if (monitorIndex != -1) - { - left += monitorInfo.rcWork.left; - top += monitorInfo.rcWork.top; - } - - mWidth = mDesiredWidth = width; - mHeight = mDesiredHeight = height; - mTop = top; - mLeft = left; - - if (fullScreen) - { - dwStyleEx |= WS_EX_TOPMOST; - mTop = monitorInfo.rcMonitor.top; - mLeft = monitorInfo.rcMonitor.left; - } - else - { - adjustWindow(width, height, &winWidth, &winHeight); - - if (!outerSize) - { - // Calculate window dimensions required - // to get the requested client area - SetRect(&rc, 0, 0, mWidth, mHeight); - AdjustWindowRect(&rc, getWindowStyle(fullScreen), false); - mWidth = rc.right - rc.left; - mHeight = rc.bottom - rc.top; - - // Clamp window rect to the nearest display monitor. - if (mLeft < monitorInfo.rcWork.left) - mLeft = monitorInfo.rcWork.left; - - if (mTop < monitorInfo.rcWork.top) - mTop = monitorInfo.rcWork.top; - - if (static_cast(winWidth) > monitorInfo.rcWork.right - mLeft) - winWidth = monitorInfo.rcWork.right - mLeft; - - if (static_cast(winHeight) > monitorInfo.rcWork.bottom - mTop) - winHeight = monitorInfo.rcWork.bottom - mTop; - } - } - - UINT classStyle = 0; - if (enableDoubleClick) - classStyle |= CS_DBLCLKS; - - - // Register the window class - // NB allow 4 bytes of window data for D3D9RenderWindow pointer - WNDCLASS wc = { classStyle, windowProc, 0, 0, hInst, - LoadIcon(0, IDI_APPLICATION), LoadCursor(NULL, IDC_ARROW), - (HBRUSH)GetStockObject(BLACK_BRUSH), 0, "OgreD3D9Wnd" }; - RegisterClass(&wc); - - // Create our main window - // Pass pointer to self - mIsExternal = false; - mHWnd = CreateWindowEx(dwStyleEx, "OgreD3D9Wnd", title.c_str(), getWindowStyle(fullScreen), - mLeft, mTop, winWidth, winHeight, 0, 0, hInst, this); - } - else - { - mHWnd = externalHandle; - mIsExternal = true; - } - - RECT rc; - // top and left represent outer window coordinates - GetWindowRect(mHWnd, &rc); - mTop = rc.top; - mLeft = rc.left; - // width and height represent interior drawable area - GetClientRect(mHWnd, &rc); - mWidth = rc.right; - mHeight = rc.bottom; - - mName = name; - mDepthBufferPoolId = depthBuffer ? DepthBuffer::POOL_DEFAULT : DepthBuffer::POOL_NO_DEPTH; - mDepthBuffer = 0; - mColourDepth = colourDepth; - - LogManager::getSingleton().stream() - << "D3D9 : Created D3D9 Rendering Window '" - << mName << "' : " << mWidth << "x" << mHeight - << ", " << mColourDepth << "bpp"; - - mActive = true; - mClosed = false; - setHidden(mHidden); - } - - void D3D9RenderWindow::setFullscreen(bool fullScreen, unsigned int width, unsigned int height) - { - if (fullScreen != mIsFullScreen || width != mWidth || height != mHeight) - { - if (fullScreen != mIsFullScreen) - mSwitchingFullscreen = true; - - bool oldFullscreen = mIsFullScreen; - mIsFullScreen = fullScreen; - mWidth = mDesiredWidth = width; - mHeight = mDesiredHeight = height; - - if (fullScreen) - { - // Get the nearest monitor to this window. - HMONITOR hMonitor = MonitorFromWindow(mHWnd, MONITOR_DEFAULTTONEAREST); - - // Get monitor info - MONITORINFO monitorInfo; - - memset(&monitorInfo, 0, sizeof(MONITORINFO)); - monitorInfo.cbSize = sizeof(MONITORINFO); - GetMonitorInfo(hMonitor, &monitorInfo); - - mTop = monitorInfo.rcMonitor.top; - mLeft = monitorInfo.rcMonitor.left; - - // need different ordering here - - if (oldFullscreen) - { - // was previously fullscreen, just changing the resolution - SetWindowPos(mHWnd, HWND_TOPMOST, mLeft, mTop, width, height, SWP_NOACTIVATE); - } - else - { - SetWindowPos(mHWnd, HWND_TOPMOST, mLeft, mTop, width, height, SWP_NOACTIVATE); - SetWindowLong(mHWnd, GWL_STYLE, getWindowStyle(mIsFullScreen)); - SetWindowPos(mHWnd, 0, 0,0, 0,0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); - } - } - else - { - // Calculate window dimensions required - // to get the requested client area - unsigned int winWidth, winHeight; - winWidth = mWidth; - winHeight = mHeight; - - adjustWindow(mWidth, mHeight, &winWidth, &winHeight); - - SetWindowLong(mHWnd, GWL_STYLE, getWindowStyle(mIsFullScreen)); - SetWindowPos(mHWnd, HWND_NOTOPMOST, 0, 0, winWidth, winHeight, - SWP_DRAWFRAME | SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOACTIVATE); - // Note that we also set the position in the restoreLostDevice method - // via _finishSwitchingFullScreen - - // Update the current rect. - updateWindowRect(); - } - - // Have to release & trigger device reset - // NB don't use windowMovedOrResized since Win32 doesn't know - // about the size change yet - mDevice->invalidate(this); - // Notify viewports of resize - ViewportList::iterator it = mViewportList.begin(); - while( it != mViewportList.end() ) - (*it++).second->_updateDimensions(); - } - } - - void D3D9RenderWindow::adjustWindow(unsigned int clientWidth, unsigned int clientHeight, - unsigned int* winWidth, unsigned int* winHeight) - { - // NB only call this for non full screen - RECT rc; - SetRect(&rc, 0, 0, clientWidth, clientHeight); - AdjustWindowRect(&rc, getWindowStyle(mIsFullScreen), false); - *winWidth = rc.right - rc.left; - *winHeight = rc.bottom - rc.top; - } - - void D3D9RenderWindow::_finishSwitchingFullscreen() - { - if(mIsFullScreen) - { - // Need to reset the region on the window sometimes, when the - // windowed mode was constrained by desktop - HRGN hRgn = CreateRectRgn(0,0,mWidth, mHeight); - SetWindowRgn(mHWnd, hRgn, FALSE); - } - else - { - // When switching back to windowed mode, need to reset window size - // after device has been restored - // We may have had a resize event which polluted our desired sizes - if (mWidth != mDesiredWidth || - mHeight != mDesiredHeight) - { - mWidth = mDesiredWidth; - mHeight = mDesiredHeight; - } - unsigned int winWidth, winHeight; - adjustWindow(mWidth, mHeight, &winWidth, &winHeight); - - // deal with centering when switching down to smaller resolution - HMONITOR hMonitor = MonitorFromWindow(mHWnd, MONITOR_DEFAULTTONEAREST); - MONITORINFO monitorInfo; - memset(&monitorInfo, 0, sizeof(MONITORINFO)); - monitorInfo.cbSize = sizeof(MONITORINFO); - GetMonitorInfo(hMonitor, &monitorInfo); - - ULONG screenw = monitorInfo.rcWork.right - monitorInfo.rcWork.left; - ULONG screenh = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top; - - int left = screenw > winWidth ? ((screenw - winWidth) / 2) : 0; - int top = screenh > winHeight ? ((screenh - winHeight) / 2) : 0; - SetWindowPos(mHWnd, HWND_NOTOPMOST, left, top, winWidth, winHeight, - SWP_DRAWFRAME | SWP_FRAMECHANGED | SWP_NOACTIVATE); - - updateWindowRect(); - } - mSwitchingFullscreen = false; - } - - void D3D9RenderWindow::buildPresentParameters(D3DPRESENT_PARAMETERS* presentParams) - { - // Set up the presentation parameters - IDirect3D9* pD3D = D3D9RenderSystem::getDirect3D9(); - D3DDEVTYPE devType = D3DDEVTYPE_HAL; - - if (mDevice != NULL) - devType = mDevice->getDeviceType(); - - - ZeroMemory( presentParams, sizeof(D3DPRESENT_PARAMETERS) ); - presentParams->Windowed = !mIsFullScreen; - - DWORD version = GetVersion(); - DWORD major = (DWORD) (LOBYTE(LOWORD(version))); - DWORD minor = (DWORD) (HIBYTE(LOWORD(version))); - bool isWindows7 = (major > 6) || ((major == 6) && (minor >= 1)); - - // http://msdn.microsoft.com/en-us/library/windows/desktop/bb172574%28v=vs.85%29.aspx - // Multisampling is valid only on a swap chain that is being created or reset with the D3DSWAPEFFECT_DISCARD swap effect. - bool useFlipSwap = D3D9RenderSystem::isDirectX9Ex() && isWindows7 && (isAA() == false); - - presentParams->SwapEffect = useFlipSwap ? D3DSWAPEFFECT_FLIPEX : D3DSWAPEFFECT_DISCARD; - // triple buffer if VSync is on or if flip swap is used. Otherwise we may get a performance penalty. - presentParams->BackBufferCount = mVSync || useFlipSwap ? 2 : 1; - presentParams->EnableAutoDepthStencil = (mDepthBufferPoolId != DepthBuffer::POOL_NO_DEPTH); - presentParams->hDeviceWindow = mHWnd; - presentParams->BackBufferWidth = mWidth; - presentParams->BackBufferHeight = mHeight; - presentParams->FullScreen_RefreshRateInHz = mIsFullScreen ? mDisplayFrequency : 0; - - if (presentParams->BackBufferWidth == 0) - presentParams->BackBufferWidth = 1; - - if (presentParams->BackBufferHeight == 0) - presentParams->BackBufferHeight = 1; - - - if (mVSync) - { - // D3D9 only seems to support 2-4 presentation intervals in fullscreen - if (mIsFullScreen) - { - switch(mVSyncInterval) - { - case 1: - default: - presentParams->PresentationInterval = D3DPRESENT_INTERVAL_ONE; - break; - case 2: - presentParams->PresentationInterval = D3DPRESENT_INTERVAL_TWO; - break; - case 3: - presentParams->PresentationInterval = D3DPRESENT_INTERVAL_THREE; - break; - case 4: - presentParams->PresentationInterval = D3DPRESENT_INTERVAL_FOUR; - break; - }; - // check that the interval was supported, revert to 1 to be safe otherwise - D3DCAPS9 caps; - pD3D->GetDeviceCaps(mDevice->getAdapterNumber(), devType, &caps); - if (!(caps.PresentationIntervals & presentParams->PresentationInterval)) - presentParams->PresentationInterval = D3DPRESENT_INTERVAL_ONE; - - } - else - { - presentParams->PresentationInterval = D3DPRESENT_INTERVAL_ONE; - } - - } - else - { - // NB not using vsync in windowed mode in D3D9 can cause jerking at low - // frame rates no matter what buffering modes are used (odd - perhaps a - // timer issue in D3D9 since GL doesn't suffer from this) - // low is < 200fps in this context - if (!mIsFullScreen) - { - LogManager::getSingleton().logWarning( - "D3D9: disabling VSync in windowed mode can cause timing issues at lower " - "frame rates, turn VSync on if you observe this problem."); - } - presentParams->PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; - } - - presentParams->BackBufferFormat = D3DFMT_R5G6B5; - if( mColourDepth > 16 ) - presentParams->BackBufferFormat = D3DFMT_X8R8G8B8; - - if (mColourDepth > 16 ) - { - // Try to create a 32-bit depth, 8-bit stencil - if( FAILED( pD3D->CheckDeviceFormat(mDevice->getAdapterNumber(), - devType, presentParams->BackBufferFormat, D3DUSAGE_DEPTHSTENCIL, - D3DRTYPE_SURFACE, D3DFMT_D24S8 ))) - { - // Bugger, no 8-bit hardware stencil, just try 32-bit zbuffer - if( FAILED( pD3D->CheckDeviceFormat(mDevice->getAdapterNumber(), - devType, presentParams->BackBufferFormat, D3DUSAGE_DEPTHSTENCIL, - D3DRTYPE_SURFACE, D3DFMT_D32 ))) - { - // Jeez, what a naff card. Fall back on 16-bit depth buffering - presentParams->AutoDepthStencilFormat = D3DFMT_D16; - } - else - presentParams->AutoDepthStencilFormat = D3DFMT_D32; - } - else - { - // Woohoo! - if( SUCCEEDED( pD3D->CheckDepthStencilMatch( mDevice->getAdapterNumber(), devType, - presentParams->BackBufferFormat, presentParams->BackBufferFormat, D3DFMT_D24S8 ) ) ) - { - presentParams->AutoDepthStencilFormat = D3DFMT_D24S8; - } - else - presentParams->AutoDepthStencilFormat = D3DFMT_D24X8; - } - } - else - // 16-bit depth, software stencil - presentParams->AutoDepthStencilFormat = D3DFMT_D16; - - - D3D9RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - - rsys->determineFSAASettings(mDevice->getD3D9Device(), - mFSAA, mFSAAHint, presentParams->BackBufferFormat, mIsFullScreen, - &mFSAAType, &mFSAAQuality); - - presentParams->MultiSampleType = mFSAAType; - presentParams->MultiSampleQuality = (mFSAAQuality == 0) ? 0 : mFSAAQuality; - - // Check sRGB - if (mHwGamma) - { - /* hmm, this never succeeds even when device does support?? - if(FAILED(pD3D->CheckDeviceFormat(mDriver->getAdapterNumber(), - devType, presentParams->BackBufferFormat, D3DUSAGE_QUERY_SRGBWRITE, - D3DRTYPE_SURFACE, presentParams->BackBufferFormat ))) - { - // disable - not supported - mHwGamma = false; - } - */ - - } - } - - void D3D9RenderWindow::destroy() - { - if (mDevice != NULL) - { - mDevice->detachRenderWindow(this); - mDevice = NULL; - } - - if (mHWnd && !mIsExternal) - { - DestroyWindow(mHWnd); - } - - mHWnd = 0; - mActive = false; - mClosed = true; - } - - bool D3D9RenderWindow::isActive() const - { - if (isFullScreen()) - return isVisible(); - - return mActive && isVisible(); - } - - bool D3D9RenderWindow::isVisible() const - { - HWND currentWindowHandle = mHWnd; - bool visible; - while ((visible = (IsIconic(currentWindowHandle) == false)) && - (GetWindowLong(currentWindowHandle, GWL_STYLE) & WS_CHILD) != 0) - { - currentWindowHandle = GetParent(currentWindowHandle); - } - return visible; - } - - void D3D9RenderWindow::setHidden(bool hidden) - { - mHidden = hidden; - if (!mIsExternal) - { - if (hidden) - ShowWindow(mHWnd, SW_HIDE); - else - ShowWindow(mHWnd, SW_SHOWNORMAL); - } - } - - void D3D9RenderWindow::setVSyncEnabled(bool vsync) - { - mVSync = vsync; - if (!mIsExternal) - { - // we need to reset the device with new vsync params - // invalidate the window to trigger this - mDevice->invalidate(this); - } - } - - bool D3D9RenderWindow::isVSyncEnabled() const - { - return mVSync; - } - - void D3D9RenderWindow::setVSyncInterval(unsigned int interval) - { - mVSyncInterval = interval; - if (mVSync) - setVSyncEnabled(true); - } - - void D3D9RenderWindow::reposition(int top, int left) - { - if (mHWnd && !mIsFullScreen) - { - SetWindowPos(mHWnd, 0, top, left, 0, 0, - SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); - } - } - - void D3D9RenderWindow::resize(unsigned int width, unsigned int height) - { - if (!mIsExternal) - { - if (mHWnd && !mIsFullScreen) - { - unsigned int winWidth, winHeight; - adjustWindow(width, height, &winWidth, &winHeight); - SetWindowPos(mHWnd, 0, 0, 0, winWidth, winHeight, - SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE); - } - } - else - updateWindowRect(); - } - - void D3D9RenderWindow::windowMovedOrResized() - { - if (!mHWnd || IsIconic(mHWnd)) - return; - - updateWindowRect(); - } - - void D3D9RenderWindow::swapBuffers( ) - { - if (mDeviceValid) - mDevice->present(this); - } - - void D3D9RenderWindow::getCustomAttribute( const String& name, void* pData ) - { - // Valid attributes and their equvalent native functions: - // D3DDEVICE : getD3DDevice - // WINDOW : getWindowHandle - - if( name == "D3DDEVICE" ) - { - *(IDirect3DDevice9**)pData = getD3D9Device(); - } - else if( name == "WINDOW" ) - { - *(HWND*)pData = getWindowHandle(); - } - else if( name == "isTexture" ) - { - *(bool*)pData = false; - } - else if( name == "D3DZBUFFER" ) - { - *(IDirect3DSurface9**)pData = mDevice->getDepthBuffer(this); - } - else if( name == "DDBACKBUFFER" ) - { - *(IDirect3DSurface9**)pData = mDevice->getBackBuffer(this); - } - else if( name == "DDFRONTBUFFER" ) - { - *(IDirect3DSurface9**)pData = mDevice->getBackBuffer(this); - } - } - - PixelFormat D3D9RenderWindow::suggestPixelFormat() const - { - return mColourDepth == 16 ? PF_R5G6B5 : PF_X8R8G8B8; - } - - void D3D9RenderWindow::copyContentsToMemory(const Box& src, const PixelBox &dst, FrameBuffer buffer) - { - mDevice->copyContentsToMemory(this, src, dst, buffer); - } - //----------------------------------------------------------------------------- - void D3D9RenderWindow::_beginUpdate() - { - // External windows should update per frame - // since it dosen't get the window resize/move messages. - if (mIsExternal) - { - updateWindowRect(); - } - - if (mWidth == 0 || mHeight == 0) - { - mDeviceValid = false; - return; - } - - D3D9RenderSystem::getDeviceManager()->setActiveRenderTargetDevice(mDevice); - - // Check that device can be used for rendering operations. - mDeviceValid = mDevice->validate(this); - if (mDeviceValid) - { - // Finish window / fullscreen mode switch. - if (_getSwitchingFullscreen()) - { - _finishSwitchingFullscreen(); - // have to re-validate since this may have altered dimensions - mDeviceValid = mDevice->validate(this); - } - } - - RenderWindow::_beginUpdate(); - } - //--------------------------------------------------------------------- - void D3D9RenderWindow::_updateViewport(Viewport* viewport, bool updateStatistics) - { - if (mDeviceValid) - { - RenderWindow::_updateViewport(viewport, updateStatistics); - } - } - //--------------------------------------------------------------------- - void D3D9RenderWindow::_endUpdate() - { - RenderWindow::_endUpdate(); - - D3D9RenderSystem::getDeviceManager()->setActiveRenderTargetDevice(NULL); - - } - //----------------------------------------------------------------------------- - IDirect3DDevice9* D3D9RenderWindow::getD3D9Device() - { - return mDevice->getD3D9Device(); - } - - //----------------------------------------------------------------------------- - IDirect3DSurface9* D3D9RenderWindow::getRenderSurface() - { - return mDevice->getBackBuffer(this); - } - - //----------------------------------------------------------------------------- - bool D3D9RenderWindow::_getSwitchingFullscreen() const - { - return mSwitchingFullscreen; - } - - //----------------------------------------------------------------------------- - D3D9Device* D3D9RenderWindow::getDevice() - { - return mDevice; - } - - //----------------------------------------------------------------------------- - void D3D9RenderWindow::setDevice(D3D9Device* device) - { - mDevice = device; - mDeviceValid = false; - } - - //----------------------------------------------------------------------------- - bool D3D9RenderWindow::isDepthBuffered() const - { - return (mDepthBufferPoolId != DepthBuffer::POOL_NO_DEPTH); - } - - //----------------------------------------------------------------------------- - void D3D9RenderWindow::updateWindowRect() - { - RECT rc; - BOOL result; - - // Update top left parameters - result = GetWindowRect(mHWnd, &rc); - if (result == FALSE) - { - mTop = 0; - mLeft = 0; - mWidth = 0; - mHeight = 0; - return; - } - - mTop = rc.top; - mLeft = rc.left; - - // width and height represent drawable area only - result = GetClientRect(mHWnd, &rc); - if (result == FALSE) - { - mTop = 0; - mLeft = 0; - mWidth = 0; - mHeight = 0; - return; - } - unsigned int width = rc.right - rc.left; - unsigned int height = rc.bottom - rc.top; - - // Case window resized. - if (width != mWidth || height != mHeight) - { - mWidth = rc.right - rc.left; - mHeight = rc.bottom - rc.top; - - // Notify viewports of resize - ViewportList::iterator it = mViewportList.begin(); - while( it != mViewportList.end() ) - (*it++).second->_updateDimensions(); - } - - } - //----------------------------------------------------------------------------- - void D3D9RenderWindow::updateStats( void ) - { - RenderTarget::updateStats(); - mStats.vBlankMissCount = mDevice->getVBlankMissCount(this); - } - //----------------------------------------------------------------------------- - bool D3D9RenderWindow::isNvPerfHUDEnable() const - { - return mUseNVPerfHUD; - } - //--------------------------------------------------------------------- - bool D3D9RenderWindow::_validateDevice() - { - mDeviceValid = mDevice->validate(this); - return mDeviceValid; - } - //--------------------------------------------------------------------- -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - void D3D9RenderWindow::_validateStereo() - { - mStereoEnabled = D3D9StereoDriverBridge::getSingleton().isStereoEnabled(this->getName()); - } -#endif - //--------------------------------------------------------------------- -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9Resource.cpp b/RenderSystems/Direct3D9/src/OgreD3D9Resource.cpp deleted file mode 100644 index 022b764206a..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9Resource.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9Resource.h" -#include "OgreD3D9ResourceManager.h" -#include "OgreD3D9RenderSystem.h" - -namespace Ogre -{ - OGRE_STATIC_MUTEX_INSTANCE(D3D9Resource::msDeviceAccessMutex); - - D3D9Resource::D3D9Resource() - { - D3D9RenderSystem::getResourceManager()->_notifyResourceCreated(static_cast(this)); - } - - D3D9Resource::~D3D9Resource() - { - D3D9RenderSystem::getResourceManager()->_notifyResourceDestroyed(static_cast(this)); - } - - void D3D9Resource::lockDeviceAccess() - { - D3D9_DEVICE_ACCESS_LOCK; - } - - void D3D9Resource::unlockDeviceAccess() - { - D3D9_DEVICE_ACCESS_UNLOCK; - } -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9ResourceManager.cpp b/RenderSystems/Direct3D9/src/OgreD3D9ResourceManager.cpp deleted file mode 100644 index c9db961934e..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9ResourceManager.cpp +++ /dev/null @@ -1,152 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9Resource.h" -#include "OgreD3D9ResourceManager.h" -#include "OgreD3D9HardwarePixelBuffer.h" - -namespace Ogre -{ - - //----------------------------------------------------------------------- - D3D9ResourceManager::D3D9ResourceManager() - { - mResourceCreationPolicy = RCP_CREATE_ON_ALL_DEVICES; - mDeviceAccessLockCount = 0; - } - - //----------------------------------------------------------------------- - D3D9ResourceManager::~D3D9ResourceManager() - { - - } - - //----------------------------------------------------------------------- - void D3D9ResourceManager::setCreationPolicy(D3D9ResourceCreationPolicy creationPolicy) - { - mResourceCreationPolicy = creationPolicy; - } - - //----------------------------------------------------------------------- - D3D9ResourceCreationPolicy D3D9ResourceManager::getCreationPolicy() const - { - return mResourceCreationPolicy; - } - - //----------------------------------------------------------------------- - void D3D9ResourceManager::notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device) - { - OGRE_LOCK_MUTEX(mResourcesMutex); - - ResourceContainerIterator it = mResources.begin(); - while (it != mResources.end()) - { - (*it)->notifyOnDeviceCreate(d3d9Device); - ++it; - } - } - - //----------------------------------------------------------------------- - void D3D9ResourceManager::notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device) - { - OGRE_LOCK_MUTEX(mResourcesMutex); - - ResourceContainerIterator it = mResources.begin(); - while (it != mResources.end()) - { - (*it)->notifyOnDeviceDestroy(d3d9Device); - ++it; - } - } - - //----------------------------------------------------------------------- - void D3D9ResourceManager::notifyOnDeviceLost(IDirect3DDevice9* d3d9Device) - { - OGRE_LOCK_MUTEX(mResourcesMutex); - - ResourceContainerIterator it = mResources.begin(); - while (it != mResources.end()) - { - (*it)->notifyOnDeviceLost(d3d9Device); - ++it; - } - } - - //----------------------------------------------------------------------- - void D3D9ResourceManager::notifyOnDeviceReset(IDirect3DDevice9* d3d9Device) - { - OGRE_LOCK_MUTEX(mResourcesMutex); - - ResourceContainerIterator it = mResources.begin(); - while (it != mResources.end()) - { - (*it)->notifyOnDeviceReset(d3d9Device); - ++it; - } - } - - //----------------------------------------------------------------------- - void D3D9ResourceManager::_notifyResourceCreated(D3D9Resource* pResource) - { - OGRE_LOCK_MUTEX(mResourcesMutex); - mResources.insert(pResource); - } - - //----------------------------------------------------------------------- - void D3D9ResourceManager::_notifyResourceDestroyed(D3D9Resource* pResource) - { - OGRE_LOCK_MUTEX(mResourcesMutex); - - mResources.erase(pResource); - } - - //----------------------------------------------------------------------- - void D3D9ResourceManager::lockDeviceAccess() - { - assert(mDeviceAccessLockCount >= 0); - mDeviceAccessLockCount++; - if (mDeviceAccessLockCount == 1) - { - OGRE_LOCK_RECURSIVE_MUTEX(mResourcesMutex); - D3D9Resource::lockDeviceAccess(); - D3D9HardwarePixelBuffer::lockDeviceAccess(); - } - } - - //----------------------------------------------------------------------- - void D3D9ResourceManager::unlockDeviceAccess() - { - assert(mDeviceAccessLockCount > 0); - mDeviceAccessLockCount--; - if (mDeviceAccessLockCount == 0) - { - D3D9HardwarePixelBuffer::unlockDeviceAccess(); - D3D9Resource::unlockDeviceAccess(); - OGRE_UNLOCK_RECURSIVE_MUTEX(mResourcesMutex); - } - } -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9StereoDriverAMD.cpp b/RenderSystems/Direct3D9/src/OgreD3D9StereoDriverAMD.cpp deleted file mode 100644 index ccc3fdef485..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9StereoDriverAMD.cpp +++ /dev/null @@ -1,418 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreD3D9StereoDriverAMD.h" - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 -#include "OgreRoot.h" -#include "OgreViewport.h" -#include "OgreD3D9RenderWindow.h" -#include "OgreD3D9DeviceManager.h" - -namespace Ogre -{ - //----------------------------------------------------------------------------- - D3D9StereoDriverAMD::D3D9StereoDriverAMD() - { - mStereoEnabled = false; - mLineOffset = 0; - mDevice = NULL; - mDriverComSurface = NULL; - mStereoBuffer = NULL; - mLeftBuffer = NULL; - mRightBuffer = NULL; - Root::getSingleton().getRenderSystem()->addListener(this); - } - //----------------------------------------------------------------------------- - D3D9StereoDriverAMD::~D3D9StereoDriverAMD() - { - Root::getSingleton().getRenderSystem()->removeListener(this); - releaseResources(); - } - //----------------------------------------------------------------------------- - bool D3D9StereoDriverAMD::addRenderWindow(D3D9RenderWindow* renderWindow) - { - // Add the window to the existing map - mRenderWindowMap[renderWindow->getName()] = renderWindow; - renderWindow->addListener(this); - - return false; - } - //----------------------------------------------------------------------------- - bool D3D9StereoDriverAMD::removeRenderWindow(const String& renderWindowName) - { - // Remove the window from the existing map - D3D9RenderWindow* renderWindow = mRenderWindowMap[renderWindowName]; - renderWindow->removeListener(this); - mRenderWindowMap.erase(renderWindowName); - - return false; - } - //----------------------------------------------------------------------------- - bool D3D9StereoDriverAMD::isStereoEnabled(const String& renderWindowName) - { - return mStereoEnabled; - } - //----------------------------------------------------------------------------- - bool D3D9StereoDriverAMD::setDrawBuffer(ColourBufferType colourBuffer) - { - // Note, setDrawBuffer is normally called at the beginning of rendering to the viewport - // but for this implementation, the related logic is in the postViewportUpdate() method - if (!mStereoEnabled) - return false; - - return true; - } - //----------------------------------------------------------------------------- - void D3D9StereoDriverAMD::eventOccurred(const String& eventName, const NameValuePairList* parameters) - { - if (eventName.compare("DeviceCreated") == 0) - deviceCreatedEvent(parameters); - else if (eventName.compare("DeviceLost") == 0) - deviceLostEvent(parameters); - else if (eventName.compare("AfterDeviceReset") == 0) - afterDeviceResetEvent(parameters); - else if (eventName.compare("BeforeDevicePresent") == 0) - beforeDevicePresentEvent(parameters); - } - //----------------------------------------------------------------------------- - void D3D9StereoDriverAMD::deviceCreatedEvent(const NameValuePairList* parameters) - { - NameValuePairList::const_iterator iter = parameters->find("D3DDEVICE"); - mDevice = reinterpret_cast(StringConverter::parseSizeT(iter->second)); - - // Cache the parameters and verify the settings are valid for stereo - if (!getPresentParamsAndVerifyStereoSettings()) - return; - - // Send the enable stereo command to the driver - if (!sendStereoCommand(ATI_STEREO_ENABLESTEREO, NULL, 0, 0, 0)) - { - releaseResources(); - return; - } - - // Send the enable anti-aliasing command to the driver - DWORD multiSampleAntiAlias; - mDevice->GetRenderState(D3DRS_MULTISAMPLEANTIALIAS, &multiSampleAntiAlias); - if (1 == multiSampleAntiAlias && !sendStereoCommand(ATI_STEREO_ENABLEPRIMARYAA, NULL, 0, 0, 0)) - { - releaseResources(); - return; - } - - // Get the available valid stereo display modes - ATIDX9GETDISPLAYMODES validStereoDisplayModes; - validStereoDisplayModes.dwNumModes = 0; - validStereoDisplayModes.pStereoModes = NULL; - - // Send stereo command to get the number of available stereo modes - if (!sendStereoCommand(ATI_STEREO_GETDISPLAYMODES, (BYTE*)(&validStereoDisplayModes), sizeof(ATIDX9GETDISPLAYMODES), 0, 0)) - { - releaseResources(); - return; - } - - // Store the list of available stereo modes - if (validStereoDisplayModes.dwNumModes != 0) - { - // Allocate memory to store the list of available stereo modes - validStereoDisplayModes.pStereoModes = new D3DDISPLAYMODE[validStereoDisplayModes.dwNumModes]; - - // Send stereo command to get the list of stereo modes - if (!sendStereoCommand(ATI_STEREO_GETDISPLAYMODES, (BYTE*)(&validStereoDisplayModes), sizeof(ATIDX9GETDISPLAYMODES), 0, 0)) - { - delete[] validStereoDisplayModes.pStereoModes; - releaseResources(); - return; - } - } - - // Get the display mode from the device - D3DDISPLAYMODE mode; - mDevice->GetDisplayMode(0, &mode); - - // Verify the display mode from the device matches one of the valid stereo display modes - int displayModeMatch = -1; - int i = 0; - while (displayModeMatch < 0 && i < (int)validStereoDisplayModes.dwNumModes) - { - if (validStereoDisplayModes.pStereoModes[i].Width == mode.Width && - validStereoDisplayModes.pStereoModes[i].Height == mode.Height && - validStereoDisplayModes.pStereoModes[i].Format == mode.Format && - validStereoDisplayModes.pStereoModes[i].RefreshRate == mode.RefreshRate) - displayModeMatch = i; - - i++; - } - - // Release memory used to store the list of available stereo modes - delete[] validStereoDisplayModes.pStereoModes; - - // Validate the device matches one of the stereo display modes - if (displayModeMatch < 0) - { - releaseResources(); - return; - } - - // Create the resources - afterDeviceResetEvent(parameters); - } - //----------------------------------------------------------------------------- - void D3D9StereoDriverAMD::deviceLostEvent(const NameValuePairList* parameters) - { - releaseResources(); - } - //----------------------------------------------------------------------------- - void D3D9StereoDriverAMD::afterDeviceResetEvent(const NameValuePairList* parameters) - { - NameValuePairList::const_iterator iter = parameters->find("D3DDEVICE"); - mDevice = reinterpret_cast(StringConverter::parseSizeT(iter->second)); - - // Verify fullscreen since AMD stereo only works in fullscreen - D3D9Device* ogreDevice = D3D9RenderSystem::getDeviceManager()->getDeviceFromD3D9Device(mDevice); - if (NULL == ogreDevice || !ogreDevice->isFullScreen()) - { - releaseResources(); - return; - } - - // Cache the parameters and verify the settings are valid for stereo - if (!getPresentParamsAndVerifyStereoSettings()) - return; - - // Get the line offset - if (!sendStereoCommand(ATI_STEREO_GETLINEOFFSET, (BYTE*)(&mLineOffset), sizeof(DWORD), 0, 0)) - { - releaseResources(); - return; - } - - // Verify the line offset is valid - if (0 == mLineOffset) - { - releaseResources(); - return; - } - - // Cache the back buffer as the final stereo buffer - if (FAILED(mDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &mStereoBuffer))) - { - releaseResources(); - return; - } - - // Create the left buffer - if (FAILED(mDevice->CreateRenderTarget(mSwapChainPresentParameters.BackBufferWidth, mSwapChainPresentParameters.BackBufferHeight, - mSwapChainPresentParameters.BackBufferFormat, mSwapChainPresentParameters.MultiSampleType, - mSwapChainPresentParameters.MultiSampleQuality, false, &mLeftBuffer, NULL))) - { - releaseResources(); - return; - } - - // Create the right buffer - if (FAILED(mDevice->CreateRenderTarget(mSwapChainPresentParameters.BackBufferWidth, mSwapChainPresentParameters.BackBufferHeight, - mSwapChainPresentParameters.BackBufferFormat, mSwapChainPresentParameters.MultiSampleType, - mSwapChainPresentParameters.MultiSampleQuality, false, &mRightBuffer, NULL))) - { - releaseResources(); - return; - } - - mStereoEnabled = true; - } - //----------------------------------------------------------------------------- - void D3D9StereoDriverAMD::beforeDevicePresentEvent(const NameValuePairList* parameters) - { - if (!mStereoEnabled) - return; - - // Use the stereo buffer render target - mDevice->SetRenderTarget(0, mStereoBuffer); - - // Update the quad buffer with the right render target - D3DSURFACE_DESC rightBufferDesc; - mRightBuffer->GetDesc(&rightBufferDesc); - D3DVIEWPORT9 viewPort; - viewPort.X = 0; - viewPort.Y = mLineOffset; - viewPort.Width = rightBufferDesc.Width; - viewPort.Height = rightBufferDesc.Height; - viewPort.MinZ = 0; - viewPort.MaxZ = 1; - mDevice->SetViewport(&viewPort); - - // Set the right quad buffer as the destination for StretchRect to the stereo buffer - DWORD eye = ATI_STEREO_RIGHTEYE; - sendStereoCommand(ATI_STEREO_SETDSTEYE, NULL, 0, (BYTE*)&eye, sizeof(eye)); - mDevice->StretchRect(mRightBuffer, NULL, mStereoBuffer, NULL, D3DTEXF_LINEAR); - - // Set the left buffer as the destination for StretchRect to the stereo buffer - viewPort.Y = 0; - mDevice->SetViewport(&viewPort); - eye = ATI_STEREO_LEFTEYE; - sendStereoCommand(ATI_STEREO_SETDSTEYE, NULL, 0, (BYTE*)&eye, sizeof(eye)); - mDevice->StretchRect(mLeftBuffer, NULL, mStereoBuffer, NULL, D3DTEXF_LINEAR); - } - //----------------------------------------------------------------------------- - bool D3D9StereoDriverAMD::getPresentParamsAndVerifyStereoSettings() - { - // Verify the swap chain exists - UINT numberOfSwapChains = mDevice->GetNumberOfSwapChains(); - if (numberOfSwapChains < 0) - return false; - - // Get the first swap chain - IDirect3DSwapChain9* swapChain = NULL; - if (FAILED(mDevice->GetSwapChain(0, &swapChain))) - return false; - - // Cache the swap chain presentation parameters and release the swap chain - swapChain->GetPresentParameters(&mSwapChainPresentParameters); - swapChain->Release(); - - // Check if multi sample type must be set to a value greater than 1 to enable stereo - if (D3DMULTISAMPLE_NONE == mSwapChainPresentParameters.MultiSampleType || D3DMULTISAMPLE_NONMASKABLE == mSwapChainPresentParameters.MultiSampleType) - return false; - - return true; - } - //----------------------------------------------------------------------------- - void D3D9StereoDriverAMD::postViewportUpdate(const RenderTargetViewportEvent& evt) - { - if (!mStereoEnabled) - return; - - // Set the correct destination buffer - IDirect3DSurface9* destSurface = NULL; - switch (evt.source->getDrawBuffer()) - { - case CBT_BACK: - case CBT_BACK_LEFT: - destSurface = mLeftBuffer; - break; - case CBT_BACK_RIGHT: - destSurface = mRightBuffer; - break; - } - - // Set the source rectangle - RECT sourceRect; - sourceRect.left = evt.source->getActualLeft(); - sourceRect.top = evt.source->getActualTop(); - sourceRect.right = evt.source->getActualWidth(); - sourceRect.bottom = evt.source->getActualHeight(); - - // Copy the back buffer to the appropriate buffer - mDevice->StretchRect(mStereoBuffer, &sourceRect, destSurface, &sourceRect, D3DTEXF_LINEAR); - } - //----------------------------------------------------------------------------- - bool D3D9StereoDriverAMD::sendStereoCommand(ATIDX9STEREOCOMMAND stereoCommand, BYTE* outBuffer, DWORD outBufferSize, BYTE* inBuffer, DWORD inBufferSize) - { - ATIDX9STEREOCOMMPACKET* stereoCommPacket; - D3DLOCKED_RECT lockedRect; - HRESULT stereoPacketResult; - - // If the input buffer exists, verfiy the size is non-zero - if (inBuffer && inBufferSize == 0) - return false; - - // If the output buffer exists, verfiy the size is non-zero - if (outBuffer && outBufferSize == 0) - return false; - - // If not already created, create a surface to be used to communicate with the driver - if (NULL == mDriverComSurface) - { - // Get the active device from the render system - D3D9RenderSystem* renderSystem = static_cast(Root::getSingleton().getRenderSystem()); - IDirect3DDevice9* device = renderSystem->getActiveD3D9Device(); - if (FAILED(device->CreateOffscreenPlainSurface(10, 10, (D3DFORMAT)FOURCC_AQBS, D3DPOOL_DEFAULT, &mDriverComSurface, NULL))) - return false; - } - - // Lock the surface and the driver will allocate and return a pointer to a stereo packet - if (FAILED(mDriverComSurface->LockRect(&lockedRect, 0, 0))) - return false; - - // Assign the data to the stereo packet - stereoCommPacket = static_cast(lockedRect.pBits); - stereoCommPacket->dwSignature = 'STER'; - stereoCommPacket->pResult = &stereoPacketResult; - stereoCommPacket->stereoCommand = stereoCommand; - stereoCommPacket->pOutBuffer = outBuffer; - stereoCommPacket->dwOutBufferSize = outBufferSize; - stereoCommPacket->pInBuffer = inBuffer; - stereoCommPacket->dwInBufferSize = inBufferSize; - - // After all bits have been set, unlock the surface - if (FAILED(mDriverComSurface->UnlockRect())) - return false; - - // Verify the stereo packet success - if (FAILED(stereoPacketResult)) - return false; - - return true; - } - //----------------------------------------------------------------------------- - void D3D9StereoDriverAMD::releaseResources() - { - mLineOffset = 0; - mStereoEnabled = false; - mDevice = NULL; - - if (NULL != mDriverComSurface) - { - mDriverComSurface->Release(); - mDriverComSurface = NULL; - } - - if (NULL != mStereoBuffer) - { - mStereoBuffer->Release(); - mStereoBuffer = NULL; - } - - if (NULL != mLeftBuffer) - { - mLeftBuffer->Release(); - mLeftBuffer = NULL; - } - - if (NULL != mRightBuffer) - { - mRightBuffer->Release(); - mRightBuffer = NULL; - } - } - //----------------------------------------------------------------------------- -} -#endif diff --git a/RenderSystems/Direct3D9/src/OgreD3D9StereoDriverBridge.cpp b/RenderSystems/Direct3D9/src/OgreD3D9StereoDriverBridge.cpp deleted file mode 100644 index 6f7e57e19c2..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9StereoDriverBridge.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreD3D9StereoDriverBridge.h" - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - -#include "OgreD3D9StereoDriverAMD.h" -#include "OgreD3D9StereoDriverNVIDIA.h" - -namespace Ogre -{ - //----------------------------------------------------------------------------- - D3D9StereoDriverBridge::D3D9StereoDriverBridge(StereoModeType stereoMode) - { - mPimpl = NULL; - mIsNvapiInitialized = false; - mStereoMode = stereoMode; - - if (!mStereoMode) - return; - - // Both initialize and set driver mode need to be called to determine whether NVIDIA stereo is available - NvAPI_Status nvStatus = NvAPI_Initialize(); - if (NVAPI_OK == nvStatus) - nvStatus = NvAPI_Stereo_SetDriverMode(NVAPI_STEREO_DRIVER_MODE_DIRECT); - - if (NVAPI_OK == nvStatus) - { - NvAPI_ShortString nvapiStatusMessage; - NvAPI_GetErrorMessage(nvStatus, nvapiStatusMessage); - mIsNvapiInitialized = true; - mPimpl = new D3D9StereoDriverNVIDIA(); - } - else - { - // Assume the AMD implementation, since the device must be created before verifying AMD QBS - mPimpl = new D3D9StereoDriverAMD(); - } - } - //----------------------------------------------------------------------------- - D3D9StereoDriverBridge::~D3D9StereoDriverBridge() - { - if (NULL != mPimpl) - { - delete mPimpl; - mPimpl = NULL; - } - - if (mIsNvapiInitialized) - { - NvAPI_Status nvStatus = NvAPI_Unload(); - NvAPI_ShortString nvapiStatusMessage; - NvAPI_GetErrorMessage(nvStatus, nvapiStatusMessage); - } - } - //----------------------------------------------------------------------------- - template<> D3D9StereoDriverBridge* Ogre::Singleton::msSingleton = 0; - D3D9StereoDriverBridge& D3D9StereoDriverBridge::getSingleton(void) - { - assert(msSingleton); - return (*msSingleton); - } - //----------------------------------------------------------------------------- - D3D9StereoDriverBridge* D3D9StereoDriverBridge::getSingletonPtr(void) - { - return msSingleton; - } - //----------------------------------------------------------------------------- - StereoModeType D3D9StereoDriverBridge::getStereoMode() const - { - return mStereoMode; - } - //----------------------------------------------------------------------------- - bool D3D9StereoDriverBridge::addRenderWindow(D3D9RenderWindow* renderWindow) const - { - if (NULL != mPimpl) - return mPimpl->addRenderWindow(renderWindow); - - return false; - } - //----------------------------------------------------------------------------- - bool D3D9StereoDriverBridge::removeRenderWindow(const String& name) const - { - if (NULL != mPimpl) - return mPimpl->removeRenderWindow(name); - - return false; - } - //----------------------------------------------------------------------------- - bool D3D9StereoDriverBridge::isStereoEnabled(const String& renderWindowName) const - { - if (NULL != mPimpl) - return mPimpl->isStereoEnabled(renderWindowName); - - return false; - } - //----------------------------------------------------------------------------- - bool D3D9StereoDriverBridge::setDrawBuffer(ColourBufferType colourBuffer) const - { - if (NULL != mPimpl) - return mPimpl->setDrawBuffer(colourBuffer); - - return false; - } - //----------------------------------------------------------------------------- -} -#endif - diff --git a/RenderSystems/Direct3D9/src/OgreD3D9StereoDriverNVIDIA.cpp b/RenderSystems/Direct3D9/src/OgreD3D9StereoDriverNVIDIA.cpp deleted file mode 100644 index 54602801e70..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9StereoDriverNVIDIA.cpp +++ /dev/null @@ -1,195 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreD3D9StereoDriverNVIDIA.h" - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 -#include "OgreD3D9RenderWindow.h" - -namespace Ogre -{ - //----------------------------------------------------------------------------- - D3D9StereoDriverNVIDIA::D3D9StereoDriverNVIDIA() - { - mStereoMap.clear(); - - // Assume NVAPI is already initialized by caller and enable direct mode - NvAPI_Status nvStatus = NvAPI_Stereo_SetDriverMode(NVAPI_STEREO_DRIVER_MODE_DIRECT); - if (!logErrorMessage(nvStatus)) - return; - - // If stereo is not enabled, enable it - nvStatus = NvAPI_Stereo_IsEnabled(&mStereoEnabled); - if (!logErrorMessage(nvStatus)) - { - return; - } - else if (!mStereoEnabled) - { - nvStatus = NvAPI_Stereo_Enable(); - if (!logErrorMessage(nvStatus)) - return; - } - - // Verify stereo is now enabled - if (!mStereoEnabled) - { - nvStatus = NvAPI_Stereo_IsEnabled(&mStereoEnabled); - if (!logErrorMessage(nvStatus) || !mStereoEnabled) - return; - } - - logErrorMessage(nvStatus); - } - //----------------------------------------------------------------------------- - D3D9StereoDriverNVIDIA::~D3D9StereoDriverNVIDIA() - { - StereoHandleMap::iterator i = mStereoMap.begin(); - while (i != mStereoMap.end()) - { - removeRenderWindow((*i).first); - i = mStereoMap.begin(); - } - } - //----------------------------------------------------------------------------- - bool D3D9StereoDriverNVIDIA::addRenderWindow(D3D9RenderWindow* renderWindow) - { - // Initialize the stereo handle - OgreStereoHandle stereoHandle; - stereoHandle.renderWindow = renderWindow; - stereoHandle.nvapiStereoHandle = 0; - stereoHandle.isStereoOn = 0; - - // Create a new NVAPI stereo handle and verify it is activated - NvAPI_Status nvStatus = NvAPI_Stereo_CreateHandleFromIUnknown(stereoHandle.renderWindow->getD3D9Device(), &stereoHandle.nvapiStereoHandle); - if (logErrorMessage(nvStatus)) - nvStatus = NvAPI_Stereo_IsActivated(stereoHandle.nvapiStereoHandle, &stereoHandle.isStereoOn); - - logErrorMessage(nvStatus); - - // Add the stereo handle to the existing map - mStereoMap[stereoHandle.renderWindow->getName()] = stereoHandle; - - return true; - } - //----------------------------------------------------------------------------- - bool D3D9StereoDriverNVIDIA::removeRenderWindow(const String& renderWindowName) - { - OgreStereoHandle stereoHandle = mStereoMap[renderWindowName]; - NvAPI_Status nvStatus = NvAPI_Stereo_DestroyHandle(stereoHandle.nvapiStereoHandle); - logErrorMessage(nvStatus); - mStereoMap.erase(renderWindowName); - - return true; - } - //----------------------------------------------------------------------------- - bool D3D9StereoDriverNVIDIA::isStereoEnabled(const String& renderWindowName) - { - // Verify stereo is supported - if (!mStereoEnabled) - return false; - - // If stereo was lost for the handle, re-create the handle - OgreStereoHandle stereoHandle; - stereoHandle = mStereoMap[renderWindowName]; - NvU8 isStereoOn; - NvAPI_Status nvStatus = NvAPI_Stereo_IsActivated(stereoHandle.nvapiStereoHandle, &isStereoOn); - if (NVAPI_OK != nvStatus || !isStereoOn) - { - // If stereo was lost for the window, log the error message - if (stereoHandle.isStereoOn != isStereoOn) - { - stereoHandle.isStereoOn = isStereoOn; - logErrorMessage(nvStatus); - } - - nvStatus = NvAPI_Stereo_DestroyHandle(stereoHandle.nvapiStereoHandle); - nvStatus = NvAPI_Stereo_CreateHandleFromIUnknown(stereoHandle.renderWindow->getD3D9Device(), &stereoHandle.nvapiStereoHandle); - if (NVAPI_OK != nvStatus) - return false; - } - - // Verify that stereo is activated for the handle - nvStatus = NvAPI_Stereo_IsActivated(stereoHandle.nvapiStereoHandle, &isStereoOn); - - // If stereo was enabled for the window, log the error message - if (stereoHandle.isStereoOn != isStereoOn) - { - stereoHandle.isStereoOn = isStereoOn; - logErrorMessage(nvStatus); - } - - return true; - } - //----------------------------------------------------------------------------- - bool D3D9StereoDriverNVIDIA::setDrawBuffer(ColourBufferType colourBuffer) - { - NvAPI_Status nvStatus; - - // Set the active eye for all render windows that have stereo enabled - for (StereoHandleMap::iterator i = mStereoMap.begin(); i != mStereoMap.end(); ++i) - { - if ((*i).second.renderWindow->isStereoEnabled()) - { - switch (colourBuffer) - { - case CBT_BACK: - nvStatus = NvAPI_Stereo_SetActiveEye((*i).second.nvapiStereoHandle, NVAPI_STEREO_EYE_MONO); - break; - case CBT_BACK_LEFT: - nvStatus = NvAPI_Stereo_SetActiveEye((*i).second.nvapiStereoHandle, NVAPI_STEREO_EYE_LEFT); - break; - case CBT_BACK_RIGHT: - nvStatus = NvAPI_Stereo_SetActiveEye((*i).second.nvapiStereoHandle, NVAPI_STEREO_EYE_RIGHT); - break; - default: - return false; - } - - logErrorMessage(nvStatus); - } - } - - return true; - } - //----------------------------------------------------------------------------- - bool D3D9StereoDriverNVIDIA::logErrorMessage(NvAPI_Status nvStatus) - { - if (NVAPI_OK != nvStatus) - { - NvAPI_ShortString nvapiStatusMessage; - NvAPI_GetErrorMessage(nvStatus, nvapiStatusMessage); - return false; - } - - return true; - } - //----------------------------------------------------------------------------- -} -#endif - diff --git a/RenderSystems/Direct3D9/src/OgreD3D9Texture.cpp b/RenderSystems/Direct3D9/src/OgreD3D9Texture.cpp deleted file mode 100644 index 57e04e300b8..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9Texture.cpp +++ /dev/null @@ -1,1418 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9Texture.h" -#include "OgreD3D9HardwarePixelBuffer.h" -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreBitwise.h" -#include "OgreD3D9Mappings.h" -#include "OgreD3D9RenderSystem.h" -#include "OgreD3D9TextureManager.h" -#include "OgreRoot.h" -#include "OgreD3D9Device.h" -#include "OgreD3D9DeviceManager.h" -#include "OgreD3D9ResourceManager.h" -#include "OgreD3D9DepthBuffer.h" - -#include - -namespace Ogre -{ - /****************************************************************************************/ - D3D9Texture::D3D9Texture(ResourceManager* creator, const String& name, - ResourceHandle handle, const String& group, bool isManual, - ManualResourceLoader* loader) - :Texture(creator, name, handle, group, isManual, loader), - mD3DPool(D3D9RenderSystem::isDirectX9Ex() ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED), - mDynamicTextures(false), - mHwGammaReadSupported(false), - mHwGammaWriteSupported(false), - mFSAAType(D3DMULTISAMPLE_NONE), - mFSAAQuality(0) - { - - } - /****************************************************************************************/ - D3D9Texture::~D3D9Texture() - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - // have to call this here reather than in Resource destructor - // since calling virtual methods in base destructors causes crash - unload(); - - // Free memory allocated per device. - DeviceToTextureResourcesIterator it = mMapDeviceToTextureResources.begin(); - while (it != mMapDeviceToTextureResources.end()) - { - TextureResources* textureResource = it->second; - - OGRE_DELETE_T(textureResource, TextureResources, MEMCATEGORY_RENDERSYS); - ++it; - } - mMapDeviceToTextureResources.clear(); - } - /****************************************************************************************/ - void D3D9Texture::copyToTexture(TexturePtr& target) - { - // check if this & target are the same format and type - // blitting from or to cube textures is not supported yet - if (target->getUsage() != getUsage() || - target->getTextureType() != getTextureType()) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "Src. and dest. textures must be of same type and must have the same usage !!!", - "D3D9Texture::copyToTexture" ); - } - - HRESULT hr; - D3D9Texture *other; - // get the target - other = reinterpret_cast< D3D9Texture * >( target.get() ); - // target rectangle (whole surface) - RECT dstRC = {0, 0, static_cast(other->getWidth()), static_cast(other->getHeight())}; - - DeviceToTextureResourcesIterator it = mMapDeviceToTextureResources.begin(); - while (it != mMapDeviceToTextureResources.end()) - { - TextureResources* srcTextureResource = it->second; - TextureResources* dstTextureResource = other->getTextureResources(it->first); - - - // do it plain for normal texture - if (getTextureType() == TEX_TYPE_2D && - srcTextureResource->pNormTex && - dstTextureResource->pNormTex) - { - // get our source surface - IDirect3DSurface9 *pSrcSurface = 0; - if( FAILED( hr = srcTextureResource->pNormTex->GetSurfaceLevel(0, &pSrcSurface) ) ) - { - String msg = DXGetErrorDescription(hr); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn't blit : " + msg, "D3D9Texture::copyToTexture" ); - } - - // get our target surface - IDirect3DSurface9 *pDstSurface = 0; - if( FAILED( hr = dstTextureResource->pNormTex->GetSurfaceLevel(0, &pDstSurface) ) ) - { - String msg = DXGetErrorDescription(hr); - SAFE_RELEASE(pSrcSurface); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn't blit : " + msg, "D3D9Texture::copyToTexture" ); - } - - // do the blit, it's called StretchRect in D3D9 :) - if( FAILED( hr = it->first->StretchRect( pSrcSurface, NULL, pDstSurface, &dstRC, D3DTEXF_NONE) ) ) - { - String msg = DXGetErrorDescription(hr); - SAFE_RELEASE(pSrcSurface); - SAFE_RELEASE(pDstSurface); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn't blit : " + msg, "D3D9Texture::copyToTexture" ); - } - - // release temp. surfaces - SAFE_RELEASE(pSrcSurface); - SAFE_RELEASE(pDstSurface); - } - else if (getTextureType() == TEX_TYPE_CUBE_MAP && - srcTextureResource->pCubeTex && - dstTextureResource->pCubeTex) - { - // blit to 6 cube faces - for (size_t face = 0; face < 6; face++) - { - // get our source surface - IDirect3DSurface9 *pSrcSurface = 0; - if( FAILED( hr =srcTextureResource->pCubeTex->GetCubeMapSurface((D3DCUBEMAP_FACES)face, 0, &pSrcSurface) ) ) - { - String msg = DXGetErrorDescription(hr); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn't blit : " + msg, "D3D9Texture::copyToTexture" ); - } - - // get our target surface - IDirect3DSurface9 *pDstSurface = 0; - if( FAILED( hr = dstTextureResource->pCubeTex->GetCubeMapSurface((D3DCUBEMAP_FACES)face, 0, &pDstSurface) ) ) - { - String msg = DXGetErrorDescription(hr); - SAFE_RELEASE(pSrcSurface); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn't blit : " + msg, "D3D9Texture::copyToTexture" ); - } - - // do the blit, it's called StretchRect in D3D9 :) - if( FAILED( hr = it->first->StretchRect( pSrcSurface, NULL, pDstSurface, &dstRC, D3DTEXF_NONE) ) ) - { - String msg = DXGetErrorDescription(hr); - SAFE_RELEASE(pSrcSurface); - SAFE_RELEASE(pDstSurface); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn't blit : " + msg, "D3D9Texture::copyToTexture" ); - } - - // release temp. surfaces - SAFE_RELEASE(pSrcSurface); - SAFE_RELEASE(pDstSurface); - } - } - else - { - OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, - "Copy to texture is implemented only for 2D and cube textures !!!", - "D3D9Texture::copyToTexture" ); - } - - ++it; - } - } - /****************************************************************************************/ - void D3D9Texture::loadImpl() - { - if (!mInternalResourcesCreated) - { - // NB: Need to initialise pool to some value other than D3DPOOL_DEFAULT, - // otherwise, if the texture loading failed, it might re-create as empty - // texture when device lost/restore. The actual pool will determine later. - // - // In directX9Ex this is not the case there is no managed pool and no device loss - mD3DPool = D3D9RenderSystem::isDirectX9Ex() ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED; - } - - Texture::loadImpl(); - - // with D3DUSAGE_AUTOGENMIPMAP, GetLevelCount always returns 1 for the number of levels. - // currect this after loading - if (mUsage & TU_AUTOMIPMAP) - mNumMipmaps = getMaxMipmaps(); - } - - /****************************************************************************************/ - void D3D9Texture::freeInternalResourcesImpl() - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - DeviceToTextureResourcesIterator it = mMapDeviceToTextureResources.begin(); - - while (it != mMapDeviceToTextureResources.end()) - { - TextureResources* textureResource = it->second; - - freeTextureResources(it->first, textureResource); - ++it; - } - } - - /****************************************************************************************/ - D3D9Texture::TextureResources* D3D9Texture::getTextureResources(IDirect3DDevice9* d3d9Device) - { - DeviceToTextureResourcesIterator it = mMapDeviceToTextureResources.find(d3d9Device); - - if (it == mMapDeviceToTextureResources.end()) - return NULL; - - return it->second; - } - - /****************************************************************************************/ - D3D9Texture::TextureResources* D3D9Texture::allocateTextureResources(IDirect3DDevice9* d3d9Device) - { - assert(mMapDeviceToTextureResources.find(d3d9Device) == mMapDeviceToTextureResources.end()); - - TextureResources* textureResources = OGRE_NEW_T(TextureResources, MEMCATEGORY_RENDERSYS); - - textureResources->pNormTex = NULL; - textureResources->pCubeTex = NULL; - textureResources->pVolumeTex = NULL; - textureResources->pBaseTex = NULL; - textureResources->pFSAASurface = NULL; - - mMapDeviceToTextureResources[d3d9Device] = textureResources; - - return textureResources; - } - - /****************************************************************************************/ - void D3D9Texture::createTextureResources(IDirect3DDevice9* d3d9Device) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - if (isManuallyLoaded()) - { - preLoadImpl(); - - // create the internal resources. - createInternalResourcesImpl(d3d9Device); - - // Load from manual loader - if (mLoader != NULL) - { - mLoader->loadResource(this); - } - postLoadImpl(); - } - else - { - prepareImpl(); - - preLoadImpl(); - - loadImpl(); - - postLoadImpl(); - } - } - - /****************************************************************************************/ - void D3D9Texture::freeTextureResources(IDirect3DDevice9* d3d9Device, D3D9Texture::TextureResources* textureResources) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - // Release surfaces from each mip level. - for(unsigned int i = 0; i < mSurfaceList.size(); ++i) - { - D3D9HardwarePixelBuffer* pixelBuffer = static_cast(mSurfaceList[i].get()); - - pixelBuffer->releaseSurfaces(d3d9Device); - } - - // Release the rest of the resources. - SAFE_RELEASE(textureResources->pBaseTex); - SAFE_RELEASE(textureResources->pNormTex); - SAFE_RELEASE(textureResources->pCubeTex); - SAFE_RELEASE(textureResources->pVolumeTex); - SAFE_RELEASE(textureResources->pFSAASurface); - } - - /****************************************************************************************/ - size_t D3D9Texture::calculateSize(void) const - { - size_t instanceSize = getNumFaces() * PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat); - - return instanceSize * mMapDeviceToTextureResources.size(); - } - - /****************************************************************************************/ - void D3D9Texture::determinePool() - { - if (useDefaultPool()) - { - mD3DPool = D3DPOOL_DEFAULT; - } - else - { - mD3DPool = D3DPOOL_MANAGED; - } - - } - /****************************************************************************************/ - void D3D9Texture::createInternalResourcesImpl(void) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - for (uint i = 0; i < D3D9RenderSystem::getResourceCreationDeviceCount(); ++i) - { - IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getResourceCreationDevice(i); - - createInternalResourcesImpl(d3d9Device); - } - } - - /****************************************************************************************/ - void D3D9Texture::createInternalResourcesImpl(IDirect3DDevice9* d3d9Device) - { - TextureResources* textureResources; - - // Check if resources already exist. - textureResources = getTextureResources(d3d9Device); - if (textureResources != NULL && textureResources->pBaseTex != NULL) - return; - - - // If mSrcWidth and mSrcHeight are zero, the requested extents have probably been set - // through setWidth and setHeight, which set mWidth and mHeight. Take those values. - if(mSrcWidth == 0 || mSrcHeight == 0) { - mSrcWidth = mWidth; - mSrcHeight = mHeight; - } - - if(mUsage & TU_AUTOMIPMAP && D3D9RenderSystem::isDirectX9Ex()) - { - mUsage |= TU_DYNAMIC; - } - - if(!PixelUtil::isDepth(mFormat)) - mFormat = TextureManager::getSingleton().getNativeFormat(mTextureType, mFormat, mUsage); - - // load based on tex.type - switch (getTextureType()) - { - case TEX_TYPE_1D: - case TEX_TYPE_2D: - _createNormTex(d3d9Device); - break; - case TEX_TYPE_CUBE_MAP: - _createCubeTex(d3d9Device); - break; - case TEX_TYPE_3D: - _createVolumeTex(d3d9Device); - break; - default: - unloadImpl(); - OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, "Unknown texture type", "D3D9Texture::createInternalResources" ); - } - } - - /****************************************************************************************/ - void D3D9Texture::_createNormTex(IDirect3DDevice9* d3d9Device) - { - // we must have those defined here - assert(mSrcWidth > 0 || mSrcHeight > 0); - - // determine which D3D9 pixel format we'll use - HRESULT hr; - D3DFORMAT d3dPF = D3D9Mappings::_getPF(mFormat); - - // Use D3DX to help us create the texture, this way it can adjust any relevant sizes - DWORD usage = (mUsage & TU_RENDERTARGET) ? D3DUSAGE_RENDERTARGET : 0; - UINT numMips = (mNumRequestedMipmaps == MIP_UNLIMITED) ? 0 : mNumMipmaps + 1; - // Check dynamic textures - if (mUsage & TU_DYNAMIC) - { - if (_canUseDynamicTextures(d3d9Device, usage, D3DRTYPE_TEXTURE, d3dPF)) - { - usage |= D3DUSAGE_DYNAMIC; - mDynamicTextures = true; - } - else - { - mDynamicTextures = false; - } - } - // Check sRGB support - if (mHwGamma) - { - mHwGammaReadSupported = _canUseHardwareGammaCorrection(d3d9Device, usage, D3DRTYPE_TEXTURE, d3dPF, false); - if (mUsage & TU_RENDERTARGET) - mHwGammaWriteSupported = _canUseHardwareGammaCorrection(d3d9Device, usage, D3DRTYPE_TEXTURE, d3dPF, true); - } - // Check FSAA level - if (mUsage & TU_RENDERTARGET) - { - D3D9RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - rsys->determineFSAASettings(d3d9Device, mFSAA, mFSAAHint, d3dPF, false, - &mFSAAType, &mFSAAQuality); - } - else - { - mFSAAType = D3DMULTISAMPLE_NONE; - mFSAAQuality = 0; - } - - D3D9Device* device = D3D9RenderSystem::getDeviceManager()->getDeviceFromD3D9Device(d3d9Device); - const D3DCAPS9& rkCurCaps = device->getD3D9DeviceCaps(); - - - // check if mip maps are supported on hardware - mMipmapsHardwareGenerated = false; - if (rkCurCaps.TextureCaps & D3DPTEXTURECAPS_MIPMAP) - { - if (mUsage & TU_AUTOMIPMAP && mNumMipmaps != 0) - { - // use auto.gen. if available, and if desired - mMipmapsHardwareGenerated = _canAutoGenMipmaps(d3d9Device, usage, D3DRTYPE_TEXTURE, d3dPF); - if (mMipmapsHardwareGenerated) - { - usage |= D3DUSAGE_AUTOGENMIPMAP; - numMips = 0; - } - } - } - else - { - // no mip map support for this kind of textures :( - mNumMipmaps = 0; - numMips = 1; - } - - // derive the pool to use - determinePool(); - - TextureResources* textureResources; - - // Get or create new texture resources structure. - textureResources = getTextureResources(d3d9Device); - if (textureResources != NULL) - freeTextureResources(d3d9Device, textureResources); - else - textureResources = allocateTextureResources(d3d9Device); - - if(PixelUtil::isDepth(mFormat)) - { - usage = D3DUSAGE_DEPTHSTENCIL; - mD3DPool = D3DPOOL_DEFAULT; - // we cannot resolve depth on D3D9 - mFSAAType = D3DMULTISAMPLE_NONE; - mFSAA = 0; - } - - // create the texture - hr = d3d9Device->CreateTexture( - static_cast(mSrcWidth), // width - static_cast(mSrcHeight), // height - numMips, // number of mip map levels - usage, // usage - d3dPF, // pixel format - mD3DPool, - &textureResources->pNormTex, NULL); - // check result and except if failed - if (FAILED(hr)) - { - unloadImpl(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error creating texture: " + String(DXGetErrorDescription(hr)), - "D3D9Texture::_createNormTex" ); - } - - // set the base texture we'll use in the render system - hr = textureResources->pNormTex->QueryInterface(IID_IDirect3DBaseTexture9, (void **)&textureResources->pBaseTex); - if (FAILED(hr)) - { - unloadImpl(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Can't get base texture: " + String(DXGetErrorDescription(hr)), - "D3D9Texture::_createNormTex" ); - } - - // set final tex. attributes from tex. description - // they may differ from the source image !!! - D3DSURFACE_DESC desc; - hr = textureResources->pNormTex->GetLevelDesc(0, &desc); - if (FAILED(hr)) - { - unloadImpl(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Can't get texture description: " + String(DXGetErrorDescription(hr)), - "D3D9Texture::_createNormTex" ); - } - - if (mFSAAType) - { - // create AA surface - HRESULT hr = d3d9Device->CreateRenderTarget(desc.Width, desc.Height, d3dPF, - mFSAAType, - mFSAAQuality, - FALSE, // not lockable - &textureResources->pFSAASurface, NULL); - - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Unable to create AA render target: " + String(DXGetErrorDescription(hr)), - "D3D9Texture::_createNormTex"); - } - - } - - _setFinalAttributes(d3d9Device, textureResources, - desc.Width, desc.Height, 1, D3D9Mappings::_getPF(desc.Format)); - - // Set best filter type - if(mMipmapsHardwareGenerated) - { - hr = textureResources->pBaseTex->SetAutoGenFilterType(_getBestFilterMethod(d3d9Device)); - if(FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Could not set best autogen filter type: " + String(DXGetErrorDescription(hr)), - "D3D9Texture::_createNormTex" ); - } - } - - } - /****************************************************************************************/ - void D3D9Texture::_createCubeTex(IDirect3DDevice9* d3d9Device) - { - // we must have those defined here - assert(mSrcWidth > 0 || mSrcHeight > 0); - - // determine which D3D9 pixel format we'll use - HRESULT hr; - D3DFORMAT d3dPF = D3D9Mappings::_getPF(mFormat); - - // Use D3DX to help us create the texture, this way it can adjust any relevant sizes - DWORD usage = (mUsage & TU_RENDERTARGET) ? D3DUSAGE_RENDERTARGET : 0; - UINT numMips = (mNumRequestedMipmaps == MIP_UNLIMITED) ? 0 : mNumMipmaps + 1; - // Check dynamic textures - if (mUsage & TU_DYNAMIC) - { - if (_canUseDynamicTextures(d3d9Device, usage, D3DRTYPE_CUBETEXTURE, d3dPF)) - { - usage |= D3DUSAGE_DYNAMIC; - mDynamicTextures = true; - } - else - { - mDynamicTextures = false; - } - } - // Check sRGB support - if (mHwGamma) - { - mHwGammaReadSupported = _canUseHardwareGammaCorrection(d3d9Device, usage, D3DRTYPE_CUBETEXTURE, d3dPF, false); - if (mUsage & TU_RENDERTARGET) - mHwGammaWriteSupported = _canUseHardwareGammaCorrection(d3d9Device, usage, D3DRTYPE_CUBETEXTURE, d3dPF, true); - } - // Check FSAA level - if (mUsage & TU_RENDERTARGET) - { - D3D9RenderSystem* rsys = static_cast(Root::getSingleton().getRenderSystem()); - rsys->determineFSAASettings(d3d9Device, mFSAA, mFSAAHint, d3dPF, false, - &mFSAAType, &mFSAAQuality); - } - else - { - mFSAAType = D3DMULTISAMPLE_NONE; - mFSAAQuality = 0; - } - - D3D9Device* device = D3D9RenderSystem::getDeviceManager()->getDeviceFromD3D9Device(d3d9Device); - const D3DCAPS9& rkCurCaps = device->getD3D9DeviceCaps(); - - // check if mip map cube textures are supported - mMipmapsHardwareGenerated = false; - if (rkCurCaps.TextureCaps & D3DPTEXTURECAPS_MIPCUBEMAP) - { - if (mUsage & TU_AUTOMIPMAP && mNumMipmaps != 0) - { - // use auto.gen. if available - mMipmapsHardwareGenerated = _canAutoGenMipmaps(d3d9Device, usage, D3DRTYPE_CUBETEXTURE, d3dPF); - if (mMipmapsHardwareGenerated) - { - usage |= D3DUSAGE_AUTOGENMIPMAP; - } - } - } - else - { - // no mip map support for this kind of textures :( - mNumMipmaps = 0; - numMips = 1; - } - - // derive the pool to use - determinePool(); - TextureResources* textureResources; - - // Get or create new texture resources structure. - textureResources = getTextureResources(d3d9Device); - if (textureResources != NULL) - freeTextureResources(d3d9Device, textureResources); - else - textureResources = allocateTextureResources(d3d9Device); - - - // create the texture - hr = d3d9Device->CreateCubeTexture( - static_cast(mSrcWidth), // dimension - numMips, // number of mip map levels - usage, // usage - d3dPF, // pixel format - mD3DPool, - &textureResources->pCubeTex, NULL); - // check result and except if failed - if (FAILED(hr)) - { - unloadImpl(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error creating texture: " + String(DXGetErrorDescription(hr)), - "D3D9Texture::_createCubeTex" ); - } - - // set the base texture we'll use in the render system - hr = textureResources->pCubeTex->QueryInterface(IID_IDirect3DBaseTexture9, (void **)&textureResources->pBaseTex); - if (FAILED(hr)) - { - unloadImpl(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Can't get base texture: " + String(DXGetErrorDescription(hr)), - "D3D9Texture::_createCubeTex" ); - } - - // set final tex. attributes from tex. description - // they may differ from the source image !!! - D3DSURFACE_DESC desc; - hr = textureResources->pCubeTex->GetLevelDesc(0, &desc); - if (FAILED(hr)) - { - unloadImpl(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Can't get texture description: " + String(DXGetErrorDescription(hr)), - "D3D9Texture::_createCubeTex" ); - } - - if (mFSAAType) - { - // create AA surface - HRESULT hr = d3d9Device->CreateRenderTarget(desc.Width, desc.Height, d3dPF, - mFSAAType, - mFSAAQuality, - FALSE, // not lockable - &textureResources->pFSAASurface, NULL); - - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Unable to create AA render target: " + String(DXGetErrorDescription(hr)), - "D3D9Texture::_createCubeTex"); - } - } - - _setFinalAttributes(d3d9Device, textureResources, - desc.Width, desc.Height, 1, D3D9Mappings::_getPF(desc.Format)); - - // Set best filter type - if(mMipmapsHardwareGenerated) - { - hr = textureResources->pBaseTex->SetAutoGenFilterType(_getBestFilterMethod(d3d9Device)); - if(FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Could not set best autogen filter type: " + String(DXGetErrorDescription(hr)), - "D3D9Texture::_createCubeTex" ); - } - } - - } - /****************************************************************************************/ - void D3D9Texture::_createVolumeTex(IDirect3DDevice9* d3d9Device) - { - // we must have those defined here - assert(mWidth > 0 && mHeight > 0 && mDepth>0); - - if (mUsage & TU_RENDERTARGET) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "D3D9 Volume texture can not be created as render target !!", - "D3D9Texture::_createVolumeTex" ); - } - - // determine which D3D9 pixel format we'll use - HRESULT hr; - D3DFORMAT d3dPF = D3D9Mappings::_getPF(mFormat); - - // Use D3DX to help us create the texture, this way it can adjust any relevant sizes - DWORD usage = (mUsage & TU_RENDERTARGET) ? D3DUSAGE_RENDERTARGET : 0; - UINT numMips = (mNumRequestedMipmaps == MIP_UNLIMITED) ? 0 : mNumMipmaps + 1; - // Check dynamic textures - if (mUsage & TU_DYNAMIC) - { - if (_canUseDynamicTextures(d3d9Device, usage, D3DRTYPE_VOLUMETEXTURE, d3dPF)) - { - usage |= D3DUSAGE_DYNAMIC; - mDynamicTextures = true; - } - else - { - mDynamicTextures = false; - } - } - // Check sRGB support - if (mHwGamma) - { - mHwGammaReadSupported = _canUseHardwareGammaCorrection(d3d9Device, usage, D3DRTYPE_VOLUMETEXTURE, d3dPF, false); - if (mUsage & TU_RENDERTARGET) - mHwGammaWriteSupported = _canUseHardwareGammaCorrection(d3d9Device, usage, D3DRTYPE_VOLUMETEXTURE, d3dPF, true); - } - - D3D9Device* device = D3D9RenderSystem::getDeviceManager()->getDeviceFromD3D9Device(d3d9Device); - const D3DCAPS9& rkCurCaps = device->getD3D9DeviceCaps(); - - - // check if mip map volume textures are supported - mMipmapsHardwareGenerated = false; - if (rkCurCaps.TextureCaps & D3DPTEXTURECAPS_MIPVOLUMEMAP) - { - if (mUsage & TU_AUTOMIPMAP && mNumMipmaps != 0) - { - // use auto.gen. if available - mMipmapsHardwareGenerated = _canAutoGenMipmaps(d3d9Device, usage, D3DRTYPE_VOLUMETEXTURE, d3dPF); - if (mMipmapsHardwareGenerated) - { - usage |= D3DUSAGE_AUTOGENMIPMAP; - numMips = 0; - } - } - } - else - { - // no mip map support for this kind of textures :( - mNumMipmaps = 0; - numMips = 1; - } - - // derive the pool to use - determinePool(); - TextureResources* textureResources; - - // Get or create new texture resources structure. - textureResources = getTextureResources(d3d9Device); - if (textureResources != NULL) - freeTextureResources(d3d9Device, textureResources); - else - textureResources = allocateTextureResources(d3d9Device); - - - // create the texture - hr = d3d9Device->CreateVolumeTexture( - static_cast(mWidth), // dimension - static_cast(mHeight), - static_cast(mDepth), - numMips, // number of mip map levels - usage, // usage - d3dPF, // pixel format - mD3DPool, - &textureResources->pVolumeTex, NULL); - // check result and except if failed - if (FAILED(hr)) - { - unloadImpl(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Error creating texture: " + String(DXGetErrorDescription(hr)), - "D3D9Texture::_createVolumeTex" ); - } - - // set the base texture we'll use in the render system - hr = textureResources->pVolumeTex->QueryInterface(IID_IDirect3DBaseTexture9, (void **)&textureResources->pBaseTex); - if (FAILED(hr)) - { - unloadImpl(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Can't get base texture: " + String(DXGetErrorDescription(hr)), - "D3D9Texture::_createVolumeTex" ); - } - - // set final tex. attributes from tex. description - // they may differ from the source image !!! - D3DVOLUME_DESC desc; - hr = textureResources->pVolumeTex->GetLevelDesc(0, &desc); - if (FAILED(hr)) - { - unloadImpl(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Can't get texture description: " + String(DXGetErrorDescription(hr)), - "D3D9Texture::_createVolumeTex" ); - } - _setFinalAttributes(d3d9Device, textureResources, - desc.Width, desc.Height, desc.Depth, D3D9Mappings::_getPF(desc.Format)); - - // Set best filter type - if(mMipmapsHardwareGenerated) - { - hr = textureResources->pBaseTex->SetAutoGenFilterType(_getBestFilterMethod(d3d9Device)); - if(FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Could not set best autogen filter type: " + String(DXGetErrorDescription(hr)), - "D3D9Texture::_createCubeTex" ); - } - } - } - - /****************************************************************************************/ - void D3D9Texture::_setFinalAttributes(IDirect3DDevice9* d3d9Device, - TextureResources* textureResources, - unsigned long width, unsigned long height, - unsigned long depth, PixelFormat format) - { - // set target texture attributes - mHeight = height; - mWidth = width; - mDepth = depth; - mFormat = format; - - // Update size (the final size, including temp space because in consumed memory) - // this is needed in Resource class - mSize = calculateSize(); - - // say to the world what we are doing - if (mWidth != mSrcWidth || - mHeight != mSrcHeight) - { - LogManager::getSingleton().logMessage("D3D9 : ***** Dimensions altered by the render system"); - LogManager::getSingleton().logMessage("D3D9 : ***** Source image dimensions : " + StringConverter::toString(mSrcWidth) + "x" + StringConverter::toString(mSrcHeight)); - LogManager::getSingleton().logMessage("D3D9 : ***** Texture dimensions : " + StringConverter::toString(mWidth) + "x" + StringConverter::toString(mHeight)); - } - - // Create list of subsurfaces for getBuffer() - _createSurfaceList(d3d9Device, textureResources); - } - /****************************************************************************************/ - D3DTEXTUREFILTERTYPE D3D9Texture::_getBestFilterMethod(IDirect3DDevice9* d3d9Device) - { - D3D9Device* device = D3D9RenderSystem::getDeviceManager()->getDeviceFromD3D9Device(d3d9Device); - const D3DCAPS9& rkCurCaps = device->getD3D9DeviceCaps(); - - - DWORD filterCaps = 0; - // Minification filter is used for mipmap generation - // Pick the best one supported for this tex type - switch (getTextureType()) - { - case TEX_TYPE_1D: // Same as 2D - case TEX_TYPE_2D: filterCaps = rkCurCaps.TextureFilterCaps; break; - case TEX_TYPE_3D: filterCaps = rkCurCaps.VolumeTextureFilterCaps; break; - case TEX_TYPE_CUBE_MAP: filterCaps = rkCurCaps.CubeTextureFilterCaps; break; - } - if(filterCaps & D3DPTFILTERCAPS_MINFGAUSSIANQUAD) - return D3DTEXF_GAUSSIANQUAD; - - if(filterCaps & D3DPTFILTERCAPS_MINFPYRAMIDALQUAD) - return D3DTEXF_PYRAMIDALQUAD; - - if(filterCaps & D3DPTFILTERCAPS_MINFANISOTROPIC) - return D3DTEXF_ANISOTROPIC; - - if(filterCaps & D3DPTFILTERCAPS_MINFLINEAR) - return D3DTEXF_LINEAR; - - if(filterCaps & D3DPTFILTERCAPS_MINFPOINT) - return D3DTEXF_POINT; - - return D3DTEXF_POINT; - } - /****************************************************************************************/ - bool D3D9Texture::_canUseDynamicTextures(IDirect3DDevice9* d3d9Device, - DWORD srcUsage, - D3DRESOURCETYPE srcType, - D3DFORMAT srcFormat) - { - HRESULT hr; - IDirect3D9* pD3D = NULL; - - hr = d3d9Device->GetDirect3D(&pD3D); - if (FAILED(hr)) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "GetDirect3D failed !!!", - "D3D9Texture::_canUseDynamicTextures" ); - } - if (pD3D != NULL) - pD3D->Release(); - - D3D9Device* device = D3D9RenderSystem::getDeviceManager()->getDeviceFromD3D9Device(d3d9Device); - const D3DCAPS9& rkCurCaps = device->getD3D9DeviceCaps(); - D3DFORMAT eBackBufferFormat = device->getBackBufferFormat(); - - - // Check for dynamic texture support - - // check for auto gen. mip maps support - hr = pD3D->CheckDeviceFormat( - rkCurCaps.AdapterOrdinal, - rkCurCaps.DeviceType, - eBackBufferFormat, - srcUsage | D3DUSAGE_DYNAMIC, - srcType, - srcFormat); - - if (hr == D3D_OK) - return true; - else - return false; - } - /****************************************************************************************/ - bool D3D9Texture::_canUseHardwareGammaCorrection(IDirect3DDevice9* d3d9Device, - DWORD srcUsage, - D3DRESOURCETYPE srcType, D3DFORMAT srcFormat, bool forwriting) - { - HRESULT hr; - IDirect3D9* pD3D = NULL; - - hr = d3d9Device->GetDirect3D(&pD3D); - if (FAILED(hr)) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "GetDirect3D failed !!!", - "D3D9Texture::_canUseDynamicTextures" ); - } - if (pD3D != NULL) - pD3D->Release(); - - D3D9Device* device = D3D9RenderSystem::getDeviceManager()->getDeviceFromD3D9Device(d3d9Device); - const D3DCAPS9& rkCurCaps = device->getD3D9DeviceCaps(); - D3DFORMAT eBackBufferFormat = device->getBackBufferFormat(); - - - // Always check 'read' capability here - // We will check 'write' capability only in the context of a render target - if (forwriting) - srcUsage |= D3DUSAGE_QUERY_SRGBWRITE; - else - srcUsage |= D3DUSAGE_QUERY_SRGBREAD; - - // Check for sRGB support - // check for auto gen. mip maps support - hr = pD3D->CheckDeviceFormat( - rkCurCaps.AdapterOrdinal, - rkCurCaps.DeviceType, - eBackBufferFormat, - srcUsage, - srcType, - srcFormat); - if (hr == D3D_OK) - return true; - else - return false; - - } - /****************************************************************************************/ - bool D3D9Texture::_canAutoGenMipmaps(IDirect3DDevice9* d3d9Device, - DWORD srcUsage, D3DRESOURCETYPE srcType, D3DFORMAT srcFormat) - { - HRESULT hr; - IDirect3D9* pD3D = NULL; - - hr = d3d9Device->GetDirect3D(&pD3D); - if (FAILED(hr)) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "GetDirect3D failed !!!", - "D3D9Texture::_canUseDynamicTextures" ); - } - if (pD3D != NULL) - pD3D->Release(); - - D3D9Device* device = D3D9RenderSystem::getDeviceManager()->getDeviceFromD3D9Device(d3d9Device); - const D3DCAPS9& rkCurCaps = device->getD3D9DeviceCaps(); - D3DFORMAT eBackBufferFormat = device->getBackBufferFormat(); - - if ((rkCurCaps.Caps2 & D3DCAPS2_CANAUTOGENMIPMAP) == 0) - return false; - - // check for auto gen. mip maps support - hr = pD3D->CheckDeviceFormat( - rkCurCaps.AdapterOrdinal, - rkCurCaps.DeviceType, - eBackBufferFormat, - srcUsage | D3DUSAGE_AUTOGENMIPMAP, - srcType, - srcFormat); - // this HR could a SUCCES - // but mip maps will not be generated - return hr == D3D_OK; - } - /****************************************************************************************/ - // Macro to hide ugly cast - #define GETLEVEL(face,mip) \ - static_cast(mSurfaceList[face*(mNumMipmaps+1)+mip].get()) - void D3D9Texture::_createSurfaceList(IDirect3DDevice9* d3d9Device, TextureResources* textureResources) - { - IDirect3DSurface9 *surface; - IDirect3DVolume9 *volume; - D3D9HardwarePixelBuffer *buffer; - size_t mip, face; - - - assert(textureResources != NULL); - assert(textureResources->pBaseTex); - // Make sure number of mips is right - mNumMipmaps = static_cast(textureResources->pBaseTex->GetLevelCount() - 1); - // Need to know static / dynamic - unsigned int bufusage; - if ((mUsage & TU_DYNAMIC) && mDynamicTextures) - { - bufusage = HardwareBuffer::HBU_DYNAMIC; - } - else - { - bufusage = HardwareBuffer::HBU_STATIC; - } - if (mUsage & TU_RENDERTARGET) - { - bufusage |= TU_RENDERTARGET; - } - - uint surfaceCount = static_cast((getNumFaces() * (mNumMipmaps + 1))); - bool updateOldList = mSurfaceList.size() == surfaceCount; - if(!updateOldList) - { - // Create new list of surfaces - mSurfaceList.clear(); - for(size_t face=0; facepNormTex); - // For all mipmaps, store surfaces as HardwarePixelBufferSharedPtr - for(mip=0; mip<=mNumMipmaps; ++mip) - { - if(textureResources->pNormTex->GetSurfaceLevel(static_cast(mip), &surface) != D3D_OK) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Get surface level failed", - "D3D9Texture::_createSurfaceList"); - - D3D9HardwarePixelBuffer* currPixelBuffer = GETLEVEL(0, mip); - - if (mip == 0 && mNumMipmaps != 0 && (mUsage & TU_AUTOMIPMAP)) - currPixelBuffer->_setMipmapping(true, mMipmapsHardwareGenerated); - - currPixelBuffer->bind(d3d9Device, surface, textureResources->pFSAASurface, - mHwGammaWriteSupported, mFSAA, mName, textureResources->pBaseTex); - - // decrement reference count, the GetSurfaceLevel call increments this - // this is safe because the pixel buffer keeps a reference as well - surface->Release(); - } - - break; - case TEX_TYPE_CUBE_MAP: - assert(textureResources->pCubeTex); - // For all faces and mipmaps, store surfaces as HardwarePixelBufferSharedPtr - for(face=0; face<6; ++face) - { - for(mip=0; mip<=mNumMipmaps; ++mip) - { - if(textureResources->pCubeTex->GetCubeMapSurface((D3DCUBEMAP_FACES)face, static_cast(mip), &surface) != D3D_OK) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Get cubemap surface failed", - "D3D9Texture::getBuffer"); - - D3D9HardwarePixelBuffer* currPixelBuffer = GETLEVEL(face, mip); - - - if (mip == 0 && mNumMipmaps != 0 && (mUsage & TU_AUTOMIPMAP) && face == 5) - currPixelBuffer->_setMipmapping(true, mMipmapsHardwareGenerated); - - currPixelBuffer->bind(d3d9Device, surface, textureResources->pFSAASurface, - mHwGammaWriteSupported, mFSAA, mName, textureResources->pBaseTex); - - // decrement reference count, the GetSurfaceLevel call increments this - // this is safe because the pixel buffer keeps a reference as well - surface->Release(); - } - } - break; - case TEX_TYPE_3D: - assert(textureResources->pVolumeTex); - // For all mipmaps, store surfaces as HardwarePixelBufferSharedPtr - for(mip=0; mip<=mNumMipmaps; ++mip) - { - if(textureResources->pVolumeTex->GetVolumeLevel(static_cast(mip), &volume) != D3D_OK) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Get volume level failed", - "D3D9Texture::getBuffer"); - - D3D9HardwarePixelBuffer* currPixelBuffer = GETLEVEL(0, mip); - - currPixelBuffer->bind(d3d9Device, volume, textureResources->pBaseTex); - - if (mip == 0 && mNumMipmaps != 0 && (mUsage & TU_AUTOMIPMAP)) - currPixelBuffer->_setMipmapping(true, mMipmapsHardwareGenerated); - - // decrement reference count, the GetSurfaceLevel call increments this - // this is safe because the pixel buffer keeps a reference as well - volume->Release(); - } - break; - }; - } - #undef GETLEVEL - /****************************************************************************************/ - const HardwarePixelBufferSharedPtr& D3D9Texture::getBuffer(size_t face, size_t mipmap) - { - IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getActiveD3D9Device(); - TextureResources* textureResources = getTextureResources(d3d9Device); - if ((!textureResources || !textureResources->pBaseTex) && isLoaded()) - { - // FIXME - // createTextureResources(d3d9Device); - // createTextureResources calls getBuffer again causing a stackoverflow - // prefer an empty texture to crashing for now - // to fix this we should probably use the notify mechanism instead of - // recrating the texture in here.. - createInternalResourcesImpl(d3d9Device); - textureResources = getTextureResources(d3d9Device); - } - assert(textureResources != NULL); - - return Texture::getBuffer(face, mipmap); - } - //--------------------------------------------------------------------- - bool D3D9Texture::useDefaultPool() - { - // Determine D3D pool to use - // Use managed unless we're a render target or user has asked for - // a dynamic texture, and device supports D3DUSAGE_DYNAMIC (because default pool - // resources without the dynamic flag are not lockable) - // or use if we are using directX9Ex as there is no managed pool under it. - return (D3D9RenderSystem::isDirectX9Ex()) || (mUsage & TU_RENDERTARGET) || ((mUsage & TU_DYNAMIC) && mDynamicTextures); - } - - //--------------------------------------------------------------------- - void D3D9Texture::notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - if (D3D9RenderSystem::getResourceManager()->getCreationPolicy() == RCP_CREATE_ON_ALL_DEVICES) - { - try - { - createTextureResources(d3d9Device); - } - catch (...) - { - mLoadingState.store(LOADSTATE_UNLOADED); - LogManager::getSingleton().stream(LML_WARNING) - << "Warning: Failed to restore texture " << getName() << " on DeviceCreate."; - } - } - } - - //--------------------------------------------------------------------- - void D3D9Texture::notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - DeviceToTextureResourcesIterator it = mMapDeviceToTextureResources.find(d3d9Device); - - if (it != mMapDeviceToTextureResources.end()) - { - StringStream ss; - - ss << "D3D9 device: 0x[" << d3d9Device << "] destroy. Releasing D3D9 texture: " << mName; - LogManager::getSingleton().logMessage(ss.str()); - - TextureResources* textureResource = it->second; - - // Destroy surfaces from each mip level. - for(unsigned int i = 0; i < mSurfaceList.size(); ++i) - { - D3D9HardwarePixelBuffer* pixelBuffer = static_cast(mSurfaceList[i].get()); - - pixelBuffer->destroyBufferResources(d3d9Device); - } - - // Just free any internal resources, don't call unload() here - // because we want the un-touched resource to keep its unloaded status - // after device reset. - freeTextureResources(d3d9Device, textureResource); - - OGRE_DELETE_T(textureResource, TextureResources, MEMCATEGORY_RENDERSYS); - - mMapDeviceToTextureResources.erase(it); - - LogManager::getSingleton().logMessage("Released D3D9 texture: " + mName); - } - } - - //--------------------------------------------------------------------- - void D3D9Texture::notifyOnDeviceLost(IDirect3DDevice9* d3d9Device) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - if(mD3DPool == D3DPOOL_DEFAULT) - { - DeviceToTextureResourcesIterator it = mMapDeviceToTextureResources.find(d3d9Device); - - if (it != mMapDeviceToTextureResources.end()) - { - StringStream ss; - - ss << "D3D9 device: 0x[" << d3d9Device << "] lost. Releasing D3D9 texture: " << mName; - LogManager::getSingleton().logMessage(ss.str()); - - TextureResources* textureResource = it->second; - - // Just free any internal resources, don't call unload() here - // because we want the un-touched resource to keep its unloaded status - // after device reset. - freeTextureResources(d3d9Device, textureResource); - - LogManager::getSingleton().logMessage("Released D3D9 texture: " + mName); - } - } - } - - //--------------------------------------------------------------------- - void D3D9Texture::notifyOnDeviceReset(IDirect3DDevice9* d3d9Device) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - if(mD3DPool == D3DPOOL_DEFAULT) - { - createTextureResources(d3d9Device); - } - } - - //--------------------------------------------------------------------- - IDirect3DBaseTexture9* D3D9Texture::getTexture() - { - TextureResources* textureResources; - IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getActiveD3D9Device(); - - textureResources = getTextureResources(d3d9Device); - if (textureResources == NULL || textureResources->pBaseTex == NULL) - { - createTextureResources(d3d9Device); - textureResources = getTextureResources(d3d9Device); - } - assert(textureResources); - assert(textureResources->pBaseTex); - - return textureResources->pBaseTex; - } - - //--------------------------------------------------------------------- - IDirect3DTexture9* D3D9Texture::getNormTexture() - { - TextureResources* textureResources; - IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getActiveD3D9Device(); - - textureResources = getTextureResources(d3d9Device); - if (textureResources == NULL || textureResources->pNormTex == NULL) - { - createTextureResources(d3d9Device); - textureResources = getTextureResources(d3d9Device); - } - assert(textureResources); - assert(textureResources->pNormTex); - - return textureResources->pNormTex; - } - - //--------------------------------------------------------------------- - IDirect3DCubeTexture9* D3D9Texture::getCubeTexture() - { - TextureResources* textureResources; - IDirect3DDevice9* d3d9Device = D3D9RenderSystem::getActiveD3D9Device(); - - textureResources = getTextureResources(d3d9Device); - if (textureResources == NULL || textureResources->pCubeTex) - { - createTextureResources(d3d9Device); - textureResources = getTextureResources(d3d9Device); - } - assert(textureResources); - assert(textureResources->pCubeTex); - - return textureResources->pCubeTex; - } - - /****************************************************************************************/ - D3D9RenderTexture::D3D9RenderTexture(const String &name, - D3D9HardwarePixelBuffer *buffer, - bool writeGamma, - uint fsaa) : RenderTexture(buffer, 0) - { - mName = name; - mHwGamma = writeGamma; - mFSAA = fsaa; - } - //--------------------------------------------------------------------- - void D3D9RenderTexture::update(bool swap) - { - D3D9DeviceManager* deviceManager = D3D9RenderSystem::getDeviceManager(); - D3D9Device* currRenderWindowDevice = deviceManager->getActiveRenderTargetDevice(); - - if (currRenderWindowDevice != NULL) - { - if (currRenderWindowDevice->isDeviceLost() == false) - RenderTexture::update(swap); - } - else - { - for (UINT i=0; i < deviceManager->getDeviceCount(); ++i) - { - D3D9Device* device = deviceManager->getDevice(i); - - if (device->isDeviceLost() == false) - { - deviceManager->setActiveRenderTargetDevice(device); - RenderTexture::update(swap); - deviceManager->setActiveRenderTargetDevice(NULL); - } - } - } - } - //--------------------------------------------------------------------- - void D3D9RenderTexture::getCustomAttribute( const String& name, void *pData ) - { - if(name == "DDBACKBUFFER") - { - auto device = D3D9RenderSystem::getActiveD3D9Device(); - auto d3dBuffer = static_cast(mBuffer); - - if(PixelUtil::isDepth(mBuffer->getFormat())) - { - *static_cast(pData) = d3dBuffer->getNullSurface(device); - return; - } - - if (mFSAA > 0) - { - // rendering to AA surface - *(IDirect3DSurface9**)pData = d3dBuffer->getFSAASurface(device); - } - else - { - *(IDirect3DSurface9**)pData = d3dBuffer->getSurface(device); - } - } - else if(name == "HWND") - { - *(HWND*)pData = NULL; - } - else if(name == "BUFFER") - { - *static_cast(pData) = mBuffer; - } - } - //--------------------------------------------------------------------- - void D3D9RenderTexture::swapBuffers() - { - // Only needed if we have to blit from AA surface - if (mFSAA > 0) - { - D3D9DeviceManager* deviceManager = D3D9RenderSystem::getDeviceManager(); - D3D9HardwarePixelBuffer* buf = static_cast(mBuffer); - - for (UINT i=0; i < deviceManager->getDeviceCount(); ++i) - { - D3D9Device* device = deviceManager->getDevice(i); - - if (device->isDeviceLost() == false) - { - IDirect3DDevice9* d3d9Device = device->getD3D9Device(); - - HRESULT hr = d3d9Device->StretchRect(buf->getFSAASurface(d3d9Device), 0, - buf->getSurface(d3d9Device), 0, D3DTEXF_NONE); - - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Unable to copy AA buffer to final buffer: " + String(DXGetErrorDescription(hr)), - "D3D9RenderTexture::swapBuffers"); - } - } - } - } - } -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9TextureManager.cpp b/RenderSystems/Direct3D9/src/OgreD3D9TextureManager.cpp deleted file mode 100644 index 0d6672059e6..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9TextureManager.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9TextureManager.h" -#include "OgreD3D9Texture.h" -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreD3D9Mappings.h" -#include "OgreRoot.h" -#include "OgreD3D9RenderSystem.h" - -#include - -namespace Ogre -{ - D3D9TextureManager::D3D9TextureManager() : TextureManager() - { - // register with group manager - ResourceGroupManager::getSingleton()._registerResourceManager(mResourceType, this); - } - - D3D9TextureManager::~D3D9TextureManager() - { - // unregister with group manager - ResourceGroupManager::getSingleton()._unregisterResourceManager(mResourceType); - - } - - Resource* D3D9TextureManager::createImpl(const String& name, - ResourceHandle handle, const String& group, bool isManual, - ManualResourceLoader* loader, const NameValuePairList* createParams) - { - D3D9Texture* ret = OGRE_NEW D3D9Texture(this, name, handle, group, isManual, loader); - return ret; - } - - PixelFormat D3D9TextureManager::getNativeFormat(TextureType ttype, PixelFormat format, int usage) - { - // Basic filtering - D3DFORMAT d3dPF = D3D9Mappings::_getPF(D3D9Mappings::_getClosestSupportedPF(format)); - - // Calculate usage - DWORD d3dusage = 0; - D3DPOOL pool = D3DPOOL_MANAGED; - if (D3D9RenderSystem::isDirectX9Ex()) - { - pool = D3DPOOL_DEFAULT; - } - if (usage & TU_RENDERTARGET) - { - d3dusage |= D3DUSAGE_RENDERTARGET; - pool = D3DPOOL_DEFAULT; - } - if (usage & TU_DYNAMIC) - { - d3dusage |= D3DUSAGE_DYNAMIC; - pool = D3DPOOL_DEFAULT; - } - - IDirect3DDevice9* pCurDevice = D3D9RenderSystem::getActiveD3D9Device(); - - // Use D3DX to adjust pixel format - switch(ttype) - { - case TEX_TYPE_1D: - case TEX_TYPE_2D: - D3DXCheckTextureRequirements(pCurDevice, NULL, NULL, NULL, d3dusage, &d3dPF, pool); - break; - case TEX_TYPE_3D: - D3DXCheckVolumeTextureRequirements(pCurDevice, NULL, NULL, NULL, NULL, d3dusage, &d3dPF, pool); - break; - case TEX_TYPE_CUBE_MAP: - D3DXCheckCubeTextureRequirements(pCurDevice, NULL, NULL, d3dusage, &d3dPF, pool); - break; - }; - - return D3D9Mappings::_getPF(d3dPF); - } - - bool D3D9TextureManager::isHardwareFilteringSupported(TextureType ttype, PixelFormat format, int usage, - bool preciseFormatOnly) - { - if (!preciseFormatOnly) - format = getNativeFormat(ttype, format, usage); - - D3D9RenderSystem* rs = static_cast( - Root::getSingleton().getRenderSystem()); - - return rs->_checkTextureFilteringSupported(ttype, format, usage); - } -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9VertexDeclaration.cpp b/RenderSystems/Direct3D9/src/OgreD3D9VertexDeclaration.cpp deleted file mode 100644 index 58d3217aa1f..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9VertexDeclaration.cpp +++ /dev/null @@ -1,173 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9VertexDeclaration.h" -#include "OgreD3D9Mappings.h" -#include "OgreException.h" -#include "OgreRoot.h" -#include "OgreD3D9RenderSystem.h" - -namespace Ogre { - - //----------------------------------------------------------------------- - D3D9VertexDeclaration::D3D9VertexDeclaration() - { - - } - //----------------------------------------------------------------------- - D3D9VertexDeclaration::~D3D9VertexDeclaration() - { - releaseDeclaration(); - } - - void D3D9VertexDeclaration::notifyChanged() - { - releaseDeclaration(); - } - - //----------------------------------------------------------------------- - void D3D9VertexDeclaration::notifyOnDeviceCreate(IDirect3DDevice9* d3d9Device) - { - - } - - //----------------------------------------------------------------------- - void D3D9VertexDeclaration::notifyOnDeviceDestroy(IDirect3DDevice9* d3d9Device) - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - DeviceToDeclarationIterator it = mMapDeviceToDeclaration.find(d3d9Device); - - if (it != mMapDeviceToDeclaration.end()) - { - SAFE_RELEASE(it->second); - mMapDeviceToDeclaration.erase(it); - } - } - - //----------------------------------------------------------------------- - IDirect3DVertexDeclaration9* D3D9VertexDeclaration::getD3DVertexDeclaration() - { - IDirect3DDevice9* pCurDevice = D3D9RenderSystem::getActiveD3D9Device(); - DeviceToDeclarationIterator it = mMapDeviceToDeclaration.find(pCurDevice); - IDirect3DVertexDeclaration9* lpVertDecl = NULL; - - // Case we have to create the declaration for this device. - if (it == mMapDeviceToDeclaration.end() || it->second == NULL) - { - size_t d3delemsSize = mElementList.size() + 1; - D3DVERTEXELEMENT9* d3delems = OGRE_ALLOC_T(D3DVERTEXELEMENT9, d3delemsSize, MEMCATEGORY_RENDERSYS); - - VertexElementList::const_iterator i, iend; - unsigned int idx; - size_t maxSource = 0; - iend = mElementList.end(); - for (idx = 0, i = mElementList.begin(); i != iend; ++i, ++idx) - { - const VertexElement & element = *i; - D3DVERTEXELEMENT9 & dxElement = d3delems[idx]; - convertElement(element, dxElement); - if(element.getSource() > maxSource) - { - maxSource = element.getSource(); - } - } - - // Add terminator - d3delems[idx].Stream = 0xff; - d3delems[idx].Offset = 0; - d3delems[idx].Type = D3DDECLTYPE_UNUSED; - d3delems[idx].Method = 0; - d3delems[idx].Usage = 0; - d3delems[idx].UsageIndex = 0; - - - HRESULT hr = pCurDevice->CreateVertexDeclaration(d3delems, &lpVertDecl); - - if (FAILED(hr)) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Cannot create D3D9 vertex declaration: " + - DXGetErrorDescription(hr), - "Direct3D9VertexDeclaration::getD3DVertexDeclaration"); - } - - OGRE_FREE(d3delems, MEMCATEGORY_RENDERSYS); - - mMapDeviceToDeclaration[pCurDevice] = lpVertDecl; - } - - // Declaration already exits. - else - { - lpVertDecl = mMapDeviceToDeclaration[pCurDevice]; - } - - return lpVertDecl; - } - //----------------------------------------------------------------------- - void D3D9VertexDeclaration::releaseDeclaration() - { - D3D9_DEVICE_ACCESS_CRITICAL_SECTION - - DeviceToDeclarationIterator it = mMapDeviceToDeclaration.begin(); - - while (it != mMapDeviceToDeclaration.end()) - { - SAFE_RELEASE(it->second); - ++it; - } - mMapDeviceToDeclaration.clear(); - } - //----------------------------------------------------------------------- - void D3D9VertexDeclaration::convertElement( const VertexElement & element, D3DVERTEXELEMENT9 & dxElement ) - { - dxElement.Method = D3DDECLMETHOD_DEFAULT; - dxElement.Offset = static_cast(element.getOffset()); - dxElement.Stream = element.getSource(); - dxElement.Type = D3D9Mappings::get(element.getType()); - dxElement.Usage = D3D9Mappings::get(element.getSemantic()); - // NB force index if colours since D3D uses the same usage for - // diffuse & specular - if (element.getSemantic() == VES_SPECULAR) - { - dxElement.UsageIndex = 1; - } - else if (element.getSemantic() == VES_DIFFUSE) - { - dxElement.UsageIndex = 0; - } - else - { - dxElement.UsageIndex = static_cast(element.getIndex()); - } - } - //----------------------------------------------------------------------- - - -} - diff --git a/RenderSystems/Direct3D9/src/OgreD3D9VideoMode.cpp b/RenderSystems/Direct3D9/src/OgreD3D9VideoMode.cpp deleted file mode 100644 index 656ded28d54..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9VideoMode.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9VideoMode.h" - -namespace Ogre -{ - String D3D9VideoMode::getDescription() const - { - unsigned int colourDepth = 16; - if( mDisplayMode.Format == D3DFMT_X8R8G8B8 || - mDisplayMode.Format == D3DFMT_A8R8G8B8 || - mDisplayMode.Format == D3DFMT_R8G8B8 ) - colourDepth = 32; - - return StringUtil::format("%d x %d @ %d-bit colour", mDisplayMode.Width, mDisplayMode.Height, colourDepth ); - } -} diff --git a/RenderSystems/Direct3D9/src/OgreD3D9VideoModeList.cpp b/RenderSystems/Direct3D9/src/OgreD3D9VideoModeList.cpp deleted file mode 100644 index 540bd06cbe5..00000000000 --- a/RenderSystems/Direct3D9/src/OgreD3D9VideoModeList.cpp +++ /dev/null @@ -1,146 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreD3D9VideoModeList.h" -#include "OgreException.h" -#include "OgreD3D9RenderSystem.h" - -namespace Ogre -{ - D3D9VideoModeList::D3D9VideoModeList( D3D9Driver* pDriver ) - { - if( NULL == pDriver ) - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "pDriver parameter is NULL", "D3D9VideoModeList::D3D9VideoModeList" ); - - mDriver = pDriver; - enumerate(); - } - - D3D9VideoModeList::~D3D9VideoModeList() - { - mDriver = NULL; - mModeList.clear(); - } - - BOOL D3D9VideoModeList::enumerate() - { - UINT iMode; - IDirect3D9* pD3D = D3D9RenderSystem::getDirect3D9(); - UINT adapter = mDriver->getAdapterNumber(); - - for( iMode=0; iMode < pD3D->GetAdapterModeCount( adapter, D3DFMT_R5G6B5 ); iMode++ ) - { - D3DDISPLAYMODE displayMode; - pD3D->EnumAdapterModes( adapter, D3DFMT_R5G6B5, iMode, &displayMode ); - - // Filter out low-resolutions - if( displayMode.Width < 640 || displayMode.Height < 400 ) - continue; - - // Check to see if it is already in the list (to filter out refresh rates) - BOOL found = FALSE; - std::vector::iterator it; - for( it = mModeList.begin(); it != mModeList.end(); ++it ) - { - D3DDISPLAYMODE oldDisp = it->getDisplayMode(); - if( oldDisp.Width == displayMode.Width && - oldDisp.Height == displayMode.Height && - oldDisp.Format == displayMode.Format ) - { - // Check refresh rate and favour higher if poss - if (oldDisp.RefreshRate < displayMode.RefreshRate) - it->increaseRefreshRate(displayMode.RefreshRate); - found = TRUE; - break; - } - } - - if( !found ) - mModeList.push_back( D3D9VideoMode( displayMode ) ); - } - - for( iMode=0; iMode < pD3D->GetAdapterModeCount( adapter, D3DFMT_X8R8G8B8 ); iMode++ ) - { - D3DDISPLAYMODE displayMode; - pD3D->EnumAdapterModes( adapter, D3DFMT_X8R8G8B8, iMode, &displayMode ); - - // Filter out low-resolutions - if( displayMode.Width < 640 || displayMode.Height < 400 ) - continue; - - // Check to see if it is already in the list (to filter out refresh rates) - BOOL found = FALSE; - std::vector::iterator it; - for( it = mModeList.begin(); it != mModeList.end(); ++it ) - { - D3DDISPLAYMODE oldDisp = it->getDisplayMode(); - if( oldDisp.Width == displayMode.Width && - oldDisp.Height == displayMode.Height && - oldDisp.Format == displayMode.Format ) - { - // Check refresh rate and favour higher if poss - if (oldDisp.RefreshRate < displayMode.RefreshRate) - it->increaseRefreshRate(displayMode.RefreshRate); - found = TRUE; - break; - } - } - - if( !found ) - mModeList.push_back( D3D9VideoMode( displayMode ) ); - } - - return TRUE; - } - - size_t D3D9VideoModeList::count() - { - return mModeList.size(); - } - - D3D9VideoMode* D3D9VideoModeList::item( size_t index ) - { - std::vector::iterator p = mModeList.begin(); - - return &p[index]; - } - - D3D9VideoMode* D3D9VideoModeList::item( const String &name ) - { - std::vector::iterator it = mModeList.begin(); - if (it == mModeList.end()) - return NULL; - - for (;it != mModeList.end(); ++it) - { - if (it->getDescription() == name) - return &(*it); - } - - return NULL; - } -} diff --git a/RenderSystems/Direct3D9/src/OgreDxErr.cpp b/RenderSystems/Direct3D9/src/OgreDxErr.cpp deleted file mode 100644 index 6d61e0ca121..00000000000 --- a/RenderSystems/Direct3D9/src/OgreDxErr.cpp +++ /dev/null @@ -1,4051 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -The source code for this package is bound to the Microsoft Public License (Ms-PL). - -Microsoft Public License (MS-PL) - -This license governs use of the accompanying software. If you use the software, you -accept this license. If you do not accept the license, do not use the software. - -1. Definitions -The terms "reproduce," "reproduction," "derivative works," and "distribution" have the -same meaning here as under U.S. copyright law. -A "contribution" is the original software, or any additions or changes to the software. -A "contributor" is any person that distributes its contribution under this license. -"Licensed patents" are a contributor's patent claims that read directly on its contribution. - -2. Grant of Rights -(A) Copyright Grant- Subject to the terms of this license, including the license conditions - and limitations in section 3, each contributor grants you a non-exclusive, worldwide, - royalty-free copyright license to reproduce its contribution, prepare derivative works of - its contribution, and distribute its contribution or any derivative works that you create. -(B) Patent Grant- Subject to the terms of this license, including the license conditions - and limitations in section 3, each contributor grants you a non-exclusive, worldwide, - royalty-free license under its licensed patents to make, have made, use, sell, offer - for sale, import, and/or otherwise dispose of its contribution in the software or - derivative works of the contribution in the software. - -3. Conditions and Limitations -(A) No Trademark License- This license does not grant you rights to use any contributors' - name, logo, or trademarks. -(B) If you bring a patent claim against any contributor over patents that you claim are - infringed by the software, your patent license from such contributor to the software - ends automatically. -(C) If you distribute any portion of the software, you must retain all copyright, patent, - trademark, and attribution notices that are present in the software. -(D) If you distribute any portion of the software in source code form, you may do so only - under this license by including a complete copy of this license with your distribution. - If you distribute any portion of the software in compiled or object code form, you may - only do so under a license that complies with this license. -(E) The software is licensed "as-is." You bear the risk of using it. The contributors give - no express warranties, guarantees or conditions. You may have additional consumer rights - under your local laws which this license cannot change. To the extent permitted under - your local laws, the contributors exclude the implied warranties of merchantability, - fitness for a particular purpose and non-infringement. - ------------------------------------------------------------------------------ -*/ - -//-------------------------------------------------------------------------------------- -// File: DXErr.cpp -// -// DirectX Error Library -// -// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO -// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A -// PARTICULAR PURPOSE. -// -// Copyright (c) Microsoft Corporation. All rights reserved. -//-------------------------------------------------------------------------------------- - -// This version only supports UNICODE. - -#include "OgrePrerequisites.h" - -#if !defined(NOMINMAX) -#define NOMINMAX -#endif -#include - -#ifndef __MINGW32__ -#pragma warning( disable : 4005 ) // warning C4005: 'xxx': macro redefinition - -#include -#include - -#if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) -#include -#include -#include - -#define DIRECTINPUT_VERSION 0x800 -#include -#include -#endif - -#include -#include - -#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP -#if defined(_WIN32_WINNT) && _WIN32_WINNT <= 0x601 // not Modern SDK -#include -#endif -#include -#include -#endif - -#include "OgreD3D9Prerequisites.h" - - -#define XAUDIO2_E_INVALID_CALL 0x88960001 -#define XAUDIO2_E_XMA_DECODER_ERROR 0x88960002 -#define XAUDIO2_E_XAPO_CREATION_FAILED 0x88960003 -#define XAUDIO2_E_DEVICE_INVALIDATED 0x88960004 - -#define XAPO_E_FORMAT_UNSUPPORTED MAKE_HRESULT(SEVERITY_ERROR, 0x897, 0x01) - -#define DXUTERR_NODIRECT3D MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0901) -#define DXUTERR_NOCOMPATIBLEDEVICES MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0902) -#define DXUTERR_MEDIANOTFOUND MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0903) -#define DXUTERR_NONZEROREFCOUNT MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0904) -#define DXUTERR_CREATINGDEVICE MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0905) -#define DXUTERR_RESETTINGDEVICE MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0906) -#define DXUTERR_CREATINGDEVICEOBJECTS MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0907) -#define DXUTERR_RESETTINGDEVICEOBJECTS MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0908) -#define DXUTERR_INCORRECTVERSION MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x0909) -#define DXUTERR_DEVICEREMOVED MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0x090A) - -//----------------------------------------------------------------------------- -#define BUFFER_SIZE 3000 - -#pragma warning( disable : 6001 6221 ) - -//-------------------------------------------------------------------------------------- -#define CHK_ERR(hrchk, strOut) \ - case hrchk: \ - return L##strOut; - -#define CHK_ERRA(hrchk) \ - case hrchk: \ - return L#hrchk; - -#define HRESULT_FROM_WIN32b(x) ((HRESULT)(x) <= 0 ? ((HRESULT)(x)) : ((HRESULT) (((x) & 0x0000FFFF) | (FACILITY_WIN32 << 16) | 0x80000000))) - -#define CHK_ERR_WIN32A(hrchk) \ - case HRESULT_FROM_WIN32b(hrchk): \ - case hrchk: \ - return L#hrchk; - -#define CHK_ERR_WIN32_ONLY(hrchk, strOut) \ - case HRESULT_FROM_WIN32b(hrchk): \ - return L##strOut; - -//----------------------------------------------------- -const WCHAR* WINAPI DXGetErrorStringW( _In_ HRESULT hr ) -{ - switch(hr) - { -// Commmented out codes are actually alises for other codes - -// ------------------------------------------------------------- -// Common Win32 error codes -// ------------------------------------------------------------- - CHK_ERRA(S_OK) - CHK_ERRA(S_FALSE) - - CHK_ERRA(E_UNEXPECTED) - CHK_ERRA(E_NOTIMPL) - CHK_ERRA(E_OUTOFMEMORY) - CHK_ERRA(E_INVALIDARG) - CHK_ERRA(E_NOINTERFACE) - CHK_ERRA(E_POINTER) - CHK_ERRA(E_HANDLE) - CHK_ERRA(E_ABORT) - CHK_ERRA(E_FAIL) - CHK_ERRA(E_ACCESSDENIED) - CHK_ERRA(E_PENDING) - CHK_ERRA(CO_E_INIT_TLS) - CHK_ERRA(CO_E_INIT_SHARED_ALLOCATOR) - CHK_ERRA(CO_E_INIT_MEMORY_ALLOCATOR) - CHK_ERRA(CO_E_INIT_CLASS_CACHE) - CHK_ERRA(CO_E_INIT_RPC_CHANNEL) - CHK_ERRA(CO_E_INIT_TLS_SET_CHANNEL_CONTROL) - CHK_ERRA(CO_E_INIT_TLS_CHANNEL_CONTROL) - CHK_ERRA(CO_E_INIT_UNACCEPTED_USER_ALLOCATOR) - CHK_ERRA(CO_E_INIT_SCM_MUTEX_EXISTS) - CHK_ERRA(CO_E_INIT_SCM_FILE_MAPPING_EXISTS) - CHK_ERRA(CO_E_INIT_SCM_MAP_VIEW_OF_FILE) - CHK_ERRA(CO_E_INIT_SCM_EXEC_FAILURE) - CHK_ERRA(CO_E_INIT_ONLY_SINGLE_THREADED) - CHK_ERRA(CO_E_CANT_REMOTE) - CHK_ERRA(CO_E_BAD_SERVER_NAME) - CHK_ERRA(CO_E_WRONG_SERVER_IDENTITY) - CHK_ERRA(CO_E_OLE1DDE_DISABLED) - CHK_ERRA(CO_E_RUNAS_SYNTAX) - CHK_ERRA(CO_E_CREATEPROCESS_FAILURE) - CHK_ERRA(CO_E_RUNAS_CREATEPROCESS_FAILURE) - CHK_ERRA(CO_E_RUNAS_LOGON_FAILURE) - CHK_ERRA(CO_E_LAUNCH_PERMSSION_DENIED) - CHK_ERRA(CO_E_START_SERVICE_FAILURE) - CHK_ERRA(CO_E_REMOTE_COMMUNICATION_FAILURE) - CHK_ERRA(CO_E_SERVER_START_TIMEOUT) - CHK_ERRA(CO_E_CLSREG_INCONSISTENT) - CHK_ERRA(CO_E_IIDREG_INCONSISTENT) - CHK_ERRA(CO_E_NOT_SUPPORTED) - CHK_ERRA(CO_E_RELOAD_DLL) - CHK_ERRA(CO_E_MSI_ERROR) - CHK_ERRA(OLE_E_FIRST) - CHK_ERRA(OLE_E_LAST) - CHK_ERRA(OLE_S_FIRST) - CHK_ERRA(OLE_S_LAST) -// CHK_ERRA(OLE_E_OLEVERB) - CHK_ERRA(OLE_E_ADVF) - CHK_ERRA(OLE_E_ENUM_NOMORE) - CHK_ERRA(OLE_E_ADVISENOTSUPPORTED) - CHK_ERRA(OLE_E_NOCONNECTION) - CHK_ERRA(OLE_E_NOTRUNNING) - CHK_ERRA(OLE_E_NOCACHE) - CHK_ERRA(OLE_E_BLANK) - CHK_ERRA(OLE_E_CLASSDIFF) - CHK_ERRA(OLE_E_CANT_GETMONIKER) - CHK_ERRA(OLE_E_CANT_BINDTOSOURCE) - CHK_ERRA(OLE_E_STATIC) - CHK_ERRA(OLE_E_PROMPTSAVECANCELLED) - CHK_ERRA(OLE_E_INVALIDRECT) - CHK_ERRA(OLE_E_WRONGCOMPOBJ) - CHK_ERRA(OLE_E_INVALIDHWND) - CHK_ERRA(OLE_E_NOT_INPLACEACTIVE) - CHK_ERRA(OLE_E_CANTCONVERT) - CHK_ERRA(OLE_E_NOSTORAGE) - CHK_ERRA(DV_E_FORMATETC) - CHK_ERRA(DV_E_DVTARGETDEVICE) - CHK_ERRA(DV_E_STGMEDIUM) - CHK_ERRA(DV_E_STATDATA) - CHK_ERRA(DV_E_LINDEX) - CHK_ERRA(DV_E_TYMED) - CHK_ERRA(DV_E_CLIPFORMAT) - CHK_ERRA(DV_E_DVASPECT) - CHK_ERRA(DV_E_DVTARGETDEVICE_SIZE) - CHK_ERRA(DV_E_NOIVIEWOBJECT) - CHK_ERRA(DRAGDROP_E_FIRST) - CHK_ERRA(DRAGDROP_E_LAST) - CHK_ERRA(DRAGDROP_S_FIRST) - CHK_ERRA(DRAGDROP_S_LAST) -// CHK_ERRA(DRAGDROP_E_NOTREGISTERED) - CHK_ERRA(DRAGDROP_E_ALREADYREGISTERED) - CHK_ERRA(DRAGDROP_E_INVALIDHWND) - CHK_ERRA(CLASSFACTORY_E_FIRST) - CHK_ERRA(CLASSFACTORY_E_LAST) - CHK_ERRA(CLASSFACTORY_S_FIRST) - CHK_ERRA(CLASSFACTORY_S_LAST) -// CHK_ERRA(CLASS_E_NOAGGREGATION) - CHK_ERRA(CLASS_E_CLASSNOTAVAILABLE) - CHK_ERRA(CLASS_E_NOTLICENSED) - CHK_ERRA(MARSHAL_E_FIRST) - CHK_ERRA(MARSHAL_E_LAST) - CHK_ERRA(MARSHAL_S_FIRST) - CHK_ERRA(MARSHAL_S_LAST) - CHK_ERRA(DATA_E_FIRST) - CHK_ERRA(DATA_E_LAST) - CHK_ERRA(DATA_S_FIRST) - CHK_ERRA(DATA_S_LAST) - CHK_ERRA(VIEW_E_FIRST) - CHK_ERRA(VIEW_E_LAST) - CHK_ERRA(VIEW_S_FIRST) - CHK_ERRA(VIEW_S_LAST) -// CHK_ERRA(VIEW_E_DRAW) - CHK_ERRA(REGDB_E_FIRST) - CHK_ERRA(REGDB_E_LAST) - CHK_ERRA(REGDB_S_FIRST) - CHK_ERRA(REGDB_S_LAST) -// CHK_ERRA(REGDB_E_READREGDB) - CHK_ERRA(REGDB_E_WRITEREGDB) - CHK_ERRA(REGDB_E_KEYMISSING) - CHK_ERRA(REGDB_E_INVALIDVALUE) - CHK_ERRA(REGDB_E_CLASSNOTREG) - CHK_ERRA(REGDB_E_IIDNOTREG) - CHK_ERRA(CAT_E_FIRST) - CHK_ERRA(CAT_E_LAST) -// CHK_ERRA(CAT_E_CATIDNOEXIST) -// CHK_ERRA(CAT_E_NODESCRIPTION) - CHK_ERRA(CS_E_FIRST) - CHK_ERRA(CS_E_LAST) -// CHK_ERRA(CS_E_PACKAGE_NOTFOUND) - CHK_ERRA(CS_E_NOT_DELETABLE) - CHK_ERRA(CS_E_CLASS_NOTFOUND) - CHK_ERRA(CS_E_INVALID_VERSION) - CHK_ERRA(CS_E_NO_CLASSSTORE) - CHK_ERRA(CS_E_OBJECT_NOTFOUND) - CHK_ERRA(CS_E_OBJECT_ALREADY_EXISTS) - CHK_ERRA(CS_E_INVALID_PATH) - CHK_ERRA(CS_E_NETWORK_ERROR) - CHK_ERRA(CS_E_ADMIN_LIMIT_EXCEEDED) - CHK_ERRA(CS_E_SCHEMA_MISMATCH) -// CHK_ERRA(CS_E_INTERNAL_ERROR) - CHK_ERRA(CACHE_E_FIRST) - CHK_ERRA(CACHE_E_LAST) - CHK_ERRA(CACHE_S_FIRST) - CHK_ERRA(CACHE_S_LAST) -// CHK_ERRA(CACHE_E_NOCACHE_UPDATED) - CHK_ERRA(OLEOBJ_E_FIRST) - CHK_ERRA(OLEOBJ_E_LAST) - CHK_ERRA(OLEOBJ_S_FIRST) - CHK_ERRA(OLEOBJ_S_LAST) -// CHK_ERRA(OLEOBJ_E_NOVERBS) - CHK_ERRA(OLEOBJ_E_INVALIDVERB) - CHK_ERRA(CLIENTSITE_E_FIRST) - CHK_ERRA(CLIENTSITE_E_LAST) - CHK_ERRA(CLIENTSITE_S_FIRST) - CHK_ERRA(CLIENTSITE_S_LAST) - CHK_ERRA(INPLACE_E_NOTUNDOABLE) - CHK_ERRA(INPLACE_E_NOTOOLSPACE) -// CHK_ERRA(INPLACE_E_FIRST) - CHK_ERRA(INPLACE_E_LAST) - CHK_ERRA(INPLACE_S_FIRST) - CHK_ERRA(INPLACE_S_LAST) - CHK_ERRA(ENUM_E_FIRST) - CHK_ERRA(ENUM_E_LAST) - CHK_ERRA(ENUM_S_FIRST) - CHK_ERRA(ENUM_S_LAST) - CHK_ERRA(CONVERT10_E_FIRST) - CHK_ERRA(CONVERT10_E_LAST) - CHK_ERRA(CONVERT10_S_FIRST) - CHK_ERRA(CONVERT10_S_LAST) -// CHK_ERRA(CONVERT10_E_OLESTREAM_GET) - CHK_ERRA(CONVERT10_E_OLESTREAM_PUT) - CHK_ERRA(CONVERT10_E_OLESTREAM_FMT) - CHK_ERRA(CONVERT10_E_OLESTREAM_BITMAP_TO_DIB) - CHK_ERRA(CONVERT10_E_STG_FMT) - CHK_ERRA(CONVERT10_E_STG_NO_STD_STREAM) - CHK_ERRA(CONVERT10_E_STG_DIB_TO_BITMAP) - CHK_ERRA(CLIPBRD_E_FIRST) - CHK_ERRA(CLIPBRD_E_LAST) - CHK_ERRA(CLIPBRD_S_FIRST) - CHK_ERRA(CLIPBRD_S_LAST) -// CHK_ERRA(CLIPBRD_E_CANT_OPEN) - CHK_ERRA(CLIPBRD_E_CANT_EMPTY) - CHK_ERRA(CLIPBRD_E_CANT_SET) - CHK_ERRA(CLIPBRD_E_BAD_DATA) - CHK_ERRA(CLIPBRD_E_CANT_CLOSE) - CHK_ERRA(MK_E_FIRST) - CHK_ERRA(MK_E_LAST) - CHK_ERRA(MK_S_FIRST) - CHK_ERRA(MK_S_LAST) -// CHK_ERRA(MK_E_CONNECTMANUALLY) - CHK_ERRA(MK_E_EXCEEDEDDEADLINE) - CHK_ERRA(MK_E_NEEDGENERIC) - CHK_ERRA(MK_E_UNAVAILABLE) - CHK_ERRA(MK_E_SYNTAX) - CHK_ERRA(MK_E_NOOBJECT) - CHK_ERRA(MK_E_INVALIDEXTENSION) - CHK_ERRA(MK_E_INTERMEDIATEINTERFACENOTSUPPORTED) - CHK_ERRA(MK_E_NOTBINDABLE) - CHK_ERRA(MK_E_NOTBOUND) - CHK_ERRA(MK_E_CANTOPENFILE) - CHK_ERRA(MK_E_MUSTBOTHERUSER) - CHK_ERRA(MK_E_NOINVERSE) - CHK_ERRA(MK_E_NOSTORAGE) - CHK_ERRA(MK_E_NOPREFIX) -// CHK_ERRA(MK_E_ENUMERATION_FAILED) - CHK_ERRA(CO_E_NOTINITIALIZED) - CHK_ERRA(CO_E_ALREADYINITIALIZED) - CHK_ERRA(CO_E_CANTDETERMINECLASS) - CHK_ERRA(CO_E_CLASSSTRING) - CHK_ERRA(CO_E_IIDSTRING) - CHK_ERRA(CO_E_APPNOTFOUND) - CHK_ERRA(CO_E_APPSINGLEUSE) - CHK_ERRA(CO_E_ERRORINAPP) - CHK_ERRA(CO_E_DLLNOTFOUND) - CHK_ERRA(CO_E_ERRORINDLL) - CHK_ERRA(CO_E_WRONGOSFORAPP) - CHK_ERRA(CO_E_OBJNOTREG) - CHK_ERRA(CO_E_OBJISREG) - CHK_ERRA(CO_E_OBJNOTCONNECTED) - CHK_ERRA(CO_E_APPDIDNTREG) - CHK_ERRA(CO_E_RELEASED) -// CHK_ERRA(OLE_S_USEREG) - CHK_ERRA(OLE_S_STATIC) - CHK_ERRA(OLE_S_MAC_CLIPFORMAT) -// CHK_ERRA(DRAGDROP_S_DROP) - CHK_ERRA(DRAGDROP_S_CANCEL) - CHK_ERRA(DRAGDROP_S_USEDEFAULTCURSORS) -// CHK_ERRA(DATA_S_SAMEFORMATETC) -// CHK_ERRA(VIEW_S_ALREADY_FROZEN) -// CHK_ERRA(CACHE_S_FORMATETC_NOTSUPPORTED) - CHK_ERRA(CACHE_S_SAMECACHE) - CHK_ERRA(CACHE_S_SOMECACHES_NOTUPDATED) -// CHK_ERRA(OLEOBJ_S_INVALIDVERB) - CHK_ERRA(OLEOBJ_S_CANNOT_DOVERB_NOW) - CHK_ERRA(OLEOBJ_S_INVALIDHWND) -// CHK_ERRA(INPLACE_S_TRUNCATED) -// CHK_ERRA(CONVERT10_S_NO_PRESENTATION) - CHK_ERRA(MK_S_REDUCED_TO_SELF) - CHK_ERRA(MK_S_ME) - CHK_ERRA(MK_S_HIM) - CHK_ERRA(MK_S_US) - CHK_ERRA(MK_S_MONIKERALREADYREGISTERED) - CHK_ERRA(CO_E_CLASS_CREATE_FAILED) - CHK_ERRA(CO_E_SCM_ERROR) - CHK_ERRA(CO_E_SCM_RPC_FAILURE) - CHK_ERRA(CO_E_BAD_PATH) - CHK_ERRA(CO_E_SERVER_EXEC_FAILURE) - CHK_ERRA(CO_E_OBJSRV_RPC_FAILURE) - CHK_ERRA(MK_E_NO_NORMALIZED) - CHK_ERRA(CO_E_SERVER_STOPPING) - CHK_ERRA(MEM_E_INVALID_ROOT) - CHK_ERRA(MEM_E_INVALID_LINK) - CHK_ERRA(MEM_E_INVALID_SIZE) - CHK_ERRA(CO_S_NOTALLINTERFACES) - CHK_ERRA(DISP_E_UNKNOWNINTERFACE) - CHK_ERRA(DISP_E_MEMBERNOTFOUND) - CHK_ERRA(DISP_E_PARAMNOTFOUND) - CHK_ERRA(DISP_E_TYPEMISMATCH) - CHK_ERRA(DISP_E_UNKNOWNNAME) - CHK_ERRA(DISP_E_NONAMEDARGS) - CHK_ERRA(DISP_E_BADVARTYPE) - CHK_ERRA(DISP_E_EXCEPTION) - CHK_ERRA(DISP_E_OVERFLOW) - CHK_ERRA(DISP_E_BADINDEX) - CHK_ERRA(DISP_E_UNKNOWNLCID) - CHK_ERRA(DISP_E_ARRAYISLOCKED) - CHK_ERRA(DISP_E_BADPARAMCOUNT) - CHK_ERRA(DISP_E_PARAMNOTOPTIONAL) - CHK_ERRA(DISP_E_BADCALLEE) - CHK_ERRA(DISP_E_NOTACOLLECTION) - CHK_ERRA(DISP_E_DIVBYZERO) - CHK_ERRA(DISP_E_BUFFERTOOSMALL) - CHK_ERRA(TYPE_E_BUFFERTOOSMALL) - CHK_ERRA(TYPE_E_FIELDNOTFOUND) - CHK_ERRA(TYPE_E_INVDATAREAD) - CHK_ERRA(TYPE_E_UNSUPFORMAT) - CHK_ERRA(TYPE_E_REGISTRYACCESS) - CHK_ERRA(TYPE_E_LIBNOTREGISTERED) - CHK_ERRA(TYPE_E_UNDEFINEDTYPE) - CHK_ERRA(TYPE_E_QUALIFIEDNAMEDISALLOWED) - CHK_ERRA(TYPE_E_INVALIDSTATE) - CHK_ERRA(TYPE_E_WRONGTYPEKIND) - CHK_ERRA(TYPE_E_ELEMENTNOTFOUND) - CHK_ERRA(TYPE_E_AMBIGUOUSNAME) - CHK_ERRA(TYPE_E_NAMECONFLICT) - CHK_ERRA(TYPE_E_UNKNOWNLCID) - CHK_ERRA(TYPE_E_DLLFUNCTIONNOTFOUND) - CHK_ERRA(TYPE_E_BADMODULEKIND) - CHK_ERRA(TYPE_E_SIZETOOBIG) - CHK_ERRA(TYPE_E_DUPLICATEID) - CHK_ERRA(TYPE_E_INVALIDID) - CHK_ERRA(TYPE_E_TYPEMISMATCH) - CHK_ERRA(TYPE_E_OUTOFBOUNDS) - CHK_ERRA(TYPE_E_IOERROR) - CHK_ERRA(TYPE_E_CANTCREATETMPFILE) - CHK_ERRA(TYPE_E_CANTLOADLIBRARY) - CHK_ERRA(TYPE_E_INCONSISTENTPROPFUNCS) - CHK_ERRA(TYPE_E_CIRCULARTYPE) - CHK_ERRA(STG_E_INVALIDFUNCTION) - CHK_ERRA(STG_E_FILENOTFOUND) - CHK_ERRA(STG_E_PATHNOTFOUND) - CHK_ERRA(STG_E_TOOMANYOPENFILES) - CHK_ERRA(STG_E_ACCESSDENIED) - CHK_ERRA(STG_E_INVALIDHANDLE) - CHK_ERRA(STG_E_INSUFFICIENTMEMORY) - CHK_ERRA(STG_E_INVALIDPOINTER) - CHK_ERRA(STG_E_NOMOREFILES) - CHK_ERRA(STG_E_DISKISWRITEPROTECTED) - CHK_ERRA(STG_E_SEEKERROR) - CHK_ERRA(STG_E_WRITEFAULT) - CHK_ERRA(STG_E_READFAULT) - CHK_ERRA(STG_E_SHAREVIOLATION) - CHK_ERRA(STG_E_LOCKVIOLATION) - CHK_ERRA(STG_E_FILEALREADYEXISTS) - CHK_ERRA(STG_E_INVALIDPARAMETER) - CHK_ERRA(STG_E_MEDIUMFULL) - CHK_ERRA(STG_E_PROPSETMISMATCHED) - CHK_ERRA(STG_E_ABNORMALAPIEXIT) - CHK_ERRA(STG_E_INVALIDHEADER) - CHK_ERRA(STG_E_INVALIDNAME) - CHK_ERRA(STG_E_UNKNOWN) - CHK_ERRA(STG_E_UNIMPLEMENTEDFUNCTION) - CHK_ERRA(STG_E_INVALIDFLAG) - CHK_ERRA(STG_E_INUSE) - CHK_ERRA(STG_E_NOTCURRENT) - CHK_ERRA(STG_E_REVERTED) - CHK_ERRA(STG_E_CANTSAVE) - CHK_ERRA(STG_E_OLDFORMAT) - CHK_ERRA(STG_E_OLDDLL) - CHK_ERRA(STG_E_SHAREREQUIRED) - CHK_ERRA(STG_E_NOTFILEBASEDSTORAGE) - CHK_ERRA(STG_E_EXTANTMARSHALLINGS) - CHK_ERRA(STG_E_DOCFILECORRUPT) - CHK_ERRA(STG_E_BADBASEADDRESS) - CHK_ERRA(STG_E_DOCFILETOOLARGE) - CHK_ERRA(STG_E_NOTSIMPLEFORMAT) - CHK_ERRA(STG_E_INCOMPLETE) - CHK_ERRA(STG_E_TERMINATED) - CHK_ERRA(STG_S_CONVERTED) - CHK_ERRA(STG_S_BLOCK) - CHK_ERRA(STG_S_RETRYNOW) - CHK_ERRA(STG_S_MONITORING) - CHK_ERRA(STG_S_MULTIPLEOPENS) - CHK_ERRA(STG_S_CONSOLIDATIONFAILED) - CHK_ERRA(STG_S_CANNOTCONSOLIDATE) - CHK_ERRA(RPC_E_CALL_REJECTED) - CHK_ERRA(RPC_E_CALL_CANCELED) - CHK_ERRA(RPC_E_CANTPOST_INSENDCALL) - CHK_ERRA(RPC_E_CANTCALLOUT_INASYNCCALL) - CHK_ERRA(RPC_E_CANTCALLOUT_INEXTERNALCALL) - CHK_ERRA(RPC_E_CONNECTION_TERMINATED) - CHK_ERRA(RPC_E_SERVER_DIED) - CHK_ERRA(RPC_E_CLIENT_DIED) - CHK_ERRA(RPC_E_INVALID_DATAPACKET) - CHK_ERRA(RPC_E_CANTTRANSMIT_CALL) - CHK_ERRA(RPC_E_CLIENT_CANTMARSHAL_DATA) - CHK_ERRA(RPC_E_CLIENT_CANTUNMARSHAL_DATA) - CHK_ERRA(RPC_E_SERVER_CANTMARSHAL_DATA) - CHK_ERRA(RPC_E_SERVER_CANTUNMARSHAL_DATA) - CHK_ERRA(RPC_E_INVALID_DATA) - CHK_ERRA(RPC_E_INVALID_PARAMETER) - CHK_ERRA(RPC_E_CANTCALLOUT_AGAIN) - CHK_ERRA(RPC_E_SERVER_DIED_DNE) - CHK_ERRA(RPC_E_SYS_CALL_FAILED) - CHK_ERRA(RPC_E_OUT_OF_RESOURCES) - CHK_ERRA(RPC_E_ATTEMPTED_MULTITHREAD) - CHK_ERRA(RPC_E_NOT_REGISTERED) - CHK_ERRA(RPC_E_FAULT) - CHK_ERRA(RPC_E_SERVERFAULT) - CHK_ERRA(RPC_E_CHANGED_MODE) - CHK_ERRA(RPC_E_INVALIDMETHOD) - CHK_ERRA(RPC_E_DISCONNECTED) - CHK_ERRA(RPC_E_RETRY) - CHK_ERRA(RPC_E_SERVERCALL_RETRYLATER) - CHK_ERRA(RPC_E_SERVERCALL_REJECTED) - CHK_ERRA(RPC_E_INVALID_CALLDATA) - CHK_ERRA(RPC_E_CANTCALLOUT_ININPUTSYNCCALL) - CHK_ERRA(RPC_E_WRONG_THREAD) - CHK_ERRA(RPC_E_THREAD_NOT_INIT) - CHK_ERRA(RPC_E_VERSION_MISMATCH) - CHK_ERRA(RPC_E_INVALID_HEADER) - CHK_ERRA(RPC_E_INVALID_EXTENSION) - CHK_ERRA(RPC_E_INVALID_IPID) - CHK_ERRA(RPC_E_INVALID_OBJECT) - CHK_ERRA(RPC_S_CALLPENDING) - CHK_ERRA(RPC_S_WAITONTIMER) - CHK_ERRA(RPC_E_CALL_COMPLETE) - CHK_ERRA(RPC_E_UNSECURE_CALL) - CHK_ERRA(RPC_E_TOO_LATE) - CHK_ERRA(RPC_E_NO_GOOD_SECURITY_PACKAGES) - CHK_ERRA(RPC_E_ACCESS_DENIED) - CHK_ERRA(RPC_E_REMOTE_DISABLED) - CHK_ERRA(RPC_E_INVALID_OBJREF) - CHK_ERRA(RPC_E_NO_CONTEXT) - CHK_ERRA(RPC_E_TIMEOUT) - CHK_ERRA(RPC_E_NO_SYNC) - CHK_ERRA(RPC_E_FULLSIC_REQUIRED) - CHK_ERRA(RPC_E_INVALID_STD_NAME) - CHK_ERRA(CO_E_FAILEDTOIMPERSONATE) - CHK_ERRA(CO_E_FAILEDTOGETSECCTX) - CHK_ERRA(CO_E_FAILEDTOOPENTHREADTOKEN) - CHK_ERRA(CO_E_FAILEDTOGETTOKENINFO) - CHK_ERRA(CO_E_TRUSTEEDOESNTMATCHCLIENT) - CHK_ERRA(CO_E_FAILEDTOQUERYCLIENTBLANKET) - CHK_ERRA(CO_E_FAILEDTOSETDACL) - CHK_ERRA(CO_E_ACCESSCHECKFAILED) - CHK_ERRA(CO_E_NETACCESSAPIFAILED) - CHK_ERRA(CO_E_WRONGTRUSTEENAMESYNTAX) - CHK_ERRA(CO_E_INVALIDSID) - CHK_ERRA(CO_E_CONVERSIONFAILED) - CHK_ERRA(CO_E_NOMATCHINGSIDFOUND) - CHK_ERRA(CO_E_LOOKUPACCSIDFAILED) - CHK_ERRA(CO_E_NOMATCHINGNAMEFOUND) - CHK_ERRA(CO_E_LOOKUPACCNAMEFAILED) - CHK_ERRA(CO_E_SETSERLHNDLFAILED) - CHK_ERRA(CO_E_FAILEDTOGETWINDIR) - CHK_ERRA(CO_E_PATHTOOLONG) - CHK_ERRA(CO_E_FAILEDTOGENUUID) - CHK_ERRA(CO_E_FAILEDTOCREATEFILE) - CHK_ERRA(CO_E_FAILEDTOCLOSEHANDLE) - CHK_ERRA(CO_E_EXCEEDSYSACLLIMIT) - CHK_ERRA(CO_E_ACESINWRONGORDER) - CHK_ERRA(CO_E_INCOMPATIBLESTREAMVERSION) - CHK_ERRA(CO_E_FAILEDTOOPENPROCESSTOKEN) - CHK_ERRA(CO_E_DECODEFAILED) - CHK_ERRA(CO_E_ACNOTINITIALIZED) - CHK_ERRA(RPC_E_UNEXPECTED) - CHK_ERRA(NTE_BAD_UID) - CHK_ERRA(NTE_BAD_HASH) - CHK_ERRA(NTE_BAD_KEY) - CHK_ERRA(NTE_BAD_LEN) - CHK_ERRA(NTE_BAD_DATA) - CHK_ERRA(NTE_BAD_SIGNATURE) - CHK_ERRA(NTE_BAD_VER) - CHK_ERRA(NTE_BAD_ALGID) - CHK_ERRA(NTE_BAD_FLAGS) - CHK_ERRA(NTE_BAD_TYPE) - CHK_ERRA(NTE_BAD_KEY_STATE) - CHK_ERRA(NTE_BAD_HASH_STATE) - CHK_ERRA(NTE_NO_KEY) - CHK_ERRA(NTE_NO_MEMORY) - CHK_ERRA(NTE_EXISTS) - CHK_ERRA(NTE_PERM) - CHK_ERRA(NTE_NOT_FOUND) - CHK_ERRA(NTE_DOUBLE_ENCRYPT) - CHK_ERRA(NTE_BAD_PROVIDER) - CHK_ERRA(NTE_BAD_PROV_TYPE) - CHK_ERRA(NTE_BAD_PUBLIC_KEY) - CHK_ERRA(NTE_BAD_KEYSET) - CHK_ERRA(NTE_PROV_TYPE_NOT_DEF) - CHK_ERRA(NTE_PROV_TYPE_ENTRY_BAD) - CHK_ERRA(NTE_KEYSET_NOT_DEF) - CHK_ERRA(NTE_KEYSET_ENTRY_BAD) - CHK_ERRA(NTE_PROV_TYPE_NO_MATCH) - CHK_ERRA(NTE_SIGNATURE_FILE_BAD) - CHK_ERRA(NTE_PROVIDER_DLL_FAIL) - CHK_ERRA(NTE_PROV_DLL_NOT_FOUND) - CHK_ERRA(NTE_BAD_KEYSET_PARAM) - CHK_ERRA(NTE_FAIL) - CHK_ERRA(NTE_SYS_ERR) - CHK_ERRA(NTE_SILENT_CONTEXT) - CHK_ERRA(NTE_TOKEN_KEYSET_STORAGE_FULL) - CHK_ERRA(CRYPT_E_MSG_ERROR) - CHK_ERRA(CRYPT_E_UNKNOWN_ALGO) - CHK_ERRA(CRYPT_E_OID_FORMAT) - CHK_ERRA(CRYPT_E_INVALID_MSG_TYPE) - CHK_ERRA(CRYPT_E_UNEXPECTED_ENCODING) - CHK_ERRA(CRYPT_E_AUTH_ATTR_MISSING) - CHK_ERRA(CRYPT_E_HASH_VALUE) - CHK_ERRA(CRYPT_E_INVALID_INDEX) - CHK_ERRA(CRYPT_E_ALREADY_DECRYPTED) - CHK_ERRA(CRYPT_E_NOT_DECRYPTED) - CHK_ERRA(CRYPT_E_RECIPIENT_NOT_FOUND) - CHK_ERRA(CRYPT_E_CONTROL_TYPE) - CHK_ERRA(CRYPT_E_ISSUER_SERIALNUMBER) - CHK_ERRA(CRYPT_E_SIGNER_NOT_FOUND) - CHK_ERRA(CRYPT_E_ATTRIBUTES_MISSING) - CHK_ERRA(CRYPT_E_STREAM_MSG_NOT_READY) - CHK_ERRA(CRYPT_E_STREAM_INSUFFICIENT_DATA) - CHK_ERRA(CRYPT_E_BAD_LEN) - CHK_ERRA(CRYPT_E_BAD_ENCODE) - CHK_ERRA(CRYPT_E_FILE_ERROR) - CHK_ERRA(CRYPT_E_NOT_FOUND) - CHK_ERRA(CRYPT_E_EXISTS) - CHK_ERRA(CRYPT_E_NO_PROVIDER) - CHK_ERRA(CRYPT_E_SELF_SIGNED) - CHK_ERRA(CRYPT_E_DELETED_PREV) - CHK_ERRA(CRYPT_E_NO_MATCH) - CHK_ERRA(CRYPT_E_UNEXPECTED_MSG_TYPE) - CHK_ERRA(CRYPT_E_NO_KEY_PROPERTY) - CHK_ERRA(CRYPT_E_NO_DECRYPT_CERT) - CHK_ERRA(CRYPT_E_BAD_MSG) - CHK_ERRA(CRYPT_E_NO_SIGNER) - CHK_ERRA(CRYPT_E_PENDING_CLOSE) - CHK_ERRA(CRYPT_E_REVOKED) - CHK_ERRA(CRYPT_E_NO_REVOCATION_DLL) - CHK_ERRA(CRYPT_E_NO_REVOCATION_CHECK) - CHK_ERRA(CRYPT_E_REVOCATION_OFFLINE) - CHK_ERRA(CRYPT_E_NOT_IN_REVOCATION_DATABASE) - CHK_ERRA(CRYPT_E_INVALID_NUMERIC_STRING) - CHK_ERRA(CRYPT_E_INVALID_PRINTABLE_STRING) - CHK_ERRA(CRYPT_E_INVALID_IA5_STRING) - CHK_ERRA(CRYPT_E_INVALID_X500_STRING) - CHK_ERRA(CRYPT_E_NOT_CHAR_STRING) - CHK_ERRA(CRYPT_E_FILERESIZED) - CHK_ERRA(CRYPT_E_SECURITY_SETTINGS) - CHK_ERRA(CRYPT_E_NO_VERIFY_USAGE_DLL) - CHK_ERRA(CRYPT_E_NO_VERIFY_USAGE_CHECK) - CHK_ERRA(CRYPT_E_VERIFY_USAGE_OFFLINE) - CHK_ERRA(CRYPT_E_NOT_IN_CTL) - CHK_ERRA(CRYPT_E_NO_TRUSTED_SIGNER) - CHK_ERRA(CRYPT_E_OSS_ERROR) - CHK_ERRA(OSS_MORE_BUF) - CHK_ERRA(OSS_NEGATIVE_UINTEGER) - CHK_ERRA(OSS_PDU_RANGE) - CHK_ERRA(OSS_MORE_INPUT) - CHK_ERRA(OSS_DATA_ERROR) - CHK_ERRA(OSS_BAD_ARG) - CHK_ERRA(OSS_BAD_VERSION) - CHK_ERRA(OSS_OUT_MEMORY) - CHK_ERRA(OSS_PDU_MISMATCH) - CHK_ERRA(OSS_LIMITED) - CHK_ERRA(OSS_BAD_PTR) - CHK_ERRA(OSS_BAD_TIME) - CHK_ERRA(OSS_INDEFINITE_NOT_SUPPORTED) - CHK_ERRA(OSS_MEM_ERROR) - CHK_ERRA(OSS_BAD_TABLE) - CHK_ERRA(OSS_TOO_LONG) - CHK_ERRA(OSS_CONSTRAINT_VIOLATED) - CHK_ERRA(OSS_FATAL_ERROR) - CHK_ERRA(OSS_ACCESS_SERIALIZATION_ERROR) - CHK_ERRA(OSS_NULL_TBL) - CHK_ERRA(OSS_NULL_FCN) - CHK_ERRA(OSS_BAD_ENCRULES) - CHK_ERRA(OSS_UNAVAIL_ENCRULES) - CHK_ERRA(OSS_CANT_OPEN_TRACE_WINDOW) - CHK_ERRA(OSS_UNIMPLEMENTED) - CHK_ERRA(OSS_OID_DLL_NOT_LINKED) - CHK_ERRA(OSS_CANT_OPEN_TRACE_FILE) - CHK_ERRA(OSS_TRACE_FILE_ALREADY_OPEN) - CHK_ERRA(OSS_TABLE_MISMATCH) - CHK_ERRA(OSS_TYPE_NOT_SUPPORTED) - CHK_ERRA(OSS_REAL_DLL_NOT_LINKED) - CHK_ERRA(OSS_REAL_CODE_NOT_LINKED) - CHK_ERRA(OSS_OUT_OF_RANGE) - CHK_ERRA(OSS_COPIER_DLL_NOT_LINKED) - CHK_ERRA(OSS_CONSTRAINT_DLL_NOT_LINKED) - CHK_ERRA(OSS_COMPARATOR_DLL_NOT_LINKED) - CHK_ERRA(OSS_COMPARATOR_CODE_NOT_LINKED) - CHK_ERRA(OSS_MEM_MGR_DLL_NOT_LINKED) - CHK_ERRA(OSS_PDV_DLL_NOT_LINKED) - CHK_ERRA(OSS_PDV_CODE_NOT_LINKED) - CHK_ERRA(OSS_API_DLL_NOT_LINKED) - CHK_ERRA(OSS_BERDER_DLL_NOT_LINKED) - CHK_ERRA(OSS_PER_DLL_NOT_LINKED) - CHK_ERRA(OSS_OPEN_TYPE_ERROR) - CHK_ERRA(OSS_MUTEX_NOT_CREATED) - CHK_ERRA(OSS_CANT_CLOSE_TRACE_FILE) - CHK_ERRA(CERTSRV_E_BAD_REQUESTSUBJECT) - CHK_ERRA(CERTSRV_E_NO_REQUEST) - CHK_ERRA(CERTSRV_E_BAD_REQUESTSTATUS) - CHK_ERRA(CERTSRV_E_PROPERTY_EMPTY) - CHK_ERRA(CERTSRV_E_INVALID_CA_CERTIFICATE) - CHK_ERRA(CERTSRV_E_UNSUPPORTED_CERT_TYPE) - CHK_ERRA(CERTSRV_E_NO_CERT_TYPE) - CHK_ERRA(TRUST_E_SYSTEM_ERROR) - CHK_ERRA(TRUST_E_NO_SIGNER_CERT) - CHK_ERRA(TRUST_E_COUNTER_SIGNER) - CHK_ERRA(TRUST_E_CERT_SIGNATURE) - CHK_ERRA(TRUST_E_TIME_STAMP) - CHK_ERRA(TRUST_E_BAD_DIGEST) - CHK_ERRA(TRUST_E_BASIC_CONSTRAINTS) - CHK_ERRA(TRUST_E_FINANCIAL_CRITERIA) -// CHK_ERRA(NTE_OP_OK) - CHK_ERRA(TRUST_E_PROVIDER_UNKNOWN) - CHK_ERRA(TRUST_E_ACTION_UNKNOWN) - CHK_ERRA(TRUST_E_SUBJECT_FORM_UNKNOWN) - CHK_ERRA(TRUST_E_SUBJECT_NOT_TRUSTED) - CHK_ERRA(DIGSIG_E_ENCODE) - CHK_ERRA(DIGSIG_E_DECODE) - CHK_ERRA(DIGSIG_E_EXTENSIBILITY) - CHK_ERRA(DIGSIG_E_CRYPTO) - CHK_ERRA(PERSIST_E_SIZEDEFINITE) - CHK_ERRA(PERSIST_E_SIZEINDEFINITE) - CHK_ERRA(PERSIST_E_NOTSELFSIZING) - CHK_ERRA(TRUST_E_NOSIGNATURE) - CHK_ERRA(CERT_E_EXPIRED) - CHK_ERRA(CERT_E_VALIDITYPERIODNESTING) - CHK_ERRA(CERT_E_ROLE) - CHK_ERRA(CERT_E_PATHLENCONST) - CHK_ERRA(CERT_E_CRITICAL) - CHK_ERRA(CERT_E_PURPOSE) - CHK_ERRA(CERT_E_ISSUERCHAINING) - CHK_ERRA(CERT_E_MALFORMED) - CHK_ERRA(CERT_E_UNTRUSTEDROOT) - CHK_ERRA(CERT_E_CHAINING) - CHK_ERRA(TRUST_E_FAIL) - CHK_ERRA(CERT_E_REVOKED) - CHK_ERRA(CERT_E_UNTRUSTEDTESTROOT) - CHK_ERRA(CERT_E_REVOCATION_FAILURE) - CHK_ERRA(CERT_E_CN_NO_MATCH) - CHK_ERRA(CERT_E_WRONG_USAGE) - CHK_ERRA(SPAPI_E_EXPECTED_SECTION_NAME) - CHK_ERRA(SPAPI_E_BAD_SECTION_NAME_LINE) - CHK_ERRA(SPAPI_E_SECTION_NAME_TOO_LONG) - CHK_ERRA(SPAPI_E_GENERAL_SYNTAX) - CHK_ERRA(SPAPI_E_WRONG_INF_STYLE) - CHK_ERRA(SPAPI_E_SECTION_NOT_FOUND) - CHK_ERRA(SPAPI_E_LINE_NOT_FOUND) - CHK_ERRA(SPAPI_E_NO_BACKUP) - CHK_ERRA(SPAPI_E_NO_ASSOCIATED_CLASS) - CHK_ERRA(SPAPI_E_CLASS_MISMATCH) - CHK_ERRA(SPAPI_E_DUPLICATE_FOUND) - CHK_ERRA(SPAPI_E_NO_DRIVER_SELECTED) - CHK_ERRA(SPAPI_E_KEY_DOES_NOT_EXIST) - CHK_ERRA(SPAPI_E_INVALID_DEVINST_NAME) - CHK_ERRA(SPAPI_E_INVALID_CLASS) - CHK_ERRA(SPAPI_E_DEVINST_ALREADY_EXISTS) - CHK_ERRA(SPAPI_E_DEVINFO_NOT_REGISTERED) - CHK_ERRA(SPAPI_E_INVALID_REG_PROPERTY) - CHK_ERRA(SPAPI_E_NO_INF) - CHK_ERRA(SPAPI_E_NO_SUCH_DEVINST) - CHK_ERRA(SPAPI_E_CANT_LOAD_CLASS_ICON) - CHK_ERRA(SPAPI_E_INVALID_CLASS_INSTALLER) - CHK_ERRA(SPAPI_E_DI_DO_DEFAULT) - CHK_ERRA(SPAPI_E_DI_NOFILECOPY) - CHK_ERRA(SPAPI_E_INVALID_HWPROFILE) - CHK_ERRA(SPAPI_E_NO_DEVICE_SELECTED) - CHK_ERRA(SPAPI_E_DEVINFO_LIST_LOCKED) - CHK_ERRA(SPAPI_E_DEVINFO_DATA_LOCKED) - CHK_ERRA(SPAPI_E_DI_BAD_PATH) - CHK_ERRA(SPAPI_E_NO_CLASSINSTALL_PARAMS) - CHK_ERRA(SPAPI_E_FILEQUEUE_LOCKED) - CHK_ERRA(SPAPI_E_BAD_SERVICE_INSTALLSECT) - CHK_ERRA(SPAPI_E_NO_CLASS_DRIVER_LIST) - CHK_ERRA(SPAPI_E_NO_ASSOCIATED_SERVICE) - CHK_ERRA(SPAPI_E_NO_DEFAULT_DEVICE_INTERFACE) - CHK_ERRA(SPAPI_E_DEVICE_INTERFACE_ACTIVE) - CHK_ERRA(SPAPI_E_DEVICE_INTERFACE_REMOVED) - CHK_ERRA(SPAPI_E_BAD_INTERFACE_INSTALLSECT) - CHK_ERRA(SPAPI_E_NO_SUCH_INTERFACE_CLASS) - CHK_ERRA(SPAPI_E_INVALID_REFERENCE_STRING) - CHK_ERRA(SPAPI_E_INVALID_MACHINENAME) - CHK_ERRA(SPAPI_E_REMOTE_COMM_FAILURE) - CHK_ERRA(SPAPI_E_MACHINE_UNAVAILABLE) - CHK_ERRA(SPAPI_E_NO_CONFIGMGR_SERVICES) - CHK_ERRA(SPAPI_E_INVALID_PROPPAGE_PROVIDER) - CHK_ERRA(SPAPI_E_NO_SUCH_DEVICE_INTERFACE) - CHK_ERRA(SPAPI_E_DI_POSTPROCESSING_REQUIRED) - CHK_ERRA(SPAPI_E_INVALID_COINSTALLER) - CHK_ERRA(SPAPI_E_NO_COMPAT_DRIVERS) - CHK_ERRA(SPAPI_E_NO_DEVICE_ICON) - CHK_ERRA(SPAPI_E_INVALID_INF_LOGCONFIG) - CHK_ERRA(SPAPI_E_DI_DONT_INSTALL) - CHK_ERRA(SPAPI_E_INVALID_FILTER_DRIVER) - CHK_ERRA(SPAPI_E_NON_WINDOWS_NT_DRIVER) - CHK_ERRA(SPAPI_E_NON_WINDOWS_DRIVER) - CHK_ERRA(SPAPI_E_NO_CATALOG_FOR_OEM_INF) - CHK_ERRA(SPAPI_E_DEVINSTALL_QUEUE_NONNATIVE) - CHK_ERRA(SPAPI_E_ERROR_NOT_INSTALLED) -// CHK_ERRA(SCARD_S_SUCCESS) - CHK_ERRA(SCARD_F_INTERNAL_ERROR) - CHK_ERRA(SCARD_E_CANCELLED) - CHK_ERRA(SCARD_E_INVALID_HANDLE) - CHK_ERRA(SCARD_E_INVALID_PARAMETER) - CHK_ERRA(SCARD_E_INVALID_TARGET) - CHK_ERRA(SCARD_E_NO_MEMORY) - CHK_ERRA(SCARD_F_WAITED_TOO_LONG) - CHK_ERRA(SCARD_E_INSUFFICIENT_BUFFER) - CHK_ERRA(SCARD_E_UNKNOWN_READER) - CHK_ERRA(SCARD_E_TIMEOUT) - CHK_ERRA(SCARD_E_SHARING_VIOLATION) - CHK_ERRA(SCARD_E_NO_SMARTCARD) - CHK_ERRA(SCARD_E_UNKNOWN_CARD) - CHK_ERRA(SCARD_E_CANT_DISPOSE) - CHK_ERRA(SCARD_E_PROTO_MISMATCH) - CHK_ERRA(SCARD_E_NOT_READY) - CHK_ERRA(SCARD_E_INVALID_VALUE) - CHK_ERRA(SCARD_E_SYSTEM_CANCELLED) - CHK_ERRA(SCARD_F_COMM_ERROR) - CHK_ERRA(SCARD_F_UNKNOWN_ERROR) - CHK_ERRA(SCARD_E_INVALID_ATR) - CHK_ERRA(SCARD_E_NOT_TRANSACTED) - CHK_ERRA(SCARD_E_READER_UNAVAILABLE) - CHK_ERRA(SCARD_P_SHUTDOWN) - CHK_ERRA(SCARD_E_PCI_TOO_SMALL) - CHK_ERRA(SCARD_E_READER_UNSUPPORTED) - CHK_ERRA(SCARD_E_DUPLICATE_READER) - CHK_ERRA(SCARD_E_CARD_UNSUPPORTED) - CHK_ERRA(SCARD_E_NO_SERVICE) - CHK_ERRA(SCARD_E_SERVICE_STOPPED) - CHK_ERRA(SCARD_E_UNEXPECTED) - CHK_ERRA(SCARD_E_ICC_INSTALLATION) - CHK_ERRA(SCARD_E_ICC_CREATEORDER) - CHK_ERRA(SCARD_E_UNSUPPORTED_FEATURE) - CHK_ERRA(SCARD_E_DIR_NOT_FOUND) - CHK_ERRA(SCARD_E_FILE_NOT_FOUND) - CHK_ERRA(SCARD_E_NO_DIR) - CHK_ERRA(SCARD_E_NO_FILE) - CHK_ERRA(SCARD_E_NO_ACCESS) - CHK_ERRA(SCARD_E_WRITE_TOO_MANY) - CHK_ERRA(SCARD_E_BAD_SEEK) - CHK_ERRA(SCARD_E_INVALID_CHV) - CHK_ERRA(SCARD_E_UNKNOWN_RES_MNG) - CHK_ERRA(SCARD_E_NO_SUCH_CERTIFICATE) - CHK_ERRA(SCARD_E_CERTIFICATE_UNAVAILABLE) - CHK_ERRA(SCARD_E_NO_READERS_AVAILABLE) - CHK_ERRA(SCARD_E_COMM_DATA_LOST) - CHK_ERRA(SCARD_W_UNSUPPORTED_CARD) - CHK_ERRA(SCARD_W_UNRESPONSIVE_CARD) - CHK_ERRA(SCARD_W_UNPOWERED_CARD) - CHK_ERRA(SCARD_W_RESET_CARD) - CHK_ERRA(SCARD_W_REMOVED_CARD) - CHK_ERRA(SCARD_W_SECURITY_VIOLATION) - CHK_ERRA(SCARD_W_WRONG_CHV) - CHK_ERRA(SCARD_W_CHV_BLOCKED) - CHK_ERRA(SCARD_W_EOF) - CHK_ERRA(SCARD_W_CANCELLED_BY_USER) - CHK_ERR_WIN32_ONLY(ERROR_INVALID_FUNCTION, "ERROR_INVALID_FUNCTION") - CHK_ERR_WIN32A(ERROR_FILE_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_PATH_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_TOO_MANY_OPEN_FILES) - CHK_ERRA(ERROR_ACCESS_DENIED) - CHK_ERRA(ERROR_INVALID_HANDLE) - CHK_ERR_WIN32A(ERROR_ARENA_TRASHED) - CHK_ERR_WIN32A(ERROR_NOT_ENOUGH_MEMORY) - CHK_ERR_WIN32A(ERROR_INVALID_BLOCK) - CHK_ERR_WIN32A(ERROR_BAD_ENVIRONMENT) - CHK_ERR_WIN32A(ERROR_BAD_FORMAT) - CHK_ERR_WIN32A(ERROR_INVALID_ACCESS) - CHK_ERR_WIN32A(ERROR_INVALID_DATA) - CHK_ERRA(ERROR_OUTOFMEMORY) - CHK_ERR_WIN32A(ERROR_INVALID_DRIVE) - CHK_ERR_WIN32A(ERROR_CURRENT_DIRECTORY) - CHK_ERR_WIN32A(ERROR_NOT_SAME_DEVICE) - CHK_ERR_WIN32A(ERROR_NO_MORE_FILES) - CHK_ERR_WIN32A(ERROR_WRITE_PROTECT) - CHK_ERR_WIN32A(ERROR_BAD_UNIT) - CHK_ERR_WIN32A(ERROR_NOT_READY) - CHK_ERR_WIN32A(ERROR_BAD_COMMAND) - CHK_ERR_WIN32A(ERROR_CRC) - CHK_ERR_WIN32A(ERROR_BAD_LENGTH) - CHK_ERR_WIN32A(ERROR_SEEK) - CHK_ERR_WIN32A(ERROR_NOT_DOS_DISK) - CHK_ERR_WIN32A(ERROR_SECTOR_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_OUT_OF_PAPER) - CHK_ERR_WIN32A(ERROR_WRITE_FAULT) - CHK_ERR_WIN32A(ERROR_READ_FAULT) - CHK_ERR_WIN32A(ERROR_GEN_FAILURE) - CHK_ERR_WIN32A(ERROR_SHARING_VIOLATION) - CHK_ERR_WIN32A(ERROR_LOCK_VIOLATION) - CHK_ERR_WIN32A(ERROR_WRONG_DISK) - CHK_ERR_WIN32A(ERROR_SHARING_BUFFER_EXCEEDED) - CHK_ERR_WIN32A(ERROR_HANDLE_EOF) - CHK_ERR_WIN32A(ERROR_HANDLE_DISK_FULL) - CHK_ERR_WIN32A(ERROR_NOT_SUPPORTED) - CHK_ERR_WIN32A(ERROR_REM_NOT_LIST) - CHK_ERR_WIN32A(ERROR_DUP_NAME) - CHK_ERR_WIN32A(ERROR_BAD_NETPATH) - CHK_ERR_WIN32A(ERROR_NETWORK_BUSY) - CHK_ERR_WIN32A(ERROR_DEV_NOT_EXIST) - CHK_ERR_WIN32A(ERROR_TOO_MANY_CMDS) - CHK_ERR_WIN32A(ERROR_ADAP_HDW_ERR) - CHK_ERR_WIN32A(ERROR_BAD_NET_RESP) - CHK_ERR_WIN32A(ERROR_UNEXP_NET_ERR) - CHK_ERR_WIN32A(ERROR_BAD_REM_ADAP) - CHK_ERR_WIN32A(ERROR_PRINTQ_FULL) - CHK_ERR_WIN32A(ERROR_NO_SPOOL_SPACE) - CHK_ERR_WIN32A(ERROR_PRINT_CANCELLED) - CHK_ERR_WIN32A(ERROR_NETNAME_DELETED) - CHK_ERR_WIN32A(ERROR_NETWORK_ACCESS_DENIED) - CHK_ERR_WIN32A(ERROR_BAD_DEV_TYPE) - CHK_ERR_WIN32A(ERROR_BAD_NET_NAME) - CHK_ERR_WIN32A(ERROR_TOO_MANY_NAMES) - CHK_ERR_WIN32A(ERROR_TOO_MANY_SESS) - CHK_ERR_WIN32A(ERROR_SHARING_PAUSED) - CHK_ERR_WIN32A(ERROR_REQ_NOT_ACCEP) - CHK_ERR_WIN32A(ERROR_REDIR_PAUSED) - CHK_ERR_WIN32A(ERROR_FILE_EXISTS) - CHK_ERR_WIN32A(ERROR_CANNOT_MAKE) - CHK_ERR_WIN32A(ERROR_FAIL_I24) - CHK_ERR_WIN32A(ERROR_OUT_OF_STRUCTURES) - CHK_ERR_WIN32A(ERROR_ALREADY_ASSIGNED) - CHK_ERR_WIN32A(ERROR_INVALID_PASSWORD) - CHK_ERRA(ERROR_INVALID_PARAMETER) - CHK_ERR_WIN32A(ERROR_NET_WRITE_FAULT) - CHK_ERR_WIN32A(ERROR_NO_PROC_SLOTS) - CHK_ERR_WIN32A(ERROR_TOO_MANY_SEMAPHORES) - CHK_ERR_WIN32A(ERROR_EXCL_SEM_ALREADY_OWNED) - CHK_ERR_WIN32A(ERROR_SEM_IS_SET) - CHK_ERR_WIN32A(ERROR_TOO_MANY_SEM_REQUESTS) - CHK_ERR_WIN32A(ERROR_INVALID_AT_INTERRUPT_TIME) - CHK_ERR_WIN32A(ERROR_SEM_OWNER_DIED) - CHK_ERR_WIN32A(ERROR_SEM_USER_LIMIT) - CHK_ERR_WIN32A(ERROR_DISK_CHANGE) - CHK_ERR_WIN32A(ERROR_DRIVE_LOCKED) - CHK_ERR_WIN32A(ERROR_BROKEN_PIPE) - CHK_ERR_WIN32A(ERROR_OPEN_FAILED) - CHK_ERR_WIN32A(ERROR_BUFFER_OVERFLOW) - CHK_ERR_WIN32A(ERROR_DISK_FULL) - CHK_ERR_WIN32A(ERROR_NO_MORE_SEARCH_HANDLES) - CHK_ERR_WIN32A(ERROR_INVALID_TARGET_HANDLE) - CHK_ERR_WIN32A(ERROR_INVALID_CATEGORY) - CHK_ERR_WIN32A(ERROR_INVALID_VERIFY_SWITCH) - CHK_ERR_WIN32A(ERROR_BAD_DRIVER_LEVEL) - CHK_ERR_WIN32A(ERROR_CALL_NOT_IMPLEMENTED) - CHK_ERR_WIN32A(ERROR_SEM_TIMEOUT) - CHK_ERR_WIN32A(ERROR_INSUFFICIENT_BUFFER) - CHK_ERR_WIN32A(ERROR_INVALID_NAME) - CHK_ERR_WIN32A(ERROR_INVALID_LEVEL) - CHK_ERR_WIN32A(ERROR_NO_VOLUME_LABEL) - CHK_ERR_WIN32A(ERROR_MOD_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_PROC_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_WAIT_NO_CHILDREN) - CHK_ERR_WIN32A(ERROR_CHILD_NOT_COMPLETE) - CHK_ERR_WIN32A(ERROR_DIRECT_ACCESS_HANDLE) - CHK_ERR_WIN32A(ERROR_NEGATIVE_SEEK) - CHK_ERR_WIN32A(ERROR_SEEK_ON_DEVICE) - CHK_ERR_WIN32A(ERROR_IS_JOIN_TARGET) - CHK_ERR_WIN32A(ERROR_IS_JOINED) - CHK_ERR_WIN32A(ERROR_IS_SUBSTED) - CHK_ERR_WIN32A(ERROR_NOT_JOINED) - CHK_ERR_WIN32A(ERROR_NOT_SUBSTED) - CHK_ERR_WIN32A(ERROR_JOIN_TO_JOIN) - CHK_ERR_WIN32A(ERROR_SUBST_TO_SUBST) - CHK_ERR_WIN32A(ERROR_JOIN_TO_SUBST) - CHK_ERR_WIN32A(ERROR_SUBST_TO_JOIN) - CHK_ERR_WIN32A(ERROR_BUSY_DRIVE) - CHK_ERR_WIN32A(ERROR_SAME_DRIVE) - CHK_ERR_WIN32A(ERROR_DIR_NOT_ROOT) - CHK_ERR_WIN32A(ERROR_DIR_NOT_EMPTY) - CHK_ERR_WIN32A(ERROR_IS_SUBST_PATH) - CHK_ERR_WIN32A(ERROR_IS_JOIN_PATH) - CHK_ERR_WIN32A(ERROR_PATH_BUSY) - CHK_ERR_WIN32A(ERROR_IS_SUBST_TARGET) - CHK_ERR_WIN32A(ERROR_SYSTEM_TRACE) - CHK_ERR_WIN32A(ERROR_INVALID_EVENT_COUNT) - CHK_ERR_WIN32A(ERROR_TOO_MANY_MUXWAITERS) - CHK_ERR_WIN32A(ERROR_INVALID_LIST_FORMAT) - CHK_ERR_WIN32A(ERROR_LABEL_TOO_LONG) - CHK_ERR_WIN32A(ERROR_TOO_MANY_TCBS) - CHK_ERR_WIN32A(ERROR_SIGNAL_REFUSED) - CHK_ERR_WIN32A(ERROR_DISCARDED) - CHK_ERR_WIN32A(ERROR_NOT_LOCKED) - CHK_ERR_WIN32A(ERROR_BAD_THREADID_ADDR) - CHK_ERR_WIN32A(ERROR_BAD_ARGUMENTS) - CHK_ERR_WIN32A(ERROR_BAD_PATHNAME) - CHK_ERR_WIN32A(ERROR_SIGNAL_PENDING) - CHK_ERR_WIN32A(ERROR_MAX_THRDS_REACHED) - CHK_ERR_WIN32A(ERROR_LOCK_FAILED) - CHK_ERR_WIN32A(ERROR_BUSY) - CHK_ERR_WIN32A(ERROR_CANCEL_VIOLATION) - CHK_ERR_WIN32A(ERROR_ATOMIC_LOCKS_NOT_SUPPORTED) - CHK_ERR_WIN32A(ERROR_INVALID_SEGMENT_NUMBER) - CHK_ERR_WIN32A(ERROR_INVALID_ORDINAL) - CHK_ERR_WIN32A(ERROR_ALREADY_EXISTS) - CHK_ERR_WIN32A(ERROR_INVALID_FLAG_NUMBER) - CHK_ERR_WIN32A(ERROR_SEM_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_INVALID_STARTING_CODESEG) - CHK_ERR_WIN32A(ERROR_INVALID_STACKSEG) - CHK_ERR_WIN32A(ERROR_INVALID_MODULETYPE) - CHK_ERR_WIN32A(ERROR_INVALID_EXE_SIGNATURE) - CHK_ERR_WIN32A(ERROR_EXE_MARKED_INVALID) - CHK_ERR_WIN32A(ERROR_BAD_EXE_FORMAT) - CHK_ERR_WIN32A(ERROR_ITERATED_DATA_EXCEEDS_64k) - CHK_ERR_WIN32A(ERROR_INVALID_MINALLOCSIZE) - CHK_ERR_WIN32A(ERROR_DYNLINK_FROM_INVALID_RING) - CHK_ERR_WIN32A(ERROR_IOPL_NOT_ENABLED) - CHK_ERR_WIN32A(ERROR_INVALID_SEGDPL) - CHK_ERR_WIN32A(ERROR_AUTODATASEG_EXCEEDS_64k) - CHK_ERRA(ERROR_RING2SEG_MUST_BE_MOVABLE) - CHK_ERRA(ERROR_RELOC_CHAIN_XEEDS_SEGLIM) - CHK_ERR_WIN32A(ERROR_INFLOOP_IN_RELOC_CHAIN) - CHK_ERR_WIN32A(ERROR_ENVVAR_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_NO_SIGNAL_SENT) - CHK_ERR_WIN32A(ERROR_FILENAME_EXCED_RANGE) - CHK_ERR_WIN32A(ERROR_RING2_STACK_IN_USE) - CHK_ERR_WIN32A(ERROR_META_EXPANSION_TOO_LONG) - CHK_ERR_WIN32A(ERROR_INVALID_SIGNAL_NUMBER) - CHK_ERR_WIN32A(ERROR_THREAD_1_INACTIVE) - CHK_ERR_WIN32A(ERROR_LOCKED) - CHK_ERR_WIN32A(ERROR_TOO_MANY_MODULES) - CHK_ERR_WIN32A(ERROR_NESTING_NOT_ALLOWED) - CHK_ERR_WIN32A(ERROR_EXE_MACHINE_TYPE_MISMATCH) - CHK_ERR_WIN32A(ERROR_BAD_PIPE) - CHK_ERR_WIN32A(ERROR_PIPE_BUSY) - CHK_ERR_WIN32A(ERROR_NO_DATA) - CHK_ERR_WIN32A(ERROR_PIPE_NOT_CONNECTED) - CHK_ERR_WIN32A(ERROR_MORE_DATA) - CHK_ERR_WIN32A(ERROR_VC_DISCONNECTED) - CHK_ERR_WIN32A(ERROR_INVALID_EA_NAME) - CHK_ERR_WIN32A(ERROR_EA_LIST_INCONSISTENT) - CHK_ERR_WIN32A(WAIT_TIMEOUT) - CHK_ERR_WIN32A(ERROR_NO_MORE_ITEMS) - CHK_ERR_WIN32A(ERROR_CANNOT_COPY) - CHK_ERR_WIN32A(ERROR_DIRECTORY) - CHK_ERR_WIN32A(ERROR_EAS_DIDNT_FIT) - CHK_ERR_WIN32A(ERROR_EA_FILE_CORRUPT) - CHK_ERR_WIN32A(ERROR_EA_TABLE_FULL) - CHK_ERR_WIN32A(ERROR_INVALID_EA_HANDLE) - CHK_ERR_WIN32A(ERROR_EAS_NOT_SUPPORTED) - CHK_ERR_WIN32A(ERROR_NOT_OWNER) - CHK_ERR_WIN32A(ERROR_TOO_MANY_POSTS) - CHK_ERR_WIN32A(ERROR_PARTIAL_COPY) - CHK_ERR_WIN32A(ERROR_OPLOCK_NOT_GRANTED) - CHK_ERR_WIN32A(ERROR_INVALID_OPLOCK_PROTOCOL) - CHK_ERR_WIN32A(ERROR_MR_MID_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_INVALID_ADDRESS) - CHK_ERR_WIN32A(ERROR_ARITHMETIC_OVERFLOW) - CHK_ERR_WIN32A(ERROR_PIPE_CONNECTED) - CHK_ERR_WIN32A(ERROR_PIPE_LISTENING) - CHK_ERR_WIN32A(ERROR_EA_ACCESS_DENIED) - CHK_ERR_WIN32A(ERROR_OPERATION_ABORTED) - CHK_ERR_WIN32A(ERROR_IO_INCOMPLETE) - CHK_ERR_WIN32A(ERROR_IO_PENDING) - CHK_ERR_WIN32A(ERROR_NOACCESS) - CHK_ERR_WIN32A(ERROR_SWAPERROR) - CHK_ERR_WIN32A(ERROR_STACK_OVERFLOW) - CHK_ERR_WIN32A(ERROR_INVALID_MESSAGE) - CHK_ERR_WIN32A(ERROR_CAN_NOT_COMPLETE) - CHK_ERR_WIN32A(ERROR_INVALID_FLAGS) - CHK_ERR_WIN32A(ERROR_UNRECOGNIZED_VOLUME) - CHK_ERR_WIN32A(ERROR_FILE_INVALID) - CHK_ERR_WIN32A(ERROR_FULLSCREEN_MODE) - CHK_ERR_WIN32A(ERROR_NO_TOKEN) - CHK_ERR_WIN32A(ERROR_BADDB) - CHK_ERR_WIN32A(ERROR_BADKEY) - CHK_ERR_WIN32A(ERROR_CANTOPEN) - CHK_ERR_WIN32A(ERROR_CANTREAD) - CHK_ERR_WIN32A(ERROR_CANTWRITE) - CHK_ERR_WIN32A(ERROR_REGISTRY_RECOVERED) - CHK_ERR_WIN32A(ERROR_REGISTRY_CORRUPT) - CHK_ERR_WIN32A(ERROR_REGISTRY_IO_FAILED) - CHK_ERR_WIN32A(ERROR_NOT_REGISTRY_FILE) - CHK_ERR_WIN32A(ERROR_KEY_DELETED) - CHK_ERR_WIN32A(ERROR_NO_LOG_SPACE) - CHK_ERR_WIN32A(ERROR_KEY_HAS_CHILDREN) - CHK_ERR_WIN32A(ERROR_CHILD_MUST_BE_VOLATILE) - CHK_ERR_WIN32A(ERROR_NOTIFY_ENUM_DIR) - CHK_ERR_WIN32A(ERROR_DEPENDENT_SERVICES_RUNNING) - CHK_ERR_WIN32A(ERROR_INVALID_SERVICE_CONTROL) - CHK_ERR_WIN32A(ERROR_SERVICE_REQUEST_TIMEOUT) - CHK_ERR_WIN32A(ERROR_SERVICE_NO_THREAD) - CHK_ERR_WIN32A(ERROR_SERVICE_DATABASE_LOCKED) - CHK_ERR_WIN32A(ERROR_SERVICE_ALREADY_RUNNING) - CHK_ERR_WIN32A(ERROR_INVALID_SERVICE_ACCOUNT) - CHK_ERR_WIN32A(ERROR_SERVICE_DISABLED) - CHK_ERR_WIN32A(ERROR_CIRCULAR_DEPENDENCY) - CHK_ERR_WIN32A(ERROR_SERVICE_DOES_NOT_EXIST) - CHK_ERR_WIN32A(ERROR_SERVICE_CANNOT_ACCEPT_CTRL) - CHK_ERR_WIN32A(ERROR_SERVICE_NOT_ACTIVE) - CHK_ERR_WIN32A(ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) - CHK_ERR_WIN32A(ERROR_EXCEPTION_IN_SERVICE) - CHK_ERR_WIN32A(ERROR_DATABASE_DOES_NOT_EXIST) - CHK_ERR_WIN32A(ERROR_SERVICE_SPECIFIC_ERROR) - CHK_ERR_WIN32A(ERROR_PROCESS_ABORTED) - CHK_ERR_WIN32A(ERROR_SERVICE_DEPENDENCY_FAIL) - CHK_ERR_WIN32A(ERROR_SERVICE_LOGON_FAILED) - CHK_ERR_WIN32A(ERROR_SERVICE_START_HANG) - CHK_ERR_WIN32A(ERROR_INVALID_SERVICE_LOCK) - CHK_ERR_WIN32A(ERROR_SERVICE_MARKED_FOR_DELETE) - CHK_ERR_WIN32A(ERROR_SERVICE_EXISTS) - CHK_ERR_WIN32A(ERROR_ALREADY_RUNNING_LKG) - CHK_ERR_WIN32A(ERROR_SERVICE_DEPENDENCY_DELETED) - CHK_ERR_WIN32A(ERROR_BOOT_ALREADY_ACCEPTED) - CHK_ERR_WIN32A(ERROR_SERVICE_NEVER_STARTED) - CHK_ERR_WIN32A(ERROR_DUPLICATE_SERVICE_NAME) - CHK_ERR_WIN32A(ERROR_DIFFERENT_SERVICE_ACCOUNT) - CHK_ERR_WIN32A(ERROR_CANNOT_DETECT_DRIVER_FAILURE) - CHK_ERR_WIN32A(ERROR_CANNOT_DETECT_PROCESS_ABORT) - CHK_ERR_WIN32A(ERROR_NO_RECOVERY_PROGRAM) - CHK_ERR_WIN32A(ERROR_SERVICE_NOT_IN_EXE) - CHK_ERR_WIN32A(ERROR_END_OF_MEDIA) - CHK_ERR_WIN32A(ERROR_FILEMARK_DETECTED) - CHK_ERR_WIN32A(ERROR_BEGINNING_OF_MEDIA) - CHK_ERR_WIN32A(ERROR_SETMARK_DETECTED) - CHK_ERR_WIN32A(ERROR_NO_DATA_DETECTED) - CHK_ERR_WIN32A(ERROR_PARTITION_FAILURE) - CHK_ERR_WIN32A(ERROR_INVALID_BLOCK_LENGTH) - CHK_ERR_WIN32A(ERROR_DEVICE_NOT_PARTITIONED) - CHK_ERR_WIN32A(ERROR_UNABLE_TO_LOCK_MEDIA) - CHK_ERR_WIN32A(ERROR_UNABLE_TO_UNLOAD_MEDIA) - CHK_ERR_WIN32A(ERROR_MEDIA_CHANGED) - CHK_ERR_WIN32A(ERROR_BUS_RESET) - CHK_ERR_WIN32A(ERROR_NO_MEDIA_IN_DRIVE) - CHK_ERR_WIN32A(ERROR_NO_UNICODE_TRANSLATION) - CHK_ERR_WIN32A(ERROR_DLL_INIT_FAILED) - CHK_ERR_WIN32A(ERROR_SHUTDOWN_IN_PROGRESS) - CHK_ERR_WIN32A(ERROR_NO_SHUTDOWN_IN_PROGRESS) - CHK_ERR_WIN32A(ERROR_IO_DEVICE) - CHK_ERR_WIN32A(ERROR_SERIAL_NO_DEVICE) - CHK_ERR_WIN32A(ERROR_IRQ_BUSY) - CHK_ERR_WIN32A(ERROR_MORE_WRITES) - CHK_ERR_WIN32A(ERROR_COUNTER_TIMEOUT) - CHK_ERR_WIN32A(ERROR_FLOPPY_ID_MARK_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_FLOPPY_WRONG_CYLINDER) - CHK_ERR_WIN32A(ERROR_FLOPPY_UNKNOWN_ERROR) - CHK_ERR_WIN32A(ERROR_FLOPPY_BAD_REGISTERS) - CHK_ERR_WIN32A(ERROR_DISK_RECALIBRATE_FAILED) - CHK_ERR_WIN32A(ERROR_DISK_OPERATION_FAILED) - CHK_ERR_WIN32A(ERROR_DISK_RESET_FAILED) - CHK_ERR_WIN32A(ERROR_EOM_OVERFLOW) - CHK_ERR_WIN32A(ERROR_NOT_ENOUGH_SERVER_MEMORY) - CHK_ERR_WIN32A(ERROR_POSSIBLE_DEADLOCK) - CHK_ERR_WIN32A(ERROR_MAPPED_ALIGNMENT) - CHK_ERR_WIN32A(ERROR_SET_POWER_STATE_VETOED) - CHK_ERR_WIN32A(ERROR_SET_POWER_STATE_FAILED) - CHK_ERR_WIN32A(ERROR_TOO_MANY_LINKS) - CHK_ERR_WIN32A(ERROR_OLD_WIN_VERSION) - CHK_ERR_WIN32A(ERROR_APP_WRONG_OS) - CHK_ERR_WIN32A(ERROR_SINGLE_INSTANCE_APP) - CHK_ERR_WIN32A(ERROR_RMODE_APP) - CHK_ERR_WIN32A(ERROR_INVALID_DLL) - CHK_ERR_WIN32A(ERROR_NO_ASSOCIATION) - CHK_ERR_WIN32A(ERROR_DDE_FAIL) - CHK_ERR_WIN32A(ERROR_DLL_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_NO_MORE_USER_HANDLES) - CHK_ERR_WIN32A(ERROR_MESSAGE_SYNC_ONLY) - CHK_ERR_WIN32A(ERROR_SOURCE_ELEMENT_EMPTY) - CHK_ERR_WIN32A(ERROR_DESTINATION_ELEMENT_FULL) - CHK_ERR_WIN32A(ERROR_ILLEGAL_ELEMENT_ADDRESS) - CHK_ERR_WIN32A(ERROR_MAGAZINE_NOT_PRESENT) - CHK_ERR_WIN32A(ERROR_DEVICE_REINITIALIZATION_NEEDED) - CHK_ERR_WIN32A(ERROR_DEVICE_REQUIRES_CLEANING) - CHK_ERR_WIN32A(ERROR_DEVICE_DOOR_OPEN) - CHK_ERR_WIN32A(ERROR_DEVICE_NOT_CONNECTED) - CHK_ERR_WIN32A(ERROR_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_NO_MATCH) - CHK_ERR_WIN32A(ERROR_SET_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_POINT_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_NO_TRACKING_SERVICE) - CHK_ERR_WIN32A(ERROR_NO_VOLUME_ID) - CHK_ERR_WIN32A(ERROR_UNABLE_TO_REMOVE_REPLACED) - CHK_ERR_WIN32A(ERROR_UNABLE_TO_MOVE_REPLACEMENT) - CHK_ERR_WIN32A(ERROR_UNABLE_TO_MOVE_REPLACEMENT_2) - CHK_ERR_WIN32A(ERROR_JOURNAL_DELETE_IN_PROGRESS) - CHK_ERR_WIN32A(ERROR_JOURNAL_NOT_ACTIVE) - CHK_ERR_WIN32A(ERROR_POTENTIAL_FILE_FOUND) - CHK_ERR_WIN32A(ERROR_BAD_DEVICE) - CHK_ERR_WIN32A(ERROR_CONNECTION_UNAVAIL) - CHK_ERR_WIN32A(ERROR_DEVICE_ALREADY_REMEMBERED) - CHK_ERR_WIN32A(ERROR_NO_NET_OR_BAD_PATH) - CHK_ERR_WIN32A(ERROR_BAD_PROVIDER) - CHK_ERR_WIN32A(ERROR_CANNOT_OPEN_PROFILE) - CHK_ERR_WIN32A(ERROR_BAD_PROFILE) - CHK_ERR_WIN32A(ERROR_NOT_CONTAINER) - CHK_ERR_WIN32A(ERROR_EXTENDED_ERROR) - CHK_ERR_WIN32A(ERROR_INVALID_GROUPNAME) - CHK_ERR_WIN32A(ERROR_INVALID_COMPUTERNAME) - CHK_ERR_WIN32A(ERROR_INVALID_EVENTNAME) - CHK_ERR_WIN32A(ERROR_INVALID_DOMAINNAME) - CHK_ERR_WIN32A(ERROR_INVALID_SERVICENAME) - CHK_ERR_WIN32A(ERROR_INVALID_NETNAME) - CHK_ERR_WIN32A(ERROR_INVALID_SHARENAME) - CHK_ERR_WIN32A(ERROR_INVALID_PASSWORDNAME) - CHK_ERR_WIN32A(ERROR_INVALID_MESSAGENAME) - CHK_ERR_WIN32A(ERROR_INVALID_MESSAGEDEST) - CHK_ERR_WIN32A(ERROR_SESSION_CREDENTIAL_CONFLICT) - CHK_ERR_WIN32A(ERROR_REMOTE_SESSION_LIMIT_EXCEEDED) - CHK_ERR_WIN32A(ERROR_DUP_DOMAINNAME) - CHK_ERR_WIN32A(ERROR_NO_NETWORK) - CHK_ERR_WIN32A(ERROR_CANCELLED) - CHK_ERR_WIN32A(ERROR_USER_MAPPED_FILE) - CHK_ERR_WIN32A(ERROR_CONNECTION_REFUSED) - CHK_ERR_WIN32A(ERROR_GRACEFUL_DISCONNECT) - CHK_ERR_WIN32A(ERROR_ADDRESS_ALREADY_ASSOCIATED) - CHK_ERR_WIN32A(ERROR_ADDRESS_NOT_ASSOCIATED) - CHK_ERR_WIN32A(ERROR_CONNECTION_INVALID) - CHK_ERR_WIN32A(ERROR_CONNECTION_ACTIVE) - CHK_ERR_WIN32A(ERROR_NETWORK_UNREACHABLE) - CHK_ERR_WIN32A(ERROR_HOST_UNREACHABLE) - CHK_ERR_WIN32A(ERROR_PROTOCOL_UNREACHABLE) - CHK_ERR_WIN32A(ERROR_PORT_UNREACHABLE) - CHK_ERR_WIN32A(ERROR_REQUEST_ABORTED) - CHK_ERR_WIN32A(ERROR_CONNECTION_ABORTED) - CHK_ERR_WIN32A(ERROR_RETRY) - CHK_ERR_WIN32A(ERROR_CONNECTION_COUNT_LIMIT) - CHK_ERR_WIN32A(ERROR_LOGIN_TIME_RESTRICTION) - CHK_ERR_WIN32A(ERROR_LOGIN_WKSTA_RESTRICTION) - CHK_ERR_WIN32A(ERROR_INCORRECT_ADDRESS) - CHK_ERR_WIN32A(ERROR_ALREADY_REGISTERED) - CHK_ERR_WIN32A(ERROR_SERVICE_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_NOT_AUTHENTICATED) - CHK_ERR_WIN32A(ERROR_NOT_LOGGED_ON) - CHK_ERR_WIN32A(ERROR_CONTINUE) - CHK_ERR_WIN32A(ERROR_ALREADY_INITIALIZED) - CHK_ERR_WIN32A(ERROR_NO_MORE_DEVICES) - CHK_ERR_WIN32A(ERROR_NO_SUCH_SITE) - CHK_ERR_WIN32A(ERROR_DOMAIN_CONTROLLER_EXISTS) - CHK_ERR_WIN32A(ERROR_NOT_ALL_ASSIGNED) - CHK_ERR_WIN32A(ERROR_SOME_NOT_MAPPED) - CHK_ERR_WIN32A(ERROR_NO_QUOTAS_FOR_ACCOUNT) - CHK_ERR_WIN32A(ERROR_LOCAL_USER_SESSION_KEY) - CHK_ERR_WIN32A(ERROR_NULL_LM_PASSWORD) - CHK_ERR_WIN32A(ERROR_UNKNOWN_REVISION) - CHK_ERR_WIN32A(ERROR_REVISION_MISMATCH) - CHK_ERR_WIN32A(ERROR_INVALID_OWNER) - CHK_ERR_WIN32A(ERROR_INVALID_PRIMARY_GROUP) - CHK_ERR_WIN32A(ERROR_NO_IMPERSONATION_TOKEN) - CHK_ERR_WIN32A(ERROR_CANT_DISABLE_MANDATORY) - CHK_ERR_WIN32A(ERROR_NO_LOGON_SERVERS) - CHK_ERR_WIN32A(ERROR_NO_SUCH_LOGON_SESSION) - CHK_ERR_WIN32A(ERROR_NO_SUCH_PRIVILEGE) - CHK_ERR_WIN32A(ERROR_PRIVILEGE_NOT_HELD) - CHK_ERR_WIN32A(ERROR_INVALID_ACCOUNT_NAME) - CHK_ERR_WIN32A(ERROR_USER_EXISTS) - CHK_ERR_WIN32A(ERROR_NO_SUCH_USER) - CHK_ERR_WIN32A(ERROR_GROUP_EXISTS) - CHK_ERR_WIN32A(ERROR_NO_SUCH_GROUP) - CHK_ERR_WIN32A(ERROR_MEMBER_IN_GROUP) - CHK_ERR_WIN32A(ERROR_MEMBER_NOT_IN_GROUP) - CHK_ERR_WIN32A(ERROR_LAST_ADMIN) - CHK_ERR_WIN32A(ERROR_WRONG_PASSWORD) - CHK_ERR_WIN32A(ERROR_ILL_FORMED_PASSWORD) - CHK_ERR_WIN32A(ERROR_PASSWORD_RESTRICTION) - CHK_ERR_WIN32A(ERROR_LOGON_FAILURE) - CHK_ERR_WIN32A(ERROR_ACCOUNT_RESTRICTION) - CHK_ERR_WIN32A(ERROR_INVALID_LOGON_HOURS) - CHK_ERR_WIN32A(ERROR_INVALID_WORKSTATION) - CHK_ERR_WIN32A(ERROR_PASSWORD_EXPIRED) - CHK_ERR_WIN32A(ERROR_ACCOUNT_DISABLED) - CHK_ERR_WIN32A(ERROR_NONE_MAPPED) - CHK_ERR_WIN32A(ERROR_TOO_MANY_LUIDS_REQUESTED) - CHK_ERR_WIN32A(ERROR_LUIDS_EXHAUSTED) - CHK_ERR_WIN32A(ERROR_INVALID_SUB_AUTHORITY) - CHK_ERR_WIN32A(ERROR_INVALID_ACL) - CHK_ERR_WIN32A(ERROR_INVALID_SID) - CHK_ERR_WIN32A(ERROR_INVALID_SECURITY_DESCR) - CHK_ERR_WIN32A(ERROR_BAD_INHERITANCE_ACL) - CHK_ERR_WIN32A(ERROR_SERVER_DISABLED) - CHK_ERR_WIN32A(ERROR_SERVER_NOT_DISABLED) - CHK_ERR_WIN32A(ERROR_INVALID_ID_AUTHORITY) - CHK_ERR_WIN32A(ERROR_ALLOTTED_SPACE_EXCEEDED) - CHK_ERR_WIN32A(ERROR_INVALID_GROUP_ATTRIBUTES) - CHK_ERR_WIN32A(ERROR_BAD_IMPERSONATION_LEVEL) - CHK_ERR_WIN32A(ERROR_CANT_OPEN_ANONYMOUS) - CHK_ERR_WIN32A(ERROR_BAD_VALIDATION_CLASS) - CHK_ERR_WIN32A(ERROR_BAD_TOKEN_TYPE) - CHK_ERR_WIN32A(ERROR_NO_SECURITY_ON_OBJECT) - CHK_ERR_WIN32A(ERROR_CANT_ACCESS_DOMAIN_INFO) - CHK_ERR_WIN32A(ERROR_INVALID_SERVER_STATE) - CHK_ERR_WIN32A(ERROR_INVALID_DOMAIN_STATE) - CHK_ERR_WIN32A(ERROR_INVALID_DOMAIN_ROLE) - CHK_ERR_WIN32A(ERROR_NO_SUCH_DOMAIN) - CHK_ERR_WIN32A(ERROR_DOMAIN_EXISTS) - CHK_ERR_WIN32A(ERROR_DOMAIN_LIMIT_EXCEEDED) - CHK_ERR_WIN32A(ERROR_INTERNAL_DB_CORRUPTION) - CHK_ERR_WIN32A(ERROR_INTERNAL_ERROR) - CHK_ERR_WIN32A(ERROR_GENERIC_NOT_MAPPED) - CHK_ERR_WIN32A(ERROR_BAD_DESCRIPTOR_FORMAT) - CHK_ERR_WIN32A(ERROR_NOT_LOGON_PROCESS) - CHK_ERR_WIN32A(ERROR_LOGON_SESSION_EXISTS) - CHK_ERR_WIN32A(ERROR_NO_SUCH_PACKAGE) - CHK_ERR_WIN32A(ERROR_BAD_LOGON_SESSION_STATE) - CHK_ERR_WIN32A(ERROR_LOGON_SESSION_COLLISION) - CHK_ERR_WIN32A(ERROR_INVALID_LOGON_TYPE) - CHK_ERR_WIN32A(ERROR_CANNOT_IMPERSONATE) - CHK_ERR_WIN32A(ERROR_RXACT_INVALID_STATE) - CHK_ERR_WIN32A(ERROR_RXACT_COMMIT_FAILURE) - CHK_ERR_WIN32A(ERROR_SPECIAL_ACCOUNT) - CHK_ERR_WIN32A(ERROR_SPECIAL_GROUP) - CHK_ERR_WIN32A(ERROR_SPECIAL_USER) - CHK_ERR_WIN32A(ERROR_MEMBERS_PRIMARY_GROUP) - CHK_ERR_WIN32A(ERROR_TOKEN_ALREADY_IN_USE) - CHK_ERR_WIN32A(ERROR_NO_SUCH_ALIAS) - CHK_ERR_WIN32A(ERROR_MEMBER_NOT_IN_ALIAS) - CHK_ERR_WIN32A(ERROR_MEMBER_IN_ALIAS) - CHK_ERR_WIN32A(ERROR_ALIAS_EXISTS) - CHK_ERR_WIN32A(ERROR_LOGON_NOT_GRANTED) - CHK_ERR_WIN32A(ERROR_TOO_MANY_SECRETS) - CHK_ERR_WIN32A(ERROR_SECRET_TOO_LONG) - CHK_ERR_WIN32A(ERROR_INTERNAL_DB_ERROR) - CHK_ERR_WIN32A(ERROR_TOO_MANY_CONTEXT_IDS) - CHK_ERR_WIN32A(ERROR_LOGON_TYPE_NOT_GRANTED) - CHK_ERR_WIN32A(ERROR_NT_CROSS_ENCRYPTION_REQUIRED) - CHK_ERR_WIN32A(ERROR_NO_SUCH_MEMBER) - CHK_ERR_WIN32A(ERROR_INVALID_MEMBER) - CHK_ERR_WIN32A(ERROR_TOO_MANY_SIDS) - CHK_ERR_WIN32A(ERROR_LM_CROSS_ENCRYPTION_REQUIRED) - CHK_ERR_WIN32A(ERROR_NO_INHERITANCE) - CHK_ERR_WIN32A(ERROR_FILE_CORRUPT) - CHK_ERR_WIN32A(ERROR_DISK_CORRUPT) - CHK_ERR_WIN32A(ERROR_NO_USER_SESSION_KEY) - CHK_ERR_WIN32A(ERROR_LICENSE_QUOTA_EXCEEDED) - CHK_ERR_WIN32A(ERROR_WRONG_TARGET_NAME) - CHK_ERR_WIN32A(ERROR_MUTUAL_AUTH_FAILED) - CHK_ERR_WIN32A(ERROR_TIME_SKEW) - CHK_ERR_WIN32A(ERROR_INVALID_WINDOW_HANDLE) - CHK_ERR_WIN32A(ERROR_INVALID_MENU_HANDLE) - CHK_ERR_WIN32A(ERROR_INVALID_CURSOR_HANDLE) - CHK_ERR_WIN32A(ERROR_INVALID_ACCEL_HANDLE) - CHK_ERR_WIN32A(ERROR_INVALID_HOOK_HANDLE) - CHK_ERR_WIN32A(ERROR_INVALID_DWP_HANDLE) - CHK_ERR_WIN32A(ERROR_TLW_WITH_WSCHILD) - CHK_ERR_WIN32A(ERROR_CANNOT_FIND_WND_CLASS) - CHK_ERR_WIN32A(ERROR_WINDOW_OF_OTHER_THREAD) - CHK_ERR_WIN32A(ERROR_HOTKEY_ALREADY_REGISTERED) - CHK_ERR_WIN32A(ERROR_CLASS_ALREADY_EXISTS) - CHK_ERR_WIN32A(ERROR_CLASS_DOES_NOT_EXIST) - CHK_ERR_WIN32A(ERROR_CLASS_HAS_WINDOWS) - CHK_ERR_WIN32A(ERROR_INVALID_INDEX) - CHK_ERR_WIN32A(ERROR_INVALID_ICON_HANDLE) - CHK_ERR_WIN32A(ERROR_PRIVATE_DIALOG_INDEX) - CHK_ERR_WIN32A(ERROR_LISTBOX_ID_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_NO_WILDCARD_CHARACTERS) - CHK_ERR_WIN32A(ERROR_CLIPBOARD_NOT_OPEN) - CHK_ERR_WIN32A(ERROR_HOTKEY_NOT_REGISTERED) - CHK_ERR_WIN32A(ERROR_WINDOW_NOT_DIALOG) - CHK_ERR_WIN32A(ERROR_CONTROL_ID_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_INVALID_COMBOBOX_MESSAGE) - CHK_ERR_WIN32A(ERROR_WINDOW_NOT_COMBOBOX) - CHK_ERR_WIN32A(ERROR_INVALID_EDIT_HEIGHT) - CHK_ERR_WIN32A(ERROR_DC_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_INVALID_HOOK_FILTER) - CHK_ERR_WIN32A(ERROR_INVALID_FILTER_PROC) - CHK_ERR_WIN32A(ERROR_HOOK_NEEDS_HMOD) - CHK_ERR_WIN32A(ERROR_GLOBAL_ONLY_HOOK) - CHK_ERR_WIN32A(ERROR_JOURNAL_HOOK_SET) - CHK_ERR_WIN32A(ERROR_HOOK_NOT_INSTALLED) - CHK_ERR_WIN32A(ERROR_INVALID_LB_MESSAGE) - CHK_ERR_WIN32A(ERROR_SETCOUNT_ON_BAD_LB) - CHK_ERR_WIN32A(ERROR_LB_WITHOUT_TABSTOPS) - CHK_ERR_WIN32A(ERROR_DESTROY_OBJECT_OF_OTHER_THREAD) - CHK_ERR_WIN32A(ERROR_CHILD_WINDOW_MENU) - CHK_ERR_WIN32A(ERROR_NO_SYSTEM_MENU) - CHK_ERR_WIN32A(ERROR_INVALID_MSGBOX_STYLE) - CHK_ERR_WIN32A(ERROR_INVALID_SPI_VALUE) - CHK_ERR_WIN32A(ERROR_SCREEN_ALREADY_LOCKED) - CHK_ERR_WIN32A(ERROR_HWNDS_HAVE_DIFF_PARENT) - CHK_ERR_WIN32A(ERROR_NOT_CHILD_WINDOW) - CHK_ERR_WIN32A(ERROR_INVALID_GW_COMMAND) - CHK_ERR_WIN32A(ERROR_INVALID_THREAD_ID) - CHK_ERR_WIN32A(ERROR_NON_MDICHILD_WINDOW) - CHK_ERR_WIN32A(ERROR_POPUP_ALREADY_ACTIVE) - CHK_ERR_WIN32A(ERROR_NO_SCROLLBARS) - CHK_ERR_WIN32A(ERROR_INVALID_SCROLLBAR_RANGE) - CHK_ERR_WIN32A(ERROR_INVALID_SHOWWIN_COMMAND) - CHK_ERR_WIN32A(ERROR_NO_SYSTEM_RESOURCES) - CHK_ERR_WIN32A(ERROR_NONPAGED_SYSTEM_RESOURCES) - CHK_ERR_WIN32A(ERROR_PAGED_SYSTEM_RESOURCES) - CHK_ERR_WIN32A(ERROR_WORKING_SET_QUOTA) - CHK_ERR_WIN32A(ERROR_PAGEFILE_QUOTA) - CHK_ERR_WIN32A(ERROR_COMMITMENT_LIMIT) - CHK_ERR_WIN32A(ERROR_MENU_ITEM_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_INVALID_KEYBOARD_HANDLE) - CHK_ERR_WIN32A(ERROR_HOOK_TYPE_NOT_ALLOWED) - CHK_ERR_WIN32A(ERROR_REQUIRES_INTERACTIVE_WINDOWSTATION) - CHK_ERR_WIN32A(ERROR_TIMEOUT) - CHK_ERR_WIN32A(ERROR_INVALID_MONITOR_HANDLE) - CHK_ERR_WIN32A(ERROR_EVENTLOG_FILE_CORRUPT) - CHK_ERR_WIN32A(ERROR_EVENTLOG_CANT_START) - CHK_ERR_WIN32A(ERROR_LOG_FILE_FULL) - CHK_ERR_WIN32A(ERROR_EVENTLOG_FILE_CHANGED) - CHK_ERR_WIN32A(ERROR_INSTALL_USEREXIT) - CHK_ERR_WIN32A(ERROR_INSTALL_FAILURE) - CHK_ERR_WIN32A(ERROR_INSTALL_SUSPEND) - CHK_ERR_WIN32A(ERROR_UNKNOWN_PRODUCT) - CHK_ERR_WIN32A(ERROR_UNKNOWN_FEATURE) - CHK_ERR_WIN32A(ERROR_UNKNOWN_COMPONENT) - CHK_ERR_WIN32A(ERROR_UNKNOWN_PROPERTY) - CHK_ERR_WIN32A(ERROR_INVALID_HANDLE_STATE) - CHK_ERR_WIN32A(ERROR_BAD_CONFIGURATION) - CHK_ERR_WIN32A(ERROR_INDEX_ABSENT) - CHK_ERR_WIN32A(ERROR_INSTALL_SOURCE_ABSENT) - CHK_ERR_WIN32A(ERROR_PRODUCT_UNINSTALLED) - CHK_ERR_WIN32A(ERROR_BAD_QUERY_SYNTAX) - CHK_ERR_WIN32A(ERROR_INVALID_FIELD) - CHK_ERR_WIN32A(ERROR_DEVICE_REMOVED) - CHK_ERR_WIN32A(RPC_S_INVALID_STRING_BINDING) - CHK_ERR_WIN32A(RPC_S_WRONG_KIND_OF_BINDING) - CHK_ERR_WIN32A(RPC_S_INVALID_BINDING) - CHK_ERR_WIN32A(RPC_S_PROTSEQ_NOT_SUPPORTED) - CHK_ERR_WIN32A(RPC_S_INVALID_RPC_PROTSEQ) - CHK_ERR_WIN32A(RPC_S_INVALID_STRING_UUID) - CHK_ERR_WIN32A(RPC_S_INVALID_ENDPOINT_FORMAT) - CHK_ERR_WIN32A(RPC_S_INVALID_NET_ADDR) - CHK_ERR_WIN32A(RPC_S_NO_ENDPOINT_FOUND) - CHK_ERR_WIN32A(RPC_S_INVALID_TIMEOUT) - CHK_ERR_WIN32A(RPC_S_OBJECT_NOT_FOUND) - CHK_ERR_WIN32A(RPC_S_ALREADY_REGISTERED) - CHK_ERR_WIN32A(RPC_S_TYPE_ALREADY_REGISTERED) - CHK_ERR_WIN32A(RPC_S_ALREADY_LISTENING) - CHK_ERR_WIN32A(RPC_S_NO_PROTSEQS_REGISTERED) - CHK_ERR_WIN32A(RPC_S_NOT_LISTENING) - CHK_ERR_WIN32A(RPC_S_UNKNOWN_MGR_TYPE) - CHK_ERR_WIN32A(RPC_S_UNKNOWN_IF) - CHK_ERR_WIN32A(RPC_S_NO_BINDINGS) - CHK_ERR_WIN32A(RPC_S_NO_PROTSEQS) - CHK_ERR_WIN32A(RPC_S_CANT_CREATE_ENDPOINT) - CHK_ERR_WIN32A(RPC_S_OUT_OF_RESOURCES) - CHK_ERR_WIN32A(RPC_S_SERVER_UNAVAILABLE) - CHK_ERR_WIN32A(RPC_S_SERVER_TOO_BUSY) - CHK_ERR_WIN32A(RPC_S_INVALID_NETWORK_OPTIONS) - CHK_ERR_WIN32A(RPC_S_NO_CALL_ACTIVE) - CHK_ERR_WIN32A(RPC_S_CALL_FAILED) - CHK_ERR_WIN32A(RPC_S_CALL_FAILED_DNE) - CHK_ERR_WIN32A(RPC_S_PROTOCOL_ERROR) - CHK_ERR_WIN32A(RPC_S_UNSUPPORTED_TRANS_SYN) - CHK_ERR_WIN32A(RPC_S_UNSUPPORTED_TYPE) - CHK_ERR_WIN32A(RPC_S_INVALID_TAG) - CHK_ERR_WIN32A(RPC_S_INVALID_BOUND) - CHK_ERR_WIN32A(RPC_S_NO_ENTRY_NAME) - CHK_ERR_WIN32A(RPC_S_INVALID_NAME_SYNTAX) - CHK_ERR_WIN32A(RPC_S_UNSUPPORTED_NAME_SYNTAX) - CHK_ERR_WIN32A(RPC_S_UUID_NO_ADDRESS) - CHK_ERR_WIN32A(RPC_S_DUPLICATE_ENDPOINT) - CHK_ERR_WIN32A(RPC_S_UNKNOWN_AUTHN_TYPE) - CHK_ERR_WIN32A(RPC_S_MAX_CALLS_TOO_SMALL) - CHK_ERR_WIN32A(RPC_S_STRING_TOO_LONG) - CHK_ERR_WIN32A(RPC_S_PROTSEQ_NOT_FOUND) - CHK_ERR_WIN32A(RPC_S_PROCNUM_OUT_OF_RANGE) - CHK_ERR_WIN32A(RPC_S_BINDING_HAS_NO_AUTH) - CHK_ERR_WIN32A(RPC_S_UNKNOWN_AUTHN_SERVICE) - CHK_ERR_WIN32A(RPC_S_UNKNOWN_AUTHN_LEVEL) - CHK_ERR_WIN32A(RPC_S_INVALID_AUTH_IDENTITY) - CHK_ERR_WIN32A(RPC_S_UNKNOWN_AUTHZ_SERVICE) - CHK_ERR_WIN32A(EPT_S_INVALID_ENTRY) - CHK_ERR_WIN32A(EPT_S_CANT_PERFORM_OP) - CHK_ERR_WIN32A(EPT_S_NOT_REGISTERED) - CHK_ERR_WIN32A(RPC_S_NOTHING_TO_EXPORT) - CHK_ERR_WIN32A(RPC_S_INCOMPLETE_NAME) - CHK_ERR_WIN32A(RPC_S_INVALID_VERS_OPTION) - CHK_ERR_WIN32A(RPC_S_NO_MORE_MEMBERS) - CHK_ERR_WIN32A(RPC_S_NOT_ALL_OBJS_UNEXPORTED) - CHK_ERR_WIN32A(RPC_S_INTERFACE_NOT_FOUND) - CHK_ERR_WIN32A(RPC_S_ENTRY_ALREADY_EXISTS) - CHK_ERR_WIN32A(RPC_S_ENTRY_NOT_FOUND) - CHK_ERR_WIN32A(RPC_S_NAME_SERVICE_UNAVAILABLE) - CHK_ERR_WIN32A(RPC_S_INVALID_NAF_ID) - CHK_ERR_WIN32A(RPC_S_CANNOT_SUPPORT) - CHK_ERR_WIN32A(RPC_S_NO_CONTEXT_AVAILABLE) - CHK_ERR_WIN32A(RPC_S_INTERNAL_ERROR) - CHK_ERR_WIN32A(RPC_S_ZERO_DIVIDE) - CHK_ERR_WIN32A(RPC_S_ADDRESS_ERROR) - CHK_ERR_WIN32A(RPC_S_FP_DIV_ZERO) - CHK_ERR_WIN32A(RPC_S_FP_UNDERFLOW) - CHK_ERR_WIN32A(RPC_S_FP_OVERFLOW) - CHK_ERR_WIN32A(RPC_X_NO_MORE_ENTRIES) - CHK_ERR_WIN32A(RPC_X_SS_CHAR_TRANS_OPEN_FAIL) - CHK_ERR_WIN32A(RPC_X_SS_CHAR_TRANS_SHORT_FILE) - CHK_ERR_WIN32A(RPC_X_SS_IN_NULL_CONTEXT) - CHK_ERR_WIN32A(RPC_X_SS_CONTEXT_DAMAGED) - CHK_ERR_WIN32A(RPC_X_SS_HANDLES_MISMATCH) - CHK_ERR_WIN32A(RPC_X_SS_CANNOT_GET_CALL_HANDLE) - CHK_ERR_WIN32A(RPC_X_NULL_REF_POINTER) - CHK_ERR_WIN32A(RPC_X_ENUM_VALUE_OUT_OF_RANGE) - CHK_ERR_WIN32A(RPC_X_BYTE_COUNT_TOO_SMALL) - CHK_ERR_WIN32A(RPC_X_BAD_STUB_DATA) - CHK_ERR_WIN32A(ERROR_INVALID_USER_BUFFER) - CHK_ERR_WIN32A(ERROR_UNRECOGNIZED_MEDIA) - CHK_ERR_WIN32A(ERROR_NO_TRUST_LSA_SECRET) - CHK_ERR_WIN32A(ERROR_NO_TRUST_SAM_ACCOUNT) - CHK_ERR_WIN32A(ERROR_TRUSTED_DOMAIN_FAILURE) - CHK_ERR_WIN32A(ERROR_TRUSTED_RELATIONSHIP_FAILURE) - CHK_ERR_WIN32A(ERROR_TRUST_FAILURE) - CHK_ERR_WIN32A(RPC_S_CALL_IN_PROGRESS) - CHK_ERR_WIN32A(ERROR_NETLOGON_NOT_STARTED) - CHK_ERR_WIN32A(ERROR_ACCOUNT_EXPIRED) - CHK_ERR_WIN32A(ERROR_REDIRECTOR_HAS_OPEN_HANDLES) - CHK_ERR_WIN32A(ERROR_PRINTER_DRIVER_ALREADY_INSTALLED) - CHK_ERR_WIN32A(ERROR_UNKNOWN_PORT) - CHK_ERR_WIN32A(ERROR_UNKNOWN_PRINTER_DRIVER) - CHK_ERR_WIN32A(ERROR_UNKNOWN_PRINTPROCESSOR) - CHK_ERR_WIN32A(ERROR_INVALID_SEPARATOR_FILE) - CHK_ERR_WIN32A(ERROR_INVALID_PRIORITY) - CHK_ERR_WIN32A(ERROR_INVALID_PRINTER_NAME) - CHK_ERR_WIN32A(ERROR_PRINTER_ALREADY_EXISTS) - CHK_ERR_WIN32A(ERROR_INVALID_PRINTER_COMMAND) - CHK_ERR_WIN32A(ERROR_INVALID_DATATYPE) - CHK_ERR_WIN32A(ERROR_INVALID_ENVIRONMENT) - CHK_ERR_WIN32A(RPC_S_NO_MORE_BINDINGS) - CHK_ERR_WIN32A(ERROR_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT) - CHK_ERR_WIN32A(ERROR_NOLOGON_WORKSTATION_TRUST_ACCOUNT) - CHK_ERR_WIN32A(ERROR_NOLOGON_SERVER_TRUST_ACCOUNT) - CHK_ERR_WIN32A(ERROR_DOMAIN_TRUST_INCONSISTENT) - CHK_ERR_WIN32A(ERROR_SERVER_HAS_OPEN_HANDLES) - CHK_ERR_WIN32A(ERROR_RESOURCE_DATA_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_RESOURCE_TYPE_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_RESOURCE_NAME_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_RESOURCE_LANG_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_NOT_ENOUGH_QUOTA) - CHK_ERR_WIN32A(RPC_S_NO_INTERFACES) - CHK_ERR_WIN32A(RPC_S_CALL_CANCELLED) - CHK_ERR_WIN32A(RPC_S_BINDING_INCOMPLETE) - CHK_ERR_WIN32A(RPC_S_COMM_FAILURE) - CHK_ERR_WIN32A(RPC_S_UNSUPPORTED_AUTHN_LEVEL) - CHK_ERR_WIN32A(RPC_S_NO_PRINC_NAME) - CHK_ERR_WIN32A(RPC_S_NOT_RPC_ERROR) - CHK_ERR_WIN32A(RPC_S_UUID_LOCAL_ONLY) - CHK_ERR_WIN32A(RPC_S_SEC_PKG_ERROR) - CHK_ERR_WIN32A(RPC_S_NOT_CANCELLED) - CHK_ERR_WIN32A(RPC_X_INVALID_ES_ACTION) - CHK_ERR_WIN32A(RPC_X_WRONG_ES_VERSION) - CHK_ERR_WIN32A(RPC_X_WRONG_STUB_VERSION) - CHK_ERR_WIN32A(RPC_X_INVALID_PIPE_OBJECT) - CHK_ERR_WIN32A(RPC_X_WRONG_PIPE_ORDER) - CHK_ERR_WIN32A(RPC_X_WRONG_PIPE_VERSION) - CHK_ERR_WIN32A(RPC_S_GROUP_MEMBER_NOT_FOUND) - CHK_ERR_WIN32A(EPT_S_CANT_CREATE) - CHK_ERR_WIN32A(RPC_S_INVALID_OBJECT) - CHK_ERR_WIN32A(ERROR_INVALID_TIME) - CHK_ERR_WIN32A(ERROR_INVALID_FORM_NAME) - CHK_ERR_WIN32A(ERROR_INVALID_FORM_SIZE) - CHK_ERR_WIN32A(ERROR_ALREADY_WAITING) - CHK_ERR_WIN32A(ERROR_PRINTER_DELETED) - CHK_ERR_WIN32A(ERROR_INVALID_PRINTER_STATE) - CHK_ERR_WIN32A(ERROR_PASSWORD_MUST_CHANGE) - CHK_ERR_WIN32A(ERROR_DOMAIN_CONTROLLER_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_ACCOUNT_LOCKED_OUT) - CHK_ERR_WIN32A(OR_INVALID_OXID) - CHK_ERR_WIN32A(OR_INVALID_OID) - CHK_ERR_WIN32A(OR_INVALID_SET) - CHK_ERR_WIN32A(RPC_S_SEND_INCOMPLETE) - CHK_ERR_WIN32A(RPC_S_INVALID_ASYNC_HANDLE) - CHK_ERR_WIN32A(RPC_S_INVALID_ASYNC_CALL) - CHK_ERR_WIN32A(RPC_X_PIPE_CLOSED) - CHK_ERR_WIN32A(RPC_X_PIPE_DISCIPLINE_ERROR) - CHK_ERR_WIN32A(RPC_X_PIPE_EMPTY) - CHK_ERR_WIN32A(ERROR_NO_SITENAME) - CHK_ERR_WIN32A(ERROR_CANT_ACCESS_FILE) - CHK_ERR_WIN32A(ERROR_CANT_RESOLVE_FILENAME) - CHK_ERR_WIN32A(ERROR_INVALID_PIXEL_FORMAT) - CHK_ERR_WIN32A(ERROR_BAD_DRIVER) - CHK_ERR_WIN32A(ERROR_INVALID_WINDOW_STYLE) - CHK_ERR_WIN32A(ERROR_METAFILE_NOT_SUPPORTED) - CHK_ERR_WIN32A(ERROR_TRANSFORM_NOT_SUPPORTED) - CHK_ERR_WIN32A(ERROR_CLIPPING_NOT_SUPPORTED) - CHK_ERR_WIN32A(ERROR_INVALID_CMM) - CHK_ERR_WIN32A(ERROR_INVALID_PROFILE) - CHK_ERR_WIN32A(ERROR_TAG_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_TAG_NOT_PRESENT) - CHK_ERR_WIN32A(ERROR_DUPLICATE_TAG) - CHK_ERR_WIN32A(ERROR_PROFILE_NOT_ASSOCIATED_WITH_DEVICE) - CHK_ERR_WIN32A(ERROR_PROFILE_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_INVALID_COLORSPACE) - CHK_ERR_WIN32A(ERROR_ICM_NOT_ENABLED) - CHK_ERR_WIN32A(ERROR_DELETING_ICM_XFORM) - CHK_ERR_WIN32A(ERROR_INVALID_TRANSFORM) - CHK_ERR_WIN32A(ERROR_COLORSPACE_MISMATCH) - CHK_ERR_WIN32A(ERROR_INVALID_COLORINDEX) - CHK_ERR_WIN32A(ERROR_CONNECTED_OTHER_PASSWORD) - CHK_ERR_WIN32A(ERROR_BAD_USERNAME) - CHK_ERR_WIN32A(ERROR_NOT_CONNECTED) - CHK_ERR_WIN32A(ERROR_OPEN_FILES) - CHK_ERR_WIN32A(ERROR_ACTIVE_CONNECTIONS) - CHK_ERR_WIN32A(ERROR_DEVICE_IN_USE) - CHK_ERR_WIN32A(ERROR_UNKNOWN_PRINT_MONITOR) - CHK_ERR_WIN32A(ERROR_PRINTER_DRIVER_IN_USE) - CHK_ERR_WIN32A(ERROR_SPOOL_FILE_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_SPL_NO_STARTDOC) - CHK_ERR_WIN32A(ERROR_SPL_NO_ADDJOB) - CHK_ERR_WIN32A(ERROR_PRINT_PROCESSOR_ALREADY_INSTALLED) - CHK_ERR_WIN32A(ERROR_PRINT_MONITOR_ALREADY_INSTALLED) - CHK_ERR_WIN32A(ERROR_INVALID_PRINT_MONITOR) - CHK_ERR_WIN32A(ERROR_PRINT_MONITOR_IN_USE) - CHK_ERR_WIN32A(ERROR_PRINTER_HAS_JOBS_QUEUED) - CHK_ERR_WIN32A(ERROR_SUCCESS_REBOOT_REQUIRED) - CHK_ERR_WIN32A(ERROR_SUCCESS_RESTART_REQUIRED) - CHK_ERR_WIN32A(ERROR_PRINTER_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_WINS_INTERNAL) - CHK_ERR_WIN32A(ERROR_CAN_NOT_DEL_LOCAL_WINS) - CHK_ERR_WIN32A(ERROR_STATIC_INIT) - CHK_ERR_WIN32A(ERROR_INC_BACKUP) - CHK_ERR_WIN32A(ERROR_FULL_BACKUP) - CHK_ERR_WIN32A(ERROR_REC_NON_EXISTENT) - CHK_ERR_WIN32A(ERROR_RPL_NOT_ALLOWED) - CHK_ERR_WIN32A(ERROR_DHCP_ADDRESS_CONFLICT) - CHK_ERR_WIN32A(ERROR_WMI_GUID_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_WMI_INSTANCE_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_WMI_ITEMID_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_WMI_TRY_AGAIN) - CHK_ERR_WIN32A(ERROR_WMI_DP_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_WMI_UNRESOLVED_INSTANCE_REF) - CHK_ERR_WIN32A(ERROR_WMI_ALREADY_ENABLED) - CHK_ERR_WIN32A(ERROR_WMI_GUID_DISCONNECTED) - CHK_ERR_WIN32A(ERROR_WMI_SERVER_UNAVAILABLE) - CHK_ERR_WIN32A(ERROR_WMI_DP_FAILED) - CHK_ERR_WIN32A(ERROR_WMI_INVALID_MOF) - CHK_ERR_WIN32A(ERROR_WMI_INVALID_REGINFO) - CHK_ERR_WIN32A(ERROR_WMI_ALREADY_DISABLED) - CHK_ERR_WIN32A(ERROR_WMI_READ_ONLY) - CHK_ERR_WIN32A(ERROR_WMI_SET_FAILURE) - CHK_ERR_WIN32A(ERROR_INVALID_MEDIA) - CHK_ERR_WIN32A(ERROR_INVALID_LIBRARY) - CHK_ERR_WIN32A(ERROR_INVALID_MEDIA_POOL) - CHK_ERR_WIN32A(ERROR_DRIVE_MEDIA_MISMATCH) - CHK_ERR_WIN32A(ERROR_MEDIA_OFFLINE) - CHK_ERR_WIN32A(ERROR_LIBRARY_OFFLINE) - CHK_ERR_WIN32A(ERROR_EMPTY) - CHK_ERR_WIN32A(ERROR_NOT_EMPTY) - CHK_ERR_WIN32A(ERROR_MEDIA_UNAVAILABLE) - CHK_ERR_WIN32A(ERROR_RESOURCE_DISABLED) - CHK_ERR_WIN32A(ERROR_INVALID_CLEANER) - CHK_ERR_WIN32A(ERROR_UNABLE_TO_CLEAN) - CHK_ERR_WIN32A(ERROR_OBJECT_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_DATABASE_FAILURE) - CHK_ERR_WIN32A(ERROR_DATABASE_FULL) - CHK_ERR_WIN32A(ERROR_MEDIA_INCOMPATIBLE) - CHK_ERR_WIN32A(ERROR_RESOURCE_NOT_PRESENT) - CHK_ERR_WIN32A(ERROR_INVALID_OPERATION) - CHK_ERR_WIN32A(ERROR_MEDIA_NOT_AVAILABLE) - CHK_ERR_WIN32A(ERROR_DEVICE_NOT_AVAILABLE) - CHK_ERR_WIN32A(ERROR_REQUEST_REFUSED) - CHK_ERR_WIN32A(ERROR_INVALID_DRIVE_OBJECT) - CHK_ERR_WIN32A(ERROR_LIBRARY_FULL) - CHK_ERR_WIN32A(ERROR_MEDIUM_NOT_ACCESSIBLE) - CHK_ERR_WIN32A(ERROR_UNABLE_TO_LOAD_MEDIUM) - CHK_ERR_WIN32A(ERROR_UNABLE_TO_INVENTORY_DRIVE) - CHK_ERR_WIN32A(ERROR_UNABLE_TO_INVENTORY_SLOT) - CHK_ERR_WIN32A(ERROR_UNABLE_TO_INVENTORY_TRANSPORT) - CHK_ERR_WIN32A(ERROR_TRANSPORT_FULL) - CHK_ERR_WIN32A(ERROR_CONTROLLING_IEPORT) - CHK_ERR_WIN32A(ERROR_UNABLE_TO_EJECT_MOUNTED_MEDIA) - CHK_ERR_WIN32A(ERROR_CLEANER_SLOT_SET) - CHK_ERR_WIN32A(ERROR_CLEANER_SLOT_NOT_SET) - CHK_ERR_WIN32A(ERROR_CLEANER_CARTRIDGE_SPENT) - CHK_ERR_WIN32A(ERROR_UNEXPECTED_OMID) - CHK_ERR_WIN32A(ERROR_CANT_DELETE_LAST_ITEM) - CHK_ERR_WIN32A(ERROR_MESSAGE_EXCEEDS_MAX_SIZE) - CHK_ERR_WIN32A(ERROR_FILE_OFFLINE) - CHK_ERR_WIN32A(ERROR_REMOTE_STORAGE_NOT_ACTIVE) - CHK_ERR_WIN32A(ERROR_REMOTE_STORAGE_MEDIA_ERROR) - CHK_ERR_WIN32A(ERROR_NOT_A_REPARSE_POINT) - CHK_ERR_WIN32A(ERROR_REPARSE_ATTRIBUTE_CONFLICT) - CHK_ERR_WIN32A(ERROR_INVALID_REPARSE_DATA) - CHK_ERR_WIN32A(ERROR_DEPENDENT_RESOURCE_EXISTS) - CHK_ERR_WIN32A(ERROR_DEPENDENCY_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_DEPENDENCY_ALREADY_EXISTS) - CHK_ERR_WIN32A(ERROR_RESOURCE_NOT_ONLINE) - CHK_ERR_WIN32A(ERROR_HOST_NODE_NOT_AVAILABLE) - CHK_ERR_WIN32A(ERROR_RESOURCE_NOT_AVAILABLE) - CHK_ERR_WIN32A(ERROR_RESOURCE_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_SHUTDOWN_CLUSTER) - CHK_ERR_WIN32A(ERROR_CANT_EVICT_ACTIVE_NODE) - CHK_ERR_WIN32A(ERROR_OBJECT_ALREADY_EXISTS) - CHK_ERR_WIN32A(ERROR_OBJECT_IN_LIST) - CHK_ERR_WIN32A(ERROR_GROUP_NOT_AVAILABLE) - CHK_ERR_WIN32A(ERROR_GROUP_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_GROUP_NOT_ONLINE) - CHK_ERR_WIN32A(ERROR_HOST_NODE_NOT_RESOURCE_OWNER) - CHK_ERR_WIN32A(ERROR_HOST_NODE_NOT_GROUP_OWNER) - CHK_ERR_WIN32A(ERROR_RESMON_CREATE_FAILED) - CHK_ERR_WIN32A(ERROR_RESMON_ONLINE_FAILED) - CHK_ERR_WIN32A(ERROR_RESOURCE_ONLINE) - CHK_ERR_WIN32A(ERROR_QUORUM_RESOURCE) - CHK_ERR_WIN32A(ERROR_NOT_QUORUM_CAPABLE) - CHK_ERR_WIN32A(ERROR_CLUSTER_SHUTTING_DOWN) - CHK_ERR_WIN32A(ERROR_INVALID_STATE) - CHK_ERR_WIN32A(ERROR_RESOURCE_PROPERTIES_STORED) - CHK_ERR_WIN32A(ERROR_NOT_QUORUM_CLASS) - CHK_ERR_WIN32A(ERROR_CORE_RESOURCE) - CHK_ERR_WIN32A(ERROR_QUORUM_RESOURCE_ONLINE_FAILED) - CHK_ERR_WIN32A(ERROR_QUORUMLOG_OPEN_FAILED) - CHK_ERR_WIN32A(ERROR_CLUSTERLOG_CORRUPT) - CHK_ERR_WIN32A(ERROR_CLUSTERLOG_RECORD_EXCEEDS_MAXSIZE) - CHK_ERR_WIN32A(ERROR_CLUSTERLOG_EXCEEDS_MAXSIZE) - CHK_ERR_WIN32A(ERROR_CLUSTERLOG_CHKPOINT_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_CLUSTERLOG_NOT_ENOUGH_SPACE) - CHK_ERR_WIN32A(ERROR_ENCRYPTION_FAILED) - CHK_ERR_WIN32A(ERROR_DECRYPTION_FAILED) - CHK_ERR_WIN32A(ERROR_FILE_ENCRYPTED) - CHK_ERR_WIN32A(ERROR_NO_RECOVERY_POLICY) - CHK_ERR_WIN32A(ERROR_NO_EFS) - CHK_ERR_WIN32A(ERROR_WRONG_EFS) - CHK_ERR_WIN32A(ERROR_NO_USER_KEYS) - CHK_ERR_WIN32A(ERROR_FILE_NOT_ENCRYPTED) - CHK_ERR_WIN32A(ERROR_NOT_EXPORT_FORMAT) - CHK_ERR_WIN32A(ERROR_NO_BROWSER_SERVERS_FOUND) - CHK_ERR_WIN32A(ERROR_CTX_WINSTATION_NAME_INVALID) - CHK_ERR_WIN32A(ERROR_CTX_INVALID_PD) - CHK_ERR_WIN32A(ERROR_CTX_PD_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_CTX_WD_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_CTX_CANNOT_MAKE_EVENTLOG_ENTRY) - CHK_ERR_WIN32A(ERROR_CTX_SERVICE_NAME_COLLISION) - CHK_ERR_WIN32A(ERROR_CTX_CLOSE_PENDING) - CHK_ERR_WIN32A(ERROR_CTX_NO_OUTBUF) - CHK_ERR_WIN32A(ERROR_CTX_MODEM_INF_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_CTX_INVALID_MODEMNAME) - CHK_ERR_WIN32A(ERROR_CTX_MODEM_RESPONSE_ERROR) - CHK_ERR_WIN32A(ERROR_CTX_MODEM_RESPONSE_TIMEOUT) - CHK_ERR_WIN32A(ERROR_CTX_MODEM_RESPONSE_NO_CARRIER) - CHK_ERR_WIN32A(ERROR_CTX_MODEM_RESPONSE_NO_DIALTONE) - CHK_ERR_WIN32A(ERROR_CTX_MODEM_RESPONSE_BUSY) - CHK_ERR_WIN32A(ERROR_CTX_MODEM_RESPONSE_VOICE) - CHK_ERR_WIN32A(ERROR_CTX_TD_ERROR) - CHK_ERR_WIN32A(ERROR_CTX_WINSTATION_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_CTX_WINSTATION_ALREADY_EXISTS) - CHK_ERR_WIN32A(ERROR_CTX_WINSTATION_BUSY) - CHK_ERR_WIN32A(ERROR_CTX_BAD_VIDEO_MODE) - CHK_ERR_WIN32A(ERROR_CTX_GRAPHICS_INVALID) - CHK_ERR_WIN32A(ERROR_CTX_LOGON_DISABLED) - CHK_ERR_WIN32A(ERROR_CTX_NOT_CONSOLE) - CHK_ERR_WIN32A(ERROR_CTX_CLIENT_QUERY_TIMEOUT) - CHK_ERR_WIN32A(ERROR_CTX_CONSOLE_DISCONNECT) - CHK_ERR_WIN32A(ERROR_CTX_CONSOLE_CONNECT) - CHK_ERR_WIN32A(ERROR_CTX_SHADOW_DENIED) - CHK_ERR_WIN32A(ERROR_CTX_WINSTATION_ACCESS_DENIED) - CHK_ERR_WIN32A(ERROR_CTX_INVALID_WD) - CHK_ERR_WIN32A(ERROR_CTX_SHADOW_INVALID) - CHK_ERR_WIN32A(ERROR_CTX_SHADOW_DISABLED) - CHK_ERR_WIN32A(FRS_ERR_INVALID_API_SEQUENCE) - CHK_ERR_WIN32A(FRS_ERR_STARTING_SERVICE) - CHK_ERR_WIN32A(FRS_ERR_STOPPING_SERVICE) - CHK_ERR_WIN32A(FRS_ERR_INTERNAL_API) - CHK_ERR_WIN32A(FRS_ERR_INTERNAL) - CHK_ERR_WIN32A(FRS_ERR_SERVICE_COMM) - CHK_ERR_WIN32A(FRS_ERR_INSUFFICIENT_PRIV) - CHK_ERR_WIN32A(FRS_ERR_AUTHENTICATION) - CHK_ERR_WIN32A(FRS_ERR_PARENT_INSUFFICIENT_PRIV) - CHK_ERR_WIN32A(FRS_ERR_PARENT_AUTHENTICATION) - CHK_ERR_WIN32A(FRS_ERR_CHILD_TO_PARENT_COMM) - CHK_ERR_WIN32A(FRS_ERR_PARENT_TO_CHILD_COMM) - CHK_ERR_WIN32A(FRS_ERR_SYSVOL_POPULATE) - CHK_ERR_WIN32A(FRS_ERR_SYSVOL_POPULATE_TIMEOUT) - CHK_ERR_WIN32A(FRS_ERR_SYSVOL_IS_BUSY) - CHK_ERR_WIN32A(FRS_ERR_SYSVOL_DEMOTE) - CHK_ERR_WIN32A(FRS_ERR_INVALID_SERVICE_PARAMETER) -// CHK_ERR_WIN32A(DS_S_SUCCESS) - CHK_ERR_WIN32A(ERROR_DS_NOT_INSTALLED) - CHK_ERR_WIN32A(ERROR_DS_MEMBERSHIP_EVALUATED_LOCALLY) - CHK_ERR_WIN32A(ERROR_DS_NO_ATTRIBUTE_OR_VALUE) - CHK_ERR_WIN32A(ERROR_DS_INVALID_ATTRIBUTE_SYNTAX) - CHK_ERR_WIN32A(ERROR_DS_ATTRIBUTE_TYPE_UNDEFINED) - CHK_ERR_WIN32A(ERROR_DS_ATTRIBUTE_OR_VALUE_EXISTS) - CHK_ERR_WIN32A(ERROR_DS_BUSY) - CHK_ERR_WIN32A(ERROR_DS_UNAVAILABLE) - CHK_ERR_WIN32A(ERROR_DS_NO_RIDS_ALLOCATED) - CHK_ERR_WIN32A(ERROR_DS_NO_MORE_RIDS) - CHK_ERR_WIN32A(ERROR_DS_INCORRECT_ROLE_OWNER) - CHK_ERR_WIN32A(ERROR_DS_RIDMGR_INIT_ERROR) - CHK_ERR_WIN32A(ERROR_DS_OBJ_CLASS_VIOLATION) - CHK_ERR_WIN32A(ERROR_DS_CANT_ON_NON_LEAF) - CHK_ERR_WIN32A(ERROR_DS_CANT_ON_RDN) - CHK_ERR_WIN32A(ERROR_DS_CANT_MOD_OBJ_CLASS) - CHK_ERR_WIN32A(ERROR_DS_CROSS_DOM_MOVE_ERROR) - CHK_ERR_WIN32A(ERROR_DS_GC_NOT_AVAILABLE) - CHK_ERR_WIN32A(ERROR_SHARED_POLICY) - CHK_ERR_WIN32A(ERROR_POLICY_OBJECT_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_POLICY_ONLY_IN_DS) - CHK_ERR_WIN32A(ERROR_PROMOTION_ACTIVE) - CHK_ERR_WIN32A(ERROR_NO_PROMOTION_ACTIVE) - CHK_ERR_WIN32A(ERROR_DS_OPERATIONS_ERROR) - CHK_ERR_WIN32A(ERROR_DS_PROTOCOL_ERROR) - CHK_ERR_WIN32A(ERROR_DS_TIMELIMIT_EXCEEDED) - CHK_ERR_WIN32A(ERROR_DS_SIZELIMIT_EXCEEDED) - CHK_ERR_WIN32A(ERROR_DS_ADMIN_LIMIT_EXCEEDED) - CHK_ERR_WIN32A(ERROR_DS_COMPARE_FALSE) - CHK_ERR_WIN32A(ERROR_DS_COMPARE_TRUE) - CHK_ERR_WIN32A(ERROR_DS_AUTH_METHOD_NOT_SUPPORTED) - CHK_ERR_WIN32A(ERROR_DS_STRONG_AUTH_REQUIRED) - CHK_ERR_WIN32A(ERROR_DS_INAPPROPRIATE_AUTH) - CHK_ERR_WIN32A(ERROR_DS_AUTH_UNKNOWN) - CHK_ERR_WIN32A(ERROR_DS_REFERRAL) - CHK_ERR_WIN32A(ERROR_DS_UNAVAILABLE_CRIT_EXTENSION) - CHK_ERR_WIN32A(ERROR_DS_CONFIDENTIALITY_REQUIRED) - CHK_ERR_WIN32A(ERROR_DS_INAPPROPRIATE_MATCHING) - CHK_ERR_WIN32A(ERROR_DS_CONSTRAINT_VIOLATION) - CHK_ERR_WIN32A(ERROR_DS_NO_SUCH_OBJECT) - CHK_ERR_WIN32A(ERROR_DS_ALIAS_PROBLEM) - CHK_ERR_WIN32A(ERROR_DS_INVALID_DN_SYNTAX) - CHK_ERR_WIN32A(ERROR_DS_IS_LEAF) - CHK_ERR_WIN32A(ERROR_DS_ALIAS_DEREF_PROBLEM) - CHK_ERR_WIN32A(ERROR_DS_UNWILLING_TO_PERFORM) - CHK_ERR_WIN32A(ERROR_DS_LOOP_DETECT) - CHK_ERR_WIN32A(ERROR_DS_NAMING_VIOLATION) - CHK_ERR_WIN32A(ERROR_DS_OBJECT_RESULTS_TOO_LARGE) - CHK_ERR_WIN32A(ERROR_DS_AFFECTS_MULTIPLE_DSAS) - CHK_ERR_WIN32A(ERROR_DS_SERVER_DOWN) - CHK_ERR_WIN32A(ERROR_DS_LOCAL_ERROR) - CHK_ERR_WIN32A(ERROR_DS_ENCODING_ERROR) - CHK_ERR_WIN32A(ERROR_DS_DECODING_ERROR) - CHK_ERR_WIN32A(ERROR_DS_FILTER_UNKNOWN) - CHK_ERR_WIN32A(ERROR_DS_PARAM_ERROR) - CHK_ERR_WIN32A(ERROR_DS_NOT_SUPPORTED) - CHK_ERR_WIN32A(ERROR_DS_NO_RESULTS_RETURNED) - CHK_ERR_WIN32A(ERROR_DS_CONTROL_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_DS_CLIENT_LOOP) - CHK_ERR_WIN32A(ERROR_DS_REFERRAL_LIMIT_EXCEEDED) - CHK_ERR_WIN32A(ERROR_DS_ROOT_MUST_BE_NC) - CHK_ERR_WIN32A(ERROR_DS_ADD_REPLICA_INHIBITED) - CHK_ERR_WIN32A(ERROR_DS_ATT_NOT_DEF_IN_SCHEMA) - CHK_ERR_WIN32A(ERROR_DS_MAX_OBJ_SIZE_EXCEEDED) - CHK_ERR_WIN32A(ERROR_DS_OBJ_STRING_NAME_EXISTS) - CHK_ERR_WIN32A(ERROR_DS_NO_RDN_DEFINED_IN_SCHEMA) - CHK_ERR_WIN32A(ERROR_DS_RDN_DOESNT_MATCH_SCHEMA) - CHK_ERR_WIN32A(ERROR_DS_NO_REQUESTED_ATTS_FOUND) - CHK_ERR_WIN32A(ERROR_DS_USER_BUFFER_TO_SMALL) - CHK_ERR_WIN32A(ERROR_DS_ATT_IS_NOT_ON_OBJ) - CHK_ERR_WIN32A(ERROR_DS_ILLEGAL_MOD_OPERATION) - CHK_ERR_WIN32A(ERROR_DS_OBJ_TOO_LARGE) - CHK_ERR_WIN32A(ERROR_DS_BAD_INSTANCE_TYPE) - CHK_ERR_WIN32A(ERROR_DS_MASTERDSA_REQUIRED) - CHK_ERR_WIN32A(ERROR_DS_OBJECT_CLASS_REQUIRED) - CHK_ERR_WIN32A(ERROR_DS_MISSING_REQUIRED_ATT) - CHK_ERR_WIN32A(ERROR_DS_ATT_NOT_DEF_FOR_CLASS) - CHK_ERR_WIN32A(ERROR_DS_ATT_ALREADY_EXISTS) - CHK_ERR_WIN32A(ERROR_DS_CANT_ADD_ATT_VALUES) - CHK_ERR_WIN32A(ERROR_DS_SINGLE_VALUE_CONSTRAINT) - CHK_ERR_WIN32A(ERROR_DS_RANGE_CONSTRAINT) - CHK_ERR_WIN32A(ERROR_DS_ATT_VAL_ALREADY_EXISTS) - CHK_ERR_WIN32A(ERROR_DS_CANT_REM_MISSING_ATT) - CHK_ERR_WIN32A(ERROR_DS_CANT_REM_MISSING_ATT_VAL) - CHK_ERR_WIN32A(ERROR_DS_ROOT_CANT_BE_SUBREF) - CHK_ERR_WIN32A(ERROR_DS_NO_CHAINING) - CHK_ERR_WIN32A(ERROR_DS_NO_CHAINED_EVAL) - CHK_ERR_WIN32A(ERROR_DS_NO_PARENT_OBJECT) - CHK_ERR_WIN32A(ERROR_DS_PARENT_IS_AN_ALIAS) - CHK_ERR_WIN32A(ERROR_DS_CANT_MIX_MASTER_AND_REPS) - CHK_ERR_WIN32A(ERROR_DS_CHILDREN_EXIST) - CHK_ERR_WIN32A(ERROR_DS_OBJ_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_DS_ALIASED_OBJ_MISSING) - CHK_ERR_WIN32A(ERROR_DS_BAD_NAME_SYNTAX) - CHK_ERR_WIN32A(ERROR_DS_ALIAS_POINTS_TO_ALIAS) - CHK_ERR_WIN32A(ERROR_DS_CANT_DEREF_ALIAS) - CHK_ERR_WIN32A(ERROR_DS_OUT_OF_SCOPE) - CHK_ERR_WIN32A(ERROR_DS_CANT_DELETE_DSA_OBJ) - CHK_ERR_WIN32A(ERROR_DS_GENERIC_ERROR) - CHK_ERR_WIN32A(ERROR_DS_DSA_MUST_BE_INT_MASTER) - CHK_ERR_WIN32A(ERROR_DS_CLASS_NOT_DSA) - CHK_ERR_WIN32A(ERROR_DS_INSUFF_ACCESS_RIGHTS) - CHK_ERR_WIN32A(ERROR_DS_ILLEGAL_SUPERIOR) - CHK_ERR_WIN32A(ERROR_DS_ATTRIBUTE_OWNED_BY_SAM) - CHK_ERR_WIN32A(ERROR_DS_NAME_TOO_MANY_PARTS) - CHK_ERR_WIN32A(ERROR_DS_NAME_TOO_LONG) - CHK_ERR_WIN32A(ERROR_DS_NAME_VALUE_TOO_LONG) - CHK_ERR_WIN32A(ERROR_DS_NAME_UNPARSEABLE) - CHK_ERR_WIN32A(ERROR_DS_NAME_TYPE_UNKNOWN) - CHK_ERR_WIN32A(ERROR_DS_NOT_AN_OBJECT) - CHK_ERR_WIN32A(ERROR_DS_SEC_DESC_TOO_SHORT) - CHK_ERR_WIN32A(ERROR_DS_SEC_DESC_INVALID) - CHK_ERR_WIN32A(ERROR_DS_NO_DELETED_NAME) - CHK_ERR_WIN32A(ERROR_DS_SUBREF_MUST_HAVE_PARENT) - CHK_ERR_WIN32A(ERROR_DS_NCNAME_MUST_BE_NC) - CHK_ERR_WIN32A(ERROR_DS_CANT_ADD_SYSTEM_ONLY) - CHK_ERR_WIN32A(ERROR_DS_CLASS_MUST_BE_CONCRETE) - CHK_ERR_WIN32A(ERROR_DS_INVALID_DMD) - CHK_ERR_WIN32A(ERROR_DS_OBJ_GUID_EXISTS) - CHK_ERR_WIN32A(ERROR_DS_NOT_ON_BACKLINK) - CHK_ERR_WIN32A(ERROR_DS_NO_CROSSREF_FOR_NC) - CHK_ERR_WIN32A(ERROR_DS_SHUTTING_DOWN) - CHK_ERR_WIN32A(ERROR_DS_UNKNOWN_OPERATION) - CHK_ERR_WIN32A(ERROR_DS_INVALID_ROLE_OWNER) - CHK_ERR_WIN32A(ERROR_DS_COULDNT_CONTACT_FSMO) - CHK_ERR_WIN32A(ERROR_DS_CROSS_NC_DN_RENAME) - CHK_ERR_WIN32A(ERROR_DS_CANT_MOD_SYSTEM_ONLY) - CHK_ERR_WIN32A(ERROR_DS_REPLICATOR_ONLY) - CHK_ERR_WIN32A(ERROR_DS_OBJ_CLASS_NOT_DEFINED) - CHK_ERR_WIN32A(ERROR_DS_OBJ_CLASS_NOT_SUBCLASS) - CHK_ERR_WIN32A(ERROR_DS_NAME_REFERENCE_INVALID) - CHK_ERR_WIN32A(ERROR_DS_CROSS_REF_EXISTS) - CHK_ERR_WIN32A(ERROR_DS_CANT_DEL_MASTER_CROSSREF) - CHK_ERR_WIN32A(ERROR_DS_SUBTREE_NOTIFY_NOT_NC_HEAD) - CHK_ERR_WIN32A(ERROR_DS_NOTIFY_FILTER_TOO_COMPLEX) - CHK_ERR_WIN32A(ERROR_DS_DUP_RDN) - CHK_ERR_WIN32A(ERROR_DS_DUP_OID) - CHK_ERR_WIN32A(ERROR_DS_DUP_MAPI_ID) - CHK_ERR_WIN32A(ERROR_DS_DUP_SCHEMA_ID_GUID) - CHK_ERR_WIN32A(ERROR_DS_DUP_LDAP_DISPLAY_NAME) - CHK_ERR_WIN32A(ERROR_DS_SEMANTIC_ATT_TEST) - CHK_ERR_WIN32A(ERROR_DS_SYNTAX_MISMATCH) - CHK_ERR_WIN32A(ERROR_DS_EXISTS_IN_MUST_HAVE) - CHK_ERR_WIN32A(ERROR_DS_EXISTS_IN_MAY_HAVE) - CHK_ERR_WIN32A(ERROR_DS_NONEXISTENT_MAY_HAVE) - CHK_ERR_WIN32A(ERROR_DS_NONEXISTENT_MUST_HAVE) - CHK_ERR_WIN32A(ERROR_DS_AUX_CLS_TEST_FAIL) - CHK_ERR_WIN32A(ERROR_DS_NONEXISTENT_POSS_SUP) - CHK_ERR_WIN32A(ERROR_DS_SUB_CLS_TEST_FAIL) - CHK_ERR_WIN32A(ERROR_DS_BAD_RDN_ATT_ID_SYNTAX) - CHK_ERR_WIN32A(ERROR_DS_EXISTS_IN_AUX_CLS) - CHK_ERR_WIN32A(ERROR_DS_EXISTS_IN_SUB_CLS) - CHK_ERR_WIN32A(ERROR_DS_EXISTS_IN_POSS_SUP) - CHK_ERR_WIN32A(ERROR_DS_RECALCSCHEMA_FAILED) - CHK_ERR_WIN32A(ERROR_DS_TREE_DELETE_NOT_FINISHED) - CHK_ERR_WIN32A(ERROR_DS_CANT_DELETE) - CHK_ERR_WIN32A(ERROR_DS_ATT_SCHEMA_REQ_ID) - CHK_ERR_WIN32A(ERROR_DS_BAD_ATT_SCHEMA_SYNTAX) - CHK_ERR_WIN32A(ERROR_DS_CANT_CACHE_ATT) - CHK_ERR_WIN32A(ERROR_DS_CANT_CACHE_CLASS) - CHK_ERR_WIN32A(ERROR_DS_CANT_REMOVE_ATT_CACHE) - CHK_ERR_WIN32A(ERROR_DS_CANT_REMOVE_CLASS_CACHE) - CHK_ERR_WIN32A(ERROR_DS_CANT_RETRIEVE_DN) - CHK_ERR_WIN32A(ERROR_DS_MISSING_SUPREF) - CHK_ERR_WIN32A(ERROR_DS_CANT_RETRIEVE_INSTANCE) - CHK_ERR_WIN32A(ERROR_DS_CODE_INCONSISTENCY) - CHK_ERR_WIN32A(ERROR_DS_DATABASE_ERROR) - CHK_ERR_WIN32A(ERROR_DS_GOVERNSID_MISSING) - CHK_ERR_WIN32A(ERROR_DS_MISSING_EXPECTED_ATT) - CHK_ERR_WIN32A(ERROR_DS_NCNAME_MISSING_CR_REF) - CHK_ERR_WIN32A(ERROR_DS_SECURITY_CHECKING_ERROR) - CHK_ERR_WIN32A(ERROR_DS_SCHEMA_NOT_LOADED) - CHK_ERR_WIN32A(ERROR_DS_SCHEMA_ALLOC_FAILED) - CHK_ERR_WIN32A(ERROR_DS_ATT_SCHEMA_REQ_SYNTAX) - CHK_ERR_WIN32A(ERROR_DS_GCVERIFY_ERROR) - CHK_ERR_WIN32A(ERROR_DS_DRA_SCHEMA_MISMATCH) - CHK_ERR_WIN32A(ERROR_DS_CANT_FIND_DSA_OBJ) - CHK_ERR_WIN32A(ERROR_DS_CANT_FIND_EXPECTED_NC) - CHK_ERR_WIN32A(ERROR_DS_CANT_FIND_NC_IN_CACHE) - CHK_ERR_WIN32A(ERROR_DS_CANT_RETRIEVE_CHILD) - CHK_ERR_WIN32A(ERROR_DS_SECURITY_ILLEGAL_MODIFY) - CHK_ERR_WIN32A(ERROR_DS_CANT_REPLACE_HIDDEN_REC) - CHK_ERR_WIN32A(ERROR_DS_BAD_HIERARCHY_FILE) - CHK_ERR_WIN32A(ERROR_DS_BUILD_HIERARCHY_TABLE_FAILED) - CHK_ERR_WIN32A(ERROR_DS_CONFIG_PARAM_MISSING) - CHK_ERR_WIN32A(ERROR_DS_COUNTING_AB_INDICES_FAILED) - CHK_ERR_WIN32A(ERROR_DS_HIERARCHY_TABLE_MALLOC_FAILED) - CHK_ERR_WIN32A(ERROR_DS_INTERNAL_FAILURE) - CHK_ERR_WIN32A(ERROR_DS_UNKNOWN_ERROR) - CHK_ERR_WIN32A(ERROR_DS_ROOT_REQUIRES_CLASS_TOP) - CHK_ERR_WIN32A(ERROR_DS_REFUSING_FSMO_ROLES) - CHK_ERR_WIN32A(ERROR_DS_MISSING_FSMO_SETTINGS) - CHK_ERR_WIN32A(ERROR_DS_UNABLE_TO_SURRENDER_ROLES) - CHK_ERR_WIN32A(ERROR_DS_DRA_GENERIC) - CHK_ERR_WIN32A(ERROR_DS_DRA_INVALID_PARAMETER) - CHK_ERR_WIN32A(ERROR_DS_DRA_BUSY) - CHK_ERR_WIN32A(ERROR_DS_DRA_BAD_DN) - CHK_ERR_WIN32A(ERROR_DS_DRA_BAD_NC) - CHK_ERR_WIN32A(ERROR_DS_DRA_DN_EXISTS) - CHK_ERR_WIN32A(ERROR_DS_DRA_INTERNAL_ERROR) - CHK_ERR_WIN32A(ERROR_DS_DRA_INCONSISTENT_DIT) - CHK_ERR_WIN32A(ERROR_DS_DRA_CONNECTION_FAILED) - CHK_ERR_WIN32A(ERROR_DS_DRA_BAD_INSTANCE_TYPE) - CHK_ERR_WIN32A(ERROR_DS_DRA_OUT_OF_MEM) - CHK_ERR_WIN32A(ERROR_DS_DRA_MAIL_PROBLEM) - CHK_ERR_WIN32A(ERROR_DS_DRA_REF_ALREADY_EXISTS) - CHK_ERR_WIN32A(ERROR_DS_DRA_REF_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_DS_DRA_OBJ_IS_REP_SOURCE) - CHK_ERR_WIN32A(ERROR_DS_DRA_DB_ERROR) - CHK_ERR_WIN32A(ERROR_DS_DRA_NO_REPLICA) - CHK_ERR_WIN32A(ERROR_DS_DRA_ACCESS_DENIED) - CHK_ERR_WIN32A(ERROR_DS_DRA_NOT_SUPPORTED) - CHK_ERR_WIN32A(ERROR_DS_DRA_RPC_CANCELLED) - CHK_ERR_WIN32A(ERROR_DS_DRA_SOURCE_DISABLED) - CHK_ERR_WIN32A(ERROR_DS_DRA_SINK_DISABLED) - CHK_ERR_WIN32A(ERROR_DS_DRA_NAME_COLLISION) - CHK_ERR_WIN32A(ERROR_DS_DRA_SOURCE_REINSTALLED) - CHK_ERR_WIN32A(ERROR_DS_DRA_MISSING_PARENT) - CHK_ERR_WIN32A(ERROR_DS_DRA_PREEMPTED) - CHK_ERR_WIN32A(ERROR_DS_DRA_ABANDON_SYNC) - CHK_ERR_WIN32A(ERROR_DS_DRA_SHUTDOWN) - CHK_ERR_WIN32A(ERROR_DS_DRA_INCOMPATIBLE_PARTIAL_SET) - CHK_ERR_WIN32A(ERROR_DS_DRA_SOURCE_IS_PARTIAL_REPLICA) - CHK_ERR_WIN32A(ERROR_DS_DRA_EXTN_CONNECTION_FAILED) - CHK_ERR_WIN32A(ERROR_DS_INSTALL_SCHEMA_MISMATCH) - CHK_ERR_WIN32A(ERROR_DS_DUP_LINK_ID) - CHK_ERR_WIN32A(ERROR_DS_NAME_ERROR_RESOLVING) - CHK_ERR_WIN32A(ERROR_DS_NAME_ERROR_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_DS_NAME_ERROR_NOT_UNIQUE) - CHK_ERR_WIN32A(ERROR_DS_NAME_ERROR_NO_MAPPING) - CHK_ERR_WIN32A(ERROR_DS_NAME_ERROR_DOMAIN_ONLY) - CHK_ERR_WIN32A(ERROR_DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING) - CHK_ERR_WIN32A(ERROR_DS_CONSTRUCTED_ATT_MOD) - CHK_ERR_WIN32A(ERROR_DS_WRONG_OM_OBJ_CLASS) - CHK_ERR_WIN32A(ERROR_DS_DRA_REPL_PENDING) - CHK_ERR_WIN32A(DNS_ERROR_RESPONSE_CODES_BASE) -// CHK_ERR_WIN32A(DNS_ERROR_MASK) - CHK_ERR_WIN32A(DNS_ERROR_RCODE_FORMAT_ERROR) - CHK_ERR_WIN32A(DNS_ERROR_RCODE_SERVER_FAILURE) - CHK_ERR_WIN32A(DNS_ERROR_RCODE_NAME_ERROR) - CHK_ERR_WIN32A(DNS_ERROR_RCODE_NOT_IMPLEMENTED) - CHK_ERR_WIN32A(DNS_ERROR_RCODE_REFUSED) - CHK_ERR_WIN32A(DNS_ERROR_RCODE_YXDOMAIN) - CHK_ERR_WIN32A(DNS_ERROR_RCODE_YXRRSET) - CHK_ERR_WIN32A(DNS_ERROR_RCODE_NXRRSET) - CHK_ERR_WIN32A(DNS_ERROR_RCODE_NOTAUTH) - CHK_ERR_WIN32A(DNS_ERROR_RCODE_NOTZONE) - CHK_ERR_WIN32A(DNS_ERROR_RCODE_BADSIG) - CHK_ERR_WIN32A(DNS_ERROR_RCODE_BADKEY) - CHK_ERR_WIN32A(DNS_ERROR_RCODE_BADTIME) - CHK_ERR_WIN32A(DNS_ERROR_PACKET_FMT_BASE) - CHK_ERR_WIN32A(DNS_INFO_NO_RECORDS) - CHK_ERR_WIN32A(DNS_ERROR_BAD_PACKET) - CHK_ERR_WIN32A(DNS_ERROR_NO_PACKET) - CHK_ERR_WIN32A(DNS_ERROR_RCODE) - CHK_ERR_WIN32A(DNS_ERROR_UNSECURE_PACKET) - CHK_ERR_WIN32A(DNS_ERROR_GENERAL_API_BASE) - CHK_ERR_WIN32A(DNS_ERROR_INVALID_TYPE) - CHK_ERR_WIN32A(DNS_ERROR_INVALID_IP_ADDRESS) - CHK_ERR_WIN32A(DNS_ERROR_INVALID_PROPERTY) - CHK_ERR_WIN32A(DNS_ERROR_TRY_AGAIN_LATER) - CHK_ERR_WIN32A(DNS_ERROR_NOT_UNIQUE) - CHK_ERR_WIN32A(DNS_ERROR_NON_RFC_NAME) - CHK_ERR_WIN32A(DNS_STATUS_FQDN) - CHK_ERR_WIN32A(DNS_STATUS_DOTTED_NAME) - CHK_ERR_WIN32A(DNS_STATUS_SINGLE_PART_NAME) - CHK_ERR_WIN32A(DNS_ERROR_ZONE_BASE) - CHK_ERR_WIN32A(DNS_ERROR_ZONE_DOES_NOT_EXIST) - CHK_ERR_WIN32A(DNS_ERROR_NO_ZONE_INFO) - CHK_ERR_WIN32A(DNS_ERROR_INVALID_ZONE_OPERATION) - CHK_ERR_WIN32A(DNS_ERROR_ZONE_CONFIGURATION_ERROR) - CHK_ERR_WIN32A(DNS_ERROR_ZONE_HAS_NO_SOA_RECORD) - CHK_ERR_WIN32A(DNS_ERROR_ZONE_HAS_NO_NS_RECORDS) - CHK_ERR_WIN32A(DNS_ERROR_ZONE_LOCKED) - CHK_ERR_WIN32A(DNS_ERROR_ZONE_CREATION_FAILED) - CHK_ERR_WIN32A(DNS_ERROR_ZONE_ALREADY_EXISTS) - CHK_ERR_WIN32A(DNS_ERROR_AUTOZONE_ALREADY_EXISTS) - CHK_ERR_WIN32A(DNS_ERROR_INVALID_ZONE_TYPE) - CHK_ERR_WIN32A(DNS_ERROR_SECONDARY_REQUIRES_MASTER_IP) - CHK_ERR_WIN32A(DNS_ERROR_ZONE_NOT_SECONDARY) - CHK_ERR_WIN32A(DNS_ERROR_NEED_SECONDARY_ADDRESSES) - CHK_ERR_WIN32A(DNS_ERROR_WINS_INIT_FAILED) - CHK_ERR_WIN32A(DNS_ERROR_NEED_WINS_SERVERS) - CHK_ERR_WIN32A(DNS_ERROR_NBSTAT_INIT_FAILED) - CHK_ERR_WIN32A(DNS_ERROR_SOA_DELETE_INVALID) - CHK_ERR_WIN32A(DNS_ERROR_DATAFILE_BASE) - CHK_ERR_WIN32A(DNS_ERROR_PRIMARY_REQUIRES_DATAFILE) - CHK_ERR_WIN32A(DNS_ERROR_INVALID_DATAFILE_NAME) - CHK_ERR_WIN32A(DNS_ERROR_DATAFILE_OPEN_FAILURE) - CHK_ERR_WIN32A(DNS_ERROR_FILE_WRITEBACK_FAILED) - CHK_ERR_WIN32A(DNS_ERROR_DATAFILE_PARSING) - CHK_ERR_WIN32A(DNS_ERROR_DATABASE_BASE) - CHK_ERR_WIN32A(DNS_ERROR_RECORD_DOES_NOT_EXIST) - CHK_ERR_WIN32A(DNS_ERROR_RECORD_FORMAT) - CHK_ERR_WIN32A(DNS_ERROR_NODE_CREATION_FAILED) - CHK_ERR_WIN32A(DNS_ERROR_UNKNOWN_RECORD_TYPE) - CHK_ERR_WIN32A(DNS_ERROR_RECORD_TIMED_OUT) - CHK_ERR_WIN32A(DNS_ERROR_NAME_NOT_IN_ZONE) - CHK_ERR_WIN32A(DNS_ERROR_CNAME_LOOP) - CHK_ERR_WIN32A(DNS_ERROR_NODE_IS_CNAME) - CHK_ERR_WIN32A(DNS_ERROR_CNAME_COLLISION) - CHK_ERR_WIN32A(DNS_ERROR_RECORD_ONLY_AT_ZONE_ROOT) - CHK_ERR_WIN32A(DNS_ERROR_RECORD_ALREADY_EXISTS) - CHK_ERR_WIN32A(DNS_ERROR_SECONDARY_DATA) - CHK_ERR_WIN32A(DNS_ERROR_NO_CREATE_CACHE_DATA) - CHK_ERR_WIN32A(DNS_ERROR_NAME_DOES_NOT_EXIST) - CHK_ERR_WIN32A(DNS_WARNING_PTR_CREATE_FAILED) - CHK_ERR_WIN32A(DNS_WARNING_DOMAIN_UNDELETED) - CHK_ERR_WIN32A(DNS_ERROR_DS_UNAVAILABLE) - CHK_ERR_WIN32A(DNS_ERROR_DS_ZONE_ALREADY_EXISTS) - CHK_ERR_WIN32A(DNS_ERROR_NO_BOOTFILE_IF_DS_ZONE) - CHK_ERR_WIN32A(DNS_ERROR_OPERATION_BASE) - CHK_ERR_WIN32A(DNS_INFO_AXFR_COMPLETE) - CHK_ERR_WIN32A(DNS_ERROR_AXFR) - CHK_ERR_WIN32A(DNS_INFO_ADDED_LOCAL_WINS) - CHK_ERR_WIN32A(DNS_ERROR_SECURE_BASE) - CHK_ERR_WIN32A(DNS_STATUS_CONTINUE_NEEDED) - CHK_ERR_WIN32A(DNS_ERROR_SETUP_BASE) - CHK_ERR_WIN32A(DNS_ERROR_NO_TCPIP) - CHK_ERR_WIN32A(DNS_ERROR_NO_DNS_SERVERS) - CHK_ERR_WIN32A(WSABASEERR) - CHK_ERR_WIN32A(WSAEINTR) - CHK_ERR_WIN32A(WSAEBADF) - CHK_ERR_WIN32A(WSAEACCES) - CHK_ERR_WIN32A(WSAEFAULT) - CHK_ERR_WIN32A(WSAEINVAL) - CHK_ERR_WIN32A(WSAEMFILE) - CHK_ERR_WIN32A(WSAEWOULDBLOCK) - CHK_ERR_WIN32A(WSAEINPROGRESS) - CHK_ERR_WIN32A(WSAEALREADY) - CHK_ERR_WIN32A(WSAENOTSOCK) - CHK_ERR_WIN32A(WSAEDESTADDRREQ) - CHK_ERR_WIN32A(WSAEMSGSIZE) - CHK_ERR_WIN32A(WSAEPROTOTYPE) - CHK_ERR_WIN32A(WSAENOPROTOOPT) - CHK_ERR_WIN32A(WSAEPROTONOSUPPORT) - CHK_ERR_WIN32A(WSAESOCKTNOSUPPORT) - CHK_ERR_WIN32A(WSAEOPNOTSUPP) - CHK_ERR_WIN32A(WSAEPFNOSUPPORT) - CHK_ERR_WIN32A(WSAEAFNOSUPPORT) - CHK_ERR_WIN32A(WSAEADDRINUSE) - CHK_ERR_WIN32A(WSAEADDRNOTAVAIL) - CHK_ERR_WIN32A(WSAENETDOWN) - CHK_ERR_WIN32A(WSAENETUNREACH) - CHK_ERR_WIN32A(WSAENETRESET) - CHK_ERR_WIN32A(WSAECONNABORTED) - CHK_ERR_WIN32A(WSAECONNRESET) - CHK_ERR_WIN32A(WSAENOBUFS) - CHK_ERR_WIN32A(WSAEISCONN) - CHK_ERR_WIN32A(WSAENOTCONN) - CHK_ERR_WIN32A(WSAESHUTDOWN) - CHK_ERR_WIN32A(WSAETOOMANYREFS) - CHK_ERR_WIN32A(WSAETIMEDOUT) - CHK_ERR_WIN32A(WSAECONNREFUSED) - CHK_ERR_WIN32A(WSAELOOP) - CHK_ERR_WIN32A(WSAENAMETOOLONG) - CHK_ERR_WIN32A(WSAEHOSTDOWN) - CHK_ERR_WIN32A(WSAEHOSTUNREACH) - CHK_ERR_WIN32A(WSAENOTEMPTY) - CHK_ERR_WIN32A(WSAEPROCLIM) - CHK_ERR_WIN32A(WSAEUSERS) - CHK_ERR_WIN32A(WSAEDQUOT) - CHK_ERR_WIN32A(WSAESTALE) - CHK_ERR_WIN32A(WSAEREMOTE) - CHK_ERR_WIN32A(WSASYSNOTREADY) - CHK_ERR_WIN32A(WSAVERNOTSUPPORTED) - CHK_ERR_WIN32A(WSANOTINITIALISED) - CHK_ERR_WIN32A(WSAEDISCON) - CHK_ERR_WIN32A(WSAENOMORE) - CHK_ERR_WIN32A(WSAECANCELLED) - CHK_ERR_WIN32A(WSAEINVALIDPROCTABLE) - CHK_ERR_WIN32A(WSAEINVALIDPROVIDER) - CHK_ERR_WIN32A(WSAEPROVIDERFAILEDINIT) - CHK_ERR_WIN32A(WSASYSCALLFAILURE) - CHK_ERR_WIN32A(WSASERVICE_NOT_FOUND) - CHK_ERR_WIN32A(WSATYPE_NOT_FOUND) - CHK_ERR_WIN32A(WSA_E_NO_MORE) - CHK_ERR_WIN32A(WSA_E_CANCELLED) - CHK_ERR_WIN32A(WSAEREFUSED) - CHK_ERR_WIN32A(WSAHOST_NOT_FOUND) - CHK_ERR_WIN32A(WSATRY_AGAIN) - CHK_ERR_WIN32A(WSANO_RECOVERY) - CHK_ERR_WIN32A(WSANO_DATA) - CHK_ERR_WIN32A(WSA_QOS_RECEIVERS) - CHK_ERR_WIN32A(WSA_QOS_SENDERS) - CHK_ERR_WIN32A(WSA_QOS_NO_SENDERS) - CHK_ERR_WIN32A(WSA_QOS_NO_RECEIVERS) - CHK_ERR_WIN32A(WSA_QOS_REQUEST_CONFIRMED) - CHK_ERR_WIN32A(WSA_QOS_ADMISSION_FAILURE) - CHK_ERR_WIN32A(WSA_QOS_POLICY_FAILURE) - CHK_ERR_WIN32A(WSA_QOS_BAD_STYLE) - CHK_ERR_WIN32A(WSA_QOS_BAD_OBJECT) - CHK_ERR_WIN32A(WSA_QOS_TRAFFIC_CTRL_ERROR) - CHK_ERR_WIN32A(WSA_QOS_GENERIC_ERROR) - - CHK_ERRA(CO_E_ATTEMPT_TO_CREATE_OUTSIDE_CLIENT_CONTEXT) - CHK_ERRA(CO_E_SERVER_PAUSED) - CHK_ERRA(CO_E_SERVER_NOT_PAUSED) - CHK_ERRA(CO_E_CLASS_DISABLED) - CHK_ERRA(CO_E_CLRNOTAVAILABLE) - CHK_ERRA(CO_E_ASYNC_WORK_REJECTED) - CHK_ERRA(CO_E_SERVER_INIT_TIMEOUT) - CHK_ERRA(CO_E_NO_SECCTX_IN_ACTIVATE) - CHK_ERRA(CO_E_TRACKER_CONFIG) - CHK_ERRA(CO_E_THREADPOOL_CONFIG) - CHK_ERRA(CO_E_SXS_CONFIG) - CHK_ERRA(CO_E_MALFORMED_SPN) - CHK_ERRA(REGDB_E_BADTHREADINGMODEL) -// CHK_ERRA(EVENT_E_FIRST) -// CHK_ERRA(EVENT_E_LAST) -// CHK_ERRA(EVENT_S_FIRST) -// CHK_ERRA(EVENT_S_LAST) -// CHK_ERRA(EVENT_S_SOME_SUBSCRIBERS_FAILED) -// CHK_ERRA(EVENT_E_ALL_SUBSCRIBERS_FAILED) - CHK_ERRA(EVENT_S_NOSUBSCRIBERS) -// CHK_ERRA(EVENT_E_QUERYSYNTAX) -// CHK_ERRA(EVENT_E_QUERYFIELD) -// CHK_ERRA(EVENT_E_INTERNALEXCEPTION) -// CHK_ERRA(EVENT_E_INTERNALERROR) -// CHK_ERRA(EVENT_E_INVALID_PER_USER_SID) -// CHK_ERRA(EVENT_E_USER_EXCEPTION) -// CHK_ERRA(EVENT_E_TOO_MANY_METHODS) -// CHK_ERRA(EVENT_E_MISSING_EVENTCLASS) -// CHK_ERRA(EVENT_E_NOT_ALL_REMOVED) -// CHK_ERRA(EVENT_E_COMPLUS_NOT_INSTALLED) -// CHK_ERRA(EVENT_E_CANT_MODIFY_OR_DELETE_UNCONFIGURED_OBJECT) -// CHK_ERRA(EVENT_E_CANT_MODIFY_OR_DELETE_CONFIGURED_OBJECT) -// CHK_ERRA(EVENT_E_INVALID_EVENT_CLASS_PARTITION) -// CHK_ERRA(EVENT_E_PER_USER_SID_NOT_LOGGED_ON) - CHK_ERRA(CONTEXT_E_FIRST) - CHK_ERRA(CONTEXT_E_LAST) - CHK_ERRA(CONTEXT_S_FIRST) - CHK_ERRA(CONTEXT_S_LAST) - CHK_ERRA(CONTEXT_E_ABORTED) - CHK_ERRA(CONTEXT_E_ABORTING) - CHK_ERRA(CONTEXT_E_NOCONTEXT) -// CHK_ERRA(CONTEXT_E_WOULD_DEADLOCK) - CHK_ERRA(CONTEXT_E_SYNCH_TIMEOUT) - CHK_ERRA(CONTEXT_E_OLDREF) - CHK_ERRA(CONTEXT_E_ROLENOTFOUND) - CHK_ERRA(CONTEXT_E_TMNOTAVAILABLE) - CHK_ERRA(CO_E_ACTIVATIONFAILED) - CHK_ERRA(CO_E_ACTIVATIONFAILED_EVENTLOGGED) - CHK_ERRA(CO_E_ACTIVATIONFAILED_CATALOGERROR) - CHK_ERRA(CO_E_ACTIVATIONFAILED_TIMEOUT) - CHK_ERRA(CO_E_INITIALIZATIONFAILED) - CHK_ERRA(CONTEXT_E_NOJIT) - CHK_ERRA(CONTEXT_E_NOTRANSACTION) - CHK_ERRA(CO_E_THREADINGMODEL_CHANGED) - CHK_ERRA(CO_E_NOIISINTRINSICS) - CHK_ERRA(CO_E_NOCOOKIES) - CHK_ERRA(CO_E_DBERROR) - CHK_ERRA(CO_E_NOTPOOLED) - CHK_ERRA(CO_E_NOTCONSTRUCTED) - CHK_ERRA(CO_E_NOSYNCHRONIZATION) -// CHK_ERRA(CO_E_ISOLEVELMISMATCH) - CHK_ERRA(SCHED_S_TASK_READY) - CHK_ERRA(SCHED_S_TASK_RUNNING) - CHK_ERRA(SCHED_S_TASK_DISABLED) - CHK_ERRA(SCHED_S_TASK_HAS_NOT_RUN) - CHK_ERRA(SCHED_S_TASK_NO_MORE_RUNS) - CHK_ERRA(SCHED_S_TASK_NOT_SCHEDULED) - CHK_ERRA(SCHED_S_TASK_TERMINATED) - CHK_ERRA(SCHED_S_TASK_NO_VALID_TRIGGERS) - CHK_ERRA(SCHED_S_EVENT_TRIGGER) - CHK_ERRA(SCHED_E_TRIGGER_NOT_FOUND) - CHK_ERRA(SCHED_E_TASK_NOT_READY) - CHK_ERRA(SCHED_E_TASK_NOT_RUNNING) - CHK_ERRA(SCHED_E_SERVICE_NOT_INSTALLED) - CHK_ERRA(SCHED_E_CANNOT_OPEN_TASK) - CHK_ERRA(SCHED_E_INVALID_TASK) - CHK_ERRA(SCHED_E_ACCOUNT_INFORMATION_NOT_SET) - CHK_ERRA(SCHED_E_ACCOUNT_NAME_NOT_FOUND) - CHK_ERRA(SCHED_E_ACCOUNT_DBASE_CORRUPT) - CHK_ERRA(SCHED_E_NO_SECURITY_SERVICES) - CHK_ERRA(SCHED_E_UNKNOWN_OBJECT_VERSION) - CHK_ERRA(SCHED_E_UNSUPPORTED_ACCOUNT_OPTION) - CHK_ERRA(SCHED_E_SERVICE_NOT_RUNNING) - CHK_ERRA(CO_S_MACHINENAMENOTFOUND) - CHK_ERRA(STG_E_STATUS_COPY_PROTECTION_FAILURE) - CHK_ERRA(STG_E_CSS_AUTHENTICATION_FAILURE) - CHK_ERRA(STG_E_CSS_KEY_NOT_PRESENT) - CHK_ERRA(STG_E_CSS_KEY_NOT_ESTABLISHED) - CHK_ERRA(STG_E_CSS_SCRAMBLED_SECTOR) - CHK_ERRA(STG_E_CSS_REGION_MISMATCH) - CHK_ERRA(STG_E_RESETS_EXHAUSTED) - CHK_ERRA(CO_E_CANCEL_DISABLED) - CHK_ERRA(ERROR_AUDITING_DISABLED) - CHK_ERRA(ERROR_ALL_SIDS_FILTERED) - CHK_ERRA(NTE_TEMPORARY_PROFILE) - CHK_ERRA(NTE_FIXEDPARAMETER) - CHK_ERRA(SEC_E_INSUFFICIENT_MEMORY) - CHK_ERRA(SEC_E_INVALID_HANDLE) - CHK_ERRA(SEC_E_UNSUPPORTED_FUNCTION) - CHK_ERRA(SEC_E_TARGET_UNKNOWN) - CHK_ERRA(SEC_E_INTERNAL_ERROR) - CHK_ERRA(SEC_E_SECPKG_NOT_FOUND) - CHK_ERRA(SEC_E_NOT_OWNER) - CHK_ERRA(SEC_E_CANNOT_INSTALL) - CHK_ERRA(SEC_E_INVALID_TOKEN) - CHK_ERRA(SEC_E_CANNOT_PACK) - CHK_ERRA(SEC_E_QOP_NOT_SUPPORTED) - CHK_ERRA(SEC_E_NO_IMPERSONATION) - CHK_ERRA(SEC_E_LOGON_DENIED) - CHK_ERRA(SEC_E_UNKNOWN_CREDENTIALS) - CHK_ERRA(SEC_E_NO_CREDENTIALS) - CHK_ERRA(SEC_E_MESSAGE_ALTERED) - CHK_ERRA(SEC_E_OUT_OF_SEQUENCE) - CHK_ERRA(SEC_E_NO_AUTHENTICATING_AUTHORITY) - CHK_ERRA(SEC_I_CONTINUE_NEEDED) - CHK_ERRA(SEC_I_COMPLETE_NEEDED) - CHK_ERRA(SEC_I_COMPLETE_AND_CONTINUE) - CHK_ERRA(SEC_I_LOCAL_LOGON) - CHK_ERRA(SEC_E_BAD_PKGID) - CHK_ERRA(SEC_E_CONTEXT_EXPIRED) - CHK_ERRA(SEC_I_CONTEXT_EXPIRED) - CHK_ERRA(SEC_E_INCOMPLETE_MESSAGE) - CHK_ERRA(SEC_E_INCOMPLETE_CREDENTIALS) - CHK_ERRA(SEC_E_BUFFER_TOO_SMALL) - CHK_ERRA(SEC_I_INCOMPLETE_CREDENTIALS) - CHK_ERRA(SEC_I_RENEGOTIATE) - CHK_ERRA(SEC_E_WRONG_PRINCIPAL) - CHK_ERRA(SEC_I_NO_LSA_CONTEXT) - CHK_ERRA(SEC_E_TIME_SKEW) - CHK_ERRA(SEC_E_UNTRUSTED_ROOT) - CHK_ERRA(SEC_E_ILLEGAL_MESSAGE) - CHK_ERRA(SEC_E_CERT_UNKNOWN) - CHK_ERRA(SEC_E_CERT_EXPIRED) - CHK_ERRA(SEC_E_ENCRYPT_FAILURE) - CHK_ERRA(SEC_E_DECRYPT_FAILURE) - CHK_ERRA(SEC_E_ALGORITHM_MISMATCH) - CHK_ERRA(SEC_E_SECURITY_QOS_FAILED) - CHK_ERRA(SEC_E_UNFINISHED_CONTEXT_DELETED) - CHK_ERRA(SEC_E_NO_TGT_REPLY) - CHK_ERRA(SEC_E_NO_IP_ADDRESSES) - CHK_ERRA(SEC_E_WRONG_CREDENTIAL_HANDLE) - CHK_ERRA(SEC_E_CRYPTO_SYSTEM_INVALID) - CHK_ERRA(SEC_E_MAX_REFERRALS_EXCEEDED) - CHK_ERRA(SEC_E_MUST_BE_KDC) - CHK_ERRA(SEC_E_STRONG_CRYPTO_NOT_SUPPORTED) - CHK_ERRA(SEC_E_TOO_MANY_PRINCIPALS) - CHK_ERRA(SEC_E_NO_PA_DATA) - CHK_ERRA(SEC_E_PKINIT_NAME_MISMATCH) - CHK_ERRA(SEC_E_SMARTCARD_LOGON_REQUIRED) - CHK_ERRA(SEC_E_SHUTDOWN_IN_PROGRESS) - CHK_ERRA(SEC_E_KDC_INVALID_REQUEST) - CHK_ERRA(SEC_E_KDC_UNABLE_TO_REFER) - CHK_ERRA(SEC_E_KDC_UNKNOWN_ETYPE) - CHK_ERRA(SEC_E_UNSUPPORTED_PREAUTH) - CHK_ERRA(SEC_E_DELEGATION_REQUIRED) - CHK_ERRA(SEC_E_BAD_BINDINGS) - CHK_ERRA(SEC_E_MULTIPLE_ACCOUNTS) - CHK_ERRA(SEC_E_NO_KERB_KEY) -// CHK_ERRA(SEC_E_CERT_WRONG_USAGE) -// CHK_ERRA(SEC_E_DOWNGRADE_DETECTED) - CHK_ERRA(SEC_E_SMARTCARD_CERT_REVOKED) - CHK_ERRA(SEC_E_ISSUING_CA_UNTRUSTED) - CHK_ERRA(SEC_E_REVOCATION_OFFLINE_C) - CHK_ERRA(SEC_E_PKINIT_CLIENT_FAILURE) - CHK_ERRA(SEC_E_SMARTCARD_CERT_EXPIRED) -// CHK_ERRA(SEC_E_NO_SPM) -// CHK_ERRA(SEC_E_NOT_SUPPORTED) - CHK_ERRA(CRYPT_I_NEW_PROTECTION_REQUIRED) - CHK_ERRA(CRYPT_E_MISSING_PUBKEY_PARA) - CHK_ERRA(CRYPT_E_ASN1_ERROR) - CHK_ERRA(CRYPT_E_ASN1_INTERNAL) - CHK_ERRA(CRYPT_E_ASN1_EOD) - CHK_ERRA(CRYPT_E_ASN1_CORRUPT) - CHK_ERRA(CRYPT_E_ASN1_LARGE) - CHK_ERRA(CRYPT_E_ASN1_CONSTRAINT) - CHK_ERRA(CRYPT_E_ASN1_MEMORY) - CHK_ERRA(CRYPT_E_ASN1_OVERFLOW) - CHK_ERRA(CRYPT_E_ASN1_BADPDU) - CHK_ERRA(CRYPT_E_ASN1_BADARGS) - CHK_ERRA(CRYPT_E_ASN1_BADREAL) - CHK_ERRA(CRYPT_E_ASN1_BADTAG) - CHK_ERRA(CRYPT_E_ASN1_CHOICE) - CHK_ERRA(CRYPT_E_ASN1_RULE) - CHK_ERRA(CRYPT_E_ASN1_UTF8) - CHK_ERRA(CRYPT_E_ASN1_PDU_TYPE) - CHK_ERRA(CRYPT_E_ASN1_NYI) - CHK_ERRA(CRYPT_E_ASN1_EXTENDED) - CHK_ERRA(CRYPT_E_ASN1_NOEOD) - CHK_ERRA(CERTSRV_E_SERVER_SUSPENDED) - CHK_ERRA(CERTSRV_E_ENCODING_LENGTH) - CHK_ERRA(CERTSRV_E_ROLECONFLICT) - CHK_ERRA(CERTSRV_E_RESTRICTEDOFFICER) - CHK_ERRA(CERTSRV_E_KEY_ARCHIVAL_NOT_CONFIGURED) - CHK_ERRA(CERTSRV_E_NO_VALID_KRA) - CHK_ERRA(CERTSRV_E_BAD_REQUEST_KEY_ARCHIVAL) - CHK_ERRA(CERTSRV_E_NO_CAADMIN_DEFINED) - CHK_ERRA(CERTSRV_E_BAD_RENEWAL_CERT_ATTRIBUTE) - CHK_ERRA(CERTSRV_E_NO_DB_SESSIONS) - CHK_ERRA(CERTSRV_E_ALIGNMENT_FAULT) - CHK_ERRA(CERTSRV_E_ENROLL_DENIED) - CHK_ERRA(CERTSRV_E_TEMPLATE_DENIED) -// CHK_ERRA(CERTSRV_E_DOWNLEVEL_DC_SSL_OR_UPGRADE) - CHK_ERRA(CERTSRV_E_TEMPLATE_CONFLICT) - CHK_ERRA(CERTSRV_E_SUBJECT_ALT_NAME_REQUIRED) - CHK_ERRA(CERTSRV_E_ARCHIVED_KEY_REQUIRED) - CHK_ERRA(CERTSRV_E_SMIME_REQUIRED) - CHK_ERRA(CERTSRV_E_BAD_RENEWAL_SUBJECT) - CHK_ERRA(CERTSRV_E_BAD_TEMPLATE_VERSION) - CHK_ERRA(CERTSRV_E_TEMPLATE_POLICY_REQUIRED) - CHK_ERRA(CERTSRV_E_SIGNATURE_POLICY_REQUIRED) - CHK_ERRA(CERTSRV_E_SIGNATURE_COUNT) - CHK_ERRA(CERTSRV_E_SIGNATURE_REJECTED) - CHK_ERRA(CERTSRV_E_ISSUANCE_POLICY_REQUIRED) - CHK_ERRA(CERTSRV_E_SUBJECT_UPN_REQUIRED) - CHK_ERRA(CERTSRV_E_SUBJECT_DIRECTORY_GUID_REQUIRED) - CHK_ERRA(CERTSRV_E_SUBJECT_DNS_REQUIRED) - CHK_ERRA(CERTSRV_E_ARCHIVED_KEY_UNEXPECTED) - CHK_ERRA(CERTSRV_E_KEY_LENGTH) -// CHK_ERRA(CERTSRV_E_SUBJECT_EMAIL_REQUIRED) -// CHK_ERRA(CERTSRV_E_UNKNOWN_CERT_TYPE) -// CHK_ERRA(CERTSRV_E_CERT_TYPE_OVERLAP) - CHK_ERRA(XENROLL_E_KEY_NOT_EXPORTABLE) - CHK_ERRA(XENROLL_E_CANNOT_ADD_ROOT_CERT) - CHK_ERRA(XENROLL_E_RESPONSE_KA_HASH_NOT_FOUND) - CHK_ERRA(XENROLL_E_RESPONSE_UNEXPECTED_KA_HASH) - CHK_ERRA(XENROLL_E_RESPONSE_KA_HASH_MISMATCH) - CHK_ERRA(XENROLL_E_KEYSPEC_SMIME_MISMATCH) - CHK_ERRA(MSSIPOTF_E_OUTOFMEMRANGE) - CHK_ERRA(MSSIPOTF_E_CANTGETOBJECT) - CHK_ERRA(MSSIPOTF_E_NOHEADTABLE) - CHK_ERRA(MSSIPOTF_E_BAD_MAGICNUMBER) - CHK_ERRA(MSSIPOTF_E_BAD_OFFSET_TABLE) - CHK_ERRA(MSSIPOTF_E_TABLE_TAGORDER) - CHK_ERRA(MSSIPOTF_E_TABLE_LONGWORD) - CHK_ERRA(MSSIPOTF_E_BAD_FIRST_TABLE_PLACEMENT) - CHK_ERRA(MSSIPOTF_E_TABLES_OVERLAP) - CHK_ERRA(MSSIPOTF_E_TABLE_PADBYTES) - CHK_ERRA(MSSIPOTF_E_FILETOOSMALL) - CHK_ERRA(MSSIPOTF_E_TABLE_CHECKSUM) - CHK_ERRA(MSSIPOTF_E_FILE_CHECKSUM) - CHK_ERRA(MSSIPOTF_E_FAILED_POLICY) - CHK_ERRA(MSSIPOTF_E_FAILED_HINTS_CHECK) - CHK_ERRA(MSSIPOTF_E_NOT_OPENTYPE) - CHK_ERRA(MSSIPOTF_E_FILE) - CHK_ERRA(MSSIPOTF_E_CRYPT) - CHK_ERRA(MSSIPOTF_E_BADVERSION) - CHK_ERRA(MSSIPOTF_E_DSIG_STRUCTURE) - CHK_ERRA(MSSIPOTF_E_PCONST_CHECK) - CHK_ERRA(MSSIPOTF_E_STRUCTURE) - CHK_ERRA(TRUST_E_EXPLICIT_DISTRUST) - CHK_ERRA(CERT_E_UNTRUSTEDCA) - CHK_ERRA(CERT_E_INVALID_POLICY) - CHK_ERRA(CERT_E_INVALID_NAME) - CHK_ERRA(SPAPI_E_NOT_DISABLEABLE) - CHK_ERRA(SPAPI_E_CANT_REMOVE_DEVINST) - CHK_ERRA(SPAPI_E_INVALID_TARGET) - CHK_ERRA(SPAPI_E_DRIVER_NONNATIVE) - CHK_ERRA(SPAPI_E_IN_WOW64) - CHK_ERRA(SPAPI_E_SET_SYSTEM_RESTORE_POINT) - CHK_ERRA(SPAPI_E_INCORRECTLY_COPIED_INF) - CHK_ERRA(SPAPI_E_SCE_DISABLED) - CHK_ERRA(SCARD_E_NO_KEY_CONTAINER) - CHK_ERRA(SCARD_W_CARD_NOT_AUTHENTICATED) - CHK_ERRA(COMADMIN_E_OBJECTERRORS) - CHK_ERRA(COMADMIN_E_OBJECTINVALID) - CHK_ERRA(COMADMIN_E_KEYMISSING) - CHK_ERRA(COMADMIN_E_ALREADYINSTALLED) - CHK_ERRA(COMADMIN_E_APP_FILE_WRITEFAIL) - CHK_ERRA(COMADMIN_E_APP_FILE_READFAIL) - CHK_ERRA(COMADMIN_E_APP_FILE_VERSION) - CHK_ERRA(COMADMIN_E_BADPATH) - CHK_ERRA(COMADMIN_E_APPLICATIONEXISTS) - CHK_ERRA(COMADMIN_E_ROLEEXISTS) - CHK_ERRA(COMADMIN_E_CANTCOPYFILE) - CHK_ERRA(COMADMIN_E_NOUSER) - CHK_ERRA(COMADMIN_E_INVALIDUSERIDS) - CHK_ERRA(COMADMIN_E_NOREGISTRYCLSID) - CHK_ERRA(COMADMIN_E_BADREGISTRYPROGID) - CHK_ERRA(COMADMIN_E_AUTHENTICATIONLEVEL) - CHK_ERRA(COMADMIN_E_USERPASSWDNOTVALID) - CHK_ERRA(COMADMIN_E_CLSIDORIIDMISMATCH) - CHK_ERRA(COMADMIN_E_REMOTEINTERFACE) - CHK_ERRA(COMADMIN_E_DLLREGISTERSERVER) - CHK_ERRA(COMADMIN_E_NOSERVERSHARE) - CHK_ERRA(COMADMIN_E_DLLLOADFAILED) - CHK_ERRA(COMADMIN_E_BADREGISTRYLIBID) - CHK_ERRA(COMADMIN_E_APPDIRNOTFOUND) - CHK_ERRA(COMADMIN_E_REGISTRARFAILED) - CHK_ERRA(COMADMIN_E_COMPFILE_DOESNOTEXIST) - CHK_ERRA(COMADMIN_E_COMPFILE_LOADDLLFAIL) - CHK_ERRA(COMADMIN_E_COMPFILE_GETCLASSOBJ) - CHK_ERRA(COMADMIN_E_COMPFILE_CLASSNOTAVAIL) - CHK_ERRA(COMADMIN_E_COMPFILE_BADTLB) - CHK_ERRA(COMADMIN_E_COMPFILE_NOTINSTALLABLE) - CHK_ERRA(COMADMIN_E_NOTCHANGEABLE) - CHK_ERRA(COMADMIN_E_NOTDELETEABLE) - CHK_ERRA(COMADMIN_E_SESSION) - CHK_ERRA(COMADMIN_E_COMP_MOVE_LOCKED) - CHK_ERRA(COMADMIN_E_COMP_MOVE_BAD_DEST) - CHK_ERRA(COMADMIN_E_REGISTERTLB) - CHK_ERRA(COMADMIN_E_SYSTEMAPP) - CHK_ERRA(COMADMIN_E_COMPFILE_NOREGISTRAR) - CHK_ERRA(COMADMIN_E_COREQCOMPINSTALLED) - CHK_ERRA(COMADMIN_E_SERVICENOTINSTALLED) - CHK_ERRA(COMADMIN_E_PROPERTYSAVEFAILED) - CHK_ERRA(COMADMIN_E_OBJECTEXISTS) - CHK_ERRA(COMADMIN_E_COMPONENTEXISTS) - CHK_ERRA(COMADMIN_E_REGFILE_CORRUPT) - CHK_ERRA(COMADMIN_E_PROPERTY_OVERFLOW) - CHK_ERRA(COMADMIN_E_NOTINREGISTRY) - CHK_ERRA(COMADMIN_E_OBJECTNOTPOOLABLE) - CHK_ERRA(COMADMIN_E_APPLID_MATCHES_CLSID) - CHK_ERRA(COMADMIN_E_ROLE_DOES_NOT_EXIST) - CHK_ERRA(COMADMIN_E_START_APP_NEEDS_COMPONENTS) - CHK_ERRA(COMADMIN_E_REQUIRES_DIFFERENT_PLATFORM) - CHK_ERRA(COMADMIN_E_CAN_NOT_EXPORT_APP_PROXY) - CHK_ERRA(COMADMIN_E_CAN_NOT_START_APP) - CHK_ERRA(COMADMIN_E_CAN_NOT_EXPORT_SYS_APP) - CHK_ERRA(COMADMIN_E_CANT_SUBSCRIBE_TO_COMPONENT) - CHK_ERRA(COMADMIN_E_EVENTCLASS_CANT_BE_SUBSCRIBER) - CHK_ERRA(COMADMIN_E_LIB_APP_PROXY_INCOMPATIBLE) - CHK_ERRA(COMADMIN_E_BASE_PARTITION_ONLY) - CHK_ERRA(COMADMIN_E_START_APP_DISABLED) - CHK_ERRA(COMADMIN_E_CAT_DUPLICATE_PARTITION_NAME) - CHK_ERRA(COMADMIN_E_CAT_INVALID_PARTITION_NAME) - CHK_ERRA(COMADMIN_E_CAT_PARTITION_IN_USE) - CHK_ERRA(COMADMIN_E_FILE_PARTITION_DUPLICATE_FILES) - CHK_ERRA(COMADMIN_E_CAT_IMPORTED_COMPONENTS_NOT_ALLOWED) - CHK_ERRA(COMADMIN_E_AMBIGUOUS_APPLICATION_NAME) - CHK_ERRA(COMADMIN_E_AMBIGUOUS_PARTITION_NAME) - CHK_ERRA(COMADMIN_E_REGDB_NOTINITIALIZED) - CHK_ERRA(COMADMIN_E_REGDB_NOTOPEN) - CHK_ERRA(COMADMIN_E_REGDB_SYSTEMERR) - CHK_ERRA(COMADMIN_E_REGDB_ALREADYRUNNING) - CHK_ERRA(COMADMIN_E_MIG_VERSIONNOTSUPPORTED) - CHK_ERRA(COMADMIN_E_MIG_SCHEMANOTFOUND) - CHK_ERRA(COMADMIN_E_CAT_BITNESSMISMATCH) - CHK_ERRA(COMADMIN_E_CAT_UNACCEPTABLEBITNESS) - CHK_ERRA(COMADMIN_E_CAT_WRONGAPPBITNESS) - CHK_ERRA(COMADMIN_E_CAT_PAUSE_RESUME_NOT_SUPPORTED) - CHK_ERRA(COMADMIN_E_CAT_SERVERFAULT) - CHK_ERRA(COMQC_E_APPLICATION_NOT_QUEUED) - CHK_ERRA(COMQC_E_NO_QUEUEABLE_INTERFACES) - CHK_ERRA(COMQC_E_QUEUING_SERVICE_NOT_AVAILABLE) - CHK_ERRA(COMQC_E_NO_IPERSISTSTREAM) - CHK_ERRA(COMQC_E_BAD_MESSAGE) - CHK_ERRA(COMQC_E_UNAUTHENTICATED) - CHK_ERRA(COMQC_E_UNTRUSTED_ENQUEUER) - CHK_ERRA(MSDTC_E_DUPLICATE_RESOURCE) - CHK_ERRA(COMADMIN_E_OBJECT_PARENT_MISSING) - CHK_ERRA(COMADMIN_E_OBJECT_DOES_NOT_EXIST) - CHK_ERRA(COMADMIN_E_APP_NOT_RUNNING) - CHK_ERRA(COMADMIN_E_INVALID_PARTITION) - CHK_ERRA(COMADMIN_E_SVCAPP_NOT_POOLABLE_OR_RECYCLABLE) - CHK_ERRA(COMADMIN_E_USER_IN_SET) - CHK_ERRA(COMADMIN_E_CANTRECYCLELIBRARYAPPS) - CHK_ERRA(COMADMIN_E_CANTRECYCLESERVICEAPPS) - CHK_ERRA(COMADMIN_E_PROCESSALREADYRECYCLED) - CHK_ERRA(COMADMIN_E_PAUSEDPROCESSMAYNOTBERECYCLED) - CHK_ERRA(COMADMIN_E_CANTMAKEINPROCSERVICE) - CHK_ERRA(COMADMIN_E_PROGIDINUSEBYCLSID) - CHK_ERRA(COMADMIN_E_DEFAULT_PARTITION_NOT_IN_SET) - CHK_ERRA(COMADMIN_E_RECYCLEDPROCESSMAYNOTBEPAUSED) - CHK_ERRA(COMADMIN_E_PARTITION_ACCESSDENIED) - CHK_ERRA(COMADMIN_E_PARTITION_MSI_ONLY) - CHK_ERRA(COMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_1_0_FORMAT) - CHK_ERRA(COMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_NONBASE_PARTITIONS) - CHK_ERRA(COMADMIN_E_COMP_MOVE_SOURCE) - CHK_ERRA(COMADMIN_E_COMP_MOVE_DEST) - CHK_ERRA(COMADMIN_E_COMP_MOVE_PRIVATE) - CHK_ERRA(COMADMIN_E_BASEPARTITION_REQUIRED_IN_SET) - CHK_ERRA(COMADMIN_E_CANNOT_ALIAS_EVENTCLASS) - CHK_ERRA(COMADMIN_E_PRIVATE_ACCESSDENIED) - CHK_ERRA(COMADMIN_E_SAFERINVALID) - CHK_ERRA(COMADMIN_E_REGISTRY_ACCESSDENIED) -// CHK_ERRA(COMADMIN_E_PARTITIONS_DISABLED) -// CHK_ERR_WIN32A(ERROR_EXE_CANNOT_MODIFY_SIGNED_BINARY) -// CHK_ERR_WIN32A(ERROR_EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY) - CHK_ERR_WIN32A(ERROR_DISK_TOO_FRAGMENTED) - CHK_ERR_WIN32A(ERROR_DELETE_PENDING) -// CHK_ERR_WIN32A(ERROR_SCOPE_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_NOT_SAFEBOOT_SERVICE) - CHK_ERR_WIN32A(ERROR_JOURNAL_ENTRY_DELETED) - CHK_ERR_WIN32A(ERROR_ONLY_IF_CONNECTED) - CHK_ERR_WIN32A(ERROR_OVERRIDE_NOCHANGES) - CHK_ERR_WIN32A(ERROR_BAD_USER_PROFILE) - CHK_ERR_WIN32A(ERROR_NOT_SUPPORTED_ON_SBS) - CHK_ERR_WIN32A(ERROR_SERVER_SHUTDOWN_IN_PROGRESS) - CHK_ERR_WIN32A(ERROR_HOST_DOWN) - CHK_ERR_WIN32A(ERROR_NON_ACCOUNT_SID) - CHK_ERR_WIN32A(ERROR_NON_DOMAIN_SID) - CHK_ERR_WIN32A(ERROR_APPHELP_BLOCK) - CHK_ERR_WIN32A(ERROR_ACCESS_DISABLED_BY_POLICY) - CHK_ERR_WIN32A(ERROR_REG_NAT_CONSUMPTION) - CHK_ERR_WIN32A(ERROR_CSCSHARE_OFFLINE) - CHK_ERR_WIN32A(ERROR_PKINIT_FAILURE) - CHK_ERR_WIN32A(ERROR_SMARTCARD_SUBSYSTEM_FAILURE) - CHK_ERR_WIN32A(ERROR_DOWNGRADE_DETECTED) - CHK_ERR_WIN32A(ERROR_MACHINE_LOCKED) - CHK_ERR_WIN32A(ERROR_CALLBACK_SUPPLIED_INVALID_DATA) - CHK_ERR_WIN32A(ERROR_SYNC_FOREGROUND_REFRESH_REQUIRED) - CHK_ERR_WIN32A(ERROR_DRIVER_BLOCKED) - CHK_ERR_WIN32A(ERROR_INVALID_IMPORT_OF_NON_DLL) -// CHK_ERR_WIN32A(ERROR_ACCESS_DISABLED_WEBBLADE) -// CHK_ERR_WIN32A(ERROR_ACCESS_DISABLED_WEBBLADE_TAMPER) -// CHK_ERR_WIN32A(ERROR_RECOVERY_FAILURE) -// CHK_ERR_WIN32A(ERROR_ALREADY_FIBER) -// CHK_ERR_WIN32A(ERROR_ALREADY_THREAD) -// CHK_ERR_WIN32A(ERROR_STACK_BUFFER_OVERRUN) -// CHK_ERR_WIN32A(ERROR_PARAMETER_QUOTA_EXCEEDED) -// CHK_ERR_WIN32A(ERROR_DEBUGGER_INACTIVE) -// CHK_ERR_WIN32A(ERROR_DELAY_LOAD_FAILED) - CHK_ERR_WIN32A(ERROR_CURRENT_DOMAIN_NOT_ALLOWED) - CHK_ERR_WIN32A(ERROR_INSTALL_SERVICE_FAILURE) - CHK_ERR_WIN32A(ERROR_INSTALL_PACKAGE_VERSION) - CHK_ERR_WIN32A(ERROR_INSTALL_ALREADY_RUNNING) - CHK_ERR_WIN32A(ERROR_INSTALL_PACKAGE_OPEN_FAILED) - CHK_ERR_WIN32A(ERROR_INSTALL_PACKAGE_INVALID) - CHK_ERR_WIN32A(ERROR_INSTALL_UI_FAILURE) - CHK_ERR_WIN32A(ERROR_INSTALL_LOG_FAILURE) - CHK_ERR_WIN32A(ERROR_INSTALL_LANGUAGE_UNSUPPORTED) - CHK_ERR_WIN32A(ERROR_INSTALL_TRANSFORM_FAILURE) - CHK_ERR_WIN32A(ERROR_INSTALL_PACKAGE_REJECTED) - CHK_ERR_WIN32A(ERROR_FUNCTION_NOT_CALLED) - CHK_ERR_WIN32A(ERROR_FUNCTION_FAILED) - CHK_ERR_WIN32A(ERROR_INVALID_TABLE) - CHK_ERR_WIN32A(ERROR_DATATYPE_MISMATCH) - CHK_ERR_WIN32A(ERROR_UNSUPPORTED_TYPE) - CHK_ERR_WIN32A(ERROR_CREATE_FAILED) - CHK_ERR_WIN32A(ERROR_INSTALL_TEMP_UNWRITABLE) - CHK_ERR_WIN32A(ERROR_INSTALL_PLATFORM_UNSUPPORTED) - CHK_ERR_WIN32A(ERROR_INSTALL_NOTUSED) - CHK_ERR_WIN32A(ERROR_PATCH_PACKAGE_OPEN_FAILED) - CHK_ERR_WIN32A(ERROR_PATCH_PACKAGE_INVALID) - CHK_ERR_WIN32A(ERROR_PATCH_PACKAGE_UNSUPPORTED) - CHK_ERR_WIN32A(ERROR_PRODUCT_VERSION) - CHK_ERR_WIN32A(ERROR_INVALID_COMMAND_LINE) - CHK_ERR_WIN32A(ERROR_INSTALL_REMOTE_DISALLOWED) - CHK_ERR_WIN32A(ERROR_SUCCESS_REBOOT_INITIATED) - CHK_ERR_WIN32A(ERROR_PATCH_TARGET_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_PATCH_PACKAGE_REJECTED) - CHK_ERR_WIN32A(ERROR_INSTALL_TRANSFORM_REJECTED) -// CHK_ERR_WIN32A(ERROR_INSTALL_REMOTE_PROHIBITED) - CHK_ERR_WIN32A(RPC_S_ENTRY_TYPE_MISMATCH) - CHK_ERR_WIN32A(RPC_S_NOT_ALL_OBJS_EXPORTED) - CHK_ERR_WIN32A(RPC_S_INTERFACE_NOT_EXPORTED) - CHK_ERR_WIN32A(RPC_S_PROFILE_NOT_ADDED) - CHK_ERR_WIN32A(RPC_S_PRF_ELT_NOT_ADDED) - CHK_ERR_WIN32A(RPC_S_PRF_ELT_NOT_REMOVED) - CHK_ERR_WIN32A(RPC_S_GRP_ELT_NOT_ADDED) - CHK_ERR_WIN32A(RPC_S_GRP_ELT_NOT_REMOVED) - CHK_ERR_WIN32A(ERROR_KM_DRIVER_BLOCKED) - CHK_ERR_WIN32A(ERROR_CONTEXT_EXPIRED) -// CHK_ERR_WIN32A(ERROR_PER_USER_TRUST_QUOTA_EXCEEDED) -// CHK_ERR_WIN32A(ERROR_ALL_USER_TRUST_QUOTA_EXCEEDED) -// CHK_ERR_WIN32A(ERROR_USER_DELETE_TRUST_QUOTA_EXCEEDED) - CHK_ERR_WIN32A(ERROR_CONNECTED_OTHER_PASSWORD_DEFAULT) - CHK_ERR_WIN32A(ERROR_PRINTER_DRIVER_WARNED) - CHK_ERR_WIN32A(ERROR_PRINTER_DRIVER_BLOCKED) - CHK_ERR_WIN32A(ERROR_VOLUME_CONTAINS_SYS_FILES) - CHK_ERR_WIN32A(ERROR_INDIGENOUS_TYPE) - CHK_ERR_WIN32A(ERROR_NO_SUPPORTING_DRIVES) - CHK_ERR_WIN32A(ERROR_CLEANER_CARTRIDGE_INSTALLED) - CHK_ERR_WIN32A(ERROR_REPARSE_TAG_INVALID) - CHK_ERR_WIN32A(ERROR_REPARSE_TAG_MISMATCH) - CHK_ERR_WIN32A(ERROR_VOLUME_NOT_SIS_ENABLED) - CHK_ERR_WIN32A(ERROR_QUORUM_OWNER_ALIVE) - CHK_ERR_WIN32A(ERROR_NETWORK_NOT_AVAILABLE) - CHK_ERR_WIN32A(ERROR_NODE_NOT_AVAILABLE) - CHK_ERR_WIN32A(ERROR_ALL_NODES_NOT_AVAILABLE) - CHK_ERR_WIN32A(ERROR_RESOURCE_FAILED) - CHK_ERR_WIN32A(ERROR_CLUSTER_INVALID_NODE) - CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_EXISTS) - CHK_ERR_WIN32A(ERROR_CLUSTER_JOIN_IN_PROGRESS) - CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_CLUSTER_LOCAL_NODE_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_CLUSTER_NETWORK_EXISTS) - CHK_ERR_WIN32A(ERROR_CLUSTER_NETWORK_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_CLUSTER_NETINTERFACE_EXISTS) - CHK_ERR_WIN32A(ERROR_CLUSTER_NETINTERFACE_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_CLUSTER_INVALID_REQUEST) - CHK_ERR_WIN32A(ERROR_CLUSTER_INVALID_NETWORK_PROVIDER) - CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_DOWN) - CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_UNREACHABLE) - CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_NOT_MEMBER) - CHK_ERR_WIN32A(ERROR_CLUSTER_JOIN_NOT_IN_PROGRESS) - CHK_ERR_WIN32A(ERROR_CLUSTER_INVALID_NETWORK) - CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_UP) - CHK_ERR_WIN32A(ERROR_CLUSTER_IPADDR_IN_USE) - CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_NOT_PAUSED) - CHK_ERR_WIN32A(ERROR_CLUSTER_NO_SECURITY_CONTEXT) - CHK_ERR_WIN32A(ERROR_CLUSTER_NETWORK_NOT_INTERNAL) - CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_ALREADY_UP) - CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_ALREADY_DOWN) - CHK_ERR_WIN32A(ERROR_CLUSTER_NETWORK_ALREADY_ONLINE) - CHK_ERR_WIN32A(ERROR_CLUSTER_NETWORK_ALREADY_OFFLINE) - CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_ALREADY_MEMBER) - CHK_ERR_WIN32A(ERROR_CLUSTER_LAST_INTERNAL_NETWORK) - CHK_ERR_WIN32A(ERROR_CLUSTER_NETWORK_HAS_DEPENDENTS) - CHK_ERR_WIN32A(ERROR_INVALID_OPERATION_ON_QUORUM) - CHK_ERR_WIN32A(ERROR_DEPENDENCY_NOT_ALLOWED) - CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_PAUSED) - CHK_ERR_WIN32A(ERROR_NODE_CANT_HOST_RESOURCE) - CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_NOT_READY) - CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_SHUTTING_DOWN) - CHK_ERR_WIN32A(ERROR_CLUSTER_JOIN_ABORTED) - CHK_ERR_WIN32A(ERROR_CLUSTER_INCOMPATIBLE_VERSIONS) - CHK_ERR_WIN32A(ERROR_CLUSTER_MAXNUM_OF_RESOURCES_EXCEEDED) - CHK_ERR_WIN32A(ERROR_CLUSTER_SYSTEM_CONFIG_CHANGED) - CHK_ERR_WIN32A(ERROR_CLUSTER_RESOURCE_TYPE_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_CLUSTER_RESTYPE_NOT_SUPPORTED) - CHK_ERR_WIN32A(ERROR_CLUSTER_RESNAME_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_CLUSTER_NO_RPC_PACKAGES_REGISTERED) - CHK_ERR_WIN32A(ERROR_CLUSTER_OWNER_NOT_IN_PREFLIST) - CHK_ERR_WIN32A(ERROR_CLUSTER_DATABASE_SEQMISMATCH) - CHK_ERR_WIN32A(ERROR_RESMON_INVALID_STATE) - CHK_ERR_WIN32A(ERROR_CLUSTER_GUM_NOT_LOCKER) - CHK_ERR_WIN32A(ERROR_QUORUM_DISK_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_DATABASE_BACKUP_CORRUPT) - CHK_ERR_WIN32A(ERROR_CLUSTER_NODE_ALREADY_HAS_DFS_ROOT) - CHK_ERR_WIN32A(ERROR_RESOURCE_PROPERTY_UNCHANGEABLE) - CHK_ERR_WIN32A(ERROR_CLUSTER_MEMBERSHIP_INVALID_STATE) - CHK_ERR_WIN32A(ERROR_CLUSTER_QUORUMLOG_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_CLUSTER_MEMBERSHIP_HALT) - CHK_ERR_WIN32A(ERROR_CLUSTER_INSTANCE_ID_MISMATCH) - CHK_ERR_WIN32A(ERROR_CLUSTER_NETWORK_NOT_FOUND_FOR_IP) - CHK_ERR_WIN32A(ERROR_CLUSTER_PROPERTY_DATA_TYPE_MISMATCH) - CHK_ERR_WIN32A(ERROR_CLUSTER_EVICT_WITHOUT_CLEANUP) - CHK_ERR_WIN32A(ERROR_CLUSTER_PARAMETER_MISMATCH) - CHK_ERR_WIN32A(ERROR_NODE_CANNOT_BE_CLUSTERED) - CHK_ERR_WIN32A(ERROR_CLUSTER_WRONG_OS_VERSION) - CHK_ERR_WIN32A(ERROR_CLUSTER_CANT_CREATE_DUP_CLUSTER_NAME) -// CHK_ERR_WIN32A(ERROR_CLUSCFG_ALREADY_COMMITTED) -// CHK_ERR_WIN32A(ERROR_CLUSCFG_ROLLBACK_FAILED) -// CHK_ERR_WIN32A(ERROR_CLUSCFG_SYSTEM_DISK_DRIVE_LETTER_CONFLICT) -// CHK_ERR_WIN32A(ERROR_CLUSTER_OLD_VERSION) -// CHK_ERR_WIN32A(ERROR_CLUSTER_MISMATCHED_COMPUTER_ACCT_NAME) - CHK_ERR_WIN32A(ERROR_FILE_READ_ONLY) - CHK_ERR_WIN32A(ERROR_DIR_EFS_DISALLOWED) - CHK_ERR_WIN32A(ERROR_EFS_SERVER_NOT_TRUSTED) - CHK_ERR_WIN32A(ERROR_BAD_RECOVERY_POLICY) - CHK_ERR_WIN32A(ERROR_EFS_ALG_BLOB_TOO_BIG) - CHK_ERR_WIN32A(ERROR_VOLUME_NOT_SUPPORT_EFS) - CHK_ERR_WIN32A(ERROR_EFS_DISABLED) - CHK_ERR_WIN32A(ERROR_EFS_VERSION_NOT_SUPPORT) - CHK_ERR_WIN32A(SCHED_E_SERVICE_NOT_LOCALSYSTEM) - CHK_ERR_WIN32A(ERROR_CTX_CLIENT_LICENSE_IN_USE) - CHK_ERR_WIN32A(ERROR_CTX_CLIENT_LICENSE_NOT_SET) - CHK_ERR_WIN32A(ERROR_CTX_LICENSE_NOT_AVAILABLE) - CHK_ERR_WIN32A(ERROR_CTX_LICENSE_CLIENT_INVALID) - CHK_ERR_WIN32A(ERROR_CTX_LICENSE_EXPIRED) - CHK_ERR_WIN32A(ERROR_CTX_SHADOW_NOT_RUNNING) - CHK_ERR_WIN32A(ERROR_CTX_SHADOW_ENDED_BY_MODE_CHANGE) -// CHK_ERR_WIN32A(ERROR_ACTIVATION_COUNT_EXCEEDED) - CHK_ERR_WIN32A(ERROR_DS_SORT_CONTROL_MISSING) - CHK_ERR_WIN32A(ERROR_DS_OFFSET_RANGE_ERROR) - CHK_ERR_WIN32A(ERROR_DS_OBJECT_BEING_REMOVED) - CHK_ERR_WIN32A(ERROR_DS_DS_REQUIRED) - CHK_ERR_WIN32A(ERROR_DS_INVALID_LDAP_DISPLAY_NAME) - CHK_ERR_WIN32A(ERROR_DS_NON_BASE_SEARCH) - CHK_ERR_WIN32A(ERROR_DS_CANT_RETRIEVE_ATTS) - CHK_ERR_WIN32A(ERROR_DS_BACKLINK_WITHOUT_LINK) - CHK_ERR_WIN32A(ERROR_DS_EPOCH_MISMATCH) - CHK_ERR_WIN32A(ERROR_DS_SRC_NAME_MISMATCH) - CHK_ERR_WIN32A(ERROR_DS_SRC_AND_DST_NC_IDENTICAL) - CHK_ERR_WIN32A(ERROR_DS_DST_NC_MISMATCH) - CHK_ERR_WIN32A(ERROR_DS_NOT_AUTHORITIVE_FOR_DST_NC) - CHK_ERR_WIN32A(ERROR_DS_SRC_GUID_MISMATCH) - CHK_ERR_WIN32A(ERROR_DS_CANT_MOVE_DELETED_OBJECT) - CHK_ERR_WIN32A(ERROR_DS_PDC_OPERATION_IN_PROGRESS) - CHK_ERR_WIN32A(ERROR_DS_CROSS_DOMAIN_CLEANUP_REQD) - CHK_ERR_WIN32A(ERROR_DS_ILLEGAL_XDOM_MOVE_OPERATION) - CHK_ERR_WIN32A(ERROR_DS_CANT_WITH_ACCT_GROUP_MEMBERSHPS) - CHK_ERR_WIN32A(ERROR_DS_NC_MUST_HAVE_NC_PARENT) - CHK_ERR_WIN32A(ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE) - CHK_ERR_WIN32A(ERROR_DS_DST_DOMAIN_NOT_NATIVE) - CHK_ERR_WIN32A(ERROR_DS_MISSING_INFRASTRUCTURE_CONTAINER) - CHK_ERR_WIN32A(ERROR_DS_CANT_MOVE_ACCOUNT_GROUP) - CHK_ERR_WIN32A(ERROR_DS_CANT_MOVE_RESOURCE_GROUP) - CHK_ERR_WIN32A(ERROR_DS_INVALID_SEARCH_FLAG) - CHK_ERR_WIN32A(ERROR_DS_NO_TREE_DELETE_ABOVE_NC) - CHK_ERR_WIN32A(ERROR_DS_COULDNT_LOCK_TREE_FOR_DELETE) - CHK_ERR_WIN32A(ERROR_DS_COULDNT_IDENTIFY_OBJECTS_FOR_TREE_DELETE) - CHK_ERR_WIN32A(ERROR_DS_SAM_INIT_FAILURE) - CHK_ERR_WIN32A(ERROR_DS_SENSITIVE_GROUP_VIOLATION) - CHK_ERR_WIN32A(ERROR_DS_CANT_MOD_PRIMARYGROUPID) - CHK_ERR_WIN32A(ERROR_DS_ILLEGAL_BASE_SCHEMA_MOD) - CHK_ERR_WIN32A(ERROR_DS_NONSAFE_SCHEMA_CHANGE) - CHK_ERR_WIN32A(ERROR_DS_SCHEMA_UPDATE_DISALLOWED) - CHK_ERR_WIN32A(ERROR_DS_CANT_CREATE_UNDER_SCHEMA) - CHK_ERR_WIN32A(ERROR_DS_INSTALL_NO_SRC_SCH_VERSION) - CHK_ERR_WIN32A(ERROR_DS_INSTALL_NO_SCH_VERSION_IN_INIFILE) - CHK_ERR_WIN32A(ERROR_DS_INVALID_GROUP_TYPE) - CHK_ERR_WIN32A(ERROR_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN) - CHK_ERR_WIN32A(ERROR_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN) - CHK_ERR_WIN32A(ERROR_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER) - CHK_ERR_WIN32A(ERROR_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER) - CHK_ERR_WIN32A(ERROR_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER) - CHK_ERR_WIN32A(ERROR_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER) - CHK_ERR_WIN32A(ERROR_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER) - CHK_ERR_WIN32A(ERROR_DS_HAVE_PRIMARY_MEMBERS) - CHK_ERR_WIN32A(ERROR_DS_STRING_SD_CONVERSION_FAILED) - CHK_ERR_WIN32A(ERROR_DS_NAMING_MASTER_GC) - CHK_ERR_WIN32A(ERROR_DS_DNS_LOOKUP_FAILURE) - CHK_ERR_WIN32A(ERROR_DS_COULDNT_UPDATE_SPNS) - CHK_ERR_WIN32A(ERROR_DS_CANT_RETRIEVE_SD) - CHK_ERR_WIN32A(ERROR_DS_KEY_NOT_UNIQUE) - CHK_ERR_WIN32A(ERROR_DS_WRONG_LINKED_ATT_SYNTAX) - CHK_ERR_WIN32A(ERROR_DS_SAM_NEED_BOOTKEY_PASSWORD) - CHK_ERR_WIN32A(ERROR_DS_SAM_NEED_BOOTKEY_FLOPPY) - CHK_ERR_WIN32A(ERROR_DS_CANT_START) - CHK_ERR_WIN32A(ERROR_DS_INIT_FAILURE) - CHK_ERR_WIN32A(ERROR_DS_NO_PKT_PRIVACY_ON_CONNECTION) - CHK_ERR_WIN32A(ERROR_DS_SOURCE_DOMAIN_IN_FOREST) - CHK_ERR_WIN32A(ERROR_DS_DESTINATION_DOMAIN_NOT_IN_FOREST) - CHK_ERR_WIN32A(ERROR_DS_DESTINATION_AUDITING_NOT_ENABLED) - CHK_ERR_WIN32A(ERROR_DS_CANT_FIND_DC_FOR_SRC_DOMAIN) - CHK_ERR_WIN32A(ERROR_DS_SRC_OBJ_NOT_GROUP_OR_USER) - CHK_ERR_WIN32A(ERROR_DS_SRC_SID_EXISTS_IN_FOREST) - CHK_ERR_WIN32A(ERROR_DS_SRC_AND_DST_OBJECT_CLASS_MISMATCH) - CHK_ERR_WIN32A(ERROR_SAM_INIT_FAILURE) - CHK_ERR_WIN32A(ERROR_DS_DRA_SCHEMA_INFO_SHIP) - CHK_ERR_WIN32A(ERROR_DS_DRA_SCHEMA_CONFLICT) - CHK_ERR_WIN32A(ERROR_DS_DRA_EARLIER_SCHEMA_CONFLICT) - CHK_ERR_WIN32A(ERROR_DS_DRA_OBJ_NC_MISMATCH) - CHK_ERR_WIN32A(ERROR_DS_NC_STILL_HAS_DSAS) - CHK_ERR_WIN32A(ERROR_DS_GC_REQUIRED) - CHK_ERR_WIN32A(ERROR_DS_LOCAL_MEMBER_OF_LOCAL_ONLY) - CHK_ERR_WIN32A(ERROR_DS_NO_FPO_IN_UNIVERSAL_GROUPS) - CHK_ERR_WIN32A(ERROR_DS_CANT_ADD_TO_GC) - CHK_ERR_WIN32A(ERROR_DS_NO_CHECKPOINT_WITH_PDC) - CHK_ERR_WIN32A(ERROR_DS_SOURCE_AUDITING_NOT_ENABLED) - CHK_ERR_WIN32A(ERROR_DS_CANT_CREATE_IN_NONDOMAIN_NC) - CHK_ERR_WIN32A(ERROR_DS_INVALID_NAME_FOR_SPN) - CHK_ERR_WIN32A(ERROR_DS_FILTER_USES_CONTRUCTED_ATTRS) - CHK_ERR_WIN32A(ERROR_DS_UNICODEPWD_NOT_IN_QUOTES) - CHK_ERR_WIN32A(ERROR_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED) - CHK_ERR_WIN32A(ERROR_DS_MUST_BE_RUN_ON_DST_DC) - CHK_ERR_WIN32A(ERROR_DS_SRC_DC_MUST_BE_SP4_OR_GREATER) - CHK_ERR_WIN32A(ERROR_DS_CANT_TREE_DELETE_CRITICAL_OBJ) - CHK_ERR_WIN32A(ERROR_DS_INIT_FAILURE_CONSOLE) - CHK_ERR_WIN32A(ERROR_DS_SAM_INIT_FAILURE_CONSOLE) - CHK_ERR_WIN32A(ERROR_DS_FOREST_VERSION_TOO_HIGH) - CHK_ERR_WIN32A(ERROR_DS_DOMAIN_VERSION_TOO_HIGH) - CHK_ERR_WIN32A(ERROR_DS_FOREST_VERSION_TOO_LOW) - CHK_ERR_WIN32A(ERROR_DS_DOMAIN_VERSION_TOO_LOW) - CHK_ERR_WIN32A(ERROR_DS_INCOMPATIBLE_VERSION) - CHK_ERR_WIN32A(ERROR_DS_LOW_DSA_VERSION) - CHK_ERR_WIN32A(ERROR_DS_NO_BEHAVIOR_VERSION_IN_MIXEDDOMAIN) - CHK_ERR_WIN32A(ERROR_DS_NOT_SUPPORTED_SORT_ORDER) - CHK_ERR_WIN32A(ERROR_DS_NAME_NOT_UNIQUE) - CHK_ERR_WIN32A(ERROR_DS_MACHINE_ACCOUNT_CREATED_PRENT4) - CHK_ERR_WIN32A(ERROR_DS_OUT_OF_VERSION_STORE) - CHK_ERR_WIN32A(ERROR_DS_INCOMPATIBLE_CONTROLS_USED) - CHK_ERR_WIN32A(ERROR_DS_NO_REF_DOMAIN) - CHK_ERR_WIN32A(ERROR_DS_RESERVED_LINK_ID) - CHK_ERR_WIN32A(ERROR_DS_LINK_ID_NOT_AVAILABLE) - CHK_ERR_WIN32A(ERROR_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER) - CHK_ERR_WIN32A(ERROR_DS_MODIFYDN_DISALLOWED_BY_INSTANCE_TYPE) - CHK_ERR_WIN32A(ERROR_DS_NO_OBJECT_MOVE_IN_SCHEMA_NC) - CHK_ERR_WIN32A(ERROR_DS_MODIFYDN_DISALLOWED_BY_FLAG) - CHK_ERR_WIN32A(ERROR_DS_MODIFYDN_WRONG_GRANDPARENT) - CHK_ERR_WIN32A(ERROR_DS_NAME_ERROR_TRUST_REFERRAL) - CHK_ERR_WIN32A(ERROR_NOT_SUPPORTED_ON_STANDARD_SERVER) - CHK_ERR_WIN32A(ERROR_DS_CANT_ACCESS_REMOTE_PART_OF_AD) - CHK_ERR_WIN32A(ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE_V2) - CHK_ERR_WIN32A(ERROR_DS_THREAD_LIMIT_EXCEEDED) - CHK_ERR_WIN32A(ERROR_DS_NOT_CLOSEST) - CHK_ERR_WIN32A(ERROR_DS_CANT_DERIVE_SPN_WITHOUT_SERVER_REF) - CHK_ERR_WIN32A(ERROR_DS_SINGLE_USER_MODE_FAILED) - CHK_ERR_WIN32A(ERROR_DS_NTDSCRIPT_SYNTAX_ERROR) - CHK_ERR_WIN32A(ERROR_DS_NTDSCRIPT_PROCESS_ERROR) - CHK_ERR_WIN32A(ERROR_DS_DIFFERENT_REPL_EPOCHS) - CHK_ERR_WIN32A(ERROR_DS_DRS_EXTENSIONS_CHANGED) - CHK_ERR_WIN32A(ERROR_DS_REPLICA_SET_CHANGE_NOT_ALLOWED_ON_DISABLED_CR) - CHK_ERR_WIN32A(ERROR_DS_NO_MSDS_INTID) - CHK_ERR_WIN32A(ERROR_DS_DUP_MSDS_INTID) - CHK_ERR_WIN32A(ERROR_DS_EXISTS_IN_RDNATTID) - CHK_ERR_WIN32A(ERROR_DS_AUTHORIZATION_FAILED) - CHK_ERR_WIN32A(ERROR_DS_INVALID_SCRIPT) - CHK_ERR_WIN32A(ERROR_DS_REMOTE_CROSSREF_OP_FAILED) -// CHK_ERR_WIN32A(ERROR_DS_CROSS_REF_BUSY) -// CHK_ERR_WIN32A(ERROR_DS_CANT_DERIVE_SPN_FOR_DELETED_DOMAIN) -// CHK_ERR_WIN32A(ERROR_DS_CANT_DEMOTE_WITH_WRITEABLE_NC) -// CHK_ERR_WIN32A(ERROR_DS_DUPLICATE_ID_FOUND) -// CHK_ERR_WIN32A(ERROR_DS_INSUFFICIENT_ATTR_TO_CREATE_OBJECT) -// CHK_ERR_WIN32A(ERROR_DS_GROUP_CONVERSION_ERROR) -// CHK_ERR_WIN32A(ERROR_DS_CANT_MOVE_APP_BASIC_GROUP) -// CHK_ERR_WIN32A(ERROR_DS_CANT_MOVE_APP_QUERY_GROUP) -// CHK_ERR_WIN32A(ERROR_DS_ROLE_NOT_VERIFIED) -// CHK_ERR_WIN32A(ERROR_DS_WKO_CONTAINER_CANNOT_BE_SPECIAL) -// CHK_ERR_WIN32A(ERROR_DS_DOMAIN_RENAME_IN_PROGRESS) -// CHK_ERR_WIN32A(ERROR_DS_EXISTING_AD_CHILD_NC) -// CHK_ERR_WIN32A(DNS_ERROR_INVALID_NAME_CHAR) -// CHK_ERR_WIN32A(DNS_ERROR_NUMERIC_NAME) -// CHK_ERR_WIN32A(DNS_ERROR_NOT_ALLOWED_ON_ROOT_SERVER) -// CHK_ERR_WIN32A(DNS_ERROR_NOT_ALLOWED_UNDER_DELEGATION) -// CHK_ERR_WIN32A(DNS_ERROR_CANNOT_FIND_ROOT_HINTS) -// CHK_ERR_WIN32A(DNS_ERROR_INCONSISTENT_ROOT_HINTS) - CHK_ERR_WIN32A(DNS_ERROR_FORWARDER_ALREADY_EXISTS) - CHK_ERR_WIN32A(DNS_ERROR_ZONE_REQUIRES_MASTER_IP) - CHK_ERR_WIN32A(DNS_ERROR_ZONE_IS_SHUTDOWN) - CHK_ERR_WIN32A(DNS_ERROR_DP_BASE) - CHK_ERR_WIN32A(DNS_ERROR_DP_DOES_NOT_EXIST) - CHK_ERR_WIN32A(DNS_ERROR_DP_ALREADY_EXISTS) - CHK_ERR_WIN32A(DNS_ERROR_DP_NOT_ENLISTED) - CHK_ERR_WIN32A(DNS_ERROR_DP_ALREADY_ENLISTED) -// CHK_ERR_WIN32A(DNS_ERROR_DP_NOT_AVAILABLE) - CHK_ERR_WIN32A(WSA_QOS_ESERVICETYPE) - CHK_ERR_WIN32A(WSA_QOS_EFLOWSPEC) - CHK_ERR_WIN32A(WSA_QOS_EPROVSPECBUF) - CHK_ERR_WIN32A(WSA_QOS_EFILTERSTYLE) - CHK_ERR_WIN32A(WSA_QOS_EFILTERTYPE) - CHK_ERR_WIN32A(WSA_QOS_EFILTERCOUNT) - CHK_ERR_WIN32A(WSA_QOS_EOBJLENGTH) - CHK_ERR_WIN32A(WSA_QOS_EFLOWCOUNT) - CHK_ERR_WIN32A(WSA_QOS_EUNKOWNPSOBJ) - CHK_ERR_WIN32A(WSA_QOS_EPOLICYOBJ) - CHK_ERR_WIN32A(WSA_QOS_EFLOWDESC) - CHK_ERR_WIN32A(WSA_QOS_EPSFLOWSPEC) - CHK_ERR_WIN32A(WSA_QOS_EPSFILTERSPEC) - CHK_ERR_WIN32A(WSA_QOS_ESDMODEOBJ) - CHK_ERR_WIN32A(WSA_QOS_ESHAPERATEOBJ) - CHK_ERR_WIN32A(WSA_QOS_RESERVED_PETYPE) - CHK_ERR_WIN32A(ERROR_SXS_SECTION_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_SXS_CANT_GEN_ACTCTX) - CHK_ERR_WIN32A(ERROR_SXS_INVALID_ACTCTXDATA_FORMAT) - CHK_ERR_WIN32A(ERROR_SXS_ASSEMBLY_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_SXS_MANIFEST_FORMAT_ERROR) - CHK_ERR_WIN32A(ERROR_SXS_MANIFEST_PARSE_ERROR) - CHK_ERR_WIN32A(ERROR_SXS_ACTIVATION_CONTEXT_DISABLED) - CHK_ERR_WIN32A(ERROR_SXS_KEY_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_SXS_VERSION_CONFLICT) - CHK_ERR_WIN32A(ERROR_SXS_WRONG_SECTION_TYPE) - CHK_ERR_WIN32A(ERROR_SXS_THREAD_QUERIES_DISABLED) - CHK_ERR_WIN32A(ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET) - CHK_ERR_WIN32A(ERROR_SXS_UNKNOWN_ENCODING_GROUP) - CHK_ERR_WIN32A(ERROR_SXS_UNKNOWN_ENCODING) - CHK_ERR_WIN32A(ERROR_SXS_INVALID_XML_NAMESPACE_URI) - CHK_ERR_WIN32A(ERROR_SXS_ROOT_MANIFEST_DEPENDENCY_NOT_INSTALLED) - CHK_ERR_WIN32A(ERROR_SXS_LEAF_MANIFEST_DEPENDENCY_NOT_INSTALLED) - CHK_ERR_WIN32A(ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE) - CHK_ERR_WIN32A(ERROR_SXS_MANIFEST_MISSING_REQUIRED_DEFAULT_NAMESPACE) - CHK_ERR_WIN32A(ERROR_SXS_MANIFEST_INVALID_REQUIRED_DEFAULT_NAMESPACE) - CHK_ERR_WIN32A(ERROR_SXS_PRIVATE_MANIFEST_CROSS_PATH_WITH_REPARSE_POINT) - CHK_ERR_WIN32A(ERROR_SXS_DUPLICATE_DLL_NAME) - CHK_ERR_WIN32A(ERROR_SXS_DUPLICATE_WINDOWCLASS_NAME) - CHK_ERR_WIN32A(ERROR_SXS_DUPLICATE_CLSID) - CHK_ERR_WIN32A(ERROR_SXS_DUPLICATE_IID) - CHK_ERR_WIN32A(ERROR_SXS_DUPLICATE_TLBID) - CHK_ERR_WIN32A(ERROR_SXS_DUPLICATE_PROGID) - CHK_ERR_WIN32A(ERROR_SXS_DUPLICATE_ASSEMBLY_NAME) - CHK_ERR_WIN32A(ERROR_SXS_FILE_HASH_MISMATCH) - CHK_ERR_WIN32A(ERROR_SXS_POLICY_PARSE_ERROR) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_MISSINGQUOTE) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_COMMENTSYNTAX) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_BADSTARTNAMECHAR) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_BADNAMECHAR) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_BADCHARINSTRING) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_XMLDECLSYNTAX) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_BADCHARDATA) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_MISSINGWHITESPACE) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_EXPECTINGTAGEND) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_MISSINGSEMICOLON) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNBALANCEDPAREN) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_INTERNALERROR) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNEXPECTED_WHITESPACE) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_INCOMPLETE_ENCODING) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_MISSING_PAREN) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_EXPECTINGCLOSEQUOTE) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_MULTIPLE_COLONS) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_INVALID_DECIMAL) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_INVALID_HEXIDECIMAL) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_INVALID_UNICODE) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_WHITESPACEORQUESTIONMARK) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNEXPECTEDENDTAG) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNCLOSEDTAG) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_DUPLICATEATTRIBUTE) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_MULTIPLEROOTS) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_INVALIDATROOTLEVEL) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_BADXMLDECL) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_MISSINGROOT) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNEXPECTEDEOF) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_BADPEREFINSUBSET) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNCLOSEDSTARTTAG) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNCLOSEDENDTAG) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNCLOSEDSTRING) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNCLOSEDCOMMENT) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNCLOSEDDECL) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNCLOSEDCDATA) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_RESERVEDNAMESPACE) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_INVALIDENCODING) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_INVALIDSWITCH) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_BADXMLCASE) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_INVALID_STANDALONE) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_UNEXPECTED_STANDALONE) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_INVALID_VERSION) - CHK_ERR_WIN32A(ERROR_SXS_XML_E_MISSINGEQUALS) - CHK_ERR_WIN32A(ERROR_SXS_PROTECTION_RECOVERY_FAILED) - CHK_ERR_WIN32A(ERROR_SXS_PROTECTION_PUBLIC_KEY_TOO_SHORT) - CHK_ERR_WIN32A(ERROR_SXS_PROTECTION_CATALOG_NOT_VALID) - CHK_ERR_WIN32A(ERROR_SXS_UNTRANSLATABLE_HRESULT) - CHK_ERR_WIN32A(ERROR_SXS_PROTECTION_CATALOG_FILE_MISSING) - CHK_ERR_WIN32A(ERROR_SXS_MISSING_ASSEMBLY_IDENTITY_ATTRIBUTE) - CHK_ERR_WIN32A(ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE_NAME) - CHK_ERR_WIN32A(ERROR_IPSEC_QM_POLICY_EXISTS) - CHK_ERR_WIN32A(ERROR_IPSEC_QM_POLICY_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_IPSEC_QM_POLICY_IN_USE) - CHK_ERR_WIN32A(ERROR_IPSEC_MM_POLICY_EXISTS) - CHK_ERR_WIN32A(ERROR_IPSEC_MM_POLICY_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_IPSEC_MM_POLICY_IN_USE) - CHK_ERR_WIN32A(ERROR_IPSEC_MM_FILTER_EXISTS) - CHK_ERR_WIN32A(ERROR_IPSEC_MM_FILTER_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_IPSEC_TRANSPORT_FILTER_EXISTS) - CHK_ERR_WIN32A(ERROR_IPSEC_TRANSPORT_FILTER_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_IPSEC_MM_AUTH_EXISTS) - CHK_ERR_WIN32A(ERROR_IPSEC_MM_AUTH_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_IPSEC_MM_AUTH_IN_USE) - CHK_ERR_WIN32A(ERROR_IPSEC_DEFAULT_MM_POLICY_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_IPSEC_DEFAULT_MM_AUTH_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_IPSEC_DEFAULT_QM_POLICY_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_IPSEC_TUNNEL_FILTER_EXISTS) - CHK_ERR_WIN32A(ERROR_IPSEC_TUNNEL_FILTER_NOT_FOUND) - CHK_ERR_WIN32A(ERROR_IPSEC_MM_FILTER_PENDING_DELETION) - CHK_ERR_WIN32A(ERROR_IPSEC_TRANSPORT_FILTER_PENDING_DELETION) - CHK_ERR_WIN32A(ERROR_IPSEC_TUNNEL_FILTER_PENDING_DELETION) - CHK_ERR_WIN32A(ERROR_IPSEC_MM_POLICY_PENDING_DELETION) - CHK_ERR_WIN32A(ERROR_IPSEC_MM_AUTH_PENDING_DELETION) - CHK_ERR_WIN32A(ERROR_IPSEC_QM_POLICY_PENDING_DELETION) -// CHK_ERR_WIN32A(WARNING_IPSEC_MM_POLICY_PRUNED) -// CHK_ERR_WIN32A(WARNING_IPSEC_QM_POLICY_PRUNED) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NEG_STATUS_BEGIN) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_AUTH_FAIL) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_ATTRIB_FAIL) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NEGOTIATION_PENDING) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_GENERAL_PROCESSING_ERROR) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_TIMED_OUT) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NO_CERT) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_SA_DELETED) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_SA_REAPED) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_MM_ACQUIRE_DROP) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_QM_ACQUIRE_DROP) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_QUEUE_DROP_MM) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_QUEUE_DROP_NO_MM) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_DROP_NO_RESPONSE) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_MM_DELAY_DROP) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_QM_DELAY_DROP) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_ERROR) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_CRL_FAILED) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_KEY_USAGE) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_CERT_TYPE) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NO_PRIVATE_KEY) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_DH_FAIL) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_HEADER) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NO_POLICY) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_SIGNATURE) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_KERBEROS_ERROR) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NO_PUBLIC_KEY) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_SA) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_PROP) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_TRANS) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_KE) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_ID) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_CERT) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_CERT_REQ) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_HASH) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_SIG) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_NONCE) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_NOTIFY) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_DELETE) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PROCESS_ERR_VENDOR) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_PAYLOAD) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_LOAD_SOFT_SA) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_SOFT_SA_TORN_DOWN) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_COOKIE) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NO_PEER_CERT) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_PEER_CRL_FAILED) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_POLICY_CHANGE) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NO_MM_POLICY) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NOTCBPRIV) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_SECLOADFAIL) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_FAILSSPINIT) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_FAILQUERYSSP) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_SRVACQFAIL) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_SRVQUERYCRED) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_GETSPIFAIL) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_FILTER) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_OUT_OF_MEMORY) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_ADD_UPDATE_KEY_FAILED) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_POLICY) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_UNKNOWN_DOI) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_SITUATION) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_DH_FAILURE) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_GROUP) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_ENCRYPT) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_DECRYPT) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_POLICY_MATCH) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_UNSUPPORTED_ID) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_HASH) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_HASH_ALG) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_HASH_SIZE) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_ENCRYPT_ALG) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_AUTH_ALG) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_SIG) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_LOAD_FAILED) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_RPC_DELETE) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_BENIGN_REINIT) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_RESPONDER_LIFETIME_NOTIFY) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_INVALID_CERT_KEYLEN) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_MM_LIMIT) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NEGOTIATION_DISABLED) - CHK_ERR_WIN32A(ERROR_IPSEC_IKE_NEG_STATUS_END) - -#if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) - -// ------------------------------------------------------------- -// ddraw.h error codes -// ------------------------------------------------------------- - CHK_ERRA(DDERR_ALREADYINITIALIZED) - CHK_ERRA(DDERR_CANNOTATTACHSURFACE) - CHK_ERRA(DDERR_CANNOTDETACHSURFACE) - CHK_ERRA(DDERR_CURRENTLYNOTAVAIL) - CHK_ERRA(DDERR_EXCEPTION) -// CHK_ERRA(DDERR_GENERIC) - CHK_ERRA(DDERR_HEIGHTALIGN) - CHK_ERRA(DDERR_INCOMPATIBLEPRIMARY) - CHK_ERRA(DDERR_INVALIDCAPS) - CHK_ERRA(DDERR_INVALIDCLIPLIST) - CHK_ERRA(DDERR_INVALIDMODE) - CHK_ERRA(DDERR_INVALIDOBJECT) -// CHK_ERRA(DDERR_INVALIDPARAMS) - CHK_ERRA(DDERR_INVALIDPIXELFORMAT) - CHK_ERRA(DDERR_INVALIDRECT) - CHK_ERRA(DDERR_LOCKEDSURFACES) - CHK_ERRA(DDERR_NO3D) - CHK_ERRA(DDERR_NOALPHAHW) - CHK_ERRA(DDERR_NOSTEREOHARDWARE) - CHK_ERRA(DDERR_NOSURFACELEFT) - CHK_ERRA(DDERR_NOCLIPLIST) - CHK_ERRA(DDERR_NOCOLORCONVHW) - CHK_ERRA(DDERR_NOCOOPERATIVELEVELSET) - CHK_ERRA(DDERR_NOCOLORKEY) - CHK_ERRA(DDERR_NOCOLORKEYHW) - CHK_ERRA(DDERR_NODIRECTDRAWSUPPORT) - CHK_ERRA(DDERR_NOEXCLUSIVEMODE) - CHK_ERRA(DDERR_NOFLIPHW) - CHK_ERRA(DDERR_NOGDI) - CHK_ERRA(DDERR_NOMIRRORHW) - CHK_ERRA(DDERR_NOTFOUND) - CHK_ERRA(DDERR_NOOVERLAYHW) - CHK_ERRA(DDERR_OVERLAPPINGRECTS) - CHK_ERRA(DDERR_NORASTEROPHW) - CHK_ERRA(DDERR_NOROTATIONHW) - CHK_ERRA(DDERR_NOSTRETCHHW) - CHK_ERRA(DDERR_NOT4BITCOLOR) - CHK_ERRA(DDERR_NOT4BITCOLORINDEX) - CHK_ERRA(DDERR_NOT8BITCOLOR) - CHK_ERRA(DDERR_NOTEXTUREHW) - CHK_ERRA(DDERR_NOVSYNCHW) - CHK_ERRA(DDERR_NOZBUFFERHW) - CHK_ERRA(DDERR_NOZOVERLAYHW) - CHK_ERRA(DDERR_OUTOFCAPS) -// CHK_ERRA(DDERR_OUTOFMEMORY) -// CHK_ERRA(DDERR_OUTOFVIDEOMEMORY) - CHK_ERRA(DDERR_OVERLAYCANTCLIP) - CHK_ERRA(DDERR_OVERLAYCOLORKEYONLYONEACTIVE) - CHK_ERRA(DDERR_PALETTEBUSY) - CHK_ERRA(DDERR_COLORKEYNOTSET) - CHK_ERRA(DDERR_SURFACEALREADYATTACHED) - CHK_ERRA(DDERR_SURFACEALREADYDEPENDENT) - CHK_ERRA(DDERR_SURFACEBUSY) - CHK_ERRA(DDERR_CANTLOCKSURFACE) - CHK_ERRA(DDERR_SURFACEISOBSCURED) - CHK_ERRA(DDERR_SURFACELOST) - CHK_ERRA(DDERR_SURFACENOTATTACHED) - CHK_ERRA(DDERR_TOOBIGHEIGHT) - CHK_ERRA(DDERR_TOOBIGSIZE) - CHK_ERRA(DDERR_TOOBIGWIDTH) -// CHK_ERRA(DDERR_UNSUPPORTED) - CHK_ERRA(DDERR_UNSUPPORTEDFORMAT) - CHK_ERRA(DDERR_UNSUPPORTEDMASK) - CHK_ERRA(DDERR_INVALIDSTREAM) - CHK_ERRA(DDERR_VERTICALBLANKINPROGRESS) - CHK_ERRA(DDERR_WASSTILLDRAWING) - CHK_ERRA(DDERR_DDSCAPSCOMPLEXREQUIRED) - CHK_ERRA(DDERR_XALIGN) - CHK_ERRA(DDERR_INVALIDDIRECTDRAWGUID) - CHK_ERRA(DDERR_DIRECTDRAWALREADYCREATED) - CHK_ERRA(DDERR_NODIRECTDRAWHW) - CHK_ERRA(DDERR_PRIMARYSURFACEALREADYEXISTS) - CHK_ERRA(DDERR_NOEMULATION) - CHK_ERRA(DDERR_REGIONTOOSMALL) - CHK_ERRA(DDERR_CLIPPERISUSINGHWND) - CHK_ERRA(DDERR_NOCLIPPERATTACHED) - CHK_ERRA(DDERR_NOHWND) - CHK_ERRA(DDERR_HWNDSUBCLASSED) - CHK_ERRA(DDERR_HWNDALREADYSET) - CHK_ERRA(DDERR_NOPALETTEATTACHED) - CHK_ERRA(DDERR_NOPALETTEHW) - CHK_ERRA(DDERR_BLTFASTCANTCLIP) - CHK_ERRA(DDERR_NOBLTHW) - CHK_ERRA(DDERR_NODDROPSHW) - CHK_ERRA(DDERR_OVERLAYNOTVISIBLE) - CHK_ERRA(DDERR_NOOVERLAYDEST) - CHK_ERRA(DDERR_INVALIDPOSITION) - CHK_ERRA(DDERR_NOTAOVERLAYSURFACE) - CHK_ERRA(DDERR_EXCLUSIVEMODEALREADYSET) - CHK_ERRA(DDERR_NOTFLIPPABLE) - CHK_ERRA(DDERR_CANTDUPLICATE) - CHK_ERRA(DDERR_NOTLOCKED) - CHK_ERRA(DDERR_CANTCREATEDC) - CHK_ERRA(DDERR_NODC) - CHK_ERRA(DDERR_WRONGMODE) - CHK_ERRA(DDERR_IMPLICITLYCREATED) - CHK_ERRA(DDERR_NOTPALETTIZED) - CHK_ERRA(DDERR_UNSUPPORTEDMODE) - CHK_ERRA(DDERR_NOMIPMAPHW) - CHK_ERRA(DDERR_INVALIDSURFACETYPE) - CHK_ERRA(DDERR_NOOPTIMIZEHW) - CHK_ERRA(DDERR_NOTLOADED) - CHK_ERRA(DDERR_NOFOCUSWINDOW) - CHK_ERRA(DDERR_NOTONMIPMAPSUBLEVEL) - CHK_ERRA(DDERR_DCALREADYCREATED) - CHK_ERRA(DDERR_NONONLOCALVIDMEM) - CHK_ERRA(DDERR_CANTPAGELOCK) - CHK_ERRA(DDERR_CANTPAGEUNLOCK) - CHK_ERRA(DDERR_NOTPAGELOCKED) - CHK_ERRA(DDERR_MOREDATA) - CHK_ERRA(DDERR_EXPIRED) - CHK_ERRA(DDERR_TESTFINISHED) - CHK_ERRA(DDERR_NEWMODE) - CHK_ERRA(DDERR_D3DNOTINITIALIZED) - CHK_ERRA(DDERR_VIDEONOTACTIVE) - CHK_ERRA(DDERR_NOMONITORINFORMATION) - CHK_ERRA(DDERR_NODRIVERSUPPORT) - CHK_ERRA(DDERR_DEVICEDOESNTOWNSURFACE) - -// ------------------------------------------------------------- -// dinput.h error codes -// ------------------------------------------------------------- -// CHK_ERRA(DI_OK) -// CHK_ERRA(DI_NOTATTACHED) -// CHK_ERRA(DI_BUFFEROVERFLOW) -// CHK_ERRA(DI_PROPNOEFFECT) -// CHK_ERRA(DI_NOEFFECT) -// CHK_ERRA(DI_POLLEDDEVICE) -// CHK_ERRA(DI_DOWNLOADSKIPPED) -// CHK_ERRA(DI_EFFECTRESTARTED) -// CHK_ERRA(DI_SETTINGSNOTSAVED_ACCESSDENIED) -// CHK_ERRA(DI_SETTINGSNOTSAVED_DISKFULL) -// CHK_ERRA(DI_TRUNCATED) -// CHK_ERRA(DI_TRUNCATEDANDRESTARTED) -// CHK_ERRA(DI_WRITEPROTECT) - CHK_ERR(DIERR_INSUFFICIENTPRIVS, "DIERR_INSUFFICIENTPRIVS & VFW_E_INVALIDMEDIATYPE") - CHK_ERR(DIERR_DEVICEFULL, "DIERR_DEVICEFULL & VFW_E_INVALIDSUBTYPE & DMO_E_INVALIDSTREAMINDEX") - CHK_ERR(DIERR_MOREDATA, "DIERR_MOREDATA & VFW_E_NEED_OWNER & DMO_E_INVALIDTYPE") - CHK_ERR(DIERR_NOTDOWNLOADED, "DIERR_NOTDOWNLOADED & VFW_E_ENUM_OUT_OF_SYNC & DMO_E_TYPE_NOT_SET") - CHK_ERR(DIERR_HASEFFECTS, "DIERR_HASEFFECTS & VFW_E_ALREADY_CONNECTED & DMO_E_NOTACCEPTING") - CHK_ERR(DIERR_NOTEXCLUSIVEACQUIRED, "DIERR_NOTEXCLUSIVEACQUIRED & VFW_E_FILTER_ACTIVE & DMO_E_TYPE_NOT_ACCEPTED") - CHK_ERR(DIERR_INCOMPLETEEFFECT, "DIERR_INCOMPLETEEFFECT & VFW_E_NO_TYPES & DMO_E_NO_MORE_ITEMS") - CHK_ERR(DIERR_NOTBUFFERED, "DIERR_NOTBUFFERED & VFW_E_NO_ACCEPTABLE_TYPES") - CHK_ERR(DIERR_EFFECTPLAYING, "DIERR_EFFECTPLAYING & VFW_E_INVALID_DIRECTION") - CHK_ERR(DIERR_UNPLUGGED, "DIERR_UNPLUGGED & VFW_E_NOT_CONNECTED") - CHK_ERR(DIERR_REPORTFULL, "DIERR_REPORTFULL & VFW_E_NO_ALLOCATOR") - CHK_ERR(DIERR_MAPFILEFAIL, "DIERR_MAPFILEFAIL & VFW_E_RUNTIME_ERROR") -// CHK_ERRA(DIERR_OLDDIRECTINPUTVERSION) -// CHK_ERRA(DIERR_GENERIC) -// CHK_ERRA(DIERR_OLDDIRECTINPUTVERSION) -// CHK_ERRA(DIERR_BETADIRECTINPUTVERSION) -// CHK_ERRA(DIERR_BADDRIVERVER) -// CHK_ERRA(DIERR_DEVICENOTREG) -// CHK_ERRA(DIERR_NOTFOUND) -// CHK_ERRA(DIERR_OBJECTNOTFOUND) -// CHK_ERRA(DIERR_INVALIDPARAM) -// CHK_ERRA(DIERR_NOINTERFACE) -// CHK_ERRA(DIERR_GENERIC) -// CHK_ERRA(DIERR_OUTOFMEMORY) -// CHK_ERRA(DIERR_UNSUPPORTED) -// CHK_ERRA(DIERR_NOTINITIALIZED) -// CHK_ERRA(DIERR_ALREADYINITIALIZED) -// CHK_ERRA(DIERR_NOAGGREGATION) -// CHK_ERRA(DIERR_OTHERAPPHASPRIO) -// CHK_ERRA(DIERR_INPUTLOST) -// CHK_ERRA(DIERR_ACQUIRED) -// CHK_ERRA(DIERR_NOTACQUIRED) -// CHK_ERRA(DIERR_READONLY) -// CHK_ERRA(DIERR_HANDLEEXISTS) - - -// ------------------------------------------------------------- -// dinputd.h error -// ------------------------------------------------------------- -// CHK_ERRA(DIERR_NOMOREITEMS) - CHK_ERRA(DIERR_DRIVERFIRST) - CHK_ERR(DIERR_DRIVERFIRST+1, "DIERR_DRIVERFIRST+1") - CHK_ERR(DIERR_DRIVERFIRST+2, "DIERR_DRIVERFIRST+2") - CHK_ERR(DIERR_DRIVERFIRST+3, "DIERR_DRIVERFIRST+3") - CHK_ERR(DIERR_DRIVERFIRST+4, "DIERR_DRIVERFIRST+4") - CHK_ERR(DIERR_DRIVERFIRST+5, "DIERR_DRIVERFIRST+5") - CHK_ERRA(DIERR_DRIVERLAST) - CHK_ERR(DIERR_INVALIDCLASSINSTALLER, "DIERR_INVALIDCLASSINSTALLER") - CHK_ERR(DIERR_CANCELLED, "DIERR_CANCELLED & MS_E_SAMPLEALLOC") - CHK_ERRA(DIERR_BADINF) - -// ------------------------------------------------------------- -// d3d9.h error codes -// ------------------------------------------------------------- -// CHK_ERRA(D3D_OK) - CHK_ERRA(D3DERR_WRONGTEXTUREFORMAT) - CHK_ERRA(D3DERR_UNSUPPORTEDCOLOROPERATION) - CHK_ERRA(D3DERR_UNSUPPORTEDCOLORARG) - CHK_ERRA(D3DERR_UNSUPPORTEDALPHAOPERATION) - CHK_ERRA(D3DERR_UNSUPPORTEDALPHAARG) - CHK_ERRA(D3DERR_TOOMANYOPERATIONS) - CHK_ERRA(D3DERR_CONFLICTINGTEXTUREFILTER) - CHK_ERRA(D3DERR_UNSUPPORTEDFACTORVALUE) - CHK_ERRA(D3DERR_CONFLICTINGRENDERSTATE) - CHK_ERRA(D3DERR_UNSUPPORTEDTEXTUREFILTER) - CHK_ERRA(D3DERR_CONFLICTINGTEXTUREPALETTE) - CHK_ERRA(D3DERR_DRIVERINTERNALERROR) - CHK_ERRA(D3DERR_NOTFOUND) - CHK_ERRA(D3DERR_MOREDATA) - CHK_ERRA(D3DERR_DEVICELOST) - CHK_ERRA(D3DERR_DEVICENOTRESET) - CHK_ERRA(D3DERR_NOTAVAILABLE) - CHK_ERRA(D3DERR_OUTOFVIDEOMEMORY) - CHK_ERRA(D3DERR_INVALIDDEVICE) - CHK_ERRA(D3DERR_INVALIDCALL) - CHK_ERRA(D3DERR_DRIVERINVALIDCALL) - //CHK_ERRA(D3DERR_WASSTILLDRAWING) - CHK_ERRA(D3DOK_NOAUTOGEN) - - // Extended for Windows Vista - CHK_ERRA(D3DERR_DEVICEREMOVED) - CHK_ERRA(S_NOT_RESIDENT) - CHK_ERRA(S_RESIDENT_IN_SHARED_MEMORY) - CHK_ERRA(S_PRESENT_MODE_CHANGED) - CHK_ERRA(S_PRESENT_OCCLUDED) - CHK_ERRA(D3DERR_DEVICEHUNG) - - // Extended for Windows 7 - CHK_ERRA(D3DERR_UNSUPPORTEDOVERLAY) - CHK_ERRA(D3DERR_UNSUPPORTEDOVERLAYFORMAT) - CHK_ERRA(D3DERR_CANNOTPROTECTCONTENT) - CHK_ERRA(D3DERR_UNSUPPORTEDCRYPTO) - CHK_ERRA(D3DERR_PRESENT_STATISTICS_DISJOINT) - -// ------------------------------------------------------------- -// dsound.h error codes -// ------------------------------------------------------------- -// CHK_ERRA(DS_OK) - CHK_ERRA(DS_NO_VIRTUALIZATION) - CHK_ERRA(DSERR_ALLOCATED) - CHK_ERRA(DSERR_CONTROLUNAVAIL) -// CHK_ERRA(DSERR_INVALIDPARAM) - CHK_ERRA(DSERR_INVALIDCALL) -// CHK_ERRA(DSERR_GENERIC) - CHK_ERRA(DSERR_PRIOLEVELNEEDED) -// CHK_ERRA(DSERR_OUTOFMEMORY) - CHK_ERRA(DSERR_BADFORMAT) -// CHK_ERRA(DSERR_UNSUPPORTED) - CHK_ERRA(DSERR_NODRIVER) - CHK_ERRA(DSERR_ALREADYINITIALIZED) -// CHK_ERRA(DSERR_NOAGGREGATION) - CHK_ERRA(DSERR_BUFFERLOST) - CHK_ERRA(DSERR_OTHERAPPHASPRIO) - CHK_ERRA(DSERR_UNINITIALIZED) -// CHK_ERRA(DSERR_NOINTERFACE) -// CHK_ERRA(DSERR_ACCESSDENIED) - CHK_ERRA(DSERR_BUFFERTOOSMALL) - CHK_ERRA(DSERR_DS8_REQUIRED) - CHK_ERRA(DSERR_SENDLOOP) - CHK_ERRA(DSERR_BADSENDBUFFERGUID) - CHK_ERRA(DSERR_OBJECTNOTFOUND) - - CHK_ERRA(DSERR_FXUNAVAILABLE) - -#endif // !WINAPI_FAMILY || WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP - -// ------------------------------------------------------------- -// d3d10.h error codes -// ------------------------------------------------------------- - CHK_ERRA(D3D10_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS) - CHK_ERRA(D3D10_ERROR_FILE_NOT_FOUND) - -// ------------------------------------------------------------- -// dxgi.h error codes -// ------------------------------------------------------------- - CHK_ERRA(DXGI_STATUS_OCCLUDED) - CHK_ERRA(DXGI_STATUS_CLIPPED) - CHK_ERRA(DXGI_STATUS_NO_REDIRECTION) - CHK_ERRA(DXGI_STATUS_NO_DESKTOP_ACCESS) - CHK_ERRA(DXGI_STATUS_GRAPHICS_VIDPN_SOURCE_IN_USE) - CHK_ERRA(DXGI_STATUS_MODE_CHANGED) - CHK_ERRA(DXGI_STATUS_MODE_CHANGE_IN_PROGRESS) - CHK_ERRA(DXGI_ERROR_INVALID_CALL) - CHK_ERRA(DXGI_ERROR_NOT_FOUND) - CHK_ERRA(DXGI_ERROR_MORE_DATA) - CHK_ERRA(DXGI_ERROR_UNSUPPORTED) - CHK_ERRA(DXGI_ERROR_DEVICE_REMOVED) - CHK_ERRA(DXGI_ERROR_DEVICE_HUNG) - CHK_ERRA(DXGI_ERROR_DEVICE_RESET) - CHK_ERRA(DXGI_ERROR_WAS_STILL_DRAWING) - CHK_ERRA(DXGI_ERROR_FRAME_STATISTICS_DISJOINT) - CHK_ERRA(DXGI_ERROR_GRAPHICS_VIDPN_SOURCE_IN_USE) - CHK_ERRA(DXGI_ERROR_DRIVER_INTERNAL_ERROR) - CHK_ERRA(DXGI_ERROR_NONEXCLUSIVE) - CHK_ERRA(DXGI_ERROR_NOT_CURRENTLY_AVAILABLE) - CHK_ERRA(DXGI_ERROR_REMOTE_CLIENT_DISCONNECTED) - CHK_ERRA(DXGI_ERROR_REMOTE_OUTOFMEMORY) - -// ------------------------------------------------------------- -// d3d11.h error codes -// ------------------------------------------------------------- - CHK_ERRA(D3D11_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS) - CHK_ERRA(D3D11_ERROR_FILE_NOT_FOUND) - CHK_ERRA(D3D11_ERROR_TOO_MANY_UNIQUE_VIEW_OBJECTS) - CHK_ERRA(D3D11_ERROR_DEFERRED_CONTEXT_MAP_WITHOUT_INITIAL_DISCARD) - -#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP - -// ------------------------------------------------------------- -// Direct2D error codes -// ------------------------------------------------------------- -// CHK_ERRA(D2DERR_UNSUPPORTED_PIXEL_FORMAT) -// CHK_ERRA(D2DERR_INSUFFICIENT_BUFFER) - CHK_ERRA(D2DERR_WRONG_STATE) - CHK_ERRA(D2DERR_NOT_INITIALIZED) - CHK_ERRA(D2DERR_UNSUPPORTED_OPERATION) - CHK_ERRA(D2DERR_SCANNER_FAILED) - CHK_ERRA(D2DERR_SCREEN_ACCESS_DENIED) - CHK_ERRA(D2DERR_DISPLAY_STATE_INVALID) - CHK_ERRA(D2DERR_ZERO_VECTOR) - CHK_ERRA(D2DERR_INTERNAL_ERROR) - CHK_ERRA(D2DERR_DISPLAY_FORMAT_NOT_SUPPORTED) - CHK_ERRA(D2DERR_INVALID_CALL) - CHK_ERRA(D2DERR_NO_HARDWARE_DEVICE) - CHK_ERRA(D2DERR_RECREATE_TARGET) - CHK_ERRA(D2DERR_TOO_MANY_SHADER_ELEMENTS) - CHK_ERRA(D2DERR_SHADER_COMPILE_FAILED) - CHK_ERRA(D2DERR_MAX_TEXTURE_SIZE_EXCEEDED) - CHK_ERRA(D2DERR_UNSUPPORTED_VERSION) - CHK_ERRA(D2DERR_BAD_NUMBER) - CHK_ERRA(D2DERR_WRONG_FACTORY) - CHK_ERRA(D2DERR_LAYER_ALREADY_IN_USE) - CHK_ERRA(D2DERR_POP_CALL_DID_NOT_MATCH_PUSH) -// CHK_ERRA(D2DERR_WRONG_RESOURCE_DOMAIN) - CHK_ERRA(D2DERR_PUSH_POP_UNBALANCED) - CHK_ERRA(D2DERR_RENDER_TARGET_HAS_LAYER_OR_CLIPRECT) - CHK_ERRA(D2DERR_INCOMPATIBLE_BRUSH_TYPES) - CHK_ERRA(D2DERR_WIN32_ERROR) - CHK_ERRA(D2DERR_TARGET_NOT_GDI_COMPATIBLE) - CHK_ERRA(D2DERR_TEXT_EFFECT_IS_WRONG_TYPE) - CHK_ERRA(D2DERR_TEXT_RENDERER_NOT_RELEASED) -// CHK_ERRA(D2DERR_EXCEEDS_MAX_BITMAP_SIZE) - -// ------------------------------------------------------------- -// DirectWrite error codes -// ------------------------------------------------------------- - CHK_ERRA(DWRITE_E_FILEFORMAT) - CHK_ERRA(DWRITE_E_UNEXPECTED) - CHK_ERRA(DWRITE_E_NOFONT) - CHK_ERRA(DWRITE_E_FILENOTFOUND) - CHK_ERRA(DWRITE_E_FILEACCESS) - CHK_ERRA(DWRITE_E_FONTCOLLECTIONOBSOLETE) - CHK_ERRA(DWRITE_E_ALREADYREGISTERED) - -// ------------------------------------------------------------- -// WIC error codes -// ------------------------------------------------------------- - CHK_ERRA(WINCODEC_ERR_WRONGSTATE) - CHK_ERRA(WINCODEC_ERR_VALUEOUTOFRANGE) - CHK_ERRA(WINCODEC_ERR_UNKNOWNIMAGEFORMAT) - CHK_ERRA(WINCODEC_ERR_UNSUPPORTEDVERSION) - CHK_ERRA(WINCODEC_ERR_NOTINITIALIZED) - CHK_ERRA(WINCODEC_ERR_ALREADYLOCKED) - CHK_ERRA(WINCODEC_ERR_PROPERTYNOTFOUND) - CHK_ERRA(WINCODEC_ERR_PROPERTYNOTSUPPORTED) - CHK_ERRA(WINCODEC_ERR_PROPERTYSIZE) - CHK_ERRA(WINCODEC_ERR_CODECPRESENT) - CHK_ERRA(WINCODEC_ERR_CODECNOTHUMBNAIL) - CHK_ERRA(WINCODEC_ERR_PALETTEUNAVAILABLE) - CHK_ERRA(WINCODEC_ERR_CODECTOOMANYSCANLINES) - CHK_ERRA(WINCODEC_ERR_INTERNALERROR) - CHK_ERRA(WINCODEC_ERR_SOURCERECTDOESNOTMATCHDIMENSIONS) - CHK_ERRA(WINCODEC_ERR_COMPONENTNOTFOUND) - CHK_ERRA(WINCODEC_ERR_IMAGESIZEOUTOFRANGE) - CHK_ERRA(WINCODEC_ERR_TOOMUCHMETADATA) - CHK_ERRA(WINCODEC_ERR_BADIMAGE) - CHK_ERRA(WINCODEC_ERR_BADHEADER) - CHK_ERRA(WINCODEC_ERR_FRAMEMISSING) - CHK_ERRA(WINCODEC_ERR_BADMETADATAHEADER) - CHK_ERRA(WINCODEC_ERR_BADSTREAMDATA) - CHK_ERRA(WINCODEC_ERR_STREAMWRITE) - CHK_ERRA(WINCODEC_ERR_STREAMREAD) - CHK_ERRA(WINCODEC_ERR_STREAMNOTAVAILABLE) - CHK_ERRA(WINCODEC_ERR_UNSUPPORTEDPIXELFORMAT) - CHK_ERRA(WINCODEC_ERR_UNSUPPORTEDOPERATION) - CHK_ERRA(WINCODEC_ERR_INVALIDREGISTRATION) - CHK_ERRA(WINCODEC_ERR_COMPONENTINITIALIZEFAILURE) - CHK_ERRA(WINCODEC_ERR_INSUFFICIENTBUFFER) - CHK_ERRA(WINCODEC_ERR_DUPLICATEMETADATAPRESENT) - CHK_ERRA(WINCODEC_ERR_PROPERTYUNEXPECTEDTYPE) - CHK_ERRA(WINCODEC_ERR_UNEXPECTEDSIZE) - CHK_ERRA(WINCODEC_ERR_INVALIDQUERYREQUEST) - CHK_ERRA(WINCODEC_ERR_UNEXPECTEDMETADATATYPE) - CHK_ERRA(WINCODEC_ERR_REQUESTONLYVALIDATMETADATAROOT) - CHK_ERRA(WINCODEC_ERR_INVALIDQUERYCHARACTER) - CHK_ERRA(WINCODEC_ERR_WIN32ERROR) - CHK_ERRA(WINCODEC_ERR_INVALIDPROGRESSIVELEVEL) - -#endif // !WINAPI_FAMILY || WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP - -// ------------------------------------------------------------- -// DXUT error codes -// ------------------------------------------------------------- - CHK_ERRA(DXUTERR_NODIRECT3D) - CHK_ERRA(DXUTERR_NOCOMPATIBLEDEVICES) - CHK_ERRA(DXUTERR_MEDIANOTFOUND) - CHK_ERRA(DXUTERR_NONZEROREFCOUNT) - CHK_ERRA(DXUTERR_CREATINGDEVICE) - CHK_ERRA(DXUTERR_RESETTINGDEVICE) - CHK_ERRA(DXUTERR_CREATINGDEVICEOBJECTS) - CHK_ERRA(DXUTERR_RESETTINGDEVICEOBJECTS) - CHK_ERRA(DXUTERR_INCORRECTVERSION) - CHK_ERRA(DXUTERR_DEVICEREMOVED) - -// ------------------------------------------------------------- -// xaudio2.h error codes -// ------------------------------------------------------------- - CHK_ERRA(XAUDIO2_E_INVALID_CALL) - CHK_ERRA(XAUDIO2_E_XMA_DECODER_ERROR) - CHK_ERRA(XAUDIO2_E_XAPO_CREATION_FAILED) - CHK_ERRA(XAUDIO2_E_DEVICE_INVALIDATED) - -// ------------------------------------------------------------- -// xapo.h error codes -// ------------------------------------------------------------- - CHK_ERRA(XAPO_E_FORMAT_UNSUPPORTED) - - default: return L"Unknown error."; - } -} - -//-------------------------------------------------------------------------------------- -#undef CHK_ERR -#undef CHK_ERRA -#undef HRESULT_FROM_WIN32b -#undef CHK_ERR_WIN32A -#undef CHK_ERR_WIN32_ONLY - -#define CHK_ERRA(hrchk) \ - case hrchk: \ - wcscpy_s( desc, count, L#hrchk ); break; - -#define CHK_ERR(hrchk, strOut) \ - case hrchk: \ - wcscpy_s( desc, count, L##strOut ); break; - - -//-------------------------------------------------------------------------------------- -void WINAPI DXGetErrorDescriptionW( _In_ HRESULT hr, _Out_cap_(count) WCHAR* desc, _In_ size_t count ) -{ - if ( !count ) - return; - - *desc = 0; - - // First try to see if FormatMessage knows this hr - UINT icount = static_cast( std::min( count, 32767 ) ); - - DWORD result = FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM, nullptr, hr, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), desc, icount, nullptr ); - - if (result > 0) - return; - - switch (hr) - { -// Commmented out codes are actually alises for other codes - -#if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) - -// ------------------------------------------------------------- -// ddraw.h error codes -// ------------------------------------------------------------- - CHK_ERR(DDERR_ALREADYINITIALIZED, "This object is already initialized") - CHK_ERR(DDERR_CANNOTATTACHSURFACE, "This surface can not be attached to the requested surface.") - CHK_ERR(DDERR_CANNOTDETACHSURFACE, "This surface can not be detached from the requested surface.") - CHK_ERR(DDERR_CURRENTLYNOTAVAIL, "Support is currently not available.") - CHK_ERR(DDERR_EXCEPTION, "An exception was encountered while performing the requested operation") -// CHK_ERR(DDERR_GENERIC, "DDERR_GENERIC") - CHK_ERR(DDERR_HEIGHTALIGN, "Height of rectangle provided is not a multiple of reqd alignment") - CHK_ERR(DDERR_INCOMPATIBLEPRIMARY, "Unable to match primary surface creation request with existing primary surface.") - CHK_ERR(DDERR_INVALIDCAPS, "One or more of the caps bits passed to the callback are incorrect.") - CHK_ERR(DDERR_INVALIDCLIPLIST, "DirectDraw does not support provided Cliplist.") - CHK_ERR(DDERR_INVALIDMODE, "DirectDraw does not support the requested mode") - CHK_ERR(DDERR_INVALIDOBJECT, "DirectDraw received a pointer that was an invalid DIRECTDRAW object.") -// CHK_ERR(DDERR_INVALIDPARAMS, "DDERR_INVALIDPARAMS") - CHK_ERR(DDERR_INVALIDPIXELFORMAT, "pixel format was invalid as specified") - CHK_ERR(DDERR_INVALIDRECT, "Rectangle provided was invalid.") - CHK_ERR(DDERR_LOCKEDSURFACES, "Operation could not be carried out because one or more surfaces are locked") - CHK_ERR(DDERR_NO3D, "There is no 3D present.") - CHK_ERR(DDERR_NOALPHAHW, "Operation could not be carried out because there is no alpha accleration hardware present or available.") - CHK_ERR(DDERR_NOSTEREOHARDWARE, "Operation could not be carried out because there is no stereo hardware present or available.") - CHK_ERR(DDERR_NOSURFACELEFT, "Operation could not be carried out because there is no hardware present which supports stereo surfaces") - CHK_ERR(DDERR_NOCLIPLIST, "no clip list available") - CHK_ERR(DDERR_NOCOLORCONVHW, "Operation could not be carried out because there is no color conversion hardware present or available.") - CHK_ERR(DDERR_NOCOOPERATIVELEVELSET, "Create function called without DirectDraw object method SetCooperativeLevel being called.") - CHK_ERR(DDERR_NOCOLORKEY, "Surface doesn't currently have a color key") - CHK_ERR(DDERR_NOCOLORKEYHW, "Operation could not be carried out because there is no hardware support of the dest color key.") - CHK_ERR(DDERR_NODIRECTDRAWSUPPORT, "No DirectDraw support possible with current display driver") - CHK_ERR(DDERR_NOEXCLUSIVEMODE, "Operation requires the application to have exclusive mode but the application does not have exclusive mode.") - CHK_ERR(DDERR_NOFLIPHW, "Flipping visible surfaces is not supported.") - CHK_ERR(DDERR_NOGDI, "There is no GDI present.") - CHK_ERR(DDERR_NOMIRRORHW, "Operation could not be carried out because there is no hardware present or available.") - CHK_ERR(DDERR_NOTFOUND, "Requested item was not found") - CHK_ERR(DDERR_NOOVERLAYHW, "Operation could not be carried out because there is no overlay hardware present or available.") - CHK_ERR(DDERR_OVERLAPPINGRECTS, "Operation could not be carried out because the source and destination rectangles are on the same surface and overlap each other.") - CHK_ERR(DDERR_NORASTEROPHW, "Operation could not be carried out because there is no appropriate raster op hardware present or available.") - CHK_ERR(DDERR_NOROTATIONHW, "Operation could not be carried out because there is no rotation hardware present or available.") - CHK_ERR(DDERR_NOSTRETCHHW, "Operation could not be carried out because there is no hardware support for stretching") - CHK_ERR(DDERR_NOT4BITCOLOR, "DirectDrawSurface is not in 4 bit color palette and the requested operation requires 4 bit color palette.") - CHK_ERR(DDERR_NOT4BITCOLORINDEX, "DirectDrawSurface is not in 4 bit color index palette and the requested operation requires 4 bit color index palette.") - CHK_ERR(DDERR_NOT8BITCOLOR, "DirectDraw Surface is not in 8 bit color mode and the requested operation requires 8 bit color.") - CHK_ERR(DDERR_NOTEXTUREHW, "Operation could not be carried out because there is no texture mapping hardware present or available.") - CHK_ERR(DDERR_NOVSYNCHW, "Operation could not be carried out because there is no hardware support for vertical blank synchronized operations.") - CHK_ERR(DDERR_NOZBUFFERHW, "Operation could not be carried out because there is no hardware support for zbuffer blting.") - CHK_ERR(DDERR_NOZOVERLAYHW, "Overlay surfaces could not be z layered based on their BltOrder because the hardware does not support z layering of overlays.") - CHK_ERR(DDERR_OUTOFCAPS, "The hardware needed for the requested operation has already been allocated.") -// CHK_ERR(DDERR_OUTOFMEMORY, "DDERR_OUTOFMEMORY") -// CHK_ERR(DDERR_OUTOFVIDEOMEMORY, "DDERR_OUTOFVIDEOMEMORY") - CHK_ERR(DDERR_OVERLAYCANTCLIP, "hardware does not support clipped overlays") - CHK_ERR(DDERR_OVERLAYCOLORKEYONLYONEACTIVE, "Can only have ony color key active at one time for overlays") - CHK_ERR(DDERR_PALETTEBUSY, "Access to this palette is being refused because the palette is already locked by another thread.") - CHK_ERR(DDERR_COLORKEYNOTSET, "No src color key specified for this operation.") - CHK_ERR(DDERR_SURFACEALREADYATTACHED, "This surface is already attached to the surface it is being attached to.") - CHK_ERR(DDERR_SURFACEALREADYDEPENDENT, "This surface is already a dependency of the surface it is being made a dependency of.") - CHK_ERR(DDERR_SURFACEBUSY, "Access to this surface is being refused because the surface is already locked by another thread.") - CHK_ERR(DDERR_CANTLOCKSURFACE, "Access to this surface is being refused because no driver exists which can supply a pointer to the surface. This is most likely to happen when attempting to lock the primary surface when no DCI provider is present. Will also happen on attempts to lock an optimized surface.") - CHK_ERR(DDERR_SURFACEISOBSCURED, "Access to Surface refused because Surface is obscured.") - CHK_ERR(DDERR_SURFACELOST, "Access to this surface is being refused because the surface is gone. The DIRECTDRAWSURFACE object representing this surface should have Restore called on it.") - CHK_ERR(DDERR_SURFACENOTATTACHED, "The requested surface is not attached.") - CHK_ERR(DDERR_TOOBIGHEIGHT, "Height requested by DirectDraw is too large.") - CHK_ERR(DDERR_TOOBIGSIZE, "Size requested by DirectDraw is too large -- The individual height and width are OK.") - CHK_ERR(DDERR_TOOBIGWIDTH, "Width requested by DirectDraw is too large.") -// CHK_ERR(DDERR_UNSUPPORTED, "DDERR_UNSUPPORTED") - CHK_ERR(DDERR_UNSUPPORTEDFORMAT, "Pixel format requested is unsupported by DirectDraw") - CHK_ERR(DDERR_UNSUPPORTEDMASK, "Bitmask in the pixel format requested is unsupported by DirectDraw") - CHK_ERR(DDERR_INVALIDSTREAM, "The specified stream contains invalid data") - CHK_ERR(DDERR_VERTICALBLANKINPROGRESS, "vertical blank is in progress") - CHK_ERR(DDERR_WASSTILLDRAWING, "Was still drawing") - CHK_ERR(DDERR_DDSCAPSCOMPLEXREQUIRED, "The specified surface type requires specification of the COMPLEX flag") - CHK_ERR(DDERR_XALIGN, "Rectangle provided was not horizontally aligned on reqd. boundary") - CHK_ERR(DDERR_INVALIDDIRECTDRAWGUID, "The GUID passed to DirectDrawCreate is not a valid DirectDraw driver identifier.") - CHK_ERR(DDERR_DIRECTDRAWALREADYCREATED, "A DirectDraw object representing this driver has already been created for this process.") - CHK_ERR(DDERR_NODIRECTDRAWHW, "A hardware only DirectDraw object creation was attempted but the driver did not support any hardware.") - CHK_ERR(DDERR_PRIMARYSURFACEALREADYEXISTS, "this process already has created a primary surface") - CHK_ERR(DDERR_NOEMULATION, "software emulation not available.") - CHK_ERR(DDERR_REGIONTOOSMALL, "region passed to Clipper::GetClipList is too small.") - CHK_ERR(DDERR_CLIPPERISUSINGHWND, "an attempt was made to set a clip list for a clipper objec that is already monitoring an hwnd.") - CHK_ERR(DDERR_NOCLIPPERATTACHED, "No clipper object attached to surface object") - CHK_ERR(DDERR_NOHWND, "Clipper notification requires an HWND or no HWND has previously been set as the CooperativeLevel HWND.") - CHK_ERR(DDERR_HWNDSUBCLASSED, "HWND used by DirectDraw CooperativeLevel has been subclassed, this prevents DirectDraw from restoring state.") - CHK_ERR(DDERR_HWNDALREADYSET, "The CooperativeLevel HWND has already been set. It can not be reset while the process has surfaces or palettes created.") - CHK_ERR(DDERR_NOPALETTEATTACHED, "No palette object attached to this surface.") - CHK_ERR(DDERR_NOPALETTEHW, "No hardware support for 16 or 256 color palettes.") - CHK_ERR(DDERR_BLTFASTCANTCLIP, "If a clipper object is attached to the source surface passed into a BltFast call.") - CHK_ERR(DDERR_NOBLTHW, "No blter.") - CHK_ERR(DDERR_NODDROPSHW, "No DirectDraw ROP hardware.") - CHK_ERR(DDERR_OVERLAYNOTVISIBLE, "returned when GetOverlayPosition is called on a hidden overlay") - CHK_ERR(DDERR_NOOVERLAYDEST, "returned when GetOverlayPosition is called on a overlay that UpdateOverlay has never been called on to establish a destionation.") - CHK_ERR(DDERR_INVALIDPOSITION, "returned when the position of the overlay on the destionation is no longer legal for that destionation.") - CHK_ERR(DDERR_NOTAOVERLAYSURFACE, "returned when an overlay member is called for a non-overlay surface") - CHK_ERR(DDERR_EXCLUSIVEMODEALREADYSET, "An attempt was made to set the cooperative level when it was already set to exclusive.") - CHK_ERR(DDERR_NOTFLIPPABLE, "An attempt has been made to flip a surface that is not flippable.") - CHK_ERR(DDERR_CANTDUPLICATE, "Can't duplicate primary & 3D surfaces, or surfaces that are implicitly created.") - CHK_ERR(DDERR_NOTLOCKED, "Surface was not locked. An attempt to unlock a surface that was not locked at all, or by this process, has been attempted.") - CHK_ERR(DDERR_CANTCREATEDC, "Windows can not create any more DCs, or a DC was requested for a paltte-indexed surface when the surface had no palette AND the display mode was not palette-indexed (in this case DirectDraw cannot select a proper palette into the DC)") - CHK_ERR(DDERR_NODC, "No DC was ever created for this surface.") - CHK_ERR(DDERR_WRONGMODE, "This surface can not be restored because it was created in a different mode.") - CHK_ERR(DDERR_IMPLICITLYCREATED, "This surface can not be restored because it is an implicitly created surface.") - CHK_ERR(DDERR_NOTPALETTIZED, "The surface being used is not a palette-based surface") - CHK_ERR(DDERR_UNSUPPORTEDMODE, "The display is currently in an unsupported mode") - CHK_ERR(DDERR_NOMIPMAPHW, "Operation could not be carried out because there is no mip-map texture mapping hardware present or available.") - CHK_ERR(DDERR_INVALIDSURFACETYPE, "The requested action could not be performed because the surface was of the wrong type.") - CHK_ERR(DDERR_NOOPTIMIZEHW, "Device does not support optimized surfaces, therefore no video memory optimized surfaces") - CHK_ERR(DDERR_NOTLOADED, "Surface is an optimized surface, but has not yet been allocated any memory") - CHK_ERR(DDERR_NOFOCUSWINDOW, "Attempt was made to create or set a device window without first setting the focus window") - CHK_ERR(DDERR_NOTONMIPMAPSUBLEVEL, "Attempt was made to set a palette on a mipmap sublevel") - CHK_ERR(DDERR_DCALREADYCREATED, "A DC has already been returned for this surface. Only one DC can be retrieved per surface.") - CHK_ERR(DDERR_NONONLOCALVIDMEM, "An attempt was made to allocate non-local video memory from a device that does not support non-local video memory.") - CHK_ERR(DDERR_CANTPAGELOCK, "The attempt to page lock a surface failed.") - CHK_ERR(DDERR_CANTPAGEUNLOCK, "The attempt to page unlock a surface failed.") - CHK_ERR(DDERR_NOTPAGELOCKED, "An attempt was made to page unlock a surface with no outstanding page locks.") - CHK_ERR(DDERR_MOREDATA, "There is more data available than the specified buffer size could hold") - CHK_ERR(DDERR_EXPIRED, "The data has expired and is therefore no longer valid.") - CHK_ERR(DDERR_TESTFINISHED, "The mode test has finished executing.") - CHK_ERR(DDERR_NEWMODE, "The mode test has switched to a new mode.") - CHK_ERR(DDERR_D3DNOTINITIALIZED, "D3D has not yet been initialized.") - CHK_ERR(DDERR_VIDEONOTACTIVE, "The video port is not active") - CHK_ERR(DDERR_NOMONITORINFORMATION, "The monitor does not have EDID data.") - CHK_ERR(DDERR_NODRIVERSUPPORT, "The driver does not enumerate display mode refresh rates.") - CHK_ERR(DDERR_DEVICEDOESNTOWNSURFACE, "Surfaces created by one direct draw device cannot be used directly by another direct draw device.") - - -// ------------------------------------------------------------- -// dinput.h error codes -// ------------------------------------------------------------- -// CHK_ERR(DI_OK, "DI_OK") -// CHK_ERR(DI_NOTATTACHED, "DI_NOTATTACHED") -// CHK_ERR(DI_BUFFEROVERFLOW, "DI_BUFFEROVERFLOW") -// CHK_ERR(DI_PROPNOEFFECT, "DI_PROPNOEFFECT") -// CHK_ERR(DI_NOEFFECT, "DI_NOEFFECT") -// CHK_ERR(DI_POLLEDDEVICE, "DI_POLLEDDEVICE") -// CHK_ERR(DI_DOWNLOADSKIPPED, "DI_DOWNLOADSKIPPED") -// CHK_ERR(DI_EFFECTRESTARTED, "DI_EFFECTRESTARTED") -// CHK_ERR(DI_SETTINGSNOTSAVED_ACCESSDENIED, "DI_SETTINGSNOTSAVED_ACCESSDENIED") -// CHK_ERR(DI_SETTINGSNOTSAVED_DISKFULL, "DI_SETTINGSNOTSAVED_DISKFULL") -// CHK_ERR(DI_TRUNCATED, "DI_TRUNCATED") -// CHK_ERR(DI_TRUNCATEDANDRESTARTED, "DI_TRUNCATEDANDRESTARTED") -// CHK_ERR(DI_WRITEPROTECT, "DI_WRITEPROTECT") - CHK_ERR(DIERR_OLDDIRECTINPUTVERSION, "The application requires a newer version of DirectInput.") -// CHK_ERR(DIERR_GENERIC, "DIERR_GENERIC") -// CHK_ERR(DIERR_OLDDIRECTINPUTVERSION, "DIERR_OLDDIRECTINPUTVERSION") - CHK_ERR(DIERR_BETADIRECTINPUTVERSION, "The application was written for an unsupported prerelease version of DirectInput.") - CHK_ERR(DIERR_BADDRIVERVER, "The object could not be created due to an incompatible driver version or mismatched or incomplete driver components.") -// CHK_ERR(DIERR_DEVICENOTREG, "DIERR_DEVICENOTREG") -// CHK_ERR(DIERR_NOTFOUND, "The requested object does not exist.") -// CHK_ERR(DIERR_OBJECTNOTFOUND, "DIERR_OBJECTNOTFOUND") -// CHK_ERR(DIERR_INVALIDPARAM, "DIERR_INVALIDPARAM") -// CHK_ERR(DIERR_NOINTERFACE, "DIERR_NOINTERFACE") -// CHK_ERR(DIERR_GENERIC, "DIERR_GENERIC") -// CHK_ERR(DIERR_OUTOFMEMORY, "DIERR_OUTOFMEMORY") -// CHK_ERR(DIERR_UNSUPPORTED, "DIERR_UNSUPPORTED") - CHK_ERR(DIERR_NOTINITIALIZED, "This object has not been initialized") - CHK_ERR(DIERR_ALREADYINITIALIZED, "This object is already initialized") -// CHK_ERR(DIERR_NOAGGREGATION, "DIERR_NOAGGREGATION") -// CHK_ERR(DIERR_OTHERAPPHASPRIO, "DIERR_OTHERAPPHASPRIO") - CHK_ERR(DIERR_INPUTLOST, "Access to the device has been lost. It must be re-acquired.") - CHK_ERR(DIERR_ACQUIRED, "The operation cannot be performed while the device is acquired.") - CHK_ERR(DIERR_NOTACQUIRED, "The operation cannot be performed unless the device is acquired.") -// CHK_ERR(DIERR_READONLY, "DIERR_READONLY") -// CHK_ERR(DIERR_HANDLEEXISTS, "DIERR_HANDLEEXISTS") - CHK_ERR(DIERR_INSUFFICIENTPRIVS, "Unable to IDirectInputJoyConfig_Acquire because the user does not have sufficient privileges to change the joystick configuration. & An invalid media type was specified") - CHK_ERR(DIERR_DEVICEFULL, "The device is full. & An invalid media subtype was specified.") - CHK_ERR(DIERR_MOREDATA, "Not all the requested information fit into the buffer. & This object can only be created as an aggregated object.") - CHK_ERR(DIERR_NOTDOWNLOADED, "The effect is not downloaded. & The enumerator has become invalid.") - CHK_ERR(DIERR_HASEFFECTS, "The device cannot be reinitialized because there are still effects attached to it. & At least one of the pins involved in the operation is already connected.") - CHK_ERR(DIERR_NOTEXCLUSIVEACQUIRED, "The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode. & This operation cannot be performed because the filter is active.") - CHK_ERR(DIERR_INCOMPLETEEFFECT, "The effect could not be downloaded because essential information is missing. For example, no axes have been associated with the effect, or no type-specific information has been created. & One of the specified pins supports no media types.") - CHK_ERR(DIERR_NOTBUFFERED, "Attempted to read buffered device data from a device that is not buffered. & There is no common media type between these pins.") - CHK_ERR(DIERR_EFFECTPLAYING, "An attempt was made to modify parameters of an effect while it is playing. Not all hardware devices support altering the parameters of an effect while it is playing. & Two pins of the same direction cannot be connected together.") - CHK_ERR(DIERR_UNPLUGGED, "The operation could not be completed because the device is not plugged in. & The operation cannot be performed because the pins are not connected.") - CHK_ERR(DIERR_REPORTFULL, "SendDeviceData failed because more information was requested to be sent than can be sent to the device. Some devices have restrictions on how much data can be sent to them. (For example, there might be a limit on the number of buttons that can be pressed at once.) & No sample buffer allocator is available.") - CHK_ERR(DIERR_MAPFILEFAIL, "A mapper file function failed because reading or writing the user or IHV settings file failed. & A run-time error occurred.") - -// ------------------------------------------------------------- -// dinputd.h error codes -// ------------------------------------------------------------- - CHK_ERR(DIERR_NOMOREITEMS, "No more items.") - CHK_ERR(DIERR_DRIVERFIRST, "Device driver-specific codes. Unless the specific driver has been precisely identified, no meaning should be attributed to these values other than that the driver originated the error.") - CHK_ERR(DIERR_DRIVERFIRST+1, "DIERR_DRIVERFIRST+1") - CHK_ERR(DIERR_DRIVERFIRST+2, "DIERR_DRIVERFIRST+2") - CHK_ERR(DIERR_DRIVERFIRST+3, "DIERR_DRIVERFIRST+3") - CHK_ERR(DIERR_DRIVERFIRST+4, "DIERR_DRIVERFIRST+4") - CHK_ERR(DIERR_DRIVERFIRST+5, "DIERR_DRIVERFIRST+5") - CHK_ERR(DIERR_DRIVERLAST, "Device installer errors.") - CHK_ERR(DIERR_INVALIDCLASSINSTALLER, "Registry entry or DLL for class installer invalid or class installer not found.") - CHK_ERR(DIERR_CANCELLED, "The user cancelled the install operation. & The stream already has allocated samples and the surface doesn't match the sample format.") - CHK_ERR(DIERR_BADINF, "The INF file for the selected device could not be found or is invalid or is damaged. & The specified purpose ID can't be used for the call.") - -// ------------------------------------------------------------- -// d3d9.h error codes -// ------------------------------------------------------------- -// CHK_ERR(D3D_OK, "Ok") - CHK_ERR(D3DERR_WRONGTEXTUREFORMAT, "Wrong texture format") - CHK_ERR(D3DERR_UNSUPPORTEDCOLOROPERATION, "Unsupported color operation") - CHK_ERR(D3DERR_UNSUPPORTEDCOLORARG, "Unsupported color arg") - CHK_ERR(D3DERR_UNSUPPORTEDALPHAOPERATION, "Unsupported alpha operation") - CHK_ERR(D3DERR_UNSUPPORTEDALPHAARG, "Unsupported alpha arg") - CHK_ERR(D3DERR_TOOMANYOPERATIONS, "Too many operations") - CHK_ERR(D3DERR_CONFLICTINGTEXTUREFILTER, "Conflicting texture filter") - CHK_ERR(D3DERR_UNSUPPORTEDFACTORVALUE, "Unsupported factor value") - CHK_ERR(D3DERR_CONFLICTINGRENDERSTATE, "Conflicting render state") - CHK_ERR(D3DERR_UNSUPPORTEDTEXTUREFILTER, "Unsupported texture filter") - CHK_ERR(D3DERR_CONFLICTINGTEXTUREPALETTE, "Conflicting texture palette") - CHK_ERR(D3DERR_DRIVERINTERNALERROR, "Driver internal error") - CHK_ERR(D3DERR_NOTFOUND, "Not found") - CHK_ERR(D3DERR_MOREDATA, "More data") - CHK_ERR(D3DERR_DEVICELOST, "Device lost") - CHK_ERR(D3DERR_DEVICENOTRESET, "Device not reset") - CHK_ERR(D3DERR_NOTAVAILABLE, "Not available") - CHK_ERR(D3DERR_OUTOFVIDEOMEMORY, "Out of video memory") - CHK_ERR(D3DERR_INVALIDDEVICE, "Invalid device") - CHK_ERR(D3DERR_INVALIDCALL, "Invalid call") - CHK_ERR(D3DERR_DRIVERINVALIDCALL, "Driver invalid call") - //CHK_ERR(D3DERR_WASSTILLDRAWING, "Was Still Drawing") - CHK_ERR(D3DOK_NOAUTOGEN, "The call succeeded but there won't be any mipmaps generated") - - // Extended for Windows Vista - CHK_ERR(D3DERR_DEVICEREMOVED, "Hardware device was removed") - CHK_ERR(S_NOT_RESIDENT, "Resource not resident in memory") - CHK_ERR(S_RESIDENT_IN_SHARED_MEMORY, "Resource resident in shared memory") - CHK_ERR(S_PRESENT_MODE_CHANGED, "Desktop display mode has changed") - CHK_ERR(S_PRESENT_OCCLUDED, "Client window is occluded (minimized or other fullscreen)") - CHK_ERR(D3DERR_DEVICEHUNG, "Hardware adapter reset by OS") - - // Extended for Windows 7 - CHK_ERR(D3DERR_UNSUPPORTEDOVERLAY, "Overlay is not supported" ) - CHK_ERR(D3DERR_UNSUPPORTEDOVERLAYFORMAT, "Overlay format is not supported" ) - CHK_ERR(D3DERR_CANNOTPROTECTCONTENT, "Contect protection not available" ) - CHK_ERR(D3DERR_UNSUPPORTEDCRYPTO, "Unsupported cryptographic system" ) - CHK_ERR(D3DERR_PRESENT_STATISTICS_DISJOINT, "Presentation statistics are disjoint" ) - - -// ------------------------------------------------------------- -// dsound.h error codes -// ------------------------------------------------------------- -// CHK_ERR(DS_OK, "") - CHK_ERR(DS_NO_VIRTUALIZATION, "The call succeeded, but we had to substitute the 3D algorithm") - CHK_ERR(DSERR_ALLOCATED, "The call failed because resources (such as a priority level) were already being used by another caller") - CHK_ERR(DSERR_CONTROLUNAVAIL, "The control (vol, pan, etc.) requested by the caller is not available") -// CHK_ERR(DSERR_INVALIDPARAM, "DSERR_INVALIDPARAM") - CHK_ERR(DSERR_INVALIDCALL, "This call is not valid for the current state of this object") -// CHK_ERR(DSERR_GENERIC, "DSERR_GENERIC") - CHK_ERR(DSERR_PRIOLEVELNEEDED, "The caller does not have the priority level required for the function to succeed") -// CHK_ERR(DSERR_OUTOFMEMORY, "Not enough free memory is available to complete the operation") - CHK_ERR(DSERR_BADFORMAT, "The specified WAVE format is not supported") -// CHK_ERR(DSERR_UNSUPPORTED, "DSERR_UNSUPPORTED") - CHK_ERR(DSERR_NODRIVER, "No sound driver is available for use") - CHK_ERR(DSERR_ALREADYINITIALIZED, "This object is already initialized") -// CHK_ERR(DSERR_NOAGGREGATION, "DSERR_NOAGGREGATION") - CHK_ERR(DSERR_BUFFERLOST, "The buffer memory has been lost, and must be restored") - CHK_ERR(DSERR_OTHERAPPHASPRIO, "Another app has a higher priority level, preventing this call from succeeding") - CHK_ERR(DSERR_UNINITIALIZED, "This object has not been initialized") -// CHK_ERR(DSERR_NOINTERFACE, "DSERR_NOINTERFACE") -// CHK_ERR(DSERR_ACCESSDENIED, "DSERR_ACCESSDENIED") - CHK_ERR(DSERR_BUFFERTOOSMALL, "Tried to create a DSBCAPS_CTRLFX buffer shorter than DSBSIZE_FX_MIN milliseconds") - CHK_ERR(DSERR_DS8_REQUIRED, "Attempt to use DirectSound 8 functionality on an older DirectSound object") - CHK_ERR(DSERR_SENDLOOP, "A circular loop of send effects was detected") - CHK_ERR(DSERR_BADSENDBUFFERGUID, "The GUID specified in an audiopath file does not match a valid MIXIN buffer") - CHK_ERR(DSERR_OBJECTNOTFOUND, "The object requested was not found (numerically equal to DMUS_E_NOT_FOUND)") - - CHK_ERR(DSERR_FXUNAVAILABLE, "Requested effects are not available") - -#endif // !WINAPI_FAMILY || WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP - -// ------------------------------------------------------------- -// d3d10.h error codes -// ------------------------------------------------------------- - CHK_ERR(D3D10_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS, "There are too many unique state objects.") - CHK_ERR(D3D10_ERROR_FILE_NOT_FOUND, "File not found") - -// ------------------------------------------------------------- -// dxgi.h error codes -// ------------------------------------------------------------- - CHK_ERR(DXGI_STATUS_OCCLUDED, "The target window or output has been occluded. The application should suspend rendering operations if possible.") - CHK_ERR(DXGI_STATUS_CLIPPED, "Target window is clipped.") - CHK_ERR(DXGI_STATUS_NO_REDIRECTION, "") - CHK_ERR(DXGI_STATUS_NO_DESKTOP_ACCESS, "No access to desktop.") - CHK_ERR(DXGI_STATUS_GRAPHICS_VIDPN_SOURCE_IN_USE, "") - CHK_ERR(DXGI_STATUS_MODE_CHANGED, "Display mode has changed") - CHK_ERR(DXGI_STATUS_MODE_CHANGE_IN_PROGRESS, "Display mode is changing") - CHK_ERR(DXGI_ERROR_INVALID_CALL, "The application has made an erroneous API call that it had enough information to avoid. This error is intended to denote that the application should be altered to avoid the error. Use of the debug version of the DXGI.DLL will provide run-time debug output with further information.") - CHK_ERR(DXGI_ERROR_NOT_FOUND, "The item requested was not found. For GetPrivateData calls, this means that the specified GUID had not been previously associated with the object.") - CHK_ERR(DXGI_ERROR_MORE_DATA, "The specified size of the destination buffer is too small to hold the requested data.") - CHK_ERR(DXGI_ERROR_UNSUPPORTED, "Unsupported.") - CHK_ERR(DXGI_ERROR_DEVICE_REMOVED, "Hardware device removed.") - CHK_ERR(DXGI_ERROR_DEVICE_HUNG, "Device hung due to badly formed commands.") - CHK_ERR(DXGI_ERROR_DEVICE_RESET, "Device reset due to a badly formed commant.") - CHK_ERR(DXGI_ERROR_WAS_STILL_DRAWING, "Was still drawing.") - CHK_ERR(DXGI_ERROR_FRAME_STATISTICS_DISJOINT, "The requested functionality is not supported by the device or the driver.") - CHK_ERR(DXGI_ERROR_GRAPHICS_VIDPN_SOURCE_IN_USE, "The requested functionality is not supported by the device or the driver.") - CHK_ERR(DXGI_ERROR_DRIVER_INTERNAL_ERROR, "An internal driver error occurred.") - CHK_ERR(DXGI_ERROR_NONEXCLUSIVE, "The application attempted to perform an operation on an DXGI output that is only legal after the output has been claimed for exclusive owenership.") - CHK_ERR(DXGI_ERROR_NOT_CURRENTLY_AVAILABLE, "The requested functionality is not supported by the device or the driver.") - CHK_ERR(DXGI_ERROR_REMOTE_CLIENT_DISCONNECTED, "Remote desktop client disconnected.") - CHK_ERR(DXGI_ERROR_REMOTE_OUTOFMEMORY, "Remote desktop client is out of memory.") - -// ------------------------------------------------------------- -// d3d11.h error codes -// ------------------------------------------------------------- - CHK_ERR(D3D11_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS, "There are too many unique state objects.") - CHK_ERR(D3D11_ERROR_FILE_NOT_FOUND, "File not found") - CHK_ERR(D3D11_ERROR_TOO_MANY_UNIQUE_VIEW_OBJECTS, "Therea are too many unique view objects.") - CHK_ERR(D3D11_ERROR_DEFERRED_CONTEXT_MAP_WITHOUT_INITIAL_DISCARD, "Deferred context requires Map-Discard usage pattern") - -#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP - -// ------------------------------------------------------------- -// Direct2D error codes -// ------------------------------------------------------------- -// CHK_ERR(D2DERR_UNSUPPORTED_PIXEL_FORMAT, "The pixel format is not supported.") -// CHK_ERR(D2DERR_INSUFFICIENT_BUFFER, "The supplied buffer was too small to accomodate the data.") - CHK_ERR(D2DERR_WRONG_STATE, "The object was not in the correct state to process the method.") - CHK_ERR(D2DERR_NOT_INITIALIZED, "The object has not yet been initialized.") - CHK_ERR(D2DERR_UNSUPPORTED_OPERATION, "The requested opertion is not supported.") - CHK_ERR(D2DERR_SCANNER_FAILED, "The geomery scanner failed to process the data.") - CHK_ERR(D2DERR_SCREEN_ACCESS_DENIED, "D2D could not access the screen.") - CHK_ERR(D2DERR_DISPLAY_STATE_INVALID, "A valid display state could not be determined.") - CHK_ERR(D2DERR_ZERO_VECTOR, "The supplied vector is zero.") - CHK_ERR(D2DERR_INTERNAL_ERROR, "An internal error (D2D bug) occurred. On checked builds, we would assert.") - CHK_ERR(D2DERR_DISPLAY_FORMAT_NOT_SUPPORTED, "The display format we need to render is not supported by the hardware device.") - CHK_ERR(D2DERR_INVALID_CALL, "A call to this method is invalid.") - CHK_ERR(D2DERR_NO_HARDWARE_DEVICE, "No HW rendering device is available for this operation.") - CHK_ERR(D2DERR_RECREATE_TARGET, "here has been a presentation error that may be recoverable. The caller needs to recreate, rerender the entire frame, and reattempt present.") - CHK_ERR(D2DERR_TOO_MANY_SHADER_ELEMENTS, "Shader construction failed because it was too complex.") - CHK_ERR(D2DERR_SHADER_COMPILE_FAILED, "Shader compilation failed.") - CHK_ERR(D2DERR_MAX_TEXTURE_SIZE_EXCEEDED, "Requested DX surface size exceeded maximum texture size.") - CHK_ERR(D2DERR_UNSUPPORTED_VERSION, "The requested D2D version is not supported.") - CHK_ERR(D2DERR_BAD_NUMBER, "Invalid number.") - CHK_ERR(D2DERR_WRONG_FACTORY, "Objects used together must be created from the same factory instance.") - CHK_ERR(D2DERR_LAYER_ALREADY_IN_USE, "A layer resource can only be in use once at any point in time.") - CHK_ERR(D2DERR_POP_CALL_DID_NOT_MATCH_PUSH, "The pop call did not match the corresponding push call") -// CHK_ERR(D2DERR_WRONG_RESOURCE_DOMAIN, "The resource was realized on the wrong render target") - CHK_ERR(D2DERR_PUSH_POP_UNBALANCED, "The push and pop calls were unbalanced") - CHK_ERR(D2DERR_RENDER_TARGET_HAS_LAYER_OR_CLIPRECT, "Attempt to copy from a render target while a layer or clip rect is applied") - CHK_ERR(D2DERR_INCOMPATIBLE_BRUSH_TYPES, "The brush types are incompatible for the call.") - CHK_ERR(D2DERR_WIN32_ERROR, "An unknown win32 failure occurred.") - CHK_ERR(D2DERR_TARGET_NOT_GDI_COMPATIBLE, "The render target is not compatible with GDI") - CHK_ERR(D2DERR_TEXT_EFFECT_IS_WRONG_TYPE, "A text client drawing effect object is of the wrong type") - CHK_ERR(D2DERR_TEXT_RENDERER_NOT_RELEASED, "The application is holding a reference to the IDWriteTextRenderer interface after the corresponding DrawText or DrawTextLayout call has returned. The IDWriteTextRenderer instance will be zombied.") -// CHK_ERR(D2DERR_EXCEEDS_MAX_BITMAP_SIZE, "The requested size is larger than the guaranteed supported texture size.") - -// ------------------------------------------------------------- -// DirectWrite error codes -// ------------------------------------------------------------- - CHK_ERR(DWRITE_E_FILEFORMAT, "Indicates an error in an input file such as a font file.") - CHK_ERR(DWRITE_E_UNEXPECTED, "Indicates an error originating in DirectWrite code, which is not expected to occur but is safe to recover from.") - CHK_ERR(DWRITE_E_NOFONT, "Indicates the specified font does not exist.") - CHK_ERR(DWRITE_E_FILENOTFOUND, "A font file could not be opened because the file, directory, network location, drive, or other storage location does not exist or is unavailable.") - CHK_ERR(DWRITE_E_FILEACCESS, "A font file exists but could not be opened due to access denied, sharing violation, or similar error.") - CHK_ERR(DWRITE_E_FONTCOLLECTIONOBSOLETE, "A font collection is obsolete due to changes in the system.") - CHK_ERR(DWRITE_E_ALREADYREGISTERED, "The given interface is already registered.") - -// ------------------------------------------------------------- -// WIC error codes -// ------------------------------------------------------------- - CHK_ERR(WINCODEC_ERR_WRONGSTATE, "WIC object in incorrect state.") - CHK_ERR(WINCODEC_ERR_VALUEOUTOFRANGE, "WIC Value out of range.") - CHK_ERR(WINCODEC_ERR_UNKNOWNIMAGEFORMAT, "Encountered unexpected value or setting in WIC image format.") - CHK_ERR(WINCODEC_ERR_UNSUPPORTEDVERSION, "Unsupported WINCODEC_SD_VERSION passed to WIC factory.") - CHK_ERR(WINCODEC_ERR_NOTINITIALIZED, "WIC component not initialized.") - CHK_ERR(WINCODEC_ERR_ALREADYLOCKED, "WIC bitmap object already locked.") - CHK_ERR(WINCODEC_ERR_PROPERTYNOTFOUND, "WIC property not found.") - CHK_ERR(WINCODEC_ERR_PROPERTYNOTSUPPORTED, "WIC property not supported.") - CHK_ERR(WINCODEC_ERR_PROPERTYSIZE, "Invalid property size") - CHK_ERRA(WINCODEC_ERR_CODECPRESENT) // not currently used by WIC - CHK_ERRA(WINCODEC_ERR_CODECNOTHUMBNAIL) // not currently used by WIC - CHK_ERR(WINCODEC_ERR_PALETTEUNAVAILABLE, "Required palette data not available.") - CHK_ERR(WINCODEC_ERR_CODECTOOMANYSCANLINES, "More scanlines requested than are available in WIC bitmap.") - CHK_ERR(WINCODEC_ERR_INTERNALERROR, "Unexpected internal error in WIC.") - CHK_ERR(WINCODEC_ERR_SOURCERECTDOESNOTMATCHDIMENSIONS, "Source WIC rectangle does not match bitmap dimensions.") - CHK_ERR(WINCODEC_ERR_COMPONENTNOTFOUND, "WIC component not found.") - CHK_ERR(WINCODEC_ERR_IMAGESIZEOUTOFRANGE, "Image size beyond expected boundaries for WIC codec." ) - CHK_ERR(WINCODEC_ERR_TOOMUCHMETADATA, "Image metadata size beyond expected boundaries for WIC codec.") - CHK_ERR(WINCODEC_ERR_BADIMAGE, "WIC image is corrupted.") - CHK_ERR(WINCODEC_ERR_BADHEADER, "Invalid header found in WIC image.") - CHK_ERR(WINCODEC_ERR_FRAMEMISSING, "Expected bitmap frame data not found in WIC image." ) - CHK_ERR(WINCODEC_ERR_BADMETADATAHEADER, "Invalid metadata header found in WIC image.") - CHK_ERR(WINCODEC_ERR_BADSTREAMDATA, "Invalid stream data found in WIC image.") - CHK_ERR(WINCODEC_ERR_STREAMWRITE, "WIC operation on write stream failed.") - CHK_ERR(WINCODEC_ERR_STREAMREAD, "WIC operation on read stream failed.") - CHK_ERR(WINCODEC_ERR_STREAMNOTAVAILABLE, "Required stream is not available." ) - CHK_ERR(WINCODEC_ERR_UNSUPPORTEDPIXELFORMAT, "The pixel format is not supported.") - CHK_ERR(WINCODEC_ERR_UNSUPPORTEDOPERATION, "This operation is not supported by WIC." ) - CHK_ERR(WINCODEC_ERR_INVALIDREGISTRATION, "Error occurred reading WIC codec registry keys.") - CHK_ERR(WINCODEC_ERR_COMPONENTINITIALIZEFAILURE, "Failed initializing WIC codec.") - CHK_ERR(WINCODEC_ERR_INSUFFICIENTBUFFER, "Not enough buffer space available for WIC operation.") - CHK_ERR(WINCODEC_ERR_DUPLICATEMETADATAPRESENT, "Duplicate metadata detected in WIC image.") - CHK_ERR(WINCODEC_ERR_PROPERTYUNEXPECTEDTYPE, "Unexpected property type in WIC image.") - CHK_ERR(WINCODEC_ERR_UNEXPECTEDSIZE, "Unexpected value size in WIC metadata.") - CHK_ERR(WINCODEC_ERR_INVALIDQUERYREQUEST, "Invalid metadata query.") - CHK_ERR(WINCODEC_ERR_UNEXPECTEDMETADATATYPE, "Unexpected metadata type encountered in WIC image.") - CHK_ERR(WINCODEC_ERR_REQUESTONLYVALIDATMETADATAROOT, "Operation only valid on meatadata root.") - CHK_ERR(WINCODEC_ERR_INVALIDQUERYCHARACTER, "Invalid character in WIC metadata query.") - CHK_ERR(WINCODEC_ERR_WIN32ERROR, "General Win32 error encountered during WIC operation.") - CHK_ERR(WINCODEC_ERR_INVALIDPROGRESSIVELEVEL, "Invalid level for progressive WIC image decode.") - -#endif // !WINAPI_FAMILY || WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP - -// ------------------------------------------------------------- -// DXUT error codes -// ------------------------------------------------------------- - CHK_ERR(DXUTERR_NODIRECT3D, "Could not initialize Direct3D.") - CHK_ERR(DXUTERR_NOCOMPATIBLEDEVICES, "No device could be found with the specified device settings.") - CHK_ERR(DXUTERR_MEDIANOTFOUND, "A media file could not be found.") - CHK_ERR(DXUTERR_NONZEROREFCOUNT, "The device interface has a non-zero reference count, meaning that some objects were not released.") - CHK_ERR(DXUTERR_CREATINGDEVICE, "An error occurred when attempting to create a device.") - CHK_ERR(DXUTERR_RESETTINGDEVICE, "An error occurred when attempting to reset a device.") - CHK_ERR(DXUTERR_CREATINGDEVICEOBJECTS, "An error occurred in the device create callback function.") - CHK_ERR(DXUTERR_RESETTINGDEVICEOBJECTS, "An error occurred in the device reset callback function.") - CHK_ERR(DXUTERR_INCORRECTVERSION, "Incorrect version of Direct3D or D3DX.") - CHK_ERR(DXUTERR_DEVICEREMOVED, "The device was removed.") - -// ------------------------------------------------------------- -// xaudio2.h error codes -// ------------------------------------------------------------- - CHK_ERR(XAUDIO2_E_INVALID_CALL, "Invalid XAudio2 API call or arguments") - CHK_ERR(XAUDIO2_E_XMA_DECODER_ERROR, "Hardware XMA decoder error") - CHK_ERR(XAUDIO2_E_XAPO_CREATION_FAILED, "Failed to create an audio effect") - CHK_ERR(XAUDIO2_E_DEVICE_INVALIDATED, "Device invalidated (unplugged, disabled, etc)") - -// ------------------------------------------------------------- -// xapo.h error codes -// ------------------------------------------------------------- - CHK_ERR(XAPO_E_FORMAT_UNSUPPORTED, "Requested audio format unsupported.") - - default: wcscpy_s( desc, count, L"Unknown error." ); break; - } -} - -//----------------------------------------------------------------------------- -HRESULT WINAPI DXTraceW( _In_z_ const WCHAR* strFile, _In_ DWORD dwLine, _In_ HRESULT hr, - _In_opt_ const WCHAR* strMsg, _In_ bool bPopMsgBox ) -{ - WCHAR strBufferLine[128]; - WCHAR strBufferError[256]; - WCHAR strBuffer[BUFFER_SIZE]; - - swprintf_s( strBufferLine, 128, L"%lu", dwLine ); - if( strFile ) - { - swprintf_s( strBuffer, BUFFER_SIZE, L"%ls(%ls): ", strFile, strBufferLine ); - OutputDebugStringW( strBuffer ); - } - - size_t nMsgLen = (strMsg) ? wcsnlen_s( strMsg, 1024 ) : 0; - if( nMsgLen > 0 ) - { - OutputDebugStringW( strMsg ); - OutputDebugStringW( L" " ); - } - - swprintf_s( strBufferError, 256, L"%ls (0x%0.8x)", DXGetErrorStringW(hr), hr ); - swprintf_s( strBuffer, BUFFER_SIZE, L"hr=%ls", strBufferError ); - OutputDebugStringW( strBuffer ); - - OutputDebugStringW( L"\n" ); - -#if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) - if( bPopMsgBox ) - { - WCHAR strBufferFile[MAX_PATH]; - wcscpy_s( strBufferFile, MAX_PATH, L"" ); - if( strFile ) - wcscpy_s( strBufferFile, MAX_PATH, strFile ); - - WCHAR strBufferMsg[1024]; - wcscpy_s( strBufferMsg, 1024, L"" ); - if( nMsgLen > 0 ) - swprintf_s( strBufferMsg, 1024, L"Calling: %ls\n", strMsg ); - - swprintf_s( strBuffer, BUFFER_SIZE, L"File: %ls\nLine: %ls\nError Code: %ls\n%lsDo you want to debug the application?", - strBufferFile, strBufferLine, strBufferError, strBufferMsg ); - - int nResult = MessageBoxW( GetForegroundWindow(), strBuffer, L"Unexpected error encountered", MB_YESNO | MB_ICONERROR ); - if( nResult == IDYES ) - DebugBreak(); - } -#else - UNREFERENCED_PARAMETER(bPopMsgBox); -#endif - - return hr; -} -#endif -namespace Ogre -{ - String DXGetErrorDescription(HRESULT hr) - { -#ifndef __MINGW32__ - WCHAR wideBuf[1024]; - wideBuf[0] = 0; - DXGetErrorDescriptionW(hr, wideBuf, ARRAYSIZE(wideBuf)); - - char narrowBuf[2048]; - narrowBuf[0] = 0; - if(0 == WideCharToMultiByte(CP_ACP, 0, wideBuf, -1, narrowBuf, ARRAYSIZE(narrowBuf), NULL, NULL)) - narrowBuf[0] = 0; - - return String(narrowBuf); -#else - return ""; -#endif - } -} diff --git a/RenderSystems/GL/CMakeLists.txt b/RenderSystems/GL/CMakeLists.txt deleted file mode 100644 index 4b8331a9fdd..00000000000 --- a/RenderSystems/GL/CMakeLists.txt +++ /dev/null @@ -1,78 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure OpenGL RenderSystem build - -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") -list(APPEND SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/glad.c") - -file(GLOB NVPARSE_SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/src/nvparse/*.cpp") -file(GLOB NVPARSE_HEADERS "${CMAKE_CURRENT_SOURCE_DIR}/src/nvparse/*.h") - -if(UNIX) - # easier than porting to new flex - foreach(NVSRC ${NVPARSE_SOURCE}) - set_source_files_properties(${NVSRC} - PROPERTIES COMPILE_FLAGS "-Wno-unused-function -Wno-shadow -Wno-cast-qual -Wno-missing-declarations -Wno-undef" - COMPILE_DEFINITIONS "register=" - ) - endforeach() - set_source_files_properties(src/atifs/src/Compiler2Pass.cpp - PROPERTIES COMPILE_FLAGS -Wno-implicit-fallthrough) -endif() - -# Remove test app file -list(REMOVE_ITEM NVPARSE_SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/src/nvparse/ps1.0__test_main.cpp") - -file(GLOB ATIFS_SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/src/atifs/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/src/atifs/src/*.cpp") -file(GLOB ATIFS_HEADERS "${CMAKE_CURRENT_SOURCE_DIR}/src/atifs/*.h") - -file(GLOB GLSL_HEADERS "${CMAKE_CURRENT_SOURCE_DIR}/src/GLSL/include/*.h") -file(GLOB GLSL_SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/src/GLSL/src/*.cpp") - -source_group(NVparse FILES ${NVPARSE_SOURCE} ${NVPARSE_HEADERS}) -source_group(ATIFS FILES ${ATIFS_SOURCE} ${ATIFS_HEADERS}) -source_group(GLSL FILES ${GLSL_SOURCE} ${GLSL_HEADERS}) - -if(OGRE_CONFIG_ENABLE_GL_STATE_CACHE_SUPPORT) - set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/src/OgreGLStateCacheManager.cpp - PROPERTIES COMPILE_DEFINITIONS OGRE_ENABLE_STATE_CACHE) -endif() - -list(APPEND HEADER_FILES - ${GLSL_HEADERS} - ${NVPARSE_HEADERS} - ${ATIFS_HEADERS} -) - -include_directories( - ${CMAKE_CURRENT_SOURCE_DIR}/src/GLSL/include - ${CMAKE_CURRENT_SOURCE_DIR}/src/atifs/include - ${CMAKE_CURRENT_SOURCE_DIR}/src/nvparse -) - -add_definitions(-DYY_NEVER_INTERACTIVE) -add_definitions(-DOGRE_GLPLUGIN_EXPORTS ${OGRE_VISIBILITY_FLAGS}) -#Note that in the next row SOURCE_FILES are added last. This is to prevent compilation problems of unity build found on Windows Visual Studio. -#In this situation any file added after the "glew.cpp" file, which belongs to the SOURCE_FILES package, does not compile -add_library(RenderSystem_GL ${OGRE_LIB_TYPE} ${HEADER_FILES} ${GLSL_SOURCE} ${ATIFS_SOURCE} ${NVPARSE_SOURCE} ${SOURCE_FILES}) -target_link_libraries(RenderSystem_GL PUBLIC OgreMain PRIVATE OgreGLSupport ${CMAKE_DL_LIBS}) -target_include_directories(RenderSystem_GL PUBLIC - "$" - $) - -target_include_directories(RenderSystem_GL PUBLIC ${OPENGL_INCLUDE_DIR}) - -ogre_config_framework(RenderSystem_GL) - -ogre_config_plugin(RenderSystem_GL) -install(FILES ${HEADER_FILES} ${GLSUPPORT_HEADERS} DESTINATION include/OGRE/RenderSystems/GL) -install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include/glad DESTINATION include/OGRE/RenderSystems/glad) -install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include/KHR DESTINATION include/OGRE/RenderSystems/KHR) diff --git a/RenderSystems/GL/include/KHR/khrplatform.h b/RenderSystems/GL/include/KHR/khrplatform.h deleted file mode 100644 index 01646449cae..00000000000 --- a/RenderSystems/GL/include/KHR/khrplatform.h +++ /dev/null @@ -1,311 +0,0 @@ -#ifndef __khrplatform_h_ -#define __khrplatform_h_ - -/* -** Copyright (c) 2008-2018 The Khronos Group Inc. -** -** Permission is hereby granted, free of charge, to any person obtaining a -** copy of this software and/or associated documentation files (the -** "Materials"), to deal in the Materials without restriction, including -** without limitation the rights to use, copy, modify, merge, publish, -** distribute, sublicense, and/or sell copies of the Materials, and to -** permit persons to whom the Materials are furnished to do so, subject to -** the following conditions: -** -** The above copyright notice and this permission notice shall be included -** in all copies or substantial portions of the Materials. -** -** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. -*/ - -/* Khronos platform-specific types and definitions. - * - * The master copy of khrplatform.h is maintained in the Khronos EGL - * Registry repository at https://github.com/KhronosGroup/EGL-Registry - * The last semantic modification to khrplatform.h was at commit ID: - * 67a3e0864c2d75ea5287b9f3d2eb74a745936692 - * - * Adopters may modify this file to suit their platform. Adopters are - * encouraged to submit platform specific modifications to the Khronos - * group so that they can be included in future versions of this file. - * Please submit changes by filing pull requests or issues on - * the EGL Registry repository linked above. - * - * - * See the Implementer's Guidelines for information about where this file - * should be located on your system and for more details of its use: - * http://www.khronos.org/registry/implementers_guide.pdf - * - * This file should be included as - * #include - * by Khronos client API header files that use its types and defines. - * - * The types in khrplatform.h should only be used to define API-specific types. - * - * Types defined in khrplatform.h: - * khronos_int8_t signed 8 bit - * khronos_uint8_t unsigned 8 bit - * khronos_int16_t signed 16 bit - * khronos_uint16_t unsigned 16 bit - * khronos_int32_t signed 32 bit - * khronos_uint32_t unsigned 32 bit - * khronos_int64_t signed 64 bit - * khronos_uint64_t unsigned 64 bit - * khronos_intptr_t signed same number of bits as a pointer - * khronos_uintptr_t unsigned same number of bits as a pointer - * khronos_ssize_t signed size - * khronos_usize_t unsigned size - * khronos_float_t signed 32 bit floating point - * khronos_time_ns_t unsigned 64 bit time in nanoseconds - * khronos_utime_nanoseconds_t unsigned time interval or absolute time in - * nanoseconds - * khronos_stime_nanoseconds_t signed time interval in nanoseconds - * khronos_boolean_enum_t enumerated boolean type. This should - * only be used as a base type when a client API's boolean type is - * an enum. Client APIs which use an integer or other type for - * booleans cannot use this as the base type for their boolean. - * - * Tokens defined in khrplatform.h: - * - * KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values. - * - * KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0. - * KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0. - * - * Calling convention macros defined in this file: - * KHRONOS_APICALL - * KHRONOS_APIENTRY - * KHRONOS_APIATTRIBUTES - * - * These may be used in function prototypes as: - * - * KHRONOS_APICALL void KHRONOS_APIENTRY funcname( - * int arg1, - * int arg2) KHRONOS_APIATTRIBUTES; - */ - -#if defined(__SCITECH_SNAP__) && !defined(KHRONOS_STATIC) -# define KHRONOS_STATIC 1 -#endif - -/*------------------------------------------------------------------------- - * Definition of KHRONOS_APICALL - *------------------------------------------------------------------------- - * This precedes the return type of the function in the function prototype. - */ -#if defined(KHRONOS_STATIC) - /* If the preprocessor constant KHRONOS_STATIC is defined, make the - * header compatible with static linking. */ -# define KHRONOS_APICALL -#elif defined(_WIN32) -# define KHRONOS_APICALL __declspec(dllimport) -#elif defined (__SYMBIAN32__) -# define KHRONOS_APICALL IMPORT_C -#elif defined(__ANDROID__) -# define KHRONOS_APICALL __attribute__((visibility("default"))) -#else -# define KHRONOS_APICALL -#endif - -/*------------------------------------------------------------------------- - * Definition of KHRONOS_APIENTRY - *------------------------------------------------------------------------- - * This follows the return type of the function and precedes the function - * name in the function prototype. - */ -#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__) - /* Win32 but not WinCE */ -# define KHRONOS_APIENTRY __stdcall -#else -# define KHRONOS_APIENTRY -#endif - -/*------------------------------------------------------------------------- - * Definition of KHRONOS_APIATTRIBUTES - *------------------------------------------------------------------------- - * This follows the closing parenthesis of the function prototype arguments. - */ -#if defined (__ARMCC_2__) -#define KHRONOS_APIATTRIBUTES __softfp -#else -#define KHRONOS_APIATTRIBUTES -#endif - -/*------------------------------------------------------------------------- - * basic type definitions - *-----------------------------------------------------------------------*/ -#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__) - - -/* - * Using - */ -#include -typedef int32_t khronos_int32_t; -typedef uint32_t khronos_uint32_t; -typedef int64_t khronos_int64_t; -typedef uint64_t khronos_uint64_t; -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 -/* - * To support platform where unsigned long cannot be used interchangeably with - * inptr_t (e.g. CHERI-extended ISAs), we can use the stdint.h intptr_t. - * Ideally, we could just use (u)intptr_t everywhere, but this could result in - * ABI breakage if khronos_uintptr_t is changed from unsigned long to - * unsigned long long or similar (this results in different C++ name mangling). - * To avoid changes for existing platforms, we restrict usage of intptr_t to - * platforms where the size of a pointer is larger than the size of long. - */ -#if defined(__SIZEOF_LONG__) && defined(__SIZEOF_POINTER__) -#if __SIZEOF_POINTER__ > __SIZEOF_LONG__ -#define KHRONOS_USE_INTPTR_T -#endif -#endif - -#elif defined(__VMS ) || defined(__sgi) - -/* - * Using - */ -#include -typedef int32_t khronos_int32_t; -typedef uint32_t khronos_uint32_t; -typedef int64_t khronos_int64_t; -typedef uint64_t khronos_uint64_t; -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 - -#elif defined(_WIN32) && !defined(__SCITECH_SNAP__) - -/* - * Win32 - */ -typedef __int32 khronos_int32_t; -typedef unsigned __int32 khronos_uint32_t; -typedef __int64 khronos_int64_t; -typedef unsigned __int64 khronos_uint64_t; -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 - -#elif defined(__sun__) || defined(__digital__) - -/* - * Sun or Digital - */ -typedef int khronos_int32_t; -typedef unsigned int khronos_uint32_t; -#if defined(__arch64__) || defined(_LP64) -typedef long int khronos_int64_t; -typedef unsigned long int khronos_uint64_t; -#else -typedef long long int khronos_int64_t; -typedef unsigned long long int khronos_uint64_t; -#endif /* __arch64__ */ -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 - -#elif 0 - -/* - * Hypothetical platform with no float or int64 support - */ -typedef int khronos_int32_t; -typedef unsigned int khronos_uint32_t; -#define KHRONOS_SUPPORT_INT64 0 -#define KHRONOS_SUPPORT_FLOAT 0 - -#else - -/* - * Generic fallback - */ -#include -typedef int32_t khronos_int32_t; -typedef uint32_t khronos_uint32_t; -typedef int64_t khronos_int64_t; -typedef uint64_t khronos_uint64_t; -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 - -#endif - - -/* - * Types that are (so far) the same on all platforms - */ -typedef signed char khronos_int8_t; -typedef unsigned char khronos_uint8_t; -typedef signed short int khronos_int16_t; -typedef unsigned short int khronos_uint16_t; - -/* - * Types that differ between LLP64 and LP64 architectures - in LLP64, - * pointers are 64 bits, but 'long' is still 32 bits. Win64 appears - * to be the only LLP64 architecture in current use. - */ -#ifdef KHRONOS_USE_INTPTR_T -typedef intptr_t khronos_intptr_t; -typedef uintptr_t khronos_uintptr_t; -#elif defined(_WIN64) -typedef signed long long int khronos_intptr_t; -typedef unsigned long long int khronos_uintptr_t; -#else -typedef signed long int khronos_intptr_t; -typedef unsigned long int khronos_uintptr_t; -#endif - -#if defined(_WIN64) -typedef signed long long int khronos_ssize_t; -typedef unsigned long long int khronos_usize_t; -#else -typedef signed long int khronos_ssize_t; -typedef unsigned long int khronos_usize_t; -#endif - -#if KHRONOS_SUPPORT_FLOAT -/* - * Float type - */ -typedef float khronos_float_t; -#endif - -#if KHRONOS_SUPPORT_INT64 -/* Time types - * - * These types can be used to represent a time interval in nanoseconds or - * an absolute Unadjusted System Time. Unadjusted System Time is the number - * of nanoseconds since some arbitrary system event (e.g. since the last - * time the system booted). The Unadjusted System Time is an unsigned - * 64 bit value that wraps back to 0 every 584 years. Time intervals - * may be either signed or unsigned. - */ -typedef khronos_uint64_t khronos_utime_nanoseconds_t; -typedef khronos_int64_t khronos_stime_nanoseconds_t; -#endif - -/* - * Dummy value used to pad enum types to 32 bits. - */ -#ifndef KHRONOS_MAX_ENUM -#define KHRONOS_MAX_ENUM 0x7FFFFFFF -#endif - -/* - * Enumerated boolean type - * - * Values other than zero should be considered to be true. Therefore - * comparisons should not be made against KHRONOS_TRUE. - */ -typedef enum { - KHRONOS_FALSE = 0, - KHRONOS_TRUE = 1, - KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM -} khronos_boolean_enum_t; - -#endif /* __khrplatform_h_ */ diff --git a/RenderSystems/GL/include/OgreGLCopyingRenderTexture.h b/RenderSystems/GL/include/OgreGLCopyingRenderTexture.h deleted file mode 100644 index edb13742523..00000000000 --- a/RenderSystems/GL/include/OgreGLCopyingRenderTexture.h +++ /dev/null @@ -1,72 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLCOPYINGRENDERTEXTURE_H__ -#define __GLCOPYINGRENDERTEXTURE_H__ - -#include "OgreGLPrerequisites.h" -#include "OgreGLRenderTexture.h" - -namespace Ogre { - /** RenderTexture for simple copying from frame buffer - */ - class GLCopyingRTTManager; - class _OgreGLExport GLCopyingRenderTexture: public GLRenderTexture - { - public: - GLCopyingRenderTexture(GLCopyingRTTManager *manager, const String &name, const GLSurfaceDesc &target, - bool writeGamma, uint fsaa); - - void getCustomAttribute(const String& name, void* pData) override; - - GLContext* getContext() const override { return NULL; } - }; - - /** Simple, copying manager/factory for RenderTextures. This is only used as the last fallback if - both PBuffers and FBOs aren't supported. - */ - class _OgreGLExport GLCopyingRTTManager: public GLRTTManager - { - public: - RenderTexture *createRenderTexture(const String &name, const GLSurfaceDesc &target, bool writeGamma, uint fsaa) override { - return new GLCopyingRenderTexture(this, name, target, writeGamma, fsaa); - } - - bool checkFormat(PixelFormat format) { - return true; - } - - void bind(RenderTarget *target) override { - // Nothing to do here - } - - void unbind(RenderTarget *target) override; - }; -} - -#endif // __GLTEXTURE_H__ diff --git a/RenderSystems/GL/include/OgreGLFBOMultiRenderTarget.h b/RenderSystems/GL/include/OgreGLFBOMultiRenderTarget.h deleted file mode 100644 index 115f9dec2d8..00000000000 --- a/RenderSystems/GL/include/OgreGLFBOMultiRenderTarget.h +++ /dev/null @@ -1,61 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLMULTIRENDERTARGET_H__ -#define __GLMULTIRENDERTARGET_H__ - -#include "OgreGLFrameBufferObject.h" - -namespace Ogre { - /** MultiRenderTarget for GL. Requires the FBO extension. - */ - class _OgreGLExport GLFBOMultiRenderTarget : public MultiRenderTarget, public GLRenderTarget - { - public: - GLFBOMultiRenderTarget(GLFBOManager *manager, const String &name); - ~GLFBOMultiRenderTarget(); - - void getCustomAttribute( const String& name, void *pData ) override; - GLContext* getContext() const override { return fbo.getContext(); } - GLFrameBufferObjectCommon* getFBO() override { return &fbo; } - - bool requiresTextureFlipping() const override { return true; } - - /// Override so we can attach the depth buffer to the FBO - bool attachDepthBuffer( DepthBuffer *depthBuffer ) override; - void detachDepthBuffer() override; - void _detachDepthBuffer() override; - private: - void bindSurfaceImpl(size_t attachment, RenderTexture *target) override; - void unbindSurfaceImpl(size_t attachment) override; - GLFrameBufferObject fbo; - }; - -} - -#endif // __GLMULTIRENDERTARGET_H__ diff --git a/RenderSystems/GL/include/OgreGLFBORenderTexture.h b/RenderSystems/GL/include/OgreGLFBORenderTexture.h deleted file mode 100644 index ad6c93ee5b7..00000000000 --- a/RenderSystems/GL/include/OgreGLFBORenderTexture.h +++ /dev/null @@ -1,113 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OgreGLFBORTT_H__ -#define __OgreGLFBORTT_H__ - -#include "OgreGLCopyingRenderTexture.h" -#include "OgreGLContext.h" -#include "OgreGLFrameBufferObject.h" - -/// Extra GL constants -#define GL_DEPTH24_STENCIL8_EXT 0x88F0 - - -namespace Ogre { - class GLFBOManager; - - /** RenderTexture for GL FBO - */ - class _OgreGLExport GLFBORenderTexture: public GLRenderTexture - { - public: - GLFBORenderTexture(GLFBOManager *manager, const String &name, const GLSurfaceDesc &target, bool writeGamma, uint fsaa); - - void getCustomAttribute(const String& name, void* pData) override; - - /// Override needed to deal with multisample buffers - void swapBuffers() override; - - /// Override so we can attach the depth buffer to the FBO - bool attachDepthBuffer( DepthBuffer *depthBuffer ) override; - void detachDepthBuffer() override; - void _detachDepthBuffer() override; - - GLContext* getContext() const override { return mFB.getContext(); } - GLFrameBufferObjectCommon* getFBO() override { return &mFB; } - protected: - GLFrameBufferObject mFB; - }; - - /** Factory for GL Frame Buffer Objects, and related things. - */ - class _OgreGLExport GLFBOManager: public GLRTTManager - { - public: - GLFBOManager(bool atimode); - ~GLFBOManager(); - - /** Bind a certain render target if it is a FBO. If it is not a FBO, bind the - main frame buffer. - */ - void bind(RenderTarget *target) override; - - /** Unbind a certain render target. No-op for FBOs. - */ - void unbind(RenderTarget *target) override {}; - - /** Get best depth and stencil supported for given internalFormat - */ - void getBestDepthStencil(PixelFormat internalFormat, GLenum *depthFormat, GLenum *stencilFormat) override; - - GLFBORenderTexture *createRenderTexture(const String &name, - const GLSurfaceDesc &target, bool writeGamma, uint fsaa) override; - - /** Request a render buffer. If format is GL_NONE, return a zero buffer. - */ - GLSurfaceDesc requestRenderBuffer(GLenum format, uint32 width, uint32 height, uint fsaa); - /** Get a FBO without depth/stencil for temporary use, like blitting between textures. - */ - GLuint getTemporaryFBO() { return mTempFBO; } - private: - /** Temporary FBO identifier - */ - GLuint mTempFBO; - - /// Buggy ATI driver? - bool mATIMode; - - /** Detect allowed FBO formats */ - void detectFBOFormats(); - GLuint _tryFormat(GLenum depthFormat, GLenum stencilFormat); - bool _tryPackedFormat(GLenum packedFormat); - void _createTempFramebuffer(GLuint internalfmt, GLuint fmt, GLenum type, GLuint &fb, GLuint &tid); - }; - - -} - -#endif diff --git a/RenderSystems/GL/include/OgreGLFrameBufferObject.h b/RenderSystems/GL/include/OgreGLFrameBufferObject.h deleted file mode 100644 index e4cd98202f2..00000000000 --- a/RenderSystems/GL/include/OgreGLFrameBufferObject.h +++ /dev/null @@ -1,68 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OgreGLFBO_H__ -#define __OgreGLFBO_H__ - -#include "OgreGLCopyingRenderTexture.h" -#include "OgreGLContext.h" - -namespace Ogre { - - /** Frame Buffer Object abstraction. - */ - class _OgreGLExport GLFrameBufferObject : public GLFrameBufferObjectCommon - { - public: - GLFrameBufferObject(GLFBOManager *manager, uint fsaa); - ~GLFrameBufferObject(); - - bool bind(bool recreateIfNeeded) override; - - /** Swap buffers - only useful when using multisample buffers. - */ - void swapBuffers(); - - /** This function acts very similar to @see GLFBORenderTexture::attachDepthBuffer - The difference between D3D & OGL is that D3D setups the DepthBuffer before rendering, - while OGL setups the DepthBuffer per FBO. So the DepthBuffer (RenderBuffer) needs to - be attached for OGL. - */ - void attachDepthBuffer( DepthBuffer *depthBuffer ); - void detachDepthBuffer(); - - GLFBOManager *getManager() { return mManager; } - private: - GLFBOManager *mManager; - GLSurfaceDesc mMultisampleColourBuffer; - - void initialise() override; - }; - -} - -#endif diff --git a/RenderSystems/GL/include/OgreGLGpuNvparseProgram.h b/RenderSystems/GL/include/OgreGLGpuNvparseProgram.h deleted file mode 100644 index 0d608b02971..00000000000 --- a/RenderSystems/GL/include/OgreGLGpuNvparseProgram.h +++ /dev/null @@ -1,61 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLGpuNvparseProgram_H__ -#define __GLGpuNvparseProgram_H__ - -#include "OgreGLPrerequisites.h" -#include "OgreGLGpuProgram.h" - -namespace Ogre { - -class _OgreGLExport GLGpuNvparseProgram : public GLGpuProgram -{ -public: - GLGpuNvparseProgram(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader); - virtual ~GLGpuNvparseProgram(); - - - /// Execute the binding functions for this program - void bindProgram(void) override; - /// Execute the unbinding functions for this program - void unbindProgram(void) override; - /// Execute the param binding functions for this program - void bindProgramParameters(GpuProgramParametersSharedPtr params, uint16 mask) override; - -protected: - /// @copydoc Resource::unload - void unloadImpl(void) override; - void loadFromSource(void) override; -}; - -} // namespace Ogre - -#endif // __GLGpuNvparseProgram_H__ diff --git a/RenderSystems/GL/include/OgreGLGpuProgram.h b/RenderSystems/GL/include/OgreGLGpuProgram.h deleted file mode 100644 index a119fe4a321..00000000000 --- a/RenderSystems/GL/include/OgreGLGpuProgram.h +++ /dev/null @@ -1,92 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLGpuProgram_H__ -#define __GLGpuProgram_H__ - -#include "OgreGLPrerequisites.h" -#include "OgreGpuProgram.h" -#include "OgreHardwareVertexBuffer.h" - -namespace Ogre { - - struct GLGpuProgramBase - { - virtual ~GLGpuProgramBase() {} - /// Execute the binding functions for this program - virtual void bindProgram(void) = 0; - /// Execute the binding functions for this program - virtual void unbindProgram(void) = 0; - /// Execute the param binding functions for this program - virtual void bindProgramParameters(GpuProgramParametersSharedPtr params, uint16 mask) = 0; - /// Test whether attribute index for a given semantic is valid - virtual bool isAttributeValid(VertexElementSemantic semantic, uint index); - }; - - /** Generalised low-level GL program, can be applied to multiple types (eg ARB and NV) */ - class _OgreGLExport GLGpuProgram : public GpuProgram, public GLGpuProgramBase - { - public: - GLGpuProgram(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual = false, ManualResourceLoader* loader = 0); - virtual ~GLGpuProgram(); - protected: - - GLuint mProgramID; - }; - - /** Specialisation of the GL low-level program for ARB programs. */ - class _OgreGLExport GLArbGpuProgram : public GLGpuProgram - { - public: - GLArbGpuProgram(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual = false, ManualResourceLoader* loader = 0); - virtual ~GLArbGpuProgram(); - - /// Execute the binding functions for this program - void bindProgram(void) override; - /// Execute the unbinding functions for this program - void unbindProgram(void) override; - /// Execute the param binding functions for this program - void bindProgramParameters(GpuProgramParametersSharedPtr params, uint16 mask) override; - - /// Get the GL type for the program - GLenum getProgramType(void) const; - - protected: - void loadFromSource(void) override; - /// @copydoc Resource::unloadImpl - void unloadImpl(void) override; - - }; - - - -} // namespace Ogre - -#endif // __GLGpuProgram_H__ diff --git a/RenderSystems/GL/include/OgreGLGpuProgramManager.h b/RenderSystems/GL/include/OgreGLGpuProgramManager.h deleted file mode 100644 index 8bc13f40cfc..00000000000 --- a/RenderSystems/GL/include/OgreGLGpuProgramManager.h +++ /dev/null @@ -1,69 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLGpuProgramManager_H__ -#define __GLGpuProgramManager_H__ - -#include "OgreGLPrerequisites.h" -#include "OgreGpuProgramManager.h" - -namespace Ogre { - -typedef GpuProgram* (*CreateGpuProgramCallback)(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - GpuProgramType gptype, const String& syntaxCode); - -struct CreateCallbackWrapper : public GpuProgramFactory -{ - String language; - CreateGpuProgramCallback callback; - const String& getLanguage(void) const override { return language; }; - GpuProgram* create(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) override - { - // type and syntax code will be corrected by GpuProgramManager - return callback(creator, name, handle, group, isManual, loader, GPT_VERTEX_PROGRAM, ""); - } - CreateCallbackWrapper(const String& lang, CreateGpuProgramCallback cb) : language(lang), callback(cb) {} -}; - -class GLGpuProgramManager -{ - std::list mFactories; -public: - void registerProgramFactory(const String& syntaxCode, CreateGpuProgramCallback createFn) - { - mFactories.emplace_back(syntaxCode, createFn); - GpuProgramManager::getSingleton().addFactory(&mFactories.back()); - } -}; - -} //namespace Ogre - -#endif //__GLGpuProgramManager_H__ diff --git a/RenderSystems/GL/include/OgreGLHardwareBuffer.h b/RenderSystems/GL/include/OgreGLHardwareBuffer.h deleted file mode 100644 index 11cf3d8278b..00000000000 --- a/RenderSystems/GL/include/OgreGLHardwareBuffer.h +++ /dev/null @@ -1,71 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLHARDWAREVERTEXBUFFER_H__ -#define __GLHARDWAREVERTEXBUFFER_H__ - -#include "OgreGLPrerequisites.h" -#include "OgreHardwareBuffer.h" - -namespace Ogre { - - /// Specialisation of HardwareVertexBuffer for OpenGL - class _OgreGLExport GLHardwareVertexBuffer : public HardwareBuffer - { - private: - GLenum mTarget; - GLuint mBufferId; - // Scratch buffer handling - bool mLockedToScratch; - size_t mScratchOffset; - size_t mScratchSize; - void* mScratchPtr; - bool mScratchUploadOnUnlock; - GLRenderSystem* mRenderSystem; - - protected: - /** See HardwareBuffer. */ - void* lockImpl(size_t offset, size_t length, LockOptions options) override; - /** See HardwareBuffer. */ - void unlockImpl(void) override; - public: - GLHardwareVertexBuffer(GLenum target, size_t sizeInBytes, Usage usage, bool useShadowBuffer); - ~GLHardwareVertexBuffer(); - /** See HardwareBuffer. */ - void readData(size_t offset, size_t length, void* pDest) override; - /** See HardwareBuffer. */ - void writeData(size_t offset, size_t length, - const void* pSource, bool discardWholeBuffer = false) override; - /** See HardwareBuffer. */ - void _updateFromShadow(void) override; - - GLuint getGLBufferId(void) const { return mBufferId; } - }; - typedef GLHardwareVertexBuffer GLHardwareBuffer; - -} -#endif // __GLHARDWAREVERTEXBUFFER_H__ diff --git a/RenderSystems/GL/include/OgreGLHardwareBufferManager.h b/RenderSystems/GL/include/OgreGLHardwareBufferManager.h deleted file mode 100644 index 00fc73c8163..00000000000 --- a/RenderSystems/GL/include/OgreGLHardwareBufferManager.h +++ /dev/null @@ -1,87 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLHARWAREBUFFERMANAGER_H__ -#define __GLHARWAREBUFFERMANAGER_H__ - -#include "OgreGLPrerequisites.h" -#include "OgreHardwareBufferManager.h" - -namespace Ogre { - - class GLStateCacheManager; - -// Default threshold at which glMapBuffer becomes more efficient than glBufferSubData (32k?) -# define OGRE_GL_DEFAULT_MAP_BUFFER_THRESHOLD (1024 * 32) - - /** Implementation of HardwareBufferManager for OpenGL. */ - class _OgreGLExport GLHardwareBufferManager : public HardwareBufferManager - { - protected: - GLRenderSystem* mRenderSystem; - char* mScratchBufferPool; - OGRE_MUTEX(mScratchMutex); - size_t mMapBufferThreshold; - - public: - GLHardwareBufferManager(); - ~GLHardwareBufferManager(); - /// Creates a vertex buffer - HardwareVertexBufferSharedPtr createVertexBuffer(size_t vertexSize, - size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer = false) override; - /// Create a hardware vertex buffer - HardwareIndexBufferSharedPtr createIndexBuffer( - HardwareIndexBuffer::IndexType itype, size_t numIndexes, - HardwareBuffer::Usage usage, bool useShadowBuffer = false) override; - /// Create a render to vertex buffer - RenderToVertexBufferSharedPtr createRenderToVertexBuffer() override; - /// Utility function to get the correct GL usage based on HBU's - static GLenum getGLUsage(unsigned int usage); - - /// Utility function to get the correct GL type based on VET's - static GLenum getGLType(unsigned int type); - - /** Allocator method to allow us to use a pool of memory as a scratch - area for hardware buffers. This is because glMapBuffer is incredibly - inefficient, seemingly no matter what options we give it. So for the - period of lock/unlock, we will instead allocate a section of a local - memory pool, and use glBufferSubDataARB / glGetBufferSubDataARB - instead. - */ - void* allocateScratch(uint32 size); - - /// @see allocateScratch - void deallocateScratch(void* ptr); - - /** Threshold after which glMapBuffer is used and not glBufferSubData - */ - size_t getGLMapBufferThreshold() const; - void setGLMapBufferThreshold( const size_t value ); - }; -} - -#endif // __GLHARWAREBUFFERMANAGER_H__ diff --git a/RenderSystems/GL/include/OgreGLHardwareOcclusionQuery.h b/RenderSystems/GL/include/OgreGLHardwareOcclusionQuery.h deleted file mode 100644 index 99ed559d233..00000000000 --- a/RenderSystems/GL/include/OgreGLHardwareOcclusionQuery.h +++ /dev/null @@ -1,108 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -/* -The nVidia occlusion query extension is defined in glext.h so you don't -need anything else. You do need to look up the function, we provide a -GLSupport class to do this, which has platform implementations for -getProcAddress. Check the way that extensions like glActiveTextureARB are -initialised and used in glRenderSystem and copy what is done there. - - - - To do: fix so dx7 and DX9 checks and flags if HW Occlusion is supported - See the openGl dito for ideas what to do. - -*/ - - - -//GL_ActiveTextureARB_Func* glActiveTextureARB_ptr = (GL_ActiveTextureARB_Func)mGLSupport->getProcAddress("glActiveTextureARB"); - -#ifndef __GLHARDWAREOCCLUSIONQUERY_H__ -#define __GLHARDWAREOCCLUSIONQUERY_H__ - -#include "OgreGLPrerequisites.h" -#include "OgreHardwareOcclusionQuery.h" - - -namespace Ogre { - - -// If you use multiple rendering passes you can test only the first pass and all other passes don't have to be rendered -// if the first pass result has too few pixels visible. - -// Be sure to render all occluder first and whats out so the RenderQue don't switch places on -// the occluding objects and the tested objects because it thinks it's more effective.. - - -/** - * This is a class that is the base class of the query class for - * hardware occlusion. - * - * @author Lee Sandberg email: lee@abcmedia.se - * Updated on 13/9/2005 by Tuan Kuranes email: tuan.kuranes@free.fr - */ - -class _OgreGLExport GLHardwareOcclusionQuery : public HardwareOcclusionQuery -{ -//---------------------------------------------------------------------- -// Public methods -//-- -public: - /** - * Default object constructor - * - */ - GLHardwareOcclusionQuery(); - /** - * Object destructor - */ - ~GLHardwareOcclusionQuery(); - - //------------------------------------------------------------------ - // Occlusion query functions (see base class documentation for this) - //-- - void beginOcclusionQuery() override; - void endOcclusionQuery() override; - bool pullOcclusionQuery( unsigned int* NumOfFragments) override; - bool isStillOutstanding(void) override; - - - //---------------------------------------------------------------------- - // private members - //-- - private: - - GLuint mQueryID; -}; - -} - -#endif - diff --git a/RenderSystems/GL/include/OgreGLHardwarePixelBuffer.h b/RenderSystems/GL/include/OgreGLHardwarePixelBuffer.h deleted file mode 100644 index 2739ba7355d..00000000000 --- a/RenderSystems/GL/include/OgreGLHardwarePixelBuffer.h +++ /dev/null @@ -1,92 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLPIXELBUFFER_H__ -#define __GLPIXELBUFFER_H__ - -#include "OgreGLPrerequisites.h" -#include "OgreGLHardwarePixelBufferCommon.h" - -namespace Ogre { - /** Texture surface. - */ - class GLTextureBuffer: public GLHardwarePixelBufferCommon - { - public: - /** Texture constructor */ - GLTextureBuffer(GLRenderSystem* renderSystem, GLTexture* parent, GLint face, GLint level, - uint32 mWidth, uint32 mHeight, uint32 mDepth); - ~GLTextureBuffer(); - - void bindToFramebuffer(uint32 attachment, uint32 zoffset) override; - /// @copydoc HardwarePixelBuffer::getRenderTarget - RenderTexture* getRenderTarget(size_t slice); - /// Upload a box of pixels to this buffer on the card - void upload(const PixelBox &data, const Box &dest) override; - /// Download a box of pixels from the card - void download(const PixelBox &data) override; - - /// Hardware implementation of blitFromMemory - void blitFromMemory(const PixelBox &src_orig, const Box &dstBox) override; - - /// Copy from framebuffer - void copyFromFramebuffer(uint32 zoffset); - /// @copydoc HardwarePixelBuffer::blit - void blit(const HardwarePixelBufferSharedPtr &src, const Box &srcBox, const Box &dstBox) override; - void blitToMemory(const Box &srcBox, const PixelBox &dst) override; - protected: - /// Blitting implementation - void blitFromTexture(GLTextureBuffer *src, const Box &srcBox, const Box &dstBox); - void _blitFromMemory(const PixelBox &src, const Box &dst); - - // In case this is a texture level - GLenum mTarget; - GLenum mFaceTarget; // same as mTarget in case of GL_TEXTURE_xD, but cubemap face for cubemaps - GLuint mTextureID; - GLint mLevel; - bool mHwGamma; - - GLRenderSystem* mRenderSystem; - }; - /** Renderbuffer surface. Needs FBO extension. - */ - class GLRenderBuffer: public GLHardwarePixelBufferCommon - { - void blitFromMemory(const PixelBox& src, const Box& dstBox) override { OgreAssertDbg(false, "Not supported"); } - void blitToMemory(const Box& srcBox, const PixelBox& dst) override { OgreAssertDbg(false, "Not supported"); } - public: - GLRenderBuffer(GLenum format, uint32 width, uint32 height, GLsizei numSamples); - ~GLRenderBuffer(); - - void bindToFramebuffer(uint32 attachment, uint32 zoffset) override; - protected: - /// In case this is a render buffer - GLuint mRenderbufferID; - }; -} - -#endif diff --git a/RenderSystems/GL/include/OgreGLPBRenderTexture.h b/RenderSystems/GL/include/OgreGLPBRenderTexture.h deleted file mode 100644 index b5585d041d3..00000000000 --- a/RenderSystems/GL/include/OgreGLPBRenderTexture.h +++ /dev/null @@ -1,106 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLPBRENDERTEXTURE_H__ -#define __GLPBRENDERTEXTURE_H__ - -#include "OgreGLCopyingRenderTexture.h" -#include "OgreGLPBuffer.h" -namespace Ogre { - - /** RenderTexture that uses a PBuffer (offscreen rendering context) for rendering. - */ - class GLPBRTTManager; - class _OgreGLExport GLPBRenderTexture: public GLRenderTexture - { - public: - GLPBRenderTexture(GLPBRTTManager *manager, const String &name, const GLSurfaceDesc &target, bool writeGamma, uint fsaa); - virtual ~GLPBRenderTexture(); - - void getCustomAttribute(const String& name, void* pData) override; - - GLContext* getContext() const override; - protected: - GLPBRTTManager *mManager; - PixelComponentType mPBFormat; - }; - - /** Manager for rendertextures and PBuffers (offscreen rendering contexts) - */ - class _OgreGLExport GLPBRTTManager: public GLRTTManager - { - public: - GLPBRTTManager(GLNativeSupport *support, RenderTarget *mainwindow); - virtual ~GLPBRTTManager(); - - RenderTexture *createRenderTexture(const String &name, - const GLSurfaceDesc &target, bool writeGamma, uint fsaa) override; - - /** @copydoc GLRTTManager::checkFormat - */ - virtual bool checkFormat(PixelFormat format); - - /** @copydoc GLRTTManager::bind - */ - void bind(RenderTarget *target) override; - - /** @copydoc GLRTTManager::unbind - */ - void unbind(RenderTarget *target) override; - - /** Create PBuffer for a certain pixel format and size - */ - void requestPBuffer(PixelComponentType ctype, uint32 width, uint32 height); - - /** Release PBuffer for a certain pixel format - */ - void releasePBuffer(PixelComponentType ctype); - - /** Get GL rendering context for a certain component type and size. - */ - GLContext *getContextFor(PixelComponentType ctype, uint32 width, uint32 height); - protected: - /** GLSupport reference, used to create PBuffers */ - GLNativeSupport *mSupport; - /** Primary window reference */ - RenderTarget *mMainWindow; - /** Primary window context */ - GLContext *mMainContext; - /** Reference to a PBuffer, with refcount */ - struct PBRef - { - PBRef(): pb(0),refcount(0) {} - GLPBuffer* pb; - size_t refcount; - }; - /** Type to map each component type to a PBuffer */ - PBRef mPBuffers[PCT_COUNT]; - }; -} - -#endif // __GLPBRENDERTEXTURE_H__ diff --git a/RenderSystems/GL/include/OgreGLPixelFormat.h b/RenderSystems/GL/include/OgreGLPixelFormat.h deleted file mode 100644 index 7f6348beafb..00000000000 --- a/RenderSystems/GL/include/OgreGLPixelFormat.h +++ /dev/null @@ -1,75 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLPIXELFORMAT_H__ -#define __GLPIXELFORMAT_H__ - -#include "OgreGLPrerequisites.h" -#include "OgrePixelFormat.h" -namespace Ogre { - - /** - * Class to do pixel format mapping between GL and OGRE - */ - class _OgreGLExport GLPixelUtil - { - public: - /** Takes the OGRE pixel format and returns the appropriate GL one - @return a GLenum describing the format, or 0 if there is no exactly matching - one (and conversion is needed) - */ - static GLenum getGLOriginFormat(PixelFormat mFormat); - - /** Takes the OGRE pixel format and returns type that must be provided - to GL as data type for reading it into the GPU - @return a GLenum describing the data type, or 0 if there is no exactly matching - one (and conversion is needed) - */ - static GLenum getGLOriginDataType(PixelFormat mFormat); - - /** Takes the OGRE pixel format and returns the type that must be provided - to GL as internal format. GL_NONE if no match exists. - @param mFormat The pixel format - @param hwGamma Whether a hardware gamma-corrected version is requested - */ - static GLenum getGLInternalFormat(PixelFormat mFormat, bool hwGamma = false); - - /** Function to get the closest matching OGRE format to an internal GL format. To be - precise, the format will be chosen that is most efficient to transfer to the card - without losing precision. - @remarks It is valid for this function to always return PF_A8R8G8B8. - */ - static PixelFormat getClosestOGREFormat(GLenum fmt); - - /** Returns next power-of-two size if required by render system, in case - RSC_NON_POWER_OF_2_TEXTURES is supported it returns value as-is. - */ - static uint32 optionalPO2(uint32 value); - }; -} - -#endif diff --git a/RenderSystems/GL/include/OgreGLPlugin.h b/RenderSystems/GL/include/OgreGLPlugin.h deleted file mode 100644 index fe4c54c0283..00000000000 --- a/RenderSystems/GL/include/OgreGLPlugin.h +++ /dev/null @@ -1,64 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLPlugin_H__ -#define __GLPlugin_H__ - -#include "OgrePlugin.h" -#include "OgreGLPrerequisites.h" - -namespace Ogre -{ - class GLRenderSystem; - - /** Plugin instance for GL Manager */ - class _OgreGLExport GLPlugin : public Plugin - { - public: - GLPlugin(); - - - /// @copydoc Plugin::getName - const String& getName() const override; - - /// @copydoc Plugin::install - void install() override; - - /// @copydoc Plugin::initialise - void initialise() override; - - /// @copydoc Plugin::shutdown - void shutdown() override; - - /// @copydoc Plugin::uninstall - void uninstall() override; - protected: - GLRenderSystem* mRenderSystem; - }; -} - -#endif diff --git a/RenderSystems/GL/include/OgreGLPrerequisites.h b/RenderSystems/GL/include/OgreGLPrerequisites.h deleted file mode 100644 index 18331d0e1c2..00000000000 --- a/RenderSystems/GL/include/OgreGLPrerequisites.h +++ /dev/null @@ -1,98 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLPrerequisites_H__ -#define __GLPrerequisites_H__ - -#include "OgrePrerequisites.h" - -namespace Ogre { - // Forward declarations - class GLNativeSupport; - class GLRenderSystem; - class GLTexture; - class GLTextureManager; - struct GLGpuProgramBase; - class GLGpuProgram; - class GLContext; - class GLRTTManager; - class GLFBOManager; - class GLHardwarePixelBuffer; - class GLRenderBuffer; - - typedef shared_ptr GLGpuProgramPtr; - typedef shared_ptr GLTexturePtr; -} - -#if (OGRE_PLATFORM == OGRE_PLATFORM_WIN32) -# ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN 1 -# endif -# ifndef NOMINMAX -# define NOMINMAX // required to stop windows.h messing up std::min -# endif -#endif - -#include - -namespace Ogre { - inline const char* glErrorToString(GLenum glErr) { - switch(glErr) - { - case GL_INVALID_ENUM: - return "GL_INVALID_ENUM"; - case GL_INVALID_VALUE: - return "GL_INVALID_VALUE"; - case GL_INVALID_OPERATION: - return "GL_INVALID_OPERATION"; - case GL_INVALID_FRAMEBUFFER_OPERATION_EXT: - return "GL_INVALID_FRAMEBUFFER_OPERATION"; - case GL_OUT_OF_MEMORY: - return "GL_OUT_OF_MEMORY"; - default: - return ""; - } - } -} - -#if (OGRE_PLATFORM == OGRE_PLATFORM_WIN32) && !defined(__MINGW32__) && !defined(OGRE_STATIC_LIB) -# ifdef OGRE_GLPLUGIN_EXPORTS -# define _OgreGLExport __declspec(dllexport) -# else -# if defined( __MINGW32__ ) -# define _OgreGLExport -# else -# define _OgreGLExport __declspec(dllimport) -# endif -# endif -#elif defined ( OGRE_GCC_VISIBILITY ) -# define _OgreGLExport __attribute__ ((visibility("default"))) -#else -# define _OgreGLExport -#endif - -#endif //#ifndef __GLPrerequisites_H__ diff --git a/RenderSystems/GL/include/OgreGLRenderSystem.h b/RenderSystems/GL/include/OgreGLRenderSystem.h deleted file mode 100644 index 7b01bb8821b..00000000000 --- a/RenderSystems/GL/include/OgreGLRenderSystem.h +++ /dev/null @@ -1,292 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLRenderSystem_H__ -#define __GLRenderSystem_H__ - -#include "OgreGLPrerequisites.h" -#include "OgrePlatform.h" -#include "OgreRenderSystem.h" -#include "OgreGLHardwareBufferManager.h" -#include "OgreGLGpuProgramManager.h" -#include "OgreVector.h" - -#include "OgreGLRenderSystemCommon.h" -#include "OgreGLStateCacheManager.h" - -namespace Ogre { - /** \addtogroup RenderSystems RenderSystems - * @{ - */ - /** \defgroup GL GL - * Implementation of GL as a rendering system. - * @{ - */ - - namespace GLSL { - class GLSLProgramFactory; - } - - /** - Implementation of GL as a rendering system. - */ - class _OgreGLExport GLRenderSystem : public GLRenderSystemCommon - { - private: - /// View matrix to set world against - Matrix4 mViewMatrix; - Matrix4 mWorldMatrix; - Matrix4 mTextureMatrix; - - /// Last min & mip filtering options, so we can combine them - FilterOptions mMinFilter; - FilterOptions mMipFilter; - - /// What texture coord set each texture unit is using - size_t mTextureCoordIndex[OGRE_MAX_TEXTURE_LAYERS]; - - /// Holds texture type settings for every stage - GLenum mTextureTypes[OGRE_MAX_TEXTURE_LAYERS]; - - /// Saved manual colour blends - ColourValue mManualBlendColours[OGRE_MAX_TEXTURE_LAYERS][2]; - - /// Number of fixed-function texture units - unsigned short mFixedFunctionTextureUnits; - - void setGLLight(size_t index, bool lt); - void makeGLMatrix(GLfloat gl_matrix[16], const Matrix4& m); - - GLint getBlendMode(SceneBlendFactor ogreBlend) const; - GLint getTextureAddressingMode(TextureAddressingMode tam) const; - void initialiseContext(RenderWindow* primary); - - /// Store last stencil mask state - uint32 mStencilWriteMask; - /// Store last depth write state - bool mDepthWrite; - - GLint convertCompareFunction(CompareFunction func) const; - GLint convertStencilOp(StencilOperation op, bool invert = false) const; - - bool mUseAutoTextureMatrix; - GLfloat mAutoTextureMatrix[16]; - - /// Check if the GL system has already been initialised - bool mGLInitialised; - - HardwareBufferManager* mHardwareBufferManager; - GLGpuProgramManager* mGpuProgramManager; - GLSL::GLSLProgramFactory* mGLSLProgramFactory; - - unsigned short mCurrentLights; - - GLGpuProgramBase* mCurrentVertexProgram; - GLGpuProgramBase* mCurrentFragmentProgram; - GLGpuProgramBase* mCurrentGeometryProgram; - - // statecaches are per context - GLStateCacheManager* mStateCacheManager; - - ushort mActiveTextureUnit; - ushort mMaxBuiltInTextureAttribIndex; - - // local data members of _render that were moved here to improve performance - // (save allocations) - std::vector mRenderAttribsBound; - std::vector mRenderInstanceAttribsBound; - - /// is fixed pipeline enabled - bool mEnableFixedPipeline; - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - /// @copydoc RenderSystem::setDrawBuffer - virtual bool setDrawBuffer(ColourBufferType colourBuffer); -#endif - - protected: - void setClipPlanesImpl(const PlaneList& clipPlanes) override; - void bindVertexElementToGpu(const VertexElement& elem, - const HardwareVertexBufferSharedPtr& vertexBuffer, - const size_t vertexStart) override; - - /** Initialises GL extensions, must be done AFTER the GL context has been - established. - */ - void initialiseExtensions(); - public: - // Default constructor / destructor - GLRenderSystem(); - ~GLRenderSystem(); - - // ---------------------------------- - // Overridden RenderSystem functions - // ---------------------------------- - - const GpuProgramParametersPtr& getFixedFunctionParams(TrackVertexColourType tracking, FogMode fog) override; - - void applyFixedFunctionParams(const GpuProgramParametersPtr& params, uint16 variabilityMask) override; - - const String& getName(void) const override; - - void _initialise() override; - - void initConfigOptions() override; - - RenderSystemCapabilities* createRenderSystemCapabilities() const override; - - void initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary) override; - - void shutdown(void) override; - - void setShadingType(ShadeOptions so) override; - - void setLightingEnabled(bool enabled) override; - - RenderWindow* _createRenderWindow(const String &name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams = 0) override; - - DepthBuffer* _createDepthBufferFor( RenderTarget *renderTarget ) override; - - MultiRenderTarget * createMultiRenderTarget(const String & name) override; - - - void destroyRenderWindow(const String& name) override; - - void setNormaliseNormals(bool normalise) override; - - // ----------------------------- - // Low-level overridden members - // ----------------------------- - - void _useLights(unsigned short limit) override; - - void setWorldMatrix(const Matrix4 &m); - - void setViewMatrix(const Matrix4 &m); - - void setProjectionMatrix(const Matrix4 &m); - - void _setSurfaceTracking(TrackVertexColourType tracking); - - void _setPointParameters(bool attenuationEnabled, Real minSize, Real maxSize) override; - - void _setLineWidth(float width) override; - - void _setPointSpritesEnabled(bool enabled) override; - - void _setTexture(size_t unit, bool enabled, const TexturePtr &tex) override; - - void _setSampler(size_t unit, Sampler& sampler) override; - - void _setTextureCoordSet(size_t stage, size_t index) override; - - void _setTextureCoordCalculation(size_t stage, TexCoordCalcMethod m, - const Frustum* frustum = 0) override; - - void _setTextureBlendMode(size_t stage, const LayerBlendModeEx& bm) override; - - void _setTextureMatrix(size_t stage, const Matrix4& xform) override; - - void _setAlphaRejectSettings(CompareFunction func, unsigned char value, bool alphaToCoverage) override; - - void _setViewport(Viewport *vp) override; - - void _endFrame(void) override; - - void _setCullingMode(CullingMode mode) override; - - void _setDepthBufferParams(bool depthTest = true, bool depthWrite = true, CompareFunction depthFunction = CMPF_LESS_EQUAL) override; - - void _setDepthBias(float constantBias, float slopeScaleBias) override; - - void setColourBlendState(const ColourBlendState& state) override; - - void _setFog(FogMode mode); - - void setClipPlane (ushort index, Real A, Real B, Real C, Real D); - - void enableClipPlane (ushort index, bool enable); - - void _setPolygonMode(PolygonMode level) override; - - void setStencilState(const StencilState& state) override; - - void _render(const RenderOperation& op) override; - - void bindGpuProgram(GpuProgram* prg) override; - - void unbindGpuProgram(GpuProgramType gptype) override; - - void bindGpuProgramParameters(GpuProgramType gptype, - const GpuProgramParametersPtr& params, uint16 variabilityMask) override; - - void setScissorTest(bool enabled, const Rect& rect = Rect()) override ; - void clearFrameBuffer(unsigned int buffers, - const ColourValue& colour = ColourValue::Black, - float depth = 1.0f, unsigned short stencil = 0) override; - HardwareOcclusionQuery* createHardwareOcclusionQuery(void) override; - - // ---------------------------------- - // GLRenderSystem specific members - // ---------------------------------- - void _oneTimeContextInitialization() override; - /** Switch GL context, dealing with involved internal cached states too - */ - void _switchContext(GLContext *context); - /** - * Set current render target to target, enabling its GL context if needed - */ - void _setRenderTarget(RenderTarget *target) override; - /** Unregister a render target->context mapping. If the context of target - is the current context, change the context to the main context so it - can be destroyed safely. - - @note This is automatically called by the destructor of - GLContext. - */ - void _unregisterContext(GLContext *context) override; - - GLStateCacheManager * _getStateCacheManager() { return mStateCacheManager; } - - /// @copydoc RenderSystem::beginProfileEvent - void beginProfileEvent( const String &eventName ) override; - - /// @copydoc RenderSystem::endProfileEvent - void endProfileEvent( void ) override; - - /// @copydoc RenderSystem::markProfileEvent - void markProfileEvent( const String &eventName ) override; - - /** @copydoc RenderTarget::copyContentsToMemory */ - void _copyContentsToMemory(Viewport* vp, const Box& src, const PixelBox &dst, RenderWindow::FrameBuffer buffer) override; - }; - /** @} */ - /** @} */ -} -#endif - diff --git a/RenderSystems/GL/include/OgreGLRenderToVertexBuffer.h b/RenderSystems/GL/include/OgreGLRenderToVertexBuffer.h deleted file mode 100644 index 0f08b014b18..00000000000 --- a/RenderSystems/GL/include/OgreGLRenderToVertexBuffer.h +++ /dev/null @@ -1,54 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLRenderToVertexBuffer_H__ -#define __GLRenderToVertexBuffer_H__ - -#include "OgreGLRenderToVertexBufferCommon.h" -#include "OgreGLPrerequisites.h" - -namespace Ogre { - class GLRenderToVertexBuffer : public GLRenderToVertexBufferCommon - { - public: - /** C'tor */ - GLRenderToVertexBuffer(); - /** D'tor */ - virtual ~GLRenderToVertexBuffer(); - - /** - Update the contents of this vertex buffer by rendering - */ - void update(SceneManager* sceneMgr) override; - protected: - void bindVerticesOutput(Pass* pass); - GLint getGLSemanticType(VertexElementSemantic semantic); - GLuint mPrimitivesDrawnQuery; - }; -} - -#endif diff --git a/RenderSystems/GL/include/OgreGLStateCacheManager.h b/RenderSystems/GL/include/OgreGLStateCacheManager.h deleted file mode 100644 index d061ceb8592..00000000000 --- a/RenderSystems/GL/include/OgreGLStateCacheManager.h +++ /dev/null @@ -1,217 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLStateCacheManager_H__ -#define __GLStateCacheManager_H__ - -#include "OgreGLPrerequisites.h" -#include "OgreGLStateCacheManagerCommon.h" -#include "OgreStdHeaders.h" - -namespace Ogre -{ - class _OgreGLExport GLStateCacheManager : public GLStateCacheManagerCommon - { - protected: - /* These variables are used for caching OpenGL state. - They are cached because state changes can be quite expensive, - which is especially important on mobile or embedded systems. - */ - - struct TexGenParams - { - std::set mEnabled; - }; - /// Stores the currently enabled texcoord generation types per texture unit - std::unordered_map mTextureCoordGen; - - /// Stores the current polygon rendering mode - GLenum mPolygonMode; - /// Stores the last bound texture id - GLuint mLastBoundTexID; - - GLenum mShadeModel; - - GLfloat mAmbient[4]; - GLfloat mDiffuse[4]; - GLfloat mSpecular[4]; - GLfloat mEmissive[4]; - GLfloat mLightAmbient[4]; - GLfloat mShininess; - - GLfloat mPointAttenuation[3]; - GLfloat mPointSize; - GLfloat mPointSizeMin; - GLfloat mPointSizeMax; - public: - GLStateCacheManager(void); - - /// See GLStateCacheManager.initializeCache. - void initializeCache(); - - /** Clears all cached values - */ - void clearCache(); - - /** Bind an OpenGL buffer of any type. - @param target The buffer target. - @param buffer The buffer ID. - */ - void bindGLBuffer(GLenum target, GLuint buffer); - - /** Delete an OpenGL buffer of any type. - @param target The buffer target. - @param buffer The buffer ID. - */ - void deleteGLBuffer(GLenum target, GLuint buffer); - - /** Bind an OpenGL texture of any type. - @param target The texture target. - @param texture The texture ID. - */ - void bindGLTexture(GLenum target, GLuint texture); - - /** Invalidates the state associated with a particular texture ID. - @param texture The texture ID. - */ - void invalidateStateForTexture(GLuint texture); - - /** Sets an integer parameter value per texture target. - @param target The texture target. - @param pname The parameter name. - @param param The parameter value. - */ - void setTexParameteri(GLenum target, GLenum pname, GLint param); - - /** Activate an OpenGL texture unit. - @param unit The texture unit to activate. - @return Whether or not the texture unit was successfully activated. - */ - bool activateGLTextureUnit(size_t unit); - - /// Set the blend equation for RGB and alpha separately. - void setBlendEquation(GLenum eqRGB, GLenum eqA); - - /// Set the blend function for RGB and alpha separately. - void setBlendFunc(GLenum source, GLenum dest, GLenum sourceA, GLenum destA); - - void setShadeModel(GLenum model); - - void setLightAmbient(GLfloat r, GLfloat g, GLfloat b); - - /** Sets the current depth mask setting. - @param mask The depth mask to use. - */ - void setDepthMask(GLboolean mask); - - /** Gets the current depth test function. - @return The current depth test function. - */ - GLenum getDepthFunc(void) const { return mDepthFunc; } - - /** Sets the current depth test function. - @param func The depth test function to use. - */ - void setDepthFunc(GLenum func); - - /** Gets the clear depth in the range from [0..1]. - @return The current clearing depth. - */ - GLclampf getClearDepth(void) const { return mClearDepth; } - - /** Sets the clear depth in the range from [0..1]. - @param depth The clear depth to use. - */ - void setClearDepth(GLclampf depth); - - /** Sets the color to clear to. - @param red The red component. - @param green The green component. - @param blue The blue component. - @param alpha The alpha component. - */ - void setClearColour(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); - - - /** Sets the current colour mask. - @param red The red component. - @param green The green component. - @param blue The blue component. - @param alpha The alpha component. - */ - void setColourMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); - - /** Sets the stencil mask. - @param mask The stencil mask to use - */ - void setStencilMask(GLuint mask); - - /** Enables a piece of OpenGL functionality. - */ - void setEnabled(GLenum flag, bool enabled); - - /** Gets the current polygon rendering mode, fill, wireframe, points, etc. - @return The current polygon rendering mode. - */ - GLenum getPolygonMode(void) const { return mPolygonMode; } - - /** Sets the current polygon rendering mode. - @param mode The polygon mode to use. - */ - void setPolygonMode(GLenum mode); - - /** Sets the face culling mode. - @return The current face culling mode - */ - GLenum getCullFace(void) const { return mCullFace; } - - /** Sets the face culling setting. - @param face The face culling mode to use. - */ - void setCullFace(GLenum face); - - /// Enable the specified texture coordinate generation option for the currently active texture unit - void enableTextureCoordGen(GLenum type); - /// Disable the specified texture coordinate generation option for the currently active texture unit - void disableTextureCoordGen(GLenum type); - - // Set material lighting parameters - void setMaterialAmbient(GLfloat r, GLfloat g, GLfloat b, GLfloat a); - void setMaterialDiffuse(GLfloat r, GLfloat g, GLfloat b, GLfloat a); - void setMaterialEmissive(GLfloat r, GLfloat g, GLfloat b, GLfloat a); - void setMaterialSpecular(GLfloat r, GLfloat g, GLfloat b, GLfloat a); - void setMaterialShininess(GLfloat shininess); - void setPointSize(GLfloat size); - void setPointParameters(const GLfloat* attenuation, float minSize = -1, float maxSize = -1); - - void setViewport(const Rect& r); - - }; -} - -#endif diff --git a/RenderSystems/GL/include/OgreGLTexture.h b/RenderSystems/GL/include/OgreGLTexture.h deleted file mode 100644 index fc276b9ba80..00000000000 --- a/RenderSystems/GL/include/OgreGLTexture.h +++ /dev/null @@ -1,71 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLTEXTURE_H__ -#define __GLTEXTURE_H__ - -#include "OgreGLPrerequisites.h" -#include "OgrePlatform.h" -#include "OgreRenderTexture.h" -#include "OgreGLTextureCommon.h" -#include "OgreHardwarePixelBuffer.h" - -namespace Ogre { - - class _OgreGLExport GLTexture : public GLTextureCommon - { - public: - // Constructor - GLTexture(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - GLRenderSystem* renderSystem); - - virtual ~GLTexture(); - - /// Takes the OGRE texture type (1d/2d/3d/cube) and returns the appropriate GL one - GLenum getGLTextureTarget(void) const; - - protected: - /// @copydoc Texture::createInternalResourcesImpl - void createInternalResourcesImpl(void) override; - /// @copydoc Texture::freeInternalResourcesImpl - void freeInternalResourcesImpl(void) override; - - /** internal method, create GLHardwarePixelBuffers for every face and - mipmap level. This method must be called after the GL texture object was created, - the number of mipmaps was set (GL_TEXTURE_MAX_LEVEL) and glTexImageXD was called to - actually allocate the buffer - */ - void _createSurfaceList(); - - private: - GLRenderSystem* mRenderSystem; - }; -} - -#endif // __GLTEXTURE_H__ diff --git a/RenderSystems/GL/include/OgreGLTextureManager.h b/RenderSystems/GL/include/OgreGLTextureManager.h deleted file mode 100644 index 8728f65422f..00000000000 --- a/RenderSystems/GL/include/OgreGLTextureManager.h +++ /dev/null @@ -1,62 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLTextureManager_H__ -#define __GLTextureManager_H__ - -#include "OgreGLPrerequisites.h" -#include "OgreTextureManager.h" -#include "OgreGLTexture.h" - -namespace Ogre { - /** GL-specific implementation of a TextureManager */ - class _OgreGLExport GLTextureManager : public TextureManager - { - public: - GLTextureManager(GLRenderSystem* renderSystem); - virtual ~GLTextureManager(); - - /// @copydoc TextureManager::getNativeFormat - PixelFormat getNativeFormat(TextureType ttype, PixelFormat format, int usage) override; - - /// @copydoc TextureManager::isHardwareFilteringSupported - bool isHardwareFilteringSupported(TextureType ttype, PixelFormat format, int usage, - bool preciseFormatOnly = false) override; - - protected: - friend class GLRenderSystem; - - /// @copydoc ResourceManager::createImpl - Resource* createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams) override; - - GLRenderSystem* mRenderSystem; - }; -} -#endif diff --git a/RenderSystems/GL/include/glad/glad.h b/RenderSystems/GL/include/glad/glad.h deleted file mode 100644 index ad18b0c2d63..00000000000 --- a/RenderSystems/GL/include/glad/glad.h +++ /dev/null @@ -1,4996 +0,0 @@ -/* - - OpenGL loader generated by glad 0.1.35 on Fri Dec 31 02:13:25 2021. - - Language/Generator: C/C++ - Specification: gl - APIs: gl=2.1 - Profile: compatibility - Extensions: - GL_ARB_depth_buffer_float, - GL_ARB_draw_buffers, - GL_ARB_draw_instanced, - GL_ARB_fragment_program, - GL_ARB_fragment_program_shadow, - GL_ARB_fragment_shader, - GL_ARB_framebuffer_object, - GL_ARB_get_program_binary, - GL_ARB_instanced_arrays, - GL_ARB_multisample, - GL_ARB_multitexture, - GL_ARB_occlusion_query, - GL_ARB_pixel_buffer_object, - GL_ARB_point_parameters, - GL_ARB_point_sprite, - GL_ARB_seamless_cube_map, - GL_ARB_shader_objects, - GL_ARB_shading_language_100, - GL_ARB_shadow, - GL_ARB_texture_compression, - GL_ARB_texture_cube_map, - GL_ARB_texture_env_combine, - GL_ARB_texture_float, - GL_ARB_texture_non_power_of_two, - GL_ARB_vertex_buffer_object, - GL_ARB_vertex_program, - GL_ARB_vertex_shader, - GL_ATI_draw_buffers, - GL_ATI_fragment_shader, - GL_ATI_texture_float, - GL_EXT_blend_equation_separate, - GL_EXT_framebuffer_blit, - GL_EXT_framebuffer_multisample, - GL_EXT_framebuffer_object, - GL_EXT_framebuffer_sRGB, - GL_EXT_geometry_shader4, - GL_EXT_pixel_buffer_object, - GL_EXT_point_parameters, - GL_EXT_secondary_color, - GL_EXT_stencil_two_side, - GL_EXT_stencil_wrap, - GL_EXT_texture_array, - GL_EXT_texture_compression_s3tc, - GL_EXT_texture_filter_anisotropic, - GL_EXT_texture_lod_bias, - GL_EXT_texture_sRGB, - GL_GREMEDY_string_marker, - GL_NV_fragment_program2, - GL_NV_fragment_program_option, - GL_NV_geometry_program4, - GL_NV_gpu_program4, - GL_NV_register_combiners, - GL_NV_register_combiners2, - GL_NV_texture_compression_vtc, - GL_NV_texture_shader, - GL_NV_transform_feedback, - GL_NV_vertex_program, - GL_NV_vertex_program2_option, - GL_NV_vertex_program3 - Loader: True - Local files: False - Omit khrplatform: False - Reproducible: False - - Commandline: - --profile="compatibility" --api="gl=2.1" --generator="c" --spec="gl" --extensions="GL_ARB_depth_buffer_float,GL_ARB_draw_buffers,GL_ARB_draw_instanced,GL_ARB_fragment_program,GL_ARB_fragment_program_shadow,GL_ARB_fragment_shader,GL_ARB_framebuffer_object,GL_ARB_get_program_binary,GL_ARB_instanced_arrays,GL_ARB_multisample,GL_ARB_multitexture,GL_ARB_occlusion_query,GL_ARB_pixel_buffer_object,GL_ARB_point_parameters,GL_ARB_point_sprite,GL_ARB_seamless_cube_map,GL_ARB_shader_objects,GL_ARB_shading_language_100,GL_ARB_shadow,GL_ARB_texture_compression,GL_ARB_texture_cube_map,GL_ARB_texture_env_combine,GL_ARB_texture_float,GL_ARB_texture_non_power_of_two,GL_ARB_vertex_buffer_object,GL_ARB_vertex_program,GL_ARB_vertex_shader,GL_ATI_draw_buffers,GL_ATI_fragment_shader,GL_ATI_texture_float,GL_EXT_blend_equation_separate,GL_EXT_framebuffer_blit,GL_EXT_framebuffer_multisample,GL_EXT_framebuffer_object,GL_EXT_framebuffer_sRGB,GL_EXT_geometry_shader4,GL_EXT_pixel_buffer_object,GL_EXT_point_parameters,GL_EXT_secondary_color,GL_EXT_stencil_two_side,GL_EXT_stencil_wrap,GL_EXT_texture_array,GL_EXT_texture_compression_s3tc,GL_EXT_texture_filter_anisotropic,GL_EXT_texture_lod_bias,GL_EXT_texture_sRGB,GL_GREMEDY_string_marker,GL_NV_fragment_program2,GL_NV_fragment_program_option,GL_NV_geometry_program4,GL_NV_gpu_program4,GL_NV_register_combiners,GL_NV_register_combiners2,GL_NV_texture_compression_vtc,GL_NV_texture_shader,GL_NV_transform_feedback,GL_NV_vertex_program,GL_NV_vertex_program2_option,GL_NV_vertex_program3" - Online: - Too many extensions -*/ - - -#ifndef __glad_h_ -#define __glad_h_ - -#ifdef __gl_h_ -#error OpenGL header already included, remove this include, glad already provides it -#endif -#define __gl_h_ - -#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) -#define APIENTRY __stdcall -#endif - -#ifndef APIENTRY -#define APIENTRY -#endif -#ifndef APIENTRYP -#define APIENTRYP APIENTRY * -#endif - -#ifndef GLAPIENTRY -#define GLAPIENTRY APIENTRY -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -struct gladGLversionStruct { - int major; - int minor; -}; - -typedef void* (* GLADloadproc)(const char *name); - -#ifndef GLAPI -# if defined(GLAD_GLAPI_EXPORT) -# if defined(_WIN32) || defined(__CYGWIN__) -# if defined(GLAD_GLAPI_EXPORT_BUILD) -# if defined(__GNUC__) -# define GLAPI __attribute__ ((dllexport)) extern -# else -# define GLAPI __declspec(dllexport) extern -# endif -# else -# if defined(__GNUC__) -# define GLAPI __attribute__ ((dllimport)) extern -# else -# define GLAPI __declspec(dllimport) extern -# endif -# endif -# elif defined(__GNUC__) && defined(GLAD_GLAPI_EXPORT_BUILD) -# define GLAPI __attribute__ ((visibility ("default"))) extern -# else -# define GLAPI extern -# endif -# else -# define GLAPI extern -# endif -#endif - -GLAPI struct gladGLversionStruct GLVersion; - -GLAPI int gladLoadGL(void); - -GLAPI int gladLoadGLLoader(GLADloadproc); - -#include -typedef unsigned int GLenum; -typedef unsigned char GLboolean; -typedef unsigned int GLbitfield; -typedef void GLvoid; -typedef khronos_int8_t GLbyte; -typedef khronos_uint8_t GLubyte; -typedef khronos_int16_t GLshort; -typedef khronos_uint16_t GLushort; -typedef int GLint; -typedef unsigned int GLuint; -typedef khronos_int32_t GLclampx; -typedef int GLsizei; -typedef khronos_float_t GLfloat; -typedef khronos_float_t GLclampf; -typedef double GLdouble; -typedef double GLclampd; -typedef void *GLeglClientBufferEXT; -typedef void *GLeglImageOES; -typedef char GLchar; -typedef char GLcharARB; -#ifdef __APPLE__ -typedef void *GLhandleARB; -#else -typedef unsigned int GLhandleARB; -#endif -typedef khronos_uint16_t GLhalf; -typedef khronos_uint16_t GLhalfARB; -typedef khronos_int32_t GLfixed; -typedef khronos_intptr_t GLintptr; -typedef khronos_intptr_t GLintptrARB; -typedef khronos_ssize_t GLsizeiptr; -typedef khronos_ssize_t GLsizeiptrARB; -typedef khronos_int64_t GLint64; -typedef khronos_int64_t GLint64EXT; -typedef khronos_uint64_t GLuint64; -typedef khronos_uint64_t GLuint64EXT; -typedef struct __GLsync *GLsync; -struct _cl_context; -struct _cl_event; -typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); -typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); -typedef void (APIENTRY *GLDEBUGPROCKHR)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); -typedef void (APIENTRY *GLDEBUGPROCAMD)(GLuint id,GLenum category,GLenum severity,GLsizei length,const GLchar *message,void *userParam); -typedef unsigned short GLhalfNV; -typedef GLintptr GLvdpauSurfaceNV; -typedef void (APIENTRY *GLVULKANPROCNV)(void); -#define GL_DEPTH_BUFFER_BIT 0x00000100 -#define GL_STENCIL_BUFFER_BIT 0x00000400 -#define GL_COLOR_BUFFER_BIT 0x00004000 -#define GL_FALSE 0 -#define GL_TRUE 1 -#define GL_POINTS 0x0000 -#define GL_LINES 0x0001 -#define GL_LINE_LOOP 0x0002 -#define GL_LINE_STRIP 0x0003 -#define GL_TRIANGLES 0x0004 -#define GL_TRIANGLE_STRIP 0x0005 -#define GL_TRIANGLE_FAN 0x0006 -#define GL_QUADS 0x0007 -#define GL_NEVER 0x0200 -#define GL_LESS 0x0201 -#define GL_EQUAL 0x0202 -#define GL_LEQUAL 0x0203 -#define GL_GREATER 0x0204 -#define GL_NOTEQUAL 0x0205 -#define GL_GEQUAL 0x0206 -#define GL_ALWAYS 0x0207 -#define GL_ZERO 0 -#define GL_ONE 1 -#define GL_SRC_COLOR 0x0300 -#define GL_ONE_MINUS_SRC_COLOR 0x0301 -#define GL_SRC_ALPHA 0x0302 -#define GL_ONE_MINUS_SRC_ALPHA 0x0303 -#define GL_DST_ALPHA 0x0304 -#define GL_ONE_MINUS_DST_ALPHA 0x0305 -#define GL_DST_COLOR 0x0306 -#define GL_ONE_MINUS_DST_COLOR 0x0307 -#define GL_SRC_ALPHA_SATURATE 0x0308 -#define GL_NONE 0 -#define GL_FRONT_LEFT 0x0400 -#define GL_FRONT_RIGHT 0x0401 -#define GL_BACK_LEFT 0x0402 -#define GL_BACK_RIGHT 0x0403 -#define GL_FRONT 0x0404 -#define GL_BACK 0x0405 -#define GL_LEFT 0x0406 -#define GL_RIGHT 0x0407 -#define GL_FRONT_AND_BACK 0x0408 -#define GL_NO_ERROR 0 -#define GL_INVALID_ENUM 0x0500 -#define GL_INVALID_VALUE 0x0501 -#define GL_INVALID_OPERATION 0x0502 -#define GL_OUT_OF_MEMORY 0x0505 -#define GL_CW 0x0900 -#define GL_CCW 0x0901 -#define GL_POINT_SIZE 0x0B11 -#define GL_POINT_SIZE_RANGE 0x0B12 -#define GL_POINT_SIZE_GRANULARITY 0x0B13 -#define GL_LINE_SMOOTH 0x0B20 -#define GL_LINE_WIDTH 0x0B21 -#define GL_LINE_WIDTH_RANGE 0x0B22 -#define GL_LINE_WIDTH_GRANULARITY 0x0B23 -#define GL_POLYGON_MODE 0x0B40 -#define GL_POLYGON_SMOOTH 0x0B41 -#define GL_CULL_FACE 0x0B44 -#define GL_CULL_FACE_MODE 0x0B45 -#define GL_FRONT_FACE 0x0B46 -#define GL_DEPTH_RANGE 0x0B70 -#define GL_DEPTH_TEST 0x0B71 -#define GL_DEPTH_WRITEMASK 0x0B72 -#define GL_DEPTH_CLEAR_VALUE 0x0B73 -#define GL_DEPTH_FUNC 0x0B74 -#define GL_STENCIL_TEST 0x0B90 -#define GL_STENCIL_CLEAR_VALUE 0x0B91 -#define GL_STENCIL_FUNC 0x0B92 -#define GL_STENCIL_VALUE_MASK 0x0B93 -#define GL_STENCIL_FAIL 0x0B94 -#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 -#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 -#define GL_STENCIL_REF 0x0B97 -#define GL_STENCIL_WRITEMASK 0x0B98 -#define GL_VIEWPORT 0x0BA2 -#define GL_DITHER 0x0BD0 -#define GL_BLEND_DST 0x0BE0 -#define GL_BLEND_SRC 0x0BE1 -#define GL_BLEND 0x0BE2 -#define GL_LOGIC_OP_MODE 0x0BF0 -#define GL_DRAW_BUFFER 0x0C01 -#define GL_READ_BUFFER 0x0C02 -#define GL_SCISSOR_BOX 0x0C10 -#define GL_SCISSOR_TEST 0x0C11 -#define GL_COLOR_CLEAR_VALUE 0x0C22 -#define GL_COLOR_WRITEMASK 0x0C23 -#define GL_DOUBLEBUFFER 0x0C32 -#define GL_STEREO 0x0C33 -#define GL_LINE_SMOOTH_HINT 0x0C52 -#define GL_POLYGON_SMOOTH_HINT 0x0C53 -#define GL_UNPACK_SWAP_BYTES 0x0CF0 -#define GL_UNPACK_LSB_FIRST 0x0CF1 -#define GL_UNPACK_ROW_LENGTH 0x0CF2 -#define GL_UNPACK_SKIP_ROWS 0x0CF3 -#define GL_UNPACK_SKIP_PIXELS 0x0CF4 -#define GL_UNPACK_ALIGNMENT 0x0CF5 -#define GL_PACK_SWAP_BYTES 0x0D00 -#define GL_PACK_LSB_FIRST 0x0D01 -#define GL_PACK_ROW_LENGTH 0x0D02 -#define GL_PACK_SKIP_ROWS 0x0D03 -#define GL_PACK_SKIP_PIXELS 0x0D04 -#define GL_PACK_ALIGNMENT 0x0D05 -#define GL_MAX_TEXTURE_SIZE 0x0D33 -#define GL_MAX_VIEWPORT_DIMS 0x0D3A -#define GL_SUBPIXEL_BITS 0x0D50 -#define GL_TEXTURE_1D 0x0DE0 -#define GL_TEXTURE_2D 0x0DE1 -#define GL_TEXTURE_WIDTH 0x1000 -#define GL_TEXTURE_HEIGHT 0x1001 -#define GL_TEXTURE_BORDER_COLOR 0x1004 -#define GL_DONT_CARE 0x1100 -#define GL_FASTEST 0x1101 -#define GL_NICEST 0x1102 -#define GL_BYTE 0x1400 -#define GL_UNSIGNED_BYTE 0x1401 -#define GL_SHORT 0x1402 -#define GL_UNSIGNED_SHORT 0x1403 -#define GL_INT 0x1404 -#define GL_UNSIGNED_INT 0x1405 -#define GL_FLOAT 0x1406 -#define GL_STACK_OVERFLOW 0x0503 -#define GL_STACK_UNDERFLOW 0x0504 -#define GL_CLEAR 0x1500 -#define GL_AND 0x1501 -#define GL_AND_REVERSE 0x1502 -#define GL_COPY 0x1503 -#define GL_AND_INVERTED 0x1504 -#define GL_NOOP 0x1505 -#define GL_XOR 0x1506 -#define GL_OR 0x1507 -#define GL_NOR 0x1508 -#define GL_EQUIV 0x1509 -#define GL_INVERT 0x150A -#define GL_OR_REVERSE 0x150B -#define GL_COPY_INVERTED 0x150C -#define GL_OR_INVERTED 0x150D -#define GL_NAND 0x150E -#define GL_SET 0x150F -#define GL_TEXTURE 0x1702 -#define GL_COLOR 0x1800 -#define GL_DEPTH 0x1801 -#define GL_STENCIL 0x1802 -#define GL_STENCIL_INDEX 0x1901 -#define GL_DEPTH_COMPONENT 0x1902 -#define GL_RED 0x1903 -#define GL_GREEN 0x1904 -#define GL_BLUE 0x1905 -#define GL_ALPHA 0x1906 -#define GL_RGB 0x1907 -#define GL_RGBA 0x1908 -#define GL_POINT 0x1B00 -#define GL_LINE 0x1B01 -#define GL_FILL 0x1B02 -#define GL_KEEP 0x1E00 -#define GL_REPLACE 0x1E01 -#define GL_INCR 0x1E02 -#define GL_DECR 0x1E03 -#define GL_VENDOR 0x1F00 -#define GL_RENDERER 0x1F01 -#define GL_VERSION 0x1F02 -#define GL_EXTENSIONS 0x1F03 -#define GL_NEAREST 0x2600 -#define GL_LINEAR 0x2601 -#define GL_NEAREST_MIPMAP_NEAREST 0x2700 -#define GL_LINEAR_MIPMAP_NEAREST 0x2701 -#define GL_NEAREST_MIPMAP_LINEAR 0x2702 -#define GL_LINEAR_MIPMAP_LINEAR 0x2703 -#define GL_TEXTURE_MAG_FILTER 0x2800 -#define GL_TEXTURE_MIN_FILTER 0x2801 -#define GL_TEXTURE_WRAP_S 0x2802 -#define GL_TEXTURE_WRAP_T 0x2803 -#define GL_REPEAT 0x2901 -#define GL_CURRENT_BIT 0x00000001 -#define GL_POINT_BIT 0x00000002 -#define GL_LINE_BIT 0x00000004 -#define GL_POLYGON_BIT 0x00000008 -#define GL_POLYGON_STIPPLE_BIT 0x00000010 -#define GL_PIXEL_MODE_BIT 0x00000020 -#define GL_LIGHTING_BIT 0x00000040 -#define GL_FOG_BIT 0x00000080 -#define GL_ACCUM_BUFFER_BIT 0x00000200 -#define GL_VIEWPORT_BIT 0x00000800 -#define GL_TRANSFORM_BIT 0x00001000 -#define GL_ENABLE_BIT 0x00002000 -#define GL_HINT_BIT 0x00008000 -#define GL_EVAL_BIT 0x00010000 -#define GL_LIST_BIT 0x00020000 -#define GL_TEXTURE_BIT 0x00040000 -#define GL_SCISSOR_BIT 0x00080000 -#define GL_ALL_ATTRIB_BITS 0xFFFFFFFF -#define GL_QUAD_STRIP 0x0008 -#define GL_POLYGON 0x0009 -#define GL_ACCUM 0x0100 -#define GL_LOAD 0x0101 -#define GL_RETURN 0x0102 -#define GL_MULT 0x0103 -#define GL_ADD 0x0104 -#define GL_AUX0 0x0409 -#define GL_AUX1 0x040A -#define GL_AUX2 0x040B -#define GL_AUX3 0x040C -#define GL_2D 0x0600 -#define GL_3D 0x0601 -#define GL_3D_COLOR 0x0602 -#define GL_3D_COLOR_TEXTURE 0x0603 -#define GL_4D_COLOR_TEXTURE 0x0604 -#define GL_PASS_THROUGH_TOKEN 0x0700 -#define GL_POINT_TOKEN 0x0701 -#define GL_LINE_TOKEN 0x0702 -#define GL_POLYGON_TOKEN 0x0703 -#define GL_BITMAP_TOKEN 0x0704 -#define GL_DRAW_PIXEL_TOKEN 0x0705 -#define GL_COPY_PIXEL_TOKEN 0x0706 -#define GL_LINE_RESET_TOKEN 0x0707 -#define GL_EXP 0x0800 -#define GL_EXP2 0x0801 -#define GL_COEFF 0x0A00 -#define GL_ORDER 0x0A01 -#define GL_DOMAIN 0x0A02 -#define GL_PIXEL_MAP_I_TO_I 0x0C70 -#define GL_PIXEL_MAP_S_TO_S 0x0C71 -#define GL_PIXEL_MAP_I_TO_R 0x0C72 -#define GL_PIXEL_MAP_I_TO_G 0x0C73 -#define GL_PIXEL_MAP_I_TO_B 0x0C74 -#define GL_PIXEL_MAP_I_TO_A 0x0C75 -#define GL_PIXEL_MAP_R_TO_R 0x0C76 -#define GL_PIXEL_MAP_G_TO_G 0x0C77 -#define GL_PIXEL_MAP_B_TO_B 0x0C78 -#define GL_PIXEL_MAP_A_TO_A 0x0C79 -#define GL_CURRENT_COLOR 0x0B00 -#define GL_CURRENT_INDEX 0x0B01 -#define GL_CURRENT_NORMAL 0x0B02 -#define GL_CURRENT_TEXTURE_COORDS 0x0B03 -#define GL_CURRENT_RASTER_COLOR 0x0B04 -#define GL_CURRENT_RASTER_INDEX 0x0B05 -#define GL_CURRENT_RASTER_TEXTURE_COORDS 0x0B06 -#define GL_CURRENT_RASTER_POSITION 0x0B07 -#define GL_CURRENT_RASTER_POSITION_VALID 0x0B08 -#define GL_CURRENT_RASTER_DISTANCE 0x0B09 -#define GL_POINT_SMOOTH 0x0B10 -#define GL_LINE_STIPPLE 0x0B24 -#define GL_LINE_STIPPLE_PATTERN 0x0B25 -#define GL_LINE_STIPPLE_REPEAT 0x0B26 -#define GL_LIST_MODE 0x0B30 -#define GL_MAX_LIST_NESTING 0x0B31 -#define GL_LIST_BASE 0x0B32 -#define GL_LIST_INDEX 0x0B33 -#define GL_POLYGON_STIPPLE 0x0B42 -#define GL_EDGE_FLAG 0x0B43 -#define GL_LIGHTING 0x0B50 -#define GL_LIGHT_MODEL_LOCAL_VIEWER 0x0B51 -#define GL_LIGHT_MODEL_TWO_SIDE 0x0B52 -#define GL_LIGHT_MODEL_AMBIENT 0x0B53 -#define GL_SHADE_MODEL 0x0B54 -#define GL_COLOR_MATERIAL_FACE 0x0B55 -#define GL_COLOR_MATERIAL_PARAMETER 0x0B56 -#define GL_COLOR_MATERIAL 0x0B57 -#define GL_FOG 0x0B60 -#define GL_FOG_INDEX 0x0B61 -#define GL_FOG_DENSITY 0x0B62 -#define GL_FOG_START 0x0B63 -#define GL_FOG_END 0x0B64 -#define GL_FOG_MODE 0x0B65 -#define GL_FOG_COLOR 0x0B66 -#define GL_ACCUM_CLEAR_VALUE 0x0B80 -#define GL_MATRIX_MODE 0x0BA0 -#define GL_NORMALIZE 0x0BA1 -#define GL_MODELVIEW_STACK_DEPTH 0x0BA3 -#define GL_PROJECTION_STACK_DEPTH 0x0BA4 -#define GL_TEXTURE_STACK_DEPTH 0x0BA5 -#define GL_MODELVIEW_MATRIX 0x0BA6 -#define GL_PROJECTION_MATRIX 0x0BA7 -#define GL_TEXTURE_MATRIX 0x0BA8 -#define GL_ATTRIB_STACK_DEPTH 0x0BB0 -#define GL_ALPHA_TEST 0x0BC0 -#define GL_ALPHA_TEST_FUNC 0x0BC1 -#define GL_ALPHA_TEST_REF 0x0BC2 -#define GL_LOGIC_OP 0x0BF1 -#define GL_AUX_BUFFERS 0x0C00 -#define GL_INDEX_CLEAR_VALUE 0x0C20 -#define GL_INDEX_WRITEMASK 0x0C21 -#define GL_INDEX_MODE 0x0C30 -#define GL_RGBA_MODE 0x0C31 -#define GL_RENDER_MODE 0x0C40 -#define GL_PERSPECTIVE_CORRECTION_HINT 0x0C50 -#define GL_POINT_SMOOTH_HINT 0x0C51 -#define GL_FOG_HINT 0x0C54 -#define GL_TEXTURE_GEN_S 0x0C60 -#define GL_TEXTURE_GEN_T 0x0C61 -#define GL_TEXTURE_GEN_R 0x0C62 -#define GL_TEXTURE_GEN_Q 0x0C63 -#define GL_PIXEL_MAP_I_TO_I_SIZE 0x0CB0 -#define GL_PIXEL_MAP_S_TO_S_SIZE 0x0CB1 -#define GL_PIXEL_MAP_I_TO_R_SIZE 0x0CB2 -#define GL_PIXEL_MAP_I_TO_G_SIZE 0x0CB3 -#define GL_PIXEL_MAP_I_TO_B_SIZE 0x0CB4 -#define GL_PIXEL_MAP_I_TO_A_SIZE 0x0CB5 -#define GL_PIXEL_MAP_R_TO_R_SIZE 0x0CB6 -#define GL_PIXEL_MAP_G_TO_G_SIZE 0x0CB7 -#define GL_PIXEL_MAP_B_TO_B_SIZE 0x0CB8 -#define GL_PIXEL_MAP_A_TO_A_SIZE 0x0CB9 -#define GL_MAP_COLOR 0x0D10 -#define GL_MAP_STENCIL 0x0D11 -#define GL_INDEX_SHIFT 0x0D12 -#define GL_INDEX_OFFSET 0x0D13 -#define GL_RED_SCALE 0x0D14 -#define GL_RED_BIAS 0x0D15 -#define GL_ZOOM_X 0x0D16 -#define GL_ZOOM_Y 0x0D17 -#define GL_GREEN_SCALE 0x0D18 -#define GL_GREEN_BIAS 0x0D19 -#define GL_BLUE_SCALE 0x0D1A -#define GL_BLUE_BIAS 0x0D1B -#define GL_ALPHA_SCALE 0x0D1C -#define GL_ALPHA_BIAS 0x0D1D -#define GL_DEPTH_SCALE 0x0D1E -#define GL_DEPTH_BIAS 0x0D1F -#define GL_MAX_EVAL_ORDER 0x0D30 -#define GL_MAX_LIGHTS 0x0D31 -#define GL_MAX_CLIP_PLANES 0x0D32 -#define GL_MAX_PIXEL_MAP_TABLE 0x0D34 -#define GL_MAX_ATTRIB_STACK_DEPTH 0x0D35 -#define GL_MAX_MODELVIEW_STACK_DEPTH 0x0D36 -#define GL_MAX_NAME_STACK_DEPTH 0x0D37 -#define GL_MAX_PROJECTION_STACK_DEPTH 0x0D38 -#define GL_MAX_TEXTURE_STACK_DEPTH 0x0D39 -#define GL_INDEX_BITS 0x0D51 -#define GL_RED_BITS 0x0D52 -#define GL_GREEN_BITS 0x0D53 -#define GL_BLUE_BITS 0x0D54 -#define GL_ALPHA_BITS 0x0D55 -#define GL_DEPTH_BITS 0x0D56 -#define GL_STENCIL_BITS 0x0D57 -#define GL_ACCUM_RED_BITS 0x0D58 -#define GL_ACCUM_GREEN_BITS 0x0D59 -#define GL_ACCUM_BLUE_BITS 0x0D5A -#define GL_ACCUM_ALPHA_BITS 0x0D5B -#define GL_NAME_STACK_DEPTH 0x0D70 -#define GL_AUTO_NORMAL 0x0D80 -#define GL_MAP1_COLOR_4 0x0D90 -#define GL_MAP1_INDEX 0x0D91 -#define GL_MAP1_NORMAL 0x0D92 -#define GL_MAP1_TEXTURE_COORD_1 0x0D93 -#define GL_MAP1_TEXTURE_COORD_2 0x0D94 -#define GL_MAP1_TEXTURE_COORD_3 0x0D95 -#define GL_MAP1_TEXTURE_COORD_4 0x0D96 -#define GL_MAP1_VERTEX_3 0x0D97 -#define GL_MAP1_VERTEX_4 0x0D98 -#define GL_MAP2_COLOR_4 0x0DB0 -#define GL_MAP2_INDEX 0x0DB1 -#define GL_MAP2_NORMAL 0x0DB2 -#define GL_MAP2_TEXTURE_COORD_1 0x0DB3 -#define GL_MAP2_TEXTURE_COORD_2 0x0DB4 -#define GL_MAP2_TEXTURE_COORD_3 0x0DB5 -#define GL_MAP2_TEXTURE_COORD_4 0x0DB6 -#define GL_MAP2_VERTEX_3 0x0DB7 -#define GL_MAP2_VERTEX_4 0x0DB8 -#define GL_MAP1_GRID_DOMAIN 0x0DD0 -#define GL_MAP1_GRID_SEGMENTS 0x0DD1 -#define GL_MAP2_GRID_DOMAIN 0x0DD2 -#define GL_MAP2_GRID_SEGMENTS 0x0DD3 -#define GL_TEXTURE_COMPONENTS 0x1003 -#define GL_TEXTURE_BORDER 0x1005 -#define GL_AMBIENT 0x1200 -#define GL_DIFFUSE 0x1201 -#define GL_SPECULAR 0x1202 -#define GL_POSITION 0x1203 -#define GL_SPOT_DIRECTION 0x1204 -#define GL_SPOT_EXPONENT 0x1205 -#define GL_SPOT_CUTOFF 0x1206 -#define GL_CONSTANT_ATTENUATION 0x1207 -#define GL_LINEAR_ATTENUATION 0x1208 -#define GL_QUADRATIC_ATTENUATION 0x1209 -#define GL_COMPILE 0x1300 -#define GL_COMPILE_AND_EXECUTE 0x1301 -#define GL_2_BYTES 0x1407 -#define GL_3_BYTES 0x1408 -#define GL_4_BYTES 0x1409 -#define GL_EMISSION 0x1600 -#define GL_SHININESS 0x1601 -#define GL_AMBIENT_AND_DIFFUSE 0x1602 -#define GL_COLOR_INDEXES 0x1603 -#define GL_MODELVIEW 0x1700 -#define GL_PROJECTION 0x1701 -#define GL_COLOR_INDEX 0x1900 -#define GL_LUMINANCE 0x1909 -#define GL_LUMINANCE_ALPHA 0x190A -#define GL_BITMAP 0x1A00 -#define GL_RENDER 0x1C00 -#define GL_FEEDBACK 0x1C01 -#define GL_SELECT 0x1C02 -#define GL_FLAT 0x1D00 -#define GL_SMOOTH 0x1D01 -#define GL_S 0x2000 -#define GL_T 0x2001 -#define GL_R 0x2002 -#define GL_Q 0x2003 -#define GL_MODULATE 0x2100 -#define GL_DECAL 0x2101 -#define GL_TEXTURE_ENV_MODE 0x2200 -#define GL_TEXTURE_ENV_COLOR 0x2201 -#define GL_TEXTURE_ENV 0x2300 -#define GL_EYE_LINEAR 0x2400 -#define GL_OBJECT_LINEAR 0x2401 -#define GL_SPHERE_MAP 0x2402 -#define GL_TEXTURE_GEN_MODE 0x2500 -#define GL_OBJECT_PLANE 0x2501 -#define GL_EYE_PLANE 0x2502 -#define GL_CLAMP 0x2900 -#define GL_CLIP_PLANE0 0x3000 -#define GL_CLIP_PLANE1 0x3001 -#define GL_CLIP_PLANE2 0x3002 -#define GL_CLIP_PLANE3 0x3003 -#define GL_CLIP_PLANE4 0x3004 -#define GL_CLIP_PLANE5 0x3005 -#define GL_LIGHT0 0x4000 -#define GL_LIGHT1 0x4001 -#define GL_LIGHT2 0x4002 -#define GL_LIGHT3 0x4003 -#define GL_LIGHT4 0x4004 -#define GL_LIGHT5 0x4005 -#define GL_LIGHT6 0x4006 -#define GL_LIGHT7 0x4007 -#define GL_COLOR_LOGIC_OP 0x0BF2 -#define GL_POLYGON_OFFSET_UNITS 0x2A00 -#define GL_POLYGON_OFFSET_POINT 0x2A01 -#define GL_POLYGON_OFFSET_LINE 0x2A02 -#define GL_POLYGON_OFFSET_FILL 0x8037 -#define GL_POLYGON_OFFSET_FACTOR 0x8038 -#define GL_TEXTURE_BINDING_1D 0x8068 -#define GL_TEXTURE_BINDING_2D 0x8069 -#define GL_TEXTURE_INTERNAL_FORMAT 0x1003 -#define GL_TEXTURE_RED_SIZE 0x805C -#define GL_TEXTURE_GREEN_SIZE 0x805D -#define GL_TEXTURE_BLUE_SIZE 0x805E -#define GL_TEXTURE_ALPHA_SIZE 0x805F -#define GL_DOUBLE 0x140A -#define GL_PROXY_TEXTURE_1D 0x8063 -#define GL_PROXY_TEXTURE_2D 0x8064 -#define GL_R3_G3_B2 0x2A10 -#define GL_RGB4 0x804F -#define GL_RGB5 0x8050 -#define GL_RGB8 0x8051 -#define GL_RGB10 0x8052 -#define GL_RGB12 0x8053 -#define GL_RGB16 0x8054 -#define GL_RGBA2 0x8055 -#define GL_RGBA4 0x8056 -#define GL_RGB5_A1 0x8057 -#define GL_RGBA8 0x8058 -#define GL_RGB10_A2 0x8059 -#define GL_RGBA12 0x805A -#define GL_RGBA16 0x805B -#define GL_CLIENT_PIXEL_STORE_BIT 0x00000001 -#define GL_CLIENT_VERTEX_ARRAY_BIT 0x00000002 -#define GL_CLIENT_ALL_ATTRIB_BITS 0xFFFFFFFF -#define GL_VERTEX_ARRAY_POINTER 0x808E -#define GL_NORMAL_ARRAY_POINTER 0x808F -#define GL_COLOR_ARRAY_POINTER 0x8090 -#define GL_INDEX_ARRAY_POINTER 0x8091 -#define GL_TEXTURE_COORD_ARRAY_POINTER 0x8092 -#define GL_EDGE_FLAG_ARRAY_POINTER 0x8093 -#define GL_FEEDBACK_BUFFER_POINTER 0x0DF0 -#define GL_SELECTION_BUFFER_POINTER 0x0DF3 -#define GL_CLIENT_ATTRIB_STACK_DEPTH 0x0BB1 -#define GL_INDEX_LOGIC_OP 0x0BF1 -#define GL_MAX_CLIENT_ATTRIB_STACK_DEPTH 0x0D3B -#define GL_FEEDBACK_BUFFER_SIZE 0x0DF1 -#define GL_FEEDBACK_BUFFER_TYPE 0x0DF2 -#define GL_SELECTION_BUFFER_SIZE 0x0DF4 -#define GL_VERTEX_ARRAY 0x8074 -#define GL_NORMAL_ARRAY 0x8075 -#define GL_COLOR_ARRAY 0x8076 -#define GL_INDEX_ARRAY 0x8077 -#define GL_TEXTURE_COORD_ARRAY 0x8078 -#define GL_EDGE_FLAG_ARRAY 0x8079 -#define GL_VERTEX_ARRAY_SIZE 0x807A -#define GL_VERTEX_ARRAY_TYPE 0x807B -#define GL_VERTEX_ARRAY_STRIDE 0x807C -#define GL_NORMAL_ARRAY_TYPE 0x807E -#define GL_NORMAL_ARRAY_STRIDE 0x807F -#define GL_COLOR_ARRAY_SIZE 0x8081 -#define GL_COLOR_ARRAY_TYPE 0x8082 -#define GL_COLOR_ARRAY_STRIDE 0x8083 -#define GL_INDEX_ARRAY_TYPE 0x8085 -#define GL_INDEX_ARRAY_STRIDE 0x8086 -#define GL_TEXTURE_COORD_ARRAY_SIZE 0x8088 -#define GL_TEXTURE_COORD_ARRAY_TYPE 0x8089 -#define GL_TEXTURE_COORD_ARRAY_STRIDE 0x808A -#define GL_EDGE_FLAG_ARRAY_STRIDE 0x808C -#define GL_TEXTURE_LUMINANCE_SIZE 0x8060 -#define GL_TEXTURE_INTENSITY_SIZE 0x8061 -#define GL_TEXTURE_PRIORITY 0x8066 -#define GL_TEXTURE_RESIDENT 0x8067 -#define GL_ALPHA4 0x803B -#define GL_ALPHA8 0x803C -#define GL_ALPHA12 0x803D -#define GL_ALPHA16 0x803E -#define GL_LUMINANCE4 0x803F -#define GL_LUMINANCE8 0x8040 -#define GL_LUMINANCE12 0x8041 -#define GL_LUMINANCE16 0x8042 -#define GL_LUMINANCE4_ALPHA4 0x8043 -#define GL_LUMINANCE6_ALPHA2 0x8044 -#define GL_LUMINANCE8_ALPHA8 0x8045 -#define GL_LUMINANCE12_ALPHA4 0x8046 -#define GL_LUMINANCE12_ALPHA12 0x8047 -#define GL_LUMINANCE16_ALPHA16 0x8048 -#define GL_INTENSITY 0x8049 -#define GL_INTENSITY4 0x804A -#define GL_INTENSITY8 0x804B -#define GL_INTENSITY12 0x804C -#define GL_INTENSITY16 0x804D -#define GL_V2F 0x2A20 -#define GL_V3F 0x2A21 -#define GL_C4UB_V2F 0x2A22 -#define GL_C4UB_V3F 0x2A23 -#define GL_C3F_V3F 0x2A24 -#define GL_N3F_V3F 0x2A25 -#define GL_C4F_N3F_V3F 0x2A26 -#define GL_T2F_V3F 0x2A27 -#define GL_T4F_V4F 0x2A28 -#define GL_T2F_C4UB_V3F 0x2A29 -#define GL_T2F_C3F_V3F 0x2A2A -#define GL_T2F_N3F_V3F 0x2A2B -#define GL_T2F_C4F_N3F_V3F 0x2A2C -#define GL_T4F_C4F_N3F_V4F 0x2A2D -#define GL_UNSIGNED_BYTE_3_3_2 0x8032 -#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 -#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 -#define GL_UNSIGNED_INT_8_8_8_8 0x8035 -#define GL_UNSIGNED_INT_10_10_10_2 0x8036 -#define GL_TEXTURE_BINDING_3D 0x806A -#define GL_PACK_SKIP_IMAGES 0x806B -#define GL_PACK_IMAGE_HEIGHT 0x806C -#define GL_UNPACK_SKIP_IMAGES 0x806D -#define GL_UNPACK_IMAGE_HEIGHT 0x806E -#define GL_TEXTURE_3D 0x806F -#define GL_PROXY_TEXTURE_3D 0x8070 -#define GL_TEXTURE_DEPTH 0x8071 -#define GL_TEXTURE_WRAP_R 0x8072 -#define GL_MAX_3D_TEXTURE_SIZE 0x8073 -#define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 -#define GL_UNSIGNED_SHORT_5_6_5 0x8363 -#define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 -#define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 -#define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 -#define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 -#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 -#define GL_BGR 0x80E0 -#define GL_BGRA 0x80E1 -#define GL_MAX_ELEMENTS_VERTICES 0x80E8 -#define GL_MAX_ELEMENTS_INDICES 0x80E9 -#define GL_CLAMP_TO_EDGE 0x812F -#define GL_TEXTURE_MIN_LOD 0x813A -#define GL_TEXTURE_MAX_LOD 0x813B -#define GL_TEXTURE_BASE_LEVEL 0x813C -#define GL_TEXTURE_MAX_LEVEL 0x813D -#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 -#define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 -#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 -#define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23 -#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E -#define GL_RESCALE_NORMAL 0x803A -#define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8 -#define GL_SINGLE_COLOR 0x81F9 -#define GL_SEPARATE_SPECULAR_COLOR 0x81FA -#define GL_ALIASED_POINT_SIZE_RANGE 0x846D -#define GL_TEXTURE0 0x84C0 -#define GL_TEXTURE1 0x84C1 -#define GL_TEXTURE2 0x84C2 -#define GL_TEXTURE3 0x84C3 -#define GL_TEXTURE4 0x84C4 -#define GL_TEXTURE5 0x84C5 -#define GL_TEXTURE6 0x84C6 -#define GL_TEXTURE7 0x84C7 -#define GL_TEXTURE8 0x84C8 -#define GL_TEXTURE9 0x84C9 -#define GL_TEXTURE10 0x84CA -#define GL_TEXTURE11 0x84CB -#define GL_TEXTURE12 0x84CC -#define GL_TEXTURE13 0x84CD -#define GL_TEXTURE14 0x84CE -#define GL_TEXTURE15 0x84CF -#define GL_TEXTURE16 0x84D0 -#define GL_TEXTURE17 0x84D1 -#define GL_TEXTURE18 0x84D2 -#define GL_TEXTURE19 0x84D3 -#define GL_TEXTURE20 0x84D4 -#define GL_TEXTURE21 0x84D5 -#define GL_TEXTURE22 0x84D6 -#define GL_TEXTURE23 0x84D7 -#define GL_TEXTURE24 0x84D8 -#define GL_TEXTURE25 0x84D9 -#define GL_TEXTURE26 0x84DA -#define GL_TEXTURE27 0x84DB -#define GL_TEXTURE28 0x84DC -#define GL_TEXTURE29 0x84DD -#define GL_TEXTURE30 0x84DE -#define GL_TEXTURE31 0x84DF -#define GL_ACTIVE_TEXTURE 0x84E0 -#define GL_MULTISAMPLE 0x809D -#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E -#define GL_SAMPLE_ALPHA_TO_ONE 0x809F -#define GL_SAMPLE_COVERAGE 0x80A0 -#define GL_SAMPLE_BUFFERS 0x80A8 -#define GL_SAMPLES 0x80A9 -#define GL_SAMPLE_COVERAGE_VALUE 0x80AA -#define GL_SAMPLE_COVERAGE_INVERT 0x80AB -#define GL_TEXTURE_CUBE_MAP 0x8513 -#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A -#define GL_PROXY_TEXTURE_CUBE_MAP 0x851B -#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C -#define GL_COMPRESSED_RGB 0x84ED -#define GL_COMPRESSED_RGBA 0x84EE -#define GL_TEXTURE_COMPRESSION_HINT 0x84EF -#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0 -#define GL_TEXTURE_COMPRESSED 0x86A1 -#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 -#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 -#define GL_CLAMP_TO_BORDER 0x812D -#define GL_CLIENT_ACTIVE_TEXTURE 0x84E1 -#define GL_MAX_TEXTURE_UNITS 0x84E2 -#define GL_TRANSPOSE_MODELVIEW_MATRIX 0x84E3 -#define GL_TRANSPOSE_PROJECTION_MATRIX 0x84E4 -#define GL_TRANSPOSE_TEXTURE_MATRIX 0x84E5 -#define GL_TRANSPOSE_COLOR_MATRIX 0x84E6 -#define GL_MULTISAMPLE_BIT 0x20000000 -#define GL_NORMAL_MAP 0x8511 -#define GL_REFLECTION_MAP 0x8512 -#define GL_COMPRESSED_ALPHA 0x84E9 -#define GL_COMPRESSED_LUMINANCE 0x84EA -#define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB -#define GL_COMPRESSED_INTENSITY 0x84EC -#define GL_COMBINE 0x8570 -#define GL_COMBINE_RGB 0x8571 -#define GL_COMBINE_ALPHA 0x8572 -#define GL_SOURCE0_RGB 0x8580 -#define GL_SOURCE1_RGB 0x8581 -#define GL_SOURCE2_RGB 0x8582 -#define GL_SOURCE0_ALPHA 0x8588 -#define GL_SOURCE1_ALPHA 0x8589 -#define GL_SOURCE2_ALPHA 0x858A -#define GL_OPERAND0_RGB 0x8590 -#define GL_OPERAND1_RGB 0x8591 -#define GL_OPERAND2_RGB 0x8592 -#define GL_OPERAND0_ALPHA 0x8598 -#define GL_OPERAND1_ALPHA 0x8599 -#define GL_OPERAND2_ALPHA 0x859A -#define GL_RGB_SCALE 0x8573 -#define GL_ADD_SIGNED 0x8574 -#define GL_INTERPOLATE 0x8575 -#define GL_SUBTRACT 0x84E7 -#define GL_CONSTANT 0x8576 -#define GL_PRIMARY_COLOR 0x8577 -#define GL_PREVIOUS 0x8578 -#define GL_DOT3_RGB 0x86AE -#define GL_DOT3_RGBA 0x86AF -#define GL_BLEND_DST_RGB 0x80C8 -#define GL_BLEND_SRC_RGB 0x80C9 -#define GL_BLEND_DST_ALPHA 0x80CA -#define GL_BLEND_SRC_ALPHA 0x80CB -#define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 -#define GL_DEPTH_COMPONENT16 0x81A5 -#define GL_DEPTH_COMPONENT24 0x81A6 -#define GL_DEPTH_COMPONENT32 0x81A7 -#define GL_MIRRORED_REPEAT 0x8370 -#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD -#define GL_TEXTURE_LOD_BIAS 0x8501 -#define GL_INCR_WRAP 0x8507 -#define GL_DECR_WRAP 0x8508 -#define GL_TEXTURE_DEPTH_SIZE 0x884A -#define GL_TEXTURE_COMPARE_MODE 0x884C -#define GL_TEXTURE_COMPARE_FUNC 0x884D -#define GL_POINT_SIZE_MIN 0x8126 -#define GL_POINT_SIZE_MAX 0x8127 -#define GL_POINT_DISTANCE_ATTENUATION 0x8129 -#define GL_GENERATE_MIPMAP 0x8191 -#define GL_GENERATE_MIPMAP_HINT 0x8192 -#define GL_FOG_COORDINATE_SOURCE 0x8450 -#define GL_FOG_COORDINATE 0x8451 -#define GL_FRAGMENT_DEPTH 0x8452 -#define GL_CURRENT_FOG_COORDINATE 0x8453 -#define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454 -#define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455 -#define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456 -#define GL_FOG_COORDINATE_ARRAY 0x8457 -#define GL_COLOR_SUM 0x8458 -#define GL_CURRENT_SECONDARY_COLOR 0x8459 -#define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A -#define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B -#define GL_SECONDARY_COLOR_ARRAY_STRIDE 0x845C -#define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D -#define GL_SECONDARY_COLOR_ARRAY 0x845E -#define GL_TEXTURE_FILTER_CONTROL 0x8500 -#define GL_DEPTH_TEXTURE_MODE 0x884B -#define GL_COMPARE_R_TO_TEXTURE 0x884E -#define GL_BLEND_COLOR 0x8005 -#define GL_BLEND_EQUATION 0x8009 -#define GL_CONSTANT_COLOR 0x8001 -#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 -#define GL_CONSTANT_ALPHA 0x8003 -#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 -#define GL_FUNC_ADD 0x8006 -#define GL_FUNC_REVERSE_SUBTRACT 0x800B -#define GL_FUNC_SUBTRACT 0x800A -#define GL_MIN 0x8007 -#define GL_MAX 0x8008 -#define GL_BUFFER_SIZE 0x8764 -#define GL_BUFFER_USAGE 0x8765 -#define GL_QUERY_COUNTER_BITS 0x8864 -#define GL_CURRENT_QUERY 0x8865 -#define GL_QUERY_RESULT 0x8866 -#define GL_QUERY_RESULT_AVAILABLE 0x8867 -#define GL_ARRAY_BUFFER 0x8892 -#define GL_ELEMENT_ARRAY_BUFFER 0x8893 -#define GL_ARRAY_BUFFER_BINDING 0x8894 -#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 -#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F -#define GL_READ_ONLY 0x88B8 -#define GL_WRITE_ONLY 0x88B9 -#define GL_READ_WRITE 0x88BA -#define GL_BUFFER_ACCESS 0x88BB -#define GL_BUFFER_MAPPED 0x88BC -#define GL_BUFFER_MAP_POINTER 0x88BD -#define GL_STREAM_DRAW 0x88E0 -#define GL_STREAM_READ 0x88E1 -#define GL_STREAM_COPY 0x88E2 -#define GL_STATIC_DRAW 0x88E4 -#define GL_STATIC_READ 0x88E5 -#define GL_STATIC_COPY 0x88E6 -#define GL_DYNAMIC_DRAW 0x88E8 -#define GL_DYNAMIC_READ 0x88E9 -#define GL_DYNAMIC_COPY 0x88EA -#define GL_SAMPLES_PASSED 0x8914 -#define GL_SRC1_ALPHA 0x8589 -#define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 -#define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897 -#define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898 -#define GL_INDEX_ARRAY_BUFFER_BINDING 0x8899 -#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A -#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B -#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C -#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D -#define GL_WEIGHT_ARRAY_BUFFER_BINDING 0x889E -#define GL_FOG_COORD_SRC 0x8450 -#define GL_FOG_COORD 0x8451 -#define GL_CURRENT_FOG_COORD 0x8453 -#define GL_FOG_COORD_ARRAY_TYPE 0x8454 -#define GL_FOG_COORD_ARRAY_STRIDE 0x8455 -#define GL_FOG_COORD_ARRAY_POINTER 0x8456 -#define GL_FOG_COORD_ARRAY 0x8457 -#define GL_FOG_COORD_ARRAY_BUFFER_BINDING 0x889D -#define GL_SRC0_RGB 0x8580 -#define GL_SRC1_RGB 0x8581 -#define GL_SRC2_RGB 0x8582 -#define GL_SRC0_ALPHA 0x8588 -#define GL_SRC2_ALPHA 0x858A -#define GL_BLEND_EQUATION_RGB 0x8009 -#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 -#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 -#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 -#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 -#define GL_CURRENT_VERTEX_ATTRIB 0x8626 -#define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642 -#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 -#define GL_STENCIL_BACK_FUNC 0x8800 -#define GL_STENCIL_BACK_FAIL 0x8801 -#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 -#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 -#define GL_MAX_DRAW_BUFFERS 0x8824 -#define GL_DRAW_BUFFER0 0x8825 -#define GL_DRAW_BUFFER1 0x8826 -#define GL_DRAW_BUFFER2 0x8827 -#define GL_DRAW_BUFFER3 0x8828 -#define GL_DRAW_BUFFER4 0x8829 -#define GL_DRAW_BUFFER5 0x882A -#define GL_DRAW_BUFFER6 0x882B -#define GL_DRAW_BUFFER7 0x882C -#define GL_DRAW_BUFFER8 0x882D -#define GL_DRAW_BUFFER9 0x882E -#define GL_DRAW_BUFFER10 0x882F -#define GL_DRAW_BUFFER11 0x8830 -#define GL_DRAW_BUFFER12 0x8831 -#define GL_DRAW_BUFFER13 0x8832 -#define GL_DRAW_BUFFER14 0x8833 -#define GL_DRAW_BUFFER15 0x8834 -#define GL_BLEND_EQUATION_ALPHA 0x883D -#define GL_MAX_VERTEX_ATTRIBS 0x8869 -#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A -#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 -#define GL_FRAGMENT_SHADER 0x8B30 -#define GL_VERTEX_SHADER 0x8B31 -#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 -#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A -#define GL_MAX_VARYING_FLOATS 0x8B4B -#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C -#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D -#define GL_SHADER_TYPE 0x8B4F -#define GL_FLOAT_VEC2 0x8B50 -#define GL_FLOAT_VEC3 0x8B51 -#define GL_FLOAT_VEC4 0x8B52 -#define GL_INT_VEC2 0x8B53 -#define GL_INT_VEC3 0x8B54 -#define GL_INT_VEC4 0x8B55 -#define GL_BOOL 0x8B56 -#define GL_BOOL_VEC2 0x8B57 -#define GL_BOOL_VEC3 0x8B58 -#define GL_BOOL_VEC4 0x8B59 -#define GL_FLOAT_MAT2 0x8B5A -#define GL_FLOAT_MAT3 0x8B5B -#define GL_FLOAT_MAT4 0x8B5C -#define GL_SAMPLER_1D 0x8B5D -#define GL_SAMPLER_2D 0x8B5E -#define GL_SAMPLER_3D 0x8B5F -#define GL_SAMPLER_CUBE 0x8B60 -#define GL_SAMPLER_1D_SHADOW 0x8B61 -#define GL_SAMPLER_2D_SHADOW 0x8B62 -#define GL_DELETE_STATUS 0x8B80 -#define GL_COMPILE_STATUS 0x8B81 -#define GL_LINK_STATUS 0x8B82 -#define GL_VALIDATE_STATUS 0x8B83 -#define GL_INFO_LOG_LENGTH 0x8B84 -#define GL_ATTACHED_SHADERS 0x8B85 -#define GL_ACTIVE_UNIFORMS 0x8B86 -#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 -#define GL_SHADER_SOURCE_LENGTH 0x8B88 -#define GL_ACTIVE_ATTRIBUTES 0x8B89 -#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A -#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B -#define GL_SHADING_LANGUAGE_VERSION 0x8B8C -#define GL_CURRENT_PROGRAM 0x8B8D -#define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0 -#define GL_LOWER_LEFT 0x8CA1 -#define GL_UPPER_LEFT 0x8CA2 -#define GL_STENCIL_BACK_REF 0x8CA3 -#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 -#define GL_STENCIL_BACK_WRITEMASK 0x8CA5 -#define GL_VERTEX_PROGRAM_TWO_SIDE 0x8643 -#define GL_POINT_SPRITE 0x8861 -#define GL_COORD_REPLACE 0x8862 -#define GL_MAX_TEXTURE_COORDS 0x8871 -#define GL_PIXEL_PACK_BUFFER 0x88EB -#define GL_PIXEL_UNPACK_BUFFER 0x88EC -#define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED -#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF -#define GL_FLOAT_MAT2x3 0x8B65 -#define GL_FLOAT_MAT2x4 0x8B66 -#define GL_FLOAT_MAT3x2 0x8B67 -#define GL_FLOAT_MAT3x4 0x8B68 -#define GL_FLOAT_MAT4x2 0x8B69 -#define GL_FLOAT_MAT4x3 0x8B6A -#define GL_SRGB 0x8C40 -#define GL_SRGB8 0x8C41 -#define GL_SRGB_ALPHA 0x8C42 -#define GL_SRGB8_ALPHA8 0x8C43 -#define GL_COMPRESSED_SRGB 0x8C48 -#define GL_COMPRESSED_SRGB_ALPHA 0x8C49 -#define GL_CURRENT_RASTER_SECONDARY_COLOR 0x845F -#define GL_SLUMINANCE_ALPHA 0x8C44 -#define GL_SLUMINANCE8_ALPHA8 0x8C45 -#define GL_SLUMINANCE 0x8C46 -#define GL_SLUMINANCE8 0x8C47 -#define GL_COMPRESSED_SLUMINANCE 0x8C4A -#define GL_COMPRESSED_SLUMINANCE_ALPHA 0x8C4B -#ifndef GL_VERSION_1_0 -#define GL_VERSION_1_0 1 -GLAPI int GLAD_GL_VERSION_1_0; -typedef void (APIENTRYP PFNGLCULLFACEPROC)(GLenum mode); -GLAPI PFNGLCULLFACEPROC glad_glCullFace; -#define glCullFace glad_glCullFace -typedef void (APIENTRYP PFNGLFRONTFACEPROC)(GLenum mode); -GLAPI PFNGLFRONTFACEPROC glad_glFrontFace; -#define glFrontFace glad_glFrontFace -typedef void (APIENTRYP PFNGLHINTPROC)(GLenum target, GLenum mode); -GLAPI PFNGLHINTPROC glad_glHint; -#define glHint glad_glHint -typedef void (APIENTRYP PFNGLLINEWIDTHPROC)(GLfloat width); -GLAPI PFNGLLINEWIDTHPROC glad_glLineWidth; -#define glLineWidth glad_glLineWidth -typedef void (APIENTRYP PFNGLPOINTSIZEPROC)(GLfloat size); -GLAPI PFNGLPOINTSIZEPROC glad_glPointSize; -#define glPointSize glad_glPointSize -typedef void (APIENTRYP PFNGLPOLYGONMODEPROC)(GLenum face, GLenum mode); -GLAPI PFNGLPOLYGONMODEPROC glad_glPolygonMode; -#define glPolygonMode glad_glPolygonMode -typedef void (APIENTRYP PFNGLSCISSORPROC)(GLint x, GLint y, GLsizei width, GLsizei height); -GLAPI PFNGLSCISSORPROC glad_glScissor; -#define glScissor glad_glScissor -typedef void (APIENTRYP PFNGLTEXPARAMETERFPROC)(GLenum target, GLenum pname, GLfloat param); -GLAPI PFNGLTEXPARAMETERFPROC glad_glTexParameterf; -#define glTexParameterf glad_glTexParameterf -typedef void (APIENTRYP PFNGLTEXPARAMETERFVPROC)(GLenum target, GLenum pname, const GLfloat *params); -GLAPI PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv; -#define glTexParameterfv glad_glTexParameterfv -typedef void (APIENTRYP PFNGLTEXPARAMETERIPROC)(GLenum target, GLenum pname, GLint param); -GLAPI PFNGLTEXPARAMETERIPROC glad_glTexParameteri; -#define glTexParameteri glad_glTexParameteri -typedef void (APIENTRYP PFNGLTEXPARAMETERIVPROC)(GLenum target, GLenum pname, const GLint *params); -GLAPI PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv; -#define glTexParameteriv glad_glTexParameteriv -typedef void (APIENTRYP PFNGLTEXIMAGE1DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); -GLAPI PFNGLTEXIMAGE1DPROC glad_glTexImage1D; -#define glTexImage1D glad_glTexImage1D -typedef void (APIENTRYP PFNGLTEXIMAGE2DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); -GLAPI PFNGLTEXIMAGE2DPROC glad_glTexImage2D; -#define glTexImage2D glad_glTexImage2D -typedef void (APIENTRYP PFNGLDRAWBUFFERPROC)(GLenum buf); -GLAPI PFNGLDRAWBUFFERPROC glad_glDrawBuffer; -#define glDrawBuffer glad_glDrawBuffer -typedef void (APIENTRYP PFNGLCLEARPROC)(GLbitfield mask); -GLAPI PFNGLCLEARPROC glad_glClear; -#define glClear glad_glClear -typedef void (APIENTRYP PFNGLCLEARCOLORPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); -GLAPI PFNGLCLEARCOLORPROC glad_glClearColor; -#define glClearColor glad_glClearColor -typedef void (APIENTRYP PFNGLCLEARSTENCILPROC)(GLint s); -GLAPI PFNGLCLEARSTENCILPROC glad_glClearStencil; -#define glClearStencil glad_glClearStencil -typedef void (APIENTRYP PFNGLCLEARDEPTHPROC)(GLdouble depth); -GLAPI PFNGLCLEARDEPTHPROC glad_glClearDepth; -#define glClearDepth glad_glClearDepth -typedef void (APIENTRYP PFNGLSTENCILMASKPROC)(GLuint mask); -GLAPI PFNGLSTENCILMASKPROC glad_glStencilMask; -#define glStencilMask glad_glStencilMask -typedef void (APIENTRYP PFNGLCOLORMASKPROC)(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); -GLAPI PFNGLCOLORMASKPROC glad_glColorMask; -#define glColorMask glad_glColorMask -typedef void (APIENTRYP PFNGLDEPTHMASKPROC)(GLboolean flag); -GLAPI PFNGLDEPTHMASKPROC glad_glDepthMask; -#define glDepthMask glad_glDepthMask -typedef void (APIENTRYP PFNGLDISABLEPROC)(GLenum cap); -GLAPI PFNGLDISABLEPROC glad_glDisable; -#define glDisable glad_glDisable -typedef void (APIENTRYP PFNGLENABLEPROC)(GLenum cap); -GLAPI PFNGLENABLEPROC glad_glEnable; -#define glEnable glad_glEnable -typedef void (APIENTRYP PFNGLFINISHPROC)(void); -GLAPI PFNGLFINISHPROC glad_glFinish; -#define glFinish glad_glFinish -typedef void (APIENTRYP PFNGLFLUSHPROC)(void); -GLAPI PFNGLFLUSHPROC glad_glFlush; -#define glFlush glad_glFlush -typedef void (APIENTRYP PFNGLBLENDFUNCPROC)(GLenum sfactor, GLenum dfactor); -GLAPI PFNGLBLENDFUNCPROC glad_glBlendFunc; -#define glBlendFunc glad_glBlendFunc -typedef void (APIENTRYP PFNGLLOGICOPPROC)(GLenum opcode); -GLAPI PFNGLLOGICOPPROC glad_glLogicOp; -#define glLogicOp glad_glLogicOp -typedef void (APIENTRYP PFNGLSTENCILFUNCPROC)(GLenum func, GLint ref, GLuint mask); -GLAPI PFNGLSTENCILFUNCPROC glad_glStencilFunc; -#define glStencilFunc glad_glStencilFunc -typedef void (APIENTRYP PFNGLSTENCILOPPROC)(GLenum fail, GLenum zfail, GLenum zpass); -GLAPI PFNGLSTENCILOPPROC glad_glStencilOp; -#define glStencilOp glad_glStencilOp -typedef void (APIENTRYP PFNGLDEPTHFUNCPROC)(GLenum func); -GLAPI PFNGLDEPTHFUNCPROC glad_glDepthFunc; -#define glDepthFunc glad_glDepthFunc -typedef void (APIENTRYP PFNGLPIXELSTOREFPROC)(GLenum pname, GLfloat param); -GLAPI PFNGLPIXELSTOREFPROC glad_glPixelStoref; -#define glPixelStoref glad_glPixelStoref -typedef void (APIENTRYP PFNGLPIXELSTOREIPROC)(GLenum pname, GLint param); -GLAPI PFNGLPIXELSTOREIPROC glad_glPixelStorei; -#define glPixelStorei glad_glPixelStorei -typedef void (APIENTRYP PFNGLREADBUFFERPROC)(GLenum src); -GLAPI PFNGLREADBUFFERPROC glad_glReadBuffer; -#define glReadBuffer glad_glReadBuffer -typedef void (APIENTRYP PFNGLREADPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); -GLAPI PFNGLREADPIXELSPROC glad_glReadPixels; -#define glReadPixels glad_glReadPixels -typedef void (APIENTRYP PFNGLGETBOOLEANVPROC)(GLenum pname, GLboolean *data); -GLAPI PFNGLGETBOOLEANVPROC glad_glGetBooleanv; -#define glGetBooleanv glad_glGetBooleanv -typedef void (APIENTRYP PFNGLGETDOUBLEVPROC)(GLenum pname, GLdouble *data); -GLAPI PFNGLGETDOUBLEVPROC glad_glGetDoublev; -#define glGetDoublev glad_glGetDoublev -typedef GLenum (APIENTRYP PFNGLGETERRORPROC)(void); -GLAPI PFNGLGETERRORPROC glad_glGetError; -#define glGetError glad_glGetError -typedef void (APIENTRYP PFNGLGETFLOATVPROC)(GLenum pname, GLfloat *data); -GLAPI PFNGLGETFLOATVPROC glad_glGetFloatv; -#define glGetFloatv glad_glGetFloatv -typedef void (APIENTRYP PFNGLGETINTEGERVPROC)(GLenum pname, GLint *data); -GLAPI PFNGLGETINTEGERVPROC glad_glGetIntegerv; -#define glGetIntegerv glad_glGetIntegerv -typedef const GLubyte * (APIENTRYP PFNGLGETSTRINGPROC)(GLenum name); -GLAPI PFNGLGETSTRINGPROC glad_glGetString; -#define glGetString glad_glGetString -typedef void (APIENTRYP PFNGLGETTEXIMAGEPROC)(GLenum target, GLint level, GLenum format, GLenum type, void *pixels); -GLAPI PFNGLGETTEXIMAGEPROC glad_glGetTexImage; -#define glGetTexImage glad_glGetTexImage -typedef void (APIENTRYP PFNGLGETTEXPARAMETERFVPROC)(GLenum target, GLenum pname, GLfloat *params); -GLAPI PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv; -#define glGetTexParameterfv glad_glGetTexParameterfv -typedef void (APIENTRYP PFNGLGETTEXPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); -GLAPI PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv; -#define glGetTexParameteriv glad_glGetTexParameteriv -typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERFVPROC)(GLenum target, GLint level, GLenum pname, GLfloat *params); -GLAPI PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv; -#define glGetTexLevelParameterfv glad_glGetTexLevelParameterfv -typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERIVPROC)(GLenum target, GLint level, GLenum pname, GLint *params); -GLAPI PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv; -#define glGetTexLevelParameteriv glad_glGetTexLevelParameteriv -typedef GLboolean (APIENTRYP PFNGLISENABLEDPROC)(GLenum cap); -GLAPI PFNGLISENABLEDPROC glad_glIsEnabled; -#define glIsEnabled glad_glIsEnabled -typedef void (APIENTRYP PFNGLDEPTHRANGEPROC)(GLdouble n, GLdouble f); -GLAPI PFNGLDEPTHRANGEPROC glad_glDepthRange; -#define glDepthRange glad_glDepthRange -typedef void (APIENTRYP PFNGLVIEWPORTPROC)(GLint x, GLint y, GLsizei width, GLsizei height); -GLAPI PFNGLVIEWPORTPROC glad_glViewport; -#define glViewport glad_glViewport -typedef void (APIENTRYP PFNGLNEWLISTPROC)(GLuint list, GLenum mode); -GLAPI PFNGLNEWLISTPROC glad_glNewList; -#define glNewList glad_glNewList -typedef void (APIENTRYP PFNGLENDLISTPROC)(void); -GLAPI PFNGLENDLISTPROC glad_glEndList; -#define glEndList glad_glEndList -typedef void (APIENTRYP PFNGLCALLLISTPROC)(GLuint list); -GLAPI PFNGLCALLLISTPROC glad_glCallList; -#define glCallList glad_glCallList -typedef void (APIENTRYP PFNGLCALLLISTSPROC)(GLsizei n, GLenum type, const void *lists); -GLAPI PFNGLCALLLISTSPROC glad_glCallLists; -#define glCallLists glad_glCallLists -typedef void (APIENTRYP PFNGLDELETELISTSPROC)(GLuint list, GLsizei range); -GLAPI PFNGLDELETELISTSPROC glad_glDeleteLists; -#define glDeleteLists glad_glDeleteLists -typedef GLuint (APIENTRYP PFNGLGENLISTSPROC)(GLsizei range); -GLAPI PFNGLGENLISTSPROC glad_glGenLists; -#define glGenLists glad_glGenLists -typedef void (APIENTRYP PFNGLLISTBASEPROC)(GLuint base); -GLAPI PFNGLLISTBASEPROC glad_glListBase; -#define glListBase glad_glListBase -typedef void (APIENTRYP PFNGLBEGINPROC)(GLenum mode); -GLAPI PFNGLBEGINPROC glad_glBegin; -#define glBegin glad_glBegin -typedef void (APIENTRYP PFNGLBITMAPPROC)(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap); -GLAPI PFNGLBITMAPPROC glad_glBitmap; -#define glBitmap glad_glBitmap -typedef void (APIENTRYP PFNGLCOLOR3BPROC)(GLbyte red, GLbyte green, GLbyte blue); -GLAPI PFNGLCOLOR3BPROC glad_glColor3b; -#define glColor3b glad_glColor3b -typedef void (APIENTRYP PFNGLCOLOR3BVPROC)(const GLbyte *v); -GLAPI PFNGLCOLOR3BVPROC glad_glColor3bv; -#define glColor3bv glad_glColor3bv -typedef void (APIENTRYP PFNGLCOLOR3DPROC)(GLdouble red, GLdouble green, GLdouble blue); -GLAPI PFNGLCOLOR3DPROC glad_glColor3d; -#define glColor3d glad_glColor3d -typedef void (APIENTRYP PFNGLCOLOR3DVPROC)(const GLdouble *v); -GLAPI PFNGLCOLOR3DVPROC glad_glColor3dv; -#define glColor3dv glad_glColor3dv -typedef void (APIENTRYP PFNGLCOLOR3FPROC)(GLfloat red, GLfloat green, GLfloat blue); -GLAPI PFNGLCOLOR3FPROC glad_glColor3f; -#define glColor3f glad_glColor3f -typedef void (APIENTRYP PFNGLCOLOR3FVPROC)(const GLfloat *v); -GLAPI PFNGLCOLOR3FVPROC glad_glColor3fv; -#define glColor3fv glad_glColor3fv -typedef void (APIENTRYP PFNGLCOLOR3IPROC)(GLint red, GLint green, GLint blue); -GLAPI PFNGLCOLOR3IPROC glad_glColor3i; -#define glColor3i glad_glColor3i -typedef void (APIENTRYP PFNGLCOLOR3IVPROC)(const GLint *v); -GLAPI PFNGLCOLOR3IVPROC glad_glColor3iv; -#define glColor3iv glad_glColor3iv -typedef void (APIENTRYP PFNGLCOLOR3SPROC)(GLshort red, GLshort green, GLshort blue); -GLAPI PFNGLCOLOR3SPROC glad_glColor3s; -#define glColor3s glad_glColor3s -typedef void (APIENTRYP PFNGLCOLOR3SVPROC)(const GLshort *v); -GLAPI PFNGLCOLOR3SVPROC glad_glColor3sv; -#define glColor3sv glad_glColor3sv -typedef void (APIENTRYP PFNGLCOLOR3UBPROC)(GLubyte red, GLubyte green, GLubyte blue); -GLAPI PFNGLCOLOR3UBPROC glad_glColor3ub; -#define glColor3ub glad_glColor3ub -typedef void (APIENTRYP PFNGLCOLOR3UBVPROC)(const GLubyte *v); -GLAPI PFNGLCOLOR3UBVPROC glad_glColor3ubv; -#define glColor3ubv glad_glColor3ubv -typedef void (APIENTRYP PFNGLCOLOR3UIPROC)(GLuint red, GLuint green, GLuint blue); -GLAPI PFNGLCOLOR3UIPROC glad_glColor3ui; -#define glColor3ui glad_glColor3ui -typedef void (APIENTRYP PFNGLCOLOR3UIVPROC)(const GLuint *v); -GLAPI PFNGLCOLOR3UIVPROC glad_glColor3uiv; -#define glColor3uiv glad_glColor3uiv -typedef void (APIENTRYP PFNGLCOLOR3USPROC)(GLushort red, GLushort green, GLushort blue); -GLAPI PFNGLCOLOR3USPROC glad_glColor3us; -#define glColor3us glad_glColor3us -typedef void (APIENTRYP PFNGLCOLOR3USVPROC)(const GLushort *v); -GLAPI PFNGLCOLOR3USVPROC glad_glColor3usv; -#define glColor3usv glad_glColor3usv -typedef void (APIENTRYP PFNGLCOLOR4BPROC)(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha); -GLAPI PFNGLCOLOR4BPROC glad_glColor4b; -#define glColor4b glad_glColor4b -typedef void (APIENTRYP PFNGLCOLOR4BVPROC)(const GLbyte *v); -GLAPI PFNGLCOLOR4BVPROC glad_glColor4bv; -#define glColor4bv glad_glColor4bv -typedef void (APIENTRYP PFNGLCOLOR4DPROC)(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha); -GLAPI PFNGLCOLOR4DPROC glad_glColor4d; -#define glColor4d glad_glColor4d -typedef void (APIENTRYP PFNGLCOLOR4DVPROC)(const GLdouble *v); -GLAPI PFNGLCOLOR4DVPROC glad_glColor4dv; -#define glColor4dv glad_glColor4dv -typedef void (APIENTRYP PFNGLCOLOR4FPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); -GLAPI PFNGLCOLOR4FPROC glad_glColor4f; -#define glColor4f glad_glColor4f -typedef void (APIENTRYP PFNGLCOLOR4FVPROC)(const GLfloat *v); -GLAPI PFNGLCOLOR4FVPROC glad_glColor4fv; -#define glColor4fv glad_glColor4fv -typedef void (APIENTRYP PFNGLCOLOR4IPROC)(GLint red, GLint green, GLint blue, GLint alpha); -GLAPI PFNGLCOLOR4IPROC glad_glColor4i; -#define glColor4i glad_glColor4i -typedef void (APIENTRYP PFNGLCOLOR4IVPROC)(const GLint *v); -GLAPI PFNGLCOLOR4IVPROC glad_glColor4iv; -#define glColor4iv glad_glColor4iv -typedef void (APIENTRYP PFNGLCOLOR4SPROC)(GLshort red, GLshort green, GLshort blue, GLshort alpha); -GLAPI PFNGLCOLOR4SPROC glad_glColor4s; -#define glColor4s glad_glColor4s -typedef void (APIENTRYP PFNGLCOLOR4SVPROC)(const GLshort *v); -GLAPI PFNGLCOLOR4SVPROC glad_glColor4sv; -#define glColor4sv glad_glColor4sv -typedef void (APIENTRYP PFNGLCOLOR4UBPROC)(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha); -GLAPI PFNGLCOLOR4UBPROC glad_glColor4ub; -#define glColor4ub glad_glColor4ub -typedef void (APIENTRYP PFNGLCOLOR4UBVPROC)(const GLubyte *v); -GLAPI PFNGLCOLOR4UBVPROC glad_glColor4ubv; -#define glColor4ubv glad_glColor4ubv -typedef void (APIENTRYP PFNGLCOLOR4UIPROC)(GLuint red, GLuint green, GLuint blue, GLuint alpha); -GLAPI PFNGLCOLOR4UIPROC glad_glColor4ui; -#define glColor4ui glad_glColor4ui -typedef void (APIENTRYP PFNGLCOLOR4UIVPROC)(const GLuint *v); -GLAPI PFNGLCOLOR4UIVPROC glad_glColor4uiv; -#define glColor4uiv glad_glColor4uiv -typedef void (APIENTRYP PFNGLCOLOR4USPROC)(GLushort red, GLushort green, GLushort blue, GLushort alpha); -GLAPI PFNGLCOLOR4USPROC glad_glColor4us; -#define glColor4us glad_glColor4us -typedef void (APIENTRYP PFNGLCOLOR4USVPROC)(const GLushort *v); -GLAPI PFNGLCOLOR4USVPROC glad_glColor4usv; -#define glColor4usv glad_glColor4usv -typedef void (APIENTRYP PFNGLEDGEFLAGPROC)(GLboolean flag); -GLAPI PFNGLEDGEFLAGPROC glad_glEdgeFlag; -#define glEdgeFlag glad_glEdgeFlag -typedef void (APIENTRYP PFNGLEDGEFLAGVPROC)(const GLboolean *flag); -GLAPI PFNGLEDGEFLAGVPROC glad_glEdgeFlagv; -#define glEdgeFlagv glad_glEdgeFlagv -typedef void (APIENTRYP PFNGLENDPROC)(void); -GLAPI PFNGLENDPROC glad_glEnd; -#define glEnd glad_glEnd -typedef void (APIENTRYP PFNGLINDEXDPROC)(GLdouble c); -GLAPI PFNGLINDEXDPROC glad_glIndexd; -#define glIndexd glad_glIndexd -typedef void (APIENTRYP PFNGLINDEXDVPROC)(const GLdouble *c); -GLAPI PFNGLINDEXDVPROC glad_glIndexdv; -#define glIndexdv glad_glIndexdv -typedef void (APIENTRYP PFNGLINDEXFPROC)(GLfloat c); -GLAPI PFNGLINDEXFPROC glad_glIndexf; -#define glIndexf glad_glIndexf -typedef void (APIENTRYP PFNGLINDEXFVPROC)(const GLfloat *c); -GLAPI PFNGLINDEXFVPROC glad_glIndexfv; -#define glIndexfv glad_glIndexfv -typedef void (APIENTRYP PFNGLINDEXIPROC)(GLint c); -GLAPI PFNGLINDEXIPROC glad_glIndexi; -#define glIndexi glad_glIndexi -typedef void (APIENTRYP PFNGLINDEXIVPROC)(const GLint *c); -GLAPI PFNGLINDEXIVPROC glad_glIndexiv; -#define glIndexiv glad_glIndexiv -typedef void (APIENTRYP PFNGLINDEXSPROC)(GLshort c); -GLAPI PFNGLINDEXSPROC glad_glIndexs; -#define glIndexs glad_glIndexs -typedef void (APIENTRYP PFNGLINDEXSVPROC)(const GLshort *c); -GLAPI PFNGLINDEXSVPROC glad_glIndexsv; -#define glIndexsv glad_glIndexsv -typedef void (APIENTRYP PFNGLNORMAL3BPROC)(GLbyte nx, GLbyte ny, GLbyte nz); -GLAPI PFNGLNORMAL3BPROC glad_glNormal3b; -#define glNormal3b glad_glNormal3b -typedef void (APIENTRYP PFNGLNORMAL3BVPROC)(const GLbyte *v); -GLAPI PFNGLNORMAL3BVPROC glad_glNormal3bv; -#define glNormal3bv glad_glNormal3bv -typedef void (APIENTRYP PFNGLNORMAL3DPROC)(GLdouble nx, GLdouble ny, GLdouble nz); -GLAPI PFNGLNORMAL3DPROC glad_glNormal3d; -#define glNormal3d glad_glNormal3d -typedef void (APIENTRYP PFNGLNORMAL3DVPROC)(const GLdouble *v); -GLAPI PFNGLNORMAL3DVPROC glad_glNormal3dv; -#define glNormal3dv glad_glNormal3dv -typedef void (APIENTRYP PFNGLNORMAL3FPROC)(GLfloat nx, GLfloat ny, GLfloat nz); -GLAPI PFNGLNORMAL3FPROC glad_glNormal3f; -#define glNormal3f glad_glNormal3f -typedef void (APIENTRYP PFNGLNORMAL3FVPROC)(const GLfloat *v); -GLAPI PFNGLNORMAL3FVPROC glad_glNormal3fv; -#define glNormal3fv glad_glNormal3fv -typedef void (APIENTRYP PFNGLNORMAL3IPROC)(GLint nx, GLint ny, GLint nz); -GLAPI PFNGLNORMAL3IPROC glad_glNormal3i; -#define glNormal3i glad_glNormal3i -typedef void (APIENTRYP PFNGLNORMAL3IVPROC)(const GLint *v); -GLAPI PFNGLNORMAL3IVPROC glad_glNormal3iv; -#define glNormal3iv glad_glNormal3iv -typedef void (APIENTRYP PFNGLNORMAL3SPROC)(GLshort nx, GLshort ny, GLshort nz); -GLAPI PFNGLNORMAL3SPROC glad_glNormal3s; -#define glNormal3s glad_glNormal3s -typedef void (APIENTRYP PFNGLNORMAL3SVPROC)(const GLshort *v); -GLAPI PFNGLNORMAL3SVPROC glad_glNormal3sv; -#define glNormal3sv glad_glNormal3sv -typedef void (APIENTRYP PFNGLRASTERPOS2DPROC)(GLdouble x, GLdouble y); -GLAPI PFNGLRASTERPOS2DPROC glad_glRasterPos2d; -#define glRasterPos2d glad_glRasterPos2d -typedef void (APIENTRYP PFNGLRASTERPOS2DVPROC)(const GLdouble *v); -GLAPI PFNGLRASTERPOS2DVPROC glad_glRasterPos2dv; -#define glRasterPos2dv glad_glRasterPos2dv -typedef void (APIENTRYP PFNGLRASTERPOS2FPROC)(GLfloat x, GLfloat y); -GLAPI PFNGLRASTERPOS2FPROC glad_glRasterPos2f; -#define glRasterPos2f glad_glRasterPos2f -typedef void (APIENTRYP PFNGLRASTERPOS2FVPROC)(const GLfloat *v); -GLAPI PFNGLRASTERPOS2FVPROC glad_glRasterPos2fv; -#define glRasterPos2fv glad_glRasterPos2fv -typedef void (APIENTRYP PFNGLRASTERPOS2IPROC)(GLint x, GLint y); -GLAPI PFNGLRASTERPOS2IPROC glad_glRasterPos2i; -#define glRasterPos2i glad_glRasterPos2i -typedef void (APIENTRYP PFNGLRASTERPOS2IVPROC)(const GLint *v); -GLAPI PFNGLRASTERPOS2IVPROC glad_glRasterPos2iv; -#define glRasterPos2iv glad_glRasterPos2iv -typedef void (APIENTRYP PFNGLRASTERPOS2SPROC)(GLshort x, GLshort y); -GLAPI PFNGLRASTERPOS2SPROC glad_glRasterPos2s; -#define glRasterPos2s glad_glRasterPos2s -typedef void (APIENTRYP PFNGLRASTERPOS2SVPROC)(const GLshort *v); -GLAPI PFNGLRASTERPOS2SVPROC glad_glRasterPos2sv; -#define glRasterPos2sv glad_glRasterPos2sv -typedef void (APIENTRYP PFNGLRASTERPOS3DPROC)(GLdouble x, GLdouble y, GLdouble z); -GLAPI PFNGLRASTERPOS3DPROC glad_glRasterPos3d; -#define glRasterPos3d glad_glRasterPos3d -typedef void (APIENTRYP PFNGLRASTERPOS3DVPROC)(const GLdouble *v); -GLAPI PFNGLRASTERPOS3DVPROC glad_glRasterPos3dv; -#define glRasterPos3dv glad_glRasterPos3dv -typedef void (APIENTRYP PFNGLRASTERPOS3FPROC)(GLfloat x, GLfloat y, GLfloat z); -GLAPI PFNGLRASTERPOS3FPROC glad_glRasterPos3f; -#define glRasterPos3f glad_glRasterPos3f -typedef void (APIENTRYP PFNGLRASTERPOS3FVPROC)(const GLfloat *v); -GLAPI PFNGLRASTERPOS3FVPROC glad_glRasterPos3fv; -#define glRasterPos3fv glad_glRasterPos3fv -typedef void (APIENTRYP PFNGLRASTERPOS3IPROC)(GLint x, GLint y, GLint z); -GLAPI PFNGLRASTERPOS3IPROC glad_glRasterPos3i; -#define glRasterPos3i glad_glRasterPos3i -typedef void (APIENTRYP PFNGLRASTERPOS3IVPROC)(const GLint *v); -GLAPI PFNGLRASTERPOS3IVPROC glad_glRasterPos3iv; -#define glRasterPos3iv glad_glRasterPos3iv -typedef void (APIENTRYP PFNGLRASTERPOS3SPROC)(GLshort x, GLshort y, GLshort z); -GLAPI PFNGLRASTERPOS3SPROC glad_glRasterPos3s; -#define glRasterPos3s glad_glRasterPos3s -typedef void (APIENTRYP PFNGLRASTERPOS3SVPROC)(const GLshort *v); -GLAPI PFNGLRASTERPOS3SVPROC glad_glRasterPos3sv; -#define glRasterPos3sv glad_glRasterPos3sv -typedef void (APIENTRYP PFNGLRASTERPOS4DPROC)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); -GLAPI PFNGLRASTERPOS4DPROC glad_glRasterPos4d; -#define glRasterPos4d glad_glRasterPos4d -typedef void (APIENTRYP PFNGLRASTERPOS4DVPROC)(const GLdouble *v); -GLAPI PFNGLRASTERPOS4DVPROC glad_glRasterPos4dv; -#define glRasterPos4dv glad_glRasterPos4dv -typedef void (APIENTRYP PFNGLRASTERPOS4FPROC)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); -GLAPI PFNGLRASTERPOS4FPROC glad_glRasterPos4f; -#define glRasterPos4f glad_glRasterPos4f -typedef void (APIENTRYP PFNGLRASTERPOS4FVPROC)(const GLfloat *v); -GLAPI PFNGLRASTERPOS4FVPROC glad_glRasterPos4fv; -#define glRasterPos4fv glad_glRasterPos4fv -typedef void (APIENTRYP PFNGLRASTERPOS4IPROC)(GLint x, GLint y, GLint z, GLint w); -GLAPI PFNGLRASTERPOS4IPROC glad_glRasterPos4i; -#define glRasterPos4i glad_glRasterPos4i -typedef void (APIENTRYP PFNGLRASTERPOS4IVPROC)(const GLint *v); -GLAPI PFNGLRASTERPOS4IVPROC glad_glRasterPos4iv; -#define glRasterPos4iv glad_glRasterPos4iv -typedef void (APIENTRYP PFNGLRASTERPOS4SPROC)(GLshort x, GLshort y, GLshort z, GLshort w); -GLAPI PFNGLRASTERPOS4SPROC glad_glRasterPos4s; -#define glRasterPos4s glad_glRasterPos4s -typedef void (APIENTRYP PFNGLRASTERPOS4SVPROC)(const GLshort *v); -GLAPI PFNGLRASTERPOS4SVPROC glad_glRasterPos4sv; -#define glRasterPos4sv glad_glRasterPos4sv -typedef void (APIENTRYP PFNGLRECTDPROC)(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2); -GLAPI PFNGLRECTDPROC glad_glRectd; -#define glRectd glad_glRectd -typedef void (APIENTRYP PFNGLRECTDVPROC)(const GLdouble *v1, const GLdouble *v2); -GLAPI PFNGLRECTDVPROC glad_glRectdv; -#define glRectdv glad_glRectdv -typedef void (APIENTRYP PFNGLRECTFPROC)(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2); -GLAPI PFNGLRECTFPROC glad_glRectf; -#define glRectf glad_glRectf -typedef void (APIENTRYP PFNGLRECTFVPROC)(const GLfloat *v1, const GLfloat *v2); -GLAPI PFNGLRECTFVPROC glad_glRectfv; -#define glRectfv glad_glRectfv -typedef void (APIENTRYP PFNGLRECTIPROC)(GLint x1, GLint y1, GLint x2, GLint y2); -GLAPI PFNGLRECTIPROC glad_glRecti; -#define glRecti glad_glRecti -typedef void (APIENTRYP PFNGLRECTIVPROC)(const GLint *v1, const GLint *v2); -GLAPI PFNGLRECTIVPROC glad_glRectiv; -#define glRectiv glad_glRectiv -typedef void (APIENTRYP PFNGLRECTSPROC)(GLshort x1, GLshort y1, GLshort x2, GLshort y2); -GLAPI PFNGLRECTSPROC glad_glRects; -#define glRects glad_glRects -typedef void (APIENTRYP PFNGLRECTSVPROC)(const GLshort *v1, const GLshort *v2); -GLAPI PFNGLRECTSVPROC glad_glRectsv; -#define glRectsv glad_glRectsv -typedef void (APIENTRYP PFNGLTEXCOORD1DPROC)(GLdouble s); -GLAPI PFNGLTEXCOORD1DPROC glad_glTexCoord1d; -#define glTexCoord1d glad_glTexCoord1d -typedef void (APIENTRYP PFNGLTEXCOORD1DVPROC)(const GLdouble *v); -GLAPI PFNGLTEXCOORD1DVPROC glad_glTexCoord1dv; -#define glTexCoord1dv glad_glTexCoord1dv -typedef void (APIENTRYP PFNGLTEXCOORD1FPROC)(GLfloat s); -GLAPI PFNGLTEXCOORD1FPROC glad_glTexCoord1f; -#define glTexCoord1f glad_glTexCoord1f -typedef void (APIENTRYP PFNGLTEXCOORD1FVPROC)(const GLfloat *v); -GLAPI PFNGLTEXCOORD1FVPROC glad_glTexCoord1fv; -#define glTexCoord1fv glad_glTexCoord1fv -typedef void (APIENTRYP PFNGLTEXCOORD1IPROC)(GLint s); -GLAPI PFNGLTEXCOORD1IPROC glad_glTexCoord1i; -#define glTexCoord1i glad_glTexCoord1i -typedef void (APIENTRYP PFNGLTEXCOORD1IVPROC)(const GLint *v); -GLAPI PFNGLTEXCOORD1IVPROC glad_glTexCoord1iv; -#define glTexCoord1iv glad_glTexCoord1iv -typedef void (APIENTRYP PFNGLTEXCOORD1SPROC)(GLshort s); -GLAPI PFNGLTEXCOORD1SPROC glad_glTexCoord1s; -#define glTexCoord1s glad_glTexCoord1s -typedef void (APIENTRYP PFNGLTEXCOORD1SVPROC)(const GLshort *v); -GLAPI PFNGLTEXCOORD1SVPROC glad_glTexCoord1sv; -#define glTexCoord1sv glad_glTexCoord1sv -typedef void (APIENTRYP PFNGLTEXCOORD2DPROC)(GLdouble s, GLdouble t); -GLAPI PFNGLTEXCOORD2DPROC glad_glTexCoord2d; -#define glTexCoord2d glad_glTexCoord2d -typedef void (APIENTRYP PFNGLTEXCOORD2DVPROC)(const GLdouble *v); -GLAPI PFNGLTEXCOORD2DVPROC glad_glTexCoord2dv; -#define glTexCoord2dv glad_glTexCoord2dv -typedef void (APIENTRYP PFNGLTEXCOORD2FPROC)(GLfloat s, GLfloat t); -GLAPI PFNGLTEXCOORD2FPROC glad_glTexCoord2f; -#define glTexCoord2f glad_glTexCoord2f -typedef void (APIENTRYP PFNGLTEXCOORD2FVPROC)(const GLfloat *v); -GLAPI PFNGLTEXCOORD2FVPROC glad_glTexCoord2fv; -#define glTexCoord2fv glad_glTexCoord2fv -typedef void (APIENTRYP PFNGLTEXCOORD2IPROC)(GLint s, GLint t); -GLAPI PFNGLTEXCOORD2IPROC glad_glTexCoord2i; -#define glTexCoord2i glad_glTexCoord2i -typedef void (APIENTRYP PFNGLTEXCOORD2IVPROC)(const GLint *v); -GLAPI PFNGLTEXCOORD2IVPROC glad_glTexCoord2iv; -#define glTexCoord2iv glad_glTexCoord2iv -typedef void (APIENTRYP PFNGLTEXCOORD2SPROC)(GLshort s, GLshort t); -GLAPI PFNGLTEXCOORD2SPROC glad_glTexCoord2s; -#define glTexCoord2s glad_glTexCoord2s -typedef void (APIENTRYP PFNGLTEXCOORD2SVPROC)(const GLshort *v); -GLAPI PFNGLTEXCOORD2SVPROC glad_glTexCoord2sv; -#define glTexCoord2sv glad_glTexCoord2sv -typedef void (APIENTRYP PFNGLTEXCOORD3DPROC)(GLdouble s, GLdouble t, GLdouble r); -GLAPI PFNGLTEXCOORD3DPROC glad_glTexCoord3d; -#define glTexCoord3d glad_glTexCoord3d -typedef void (APIENTRYP PFNGLTEXCOORD3DVPROC)(const GLdouble *v); -GLAPI PFNGLTEXCOORD3DVPROC glad_glTexCoord3dv; -#define glTexCoord3dv glad_glTexCoord3dv -typedef void (APIENTRYP PFNGLTEXCOORD3FPROC)(GLfloat s, GLfloat t, GLfloat r); -GLAPI PFNGLTEXCOORD3FPROC glad_glTexCoord3f; -#define glTexCoord3f glad_glTexCoord3f -typedef void (APIENTRYP PFNGLTEXCOORD3FVPROC)(const GLfloat *v); -GLAPI PFNGLTEXCOORD3FVPROC glad_glTexCoord3fv; -#define glTexCoord3fv glad_glTexCoord3fv -typedef void (APIENTRYP PFNGLTEXCOORD3IPROC)(GLint s, GLint t, GLint r); -GLAPI PFNGLTEXCOORD3IPROC glad_glTexCoord3i; -#define glTexCoord3i glad_glTexCoord3i -typedef void (APIENTRYP PFNGLTEXCOORD3IVPROC)(const GLint *v); -GLAPI PFNGLTEXCOORD3IVPROC glad_glTexCoord3iv; -#define glTexCoord3iv glad_glTexCoord3iv -typedef void (APIENTRYP PFNGLTEXCOORD3SPROC)(GLshort s, GLshort t, GLshort r); -GLAPI PFNGLTEXCOORD3SPROC glad_glTexCoord3s; -#define glTexCoord3s glad_glTexCoord3s -typedef void (APIENTRYP PFNGLTEXCOORD3SVPROC)(const GLshort *v); -GLAPI PFNGLTEXCOORD3SVPROC glad_glTexCoord3sv; -#define glTexCoord3sv glad_glTexCoord3sv -typedef void (APIENTRYP PFNGLTEXCOORD4DPROC)(GLdouble s, GLdouble t, GLdouble r, GLdouble q); -GLAPI PFNGLTEXCOORD4DPROC glad_glTexCoord4d; -#define glTexCoord4d glad_glTexCoord4d -typedef void (APIENTRYP PFNGLTEXCOORD4DVPROC)(const GLdouble *v); -GLAPI PFNGLTEXCOORD4DVPROC glad_glTexCoord4dv; -#define glTexCoord4dv glad_glTexCoord4dv -typedef void (APIENTRYP PFNGLTEXCOORD4FPROC)(GLfloat s, GLfloat t, GLfloat r, GLfloat q); -GLAPI PFNGLTEXCOORD4FPROC glad_glTexCoord4f; -#define glTexCoord4f glad_glTexCoord4f -typedef void (APIENTRYP PFNGLTEXCOORD4FVPROC)(const GLfloat *v); -GLAPI PFNGLTEXCOORD4FVPROC glad_glTexCoord4fv; -#define glTexCoord4fv glad_glTexCoord4fv -typedef void (APIENTRYP PFNGLTEXCOORD4IPROC)(GLint s, GLint t, GLint r, GLint q); -GLAPI PFNGLTEXCOORD4IPROC glad_glTexCoord4i; -#define glTexCoord4i glad_glTexCoord4i -typedef void (APIENTRYP PFNGLTEXCOORD4IVPROC)(const GLint *v); -GLAPI PFNGLTEXCOORD4IVPROC glad_glTexCoord4iv; -#define glTexCoord4iv glad_glTexCoord4iv -typedef void (APIENTRYP PFNGLTEXCOORD4SPROC)(GLshort s, GLshort t, GLshort r, GLshort q); -GLAPI PFNGLTEXCOORD4SPROC glad_glTexCoord4s; -#define glTexCoord4s glad_glTexCoord4s -typedef void (APIENTRYP PFNGLTEXCOORD4SVPROC)(const GLshort *v); -GLAPI PFNGLTEXCOORD4SVPROC glad_glTexCoord4sv; -#define glTexCoord4sv glad_glTexCoord4sv -typedef void (APIENTRYP PFNGLVERTEX2DPROC)(GLdouble x, GLdouble y); -GLAPI PFNGLVERTEX2DPROC glad_glVertex2d; -#define glVertex2d glad_glVertex2d -typedef void (APIENTRYP PFNGLVERTEX2DVPROC)(const GLdouble *v); -GLAPI PFNGLVERTEX2DVPROC glad_glVertex2dv; -#define glVertex2dv glad_glVertex2dv -typedef void (APIENTRYP PFNGLVERTEX2FPROC)(GLfloat x, GLfloat y); -GLAPI PFNGLVERTEX2FPROC glad_glVertex2f; -#define glVertex2f glad_glVertex2f -typedef void (APIENTRYP PFNGLVERTEX2FVPROC)(const GLfloat *v); -GLAPI PFNGLVERTEX2FVPROC glad_glVertex2fv; -#define glVertex2fv glad_glVertex2fv -typedef void (APIENTRYP PFNGLVERTEX2IPROC)(GLint x, GLint y); -GLAPI PFNGLVERTEX2IPROC glad_glVertex2i; -#define glVertex2i glad_glVertex2i -typedef void (APIENTRYP PFNGLVERTEX2IVPROC)(const GLint *v); -GLAPI PFNGLVERTEX2IVPROC glad_glVertex2iv; -#define glVertex2iv glad_glVertex2iv -typedef void (APIENTRYP PFNGLVERTEX2SPROC)(GLshort x, GLshort y); -GLAPI PFNGLVERTEX2SPROC glad_glVertex2s; -#define glVertex2s glad_glVertex2s -typedef void (APIENTRYP PFNGLVERTEX2SVPROC)(const GLshort *v); -GLAPI PFNGLVERTEX2SVPROC glad_glVertex2sv; -#define glVertex2sv glad_glVertex2sv -typedef void (APIENTRYP PFNGLVERTEX3DPROC)(GLdouble x, GLdouble y, GLdouble z); -GLAPI PFNGLVERTEX3DPROC glad_glVertex3d; -#define glVertex3d glad_glVertex3d -typedef void (APIENTRYP PFNGLVERTEX3DVPROC)(const GLdouble *v); -GLAPI PFNGLVERTEX3DVPROC glad_glVertex3dv; -#define glVertex3dv glad_glVertex3dv -typedef void (APIENTRYP PFNGLVERTEX3FPROC)(GLfloat x, GLfloat y, GLfloat z); -GLAPI PFNGLVERTEX3FPROC glad_glVertex3f; -#define glVertex3f glad_glVertex3f -typedef void (APIENTRYP PFNGLVERTEX3FVPROC)(const GLfloat *v); -GLAPI PFNGLVERTEX3FVPROC glad_glVertex3fv; -#define glVertex3fv glad_glVertex3fv -typedef void (APIENTRYP PFNGLVERTEX3IPROC)(GLint x, GLint y, GLint z); -GLAPI PFNGLVERTEX3IPROC glad_glVertex3i; -#define glVertex3i glad_glVertex3i -typedef void (APIENTRYP PFNGLVERTEX3IVPROC)(const GLint *v); -GLAPI PFNGLVERTEX3IVPROC glad_glVertex3iv; -#define glVertex3iv glad_glVertex3iv -typedef void (APIENTRYP PFNGLVERTEX3SPROC)(GLshort x, GLshort y, GLshort z); -GLAPI PFNGLVERTEX3SPROC glad_glVertex3s; -#define glVertex3s glad_glVertex3s -typedef void (APIENTRYP PFNGLVERTEX3SVPROC)(const GLshort *v); -GLAPI PFNGLVERTEX3SVPROC glad_glVertex3sv; -#define glVertex3sv glad_glVertex3sv -typedef void (APIENTRYP PFNGLVERTEX4DPROC)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); -GLAPI PFNGLVERTEX4DPROC glad_glVertex4d; -#define glVertex4d glad_glVertex4d -typedef void (APIENTRYP PFNGLVERTEX4DVPROC)(const GLdouble *v); -GLAPI PFNGLVERTEX4DVPROC glad_glVertex4dv; -#define glVertex4dv glad_glVertex4dv -typedef void (APIENTRYP PFNGLVERTEX4FPROC)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); -GLAPI PFNGLVERTEX4FPROC glad_glVertex4f; -#define glVertex4f glad_glVertex4f -typedef void (APIENTRYP PFNGLVERTEX4FVPROC)(const GLfloat *v); -GLAPI PFNGLVERTEX4FVPROC glad_glVertex4fv; -#define glVertex4fv glad_glVertex4fv -typedef void (APIENTRYP PFNGLVERTEX4IPROC)(GLint x, GLint y, GLint z, GLint w); -GLAPI PFNGLVERTEX4IPROC glad_glVertex4i; -#define glVertex4i glad_glVertex4i -typedef void (APIENTRYP PFNGLVERTEX4IVPROC)(const GLint *v); -GLAPI PFNGLVERTEX4IVPROC glad_glVertex4iv; -#define glVertex4iv glad_glVertex4iv -typedef void (APIENTRYP PFNGLVERTEX4SPROC)(GLshort x, GLshort y, GLshort z, GLshort w); -GLAPI PFNGLVERTEX4SPROC glad_glVertex4s; -#define glVertex4s glad_glVertex4s -typedef void (APIENTRYP PFNGLVERTEX4SVPROC)(const GLshort *v); -GLAPI PFNGLVERTEX4SVPROC glad_glVertex4sv; -#define glVertex4sv glad_glVertex4sv -typedef void (APIENTRYP PFNGLCLIPPLANEPROC)(GLenum plane, const GLdouble *equation); -GLAPI PFNGLCLIPPLANEPROC glad_glClipPlane; -#define glClipPlane glad_glClipPlane -typedef void (APIENTRYP PFNGLCOLORMATERIALPROC)(GLenum face, GLenum mode); -GLAPI PFNGLCOLORMATERIALPROC glad_glColorMaterial; -#define glColorMaterial glad_glColorMaterial -typedef void (APIENTRYP PFNGLFOGFPROC)(GLenum pname, GLfloat param); -GLAPI PFNGLFOGFPROC glad_glFogf; -#define glFogf glad_glFogf -typedef void (APIENTRYP PFNGLFOGFVPROC)(GLenum pname, const GLfloat *params); -GLAPI PFNGLFOGFVPROC glad_glFogfv; -#define glFogfv glad_glFogfv -typedef void (APIENTRYP PFNGLFOGIPROC)(GLenum pname, GLint param); -GLAPI PFNGLFOGIPROC glad_glFogi; -#define glFogi glad_glFogi -typedef void (APIENTRYP PFNGLFOGIVPROC)(GLenum pname, const GLint *params); -GLAPI PFNGLFOGIVPROC glad_glFogiv; -#define glFogiv glad_glFogiv -typedef void (APIENTRYP PFNGLLIGHTFPROC)(GLenum light, GLenum pname, GLfloat param); -GLAPI PFNGLLIGHTFPROC glad_glLightf; -#define glLightf glad_glLightf -typedef void (APIENTRYP PFNGLLIGHTFVPROC)(GLenum light, GLenum pname, const GLfloat *params); -GLAPI PFNGLLIGHTFVPROC glad_glLightfv; -#define glLightfv glad_glLightfv -typedef void (APIENTRYP PFNGLLIGHTIPROC)(GLenum light, GLenum pname, GLint param); -GLAPI PFNGLLIGHTIPROC glad_glLighti; -#define glLighti glad_glLighti -typedef void (APIENTRYP PFNGLLIGHTIVPROC)(GLenum light, GLenum pname, const GLint *params); -GLAPI PFNGLLIGHTIVPROC glad_glLightiv; -#define glLightiv glad_glLightiv -typedef void (APIENTRYP PFNGLLIGHTMODELFPROC)(GLenum pname, GLfloat param); -GLAPI PFNGLLIGHTMODELFPROC glad_glLightModelf; -#define glLightModelf glad_glLightModelf -typedef void (APIENTRYP PFNGLLIGHTMODELFVPROC)(GLenum pname, const GLfloat *params); -GLAPI PFNGLLIGHTMODELFVPROC glad_glLightModelfv; -#define glLightModelfv glad_glLightModelfv -typedef void (APIENTRYP PFNGLLIGHTMODELIPROC)(GLenum pname, GLint param); -GLAPI PFNGLLIGHTMODELIPROC glad_glLightModeli; -#define glLightModeli glad_glLightModeli -typedef void (APIENTRYP PFNGLLIGHTMODELIVPROC)(GLenum pname, const GLint *params); -GLAPI PFNGLLIGHTMODELIVPROC glad_glLightModeliv; -#define glLightModeliv glad_glLightModeliv -typedef void (APIENTRYP PFNGLLINESTIPPLEPROC)(GLint factor, GLushort pattern); -GLAPI PFNGLLINESTIPPLEPROC glad_glLineStipple; -#define glLineStipple glad_glLineStipple -typedef void (APIENTRYP PFNGLMATERIALFPROC)(GLenum face, GLenum pname, GLfloat param); -GLAPI PFNGLMATERIALFPROC glad_glMaterialf; -#define glMaterialf glad_glMaterialf -typedef void (APIENTRYP PFNGLMATERIALFVPROC)(GLenum face, GLenum pname, const GLfloat *params); -GLAPI PFNGLMATERIALFVPROC glad_glMaterialfv; -#define glMaterialfv glad_glMaterialfv -typedef void (APIENTRYP PFNGLMATERIALIPROC)(GLenum face, GLenum pname, GLint param); -GLAPI PFNGLMATERIALIPROC glad_glMateriali; -#define glMateriali glad_glMateriali -typedef void (APIENTRYP PFNGLMATERIALIVPROC)(GLenum face, GLenum pname, const GLint *params); -GLAPI PFNGLMATERIALIVPROC glad_glMaterialiv; -#define glMaterialiv glad_glMaterialiv -typedef void (APIENTRYP PFNGLPOLYGONSTIPPLEPROC)(const GLubyte *mask); -GLAPI PFNGLPOLYGONSTIPPLEPROC glad_glPolygonStipple; -#define glPolygonStipple glad_glPolygonStipple -typedef void (APIENTRYP PFNGLSHADEMODELPROC)(GLenum mode); -GLAPI PFNGLSHADEMODELPROC glad_glShadeModel; -#define glShadeModel glad_glShadeModel -typedef void (APIENTRYP PFNGLTEXENVFPROC)(GLenum target, GLenum pname, GLfloat param); -GLAPI PFNGLTEXENVFPROC glad_glTexEnvf; -#define glTexEnvf glad_glTexEnvf -typedef void (APIENTRYP PFNGLTEXENVFVPROC)(GLenum target, GLenum pname, const GLfloat *params); -GLAPI PFNGLTEXENVFVPROC glad_glTexEnvfv; -#define glTexEnvfv glad_glTexEnvfv -typedef void (APIENTRYP PFNGLTEXENVIPROC)(GLenum target, GLenum pname, GLint param); -GLAPI PFNGLTEXENVIPROC glad_glTexEnvi; -#define glTexEnvi glad_glTexEnvi -typedef void (APIENTRYP PFNGLTEXENVIVPROC)(GLenum target, GLenum pname, const GLint *params); -GLAPI PFNGLTEXENVIVPROC glad_glTexEnviv; -#define glTexEnviv glad_glTexEnviv -typedef void (APIENTRYP PFNGLTEXGENDPROC)(GLenum coord, GLenum pname, GLdouble param); -GLAPI PFNGLTEXGENDPROC glad_glTexGend; -#define glTexGend glad_glTexGend -typedef void (APIENTRYP PFNGLTEXGENDVPROC)(GLenum coord, GLenum pname, const GLdouble *params); -GLAPI PFNGLTEXGENDVPROC glad_glTexGendv; -#define glTexGendv glad_glTexGendv -typedef void (APIENTRYP PFNGLTEXGENFPROC)(GLenum coord, GLenum pname, GLfloat param); -GLAPI PFNGLTEXGENFPROC glad_glTexGenf; -#define glTexGenf glad_glTexGenf -typedef void (APIENTRYP PFNGLTEXGENFVPROC)(GLenum coord, GLenum pname, const GLfloat *params); -GLAPI PFNGLTEXGENFVPROC glad_glTexGenfv; -#define glTexGenfv glad_glTexGenfv -typedef void (APIENTRYP PFNGLTEXGENIPROC)(GLenum coord, GLenum pname, GLint param); -GLAPI PFNGLTEXGENIPROC glad_glTexGeni; -#define glTexGeni glad_glTexGeni -typedef void (APIENTRYP PFNGLTEXGENIVPROC)(GLenum coord, GLenum pname, const GLint *params); -GLAPI PFNGLTEXGENIVPROC glad_glTexGeniv; -#define glTexGeniv glad_glTexGeniv -typedef void (APIENTRYP PFNGLFEEDBACKBUFFERPROC)(GLsizei size, GLenum type, GLfloat *buffer); -GLAPI PFNGLFEEDBACKBUFFERPROC glad_glFeedbackBuffer; -#define glFeedbackBuffer glad_glFeedbackBuffer -typedef void (APIENTRYP PFNGLSELECTBUFFERPROC)(GLsizei size, GLuint *buffer); -GLAPI PFNGLSELECTBUFFERPROC glad_glSelectBuffer; -#define glSelectBuffer glad_glSelectBuffer -typedef GLint (APIENTRYP PFNGLRENDERMODEPROC)(GLenum mode); -GLAPI PFNGLRENDERMODEPROC glad_glRenderMode; -#define glRenderMode glad_glRenderMode -typedef void (APIENTRYP PFNGLINITNAMESPROC)(void); -GLAPI PFNGLINITNAMESPROC glad_glInitNames; -#define glInitNames glad_glInitNames -typedef void (APIENTRYP PFNGLLOADNAMEPROC)(GLuint name); -GLAPI PFNGLLOADNAMEPROC glad_glLoadName; -#define glLoadName glad_glLoadName -typedef void (APIENTRYP PFNGLPASSTHROUGHPROC)(GLfloat token); -GLAPI PFNGLPASSTHROUGHPROC glad_glPassThrough; -#define glPassThrough glad_glPassThrough -typedef void (APIENTRYP PFNGLPOPNAMEPROC)(void); -GLAPI PFNGLPOPNAMEPROC glad_glPopName; -#define glPopName glad_glPopName -typedef void (APIENTRYP PFNGLPUSHNAMEPROC)(GLuint name); -GLAPI PFNGLPUSHNAMEPROC glad_glPushName; -#define glPushName glad_glPushName -typedef void (APIENTRYP PFNGLCLEARACCUMPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); -GLAPI PFNGLCLEARACCUMPROC glad_glClearAccum; -#define glClearAccum glad_glClearAccum -typedef void (APIENTRYP PFNGLCLEARINDEXPROC)(GLfloat c); -GLAPI PFNGLCLEARINDEXPROC glad_glClearIndex; -#define glClearIndex glad_glClearIndex -typedef void (APIENTRYP PFNGLINDEXMASKPROC)(GLuint mask); -GLAPI PFNGLINDEXMASKPROC glad_glIndexMask; -#define glIndexMask glad_glIndexMask -typedef void (APIENTRYP PFNGLACCUMPROC)(GLenum op, GLfloat value); -GLAPI PFNGLACCUMPROC glad_glAccum; -#define glAccum glad_glAccum -typedef void (APIENTRYP PFNGLPOPATTRIBPROC)(void); -GLAPI PFNGLPOPATTRIBPROC glad_glPopAttrib; -#define glPopAttrib glad_glPopAttrib -typedef void (APIENTRYP PFNGLPUSHATTRIBPROC)(GLbitfield mask); -GLAPI PFNGLPUSHATTRIBPROC glad_glPushAttrib; -#define glPushAttrib glad_glPushAttrib -typedef void (APIENTRYP PFNGLMAP1DPROC)(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points); -GLAPI PFNGLMAP1DPROC glad_glMap1d; -#define glMap1d glad_glMap1d -typedef void (APIENTRYP PFNGLMAP1FPROC)(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points); -GLAPI PFNGLMAP1FPROC glad_glMap1f; -#define glMap1f glad_glMap1f -typedef void (APIENTRYP PFNGLMAP2DPROC)(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points); -GLAPI PFNGLMAP2DPROC glad_glMap2d; -#define glMap2d glad_glMap2d -typedef void (APIENTRYP PFNGLMAP2FPROC)(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points); -GLAPI PFNGLMAP2FPROC glad_glMap2f; -#define glMap2f glad_glMap2f -typedef void (APIENTRYP PFNGLMAPGRID1DPROC)(GLint un, GLdouble u1, GLdouble u2); -GLAPI PFNGLMAPGRID1DPROC glad_glMapGrid1d; -#define glMapGrid1d glad_glMapGrid1d -typedef void (APIENTRYP PFNGLMAPGRID1FPROC)(GLint un, GLfloat u1, GLfloat u2); -GLAPI PFNGLMAPGRID1FPROC glad_glMapGrid1f; -#define glMapGrid1f glad_glMapGrid1f -typedef void (APIENTRYP PFNGLMAPGRID2DPROC)(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2); -GLAPI PFNGLMAPGRID2DPROC glad_glMapGrid2d; -#define glMapGrid2d glad_glMapGrid2d -typedef void (APIENTRYP PFNGLMAPGRID2FPROC)(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2); -GLAPI PFNGLMAPGRID2FPROC glad_glMapGrid2f; -#define glMapGrid2f glad_glMapGrid2f -typedef void (APIENTRYP PFNGLEVALCOORD1DPROC)(GLdouble u); -GLAPI PFNGLEVALCOORD1DPROC glad_glEvalCoord1d; -#define glEvalCoord1d glad_glEvalCoord1d -typedef void (APIENTRYP PFNGLEVALCOORD1DVPROC)(const GLdouble *u); -GLAPI PFNGLEVALCOORD1DVPROC glad_glEvalCoord1dv; -#define glEvalCoord1dv glad_glEvalCoord1dv -typedef void (APIENTRYP PFNGLEVALCOORD1FPROC)(GLfloat u); -GLAPI PFNGLEVALCOORD1FPROC glad_glEvalCoord1f; -#define glEvalCoord1f glad_glEvalCoord1f -typedef void (APIENTRYP PFNGLEVALCOORD1FVPROC)(const GLfloat *u); -GLAPI PFNGLEVALCOORD1FVPROC glad_glEvalCoord1fv; -#define glEvalCoord1fv glad_glEvalCoord1fv -typedef void (APIENTRYP PFNGLEVALCOORD2DPROC)(GLdouble u, GLdouble v); -GLAPI PFNGLEVALCOORD2DPROC glad_glEvalCoord2d; -#define glEvalCoord2d glad_glEvalCoord2d -typedef void (APIENTRYP PFNGLEVALCOORD2DVPROC)(const GLdouble *u); -GLAPI PFNGLEVALCOORD2DVPROC glad_glEvalCoord2dv; -#define glEvalCoord2dv glad_glEvalCoord2dv -typedef void (APIENTRYP PFNGLEVALCOORD2FPROC)(GLfloat u, GLfloat v); -GLAPI PFNGLEVALCOORD2FPROC glad_glEvalCoord2f; -#define glEvalCoord2f glad_glEvalCoord2f -typedef void (APIENTRYP PFNGLEVALCOORD2FVPROC)(const GLfloat *u); -GLAPI PFNGLEVALCOORD2FVPROC glad_glEvalCoord2fv; -#define glEvalCoord2fv glad_glEvalCoord2fv -typedef void (APIENTRYP PFNGLEVALMESH1PROC)(GLenum mode, GLint i1, GLint i2); -GLAPI PFNGLEVALMESH1PROC glad_glEvalMesh1; -#define glEvalMesh1 glad_glEvalMesh1 -typedef void (APIENTRYP PFNGLEVALPOINT1PROC)(GLint i); -GLAPI PFNGLEVALPOINT1PROC glad_glEvalPoint1; -#define glEvalPoint1 glad_glEvalPoint1 -typedef void (APIENTRYP PFNGLEVALMESH2PROC)(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2); -GLAPI PFNGLEVALMESH2PROC glad_glEvalMesh2; -#define glEvalMesh2 glad_glEvalMesh2 -typedef void (APIENTRYP PFNGLEVALPOINT2PROC)(GLint i, GLint j); -GLAPI PFNGLEVALPOINT2PROC glad_glEvalPoint2; -#define glEvalPoint2 glad_glEvalPoint2 -typedef void (APIENTRYP PFNGLALPHAFUNCPROC)(GLenum func, GLfloat ref); -GLAPI PFNGLALPHAFUNCPROC glad_glAlphaFunc; -#define glAlphaFunc glad_glAlphaFunc -typedef void (APIENTRYP PFNGLPIXELZOOMPROC)(GLfloat xfactor, GLfloat yfactor); -GLAPI PFNGLPIXELZOOMPROC glad_glPixelZoom; -#define glPixelZoom glad_glPixelZoom -typedef void (APIENTRYP PFNGLPIXELTRANSFERFPROC)(GLenum pname, GLfloat param); -GLAPI PFNGLPIXELTRANSFERFPROC glad_glPixelTransferf; -#define glPixelTransferf glad_glPixelTransferf -typedef void (APIENTRYP PFNGLPIXELTRANSFERIPROC)(GLenum pname, GLint param); -GLAPI PFNGLPIXELTRANSFERIPROC glad_glPixelTransferi; -#define glPixelTransferi glad_glPixelTransferi -typedef void (APIENTRYP PFNGLPIXELMAPFVPROC)(GLenum map, GLsizei mapsize, const GLfloat *values); -GLAPI PFNGLPIXELMAPFVPROC glad_glPixelMapfv; -#define glPixelMapfv glad_glPixelMapfv -typedef void (APIENTRYP PFNGLPIXELMAPUIVPROC)(GLenum map, GLsizei mapsize, const GLuint *values); -GLAPI PFNGLPIXELMAPUIVPROC glad_glPixelMapuiv; -#define glPixelMapuiv glad_glPixelMapuiv -typedef void (APIENTRYP PFNGLPIXELMAPUSVPROC)(GLenum map, GLsizei mapsize, const GLushort *values); -GLAPI PFNGLPIXELMAPUSVPROC glad_glPixelMapusv; -#define glPixelMapusv glad_glPixelMapusv -typedef void (APIENTRYP PFNGLCOPYPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type); -GLAPI PFNGLCOPYPIXELSPROC glad_glCopyPixels; -#define glCopyPixels glad_glCopyPixels -typedef void (APIENTRYP PFNGLDRAWPIXELSPROC)(GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); -GLAPI PFNGLDRAWPIXELSPROC glad_glDrawPixels; -#define glDrawPixels glad_glDrawPixels -typedef void (APIENTRYP PFNGLGETCLIPPLANEPROC)(GLenum plane, GLdouble *equation); -GLAPI PFNGLGETCLIPPLANEPROC glad_glGetClipPlane; -#define glGetClipPlane glad_glGetClipPlane -typedef void (APIENTRYP PFNGLGETLIGHTFVPROC)(GLenum light, GLenum pname, GLfloat *params); -GLAPI PFNGLGETLIGHTFVPROC glad_glGetLightfv; -#define glGetLightfv glad_glGetLightfv -typedef void (APIENTRYP PFNGLGETLIGHTIVPROC)(GLenum light, GLenum pname, GLint *params); -GLAPI PFNGLGETLIGHTIVPROC glad_glGetLightiv; -#define glGetLightiv glad_glGetLightiv -typedef void (APIENTRYP PFNGLGETMAPDVPROC)(GLenum target, GLenum query, GLdouble *v); -GLAPI PFNGLGETMAPDVPROC glad_glGetMapdv; -#define glGetMapdv glad_glGetMapdv -typedef void (APIENTRYP PFNGLGETMAPFVPROC)(GLenum target, GLenum query, GLfloat *v); -GLAPI PFNGLGETMAPFVPROC glad_glGetMapfv; -#define glGetMapfv glad_glGetMapfv -typedef void (APIENTRYP PFNGLGETMAPIVPROC)(GLenum target, GLenum query, GLint *v); -GLAPI PFNGLGETMAPIVPROC glad_glGetMapiv; -#define glGetMapiv glad_glGetMapiv -typedef void (APIENTRYP PFNGLGETMATERIALFVPROC)(GLenum face, GLenum pname, GLfloat *params); -GLAPI PFNGLGETMATERIALFVPROC glad_glGetMaterialfv; -#define glGetMaterialfv glad_glGetMaterialfv -typedef void (APIENTRYP PFNGLGETMATERIALIVPROC)(GLenum face, GLenum pname, GLint *params); -GLAPI PFNGLGETMATERIALIVPROC glad_glGetMaterialiv; -#define glGetMaterialiv glad_glGetMaterialiv -typedef void (APIENTRYP PFNGLGETPIXELMAPFVPROC)(GLenum map, GLfloat *values); -GLAPI PFNGLGETPIXELMAPFVPROC glad_glGetPixelMapfv; -#define glGetPixelMapfv glad_glGetPixelMapfv -typedef void (APIENTRYP PFNGLGETPIXELMAPUIVPROC)(GLenum map, GLuint *values); -GLAPI PFNGLGETPIXELMAPUIVPROC glad_glGetPixelMapuiv; -#define glGetPixelMapuiv glad_glGetPixelMapuiv -typedef void (APIENTRYP PFNGLGETPIXELMAPUSVPROC)(GLenum map, GLushort *values); -GLAPI PFNGLGETPIXELMAPUSVPROC glad_glGetPixelMapusv; -#define glGetPixelMapusv glad_glGetPixelMapusv -typedef void (APIENTRYP PFNGLGETPOLYGONSTIPPLEPROC)(GLubyte *mask); -GLAPI PFNGLGETPOLYGONSTIPPLEPROC glad_glGetPolygonStipple; -#define glGetPolygonStipple glad_glGetPolygonStipple -typedef void (APIENTRYP PFNGLGETTEXENVFVPROC)(GLenum target, GLenum pname, GLfloat *params); -GLAPI PFNGLGETTEXENVFVPROC glad_glGetTexEnvfv; -#define glGetTexEnvfv glad_glGetTexEnvfv -typedef void (APIENTRYP PFNGLGETTEXENVIVPROC)(GLenum target, GLenum pname, GLint *params); -GLAPI PFNGLGETTEXENVIVPROC glad_glGetTexEnviv; -#define glGetTexEnviv glad_glGetTexEnviv -typedef void (APIENTRYP PFNGLGETTEXGENDVPROC)(GLenum coord, GLenum pname, GLdouble *params); -GLAPI PFNGLGETTEXGENDVPROC glad_glGetTexGendv; -#define glGetTexGendv glad_glGetTexGendv -typedef void (APIENTRYP PFNGLGETTEXGENFVPROC)(GLenum coord, GLenum pname, GLfloat *params); -GLAPI PFNGLGETTEXGENFVPROC glad_glGetTexGenfv; -#define glGetTexGenfv glad_glGetTexGenfv -typedef void (APIENTRYP PFNGLGETTEXGENIVPROC)(GLenum coord, GLenum pname, GLint *params); -GLAPI PFNGLGETTEXGENIVPROC glad_glGetTexGeniv; -#define glGetTexGeniv glad_glGetTexGeniv -typedef GLboolean (APIENTRYP PFNGLISLISTPROC)(GLuint list); -GLAPI PFNGLISLISTPROC glad_glIsList; -#define glIsList glad_glIsList -typedef void (APIENTRYP PFNGLFRUSTUMPROC)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); -GLAPI PFNGLFRUSTUMPROC glad_glFrustum; -#define glFrustum glad_glFrustum -typedef void (APIENTRYP PFNGLLOADIDENTITYPROC)(void); -GLAPI PFNGLLOADIDENTITYPROC glad_glLoadIdentity; -#define glLoadIdentity glad_glLoadIdentity -typedef void (APIENTRYP PFNGLLOADMATRIXFPROC)(const GLfloat *m); -GLAPI PFNGLLOADMATRIXFPROC glad_glLoadMatrixf; -#define glLoadMatrixf glad_glLoadMatrixf -typedef void (APIENTRYP PFNGLLOADMATRIXDPROC)(const GLdouble *m); -GLAPI PFNGLLOADMATRIXDPROC glad_glLoadMatrixd; -#define glLoadMatrixd glad_glLoadMatrixd -typedef void (APIENTRYP PFNGLMATRIXMODEPROC)(GLenum mode); -GLAPI PFNGLMATRIXMODEPROC glad_glMatrixMode; -#define glMatrixMode glad_glMatrixMode -typedef void (APIENTRYP PFNGLMULTMATRIXFPROC)(const GLfloat *m); -GLAPI PFNGLMULTMATRIXFPROC glad_glMultMatrixf; -#define glMultMatrixf glad_glMultMatrixf -typedef void (APIENTRYP PFNGLMULTMATRIXDPROC)(const GLdouble *m); -GLAPI PFNGLMULTMATRIXDPROC glad_glMultMatrixd; -#define glMultMatrixd glad_glMultMatrixd -typedef void (APIENTRYP PFNGLORTHOPROC)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); -GLAPI PFNGLORTHOPROC glad_glOrtho; -#define glOrtho glad_glOrtho -typedef void (APIENTRYP PFNGLPOPMATRIXPROC)(void); -GLAPI PFNGLPOPMATRIXPROC glad_glPopMatrix; -#define glPopMatrix glad_glPopMatrix -typedef void (APIENTRYP PFNGLPUSHMATRIXPROC)(void); -GLAPI PFNGLPUSHMATRIXPROC glad_glPushMatrix; -#define glPushMatrix glad_glPushMatrix -typedef void (APIENTRYP PFNGLROTATEDPROC)(GLdouble angle, GLdouble x, GLdouble y, GLdouble z); -GLAPI PFNGLROTATEDPROC glad_glRotated; -#define glRotated glad_glRotated -typedef void (APIENTRYP PFNGLROTATEFPROC)(GLfloat angle, GLfloat x, GLfloat y, GLfloat z); -GLAPI PFNGLROTATEFPROC glad_glRotatef; -#define glRotatef glad_glRotatef -typedef void (APIENTRYP PFNGLSCALEDPROC)(GLdouble x, GLdouble y, GLdouble z); -GLAPI PFNGLSCALEDPROC glad_glScaled; -#define glScaled glad_glScaled -typedef void (APIENTRYP PFNGLSCALEFPROC)(GLfloat x, GLfloat y, GLfloat z); -GLAPI PFNGLSCALEFPROC glad_glScalef; -#define glScalef glad_glScalef -typedef void (APIENTRYP PFNGLTRANSLATEDPROC)(GLdouble x, GLdouble y, GLdouble z); -GLAPI PFNGLTRANSLATEDPROC glad_glTranslated; -#define glTranslated glad_glTranslated -typedef void (APIENTRYP PFNGLTRANSLATEFPROC)(GLfloat x, GLfloat y, GLfloat z); -GLAPI PFNGLTRANSLATEFPROC glad_glTranslatef; -#define glTranslatef glad_glTranslatef -#endif -#ifndef GL_VERSION_1_1 -#define GL_VERSION_1_1 1 -GLAPI int GLAD_GL_VERSION_1_1; -typedef void (APIENTRYP PFNGLDRAWARRAYSPROC)(GLenum mode, GLint first, GLsizei count); -GLAPI PFNGLDRAWARRAYSPROC glad_glDrawArrays; -#define glDrawArrays glad_glDrawArrays -typedef void (APIENTRYP PFNGLDRAWELEMENTSPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices); -GLAPI PFNGLDRAWELEMENTSPROC glad_glDrawElements; -#define glDrawElements glad_glDrawElements -typedef void (APIENTRYP PFNGLGETPOINTERVPROC)(GLenum pname, void **params); -GLAPI PFNGLGETPOINTERVPROC glad_glGetPointerv; -#define glGetPointerv glad_glGetPointerv -typedef void (APIENTRYP PFNGLPOLYGONOFFSETPROC)(GLfloat factor, GLfloat units); -GLAPI PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset; -#define glPolygonOffset glad_glPolygonOffset -typedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); -GLAPI PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D; -#define glCopyTexImage1D glad_glCopyTexImage1D -typedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); -GLAPI PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D; -#define glCopyTexImage2D glad_glCopyTexImage2D -typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); -GLAPI PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D; -#define glCopyTexSubImage1D glad_glCopyTexSubImage1D -typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); -GLAPI PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D; -#define glCopyTexSubImage2D glad_glCopyTexSubImage2D -typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); -GLAPI PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D; -#define glTexSubImage1D glad_glTexSubImage1D -typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); -GLAPI PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D; -#define glTexSubImage2D glad_glTexSubImage2D -typedef void (APIENTRYP PFNGLBINDTEXTUREPROC)(GLenum target, GLuint texture); -GLAPI PFNGLBINDTEXTUREPROC glad_glBindTexture; -#define glBindTexture glad_glBindTexture -typedef void (APIENTRYP PFNGLDELETETEXTURESPROC)(GLsizei n, const GLuint *textures); -GLAPI PFNGLDELETETEXTURESPROC glad_glDeleteTextures; -#define glDeleteTextures glad_glDeleteTextures -typedef void (APIENTRYP PFNGLGENTEXTURESPROC)(GLsizei n, GLuint *textures); -GLAPI PFNGLGENTEXTURESPROC glad_glGenTextures; -#define glGenTextures glad_glGenTextures -typedef GLboolean (APIENTRYP PFNGLISTEXTUREPROC)(GLuint texture); -GLAPI PFNGLISTEXTUREPROC glad_glIsTexture; -#define glIsTexture glad_glIsTexture -typedef void (APIENTRYP PFNGLARRAYELEMENTPROC)(GLint i); -GLAPI PFNGLARRAYELEMENTPROC glad_glArrayElement; -#define glArrayElement glad_glArrayElement -typedef void (APIENTRYP PFNGLCOLORPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); -GLAPI PFNGLCOLORPOINTERPROC glad_glColorPointer; -#define glColorPointer glad_glColorPointer -typedef void (APIENTRYP PFNGLDISABLECLIENTSTATEPROC)(GLenum array); -GLAPI PFNGLDISABLECLIENTSTATEPROC glad_glDisableClientState; -#define glDisableClientState glad_glDisableClientState -typedef void (APIENTRYP PFNGLEDGEFLAGPOINTERPROC)(GLsizei stride, const void *pointer); -GLAPI PFNGLEDGEFLAGPOINTERPROC glad_glEdgeFlagPointer; -#define glEdgeFlagPointer glad_glEdgeFlagPointer -typedef void (APIENTRYP PFNGLENABLECLIENTSTATEPROC)(GLenum array); -GLAPI PFNGLENABLECLIENTSTATEPROC glad_glEnableClientState; -#define glEnableClientState glad_glEnableClientState -typedef void (APIENTRYP PFNGLINDEXPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer); -GLAPI PFNGLINDEXPOINTERPROC glad_glIndexPointer; -#define glIndexPointer glad_glIndexPointer -typedef void (APIENTRYP PFNGLINTERLEAVEDARRAYSPROC)(GLenum format, GLsizei stride, const void *pointer); -GLAPI PFNGLINTERLEAVEDARRAYSPROC glad_glInterleavedArrays; -#define glInterleavedArrays glad_glInterleavedArrays -typedef void (APIENTRYP PFNGLNORMALPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer); -GLAPI PFNGLNORMALPOINTERPROC glad_glNormalPointer; -#define glNormalPointer glad_glNormalPointer -typedef void (APIENTRYP PFNGLTEXCOORDPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); -GLAPI PFNGLTEXCOORDPOINTERPROC glad_glTexCoordPointer; -#define glTexCoordPointer glad_glTexCoordPointer -typedef void (APIENTRYP PFNGLVERTEXPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); -GLAPI PFNGLVERTEXPOINTERPROC glad_glVertexPointer; -#define glVertexPointer glad_glVertexPointer -typedef GLboolean (APIENTRYP PFNGLARETEXTURESRESIDENTPROC)(GLsizei n, const GLuint *textures, GLboolean *residences); -GLAPI PFNGLARETEXTURESRESIDENTPROC glad_glAreTexturesResident; -#define glAreTexturesResident glad_glAreTexturesResident -typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESPROC)(GLsizei n, const GLuint *textures, const GLfloat *priorities); -GLAPI PFNGLPRIORITIZETEXTURESPROC glad_glPrioritizeTextures; -#define glPrioritizeTextures glad_glPrioritizeTextures -typedef void (APIENTRYP PFNGLINDEXUBPROC)(GLubyte c); -GLAPI PFNGLINDEXUBPROC glad_glIndexub; -#define glIndexub glad_glIndexub -typedef void (APIENTRYP PFNGLINDEXUBVPROC)(const GLubyte *c); -GLAPI PFNGLINDEXUBVPROC glad_glIndexubv; -#define glIndexubv glad_glIndexubv -typedef void (APIENTRYP PFNGLPOPCLIENTATTRIBPROC)(void); -GLAPI PFNGLPOPCLIENTATTRIBPROC glad_glPopClientAttrib; -#define glPopClientAttrib glad_glPopClientAttrib -typedef void (APIENTRYP PFNGLPUSHCLIENTATTRIBPROC)(GLbitfield mask); -GLAPI PFNGLPUSHCLIENTATTRIBPROC glad_glPushClientAttrib; -#define glPushClientAttrib glad_glPushClientAttrib -#endif -#ifndef GL_VERSION_1_2 -#define GL_VERSION_1_2 1 -GLAPI int GLAD_GL_VERSION_1_2; -typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); -GLAPI PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements; -#define glDrawRangeElements glad_glDrawRangeElements -typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); -GLAPI PFNGLTEXIMAGE3DPROC glad_glTexImage3D; -#define glTexImage3D glad_glTexImage3D -typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); -GLAPI PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D; -#define glTexSubImage3D glad_glTexSubImage3D -typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); -GLAPI PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D; -#define glCopyTexSubImage3D glad_glCopyTexSubImage3D -#endif -#ifndef GL_VERSION_1_3 -#define GL_VERSION_1_3 1 -GLAPI int GLAD_GL_VERSION_1_3; -typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC)(GLenum texture); -GLAPI PFNGLACTIVETEXTUREPROC glad_glActiveTexture; -#define glActiveTexture glad_glActiveTexture -typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC)(GLfloat value, GLboolean invert); -GLAPI PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage; -#define glSampleCoverage glad_glSampleCoverage -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); -GLAPI PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D; -#define glCompressedTexImage3D glad_glCompressedTexImage3D -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); -GLAPI PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D; -#define glCompressedTexImage2D glad_glCompressedTexImage2D -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); -GLAPI PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D; -#define glCompressedTexImage1D glad_glCompressedTexImage1D -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); -GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D; -#define glCompressedTexSubImage3D glad_glCompressedTexSubImage3D -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); -GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D; -#define glCompressedTexSubImage2D glad_glCompressedTexSubImage2D -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); -GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D; -#define glCompressedTexSubImage1D glad_glCompressedTexSubImage1D -typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC)(GLenum target, GLint level, void *img); -GLAPI PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage; -#define glGetCompressedTexImage glad_glGetCompressedTexImage -typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREPROC)(GLenum texture); -GLAPI PFNGLCLIENTACTIVETEXTUREPROC glad_glClientActiveTexture; -#define glClientActiveTexture glad_glClientActiveTexture -typedef void (APIENTRYP PFNGLMULTITEXCOORD1DPROC)(GLenum target, GLdouble s); -GLAPI PFNGLMULTITEXCOORD1DPROC glad_glMultiTexCoord1d; -#define glMultiTexCoord1d glad_glMultiTexCoord1d -typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVPROC)(GLenum target, const GLdouble *v); -GLAPI PFNGLMULTITEXCOORD1DVPROC glad_glMultiTexCoord1dv; -#define glMultiTexCoord1dv glad_glMultiTexCoord1dv -typedef void (APIENTRYP PFNGLMULTITEXCOORD1FPROC)(GLenum target, GLfloat s); -GLAPI PFNGLMULTITEXCOORD1FPROC glad_glMultiTexCoord1f; -#define glMultiTexCoord1f glad_glMultiTexCoord1f -typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVPROC)(GLenum target, const GLfloat *v); -GLAPI PFNGLMULTITEXCOORD1FVPROC glad_glMultiTexCoord1fv; -#define glMultiTexCoord1fv glad_glMultiTexCoord1fv -typedef void (APIENTRYP PFNGLMULTITEXCOORD1IPROC)(GLenum target, GLint s); -GLAPI PFNGLMULTITEXCOORD1IPROC glad_glMultiTexCoord1i; -#define glMultiTexCoord1i glad_glMultiTexCoord1i -typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVPROC)(GLenum target, const GLint *v); -GLAPI PFNGLMULTITEXCOORD1IVPROC glad_glMultiTexCoord1iv; -#define glMultiTexCoord1iv glad_glMultiTexCoord1iv -typedef void (APIENTRYP PFNGLMULTITEXCOORD1SPROC)(GLenum target, GLshort s); -GLAPI PFNGLMULTITEXCOORD1SPROC glad_glMultiTexCoord1s; -#define glMultiTexCoord1s glad_glMultiTexCoord1s -typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVPROC)(GLenum target, const GLshort *v); -GLAPI PFNGLMULTITEXCOORD1SVPROC glad_glMultiTexCoord1sv; -#define glMultiTexCoord1sv glad_glMultiTexCoord1sv -typedef void (APIENTRYP PFNGLMULTITEXCOORD2DPROC)(GLenum target, GLdouble s, GLdouble t); -GLAPI PFNGLMULTITEXCOORD2DPROC glad_glMultiTexCoord2d; -#define glMultiTexCoord2d glad_glMultiTexCoord2d -typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVPROC)(GLenum target, const GLdouble *v); -GLAPI PFNGLMULTITEXCOORD2DVPROC glad_glMultiTexCoord2dv; -#define glMultiTexCoord2dv glad_glMultiTexCoord2dv -typedef void (APIENTRYP PFNGLMULTITEXCOORD2FPROC)(GLenum target, GLfloat s, GLfloat t); -GLAPI PFNGLMULTITEXCOORD2FPROC glad_glMultiTexCoord2f; -#define glMultiTexCoord2f glad_glMultiTexCoord2f -typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVPROC)(GLenum target, const GLfloat *v); -GLAPI PFNGLMULTITEXCOORD2FVPROC glad_glMultiTexCoord2fv; -#define glMultiTexCoord2fv glad_glMultiTexCoord2fv -typedef void (APIENTRYP PFNGLMULTITEXCOORD2IPROC)(GLenum target, GLint s, GLint t); -GLAPI PFNGLMULTITEXCOORD2IPROC glad_glMultiTexCoord2i; -#define glMultiTexCoord2i glad_glMultiTexCoord2i -typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVPROC)(GLenum target, const GLint *v); -GLAPI PFNGLMULTITEXCOORD2IVPROC glad_glMultiTexCoord2iv; -#define glMultiTexCoord2iv glad_glMultiTexCoord2iv -typedef void (APIENTRYP PFNGLMULTITEXCOORD2SPROC)(GLenum target, GLshort s, GLshort t); -GLAPI PFNGLMULTITEXCOORD2SPROC glad_glMultiTexCoord2s; -#define glMultiTexCoord2s glad_glMultiTexCoord2s -typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVPROC)(GLenum target, const GLshort *v); -GLAPI PFNGLMULTITEXCOORD2SVPROC glad_glMultiTexCoord2sv; -#define glMultiTexCoord2sv glad_glMultiTexCoord2sv -typedef void (APIENTRYP PFNGLMULTITEXCOORD3DPROC)(GLenum target, GLdouble s, GLdouble t, GLdouble r); -GLAPI PFNGLMULTITEXCOORD3DPROC glad_glMultiTexCoord3d; -#define glMultiTexCoord3d glad_glMultiTexCoord3d -typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVPROC)(GLenum target, const GLdouble *v); -GLAPI PFNGLMULTITEXCOORD3DVPROC glad_glMultiTexCoord3dv; -#define glMultiTexCoord3dv glad_glMultiTexCoord3dv -typedef void (APIENTRYP PFNGLMULTITEXCOORD3FPROC)(GLenum target, GLfloat s, GLfloat t, GLfloat r); -GLAPI PFNGLMULTITEXCOORD3FPROC glad_glMultiTexCoord3f; -#define glMultiTexCoord3f glad_glMultiTexCoord3f -typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVPROC)(GLenum target, const GLfloat *v); -GLAPI PFNGLMULTITEXCOORD3FVPROC glad_glMultiTexCoord3fv; -#define glMultiTexCoord3fv glad_glMultiTexCoord3fv -typedef void (APIENTRYP PFNGLMULTITEXCOORD3IPROC)(GLenum target, GLint s, GLint t, GLint r); -GLAPI PFNGLMULTITEXCOORD3IPROC glad_glMultiTexCoord3i; -#define glMultiTexCoord3i glad_glMultiTexCoord3i -typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVPROC)(GLenum target, const GLint *v); -GLAPI PFNGLMULTITEXCOORD3IVPROC glad_glMultiTexCoord3iv; -#define glMultiTexCoord3iv glad_glMultiTexCoord3iv -typedef void (APIENTRYP PFNGLMULTITEXCOORD3SPROC)(GLenum target, GLshort s, GLshort t, GLshort r); -GLAPI PFNGLMULTITEXCOORD3SPROC glad_glMultiTexCoord3s; -#define glMultiTexCoord3s glad_glMultiTexCoord3s -typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVPROC)(GLenum target, const GLshort *v); -GLAPI PFNGLMULTITEXCOORD3SVPROC glad_glMultiTexCoord3sv; -#define glMultiTexCoord3sv glad_glMultiTexCoord3sv -typedef void (APIENTRYP PFNGLMULTITEXCOORD4DPROC)(GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); -GLAPI PFNGLMULTITEXCOORD4DPROC glad_glMultiTexCoord4d; -#define glMultiTexCoord4d glad_glMultiTexCoord4d -typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVPROC)(GLenum target, const GLdouble *v); -GLAPI PFNGLMULTITEXCOORD4DVPROC glad_glMultiTexCoord4dv; -#define glMultiTexCoord4dv glad_glMultiTexCoord4dv -typedef void (APIENTRYP PFNGLMULTITEXCOORD4FPROC)(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); -GLAPI PFNGLMULTITEXCOORD4FPROC glad_glMultiTexCoord4f; -#define glMultiTexCoord4f glad_glMultiTexCoord4f -typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVPROC)(GLenum target, const GLfloat *v); -GLAPI PFNGLMULTITEXCOORD4FVPROC glad_glMultiTexCoord4fv; -#define glMultiTexCoord4fv glad_glMultiTexCoord4fv -typedef void (APIENTRYP PFNGLMULTITEXCOORD4IPROC)(GLenum target, GLint s, GLint t, GLint r, GLint q); -GLAPI PFNGLMULTITEXCOORD4IPROC glad_glMultiTexCoord4i; -#define glMultiTexCoord4i glad_glMultiTexCoord4i -typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVPROC)(GLenum target, const GLint *v); -GLAPI PFNGLMULTITEXCOORD4IVPROC glad_glMultiTexCoord4iv; -#define glMultiTexCoord4iv glad_glMultiTexCoord4iv -typedef void (APIENTRYP PFNGLMULTITEXCOORD4SPROC)(GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); -GLAPI PFNGLMULTITEXCOORD4SPROC glad_glMultiTexCoord4s; -#define glMultiTexCoord4s glad_glMultiTexCoord4s -typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVPROC)(GLenum target, const GLshort *v); -GLAPI PFNGLMULTITEXCOORD4SVPROC glad_glMultiTexCoord4sv; -#define glMultiTexCoord4sv glad_glMultiTexCoord4sv -typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFPROC)(const GLfloat *m); -GLAPI PFNGLLOADTRANSPOSEMATRIXFPROC glad_glLoadTransposeMatrixf; -#define glLoadTransposeMatrixf glad_glLoadTransposeMatrixf -typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDPROC)(const GLdouble *m); -GLAPI PFNGLLOADTRANSPOSEMATRIXDPROC glad_glLoadTransposeMatrixd; -#define glLoadTransposeMatrixd glad_glLoadTransposeMatrixd -typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFPROC)(const GLfloat *m); -GLAPI PFNGLMULTTRANSPOSEMATRIXFPROC glad_glMultTransposeMatrixf; -#define glMultTransposeMatrixf glad_glMultTransposeMatrixf -typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDPROC)(const GLdouble *m); -GLAPI PFNGLMULTTRANSPOSEMATRIXDPROC glad_glMultTransposeMatrixd; -#define glMultTransposeMatrixd glad_glMultTransposeMatrixd -#endif -#ifndef GL_VERSION_1_4 -#define GL_VERSION_1_4 1 -GLAPI int GLAD_GL_VERSION_1_4; -typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC)(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); -GLAPI PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate; -#define glBlendFuncSeparate glad_glBlendFuncSeparate -typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC)(GLenum mode, const GLint *first, const GLsizei *count, GLsizei drawcount); -GLAPI PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays; -#define glMultiDrawArrays glad_glMultiDrawArrays -typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC)(GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount); -GLAPI PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements; -#define glMultiDrawElements glad_glMultiDrawElements -typedef void (APIENTRYP PFNGLPOINTPARAMETERFPROC)(GLenum pname, GLfloat param); -GLAPI PFNGLPOINTPARAMETERFPROC glad_glPointParameterf; -#define glPointParameterf glad_glPointParameterf -typedef void (APIENTRYP PFNGLPOINTPARAMETERFVPROC)(GLenum pname, const GLfloat *params); -GLAPI PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv; -#define glPointParameterfv glad_glPointParameterfv -typedef void (APIENTRYP PFNGLPOINTPARAMETERIPROC)(GLenum pname, GLint param); -GLAPI PFNGLPOINTPARAMETERIPROC glad_glPointParameteri; -#define glPointParameteri glad_glPointParameteri -typedef void (APIENTRYP PFNGLPOINTPARAMETERIVPROC)(GLenum pname, const GLint *params); -GLAPI PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv; -#define glPointParameteriv glad_glPointParameteriv -typedef void (APIENTRYP PFNGLFOGCOORDFPROC)(GLfloat coord); -GLAPI PFNGLFOGCOORDFPROC glad_glFogCoordf; -#define glFogCoordf glad_glFogCoordf -typedef void (APIENTRYP PFNGLFOGCOORDFVPROC)(const GLfloat *coord); -GLAPI PFNGLFOGCOORDFVPROC glad_glFogCoordfv; -#define glFogCoordfv glad_glFogCoordfv -typedef void (APIENTRYP PFNGLFOGCOORDDPROC)(GLdouble coord); -GLAPI PFNGLFOGCOORDDPROC glad_glFogCoordd; -#define glFogCoordd glad_glFogCoordd -typedef void (APIENTRYP PFNGLFOGCOORDDVPROC)(const GLdouble *coord); -GLAPI PFNGLFOGCOORDDVPROC glad_glFogCoorddv; -#define glFogCoorddv glad_glFogCoorddv -typedef void (APIENTRYP PFNGLFOGCOORDPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer); -GLAPI PFNGLFOGCOORDPOINTERPROC glad_glFogCoordPointer; -#define glFogCoordPointer glad_glFogCoordPointer -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BPROC)(GLbyte red, GLbyte green, GLbyte blue); -GLAPI PFNGLSECONDARYCOLOR3BPROC glad_glSecondaryColor3b; -#define glSecondaryColor3b glad_glSecondaryColor3b -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVPROC)(const GLbyte *v); -GLAPI PFNGLSECONDARYCOLOR3BVPROC glad_glSecondaryColor3bv; -#define glSecondaryColor3bv glad_glSecondaryColor3bv -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DPROC)(GLdouble red, GLdouble green, GLdouble blue); -GLAPI PFNGLSECONDARYCOLOR3DPROC glad_glSecondaryColor3d; -#define glSecondaryColor3d glad_glSecondaryColor3d -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVPROC)(const GLdouble *v); -GLAPI PFNGLSECONDARYCOLOR3DVPROC glad_glSecondaryColor3dv; -#define glSecondaryColor3dv glad_glSecondaryColor3dv -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FPROC)(GLfloat red, GLfloat green, GLfloat blue); -GLAPI PFNGLSECONDARYCOLOR3FPROC glad_glSecondaryColor3f; -#define glSecondaryColor3f glad_glSecondaryColor3f -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVPROC)(const GLfloat *v); -GLAPI PFNGLSECONDARYCOLOR3FVPROC glad_glSecondaryColor3fv; -#define glSecondaryColor3fv glad_glSecondaryColor3fv -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IPROC)(GLint red, GLint green, GLint blue); -GLAPI PFNGLSECONDARYCOLOR3IPROC glad_glSecondaryColor3i; -#define glSecondaryColor3i glad_glSecondaryColor3i -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVPROC)(const GLint *v); -GLAPI PFNGLSECONDARYCOLOR3IVPROC glad_glSecondaryColor3iv; -#define glSecondaryColor3iv glad_glSecondaryColor3iv -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SPROC)(GLshort red, GLshort green, GLshort blue); -GLAPI PFNGLSECONDARYCOLOR3SPROC glad_glSecondaryColor3s; -#define glSecondaryColor3s glad_glSecondaryColor3s -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVPROC)(const GLshort *v); -GLAPI PFNGLSECONDARYCOLOR3SVPROC glad_glSecondaryColor3sv; -#define glSecondaryColor3sv glad_glSecondaryColor3sv -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBPROC)(GLubyte red, GLubyte green, GLubyte blue); -GLAPI PFNGLSECONDARYCOLOR3UBPROC glad_glSecondaryColor3ub; -#define glSecondaryColor3ub glad_glSecondaryColor3ub -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVPROC)(const GLubyte *v); -GLAPI PFNGLSECONDARYCOLOR3UBVPROC glad_glSecondaryColor3ubv; -#define glSecondaryColor3ubv glad_glSecondaryColor3ubv -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIPROC)(GLuint red, GLuint green, GLuint blue); -GLAPI PFNGLSECONDARYCOLOR3UIPROC glad_glSecondaryColor3ui; -#define glSecondaryColor3ui glad_glSecondaryColor3ui -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVPROC)(const GLuint *v); -GLAPI PFNGLSECONDARYCOLOR3UIVPROC glad_glSecondaryColor3uiv; -#define glSecondaryColor3uiv glad_glSecondaryColor3uiv -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USPROC)(GLushort red, GLushort green, GLushort blue); -GLAPI PFNGLSECONDARYCOLOR3USPROC glad_glSecondaryColor3us; -#define glSecondaryColor3us glad_glSecondaryColor3us -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVPROC)(const GLushort *v); -GLAPI PFNGLSECONDARYCOLOR3USVPROC glad_glSecondaryColor3usv; -#define glSecondaryColor3usv glad_glSecondaryColor3usv -typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); -GLAPI PFNGLSECONDARYCOLORPOINTERPROC glad_glSecondaryColorPointer; -#define glSecondaryColorPointer glad_glSecondaryColorPointer -typedef void (APIENTRYP PFNGLWINDOWPOS2DPROC)(GLdouble x, GLdouble y); -GLAPI PFNGLWINDOWPOS2DPROC glad_glWindowPos2d; -#define glWindowPos2d glad_glWindowPos2d -typedef void (APIENTRYP PFNGLWINDOWPOS2DVPROC)(const GLdouble *v); -GLAPI PFNGLWINDOWPOS2DVPROC glad_glWindowPos2dv; -#define glWindowPos2dv glad_glWindowPos2dv -typedef void (APIENTRYP PFNGLWINDOWPOS2FPROC)(GLfloat x, GLfloat y); -GLAPI PFNGLWINDOWPOS2FPROC glad_glWindowPos2f; -#define glWindowPos2f glad_glWindowPos2f -typedef void (APIENTRYP PFNGLWINDOWPOS2FVPROC)(const GLfloat *v); -GLAPI PFNGLWINDOWPOS2FVPROC glad_glWindowPos2fv; -#define glWindowPos2fv glad_glWindowPos2fv -typedef void (APIENTRYP PFNGLWINDOWPOS2IPROC)(GLint x, GLint y); -GLAPI PFNGLWINDOWPOS2IPROC glad_glWindowPos2i; -#define glWindowPos2i glad_glWindowPos2i -typedef void (APIENTRYP PFNGLWINDOWPOS2IVPROC)(const GLint *v); -GLAPI PFNGLWINDOWPOS2IVPROC glad_glWindowPos2iv; -#define glWindowPos2iv glad_glWindowPos2iv -typedef void (APIENTRYP PFNGLWINDOWPOS2SPROC)(GLshort x, GLshort y); -GLAPI PFNGLWINDOWPOS2SPROC glad_glWindowPos2s; -#define glWindowPos2s glad_glWindowPos2s -typedef void (APIENTRYP PFNGLWINDOWPOS2SVPROC)(const GLshort *v); -GLAPI PFNGLWINDOWPOS2SVPROC glad_glWindowPos2sv; -#define glWindowPos2sv glad_glWindowPos2sv -typedef void (APIENTRYP PFNGLWINDOWPOS3DPROC)(GLdouble x, GLdouble y, GLdouble z); -GLAPI PFNGLWINDOWPOS3DPROC glad_glWindowPos3d; -#define glWindowPos3d glad_glWindowPos3d -typedef void (APIENTRYP PFNGLWINDOWPOS3DVPROC)(const GLdouble *v); -GLAPI PFNGLWINDOWPOS3DVPROC glad_glWindowPos3dv; -#define glWindowPos3dv glad_glWindowPos3dv -typedef void (APIENTRYP PFNGLWINDOWPOS3FPROC)(GLfloat x, GLfloat y, GLfloat z); -GLAPI PFNGLWINDOWPOS3FPROC glad_glWindowPos3f; -#define glWindowPos3f glad_glWindowPos3f -typedef void (APIENTRYP PFNGLWINDOWPOS3FVPROC)(const GLfloat *v); -GLAPI PFNGLWINDOWPOS3FVPROC glad_glWindowPos3fv; -#define glWindowPos3fv glad_glWindowPos3fv -typedef void (APIENTRYP PFNGLWINDOWPOS3IPROC)(GLint x, GLint y, GLint z); -GLAPI PFNGLWINDOWPOS3IPROC glad_glWindowPos3i; -#define glWindowPos3i glad_glWindowPos3i -typedef void (APIENTRYP PFNGLWINDOWPOS3IVPROC)(const GLint *v); -GLAPI PFNGLWINDOWPOS3IVPROC glad_glWindowPos3iv; -#define glWindowPos3iv glad_glWindowPos3iv -typedef void (APIENTRYP PFNGLWINDOWPOS3SPROC)(GLshort x, GLshort y, GLshort z); -GLAPI PFNGLWINDOWPOS3SPROC glad_glWindowPos3s; -#define glWindowPos3s glad_glWindowPos3s -typedef void (APIENTRYP PFNGLWINDOWPOS3SVPROC)(const GLshort *v); -GLAPI PFNGLWINDOWPOS3SVPROC glad_glWindowPos3sv; -#define glWindowPos3sv glad_glWindowPos3sv -typedef void (APIENTRYP PFNGLBLENDCOLORPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); -GLAPI PFNGLBLENDCOLORPROC glad_glBlendColor; -#define glBlendColor glad_glBlendColor -typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC)(GLenum mode); -GLAPI PFNGLBLENDEQUATIONPROC glad_glBlendEquation; -#define glBlendEquation glad_glBlendEquation -#endif -#ifndef GL_VERSION_1_5 -#define GL_VERSION_1_5 1 -GLAPI int GLAD_GL_VERSION_1_5; -typedef void (APIENTRYP PFNGLGENQUERIESPROC)(GLsizei n, GLuint *ids); -GLAPI PFNGLGENQUERIESPROC glad_glGenQueries; -#define glGenQueries glad_glGenQueries -typedef void (APIENTRYP PFNGLDELETEQUERIESPROC)(GLsizei n, const GLuint *ids); -GLAPI PFNGLDELETEQUERIESPROC glad_glDeleteQueries; -#define glDeleteQueries glad_glDeleteQueries -typedef GLboolean (APIENTRYP PFNGLISQUERYPROC)(GLuint id); -GLAPI PFNGLISQUERYPROC glad_glIsQuery; -#define glIsQuery glad_glIsQuery -typedef void (APIENTRYP PFNGLBEGINQUERYPROC)(GLenum target, GLuint id); -GLAPI PFNGLBEGINQUERYPROC glad_glBeginQuery; -#define glBeginQuery glad_glBeginQuery -typedef void (APIENTRYP PFNGLENDQUERYPROC)(GLenum target); -GLAPI PFNGLENDQUERYPROC glad_glEndQuery; -#define glEndQuery glad_glEndQuery -typedef void (APIENTRYP PFNGLGETQUERYIVPROC)(GLenum target, GLenum pname, GLint *params); -GLAPI PFNGLGETQUERYIVPROC glad_glGetQueryiv; -#define glGetQueryiv glad_glGetQueryiv -typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC)(GLuint id, GLenum pname, GLint *params); -GLAPI PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv; -#define glGetQueryObjectiv glad_glGetQueryObjectiv -typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC)(GLuint id, GLenum pname, GLuint *params); -GLAPI PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv; -#define glGetQueryObjectuiv glad_glGetQueryObjectuiv -typedef void (APIENTRYP PFNGLBINDBUFFERPROC)(GLenum target, GLuint buffer); -GLAPI PFNGLBINDBUFFERPROC glad_glBindBuffer; -#define glBindBuffer glad_glBindBuffer -typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC)(GLsizei n, const GLuint *buffers); -GLAPI PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers; -#define glDeleteBuffers glad_glDeleteBuffers -typedef void (APIENTRYP PFNGLGENBUFFERSPROC)(GLsizei n, GLuint *buffers); -GLAPI PFNGLGENBUFFERSPROC glad_glGenBuffers; -#define glGenBuffers glad_glGenBuffers -typedef GLboolean (APIENTRYP PFNGLISBUFFERPROC)(GLuint buffer); -GLAPI PFNGLISBUFFERPROC glad_glIsBuffer; -#define glIsBuffer glad_glIsBuffer -typedef void (APIENTRYP PFNGLBUFFERDATAPROC)(GLenum target, GLsizeiptr size, const void *data, GLenum usage); -GLAPI PFNGLBUFFERDATAPROC glad_glBufferData; -#define glBufferData glad_glBufferData -typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC)(GLenum target, GLintptr offset, GLsizeiptr size, const void *data); -GLAPI PFNGLBUFFERSUBDATAPROC glad_glBufferSubData; -#define glBufferSubData glad_glBufferSubData -typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC)(GLenum target, GLintptr offset, GLsizeiptr size, void *data); -GLAPI PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData; -#define glGetBufferSubData glad_glGetBufferSubData -typedef void * (APIENTRYP PFNGLMAPBUFFERPROC)(GLenum target, GLenum access); -GLAPI PFNGLMAPBUFFERPROC glad_glMapBuffer; -#define glMapBuffer glad_glMapBuffer -typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC)(GLenum target); -GLAPI PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer; -#define glUnmapBuffer glad_glUnmapBuffer -typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); -GLAPI PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv; -#define glGetBufferParameteriv glad_glGetBufferParameteriv -typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC)(GLenum target, GLenum pname, void **params); -GLAPI PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv; -#define glGetBufferPointerv glad_glGetBufferPointerv -#endif -#ifndef GL_VERSION_2_0 -#define GL_VERSION_2_0 1 -GLAPI int GLAD_GL_VERSION_2_0; -typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC)(GLenum modeRGB, GLenum modeAlpha); -GLAPI PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate; -#define glBlendEquationSeparate glad_glBlendEquationSeparate -typedef void (APIENTRYP PFNGLDRAWBUFFERSPROC)(GLsizei n, const GLenum *bufs); -GLAPI PFNGLDRAWBUFFERSPROC glad_glDrawBuffers; -#define glDrawBuffers glad_glDrawBuffers -typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEPROC)(GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); -GLAPI PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate; -#define glStencilOpSeparate glad_glStencilOpSeparate -typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC)(GLenum face, GLenum func, GLint ref, GLuint mask); -GLAPI PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate; -#define glStencilFuncSeparate glad_glStencilFuncSeparate -typedef void (APIENTRYP PFNGLSTENCILMASKSEPARATEPROC)(GLenum face, GLuint mask); -GLAPI PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate; -#define glStencilMaskSeparate glad_glStencilMaskSeparate -typedef void (APIENTRYP PFNGLATTACHSHADERPROC)(GLuint program, GLuint shader); -GLAPI PFNGLATTACHSHADERPROC glad_glAttachShader; -#define glAttachShader glad_glAttachShader -typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONPROC)(GLuint program, GLuint index, const GLchar *name); -GLAPI PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation; -#define glBindAttribLocation glad_glBindAttribLocation -typedef void (APIENTRYP PFNGLCOMPILESHADERPROC)(GLuint shader); -GLAPI PFNGLCOMPILESHADERPROC glad_glCompileShader; -#define glCompileShader glad_glCompileShader -typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC)(void); -GLAPI PFNGLCREATEPROGRAMPROC glad_glCreateProgram; -#define glCreateProgram glad_glCreateProgram -typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC)(GLenum type); -GLAPI PFNGLCREATESHADERPROC glad_glCreateShader; -#define glCreateShader glad_glCreateShader -typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC)(GLuint program); -GLAPI PFNGLDELETEPROGRAMPROC glad_glDeleteProgram; -#define glDeleteProgram glad_glDeleteProgram -typedef void (APIENTRYP PFNGLDELETESHADERPROC)(GLuint shader); -GLAPI PFNGLDELETESHADERPROC glad_glDeleteShader; -#define glDeleteShader glad_glDeleteShader -typedef void (APIENTRYP PFNGLDETACHSHADERPROC)(GLuint program, GLuint shader); -GLAPI PFNGLDETACHSHADERPROC glad_glDetachShader; -#define glDetachShader glad_glDetachShader -typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC)(GLuint index); -GLAPI PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray; -#define glDisableVertexAttribArray glad_glDisableVertexAttribArray -typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC)(GLuint index); -GLAPI PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray; -#define glEnableVertexAttribArray glad_glEnableVertexAttribArray -typedef void (APIENTRYP PFNGLGETACTIVEATTRIBPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); -GLAPI PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib; -#define glGetActiveAttrib glad_glGetActiveAttrib -typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); -GLAPI PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform; -#define glGetActiveUniform glad_glGetActiveUniform -typedef void (APIENTRYP PFNGLGETATTACHEDSHADERSPROC)(GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); -GLAPI PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders; -#define glGetAttachedShaders glad_glGetAttachedShaders -typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC)(GLuint program, const GLchar *name); -GLAPI PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation; -#define glGetAttribLocation glad_glGetAttribLocation -typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC)(GLuint program, GLenum pname, GLint *params); -GLAPI PFNGLGETPROGRAMIVPROC glad_glGetProgramiv; -#define glGetProgramiv glad_glGetProgramiv -typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC)(GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); -GLAPI PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog; -#define glGetProgramInfoLog glad_glGetProgramInfoLog -typedef void (APIENTRYP PFNGLGETSHADERIVPROC)(GLuint shader, GLenum pname, GLint *params); -GLAPI PFNGLGETSHADERIVPROC glad_glGetShaderiv; -#define glGetShaderiv glad_glGetShaderiv -typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); -GLAPI PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog; -#define glGetShaderInfoLog glad_glGetShaderInfoLog -typedef void (APIENTRYP PFNGLGETSHADERSOURCEPROC)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); -GLAPI PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource; -#define glGetShaderSource glad_glGetShaderSource -typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC)(GLuint program, const GLchar *name); -GLAPI PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation; -#define glGetUniformLocation glad_glGetUniformLocation -typedef void (APIENTRYP PFNGLGETUNIFORMFVPROC)(GLuint program, GLint location, GLfloat *params); -GLAPI PFNGLGETUNIFORMFVPROC glad_glGetUniformfv; -#define glGetUniformfv glad_glGetUniformfv -typedef void (APIENTRYP PFNGLGETUNIFORMIVPROC)(GLuint program, GLint location, GLint *params); -GLAPI PFNGLGETUNIFORMIVPROC glad_glGetUniformiv; -#define glGetUniformiv glad_glGetUniformiv -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVPROC)(GLuint index, GLenum pname, GLdouble *params); -GLAPI PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv; -#define glGetVertexAttribdv glad_glGetVertexAttribdv -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVPROC)(GLuint index, GLenum pname, GLfloat *params); -GLAPI PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv; -#define glGetVertexAttribfv glad_glGetVertexAttribfv -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC)(GLuint index, GLenum pname, GLint *params); -GLAPI PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv; -#define glGetVertexAttribiv glad_glGetVertexAttribiv -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC)(GLuint index, GLenum pname, void **pointer); -GLAPI PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv; -#define glGetVertexAttribPointerv glad_glGetVertexAttribPointerv -typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC)(GLuint program); -GLAPI PFNGLISPROGRAMPROC glad_glIsProgram; -#define glIsProgram glad_glIsProgram -typedef GLboolean (APIENTRYP PFNGLISSHADERPROC)(GLuint shader); -GLAPI PFNGLISSHADERPROC glad_glIsShader; -#define glIsShader glad_glIsShader -typedef void (APIENTRYP PFNGLLINKPROGRAMPROC)(GLuint program); -GLAPI PFNGLLINKPROGRAMPROC glad_glLinkProgram; -#define glLinkProgram glad_glLinkProgram -typedef void (APIENTRYP PFNGLSHADERSOURCEPROC)(GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); -GLAPI PFNGLSHADERSOURCEPROC glad_glShaderSource; -#define glShaderSource glad_glShaderSource -typedef void (APIENTRYP PFNGLUSEPROGRAMPROC)(GLuint program); -GLAPI PFNGLUSEPROGRAMPROC glad_glUseProgram; -#define glUseProgram glad_glUseProgram -typedef void (APIENTRYP PFNGLUNIFORM1FPROC)(GLint location, GLfloat v0); -GLAPI PFNGLUNIFORM1FPROC glad_glUniform1f; -#define glUniform1f glad_glUniform1f -typedef void (APIENTRYP PFNGLUNIFORM2FPROC)(GLint location, GLfloat v0, GLfloat v1); -GLAPI PFNGLUNIFORM2FPROC glad_glUniform2f; -#define glUniform2f glad_glUniform2f -typedef void (APIENTRYP PFNGLUNIFORM3FPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2); -GLAPI PFNGLUNIFORM3FPROC glad_glUniform3f; -#define glUniform3f glad_glUniform3f -typedef void (APIENTRYP PFNGLUNIFORM4FPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); -GLAPI PFNGLUNIFORM4FPROC glad_glUniform4f; -#define glUniform4f glad_glUniform4f -typedef void (APIENTRYP PFNGLUNIFORM1IPROC)(GLint location, GLint v0); -GLAPI PFNGLUNIFORM1IPROC glad_glUniform1i; -#define glUniform1i glad_glUniform1i -typedef void (APIENTRYP PFNGLUNIFORM2IPROC)(GLint location, GLint v0, GLint v1); -GLAPI PFNGLUNIFORM2IPROC glad_glUniform2i; -#define glUniform2i glad_glUniform2i -typedef void (APIENTRYP PFNGLUNIFORM3IPROC)(GLint location, GLint v0, GLint v1, GLint v2); -GLAPI PFNGLUNIFORM3IPROC glad_glUniform3i; -#define glUniform3i glad_glUniform3i -typedef void (APIENTRYP PFNGLUNIFORM4IPROC)(GLint location, GLint v0, GLint v1, GLint v2, GLint v3); -GLAPI PFNGLUNIFORM4IPROC glad_glUniform4i; -#define glUniform4i glad_glUniform4i -typedef void (APIENTRYP PFNGLUNIFORM1FVPROC)(GLint location, GLsizei count, const GLfloat *value); -GLAPI PFNGLUNIFORM1FVPROC glad_glUniform1fv; -#define glUniform1fv glad_glUniform1fv -typedef void (APIENTRYP PFNGLUNIFORM2FVPROC)(GLint location, GLsizei count, const GLfloat *value); -GLAPI PFNGLUNIFORM2FVPROC glad_glUniform2fv; -#define glUniform2fv glad_glUniform2fv -typedef void (APIENTRYP PFNGLUNIFORM3FVPROC)(GLint location, GLsizei count, const GLfloat *value); -GLAPI PFNGLUNIFORM3FVPROC glad_glUniform3fv; -#define glUniform3fv glad_glUniform3fv -typedef void (APIENTRYP PFNGLUNIFORM4FVPROC)(GLint location, GLsizei count, const GLfloat *value); -GLAPI PFNGLUNIFORM4FVPROC glad_glUniform4fv; -#define glUniform4fv glad_glUniform4fv -typedef void (APIENTRYP PFNGLUNIFORM1IVPROC)(GLint location, GLsizei count, const GLint *value); -GLAPI PFNGLUNIFORM1IVPROC glad_glUniform1iv; -#define glUniform1iv glad_glUniform1iv -typedef void (APIENTRYP PFNGLUNIFORM2IVPROC)(GLint location, GLsizei count, const GLint *value); -GLAPI PFNGLUNIFORM2IVPROC glad_glUniform2iv; -#define glUniform2iv glad_glUniform2iv -typedef void (APIENTRYP PFNGLUNIFORM3IVPROC)(GLint location, GLsizei count, const GLint *value); -GLAPI PFNGLUNIFORM3IVPROC glad_glUniform3iv; -#define glUniform3iv glad_glUniform3iv -typedef void (APIENTRYP PFNGLUNIFORM4IVPROC)(GLint location, GLsizei count, const GLint *value); -GLAPI PFNGLUNIFORM4IVPROC glad_glUniform4iv; -#define glUniform4iv glad_glUniform4iv -typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv; -#define glUniformMatrix2fv glad_glUniformMatrix2fv -typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv; -#define glUniformMatrix3fv glad_glUniformMatrix3fv -typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv; -#define glUniformMatrix4fv glad_glUniformMatrix4fv -typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC)(GLuint program); -GLAPI PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram; -#define glValidateProgram glad_glValidateProgram -typedef void (APIENTRYP PFNGLVERTEXATTRIB1DPROC)(GLuint index, GLdouble x); -GLAPI PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d; -#define glVertexAttrib1d glad_glVertexAttrib1d -typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVPROC)(GLuint index, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv; -#define glVertexAttrib1dv glad_glVertexAttrib1dv -typedef void (APIENTRYP PFNGLVERTEXATTRIB1FPROC)(GLuint index, GLfloat x); -GLAPI PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f; -#define glVertexAttrib1f glad_glVertexAttrib1f -typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVPROC)(GLuint index, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv; -#define glVertexAttrib1fv glad_glVertexAttrib1fv -typedef void (APIENTRYP PFNGLVERTEXATTRIB1SPROC)(GLuint index, GLshort x); -GLAPI PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s; -#define glVertexAttrib1s glad_glVertexAttrib1s -typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv; -#define glVertexAttrib1sv glad_glVertexAttrib1sv -typedef void (APIENTRYP PFNGLVERTEXATTRIB2DPROC)(GLuint index, GLdouble x, GLdouble y); -GLAPI PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d; -#define glVertexAttrib2d glad_glVertexAttrib2d -typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVPROC)(GLuint index, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv; -#define glVertexAttrib2dv glad_glVertexAttrib2dv -typedef void (APIENTRYP PFNGLVERTEXATTRIB2FPROC)(GLuint index, GLfloat x, GLfloat y); -GLAPI PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f; -#define glVertexAttrib2f glad_glVertexAttrib2f -typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVPROC)(GLuint index, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv; -#define glVertexAttrib2fv glad_glVertexAttrib2fv -typedef void (APIENTRYP PFNGLVERTEXATTRIB2SPROC)(GLuint index, GLshort x, GLshort y); -GLAPI PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s; -#define glVertexAttrib2s glad_glVertexAttrib2s -typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv; -#define glVertexAttrib2sv glad_glVertexAttrib2sv -typedef void (APIENTRYP PFNGLVERTEXATTRIB3DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z); -GLAPI PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d; -#define glVertexAttrib3d glad_glVertexAttrib3d -typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVPROC)(GLuint index, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv; -#define glVertexAttrib3dv glad_glVertexAttrib3dv -typedef void (APIENTRYP PFNGLVERTEXATTRIB3FPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z); -GLAPI PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f; -#define glVertexAttrib3f glad_glVertexAttrib3f -typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVPROC)(GLuint index, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv; -#define glVertexAttrib3fv glad_glVertexAttrib3fv -typedef void (APIENTRYP PFNGLVERTEXATTRIB3SPROC)(GLuint index, GLshort x, GLshort y, GLshort z); -GLAPI PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s; -#define glVertexAttrib3s glad_glVertexAttrib3s -typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv; -#define glVertexAttrib3sv glad_glVertexAttrib3sv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVPROC)(GLuint index, const GLbyte *v); -GLAPI PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv; -#define glVertexAttrib4Nbv glad_glVertexAttrib4Nbv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVPROC)(GLuint index, const GLint *v); -GLAPI PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv; -#define glVertexAttrib4Niv glad_glVertexAttrib4Niv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv; -#define glVertexAttrib4Nsv glad_glVertexAttrib4Nsv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBPROC)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); -GLAPI PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub; -#define glVertexAttrib4Nub glad_glVertexAttrib4Nub -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC)(GLuint index, const GLubyte *v); -GLAPI PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv; -#define glVertexAttrib4Nubv glad_glVertexAttrib4Nubv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC)(GLuint index, const GLuint *v); -GLAPI PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv; -#define glVertexAttrib4Nuiv glad_glVertexAttrib4Nuiv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC)(GLuint index, const GLushort *v); -GLAPI PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv; -#define glVertexAttrib4Nusv glad_glVertexAttrib4Nusv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVPROC)(GLuint index, const GLbyte *v); -GLAPI PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv; -#define glVertexAttrib4bv glad_glVertexAttrib4bv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); -GLAPI PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d; -#define glVertexAttrib4d glad_glVertexAttrib4d -typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVPROC)(GLuint index, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv; -#define glVertexAttrib4dv glad_glVertexAttrib4dv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4FPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); -GLAPI PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f; -#define glVertexAttrib4f glad_glVertexAttrib4f -typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVPROC)(GLuint index, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv; -#define glVertexAttrib4fv glad_glVertexAttrib4fv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVPROC)(GLuint index, const GLint *v); -GLAPI PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv; -#define glVertexAttrib4iv glad_glVertexAttrib4iv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4SPROC)(GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); -GLAPI PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s; -#define glVertexAttrib4s glad_glVertexAttrib4s -typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv; -#define glVertexAttrib4sv glad_glVertexAttrib4sv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVPROC)(GLuint index, const GLubyte *v); -GLAPI PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv; -#define glVertexAttrib4ubv glad_glVertexAttrib4ubv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVPROC)(GLuint index, const GLuint *v); -GLAPI PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv; -#define glVertexAttrib4uiv glad_glVertexAttrib4uiv -typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVPROC)(GLuint index, const GLushort *v); -GLAPI PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv; -#define glVertexAttrib4usv glad_glVertexAttrib4usv -typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); -GLAPI PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer; -#define glVertexAttribPointer glad_glVertexAttribPointer -#endif -#ifndef GL_VERSION_2_1 -#define GL_VERSION_2_1 1 -GLAPI int GLAD_GL_VERSION_2_1; -typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX2X3FVPROC glad_glUniformMatrix2x3fv; -#define glUniformMatrix2x3fv glad_glUniformMatrix2x3fv -typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX3X2FVPROC glad_glUniformMatrix3x2fv; -#define glUniformMatrix3x2fv glad_glUniformMatrix3x2fv -typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX2X4FVPROC glad_glUniformMatrix2x4fv; -#define glUniformMatrix2x4fv glad_glUniformMatrix2x4fv -typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX4X2FVPROC glad_glUniformMatrix4x2fv; -#define glUniformMatrix4x2fv glad_glUniformMatrix4x2fv -typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX3X4FVPROC glad_glUniformMatrix3x4fv; -#define glUniformMatrix3x4fv glad_glUniformMatrix3x4fv -typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX4X3FVPROC glad_glUniformMatrix4x3fv; -#define glUniformMatrix4x3fv glad_glUniformMatrix4x3fv -#endif -#define GL_DEPTH_COMPONENT32F 0x8CAC -#define GL_DEPTH32F_STENCIL8 0x8CAD -#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD -#define GL_MAX_DRAW_BUFFERS_ARB 0x8824 -#define GL_DRAW_BUFFER0_ARB 0x8825 -#define GL_DRAW_BUFFER1_ARB 0x8826 -#define GL_DRAW_BUFFER2_ARB 0x8827 -#define GL_DRAW_BUFFER3_ARB 0x8828 -#define GL_DRAW_BUFFER4_ARB 0x8829 -#define GL_DRAW_BUFFER5_ARB 0x882A -#define GL_DRAW_BUFFER6_ARB 0x882B -#define GL_DRAW_BUFFER7_ARB 0x882C -#define GL_DRAW_BUFFER8_ARB 0x882D -#define GL_DRAW_BUFFER9_ARB 0x882E -#define GL_DRAW_BUFFER10_ARB 0x882F -#define GL_DRAW_BUFFER11_ARB 0x8830 -#define GL_DRAW_BUFFER12_ARB 0x8831 -#define GL_DRAW_BUFFER13_ARB 0x8832 -#define GL_DRAW_BUFFER14_ARB 0x8833 -#define GL_DRAW_BUFFER15_ARB 0x8834 -#define GL_FRAGMENT_PROGRAM_ARB 0x8804 -#define GL_PROGRAM_FORMAT_ASCII_ARB 0x8875 -#define GL_PROGRAM_LENGTH_ARB 0x8627 -#define GL_PROGRAM_FORMAT_ARB 0x8876 -#define GL_PROGRAM_BINDING_ARB 0x8677 -#define GL_PROGRAM_INSTRUCTIONS_ARB 0x88A0 -#define GL_MAX_PROGRAM_INSTRUCTIONS_ARB 0x88A1 -#define GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A2 -#define GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A3 -#define GL_PROGRAM_TEMPORARIES_ARB 0x88A4 -#define GL_MAX_PROGRAM_TEMPORARIES_ARB 0x88A5 -#define GL_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A6 -#define GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A7 -#define GL_PROGRAM_PARAMETERS_ARB 0x88A8 -#define GL_MAX_PROGRAM_PARAMETERS_ARB 0x88A9 -#define GL_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AA -#define GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AB -#define GL_PROGRAM_ATTRIBS_ARB 0x88AC -#define GL_MAX_PROGRAM_ATTRIBS_ARB 0x88AD -#define GL_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AE -#define GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AF -#define GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB 0x88B4 -#define GL_MAX_PROGRAM_ENV_PARAMETERS_ARB 0x88B5 -#define GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB 0x88B6 -#define GL_PROGRAM_ALU_INSTRUCTIONS_ARB 0x8805 -#define GL_PROGRAM_TEX_INSTRUCTIONS_ARB 0x8806 -#define GL_PROGRAM_TEX_INDIRECTIONS_ARB 0x8807 -#define GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x8808 -#define GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x8809 -#define GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x880A -#define GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB 0x880B -#define GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB 0x880C -#define GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB 0x880D -#define GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x880E -#define GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x880F -#define GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x8810 -#define GL_PROGRAM_STRING_ARB 0x8628 -#define GL_PROGRAM_ERROR_POSITION_ARB 0x864B -#define GL_CURRENT_MATRIX_ARB 0x8641 -#define GL_TRANSPOSE_CURRENT_MATRIX_ARB 0x88B7 -#define GL_CURRENT_MATRIX_STACK_DEPTH_ARB 0x8640 -#define GL_MAX_PROGRAM_MATRICES_ARB 0x862F -#define GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB 0x862E -#define GL_MAX_TEXTURE_COORDS_ARB 0x8871 -#define GL_MAX_TEXTURE_IMAGE_UNITS_ARB 0x8872 -#define GL_PROGRAM_ERROR_STRING_ARB 0x8874 -#define GL_MATRIX0_ARB 0x88C0 -#define GL_MATRIX1_ARB 0x88C1 -#define GL_MATRIX2_ARB 0x88C2 -#define GL_MATRIX3_ARB 0x88C3 -#define GL_MATRIX4_ARB 0x88C4 -#define GL_MATRIX5_ARB 0x88C5 -#define GL_MATRIX6_ARB 0x88C6 -#define GL_MATRIX7_ARB 0x88C7 -#define GL_MATRIX8_ARB 0x88C8 -#define GL_MATRIX9_ARB 0x88C9 -#define GL_MATRIX10_ARB 0x88CA -#define GL_MATRIX11_ARB 0x88CB -#define GL_MATRIX12_ARB 0x88CC -#define GL_MATRIX13_ARB 0x88CD -#define GL_MATRIX14_ARB 0x88CE -#define GL_MATRIX15_ARB 0x88CF -#define GL_MATRIX16_ARB 0x88D0 -#define GL_MATRIX17_ARB 0x88D1 -#define GL_MATRIX18_ARB 0x88D2 -#define GL_MATRIX19_ARB 0x88D3 -#define GL_MATRIX20_ARB 0x88D4 -#define GL_MATRIX21_ARB 0x88D5 -#define GL_MATRIX22_ARB 0x88D6 -#define GL_MATRIX23_ARB 0x88D7 -#define GL_MATRIX24_ARB 0x88D8 -#define GL_MATRIX25_ARB 0x88D9 -#define GL_MATRIX26_ARB 0x88DA -#define GL_MATRIX27_ARB 0x88DB -#define GL_MATRIX28_ARB 0x88DC -#define GL_MATRIX29_ARB 0x88DD -#define GL_MATRIX30_ARB 0x88DE -#define GL_MATRIX31_ARB 0x88DF -#define GL_FRAGMENT_SHADER_ARB 0x8B30 -#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB 0x8B49 -#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB 0x8B8B -#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 -#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 -#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 -#define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 -#define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 -#define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 -#define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 -#define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 -#define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 -#define GL_FRAMEBUFFER_DEFAULT 0x8218 -#define GL_FRAMEBUFFER_UNDEFINED 0x8219 -#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A -#define GL_MAX_RENDERBUFFER_SIZE 0x84E8 -#define GL_DEPTH_STENCIL 0x84F9 -#define GL_UNSIGNED_INT_24_8 0x84FA -#define GL_DEPTH24_STENCIL8 0x88F0 -#define GL_TEXTURE_STENCIL_SIZE 0x88F1 -#define GL_UNSIGNED_NORMALIZED 0x8C17 -#define GL_FRAMEBUFFER_BINDING 0x8CA6 -#define GL_DRAW_FRAMEBUFFER_BINDING 0x8CA6 -#define GL_RENDERBUFFER_BINDING 0x8CA7 -#define GL_READ_FRAMEBUFFER 0x8CA8 -#define GL_DRAW_FRAMEBUFFER 0x8CA9 -#define GL_READ_FRAMEBUFFER_BINDING 0x8CAA -#define GL_RENDERBUFFER_SAMPLES 0x8CAB -#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 -#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 -#define GL_FRAMEBUFFER_COMPLETE 0x8CD5 -#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 -#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 -#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER 0x8CDB -#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER 0x8CDC -#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD -#define GL_MAX_COLOR_ATTACHMENTS 0x8CDF -#define GL_COLOR_ATTACHMENT0 0x8CE0 -#define GL_COLOR_ATTACHMENT1 0x8CE1 -#define GL_COLOR_ATTACHMENT2 0x8CE2 -#define GL_COLOR_ATTACHMENT3 0x8CE3 -#define GL_COLOR_ATTACHMENT4 0x8CE4 -#define GL_COLOR_ATTACHMENT5 0x8CE5 -#define GL_COLOR_ATTACHMENT6 0x8CE6 -#define GL_COLOR_ATTACHMENT7 0x8CE7 -#define GL_COLOR_ATTACHMENT8 0x8CE8 -#define GL_COLOR_ATTACHMENT9 0x8CE9 -#define GL_COLOR_ATTACHMENT10 0x8CEA -#define GL_COLOR_ATTACHMENT11 0x8CEB -#define GL_COLOR_ATTACHMENT12 0x8CEC -#define GL_COLOR_ATTACHMENT13 0x8CED -#define GL_COLOR_ATTACHMENT14 0x8CEE -#define GL_COLOR_ATTACHMENT15 0x8CEF -#define GL_DEPTH_ATTACHMENT 0x8D00 -#define GL_STENCIL_ATTACHMENT 0x8D20 -#define GL_FRAMEBUFFER 0x8D40 -#define GL_RENDERBUFFER 0x8D41 -#define GL_RENDERBUFFER_WIDTH 0x8D42 -#define GL_RENDERBUFFER_HEIGHT 0x8D43 -#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 -#define GL_STENCIL_INDEX1 0x8D46 -#define GL_STENCIL_INDEX4 0x8D47 -#define GL_STENCIL_INDEX8 0x8D48 -#define GL_STENCIL_INDEX16 0x8D49 -#define GL_RENDERBUFFER_RED_SIZE 0x8D50 -#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 -#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 -#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 -#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 -#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 -#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 -#define GL_MAX_SAMPLES 0x8D57 -#define GL_INDEX 0x8222 -#define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 0x8257 -#define GL_PROGRAM_BINARY_LENGTH 0x8741 -#define GL_NUM_PROGRAM_BINARY_FORMATS 0x87FE -#define GL_PROGRAM_BINARY_FORMATS 0x87FF -#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ARB 0x88FE -#define GL_MULTISAMPLE_ARB 0x809D -#define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB 0x809E -#define GL_SAMPLE_ALPHA_TO_ONE_ARB 0x809F -#define GL_SAMPLE_COVERAGE_ARB 0x80A0 -#define GL_SAMPLE_BUFFERS_ARB 0x80A8 -#define GL_SAMPLES_ARB 0x80A9 -#define GL_SAMPLE_COVERAGE_VALUE_ARB 0x80AA -#define GL_SAMPLE_COVERAGE_INVERT_ARB 0x80AB -#define GL_MULTISAMPLE_BIT_ARB 0x20000000 -#define GL_TEXTURE0_ARB 0x84C0 -#define GL_TEXTURE1_ARB 0x84C1 -#define GL_TEXTURE2_ARB 0x84C2 -#define GL_TEXTURE3_ARB 0x84C3 -#define GL_TEXTURE4_ARB 0x84C4 -#define GL_TEXTURE5_ARB 0x84C5 -#define GL_TEXTURE6_ARB 0x84C6 -#define GL_TEXTURE7_ARB 0x84C7 -#define GL_TEXTURE8_ARB 0x84C8 -#define GL_TEXTURE9_ARB 0x84C9 -#define GL_TEXTURE10_ARB 0x84CA -#define GL_TEXTURE11_ARB 0x84CB -#define GL_TEXTURE12_ARB 0x84CC -#define GL_TEXTURE13_ARB 0x84CD -#define GL_TEXTURE14_ARB 0x84CE -#define GL_TEXTURE15_ARB 0x84CF -#define GL_TEXTURE16_ARB 0x84D0 -#define GL_TEXTURE17_ARB 0x84D1 -#define GL_TEXTURE18_ARB 0x84D2 -#define GL_TEXTURE19_ARB 0x84D3 -#define GL_TEXTURE20_ARB 0x84D4 -#define GL_TEXTURE21_ARB 0x84D5 -#define GL_TEXTURE22_ARB 0x84D6 -#define GL_TEXTURE23_ARB 0x84D7 -#define GL_TEXTURE24_ARB 0x84D8 -#define GL_TEXTURE25_ARB 0x84D9 -#define GL_TEXTURE26_ARB 0x84DA -#define GL_TEXTURE27_ARB 0x84DB -#define GL_TEXTURE28_ARB 0x84DC -#define GL_TEXTURE29_ARB 0x84DD -#define GL_TEXTURE30_ARB 0x84DE -#define GL_TEXTURE31_ARB 0x84DF -#define GL_ACTIVE_TEXTURE_ARB 0x84E0 -#define GL_CLIENT_ACTIVE_TEXTURE_ARB 0x84E1 -#define GL_MAX_TEXTURE_UNITS_ARB 0x84E2 -#define GL_QUERY_COUNTER_BITS_ARB 0x8864 -#define GL_CURRENT_QUERY_ARB 0x8865 -#define GL_QUERY_RESULT_ARB 0x8866 -#define GL_QUERY_RESULT_AVAILABLE_ARB 0x8867 -#define GL_SAMPLES_PASSED_ARB 0x8914 -#define GL_PIXEL_PACK_BUFFER_ARB 0x88EB -#define GL_PIXEL_UNPACK_BUFFER_ARB 0x88EC -#define GL_PIXEL_PACK_BUFFER_BINDING_ARB 0x88ED -#define GL_PIXEL_UNPACK_BUFFER_BINDING_ARB 0x88EF -#define GL_POINT_SIZE_MIN_ARB 0x8126 -#define GL_POINT_SIZE_MAX_ARB 0x8127 -#define GL_POINT_FADE_THRESHOLD_SIZE_ARB 0x8128 -#define GL_POINT_DISTANCE_ATTENUATION_ARB 0x8129 -#define GL_POINT_SPRITE_ARB 0x8861 -#define GL_COORD_REPLACE_ARB 0x8862 -#define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F -#define GL_PROGRAM_OBJECT_ARB 0x8B40 -#define GL_SHADER_OBJECT_ARB 0x8B48 -#define GL_OBJECT_TYPE_ARB 0x8B4E -#define GL_OBJECT_SUBTYPE_ARB 0x8B4F -#define GL_FLOAT_VEC2_ARB 0x8B50 -#define GL_FLOAT_VEC3_ARB 0x8B51 -#define GL_FLOAT_VEC4_ARB 0x8B52 -#define GL_INT_VEC2_ARB 0x8B53 -#define GL_INT_VEC3_ARB 0x8B54 -#define GL_INT_VEC4_ARB 0x8B55 -#define GL_BOOL_ARB 0x8B56 -#define GL_BOOL_VEC2_ARB 0x8B57 -#define GL_BOOL_VEC3_ARB 0x8B58 -#define GL_BOOL_VEC4_ARB 0x8B59 -#define GL_FLOAT_MAT2_ARB 0x8B5A -#define GL_FLOAT_MAT3_ARB 0x8B5B -#define GL_FLOAT_MAT4_ARB 0x8B5C -#define GL_SAMPLER_1D_ARB 0x8B5D -#define GL_SAMPLER_2D_ARB 0x8B5E -#define GL_SAMPLER_3D_ARB 0x8B5F -#define GL_SAMPLER_CUBE_ARB 0x8B60 -#define GL_SAMPLER_1D_SHADOW_ARB 0x8B61 -#define GL_SAMPLER_2D_SHADOW_ARB 0x8B62 -#define GL_SAMPLER_2D_RECT_ARB 0x8B63 -#define GL_SAMPLER_2D_RECT_SHADOW_ARB 0x8B64 -#define GL_OBJECT_DELETE_STATUS_ARB 0x8B80 -#define GL_OBJECT_COMPILE_STATUS_ARB 0x8B81 -#define GL_OBJECT_LINK_STATUS_ARB 0x8B82 -#define GL_OBJECT_VALIDATE_STATUS_ARB 0x8B83 -#define GL_OBJECT_INFO_LOG_LENGTH_ARB 0x8B84 -#define GL_OBJECT_ATTACHED_OBJECTS_ARB 0x8B85 -#define GL_OBJECT_ACTIVE_UNIFORMS_ARB 0x8B86 -#define GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB 0x8B87 -#define GL_OBJECT_SHADER_SOURCE_LENGTH_ARB 0x8B88 -#define GL_SHADING_LANGUAGE_VERSION_ARB 0x8B8C -#define GL_TEXTURE_COMPARE_MODE_ARB 0x884C -#define GL_TEXTURE_COMPARE_FUNC_ARB 0x884D -#define GL_COMPARE_R_TO_TEXTURE_ARB 0x884E -#define GL_COMPRESSED_ALPHA_ARB 0x84E9 -#define GL_COMPRESSED_LUMINANCE_ARB 0x84EA -#define GL_COMPRESSED_LUMINANCE_ALPHA_ARB 0x84EB -#define GL_COMPRESSED_INTENSITY_ARB 0x84EC -#define GL_COMPRESSED_RGB_ARB 0x84ED -#define GL_COMPRESSED_RGBA_ARB 0x84EE -#define GL_TEXTURE_COMPRESSION_HINT_ARB 0x84EF -#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB 0x86A0 -#define GL_TEXTURE_COMPRESSED_ARB 0x86A1 -#define GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A2 -#define GL_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A3 -#define GL_NORMAL_MAP_ARB 0x8511 -#define GL_REFLECTION_MAP_ARB 0x8512 -#define GL_TEXTURE_CUBE_MAP_ARB 0x8513 -#define GL_TEXTURE_BINDING_CUBE_MAP_ARB 0x8514 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x8515 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x8516 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x8517 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x8518 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x8519 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x851A -#define GL_PROXY_TEXTURE_CUBE_MAP_ARB 0x851B -#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB 0x851C -#define GL_COMBINE_ARB 0x8570 -#define GL_COMBINE_RGB_ARB 0x8571 -#define GL_COMBINE_ALPHA_ARB 0x8572 -#define GL_SOURCE0_RGB_ARB 0x8580 -#define GL_SOURCE1_RGB_ARB 0x8581 -#define GL_SOURCE2_RGB_ARB 0x8582 -#define GL_SOURCE0_ALPHA_ARB 0x8588 -#define GL_SOURCE1_ALPHA_ARB 0x8589 -#define GL_SOURCE2_ALPHA_ARB 0x858A -#define GL_OPERAND0_RGB_ARB 0x8590 -#define GL_OPERAND1_RGB_ARB 0x8591 -#define GL_OPERAND2_RGB_ARB 0x8592 -#define GL_OPERAND0_ALPHA_ARB 0x8598 -#define GL_OPERAND1_ALPHA_ARB 0x8599 -#define GL_OPERAND2_ALPHA_ARB 0x859A -#define GL_RGB_SCALE_ARB 0x8573 -#define GL_ADD_SIGNED_ARB 0x8574 -#define GL_INTERPOLATE_ARB 0x8575 -#define GL_SUBTRACT_ARB 0x84E7 -#define GL_CONSTANT_ARB 0x8576 -#define GL_PRIMARY_COLOR_ARB 0x8577 -#define GL_PREVIOUS_ARB 0x8578 -#define GL_TEXTURE_RED_TYPE_ARB 0x8C10 -#define GL_TEXTURE_GREEN_TYPE_ARB 0x8C11 -#define GL_TEXTURE_BLUE_TYPE_ARB 0x8C12 -#define GL_TEXTURE_ALPHA_TYPE_ARB 0x8C13 -#define GL_TEXTURE_LUMINANCE_TYPE_ARB 0x8C14 -#define GL_TEXTURE_INTENSITY_TYPE_ARB 0x8C15 -#define GL_TEXTURE_DEPTH_TYPE_ARB 0x8C16 -#define GL_UNSIGNED_NORMALIZED_ARB 0x8C17 -#define GL_RGBA32F_ARB 0x8814 -#define GL_RGB32F_ARB 0x8815 -#define GL_ALPHA32F_ARB 0x8816 -#define GL_INTENSITY32F_ARB 0x8817 -#define GL_LUMINANCE32F_ARB 0x8818 -#define GL_LUMINANCE_ALPHA32F_ARB 0x8819 -#define GL_RGBA16F_ARB 0x881A -#define GL_RGB16F_ARB 0x881B -#define GL_ALPHA16F_ARB 0x881C -#define GL_INTENSITY16F_ARB 0x881D -#define GL_LUMINANCE16F_ARB 0x881E -#define GL_LUMINANCE_ALPHA16F_ARB 0x881F -#define GL_BUFFER_SIZE_ARB 0x8764 -#define GL_BUFFER_USAGE_ARB 0x8765 -#define GL_ARRAY_BUFFER_ARB 0x8892 -#define GL_ELEMENT_ARRAY_BUFFER_ARB 0x8893 -#define GL_ARRAY_BUFFER_BINDING_ARB 0x8894 -#define GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB 0x8895 -#define GL_VERTEX_ARRAY_BUFFER_BINDING_ARB 0x8896 -#define GL_NORMAL_ARRAY_BUFFER_BINDING_ARB 0x8897 -#define GL_COLOR_ARRAY_BUFFER_BINDING_ARB 0x8898 -#define GL_INDEX_ARRAY_BUFFER_BINDING_ARB 0x8899 -#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB 0x889A -#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB 0x889B -#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB 0x889C -#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB 0x889D -#define GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB 0x889E -#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB 0x889F -#define GL_READ_ONLY_ARB 0x88B8 -#define GL_WRITE_ONLY_ARB 0x88B9 -#define GL_READ_WRITE_ARB 0x88BA -#define GL_BUFFER_ACCESS_ARB 0x88BB -#define GL_BUFFER_MAPPED_ARB 0x88BC -#define GL_BUFFER_MAP_POINTER_ARB 0x88BD -#define GL_STREAM_DRAW_ARB 0x88E0 -#define GL_STREAM_READ_ARB 0x88E1 -#define GL_STREAM_COPY_ARB 0x88E2 -#define GL_STATIC_DRAW_ARB 0x88E4 -#define GL_STATIC_READ_ARB 0x88E5 -#define GL_STATIC_COPY_ARB 0x88E6 -#define GL_DYNAMIC_DRAW_ARB 0x88E8 -#define GL_DYNAMIC_READ_ARB 0x88E9 -#define GL_DYNAMIC_COPY_ARB 0x88EA -#define GL_COLOR_SUM_ARB 0x8458 -#define GL_VERTEX_PROGRAM_ARB 0x8620 -#define GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB 0x8622 -#define GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB 0x8623 -#define GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB 0x8624 -#define GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB 0x8625 -#define GL_CURRENT_VERTEX_ATTRIB_ARB 0x8626 -#define GL_VERTEX_PROGRAM_POINT_SIZE_ARB 0x8642 -#define GL_VERTEX_PROGRAM_TWO_SIDE_ARB 0x8643 -#define GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB 0x8645 -#define GL_MAX_VERTEX_ATTRIBS_ARB 0x8869 -#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB 0x886A -#define GL_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B0 -#define GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B1 -#define GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B2 -#define GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B3 -#define GL_VERTEX_SHADER_ARB 0x8B31 -#define GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB 0x8B4A -#define GL_MAX_VARYING_FLOATS_ARB 0x8B4B -#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB 0x8B4C -#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB 0x8B4D -#define GL_OBJECT_ACTIVE_ATTRIBUTES_ARB 0x8B89 -#define GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB 0x8B8A -#define GL_MAX_DRAW_BUFFERS_ATI 0x8824 -#define GL_DRAW_BUFFER0_ATI 0x8825 -#define GL_DRAW_BUFFER1_ATI 0x8826 -#define GL_DRAW_BUFFER2_ATI 0x8827 -#define GL_DRAW_BUFFER3_ATI 0x8828 -#define GL_DRAW_BUFFER4_ATI 0x8829 -#define GL_DRAW_BUFFER5_ATI 0x882A -#define GL_DRAW_BUFFER6_ATI 0x882B -#define GL_DRAW_BUFFER7_ATI 0x882C -#define GL_DRAW_BUFFER8_ATI 0x882D -#define GL_DRAW_BUFFER9_ATI 0x882E -#define GL_DRAW_BUFFER10_ATI 0x882F -#define GL_DRAW_BUFFER11_ATI 0x8830 -#define GL_DRAW_BUFFER12_ATI 0x8831 -#define GL_DRAW_BUFFER13_ATI 0x8832 -#define GL_DRAW_BUFFER14_ATI 0x8833 -#define GL_DRAW_BUFFER15_ATI 0x8834 -#define GL_FRAGMENT_SHADER_ATI 0x8920 -#define GL_REG_0_ATI 0x8921 -#define GL_REG_1_ATI 0x8922 -#define GL_REG_2_ATI 0x8923 -#define GL_REG_3_ATI 0x8924 -#define GL_REG_4_ATI 0x8925 -#define GL_REG_5_ATI 0x8926 -#define GL_REG_6_ATI 0x8927 -#define GL_REG_7_ATI 0x8928 -#define GL_REG_8_ATI 0x8929 -#define GL_REG_9_ATI 0x892A -#define GL_REG_10_ATI 0x892B -#define GL_REG_11_ATI 0x892C -#define GL_REG_12_ATI 0x892D -#define GL_REG_13_ATI 0x892E -#define GL_REG_14_ATI 0x892F -#define GL_REG_15_ATI 0x8930 -#define GL_REG_16_ATI 0x8931 -#define GL_REG_17_ATI 0x8932 -#define GL_REG_18_ATI 0x8933 -#define GL_REG_19_ATI 0x8934 -#define GL_REG_20_ATI 0x8935 -#define GL_REG_21_ATI 0x8936 -#define GL_REG_22_ATI 0x8937 -#define GL_REG_23_ATI 0x8938 -#define GL_REG_24_ATI 0x8939 -#define GL_REG_25_ATI 0x893A -#define GL_REG_26_ATI 0x893B -#define GL_REG_27_ATI 0x893C -#define GL_REG_28_ATI 0x893D -#define GL_REG_29_ATI 0x893E -#define GL_REG_30_ATI 0x893F -#define GL_REG_31_ATI 0x8940 -#define GL_CON_0_ATI 0x8941 -#define GL_CON_1_ATI 0x8942 -#define GL_CON_2_ATI 0x8943 -#define GL_CON_3_ATI 0x8944 -#define GL_CON_4_ATI 0x8945 -#define GL_CON_5_ATI 0x8946 -#define GL_CON_6_ATI 0x8947 -#define GL_CON_7_ATI 0x8948 -#define GL_CON_8_ATI 0x8949 -#define GL_CON_9_ATI 0x894A -#define GL_CON_10_ATI 0x894B -#define GL_CON_11_ATI 0x894C -#define GL_CON_12_ATI 0x894D -#define GL_CON_13_ATI 0x894E -#define GL_CON_14_ATI 0x894F -#define GL_CON_15_ATI 0x8950 -#define GL_CON_16_ATI 0x8951 -#define GL_CON_17_ATI 0x8952 -#define GL_CON_18_ATI 0x8953 -#define GL_CON_19_ATI 0x8954 -#define GL_CON_20_ATI 0x8955 -#define GL_CON_21_ATI 0x8956 -#define GL_CON_22_ATI 0x8957 -#define GL_CON_23_ATI 0x8958 -#define GL_CON_24_ATI 0x8959 -#define GL_CON_25_ATI 0x895A -#define GL_CON_26_ATI 0x895B -#define GL_CON_27_ATI 0x895C -#define GL_CON_28_ATI 0x895D -#define GL_CON_29_ATI 0x895E -#define GL_CON_30_ATI 0x895F -#define GL_CON_31_ATI 0x8960 -#define GL_MOV_ATI 0x8961 -#define GL_ADD_ATI 0x8963 -#define GL_MUL_ATI 0x8964 -#define GL_SUB_ATI 0x8965 -#define GL_DOT3_ATI 0x8966 -#define GL_DOT4_ATI 0x8967 -#define GL_MAD_ATI 0x8968 -#define GL_LERP_ATI 0x8969 -#define GL_CND_ATI 0x896A -#define GL_CND0_ATI 0x896B -#define GL_DOT2_ADD_ATI 0x896C -#define GL_SECONDARY_INTERPOLATOR_ATI 0x896D -#define GL_NUM_FRAGMENT_REGISTERS_ATI 0x896E -#define GL_NUM_FRAGMENT_CONSTANTS_ATI 0x896F -#define GL_NUM_PASSES_ATI 0x8970 -#define GL_NUM_INSTRUCTIONS_PER_PASS_ATI 0x8971 -#define GL_NUM_INSTRUCTIONS_TOTAL_ATI 0x8972 -#define GL_NUM_INPUT_INTERPOLATOR_COMPONENTS_ATI 0x8973 -#define GL_NUM_LOOPBACK_COMPONENTS_ATI 0x8974 -#define GL_COLOR_ALPHA_PAIRING_ATI 0x8975 -#define GL_SWIZZLE_STR_ATI 0x8976 -#define GL_SWIZZLE_STQ_ATI 0x8977 -#define GL_SWIZZLE_STR_DR_ATI 0x8978 -#define GL_SWIZZLE_STQ_DQ_ATI 0x8979 -#define GL_SWIZZLE_STRQ_ATI 0x897A -#define GL_SWIZZLE_STRQ_DQ_ATI 0x897B -#define GL_RED_BIT_ATI 0x00000001 -#define GL_GREEN_BIT_ATI 0x00000002 -#define GL_BLUE_BIT_ATI 0x00000004 -#define GL_2X_BIT_ATI 0x00000001 -#define GL_4X_BIT_ATI 0x00000002 -#define GL_8X_BIT_ATI 0x00000004 -#define GL_HALF_BIT_ATI 0x00000008 -#define GL_QUARTER_BIT_ATI 0x00000010 -#define GL_EIGHTH_BIT_ATI 0x00000020 -#define GL_SATURATE_BIT_ATI 0x00000040 -#define GL_COMP_BIT_ATI 0x00000002 -#define GL_NEGATE_BIT_ATI 0x00000004 -#define GL_BIAS_BIT_ATI 0x00000008 -#define GL_RGBA_FLOAT32_ATI 0x8814 -#define GL_RGB_FLOAT32_ATI 0x8815 -#define GL_ALPHA_FLOAT32_ATI 0x8816 -#define GL_INTENSITY_FLOAT32_ATI 0x8817 -#define GL_LUMINANCE_FLOAT32_ATI 0x8818 -#define GL_LUMINANCE_ALPHA_FLOAT32_ATI 0x8819 -#define GL_RGBA_FLOAT16_ATI 0x881A -#define GL_RGB_FLOAT16_ATI 0x881B -#define GL_ALPHA_FLOAT16_ATI 0x881C -#define GL_INTENSITY_FLOAT16_ATI 0x881D -#define GL_LUMINANCE_FLOAT16_ATI 0x881E -#define GL_LUMINANCE_ALPHA_FLOAT16_ATI 0x881F -#define GL_BLEND_EQUATION_RGB_EXT 0x8009 -#define GL_BLEND_EQUATION_ALPHA_EXT 0x883D -#define GL_READ_FRAMEBUFFER_EXT 0x8CA8 -#define GL_DRAW_FRAMEBUFFER_EXT 0x8CA9 -#define GL_DRAW_FRAMEBUFFER_BINDING_EXT 0x8CA6 -#define GL_READ_FRAMEBUFFER_BINDING_EXT 0x8CAA -#define GL_RENDERBUFFER_SAMPLES_EXT 0x8CAB -#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT 0x8D56 -#define GL_MAX_SAMPLES_EXT 0x8D57 -#define GL_INVALID_FRAMEBUFFER_OPERATION_EXT 0x0506 -#define GL_MAX_RENDERBUFFER_SIZE_EXT 0x84E8 -#define GL_FRAMEBUFFER_BINDING_EXT 0x8CA6 -#define GL_RENDERBUFFER_BINDING_EXT 0x8CA7 -#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT 0x8CD0 -#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT 0x8CD1 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT 0x8CD2 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT 0x8CD3 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT 0x8CD4 -#define GL_FRAMEBUFFER_COMPLETE_EXT 0x8CD5 -#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT 0x8CD6 -#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT 0x8CD7 -#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT 0x8CD9 -#define GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT 0x8CDA -#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT 0x8CDB -#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT 0x8CDC -#define GL_FRAMEBUFFER_UNSUPPORTED_EXT 0x8CDD -#define GL_MAX_COLOR_ATTACHMENTS_EXT 0x8CDF -#define GL_COLOR_ATTACHMENT0_EXT 0x8CE0 -#define GL_COLOR_ATTACHMENT1_EXT 0x8CE1 -#define GL_COLOR_ATTACHMENT2_EXT 0x8CE2 -#define GL_COLOR_ATTACHMENT3_EXT 0x8CE3 -#define GL_COLOR_ATTACHMENT4_EXT 0x8CE4 -#define GL_COLOR_ATTACHMENT5_EXT 0x8CE5 -#define GL_COLOR_ATTACHMENT6_EXT 0x8CE6 -#define GL_COLOR_ATTACHMENT7_EXT 0x8CE7 -#define GL_COLOR_ATTACHMENT8_EXT 0x8CE8 -#define GL_COLOR_ATTACHMENT9_EXT 0x8CE9 -#define GL_COLOR_ATTACHMENT10_EXT 0x8CEA -#define GL_COLOR_ATTACHMENT11_EXT 0x8CEB -#define GL_COLOR_ATTACHMENT12_EXT 0x8CEC -#define GL_COLOR_ATTACHMENT13_EXT 0x8CED -#define GL_COLOR_ATTACHMENT14_EXT 0x8CEE -#define GL_COLOR_ATTACHMENT15_EXT 0x8CEF -#define GL_DEPTH_ATTACHMENT_EXT 0x8D00 -#define GL_STENCIL_ATTACHMENT_EXT 0x8D20 -#define GL_FRAMEBUFFER_EXT 0x8D40 -#define GL_RENDERBUFFER_EXT 0x8D41 -#define GL_RENDERBUFFER_WIDTH_EXT 0x8D42 -#define GL_RENDERBUFFER_HEIGHT_EXT 0x8D43 -#define GL_RENDERBUFFER_INTERNAL_FORMAT_EXT 0x8D44 -#define GL_STENCIL_INDEX1_EXT 0x8D46 -#define GL_STENCIL_INDEX4_EXT 0x8D47 -#define GL_STENCIL_INDEX8_EXT 0x8D48 -#define GL_STENCIL_INDEX16_EXT 0x8D49 -#define GL_RENDERBUFFER_RED_SIZE_EXT 0x8D50 -#define GL_RENDERBUFFER_GREEN_SIZE_EXT 0x8D51 -#define GL_RENDERBUFFER_BLUE_SIZE_EXT 0x8D52 -#define GL_RENDERBUFFER_ALPHA_SIZE_EXT 0x8D53 -#define GL_RENDERBUFFER_DEPTH_SIZE_EXT 0x8D54 -#define GL_RENDERBUFFER_STENCIL_SIZE_EXT 0x8D55 -#define GL_FRAMEBUFFER_SRGB_EXT 0x8DB9 -#define GL_FRAMEBUFFER_SRGB_CAPABLE_EXT 0x8DBA -#define GL_GEOMETRY_SHADER_EXT 0x8DD9 -#define GL_GEOMETRY_VERTICES_OUT_EXT 0x8DDA -#define GL_GEOMETRY_INPUT_TYPE_EXT 0x8DDB -#define GL_GEOMETRY_OUTPUT_TYPE_EXT 0x8DDC -#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_EXT 0x8C29 -#define GL_MAX_GEOMETRY_VARYING_COMPONENTS_EXT 0x8DDD -#define GL_MAX_VERTEX_VARYING_COMPONENTS_EXT 0x8DDE -#define GL_MAX_VARYING_COMPONENTS_EXT 0x8B4B -#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT 0x8DDF -#define GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT 0x8DE0 -#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_EXT 0x8DE1 -#define GL_LINES_ADJACENCY_EXT 0x000A -#define GL_LINE_STRIP_ADJACENCY_EXT 0x000B -#define GL_TRIANGLES_ADJACENCY_EXT 0x000C -#define GL_TRIANGLE_STRIP_ADJACENCY_EXT 0x000D -#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_EXT 0x8DA8 -#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_EXT 0x8DA9 -#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_EXT 0x8DA7 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT 0x8CD4 -#define GL_PROGRAM_POINT_SIZE_EXT 0x8642 -#define GL_PIXEL_PACK_BUFFER_EXT 0x88EB -#define GL_PIXEL_UNPACK_BUFFER_EXT 0x88EC -#define GL_PIXEL_PACK_BUFFER_BINDING_EXT 0x88ED -#define GL_PIXEL_UNPACK_BUFFER_BINDING_EXT 0x88EF -#define GL_POINT_SIZE_MIN_EXT 0x8126 -#define GL_POINT_SIZE_MAX_EXT 0x8127 -#define GL_POINT_FADE_THRESHOLD_SIZE_EXT 0x8128 -#define GL_DISTANCE_ATTENUATION_EXT 0x8129 -#define GL_COLOR_SUM_EXT 0x8458 -#define GL_CURRENT_SECONDARY_COLOR_EXT 0x8459 -#define GL_SECONDARY_COLOR_ARRAY_SIZE_EXT 0x845A -#define GL_SECONDARY_COLOR_ARRAY_TYPE_EXT 0x845B -#define GL_SECONDARY_COLOR_ARRAY_STRIDE_EXT 0x845C -#define GL_SECONDARY_COLOR_ARRAY_POINTER_EXT 0x845D -#define GL_SECONDARY_COLOR_ARRAY_EXT 0x845E -#define GL_STENCIL_TEST_TWO_SIDE_EXT 0x8910 -#define GL_ACTIVE_STENCIL_FACE_EXT 0x8911 -#define GL_INCR_WRAP_EXT 0x8507 -#define GL_DECR_WRAP_EXT 0x8508 -#define GL_TEXTURE_1D_ARRAY_EXT 0x8C18 -#define GL_PROXY_TEXTURE_1D_ARRAY_EXT 0x8C19 -#define GL_TEXTURE_2D_ARRAY_EXT 0x8C1A -#define GL_PROXY_TEXTURE_2D_ARRAY_EXT 0x8C1B -#define GL_TEXTURE_BINDING_1D_ARRAY_EXT 0x8C1C -#define GL_TEXTURE_BINDING_2D_ARRAY_EXT 0x8C1D -#define GL_MAX_ARRAY_TEXTURE_LAYERS_EXT 0x88FF -#define GL_COMPARE_REF_DEPTH_TO_TEXTURE_EXT 0x884E -#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 -#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 -#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 -#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 -#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE -#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF -#define GL_MAX_TEXTURE_LOD_BIAS_EXT 0x84FD -#define GL_TEXTURE_FILTER_CONTROL_EXT 0x8500 -#define GL_TEXTURE_LOD_BIAS_EXT 0x8501 -#define GL_SRGB_EXT 0x8C40 -#define GL_SRGB8_EXT 0x8C41 -#define GL_SRGB_ALPHA_EXT 0x8C42 -#define GL_SRGB8_ALPHA8_EXT 0x8C43 -#define GL_SLUMINANCE_ALPHA_EXT 0x8C44 -#define GL_SLUMINANCE8_ALPHA8_EXT 0x8C45 -#define GL_SLUMINANCE_EXT 0x8C46 -#define GL_SLUMINANCE8_EXT 0x8C47 -#define GL_COMPRESSED_SRGB_EXT 0x8C48 -#define GL_COMPRESSED_SRGB_ALPHA_EXT 0x8C49 -#define GL_COMPRESSED_SLUMINANCE_EXT 0x8C4A -#define GL_COMPRESSED_SLUMINANCE_ALPHA_EXT 0x8C4B -#define GL_COMPRESSED_SRGB_S3TC_DXT1_EXT 0x8C4C -#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT 0x8C4D -#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT 0x8C4E -#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT 0x8C4F -#define GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV 0x88F4 -#define GL_MAX_PROGRAM_CALL_DEPTH_NV 0x88F5 -#define GL_MAX_PROGRAM_IF_DEPTH_NV 0x88F6 -#define GL_MAX_PROGRAM_LOOP_DEPTH_NV 0x88F7 -#define GL_MAX_PROGRAM_LOOP_COUNT_NV 0x88F8 -#define GL_GEOMETRY_PROGRAM_NV 0x8C26 -#define GL_MAX_PROGRAM_OUTPUT_VERTICES_NV 0x8C27 -#define GL_MAX_PROGRAM_TOTAL_OUTPUT_COMPONENTS_NV 0x8C28 -#define GL_MIN_PROGRAM_TEXEL_OFFSET_NV 0x8904 -#define GL_MAX_PROGRAM_TEXEL_OFFSET_NV 0x8905 -#define GL_PROGRAM_ATTRIB_COMPONENTS_NV 0x8906 -#define GL_PROGRAM_RESULT_COMPONENTS_NV 0x8907 -#define GL_MAX_PROGRAM_ATTRIB_COMPONENTS_NV 0x8908 -#define GL_MAX_PROGRAM_RESULT_COMPONENTS_NV 0x8909 -#define GL_MAX_PROGRAM_GENERIC_ATTRIBS_NV 0x8DA5 -#define GL_MAX_PROGRAM_GENERIC_RESULTS_NV 0x8DA6 -#define GL_REGISTER_COMBINERS_NV 0x8522 -#define GL_VARIABLE_A_NV 0x8523 -#define GL_VARIABLE_B_NV 0x8524 -#define GL_VARIABLE_C_NV 0x8525 -#define GL_VARIABLE_D_NV 0x8526 -#define GL_VARIABLE_E_NV 0x8527 -#define GL_VARIABLE_F_NV 0x8528 -#define GL_VARIABLE_G_NV 0x8529 -#define GL_CONSTANT_COLOR0_NV 0x852A -#define GL_CONSTANT_COLOR1_NV 0x852B -#define GL_PRIMARY_COLOR_NV 0x852C -#define GL_SECONDARY_COLOR_NV 0x852D -#define GL_SPARE0_NV 0x852E -#define GL_SPARE1_NV 0x852F -#define GL_DISCARD_NV 0x8530 -#define GL_E_TIMES_F_NV 0x8531 -#define GL_SPARE0_PLUS_SECONDARY_COLOR_NV 0x8532 -#define GL_UNSIGNED_IDENTITY_NV 0x8536 -#define GL_UNSIGNED_INVERT_NV 0x8537 -#define GL_EXPAND_NORMAL_NV 0x8538 -#define GL_EXPAND_NEGATE_NV 0x8539 -#define GL_HALF_BIAS_NORMAL_NV 0x853A -#define GL_HALF_BIAS_NEGATE_NV 0x853B -#define GL_SIGNED_IDENTITY_NV 0x853C -#define GL_SIGNED_NEGATE_NV 0x853D -#define GL_SCALE_BY_TWO_NV 0x853E -#define GL_SCALE_BY_FOUR_NV 0x853F -#define GL_SCALE_BY_ONE_HALF_NV 0x8540 -#define GL_BIAS_BY_NEGATIVE_ONE_HALF_NV 0x8541 -#define GL_COMBINER_INPUT_NV 0x8542 -#define GL_COMBINER_MAPPING_NV 0x8543 -#define GL_COMBINER_COMPONENT_USAGE_NV 0x8544 -#define GL_COMBINER_AB_DOT_PRODUCT_NV 0x8545 -#define GL_COMBINER_CD_DOT_PRODUCT_NV 0x8546 -#define GL_COMBINER_MUX_SUM_NV 0x8547 -#define GL_COMBINER_SCALE_NV 0x8548 -#define GL_COMBINER_BIAS_NV 0x8549 -#define GL_COMBINER_AB_OUTPUT_NV 0x854A -#define GL_COMBINER_CD_OUTPUT_NV 0x854B -#define GL_COMBINER_SUM_OUTPUT_NV 0x854C -#define GL_MAX_GENERAL_COMBINERS_NV 0x854D -#define GL_NUM_GENERAL_COMBINERS_NV 0x854E -#define GL_COLOR_SUM_CLAMP_NV 0x854F -#define GL_COMBINER0_NV 0x8550 -#define GL_COMBINER1_NV 0x8551 -#define GL_COMBINER2_NV 0x8552 -#define GL_COMBINER3_NV 0x8553 -#define GL_COMBINER4_NV 0x8554 -#define GL_COMBINER5_NV 0x8555 -#define GL_COMBINER6_NV 0x8556 -#define GL_COMBINER7_NV 0x8557 -#define GL_PER_STAGE_CONSTANTS_NV 0x8535 -#define GL_OFFSET_TEXTURE_RECTANGLE_NV 0x864C -#define GL_OFFSET_TEXTURE_RECTANGLE_SCALE_NV 0x864D -#define GL_DOT_PRODUCT_TEXTURE_RECTANGLE_NV 0x864E -#define GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV 0x86D9 -#define GL_UNSIGNED_INT_S8_S8_8_8_NV 0x86DA -#define GL_UNSIGNED_INT_8_8_S8_S8_REV_NV 0x86DB -#define GL_DSDT_MAG_INTENSITY_NV 0x86DC -#define GL_SHADER_CONSISTENT_NV 0x86DD -#define GL_TEXTURE_SHADER_NV 0x86DE -#define GL_SHADER_OPERATION_NV 0x86DF -#define GL_CULL_MODES_NV 0x86E0 -#define GL_OFFSET_TEXTURE_MATRIX_NV 0x86E1 -#define GL_OFFSET_TEXTURE_SCALE_NV 0x86E2 -#define GL_OFFSET_TEXTURE_BIAS_NV 0x86E3 -#define GL_OFFSET_TEXTURE_2D_MATRIX_NV 0x86E1 -#define GL_OFFSET_TEXTURE_2D_SCALE_NV 0x86E2 -#define GL_OFFSET_TEXTURE_2D_BIAS_NV 0x86E3 -#define GL_PREVIOUS_TEXTURE_INPUT_NV 0x86E4 -#define GL_CONST_EYE_NV 0x86E5 -#define GL_PASS_THROUGH_NV 0x86E6 -#define GL_CULL_FRAGMENT_NV 0x86E7 -#define GL_OFFSET_TEXTURE_2D_NV 0x86E8 -#define GL_DEPENDENT_AR_TEXTURE_2D_NV 0x86E9 -#define GL_DEPENDENT_GB_TEXTURE_2D_NV 0x86EA -#define GL_DOT_PRODUCT_NV 0x86EC -#define GL_DOT_PRODUCT_DEPTH_REPLACE_NV 0x86ED -#define GL_DOT_PRODUCT_TEXTURE_2D_NV 0x86EE -#define GL_DOT_PRODUCT_TEXTURE_CUBE_MAP_NV 0x86F0 -#define GL_DOT_PRODUCT_DIFFUSE_CUBE_MAP_NV 0x86F1 -#define GL_DOT_PRODUCT_REFLECT_CUBE_MAP_NV 0x86F2 -#define GL_DOT_PRODUCT_CONST_EYE_REFLECT_CUBE_MAP_NV 0x86F3 -#define GL_HILO_NV 0x86F4 -#define GL_DSDT_NV 0x86F5 -#define GL_DSDT_MAG_NV 0x86F6 -#define GL_DSDT_MAG_VIB_NV 0x86F7 -#define GL_HILO16_NV 0x86F8 -#define GL_SIGNED_HILO_NV 0x86F9 -#define GL_SIGNED_HILO16_NV 0x86FA -#define GL_SIGNED_RGBA_NV 0x86FB -#define GL_SIGNED_RGBA8_NV 0x86FC -#define GL_SIGNED_RGB_NV 0x86FE -#define GL_SIGNED_RGB8_NV 0x86FF -#define GL_SIGNED_LUMINANCE_NV 0x8701 -#define GL_SIGNED_LUMINANCE8_NV 0x8702 -#define GL_SIGNED_LUMINANCE_ALPHA_NV 0x8703 -#define GL_SIGNED_LUMINANCE8_ALPHA8_NV 0x8704 -#define GL_SIGNED_ALPHA_NV 0x8705 -#define GL_SIGNED_ALPHA8_NV 0x8706 -#define GL_SIGNED_INTENSITY_NV 0x8707 -#define GL_SIGNED_INTENSITY8_NV 0x8708 -#define GL_DSDT8_NV 0x8709 -#define GL_DSDT8_MAG8_NV 0x870A -#define GL_DSDT8_MAG8_INTENSITY8_NV 0x870B -#define GL_SIGNED_RGB_UNSIGNED_ALPHA_NV 0x870C -#define GL_SIGNED_RGB8_UNSIGNED_ALPHA8_NV 0x870D -#define GL_HI_SCALE_NV 0x870E -#define GL_LO_SCALE_NV 0x870F -#define GL_DS_SCALE_NV 0x8710 -#define GL_DT_SCALE_NV 0x8711 -#define GL_MAGNITUDE_SCALE_NV 0x8712 -#define GL_VIBRANCE_SCALE_NV 0x8713 -#define GL_HI_BIAS_NV 0x8714 -#define GL_LO_BIAS_NV 0x8715 -#define GL_DS_BIAS_NV 0x8716 -#define GL_DT_BIAS_NV 0x8717 -#define GL_MAGNITUDE_BIAS_NV 0x8718 -#define GL_VIBRANCE_BIAS_NV 0x8719 -#define GL_TEXTURE_BORDER_VALUES_NV 0x871A -#define GL_TEXTURE_HI_SIZE_NV 0x871B -#define GL_TEXTURE_LO_SIZE_NV 0x871C -#define GL_TEXTURE_DS_SIZE_NV 0x871D -#define GL_TEXTURE_DT_SIZE_NV 0x871E -#define GL_TEXTURE_MAG_SIZE_NV 0x871F -#define GL_BACK_PRIMARY_COLOR_NV 0x8C77 -#define GL_BACK_SECONDARY_COLOR_NV 0x8C78 -#define GL_TEXTURE_COORD_NV 0x8C79 -#define GL_CLIP_DISTANCE_NV 0x8C7A -#define GL_VERTEX_ID_NV 0x8C7B -#define GL_PRIMITIVE_ID_NV 0x8C7C -#define GL_GENERIC_ATTRIB_NV 0x8C7D -#define GL_TRANSFORM_FEEDBACK_ATTRIBS_NV 0x8C7E -#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE_NV 0x8C7F -#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_NV 0x8C80 -#define GL_ACTIVE_VARYINGS_NV 0x8C81 -#define GL_ACTIVE_VARYING_MAX_LENGTH_NV 0x8C82 -#define GL_TRANSFORM_FEEDBACK_VARYINGS_NV 0x8C83 -#define GL_TRANSFORM_FEEDBACK_BUFFER_START_NV 0x8C84 -#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE_NV 0x8C85 -#define GL_TRANSFORM_FEEDBACK_RECORD_NV 0x8C86 -#define GL_PRIMITIVES_GENERATED_NV 0x8C87 -#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_NV 0x8C88 -#define GL_RASTERIZER_DISCARD_NV 0x8C89 -#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_NV 0x8C8A -#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS_NV 0x8C8B -#define GL_INTERLEAVED_ATTRIBS_NV 0x8C8C -#define GL_SEPARATE_ATTRIBS_NV 0x8C8D -#define GL_TRANSFORM_FEEDBACK_BUFFER_NV 0x8C8E -#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING_NV 0x8C8F -#define GL_LAYER_NV 0x8DAA -#define GL_NEXT_BUFFER_NV -2 -#define GL_SKIP_COMPONENTS4_NV -3 -#define GL_SKIP_COMPONENTS3_NV -4 -#define GL_SKIP_COMPONENTS2_NV -5 -#define GL_SKIP_COMPONENTS1_NV -6 -#define GL_VERTEX_PROGRAM_NV 0x8620 -#define GL_VERTEX_STATE_PROGRAM_NV 0x8621 -#define GL_ATTRIB_ARRAY_SIZE_NV 0x8623 -#define GL_ATTRIB_ARRAY_STRIDE_NV 0x8624 -#define GL_ATTRIB_ARRAY_TYPE_NV 0x8625 -#define GL_CURRENT_ATTRIB_NV 0x8626 -#define GL_PROGRAM_LENGTH_NV 0x8627 -#define GL_PROGRAM_STRING_NV 0x8628 -#define GL_MODELVIEW_PROJECTION_NV 0x8629 -#define GL_IDENTITY_NV 0x862A -#define GL_INVERSE_NV 0x862B -#define GL_TRANSPOSE_NV 0x862C -#define GL_INVERSE_TRANSPOSE_NV 0x862D -#define GL_MAX_TRACK_MATRIX_STACK_DEPTH_NV 0x862E -#define GL_MAX_TRACK_MATRICES_NV 0x862F -#define GL_MATRIX0_NV 0x8630 -#define GL_MATRIX1_NV 0x8631 -#define GL_MATRIX2_NV 0x8632 -#define GL_MATRIX3_NV 0x8633 -#define GL_MATRIX4_NV 0x8634 -#define GL_MATRIX5_NV 0x8635 -#define GL_MATRIX6_NV 0x8636 -#define GL_MATRIX7_NV 0x8637 -#define GL_CURRENT_MATRIX_STACK_DEPTH_NV 0x8640 -#define GL_CURRENT_MATRIX_NV 0x8641 -#define GL_VERTEX_PROGRAM_POINT_SIZE_NV 0x8642 -#define GL_VERTEX_PROGRAM_TWO_SIDE_NV 0x8643 -#define GL_PROGRAM_PARAMETER_NV 0x8644 -#define GL_ATTRIB_ARRAY_POINTER_NV 0x8645 -#define GL_PROGRAM_TARGET_NV 0x8646 -#define GL_PROGRAM_RESIDENT_NV 0x8647 -#define GL_TRACK_MATRIX_NV 0x8648 -#define GL_TRACK_MATRIX_TRANSFORM_NV 0x8649 -#define GL_VERTEX_PROGRAM_BINDING_NV 0x864A -#define GL_PROGRAM_ERROR_POSITION_NV 0x864B -#define GL_VERTEX_ATTRIB_ARRAY0_NV 0x8650 -#define GL_VERTEX_ATTRIB_ARRAY1_NV 0x8651 -#define GL_VERTEX_ATTRIB_ARRAY2_NV 0x8652 -#define GL_VERTEX_ATTRIB_ARRAY3_NV 0x8653 -#define GL_VERTEX_ATTRIB_ARRAY4_NV 0x8654 -#define GL_VERTEX_ATTRIB_ARRAY5_NV 0x8655 -#define GL_VERTEX_ATTRIB_ARRAY6_NV 0x8656 -#define GL_VERTEX_ATTRIB_ARRAY7_NV 0x8657 -#define GL_VERTEX_ATTRIB_ARRAY8_NV 0x8658 -#define GL_VERTEX_ATTRIB_ARRAY9_NV 0x8659 -#define GL_VERTEX_ATTRIB_ARRAY10_NV 0x865A -#define GL_VERTEX_ATTRIB_ARRAY11_NV 0x865B -#define GL_VERTEX_ATTRIB_ARRAY12_NV 0x865C -#define GL_VERTEX_ATTRIB_ARRAY13_NV 0x865D -#define GL_VERTEX_ATTRIB_ARRAY14_NV 0x865E -#define GL_VERTEX_ATTRIB_ARRAY15_NV 0x865F -#define GL_MAP1_VERTEX_ATTRIB0_4_NV 0x8660 -#define GL_MAP1_VERTEX_ATTRIB1_4_NV 0x8661 -#define GL_MAP1_VERTEX_ATTRIB2_4_NV 0x8662 -#define GL_MAP1_VERTEX_ATTRIB3_4_NV 0x8663 -#define GL_MAP1_VERTEX_ATTRIB4_4_NV 0x8664 -#define GL_MAP1_VERTEX_ATTRIB5_4_NV 0x8665 -#define GL_MAP1_VERTEX_ATTRIB6_4_NV 0x8666 -#define GL_MAP1_VERTEX_ATTRIB7_4_NV 0x8667 -#define GL_MAP1_VERTEX_ATTRIB8_4_NV 0x8668 -#define GL_MAP1_VERTEX_ATTRIB9_4_NV 0x8669 -#define GL_MAP1_VERTEX_ATTRIB10_4_NV 0x866A -#define GL_MAP1_VERTEX_ATTRIB11_4_NV 0x866B -#define GL_MAP1_VERTEX_ATTRIB12_4_NV 0x866C -#define GL_MAP1_VERTEX_ATTRIB13_4_NV 0x866D -#define GL_MAP1_VERTEX_ATTRIB14_4_NV 0x866E -#define GL_MAP1_VERTEX_ATTRIB15_4_NV 0x866F -#define GL_MAP2_VERTEX_ATTRIB0_4_NV 0x8670 -#define GL_MAP2_VERTEX_ATTRIB1_4_NV 0x8671 -#define GL_MAP2_VERTEX_ATTRIB2_4_NV 0x8672 -#define GL_MAP2_VERTEX_ATTRIB3_4_NV 0x8673 -#define GL_MAP2_VERTEX_ATTRIB4_4_NV 0x8674 -#define GL_MAP2_VERTEX_ATTRIB5_4_NV 0x8675 -#define GL_MAP2_VERTEX_ATTRIB6_4_NV 0x8676 -#define GL_MAP2_VERTEX_ATTRIB7_4_NV 0x8677 -#define GL_MAP2_VERTEX_ATTRIB8_4_NV 0x8678 -#define GL_MAP2_VERTEX_ATTRIB9_4_NV 0x8679 -#define GL_MAP2_VERTEX_ATTRIB10_4_NV 0x867A -#define GL_MAP2_VERTEX_ATTRIB11_4_NV 0x867B -#define GL_MAP2_VERTEX_ATTRIB12_4_NV 0x867C -#define GL_MAP2_VERTEX_ATTRIB13_4_NV 0x867D -#define GL_MAP2_VERTEX_ATTRIB14_4_NV 0x867E -#define GL_MAP2_VERTEX_ATTRIB15_4_NV 0x867F -#ifndef GL_ARB_depth_buffer_float -#define GL_ARB_depth_buffer_float 1 -GLAPI int GLAD_GL_ARB_depth_buffer_float; -#endif -#ifndef GL_ARB_draw_buffers -#define GL_ARB_draw_buffers 1 -GLAPI int GLAD_GL_ARB_draw_buffers; -typedef void (APIENTRYP PFNGLDRAWBUFFERSARBPROC)(GLsizei n, const GLenum *bufs); -GLAPI PFNGLDRAWBUFFERSARBPROC glad_glDrawBuffersARB; -#define glDrawBuffersARB glad_glDrawBuffersARB -#endif -#ifndef GL_ARB_draw_instanced -#define GL_ARB_draw_instanced 1 -GLAPI int GLAD_GL_ARB_draw_instanced; -typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDARBPROC)(GLenum mode, GLint first, GLsizei count, GLsizei primcount); -GLAPI PFNGLDRAWARRAYSINSTANCEDARBPROC glad_glDrawArraysInstancedARB; -#define glDrawArraysInstancedARB glad_glDrawArraysInstancedARB -typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDARBPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); -GLAPI PFNGLDRAWELEMENTSINSTANCEDARBPROC glad_glDrawElementsInstancedARB; -#define glDrawElementsInstancedARB glad_glDrawElementsInstancedARB -#endif -#ifndef GL_ARB_fragment_program -#define GL_ARB_fragment_program 1 -GLAPI int GLAD_GL_ARB_fragment_program; -typedef void (APIENTRYP PFNGLPROGRAMSTRINGARBPROC)(GLenum target, GLenum format, GLsizei len, const void *string); -GLAPI PFNGLPROGRAMSTRINGARBPROC glad_glProgramStringARB; -#define glProgramStringARB glad_glProgramStringARB -typedef void (APIENTRYP PFNGLBINDPROGRAMARBPROC)(GLenum target, GLuint program); -GLAPI PFNGLBINDPROGRAMARBPROC glad_glBindProgramARB; -#define glBindProgramARB glad_glBindProgramARB -typedef void (APIENTRYP PFNGLDELETEPROGRAMSARBPROC)(GLsizei n, const GLuint *programs); -GLAPI PFNGLDELETEPROGRAMSARBPROC glad_glDeleteProgramsARB; -#define glDeleteProgramsARB glad_glDeleteProgramsARB -typedef void (APIENTRYP PFNGLGENPROGRAMSARBPROC)(GLsizei n, GLuint *programs); -GLAPI PFNGLGENPROGRAMSARBPROC glad_glGenProgramsARB; -#define glGenProgramsARB glad_glGenProgramsARB -typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DARBPROC)(GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); -GLAPI PFNGLPROGRAMENVPARAMETER4DARBPROC glad_glProgramEnvParameter4dARB; -#define glProgramEnvParameter4dARB glad_glProgramEnvParameter4dARB -typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DVARBPROC)(GLenum target, GLuint index, const GLdouble *params); -GLAPI PFNGLPROGRAMENVPARAMETER4DVARBPROC glad_glProgramEnvParameter4dvARB; -#define glProgramEnvParameter4dvARB glad_glProgramEnvParameter4dvARB -typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FARBPROC)(GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); -GLAPI PFNGLPROGRAMENVPARAMETER4FARBPROC glad_glProgramEnvParameter4fARB; -#define glProgramEnvParameter4fARB glad_glProgramEnvParameter4fARB -typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FVARBPROC)(GLenum target, GLuint index, const GLfloat *params); -GLAPI PFNGLPROGRAMENVPARAMETER4FVARBPROC glad_glProgramEnvParameter4fvARB; -#define glProgramEnvParameter4fvARB glad_glProgramEnvParameter4fvARB -typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DARBPROC)(GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); -GLAPI PFNGLPROGRAMLOCALPARAMETER4DARBPROC glad_glProgramLocalParameter4dARB; -#define glProgramLocalParameter4dARB glad_glProgramLocalParameter4dARB -typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DVARBPROC)(GLenum target, GLuint index, const GLdouble *params); -GLAPI PFNGLPROGRAMLOCALPARAMETER4DVARBPROC glad_glProgramLocalParameter4dvARB; -#define glProgramLocalParameter4dvARB glad_glProgramLocalParameter4dvARB -typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FARBPROC)(GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); -GLAPI PFNGLPROGRAMLOCALPARAMETER4FARBPROC glad_glProgramLocalParameter4fARB; -#define glProgramLocalParameter4fARB glad_glProgramLocalParameter4fARB -typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FVARBPROC)(GLenum target, GLuint index, const GLfloat *params); -GLAPI PFNGLPROGRAMLOCALPARAMETER4FVARBPROC glad_glProgramLocalParameter4fvARB; -#define glProgramLocalParameter4fvARB glad_glProgramLocalParameter4fvARB -typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERDVARBPROC)(GLenum target, GLuint index, GLdouble *params); -GLAPI PFNGLGETPROGRAMENVPARAMETERDVARBPROC glad_glGetProgramEnvParameterdvARB; -#define glGetProgramEnvParameterdvARB glad_glGetProgramEnvParameterdvARB -typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERFVARBPROC)(GLenum target, GLuint index, GLfloat *params); -GLAPI PFNGLGETPROGRAMENVPARAMETERFVARBPROC glad_glGetProgramEnvParameterfvARB; -#define glGetProgramEnvParameterfvARB glad_glGetProgramEnvParameterfvARB -typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC)(GLenum target, GLuint index, GLdouble *params); -GLAPI PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC glad_glGetProgramLocalParameterdvARB; -#define glGetProgramLocalParameterdvARB glad_glGetProgramLocalParameterdvARB -typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC)(GLenum target, GLuint index, GLfloat *params); -GLAPI PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC glad_glGetProgramLocalParameterfvARB; -#define glGetProgramLocalParameterfvARB glad_glGetProgramLocalParameterfvARB -typedef void (APIENTRYP PFNGLGETPROGRAMIVARBPROC)(GLenum target, GLenum pname, GLint *params); -GLAPI PFNGLGETPROGRAMIVARBPROC glad_glGetProgramivARB; -#define glGetProgramivARB glad_glGetProgramivARB -typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGARBPROC)(GLenum target, GLenum pname, void *string); -GLAPI PFNGLGETPROGRAMSTRINGARBPROC glad_glGetProgramStringARB; -#define glGetProgramStringARB glad_glGetProgramStringARB -typedef GLboolean (APIENTRYP PFNGLISPROGRAMARBPROC)(GLuint program); -GLAPI PFNGLISPROGRAMARBPROC glad_glIsProgramARB; -#define glIsProgramARB glad_glIsProgramARB -#endif -#ifndef GL_ARB_fragment_program_shadow -#define GL_ARB_fragment_program_shadow 1 -GLAPI int GLAD_GL_ARB_fragment_program_shadow; -#endif -#ifndef GL_ARB_fragment_shader -#define GL_ARB_fragment_shader 1 -GLAPI int GLAD_GL_ARB_fragment_shader; -#endif -#ifndef GL_ARB_framebuffer_object -#define GL_ARB_framebuffer_object 1 -GLAPI int GLAD_GL_ARB_framebuffer_object; -typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFERPROC)(GLuint renderbuffer); -GLAPI PFNGLISRENDERBUFFERPROC glad_glIsRenderbuffer; -#define glIsRenderbuffer glad_glIsRenderbuffer -typedef void (APIENTRYP PFNGLBINDRENDERBUFFERPROC)(GLenum target, GLuint renderbuffer); -GLAPI PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer; -#define glBindRenderbuffer glad_glBindRenderbuffer -typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSPROC)(GLsizei n, const GLuint *renderbuffers); -GLAPI PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers; -#define glDeleteRenderbuffers glad_glDeleteRenderbuffers -typedef void (APIENTRYP PFNGLGENRENDERBUFFERSPROC)(GLsizei n, GLuint *renderbuffers); -GLAPI PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers; -#define glGenRenderbuffers glad_glGenRenderbuffers -typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEPROC)(GLenum target, GLenum internalformat, GLsizei width, GLsizei height); -GLAPI PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage; -#define glRenderbufferStorage glad_glRenderbufferStorage -typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); -GLAPI PFNGLGETRENDERBUFFERPARAMETERIVPROC glad_glGetRenderbufferParameteriv; -#define glGetRenderbufferParameteriv glad_glGetRenderbufferParameteriv -typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFERPROC)(GLuint framebuffer); -GLAPI PFNGLISFRAMEBUFFERPROC glad_glIsFramebuffer; -#define glIsFramebuffer glad_glIsFramebuffer -typedef void (APIENTRYP PFNGLBINDFRAMEBUFFERPROC)(GLenum target, GLuint framebuffer); -GLAPI PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer; -#define glBindFramebuffer glad_glBindFramebuffer -typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSPROC)(GLsizei n, const GLuint *framebuffers); -GLAPI PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers; -#define glDeleteFramebuffers glad_glDeleteFramebuffers -typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSPROC)(GLsizei n, GLuint *framebuffers); -GLAPI PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers; -#define glGenFramebuffers glad_glGenFramebuffers -typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSPROC)(GLenum target); -GLAPI PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus; -#define glCheckFramebufferStatus glad_glCheckFramebufferStatus -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); -GLAPI PFNGLFRAMEBUFFERTEXTURE1DPROC glad_glFramebufferTexture1D; -#define glFramebufferTexture1D glad_glFramebufferTexture1D -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); -GLAPI PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D; -#define glFramebufferTexture2D glad_glFramebufferTexture2D -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); -GLAPI PFNGLFRAMEBUFFERTEXTURE3DPROC glad_glFramebufferTexture3D; -#define glFramebufferTexture3D glad_glFramebufferTexture3D -typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFERPROC)(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); -GLAPI PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer; -#define glFramebufferRenderbuffer glad_glFramebufferRenderbuffer -typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)(GLenum target, GLenum attachment, GLenum pname, GLint *params); -GLAPI PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetFramebufferAttachmentParameteriv; -#define glGetFramebufferAttachmentParameteriv glad_glGetFramebufferAttachmentParameteriv -typedef void (APIENTRYP PFNGLGENERATEMIPMAPPROC)(GLenum target); -GLAPI PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap; -#define glGenerateMipmap glad_glGenerateMipmap -typedef void (APIENTRYP PFNGLBLITFRAMEBUFFERPROC)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); -GLAPI PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer; -#define glBlitFramebuffer glad_glBlitFramebuffer -typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -GLAPI PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glRenderbufferStorageMultisample; -#define glRenderbufferStorageMultisample glad_glRenderbufferStorageMultisample -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERPROC)(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); -GLAPI PFNGLFRAMEBUFFERTEXTURELAYERPROC glad_glFramebufferTextureLayer; -#define glFramebufferTextureLayer glad_glFramebufferTextureLayer -#endif -#ifndef GL_ARB_get_program_binary -#define GL_ARB_get_program_binary 1 -GLAPI int GLAD_GL_ARB_get_program_binary; -typedef void (APIENTRYP PFNGLGETPROGRAMBINARYPROC)(GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); -GLAPI PFNGLGETPROGRAMBINARYPROC glad_glGetProgramBinary; -#define glGetProgramBinary glad_glGetProgramBinary -typedef void (APIENTRYP PFNGLPROGRAMBINARYPROC)(GLuint program, GLenum binaryFormat, const void *binary, GLsizei length); -GLAPI PFNGLPROGRAMBINARYPROC glad_glProgramBinary; -#define glProgramBinary glad_glProgramBinary -typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIPROC)(GLuint program, GLenum pname, GLint value); -GLAPI PFNGLPROGRAMPARAMETERIPROC glad_glProgramParameteri; -#define glProgramParameteri glad_glProgramParameteri -#endif -#ifndef GL_ARB_instanced_arrays -#define GL_ARB_instanced_arrays 1 -GLAPI int GLAD_GL_ARB_instanced_arrays; -typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORARBPROC)(GLuint index, GLuint divisor); -GLAPI PFNGLVERTEXATTRIBDIVISORARBPROC glad_glVertexAttribDivisorARB; -#define glVertexAttribDivisorARB glad_glVertexAttribDivisorARB -#endif -#ifndef GL_ARB_multisample -#define GL_ARB_multisample 1 -GLAPI int GLAD_GL_ARB_multisample; -typedef void (APIENTRYP PFNGLSAMPLECOVERAGEARBPROC)(GLfloat value, GLboolean invert); -GLAPI PFNGLSAMPLECOVERAGEARBPROC glad_glSampleCoverageARB; -#define glSampleCoverageARB glad_glSampleCoverageARB -#endif -#ifndef GL_ARB_multitexture -#define GL_ARB_multitexture 1 -GLAPI int GLAD_GL_ARB_multitexture; -typedef void (APIENTRYP PFNGLACTIVETEXTUREARBPROC)(GLenum texture); -GLAPI PFNGLACTIVETEXTUREARBPROC glad_glActiveTextureARB; -#define glActiveTextureARB glad_glActiveTextureARB -typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREARBPROC)(GLenum texture); -GLAPI PFNGLCLIENTACTIVETEXTUREARBPROC glad_glClientActiveTextureARB; -#define glClientActiveTextureARB glad_glClientActiveTextureARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD1DARBPROC)(GLenum target, GLdouble s); -GLAPI PFNGLMULTITEXCOORD1DARBPROC glad_glMultiTexCoord1dARB; -#define glMultiTexCoord1dARB glad_glMultiTexCoord1dARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVARBPROC)(GLenum target, const GLdouble *v); -GLAPI PFNGLMULTITEXCOORD1DVARBPROC glad_glMultiTexCoord1dvARB; -#define glMultiTexCoord1dvARB glad_glMultiTexCoord1dvARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD1FARBPROC)(GLenum target, GLfloat s); -GLAPI PFNGLMULTITEXCOORD1FARBPROC glad_glMultiTexCoord1fARB; -#define glMultiTexCoord1fARB glad_glMultiTexCoord1fARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVARBPROC)(GLenum target, const GLfloat *v); -GLAPI PFNGLMULTITEXCOORD1FVARBPROC glad_glMultiTexCoord1fvARB; -#define glMultiTexCoord1fvARB glad_glMultiTexCoord1fvARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD1IARBPROC)(GLenum target, GLint s); -GLAPI PFNGLMULTITEXCOORD1IARBPROC glad_glMultiTexCoord1iARB; -#define glMultiTexCoord1iARB glad_glMultiTexCoord1iARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVARBPROC)(GLenum target, const GLint *v); -GLAPI PFNGLMULTITEXCOORD1IVARBPROC glad_glMultiTexCoord1ivARB; -#define glMultiTexCoord1ivARB glad_glMultiTexCoord1ivARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD1SARBPROC)(GLenum target, GLshort s); -GLAPI PFNGLMULTITEXCOORD1SARBPROC glad_glMultiTexCoord1sARB; -#define glMultiTexCoord1sARB glad_glMultiTexCoord1sARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVARBPROC)(GLenum target, const GLshort *v); -GLAPI PFNGLMULTITEXCOORD1SVARBPROC glad_glMultiTexCoord1svARB; -#define glMultiTexCoord1svARB glad_glMultiTexCoord1svARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD2DARBPROC)(GLenum target, GLdouble s, GLdouble t); -GLAPI PFNGLMULTITEXCOORD2DARBPROC glad_glMultiTexCoord2dARB; -#define glMultiTexCoord2dARB glad_glMultiTexCoord2dARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVARBPROC)(GLenum target, const GLdouble *v); -GLAPI PFNGLMULTITEXCOORD2DVARBPROC glad_glMultiTexCoord2dvARB; -#define glMultiTexCoord2dvARB glad_glMultiTexCoord2dvARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD2FARBPROC)(GLenum target, GLfloat s, GLfloat t); -GLAPI PFNGLMULTITEXCOORD2FARBPROC glad_glMultiTexCoord2fARB; -#define glMultiTexCoord2fARB glad_glMultiTexCoord2fARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVARBPROC)(GLenum target, const GLfloat *v); -GLAPI PFNGLMULTITEXCOORD2FVARBPROC glad_glMultiTexCoord2fvARB; -#define glMultiTexCoord2fvARB glad_glMultiTexCoord2fvARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD2IARBPROC)(GLenum target, GLint s, GLint t); -GLAPI PFNGLMULTITEXCOORD2IARBPROC glad_glMultiTexCoord2iARB; -#define glMultiTexCoord2iARB glad_glMultiTexCoord2iARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVARBPROC)(GLenum target, const GLint *v); -GLAPI PFNGLMULTITEXCOORD2IVARBPROC glad_glMultiTexCoord2ivARB; -#define glMultiTexCoord2ivARB glad_glMultiTexCoord2ivARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD2SARBPROC)(GLenum target, GLshort s, GLshort t); -GLAPI PFNGLMULTITEXCOORD2SARBPROC glad_glMultiTexCoord2sARB; -#define glMultiTexCoord2sARB glad_glMultiTexCoord2sARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVARBPROC)(GLenum target, const GLshort *v); -GLAPI PFNGLMULTITEXCOORD2SVARBPROC glad_glMultiTexCoord2svARB; -#define glMultiTexCoord2svARB glad_glMultiTexCoord2svARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD3DARBPROC)(GLenum target, GLdouble s, GLdouble t, GLdouble r); -GLAPI PFNGLMULTITEXCOORD3DARBPROC glad_glMultiTexCoord3dARB; -#define glMultiTexCoord3dARB glad_glMultiTexCoord3dARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVARBPROC)(GLenum target, const GLdouble *v); -GLAPI PFNGLMULTITEXCOORD3DVARBPROC glad_glMultiTexCoord3dvARB; -#define glMultiTexCoord3dvARB glad_glMultiTexCoord3dvARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD3FARBPROC)(GLenum target, GLfloat s, GLfloat t, GLfloat r); -GLAPI PFNGLMULTITEXCOORD3FARBPROC glad_glMultiTexCoord3fARB; -#define glMultiTexCoord3fARB glad_glMultiTexCoord3fARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVARBPROC)(GLenum target, const GLfloat *v); -GLAPI PFNGLMULTITEXCOORD3FVARBPROC glad_glMultiTexCoord3fvARB; -#define glMultiTexCoord3fvARB glad_glMultiTexCoord3fvARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD3IARBPROC)(GLenum target, GLint s, GLint t, GLint r); -GLAPI PFNGLMULTITEXCOORD3IARBPROC glad_glMultiTexCoord3iARB; -#define glMultiTexCoord3iARB glad_glMultiTexCoord3iARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVARBPROC)(GLenum target, const GLint *v); -GLAPI PFNGLMULTITEXCOORD3IVARBPROC glad_glMultiTexCoord3ivARB; -#define glMultiTexCoord3ivARB glad_glMultiTexCoord3ivARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD3SARBPROC)(GLenum target, GLshort s, GLshort t, GLshort r); -GLAPI PFNGLMULTITEXCOORD3SARBPROC glad_glMultiTexCoord3sARB; -#define glMultiTexCoord3sARB glad_glMultiTexCoord3sARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVARBPROC)(GLenum target, const GLshort *v); -GLAPI PFNGLMULTITEXCOORD3SVARBPROC glad_glMultiTexCoord3svARB; -#define glMultiTexCoord3svARB glad_glMultiTexCoord3svARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD4DARBPROC)(GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); -GLAPI PFNGLMULTITEXCOORD4DARBPROC glad_glMultiTexCoord4dARB; -#define glMultiTexCoord4dARB glad_glMultiTexCoord4dARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVARBPROC)(GLenum target, const GLdouble *v); -GLAPI PFNGLMULTITEXCOORD4DVARBPROC glad_glMultiTexCoord4dvARB; -#define glMultiTexCoord4dvARB glad_glMultiTexCoord4dvARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD4FARBPROC)(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); -GLAPI PFNGLMULTITEXCOORD4FARBPROC glad_glMultiTexCoord4fARB; -#define glMultiTexCoord4fARB glad_glMultiTexCoord4fARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVARBPROC)(GLenum target, const GLfloat *v); -GLAPI PFNGLMULTITEXCOORD4FVARBPROC glad_glMultiTexCoord4fvARB; -#define glMultiTexCoord4fvARB glad_glMultiTexCoord4fvARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD4IARBPROC)(GLenum target, GLint s, GLint t, GLint r, GLint q); -GLAPI PFNGLMULTITEXCOORD4IARBPROC glad_glMultiTexCoord4iARB; -#define glMultiTexCoord4iARB glad_glMultiTexCoord4iARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVARBPROC)(GLenum target, const GLint *v); -GLAPI PFNGLMULTITEXCOORD4IVARBPROC glad_glMultiTexCoord4ivARB; -#define glMultiTexCoord4ivARB glad_glMultiTexCoord4ivARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD4SARBPROC)(GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); -GLAPI PFNGLMULTITEXCOORD4SARBPROC glad_glMultiTexCoord4sARB; -#define glMultiTexCoord4sARB glad_glMultiTexCoord4sARB -typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVARBPROC)(GLenum target, const GLshort *v); -GLAPI PFNGLMULTITEXCOORD4SVARBPROC glad_glMultiTexCoord4svARB; -#define glMultiTexCoord4svARB glad_glMultiTexCoord4svARB -#endif -#ifndef GL_ARB_occlusion_query -#define GL_ARB_occlusion_query 1 -GLAPI int GLAD_GL_ARB_occlusion_query; -typedef void (APIENTRYP PFNGLGENQUERIESARBPROC)(GLsizei n, GLuint *ids); -GLAPI PFNGLGENQUERIESARBPROC glad_glGenQueriesARB; -#define glGenQueriesARB glad_glGenQueriesARB -typedef void (APIENTRYP PFNGLDELETEQUERIESARBPROC)(GLsizei n, const GLuint *ids); -GLAPI PFNGLDELETEQUERIESARBPROC glad_glDeleteQueriesARB; -#define glDeleteQueriesARB glad_glDeleteQueriesARB -typedef GLboolean (APIENTRYP PFNGLISQUERYARBPROC)(GLuint id); -GLAPI PFNGLISQUERYARBPROC glad_glIsQueryARB; -#define glIsQueryARB glad_glIsQueryARB -typedef void (APIENTRYP PFNGLBEGINQUERYARBPROC)(GLenum target, GLuint id); -GLAPI PFNGLBEGINQUERYARBPROC glad_glBeginQueryARB; -#define glBeginQueryARB glad_glBeginQueryARB -typedef void (APIENTRYP PFNGLENDQUERYARBPROC)(GLenum target); -GLAPI PFNGLENDQUERYARBPROC glad_glEndQueryARB; -#define glEndQueryARB glad_glEndQueryARB -typedef void (APIENTRYP PFNGLGETQUERYIVARBPROC)(GLenum target, GLenum pname, GLint *params); -GLAPI PFNGLGETQUERYIVARBPROC glad_glGetQueryivARB; -#define glGetQueryivARB glad_glGetQueryivARB -typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVARBPROC)(GLuint id, GLenum pname, GLint *params); -GLAPI PFNGLGETQUERYOBJECTIVARBPROC glad_glGetQueryObjectivARB; -#define glGetQueryObjectivARB glad_glGetQueryObjectivARB -typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVARBPROC)(GLuint id, GLenum pname, GLuint *params); -GLAPI PFNGLGETQUERYOBJECTUIVARBPROC glad_glGetQueryObjectuivARB; -#define glGetQueryObjectuivARB glad_glGetQueryObjectuivARB -#endif -#ifndef GL_ARB_pixel_buffer_object -#define GL_ARB_pixel_buffer_object 1 -GLAPI int GLAD_GL_ARB_pixel_buffer_object; -#endif -#ifndef GL_ARB_point_parameters -#define GL_ARB_point_parameters 1 -GLAPI int GLAD_GL_ARB_point_parameters; -typedef void (APIENTRYP PFNGLPOINTPARAMETERFARBPROC)(GLenum pname, GLfloat param); -GLAPI PFNGLPOINTPARAMETERFARBPROC glad_glPointParameterfARB; -#define glPointParameterfARB glad_glPointParameterfARB -typedef void (APIENTRYP PFNGLPOINTPARAMETERFVARBPROC)(GLenum pname, const GLfloat *params); -GLAPI PFNGLPOINTPARAMETERFVARBPROC glad_glPointParameterfvARB; -#define glPointParameterfvARB glad_glPointParameterfvARB -#endif -#ifndef GL_ARB_point_sprite -#define GL_ARB_point_sprite 1 -GLAPI int GLAD_GL_ARB_point_sprite; -#endif -#ifndef GL_ARB_seamless_cube_map -#define GL_ARB_seamless_cube_map 1 -GLAPI int GLAD_GL_ARB_seamless_cube_map; -#endif -#ifndef GL_ARB_shader_objects -#define GL_ARB_shader_objects 1 -GLAPI int GLAD_GL_ARB_shader_objects; -typedef void (APIENTRYP PFNGLDELETEOBJECTARBPROC)(GLhandleARB obj); -GLAPI PFNGLDELETEOBJECTARBPROC glad_glDeleteObjectARB; -#define glDeleteObjectARB glad_glDeleteObjectARB -typedef GLhandleARB (APIENTRYP PFNGLGETHANDLEARBPROC)(GLenum pname); -GLAPI PFNGLGETHANDLEARBPROC glad_glGetHandleARB; -#define glGetHandleARB glad_glGetHandleARB -typedef void (APIENTRYP PFNGLDETACHOBJECTARBPROC)(GLhandleARB containerObj, GLhandleARB attachedObj); -GLAPI PFNGLDETACHOBJECTARBPROC glad_glDetachObjectARB; -#define glDetachObjectARB glad_glDetachObjectARB -typedef GLhandleARB (APIENTRYP PFNGLCREATESHADEROBJECTARBPROC)(GLenum shaderType); -GLAPI PFNGLCREATESHADEROBJECTARBPROC glad_glCreateShaderObjectARB; -#define glCreateShaderObjectARB glad_glCreateShaderObjectARB -typedef void (APIENTRYP PFNGLSHADERSOURCEARBPROC)(GLhandleARB shaderObj, GLsizei count, const GLcharARB **string, const GLint *length); -GLAPI PFNGLSHADERSOURCEARBPROC glad_glShaderSourceARB; -#define glShaderSourceARB glad_glShaderSourceARB -typedef void (APIENTRYP PFNGLCOMPILESHADERARBPROC)(GLhandleARB shaderObj); -GLAPI PFNGLCOMPILESHADERARBPROC glad_glCompileShaderARB; -#define glCompileShaderARB glad_glCompileShaderARB -typedef GLhandleARB (APIENTRYP PFNGLCREATEPROGRAMOBJECTARBPROC)(void); -GLAPI PFNGLCREATEPROGRAMOBJECTARBPROC glad_glCreateProgramObjectARB; -#define glCreateProgramObjectARB glad_glCreateProgramObjectARB -typedef void (APIENTRYP PFNGLATTACHOBJECTARBPROC)(GLhandleARB containerObj, GLhandleARB obj); -GLAPI PFNGLATTACHOBJECTARBPROC glad_glAttachObjectARB; -#define glAttachObjectARB glad_glAttachObjectARB -typedef void (APIENTRYP PFNGLLINKPROGRAMARBPROC)(GLhandleARB programObj); -GLAPI PFNGLLINKPROGRAMARBPROC glad_glLinkProgramARB; -#define glLinkProgramARB glad_glLinkProgramARB -typedef void (APIENTRYP PFNGLUSEPROGRAMOBJECTARBPROC)(GLhandleARB programObj); -GLAPI PFNGLUSEPROGRAMOBJECTARBPROC glad_glUseProgramObjectARB; -#define glUseProgramObjectARB glad_glUseProgramObjectARB -typedef void (APIENTRYP PFNGLVALIDATEPROGRAMARBPROC)(GLhandleARB programObj); -GLAPI PFNGLVALIDATEPROGRAMARBPROC glad_glValidateProgramARB; -#define glValidateProgramARB glad_glValidateProgramARB -typedef void (APIENTRYP PFNGLUNIFORM1FARBPROC)(GLint location, GLfloat v0); -GLAPI PFNGLUNIFORM1FARBPROC glad_glUniform1fARB; -#define glUniform1fARB glad_glUniform1fARB -typedef void (APIENTRYP PFNGLUNIFORM2FARBPROC)(GLint location, GLfloat v0, GLfloat v1); -GLAPI PFNGLUNIFORM2FARBPROC glad_glUniform2fARB; -#define glUniform2fARB glad_glUniform2fARB -typedef void (APIENTRYP PFNGLUNIFORM3FARBPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2); -GLAPI PFNGLUNIFORM3FARBPROC glad_glUniform3fARB; -#define glUniform3fARB glad_glUniform3fARB -typedef void (APIENTRYP PFNGLUNIFORM4FARBPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); -GLAPI PFNGLUNIFORM4FARBPROC glad_glUniform4fARB; -#define glUniform4fARB glad_glUniform4fARB -typedef void (APIENTRYP PFNGLUNIFORM1IARBPROC)(GLint location, GLint v0); -GLAPI PFNGLUNIFORM1IARBPROC glad_glUniform1iARB; -#define glUniform1iARB glad_glUniform1iARB -typedef void (APIENTRYP PFNGLUNIFORM2IARBPROC)(GLint location, GLint v0, GLint v1); -GLAPI PFNGLUNIFORM2IARBPROC glad_glUniform2iARB; -#define glUniform2iARB glad_glUniform2iARB -typedef void (APIENTRYP PFNGLUNIFORM3IARBPROC)(GLint location, GLint v0, GLint v1, GLint v2); -GLAPI PFNGLUNIFORM3IARBPROC glad_glUniform3iARB; -#define glUniform3iARB glad_glUniform3iARB -typedef void (APIENTRYP PFNGLUNIFORM4IARBPROC)(GLint location, GLint v0, GLint v1, GLint v2, GLint v3); -GLAPI PFNGLUNIFORM4IARBPROC glad_glUniform4iARB; -#define glUniform4iARB glad_glUniform4iARB -typedef void (APIENTRYP PFNGLUNIFORM1FVARBPROC)(GLint location, GLsizei count, const GLfloat *value); -GLAPI PFNGLUNIFORM1FVARBPROC glad_glUniform1fvARB; -#define glUniform1fvARB glad_glUniform1fvARB -typedef void (APIENTRYP PFNGLUNIFORM2FVARBPROC)(GLint location, GLsizei count, const GLfloat *value); -GLAPI PFNGLUNIFORM2FVARBPROC glad_glUniform2fvARB; -#define glUniform2fvARB glad_glUniform2fvARB -typedef void (APIENTRYP PFNGLUNIFORM3FVARBPROC)(GLint location, GLsizei count, const GLfloat *value); -GLAPI PFNGLUNIFORM3FVARBPROC glad_glUniform3fvARB; -#define glUniform3fvARB glad_glUniform3fvARB -typedef void (APIENTRYP PFNGLUNIFORM4FVARBPROC)(GLint location, GLsizei count, const GLfloat *value); -GLAPI PFNGLUNIFORM4FVARBPROC glad_glUniform4fvARB; -#define glUniform4fvARB glad_glUniform4fvARB -typedef void (APIENTRYP PFNGLUNIFORM1IVARBPROC)(GLint location, GLsizei count, const GLint *value); -GLAPI PFNGLUNIFORM1IVARBPROC glad_glUniform1ivARB; -#define glUniform1ivARB glad_glUniform1ivARB -typedef void (APIENTRYP PFNGLUNIFORM2IVARBPROC)(GLint location, GLsizei count, const GLint *value); -GLAPI PFNGLUNIFORM2IVARBPROC glad_glUniform2ivARB; -#define glUniform2ivARB glad_glUniform2ivARB -typedef void (APIENTRYP PFNGLUNIFORM3IVARBPROC)(GLint location, GLsizei count, const GLint *value); -GLAPI PFNGLUNIFORM3IVARBPROC glad_glUniform3ivARB; -#define glUniform3ivARB glad_glUniform3ivARB -typedef void (APIENTRYP PFNGLUNIFORM4IVARBPROC)(GLint location, GLsizei count, const GLint *value); -GLAPI PFNGLUNIFORM4IVARBPROC glad_glUniform4ivARB; -#define glUniform4ivARB glad_glUniform4ivARB -typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVARBPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX2FVARBPROC glad_glUniformMatrix2fvARB; -#define glUniformMatrix2fvARB glad_glUniformMatrix2fvARB -typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVARBPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX3FVARBPROC glad_glUniformMatrix3fvARB; -#define glUniformMatrix3fvARB glad_glUniformMatrix3fvARB -typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVARBPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI PFNGLUNIFORMMATRIX4FVARBPROC glad_glUniformMatrix4fvARB; -#define glUniformMatrix4fvARB glad_glUniformMatrix4fvARB -typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERFVARBPROC)(GLhandleARB obj, GLenum pname, GLfloat *params); -GLAPI PFNGLGETOBJECTPARAMETERFVARBPROC glad_glGetObjectParameterfvARB; -#define glGetObjectParameterfvARB glad_glGetObjectParameterfvARB -typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERIVARBPROC)(GLhandleARB obj, GLenum pname, GLint *params); -GLAPI PFNGLGETOBJECTPARAMETERIVARBPROC glad_glGetObjectParameterivARB; -#define glGetObjectParameterivARB glad_glGetObjectParameterivARB -typedef void (APIENTRYP PFNGLGETINFOLOGARBPROC)(GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog); -GLAPI PFNGLGETINFOLOGARBPROC glad_glGetInfoLogARB; -#define glGetInfoLogARB glad_glGetInfoLogARB -typedef void (APIENTRYP PFNGLGETATTACHEDOBJECTSARBPROC)(GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj); -GLAPI PFNGLGETATTACHEDOBJECTSARBPROC glad_glGetAttachedObjectsARB; -#define glGetAttachedObjectsARB glad_glGetAttachedObjectsARB -typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONARBPROC)(GLhandleARB programObj, const GLcharARB *name); -GLAPI PFNGLGETUNIFORMLOCATIONARBPROC glad_glGetUniformLocationARB; -#define glGetUniformLocationARB glad_glGetUniformLocationARB -typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMARBPROC)(GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); -GLAPI PFNGLGETACTIVEUNIFORMARBPROC glad_glGetActiveUniformARB; -#define glGetActiveUniformARB glad_glGetActiveUniformARB -typedef void (APIENTRYP PFNGLGETUNIFORMFVARBPROC)(GLhandleARB programObj, GLint location, GLfloat *params); -GLAPI PFNGLGETUNIFORMFVARBPROC glad_glGetUniformfvARB; -#define glGetUniformfvARB glad_glGetUniformfvARB -typedef void (APIENTRYP PFNGLGETUNIFORMIVARBPROC)(GLhandleARB programObj, GLint location, GLint *params); -GLAPI PFNGLGETUNIFORMIVARBPROC glad_glGetUniformivARB; -#define glGetUniformivARB glad_glGetUniformivARB -typedef void (APIENTRYP PFNGLGETSHADERSOURCEARBPROC)(GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source); -GLAPI PFNGLGETSHADERSOURCEARBPROC glad_glGetShaderSourceARB; -#define glGetShaderSourceARB glad_glGetShaderSourceARB -#endif -#ifndef GL_ARB_shading_language_100 -#define GL_ARB_shading_language_100 1 -GLAPI int GLAD_GL_ARB_shading_language_100; -#endif -#ifndef GL_ARB_shadow -#define GL_ARB_shadow 1 -GLAPI int GLAD_GL_ARB_shadow; -#endif -#ifndef GL_ARB_texture_compression -#define GL_ARB_texture_compression 1 -GLAPI int GLAD_GL_ARB_texture_compression; -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DARBPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); -GLAPI PFNGLCOMPRESSEDTEXIMAGE3DARBPROC glad_glCompressedTexImage3DARB; -#define glCompressedTexImage3DARB glad_glCompressedTexImage3DARB -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DARBPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); -GLAPI PFNGLCOMPRESSEDTEXIMAGE2DARBPROC glad_glCompressedTexImage2DARB; -#define glCompressedTexImage2DARB glad_glCompressedTexImage2DARB -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DARBPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); -GLAPI PFNGLCOMPRESSEDTEXIMAGE1DARBPROC glad_glCompressedTexImage1DARB; -#define glCompressedTexImage1DARB glad_glCompressedTexImage1DARB -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); -GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC glad_glCompressedTexSubImage3DARB; -#define glCompressedTexSubImage3DARB glad_glCompressedTexSubImage3DARB -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); -GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC glad_glCompressedTexSubImage2DARB; -#define glCompressedTexSubImage2DARB glad_glCompressedTexSubImage2DARB -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); -GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC glad_glCompressedTexSubImage1DARB; -#define glCompressedTexSubImage1DARB glad_glCompressedTexSubImage1DARB -typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEARBPROC)(GLenum target, GLint level, void *img); -GLAPI PFNGLGETCOMPRESSEDTEXIMAGEARBPROC glad_glGetCompressedTexImageARB; -#define glGetCompressedTexImageARB glad_glGetCompressedTexImageARB -#endif -#ifndef GL_ARB_texture_cube_map -#define GL_ARB_texture_cube_map 1 -GLAPI int GLAD_GL_ARB_texture_cube_map; -#endif -#ifndef GL_ARB_texture_env_combine -#define GL_ARB_texture_env_combine 1 -GLAPI int GLAD_GL_ARB_texture_env_combine; -#endif -#ifndef GL_ARB_texture_float -#define GL_ARB_texture_float 1 -GLAPI int GLAD_GL_ARB_texture_float; -#endif -#ifndef GL_ARB_texture_non_power_of_two -#define GL_ARB_texture_non_power_of_two 1 -GLAPI int GLAD_GL_ARB_texture_non_power_of_two; -#endif -#ifndef GL_ARB_vertex_buffer_object -#define GL_ARB_vertex_buffer_object 1 -GLAPI int GLAD_GL_ARB_vertex_buffer_object; -typedef void (APIENTRYP PFNGLBINDBUFFERARBPROC)(GLenum target, GLuint buffer); -GLAPI PFNGLBINDBUFFERARBPROC glad_glBindBufferARB; -#define glBindBufferARB glad_glBindBufferARB -typedef void (APIENTRYP PFNGLDELETEBUFFERSARBPROC)(GLsizei n, const GLuint *buffers); -GLAPI PFNGLDELETEBUFFERSARBPROC glad_glDeleteBuffersARB; -#define glDeleteBuffersARB glad_glDeleteBuffersARB -typedef void (APIENTRYP PFNGLGENBUFFERSARBPROC)(GLsizei n, GLuint *buffers); -GLAPI PFNGLGENBUFFERSARBPROC glad_glGenBuffersARB; -#define glGenBuffersARB glad_glGenBuffersARB -typedef GLboolean (APIENTRYP PFNGLISBUFFERARBPROC)(GLuint buffer); -GLAPI PFNGLISBUFFERARBPROC glad_glIsBufferARB; -#define glIsBufferARB glad_glIsBufferARB -typedef void (APIENTRYP PFNGLBUFFERDATAARBPROC)(GLenum target, GLsizeiptrARB size, const void *data, GLenum usage); -GLAPI PFNGLBUFFERDATAARBPROC glad_glBufferDataARB; -#define glBufferDataARB glad_glBufferDataARB -typedef void (APIENTRYP PFNGLBUFFERSUBDATAARBPROC)(GLenum target, GLintptrARB offset, GLsizeiptrARB size, const void *data); -GLAPI PFNGLBUFFERSUBDATAARBPROC glad_glBufferSubDataARB; -#define glBufferSubDataARB glad_glBufferSubDataARB -typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAARBPROC)(GLenum target, GLintptrARB offset, GLsizeiptrARB size, void *data); -GLAPI PFNGLGETBUFFERSUBDATAARBPROC glad_glGetBufferSubDataARB; -#define glGetBufferSubDataARB glad_glGetBufferSubDataARB -typedef void * (APIENTRYP PFNGLMAPBUFFERARBPROC)(GLenum target, GLenum access); -GLAPI PFNGLMAPBUFFERARBPROC glad_glMapBufferARB; -#define glMapBufferARB glad_glMapBufferARB -typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERARBPROC)(GLenum target); -GLAPI PFNGLUNMAPBUFFERARBPROC glad_glUnmapBufferARB; -#define glUnmapBufferARB glad_glUnmapBufferARB -typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVARBPROC)(GLenum target, GLenum pname, GLint *params); -GLAPI PFNGLGETBUFFERPARAMETERIVARBPROC glad_glGetBufferParameterivARB; -#define glGetBufferParameterivARB glad_glGetBufferParameterivARB -typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVARBPROC)(GLenum target, GLenum pname, void **params); -GLAPI PFNGLGETBUFFERPOINTERVARBPROC glad_glGetBufferPointervARB; -#define glGetBufferPointervARB glad_glGetBufferPointervARB -#endif -#ifndef GL_ARB_vertex_program -#define GL_ARB_vertex_program 1 -GLAPI int GLAD_GL_ARB_vertex_program; -typedef void (APIENTRYP PFNGLVERTEXATTRIB1DARBPROC)(GLuint index, GLdouble x); -GLAPI PFNGLVERTEXATTRIB1DARBPROC glad_glVertexAttrib1dARB; -#define glVertexAttrib1dARB glad_glVertexAttrib1dARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVARBPROC)(GLuint index, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIB1DVARBPROC glad_glVertexAttrib1dvARB; -#define glVertexAttrib1dvARB glad_glVertexAttrib1dvARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB1FARBPROC)(GLuint index, GLfloat x); -GLAPI PFNGLVERTEXATTRIB1FARBPROC glad_glVertexAttrib1fARB; -#define glVertexAttrib1fARB glad_glVertexAttrib1fARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVARBPROC)(GLuint index, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIB1FVARBPROC glad_glVertexAttrib1fvARB; -#define glVertexAttrib1fvARB glad_glVertexAttrib1fvARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB1SARBPROC)(GLuint index, GLshort x); -GLAPI PFNGLVERTEXATTRIB1SARBPROC glad_glVertexAttrib1sARB; -#define glVertexAttrib1sARB glad_glVertexAttrib1sARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVARBPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIB1SVARBPROC glad_glVertexAttrib1svARB; -#define glVertexAttrib1svARB glad_glVertexAttrib1svARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB2DARBPROC)(GLuint index, GLdouble x, GLdouble y); -GLAPI PFNGLVERTEXATTRIB2DARBPROC glad_glVertexAttrib2dARB; -#define glVertexAttrib2dARB glad_glVertexAttrib2dARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVARBPROC)(GLuint index, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIB2DVARBPROC glad_glVertexAttrib2dvARB; -#define glVertexAttrib2dvARB glad_glVertexAttrib2dvARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB2FARBPROC)(GLuint index, GLfloat x, GLfloat y); -GLAPI PFNGLVERTEXATTRIB2FARBPROC glad_glVertexAttrib2fARB; -#define glVertexAttrib2fARB glad_glVertexAttrib2fARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVARBPROC)(GLuint index, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIB2FVARBPROC glad_glVertexAttrib2fvARB; -#define glVertexAttrib2fvARB glad_glVertexAttrib2fvARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB2SARBPROC)(GLuint index, GLshort x, GLshort y); -GLAPI PFNGLVERTEXATTRIB2SARBPROC glad_glVertexAttrib2sARB; -#define glVertexAttrib2sARB glad_glVertexAttrib2sARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVARBPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIB2SVARBPROC glad_glVertexAttrib2svARB; -#define glVertexAttrib2svARB glad_glVertexAttrib2svARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB3DARBPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z); -GLAPI PFNGLVERTEXATTRIB3DARBPROC glad_glVertexAttrib3dARB; -#define glVertexAttrib3dARB glad_glVertexAttrib3dARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVARBPROC)(GLuint index, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIB3DVARBPROC glad_glVertexAttrib3dvARB; -#define glVertexAttrib3dvARB glad_glVertexAttrib3dvARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB3FARBPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z); -GLAPI PFNGLVERTEXATTRIB3FARBPROC glad_glVertexAttrib3fARB; -#define glVertexAttrib3fARB glad_glVertexAttrib3fARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVARBPROC)(GLuint index, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIB3FVARBPROC glad_glVertexAttrib3fvARB; -#define glVertexAttrib3fvARB glad_glVertexAttrib3fvARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB3SARBPROC)(GLuint index, GLshort x, GLshort y, GLshort z); -GLAPI PFNGLVERTEXATTRIB3SARBPROC glad_glVertexAttrib3sARB; -#define glVertexAttrib3sARB glad_glVertexAttrib3sARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVARBPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIB3SVARBPROC glad_glVertexAttrib3svARB; -#define glVertexAttrib3svARB glad_glVertexAttrib3svARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVARBPROC)(GLuint index, const GLbyte *v); -GLAPI PFNGLVERTEXATTRIB4NBVARBPROC glad_glVertexAttrib4NbvARB; -#define glVertexAttrib4NbvARB glad_glVertexAttrib4NbvARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVARBPROC)(GLuint index, const GLint *v); -GLAPI PFNGLVERTEXATTRIB4NIVARBPROC glad_glVertexAttrib4NivARB; -#define glVertexAttrib4NivARB glad_glVertexAttrib4NivARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVARBPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIB4NSVARBPROC glad_glVertexAttrib4NsvARB; -#define glVertexAttrib4NsvARB glad_glVertexAttrib4NsvARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBARBPROC)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); -GLAPI PFNGLVERTEXATTRIB4NUBARBPROC glad_glVertexAttrib4NubARB; -#define glVertexAttrib4NubARB glad_glVertexAttrib4NubARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVARBPROC)(GLuint index, const GLubyte *v); -GLAPI PFNGLVERTEXATTRIB4NUBVARBPROC glad_glVertexAttrib4NubvARB; -#define glVertexAttrib4NubvARB glad_glVertexAttrib4NubvARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVARBPROC)(GLuint index, const GLuint *v); -GLAPI PFNGLVERTEXATTRIB4NUIVARBPROC glad_glVertexAttrib4NuivARB; -#define glVertexAttrib4NuivARB glad_glVertexAttrib4NuivARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVARBPROC)(GLuint index, const GLushort *v); -GLAPI PFNGLVERTEXATTRIB4NUSVARBPROC glad_glVertexAttrib4NusvARB; -#define glVertexAttrib4NusvARB glad_glVertexAttrib4NusvARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVARBPROC)(GLuint index, const GLbyte *v); -GLAPI PFNGLVERTEXATTRIB4BVARBPROC glad_glVertexAttrib4bvARB; -#define glVertexAttrib4bvARB glad_glVertexAttrib4bvARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB4DARBPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); -GLAPI PFNGLVERTEXATTRIB4DARBPROC glad_glVertexAttrib4dARB; -#define glVertexAttrib4dARB glad_glVertexAttrib4dARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVARBPROC)(GLuint index, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIB4DVARBPROC glad_glVertexAttrib4dvARB; -#define glVertexAttrib4dvARB glad_glVertexAttrib4dvARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB4FARBPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); -GLAPI PFNGLVERTEXATTRIB4FARBPROC glad_glVertexAttrib4fARB; -#define glVertexAttrib4fARB glad_glVertexAttrib4fARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVARBPROC)(GLuint index, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIB4FVARBPROC glad_glVertexAttrib4fvARB; -#define glVertexAttrib4fvARB glad_glVertexAttrib4fvARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVARBPROC)(GLuint index, const GLint *v); -GLAPI PFNGLVERTEXATTRIB4IVARBPROC glad_glVertexAttrib4ivARB; -#define glVertexAttrib4ivARB glad_glVertexAttrib4ivARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB4SARBPROC)(GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); -GLAPI PFNGLVERTEXATTRIB4SARBPROC glad_glVertexAttrib4sARB; -#define glVertexAttrib4sARB glad_glVertexAttrib4sARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVARBPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIB4SVARBPROC glad_glVertexAttrib4svARB; -#define glVertexAttrib4svARB glad_glVertexAttrib4svARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVARBPROC)(GLuint index, const GLubyte *v); -GLAPI PFNGLVERTEXATTRIB4UBVARBPROC glad_glVertexAttrib4ubvARB; -#define glVertexAttrib4ubvARB glad_glVertexAttrib4ubvARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVARBPROC)(GLuint index, const GLuint *v); -GLAPI PFNGLVERTEXATTRIB4UIVARBPROC glad_glVertexAttrib4uivARB; -#define glVertexAttrib4uivARB glad_glVertexAttrib4uivARB -typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVARBPROC)(GLuint index, const GLushort *v); -GLAPI PFNGLVERTEXATTRIB4USVARBPROC glad_glVertexAttrib4usvARB; -#define glVertexAttrib4usvARB glad_glVertexAttrib4usvARB -typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERARBPROC)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); -GLAPI PFNGLVERTEXATTRIBPOINTERARBPROC glad_glVertexAttribPointerARB; -#define glVertexAttribPointerARB glad_glVertexAttribPointerARB -typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYARBPROC)(GLuint index); -GLAPI PFNGLENABLEVERTEXATTRIBARRAYARBPROC glad_glEnableVertexAttribArrayARB; -#define glEnableVertexAttribArrayARB glad_glEnableVertexAttribArrayARB -typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYARBPROC)(GLuint index); -GLAPI PFNGLDISABLEVERTEXATTRIBARRAYARBPROC glad_glDisableVertexAttribArrayARB; -#define glDisableVertexAttribArrayARB glad_glDisableVertexAttribArrayARB -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVARBPROC)(GLuint index, GLenum pname, GLdouble *params); -GLAPI PFNGLGETVERTEXATTRIBDVARBPROC glad_glGetVertexAttribdvARB; -#define glGetVertexAttribdvARB glad_glGetVertexAttribdvARB -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVARBPROC)(GLuint index, GLenum pname, GLfloat *params); -GLAPI PFNGLGETVERTEXATTRIBFVARBPROC glad_glGetVertexAttribfvARB; -#define glGetVertexAttribfvARB glad_glGetVertexAttribfvARB -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVARBPROC)(GLuint index, GLenum pname, GLint *params); -GLAPI PFNGLGETVERTEXATTRIBIVARBPROC glad_glGetVertexAttribivARB; -#define glGetVertexAttribivARB glad_glGetVertexAttribivARB -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVARBPROC)(GLuint index, GLenum pname, void **pointer); -GLAPI PFNGLGETVERTEXATTRIBPOINTERVARBPROC glad_glGetVertexAttribPointervARB; -#define glGetVertexAttribPointervARB glad_glGetVertexAttribPointervARB -#endif -#ifndef GL_ARB_vertex_shader -#define GL_ARB_vertex_shader 1 -GLAPI int GLAD_GL_ARB_vertex_shader; -typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONARBPROC)(GLhandleARB programObj, GLuint index, const GLcharARB *name); -GLAPI PFNGLBINDATTRIBLOCATIONARBPROC glad_glBindAttribLocationARB; -#define glBindAttribLocationARB glad_glBindAttribLocationARB -typedef void (APIENTRYP PFNGLGETACTIVEATTRIBARBPROC)(GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); -GLAPI PFNGLGETACTIVEATTRIBARBPROC glad_glGetActiveAttribARB; -#define glGetActiveAttribARB glad_glGetActiveAttribARB -typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONARBPROC)(GLhandleARB programObj, const GLcharARB *name); -GLAPI PFNGLGETATTRIBLOCATIONARBPROC glad_glGetAttribLocationARB; -#define glGetAttribLocationARB glad_glGetAttribLocationARB -#endif -#ifndef GL_ATI_draw_buffers -#define GL_ATI_draw_buffers 1 -GLAPI int GLAD_GL_ATI_draw_buffers; -typedef void (APIENTRYP PFNGLDRAWBUFFERSATIPROC)(GLsizei n, const GLenum *bufs); -GLAPI PFNGLDRAWBUFFERSATIPROC glad_glDrawBuffersATI; -#define glDrawBuffersATI glad_glDrawBuffersATI -#endif -#ifndef GL_ATI_fragment_shader -#define GL_ATI_fragment_shader 1 -GLAPI int GLAD_GL_ATI_fragment_shader; -typedef GLuint (APIENTRYP PFNGLGENFRAGMENTSHADERSATIPROC)(GLuint range); -GLAPI PFNGLGENFRAGMENTSHADERSATIPROC glad_glGenFragmentShadersATI; -#define glGenFragmentShadersATI glad_glGenFragmentShadersATI -typedef void (APIENTRYP PFNGLBINDFRAGMENTSHADERATIPROC)(GLuint id); -GLAPI PFNGLBINDFRAGMENTSHADERATIPROC glad_glBindFragmentShaderATI; -#define glBindFragmentShaderATI glad_glBindFragmentShaderATI -typedef void (APIENTRYP PFNGLDELETEFRAGMENTSHADERATIPROC)(GLuint id); -GLAPI PFNGLDELETEFRAGMENTSHADERATIPROC glad_glDeleteFragmentShaderATI; -#define glDeleteFragmentShaderATI glad_glDeleteFragmentShaderATI -typedef void (APIENTRYP PFNGLBEGINFRAGMENTSHADERATIPROC)(void); -GLAPI PFNGLBEGINFRAGMENTSHADERATIPROC glad_glBeginFragmentShaderATI; -#define glBeginFragmentShaderATI glad_glBeginFragmentShaderATI -typedef void (APIENTRYP PFNGLENDFRAGMENTSHADERATIPROC)(void); -GLAPI PFNGLENDFRAGMENTSHADERATIPROC glad_glEndFragmentShaderATI; -#define glEndFragmentShaderATI glad_glEndFragmentShaderATI -typedef void (APIENTRYP PFNGLPASSTEXCOORDATIPROC)(GLuint dst, GLuint coord, GLenum swizzle); -GLAPI PFNGLPASSTEXCOORDATIPROC glad_glPassTexCoordATI; -#define glPassTexCoordATI glad_glPassTexCoordATI -typedef void (APIENTRYP PFNGLSAMPLEMAPATIPROC)(GLuint dst, GLuint interp, GLenum swizzle); -GLAPI PFNGLSAMPLEMAPATIPROC glad_glSampleMapATI; -#define glSampleMapATI glad_glSampleMapATI -typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP1ATIPROC)(GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod); -GLAPI PFNGLCOLORFRAGMENTOP1ATIPROC glad_glColorFragmentOp1ATI; -#define glColorFragmentOp1ATI glad_glColorFragmentOp1ATI -typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP2ATIPROC)(GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod); -GLAPI PFNGLCOLORFRAGMENTOP2ATIPROC glad_glColorFragmentOp2ATI; -#define glColorFragmentOp2ATI glad_glColorFragmentOp2ATI -typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP3ATIPROC)(GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod); -GLAPI PFNGLCOLORFRAGMENTOP3ATIPROC glad_glColorFragmentOp3ATI; -#define glColorFragmentOp3ATI glad_glColorFragmentOp3ATI -typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP1ATIPROC)(GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod); -GLAPI PFNGLALPHAFRAGMENTOP1ATIPROC glad_glAlphaFragmentOp1ATI; -#define glAlphaFragmentOp1ATI glad_glAlphaFragmentOp1ATI -typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP2ATIPROC)(GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod); -GLAPI PFNGLALPHAFRAGMENTOP2ATIPROC glad_glAlphaFragmentOp2ATI; -#define glAlphaFragmentOp2ATI glad_glAlphaFragmentOp2ATI -typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP3ATIPROC)(GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod); -GLAPI PFNGLALPHAFRAGMENTOP3ATIPROC glad_glAlphaFragmentOp3ATI; -#define glAlphaFragmentOp3ATI glad_glAlphaFragmentOp3ATI -typedef void (APIENTRYP PFNGLSETFRAGMENTSHADERCONSTANTATIPROC)(GLuint dst, const GLfloat *value); -GLAPI PFNGLSETFRAGMENTSHADERCONSTANTATIPROC glad_glSetFragmentShaderConstantATI; -#define glSetFragmentShaderConstantATI glad_glSetFragmentShaderConstantATI -#endif -#ifndef GL_ATI_texture_float -#define GL_ATI_texture_float 1 -GLAPI int GLAD_GL_ATI_texture_float; -#endif -#ifndef GL_EXT_blend_equation_separate -#define GL_EXT_blend_equation_separate 1 -GLAPI int GLAD_GL_EXT_blend_equation_separate; -typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEEXTPROC)(GLenum modeRGB, GLenum modeAlpha); -GLAPI PFNGLBLENDEQUATIONSEPARATEEXTPROC glad_glBlendEquationSeparateEXT; -#define glBlendEquationSeparateEXT glad_glBlendEquationSeparateEXT -#endif -#ifndef GL_EXT_framebuffer_blit -#define GL_EXT_framebuffer_blit 1 -GLAPI int GLAD_GL_EXT_framebuffer_blit; -typedef void (APIENTRYP PFNGLBLITFRAMEBUFFEREXTPROC)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); -GLAPI PFNGLBLITFRAMEBUFFEREXTPROC glad_glBlitFramebufferEXT; -#define glBlitFramebufferEXT glad_glBlitFramebufferEXT -#endif -#ifndef GL_EXT_framebuffer_multisample -#define GL_EXT_framebuffer_multisample 1 -GLAPI int GLAD_GL_EXT_framebuffer_multisample; -typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -GLAPI PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC glad_glRenderbufferStorageMultisampleEXT; -#define glRenderbufferStorageMultisampleEXT glad_glRenderbufferStorageMultisampleEXT -#endif -#ifndef GL_EXT_framebuffer_object -#define GL_EXT_framebuffer_object 1 -GLAPI int GLAD_GL_EXT_framebuffer_object; -typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFEREXTPROC)(GLuint renderbuffer); -GLAPI PFNGLISRENDERBUFFEREXTPROC glad_glIsRenderbufferEXT; -#define glIsRenderbufferEXT glad_glIsRenderbufferEXT -typedef void (APIENTRYP PFNGLBINDRENDERBUFFEREXTPROC)(GLenum target, GLuint renderbuffer); -GLAPI PFNGLBINDRENDERBUFFEREXTPROC glad_glBindRenderbufferEXT; -#define glBindRenderbufferEXT glad_glBindRenderbufferEXT -typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSEXTPROC)(GLsizei n, const GLuint *renderbuffers); -GLAPI PFNGLDELETERENDERBUFFERSEXTPROC glad_glDeleteRenderbuffersEXT; -#define glDeleteRenderbuffersEXT glad_glDeleteRenderbuffersEXT -typedef void (APIENTRYP PFNGLGENRENDERBUFFERSEXTPROC)(GLsizei n, GLuint *renderbuffers); -GLAPI PFNGLGENRENDERBUFFERSEXTPROC glad_glGenRenderbuffersEXT; -#define glGenRenderbuffersEXT glad_glGenRenderbuffersEXT -typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEEXTPROC)(GLenum target, GLenum internalformat, GLsizei width, GLsizei height); -GLAPI PFNGLRENDERBUFFERSTORAGEEXTPROC glad_glRenderbufferStorageEXT; -#define glRenderbufferStorageEXT glad_glRenderbufferStorageEXT -typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC)(GLenum target, GLenum pname, GLint *params); -GLAPI PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC glad_glGetRenderbufferParameterivEXT; -#define glGetRenderbufferParameterivEXT glad_glGetRenderbufferParameterivEXT -typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFEREXTPROC)(GLuint framebuffer); -GLAPI PFNGLISFRAMEBUFFEREXTPROC glad_glIsFramebufferEXT; -#define glIsFramebufferEXT glad_glIsFramebufferEXT -typedef void (APIENTRYP PFNGLBINDFRAMEBUFFEREXTPROC)(GLenum target, GLuint framebuffer); -GLAPI PFNGLBINDFRAMEBUFFEREXTPROC glad_glBindFramebufferEXT; -#define glBindFramebufferEXT glad_glBindFramebufferEXT -typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSEXTPROC)(GLsizei n, const GLuint *framebuffers); -GLAPI PFNGLDELETEFRAMEBUFFERSEXTPROC glad_glDeleteFramebuffersEXT; -#define glDeleteFramebuffersEXT glad_glDeleteFramebuffersEXT -typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSEXTPROC)(GLsizei n, GLuint *framebuffers); -GLAPI PFNGLGENFRAMEBUFFERSEXTPROC glad_glGenFramebuffersEXT; -#define glGenFramebuffersEXT glad_glGenFramebuffersEXT -typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC)(GLenum target); -GLAPI PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glad_glCheckFramebufferStatusEXT; -#define glCheckFramebufferStatusEXT glad_glCheckFramebufferStatusEXT -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DEXTPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); -GLAPI PFNGLFRAMEBUFFERTEXTURE1DEXTPROC glad_glFramebufferTexture1DEXT; -#define glFramebufferTexture1DEXT glad_glFramebufferTexture1DEXT -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DEXTPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); -GLAPI PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glad_glFramebufferTexture2DEXT; -#define glFramebufferTexture2DEXT glad_glFramebufferTexture2DEXT -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DEXTPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); -GLAPI PFNGLFRAMEBUFFERTEXTURE3DEXTPROC glad_glFramebufferTexture3DEXT; -#define glFramebufferTexture3DEXT glad_glFramebufferTexture3DEXT -typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC)(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); -GLAPI PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC glad_glFramebufferRenderbufferEXT; -#define glFramebufferRenderbufferEXT glad_glFramebufferRenderbufferEXT -typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC)(GLenum target, GLenum attachment, GLenum pname, GLint *params); -GLAPI PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC glad_glGetFramebufferAttachmentParameterivEXT; -#define glGetFramebufferAttachmentParameterivEXT glad_glGetFramebufferAttachmentParameterivEXT -typedef void (APIENTRYP PFNGLGENERATEMIPMAPEXTPROC)(GLenum target); -GLAPI PFNGLGENERATEMIPMAPEXTPROC glad_glGenerateMipmapEXT; -#define glGenerateMipmapEXT glad_glGenerateMipmapEXT -#endif -#ifndef GL_EXT_framebuffer_sRGB -#define GL_EXT_framebuffer_sRGB 1 -GLAPI int GLAD_GL_EXT_framebuffer_sRGB; -#endif -#ifndef GL_EXT_geometry_shader4 -#define GL_EXT_geometry_shader4 1 -GLAPI int GLAD_GL_EXT_geometry_shader4; -typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIEXTPROC)(GLuint program, GLenum pname, GLint value); -GLAPI PFNGLPROGRAMPARAMETERIEXTPROC glad_glProgramParameteriEXT; -#define glProgramParameteriEXT glad_glProgramParameteriEXT -#endif -#ifndef GL_EXT_pixel_buffer_object -#define GL_EXT_pixel_buffer_object 1 -GLAPI int GLAD_GL_EXT_pixel_buffer_object; -#endif -#ifndef GL_EXT_point_parameters -#define GL_EXT_point_parameters 1 -GLAPI int GLAD_GL_EXT_point_parameters; -typedef void (APIENTRYP PFNGLPOINTPARAMETERFEXTPROC)(GLenum pname, GLfloat param); -GLAPI PFNGLPOINTPARAMETERFEXTPROC glad_glPointParameterfEXT; -#define glPointParameterfEXT glad_glPointParameterfEXT -typedef void (APIENTRYP PFNGLPOINTPARAMETERFVEXTPROC)(GLenum pname, const GLfloat *params); -GLAPI PFNGLPOINTPARAMETERFVEXTPROC glad_glPointParameterfvEXT; -#define glPointParameterfvEXT glad_glPointParameterfvEXT -#endif -#ifndef GL_EXT_secondary_color -#define GL_EXT_secondary_color 1 -GLAPI int GLAD_GL_EXT_secondary_color; -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BEXTPROC)(GLbyte red, GLbyte green, GLbyte blue); -GLAPI PFNGLSECONDARYCOLOR3BEXTPROC glad_glSecondaryColor3bEXT; -#define glSecondaryColor3bEXT glad_glSecondaryColor3bEXT -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVEXTPROC)(const GLbyte *v); -GLAPI PFNGLSECONDARYCOLOR3BVEXTPROC glad_glSecondaryColor3bvEXT; -#define glSecondaryColor3bvEXT glad_glSecondaryColor3bvEXT -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DEXTPROC)(GLdouble red, GLdouble green, GLdouble blue); -GLAPI PFNGLSECONDARYCOLOR3DEXTPROC glad_glSecondaryColor3dEXT; -#define glSecondaryColor3dEXT glad_glSecondaryColor3dEXT -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVEXTPROC)(const GLdouble *v); -GLAPI PFNGLSECONDARYCOLOR3DVEXTPROC glad_glSecondaryColor3dvEXT; -#define glSecondaryColor3dvEXT glad_glSecondaryColor3dvEXT -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FEXTPROC)(GLfloat red, GLfloat green, GLfloat blue); -GLAPI PFNGLSECONDARYCOLOR3FEXTPROC glad_glSecondaryColor3fEXT; -#define glSecondaryColor3fEXT glad_glSecondaryColor3fEXT -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVEXTPROC)(const GLfloat *v); -GLAPI PFNGLSECONDARYCOLOR3FVEXTPROC glad_glSecondaryColor3fvEXT; -#define glSecondaryColor3fvEXT glad_glSecondaryColor3fvEXT -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IEXTPROC)(GLint red, GLint green, GLint blue); -GLAPI PFNGLSECONDARYCOLOR3IEXTPROC glad_glSecondaryColor3iEXT; -#define glSecondaryColor3iEXT glad_glSecondaryColor3iEXT -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVEXTPROC)(const GLint *v); -GLAPI PFNGLSECONDARYCOLOR3IVEXTPROC glad_glSecondaryColor3ivEXT; -#define glSecondaryColor3ivEXT glad_glSecondaryColor3ivEXT -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SEXTPROC)(GLshort red, GLshort green, GLshort blue); -GLAPI PFNGLSECONDARYCOLOR3SEXTPROC glad_glSecondaryColor3sEXT; -#define glSecondaryColor3sEXT glad_glSecondaryColor3sEXT -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVEXTPROC)(const GLshort *v); -GLAPI PFNGLSECONDARYCOLOR3SVEXTPROC glad_glSecondaryColor3svEXT; -#define glSecondaryColor3svEXT glad_glSecondaryColor3svEXT -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBEXTPROC)(GLubyte red, GLubyte green, GLubyte blue); -GLAPI PFNGLSECONDARYCOLOR3UBEXTPROC glad_glSecondaryColor3ubEXT; -#define glSecondaryColor3ubEXT glad_glSecondaryColor3ubEXT -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVEXTPROC)(const GLubyte *v); -GLAPI PFNGLSECONDARYCOLOR3UBVEXTPROC glad_glSecondaryColor3ubvEXT; -#define glSecondaryColor3ubvEXT glad_glSecondaryColor3ubvEXT -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIEXTPROC)(GLuint red, GLuint green, GLuint blue); -GLAPI PFNGLSECONDARYCOLOR3UIEXTPROC glad_glSecondaryColor3uiEXT; -#define glSecondaryColor3uiEXT glad_glSecondaryColor3uiEXT -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVEXTPROC)(const GLuint *v); -GLAPI PFNGLSECONDARYCOLOR3UIVEXTPROC glad_glSecondaryColor3uivEXT; -#define glSecondaryColor3uivEXT glad_glSecondaryColor3uivEXT -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USEXTPROC)(GLushort red, GLushort green, GLushort blue); -GLAPI PFNGLSECONDARYCOLOR3USEXTPROC glad_glSecondaryColor3usEXT; -#define glSecondaryColor3usEXT glad_glSecondaryColor3usEXT -typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVEXTPROC)(const GLushort *v); -GLAPI PFNGLSECONDARYCOLOR3USVEXTPROC glad_glSecondaryColor3usvEXT; -#define glSecondaryColor3usvEXT glad_glSecondaryColor3usvEXT -typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTEREXTPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); -GLAPI PFNGLSECONDARYCOLORPOINTEREXTPROC glad_glSecondaryColorPointerEXT; -#define glSecondaryColorPointerEXT glad_glSecondaryColorPointerEXT -#endif -#ifndef GL_EXT_stencil_two_side -#define GL_EXT_stencil_two_side 1 -GLAPI int GLAD_GL_EXT_stencil_two_side; -typedef void (APIENTRYP PFNGLACTIVESTENCILFACEEXTPROC)(GLenum face); -GLAPI PFNGLACTIVESTENCILFACEEXTPROC glad_glActiveStencilFaceEXT; -#define glActiveStencilFaceEXT glad_glActiveStencilFaceEXT -#endif -#ifndef GL_EXT_stencil_wrap -#define GL_EXT_stencil_wrap 1 -GLAPI int GLAD_GL_EXT_stencil_wrap; -#endif -#ifndef GL_EXT_texture_array -#define GL_EXT_texture_array 1 -GLAPI int GLAD_GL_EXT_texture_array; -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYEREXTPROC)(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); -GLAPI PFNGLFRAMEBUFFERTEXTURELAYEREXTPROC glad_glFramebufferTextureLayerEXT; -#define glFramebufferTextureLayerEXT glad_glFramebufferTextureLayerEXT -#endif -#ifndef GL_EXT_texture_compression_s3tc -#define GL_EXT_texture_compression_s3tc 1 -GLAPI int GLAD_GL_EXT_texture_compression_s3tc; -#endif -#ifndef GL_EXT_texture_filter_anisotropic -#define GL_EXT_texture_filter_anisotropic 1 -GLAPI int GLAD_GL_EXT_texture_filter_anisotropic; -#endif -#ifndef GL_EXT_texture_lod_bias -#define GL_EXT_texture_lod_bias 1 -GLAPI int GLAD_GL_EXT_texture_lod_bias; -#endif -#ifndef GL_EXT_texture_sRGB -#define GL_EXT_texture_sRGB 1 -GLAPI int GLAD_GL_EXT_texture_sRGB; -#endif -#ifndef GL_GREMEDY_string_marker -#define GL_GREMEDY_string_marker 1 -GLAPI int GLAD_GL_GREMEDY_string_marker; -typedef void (APIENTRYP PFNGLSTRINGMARKERGREMEDYPROC)(GLsizei len, const void *string); -GLAPI PFNGLSTRINGMARKERGREMEDYPROC glad_glStringMarkerGREMEDY; -#define glStringMarkerGREMEDY glad_glStringMarkerGREMEDY -#endif -#ifndef GL_NV_fragment_program2 -#define GL_NV_fragment_program2 1 -GLAPI int GLAD_GL_NV_fragment_program2; -#endif -#ifndef GL_NV_fragment_program_option -#define GL_NV_fragment_program_option 1 -GLAPI int GLAD_GL_NV_fragment_program_option; -#endif -#ifndef GL_NV_geometry_program4 -#define GL_NV_geometry_program4 1 -GLAPI int GLAD_GL_NV_geometry_program4; -typedef void (APIENTRYP PFNGLPROGRAMVERTEXLIMITNVPROC)(GLenum target, GLint limit); -GLAPI PFNGLPROGRAMVERTEXLIMITNVPROC glad_glProgramVertexLimitNV; -#define glProgramVertexLimitNV glad_glProgramVertexLimitNV -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREEXTPROC)(GLenum target, GLenum attachment, GLuint texture, GLint level); -GLAPI PFNGLFRAMEBUFFERTEXTUREEXTPROC glad_glFramebufferTextureEXT; -#define glFramebufferTextureEXT glad_glFramebufferTextureEXT -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREFACEEXTPROC)(GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face); -GLAPI PFNGLFRAMEBUFFERTEXTUREFACEEXTPROC glad_glFramebufferTextureFaceEXT; -#define glFramebufferTextureFaceEXT glad_glFramebufferTextureFaceEXT -#endif -#ifndef GL_NV_gpu_program4 -#define GL_NV_gpu_program4 1 -GLAPI int GLAD_GL_NV_gpu_program4; -typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4INVPROC)(GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); -GLAPI PFNGLPROGRAMLOCALPARAMETERI4INVPROC glad_glProgramLocalParameterI4iNV; -#define glProgramLocalParameterI4iNV glad_glProgramLocalParameterI4iNV -typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4IVNVPROC)(GLenum target, GLuint index, const GLint *params); -GLAPI PFNGLPROGRAMLOCALPARAMETERI4IVNVPROC glad_glProgramLocalParameterI4ivNV; -#define glProgramLocalParameterI4ivNV glad_glProgramLocalParameterI4ivNV -typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERSI4IVNVPROC)(GLenum target, GLuint index, GLsizei count, const GLint *params); -GLAPI PFNGLPROGRAMLOCALPARAMETERSI4IVNVPROC glad_glProgramLocalParametersI4ivNV; -#define glProgramLocalParametersI4ivNV glad_glProgramLocalParametersI4ivNV -typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4UINVPROC)(GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); -GLAPI PFNGLPROGRAMLOCALPARAMETERI4UINVPROC glad_glProgramLocalParameterI4uiNV; -#define glProgramLocalParameterI4uiNV glad_glProgramLocalParameterI4uiNV -typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4UIVNVPROC)(GLenum target, GLuint index, const GLuint *params); -GLAPI PFNGLPROGRAMLOCALPARAMETERI4UIVNVPROC glad_glProgramLocalParameterI4uivNV; -#define glProgramLocalParameterI4uivNV glad_glProgramLocalParameterI4uivNV -typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERSI4UIVNVPROC)(GLenum target, GLuint index, GLsizei count, const GLuint *params); -GLAPI PFNGLPROGRAMLOCALPARAMETERSI4UIVNVPROC glad_glProgramLocalParametersI4uivNV; -#define glProgramLocalParametersI4uivNV glad_glProgramLocalParametersI4uivNV -typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4INVPROC)(GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); -GLAPI PFNGLPROGRAMENVPARAMETERI4INVPROC glad_glProgramEnvParameterI4iNV; -#define glProgramEnvParameterI4iNV glad_glProgramEnvParameterI4iNV -typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4IVNVPROC)(GLenum target, GLuint index, const GLint *params); -GLAPI PFNGLPROGRAMENVPARAMETERI4IVNVPROC glad_glProgramEnvParameterI4ivNV; -#define glProgramEnvParameterI4ivNV glad_glProgramEnvParameterI4ivNV -typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERSI4IVNVPROC)(GLenum target, GLuint index, GLsizei count, const GLint *params); -GLAPI PFNGLPROGRAMENVPARAMETERSI4IVNVPROC glad_glProgramEnvParametersI4ivNV; -#define glProgramEnvParametersI4ivNV glad_glProgramEnvParametersI4ivNV -typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4UINVPROC)(GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); -GLAPI PFNGLPROGRAMENVPARAMETERI4UINVPROC glad_glProgramEnvParameterI4uiNV; -#define glProgramEnvParameterI4uiNV glad_glProgramEnvParameterI4uiNV -typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4UIVNVPROC)(GLenum target, GLuint index, const GLuint *params); -GLAPI PFNGLPROGRAMENVPARAMETERI4UIVNVPROC glad_glProgramEnvParameterI4uivNV; -#define glProgramEnvParameterI4uivNV glad_glProgramEnvParameterI4uivNV -typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERSI4UIVNVPROC)(GLenum target, GLuint index, GLsizei count, const GLuint *params); -GLAPI PFNGLPROGRAMENVPARAMETERSI4UIVNVPROC glad_glProgramEnvParametersI4uivNV; -#define glProgramEnvParametersI4uivNV glad_glProgramEnvParametersI4uivNV -typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERIIVNVPROC)(GLenum target, GLuint index, GLint *params); -GLAPI PFNGLGETPROGRAMLOCALPARAMETERIIVNVPROC glad_glGetProgramLocalParameterIivNV; -#define glGetProgramLocalParameterIivNV glad_glGetProgramLocalParameterIivNV -typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERIUIVNVPROC)(GLenum target, GLuint index, GLuint *params); -GLAPI PFNGLGETPROGRAMLOCALPARAMETERIUIVNVPROC glad_glGetProgramLocalParameterIuivNV; -#define glGetProgramLocalParameterIuivNV glad_glGetProgramLocalParameterIuivNV -typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERIIVNVPROC)(GLenum target, GLuint index, GLint *params); -GLAPI PFNGLGETPROGRAMENVPARAMETERIIVNVPROC glad_glGetProgramEnvParameterIivNV; -#define glGetProgramEnvParameterIivNV glad_glGetProgramEnvParameterIivNV -typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERIUIVNVPROC)(GLenum target, GLuint index, GLuint *params); -GLAPI PFNGLGETPROGRAMENVPARAMETERIUIVNVPROC glad_glGetProgramEnvParameterIuivNV; -#define glGetProgramEnvParameterIuivNV glad_glGetProgramEnvParameterIuivNV -#endif -#ifndef GL_NV_register_combiners -#define GL_NV_register_combiners 1 -GLAPI int GLAD_GL_NV_register_combiners; -typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFVNVPROC)(GLenum pname, const GLfloat *params); -GLAPI PFNGLCOMBINERPARAMETERFVNVPROC glad_glCombinerParameterfvNV; -#define glCombinerParameterfvNV glad_glCombinerParameterfvNV -typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFNVPROC)(GLenum pname, GLfloat param); -GLAPI PFNGLCOMBINERPARAMETERFNVPROC glad_glCombinerParameterfNV; -#define glCombinerParameterfNV glad_glCombinerParameterfNV -typedef void (APIENTRYP PFNGLCOMBINERPARAMETERIVNVPROC)(GLenum pname, const GLint *params); -GLAPI PFNGLCOMBINERPARAMETERIVNVPROC glad_glCombinerParameterivNV; -#define glCombinerParameterivNV glad_glCombinerParameterivNV -typedef void (APIENTRYP PFNGLCOMBINERPARAMETERINVPROC)(GLenum pname, GLint param); -GLAPI PFNGLCOMBINERPARAMETERINVPROC glad_glCombinerParameteriNV; -#define glCombinerParameteriNV glad_glCombinerParameteriNV -typedef void (APIENTRYP PFNGLCOMBINERINPUTNVPROC)(GLenum stage, GLenum portion, GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage); -GLAPI PFNGLCOMBINERINPUTNVPROC glad_glCombinerInputNV; -#define glCombinerInputNV glad_glCombinerInputNV -typedef void (APIENTRYP PFNGLCOMBINEROUTPUTNVPROC)(GLenum stage, GLenum portion, GLenum abOutput, GLenum cdOutput, GLenum sumOutput, GLenum scale, GLenum bias, GLboolean abDotProduct, GLboolean cdDotProduct, GLboolean muxSum); -GLAPI PFNGLCOMBINEROUTPUTNVPROC glad_glCombinerOutputNV; -#define glCombinerOutputNV glad_glCombinerOutputNV -typedef void (APIENTRYP PFNGLFINALCOMBINERINPUTNVPROC)(GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage); -GLAPI PFNGLFINALCOMBINERINPUTNVPROC glad_glFinalCombinerInputNV; -#define glFinalCombinerInputNV glad_glFinalCombinerInputNV -typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERFVNVPROC)(GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLfloat *params); -GLAPI PFNGLGETCOMBINERINPUTPARAMETERFVNVPROC glad_glGetCombinerInputParameterfvNV; -#define glGetCombinerInputParameterfvNV glad_glGetCombinerInputParameterfvNV -typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERIVNVPROC)(GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLint *params); -GLAPI PFNGLGETCOMBINERINPUTPARAMETERIVNVPROC glad_glGetCombinerInputParameterivNV; -#define glGetCombinerInputParameterivNV glad_glGetCombinerInputParameterivNV -typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERFVNVPROC)(GLenum stage, GLenum portion, GLenum pname, GLfloat *params); -GLAPI PFNGLGETCOMBINEROUTPUTPARAMETERFVNVPROC glad_glGetCombinerOutputParameterfvNV; -#define glGetCombinerOutputParameterfvNV glad_glGetCombinerOutputParameterfvNV -typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERIVNVPROC)(GLenum stage, GLenum portion, GLenum pname, GLint *params); -GLAPI PFNGLGETCOMBINEROUTPUTPARAMETERIVNVPROC glad_glGetCombinerOutputParameterivNV; -#define glGetCombinerOutputParameterivNV glad_glGetCombinerOutputParameterivNV -typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERFVNVPROC)(GLenum variable, GLenum pname, GLfloat *params); -GLAPI PFNGLGETFINALCOMBINERINPUTPARAMETERFVNVPROC glad_glGetFinalCombinerInputParameterfvNV; -#define glGetFinalCombinerInputParameterfvNV glad_glGetFinalCombinerInputParameterfvNV -typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC)(GLenum variable, GLenum pname, GLint *params); -GLAPI PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC glad_glGetFinalCombinerInputParameterivNV; -#define glGetFinalCombinerInputParameterivNV glad_glGetFinalCombinerInputParameterivNV -#endif -#ifndef GL_NV_register_combiners2 -#define GL_NV_register_combiners2 1 -GLAPI int GLAD_GL_NV_register_combiners2; -typedef void (APIENTRYP PFNGLCOMBINERSTAGEPARAMETERFVNVPROC)(GLenum stage, GLenum pname, const GLfloat *params); -GLAPI PFNGLCOMBINERSTAGEPARAMETERFVNVPROC glad_glCombinerStageParameterfvNV; -#define glCombinerStageParameterfvNV glad_glCombinerStageParameterfvNV -typedef void (APIENTRYP PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC)(GLenum stage, GLenum pname, GLfloat *params); -GLAPI PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC glad_glGetCombinerStageParameterfvNV; -#define glGetCombinerStageParameterfvNV glad_glGetCombinerStageParameterfvNV -#endif -#ifndef GL_NV_texture_compression_vtc -#define GL_NV_texture_compression_vtc 1 -GLAPI int GLAD_GL_NV_texture_compression_vtc; -#endif -#ifndef GL_NV_texture_shader -#define GL_NV_texture_shader 1 -GLAPI int GLAD_GL_NV_texture_shader; -#endif -#ifndef GL_NV_transform_feedback -#define GL_NV_transform_feedback 1 -GLAPI int GLAD_GL_NV_transform_feedback; -typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKNVPROC)(GLenum primitiveMode); -GLAPI PFNGLBEGINTRANSFORMFEEDBACKNVPROC glad_glBeginTransformFeedbackNV; -#define glBeginTransformFeedbackNV glad_glBeginTransformFeedbackNV -typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKNVPROC)(void); -GLAPI PFNGLENDTRANSFORMFEEDBACKNVPROC glad_glEndTransformFeedbackNV; -#define glEndTransformFeedbackNV glad_glEndTransformFeedbackNV -typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKATTRIBSNVPROC)(GLsizei count, const GLint *attribs, GLenum bufferMode); -GLAPI PFNGLTRANSFORMFEEDBACKATTRIBSNVPROC glad_glTransformFeedbackAttribsNV; -#define glTransformFeedbackAttribsNV glad_glTransformFeedbackAttribsNV -typedef void (APIENTRYP PFNGLBINDBUFFERRANGENVPROC)(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); -GLAPI PFNGLBINDBUFFERRANGENVPROC glad_glBindBufferRangeNV; -#define glBindBufferRangeNV glad_glBindBufferRangeNV -typedef void (APIENTRYP PFNGLBINDBUFFEROFFSETNVPROC)(GLenum target, GLuint index, GLuint buffer, GLintptr offset); -GLAPI PFNGLBINDBUFFEROFFSETNVPROC glad_glBindBufferOffsetNV; -#define glBindBufferOffsetNV glad_glBindBufferOffsetNV -typedef void (APIENTRYP PFNGLBINDBUFFERBASENVPROC)(GLenum target, GLuint index, GLuint buffer); -GLAPI PFNGLBINDBUFFERBASENVPROC glad_glBindBufferBaseNV; -#define glBindBufferBaseNV glad_glBindBufferBaseNV -typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSNVPROC)(GLuint program, GLsizei count, const GLint *locations, GLenum bufferMode); -GLAPI PFNGLTRANSFORMFEEDBACKVARYINGSNVPROC glad_glTransformFeedbackVaryingsNV; -#define glTransformFeedbackVaryingsNV glad_glTransformFeedbackVaryingsNV -typedef void (APIENTRYP PFNGLACTIVEVARYINGNVPROC)(GLuint program, const GLchar *name); -GLAPI PFNGLACTIVEVARYINGNVPROC glad_glActiveVaryingNV; -#define glActiveVaryingNV glad_glActiveVaryingNV -typedef GLint (APIENTRYP PFNGLGETVARYINGLOCATIONNVPROC)(GLuint program, const GLchar *name); -GLAPI PFNGLGETVARYINGLOCATIONNVPROC glad_glGetVaryingLocationNV; -#define glGetVaryingLocationNV glad_glGetVaryingLocationNV -typedef void (APIENTRYP PFNGLGETACTIVEVARYINGNVPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); -GLAPI PFNGLGETACTIVEVARYINGNVPROC glad_glGetActiveVaryingNV; -#define glGetActiveVaryingNV glad_glGetActiveVaryingNV -typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGNVPROC)(GLuint program, GLuint index, GLint *location); -GLAPI PFNGLGETTRANSFORMFEEDBACKVARYINGNVPROC glad_glGetTransformFeedbackVaryingNV; -#define glGetTransformFeedbackVaryingNV glad_glGetTransformFeedbackVaryingNV -typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKSTREAMATTRIBSNVPROC)(GLsizei count, const GLint *attribs, GLsizei nbuffers, const GLint *bufstreams, GLenum bufferMode); -GLAPI PFNGLTRANSFORMFEEDBACKSTREAMATTRIBSNVPROC glad_glTransformFeedbackStreamAttribsNV; -#define glTransformFeedbackStreamAttribsNV glad_glTransformFeedbackStreamAttribsNV -#endif -#ifndef GL_NV_vertex_program -#define GL_NV_vertex_program 1 -GLAPI int GLAD_GL_NV_vertex_program; -typedef GLboolean (APIENTRYP PFNGLAREPROGRAMSRESIDENTNVPROC)(GLsizei n, const GLuint *programs, GLboolean *residences); -GLAPI PFNGLAREPROGRAMSRESIDENTNVPROC glad_glAreProgramsResidentNV; -#define glAreProgramsResidentNV glad_glAreProgramsResidentNV -typedef void (APIENTRYP PFNGLBINDPROGRAMNVPROC)(GLenum target, GLuint id); -GLAPI PFNGLBINDPROGRAMNVPROC glad_glBindProgramNV; -#define glBindProgramNV glad_glBindProgramNV -typedef void (APIENTRYP PFNGLDELETEPROGRAMSNVPROC)(GLsizei n, const GLuint *programs); -GLAPI PFNGLDELETEPROGRAMSNVPROC glad_glDeleteProgramsNV; -#define glDeleteProgramsNV glad_glDeleteProgramsNV -typedef void (APIENTRYP PFNGLEXECUTEPROGRAMNVPROC)(GLenum target, GLuint id, const GLfloat *params); -GLAPI PFNGLEXECUTEPROGRAMNVPROC glad_glExecuteProgramNV; -#define glExecuteProgramNV glad_glExecuteProgramNV -typedef void (APIENTRYP PFNGLGENPROGRAMSNVPROC)(GLsizei n, GLuint *programs); -GLAPI PFNGLGENPROGRAMSNVPROC glad_glGenProgramsNV; -#define glGenProgramsNV glad_glGenProgramsNV -typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERDVNVPROC)(GLenum target, GLuint index, GLenum pname, GLdouble *params); -GLAPI PFNGLGETPROGRAMPARAMETERDVNVPROC glad_glGetProgramParameterdvNV; -#define glGetProgramParameterdvNV glad_glGetProgramParameterdvNV -typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERFVNVPROC)(GLenum target, GLuint index, GLenum pname, GLfloat *params); -GLAPI PFNGLGETPROGRAMPARAMETERFVNVPROC glad_glGetProgramParameterfvNV; -#define glGetProgramParameterfvNV glad_glGetProgramParameterfvNV -typedef void (APIENTRYP PFNGLGETPROGRAMIVNVPROC)(GLuint id, GLenum pname, GLint *params); -GLAPI PFNGLGETPROGRAMIVNVPROC glad_glGetProgramivNV; -#define glGetProgramivNV glad_glGetProgramivNV -typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGNVPROC)(GLuint id, GLenum pname, GLubyte *program); -GLAPI PFNGLGETPROGRAMSTRINGNVPROC glad_glGetProgramStringNV; -#define glGetProgramStringNV glad_glGetProgramStringNV -typedef void (APIENTRYP PFNGLGETTRACKMATRIXIVNVPROC)(GLenum target, GLuint address, GLenum pname, GLint *params); -GLAPI PFNGLGETTRACKMATRIXIVNVPROC glad_glGetTrackMatrixivNV; -#define glGetTrackMatrixivNV glad_glGetTrackMatrixivNV -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVNVPROC)(GLuint index, GLenum pname, GLdouble *params); -GLAPI PFNGLGETVERTEXATTRIBDVNVPROC glad_glGetVertexAttribdvNV; -#define glGetVertexAttribdvNV glad_glGetVertexAttribdvNV -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVNVPROC)(GLuint index, GLenum pname, GLfloat *params); -GLAPI PFNGLGETVERTEXATTRIBFVNVPROC glad_glGetVertexAttribfvNV; -#define glGetVertexAttribfvNV glad_glGetVertexAttribfvNV -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVNVPROC)(GLuint index, GLenum pname, GLint *params); -GLAPI PFNGLGETVERTEXATTRIBIVNVPROC glad_glGetVertexAttribivNV; -#define glGetVertexAttribivNV glad_glGetVertexAttribivNV -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVNVPROC)(GLuint index, GLenum pname, void **pointer); -GLAPI PFNGLGETVERTEXATTRIBPOINTERVNVPROC glad_glGetVertexAttribPointervNV; -#define glGetVertexAttribPointervNV glad_glGetVertexAttribPointervNV -typedef GLboolean (APIENTRYP PFNGLISPROGRAMNVPROC)(GLuint id); -GLAPI PFNGLISPROGRAMNVPROC glad_glIsProgramNV; -#define glIsProgramNV glad_glIsProgramNV -typedef void (APIENTRYP PFNGLLOADPROGRAMNVPROC)(GLenum target, GLuint id, GLsizei len, const GLubyte *program); -GLAPI PFNGLLOADPROGRAMNVPROC glad_glLoadProgramNV; -#define glLoadProgramNV glad_glLoadProgramNV -typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DNVPROC)(GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); -GLAPI PFNGLPROGRAMPARAMETER4DNVPROC glad_glProgramParameter4dNV; -#define glProgramParameter4dNV glad_glProgramParameter4dNV -typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DVNVPROC)(GLenum target, GLuint index, const GLdouble *v); -GLAPI PFNGLPROGRAMPARAMETER4DVNVPROC glad_glProgramParameter4dvNV; -#define glProgramParameter4dvNV glad_glProgramParameter4dvNV -typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FNVPROC)(GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); -GLAPI PFNGLPROGRAMPARAMETER4FNVPROC glad_glProgramParameter4fNV; -#define glProgramParameter4fNV glad_glProgramParameter4fNV -typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FVNVPROC)(GLenum target, GLuint index, const GLfloat *v); -GLAPI PFNGLPROGRAMPARAMETER4FVNVPROC glad_glProgramParameter4fvNV; -#define glProgramParameter4fvNV glad_glProgramParameter4fvNV -typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4DVNVPROC)(GLenum target, GLuint index, GLsizei count, const GLdouble *v); -GLAPI PFNGLPROGRAMPARAMETERS4DVNVPROC glad_glProgramParameters4dvNV; -#define glProgramParameters4dvNV glad_glProgramParameters4dvNV -typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4FVNVPROC)(GLenum target, GLuint index, GLsizei count, const GLfloat *v); -GLAPI PFNGLPROGRAMPARAMETERS4FVNVPROC glad_glProgramParameters4fvNV; -#define glProgramParameters4fvNV glad_glProgramParameters4fvNV -typedef void (APIENTRYP PFNGLREQUESTRESIDENTPROGRAMSNVPROC)(GLsizei n, const GLuint *programs); -GLAPI PFNGLREQUESTRESIDENTPROGRAMSNVPROC glad_glRequestResidentProgramsNV; -#define glRequestResidentProgramsNV glad_glRequestResidentProgramsNV -typedef void (APIENTRYP PFNGLTRACKMATRIXNVPROC)(GLenum target, GLuint address, GLenum matrix, GLenum transform); -GLAPI PFNGLTRACKMATRIXNVPROC glad_glTrackMatrixNV; -#define glTrackMatrixNV glad_glTrackMatrixNV -typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERNVPROC)(GLuint index, GLint fsize, GLenum type, GLsizei stride, const void *pointer); -GLAPI PFNGLVERTEXATTRIBPOINTERNVPROC glad_glVertexAttribPointerNV; -#define glVertexAttribPointerNV glad_glVertexAttribPointerNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB1DNVPROC)(GLuint index, GLdouble x); -GLAPI PFNGLVERTEXATTRIB1DNVPROC glad_glVertexAttrib1dNV; -#define glVertexAttrib1dNV glad_glVertexAttrib1dNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVNVPROC)(GLuint index, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIB1DVNVPROC glad_glVertexAttrib1dvNV; -#define glVertexAttrib1dvNV glad_glVertexAttrib1dvNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB1FNVPROC)(GLuint index, GLfloat x); -GLAPI PFNGLVERTEXATTRIB1FNVPROC glad_glVertexAttrib1fNV; -#define glVertexAttrib1fNV glad_glVertexAttrib1fNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVNVPROC)(GLuint index, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIB1FVNVPROC glad_glVertexAttrib1fvNV; -#define glVertexAttrib1fvNV glad_glVertexAttrib1fvNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB1SNVPROC)(GLuint index, GLshort x); -GLAPI PFNGLVERTEXATTRIB1SNVPROC glad_glVertexAttrib1sNV; -#define glVertexAttrib1sNV glad_glVertexAttrib1sNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVNVPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIB1SVNVPROC glad_glVertexAttrib1svNV; -#define glVertexAttrib1svNV glad_glVertexAttrib1svNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB2DNVPROC)(GLuint index, GLdouble x, GLdouble y); -GLAPI PFNGLVERTEXATTRIB2DNVPROC glad_glVertexAttrib2dNV; -#define glVertexAttrib2dNV glad_glVertexAttrib2dNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVNVPROC)(GLuint index, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIB2DVNVPROC glad_glVertexAttrib2dvNV; -#define glVertexAttrib2dvNV glad_glVertexAttrib2dvNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB2FNVPROC)(GLuint index, GLfloat x, GLfloat y); -GLAPI PFNGLVERTEXATTRIB2FNVPROC glad_glVertexAttrib2fNV; -#define glVertexAttrib2fNV glad_glVertexAttrib2fNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVNVPROC)(GLuint index, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIB2FVNVPROC glad_glVertexAttrib2fvNV; -#define glVertexAttrib2fvNV glad_glVertexAttrib2fvNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB2SNVPROC)(GLuint index, GLshort x, GLshort y); -GLAPI PFNGLVERTEXATTRIB2SNVPROC glad_glVertexAttrib2sNV; -#define glVertexAttrib2sNV glad_glVertexAttrib2sNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVNVPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIB2SVNVPROC glad_glVertexAttrib2svNV; -#define glVertexAttrib2svNV glad_glVertexAttrib2svNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB3DNVPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z); -GLAPI PFNGLVERTEXATTRIB3DNVPROC glad_glVertexAttrib3dNV; -#define glVertexAttrib3dNV glad_glVertexAttrib3dNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVNVPROC)(GLuint index, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIB3DVNVPROC glad_glVertexAttrib3dvNV; -#define glVertexAttrib3dvNV glad_glVertexAttrib3dvNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB3FNVPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z); -GLAPI PFNGLVERTEXATTRIB3FNVPROC glad_glVertexAttrib3fNV; -#define glVertexAttrib3fNV glad_glVertexAttrib3fNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVNVPROC)(GLuint index, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIB3FVNVPROC glad_glVertexAttrib3fvNV; -#define glVertexAttrib3fvNV glad_glVertexAttrib3fvNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB3SNVPROC)(GLuint index, GLshort x, GLshort y, GLshort z); -GLAPI PFNGLVERTEXATTRIB3SNVPROC glad_glVertexAttrib3sNV; -#define glVertexAttrib3sNV glad_glVertexAttrib3sNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVNVPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIB3SVNVPROC glad_glVertexAttrib3svNV; -#define glVertexAttrib3svNV glad_glVertexAttrib3svNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB4DNVPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); -GLAPI PFNGLVERTEXATTRIB4DNVPROC glad_glVertexAttrib4dNV; -#define glVertexAttrib4dNV glad_glVertexAttrib4dNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVNVPROC)(GLuint index, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIB4DVNVPROC glad_glVertexAttrib4dvNV; -#define glVertexAttrib4dvNV glad_glVertexAttrib4dvNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB4FNVPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); -GLAPI PFNGLVERTEXATTRIB4FNVPROC glad_glVertexAttrib4fNV; -#define glVertexAttrib4fNV glad_glVertexAttrib4fNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVNVPROC)(GLuint index, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIB4FVNVPROC glad_glVertexAttrib4fvNV; -#define glVertexAttrib4fvNV glad_glVertexAttrib4fvNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB4SNVPROC)(GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); -GLAPI PFNGLVERTEXATTRIB4SNVPROC glad_glVertexAttrib4sNV; -#define glVertexAttrib4sNV glad_glVertexAttrib4sNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVNVPROC)(GLuint index, const GLshort *v); -GLAPI PFNGLVERTEXATTRIB4SVNVPROC glad_glVertexAttrib4svNV; -#define glVertexAttrib4svNV glad_glVertexAttrib4svNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBNVPROC)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); -GLAPI PFNGLVERTEXATTRIB4UBNVPROC glad_glVertexAttrib4ubNV; -#define glVertexAttrib4ubNV glad_glVertexAttrib4ubNV -typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVNVPROC)(GLuint index, const GLubyte *v); -GLAPI PFNGLVERTEXATTRIB4UBVNVPROC glad_glVertexAttrib4ubvNV; -#define glVertexAttrib4ubvNV glad_glVertexAttrib4ubvNV -typedef void (APIENTRYP PFNGLVERTEXATTRIBS1DVNVPROC)(GLuint index, GLsizei count, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIBS1DVNVPROC glad_glVertexAttribs1dvNV; -#define glVertexAttribs1dvNV glad_glVertexAttribs1dvNV -typedef void (APIENTRYP PFNGLVERTEXATTRIBS1FVNVPROC)(GLuint index, GLsizei count, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIBS1FVNVPROC glad_glVertexAttribs1fvNV; -#define glVertexAttribs1fvNV glad_glVertexAttribs1fvNV -typedef void (APIENTRYP PFNGLVERTEXATTRIBS1SVNVPROC)(GLuint index, GLsizei count, const GLshort *v); -GLAPI PFNGLVERTEXATTRIBS1SVNVPROC glad_glVertexAttribs1svNV; -#define glVertexAttribs1svNV glad_glVertexAttribs1svNV -typedef void (APIENTRYP PFNGLVERTEXATTRIBS2DVNVPROC)(GLuint index, GLsizei count, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIBS2DVNVPROC glad_glVertexAttribs2dvNV; -#define glVertexAttribs2dvNV glad_glVertexAttribs2dvNV -typedef void (APIENTRYP PFNGLVERTEXATTRIBS2FVNVPROC)(GLuint index, GLsizei count, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIBS2FVNVPROC glad_glVertexAttribs2fvNV; -#define glVertexAttribs2fvNV glad_glVertexAttribs2fvNV -typedef void (APIENTRYP PFNGLVERTEXATTRIBS2SVNVPROC)(GLuint index, GLsizei count, const GLshort *v); -GLAPI PFNGLVERTEXATTRIBS2SVNVPROC glad_glVertexAttribs2svNV; -#define glVertexAttribs2svNV glad_glVertexAttribs2svNV -typedef void (APIENTRYP PFNGLVERTEXATTRIBS3DVNVPROC)(GLuint index, GLsizei count, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIBS3DVNVPROC glad_glVertexAttribs3dvNV; -#define glVertexAttribs3dvNV glad_glVertexAttribs3dvNV -typedef void (APIENTRYP PFNGLVERTEXATTRIBS3FVNVPROC)(GLuint index, GLsizei count, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIBS3FVNVPROC glad_glVertexAttribs3fvNV; -#define glVertexAttribs3fvNV glad_glVertexAttribs3fvNV -typedef void (APIENTRYP PFNGLVERTEXATTRIBS3SVNVPROC)(GLuint index, GLsizei count, const GLshort *v); -GLAPI PFNGLVERTEXATTRIBS3SVNVPROC glad_glVertexAttribs3svNV; -#define glVertexAttribs3svNV glad_glVertexAttribs3svNV -typedef void (APIENTRYP PFNGLVERTEXATTRIBS4DVNVPROC)(GLuint index, GLsizei count, const GLdouble *v); -GLAPI PFNGLVERTEXATTRIBS4DVNVPROC glad_glVertexAttribs4dvNV; -#define glVertexAttribs4dvNV glad_glVertexAttribs4dvNV -typedef void (APIENTRYP PFNGLVERTEXATTRIBS4FVNVPROC)(GLuint index, GLsizei count, const GLfloat *v); -GLAPI PFNGLVERTEXATTRIBS4FVNVPROC glad_glVertexAttribs4fvNV; -#define glVertexAttribs4fvNV glad_glVertexAttribs4fvNV -typedef void (APIENTRYP PFNGLVERTEXATTRIBS4SVNVPROC)(GLuint index, GLsizei count, const GLshort *v); -GLAPI PFNGLVERTEXATTRIBS4SVNVPROC glad_glVertexAttribs4svNV; -#define glVertexAttribs4svNV glad_glVertexAttribs4svNV -typedef void (APIENTRYP PFNGLVERTEXATTRIBS4UBVNVPROC)(GLuint index, GLsizei count, const GLubyte *v); -GLAPI PFNGLVERTEXATTRIBS4UBVNVPROC glad_glVertexAttribs4ubvNV; -#define glVertexAttribs4ubvNV glad_glVertexAttribs4ubvNV -#endif -#ifndef GL_NV_vertex_program2_option -#define GL_NV_vertex_program2_option 1 -GLAPI int GLAD_GL_NV_vertex_program2_option; -#endif -#ifndef GL_NV_vertex_program3 -#define GL_NV_vertex_program3 1 -GLAPI int GLAD_GL_NV_vertex_program3; -#endif - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/RenderSystems/GL/src/GLSL/include/OgreGLSLExtSupport.h b/RenderSystems/GL/src/GLSL/include/OgreGLSLExtSupport.h deleted file mode 100644 index 2744039a4f6..00000000000 --- a/RenderSystems/GL/src/GLSL/include/OgreGLSLExtSupport.h +++ /dev/null @@ -1,67 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - - - -#ifndef __GLSLExtSupport_H__ -#define __GLSLExtSupport_H__ - -#include "OgreGLPrerequisites.h" - -// -// OpenGL Shading Language entry points -// -namespace Ogre -{ - namespace GLSL { - - // forward declarations - class GLSLProgram; - class GLSLGpuProgram; - class GLSLLinkProgram; - class GLSLLinkProgramManager; - class GLSLProgramFactory; - - - /** Check for GL errors and report them in the Ogre Log. - */ - void reportGLSLError(GLenum glErr, const String& ogreMethod, const String& errorTextPrefix, const uint obj, const bool forceInfoLog = false, const bool forceException = false); - - /** if there is a message in GL info log then post it in the Ogre Log - @param msg the info log message string is appended to this string - @param obj the GL object that is used to retrieve the info log - */ - String logObjectInfo(const String& msg, uint obj); - - /// just return the info without logging it - String getObjectInfo(GLuint obj); - - } -} // namespace Ogre - -#endif // __GLSLExtSupport_H__ diff --git a/RenderSystems/GL/src/GLSL/include/OgreGLSLLinkProgram.h b/RenderSystems/GL/src/GLSL/include/OgreGLSLLinkProgram.h deleted file mode 100644 index cd998864cd9..00000000000 --- a/RenderSystems/GL/src/GLSL/include/OgreGLSLLinkProgram.h +++ /dev/null @@ -1,86 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLSLLinkProgram_H__ -#define __GLSLLinkProgram_H__ - -#include "OgreGLPrerequisites.h" -#include "OgreGpuProgram.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreGLUniformCache.h" -#include "OgreGLSLProgramCommon.h" - -namespace Ogre { - namespace GLSL { - - /** C++ encapsulation of GLSL Program Object - - */ - - class _OgreGLExport GLSLLinkProgram : public GLSLProgramCommon - { - private: - GLUniformCache *mUniformCache; - - /// Build uniform references from active named uniforms - void buildGLUniformReferences(void); - /// Extract attributes - void extractAttributes(void); - - typedef std::set AttributeSet; - /// Custom attribute bindings - AttributeSet mValidAttributes; - - /// Compiles and links the the vertex and fragment programs - void compileAndLink() override; - /// Get the the binary data of a program from the microcode cache - void getMicrocodeFromCache(uint32 id); - public: - /// Constructor should only be used by GLSLLinkProgramManager - explicit GLSLLinkProgram(const GLShaderList& shaders); - ~GLSLLinkProgram(void); - - /** Makes a program object active by making sure it is linked and then putting it in use. - - */ - void activate(void) override; - - bool isAttributeValid(VertexElementSemantic semantic, uint index); - - /** Updates program object uniforms using data from GpuProgramParameters. - normally called by GLSLGpuProgram::bindParameters() just before rendering occurs. - */ - void updateUniforms(GpuProgramParametersSharedPtr params, uint16 mask, GpuProgramType fromProgType) override; - - /// Get the GL Handle for the program object - uint getGLHandle(void) const { return mGLProgramHandle; } - }; - - } -} - -#endif // __GLSLLinkProgram_H__ diff --git a/RenderSystems/GL/src/GLSL/include/OgreGLSLLinkProgramManager.h b/RenderSystems/GL/src/GLSL/include/OgreGLSLLinkProgramManager.h deleted file mode 100644 index 5459d2dc6e0..00000000000 --- a/RenderSystems/GL/src/GLSL/include/OgreGLSLLinkProgramManager.h +++ /dev/null @@ -1,82 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLSLLinkProgramManager_H__ -#define __GLSLLinkProgramManager_H__ - -#include "OgreGLPrerequisites.h" -#include "OgreSingleton.h" -#include "OgreGLSLProgramManagerCommon.h" -#include "OgreGLSLExtSupport.h" -#include "OgreGLSLLinkProgram.h" - -namespace Ogre { - - namespace GLSL { - - class _OgreGLExport GLSLLinkProgramManager : public Singleton, public GLSLProgramManagerCommon - { - public: - - GLSLLinkProgramManager(void); - ~GLSLLinkProgramManager(void); - - /** - Get the program object that links the two active shader objects together - if a program object was not already created and linked a new one is created and linked - */ - GLSLLinkProgram* getActiveLinkProgram(void); - - /** Populate a list of uniforms based on a program object. - @param programObject Handle to the program object to query - @param vertexConstantDefs Definition of the constants extracted from the - vertex program, used to match up physical buffer indexes with program - uniforms. May be null if there is no vertex program. - @param geometryConstantDefs Definition of the constants extracted from the - geometry program, used to match up physical buffer indexes with program - uniforms. May be null if there is no geometry program. - @param fragmentConstantDefs Definition of the constants extracted from the - fragment program, used to match up physical buffer indexes with program - uniforms. May be null if there is no fragment program. - @param list The list to populate (will not be cleared before adding, clear - it yourself before calling this if that's what you want). - */ - static void extractUniforms(uint programObject, - const GpuConstantDefinitionMap* vertexConstantDefs, - const GpuConstantDefinitionMap* geometryConstantDefs, - const GpuConstantDefinitionMap* fragmentConstantDefs, - GLUniformReferenceList& list); - - static GLSLLinkProgramManager& getSingleton(void); - static GLSLLinkProgramManager* getSingletonPtr(void); - - }; - - } -} - -#endif // __GLSLLinkProgramManager_H__ diff --git a/RenderSystems/GL/src/GLSL/include/OgreGLSLProgram.h b/RenderSystems/GL/src/GLSL/include/OgreGLSLProgram.h deleted file mode 100644 index 66d24b12ae1..00000000000 --- a/RenderSystems/GL/src/GLSL/include/OgreGLSLProgram.h +++ /dev/null @@ -1,125 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLSLProgram_H__ -#define __GLSLProgram_H__ - -#include "OgreGLPrerequisites.h" -#include "OgreGLSLShaderCommon.h" -#include "OgreRenderOperation.h" -#include "OgreGLGpuProgram.h" - -namespace Ogre { - namespace GLSL { - class _OgreGLExport GLSLProgram : public GLSLShaderCommon, public GLGpuProgramBase - { - public: - GLSLProgram(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader); - ~GLSLProgram(); - - void attachToProgramObject( const uint programObject ) override; - void detachFromProgramObject( const uint programObject ) override; - - /// Overridden from GpuProgram - const String& getLanguage(void) const override; - - bool getPassTransformStates(void) const override { - return mPassFFPStates; - } - bool getPassSurfaceAndLightStates(void) const override { - return mPassFFPStates; - } - bool getPassFogStates(void) const override { - return mPassFFPStates; - } - - /** Returns the operation type that this geometry program expects to - receive as input - */ - RenderOperation::OperationType getInputOperationType(void) const - { return mInputOperationType; } - /** Returns the operation type that this geometry program will emit - */ - RenderOperation::OperationType getOutputOperationType(void) const - { return mOutputOperationType; } - /** Returns the maximum number of vertices that this geometry program can - output in a single run - */ - int getMaxOutputVertices(void) const { return mMaxOutputVertices; } - - /** Sets the operation type that this geometry program expects to receive - */ - void setInputOperationType(RenderOperation::OperationType operationType) - { mInputOperationType = operationType; } - /** Set the operation type that this geometry program will emit - */ - void setOutputOperationType(RenderOperation::OperationType operationType) - { - switch (operationType) - { - case RenderOperation::OT_POINT_LIST: - case RenderOperation::OT_LINE_STRIP: - case RenderOperation::OT_TRIANGLE_STRIP: - break; - default: - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Geometry shader output operation type can only be point list," - "line strip or triangle strip"); - } - - mOutputOperationType = operationType; - } - /** Set the maximum number of vertices that a single run of this geometry program - can emit. - */ - void setMaxOutputVertices(int maxOutputVertices) - { mMaxOutputVertices = maxOutputVertices; } - - void bindProgram() override; - void unbindProgram() override; - void bindProgramParameters(GpuProgramParametersSharedPtr params, uint16 mask) override; - bool isAttributeValid(VertexElementSemantic semantic, uint index) override; - protected: - void loadFromSource() override; - /// Internal unload implementation, must be implemented by subclasses - void unloadHighLevelImpl(void) override; - - /// Populate the passed parameters with name->index map, must be overridden - void buildConstantDefinitions() override; - - // legacy GL_EXT_geometry_shader4 functionality - RenderOperation::OperationType mInputOperationType; - RenderOperation::OperationType mOutputOperationType; - int mMaxOutputVertices; - bool mPassFFPStates; - }; - } -} - -#endif // __GLSLProgram_H__ diff --git a/RenderSystems/GL/src/GLSL/include/OgreGLSLProgramFactory.h b/RenderSystems/GL/src/GLSL/include/OgreGLSLProgramFactory.h deleted file mode 100644 index a16339c99cf..00000000000 --- a/RenderSystems/GL/src/GLSL/include/OgreGLSLProgramFactory.h +++ /dev/null @@ -1,62 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - - -#ifndef __GLSLProgramFactory_H__ -#define __GLSLProgramFactory_H__ - -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreGLSLExtSupport.h" - -namespace Ogre -{ - namespace GLSL { - - /** Factory class for GLSL programs. */ - class _OgreGLExport GLSLProgramFactory : public HighLevelGpuProgramFactory - { - protected: - static String sLanguageName; - public: - GLSLProgramFactory(void); - ~GLSLProgramFactory(void); - /// Get the name of the language this factory creates programs for - const String& getLanguage(void) const override; - /// Create an instance of GLSLProgram - GpuProgram* create(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) override; - - private: - GLSLLinkProgramManager* mLinkProgramManager; - - }; - } -} - -#endif // __GLSLProgramFactory_H__ diff --git a/RenderSystems/GL/src/GLSL/src/OgreGLSLExtSupport.cpp b/RenderSystems/GL/src/GLSL/src/OgreGLSLExtSupport.cpp deleted file mode 100644 index cbb925f6b73..00000000000 --- a/RenderSystems/GL/src/GLSL/src/OgreGLSLExtSupport.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreGLSLExtSupport.h" - -namespace Ogre -{ - namespace GLSL - { - - //----------------------------------------------------------------------------- - void reportGLSLError(GLenum glErr, const String& ogreMethod, const String& errorTextPrefix, const uint obj, const bool forceInfoLog, const bool forceException) - { - bool errorsFound = false; - String msg = errorTextPrefix; - - // get all the GL errors - while (glErr != GL_NO_ERROR) - { - msg += glErrorToString(glErr); - glErr = glGetError(); - errorsFound = true; - } - - - // if errors were found then put them in the Log and raise and exception - if (errorsFound || forceInfoLog) - { - // if shader or program object then get the log message and send to the log manager - msg += logObjectInfo( msg, obj ); - - if (forceException) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, msg, ogreMethod); - } - } - } - - String logObjectInfo(const String& msg, GLuint obj) - { - String logMessage = getObjectInfo(obj); - - if (logMessage.empty()) - return msg; - - logMessage = msg + "\n" + logMessage; - - LogManager::getSingleton().logMessage(LML_CRITICAL, logMessage); - - return logMessage; - } - - //----------------------------------------------------------------------------- - String getObjectInfo(GLuint obj) - { - String logMessage; - - if (obj > 0) - { - GLint infologLength = 0; - - if(glIsProgram(obj)) - glValidateProgram(obj); - - glGetObjectParameterivARB((GLhandleARB)obj, GL_OBJECT_INFO_LOG_LENGTH_ARB, &infologLength); - - if (infologLength > 0) - { - GLint charsWritten = 0; - - GLcharARB * infoLog = new GLcharARB[infologLength]; - - glGetInfoLogARB((GLhandleARB)obj, infologLength, &charsWritten, infoLog); - logMessage = String(infoLog); - - delete [] infoLog; - } - } - - return logMessage; - - } - - } // namespace GLSL -} // namespace Ogre diff --git a/RenderSystems/GL/src/GLSL/src/OgreGLSLLinkProgram.cpp b/RenderSystems/GL/src/GLSL/src/OgreGLSLLinkProgram.cpp deleted file mode 100644 index 5404b28e532..00000000000 --- a/RenderSystems/GL/src/GLSL/src/OgreGLSLLinkProgram.cpp +++ /dev/null @@ -1,498 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLSLExtSupport.h" -#include "OgreGLSLLinkProgram.h" -#include "OgreStringConverter.h" -#include "OgreGLSLProgram.h" -#include "OgreGLSLLinkProgramManager.h" -#include "OgreException.h" -#include "OgreGpuProgramManager.h" -#include "OgreGLSLProgramCommon.h" - -namespace Ogre { - namespace GLSL { - - static GLint getGLGeometryInputPrimitiveType(RenderOperation::OperationType operationType) - { - switch (operationType) - { - case RenderOperation::OT_POINT_LIST: - return GL_POINTS; - case RenderOperation::OT_LINE_LIST: - case RenderOperation::OT_LINE_STRIP: - return GL_LINES; - case RenderOperation::OT_LINE_LIST_ADJ: - case RenderOperation::OT_LINE_STRIP_ADJ: - return GL_LINES_ADJACENCY_EXT; - case RenderOperation::OT_TRIANGLE_LIST_ADJ: - case RenderOperation::OT_TRIANGLE_STRIP_ADJ: - return GL_TRIANGLES_ADJACENCY_EXT; - default: - case RenderOperation::OT_TRIANGLE_LIST: - case RenderOperation::OT_TRIANGLE_STRIP: - case RenderOperation::OT_TRIANGLE_FAN: - return GL_TRIANGLES; - } - } - //----------------------------------------------------------------------- - static GLint getGLGeometryOutputPrimitiveType(RenderOperation::OperationType operationType) - { - switch (operationType) - { - case RenderOperation::OT_POINT_LIST: - return GL_POINTS; - case RenderOperation::OT_LINE_STRIP: - return GL_LINE_STRIP; - default: - case RenderOperation::OT_TRIANGLE_STRIP: - return GL_TRIANGLE_STRIP; - } - } - - //----------------------------------------------------------------------- - GLSLLinkProgram::GLSLLinkProgram(const GLShaderList& shaders) : GLSLProgramCommon(shaders) - { - // Initialise uniform cache - mUniformCache = new GLUniformCache(); - } - - //----------------------------------------------------------------------- - GLSLLinkProgram::~GLSLLinkProgram(void) - { - glDeleteObjectARB((GLhandleARB)mGLProgramHandle); - - delete mUniformCache; - mUniformCache = 0; - } - - //----------------------------------------------------------------------- - void GLSLLinkProgram::activate(void) - { - if (!mLinked) - { - glGetError(); //Clean up the error. Otherwise will flood log. - - mGLProgramHandle = (size_t)glCreateProgramObjectARB(); - - GLenum glErr = glGetError(); - if(glErr != GL_NO_ERROR) - { - reportGLSLError( glErr, "GLSLLinkProgram::activate", "Error Creating GLSL Program Object", 0 ); - } - - uint32 hash = getCombinedHash(); - - if ( GpuProgramManager::getSingleton().canGetCompiledShaderBuffer() && - GpuProgramManager::getSingleton().isMicrocodeAvailableInCache(hash) && - !mShaders[GPT_GEOMETRY_PROGRAM]) - { - getMicrocodeFromCache(hash); - } - else - { - compileAndLink(); - - } - buildGLUniformReferences(); - extractAttributes(); - } - if (mLinked) - { - glUseProgramObjectARB( (GLhandleARB)mGLProgramHandle ); - - GLenum glErr = glGetError(); - if(glErr != GL_NO_ERROR) - { - reportGLSLError( glErr, "GLSLLinkProgram::Activate", - "Error using GLSL Program Object : ", mGLProgramHandle, false, false); - } - } - } - //----------------------------------------------------------------------- - void GLSLLinkProgram::getMicrocodeFromCache(uint32 id) - { - GpuProgramManager::Microcode cacheMicrocode = - GpuProgramManager::getSingleton().getMicrocodeFromCache(id); - - GLenum binaryFormat = *((GLenum *)(cacheMicrocode->getPtr())); - uint8 * programBuffer = cacheMicrocode->getPtr() + sizeof(GLenum); - size_t sizeOfBuffer = cacheMicrocode->size() - sizeof(GLenum); - glProgramBinary(mGLProgramHandle, - binaryFormat, - programBuffer, - static_cast(sizeOfBuffer) - ); - - glGetProgramiv(mGLProgramHandle, GL_LINK_STATUS, &mLinked); - if (!mLinked) - { - // - // Something must have changed since the program binaries - // were cached away. Fallback to source shader loading path, - // and then retrieve and cache new program binaries once again. - // - compileAndLink(); - } - } - //----------------------------------------------------------------------- - void GLSLLinkProgram::extractAttributes(void) - { - size_t numAttribs = sizeof(msCustomAttributes)/sizeof(CustomAttribute); - - for (size_t i = 0; i < numAttribs; ++i) - { - const CustomAttribute& a = msCustomAttributes[i]; - GLint attrib = glGetAttribLocationARB((GLhandleARB)mGLProgramHandle, a.name); - - if (attrib != -1) - { - mValidAttributes.insert(a.attrib); - - if(a.semantic != VES_TEXTURE_COORDINATES) continue; - - // also enable next 4 attributes to allow matrix types in texcoord semantic - // might cause problems with mixing builtin and custom names, - // but then again you should not - for(int j = 0; j < 4; j++) - mValidAttributes.insert(msCustomAttributes[i + j].attrib); - } - } - } - //----------------------------------------------------------------------- - bool GLSLLinkProgram::isAttributeValid(VertexElementSemantic semantic, uint index) - { - return mValidAttributes.find(getFixedAttributeIndex(semantic, index)) != mValidAttributes.end(); - } - //----------------------------------------------------------------------- - void GLSLLinkProgram::buildGLUniformReferences(void) - { - if (!mUniformRefsBuilt) - { - const GpuConstantDefinitionMap* vertParams = 0; - const GpuConstantDefinitionMap* fragParams = 0; - const GpuConstantDefinitionMap* geomParams = 0; - if (mShaders[GPT_VERTEX_PROGRAM]) - { - vertParams = &(mShaders[GPT_VERTEX_PROGRAM]->getConstantDefinitions().map); - } - if (mShaders[GPT_GEOMETRY_PROGRAM]) - { - geomParams = &(mShaders[GPT_GEOMETRY_PROGRAM]->getConstantDefinitions().map); - } - if (mShaders[GPT_FRAGMENT_PROGRAM]) - { - fragParams = &(mShaders[GPT_FRAGMENT_PROGRAM]->getConstantDefinitions().map); - } - - GLSLLinkProgramManager::extractUniforms( - mGLProgramHandle, vertParams, geomParams, fragParams, mGLUniformReferences); - - mUniformRefsBuilt = true; - } - } - - //----------------------------------------------------------------------- - void GLSLLinkProgram::updateUniforms(GpuProgramParametersSharedPtr params, - uint16 mask, GpuProgramType fromProgType) - { - // iterate through uniform reference list and update uniform values - GLUniformReferenceIterator currentUniform = mGLUniformReferences.begin(); - GLUniformReferenceIterator endUniform = mGLUniformReferences.end(); - - // determine if we need to transpose matrices when binding - bool transpose = !mShaders[fromProgType] || mShaders[fromProgType]->getColumnMajorMatrices(); - - for (;currentUniform != endUniform; ++currentUniform) - { - // Only pull values from buffer it's supposed to be in (vertex or fragment) - // This method will be called twice, once for vertex program params, - // and once for fragment program params. - if (fromProgType == currentUniform->mSourceProgType) - { - const GpuConstantDefinition* def = currentUniform->mConstantDef; - if (def->variability & mask) - { - - GLsizei glArraySize = (GLsizei)def->arraySize; - - void* val = def->isSampler() ? (void*)params->getRegPointer(def->physicalIndex) - : (void*)params->getFloatPointer(def->physicalIndex); - - bool shouldUpdate = mUniformCache->updateUniform(currentUniform->mLocation, val, - def->elementSize * def->arraySize * 4); - if(!shouldUpdate) - continue; - - // get the index in the parameter real list - switch (def->constType) - { - case GCT_FLOAT1: - glUniform1fvARB(currentUniform->mLocation, glArraySize, - params->getFloatPointer(def->physicalIndex)); - break; - case GCT_FLOAT2: - glUniform2fvARB(currentUniform->mLocation, glArraySize, - params->getFloatPointer(def->physicalIndex)); - break; - case GCT_FLOAT3: - glUniform3fvARB(currentUniform->mLocation, glArraySize, - params->getFloatPointer(def->physicalIndex)); - break; - case GCT_FLOAT4: - glUniform4fvARB(currentUniform->mLocation, glArraySize, - params->getFloatPointer(def->physicalIndex)); - break; - case GCT_MATRIX_2X2: - glUniformMatrix2fvARB(currentUniform->mLocation, glArraySize, - transpose, params->getFloatPointer(def->physicalIndex)); - break; - case GCT_MATRIX_2X3: - if (GLAD_GL_VERSION_2_1) - { - glUniformMatrix2x3fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex)); - } - break; - case GCT_MATRIX_2X4: - if (GLAD_GL_VERSION_2_1) - { - glUniformMatrix2x4fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex)); - } - break; - case GCT_MATRIX_3X2: - if (GLAD_GL_VERSION_2_1) - { - glUniformMatrix3x2fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex)); - } - break; - case GCT_MATRIX_3X3: - glUniformMatrix3fvARB(currentUniform->mLocation, glArraySize, - transpose, params->getFloatPointer(def->physicalIndex)); - break; - case GCT_MATRIX_3X4: - if (GLAD_GL_VERSION_2_1) - { - glUniformMatrix3x4fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex)); - } - break; - case GCT_MATRIX_4X2: - if (GLAD_GL_VERSION_2_1) - { - glUniformMatrix4x2fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex)); - } - break; - case GCT_MATRIX_4X3: - if (GLAD_GL_VERSION_2_1) - { - glUniformMatrix4x3fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex)); - } - break; - case GCT_MATRIX_4X4: - glUniformMatrix4fvARB(currentUniform->mLocation, glArraySize, - transpose, params->getFloatPointer(def->physicalIndex)); - break; - case GCT_SAMPLER1D: - case GCT_SAMPLER1DSHADOW: - case GCT_SAMPLER2D: - case GCT_SAMPLER2DSHADOW: - case GCT_SAMPLER2DARRAY: - case GCT_SAMPLER3D: - case GCT_SAMPLERCUBE: - // samplers handled like 1-element ints - case GCT_INT1: - glUniform1ivARB(currentUniform->mLocation, glArraySize, (GLint*)val); - break; - case GCT_INT2: - glUniform2ivARB(currentUniform->mLocation, glArraySize, - (GLint*)params->getIntPointer(def->physicalIndex)); - break; - case GCT_INT3: - glUniform3ivARB(currentUniform->mLocation, glArraySize, - (GLint*)params->getIntPointer(def->physicalIndex)); - break; - case GCT_INT4: - glUniform4ivARB(currentUniform->mLocation, glArraySize, - (GLint*)params->getIntPointer(def->physicalIndex)); - break; - case GCT_UNKNOWN: - default: - break; - - } // end switch - #if OGRE_DEBUG_MODE - GLenum glErr = glGetError(); - if(glErr != GL_NO_ERROR) - { - reportGLSLError( glErr, "GLSLLinkProgram::updateUniforms", "Error updating uniform", 0 ); - } - #endif - } // variability & mask - } // fromProgType == currentUniform->mSourceProgType - - } // end for - } - //----------------------------------------------------------------------- - void GLSLLinkProgram::compileAndLink() - { - uint32 hash = 0; - if (mShaders[GPT_VERTEX_PROGRAM]) - { - // attach Vertex Program - mShaders[GPT_VERTEX_PROGRAM]->attachToProgramObject(mGLProgramHandle); - - // Some drivers (e.g. OS X on nvidia) incorrectly determine the attribute binding automatically - - // and end up aliasing existing built-ins. So avoid! - // Bind all used attribs - not all possible ones otherwise we'll get - // lots of warnings in the log, and also may end up aliasing names used - // as varyings by accident - // Because we can't ask GL whether an attribute is used in the shader - // until it is linked (chicken and egg!) we have to parse the source - - size_t numAttribs = sizeof(msCustomAttributes)/sizeof(CustomAttribute); - const String& vpSource = mShaders[GPT_VERTEX_PROGRAM]->getSource(); - - hash = mShaders[GPT_VERTEX_PROGRAM]->_getHash(hash); - for (size_t i = 0; i < numAttribs; ++i) - { - const CustomAttribute& a = msCustomAttributes[i]; - - // we're looking for either: - // attribute vec - // in vec - // The latter is recommended in GLSL 1.3 onwards - // be slightly flexible about formatting - String::size_type pos = vpSource.find(a.name); - bool foundAttr = false; - while (pos != String::npos && !foundAttr) - { - String::size_type startpos = vpSource.find("attribute", pos < 20 ? 0 : pos-20); - if (startpos == String::npos) - startpos = vpSource.find("in", pos-20); - if (startpos != String::npos && startpos < pos) - { - // final check - String expr = vpSource.substr(startpos, pos + strlen(a.name) - startpos); - StringVector vec = StringUtil::split(expr); - if ((vec[0] == "in" || vec[0] == "attribute") && vec[2] == a.name) - { - glBindAttribLocationARB((GLhandleARB)mGLProgramHandle, a.attrib, a.name); - foundAttr = true; - } - } - // Find the position of the next occurrence if needed - pos = vpSource.find(a.name, pos + strlen(a.name)); - } - } - } - - if (auto gshader = static_cast(mShaders[GPT_GEOMETRY_PROGRAM])) - { - hash = mShaders[GPT_GEOMETRY_PROGRAM]->_getHash(hash); - // attach Geometry Program - mShaders[GPT_GEOMETRY_PROGRAM]->attachToProgramObject(mGLProgramHandle); - - if (GLAD_GL_EXT_geometry_shader4) - { - RenderOperation::OperationType inputOperationType = gshader->getInputOperationType(); - glProgramParameteriEXT(mGLProgramHandle, GL_GEOMETRY_INPUT_TYPE_EXT, - getGLGeometryInputPrimitiveType(inputOperationType)); - - RenderOperation::OperationType outputOperationType = gshader->getOutputOperationType(); - - glProgramParameteriEXT(mGLProgramHandle, GL_GEOMETRY_OUTPUT_TYPE_EXT, - getGLGeometryOutputPrimitiveType(outputOperationType)); - - glProgramParameteriEXT(mGLProgramHandle, GL_GEOMETRY_VERTICES_OUT_EXT, gshader->getMaxOutputVertices()); - } - } - - if (mShaders[GPT_FRAGMENT_PROGRAM]) - { - hash = mShaders[GPT_FRAGMENT_PROGRAM]->_getHash(hash); - // attach Fragment Program - mShaders[GPT_FRAGMENT_PROGRAM]->attachToProgramObject(mGLProgramHandle); - } - - - // now the link - - glLinkProgramARB( (GLhandleARB)mGLProgramHandle ); - glGetObjectParameterivARB( (GLhandleARB)mGLProgramHandle, GL_OBJECT_LINK_STATUS_ARB, &mLinked ); - - // force logging and raise exception if not linked - GLenum glErr = glGetError(); - if(glErr != GL_NO_ERROR) - { - reportGLSLError( glErr, "GLSLLinkProgram::compileAndLink", - "Error linking GLSL Program Object : ", mGLProgramHandle, !mLinked, !mLinked ); - } - - if(mLinked) - { - logObjectInfo( getCombinedName() + String(" GLSL link result : "), mGLProgramHandle ); - } - - if (mLinked) - { - if ( GpuProgramManager::getSingleton().getSaveMicrocodesToCache() ) - { - // add to the microcode to the cache - - // get buffer size - GLint binaryLength = 0; - glGetProgramiv(mGLProgramHandle, GL_PROGRAM_BINARY_LENGTH, &binaryLength); - - // turns out we need this param when loading - // it will be the first bytes of the array in the microcode - GLenum binaryFormat = 0; - - // create microcode - auto newMicrocode = GpuProgramManager::createMicrocode(binaryLength + sizeof(GLenum)); - - // get binary - uint8 * programBuffer = newMicrocode->getPtr() + sizeof(GLenum); - glGetProgramBinary(mGLProgramHandle, binaryLength, NULL, &binaryFormat, programBuffer); - - // save binary format - memcpy(newMicrocode->getPtr(), &binaryFormat, sizeof(GLenum)); - - // add to the microcode to the cache - GpuProgramManager::getSingleton().addMicrocodeToCache(hash, newMicrocode); - } - } - } - //----------------------------------------------------------------------- -} // namespace GLSL -} // namespace Ogre diff --git a/RenderSystems/GL/src/GLSL/src/OgreGLSLLinkProgramManager.cpp b/RenderSystems/GL/src/GLSL/src/OgreGLSLLinkProgramManager.cpp deleted file mode 100644 index 8080572889c..00000000000 --- a/RenderSystems/GL/src/GLSL/src/OgreGLSLLinkProgramManager.cpp +++ /dev/null @@ -1,137 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLSLLinkProgramManager.h" -#include "OgreGLSLProgram.h" -#include "OgreStringConverter.h" -#include "OgreLogManager.h" - -namespace Ogre { - - //----------------------------------------------------------------------- - template<> GLSL::GLSLLinkProgramManager* Singleton::msSingleton = 0; - - namespace GLSL { - - //----------------------------------------------------------------------- - GLSLLinkProgramManager* GLSLLinkProgramManager::getSingletonPtr(void) - { - return msSingleton; - } - - //----------------------------------------------------------------------- - GLSLLinkProgramManager& GLSLLinkProgramManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - - //----------------------------------------------------------------------- - GLSLLinkProgramManager::GLSLLinkProgramManager(void) {} - - //----------------------------------------------------------------------- - GLSLLinkProgramManager::~GLSLLinkProgramManager(void) {} - - //----------------------------------------------------------------------- - GLSLLinkProgram* GLSLLinkProgramManager::getActiveLinkProgram(void) - { - // if there is an active link program then return it - if (mActiveProgram) - return static_cast(mActiveProgram);; - - // no active link program so find one or make a new one - // is there an active key? - uint32 activeKey = 0; - for(auto shader : mActiveShader) - { - if(!shader) continue; - activeKey = HashCombine(activeKey, shader->getShaderID()); - } - - // only return a link program object if a vertex, geometry or fragment program exist - if (activeKey > 0) - { - // find the key in the hash map - ProgramIterator programFound = mPrograms.find(activeKey); - // program object not found for key so need to create it - if (programFound == mPrograms.end()) - { - mActiveProgram = new GLSLLinkProgram(mActiveShader); - mPrograms[activeKey] = mActiveProgram; - } - else - { - // found a link program in map container so make it active - mActiveProgram = static_cast(programFound->second); - } - - } - // make the program object active - if (mActiveProgram) mActiveProgram->activate(); - - return static_cast(mActiveProgram);; - - } - //--------------------------------------------------------------------- - void GLSLLinkProgramManager::extractUniforms(uint programObject, - const GpuConstantDefinitionMap* vertexConstantDefs, - const GpuConstantDefinitionMap* geometryConstantDefs, - const GpuConstantDefinitionMap* fragmentConstantDefs, - GLUniformReferenceList& list) - { - // scan through the active uniforms and add them to the reference list - GLint uniformCount = 0; - - #define BUFFERSIZE 200 - char uniformName[BUFFERSIZE] = ""; - //GLint location; - GLUniformReference newGLUniformReference; - - // get the number of active uniforms - glGetObjectParameterivARB((GLhandleARB)programObject, GL_OBJECT_ACTIVE_UNIFORMS_ARB, - &uniformCount); - - const GpuConstantDefinitionMap* params[6] = { vertexConstantDefs, fragmentConstantDefs, geometryConstantDefs }; - - // Loop over each of the active uniforms, and add them to the reference container - // only do this for user defined uniforms, ignore built in gl state uniforms - for (int index = 0; index < uniformCount; index++) - { - GLint numActiveArrayElements = 0; - GLenum glType; - glGetActiveUniformARB((GLhandleARB)programObject, index, BUFFERSIZE, NULL, - &numActiveArrayElements, &glType, uniformName); - newGLUniformReference.mLocation = glGetUniformLocationARB((GLhandleARB)programObject, uniformName); - - if(!validateParam(uniformName, numActiveArrayElements, params, newGLUniformReference)) - continue; - list.push_back(newGLUniformReference); - } - - } -} -} diff --git a/RenderSystems/GL/src/GLSL/src/OgreGLSLProgram.cpp b/RenderSystems/GL/src/GLSL/src/OgreGLSLProgram.cpp deleted file mode 100644 index 68dcf8f4a33..00000000000 --- a/RenderSystems/GL/src/GLSL/src/OgreGLSLProgram.cpp +++ /dev/null @@ -1,407 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreGpuProgram.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" -#include "OgreRenderSystemCapabilities.h" -#include "OgreStringConverter.h" -#include "OgreGpuProgramManager.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreLogManager.h" - -#include "OgreGLSLProgram.h" -#include "OgreGLSLExtSupport.h" -#include "OgreGLSLLinkProgramManager.h" -#include "OgreGLSLPreprocessor.h" - -namespace Ogre { - namespace GLSL { - //----------------------------------------------------------------------- - static RenderOperation::OperationType parseOperationType(const String& val) - { - if (val == "point_list") - { - return RenderOperation::OT_POINT_LIST; - } - else if (val == "line_list") - { - return RenderOperation::OT_LINE_LIST; - } - else if (val == "line_list_adj") - { - return RenderOperation::OT_LINE_LIST_ADJ; - } - else if (val == "line_strip") - { - return RenderOperation::OT_LINE_STRIP; - } - else if (val == "line_strip_adj") - { - return RenderOperation::OT_LINE_STRIP_ADJ; - } - else if (val == "triangle_strip") - { - return RenderOperation::OT_TRIANGLE_STRIP; - } - else if (val == "triangle_strip_adj") - { - return RenderOperation::OT_TRIANGLE_STRIP_ADJ; - } - else if (val == "triangle_fan") - { - return RenderOperation::OT_TRIANGLE_FAN; - } - else if (val == "triangle_list_adj") - { - return RenderOperation::OT_TRIANGLE_LIST_ADJ; - } - else - { - //Triangle list is the default fallback. Keep it this way? - return RenderOperation::OT_TRIANGLE_LIST; - } - } - //----------------------------------------------------------------------- - static const char* operationTypeToString(RenderOperation::OperationType val) - { - switch (val) - { - case RenderOperation::OT_POINT_LIST: - return "point_list"; - break; - case RenderOperation::OT_LINE_LIST: - return "line_list"; - break; - case RenderOperation::OT_LINE_LIST_ADJ: - return "line_list_adj"; - break; - case RenderOperation::OT_LINE_STRIP: - return "line_strip"; - break; - case RenderOperation::OT_LINE_STRIP_ADJ: - return "line_strip_adj"; - break; - case RenderOperation::OT_TRIANGLE_STRIP: - return "triangle_strip"; - break; - case RenderOperation::OT_TRIANGLE_STRIP_ADJ: - return "triangle_strip_adj"; - break; - case RenderOperation::OT_TRIANGLE_FAN: - return "triangle_fan"; - break; - case RenderOperation::OT_TRIANGLE_LIST_ADJ: - return "triangle_list_adj"; - break; - case RenderOperation::OT_TRIANGLE_LIST: - default: - return "triangle_list"; - break; - } - } - /// Command object for setting the input operation type (geometry shader only) - class CmdInputOperationType : public ParamCommand - { - public: - String doGet(const void* target) const override - { - const GLSLProgram* t = static_cast(target); - return operationTypeToString(t->getInputOperationType()); - } - void doSet(void* target, const String& val) override - { - GLSLProgram* t = static_cast(target); - t->setInputOperationType(parseOperationType(val)); - } - }; - /// Command object for setting the output operation type (geometry shader only) - class CmdOutputOperationType : public ParamCommand - { - public: - String doGet(const void* target) const override - { - const GLSLProgram* t = static_cast(target); - return operationTypeToString(t->getOutputOperationType()); - } - void doSet(void* target, const String& val) override - { - GLSLProgram* t = static_cast(target); - t->setOutputOperationType(parseOperationType(val)); - } - }; - /// Command object for setting the maximum output vertices (geometry shader only) - class CmdMaxOutputVertices : public ParamCommand - { - public: - String doGet(const void* target) const override - { - const GLSLProgram* t = static_cast(target); - return StringConverter::toString(t->getMaxOutputVertices()); - } - void doSet(void* target, const String& val) override - { - GLSLProgram* t = static_cast(target); - t->setMaxOutputVertices(StringConverter::parseInt(val)); - } - }; - static CmdInputOperationType msInputOperationTypeCmd; - static CmdOutputOperationType msOutputOperationTypeCmd; - static CmdMaxOutputVertices msMaxOutputVerticesCmd; - //--------------------------------------------------------------------------- - GLSLProgram::~GLSLProgram() - { - // Have to call this here rather than in Resource destructor - // since calling virtual methods in base destructors causes crash - if (isLoaded()) - { - unload(); - } - else - { - unloadHighLevel(); - } - } - //--------------------------------------------------------------------------- - void GLSLProgram::loadFromSource() - { - // only create a shader object if glsl is supported - if (isSupported()) - { - // create shader object - GLenum shaderType = 0x0000; - switch (mType) - { - case GPT_VERTEX_PROGRAM: - shaderType = GL_VERTEX_SHADER_ARB; - break; - case GPT_FRAGMENT_PROGRAM: - shaderType = GL_FRAGMENT_SHADER_ARB; - break; - case GPT_GEOMETRY_PROGRAM: - shaderType = GL_GEOMETRY_SHADER_EXT; - break; - case GPT_COMPUTE_PROGRAM: - case GPT_DOMAIN_PROGRAM: - case GPT_HULL_PROGRAM: - break; - } - mGLShaderHandle = (size_t)glCreateShaderObjectARB(shaderType); - } - - // Add preprocessor extras and main source - if (!mSource.empty()) - { - const char *source = mSource.c_str(); - glShaderSourceARB((GLhandleARB)mGLShaderHandle, 1, &source, NULL); - } - - glCompileShaderARB((GLhandleARB)mGLShaderHandle); - // check for compile errors - int compiled = 0; - glGetObjectParameterivARB((GLhandleARB)mGLShaderHandle, GL_OBJECT_COMPILE_STATUS_ARB, &compiled); - - String compileInfo = getObjectInfo(mGLShaderHandle); - - if (!compiled) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, getResourceLogName() + " " + compileInfo, "compile"); - - // probably we have warnings - if (!compileInfo.empty()) - LogManager::getSingleton().stream(LML_WARNING) << getResourceLogName() << " " << compileInfo; - } - //----------------------------------------------------------------------- - void GLSLProgram::unloadHighLevelImpl(void) - { - if (isSupported()) - { - glDeleteObjectARB((GLhandleARB)mGLShaderHandle); - mGLShaderHandle = 0; - - // destroy all programs using this shader - GLSLLinkProgramManager::getSingletonPtr()->destroyAllByShader(this); - } - } - //----------------------------------------------------------------------- - void GLSLProgram::buildConstantDefinitions() - { - // We need an accurate list of all the uniforms in the shader, but we - // can't get at them until we link all the shaders into a program object. - - - // Therefore instead, parse the source code manually and extract the uniforms - createParameterMappingStructures(true); - mLogicalToPhysical.reset(); - - GLSLLinkProgramManager::getSingleton().extractUniformsFromGLSL( - mSource, *mConstantDefs, getResourceLogName()); - - // Also parse any attached sources - for (auto childShader : mAttachedGLSLPrograms) - { - GLSLLinkProgramManager::getSingleton().extractUniformsFromGLSL( - childShader->getSource(), *mConstantDefs, childShader->getName()); - - } - } - - //----------------------------------------------------------------------- - GLSLProgram::GLSLProgram(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - : GLSLShaderCommon(creator, name, handle, group, isManual, loader) - , mInputOperationType(RenderOperation::OT_TRIANGLE_LIST) - , mOutputOperationType(RenderOperation::OT_TRIANGLE_LIST) - , mMaxOutputVertices(3) - { - // add parameter command "attach" to the material serializer dictionary - if (createParamDictionary("GLSLProgram")) - { - setupBaseParamDictionary(); - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter(ParameterDef("attach", - "name of another GLSL program needed by this program", - PT_STRING),&msCmdAttach); - dict->addParameter(ParameterDef("column_major_matrices", - "Whether matrix packing in column-major order.", - PT_BOOL),&msCmdColumnMajorMatrices); - dict->addParameter( - ParameterDef("input_operation_type", - "The input operation type for this geometry program. \ - Can be 'point_list', 'line_list', 'line_strip', 'triangle_list', \ - 'triangle_strip' or 'triangle_fan'", PT_STRING), - &msInputOperationTypeCmd); - dict->addParameter( - ParameterDef("output_operation_type", - "The input operation type for this geometry program. \ - Can be 'point_list', 'line_strip' or 'triangle_strip'", - PT_STRING), - &msOutputOperationTypeCmd); - dict->addParameter( - ParameterDef("max_output_vertices", - "The maximum number of vertices a single run of this geometry program can output", - PT_INT),&msMaxOutputVerticesCmd); - } - mPassFFPStates = Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_FIXED_FUNCTION); - } - - //----------------------------------------------------------------------- - void GLSLProgram::attachToProgramObject( const uint programObject ) - { - // attach child objects - for (auto childShader : mAttachedGLSLPrograms) - { - childShader->attachToProgramObject(programObject); - } - glAttachObjectARB( (GLhandleARB)programObject, (GLhandleARB)mGLShaderHandle ); - GLenum glErr = glGetError(); - if(glErr != GL_NO_ERROR) - { - reportGLSLError( glErr, "GLSLProgram::attachToProgramObject", - "Error attaching " + mName + " shader object to GLSL Program Object", programObject ); - } - - } - //----------------------------------------------------------------------- - void GLSLProgram::detachFromProgramObject( const uint programObject ) - { - glDetachObjectARB((GLhandleARB)programObject, (GLhandleARB)mGLShaderHandle); - - GLenum glErr = glGetError(); - if(glErr != GL_NO_ERROR) - { - reportGLSLError( glErr, "GLSLProgram::detachFromProgramObject", - "Error detaching " + mName + " shader object from GLSL Program Object", programObject ); - } - // attach child objects - GLSLProgramContainerIterator childprogramcurrent = mAttachedGLSLPrograms.begin(); - GLSLProgramContainerIterator childprogramend = mAttachedGLSLPrograms.end(); - - while (childprogramcurrent != childprogramend) - { - GLSLShaderCommon* childShader = *childprogramcurrent; - childShader->detachFromProgramObject( programObject ); - ++childprogramcurrent; - } - - } - - //----------------------------------------------------------------------- - const String& GLSLProgram::getLanguage(void) const - { - static const String language = "glsl"; - - return language; - } - //----------------------------------------------------------------------------- - void GLSLProgram::bindProgram(void) - { - // Tell the Link Program Manager what shader is to become active - GLSLLinkProgramManager::getSingleton().setActiveShader( mType, this ); - } - //----------------------------------------------------------------------------- - void GLSLProgram::unbindProgram(void) - { - // Tell the Link Program Manager what shader is to become inactive - GLSLLinkProgramManager::getSingleton().setActiveShader( mType, NULL ); - // change back to fixed pipeline - glUseProgramObjectARB(0); - } - - //----------------------------------------------------------------------------- - void GLSLProgram::bindProgramParameters(GpuProgramParametersSharedPtr params, uint16 mask) - { - // link can throw exceptions, ignore them at this point - try - { - // activate the link program object - GLSLLinkProgram* linkProgram = GLSLLinkProgramManager::getSingleton().getActiveLinkProgram(); - // pass on parameters from params to program object uniforms - linkProgram->updateUniforms(params, mask, mType); - } - catch (Exception&) {} - - } - //----------------------------------------------------------------------------- - bool GLSLProgram::isAttributeValid(VertexElementSemantic semantic, uint index) - { - // get link program - only call this in the context of bound program - GLSLLinkProgram* linkProgram = GLSLLinkProgramManager::getSingleton().getActiveLinkProgram(); - - if (linkProgram->isAttributeValid(semantic, index)) - { - return true; - } - else - { - // fall back to default implementation, allow default bindings - return GLGpuProgramBase::isAttributeValid(semantic, index); - } - } -} -} diff --git a/RenderSystems/GL/src/GLSL/src/OgreGLSLProgramFactory.cpp b/RenderSystems/GL/src/GLSL/src/OgreGLSLProgramFactory.cpp deleted file mode 100644 index 2d2203e1cac..00000000000 --- a/RenderSystems/GL/src/GLSL/src/OgreGLSLProgramFactory.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLSLProgramFactory.h" -#include "OgreGLSLLinkProgramManager.h" -#include "OgreGLSLProgram.h" - -namespace Ogre { - namespace GLSL { - //----------------------------------------------------------------------- - String GLSLProgramFactory::sLanguageName = "glsl"; - //----------------------------------------------------------------------- - GLSLProgramFactory::GLSLProgramFactory(void) - { - mLinkProgramManager = new GLSLLinkProgramManager(); - } - //----------------------------------------------------------------------- - GLSLProgramFactory::~GLSLProgramFactory(void) - { - if (mLinkProgramManager) - delete mLinkProgramManager; - } - //----------------------------------------------------------------------- - const String& GLSLProgramFactory::getLanguage(void) const - { - return sLanguageName; - } - //----------------------------------------------------------------------- - GpuProgram* GLSLProgramFactory::create(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - { - return new GLSLProgram(creator, name, handle, group, isManual, loader); - } -} -} diff --git a/RenderSystems/GL/src/OgreGLCopyingRenderTexture.cpp b/RenderSystems/GL/src/OgreGLCopyingRenderTexture.cpp deleted file mode 100755 index d4be459a3e7..00000000000 --- a/RenderSystems/GL/src/OgreGLCopyingRenderTexture.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreGLCopyingRenderTexture.h" -#include "OgreGLPixelFormat.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreRoot.h" -#include "OgreGLHardwarePixelBuffer.h" - -namespace Ogre { - -//----------------------------------------------------------------------------- - GLCopyingRenderTexture::GLCopyingRenderTexture(GLCopyingRTTManager *manager, - const String &name, const GLSurfaceDesc &target, bool writeGamma, uint fsaa): - GLRenderTexture(name, target, writeGamma, fsaa) - { - } - void GLCopyingRenderTexture::getCustomAttribute(const String& name, void* pData) - { - if( name == GLRenderTexture::CustomAttributeString_TARGET ) - { - GLSurfaceDesc &target = *static_cast(pData); - target.buffer = static_cast(mBuffer); - target.zoffset = mZOffset; - } - } -//----------------------------------------------------------------------------- - void GLCopyingRTTManager::unbind(RenderTarget *target) - { - // Copy on unbind - GLSurfaceDesc surface; - surface.buffer = 0; - target->getCustomAttribute(GLRenderTexture::CustomAttributeString_TARGET, &surface); - if(surface.buffer) - static_cast(surface.buffer)->copyFromFramebuffer(surface.zoffset); - } -} - diff --git a/RenderSystems/GL/src/OgreGLEngineDll.cpp b/RenderSystems/GL/src/OgreGLEngineDll.cpp deleted file mode 100644 index 611fcafd39d..00000000000 --- a/RenderSystems/GL/src/OgreGLEngineDll.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLPrerequisites.h" -#include "OgreRoot.h" -#include "OgreGLPlugin.h" - -#ifndef OGRE_STATIC_LIB - -namespace Ogre -{ - static GLPlugin* plugin; - extern "C" void _OgreGLExport dllStartPlugin(void); - extern "C" void _OgreGLExport dllStopPlugin(void); - - extern "C" void _OgreGLExport dllStartPlugin(void) - { - plugin = OGRE_NEW GLPlugin(); - Root::getSingleton().installPlugin(plugin); - } - - extern "C" void _OgreGLExport dllStopPlugin(void) - { - Root::getSingleton().uninstallPlugin(plugin); - OGRE_DELETE plugin; - } -} - -#endif diff --git a/RenderSystems/GL/src/OgreGLFBOMultiRenderTarget.cpp b/RenderSystems/GL/src/OgreGLFBOMultiRenderTarget.cpp deleted file mode 100755 index 6d7ae6bbc98..00000000000 --- a/RenderSystems/GL/src/OgreGLFBOMultiRenderTarget.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLFBOMultiRenderTarget.h" -#include "OgreGLPixelFormat.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreRoot.h" -#include "OgreGLHardwarePixelBuffer.h" - -namespace Ogre { - - GLFBOMultiRenderTarget::GLFBOMultiRenderTarget(GLFBOManager *manager, const String &name): - MultiRenderTarget(name), - fbo(manager, 0 /* TODO: multisampling on MRTs? */) - { - } - - GLFBOMultiRenderTarget::~GLFBOMultiRenderTarget() - { - } - - void GLFBOMultiRenderTarget::bindSurfaceImpl(size_t attachment, RenderTexture *target) - { - /// Check if the render target is in the rendertarget->FBO map - auto fbobj = dynamic_cast(target)->getFBO(); - assert(fbobj); - fbo.bindSurface(attachment, fbobj->getSurface(0)); - - // Set width and height - mWidth = fbo.getWidth(); - mHeight = fbo.getHeight(); - } - - void GLFBOMultiRenderTarget::unbindSurfaceImpl(size_t attachment) - { - fbo.unbindSurface(attachment); - - // Set width and height - mWidth = fbo.getWidth(); - mHeight = fbo.getHeight(); - } - - void GLFBOMultiRenderTarget::getCustomAttribute( const String& name, void *pData ) - { - if( name == GLRenderTexture::CustomAttributeString_FBO ) - { - *static_cast(pData) = &fbo; - } - } - //----------------------------------------------------------------------------- - bool GLFBOMultiRenderTarget::attachDepthBuffer( DepthBuffer *depthBuffer ) - { - bool result; - if( (result = MultiRenderTarget::attachDepthBuffer( depthBuffer )) ) - fbo.attachDepthBuffer( depthBuffer ); - - return result; - } - //----------------------------------------------------------------------------- - void GLFBOMultiRenderTarget::detachDepthBuffer() - { - fbo.detachDepthBuffer(); - MultiRenderTarget::detachDepthBuffer(); - } - //----------------------------------------------------------------------------- - void GLFBOMultiRenderTarget::_detachDepthBuffer() - { - fbo.detachDepthBuffer(); - MultiRenderTarget::_detachDepthBuffer(); - } -} diff --git a/RenderSystems/GL/src/OgreGLFBORenderTexture.cpp b/RenderSystems/GL/src/OgreGLFBORenderTexture.cpp deleted file mode 100644 index eca17899421..00000000000 --- a/RenderSystems/GL/src/OgreGLFBORenderTexture.cpp +++ /dev/null @@ -1,525 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLFBORenderTexture.h" -#include "OgreGLPixelFormat.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreRoot.h" -#include "OgreGLHardwarePixelBuffer.h" -#include "OgreGLFBOMultiRenderTarget.h" - -namespace Ogre { - -//----------------------------------------------------------------------------- - GLFBORenderTexture::GLFBORenderTexture(GLFBOManager *manager, const String &name, - const GLSurfaceDesc &target, bool writeGamma, uint fsaa): - GLRenderTexture(name, target, writeGamma, fsaa), - mFB(manager, fsaa) - { - // Bind target to surface 0 and initialise - mFB.bindSurface(0, target); - // Get attributes - mWidth = mFB.getWidth(); - mHeight = mFB.getHeight(); - } - - void GLFBORenderTexture::getCustomAttribute(const String& name, void* pData) - { - if( name == GLRenderTexture::CustomAttributeString_FBO ) - { - *static_cast(pData) = &mFB; - } - else if(name == GLRenderTexture::CustomAttributeString_GLCONTEXT) - { - *static_cast(pData) = mFB.getContext(); - } - else if (name == "GL_FBOID") - { - *static_cast(pData) = mFB.getGLFBOID(); - } - else if (name == "GL_MULTISAMPLEFBOID") - { - *static_cast(pData) = mFB.getGLMultisampleFBOID(); - } - } - - void GLFBORenderTexture::swapBuffers() - { - mFB.swapBuffers(); - } - //----------------------------------------------------------------------------- - bool GLFBORenderTexture::attachDepthBuffer( DepthBuffer *depthBuffer ) - { - bool result; - if( (result = GLRenderTexture::attachDepthBuffer( depthBuffer )) ) - mFB.attachDepthBuffer( depthBuffer ); - - return result; - } - //----------------------------------------------------------------------------- - void GLFBORenderTexture::detachDepthBuffer() - { - mFB.detachDepthBuffer(); - GLRenderTexture::detachDepthBuffer(); - } - //----------------------------------------------------------------------------- - void GLFBORenderTexture::_detachDepthBuffer() - { - mFB.detachDepthBuffer(); - GLRenderTexture::_detachDepthBuffer(); - } - -/// Size of probe texture -#define PROBE_SIZE 16 - -/// Stencil and depth formats to be tried -static const GLenum stencilFormats[] = -{ - GL_NONE, // No stencil - GL_STENCIL_INDEX1_EXT, - GL_STENCIL_INDEX4_EXT, - GL_STENCIL_INDEX8_EXT, - GL_STENCIL_INDEX16_EXT -}; -static const uchar stencilBits[] = -{ - 0, 1, 4, 8, 16 -}; -#define STENCILFORMAT_COUNT (sizeof(stencilFormats)/sizeof(GLenum)) - -static const GLenum depthFormats[] = -{ - GL_NONE, - GL_DEPTH_COMPONENT16, - GL_DEPTH_COMPONENT24, // Prefer 24 bit depth - GL_DEPTH_COMPONENT32, - GL_DEPTH24_STENCIL8_EXT // packed depth / stencil -}; -static const uchar depthBits[] = -{ - 0,16,24,32,24 -}; -#define DEPTHFORMAT_COUNT (sizeof(depthFormats)/sizeof(GLenum)) - - GLFBOManager::GLFBOManager(bool atimode): - mATIMode(atimode) - { - detectFBOFormats(); - - glGenFramebuffersEXT(1, &mTempFBO); - } - - GLFBOManager::~GLFBOManager() - { - if(!mRenderBufferMap.empty()) - { - LogManager::getSingleton().logWarning("GLFBOManager destructor called, but not all renderbuffers were released."); - } - - glDeleteFramebuffersEXT(1, &mTempFBO); - } - - void GLFBOManager::_createTempFramebuffer(GLuint internalfmt, GLuint fmt, GLenum type, GLuint &fb, GLuint &tid) - { - // NB we bypass state cache, this method is only called on startup and not after - // GLStateCacheManager::initializeCache - - glGenFramebuffersEXT(1, &fb); - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb); - if (fmt != GL_NONE) - { - if (tid) - glDeleteTextures(1, &tid); - - // Create and attach texture - glGenTextures(1, &tid); - glBindTexture(GL_TEXTURE_2D, tid); - - // Set some default parameters so it won't fail on NVidia cards - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - - glTexImage2D(GL_TEXTURE_2D, 0, internalfmt, PROBE_SIZE, PROBE_SIZE, 0, fmt, type, 0); - glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, - fmt == GL_DEPTH_COMPONENT ? GL_DEPTH_ATTACHMENT_EXT - : GL_COLOR_ATTACHMENT0_EXT, - GL_TEXTURE_2D, tid, 0); - } - else - { - // Draw to nowhere -- stencil/depth only - glDrawBuffer(GL_NONE); - glReadBuffer(GL_NONE); - } - } - - /** Try a certain FBO format, and return the status. Also sets mDepthRB and mStencilRB. - @return true if this combo is supported - false if this combo is not supported - */ - GLuint GLFBOManager::_tryFormat(GLenum depthFormat, GLenum stencilFormat) - { - GLuint status, depthRB = 0, stencilRB = 0; - bool failed = false; // flag on GL errors - - if(depthFormat != GL_NONE) - { - /// Generate depth renderbuffer - glGenRenderbuffersEXT(1, &depthRB); - /// Bind it to FBO - glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depthRB); - - /// Allocate storage for depth buffer - glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, depthFormat, - PROBE_SIZE, PROBE_SIZE); - - /// Attach depth - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, - GL_RENDERBUFFER_EXT, depthRB); - } - - if(stencilFormat != GL_NONE) - { - /// Generate stencil renderbuffer - glGenRenderbuffersEXT(1, &stencilRB); - /// Bind it to FBO - glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, stencilRB); - glGetError(); // NV hack - /// Allocate storage for stencil buffer - glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, stencilFormat, - PROBE_SIZE, PROBE_SIZE); - if(glGetError() != GL_NO_ERROR) // NV hack - failed = true; - /// Attach stencil - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, - GL_RENDERBUFFER_EXT, stencilRB); - if(glGetError() != GL_NO_ERROR) // NV hack - failed = true; - } - - status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); - /// If status is negative, clean up - // Detach and destroy - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0); - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0); - - if (depthRB) - glDeleteRenderbuffersEXT(1, &depthRB); - if (stencilRB) - glDeleteRenderbuffersEXT(1, &stencilRB); - - return status == GL_FRAMEBUFFER_COMPLETE_EXT && !failed; - } - - /** Try a certain packed depth/stencil format, and return the status. - @return true if this combo is supported - false if this combo is not supported - */ - bool GLFBOManager::_tryPackedFormat(GLenum packedFormat) - { - GLuint packedRB = 0; - bool failed = false; // flag on GL errors - - /// Generate renderbuffer - glGenRenderbuffersEXT(1, &packedRB); - - /// Bind it to FBO - glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, packedRB); - - /// Allocate storage for buffer - glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, packedFormat, PROBE_SIZE, PROBE_SIZE); - glGetError(); // NV hack - - /// Attach depth - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, - GL_RENDERBUFFER_EXT, packedRB); - if(glGetError() != GL_NO_ERROR) // NV hack - failed = true; - - /// Attach stencil - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, - GL_RENDERBUFFER_EXT, packedRB); - if(glGetError() != GL_NO_ERROR) // NV hack - failed = true; - - GLuint status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); - - /// Detach and destroy - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0); - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0); - glDeleteRenderbuffersEXT(1, &packedRB); - - return status == GL_FRAMEBUFFER_COMPLETE_EXT && !failed; - } - - /** Detect which internal formats are allowed as RTT - Also detect what combinations of stencil and depth are allowed with this internal - format. - */ - void GLFBOManager::detectFBOFormats() - { - // Try all formats, and report which ones work as target - GLuint fb = 0, tid = 0; - GLint old_drawbuffer = 0, old_readbuffer = 0; - - glGetIntegerv (GL_DRAW_BUFFER, &old_drawbuffer); - glGetIntegerv (GL_READ_BUFFER, &old_readbuffer); - - for(size_t x=0; xbestscore) - { - bestscore = desirability; - bestmode = mode; - } - } - *depthFormat = depthFormats[props.modes[bestmode].depth]; - *stencilFormat = requestDepthOnly ? 0 : stencilFormats[props.modes[bestmode].stencil]; - } - - GLFBORenderTexture *GLFBOManager::createRenderTexture(const String &name, - const GLSurfaceDesc &target, bool writeGamma, uint fsaa) - { - GLFBORenderTexture *retval = new GLFBORenderTexture(this, name, target, writeGamma, fsaa); - return retval; - } - //--------------------------------------------------------------------- - void GLFBOManager::bind(RenderTarget *target) - { - /// Check if the render target is in the rendertarget->FBO map - if(auto fbo = dynamic_cast(target)->getFBO()) - fbo->bind(true); - else - // Old style context (window/pbuffer) or copying render texture - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); - } - - GLSurfaceDesc GLFBOManager::requestRenderBuffer(GLenum format, uint32 width, uint32 height, uint fsaa) - { - GLSurfaceDesc retval; - retval.buffer = 0; // Return 0 buffer if GL_NONE is requested - if(format != GL_NONE) - { - RBFormat key(format, width, height, fsaa); - RenderBufferMap::iterator it = mRenderBufferMap.find(key); - if(it != mRenderBufferMap.end()) - { - retval.buffer = it->second.buffer; - retval.zoffset = 0; - retval.numSamples = fsaa; - // Increase refcount - ++it->second.refcount; - } - else - { - // New one - GLRenderBuffer *rb = new GLRenderBuffer(format, width, height, fsaa); - mRenderBufferMap[key] = RBRef(rb); - retval.buffer = rb; - retval.zoffset = 0; - retval.numSamples = fsaa; - } - } - //std::cerr << "Requested renderbuffer with format " << std::hex << format << std::dec << " of " << width << "x" << height << " :" << retval.buffer << std::endl; - return retval; - } -} diff --git a/RenderSystems/GL/src/OgreGLFrameBufferObject.cpp b/RenderSystems/GL/src/OgreGLFrameBufferObject.cpp deleted file mode 100755 index 34445d72a77..00000000000 --- a/RenderSystems/GL/src/OgreGLFrameBufferObject.cpp +++ /dev/null @@ -1,273 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLFrameBufferObject.h" -#include "OgreGLPixelFormat.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreRoot.h" -#include "OgreGLHardwarePixelBuffer.h" -#include "OgreGLFBORenderTexture.h" -#include "OgreGLDepthBufferCommon.h" -#include "OgreGLRenderSystemCommon.h" - -namespace Ogre { - -//----------------------------------------------------------------------------- - GLFrameBufferObject::GLFrameBufferObject(GLFBOManager *manager, uint fsaa): - GLFrameBufferObjectCommon(fsaa), mManager(manager) - { - // Generate framebuffer object - glGenFramebuffersEXT(1, &mFB); - // check multisampling - if (GLAD_GL_EXT_framebuffer_blit && GLAD_GL_EXT_framebuffer_multisample) - { - // check samples supported - GLint maxSamples; - glGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSamples); - mNumSamples = std::min(mNumSamples, (GLsizei)maxSamples); - } - else - { - mNumSamples = 0; - } - // will we need a second FBO to do multisampling? - if (mNumSamples) - { - glGenFramebuffersEXT(1, &mMultisampleFB); - } - else - { - mMultisampleFB = 0; - } - } - GLFrameBufferObject::~GLFrameBufferObject() - { - mManager->releaseRenderBuffer(mDepth); - mManager->releaseRenderBuffer(mStencil); - mManager->releaseRenderBuffer(mMultisampleColourBuffer); - // Delete framebuffer object - glDeleteFramebuffersEXT(1, &mFB); - if (mMultisampleFB) - glDeleteFramebuffersEXT(1, &mMultisampleFB); - - } - void GLFrameBufferObject::initialise() - { - // Release depth and stencil, if they were bound - mManager->releaseRenderBuffer(mDepth); - mManager->releaseRenderBuffer(mStencil); - mManager->releaseRenderBuffer(mMultisampleColourBuffer); - // First buffer must be bound - if(!mColour[0].buffer) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Attachment 0 must have surface attached", - "GLFrameBufferObject::initialise"); - } - - // If we're doing multisampling, then we need another FBO which contains a - // renderbuffer which is set up to multisample, and we'll blit it to the final - // FBO afterwards to perform the multisample resolve. In that case, the - // mMultisampleFB is bound during rendering and is the one with a depth/stencil - - // Store basic stats - uint32 width = mColour[0].buffer->getWidth(); - uint32 height = mColour[0].buffer->getHeight(); - GLuint format = mColour[0].buffer->getGLFormat(); - - auto rsc = Root::getSingleton().getRenderSystem()->getCapabilities(); - ushort maxSupportedMRTs = rsc->getNumMultiRenderTargets(); - - // Bind simple buffer to add colour attachments - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mFB); - - // Bind all attachment points to frame buffer - for(unsigned int x=0; xgetWidth() != width || mColour[x].buffer->getHeight() != height) - { - StringStream ss; - ss << "Attachment " << x << " has incompatible size "; - ss << mColour[x].buffer->getWidth() << "x" << mColour[x].buffer->getHeight(); - ss << ". It must be of the same as the size of surface 0, "; - ss << width << "x" << height; - ss << "."; - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLFrameBufferObject::initialise"); - } - - bool isDepth = PixelUtil::isDepth(mColour[x].buffer->getFormat()); - mColour[x].buffer->bindToFramebuffer( - isDepth ? GL_DEPTH_ATTACHMENT_EXT : (GL_COLOR_ATTACHMENT0_EXT + x), mColour[x].zoffset); - } - else - { - // Detach - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT+x, - GL_RENDERBUFFER_EXT, 0); - } - } - - // Now deal with depth / stencil - if (mMultisampleFB && !PixelUtil::isDepth(getFormat())) - { - // Bind multisample buffer - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mMultisampleFB); - - // Create AA render buffer (colour) - // note, this can be shared too because we blit it to the final FBO - // right after the render is finished - mMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples); - - // Attach it, because we won't be attaching below and non-multisample has - // actually been attached to other FBO - mMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0_EXT, - mMultisampleColourBuffer.zoffset); - - // depth & stencil will be dealt with below - - } - - // Depth buffer is not handled here anymore. - // See GLFrameBufferObject::attachDepthBuffer() & RenderSystem::setDepthBufferFor() - - // Do glDrawBuffer calls - GLenum bufs[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; - GLsizei n=0; - for(unsigned int x=0; xgetFormat()); - bufs[x] = isDepth ? GL_NONE : (GL_COLOR_ATTACHMENT0_EXT + x); - // Keep highest used buffer + 1 - if(!isDepth) - n = x+1; - } - else - { - bufs[x] = GL_NONE; - } - } - - if(glDrawBuffers) - // Drawbuffer extension supported, use it - glDrawBuffers(n, bufs); - else - // In this case, the capabilities will not show more than 1 simultaneaous render target. - glDrawBuffer(bufs[0]); - - // Check status - GLuint status; - status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); - - // Bind main buffer - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); - - switch(status) - { - case GL_FRAMEBUFFER_COMPLETE_EXT: - // All is good - break; - case GL_FRAMEBUFFER_UNSUPPORTED_EXT: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "All framebuffer formats with this texture internal format unsupported", - "GLFrameBufferObject::initialise"); - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Framebuffer incomplete or other FBO status error", - "GLFrameBufferObject::initialise"); - } - - } - bool GLFrameBufferObject::bind(bool recreateIfNeeded) - { - // Bind it to FBO - const GLuint fb = mMultisampleFB ? mMultisampleFB : mFB; - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb); - return mContext != 0; - } - - void GLFrameBufferObject::swapBuffers() - { - if (mMultisampleFB) - { - GLint oldfb = 0; - glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, &oldfb); - - // Blit from multisample buffer to final buffer, triggers resolve - uint32 width = mColour[0].buffer->getWidth(); - uint32 height = mColour[0].buffer->getHeight(); - glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, mMultisampleFB); - glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, mFB); - glBlitFramebufferEXT(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST); - - // Unbind - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, oldfb); - } - } - - void GLFrameBufferObject::attachDepthBuffer( DepthBuffer *depthBuffer ) - { - auto glDepthBuffer = static_cast(depthBuffer); - - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mMultisampleFB ? mMultisampleFB : mFB ); - - if( glDepthBuffer ) - { - auto *depthBuf = glDepthBuffer->getDepthBuffer(); - auto *stencilBuf = glDepthBuffer->getStencilBuffer(); - - // Attach depth buffer, if it has one. - if( depthBuf ) - depthBuf->bindToFramebuffer( GL_DEPTH_ATTACHMENT_EXT, 0 ); - - // Attach stencil buffer, if it has one. - if( stencilBuf ) - stencilBuf->bindToFramebuffer( GL_STENCIL_ATTACHMENT_EXT, 0 ); - } - else - { - glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, - GL_RENDERBUFFER_EXT, 0); - glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, - GL_RENDERBUFFER_EXT, 0); - } - } - //----------------------------------------------------------------------------- - void GLFrameBufferObject::detachDepthBuffer() - { - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mMultisampleFB ? mMultisampleFB : mFB ); - glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0 ); - glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, - GL_RENDERBUFFER_EXT, 0 ); - } -} diff --git a/RenderSystems/GL/src/OgreGLGpuNvparseProgram.cpp b/RenderSystems/GL/src/OgreGLGpuNvparseProgram.cpp deleted file mode 100644 index 99df39ca2e6..00000000000 --- a/RenderSystems/GL/src/OgreGLGpuNvparseProgram.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLGpuNvparseProgram.h" -#include "OgreException.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" -#include "OgreRenderSystemCapabilities.h" -#include "OgreLogManager.h" -#include "nvparse.h" - -namespace Ogre { - -GLGpuNvparseProgram::GLGpuNvparseProgram(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - : GLGpuProgram(creator, name, handle, group, isManual, loader) -{ - mProgramID = glGenLists(1); -} - -GLGpuNvparseProgram::~GLGpuNvparseProgram() -{ - // have to call this here reather than in Resource destructor - // since calling virtual methods in base destructors causes crash - unload(); -} - -void GLGpuNvparseProgram::bindProgram(void) -{ - glCallList(mProgramID); - glEnable(GL_TEXTURE_SHADER_NV); - glEnable(GL_REGISTER_COMBINERS_NV); - glEnable(GL_PER_STAGE_CONSTANTS_NV); -} - -void GLGpuNvparseProgram::unbindProgram(void) -{ - - glDisable(GL_TEXTURE_SHADER_NV); - glDisable(GL_REGISTER_COMBINERS_NV); - glDisable(GL_PER_STAGE_CONSTANTS_NV); -} - -void GLGpuNvparseProgram::bindProgramParameters(GpuProgramParametersSharedPtr params, uint16 mask) -{ - // NB, register combiners uses 2 constants per texture stage (0 and 1) - // We have stored these as (stage * 2) + const_index in the physical buffer - // There are no other parameters in a register combiners shader - const float* floatList = params->getFloatPointer(0); - for (size_t i = 0; i < params->getConstantList().size()/4; ++i) - { - GLenum combinerStage = GL_COMBINER0_NV + (unsigned int)(i / 2); - GLenum pname = GL_CONSTANT_COLOR0_NV + (i % 2); - glCombinerStageParameterfvNV(combinerStage, pname, floatList + i); - } -} -void GLGpuNvparseProgram::unloadImpl(void) -{ - glDeleteLists(mProgramID,1); -} - -void GLGpuNvparseProgram::loadFromSource(void) -{ - glNewList(mProgramID, GL_COMPILE); - - String::size_type pos = mSource.find("!!"); - - while (pos != String::npos) { - String::size_type newPos = mSource.find("!!", pos + 1); - - String script = mSource.substr(pos, newPos - pos); - nvparse(script.c_str(), 0); - - for (char* const * errors= nvparse_get_errors(); *errors; errors++) - { - LogManager::getSingleton().logMessage("Warning: nvparse reported the following errors:"); - LogManager::getSingleton().logMessage("\t" + String(*errors)); - } - - pos = newPos; - } - - glEndList(); -} - -} \ No newline at end of file diff --git a/RenderSystems/GL/src/OgreGLGpuProgram.cpp b/RenderSystems/GL/src/OgreGLGpuProgram.cpp deleted file mode 100644 index b320ae21776..00000000000 --- a/RenderSystems/GL/src/OgreGLGpuProgram.cpp +++ /dev/null @@ -1,167 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLGpuProgram.h" -#include "OgreException.h" -#include "OgreStringConverter.h" -#include "OgreLogManager.h" -#include "OgreGLSLProgramCommon.h" - -namespace Ogre { - -GLenum GLArbGpuProgram::getProgramType() const -{ - switch (mType) - { - case GPT_VERTEX_PROGRAM: - default: - return GL_VERTEX_PROGRAM_ARB; - case GPT_GEOMETRY_PROGRAM: - return GL_GEOMETRY_PROGRAM_NV; - case GPT_FRAGMENT_PROGRAM: - return GL_FRAGMENT_PROGRAM_ARB; - } -} - -GLGpuProgram::GLGpuProgram(ResourceManager* creator, const String& name, - ResourceHandle handle, const String& group, bool isManual, - ManualResourceLoader* loader) - : GpuProgram(creator, name, handle, group, isManual, loader) -{ - if (createParamDictionary("GLGpuProgram")) - { - setupBaseParamDictionary(); - } -} - -GLGpuProgram::~GLGpuProgram() -{ - // have to call this here reather than in Resource destructor - // since calling virtual methods in base destructors causes crash - unload(); -} - -bool GLGpuProgramBase::isAttributeValid(VertexElementSemantic semantic, uint index) -{ - // default implementation - switch(semantic) - { - case VES_POSITION: - case VES_NORMAL: - case VES_DIFFUSE: - case VES_SPECULAR: - case VES_TEXTURE_COORDINATES: - return false; - case VES_BLEND_WEIGHTS: - case VES_BLEND_INDICES: - case VES_BINORMAL: - case VES_TANGENT: - return true; // with default binding - } - - return false; -} - -GLArbGpuProgram::GLArbGpuProgram(ResourceManager* creator, const String& name, - ResourceHandle handle, const String& group, bool isManual, - ManualResourceLoader* loader) - : GLGpuProgram(creator, name, handle, group, isManual, loader) -{ - glGenProgramsARB(1, &mProgramID); -} - -GLArbGpuProgram::~GLArbGpuProgram() -{ - // have to call this here reather than in Resource destructor - // since calling virtual methods in base destructors causes crash - unload(); -} - -void GLArbGpuProgram::bindProgram(void) -{ - glEnable(getProgramType()); - glBindProgramARB(getProgramType(), mProgramID); -} - -void GLArbGpuProgram::unbindProgram(void) -{ - glBindProgramARB(getProgramType(), 0); - glDisable(getProgramType()); -} - -void GLArbGpuProgram::bindProgramParameters(GpuProgramParametersSharedPtr params, uint16 mask) -{ - GLenum type = getProgramType(); - - // only supports float constants - GpuLogicalBufferStructPtr floatStruct = params->getLogicalBufferStruct(); - - for (GpuLogicalIndexUseMap::const_iterator i = floatStruct->map.begin(); - i != floatStruct->map.end(); ++i) - { - if (i->second.variability & mask) - { - GLuint logicalIndex = static_cast(i->first); - const float* pFloat = params->getFloatPointer(i->second.physicalIndex); - // Iterate over the params, set in 4-float chunks (low-level) - for (size_t j = 0; j < i->second.currentSize; j+=4) - { - glProgramLocalParameter4fvARB(type, logicalIndex, pFloat); - pFloat += 4; - ++logicalIndex; - } - } - } -} - -void GLArbGpuProgram::unloadImpl(void) -{ - glDeleteProgramsARB(1, &mProgramID); -} - -void GLArbGpuProgram::loadFromSource(void) -{ - if (GL_INVALID_OPERATION == glGetError()) { - LogManager::getSingleton().logMessage("Invalid Operation before loading program "+mName, LML_CRITICAL); - - } - glBindProgramARB(getProgramType(), mProgramID); - glProgramStringARB(getProgramType(), GL_PROGRAM_FORMAT_ASCII_ARB, (GLsizei)mSource.length(), mSource.c_str()); - - if (GL_INVALID_OPERATION == glGetError()) - { - GLint errPos; - glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errPos); - const char* errStr = (const char*)glGetString(GL_PROGRAM_ERROR_STRING_ARB); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "'" + mName + "' " + errStr); - } - glBindProgramARB(getProgramType(), 0); -} - - -} diff --git a/RenderSystems/GL/src/OgreGLHardwareBuffer.cpp b/RenderSystems/GL/src/OgreGLHardwareBuffer.cpp deleted file mode 100644 index 73e1f7c9faf..00000000000 --- a/RenderSystems/GL/src/OgreGLHardwareBuffer.cpp +++ /dev/null @@ -1,225 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreGLHardwareBufferManager.h" -#include "OgreGLHardwareBuffer.h" -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreGLStateCacheManager.h" -#include "OgreRoot.h" -#include "OgreGLRenderSystem.h" - -namespace Ogre { - - //--------------------------------------------------------------------- - GLHardwareVertexBuffer::GLHardwareVertexBuffer(GLenum target, size_t sizeInBytes, - Usage usage, bool useShadowBuffer) - : HardwareBuffer(usage, useShadowBuffer), mTarget(target), mLockedToScratch(false), - mScratchOffset(0), mScratchSize(0), mScratchPtr(0), mScratchUploadOnUnlock(false) - { - mSizeInBytes = sizeInBytes; - mRenderSystem = static_cast(Root::getSingleton().getRenderSystem()); - - glGenBuffersARB( 1, &mBufferId ); - - if (!mBufferId) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Cannot create GL buffer"); - } - - mRenderSystem->_getStateCacheManager()->bindGLBuffer(mTarget, mBufferId); - - // Initialise mapped buffer and set usage - glBufferDataARB(mTarget, mSizeInBytes, NULL, GLHardwareBufferManager::getGLUsage(usage)); - - //std::cerr << "creating vertex buffer = " << mBufferId << std::endl; - } - //--------------------------------------------------------------------- - GLHardwareVertexBuffer::~GLHardwareVertexBuffer() - { - if(GLStateCacheManager* stateCacheManager = mRenderSystem->_getStateCacheManager()) - stateCacheManager->deleteGLBuffer(mTarget, mBufferId); - } - //--------------------------------------------------------------------- - void* GLHardwareVertexBuffer::lockImpl(size_t offset, - size_t length, LockOptions options) - { - void* retPtr = 0; - - GLHardwareBufferManager* glBufManager = static_cast(HardwareBufferManager::getSingletonPtr()); - - // Try to use scratch buffers for smaller buffers - if( length < glBufManager->getGLMapBufferThreshold() ) - { - // if this fails, we fall back on mapping - retPtr = glBufManager->allocateScratch((uint32)length); - - if (retPtr) - { - mLockedToScratch = true; - mScratchOffset = offset; - mScratchSize = length; - mScratchPtr = retPtr; - mScratchUploadOnUnlock = (options != HBL_READ_ONLY); - - if (options != HBL_DISCARD && options != HBL_NO_OVERWRITE) - { - // have to read back the data before returning the pointer - readData(offset, length, retPtr); - } - } - } - - if (!retPtr) - { - GLenum access = 0; - // Use glMapBuffer - mRenderSystem->_getStateCacheManager()->bindGLBuffer(mTarget, mBufferId); - // Use glMapBuffer - if(options == HBL_DISCARD) // TODO: check possibility to use GL_MAP_UNSYNCHRONIZED_BIT for HBL_NO_OVERWRITE locking promise - { - // Discard the buffer - glBufferDataARB(mTarget, mSizeInBytes, NULL, GLHardwareBufferManager::getGLUsage(mUsage)); - } - if (mUsage & HBU_DETAIL_WRITE_ONLY) - access = GL_WRITE_ONLY_ARB; - else if (options == HBL_READ_ONLY) - access = GL_READ_ONLY_ARB; - else - access = GL_READ_WRITE_ARB; - - void* pBuffer = glMapBufferARB( mTarget, access); - if(pBuffer == 0) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Buffer: Out of memory"); - } - - // return offsetted - retPtr = static_cast(static_cast(pBuffer) + offset); - - mLockedToScratch = false; - } - - return retPtr; - } - //--------------------------------------------------------------------- - void GLHardwareVertexBuffer::unlockImpl(void) - { - if (mLockedToScratch) - { - if (mScratchUploadOnUnlock) - { - // have to write the data back to vertex buffer - writeData(mScratchOffset, mScratchSize, mScratchPtr, - mScratchOffset == 0 && mScratchSize == getSizeInBytes()); - } - - // deallocate from scratch buffer - static_cast( - HardwareBufferManager::getSingletonPtr())->deallocateScratch(mScratchPtr); - - mLockedToScratch = false; - } - else - { - mRenderSystem->_getStateCacheManager()->bindGLBuffer(mTarget, mBufferId); - - if(!glUnmapBufferARB( mTarget )) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Buffer data corrupted, please reload"); - } - } - } - //--------------------------------------------------------------------- - void GLHardwareVertexBuffer::readData(size_t offset, size_t length, - void* pDest) - { - if(mShadowBuffer) - { - mShadowBuffer->readData(offset, length, pDest); - } - else - { - // get data from the real buffer - mRenderSystem->_getStateCacheManager()->bindGLBuffer(mTarget, mBufferId); - - glGetBufferSubDataARB(mTarget, offset, length, pDest); - } - } - //--------------------------------------------------------------------- - void GLHardwareVertexBuffer::writeData(size_t offset, size_t length, - const void* pSource, bool discardWholeBuffer) - { - mRenderSystem->_getStateCacheManager()->bindGLBuffer(mTarget, mBufferId); - - // Update the shadow buffer - if(mShadowBuffer) - { - mShadowBuffer->writeData(offset, length, pSource, discardWholeBuffer); - } - - if (offset == 0 && length == mSizeInBytes) - { - glBufferDataARB(mTarget, mSizeInBytes, pSource, - GLHardwareBufferManager::getGLUsage(mUsage)); - } - else - { - if(discardWholeBuffer) - { - glBufferDataARB(mTarget, mSizeInBytes, NULL, - GLHardwareBufferManager::getGLUsage(mUsage)); - } - - // Now update the real buffer - glBufferSubDataARB(mTarget, offset, length, pSource); - } - } - //--------------------------------------------------------------------- - void GLHardwareVertexBuffer::_updateFromShadow(void) - { - if (mShadowBuffer && mShadowUpdated && !mSuppressHardwareUpdate) - { - HardwareBufferLockGuard shadowLock(mShadowBuffer.get(), mLockStart, mLockSize, HBL_READ_ONLY); - - mRenderSystem->_getStateCacheManager()->bindGLBuffer(mTarget, mBufferId); - - // Update whole buffer if possible, otherwise normal - if (mLockStart == 0 && mLockSize == mSizeInBytes) - { - glBufferDataARB(mTarget, mSizeInBytes, shadowLock.pData, - GLHardwareBufferManager::getGLUsage(mUsage)); - } - else - { - glBufferSubDataARB(mTarget, mLockStart, mLockSize, shadowLock.pData); - } - - mShadowUpdated = false; - } - } -} diff --git a/RenderSystems/GL/src/OgreGLHardwareBufferManager.cpp b/RenderSystems/GL/src/OgreGLHardwareBufferManager.cpp deleted file mode 100644 index 9846fe44c18..00000000000 --- a/RenderSystems/GL/src/OgreGLHardwareBufferManager.cpp +++ /dev/null @@ -1,255 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreGLHardwareBufferManager.h" -#include "OgreGLHardwareBuffer.h" -#include "OgreGLRenderSystem.h" -#include "OgreGLRenderToVertexBuffer.h" -#include "OgreHardwareBuffer.h" -#include "OgreRoot.h" -#include "OgreRenderSystemCapabilities.h" - -namespace Ogre { - //----------------------------------------------------------------------- - // Scratch pool management (32 bit structure) - struct GLScratchBufferAlloc - { - /// Size in bytes - uint32 size: 31; - /// Free? (pack with size) - uint32 free: 1; - }; - #define SCRATCH_POOL_SIZE 1 * 1024 * 1024 - //--------------------------------------------------------------------- - GLHardwareBufferManager::GLHardwareBufferManager() - : mScratchBufferPool(NULL), mMapBufferThreshold(OGRE_GL_DEFAULT_MAP_BUFFER_THRESHOLD) - { - mRenderSystem = static_cast(Root::getSingleton().getRenderSystem()); - - // Init scratch pool - // TODO make it a configurable size? - // 32-bit aligned buffer - mScratchBufferPool = static_cast(OGRE_MALLOC_SIMD(SCRATCH_POOL_SIZE, MEMCATEGORY_GEOMETRY)); - GLScratchBufferAlloc* ptrAlloc = (GLScratchBufferAlloc*)mScratchBufferPool; - ptrAlloc->size = SCRATCH_POOL_SIZE - sizeof(GLScratchBufferAlloc); - ptrAlloc->free = 1; - mMapBufferThreshold = 0; - } - //----------------------------------------------------------------------- - GLHardwareBufferManager::~GLHardwareBufferManager() - { - destroyAllDeclarations(); - destroyAllBindings(); - - OGRE_FREE_SIMD(mScratchBufferPool, MEMCATEGORY_GEOMETRY); - } - //----------------------------------------------------------------------- - HardwareVertexBufferSharedPtr GLHardwareBufferManager::createVertexBuffer( - size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer) - { - auto impl = new GLHardwareVertexBuffer(GL_ARRAY_BUFFER, vertexSize * numVerts, usage, useShadowBuffer); - auto buf = std::make_shared(this, vertexSize, numVerts, impl); - { - OGRE_LOCK_MUTEX(mVertexBuffersMutex); - mVertexBuffers.insert(buf.get()); - } - return buf; - } - //----------------------------------------------------------------------- - HardwareIndexBufferSharedPtr - GLHardwareBufferManager::createIndexBuffer( - HardwareIndexBuffer::IndexType itype, size_t numIndexes, - HardwareBuffer::Usage usage, bool useShadowBuffer) - { - // Calculate the size of the indexes - auto indexSize = HardwareIndexBuffer::indexSize(itype); - auto impl = new GLHardwareBuffer(GL_ELEMENT_ARRAY_BUFFER, indexSize * numIndexes, usage, useShadowBuffer); - - return std::make_shared(this, itype, numIndexes, impl); - } - //--------------------------------------------------------------------- - RenderToVertexBufferSharedPtr - GLHardwareBufferManager::createRenderToVertexBuffer() - { - return RenderToVertexBufferSharedPtr(new GLRenderToVertexBuffer); - } - //--------------------------------------------------------------------- - GLenum GLHardwareBufferManager::getGLUsage(unsigned int usage) - { - return (usage == HBU_GPU_TO_CPU) ? GL_STATIC_READ - : (usage == HBU_GPU_ONLY) ? GL_STATIC_DRAW : GL_DYNAMIC_DRAW; - } - //--------------------------------------------------------------------- - GLenum GLHardwareBufferManager::getGLType(unsigned int type) - { - switch(type) - { - case VET_FLOAT1: - case VET_FLOAT2: - case VET_FLOAT3: - case VET_FLOAT4: - return GL_FLOAT; - case VET_SHORT1: - case VET_SHORT2: - case VET_SHORT3: - case VET_SHORT4: - case VET_SHORT2_NORM: - case VET_SHORT4_NORM: - return GL_SHORT; - case VET_UBYTE4: - case VET_UBYTE4_NORM: - return GL_UNSIGNED_BYTE; - case VET_BYTE4: - case VET_BYTE4_NORM: - return GL_BYTE; - case VET_USHORT2_NORM: - case VET_USHORT4_NORM: - return GL_UNSIGNED_SHORT; - default: - return 0; - }; - } - //--------------------------------------------------------------------- - //--------------------------------------------------------------------- - void* GLHardwareBufferManager::allocateScratch(uint32 size) - { - // simple forward link search based on alloc sizes - // not that fast but the list should never get that long since not many - // locks at once (hopefully) - OGRE_LOCK_MUTEX(mScratchMutex); - - - // Alignment - round up the size to 32 bits - // control blocks are 32 bits too so this packs nicely - if (size % 4 != 0) - { - size += 4 - (size % 4); - } - - uint32 bufferPos = 0; - while (bufferPos < SCRATCH_POOL_SIZE) - { - GLScratchBufferAlloc* pNext = (GLScratchBufferAlloc*)(mScratchBufferPool + bufferPos); - // Big enough? - if (pNext->free && pNext->size >= size) - { - // split? And enough space for control block - if(pNext->size > size + sizeof(GLScratchBufferAlloc)) - { - uint32 offset = (uint32)sizeof(GLScratchBufferAlloc) + size; - - GLScratchBufferAlloc* pSplitAlloc = (GLScratchBufferAlloc*) - (mScratchBufferPool + bufferPos + offset); - pSplitAlloc->free = 1; - // split size is remainder minus new control block - pSplitAlloc->size = pNext->size - size - sizeof(GLScratchBufferAlloc); - - // New size of current - pNext->size = size; - } - // allocate and return - pNext->free = 0; - - // return pointer just after this control block (++ will do that for us) - return ++pNext; - - } - - bufferPos += (uint32)sizeof(GLScratchBufferAlloc) + pNext->size; - - } - - // no available alloc - return 0; - - } - //--------------------------------------------------------------------- - void GLHardwareBufferManager::deallocateScratch(void* ptr) - { - OGRE_LOCK_MUTEX(mScratchMutex); - - // Simple linear search dealloc - uint32 bufferPos = 0; - GLScratchBufferAlloc* pLast = 0; - while (bufferPos < SCRATCH_POOL_SIZE) - { - GLScratchBufferAlloc* pCurrent = (GLScratchBufferAlloc*)(mScratchBufferPool + bufferPos); - - // Pointers match? - if ((mScratchBufferPool + bufferPos + sizeof(GLScratchBufferAlloc)) - == ptr) - { - // dealloc - pCurrent->free = 1; - - // merge with previous - if (pLast && pLast->free) - { - // adjust buffer pos - bufferPos -= (pLast->size + (uint32)sizeof(GLScratchBufferAlloc)); - // merge free space - pLast->size += pCurrent->size + sizeof(GLScratchBufferAlloc); - pCurrent = pLast; - } - - // merge with next - uint32 offset = bufferPos + pCurrent->size + (uint32)sizeof(GLScratchBufferAlloc); - if (offset < SCRATCH_POOL_SIZE) - { - GLScratchBufferAlloc* pNext = (GLScratchBufferAlloc*)( - mScratchBufferPool + offset); - if (pNext->free) - { - pCurrent->size += pNext->size + sizeof(GLScratchBufferAlloc); - } - } - - // done - return; - } - - bufferPos += (uint32)sizeof(GLScratchBufferAlloc) + pCurrent->size; - pLast = pCurrent; - - } - - // Should never get here unless there's a corruption - assert (false && "Memory deallocation error"); - - - } - //--------------------------------------------------------------------- - size_t GLHardwareBufferManager::getGLMapBufferThreshold() const - { - return mMapBufferThreshold; - } - //--------------------------------------------------------------------- - void GLHardwareBufferManager::setGLMapBufferThreshold( const size_t value ) - { - mMapBufferThreshold = value; - } -} diff --git a/RenderSystems/GL/src/OgreGLHardwareOcclusionQuery.cpp b/RenderSystems/GL/src/OgreGLHardwareOcclusionQuery.cpp deleted file mode 100644 index 9afca66ab59..00000000000 --- a/RenderSystems/GL/src/OgreGLHardwareOcclusionQuery.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLHardwareOcclusionQuery.h" -#include "OgreException.h" - -namespace Ogre { - -/** - * This is a class that is the base class of the query class for - * hardware occlusion testing. - * - * @author Lee Sandberg email: lee@abcmedia.se - * - * Updated on 12/7/2004 by Chris McGuirk - * - Implemented ARB_occlusion_query - * Updated on 13/9/2005 by Tuan Kuranes email: tuan.kuranes@free.fr - */ -//------------------------------------------------------------------ -/** - * Default object constructor - * - */ -GLHardwareOcclusionQuery::GLHardwareOcclusionQuery() -{ - glGenQueriesARB(1, &mQueryID ); -} -//------------------------------------------------------------------ -/** - * Object destructor - */ -GLHardwareOcclusionQuery::~GLHardwareOcclusionQuery() -{ - glDeleteQueriesARB(1, &mQueryID); -} -//------------------------------------------------------------------ -void GLHardwareOcclusionQuery::beginOcclusionQuery() -{ - glBeginQueryARB(GL_SAMPLES_PASSED_ARB, mQueryID); -} -//------------------------------------------------------------------ -void GLHardwareOcclusionQuery::endOcclusionQuery() -{ - glEndQueryARB(GL_SAMPLES_PASSED_ARB); -} -//------------------------------------------------------------------ -bool GLHardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments ) -{ - glGetQueryObjectuivARB(mQueryID, GL_QUERY_RESULT_ARB, (GLuint*)NumOfFragments); - mPixelCount = *NumOfFragments; - return true; -} -//------------------------------------------------------------------ -bool GLHardwareOcclusionQuery::isStillOutstanding(void) -{ - GLuint available = GL_FALSE; - - glGetQueryObjectuivARB(mQueryID, GL_QUERY_RESULT_AVAILABLE_ARB, &available); - - // GL_TRUE means a wait would occur - return !(available == GL_TRUE); -} - -} - - diff --git a/RenderSystems/GL/src/OgreGLHardwarePixelBuffer.cpp b/RenderSystems/GL/src/OgreGLHardwarePixelBuffer.cpp deleted file mode 100644 index 32b9c665e8e..00000000000 --- a/RenderSystems/GL/src/OgreGLHardwarePixelBuffer.cpp +++ /dev/null @@ -1,684 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreGLHardwarePixelBuffer.h" - -#include "OgreTextureManager.h" - -#include "OgreGLTexture.h" -#include "OgreGLRenderSystem.h" -#include "OgreGLPixelFormat.h" -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreBitwise.h" -#include "OgreGLFBORenderTexture.h" -#include "OgreRoot.h" -#include "OgreGLStateCacheManager.h" - -namespace Ogre { -//----------------------------------------------------------------------------- -void GLTextureBuffer::_blitFromMemory(const PixelBox &src, const Box &dst) -{ - if(!mBuffer.contains(src)) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "destination box out of range", - "GLHardwarePixelBuffer::blitFromMemory"); - PixelBox converted; - - if(GLPixelUtil::getGLInternalFormat(src.format) == 0) - { - // Extents match, but format is not accepted as valid source format for GL - // do conversion in temporary buffer - allocateBuffer(); - converted = mBuffer.getSubVolume(src); - PixelUtil::bulkPixelConversion(src, converted); - } - else - { - // No scaling or conversion needed - converted = src; - } - - upload(converted, dst); - freeBuffer(); -} -//----------------------------------------------------------------------------- -void GLTextureBuffer::blitToMemory(const Box &srcBox, const PixelBox &dst) -{ - if(!mBuffer.contains(srcBox)) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "source box out of range", - "GLHardwarePixelBuffer::blitToMemory"); - if(srcBox.getOrigin() == Vector3i(0, 0 ,0) && - srcBox.getSize() == getSize() && - dst.getSize() == getSize() && - GLPixelUtil::getGLInternalFormat(dst.format) != 0) - { - // The direct case: the user wants the entire texture in a format supported by GL - // so we don't need an intermediate buffer - download(dst); - } - else - { - // Use buffer for intermediate copy - allocateBuffer(); - // Download entire buffer - download(mBuffer); - if(srcBox.getSize() != dst.getSize()) - { - // We need scaling - Image::scale(mBuffer.getSubVolume(srcBox), dst, Image::FILTER_BILINEAR); - } - else - { - // Just copy the bit that we need - PixelUtil::bulkPixelConversion(mBuffer.getSubVolume(srcBox), dst); - } - freeBuffer(); - } -} -//********* GLTextureBuffer -GLTextureBuffer::GLTextureBuffer(GLRenderSystem* renderSystem, GLTexture* parent, GLint face, - GLint level, uint32 width, uint32 height, uint32 depth) - : GLHardwarePixelBufferCommon(width, height, depth, parent->getFormat(), (Usage)parent->getUsage()), - mTarget(parent->getGLTextureTarget()), mFaceTarget(0), mTextureID(parent->getGLID()), - mLevel(level), mHwGamma(parent->isHardwareGammaEnabled()), - mRenderSystem(renderSystem) -{ - // Get face identifier - mFaceTarget = mTarget; - if(mTarget == GL_TEXTURE_CUBE_MAP) - mFaceTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + face; - - // Get format - mGLInternalFormat = GLPixelUtil::getGLInternalFormat(mFormat, mHwGamma); - - // Log a message - /* - std::stringstream str; - str << "GLHardwarePixelBuffer constructed for texture " << mTextureID - << " face " << mFace << " level " << mLevel << ": " - << "width=" << mWidth << " height="<< mHeight << " depth=" << mDepth - << "format=" << PixelUtil::getFormatName(mFormat) << "(internal 0x" - << std::hex << value << ")"; - LogManager::getSingleton().logMessage( - LML_NORMAL, str.str()); - */ - // Set up pixel box - mBuffer = PixelBox(mWidth, mHeight, mDepth, mFormat); - - if(mWidth==0 || mHeight==0 || mDepth==0) - /// We are invalid, do not allocate a buffer - return; - // Allocate buffer - //if(mUsage & HBU_STATIC) - // allocateBuffer(); - // Is this a render target? - if(mUsage & TU_RENDERTARGET) - { - // Create render target for each slice - mSliceTRT.reserve(mDepth); - for(uint32 zoffset=0; zoffsetgetName(); - GLSurfaceDesc surface; - surface.buffer = this; - surface.zoffset = zoffset; - RenderTexture *trt = GLRTTManager::getSingleton().createRenderTexture(name, surface, mHwGamma, parent->getFSAA()); - mSliceTRT.push_back(trt); - Root::getSingleton().getRenderSystem()->attachRenderTarget(*mSliceTRT[zoffset]); - } - } -} -GLTextureBuffer::~GLTextureBuffer() -{ -} -//----------------------------------------------------------------------------- -void GLTextureBuffer::upload(const PixelBox &data, const Box &dest) -{ - mRenderSystem->_getStateCacheManager()->bindGLTexture( mTarget, mTextureID ); - if(PixelUtil::isCompressed(data.format)) - { - if(data.format != mFormat || !data.isConsecutive()) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Compressed images must be consecutive, in the source format", - "GLTextureBuffer::upload"); - GLenum format = GLPixelUtil::getGLInternalFormat(mFormat, mHwGamma); - // Data must be consecutive and at beginning of buffer as PixelStorei not allowed - // for compressed formats - switch(mTarget) { - case GL_TEXTURE_1D: - // some systems (e.g. old Apple) don't like compressed subimage calls - // so prefer non-sub versions - if (dest.left == 0) - { - glCompressedTexImage1DARB(GL_TEXTURE_1D, mLevel, - format, - dest.getWidth(), - 0, - data.getConsecutiveSize(), - data.data); - } - else - { - glCompressedTexSubImage1DARB(GL_TEXTURE_1D, mLevel, - dest.left, - dest.getWidth(), - format, data.getConsecutiveSize(), - data.data); - } - break; - case GL_TEXTURE_2D: - case GL_TEXTURE_CUBE_MAP: - // some systems (e.g. old Apple) don't like compressed subimage calls - // so prefer non-sub versions - if (dest.left == 0 && dest.top == 0) - { - glCompressedTexImage2DARB(mFaceTarget, mLevel, - format, - dest.getWidth(), - dest.getHeight(), - 0, - data.getConsecutiveSize(), - data.data); - } - else - { - glCompressedTexSubImage2DARB(mFaceTarget, mLevel, - dest.left, dest.top, - dest.getWidth(), dest.getHeight(), - format, data.getConsecutiveSize(), - data.data); - } - break; - case GL_TEXTURE_3D: - case GL_TEXTURE_2D_ARRAY_EXT: - // some systems (e.g. old Apple) don't like compressed subimage calls - // so prefer non-sub versions - if (dest.left == 0 && dest.top == 0 && dest.front == 0) - { - glCompressedTexImage3DARB(mTarget, mLevel, - format, - dest.getWidth(), - dest.getHeight(), - dest.getDepth(), - 0, - data.getConsecutiveSize(), - data.data); - } - else - { - glCompressedTexSubImage3DARB(mTarget, mLevel, - dest.left, dest.top, dest.front, - dest.getWidth(), dest.getHeight(), dest.getDepth(), - format, data.getConsecutiveSize(), - data.data); - } - break; - } - - } - else - { - if(data.getWidth() != data.rowPitch) - glPixelStorei(GL_UNPACK_ROW_LENGTH, data.rowPitch); - if(data.getWidth() > 0 && data.getHeight()*data.getWidth() != data.slicePitch) - glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, (data.slicePitch/data.getWidth())); - if((data.getWidth()*PixelUtil::getNumElemBytes(data.format)) & 3) { - // Standard alignment of 4 is not right - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - } - - void* pdata = data.getTopLeftFrontPixelPtr(); - - switch(mTarget) { - case GL_TEXTURE_1D: - glTexSubImage1D(GL_TEXTURE_1D, mLevel, - dest.left, - dest.getWidth(), - GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format), - pdata); - break; - case GL_TEXTURE_2D: - case GL_TEXTURE_CUBE_MAP: - glTexSubImage2D(mFaceTarget, mLevel, - dest.left, dest.top, - dest.getWidth(), dest.getHeight(), - GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format), - pdata); - break; - case GL_TEXTURE_3D: - case GL_TEXTURE_2D_ARRAY_EXT: - glTexSubImage3D( - mTarget, mLevel, - dest.left, dest.top, dest.front, - dest.getWidth(), dest.getHeight(), dest.getDepth(), - GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format), - pdata); - break; - } - } - - // TU_AUTOMIPMAP is only enabled when there are no custom mips - // so we do not have to care about overwriting - if((mUsage & TU_AUTOMIPMAP) && (mLevel == 0)) - { - glGenerateMipmapEXT(mTarget); - } - - // Restore defaults - glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); - glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0); - glPixelStorei(GL_UNPACK_ALIGNMENT, 4); -} -//----------------------------------------------------------------------------- -void GLTextureBuffer::download(const PixelBox &data) -{ - if(data.getSize() != getSize()) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "only download of entire buffer is supported by GL", - "GLTextureBuffer::download"); - mRenderSystem->_getStateCacheManager()->bindGLTexture( mTarget, mTextureID ); - if(PixelUtil::isCompressed(data.format)) - { - if(data.format != mFormat || !data.isConsecutive()) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Compressed images must be consecutive, in the source format", - "GLTextureBuffer::download"); - // Data must be consecutive and at beginning of buffer as PixelStorei not allowed - // for compressed formate - glGetCompressedTexImageARB(mFaceTarget, mLevel, data.data); - } - else - { - if(data.getWidth() != data.rowPitch) - glPixelStorei(GL_PACK_ROW_LENGTH, data.rowPitch); - if(data.getHeight()*data.getWidth() != data.slicePitch) - glPixelStorei(GL_PACK_IMAGE_HEIGHT, (data.slicePitch/data.getWidth())); - if((data.getWidth()*PixelUtil::getNumElemBytes(data.format)) & 3) { - // Standard alignment of 4 is not right - glPixelStorei(GL_PACK_ALIGNMENT, 1); - } - // We can only get the entire texture - glGetTexImage(mFaceTarget, mLevel, - GLPixelUtil::getGLOriginFormat(data.format), GLPixelUtil::getGLOriginDataType(data.format), - data.getTopLeftFrontPixelPtr()); - // Restore defaults - glPixelStorei(GL_PACK_ROW_LENGTH, 0); - glPixelStorei(GL_PACK_IMAGE_HEIGHT, 0); - glPixelStorei(GL_PACK_ALIGNMENT, 4); - } -} -//----------------------------------------------------------------------------- -void GLTextureBuffer::bindToFramebuffer(uint32 attachment, uint32 zoffset) -{ - assert(zoffset < mDepth); - switch(mTarget) - { - case GL_TEXTURE_1D: - glFramebufferTexture1DEXT(GL_FRAMEBUFFER_EXT, attachment, - mFaceTarget, mTextureID, mLevel); - break; - case GL_TEXTURE_2D: - case GL_TEXTURE_CUBE_MAP: - glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, attachment, - mFaceTarget, mTextureID, mLevel); - break; - case GL_TEXTURE_3D: - case GL_TEXTURE_2D_ARRAY_EXT: - glFramebufferTexture3DEXT(GL_FRAMEBUFFER_EXT, attachment, - mFaceTarget, mTextureID, mLevel, zoffset); - break; - } -} -//----------------------------------------------------------------------------- -void GLTextureBuffer::copyFromFramebuffer(uint32 zoffset) -{ - mRenderSystem->_getStateCacheManager()->bindGLTexture(mTarget, mTextureID); - switch(mTarget) - { - case GL_TEXTURE_1D: - glCopyTexSubImage1D(mFaceTarget, mLevel, 0, 0, 0, mWidth); - break; - case GL_TEXTURE_2D: - case GL_TEXTURE_CUBE_MAP: - glCopyTexSubImage2D(mFaceTarget, mLevel, 0, 0, 0, 0, mWidth, mHeight); - break; - case GL_TEXTURE_3D: - case GL_TEXTURE_2D_ARRAY_EXT: - glCopyTexSubImage3D(mFaceTarget, mLevel, 0, 0, zoffset, 0, 0, mWidth, mHeight); - break; - } -} -//----------------------------------------------------------------------------- -void GLTextureBuffer::blit(const HardwarePixelBufferSharedPtr &src, const Box &srcBox, const Box &dstBox) -{ - GLTextureBuffer *srct = static_cast(src.get()); - /// Check for FBO support first - /// Destination texture must be 1D, 2D, 3D, or Cube - /// Source texture must be 1D, 2D or 3D - - // Using this in Terrain composite map RTT interferes with Impostor RTT rendering in pagedgeometry - // I have no idea why! For the moment, disable when src is RTT - if(GLAD_GL_EXT_framebuffer_object && (src->getUsage() & TU_RENDERTARGET) == 0 && - (srct->mTarget==GL_TEXTURE_1D||srct->mTarget==GL_TEXTURE_2D - ||srct->mTarget==GL_TEXTURE_3D)&&mTarget!=GL_TEXTURE_2D_ARRAY_EXT) - { - blitFromTexture(srct, srcBox, dstBox); - } - else - { - GLHardwarePixelBufferCommon::blit(src, srcBox, dstBox); - } -} - -//----------------------------------------------------------------------------- -/// Very fast texture-to-texture blitter and hardware bi/trilinear scaling implementation using FBO -/// Destination texture must be 1D, 2D, 3D, or Cube -/// Source texture must be 1D, 2D or 3D -/// Supports compressed formats as both source and destination format, it will use the hardware DXT compressor -/// if available. -/// @author W.J. van der Laan -void GLTextureBuffer::blitFromTexture(GLTextureBuffer *src, const Box &srcBox, const Box &dstBox) -{ - //std::cerr << "GLTextureBuffer::blitFromTexture " << - //src->mTextureID << ":" << srcBox.left << "," << srcBox.top << "," << srcBox.right << "," << srcBox.bottom << " " << - //mTextureID << ":" << dstBox.left << "," << dstBox.top << "," << dstBox.right << "," << dstBox.bottom << std::endl; - /// Store reference to FBO manager - GLFBOManager *fboMan = static_cast(GLRTTManager::getSingletonPtr()); - - /// Save and clear GL state for rendering - glPushAttrib(GL_COLOR_BUFFER_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT | GL_ENABLE_BIT | - GL_FOG_BIT | GL_LIGHTING_BIT | GL_POLYGON_BIT | GL_SCISSOR_BIT | GL_STENCIL_BUFFER_BIT | - GL_TEXTURE_BIT | GL_VIEWPORT_BIT); - - // Important to disable all other texture units - RenderSystem* rsys = Root::getSingleton().getRenderSystem(); - rsys->_disableTextureUnitsFrom(0); - mRenderSystem->_getStateCacheManager()->activateGLTextureUnit(0); - - /// Disable alpha, depth and scissor testing, disable blending, - /// disable culling, disble lighting, disable fog and reset foreground - /// colour. - mRenderSystem->_getStateCacheManager()->setEnabled(GL_ALPHA_TEST, false); - mRenderSystem->_getStateCacheManager()->setEnabled(GL_DEPTH_TEST, false); - mRenderSystem->_getStateCacheManager()->setEnabled(GL_SCISSOR_TEST, false); - mRenderSystem->_getStateCacheManager()->setEnabled(GL_BLEND, false); - mRenderSystem->_getStateCacheManager()->setEnabled(GL_CULL_FACE, false); - mRenderSystem->_getStateCacheManager()->setEnabled(GL_LIGHTING, false); - mRenderSystem->_getStateCacheManager()->setEnabled(GL_FOG, false); - - /// Save and reset matrices - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - glLoadIdentity(); - glMatrixMode(GL_PROJECTION); - glPushMatrix(); - glLoadIdentity(); - glMatrixMode(GL_TEXTURE); - glPushMatrix(); - glLoadIdentity(); - - /// Set up source texture - mRenderSystem->_getStateCacheManager()->bindGLTexture(src->mTarget, src->mTextureID); - - /// Set filtering modes depending on the dimensions and source - if(srcBox.getSize()==dstBox.getSize()) - { - /// Dimensions match -- use nearest filtering (fastest and pixel correct) - mRenderSystem->_getStateCacheManager()->setTexParameteri(src->mTarget, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - mRenderSystem->_getStateCacheManager()->setTexParameteri(src->mTarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - } - else - { - /// Dimensions don't match -- use bi or trilinear filtering depending on the - /// source texture. - if(src->mUsage & TU_AUTOMIPMAP) - { - /// Automatic mipmaps, we can safely use trilinear filter which - /// brings greatly imporoved quality for minimisation. - mRenderSystem->_getStateCacheManager()->setTexParameteri(src->mTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - mRenderSystem->_getStateCacheManager()->setTexParameteri(src->mTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - } - else - { - /// Manual mipmaps, stay safe with bilinear filtering so that no - /// intermipmap leakage occurs. - mRenderSystem->_getStateCacheManager()->setTexParameteri(src->mTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - mRenderSystem->_getStateCacheManager()->setTexParameteri(src->mTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - } - } - - /// Clamp to edge (fastest) - mRenderSystem->_getStateCacheManager()->setTexParameteri(src->mTarget, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - mRenderSystem->_getStateCacheManager()->setTexParameteri(src->mTarget, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - mRenderSystem->_getStateCacheManager()->setTexParameteri(src->mTarget, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); - - /// Set origin base level mipmap to make sure we source from the right mip - /// level. - mRenderSystem->_getStateCacheManager()->setTexParameteri(src->mTarget, GL_TEXTURE_BASE_LEVEL, src->mLevel); - - /// Store old binding so it can be restored later - GLint oldfb; - glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, &oldfb); - - /// Set up temporary FBO - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fboMan->getTemporaryFBO()); - - TexturePtr tempTex; - if(!fboMan->checkFormat(mFormat)) - { - /// If target format not directly supported, create intermediate texture - tempTex = TextureManager::getSingleton().createManual( - "GLBlitFromTextureTMP", ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D, - dstBox.getWidth(), dstBox.getHeight(), dstBox.getDepth(), 0, - fboMan->getSupportedAlternative(mFormat)); - - glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, - GL_TEXTURE_2D, static_pointer_cast(tempTex)->getGLID(), 0); - /// Set viewport to size of destination slice - mRenderSystem->_getStateCacheManager()->setViewport(Rect(0, 0, dstBox.getWidth(), dstBox.getHeight())); - } - else - { - /// We are going to bind directly, so set viewport to size and position of destination slice - mRenderSystem->_getStateCacheManager()->setViewport(Rect(dstBox.left, dstBox.top, dstBox.right, dstBox.bottom)); - } - - /// Process each destination slice - for(uint32 slice=dstBox.front; slicemWidth; - float v1 = (float)srcBox.top / (float)src->mHeight; - float u2 = (float)srcBox.right / (float)src->mWidth; - float v2 = (float)srcBox.bottom / (float)src->mHeight; - /// Calculate source slice for this destination slice - float w = (float)(slice - dstBox.front) / (float)dstBox.getDepth(); - /// Get slice # in source - w = w * (float)(srcBox.getDepth() + srcBox.front); - /// Normalise to texture coordinate in 0.0 .. 1.0 - w = (w+0.5f) / (float)src->mDepth; - - /// Finally we're ready to rumble - mRenderSystem->_getStateCacheManager()->bindGLTexture(src->mTarget, src->mTextureID); - mRenderSystem->_getStateCacheManager()->setEnabled(src->mTarget, true); - glBegin(GL_QUADS); - glTexCoord3f(u1, v1, w); - glVertex2f(-1.0f, -1.0f); - glTexCoord3f(u2, v1, w); - glVertex2f(1.0f, -1.0f); - glTexCoord3f(u2, v2, w); - glVertex2f(1.0f, 1.0f); - glTexCoord3f(u1, v2, w); - glVertex2f(-1.0f, 1.0f); - glEnd(); - mRenderSystem->_getStateCacheManager()->setEnabled(src->mTarget, false); - - if(tempTex) - { - /// Copy temporary texture - mRenderSystem->_getStateCacheManager()->bindGLTexture(mTarget, mTextureID); - switch(mTarget) - { - case GL_TEXTURE_1D: - glCopyTexSubImage1D(mFaceTarget, mLevel, - dstBox.left, - 0, 0, dstBox.getWidth()); - break; - case GL_TEXTURE_2D: - case GL_TEXTURE_CUBE_MAP: - glCopyTexSubImage2D(mFaceTarget, mLevel, - dstBox.left, dstBox.top, - 0, 0, dstBox.getWidth(), dstBox.getHeight()); - break; - case GL_TEXTURE_3D: - case GL_TEXTURE_2D_ARRAY_EXT: - glCopyTexSubImage3D(mFaceTarget, mLevel, - dstBox.left, dstBox.top, slice, - 0, 0, dstBox.getWidth(), dstBox.getHeight()); - break; - } - } - } - /// Finish up - if(!tempTex) - { - /// Generate mipmaps - if(mUsage & TU_AUTOMIPMAP) - { - mRenderSystem->_getStateCacheManager()->bindGLTexture(mTarget, mTextureID); - glGenerateMipmapEXT(mTarget); - } - } - - /// Reset source texture to sane state - mRenderSystem->_getStateCacheManager()->bindGLTexture(src->mTarget, src->mTextureID); - mRenderSystem->_getStateCacheManager()->setTexParameteri(src->mTarget, GL_TEXTURE_BASE_LEVEL, 0); - - /// Detach texture from temporary framebuffer - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, - GL_RENDERBUFFER_EXT, 0); - /// Restore old framebuffer - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, oldfb); - /// Restore matrix stacks and render state - glMatrixMode(GL_TEXTURE); - glPopMatrix(); - glMatrixMode(GL_PROJECTION); - glPopMatrix(); - glMatrixMode(GL_MODELVIEW); - glPopMatrix(); - glPopAttrib(); - - if(tempTex) - TextureManager::getSingleton().remove(tempTex); -} -//----------------------------------------------------------------------------- -/// blitFromMemory doing hardware trilinear scaling -void GLTextureBuffer::blitFromMemory(const PixelBox &src, const Box &dstBox) -{ - /// Fall back to normal GLHardwarePixelBuffer::blitFromMemory in case - /// - FBO is not supported - /// - the source dimensions match the destination ones, in which case no scaling is needed - if (!GLAD_GL_EXT_framebuffer_object || - (src.getSize() == dstBox.getSize())) - { - _blitFromMemory(src, dstBox); - return; - } - if(!mBuffer.contains(dstBox)) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "destination box out of range", - "GLTextureBuffer::blitFromMemory"); - - TextureType type = (src.getDepth() != 1) ? TEX_TYPE_3D : TEX_TYPE_2D; - - // Set automatic mipmap generation; nice for minimisation - TexturePtr tex = TextureManager::getSingleton().createManual( - "GLBlitFromMemoryTMP", ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, type, - src.getWidth(), src.getHeight(), src.getDepth(), MIP_UNLIMITED, src.format); - - // Upload data to 0,0,0 in temporary texture - Box tempTarget(src.getSize()); - tex->getBuffer()->blitFromMemory(src, tempTarget); - - // Blit from texture - blit(tex->getBuffer(), tempTarget, dstBox); - - // Delete temp texture - TextureManager::getSingleton().remove(tex); -} -//----------------------------------------------------------------------------- - -RenderTexture *GLTextureBuffer::getRenderTarget(size_t zoffset) -{ - assert(mUsage & TU_RENDERTARGET); - assert(zoffset < mDepth); - return mSliceTRT[zoffset]; -} -//********* GLRenderBuffer -//----------------------------------------------------------------------------- -GLRenderBuffer::GLRenderBuffer(GLenum format, uint32 width, uint32 height, GLsizei numSamples): - GLHardwarePixelBufferCommon(width, height, 1, GLPixelUtil::getClosestOGREFormat(format),HBU_GPU_ONLY), - mRenderbufferID(0) -{ - mGLInternalFormat = format; - /// Generate renderbuffer - glGenRenderbuffersEXT(1, &mRenderbufferID); - /// Bind it to FBO - glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, mRenderbufferID); - - /// Allocate storage for depth buffer - if (numSamples > 0) - { - glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, - numSamples, format, width, height); - } - else - { - glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, format, - width, height); - } -} -//----------------------------------------------------------------------------- -GLRenderBuffer::~GLRenderBuffer() -{ - /// Generate renderbuffer - glDeleteRenderbuffersEXT(1, &mRenderbufferID); -} -//----------------------------------------------------------------------------- -void GLRenderBuffer::bindToFramebuffer(uint32 attachment, uint32 zoffset) -{ - assert(zoffset < mDepth); - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, attachment, - GL_RENDERBUFFER_EXT, mRenderbufferID); -} - -} diff --git a/RenderSystems/GL/src/OgreGLPBRenderTexture.cpp b/RenderSystems/GL/src/OgreGLPBRenderTexture.cpp deleted file mode 100644 index cf7726f4e9e..00000000000 --- a/RenderSystems/GL/src/OgreGLPBRenderTexture.cpp +++ /dev/null @@ -1,163 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreGLPBRenderTexture.h" -#include "OgreGLContext.h" -#include "OgreGLPixelFormat.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreRoot.h" -#include "OgreGLHardwarePixelBuffer.h" -#include "OgreGLNativeSupport.h" - -namespace Ogre { -//----------------------------------------------------------------------------- - GLPBRenderTexture::GLPBRenderTexture(GLPBRTTManager *manager, const String &name, - const GLSurfaceDesc &target, bool writeGamma, uint fsaa): - GLRenderTexture(name, target, writeGamma, fsaa), - mManager(manager) - { - mPBFormat = PixelUtil::getComponentType(target.buffer->getFormat()); - - mManager->requestPBuffer(mPBFormat, mWidth, mHeight); - } - GLPBRenderTexture::~GLPBRenderTexture() - { - // Release PBuffer - mManager->releasePBuffer(mPBFormat); - } - void GLPBRenderTexture::getCustomAttribute(const String& name, void* pData) - { - if( name == GLRenderTexture::CustomAttributeString_TARGET ) - { - GLSurfaceDesc &target = *static_cast(pData); - target.buffer = static_cast(mBuffer); - target.zoffset = mZOffset; - } - else if (name == GLRenderTexture::CustomAttributeString_GLCONTEXT ) - { - // Get PBuffer for our internal format - *static_cast(pData) = getContext(); - } - } - - GLContext* GLPBRenderTexture::getContext() const - { - return mManager->getContextFor(mPBFormat, mWidth, mHeight); - } - -//----------------------------------------------------------------------------- - GLPBRTTManager::GLPBRTTManager(GLNativeSupport *support, RenderTarget *mainwindow): - mSupport(support), - mMainWindow(mainwindow), - mMainContext(0) - { - mMainContext = dynamic_cast(mMainWindow)->getContext(); - } - GLPBRTTManager::~GLPBRTTManager() - { - // Delete remaining PBuffers - for(auto & mPBuffer : mPBuffers) - { - delete mPBuffer.pb; - } - } - - RenderTexture *GLPBRTTManager::createRenderTexture(const String &name, - const GLSurfaceDesc &target, bool writeGamma, uint fsaa) - { - return new GLPBRenderTexture(this, name, target, writeGamma, fsaa); - } - - bool GLPBRTTManager::checkFormat(PixelFormat format) - { - return true; - } - - void GLPBRTTManager::bind(RenderTarget *target) - { - // Nothing to do here - // Binding of context is done by GL subsystem, as contexts are also used for RenderWindows - } - - void GLPBRTTManager::unbind(RenderTarget *target) - { - // Copy on unbind - GLSurfaceDesc surface; - surface.buffer = 0; - target->getCustomAttribute(GLRenderTexture::CustomAttributeString_TARGET, &surface); - if(surface.buffer) - static_cast(surface.buffer)->copyFromFramebuffer(surface.zoffset); - } - - void GLPBRTTManager::requestPBuffer(PixelComponentType ctype, uint32 width, uint32 height) - { - //Check size - if(mPBuffers[ctype].pb) - { - if(mPBuffers[ctype].pb->getWidth()getHeight()createPBuffer(ctype, width, height); - } - - ++mPBuffers[ctype].refcount; - } - - void GLPBRTTManager::releasePBuffer(PixelComponentType ctype) - { - --mPBuffers[ctype].refcount; - if(mPBuffers[ctype].refcount == 0) - { - delete mPBuffers[ctype].pb; - mPBuffers[ctype].pb = 0; - } - } - - GLContext *GLPBRTTManager::getContextFor(PixelComponentType ctype, uint32 width, uint32 height) - { - // Faster to return main context if the RTT is smaller than the window size - // and ctype is PCT_BYTE. This must be checked every time because the window might have been resized - if(ctype == PCT_BYTE) - { - if(width <= mMainWindow->getWidth() && height <= mMainWindow->getHeight()) - return mMainContext; - } - assert(mPBuffers[ctype].pb); - return mPBuffers[ctype].pb->getContext(); - } -//--------------------------------------------------------------------------------------------- - -} - diff --git a/RenderSystems/GL/src/OgreGLPixelFormat.cpp b/RenderSystems/GL/src/OgreGLPixelFormat.cpp deleted file mode 100644 index 92b16ee0f0b..00000000000 --- a/RenderSystems/GL/src/OgreGLPixelFormat.cpp +++ /dev/null @@ -1,169 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLPixelFormat.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" -#include "OgreBitwise.h" - -#ifndef GL_HALF_FLOAT -#define GL_HALF_FLOAT 0x140B -#endif - -namespace Ogre { - - struct GLPixelFormatDescription { - GLenum format; - GLenum type; - GLenum internalFormat; - }; - - static GLPixelFormatDescription _pixelFormats[int(PF_COUNT)] = { - {GL_NONE}, // PF_UNKNOWN - {GL_LUMINANCE, GL_UNSIGNED_BYTE, GL_LUMINANCE8}, // PF_L8 - {GL_LUMINANCE, GL_UNSIGNED_SHORT, GL_LUMINANCE16}, // PF_L16 - {GL_ALPHA, GL_UNSIGNED_BYTE, GL_ALPHA8}, // PF_A8 - {GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, GL_LUMINANCE8_ALPHA8},// PF_BYTE_LA - {GL_RGB, GL_UNSIGNED_SHORT_5_6_5, GL_RGB5}, // PF_R5G6B5 - {GL_BGR, GL_UNSIGNED_SHORT_5_6_5, GL_RGB5}, // PF_B5G6R5 - {GL_BGRA, GL_UNSIGNED_SHORT_4_4_4_4_REV, GL_RGBA4}, // PF_A4R4G4B4 - {GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, GL_RGB5_A1},// PF_A1R5G5B5 -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - {GL_RGB, GL_UNSIGNED_BYTE, GL_RGB8}, // PF_R8G8B8 - {GL_BGR, GL_UNSIGNED_BYTE, GL_RGB8}, // PF_B8G8R8 -#else - {GL_BGR, GL_UNSIGNED_BYTE, GL_RGB8}, // PF_R8G8B8 - {GL_RGB, GL_UNSIGNED_BYTE, GL_RGB8}, // PF_B8G8R8 -#endif - {GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, GL_RGBA8}, // PF_A8R8G8B8 - {GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, GL_RGBA8}, // PF_A8B8G8R8 - {GL_BGRA, GL_UNSIGNED_INT_8_8_8_8, GL_RGBA8}, // PF_B8G8R8A8 - {GL_NONE}, // PF_A2R10G10B10 - {GL_NONE}, // PF_A2B10G10R10 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT},// PF_DXT1 - {GL_NONE}, // PF_DXT2 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT},// PF_DXT3 - {GL_NONE}, // PF_DXT4 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT},// PF_DXT5 - {GL_RGB, GL_HALF_FLOAT, GL_RGB16F_ARB}, // PF_FLOAT16_RGB - {GL_RGBA, GL_HALF_FLOAT, GL_RGBA16F_ARB}, // PF_FLOAT16_RGBA - {GL_RGB, GL_FLOAT, GL_RGB32F_ARB}, // PF_FLOAT32_RGB - {GL_RGBA, GL_FLOAT, GL_RGBA32F_ARB}, // PF_FLOAT32_RGBA - {GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, GL_RGBA8}, // PF_X8R8G8B8 - {GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, GL_RGBA8}, // PF_X8B8G8R8 - {GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, GL_RGBA8}, // PF_R8G8B8A8 - {GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, GL_DEPTH_COMPONENT16}, // PF_DEPTH16 - {GL_RGBA, GL_UNSIGNED_SHORT, GL_RGBA16}, // PF_SHORT_RGBA - {GL_RGB, GL_UNSIGNED_BYTE_3_3_2, GL_R3_G3_B2}, // PF_R3G3B2 - {GL_LUMINANCE, GL_HALF_FLOAT, GL_LUMINANCE16F_ARB}, // PF_FLOAT16_R - {GL_LUMINANCE, GL_FLOAT, GL_LUMINANCE32F_ARB}, // PF_FLOAT32_R - {GL_LUMINANCE_ALPHA, GL_UNSIGNED_SHORT, GL_LUMINANCE16_ALPHA16},// PF_SHORT_GR - {GL_LUMINANCE_ALPHA, GL_HALF_FLOAT, GL_LUMINANCE_ALPHA16F_ARB}, // PF_FLOAT16_GR - {GL_LUMINANCE_ALPHA, GL_FLOAT, GL_LUMINANCE_ALPHA32F_ARB}, // PF_FLOAT32_GR - {GL_RGB, GL_UNSIGNED_SHORT, GL_RGB16}, // PF_SHORT_RGB - // limited format support: the rest is PF_NONE - }; - - //----------------------------------------------------------------------------- - GLenum GLPixelUtil::getGLOriginFormat(PixelFormat pf) - { - return _pixelFormats[pf].format; - } - //----------------------------------------------------------------------------- - GLenum GLPixelUtil::getGLOriginDataType(PixelFormat pf) - { - return _pixelFormats[pf].type; - } - - GLenum GLPixelUtil::getGLInternalFormat(PixelFormat pf, bool hwGamma) - { - GLenum ret = _pixelFormats[pf].internalFormat; - - if(!hwGamma) - return ret; - - switch(ret) - { - case GL_RGB8: - return GL_SRGB8; - case GL_RGBA8: - return GL_SRGB8_ALPHA8; - case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: - return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; - case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: - return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; - case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: - return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; - default: - return ret; - } - } - - //----------------------------------------------------------------------------- - PixelFormat GLPixelUtil::getClosestOGREFormat(GLenum format) - { - switch(format) - { - case GL_DEPTH_COMPONENT24: - case GL_DEPTH_COMPONENT32: - case GL_DEPTH_COMPONENT32F: - case GL_DEPTH_COMPONENT: - return PF_DEPTH16; - case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: - return PF_DXT1; - case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: - return PF_DXT3; - case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: - return PF_DXT5; - case GL_SRGB8: - case GL_RGB8: // prefer native endian byte format - return PF_BYTE_RGB; - case GL_SRGB8_ALPHA8: - case GL_RGBA8: // prefer native endian byte format - return PF_BYTE_RGBA; - }; - - for(int pf = 0; pf < PF_COUNT; pf++) { - if(_pixelFormats[pf].internalFormat == format) - return (PixelFormat)pf; - } - - return PF_BYTE_RGBA; - } - //----------------------------------------------------------------------------- - uint32 GLPixelUtil::optionalPO2(uint32 value) - { - const RenderSystemCapabilities *caps = Root::getSingleton().getRenderSystem()->getCapabilities(); - if(caps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES)) - return value; - else - return Bitwise::firstPO2From(value); - } - - -} diff --git a/RenderSystems/GL/src/OgreGLPlugin.cpp b/RenderSystems/GL/src/OgreGLPlugin.cpp deleted file mode 100644 index d76f3035fd4..00000000000 --- a/RenderSystems/GL/src/OgreGLPlugin.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLPlugin.h" -#include "OgreRoot.h" -#include "OgreGLRenderSystem.h" - -namespace Ogre -{ - const String sPluginName = "GL RenderSystem"; - //--------------------------------------------------------------------- - GLPlugin::GLPlugin() - : mRenderSystem(0) - { - - } - //--------------------------------------------------------------------- - const String& GLPlugin::getName() const - { - return sPluginName; - } - //--------------------------------------------------------------------- - void GLPlugin::install() - { - mRenderSystem = OGRE_NEW GLRenderSystem(); - - Root::getSingleton().addRenderSystem(mRenderSystem); - } - //--------------------------------------------------------------------- - void GLPlugin::initialise() - { - // nothing to do - } - //--------------------------------------------------------------------- - void GLPlugin::shutdown() - { - // nothing to do - } - //--------------------------------------------------------------------- - void GLPlugin::uninstall() - { - OGRE_DELETE mRenderSystem; - mRenderSystem = 0; - } -} diff --git a/RenderSystems/GL/src/OgreGLRenderSystem.cpp b/RenderSystems/GL/src/OgreGLRenderSystem.cpp deleted file mode 100644 index 09a3b6c03ee..00000000000 --- a/RenderSystems/GL/src/OgreGLRenderSystem.cpp +++ /dev/null @@ -1,3028 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - - -#include "OgreGLRenderSystem.h" -#include "OgreGLNativeSupport.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreFrustum.h" -#include "OgreGLTextureManager.h" -#include "OgreGLHardwareBuffer.h" -#include "OgreDefaultHardwareBufferManager.h" -#include "OgreGLUtil.h" -#include "OgreGLGpuProgram.h" -#include "OgreGLGpuNvparseProgram.h" -#include "ATI_FS_GLGpuProgram.h" -#include "OgreGLGpuProgramManager.h" -#include "OgreException.h" -#include "OgreGLSLExtSupport.h" -#include "OgreGLHardwareOcclusionQuery.h" -#include "OgreGLDepthBufferCommon.h" -#include "OgreGLHardwarePixelBuffer.h" -#include "OgreGLContext.h" -#include "OgreGLSLProgramFactory.h" -#include "OgreGLStateCacheManager.h" - -#include "OgreGLFBORenderTexture.h" -#include "OgreGLPBRenderTexture.h" -#include "OgreConfig.h" -#include "OgreViewport.h" - -#include "OgreGLPixelFormat.h" - -#include "OgreGLSLProgramCommon.h" -#include "OgreGLFBOMultiRenderTarget.h" - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE -extern "C" void glFlushRenderAPPLE(); -#endif - -namespace Ogre { - - static GLNativeSupport* glsupport; - static void* get_proc(const char* proc) { - return glsupport->getProcAddress(proc); - } - - typedef TransformBase<4, float> Matrix4f; - - // Callback function used when registering GLGpuPrograms - static GpuProgram* createGLArbGpuProgram(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - GpuProgramType gptype, const String& syntaxCode) - { - GLArbGpuProgram* ret = new GLArbGpuProgram( - creator, name, handle, group, isManual, loader); - ret->setType(gptype); - ret->setSyntaxCode(syntaxCode); - return ret; - } - - static GpuProgram* createGLGpuNvparseProgram(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - GpuProgramType gptype, const String& syntaxCode) - { - GLGpuNvparseProgram* ret = new GLGpuNvparseProgram( - creator, name, handle, group, isManual, loader); - ret->setType(gptype); - ret->setSyntaxCode(syntaxCode); - return ret; - } - - static GpuProgram* createGL_ATI_FS_GpuProgram(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - GpuProgramType gptype, const String& syntaxCode) - { - - ATI_FS_GLGpuProgram* ret = new ATI_FS_GLGpuProgram( - creator, name, handle, group, isManual, loader); - ret->setType(gptype); - ret->setSyntaxCode(syntaxCode); - return ret; - } - - static GLint getCombinedMinMipFilter(FilterOptions min, FilterOptions mip) - { - switch(min) - { - case FO_ANISOTROPIC: - case FO_LINEAR: - switch (mip) - { - case FO_ANISOTROPIC: - case FO_LINEAR: - // linear min, linear mip - return GL_LINEAR_MIPMAP_LINEAR; - case FO_POINT: - // linear min, point mip - return GL_LINEAR_MIPMAP_NEAREST; - case FO_NONE: - // linear min, no mip - return GL_LINEAR; - } - break; - case FO_POINT: - case FO_NONE: - switch (mip) - { - case FO_ANISOTROPIC: - case FO_LINEAR: - // nearest min, linear mip - return GL_NEAREST_MIPMAP_LINEAR; - case FO_POINT: - // nearest min, point mip - return GL_NEAREST_MIPMAP_NEAREST; - case FO_NONE: - // nearest min, no mip - return GL_NEAREST; - } - break; - } - - // should never get here - return 0; - } - - GLRenderSystem::GLRenderSystem() - : mFixedFunctionTextureUnits(0), - mStencilWriteMask(0xFFFFFFFF), - mDepthWrite(true), - mUseAutoTextureMatrix(false), - mHardwareBufferManager(0), - mGpuProgramManager(0), - mGLSLProgramFactory(0), - mStateCacheManager(0), - mActiveTextureUnit(0), - mMaxBuiltInTextureAttribIndex(0) - { - size_t i; - - LogManager::getSingleton().logMessage(getName() + " created."); - - mRenderAttribsBound.reserve(100); - mRenderInstanceAttribsBound.reserve(100); - - // Get our GLSupport - mGLSupport = getGLSupport(GLNativeSupport::CONTEXT_COMPATIBILITY); - glsupport = mGLSupport; - - mWorldMatrix = Matrix4::IDENTITY; - mViewMatrix = Matrix4::IDENTITY; - - initConfigOptions(); - - for (i = 0; i < OGRE_MAX_TEXTURE_LAYERS; i++) - { - // Dummy value - mTextureCoordIndex[i] = 99; - mTextureTypes[i] = 0; - } - - mActiveRenderTarget = 0; - mCurrentContext = 0; - mMainContext = 0; - - mGLInitialised = false; - mEnableFixedPipeline = true; - - mCurrentLights = 0; - mMinFilter = FO_LINEAR; - mMipFilter = FO_POINT; - mCurrentVertexProgram = 0; - mCurrentGeometryProgram = 0; - mCurrentFragmentProgram = 0; - mRTTManager = NULL; - } - - GLRenderSystem::~GLRenderSystem() - { - shutdown(); - - delete mGLSupport; - } - - const GpuProgramParametersPtr& GLRenderSystem::getFixedFunctionParams(TrackVertexColourType tracking, - FogMode fog) - { - _setSurfaceTracking(tracking); - _setFog(fog); - - return mFixedFunctionParams; - } - - void GLRenderSystem::applyFixedFunctionParams(const GpuProgramParametersPtr& params, uint16 mask) - { - bool updateLightPos = false; - - // Autoconstant index is not a physical index - for (const auto& ac : params->getAutoConstants()) - { - // Only update needed slots - if (ac.variability & mask) - { - const float* ptr = params->getFloatPointer(ac.physicalIndex); - switch(ac.paramType) - { - case GpuProgramParameters::ACT_WORLD_MATRIX: - setWorldMatrix(Matrix4(ptr)); - break; - case GpuProgramParameters::ACT_VIEW_MATRIX: - // force light update - updateLightPos = true; - mask |= GPV_LIGHTS; - setViewMatrix(Matrix4(ptr)); - break; - case GpuProgramParameters::ACT_PROJECTION_MATRIX: - setProjectionMatrix(Matrix4(ptr)); - break; - case GpuProgramParameters::ACT_SURFACE_AMBIENT_COLOUR: - mStateCacheManager->setMaterialAmbient(ptr[0], ptr[1], ptr[2], ptr[3]); - break; - case GpuProgramParameters::ACT_SURFACE_DIFFUSE_COLOUR: - mStateCacheManager->setMaterialDiffuse(ptr[0], ptr[1], ptr[2], ptr[3]); - break; - case GpuProgramParameters::ACT_SURFACE_SPECULAR_COLOUR: - mStateCacheManager->setMaterialSpecular(ptr[0], ptr[1], ptr[2], ptr[3]); - break; - case GpuProgramParameters::ACT_SURFACE_EMISSIVE_COLOUR: - mStateCacheManager->setMaterialEmissive(ptr[0], ptr[1], ptr[2], ptr[3]); - break; - case GpuProgramParameters::ACT_SURFACE_SHININESS: - mStateCacheManager->setMaterialShininess(ptr[0]); - break; - case GpuProgramParameters::ACT_POINT_PARAMS: - mStateCacheManager->setPointSize(ptr[0]); - mStateCacheManager->setPointParameters(ptr + 1); - break; - case GpuProgramParameters::ACT_FOG_PARAMS: - glFogf(GL_FOG_DENSITY, ptr[0]); - glFogf(GL_FOG_START, ptr[1]); - glFogf(GL_FOG_END, ptr[2]); - break; - case GpuProgramParameters::ACT_FOG_COLOUR: - glFogfv(GL_FOG_COLOR, ptr); - break; - case GpuProgramParameters::ACT_AMBIENT_LIGHT_COLOUR: - mStateCacheManager->setLightAmbient(ptr[0], ptr[1], ptr[2]); - break; - case GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR: - glLightfv(GL_LIGHT0 + ac.data, GL_DIFFUSE, ptr); - break; - case GpuProgramParameters::ACT_LIGHT_SPECULAR_COLOUR: - glLightfv(GL_LIGHT0 + ac.data, GL_SPECULAR, ptr); - break; - case GpuProgramParameters::ACT_LIGHT_ATTENUATION: - glLightf(GL_LIGHT0 + ac.data, GL_CONSTANT_ATTENUATION, ptr[1]); - glLightf(GL_LIGHT0 + ac.data, GL_LINEAR_ATTENUATION, ptr[2]); - glLightf(GL_LIGHT0 + ac.data, GL_QUADRATIC_ATTENUATION, ptr[3]); - break; - case GpuProgramParameters::ACT_SPOTLIGHT_PARAMS: - { - float cutoff = ptr[3] ? Math::RadiansToDegrees(std::acos(ptr[1])) : 180; - glLightf(GL_LIGHT0 + ac.data, GL_SPOT_CUTOFF, cutoff); - glLightf(GL_LIGHT0 + ac.data, GL_SPOT_EXPONENT, ptr[2]); - break; - } - case GpuProgramParameters::ACT_LIGHT_POSITION: - case GpuProgramParameters::ACT_LIGHT_DIRECTION: - // handled below - updateLightPos = true; - break; - default: - OgreAssert(false, "unknown autoconstant"); - break; - } - } - } - - if(!updateLightPos) return; - - // GL lights use eye coordinates, which we only know now - - // Save previous modelview - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - glLoadMatrixf(Matrix4f(mViewMatrix.transpose())[0]); - - for (const auto& ac : params->getAutoConstants()) - { - // Only update needed slots - if ((GPV_GLOBAL | GPV_LIGHTS) & mask) - { - const float* ptr = params->getFloatPointer(ac.physicalIndex); - switch(ac.paramType) - { - case GpuProgramParameters::ACT_LIGHT_POSITION: - glLightfv(GL_LIGHT0 + ac.data, GL_POSITION, ptr); - break; - case GpuProgramParameters::ACT_LIGHT_DIRECTION: - glLightfv(GL_LIGHT0 + ac.data, GL_SPOT_DIRECTION, ptr); - break; - default: - break; - } - } - } - glPopMatrix(); - } - - const String& GLRenderSystem::getName(void) const - { - static String strName("OpenGL Rendering Subsystem"); - return strName; - } - - void GLRenderSystem::_initialise() - { - RenderSystem::_initialise(); - - mGLSupport->start(); - - // Create the texture manager - mTextureManager = new GLTextureManager(this); - } - - void GLRenderSystem::initConfigOptions() - { - GLRenderSystemCommon::initConfigOptions(); - - ConfigOption optRTTMode; - optRTTMode.name = "RTT Preferred Mode"; - optRTTMode.possibleValues = {"FBO", "PBuffer", "Copy"}; - optRTTMode.currentValue = optRTTMode.possibleValues[0]; - optRTTMode.immutable = true; - mOptions[optRTTMode.name] = optRTTMode; - - ConfigOption opt; - opt.name = "Fixed Pipeline Enabled"; - opt.possibleValues = {"Yes", "No"}; - opt.currentValue = opt.possibleValues[0]; - opt.immutable = false; - - mOptions[opt.name] = opt; - } - - RenderSystemCapabilities* GLRenderSystem::createRenderSystemCapabilities() const - { - RenderSystemCapabilities* rsc = new RenderSystemCapabilities(); - - rsc->setCategoryRelevant(CAPS_CATEGORY_GL, true); - rsc->setDriverVersion(mDriverVersion); - const char* deviceName = (const char*)glGetString(GL_RENDERER); - rsc->setDeviceName(deviceName); - rsc->setRenderSystemName(getName()); - rsc->setVendor(mVendor); - - if (mEnableFixedPipeline) - { - // Supports fixed-function - rsc->setCapability(RSC_FIXED_FUNCTION); - } - - rsc->setCapability(RSC_AUTOMIPMAP_COMPRESSED); - - // Check for Multitexturing support and set number of texture units - GLint units; - glGetIntegerv( GL_MAX_TEXTURE_UNITS, &units ); - - if (GLAD_GL_ARB_fragment_program) - { - // Also check GL_MAX_TEXTURE_IMAGE_UNITS_ARB since NV at least - // only increased this on the FX/6x00 series - GLint arbUnits; - glGetIntegerv( GL_MAX_TEXTURE_IMAGE_UNITS_ARB, &arbUnits ); - if (arbUnits > units) - units = arbUnits; - } - rsc->setNumTextureUnits(std::min(OGRE_MAX_TEXTURE_LAYERS, units)); - - // Check for Anisotropy support - if(GLAD_GL_EXT_texture_filter_anisotropic) - { - GLfloat maxAnisotropy = 0; - glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maxAnisotropy); - rsc->setMaxSupportedAnisotropy(maxAnisotropy); - rsc->setCapability(RSC_ANISOTROPY); - } - - // Point sprites - if (GLAD_GL_VERSION_2_0 || GLAD_GL_ARB_point_sprite) - { - rsc->setCapability(RSC_POINT_SPRITES); - } - - if(GLAD_GL_ARB_point_parameters) - { - glPointParameterf = glPointParameterfARB; - glPointParameterfv = glPointParameterfvARB; - } - else if(GLAD_GL_EXT_point_parameters) - { - glPointParameterf = glPointParameterfEXT; - glPointParameterfv = glPointParameterfvEXT; - } - - // Check for hardware stencil support and set bit depth - GLint stencil; - glGetIntegerv(GL_STENCIL_BITS,&stencil); - - if(stencil) - { - rsc->setCapability(RSC_HWSTENCIL); - } - - rsc->setCapability(RSC_HW_GAMMA); - - rsc->setCapability(RSC_MAPBUFFER); - rsc->setCapability(RSC_32BIT_INDEX); - - if(GLAD_GL_ARB_vertex_program) - { - rsc->setCapability(RSC_VERTEX_PROGRAM); - - // Vertex Program Properties - GLint floatConstantCount; - glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, &floatConstantCount); - rsc->setVertexProgramConstantFloatCount(floatConstantCount); - - GLint attrs; - glGetIntegerv( GL_MAX_VERTEX_ATTRIBS_ARB, &attrs); - rsc->setNumVertexAttributes(attrs); - - rsc->addShaderProfile("arbvp1"); - if (GLAD_GL_NV_vertex_program2_option) - { - rsc->addShaderProfile("vp30"); - } - - if (GLAD_GL_NV_vertex_program3) - { - rsc->addShaderProfile("vp40"); - } - - if (GLAD_GL_NV_gpu_program4) - { - rsc->addShaderProfile("gp4vp"); - rsc->addShaderProfile("gpu_vp"); - } - } - - if (GLAD_GL_NV_register_combiners2 && - GLAD_GL_NV_texture_shader) - { - rsc->addShaderProfile("fp20"); - } - - // NFZ - check for ATI fragment shader support - if (GLAD_GL_ATI_fragment_shader) - { - // only 8 Vector4 constant floats supported - rsc->setFragmentProgramConstantFloatCount(8); - - rsc->addShaderProfile("ps_1_4"); - rsc->addShaderProfile("ps_1_3"); - rsc->addShaderProfile("ps_1_2"); - rsc->addShaderProfile("ps_1_1"); - } - - if (GLAD_GL_ARB_fragment_program) - { - // Fragment Program Properties - GLint floatConstantCount; - glGetProgramivARB(GL_FRAGMENT_PROGRAM_ARB, GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB, &floatConstantCount); - rsc->setFragmentProgramConstantFloatCount(floatConstantCount); - - rsc->addShaderProfile("arbfp1"); - if (GLAD_GL_NV_fragment_program_option) - { - rsc->addShaderProfile("fp30"); - } - - if (GLAD_GL_NV_fragment_program2) - { - rsc->addShaderProfile("fp40"); - } - - if (GLAD_GL_NV_gpu_program4) - { - rsc->addShaderProfile("gp4fp"); - rsc->addShaderProfile("gpu_fp"); - } - } - - // NFZ - Check if GLSL is supported - if ( GLAD_GL_VERSION_2_0 || - (GLAD_GL_ARB_shading_language_100 && - GLAD_GL_ARB_shader_objects && - GLAD_GL_ARB_fragment_shader && - GLAD_GL_ARB_vertex_shader) ) - { - rsc->addShaderProfile("glsl"); - if(getNativeShadingLanguageVersion() >= 120) - rsc->addShaderProfile("glsl120"); - if(getNativeShadingLanguageVersion() >= 110) - rsc->addShaderProfile("glsl110"); - if(getNativeShadingLanguageVersion() >= 100) - rsc->addShaderProfile("glsl100"); - } - - // Check if geometry shaders are supported - if (hasMinGLVersion(3, 2) || (GLAD_GL_VERSION_2_0 && GLAD_GL_EXT_geometry_shader4)) - { - rsc->setCapability(RSC_GEOMETRY_PROGRAM); - GLint floatConstantCount = 0; - glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT, &floatConstantCount); - rsc->setGeometryProgramConstantFloatCount(floatConstantCount/4); - - GLint maxOutputVertices; - glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT,&maxOutputVertices); - rsc->setGeometryProgramNumOutputVertices(maxOutputVertices); - } - - if(GLAD_GL_NV_gpu_program4) - { - rsc->setCapability(RSC_GEOMETRY_PROGRAM); - rsc->addShaderProfile("nvgp4"); - - //Also add the CG profiles - rsc->addShaderProfile("gpu_gp"); - rsc->addShaderProfile("gp4gp"); - } - - if (checkExtension("GL_ARB_get_program_binary")) - { - // states 3.0 here: http://developer.download.nvidia.com/opengl/specs/GL_ARB_get_program_binary.txt - // but not here: http://www.opengl.org/sdk/docs/man4/xhtml/glGetProgramBinary.xml - // and here states 4.1: http://www.geeks3d.com/20100727/opengl-4-1-allows-the-use-of-binary-shaders/ - GLint formats; - glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS, &formats); - - if(formats > 0) - rsc->setCapability(RSC_CAN_GET_COMPILED_SHADER_BUFFER); - } - - if (hasMinGLVersion(3, 3) || GLAD_GL_ARB_instanced_arrays) - { - // states 3.3 here: http://www.opengl.org/sdk/docs/man3/xhtml/glVertexAttribDivisor.xml - rsc->setCapability(RSC_VERTEX_BUFFER_INSTANCE_DATA); - } - - //Check if render to vertex buffer (transform feedback in OpenGL) - if (GLAD_GL_VERSION_2_0 && - GLAD_GL_NV_transform_feedback) - { - rsc->setCapability(RSC_HWRENDER_TO_VERTEX_BUFFER); - } - - // Check for texture compression - rsc->setCapability(RSC_TEXTURE_COMPRESSION); - - // Check for dxt compression - if(GLAD_GL_EXT_texture_compression_s3tc) - { -#if defined(__APPLE__) && defined(__PPC__) - // Apple on ATI & PPC has errors in DXT - if (mGLSupport->getGLVendor().find("ATI") == std::string::npos) -#endif - rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT); - } - // Check for vtc compression - if(GLAD_GL_NV_texture_compression_vtc) - { - rsc->setCapability(RSC_TEXTURE_COMPRESSION_VTC); - } - - // As are user clipping planes - rsc->setCapability(RSC_USER_CLIP_PLANES); - - // 2-sided stencil? - if (GLAD_GL_VERSION_2_0 || GLAD_GL_EXT_stencil_two_side) - { - rsc->setCapability(RSC_TWO_SIDED_STENCIL); - } - rsc->setCapability(RSC_STENCIL_WRAP); - rsc->setCapability(RSC_HWOCCLUSION); - - // Check for non-power-of-2 texture support - if(GLAD_GL_ARB_texture_non_power_of_two) - { - rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES); - } - - // Check for Float textures - if(GLAD_GL_ATI_texture_float || GLAD_GL_ARB_texture_float) - { - rsc->setCapability(RSC_TEXTURE_FLOAT); - } - - // 3D textures should be supported by GL 1.2, which is our minimum version - rsc->setCapability(RSC_TEXTURE_1D); - rsc->setCapability(RSC_TEXTURE_3D); - - if(hasMinGLVersion(3, 0) || GLAD_GL_EXT_texture_array) - rsc->setCapability(RSC_TEXTURE_2D_ARRAY); - - // Check for framebuffer object extension - if(GLAD_GL_EXT_framebuffer_object) - { - // Probe number of draw buffers - // Only makes sense with FBO support, so probe here - if(GLAD_GL_VERSION_2_0 || - GLAD_GL_ARB_draw_buffers || - GLAD_GL_ATI_draw_buffers) - { - GLint buffers; - glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &buffers); - rsc->setNumMultiRenderTargets(std::min(buffers, (GLint)OGRE_MAX_MULTIPLE_RENDER_TARGETS)); - - } - rsc->setCapability(RSC_HWRENDER_TO_TEXTURE); - } - - // Check GLSupport for PBuffer support - if(GLAD_GL_ARB_pixel_buffer_object || GLAD_GL_EXT_pixel_buffer_object) - { - // Use PBuffers - rsc->setCapability(RSC_HWRENDER_TO_TEXTURE); - rsc->setCapability(RSC_PBUFFER); - } - - // Point size - float ps; - glGetFloatv(GL_POINT_SIZE_MAX, &ps); - rsc->setMaxPointSize(ps); - - // Vertex texture fetching - if (checkExtension("GL_ARB_vertex_shader")) - { - GLint vUnits; - glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, &vUnits); - rsc->setNumVertexTextureUnits(static_cast(vUnits)); - if (vUnits > 0) - { - rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH); - } - } - - rsc->setCapability(RSC_MIPMAP_LOD_BIAS); - - // Alpha to coverage? - if (checkExtension("GL_ARB_multisample")) - { - // Alpha to coverage always 'supported' when MSAA is available - // although card may ignore it if it doesn't specifically support A2C - rsc->setCapability(RSC_ALPHA_TO_COVERAGE); - } - - GLfloat lineWidth[2] = {1, 1}; - glGetFloatv(GL_ALIASED_LINE_WIDTH_RANGE, lineWidth); - if(lineWidth[1] != 1 && lineWidth[1] != lineWidth[0]) - rsc->setCapability(RSC_WIDE_LINES); - - return rsc; - } - - void GLRenderSystem::initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary) - { - // set texture the number of texture units - mFixedFunctionTextureUnits = caps->getNumTextureUnits(); - - //In GL there can be less fixed function texture units than general - //texture units. Get the minimum of the two. - if (caps->hasCapability(RSC_FRAGMENT_PROGRAM)) - { - GLint maxTexCoords = 0; - glGetIntegerv(GL_MAX_TEXTURE_COORDS_ARB, &maxTexCoords); - if (mFixedFunctionTextureUnits > maxTexCoords) - { - mFixedFunctionTextureUnits = maxTexCoords; - } - } - - if(!GLAD_GL_ARB_vertex_buffer_object) - { - // Assign ARB functions same to GL 1.5 version since - // interface identical - glBindBufferARB = glBindBuffer; - glBufferDataARB = glBufferData; - glBufferSubDataARB = glBufferSubData; - glDeleteBuffersARB = glDeleteBuffers; - glGenBuffersARB = glGenBuffers; - glGetBufferParameterivARB = glGetBufferParameteriv; - glGetBufferPointervARB = glGetBufferPointerv; - glGetBufferSubDataARB = glGetBufferSubData; - glIsBufferARB = glIsBuffer; - glMapBufferARB = glMapBuffer; - glUnmapBufferARB = glUnmapBuffer; - } - - mHardwareBufferManager = new GLHardwareBufferManager; - - // XXX Need to check for nv2 support and make a program manager for it - // XXX Probably nv1 as well for older cards - // GPU Program Manager setup - mGpuProgramManager = new GLGpuProgramManager(); - - if(caps->hasCapability(RSC_VERTEX_PROGRAM)) - { - if(caps->isShaderProfileSupported("arbvp1")) - { - mGpuProgramManager->registerProgramFactory("arbvp1", createGLArbGpuProgram); - } - - if(caps->isShaderProfileSupported("vp30")) - { - mGpuProgramManager->registerProgramFactory("vp30", createGLArbGpuProgram); - } - - if(caps->isShaderProfileSupported("vp40")) - { - mGpuProgramManager->registerProgramFactory("vp40", createGLArbGpuProgram); - } - - if(caps->isShaderProfileSupported("gp4vp")) - { - mGpuProgramManager->registerProgramFactory("gp4vp", createGLArbGpuProgram); - } - - if(caps->isShaderProfileSupported("gpu_vp")) - { - mGpuProgramManager->registerProgramFactory("gpu_vp", createGLArbGpuProgram); - } - } - - if(caps->hasCapability(RSC_GEOMETRY_PROGRAM)) - { - //TODO : Should these be createGLArbGpuProgram or createGLGpuNVparseProgram? - if(caps->isShaderProfileSupported("nvgp4")) - { - mGpuProgramManager->registerProgramFactory("nvgp4", createGLArbGpuProgram); - } - if(caps->isShaderProfileSupported("gp4gp")) - { - mGpuProgramManager->registerProgramFactory("gp4gp", createGLArbGpuProgram); - } - if(caps->isShaderProfileSupported("gpu_gp")) - { - mGpuProgramManager->registerProgramFactory("gpu_gp", createGLArbGpuProgram); - } - } - - if(caps->hasCapability(RSC_FRAGMENT_PROGRAM)) - { - - if(caps->isShaderProfileSupported("fp20")) - { - mGpuProgramManager->registerProgramFactory("fp20", createGLGpuNvparseProgram); - } - - if(caps->isShaderProfileSupported("ps_1_4")) - { - mGpuProgramManager->registerProgramFactory("ps_1_4", createGL_ATI_FS_GpuProgram); - } - - if(caps->isShaderProfileSupported("ps_1_3")) - { - mGpuProgramManager->registerProgramFactory("ps_1_3", createGL_ATI_FS_GpuProgram); - } - - if(caps->isShaderProfileSupported("ps_1_2")) - { - mGpuProgramManager->registerProgramFactory("ps_1_2", createGL_ATI_FS_GpuProgram); - } - - if(caps->isShaderProfileSupported("ps_1_1")) - { - mGpuProgramManager->registerProgramFactory("ps_1_1", createGL_ATI_FS_GpuProgram); - } - - if(caps->isShaderProfileSupported("arbfp1")) - { - mGpuProgramManager->registerProgramFactory("arbfp1", createGLArbGpuProgram); - } - - if(caps->isShaderProfileSupported("fp40")) - { - mGpuProgramManager->registerProgramFactory("fp40", createGLArbGpuProgram); - } - - if(caps->isShaderProfileSupported("fp30")) - { - mGpuProgramManager->registerProgramFactory("fp30", createGLArbGpuProgram); - } - - if(caps->isShaderProfileSupported("gp4fp")) - { - mGpuProgramManager->registerProgramFactory("gp4fp", createGLArbGpuProgram); - } - - if(caps->isShaderProfileSupported("gpu_fp")) - { - mGpuProgramManager->registerProgramFactory("gpu_fp", createGLArbGpuProgram); - } - - } - - if(caps->isShaderProfileSupported("glsl")) - { - // NFZ - check for GLSL vertex and fragment shader support successful - mGLSLProgramFactory = new GLSL::GLSLProgramFactory(); - HighLevelGpuProgramManager::getSingleton().addFactory(mGLSLProgramFactory); - LogManager::getSingleton().logMessage("GLSL support detected"); - } - - if(caps->hasCapability(RSC_HWOCCLUSION) && !GLAD_GL_ARB_occlusion_query) - { - // Assign ARB functions same to GL 1.5 version since - // interface identical - glBeginQueryARB = glBeginQuery; - glDeleteQueriesARB = glDeleteQueries; - glEndQueryARB = glEndQuery; - glGenQueriesARB = glGenQueries; - glGetQueryObjectivARB = glGetQueryObjectiv; - glGetQueryObjectuivARB = glGetQueryObjectuiv; - glGetQueryivARB = glGetQueryiv; - glIsQueryARB = glIsQuery; - } - - - /// Do this after extension function pointers are initialised as the extension - /// is used to probe further capabilities. - auto cfi = getConfigOptions().find("RTT Preferred Mode"); - // RTT Mode: 0 use whatever available, 1 use PBuffers, 2 force use copying - int rttMode = 0; - if (cfi != getConfigOptions().end()) - { - if (cfi->second.currentValue == "PBuffer") - { - rttMode = 1; - } - else if (cfi->second.currentValue == "Copy") - { - rttMode = 2; - } - } - - - - - // Check for framebuffer object extension - if(caps->hasCapability(RSC_HWRENDER_TO_TEXTURE) && rttMode < 1) - { - // Before GL version 2.0, we need to get one of the extensions - if(GLAD_GL_ARB_draw_buffers) - glDrawBuffers = glDrawBuffersARB; - else if(GLAD_GL_ATI_draw_buffers) - glDrawBuffers = glDrawBuffersATI; - - // Create FBO manager - LogManager::getSingleton().logMessage("GL: Using GL_EXT_framebuffer_object for rendering to textures (best)"); - mRTTManager = new GLFBOManager(false); - //TODO: Check if we're using OpenGL 3.0 and add RSC_RTT_DEPTHBUFFER_RESOLUTION_LESSEQUAL flag - } - else - { - // Check GLSupport for PBuffer support - if(caps->hasCapability(RSC_PBUFFER) && rttMode < 2) - { - if(caps->hasCapability(RSC_HWRENDER_TO_TEXTURE)) - { - // Use PBuffers - mRTTManager = new GLPBRTTManager(mGLSupport, primary); - LogManager::getSingleton().logWarning("GL: Using PBuffers for rendering to textures"); - - //TODO: Depth buffer sharing in pbuffer is left unsupported - } - } - else - { - // No pbuffer support either -- fallback to simplest copying from framebuffer - mRTTManager = new GLCopyingRTTManager(); - LogManager::getSingleton().logWarning("GL: Using framebuffer copy for rendering to textures (worst)"); - LogManager::getSingleton().logWarning("GL: RenderTexture size is restricted to size of framebuffer. If you are on Linux, consider using GLX instead of SDL."); - - //Copy method uses the main depth buffer but no other depth buffer - caps->setCapability(RSC_RTT_MAIN_DEPTHBUFFER_ATTACHABLE); - caps->setCapability(RSC_RTT_DEPTHBUFFER_RESOLUTION_LESSEQUAL); - } - - // Downgrade number of simultaneous targets - caps->setNumMultiRenderTargets(1); - } - - mGLInitialised = true; - } - - void GLRenderSystem::shutdown(void) - { - RenderSystem::shutdown(); - - // Deleting the GLSL program factory - if (mGLSLProgramFactory) - { - // Remove from manager safely - if (HighLevelGpuProgramManager::getSingletonPtr()) - HighLevelGpuProgramManager::getSingleton().removeFactory(mGLSLProgramFactory); - delete mGLSLProgramFactory; - mGLSLProgramFactory = 0; - } - - // Delete extra threads contexts - for (auto pCurContext : mBackgroundContextList) - { - pCurContext->releaseContext(); - OGRE_DELETE pCurContext; - } - mBackgroundContextList.clear(); - - // Deleting the GPU program manager and hardware buffer manager. Has to be done before the mGLSupport->stop(). - delete mGpuProgramManager; - mGpuProgramManager = 0; - - delete mHardwareBufferManager; - mHardwareBufferManager = 0; - - delete mRTTManager; - mRTTManager = 0; - - mGLSupport->stop(); - - delete mTextureManager; - mTextureManager = 0; - - // There will be a new initial window and so forth, thus any call to test - // some params will access an invalid pointer, so it is best to reset - // the whole state. - mGLInitialised = 0; - } - - void GLRenderSystem::setShadingType(ShadeOptions so) - { - // XXX Don't do this when using shader - switch(so) - { - case SO_FLAT: - mStateCacheManager->setShadeModel(GL_FLAT); - break; - default: - mStateCacheManager->setShadeModel(GL_SMOOTH); - break; - } - } - //--------------------------------------------------------------------- - RenderWindow* GLRenderSystem::_createRenderWindow(const String &name, - unsigned int width, unsigned int height, bool fullScreen, - const NameValuePairList *miscParams) - { - RenderSystem::_createRenderWindow(name, width, height, fullScreen, miscParams); - - // Create the window - RenderWindow* win = mGLSupport->newWindow(name, width, height, - fullScreen, miscParams); - - attachRenderTarget( *win ); - - if (!mGLInitialised) - { - // set up glew and GLSupport - initialiseContext(win); - - const char* shadingLangVersion = (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION); - StringVector tokens = StringUtil::split(shadingLangVersion, ". "); - mNativeShadingLanguageVersion = (StringConverter::parseUnsignedInt(tokens[0]) * 100) + StringConverter::parseUnsignedInt(tokens[1]); - - auto it = mOptions.find("Fixed Pipeline Enabled"); - if (it != mOptions.end()) - { - mEnableFixedPipeline = StringConverter::parseBool(it->second.currentValue); - } - - // Initialise GL after the first window has been created - // TODO: fire this from emulation options, and don't duplicate Real and Current capabilities - mRealCapabilities = createRenderSystemCapabilities(); - initFixedFunctionParams(); // create params - - // use real capabilities if custom capabilities are not available - if(!mUseCustomCapabilities) - mCurrentCapabilities = mRealCapabilities; - - fireEvent("RenderSystemCapabilitiesCreated"); - - initialiseFromRenderSystemCapabilities(mCurrentCapabilities, win); - - // Initialise the main context - _oneTimeContextInitialization(); - if(mCurrentContext) - mCurrentContext->setInitialized(); - } - - if( win->getDepthBufferPool() != DepthBuffer::POOL_NO_DEPTH ) - { - //Unlike D3D9, OGL doesn't allow sharing the main depth buffer, so keep them separate. - //Only Copy does, but Copy means only one depth buffer... - GLContext *windowContext = dynamic_cast(win)->getContext();; - - auto depthBuffer = - new GLDepthBufferCommon(DepthBuffer::POOL_DEFAULT, this, windowContext, 0, 0, win, true); - - mDepthBufferPool[depthBuffer->getPoolId()].push_back( depthBuffer ); - - win->attachDepthBuffer( depthBuffer ); - } - - return win; - } - //--------------------------------------------------------------------- - DepthBuffer* GLRenderSystem::_createDepthBufferFor( RenderTarget *renderTarget ) - { - if( auto fbo = dynamic_cast(renderTarget)->getFBO() ) - { - //Find best depth & stencil format suited for the RT's format - GLuint depthFormat, stencilFormat; - mRTTManager->getBestDepthStencil(fbo->getFormat(), &depthFormat, &stencilFormat); - - GLRenderBuffer *depthBuffer = new GLRenderBuffer( depthFormat, fbo->getWidth(), - fbo->getHeight(), fbo->getFSAA() ); - - GLRenderBuffer *stencilBuffer = NULL; - if ( depthFormat == GL_DEPTH24_STENCIL8_EXT) - { - // If we have a packed format, the stencilBuffer is the same as the depthBuffer - stencilBuffer = depthBuffer; - } - else if(stencilFormat) - { - stencilBuffer = new GLRenderBuffer( stencilFormat, fbo->getWidth(), - fbo->getHeight(), fbo->getFSAA() ); - } - - return new GLDepthBufferCommon(0, this, mCurrentContext, depthBuffer, stencilBuffer, - renderTarget, false); - } - - return NULL; - } - - void GLRenderSystem::initialiseContext(RenderWindow* primary) - { - // Set main and current context - mMainContext = dynamic_cast(primary)->getContext(); - mCurrentContext = mMainContext; - - // Set primary context as active - if(mCurrentContext) - mCurrentContext->setCurrent(); - - gladLoadGLLoader(get_proc); - - if (!GLAD_GL_VERSION_1_5) { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "OpenGL 1.5 is not supported", - "GLRenderSystem::initialiseContext"); - } - - // Get extension function pointers - initialiseExtensions(); - - mStateCacheManager = mCurrentContext->createOrRetrieveStateCacheManager(); - - LogManager::getSingleton().logMessage("***************************"); - LogManager::getSingleton().logMessage("*** GL Renderer Started ***"); - LogManager::getSingleton().logMessage("***************************"); - } - - - - //----------------------------------------------------------------------- - MultiRenderTarget * GLRenderSystem::createMultiRenderTarget(const String & name) - { - auto fboMgr = dynamic_cast(mRTTManager); - if (!fboMgr) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "MultiRenderTarget is not supported"); - - MultiRenderTarget *retval = new GLFBOMultiRenderTarget(fboMgr, name); - attachRenderTarget( *retval ); - return retval; - } - - //----------------------------------------------------------------------- - void GLRenderSystem::destroyRenderWindow(const String& name) - { - // Find it to remove from list. - RenderTarget* pWin = detachRenderTarget(name); - OgreAssert(pWin, "unknown RenderWindow name"); - - GLContext *windowContext = dynamic_cast(pWin)->getContext(); - - //1 Window <-> 1 Context, should be always true - assert( windowContext ); - - bool bFound = false; - //Find the depth buffer from this window and remove it. - DepthBufferMap::iterator itMap = mDepthBufferPool.begin(); - DepthBufferMap::iterator enMap = mDepthBufferPool.end(); - - while( itMap != enMap && !bFound ) - { - DepthBufferVec::iterator itor = itMap->second.begin(); - DepthBufferVec::iterator end = itMap->second.end(); - - while( itor != end ) - { - //A DepthBuffer with no depth & stencil pointers is a dummy one, - //look for the one that matches the same GL context - auto depthBuffer = static_cast(*itor); - GLContext *glContext = depthBuffer->getGLContext(); - - if( glContext == windowContext && - (depthBuffer->getDepthBuffer() || depthBuffer->getStencilBuffer()) ) - { - bFound = true; - - delete *itor; - itMap->second.erase( itor ); - break; - } - ++itor; - } - - ++itMap; - } - - delete pWin; - } - - //--------------------------------------------------------------------- - void GLRenderSystem::_useLights(unsigned short limit) - { - if(limit == mCurrentLights) - return; - - unsigned short num = 0; - for (;num < limit; ++num) - { - setGLLight(num, true); - } - // Disable extra lights - for (; num < mCurrentLights; ++num) - { - setGLLight(num, false); - } - mCurrentLights = limit; - } - - void GLRenderSystem::setGLLight(size_t index, bool lt) - { - setFFPLightParams(index, lt); - - GLenum gl_index = GL_LIGHT0 + index; - - if (!lt) - { - // Disable in the scene - mStateCacheManager->setEnabled(gl_index, false); - } - else - { - GLfloat f4vals[4] = {0, 0, 0, 1}; - // Disable ambient light for movables; - glLightfv(gl_index, GL_AMBIENT, f4vals); - - // Enable in the scene - mStateCacheManager->setEnabled(gl_index, true); - } - } - - //----------------------------------------------------------------------------- - void GLRenderSystem::makeGLMatrix(GLfloat gl_matrix[16], const Matrix4& m) - { - size_t x = 0; - for (size_t i = 0; i < 4; i++) - { - for (size_t j = 0; j < 4; j++) - { - gl_matrix[x] = m[j][i]; - x++; - } - } - } - //----------------------------------------------------------------------------- - void GLRenderSystem::setWorldMatrix( const Matrix4 &m ) - { - mWorldMatrix = m; - glMatrixMode(GL_MODELVIEW); - glLoadMatrixf(Matrix4f((mViewMatrix * mWorldMatrix).transpose())[0]); - } - - //----------------------------------------------------------------------------- - void GLRenderSystem::setViewMatrix( const Matrix4 &m ) - { - mViewMatrix = m; - glMatrixMode(GL_MODELVIEW); - glLoadMatrixf(Matrix4f((mViewMatrix * mWorldMatrix).transpose())[0]); - - // also mark clip planes dirty - if (!mClipPlanes.empty()) - mClipPlanesDirty = true; - } - //----------------------------------------------------------------------------- - void GLRenderSystem::setProjectionMatrix(const Matrix4 &m) - { - glMatrixMode(GL_PROJECTION); - glLoadMatrixf(Matrix4f(m.transpose())[0]); - glMatrixMode(GL_MODELVIEW); - - // also mark clip planes dirty - if (!mClipPlanes.empty()) - mClipPlanesDirty = true; - } - //----------------------------------------------------------------------------- - void GLRenderSystem::_setSurfaceTracking(TrackVertexColourType tracking) - { - - // Track vertex colour - if(tracking != TVC_NONE) - { - GLenum gt = GL_DIFFUSE; - // There are actually 15 different combinations for tracking, of which - // GL only supports the most used 5. This means that we have to do some - // magic to find the best match. NOTE: - // GL_AMBIENT_AND_DIFFUSE != GL_AMBIENT | GL__DIFFUSE - if(tracking & TVC_AMBIENT) - { - if(tracking & TVC_DIFFUSE) - { - gt = GL_AMBIENT_AND_DIFFUSE; - } - else - { - gt = GL_AMBIENT; - } - } - else if(tracking & TVC_DIFFUSE) - { - gt = GL_DIFFUSE; - } - else if(tracking & TVC_SPECULAR) - { - gt = GL_SPECULAR; - } - else if(tracking & TVC_EMISSIVE) - { - gt = GL_EMISSION; - } - glColorMaterial(GL_FRONT_AND_BACK, gt); - - mStateCacheManager->setEnabled(GL_COLOR_MATERIAL, true); - } - else - { - mStateCacheManager->setEnabled(GL_COLOR_MATERIAL, false); - } - } - //----------------------------------------------------------------------------- - void GLRenderSystem::_setPointParameters(bool attenuationEnabled, Real minSize, Real maxSize) - { - if(attenuationEnabled) - { - // Point size is still calculated in pixels even when attenuation is - // enabled, which is pretty awkward, since you typically want a viewport - // independent size if you're looking for attenuation. - // So, scale the point size up by viewport size (this is equivalent to - // what D3D does as standard) - minSize = minSize * mActiveViewport->getActualHeight(); - if (maxSize == 0.0f) - maxSize = mCurrentCapabilities->getMaxPointSize(); // pixels - else - maxSize = maxSize * mActiveViewport->getActualHeight(); - - if (mCurrentCapabilities->hasCapability(RSC_VERTEX_PROGRAM)) - mStateCacheManager->setEnabled(GL_VERTEX_PROGRAM_POINT_SIZE, true); - } - else - { - if (maxSize == 0.0f) - maxSize = mCurrentCapabilities->getMaxPointSize(); - if (mCurrentCapabilities->hasCapability(RSC_VERTEX_PROGRAM)) - mStateCacheManager->setEnabled(GL_VERTEX_PROGRAM_POINT_SIZE, false); - } - - mStateCacheManager->setPointParameters(NULL, minSize, maxSize); - } - - void GLRenderSystem::_setLineWidth(float width) - { - glLineWidth(width); - } - - //--------------------------------------------------------------------- - void GLRenderSystem::_setPointSpritesEnabled(bool enabled) - { - if (!getCapabilities()->hasCapability(RSC_POINT_SPRITES)) - return; - - mStateCacheManager->setEnabled(GL_POINT_SPRITE, enabled); - - // Set sprite texture coord generation - // Don't offer this as an option since D3D links it to sprite enabled - for (ushort i = 0; i < mFixedFunctionTextureUnits; ++i) - { - mStateCacheManager->activateGLTextureUnit(i); - glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, - enabled ? GL_TRUE : GL_FALSE); - } - } - //----------------------------------------------------------------------------- - void GLRenderSystem::_setTexture(size_t stage, bool enabled, const TexturePtr &texPtr) - { - GLenum lastTextureType = mTextureTypes[stage]; - - mStateCacheManager->activateGLTextureUnit(stage); - - if (enabled) - { - GLTexturePtr tex = static_pointer_cast(texPtr); - - // note used - tex->touch(); - mTextureTypes[stage] = tex->getGLTextureTarget(); - - if(lastTextureType != mTextureTypes[stage] && lastTextureType != 0) - { - if (stage < mFixedFunctionTextureUnits) - { - if(lastTextureType != GL_TEXTURE_2D_ARRAY_EXT) - glDisable( lastTextureType ); - } - } - - if (stage < mFixedFunctionTextureUnits) - { - if(mTextureTypes[stage] != GL_TEXTURE_2D_ARRAY_EXT) - glEnable( mTextureTypes[stage] ); - } - - mStateCacheManager->bindGLTexture( mTextureTypes[stage], tex->getGLID() ); - } - else - { - if (stage < mFixedFunctionTextureUnits) - { - if (lastTextureType != 0) - { - if(mTextureTypes[stage] != GL_TEXTURE_2D_ARRAY_EXT) - glDisable( mTextureTypes[stage] ); - } - glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - } - // bind zero texture - mStateCacheManager->bindGLTexture(GL_TEXTURE_2D, 0); - } - } - - void GLRenderSystem::_setSampler(size_t unit, Sampler& sampler) - { - mStateCacheManager->activateGLTextureUnit(unit); - - GLenum target = mTextureTypes[unit]; - - const Sampler::UVWAddressingMode& uvw = sampler.getAddressingMode(); - mStateCacheManager->setTexParameteri(target, GL_TEXTURE_WRAP_S, getTextureAddressingMode(uvw.u)); - mStateCacheManager->setTexParameteri(target, GL_TEXTURE_WRAP_T, getTextureAddressingMode(uvw.v)); - mStateCacheManager->setTexParameteri(target, GL_TEXTURE_WRAP_R, getTextureAddressingMode(uvw.w)); - - if (uvw.u == TAM_BORDER || uvw.v == TAM_BORDER || uvw.w == TAM_BORDER) - glTexParameterfv( target, GL_TEXTURE_BORDER_COLOR, sampler.getBorderColour().ptr()); - - if (mCurrentCapabilities->hasCapability(RSC_MIPMAP_LOD_BIAS)) - { - glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, sampler.getMipmapBias()); - } - - if (mCurrentCapabilities->hasCapability(RSC_ANISOTROPY)) - mStateCacheManager->setTexParameteri( - target, GL_TEXTURE_MAX_ANISOTROPY_EXT, - std::min(mCurrentCapabilities->getMaxSupportedAnisotropy(), sampler.getAnisotropy())); - - if(GLAD_GL_VERSION_2_0) - { - mStateCacheManager->setTexParameteri(target, GL_TEXTURE_COMPARE_MODE, - sampler.getCompareEnabled() ? GL_COMPARE_REF_DEPTH_TO_TEXTURE_EXT - : GL_NONE); - if (sampler.getCompareEnabled()) - mStateCacheManager->setTexParameteri(target, GL_TEXTURE_COMPARE_FUNC, - convertCompareFunction(sampler.getCompareFunction())); - } - - // Combine with existing mip filter - mStateCacheManager->setTexParameteri( - target, GL_TEXTURE_MIN_FILTER, - getCombinedMinMipFilter(sampler.getFiltering(FT_MIN), sampler.getFiltering(FT_MIP))); - - switch (sampler.getFiltering(FT_MAG)) - { - case FO_ANISOTROPIC: // GL treats linear and aniso the same - case FO_LINEAR: - mStateCacheManager->setTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - break; - case FO_POINT: - case FO_NONE: - mStateCacheManager->setTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - break; - } - } - - //----------------------------------------------------------------------------- - void GLRenderSystem::_setTextureCoordSet(size_t stage, size_t index) - { - mTextureCoordIndex[stage] = index; - } - //----------------------------------------------------------------------------- - void GLRenderSystem::_setTextureCoordCalculation(size_t stage, TexCoordCalcMethod m, - const Frustum* frustum) - { - if (stage >= mFixedFunctionTextureUnits) - { - // Can't do this - return; - } - - GLfloat M[16]; - Matrix4 projectionBias; - - // Default to no extra auto texture matrix - mUseAutoTextureMatrix = false; - - GLfloat eyePlaneS[] = {1.0, 0.0, 0.0, 0.0}; - GLfloat eyePlaneT[] = {0.0, 1.0, 0.0, 0.0}; - GLfloat eyePlaneR[] = {0.0, 0.0, 1.0, 0.0}; - GLfloat eyePlaneQ[] = {0.0, 0.0, 0.0, 1.0}; - - mStateCacheManager->activateGLTextureUnit(stage); - - switch( m ) - { - case TEXCALC_NONE: - mStateCacheManager->disableTextureCoordGen( GL_TEXTURE_GEN_S ); - mStateCacheManager->disableTextureCoordGen( GL_TEXTURE_GEN_T ); - mStateCacheManager->disableTextureCoordGen( GL_TEXTURE_GEN_R ); - mStateCacheManager->disableTextureCoordGen( GL_TEXTURE_GEN_Q ); - break; - - case TEXCALC_ENVIRONMENT_MAP_PLANAR: - // should be view position .xy, according to doc, but we want to match OGRE D3D9 behaviour here - case TEXCALC_ENVIRONMENT_MAP: - glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP ); - glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP ); - - mStateCacheManager->enableTextureCoordGen( GL_TEXTURE_GEN_S ); - mStateCacheManager->enableTextureCoordGen( GL_TEXTURE_GEN_T ); - mStateCacheManager->disableTextureCoordGen( GL_TEXTURE_GEN_R ); - mStateCacheManager->disableTextureCoordGen( GL_TEXTURE_GEN_Q ); - - // Need to use a texture matrix to flip the spheremap - mUseAutoTextureMatrix = true; - memset(mAutoTextureMatrix, 0, sizeof(GLfloat)*16); - mAutoTextureMatrix[0] = mAutoTextureMatrix[10] = mAutoTextureMatrix[15] = 1.0f; - mAutoTextureMatrix[5] = -1.0f; - - break; - - case TEXCALC_ENVIRONMENT_MAP_REFLECTION: - - glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP ); - glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP ); - glTexGeni( GL_R, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP ); - - mStateCacheManager->enableTextureCoordGen( GL_TEXTURE_GEN_S ); - mStateCacheManager->enableTextureCoordGen( GL_TEXTURE_GEN_T ); - mStateCacheManager->enableTextureCoordGen( GL_TEXTURE_GEN_R ); - mStateCacheManager->disableTextureCoordGen( GL_TEXTURE_GEN_Q ); - - // We need an extra texture matrix here - // This sets the texture matrix to be the inverse of the view matrix - mUseAutoTextureMatrix = true; - makeGLMatrix( M, mViewMatrix); - - // Transpose 3x3 in order to invert matrix (rotation) - // Note that we need to invert the Z _before_ the rotation - // No idea why we have to invert the Z at all, but reflection is wrong without it - mAutoTextureMatrix[0] = M[0]; mAutoTextureMatrix[1] = M[4]; mAutoTextureMatrix[2] = -M[8]; - mAutoTextureMatrix[4] = M[1]; mAutoTextureMatrix[5] = M[5]; mAutoTextureMatrix[6] = -M[9]; - mAutoTextureMatrix[8] = M[2]; mAutoTextureMatrix[9] = M[6]; mAutoTextureMatrix[10] = -M[10]; - mAutoTextureMatrix[3] = mAutoTextureMatrix[7] = mAutoTextureMatrix[11] = 0.0f; - mAutoTextureMatrix[12] = mAutoTextureMatrix[13] = mAutoTextureMatrix[14] = 0.0f; - mAutoTextureMatrix[15] = 1.0f; - - break; - case TEXCALC_ENVIRONMENT_MAP_NORMAL: - glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, GL_NORMAL_MAP ); - glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, GL_NORMAL_MAP ); - glTexGeni( GL_R, GL_TEXTURE_GEN_MODE, GL_NORMAL_MAP ); - - mStateCacheManager->enableTextureCoordGen( GL_TEXTURE_GEN_S ); - mStateCacheManager->enableTextureCoordGen( GL_TEXTURE_GEN_T ); - mStateCacheManager->enableTextureCoordGen( GL_TEXTURE_GEN_R ); - mStateCacheManager->disableTextureCoordGen( GL_TEXTURE_GEN_Q ); - break; - case TEXCALC_PROJECTIVE_TEXTURE: - glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); - glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); - glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); - glTexGeni(GL_Q, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR); - glTexGenfv(GL_S, GL_EYE_PLANE, eyePlaneS); - glTexGenfv(GL_T, GL_EYE_PLANE, eyePlaneT); - glTexGenfv(GL_R, GL_EYE_PLANE, eyePlaneR); - glTexGenfv(GL_Q, GL_EYE_PLANE, eyePlaneQ); - mStateCacheManager->enableTextureCoordGen(GL_TEXTURE_GEN_S); - mStateCacheManager->enableTextureCoordGen(GL_TEXTURE_GEN_T); - mStateCacheManager->enableTextureCoordGen(GL_TEXTURE_GEN_R); - mStateCacheManager->enableTextureCoordGen(GL_TEXTURE_GEN_Q); - - mUseAutoTextureMatrix = true; - - // Set scale and translation matrix for projective textures - projectionBias = Matrix4::CLIPSPACE2DTOIMAGESPACE; - - projectionBias = projectionBias * frustum->getProjectionMatrix(); - if(mTexProjRelative) - { - Matrix4 viewMatrix; - frustum->calcViewMatrixRelative(mTexProjRelativeOrigin, viewMatrix); - projectionBias = projectionBias * viewMatrix; - } - else - { - projectionBias = projectionBias * frustum->getViewMatrix(); - } - projectionBias = projectionBias * mWorldMatrix; - - makeGLMatrix(mAutoTextureMatrix, projectionBias); - break; - default: - break; - } - } - //----------------------------------------------------------------------------- - GLint GLRenderSystem::getTextureAddressingMode( - TextureAddressingMode tam) const - { - switch(tam) - { - default: - case TextureUnitState::TAM_WRAP: - return GL_REPEAT; - case TextureUnitState::TAM_MIRROR: - return GL_MIRRORED_REPEAT; - case TextureUnitState::TAM_CLAMP: - return GL_CLAMP_TO_EDGE; - case TextureUnitState::TAM_BORDER: - return GL_CLAMP_TO_BORDER; - } - - } - //----------------------------------------------------------------------------- - void GLRenderSystem::_setTextureMatrix(size_t stage, const Matrix4& xform) - { - if (stage >= mFixedFunctionTextureUnits) - { - // Can't do this - return; - } - - mStateCacheManager->activateGLTextureUnit(stage); - glMatrixMode(GL_TEXTURE); - - // Load this matrix in - glLoadMatrixf(Matrix4f(xform.transpose())[0]); - - if (mUseAutoTextureMatrix) - { - // Concat auto matrix - glMultMatrixf(mAutoTextureMatrix); - } - - glMatrixMode(GL_MODELVIEW); - } - //----------------------------------------------------------------------------- - GLint GLRenderSystem::getBlendMode(SceneBlendFactor ogreBlend) const - { - switch(ogreBlend) - { - case SBF_ONE: - return GL_ONE; - case SBF_ZERO: - return GL_ZERO; - case SBF_DEST_COLOUR: - return GL_DST_COLOR; - case SBF_SOURCE_COLOUR: - return GL_SRC_COLOR; - case SBF_ONE_MINUS_DEST_COLOUR: - return GL_ONE_MINUS_DST_COLOR; - case SBF_ONE_MINUS_SOURCE_COLOUR: - return GL_ONE_MINUS_SRC_COLOR; - case SBF_DEST_ALPHA: - return GL_DST_ALPHA; - case SBF_SOURCE_ALPHA: - return GL_SRC_ALPHA; - case SBF_ONE_MINUS_DEST_ALPHA: - return GL_ONE_MINUS_DST_ALPHA; - case SBF_ONE_MINUS_SOURCE_ALPHA: - return GL_ONE_MINUS_SRC_ALPHA; - }; - // to keep compiler happy - return GL_ONE; - } - //----------------------------------------------------------------------------- - void GLRenderSystem::_setAlphaRejectSettings(CompareFunction func, unsigned char value, bool alphaToCoverage) - { - bool enable = func != CMPF_ALWAYS_PASS; - - mStateCacheManager->setEnabled(GL_ALPHA_TEST, enable); - - if(enable) - { - glAlphaFunc(convertCompareFunction(func), value / 255.0f); - } - - if (getCapabilities()->hasCapability(RSC_ALPHA_TO_COVERAGE)) - { - mStateCacheManager->setEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE, alphaToCoverage && enable); - } - - } - //----------------------------------------------------------------------------- - void GLRenderSystem::_setViewport(Viewport *vp) - { - // Check if viewport is different - if (!vp) - { - mActiveViewport = NULL; - _setRenderTarget(NULL); - } - else if (vp != mActiveViewport || vp->_isUpdated()) - { - RenderTarget* target; - target = vp->getTarget(); - _setRenderTarget(target); - mActiveViewport = vp; - - // Calculate the "lower-left" corner of the viewport - Rect vpRect = vp->getActualDimensions(); - if (!target->requiresTextureFlipping()) - { - // Convert "upper-left" corner to "lower-left" - std::swap(vpRect.top, vpRect.bottom); - vpRect.top = target->getHeight() - vpRect.top; - vpRect.bottom = target->getHeight() - vpRect.bottom; - } - mStateCacheManager->setViewport(vpRect); - - vp->_clearUpdatedFlag(); - } - } - - //----------------------------------------------------------------------------- - void GLRenderSystem::_endFrame(void) - { - // unbind GPU programs at end of frame - // this is mostly to avoid holding bound programs that might get deleted - // outside via the resource manager - unbindGpuProgram(GPT_VERTEX_PROGRAM); - unbindGpuProgram(GPT_FRAGMENT_PROGRAM); - } - - //----------------------------------------------------------------------------- - void GLRenderSystem::_setCullingMode(CullingMode mode) - { - mCullingMode = mode; - - GLenum cullMode; - bool flip = flipFrontFace(); - glFrontFace(flip ? GL_CW : GL_CCW); - - switch( mode ) - { - case CULL_NONE: - mStateCacheManager->setEnabled( GL_CULL_FACE, false ); - return; - case CULL_CLOCKWISE: - cullMode = GL_BACK; - break; - case CULL_ANTICLOCKWISE: - cullMode = GL_FRONT; - break; - } - - mStateCacheManager->setEnabled( GL_CULL_FACE, true ); - mStateCacheManager->setCullFace( cullMode ); - } - //----------------------------------------------------------------------------- - void GLRenderSystem::_setDepthBufferParams(bool depthTest, bool depthWrite, CompareFunction depthFunction) - { - if (depthTest) - { - mStateCacheManager->setClearDepth(1.0f); - } - mStateCacheManager->setEnabled(GL_DEPTH_TEST, depthTest); - mStateCacheManager->setDepthMask( depthWrite ); - // Store for reference in _beginFrame - mDepthWrite = depthWrite; - mStateCacheManager->setDepthFunc(convertCompareFunction(depthFunction)); - } - //----------------------------------------------------------------------------- - void GLRenderSystem::_setDepthBias(float constantBias, float slopeScaleBias) - { - bool enable = constantBias != 0 || slopeScaleBias != 0; - mStateCacheManager->setEnabled(GL_POLYGON_OFFSET_FILL, enable); - mStateCacheManager->setEnabled(GL_POLYGON_OFFSET_POINT, enable); - mStateCacheManager->setEnabled(GL_POLYGON_OFFSET_LINE, enable); - - if (enable) - { - glPolygonOffset(-slopeScaleBias, -constantBias); - } - } - //----------------------------------------------------------------------------- - static GLenum getBlendOp(SceneBlendOperation op) - { - switch (op) - { - case SBO_ADD: - return GL_FUNC_ADD; - case SBO_SUBTRACT: - return GL_FUNC_SUBTRACT; - case SBO_REVERSE_SUBTRACT: - return GL_FUNC_REVERSE_SUBTRACT; - case SBO_MIN: - return GL_MIN; - case SBO_MAX: - return GL_MAX; - } - return GL_FUNC_ADD; - } - void GLRenderSystem::setColourBlendState(const ColourBlendState& state) - { - // record this - mCurrentBlend = state; - - if (state.blendingEnabled()) - { - mStateCacheManager->setEnabled(GL_BLEND, true); - mStateCacheManager->setBlendFunc( - getBlendMode(state.sourceFactor), getBlendMode(state.destFactor), - getBlendMode(state.sourceFactorAlpha), getBlendMode(state.destFactorAlpha)); - } - else - { - mStateCacheManager->setEnabled(GL_BLEND, false); - } - - mStateCacheManager->setBlendEquation(getBlendOp(state.operation), getBlendOp(state.alphaOperation)); - mStateCacheManager->setColourMask(state.writeR, state.writeG, state.writeB, state.writeA); - } - //----------------------------------------------------------------------------- - void GLRenderSystem::setLightingEnabled(bool enabled) - { - mStateCacheManager->setEnabled(GL_LIGHTING, enabled); - } - //----------------------------------------------------------------------------- - void GLRenderSystem::_setFog(FogMode mode) - { - - GLint fogMode; - switch (mode) - { - case FOG_EXP: - fogMode = GL_EXP; - break; - case FOG_EXP2: - fogMode = GL_EXP2; - break; - case FOG_LINEAR: - fogMode = GL_LINEAR; - break; - default: - // Give up on it - mStateCacheManager->setEnabled(GL_FOG, false); - mFixedFunctionParams->clearAutoConstant(18); - mFixedFunctionParams->clearAutoConstant(19); - return; - } - - mFixedFunctionParams->setAutoConstant(18, GpuProgramParameters::ACT_FOG_PARAMS); - mFixedFunctionParams->setAutoConstant(19, GpuProgramParameters::ACT_FOG_COLOUR); - mStateCacheManager->setEnabled(GL_FOG, true); - glFogi(GL_FOG_MODE, fogMode); - } - - void GLRenderSystem::_setPolygonMode(PolygonMode level) - { - GLenum glmode; - switch(level) - { - case PM_POINTS: - glmode = GL_POINT; - break; - case PM_WIREFRAME: - glmode = GL_LINE; - break; - default: - case PM_SOLID: - glmode = GL_FILL; - break; - } - mStateCacheManager->setPolygonMode(glmode); - } - //--------------------------------------------------------------------- - void GLRenderSystem::setStencilState(const StencilState& state) - { - mStateCacheManager->setEnabled(GL_STENCIL_TEST, state.enabled); - - if(!state.enabled) - return; - - bool flip = false; - mStencilWriteMask = state.writeMask; - - auto compareOp = convertCompareFunction(state.compareOp); - - if (state.twoSidedOperation) - { - if (!mCurrentCapabilities->hasCapability(RSC_TWO_SIDED_STENCIL)) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "2-sided stencils are not supported"); - - if(GLAD_GL_VERSION_2_0) // New GL2 commands - { - // Back - glStencilMaskSeparate(GL_BACK, state.writeMask); - glStencilFuncSeparate(GL_BACK, compareOp, state.referenceValue, state.compareMask); - glStencilOpSeparate(GL_BACK, - convertStencilOp(state.stencilFailOp, !flip), - convertStencilOp(state.depthFailOp, !flip), - convertStencilOp(state.depthStencilPassOp, !flip)); - // Front - glStencilMaskSeparate(GL_FRONT, state.writeMask); - glStencilFuncSeparate(GL_FRONT, compareOp, state.referenceValue, state.compareMask); - glStencilOpSeparate(GL_FRONT, - convertStencilOp(state.stencilFailOp, flip), - convertStencilOp(state.depthFailOp, flip), - convertStencilOp(state.depthStencilPassOp, flip)); - } - else // EXT_stencil_two_side - { - mStateCacheManager->setEnabled(GL_STENCIL_TEST_TWO_SIDE_EXT, true); - // Back - glActiveStencilFaceEXT(GL_BACK); - mStateCacheManager->setStencilMask(state.writeMask); - glStencilFunc(compareOp, state.referenceValue, state.compareMask); - glStencilOp( - convertStencilOp(state.stencilFailOp, !flip), - convertStencilOp(state.depthFailOp, !flip), - convertStencilOp(state.depthStencilPassOp, !flip)); - // Front - glActiveStencilFaceEXT(GL_FRONT); - mStateCacheManager->setStencilMask(state.writeMask); - glStencilFunc(compareOp, state.referenceValue, state.compareMask); - glStencilOp( - convertStencilOp(state.stencilFailOp, flip), - convertStencilOp(state.depthFailOp, flip), - convertStencilOp(state.depthStencilPassOp, flip)); - } - } - else - { - if(!GLAD_GL_VERSION_2_0) - mStateCacheManager->setEnabled(GL_STENCIL_TEST_TWO_SIDE_EXT, false); - - flip = false; - mStateCacheManager->setStencilMask(state.writeMask); - glStencilFunc(compareOp, state.referenceValue, state.compareMask); - glStencilOp( - convertStencilOp(state.stencilFailOp, flip), - convertStencilOp(state.depthFailOp, flip), - convertStencilOp(state.depthStencilPassOp, flip)); - } - } - //--------------------------------------------------------------------- - GLint GLRenderSystem::convertCompareFunction(CompareFunction func) const - { - switch(func) - { - case CMPF_ALWAYS_FAIL: - return GL_NEVER; - case CMPF_ALWAYS_PASS: - return GL_ALWAYS; - case CMPF_LESS: - return GL_LESS; - case CMPF_LESS_EQUAL: - return GL_LEQUAL; - case CMPF_EQUAL: - return GL_EQUAL; - case CMPF_NOT_EQUAL: - return GL_NOTEQUAL; - case CMPF_GREATER_EQUAL: - return GL_GEQUAL; - case CMPF_GREATER: - return GL_GREATER; - }; - // to keep compiler happy - return GL_ALWAYS; - } - //--------------------------------------------------------------------- - GLint GLRenderSystem::convertStencilOp(StencilOperation op, bool invert) const - { - switch(op) - { - case SOP_KEEP: - return GL_KEEP; - case SOP_ZERO: - return GL_ZERO; - case SOP_REPLACE: - return GL_REPLACE; - case SOP_INCREMENT: - return invert ? GL_DECR : GL_INCR; - case SOP_DECREMENT: - return invert ? GL_INCR : GL_DECR; - case SOP_INCREMENT_WRAP: - return invert ? GL_DECR_WRAP_EXT : GL_INCR_WRAP_EXT; - case SOP_DECREMENT_WRAP: - return invert ? GL_INCR_WRAP_EXT : GL_DECR_WRAP_EXT; - case SOP_INVERT: - return GL_INVERT; - }; - // to keep compiler happy - return SOP_KEEP; - } - //----------------------------------------------------------------------------- - void GLRenderSystem::_setTextureBlendMode(size_t stage, const LayerBlendModeEx& bm) - { - if (stage >= mFixedFunctionTextureUnits) - { - // Can't do this - return; - } - - GLenum src1op, src2op, cmd; - GLfloat cv1[4], cv2[4]; - - if (bm.blendType == LBT_COLOUR) - { - cv1[0] = bm.colourArg1.r; - cv1[1] = bm.colourArg1.g; - cv1[2] = bm.colourArg1.b; - cv1[3] = bm.colourArg1.a; - mManualBlendColours[stage][0] = bm.colourArg1; - - - cv2[0] = bm.colourArg2.r; - cv2[1] = bm.colourArg2.g; - cv2[2] = bm.colourArg2.b; - cv2[3] = bm.colourArg2.a; - mManualBlendColours[stage][1] = bm.colourArg2; - } - - if (bm.blendType == LBT_ALPHA) - { - cv1[0] = mManualBlendColours[stage][0].r; - cv1[1] = mManualBlendColours[stage][0].g; - cv1[2] = mManualBlendColours[stage][0].b; - cv1[3] = bm.alphaArg1; - - cv2[0] = mManualBlendColours[stage][1].r; - cv2[1] = mManualBlendColours[stage][1].g; - cv2[2] = mManualBlendColours[stage][1].b; - cv2[3] = bm.alphaArg2; - } - - switch (bm.source1) - { - case LBS_CURRENT: - src1op = GL_PREVIOUS; - break; - case LBS_TEXTURE: - src1op = GL_TEXTURE; - break; - case LBS_MANUAL: - src1op = GL_CONSTANT; - break; - case LBS_DIFFUSE: - src1op = GL_PRIMARY_COLOR; - break; - // XXX - case LBS_SPECULAR: - src1op = GL_PRIMARY_COLOR; - break; - default: - src1op = 0; - } - - switch (bm.source2) - { - case LBS_CURRENT: - src2op = GL_PREVIOUS; - break; - case LBS_TEXTURE: - src2op = GL_TEXTURE; - break; - case LBS_MANUAL: - src2op = GL_CONSTANT; - break; - case LBS_DIFFUSE: - src2op = GL_PRIMARY_COLOR; - break; - // XXX - case LBS_SPECULAR: - src2op = GL_PRIMARY_COLOR; - break; - default: - src2op = 0; - } - - switch (bm.operation) - { - case LBX_SOURCE1: - cmd = GL_REPLACE; - break; - case LBX_SOURCE2: - cmd = GL_REPLACE; - break; - case LBX_MODULATE: - cmd = GL_MODULATE; - break; - case LBX_MODULATE_X2: - cmd = GL_MODULATE; - break; - case LBX_MODULATE_X4: - cmd = GL_MODULATE; - break; - case LBX_ADD: - cmd = GL_ADD; - break; - case LBX_ADD_SIGNED: - cmd = GL_ADD_SIGNED; - break; - case LBX_ADD_SMOOTH: - cmd = GL_INTERPOLATE; - break; - case LBX_SUBTRACT: - cmd = GL_SUBTRACT; - break; - case LBX_BLEND_DIFFUSE_COLOUR: - cmd = GL_INTERPOLATE; - break; - case LBX_BLEND_DIFFUSE_ALPHA: - cmd = GL_INTERPOLATE; - break; - case LBX_BLEND_TEXTURE_ALPHA: - cmd = GL_INTERPOLATE; - break; - case LBX_BLEND_CURRENT_ALPHA: - cmd = GL_INTERPOLATE; - break; - case LBX_BLEND_MANUAL: - cmd = GL_INTERPOLATE; - break; - case LBX_DOTPRODUCT: - cmd = GL_DOT3_RGB; - break; - default: - cmd = 0; - } - - mStateCacheManager->activateGLTextureUnit(stage); - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE); - - if (bm.blendType == LBT_COLOUR) - { - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, cmd); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB, src1op); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB, src2op); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_CONSTANT); - } - else - { - glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, cmd); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA, src1op); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA, src2op); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA, GL_CONSTANT); - } - - float blendValue[4] = {0, 0, 0, static_cast(bm.factor)}; - switch (bm.operation) - { - case LBX_BLEND_DIFFUSE_COLOUR: - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_PRIMARY_COLOR); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA, GL_PRIMARY_COLOR); - break; - case LBX_BLEND_DIFFUSE_ALPHA: - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_PRIMARY_COLOR); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA, GL_PRIMARY_COLOR); - break; - case LBX_BLEND_TEXTURE_ALPHA: - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_TEXTURE); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA, GL_TEXTURE); - break; - case LBX_BLEND_CURRENT_ALPHA: - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB, GL_PREVIOUS); - glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA, GL_PREVIOUS); - break; - case LBX_BLEND_MANUAL: - glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, blendValue); - break; - default: - break; - }; - - switch (bm.operation) - { - case LBX_MODULATE_X2: - glTexEnvi(GL_TEXTURE_ENV, bm.blendType == LBT_COLOUR ? - GL_RGB_SCALE : GL_ALPHA_SCALE, 2); - break; - case LBX_MODULATE_X4: - glTexEnvi(GL_TEXTURE_ENV, bm.blendType == LBT_COLOUR ? - GL_RGB_SCALE : GL_ALPHA_SCALE, 4); - break; - default: - glTexEnvi(GL_TEXTURE_ENV, bm.blendType == LBT_COLOUR ? - GL_RGB_SCALE : GL_ALPHA_SCALE, 1); - break; - } - - if (bm.blendType == LBT_COLOUR){ - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB, GL_SRC_COLOR); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB, GL_SRC_COLOR); - if (bm.operation == LBX_BLEND_DIFFUSE_COLOUR){ - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_COLOR); - } else { - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_ALPHA); - } - } - - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA, GL_SRC_ALPHA); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA, GL_SRC_ALPHA); - glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_ALPHA, GL_SRC_ALPHA); - if(bm.source1 == LBS_MANUAL) - glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, cv1); - if (bm.source2 == LBS_MANUAL) - glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, cv2); - } - //--------------------------------------------------------------------- - void GLRenderSystem::_render(const RenderOperation& op) - { - // Call super class - RenderSystem::_render(op); - - mMaxBuiltInTextureAttribIndex = 0; - - const VertexDeclaration::VertexElementList& decl = - op.vertexData->vertexDeclaration->getElements(); - VertexDeclaration::VertexElementList::const_iterator elemIter, elemEnd; - elemEnd = decl.end(); - - for (elemIter = decl.begin(); elemIter != elemEnd; ++elemIter) - { - const VertexElement & elem = *elemIter; - size_t source = elem.getSource(); - - if (!op.vertexData->vertexBufferBinding->isBufferBound(source)) - continue; // skip unbound elements - - HardwareVertexBufferSharedPtr vertexBuffer = - op.vertexData->vertexBufferBinding->getBuffer(source); - - bindVertexElementToGpu(elem, vertexBuffer, op.vertexData->vertexStart); - } - - auto numberOfInstances = op.numberOfInstances; - - bool multitexturing = (getCapabilities()->getNumTextureUnits() > 1); - if (multitexturing) - glClientActiveTextureARB(GL_TEXTURE0); - - // Find the correct type to render - GLint primType; - switch (op.operationType) - { - case RenderOperation::OT_POINT_LIST: - primType = GL_POINTS; - break; - case RenderOperation::OT_LINE_LIST: - primType = GL_LINES; - break; - case RenderOperation::OT_LINE_LIST_ADJ: - primType = GL_LINES_ADJACENCY_EXT; - break; - case RenderOperation::OT_LINE_STRIP: - primType = GL_LINE_STRIP; - break; - case RenderOperation::OT_LINE_STRIP_ADJ: - primType = GL_LINE_STRIP_ADJACENCY_EXT; - break; - default: - case RenderOperation::OT_TRIANGLE_LIST: - primType = GL_TRIANGLES; - break; - case RenderOperation::OT_TRIANGLE_LIST_ADJ: - primType = GL_TRIANGLES_ADJACENCY_EXT; - break; - case RenderOperation::OT_TRIANGLE_STRIP: - primType = GL_TRIANGLE_STRIP; - break; - case RenderOperation::OT_TRIANGLE_STRIP_ADJ: - primType = GL_TRIANGLE_STRIP_ADJACENCY_EXT; - break; - case RenderOperation::OT_TRIANGLE_FAN: - primType = GL_TRIANGLE_FAN; - break; - } - - if (op.useIndexes) - { - void* pBufferData = 0; - mStateCacheManager->bindGLBuffer(GL_ELEMENT_ARRAY_BUFFER_ARB, - op.indexData->indexBuffer->_getImpl()->getGLBufferId()); - - pBufferData = VBO_BUFFER_OFFSET( - op.indexData->indexStart * op.indexData->indexBuffer->getIndexSize()); - - GLenum indexType = (op.indexData->indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT; - - do - { - if(numberOfInstances > 1) - { - glDrawElementsInstancedARB(primType, op.indexData->indexCount, indexType, pBufferData, numberOfInstances); - } - else - { - glDrawElements(primType, op.indexData->indexCount, indexType, pBufferData); - } - } while (updatePassIterationRenderState()); - - } - else - { - do - { - if(numberOfInstances > 1) - { - glDrawArraysInstancedARB(primType, 0, op.vertexData->vertexCount, numberOfInstances); - } - else - { - glDrawArrays(primType, 0, op.vertexData->vertexCount); - } - } while (updatePassIterationRenderState()); - } - - glDisableClientState( GL_VERTEX_ARRAY ); - // only valid up to GL_MAX_TEXTURE_UNITS, which is recorded in mFixedFunctionTextureUnits - if (multitexturing) - { - unsigned short mNumEnabledTextures = std::max(std::min((unsigned short)mDisabledTexUnitsFrom, mFixedFunctionTextureUnits), (unsigned short)(mMaxBuiltInTextureAttribIndex + 1)); - for (unsigned short i = 0; i < mNumEnabledTextures; i++) - { - // No need to disable for texture units that weren't used - glClientActiveTextureARB(GL_TEXTURE0 + i); - glDisableClientState( GL_TEXTURE_COORD_ARRAY ); - } - glClientActiveTextureARB(GL_TEXTURE0); - } - else - { - glDisableClientState( GL_TEXTURE_COORD_ARRAY ); - } - glDisableClientState( GL_NORMAL_ARRAY ); - glDisableClientState( GL_COLOR_ARRAY ); - if (GLAD_GL_EXT_secondary_color) - { - glDisableClientState( GL_SECONDARY_COLOR_ARRAY ); - } - // unbind any custom attributes - for (unsigned int & ai : mRenderAttribsBound) - { - glDisableVertexAttribArrayARB(ai); - } - - // unbind any instance attributes - for (unsigned int & ai : mRenderInstanceAttribsBound) - { - glVertexAttribDivisorARB(ai, 0); - } - - mRenderAttribsBound.clear(); - mRenderInstanceAttribsBound.clear(); - - } - //--------------------------------------------------------------------- - void GLRenderSystem::setNormaliseNormals(bool normalise) - { - mStateCacheManager->setEnabled(GL_NORMALIZE, normalise); - } - //--------------------------------------------------------------------- - void GLRenderSystem::bindGpuProgram(GpuProgram* prg) - { - if (!prg) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Null program bound.", - "GLRenderSystem::bindGpuProgram"); - } - - GLGpuProgramBase* glprg = dynamic_cast(prg); - - // Unbind previous gpu program first. - // - // Note: - // 1. Even if both previous and current are the same object, we can't - // bypass re-bind completely since the object itself maybe modified. - // But we can bypass unbind based on the assumption that object - // internally GL program type shouldn't be changed after it has - // been created. The behavior of bind to a GL program type twice - // should be same as unbind and rebind that GL program type, even - // for difference objects. - // 2. We also assumed that the program's type (vertex or fragment) should - // not be changed during it's in using. If not, the following switch - // statement will confuse GL state completely, and we can't fix it - // here. To fix this case, we must coding the program implementation - // itself, if type is changing (during load/unload, etc), and it's inuse, - // unbind and notify render system to correct for its state. - // - switch (prg->getType()) - { - case GPT_VERTEX_PROGRAM: - if (mCurrentVertexProgram != glprg) - { - if (mCurrentVertexProgram) - mCurrentVertexProgram->unbindProgram(); - mCurrentVertexProgram = glprg; - } - break; - - case GPT_FRAGMENT_PROGRAM: - if (mCurrentFragmentProgram != glprg) - { - if (mCurrentFragmentProgram) - mCurrentFragmentProgram->unbindProgram(); - mCurrentFragmentProgram = glprg; - } - break; - case GPT_GEOMETRY_PROGRAM: - if (mCurrentGeometryProgram != glprg) - { - if (mCurrentGeometryProgram) - mCurrentGeometryProgram->unbindProgram(); - mCurrentGeometryProgram = glprg; - } - break; - case GPT_COMPUTE_PROGRAM: - case GPT_DOMAIN_PROGRAM: - case GPT_HULL_PROGRAM: - break; - } - - // Bind the program - glprg->bindProgram(); - - RenderSystem::bindGpuProgram(prg); - } - //--------------------------------------------------------------------- - void GLRenderSystem::unbindGpuProgram(GpuProgramType gptype) - { - mActiveParameters[gptype].reset(); - if (gptype == GPT_VERTEX_PROGRAM && mCurrentVertexProgram) - { - mCurrentVertexProgram->unbindProgram(); - mCurrentVertexProgram = 0; - } - else if (gptype == GPT_GEOMETRY_PROGRAM && mCurrentGeometryProgram) - { - mCurrentGeometryProgram->unbindProgram(); - mCurrentGeometryProgram = 0; - } - else if (gptype == GPT_FRAGMENT_PROGRAM && mCurrentFragmentProgram) - { - mCurrentFragmentProgram->unbindProgram(); - mCurrentFragmentProgram = 0; - } - RenderSystem::unbindGpuProgram(gptype); - - } - //--------------------------------------------------------------------- - void GLRenderSystem::bindGpuProgramParameters(GpuProgramType gptype, const GpuProgramParametersPtr& params, uint16 mask) - { - if (mask & (uint16)GPV_GLOBAL) - { - // We could maybe use GL_EXT_bindable_uniform here to produce Dx10-style - // shared constant buffers, but GPU support seems fairly weak? - // for now, just copy - params->_copySharedParams(); - } - mActiveParameters[gptype] = params; - switch (gptype) - { - case GPT_VERTEX_PROGRAM: - mCurrentVertexProgram->bindProgramParameters(params, mask); - break; - case GPT_GEOMETRY_PROGRAM: - mCurrentGeometryProgram->bindProgramParameters(params, mask); - break; - case GPT_FRAGMENT_PROGRAM: - mCurrentFragmentProgram->bindProgramParameters(params, mask); - break; - case GPT_COMPUTE_PROGRAM: - case GPT_DOMAIN_PROGRAM: - case GPT_HULL_PROGRAM: - break; - } - } - //--------------------------------------------------------------------- - void GLRenderSystem::setClipPlanesImpl(const PlaneList& clipPlanes) - { - // A note on GL user clipping: - // When an ARB vertex program is enabled in GL, user clipping is completely - // disabled. There is no way around this, it's just turned off. - // When using GLSL, user clipping can work but you have to include a - // glClipVertex command in your vertex shader. - // Thus the planes set here may not actually be respected. - - - size_t i = 0; - size_t numClipPlanes; - GLdouble clipPlane[4]; - - // Save previous modelview - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - // just load view matrix (identity world) - GLfloat mat[16]; - makeGLMatrix(mat, mViewMatrix); - glLoadMatrixf(mat); - - numClipPlanes = clipPlanes.size(); - for (i = 0; i < numClipPlanes; ++i) - { - GLenum clipPlaneId = static_cast(GL_CLIP_PLANE0 + i); - const Plane& plane = clipPlanes[i]; - - if (i >= 6/*GL_MAX_CLIP_PLANES*/) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to set clip plane", - "GLRenderSystem::setClipPlanes"); - } - - clipPlane[0] = plane.normal.x; - clipPlane[1] = plane.normal.y; - clipPlane[2] = plane.normal.z; - clipPlane[3] = plane.d; - - glClipPlane(clipPlaneId, clipPlane); - mStateCacheManager->setEnabled(clipPlaneId, true); - } - - // disable remaining clip planes - for ( ; i < 6/*GL_MAX_CLIP_PLANES*/; ++i) - { - mStateCacheManager->setEnabled(static_cast(GL_CLIP_PLANE0 + i), false); - } - - // restore matrices - glPopMatrix(); - } - //--------------------------------------------------------------------- - void GLRenderSystem::setScissorTest(bool enabled, const Rect& rect) - { - mStateCacheManager->setEnabled(GL_SCISSOR_TEST, enabled); - - if (!enabled) - return; - - // If request texture flipping, use "upper-left", otherwise use "lower-left" - bool flipping = mActiveRenderTarget->requiresTextureFlipping(); - // GL measures from the bottom, not the top - long targetHeight = mActiveRenderTarget->getHeight(); - long top = flipping ? rect.top : targetHeight - rect.bottom; - // NB GL uses width / height rather than right / bottom - glScissor(rect.left, top, rect.width(), rect.height()); - } - //--------------------------------------------------------------------- - void GLRenderSystem::clearFrameBuffer(unsigned int buffers, - const ColourValue& colour, float depth, unsigned short stencil) - { - bool colourMask = - !(mCurrentBlend.writeR && mCurrentBlend.writeG && mCurrentBlend.writeB && mCurrentBlend.writeA); - - if(mCurrentContext) - mCurrentContext->setCurrent(); - - GLbitfield flags = 0; - if (buffers & FBT_COLOUR) - { - flags |= GL_COLOR_BUFFER_BIT; - // Enable buffer for writing if it isn't - if (colourMask) - { - mStateCacheManager->setColourMask(true, true, true, true); - } - mStateCacheManager->setClearColour(colour.r, colour.g, colour.b, colour.a); - } - if (buffers & FBT_DEPTH) - { - flags |= GL_DEPTH_BUFFER_BIT; - // Enable buffer for writing if it isn't - if (!mDepthWrite) - { - mStateCacheManager->setDepthMask( GL_TRUE ); - } - mStateCacheManager->setClearDepth(depth); - } - if (buffers & FBT_STENCIL) - { - flags |= GL_STENCIL_BUFFER_BIT; - // Enable buffer for writing if it isn't - mStateCacheManager->setStencilMask(0xFFFFFFFF); - - glClearStencil(stencil); - } - - Rect vpRect = mActiveViewport->getActualDimensions(); - bool needScissorBox = - vpRect != Rect(0, 0, mActiveRenderTarget->getWidth(), mActiveRenderTarget->getHeight()); - if (needScissorBox) - { - // Should be enable scissor test due the clear region is - // relied on scissor box bounds. - setScissorTest(true, vpRect); - } - - // Clear buffers - glClear(flags); - - // Restore scissor test - if (needScissorBox) - { - setScissorTest(false); - } - - // Reset buffer write state - if (!mDepthWrite && (buffers & FBT_DEPTH)) - { - mStateCacheManager->setDepthMask( GL_FALSE ); - } - if (colourMask && (buffers & FBT_COLOUR)) - { - mStateCacheManager->setColourMask(mCurrentBlend.writeR, mCurrentBlend.writeG, - mCurrentBlend.writeB, mCurrentBlend.writeA); - } - if (buffers & FBT_STENCIL) - { - mStateCacheManager->setStencilMask(mStencilWriteMask); - } - } - //--------------------------------------------------------------------- - HardwareOcclusionQuery* GLRenderSystem::createHardwareOcclusionQuery(void) - { - GLHardwareOcclusionQuery* ret = new GLHardwareOcclusionQuery(); - mHwOcclusionQueries.push_back(ret); - return ret; - } - //--------------------------------------------------------------------- - void GLRenderSystem::_oneTimeContextInitialization() - { - // Set nicer lighting model -- d3d9 has this by default - glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR); - glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1); - mStateCacheManager->setEnabled(GL_COLOR_SUM, true); - mStateCacheManager->setEnabled(GL_DITHER, false); - - // Check for FSAA - // Enable the extension if it was enabled by the GLSupport - if (checkExtension("GL_ARB_multisample")) - { - int fsaa_active = false; - glGetIntegerv(GL_SAMPLE_BUFFERS_ARB,(GLint*)&fsaa_active); - if(fsaa_active) - { - mStateCacheManager->setEnabled(GL_MULTISAMPLE_ARB, true); - LogManager::getSingleton().logMessage("Using FSAA from GL_ARB_multisample extension."); - } - } - - if (checkExtension("GL_ARB_seamless_cube_map")) - { - // Enable seamless cube maps - glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); - } - } - - //--------------------------------------------------------------------- - void GLRenderSystem::_switchContext(GLContext *context) - { - // Unbind GPU programs and rebind to new context later, because - // scene manager treat render system as ONE 'context' ONLY, and it - // cached the GPU programs using state. - if (mCurrentVertexProgram) - mCurrentVertexProgram->unbindProgram(); - if (mCurrentGeometryProgram) - mCurrentGeometryProgram->unbindProgram(); - if (mCurrentFragmentProgram) - mCurrentFragmentProgram->unbindProgram(); - - // Disable lights - for (unsigned short i = 0; i < mCurrentLights; ++i) - { - setGLLight(i, false); - } - mCurrentLights = 0; - - // Disable textures - _disableTextureUnitsFrom(0); - - // It's ready for switching - if (mCurrentContext!=context) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE - // NSGLContext::makeCurrentContext does not flush automatically. everybody else does. - glFlushRenderAPPLE(); -#endif - if (mCurrentContext) - mCurrentContext->endCurrent(); - mCurrentContext = context; - } - - if (mCurrentContext) - { - mCurrentContext->setCurrent(); - - mStateCacheManager = mCurrentContext->createOrRetrieveStateCacheManager(); - - // Check if the context has already done one-time initialisation - if(!mCurrentContext->getInitialized()) - { - _oneTimeContextInitialization(); - mCurrentContext->setInitialized(); - } - } - - // Rebind GPU programs to new context - if (mCurrentVertexProgram) - mCurrentVertexProgram->bindProgram(); - if (mCurrentGeometryProgram) - mCurrentGeometryProgram->bindProgram(); - if (mCurrentFragmentProgram) - mCurrentFragmentProgram->bindProgram(); - - // Must reset depth/colour write mask to according with user desired, otherwise, - // clearFrameBuffer would be wrong because the value we are recorded may be - // difference with the really state stored in GL context. - mStateCacheManager->setDepthMask(mDepthWrite); - mStateCacheManager->setColourMask(mCurrentBlend.writeR, mCurrentBlend.writeG, - mCurrentBlend.writeB, mCurrentBlend.writeA); - mStateCacheManager->setStencilMask(mStencilWriteMask); - - } - //--------------------------------------------------------------------- - void GLRenderSystem::_setRenderTarget(RenderTarget *target) - { - // Unbind frame buffer object - if(mActiveRenderTarget) - mRTTManager->unbind(mActiveRenderTarget); - - mActiveRenderTarget = target; - if (target) - { - // Switch context if different from current one - GLContext *newContext = dynamic_cast(target)->getContext(); - if(newContext && mCurrentContext != newContext) - { - _switchContext(newContext); - } - - //Check the FBO's depth buffer status - auto depthBuffer = static_cast(target->getDepthBuffer()); - - if( target->getDepthBufferPool() != DepthBuffer::POOL_NO_DEPTH && - (!depthBuffer || depthBuffer->getGLContext() != mCurrentContext ) ) - { - //Depth is automatically managed and there is no depth buffer attached to this RT - //or the Current context doesn't match the one this Depth buffer was created with - setDepthBufferFor( target ); - } - - // Bind frame buffer object - mRTTManager->bind(target); - - if (GLAD_GL_EXT_framebuffer_sRGB) - { - // Enable / disable sRGB states - mStateCacheManager->setEnabled(GL_FRAMEBUFFER_SRGB_EXT, target->isHardwareGammaEnabled()); - // Note: could test GL_FRAMEBUFFER_SRGB_CAPABLE_EXT here before - // enabling, but GL spec says incapable surfaces ignore the setting - // anyway. We test the capability to enable isHardwareGammaEnabled. - } - } - } - //--------------------------------------------------------------------- - void GLRenderSystem::_unregisterContext(GLContext *context) - { - if(mCurrentContext == context) { - // Change the context to something else so that a valid context - // remains active. When this is the main context being unregistered, - // we set the main context to 0. - if(mCurrentContext != mMainContext) { - _switchContext(mMainContext); - } else { - /// No contexts remain - mCurrentContext->endCurrent(); - mCurrentContext = 0; - mMainContext = 0; - mStateCacheManager = 0; - } - } - } - - //--------------------------------------------------------------------- - void GLRenderSystem::beginProfileEvent( const String &eventName ) - { - markProfileEvent("Begin Event: " + eventName); - } - - //--------------------------------------------------------------------- - void GLRenderSystem::endProfileEvent( void ) - { - markProfileEvent("End Event"); - } - - //--------------------------------------------------------------------- - void GLRenderSystem::markProfileEvent( const String &eventName ) - { - if( eventName.empty() ) - return; - - if(GLAD_GL_GREMEDY_string_marker) - glStringMarkerGREMEDY(eventName.length(), eventName.c_str()); - } - - //--------------------------------------------------------------------- - void GLRenderSystem::bindVertexElementToGpu(const VertexElement& elem, - const HardwareVertexBufferSharedPtr& vertexBuffer, - const size_t vertexStart) - { - void* pBufferData = 0; - const GLHardwareBuffer* hwGlBuffer = vertexBuffer->_getImpl(); - - mStateCacheManager->bindGLBuffer(GL_ARRAY_BUFFER_ARB, - hwGlBuffer->getGLBufferId()); - pBufferData = VBO_BUFFER_OFFSET(elem.getOffset()); - - if (vertexStart) - { - pBufferData = static_cast(pBufferData) + vertexStart * vertexBuffer->getVertexSize(); - } - - VertexElementSemantic sem = elem.getSemantic(); - bool multitexturing = (getCapabilities()->getNumTextureUnits() > 1); - - bool isCustomAttrib = false; - if (mCurrentVertexProgram) - { - isCustomAttrib = !mEnableFixedPipeline || mCurrentVertexProgram->isAttributeValid(sem, elem.getIndex()); - - if (vertexBuffer->isInstanceData()) - { - GLint attrib = GLSLProgramCommon::getFixedAttributeIndex(sem, elem.getIndex()); - glVertexAttribDivisorARB(attrib, vertexBuffer->getInstanceDataStepRate() ); - mRenderInstanceAttribsBound.push_back(attrib); - } - } - - - // Custom attribute support - // tangents, binormals, blendweights etc always via this route - // builtins may be done this way too - if (isCustomAttrib) - { - GLint attrib = GLSLProgramCommon::getFixedAttributeIndex(sem, elem.getIndex()); - unsigned short typeCount = VertexElement::getTypeCount(elem.getType()); - GLboolean normalised = GL_FALSE; - switch(elem.getType()) - { - case VET_UBYTE4_NORM: - case VET_SHORT2_NORM: - case VET_USHORT2_NORM: - case VET_SHORT4_NORM: - case VET_USHORT4_NORM: - normalised = GL_TRUE; - break; - default: - break; - }; - - glVertexAttribPointerARB( - attrib, - typeCount, - GLHardwareBufferManager::getGLType(elem.getType()), - normalised, - static_cast(vertexBuffer->getVertexSize()), - pBufferData); - glEnableVertexAttribArrayARB(attrib); - - mRenderAttribsBound.push_back(attrib); - } - else - { - // fixed-function & builtin attribute support - switch(sem) - { - case VES_POSITION: - glVertexPointer(VertexElement::getTypeCount( - elem.getType()), - GLHardwareBufferManager::getGLType(elem.getType()), - static_cast(vertexBuffer->getVertexSize()), - pBufferData); - glEnableClientState( GL_VERTEX_ARRAY ); - break; - case VES_NORMAL: - glNormalPointer( - GLHardwareBufferManager::getGLType(elem.getType()), - static_cast(vertexBuffer->getVertexSize()), - pBufferData); - glEnableClientState( GL_NORMAL_ARRAY ); - break; - case VES_DIFFUSE: - glColorPointer(4, - GLHardwareBufferManager::getGLType(elem.getType()), - static_cast(vertexBuffer->getVertexSize()), - pBufferData); - glEnableClientState( GL_COLOR_ARRAY ); - break; - case VES_SPECULAR: - if (GLAD_GL_EXT_secondary_color) - { - glSecondaryColorPointerEXT(4, - GLHardwareBufferManager::getGLType(elem.getType()), - static_cast(vertexBuffer->getVertexSize()), - pBufferData); - glEnableClientState( GL_SECONDARY_COLOR_ARRAY ); - } - break; - case VES_TEXTURE_COORDINATES: - - if (mCurrentVertexProgram) - { - // Programmable pipeline - direct UV assignment - glClientActiveTextureARB(GL_TEXTURE0 + elem.getIndex()); - glTexCoordPointer( - VertexElement::getTypeCount(elem.getType()), - GLHardwareBufferManager::getGLType(elem.getType()), - static_cast(vertexBuffer->getVertexSize()), - pBufferData); - glEnableClientState( GL_TEXTURE_COORD_ARRAY ); - if (elem.getIndex() > mMaxBuiltInTextureAttribIndex) - mMaxBuiltInTextureAttribIndex = elem.getIndex(); - } - else - { - // fixed function matching to units based on tex_coord_set - for (unsigned int i = 0; i < mDisabledTexUnitsFrom; i++) - { - // Only set this texture unit's texcoord pointer if it - // is supposed to be using this element's index - if (mTextureCoordIndex[i] == elem.getIndex() && i < mFixedFunctionTextureUnits) - { - if (multitexturing) - glClientActiveTextureARB(GL_TEXTURE0 + i); - glTexCoordPointer( - VertexElement::getTypeCount(elem.getType()), - GLHardwareBufferManager::getGLType(elem.getType()), - static_cast(vertexBuffer->getVertexSize()), - pBufferData); - glEnableClientState( GL_TEXTURE_COORD_ARRAY ); - } - } - } - break; - default: - break; - }; - } // isCustomAttrib - } - - //--------------------------------------------------------------------- -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - bool GLRenderSystem::setDrawBuffer(ColourBufferType colourBuffer) - { - bool result = true; - - switch (colourBuffer) - { - case CBT_BACK: - glDrawBuffer(GL_BACK); - break; - case CBT_BACK_LEFT: - glDrawBuffer(GL_BACK_LEFT); - break; - case CBT_BACK_RIGHT: - glDrawBuffer(GL_BACK_RIGHT); - break; - default: - result = false; - } - - // Check for any errors - GLenum error = glGetError(); - if (result && GL_NO_ERROR != error) - { - const char* errorCode = glErrorToString(error); - String errorString = "GLRenderSystem::setDrawBuffer(" - + Ogre::StringConverter::toString(colourBuffer) + "): " + errorCode; - - Ogre::LogManager::getSingleton().logMessage(errorString); - result = false; - } - - return result; - } -#endif - - void GLRenderSystem::_copyContentsToMemory(Viewport* vp, const Box& src, const PixelBox &dst, RenderWindow::FrameBuffer buffer) - { - GLenum format = GLPixelUtil::getGLOriginFormat(dst.format); - GLenum type = GLPixelUtil::getGLOriginDataType(dst.format); - - if ((format == GL_NONE) || (type == 0)) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Unsupported format.", "GLRenderSystem::copyContentsToMemory" ); - } - - // Switch context if different from current one - _setViewport(vp); - - if(dst.getWidth() != dst.rowPitch) - glPixelStorei(GL_PACK_ROW_LENGTH, dst.rowPitch); - // Must change the packing to ensure no overruns! - glPixelStorei(GL_PACK_ALIGNMENT, 1); - - glReadBuffer((buffer == RenderWindow::FB_FRONT)? GL_FRONT : GL_BACK); - - uint32_t height = vp->getTarget()->getHeight(); - - glReadPixels((GLint)src.left, (GLint)(height - src.bottom), - (GLsizei)dst.getWidth(), (GLsizei)dst.getHeight(), - format, type, dst.getTopLeftFrontPixelPtr()); - - // restore default alignment - glPixelStorei(GL_PACK_ALIGNMENT, 4); - glPixelStorei(GL_PACK_ROW_LENGTH, 0); - - PixelUtil::bulkPixelVerticalFlip(dst); - } - //--------------------------------------------------------------------- - void GLRenderSystem::initialiseExtensions(void) - { - // Set version string - const GLubyte* pcVer = glGetString(GL_VERSION); - assert(pcVer && "Problems getting GL version string using glGetString"); - - String tmpStr = (const char*)pcVer; - mDriverVersion.fromString(tmpStr.substr(0, tmpStr.find(' '))); - LogManager::getSingleton().logMessage("GL_VERSION = " + mDriverVersion.toString()); - - // Get vendor - const GLubyte* pcVendor = glGetString(GL_VENDOR); - tmpStr = (const char*)pcVendor; - LogManager::getSingleton().logMessage("GL_VENDOR = " + tmpStr); - mVendor = RenderSystemCapabilities::vendorFromString(tmpStr.substr(0, tmpStr.find(' '))); - - // Get renderer - const GLubyte* pcRenderer = glGetString(GL_RENDERER); - tmpStr = (const char*)pcRenderer; - LogManager::getSingleton().logMessage("GL_RENDERER = " + tmpStr); - - // Set extension list - StringStream ext; - String str; - - const GLubyte* pcExt = glGetString(GL_EXTENSIONS); - assert(pcExt && "Problems getting GL extension string using glGetString"); - LogManager::getSingleton().logMessage("GL_EXTENSIONS = " + String((const char*)pcExt)); - - ext << pcExt; - - while(ext >> str) - { - mExtensionList.insert(str); - } - } -} diff --git a/RenderSystems/GL/src/OgreGLRenderToVertexBuffer.cpp b/RenderSystems/GL/src/OgreGLRenderToVertexBuffer.cpp deleted file mode 100644 index 217b77cf9f3..00000000000 --- a/RenderSystems/GL/src/OgreGLRenderToVertexBuffer.cpp +++ /dev/null @@ -1,269 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLRenderToVertexBuffer.h" -#include "OgreHardwareBufferManager.h" -#include "OgreGLHardwareBuffer.h" -#include "OgreRenderable.h" -#include "OgreRoot.h" -#include "OgreGLRenderSystem.h" -#include "OgreGLSLLinkProgramManager.h" -#include "OgreLogManager.h" - -namespace Ogre { -//----------------------------------------------------------------------------- - static GLint getR2VBPrimitiveType(RenderOperation::OperationType operationType) - { - switch (operationType) - { - case RenderOperation::OT_POINT_LIST: - return GL_POINTS; - case RenderOperation::OT_LINE_LIST: - return GL_LINES; - case RenderOperation::OT_TRIANGLE_LIST: - return GL_TRIANGLES; - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "GL RenderToVertexBuffer" - "can only output point lists, line lists, or triangle lists", - "OgreGLRenderToVertexBuffer::getR2VBPrimitiveType"); - } - } -//----------------------------------------------------------------------------- - static void checkGLError(bool logError, bool throwException, - const Ogre::String& sectionName = BLANKSTRING) - { - String msg; - bool foundError = false; - - // get all the GL errors - GLenum glErr = glGetError(); - while (glErr != GL_NO_ERROR) - { - msg += glErrorToString(glErr); - glErr = glGetError(); - foundError = true; - } - - if (foundError && (logError || throwException)) - { - String fullErrorMessage = "GL Error : " + msg + " in " + sectionName; - if (logError) - { - LogManager::getSingleton().getDefaultLog()->logMessage(fullErrorMessage, LML_CRITICAL); - } - if (throwException) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - fullErrorMessage, "OgreGLRenderToVertexBuffer"); - } - } - } -//----------------------------------------------------------------------------- - GLRenderToVertexBuffer::GLRenderToVertexBuffer() - { - mVertexBuffers[0].reset(); - mVertexBuffers[1].reset(); - - // create query objects - glGenQueries(1, &mPrimitivesDrawnQuery); - } -//----------------------------------------------------------------------------- - GLRenderToVertexBuffer::~GLRenderToVertexBuffer() - { - glDeleteQueries(1, &mPrimitivesDrawnQuery); - } -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- - void GLRenderToVertexBuffer::update(SceneManager* sceneMgr) - { - checkGLError(true, false, "start of GLRenderToVertexBuffer::update"); - - size_t bufSize = mVertexData->vertexDeclaration->getVertexSize(0) * mMaxVertexCount; - if (!mVertexBuffers[0] || mVertexBuffers[0]->getSizeInBytes() != bufSize) - { - //Buffers don't match. Need to reallocate. - mResetRequested = true; - } - - Ogre::Pass* r2vbPass = derivePass(sceneMgr); - - checkGLError(true, false); - - bindVerticesOutput(r2vbPass); - - RenderOperation renderOp; - auto targetBufferIndex = mTargetBufferIndex; - if (mResetRequested || mResetsEveryUpdate) - { - //Use source data to render to first buffer - mSourceRenderable->getRenderOperation(renderOp); - } - else - { - //Use current front buffer to render to back buffer - this->getRenderOperation(renderOp); - } - - if (!mVertexBuffers[targetBufferIndex] || - mVertexBuffers[targetBufferIndex]->getSizeInBytes() != bufSize) - { - reallocateBuffer(targetBufferIndex); - } - - GLHardwareBuffer* vertexBuffer = mVertexBuffers[targetBufferIndex]->_getImpl(); - GLuint bufferId = vertexBuffer->getGLBufferId(); - - //Bind the target buffer - glBindBufferOffsetNV(GL_TRANSFORM_FEEDBACK_BUFFER_NV, 0, bufferId, 0); - - glBeginTransformFeedbackNV(getR2VBPrimitiveType(mOperationType)); - - glEnable(GL_RASTERIZER_DISCARD_NV); // disable rasterization - - glBeginQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_NV, mPrimitivesDrawnQuery); - - GLRenderSystem* targetRenderSystem = static_cast(Root::getSingleton().getRenderSystem()); - //Draw the object - targetRenderSystem->setWorldMatrix(Matrix4::IDENTITY); - targetRenderSystem->setViewMatrix(Matrix4::IDENTITY); - targetRenderSystem->setProjectionMatrix(Matrix4::IDENTITY); - targetRenderSystem->_render(renderOp); - - //Finish the query - glEndQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_NV); - glDisable(GL_RASTERIZER_DISCARD_NV); - glEndTransformFeedbackNV(); - - //read back query results - GLuint primitivesWritten; - glGetQueryObjectuiv(mPrimitivesDrawnQuery, GL_QUERY_RESULT, &primitivesWritten); - mVertexData->vertexCount = primitivesWritten * getVertexCountPerPrimitive(mOperationType); - - checkGLError(true, true, "GLRenderToVertexBuffer::update"); - - //Switch the vertex binding - mVertexData->vertexBufferBinding->unsetAllBindings(); - mVertexData->vertexBufferBinding->setBinding(0, mVertexBuffers[targetBufferIndex]); - mTargetBufferIndex = mTargetBufferIndex == 0 ? 1 : 0; - - glDisable(GL_RASTERIZER_DISCARD_NV); // enable rasterization - - //Clear the reset flag - mResetRequested = false; - } -//----------------------------------------------------------------------------- - GLint GLRenderToVertexBuffer::getGLSemanticType(VertexElementSemantic semantic) - { - switch (semantic) - { - case VES_POSITION: - return GL_POSITION; - case VES_TEXTURE_COORDINATES: - return GL_TEXTURE_COORD_NV; - case VES_DIFFUSE: - return GL_PRIMARY_COLOR; - case VES_SPECULAR: - return GL_SECONDARY_COLOR_NV; - //TODO : Implement more? - default: - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Unsupported vertex element semantic in render to vertex buffer", - "OgreGLRenderToVertexBuffer::getGLSemanticType"); - - } - } -//----------------------------------------------------------------------------- - void GLRenderToVertexBuffer::bindVerticesOutput(Pass* pass) - { - VertexDeclaration* declaration = mVertexData->vertexDeclaration; - bool useVaryingAttributes = false; - - //Check if we are FixedFunc/ASM shaders (Static attributes) or GLSL (Varying attributes) - //We assume that there isn't a mix of GLSL and ASM as this is illegal - GpuProgram* sampleProgram = 0; - if (pass->hasVertexProgram()) - { - sampleProgram = pass->getVertexProgram().get(); - } - else if (pass->hasGeometryProgram()) - { - sampleProgram = pass->getGeometryProgram().get(); - } - if (sampleProgram && (sampleProgram->_getBindingDelegate()->getLanguage() == "glsl")) - { - useVaryingAttributes = true; - } - - if (useVaryingAttributes) - { - //Have GLSL shaders, using varying attributes - GLSL::GLSLLinkProgram* linkProgram = GLSL::GLSLLinkProgramManager::getSingleton().getActiveLinkProgram(); - uint linkProgramId = linkProgram->getGLHandle(); - - std::vector locations; - for (unsigned short e=0; e < declaration->getElementCount(); e++) - { - const VertexElement* element =declaration->getElement(e); - String varyingName = getSemanticVaryingName(element->getSemantic(), element->getIndex()); - GLint location = glGetVaryingLocationNV(linkProgramId, varyingName.c_str()); - if (location < 0) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "GLSL link program does not output " + varyingName + - " so it cannot fill the requested vertex buffer", - "OgreGLRenderToVertexBuffer::bindVerticesOutput"); - } - locations.push_back(location); - } - glTransformFeedbackVaryingsNV( - linkProgramId, static_cast(locations.size()), - &locations[0], GL_INTERLEAVED_ATTRIBS_NV); - } - else - { - //Either fixed function or assembly (CG = assembly) shaders - std::vector attribs; - for (unsigned short e=0; e < declaration->getElementCount(); e++) - { - const VertexElement* element = declaration->getElement(e); - //Type - attribs.push_back(getGLSemanticType(element->getSemantic())); - //Number of components - attribs.push_back(VertexElement::getTypeCount(element->getType())); - //Index - attribs.push_back(element->getIndex()); - } - - glTransformFeedbackAttribsNV( - static_cast(declaration->getElementCount()), - &attribs[0], GL_INTERLEAVED_ATTRIBS_NV); - } - - checkGLError(true, true, "GLRenderToVertexBuffer::bindVerticesOutput"); - } -} diff --git a/RenderSystems/GL/src/OgreGLStateCacheManager.cpp b/RenderSystems/GL/src/OgreGLStateCacheManager.cpp deleted file mode 100644 index 747a03d1eba..00000000000 --- a/RenderSystems/GL/src/OgreGLStateCacheManager.cpp +++ /dev/null @@ -1,650 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ - -#include "OgreGLStateCacheManager.h" -#include "OgreGLRenderSystem.h" -#include "OgreRoot.h" - -namespace Ogre { - - GLStateCacheManager::GLStateCacheManager(void) - { - clearCache(); - } - - void GLStateCacheManager::initializeCache() - { - glBlendEquation(GL_FUNC_ADD); - - if(GLAD_GL_VERSION_2_0) - { - glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD); - } - else if(GLAD_GL_EXT_blend_equation_separate) - { - glBlendEquationSeparateEXT(GL_FUNC_ADD, GL_FUNC_ADD); - } - - glBlendFunc(GL_ONE, GL_ZERO); - - glCullFace(mCullFace); - - glDepthFunc(mDepthFunc); - - glDepthMask(mDepthMask); - - glStencilMask(mStencilMask); - - glClearDepth(mClearDepth); - - glBindTexture(GL_TEXTURE_2D, 0); - - glBindBuffer(GL_ARRAY_BUFFER, 0); - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - - glBindFramebufferEXT(GL_FRAMEBUFFER, 0); - - glBindRenderbufferEXT(GL_RENDERBUFFER, 0); - - glActiveTexture(GL_TEXTURE0); - - glClearColor(mClearColour[0], mClearColour[1], mClearColour[2], mClearColour[3]); - - glColorMask(mColourMask[0], mColourMask[1], mColourMask[2], mColourMask[3]); - - glPolygonMode(GL_FRONT_AND_BACK, mPolygonMode); - } - - void GLStateCacheManager::clearCache() - { - mDepthMask = GL_TRUE; - mBlendEquationRGB = GL_FUNC_ADD; - mBlendEquationAlpha = GL_FUNC_ADD; - mCullFace = GL_BACK; - mDepthFunc = GL_LESS; - mStencilMask = 0xFFFFFFFF; - mActiveTextureUnit = 0; - mClearDepth = 1.0f; - mLastBoundTexID = 0; - mShininess = 0.0f; - mPolygonMode = GL_FILL; - mShadeModel = GL_SMOOTH; - - // Initialize our cache variables and also the GL so that the - // stored values match the GL state - mBlendFuncSource = GL_ONE; - mBlendFuncDest = GL_ZERO; - mBlendFuncSourceAlpha = GL_ONE; - mBlendFuncDestAlpha = GL_ZERO; - - mClearColour[0] = mClearColour[1] = mClearColour[2] = mClearColour[3] = 0.0f; - mColourMask[0] = mColourMask[1] = mColourMask[2] = mColourMask[3] = GL_TRUE; - -#ifdef OGRE_ENABLE_STATE_CACHE - mEnableVector.reserve(25); - mEnableVector.clear(); -#endif - mActiveBufferMap.clear(); - mTexUnitsMap.clear(); - mTextureCoordGen.clear(); - - mAmbient[0] = 0.2f; - mAmbient[1] = 0.2f; - mAmbient[2] = 0.2f; - mAmbient[3] = 1.0f; - - mDiffuse[0] = 0.8f; - mDiffuse[1] = 0.8f; - mDiffuse[2] = 0.8f; - mDiffuse[3] = 1.0f; - - mSpecular[0] = 0.0f; - mSpecular[1] = 0.0f; - mSpecular[2] = 0.0f; - mSpecular[3] = 1.0f; - - mEmissive[0] = 0.0f; - mEmissive[1] = 0.0f; - mEmissive[2] = 0.0f; - mEmissive[3] = 1.0f; - - mLightAmbient[0] = 0.2f; - mLightAmbient[1] = 0.2f; - mLightAmbient[2] = 0.2f; - mLightAmbient[3] = 1.0f; - - mPointSize = 1.0f; - mPointSizeMin = 1.0f; - mPointSizeMax = 1.0f; - mPointAttenuation[0] = 1.0f; - mPointAttenuation[1] = 0.0f; - mPointAttenuation[2] = 0.0f; - } - - void GLStateCacheManager::bindGLBuffer(GLenum target, GLuint buffer) - { -#ifdef OGRE_ENABLE_STATE_CACHE - auto ret = mActiveBufferMap.emplace(target, buffer); - if(ret.first->second != buffer) // Update the cached value if needed - { - ret.first->second = buffer; - ret.second = true; - } - - // Update GL - if(ret.second) -#endif - { - if(target == GL_FRAMEBUFFER) - { - OgreAssert(false, "not implemented"); - } - else if(target == GL_RENDERBUFFER) - { - glBindRenderbufferEXT(target, buffer); - } - else - { - glBindBuffer(target, buffer); - } - } - - } - - void GLStateCacheManager::deleteGLBuffer(GLenum target, GLuint buffer) - { - // Buffer name 0 is reserved and we should never try to delete it - if(buffer == 0) - return; - - if(target == GL_FRAMEBUFFER) - { - glDeleteFramebuffers(1, &buffer); - } - else if(target == GL_RENDERBUFFER) - { - glDeleteRenderbuffers(1, &buffer); - } - else - { - glDeleteBuffers(1, &buffer); - } - -#ifdef OGRE_ENABLE_STATE_CACHE - BindBufferMap::iterator i = mActiveBufferMap.find(target); - - if (i != mActiveBufferMap.end() && ((*i).second == buffer)) - { - // Currently bound buffer is being deleted, update the cached value to 0, - // which it likely the buffer that will be bound by the driver. - // An update will be forced next time we try to bind on this target. - (*i).second = 0; - } -#endif - } - - void GLStateCacheManager::invalidateStateForTexture(GLuint texture) - { -#ifdef OGRE_ENABLE_STATE_CACHE - mTexUnitsMap.erase(texture); -#endif - } - - // TODO: Store as high/low bits of a GLuint, use vector instead of map for TexParameteriMap - void GLStateCacheManager::setTexParameteri(GLenum target, GLenum pname, GLint param) - { -#ifdef OGRE_ENABLE_STATE_CACHE - // Check if we have a map entry for this texture id. If not, create a blank one and insert it. - TexUnitsMap::iterator it = mTexUnitsMap.find(mLastBoundTexID); - if (it == mTexUnitsMap.end()) - { - TexParameteriMap unit; - mTexUnitsMap[mLastBoundTexID] = unit; - - // Update the iterator - it = mTexUnitsMap.find(mLastBoundTexID); - } - - // Get a local copy of the parameter map and search for this parameter - TexParameteriMap &myMap = (*it).second; - - auto ret = myMap.emplace(pname, param); - TexParameteriMap::iterator i = ret.first; - - // Update the cached value if needed - if((*i).second != param || ret.second) - { - (*i).second = param; - - // Update GL - glTexParameteri(target, pname, param); - } -#else - glTexParameteri(target, pname, param); -#endif - } - - void GLStateCacheManager::bindGLTexture(GLenum target, GLuint texture) - { - mLastBoundTexID = texture; - - // Update GL - glBindTexture(target, texture); - } - - bool GLStateCacheManager::activateGLTextureUnit(size_t unit) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if (mActiveTextureUnit == unit) - return true; -#endif - - glActiveTexture(GL_TEXTURE0 + unit); - mActiveTextureUnit = unit; - return true; - } - - void GLStateCacheManager::setBlendFunc(GLenum source, GLenum dest, GLenum sourceA, GLenum destA) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mBlendFuncSource != source || mBlendFuncDest != dest || sourceA != mBlendFuncSourceAlpha || destA != mBlendFuncDestAlpha ) -#endif - { - mBlendFuncSource = source; - mBlendFuncDest = dest; - mBlendFuncSourceAlpha = sourceA; - mBlendFuncDestAlpha = destA; - - glBlendFuncSeparate(source, dest, sourceA, destA); - } - } - - void GLStateCacheManager::setDepthMask(GLboolean mask) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mDepthMask != mask) -#endif - { - mDepthMask = mask; - - glDepthMask(mask); - } - } - - void GLStateCacheManager::setDepthFunc(GLenum func) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mDepthFunc != func) -#endif - { - mDepthFunc = func; - - glDepthFunc(func); - } - } - - void GLStateCacheManager::setClearDepth(GLclampf depth) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mClearDepth != depth) -#endif - { - mClearDepth = depth; - - glClearDepth(depth); - } - } - - void GLStateCacheManager::setClearColour(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if((mClearColour[0] != red) || - (mClearColour[1] != green) || - (mClearColour[2] != blue) || - (mClearColour[3] != alpha)) -#endif - { - mClearColour[0] = red; - mClearColour[1] = green; - mClearColour[2] = blue; - mClearColour[3] = alpha; - - glClearColor(mClearColour[0], mClearColour[1], mClearColour[2], mClearColour[3]); - } - } - - void GLStateCacheManager::setColourMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if((mColourMask[0] != red) || - (mColourMask[1] != green) || - (mColourMask[2] != blue) || - (mColourMask[3] != alpha)) -#endif - { - mColourMask[0] = red; - mColourMask[1] = green; - mColourMask[2] = blue; - mColourMask[3] = alpha; - - glColorMask(mColourMask[0], mColourMask[1], mColourMask[2], mColourMask[3]); - } - } - - void GLStateCacheManager::setStencilMask(GLuint mask) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mStencilMask != mask) -#endif - { - mStencilMask = mask; - - glStencilMask(mask); - } - } - - void GLStateCacheManager::setEnabled(GLenum flag, bool enabled) - { -#ifdef OGRE_ENABLE_STATE_CACHE - auto iter = std::find(mEnableVector.begin(), mEnableVector.end(), flag); - bool was_enabled = iter != mEnableVector.end(); - - if(was_enabled == enabled) - return; // no change - - if(!enabled) - { - mEnableVector.erase(iter); - } - else - { - mEnableVector.push_back(flag); - } -#endif - if(!enabled) - { - glDisable(flag); - } - else - { - glEnable(flag); - } - } - - void GLStateCacheManager::setViewport(const Rect& r) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mViewport != r) -#endif - { - mViewport = r; - glViewport(r.left, r.top, r.width(), r.height()); - } - } - - void GLStateCacheManager::setCullFace(GLenum face) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mCullFace != face) -#endif - { - mCullFace = face; - - glCullFace(face); - } - } - - void GLStateCacheManager::setBlendEquation(GLenum eqRGB, GLenum eqAlpha) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mBlendEquationRGB != eqRGB || mBlendEquationAlpha != eqAlpha) -#endif - { - mBlendEquationRGB = eqRGB; - mBlendEquationAlpha = eqAlpha; - - if(GLAD_GL_VERSION_2_0) - { - glBlendEquationSeparate(eqRGB, eqAlpha); - } - else if(GLAD_GL_EXT_blend_equation_separate) - { - glBlendEquationSeparateEXT(eqRGB, eqAlpha); - } - else - { - glBlendEquation(eqRGB); - } - } - } - - void GLStateCacheManager::setMaterialDiffuse(GLfloat r, GLfloat g, GLfloat b, GLfloat a) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if((mDiffuse[0] != r) || - (mDiffuse[1] != g) || - (mDiffuse[2] != b) || - (mDiffuse[3] != a)) -#endif - { - mDiffuse[0] = r; - mDiffuse[1] = g; - mDiffuse[2] = b; - mDiffuse[3] = a; - - glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, &mDiffuse[0]); - } - } - - void GLStateCacheManager::setMaterialAmbient(GLfloat r, GLfloat g, GLfloat b, GLfloat a) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if((mAmbient[0] != r) || - (mAmbient[1] != g) || - (mAmbient[2] != b) || - (mAmbient[3] != a)) -#endif - { - mAmbient[0] = r; - mAmbient[1] = g; - mAmbient[2] = b; - mAmbient[3] = a; - - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, &mAmbient[0]); - } - } - - void GLStateCacheManager::setMaterialEmissive(GLfloat r, GLfloat g, GLfloat b, GLfloat a) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if((mEmissive[0] != r) || - (mEmissive[1] != g) || - (mEmissive[2] != b) || - (mEmissive[3] != a)) -#endif - { - mEmissive[0] = r; - mEmissive[1] = g; - mEmissive[2] = b; - mEmissive[3] = a; - - glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, &mEmissive[0]); - } - } - - void GLStateCacheManager::setMaterialSpecular(GLfloat r, GLfloat g, GLfloat b, GLfloat a) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if((mSpecular[0] != r) || - (mSpecular[1] != g) || - (mSpecular[2] != b) || - (mSpecular[3] != a)) -#endif - { - mSpecular[0] = r; - mSpecular[1] = g; - mSpecular[2] = b; - mSpecular[3] = a; - - glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, &mSpecular[0]); - } - } - - void GLStateCacheManager::setMaterialShininess(GLfloat shininess) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if (mShininess != shininess) -#endif - { - mShininess = shininess; - glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, mShininess); - } - } - - void GLStateCacheManager::setPolygonMode(GLenum mode) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if (mPolygonMode != mode) -#endif - { - mPolygonMode = mode; - glPolygonMode(GL_FRONT_AND_BACK, mPolygonMode); - } - } - - void GLStateCacheManager::setShadeModel(GLenum model) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if (mShadeModel != model) -#endif - { - mShadeModel = model; - glShadeModel(model); - } - } - - void GLStateCacheManager::setLightAmbient(GLfloat r, GLfloat g, GLfloat b) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if((mLightAmbient[0] != r) || - (mLightAmbient[1] != g) || - (mLightAmbient[2] != b)) -#endif - { - mLightAmbient[0] = r; - mLightAmbient[1] = g; - mLightAmbient[2] = b; - - glLightModelfv(GL_LIGHT_MODEL_AMBIENT, &mLightAmbient[0]); - } - } - - void GLStateCacheManager::setPointSize(GLfloat size) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if (mPointSize != size) -#endif - { - mPointSize = size; - glPointSize(mPointSize); - } - } - - void GLStateCacheManager::setPointParameters(const GLfloat *attenuation, float minSize, float maxSize) - { - if(minSize > -1) -#ifdef OGRE_ENABLE_STATE_CACHE - if (minSize != mPointSizeMin) -#endif - { - mPointSizeMin = minSize; - glPointParameterf(GL_POINT_SIZE_MIN, mPointSizeMin); - } - - if(maxSize > -1) -#ifdef OGRE_ENABLE_STATE_CACHE - if (maxSize != mPointSizeMax) -#endif - { - mPointSizeMax = maxSize; - glPointParameterf(GL_POINT_SIZE_MAX, mPointSizeMax); - } - - if(attenuation) -#ifdef OGRE_ENABLE_STATE_CACHE - if (attenuation[0] != mPointAttenuation[0] || attenuation[1] != mPointAttenuation[1] || attenuation[2] != mPointAttenuation[2]) -#endif - { - mPointAttenuation[0] = attenuation[0]; - mPointAttenuation[1] = attenuation[1]; - mPointAttenuation[2] = attenuation[2]; - glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, &mPointAttenuation[0]); - } - } - - void GLStateCacheManager::enableTextureCoordGen(GLenum type) - { -#ifdef OGRE_ENABLE_STATE_CACHE - std::unordered_map::iterator it = mTextureCoordGen.find(mActiveTextureUnit); - if (it == mTextureCoordGen.end()) - { - glEnable(type); - mTextureCoordGen[mActiveTextureUnit].mEnabled.insert(type); - } - else - { - if (it->second.mEnabled.find(type) == it->second.mEnabled.end()) - { - glEnable(type); - it->second.mEnabled.insert(type); - } - } -#else - glEnable(type); -#endif - } - - void GLStateCacheManager::disableTextureCoordGen(GLenum type) - { -#ifdef OGRE_ENABLE_STATE_CACHE - std::unordered_map::iterator it = mTextureCoordGen.find(mActiveTextureUnit); - if (it != mTextureCoordGen.end()) - { - std::set::iterator found = it->second.mEnabled.find(type); - if (found != it->second.mEnabled.end()) - { - glDisable(type); - it->second.mEnabled.erase(found); - } - } -#else - glDisable(type); -#endif - } -} diff --git a/RenderSystems/GL/src/OgreGLTexture.cpp b/RenderSystems/GL/src/OgreGLTexture.cpp deleted file mode 100644 index ae1e1f826e5..00000000000 --- a/RenderSystems/GL/src/OgreGLTexture.cpp +++ /dev/null @@ -1,273 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLTexture.h" -#include "OgreGLRenderSystem.h" -#include "OgreGLPixelFormat.h" -#include "OgreGLHardwarePixelBuffer.h" - -#include "OgreTextureManager.h" -#include "OgreImage.h" -#include "OgreLogManager.h" -#include "OgreCamera.h" -#include "OgreException.h" -#include "OgreRoot.h" -#include "OgreCodec.h" -#include "OgreImageCodec.h" -#include "OgreStringConverter.h" -#include "OgreBitwise.h" - -#include "OgreGLFBORenderTexture.h" -#include "OgreGLStateCacheManager.h" - -namespace Ogre { - - - - GLTexture::GLTexture(ResourceManager* creator, const String& name, - ResourceHandle handle, const String& group, bool isManual, - ManualResourceLoader* loader, GLRenderSystem* renderSystem) - : GLTextureCommon(creator, name, handle, group, isManual, loader), - mRenderSystem(renderSystem) - { - } - - - GLTexture::~GLTexture() - { - unload(); - } - - GLenum GLTexture::getGLTextureTarget(void) const - { - switch(mTextureType) - { - case TEX_TYPE_1D: - return GL_TEXTURE_1D; - case TEX_TYPE_2D: - return GL_TEXTURE_2D; - case TEX_TYPE_3D: - return GL_TEXTURE_3D; - case TEX_TYPE_CUBE_MAP: - return GL_TEXTURE_CUBE_MAP; - case TEX_TYPE_2D_ARRAY: - return GL_TEXTURE_2D_ARRAY_EXT; - default: - return 0; - }; - } - - //* Creation / loading methods ******************************************** - void GLTexture::createInternalResourcesImpl(void) - { - OgreAssert(mTextureType != TEX_TYPE_EXTERNAL_OES, - "TEX_TYPE_EXTERNAL_OES is not available for openGL"); - - // Convert to nearest power-of-two size if required - mWidth = GLPixelUtil::optionalPO2(mWidth); - mHeight = GLPixelUtil::optionalPO2(mHeight); - mDepth = GLPixelUtil::optionalPO2(mDepth); - - - // Adjust format if required - mFormat = TextureManager::getSingleton().getNativeFormat(mTextureType, mFormat, mUsage); - - // Check if we can do HW mipmap generation - mMipmapsHardwareGenerated = true; - - // Generate texture name - glGenTextures( 1, &mTextureID ); - - // Set texture type - mRenderSystem->_getStateCacheManager()->bindGLTexture( getGLTextureTarget(), mTextureID ); - - // This needs to be set otherwise the texture doesn't get rendered - mRenderSystem->_getStateCacheManager()->setTexParameteri(getGLTextureTarget(), GL_TEXTURE_MAX_LEVEL, - mNumMipmaps); - - if ((mUsage & TU_AUTOMIPMAP) && mNumMipmaps) - { - mRenderSystem->_getStateCacheManager()->setTexParameteri( getGLTextureTarget(), GL_GENERATE_MIPMAP, GL_TRUE ); - } - - // Allocate internal buffer so that glTexSubImageXD can be used - // Internal format - GLenum internalformat = GLPixelUtil::getGLInternalFormat(mFormat, mHwGamma); - uint32 width = mWidth; - uint32 height = mHeight; - uint32 depth = mDepth; - - GLenum format = GLPixelUtil::getGLOriginFormat(mFormat); - GLenum datatype = GLPixelUtil::getGLOriginDataType(mFormat); - - if(PixelUtil::isCompressed(mFormat)) - { - // Compressed formats - GLsizei size = static_cast(PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat)); - // Provide temporary buffer filled with zeroes as glCompressedTexImageXD does not - // accept a 0 pointer like normal glTexImageXD - // Run through this process for every mipmap to pregenerate mipmap piramid - std::vector tmpdata(size); - - for(uint32 mip=0; mip<=mNumMipmaps; mip++) - { - size = static_cast(PixelUtil::getMemorySize(width, height, depth, mFormat)); - switch(mTextureType) - { - case TEX_TYPE_1D: - glCompressedTexImage1DARB(GL_TEXTURE_1D, mip, internalformat, - width, 0, - size, &tmpdata[0]); - break; - case TEX_TYPE_2D: - glCompressedTexImage2DARB(GL_TEXTURE_2D, mip, internalformat, - width, height, 0, - size, &tmpdata[0]); - break; - case TEX_TYPE_2D_ARRAY: - case TEX_TYPE_3D: - glCompressedTexImage3DARB(getGLTextureTarget(), mip, internalformat, - width, height, depth, 0, - size, &tmpdata[0]); - break; - case TEX_TYPE_CUBE_MAP: - for(int face=0; face<6; face++) { - glCompressedTexImage2DARB(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, internalformat, - width, height, 0, - size, &tmpdata[0]); - } - break; - case TEX_TYPE_EXTERNAL_OES: - OGRE_EXCEPT( - Exception::ERR_RENDERINGAPI_ERROR, - "Attempt to create mipmaps for unsupported TEX_TYPE_EXTERNAL_OES, should never happen", - "GLTexture::createInternalResourcesImpl" - ); - break; - }; - if(width>1) - width = width/2; - if(height>1) - height = height/2; - if(depth>1 && mTextureType != TEX_TYPE_2D_ARRAY) - depth = depth/2; - } - } - else - { - // Run through this process to pregenerate mipmap pyramid - for(uint32 mip=0; mip<=mNumMipmaps; mip++) - { - // Normal formats - switch(mTextureType) - { - case TEX_TYPE_1D: - glTexImage1D(GL_TEXTURE_1D, mip, internalformat, - width, 0, - format, datatype, 0); - - break; - case TEX_TYPE_2D: - glTexImage2D(GL_TEXTURE_2D, mip, internalformat, - width, height, 0, - format, datatype, 0); - break; - case TEX_TYPE_2D_ARRAY: - case TEX_TYPE_3D: - glTexImage3D(getGLTextureTarget(), mip, internalformat, - width, height, depth, 0, - format, datatype, 0); - break; - case TEX_TYPE_CUBE_MAP: - for(int face=0; face<6; face++) { - glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, internalformat, - width, height, 0, - format, datatype, 0); - } - break; - case TEX_TYPE_EXTERNAL_OES: - OGRE_EXCEPT( - Exception::ERR_RENDERINGAPI_ERROR, - "Attempt to create mipmaps for unsupported TEX_TYPE_EXTERNAL_OES, should never happen", - "GLTexture::createInternalResourcesImpl" - ); - break; - }; - if(width>1) - width = width/2; - if(height>1) - height = height/2; - if(depth>1 && mTextureType != TEX_TYPE_2D_ARRAY) - depth = depth/2; - } - } - _createSurfaceList(); - // Get final internal format - mFormat = getBuffer(0,0)->getFormat(); - } - - //************************************************************************* - - void GLTexture::freeInternalResourcesImpl() - { - if (GLStateCacheManager* stateCacheManager = mRenderSystem->_getStateCacheManager()) - { - glDeleteTextures(1, &mTextureID); - stateCacheManager->invalidateStateForTexture(mTextureID); - } - } - - //--------------------------------------------------------------------------------------------- - void GLTexture::_createSurfaceList() - { - mSurfaceList.clear(); - - uint32 depth = mDepth; - - // For all faces and mipmaps, store surfaces as HardwarePixelBufferSharedPtr - for(GLint face=0; face(getNumFaces()); face++) - { - uint32 width = mWidth; - uint32 height = mHeight; - - for(uint32 mip=0; mip<=getNumMipmaps(); mip++) - { - auto buf = std::make_shared(mRenderSystem, this, face, mip, width, height, depth); - mSurfaceList.push_back(buf); - - if (width > 1) - width = width / 2; - if (height > 1) - height = height / 2; - if (depth > 1 && mTextureType != TEX_TYPE_2D_ARRAY) - depth = depth / 2; - } - } - } -} - diff --git a/RenderSystems/GL/src/OgreGLTextureManager.cpp b/RenderSystems/GL/src/OgreGLTextureManager.cpp deleted file mode 100644 index 63f41dcd18f..00000000000 --- a/RenderSystems/GL/src/OgreGLTextureManager.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLTextureManager.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" -#include "OgreGLCopyingRenderTexture.h" -#include "OgreGLTexture.h" -#include "OgreGLPixelFormat.h" -#include "OgreGLRenderSystem.h" - -namespace Ogre { - //----------------------------------------------------------------------------- - GLTextureManager::GLTextureManager(GLRenderSystem* renderSystem) - : TextureManager(), mRenderSystem(renderSystem) - { - // register with group manager - ResourceGroupManager::getSingleton()._registerResourceManager(mResourceType, this); - } - //----------------------------------------------------------------------------- - GLTextureManager::~GLTextureManager() - { - // unregister with group manager - ResourceGroupManager::getSingleton()._unregisterResourceManager(mResourceType); - } - //----------------------------------------------------------------------------- - Resource* GLTextureManager::createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams) - { - return new GLTexture(this, name, handle, group, isManual, loader, mRenderSystem); - } - - //----------------------------------------------------------------------------- - PixelFormat GLTextureManager::getNativeFormat(TextureType ttype, PixelFormat format, int usage) - { - // Adjust requested parameters to capabilities - const RenderSystemCapabilities *caps = Root::getSingleton().getRenderSystem()->getCapabilities(); - - // Check compressed texture support - // if a compressed format not supported, revert to PF_A8R8G8B8 - if(PixelUtil::isCompressed(format) && - !caps->hasCapability( RSC_TEXTURE_COMPRESSION_DXT )) - { - return PF_BYTE_RGBA; - } - // if floating point textures not supported, revert to PF_A8R8G8B8 - if(PixelUtil::isFloatingPoint(format) && - !caps->hasCapability( RSC_TEXTURE_FLOAT )) - { - return PF_BYTE_RGBA; - } - - // Check if this is a valid rendertarget format - if( usage & TU_RENDERTARGET ) - { - /// Get closest supported alternative - /// If mFormat is supported it's returned - return GLRTTManager::getSingleton().getSupportedAlternative(format); - } - - if(GLPixelUtil::getGLInternalFormat(format) == GL_NONE) - { - return PF_BYTE_RGBA; - } - - // Supported - return format; - - - } - //----------------------------------------------------------------------------- - bool GLTextureManager::isHardwareFilteringSupported(TextureType ttype, PixelFormat format, int usage, - bool preciseFormatOnly) - { - // precise format check - if (!TextureManager::isHardwareFilteringSupported(ttype, format, usage, preciseFormatOnly)) - return false; - - // Assume non-floating point is supported always - if (!PixelUtil::isFloatingPoint(getNativeFormat(ttype, format, usage))) - return true; - - // check for floating point extension - // note false positives on old harware: - // https://www.khronos.org/opengl/wiki/Floating_point_and_mipmapping_and_filtering - return mRenderSystem->checkExtension("GL_ARB_texture_float"); - } - -} diff --git a/RenderSystems/GL/src/atifs/include/ATI_FS_GLGpuProgram.h b/RenderSystems/GL/src/atifs/include/ATI_FS_GLGpuProgram.h deleted file mode 100644 index 31fc1828762..00000000000 --- a/RenderSystems/GL/src/atifs/include/ATI_FS_GLGpuProgram.h +++ /dev/null @@ -1,66 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __ATI_FS_GLGpuProgram_H__ -#define __ATI_FS_GLGpuProgram_H__ - -#include "OgreGLPrerequisites.h" -#include "OgreGLGpuProgram.h" - -namespace Ogre { - - /** Specialisation of the GL low-level program for ATI Fragment Shader programs. */ - class _OgreGLExport ATI_FS_GLGpuProgram : public GLGpuProgram - { - public: - ATI_FS_GLGpuProgram(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader); - virtual ~ATI_FS_GLGpuProgram(); - - - /// Execute the binding functions for this program - void bindProgram(void) override; - /// Execute the unbinding functions for this program - void unbindProgram(void) override; - /// Execute the param binding functions for this program - void bindProgramParameters(GpuProgramParametersSharedPtr params, uint16 mask) override; - - protected: - /// @copydoc Resource::unload - void unloadImpl(void) override; - void loadFromSource(void) override; - GLenum mProgramType; - - }; // class ATI_FS_GLGpuProgram - - - -} // namespace Ogre - -#endif // __ATI_FS_GLGpuProgram_H__ diff --git a/RenderSystems/GL/src/atifs/include/Compiler2Pass.h b/RenderSystems/GL/src/atifs/include/Compiler2Pass.h deleted file mode 100644 index f2d20ded713..00000000000 --- a/RenderSystems/GL/src/atifs/include/Compiler2Pass.h +++ /dev/null @@ -1,272 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - - -#ifndef COMPILER2PASS_H -#define COMPILER2PASS_H - -#include - -// FIX ME - should not be hard coded -#define BAD_TOKEN 999 - -typedef unsigned int uint; - - - -/** Compiler2Pass is a generic compiler/assembler - - provides a tokenizer in pass 1 and relies on the subclass to provide the virtual method for pass 2 - - PASS 1 - tokenize source: this is a simple brute force lexical scanner/analyzer that also parses - the formed token for proper semantics and context in one pass - it uses Look Ahead Left-Right (LALR) ruling based on Backus - Naur From notation for semantic - checking and also performs context checking allowing for language dialects - - PASS 2 - generate application specific instructions ie native instructions - -@par - this class must be subclassed with the subclass providing implementation for Pass 2. The subclass - is responsible for setting up the token libraries along with defining the language syntax. - -*/ -class Compiler2Pass { - -protected: - - // BNF operation types - enum OperationType {otRULE, otAND, otOR, otOPTIONAL, otREPEAT, otEND}; - - /** structure used to build rule paths - - */ - struct TokenRule { - OperationType mOperation; - uint mTokenID; - const char* mSymbol; - uint mErrorID; - - }; - - /** structure used to build Symbol Type library */ - struct SymbolDef { - uint mID; // Token ID which is the index into the Token Type library - uint mPass2Data; // data used by pass 2 to build native instructions - - uint mContextKey; // context key to fit the Active Context - uint mContextPatternSet; // new pattern to set for Active Context bits - uint mContextPatternClear;// Contexts bits to clear Active Context bits - - int mDefTextID; // index into text table for default name : set at runtime - uint mRuleID; // index into Rule database for non-terminal took rulepath - // if RuleID is zero the token is terminal - - }; - - - /** structure for Token instructions */ - struct TokenInst { - uint mNTTRuleID; // Non-Terminal Token Rule ID that generated Token - uint mID; // Token ID - int mLine; // line number in source code where Token was found - int mPos; // Character position in source where Token was found - - }; - - typedef std::vector TokenInstContainer; - //typedef TokenInstContainer::iterator TokenInstIterator; - - /// container for Tokens extracted from source - TokenInstContainer mTokenInstructions; - - /// pointer to the source to be compiled - const char* mSource; - int mEndOfSource; - - /// pointers to Text and Token Type libraries setup by subclass - SymbolDef* mSymbolTypeLib; - - /// pointer to root rule path - has to be set by subclass constructor - TokenRule* mRootRulePath; - - /// number of entries in Text and Token Type libraries - int mRulePathLibCnt; - int mSymbolTypeLibCnt; - - /// mVauleID needs to be initialized by the subclass before compiling occurs - /// it defines the token ID used in the symbol type library - uint mValueID; - - - /// storage container for constants defined in source - std::vector mConstants; - - /// Active Contexts pattern used in pass 1 to determine which tokens are valid for a certain context - uint mActiveContexts; - - /** check token semantics between ID1 and ID2 using left/right semantic data in Token Type library - @param ID1 token ID on the left - @param ID2 token ID on the right - @return - true if both will bind to each other - false if either fails the semantic bind test - - */ - //bool checkTokenSemantics(uint ID1, uint ID2); - - /** perform pass 1 of compile process - scans source for symbols that can be tokenized and then - performs general semantic and context verification on each symbol before it is tokenized. - A tokenized instruction list is built to be used by Pass 2. - - */ - bool doPass1(); - - /** pure virtual method that must be set up by subclass to perform Pass 2 of compile process - @remark - Pass 2 is for the subclass to take the token instructions generated in Pass 1 and - build the application specific instructions along with verifying - symantic and context rules that could not be checked in Pass 1 - - */ - virtual bool doPass2() = 0; - - void findEOL(); - - /** get the text symbol for this token - @remark - mainly used for debugging and in test routines - @param sid is the token ID - @return a pointer to the string text - */ - const char* getTypeDefText(const uint sid); - - /** check to see if the text at the present position in the source is a numerical constant - @param fvalue is a reference that will receive the float value that is in the source - @param charsize reference to receive number of characters that make of the value in the source - @return - true if characters form a valid float representation - false if a number value could not be extracted - */ - bool isFloatValue(float & fvalue, int & charsize); - - /** check to see if the text is in the symbol text library - @param symbol points to beginning of text where a symbol token might exist - @param symbolsize reference that will receive the size value of the symbol found - @return - true if a matching token could be found in the token type library - false if could not be tokenized - */ - bool isSymbol(const char* symbol, int & symbolsize); - - - /// position to the next possible valid sysmbol - bool positionToNextSymbol(); - - - /** process input source text using rulepath to determine allowed tokens - - the method is reentrant and recursive - if a non-terminal token is encountered in the current rule path then the method is - called using the new rule path referenced by the non-terminal token - Tokens can have the following operation states which effects the flow path of the rule - RULE: defines a rule path for the non-terminal token - AND: the token is required for the rule to pass - OR: if the previous tokens failed then try these ones - OPTIONAL: the token is optional and does not cause the rule to fail if the token is not found - REPEAT: the token is required but there can be more than one in a sequence - END: end of the rule path - the method returns the succuss of the rule - - @param rulepathIDX index into to array of Token Rules that define a rule path to be processed - @return - true if rule passed - all required tokens found - false if one or more tokens required to complete the rule were not found - */ - bool processRulePath( uint rulepathIDX); - - - // setup ActiveContexts - should be called by subclass to setup initial language contexts - void setActiveContexts(const uint contexts){ mActiveContexts = contexts; } - - - /// comment specifiers are hard coded - void skipComments(); - - /// find end of line marker and move past it - void skipEOL(); - - /// skip all the white space which includes spaces and tabs - void skipWhiteSpace(); - - - /** check if current position in source has the symbol text equivalent to the TokenID - @param rulepathIDX index into rule path database of token to validate - @param activeRuleID index of non-terminal rule that generated the token - @return - true if token was found - false if token symbol text does not match the source text - if token is non-terminal then processRulePath is called - */ - bool ValidateToken(const uint rulepathIDX, const uint activeRuleID); - - -public: - // ** these probably should not be public - int mCurrentLine; - int mCharPos; - - - /// constructor - Compiler2Pass(); - virtual ~Compiler2Pass() {} - /** compile the source - performs 2 passes - first pass is to tokinize, check semantics and context - second pass is performed by subclass and converts tokens to application specific instructions - @remark - Pass 2 only gets executed if Pass 1 has no errors - @param source a pointer to the source text to be compiled - @return - true if Pass 1 and Pass 2 are successful - false if any errors occur in Pass 1 or Pass 2 - */ - bool compile(const char* source); - - /** Initialize the type library with matching symbol text found in symbol text library - find a default text for all Symbol Types in library - - scan through all the rules and initialize TypeLib with index to text and index to rules for non-terminal tokens - - must be called by subclass after libraries and rule database setup - */ - - void InitSymbolTypeLib(); - -}; - -#endif - diff --git a/RenderSystems/GL/src/atifs/include/ps_1_4.h b/RenderSystems/GL/src/atifs/include/ps_1_4.h deleted file mode 100644 index ecbe82b4784..00000000000 --- a/RenderSystems/GL/src/atifs/include/ps_1_4.h +++ /dev/null @@ -1,366 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - - -/** - A number of invaluable references were used to put together this ps.1.x compiler for ATI_fragment_shader execution - - References: - 1. MSDN: DirectX 8.1 Reference - 2. Wolfgang F. Engel "Fundamentals of Pixel Shaders - Introduction to Shader Programming Part III" on gamedev.net - 3. Martin Ecker - XEngine - 4. Shawn Kirst - ps14toATIfs - 5. Jason L. Mitchell "Real-Time 3D Graphics With Pixel Shaders" - 6. Jason L. Mitchell "1.4 Pixel Shaders" - 7. Jason L. Mitchell and Evan Hart "Hardware Shading with EXT_vertex_shader and ATI_fragment_shader" - 6. ATI 8500 SDK - 7. GL_ATI_fragment_shader extension reference - -*/ -//--------------------------------------------------------------------------- -#ifndef ps_1_4H -#define ps_1_4H - -#include -#include -#include - -#include "OgreGLPrerequisites.h" -#include "Compiler2Pass.h" - - -//--------------------------------------------------------------------------- -// macro to get the size of a static array -#undef ARRAYSIZE -#define ARRAYSIZE(array) (sizeof(array)/sizeof(array[0])) - -#define ALPHA_BIT 0x08 -#define RGB_BITS 0x07 - -// Context key patterns -#define ckp_PS_BASE 0x1 -#define ckp_PS_1_1 0x2 -#define ckp_PS_1_2 0x4 -#define ckp_PS_1_3 0x8 -#define ckp_PS_1_4 0x10 - -#define ckp_PS_1_4_BASE (ckp_PS_BASE + ckp_PS_1_4) - - - - -/** Subclasses Compiler2Pass to provide a ps_1_x compiler that takes DirectX pixel shader assembly - and converts it to a form that can be used by ATI_fragment_shader OpenGL API - - all ps_1_1, ps_1_2, ps_1_3, ps_1_4 assembly instructions are recognized but not all are passed - on to ATI_fragment_shader. ATI_fragment_shader does not have an equivalent directive for - texkill or texdepth instructions. - - The user must provide the GL binding interfaces. - - A Test method is provided to verify the basic operation of the compiler which outputs the test - results to a file. - - -*/ -class PS_1_4 : public Compiler2Pass{ -private: - enum RWAflags {rwa_NONE = 0, rwa_READ = 1, rwa_WRITE = 2}; - - enum MachineInstID {mi_COLOROP1, mi_COLOROP2, mi_COLOROP3, mi_ALPHAOP1, mi_ALPHAOP2, - mi_ALPHAOP3, mi_SETCONSTANTS, mi_PASSTEXCOORD, mi_SAMPLEMAP, mi_TEX, - mi_TEXCOORD, mi_TEXREG2RGB, mi_NOP - }; - - struct TokenInstType{ - char* Name; - GLuint ID; - - }; - - struct RegisterUsage { - bool Phase1Write; - bool Phase2Write; - }; - - // Token ID enumeration - enum SymbolID { - // Terminal Tokens section - - // DirectX pixel shader source formats - sid_PS_1_4, sid_PS_1_1, sid_PS_1_2, sid_PS_1_3, - - // PS_BASE - sid_C0, sid_C1, sid_C2, sid_C3, sid_C4, sid_C5, sid_C6, sid_C7, - sid_V0, sid_V1, - sid_ADD, sid_SUB, sid_MUL, sid_MAD, sid_LRP, sid_MOV, sid_CMP, sid_CND, - sid_DP3, sid_DP4, sid_DEF, - sid_R, sid_RA, sid_G, sid_GA, sid_B, sid_BA, sid_A, sid_RGBA, sid_RGB, - sid_RG, sid_RGA, sid_RB, sid_RBA, sid_GB, sid_GBA, - sid_RRRR, sid_GGGG, sid_BBBB, sid_AAAA, - sid_X2, sid_X4, sid_D2, sid_SAT, - sid_BIAS, sid_INVERT, sid_NEGATE, sid_BX2, - sid_COMMA, sid_VALUE, - - //PS_1_4 sid - sid_R0, sid_R1, sid_R2, sid_R3, sid_R4, sid_R5, - sid_T0, sid_T1, sid_T2, sid_T3, sid_T4, sid_T5, - sid_DP2ADD, - sid_X8, sid_D8, sid_D4, - sid_TEXCRD, sid_TEXLD, - sid_STR, sid_STQ, - sid_STRDR, sid_STQDQ, - sid_BEM, - sid_PHASE, - - //PS_1_1 sid - sid_1R0, sid_1R1, sid_1T0, sid_1T1, sid_1T2, sid_1T3, - sid_TEX, sid_TEXCOORD, sid_TEXM3X2PAD, - sid_TEXM3X2TEX, sid_TEXM3X3PAD, sid_TEXM3X3TEX, sid_TEXM3X3SPEC, sid_TEXM3X3VSPEC, - sid_TEXREG2AR, sid_TEXREG2GB, - - //PS_1_2 side - sid_TEXREG2RGB, sid_TEXDP3, sid_TEXDP3TEX, - - // common - sid_SKIP, sid_PLUS, - - // non-terminal tokens section - sid_PROGRAM, sid_PROGRAMTYPE, sid_DECLCONSTS, sid_DEFCONST, - sid_CONSTANT, sid_COLOR, - sid_TEXSWIZZLE, sid_UNARYOP, - sid_NUMVAL, sid_SEPERATOR, sid_ALUOPS, sid_TEXMASK, sid_TEXOP_PS1_1_3, - sid_TEXOP_PS1_4, - sid_ALU_STATEMENT, sid_DSTMODSAT, sid_UNARYOP_ARGS, sid_REG_PS1_4, - sid_TEX_PS1_4, sid_REG_PS1_1_3, sid_TEX_PS1_1_3, sid_DSTINFO, - sid_SRCINFO, sid_BINARYOP_ARGS, sid_TERNARYOP_ARGS, sid_TEMPREG, - sid_DSTMASK, sid_PRESRCMOD, sid_SRCNAME, sid_SRCREP, sid_POSTSRCMOD, - sid_DSTMOD, sid_DSTSAT, sid_BINARYOP, sid_TERNARYOP, - sid_TEXOPS_PHASE1, sid_COISSUE, sid_PHASEMARKER, sid_TEXOPS_PHASE2, - sid_TEXREG_PS1_4, sid_TEXOPS_PS1_4, sid_TEXOPS_PS1_1_3, sid_TEXCISCOP_PS1_1_3, - - - // last token - sid_INVALID = BAD_TOKEN // must be last in enumeration - }; - - /// structure used to keep track of arguments and instruction parameters - struct OpParram { - GLuint Arg; // type of argument - bool Filled; // has it been filled yet - GLuint MaskRep; // Mask/Replicator flags - GLuint Mod; // argument modifier - }; - - typedef std::vector MachineInstContainer; - //typedef MachineInstContainer::iterator MachineInstIterator; - - - // there are 2 phases with 2 subphases each - enum PhaseType {ptPHASE1TEX, ptPHASE1ALU, ptPHASE2TEX, ptPHASE2ALU }; - - struct RegModOffset { - uint MacroOffset; - uint RegisterBase; - uint OpParramsIndex; - }; - - struct MacroRegModify { - TokenInst * Macro; - uint MacroSize; - RegModOffset * RegMods; - uint RegModSize; - - }; - - #define R_BASE static_cast((sid_R0 - GL_REG_0_ATI)) - #define C_BASE static_cast((sid_C0 - GL_CON_0_ATI)) - #define T_BASE static_cast((sid_1T0 - GL_REG_0_ATI)) - - // static library database for tokens and BNF rules - static SymbolDef PS_1_4_SymbolTypeLib[]; - static TokenRule PS_1_x_RulePath[]; - static bool LibInitialized; - - // Static Macro database for ps.1.1 ps.1.2 ps.1.3 instructions - - static TokenInst texreg2ar[]; - static RegModOffset texreg2xx_RegMods[]; - static MacroRegModify texreg2ar_MacroMods; - - static TokenInst texreg2gb[]; - static MacroRegModify texreg2gb_MacroMods; - - static TokenInst texdp3[]; - static RegModOffset texdp3_RegMods[]; - static MacroRegModify texdp3_MacroMods; - - static TokenInst texdp3tex[]; - static RegModOffset texdp3tex_RegMods[]; - static MacroRegModify texdp3tex_MacroMods; - - static TokenInst texm3x2pad[]; - static RegModOffset texm3xxpad_RegMods[]; - static MacroRegModify texm3x2pad_MacroMods; - - static TokenInst texm3x2tex[]; - static RegModOffset texm3xxtex_RegMods[]; - static MacroRegModify texm3x2tex_MacroMods; - - static TokenInst texm3x3pad[]; - static MacroRegModify texm3x3pad_MacroMods; - - static TokenInst texm3x3tex[]; - static MacroRegModify texm3x3tex_MacroMods; - - static TokenInst texm3x3spec[]; - static RegModOffset texm3x3spec_RegMods[]; - static MacroRegModify texm3x3spec_MacroMods; - - static TokenInst texm3x3vspec[]; - static RegModOffset texm3x3vspec_RegMods[]; - static MacroRegModify texm3x3vspec_MacroMods; - - - MachineInstContainer mPhase1TEX_mi; /// machine instructions for phase one texture section - MachineInstContainer mPhase1ALU_mi; /// machine instructions for phase one ALU section - MachineInstContainer mPhase2TEX_mi; /// machine instructions for phase two texture section - MachineInstContainer mPhase2ALU_mi; /// machine instructions for phase two ALU section - - // vars used during pass 2 - MachineInstID mOpType; - uint mOpInst; - bool mDo_Alpha; - PhaseType mInstructionPhase; - int mArgCnt; - int mConstantsPos; - - #define MAXOPPARRAMS 5 // max number of parrams bound to an instruction - - OpParram mOpParrams[MAXOPPARRAMS]; - - /// keeps track of which registers are written to in each phase - /// if a register is read from but has not been written to in phase 2 - /// then if it was written to in phase 1 perform a register pass function - /// at the beginning of phase2 so that the register has something worthwhile in it - /// NB: check ALU and TEX section of phase 1 and phase 2 - /// there are 6 temp registers r0 to r5 to keep track off - /// checks are performed in pass 2 when building machine instructions - RegisterUsage Phase_RegisterUsage[6]; - - bool mMacroOn; // if true then put all ALU instructions in phase 1 - - uint mTexm3x3padCount; // keep track of how many texm3x3pad instructions are used so know which mask to use - - size_t mLastInstructionPos; // keep track of last phase 2 ALU instruction to check for R0 setting - size_t mSecondLastInstructionPos; - - // keep track if phase marker found: determines which phase the ALU instructions go into - bool mPhaseMarkerFound; - -#ifdef _DEBUG - FILE* fp; - // full compiler test with output results going to a text file - void testCompile(char* testname, char* teststr, SymbolID* testresult, - uint testresultsize, GLuint* MachinInstResults = NULL, uint MachinInstResultsSize = 0); -#endif // _DEBUG - - - /** attempt to build a machine instruction using current tokens - determines what phase machine insturction should be in and if an Alpha Op is required - calls expandMachineInstruction() to expand the token into machine instructions - */ - bool BuildMachineInst(); - - void clearMachineInstState(); - - bool setOpParram(const SymbolDef* symboldef); - - /** optimizes machine instructions depending on pixel shader context - only applies to ps.1.1 ps.1.2 and ps.1.3 since they use CISC instructions - that must be transformed into RISC instructions - */ - void optimize(); - - // the method is expected to be recursive to allow for inline expansion of instructions if required - bool Pass2scan(const TokenInst * Tokens, const size_t size); - - // supply virtual functions for Compiler2Pass - /// Pass 1 is completed so now take tokens generated and build machine instructions - bool doPass2() override; - - /** Build a machine instruction from token and ready it for expansion - will expand CISC tokens using macro database - - */ - bool bindMachineInstInPassToFragmentShader(const MachineInstContainer & PassMachineInstructions); - - /** Expand CISC tokens into PS1_4 token equivalents - - */ - bool expandMacro(const MacroRegModify & MacroMod); - - /** Expand Machine instruction into operation type and arguments and put into proper machine - instruction container - also expands scaler alpha machine instructions if required - - */ - bool expandMachineInstruction(); - - // mainly used by tests - too slow for use in binding - size_t getMachineInst(size_t Idx); - - size_t getMachineInstCount(); - - void addMachineInst(PhaseType phase, const uint inst); - - void clearAllMachineInst(); - - void updateRegisterWriteState(const PhaseType phase); - - bool isRegisterReadValid(const PhaseType phase, const int param); - -public: - - /// constructor - PS_1_4(); - - /// binds machine instructions generated in Pass 2 to the ATI GL fragment shader - bool bindAllMachineInstToFragmentShader(); - -#ifdef _DEBUG - /// perform compiler tests - only available in _DEBUG mode - void test(); - void testbinder(); - -#endif -}; - - -#endif - diff --git a/RenderSystems/GL/src/atifs/src/ATI_FS_GLGpuProgram.cpp b/RenderSystems/GL/src/atifs/src/ATI_FS_GLGpuProgram.cpp deleted file mode 100644 index 0b767ec8924..00000000000 --- a/RenderSystems/GL/src/atifs/src/ATI_FS_GLGpuProgram.cpp +++ /dev/null @@ -1,140 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "ps_1_4.h" -#include "OgreException.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" -#include "OgreRenderSystemCapabilities.h" -#include "OgreLogManager.h" -#include "ATI_FS_GLGpuProgram.h" - - -namespace Ogre { - -ATI_FS_GLGpuProgram::ATI_FS_GLGpuProgram(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) : - GLGpuProgram(creator, name, handle, group, isManual, loader) -{ - mProgramType = GL_FRAGMENT_SHADER_ATI; - mProgramID = glGenFragmentShadersATI(1); -} - -ATI_FS_GLGpuProgram::~ATI_FS_GLGpuProgram() -{ - // have to call this here reather than in Resource destructor - // since calling virtual methods in base destructors causes crash - unload(); -} - -void ATI_FS_GLGpuProgram::bindProgram(void) -{ - glEnable(mProgramType); - glBindFragmentShaderATI(mProgramID); -} - -void ATI_FS_GLGpuProgram::unbindProgram(void) -{ - glDisable(mProgramType); -} - - -void ATI_FS_GLGpuProgram::bindProgramParameters(GpuProgramParametersSharedPtr params, uint16 mask) -{ - // only supports float constants - GpuLogicalBufferStructPtr floatStruct = params->getLogicalBufferStruct(); - - for (GpuLogicalIndexUseMap::const_iterator i = floatStruct->map.begin(); - i != floatStruct->map.end(); ++i) - { - if (i->second.variability & mask) - { - size_t logicalIndex = i->first; - const float* pFloat = params->getFloatPointer(i->second.physicalIndex); - // Iterate over the params, set in 4-float chunks (low-level) - for (size_t j = 0; j < i->second.currentSize; j+=4) - { - glSetFragmentShaderConstantATI(GL_CON_0_ATI + logicalIndex, pFloat); - pFloat += 4; - ++logicalIndex; - } - } - } - -} - -void ATI_FS_GLGpuProgram::unloadImpl(void) -{ - glDeleteFragmentShaderATI(mProgramID); -} - - -void ATI_FS_GLGpuProgram::loadFromSource(void) -{ - - PS_1_4 PS1_4Assembler; - // attempt to compile the source -#ifdef _DEBUG - PS1_4Assembler.test(); // run compiler tests in debug mode -#endif - - bool Error = !PS1_4Assembler.compile(mSource.c_str()); - - if(!Error) { - glBindFragmentShaderATI(mProgramID); - glBeginFragmentShaderATI(); - // compile was successful so send the machine instructions thru GL to GPU - Error = !PS1_4Assembler.bindAllMachineInstToFragmentShader(); - glEndFragmentShaderATI(); - - // check GL for GPU machine instruction bind erros - if (Error) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Cannot Bind ATI fragment shader :" + mName, mName); - } - - } - else - { - // an error occurred when compiling the ps_1_4 source code - char buff[50]; - sprintf(buff,"error on line %d in pixel shader source\n", PS1_4Assembler.mCurrentLine); - - LogManager::getSingleton().logMessage("Warning: atifs compiler reported the following errors:"); - LogManager::getSingleton().logMessage(buff + mName); - - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Cannot Compile ATI fragment shader : " + mName + "\n\n" + buff , mName);// + - } - - -} - -} diff --git a/RenderSystems/GL/src/atifs/src/Compiler2Pass.cpp b/RenderSystems/GL/src/atifs/src/Compiler2Pass.cpp deleted file mode 100644 index 9c5026d0772..00000000000 --- a/RenderSystems/GL/src/atifs/src/Compiler2Pass.cpp +++ /dev/null @@ -1,379 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include -#include -#include -#include -#include "Compiler2Pass.h" - -Compiler2Pass::Compiler2Pass() -{ - // reserve some memory space in the containers being used - mTokenInstructions.reserve(100); - mConstants.reserve(80); - // default contexts allows all contexts - // subclass should change it to fit the language being compiled - mActiveContexts = 0xffffffff; - -} - - - -void Compiler2Pass::InitSymbolTypeLib() -{ - uint token_ID; - // find a default text for all Symbol Types in library - - // scan through all the rules and initialize TypeLib with index to text and index to rules for non-terminal tokens - for(int i = 0; i < mRulePathLibCnt; i++) { - token_ID = mRootRulePath[i].mTokenID; - // make sure SymbolTypeLib holds valid token - assert(mSymbolTypeLib[token_ID].mID == token_ID); - switch(mRootRulePath[i].mOperation) { - case otRULE: - // if operation is a rule then update typelib - mSymbolTypeLib[token_ID].mRuleID = i; - - case otAND: - case otOR: - case otOPTIONAL: - // update text index in typelib - if (mRootRulePath[i].mSymbol != NULL) mSymbolTypeLib[token_ID].mDefTextID = i; - break; - case otREPEAT: - case otEND: - break; - } - } - -} - - -bool Compiler2Pass::compile(const char* source) -{ - bool Passed = false; - - mSource = source; - // start compiling if there is a rule base to work with - if(mRootRulePath != NULL) { - Passed = doPass1(); - - if(Passed) { - Passed = doPass2(); - } - } - return Passed; -} - - -bool Compiler2Pass::doPass1() -{ - // scan through Source string and build a token list using TokenInstructions - // this is a simple brute force lexical scanner/analyzer that also parses the formed - // token for proper semantics and context in one pass - - mCurrentLine = 1; - mCharPos = 0; - // reset position in Constants container - mConstants.clear(); - mEndOfSource = strlen(mSource); - - // start with a clean slate - mTokenInstructions.clear(); - // tokenize and check semantics until an error occurs or end of source is reached - // assume RootRulePath has pointer to rules so start at index + 1 for first rule path - // first rule token would be a rule definition so skip over it - bool passed = processRulePath(0); - // if a symbol in source still exists then the end of source was not reached and there was a problem some where - if (positionToNextSymbol()) passed = false; - return passed; - -} - - -bool Compiler2Pass::processRulePath( uint rulepathIDX) -{ - // rule path determines what tokens and therefore what symbols are acceptable from the source - // it is assumed that the tokens with the longest similar symbols are arranged first so - // if a match is found it is accepted and no further searching is done - - // record position of last token in container - // to be used as the rollback position if a valid token is not found - uint TokenContainerOldSize = mTokenInstructions.size(); - int OldCharPos = mCharPos; - int OldLinePos = mCurrentLine; - uint OldConstantsSize = mConstants.size(); - - // keep track of what non-terminal token activated the rule - uint ActiveNTTRule = mRootRulePath[rulepathIDX].mTokenID; - // start rule path at next position for definition - rulepathIDX++; - - // assume the rule will pass - bool Passed = true; - bool EndFound = false; - - // keep following rulepath until the end is reached - while (EndFound == false) { - switch (mRootRulePath[rulepathIDX].mOperation) { - - case otAND: - // only validate if the previous rule passed - if(Passed) Passed = ValidateToken(rulepathIDX, ActiveNTTRule); - break; - - case otOR: - // only validate if the previous rule failed - if ( Passed == false ) { - // clear previous tokens from entry and try again - mTokenInstructions.resize(TokenContainerOldSize); - Passed = ValidateToken(rulepathIDX, ActiveNTTRule); - } - else { // path passed up to this point therefore finished so pretend end marker found - EndFound = true; - } - break; - - case otOPTIONAL: - // if previous passed then try this rule but it does not effect succes of rule since its optional - if(Passed) ValidateToken(rulepathIDX, ActiveNTTRule); - break; - - case otREPEAT: - // repeat until no tokens of this type found - // at least one must be found - if(Passed) { - int TokensPassed = 0; - // keep calling until failure - while ((Passed = ValidateToken(rulepathIDX, ActiveNTTRule))) { - // increment count for previous passed token - TokensPassed++; - } - // defaults to Passed = fail - // if at least one token found then return passed = true - if (TokensPassed > 0) Passed = true; - } - break; - - case otEND: - // end of rule found so time to return - EndFound = true; - if(Passed == false) { - // the rule did not validate so get rid of tokens decoded - // roll back the token container end position to what it was when rule started - // this will get rid of all tokens that had been pushed on the container while - // trying to validating this rule - mTokenInstructions.resize(TokenContainerOldSize); - mConstants.resize(OldConstantsSize); - mCharPos = OldCharPos; - mCurrentLine = OldLinePos; - } - break; - - default: - // an exception should be raised since the code should never get here - Passed = false; - EndFound = true; - break; - - } - - - // move on to the next rule in the path - rulepathIDX++; - } - - return Passed; - -} - - -bool Compiler2Pass::ValidateToken(const uint rulepathIDX, const uint activeRuleID) -{ - int tokenlength = 0; - // assume the test is going to fail - bool Passed = false; - uint TokenID = mRootRulePath[rulepathIDX].mTokenID; - // only validate token if context is correct - if (mSymbolTypeLib[TokenID].mContextKey & mActiveContexts) { - - // if terminal token then compare text of symbol with what is in source - if ( mSymbolTypeLib[TokenID].mRuleID == 0){ - - if (positionToNextSymbol()) { - // if Token is supposed to be a number then check if its a numerical constant - if (TokenID == mValueID) { - float constantvalue; - if((Passed = isFloatValue(constantvalue, tokenlength))) { - mConstants.push_back(constantvalue); - } - - } - // compare token symbol text with source text - else Passed = isSymbol(mRootRulePath[rulepathIDX].mSymbol, tokenlength); - - if(Passed) { - TokenInst newtoken; - // push token onto end of container - newtoken.mID = TokenID; - newtoken.mNTTRuleID = activeRuleID; - newtoken.mLine = mCurrentLine; - newtoken.mPos = mCharPos; - - mTokenInstructions.push_back(newtoken); - // update source position - mCharPos += tokenlength; - - // allow token instruction to change the ActiveContexts - // use token contexts pattern to clear ActiveContexts pattern bits - mActiveContexts &= ~mSymbolTypeLib[TokenID].mContextPatternClear; - // use token contexts pattern to set ActiveContexts pattern bits - mActiveContexts |= mSymbolTypeLib[TokenID].mContextPatternSet; - } - } - - } - // else a non terminal token was found - else { - - // execute rule for non-terminal - // get rule_ID for index into rulepath to be called - Passed = processRulePath(mSymbolTypeLib[TokenID].mRuleID); - } - } - - - return Passed; - -} - - -const char* Compiler2Pass::getTypeDefText(const uint sid) -{ - return mRootRulePath[mSymbolTypeLib[sid].mDefTextID].mSymbol; -} - - -bool Compiler2Pass::isFloatValue(float& fvalue, int& charsize) -{ - // check to see if it is a numeric float value - bool valuefound = false; - - const char* startptr = mSource + mCharPos; - char* endptr = NULL; - - fvalue = (float)strtod(startptr, &endptr); - // if a valid float was found then endptr will have the pointer to the first invalid character - if(endptr) { - if(endptr>startptr) { - // a valid value was found so process it - charsize = endptr - startptr; - valuefound = true; - } - } - - return valuefound; -} - - -bool Compiler2Pass::isSymbol(const char* symbol, int& symbolsize) -{ - // compare text at source+charpos with the symbol : limit testing to symbolsize - bool symbolfound = false; - symbolsize = strlen(symbol); - if(strncmp(mSource + mCharPos, symbol, symbolsize)==0) { - symbolfound = true; - } - - return symbolfound; -} - - -bool Compiler2Pass::positionToNextSymbol() -{ - bool validsymbolfound = false; - bool endofsource = false; - while(!validsymbolfound && !endofsource) { - skipWhiteSpace(); - skipEOL(); - skipComments(); - // have we reached the end of the string? - if (mCharPos == mEndOfSource) endofsource = true; - else { - // if ASCII > space then assume valid character is found - if (mSource[mCharPos] > ' ') validsymbolfound = true; - } - }// end of while - - return validsymbolfound; -} - - - -void Compiler2Pass::skipComments() -{ - // if current char and next are // then search for EOL - if(mCharPos < mEndOfSource) { - if( ((mSource[mCharPos] == '/') && (mSource[mCharPos + 1] == '/')) || - (mSource[mCharPos] == ';') || - (mSource[mCharPos] == '#') ) findEOL(); - } -} - - -void Compiler2Pass::findEOL() -{ - // find eol charter and move to this position - const char* newpos = strchr(&mSource[mCharPos], '\n'); - if(newpos) { - mCharPos += newpos - &mSource[mCharPos]; - } - // couldn't find end of line so skip to the end - else mCharPos = mEndOfSource - 1; - -} - - -void Compiler2Pass::skipEOL() -{ - if ((mSource[mCharPos] == '\n') || (mSource[mCharPos] == '\r')) { - mCurrentLine++; - mCharPos++; - if ((mSource[mCharPos] == '\n') || (mSource[mCharPos] == '\r')) { - mCharPos++; - } - } -} - - -void Compiler2Pass::skipWhiteSpace() -{ - // FIX - this method kinda slow - while((mSource[mCharPos] == ' ') || (mSource[mCharPos] == '\t')) mCharPos++; // find first non white space character -} - diff --git a/RenderSystems/GL/src/atifs/src/ps_1_4.cpp b/RenderSystems/GL/src/atifs/src/ps_1_4.cpp deleted file mode 100644 index baaa2d14aa1..00000000000 --- a/RenderSystems/GL/src/atifs/src/ps_1_4.cpp +++ /dev/null @@ -1,2149 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - - - //--------------------------------------------------------------------------- -#include "ps_1_4.h" - -//--------------------------------------------------------------------------- - -/* ********************* START OF PS_1_4 CLASS STATIC DATA ********************************* */ - - -// library of built in symbol types - -bool PS_1_4::LibInitialized = false; - -#define SYMSTART { -#define SYMDEF ,0,0,0,0},{ -#define SYMEND ,0,0,0,0} - -PS_1_4::SymbolDef PS_1_4::PS_1_4_SymbolTypeLib[] = { - // pixel shader versions supported - { sid_PS_1_4, GL_NONE, ckp_PS_BASE, ckp_PS_1_4, 0, 0, 0 }, - { sid_PS_1_1, GL_NONE, ckp_PS_BASE, ckp_PS_1_1, 0, 0, 0 }, - { sid_PS_1_2, GL_NONE, ckp_PS_BASE, ckp_PS_1_2 + ckp_PS_1_1, 0, 0, 0 }, - { sid_PS_1_3, GL_NONE, ckp_PS_BASE, ckp_PS_1_3 + ckp_PS_1_2 + ckp_PS_1_1, 0, 0, 0 }, - - // PS_BASE - - // constants - SYMSTART sid_C0, GL_CON_0_ATI, ckp_PS_BASE - SYMDEF sid_C1, GL_CON_1_ATI, ckp_PS_BASE - SYMDEF sid_C2, GL_CON_2_ATI, ckp_PS_BASE - SYMDEF sid_C3, GL_CON_3_ATI, ckp_PS_BASE - SYMDEF sid_C4, GL_CON_4_ATI, ckp_PS_BASE - SYMDEF sid_C5, GL_CON_5_ATI, ckp_PS_BASE - SYMDEF sid_C6, GL_CON_6_ATI, ckp_PS_BASE - SYMDEF sid_C7, GL_CON_7_ATI, ckp_PS_BASE - - // colour - SYMDEF sid_V0, GL_PRIMARY_COLOR_ARB, ckp_PS_BASE - SYMDEF sid_V1, GL_SECONDARY_INTERPOLATOR_ATI, ckp_PS_BASE - - // instruction ops - SYMDEF sid_ADD, GL_ADD_ATI, ckp_PS_BASE - SYMDEF sid_SUB, GL_SUB_ATI, ckp_PS_BASE - SYMDEF sid_MUL, GL_MUL_ATI, ckp_PS_BASE - SYMDEF sid_MAD, GL_MAD_ATI, ckp_PS_BASE - SYMDEF sid_LRP, GL_LERP_ATI, ckp_PS_BASE - SYMDEF sid_MOV, GL_MOV_ATI, ckp_PS_BASE - SYMDEF sid_CMP, GL_CND0_ATI, ckp_PS_BASE - SYMDEF sid_CND, GL_CND_ATI, ckp_PS_BASE - SYMDEF sid_DP3, GL_DOT3_ATI, ckp_PS_BASE - SYMDEF sid_DP4, GL_DOT4_ATI, ckp_PS_BASE - - SYMDEF sid_DEF, GL_NONE, ckp_PS_BASE - - // Masks - SYMDEF sid_R, GL_RED_BIT_ATI, ckp_PS_1_4 - SYMDEF sid_RA, GL_RED_BIT_ATI | ALPHA_BIT, ckp_PS_1_4 - SYMDEF sid_G, GL_GREEN_BIT_ATI, ckp_PS_1_4 - SYMDEF sid_GA, GL_GREEN_BIT_ATI | ALPHA_BIT, ckp_PS_1_4 - SYMDEF sid_B, GL_BLUE_BIT_ATI, ckp_PS_1_4 - SYMDEF sid_BA, GL_BLUE_BIT_ATI | ALPHA_BIT, ckp_PS_1_4 - SYMDEF sid_A, ALPHA_BIT, ckp_PS_BASE - SYMDEF sid_RGBA, RGB_BITS | ALPHA_BIT, ckp_PS_BASE - SYMDEF sid_RGB, RGB_BITS, ckp_PS_BASE - SYMDEF sid_RG, GL_RED_BIT_ATI | GL_GREEN_BIT_ATI, ckp_PS_1_4 - SYMDEF sid_RGA, GL_RED_BIT_ATI | GL_GREEN_BIT_ATI | ALPHA_BIT, ckp_PS_1_4 - SYMDEF sid_RB, GL_RED_BIT_ATI | GL_BLUE_BIT_ATI, ckp_PS_1_4 - SYMDEF sid_RBA, GL_RED_BIT_ATI | GL_BLUE_BIT_ATI | ALPHA_BIT, ckp_PS_1_4 - SYMDEF sid_GB, GL_GREEN_BIT_ATI | GL_BLUE_BIT_ATI, ckp_PS_1_4 - SYMDEF sid_GBA, GL_GREEN_BIT_ATI | GL_BLUE_BIT_ATI | ALPHA_BIT, ckp_PS_1_4 - - // Rep - SYMDEF sid_RRRR, GL_RED, ckp_PS_1_4 - SYMDEF sid_GGGG, GL_GREEN, ckp_PS_1_4 - SYMDEF sid_BBBB, GL_BLUE, ckp_PS_BASE - SYMDEF sid_AAAA, GL_ALPHA, ckp_PS_BASE - - - // modifiers - SYMDEF sid_X2, GL_2X_BIT_ATI, ckp_PS_BASE - SYMDEF sid_X4, GL_4X_BIT_ATI, ckp_PS_BASE - SYMDEF sid_D2, GL_HALF_BIT_ATI, ckp_PS_BASE - SYMDEF sid_SAT, GL_SATURATE_BIT_ATI, ckp_PS_BASE - - // argument modifiers - SYMDEF sid_BIAS, GL_BIAS_BIT_ATI, ckp_PS_BASE - SYMDEF sid_INVERT, GL_COMP_BIT_ATI, ckp_PS_BASE - SYMDEF sid_NEGATE, GL_NEGATE_BIT_ATI, ckp_PS_BASE - SYMDEF sid_BX2, GL_2X_BIT_ATI | GL_BIAS_BIT_ATI, ckp_PS_BASE - - // seperator characters - SYMDEF sid_COMMA, GL_NONE, ckp_PS_BASE - SYMDEF sid_VALUE, GL_NONE, ckp_PS_BASE - - // PS_1_4 - // temp R/W registers - SYMDEF sid_R0, GL_REG_0_ATI, ckp_PS_1_4 - SYMDEF sid_R1, GL_REG_1_ATI, ckp_PS_1_4 - SYMDEF sid_R2, GL_REG_2_ATI, ckp_PS_1_4 - SYMDEF sid_R3, GL_REG_3_ATI, ckp_PS_1_4 - SYMDEF sid_R4, GL_REG_4_ATI, ckp_PS_1_4 - SYMDEF sid_R5, GL_REG_5_ATI, ckp_PS_1_4 - - // textures - SYMDEF sid_T0, GL_TEXTURE0_ARB, ckp_PS_1_4 - SYMDEF sid_T1, GL_TEXTURE1_ARB, ckp_PS_1_4 - SYMDEF sid_T2, GL_TEXTURE2_ARB, ckp_PS_1_4 - SYMDEF sid_T3, GL_TEXTURE3_ARB, ckp_PS_1_4 - SYMDEF sid_T4, GL_TEXTURE4_ARB, ckp_PS_1_4 - SYMDEF sid_T5, GL_TEXTURE5_ARB, ckp_PS_1_4 - SYMDEF sid_DP2ADD, GL_DOT2_ADD_ATI, ckp_PS_1_4 - - // modifiers - SYMDEF sid_X8, GL_8X_BIT_ATI, ckp_PS_1_4 - SYMDEF sid_D8, GL_EIGHTH_BIT_ATI, ckp_PS_1_4 - SYMDEF sid_D4, GL_QUARTER_BIT_ATI, ckp_PS_1_4 - - // instructions - SYMDEF sid_TEXCRD, GL_NONE, ckp_PS_1_4 - SYMDEF sid_TEXLD, GL_NONE, ckp_PS_1_4 - - // texture swizzlers - - SYMDEF sid_STR, GL_SWIZZLE_STR_ATI - GL_SWIZZLE_STR_ATI, ckp_PS_1_4 - SYMDEF sid_STQ, GL_SWIZZLE_STQ_ATI - GL_SWIZZLE_STR_ATI, ckp_PS_1_4 - SYMDEF sid_STRDR, GL_SWIZZLE_STR_DR_ATI - GL_SWIZZLE_STR_ATI, ckp_PS_1_4 - SYMDEF sid_STQDQ, GL_SWIZZLE_STQ_DQ_ATI - GL_SWIZZLE_STR_ATI, ckp_PS_1_4 - - SYMDEF sid_BEM, GL_NONE, ckp_PS_1_4 - SYMDEF sid_PHASE, GL_NONE, ckp_PS_1_4 - - // PS_1_1 - // temp R/W registers - // r0, r1 are mapped to r4, r5 - // t0 to t3 are mapped to r0 to r3 - SYMDEF sid_1R0, GL_REG_4_ATI, ckp_PS_1_1 - SYMDEF sid_1R1, GL_REG_5_ATI, ckp_PS_1_1 - SYMDEF sid_1T0, GL_REG_0_ATI, ckp_PS_1_1 - SYMDEF sid_1T1, GL_REG_1_ATI, ckp_PS_1_1 - SYMDEF sid_1T2, GL_REG_2_ATI, ckp_PS_1_1 - SYMDEF sid_1T3, GL_REG_3_ATI, ckp_PS_1_1 - - // instructions common to PS_1_1, PS_1_2, PS_1_3 - SYMDEF sid_TEX, GL_NONE, ckp_PS_1_1 - SYMDEF sid_TEXCOORD, GL_NONE, ckp_PS_1_1 - SYMDEF sid_TEXM3X2PAD, GL_NONE, ckp_PS_1_1 - SYMDEF sid_TEXM3X2TEX, GL_NONE, ckp_PS_1_1 - SYMDEF sid_TEXM3X3PAD, GL_NONE, ckp_PS_1_1 - SYMDEF sid_TEXM3X3TEX, GL_NONE, ckp_PS_1_1 - SYMDEF sid_TEXM3X3SPEC, GL_NONE, ckp_PS_1_1 - SYMDEF sid_TEXM3X3VSPEC, GL_NONE, ckp_PS_1_1 - SYMDEF sid_TEXREG2AR, GL_NONE, ckp_PS_1_2 - SYMDEF sid_TEXREG2GB, GL_NONE, ckp_PS_1_2 - - // PS_1_2 & PS_1_3 - SYMDEF sid_TEXREG2RGB, GL_NONE, ckp_PS_1_2 - SYMDEF sid_TEXDP3, GL_NONE, ckp_PS_1_2 - SYMDEF sid_TEXDP3TEX, GL_NONE, ckp_PS_1_2 - - - // Common - SYMDEF sid_SKIP, GL_NONE, ckp_PS_BASE - SYMDEF sid_PLUS, GL_NONE, ckp_PS_BASE - - // Non-Terminal Tokens - SYMDEF sid_PROGRAM, GL_NONE, ckp_PS_BASE - SYMDEF sid_PROGRAMTYPE, GL_NONE, ckp_PS_BASE - SYMDEF sid_DECLCONSTS, GL_NONE, ckp_PS_BASE - SYMDEF sid_DEFCONST, GL_NONE, ckp_PS_BASE - SYMDEF sid_CONSTANT, GL_NONE, ckp_PS_BASE - SYMDEF sid_COLOR, GL_NONE, ckp_PS_BASE - SYMDEF sid_TEXSWIZZLE, GL_NONE, ckp_PS_BASE - SYMDEF sid_UNARYOP, GL_NONE, ckp_PS_BASE - SYMDEF sid_NUMVAL, GL_NONE, ckp_PS_BASE - SYMDEF sid_SEPERATOR, GL_NONE, ckp_PS_BASE - SYMDEF sid_ALUOPS, GL_NONE, ckp_PS_BASE - SYMDEF sid_TEXMASK, GL_NONE, ckp_PS_BASE - SYMDEF sid_TEXOP_PS1_1_3, GL_NONE, ckp_PS_1_1 - SYMDEF sid_TEXOP_PS1_4, GL_NONE, ckp_PS_1_4 - SYMDEF sid_ALU_STATEMENT, GL_NONE, ckp_PS_BASE - SYMDEF sid_DSTMODSAT, GL_NONE, ckp_PS_BASE - SYMDEF sid_UNARYOP_ARGS, GL_NONE, ckp_PS_BASE - SYMDEF sid_REG_PS1_4, GL_NONE, ckp_PS_1_4 - SYMDEF sid_TEX_PS1_4, GL_NONE, ckp_PS_1_4 - SYMDEF sid_REG_PS1_1_3, GL_NONE, ckp_PS_1_1 - SYMDEF sid_TEX_PS1_1_3, GL_NONE, ckp_PS_1_1 - SYMDEF sid_DSTINFO, GL_NONE, ckp_PS_BASE - SYMDEF sid_SRCINFO, GL_NONE, ckp_PS_BASE - SYMDEF sid_BINARYOP_ARGS, GL_NONE, ckp_PS_BASE - SYMDEF sid_TERNARYOP_ARGS, GL_NONE, ckp_PS_BASE - SYMDEF sid_TEMPREG, GL_NONE, ckp_PS_BASE - SYMDEF sid_DSTMASK, GL_NONE, ckp_PS_BASE - SYMDEF sid_PRESRCMOD, GL_NONE, ckp_PS_BASE - SYMDEF sid_SRCNAME, GL_NONE, ckp_PS_BASE - SYMDEF sid_SRCREP, GL_NONE, ckp_PS_BASE - SYMDEF sid_POSTSRCMOD, GL_NONE, ckp_PS_BASE - SYMDEF sid_DSTMOD, GL_NONE, ckp_PS_BASE - SYMDEF sid_DSTSAT, GL_NONE, ckp_PS_BASE - SYMDEF sid_BINARYOP, GL_NONE, ckp_PS_BASE - SYMDEF sid_TERNARYOP, GL_NONE, ckp_PS_BASE - SYMDEF sid_TEXOPS_PHASE1, GL_NONE, ckp_PS_BASE - SYMDEF sid_COISSUE, GL_NONE, ckp_PS_BASE - SYMDEF sid_PHASEMARKER, GL_NONE, ckp_PS_1_4 - SYMDEF sid_TEXOPS_PHASE2, GL_NONE, ckp_PS_1_4 - SYMDEF sid_TEXREG_PS1_4, GL_NONE, ckp_PS_1_4 - SYMDEF sid_TEXOPS_PS1_4, GL_NONE, ckp_PS_1_4 - SYMDEF sid_TEXOPS_PS1_1_3, GL_NONE, ckp_PS_1_1 - SYMDEF sid_TEXCISCOP_PS1_1_3, GL_NONE, ckp_PS_1_1 - SYMEND -}; - - -// Rule Path Database for ps.1.x code based on extended Backus Naur Form notation - -// <> - non-terminal token -#define _rule_ {otRULE, // ::= - rule definition -#define _is_ ,0},{otAND, -#define _and_ ,0},{otAND, // - blank space is an implied "AND" meaning the token is required -#define _or_ ,0},{otOR, // | - or -#define _optional_ ,0},{otOPTIONAL, // [] - optional -#define _repeat_ ,0},{otREPEAT, // {} - repeat until fail -#define _end_ ,0},{otEND,0,0,0}, -#define _nt_ ,0 -// " " - terminal token string - -PS_1_4::TokenRule PS_1_4::PS_1_x_RulePath[] = { - - _rule_ sid_PROGRAM, "Program" - - _is_ sid_PROGRAMTYPE _nt_ - _optional_ sid_DECLCONSTS _nt_ - _optional_ sid_TEXOPS_PHASE1 _nt_ - _optional_ sid_ALUOPS _nt_ - _optional_ sid_PHASEMARKER _nt_ - _optional_ sid_TEXOPS_PHASE2 _nt_ - _optional_ sid_ALUOPS _nt_ - _end_ - - _rule_ sid_PROGRAMTYPE, "" - - _is_ sid_PS_1_4, "ps.1.4" - _or_ sid_PS_1_1, "ps.1.1" - _or_ sid_PS_1_2, "ps.1.2" - _or_ sid_PS_1_3, "ps.1.3" - _end_ - - _rule_ sid_PHASEMARKER, "" - - _is_ sid_PHASE, "phase" - _end_ - - _rule_ sid_DECLCONSTS, "" - - _repeat_ sid_DEFCONST _nt_ - _end_ - - - _rule_ sid_TEXOPS_PHASE1, "" - - _is_ sid_TEXOPS_PS1_1_3 _nt_ - _or_ sid_TEXOPS_PS1_4 _nt_ - _end_ - - _rule_ sid_TEXOPS_PHASE2, "" - - _is_ sid_TEXOPS_PS1_4 _nt_ - _end_ - - _rule_ sid_NUMVAL, "" - - _is_ sid_VALUE, "Float Value" - _end_ - - _rule_ sid_TEXOPS_PS1_1_3, "" - - _repeat_ sid_TEXOP_PS1_1_3 _nt_ - _end_ - - _rule_ sid_TEXOPS_PS1_4, "" - - _repeat_ sid_TEXOP_PS1_4 _nt_ - _end_ - - _rule_ sid_TEXOP_PS1_1_3, "" - - _is_ sid_TEXCISCOP_PS1_1_3 _nt_ - _and_ sid_TEX_PS1_1_3 _nt_ - _and_ sid_SEPERATOR _nt_ - _and_ sid_TEX_PS1_1_3 _nt_ - - _or_ sid_TEXCOORD, "texcoord" - _and_ sid_TEX_PS1_1_3 _nt_ - - _or_ sid_TEX, "tex" - _and_ sid_TEX_PS1_1_3 _nt_ - - - - _end_ - - _rule_ sid_TEXOP_PS1_4, "" - - _is_ sid_TEXCRD, "texcrd" - _and_ sid_REG_PS1_4 _nt_ - _optional_ sid_TEXMASK _nt_ - _and_ sid_SEPERATOR _nt_ - _and_ sid_TEXREG_PS1_4 _nt_ - - _or_ sid_TEXLD, "texld" - _and_ sid_REG_PS1_4 _nt_ - _optional_ sid_TEXMASK _nt_ - _and_ sid_SEPERATOR _nt_ - _and_ sid_TEXREG_PS1_4 _nt_ - _end_ - - _rule_ sid_ALUOPS, "" - - _repeat_ sid_ALU_STATEMENT _nt_ - _end_ - - _rule_ sid_ALU_STATEMENT, "" - - _is_ sid_COISSUE _nt_ - _and_ sid_UNARYOP _nt_ - _optional_ sid_DSTMODSAT _nt_ - _and_ sid_UNARYOP_ARGS _nt_ - - _or_ sid_COISSUE _nt_ - _and_ sid_BINARYOP _nt_ - _optional_ sid_DSTMODSAT _nt_ - _and_ sid_BINARYOP_ARGS _nt_ - - _or_ sid_COISSUE _nt_ - _and_ sid_TERNARYOP _nt_ - _optional_ sid_DSTMODSAT _nt_ - _and_ sid_TERNARYOP_ARGS _nt_ - _end_ - - - _rule_ sid_TEXREG_PS1_4, "" - - _is_ sid_TEX_PS1_4 _nt_ - _optional_ sid_TEXSWIZZLE _nt_ - _or_ sid_REG_PS1_4 _nt_ - _optional_ sid_TEXSWIZZLE _nt_ - _end_ - - _rule_ sid_UNARYOP_ARGS, "" - - _is_ sid_DSTINFO _nt_ - _and_ sid_SRCINFO _nt_ - _end_ - - _rule_ sid_BINARYOP_ARGS, "" - - _is_ sid_DSTINFO _nt_ - _and_ sid_SRCINFO _nt_ - _and_ sid_SRCINFO _nt_ - _end_ - - _rule_ sid_TERNARYOP_ARGS, "" - - _is_ sid_DSTINFO _nt_ - _and_ sid_SRCINFO _nt_ - _and_ sid_SRCINFO _nt_ - _and_ sid_SRCINFO _nt_ - _end_ - - _rule_ sid_DSTINFO, "" - - _is_ sid_TEMPREG _nt_ - _optional_ sid_DSTMASK _nt_ - _end_ - - _rule_ sid_SRCINFO, "" - - _is_ sid_SEPERATOR _nt_ - _optional_ sid_PRESRCMOD _nt_ - _and_ sid_SRCNAME _nt_ - _optional_ sid_POSTSRCMOD _nt_ - _optional_ sid_SRCREP _nt_ - _end_ - - _rule_ sid_SRCNAME, "" - - _is_ sid_TEMPREG _nt_ - _or_ sid_CONSTANT _nt_ - _or_ sid_COLOR _nt_ - _end_ - - _rule_ sid_DEFCONST, "" - - _is_ sid_DEF, "def" - _and_ sid_CONSTANT _nt_ - _and_ sid_SEPERATOR _nt_ - _and_ sid_NUMVAL _nt_ - _and_ sid_SEPERATOR _nt_ - _and_ sid_NUMVAL _nt_ - _and_ sid_SEPERATOR _nt_ - _and_ sid_NUMVAL _nt_ - _and_ sid_SEPERATOR _nt_ - _and_ sid_NUMVAL _nt_ - _end_ - - _rule_ sid_CONSTANT, "" - - _is_ sid_C0, "c0" - _or_ sid_C1, "c1" - _or_ sid_C2, "c2" - _or_ sid_C3, "c3" - _or_ sid_C4, "c4" - _or_ sid_C5, "c5" - _or_ sid_C6, "c6" - _or_ sid_C7, "c7" - _end_ - - - _rule_ sid_TEXCISCOP_PS1_1_3, "" - - _is_ sid_TEXDP3TEX, "texdp3tex" - _or_ sid_TEXDP3, "texdp3" - _or_ sid_TEXM3X2PAD, "texm3x2pad" - _or_ sid_TEXM3X2TEX, "texm3x2tex" - _or_ sid_TEXM3X3PAD, "texm3x3pad" - _or_ sid_TEXM3X3TEX, "texm3x3tex" - _or_ sid_TEXM3X3SPEC, "texm3x3spec" - _or_ sid_TEXM3X3VSPEC, "texm3x3vspec" - _or_ sid_TEXREG2RGB, "texreg2rgb" - _or_ sid_TEXREG2AR, "texreg2ar" - _or_ sid_TEXREG2GB, "texreg2gb" - _end_ - - - _rule_ sid_TEXSWIZZLE, "" - - _is_ sid_STQDQ, "_dw.xyw" - _or_ sid_STQDQ, "_dw" - _or_ sid_STQDQ, "_da.rga" - _or_ sid_STQDQ, "_da" - _or_ sid_STRDR, "_dz.xyz" - _or_ sid_STRDR, "_dz" - _or_ sid_STRDR, "_db.rgb" - _or_ sid_STRDR, "_db" - _or_ sid_STR, ".xyz" - _or_ sid_STR, ".rgb" - _or_ sid_STQ, ".xyw" - _or_ sid_STQ, ".rga" - _end_ - - _rule_ sid_TEXMASK, "" - - _is_ sid_RGB, ".rgb" - _or_ sid_RGB, ".xyz" - _or_ sid_RG, ".rg" - _or_ sid_RG, ".xy" - _end_ - - _rule_ sid_SEPERATOR, "" - - _is_ sid_COMMA, "," - _end_ - - _rule_ sid_REG_PS1_4, "" - - _is_ sid_R0, "r0" - _or_ sid_R1, "r1" - _or_ sid_R2, "r2" - _or_ sid_R3, "r3" - _or_ sid_R4, "r4" - _or_ sid_R5, "r5" - _end_ - - _rule_ sid_TEX_PS1_4, "" - - _is_ sid_T0, "t0" - _or_ sid_T1, "t1" - _or_ sid_T2, "t2" - _or_ sid_T3, "t3" - _or_ sid_T4, "t4" - _or_ sid_T5, "t5" - _end_ - - _rule_ sid_REG_PS1_1_3, "" - - _is_ sid_1R0, "r0" - _or_ sid_1R1, "r1" - _end_ - - _rule_ sid_TEX_PS1_1_3, "" - - _is_ sid_1T0, "t0" - _or_ sid_1T1, "t1" - _or_ sid_1T2, "t2" - _or_ sid_1T3, "t3" - _end_ - - _rule_ sid_COLOR, "" - - _is_ sid_V0, "v0" - _or_ sid_V1, "v1" - _end_ - - - _rule_ sid_TEMPREG, "" - - _is_ sid_REG_PS1_4 _nt_ - _or_ sid_REG_PS1_1_3 _nt_ - _or_ sid_TEX_PS1_1_3 _nt_ - _end_ - - _rule_ sid_DSTMODSAT, "" - - _optional_ sid_DSTMOD _nt_ - _optional_ sid_DSTSAT _nt_ - _end_ - - _rule_ sid_UNARYOP, "" - - _is_ sid_MOV, "mov" - _end_ - - _rule_ sid_BINARYOP, "" - - _is_ sid_ADD, "add" - _or_ sid_MUL, "mul" - _or_ sid_SUB, "sub" - _or_ sid_DP3, "dp3" - _or_ sid_DP4, "dp4" - _or_ sid_BEM, "bem" - _end_ - - _rule_ sid_TERNARYOP, "" - - _is_ sid_MAD, "mad" - _or_ sid_LRP, "lrp" - _or_ sid_CND, "cnd" - _or_ sid_CMP, "cmp" - _end_ - - _rule_ sid_DSTMASK, "" - - _is_ sid_RGBA, ".rgba" - _or_ sid_RGBA, ".xyzw" - _or_ sid_RGB, ".rgb" - _or_ sid_RGB, ".xyz" - _or_ sid_RGA, ".xyw" - _or_ sid_RGA, ".rga" - _or_ sid_RBA, ".rba" - _or_ sid_RBA, ".xzw" - _or_ sid_GBA, ".gba" - _or_ sid_GBA, ".yzw" - _or_ sid_RG, ".rg" - _or_ sid_RG, ".xy" - _or_ sid_RB, ".xz" - _or_ sid_RB, ".rb" - _or_ sid_RA, ".xw" - _or_ sid_RA, ".ra" - _or_ sid_GB, ".gb" - _or_ sid_GB, ".yz" - _or_ sid_GA, ".yw" - _or_ sid_GA, ".ga" - _or_ sid_BA, ".zw" - _or_ sid_BA, ".ba" - _or_ sid_R, ".r" - _or_ sid_R, ".x" - _or_ sid_G, ".g" - _or_ sid_G, ".y" - _or_ sid_B, ".b" - _or_ sid_B, ".z" - _or_ sid_A, ".a" - _or_ sid_A, ".w" - _end_ - - _rule_ sid_SRCREP, "" - - _is_ sid_RRRR, ".r" - _or_ sid_RRRR, ".x" - _or_ sid_GGGG, ".g" - _or_ sid_GGGG, ".y" - _or_ sid_BBBB, ".b" - _or_ sid_BBBB, ".z" - _or_ sid_AAAA, ".a" - _or_ sid_AAAA, ".w" - _end_ - - _rule_ sid_PRESRCMOD, "" - - _is_ sid_INVERT, "1-" - _or_ sid_INVERT, "1 -" - _or_ sid_NEGATE, "-" - _end_ - - _rule_ sid_POSTSRCMOD, "" - - _is_ sid_BX2, "_bx2" - _or_ sid_X2, "_x2" - _or_ sid_BIAS, "_bias" - _end_ - - _rule_ sid_DSTMOD, "" - - _is_ sid_X2, "_x2" - _or_ sid_X4, "_x4" - _or_ sid_D2, "_d2" - _or_ sid_X8, "_x8" - _or_ sid_D4, "_d4" - _or_ sid_D8, "_d8" - _end_ - - _rule_ sid_DSTSAT, "" - - _is_ sid_SAT, "_sat" - _end_ - - _rule_ sid_COISSUE, "" - - _optional_ sid_PLUS, "+" - _end_ - -}; - -//***************************** MACROs for PS1_1 , PS1_2, PS1_3 CISC instructions ************************************** - -// macro to make the macro text data easier to read -#define _token_ ,0,0},{ -#define _token_end_ ,0,0} -// macro token expansion for ps_1_2 instruction: texreg2ar -PS_1_4::TokenInst PS_1_4::texreg2ar[] = { - // mov r(x).r, r(y).a - { sid_UNARYOP, sid_MOV - _token_ sid_REG_PS1_4, sid_R1 - _token_ sid_DSTMASK, sid_R - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R0 - _token_ sid_SRCREP, sid_AAAA - - // mov r(x).g, r(y).r - _token_ sid_UNARYOP, sid_MOV - _token_ sid_REG_PS1_4, sid_R1 - _token_ sid_DSTMASK, sid_G - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R0 - _token_ sid_SRCREP, sid_RRRR - - // texld r(x), r(x) - _token_ sid_TEXOP_PS1_4, sid_TEXLD - _token_ sid_REG_PS1_4, sid_R1 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R1 - _token_end_ -}; - -PS_1_4::RegModOffset PS_1_4::texreg2xx_RegMods[] = { - {1, R_BASE, 0}, - {7, R_BASE, 0}, - {13, R_BASE, 0}, - {15, R_BASE, 0}, - {4, R_BASE, 1}, - {10, R_BASE, 1}, - -}; - -PS_1_4::MacroRegModify PS_1_4::texreg2ar_MacroMods = { - texreg2ar, ARRAYSIZE(texreg2ar), - texreg2xx_RegMods, ARRAYSIZE(texreg2xx_RegMods) -}; - -// macro token expansion for ps_1_2 instruction: texreg2gb -PS_1_4::TokenInst PS_1_4::texreg2gb[] = { - // mov r(x).r, r(y).g - { sid_UNARYOP, sid_MOV - _token_ sid_REG_PS1_4, sid_R1 - _token_ sid_DSTMASK, sid_R - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R0 - _token_ sid_SRCREP, sid_GGGG - - // mov r(x).g, r(y).b - _token_ sid_UNARYOP, sid_MOV - _token_ sid_REG_PS1_4, sid_R1 - _token_ sid_DSTMASK, sid_G - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R0 - _token_ sid_SRCREP, sid_BBBB - - // texld r(x), r(x) - _token_ sid_TEXOP_PS1_4, sid_TEXLD - _token_ sid_REG_PS1_4, sid_R1 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R1 - _token_end_ -}; - -PS_1_4::MacroRegModify PS_1_4::texreg2gb_MacroMods = { - texreg2gb, ARRAYSIZE(texreg2gb), - texreg2xx_RegMods, ARRAYSIZE(texreg2xx_RegMods) -}; - - -// macro token expansion for ps_1_1 instruction: texdp3 -PS_1_4::TokenInst PS_1_4::texdp3[] = { - // texcoord t(x) - { sid_TEXOP_PS1_1_3, sid_TEXCOORD - _token_ sid_TEX_PS1_1_3, sid_1T1 - - // dp3 r(x), r(x), r(y) - _token_ sid_BINARYOP, sid_DP3 - _token_ sid_REG_PS1_4, sid_R1 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R1 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R0 - _token_end_ -}; - - -PS_1_4::RegModOffset PS_1_4::texdp3_RegMods[] = { - {1, T_BASE, 0}, - {3, R_BASE, 0}, - {5, R_BASE, 0}, - {7, R_BASE, 1}, - -}; - - -PS_1_4::MacroRegModify PS_1_4::texdp3_MacroMods = { - texdp3, ARRAYSIZE(texdp3), - texdp3_RegMods, ARRAYSIZE(texdp3_RegMods) -}; - - -// macro token expansion for ps_1_1 instruction: texdp3tex -PS_1_4::TokenInst PS_1_4::texdp3tex[] = { - // texcoord t(x) - { sid_TEXOP_PS1_1_3, sid_TEXCOORD - _token_ sid_TEX_PS1_1_3, sid_1T1 - - // dp3 r1, r(x), r(y) - _token_ sid_BINARYOP, sid_DP3 - _token_ sid_REG_PS1_4, sid_R1 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R1 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R0 - - // texld r(x), r(x) - _token_ sid_TEXOP_PS1_4, sid_TEXLD - _token_ sid_REG_PS1_4, sid_R1 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R1 - _token_end_ -}; - - -PS_1_4::RegModOffset PS_1_4::texdp3tex_RegMods[] = { - {1, T_BASE, 0}, - {3, R_BASE, 0}, - {5, R_BASE, 0}, - {7, R_BASE, 1}, - {9, R_BASE, 1}, - {11, R_BASE, 1}, - -}; - - -PS_1_4::MacroRegModify PS_1_4::texdp3tex_MacroMods = { - texdp3tex, ARRAYSIZE(texdp3tex), - texdp3tex_RegMods, ARRAYSIZE(texdp3tex_RegMods) -}; - - -// macro token expansion for ps_1_1 instruction: texm3x2pad -PS_1_4::TokenInst PS_1_4::texm3x2pad[] = { - // texcoord t(x) - { sid_TEXOP_PS1_1_3, sid_TEXCOORD - _token_ sid_TEX_PS1_1_3, sid_1T0 - - // dp3 r4.r, r(x), r(y) - _token_ sid_BINARYOP, sid_DP3 - _token_ sid_REG_PS1_4, sid_R4 - _token_ sid_DSTMASK, sid_R - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R1 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R0 - _token_end_ - -}; - - -PS_1_4::RegModOffset PS_1_4::texm3xxpad_RegMods[] = { - {1, T_BASE, 0}, - {6, R_BASE, 0}, - {8, R_BASE, 1}, -}; - - -PS_1_4::MacroRegModify PS_1_4::texm3x2pad_MacroMods = { - texm3x2pad, ARRAYSIZE(texm3x2pad), - texm3xxpad_RegMods, ARRAYSIZE(texm3xxpad_RegMods) -}; - - -// macro token expansion for ps_1_1 instruction: texm3x2tex -PS_1_4::TokenInst PS_1_4::texm3x2tex[] = { - // texcoord t(x) - { sid_TEXOP_PS1_1_3, sid_TEXCOORD - _token_ sid_TEX_PS1_1_3, sid_1T1 - - // dp3 r4.g, r(x), r(y) - _token_ sid_BINARYOP, sid_DP3 - _token_ sid_REG_PS1_4, sid_R4 - _token_ sid_DSTMASK, sid_G - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R1 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R0 - - // texld r(x), r4 - _token_ sid_TEXOP_PS1_4, sid_TEXLD - _token_ sid_REG_PS1_4, sid_R1 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R4 - _token_end_ - -}; - -PS_1_4::RegModOffset PS_1_4::texm3xxtex_RegMods[] = { - {1, T_BASE, 0}, - {6, R_BASE, 0}, - {8, R_BASE, 1}, - {10, R_BASE, 0} -}; - -PS_1_4::MacroRegModify PS_1_4::texm3x2tex_MacroMods = { - texm3x2tex, ARRAYSIZE(texm3x2tex), - texm3xxtex_RegMods, ARRAYSIZE(texm3xxtex_RegMods) -}; - -// macro token expansion for ps_1_1 instruction: texm3x3tex -PS_1_4::TokenInst PS_1_4::texm3x3pad[] = { - // texcoord t(x) - { sid_TEXOP_PS1_1_3, sid_TEXCOORD - _token_ sid_TEX_PS1_1_3, sid_1T0 - - // dp3 r4.b, r(x), r(y) - _token_ sid_BINARYOP, sid_DP3 - _token_ sid_REG_PS1_4, sid_R4 - _token_ sid_DSTMASK, sid_B - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R1 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R0 - _token_end_ - -}; - - -PS_1_4::MacroRegModify PS_1_4::texm3x3pad_MacroMods = { - texm3x3pad, ARRAYSIZE(texm3x3pad), - texm3xxpad_RegMods, ARRAYSIZE(texm3xxpad_RegMods) -}; - - -// macro token expansion for ps_1_1 instruction: texm3x3pad -PS_1_4::TokenInst PS_1_4::texm3x3tex[] = { - // texcoord t(x) - { sid_TEXOP_PS1_1_3, sid_TEXCOORD - _token_ sid_TEX_PS1_1_3, sid_1T1 - - // dp3 r4.b, r(x), r(y) - _token_ sid_BINARYOP, sid_DP3 - _token_ sid_REG_PS1_4, sid_R4 - _token_ sid_DSTMASK, sid_B - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R1 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R0 - - // texld r1, r4 - _token_ sid_TEXOP_PS1_4, sid_TEXLD - _token_ sid_REG_PS1_4, sid_R1 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R4 - _token_end_ -}; - - - - - - -PS_1_4::MacroRegModify PS_1_4::texm3x3tex_MacroMods = { - texm3x3tex, ARRAYSIZE(texm3x3tex), - texm3xxtex_RegMods, ARRAYSIZE(texm3xxtex_RegMods) -}; - - -// macro token expansion for ps_1_1 instruction: texm3x3spec -PS_1_4::TokenInst PS_1_4::texm3x3spec[] = { - // texcoord t(x) - { sid_TEXOP_PS1_1_3, sid_TEXCOORD - _token_ sid_TEX_PS1_1_3, sid_1T3 - - // dp3 r4.b, r3, r(x) - _token_ sid_BINARYOP, sid_DP3 - _token_ sid_REG_PS1_4, sid_R4 - _token_ sid_DSTMASK, sid_B - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R3 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R0 - - // dp3_x2 r3, r4, c(x) - _token_ sid_BINARYOP, sid_DP3 - _token_ sid_DSTMOD, sid_X2 - _token_ sid_REG_PS1_4, sid_R3 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R4 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_CONSTANT, sid_C0 - - // mul r3, r3, c(x) - _token_ sid_UNARYOP, sid_MUL - _token_ sid_REG_PS1_4, sid_R3 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R3 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_CONSTANT, sid_C0 - - // dp3 r2, r4, r4 - _token_ sid_BINARYOP, sid_DP3 - _token_ sid_REG_PS1_4, sid_R2 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R4 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R4 - - // mad r4.rgb, 1-c(x), r2, r3 - _token_ sid_TERNARYOP, sid_MAD - _token_ sid_REG_PS1_4, sid_R4 - _token_ sid_DSTMASK, sid_RGB - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_PRESRCMOD, sid_INVERT - _token_ sid_CONSTANT, sid_C0 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R2 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R3 - - // + mov r4.a, r2.r - _token_ sid_UNARYOP, sid_MOV - _token_ sid_REG_PS1_4, sid_R4 - _token_ sid_DSTMASK, sid_A - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R2 - _token_ sid_SRCREP, sid_RRRR - - // texld r3, r4.xyz_dz - _token_ sid_TEXOP_PS1_4, sid_TEXLD - _token_ sid_REG_PS1_4, sid_R3 - _token_ sid_SEPERATOR, sid_COMMA - _token_ sid_REG_PS1_4, sid_R4 - _token_ sid_TEXSWIZZLE, sid_STRDR - _token_end_ - -}; - -PS_1_4::RegModOffset PS_1_4::texm3x3spec_RegMods[] = { - {8, R_BASE, 1}, - {15, R_BASE, 2}, - {21, C_BASE, 2}, - {33, C_BASE, 2}, - -}; - -PS_1_4::MacroRegModify PS_1_4::texm3x3spec_MacroMods = { - texm3x3spec, ARRAYSIZE(texm3x3spec), - texm3x3spec_RegMods, ARRAYSIZE(texm3x3spec_RegMods) -}; - - -/* ********************* END OF CLASS STATIC DATA ********************************* */ - -PS_1_4::PS_1_4() -{ - // allocate enough room for a large pixel shader - mPhase1TEX_mi.reserve(50); - mPhase2TEX_mi.reserve(30); - mPhase1ALU_mi.reserve(100); - mPhase2ALU_mi.reserve(100); - - - mSymbolTypeLib = PS_1_4_SymbolTypeLib; - mSymbolTypeLibCnt = ARRAYSIZE(PS_1_4_SymbolTypeLib); - mRootRulePath = PS_1_x_RulePath; - mRulePathLibCnt = ARRAYSIZE(PS_1_x_RulePath); - // tell compiler what the symbol id is for a numeric value - mValueID = sid_VALUE; - // The type library must have text definitions initialized - // before compiler is invoked - - // only need to initialize the rule database once - if(LibInitialized == false) { - InitSymbolTypeLib(); - LibInitialized = true; - } - - // set initial context to recognize PS base instructions - mActiveContexts = ckp_PS_BASE; - -} - - -bool PS_1_4::bindMachineInstInPassToFragmentShader(const MachineInstContainer & PassMachineInstructions) -{ - size_t instIDX = 0; - size_t instCount = PassMachineInstructions.size(); - bool error = false; - - while ((instIDX < instCount) && !error) { - switch(PassMachineInstructions[instIDX]) { - case mi_COLOROP1: - if((instIDX+7) < instCount) - glColorFragmentOp1ATI(PassMachineInstructions[instIDX+1], // op - PassMachineInstructions[instIDX+2], // dst - PassMachineInstructions[instIDX+3], // dstMask - PassMachineInstructions[instIDX+4], // dstMod - PassMachineInstructions[instIDX+5], // arg1 - PassMachineInstructions[instIDX+6], // arg1Rep - PassMachineInstructions[instIDX+7]);// arg1Mod - instIDX += 8; - break; - - case mi_COLOROP2: - if((instIDX+10) < instCount) - glColorFragmentOp2ATI(PassMachineInstructions[instIDX+1], // op - PassMachineInstructions[instIDX+2], // dst - PassMachineInstructions[instIDX+3], // dstMask - PassMachineInstructions[instIDX+4], // dstMod - PassMachineInstructions[instIDX+5], // arg1 - PassMachineInstructions[instIDX+6], // arg1Rep - PassMachineInstructions[instIDX+7], // arg1Mod - PassMachineInstructions[instIDX+8], // arg2 - PassMachineInstructions[instIDX+9], // arg2Rep - PassMachineInstructions[instIDX+10]);// arg2Mod - instIDX += 11; - break; - - case mi_COLOROP3: - if((instIDX+13) < instCount) - glColorFragmentOp3ATI(PassMachineInstructions[instIDX+1], // op - PassMachineInstructions[instIDX+2], // dst - PassMachineInstructions[instIDX+3], // dstMask - PassMachineInstructions[instIDX+4], // dstMod - PassMachineInstructions[instIDX+5], // arg1 - PassMachineInstructions[instIDX+6], // arg1Rep - PassMachineInstructions[instIDX+7], // arg1Mod - PassMachineInstructions[instIDX+8], // arg2 - PassMachineInstructions[instIDX+9], // arg2Rep - PassMachineInstructions[instIDX+10], // arg2Mod - PassMachineInstructions[instIDX+11], // arg2 - PassMachineInstructions[instIDX+12], // arg2Rep - PassMachineInstructions[instIDX+13]);// arg2Mod - instIDX += 14; - break; - - case mi_ALPHAOP1: - if((instIDX+6) < instCount) - glAlphaFragmentOp1ATI(PassMachineInstructions[instIDX+1], // op - PassMachineInstructions[instIDX+2], // dst - PassMachineInstructions[instIDX+3], // dstMod - PassMachineInstructions[instIDX+4], // arg1 - PassMachineInstructions[instIDX+5], // arg1Rep - PassMachineInstructions[instIDX+6]); // arg1Mod - instIDX += 7; - break; - - case mi_ALPHAOP2: - if((instIDX+9) < instCount) - glAlphaFragmentOp2ATI(PassMachineInstructions[instIDX+1], // op - PassMachineInstructions[instIDX+2], // dst - PassMachineInstructions[instIDX+3], // dstMod - PassMachineInstructions[instIDX+4], // arg1 - PassMachineInstructions[instIDX+5], // arg1Rep - PassMachineInstructions[instIDX+6], // arg1Mod - PassMachineInstructions[instIDX+7], // arg2 - PassMachineInstructions[instIDX+8], // arg2Rep - PassMachineInstructions[instIDX+9]); // arg2Mod - instIDX += 10; - break; - - case mi_ALPHAOP3: - if((instIDX+12) < instCount) - glAlphaFragmentOp3ATI(PassMachineInstructions[instIDX+1], // op - PassMachineInstructions[instIDX+2], // dst - PassMachineInstructions[instIDX+3], // dstMod - PassMachineInstructions[instIDX+4], // arg1 - PassMachineInstructions[instIDX+5], // arg1Rep - PassMachineInstructions[instIDX+6], // arg1Mod - PassMachineInstructions[instIDX+7], // arg2 - PassMachineInstructions[instIDX+8], // arg2Rep - PassMachineInstructions[instIDX+9], // arg2Mod - PassMachineInstructions[instIDX+10], // arg2 - PassMachineInstructions[instIDX+11], // arg2Rep - PassMachineInstructions[instIDX+12]); // arg2Mod - instIDX += 13; - break; - - case mi_SETCONSTANTS: - if((instIDX+2) < instCount) - glSetFragmentShaderConstantATI(PassMachineInstructions[instIDX+1], // dst - &mConstants[PassMachineInstructions[instIDX+2]]); - instIDX += 3; - break; - - case mi_PASSTEXCOORD: - if((instIDX+3) < instCount) - glPassTexCoordATI(PassMachineInstructions[instIDX+1], // dst - PassMachineInstructions[instIDX+2], // coord - PassMachineInstructions[instIDX+3]); // swizzle - instIDX += 4; - break; - - case mi_SAMPLEMAP: - if((instIDX+3) < instCount) - glSampleMapATI(PassMachineInstructions[instIDX+1], // dst - PassMachineInstructions[instIDX+2], // interp - PassMachineInstructions[instIDX+3]); // swizzle - instIDX += 4; - break; - - default: - instIDX = instCount; - // should generate an error since an unknown instruction was found - // instead for now the bind process is terminated and the fragment program may still function - // but its output may not be what was programmed - - } // end of switch - - error = (glGetError() != GL_NO_ERROR); - }// end of while - - return !error; - -} - - -size_t PS_1_4::getMachineInst( size_t Idx) -{ - if (Idx < mPhase1TEX_mi.size()) { - return mPhase1TEX_mi[Idx]; - } - else { - Idx -= mPhase1TEX_mi.size(); - if (Idx < mPhase1ALU_mi.size()) { - return mPhase1ALU_mi[Idx]; - } - else { - Idx -= mPhase1ALU_mi.size(); - if (Idx < mPhase2TEX_mi.size()) { - return mPhase2TEX_mi[Idx]; - } - else { - Idx -= mPhase2TEX_mi.size(); - if (Idx < mPhase2ALU_mi.size()) { - return mPhase2ALU_mi[Idx]; - } - - } - - } - - } - - return 0; - -} - - -void PS_1_4::addMachineInst(const PhaseType phase, const uint inst) -{ - switch(phase) { - - case ptPHASE1TEX: - mPhase1TEX_mi.push_back(inst); - break; - - case ptPHASE1ALU: - mPhase1ALU_mi.push_back(inst); - break; - - case ptPHASE2TEX: - mPhase2TEX_mi.push_back(inst); - - break; - - case ptPHASE2ALU: - mPhase2ALU_mi.push_back(inst); - break; - - - } // end switch(phase) - -} - -size_t PS_1_4::getMachineInstCount() -{ - - return (mPhase1TEX_mi.size() + mPhase1ALU_mi.size() + mPhase2TEX_mi.size() + mPhase2ALU_mi.size()); -} - - -bool PS_1_4::bindAllMachineInstToFragmentShader() -{ - bool passed; - - // there are 4 machine instruction ques to pass to the ATI fragment shader - passed = bindMachineInstInPassToFragmentShader(mPhase1TEX_mi); - passed &= bindMachineInstInPassToFragmentShader(mPhase1ALU_mi); - passed &= bindMachineInstInPassToFragmentShader(mPhase2TEX_mi); - passed &= bindMachineInstInPassToFragmentShader(mPhase2ALU_mi); - return passed; - -} - - -bool PS_1_4::expandMacro(const MacroRegModify & MacroMod) -{ - - RegModOffset * regmod; - - // set source and destination registers in macro expansion - for (uint i = 0; i < MacroMod.RegModSize; i++) { - regmod = &MacroMod.RegMods[i]; - MacroMod.Macro[regmod->MacroOffset].mID = regmod->RegisterBase + mOpParrams[regmod->OpParramsIndex].Arg; - - } - - // turn macro support on so that ps.1.4 ALU instructions get put in phase 1 alu instruction sequence container - mMacroOn = true; - // pass macro tokens on to be turned into machine instructions - // expand macro to ps.1.4 by doing recursive call to doPass2 - bool passed = Pass2scan(MacroMod.Macro, MacroMod.MacroSize); - mMacroOn = false; - - return passed; -} - - -bool PS_1_4::BuildMachineInst() -{ - - // check the states to see if a machine instruction can be assembled - - // assume all arguments have been set up - bool passed = false; - - - - passed = true; // assume everything will go okay until proven otherwise - - // start with machine NOP instruction - // this is used after the switch to see if an instruction was set up - // determine which MachineInstID is required based on the op instruction - mOpType = mi_NOP; - - switch(mOpInst) { - // ALU operations - case sid_ADD: - case sid_SUB: - case sid_MUL: - case sid_MAD: - case sid_LRP: - case sid_MOV: - case sid_CMP: - case sid_CND: - case sid_DP2ADD: - case sid_DP3: - case sid_DP4: - mOpType = (MachineInstID)(mi_COLOROP1 + mArgCnt - 1); - - // if context is ps.1.x and Macro not on or a phase marker was found then put all ALU ops in phase 2 ALU container - if (((mActiveContexts & ckp_PS_1_1) && !mMacroOn) || mPhaseMarkerFound) mInstructionPhase = ptPHASE2ALU; - else mInstructionPhase = ptPHASE1ALU; - // check for alpha op in destination register which is OpParrams[0] - // if no Mask for destination then make it .rgba - if(mOpParrams[0].MaskRep == 0) mOpParrams[0].MaskRep = - GL_RED_BIT_ATI | GL_GREEN_BIT_ATI | GL_BLUE_BIT_ATI | ALPHA_BIT; - if (mOpParrams[0].MaskRep & ALPHA_BIT) { - mDo_Alpha = true; - mOpParrams[0].MaskRep -= ALPHA_BIT; - if(mOpParrams[0].MaskRep == 0) mOpType = mi_NOP; // only do alpha op - } - break; - - case sid_TEXCRD: - mOpType = mi_PASSTEXCOORD; - if (mPhaseMarkerFound) mInstructionPhase = ptPHASE2TEX; - else mInstructionPhase = ptPHASE1TEX; - break; - - case sid_TEXLD: - mOpType = mi_SAMPLEMAP; - if (mPhaseMarkerFound) mInstructionPhase = ptPHASE2TEX; - else mInstructionPhase = ptPHASE1TEX; - break; - - case sid_TEX: // PS_1_1 emulation - mOpType = mi_TEX; - mInstructionPhase = ptPHASE1TEX; - break; - - case sid_TEXCOORD: // PS_1_1 emulation - mOpType = mi_TEXCOORD; - mInstructionPhase = ptPHASE1TEX; - break; - - case sid_TEXREG2AR: - passed = expandMacro(texreg2ar_MacroMods); - break; - - case sid_TEXREG2GB: - passed = expandMacro(texreg2gb_MacroMods); - break; - - case sid_TEXDP3: - passed = expandMacro(texdp3_MacroMods); - break; - - case sid_TEXDP3TEX: - passed = expandMacro(texdp3tex_MacroMods); - break; - - case sid_TEXM3X2PAD: - passed = expandMacro(texm3x2pad_MacroMods); - break; - - case sid_TEXM3X2TEX: - passed = expandMacro(texm3x2tex_MacroMods); - break; - - case sid_TEXM3X3PAD: - // only 2 texm3x3pad instructions allowed - // use count to modify macro to select which mask to use - if(mTexm3x3padCount<2) { - texm3x3pad[4].mID = sid_R + mTexm3x3padCount; - mTexm3x3padCount++; - passed = expandMacro(texm3x3pad_MacroMods); - - } - else passed = false; - - break; - - case sid_TEXM3X3TEX: - passed = expandMacro(texm3x3tex_MacroMods); - break; - - case sid_DEF: - mOpType = mi_SETCONSTANTS; - mInstructionPhase = ptPHASE1TEX; - break; - - case sid_PHASE: // PS_1_4 only - mPhaseMarkerFound = true; - break; - - } // end of switch - - if(passed) passed = expandMachineInstruction(); - - return passed; -} - - -bool PS_1_4::expandMachineInstruction() -{ - // now push instructions onto MachineInstructions container - // assume that an instruction will be expanded - bool passed = true; - - if (mOpType != mi_NOP) { - - // a machine instruction will be built - // this is currently the last one being built so keep track of it - if (mInstructionPhase == ptPHASE2ALU) { - mSecondLastInstructionPos = mLastInstructionPos; - mLastInstructionPos = mPhase2ALU_mi.size(); - } - - - switch (mOpType) { - case mi_COLOROP1: - case mi_COLOROP2: - case mi_COLOROP3: - { - addMachineInst(mInstructionPhase, mOpType); - addMachineInst(mInstructionPhase, mSymbolTypeLib[mOpInst].mPass2Data); - // send all parameters to machine inst container - for(int i=0; i<=mArgCnt; i++) { - addMachineInst(mInstructionPhase, mOpParrams[i].Arg); - addMachineInst(mInstructionPhase, mOpParrams[i].MaskRep); - addMachineInst(mInstructionPhase, mOpParrams[i].Mod); - // check if source register read is valid in this phase - passed &= isRegisterReadValid(mInstructionPhase, i); - } - - // record which registers were written to and in which phase - // mOpParrams[0].Arg is always the destination register r0 -> r5 - updateRegisterWriteState(mInstructionPhase); - - } - break; - - case mi_SETCONSTANTS: - addMachineInst(mInstructionPhase, mOpType); - addMachineInst(mInstructionPhase, mOpParrams[0].Arg); // dst - addMachineInst(mInstructionPhase, mConstantsPos); // index into constants array - break; - - case mi_PASSTEXCOORD: - case mi_SAMPLEMAP: - // if source is a temp register than place instruction in phase 2 Texture ops - if ((mOpParrams[1].Arg >= GL_REG_0_ATI) && (mOpParrams[1].Arg <= GL_REG_5_ATI)) { - mInstructionPhase = ptPHASE2TEX; - } - - addMachineInst(mInstructionPhase, mOpType); - addMachineInst(mInstructionPhase, mOpParrams[0].Arg); // dst - addMachineInst(mInstructionPhase, mOpParrams[1].Arg); // coord - addMachineInst(mInstructionPhase, mOpParrams[1].MaskRep + GL_SWIZZLE_STR_ATI); // swizzle - // record which registers were written to and in which phase - // mOpParrams[0].Arg is always the destination register r0 -> r5 - updateRegisterWriteState(mInstructionPhase); - break; - - case mi_TEX: // PS_1_1 emulation - turn CISC into RISC - phase 1 - addMachineInst(mInstructionPhase, mi_SAMPLEMAP); - addMachineInst(mInstructionPhase, mOpParrams[0].Arg); // dst - // tex tx becomes texld rx, tx with x: 0 - 3 - addMachineInst(mInstructionPhase, mOpParrams[0].Arg - GL_REG_0_ATI + GL_TEXTURE0_ARB); // interp - // default to str which fills rgb of destination register - addMachineInst(mInstructionPhase, GL_SWIZZLE_STR_ATI); // swizzle - // record which registers were written to and in which phase - // mOpParrams[0].Arg is always the destination register r0 -> r5 - updateRegisterWriteState(mInstructionPhase); - break; - - case mi_TEXCOORD: // PS_1_1 emulation - turn CISC into RISC - phase 1 - addMachineInst(mInstructionPhase, mi_PASSTEXCOORD); - addMachineInst(mInstructionPhase, mOpParrams[0].Arg); // dst - // texcoord tx becomes texcrd rx, tx with x: 0 - 3 - addMachineInst(mInstructionPhase, mOpParrams[0].Arg - GL_REG_0_ATI + GL_TEXTURE0_ARB); // interp - // default to str which fills rgb of destination register - addMachineInst(mInstructionPhase, GL_SWIZZLE_STR_ATI); // swizzle - // record which registers were written to and in which phase - // mOpParrams[0].Arg is always the destination register r0 -> r5 - updateRegisterWriteState(mInstructionPhase); - break; - - case mi_ALPHAOP1: - case mi_ALPHAOP2: - case mi_ALPHAOP3: - case mi_TEXREG2RGB: - case mi_NOP: - break; - - - } // end of switch (mOpType) - } // end of if (mOpType != mi_NOP) - - if(mDo_Alpha) { - // process alpha channel - // - // a scaler machine instruction will be built - // this is currently the last one being built so keep track of it - if (mInstructionPhase == ptPHASE2ALU) { - mSecondLastInstructionPos = mLastInstructionPos; - mLastInstructionPos = mPhase2ALU_mi.size(); - } - - MachineInstID alphaoptype = (MachineInstID)(mi_ALPHAOP1 + mArgCnt - 1); - addMachineInst(mInstructionPhase, alphaoptype); - addMachineInst(mInstructionPhase, mSymbolTypeLib[mOpInst].mPass2Data); - // put all parameters in instruction que - for(int i=0; i<=mArgCnt; i++) { - addMachineInst(mInstructionPhase, mOpParrams[i].Arg); - // destination parameter has no mask since it is the alpha channel - // don't push mask for parrameter 0 (dst) - if(i>0) addMachineInst(mInstructionPhase, mOpParrams[i].MaskRep); - addMachineInst(mInstructionPhase, mOpParrams[i].Mod); - // check if source register read is valid in this phase - passed &= isRegisterReadValid(mInstructionPhase, i); - } - - updateRegisterWriteState(mInstructionPhase); - } - - // instruction passed on to machine instruction so clear the pipe - clearMachineInstState(); - - return passed; - -} - - -void PS_1_4::updateRegisterWriteState(const PhaseType phase) -{ - int reg_offset = mOpParrams[0].Arg - GL_REG_0_ATI; - - switch(phase) { - - case ptPHASE1TEX: - case ptPHASE1ALU: - Phase_RegisterUsage[reg_offset].Phase1Write = true; - break; - - case ptPHASE2TEX: - case ptPHASE2ALU: - Phase_RegisterUsage[reg_offset].Phase2Write = true; - break; - - } // end switch(phase) - -} - - -bool PS_1_4::isRegisterReadValid(const PhaseType phase, const int param) -{ - bool passed = true; // assume everything will go alright - // if in phase 2 ALU and argument is a source - if((phase == ptPHASE2ALU) && (param>0)) { - // is source argument a temp register r0 - r5? - if((mOpParrams[param].Arg >= GL_REG_0_ATI) && (mOpParrams[param].Arg <= GL_REG_5_ATI)) { - int reg_offset = mOpParrams[param].Arg - GL_REG_0_ATI; - // if register was not written to in phase 2 but was in phase 1 - if((Phase_RegisterUsage[reg_offset].Phase2Write == false) && Phase_RegisterUsage[reg_offset].Phase1Write) { - // only perform register pass if there are ALU instructions in phase 1 - - if(mPhase1ALU_mi.size() > 0) { - // build machine instructions for passing a register from phase 1 to phase 2 - // NB: only rgb components of register will get passed - - addMachineInst(ptPHASE2TEX, mi_PASSTEXCOORD); - addMachineInst(ptPHASE2TEX, mOpParrams[param].Arg); // dst - addMachineInst(ptPHASE2TEX, mOpParrams[param].Arg); // coord - addMachineInst(ptPHASE2TEX, GL_SWIZZLE_STR_ATI); // swizzle - // mark register as being written to - Phase_RegisterUsage[reg_offset].Phase2Write = true; - } - - } - // register can not be used because it has not been written to previously - else passed = false; - } - - } - - return passed; - -} - - -void PS_1_4::optimize() -{ - // perform some optimizations on ps.1.1 machine instructions - if (mActiveContexts & ckp_PS_1_1) { - // need to check last few instructions to make sure r0 is set - // ps.1.1 emulation uses r4 for r0 so last couple of instructions will probably require - // changine destination register back to r0 - if (mLastInstructionPos < mPhase2ALU_mi.size()) { - // first argument at mLastInstructionPos + 2 is destination register for all ps.1.1 ALU instructions - mPhase2ALU_mi[mLastInstructionPos + 2] = GL_REG_0_ATI; - // if was an alpha op only then modify second last instruction destination register - if ((mPhase2ALU_mi[mLastInstructionPos] == mi_ALPHAOP1) || - (mPhase2ALU_mi[mLastInstructionPos] == mi_ALPHAOP2) || - (mPhase2ALU_mi[mLastInstructionPos] == mi_ALPHAOP3) - - ) { - - mPhase2ALU_mi[mSecondLastInstructionPos + 2] = GL_REG_0_ATI; - } - - }// end if (mLastInstructionPos < mMachineInstructions.size()) - - }// end if (mActiveContexts & ckp_PS_1_1) - -} - - -void PS_1_4::clearMachineInstState() -{ - // set current Machine Instruction State to baseline - mOpType = mi_NOP; - mOpInst = sid_INVALID; - mDo_Alpha = false; - mArgCnt = 0; - - for(int i=0; imID; - } - else passed = false; - break; - - case sid_DSTMASK: - case sid_SRCREP: - case sid_TEXSWIZZLE: - // could be a dst mask or a arg replicator - // if dst mask and alpha included then make up a alpha instruction: maybe best to wait until instruction args completed - mOpParrams[mArgCnt].MaskRep = cursymboldef->mPass2Data; - break; - - case sid_DSTMOD: - case sid_DSTSAT: - case sid_PRESRCMOD: - case sid_POSTSRCMOD: - mOpParrams[mArgCnt].Mod |= cursymboldef->mPass2Data; - break; - - - case sid_NUMVAL: - passed = setOpParram(cursymboldef); - // keep track of how many values are used - // update Constants array position - mConstantsPos++; - break; - - case sid_SEPERATOR: - mArgCnt++; - break; - } // end of switch - - if(!passed) break; - }// end of for: imPass2Data; - } - else success = false; - - return success; -} - - - - -// ********************************************************************************* -// this is where the tests are carried out to make sure the PS_1_4 compiler works - -#ifdef _DEBUG -// check the functionality of functions in PS_1_4: each test will print to the output file PASSED of FAILED -void PS_1_4::test() -{ - - - struct test1result{ - char character; - int line; - }; - - struct testfloatresult{ - char *teststr; - float fvalue; - int charsize; - }; - - char TestStr1[] = " \n\r //c \n\r// test\n\r \t c - \n\r , e"; - test1result test1results[] = { - {'c', 4}, - {'-', 4}, - {',', 5}, - {'e', 5} - }; - - testfloatresult testfloatresults[] = { - {"1 test", 1.0f, 1}, - {"2.3f test", 2.3f, 3}, - {"-0.5 test", -0.5f, 4}, - {" 23.6 test", 23.6f, 5}, - {" -0.021 test", -0.021f, 8}, - {"12 test", 12.0f, 2}, - {"3test", 3.0f, 1} - }; - - - - SymbolID test3result[] = { sid_MOV, sid_COMMA, sid_MUL, sid_ADD, sid_NEGATE, sid_T0 - }; - - #define PART2INST 17 - char TestStr3[] = "mov r0,c1"; - char TestSymbols[] = "mov"; - char passed[] = "PASSED\n"; - char failed[] = "***** FAILED *****\n"; - - int resultID = 0; - - // loop variable used in for loops - int i; - fp = fopen("ASMTests.txt", "wt"); - -// ************************************************************** - // first test: see if positionToNextSymbol can find a valid Symbol - fprintf(fp, "Testing: positionToNextSymbol\n"); - - mSource = TestStr1; - mCharPos = 0; - mCurrentLine = 1; - mEndOfSource = (int)strlen(mSource); - while (positionToNextSymbol()) { - fprintf(fp," character found: [%c] Line:%d : " , mSource[mCharPos], mCurrentLine); - if( (mSource[mCharPos] == test1results[resultID].character) && (mCurrentLine==test1results[resultID].line)) fprintf(fp, passed); - else fprintf(fp, failed); - resultID++; - mCharPos++; - } - fprintf(fp, "finished testing: positionToNextSymbol\n"); - - -// ************************************************************** - // Second Test - // did the type lib get initialized properly with a default name index - fprintf(fp, "\nTesting: getTypeDefText\n"); - const char* resultstr = getTypeDefText(sid_MOV); - fprintf(fp, " default name of mov is: [%s]: %s", resultstr, (strcmp("mov", resultstr)==0)?passed:failed); - fprintf(fp, "finished testing: getTypeDefText\n"); - -// ************************************************************** -// ************************************************************** - // fourth test - does isSymbol work correctly - fprintf(fp, "\nTesting: isSymbol\n"); - mSource = TestStr3; - mCharPos = 0; - fprintf(fp, " before: [%s]\n", mSource + mCharPos); - fprintf(fp, " symbol to find: [%s]\n", TestSymbols); - if(isSymbol(TestSymbols, resultID)) { - fprintf(fp, " after: [%s] : %s", mSource + resultID + 1, (mSource[resultID + 1] == 'r')? passed:failed); - } - else fprintf(fp, failed); - fprintf(fp," symbol size: %d\n", resultID); - fprintf(fp, "finished testing: isSymbol\n"); - -// ************************************************************** - fprintf(fp, "\nTesting: isFloatValue\n"); - float fvalue = 0; - int charsize = 0; - char teststrfloat1[] = "1 test"; - mCharPos = 0; - int testsize = ARRAYSIZE(testfloatresults); - for(i=0; i -#include -#include -#include - -static void* get_proc(const char *namez); - -#if defined(_WIN32) || defined(__CYGWIN__) -#ifndef _WINDOWS_ -#undef APIENTRY -#endif -#include -static HMODULE libGL; - -typedef void* (APIENTRYP PFNWGLGETPROCADDRESSPROC_PRIVATE)(const char*); -static PFNWGLGETPROCADDRESSPROC_PRIVATE gladGetProcAddressPtr; - -#ifdef _MSC_VER -#ifdef __has_include - #if __has_include() - #define HAVE_WINAPIFAMILY 1 - #endif -#elif _MSC_VER >= 1700 && !_USING_V110_SDK71_ - #define HAVE_WINAPIFAMILY 1 -#endif -#endif - -#ifdef HAVE_WINAPIFAMILY - #include - #if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) - #define IS_UWP 1 - #endif -#endif - -static -int open_gl(void) { -#ifndef IS_UWP - libGL = LoadLibraryW(L"opengl32.dll"); - if(libGL != NULL) { - void (* tmp)(void); - tmp = (void(*)(void)) GetProcAddress(libGL, "wglGetProcAddress"); - gladGetProcAddressPtr = (PFNWGLGETPROCADDRESSPROC_PRIVATE) tmp; - return gladGetProcAddressPtr != NULL; - } -#endif - - return 0; -} - -static -void close_gl(void) { - if(libGL != NULL) { - FreeLibrary((HMODULE) libGL); - libGL = NULL; - } -} -#else -#include -static void* libGL; - -#if !defined(__APPLE__) && !defined(__HAIKU__) -typedef void* (APIENTRYP PFNGLXGETPROCADDRESSPROC_PRIVATE)(const char*); -static PFNGLXGETPROCADDRESSPROC_PRIVATE gladGetProcAddressPtr; -#endif - -static -int open_gl(void) { -#ifdef __APPLE__ - static const char *NAMES[] = { - "../Frameworks/OpenGL.framework/OpenGL", - "/Library/Frameworks/OpenGL.framework/OpenGL", - "/System/Library/Frameworks/OpenGL.framework/OpenGL", - "/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL" - }; -#else - static const char *NAMES[] = {"libGL.so.1", "libGL.so"}; -#endif - - unsigned int index = 0; - for(index = 0; index < (sizeof(NAMES) / sizeof(NAMES[0])); index++) { - libGL = dlopen(NAMES[index], RTLD_NOW | RTLD_GLOBAL); - - if(libGL != NULL) { -#if defined(__APPLE__) || defined(__HAIKU__) - return 1; -#else - gladGetProcAddressPtr = (PFNGLXGETPROCADDRESSPROC_PRIVATE)dlsym(libGL, - "glXGetProcAddressARB"); - return gladGetProcAddressPtr != NULL; -#endif - } - } - - return 0; -} - -static -void close_gl(void) { - if(libGL != NULL) { - dlclose(libGL); - libGL = NULL; - } -} -#endif - -static -void* get_proc(const char *namez) { - void* result = NULL; - if(libGL == NULL) return NULL; - -#if !defined(__APPLE__) && !defined(__HAIKU__) - if(gladGetProcAddressPtr != NULL) { - result = gladGetProcAddressPtr(namez); - } -#endif - if(result == NULL) { -#if defined(_WIN32) || defined(__CYGWIN__) - result = (void*)GetProcAddress((HMODULE) libGL, namez); -#else - result = dlsym(libGL, namez); -#endif - } - - return result; -} - -int gladLoadGL(void) { - int status = 0; - - if(open_gl()) { - status = gladLoadGLLoader(&get_proc); - close_gl(); - } - - return status; -} - -struct gladGLversionStruct GLVersion = { 0, 0 }; - -#if defined(GL_ES_VERSION_3_0) || defined(GL_VERSION_3_0) -#define _GLAD_IS_SOME_NEW_VERSION 1 -#endif - -static int max_loaded_major; -static int max_loaded_minor; - -static const char *exts = NULL; -static int num_exts_i = 0; -static char **exts_i = NULL; - -static int get_exts(void) { -#ifdef _GLAD_IS_SOME_NEW_VERSION - if(max_loaded_major < 3) { -#endif - exts = (const char *)glGetString(GL_EXTENSIONS); -#ifdef _GLAD_IS_SOME_NEW_VERSION - } else { - unsigned int index; - - num_exts_i = 0; - glGetIntegerv(GL_NUM_EXTENSIONS, &num_exts_i); - if (num_exts_i > 0) { - exts_i = (char **)malloc((size_t)num_exts_i * (sizeof *exts_i)); - } - - if (exts_i == NULL) { - return 0; - } - - for(index = 0; index < (unsigned)num_exts_i; index++) { - const char *gl_str_tmp = (const char*)glGetStringi(GL_EXTENSIONS, index); - size_t len = strlen(gl_str_tmp); - - char *local_str = (char*)malloc((len+1) * sizeof(char)); - if(local_str != NULL) { - memcpy(local_str, gl_str_tmp, (len+1) * sizeof(char)); - } - exts_i[index] = local_str; - } - } -#endif - return 1; -} - -static void free_exts(void) { - if (exts_i != NULL) { - int index; - for(index = 0; index < num_exts_i; index++) { - free((char *)exts_i[index]); - } - free((void *)exts_i); - exts_i = NULL; - } -} - -static int has_ext(const char *ext) { -#ifdef _GLAD_IS_SOME_NEW_VERSION - if(max_loaded_major < 3) { -#endif - const char *extensions; - const char *loc; - const char *terminator; - extensions = exts; - if(extensions == NULL || ext == NULL) { - return 0; - } - - while(1) { - loc = strstr(extensions, ext); - if(loc == NULL) { - return 0; - } - - terminator = loc + strlen(ext); - if((loc == extensions || *(loc - 1) == ' ') && - (*terminator == ' ' || *terminator == '\0')) { - return 1; - } - extensions = terminator; - } -#ifdef _GLAD_IS_SOME_NEW_VERSION - } else { - int index; - if(exts_i == NULL) return 0; - for(index = 0; index < num_exts_i; index++) { - const char *e = exts_i[index]; - - if(exts_i[index] != NULL && strcmp(e, ext) == 0) { - return 1; - } - } - } -#endif - - return 0; -} -int GLAD_GL_VERSION_1_0 = 0; -int GLAD_GL_VERSION_1_1 = 0; -int GLAD_GL_VERSION_1_2 = 0; -int GLAD_GL_VERSION_1_3 = 0; -int GLAD_GL_VERSION_1_4 = 0; -int GLAD_GL_VERSION_1_5 = 0; -int GLAD_GL_VERSION_2_0 = 0; -int GLAD_GL_VERSION_2_1 = 0; -PFNGLACCUMPROC glad_glAccum = NULL; -PFNGLACTIVETEXTUREPROC glad_glActiveTexture = NULL; -PFNGLALPHAFUNCPROC glad_glAlphaFunc = NULL; -PFNGLARETEXTURESRESIDENTPROC glad_glAreTexturesResident = NULL; -PFNGLARRAYELEMENTPROC glad_glArrayElement = NULL; -PFNGLATTACHSHADERPROC glad_glAttachShader = NULL; -PFNGLBEGINPROC glad_glBegin = NULL; -PFNGLBEGINQUERYPROC glad_glBeginQuery = NULL; -PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation = NULL; -PFNGLBINDBUFFERPROC glad_glBindBuffer = NULL; -PFNGLBINDTEXTUREPROC glad_glBindTexture = NULL; -PFNGLBITMAPPROC glad_glBitmap = NULL; -PFNGLBLENDCOLORPROC glad_glBlendColor = NULL; -PFNGLBLENDEQUATIONPROC glad_glBlendEquation = NULL; -PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate = NULL; -PFNGLBLENDFUNCPROC glad_glBlendFunc = NULL; -PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate = NULL; -PFNGLBUFFERDATAPROC glad_glBufferData = NULL; -PFNGLBUFFERSUBDATAPROC glad_glBufferSubData = NULL; -PFNGLCALLLISTPROC glad_glCallList = NULL; -PFNGLCALLLISTSPROC glad_glCallLists = NULL; -PFNGLCLEARPROC glad_glClear = NULL; -PFNGLCLEARACCUMPROC glad_glClearAccum = NULL; -PFNGLCLEARCOLORPROC glad_glClearColor = NULL; -PFNGLCLEARDEPTHPROC glad_glClearDepth = NULL; -PFNGLCLEARINDEXPROC glad_glClearIndex = NULL; -PFNGLCLEARSTENCILPROC glad_glClearStencil = NULL; -PFNGLCLIENTACTIVETEXTUREPROC glad_glClientActiveTexture = NULL; -PFNGLCLIPPLANEPROC glad_glClipPlane = NULL; -PFNGLCOLOR3BPROC glad_glColor3b = NULL; -PFNGLCOLOR3BVPROC glad_glColor3bv = NULL; -PFNGLCOLOR3DPROC glad_glColor3d = NULL; -PFNGLCOLOR3DVPROC glad_glColor3dv = NULL; -PFNGLCOLOR3FPROC glad_glColor3f = NULL; -PFNGLCOLOR3FVPROC glad_glColor3fv = NULL; -PFNGLCOLOR3IPROC glad_glColor3i = NULL; -PFNGLCOLOR3IVPROC glad_glColor3iv = NULL; -PFNGLCOLOR3SPROC glad_glColor3s = NULL; -PFNGLCOLOR3SVPROC glad_glColor3sv = NULL; -PFNGLCOLOR3UBPROC glad_glColor3ub = NULL; -PFNGLCOLOR3UBVPROC glad_glColor3ubv = NULL; -PFNGLCOLOR3UIPROC glad_glColor3ui = NULL; -PFNGLCOLOR3UIVPROC glad_glColor3uiv = NULL; -PFNGLCOLOR3USPROC glad_glColor3us = NULL; -PFNGLCOLOR3USVPROC glad_glColor3usv = NULL; -PFNGLCOLOR4BPROC glad_glColor4b = NULL; -PFNGLCOLOR4BVPROC glad_glColor4bv = NULL; -PFNGLCOLOR4DPROC glad_glColor4d = NULL; -PFNGLCOLOR4DVPROC glad_glColor4dv = NULL; -PFNGLCOLOR4FPROC glad_glColor4f = NULL; -PFNGLCOLOR4FVPROC glad_glColor4fv = NULL; -PFNGLCOLOR4IPROC glad_glColor4i = NULL; -PFNGLCOLOR4IVPROC glad_glColor4iv = NULL; -PFNGLCOLOR4SPROC glad_glColor4s = NULL; -PFNGLCOLOR4SVPROC glad_glColor4sv = NULL; -PFNGLCOLOR4UBPROC glad_glColor4ub = NULL; -PFNGLCOLOR4UBVPROC glad_glColor4ubv = NULL; -PFNGLCOLOR4UIPROC glad_glColor4ui = NULL; -PFNGLCOLOR4UIVPROC glad_glColor4uiv = NULL; -PFNGLCOLOR4USPROC glad_glColor4us = NULL; -PFNGLCOLOR4USVPROC glad_glColor4usv = NULL; -PFNGLCOLORMASKPROC glad_glColorMask = NULL; -PFNGLCOLORMATERIALPROC glad_glColorMaterial = NULL; -PFNGLCOLORPOINTERPROC glad_glColorPointer = NULL; -PFNGLCOMPILESHADERPROC glad_glCompileShader = NULL; -PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D = NULL; -PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D = NULL; -PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D = NULL; -PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D = NULL; -PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D = NULL; -PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D = NULL; -PFNGLCOPYPIXELSPROC glad_glCopyPixels = NULL; -PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D = NULL; -PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D = NULL; -PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D = NULL; -PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D = NULL; -PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D = NULL; -PFNGLCREATEPROGRAMPROC glad_glCreateProgram = NULL; -PFNGLCREATESHADERPROC glad_glCreateShader = NULL; -PFNGLCULLFACEPROC glad_glCullFace = NULL; -PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers = NULL; -PFNGLDELETELISTSPROC glad_glDeleteLists = NULL; -PFNGLDELETEPROGRAMPROC glad_glDeleteProgram = NULL; -PFNGLDELETEQUERIESPROC glad_glDeleteQueries = NULL; -PFNGLDELETESHADERPROC glad_glDeleteShader = NULL; -PFNGLDELETETEXTURESPROC glad_glDeleteTextures = NULL; -PFNGLDEPTHFUNCPROC glad_glDepthFunc = NULL; -PFNGLDEPTHMASKPROC glad_glDepthMask = NULL; -PFNGLDEPTHRANGEPROC glad_glDepthRange = NULL; -PFNGLDETACHSHADERPROC glad_glDetachShader = NULL; -PFNGLDISABLEPROC glad_glDisable = NULL; -PFNGLDISABLECLIENTSTATEPROC glad_glDisableClientState = NULL; -PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray = NULL; -PFNGLDRAWARRAYSPROC glad_glDrawArrays = NULL; -PFNGLDRAWBUFFERPROC glad_glDrawBuffer = NULL; -PFNGLDRAWBUFFERSPROC glad_glDrawBuffers = NULL; -PFNGLDRAWELEMENTSPROC glad_glDrawElements = NULL; -PFNGLDRAWPIXELSPROC glad_glDrawPixels = NULL; -PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements = NULL; -PFNGLEDGEFLAGPROC glad_glEdgeFlag = NULL; -PFNGLEDGEFLAGPOINTERPROC glad_glEdgeFlagPointer = NULL; -PFNGLEDGEFLAGVPROC glad_glEdgeFlagv = NULL; -PFNGLENABLEPROC glad_glEnable = NULL; -PFNGLENABLECLIENTSTATEPROC glad_glEnableClientState = NULL; -PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray = NULL; -PFNGLENDPROC glad_glEnd = NULL; -PFNGLENDLISTPROC glad_glEndList = NULL; -PFNGLENDQUERYPROC glad_glEndQuery = NULL; -PFNGLEVALCOORD1DPROC glad_glEvalCoord1d = NULL; -PFNGLEVALCOORD1DVPROC glad_glEvalCoord1dv = NULL; -PFNGLEVALCOORD1FPROC glad_glEvalCoord1f = NULL; -PFNGLEVALCOORD1FVPROC glad_glEvalCoord1fv = NULL; -PFNGLEVALCOORD2DPROC glad_glEvalCoord2d = NULL; -PFNGLEVALCOORD2DVPROC glad_glEvalCoord2dv = NULL; -PFNGLEVALCOORD2FPROC glad_glEvalCoord2f = NULL; -PFNGLEVALCOORD2FVPROC glad_glEvalCoord2fv = NULL; -PFNGLEVALMESH1PROC glad_glEvalMesh1 = NULL; -PFNGLEVALMESH2PROC glad_glEvalMesh2 = NULL; -PFNGLEVALPOINT1PROC glad_glEvalPoint1 = NULL; -PFNGLEVALPOINT2PROC glad_glEvalPoint2 = NULL; -PFNGLFEEDBACKBUFFERPROC glad_glFeedbackBuffer = NULL; -PFNGLFINISHPROC glad_glFinish = NULL; -PFNGLFLUSHPROC glad_glFlush = NULL; -PFNGLFOGCOORDPOINTERPROC glad_glFogCoordPointer = NULL; -PFNGLFOGCOORDDPROC glad_glFogCoordd = NULL; -PFNGLFOGCOORDDVPROC glad_glFogCoorddv = NULL; -PFNGLFOGCOORDFPROC glad_glFogCoordf = NULL; -PFNGLFOGCOORDFVPROC glad_glFogCoordfv = NULL; -PFNGLFOGFPROC glad_glFogf = NULL; -PFNGLFOGFVPROC glad_glFogfv = NULL; -PFNGLFOGIPROC glad_glFogi = NULL; -PFNGLFOGIVPROC glad_glFogiv = NULL; -PFNGLFRONTFACEPROC glad_glFrontFace = NULL; -PFNGLFRUSTUMPROC glad_glFrustum = NULL; -PFNGLGENBUFFERSPROC glad_glGenBuffers = NULL; -PFNGLGENLISTSPROC glad_glGenLists = NULL; -PFNGLGENQUERIESPROC glad_glGenQueries = NULL; -PFNGLGENTEXTURESPROC glad_glGenTextures = NULL; -PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib = NULL; -PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform = NULL; -PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders = NULL; -PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation = NULL; -PFNGLGETBOOLEANVPROC glad_glGetBooleanv = NULL; -PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv = NULL; -PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv = NULL; -PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData = NULL; -PFNGLGETCLIPPLANEPROC glad_glGetClipPlane = NULL; -PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage = NULL; -PFNGLGETDOUBLEVPROC glad_glGetDoublev = NULL; -PFNGLGETERRORPROC glad_glGetError = NULL; -PFNGLGETFLOATVPROC glad_glGetFloatv = NULL; -PFNGLGETINTEGERVPROC glad_glGetIntegerv = NULL; -PFNGLGETLIGHTFVPROC glad_glGetLightfv = NULL; -PFNGLGETLIGHTIVPROC glad_glGetLightiv = NULL; -PFNGLGETMAPDVPROC glad_glGetMapdv = NULL; -PFNGLGETMAPFVPROC glad_glGetMapfv = NULL; -PFNGLGETMAPIVPROC glad_glGetMapiv = NULL; -PFNGLGETMATERIALFVPROC glad_glGetMaterialfv = NULL; -PFNGLGETMATERIALIVPROC glad_glGetMaterialiv = NULL; -PFNGLGETPIXELMAPFVPROC glad_glGetPixelMapfv = NULL; -PFNGLGETPIXELMAPUIVPROC glad_glGetPixelMapuiv = NULL; -PFNGLGETPIXELMAPUSVPROC glad_glGetPixelMapusv = NULL; -PFNGLGETPOINTERVPROC glad_glGetPointerv = NULL; -PFNGLGETPOLYGONSTIPPLEPROC glad_glGetPolygonStipple = NULL; -PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog = NULL; -PFNGLGETPROGRAMIVPROC glad_glGetProgramiv = NULL; -PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv = NULL; -PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv = NULL; -PFNGLGETQUERYIVPROC glad_glGetQueryiv = NULL; -PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog = NULL; -PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource = NULL; -PFNGLGETSHADERIVPROC glad_glGetShaderiv = NULL; -PFNGLGETSTRINGPROC glad_glGetString = NULL; -PFNGLGETTEXENVFVPROC glad_glGetTexEnvfv = NULL; -PFNGLGETTEXENVIVPROC glad_glGetTexEnviv = NULL; -PFNGLGETTEXGENDVPROC glad_glGetTexGendv = NULL; -PFNGLGETTEXGENFVPROC glad_glGetTexGenfv = NULL; -PFNGLGETTEXGENIVPROC glad_glGetTexGeniv = NULL; -PFNGLGETTEXIMAGEPROC glad_glGetTexImage = NULL; -PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv = NULL; -PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv = NULL; -PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv = NULL; -PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv = NULL; -PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation = NULL; -PFNGLGETUNIFORMFVPROC glad_glGetUniformfv = NULL; -PFNGLGETUNIFORMIVPROC glad_glGetUniformiv = NULL; -PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv = NULL; -PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv = NULL; -PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv = NULL; -PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv = NULL; -PFNGLHINTPROC glad_glHint = NULL; -PFNGLINDEXMASKPROC glad_glIndexMask = NULL; -PFNGLINDEXPOINTERPROC glad_glIndexPointer = NULL; -PFNGLINDEXDPROC glad_glIndexd = NULL; -PFNGLINDEXDVPROC glad_glIndexdv = NULL; -PFNGLINDEXFPROC glad_glIndexf = NULL; -PFNGLINDEXFVPROC glad_glIndexfv = NULL; -PFNGLINDEXIPROC glad_glIndexi = NULL; -PFNGLINDEXIVPROC glad_glIndexiv = NULL; -PFNGLINDEXSPROC glad_glIndexs = NULL; -PFNGLINDEXSVPROC glad_glIndexsv = NULL; -PFNGLINDEXUBPROC glad_glIndexub = NULL; -PFNGLINDEXUBVPROC glad_glIndexubv = NULL; -PFNGLINITNAMESPROC glad_glInitNames = NULL; -PFNGLINTERLEAVEDARRAYSPROC glad_glInterleavedArrays = NULL; -PFNGLISBUFFERPROC glad_glIsBuffer = NULL; -PFNGLISENABLEDPROC glad_glIsEnabled = NULL; -PFNGLISLISTPROC glad_glIsList = NULL; -PFNGLISPROGRAMPROC glad_glIsProgram = NULL; -PFNGLISQUERYPROC glad_glIsQuery = NULL; -PFNGLISSHADERPROC glad_glIsShader = NULL; -PFNGLISTEXTUREPROC glad_glIsTexture = NULL; -PFNGLLIGHTMODELFPROC glad_glLightModelf = NULL; -PFNGLLIGHTMODELFVPROC glad_glLightModelfv = NULL; -PFNGLLIGHTMODELIPROC glad_glLightModeli = NULL; -PFNGLLIGHTMODELIVPROC glad_glLightModeliv = NULL; -PFNGLLIGHTFPROC glad_glLightf = NULL; -PFNGLLIGHTFVPROC glad_glLightfv = NULL; -PFNGLLIGHTIPROC glad_glLighti = NULL; -PFNGLLIGHTIVPROC glad_glLightiv = NULL; -PFNGLLINESTIPPLEPROC glad_glLineStipple = NULL; -PFNGLLINEWIDTHPROC glad_glLineWidth = NULL; -PFNGLLINKPROGRAMPROC glad_glLinkProgram = NULL; -PFNGLLISTBASEPROC glad_glListBase = NULL; -PFNGLLOADIDENTITYPROC glad_glLoadIdentity = NULL; -PFNGLLOADMATRIXDPROC glad_glLoadMatrixd = NULL; -PFNGLLOADMATRIXFPROC glad_glLoadMatrixf = NULL; -PFNGLLOADNAMEPROC glad_glLoadName = NULL; -PFNGLLOADTRANSPOSEMATRIXDPROC glad_glLoadTransposeMatrixd = NULL; -PFNGLLOADTRANSPOSEMATRIXFPROC glad_glLoadTransposeMatrixf = NULL; -PFNGLLOGICOPPROC glad_glLogicOp = NULL; -PFNGLMAP1DPROC glad_glMap1d = NULL; -PFNGLMAP1FPROC glad_glMap1f = NULL; -PFNGLMAP2DPROC glad_glMap2d = NULL; -PFNGLMAP2FPROC glad_glMap2f = NULL; -PFNGLMAPBUFFERPROC glad_glMapBuffer = NULL; -PFNGLMAPGRID1DPROC glad_glMapGrid1d = NULL; -PFNGLMAPGRID1FPROC glad_glMapGrid1f = NULL; -PFNGLMAPGRID2DPROC glad_glMapGrid2d = NULL; -PFNGLMAPGRID2FPROC glad_glMapGrid2f = NULL; -PFNGLMATERIALFPROC glad_glMaterialf = NULL; -PFNGLMATERIALFVPROC glad_glMaterialfv = NULL; -PFNGLMATERIALIPROC glad_glMateriali = NULL; -PFNGLMATERIALIVPROC glad_glMaterialiv = NULL; -PFNGLMATRIXMODEPROC glad_glMatrixMode = NULL; -PFNGLMULTMATRIXDPROC glad_glMultMatrixd = NULL; -PFNGLMULTMATRIXFPROC glad_glMultMatrixf = NULL; -PFNGLMULTTRANSPOSEMATRIXDPROC glad_glMultTransposeMatrixd = NULL; -PFNGLMULTTRANSPOSEMATRIXFPROC glad_glMultTransposeMatrixf = NULL; -PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays = NULL; -PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements = NULL; -PFNGLMULTITEXCOORD1DPROC glad_glMultiTexCoord1d = NULL; -PFNGLMULTITEXCOORD1DVPROC glad_glMultiTexCoord1dv = NULL; -PFNGLMULTITEXCOORD1FPROC glad_glMultiTexCoord1f = NULL; -PFNGLMULTITEXCOORD1FVPROC glad_glMultiTexCoord1fv = NULL; -PFNGLMULTITEXCOORD1IPROC glad_glMultiTexCoord1i = NULL; -PFNGLMULTITEXCOORD1IVPROC glad_glMultiTexCoord1iv = NULL; -PFNGLMULTITEXCOORD1SPROC glad_glMultiTexCoord1s = NULL; -PFNGLMULTITEXCOORD1SVPROC glad_glMultiTexCoord1sv = NULL; -PFNGLMULTITEXCOORD2DPROC glad_glMultiTexCoord2d = NULL; -PFNGLMULTITEXCOORD2DVPROC glad_glMultiTexCoord2dv = NULL; -PFNGLMULTITEXCOORD2FPROC glad_glMultiTexCoord2f = NULL; -PFNGLMULTITEXCOORD2FVPROC glad_glMultiTexCoord2fv = NULL; -PFNGLMULTITEXCOORD2IPROC glad_glMultiTexCoord2i = NULL; -PFNGLMULTITEXCOORD2IVPROC glad_glMultiTexCoord2iv = NULL; -PFNGLMULTITEXCOORD2SPROC glad_glMultiTexCoord2s = NULL; -PFNGLMULTITEXCOORD2SVPROC glad_glMultiTexCoord2sv = NULL; -PFNGLMULTITEXCOORD3DPROC glad_glMultiTexCoord3d = NULL; -PFNGLMULTITEXCOORD3DVPROC glad_glMultiTexCoord3dv = NULL; -PFNGLMULTITEXCOORD3FPROC glad_glMultiTexCoord3f = NULL; -PFNGLMULTITEXCOORD3FVPROC glad_glMultiTexCoord3fv = NULL; -PFNGLMULTITEXCOORD3IPROC glad_glMultiTexCoord3i = NULL; -PFNGLMULTITEXCOORD3IVPROC glad_glMultiTexCoord3iv = NULL; -PFNGLMULTITEXCOORD3SPROC glad_glMultiTexCoord3s = NULL; -PFNGLMULTITEXCOORD3SVPROC glad_glMultiTexCoord3sv = NULL; -PFNGLMULTITEXCOORD4DPROC glad_glMultiTexCoord4d = NULL; -PFNGLMULTITEXCOORD4DVPROC glad_glMultiTexCoord4dv = NULL; -PFNGLMULTITEXCOORD4FPROC glad_glMultiTexCoord4f = NULL; -PFNGLMULTITEXCOORD4FVPROC glad_glMultiTexCoord4fv = NULL; -PFNGLMULTITEXCOORD4IPROC glad_glMultiTexCoord4i = NULL; -PFNGLMULTITEXCOORD4IVPROC glad_glMultiTexCoord4iv = NULL; -PFNGLMULTITEXCOORD4SPROC glad_glMultiTexCoord4s = NULL; -PFNGLMULTITEXCOORD4SVPROC glad_glMultiTexCoord4sv = NULL; -PFNGLNEWLISTPROC glad_glNewList = NULL; -PFNGLNORMAL3BPROC glad_glNormal3b = NULL; -PFNGLNORMAL3BVPROC glad_glNormal3bv = NULL; -PFNGLNORMAL3DPROC glad_glNormal3d = NULL; -PFNGLNORMAL3DVPROC glad_glNormal3dv = NULL; -PFNGLNORMAL3FPROC glad_glNormal3f = NULL; -PFNGLNORMAL3FVPROC glad_glNormal3fv = NULL; -PFNGLNORMAL3IPROC glad_glNormal3i = NULL; -PFNGLNORMAL3IVPROC glad_glNormal3iv = NULL; -PFNGLNORMAL3SPROC glad_glNormal3s = NULL; -PFNGLNORMAL3SVPROC glad_glNormal3sv = NULL; -PFNGLNORMALPOINTERPROC glad_glNormalPointer = NULL; -PFNGLORTHOPROC glad_glOrtho = NULL; -PFNGLPASSTHROUGHPROC glad_glPassThrough = NULL; -PFNGLPIXELMAPFVPROC glad_glPixelMapfv = NULL; -PFNGLPIXELMAPUIVPROC glad_glPixelMapuiv = NULL; -PFNGLPIXELMAPUSVPROC glad_glPixelMapusv = NULL; -PFNGLPIXELSTOREFPROC glad_glPixelStoref = NULL; -PFNGLPIXELSTOREIPROC glad_glPixelStorei = NULL; -PFNGLPIXELTRANSFERFPROC glad_glPixelTransferf = NULL; -PFNGLPIXELTRANSFERIPROC glad_glPixelTransferi = NULL; -PFNGLPIXELZOOMPROC glad_glPixelZoom = NULL; -PFNGLPOINTPARAMETERFPROC glad_glPointParameterf = NULL; -PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv = NULL; -PFNGLPOINTPARAMETERIPROC glad_glPointParameteri = NULL; -PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv = NULL; -PFNGLPOINTSIZEPROC glad_glPointSize = NULL; -PFNGLPOLYGONMODEPROC glad_glPolygonMode = NULL; -PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset = NULL; -PFNGLPOLYGONSTIPPLEPROC glad_glPolygonStipple = NULL; -PFNGLPOPATTRIBPROC glad_glPopAttrib = NULL; -PFNGLPOPCLIENTATTRIBPROC glad_glPopClientAttrib = NULL; -PFNGLPOPMATRIXPROC glad_glPopMatrix = NULL; -PFNGLPOPNAMEPROC glad_glPopName = NULL; -PFNGLPRIORITIZETEXTURESPROC glad_glPrioritizeTextures = NULL; -PFNGLPUSHATTRIBPROC glad_glPushAttrib = NULL; -PFNGLPUSHCLIENTATTRIBPROC glad_glPushClientAttrib = NULL; -PFNGLPUSHMATRIXPROC glad_glPushMatrix = NULL; -PFNGLPUSHNAMEPROC glad_glPushName = NULL; -PFNGLRASTERPOS2DPROC glad_glRasterPos2d = NULL; -PFNGLRASTERPOS2DVPROC glad_glRasterPos2dv = NULL; -PFNGLRASTERPOS2FPROC glad_glRasterPos2f = NULL; -PFNGLRASTERPOS2FVPROC glad_glRasterPos2fv = NULL; -PFNGLRASTERPOS2IPROC glad_glRasterPos2i = NULL; -PFNGLRASTERPOS2IVPROC glad_glRasterPos2iv = NULL; -PFNGLRASTERPOS2SPROC glad_glRasterPos2s = NULL; -PFNGLRASTERPOS2SVPROC glad_glRasterPos2sv = NULL; -PFNGLRASTERPOS3DPROC glad_glRasterPos3d = NULL; -PFNGLRASTERPOS3DVPROC glad_glRasterPos3dv = NULL; -PFNGLRASTERPOS3FPROC glad_glRasterPos3f = NULL; -PFNGLRASTERPOS3FVPROC glad_glRasterPos3fv = NULL; -PFNGLRASTERPOS3IPROC glad_glRasterPos3i = NULL; -PFNGLRASTERPOS3IVPROC glad_glRasterPos3iv = NULL; -PFNGLRASTERPOS3SPROC glad_glRasterPos3s = NULL; -PFNGLRASTERPOS3SVPROC glad_glRasterPos3sv = NULL; -PFNGLRASTERPOS4DPROC glad_glRasterPos4d = NULL; -PFNGLRASTERPOS4DVPROC glad_glRasterPos4dv = NULL; -PFNGLRASTERPOS4FPROC glad_glRasterPos4f = NULL; -PFNGLRASTERPOS4FVPROC glad_glRasterPos4fv = NULL; -PFNGLRASTERPOS4IPROC glad_glRasterPos4i = NULL; -PFNGLRASTERPOS4IVPROC glad_glRasterPos4iv = NULL; -PFNGLRASTERPOS4SPROC glad_glRasterPos4s = NULL; -PFNGLRASTERPOS4SVPROC glad_glRasterPos4sv = NULL; -PFNGLREADBUFFERPROC glad_glReadBuffer = NULL; -PFNGLREADPIXELSPROC glad_glReadPixels = NULL; -PFNGLRECTDPROC glad_glRectd = NULL; -PFNGLRECTDVPROC glad_glRectdv = NULL; -PFNGLRECTFPROC glad_glRectf = NULL; -PFNGLRECTFVPROC glad_glRectfv = NULL; -PFNGLRECTIPROC glad_glRecti = NULL; -PFNGLRECTIVPROC glad_glRectiv = NULL; -PFNGLRECTSPROC glad_glRects = NULL; -PFNGLRECTSVPROC glad_glRectsv = NULL; -PFNGLRENDERMODEPROC glad_glRenderMode = NULL; -PFNGLROTATEDPROC glad_glRotated = NULL; -PFNGLROTATEFPROC glad_glRotatef = NULL; -PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage = NULL; -PFNGLSCALEDPROC glad_glScaled = NULL; -PFNGLSCALEFPROC glad_glScalef = NULL; -PFNGLSCISSORPROC glad_glScissor = NULL; -PFNGLSECONDARYCOLOR3BPROC glad_glSecondaryColor3b = NULL; -PFNGLSECONDARYCOLOR3BVPROC glad_glSecondaryColor3bv = NULL; -PFNGLSECONDARYCOLOR3DPROC glad_glSecondaryColor3d = NULL; -PFNGLSECONDARYCOLOR3DVPROC glad_glSecondaryColor3dv = NULL; -PFNGLSECONDARYCOLOR3FPROC glad_glSecondaryColor3f = NULL; -PFNGLSECONDARYCOLOR3FVPROC glad_glSecondaryColor3fv = NULL; -PFNGLSECONDARYCOLOR3IPROC glad_glSecondaryColor3i = NULL; -PFNGLSECONDARYCOLOR3IVPROC glad_glSecondaryColor3iv = NULL; -PFNGLSECONDARYCOLOR3SPROC glad_glSecondaryColor3s = NULL; -PFNGLSECONDARYCOLOR3SVPROC glad_glSecondaryColor3sv = NULL; -PFNGLSECONDARYCOLOR3UBPROC glad_glSecondaryColor3ub = NULL; -PFNGLSECONDARYCOLOR3UBVPROC glad_glSecondaryColor3ubv = NULL; -PFNGLSECONDARYCOLOR3UIPROC glad_glSecondaryColor3ui = NULL; -PFNGLSECONDARYCOLOR3UIVPROC glad_glSecondaryColor3uiv = NULL; -PFNGLSECONDARYCOLOR3USPROC glad_glSecondaryColor3us = NULL; -PFNGLSECONDARYCOLOR3USVPROC glad_glSecondaryColor3usv = NULL; -PFNGLSECONDARYCOLORPOINTERPROC glad_glSecondaryColorPointer = NULL; -PFNGLSELECTBUFFERPROC glad_glSelectBuffer = NULL; -PFNGLSHADEMODELPROC glad_glShadeModel = NULL; -PFNGLSHADERSOURCEPROC glad_glShaderSource = NULL; -PFNGLSTENCILFUNCPROC glad_glStencilFunc = NULL; -PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate = NULL; -PFNGLSTENCILMASKPROC glad_glStencilMask = NULL; -PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate = NULL; -PFNGLSTENCILOPPROC glad_glStencilOp = NULL; -PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate = NULL; -PFNGLTEXCOORD1DPROC glad_glTexCoord1d = NULL; -PFNGLTEXCOORD1DVPROC glad_glTexCoord1dv = NULL; -PFNGLTEXCOORD1FPROC glad_glTexCoord1f = NULL; -PFNGLTEXCOORD1FVPROC glad_glTexCoord1fv = NULL; -PFNGLTEXCOORD1IPROC glad_glTexCoord1i = NULL; -PFNGLTEXCOORD1IVPROC glad_glTexCoord1iv = NULL; -PFNGLTEXCOORD1SPROC glad_glTexCoord1s = NULL; -PFNGLTEXCOORD1SVPROC glad_glTexCoord1sv = NULL; -PFNGLTEXCOORD2DPROC glad_glTexCoord2d = NULL; -PFNGLTEXCOORD2DVPROC glad_glTexCoord2dv = NULL; -PFNGLTEXCOORD2FPROC glad_glTexCoord2f = NULL; -PFNGLTEXCOORD2FVPROC glad_glTexCoord2fv = NULL; -PFNGLTEXCOORD2IPROC glad_glTexCoord2i = NULL; -PFNGLTEXCOORD2IVPROC glad_glTexCoord2iv = NULL; -PFNGLTEXCOORD2SPROC glad_glTexCoord2s = NULL; -PFNGLTEXCOORD2SVPROC glad_glTexCoord2sv = NULL; -PFNGLTEXCOORD3DPROC glad_glTexCoord3d = NULL; -PFNGLTEXCOORD3DVPROC glad_glTexCoord3dv = NULL; -PFNGLTEXCOORD3FPROC glad_glTexCoord3f = NULL; -PFNGLTEXCOORD3FVPROC glad_glTexCoord3fv = NULL; -PFNGLTEXCOORD3IPROC glad_glTexCoord3i = NULL; -PFNGLTEXCOORD3IVPROC glad_glTexCoord3iv = NULL; -PFNGLTEXCOORD3SPROC glad_glTexCoord3s = NULL; -PFNGLTEXCOORD3SVPROC glad_glTexCoord3sv = NULL; -PFNGLTEXCOORD4DPROC glad_glTexCoord4d = NULL; -PFNGLTEXCOORD4DVPROC glad_glTexCoord4dv = NULL; -PFNGLTEXCOORD4FPROC glad_glTexCoord4f = NULL; -PFNGLTEXCOORD4FVPROC glad_glTexCoord4fv = NULL; -PFNGLTEXCOORD4IPROC glad_glTexCoord4i = NULL; -PFNGLTEXCOORD4IVPROC glad_glTexCoord4iv = NULL; -PFNGLTEXCOORD4SPROC glad_glTexCoord4s = NULL; -PFNGLTEXCOORD4SVPROC glad_glTexCoord4sv = NULL; -PFNGLTEXCOORDPOINTERPROC glad_glTexCoordPointer = NULL; -PFNGLTEXENVFPROC glad_glTexEnvf = NULL; -PFNGLTEXENVFVPROC glad_glTexEnvfv = NULL; -PFNGLTEXENVIPROC glad_glTexEnvi = NULL; -PFNGLTEXENVIVPROC glad_glTexEnviv = NULL; -PFNGLTEXGENDPROC glad_glTexGend = NULL; -PFNGLTEXGENDVPROC glad_glTexGendv = NULL; -PFNGLTEXGENFPROC glad_glTexGenf = NULL; -PFNGLTEXGENFVPROC glad_glTexGenfv = NULL; -PFNGLTEXGENIPROC glad_glTexGeni = NULL; -PFNGLTEXGENIVPROC glad_glTexGeniv = NULL; -PFNGLTEXIMAGE1DPROC glad_glTexImage1D = NULL; -PFNGLTEXIMAGE2DPROC glad_glTexImage2D = NULL; -PFNGLTEXIMAGE3DPROC glad_glTexImage3D = NULL; -PFNGLTEXPARAMETERFPROC glad_glTexParameterf = NULL; -PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv = NULL; -PFNGLTEXPARAMETERIPROC glad_glTexParameteri = NULL; -PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv = NULL; -PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D = NULL; -PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D = NULL; -PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D = NULL; -PFNGLTRANSLATEDPROC glad_glTranslated = NULL; -PFNGLTRANSLATEFPROC glad_glTranslatef = NULL; -PFNGLUNIFORM1FPROC glad_glUniform1f = NULL; -PFNGLUNIFORM1FVPROC glad_glUniform1fv = NULL; -PFNGLUNIFORM1IPROC glad_glUniform1i = NULL; -PFNGLUNIFORM1IVPROC glad_glUniform1iv = NULL; -PFNGLUNIFORM2FPROC glad_glUniform2f = NULL; -PFNGLUNIFORM2FVPROC glad_glUniform2fv = NULL; -PFNGLUNIFORM2IPROC glad_glUniform2i = NULL; -PFNGLUNIFORM2IVPROC glad_glUniform2iv = NULL; -PFNGLUNIFORM3FPROC glad_glUniform3f = NULL; -PFNGLUNIFORM3FVPROC glad_glUniform3fv = NULL; -PFNGLUNIFORM3IPROC glad_glUniform3i = NULL; -PFNGLUNIFORM3IVPROC glad_glUniform3iv = NULL; -PFNGLUNIFORM4FPROC glad_glUniform4f = NULL; -PFNGLUNIFORM4FVPROC glad_glUniform4fv = NULL; -PFNGLUNIFORM4IPROC glad_glUniform4i = NULL; -PFNGLUNIFORM4IVPROC glad_glUniform4iv = NULL; -PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv = NULL; -PFNGLUNIFORMMATRIX2X3FVPROC glad_glUniformMatrix2x3fv = NULL; -PFNGLUNIFORMMATRIX2X4FVPROC glad_glUniformMatrix2x4fv = NULL; -PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv = NULL; -PFNGLUNIFORMMATRIX3X2FVPROC glad_glUniformMatrix3x2fv = NULL; -PFNGLUNIFORMMATRIX3X4FVPROC glad_glUniformMatrix3x4fv = NULL; -PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv = NULL; -PFNGLUNIFORMMATRIX4X2FVPROC glad_glUniformMatrix4x2fv = NULL; -PFNGLUNIFORMMATRIX4X3FVPROC glad_glUniformMatrix4x3fv = NULL; -PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer = NULL; -PFNGLUSEPROGRAMPROC glad_glUseProgram = NULL; -PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram = NULL; -PFNGLVERTEX2DPROC glad_glVertex2d = NULL; -PFNGLVERTEX2DVPROC glad_glVertex2dv = NULL; -PFNGLVERTEX2FPROC glad_glVertex2f = NULL; -PFNGLVERTEX2FVPROC glad_glVertex2fv = NULL; -PFNGLVERTEX2IPROC glad_glVertex2i = NULL; -PFNGLVERTEX2IVPROC glad_glVertex2iv = NULL; -PFNGLVERTEX2SPROC glad_glVertex2s = NULL; -PFNGLVERTEX2SVPROC glad_glVertex2sv = NULL; -PFNGLVERTEX3DPROC glad_glVertex3d = NULL; -PFNGLVERTEX3DVPROC glad_glVertex3dv = NULL; -PFNGLVERTEX3FPROC glad_glVertex3f = NULL; -PFNGLVERTEX3FVPROC glad_glVertex3fv = NULL; -PFNGLVERTEX3IPROC glad_glVertex3i = NULL; -PFNGLVERTEX3IVPROC glad_glVertex3iv = NULL; -PFNGLVERTEX3SPROC glad_glVertex3s = NULL; -PFNGLVERTEX3SVPROC glad_glVertex3sv = NULL; -PFNGLVERTEX4DPROC glad_glVertex4d = NULL; -PFNGLVERTEX4DVPROC glad_glVertex4dv = NULL; -PFNGLVERTEX4FPROC glad_glVertex4f = NULL; -PFNGLVERTEX4FVPROC glad_glVertex4fv = NULL; -PFNGLVERTEX4IPROC glad_glVertex4i = NULL; -PFNGLVERTEX4IVPROC glad_glVertex4iv = NULL; -PFNGLVERTEX4SPROC glad_glVertex4s = NULL; -PFNGLVERTEX4SVPROC glad_glVertex4sv = NULL; -PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d = NULL; -PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv = NULL; -PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f = NULL; -PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv = NULL; -PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s = NULL; -PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv = NULL; -PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d = NULL; -PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv = NULL; -PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f = NULL; -PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv = NULL; -PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s = NULL; -PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv = NULL; -PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d = NULL; -PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv = NULL; -PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f = NULL; -PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv = NULL; -PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s = NULL; -PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv = NULL; -PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv = NULL; -PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv = NULL; -PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv = NULL; -PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub = NULL; -PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv = NULL; -PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv = NULL; -PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv = NULL; -PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv = NULL; -PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d = NULL; -PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv = NULL; -PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f = NULL; -PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv = NULL; -PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv = NULL; -PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s = NULL; -PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv = NULL; -PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv = NULL; -PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv = NULL; -PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv = NULL; -PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer = NULL; -PFNGLVERTEXPOINTERPROC glad_glVertexPointer = NULL; -PFNGLVIEWPORTPROC glad_glViewport = NULL; -PFNGLWINDOWPOS2DPROC glad_glWindowPos2d = NULL; -PFNGLWINDOWPOS2DVPROC glad_glWindowPos2dv = NULL; -PFNGLWINDOWPOS2FPROC glad_glWindowPos2f = NULL; -PFNGLWINDOWPOS2FVPROC glad_glWindowPos2fv = NULL; -PFNGLWINDOWPOS2IPROC glad_glWindowPos2i = NULL; -PFNGLWINDOWPOS2IVPROC glad_glWindowPos2iv = NULL; -PFNGLWINDOWPOS2SPROC glad_glWindowPos2s = NULL; -PFNGLWINDOWPOS2SVPROC glad_glWindowPos2sv = NULL; -PFNGLWINDOWPOS3DPROC glad_glWindowPos3d = NULL; -PFNGLWINDOWPOS3DVPROC glad_glWindowPos3dv = NULL; -PFNGLWINDOWPOS3FPROC glad_glWindowPos3f = NULL; -PFNGLWINDOWPOS3FVPROC glad_glWindowPos3fv = NULL; -PFNGLWINDOWPOS3IPROC glad_glWindowPos3i = NULL; -PFNGLWINDOWPOS3IVPROC glad_glWindowPos3iv = NULL; -PFNGLWINDOWPOS3SPROC glad_glWindowPos3s = NULL; -PFNGLWINDOWPOS3SVPROC glad_glWindowPos3sv = NULL; -int GLAD_GL_ARB_depth_buffer_float = 0; -int GLAD_GL_ARB_draw_buffers = 0; -int GLAD_GL_ARB_draw_instanced = 0; -int GLAD_GL_ARB_fragment_program = 0; -int GLAD_GL_ARB_fragment_program_shadow = 0; -int GLAD_GL_ARB_fragment_shader = 0; -int GLAD_GL_ARB_framebuffer_object = 0; -int GLAD_GL_ARB_get_program_binary = 0; -int GLAD_GL_ARB_instanced_arrays = 0; -int GLAD_GL_ARB_multisample = 0; -int GLAD_GL_ARB_multitexture = 0; -int GLAD_GL_ARB_occlusion_query = 0; -int GLAD_GL_ARB_pixel_buffer_object = 0; -int GLAD_GL_ARB_point_parameters = 0; -int GLAD_GL_ARB_point_sprite = 0; -int GLAD_GL_ARB_seamless_cube_map = 0; -int GLAD_GL_ARB_shader_objects = 0; -int GLAD_GL_ARB_shading_language_100 = 0; -int GLAD_GL_ARB_shadow = 0; -int GLAD_GL_ARB_texture_compression = 0; -int GLAD_GL_ARB_texture_cube_map = 0; -int GLAD_GL_ARB_texture_env_combine = 0; -int GLAD_GL_ARB_texture_float = 0; -int GLAD_GL_ARB_texture_non_power_of_two = 0; -int GLAD_GL_ARB_vertex_buffer_object = 0; -int GLAD_GL_ARB_vertex_program = 0; -int GLAD_GL_ARB_vertex_shader = 0; -int GLAD_GL_ATI_draw_buffers = 0; -int GLAD_GL_ATI_fragment_shader = 0; -int GLAD_GL_ATI_texture_float = 0; -int GLAD_GL_EXT_blend_equation_separate = 0; -int GLAD_GL_EXT_framebuffer_blit = 0; -int GLAD_GL_EXT_framebuffer_multisample = 0; -int GLAD_GL_EXT_framebuffer_object = 0; -int GLAD_GL_EXT_framebuffer_sRGB = 0; -int GLAD_GL_EXT_geometry_shader4 = 0; -int GLAD_GL_EXT_pixel_buffer_object = 0; -int GLAD_GL_EXT_point_parameters = 0; -int GLAD_GL_EXT_secondary_color = 0; -int GLAD_GL_EXT_stencil_two_side = 0; -int GLAD_GL_EXT_stencil_wrap = 0; -int GLAD_GL_EXT_texture_array = 0; -int GLAD_GL_EXT_texture_compression_s3tc = 0; -int GLAD_GL_EXT_texture_filter_anisotropic = 0; -int GLAD_GL_EXT_texture_lod_bias = 0; -int GLAD_GL_EXT_texture_sRGB = 0; -int GLAD_GL_GREMEDY_string_marker = 0; -int GLAD_GL_NV_fragment_program2 = 0; -int GLAD_GL_NV_fragment_program_option = 0; -int GLAD_GL_NV_geometry_program4 = 0; -int GLAD_GL_NV_gpu_program4 = 0; -int GLAD_GL_NV_register_combiners = 0; -int GLAD_GL_NV_register_combiners2 = 0; -int GLAD_GL_NV_texture_compression_vtc = 0; -int GLAD_GL_NV_texture_shader = 0; -int GLAD_GL_NV_transform_feedback = 0; -int GLAD_GL_NV_vertex_program = 0; -int GLAD_GL_NV_vertex_program2_option = 0; -int GLAD_GL_NV_vertex_program3 = 0; -PFNGLDRAWBUFFERSARBPROC glad_glDrawBuffersARB = NULL; -PFNGLDRAWARRAYSINSTANCEDARBPROC glad_glDrawArraysInstancedARB = NULL; -PFNGLDRAWELEMENTSINSTANCEDARBPROC glad_glDrawElementsInstancedARB = NULL; -PFNGLPROGRAMSTRINGARBPROC glad_glProgramStringARB = NULL; -PFNGLBINDPROGRAMARBPROC glad_glBindProgramARB = NULL; -PFNGLDELETEPROGRAMSARBPROC glad_glDeleteProgramsARB = NULL; -PFNGLGENPROGRAMSARBPROC glad_glGenProgramsARB = NULL; -PFNGLPROGRAMENVPARAMETER4DARBPROC glad_glProgramEnvParameter4dARB = NULL; -PFNGLPROGRAMENVPARAMETER4DVARBPROC glad_glProgramEnvParameter4dvARB = NULL; -PFNGLPROGRAMENVPARAMETER4FARBPROC glad_glProgramEnvParameter4fARB = NULL; -PFNGLPROGRAMENVPARAMETER4FVARBPROC glad_glProgramEnvParameter4fvARB = NULL; -PFNGLPROGRAMLOCALPARAMETER4DARBPROC glad_glProgramLocalParameter4dARB = NULL; -PFNGLPROGRAMLOCALPARAMETER4DVARBPROC glad_glProgramLocalParameter4dvARB = NULL; -PFNGLPROGRAMLOCALPARAMETER4FARBPROC glad_glProgramLocalParameter4fARB = NULL; -PFNGLPROGRAMLOCALPARAMETER4FVARBPROC glad_glProgramLocalParameter4fvARB = NULL; -PFNGLGETPROGRAMENVPARAMETERDVARBPROC glad_glGetProgramEnvParameterdvARB = NULL; -PFNGLGETPROGRAMENVPARAMETERFVARBPROC glad_glGetProgramEnvParameterfvARB = NULL; -PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC glad_glGetProgramLocalParameterdvARB = NULL; -PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC glad_glGetProgramLocalParameterfvARB = NULL; -PFNGLGETPROGRAMIVARBPROC glad_glGetProgramivARB = NULL; -PFNGLGETPROGRAMSTRINGARBPROC glad_glGetProgramStringARB = NULL; -PFNGLISPROGRAMARBPROC glad_glIsProgramARB = NULL; -PFNGLISRENDERBUFFERPROC glad_glIsRenderbuffer = NULL; -PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer = NULL; -PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers = NULL; -PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers = NULL; -PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage = NULL; -PFNGLGETRENDERBUFFERPARAMETERIVPROC glad_glGetRenderbufferParameteriv = NULL; -PFNGLISFRAMEBUFFERPROC glad_glIsFramebuffer = NULL; -PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer = NULL; -PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers = NULL; -PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers = NULL; -PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus = NULL; -PFNGLFRAMEBUFFERTEXTURE1DPROC glad_glFramebufferTexture1D = NULL; -PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D = NULL; -PFNGLFRAMEBUFFERTEXTURE3DPROC glad_glFramebufferTexture3D = NULL; -PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer = NULL; -PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetFramebufferAttachmentParameteriv = NULL; -PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap = NULL; -PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer = NULL; -PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glRenderbufferStorageMultisample = NULL; -PFNGLFRAMEBUFFERTEXTURELAYERPROC glad_glFramebufferTextureLayer = NULL; -PFNGLGETPROGRAMBINARYPROC glad_glGetProgramBinary = NULL; -PFNGLPROGRAMBINARYPROC glad_glProgramBinary = NULL; -PFNGLPROGRAMPARAMETERIPROC glad_glProgramParameteri = NULL; -PFNGLVERTEXATTRIBDIVISORARBPROC glad_glVertexAttribDivisorARB = NULL; -PFNGLSAMPLECOVERAGEARBPROC glad_glSampleCoverageARB = NULL; -PFNGLACTIVETEXTUREARBPROC glad_glActiveTextureARB = NULL; -PFNGLCLIENTACTIVETEXTUREARBPROC glad_glClientActiveTextureARB = NULL; -PFNGLMULTITEXCOORD1DARBPROC glad_glMultiTexCoord1dARB = NULL; -PFNGLMULTITEXCOORD1DVARBPROC glad_glMultiTexCoord1dvARB = NULL; -PFNGLMULTITEXCOORD1FARBPROC glad_glMultiTexCoord1fARB = NULL; -PFNGLMULTITEXCOORD1FVARBPROC glad_glMultiTexCoord1fvARB = NULL; -PFNGLMULTITEXCOORD1IARBPROC glad_glMultiTexCoord1iARB = NULL; -PFNGLMULTITEXCOORD1IVARBPROC glad_glMultiTexCoord1ivARB = NULL; -PFNGLMULTITEXCOORD1SARBPROC glad_glMultiTexCoord1sARB = NULL; -PFNGLMULTITEXCOORD1SVARBPROC glad_glMultiTexCoord1svARB = NULL; -PFNGLMULTITEXCOORD2DARBPROC glad_glMultiTexCoord2dARB = NULL; -PFNGLMULTITEXCOORD2DVARBPROC glad_glMultiTexCoord2dvARB = NULL; -PFNGLMULTITEXCOORD2FARBPROC glad_glMultiTexCoord2fARB = NULL; -PFNGLMULTITEXCOORD2FVARBPROC glad_glMultiTexCoord2fvARB = NULL; -PFNGLMULTITEXCOORD2IARBPROC glad_glMultiTexCoord2iARB = NULL; -PFNGLMULTITEXCOORD2IVARBPROC glad_glMultiTexCoord2ivARB = NULL; -PFNGLMULTITEXCOORD2SARBPROC glad_glMultiTexCoord2sARB = NULL; -PFNGLMULTITEXCOORD2SVARBPROC glad_glMultiTexCoord2svARB = NULL; -PFNGLMULTITEXCOORD3DARBPROC glad_glMultiTexCoord3dARB = NULL; -PFNGLMULTITEXCOORD3DVARBPROC glad_glMultiTexCoord3dvARB = NULL; -PFNGLMULTITEXCOORD3FARBPROC glad_glMultiTexCoord3fARB = NULL; -PFNGLMULTITEXCOORD3FVARBPROC glad_glMultiTexCoord3fvARB = NULL; -PFNGLMULTITEXCOORD3IARBPROC glad_glMultiTexCoord3iARB = NULL; -PFNGLMULTITEXCOORD3IVARBPROC glad_glMultiTexCoord3ivARB = NULL; -PFNGLMULTITEXCOORD3SARBPROC glad_glMultiTexCoord3sARB = NULL; -PFNGLMULTITEXCOORD3SVARBPROC glad_glMultiTexCoord3svARB = NULL; -PFNGLMULTITEXCOORD4DARBPROC glad_glMultiTexCoord4dARB = NULL; -PFNGLMULTITEXCOORD4DVARBPROC glad_glMultiTexCoord4dvARB = NULL; -PFNGLMULTITEXCOORD4FARBPROC glad_glMultiTexCoord4fARB = NULL; -PFNGLMULTITEXCOORD4FVARBPROC glad_glMultiTexCoord4fvARB = NULL; -PFNGLMULTITEXCOORD4IARBPROC glad_glMultiTexCoord4iARB = NULL; -PFNGLMULTITEXCOORD4IVARBPROC glad_glMultiTexCoord4ivARB = NULL; -PFNGLMULTITEXCOORD4SARBPROC glad_glMultiTexCoord4sARB = NULL; -PFNGLMULTITEXCOORD4SVARBPROC glad_glMultiTexCoord4svARB = NULL; -PFNGLGENQUERIESARBPROC glad_glGenQueriesARB = NULL; -PFNGLDELETEQUERIESARBPROC glad_glDeleteQueriesARB = NULL; -PFNGLISQUERYARBPROC glad_glIsQueryARB = NULL; -PFNGLBEGINQUERYARBPROC glad_glBeginQueryARB = NULL; -PFNGLENDQUERYARBPROC glad_glEndQueryARB = NULL; -PFNGLGETQUERYIVARBPROC glad_glGetQueryivARB = NULL; -PFNGLGETQUERYOBJECTIVARBPROC glad_glGetQueryObjectivARB = NULL; -PFNGLGETQUERYOBJECTUIVARBPROC glad_glGetQueryObjectuivARB = NULL; -PFNGLPOINTPARAMETERFARBPROC glad_glPointParameterfARB = NULL; -PFNGLPOINTPARAMETERFVARBPROC glad_glPointParameterfvARB = NULL; -PFNGLDELETEOBJECTARBPROC glad_glDeleteObjectARB = NULL; -PFNGLGETHANDLEARBPROC glad_glGetHandleARB = NULL; -PFNGLDETACHOBJECTARBPROC glad_glDetachObjectARB = NULL; -PFNGLCREATESHADEROBJECTARBPROC glad_glCreateShaderObjectARB = NULL; -PFNGLSHADERSOURCEARBPROC glad_glShaderSourceARB = NULL; -PFNGLCOMPILESHADERARBPROC glad_glCompileShaderARB = NULL; -PFNGLCREATEPROGRAMOBJECTARBPROC glad_glCreateProgramObjectARB = NULL; -PFNGLATTACHOBJECTARBPROC glad_glAttachObjectARB = NULL; -PFNGLLINKPROGRAMARBPROC glad_glLinkProgramARB = NULL; -PFNGLUSEPROGRAMOBJECTARBPROC glad_glUseProgramObjectARB = NULL; -PFNGLVALIDATEPROGRAMARBPROC glad_glValidateProgramARB = NULL; -PFNGLUNIFORM1FARBPROC glad_glUniform1fARB = NULL; -PFNGLUNIFORM2FARBPROC glad_glUniform2fARB = NULL; -PFNGLUNIFORM3FARBPROC glad_glUniform3fARB = NULL; -PFNGLUNIFORM4FARBPROC glad_glUniform4fARB = NULL; -PFNGLUNIFORM1IARBPROC glad_glUniform1iARB = NULL; -PFNGLUNIFORM2IARBPROC glad_glUniform2iARB = NULL; -PFNGLUNIFORM3IARBPROC glad_glUniform3iARB = NULL; -PFNGLUNIFORM4IARBPROC glad_glUniform4iARB = NULL; -PFNGLUNIFORM1FVARBPROC glad_glUniform1fvARB = NULL; -PFNGLUNIFORM2FVARBPROC glad_glUniform2fvARB = NULL; -PFNGLUNIFORM3FVARBPROC glad_glUniform3fvARB = NULL; -PFNGLUNIFORM4FVARBPROC glad_glUniform4fvARB = NULL; -PFNGLUNIFORM1IVARBPROC glad_glUniform1ivARB = NULL; -PFNGLUNIFORM2IVARBPROC glad_glUniform2ivARB = NULL; -PFNGLUNIFORM3IVARBPROC glad_glUniform3ivARB = NULL; -PFNGLUNIFORM4IVARBPROC glad_glUniform4ivARB = NULL; -PFNGLUNIFORMMATRIX2FVARBPROC glad_glUniformMatrix2fvARB = NULL; -PFNGLUNIFORMMATRIX3FVARBPROC glad_glUniformMatrix3fvARB = NULL; -PFNGLUNIFORMMATRIX4FVARBPROC glad_glUniformMatrix4fvARB = NULL; -PFNGLGETOBJECTPARAMETERFVARBPROC glad_glGetObjectParameterfvARB = NULL; -PFNGLGETOBJECTPARAMETERIVARBPROC glad_glGetObjectParameterivARB = NULL; -PFNGLGETINFOLOGARBPROC glad_glGetInfoLogARB = NULL; -PFNGLGETATTACHEDOBJECTSARBPROC glad_glGetAttachedObjectsARB = NULL; -PFNGLGETUNIFORMLOCATIONARBPROC glad_glGetUniformLocationARB = NULL; -PFNGLGETACTIVEUNIFORMARBPROC glad_glGetActiveUniformARB = NULL; -PFNGLGETUNIFORMFVARBPROC glad_glGetUniformfvARB = NULL; -PFNGLGETUNIFORMIVARBPROC glad_glGetUniformivARB = NULL; -PFNGLGETSHADERSOURCEARBPROC glad_glGetShaderSourceARB = NULL; -PFNGLCOMPRESSEDTEXIMAGE3DARBPROC glad_glCompressedTexImage3DARB = NULL; -PFNGLCOMPRESSEDTEXIMAGE2DARBPROC glad_glCompressedTexImage2DARB = NULL; -PFNGLCOMPRESSEDTEXIMAGE1DARBPROC glad_glCompressedTexImage1DARB = NULL; -PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC glad_glCompressedTexSubImage3DARB = NULL; -PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC glad_glCompressedTexSubImage2DARB = NULL; -PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC glad_glCompressedTexSubImage1DARB = NULL; -PFNGLGETCOMPRESSEDTEXIMAGEARBPROC glad_glGetCompressedTexImageARB = NULL; -PFNGLBINDBUFFERARBPROC glad_glBindBufferARB = NULL; -PFNGLDELETEBUFFERSARBPROC glad_glDeleteBuffersARB = NULL; -PFNGLGENBUFFERSARBPROC glad_glGenBuffersARB = NULL; -PFNGLISBUFFERARBPROC glad_glIsBufferARB = NULL; -PFNGLBUFFERDATAARBPROC glad_glBufferDataARB = NULL; -PFNGLBUFFERSUBDATAARBPROC glad_glBufferSubDataARB = NULL; -PFNGLGETBUFFERSUBDATAARBPROC glad_glGetBufferSubDataARB = NULL; -PFNGLMAPBUFFERARBPROC glad_glMapBufferARB = NULL; -PFNGLUNMAPBUFFERARBPROC glad_glUnmapBufferARB = NULL; -PFNGLGETBUFFERPARAMETERIVARBPROC glad_glGetBufferParameterivARB = NULL; -PFNGLGETBUFFERPOINTERVARBPROC glad_glGetBufferPointervARB = NULL; -PFNGLVERTEXATTRIB1DARBPROC glad_glVertexAttrib1dARB = NULL; -PFNGLVERTEXATTRIB1DVARBPROC glad_glVertexAttrib1dvARB = NULL; -PFNGLVERTEXATTRIB1FARBPROC glad_glVertexAttrib1fARB = NULL; -PFNGLVERTEXATTRIB1FVARBPROC glad_glVertexAttrib1fvARB = NULL; -PFNGLVERTEXATTRIB1SARBPROC glad_glVertexAttrib1sARB = NULL; -PFNGLVERTEXATTRIB1SVARBPROC glad_glVertexAttrib1svARB = NULL; -PFNGLVERTEXATTRIB2DARBPROC glad_glVertexAttrib2dARB = NULL; -PFNGLVERTEXATTRIB2DVARBPROC glad_glVertexAttrib2dvARB = NULL; -PFNGLVERTEXATTRIB2FARBPROC glad_glVertexAttrib2fARB = NULL; -PFNGLVERTEXATTRIB2FVARBPROC glad_glVertexAttrib2fvARB = NULL; -PFNGLVERTEXATTRIB2SARBPROC glad_glVertexAttrib2sARB = NULL; -PFNGLVERTEXATTRIB2SVARBPROC glad_glVertexAttrib2svARB = NULL; -PFNGLVERTEXATTRIB3DARBPROC glad_glVertexAttrib3dARB = NULL; -PFNGLVERTEXATTRIB3DVARBPROC glad_glVertexAttrib3dvARB = NULL; -PFNGLVERTEXATTRIB3FARBPROC glad_glVertexAttrib3fARB = NULL; -PFNGLVERTEXATTRIB3FVARBPROC glad_glVertexAttrib3fvARB = NULL; -PFNGLVERTEXATTRIB3SARBPROC glad_glVertexAttrib3sARB = NULL; -PFNGLVERTEXATTRIB3SVARBPROC glad_glVertexAttrib3svARB = NULL; -PFNGLVERTEXATTRIB4NBVARBPROC glad_glVertexAttrib4NbvARB = NULL; -PFNGLVERTEXATTRIB4NIVARBPROC glad_glVertexAttrib4NivARB = NULL; -PFNGLVERTEXATTRIB4NSVARBPROC glad_glVertexAttrib4NsvARB = NULL; -PFNGLVERTEXATTRIB4NUBARBPROC glad_glVertexAttrib4NubARB = NULL; -PFNGLVERTEXATTRIB4NUBVARBPROC glad_glVertexAttrib4NubvARB = NULL; -PFNGLVERTEXATTRIB4NUIVARBPROC glad_glVertexAttrib4NuivARB = NULL; -PFNGLVERTEXATTRIB4NUSVARBPROC glad_glVertexAttrib4NusvARB = NULL; -PFNGLVERTEXATTRIB4BVARBPROC glad_glVertexAttrib4bvARB = NULL; -PFNGLVERTEXATTRIB4DARBPROC glad_glVertexAttrib4dARB = NULL; -PFNGLVERTEXATTRIB4DVARBPROC glad_glVertexAttrib4dvARB = NULL; -PFNGLVERTEXATTRIB4FARBPROC glad_glVertexAttrib4fARB = NULL; -PFNGLVERTEXATTRIB4FVARBPROC glad_glVertexAttrib4fvARB = NULL; -PFNGLVERTEXATTRIB4IVARBPROC glad_glVertexAttrib4ivARB = NULL; -PFNGLVERTEXATTRIB4SARBPROC glad_glVertexAttrib4sARB = NULL; -PFNGLVERTEXATTRIB4SVARBPROC glad_glVertexAttrib4svARB = NULL; -PFNGLVERTEXATTRIB4UBVARBPROC glad_glVertexAttrib4ubvARB = NULL; -PFNGLVERTEXATTRIB4UIVARBPROC glad_glVertexAttrib4uivARB = NULL; -PFNGLVERTEXATTRIB4USVARBPROC glad_glVertexAttrib4usvARB = NULL; -PFNGLVERTEXATTRIBPOINTERARBPROC glad_glVertexAttribPointerARB = NULL; -PFNGLENABLEVERTEXATTRIBARRAYARBPROC glad_glEnableVertexAttribArrayARB = NULL; -PFNGLDISABLEVERTEXATTRIBARRAYARBPROC glad_glDisableVertexAttribArrayARB = NULL; -PFNGLGETVERTEXATTRIBDVARBPROC glad_glGetVertexAttribdvARB = NULL; -PFNGLGETVERTEXATTRIBFVARBPROC glad_glGetVertexAttribfvARB = NULL; -PFNGLGETVERTEXATTRIBIVARBPROC glad_glGetVertexAttribivARB = NULL; -PFNGLGETVERTEXATTRIBPOINTERVARBPROC glad_glGetVertexAttribPointervARB = NULL; -PFNGLBINDATTRIBLOCATIONARBPROC glad_glBindAttribLocationARB = NULL; -PFNGLGETACTIVEATTRIBARBPROC glad_glGetActiveAttribARB = NULL; -PFNGLGETATTRIBLOCATIONARBPROC glad_glGetAttribLocationARB = NULL; -PFNGLDRAWBUFFERSATIPROC glad_glDrawBuffersATI = NULL; -PFNGLGENFRAGMENTSHADERSATIPROC glad_glGenFragmentShadersATI = NULL; -PFNGLBINDFRAGMENTSHADERATIPROC glad_glBindFragmentShaderATI = NULL; -PFNGLDELETEFRAGMENTSHADERATIPROC glad_glDeleteFragmentShaderATI = NULL; -PFNGLBEGINFRAGMENTSHADERATIPROC glad_glBeginFragmentShaderATI = NULL; -PFNGLENDFRAGMENTSHADERATIPROC glad_glEndFragmentShaderATI = NULL; -PFNGLPASSTEXCOORDATIPROC glad_glPassTexCoordATI = NULL; -PFNGLSAMPLEMAPATIPROC glad_glSampleMapATI = NULL; -PFNGLCOLORFRAGMENTOP1ATIPROC glad_glColorFragmentOp1ATI = NULL; -PFNGLCOLORFRAGMENTOP2ATIPROC glad_glColorFragmentOp2ATI = NULL; -PFNGLCOLORFRAGMENTOP3ATIPROC glad_glColorFragmentOp3ATI = NULL; -PFNGLALPHAFRAGMENTOP1ATIPROC glad_glAlphaFragmentOp1ATI = NULL; -PFNGLALPHAFRAGMENTOP2ATIPROC glad_glAlphaFragmentOp2ATI = NULL; -PFNGLALPHAFRAGMENTOP3ATIPROC glad_glAlphaFragmentOp3ATI = NULL; -PFNGLSETFRAGMENTSHADERCONSTANTATIPROC glad_glSetFragmentShaderConstantATI = NULL; -PFNGLBLENDEQUATIONSEPARATEEXTPROC glad_glBlendEquationSeparateEXT = NULL; -PFNGLBLITFRAMEBUFFEREXTPROC glad_glBlitFramebufferEXT = NULL; -PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC glad_glRenderbufferStorageMultisampleEXT = NULL; -PFNGLISRENDERBUFFEREXTPROC glad_glIsRenderbufferEXT = NULL; -PFNGLBINDRENDERBUFFEREXTPROC glad_glBindRenderbufferEXT = NULL; -PFNGLDELETERENDERBUFFERSEXTPROC glad_glDeleteRenderbuffersEXT = NULL; -PFNGLGENRENDERBUFFERSEXTPROC glad_glGenRenderbuffersEXT = NULL; -PFNGLRENDERBUFFERSTORAGEEXTPROC glad_glRenderbufferStorageEXT = NULL; -PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC glad_glGetRenderbufferParameterivEXT = NULL; -PFNGLISFRAMEBUFFEREXTPROC glad_glIsFramebufferEXT = NULL; -PFNGLBINDFRAMEBUFFEREXTPROC glad_glBindFramebufferEXT = NULL; -PFNGLDELETEFRAMEBUFFERSEXTPROC glad_glDeleteFramebuffersEXT = NULL; -PFNGLGENFRAMEBUFFERSEXTPROC glad_glGenFramebuffersEXT = NULL; -PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glad_glCheckFramebufferStatusEXT = NULL; -PFNGLFRAMEBUFFERTEXTURE1DEXTPROC glad_glFramebufferTexture1DEXT = NULL; -PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glad_glFramebufferTexture2DEXT = NULL; -PFNGLFRAMEBUFFERTEXTURE3DEXTPROC glad_glFramebufferTexture3DEXT = NULL; -PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC glad_glFramebufferRenderbufferEXT = NULL; -PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC glad_glGetFramebufferAttachmentParameterivEXT = NULL; -PFNGLGENERATEMIPMAPEXTPROC glad_glGenerateMipmapEXT = NULL; -PFNGLPROGRAMPARAMETERIEXTPROC glad_glProgramParameteriEXT = NULL; -PFNGLPOINTPARAMETERFEXTPROC glad_glPointParameterfEXT = NULL; -PFNGLPOINTPARAMETERFVEXTPROC glad_glPointParameterfvEXT = NULL; -PFNGLSECONDARYCOLOR3BEXTPROC glad_glSecondaryColor3bEXT = NULL; -PFNGLSECONDARYCOLOR3BVEXTPROC glad_glSecondaryColor3bvEXT = NULL; -PFNGLSECONDARYCOLOR3DEXTPROC glad_glSecondaryColor3dEXT = NULL; -PFNGLSECONDARYCOLOR3DVEXTPROC glad_glSecondaryColor3dvEXT = NULL; -PFNGLSECONDARYCOLOR3FEXTPROC glad_glSecondaryColor3fEXT = NULL; -PFNGLSECONDARYCOLOR3FVEXTPROC glad_glSecondaryColor3fvEXT = NULL; -PFNGLSECONDARYCOLOR3IEXTPROC glad_glSecondaryColor3iEXT = NULL; -PFNGLSECONDARYCOLOR3IVEXTPROC glad_glSecondaryColor3ivEXT = NULL; -PFNGLSECONDARYCOLOR3SEXTPROC glad_glSecondaryColor3sEXT = NULL; -PFNGLSECONDARYCOLOR3SVEXTPROC glad_glSecondaryColor3svEXT = NULL; -PFNGLSECONDARYCOLOR3UBEXTPROC glad_glSecondaryColor3ubEXT = NULL; -PFNGLSECONDARYCOLOR3UBVEXTPROC glad_glSecondaryColor3ubvEXT = NULL; -PFNGLSECONDARYCOLOR3UIEXTPROC glad_glSecondaryColor3uiEXT = NULL; -PFNGLSECONDARYCOLOR3UIVEXTPROC glad_glSecondaryColor3uivEXT = NULL; -PFNGLSECONDARYCOLOR3USEXTPROC glad_glSecondaryColor3usEXT = NULL; -PFNGLSECONDARYCOLOR3USVEXTPROC glad_glSecondaryColor3usvEXT = NULL; -PFNGLSECONDARYCOLORPOINTEREXTPROC glad_glSecondaryColorPointerEXT = NULL; -PFNGLACTIVESTENCILFACEEXTPROC glad_glActiveStencilFaceEXT = NULL; -PFNGLFRAMEBUFFERTEXTURELAYEREXTPROC glad_glFramebufferTextureLayerEXT = NULL; -PFNGLSTRINGMARKERGREMEDYPROC glad_glStringMarkerGREMEDY = NULL; -PFNGLPROGRAMVERTEXLIMITNVPROC glad_glProgramVertexLimitNV = NULL; -PFNGLFRAMEBUFFERTEXTUREEXTPROC glad_glFramebufferTextureEXT = NULL; -PFNGLFRAMEBUFFERTEXTUREFACEEXTPROC glad_glFramebufferTextureFaceEXT = NULL; -PFNGLPROGRAMLOCALPARAMETERI4INVPROC glad_glProgramLocalParameterI4iNV = NULL; -PFNGLPROGRAMLOCALPARAMETERI4IVNVPROC glad_glProgramLocalParameterI4ivNV = NULL; -PFNGLPROGRAMLOCALPARAMETERSI4IVNVPROC glad_glProgramLocalParametersI4ivNV = NULL; -PFNGLPROGRAMLOCALPARAMETERI4UINVPROC glad_glProgramLocalParameterI4uiNV = NULL; -PFNGLPROGRAMLOCALPARAMETERI4UIVNVPROC glad_glProgramLocalParameterI4uivNV = NULL; -PFNGLPROGRAMLOCALPARAMETERSI4UIVNVPROC glad_glProgramLocalParametersI4uivNV = NULL; -PFNGLPROGRAMENVPARAMETERI4INVPROC glad_glProgramEnvParameterI4iNV = NULL; -PFNGLPROGRAMENVPARAMETERI4IVNVPROC glad_glProgramEnvParameterI4ivNV = NULL; -PFNGLPROGRAMENVPARAMETERSI4IVNVPROC glad_glProgramEnvParametersI4ivNV = NULL; -PFNGLPROGRAMENVPARAMETERI4UINVPROC glad_glProgramEnvParameterI4uiNV = NULL; -PFNGLPROGRAMENVPARAMETERI4UIVNVPROC glad_glProgramEnvParameterI4uivNV = NULL; -PFNGLPROGRAMENVPARAMETERSI4UIVNVPROC glad_glProgramEnvParametersI4uivNV = NULL; -PFNGLGETPROGRAMLOCALPARAMETERIIVNVPROC glad_glGetProgramLocalParameterIivNV = NULL; -PFNGLGETPROGRAMLOCALPARAMETERIUIVNVPROC glad_glGetProgramLocalParameterIuivNV = NULL; -PFNGLGETPROGRAMENVPARAMETERIIVNVPROC glad_glGetProgramEnvParameterIivNV = NULL; -PFNGLGETPROGRAMENVPARAMETERIUIVNVPROC glad_glGetProgramEnvParameterIuivNV = NULL; -PFNGLCOMBINERPARAMETERFVNVPROC glad_glCombinerParameterfvNV = NULL; -PFNGLCOMBINERPARAMETERFNVPROC glad_glCombinerParameterfNV = NULL; -PFNGLCOMBINERPARAMETERIVNVPROC glad_glCombinerParameterivNV = NULL; -PFNGLCOMBINERPARAMETERINVPROC glad_glCombinerParameteriNV = NULL; -PFNGLCOMBINERINPUTNVPROC glad_glCombinerInputNV = NULL; -PFNGLCOMBINEROUTPUTNVPROC glad_glCombinerOutputNV = NULL; -PFNGLFINALCOMBINERINPUTNVPROC glad_glFinalCombinerInputNV = NULL; -PFNGLGETCOMBINERINPUTPARAMETERFVNVPROC glad_glGetCombinerInputParameterfvNV = NULL; -PFNGLGETCOMBINERINPUTPARAMETERIVNVPROC glad_glGetCombinerInputParameterivNV = NULL; -PFNGLGETCOMBINEROUTPUTPARAMETERFVNVPROC glad_glGetCombinerOutputParameterfvNV = NULL; -PFNGLGETCOMBINEROUTPUTPARAMETERIVNVPROC glad_glGetCombinerOutputParameterivNV = NULL; -PFNGLGETFINALCOMBINERINPUTPARAMETERFVNVPROC glad_glGetFinalCombinerInputParameterfvNV = NULL; -PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC glad_glGetFinalCombinerInputParameterivNV = NULL; -PFNGLCOMBINERSTAGEPARAMETERFVNVPROC glad_glCombinerStageParameterfvNV = NULL; -PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC glad_glGetCombinerStageParameterfvNV = NULL; -PFNGLBEGINTRANSFORMFEEDBACKNVPROC glad_glBeginTransformFeedbackNV = NULL; -PFNGLENDTRANSFORMFEEDBACKNVPROC glad_glEndTransformFeedbackNV = NULL; -PFNGLTRANSFORMFEEDBACKATTRIBSNVPROC glad_glTransformFeedbackAttribsNV = NULL; -PFNGLBINDBUFFERRANGENVPROC glad_glBindBufferRangeNV = NULL; -PFNGLBINDBUFFEROFFSETNVPROC glad_glBindBufferOffsetNV = NULL; -PFNGLBINDBUFFERBASENVPROC glad_glBindBufferBaseNV = NULL; -PFNGLTRANSFORMFEEDBACKVARYINGSNVPROC glad_glTransformFeedbackVaryingsNV = NULL; -PFNGLACTIVEVARYINGNVPROC glad_glActiveVaryingNV = NULL; -PFNGLGETVARYINGLOCATIONNVPROC glad_glGetVaryingLocationNV = NULL; -PFNGLGETACTIVEVARYINGNVPROC glad_glGetActiveVaryingNV = NULL; -PFNGLGETTRANSFORMFEEDBACKVARYINGNVPROC glad_glGetTransformFeedbackVaryingNV = NULL; -PFNGLTRANSFORMFEEDBACKSTREAMATTRIBSNVPROC glad_glTransformFeedbackStreamAttribsNV = NULL; -PFNGLAREPROGRAMSRESIDENTNVPROC glad_glAreProgramsResidentNV = NULL; -PFNGLBINDPROGRAMNVPROC glad_glBindProgramNV = NULL; -PFNGLDELETEPROGRAMSNVPROC glad_glDeleteProgramsNV = NULL; -PFNGLEXECUTEPROGRAMNVPROC glad_glExecuteProgramNV = NULL; -PFNGLGENPROGRAMSNVPROC glad_glGenProgramsNV = NULL; -PFNGLGETPROGRAMPARAMETERDVNVPROC glad_glGetProgramParameterdvNV = NULL; -PFNGLGETPROGRAMPARAMETERFVNVPROC glad_glGetProgramParameterfvNV = NULL; -PFNGLGETPROGRAMIVNVPROC glad_glGetProgramivNV = NULL; -PFNGLGETPROGRAMSTRINGNVPROC glad_glGetProgramStringNV = NULL; -PFNGLGETTRACKMATRIXIVNVPROC glad_glGetTrackMatrixivNV = NULL; -PFNGLGETVERTEXATTRIBDVNVPROC glad_glGetVertexAttribdvNV = NULL; -PFNGLGETVERTEXATTRIBFVNVPROC glad_glGetVertexAttribfvNV = NULL; -PFNGLGETVERTEXATTRIBIVNVPROC glad_glGetVertexAttribivNV = NULL; -PFNGLGETVERTEXATTRIBPOINTERVNVPROC glad_glGetVertexAttribPointervNV = NULL; -PFNGLISPROGRAMNVPROC glad_glIsProgramNV = NULL; -PFNGLLOADPROGRAMNVPROC glad_glLoadProgramNV = NULL; -PFNGLPROGRAMPARAMETER4DNVPROC glad_glProgramParameter4dNV = NULL; -PFNGLPROGRAMPARAMETER4DVNVPROC glad_glProgramParameter4dvNV = NULL; -PFNGLPROGRAMPARAMETER4FNVPROC glad_glProgramParameter4fNV = NULL; -PFNGLPROGRAMPARAMETER4FVNVPROC glad_glProgramParameter4fvNV = NULL; -PFNGLPROGRAMPARAMETERS4DVNVPROC glad_glProgramParameters4dvNV = NULL; -PFNGLPROGRAMPARAMETERS4FVNVPROC glad_glProgramParameters4fvNV = NULL; -PFNGLREQUESTRESIDENTPROGRAMSNVPROC glad_glRequestResidentProgramsNV = NULL; -PFNGLTRACKMATRIXNVPROC glad_glTrackMatrixNV = NULL; -PFNGLVERTEXATTRIBPOINTERNVPROC glad_glVertexAttribPointerNV = NULL; -PFNGLVERTEXATTRIB1DNVPROC glad_glVertexAttrib1dNV = NULL; -PFNGLVERTEXATTRIB1DVNVPROC glad_glVertexAttrib1dvNV = NULL; -PFNGLVERTEXATTRIB1FNVPROC glad_glVertexAttrib1fNV = NULL; -PFNGLVERTEXATTRIB1FVNVPROC glad_glVertexAttrib1fvNV = NULL; -PFNGLVERTEXATTRIB1SNVPROC glad_glVertexAttrib1sNV = NULL; -PFNGLVERTEXATTRIB1SVNVPROC glad_glVertexAttrib1svNV = NULL; -PFNGLVERTEXATTRIB2DNVPROC glad_glVertexAttrib2dNV = NULL; -PFNGLVERTEXATTRIB2DVNVPROC glad_glVertexAttrib2dvNV = NULL; -PFNGLVERTEXATTRIB2FNVPROC glad_glVertexAttrib2fNV = NULL; -PFNGLVERTEXATTRIB2FVNVPROC glad_glVertexAttrib2fvNV = NULL; -PFNGLVERTEXATTRIB2SNVPROC glad_glVertexAttrib2sNV = NULL; -PFNGLVERTEXATTRIB2SVNVPROC glad_glVertexAttrib2svNV = NULL; -PFNGLVERTEXATTRIB3DNVPROC glad_glVertexAttrib3dNV = NULL; -PFNGLVERTEXATTRIB3DVNVPROC glad_glVertexAttrib3dvNV = NULL; -PFNGLVERTEXATTRIB3FNVPROC glad_glVertexAttrib3fNV = NULL; -PFNGLVERTEXATTRIB3FVNVPROC glad_glVertexAttrib3fvNV = NULL; -PFNGLVERTEXATTRIB3SNVPROC glad_glVertexAttrib3sNV = NULL; -PFNGLVERTEXATTRIB3SVNVPROC glad_glVertexAttrib3svNV = NULL; -PFNGLVERTEXATTRIB4DNVPROC glad_glVertexAttrib4dNV = NULL; -PFNGLVERTEXATTRIB4DVNVPROC glad_glVertexAttrib4dvNV = NULL; -PFNGLVERTEXATTRIB4FNVPROC glad_glVertexAttrib4fNV = NULL; -PFNGLVERTEXATTRIB4FVNVPROC glad_glVertexAttrib4fvNV = NULL; -PFNGLVERTEXATTRIB4SNVPROC glad_glVertexAttrib4sNV = NULL; -PFNGLVERTEXATTRIB4SVNVPROC glad_glVertexAttrib4svNV = NULL; -PFNGLVERTEXATTRIB4UBNVPROC glad_glVertexAttrib4ubNV = NULL; -PFNGLVERTEXATTRIB4UBVNVPROC glad_glVertexAttrib4ubvNV = NULL; -PFNGLVERTEXATTRIBS1DVNVPROC glad_glVertexAttribs1dvNV = NULL; -PFNGLVERTEXATTRIBS1FVNVPROC glad_glVertexAttribs1fvNV = NULL; -PFNGLVERTEXATTRIBS1SVNVPROC glad_glVertexAttribs1svNV = NULL; -PFNGLVERTEXATTRIBS2DVNVPROC glad_glVertexAttribs2dvNV = NULL; -PFNGLVERTEXATTRIBS2FVNVPROC glad_glVertexAttribs2fvNV = NULL; -PFNGLVERTEXATTRIBS2SVNVPROC glad_glVertexAttribs2svNV = NULL; -PFNGLVERTEXATTRIBS3DVNVPROC glad_glVertexAttribs3dvNV = NULL; -PFNGLVERTEXATTRIBS3FVNVPROC glad_glVertexAttribs3fvNV = NULL; -PFNGLVERTEXATTRIBS3SVNVPROC glad_glVertexAttribs3svNV = NULL; -PFNGLVERTEXATTRIBS4DVNVPROC glad_glVertexAttribs4dvNV = NULL; -PFNGLVERTEXATTRIBS4FVNVPROC glad_glVertexAttribs4fvNV = NULL; -PFNGLVERTEXATTRIBS4SVNVPROC glad_glVertexAttribs4svNV = NULL; -PFNGLVERTEXATTRIBS4UBVNVPROC glad_glVertexAttribs4ubvNV = NULL; -static void load_GL_VERSION_1_0(GLADloadproc load) { - if(!GLAD_GL_VERSION_1_0) return; - glad_glCullFace = (PFNGLCULLFACEPROC)load("glCullFace"); - glad_glFrontFace = (PFNGLFRONTFACEPROC)load("glFrontFace"); - glad_glHint = (PFNGLHINTPROC)load("glHint"); - glad_glLineWidth = (PFNGLLINEWIDTHPROC)load("glLineWidth"); - glad_glPointSize = (PFNGLPOINTSIZEPROC)load("glPointSize"); - glad_glPolygonMode = (PFNGLPOLYGONMODEPROC)load("glPolygonMode"); - glad_glScissor = (PFNGLSCISSORPROC)load("glScissor"); - glad_glTexParameterf = (PFNGLTEXPARAMETERFPROC)load("glTexParameterf"); - glad_glTexParameterfv = (PFNGLTEXPARAMETERFVPROC)load("glTexParameterfv"); - glad_glTexParameteri = (PFNGLTEXPARAMETERIPROC)load("glTexParameteri"); - glad_glTexParameteriv = (PFNGLTEXPARAMETERIVPROC)load("glTexParameteriv"); - glad_glTexImage1D = (PFNGLTEXIMAGE1DPROC)load("glTexImage1D"); - glad_glTexImage2D = (PFNGLTEXIMAGE2DPROC)load("glTexImage2D"); - glad_glDrawBuffer = (PFNGLDRAWBUFFERPROC)load("glDrawBuffer"); - glad_glClear = (PFNGLCLEARPROC)load("glClear"); - glad_glClearColor = (PFNGLCLEARCOLORPROC)load("glClearColor"); - glad_glClearStencil = (PFNGLCLEARSTENCILPROC)load("glClearStencil"); - glad_glClearDepth = (PFNGLCLEARDEPTHPROC)load("glClearDepth"); - glad_glStencilMask = (PFNGLSTENCILMASKPROC)load("glStencilMask"); - glad_glColorMask = (PFNGLCOLORMASKPROC)load("glColorMask"); - glad_glDepthMask = (PFNGLDEPTHMASKPROC)load("glDepthMask"); - glad_glDisable = (PFNGLDISABLEPROC)load("glDisable"); - glad_glEnable = (PFNGLENABLEPROC)load("glEnable"); - glad_glFinish = (PFNGLFINISHPROC)load("glFinish"); - glad_glFlush = (PFNGLFLUSHPROC)load("glFlush"); - glad_glBlendFunc = (PFNGLBLENDFUNCPROC)load("glBlendFunc"); - glad_glLogicOp = (PFNGLLOGICOPPROC)load("glLogicOp"); - glad_glStencilFunc = (PFNGLSTENCILFUNCPROC)load("glStencilFunc"); - glad_glStencilOp = (PFNGLSTENCILOPPROC)load("glStencilOp"); - glad_glDepthFunc = (PFNGLDEPTHFUNCPROC)load("glDepthFunc"); - glad_glPixelStoref = (PFNGLPIXELSTOREFPROC)load("glPixelStoref"); - glad_glPixelStorei = (PFNGLPIXELSTOREIPROC)load("glPixelStorei"); - glad_glReadBuffer = (PFNGLREADBUFFERPROC)load("glReadBuffer"); - glad_glReadPixels = (PFNGLREADPIXELSPROC)load("glReadPixels"); - glad_glGetBooleanv = (PFNGLGETBOOLEANVPROC)load("glGetBooleanv"); - glad_glGetDoublev = (PFNGLGETDOUBLEVPROC)load("glGetDoublev"); - glad_glGetError = (PFNGLGETERRORPROC)load("glGetError"); - glad_glGetFloatv = (PFNGLGETFLOATVPROC)load("glGetFloatv"); - glad_glGetIntegerv = (PFNGLGETINTEGERVPROC)load("glGetIntegerv"); - glad_glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); - glad_glGetTexImage = (PFNGLGETTEXIMAGEPROC)load("glGetTexImage"); - glad_glGetTexParameterfv = (PFNGLGETTEXPARAMETERFVPROC)load("glGetTexParameterfv"); - glad_glGetTexParameteriv = (PFNGLGETTEXPARAMETERIVPROC)load("glGetTexParameteriv"); - glad_glGetTexLevelParameterfv = (PFNGLGETTEXLEVELPARAMETERFVPROC)load("glGetTexLevelParameterfv"); - glad_glGetTexLevelParameteriv = (PFNGLGETTEXLEVELPARAMETERIVPROC)load("glGetTexLevelParameteriv"); - glad_glIsEnabled = (PFNGLISENABLEDPROC)load("glIsEnabled"); - glad_glDepthRange = (PFNGLDEPTHRANGEPROC)load("glDepthRange"); - glad_glViewport = (PFNGLVIEWPORTPROC)load("glViewport"); - glad_glNewList = (PFNGLNEWLISTPROC)load("glNewList"); - glad_glEndList = (PFNGLENDLISTPROC)load("glEndList"); - glad_glCallList = (PFNGLCALLLISTPROC)load("glCallList"); - glad_glCallLists = (PFNGLCALLLISTSPROC)load("glCallLists"); - glad_glDeleteLists = (PFNGLDELETELISTSPROC)load("glDeleteLists"); - glad_glGenLists = (PFNGLGENLISTSPROC)load("glGenLists"); - glad_glListBase = (PFNGLLISTBASEPROC)load("glListBase"); - glad_glBegin = (PFNGLBEGINPROC)load("glBegin"); - glad_glBitmap = (PFNGLBITMAPPROC)load("glBitmap"); - glad_glColor3b = (PFNGLCOLOR3BPROC)load("glColor3b"); - glad_glColor3bv = (PFNGLCOLOR3BVPROC)load("glColor3bv"); - glad_glColor3d = (PFNGLCOLOR3DPROC)load("glColor3d"); - glad_glColor3dv = (PFNGLCOLOR3DVPROC)load("glColor3dv"); - glad_glColor3f = (PFNGLCOLOR3FPROC)load("glColor3f"); - glad_glColor3fv = (PFNGLCOLOR3FVPROC)load("glColor3fv"); - glad_glColor3i = (PFNGLCOLOR3IPROC)load("glColor3i"); - glad_glColor3iv = (PFNGLCOLOR3IVPROC)load("glColor3iv"); - glad_glColor3s = (PFNGLCOLOR3SPROC)load("glColor3s"); - glad_glColor3sv = (PFNGLCOLOR3SVPROC)load("glColor3sv"); - glad_glColor3ub = (PFNGLCOLOR3UBPROC)load("glColor3ub"); - glad_glColor3ubv = (PFNGLCOLOR3UBVPROC)load("glColor3ubv"); - glad_glColor3ui = (PFNGLCOLOR3UIPROC)load("glColor3ui"); - glad_glColor3uiv = (PFNGLCOLOR3UIVPROC)load("glColor3uiv"); - glad_glColor3us = (PFNGLCOLOR3USPROC)load("glColor3us"); - glad_glColor3usv = (PFNGLCOLOR3USVPROC)load("glColor3usv"); - glad_glColor4b = (PFNGLCOLOR4BPROC)load("glColor4b"); - glad_glColor4bv = (PFNGLCOLOR4BVPROC)load("glColor4bv"); - glad_glColor4d = (PFNGLCOLOR4DPROC)load("glColor4d"); - glad_glColor4dv = (PFNGLCOLOR4DVPROC)load("glColor4dv"); - glad_glColor4f = (PFNGLCOLOR4FPROC)load("glColor4f"); - glad_glColor4fv = (PFNGLCOLOR4FVPROC)load("glColor4fv"); - glad_glColor4i = (PFNGLCOLOR4IPROC)load("glColor4i"); - glad_glColor4iv = (PFNGLCOLOR4IVPROC)load("glColor4iv"); - glad_glColor4s = (PFNGLCOLOR4SPROC)load("glColor4s"); - glad_glColor4sv = (PFNGLCOLOR4SVPROC)load("glColor4sv"); - glad_glColor4ub = (PFNGLCOLOR4UBPROC)load("glColor4ub"); - glad_glColor4ubv = (PFNGLCOLOR4UBVPROC)load("glColor4ubv"); - glad_glColor4ui = (PFNGLCOLOR4UIPROC)load("glColor4ui"); - glad_glColor4uiv = (PFNGLCOLOR4UIVPROC)load("glColor4uiv"); - glad_glColor4us = (PFNGLCOLOR4USPROC)load("glColor4us"); - glad_glColor4usv = (PFNGLCOLOR4USVPROC)load("glColor4usv"); - glad_glEdgeFlag = (PFNGLEDGEFLAGPROC)load("glEdgeFlag"); - glad_glEdgeFlagv = (PFNGLEDGEFLAGVPROC)load("glEdgeFlagv"); - glad_glEnd = (PFNGLENDPROC)load("glEnd"); - glad_glIndexd = (PFNGLINDEXDPROC)load("glIndexd"); - glad_glIndexdv = (PFNGLINDEXDVPROC)load("glIndexdv"); - glad_glIndexf = (PFNGLINDEXFPROC)load("glIndexf"); - glad_glIndexfv = (PFNGLINDEXFVPROC)load("glIndexfv"); - glad_glIndexi = (PFNGLINDEXIPROC)load("glIndexi"); - glad_glIndexiv = (PFNGLINDEXIVPROC)load("glIndexiv"); - glad_glIndexs = (PFNGLINDEXSPROC)load("glIndexs"); - glad_glIndexsv = (PFNGLINDEXSVPROC)load("glIndexsv"); - glad_glNormal3b = (PFNGLNORMAL3BPROC)load("glNormal3b"); - glad_glNormal3bv = (PFNGLNORMAL3BVPROC)load("glNormal3bv"); - glad_glNormal3d = (PFNGLNORMAL3DPROC)load("glNormal3d"); - glad_glNormal3dv = (PFNGLNORMAL3DVPROC)load("glNormal3dv"); - glad_glNormal3f = (PFNGLNORMAL3FPROC)load("glNormal3f"); - glad_glNormal3fv = (PFNGLNORMAL3FVPROC)load("glNormal3fv"); - glad_glNormal3i = (PFNGLNORMAL3IPROC)load("glNormal3i"); - glad_glNormal3iv = (PFNGLNORMAL3IVPROC)load("glNormal3iv"); - glad_glNormal3s = (PFNGLNORMAL3SPROC)load("glNormal3s"); - glad_glNormal3sv = (PFNGLNORMAL3SVPROC)load("glNormal3sv"); - glad_glRasterPos2d = (PFNGLRASTERPOS2DPROC)load("glRasterPos2d"); - glad_glRasterPos2dv = (PFNGLRASTERPOS2DVPROC)load("glRasterPos2dv"); - glad_glRasterPos2f = (PFNGLRASTERPOS2FPROC)load("glRasterPos2f"); - glad_glRasterPos2fv = (PFNGLRASTERPOS2FVPROC)load("glRasterPos2fv"); - glad_glRasterPos2i = (PFNGLRASTERPOS2IPROC)load("glRasterPos2i"); - glad_glRasterPos2iv = (PFNGLRASTERPOS2IVPROC)load("glRasterPos2iv"); - glad_glRasterPos2s = (PFNGLRASTERPOS2SPROC)load("glRasterPos2s"); - glad_glRasterPos2sv = (PFNGLRASTERPOS2SVPROC)load("glRasterPos2sv"); - glad_glRasterPos3d = (PFNGLRASTERPOS3DPROC)load("glRasterPos3d"); - glad_glRasterPos3dv = (PFNGLRASTERPOS3DVPROC)load("glRasterPos3dv"); - glad_glRasterPos3f = (PFNGLRASTERPOS3FPROC)load("glRasterPos3f"); - glad_glRasterPos3fv = (PFNGLRASTERPOS3FVPROC)load("glRasterPos3fv"); - glad_glRasterPos3i = (PFNGLRASTERPOS3IPROC)load("glRasterPos3i"); - glad_glRasterPos3iv = (PFNGLRASTERPOS3IVPROC)load("glRasterPos3iv"); - glad_glRasterPos3s = (PFNGLRASTERPOS3SPROC)load("glRasterPos3s"); - glad_glRasterPos3sv = (PFNGLRASTERPOS3SVPROC)load("glRasterPos3sv"); - glad_glRasterPos4d = (PFNGLRASTERPOS4DPROC)load("glRasterPos4d"); - glad_glRasterPos4dv = (PFNGLRASTERPOS4DVPROC)load("glRasterPos4dv"); - glad_glRasterPos4f = (PFNGLRASTERPOS4FPROC)load("glRasterPos4f"); - glad_glRasterPos4fv = (PFNGLRASTERPOS4FVPROC)load("glRasterPos4fv"); - glad_glRasterPos4i = (PFNGLRASTERPOS4IPROC)load("glRasterPos4i"); - glad_glRasterPos4iv = (PFNGLRASTERPOS4IVPROC)load("glRasterPos4iv"); - glad_glRasterPos4s = (PFNGLRASTERPOS4SPROC)load("glRasterPos4s"); - glad_glRasterPos4sv = (PFNGLRASTERPOS4SVPROC)load("glRasterPos4sv"); - glad_glRectd = (PFNGLRECTDPROC)load("glRectd"); - glad_glRectdv = (PFNGLRECTDVPROC)load("glRectdv"); - glad_glRectf = (PFNGLRECTFPROC)load("glRectf"); - glad_glRectfv = (PFNGLRECTFVPROC)load("glRectfv"); - glad_glRecti = (PFNGLRECTIPROC)load("glRecti"); - glad_glRectiv = (PFNGLRECTIVPROC)load("glRectiv"); - glad_glRects = (PFNGLRECTSPROC)load("glRects"); - glad_glRectsv = (PFNGLRECTSVPROC)load("glRectsv"); - glad_glTexCoord1d = (PFNGLTEXCOORD1DPROC)load("glTexCoord1d"); - glad_glTexCoord1dv = (PFNGLTEXCOORD1DVPROC)load("glTexCoord1dv"); - glad_glTexCoord1f = (PFNGLTEXCOORD1FPROC)load("glTexCoord1f"); - glad_glTexCoord1fv = (PFNGLTEXCOORD1FVPROC)load("glTexCoord1fv"); - glad_glTexCoord1i = (PFNGLTEXCOORD1IPROC)load("glTexCoord1i"); - glad_glTexCoord1iv = (PFNGLTEXCOORD1IVPROC)load("glTexCoord1iv"); - glad_glTexCoord1s = (PFNGLTEXCOORD1SPROC)load("glTexCoord1s"); - glad_glTexCoord1sv = (PFNGLTEXCOORD1SVPROC)load("glTexCoord1sv"); - glad_glTexCoord2d = (PFNGLTEXCOORD2DPROC)load("glTexCoord2d"); - glad_glTexCoord2dv = (PFNGLTEXCOORD2DVPROC)load("glTexCoord2dv"); - glad_glTexCoord2f = (PFNGLTEXCOORD2FPROC)load("glTexCoord2f"); - glad_glTexCoord2fv = (PFNGLTEXCOORD2FVPROC)load("glTexCoord2fv"); - glad_glTexCoord2i = (PFNGLTEXCOORD2IPROC)load("glTexCoord2i"); - glad_glTexCoord2iv = (PFNGLTEXCOORD2IVPROC)load("glTexCoord2iv"); - glad_glTexCoord2s = (PFNGLTEXCOORD2SPROC)load("glTexCoord2s"); - glad_glTexCoord2sv = (PFNGLTEXCOORD2SVPROC)load("glTexCoord2sv"); - glad_glTexCoord3d = (PFNGLTEXCOORD3DPROC)load("glTexCoord3d"); - glad_glTexCoord3dv = (PFNGLTEXCOORD3DVPROC)load("glTexCoord3dv"); - glad_glTexCoord3f = (PFNGLTEXCOORD3FPROC)load("glTexCoord3f"); - glad_glTexCoord3fv = (PFNGLTEXCOORD3FVPROC)load("glTexCoord3fv"); - glad_glTexCoord3i = (PFNGLTEXCOORD3IPROC)load("glTexCoord3i"); - glad_glTexCoord3iv = (PFNGLTEXCOORD3IVPROC)load("glTexCoord3iv"); - glad_glTexCoord3s = (PFNGLTEXCOORD3SPROC)load("glTexCoord3s"); - glad_glTexCoord3sv = (PFNGLTEXCOORD3SVPROC)load("glTexCoord3sv"); - glad_glTexCoord4d = (PFNGLTEXCOORD4DPROC)load("glTexCoord4d"); - glad_glTexCoord4dv = (PFNGLTEXCOORD4DVPROC)load("glTexCoord4dv"); - glad_glTexCoord4f = (PFNGLTEXCOORD4FPROC)load("glTexCoord4f"); - glad_glTexCoord4fv = (PFNGLTEXCOORD4FVPROC)load("glTexCoord4fv"); - glad_glTexCoord4i = (PFNGLTEXCOORD4IPROC)load("glTexCoord4i"); - glad_glTexCoord4iv = (PFNGLTEXCOORD4IVPROC)load("glTexCoord4iv"); - glad_glTexCoord4s = (PFNGLTEXCOORD4SPROC)load("glTexCoord4s"); - glad_glTexCoord4sv = (PFNGLTEXCOORD4SVPROC)load("glTexCoord4sv"); - glad_glVertex2d = (PFNGLVERTEX2DPROC)load("glVertex2d"); - glad_glVertex2dv = (PFNGLVERTEX2DVPROC)load("glVertex2dv"); - glad_glVertex2f = (PFNGLVERTEX2FPROC)load("glVertex2f"); - glad_glVertex2fv = (PFNGLVERTEX2FVPROC)load("glVertex2fv"); - glad_glVertex2i = (PFNGLVERTEX2IPROC)load("glVertex2i"); - glad_glVertex2iv = (PFNGLVERTEX2IVPROC)load("glVertex2iv"); - glad_glVertex2s = (PFNGLVERTEX2SPROC)load("glVertex2s"); - glad_glVertex2sv = (PFNGLVERTEX2SVPROC)load("glVertex2sv"); - glad_glVertex3d = (PFNGLVERTEX3DPROC)load("glVertex3d"); - glad_glVertex3dv = (PFNGLVERTEX3DVPROC)load("glVertex3dv"); - glad_glVertex3f = (PFNGLVERTEX3FPROC)load("glVertex3f"); - glad_glVertex3fv = (PFNGLVERTEX3FVPROC)load("glVertex3fv"); - glad_glVertex3i = (PFNGLVERTEX3IPROC)load("glVertex3i"); - glad_glVertex3iv = (PFNGLVERTEX3IVPROC)load("glVertex3iv"); - glad_glVertex3s = (PFNGLVERTEX3SPROC)load("glVertex3s"); - glad_glVertex3sv = (PFNGLVERTEX3SVPROC)load("glVertex3sv"); - glad_glVertex4d = (PFNGLVERTEX4DPROC)load("glVertex4d"); - glad_glVertex4dv = (PFNGLVERTEX4DVPROC)load("glVertex4dv"); - glad_glVertex4f = (PFNGLVERTEX4FPROC)load("glVertex4f"); - glad_glVertex4fv = (PFNGLVERTEX4FVPROC)load("glVertex4fv"); - glad_glVertex4i = (PFNGLVERTEX4IPROC)load("glVertex4i"); - glad_glVertex4iv = (PFNGLVERTEX4IVPROC)load("glVertex4iv"); - glad_glVertex4s = (PFNGLVERTEX4SPROC)load("glVertex4s"); - glad_glVertex4sv = (PFNGLVERTEX4SVPROC)load("glVertex4sv"); - glad_glClipPlane = (PFNGLCLIPPLANEPROC)load("glClipPlane"); - glad_glColorMaterial = (PFNGLCOLORMATERIALPROC)load("glColorMaterial"); - glad_glFogf = (PFNGLFOGFPROC)load("glFogf"); - glad_glFogfv = (PFNGLFOGFVPROC)load("glFogfv"); - glad_glFogi = (PFNGLFOGIPROC)load("glFogi"); - glad_glFogiv = (PFNGLFOGIVPROC)load("glFogiv"); - glad_glLightf = (PFNGLLIGHTFPROC)load("glLightf"); - glad_glLightfv = (PFNGLLIGHTFVPROC)load("glLightfv"); - glad_glLighti = (PFNGLLIGHTIPROC)load("glLighti"); - glad_glLightiv = (PFNGLLIGHTIVPROC)load("glLightiv"); - glad_glLightModelf = (PFNGLLIGHTMODELFPROC)load("glLightModelf"); - glad_glLightModelfv = (PFNGLLIGHTMODELFVPROC)load("glLightModelfv"); - glad_glLightModeli = (PFNGLLIGHTMODELIPROC)load("glLightModeli"); - glad_glLightModeliv = (PFNGLLIGHTMODELIVPROC)load("glLightModeliv"); - glad_glLineStipple = (PFNGLLINESTIPPLEPROC)load("glLineStipple"); - glad_glMaterialf = (PFNGLMATERIALFPROC)load("glMaterialf"); - glad_glMaterialfv = (PFNGLMATERIALFVPROC)load("glMaterialfv"); - glad_glMateriali = (PFNGLMATERIALIPROC)load("glMateriali"); - glad_glMaterialiv = (PFNGLMATERIALIVPROC)load("glMaterialiv"); - glad_glPolygonStipple = (PFNGLPOLYGONSTIPPLEPROC)load("glPolygonStipple"); - glad_glShadeModel = (PFNGLSHADEMODELPROC)load("glShadeModel"); - glad_glTexEnvf = (PFNGLTEXENVFPROC)load("glTexEnvf"); - glad_glTexEnvfv = (PFNGLTEXENVFVPROC)load("glTexEnvfv"); - glad_glTexEnvi = (PFNGLTEXENVIPROC)load("glTexEnvi"); - glad_glTexEnviv = (PFNGLTEXENVIVPROC)load("glTexEnviv"); - glad_glTexGend = (PFNGLTEXGENDPROC)load("glTexGend"); - glad_glTexGendv = (PFNGLTEXGENDVPROC)load("glTexGendv"); - glad_glTexGenf = (PFNGLTEXGENFPROC)load("glTexGenf"); - glad_glTexGenfv = (PFNGLTEXGENFVPROC)load("glTexGenfv"); - glad_glTexGeni = (PFNGLTEXGENIPROC)load("glTexGeni"); - glad_glTexGeniv = (PFNGLTEXGENIVPROC)load("glTexGeniv"); - glad_glFeedbackBuffer = (PFNGLFEEDBACKBUFFERPROC)load("glFeedbackBuffer"); - glad_glSelectBuffer = (PFNGLSELECTBUFFERPROC)load("glSelectBuffer"); - glad_glRenderMode = (PFNGLRENDERMODEPROC)load("glRenderMode"); - glad_glInitNames = (PFNGLINITNAMESPROC)load("glInitNames"); - glad_glLoadName = (PFNGLLOADNAMEPROC)load("glLoadName"); - glad_glPassThrough = (PFNGLPASSTHROUGHPROC)load("glPassThrough"); - glad_glPopName = (PFNGLPOPNAMEPROC)load("glPopName"); - glad_glPushName = (PFNGLPUSHNAMEPROC)load("glPushName"); - glad_glClearAccum = (PFNGLCLEARACCUMPROC)load("glClearAccum"); - glad_glClearIndex = (PFNGLCLEARINDEXPROC)load("glClearIndex"); - glad_glIndexMask = (PFNGLINDEXMASKPROC)load("glIndexMask"); - glad_glAccum = (PFNGLACCUMPROC)load("glAccum"); - glad_glPopAttrib = (PFNGLPOPATTRIBPROC)load("glPopAttrib"); - glad_glPushAttrib = (PFNGLPUSHATTRIBPROC)load("glPushAttrib"); - glad_glMap1d = (PFNGLMAP1DPROC)load("glMap1d"); - glad_glMap1f = (PFNGLMAP1FPROC)load("glMap1f"); - glad_glMap2d = (PFNGLMAP2DPROC)load("glMap2d"); - glad_glMap2f = (PFNGLMAP2FPROC)load("glMap2f"); - glad_glMapGrid1d = (PFNGLMAPGRID1DPROC)load("glMapGrid1d"); - glad_glMapGrid1f = (PFNGLMAPGRID1FPROC)load("glMapGrid1f"); - glad_glMapGrid2d = (PFNGLMAPGRID2DPROC)load("glMapGrid2d"); - glad_glMapGrid2f = (PFNGLMAPGRID2FPROC)load("glMapGrid2f"); - glad_glEvalCoord1d = (PFNGLEVALCOORD1DPROC)load("glEvalCoord1d"); - glad_glEvalCoord1dv = (PFNGLEVALCOORD1DVPROC)load("glEvalCoord1dv"); - glad_glEvalCoord1f = (PFNGLEVALCOORD1FPROC)load("glEvalCoord1f"); - glad_glEvalCoord1fv = (PFNGLEVALCOORD1FVPROC)load("glEvalCoord1fv"); - glad_glEvalCoord2d = (PFNGLEVALCOORD2DPROC)load("glEvalCoord2d"); - glad_glEvalCoord2dv = (PFNGLEVALCOORD2DVPROC)load("glEvalCoord2dv"); - glad_glEvalCoord2f = (PFNGLEVALCOORD2FPROC)load("glEvalCoord2f"); - glad_glEvalCoord2fv = (PFNGLEVALCOORD2FVPROC)load("glEvalCoord2fv"); - glad_glEvalMesh1 = (PFNGLEVALMESH1PROC)load("glEvalMesh1"); - glad_glEvalPoint1 = (PFNGLEVALPOINT1PROC)load("glEvalPoint1"); - glad_glEvalMesh2 = (PFNGLEVALMESH2PROC)load("glEvalMesh2"); - glad_glEvalPoint2 = (PFNGLEVALPOINT2PROC)load("glEvalPoint2"); - glad_glAlphaFunc = (PFNGLALPHAFUNCPROC)load("glAlphaFunc"); - glad_glPixelZoom = (PFNGLPIXELZOOMPROC)load("glPixelZoom"); - glad_glPixelTransferf = (PFNGLPIXELTRANSFERFPROC)load("glPixelTransferf"); - glad_glPixelTransferi = (PFNGLPIXELTRANSFERIPROC)load("glPixelTransferi"); - glad_glPixelMapfv = (PFNGLPIXELMAPFVPROC)load("glPixelMapfv"); - glad_glPixelMapuiv = (PFNGLPIXELMAPUIVPROC)load("glPixelMapuiv"); - glad_glPixelMapusv = (PFNGLPIXELMAPUSVPROC)load("glPixelMapusv"); - glad_glCopyPixels = (PFNGLCOPYPIXELSPROC)load("glCopyPixels"); - glad_glDrawPixels = (PFNGLDRAWPIXELSPROC)load("glDrawPixels"); - glad_glGetClipPlane = (PFNGLGETCLIPPLANEPROC)load("glGetClipPlane"); - glad_glGetLightfv = (PFNGLGETLIGHTFVPROC)load("glGetLightfv"); - glad_glGetLightiv = (PFNGLGETLIGHTIVPROC)load("glGetLightiv"); - glad_glGetMapdv = (PFNGLGETMAPDVPROC)load("glGetMapdv"); - glad_glGetMapfv = (PFNGLGETMAPFVPROC)load("glGetMapfv"); - glad_glGetMapiv = (PFNGLGETMAPIVPROC)load("glGetMapiv"); - glad_glGetMaterialfv = (PFNGLGETMATERIALFVPROC)load("glGetMaterialfv"); - glad_glGetMaterialiv = (PFNGLGETMATERIALIVPROC)load("glGetMaterialiv"); - glad_glGetPixelMapfv = (PFNGLGETPIXELMAPFVPROC)load("glGetPixelMapfv"); - glad_glGetPixelMapuiv = (PFNGLGETPIXELMAPUIVPROC)load("glGetPixelMapuiv"); - glad_glGetPixelMapusv = (PFNGLGETPIXELMAPUSVPROC)load("glGetPixelMapusv"); - glad_glGetPolygonStipple = (PFNGLGETPOLYGONSTIPPLEPROC)load("glGetPolygonStipple"); - glad_glGetTexEnvfv = (PFNGLGETTEXENVFVPROC)load("glGetTexEnvfv"); - glad_glGetTexEnviv = (PFNGLGETTEXENVIVPROC)load("glGetTexEnviv"); - glad_glGetTexGendv = (PFNGLGETTEXGENDVPROC)load("glGetTexGendv"); - glad_glGetTexGenfv = (PFNGLGETTEXGENFVPROC)load("glGetTexGenfv"); - glad_glGetTexGeniv = (PFNGLGETTEXGENIVPROC)load("glGetTexGeniv"); - glad_glIsList = (PFNGLISLISTPROC)load("glIsList"); - glad_glFrustum = (PFNGLFRUSTUMPROC)load("glFrustum"); - glad_glLoadIdentity = (PFNGLLOADIDENTITYPROC)load("glLoadIdentity"); - glad_glLoadMatrixf = (PFNGLLOADMATRIXFPROC)load("glLoadMatrixf"); - glad_glLoadMatrixd = (PFNGLLOADMATRIXDPROC)load("glLoadMatrixd"); - glad_glMatrixMode = (PFNGLMATRIXMODEPROC)load("glMatrixMode"); - glad_glMultMatrixf = (PFNGLMULTMATRIXFPROC)load("glMultMatrixf"); - glad_glMultMatrixd = (PFNGLMULTMATRIXDPROC)load("glMultMatrixd"); - glad_glOrtho = (PFNGLORTHOPROC)load("glOrtho"); - glad_glPopMatrix = (PFNGLPOPMATRIXPROC)load("glPopMatrix"); - glad_glPushMatrix = (PFNGLPUSHMATRIXPROC)load("glPushMatrix"); - glad_glRotated = (PFNGLROTATEDPROC)load("glRotated"); - glad_glRotatef = (PFNGLROTATEFPROC)load("glRotatef"); - glad_glScaled = (PFNGLSCALEDPROC)load("glScaled"); - glad_glScalef = (PFNGLSCALEFPROC)load("glScalef"); - glad_glTranslated = (PFNGLTRANSLATEDPROC)load("glTranslated"); - glad_glTranslatef = (PFNGLTRANSLATEFPROC)load("glTranslatef"); -} -static void load_GL_VERSION_1_1(GLADloadproc load) { - if(!GLAD_GL_VERSION_1_1) return; - glad_glDrawArrays = (PFNGLDRAWARRAYSPROC)load("glDrawArrays"); - glad_glDrawElements = (PFNGLDRAWELEMENTSPROC)load("glDrawElements"); - glad_glGetPointerv = (PFNGLGETPOINTERVPROC)load("glGetPointerv"); - glad_glPolygonOffset = (PFNGLPOLYGONOFFSETPROC)load("glPolygonOffset"); - glad_glCopyTexImage1D = (PFNGLCOPYTEXIMAGE1DPROC)load("glCopyTexImage1D"); - glad_glCopyTexImage2D = (PFNGLCOPYTEXIMAGE2DPROC)load("glCopyTexImage2D"); - glad_glCopyTexSubImage1D = (PFNGLCOPYTEXSUBIMAGE1DPROC)load("glCopyTexSubImage1D"); - glad_glCopyTexSubImage2D = (PFNGLCOPYTEXSUBIMAGE2DPROC)load("glCopyTexSubImage2D"); - glad_glTexSubImage1D = (PFNGLTEXSUBIMAGE1DPROC)load("glTexSubImage1D"); - glad_glTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC)load("glTexSubImage2D"); - glad_glBindTexture = (PFNGLBINDTEXTUREPROC)load("glBindTexture"); - glad_glDeleteTextures = (PFNGLDELETETEXTURESPROC)load("glDeleteTextures"); - glad_glGenTextures = (PFNGLGENTEXTURESPROC)load("glGenTextures"); - glad_glIsTexture = (PFNGLISTEXTUREPROC)load("glIsTexture"); - glad_glArrayElement = (PFNGLARRAYELEMENTPROC)load("glArrayElement"); - glad_glColorPointer = (PFNGLCOLORPOINTERPROC)load("glColorPointer"); - glad_glDisableClientState = (PFNGLDISABLECLIENTSTATEPROC)load("glDisableClientState"); - glad_glEdgeFlagPointer = (PFNGLEDGEFLAGPOINTERPROC)load("glEdgeFlagPointer"); - glad_glEnableClientState = (PFNGLENABLECLIENTSTATEPROC)load("glEnableClientState"); - glad_glIndexPointer = (PFNGLINDEXPOINTERPROC)load("glIndexPointer"); - glad_glInterleavedArrays = (PFNGLINTERLEAVEDARRAYSPROC)load("glInterleavedArrays"); - glad_glNormalPointer = (PFNGLNORMALPOINTERPROC)load("glNormalPointer"); - glad_glTexCoordPointer = (PFNGLTEXCOORDPOINTERPROC)load("glTexCoordPointer"); - glad_glVertexPointer = (PFNGLVERTEXPOINTERPROC)load("glVertexPointer"); - glad_glAreTexturesResident = (PFNGLARETEXTURESRESIDENTPROC)load("glAreTexturesResident"); - glad_glPrioritizeTextures = (PFNGLPRIORITIZETEXTURESPROC)load("glPrioritizeTextures"); - glad_glIndexub = (PFNGLINDEXUBPROC)load("glIndexub"); - glad_glIndexubv = (PFNGLINDEXUBVPROC)load("glIndexubv"); - glad_glPopClientAttrib = (PFNGLPOPCLIENTATTRIBPROC)load("glPopClientAttrib"); - glad_glPushClientAttrib = (PFNGLPUSHCLIENTATTRIBPROC)load("glPushClientAttrib"); -} -static void load_GL_VERSION_1_2(GLADloadproc load) { - if(!GLAD_GL_VERSION_1_2) return; - glad_glDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC)load("glDrawRangeElements"); - glad_glTexImage3D = (PFNGLTEXIMAGE3DPROC)load("glTexImage3D"); - glad_glTexSubImage3D = (PFNGLTEXSUBIMAGE3DPROC)load("glTexSubImage3D"); - glad_glCopyTexSubImage3D = (PFNGLCOPYTEXSUBIMAGE3DPROC)load("glCopyTexSubImage3D"); -} -static void load_GL_VERSION_1_3(GLADloadproc load) { - if(!GLAD_GL_VERSION_1_3) return; - glad_glActiveTexture = (PFNGLACTIVETEXTUREPROC)load("glActiveTexture"); - glad_glSampleCoverage = (PFNGLSAMPLECOVERAGEPROC)load("glSampleCoverage"); - glad_glCompressedTexImage3D = (PFNGLCOMPRESSEDTEXIMAGE3DPROC)load("glCompressedTexImage3D"); - glad_glCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)load("glCompressedTexImage2D"); - glad_glCompressedTexImage1D = (PFNGLCOMPRESSEDTEXIMAGE1DPROC)load("glCompressedTexImage1D"); - glad_glCompressedTexSubImage3D = (PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)load("glCompressedTexSubImage3D"); - glad_glCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)load("glCompressedTexSubImage2D"); - glad_glCompressedTexSubImage1D = (PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)load("glCompressedTexSubImage1D"); - glad_glGetCompressedTexImage = (PFNGLGETCOMPRESSEDTEXIMAGEPROC)load("glGetCompressedTexImage"); - glad_glClientActiveTexture = (PFNGLCLIENTACTIVETEXTUREPROC)load("glClientActiveTexture"); - glad_glMultiTexCoord1d = (PFNGLMULTITEXCOORD1DPROC)load("glMultiTexCoord1d"); - glad_glMultiTexCoord1dv = (PFNGLMULTITEXCOORD1DVPROC)load("glMultiTexCoord1dv"); - glad_glMultiTexCoord1f = (PFNGLMULTITEXCOORD1FPROC)load("glMultiTexCoord1f"); - glad_glMultiTexCoord1fv = (PFNGLMULTITEXCOORD1FVPROC)load("glMultiTexCoord1fv"); - glad_glMultiTexCoord1i = (PFNGLMULTITEXCOORD1IPROC)load("glMultiTexCoord1i"); - glad_glMultiTexCoord1iv = (PFNGLMULTITEXCOORD1IVPROC)load("glMultiTexCoord1iv"); - glad_glMultiTexCoord1s = (PFNGLMULTITEXCOORD1SPROC)load("glMultiTexCoord1s"); - glad_glMultiTexCoord1sv = (PFNGLMULTITEXCOORD1SVPROC)load("glMultiTexCoord1sv"); - glad_glMultiTexCoord2d = (PFNGLMULTITEXCOORD2DPROC)load("glMultiTexCoord2d"); - glad_glMultiTexCoord2dv = (PFNGLMULTITEXCOORD2DVPROC)load("glMultiTexCoord2dv"); - glad_glMultiTexCoord2f = (PFNGLMULTITEXCOORD2FPROC)load("glMultiTexCoord2f"); - glad_glMultiTexCoord2fv = (PFNGLMULTITEXCOORD2FVPROC)load("glMultiTexCoord2fv"); - glad_glMultiTexCoord2i = (PFNGLMULTITEXCOORD2IPROC)load("glMultiTexCoord2i"); - glad_glMultiTexCoord2iv = (PFNGLMULTITEXCOORD2IVPROC)load("glMultiTexCoord2iv"); - glad_glMultiTexCoord2s = (PFNGLMULTITEXCOORD2SPROC)load("glMultiTexCoord2s"); - glad_glMultiTexCoord2sv = (PFNGLMULTITEXCOORD2SVPROC)load("glMultiTexCoord2sv"); - glad_glMultiTexCoord3d = (PFNGLMULTITEXCOORD3DPROC)load("glMultiTexCoord3d"); - glad_glMultiTexCoord3dv = (PFNGLMULTITEXCOORD3DVPROC)load("glMultiTexCoord3dv"); - glad_glMultiTexCoord3f = (PFNGLMULTITEXCOORD3FPROC)load("glMultiTexCoord3f"); - glad_glMultiTexCoord3fv = (PFNGLMULTITEXCOORD3FVPROC)load("glMultiTexCoord3fv"); - glad_glMultiTexCoord3i = (PFNGLMULTITEXCOORD3IPROC)load("glMultiTexCoord3i"); - glad_glMultiTexCoord3iv = (PFNGLMULTITEXCOORD3IVPROC)load("glMultiTexCoord3iv"); - glad_glMultiTexCoord3s = (PFNGLMULTITEXCOORD3SPROC)load("glMultiTexCoord3s"); - glad_glMultiTexCoord3sv = (PFNGLMULTITEXCOORD3SVPROC)load("glMultiTexCoord3sv"); - glad_glMultiTexCoord4d = (PFNGLMULTITEXCOORD4DPROC)load("glMultiTexCoord4d"); - glad_glMultiTexCoord4dv = (PFNGLMULTITEXCOORD4DVPROC)load("glMultiTexCoord4dv"); - glad_glMultiTexCoord4f = (PFNGLMULTITEXCOORD4FPROC)load("glMultiTexCoord4f"); - glad_glMultiTexCoord4fv = (PFNGLMULTITEXCOORD4FVPROC)load("glMultiTexCoord4fv"); - glad_glMultiTexCoord4i = (PFNGLMULTITEXCOORD4IPROC)load("glMultiTexCoord4i"); - glad_glMultiTexCoord4iv = (PFNGLMULTITEXCOORD4IVPROC)load("glMultiTexCoord4iv"); - glad_glMultiTexCoord4s = (PFNGLMULTITEXCOORD4SPROC)load("glMultiTexCoord4s"); - glad_glMultiTexCoord4sv = (PFNGLMULTITEXCOORD4SVPROC)load("glMultiTexCoord4sv"); - glad_glLoadTransposeMatrixf = (PFNGLLOADTRANSPOSEMATRIXFPROC)load("glLoadTransposeMatrixf"); - glad_glLoadTransposeMatrixd = (PFNGLLOADTRANSPOSEMATRIXDPROC)load("glLoadTransposeMatrixd"); - glad_glMultTransposeMatrixf = (PFNGLMULTTRANSPOSEMATRIXFPROC)load("glMultTransposeMatrixf"); - glad_glMultTransposeMatrixd = (PFNGLMULTTRANSPOSEMATRIXDPROC)load("glMultTransposeMatrixd"); -} -static void load_GL_VERSION_1_4(GLADloadproc load) { - if(!GLAD_GL_VERSION_1_4) return; - glad_glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)load("glBlendFuncSeparate"); - glad_glMultiDrawArrays = (PFNGLMULTIDRAWARRAYSPROC)load("glMultiDrawArrays"); - glad_glMultiDrawElements = (PFNGLMULTIDRAWELEMENTSPROC)load("glMultiDrawElements"); - glad_glPointParameterf = (PFNGLPOINTPARAMETERFPROC)load("glPointParameterf"); - glad_glPointParameterfv = (PFNGLPOINTPARAMETERFVPROC)load("glPointParameterfv"); - glad_glPointParameteri = (PFNGLPOINTPARAMETERIPROC)load("glPointParameteri"); - glad_glPointParameteriv = (PFNGLPOINTPARAMETERIVPROC)load("glPointParameteriv"); - glad_glFogCoordf = (PFNGLFOGCOORDFPROC)load("glFogCoordf"); - glad_glFogCoordfv = (PFNGLFOGCOORDFVPROC)load("glFogCoordfv"); - glad_glFogCoordd = (PFNGLFOGCOORDDPROC)load("glFogCoordd"); - glad_glFogCoorddv = (PFNGLFOGCOORDDVPROC)load("glFogCoorddv"); - glad_glFogCoordPointer = (PFNGLFOGCOORDPOINTERPROC)load("glFogCoordPointer"); - glad_glSecondaryColor3b = (PFNGLSECONDARYCOLOR3BPROC)load("glSecondaryColor3b"); - glad_glSecondaryColor3bv = (PFNGLSECONDARYCOLOR3BVPROC)load("glSecondaryColor3bv"); - glad_glSecondaryColor3d = (PFNGLSECONDARYCOLOR3DPROC)load("glSecondaryColor3d"); - glad_glSecondaryColor3dv = (PFNGLSECONDARYCOLOR3DVPROC)load("glSecondaryColor3dv"); - glad_glSecondaryColor3f = (PFNGLSECONDARYCOLOR3FPROC)load("glSecondaryColor3f"); - glad_glSecondaryColor3fv = (PFNGLSECONDARYCOLOR3FVPROC)load("glSecondaryColor3fv"); - glad_glSecondaryColor3i = (PFNGLSECONDARYCOLOR3IPROC)load("glSecondaryColor3i"); - glad_glSecondaryColor3iv = (PFNGLSECONDARYCOLOR3IVPROC)load("glSecondaryColor3iv"); - glad_glSecondaryColor3s = (PFNGLSECONDARYCOLOR3SPROC)load("glSecondaryColor3s"); - glad_glSecondaryColor3sv = (PFNGLSECONDARYCOLOR3SVPROC)load("glSecondaryColor3sv"); - glad_glSecondaryColor3ub = (PFNGLSECONDARYCOLOR3UBPROC)load("glSecondaryColor3ub"); - glad_glSecondaryColor3ubv = (PFNGLSECONDARYCOLOR3UBVPROC)load("glSecondaryColor3ubv"); - glad_glSecondaryColor3ui = (PFNGLSECONDARYCOLOR3UIPROC)load("glSecondaryColor3ui"); - glad_glSecondaryColor3uiv = (PFNGLSECONDARYCOLOR3UIVPROC)load("glSecondaryColor3uiv"); - glad_glSecondaryColor3us = (PFNGLSECONDARYCOLOR3USPROC)load("glSecondaryColor3us"); - glad_glSecondaryColor3usv = (PFNGLSECONDARYCOLOR3USVPROC)load("glSecondaryColor3usv"); - glad_glSecondaryColorPointer = (PFNGLSECONDARYCOLORPOINTERPROC)load("glSecondaryColorPointer"); - glad_glWindowPos2d = (PFNGLWINDOWPOS2DPROC)load("glWindowPos2d"); - glad_glWindowPos2dv = (PFNGLWINDOWPOS2DVPROC)load("glWindowPos2dv"); - glad_glWindowPos2f = (PFNGLWINDOWPOS2FPROC)load("glWindowPos2f"); - glad_glWindowPos2fv = (PFNGLWINDOWPOS2FVPROC)load("glWindowPos2fv"); - glad_glWindowPos2i = (PFNGLWINDOWPOS2IPROC)load("glWindowPos2i"); - glad_glWindowPos2iv = (PFNGLWINDOWPOS2IVPROC)load("glWindowPos2iv"); - glad_glWindowPos2s = (PFNGLWINDOWPOS2SPROC)load("glWindowPos2s"); - glad_glWindowPos2sv = (PFNGLWINDOWPOS2SVPROC)load("glWindowPos2sv"); - glad_glWindowPos3d = (PFNGLWINDOWPOS3DPROC)load("glWindowPos3d"); - glad_glWindowPos3dv = (PFNGLWINDOWPOS3DVPROC)load("glWindowPos3dv"); - glad_glWindowPos3f = (PFNGLWINDOWPOS3FPROC)load("glWindowPos3f"); - glad_glWindowPos3fv = (PFNGLWINDOWPOS3FVPROC)load("glWindowPos3fv"); - glad_glWindowPos3i = (PFNGLWINDOWPOS3IPROC)load("glWindowPos3i"); - glad_glWindowPos3iv = (PFNGLWINDOWPOS3IVPROC)load("glWindowPos3iv"); - glad_glWindowPos3s = (PFNGLWINDOWPOS3SPROC)load("glWindowPos3s"); - glad_glWindowPos3sv = (PFNGLWINDOWPOS3SVPROC)load("glWindowPos3sv"); - glad_glBlendColor = (PFNGLBLENDCOLORPROC)load("glBlendColor"); - glad_glBlendEquation = (PFNGLBLENDEQUATIONPROC)load("glBlendEquation"); -} -static void load_GL_VERSION_1_5(GLADloadproc load) { - if(!GLAD_GL_VERSION_1_5) return; - glad_glGenQueries = (PFNGLGENQUERIESPROC)load("glGenQueries"); - glad_glDeleteQueries = (PFNGLDELETEQUERIESPROC)load("glDeleteQueries"); - glad_glIsQuery = (PFNGLISQUERYPROC)load("glIsQuery"); - glad_glBeginQuery = (PFNGLBEGINQUERYPROC)load("glBeginQuery"); - glad_glEndQuery = (PFNGLENDQUERYPROC)load("glEndQuery"); - glad_glGetQueryiv = (PFNGLGETQUERYIVPROC)load("glGetQueryiv"); - glad_glGetQueryObjectiv = (PFNGLGETQUERYOBJECTIVPROC)load("glGetQueryObjectiv"); - glad_glGetQueryObjectuiv = (PFNGLGETQUERYOBJECTUIVPROC)load("glGetQueryObjectuiv"); - glad_glBindBuffer = (PFNGLBINDBUFFERPROC)load("glBindBuffer"); - glad_glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)load("glDeleteBuffers"); - glad_glGenBuffers = (PFNGLGENBUFFERSPROC)load("glGenBuffers"); - glad_glIsBuffer = (PFNGLISBUFFERPROC)load("glIsBuffer"); - glad_glBufferData = (PFNGLBUFFERDATAPROC)load("glBufferData"); - glad_glBufferSubData = (PFNGLBUFFERSUBDATAPROC)load("glBufferSubData"); - glad_glGetBufferSubData = (PFNGLGETBUFFERSUBDATAPROC)load("glGetBufferSubData"); - glad_glMapBuffer = (PFNGLMAPBUFFERPROC)load("glMapBuffer"); - glad_glUnmapBuffer = (PFNGLUNMAPBUFFERPROC)load("glUnmapBuffer"); - glad_glGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVPROC)load("glGetBufferParameteriv"); - glad_glGetBufferPointerv = (PFNGLGETBUFFERPOINTERVPROC)load("glGetBufferPointerv"); -} -static void load_GL_VERSION_2_0(GLADloadproc load) { - if(!GLAD_GL_VERSION_2_0) return; - glad_glBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)load("glBlendEquationSeparate"); - glad_glDrawBuffers = (PFNGLDRAWBUFFERSPROC)load("glDrawBuffers"); - glad_glStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)load("glStencilOpSeparate"); - glad_glStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)load("glStencilFuncSeparate"); - glad_glStencilMaskSeparate = (PFNGLSTENCILMASKSEPARATEPROC)load("glStencilMaskSeparate"); - glad_glAttachShader = (PFNGLATTACHSHADERPROC)load("glAttachShader"); - glad_glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)load("glBindAttribLocation"); - glad_glCompileShader = (PFNGLCOMPILESHADERPROC)load("glCompileShader"); - glad_glCreateProgram = (PFNGLCREATEPROGRAMPROC)load("glCreateProgram"); - glad_glCreateShader = (PFNGLCREATESHADERPROC)load("glCreateShader"); - glad_glDeleteProgram = (PFNGLDELETEPROGRAMPROC)load("glDeleteProgram"); - glad_glDeleteShader = (PFNGLDELETESHADERPROC)load("glDeleteShader"); - glad_glDetachShader = (PFNGLDETACHSHADERPROC)load("glDetachShader"); - glad_glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)load("glDisableVertexAttribArray"); - glad_glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)load("glEnableVertexAttribArray"); - glad_glGetActiveAttrib = (PFNGLGETACTIVEATTRIBPROC)load("glGetActiveAttrib"); - glad_glGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)load("glGetActiveUniform"); - glad_glGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC)load("glGetAttachedShaders"); - glad_glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)load("glGetAttribLocation"); - glad_glGetProgramiv = (PFNGLGETPROGRAMIVPROC)load("glGetProgramiv"); - glad_glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)load("glGetProgramInfoLog"); - glad_glGetShaderiv = (PFNGLGETSHADERIVPROC)load("glGetShaderiv"); - glad_glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)load("glGetShaderInfoLog"); - glad_glGetShaderSource = (PFNGLGETSHADERSOURCEPROC)load("glGetShaderSource"); - glad_glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)load("glGetUniformLocation"); - glad_glGetUniformfv = (PFNGLGETUNIFORMFVPROC)load("glGetUniformfv"); - glad_glGetUniformiv = (PFNGLGETUNIFORMIVPROC)load("glGetUniformiv"); - glad_glGetVertexAttribdv = (PFNGLGETVERTEXATTRIBDVPROC)load("glGetVertexAttribdv"); - glad_glGetVertexAttribfv = (PFNGLGETVERTEXATTRIBFVPROC)load("glGetVertexAttribfv"); - glad_glGetVertexAttribiv = (PFNGLGETVERTEXATTRIBIVPROC)load("glGetVertexAttribiv"); - glad_glGetVertexAttribPointerv = (PFNGLGETVERTEXATTRIBPOINTERVPROC)load("glGetVertexAttribPointerv"); - glad_glIsProgram = (PFNGLISPROGRAMPROC)load("glIsProgram"); - glad_glIsShader = (PFNGLISSHADERPROC)load("glIsShader"); - glad_glLinkProgram = (PFNGLLINKPROGRAMPROC)load("glLinkProgram"); - glad_glShaderSource = (PFNGLSHADERSOURCEPROC)load("glShaderSource"); - glad_glUseProgram = (PFNGLUSEPROGRAMPROC)load("glUseProgram"); - glad_glUniform1f = (PFNGLUNIFORM1FPROC)load("glUniform1f"); - glad_glUniform2f = (PFNGLUNIFORM2FPROC)load("glUniform2f"); - glad_glUniform3f = (PFNGLUNIFORM3FPROC)load("glUniform3f"); - glad_glUniform4f = (PFNGLUNIFORM4FPROC)load("glUniform4f"); - glad_glUniform1i = (PFNGLUNIFORM1IPROC)load("glUniform1i"); - glad_glUniform2i = (PFNGLUNIFORM2IPROC)load("glUniform2i"); - glad_glUniform3i = (PFNGLUNIFORM3IPROC)load("glUniform3i"); - glad_glUniform4i = (PFNGLUNIFORM4IPROC)load("glUniform4i"); - glad_glUniform1fv = (PFNGLUNIFORM1FVPROC)load("glUniform1fv"); - glad_glUniform2fv = (PFNGLUNIFORM2FVPROC)load("glUniform2fv"); - glad_glUniform3fv = (PFNGLUNIFORM3FVPROC)load("glUniform3fv"); - glad_glUniform4fv = (PFNGLUNIFORM4FVPROC)load("glUniform4fv"); - glad_glUniform1iv = (PFNGLUNIFORM1IVPROC)load("glUniform1iv"); - glad_glUniform2iv = (PFNGLUNIFORM2IVPROC)load("glUniform2iv"); - glad_glUniform3iv = (PFNGLUNIFORM3IVPROC)load("glUniform3iv"); - glad_glUniform4iv = (PFNGLUNIFORM4IVPROC)load("glUniform4iv"); - glad_glUniformMatrix2fv = (PFNGLUNIFORMMATRIX2FVPROC)load("glUniformMatrix2fv"); - glad_glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)load("glUniformMatrix3fv"); - glad_glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)load("glUniformMatrix4fv"); - glad_glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)load("glValidateProgram"); - glad_glVertexAttrib1d = (PFNGLVERTEXATTRIB1DPROC)load("glVertexAttrib1d"); - glad_glVertexAttrib1dv = (PFNGLVERTEXATTRIB1DVPROC)load("glVertexAttrib1dv"); - glad_glVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC)load("glVertexAttrib1f"); - glad_glVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC)load("glVertexAttrib1fv"); - glad_glVertexAttrib1s = (PFNGLVERTEXATTRIB1SPROC)load("glVertexAttrib1s"); - glad_glVertexAttrib1sv = (PFNGLVERTEXATTRIB1SVPROC)load("glVertexAttrib1sv"); - glad_glVertexAttrib2d = (PFNGLVERTEXATTRIB2DPROC)load("glVertexAttrib2d"); - glad_glVertexAttrib2dv = (PFNGLVERTEXATTRIB2DVPROC)load("glVertexAttrib2dv"); - glad_glVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC)load("glVertexAttrib2f"); - glad_glVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC)load("glVertexAttrib2fv"); - glad_glVertexAttrib2s = (PFNGLVERTEXATTRIB2SPROC)load("glVertexAttrib2s"); - glad_glVertexAttrib2sv = (PFNGLVERTEXATTRIB2SVPROC)load("glVertexAttrib2sv"); - glad_glVertexAttrib3d = (PFNGLVERTEXATTRIB3DPROC)load("glVertexAttrib3d"); - glad_glVertexAttrib3dv = (PFNGLVERTEXATTRIB3DVPROC)load("glVertexAttrib3dv"); - glad_glVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC)load("glVertexAttrib3f"); - glad_glVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC)load("glVertexAttrib3fv"); - glad_glVertexAttrib3s = (PFNGLVERTEXATTRIB3SPROC)load("glVertexAttrib3s"); - glad_glVertexAttrib3sv = (PFNGLVERTEXATTRIB3SVPROC)load("glVertexAttrib3sv"); - glad_glVertexAttrib4Nbv = (PFNGLVERTEXATTRIB4NBVPROC)load("glVertexAttrib4Nbv"); - glad_glVertexAttrib4Niv = (PFNGLVERTEXATTRIB4NIVPROC)load("glVertexAttrib4Niv"); - glad_glVertexAttrib4Nsv = (PFNGLVERTEXATTRIB4NSVPROC)load("glVertexAttrib4Nsv"); - glad_glVertexAttrib4Nub = (PFNGLVERTEXATTRIB4NUBPROC)load("glVertexAttrib4Nub"); - glad_glVertexAttrib4Nubv = (PFNGLVERTEXATTRIB4NUBVPROC)load("glVertexAttrib4Nubv"); - glad_glVertexAttrib4Nuiv = (PFNGLVERTEXATTRIB4NUIVPROC)load("glVertexAttrib4Nuiv"); - glad_glVertexAttrib4Nusv = (PFNGLVERTEXATTRIB4NUSVPROC)load("glVertexAttrib4Nusv"); - glad_glVertexAttrib4bv = (PFNGLVERTEXATTRIB4BVPROC)load("glVertexAttrib4bv"); - glad_glVertexAttrib4d = (PFNGLVERTEXATTRIB4DPROC)load("glVertexAttrib4d"); - glad_glVertexAttrib4dv = (PFNGLVERTEXATTRIB4DVPROC)load("glVertexAttrib4dv"); - glad_glVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC)load("glVertexAttrib4f"); - glad_glVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC)load("glVertexAttrib4fv"); - glad_glVertexAttrib4iv = (PFNGLVERTEXATTRIB4IVPROC)load("glVertexAttrib4iv"); - glad_glVertexAttrib4s = (PFNGLVERTEXATTRIB4SPROC)load("glVertexAttrib4s"); - glad_glVertexAttrib4sv = (PFNGLVERTEXATTRIB4SVPROC)load("glVertexAttrib4sv"); - glad_glVertexAttrib4ubv = (PFNGLVERTEXATTRIB4UBVPROC)load("glVertexAttrib4ubv"); - glad_glVertexAttrib4uiv = (PFNGLVERTEXATTRIB4UIVPROC)load("glVertexAttrib4uiv"); - glad_glVertexAttrib4usv = (PFNGLVERTEXATTRIB4USVPROC)load("glVertexAttrib4usv"); - glad_glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)load("glVertexAttribPointer"); -} -static void load_GL_VERSION_2_1(GLADloadproc load) { - if(!GLAD_GL_VERSION_2_1) return; - glad_glUniformMatrix2x3fv = (PFNGLUNIFORMMATRIX2X3FVPROC)load("glUniformMatrix2x3fv"); - glad_glUniformMatrix3x2fv = (PFNGLUNIFORMMATRIX3X2FVPROC)load("glUniformMatrix3x2fv"); - glad_glUniformMatrix2x4fv = (PFNGLUNIFORMMATRIX2X4FVPROC)load("glUniformMatrix2x4fv"); - glad_glUniformMatrix4x2fv = (PFNGLUNIFORMMATRIX4X2FVPROC)load("glUniformMatrix4x2fv"); - glad_glUniformMatrix3x4fv = (PFNGLUNIFORMMATRIX3X4FVPROC)load("glUniformMatrix3x4fv"); - glad_glUniformMatrix4x3fv = (PFNGLUNIFORMMATRIX4X3FVPROC)load("glUniformMatrix4x3fv"); -} -static void load_GL_ARB_draw_buffers(GLADloadproc load) { - if(!GLAD_GL_ARB_draw_buffers) return; - glad_glDrawBuffersARB = (PFNGLDRAWBUFFERSARBPROC)load("glDrawBuffersARB"); -} -static void load_GL_ARB_draw_instanced(GLADloadproc load) { - if(!GLAD_GL_ARB_draw_instanced) return; - glad_glDrawArraysInstancedARB = (PFNGLDRAWARRAYSINSTANCEDARBPROC)load("glDrawArraysInstancedARB"); - glad_glDrawElementsInstancedARB = (PFNGLDRAWELEMENTSINSTANCEDARBPROC)load("glDrawElementsInstancedARB"); -} -static void load_GL_ARB_fragment_program(GLADloadproc load) { - if(!GLAD_GL_ARB_fragment_program) return; - glad_glProgramStringARB = (PFNGLPROGRAMSTRINGARBPROC)load("glProgramStringARB"); - glad_glBindProgramARB = (PFNGLBINDPROGRAMARBPROC)load("glBindProgramARB"); - glad_glDeleteProgramsARB = (PFNGLDELETEPROGRAMSARBPROC)load("glDeleteProgramsARB"); - glad_glGenProgramsARB = (PFNGLGENPROGRAMSARBPROC)load("glGenProgramsARB"); - glad_glProgramEnvParameter4dARB = (PFNGLPROGRAMENVPARAMETER4DARBPROC)load("glProgramEnvParameter4dARB"); - glad_glProgramEnvParameter4dvARB = (PFNGLPROGRAMENVPARAMETER4DVARBPROC)load("glProgramEnvParameter4dvARB"); - glad_glProgramEnvParameter4fARB = (PFNGLPROGRAMENVPARAMETER4FARBPROC)load("glProgramEnvParameter4fARB"); - glad_glProgramEnvParameter4fvARB = (PFNGLPROGRAMENVPARAMETER4FVARBPROC)load("glProgramEnvParameter4fvARB"); - glad_glProgramLocalParameter4dARB = (PFNGLPROGRAMLOCALPARAMETER4DARBPROC)load("glProgramLocalParameter4dARB"); - glad_glProgramLocalParameter4dvARB = (PFNGLPROGRAMLOCALPARAMETER4DVARBPROC)load("glProgramLocalParameter4dvARB"); - glad_glProgramLocalParameter4fARB = (PFNGLPROGRAMLOCALPARAMETER4FARBPROC)load("glProgramLocalParameter4fARB"); - glad_glProgramLocalParameter4fvARB = (PFNGLPROGRAMLOCALPARAMETER4FVARBPROC)load("glProgramLocalParameter4fvARB"); - glad_glGetProgramEnvParameterdvARB = (PFNGLGETPROGRAMENVPARAMETERDVARBPROC)load("glGetProgramEnvParameterdvARB"); - glad_glGetProgramEnvParameterfvARB = (PFNGLGETPROGRAMENVPARAMETERFVARBPROC)load("glGetProgramEnvParameterfvARB"); - glad_glGetProgramLocalParameterdvARB = (PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC)load("glGetProgramLocalParameterdvARB"); - glad_glGetProgramLocalParameterfvARB = (PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC)load("glGetProgramLocalParameterfvARB"); - glad_glGetProgramivARB = (PFNGLGETPROGRAMIVARBPROC)load("glGetProgramivARB"); - glad_glGetProgramStringARB = (PFNGLGETPROGRAMSTRINGARBPROC)load("glGetProgramStringARB"); - glad_glIsProgramARB = (PFNGLISPROGRAMARBPROC)load("glIsProgramARB"); -} -static void load_GL_ARB_framebuffer_object(GLADloadproc load) { - if(!GLAD_GL_ARB_framebuffer_object) return; - glad_glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)load("glIsRenderbuffer"); - glad_glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)load("glBindRenderbuffer"); - glad_glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)load("glDeleteRenderbuffers"); - glad_glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)load("glGenRenderbuffers"); - glad_glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)load("glRenderbufferStorage"); - glad_glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)load("glGetRenderbufferParameteriv"); - glad_glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)load("glIsFramebuffer"); - glad_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)load("glBindFramebuffer"); - glad_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)load("glDeleteFramebuffers"); - glad_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)load("glGenFramebuffers"); - glad_glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)load("glCheckFramebufferStatus"); - glad_glFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC)load("glFramebufferTexture1D"); - glad_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)load("glFramebufferTexture2D"); - glad_glFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC)load("glFramebufferTexture3D"); - glad_glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)load("glFramebufferRenderbuffer"); - glad_glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)load("glGetFramebufferAttachmentParameteriv"); - glad_glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)load("glGenerateMipmap"); - glad_glBlitFramebuffer = (PFNGLBLITFRAMEBUFFERPROC)load("glBlitFramebuffer"); - glad_glRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)load("glRenderbufferStorageMultisample"); - glad_glFramebufferTextureLayer = (PFNGLFRAMEBUFFERTEXTURELAYERPROC)load("glFramebufferTextureLayer"); -} -static void load_GL_ARB_get_program_binary(GLADloadproc load) { - if(!GLAD_GL_ARB_get_program_binary) return; - glad_glGetProgramBinary = (PFNGLGETPROGRAMBINARYPROC)load("glGetProgramBinary"); - glad_glProgramBinary = (PFNGLPROGRAMBINARYPROC)load("glProgramBinary"); - glad_glProgramParameteri = (PFNGLPROGRAMPARAMETERIPROC)load("glProgramParameteri"); -} -static void load_GL_ARB_instanced_arrays(GLADloadproc load) { - if(!GLAD_GL_ARB_instanced_arrays) return; - glad_glVertexAttribDivisorARB = (PFNGLVERTEXATTRIBDIVISORARBPROC)load("glVertexAttribDivisorARB"); -} -static void load_GL_ARB_multisample(GLADloadproc load) { - if(!GLAD_GL_ARB_multisample) return; - glad_glSampleCoverageARB = (PFNGLSAMPLECOVERAGEARBPROC)load("glSampleCoverageARB"); -} -static void load_GL_ARB_multitexture(GLADloadproc load) { - if(!GLAD_GL_ARB_multitexture) return; - glad_glActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC)load("glActiveTextureARB"); - glad_glClientActiveTextureARB = (PFNGLCLIENTACTIVETEXTUREARBPROC)load("glClientActiveTextureARB"); - glad_glMultiTexCoord1dARB = (PFNGLMULTITEXCOORD1DARBPROC)load("glMultiTexCoord1dARB"); - glad_glMultiTexCoord1dvARB = (PFNGLMULTITEXCOORD1DVARBPROC)load("glMultiTexCoord1dvARB"); - glad_glMultiTexCoord1fARB = (PFNGLMULTITEXCOORD1FARBPROC)load("glMultiTexCoord1fARB"); - glad_glMultiTexCoord1fvARB = (PFNGLMULTITEXCOORD1FVARBPROC)load("glMultiTexCoord1fvARB"); - glad_glMultiTexCoord1iARB = (PFNGLMULTITEXCOORD1IARBPROC)load("glMultiTexCoord1iARB"); - glad_glMultiTexCoord1ivARB = (PFNGLMULTITEXCOORD1IVARBPROC)load("glMultiTexCoord1ivARB"); - glad_glMultiTexCoord1sARB = (PFNGLMULTITEXCOORD1SARBPROC)load("glMultiTexCoord1sARB"); - glad_glMultiTexCoord1svARB = (PFNGLMULTITEXCOORD1SVARBPROC)load("glMultiTexCoord1svARB"); - glad_glMultiTexCoord2dARB = (PFNGLMULTITEXCOORD2DARBPROC)load("glMultiTexCoord2dARB"); - glad_glMultiTexCoord2dvARB = (PFNGLMULTITEXCOORD2DVARBPROC)load("glMultiTexCoord2dvARB"); - glad_glMultiTexCoord2fARB = (PFNGLMULTITEXCOORD2FARBPROC)load("glMultiTexCoord2fARB"); - glad_glMultiTexCoord2fvARB = (PFNGLMULTITEXCOORD2FVARBPROC)load("glMultiTexCoord2fvARB"); - glad_glMultiTexCoord2iARB = (PFNGLMULTITEXCOORD2IARBPROC)load("glMultiTexCoord2iARB"); - glad_glMultiTexCoord2ivARB = (PFNGLMULTITEXCOORD2IVARBPROC)load("glMultiTexCoord2ivARB"); - glad_glMultiTexCoord2sARB = (PFNGLMULTITEXCOORD2SARBPROC)load("glMultiTexCoord2sARB"); - glad_glMultiTexCoord2svARB = (PFNGLMULTITEXCOORD2SVARBPROC)load("glMultiTexCoord2svARB"); - glad_glMultiTexCoord3dARB = (PFNGLMULTITEXCOORD3DARBPROC)load("glMultiTexCoord3dARB"); - glad_glMultiTexCoord3dvARB = (PFNGLMULTITEXCOORD3DVARBPROC)load("glMultiTexCoord3dvARB"); - glad_glMultiTexCoord3fARB = (PFNGLMULTITEXCOORD3FARBPROC)load("glMultiTexCoord3fARB"); - glad_glMultiTexCoord3fvARB = (PFNGLMULTITEXCOORD3FVARBPROC)load("glMultiTexCoord3fvARB"); - glad_glMultiTexCoord3iARB = (PFNGLMULTITEXCOORD3IARBPROC)load("glMultiTexCoord3iARB"); - glad_glMultiTexCoord3ivARB = (PFNGLMULTITEXCOORD3IVARBPROC)load("glMultiTexCoord3ivARB"); - glad_glMultiTexCoord3sARB = (PFNGLMULTITEXCOORD3SARBPROC)load("glMultiTexCoord3sARB"); - glad_glMultiTexCoord3svARB = (PFNGLMULTITEXCOORD3SVARBPROC)load("glMultiTexCoord3svARB"); - glad_glMultiTexCoord4dARB = (PFNGLMULTITEXCOORD4DARBPROC)load("glMultiTexCoord4dARB"); - glad_glMultiTexCoord4dvARB = (PFNGLMULTITEXCOORD4DVARBPROC)load("glMultiTexCoord4dvARB"); - glad_glMultiTexCoord4fARB = (PFNGLMULTITEXCOORD4FARBPROC)load("glMultiTexCoord4fARB"); - glad_glMultiTexCoord4fvARB = (PFNGLMULTITEXCOORD4FVARBPROC)load("glMultiTexCoord4fvARB"); - glad_glMultiTexCoord4iARB = (PFNGLMULTITEXCOORD4IARBPROC)load("glMultiTexCoord4iARB"); - glad_glMultiTexCoord4ivARB = (PFNGLMULTITEXCOORD4IVARBPROC)load("glMultiTexCoord4ivARB"); - glad_glMultiTexCoord4sARB = (PFNGLMULTITEXCOORD4SARBPROC)load("glMultiTexCoord4sARB"); - glad_glMultiTexCoord4svARB = (PFNGLMULTITEXCOORD4SVARBPROC)load("glMultiTexCoord4svARB"); -} -static void load_GL_ARB_occlusion_query(GLADloadproc load) { - if(!GLAD_GL_ARB_occlusion_query) return; - glad_glGenQueriesARB = (PFNGLGENQUERIESARBPROC)load("glGenQueriesARB"); - glad_glDeleteQueriesARB = (PFNGLDELETEQUERIESARBPROC)load("glDeleteQueriesARB"); - glad_glIsQueryARB = (PFNGLISQUERYARBPROC)load("glIsQueryARB"); - glad_glBeginQueryARB = (PFNGLBEGINQUERYARBPROC)load("glBeginQueryARB"); - glad_glEndQueryARB = (PFNGLENDQUERYARBPROC)load("glEndQueryARB"); - glad_glGetQueryivARB = (PFNGLGETQUERYIVARBPROC)load("glGetQueryivARB"); - glad_glGetQueryObjectivARB = (PFNGLGETQUERYOBJECTIVARBPROC)load("glGetQueryObjectivARB"); - glad_glGetQueryObjectuivARB = (PFNGLGETQUERYOBJECTUIVARBPROC)load("glGetQueryObjectuivARB"); -} -static void load_GL_ARB_point_parameters(GLADloadproc load) { - if(!GLAD_GL_ARB_point_parameters) return; - glad_glPointParameterfARB = (PFNGLPOINTPARAMETERFARBPROC)load("glPointParameterfARB"); - glad_glPointParameterfvARB = (PFNGLPOINTPARAMETERFVARBPROC)load("glPointParameterfvARB"); -} -static void load_GL_ARB_shader_objects(GLADloadproc load) { - if(!GLAD_GL_ARB_shader_objects) return; - glad_glDeleteObjectARB = (PFNGLDELETEOBJECTARBPROC)load("glDeleteObjectARB"); - glad_glGetHandleARB = (PFNGLGETHANDLEARBPROC)load("glGetHandleARB"); - glad_glDetachObjectARB = (PFNGLDETACHOBJECTARBPROC)load("glDetachObjectARB"); - glad_glCreateShaderObjectARB = (PFNGLCREATESHADEROBJECTARBPROC)load("glCreateShaderObjectARB"); - glad_glShaderSourceARB = (PFNGLSHADERSOURCEARBPROC)load("glShaderSourceARB"); - glad_glCompileShaderARB = (PFNGLCOMPILESHADERARBPROC)load("glCompileShaderARB"); - glad_glCreateProgramObjectARB = (PFNGLCREATEPROGRAMOBJECTARBPROC)load("glCreateProgramObjectARB"); - glad_glAttachObjectARB = (PFNGLATTACHOBJECTARBPROC)load("glAttachObjectARB"); - glad_glLinkProgramARB = (PFNGLLINKPROGRAMARBPROC)load("glLinkProgramARB"); - glad_glUseProgramObjectARB = (PFNGLUSEPROGRAMOBJECTARBPROC)load("glUseProgramObjectARB"); - glad_glValidateProgramARB = (PFNGLVALIDATEPROGRAMARBPROC)load("glValidateProgramARB"); - glad_glUniform1fARB = (PFNGLUNIFORM1FARBPROC)load("glUniform1fARB"); - glad_glUniform2fARB = (PFNGLUNIFORM2FARBPROC)load("glUniform2fARB"); - glad_glUniform3fARB = (PFNGLUNIFORM3FARBPROC)load("glUniform3fARB"); - glad_glUniform4fARB = (PFNGLUNIFORM4FARBPROC)load("glUniform4fARB"); - glad_glUniform1iARB = (PFNGLUNIFORM1IARBPROC)load("glUniform1iARB"); - glad_glUniform2iARB = (PFNGLUNIFORM2IARBPROC)load("glUniform2iARB"); - glad_glUniform3iARB = (PFNGLUNIFORM3IARBPROC)load("glUniform3iARB"); - glad_glUniform4iARB = (PFNGLUNIFORM4IARBPROC)load("glUniform4iARB"); - glad_glUniform1fvARB = (PFNGLUNIFORM1FVARBPROC)load("glUniform1fvARB"); - glad_glUniform2fvARB = (PFNGLUNIFORM2FVARBPROC)load("glUniform2fvARB"); - glad_glUniform3fvARB = (PFNGLUNIFORM3FVARBPROC)load("glUniform3fvARB"); - glad_glUniform4fvARB = (PFNGLUNIFORM4FVARBPROC)load("glUniform4fvARB"); - glad_glUniform1ivARB = (PFNGLUNIFORM1IVARBPROC)load("glUniform1ivARB"); - glad_glUniform2ivARB = (PFNGLUNIFORM2IVARBPROC)load("glUniform2ivARB"); - glad_glUniform3ivARB = (PFNGLUNIFORM3IVARBPROC)load("glUniform3ivARB"); - glad_glUniform4ivARB = (PFNGLUNIFORM4IVARBPROC)load("glUniform4ivARB"); - glad_glUniformMatrix2fvARB = (PFNGLUNIFORMMATRIX2FVARBPROC)load("glUniformMatrix2fvARB"); - glad_glUniformMatrix3fvARB = (PFNGLUNIFORMMATRIX3FVARBPROC)load("glUniformMatrix3fvARB"); - glad_glUniformMatrix4fvARB = (PFNGLUNIFORMMATRIX4FVARBPROC)load("glUniformMatrix4fvARB"); - glad_glGetObjectParameterfvARB = (PFNGLGETOBJECTPARAMETERFVARBPROC)load("glGetObjectParameterfvARB"); - glad_glGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIVARBPROC)load("glGetObjectParameterivARB"); - glad_glGetInfoLogARB = (PFNGLGETINFOLOGARBPROC)load("glGetInfoLogARB"); - glad_glGetAttachedObjectsARB = (PFNGLGETATTACHEDOBJECTSARBPROC)load("glGetAttachedObjectsARB"); - glad_glGetUniformLocationARB = (PFNGLGETUNIFORMLOCATIONARBPROC)load("glGetUniformLocationARB"); - glad_glGetActiveUniformARB = (PFNGLGETACTIVEUNIFORMARBPROC)load("glGetActiveUniformARB"); - glad_glGetUniformfvARB = (PFNGLGETUNIFORMFVARBPROC)load("glGetUniformfvARB"); - glad_glGetUniformivARB = (PFNGLGETUNIFORMIVARBPROC)load("glGetUniformivARB"); - glad_glGetShaderSourceARB = (PFNGLGETSHADERSOURCEARBPROC)load("glGetShaderSourceARB"); -} -static void load_GL_ARB_texture_compression(GLADloadproc load) { - if(!GLAD_GL_ARB_texture_compression) return; - glad_glCompressedTexImage3DARB = (PFNGLCOMPRESSEDTEXIMAGE3DARBPROC)load("glCompressedTexImage3DARB"); - glad_glCompressedTexImage2DARB = (PFNGLCOMPRESSEDTEXIMAGE2DARBPROC)load("glCompressedTexImage2DARB"); - glad_glCompressedTexImage1DARB = (PFNGLCOMPRESSEDTEXIMAGE1DARBPROC)load("glCompressedTexImage1DARB"); - glad_glCompressedTexSubImage3DARB = (PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC)load("glCompressedTexSubImage3DARB"); - glad_glCompressedTexSubImage2DARB = (PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC)load("glCompressedTexSubImage2DARB"); - glad_glCompressedTexSubImage1DARB = (PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC)load("glCompressedTexSubImage1DARB"); - glad_glGetCompressedTexImageARB = (PFNGLGETCOMPRESSEDTEXIMAGEARBPROC)load("glGetCompressedTexImageARB"); -} -static void load_GL_ARB_vertex_buffer_object(GLADloadproc load) { - if(!GLAD_GL_ARB_vertex_buffer_object) return; - glad_glBindBufferARB = (PFNGLBINDBUFFERARBPROC)load("glBindBufferARB"); - glad_glDeleteBuffersARB = (PFNGLDELETEBUFFERSARBPROC)load("glDeleteBuffersARB"); - glad_glGenBuffersARB = (PFNGLGENBUFFERSARBPROC)load("glGenBuffersARB"); - glad_glIsBufferARB = (PFNGLISBUFFERARBPROC)load("glIsBufferARB"); - glad_glBufferDataARB = (PFNGLBUFFERDATAARBPROC)load("glBufferDataARB"); - glad_glBufferSubDataARB = (PFNGLBUFFERSUBDATAARBPROC)load("glBufferSubDataARB"); - glad_glGetBufferSubDataARB = (PFNGLGETBUFFERSUBDATAARBPROC)load("glGetBufferSubDataARB"); - glad_glMapBufferARB = (PFNGLMAPBUFFERARBPROC)load("glMapBufferARB"); - glad_glUnmapBufferARB = (PFNGLUNMAPBUFFERARBPROC)load("glUnmapBufferARB"); - glad_glGetBufferParameterivARB = (PFNGLGETBUFFERPARAMETERIVARBPROC)load("glGetBufferParameterivARB"); - glad_glGetBufferPointervARB = (PFNGLGETBUFFERPOINTERVARBPROC)load("glGetBufferPointervARB"); -} -static void load_GL_ARB_vertex_program(GLADloadproc load) { - if(!GLAD_GL_ARB_vertex_program) return; - glad_glVertexAttrib1dARB = (PFNGLVERTEXATTRIB1DARBPROC)load("glVertexAttrib1dARB"); - glad_glVertexAttrib1dvARB = (PFNGLVERTEXATTRIB1DVARBPROC)load("glVertexAttrib1dvARB"); - glad_glVertexAttrib1fARB = (PFNGLVERTEXATTRIB1FARBPROC)load("glVertexAttrib1fARB"); - glad_glVertexAttrib1fvARB = (PFNGLVERTEXATTRIB1FVARBPROC)load("glVertexAttrib1fvARB"); - glad_glVertexAttrib1sARB = (PFNGLVERTEXATTRIB1SARBPROC)load("glVertexAttrib1sARB"); - glad_glVertexAttrib1svARB = (PFNGLVERTEXATTRIB1SVARBPROC)load("glVertexAttrib1svARB"); - glad_glVertexAttrib2dARB = (PFNGLVERTEXATTRIB2DARBPROC)load("glVertexAttrib2dARB"); - glad_glVertexAttrib2dvARB = (PFNGLVERTEXATTRIB2DVARBPROC)load("glVertexAttrib2dvARB"); - glad_glVertexAttrib2fARB = (PFNGLVERTEXATTRIB2FARBPROC)load("glVertexAttrib2fARB"); - glad_glVertexAttrib2fvARB = (PFNGLVERTEXATTRIB2FVARBPROC)load("glVertexAttrib2fvARB"); - glad_glVertexAttrib2sARB = (PFNGLVERTEXATTRIB2SARBPROC)load("glVertexAttrib2sARB"); - glad_glVertexAttrib2svARB = (PFNGLVERTEXATTRIB2SVARBPROC)load("glVertexAttrib2svARB"); - glad_glVertexAttrib3dARB = (PFNGLVERTEXATTRIB3DARBPROC)load("glVertexAttrib3dARB"); - glad_glVertexAttrib3dvARB = (PFNGLVERTEXATTRIB3DVARBPROC)load("glVertexAttrib3dvARB"); - glad_glVertexAttrib3fARB = (PFNGLVERTEXATTRIB3FARBPROC)load("glVertexAttrib3fARB"); - glad_glVertexAttrib3fvARB = (PFNGLVERTEXATTRIB3FVARBPROC)load("glVertexAttrib3fvARB"); - glad_glVertexAttrib3sARB = (PFNGLVERTEXATTRIB3SARBPROC)load("glVertexAttrib3sARB"); - glad_glVertexAttrib3svARB = (PFNGLVERTEXATTRIB3SVARBPROC)load("glVertexAttrib3svARB"); - glad_glVertexAttrib4NbvARB = (PFNGLVERTEXATTRIB4NBVARBPROC)load("glVertexAttrib4NbvARB"); - glad_glVertexAttrib4NivARB = (PFNGLVERTEXATTRIB4NIVARBPROC)load("glVertexAttrib4NivARB"); - glad_glVertexAttrib4NsvARB = (PFNGLVERTEXATTRIB4NSVARBPROC)load("glVertexAttrib4NsvARB"); - glad_glVertexAttrib4NubARB = (PFNGLVERTEXATTRIB4NUBARBPROC)load("glVertexAttrib4NubARB"); - glad_glVertexAttrib4NubvARB = (PFNGLVERTEXATTRIB4NUBVARBPROC)load("glVertexAttrib4NubvARB"); - glad_glVertexAttrib4NuivARB = (PFNGLVERTEXATTRIB4NUIVARBPROC)load("glVertexAttrib4NuivARB"); - glad_glVertexAttrib4NusvARB = (PFNGLVERTEXATTRIB4NUSVARBPROC)load("glVertexAttrib4NusvARB"); - glad_glVertexAttrib4bvARB = (PFNGLVERTEXATTRIB4BVARBPROC)load("glVertexAttrib4bvARB"); - glad_glVertexAttrib4dARB = (PFNGLVERTEXATTRIB4DARBPROC)load("glVertexAttrib4dARB"); - glad_glVertexAttrib4dvARB = (PFNGLVERTEXATTRIB4DVARBPROC)load("glVertexAttrib4dvARB"); - glad_glVertexAttrib4fARB = (PFNGLVERTEXATTRIB4FARBPROC)load("glVertexAttrib4fARB"); - glad_glVertexAttrib4fvARB = (PFNGLVERTEXATTRIB4FVARBPROC)load("glVertexAttrib4fvARB"); - glad_glVertexAttrib4ivARB = (PFNGLVERTEXATTRIB4IVARBPROC)load("glVertexAttrib4ivARB"); - glad_glVertexAttrib4sARB = (PFNGLVERTEXATTRIB4SARBPROC)load("glVertexAttrib4sARB"); - glad_glVertexAttrib4svARB = (PFNGLVERTEXATTRIB4SVARBPROC)load("glVertexAttrib4svARB"); - glad_glVertexAttrib4ubvARB = (PFNGLVERTEXATTRIB4UBVARBPROC)load("glVertexAttrib4ubvARB"); - glad_glVertexAttrib4uivARB = (PFNGLVERTEXATTRIB4UIVARBPROC)load("glVertexAttrib4uivARB"); - glad_glVertexAttrib4usvARB = (PFNGLVERTEXATTRIB4USVARBPROC)load("glVertexAttrib4usvARB"); - glad_glVertexAttribPointerARB = (PFNGLVERTEXATTRIBPOINTERARBPROC)load("glVertexAttribPointerARB"); - glad_glEnableVertexAttribArrayARB = (PFNGLENABLEVERTEXATTRIBARRAYARBPROC)load("glEnableVertexAttribArrayARB"); - glad_glDisableVertexAttribArrayARB = (PFNGLDISABLEVERTEXATTRIBARRAYARBPROC)load("glDisableVertexAttribArrayARB"); - glad_glProgramStringARB = (PFNGLPROGRAMSTRINGARBPROC)load("glProgramStringARB"); - glad_glBindProgramARB = (PFNGLBINDPROGRAMARBPROC)load("glBindProgramARB"); - glad_glDeleteProgramsARB = (PFNGLDELETEPROGRAMSARBPROC)load("glDeleteProgramsARB"); - glad_glGenProgramsARB = (PFNGLGENPROGRAMSARBPROC)load("glGenProgramsARB"); - glad_glProgramEnvParameter4dARB = (PFNGLPROGRAMENVPARAMETER4DARBPROC)load("glProgramEnvParameter4dARB"); - glad_glProgramEnvParameter4dvARB = (PFNGLPROGRAMENVPARAMETER4DVARBPROC)load("glProgramEnvParameter4dvARB"); - glad_glProgramEnvParameter4fARB = (PFNGLPROGRAMENVPARAMETER4FARBPROC)load("glProgramEnvParameter4fARB"); - glad_glProgramEnvParameter4fvARB = (PFNGLPROGRAMENVPARAMETER4FVARBPROC)load("glProgramEnvParameter4fvARB"); - glad_glProgramLocalParameter4dARB = (PFNGLPROGRAMLOCALPARAMETER4DARBPROC)load("glProgramLocalParameter4dARB"); - glad_glProgramLocalParameter4dvARB = (PFNGLPROGRAMLOCALPARAMETER4DVARBPROC)load("glProgramLocalParameter4dvARB"); - glad_glProgramLocalParameter4fARB = (PFNGLPROGRAMLOCALPARAMETER4FARBPROC)load("glProgramLocalParameter4fARB"); - glad_glProgramLocalParameter4fvARB = (PFNGLPROGRAMLOCALPARAMETER4FVARBPROC)load("glProgramLocalParameter4fvARB"); - glad_glGetProgramEnvParameterdvARB = (PFNGLGETPROGRAMENVPARAMETERDVARBPROC)load("glGetProgramEnvParameterdvARB"); - glad_glGetProgramEnvParameterfvARB = (PFNGLGETPROGRAMENVPARAMETERFVARBPROC)load("glGetProgramEnvParameterfvARB"); - glad_glGetProgramLocalParameterdvARB = (PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC)load("glGetProgramLocalParameterdvARB"); - glad_glGetProgramLocalParameterfvARB = (PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC)load("glGetProgramLocalParameterfvARB"); - glad_glGetProgramivARB = (PFNGLGETPROGRAMIVARBPROC)load("glGetProgramivARB"); - glad_glGetProgramStringARB = (PFNGLGETPROGRAMSTRINGARBPROC)load("glGetProgramStringARB"); - glad_glGetVertexAttribdvARB = (PFNGLGETVERTEXATTRIBDVARBPROC)load("glGetVertexAttribdvARB"); - glad_glGetVertexAttribfvARB = (PFNGLGETVERTEXATTRIBFVARBPROC)load("glGetVertexAttribfvARB"); - glad_glGetVertexAttribivARB = (PFNGLGETVERTEXATTRIBIVARBPROC)load("glGetVertexAttribivARB"); - glad_glGetVertexAttribPointervARB = (PFNGLGETVERTEXATTRIBPOINTERVARBPROC)load("glGetVertexAttribPointervARB"); - glad_glIsProgramARB = (PFNGLISPROGRAMARBPROC)load("glIsProgramARB"); -} -static void load_GL_ARB_vertex_shader(GLADloadproc load) { - if(!GLAD_GL_ARB_vertex_shader) return; - glad_glVertexAttrib1fARB = (PFNGLVERTEXATTRIB1FARBPROC)load("glVertexAttrib1fARB"); - glad_glVertexAttrib1sARB = (PFNGLVERTEXATTRIB1SARBPROC)load("glVertexAttrib1sARB"); - glad_glVertexAttrib1dARB = (PFNGLVERTEXATTRIB1DARBPROC)load("glVertexAttrib1dARB"); - glad_glVertexAttrib2fARB = (PFNGLVERTEXATTRIB2FARBPROC)load("glVertexAttrib2fARB"); - glad_glVertexAttrib2sARB = (PFNGLVERTEXATTRIB2SARBPROC)load("glVertexAttrib2sARB"); - glad_glVertexAttrib2dARB = (PFNGLVERTEXATTRIB2DARBPROC)load("glVertexAttrib2dARB"); - glad_glVertexAttrib3fARB = (PFNGLVERTEXATTRIB3FARBPROC)load("glVertexAttrib3fARB"); - glad_glVertexAttrib3sARB = (PFNGLVERTEXATTRIB3SARBPROC)load("glVertexAttrib3sARB"); - glad_glVertexAttrib3dARB = (PFNGLVERTEXATTRIB3DARBPROC)load("glVertexAttrib3dARB"); - glad_glVertexAttrib4fARB = (PFNGLVERTEXATTRIB4FARBPROC)load("glVertexAttrib4fARB"); - glad_glVertexAttrib4sARB = (PFNGLVERTEXATTRIB4SARBPROC)load("glVertexAttrib4sARB"); - glad_glVertexAttrib4dARB = (PFNGLVERTEXATTRIB4DARBPROC)load("glVertexAttrib4dARB"); - glad_glVertexAttrib4NubARB = (PFNGLVERTEXATTRIB4NUBARBPROC)load("glVertexAttrib4NubARB"); - glad_glVertexAttrib1fvARB = (PFNGLVERTEXATTRIB1FVARBPROC)load("glVertexAttrib1fvARB"); - glad_glVertexAttrib1svARB = (PFNGLVERTEXATTRIB1SVARBPROC)load("glVertexAttrib1svARB"); - glad_glVertexAttrib1dvARB = (PFNGLVERTEXATTRIB1DVARBPROC)load("glVertexAttrib1dvARB"); - glad_glVertexAttrib2fvARB = (PFNGLVERTEXATTRIB2FVARBPROC)load("glVertexAttrib2fvARB"); - glad_glVertexAttrib2svARB = (PFNGLVERTEXATTRIB2SVARBPROC)load("glVertexAttrib2svARB"); - glad_glVertexAttrib2dvARB = (PFNGLVERTEXATTRIB2DVARBPROC)load("glVertexAttrib2dvARB"); - glad_glVertexAttrib3fvARB = (PFNGLVERTEXATTRIB3FVARBPROC)load("glVertexAttrib3fvARB"); - glad_glVertexAttrib3svARB = (PFNGLVERTEXATTRIB3SVARBPROC)load("glVertexAttrib3svARB"); - glad_glVertexAttrib3dvARB = (PFNGLVERTEXATTRIB3DVARBPROC)load("glVertexAttrib3dvARB"); - glad_glVertexAttrib4fvARB = (PFNGLVERTEXATTRIB4FVARBPROC)load("glVertexAttrib4fvARB"); - glad_glVertexAttrib4svARB = (PFNGLVERTEXATTRIB4SVARBPROC)load("glVertexAttrib4svARB"); - glad_glVertexAttrib4dvARB = (PFNGLVERTEXATTRIB4DVARBPROC)load("glVertexAttrib4dvARB"); - glad_glVertexAttrib4ivARB = (PFNGLVERTEXATTRIB4IVARBPROC)load("glVertexAttrib4ivARB"); - glad_glVertexAttrib4bvARB = (PFNGLVERTEXATTRIB4BVARBPROC)load("glVertexAttrib4bvARB"); - glad_glVertexAttrib4ubvARB = (PFNGLVERTEXATTRIB4UBVARBPROC)load("glVertexAttrib4ubvARB"); - glad_glVertexAttrib4usvARB = (PFNGLVERTEXATTRIB4USVARBPROC)load("glVertexAttrib4usvARB"); - glad_glVertexAttrib4uivARB = (PFNGLVERTEXATTRIB4UIVARBPROC)load("glVertexAttrib4uivARB"); - glad_glVertexAttrib4NbvARB = (PFNGLVERTEXATTRIB4NBVARBPROC)load("glVertexAttrib4NbvARB"); - glad_glVertexAttrib4NsvARB = (PFNGLVERTEXATTRIB4NSVARBPROC)load("glVertexAttrib4NsvARB"); - glad_glVertexAttrib4NivARB = (PFNGLVERTEXATTRIB4NIVARBPROC)load("glVertexAttrib4NivARB"); - glad_glVertexAttrib4NubvARB = (PFNGLVERTEXATTRIB4NUBVARBPROC)load("glVertexAttrib4NubvARB"); - glad_glVertexAttrib4NusvARB = (PFNGLVERTEXATTRIB4NUSVARBPROC)load("glVertexAttrib4NusvARB"); - glad_glVertexAttrib4NuivARB = (PFNGLVERTEXATTRIB4NUIVARBPROC)load("glVertexAttrib4NuivARB"); - glad_glVertexAttribPointerARB = (PFNGLVERTEXATTRIBPOINTERARBPROC)load("glVertexAttribPointerARB"); - glad_glEnableVertexAttribArrayARB = (PFNGLENABLEVERTEXATTRIBARRAYARBPROC)load("glEnableVertexAttribArrayARB"); - glad_glDisableVertexAttribArrayARB = (PFNGLDISABLEVERTEXATTRIBARRAYARBPROC)load("glDisableVertexAttribArrayARB"); - glad_glBindAttribLocationARB = (PFNGLBINDATTRIBLOCATIONARBPROC)load("glBindAttribLocationARB"); - glad_glGetActiveAttribARB = (PFNGLGETACTIVEATTRIBARBPROC)load("glGetActiveAttribARB"); - glad_glGetAttribLocationARB = (PFNGLGETATTRIBLOCATIONARBPROC)load("glGetAttribLocationARB"); - glad_glGetVertexAttribdvARB = (PFNGLGETVERTEXATTRIBDVARBPROC)load("glGetVertexAttribdvARB"); - glad_glGetVertexAttribfvARB = (PFNGLGETVERTEXATTRIBFVARBPROC)load("glGetVertexAttribfvARB"); - glad_glGetVertexAttribivARB = (PFNGLGETVERTEXATTRIBIVARBPROC)load("glGetVertexAttribivARB"); - glad_glGetVertexAttribPointervARB = (PFNGLGETVERTEXATTRIBPOINTERVARBPROC)load("glGetVertexAttribPointervARB"); -} -static void load_GL_ATI_draw_buffers(GLADloadproc load) { - if(!GLAD_GL_ATI_draw_buffers) return; - glad_glDrawBuffersATI = (PFNGLDRAWBUFFERSATIPROC)load("glDrawBuffersATI"); -} -static void load_GL_ATI_fragment_shader(GLADloadproc load) { - if(!GLAD_GL_ATI_fragment_shader) return; - glad_glGenFragmentShadersATI = (PFNGLGENFRAGMENTSHADERSATIPROC)load("glGenFragmentShadersATI"); - glad_glBindFragmentShaderATI = (PFNGLBINDFRAGMENTSHADERATIPROC)load("glBindFragmentShaderATI"); - glad_glDeleteFragmentShaderATI = (PFNGLDELETEFRAGMENTSHADERATIPROC)load("glDeleteFragmentShaderATI"); - glad_glBeginFragmentShaderATI = (PFNGLBEGINFRAGMENTSHADERATIPROC)load("glBeginFragmentShaderATI"); - glad_glEndFragmentShaderATI = (PFNGLENDFRAGMENTSHADERATIPROC)load("glEndFragmentShaderATI"); - glad_glPassTexCoordATI = (PFNGLPASSTEXCOORDATIPROC)load("glPassTexCoordATI"); - glad_glSampleMapATI = (PFNGLSAMPLEMAPATIPROC)load("glSampleMapATI"); - glad_glColorFragmentOp1ATI = (PFNGLCOLORFRAGMENTOP1ATIPROC)load("glColorFragmentOp1ATI"); - glad_glColorFragmentOp2ATI = (PFNGLCOLORFRAGMENTOP2ATIPROC)load("glColorFragmentOp2ATI"); - glad_glColorFragmentOp3ATI = (PFNGLCOLORFRAGMENTOP3ATIPROC)load("glColorFragmentOp3ATI"); - glad_glAlphaFragmentOp1ATI = (PFNGLALPHAFRAGMENTOP1ATIPROC)load("glAlphaFragmentOp1ATI"); - glad_glAlphaFragmentOp2ATI = (PFNGLALPHAFRAGMENTOP2ATIPROC)load("glAlphaFragmentOp2ATI"); - glad_glAlphaFragmentOp3ATI = (PFNGLALPHAFRAGMENTOP3ATIPROC)load("glAlphaFragmentOp3ATI"); - glad_glSetFragmentShaderConstantATI = (PFNGLSETFRAGMENTSHADERCONSTANTATIPROC)load("glSetFragmentShaderConstantATI"); -} -static void load_GL_EXT_blend_equation_separate(GLADloadproc load) { - if(!GLAD_GL_EXT_blend_equation_separate) return; - glad_glBlendEquationSeparateEXT = (PFNGLBLENDEQUATIONSEPARATEEXTPROC)load("glBlendEquationSeparateEXT"); -} -static void load_GL_EXT_framebuffer_blit(GLADloadproc load) { - if(!GLAD_GL_EXT_framebuffer_blit) return; - glad_glBlitFramebufferEXT = (PFNGLBLITFRAMEBUFFEREXTPROC)load("glBlitFramebufferEXT"); -} -static void load_GL_EXT_framebuffer_multisample(GLADloadproc load) { - if(!GLAD_GL_EXT_framebuffer_multisample) return; - glad_glRenderbufferStorageMultisampleEXT = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC)load("glRenderbufferStorageMultisampleEXT"); -} -static void load_GL_EXT_framebuffer_object(GLADloadproc load) { - if(!GLAD_GL_EXT_framebuffer_object) return; - glad_glIsRenderbufferEXT = (PFNGLISRENDERBUFFEREXTPROC)load("glIsRenderbufferEXT"); - glad_glBindRenderbufferEXT = (PFNGLBINDRENDERBUFFEREXTPROC)load("glBindRenderbufferEXT"); - glad_glDeleteRenderbuffersEXT = (PFNGLDELETERENDERBUFFERSEXTPROC)load("glDeleteRenderbuffersEXT"); - glad_glGenRenderbuffersEXT = (PFNGLGENRENDERBUFFERSEXTPROC)load("glGenRenderbuffersEXT"); - glad_glRenderbufferStorageEXT = (PFNGLRENDERBUFFERSTORAGEEXTPROC)load("glRenderbufferStorageEXT"); - glad_glGetRenderbufferParameterivEXT = (PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC)load("glGetRenderbufferParameterivEXT"); - glad_glIsFramebufferEXT = (PFNGLISFRAMEBUFFEREXTPROC)load("glIsFramebufferEXT"); - glad_glBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC)load("glBindFramebufferEXT"); - glad_glDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC)load("glDeleteFramebuffersEXT"); - glad_glGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC)load("glGenFramebuffersEXT"); - glad_glCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC)load("glCheckFramebufferStatusEXT"); - glad_glFramebufferTexture1DEXT = (PFNGLFRAMEBUFFERTEXTURE1DEXTPROC)load("glFramebufferTexture1DEXT"); - glad_glFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC)load("glFramebufferTexture2DEXT"); - glad_glFramebufferTexture3DEXT = (PFNGLFRAMEBUFFERTEXTURE3DEXTPROC)load("glFramebufferTexture3DEXT"); - glad_glFramebufferRenderbufferEXT = (PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC)load("glFramebufferRenderbufferEXT"); - glad_glGetFramebufferAttachmentParameterivEXT = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC)load("glGetFramebufferAttachmentParameterivEXT"); - glad_glGenerateMipmapEXT = (PFNGLGENERATEMIPMAPEXTPROC)load("glGenerateMipmapEXT"); -} -static void load_GL_EXT_geometry_shader4(GLADloadproc load) { - if(!GLAD_GL_EXT_geometry_shader4) return; - glad_glProgramParameteriEXT = (PFNGLPROGRAMPARAMETERIEXTPROC)load("glProgramParameteriEXT"); -} -static void load_GL_EXT_point_parameters(GLADloadproc load) { - if(!GLAD_GL_EXT_point_parameters) return; - glad_glPointParameterfEXT = (PFNGLPOINTPARAMETERFEXTPROC)load("glPointParameterfEXT"); - glad_glPointParameterfvEXT = (PFNGLPOINTPARAMETERFVEXTPROC)load("glPointParameterfvEXT"); -} -static void load_GL_EXT_secondary_color(GLADloadproc load) { - if(!GLAD_GL_EXT_secondary_color) return; - glad_glSecondaryColor3bEXT = (PFNGLSECONDARYCOLOR3BEXTPROC)load("glSecondaryColor3bEXT"); - glad_glSecondaryColor3bvEXT = (PFNGLSECONDARYCOLOR3BVEXTPROC)load("glSecondaryColor3bvEXT"); - glad_glSecondaryColor3dEXT = (PFNGLSECONDARYCOLOR3DEXTPROC)load("glSecondaryColor3dEXT"); - glad_glSecondaryColor3dvEXT = (PFNGLSECONDARYCOLOR3DVEXTPROC)load("glSecondaryColor3dvEXT"); - glad_glSecondaryColor3fEXT = (PFNGLSECONDARYCOLOR3FEXTPROC)load("glSecondaryColor3fEXT"); - glad_glSecondaryColor3fvEXT = (PFNGLSECONDARYCOLOR3FVEXTPROC)load("glSecondaryColor3fvEXT"); - glad_glSecondaryColor3iEXT = (PFNGLSECONDARYCOLOR3IEXTPROC)load("glSecondaryColor3iEXT"); - glad_glSecondaryColor3ivEXT = (PFNGLSECONDARYCOLOR3IVEXTPROC)load("glSecondaryColor3ivEXT"); - glad_glSecondaryColor3sEXT = (PFNGLSECONDARYCOLOR3SEXTPROC)load("glSecondaryColor3sEXT"); - glad_glSecondaryColor3svEXT = (PFNGLSECONDARYCOLOR3SVEXTPROC)load("glSecondaryColor3svEXT"); - glad_glSecondaryColor3ubEXT = (PFNGLSECONDARYCOLOR3UBEXTPROC)load("glSecondaryColor3ubEXT"); - glad_glSecondaryColor3ubvEXT = (PFNGLSECONDARYCOLOR3UBVEXTPROC)load("glSecondaryColor3ubvEXT"); - glad_glSecondaryColor3uiEXT = (PFNGLSECONDARYCOLOR3UIEXTPROC)load("glSecondaryColor3uiEXT"); - glad_glSecondaryColor3uivEXT = (PFNGLSECONDARYCOLOR3UIVEXTPROC)load("glSecondaryColor3uivEXT"); - glad_glSecondaryColor3usEXT = (PFNGLSECONDARYCOLOR3USEXTPROC)load("glSecondaryColor3usEXT"); - glad_glSecondaryColor3usvEXT = (PFNGLSECONDARYCOLOR3USVEXTPROC)load("glSecondaryColor3usvEXT"); - glad_glSecondaryColorPointerEXT = (PFNGLSECONDARYCOLORPOINTEREXTPROC)load("glSecondaryColorPointerEXT"); -} -static void load_GL_EXT_stencil_two_side(GLADloadproc load) { - if(!GLAD_GL_EXT_stencil_two_side) return; - glad_glActiveStencilFaceEXT = (PFNGLACTIVESTENCILFACEEXTPROC)load("glActiveStencilFaceEXT"); -} -static void load_GL_EXT_texture_array(GLADloadproc load) { - if(!GLAD_GL_EXT_texture_array) return; - glad_glFramebufferTextureLayerEXT = (PFNGLFRAMEBUFFERTEXTURELAYEREXTPROC)load("glFramebufferTextureLayerEXT"); -} -static void load_GL_GREMEDY_string_marker(GLADloadproc load) { - if(!GLAD_GL_GREMEDY_string_marker) return; - glad_glStringMarkerGREMEDY = (PFNGLSTRINGMARKERGREMEDYPROC)load("glStringMarkerGREMEDY"); -} -static void load_GL_NV_geometry_program4(GLADloadproc load) { - if(!GLAD_GL_NV_geometry_program4) return; - glad_glProgramVertexLimitNV = (PFNGLPROGRAMVERTEXLIMITNVPROC)load("glProgramVertexLimitNV"); - glad_glFramebufferTextureEXT = (PFNGLFRAMEBUFFERTEXTUREEXTPROC)load("glFramebufferTextureEXT"); - glad_glFramebufferTextureLayerEXT = (PFNGLFRAMEBUFFERTEXTURELAYEREXTPROC)load("glFramebufferTextureLayerEXT"); - glad_glFramebufferTextureFaceEXT = (PFNGLFRAMEBUFFERTEXTUREFACEEXTPROC)load("glFramebufferTextureFaceEXT"); -} -static void load_GL_NV_gpu_program4(GLADloadproc load) { - if(!GLAD_GL_NV_gpu_program4) return; - glad_glProgramLocalParameterI4iNV = (PFNGLPROGRAMLOCALPARAMETERI4INVPROC)load("glProgramLocalParameterI4iNV"); - glad_glProgramLocalParameterI4ivNV = (PFNGLPROGRAMLOCALPARAMETERI4IVNVPROC)load("glProgramLocalParameterI4ivNV"); - glad_glProgramLocalParametersI4ivNV = (PFNGLPROGRAMLOCALPARAMETERSI4IVNVPROC)load("glProgramLocalParametersI4ivNV"); - glad_glProgramLocalParameterI4uiNV = (PFNGLPROGRAMLOCALPARAMETERI4UINVPROC)load("glProgramLocalParameterI4uiNV"); - glad_glProgramLocalParameterI4uivNV = (PFNGLPROGRAMLOCALPARAMETERI4UIVNVPROC)load("glProgramLocalParameterI4uivNV"); - glad_glProgramLocalParametersI4uivNV = (PFNGLPROGRAMLOCALPARAMETERSI4UIVNVPROC)load("glProgramLocalParametersI4uivNV"); - glad_glProgramEnvParameterI4iNV = (PFNGLPROGRAMENVPARAMETERI4INVPROC)load("glProgramEnvParameterI4iNV"); - glad_glProgramEnvParameterI4ivNV = (PFNGLPROGRAMENVPARAMETERI4IVNVPROC)load("glProgramEnvParameterI4ivNV"); - glad_glProgramEnvParametersI4ivNV = (PFNGLPROGRAMENVPARAMETERSI4IVNVPROC)load("glProgramEnvParametersI4ivNV"); - glad_glProgramEnvParameterI4uiNV = (PFNGLPROGRAMENVPARAMETERI4UINVPROC)load("glProgramEnvParameterI4uiNV"); - glad_glProgramEnvParameterI4uivNV = (PFNGLPROGRAMENVPARAMETERI4UIVNVPROC)load("glProgramEnvParameterI4uivNV"); - glad_glProgramEnvParametersI4uivNV = (PFNGLPROGRAMENVPARAMETERSI4UIVNVPROC)load("glProgramEnvParametersI4uivNV"); - glad_glGetProgramLocalParameterIivNV = (PFNGLGETPROGRAMLOCALPARAMETERIIVNVPROC)load("glGetProgramLocalParameterIivNV"); - glad_glGetProgramLocalParameterIuivNV = (PFNGLGETPROGRAMLOCALPARAMETERIUIVNVPROC)load("glGetProgramLocalParameterIuivNV"); - glad_glGetProgramEnvParameterIivNV = (PFNGLGETPROGRAMENVPARAMETERIIVNVPROC)load("glGetProgramEnvParameterIivNV"); - glad_glGetProgramEnvParameterIuivNV = (PFNGLGETPROGRAMENVPARAMETERIUIVNVPROC)load("glGetProgramEnvParameterIuivNV"); -} -static void load_GL_NV_register_combiners(GLADloadproc load) { - if(!GLAD_GL_NV_register_combiners) return; - glad_glCombinerParameterfvNV = (PFNGLCOMBINERPARAMETERFVNVPROC)load("glCombinerParameterfvNV"); - glad_glCombinerParameterfNV = (PFNGLCOMBINERPARAMETERFNVPROC)load("glCombinerParameterfNV"); - glad_glCombinerParameterivNV = (PFNGLCOMBINERPARAMETERIVNVPROC)load("glCombinerParameterivNV"); - glad_glCombinerParameteriNV = (PFNGLCOMBINERPARAMETERINVPROC)load("glCombinerParameteriNV"); - glad_glCombinerInputNV = (PFNGLCOMBINERINPUTNVPROC)load("glCombinerInputNV"); - glad_glCombinerOutputNV = (PFNGLCOMBINEROUTPUTNVPROC)load("glCombinerOutputNV"); - glad_glFinalCombinerInputNV = (PFNGLFINALCOMBINERINPUTNVPROC)load("glFinalCombinerInputNV"); - glad_glGetCombinerInputParameterfvNV = (PFNGLGETCOMBINERINPUTPARAMETERFVNVPROC)load("glGetCombinerInputParameterfvNV"); - glad_glGetCombinerInputParameterivNV = (PFNGLGETCOMBINERINPUTPARAMETERIVNVPROC)load("glGetCombinerInputParameterivNV"); - glad_glGetCombinerOutputParameterfvNV = (PFNGLGETCOMBINEROUTPUTPARAMETERFVNVPROC)load("glGetCombinerOutputParameterfvNV"); - glad_glGetCombinerOutputParameterivNV = (PFNGLGETCOMBINEROUTPUTPARAMETERIVNVPROC)load("glGetCombinerOutputParameterivNV"); - glad_glGetFinalCombinerInputParameterfvNV = (PFNGLGETFINALCOMBINERINPUTPARAMETERFVNVPROC)load("glGetFinalCombinerInputParameterfvNV"); - glad_glGetFinalCombinerInputParameterivNV = (PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC)load("glGetFinalCombinerInputParameterivNV"); -} -static void load_GL_NV_register_combiners2(GLADloadproc load) { - if(!GLAD_GL_NV_register_combiners2) return; - glad_glCombinerStageParameterfvNV = (PFNGLCOMBINERSTAGEPARAMETERFVNVPROC)load("glCombinerStageParameterfvNV"); - glad_glGetCombinerStageParameterfvNV = (PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC)load("glGetCombinerStageParameterfvNV"); -} -static void load_GL_NV_transform_feedback(GLADloadproc load) { - if(!GLAD_GL_NV_transform_feedback) return; - glad_glBeginTransformFeedbackNV = (PFNGLBEGINTRANSFORMFEEDBACKNVPROC)load("glBeginTransformFeedbackNV"); - glad_glEndTransformFeedbackNV = (PFNGLENDTRANSFORMFEEDBACKNVPROC)load("glEndTransformFeedbackNV"); - glad_glTransformFeedbackAttribsNV = (PFNGLTRANSFORMFEEDBACKATTRIBSNVPROC)load("glTransformFeedbackAttribsNV"); - glad_glBindBufferRangeNV = (PFNGLBINDBUFFERRANGENVPROC)load("glBindBufferRangeNV"); - glad_glBindBufferOffsetNV = (PFNGLBINDBUFFEROFFSETNVPROC)load("glBindBufferOffsetNV"); - glad_glBindBufferBaseNV = (PFNGLBINDBUFFERBASENVPROC)load("glBindBufferBaseNV"); - glad_glTransformFeedbackVaryingsNV = (PFNGLTRANSFORMFEEDBACKVARYINGSNVPROC)load("glTransformFeedbackVaryingsNV"); - glad_glActiveVaryingNV = (PFNGLACTIVEVARYINGNVPROC)load("glActiveVaryingNV"); - glad_glGetVaryingLocationNV = (PFNGLGETVARYINGLOCATIONNVPROC)load("glGetVaryingLocationNV"); - glad_glGetActiveVaryingNV = (PFNGLGETACTIVEVARYINGNVPROC)load("glGetActiveVaryingNV"); - glad_glGetTransformFeedbackVaryingNV = (PFNGLGETTRANSFORMFEEDBACKVARYINGNVPROC)load("glGetTransformFeedbackVaryingNV"); - glad_glTransformFeedbackStreamAttribsNV = (PFNGLTRANSFORMFEEDBACKSTREAMATTRIBSNVPROC)load("glTransformFeedbackStreamAttribsNV"); -} -static void load_GL_NV_vertex_program(GLADloadproc load) { - if(!GLAD_GL_NV_vertex_program) return; - glad_glAreProgramsResidentNV = (PFNGLAREPROGRAMSRESIDENTNVPROC)load("glAreProgramsResidentNV"); - glad_glBindProgramNV = (PFNGLBINDPROGRAMNVPROC)load("glBindProgramNV"); - glad_glDeleteProgramsNV = (PFNGLDELETEPROGRAMSNVPROC)load("glDeleteProgramsNV"); - glad_glExecuteProgramNV = (PFNGLEXECUTEPROGRAMNVPROC)load("glExecuteProgramNV"); - glad_glGenProgramsNV = (PFNGLGENPROGRAMSNVPROC)load("glGenProgramsNV"); - glad_glGetProgramParameterdvNV = (PFNGLGETPROGRAMPARAMETERDVNVPROC)load("glGetProgramParameterdvNV"); - glad_glGetProgramParameterfvNV = (PFNGLGETPROGRAMPARAMETERFVNVPROC)load("glGetProgramParameterfvNV"); - glad_glGetProgramivNV = (PFNGLGETPROGRAMIVNVPROC)load("glGetProgramivNV"); - glad_glGetProgramStringNV = (PFNGLGETPROGRAMSTRINGNVPROC)load("glGetProgramStringNV"); - glad_glGetTrackMatrixivNV = (PFNGLGETTRACKMATRIXIVNVPROC)load("glGetTrackMatrixivNV"); - glad_glGetVertexAttribdvNV = (PFNGLGETVERTEXATTRIBDVNVPROC)load("glGetVertexAttribdvNV"); - glad_glGetVertexAttribfvNV = (PFNGLGETVERTEXATTRIBFVNVPROC)load("glGetVertexAttribfvNV"); - glad_glGetVertexAttribivNV = (PFNGLGETVERTEXATTRIBIVNVPROC)load("glGetVertexAttribivNV"); - glad_glGetVertexAttribPointervNV = (PFNGLGETVERTEXATTRIBPOINTERVNVPROC)load("glGetVertexAttribPointervNV"); - glad_glIsProgramNV = (PFNGLISPROGRAMNVPROC)load("glIsProgramNV"); - glad_glLoadProgramNV = (PFNGLLOADPROGRAMNVPROC)load("glLoadProgramNV"); - glad_glProgramParameter4dNV = (PFNGLPROGRAMPARAMETER4DNVPROC)load("glProgramParameter4dNV"); - glad_glProgramParameter4dvNV = (PFNGLPROGRAMPARAMETER4DVNVPROC)load("glProgramParameter4dvNV"); - glad_glProgramParameter4fNV = (PFNGLPROGRAMPARAMETER4FNVPROC)load("glProgramParameter4fNV"); - glad_glProgramParameter4fvNV = (PFNGLPROGRAMPARAMETER4FVNVPROC)load("glProgramParameter4fvNV"); - glad_glProgramParameters4dvNV = (PFNGLPROGRAMPARAMETERS4DVNVPROC)load("glProgramParameters4dvNV"); - glad_glProgramParameters4fvNV = (PFNGLPROGRAMPARAMETERS4FVNVPROC)load("glProgramParameters4fvNV"); - glad_glRequestResidentProgramsNV = (PFNGLREQUESTRESIDENTPROGRAMSNVPROC)load("glRequestResidentProgramsNV"); - glad_glTrackMatrixNV = (PFNGLTRACKMATRIXNVPROC)load("glTrackMatrixNV"); - glad_glVertexAttribPointerNV = (PFNGLVERTEXATTRIBPOINTERNVPROC)load("glVertexAttribPointerNV"); - glad_glVertexAttrib1dNV = (PFNGLVERTEXATTRIB1DNVPROC)load("glVertexAttrib1dNV"); - glad_glVertexAttrib1dvNV = (PFNGLVERTEXATTRIB1DVNVPROC)load("glVertexAttrib1dvNV"); - glad_glVertexAttrib1fNV = (PFNGLVERTEXATTRIB1FNVPROC)load("glVertexAttrib1fNV"); - glad_glVertexAttrib1fvNV = (PFNGLVERTEXATTRIB1FVNVPROC)load("glVertexAttrib1fvNV"); - glad_glVertexAttrib1sNV = (PFNGLVERTEXATTRIB1SNVPROC)load("glVertexAttrib1sNV"); - glad_glVertexAttrib1svNV = (PFNGLVERTEXATTRIB1SVNVPROC)load("glVertexAttrib1svNV"); - glad_glVertexAttrib2dNV = (PFNGLVERTEXATTRIB2DNVPROC)load("glVertexAttrib2dNV"); - glad_glVertexAttrib2dvNV = (PFNGLVERTEXATTRIB2DVNVPROC)load("glVertexAttrib2dvNV"); - glad_glVertexAttrib2fNV = (PFNGLVERTEXATTRIB2FNVPROC)load("glVertexAttrib2fNV"); - glad_glVertexAttrib2fvNV = (PFNGLVERTEXATTRIB2FVNVPROC)load("glVertexAttrib2fvNV"); - glad_glVertexAttrib2sNV = (PFNGLVERTEXATTRIB2SNVPROC)load("glVertexAttrib2sNV"); - glad_glVertexAttrib2svNV = (PFNGLVERTEXATTRIB2SVNVPROC)load("glVertexAttrib2svNV"); - glad_glVertexAttrib3dNV = (PFNGLVERTEXATTRIB3DNVPROC)load("glVertexAttrib3dNV"); - glad_glVertexAttrib3dvNV = (PFNGLVERTEXATTRIB3DVNVPROC)load("glVertexAttrib3dvNV"); - glad_glVertexAttrib3fNV = (PFNGLVERTEXATTRIB3FNVPROC)load("glVertexAttrib3fNV"); - glad_glVertexAttrib3fvNV = (PFNGLVERTEXATTRIB3FVNVPROC)load("glVertexAttrib3fvNV"); - glad_glVertexAttrib3sNV = (PFNGLVERTEXATTRIB3SNVPROC)load("glVertexAttrib3sNV"); - glad_glVertexAttrib3svNV = (PFNGLVERTEXATTRIB3SVNVPROC)load("glVertexAttrib3svNV"); - glad_glVertexAttrib4dNV = (PFNGLVERTEXATTRIB4DNVPROC)load("glVertexAttrib4dNV"); - glad_glVertexAttrib4dvNV = (PFNGLVERTEXATTRIB4DVNVPROC)load("glVertexAttrib4dvNV"); - glad_glVertexAttrib4fNV = (PFNGLVERTEXATTRIB4FNVPROC)load("glVertexAttrib4fNV"); - glad_glVertexAttrib4fvNV = (PFNGLVERTEXATTRIB4FVNVPROC)load("glVertexAttrib4fvNV"); - glad_glVertexAttrib4sNV = (PFNGLVERTEXATTRIB4SNVPROC)load("glVertexAttrib4sNV"); - glad_glVertexAttrib4svNV = (PFNGLVERTEXATTRIB4SVNVPROC)load("glVertexAttrib4svNV"); - glad_glVertexAttrib4ubNV = (PFNGLVERTEXATTRIB4UBNVPROC)load("glVertexAttrib4ubNV"); - glad_glVertexAttrib4ubvNV = (PFNGLVERTEXATTRIB4UBVNVPROC)load("glVertexAttrib4ubvNV"); - glad_glVertexAttribs1dvNV = (PFNGLVERTEXATTRIBS1DVNVPROC)load("glVertexAttribs1dvNV"); - glad_glVertexAttribs1fvNV = (PFNGLVERTEXATTRIBS1FVNVPROC)load("glVertexAttribs1fvNV"); - glad_glVertexAttribs1svNV = (PFNGLVERTEXATTRIBS1SVNVPROC)load("glVertexAttribs1svNV"); - glad_glVertexAttribs2dvNV = (PFNGLVERTEXATTRIBS2DVNVPROC)load("glVertexAttribs2dvNV"); - glad_glVertexAttribs2fvNV = (PFNGLVERTEXATTRIBS2FVNVPROC)load("glVertexAttribs2fvNV"); - glad_glVertexAttribs2svNV = (PFNGLVERTEXATTRIBS2SVNVPROC)load("glVertexAttribs2svNV"); - glad_glVertexAttribs3dvNV = (PFNGLVERTEXATTRIBS3DVNVPROC)load("glVertexAttribs3dvNV"); - glad_glVertexAttribs3fvNV = (PFNGLVERTEXATTRIBS3FVNVPROC)load("glVertexAttribs3fvNV"); - glad_glVertexAttribs3svNV = (PFNGLVERTEXATTRIBS3SVNVPROC)load("glVertexAttribs3svNV"); - glad_glVertexAttribs4dvNV = (PFNGLVERTEXATTRIBS4DVNVPROC)load("glVertexAttribs4dvNV"); - glad_glVertexAttribs4fvNV = (PFNGLVERTEXATTRIBS4FVNVPROC)load("glVertexAttribs4fvNV"); - glad_glVertexAttribs4svNV = (PFNGLVERTEXATTRIBS4SVNVPROC)load("glVertexAttribs4svNV"); - glad_glVertexAttribs4ubvNV = (PFNGLVERTEXATTRIBS4UBVNVPROC)load("glVertexAttribs4ubvNV"); -} -static int find_extensionsGL(void) { - if (!get_exts()) return 0; - GLAD_GL_ARB_depth_buffer_float = has_ext("GL_ARB_depth_buffer_float"); - GLAD_GL_ARB_draw_buffers = has_ext("GL_ARB_draw_buffers"); - GLAD_GL_ARB_draw_instanced = has_ext("GL_ARB_draw_instanced"); - GLAD_GL_ARB_fragment_program = has_ext("GL_ARB_fragment_program"); - GLAD_GL_ARB_fragment_program_shadow = has_ext("GL_ARB_fragment_program_shadow"); - GLAD_GL_ARB_fragment_shader = has_ext("GL_ARB_fragment_shader"); - GLAD_GL_ARB_framebuffer_object = has_ext("GL_ARB_framebuffer_object"); - GLAD_GL_ARB_get_program_binary = has_ext("GL_ARB_get_program_binary"); - GLAD_GL_ARB_instanced_arrays = has_ext("GL_ARB_instanced_arrays"); - GLAD_GL_ARB_multisample = has_ext("GL_ARB_multisample"); - GLAD_GL_ARB_multitexture = has_ext("GL_ARB_multitexture"); - GLAD_GL_ARB_occlusion_query = has_ext("GL_ARB_occlusion_query"); - GLAD_GL_ARB_pixel_buffer_object = has_ext("GL_ARB_pixel_buffer_object"); - GLAD_GL_ARB_point_parameters = has_ext("GL_ARB_point_parameters"); - GLAD_GL_ARB_point_sprite = has_ext("GL_ARB_point_sprite"); - GLAD_GL_ARB_seamless_cube_map = has_ext("GL_ARB_seamless_cube_map"); - GLAD_GL_ARB_shader_objects = has_ext("GL_ARB_shader_objects"); - GLAD_GL_ARB_shading_language_100 = has_ext("GL_ARB_shading_language_100"); - GLAD_GL_ARB_shadow = has_ext("GL_ARB_shadow"); - GLAD_GL_ARB_texture_compression = has_ext("GL_ARB_texture_compression"); - GLAD_GL_ARB_texture_cube_map = has_ext("GL_ARB_texture_cube_map"); - GLAD_GL_ARB_texture_env_combine = has_ext("GL_ARB_texture_env_combine"); - GLAD_GL_ARB_texture_float = has_ext("GL_ARB_texture_float"); - GLAD_GL_ARB_texture_non_power_of_two = has_ext("GL_ARB_texture_non_power_of_two"); - GLAD_GL_ARB_vertex_buffer_object = has_ext("GL_ARB_vertex_buffer_object"); - GLAD_GL_ARB_vertex_program = has_ext("GL_ARB_vertex_program"); - GLAD_GL_ARB_vertex_shader = has_ext("GL_ARB_vertex_shader"); - GLAD_GL_ATI_draw_buffers = has_ext("GL_ATI_draw_buffers"); - GLAD_GL_ATI_fragment_shader = has_ext("GL_ATI_fragment_shader"); - GLAD_GL_ATI_texture_float = has_ext("GL_ATI_texture_float"); - GLAD_GL_EXT_blend_equation_separate = has_ext("GL_EXT_blend_equation_separate"); - GLAD_GL_EXT_framebuffer_blit = has_ext("GL_EXT_framebuffer_blit"); - GLAD_GL_EXT_framebuffer_multisample = has_ext("GL_EXT_framebuffer_multisample"); - GLAD_GL_EXT_framebuffer_object = has_ext("GL_EXT_framebuffer_object"); - GLAD_GL_EXT_framebuffer_sRGB = has_ext("GL_EXT_framebuffer_sRGB"); - GLAD_GL_EXT_geometry_shader4 = has_ext("GL_EXT_geometry_shader4"); - GLAD_GL_EXT_pixel_buffer_object = has_ext("GL_EXT_pixel_buffer_object"); - GLAD_GL_EXT_point_parameters = has_ext("GL_EXT_point_parameters"); - GLAD_GL_EXT_secondary_color = has_ext("GL_EXT_secondary_color"); - GLAD_GL_EXT_stencil_two_side = has_ext("GL_EXT_stencil_two_side"); - GLAD_GL_EXT_stencil_wrap = has_ext("GL_EXT_stencil_wrap"); - GLAD_GL_EXT_texture_array = has_ext("GL_EXT_texture_array"); - GLAD_GL_EXT_texture_compression_s3tc = has_ext("GL_EXT_texture_compression_s3tc"); - GLAD_GL_EXT_texture_filter_anisotropic = has_ext("GL_EXT_texture_filter_anisotropic"); - GLAD_GL_EXT_texture_lod_bias = has_ext("GL_EXT_texture_lod_bias"); - GLAD_GL_EXT_texture_sRGB = has_ext("GL_EXT_texture_sRGB"); - GLAD_GL_GREMEDY_string_marker = has_ext("GL_GREMEDY_string_marker"); - GLAD_GL_NV_fragment_program2 = has_ext("GL_NV_fragment_program2"); - GLAD_GL_NV_fragment_program_option = has_ext("GL_NV_fragment_program_option"); - GLAD_GL_NV_geometry_program4 = has_ext("GL_NV_geometry_program4"); - GLAD_GL_NV_gpu_program4 = has_ext("GL_NV_gpu_program4"); - GLAD_GL_NV_register_combiners = has_ext("GL_NV_register_combiners"); - GLAD_GL_NV_register_combiners2 = has_ext("GL_NV_register_combiners2"); - GLAD_GL_NV_texture_compression_vtc = has_ext("GL_NV_texture_compression_vtc"); - GLAD_GL_NV_texture_shader = has_ext("GL_NV_texture_shader"); - GLAD_GL_NV_transform_feedback = has_ext("GL_NV_transform_feedback"); - GLAD_GL_NV_vertex_program = has_ext("GL_NV_vertex_program"); - GLAD_GL_NV_vertex_program2_option = has_ext("GL_NV_vertex_program2_option"); - GLAD_GL_NV_vertex_program3 = has_ext("GL_NV_vertex_program3"); - free_exts(); - return 1; -} - -static void find_coreGL(void) { - - /* Thank you @elmindreda - * https://github.com/elmindreda/greg/blob/master/templates/greg.c.in#L176 - * https://github.com/glfw/glfw/blob/master/src/context.c#L36 - */ - int i, major, minor; - - const char* version; - const char* prefixes[] = { - "OpenGL ES-CM ", - "OpenGL ES-CL ", - "OpenGL ES ", - NULL - }; - - version = (const char*) glGetString(GL_VERSION); - if (!version) return; - - for (i = 0; prefixes[i]; i++) { - const size_t length = strlen(prefixes[i]); - if (strncmp(version, prefixes[i], length) == 0) { - version += length; - break; - } - } - -/* PR #18 */ -#ifdef _MSC_VER - sscanf_s(version, "%d.%d", &major, &minor); -#else - sscanf(version, "%d.%d", &major, &minor); -#endif - - GLVersion.major = major; GLVersion.minor = minor; - max_loaded_major = major; max_loaded_minor = minor; - GLAD_GL_VERSION_1_0 = (major == 1 && minor >= 0) || major > 1; - GLAD_GL_VERSION_1_1 = (major == 1 && minor >= 1) || major > 1; - GLAD_GL_VERSION_1_2 = (major == 1 && minor >= 2) || major > 1; - GLAD_GL_VERSION_1_3 = (major == 1 && minor >= 3) || major > 1; - GLAD_GL_VERSION_1_4 = (major == 1 && minor >= 4) || major > 1; - GLAD_GL_VERSION_1_5 = (major == 1 && minor >= 5) || major > 1; - GLAD_GL_VERSION_2_0 = (major == 2 && minor >= 0) || major > 2; - GLAD_GL_VERSION_2_1 = (major == 2 && minor >= 1) || major > 2; - if (GLVersion.major > 2 || (GLVersion.major >= 2 && GLVersion.minor >= 1)) { - max_loaded_major = 2; - max_loaded_minor = 1; - } -} - -int gladLoadGLLoader(GLADloadproc load) { - GLVersion.major = 0; GLVersion.minor = 0; - glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); - if(glGetString == NULL) return 0; - if(glGetString(GL_VERSION) == NULL) return 0; - find_coreGL(); - load_GL_VERSION_1_0(load); - load_GL_VERSION_1_1(load); - load_GL_VERSION_1_2(load); - load_GL_VERSION_1_3(load); - load_GL_VERSION_1_4(load); - load_GL_VERSION_1_5(load); - load_GL_VERSION_2_0(load); - load_GL_VERSION_2_1(load); - - if (!find_extensionsGL()) return 0; - load_GL_ARB_draw_buffers(load); - load_GL_ARB_draw_instanced(load); - load_GL_ARB_fragment_program(load); - load_GL_ARB_framebuffer_object(load); - load_GL_ARB_get_program_binary(load); - load_GL_ARB_instanced_arrays(load); - load_GL_ARB_multisample(load); - load_GL_ARB_multitexture(load); - load_GL_ARB_occlusion_query(load); - load_GL_ARB_point_parameters(load); - load_GL_ARB_shader_objects(load); - load_GL_ARB_texture_compression(load); - load_GL_ARB_vertex_buffer_object(load); - load_GL_ARB_vertex_program(load); - load_GL_ARB_vertex_shader(load); - load_GL_ATI_draw_buffers(load); - load_GL_ATI_fragment_shader(load); - load_GL_EXT_blend_equation_separate(load); - load_GL_EXT_framebuffer_blit(load); - load_GL_EXT_framebuffer_multisample(load); - load_GL_EXT_framebuffer_object(load); - load_GL_EXT_geometry_shader4(load); - load_GL_EXT_point_parameters(load); - load_GL_EXT_secondary_color(load); - load_GL_EXT_stencil_two_side(load); - load_GL_EXT_texture_array(load); - load_GL_GREMEDY_string_marker(load); - load_GL_NV_geometry_program4(load); - load_GL_NV_gpu_program4(load); - load_GL_NV_register_combiners(load); - load_GL_NV_register_combiners2(load); - load_GL_NV_transform_feedback(load); - load_GL_NV_vertex_program(load); - return GLVersion.major != 0 || GLVersion.minor != 0; -} diff --git a/RenderSystems/GL/src/nvparse/Makefile.reyacc b/RenderSystems/GL/src/nvparse/Makefile.reyacc deleted file mode 100644 index 10a5ad491bf..00000000000 --- a/RenderSystems/GL/src/nvparse/Makefile.reyacc +++ /dev/null @@ -1,19 +0,0 @@ -MAIN=../libnvparse.a - -$(MAIN): - -bison -d -o _ps1.0_parser.c ps1.0_grammar.y - -mv -f _ps1.0_parser.c _ps1.0_parser.cpp - -bison -d -o _rc1.0_parser.c rc1.0_grammar.y - -mv -f _rc1.0_parser.c _rc1.0_parser.cpp - -bison -d -o _ts1.0_parser.c ts1.0_grammar.y - -mv -f _ts1.0_parser.c _ts1.0_parser.cpp - -bison -d -o _vs1.0_parser.c vs1.0_grammar.y - -mv -f _vs1.0_parser.c _vs1.0_parser.cpp - -flex -o_rc1.0_lexer.cpp rc1.0_tokens.l - -flex -o_ps1.0_lexer.cpp ps1.0_tokens.l - -flex -o_ts1.0_lexer.cpp ts1.0_tokens.l - -flex -o_vs1.0_lexer.cpp vs1.0_tokens.l - -all: $(MAIN) - -install: diff --git a/RenderSystems/GL/src/nvparse/_ps1.0_lexer.cpp b/RenderSystems/GL/src/nvparse/_ps1.0_lexer.cpp deleted file mode 100644 index 1232575ba60..00000000000 --- a/RenderSystems/GL/src/nvparse/_ps1.0_lexer.cpp +++ /dev/null @@ -1,1891 +0,0 @@ -#define yy_create_buffer ps10__create_buffer -#define yy_delete_buffer ps10__delete_buffer -#define yy_scan_buffer ps10__scan_buffer -#define yy_scan_string ps10__scan_string -#define yy_scan_bytes ps10__scan_bytes -#define yy_flex_debug ps10__flex_debug -#define yy_init_buffer ps10__init_buffer -#define yy_flush_buffer ps10__flush_buffer -#define yy_load_buffer_state ps10__load_buffer_state -#define yy_switch_to_buffer ps10__switch_to_buffer -#define yyin ps10_in -#define yyleng ps10_leng -#define yylex ps10_lex -#define yyout ps10_out -#define yyrestart ps10_restart -#define yytext ps10_text -#define yywrap ps10_wrap - -#line 20 "_ps1.0_lexer.cpp" -/* A lexical scanner generated by flex */ - -/* Scanner skeleton version: - * $Header: /home/daffy/u0/vern/flex/RCS/flex.skl,v 2.91 96/09/10 16:58:48 vern Exp $ - */ - -#define FLEX_SCANNER -#define YY_FLEX_MAJOR_VERSION 2 -#define YY_FLEX_MINOR_VERSION 5 - -#include -#include - -/* cfront 1.2 defines "c_plusplus" instead of "__cplusplus" */ -#ifdef c_plusplus -#ifndef __cplusplus -#define __cplusplus -#endif -#endif - - -#ifdef __cplusplus - -#include -#ifndef _WIN32 -#include -#endif - -/* Use prototypes in function declarations. */ -#define YY_USE_PROTOS - -/* The "const" storage-class-modifier is valid. */ -#define YY_USE_CONST - -#else /* ! __cplusplus */ - -#if __STDC__ - -#define YY_USE_PROTOS -#define YY_USE_CONST - -#endif /* __STDC__ */ -#endif /* ! __cplusplus */ - -#ifdef __TURBOC__ - #pragma warn -rch - #pragma warn -use -#include -#include -#define YY_USE_CONST -#define YY_USE_PROTOS -#endif - -#ifdef YY_USE_CONST -#define yyconst const -#else -#define yyconst -#endif - - -#ifdef YY_USE_PROTOS -#define YY_PROTO(proto) proto -#else -#define YY_PROTO(proto) () -#endif - - -/* Returned upon end-of-file. */ -#define YY_NULL 0 - -/* Promotes a possibly negative, possibly signed char to an unsigned - * integer for use as an array index. If the signed char is negative, - * we want to instead treat it as an 8-bit unsigned char, hence the - * double cast. - */ -#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) - -/* Enter a start condition. This macro really ought to take a parameter, - * but we do it the disgusting crufty way forced on us by the ()-less - * definition of BEGIN. - */ -#define BEGIN yy_start = 1 + 2 * - -/* Translate the current start state into a value that can be later handed - * to BEGIN to return to the state. The YYSTATE alias is for lex - * compatibility. - */ -#define YY_START ((yy_start - 1) / 2) -#define YYSTATE YY_START - -/* Action number for EOF rule of a given start state. */ -#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) - -/* Special action meaning "start processing a new file". */ -#define YY_NEW_FILE yyrestart( yyin ) - -#define YY_END_OF_BUFFER_CHAR 0 - -/* Size of default input buffer. */ -#define YY_BUF_SIZE 16384 - -typedef struct yy_buffer_state *YY_BUFFER_STATE; - -extern int yyleng; -extern FILE *yyin, *yyout; - -#define EOB_ACT_CONTINUE_SCAN 0 -#define EOB_ACT_END_OF_FILE 1 -#define EOB_ACT_LAST_MATCH 2 - -/* The funky do-while in the following #define is used to turn the definition - * int a single C statement (which needs a semi-colon terminator). This - * avoids problems with code like: - * - * if ( condition_holds ) - * yyless( 5 ); - * else - * do_something_else(); - * - * Prior to using the do-while the compiler would get upset at the - * "else" because it interpreted the "if" statement as being all - * done when it reached the ';' after the yyless() call. - */ - -/* Return all but the first 'n' matched characters back to the input stream. */ - -#define yyless(n) \ - do \ - { \ - /* Undo effects of setting up yytext. */ \ - *yy_cp = yy_hold_char; \ - YY_RESTORE_YY_MORE_OFFSET \ - yy_c_buf_p = yy_cp = yy_bp + n - YY_MORE_ADJ; \ - YY_DO_BEFORE_ACTION; /* set up yytext again */ \ - } \ - while ( 0 ) - -#define unput(c) yyunput( c, yytext_ptr ) - -/* The following is because we cannot portably get our hands on size_t - * (without autoconf's help, which isn't available because we want - * flex-generated scanners to compile on their own). - */ -typedef unsigned int yy_size_t; - - -struct yy_buffer_state - { - FILE *yy_input_file; - - char *yy_ch_buf; /* input buffer */ - char *yy_buf_pos; /* current position in input buffer */ - - /* Size of input buffer in bytes, not including room for EOB - * characters. - */ - yy_size_t yy_buf_size; - - /* Number of characters read into yy_ch_buf, not including EOB - * characters. - */ - int yy_n_chars; - - /* Whether we "own" the buffer - i.e., we know we created it, - * and can realloc() it to grow it, and should free() it to - * delete it. - */ - int yy_is_our_buffer; - - /* Whether this is an "interactive" input source; if so, and - * if we're using stdio for input, then we want to use getc() - * instead of fread(), to make sure we stop fetching input after - * each newline. - */ - int yy_is_interactive; - - /* Whether we're considered to be at the beginning of a line. - * If so, '^' rules will be active on the next match, otherwise - * not. - */ - int yy_at_bol; - - /* Whether to try to fill the input buffer when we reach the - * end of it. - */ - int yy_fill_buffer; - - int yy_buffer_status; -#define YY_BUFFER_NEW 0 -#define YY_BUFFER_NORMAL 1 - /* When an EOF's been seen but there's still some text to process - * then we mark the buffer as YY_EOF_PENDING, to indicate that we - * shouldn't try reading from the input source any more. We might - * still have a bunch of tokens to match, though, because of - * possible backing-up. - * - * When we actually see the EOF, we change the status to "new" - * (via yyrestart()), so that the user can continue scanning by - * just pointing yyin at a new input file. - */ -#define YY_BUFFER_EOF_PENDING 2 - }; - -static YY_BUFFER_STATE yy_current_buffer = 0; - -/* We provide macros for accessing buffer states in case in the - * future we want to put the buffer states in a more general - * "scanner state". - */ -#define YY_CURRENT_BUFFER yy_current_buffer - - -/* yy_hold_char holds the character lost when yytext is formed. */ -static char yy_hold_char; - -static int yy_n_chars; /* number of characters read into yy_ch_buf */ - - -int yyleng; - -/* Points to current character in buffer. */ -static char *yy_c_buf_p = (char *) 0; -static int yy_init = 1; /* whether we need to initialize */ -static int yy_start = 0; /* start state number */ - -/* Flag which is used to allow yywrap()'s to do buffer switches - * instead of setting up a fresh yyin. A bit of a hack ... - */ -static int yy_did_buffer_switch_on_eof; - -void yyrestart YY_PROTO(( FILE *input_file )); - -void yy_switch_to_buffer YY_PROTO(( YY_BUFFER_STATE new_buffer )); -void yy_load_buffer_state YY_PROTO(( void )); -YY_BUFFER_STATE yy_create_buffer YY_PROTO(( FILE *file, int size )); -void yy_delete_buffer YY_PROTO(( YY_BUFFER_STATE b )); -void yy_init_buffer YY_PROTO(( YY_BUFFER_STATE b, FILE *file )); -void yy_flush_buffer YY_PROTO(( YY_BUFFER_STATE b )); -#define YY_FLUSH_BUFFER yy_flush_buffer( yy_current_buffer ) - -YY_BUFFER_STATE yy_scan_buffer YY_PROTO(( char *base, yy_size_t size )); -YY_BUFFER_STATE yy_scan_string YY_PROTO(( yyconst char *yy_str )); -YY_BUFFER_STATE yy_scan_bytes YY_PROTO(( yyconst char *bytes, int len )); - -static void *yy_flex_alloc YY_PROTO(( yy_size_t )); -static void *yy_flex_realloc YY_PROTO(( void *, yy_size_t )); -static void yy_flex_free YY_PROTO(( void * )); - -#define yy_new_buffer yy_create_buffer - -#define yy_set_interactive(is_interactive) \ - { \ - if ( ! yy_current_buffer ) \ - yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \ - yy_current_buffer->yy_is_interactive = is_interactive; \ - } - -#define yy_set_bol(at_bol) \ - { \ - if ( ! yy_current_buffer ) \ - yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \ - yy_current_buffer->yy_at_bol = at_bol; \ - } - -#define YY_AT_BOL() (yy_current_buffer->yy_at_bol) - -typedef unsigned char YY_CHAR; -FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0; -typedef int yy_state_type; -extern char *yytext; -#define yytext_ptr yytext - -static yy_state_type yy_get_previous_state YY_PROTO(( void )); -static yy_state_type yy_try_NUL_trans YY_PROTO(( yy_state_type current_state )); -static int yy_get_next_buffer YY_PROTO(( void )); -static void yy_fatal_error YY_PROTO(( yyconst char msg[] )); - -/* Done after the current pattern has been matched and before the - * corresponding action - sets up yytext. - */ -#define YY_DO_BEFORE_ACTION \ - yytext_ptr = yy_bp; \ - yyleng = (int) (yy_cp - yy_bp); \ - yy_hold_char = *yy_cp; \ - *yy_cp = '\0'; \ - yy_c_buf_p = yy_cp; - -#define YY_NUM_RULES 36 -#define YY_END_OF_BUFFER 37 -static yyconst short int yy_accept[231] = - { 0, - 0, 0, 0, 0, 37, 35, 33, 32, 35, 35, - 35, 35, 1, 35, 35, 35, 35, 35, 35, 35, - 35, 35, 35, 35, 35, 35, 5, 5, 33, 32, - 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, - 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, - 7, 0, 9, 0, 10, 0, 5, 4, 3, 0, - 11, 0, 0, 12, 6, 13, 14, 15, 16, 17, - 0, 0, 18, 0, 0, 19, 0, 0, 3, 0, - 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 7, 0, 0, 0, 0, 9, 0, 0, 0, - - 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 34, 11, 0, 0, 12, - 0, 13, 0, 14, 0, 15, 0, 16, 0, 17, - 0, 0, 18, 0, 0, 20, 0, 0, 0, 0, - 0, 0, 11, 0, 12, 0, 13, 0, 14, 0, - 15, 0, 16, 0, 17, 0, 18, 21, 0, 23, - - 0, 0, 0, 22, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 26, 27, - 24, 25, 28, 0, 30, 0, 29, 0, 31, 0 - } ; - -static yyconst int yy_ec[256] = - { 0, - 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, - 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 5, 1, 6, 7, 8, 9, 10, 11, - 12, 13, 14, 14, 14, 15, 15, 1, 16, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 17, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 18, 1, 19, 20, 21, 22, - - 23, 24, 25, 1, 26, 1, 27, 28, 29, 30, - 31, 32, 1, 33, 34, 35, 36, 37, 38, 39, - 40, 41, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1 - } ; - -static yyconst int yy_meta[42] = - { 0, - 1, 1, 2, 1, 1, 1, 3, 1, 4, 4, - 4, 4, 4, 4, 5, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1 - } ; - -static yyconst short int yy_base[236] = - { 0, - 0, 0, 37, 0, 365, 366, 51, 54, 361, 43, - 355, 57, 366, 328, 339, 330, 37, 326, 43, 56, - 322, 61, 58, 350, 75, 0, 349, 79, 85, 88, - 352, 91, 81, 110, 88, 94, 90, 366, 105, 107, - 347, 331, 108, 330, 327, 338, 317, 326, 310, 318, - 118, 325, 120, 305, 123, 0, 336, 0, 0, 332, - 323, 112, 320, 321, 366, 320, 319, 318, 317, 316, - 114, 313, 314, 129, 311, 136, 139, 310, 0, 0, - 121, 366, 304, 288, 135, 132, 142, 148, 151, 157, - 158, 366, 302, 286, 149, 161, 366, 300, 284, 160, - - 300, 291, 295, 308, 296, 366, 293, 277, 163, 184, - 305, 296, 124, 294, 272, 293, 300, 299, 290, 190, - 297, 288, 193, 295, 286, 194, 293, 284, 197, 291, - 282, 198, 289, 280, 201, 278, 256, 277, 284, 283, - 274, 202, 272, 250, 271, 278, 259, 256, 258, 246, - 259, 263, 241, 262, 269, 366, 261, 243, 243, 258, - 240, 256, 238, 254, 236, 252, 234, 250, 232, 248, - 230, 230, 245, 227, 227, 232, 226, 230, 205, 246, - 222, 221, 366, 220, 366, 219, 366, 218, 366, 217, - 366, 216, 366, 215, 366, 214, 366, 366, 225, 366, - - 186, 188, 205, 366, 223, 209, 210, 196, 204, 192, - 186, 178, 162, 107, 117, 106, 78, 81, 366, 366, - 366, 366, 366, 80, 366, 52, 366, 40, 366, 366, - 227, 231, 233, 235, 240 - } ; - -static yyconst short int yy_def[236] = - { 0, - 230, 1, 1, 3, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 231, 230, 230, 230, 230, - 230, 230, 230, 232, 232, 233, 232, 232, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 233, 232, 233, 234, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 234, 235, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 0, - 230, 230, 230, 230, 230 - } ; - -static yyconst short int yy_nxt[408] = - { 0, - 6, 7, 8, 9, 6, 10, 6, 11, 6, 12, - 6, 6, 6, 6, 6, 13, 14, 6, 15, 6, - 16, 17, 6, 6, 6, 6, 6, 18, 19, 6, - 6, 14, 20, 21, 22, 6, 23, 6, 6, 6, - 6, 24, 25, 26, 33, 27, 28, 27, 27, 27, - 27, 27, 29, 30, 31, 32, 30, 31, 39, 45, - 229, 48, 40, 34, 51, 51, 55, 55, 46, 53, - 53, 53, 53, 49, 228, 35, 33, 36, 50, 37, - 39, 56, 33, 54, 40, 59, 29, 30, 31, 32, - 30, 31, 32, 30, 31, 34, 51, 51, 55, 55, - - 227, 34, 53, 53, 53, 53, 39, 35, 33, 36, - 40, 37, 226, 35, 62, 36, 225, 37, 43, 43, - 43, 43, 43, 43, 71, 63, 74, 34, 224, 77, - 82, 82, 92, 92, 157, 72, 157, 75, 223, 35, - 78, 36, 111, 37, 83, 222, 93, 97, 97, 82, - 84, 92, 94, 118, 112, 101, 102, 106, 106, 113, - 116, 98, 103, 121, 104, 119, 97, 99, 105, 124, - 120, 107, 127, 117, 138, 122, 106, 108, 130, 133, - 123, 125, 140, 221, 128, 145, 126, 139, 154, 129, - 131, 134, 156, 156, 141, 132, 135, 220, 146, 142, - - 160, 155, 160, 162, 164, 162, 164, 166, 168, 166, - 168, 170, 173, 170, 173, 201, 202, 205, 219, 207, - 206, 208, 209, 211, 210, 218, 217, 216, 215, 212, - 43, 214, 43, 57, 57, 57, 58, 58, 79, 79, - 110, 213, 110, 110, 110, 110, 204, 141, 134, 131, - 128, 125, 122, 119, 112, 106, 203, 200, 199, 198, - 97, 197, 196, 92, 195, 194, 193, 192, 191, 190, - 189, 188, 187, 186, 185, 184, 82, 183, 182, 106, - 181, 106, 106, 180, 179, 178, 177, 176, 97, 175, - 97, 97, 174, 173, 92, 172, 92, 92, 171, 170, - - 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, - 82, 159, 82, 82, 158, 157, 153, 152, 151, 150, - 149, 148, 147, 144, 143, 137, 136, 115, 114, 109, - 100, 96, 95, 91, 90, 89, 88, 87, 86, 85, - 81, 80, 59, 76, 73, 70, 69, 68, 67, 66, - 65, 64, 61, 60, 30, 59, 56, 52, 47, 44, - 42, 41, 38, 30, 230, 5, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - - 230, 230, 230, 230, 230, 230, 230 - } ; - -static yyconst short int yy_chk[408] = - { 0, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 3, 3, 3, 10, 3, 3, 3, 3, 3, - 3, 3, 7, 7, 7, 8, 8, 8, 12, 17, - 228, 19, 12, 10, 20, 20, 23, 23, 17, 22, - 22, 22, 22, 19, 226, 10, 25, 10, 19, 10, - 28, 25, 33, 22, 28, 28, 29, 29, 29, 30, - 30, 30, 32, 32, 32, 25, 35, 35, 37, 37, - - 224, 33, 36, 36, 36, 36, 39, 25, 40, 25, - 39, 25, 218, 33, 43, 33, 217, 33, 34, 34, - 34, 34, 34, 34, 51, 43, 53, 40, 216, 55, - 62, 62, 71, 71, 113, 51, 113, 53, 215, 40, - 55, 40, 81, 40, 62, 214, 71, 74, 74, 62, - 62, 71, 71, 86, 81, 76, 76, 77, 77, 81, - 85, 74, 76, 87, 76, 86, 74, 74, 76, 88, - 86, 77, 89, 85, 95, 87, 77, 77, 90, 91, - 87, 88, 96, 213, 89, 100, 88, 95, 109, 89, - 90, 91, 110, 110, 96, 90, 91, 212, 100, 96, - - 120, 109, 120, 123, 126, 123, 126, 129, 132, 129, - 132, 135, 142, 135, 142, 179, 179, 201, 211, 202, - 201, 202, 202, 203, 202, 210, 209, 208, 207, 203, - 231, 206, 231, 232, 232, 232, 233, 233, 234, 234, - 235, 205, 235, 235, 235, 235, 199, 196, 194, 192, - 190, 188, 186, 184, 182, 181, 180, 178, 177, 176, - 175, 174, 173, 172, 171, 170, 169, 168, 167, 166, - 165, 164, 163, 162, 161, 160, 159, 158, 157, 155, - 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, - 144, 143, 141, 140, 139, 138, 137, 136, 134, 133, - - 131, 130, 128, 127, 125, 124, 122, 121, 119, 118, - 117, 116, 115, 114, 112, 111, 108, 107, 105, 104, - 103, 102, 101, 99, 98, 94, 93, 84, 83, 78, - 75, 73, 72, 70, 69, 68, 67, 66, 64, 63, - 61, 60, 57, 54, 52, 50, 49, 48, 47, 46, - 45, 44, 42, 41, 31, 27, 24, 21, 18, 16, - 15, 14, 11, 9, 5, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, - - 230, 230, 230, 230, 230, 230, 230 - } ; - -static yy_state_type yy_last_accepting_state; -static char *yy_last_accepting_cpos; - -/* The intent behind this definition is that it'll catch - * any uses of REJECT which flex missed. - */ -#define REJECT reject_used_but_not_detected -#define yymore() yymore_used_but_not_detected -#define YY_MORE_ADJ 0 -#define YY_RESTORE_YY_MORE_OFFSET -char *yytext; -#line 1 "ps1.0_tokens.l" -#define INITIAL 0 -/* definitions */ -#line 8 "ps1.0_tokens.l" - -#include -#include -#include - -#include "ps1.0_program.h" - -using namespace std; -using namespace ps10; - -#include "_ps1.0_parser.h" - -#include "nvparse_errors.h" -#include "nvparse_externs.h" -#define YY_NO_UNPUT - -#define YY_INPUT(buf,result,max_size) \ -{ \ - int c = *myin++; \ - result = (c == 0) ? YY_NULL : (buf[0] = c, 1); \ -} - -#define YY_ALWAYS_INTERACTIVE 1 - -//#define DBG_MESG(msg, line) errors.set(msg, line) -#define DBG_MESG(msg, line) - -static char buf[80]; - - -#define DEFSTATE 1 - -/* end of definitions */ -#line 586 "_ps1.0_lexer.cpp" - -/* Macros after this point can all be overridden by user definitions in - * section 1. - */ - -#ifndef YY_SKIP_YYWRAP -#ifdef __cplusplus -extern "C" int yywrap YY_PROTO(( void )); -#else -extern int yywrap YY_PROTO(( void )); -#endif -#endif - -#ifndef YY_NO_UNPUT -static void yyunput YY_PROTO(( int c, char *buf_ptr )); -#endif - -#ifndef yytext_ptr -static void yy_flex_strncpy YY_PROTO(( char *, yyconst char *, int )); -#endif - -#ifdef YY_NEED_STRLEN -static int yy_flex_strlen YY_PROTO(( yyconst char * )); -#endif - -#ifndef YY_NO_INPUT -#ifdef __cplusplus -static int yyinput YY_PROTO(( void )); -#else -static int input YY_PROTO(( void )); -#endif -#endif - -#if YY_STACK_USED -static int yy_start_stack_ptr = 0; -static int yy_start_stack_depth = 0; -static int *yy_start_stack = 0; -#ifndef YY_NO_PUSH_STATE -static void yy_push_state YY_PROTO(( int new_state )); -#endif -#ifndef YY_NO_POP_STATE -static void yy_pop_state YY_PROTO(( void )); -#endif -#ifndef YY_NO_TOP_STATE -static int yy_top_state YY_PROTO(( void )); -#endif - -#else -#define YY_NO_PUSH_STATE 1 -#define YY_NO_POP_STATE 1 -#define YY_NO_TOP_STATE 1 -#endif - -#ifdef YY_MALLOC_DECL -YY_MALLOC_DECL -#else -#if __STDC__ -#ifndef __cplusplus -#include -#endif -#else -/* Just try to get by without declaring the routines. This will fail - * miserably on non-ANSI systems for which sizeof(size_t) != sizeof(int) - * or sizeof(void*) != sizeof(int). - */ -#endif -#endif - -/* Amount of stuff to slurp up with each read. */ -#ifndef YY_READ_BUF_SIZE -#define YY_READ_BUF_SIZE 8192 -#endif - -/* Copy whatever the last rule matched to the standard output. */ - -#ifndef ECHO -/* This used to be an fputs(), but since the string might contain NUL's, - * we now use fwrite(). - */ -#define ECHO (void) fwrite( yytext, yyleng, 1, yyout ) -#endif - -/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, - * is returned in "result". - */ -#ifndef YY_INPUT -#define YY_INPUT(buf,result,max_size) \ - if ( yy_current_buffer->yy_is_interactive ) \ - { \ - int c = '*', n; \ - for ( n = 0; n < max_size && \ - (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ - buf[n] = (char) c; \ - if ( c == '\n' ) \ - buf[n++] = (char) c; \ - if ( c == EOF && ferror( yyin ) ) \ - YY_FATAL_ERROR( "input in flex scanner failed" ); \ - result = n; \ - } \ - else \ - { \ - errno=0; \ - while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ - { \ - if( errno != EINTR) \ - { \ - YY_FATAL_ERROR( "input in flex scanner failed" ); \ - break; \ - } \ - errno=0; \ - clearerr(yyin); \ - } \ - } -#endif - -/* No semi-colon after return; correct usage is to write "yyterminate();" - - * we don't want an extra ';' after the "return" because that will cause - * some compilers to complain about unreachable statements. - */ -#ifndef yyterminate -#define yyterminate() return YY_NULL -#endif - -/* Number of entries by which start-condition stack grows. */ -#ifndef YY_START_STACK_INCR -#define YY_START_STACK_INCR 25 -#endif - -/* Report a fatal error. */ -#ifndef YY_FATAL_ERROR -#define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) -#endif - -/* Default declaration of generated scanner - a define so the user can - * easily add parameters. - */ -#ifndef YY_DECL -#define YY_DECL int yylex YY_PROTO(( void )) -#endif - -/* Code executed at the beginning of each rule, after yytext and yyleng - * have been set up. - */ -#ifndef YY_USER_ACTION -#define YY_USER_ACTION -#endif - -/* Code executed at the end of each rule. */ -#ifndef YY_BREAK -#define YY_BREAK break; -#endif - -#define YY_RULE_SETUP \ - YY_USER_ACTION - -YY_DECL - { - yy_state_type yy_current_state; - char *yy_cp, *yy_bp; - int yy_act; - -#line 43 "ps1.0_tokens.l" - - -#line 751 "_ps1.0_lexer.cpp" - - if ( yy_init ) - { - yy_init = 0; - -#ifdef YY_USER_INIT - YY_USER_INIT; -#endif - - if ( ! yy_start ) - yy_start = 1; /* first start state */ - - if ( ! yyin ) - yyin = stdin; - - if ( ! yyout ) - yyout = stdout; - - if ( ! yy_current_buffer ) - yy_current_buffer = - yy_create_buffer( yyin, YY_BUF_SIZE ); - - yy_load_buffer_state(); - } - - while ( 1 ) /* loops until end-of-file is reached */ - { - yy_cp = yy_c_buf_p; - - /* Support of yytext. */ - *yy_cp = yy_hold_char; - - /* yy_bp points to the position in yy_ch_buf of the start of - * the current run. - */ - yy_bp = yy_cp; - - yy_current_state = yy_start; -yy_match: - do - { - YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; - if ( yy_accept[yy_current_state] ) - { - yy_last_accepting_state = yy_current_state; - yy_last_accepting_cpos = yy_cp; - } - while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) - { - yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 231 ) - yy_c = yy_meta[(unsigned int) yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; - ++yy_cp; - } - while ( yy_base[yy_current_state] != 366 ); - -yy_find_action: - yy_act = yy_accept[yy_current_state]; - if ( yy_act == 0 ) - { /* have to back up */ - yy_cp = yy_last_accepting_cpos; - yy_current_state = yy_last_accepting_state; - yy_act = yy_accept[yy_current_state]; - } - - YY_DO_BEFORE_ACTION; - - -do_action: /* This label is used only to access EOF actions. */ - - - switch ( yy_act ) - { /* beginning of action switch */ - case 0: /* must back up */ - /* undo the effects of YY_DO_BEFORE_ACTION */ - *yy_cp = yy_hold_char; - yy_cp = yy_last_accepting_cpos; - yy_current_state = yy_last_accepting_state; - goto yy_find_action; - -case 1: -#line 46 "ps1.0_tokens.l" -case 2: -YY_RULE_SETUP -#line 46 "ps1.0_tokens.l" -{ - char ch; - while ((ch = yyinput()) != '\n') - ; - line_number++; - DBG_MESG("dbg: comment, NEWLINE", line_number-1); - return NEWLINE; - } - YY_BREAK -case 3: -#line 56 "ps1.0_tokens.l" -case 4: -#line 57 "ps1.0_tokens.l" -case 5: -YY_RULE_SETUP -#line 57 "ps1.0_tokens.l" -{ - ps10_lval.fval = (float)atof(yytext); - // debug - DBG_MESG("dbg: NUMBER", line_number); - return NUMBER; - } - YY_BREAK -case 6: -YY_RULE_SETUP -#line 67 "ps1.0_tokens.l" -{ - // debug - DBG_MESG("dbg: DEF", line_number); - BEGIN DEFSTATE; - return DEF; - } - YY_BREAK -case 7: -#line 76 "ps1.0_tokens.l" -case 8: -#line 77 "ps1.0_tokens.l" -case 9: -#line 78 "ps1.0_tokens.l" -case 10: -YY_RULE_SETUP -#line 78 "ps1.0_tokens.l" -{ - sprintf(buf, "dbg: REG = %s", yytext); - // debug - DBG_MESG(buf, line_number); - ps10_lval.sval = new string(yytext); - return REG; - } - YY_BREAK -case 11: -#line 87 "ps1.0_tokens.l" -case 12: -#line 88 "ps1.0_tokens.l" -case 13: -#line 89 "ps1.0_tokens.l" -case 14: -#line 90 "ps1.0_tokens.l" -case 15: -#line 91 "ps1.0_tokens.l" -case 16: -#line 92 "ps1.0_tokens.l" -case 17: -#line 93 "ps1.0_tokens.l" -case 18: -YY_RULE_SETUP -#line 93 "ps1.0_tokens.l" -{ - sprintf(buf, "dbg: BLENDOP = %s", yytext); - // debug - DBG_MESG(buf, line_number); - ps10_lval.sval = new string(yytext); - return BLENDOP; - } - YY_BREAK -case 19: -#line 102 "ps1.0_tokens.l" -case 20: -#line 103 "ps1.0_tokens.l" -case 21: -#line 104 "ps1.0_tokens.l" -case 22: -#line 105 "ps1.0_tokens.l" -case 23: -#line 106 "ps1.0_tokens.l" -case 24: -#line 107 "ps1.0_tokens.l" -case 25: -#line 108 "ps1.0_tokens.l" -case 26: -#line 109 "ps1.0_tokens.l" -case 27: -#line 110 "ps1.0_tokens.l" -case 28: -#line 111 "ps1.0_tokens.l" -case 29: -#line 112 "ps1.0_tokens.l" -case 30: -#line 113 "ps1.0_tokens.l" -case 31: -YY_RULE_SETUP -#line 113 "ps1.0_tokens.l" -{ - sprintf(buf, "dbg: ADDROP = %s", yytext); - // debug - DBG_MESG(buf, line_number); - ps10_lval.sval = new string(yytext); - return ADDROP; - } - YY_BREAK -case 32: -YY_RULE_SETUP -#line 123 "ps1.0_tokens.l" -{ - line_number++; - BEGIN 0; - // debug - DBG_MESG("dbg: NEWLINE", line_number-1); - return NEWLINE; - } - YY_BREAK -case 33: -YY_RULE_SETUP -#line 131 "ps1.0_tokens.l" -{ - } - YY_BREAK -case 34: -YY_RULE_SETUP -#line 134 "ps1.0_tokens.l" -{ - return HEADER; - } - YY_BREAK -case 35: -YY_RULE_SETUP -#line 138 "ps1.0_tokens.l" -{ - char buf[40]; - sprintf(buf, "character token == '%c'", *yytext); - DBG_MESG(buf, line_number); - return *yytext; - } - YY_BREAK -case 36: -YY_RULE_SETUP -#line 145 "ps1.0_tokens.l" -ECHO; - YY_BREAK -#line 988 "_ps1.0_lexer.cpp" -case YY_STATE_EOF(INITIAL): -case YY_STATE_EOF(DEFSTATE): - yyterminate(); - - case YY_END_OF_BUFFER: - { - /* Amount of text matched not including the EOB char. */ - int yy_amount_of_matched_text = (int) (yy_cp - yytext_ptr) - 1; - - /* Undo the effects of YY_DO_BEFORE_ACTION. */ - *yy_cp = yy_hold_char; - YY_RESTORE_YY_MORE_OFFSET - - if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_NEW ) - { - /* We're scanning a new file or input source. It's - * possible that this happened because the user - * just pointed yyin at a new source and called - * yylex(). If so, then we have to assure - * consistency between yy_current_buffer and our - * globals. Here is the right place to do so, because - * this is the first action (other than possibly a - * back-up) that will match for the new input source. - */ - yy_n_chars = yy_current_buffer->yy_n_chars; - yy_current_buffer->yy_input_file = yyin; - yy_current_buffer->yy_buffer_status = YY_BUFFER_NORMAL; - } - - /* Note that here we test for yy_c_buf_p "<=" to the position - * of the first EOB in the buffer, since yy_c_buf_p will - * already have been incremented past the NUL character - * (since all states make transitions on EOB to the - * end-of-buffer state). Contrast this with the test - * in input(). - */ - if ( yy_c_buf_p <= &yy_current_buffer->yy_ch_buf[yy_n_chars] ) - { /* This was really a NUL. */ - yy_state_type yy_next_state; - - yy_c_buf_p = yytext_ptr + yy_amount_of_matched_text; - - yy_current_state = yy_get_previous_state(); - - /* Okay, we're now positioned to make the NUL - * transition. We couldn't have - * yy_get_previous_state() go ahead and do it - * for us because it doesn't know how to deal - * with the possibility of jamming (and we don't - * want to build jamming into it because then it - * will run more slowly). - */ - - yy_next_state = yy_try_NUL_trans( yy_current_state ); - - yy_bp = yytext_ptr + YY_MORE_ADJ; - - if ( yy_next_state ) - { - /* Consume the NUL. */ - yy_cp = ++yy_c_buf_p; - yy_current_state = yy_next_state; - goto yy_match; - } - - else - { - yy_cp = yy_c_buf_p; - goto yy_find_action; - } - } - - else switch ( yy_get_next_buffer() ) - { - case EOB_ACT_END_OF_FILE: - { - yy_did_buffer_switch_on_eof = 0; - - if ( yywrap() ) - { - /* Note: because we've taken care in - * yy_get_next_buffer() to have set up - * yytext, we can now set up - * yy_c_buf_p so that if some total - * hoser (like flex itself) wants to - * call the scanner after we return the - * YY_NULL, it'll still work - another - * YY_NULL will get returned. - */ - yy_c_buf_p = yytext_ptr + YY_MORE_ADJ; - - yy_act = YY_STATE_EOF(YY_START); - goto do_action; - } - - else - { - if ( ! yy_did_buffer_switch_on_eof ) - YY_NEW_FILE; - } - break; - } - - case EOB_ACT_CONTINUE_SCAN: - yy_c_buf_p = - yytext_ptr + yy_amount_of_matched_text; - - yy_current_state = yy_get_previous_state(); - - yy_cp = yy_c_buf_p; - yy_bp = yytext_ptr + YY_MORE_ADJ; - goto yy_match; - - case EOB_ACT_LAST_MATCH: - yy_c_buf_p = - &yy_current_buffer->yy_ch_buf[yy_n_chars]; - - yy_current_state = yy_get_previous_state(); - - yy_cp = yy_c_buf_p; - yy_bp = yytext_ptr + YY_MORE_ADJ; - goto yy_find_action; - } - break; - } - - default: - YY_FATAL_ERROR( - "fatal flex scanner internal error--no action found" ); - } /* end of action switch */ - } /* end of scanning one token */ - } /* end of yylex */ - - -/* yy_get_next_buffer - try to read in a new buffer - * - * Returns a code representing an action: - * EOB_ACT_LAST_MATCH - - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position - * EOB_ACT_END_OF_FILE - end of file - */ - -static int yy_get_next_buffer() - { - char *dest = yy_current_buffer->yy_ch_buf; - char *source = yytext_ptr; - int number_to_move, i; - int ret_val; - - if ( yy_c_buf_p > &yy_current_buffer->yy_ch_buf[yy_n_chars + 1] ) - YY_FATAL_ERROR( - "fatal flex scanner internal error--end of buffer missed" ); - - if ( yy_current_buffer->yy_fill_buffer == 0 ) - { /* Don't try to fill the buffer, so this is an EOF. */ - if ( yy_c_buf_p - yytext_ptr - YY_MORE_ADJ == 1 ) - { - /* We matched a single character, the EOB, so - * treat this as a final EOF. - */ - return EOB_ACT_END_OF_FILE; - } - - else - { - /* We matched some text prior to the EOB, first - * process it. - */ - return EOB_ACT_LAST_MATCH; - } - } - - /* Try to read more data. */ - - /* First move last chars to start of buffer. */ - number_to_move = (int) (yy_c_buf_p - yytext_ptr) - 1; - - for ( i = 0; i < number_to_move; ++i ) - *(dest++) = *(source++); - - if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_EOF_PENDING ) - /* don't do the read, it's not guaranteed to return an EOF, - * just force an EOF - */ - yy_current_buffer->yy_n_chars = yy_n_chars = 0; - - else - { - int num_to_read = - yy_current_buffer->yy_buf_size - number_to_move - 1; - - while ( num_to_read <= 0 ) - { /* Not enough room in the buffer - grow it. */ -#ifdef YY_USES_REJECT - YY_FATAL_ERROR( -"input buffer overflow, can't enlarge buffer because scanner uses REJECT" ); -#else - - /* just a shorter name for the current buffer */ - YY_BUFFER_STATE b = yy_current_buffer; - - int yy_c_buf_p_offset = - (int) (yy_c_buf_p - b->yy_ch_buf); - - if ( b->yy_is_our_buffer ) - { - int new_size = b->yy_buf_size * 2; - - if ( new_size <= 0 ) - b->yy_buf_size += b->yy_buf_size / 8; - else - b->yy_buf_size *= 2; - - b->yy_ch_buf = (char *) - /* Include room in for 2 EOB chars. */ - yy_flex_realloc( (void *) b->yy_ch_buf, - b->yy_buf_size + 2 ); - } - else - /* Can't grow it, we don't own it. */ - b->yy_ch_buf = 0; - - if ( ! b->yy_ch_buf ) - YY_FATAL_ERROR( - "fatal error - scanner input buffer overflow" ); - - yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; - - num_to_read = yy_current_buffer->yy_buf_size - - number_to_move - 1; -#endif - } - - if ( num_to_read > YY_READ_BUF_SIZE ) - num_to_read = YY_READ_BUF_SIZE; - - /* Read in more data. */ - YY_INPUT( (&yy_current_buffer->yy_ch_buf[number_to_move]), - yy_n_chars, num_to_read ); - - yy_current_buffer->yy_n_chars = yy_n_chars; - } - - if ( yy_n_chars == 0 ) - { - if ( number_to_move == YY_MORE_ADJ ) - { - ret_val = EOB_ACT_END_OF_FILE; - yyrestart( yyin ); - } - - else - { - ret_val = EOB_ACT_LAST_MATCH; - yy_current_buffer->yy_buffer_status = - YY_BUFFER_EOF_PENDING; - } - } - - else - ret_val = EOB_ACT_CONTINUE_SCAN; - - yy_n_chars += number_to_move; - yy_current_buffer->yy_ch_buf[yy_n_chars] = YY_END_OF_BUFFER_CHAR; - yy_current_buffer->yy_ch_buf[yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; - - yytext_ptr = &yy_current_buffer->yy_ch_buf[0]; - - return ret_val; - } - - -/* yy_get_previous_state - get the state just before the EOB char was reached */ - -static yy_state_type yy_get_previous_state() - { - yy_state_type yy_current_state; - char *yy_cp; - - yy_current_state = yy_start; - - for ( yy_cp = yytext_ptr + YY_MORE_ADJ; yy_cp < yy_c_buf_p; ++yy_cp ) - { - YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); - if ( yy_accept[yy_current_state] ) - { - yy_last_accepting_state = yy_current_state; - yy_last_accepting_cpos = yy_cp; - } - while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) - { - yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 231 ) - yy_c = yy_meta[(unsigned int) yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; - } - - return yy_current_state; - } - - -/* yy_try_NUL_trans - try to make a transition on the NUL character - * - * synopsis - * next_state = yy_try_NUL_trans( current_state ); - */ - -#ifdef YY_USE_PROTOS -static yy_state_type yy_try_NUL_trans( yy_state_type yy_current_state ) -#else -static yy_state_type yy_try_NUL_trans( yy_current_state ) -yy_state_type yy_current_state; -#endif - { - int yy_is_jam; - char *yy_cp = yy_c_buf_p; - - YY_CHAR yy_c = 1; - if ( yy_accept[yy_current_state] ) - { - yy_last_accepting_state = yy_current_state; - yy_last_accepting_cpos = yy_cp; - } - while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) - { - yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 231 ) - yy_c = yy_meta[(unsigned int) yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; - yy_is_jam = (yy_current_state == 230); - - return yy_is_jam ? 0 : yy_current_state; - } - - -#ifndef YY_NO_UNPUT -#ifdef YY_USE_PROTOS -static void yyunput( int c, char *yy_bp ) -#else -static void yyunput( c, yy_bp ) -int c; -char *yy_bp; -#endif - { - char *yy_cp = yy_c_buf_p; - - /* undo effects of setting up yytext */ - *yy_cp = yy_hold_char; - - if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 ) - { /* need to shift things up to make room */ - /* +2 for EOB chars. */ - int number_to_move = yy_n_chars + 2; - char *dest = &yy_current_buffer->yy_ch_buf[ - yy_current_buffer->yy_buf_size + 2]; - char *source = - &yy_current_buffer->yy_ch_buf[number_to_move]; - - while ( source > yy_current_buffer->yy_ch_buf ) - *--dest = *--source; - - yy_cp += (int) (dest - source); - yy_bp += (int) (dest - source); - yy_current_buffer->yy_n_chars = - yy_n_chars = yy_current_buffer->yy_buf_size; - - if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 ) - YY_FATAL_ERROR( "flex scanner push-back overflow" ); - } - - *--yy_cp = (char) c; - - - yytext_ptr = yy_bp; - yy_hold_char = *yy_cp; - yy_c_buf_p = yy_cp; - } -#endif /* ifndef YY_NO_UNPUT */ - - -#ifdef __cplusplus -static int yyinput() -#else -static int input() -#endif - { - int c; - - *yy_c_buf_p = yy_hold_char; - - if ( *yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) - { - /* yy_c_buf_p now points to the character we want to return. - * If this occurs *before* the EOB characters, then it's a - * valid NUL; if not, then we've hit the end of the buffer. - */ - if ( yy_c_buf_p < &yy_current_buffer->yy_ch_buf[yy_n_chars] ) - /* This was really a NUL. */ - *yy_c_buf_p = '\0'; - - else - { /* need more input */ - int offset = yy_c_buf_p - yytext_ptr; - ++yy_c_buf_p; - - switch ( yy_get_next_buffer() ) - { - case EOB_ACT_LAST_MATCH: - /* This happens because yy_g_n_b() - * sees that we've accumulated a - * token and flags that we need to - * try matching the token before - * proceeding. But for input(), - * there's no matching to consider. - * So convert the EOB_ACT_LAST_MATCH - * to EOB_ACT_END_OF_FILE. - */ - - /* Reset buffer status. */ - yyrestart( yyin ); - - /* fall through */ - - case EOB_ACT_END_OF_FILE: - { - if ( yywrap() ) - return EOF; - - if ( ! yy_did_buffer_switch_on_eof ) - YY_NEW_FILE; -#ifdef __cplusplus - return yyinput(); -#else - return input(); -#endif - } - - case EOB_ACT_CONTINUE_SCAN: - yy_c_buf_p = yytext_ptr + offset; - break; - } - } - } - - c = *(unsigned char *) yy_c_buf_p; /* cast for 8-bit char's */ - *yy_c_buf_p = '\0'; /* preserve yytext */ - yy_hold_char = *++yy_c_buf_p; - - - return c; - } - - -#ifdef YY_USE_PROTOS -void yyrestart( FILE *input_file ) -#else -void yyrestart( input_file ) -FILE *input_file; -#endif - { - if ( ! yy_current_buffer ) - yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); - - yy_init_buffer( yy_current_buffer, input_file ); - yy_load_buffer_state(); - } - - -#ifdef YY_USE_PROTOS -void yy_switch_to_buffer( YY_BUFFER_STATE new_buffer ) -#else -void yy_switch_to_buffer( new_buffer ) -YY_BUFFER_STATE new_buffer; -#endif - { - if ( yy_current_buffer == new_buffer ) - return; - - if ( yy_current_buffer ) - { - /* Flush out information for old buffer. */ - *yy_c_buf_p = yy_hold_char; - yy_current_buffer->yy_buf_pos = yy_c_buf_p; - yy_current_buffer->yy_n_chars = yy_n_chars; - } - - yy_current_buffer = new_buffer; - yy_load_buffer_state(); - - /* We don't actually know whether we did this switch during - * EOF (yywrap()) processing, but the only time this flag - * is looked at is after yywrap() is called, so it's safe - * to go ahead and always set it. - */ - yy_did_buffer_switch_on_eof = 1; - } - - -#ifdef YY_USE_PROTOS -void yy_load_buffer_state( void ) -#else -void yy_load_buffer_state() -#endif - { - yy_n_chars = yy_current_buffer->yy_n_chars; - yytext_ptr = yy_c_buf_p = yy_current_buffer->yy_buf_pos; - yyin = yy_current_buffer->yy_input_file; - yy_hold_char = *yy_c_buf_p; - } - - -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_create_buffer( FILE *file, int size ) -#else -YY_BUFFER_STATE yy_create_buffer( file, size ) -FILE *file; -int size; -#endif - { - YY_BUFFER_STATE b; - - b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) ); - if ( ! b ) - YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); - - b->yy_buf_size = size; - - /* yy_ch_buf has to be 2 characters longer than the size given because - * we need to put in 2 end-of-buffer characters. - */ - b->yy_ch_buf = (char *) yy_flex_alloc( b->yy_buf_size + 2 ); - if ( ! b->yy_ch_buf ) - YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); - - b->yy_is_our_buffer = 1; - - yy_init_buffer( b, file ); - - return b; - } - - -#ifdef YY_USE_PROTOS -void yy_delete_buffer( YY_BUFFER_STATE b ) -#else -void yy_delete_buffer( b ) -YY_BUFFER_STATE b; -#endif - { - if ( ! b ) - return; - - if ( b == yy_current_buffer ) - yy_current_buffer = (YY_BUFFER_STATE) 0; - - if ( b->yy_is_our_buffer ) - yy_flex_free( (void *) b->yy_ch_buf ); - - yy_flex_free( (void *) b ); - } - - -#ifndef _WIN32 -#include -#else -#ifndef YY_ALWAYS_INTERACTIVE -#ifndef YY_NEVER_INTERACTIVE -extern int isatty YY_PROTO(( int )); -#endif -#endif -#endif - -#ifdef YY_USE_PROTOS -void yy_init_buffer( YY_BUFFER_STATE b, FILE *file ) -#else -void yy_init_buffer( b, file ) -YY_BUFFER_STATE b; -FILE *file; -#endif - - - { - yy_flush_buffer( b ); - - b->yy_input_file = file; - b->yy_fill_buffer = 1; - -#if YY_ALWAYS_INTERACTIVE - b->yy_is_interactive = 1; -#else -#if YY_NEVER_INTERACTIVE - b->yy_is_interactive = 0; -#else - b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; -#endif -#endif - } - - -#ifdef YY_USE_PROTOS -void yy_flush_buffer( YY_BUFFER_STATE b ) -#else -void yy_flush_buffer( b ) -YY_BUFFER_STATE b; -#endif - - { - if ( ! b ) - return; - - b->yy_n_chars = 0; - - /* We always need two end-of-buffer characters. The first causes - * a transition to the end-of-buffer state. The second causes - * a jam in that state. - */ - b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; - b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; - - b->yy_buf_pos = &b->yy_ch_buf[0]; - - b->yy_at_bol = 1; - b->yy_buffer_status = YY_BUFFER_NEW; - - if ( b == yy_current_buffer ) - yy_load_buffer_state(); - } - - -#ifndef YY_NO_SCAN_BUFFER -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_scan_buffer( char *base, yy_size_t size ) -#else -YY_BUFFER_STATE yy_scan_buffer( base, size ) -char *base; -yy_size_t size; -#endif - { - YY_BUFFER_STATE b; - - if ( size < 2 || - base[size-2] != YY_END_OF_BUFFER_CHAR || - base[size-1] != YY_END_OF_BUFFER_CHAR ) - /* They forgot to leave room for the EOB's. */ - return 0; - - b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) ); - if ( ! b ) - YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); - - b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ - b->yy_buf_pos = b->yy_ch_buf = base; - b->yy_is_our_buffer = 0; - b->yy_input_file = 0; - b->yy_n_chars = b->yy_buf_size; - b->yy_is_interactive = 0; - b->yy_at_bol = 1; - b->yy_fill_buffer = 0; - b->yy_buffer_status = YY_BUFFER_NEW; - - yy_switch_to_buffer( b ); - - return b; - } -#endif - - -#ifndef YY_NO_SCAN_STRING -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_scan_string( yyconst char *yy_str ) -#else -YY_BUFFER_STATE yy_scan_string( yy_str ) -yyconst char *yy_str; -#endif - { - int len; - for ( len = 0; yy_str[len]; ++len ) - ; - - return yy_scan_bytes( yy_str, len ); - } -#endif - - -#ifndef YY_NO_SCAN_BYTES -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_scan_bytes( yyconst char *bytes, int len ) -#else -YY_BUFFER_STATE yy_scan_bytes( bytes, len ) -yyconst char *bytes; -int len; -#endif - { - YY_BUFFER_STATE b; - char *buf; - yy_size_t n; - int i; - - /* Get memory for full buffer, including space for trailing EOB's. */ - n = len + 2; - buf = (char *) yy_flex_alloc( n ); - if ( ! buf ) - YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); - - for ( i = 0; i < len; ++i ) - buf[i] = bytes[i]; - - buf[len] = buf[len+1] = YY_END_OF_BUFFER_CHAR; - - b = yy_scan_buffer( buf, n ); - if ( ! b ) - YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); - - /* It's okay to grow etc. this buffer, and we should throw it - * away when we're done. - */ - b->yy_is_our_buffer = 1; - - return b; - } -#endif - - -#ifndef YY_NO_PUSH_STATE -#ifdef YY_USE_PROTOS -static void yy_push_state( int new_state ) -#else -static void yy_push_state( new_state ) -int new_state; -#endif - { - if ( yy_start_stack_ptr >= yy_start_stack_depth ) - { - yy_size_t new_size; - - yy_start_stack_depth += YY_START_STACK_INCR; - new_size = yy_start_stack_depth * sizeof( int ); - - if ( ! yy_start_stack ) - yy_start_stack = (int *) yy_flex_alloc( new_size ); - - else - yy_start_stack = (int *) yy_flex_realloc( - (void *) yy_start_stack, new_size ); - - if ( ! yy_start_stack ) - YY_FATAL_ERROR( - "out of memory expanding start-condition stack" ); - } - - yy_start_stack[yy_start_stack_ptr++] = YY_START; - - BEGIN(new_state); - } -#endif - - -#ifndef YY_NO_POP_STATE -static void yy_pop_state() - { - if ( --yy_start_stack_ptr < 0 ) - YY_FATAL_ERROR( "start-condition stack underflow" ); - - BEGIN(yy_start_stack[yy_start_stack_ptr]); - } -#endif - - -#ifndef YY_NO_TOP_STATE -static int yy_top_state() - { - return yy_start_stack[yy_start_stack_ptr - 1]; - } -#endif - -#ifndef YY_EXIT_FAILURE -#define YY_EXIT_FAILURE 2 -#endif - -#ifdef YY_USE_PROTOS -static void yy_fatal_error( yyconst char msg[] ) -#else -static void yy_fatal_error( msg ) -char msg[]; -#endif - { - (void) fprintf( stderr, "%s\n", msg ); - exit( YY_EXIT_FAILURE ); - } - - - -/* Redefine yyless() so it works in section 3 code. */ - -#undef yyless -#define yyless(n) \ - do \ - { \ - /* Undo effects of setting up yytext. */ \ - yytext[yyleng] = yy_hold_char; \ - yy_c_buf_p = yytext + n; \ - yy_hold_char = *yy_c_buf_p; \ - *yy_c_buf_p = '\0'; \ - yyleng = n; \ - } \ - while ( 0 ) - - -/* Internal utility routines. */ - -#ifndef yytext_ptr -#ifdef YY_USE_PROTOS -static void yy_flex_strncpy( char *s1, yyconst char *s2, int n ) -#else -static void yy_flex_strncpy( s1, s2, n ) -char *s1; -yyconst char *s2; -int n; -#endif - { - int i; - for ( i = 0; i < n; ++i ) - s1[i] = s2[i]; - } -#endif - -#ifdef YY_NEED_STRLEN -#ifdef YY_USE_PROTOS -static int yy_flex_strlen( yyconst char *s ) -#else -static int yy_flex_strlen( s ) -yyconst char *s; -#endif - { - int n; - for ( n = 0; s[n]; ++n ) - ; - - return n; - } -#endif - - -#ifdef YY_USE_PROTOS -static void *yy_flex_alloc( yy_size_t size ) -#else -static void *yy_flex_alloc( size ) -yy_size_t size; -#endif - { - return (void *) malloc( size ); - } - -#ifdef YY_USE_PROTOS -static void *yy_flex_realloc( void *ptr, yy_size_t size ) -#else -static void *yy_flex_realloc( ptr, size ) -void *ptr; -yy_size_t size; -#endif - { - /* The cast to (char *) in the following accommodates both - * implementations that use char* generic pointers, and those - * that use void* generic pointers. It works with the latter - * because both ANSI C and C++ allow castless assignment from - * any pointer type to void*, and deal with argument conversions - * as though doing an assignment. - */ - return (void *) realloc( (char *) ptr, size ); - } - -#ifdef YY_USE_PROTOS -static void yy_flex_free( void *ptr ) -#else -static void yy_flex_free( ptr ) -void *ptr; -#endif - { - free( ptr ); - } - -#if YY_MAIN -int main() - { - yylex(); - return 0; - } -#endif -#line 145 "ps1.0_tokens.l" - -bool ps10_init(char* inputString) -{ - myin = inputString; - return init_extensions(); -} - -#ifndef ps10_wrap -int ps10_wrap(void) -{ - return(1); -} -#endif diff --git a/RenderSystems/GL/src/nvparse/_ps1.0_parser.cpp b/RenderSystems/GL/src/nvparse/_ps1.0_parser.cpp deleted file mode 100644 index 92018e89057..00000000000 --- a/RenderSystems/GL/src/nvparse/_ps1.0_parser.cpp +++ /dev/null @@ -1,1796 +0,0 @@ -/* A Bison parser, made by GNU Bison 3.0.2. */ - -/* Bison implementation for Yacc-like parsers in C - - Copyright (C) 1984, 1989-1990, 2000-2013 Free Software Foundation, Inc. - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . */ - -/* As a special exception, you may create a larger work that contains - part or all of the Bison parser skeleton and distribute that work - under terms of your choice, so long as that work isn't itself a - parser generator using the skeleton or a modified version thereof - as a parser skeleton. Alternatively, if you modify or redistribute - the parser skeleton itself, you may (at your option) remove this - special exception, which will cause the skeleton and the resulting - Bison output files to be licensed under the GNU General Public - License without this special exception. - - This special exception was added by the Free Software Foundation in - version 2.2 of Bison. */ - -/* C LALR(1) parser skeleton written by Richard Stallman, by - simplifying the original so-called "semantic" parser. */ - -/* All symbols defined below should begin with yy or YY, to avoid - infringing on user name space. This should be done even for local - variables, as they might otherwise be expanded by user macros. - There are some unavoidable exceptions within include files to - define necessary library symbols; they are noted "INFRINGES ON - USER NAME SPACE" below. */ - -/* Identify Bison output. */ -#define YYBISON 1 - -/* Bison version. */ -#define YYBISON_VERSION "3.0.2" - -/* Skeleton name. */ -#define YYSKELETON_NAME "yacc.c" - -/* Pure parsers. */ -#define YYPURE 0 - -/* Push parsers. */ -#define YYPUSH 0 - -/* Pull parsers. */ -#define YYPULL 1 - - -/* Substitute the variable and function names. */ -#define yyparse ps10_parse -#define yylex ps10_lex -#define yyerror ps10_error -#define yydebug ps10_debug -#define yynerrs ps10_nerrs - -#define yylval ps10_lval -#define yychar ps10_char - -/* Copy the first part of user declarations. */ -#line 3 "ps1.0_grammar.y" /* yacc.c:339 */ - - -/* - - This is a parser for the DX8 PS1.0 pixel shaders. I intend - to use it to set NV_texture_shader* and NV_register_combiners* - state in OpenGL, but the parse tree could be used for any - other purpose. - - Cass Everitt - 7-19-01 - -*/ - -void yyerror(const char* s); -int yylex ( void ); - -#ifdef _WIN32 -# include -#endif - -#include -#include - -#include "ps1.0_program.h" -#include "nvparse_errors.h" -#include "nvparse_externs.h" - -#include -#include - -using namespace std; -using namespace ps10; - -//#define DBG_MESG(msg, line) errors.set(msg, line) -#define DBG_MESG(msg, line) - - - -#line 114 "_ps1.0_parser.c" /* yacc.c:339 */ - -# ifndef YY_NULLPTR -# if defined __cplusplus && 201103L <= __cplusplus -# define YY_NULLPTR nullptr -# else -# define YY_NULLPTR 0 -# endif -# endif - -/* Enabling verbose error messages. */ -#ifdef YYERROR_VERBOSE -# undef YYERROR_VERBOSE -# define YYERROR_VERBOSE 1 -#else -# define YYERROR_VERBOSE 0 -#endif - -/* In a future release of Bison, this section will be replaced - by #include "_ps1.0_parser.h". */ -#ifndef YY_PS10_PS1_0_PARSER_H_INCLUDED -# define YY_PS10_PS1_0_PARSER_H_INCLUDED -/* Debug traces. */ -#ifndef YYDEBUG -# define YYDEBUG 0 -#endif -#if YYDEBUG -extern int ps10_debug; -#endif - -/* Token type. */ -#ifndef YYTOKENTYPE -# define YYTOKENTYPE - enum yytokentype - { - HEADER = 258, - NEWLINE = 259, - NUMBER = 260, - REG = 261, - DEF = 262, - ADDROP = 263, - BLENDOP = 264 - }; -#endif - -/* Value type. */ -#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED -typedef union YYSTYPE YYSTYPE; -union YYSTYPE -{ -#line 43 "ps1.0_grammar.y" /* yacc.c:355 */ - - int ival; - float fval; - - string * sval; - constdef * cdef; - vector * consts; - vector * line; - list > * lines; - -#line 175 "_ps1.0_parser.c" /* yacc.c:355 */ -}; -# define YYSTYPE_IS_TRIVIAL 1 -# define YYSTYPE_IS_DECLARED 1 -#endif - - -extern YYSTYPE ps10_lval; - -int ps10_parse (void); - -#endif /* !YY_PS10_PS1_0_PARSER_H_INCLUDED */ - -/* Copy the second part of user declarations. */ - -#line 190 "_ps1.0_parser.c" /* yacc.c:358 */ - -#ifdef short -# undef short -#endif - -#ifdef YYTYPE_UINT8 -typedef YYTYPE_UINT8 yytype_uint8; -#else -typedef unsigned char yytype_uint8; -#endif - -#ifdef YYTYPE_INT8 -typedef YYTYPE_INT8 yytype_int8; -#else -typedef signed char yytype_int8; -#endif - -#ifdef YYTYPE_UINT16 -typedef YYTYPE_UINT16 yytype_uint16; -#else -typedef unsigned short int yytype_uint16; -#endif - -#ifdef YYTYPE_INT16 -typedef YYTYPE_INT16 yytype_int16; -#else -typedef short int yytype_int16; -#endif - -#ifndef YYSIZE_T -# ifdef __SIZE_TYPE__ -# define YYSIZE_T __SIZE_TYPE__ -# elif defined size_t -# define YYSIZE_T size_t -# elif ! defined YYSIZE_T -# include /* INFRINGES ON USER NAME SPACE */ -# define YYSIZE_T size_t -# else -# define YYSIZE_T unsigned int -# endif -#endif - -#define YYSIZE_MAXIMUM ((YYSIZE_T) -1) - -#ifndef YY_ -# if defined YYENABLE_NLS && YYENABLE_NLS -# if ENABLE_NLS -# include /* INFRINGES ON USER NAME SPACE */ -# define YY_(Msgid) dgettext ("bison-runtime", Msgid) -# endif -# endif -# ifndef YY_ -# define YY_(Msgid) Msgid -# endif -#endif - -#ifndef YY_ATTRIBUTE -# if (defined __GNUC__ \ - && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \ - || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C -# define YY_ATTRIBUTE(Spec) __attribute__(Spec) -# else -# define YY_ATTRIBUTE(Spec) /* empty */ -# endif -#endif - -#ifndef YY_ATTRIBUTE_PURE -# define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__)) -#endif - -#ifndef YY_ATTRIBUTE_UNUSED -# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__)) -#endif - -#if !defined _Noreturn \ - && (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112) -# if defined _MSC_VER && 1200 <= _MSC_VER -# define _Noreturn __declspec (noreturn) -# else -# define _Noreturn YY_ATTRIBUTE ((__noreturn__)) -# endif -#endif - -/* Suppress unused-variable warnings by "using" E. */ -#if ! defined lint || defined __GNUC__ -# define YYUSE(E) ((void) (E)) -#else -# define YYUSE(E) /* empty */ -#endif - -#if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ -/* Suppress an incorrect diagnostic about yylval being uninitialized. */ -# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ - _Pragma ("GCC diagnostic push") \ - _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\ - _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") -# define YY_IGNORE_MAYBE_UNINITIALIZED_END \ - _Pragma ("GCC diagnostic pop") -#else -# define YY_INITIAL_VALUE(Value) Value -#endif -#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN -# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN -# define YY_IGNORE_MAYBE_UNINITIALIZED_END -#endif -#ifndef YY_INITIAL_VALUE -# define YY_INITIAL_VALUE(Value) /* Nothing. */ -#endif - - -#if ! defined yyoverflow || YYERROR_VERBOSE - -/* The parser invokes alloca or malloc; define the necessary symbols. */ - -# ifdef YYSTACK_USE_ALLOCA -# if YYSTACK_USE_ALLOCA -# ifdef __GNUC__ -# define YYSTACK_ALLOC __builtin_alloca -# elif defined __BUILTIN_VA_ARG_INCR -# include /* INFRINGES ON USER NAME SPACE */ -# elif defined _AIX -# define YYSTACK_ALLOC __alloca -# elif defined _MSC_VER -# include /* INFRINGES ON USER NAME SPACE */ -# define alloca _alloca -# else -# define YYSTACK_ALLOC alloca -# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS -# include /* INFRINGES ON USER NAME SPACE */ - /* Use EXIT_SUCCESS as a witness for stdlib.h. */ -# ifndef EXIT_SUCCESS -# define EXIT_SUCCESS 0 -# endif -# endif -# endif -# endif -# endif - -# ifdef YYSTACK_ALLOC - /* Pacify GCC's 'empty if-body' warning. */ -# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) -# ifndef YYSTACK_ALLOC_MAXIMUM - /* The OS might guarantee only one guard page at the bottom of the stack, - and a page size can be as small as 4096 bytes. So we cannot safely - invoke alloca (N) if N exceeds 4096. Use a slightly smaller number - to allow for a few compiler-allocated temporary stack slots. */ -# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ -# endif -# else -# define YYSTACK_ALLOC YYMALLOC -# define YYSTACK_FREE YYFREE -# ifndef YYSTACK_ALLOC_MAXIMUM -# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM -# endif -# if (defined __cplusplus && ! defined EXIT_SUCCESS \ - && ! ((defined YYMALLOC || defined malloc) \ - && (defined YYFREE || defined free))) -# include /* INFRINGES ON USER NAME SPACE */ -# ifndef EXIT_SUCCESS -# define EXIT_SUCCESS 0 -# endif -# endif -# ifndef YYMALLOC -# define YYMALLOC malloc -# if ! defined malloc && ! defined EXIT_SUCCESS -void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ -# endif -# endif -# ifndef YYFREE -# define YYFREE free -# if ! defined free && ! defined EXIT_SUCCESS -void free (void *); /* INFRINGES ON USER NAME SPACE */ -# endif -# endif -# endif -#endif /* ! defined yyoverflow || YYERROR_VERBOSE */ - - -#if (! defined yyoverflow \ - && (! defined __cplusplus \ - || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) - -/* A type that is properly aligned for any stack member. */ -union yyalloc -{ - yytype_int16 yyss_alloc; - YYSTYPE yyvs_alloc; -}; - -/* The size of the maximum gap between one aligned stack and the next. */ -# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) - -/* The size of an array large to enough to hold all stacks, each with - N elements. */ -# define YYSTACK_BYTES(N) \ - ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ - + YYSTACK_GAP_MAXIMUM) - -# define YYCOPY_NEEDED 1 - -/* Relocate STACK from its old location to the new one. The - local variables YYSIZE and YYSTACKSIZE give the old and new number of - elements in the stack, and YYPTR gives the new location of the - stack. Advance YYPTR to a properly aligned location for the next - stack. */ -# define YYSTACK_RELOCATE(Stack_alloc, Stack) \ - do \ - { \ - YYSIZE_T yynewbytes; \ - YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ - Stack = &yyptr->Stack_alloc; \ - yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ - yyptr += yynewbytes / sizeof (*yyptr); \ - } \ - while (0) - -#endif - -#if defined YYCOPY_NEEDED && YYCOPY_NEEDED -/* Copy COUNT objects from SRC to DST. The source and destination do - not overlap. */ -# ifndef YYCOPY -# if defined __GNUC__ && 1 < __GNUC__ -# define YYCOPY(Dst, Src, Count) \ - __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src))) -# else -# define YYCOPY(Dst, Src, Count) \ - do \ - { \ - YYSIZE_T yyi; \ - for (yyi = 0; yyi < (Count); yyi++) \ - (Dst)[yyi] = (Src)[yyi]; \ - } \ - while (0) -# endif -# endif -#endif /* !YYCOPY_NEEDED */ - -/* YYFINAL -- State number of the termination state. */ -#define YYFINAL 6 -/* YYLAST -- Last index in YYTABLE. */ -#define YYLAST 80 - -/* YYNTOKENS -- Number of terminals. */ -#define YYNTOKENS 12 -/* YYNNTS -- Number of nonterminals. */ -#define YYNNTS 10 -/* YYNRULES -- Number of rules. */ -#define YYNRULES 26 -/* YYNSTATES -- Number of states. */ -#define YYNSTATES 63 - -/* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned - by yylex, with out-of-bounds checking. */ -#define YYUNDEFTOK 2 -#define YYMAXUTOK 264 - -#define YYTRANSLATE(YYX) \ - ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) - -/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM - as returned by yylex, without out-of-bounds checking. */ -static const yytype_uint8 yytranslate[] = -{ - 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 11, 10, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, - 5, 6, 7, 8, 9 -}; - -#if YYDEBUG - /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ -static const yytype_uint16 yyrline[] = -{ - 0, 72, 72, 79, 86, 93, 100, 107, 114, 121, - 131, 139, 151, 165, 173, 184, 194, 206, 223, 231, - 243, 257, 273, 293, 295, 301, 305 -}; -#endif - -#if YYDEBUG || YYERROR_VERBOSE || 0 -/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. - First, the terminals, then, starting at YYNTOKENS, nonterminals. */ -static const char *const yytname[] = -{ - "$end", "error", "$undefined", "HEADER", "NEWLINE", "NUMBER", "REG", - "DEF", "ADDROP", "BLENDOP", "','", "'+'", "$accept", "WholeEnchilada", - "Defs", "Def", "AddrOps", "AddrOp", "BlendOps", "BlendOp", "MaybePlus", - "Newlines", YY_NULLPTR -}; -#endif - -# ifdef YYPRINT -/* YYTOKNUM[NUM] -- (External) token number corresponding to the - (internal) symbol number NUM (which must be that of a token). */ -static const yytype_uint16 yytoknum[] = -{ - 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, - 44, 43 -}; -# endif - -#define YYPACT_NINF -15 - -#define yypact_value_is_default(Yystate) \ - (!!((Yystate) == (-15))) - -#define YYTABLE_NINF -24 - -#define yytable_value_is_error(Yytable_value) \ - 0 - - /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing - STATE-NUM. */ -static const yytype_int8 yypact[] = -{ - 10, 1, -15, 47, 52, 0, -15, 1, -15, 37, - 51, -15, 43, -15, 41, -15, -8, -15, 53, 0, - 50, 26, -15, 41, -8, -15, -8, -15, 55, 43, - 41, -8, 58, 59, 60, -8, 56, 41, -8, -8, - 57, 27, 62, -8, 64, 65, 60, 34, 63, 1, - 66, 60, 69, 60, 35, 67, 70, 60, 73, 1, - 1, 60, 60 -}; - - /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. - Performed when YYTABLE does not specify something else to do. Zero - means the default is an error. */ -static const yytype_uint8 yydefact[] = -{ - 0, 0, 25, 0, 0, 23, 1, 0, 26, 0, - 0, 24, 23, 10, 23, 13, 8, 18, 0, 23, - 0, 0, 11, 23, 6, 14, 4, 19, 0, 23, - 23, 9, 0, 0, 15, 2, 0, 23, 7, 5, - 0, 0, 0, 3, 0, 0, 16, 0, 0, 0, - 0, 20, 0, 17, 0, 0, 0, 21, 0, 0, - 0, 22, 12 -}; - - /* YYPGOTO[NTERM-NUM]. */ -static const yytype_int8 yypgoto[] = -{ - -15, -15, 61, -3, 3, 5, 4, -14, -15, -1 -}; - - /* YYDEFGOTO[NTERM-NUM]. */ -static const yytype_int8 yydefgoto[] = -{ - -1, 3, 12, 13, 14, 15, 16, 17, 18, 4 -}; - - /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If - positive, shift that token. If negative, reduce the rule whose - number is the opposite. If YYTABLE_NINF, syntax error. */ -static const yytype_int8 yytable[] = -{ - 5, -23, 27, 11, 8, 2, 19, 9, 10, 22, - 27, 11, 27, 1, 2, 23, 24, 27, 26, 25, - 34, 27, 30, 31, 27, 27, 22, 35, 25, 27, - 2, 2, 37, 38, 39, 25, 33, 45, 2, 2, - 46, 43, 25, 20, 50, 56, 51, 6, 53, 10, - 9, 10, 11, 57, 11, 7, 8, 21, 61, 62, - 32, 36, 28, 40, 8, 41, 42, 44, 47, 48, - 0, 49, 54, 52, 55, 0, 59, 58, 60, 0, - 29 -}; - -static const yytype_int8 yycheck[] = -{ - 1, 9, 16, 11, 4, 4, 7, 7, 8, 12, - 24, 11, 26, 3, 4, 12, 12, 31, 14, 14, - 21, 35, 19, 19, 38, 39, 29, 23, 23, 43, - 4, 4, 29, 29, 30, 30, 10, 10, 4, 4, - 41, 37, 37, 6, 10, 10, 47, 0, 49, 8, - 7, 8, 11, 54, 11, 3, 4, 6, 59, 60, - 10, 6, 9, 5, 4, 6, 10, 10, 6, 5, - -1, 6, 6, 10, 5, -1, 6, 10, 5, -1, - 19 -}; - - /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing - symbol of state STATE-NUM. */ -static const yytype_uint8 yystos[] = -{ - 0, 3, 4, 13, 21, 21, 0, 3, 4, 7, - 8, 11, 14, 15, 16, 17, 18, 19, 20, 21, - 6, 6, 15, 16, 18, 17, 18, 19, 9, 14, - 16, 18, 10, 10, 21, 18, 6, 16, 18, 18, - 5, 6, 10, 18, 10, 10, 21, 6, 5, 6, - 10, 21, 10, 21, 6, 5, 10, 21, 10, 6, - 5, 21, 21 -}; - - /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ -static const yytype_uint8 yyr1[] = -{ - 0, 12, 13, 13, 13, 13, 13, 13, 13, 13, - 14, 14, 15, 16, 16, 17, 17, 17, 18, 18, - 19, 19, 19, 20, 20, 21, 21 -}; - - /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */ -static const yytype_uint8 yyr2[] = -{ - 0, 2, 5, 6, 4, 5, 4, 5, 3, 4, - 1, 2, 11, 1, 2, 3, 5, 7, 1, 2, - 6, 8, 10, 0, 1, 1, 2 -}; - - -#define yyerrok (yyerrstatus = 0) -#define yyclearin (yychar = YYEMPTY) -#define YYEMPTY (-2) -#define YYEOF 0 - -#define YYACCEPT goto yyacceptlab -#define YYABORT goto yyabortlab -#define YYERROR goto yyerrorlab - - -#define YYRECOVERING() (!!yyerrstatus) - -#define YYBACKUP(Token, Value) \ -do \ - if (yychar == YYEMPTY) \ - { \ - yychar = (Token); \ - yylval = (Value); \ - YYPOPSTACK (yylen); \ - yystate = *yyssp; \ - goto yybackup; \ - } \ - else \ - { \ - yyerror (YY_("syntax error: cannot back up")); \ - YYERROR; \ - } \ -while (0) - -/* Error token number */ -#define YYTERROR 1 -#define YYERRCODE 256 - - - -/* Enable debugging if requested. */ -#if YYDEBUG - -# ifndef YYFPRINTF -# include /* INFRINGES ON USER NAME SPACE */ -# define YYFPRINTF fprintf -# endif - -# define YYDPRINTF(Args) \ -do { \ - if (yydebug) \ - YYFPRINTF Args; \ -} while (0) - -/* This macro is provided for backward compatibility. */ -#ifndef YY_LOCATION_PRINT -# define YY_LOCATION_PRINT(File, Loc) ((void) 0) -#endif - - -# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ -do { \ - if (yydebug) \ - { \ - YYFPRINTF (stderr, "%s ", Title); \ - yy_symbol_print (stderr, \ - Type, Value); \ - YYFPRINTF (stderr, "\n"); \ - } \ -} while (0) - - -/*----------------------------------------. -| Print this symbol's value on YYOUTPUT. | -`----------------------------------------*/ - -static void -yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) -{ - FILE *yyo = yyoutput; - YYUSE (yyo); - if (!yyvaluep) - return; -# ifdef YYPRINT - if (yytype < YYNTOKENS) - YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); -# endif - YYUSE (yytype); -} - - -/*--------------------------------. -| Print this symbol on YYOUTPUT. | -`--------------------------------*/ - -static void -yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) -{ - YYFPRINTF (yyoutput, "%s %s (", - yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]); - - yy_symbol_value_print (yyoutput, yytype, yyvaluep); - YYFPRINTF (yyoutput, ")"); -} - -/*------------------------------------------------------------------. -| yy_stack_print -- Print the state stack from its BOTTOM up to its | -| TOP (included). | -`------------------------------------------------------------------*/ - -static void -yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) -{ - YYFPRINTF (stderr, "Stack now"); - for (; yybottom <= yytop; yybottom++) - { - int yybot = *yybottom; - YYFPRINTF (stderr, " %d", yybot); - } - YYFPRINTF (stderr, "\n"); -} - -# define YY_STACK_PRINT(Bottom, Top) \ -do { \ - if (yydebug) \ - yy_stack_print ((Bottom), (Top)); \ -} while (0) - - -/*------------------------------------------------. -| Report that the YYRULE is going to be reduced. | -`------------------------------------------------*/ - -static void -yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule) -{ - unsigned long int yylno = yyrline[yyrule]; - int yynrhs = yyr2[yyrule]; - int yyi; - YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", - yyrule - 1, yylno); - /* The symbols being reduced. */ - for (yyi = 0; yyi < yynrhs; yyi++) - { - YYFPRINTF (stderr, " $%d = ", yyi + 1); - yy_symbol_print (stderr, - yystos[yyssp[yyi + 1 - yynrhs]], - &(yyvsp[(yyi + 1) - (yynrhs)]) - ); - YYFPRINTF (stderr, "\n"); - } -} - -# define YY_REDUCE_PRINT(Rule) \ -do { \ - if (yydebug) \ - yy_reduce_print (yyssp, yyvsp, Rule); \ -} while (0) - -/* Nonzero means print parse trace. It is left uninitialized so that - multiple parsers can coexist. */ -int yydebug; -#else /* !YYDEBUG */ -# define YYDPRINTF(Args) -# define YY_SYMBOL_PRINT(Title, Type, Value, Location) -# define YY_STACK_PRINT(Bottom, Top) -# define YY_REDUCE_PRINT(Rule) -#endif /* !YYDEBUG */ - - -/* YYINITDEPTH -- initial size of the parser's stacks. */ -#ifndef YYINITDEPTH -# define YYINITDEPTH 200 -#endif - -/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only - if the built-in stack extension method is used). - - Do not make this value too large; the results are undefined if - YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) - evaluated with infinite-precision integer arithmetic. */ - -#ifndef YYMAXDEPTH -# define YYMAXDEPTH 10000 -#endif - - -#if YYERROR_VERBOSE - -# ifndef yystrlen -# if defined __GLIBC__ && defined _STRING_H -# define yystrlen strlen -# else -/* Return the length of YYSTR. */ -static YYSIZE_T -yystrlen (const char *yystr) -{ - YYSIZE_T yylen; - for (yylen = 0; yystr[yylen]; yylen++) - continue; - return yylen; -} -# endif -# endif - -# ifndef yystpcpy -# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE -# define yystpcpy stpcpy -# else -/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in - YYDEST. */ -static char * -yystpcpy (char *yydest, const char *yysrc) -{ - char *yyd = yydest; - const char *yys = yysrc; - - while ((*yyd++ = *yys++) != '\0') - continue; - - return yyd - 1; -} -# endif -# endif - -# ifndef yytnamerr -/* Copy to YYRES the contents of YYSTR after stripping away unnecessary - quotes and backslashes, so that it's suitable for yyerror. The - heuristic is that double-quoting is unnecessary unless the string - contains an apostrophe, a comma, or backslash (other than - backslash-backslash). YYSTR is taken from yytname. If YYRES is - null, do not copy; instead, return the length of what the result - would have been. */ -static YYSIZE_T -yytnamerr (char *yyres, const char *yystr) -{ - if (*yystr == '"') - { - YYSIZE_T yyn = 0; - char const *yyp = yystr; - - for (;;) - switch (*++yyp) - { - case '\'': - case ',': - goto do_not_strip_quotes; - - case '\\': - if (*++yyp != '\\') - goto do_not_strip_quotes; - /* Fall through. */ - default: - if (yyres) - yyres[yyn] = *yyp; - yyn++; - break; - - case '"': - if (yyres) - yyres[yyn] = '\0'; - return yyn; - } - do_not_strip_quotes: ; - } - - if (! yyres) - return yystrlen (yystr); - - return yystpcpy (yyres, yystr) - yyres; -} -# endif - -/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message - about the unexpected token YYTOKEN for the state stack whose top is - YYSSP. - - Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is - not large enough to hold the message. In that case, also set - *YYMSG_ALLOC to the required number of bytes. Return 2 if the - required number of bytes is too large to store. */ -static int -yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg, - yytype_int16 *yyssp, int yytoken) -{ - YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]); - YYSIZE_T yysize = yysize0; - enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; - /* Internationalized format string. */ - const char *yyformat = YY_NULLPTR; - /* Arguments of yyformat. */ - char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; - /* Number of reported tokens (one for the "unexpected", one per - "expected"). */ - int yycount = 0; - - /* There are many possibilities here to consider: - - If this state is a consistent state with a default action, then - the only way this function was invoked is if the default action - is an error action. In that case, don't check for expected - tokens because there are none. - - The only way there can be no lookahead present (in yychar) is if - this state is a consistent state with a default action. Thus, - detecting the absence of a lookahead is sufficient to determine - that there is no unexpected or expected token to report. In that - case, just report a simple "syntax error". - - Don't assume there isn't a lookahead just because this state is a - consistent state with a default action. There might have been a - previous inconsistent state, consistent state with a non-default - action, or user semantic action that manipulated yychar. - - Of course, the expected token list depends on states to have - correct lookahead information, and it depends on the parser not - to perform extra reductions after fetching a lookahead from the - scanner and before detecting a syntax error. Thus, state merging - (from LALR or IELR) and default reductions corrupt the expected - token list. However, the list is correct for canonical LR with - one exception: it will still contain any token that will not be - accepted due to an error action in a later state. - */ - if (yytoken != YYEMPTY) - { - int yyn = yypact[*yyssp]; - yyarg[yycount++] = yytname[yytoken]; - if (!yypact_value_is_default (yyn)) - { - /* Start YYX at -YYN if negative to avoid negative indexes in - YYCHECK. In other words, skip the first -YYN actions for - this state because they are default actions. */ - int yyxbegin = yyn < 0 ? -yyn : 0; - /* Stay within bounds of both yycheck and yytname. */ - int yychecklim = YYLAST - yyn + 1; - int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; - int yyx; - - for (yyx = yyxbegin; yyx < yyxend; ++yyx) - if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR - && !yytable_value_is_error (yytable[yyx + yyn])) - { - if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) - { - yycount = 1; - yysize = yysize0; - break; - } - yyarg[yycount++] = yytname[yyx]; - { - YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]); - if (! (yysize <= yysize1 - && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) - return 2; - yysize = yysize1; - } - } - } - } - - switch (yycount) - { -# define YYCASE_(N, S) \ - case N: \ - yyformat = S; \ - break - YYCASE_(0, YY_("syntax error")); - YYCASE_(1, YY_("syntax error, unexpected %s")); - YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); - YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); - YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); - YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); -# undef YYCASE_ - } - - { - YYSIZE_T yysize1 = yysize + yystrlen (yyformat); - if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) - return 2; - yysize = yysize1; - } - - if (*yymsg_alloc < yysize) - { - *yymsg_alloc = 2 * yysize; - if (! (yysize <= *yymsg_alloc - && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) - *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; - return 1; - } - - /* Avoid sprintf, as that infringes on the user's name space. - Don't have undefined behavior even if the translation - produced a string with the wrong number of "%s"s. */ - { - char *yyp = *yymsg; - int yyi = 0; - while ((*yyp = *yyformat) != '\0') - if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) - { - yyp += yytnamerr (yyp, yyarg[yyi++]); - yyformat += 2; - } - else - { - yyp++; - yyformat++; - } - } - return 0; -} -#endif /* YYERROR_VERBOSE */ - -/*-----------------------------------------------. -| Release the memory associated to this symbol. | -`-----------------------------------------------*/ - -static void -yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep) -{ - YYUSE (yyvaluep); - if (!yymsg) - yymsg = "Deleting"; - YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); - - YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN - YYUSE (yytype); - YY_IGNORE_MAYBE_UNINITIALIZED_END -} - - - - -/* The lookahead symbol. */ -int yychar; - -/* The semantic value of the lookahead symbol. */ -YYSTYPE yylval; -/* Number of syntax errors so far. */ -int yynerrs; - - -/*----------. -| yyparse. | -`----------*/ - -int -yyparse (void) -{ - int yystate; - /* Number of tokens to shift before error messages enabled. */ - int yyerrstatus; - - /* The stacks and their tools: - 'yyss': related to states. - 'yyvs': related to semantic values. - - Refer to the stacks through separate pointers, to allow yyoverflow - to reallocate them elsewhere. */ - - /* The state stack. */ - yytype_int16 yyssa[YYINITDEPTH]; - yytype_int16 *yyss; - yytype_int16 *yyssp; - - /* The semantic value stack. */ - YYSTYPE yyvsa[YYINITDEPTH]; - YYSTYPE *yyvs; - YYSTYPE *yyvsp; - - YYSIZE_T yystacksize; - - int yyn; - int yyresult; - /* Lookahead token as an internal (translated) token number. */ - int yytoken = 0; - /* The variables used to return semantic value and location from the - action routines. */ - YYSTYPE yyval; - -#if YYERROR_VERBOSE - /* Buffer for error messages, and its allocated size. */ - char yymsgbuf[128]; - char *yymsg = yymsgbuf; - YYSIZE_T yymsg_alloc = sizeof yymsgbuf; -#endif - -#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) - - /* The number of symbols on the RHS of the reduced rule. - Keep to zero when no symbol should be popped. */ - int yylen = 0; - - yyssp = yyss = yyssa; - yyvsp = yyvs = yyvsa; - yystacksize = YYINITDEPTH; - - YYDPRINTF ((stderr, "Starting parse\n")); - - yystate = 0; - yyerrstatus = 0; - yynerrs = 0; - yychar = YYEMPTY; /* Cause a token to be read. */ - goto yysetstate; - -/*------------------------------------------------------------. -| yynewstate -- Push a new state, which is found in yystate. | -`------------------------------------------------------------*/ - yynewstate: - /* In all cases, when you get here, the value and location stacks - have just been pushed. So pushing a state here evens the stacks. */ - yyssp++; - - yysetstate: - *yyssp = yystate; - - if (yyss + yystacksize - 1 <= yyssp) - { - /* Get the current used size of the three stacks, in elements. */ - YYSIZE_T yysize = yyssp - yyss + 1; - -#ifdef yyoverflow - { - /* Give user a chance to reallocate the stack. Use copies of - these so that the &'s don't force the real ones into - memory. */ - YYSTYPE *yyvs1 = yyvs; - yytype_int16 *yyss1 = yyss; - - /* Each stack pointer address is followed by the size of the - data in use in that stack, in bytes. This used to be a - conditional around just the two extra args, but that might - be undefined if yyoverflow is a macro. */ - yyoverflow (YY_("memory exhausted"), - &yyss1, yysize * sizeof (*yyssp), - &yyvs1, yysize * sizeof (*yyvsp), - &yystacksize); - - yyss = yyss1; - yyvs = yyvs1; - } -#else /* no yyoverflow */ -# ifndef YYSTACK_RELOCATE - goto yyexhaustedlab; -# else - /* Extend the stack our own way. */ - if (YYMAXDEPTH <= yystacksize) - goto yyexhaustedlab; - yystacksize *= 2; - if (YYMAXDEPTH < yystacksize) - yystacksize = YYMAXDEPTH; - - { - yytype_int16 *yyss1 = yyss; - union yyalloc *yyptr = - (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); - if (! yyptr) - goto yyexhaustedlab; - YYSTACK_RELOCATE (yyss_alloc, yyss); - YYSTACK_RELOCATE (yyvs_alloc, yyvs); -# undef YYSTACK_RELOCATE - if (yyss1 != yyssa) - YYSTACK_FREE (yyss1); - } -# endif -#endif /* no yyoverflow */ - - yyssp = yyss + yysize - 1; - yyvsp = yyvs + yysize - 1; - - YYDPRINTF ((stderr, "Stack size increased to %lu\n", - (unsigned long int) yystacksize)); - - if (yyss + yystacksize - 1 <= yyssp) - YYABORT; - } - - YYDPRINTF ((stderr, "Entering state %d\n", yystate)); - - if (yystate == YYFINAL) - YYACCEPT; - - goto yybackup; - -/*-----------. -| yybackup. | -`-----------*/ -yybackup: - - /* Do appropriate processing given the current state. Read a - lookahead token if we need one and don't already have one. */ - - /* First try to decide what to do without reference to lookahead token. */ - yyn = yypact[yystate]; - if (yypact_value_is_default (yyn)) - goto yydefault; - - /* Not known => get a lookahead token if don't already have one. */ - - /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ - if (yychar == YYEMPTY) - { - YYDPRINTF ((stderr, "Reading a token: ")); - yychar = yylex (); - } - - if (yychar <= YYEOF) - { - yychar = yytoken = YYEOF; - YYDPRINTF ((stderr, "Now at end of input.\n")); - } - else - { - yytoken = YYTRANSLATE (yychar); - YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); - } - - /* If the proper action on seeing token YYTOKEN is to reduce or to - detect an error, take that action. */ - yyn += yytoken; - if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) - goto yydefault; - yyn = yytable[yyn]; - if (yyn <= 0) - { - if (yytable_value_is_error (yyn)) - goto yyerrlab; - yyn = -yyn; - goto yyreduce; - } - - /* Count tokens shifted since error; after three, turn off error - status. */ - if (yyerrstatus) - yyerrstatus--; - - /* Shift the lookahead token. */ - YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); - - /* Discard the shifted token. */ - yychar = YYEMPTY; - - yystate = yyn; - YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN - *++yyvsp = yylval; - YY_IGNORE_MAYBE_UNINITIALIZED_END - - goto yynewstate; - - -/*-----------------------------------------------------------. -| yydefault -- do the default action for the current state. | -`-----------------------------------------------------------*/ -yydefault: - yyn = yydefact[yystate]; - if (yyn == 0) - goto yyerrlab; - goto yyreduce; - - -/*-----------------------------. -| yyreduce -- Do a reduction. | -`-----------------------------*/ -yyreduce: - /* yyn is the number of a rule to reduce with. */ - yylen = yyr2[yyn]; - - /* If YYLEN is nonzero, implement the default value of the action: - '$$ = $1'. - - Otherwise, the following line sets YYVAL to garbage. - This behavior is undocumented and Bison - users should not rely upon it. Assigning to YYVAL - unconditionally makes the parser a bit smaller, and it avoids a - GCC warning that YYVAL may be used uninitialized. */ - yyval = yyvsp[1-yylen]; - - - YY_REDUCE_PRINT (yyn); - switch (yyn) - { - case 2: -#line 73 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - DBG_MESG("dbg: WholeEnchilada", line_number); - ps10::invoke((yyvsp[-2].consts), (yyvsp[-1].lines), (yyvsp[0].lines)); - } -#line 1302 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 3: -#line 80 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - DBG_MESG("dbg: WholeEnchilada", line_number); - ps10::invoke((yyvsp[-2].consts), (yyvsp[-1].lines), (yyvsp[0].lines)); - } -#line 1311 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 4: -#line 87 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - DBG_MESG("dbg: WholeEnchilada", line_number); - ps10::invoke( 0, (yyvsp[-1].lines), (yyvsp[0].lines)); - } -#line 1320 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 5: -#line 94 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - DBG_MESG("dbg: WholeEnchilada", line_number); - ps10::invoke( 0, (yyvsp[-1].lines), (yyvsp[0].lines)); - } -#line 1329 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 6: -#line 101 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - DBG_MESG("dbg: WholeEnchilada", line_number); - ps10::invoke((yyvsp[-1].consts), 0, (yyvsp[0].lines)); - } -#line 1338 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 7: -#line 108 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - DBG_MESG("dbg: WholeEnchilada", line_number); - ps10::invoke((yyvsp[-1].consts), 0, (yyvsp[0].lines)); - } -#line 1347 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 8: -#line 115 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - DBG_MESG("dbg: WholeEnchilada", line_number); - ps10::invoke( 0, 0, (yyvsp[0].lines)); - } -#line 1356 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 9: -#line 122 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - DBG_MESG("dbg: WholeEnchilada", line_number); - ps10::invoke( 0, 0, (yyvsp[0].lines)); - } -#line 1365 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 10: -#line 132 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.consts) = new vector; - (yyval.consts)->push_back(* (yyvsp[0].cdef)); - delete (yyvsp[0].cdef); - } -#line 1375 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 11: -#line 140 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.consts) = (yyvsp[-1].consts); - (yyval.consts)->push_back(* (yyvsp[0].cdef)); - delete (yyvsp[0].cdef); - } -#line 1385 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 12: -#line 152 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.cdef) = new constdef; - (yyval.cdef)->reg = * (yyvsp[-9].sval); - (yyval.cdef)->r = (yyvsp[-7].fval); - (yyval.cdef)->g = (yyvsp[-5].fval); - (yyval.cdef)->b = (yyvsp[-3].fval); - (yyval.cdef)->a = (yyvsp[-1].fval); - delete (yyvsp[-9].sval); - } -#line 1399 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 13: -#line 166 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.lines) = new list >; - (yyval.lines)->push_back(* (yyvsp[0].line)); - delete (yyvsp[0].line); - } -#line 1409 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 14: -#line 174 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.lines) = (yyvsp[-1].lines); - (yyval.lines)->push_back(* (yyvsp[0].line)); - delete (yyvsp[0].line); - } -#line 1419 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 15: -#line 185 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.line) = new vector; - (yyval.line)->push_back(* (yyvsp[-2].sval)); - (yyval.line)->push_back(* (yyvsp[-1].sval)); - delete (yyvsp[-2].sval); - delete (yyvsp[-1].sval); - } -#line 1431 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 16: -#line 195 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.line) = new vector; - (yyval.line)->push_back(* (yyvsp[-4].sval)); - (yyval.line)->push_back(* (yyvsp[-3].sval)); - (yyval.line)->push_back(* (yyvsp[-1].sval)); - delete (yyvsp[-4].sval); - delete (yyvsp[-3].sval); - delete (yyvsp[-1].sval); - } -#line 1445 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 17: -#line 207 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.line) = new vector; - (yyval.line)->push_back(* (yyvsp[-6].sval)); - (yyval.line)->push_back(* (yyvsp[-5].sval)); - (yyval.line)->push_back(* (yyvsp[-3].sval)); - (yyval.line)->push_back(* (yyvsp[-1].sval)); - delete (yyvsp[-6].sval); - delete (yyvsp[-5].sval); - delete (yyvsp[-3].sval); - delete (yyvsp[-1].sval); - } -#line 1461 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 18: -#line 224 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.lines) = new list >; - (yyval.lines)->push_back(* (yyvsp[0].line)); - delete (yyvsp[0].line); - } -#line 1471 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 19: -#line 232 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.lines) = (yyvsp[-1].lines); - (yyval.lines)->push_back(* (yyvsp[0].line)); - delete (yyvsp[0].line); - } -#line 1481 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 20: -#line 244 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.line) = new vector; - if ( (yyvsp[-5].ival) ) - (yyval.line)->push_back("+"); - (yyval.line)->push_back(* (yyvsp[-4].sval)); - (yyval.line)->push_back(* (yyvsp[-3].sval)); - (yyval.line)->push_back(* (yyvsp[-1].sval)); - delete (yyvsp[-4].sval); - delete (yyvsp[-3].sval); - delete (yyvsp[-1].sval); - } -#line 1497 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 21: -#line 258 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.line) = new vector; - if ( (yyvsp[-7].ival) ) - (yyval.line)->push_back("+"); - (yyval.line)->push_back(* (yyvsp[-6].sval)); - (yyval.line)->push_back(* (yyvsp[-5].sval)); - (yyval.line)->push_back(* (yyvsp[-3].sval)); - (yyval.line)->push_back(* (yyvsp[-1].sval)); - delete (yyvsp[-6].sval); - delete (yyvsp[-5].sval); - delete (yyvsp[-3].sval); - delete (yyvsp[-1].sval); - } -#line 1515 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 22: -#line 274 "ps1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.line) = new vector; - if ( (yyvsp[-9].ival) ) - (yyval.line)->push_back("+"); - (yyval.line)->push_back(* (yyvsp[-8].sval)); - (yyval.line)->push_back(* (yyvsp[-7].sval)); - (yyval.line)->push_back(* (yyvsp[-5].sval)); - (yyval.line)->push_back(* (yyvsp[-3].sval)); - (yyval.line)->push_back(* (yyvsp[-1].sval)); - delete (yyvsp[-8].sval); - delete (yyvsp[-7].sval); - delete (yyvsp[-5].sval); - delete (yyvsp[-3].sval); - delete (yyvsp[-1].sval); - } -#line 1535 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 23: -#line 293 "ps1.0_grammar.y" /* yacc.c:1646 */ - { (yyval.ival)=0; } -#line 1541 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 24: -#line 296 "ps1.0_grammar.y" /* yacc.c:1646 */ - { (yyval.ival)=1; } -#line 1547 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 25: -#line 302 "ps1.0_grammar.y" /* yacc.c:1646 */ - {} -#line 1553 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - case 26: -#line 306 "ps1.0_grammar.y" /* yacc.c:1646 */ - {} -#line 1559 "_ps1.0_parser.c" /* yacc.c:1646 */ - break; - - -#line 1563 "_ps1.0_parser.c" /* yacc.c:1646 */ - default: break; - } - /* User semantic actions sometimes alter yychar, and that requires - that yytoken be updated with the new translation. We take the - approach of translating immediately before every use of yytoken. - One alternative is translating here after every semantic action, - but that translation would be missed if the semantic action invokes - YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or - if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an - incorrect destructor might then be invoked immediately. In the - case of YYERROR or YYBACKUP, subsequent parser actions might lead - to an incorrect destructor call or verbose syntax error message - before the lookahead is translated. */ - YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); - - YYPOPSTACK (yylen); - yylen = 0; - YY_STACK_PRINT (yyss, yyssp); - - *++yyvsp = yyval; - - /* Now 'shift' the result of the reduction. Determine what state - that goes to, based on the state we popped back to and the rule - number reduced by. */ - - yyn = yyr1[yyn]; - - yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; - if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) - yystate = yytable[yystate]; - else - yystate = yydefgoto[yyn - YYNTOKENS]; - - goto yynewstate; - - -/*--------------------------------------. -| yyerrlab -- here on detecting error. | -`--------------------------------------*/ -yyerrlab: - /* Make sure we have latest lookahead translation. See comments at - user semantic actions for why this is necessary. */ - yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); - - /* If not already recovering from an error, report this error. */ - if (!yyerrstatus) - { - ++yynerrs; -#if ! YYERROR_VERBOSE - yyerror (YY_("syntax error")); -#else -# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ - yyssp, yytoken) - { - char const *yymsgp = YY_("syntax error"); - int yysyntax_error_status; - yysyntax_error_status = YYSYNTAX_ERROR; - if (yysyntax_error_status == 0) - yymsgp = yymsg; - else if (yysyntax_error_status == 1) - { - if (yymsg != yymsgbuf) - YYSTACK_FREE (yymsg); - yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); - if (!yymsg) - { - yymsg = yymsgbuf; - yymsg_alloc = sizeof yymsgbuf; - yysyntax_error_status = 2; - } - else - { - yysyntax_error_status = YYSYNTAX_ERROR; - yymsgp = yymsg; - } - } - yyerror (yymsgp); - if (yysyntax_error_status == 2) - goto yyexhaustedlab; - } -# undef YYSYNTAX_ERROR -#endif - } - - - - if (yyerrstatus == 3) - { - /* If just tried and failed to reuse lookahead token after an - error, discard it. */ - - if (yychar <= YYEOF) - { - /* Return failure if at end of input. */ - if (yychar == YYEOF) - YYABORT; - } - else - { - yydestruct ("Error: discarding", - yytoken, &yylval); - yychar = YYEMPTY; - } - } - - /* Else will try to reuse lookahead token after shifting the error - token. */ - goto yyerrlab1; - - -/*---------------------------------------------------. -| yyerrorlab -- error raised explicitly by YYERROR. | -`---------------------------------------------------*/ -yyerrorlab: - - /* Pacify compilers like GCC when the user code never invokes - YYERROR and the label yyerrorlab therefore never appears in user - code. */ - if (/*CONSTCOND*/ 0) - goto yyerrorlab; - - /* Do not reclaim the symbols of the rule whose action triggered - this YYERROR. */ - YYPOPSTACK (yylen); - yylen = 0; - YY_STACK_PRINT (yyss, yyssp); - yystate = *yyssp; - goto yyerrlab1; - - -/*-------------------------------------------------------------. -| yyerrlab1 -- common code for both syntax error and YYERROR. | -`-------------------------------------------------------------*/ -yyerrlab1: - yyerrstatus = 3; /* Each real token shifted decrements this. */ - - for (;;) - { - yyn = yypact[yystate]; - if (!yypact_value_is_default (yyn)) - { - yyn += YYTERROR; - if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) - { - yyn = yytable[yyn]; - if (0 < yyn) - break; - } - } - - /* Pop the current state because it cannot handle the error token. */ - if (yyssp == yyss) - YYABORT; - - - yydestruct ("Error: popping", - yystos[yystate], yyvsp); - YYPOPSTACK (1); - yystate = *yyssp; - YY_STACK_PRINT (yyss, yyssp); - } - - YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN - *++yyvsp = yylval; - YY_IGNORE_MAYBE_UNINITIALIZED_END - - - /* Shift the error token. */ - YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); - - yystate = yyn; - goto yynewstate; - - -/*-------------------------------------. -| yyacceptlab -- YYACCEPT comes here. | -`-------------------------------------*/ -yyacceptlab: - yyresult = 0; - goto yyreturn; - -/*-----------------------------------. -| yyabortlab -- YYABORT comes here. | -`-----------------------------------*/ -yyabortlab: - yyresult = 1; - goto yyreturn; - -#if !defined yyoverflow || YYERROR_VERBOSE -/*-------------------------------------------------. -| yyexhaustedlab -- memory exhaustion comes here. | -`-------------------------------------------------*/ -yyexhaustedlab: - yyerror (YY_("memory exhausted")); - yyresult = 2; - /* Fall through. */ -#endif - -yyreturn: - if (yychar != YYEMPTY) - { - /* Make sure we have latest lookahead translation. See comments at - user semantic actions for why this is necessary. */ - yytoken = YYTRANSLATE (yychar); - yydestruct ("Cleanup: discarding lookahead", - yytoken, &yylval); - } - /* Do not reclaim the symbols of the rule whose action triggered - this YYABORT or YYACCEPT. */ - YYPOPSTACK (yylen); - YY_STACK_PRINT (yyss, yyssp); - while (yyssp != yyss) - { - yydestruct ("Cleanup: popping", - yystos[*yyssp], yyvsp); - YYPOPSTACK (1); - } -#ifndef yyoverflow - if (yyss != yyssa) - YYSTACK_FREE (yyss); -#endif -#if YYERROR_VERBOSE - if (yymsg != yymsgbuf) - YYSTACK_FREE (yymsg); -#endif - return yyresult; -} -#line 309 "ps1.0_grammar.y" /* yacc.c:1906 */ - - -void yyerror(const char* s) -{ - errors.set("parser: syntax error", line_number); -} diff --git a/RenderSystems/GL/src/nvparse/_ps1.0_parser.h b/RenderSystems/GL/src/nvparse/_ps1.0_parser.h deleted file mode 100644 index 6144a4a787b..00000000000 --- a/RenderSystems/GL/src/nvparse/_ps1.0_parser.h +++ /dev/null @@ -1,85 +0,0 @@ -/* A Bison parser, made by GNU Bison 3.0.2. */ - -/* Bison interface for Yacc-like parsers in C - - Copyright (C) 1984, 1989-1990, 2000-2013 Free Software Foundation, Inc. - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . */ - -/* As a special exception, you may create a larger work that contains - part or all of the Bison parser skeleton and distribute that work - under terms of your choice, so long as that work isn't itself a - parser generator using the skeleton or a modified version thereof - as a parser skeleton. Alternatively, if you modify or redistribute - the parser skeleton itself, you may (at your option) remove this - special exception, which will cause the skeleton and the resulting - Bison output files to be licensed under the GNU General Public - License without this special exception. - - This special exception was added by the Free Software Foundation in - version 2.2 of Bison. */ - -#ifndef YY_PS10_PS1_0_PARSER_H_INCLUDED -# define YY_PS10_PS1_0_PARSER_H_INCLUDED -/* Debug traces. */ -#ifndef YYDEBUG -# define YYDEBUG 0 -#endif -#if YYDEBUG -extern int ps10_debug; -#endif - -/* Token type. */ -#ifndef YYTOKENTYPE -# define YYTOKENTYPE - enum yytokentype - { - HEADER = 258, - NEWLINE = 259, - NUMBER = 260, - REG = 261, - DEF = 262, - ADDROP = 263, - BLENDOP = 264 - }; -#endif - -/* Value type. */ -#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED -typedef union YYSTYPE YYSTYPE; -union YYSTYPE -{ -#line 43 "ps1.0_grammar.y" /* yacc.c:1909 */ - - int ival; - float fval; - - string * sval; - constdef * cdef; - vector * consts; - vector * line; - list > * lines; - -#line 75 "_ps1.0_parser.h" /* yacc.c:1909 */ -}; -# define YYSTYPE_IS_TRIVIAL 1 -# define YYSTYPE_IS_DECLARED 1 -#endif - - -extern YYSTYPE ps10_lval; - -int ps10_parse (void); - -#endif /* !YY_PS10_PS1_0_PARSER_H_INCLUDED */ diff --git a/RenderSystems/GL/src/nvparse/_rc1.0_lexer.cpp b/RenderSystems/GL/src/nvparse/_rc1.0_lexer.cpp deleted file mode 100644 index 461a23c1deb..00000000000 --- a/RenderSystems/GL/src/nvparse/_rc1.0_lexer.cpp +++ /dev/null @@ -1,2494 +0,0 @@ -#define yy_create_buffer rc10__create_buffer -#define yy_delete_buffer rc10__delete_buffer -#define yy_scan_buffer rc10__scan_buffer -#define yy_scan_string rc10__scan_string -#define yy_scan_bytes rc10__scan_bytes -#define yy_flex_debug rc10__flex_debug -#define yy_init_buffer rc10__init_buffer -#define yy_flush_buffer rc10__flush_buffer -#define yy_load_buffer_state rc10__load_buffer_state -#define yy_switch_to_buffer rc10__switch_to_buffer -#define yyin rc10_in -#define yyleng rc10_leng -#define yylex rc10_lex -#define yyout rc10_out -#define yyrestart rc10_restart -#define yytext rc10_text -#define yywrap rc10_wrap - -#line 20 "_rc1.0_lexer.cpp" -/* A lexical scanner generated by flex */ - -/* Scanner skeleton version: - * $Header: /home/daffy/u0/vern/flex/RCS/flex.skl,v 2.91 96/09/10 16:58:48 vern Exp $ - */ - -#define FLEX_SCANNER -#define YY_FLEX_MAJOR_VERSION 2 -#define YY_FLEX_MINOR_VERSION 5 - -#include -#include - -/* cfront 1.2 defines "c_plusplus" instead of "__cplusplus" */ -#ifdef c_plusplus -#ifndef __cplusplus -#define __cplusplus -#endif -#endif - - -#ifdef __cplusplus - -#include -#ifndef _WIN32 -#include -#endif - -/* Use prototypes in function declarations. */ -#define YY_USE_PROTOS - -/* The "const" storage-class-modifier is valid. */ -#define YY_USE_CONST - -#else /* ! __cplusplus */ - -#if __STDC__ - -#define YY_USE_PROTOS -#define YY_USE_CONST - -#endif /* __STDC__ */ -#endif /* ! __cplusplus */ - -#ifdef __TURBOC__ - #pragma warn -rch - #pragma warn -use -#include -#include -#define YY_USE_CONST -#define YY_USE_PROTOS -#endif - -#ifdef YY_USE_CONST -#define yyconst const -#else -#define yyconst -#endif - - -#ifdef YY_USE_PROTOS -#define YY_PROTO(proto) proto -#else -#define YY_PROTO(proto) () -#endif - - -/* Returned upon end-of-file. */ -#define YY_NULL 0 - -/* Promotes a possibly negative, possibly signed char to an unsigned - * integer for use as an array index. If the signed char is negative, - * we want to instead treat it as an 8-bit unsigned char, hence the - * double cast. - */ -#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) - -/* Enter a start condition. This macro really ought to take a parameter, - * but we do it the disgusting crufty way forced on us by the ()-less - * definition of BEGIN. - */ -#define BEGIN yy_start = 1 + 2 * - -/* Translate the current start state into a value that can be later handed - * to BEGIN to return to the state. The YYSTATE alias is for lex - * compatibility. - */ -#define YY_START ((yy_start - 1) / 2) -#define YYSTATE YY_START - -/* Action number for EOF rule of a given start state. */ -#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) - -/* Special action meaning "start processing a new file". */ -#define YY_NEW_FILE yyrestart( yyin ) - -#define YY_END_OF_BUFFER_CHAR 0 - -/* Size of default input buffer. */ -#define YY_BUF_SIZE 16384 - -typedef struct yy_buffer_state *YY_BUFFER_STATE; - -extern int yyleng; -extern FILE *yyin, *yyout; - -#define EOB_ACT_CONTINUE_SCAN 0 -#define EOB_ACT_END_OF_FILE 1 -#define EOB_ACT_LAST_MATCH 2 - -/* The funky do-while in the following #define is used to turn the definition - * int a single C statement (which needs a semi-colon terminator). This - * avoids problems with code like: - * - * if ( condition_holds ) - * yyless( 5 ); - * else - * do_something_else(); - * - * Prior to using the do-while the compiler would get upset at the - * "else" because it interpreted the "if" statement as being all - * done when it reached the ';' after the yyless() call. - */ - -/* Return all but the first 'n' matched characters back to the input stream. */ - -#define yyless(n) \ - do \ - { \ - /* Undo effects of setting up yytext. */ \ - *yy_cp = yy_hold_char; \ - YY_RESTORE_YY_MORE_OFFSET \ - yy_c_buf_p = yy_cp = yy_bp + n - YY_MORE_ADJ; \ - YY_DO_BEFORE_ACTION; /* set up yytext again */ \ - } \ - while ( 0 ) - -#define unput(c) yyunput( c, yytext_ptr ) - -/* The following is because we cannot portably get our hands on size_t - * (without autoconf's help, which isn't available because we want - * flex-generated scanners to compile on their own). - */ -typedef unsigned int yy_size_t; - - -struct yy_buffer_state - { - FILE *yy_input_file; - - char *yy_ch_buf; /* input buffer */ - char *yy_buf_pos; /* current position in input buffer */ - - /* Size of input buffer in bytes, not including room for EOB - * characters. - */ - yy_size_t yy_buf_size; - - /* Number of characters read into yy_ch_buf, not including EOB - * characters. - */ - int yy_n_chars; - - /* Whether we "own" the buffer - i.e., we know we created it, - * and can realloc() it to grow it, and should free() it to - * delete it. - */ - int yy_is_our_buffer; - - /* Whether this is an "interactive" input source; if so, and - * if we're using stdio for input, then we want to use getc() - * instead of fread(), to make sure we stop fetching input after - * each newline. - */ - int yy_is_interactive; - - /* Whether we're considered to be at the beginning of a line. - * If so, '^' rules will be active on the next match, otherwise - * not. - */ - int yy_at_bol; - - /* Whether to try to fill the input buffer when we reach the - * end of it. - */ - int yy_fill_buffer; - - int yy_buffer_status; -#define YY_BUFFER_NEW 0 -#define YY_BUFFER_NORMAL 1 - /* When an EOF's been seen but there's still some text to process - * then we mark the buffer as YY_EOF_PENDING, to indicate that we - * shouldn't try reading from the input source any more. We might - * still have a bunch of tokens to match, though, because of - * possible backing-up. - * - * When we actually see the EOF, we change the status to "new" - * (via yyrestart()), so that the user can continue scanning by - * just pointing yyin at a new input file. - */ -#define YY_BUFFER_EOF_PENDING 2 - }; - -static YY_BUFFER_STATE yy_current_buffer = 0; - -/* We provide macros for accessing buffer states in case in the - * future we want to put the buffer states in a more general - * "scanner state". - */ -#define YY_CURRENT_BUFFER yy_current_buffer - - -/* yy_hold_char holds the character lost when yytext is formed. */ -static char yy_hold_char; - -static int yy_n_chars; /* number of characters read into yy_ch_buf */ - - -int yyleng; - -/* Points to current character in buffer. */ -static char *yy_c_buf_p = (char *) 0; -static int yy_init = 1; /* whether we need to initialize */ -static int yy_start = 0; /* start state number */ - -/* Flag which is used to allow yywrap()'s to do buffer switches - * instead of setting up a fresh yyin. A bit of a hack ... - */ -static int yy_did_buffer_switch_on_eof; - -void yyrestart YY_PROTO(( FILE *input_file )); - -void yy_switch_to_buffer YY_PROTO(( YY_BUFFER_STATE new_buffer )); -void yy_load_buffer_state YY_PROTO(( void )); -YY_BUFFER_STATE yy_create_buffer YY_PROTO(( FILE *file, int size )); -void yy_delete_buffer YY_PROTO(( YY_BUFFER_STATE b )); -void yy_init_buffer YY_PROTO(( YY_BUFFER_STATE b, FILE *file )); -void yy_flush_buffer YY_PROTO(( YY_BUFFER_STATE b )); -#define YY_FLUSH_BUFFER yy_flush_buffer( yy_current_buffer ) - -YY_BUFFER_STATE yy_scan_buffer YY_PROTO(( char *base, yy_size_t size )); -YY_BUFFER_STATE yy_scan_string YY_PROTO(( yyconst char *yy_str )); -YY_BUFFER_STATE yy_scan_bytes YY_PROTO(( yyconst char *bytes, int len )); - -static void *yy_flex_alloc YY_PROTO(( yy_size_t )); -static void *yy_flex_realloc YY_PROTO(( void *, yy_size_t )); -static void yy_flex_free YY_PROTO(( void * )); - -#define yy_new_buffer yy_create_buffer - -#define yy_set_interactive(is_interactive) \ - { \ - if ( ! yy_current_buffer ) \ - yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \ - yy_current_buffer->yy_is_interactive = is_interactive; \ - } - -#define yy_set_bol(at_bol) \ - { \ - if ( ! yy_current_buffer ) \ - yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \ - yy_current_buffer->yy_at_bol = at_bol; \ - } - -#define YY_AT_BOL() (yy_current_buffer->yy_at_bol) - -typedef unsigned char YY_CHAR; -FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0; -typedef int yy_state_type; -extern char *yytext; -#define yytext_ptr yytext - -static yy_state_type yy_get_previous_state YY_PROTO(( void )); -static yy_state_type yy_try_NUL_trans YY_PROTO(( yy_state_type current_state )); -static int yy_get_next_buffer YY_PROTO(( void )); -static void yy_fatal_error YY_PROTO(( yyconst char msg[] )); - -/* Done after the current pattern has been matched and before the - * corresponding action - sets up yytext. - */ -#define YY_DO_BEFORE_ACTION \ - yytext_ptr = yy_bp; \ - yyleng = (int) (yy_cp - yy_bp); \ - yy_hold_char = *yy_cp; \ - *yy_cp = '\0'; \ - yy_c_buf_p = yy_cp; - -#define YY_NUM_RULES 94 -#define YY_END_OF_BUFFER 95 -static yyconst short int yy_accept[309] = - { 0, - 0, 0, 95, 94, 92, 91, 94, 94, 3, 82, - 83, 87, 89, 85, 88, 86, 94, 79, 84, 90, - 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, - 93, 93, 93, 93, 93, 93, 80, 81, 92, 91, - 0, 0, 0, 79, 78, 1, 2, 77, 79, 93, - 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, - 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, - 0, 77, 93, 93, 93, 93, 93, 93, 93, 93, - 8, 93, 93, 66, 56, 93, 68, 93, 93, 67, - 93, 93, 93, 0, 93, 93, 93, 12, 16, 93, - - 93, 93, 93, 93, 0, 93, 71, 0, 0, 93, - 93, 28, 32, 36, 40, 93, 52, 0, 69, 93, - 93, 0, 0, 93, 93, 93, 93, 93, 6, 7, - 0, 93, 54, 55, 0, 59, 0, 93, 93, 0, - 0, 0, 0, 93, 0, 0, 93, 93, 10, 11, - 0, 14, 15, 0, 93, 44, 48, 93, 62, 93, - 0, 93, 0, 0, 93, 20, 24, 26, 27, 0, - 30, 31, 0, 34, 35, 0, 38, 39, 0, 93, - 50, 51, 0, 4, 93, 93, 0, 0, 93, 0, - 0, 57, 93, 5, 93, 53, 58, 93, 0, 0, - - 0, 0, 0, 0, 93, 0, 93, 93, 9, 13, - 93, 42, 43, 0, 46, 47, 0, 93, 93, 93, - 18, 19, 0, 22, 23, 0, 25, 29, 33, 37, - 64, 49, 93, 93, 61, 0, 0, 93, 63, 93, - 0, 0, 93, 93, 93, 41, 45, 93, 93, 93, - 93, 17, 21, 93, 93, 93, 93, 93, 93, 93, - 93, 93, 93, 93, 93, 93, 75, 93, 93, 93, - 60, 76, 93, 93, 93, 93, 93, 93, 93, 70, - 93, 65, 93, 93, 93, 74, 93, 93, 93, 93, - 93, 93, 93, 73, 93, 93, 93, 93, 93, 93, - - 93, 93, 93, 93, 93, 93, 72, 0 - } ; - -static yyconst int yy_ec[256] = - { 0, - 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, - 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 2, 5, 1, 6, 1, 1, 1, 1, 7, - 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, - 18, 19, 19, 19, 19, 19, 19, 1, 20, 1, - 21, 1, 1, 1, 22, 22, 23, 22, 22, 22, - 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, - 22, 24, 22, 22, 22, 22, 22, 22, 22, 22, - 1, 1, 1, 1, 25, 1, 26, 27, 28, 29, - - 30, 31, 32, 33, 34, 22, 22, 35, 36, 37, - 38, 39, 22, 40, 41, 42, 43, 44, 45, 46, - 47, 48, 49, 1, 50, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1 - } ; - -static yyconst int yy_meta[51] = - { 0, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 2, 1, 2, 2, 2, 2, 2, 1, - 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 1, 1 - } ; - -static yyconst short int yy_base[310] = - { 0, - 0, 0, 543, 544, 540, 544, 48, 536, 544, 544, - 544, 544, 40, 544, 47, 52, 63, 63, 544, 544, - 527, 48, 41, 60, 71, 61, 72, 73, 74, 75, - 76, 77, 83, 78, 79, 84, 544, 544, 537, 544, - 90, 514, 112, 119, 124, 544, 544, 129, 136, 524, - 111, 89, 99, 143, 120, 144, 145, 88, 146, 147, - 149, 87, 150, 152, 151, 158, 153, 154, 155, 157, - 513, 157, 90, 172, 173, 178, 177, 175, 185, 186, - 522, 188, 189, 521, 520, 519, 518, 191, 192, 517, - 207, 193, 195, 513, 204, 216, 197, 515, 514, 194, - - 201, 218, 202, 222, 211, 227, 513, 219, 216, 234, - 235, 512, 511, 510, 509, 236, 508, 507, 506, 240, - 237, 234, 243, 241, 260, 242, 250, 259, 544, 544, - 486, 258, 544, 544, 485, 544, 484, 264, 265, 260, - 264, 266, 268, 275, 270, 500, 285, 286, 544, 544, - 482, 544, 544, 481, 288, 499, 498, 289, 497, 292, - 482, 290, 481, 480, 294, 493, 492, 544, 544, 472, - 544, 544, 471, 544, 544, 470, 544, 544, 469, 296, - 544, 544, 468, 544, 298, 300, 472, 471, 302, 290, - 293, 484, 309, 544, 314, 544, 544, 312, 308, 310, - - 469, 465, 464, 463, 315, 461, 326, 329, 544, 544, - 330, 544, 544, 455, 544, 544, 454, 333, 328, 340, - 544, 544, 453, 544, 544, 452, 544, 544, 544, 544, - 342, 544, 338, 334, 470, 455, 454, 341, 467, 343, - 452, 451, 339, 344, 347, 544, 544, 345, 348, 362, - 349, 544, 544, 364, 365, 367, 369, 366, 370, 376, - 371, 377, 380, 382, 383, 385, 464, 390, 391, 389, - 463, 460, 393, 394, 392, 395, 403, 398, 400, 457, - 404, 245, 420, 415, 399, 208, 405, 414, 422, 425, - 428, 430, 435, 436, 409, 439, 438, 440, 442, 443, - - 444, 446, 449, 447, 450, 456, 156, 544, 119 - } ; - -static yyconst short int yy_def[310] = - { 0, - 308, 1, 308, 308, 308, 308, 308, 308, 308, 308, - 308, 308, 308, 308, 308, 308, 308, 309, 308, 308, - 309, 309, 309, 309, 309, 309, 309, 309, 309, 309, - 309, 309, 309, 309, 309, 309, 308, 308, 308, 308, - 308, 308, 308, 308, 308, 308, 308, 308, 309, 309, - 309, 309, 309, 309, 309, 309, 309, 309, 309, 309, - 309, 309, 309, 309, 309, 309, 309, 309, 309, 309, - 308, 308, 309, 309, 309, 309, 309, 309, 309, 309, - 309, 309, 309, 309, 309, 309, 309, 309, 309, 309, - 309, 309, 309, 308, 309, 309, 309, 309, 309, 309, - - 309, 309, 309, 309, 308, 309, 309, 308, 308, 309, - 309, 309, 309, 309, 309, 309, 309, 308, 309, 309, - 309, 308, 308, 309, 309, 309, 309, 309, 308, 308, - 308, 309, 308, 308, 308, 308, 308, 309, 309, 308, - 308, 308, 308, 309, 308, 308, 309, 309, 308, 308, - 308, 308, 308, 308, 309, 309, 309, 309, 309, 309, - 308, 309, 308, 308, 309, 309, 309, 308, 308, 308, - 308, 308, 308, 308, 308, 308, 308, 308, 308, 309, - 308, 308, 308, 308, 309, 309, 308, 308, 309, 308, - 308, 309, 309, 308, 309, 308, 308, 309, 308, 308, - - 308, 308, 308, 308, 309, 308, 309, 309, 308, 308, - 309, 308, 308, 308, 308, 308, 308, 309, 309, 309, - 308, 308, 308, 308, 308, 308, 308, 308, 308, 308, - 309, 308, 309, 309, 309, 308, 308, 309, 309, 309, - 308, 308, 309, 309, 309, 308, 308, 309, 309, 309, - 309, 308, 308, 309, 309, 309, 309, 309, 309, 309, - 309, 309, 309, 309, 309, 309, 309, 309, 309, 309, - 309, 309, 309, 309, 309, 309, 309, 309, 309, 309, - 309, 309, 309, 309, 309, 309, 309, 309, 309, 309, - 309, 309, 309, 309, 309, 309, 309, 309, 309, 309, - - 309, 309, 309, 309, 309, 309, 309, 0, 308 - } ; - -static yyconst short int yy_nxt[595] = - { 0, - 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 18, 18, 18, 18, 19, - 20, 21, 21, 21, 21, 22, 23, 24, 25, 26, - 27, 21, 28, 21, 29, 30, 21, 31, 21, 32, - 33, 34, 35, 21, 21, 21, 21, 36, 37, 38, - 40, 41, 43, 308, 44, 44, 44, 44, 44, 43, - 308, 44, 44, 44, 44, 44, 45, 45, 45, 45, - 45, 46, 308, 308, 52, 48, 47, 49, 49, 49, - 49, 49, 51, 308, 308, 308, 308, 308, 308, 308, - 308, 308, 40, 41, 53, 308, 308, 54, 59, 308, - - 308, 308, 308, 60, 55, 57, 56, 68, 64, 58, - 65, 308, 62, 70, 74, 69, 85, 61, 63, 81, - 50, 66, 95, 308, 75, 67, 45, 45, 45, 45, - 45, 48, 308, 44, 44, 44, 44, 44, 45, 45, - 45, 45, 45, 72, 72, 72, 72, 72, 48, 73, - 49, 49, 49, 49, 49, 308, 308, 308, 308, 308, - 78, 308, 308, 308, 308, 308, 308, 308, 308, 308, - 308, 72, 72, 72, 72, 72, 88, 76, 87, 77, - 82, 80, 79, 89, 308, 308, 83, 308, 90, 308, - 308, 86, 98, 99, 84, 92, 93, 308, 308, 91, - - 308, 308, 102, 308, 308, 308, 308, 308, 97, 308, - 103, 104, 96, 308, 308, 100, 308, 101, 106, 308, - 308, 112, 113, 114, 115, 110, 116, 107, 308, 119, - 308, 111, 117, 124, 308, 121, 129, 130, 127, 308, - 120, 136, 125, 126, 133, 134, 308, 308, 308, 308, - 131, 132, 308, 308, 308, 137, 128, 308, 135, 149, - 150, 148, 308, 138, 139, 155, 147, 144, 152, 153, - 308, 308, 308, 151, 156, 157, 308, 308, 159, 166, - 167, 158, 154, 160, 162, 168, 169, 308, 165, 171, - 172, 174, 175, 177, 178, 181, 182, 308, 308, 170, - - 308, 308, 308, 173, 308, 176, 308, 179, 308, 183, - 308, 180, 308, 186, 308, 212, 213, 192, 215, 216, - 198, 308, 207, 195, 308, 205, 308, 308, 189, 214, - 193, 185, 217, 221, 222, 224, 225, 208, 308, 219, - 308, 308, 308, 231, 211, 308, 308, 223, 218, 226, - 308, 308, 308, 308, 308, 308, 308, 308, 220, 308, - 308, 308, 233, 234, 240, 235, 243, 244, 239, 248, - 238, 245, 254, 249, 308, 255, 308, 308, 308, 308, - 250, 308, 308, 308, 251, 258, 256, 257, 308, 308, - 262, 263, 308, 260, 308, 308, 264, 308, 259, 266, - - 261, 308, 308, 308, 308, 308, 308, 308, 265, 273, - 308, 308, 308, 267, 268, 308, 308, 308, 269, 274, - 270, 308, 272, 271, 275, 277, 308, 308, 281, 283, - 280, 276, 308, 278, 308, 279, 287, 308, 284, 282, - 308, 288, 308, 289, 285, 286, 290, 308, 308, 296, - 308, 308, 308, 292, 308, 308, 308, 291, 308, 308, - 295, 308, 308, 298, 293, 294, 297, 301, 308, 308, - 302, 300, 308, 304, 299, 308, 308, 253, 252, 308, - 247, 246, 308, 242, 241, 237, 236, 232, 305, 230, - 229, 228, 303, 307, 306, 227, 308, 210, 209, 206, - - 204, 203, 202, 201, 200, 199, 197, 196, 194, 308, - 191, 190, 188, 187, 184, 164, 163, 161, 308, 146, - 145, 143, 142, 141, 140, 308, 123, 122, 118, 308, - 308, 109, 108, 308, 105, 94, 308, 71, 39, 308, - 42, 39, 308, 3, 308, 308, 308, 308, 308, 308, - 308, 308, 308, 308, 308, 308, 308, 308, 308, 308, - 308, 308, 308, 308, 308, 308, 308, 308, 308, 308, - 308, 308, 308, 308, 308, 308, 308, 308, 308, 308, - 308, 308, 308, 308, 308, 308, 308, 308, 308, 308, - 308, 308, 308, 308 - - } ; - -static yyconst short int yy_chk[595] = - { 0, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 7, 7, 13, 23, 13, 13, 13, 13, 13, 15, - 22, 15, 15, 15, 15, 15, 16, 16, 16, 16, - 16, 17, 24, 26, 23, 18, 17, 18, 18, 18, - 18, 18, 22, 25, 27, 28, 29, 30, 31, 32, - 34, 35, 41, 41, 24, 33, 36, 24, 28, 62, - - 58, 52, 73, 29, 25, 27, 26, 34, 32, 27, - 33, 53, 31, 36, 52, 35, 62, 30, 31, 58, - 309, 33, 73, 51, 53, 33, 43, 43, 43, 43, - 43, 44, 55, 44, 44, 44, 44, 44, 45, 45, - 45, 45, 45, 48, 48, 48, 48, 48, 49, 51, - 49, 49, 49, 49, 49, 54, 56, 57, 59, 60, - 55, 61, 63, 65, 64, 67, 68, 69, 307, 70, - 66, 72, 72, 72, 72, 72, 65, 54, 64, 54, - 59, 57, 56, 66, 74, 75, 60, 78, 67, 77, - 76, 63, 76, 76, 61, 69, 70, 79, 80, 68, - - 82, 83, 78, 88, 89, 92, 100, 93, 75, 97, - 79, 80, 74, 101, 103, 76, 95, 77, 82, 91, - 286, 91, 91, 91, 91, 88, 92, 83, 96, 95, - 102, 89, 93, 100, 104, 97, 105, 105, 103, 106, - 96, 109, 101, 102, 108, 108, 110, 111, 116, 121, - 105, 106, 120, 124, 126, 109, 104, 282, 108, 122, - 122, 121, 127, 110, 111, 124, 120, 116, 123, 123, - 132, 128, 125, 122, 125, 125, 138, 139, 127, 139, - 139, 126, 123, 128, 132, 140, 140, 144, 138, 141, - 141, 142, 142, 143, 143, 145, 145, 147, 148, 140, - - 155, 158, 162, 141, 160, 142, 165, 143, 180, 145, - 185, 144, 186, 148, 189, 190, 190, 158, 191, 191, - 165, 193, 185, 162, 198, 180, 195, 205, 155, 190, - 160, 147, 191, 199, 199, 200, 200, 186, 207, 195, - 219, 208, 211, 205, 189, 218, 234, 199, 193, 200, - 233, 243, 220, 238, 231, 240, 244, 248, 198, 245, - 249, 251, 207, 208, 220, 211, 231, 233, 219, 238, - 218, 234, 243, 240, 250, 244, 254, 255, 258, 256, - 240, 257, 259, 261, 240, 249, 245, 248, 260, 262, - 255, 256, 263, 251, 264, 265, 257, 266, 250, 259, - - 254, 270, 268, 269, 275, 273, 274, 276, 258, 266, - 278, 285, 279, 260, 261, 277, 281, 287, 262, 268, - 263, 295, 265, 264, 269, 273, 288, 284, 277, 279, - 276, 270, 283, 274, 289, 275, 285, 290, 281, 278, - 291, 287, 292, 288, 283, 284, 289, 293, 294, 295, - 297, 296, 298, 291, 299, 300, 301, 290, 302, 304, - 294, 303, 305, 297, 292, 293, 296, 300, 306, 280, - 301, 299, 272, 303, 298, 271, 267, 242, 241, 239, - 237, 236, 235, 226, 223, 217, 214, 206, 304, 204, - 203, 202, 302, 306, 305, 201, 192, 188, 187, 183, - - 179, 176, 173, 170, 167, 166, 164, 163, 161, 159, - 157, 156, 154, 151, 146, 137, 135, 131, 119, 118, - 117, 115, 114, 113, 112, 107, 99, 98, 94, 90, - 87, 86, 85, 84, 81, 71, 50, 42, 39, 21, - 8, 5, 3, 308, 308, 308, 308, 308, 308, 308, - 308, 308, 308, 308, 308, 308, 308, 308, 308, 308, - 308, 308, 308, 308, 308, 308, 308, 308, 308, 308, - 308, 308, 308, 308, 308, 308, 308, 308, 308, 308, - 308, 308, 308, 308, 308, 308, 308, 308, 308, 308, - 308, 308, 308, 308 - - } ; - -static yy_state_type yy_last_accepting_state; -static char *yy_last_accepting_cpos; - -/* The intent behind this definition is that it'll catch - * any uses of REJECT which flex missed. - */ -#define REJECT reject_used_but_not_detected -#define yymore() yymore_used_but_not_detected -#define YY_MORE_ADJ 0 -#define YY_RESTORE_YY_MORE_OFFSET -char *yytext; -#line 1 "rc1.0_tokens.l" -#define INITIAL 0 -/* definitions */ -#line 8 "rc1.0_tokens.l" - -#include -#include "rc1.0_combiners.h" -#include "_rc1.0_parser.h" - -#include "nvparse_errors.h" -#include "nvparse_externs.h" -#define YY_NO_UNPUT - -#define YY_INPUT(buf,result,max_size) \ -{ \ - result = 0; \ - while (*myin && result < max_size) \ - buf[result++] = *myin++; \ -} - -#define YY_ALWAYS_INTERACTIVE 1 - -/* end of definitions */ -#line 639 "_rc1.0_lexer.cpp" - -/* Macros after this point can all be overridden by user definitions in - * section 1. - */ - -#ifndef YY_SKIP_YYWRAP -#ifdef __cplusplus -extern "C" int yywrap YY_PROTO(( void )); -#else -extern int yywrap YY_PROTO(( void )); -#endif -#endif - -#ifndef YY_NO_UNPUT -static void yyunput YY_PROTO(( int c, char *buf_ptr )); -#endif - -#ifndef yytext_ptr -static void yy_flex_strncpy YY_PROTO(( char *, yyconst char *, int )); -#endif - -#ifdef YY_NEED_STRLEN -static int yy_flex_strlen YY_PROTO(( yyconst char * )); -#endif - -#ifndef YY_NO_INPUT -#ifdef __cplusplus -static int yyinput YY_PROTO(( void )); -#else -static int input YY_PROTO(( void )); -#endif -#endif - -#if YY_STACK_USED -static int yy_start_stack_ptr = 0; -static int yy_start_stack_depth = 0; -static int *yy_start_stack = 0; -#ifndef YY_NO_PUSH_STATE -static void yy_push_state YY_PROTO(( int new_state )); -#endif -#ifndef YY_NO_POP_STATE -static void yy_pop_state YY_PROTO(( void )); -#endif -#ifndef YY_NO_TOP_STATE -static int yy_top_state YY_PROTO(( void )); -#endif - -#else -#define YY_NO_PUSH_STATE 1 -#define YY_NO_POP_STATE 1 -#define YY_NO_TOP_STATE 1 -#endif - -#ifdef YY_MALLOC_DECL -YY_MALLOC_DECL -#else -#if __STDC__ -#ifndef __cplusplus -#include -#endif -#else -/* Just try to get by without declaring the routines. This will fail - * miserably on non-ANSI systems for which sizeof(size_t) != sizeof(int) - * or sizeof(void*) != sizeof(int). - */ -#endif -#endif - -/* Amount of stuff to slurp up with each read. */ -#ifndef YY_READ_BUF_SIZE -#define YY_READ_BUF_SIZE 8192 -#endif - -/* Copy whatever the last rule matched to the standard output. */ - -#ifndef ECHO -/* This used to be an fputs(), but since the string might contain NUL's, - * we now use fwrite(). - */ -#define ECHO (void) fwrite( yytext, yyleng, 1, yyout ) -#endif - -/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, - * is returned in "result". - */ -#ifndef YY_INPUT -#define YY_INPUT(buf,result,max_size) \ - if ( yy_current_buffer->yy_is_interactive ) \ - { \ - int c = '*', n; \ - for ( n = 0; n < max_size && \ - (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ - buf[n] = (char) c; \ - if ( c == '\n' ) \ - buf[n++] = (char) c; \ - if ( c == EOF && ferror( yyin ) ) \ - YY_FATAL_ERROR( "input in flex scanner failed" ); \ - result = n; \ - } \ - else \ - { \ - errno=0; \ - while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ - { \ - if( errno != EINTR) \ - { \ - YY_FATAL_ERROR( "input in flex scanner failed" ); \ - break; \ - } \ - errno=0; \ - clearerr(yyin); \ - } \ - } -#endif - -/* No semi-colon after return; correct usage is to write "yyterminate();" - - * we don't want an extra ';' after the "return" because that will cause - * some compilers to complain about unreachable statements. - */ -#ifndef yyterminate -#define yyterminate() return YY_NULL -#endif - -/* Number of entries by which start-condition stack grows. */ -#ifndef YY_START_STACK_INCR -#define YY_START_STACK_INCR 25 -#endif - -/* Report a fatal error. */ -#ifndef YY_FATAL_ERROR -#define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) -#endif - -/* Default declaration of generated scanner - a define so the user can - * easily add parameters. - */ -#ifndef YY_DECL -#define YY_DECL int yylex YY_PROTO(( void )) -#endif - -/* Code executed at the beginning of each rule, after yytext and yyleng - * have been set up. - */ -#ifndef YY_USER_ACTION -#define YY_USER_ACTION -#endif - -/* Code executed at the end of each rule. */ -#ifndef YY_BREAK -#define YY_BREAK break; -#endif - -#define YY_RULE_SETUP \ - YY_USER_ACTION - -YY_DECL - { - yy_state_type yy_current_state; - char *yy_cp, *yy_bp; - int yy_act; - -#line 28 "rc1.0_tokens.l" - - -#line 804 "_rc1.0_lexer.cpp" - - if ( yy_init ) - { - yy_init = 0; - -#ifdef YY_USER_INIT - YY_USER_INIT; -#endif - - if ( ! yy_start ) - yy_start = 1; /* first start state */ - - if ( ! yyin ) - yyin = stdin; - - if ( ! yyout ) - yyout = stdout; - - if ( ! yy_current_buffer ) - yy_current_buffer = - yy_create_buffer( yyin, YY_BUF_SIZE ); - - yy_load_buffer_state(); - } - - while ( 1 ) /* loops until end-of-file is reached */ - { - yy_cp = yy_c_buf_p; - - /* Support of yytext. */ - *yy_cp = yy_hold_char; - - /* yy_bp points to the position in yy_ch_buf of the start of - * the current run. - */ - yy_bp = yy_cp; - - yy_current_state = yy_start; -yy_match: - do - { - YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; - if ( yy_accept[yy_current_state] ) - { - yy_last_accepting_state = yy_current_state; - yy_last_accepting_cpos = yy_cp; - } - while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) - { - yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 309 ) - yy_c = yy_meta[(unsigned int) yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; - ++yy_cp; - } - while ( yy_base[yy_current_state] != 544 ); - -yy_find_action: - yy_act = yy_accept[yy_current_state]; - if ( yy_act == 0 ) - { /* have to back up */ - yy_cp = yy_last_accepting_cpos; - yy_current_state = yy_last_accepting_state; - yy_act = yy_accept[yy_current_state]; - } - - YY_DO_BEFORE_ACTION; - - -do_action: /* This label is used only to access EOF actions. */ - - - switch ( yy_act ) - { /* beginning of action switch */ - case 0: /* must back up */ - /* undo the effects of YY_DO_BEFORE_ACTION */ - *yy_cp = yy_hold_char; - yy_cp = yy_last_accepting_cpos; - yy_current_state = yy_last_accepting_state; - goto yy_find_action; - -case 1: -YY_RULE_SETUP -#line 30 "rc1.0_tokens.l" -{ - A: - switch (yyinput()) { - case '*': goto B; - case 0: errors.set("end-of-file in comment", line_number); break; - case '\n': line_number++; - default: goto A; - } - B: - switch (yyinput()) { - case '*': goto B; - case '/': break; - case 0: errors.set("end-of-file in comment", line_number); break; - case '\n': line_number++; - default: goto A; - } - } - YY_BREAK -case 2: -YY_RULE_SETUP -#line 48 "rc1.0_tokens.l" -{ - char ch; - while ((ch = yyinput()) != '\n'); - if (ch == '\n') line_number++; - } - YY_BREAK -case 3: -YY_RULE_SETUP -#line 54 "rc1.0_tokens.l" -{ - char ch; - while ((ch = yyinput()) != '\n'); - if (ch == '\n') line_number++; - } - YY_BREAK -case 4: -YY_RULE_SETUP -#line 60 "rc1.0_tokens.l" -{ /* eat header */ } - YY_BREAK -case 5: -YY_RULE_SETUP -#line 62 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_FOG_RGB; - return(regVariable); - } - YY_BREAK -case 6: -YY_RULE_SETUP -#line 66 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_FOG_ALPHA; - return(regVariable); - } - YY_BREAK -case 7: -YY_RULE_SETUP -#line 70 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_FOG_BLUE; - return(regVariable); - } - YY_BREAK -case 8: -YY_RULE_SETUP -#line 74 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_FOG; - return(regVariable); - } - YY_BREAK -case 9: -YY_RULE_SETUP -#line 79 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_PRIMARY_COLOR_RGB; - return(regVariable); - } - YY_BREAK -case 10: -YY_RULE_SETUP -#line 83 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_PRIMARY_COLOR_ALPHA; - return(regVariable); - } - YY_BREAK -case 11: -YY_RULE_SETUP -#line 87 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_PRIMARY_COLOR_BLUE; - return(regVariable); - } - YY_BREAK -case 12: -YY_RULE_SETUP -#line 91 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_PRIMARY_COLOR; - return(regVariable); - } - YY_BREAK -case 13: -YY_RULE_SETUP -#line 96 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_SECONDARY_COLOR_RGB; - return(regVariable); - } - YY_BREAK -case 14: -YY_RULE_SETUP -#line 100 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_SECONDARY_COLOR_ALPHA; - return(regVariable); - } - YY_BREAK -case 15: -YY_RULE_SETUP -#line 104 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_SECONDARY_COLOR_BLUE; - return(regVariable); - } - YY_BREAK -case 16: -YY_RULE_SETUP -#line 108 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_SECONDARY_COLOR; - return(regVariable); - } - YY_BREAK -case 17: -YY_RULE_SETUP -#line 113 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_SPARE0_RGB; - return(regVariable); - } - YY_BREAK -case 18: -YY_RULE_SETUP -#line 117 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_SPARE0_ALPHA; - return(regVariable); - } - YY_BREAK -case 19: -YY_RULE_SETUP -#line 121 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_SPARE0_BLUE; - return(regVariable); - } - YY_BREAK -case 20: -YY_RULE_SETUP -#line 125 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_SPARE0; - return(regVariable); - } - YY_BREAK -case 21: -YY_RULE_SETUP -#line 130 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_SPARE1_RGB; - return(regVariable); - } - YY_BREAK -case 22: -YY_RULE_SETUP -#line 134 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_SPARE1_ALPHA; - return(regVariable); - } - YY_BREAK -case 23: -YY_RULE_SETUP -#line 138 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_SPARE1_BLUE; - return(regVariable); - } - YY_BREAK -case 24: -YY_RULE_SETUP -#line 142 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_SPARE1; - return(regVariable); - } - YY_BREAK -case 25: -YY_RULE_SETUP -#line 147 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_TEXTURE0_RGB; - return(regVariable); - } - YY_BREAK -case 26: -YY_RULE_SETUP -#line 151 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_TEXTURE0_ALPHA; - return(regVariable); - } - YY_BREAK -case 27: -YY_RULE_SETUP -#line 155 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_TEXTURE0_BLUE; - return(regVariable); - } - YY_BREAK -case 28: -YY_RULE_SETUP -#line 159 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_TEXTURE0; - return(regVariable); - } - YY_BREAK -case 29: -YY_RULE_SETUP -#line 164 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_TEXTURE1_RGB; - return(regVariable); - } - YY_BREAK -case 30: -YY_RULE_SETUP -#line 168 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_TEXTURE1_ALPHA; - return(regVariable); - } - YY_BREAK -case 31: -YY_RULE_SETUP -#line 172 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_TEXTURE1_BLUE; - return(regVariable); - } - YY_BREAK -case 32: -YY_RULE_SETUP -#line 176 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_TEXTURE1; - return(regVariable); - } - YY_BREAK -case 33: -YY_RULE_SETUP -#line 181 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_TEXTURE2_RGB; - return(regVariable); - } - YY_BREAK -case 34: -YY_RULE_SETUP -#line 185 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_TEXTURE2_ALPHA; - return(regVariable); - } - YY_BREAK -case 35: -YY_RULE_SETUP -#line 189 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_TEXTURE2_BLUE; - return(regVariable); - } - YY_BREAK -case 36: -YY_RULE_SETUP -#line 193 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_TEXTURE2; - return(regVariable); - } - YY_BREAK -case 37: -YY_RULE_SETUP -#line 198 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_TEXTURE3_RGB; - return(regVariable); - } - YY_BREAK -case 38: -YY_RULE_SETUP -#line 202 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_TEXTURE3_ALPHA; - return(regVariable); - } - YY_BREAK -case 39: -YY_RULE_SETUP -#line 206 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_TEXTURE3_BLUE; - return(regVariable); - } - YY_BREAK -case 40: -YY_RULE_SETUP -#line 210 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_TEXTURE3; - return(regVariable); - } - YY_BREAK -case 41: -YY_RULE_SETUP -#line 215 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_CONST_COLOR0_RGB; - return(regVariable); - } - YY_BREAK -case 42: -YY_RULE_SETUP -#line 219 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_CONST_COLOR0_ALPHA; - return(regVariable); - } - YY_BREAK -case 43: -YY_RULE_SETUP -#line 223 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_CONST_COLOR0_BLUE; - return(regVariable); - } - YY_BREAK -case 44: -YY_RULE_SETUP -#line 227 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_CONST_COLOR0; - return(constVariable); - } - YY_BREAK -case 45: -YY_RULE_SETUP -#line 232 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_CONST_COLOR1_RGB; - return(regVariable); - } - YY_BREAK -case 46: -YY_RULE_SETUP -#line 236 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_CONST_COLOR1_ALPHA; - return(regVariable); - } - YY_BREAK -case 47: -YY_RULE_SETUP -#line 240 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_CONST_COLOR1_BLUE; - return(regVariable); - } - YY_BREAK -case 48: -YY_RULE_SETUP -#line 244 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_CONST_COLOR1; - return(constVariable); - } - YY_BREAK -case 49: -YY_RULE_SETUP -#line 249 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_ZERO_RGB; - return(regVariable); - } - YY_BREAK -case 50: -YY_RULE_SETUP -#line 253 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_ZERO_ALPHA; - return(regVariable); - } - YY_BREAK -case 51: -YY_RULE_SETUP -#line 257 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_ZERO_BLUE; - return(regVariable); - } - YY_BREAK -case 52: -YY_RULE_SETUP -#line 261 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_ZERO; - return(regVariable); - } - YY_BREAK -case 53: -YY_RULE_SETUP -#line 266 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_ONE_RGB; - return(regVariable); - } - YY_BREAK -case 54: -YY_RULE_SETUP -#line 270 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_ONE_ALPHA; - return(regVariable); - } - YY_BREAK -case 55: -YY_RULE_SETUP -#line 274 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_ONE_BLUE; - return(regVariable); - } - YY_BREAK -case 56: -YY_RULE_SETUP -#line 278 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_ONE; - return(regVariable); - } - YY_BREAK -case 57: -YY_RULE_SETUP -#line 283 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_DISCARD; - return(regVariable); - } - YY_BREAK -case 58: -YY_RULE_SETUP -#line 288 "rc1.0_tokens.l" -return(fragment_rgb); - YY_BREAK -case 59: -YY_RULE_SETUP -#line 289 "rc1.0_tokens.l" -return(fragment_alpha); - YY_BREAK -case 60: -YY_RULE_SETUP -#line 291 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_FINAL_PRODUCT; - return(final_product); - } - YY_BREAK -case 61: -YY_RULE_SETUP -#line 296 "rc1.0_tokens.l" -{ - rc10_lval.registerEnum.word = RCP_COLOR_SUM; - return(color_sum); - } - YY_BREAK -case 62: -YY_RULE_SETUP -#line 301 "rc1.0_tokens.l" -return(expandString); - YY_BREAK -case 63: -YY_RULE_SETUP -#line 302 "rc1.0_tokens.l" -return(halfBiasString); - YY_BREAK -case 64: -YY_RULE_SETUP -#line 303 "rc1.0_tokens.l" -return(unsignedString); - YY_BREAK -case 65: -YY_RULE_SETUP -#line 304 "rc1.0_tokens.l" -return(unsignedInvertString); - YY_BREAK -case 66: -YY_RULE_SETUP -#line 305 "rc1.0_tokens.l" -{ - rc10_lval.ival = GL_TRUE; - return(muxString); - } - YY_BREAK -case 67: -YY_RULE_SETUP -#line 310 "rc1.0_tokens.l" -{ - rc10_lval.ival = GL_FALSE; - return(sumString); - } - YY_BREAK -case 68: -YY_RULE_SETUP -#line 315 "rc1.0_tokens.l" -{ - rc10_lval.ival = RCP_RGB; - return(rgb_portion); - } - YY_BREAK -case 69: -YY_RULE_SETUP -#line 319 "rc1.0_tokens.l" -{ - rc10_lval.ival = RCP_ALPHA; - return(alpha_portion); - } - YY_BREAK -case 70: -YY_RULE_SETUP -#line 324 "rc1.0_tokens.l" -{ - rc10_lval.ival = true; - return(clamp_color_sum); - } - YY_BREAK -case 71: -YY_RULE_SETUP -#line 328 "rc1.0_tokens.l" -return(lerp); - YY_BREAK -case 72: -YY_RULE_SETUP -#line 331 "rc1.0_tokens.l" -{ - rc10_lval.biasScaleEnum.word = RCP_BIAS_BY_NEGATIVE_ONE_HALF_SCALE_BY_TWO; - return(bias_by_negative_one_half_scale_by_two); - } - YY_BREAK -case 73: -YY_RULE_SETUP -#line 335 "rc1.0_tokens.l" -{ - rc10_lval.biasScaleEnum.word = RCP_BIAS_BY_NEGATIVE_ONE_HALF; - return(bias_by_negative_one_half); - } - YY_BREAK -case 74: -YY_RULE_SETUP -#line 339 "rc1.0_tokens.l" -{ - rc10_lval.biasScaleEnum.word = RCP_SCALE_BY_ONE_HALF; - return(scale_by_one_half); - } - YY_BREAK -case 75: -YY_RULE_SETUP -#line 343 "rc1.0_tokens.l" -{ - rc10_lval.biasScaleEnum.word = RCP_SCALE_BY_TWO; - return(scale_by_two); - } - YY_BREAK -case 76: -YY_RULE_SETUP -#line 347 "rc1.0_tokens.l" -{ - rc10_lval.biasScaleEnum.word = RCP_SCALE_BY_FOUR; - return(scale_by_four); - } - YY_BREAK -case 77: -YY_RULE_SETUP -#line 352 "rc1.0_tokens.l" -{ - rc10_lval.fval = (float)atof(yytext); - return(floatValue); - } - YY_BREAK -case 78: -YY_RULE_SETUP -#line 357 "rc1.0_tokens.l" -{ - rc10_lval.fval = (float)atof(yytext); - return(floatValue); - } - YY_BREAK -case 79: -YY_RULE_SETUP -#line 362 "rc1.0_tokens.l" -{ - rc10_lval.fval = (float)atof(yytext); - return(floatValue); - } - YY_BREAK -case 80: -YY_RULE_SETUP -#line 367 "rc1.0_tokens.l" -return(openBracket); - YY_BREAK -case 81: -YY_RULE_SETUP -#line 368 "rc1.0_tokens.l" -return(closeBracket); - YY_BREAK -case 82: -YY_RULE_SETUP -#line 369 "rc1.0_tokens.l" -return(openParen); - YY_BREAK -case 83: -YY_RULE_SETUP -#line 370 "rc1.0_tokens.l" -return(closeParen); - YY_BREAK -case 84: -YY_RULE_SETUP -#line 371 "rc1.0_tokens.l" -return(semicolon); - YY_BREAK -case 85: -YY_RULE_SETUP -#line 372 "rc1.0_tokens.l" -return(comma); - YY_BREAK -case 86: -YY_RULE_SETUP -#line 373 "rc1.0_tokens.l" -return(dot); - YY_BREAK -case 87: -YY_RULE_SETUP -#line 374 "rc1.0_tokens.l" -return(times); - YY_BREAK -case 88: -YY_RULE_SETUP -#line 375 "rc1.0_tokens.l" -return(minus); - YY_BREAK -case 89: -YY_RULE_SETUP -#line 376 "rc1.0_tokens.l" -return(plus); - YY_BREAK -case 90: -YY_RULE_SETUP -#line 377 "rc1.0_tokens.l" -return(equals); - YY_BREAK -case 91: -YY_RULE_SETUP -#line 379 "rc1.0_tokens.l" -{ - line_number++; - } - YY_BREAK -case 92: -YY_RULE_SETUP -#line 383 "rc1.0_tokens.l" -{} - YY_BREAK -case 93: -YY_RULE_SETUP -#line 385 "rc1.0_tokens.l" -{ - errors.set("unrecognized token", line_number); - } - YY_BREAK -case 94: -YY_RULE_SETUP -#line 390 "rc1.0_tokens.l" -ECHO; - YY_BREAK -#line 1589 "_rc1.0_lexer.cpp" -case YY_STATE_EOF(INITIAL): - yyterminate(); - - case YY_END_OF_BUFFER: - { - /* Amount of text matched not including the EOB char. */ - int yy_amount_of_matched_text = (int) (yy_cp - yytext_ptr) - 1; - - /* Undo the effects of YY_DO_BEFORE_ACTION. */ - *yy_cp = yy_hold_char; - YY_RESTORE_YY_MORE_OFFSET - - if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_NEW ) - { - /* We're scanning a new file or input source. It's - * possible that this happened because the user - * just pointed yyin at a new source and called - * yylex(). If so, then we have to assure - * consistency between yy_current_buffer and our - * globals. Here is the right place to do so, because - * this is the first action (other than possibly a - * back-up) that will match for the new input source. - */ - yy_n_chars = yy_current_buffer->yy_n_chars; - yy_current_buffer->yy_input_file = yyin; - yy_current_buffer->yy_buffer_status = YY_BUFFER_NORMAL; - } - - /* Note that here we test for yy_c_buf_p "<=" to the position - * of the first EOB in the buffer, since yy_c_buf_p will - * already have been incremented past the NUL character - * (since all states make transitions on EOB to the - * end-of-buffer state). Contrast this with the test - * in input(). - */ - if ( yy_c_buf_p <= &yy_current_buffer->yy_ch_buf[yy_n_chars] ) - { /* This was really a NUL. */ - yy_state_type yy_next_state; - - yy_c_buf_p = yytext_ptr + yy_amount_of_matched_text; - - yy_current_state = yy_get_previous_state(); - - /* Okay, we're now positioned to make the NUL - * transition. We couldn't have - * yy_get_previous_state() go ahead and do it - * for us because it doesn't know how to deal - * with the possibility of jamming (and we don't - * want to build jamming into it because then it - * will run more slowly). - */ - - yy_next_state = yy_try_NUL_trans( yy_current_state ); - - yy_bp = yytext_ptr + YY_MORE_ADJ; - - if ( yy_next_state ) - { - /* Consume the NUL. */ - yy_cp = ++yy_c_buf_p; - yy_current_state = yy_next_state; - goto yy_match; - } - - else - { - yy_cp = yy_c_buf_p; - goto yy_find_action; - } - } - - else switch ( yy_get_next_buffer() ) - { - case EOB_ACT_END_OF_FILE: - { - yy_did_buffer_switch_on_eof = 0; - - if ( yywrap() ) - { - /* Note: because we've taken care in - * yy_get_next_buffer() to have set up - * yytext, we can now set up - * yy_c_buf_p so that if some total - * hoser (like flex itself) wants to - * call the scanner after we return the - * YY_NULL, it'll still work - another - * YY_NULL will get returned. - */ - yy_c_buf_p = yytext_ptr + YY_MORE_ADJ; - - yy_act = YY_STATE_EOF(YY_START); - goto do_action; - } - - else - { - if ( ! yy_did_buffer_switch_on_eof ) - YY_NEW_FILE; - } - break; - } - - case EOB_ACT_CONTINUE_SCAN: - yy_c_buf_p = - yytext_ptr + yy_amount_of_matched_text; - - yy_current_state = yy_get_previous_state(); - - yy_cp = yy_c_buf_p; - yy_bp = yytext_ptr + YY_MORE_ADJ; - goto yy_match; - - case EOB_ACT_LAST_MATCH: - yy_c_buf_p = - &yy_current_buffer->yy_ch_buf[yy_n_chars]; - - yy_current_state = yy_get_previous_state(); - - yy_cp = yy_c_buf_p; - yy_bp = yytext_ptr + YY_MORE_ADJ; - goto yy_find_action; - } - break; - } - - default: - YY_FATAL_ERROR( - "fatal flex scanner internal error--no action found" ); - } /* end of action switch */ - } /* end of scanning one token */ - } /* end of yylex */ - - -/* yy_get_next_buffer - try to read in a new buffer - * - * Returns a code representing an action: - * EOB_ACT_LAST_MATCH - - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position - * EOB_ACT_END_OF_FILE - end of file - */ - -static int yy_get_next_buffer() - { - char *dest = yy_current_buffer->yy_ch_buf; - char *source = yytext_ptr; - int number_to_move, i; - int ret_val; - - if ( yy_c_buf_p > &yy_current_buffer->yy_ch_buf[yy_n_chars + 1] ) - YY_FATAL_ERROR( - "fatal flex scanner internal error--end of buffer missed" ); - - if ( yy_current_buffer->yy_fill_buffer == 0 ) - { /* Don't try to fill the buffer, so this is an EOF. */ - if ( yy_c_buf_p - yytext_ptr - YY_MORE_ADJ == 1 ) - { - /* We matched a single character, the EOB, so - * treat this as a final EOF. - */ - return EOB_ACT_END_OF_FILE; - } - - else - { - /* We matched some text prior to the EOB, first - * process it. - */ - return EOB_ACT_LAST_MATCH; - } - } - - /* Try to read more data. */ - - /* First move last chars to start of buffer. */ - number_to_move = (int) (yy_c_buf_p - yytext_ptr) - 1; - - for ( i = 0; i < number_to_move; ++i ) - *(dest++) = *(source++); - - if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_EOF_PENDING ) - /* don't do the read, it's not guaranteed to return an EOF, - * just force an EOF - */ - yy_current_buffer->yy_n_chars = yy_n_chars = 0; - - else - { - int num_to_read = - yy_current_buffer->yy_buf_size - number_to_move - 1; - - while ( num_to_read <= 0 ) - { /* Not enough room in the buffer - grow it. */ -#ifdef YY_USES_REJECT - YY_FATAL_ERROR( -"input buffer overflow, can't enlarge buffer because scanner uses REJECT" ); -#else - - /* just a shorter name for the current buffer */ - YY_BUFFER_STATE b = yy_current_buffer; - - int yy_c_buf_p_offset = - (int) (yy_c_buf_p - b->yy_ch_buf); - - if ( b->yy_is_our_buffer ) - { - int new_size = b->yy_buf_size * 2; - - if ( new_size <= 0 ) - b->yy_buf_size += b->yy_buf_size / 8; - else - b->yy_buf_size *= 2; - - b->yy_ch_buf = (char *) - /* Include room in for 2 EOB chars. */ - yy_flex_realloc( (void *) b->yy_ch_buf, - b->yy_buf_size + 2 ); - } - else - /* Can't grow it, we don't own it. */ - b->yy_ch_buf = 0; - - if ( ! b->yy_ch_buf ) - YY_FATAL_ERROR( - "fatal error - scanner input buffer overflow" ); - - yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; - - num_to_read = yy_current_buffer->yy_buf_size - - number_to_move - 1; -#endif - } - - if ( num_to_read > YY_READ_BUF_SIZE ) - num_to_read = YY_READ_BUF_SIZE; - - /* Read in more data. */ - YY_INPUT( (&yy_current_buffer->yy_ch_buf[number_to_move]), - yy_n_chars, num_to_read ); - - yy_current_buffer->yy_n_chars = yy_n_chars; - } - - if ( yy_n_chars == 0 ) - { - if ( number_to_move == YY_MORE_ADJ ) - { - ret_val = EOB_ACT_END_OF_FILE; - yyrestart( yyin ); - } - - else - { - ret_val = EOB_ACT_LAST_MATCH; - yy_current_buffer->yy_buffer_status = - YY_BUFFER_EOF_PENDING; - } - } - - else - ret_val = EOB_ACT_CONTINUE_SCAN; - - yy_n_chars += number_to_move; - yy_current_buffer->yy_ch_buf[yy_n_chars] = YY_END_OF_BUFFER_CHAR; - yy_current_buffer->yy_ch_buf[yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; - - yytext_ptr = &yy_current_buffer->yy_ch_buf[0]; - - return ret_val; - } - - -/* yy_get_previous_state - get the state just before the EOB char was reached */ - -static yy_state_type yy_get_previous_state() - { - yy_state_type yy_current_state; - char *yy_cp; - - yy_current_state = yy_start; - - for ( yy_cp = yytext_ptr + YY_MORE_ADJ; yy_cp < yy_c_buf_p; ++yy_cp ) - { - YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); - if ( yy_accept[yy_current_state] ) - { - yy_last_accepting_state = yy_current_state; - yy_last_accepting_cpos = yy_cp; - } - while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) - { - yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 309 ) - yy_c = yy_meta[(unsigned int) yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; - } - - return yy_current_state; - } - - -/* yy_try_NUL_trans - try to make a transition on the NUL character - * - * synopsis - * next_state = yy_try_NUL_trans( current_state ); - */ - -#ifdef YY_USE_PROTOS -static yy_state_type yy_try_NUL_trans( yy_state_type yy_current_state ) -#else -static yy_state_type yy_try_NUL_trans( yy_current_state ) -yy_state_type yy_current_state; -#endif - { - int yy_is_jam; - char *yy_cp = yy_c_buf_p; - - YY_CHAR yy_c = 1; - if ( yy_accept[yy_current_state] ) - { - yy_last_accepting_state = yy_current_state; - yy_last_accepting_cpos = yy_cp; - } - while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) - { - yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 309 ) - yy_c = yy_meta[(unsigned int) yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; - yy_is_jam = (yy_current_state == 308); - - return yy_is_jam ? 0 : yy_current_state; - } - - -#ifndef YY_NO_UNPUT -#ifdef YY_USE_PROTOS -static void yyunput( int c, char *yy_bp ) -#else -static void yyunput( c, yy_bp ) -int c; -char *yy_bp; -#endif - { - char *yy_cp = yy_c_buf_p; - - /* undo effects of setting up yytext */ - *yy_cp = yy_hold_char; - - if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 ) - { /* need to shift things up to make room */ - /* +2 for EOB chars. */ - int number_to_move = yy_n_chars + 2; - char *dest = &yy_current_buffer->yy_ch_buf[ - yy_current_buffer->yy_buf_size + 2]; - char *source = - &yy_current_buffer->yy_ch_buf[number_to_move]; - - while ( source > yy_current_buffer->yy_ch_buf ) - *--dest = *--source; - - yy_cp += (int) (dest - source); - yy_bp += (int) (dest - source); - yy_current_buffer->yy_n_chars = - yy_n_chars = yy_current_buffer->yy_buf_size; - - if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 ) - YY_FATAL_ERROR( "flex scanner push-back overflow" ); - } - - *--yy_cp = (char) c; - - - yytext_ptr = yy_bp; - yy_hold_char = *yy_cp; - yy_c_buf_p = yy_cp; - } -#endif /* ifndef YY_NO_UNPUT */ - - -#ifdef __cplusplus -static int yyinput() -#else -static int input() -#endif - { - int c; - - *yy_c_buf_p = yy_hold_char; - - if ( *yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) - { - /* yy_c_buf_p now points to the character we want to return. - * If this occurs *before* the EOB characters, then it's a - * valid NUL; if not, then we've hit the end of the buffer. - */ - if ( yy_c_buf_p < &yy_current_buffer->yy_ch_buf[yy_n_chars] ) - /* This was really a NUL. */ - *yy_c_buf_p = '\0'; - - else - { /* need more input */ - int offset = yy_c_buf_p - yytext_ptr; - ++yy_c_buf_p; - - switch ( yy_get_next_buffer() ) - { - case EOB_ACT_LAST_MATCH: - /* This happens because yy_g_n_b() - * sees that we've accumulated a - * token and flags that we need to - * try matching the token before - * proceeding. But for input(), - * there's no matching to consider. - * So convert the EOB_ACT_LAST_MATCH - * to EOB_ACT_END_OF_FILE. - */ - - /* Reset buffer status. */ - yyrestart( yyin ); - - /* fall through */ - - case EOB_ACT_END_OF_FILE: - { - if ( yywrap() ) - return EOF; - - if ( ! yy_did_buffer_switch_on_eof ) - YY_NEW_FILE; -#ifdef __cplusplus - return yyinput(); -#else - return input(); -#endif - } - - case EOB_ACT_CONTINUE_SCAN: - yy_c_buf_p = yytext_ptr + offset; - break; - } - } - } - - c = *(unsigned char *) yy_c_buf_p; /* cast for 8-bit char's */ - *yy_c_buf_p = '\0'; /* preserve yytext */ - yy_hold_char = *++yy_c_buf_p; - - - return c; - } - - -#ifdef YY_USE_PROTOS -void yyrestart( FILE *input_file ) -#else -void yyrestart( input_file ) -FILE *input_file; -#endif - { - if ( ! yy_current_buffer ) - yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); - - yy_init_buffer( yy_current_buffer, input_file ); - yy_load_buffer_state(); - } - - -#ifdef YY_USE_PROTOS -void yy_switch_to_buffer( YY_BUFFER_STATE new_buffer ) -#else -void yy_switch_to_buffer( new_buffer ) -YY_BUFFER_STATE new_buffer; -#endif - { - if ( yy_current_buffer == new_buffer ) - return; - - if ( yy_current_buffer ) - { - /* Flush out information for old buffer. */ - *yy_c_buf_p = yy_hold_char; - yy_current_buffer->yy_buf_pos = yy_c_buf_p; - yy_current_buffer->yy_n_chars = yy_n_chars; - } - - yy_current_buffer = new_buffer; - yy_load_buffer_state(); - - /* We don't actually know whether we did this switch during - * EOF (yywrap()) processing, but the only time this flag - * is looked at is after yywrap() is called, so it's safe - * to go ahead and always set it. - */ - yy_did_buffer_switch_on_eof = 1; - } - - -#ifdef YY_USE_PROTOS -void yy_load_buffer_state( void ) -#else -void yy_load_buffer_state() -#endif - { - yy_n_chars = yy_current_buffer->yy_n_chars; - yytext_ptr = yy_c_buf_p = yy_current_buffer->yy_buf_pos; - yyin = yy_current_buffer->yy_input_file; - yy_hold_char = *yy_c_buf_p; - } - - -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_create_buffer( FILE *file, int size ) -#else -YY_BUFFER_STATE yy_create_buffer( file, size ) -FILE *file; -int size; -#endif - { - YY_BUFFER_STATE b; - - b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) ); - if ( ! b ) - YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); - - b->yy_buf_size = size; - - /* yy_ch_buf has to be 2 characters longer than the size given because - * we need to put in 2 end-of-buffer characters. - */ - b->yy_ch_buf = (char *) yy_flex_alloc( b->yy_buf_size + 2 ); - if ( ! b->yy_ch_buf ) - YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); - - b->yy_is_our_buffer = 1; - - yy_init_buffer( b, file ); - - return b; - } - - -#ifdef YY_USE_PROTOS -void yy_delete_buffer( YY_BUFFER_STATE b ) -#else -void yy_delete_buffer( b ) -YY_BUFFER_STATE b; -#endif - { - if ( ! b ) - return; - - if ( b == yy_current_buffer ) - yy_current_buffer = (YY_BUFFER_STATE) 0; - - if ( b->yy_is_our_buffer ) - yy_flex_free( (void *) b->yy_ch_buf ); - - yy_flex_free( (void *) b ); - } - - -#ifndef _WIN32 -#include -#else -#ifndef YY_ALWAYS_INTERACTIVE -#ifndef YY_NEVER_INTERACTIVE -extern int isatty YY_PROTO(( int )); -#endif -#endif -#endif - -#ifdef YY_USE_PROTOS -void yy_init_buffer( YY_BUFFER_STATE b, FILE *file ) -#else -void yy_init_buffer( b, file ) -YY_BUFFER_STATE b; -FILE *file; -#endif - - - { - yy_flush_buffer( b ); - - b->yy_input_file = file; - b->yy_fill_buffer = 1; - -#if YY_ALWAYS_INTERACTIVE - b->yy_is_interactive = 1; -#else -#if YY_NEVER_INTERACTIVE - b->yy_is_interactive = 0; -#else - b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; -#endif -#endif - } - - -#ifdef YY_USE_PROTOS -void yy_flush_buffer( YY_BUFFER_STATE b ) -#else -void yy_flush_buffer( b ) -YY_BUFFER_STATE b; -#endif - - { - if ( ! b ) - return; - - b->yy_n_chars = 0; - - /* We always need two end-of-buffer characters. The first causes - * a transition to the end-of-buffer state. The second causes - * a jam in that state. - */ - b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; - b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; - - b->yy_buf_pos = &b->yy_ch_buf[0]; - - b->yy_at_bol = 1; - b->yy_buffer_status = YY_BUFFER_NEW; - - if ( b == yy_current_buffer ) - yy_load_buffer_state(); - } - - -#ifndef YY_NO_SCAN_BUFFER -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_scan_buffer( char *base, yy_size_t size ) -#else -YY_BUFFER_STATE yy_scan_buffer( base, size ) -char *base; -yy_size_t size; -#endif - { - YY_BUFFER_STATE b; - - if ( size < 2 || - base[size-2] != YY_END_OF_BUFFER_CHAR || - base[size-1] != YY_END_OF_BUFFER_CHAR ) - /* They forgot to leave room for the EOB's. */ - return 0; - - b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) ); - if ( ! b ) - YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); - - b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ - b->yy_buf_pos = b->yy_ch_buf = base; - b->yy_is_our_buffer = 0; - b->yy_input_file = 0; - b->yy_n_chars = b->yy_buf_size; - b->yy_is_interactive = 0; - b->yy_at_bol = 1; - b->yy_fill_buffer = 0; - b->yy_buffer_status = YY_BUFFER_NEW; - - yy_switch_to_buffer( b ); - - return b; - } -#endif - - -#ifndef YY_NO_SCAN_STRING -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_scan_string( yyconst char *yy_str ) -#else -YY_BUFFER_STATE yy_scan_string( yy_str ) -yyconst char *yy_str; -#endif - { - int len; - for ( len = 0; yy_str[len]; ++len ) - ; - - return yy_scan_bytes( yy_str, len ); - } -#endif - - -#ifndef YY_NO_SCAN_BYTES -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_scan_bytes( yyconst char *bytes, int len ) -#else -YY_BUFFER_STATE yy_scan_bytes( bytes, len ) -yyconst char *bytes; -int len; -#endif - { - YY_BUFFER_STATE b; - char *buf; - yy_size_t n; - int i; - - /* Get memory for full buffer, including space for trailing EOB's. */ - n = len + 2; - buf = (char *) yy_flex_alloc( n ); - if ( ! buf ) - YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); - - for ( i = 0; i < len; ++i ) - buf[i] = bytes[i]; - - buf[len] = buf[len+1] = YY_END_OF_BUFFER_CHAR; - - b = yy_scan_buffer( buf, n ); - if ( ! b ) - YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); - - /* It's okay to grow etc. this buffer, and we should throw it - * away when we're done. - */ - b->yy_is_our_buffer = 1; - - return b; - } -#endif - - -#ifndef YY_NO_PUSH_STATE -#ifdef YY_USE_PROTOS -static void yy_push_state( int new_state ) -#else -static void yy_push_state( new_state ) -int new_state; -#endif - { - if ( yy_start_stack_ptr >= yy_start_stack_depth ) - { - yy_size_t new_size; - - yy_start_stack_depth += YY_START_STACK_INCR; - new_size = yy_start_stack_depth * sizeof( int ); - - if ( ! yy_start_stack ) - yy_start_stack = (int *) yy_flex_alloc( new_size ); - - else - yy_start_stack = (int *) yy_flex_realloc( - (void *) yy_start_stack, new_size ); - - if ( ! yy_start_stack ) - YY_FATAL_ERROR( - "out of memory expanding start-condition stack" ); - } - - yy_start_stack[yy_start_stack_ptr++] = YY_START; - - BEGIN(new_state); - } -#endif - - -#ifndef YY_NO_POP_STATE -static void yy_pop_state() - { - if ( --yy_start_stack_ptr < 0 ) - YY_FATAL_ERROR( "start-condition stack underflow" ); - - BEGIN(yy_start_stack[yy_start_stack_ptr]); - } -#endif - - -#ifndef YY_NO_TOP_STATE -static int yy_top_state() - { - return yy_start_stack[yy_start_stack_ptr - 1]; - } -#endif - -#ifndef YY_EXIT_FAILURE -#define YY_EXIT_FAILURE 2 -#endif - -#ifdef YY_USE_PROTOS -static void yy_fatal_error( yyconst char msg[] ) -#else -static void yy_fatal_error( msg ) -char msg[]; -#endif - { - (void) fprintf( stderr, "%s\n", msg ); - exit( YY_EXIT_FAILURE ); - } - - - -/* Redefine yyless() so it works in section 3 code. */ - -#undef yyless -#define yyless(n) \ - do \ - { \ - /* Undo effects of setting up yytext. */ \ - yytext[yyleng] = yy_hold_char; \ - yy_c_buf_p = yytext + n; \ - yy_hold_char = *yy_c_buf_p; \ - *yy_c_buf_p = '\0'; \ - yyleng = n; \ - } \ - while ( 0 ) - - -/* Internal utility routines. */ - -#ifndef yytext_ptr -#ifdef YY_USE_PROTOS -static void yy_flex_strncpy( char *s1, yyconst char *s2, int n ) -#else -static void yy_flex_strncpy( s1, s2, n ) -char *s1; -yyconst char *s2; -int n; -#endif - { - int i; - for ( i = 0; i < n; ++i ) - s1[i] = s2[i]; - } -#endif - -#ifdef YY_NEED_STRLEN -#ifdef YY_USE_PROTOS -static int yy_flex_strlen( yyconst char *s ) -#else -static int yy_flex_strlen( s ) -yyconst char *s; -#endif - { - int n; - for ( n = 0; s[n]; ++n ) - ; - - return n; - } -#endif - - -#ifdef YY_USE_PROTOS -static void *yy_flex_alloc( yy_size_t size ) -#else -static void *yy_flex_alloc( size ) -yy_size_t size; -#endif - { - return (void *) malloc( size ); - } - -#ifdef YY_USE_PROTOS -static void *yy_flex_realloc( void *ptr, yy_size_t size ) -#else -static void *yy_flex_realloc( ptr, size ) -void *ptr; -yy_size_t size; -#endif - { - /* The cast to (char *) in the following accommodates both - * implementations that use char* generic pointers, and those - * that use void* generic pointers. It works with the latter - * because both ANSI C and C++ allow castless assignment from - * any pointer type to void*, and deal with argument conversions - * as though doing an assignment. - */ - return (void *) realloc( (char *) ptr, size ); - } - -#ifdef YY_USE_PROTOS -static void yy_flex_free( void *ptr ) -#else -static void yy_flex_free( ptr ) -void *ptr; -#endif - { - free( ptr ); - } - -#if YY_MAIN -int main() - { - yylex(); - return 0; - } -#endif -#line 390 "rc1.0_tokens.l" - - -bool rc10_init_more(); - -bool rc10_init(char* inputString) -{ - myin = inputString; - return rc10_init_more(); -} - -#ifndef rc10_wrap -int rc10_wrap(void) -{ - return(1); -} -#endif diff --git a/RenderSystems/GL/src/nvparse/_rc1.0_parser.cpp b/RenderSystems/GL/src/nvparse/_rc1.0_parser.cpp deleted file mode 100644 index 5b3d48a30af..00000000000 --- a/RenderSystems/GL/src/nvparse/_rc1.0_parser.cpp +++ /dev/null @@ -1,2565 +0,0 @@ -/* A Bison parser, made by GNU Bison 3.0.2. */ - -/* Bison implementation for Yacc-like parsers in C - - Copyright (C) 1984, 1989-1990, 2000-2013 Free Software Foundation, Inc. - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . */ - -/* As a special exception, you may create a larger work that contains - part or all of the Bison parser skeleton and distribute that work - under terms of your choice, so long as that work isn't itself a - parser generator using the skeleton or a modified version thereof - as a parser skeleton. Alternatively, if you modify or redistribute - the parser skeleton itself, you may (at your option) remove this - special exception, which will cause the skeleton and the resulting - Bison output files to be licensed under the GNU General Public - License without this special exception. - - This special exception was added by the Free Software Foundation in - version 2.2 of Bison. */ - -/* C LALR(1) parser skeleton written by Richard Stallman, by - simplifying the original so-called "semantic" parser. */ - -/* All symbols defined below should begin with yy or YY, to avoid - infringing on user name space. This should be done even for local - variables, as they might otherwise be expanded by user macros. - There are some unavoidable exceptions within include files to - define necessary library symbols; they are noted "INFRINGES ON - USER NAME SPACE" below. */ - -/* Identify Bison output. */ -#define YYBISON 1 - -/* Bison version. */ -#define YYBISON_VERSION "3.0.2" - -/* Skeleton name. */ -#define YYSKELETON_NAME "yacc.c" - -/* Pure parsers. */ -#define YYPURE 0 - -/* Push parsers. */ -#define YYPUSH 0 - -/* Pull parsers. */ -#define YYPULL 1 - - -/* Substitute the variable and function names. */ -#define yyparse rc10_parse -#define yylex rc10_lex -#define yyerror rc10_error -#define yydebug rc10_debug -#define yynerrs rc10_nerrs - -#define yylval rc10_lval -#define yychar rc10_char - -/* Copy the first part of user declarations. */ -#line 3 "rc1.0_grammar.y" /* yacc.c:339 */ - -void yyerror(const char* s); -int yylex ( void ); - -#ifdef _WIN32 -# include -#endif - -#include -#include - -#include "rc1.0_combiners.h" -#include "nvparse_errors.h" -#include "nvparse_externs.h" - - - -#line 92 "_rc1.0_parser.c" /* yacc.c:339 */ - -# ifndef YY_NULLPTR -# if defined __cplusplus && 201103L <= __cplusplus -# define YY_NULLPTR nullptr -# else -# define YY_NULLPTR 0 -# endif -# endif - -/* Enabling verbose error messages. */ -#ifdef YYERROR_VERBOSE -# undef YYERROR_VERBOSE -# define YYERROR_VERBOSE 1 -#else -# define YYERROR_VERBOSE 0 -#endif - -/* In a future release of Bison, this section will be replaced - by #include "_rc1.0_parser.h". */ -#ifndef YY_RC10_RC1_0_PARSER_H_INCLUDED -# define YY_RC10_RC1_0_PARSER_H_INCLUDED -/* Debug traces. */ -#ifndef YYDEBUG -# define YYDEBUG 0 -#endif -#if YYDEBUG -extern int rc10_debug; -#endif - -/* Token type. */ -#ifndef YYTOKENTYPE -# define YYTOKENTYPE - enum yytokentype - { - regVariable = 258, - constVariable = 259, - color_sum = 260, - final_product = 261, - expandString = 262, - halfBiasString = 263, - unsignedString = 264, - unsignedInvertString = 265, - muxString = 266, - sumString = 267, - rgb_portion = 268, - alpha_portion = 269, - openParen = 270, - closeParen = 271, - openBracket = 272, - closeBracket = 273, - semicolon = 274, - comma = 275, - dot = 276, - times = 277, - minus = 278, - equals = 279, - plus = 280, - bias_by_negative_one_half_scale_by_two = 281, - bias_by_negative_one_half = 282, - scale_by_one_half = 283, - scale_by_two = 284, - scale_by_four = 285, - clamp_color_sum = 286, - lerp = 287, - fragment_rgb = 288, - fragment_alpha = 289, - floatValue = 290 - }; -#endif - -/* Value type. */ -#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED -typedef union YYSTYPE YYSTYPE; -union YYSTYPE -{ -#line 20 "rc1.0_grammar.y" /* yacc.c:355 */ - - int ival; - float fval; - RegisterEnum registerEnum; - BiasScaleEnum biasScaleEnum; - MappedRegisterStruct mappedRegisterStruct; - ConstColorStruct constColorStruct; - GeneralPortionStruct generalPortionStruct; - GeneralFunctionStruct generalFunctionStruct; - OpStruct opStruct; - GeneralCombinerStruct generalCombinerStruct; - GeneralCombinersStruct generalCombinersStruct; - FinalProductStruct finalProductStruct; - FinalRgbFunctionStruct finalRgbFunctionStruct; - FinalAlphaFunctionStruct finalAlphaFunctionStruct; - FinalCombinerStruct finalCombinerStruct; - CombinersStruct combinersStruct; - -#line 187 "_rc1.0_parser.c" /* yacc.c:355 */ -}; -# define YYSTYPE_IS_TRIVIAL 1 -# define YYSTYPE_IS_DECLARED 1 -#endif - - -extern YYSTYPE rc10_lval; - -int rc10_parse (void); - -#endif /* !YY_RC10_RC1_0_PARSER_H_INCLUDED */ - -/* Copy the second part of user declarations. */ - -#line 202 "_rc1.0_parser.c" /* yacc.c:358 */ - -#ifdef short -# undef short -#endif - -#ifdef YYTYPE_UINT8 -typedef YYTYPE_UINT8 yytype_uint8; -#else -typedef unsigned char yytype_uint8; -#endif - -#ifdef YYTYPE_INT8 -typedef YYTYPE_INT8 yytype_int8; -#else -typedef signed char yytype_int8; -#endif - -#ifdef YYTYPE_UINT16 -typedef YYTYPE_UINT16 yytype_uint16; -#else -typedef unsigned short int yytype_uint16; -#endif - -#ifdef YYTYPE_INT16 -typedef YYTYPE_INT16 yytype_int16; -#else -typedef short int yytype_int16; -#endif - -#ifndef YYSIZE_T -# ifdef __SIZE_TYPE__ -# define YYSIZE_T __SIZE_TYPE__ -# elif defined size_t -# define YYSIZE_T size_t -# elif ! defined YYSIZE_T -# include /* INFRINGES ON USER NAME SPACE */ -# define YYSIZE_T size_t -# else -# define YYSIZE_T unsigned int -# endif -#endif - -#define YYSIZE_MAXIMUM ((YYSIZE_T) -1) - -#ifndef YY_ -# if defined YYENABLE_NLS && YYENABLE_NLS -# if ENABLE_NLS -# include /* INFRINGES ON USER NAME SPACE */ -# define YY_(Msgid) dgettext ("bison-runtime", Msgid) -# endif -# endif -# ifndef YY_ -# define YY_(Msgid) Msgid -# endif -#endif - -#ifndef YY_ATTRIBUTE -# if (defined __GNUC__ \ - && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \ - || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C -# define YY_ATTRIBUTE(Spec) __attribute__(Spec) -# else -# define YY_ATTRIBUTE(Spec) /* empty */ -# endif -#endif - -#ifndef YY_ATTRIBUTE_PURE -# define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__)) -#endif - -#ifndef YY_ATTRIBUTE_UNUSED -# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__)) -#endif - -#if !defined _Noreturn \ - && (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112) -# if defined _MSC_VER && 1200 <= _MSC_VER -# define _Noreturn __declspec (noreturn) -# else -# define _Noreturn YY_ATTRIBUTE ((__noreturn__)) -# endif -#endif - -/* Suppress unused-variable warnings by "using" E. */ -#if ! defined lint || defined __GNUC__ -# define YYUSE(E) ((void) (E)) -#else -# define YYUSE(E) /* empty */ -#endif - -#if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ -/* Suppress an incorrect diagnostic about yylval being uninitialized. */ -# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ - _Pragma ("GCC diagnostic push") \ - _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\ - _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") -# define YY_IGNORE_MAYBE_UNINITIALIZED_END \ - _Pragma ("GCC diagnostic pop") -#else -# define YY_INITIAL_VALUE(Value) Value -#endif -#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN -# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN -# define YY_IGNORE_MAYBE_UNINITIALIZED_END -#endif -#ifndef YY_INITIAL_VALUE -# define YY_INITIAL_VALUE(Value) /* Nothing. */ -#endif - - -#if ! defined yyoverflow || YYERROR_VERBOSE - -/* The parser invokes alloca or malloc; define the necessary symbols. */ - -# ifdef YYSTACK_USE_ALLOCA -# if YYSTACK_USE_ALLOCA -# ifdef __GNUC__ -# define YYSTACK_ALLOC __builtin_alloca -# elif defined __BUILTIN_VA_ARG_INCR -# include /* INFRINGES ON USER NAME SPACE */ -# elif defined _AIX -# define YYSTACK_ALLOC __alloca -# elif defined _MSC_VER -# include /* INFRINGES ON USER NAME SPACE */ -# define alloca _alloca -# else -# define YYSTACK_ALLOC alloca -# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS -# include /* INFRINGES ON USER NAME SPACE */ - /* Use EXIT_SUCCESS as a witness for stdlib.h. */ -# ifndef EXIT_SUCCESS -# define EXIT_SUCCESS 0 -# endif -# endif -# endif -# endif -# endif - -# ifdef YYSTACK_ALLOC - /* Pacify GCC's 'empty if-body' warning. */ -# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) -# ifndef YYSTACK_ALLOC_MAXIMUM - /* The OS might guarantee only one guard page at the bottom of the stack, - and a page size can be as small as 4096 bytes. So we cannot safely - invoke alloca (N) if N exceeds 4096. Use a slightly smaller number - to allow for a few compiler-allocated temporary stack slots. */ -# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ -# endif -# else -# define YYSTACK_ALLOC YYMALLOC -# define YYSTACK_FREE YYFREE -# ifndef YYSTACK_ALLOC_MAXIMUM -# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM -# endif -# if (defined __cplusplus && ! defined EXIT_SUCCESS \ - && ! ((defined YYMALLOC || defined malloc) \ - && (defined YYFREE || defined free))) -# include /* INFRINGES ON USER NAME SPACE */ -# ifndef EXIT_SUCCESS -# define EXIT_SUCCESS 0 -# endif -# endif -# ifndef YYMALLOC -# define YYMALLOC malloc -# if ! defined malloc && ! defined EXIT_SUCCESS -void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ -# endif -# endif -# ifndef YYFREE -# define YYFREE free -# if ! defined free && ! defined EXIT_SUCCESS -void free (void *); /* INFRINGES ON USER NAME SPACE */ -# endif -# endif -# endif -#endif /* ! defined yyoverflow || YYERROR_VERBOSE */ - - -#if (! defined yyoverflow \ - && (! defined __cplusplus \ - || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) - -/* A type that is properly aligned for any stack member. */ -union yyalloc -{ - yytype_int16 yyss_alloc; - YYSTYPE yyvs_alloc; -}; - -/* The size of the maximum gap between one aligned stack and the next. */ -# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) - -/* The size of an array large to enough to hold all stacks, each with - N elements. */ -# define YYSTACK_BYTES(N) \ - ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ - + YYSTACK_GAP_MAXIMUM) - -# define YYCOPY_NEEDED 1 - -/* Relocate STACK from its old location to the new one. The - local variables YYSIZE and YYSTACKSIZE give the old and new number of - elements in the stack, and YYPTR gives the new location of the - stack. Advance YYPTR to a properly aligned location for the next - stack. */ -# define YYSTACK_RELOCATE(Stack_alloc, Stack) \ - do \ - { \ - YYSIZE_T yynewbytes; \ - YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ - Stack = &yyptr->Stack_alloc; \ - yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ - yyptr += yynewbytes / sizeof (*yyptr); \ - } \ - while (0) - -#endif - -#if defined YYCOPY_NEEDED && YYCOPY_NEEDED -/* Copy COUNT objects from SRC to DST. The source and destination do - not overlap. */ -# ifndef YYCOPY -# if defined __GNUC__ && 1 < __GNUC__ -# define YYCOPY(Dst, Src, Count) \ - __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src))) -# else -# define YYCOPY(Dst, Src, Count) \ - do \ - { \ - YYSIZE_T yyi; \ - for (yyi = 0; yyi < (Count); yyi++) \ - (Dst)[yyi] = (Src)[yyi]; \ - } \ - while (0) -# endif -# endif -#endif /* !YYCOPY_NEEDED */ - -/* YYFINAL -- State number of the termination state. */ -#define YYFINAL 27 -/* YYLAST -- Last index in YYTABLE. */ -#define YYLAST 258 - -/* YYNTOKENS -- Number of terminals. */ -#define YYNTOKENS 36 -/* YYNNTS -- Number of nonterminals. */ -#define YYNNTS 22 -/* YYNRULES -- Number of rules. */ -#define YYNRULES 88 -/* YYNSTATES -- Number of states. */ -#define YYNSTATES 220 - -/* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned - by yylex, with out-of-bounds checking. */ -#define YYUNDEFTOK 2 -#define YYMAXUTOK 290 - -#define YYTRANSLATE(YYX) \ - ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) - -/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM - as returned by yylex, without out-of-bounds checking. */ -static const yytype_uint8 yytranslate[] = -{ - 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, - 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, - 35 -}; - -#if YYDEBUG - /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ -static const yytype_uint16 yyrline[] = -{ - 0, 73, 73, 80, 86, 92, 98, 106, 114, 124, - 133, 138, 146, 152, 158, 164, 170, 176, 184, 190, - 200, 204, 210, 216, 222, 228, 234, 240, 246, 252, - 260, 266, 272, 278, 284, 290, 296, 302, 310, 318, - 324, 336, 344, 352, 356, 360, 364, 368, 374, 380, - 386, 392, 398, 404, 410, 416, 422, 430, 436, 442, - 448, 454, 461, 467, 473, 479, 485, 492, 500, 508, - 516, 524, 533, 541, 549, 557, 565, 575, 581, 589, - 595, 601, 611, 623, 633, 647, 661, 669, 673 -}; -#endif - -#if YYDEBUG || YYERROR_VERBOSE || 0 -/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. - First, the terminals, then, starting at YYNTOKENS, nonterminals. */ -static const char *const yytname[] = -{ - "$end", "error", "$undefined", "regVariable", "constVariable", - "color_sum", "final_product", "expandString", "halfBiasString", - "unsignedString", "unsignedInvertString", "muxString", "sumString", - "rgb_portion", "alpha_portion", "openParen", "closeParen", "openBracket", - "closeBracket", "semicolon", "comma", "dot", "times", "minus", "equals", - "plus", "bias_by_negative_one_half_scale_by_two", - "bias_by_negative_one_half", "scale_by_one_half", "scale_by_two", - "scale_by_four", "clamp_color_sum", "lerp", "fragment_rgb", - "fragment_alpha", "floatValue", "$accept", "WholeEnchilada", "Combiners", - "ConstColor", "GeneralCombiners", "GeneralCombiner", "GeneralPortion", - "PortionDesignator", "GeneralMappedRegister", "GeneralFunction", "Dot", - "Mul", "Mux", "Sum", "BiasScale", "FinalMappedRegister", "FinalCombiner", - "ClampColorSum", "FinalProduct", "FinalRgbFunction", - "FinalAlphaFunction", "Register", YY_NULLPTR -}; -#endif - -# ifdef YYPRINT -/* YYTOKNUM[NUM] -- (External) token number corresponding to the - (internal) symbol number NUM (which must be that of a token). */ -static const yytype_uint16 yytoknum[] = -{ - 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, - 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, - 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, - 285, 286, 287, 288, 289, 290 -}; -# endif - -#define YYPACT_NINF -63 - -#define yypact_value_is_default(Yystate) \ - (!!((Yystate) == (-63))) - -#define YYTABLE_NINF -1 - -#define yytable_value_is_error(Yytable_value) \ - 0 - - /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing - STATE-NUM. */ -static const yytype_int16 yypact[] = -{ - 48, -13, -8, 53, 16, 11, 14, 73, -63, 48, - 94, -63, -63, 43, 147, 44, 47, 70, 144, -63, - -63, 53, -5, 74, 78, 83, 144, -63, 94, 94, - -63, -63, -63, 17, 44, 47, 17, 44, 47, -63, - -63, 64, -63, -63, -63, -63, 97, 111, 107, -63, - 58, 103, -63, 117, 80, 132, 142, 21, 139, 94, - -63, -63, 44, 47, -63, -63, 44, 47, -63, -63, - 146, 167, 171, 144, 151, -63, 149, -63, 116, 80, - 80, 138, -63, 144, -63, 144, 92, -63, -63, -63, - -63, -63, -63, 133, 170, 173, 174, 175, 176, 177, - 160, -63, 169, -63, -63, 179, 180, 181, 182, 183, - 184, -63, -63, -63, 80, 129, 185, 28, 186, 187, - 188, -63, -63, -63, -63, -63, -63, -63, -63, 191, - 193, 194, 195, 196, -63, -63, -63, 189, 199, 200, - 201, 202, 152, 163, -63, 144, -63, 144, 144, -63, - 164, 203, 204, 205, 206, 207, 98, 80, 80, 80, - 80, 212, 213, -63, -63, 129, 129, 198, 210, 211, - 214, -63, -63, -63, -63, -63, 215, 217, 219, 220, - 221, 222, 80, 80, 223, 224, 144, -63, 144, 165, - 225, 228, -63, -63, -63, -63, 229, 230, -63, -63, - 231, 232, 233, 234, 235, -63, -63, 50, 144, 236, - -63, -63, -63, 144, 240, -63, 238, 239, -63, -63 -}; - - /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. - Performed when YYTABLE does not specify something else to do. Zero - means the default is an error. */ -static const yytype_uint8 yydefact[] = -{ - 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, - 0, 11, 8, 0, 0, 67, 72, 0, 0, 20, - 21, 0, 0, 0, 0, 0, 0, 1, 0, 0, - 6, 10, 5, 0, 68, 73, 0, 69, 74, 62, - 57, 0, 88, 87, 51, 54, 0, 0, 0, 48, - 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, - 7, 3, 70, 75, 63, 58, 71, 76, 64, 59, - 0, 0, 0, 0, 0, 16, 0, 12, 0, 33, - 37, 0, 77, 0, 84, 0, 0, 86, 4, 65, - 60, 66, 61, 0, 0, 0, 0, 0, 0, 0, - 0, 17, 0, 13, 19, 0, 0, 0, 0, 0, - 0, 30, 31, 32, 34, 0, 0, 0, 0, 0, - 0, 52, 55, 49, 53, 56, 50, 78, 14, 0, - 0, 0, 0, 0, 18, 35, 36, 0, 0, 0, - 0, 0, 0, 0, 22, 0, 82, 0, 0, 85, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 23, 40, 0, 0, 0, 0, 0, - 0, 43, 44, 45, 46, 47, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 83, 0, 0, - 0, 0, 24, 26, 28, 29, 0, 0, 38, 39, - 0, 0, 0, 0, 0, 25, 27, 0, 0, 0, - 41, 42, 81, 0, 0, 9, 0, 0, 79, 80 -}; - - /* YYPGOTO[NTERM-NUM]. */ -static const yytype_int16 yypgoto[] = -{ - -63, -63, -63, 9, -2, 0, -18, -63, -62, -63, - 39, 61, -63, -63, -63, -25, -4, 190, 208, 1, - 8, -52 -}; - - /* YYDEFGOTO[NTERM-NUM]. */ -static const yytype_int16 yydefgoto[] = -{ - -1, 7, 8, 9, 10, 11, 22, 23, 143, 78, - 79, 80, 135, 136, 110, 48, 12, 13, 14, 15, - 16, 49 -}; - - /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If - positive, shift that token. If negative, reduce the rule whose - number is the opposite. If YYTABLE_NINF, syntax error. */ -static const yytype_uint8 yytable[] = -{ - 57, 58, 81, 51, 53, 30, 32, 29, 19, 20, - 31, 17, 21, 52, 34, 37, 18, 40, 28, 96, - 99, 35, 38, 39, 60, 61, 59, 81, 81, 31, - 50, 24, 74, 76, 62, 25, 65, 66, 26, 69, - 84, 63, 64, 85, 67, 68, 86, 146, 100, 2, - 5, 6, 1, 147, 2, 88, 102, 1, 116, 31, - 117, 119, 137, 144, 90, 3, 19, 20, 92, 212, - 89, 19, 20, 27, 91, 213, 5, 6, 6, 4, - 5, 5, 6, 42, 43, 41, 42, 43, 44, 45, - 163, 54, 46, 47, 55, 42, 43, 44, 45, 70, - 2, 46, 47, 184, 185, 178, 179, 180, 181, 176, - 177, 3, 71, 144, 144, 56, 19, 20, 111, 113, - 167, 75, 168, 169, 118, 4, 72, 5, 6, 73, - 196, 197, 42, 43, 104, 77, 138, 139, 140, 141, - 112, 114, 105, 106, 107, 108, 109, 42, 43, 44, - 45, 82, 142, 46, 47, 42, 43, 83, 87, 161, - 162, 200, 115, 201, 19, 20, 93, 103, 120, 101, - 42, 43, 94, 95, 42, 43, 97, 98, 4, 127, - 5, 6, 164, 214, 165, 166, 121, 128, 216, 122, - 123, 124, 125, 126, 129, 130, 131, 132, 133, 170, - 202, 148, 134, 0, 36, 145, 149, 151, 150, 152, - 153, 154, 155, 156, 157, 158, 159, 160, 186, 0, - 0, 33, 171, 172, 173, 174, 175, 182, 183, 187, - 190, 188, 191, 0, 189, 192, 193, 194, 195, 0, - 0, 203, 198, 199, 204, 205, 206, 207, 0, 209, - 0, 0, 208, 210, 211, 215, 217, 218, 219 -}; - -static const yytype_int16 yycheck[] = -{ - 25, 26, 54, 21, 22, 9, 10, 9, 13, 14, - 10, 24, 3, 18, 13, 14, 24, 16, 9, 71, - 72, 13, 14, 15, 28, 29, 28, 79, 80, 29, - 21, 15, 50, 51, 33, 24, 35, 36, 24, 38, - 19, 33, 34, 22, 36, 37, 25, 19, 73, 6, - 33, 34, 4, 25, 6, 59, 74, 4, 83, 59, - 85, 86, 114, 115, 63, 17, 13, 14, 67, 19, - 62, 13, 14, 0, 66, 25, 33, 34, 34, 31, - 33, 33, 34, 3, 4, 15, 3, 4, 5, 6, - 142, 17, 9, 10, 16, 3, 4, 5, 6, 35, - 6, 9, 10, 165, 166, 157, 158, 159, 160, 11, - 12, 17, 15, 165, 166, 32, 13, 14, 79, 80, - 145, 18, 147, 148, 32, 31, 15, 33, 34, 22, - 182, 183, 3, 4, 18, 18, 7, 8, 9, 10, - 79, 80, 26, 27, 28, 29, 30, 3, 4, 5, - 6, 19, 23, 9, 10, 3, 4, 15, 19, 7, - 8, 186, 24, 188, 13, 14, 20, 18, 35, 18, - 3, 4, 5, 6, 3, 4, 5, 6, 31, 19, - 33, 34, 19, 208, 21, 22, 16, 18, 213, 16, - 16, 16, 16, 16, 15, 15, 15, 15, 15, 35, - 35, 15, 18, -1, 14, 20, 19, 16, 20, 16, - 16, 16, 16, 24, 15, 15, 15, 15, 20, -1, - -1, 13, 19, 19, 19, 19, 19, 15, 15, 19, - 15, 20, 15, -1, 20, 16, 16, 16, 16, -1, - -1, 16, 19, 19, 16, 16, 16, 16, -1, 16, - -1, -1, 20, 19, 19, 19, 16, 19, 19 -}; - - /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing - symbol of state STATE-NUM. */ -static const yytype_uint8 yystos[] = -{ - 0, 4, 6, 17, 31, 33, 34, 37, 38, 39, - 40, 41, 52, 53, 54, 55, 56, 24, 24, 13, - 14, 39, 42, 43, 15, 24, 24, 0, 39, 40, - 52, 41, 52, 54, 55, 56, 53, 55, 56, 56, - 55, 15, 3, 4, 5, 6, 9, 10, 51, 57, - 39, 42, 18, 42, 17, 16, 32, 51, 51, 40, - 52, 52, 55, 56, 56, 55, 55, 56, 56, 55, - 35, 15, 15, 22, 42, 18, 42, 18, 45, 46, - 47, 57, 19, 15, 19, 22, 25, 19, 52, 56, - 55, 56, 55, 20, 5, 6, 57, 5, 6, 57, - 51, 18, 42, 18, 18, 26, 27, 28, 29, 30, - 50, 46, 47, 46, 47, 24, 51, 51, 32, 51, - 35, 16, 16, 16, 16, 16, 16, 19, 18, 15, - 15, 15, 15, 15, 18, 48, 49, 57, 7, 8, - 9, 10, 23, 44, 57, 20, 19, 25, 15, 19, - 20, 16, 16, 16, 16, 16, 24, 15, 15, 15, - 15, 7, 8, 57, 19, 21, 22, 51, 51, 51, - 35, 19, 19, 19, 19, 19, 11, 12, 57, 57, - 57, 57, 15, 15, 44, 44, 20, 19, 20, 20, - 15, 15, 16, 16, 16, 16, 57, 57, 19, 19, - 51, 51, 35, 16, 16, 16, 16, 16, 20, 16, - 19, 19, 19, 25, 51, 19, 51, 16, 19, 19 -}; - - /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ -static const yytype_uint8 yyr1[] = -{ - 0, 36, 37, 38, 38, 38, 38, 38, 38, 39, - 40, 40, 41, 41, 41, 41, 41, 41, 42, 42, - 43, 43, 44, 44, 44, 44, 44, 44, 44, 44, - 45, 45, 45, 45, 45, 45, 45, 45, 46, 47, - 47, 48, 49, 50, 50, 50, 50, 50, 51, 51, - 51, 51, 51, 51, 51, 51, 51, 52, 52, 52, - 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, - 52, 52, 52, 52, 52, 52, 52, 53, 54, 55, - 55, 55, 55, 55, 55, 55, 56, 57, 57 -}; - - /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */ -static const yytype_uint8 yyr2[] = -{ - 0, 2, 1, 3, 4, 2, 2, 3, 1, 12, - 2, 1, 4, 5, 6, 3, 4, 5, 5, 4, - 1, 1, 1, 2, 4, 5, 4, 5, 4, 4, - 2, 2, 2, 1, 2, 3, 3, 1, 6, 6, - 4, 6, 6, 4, 4, 4, 4, 4, 1, 4, - 4, 1, 4, 4, 1, 4, 4, 2, 3, 3, - 4, 4, 2, 3, 3, 4, 4, 1, 2, 2, - 3, 3, 1, 2, 2, 3, 3, 4, 6, 13, - 13, 11, 6, 8, 4, 6, 4, 1, 1 -}; - - -#define yyerrok (yyerrstatus = 0) -#define yyclearin (yychar = YYEMPTY) -#define YYEMPTY (-2) -#define YYEOF 0 - -#define YYACCEPT goto yyacceptlab -#define YYABORT goto yyabortlab -#define YYERROR goto yyerrorlab - - -#define YYRECOVERING() (!!yyerrstatus) - -#define YYBACKUP(Token, Value) \ -do \ - if (yychar == YYEMPTY) \ - { \ - yychar = (Token); \ - yylval = (Value); \ - YYPOPSTACK (yylen); \ - yystate = *yyssp; \ - goto yybackup; \ - } \ - else \ - { \ - yyerror (YY_("syntax error: cannot back up")); \ - YYERROR; \ - } \ -while (0) - -/* Error token number */ -#define YYTERROR 1 -#define YYERRCODE 256 - - - -/* Enable debugging if requested. */ -#if YYDEBUG - -# ifndef YYFPRINTF -# include /* INFRINGES ON USER NAME SPACE */ -# define YYFPRINTF fprintf -# endif - -# define YYDPRINTF(Args) \ -do { \ - if (yydebug) \ - YYFPRINTF Args; \ -} while (0) - -/* This macro is provided for backward compatibility. */ -#ifndef YY_LOCATION_PRINT -# define YY_LOCATION_PRINT(File, Loc) ((void) 0) -#endif - - -# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ -do { \ - if (yydebug) \ - { \ - YYFPRINTF (stderr, "%s ", Title); \ - yy_symbol_print (stderr, \ - Type, Value); \ - YYFPRINTF (stderr, "\n"); \ - } \ -} while (0) - - -/*----------------------------------------. -| Print this symbol's value on YYOUTPUT. | -`----------------------------------------*/ - -static void -yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) -{ - FILE *yyo = yyoutput; - YYUSE (yyo); - if (!yyvaluep) - return; -# ifdef YYPRINT - if (yytype < YYNTOKENS) - YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); -# endif - YYUSE (yytype); -} - - -/*--------------------------------. -| Print this symbol on YYOUTPUT. | -`--------------------------------*/ - -static void -yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) -{ - YYFPRINTF (yyoutput, "%s %s (", - yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]); - - yy_symbol_value_print (yyoutput, yytype, yyvaluep); - YYFPRINTF (yyoutput, ")"); -} - -/*------------------------------------------------------------------. -| yy_stack_print -- Print the state stack from its BOTTOM up to its | -| TOP (included). | -`------------------------------------------------------------------*/ - -static void -yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) -{ - YYFPRINTF (stderr, "Stack now"); - for (; yybottom <= yytop; yybottom++) - { - int yybot = *yybottom; - YYFPRINTF (stderr, " %d", yybot); - } - YYFPRINTF (stderr, "\n"); -} - -# define YY_STACK_PRINT(Bottom, Top) \ -do { \ - if (yydebug) \ - yy_stack_print ((Bottom), (Top)); \ -} while (0) - - -/*------------------------------------------------. -| Report that the YYRULE is going to be reduced. | -`------------------------------------------------*/ - -static void -yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule) -{ - unsigned long int yylno = yyrline[yyrule]; - int yynrhs = yyr2[yyrule]; - int yyi; - YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", - yyrule - 1, yylno); - /* The symbols being reduced. */ - for (yyi = 0; yyi < yynrhs; yyi++) - { - YYFPRINTF (stderr, " $%d = ", yyi + 1); - yy_symbol_print (stderr, - yystos[yyssp[yyi + 1 - yynrhs]], - &(yyvsp[(yyi + 1) - (yynrhs)]) - ); - YYFPRINTF (stderr, "\n"); - } -} - -# define YY_REDUCE_PRINT(Rule) \ -do { \ - if (yydebug) \ - yy_reduce_print (yyssp, yyvsp, Rule); \ -} while (0) - -/* Nonzero means print parse trace. It is left uninitialized so that - multiple parsers can coexist. */ -int yydebug; -#else /* !YYDEBUG */ -# define YYDPRINTF(Args) -# define YY_SYMBOL_PRINT(Title, Type, Value, Location) -# define YY_STACK_PRINT(Bottom, Top) -# define YY_REDUCE_PRINT(Rule) -#endif /* !YYDEBUG */ - - -/* YYINITDEPTH -- initial size of the parser's stacks. */ -#ifndef YYINITDEPTH -# define YYINITDEPTH 200 -#endif - -/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only - if the built-in stack extension method is used). - - Do not make this value too large; the results are undefined if - YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) - evaluated with infinite-precision integer arithmetic. */ - -#ifndef YYMAXDEPTH -# define YYMAXDEPTH 10000 -#endif - - -#if YYERROR_VERBOSE - -# ifndef yystrlen -# if defined __GLIBC__ && defined _STRING_H -# define yystrlen strlen -# else -/* Return the length of YYSTR. */ -static YYSIZE_T -yystrlen (const char *yystr) -{ - YYSIZE_T yylen; - for (yylen = 0; yystr[yylen]; yylen++) - continue; - return yylen; -} -# endif -# endif - -# ifndef yystpcpy -# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE -# define yystpcpy stpcpy -# else -/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in - YYDEST. */ -static char * -yystpcpy (char *yydest, const char *yysrc) -{ - char *yyd = yydest; - const char *yys = yysrc; - - while ((*yyd++ = *yys++) != '\0') - continue; - - return yyd - 1; -} -# endif -# endif - -# ifndef yytnamerr -/* Copy to YYRES the contents of YYSTR after stripping away unnecessary - quotes and backslashes, so that it's suitable for yyerror. The - heuristic is that double-quoting is unnecessary unless the string - contains an apostrophe, a comma, or backslash (other than - backslash-backslash). YYSTR is taken from yytname. If YYRES is - null, do not copy; instead, return the length of what the result - would have been. */ -static YYSIZE_T -yytnamerr (char *yyres, const char *yystr) -{ - if (*yystr == '"') - { - YYSIZE_T yyn = 0; - char const *yyp = yystr; - - for (;;) - switch (*++yyp) - { - case '\'': - case ',': - goto do_not_strip_quotes; - - case '\\': - if (*++yyp != '\\') - goto do_not_strip_quotes; - /* Fall through. */ - default: - if (yyres) - yyres[yyn] = *yyp; - yyn++; - break; - - case '"': - if (yyres) - yyres[yyn] = '\0'; - return yyn; - } - do_not_strip_quotes: ; - } - - if (! yyres) - return yystrlen (yystr); - - return yystpcpy (yyres, yystr) - yyres; -} -# endif - -/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message - about the unexpected token YYTOKEN for the state stack whose top is - YYSSP. - - Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is - not large enough to hold the message. In that case, also set - *YYMSG_ALLOC to the required number of bytes. Return 2 if the - required number of bytes is too large to store. */ -static int -yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg, - yytype_int16 *yyssp, int yytoken) -{ - YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]); - YYSIZE_T yysize = yysize0; - enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; - /* Internationalized format string. */ - const char *yyformat = YY_NULLPTR; - /* Arguments of yyformat. */ - char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; - /* Number of reported tokens (one for the "unexpected", one per - "expected"). */ - int yycount = 0; - - /* There are many possibilities here to consider: - - If this state is a consistent state with a default action, then - the only way this function was invoked is if the default action - is an error action. In that case, don't check for expected - tokens because there are none. - - The only way there can be no lookahead present (in yychar) is if - this state is a consistent state with a default action. Thus, - detecting the absence of a lookahead is sufficient to determine - that there is no unexpected or expected token to report. In that - case, just report a simple "syntax error". - - Don't assume there isn't a lookahead just because this state is a - consistent state with a default action. There might have been a - previous inconsistent state, consistent state with a non-default - action, or user semantic action that manipulated yychar. - - Of course, the expected token list depends on states to have - correct lookahead information, and it depends on the parser not - to perform extra reductions after fetching a lookahead from the - scanner and before detecting a syntax error. Thus, state merging - (from LALR or IELR) and default reductions corrupt the expected - token list. However, the list is correct for canonical LR with - one exception: it will still contain any token that will not be - accepted due to an error action in a later state. - */ - if (yytoken != YYEMPTY) - { - int yyn = yypact[*yyssp]; - yyarg[yycount++] = yytname[yytoken]; - if (!yypact_value_is_default (yyn)) - { - /* Start YYX at -YYN if negative to avoid negative indexes in - YYCHECK. In other words, skip the first -YYN actions for - this state because they are default actions. */ - int yyxbegin = yyn < 0 ? -yyn : 0; - /* Stay within bounds of both yycheck and yytname. */ - int yychecklim = YYLAST - yyn + 1; - int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; - int yyx; - - for (yyx = yyxbegin; yyx < yyxend; ++yyx) - if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR - && !yytable_value_is_error (yytable[yyx + yyn])) - { - if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) - { - yycount = 1; - yysize = yysize0; - break; - } - yyarg[yycount++] = yytname[yyx]; - { - YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]); - if (! (yysize <= yysize1 - && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) - return 2; - yysize = yysize1; - } - } - } - } - - switch (yycount) - { -# define YYCASE_(N, S) \ - case N: \ - yyformat = S; \ - break - YYCASE_(0, YY_("syntax error")); - YYCASE_(1, YY_("syntax error, unexpected %s")); - YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); - YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); - YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); - YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); -# undef YYCASE_ - } - - { - YYSIZE_T yysize1 = yysize + yystrlen (yyformat); - if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) - return 2; - yysize = yysize1; - } - - if (*yymsg_alloc < yysize) - { - *yymsg_alloc = 2 * yysize; - if (! (yysize <= *yymsg_alloc - && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) - *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; - return 1; - } - - /* Avoid sprintf, as that infringes on the user's name space. - Don't have undefined behavior even if the translation - produced a string with the wrong number of "%s"s. */ - { - char *yyp = *yymsg; - int yyi = 0; - while ((*yyp = *yyformat) != '\0') - if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) - { - yyp += yytnamerr (yyp, yyarg[yyi++]); - yyformat += 2; - } - else - { - yyp++; - yyformat++; - } - } - return 0; -} -#endif /* YYERROR_VERBOSE */ - -/*-----------------------------------------------. -| Release the memory associated to this symbol. | -`-----------------------------------------------*/ - -static void -yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep) -{ - YYUSE (yyvaluep); - if (!yymsg) - yymsg = "Deleting"; - YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); - - YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN - YYUSE (yytype); - YY_IGNORE_MAYBE_UNINITIALIZED_END -} - - - - -/* The lookahead symbol. */ -int yychar; - -/* The semantic value of the lookahead symbol. */ -YYSTYPE yylval; -/* Number of syntax errors so far. */ -int yynerrs; - - -/*----------. -| yyparse. | -`----------*/ - -int -yyparse (void) -{ - int yystate; - /* Number of tokens to shift before error messages enabled. */ - int yyerrstatus; - - /* The stacks and their tools: - 'yyss': related to states. - 'yyvs': related to semantic values. - - Refer to the stacks through separate pointers, to allow yyoverflow - to reallocate them elsewhere. */ - - /* The state stack. */ - yytype_int16 yyssa[YYINITDEPTH]; - yytype_int16 *yyss; - yytype_int16 *yyssp; - - /* The semantic value stack. */ - YYSTYPE yyvsa[YYINITDEPTH]; - YYSTYPE *yyvs; - YYSTYPE *yyvsp; - - YYSIZE_T yystacksize; - - int yyn; - int yyresult; - /* Lookahead token as an internal (translated) token number. */ - int yytoken = 0; - /* The variables used to return semantic value and location from the - action routines. */ - YYSTYPE yyval; - -#if YYERROR_VERBOSE - /* Buffer for error messages, and its allocated size. */ - char yymsgbuf[128]; - char *yymsg = yymsgbuf; - YYSIZE_T yymsg_alloc = sizeof yymsgbuf; -#endif - -#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) - - /* The number of symbols on the RHS of the reduced rule. - Keep to zero when no symbol should be popped. */ - int yylen = 0; - - yyssp = yyss = yyssa; - yyvsp = yyvs = yyvsa; - yystacksize = YYINITDEPTH; - - YYDPRINTF ((stderr, "Starting parse\n")); - - yystate = 0; - yyerrstatus = 0; - yynerrs = 0; - yychar = YYEMPTY; /* Cause a token to be read. */ - goto yysetstate; - -/*------------------------------------------------------------. -| yynewstate -- Push a new state, which is found in yystate. | -`------------------------------------------------------------*/ - yynewstate: - /* In all cases, when you get here, the value and location stacks - have just been pushed. So pushing a state here evens the stacks. */ - yyssp++; - - yysetstate: - *yyssp = yystate; - - if (yyss + yystacksize - 1 <= yyssp) - { - /* Get the current used size of the three stacks, in elements. */ - YYSIZE_T yysize = yyssp - yyss + 1; - -#ifdef yyoverflow - { - /* Give user a chance to reallocate the stack. Use copies of - these so that the &'s don't force the real ones into - memory. */ - YYSTYPE *yyvs1 = yyvs; - yytype_int16 *yyss1 = yyss; - - /* Each stack pointer address is followed by the size of the - data in use in that stack, in bytes. This used to be a - conditional around just the two extra args, but that might - be undefined if yyoverflow is a macro. */ - yyoverflow (YY_("memory exhausted"), - &yyss1, yysize * sizeof (*yyssp), - &yyvs1, yysize * sizeof (*yyvsp), - &yystacksize); - - yyss = yyss1; - yyvs = yyvs1; - } -#else /* no yyoverflow */ -# ifndef YYSTACK_RELOCATE - goto yyexhaustedlab; -# else - /* Extend the stack our own way. */ - if (YYMAXDEPTH <= yystacksize) - goto yyexhaustedlab; - yystacksize *= 2; - if (YYMAXDEPTH < yystacksize) - yystacksize = YYMAXDEPTH; - - { - yytype_int16 *yyss1 = yyss; - union yyalloc *yyptr = - (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); - if (! yyptr) - goto yyexhaustedlab; - YYSTACK_RELOCATE (yyss_alloc, yyss); - YYSTACK_RELOCATE (yyvs_alloc, yyvs); -# undef YYSTACK_RELOCATE - if (yyss1 != yyssa) - YYSTACK_FREE (yyss1); - } -# endif -#endif /* no yyoverflow */ - - yyssp = yyss + yysize - 1; - yyvsp = yyvs + yysize - 1; - - YYDPRINTF ((stderr, "Stack size increased to %lu\n", - (unsigned long int) yystacksize)); - - if (yyss + yystacksize - 1 <= yyssp) - YYABORT; - } - - YYDPRINTF ((stderr, "Entering state %d\n", yystate)); - - if (yystate == YYFINAL) - YYACCEPT; - - goto yybackup; - -/*-----------. -| yybackup. | -`-----------*/ -yybackup: - - /* Do appropriate processing given the current state. Read a - lookahead token if we need one and don't already have one. */ - - /* First try to decide what to do without reference to lookahead token. */ - yyn = yypact[yystate]; - if (yypact_value_is_default (yyn)) - goto yydefault; - - /* Not known => get a lookahead token if don't already have one. */ - - /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ - if (yychar == YYEMPTY) - { - YYDPRINTF ((stderr, "Reading a token: ")); - yychar = yylex (); - } - - if (yychar <= YYEOF) - { - yychar = yytoken = YYEOF; - YYDPRINTF ((stderr, "Now at end of input.\n")); - } - else - { - yytoken = YYTRANSLATE (yychar); - YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); - } - - /* If the proper action on seeing token YYTOKEN is to reduce or to - detect an error, take that action. */ - yyn += yytoken; - if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) - goto yydefault; - yyn = yytable[yyn]; - if (yyn <= 0) - { - if (yytable_value_is_error (yyn)) - goto yyerrlab; - yyn = -yyn; - goto yyreduce; - } - - /* Count tokens shifted since error; after three, turn off error - status. */ - if (yyerrstatus) - yyerrstatus--; - - /* Shift the lookahead token. */ - YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); - - /* Discard the shifted token. */ - yychar = YYEMPTY; - - yystate = yyn; - YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN - *++yyvsp = yylval; - YY_IGNORE_MAYBE_UNINITIALIZED_END - - goto yynewstate; - - -/*-----------------------------------------------------------. -| yydefault -- do the default action for the current state. | -`-----------------------------------------------------------*/ -yydefault: - yyn = yydefact[yystate]; - if (yyn == 0) - goto yyerrlab; - goto yyreduce; - - -/*-----------------------------. -| yyreduce -- Do a reduction. | -`-----------------------------*/ -yyreduce: - /* yyn is the number of a rule to reduce with. */ - yylen = yyr2[yyn]; - - /* If YYLEN is nonzero, implement the default value of the action: - '$$ = $1'. - - Otherwise, the following line sets YYVAL to garbage. - This behavior is undocumented and Bison - users should not rely upon it. Assigning to YYVAL - unconditionally makes the parser a bit smaller, and it avoids a - GCC warning that YYVAL may be used uninitialized. */ - yyval = yyvsp[1-yylen]; - - - YY_REDUCE_PRINT (yyn); - switch (yyn) - { - case 2: -#line 74 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - (yyvsp[0].combinersStruct).Validate(); - (yyvsp[0].combinersStruct).Invoke(); - } -#line 1430 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 3: -#line 81 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - CombinersStruct combinersStruct; - combinersStruct.Init((yyvsp[-1].generalCombinersStruct), (yyvsp[0].finalCombinerStruct), (yyvsp[-2].constColorStruct)); - (yyval.combinersStruct) = combinersStruct; - } -#line 1440 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 4: -#line 87 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - CombinersStruct combinersStruct; - combinersStruct.Init((yyvsp[-1].generalCombinersStruct), (yyvsp[0].finalCombinerStruct), (yyvsp[-3].constColorStruct), (yyvsp[-2].constColorStruct)); - (yyval.combinersStruct) = combinersStruct; - } -#line 1450 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 5: -#line 93 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - CombinersStruct combinersStruct; - combinersStruct.Init((yyvsp[-1].generalCombinersStruct), (yyvsp[0].finalCombinerStruct)); - (yyval.combinersStruct) = combinersStruct; - } -#line 1460 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 6: -#line 99 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - GeneralCombinersStruct generalCombinersStruct; - generalCombinersStruct.Init(); - CombinersStruct combinersStruct; - combinersStruct.Init(generalCombinersStruct, (yyvsp[0].finalCombinerStruct), (yyvsp[-1].constColorStruct)); - (yyval.combinersStruct) = combinersStruct; - } -#line 1472 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 7: -#line 107 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - GeneralCombinersStruct generalCombinersStruct; - generalCombinersStruct.Init(); - CombinersStruct combinersStruct; - combinersStruct.Init(generalCombinersStruct, (yyvsp[0].finalCombinerStruct), (yyvsp[-2].constColorStruct), (yyvsp[-1].constColorStruct)); - (yyval.combinersStruct) = combinersStruct; - } -#line 1484 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 8: -#line 115 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - GeneralCombinersStruct generalCombinersStruct; - generalCombinersStruct.Init(); - CombinersStruct combinersStruct; - combinersStruct.Init(generalCombinersStruct, (yyvsp[0].finalCombinerStruct)); - (yyval.combinersStruct) = combinersStruct; - } -#line 1496 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 9: -#line 125 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - ConstColorStruct constColorStruct; - constColorStruct.Init((yyvsp[-11].registerEnum), (yyvsp[-8].fval), (yyvsp[-6].fval), (yyvsp[-4].fval), (yyvsp[-2].fval)); - (yyval.constColorStruct) = constColorStruct; - } -#line 1506 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 10: -#line 134 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - (yyvsp[-1].generalCombinersStruct) += (yyvsp[0].generalCombinerStruct); - (yyval.generalCombinersStruct) = (yyvsp[-1].generalCombinersStruct); - } -#line 1515 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 11: -#line 139 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - GeneralCombinersStruct generalCombinersStruct; - generalCombinersStruct.Init((yyvsp[0].generalCombinerStruct)); - (yyval.generalCombinersStruct) = generalCombinersStruct; - } -#line 1525 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 12: -#line 147 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - GeneralCombinerStruct generalCombinerStruct; - generalCombinerStruct.Init((yyvsp[-2].generalPortionStruct), (yyvsp[-1].generalPortionStruct)); - (yyval.generalCombinerStruct) = generalCombinerStruct; - } -#line 1535 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 13: -#line 153 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - GeneralCombinerStruct generalCombinerStruct; - generalCombinerStruct.Init((yyvsp[-2].generalPortionStruct), (yyvsp[-1].generalPortionStruct), (yyvsp[-3].constColorStruct)); - (yyval.generalCombinerStruct) = generalCombinerStruct; - } -#line 1545 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 14: -#line 159 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - GeneralCombinerStruct generalCombinerStruct; - generalCombinerStruct.Init((yyvsp[-2].generalPortionStruct), (yyvsp[-1].generalPortionStruct), (yyvsp[-4].constColorStruct), (yyvsp[-3].constColorStruct)); - (yyval.generalCombinerStruct) = generalCombinerStruct; - } -#line 1555 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 15: -#line 165 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - GeneralCombinerStruct generalCombinerStruct; - generalCombinerStruct.Init((yyvsp[-1].generalPortionStruct)); - (yyval.generalCombinerStruct) = generalCombinerStruct; - } -#line 1565 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 16: -#line 171 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - GeneralCombinerStruct generalCombinerStruct; - generalCombinerStruct.Init((yyvsp[-1].generalPortionStruct), (yyvsp[-2].constColorStruct)); - (yyval.generalCombinerStruct) = generalCombinerStruct; - } -#line 1575 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 17: -#line 177 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - GeneralCombinerStruct generalCombinerStruct; - generalCombinerStruct.Init((yyvsp[-1].generalPortionStruct), (yyvsp[-3].constColorStruct), (yyvsp[-2].constColorStruct)); - (yyval.generalCombinerStruct) = generalCombinerStruct; - } -#line 1585 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 18: -#line 185 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - GeneralPortionStruct generalPortionStruct; - generalPortionStruct.Init((yyvsp[-4].ival), (yyvsp[-2].generalFunctionStruct), (yyvsp[-1].biasScaleEnum)); - (yyval.generalPortionStruct) = generalPortionStruct; - } -#line 1595 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 19: -#line 191 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - BiasScaleEnum noScale; - noScale.word = RCP_SCALE_BY_ONE; - GeneralPortionStruct generalPortionStruct; - generalPortionStruct.Init((yyvsp[-3].ival), (yyvsp[-1].generalFunctionStruct), noScale); - (yyval.generalPortionStruct) = generalPortionStruct; - } -#line 1607 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 20: -#line 201 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = (yyvsp[0].ival); - } -#line 1615 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 21: -#line 205 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = (yyvsp[0].ival); - } -#line 1623 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 22: -#line 211 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - MappedRegisterStruct reg; - reg.Init((yyvsp[0].registerEnum), GL_SIGNED_IDENTITY_NV); - (yyval.mappedRegisterStruct) = reg; - } -#line 1633 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 23: -#line 217 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - MappedRegisterStruct reg; - reg.Init((yyvsp[0].registerEnum), GL_SIGNED_NEGATE_NV); - (yyval.mappedRegisterStruct) = reg; - } -#line 1643 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 24: -#line 223 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - MappedRegisterStruct reg; - reg.Init((yyvsp[-1].registerEnum), GL_EXPAND_NORMAL_NV); - (yyval.mappedRegisterStruct) = reg; - } -#line 1653 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 25: -#line 229 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - MappedRegisterStruct reg; - reg.Init((yyvsp[-1].registerEnum), GL_EXPAND_NEGATE_NV); - (yyval.mappedRegisterStruct) = reg; - } -#line 1663 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 26: -#line 235 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - MappedRegisterStruct reg; - reg.Init((yyvsp[-1].registerEnum), GL_HALF_BIAS_NORMAL_NV); - (yyval.mappedRegisterStruct) = reg; - } -#line 1673 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 27: -#line 241 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - MappedRegisterStruct reg; - reg.Init((yyvsp[-1].registerEnum), GL_HALF_BIAS_NEGATE_NV); - (yyval.mappedRegisterStruct) = reg; - } -#line 1683 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 28: -#line 247 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - MappedRegisterStruct reg; - reg.Init((yyvsp[-1].registerEnum), GL_UNSIGNED_IDENTITY_NV); - (yyval.mappedRegisterStruct) = reg; - } -#line 1693 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 29: -#line 253 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - MappedRegisterStruct reg; - reg.Init((yyvsp[-1].registerEnum), GL_UNSIGNED_INVERT_NV); - (yyval.mappedRegisterStruct) = reg; - } -#line 1703 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 30: -#line 261 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - GeneralFunctionStruct generalFunction; - generalFunction.Init((yyvsp[-1].opStruct), (yyvsp[0].opStruct)); - (yyval.generalFunctionStruct) = generalFunction; - } -#line 1713 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 31: -#line 267 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - GeneralFunctionStruct generalFunction; - generalFunction.Init((yyvsp[-1].opStruct), (yyvsp[0].opStruct)); - (yyval.generalFunctionStruct) = generalFunction; - } -#line 1723 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 32: -#line 273 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - GeneralFunctionStruct generalFunction; - generalFunction.Init((yyvsp[-1].opStruct), (yyvsp[0].opStruct)); - (yyval.generalFunctionStruct) = generalFunction; - } -#line 1733 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 33: -#line 279 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - GeneralFunctionStruct generalFunction; - generalFunction.Init((yyvsp[0].opStruct)); - (yyval.generalFunctionStruct) = generalFunction; - } -#line 1743 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 34: -#line 285 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - GeneralFunctionStruct generalFunction; - generalFunction.Init((yyvsp[-1].opStruct), (yyvsp[0].opStruct)); - (yyval.generalFunctionStruct) = generalFunction; - } -#line 1753 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 35: -#line 291 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - GeneralFunctionStruct generalFunction; - generalFunction.Init((yyvsp[-2].opStruct), (yyvsp[-1].opStruct), (yyvsp[0].opStruct)); - (yyval.generalFunctionStruct) = generalFunction; - } -#line 1763 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 36: -#line 297 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - GeneralFunctionStruct generalFunction; - generalFunction.Init((yyvsp[-2].opStruct), (yyvsp[-1].opStruct), (yyvsp[0].opStruct)); - (yyval.generalFunctionStruct) = generalFunction; - } -#line 1773 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 37: -#line 303 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - GeneralFunctionStruct generalFunction; - generalFunction.Init((yyvsp[0].opStruct)); - (yyval.generalFunctionStruct) = generalFunction; - } -#line 1783 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 38: -#line 311 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - OpStruct dotFunction; - dotFunction.Init(RCP_DOT, (yyvsp[-5].registerEnum), (yyvsp[-3].mappedRegisterStruct), (yyvsp[-1].mappedRegisterStruct)); - (yyval.opStruct) = dotFunction; - } -#line 1793 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 39: -#line 319 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - OpStruct mulFunction; - mulFunction.Init(RCP_MUL, (yyvsp[-5].registerEnum), (yyvsp[-3].mappedRegisterStruct), (yyvsp[-1].mappedRegisterStruct)); - (yyval.opStruct) = mulFunction; - } -#line 1803 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 40: -#line 325 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - RegisterEnum zero; - zero.word = RCP_ZERO; - MappedRegisterStruct one; - one.Init(zero, GL_UNSIGNED_INVERT_NV); - OpStruct mulFunction; - mulFunction.Init(RCP_MUL, (yyvsp[-3].registerEnum), (yyvsp[-1].mappedRegisterStruct), one); - (yyval.opStruct) = mulFunction; - } -#line 1817 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 41: -#line 337 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - OpStruct muxFunction; - muxFunction.Init(RCP_MUX, (yyvsp[-5].registerEnum)); - (yyval.opStruct) = muxFunction; - } -#line 1827 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 42: -#line 345 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - OpStruct sumFunction; - sumFunction.Init(RCP_SUM, (yyvsp[-5].registerEnum)); - (yyval.opStruct) = sumFunction; - } -#line 1837 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 43: -#line 353 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.biasScaleEnum) = (yyvsp[-3].biasScaleEnum); - } -#line 1845 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 44: -#line 357 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.biasScaleEnum) = (yyvsp[-3].biasScaleEnum); - } -#line 1853 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 45: -#line 361 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.biasScaleEnum) = (yyvsp[-3].biasScaleEnum); - } -#line 1861 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 46: -#line 365 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.biasScaleEnum) = (yyvsp[-3].biasScaleEnum); - } -#line 1869 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 47: -#line 369 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.biasScaleEnum) = (yyvsp[-3].biasScaleEnum); - } -#line 1877 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 48: -#line 375 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - MappedRegisterStruct reg; - reg.Init((yyvsp[0].registerEnum), GL_UNSIGNED_IDENTITY_NV); - (yyval.mappedRegisterStruct) = reg; - } -#line 1887 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 49: -#line 381 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - MappedRegisterStruct reg; - reg.Init((yyvsp[-1].registerEnum), GL_UNSIGNED_IDENTITY_NV); - (yyval.mappedRegisterStruct) = reg; - } -#line 1897 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 50: -#line 387 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - MappedRegisterStruct reg; - reg.Init((yyvsp[-1].registerEnum), GL_UNSIGNED_INVERT_NV); - (yyval.mappedRegisterStruct) = reg; - } -#line 1907 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 51: -#line 393 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - MappedRegisterStruct reg; - reg.Init((yyvsp[0].registerEnum)); - (yyval.mappedRegisterStruct) = reg; - } -#line 1917 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 52: -#line 399 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - MappedRegisterStruct reg; - reg.Init((yyvsp[-1].registerEnum), GL_UNSIGNED_IDENTITY_NV); - (yyval.mappedRegisterStruct) = reg; - } -#line 1927 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 53: -#line 405 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - MappedRegisterStruct reg; - reg.Init((yyvsp[-1].registerEnum), GL_UNSIGNED_INVERT_NV); - (yyval.mappedRegisterStruct) = reg; - } -#line 1937 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 54: -#line 411 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - MappedRegisterStruct reg; - reg.Init((yyvsp[0].registerEnum)); - (yyval.mappedRegisterStruct) = reg; - } -#line 1947 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 55: -#line 417 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - MappedRegisterStruct reg; - reg.Init((yyvsp[-1].registerEnum), GL_UNSIGNED_IDENTITY_NV); - (yyval.mappedRegisterStruct) = reg; - } -#line 1957 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 56: -#line 423 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - MappedRegisterStruct reg; - reg.Init((yyvsp[-1].registerEnum), GL_UNSIGNED_INVERT_NV); - (yyval.mappedRegisterStruct) = reg; - } -#line 1967 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 57: -#line 431 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init((yyvsp[0].finalRgbFunctionStruct), (yyvsp[-1].finalAlphaFunctionStruct), false); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 1977 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 58: -#line 437 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init((yyvsp[0].finalRgbFunctionStruct), (yyvsp[-1].finalAlphaFunctionStruct), true); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 1987 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 59: -#line 443 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init((yyvsp[0].finalRgbFunctionStruct), (yyvsp[-1].finalAlphaFunctionStruct), false, (yyvsp[-2].finalProductStruct)); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 1997 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 60: -#line 449 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init((yyvsp[0].finalRgbFunctionStruct), (yyvsp[-1].finalAlphaFunctionStruct), true, (yyvsp[-2].finalProductStruct)); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 2007 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 61: -#line 455 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init((yyvsp[0].finalRgbFunctionStruct), (yyvsp[-1].finalAlphaFunctionStruct), true, (yyvsp[-3].finalProductStruct)); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 2017 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 62: -#line 462 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init((yyvsp[-1].finalRgbFunctionStruct), (yyvsp[0].finalAlphaFunctionStruct), false); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 2027 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 63: -#line 468 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init((yyvsp[-1].finalRgbFunctionStruct), (yyvsp[0].finalAlphaFunctionStruct), true); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 2037 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 64: -#line 474 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init((yyvsp[-1].finalRgbFunctionStruct), (yyvsp[0].finalAlphaFunctionStruct), false, (yyvsp[-2].finalProductStruct)); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 2047 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 65: -#line 480 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init((yyvsp[-1].finalRgbFunctionStruct), (yyvsp[0].finalAlphaFunctionStruct), true, (yyvsp[-2].finalProductStruct)); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 2057 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 66: -#line 486 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init((yyvsp[-1].finalRgbFunctionStruct), (yyvsp[0].finalAlphaFunctionStruct), true, (yyvsp[-3].finalProductStruct)); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 2067 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 67: -#line 493 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - FinalAlphaFunctionStruct finalAlphaFunctionStruct; - finalAlphaFunctionStruct.ZeroOut(); - finalCombinerStruct.Init((yyvsp[0].finalRgbFunctionStruct), finalAlphaFunctionStruct, false); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 2079 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 68: -#line 501 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - FinalAlphaFunctionStruct finalAlphaFunctionStruct; - finalAlphaFunctionStruct.ZeroOut(); - finalCombinerStruct.Init((yyvsp[0].finalRgbFunctionStruct), finalAlphaFunctionStruct, true); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 2091 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 69: -#line 509 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - FinalAlphaFunctionStruct finalAlphaFunctionStruct; - finalAlphaFunctionStruct.ZeroOut(); - finalCombinerStruct.Init((yyvsp[0].finalRgbFunctionStruct), finalAlphaFunctionStruct, false, (yyvsp[-1].finalProductStruct)); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 2103 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 70: -#line 517 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - FinalAlphaFunctionStruct finalAlphaFunctionStruct; - finalAlphaFunctionStruct.ZeroOut(); - finalCombinerStruct.Init((yyvsp[0].finalRgbFunctionStruct), finalAlphaFunctionStruct, true, (yyvsp[-1].finalProductStruct)); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 2115 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 71: -#line 525 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - FinalAlphaFunctionStruct finalAlphaFunctionStruct; - finalAlphaFunctionStruct.ZeroOut(); - finalCombinerStruct.Init((yyvsp[0].finalRgbFunctionStruct), finalAlphaFunctionStruct, true, (yyvsp[-2].finalProductStruct)); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 2127 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 72: -#line 534 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.ZeroOut(); - finalCombinerStruct.Init(finalRgbFunctionStruct, (yyvsp[0].finalAlphaFunctionStruct), false); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 2139 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 73: -#line 542 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.ZeroOut(); - finalCombinerStruct.Init(finalRgbFunctionStruct, (yyvsp[0].finalAlphaFunctionStruct), true); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 2151 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 74: -#line 550 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.ZeroOut(); - finalCombinerStruct.Init(finalRgbFunctionStruct, (yyvsp[0].finalAlphaFunctionStruct), false, (yyvsp[-1].finalProductStruct)); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 2163 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 75: -#line 558 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.ZeroOut(); - finalCombinerStruct.Init(finalRgbFunctionStruct, (yyvsp[0].finalAlphaFunctionStruct), true, (yyvsp[-1].finalProductStruct)); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 2175 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 76: -#line 566 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalCombinerStruct finalCombinerStruct; - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.ZeroOut(); - finalCombinerStruct.Init(finalRgbFunctionStruct, (yyvsp[0].finalAlphaFunctionStruct), true, (yyvsp[-2].finalProductStruct)); - (yyval.finalCombinerStruct) = finalCombinerStruct; - } -#line 2187 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 77: -#line 576 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = (yyvsp[-3].ival); - } -#line 2195 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 78: -#line 582 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalProductStruct finalProductStruct; - finalProductStruct.Init((yyvsp[-3].mappedRegisterStruct), (yyvsp[-1].mappedRegisterStruct)); - (yyval.finalProductStruct) = finalProductStruct; - } -#line 2205 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 79: -#line 590 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.Init((yyvsp[-8].mappedRegisterStruct), (yyvsp[-6].mappedRegisterStruct), (yyvsp[-4].mappedRegisterStruct), (yyvsp[-1].mappedRegisterStruct)); - (yyval.finalRgbFunctionStruct) = finalRgbFunctionStruct; - } -#line 2215 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 80: -#line 596 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.Init((yyvsp[-6].mappedRegisterStruct), (yyvsp[-4].mappedRegisterStruct), (yyvsp[-2].mappedRegisterStruct), (yyvsp[-10].mappedRegisterStruct)); - (yyval.finalRgbFunctionStruct) = finalRgbFunctionStruct; - } -#line 2225 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 81: -#line 602 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - RegisterEnum zero; - zero.word = RCP_ZERO; - MappedRegisterStruct reg; - reg.Init(zero, GL_UNSIGNED_IDENTITY_NV); - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.Init((yyvsp[-6].mappedRegisterStruct), (yyvsp[-4].mappedRegisterStruct), (yyvsp[-2].mappedRegisterStruct), reg); - (yyval.finalRgbFunctionStruct) = finalRgbFunctionStruct; - } -#line 2239 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 82: -#line 612 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - RegisterEnum zero; - zero.word = RCP_ZERO; - MappedRegisterStruct reg1; - reg1.Init(zero, GL_UNSIGNED_IDENTITY_NV); - MappedRegisterStruct reg2; - reg2.Init(zero, GL_UNSIGNED_IDENTITY_NV); - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.Init((yyvsp[-3].mappedRegisterStruct), (yyvsp[-1].mappedRegisterStruct), reg1, reg2); - (yyval.finalRgbFunctionStruct) = finalRgbFunctionStruct; - } -#line 2255 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 83: -#line 624 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - RegisterEnum zero; - zero.word = RCP_ZERO; - MappedRegisterStruct reg1; - reg1.Init(zero, GL_UNSIGNED_IDENTITY_NV); - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.Init((yyvsp[-5].mappedRegisterStruct), (yyvsp[-3].mappedRegisterStruct), reg1, (yyvsp[-1].mappedRegisterStruct)); - (yyval.finalRgbFunctionStruct) = finalRgbFunctionStruct; - } -#line 2269 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 84: -#line 634 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - RegisterEnum zero; - zero.word = RCP_ZERO; - MappedRegisterStruct reg1; - reg1.Init(zero, GL_UNSIGNED_IDENTITY_NV); - MappedRegisterStruct reg2; - reg2.Init(zero, GL_UNSIGNED_IDENTITY_NV); - MappedRegisterStruct reg3; - reg3.Init(zero, GL_UNSIGNED_IDENTITY_NV); - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.Init(reg1, reg2, reg3, (yyvsp[-1].mappedRegisterStruct)); - (yyval.finalRgbFunctionStruct) = finalRgbFunctionStruct; - } -#line 2287 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 85: -#line 648 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - RegisterEnum zero; - zero.word = RCP_ZERO; - MappedRegisterStruct reg2; - reg2.Init(zero, GL_UNSIGNED_INVERT_NV); - MappedRegisterStruct reg3; - reg3.Init(zero, GL_UNSIGNED_IDENTITY_NV); - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.Init((yyvsp[-3].mappedRegisterStruct), reg2, reg3, (yyvsp[-1].mappedRegisterStruct)); - (yyval.finalRgbFunctionStruct) = finalRgbFunctionStruct; - } -#line 2303 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 86: -#line 662 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - FinalAlphaFunctionStruct finalAlphaFunctionStruct; - finalAlphaFunctionStruct.Init((yyvsp[-1].mappedRegisterStruct)); - (yyval.finalAlphaFunctionStruct) = finalAlphaFunctionStruct; - } -#line 2313 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 87: -#line 670 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.registerEnum) = (yyvsp[0].registerEnum); - } -#line 2321 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - case 88: -#line 674 "rc1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.registerEnum) = (yyvsp[0].registerEnum); - } -#line 2329 "_rc1.0_parser.c" /* yacc.c:1646 */ - break; - - -#line 2333 "_rc1.0_parser.c" /* yacc.c:1646 */ - default: break; - } - /* User semantic actions sometimes alter yychar, and that requires - that yytoken be updated with the new translation. We take the - approach of translating immediately before every use of yytoken. - One alternative is translating here after every semantic action, - but that translation would be missed if the semantic action invokes - YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or - if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an - incorrect destructor might then be invoked immediately. In the - case of YYERROR or YYBACKUP, subsequent parser actions might lead - to an incorrect destructor call or verbose syntax error message - before the lookahead is translated. */ - YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); - - YYPOPSTACK (yylen); - yylen = 0; - YY_STACK_PRINT (yyss, yyssp); - - *++yyvsp = yyval; - - /* Now 'shift' the result of the reduction. Determine what state - that goes to, based on the state we popped back to and the rule - number reduced by. */ - - yyn = yyr1[yyn]; - - yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; - if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) - yystate = yytable[yystate]; - else - yystate = yydefgoto[yyn - YYNTOKENS]; - - goto yynewstate; - - -/*--------------------------------------. -| yyerrlab -- here on detecting error. | -`--------------------------------------*/ -yyerrlab: - /* Make sure we have latest lookahead translation. See comments at - user semantic actions for why this is necessary. */ - yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); - - /* If not already recovering from an error, report this error. */ - if (!yyerrstatus) - { - ++yynerrs; -#if ! YYERROR_VERBOSE - yyerror (YY_("syntax error")); -#else -# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ - yyssp, yytoken) - { - char const *yymsgp = YY_("syntax error"); - int yysyntax_error_status; - yysyntax_error_status = YYSYNTAX_ERROR; - if (yysyntax_error_status == 0) - yymsgp = yymsg; - else if (yysyntax_error_status == 1) - { - if (yymsg != yymsgbuf) - YYSTACK_FREE (yymsg); - yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); - if (!yymsg) - { - yymsg = yymsgbuf; - yymsg_alloc = sizeof yymsgbuf; - yysyntax_error_status = 2; - } - else - { - yysyntax_error_status = YYSYNTAX_ERROR; - yymsgp = yymsg; - } - } - yyerror (yymsgp); - if (yysyntax_error_status == 2) - goto yyexhaustedlab; - } -# undef YYSYNTAX_ERROR -#endif - } - - - - if (yyerrstatus == 3) - { - /* If just tried and failed to reuse lookahead token after an - error, discard it. */ - - if (yychar <= YYEOF) - { - /* Return failure if at end of input. */ - if (yychar == YYEOF) - YYABORT; - } - else - { - yydestruct ("Error: discarding", - yytoken, &yylval); - yychar = YYEMPTY; - } - } - - /* Else will try to reuse lookahead token after shifting the error - token. */ - goto yyerrlab1; - - -/*---------------------------------------------------. -| yyerrorlab -- error raised explicitly by YYERROR. | -`---------------------------------------------------*/ -yyerrorlab: - - /* Pacify compilers like GCC when the user code never invokes - YYERROR and the label yyerrorlab therefore never appears in user - code. */ - if (/*CONSTCOND*/ 0) - goto yyerrorlab; - - /* Do not reclaim the symbols of the rule whose action triggered - this YYERROR. */ - YYPOPSTACK (yylen); - yylen = 0; - YY_STACK_PRINT (yyss, yyssp); - yystate = *yyssp; - goto yyerrlab1; - - -/*-------------------------------------------------------------. -| yyerrlab1 -- common code for both syntax error and YYERROR. | -`-------------------------------------------------------------*/ -yyerrlab1: - yyerrstatus = 3; /* Each real token shifted decrements this. */ - - for (;;) - { - yyn = yypact[yystate]; - if (!yypact_value_is_default (yyn)) - { - yyn += YYTERROR; - if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) - { - yyn = yytable[yyn]; - if (0 < yyn) - break; - } - } - - /* Pop the current state because it cannot handle the error token. */ - if (yyssp == yyss) - YYABORT; - - - yydestruct ("Error: popping", - yystos[yystate], yyvsp); - YYPOPSTACK (1); - yystate = *yyssp; - YY_STACK_PRINT (yyss, yyssp); - } - - YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN - *++yyvsp = yylval; - YY_IGNORE_MAYBE_UNINITIALIZED_END - - - /* Shift the error token. */ - YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); - - yystate = yyn; - goto yynewstate; - - -/*-------------------------------------. -| yyacceptlab -- YYACCEPT comes here. | -`-------------------------------------*/ -yyacceptlab: - yyresult = 0; - goto yyreturn; - -/*-----------------------------------. -| yyabortlab -- YYABORT comes here. | -`-----------------------------------*/ -yyabortlab: - yyresult = 1; - goto yyreturn; - -#if !defined yyoverflow || YYERROR_VERBOSE -/*-------------------------------------------------. -| yyexhaustedlab -- memory exhaustion comes here. | -`-------------------------------------------------*/ -yyexhaustedlab: - yyerror (YY_("memory exhausted")); - yyresult = 2; - /* Fall through. */ -#endif - -yyreturn: - if (yychar != YYEMPTY) - { - /* Make sure we have latest lookahead translation. See comments at - user semantic actions for why this is necessary. */ - yytoken = YYTRANSLATE (yychar); - yydestruct ("Cleanup: discarding lookahead", - yytoken, &yylval); - } - /* Do not reclaim the symbols of the rule whose action triggered - this YYABORT or YYACCEPT. */ - YYPOPSTACK (yylen); - YY_STACK_PRINT (yyss, yyssp); - while (yyssp != yyss) - { - yydestruct ("Cleanup: popping", - yystos[*yyssp], yyvsp); - YYPOPSTACK (1); - } -#ifndef yyoverflow - if (yyss != yyssa) - YYSTACK_FREE (yyss); -#endif -#if YYERROR_VERBOSE - if (yymsg != yymsgbuf) - YYSTACK_FREE (yymsg); -#endif - return yyresult; -} -#line 679 "rc1.0_grammar.y" /* yacc.c:1906 */ - -void yyerror(const char* s) -{ - errors.set("unrecognized token"); -} diff --git a/RenderSystems/GL/src/nvparse/_rc1.0_parser.h b/RenderSystems/GL/src/nvparse/_rc1.0_parser.h deleted file mode 100644 index f1682bd91db..00000000000 --- a/RenderSystems/GL/src/nvparse/_rc1.0_parser.h +++ /dev/null @@ -1,119 +0,0 @@ -/* A Bison parser, made by GNU Bison 3.0.2. */ - -/* Bison interface for Yacc-like parsers in C - - Copyright (C) 1984, 1989-1990, 2000-2013 Free Software Foundation, Inc. - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . */ - -/* As a special exception, you may create a larger work that contains - part or all of the Bison parser skeleton and distribute that work - under terms of your choice, so long as that work isn't itself a - parser generator using the skeleton or a modified version thereof - as a parser skeleton. Alternatively, if you modify or redistribute - the parser skeleton itself, you may (at your option) remove this - special exception, which will cause the skeleton and the resulting - Bison output files to be licensed under the GNU General Public - License without this special exception. - - This special exception was added by the Free Software Foundation in - version 2.2 of Bison. */ - -#ifndef YY_RC10_RC1_0_PARSER_H_INCLUDED -# define YY_RC10_RC1_0_PARSER_H_INCLUDED -/* Debug traces. */ -#ifndef YYDEBUG -# define YYDEBUG 0 -#endif -#if YYDEBUG -extern int rc10_debug; -#endif - -/* Token type. */ -#ifndef YYTOKENTYPE -# define YYTOKENTYPE - enum yytokentype - { - regVariable = 258, - constVariable = 259, - color_sum = 260, - final_product = 261, - expandString = 262, - halfBiasString = 263, - unsignedString = 264, - unsignedInvertString = 265, - muxString = 266, - sumString = 267, - rgb_portion = 268, - alpha_portion = 269, - openParen = 270, - closeParen = 271, - openBracket = 272, - closeBracket = 273, - semicolon = 274, - comma = 275, - dot = 276, - times = 277, - minus = 278, - equals = 279, - plus = 280, - bias_by_negative_one_half_scale_by_two = 281, - bias_by_negative_one_half = 282, - scale_by_one_half = 283, - scale_by_two = 284, - scale_by_four = 285, - clamp_color_sum = 286, - lerp = 287, - fragment_rgb = 288, - fragment_alpha = 289, - floatValue = 290 - }; -#endif - -/* Value type. */ -#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED -typedef union YYSTYPE YYSTYPE; -union YYSTYPE -{ -#line 20 "rc1.0_grammar.y" /* yacc.c:1909 */ - - int ival; - float fval; - RegisterEnum registerEnum; - BiasScaleEnum biasScaleEnum; - MappedRegisterStruct mappedRegisterStruct; - ConstColorStruct constColorStruct; - GeneralPortionStruct generalPortionStruct; - GeneralFunctionStruct generalFunctionStruct; - OpStruct opStruct; - GeneralCombinerStruct generalCombinerStruct; - GeneralCombinersStruct generalCombinersStruct; - FinalProductStruct finalProductStruct; - FinalRgbFunctionStruct finalRgbFunctionStruct; - FinalAlphaFunctionStruct finalAlphaFunctionStruct; - FinalCombinerStruct finalCombinerStruct; - CombinersStruct combinersStruct; - -#line 109 "_rc1.0_parser.h" /* yacc.c:1909 */ -}; -# define YYSTYPE_IS_TRIVIAL 1 -# define YYSTYPE_IS_DECLARED 1 -#endif - - -extern YYSTYPE rc10_lval; - -int rc10_parse (void); - -#endif /* !YY_RC10_RC1_0_PARSER_H_INCLUDED */ diff --git a/RenderSystems/GL/src/nvparse/_ts1.0_lexer.cpp b/RenderSystems/GL/src/nvparse/_ts1.0_lexer.cpp deleted file mode 100644 index 4abeb1e35ac..00000000000 --- a/RenderSystems/GL/src/nvparse/_ts1.0_lexer.cpp +++ /dev/null @@ -1,2241 +0,0 @@ -#define yy_create_buffer ts10__create_buffer -#define yy_delete_buffer ts10__delete_buffer -#define yy_scan_buffer ts10__scan_buffer -#define yy_scan_string ts10__scan_string -#define yy_scan_bytes ts10__scan_bytes -#define yy_flex_debug ts10__flex_debug -#define yy_init_buffer ts10__init_buffer -#define yy_flush_buffer ts10__flush_buffer -#define yy_load_buffer_state ts10__load_buffer_state -#define yy_switch_to_buffer ts10__switch_to_buffer -#define yyin ts10_in -#define yyleng ts10_leng -#define yylex ts10_lex -#define yyout ts10_out -#define yyrestart ts10_restart -#define yytext ts10_text -#define yywrap ts10_wrap - -#line 20 "_ts1.0_lexer.cpp" -/* A lexical scanner generated by flex */ - -/* Scanner skeleton version: - * $Header: /home/daffy/u0/vern/flex/RCS/flex.skl,v 2.91 96/09/10 16:58:48 vern Exp $ - */ - -#define FLEX_SCANNER -#define YY_FLEX_MAJOR_VERSION 2 -#define YY_FLEX_MINOR_VERSION 5 - -#include -#include - -/* cfront 1.2 defines "c_plusplus" instead of "__cplusplus" */ -#ifdef c_plusplus -#ifndef __cplusplus -#define __cplusplus -#endif -#endif - - -#ifdef __cplusplus - -#include -#ifndef _WIN32 -#include -#endif - -/* Use prototypes in function declarations. */ -#define YY_USE_PROTOS - -/* The "const" storage-class-modifier is valid. */ -#define YY_USE_CONST - -#else /* ! __cplusplus */ - -#if __STDC__ - -#define YY_USE_PROTOS -#define YY_USE_CONST - -#endif /* __STDC__ */ -#endif /* ! __cplusplus */ - -#ifdef __TURBOC__ - #pragma warn -rch - #pragma warn -use -#include -#include -#define YY_USE_CONST -#define YY_USE_PROTOS -#endif - -#ifdef YY_USE_CONST -#define yyconst const -#else -#define yyconst -#endif - - -#ifdef YY_USE_PROTOS -#define YY_PROTO(proto) proto -#else -#define YY_PROTO(proto) () -#endif - - -/* Returned upon end-of-file. */ -#define YY_NULL 0 - -/* Promotes a possibly negative, possibly signed char to an unsigned - * integer for use as an array index. If the signed char is negative, - * we want to instead treat it as an 8-bit unsigned char, hence the - * double cast. - */ -#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) - -/* Enter a start condition. This macro really ought to take a parameter, - * but we do it the disgusting crufty way forced on us by the ()-less - * definition of BEGIN. - */ -#define BEGIN yy_start = 1 + 2 * - -/* Translate the current start state into a value that can be later handed - * to BEGIN to return to the state. The YYSTATE alias is for lex - * compatibility. - */ -#define YY_START ((yy_start - 1) / 2) -#define YYSTATE YY_START - -/* Action number for EOF rule of a given start state. */ -#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) - -/* Special action meaning "start processing a new file". */ -#define YY_NEW_FILE yyrestart( yyin ) - -#define YY_END_OF_BUFFER_CHAR 0 - -/* Size of default input buffer. */ -#define YY_BUF_SIZE 16384 - -typedef struct yy_buffer_state *YY_BUFFER_STATE; - -extern int yyleng; -extern FILE *yyin, *yyout; - -#define EOB_ACT_CONTINUE_SCAN 0 -#define EOB_ACT_END_OF_FILE 1 -#define EOB_ACT_LAST_MATCH 2 - -/* The funky do-while in the following #define is used to turn the definition - * int a single C statement (which needs a semi-colon terminator). This - * avoids problems with code like: - * - * if ( condition_holds ) - * yyless( 5 ); - * else - * do_something_else(); - * - * Prior to using the do-while the compiler would get upset at the - * "else" because it interpreted the "if" statement as being all - * done when it reached the ';' after the yyless() call. - */ - -/* Return all but the first 'n' matched characters back to the input stream. */ - -#define yyless(n) \ - do \ - { \ - /* Undo effects of setting up yytext. */ \ - *yy_cp = yy_hold_char; \ - YY_RESTORE_YY_MORE_OFFSET \ - yy_c_buf_p = yy_cp = yy_bp + n - YY_MORE_ADJ; \ - YY_DO_BEFORE_ACTION; /* set up yytext again */ \ - } \ - while ( 0 ) - -#define unput(c) yyunput( c, yytext_ptr ) - -/* The following is because we cannot portably get our hands on size_t - * (without autoconf's help, which isn't available because we want - * flex-generated scanners to compile on their own). - */ -typedef unsigned int yy_size_t; - - -struct yy_buffer_state - { - FILE *yy_input_file; - - char *yy_ch_buf; /* input buffer */ - char *yy_buf_pos; /* current position in input buffer */ - - /* Size of input buffer in bytes, not including room for EOB - * characters. - */ - yy_size_t yy_buf_size; - - /* Number of characters read into yy_ch_buf, not including EOB - * characters. - */ - int yy_n_chars; - - /* Whether we "own" the buffer - i.e., we know we created it, - * and can realloc() it to grow it, and should free() it to - * delete it. - */ - int yy_is_our_buffer; - - /* Whether this is an "interactive" input source; if so, and - * if we're using stdio for input, then we want to use getc() - * instead of fread(), to make sure we stop fetching input after - * each newline. - */ - int yy_is_interactive; - - /* Whether we're considered to be at the beginning of a line. - * If so, '^' rules will be active on the next match, otherwise - * not. - */ - int yy_at_bol; - - /* Whether to try to fill the input buffer when we reach the - * end of it. - */ - int yy_fill_buffer; - - int yy_buffer_status; -#define YY_BUFFER_NEW 0 -#define YY_BUFFER_NORMAL 1 - /* When an EOF's been seen but there's still some text to process - * then we mark the buffer as YY_EOF_PENDING, to indicate that we - * shouldn't try reading from the input source any more. We might - * still have a bunch of tokens to match, though, because of - * possible backing-up. - * - * When we actually see the EOF, we change the status to "new" - * (via yyrestart()), so that the user can continue scanning by - * just pointing yyin at a new input file. - */ -#define YY_BUFFER_EOF_PENDING 2 - }; - -static YY_BUFFER_STATE yy_current_buffer = 0; - -/* We provide macros for accessing buffer states in case in the - * future we want to put the buffer states in a more general - * "scanner state". - */ -#define YY_CURRENT_BUFFER yy_current_buffer - - -/* yy_hold_char holds the character lost when yytext is formed. */ -static char yy_hold_char; - -static int yy_n_chars; /* number of characters read into yy_ch_buf */ - - -int yyleng; - -/* Points to current character in buffer. */ -static char *yy_c_buf_p = (char *) 0; -static int yy_init = 1; /* whether we need to initialize */ -static int yy_start = 0; /* start state number */ - -/* Flag which is used to allow yywrap()'s to do buffer switches - * instead of setting up a fresh yyin. A bit of a hack ... - */ -static int yy_did_buffer_switch_on_eof; - -void yyrestart YY_PROTO(( FILE *input_file )); - -void yy_switch_to_buffer YY_PROTO(( YY_BUFFER_STATE new_buffer )); -void yy_load_buffer_state YY_PROTO(( void )); -YY_BUFFER_STATE yy_create_buffer YY_PROTO(( FILE *file, int size )); -void yy_delete_buffer YY_PROTO(( YY_BUFFER_STATE b )); -void yy_init_buffer YY_PROTO(( YY_BUFFER_STATE b, FILE *file )); -void yy_flush_buffer YY_PROTO(( YY_BUFFER_STATE b )); -#define YY_FLUSH_BUFFER yy_flush_buffer( yy_current_buffer ) - -YY_BUFFER_STATE yy_scan_buffer YY_PROTO(( char *base, yy_size_t size )); -YY_BUFFER_STATE yy_scan_string YY_PROTO(( yyconst char *yy_str )); -YY_BUFFER_STATE yy_scan_bytes YY_PROTO(( yyconst char *bytes, int len )); - -static void *yy_flex_alloc YY_PROTO(( yy_size_t )); -static void *yy_flex_realloc YY_PROTO(( void *, yy_size_t )); -static void yy_flex_free YY_PROTO(( void * )); - -#define yy_new_buffer yy_create_buffer - -#define yy_set_interactive(is_interactive) \ - { \ - if ( ! yy_current_buffer ) \ - yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \ - yy_current_buffer->yy_is_interactive = is_interactive; \ - } - -#define yy_set_bol(at_bol) \ - { \ - if ( ! yy_current_buffer ) \ - yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \ - yy_current_buffer->yy_at_bol = at_bol; \ - } - -#define YY_AT_BOL() (yy_current_buffer->yy_at_bol) - -typedef unsigned char YY_CHAR; -FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0; -typedef int yy_state_type; -extern char *yytext; -#define yytext_ptr yytext - -static yy_state_type yy_get_previous_state YY_PROTO(( void )); -static yy_state_type yy_try_NUL_trans YY_PROTO(( yy_state_type current_state )); -static int yy_get_next_buffer YY_PROTO(( void )); -static void yy_fatal_error YY_PROTO(( yyconst char msg[] )); - -/* Done after the current pattern has been matched and before the - * corresponding action - sets up yytext. - */ -#define YY_DO_BEFORE_ACTION \ - yytext_ptr = yy_bp; \ - yyleng = (int) (yy_cp - yy_bp); \ - yy_hold_char = *yy_cp; \ - *yy_cp = '\0'; \ - yy_c_buf_p = yy_cp; - -#define YY_NUM_RULES 59 -#define YY_END_OF_BUFFER 60 -static yyconst short int yy_accept[404] = - { 0, - 0, 0, 60, 59, 57, 56, 59, 59, 3, 4, - 5, 59, 7, 59, 59, 55, 6, 58, 58, 58, - 58, 58, 58, 58, 58, 58, 58, 57, 56, 0, - 0, 0, 55, 54, 1, 2, 53, 55, 58, 58, - 58, 58, 58, 58, 58, 58, 58, 58, 58, 0, - 53, 58, 58, 58, 58, 58, 58, 15, 58, 58, - 58, 0, 58, 58, 58, 58, 58, 58, 58, 58, - 9, 10, 11, 58, 0, 58, 58, 58, 58, 58, - 58, 58, 58, 58, 0, 58, 58, 58, 58, 58, - 12, 58, 58, 58, 8, 58, 58, 58, 58, 58, - - 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, - 58, 58, 58, 58, 58, 58, 58, 24, 58, 58, - 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, - 58, 58, 58, 16, 17, 19, 58, 58, 58, 58, - 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, - 58, 58, 27, 28, 58, 58, 58, 22, 58, 58, - 58, 58, 21, 58, 58, 58, 58, 58, 58, 58, - 58, 58, 13, 14, 58, 58, 58, 58, 58, 58, - 58, 58, 58, 58, 58, 58, 58, 58, 58, 23, - 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, - - 58, 58, 26, 20, 58, 58, 58, 58, 58, 58, - 58, 58, 58, 58, 58, 18, 58, 58, 58, 58, - 58, 58, 58, 58, 58, 58, 29, 30, 35, 36, - 37, 58, 58, 58, 58, 58, 58, 58, 58, 58, - 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, - 58, 58, 58, 25, 58, 58, 58, 58, 58, 58, - 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, - 38, 39, 40, 58, 58, 58, 58, 58, 58, 58, - 31, 32, 58, 58, 58, 58, 58, 58, 58, 58, - 58, 58, 58, 58, 58, 58, 33, 34, 58, 58, - - 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, - 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, - 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, - 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, - 58, 58, 58, 58, 58, 58, 44, 45, 46, 58, - 58, 58, 58, 58, 58, 58, 58, 58, 58, 41, - 42, 43, 58, 58, 58, 58, 58, 58, 58, 58, - 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, - 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, - 50, 51, 52, 58, 58, 58, 58, 58, 58, 47, - - 48, 49, 0 - } ; - -static yyconst int yy_ec[256] = - { 0, - 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, - 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 2, 5, 1, 6, 1, 1, 1, 1, 7, - 8, 9, 10, 11, 10, 12, 13, 14, 15, 16, - 17, 18, 18, 18, 18, 18, 18, 1, 19, 1, - 1, 1, 1, 1, 20, 21, 21, 21, 22, 21, - 23, 24, 21, 21, 21, 25, 21, 26, 27, 21, - 28, 29, 30, 31, 32, 21, 21, 21, 21, 33, - 1, 1, 1, 1, 34, 1, 35, 36, 37, 38, - - 39, 40, 41, 42, 21, 21, 21, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 21, 21, 53, - 54, 21, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1 - } ; - -static yyconst int yy_meta[55] = - { 0, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 2, 1, 2, 2, 2, 2, 2, 1, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2 - } ; - -static yyconst short int yy_base[405] = - { 0, - 0, 0, 844, 845, 841, 845, 52, 837, 845, 845, - 845, 45, 845, 50, 60, 60, 845, 829, 58, 59, - 46, 67, 70, 71, 72, 73, 75, 838, 845, 85, - 808, 76, 85, 104, 845, 845, 110, 117, 826, 83, - 74, 93, 95, 97, 98, 103, 104, 118, 84, 807, - 137, 126, 127, 128, 131, 129, 134, 824, 135, 137, - 150, 820, 147, 144, 148, 149, 160, 161, 163, 162, - 822, 821, 820, 164, 819, 165, 167, 168, 171, 169, - 172, 174, 176, 177, 816, 179, 180, 181, 183, 185, - 817, 187, 191, 193, 845, 188, 200, 199, 202, 203, - - 212, 205, 211, 217, 223, 224, 225, 226, 228, 230, - 227, 240, 234, 236, 231, 238, 246, 247, 248, 239, - 241, 250, 252, 251, 255, 259, 262, 268, 270, 272, - 274, 275, 281, 816, 815, 814, 284, 288, 286, 287, - 285, 289, 292, 298, 290, 294, 300, 301, 302, 304, - 305, 303, 813, 812, 319, 306, 307, 811, 309, 325, - 332, 334, 810, 327, 333, 335, 336, 337, 338, 339, - 346, 343, 809, 808, 350, 351, 355, 352, 357, 354, - 358, 360, 361, 362, 388, 367, 370, 371, 374, 807, - 377, 380, 386, 384, 395, 396, 397, 398, 399, 403, - - 400, 401, 402, 806, 407, 408, 411, 412, 413, 414, - 406, 422, 416, 420, 419, 805, 443, 446, 448, 451, - 454, 435, 425, 426, 427, 452, 804, 803, 802, 801, - 800, 437, 460, 461, 463, 465, 464, 467, 468, 469, - 470, 475, 473, 471, 474, 476, 481, 482, 483, 489, - 484, 496, 497, 799, 490, 491, 505, 506, 509, 508, - 510, 511, 520, 523, 524, 513, 512, 526, 527, 530, - 798, 797, 796, 531, 536, 537, 543, 540, 546, 545, - 795, 793, 551, 550, 553, 556, 557, 560, 561, 565, - 559, 567, 562, 571, 570, 563, 791, 790, 564, 569, - - 576, 577, 579, 580, 582, 583, 584, 585, 586, 596, - 599, 600, 601, 603, 604, 607, 608, 612, 613, 616, - 617, 619, 618, 622, 623, 628, 626, 627, 629, 641, - 642, 645, 647, 649, 652, 653, 656, 657, 665, 666, - 668, 654, 655, 672, 674, 648, 789, 788, 787, 679, - 683, 685, 686, 678, 687, 691, 693, 694, 695, 786, - 785, 784, 697, 699, 700, 701, 702, 703, 704, 709, - 712, 718, 720, 714, 721, 710, 715, 723, 728, 730, - 716, 731, 733, 751, 753, 760, 763, 735, 743, 745, - 783, 782, 781, 747, 764, 766, 767, 771, 773, 780, - - 774, 770, 845, 744 - } ; - -static yyconst short int yy_def[405] = - { 0, - 403, 1, 403, 403, 403, 403, 403, 403, 403, 403, - 403, 403, 403, 403, 403, 404, 403, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 403, 403, 403, - 403, 403, 403, 403, 403, 403, 403, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 403, - 403, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 403, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 403, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 403, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 403, 404, 404, 404, 404, 404, - - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - 404, 404, 404, 404, 404, 404, 404, 404, 404, 404, - - 404, 404, 0, 403 - } ; - -static yyconst short int yy_nxt[900] = - { 0, - 4, 5, 6, 7, 8, 9, 10, 11, 4, 12, - 13, 14, 15, 16, 16, 16, 16, 16, 17, 18, - 18, 18, 19, 18, 20, 18, 18, 18, 18, 18, - 18, 18, 18, 18, 18, 18, 21, 22, 23, 18, - 18, 18, 18, 18, 24, 25, 26, 18, 18, 18, - 27, 18, 18, 18, 29, 30, 32, 403, 33, 33, - 33, 33, 33, 34, 34, 34, 34, 34, 35, 403, - 403, 37, 36, 38, 38, 38, 38, 38, 403, 40, - 41, 403, 403, 403, 403, 403, 403, 29, 30, 34, - 34, 34, 34, 34, 403, 403, 37, 42, 33, 33, - - 33, 33, 33, 53, 403, 43, 403, 48, 403, 403, - 52, 47, 44, 49, 403, 403, 46, 34, 34, 34, - 34, 34, 45, 51, 51, 51, 51, 51, 37, 403, - 38, 38, 38, 38, 38, 54, 61, 403, 403, 403, - 403, 55, 403, 59, 57, 403, 403, 56, 403, 58, - 51, 51, 51, 51, 51, 403, 64, 63, 403, 403, - 403, 403, 67, 71, 72, 73, 76, 60, 68, 66, - 65, 403, 403, 403, 403, 403, 403, 77, 403, 403, - 403, 78, 403, 403, 69, 403, 70, 403, 403, 86, - 403, 403, 403, 79, 403, 83, 403, 87, 403, 403, - - 74, 82, 403, 97, 403, 81, 80, 88, 89, 91, - 403, 403, 96, 403, 403, 84, 403, 90, 104, 105, - 101, 99, 403, 403, 92, 94, 93, 109, 403, 98, - 100, 103, 102, 106, 403, 403, 403, 403, 403, 403, - 108, 403, 403, 113, 112, 403, 107, 403, 114, 403, - 403, 403, 403, 111, 121, 122, 123, 403, 403, 403, - 110, 403, 403, 403, 115, 118, 403, 126, 119, 127, - 403, 129, 120, 403, 128, 116, 124, 117, 134, 403, - 131, 403, 130, 403, 132, 403, 403, 135, 125, 136, - 133, 139, 403, 138, 140, 403, 403, 403, 403, 403, - - 403, 403, 137, 403, 142, 403, 141, 150, 151, 403, - 143, 403, 403, 403, 403, 403, 403, 403, 403, 148, - 403, 147, 144, 145, 149, 146, 156, 154, 157, 152, - 403, 155, 161, 162, 164, 165, 403, 153, 403, 159, - 169, 158, 171, 403, 403, 403, 403, 403, 403, 403, - 403, 170, 160, 163, 403, 166, 167, 403, 173, 172, - 174, 403, 403, 403, 175, 403, 403, 168, 403, 403, - 176, 403, 403, 403, 178, 179, 194, 195, 403, 181, - 180, 403, 403, 184, 185, 403, 177, 183, 403, 182, - 186, 403, 190, 188, 192, 403, 189, 403, 187, 403, - - 191, 193, 196, 197, 198, 199, 403, 403, 403, 403, - 403, 403, 403, 403, 403, 203, 202, 403, 403, 403, - 200, 201, 403, 403, 403, 403, 204, 403, 205, 206, - 403, 403, 211, 403, 213, 215, 403, 403, 403, 214, - 207, 208, 209, 210, 212, 216, 403, 217, 403, 222, - 218, 219, 220, 221, 403, 223, 225, 403, 227, 403, - 224, 228, 403, 403, 229, 403, 234, 230, 226, 232, - 231, 403, 403, 233, 403, 403, 403, 235, 403, 403, - 403, 403, 403, 237, 403, 403, 403, 403, 236, 247, - 248, 249, 403, 403, 403, 403, 240, 242, 238, 241, - - 403, 403, 403, 239, 252, 245, 244, 403, 403, 250, - 260, 261, 246, 243, 254, 251, 403, 403, 259, 403, - 403, 403, 403, 403, 403, 253, 255, 256, 257, 263, - 264, 403, 262, 258, 403, 403, 271, 403, 403, 272, - 273, 403, 403, 266, 265, 267, 274, 403, 403, 270, - 275, 403, 281, 268, 403, 269, 403, 403, 282, 285, - 286, 403, 403, 278, 403, 276, 277, 403, 403, 280, - 403, 403, 403, 403, 403, 403, 403, 297, 403, 279, - 403, 403, 403, 283, 284, 287, 298, 403, 403, 288, - 403, 403, 295, 403, 403, 403, 403, 403, 289, 301, - - 293, 290, 292, 291, 294, 296, 299, 403, 300, 302, - 403, 403, 403, 307, 403, 403, 309, 306, 403, 403, - 310, 305, 303, 403, 403, 312, 304, 403, 403, 403, - 403, 308, 314, 403, 403, 311, 316, 403, 403, 403, - 403, 317, 329, 330, 331, 319, 322, 313, 315, 318, - 324, 326, 403, 403, 323, 321, 403, 328, 403, 403, - 403, 320, 325, 403, 403, 403, 403, 403, 403, 327, - 342, 343, 344, 333, 334, 332, 403, 403, 337, 403, - 338, 347, 348, 403, 349, 403, 335, 336, 339, 403, - 403, 340, 341, 345, 403, 346, 403, 403, 403, 350, - - 351, 354, 403, 360, 403, 403, 403, 361, 403, 362, - 403, 403, 403, 403, 403, 403, 359, 352, 355, 353, - 403, 403, 356, 403, 357, 403, 403, 403, 364, 403, - 358, 403, 403, 367, 403, 377, 378, 379, 366, 403, - 369, 403, 403, 363, 403, 39, 403, 365, 370, 368, - 373, 374, 372, 375, 403, 385, 403, 371, 403, 380, - 381, 376, 403, 384, 403, 388, 389, 390, 382, 391, - 386, 403, 387, 383, 403, 403, 392, 403, 403, 393, - 394, 403, 403, 400, 403, 403, 397, 401, 395, 402, - 396, 403, 403, 403, 403, 403, 403, 403, 403, 403, - - 403, 403, 403, 398, 403, 399, 403, 403, 403, 403, - 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, - 403, 403, 403, 403, 403, 403, 403, 403, 403, 95, - 85, 403, 403, 403, 75, 403, 62, 403, 50, 28, - 403, 31, 28, 403, 3, 403, 403, 403, 403, 403, - 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, - 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, - 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, - 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, - 403, 403, 403, 403, 403, 403, 403, 403, 403 - - } ; - -static yyconst short int yy_chk[900] = - { 0, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 7, 7, 12, 21, 12, 12, - 12, 12, 12, 14, 14, 14, 14, 14, 15, 19, - 20, 16, 15, 16, 16, 16, 16, 16, 22, 19, - 20, 23, 24, 25, 26, 41, 27, 30, 30, 32, - 32, 32, 32, 32, 40, 49, 33, 21, 33, 33, - - 33, 33, 33, 41, 42, 22, 43, 26, 44, 45, - 40, 25, 22, 27, 46, 47, 24, 34, 34, 34, - 34, 34, 23, 37, 37, 37, 37, 37, 38, 48, - 38, 38, 38, 38, 38, 42, 49, 52, 53, 54, - 56, 43, 55, 47, 45, 57, 59, 44, 60, 46, - 51, 51, 51, 51, 51, 64, 53, 52, 63, 65, - 66, 61, 56, 61, 61, 61, 63, 48, 57, 55, - 54, 67, 68, 70, 69, 74, 76, 64, 77, 78, - 80, 65, 79, 81, 59, 82, 60, 83, 84, 76, - 86, 87, 88, 66, 89, 70, 90, 77, 92, 96, - - 61, 69, 93, 87, 94, 68, 67, 78, 79, 81, - 98, 97, 86, 99, 100, 74, 102, 80, 96, 97, - 92, 89, 103, 101, 82, 84, 83, 101, 104, 88, - 90, 94, 93, 98, 105, 106, 107, 108, 111, 109, - 100, 110, 115, 104, 103, 113, 99, 114, 105, 116, - 120, 112, 121, 102, 112, 112, 112, 117, 118, 119, - 101, 122, 124, 123, 106, 109, 125, 113, 110, 114, - 126, 116, 111, 127, 115, 107, 112, 108, 121, 128, - 118, 129, 117, 130, 119, 131, 132, 122, 112, 123, - 120, 126, 133, 125, 127, 137, 141, 139, 140, 138, - - 142, 145, 124, 143, 129, 146, 128, 139, 140, 144, - 129, 147, 148, 149, 152, 150, 151, 156, 157, 137, - 159, 133, 130, 131, 138, 132, 145, 143, 146, 141, - 155, 144, 150, 151, 155, 155, 160, 142, 164, 148, - 156, 147, 159, 161, 165, 162, 166, 167, 168, 169, - 170, 157, 149, 152, 172, 155, 155, 171, 161, 160, - 162, 175, 176, 178, 164, 180, 177, 155, 179, 181, - 165, 182, 183, 184, 167, 168, 184, 184, 186, 170, - 169, 187, 188, 175, 176, 189, 166, 172, 191, 171, - 177, 192, 180, 179, 182, 194, 179, 193, 178, 185, - - 181, 183, 185, 185, 185, 186, 195, 196, 197, 198, - 199, 201, 202, 203, 200, 191, 189, 211, 205, 206, - 187, 188, 207, 208, 209, 210, 192, 213, 193, 194, - 215, 214, 199, 212, 201, 203, 223, 224, 225, 202, - 195, 196, 197, 198, 200, 205, 222, 206, 232, 211, - 207, 208, 209, 210, 217, 212, 214, 218, 217, 219, - 213, 218, 220, 226, 219, 221, 224, 220, 215, 222, - 221, 233, 234, 223, 235, 237, 236, 225, 238, 239, - 240, 241, 244, 232, 243, 245, 242, 246, 226, 242, - 242, 242, 247, 248, 249, 251, 235, 237, 233, 236, - - 250, 255, 256, 234, 244, 240, 239, 252, 253, 242, - 252, 252, 241, 238, 246, 243, 257, 258, 251, 260, - 259, 261, 262, 267, 266, 245, 247, 248, 249, 255, - 256, 263, 253, 250, 264, 265, 263, 268, 269, 264, - 265, 270, 274, 258, 257, 259, 266, 275, 276, 262, - 267, 278, 276, 260, 277, 261, 280, 279, 277, 280, - 280, 284, 283, 270, 285, 268, 269, 286, 287, 275, - 291, 288, 289, 293, 296, 299, 290, 293, 292, 274, - 300, 295, 294, 278, 279, 283, 294, 301, 302, 284, - 303, 304, 291, 305, 306, 307, 308, 309, 285, 296, - - 289, 286, 288, 287, 290, 292, 295, 310, 295, 299, - 311, 312, 313, 304, 314, 315, 306, 303, 316, 317, - 307, 302, 300, 318, 319, 309, 301, 320, 321, 323, - 322, 305, 311, 324, 325, 308, 313, 327, 328, 326, - 329, 314, 326, 326, 326, 316, 319, 310, 312, 315, - 321, 323, 330, 331, 320, 318, 332, 325, 333, 346, - 334, 317, 322, 335, 336, 342, 343, 337, 338, 324, - 337, 337, 337, 328, 329, 327, 339, 340, 332, 341, - 333, 339, 340, 344, 341, 345, 330, 331, 334, 354, - 350, 335, 336, 338, 351, 338, 352, 353, 355, 342, - - 343, 346, 356, 355, 357, 358, 359, 356, 363, 357, - 364, 365, 366, 367, 368, 369, 354, 344, 350, 345, - 370, 376, 351, 371, 352, 374, 377, 381, 359, 372, - 353, 373, 375, 365, 378, 375, 375, 375, 364, 379, - 367, 380, 382, 358, 383, 404, 388, 363, 368, 366, - 371, 372, 370, 373, 389, 381, 390, 369, 394, 376, - 377, 374, 384, 380, 385, 384, 384, 384, 378, 385, - 382, 386, 383, 379, 387, 395, 386, 396, 397, 387, - 388, 402, 398, 397, 399, 401, 394, 398, 389, 399, - 390, 400, 393, 392, 391, 362, 361, 360, 349, 348, - - 347, 298, 297, 395, 282, 396, 281, 273, 272, 271, - 254, 231, 230, 229, 228, 227, 216, 204, 190, 174, - 173, 163, 158, 154, 153, 136, 135, 134, 91, 85, - 75, 73, 72, 71, 62, 58, 50, 39, 31, 28, - 18, 8, 5, 3, 403, 403, 403, 403, 403, 403, - 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, - 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, - 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, - 403, 403, 403, 403, 403, 403, 403, 403, 403, 403, - 403, 403, 403, 403, 403, 403, 403, 403, 403 - - } ; - -static yy_state_type yy_last_accepting_state; -static char *yy_last_accepting_cpos; - -/* The intent behind this definition is that it'll catch - * any uses of REJECT which flex missed. - */ -#define REJECT reject_used_but_not_detected -#define yymore() yymore_used_but_not_detected -#define YY_MORE_ADJ 0 -#define YY_RESTORE_YY_MORE_OFFSET -char *yytext; -#line 1 "ts1.0_tokens.l" -#define INITIAL 0 -/* definitions */ -#line 7 "ts1.0_tokens.l" -#include -#include "ts1.0_inst.h" -#include "ts1.0_inst_list.h" -#include "_ts1.0_parser.h" -#ifdef _WIN32 -# include -#endif -#include "nvparse_errors.h" -#include "nvparse_externs.h" -#define YY_NO_UNPUT - -#define YY_INPUT(buf,result,max_size) \ -{ \ - int c = *myin++; \ - result = (c == 0) ? YY_NULL : (buf[0] = c, 1); \ -} - -#define YY_ALWAYS_INTERACTIVE 1 - -/* end of definitions */ -#line 740 "_ts1.0_lexer.cpp" - -/* Macros after this point can all be overridden by user definitions in - * section 1. - */ - -#ifndef YY_SKIP_YYWRAP -#ifdef __cplusplus -extern "C" int yywrap YY_PROTO(( void )); -#else -extern int yywrap YY_PROTO(( void )); -#endif -#endif - -#ifndef YY_NO_UNPUT -static void yyunput YY_PROTO(( int c, char *buf_ptr )); -#endif - -#ifndef yytext_ptr -static void yy_flex_strncpy YY_PROTO(( char *, yyconst char *, int )); -#endif - -#ifdef YY_NEED_STRLEN -static int yy_flex_strlen YY_PROTO(( yyconst char * )); -#endif - -#ifndef YY_NO_INPUT -#ifdef __cplusplus -static int yyinput YY_PROTO(( void )); -#else -static int input YY_PROTO(( void )); -#endif -#endif - -#if YY_STACK_USED -static int yy_start_stack_ptr = 0; -static int yy_start_stack_depth = 0; -static int *yy_start_stack = 0; -#ifndef YY_NO_PUSH_STATE -static void yy_push_state YY_PROTO(( int new_state )); -#endif -#ifndef YY_NO_POP_STATE -static void yy_pop_state YY_PROTO(( void )); -#endif -#ifndef YY_NO_TOP_STATE -static int yy_top_state YY_PROTO(( void )); -#endif - -#else -#define YY_NO_PUSH_STATE 1 -#define YY_NO_POP_STATE 1 -#define YY_NO_TOP_STATE 1 -#endif - -#ifdef YY_MALLOC_DECL -YY_MALLOC_DECL -#else -#if __STDC__ -#ifndef __cplusplus -#include -#endif -#else -/* Just try to get by without declaring the routines. This will fail - * miserably on non-ANSI systems for which sizeof(size_t) != sizeof(int) - * or sizeof(void*) != sizeof(int). - */ -#endif -#endif - -/* Amount of stuff to slurp up with each read. */ -#ifndef YY_READ_BUF_SIZE -#define YY_READ_BUF_SIZE 8192 -#endif - -/* Copy whatever the last rule matched to the standard output. */ - -#ifndef ECHO -/* This used to be an fputs(), but since the string might contain NUL's, - * we now use fwrite(). - */ -#define ECHO (void) fwrite( yytext, yyleng, 1, yyout ) -#endif - -/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, - * is returned in "result". - */ -#ifndef YY_INPUT -#define YY_INPUT(buf,result,max_size) \ - if ( yy_current_buffer->yy_is_interactive ) \ - { \ - int c = '*', n; \ - for ( n = 0; n < max_size && \ - (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ - buf[n] = (char) c; \ - if ( c == '\n' ) \ - buf[n++] = (char) c; \ - if ( c == EOF && ferror( yyin ) ) \ - YY_FATAL_ERROR( "input in flex scanner failed" ); \ - result = n; \ - } \ - else \ - { \ - errno=0; \ - while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ - { \ - if( errno != EINTR) \ - { \ - YY_FATAL_ERROR( "input in flex scanner failed" ); \ - break; \ - } \ - errno=0; \ - clearerr(yyin); \ - } \ - } -#endif - -/* No semi-colon after return; correct usage is to write "yyterminate();" - - * we don't want an extra ';' after the "return" because that will cause - * some compilers to complain about unreachable statements. - */ -#ifndef yyterminate -#define yyterminate() return YY_NULL -#endif - -/* Number of entries by which start-condition stack grows. */ -#ifndef YY_START_STACK_INCR -#define YY_START_STACK_INCR 25 -#endif - -/* Report a fatal error. */ -#ifndef YY_FATAL_ERROR -#define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) -#endif - -/* Default declaration of generated scanner - a define so the user can - * easily add parameters. - */ -#ifndef YY_DECL -#define YY_DECL int yylex YY_PROTO(( void )) -#endif - -/* Code executed at the beginning of each rule, after yytext and yyleng - * have been set up. - */ -#ifndef YY_USER_ACTION -#define YY_USER_ACTION -#endif - -/* Code executed at the end of each rule. */ -#ifndef YY_BREAK -#define YY_BREAK break; -#endif - -#define YY_RULE_SETUP \ - YY_USER_ACTION - -YY_DECL - { - yy_state_type yy_current_state; - char *yy_cp, *yy_bp; - int yy_act; - -#line 28 "ts1.0_tokens.l" - - -#line 905 "_ts1.0_lexer.cpp" - - if ( yy_init ) - { - yy_init = 0; - -#ifdef YY_USER_INIT - YY_USER_INIT; -#endif - - if ( ! yy_start ) - yy_start = 1; /* first start state */ - - if ( ! yyin ) - yyin = stdin; - - if ( ! yyout ) - yyout = stdout; - - if ( ! yy_current_buffer ) - yy_current_buffer = - yy_create_buffer( yyin, YY_BUF_SIZE ); - - yy_load_buffer_state(); - } - - while ( 1 ) /* loops until end-of-file is reached */ - { - yy_cp = yy_c_buf_p; - - /* Support of yytext. */ - *yy_cp = yy_hold_char; - - /* yy_bp points to the position in yy_ch_buf of the start of - * the current run. - */ - yy_bp = yy_cp; - - yy_current_state = yy_start; -yy_match: - do - { - YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; - if ( yy_accept[yy_current_state] ) - { - yy_last_accepting_state = yy_current_state; - yy_last_accepting_cpos = yy_cp; - } - while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) - { - yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 404 ) - yy_c = yy_meta[(unsigned int) yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; - ++yy_cp; - } - while ( yy_base[yy_current_state] != 845 ); - -yy_find_action: - yy_act = yy_accept[yy_current_state]; - if ( yy_act == 0 ) - { /* have to back up */ - yy_cp = yy_last_accepting_cpos; - yy_current_state = yy_last_accepting_state; - yy_act = yy_accept[yy_current_state]; - } - - YY_DO_BEFORE_ACTION; - - -do_action: /* This label is used only to access EOF actions. */ - - - switch ( yy_act ) - { /* beginning of action switch */ - case 0: /* must back up */ - /* undo the effects of YY_DO_BEFORE_ACTION */ - *yy_cp = yy_hold_char; - yy_cp = yy_last_accepting_cpos; - yy_current_state = yy_last_accepting_state; - goto yy_find_action; - -case 1: -YY_RULE_SETUP -#line 30 "ts1.0_tokens.l" -{ - A: - switch (yyinput()) { - case '*': goto B; - case 0: errors.set("end-of-file in comment", line_number); break; - case '\n': line_number++; - default: goto A; - } - B: - switch (yyinput()) { - case '*': goto B; - case '/': break; - case 0: errors.set("end-of-file in comment", line_number); break; - case '\n': line_number++; - default: goto A; - } - } - YY_BREAK -case 2: -YY_RULE_SETUP -#line 48 "ts1.0_tokens.l" -{ - char ch; - while ((ch = yyinput()) != '\n'); - if (ch == '\n') line_number++; - } - YY_BREAK -case 3: -YY_RULE_SETUP -#line 54 "ts1.0_tokens.l" -{ - char ch; - while ((ch = yyinput()) != '\n'); - if (ch == '\n') line_number++; - } - YY_BREAK -case 4: -YY_RULE_SETUP -#line 60 "ts1.0_tokens.l" -return(openParen); - YY_BREAK -case 5: -YY_RULE_SETUP -#line 61 "ts1.0_tokens.l" -return(closeParen); - YY_BREAK -case 6: -YY_RULE_SETUP -#line 62 "ts1.0_tokens.l" -return(semicolon); - YY_BREAK -case 7: -YY_RULE_SETUP -#line 63 "ts1.0_tokens.l" -return(comma); - YY_BREAK -case 8: -YY_RULE_SETUP -#line 65 "ts1.0_tokens.l" -{ /* eat header */ } - YY_BREAK -case 9: -YY_RULE_SETUP -#line 67 "ts1.0_tokens.l" -{ - ts10_lval.fval = (float)0; - return(texVariable); - } - YY_BREAK -case 10: -YY_RULE_SETUP -#line 72 "ts1.0_tokens.l" -{ - ts10_lval.fval = (float)1; - return(texVariable); - } - YY_BREAK -case 11: -YY_RULE_SETUP -#line 77 "ts1.0_tokens.l" -{ - ts10_lval.fval = (float)2; - return(texVariable); - } - YY_BREAK -case 12: -YY_RULE_SETUP -#line 82 "ts1.0_tokens.l" -return(expandString); - YY_BREAK -case 13: -YY_RULE_SETUP -#line 84 "ts1.0_tokens.l" -{ - ts10_lval.fval = (float)GL_GEQUAL; - return (gequal); - } - YY_BREAK -case 14: -YY_RULE_SETUP -#line 89 "ts1.0_tokens.l" -{ - ts10_lval.fval = (float)GL_LESS; - return(less); - } - YY_BREAK -case 15: -YY_RULE_SETUP -#line 94 "ts1.0_tokens.l" -return(nop); - YY_BREAK -case 16: -YY_RULE_SETUP -#line 95 "ts1.0_tokens.l" -return(texture_1d); - YY_BREAK -case 17: -YY_RULE_SETUP -#line 96 "ts1.0_tokens.l" -return(texture_2d); - YY_BREAK -case 18: -YY_RULE_SETUP -#line 97 "ts1.0_tokens.l" -return(texture_rectangle); - YY_BREAK -case 19: -YY_RULE_SETUP -#line 98 "ts1.0_tokens.l" -return(texture_3d); - YY_BREAK -case 20: -YY_RULE_SETUP -#line 99 "ts1.0_tokens.l" -return(texture_cube_map); - YY_BREAK -case 21: -YY_RULE_SETUP -#line 100 "ts1.0_tokens.l" -return(cull_fragment); - YY_BREAK -case 22: -YY_RULE_SETUP -#line 101 "ts1.0_tokens.l" -return(pass_through); - YY_BREAK -case 23: -YY_RULE_SETUP -#line 102 "ts1.0_tokens.l" -return(offset_2d_scale); - YY_BREAK -case 24: -YY_RULE_SETUP -#line 103 "ts1.0_tokens.l" -return(offset_2d); - YY_BREAK -case 25: -YY_RULE_SETUP -#line 104 "ts1.0_tokens.l" -return(offset_rectangle_scale); - YY_BREAK -case 26: -YY_RULE_SETUP -#line 105 "ts1.0_tokens.l" -return(offset_rectangle); - YY_BREAK -case 27: -YY_RULE_SETUP -#line 106 "ts1.0_tokens.l" -return(dependent_ar); - YY_BREAK -case 28: -YY_RULE_SETUP -#line 107 "ts1.0_tokens.l" -return(dependent_gb); - YY_BREAK -case 29: -YY_RULE_SETUP -#line 109 "ts1.0_tokens.l" -return(dot_product_2d_1of2); - YY_BREAK -case 30: -YY_RULE_SETUP -#line 110 "ts1.0_tokens.l" -return(dot_product_2d_2of2); - YY_BREAK -case 31: -YY_RULE_SETUP -#line 112 "ts1.0_tokens.l" -return(dot_product_rectangle_1of2); - YY_BREAK -case 32: -YY_RULE_SETUP -#line 113 "ts1.0_tokens.l" -return(dot_product_rectangle_2of2); - YY_BREAK -case 33: -YY_RULE_SETUP -#line 115 "ts1.0_tokens.l" -return(dot_product_depth_replace_1of2); - YY_BREAK -case 34: -YY_RULE_SETUP -#line 116 "ts1.0_tokens.l" -return(dot_product_depth_replace_2of2); - YY_BREAK -case 35: -YY_RULE_SETUP -#line 118 "ts1.0_tokens.l" -return(dot_product_3d_1of3); - YY_BREAK -case 36: -YY_RULE_SETUP -#line 119 "ts1.0_tokens.l" -return(dot_product_3d_2of3); - YY_BREAK -case 37: -YY_RULE_SETUP -#line 120 "ts1.0_tokens.l" -return(dot_product_3d_3of3); - YY_BREAK -case 38: -YY_RULE_SETUP -#line 122 "ts1.0_tokens.l" -return(dot_product_cube_map_1of3); - YY_BREAK -case 39: -YY_RULE_SETUP -#line 123 "ts1.0_tokens.l" -return(dot_product_cube_map_2of3); - YY_BREAK -case 40: -YY_RULE_SETUP -#line 124 "ts1.0_tokens.l" -return(dot_product_cube_map_3of3); - YY_BREAK -case 41: -YY_RULE_SETUP -#line 126 "ts1.0_tokens.l" -return(dot_product_reflect_cube_map_eye_from_qs_1of3); - YY_BREAK -case 42: -YY_RULE_SETUP -#line 127 "ts1.0_tokens.l" -return(dot_product_reflect_cube_map_eye_from_qs_2of3); - YY_BREAK -case 43: -YY_RULE_SETUP -#line 128 "ts1.0_tokens.l" -return(dot_product_reflect_cube_map_eye_from_qs_3of3); - YY_BREAK -case 44: -YY_RULE_SETUP -#line 130 "ts1.0_tokens.l" -return(dot_product_reflect_cube_map_const_eye_1of3); - YY_BREAK -case 45: -YY_RULE_SETUP -#line 131 "ts1.0_tokens.l" -return(dot_product_reflect_cube_map_const_eye_2of3); - YY_BREAK -case 46: -YY_RULE_SETUP -#line 132 "ts1.0_tokens.l" -return(dot_product_reflect_cube_map_const_eye_3of3); - YY_BREAK -case 47: -YY_RULE_SETUP -#line 134 "ts1.0_tokens.l" -return(dot_product_cube_map_and_reflect_cube_map_eye_from_qs_1of3); - YY_BREAK -case 48: -YY_RULE_SETUP -#line 135 "ts1.0_tokens.l" -return(dot_product_cube_map_and_reflect_cube_map_eye_from_qs_2of3); - YY_BREAK -case 49: -YY_RULE_SETUP -#line 136 "ts1.0_tokens.l" -return(dot_product_cube_map_and_reflect_cube_map_eye_from_qs_3of3); - YY_BREAK -case 50: -YY_RULE_SETUP -#line 138 "ts1.0_tokens.l" -return(dot_product_cube_map_and_reflect_cube_map_const_eye_1of3); - YY_BREAK -case 51: -YY_RULE_SETUP -#line 139 "ts1.0_tokens.l" -return(dot_product_cube_map_and_reflect_cube_map_const_eye_2of3); - YY_BREAK -case 52: -YY_RULE_SETUP -#line 140 "ts1.0_tokens.l" -return(dot_product_cube_map_and_reflect_cube_map_const_eye_3of3); - YY_BREAK -case 53: -YY_RULE_SETUP -#line 142 "ts1.0_tokens.l" -{ - ts10_lval.fval = (float)atof(yytext); - return(floatValue); - } - YY_BREAK -case 54: -YY_RULE_SETUP -#line 147 "ts1.0_tokens.l" -{ - ts10_lval.fval = (float)atof(yytext); - return(floatValue); - } - YY_BREAK -case 55: -YY_RULE_SETUP -#line 152 "ts1.0_tokens.l" -{ - ts10_lval.fval = (float)atof(yytext); - return(floatValue); - } - YY_BREAK -case 56: -YY_RULE_SETUP -#line 157 "ts1.0_tokens.l" -{ - line_number++; - } - YY_BREAK -case 57: -YY_RULE_SETUP -#line 161 "ts1.0_tokens.l" -{} - YY_BREAK -case 58: -YY_RULE_SETUP -#line 163 "ts1.0_tokens.l" -{ - errors.set("unrecognized token", line_number); - } - YY_BREAK -case 59: -YY_RULE_SETUP -#line 168 "ts1.0_tokens.l" -ECHO; - YY_BREAK -#line 1335 "_ts1.0_lexer.cpp" -case YY_STATE_EOF(INITIAL): - yyterminate(); - - case YY_END_OF_BUFFER: - { - /* Amount of text matched not including the EOB char. */ - int yy_amount_of_matched_text = (int) (yy_cp - yytext_ptr) - 1; - - /* Undo the effects of YY_DO_BEFORE_ACTION. */ - *yy_cp = yy_hold_char; - YY_RESTORE_YY_MORE_OFFSET - - if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_NEW ) - { - /* We're scanning a new file or input source. It's - * possible that this happened because the user - * just pointed yyin at a new source and called - * yylex(). If so, then we have to assure - * consistency between yy_current_buffer and our - * globals. Here is the right place to do so, because - * this is the first action (other than possibly a - * back-up) that will match for the new input source. - */ - yy_n_chars = yy_current_buffer->yy_n_chars; - yy_current_buffer->yy_input_file = yyin; - yy_current_buffer->yy_buffer_status = YY_BUFFER_NORMAL; - } - - /* Note that here we test for yy_c_buf_p "<=" to the position - * of the first EOB in the buffer, since yy_c_buf_p will - * already have been incremented past the NUL character - * (since all states make transitions on EOB to the - * end-of-buffer state). Contrast this with the test - * in input(). - */ - if ( yy_c_buf_p <= &yy_current_buffer->yy_ch_buf[yy_n_chars] ) - { /* This was really a NUL. */ - yy_state_type yy_next_state; - - yy_c_buf_p = yytext_ptr + yy_amount_of_matched_text; - - yy_current_state = yy_get_previous_state(); - - /* Okay, we're now positioned to make the NUL - * transition. We couldn't have - * yy_get_previous_state() go ahead and do it - * for us because it doesn't know how to deal - * with the possibility of jamming (and we don't - * want to build jamming into it because then it - * will run more slowly). - */ - - yy_next_state = yy_try_NUL_trans( yy_current_state ); - - yy_bp = yytext_ptr + YY_MORE_ADJ; - - if ( yy_next_state ) - { - /* Consume the NUL. */ - yy_cp = ++yy_c_buf_p; - yy_current_state = yy_next_state; - goto yy_match; - } - - else - { - yy_cp = yy_c_buf_p; - goto yy_find_action; - } - } - - else switch ( yy_get_next_buffer() ) - { - case EOB_ACT_END_OF_FILE: - { - yy_did_buffer_switch_on_eof = 0; - - if ( yywrap() ) - { - /* Note: because we've taken care in - * yy_get_next_buffer() to have set up - * yytext, we can now set up - * yy_c_buf_p so that if some total - * hoser (like flex itself) wants to - * call the scanner after we return the - * YY_NULL, it'll still work - another - * YY_NULL will get returned. - */ - yy_c_buf_p = yytext_ptr + YY_MORE_ADJ; - - yy_act = YY_STATE_EOF(YY_START); - goto do_action; - } - - else - { - if ( ! yy_did_buffer_switch_on_eof ) - YY_NEW_FILE; - } - break; - } - - case EOB_ACT_CONTINUE_SCAN: - yy_c_buf_p = - yytext_ptr + yy_amount_of_matched_text; - - yy_current_state = yy_get_previous_state(); - - yy_cp = yy_c_buf_p; - yy_bp = yytext_ptr + YY_MORE_ADJ; - goto yy_match; - - case EOB_ACT_LAST_MATCH: - yy_c_buf_p = - &yy_current_buffer->yy_ch_buf[yy_n_chars]; - - yy_current_state = yy_get_previous_state(); - - yy_cp = yy_c_buf_p; - yy_bp = yytext_ptr + YY_MORE_ADJ; - goto yy_find_action; - } - break; - } - - default: - YY_FATAL_ERROR( - "fatal flex scanner internal error--no action found" ); - } /* end of action switch */ - } /* end of scanning one token */ - } /* end of yylex */ - - -/* yy_get_next_buffer - try to read in a new buffer - * - * Returns a code representing an action: - * EOB_ACT_LAST_MATCH - - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position - * EOB_ACT_END_OF_FILE - end of file - */ - -static int yy_get_next_buffer() - { - char *dest = yy_current_buffer->yy_ch_buf; - char *source = yytext_ptr; - int number_to_move, i; - int ret_val; - - if ( yy_c_buf_p > &yy_current_buffer->yy_ch_buf[yy_n_chars + 1] ) - YY_FATAL_ERROR( - "fatal flex scanner internal error--end of buffer missed" ); - - if ( yy_current_buffer->yy_fill_buffer == 0 ) - { /* Don't try to fill the buffer, so this is an EOF. */ - if ( yy_c_buf_p - yytext_ptr - YY_MORE_ADJ == 1 ) - { - /* We matched a single character, the EOB, so - * treat this as a final EOF. - */ - return EOB_ACT_END_OF_FILE; - } - - else - { - /* We matched some text prior to the EOB, first - * process it. - */ - return EOB_ACT_LAST_MATCH; - } - } - - /* Try to read more data. */ - - /* First move last chars to start of buffer. */ - number_to_move = (int) (yy_c_buf_p - yytext_ptr) - 1; - - for ( i = 0; i < number_to_move; ++i ) - *(dest++) = *(source++); - - if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_EOF_PENDING ) - /* don't do the read, it's not guaranteed to return an EOF, - * just force an EOF - */ - yy_current_buffer->yy_n_chars = yy_n_chars = 0; - - else - { - int num_to_read = - yy_current_buffer->yy_buf_size - number_to_move - 1; - - while ( num_to_read <= 0 ) - { /* Not enough room in the buffer - grow it. */ -#ifdef YY_USES_REJECT - YY_FATAL_ERROR( -"input buffer overflow, can't enlarge buffer because scanner uses REJECT" ); -#else - - /* just a shorter name for the current buffer */ - YY_BUFFER_STATE b = yy_current_buffer; - - int yy_c_buf_p_offset = - (int) (yy_c_buf_p - b->yy_ch_buf); - - if ( b->yy_is_our_buffer ) - { - int new_size = b->yy_buf_size * 2; - - if ( new_size <= 0 ) - b->yy_buf_size += b->yy_buf_size / 8; - else - b->yy_buf_size *= 2; - - b->yy_ch_buf = (char *) - /* Include room in for 2 EOB chars. */ - yy_flex_realloc( (void *) b->yy_ch_buf, - b->yy_buf_size + 2 ); - } - else - /* Can't grow it, we don't own it. */ - b->yy_ch_buf = 0; - - if ( ! b->yy_ch_buf ) - YY_FATAL_ERROR( - "fatal error - scanner input buffer overflow" ); - - yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; - - num_to_read = yy_current_buffer->yy_buf_size - - number_to_move - 1; -#endif - } - - if ( num_to_read > YY_READ_BUF_SIZE ) - num_to_read = YY_READ_BUF_SIZE; - - /* Read in more data. */ - YY_INPUT( (&yy_current_buffer->yy_ch_buf[number_to_move]), - yy_n_chars, num_to_read ); - - yy_current_buffer->yy_n_chars = yy_n_chars; - } - - if ( yy_n_chars == 0 ) - { - if ( number_to_move == YY_MORE_ADJ ) - { - ret_val = EOB_ACT_END_OF_FILE; - yyrestart( yyin ); - } - - else - { - ret_val = EOB_ACT_LAST_MATCH; - yy_current_buffer->yy_buffer_status = - YY_BUFFER_EOF_PENDING; - } - } - - else - ret_val = EOB_ACT_CONTINUE_SCAN; - - yy_n_chars += number_to_move; - yy_current_buffer->yy_ch_buf[yy_n_chars] = YY_END_OF_BUFFER_CHAR; - yy_current_buffer->yy_ch_buf[yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; - - yytext_ptr = &yy_current_buffer->yy_ch_buf[0]; - - return ret_val; - } - - -/* yy_get_previous_state - get the state just before the EOB char was reached */ - -static yy_state_type yy_get_previous_state() - { - yy_state_type yy_current_state; - char *yy_cp; - - yy_current_state = yy_start; - - for ( yy_cp = yytext_ptr + YY_MORE_ADJ; yy_cp < yy_c_buf_p; ++yy_cp ) - { - YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); - if ( yy_accept[yy_current_state] ) - { - yy_last_accepting_state = yy_current_state; - yy_last_accepting_cpos = yy_cp; - } - while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) - { - yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 404 ) - yy_c = yy_meta[(unsigned int) yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; - } - - return yy_current_state; - } - - -/* yy_try_NUL_trans - try to make a transition on the NUL character - * - * synopsis - * next_state = yy_try_NUL_trans( current_state ); - */ - -#ifdef YY_USE_PROTOS -static yy_state_type yy_try_NUL_trans( yy_state_type yy_current_state ) -#else -static yy_state_type yy_try_NUL_trans( yy_current_state ) -yy_state_type yy_current_state; -#endif - { - int yy_is_jam; - char *yy_cp = yy_c_buf_p; - - YY_CHAR yy_c = 1; - if ( yy_accept[yy_current_state] ) - { - yy_last_accepting_state = yy_current_state; - yy_last_accepting_cpos = yy_cp; - } - while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) - { - yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 404 ) - yy_c = yy_meta[(unsigned int) yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; - yy_is_jam = (yy_current_state == 403); - - return yy_is_jam ? 0 : yy_current_state; - } - - -#ifndef YY_NO_UNPUT -#ifdef YY_USE_PROTOS -static void yyunput( int c, char *yy_bp ) -#else -static void yyunput( c, yy_bp ) -int c; -char *yy_bp; -#endif - { - char *yy_cp = yy_c_buf_p; - - /* undo effects of setting up yytext */ - *yy_cp = yy_hold_char; - - if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 ) - { /* need to shift things up to make room */ - /* +2 for EOB chars. */ - int number_to_move = yy_n_chars + 2; - char *dest = &yy_current_buffer->yy_ch_buf[ - yy_current_buffer->yy_buf_size + 2]; - char *source = - &yy_current_buffer->yy_ch_buf[number_to_move]; - - while ( source > yy_current_buffer->yy_ch_buf ) - *--dest = *--source; - - yy_cp += (int) (dest - source); - yy_bp += (int) (dest - source); - yy_current_buffer->yy_n_chars = - yy_n_chars = yy_current_buffer->yy_buf_size; - - if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 ) - YY_FATAL_ERROR( "flex scanner push-back overflow" ); - } - - *--yy_cp = (char) c; - - - yytext_ptr = yy_bp; - yy_hold_char = *yy_cp; - yy_c_buf_p = yy_cp; - } -#endif /* ifndef YY_NO_UNPUT */ - - -#ifdef __cplusplus -static int yyinput() -#else -static int input() -#endif - { - int c; - - *yy_c_buf_p = yy_hold_char; - - if ( *yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) - { - /* yy_c_buf_p now points to the character we want to return. - * If this occurs *before* the EOB characters, then it's a - * valid NUL; if not, then we've hit the end of the buffer. - */ - if ( yy_c_buf_p < &yy_current_buffer->yy_ch_buf[yy_n_chars] ) - /* This was really a NUL. */ - *yy_c_buf_p = '\0'; - - else - { /* need more input */ - int offset = yy_c_buf_p - yytext_ptr; - ++yy_c_buf_p; - - switch ( yy_get_next_buffer() ) - { - case EOB_ACT_LAST_MATCH: - /* This happens because yy_g_n_b() - * sees that we've accumulated a - * token and flags that we need to - * try matching the token before - * proceeding. But for input(), - * there's no matching to consider. - * So convert the EOB_ACT_LAST_MATCH - * to EOB_ACT_END_OF_FILE. - */ - - /* Reset buffer status. */ - yyrestart( yyin ); - - /* fall through */ - - case EOB_ACT_END_OF_FILE: - { - if ( yywrap() ) - return EOF; - - if ( ! yy_did_buffer_switch_on_eof ) - YY_NEW_FILE; -#ifdef __cplusplus - return yyinput(); -#else - return input(); -#endif - } - - case EOB_ACT_CONTINUE_SCAN: - yy_c_buf_p = yytext_ptr + offset; - break; - } - } - } - - c = *(unsigned char *) yy_c_buf_p; /* cast for 8-bit char's */ - *yy_c_buf_p = '\0'; /* preserve yytext */ - yy_hold_char = *++yy_c_buf_p; - - - return c; - } - - -#ifdef YY_USE_PROTOS -void yyrestart( FILE *input_file ) -#else -void yyrestart( input_file ) -FILE *input_file; -#endif - { - if ( ! yy_current_buffer ) - yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); - - yy_init_buffer( yy_current_buffer, input_file ); - yy_load_buffer_state(); - } - - -#ifdef YY_USE_PROTOS -void yy_switch_to_buffer( YY_BUFFER_STATE new_buffer ) -#else -void yy_switch_to_buffer( new_buffer ) -YY_BUFFER_STATE new_buffer; -#endif - { - if ( yy_current_buffer == new_buffer ) - return; - - if ( yy_current_buffer ) - { - /* Flush out information for old buffer. */ - *yy_c_buf_p = yy_hold_char; - yy_current_buffer->yy_buf_pos = yy_c_buf_p; - yy_current_buffer->yy_n_chars = yy_n_chars; - } - - yy_current_buffer = new_buffer; - yy_load_buffer_state(); - - /* We don't actually know whether we did this switch during - * EOF (yywrap()) processing, but the only time this flag - * is looked at is after yywrap() is called, so it's safe - * to go ahead and always set it. - */ - yy_did_buffer_switch_on_eof = 1; - } - - -#ifdef YY_USE_PROTOS -void yy_load_buffer_state( void ) -#else -void yy_load_buffer_state() -#endif - { - yy_n_chars = yy_current_buffer->yy_n_chars; - yytext_ptr = yy_c_buf_p = yy_current_buffer->yy_buf_pos; - yyin = yy_current_buffer->yy_input_file; - yy_hold_char = *yy_c_buf_p; - } - - -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_create_buffer( FILE *file, int size ) -#else -YY_BUFFER_STATE yy_create_buffer( file, size ) -FILE *file; -int size; -#endif - { - YY_BUFFER_STATE b; - - b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) ); - if ( ! b ) - YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); - - b->yy_buf_size = size; - - /* yy_ch_buf has to be 2 characters longer than the size given because - * we need to put in 2 end-of-buffer characters. - */ - b->yy_ch_buf = (char *) yy_flex_alloc( b->yy_buf_size + 2 ); - if ( ! b->yy_ch_buf ) - YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); - - b->yy_is_our_buffer = 1; - - yy_init_buffer( b, file ); - - return b; - } - - -#ifdef YY_USE_PROTOS -void yy_delete_buffer( YY_BUFFER_STATE b ) -#else -void yy_delete_buffer( b ) -YY_BUFFER_STATE b; -#endif - { - if ( ! b ) - return; - - if ( b == yy_current_buffer ) - yy_current_buffer = (YY_BUFFER_STATE) 0; - - if ( b->yy_is_our_buffer ) - yy_flex_free( (void *) b->yy_ch_buf ); - - yy_flex_free( (void *) b ); - } - - -#ifndef _WIN32 -#include -#else -#ifndef YY_ALWAYS_INTERACTIVE -#ifndef YY_NEVER_INTERACTIVE -extern int isatty YY_PROTO(( int )); -#endif -#endif -#endif - -#ifdef YY_USE_PROTOS -void yy_init_buffer( YY_BUFFER_STATE b, FILE *file ) -#else -void yy_init_buffer( b, file ) -YY_BUFFER_STATE b; -FILE *file; -#endif - - - { - yy_flush_buffer( b ); - - b->yy_input_file = file; - b->yy_fill_buffer = 1; - -#if YY_ALWAYS_INTERACTIVE - b->yy_is_interactive = 1; -#else -#if YY_NEVER_INTERACTIVE - b->yy_is_interactive = 0; -#else - b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; -#endif -#endif - } - - -#ifdef YY_USE_PROTOS -void yy_flush_buffer( YY_BUFFER_STATE b ) -#else -void yy_flush_buffer( b ) -YY_BUFFER_STATE b; -#endif - - { - if ( ! b ) - return; - - b->yy_n_chars = 0; - - /* We always need two end-of-buffer characters. The first causes - * a transition to the end-of-buffer state. The second causes - * a jam in that state. - */ - b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; - b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; - - b->yy_buf_pos = &b->yy_ch_buf[0]; - - b->yy_at_bol = 1; - b->yy_buffer_status = YY_BUFFER_NEW; - - if ( b == yy_current_buffer ) - yy_load_buffer_state(); - } - - -#ifndef YY_NO_SCAN_BUFFER -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_scan_buffer( char *base, yy_size_t size ) -#else -YY_BUFFER_STATE yy_scan_buffer( base, size ) -char *base; -yy_size_t size; -#endif - { - YY_BUFFER_STATE b; - - if ( size < 2 || - base[size-2] != YY_END_OF_BUFFER_CHAR || - base[size-1] != YY_END_OF_BUFFER_CHAR ) - /* They forgot to leave room for the EOB's. */ - return 0; - - b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) ); - if ( ! b ) - YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); - - b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ - b->yy_buf_pos = b->yy_ch_buf = base; - b->yy_is_our_buffer = 0; - b->yy_input_file = 0; - b->yy_n_chars = b->yy_buf_size; - b->yy_is_interactive = 0; - b->yy_at_bol = 1; - b->yy_fill_buffer = 0; - b->yy_buffer_status = YY_BUFFER_NEW; - - yy_switch_to_buffer( b ); - - return b; - } -#endif - - -#ifndef YY_NO_SCAN_STRING -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_scan_string( yyconst char *yy_str ) -#else -YY_BUFFER_STATE yy_scan_string( yy_str ) -yyconst char *yy_str; -#endif - { - int len; - for ( len = 0; yy_str[len]; ++len ) - ; - - return yy_scan_bytes( yy_str, len ); - } -#endif - - -#ifndef YY_NO_SCAN_BYTES -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_scan_bytes( yyconst char *bytes, int len ) -#else -YY_BUFFER_STATE yy_scan_bytes( bytes, len ) -yyconst char *bytes; -int len; -#endif - { - YY_BUFFER_STATE b; - char *buf; - yy_size_t n; - int i; - - /* Get memory for full buffer, including space for trailing EOB's. */ - n = len + 2; - buf = (char *) yy_flex_alloc( n ); - if ( ! buf ) - YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); - - for ( i = 0; i < len; ++i ) - buf[i] = bytes[i]; - - buf[len] = buf[len+1] = YY_END_OF_BUFFER_CHAR; - - b = yy_scan_buffer( buf, n ); - if ( ! b ) - YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); - - /* It's okay to grow etc. this buffer, and we should throw it - * away when we're done. - */ - b->yy_is_our_buffer = 1; - - return b; - } -#endif - - -#ifndef YY_NO_PUSH_STATE -#ifdef YY_USE_PROTOS -static void yy_push_state( int new_state ) -#else -static void yy_push_state( new_state ) -int new_state; -#endif - { - if ( yy_start_stack_ptr >= yy_start_stack_depth ) - { - yy_size_t new_size; - - yy_start_stack_depth += YY_START_STACK_INCR; - new_size = yy_start_stack_depth * sizeof( int ); - - if ( ! yy_start_stack ) - yy_start_stack = (int *) yy_flex_alloc( new_size ); - - else - yy_start_stack = (int *) yy_flex_realloc( - (void *) yy_start_stack, new_size ); - - if ( ! yy_start_stack ) - YY_FATAL_ERROR( - "out of memory expanding start-condition stack" ); - } - - yy_start_stack[yy_start_stack_ptr++] = YY_START; - - BEGIN(new_state); - } -#endif - - -#ifndef YY_NO_POP_STATE -static void yy_pop_state() - { - if ( --yy_start_stack_ptr < 0 ) - YY_FATAL_ERROR( "start-condition stack underflow" ); - - BEGIN(yy_start_stack[yy_start_stack_ptr]); - } -#endif - - -#ifndef YY_NO_TOP_STATE -static int yy_top_state() - { - return yy_start_stack[yy_start_stack_ptr - 1]; - } -#endif - -#ifndef YY_EXIT_FAILURE -#define YY_EXIT_FAILURE 2 -#endif - -#ifdef YY_USE_PROTOS -static void yy_fatal_error( yyconst char msg[] ) -#else -static void yy_fatal_error( msg ) -char msg[]; -#endif - { - (void) fprintf( stderr, "%s\n", msg ); - exit( YY_EXIT_FAILURE ); - } - - - -/* Redefine yyless() so it works in section 3 code. */ - -#undef yyless -#define yyless(n) \ - do \ - { \ - /* Undo effects of setting up yytext. */ \ - yytext[yyleng] = yy_hold_char; \ - yy_c_buf_p = yytext + n; \ - yy_hold_char = *yy_c_buf_p; \ - *yy_c_buf_p = '\0'; \ - yyleng = n; \ - } \ - while ( 0 ) - - -/* Internal utility routines. */ - -#ifndef yytext_ptr -#ifdef YY_USE_PROTOS -static void yy_flex_strncpy( char *s1, yyconst char *s2, int n ) -#else -static void yy_flex_strncpy( s1, s2, n ) -char *s1; -yyconst char *s2; -int n; -#endif - { - int i; - for ( i = 0; i < n; ++i ) - s1[i] = s2[i]; - } -#endif - -#ifdef YY_NEED_STRLEN -#ifdef YY_USE_PROTOS -static int yy_flex_strlen( yyconst char *s ) -#else -static int yy_flex_strlen( s ) -yyconst char *s; -#endif - { - int n; - for ( n = 0; s[n]; ++n ) - ; - - return n; - } -#endif - - -#ifdef YY_USE_PROTOS -static void *yy_flex_alloc( yy_size_t size ) -#else -static void *yy_flex_alloc( size ) -yy_size_t size; -#endif - { - return (void *) malloc( size ); - } - -#ifdef YY_USE_PROTOS -static void *yy_flex_realloc( void *ptr, yy_size_t size ) -#else -static void *yy_flex_realloc( ptr, size ) -void *ptr; -yy_size_t size; -#endif - { - /* The cast to (char *) in the following accommodates both - * implementations that use char* generic pointers, and those - * that use void* generic pointers. It works with the latter - * because both ANSI C and C++ allow castless assignment from - * any pointer type to void*, and deal with argument conversions - * as though doing an assignment. - */ - return (void *) realloc( (char *) ptr, size ); - } - -#ifdef YY_USE_PROTOS -static void yy_flex_free( void *ptr ) -#else -static void yy_flex_free( ptr ) -void *ptr; -#endif - { - free( ptr ); - } - -#if YY_MAIN -int main() - { - yylex(); - return 0; - } -#endif -#line 168 "ts1.0_tokens.l" - - -bool ts10_init_more(); - -bool ts10_init(char* inputString) -{ - myin = inputString; - return ts10_init_more(); -} - - -#ifndef ts10_wrap -int ts10_wrap(void) -{ - return(1); -} -#endif diff --git a/RenderSystems/GL/src/nvparse/_ts1.0_parser.cpp b/RenderSystems/GL/src/nvparse/_ts1.0_parser.cpp deleted file mode 100644 index 0d123a73a2f..00000000000 --- a/RenderSystems/GL/src/nvparse/_ts1.0_parser.cpp +++ /dev/null @@ -1,2044 +0,0 @@ -/* A Bison parser, made by GNU Bison 3.0.2. */ - -/* Bison implementation for Yacc-like parsers in C - - Copyright (C) 1984, 1989-1990, 2000-2013 Free Software Foundation, Inc. - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . */ - -/* As a special exception, you may create a larger work that contains - part or all of the Bison parser skeleton and distribute that work - under terms of your choice, so long as that work isn't itself a - parser generator using the skeleton or a modified version thereof - as a parser skeleton. Alternatively, if you modify or redistribute - the parser skeleton itself, you may (at your option) remove this - special exception, which will cause the skeleton and the resulting - Bison output files to be licensed under the GNU General Public - License without this special exception. - - This special exception was added by the Free Software Foundation in - version 2.2 of Bison. */ - -/* C LALR(1) parser skeleton written by Richard Stallman, by - simplifying the original so-called "semantic" parser. */ - -/* All symbols defined below should begin with yy or YY, to avoid - infringing on user name space. This should be done even for local - variables, as they might otherwise be expanded by user macros. - There are some unavoidable exceptions within include files to - define necessary library symbols; they are noted "INFRINGES ON - USER NAME SPACE" below. */ - -/* Identify Bison output. */ -#define YYBISON 1 - -/* Bison version. */ -#define YYBISON_VERSION "3.0.2" - -/* Skeleton name. */ -#define YYSKELETON_NAME "yacc.c" - -/* Pure parsers. */ -#define YYPURE 0 - -/* Push parsers. */ -#define YYPUSH 0 - -/* Pull parsers. */ -#define YYPULL 1 - - -/* Substitute the variable and function names. */ -#define yyparse ts10_parse -#define yylex ts10_lex -#define yyerror ts10_error -#define yydebug ts10_debug -#define yynerrs ts10_nerrs - -#define yylval ts10_lval -#define yychar ts10_char - -/* Copy the first part of user declarations. */ -#line 3 "ts1.0_grammar.y" /* yacc.c:339 */ - -void yyerror(const char* s); -int yylex ( void ); - -#ifdef _WIN32 -# include -#endif -#include -#include -#include "ts1.0_inst.h" -#include "ts1.0_inst_list.h" -#include "nvparse_errors.h" -#include "nvparse_externs.h" - - -#line 90 "_ts1.0_parser.c" /* yacc.c:339 */ - -# ifndef YY_NULLPTR -# if defined __cplusplus && 201103L <= __cplusplus -# define YY_NULLPTR nullptr -# else -# define YY_NULLPTR 0 -# endif -# endif - -/* Enabling verbose error messages. */ -#ifdef YYERROR_VERBOSE -# undef YYERROR_VERBOSE -# define YYERROR_VERBOSE 1 -#else -# define YYERROR_VERBOSE 0 -#endif - -/* In a future release of Bison, this section will be replaced - by #include "_ts1.0_parser.h". */ -#ifndef YY_TS10_TS1_0_PARSER_H_INCLUDED -# define YY_TS10_TS1_0_PARSER_H_INCLUDED -/* Debug traces. */ -#ifndef YYDEBUG -# define YYDEBUG 0 -#endif -#if YYDEBUG -extern int ts10_debug; -#endif - -/* Token type. */ -#ifndef YYTOKENTYPE -# define YYTOKENTYPE - enum yytokentype - { - floatValue = 258, - gequal = 259, - less = 260, - texVariable = 261, - expandString = 262, - openParen = 263, - closeParen = 264, - semicolon = 265, - comma = 266, - nop = 267, - texture_1d = 268, - texture_2d = 269, - texture_rectangle = 270, - texture_3d = 271, - texture_cube_map = 272, - cull_fragment = 273, - pass_through = 274, - offset_2d_scale = 275, - offset_2d = 276, - offset_rectangle_scale = 277, - offset_rectangle = 278, - dependent_ar = 279, - dependent_gb = 280, - dot_product_2d_1of2 = 281, - dot_product_2d_2of2 = 282, - dot_product_rectangle_1of2 = 283, - dot_product_rectangle_2of2 = 284, - dot_product_depth_replace_1of2 = 285, - dot_product_depth_replace_2of2 = 286, - dot_product_3d_1of3 = 287, - dot_product_3d_2of3 = 288, - dot_product_3d_3of3 = 289, - dot_product_cube_map_1of3 = 290, - dot_product_cube_map_2of3 = 291, - dot_product_cube_map_3of3 = 292, - dot_product_reflect_cube_map_eye_from_qs_1of3 = 293, - dot_product_reflect_cube_map_eye_from_qs_2of3 = 294, - dot_product_reflect_cube_map_eye_from_qs_3of3 = 295, - dot_product_reflect_cube_map_const_eye_1of3 = 296, - dot_product_reflect_cube_map_const_eye_2of3 = 297, - dot_product_reflect_cube_map_const_eye_3of3 = 298, - dot_product_cube_map_and_reflect_cube_map_eye_from_qs_1of3 = 299, - dot_product_cube_map_and_reflect_cube_map_eye_from_qs_2of3 = 300, - dot_product_cube_map_and_reflect_cube_map_eye_from_qs_3of3 = 301, - dot_product_cube_map_and_reflect_cube_map_const_eye_1of3 = 302, - dot_product_cube_map_and_reflect_cube_map_const_eye_2of3 = 303, - dot_product_cube_map_and_reflect_cube_map_const_eye_3of3 = 304 - }; -#endif - -/* Value type. */ -#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED -typedef union YYSTYPE YYSTYPE; -union YYSTYPE -{ -#line 18 "ts1.0_grammar.y" /* yacc.c:355 */ - - float fval; - InstPtr inst; - InstListPtr instList; - MappedVariablePtr variable; - -#line 187 "_ts1.0_parser.c" /* yacc.c:355 */ -}; -# define YYSTYPE_IS_TRIVIAL 1 -# define YYSTYPE_IS_DECLARED 1 -#endif - - -extern YYSTYPE ts10_lval; - -int ts10_parse (void); - -#endif /* !YY_TS10_TS1_0_PARSER_H_INCLUDED */ - -/* Copy the second part of user declarations. */ - -#line 202 "_ts1.0_parser.c" /* yacc.c:358 */ - -#ifdef short -# undef short -#endif - -#ifdef YYTYPE_UINT8 -typedef YYTYPE_UINT8 yytype_uint8; -#else -typedef unsigned char yytype_uint8; -#endif - -#ifdef YYTYPE_INT8 -typedef YYTYPE_INT8 yytype_int8; -#else -typedef signed char yytype_int8; -#endif - -#ifdef YYTYPE_UINT16 -typedef YYTYPE_UINT16 yytype_uint16; -#else -typedef unsigned short int yytype_uint16; -#endif - -#ifdef YYTYPE_INT16 -typedef YYTYPE_INT16 yytype_int16; -#else -typedef short int yytype_int16; -#endif - -#ifndef YYSIZE_T -# ifdef __SIZE_TYPE__ -# define YYSIZE_T __SIZE_TYPE__ -# elif defined size_t -# define YYSIZE_T size_t -# elif ! defined YYSIZE_T -# include /* INFRINGES ON USER NAME SPACE */ -# define YYSIZE_T size_t -# else -# define YYSIZE_T unsigned int -# endif -#endif - -#define YYSIZE_MAXIMUM ((YYSIZE_T) -1) - -#ifndef YY_ -# if defined YYENABLE_NLS && YYENABLE_NLS -# if ENABLE_NLS -# include /* INFRINGES ON USER NAME SPACE */ -# define YY_(Msgid) dgettext ("bison-runtime", Msgid) -# endif -# endif -# ifndef YY_ -# define YY_(Msgid) Msgid -# endif -#endif - -#ifndef YY_ATTRIBUTE -# if (defined __GNUC__ \ - && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \ - || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C -# define YY_ATTRIBUTE(Spec) __attribute__(Spec) -# else -# define YY_ATTRIBUTE(Spec) /* empty */ -# endif -#endif - -#ifndef YY_ATTRIBUTE_PURE -# define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__)) -#endif - -#ifndef YY_ATTRIBUTE_UNUSED -# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__)) -#endif - -#if !defined _Noreturn \ - && (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112) -# if defined _MSC_VER && 1200 <= _MSC_VER -# define _Noreturn __declspec (noreturn) -# else -# define _Noreturn YY_ATTRIBUTE ((__noreturn__)) -# endif -#endif - -/* Suppress unused-variable warnings by "using" E. */ -#if ! defined lint || defined __GNUC__ -# define YYUSE(E) ((void) (E)) -#else -# define YYUSE(E) /* empty */ -#endif - -#if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ -/* Suppress an incorrect diagnostic about yylval being uninitialized. */ -# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ - _Pragma ("GCC diagnostic push") \ - _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\ - _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") -# define YY_IGNORE_MAYBE_UNINITIALIZED_END \ - _Pragma ("GCC diagnostic pop") -#else -# define YY_INITIAL_VALUE(Value) Value -#endif -#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN -# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN -# define YY_IGNORE_MAYBE_UNINITIALIZED_END -#endif -#ifndef YY_INITIAL_VALUE -# define YY_INITIAL_VALUE(Value) /* Nothing. */ -#endif - - -#if ! defined yyoverflow || YYERROR_VERBOSE - -/* The parser invokes alloca or malloc; define the necessary symbols. */ - -# ifdef YYSTACK_USE_ALLOCA -# if YYSTACK_USE_ALLOCA -# ifdef __GNUC__ -# define YYSTACK_ALLOC __builtin_alloca -# elif defined __BUILTIN_VA_ARG_INCR -# include /* INFRINGES ON USER NAME SPACE */ -# elif defined _AIX -# define YYSTACK_ALLOC __alloca -# elif defined _MSC_VER -# include /* INFRINGES ON USER NAME SPACE */ -# define alloca _alloca -# else -# define YYSTACK_ALLOC alloca -# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS -# include /* INFRINGES ON USER NAME SPACE */ - /* Use EXIT_SUCCESS as a witness for stdlib.h. */ -# ifndef EXIT_SUCCESS -# define EXIT_SUCCESS 0 -# endif -# endif -# endif -# endif -# endif - -# ifdef YYSTACK_ALLOC - /* Pacify GCC's 'empty if-body' warning. */ -# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) -# ifndef YYSTACK_ALLOC_MAXIMUM - /* The OS might guarantee only one guard page at the bottom of the stack, - and a page size can be as small as 4096 bytes. So we cannot safely - invoke alloca (N) if N exceeds 4096. Use a slightly smaller number - to allow for a few compiler-allocated temporary stack slots. */ -# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ -# endif -# else -# define YYSTACK_ALLOC YYMALLOC -# define YYSTACK_FREE YYFREE -# ifndef YYSTACK_ALLOC_MAXIMUM -# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM -# endif -# if (defined __cplusplus && ! defined EXIT_SUCCESS \ - && ! ((defined YYMALLOC || defined malloc) \ - && (defined YYFREE || defined free))) -# include /* INFRINGES ON USER NAME SPACE */ -# ifndef EXIT_SUCCESS -# define EXIT_SUCCESS 0 -# endif -# endif -# ifndef YYMALLOC -# define YYMALLOC malloc -# if ! defined malloc && ! defined EXIT_SUCCESS -void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ -# endif -# endif -# ifndef YYFREE -# define YYFREE free -# if ! defined free && ! defined EXIT_SUCCESS -void free (void *); /* INFRINGES ON USER NAME SPACE */ -# endif -# endif -# endif -#endif /* ! defined yyoverflow || YYERROR_VERBOSE */ - - -#if (! defined yyoverflow \ - && (! defined __cplusplus \ - || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) - -/* A type that is properly aligned for any stack member. */ -union yyalloc -{ - yytype_int16 yyss_alloc; - YYSTYPE yyvs_alloc; -}; - -/* The size of the maximum gap between one aligned stack and the next. */ -# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) - -/* The size of an array large to enough to hold all stacks, each with - N elements. */ -# define YYSTACK_BYTES(N) \ - ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ - + YYSTACK_GAP_MAXIMUM) - -# define YYCOPY_NEEDED 1 - -/* Relocate STACK from its old location to the new one. The - local variables YYSIZE and YYSTACKSIZE give the old and new number of - elements in the stack, and YYPTR gives the new location of the - stack. Advance YYPTR to a properly aligned location for the next - stack. */ -# define YYSTACK_RELOCATE(Stack_alloc, Stack) \ - do \ - { \ - YYSIZE_T yynewbytes; \ - YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ - Stack = &yyptr->Stack_alloc; \ - yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ - yyptr += yynewbytes / sizeof (*yyptr); \ - } \ - while (0) - -#endif - -#if defined YYCOPY_NEEDED && YYCOPY_NEEDED -/* Copy COUNT objects from SRC to DST. The source and destination do - not overlap. */ -# ifndef YYCOPY -# if defined __GNUC__ && 1 < __GNUC__ -# define YYCOPY(Dst, Src, Count) \ - __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src))) -# else -# define YYCOPY(Dst, Src, Count) \ - do \ - { \ - YYSIZE_T yyi; \ - for (yyi = 0; yyi < (Count); yyi++) \ - (Dst)[yyi] = (Src)[yyi]; \ - } \ - while (0) -# endif -# endif -#endif /* !YYCOPY_NEEDED */ - -/* YYFINAL -- State number of the termination state. */ -#define YYFINAL 80 -/* YYLAST -- Last index in YYTABLE. */ -#define YYLAST 223 - -/* YYNTOKENS -- Number of terminals. */ -#define YYNTOKENS 50 -/* YYNNTS -- Number of nonterminals. */ -#define YYNNTS 6 -/* YYNRULES -- Number of rules. */ -#define YYNRULES 46 -/* YYNSTATES -- Number of states. */ -#define YYNSTATES 218 - -/* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned - by yylex, with out-of-bounds checking. */ -#define YYUNDEFTOK 2 -#define YYMAXUTOK 304 - -#define YYTRANSLATE(YYX) \ - ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) - -/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM - as returned by yylex, without out-of-bounds checking. */ -static const yytype_uint8 yytranslate[] = -{ - 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, - 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, - 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, - 45, 46, 47, 48, 49 -}; - -#if YYDEBUG - /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ -static const yytype_uint16 yyrline[] = -{ - 0, 73, 73, 81, 87, 97, 103, 111, 115, 119, - 123, 127, 131, 135, 139, 143, 147, 151, 155, 159, - 163, 167, 172, 177, 182, 187, 192, 197, 202, 207, - 212, 217, 222, 227, 232, 237, 242, 247, 252, 257, - 262, 267, 272, 277, 282, 289, 293 -}; -#endif - -#if YYDEBUG || YYERROR_VERBOSE || 0 -/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. - First, the terminals, then, starting at YYNTOKENS, nonterminals. */ -static const char *const yytname[] = -{ - "$end", "error", "$undefined", "floatValue", "gequal", "less", - "texVariable", "expandString", "openParen", "closeParen", "semicolon", - "comma", "nop", "texture_1d", "texture_2d", "texture_rectangle", - "texture_3d", "texture_cube_map", "cull_fragment", "pass_through", - "offset_2d_scale", "offset_2d", "offset_rectangle_scale", - "offset_rectangle", "dependent_ar", "dependent_gb", - "dot_product_2d_1of2", "dot_product_2d_2of2", - "dot_product_rectangle_1of2", "dot_product_rectangle_2of2", - "dot_product_depth_replace_1of2", "dot_product_depth_replace_2of2", - "dot_product_3d_1of3", "dot_product_3d_2of3", "dot_product_3d_3of3", - "dot_product_cube_map_1of3", "dot_product_cube_map_2of3", - "dot_product_cube_map_3of3", - "dot_product_reflect_cube_map_eye_from_qs_1of3", - "dot_product_reflect_cube_map_eye_from_qs_2of3", - "dot_product_reflect_cube_map_eye_from_qs_3of3", - "dot_product_reflect_cube_map_const_eye_1of3", - "dot_product_reflect_cube_map_const_eye_2of3", - "dot_product_reflect_cube_map_const_eye_3of3", - "dot_product_cube_map_and_reflect_cube_map_eye_from_qs_1of3", - "dot_product_cube_map_and_reflect_cube_map_eye_from_qs_2of3", - "dot_product_cube_map_and_reflect_cube_map_eye_from_qs_3of3", - "dot_product_cube_map_and_reflect_cube_map_const_eye_1of3", - "dot_product_cube_map_and_reflect_cube_map_const_eye_2of3", - "dot_product_cube_map_and_reflect_cube_map_const_eye_3of3", "$accept", - "WholeEnchilada", "InstListDesc", "MappedVariableDesc", "InstDesc", - "CondDesc", YY_NULLPTR -}; -#endif - -# ifdef YYPRINT -/* YYTOKNUM[NUM] -- (External) token number corresponding to the - (internal) symbol number NUM (which must be that of a token). */ -static const yytype_uint16 yytoknum[] = -{ - 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, - 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, - 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, - 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, - 295, 296, 297, 298, 299, 300, 301, 302, 303, 304 -}; -# endif - -#define YYPACT_NINF -127 - -#define yypact_value_is_default(Yystate) \ - (!!((Yystate) == (-127))) - -#define YYTABLE_NINF -1 - -#define yytable_value_is_error(Yytable_value) \ - 0 - - /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing - STATE-NUM. */ -static const yytype_int16 yypact[] = -{ - -11, 31, 35, 39, 40, 41, 42, 43, 44, 45, - 46, 71, 72, 73, 74, 75, 76, 77, 78, 79, - 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, - 90, 91, 92, 93, 94, 95, 96, 97, 98, 107, - -11, 36, 99, 100, 101, 102, 103, 104, 37, 105, - 109, 110, 111, 112, 113, 114, 38, 38, 38, 38, - 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, - 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, - -127, 115, -127, -127, -127, -127, -127, -127, -127, -127, - -127, 116, -127, 117, 118, 119, 120, 123, 124, -127, - 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, - 136, 137, 138, 139, 140, 141, 142, 143, 145, 146, - 147, 148, 149, 150, 152, -127, 37, 121, 155, 159, - 160, -127, -127, 158, -127, -127, -127, -127, -127, -127, - -127, -127, -127, -127, -127, -127, -127, -127, -127, 162, - -127, -127, -127, -127, -127, 163, -127, -127, 156, 157, - 161, 164, 165, 168, 167, 169, 37, 166, 170, 171, - 176, -127, 178, 179, 172, 173, 174, 175, 177, 180, - 181, 37, 184, 186, 187, 190, 191, 192, 188, 185, - 189, 193, 194, 197, 198, -127, 195, 196, 199, 200, - -127, -127, 201, 202, 203, 204, 205, -127, 206, -127, - 207, 208, 212, 213, 211, 214, -127, -127 -}; - - /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. - Performed when YYTABLE does not specify something else to do. Zero - means the default is an error. */ -static const yytype_uint8 yydefact[] = -{ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 1, 0, 4, 7, 8, 9, 10, 11, 12, 45, - 46, 0, 14, 0, 0, 0, 0, 0, 0, 6, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, - 0, 19, 20, 0, 21, 22, 23, 24, 25, 26, - 27, 28, 29, 30, 31, 32, 33, 34, 35, 0, - 37, 38, 39, 40, 41, 0, 43, 44, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 13, 0, 0, 0, 0, - 36, 42, 0, 0, 0, 0, 0, 16, 0, 18, - 0, 0, 0, 0, 0, 0, 15, 17 -}; - - /* YYPGOTO[NTERM-NUM]. */ -static const yytype_int16 yypgoto[] = -{ - -127, -127, -127, -1, 182, -126 -}; - - /* YYDEFGOTO[NTERM-NUM]. */ -static const yytype_int8 yydefgoto[] = -{ - -1, 39, 40, 101, 41, 91 -}; - - /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If - positive, shift that token. If negative, reduce the rule whose - number is the opposite. If YYTABLE_NINF, syntax error. */ -static const yytype_uint8 yytable[] = -{ - 158, 1, 2, 3, 4, 5, 6, 7, 8, 9, - 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, - 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, - 30, 31, 32, 33, 34, 35, 36, 37, 38, 42, - 174, 89, 90, 43, 99, 100, 82, 44, 45, 46, - 47, 48, 49, 50, 51, 188, 102, 103, 104, 105, - 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, - 116, 117, 118, 119, 120, 121, 122, 123, 124, 52, - 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, - 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, - 73, 74, 75, 76, 77, 78, 79, 80, 83, 84, - 85, 86, 87, 88, 92, 93, 94, 95, 96, 97, - 98, 0, 0, 0, 159, 125, 0, 126, 127, 128, - 129, 130, 131, 132, 133, 0, 134, 135, 136, 137, - 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, - 148, 0, 150, 149, 151, 152, 153, 154, 160, 156, - 155, 157, 161, 162, 163, 164, 165, 166, 167, 175, - 0, 0, 168, 176, 177, 169, 170, 171, 172, 178, - 173, 179, 180, 181, 182, 183, 184, 189, 185, 190, - 191, 186, 187, 192, 193, 194, 196, 195, 202, 203, - 197, 0, 204, 205, 198, 199, 200, 201, 210, 211, - 0, 207, 206, 209, 208, 214, 215, 0, 212, 213, - 216, 0, 81, 217 -}; - -static const yytype_int16 yycheck[] = -{ - 126, 12, 13, 14, 15, 16, 17, 18, 19, 20, - 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, - 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 8, - 166, 4, 5, 8, 6, 7, 10, 8, 8, 8, - 8, 8, 8, 8, 8, 181, 57, 58, 59, 60, - 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, - 71, 72, 73, 74, 75, 76, 77, 78, 79, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 0, 9, 9, - 9, 9, 9, 9, 9, 6, 6, 6, 6, 6, - 6, -1, -1, -1, 3, 10, -1, 11, 11, 11, - 11, 11, 9, 9, 8, -1, 9, 9, 9, 9, - 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, - 9, -1, 9, 11, 9, 9, 9, 9, 3, 9, - 11, 9, 3, 3, 6, 3, 3, 11, 11, 3, - -1, -1, 11, 3, 3, 11, 11, 9, 11, 3, - 11, 3, 3, 11, 11, 11, 11, 3, 11, 3, - 3, 11, 11, 3, 3, 3, 11, 9, 3, 3, - 11, -1, 3, 3, 11, 11, 9, 9, 3, 3, - -1, 9, 11, 9, 11, 3, 3, -1, 11, 11, - 9, -1, 40, 9 -}; - - /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing - symbol of state STATE-NUM. */ -static const yytype_uint8 yystos[] = -{ - 0, 12, 13, 14, 15, 16, 17, 18, 19, 20, - 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, - 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 51, - 52, 54, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 0, 54, 10, 9, 9, 9, 9, 9, 9, 4, - 5, 55, 9, 6, 6, 6, 6, 6, 6, 6, - 7, 53, 53, 53, 53, 53, 53, 53, 53, 53, - 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, - 53, 53, 53, 53, 53, 10, 11, 11, 11, 11, - 11, 9, 9, 8, 9, 9, 9, 9, 9, 9, - 9, 9, 9, 9, 9, 9, 9, 9, 9, 11, - 9, 9, 9, 9, 9, 11, 9, 9, 55, 3, - 3, 3, 3, 6, 3, 3, 11, 11, 11, 11, - 11, 9, 11, 11, 55, 3, 3, 3, 3, 3, - 3, 11, 11, 11, 11, 11, 11, 11, 55, 3, - 3, 3, 3, 3, 3, 9, 11, 11, 11, 11, - 9, 9, 3, 3, 3, 3, 11, 9, 11, 9, - 3, 3, 11, 11, 3, 3, 9, 9 -}; - - /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ -static const yytype_uint8 yyr1[] = -{ - 0, 50, 51, 52, 52, 53, 53, 54, 54, 54, - 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, - 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, - 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, - 54, 54, 54, 54, 54, 55, 55 -}; - - /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */ -static const yytype_uint8 yyr2[] = -{ - 0, 2, 1, 3, 2, 4, 1, 3, 3, 3, - 3, 3, 3, 10, 3, 16, 12, 16, 12, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 10, 4, 4, 4, - 4, 4, 10, 4, 4, 1, 1 -}; - - -#define yyerrok (yyerrstatus = 0) -#define yyclearin (yychar = YYEMPTY) -#define YYEMPTY (-2) -#define YYEOF 0 - -#define YYACCEPT goto yyacceptlab -#define YYABORT goto yyabortlab -#define YYERROR goto yyerrorlab - - -#define YYRECOVERING() (!!yyerrstatus) - -#define YYBACKUP(Token, Value) \ -do \ - if (yychar == YYEMPTY) \ - { \ - yychar = (Token); \ - yylval = (Value); \ - YYPOPSTACK (yylen); \ - yystate = *yyssp; \ - goto yybackup; \ - } \ - else \ - { \ - yyerror (YY_("syntax error: cannot back up")); \ - YYERROR; \ - } \ -while (0) - -/* Error token number */ -#define YYTERROR 1 -#define YYERRCODE 256 - - - -/* Enable debugging if requested. */ -#if YYDEBUG - -# ifndef YYFPRINTF -# include /* INFRINGES ON USER NAME SPACE */ -# define YYFPRINTF fprintf -# endif - -# define YYDPRINTF(Args) \ -do { \ - if (yydebug) \ - YYFPRINTF Args; \ -} while (0) - -/* This macro is provided for backward compatibility. */ -#ifndef YY_LOCATION_PRINT -# define YY_LOCATION_PRINT(File, Loc) ((void) 0) -#endif - - -# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ -do { \ - if (yydebug) \ - { \ - YYFPRINTF (stderr, "%s ", Title); \ - yy_symbol_print (stderr, \ - Type, Value); \ - YYFPRINTF (stderr, "\n"); \ - } \ -} while (0) - - -/*----------------------------------------. -| Print this symbol's value on YYOUTPUT. | -`----------------------------------------*/ - -static void -yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) -{ - FILE *yyo = yyoutput; - YYUSE (yyo); - if (!yyvaluep) - return; -# ifdef YYPRINT - if (yytype < YYNTOKENS) - YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); -# endif - YYUSE (yytype); -} - - -/*--------------------------------. -| Print this symbol on YYOUTPUT. | -`--------------------------------*/ - -static void -yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) -{ - YYFPRINTF (yyoutput, "%s %s (", - yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]); - - yy_symbol_value_print (yyoutput, yytype, yyvaluep); - YYFPRINTF (yyoutput, ")"); -} - -/*------------------------------------------------------------------. -| yy_stack_print -- Print the state stack from its BOTTOM up to its | -| TOP (included). | -`------------------------------------------------------------------*/ - -static void -yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) -{ - YYFPRINTF (stderr, "Stack now"); - for (; yybottom <= yytop; yybottom++) - { - int yybot = *yybottom; - YYFPRINTF (stderr, " %d", yybot); - } - YYFPRINTF (stderr, "\n"); -} - -# define YY_STACK_PRINT(Bottom, Top) \ -do { \ - if (yydebug) \ - yy_stack_print ((Bottom), (Top)); \ -} while (0) - - -/*------------------------------------------------. -| Report that the YYRULE is going to be reduced. | -`------------------------------------------------*/ - -static void -yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule) -{ - unsigned long int yylno = yyrline[yyrule]; - int yynrhs = yyr2[yyrule]; - int yyi; - YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", - yyrule - 1, yylno); - /* The symbols being reduced. */ - for (yyi = 0; yyi < yynrhs; yyi++) - { - YYFPRINTF (stderr, " $%d = ", yyi + 1); - yy_symbol_print (stderr, - yystos[yyssp[yyi + 1 - yynrhs]], - &(yyvsp[(yyi + 1) - (yynrhs)]) - ); - YYFPRINTF (stderr, "\n"); - } -} - -# define YY_REDUCE_PRINT(Rule) \ -do { \ - if (yydebug) \ - yy_reduce_print (yyssp, yyvsp, Rule); \ -} while (0) - -/* Nonzero means print parse trace. It is left uninitialized so that - multiple parsers can coexist. */ -int yydebug; -#else /* !YYDEBUG */ -# define YYDPRINTF(Args) -# define YY_SYMBOL_PRINT(Title, Type, Value, Location) -# define YY_STACK_PRINT(Bottom, Top) -# define YY_REDUCE_PRINT(Rule) -#endif /* !YYDEBUG */ - - -/* YYINITDEPTH -- initial size of the parser's stacks. */ -#ifndef YYINITDEPTH -# define YYINITDEPTH 200 -#endif - -/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only - if the built-in stack extension method is used). - - Do not make this value too large; the results are undefined if - YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) - evaluated with infinite-precision integer arithmetic. */ - -#ifndef YYMAXDEPTH -# define YYMAXDEPTH 10000 -#endif - - -#if YYERROR_VERBOSE - -# ifndef yystrlen -# if defined __GLIBC__ && defined _STRING_H -# define yystrlen strlen -# else -/* Return the length of YYSTR. */ -static YYSIZE_T -yystrlen (const char *yystr) -{ - YYSIZE_T yylen; - for (yylen = 0; yystr[yylen]; yylen++) - continue; - return yylen; -} -# endif -# endif - -# ifndef yystpcpy -# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE -# define yystpcpy stpcpy -# else -/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in - YYDEST. */ -static char * -yystpcpy (char *yydest, const char *yysrc) -{ - char *yyd = yydest; - const char *yys = yysrc; - - while ((*yyd++ = *yys++) != '\0') - continue; - - return yyd - 1; -} -# endif -# endif - -# ifndef yytnamerr -/* Copy to YYRES the contents of YYSTR after stripping away unnecessary - quotes and backslashes, so that it's suitable for yyerror. The - heuristic is that double-quoting is unnecessary unless the string - contains an apostrophe, a comma, or backslash (other than - backslash-backslash). YYSTR is taken from yytname. If YYRES is - null, do not copy; instead, return the length of what the result - would have been. */ -static YYSIZE_T -yytnamerr (char *yyres, const char *yystr) -{ - if (*yystr == '"') - { - YYSIZE_T yyn = 0; - char const *yyp = yystr; - - for (;;) - switch (*++yyp) - { - case '\'': - case ',': - goto do_not_strip_quotes; - - case '\\': - if (*++yyp != '\\') - goto do_not_strip_quotes; - /* Fall through. */ - default: - if (yyres) - yyres[yyn] = *yyp; - yyn++; - break; - - case '"': - if (yyres) - yyres[yyn] = '\0'; - return yyn; - } - do_not_strip_quotes: ; - } - - if (! yyres) - return yystrlen (yystr); - - return yystpcpy (yyres, yystr) - yyres; -} -# endif - -/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message - about the unexpected token YYTOKEN for the state stack whose top is - YYSSP. - - Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is - not large enough to hold the message. In that case, also set - *YYMSG_ALLOC to the required number of bytes. Return 2 if the - required number of bytes is too large to store. */ -static int -yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg, - yytype_int16 *yyssp, int yytoken) -{ - YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]); - YYSIZE_T yysize = yysize0; - enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; - /* Internationalized format string. */ - const char *yyformat = YY_NULLPTR; - /* Arguments of yyformat. */ - char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; - /* Number of reported tokens (one for the "unexpected", one per - "expected"). */ - int yycount = 0; - - /* There are many possibilities here to consider: - - If this state is a consistent state with a default action, then - the only way this function was invoked is if the default action - is an error action. In that case, don't check for expected - tokens because there are none. - - The only way there can be no lookahead present (in yychar) is if - this state is a consistent state with a default action. Thus, - detecting the absence of a lookahead is sufficient to determine - that there is no unexpected or expected token to report. In that - case, just report a simple "syntax error". - - Don't assume there isn't a lookahead just because this state is a - consistent state with a default action. There might have been a - previous inconsistent state, consistent state with a non-default - action, or user semantic action that manipulated yychar. - - Of course, the expected token list depends on states to have - correct lookahead information, and it depends on the parser not - to perform extra reductions after fetching a lookahead from the - scanner and before detecting a syntax error. Thus, state merging - (from LALR or IELR) and default reductions corrupt the expected - token list. However, the list is correct for canonical LR with - one exception: it will still contain any token that will not be - accepted due to an error action in a later state. - */ - if (yytoken != YYEMPTY) - { - int yyn = yypact[*yyssp]; - yyarg[yycount++] = yytname[yytoken]; - if (!yypact_value_is_default (yyn)) - { - /* Start YYX at -YYN if negative to avoid negative indexes in - YYCHECK. In other words, skip the first -YYN actions for - this state because they are default actions. */ - int yyxbegin = yyn < 0 ? -yyn : 0; - /* Stay within bounds of both yycheck and yytname. */ - int yychecklim = YYLAST - yyn + 1; - int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; - int yyx; - - for (yyx = yyxbegin; yyx < yyxend; ++yyx) - if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR - && !yytable_value_is_error (yytable[yyx + yyn])) - { - if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) - { - yycount = 1; - yysize = yysize0; - break; - } - yyarg[yycount++] = yytname[yyx]; - { - YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]); - if (! (yysize <= yysize1 - && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) - return 2; - yysize = yysize1; - } - } - } - } - - switch (yycount) - { -# define YYCASE_(N, S) \ - case N: \ - yyformat = S; \ - break - YYCASE_(0, YY_("syntax error")); - YYCASE_(1, YY_("syntax error, unexpected %s")); - YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); - YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); - YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); - YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); -# undef YYCASE_ - } - - { - YYSIZE_T yysize1 = yysize + yystrlen (yyformat); - if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) - return 2; - yysize = yysize1; - } - - if (*yymsg_alloc < yysize) - { - *yymsg_alloc = 2 * yysize; - if (! (yysize <= *yymsg_alloc - && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) - *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; - return 1; - } - - /* Avoid sprintf, as that infringes on the user's name space. - Don't have undefined behavior even if the translation - produced a string with the wrong number of "%s"s. */ - { - char *yyp = *yymsg; - int yyi = 0; - while ((*yyp = *yyformat) != '\0') - if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) - { - yyp += yytnamerr (yyp, yyarg[yyi++]); - yyformat += 2; - } - else - { - yyp++; - yyformat++; - } - } - return 0; -} -#endif /* YYERROR_VERBOSE */ - -/*-----------------------------------------------. -| Release the memory associated to this symbol. | -`-----------------------------------------------*/ - -static void -yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep) -{ - YYUSE (yyvaluep); - if (!yymsg) - yymsg = "Deleting"; - YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); - - YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN - YYUSE (yytype); - YY_IGNORE_MAYBE_UNINITIALIZED_END -} - - - - -/* The lookahead symbol. */ -int yychar; - -/* The semantic value of the lookahead symbol. */ -YYSTYPE yylval; -/* Number of syntax errors so far. */ -int yynerrs; - - -/*----------. -| yyparse. | -`----------*/ - -int -yyparse (void) -{ - int yystate; - /* Number of tokens to shift before error messages enabled. */ - int yyerrstatus; - - /* The stacks and their tools: - 'yyss': related to states. - 'yyvs': related to semantic values. - - Refer to the stacks through separate pointers, to allow yyoverflow - to reallocate them elsewhere. */ - - /* The state stack. */ - yytype_int16 yyssa[YYINITDEPTH]; - yytype_int16 *yyss; - yytype_int16 *yyssp; - - /* The semantic value stack. */ - YYSTYPE yyvsa[YYINITDEPTH]; - YYSTYPE *yyvs; - YYSTYPE *yyvsp; - - YYSIZE_T yystacksize; - - int yyn; - int yyresult; - /* Lookahead token as an internal (translated) token number. */ - int yytoken = 0; - /* The variables used to return semantic value and location from the - action routines. */ - YYSTYPE yyval; - -#if YYERROR_VERBOSE - /* Buffer for error messages, and its allocated size. */ - char yymsgbuf[128]; - char *yymsg = yymsgbuf; - YYSIZE_T yymsg_alloc = sizeof yymsgbuf; -#endif - -#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) - - /* The number of symbols on the RHS of the reduced rule. - Keep to zero when no symbol should be popped. */ - int yylen = 0; - - yyssp = yyss = yyssa; - yyvsp = yyvs = yyvsa; - yystacksize = YYINITDEPTH; - - YYDPRINTF ((stderr, "Starting parse\n")); - - yystate = 0; - yyerrstatus = 0; - yynerrs = 0; - yychar = YYEMPTY; /* Cause a token to be read. */ - goto yysetstate; - -/*------------------------------------------------------------. -| yynewstate -- Push a new state, which is found in yystate. | -`------------------------------------------------------------*/ - yynewstate: - /* In all cases, when you get here, the value and location stacks - have just been pushed. So pushing a state here evens the stacks. */ - yyssp++; - - yysetstate: - *yyssp = yystate; - - if (yyss + yystacksize - 1 <= yyssp) - { - /* Get the current used size of the three stacks, in elements. */ - YYSIZE_T yysize = yyssp - yyss + 1; - -#ifdef yyoverflow - { - /* Give user a chance to reallocate the stack. Use copies of - these so that the &'s don't force the real ones into - memory. */ - YYSTYPE *yyvs1 = yyvs; - yytype_int16 *yyss1 = yyss; - - /* Each stack pointer address is followed by the size of the - data in use in that stack, in bytes. This used to be a - conditional around just the two extra args, but that might - be undefined if yyoverflow is a macro. */ - yyoverflow (YY_("memory exhausted"), - &yyss1, yysize * sizeof (*yyssp), - &yyvs1, yysize * sizeof (*yyvsp), - &yystacksize); - - yyss = yyss1; - yyvs = yyvs1; - } -#else /* no yyoverflow */ -# ifndef YYSTACK_RELOCATE - goto yyexhaustedlab; -# else - /* Extend the stack our own way. */ - if (YYMAXDEPTH <= yystacksize) - goto yyexhaustedlab; - yystacksize *= 2; - if (YYMAXDEPTH < yystacksize) - yystacksize = YYMAXDEPTH; - - { - yytype_int16 *yyss1 = yyss; - union yyalloc *yyptr = - (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); - if (! yyptr) - goto yyexhaustedlab; - YYSTACK_RELOCATE (yyss_alloc, yyss); - YYSTACK_RELOCATE (yyvs_alloc, yyvs); -# undef YYSTACK_RELOCATE - if (yyss1 != yyssa) - YYSTACK_FREE (yyss1); - } -# endif -#endif /* no yyoverflow */ - - yyssp = yyss + yysize - 1; - yyvsp = yyvs + yysize - 1; - - YYDPRINTF ((stderr, "Stack size increased to %lu\n", - (unsigned long int) yystacksize)); - - if (yyss + yystacksize - 1 <= yyssp) - YYABORT; - } - - YYDPRINTF ((stderr, "Entering state %d\n", yystate)); - - if (yystate == YYFINAL) - YYACCEPT; - - goto yybackup; - -/*-----------. -| yybackup. | -`-----------*/ -yybackup: - - /* Do appropriate processing given the current state. Read a - lookahead token if we need one and don't already have one. */ - - /* First try to decide what to do without reference to lookahead token. */ - yyn = yypact[yystate]; - if (yypact_value_is_default (yyn)) - goto yydefault; - - /* Not known => get a lookahead token if don't already have one. */ - - /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ - if (yychar == YYEMPTY) - { - YYDPRINTF ((stderr, "Reading a token: ")); - yychar = yylex (); - } - - if (yychar <= YYEOF) - { - yychar = yytoken = YYEOF; - YYDPRINTF ((stderr, "Now at end of input.\n")); - } - else - { - yytoken = YYTRANSLATE (yychar); - YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); - } - - /* If the proper action on seeing token YYTOKEN is to reduce or to - detect an error, take that action. */ - yyn += yytoken; - if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) - goto yydefault; - yyn = yytable[yyn]; - if (yyn <= 0) - { - if (yytable_value_is_error (yyn)) - goto yyerrlab; - yyn = -yyn; - goto yyreduce; - } - - /* Count tokens shifted since error; after three, turn off error - status. */ - if (yyerrstatus) - yyerrstatus--; - - /* Shift the lookahead token. */ - YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); - - /* Discard the shifted token. */ - yychar = YYEMPTY; - - yystate = yyn; - YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN - *++yyvsp = yylval; - YY_IGNORE_MAYBE_UNINITIALIZED_END - - goto yynewstate; - - -/*-----------------------------------------------------------. -| yydefault -- do the default action for the current state. | -`-----------------------------------------------------------*/ -yydefault: - yyn = yydefact[yystate]; - if (yyn == 0) - goto yyerrlab; - goto yyreduce; - - -/*-----------------------------. -| yyreduce -- Do a reduction. | -`-----------------------------*/ -yyreduce: - /* yyn is the number of a rule to reduce with. */ - yylen = yyr2[yyn]; - - /* If YYLEN is nonzero, implement the default value of the action: - '$$ = $1'. - - Otherwise, the following line sets YYVAL to garbage. - This behavior is undocumented and Bison - users should not rely upon it. Assigning to YYVAL - unconditionally makes the parser a bit smaller, and it avoids a - GCC warning that YYVAL may be used uninitialized. */ - yyval = yyvsp[1-yylen]; - - - YY_REDUCE_PRINT (yyn); - switch (yyn) - { - case 2: -#line 74 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyvsp[0].instList)->Validate(); - (yyvsp[0].instList)->Invoke(); - delete (yyvsp[0].instList); - } -#line 1423 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 3: -#line 82 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - *((yyvsp[-2].instList)) += (yyvsp[-1].inst); - delete (yyvsp[-1].inst); - (yyval.instList) = (yyvsp[-2].instList); - } -#line 1433 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 4: -#line 88 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - InstListPtr instList = new InstList; - *instList += (yyvsp[-1].inst); - delete (yyvsp[-1].inst); - (yyval.instList) = instList; - } -#line 1444 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 5: -#line 98 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.variable) = new MappedVariable; - (yyval.variable)->var = (yyvsp[-1].fval); - (yyval.variable)->expand = true; - } -#line 1454 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 6: -#line 104 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.variable) = new MappedVariable; - (yyval.variable)->var = (yyvsp[0].fval); - (yyval.variable)->expand = false; - } -#line 1464 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 7: -#line 112 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_NOP); - } -#line 1472 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 8: -#line 116 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_TEXTURE_1D); - } -#line 1480 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 9: -#line 120 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_TEXTURE_2D); - } -#line 1488 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 10: -#line 124 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_TEXTURE_RECTANGLE); - } -#line 1496 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 11: -#line 128 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_TEXTURE_3D); - } -#line 1504 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 12: -#line 132 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_TEXTURE_CUBE_MAP); - } -#line 1512 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 13: -#line 136 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_CULL_FRAGMENT, (yyvsp[-7].fval), (yyvsp[-5].fval), (yyvsp[-3].fval), (yyvsp[-1].fval)); - } -#line 1520 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 14: -#line 140 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_PASS_THROUGH); - } -#line 1528 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 15: -#line 144 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_OFFSET_2D_SCALE, (yyvsp[-13].fval), (yyvsp[-11].fval), (yyvsp[-9].fval), (yyvsp[-7].fval), (yyvsp[-5].fval), (yyvsp[-3].fval), (yyvsp[-1].fval)); - } -#line 1536 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 16: -#line 148 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_OFFSET_2D, (yyvsp[-9].fval), (yyvsp[-7].fval), (yyvsp[-5].fval), (yyvsp[-3].fval), (yyvsp[-1].fval)); - } -#line 1544 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 17: -#line 152 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_OFFSET_RECTANGLE_SCALE, (yyvsp[-13].fval), (yyvsp[-11].fval), (yyvsp[-9].fval), (yyvsp[-7].fval), (yyvsp[-5].fval), (yyvsp[-3].fval), (yyvsp[-1].fval)); - } -#line 1552 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 18: -#line 156 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_OFFSET_RECTANGLE, (yyvsp[-9].fval), (yyvsp[-7].fval), (yyvsp[-5].fval), (yyvsp[-3].fval), (yyvsp[-1].fval)); - } -#line 1560 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 19: -#line 160 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DEPENDENT_AR, (yyvsp[-1].fval)); - } -#line 1568 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 20: -#line 164 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DEPENDENT_GB, (yyvsp[-1].fval)); - } -#line 1576 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 21: -#line 168 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_2D_1_OF_2, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1585 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 22: -#line 173 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_2D_2_OF_2, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1594 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 23: -#line 178 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_RECTANGLE_1_OF_2, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1603 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 24: -#line 183 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_RECTANGLE_2_OF_2, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1612 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 25: -#line 188 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_DEPTH_REPLACE_1_OF_2, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1621 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 26: -#line 193 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_DEPTH_REPLACE_2_OF_2, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1630 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 27: -#line 198 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_3D_1_OF_3, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1639 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 28: -#line 203 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_3D_2_OF_3, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1648 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 29: -#line 208 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_3D_3_OF_3, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1657 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 30: -#line 213 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_CUBE_MAP_1_OF_3, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1666 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 31: -#line 218 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_CUBE_MAP_2_OF_3, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1675 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 32: -#line 223 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_CUBE_MAP_3_OF_3, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1684 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 33: -#line 228 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_EYE_FROM_QS_1_OF_3, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1693 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 34: -#line 233 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_EYE_FROM_QS_2_OF_3, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1702 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 35: -#line 238 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_EYE_FROM_QS_3_OF_3, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1711 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 36: -#line 243 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_CONST_EYE_1_OF_3, (yyvsp[-7].variable), (yyvsp[-5].fval), (yyvsp[-3].fval), (yyvsp[-1].fval)); - delete (yyvsp[-7].variable); - } -#line 1720 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 37: -#line 248 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_CONST_EYE_2_OF_3, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1729 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 38: -#line 253 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_CONST_EYE_3_OF_3, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1738 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 39: -#line 258 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_EYE_FROM_QS_1_OF_3, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1747 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 40: -#line 263 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_EYE_FROM_QS_2_OF_3, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1756 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 41: -#line 268 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_EYE_FROM_QS_3_OF_3, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1765 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 42: -#line 273 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_CONST_EYE_1_OF_3, (yyvsp[-7].variable), (yyvsp[-5].fval), (yyvsp[-3].fval), (yyvsp[-1].fval)); - delete (yyvsp[-7].variable); - } -#line 1774 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 43: -#line 278 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_CONST_EYE_2_OF_3, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1783 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 44: -#line 283 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new Inst(TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_CONST_EYE_3_OF_3, (yyvsp[-1].variable)); - delete (yyvsp[-1].variable); - } -#line 1792 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 45: -#line 290 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.fval) = (yyvsp[0].fval); - } -#line 1800 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - case 46: -#line 294 "ts1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.fval) = (yyvsp[0].fval); - } -#line 1808 "_ts1.0_parser.c" /* yacc.c:1646 */ - break; - - -#line 1812 "_ts1.0_parser.c" /* yacc.c:1646 */ - default: break; - } - /* User semantic actions sometimes alter yychar, and that requires - that yytoken be updated with the new translation. We take the - approach of translating immediately before every use of yytoken. - One alternative is translating here after every semantic action, - but that translation would be missed if the semantic action invokes - YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or - if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an - incorrect destructor might then be invoked immediately. In the - case of YYERROR or YYBACKUP, subsequent parser actions might lead - to an incorrect destructor call or verbose syntax error message - before the lookahead is translated. */ - YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); - - YYPOPSTACK (yylen); - yylen = 0; - YY_STACK_PRINT (yyss, yyssp); - - *++yyvsp = yyval; - - /* Now 'shift' the result of the reduction. Determine what state - that goes to, based on the state we popped back to and the rule - number reduced by. */ - - yyn = yyr1[yyn]; - - yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; - if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) - yystate = yytable[yystate]; - else - yystate = yydefgoto[yyn - YYNTOKENS]; - - goto yynewstate; - - -/*--------------------------------------. -| yyerrlab -- here on detecting error. | -`--------------------------------------*/ -yyerrlab: - /* Make sure we have latest lookahead translation. See comments at - user semantic actions for why this is necessary. */ - yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); - - /* If not already recovering from an error, report this error. */ - if (!yyerrstatus) - { - ++yynerrs; -#if ! YYERROR_VERBOSE - yyerror (YY_("syntax error")); -#else -# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ - yyssp, yytoken) - { - char const *yymsgp = YY_("syntax error"); - int yysyntax_error_status; - yysyntax_error_status = YYSYNTAX_ERROR; - if (yysyntax_error_status == 0) - yymsgp = yymsg; - else if (yysyntax_error_status == 1) - { - if (yymsg != yymsgbuf) - YYSTACK_FREE (yymsg); - yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); - if (!yymsg) - { - yymsg = yymsgbuf; - yymsg_alloc = sizeof yymsgbuf; - yysyntax_error_status = 2; - } - else - { - yysyntax_error_status = YYSYNTAX_ERROR; - yymsgp = yymsg; - } - } - yyerror (yymsgp); - if (yysyntax_error_status == 2) - goto yyexhaustedlab; - } -# undef YYSYNTAX_ERROR -#endif - } - - - - if (yyerrstatus == 3) - { - /* If just tried and failed to reuse lookahead token after an - error, discard it. */ - - if (yychar <= YYEOF) - { - /* Return failure if at end of input. */ - if (yychar == YYEOF) - YYABORT; - } - else - { - yydestruct ("Error: discarding", - yytoken, &yylval); - yychar = YYEMPTY; - } - } - - /* Else will try to reuse lookahead token after shifting the error - token. */ - goto yyerrlab1; - - -/*---------------------------------------------------. -| yyerrorlab -- error raised explicitly by YYERROR. | -`---------------------------------------------------*/ -yyerrorlab: - - /* Pacify compilers like GCC when the user code never invokes - YYERROR and the label yyerrorlab therefore never appears in user - code. */ - if (/*CONSTCOND*/ 0) - goto yyerrorlab; - - /* Do not reclaim the symbols of the rule whose action triggered - this YYERROR. */ - YYPOPSTACK (yylen); - yylen = 0; - YY_STACK_PRINT (yyss, yyssp); - yystate = *yyssp; - goto yyerrlab1; - - -/*-------------------------------------------------------------. -| yyerrlab1 -- common code for both syntax error and YYERROR. | -`-------------------------------------------------------------*/ -yyerrlab1: - yyerrstatus = 3; /* Each real token shifted decrements this. */ - - for (;;) - { - yyn = yypact[yystate]; - if (!yypact_value_is_default (yyn)) - { - yyn += YYTERROR; - if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) - { - yyn = yytable[yyn]; - if (0 < yyn) - break; - } - } - - /* Pop the current state because it cannot handle the error token. */ - if (yyssp == yyss) - YYABORT; - - - yydestruct ("Error: popping", - yystos[yystate], yyvsp); - YYPOPSTACK (1); - yystate = *yyssp; - YY_STACK_PRINT (yyss, yyssp); - } - - YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN - *++yyvsp = yylval; - YY_IGNORE_MAYBE_UNINITIALIZED_END - - - /* Shift the error token. */ - YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); - - yystate = yyn; - goto yynewstate; - - -/*-------------------------------------. -| yyacceptlab -- YYACCEPT comes here. | -`-------------------------------------*/ -yyacceptlab: - yyresult = 0; - goto yyreturn; - -/*-----------------------------------. -| yyabortlab -- YYABORT comes here. | -`-----------------------------------*/ -yyabortlab: - yyresult = 1; - goto yyreturn; - -#if !defined yyoverflow || YYERROR_VERBOSE -/*-------------------------------------------------. -| yyexhaustedlab -- memory exhaustion comes here. | -`-------------------------------------------------*/ -yyexhaustedlab: - yyerror (YY_("memory exhausted")); - yyresult = 2; - /* Fall through. */ -#endif - -yyreturn: - if (yychar != YYEMPTY) - { - /* Make sure we have latest lookahead translation. See comments at - user semantic actions for why this is necessary. */ - yytoken = YYTRANSLATE (yychar); - yydestruct ("Cleanup: discarding lookahead", - yytoken, &yylval); - } - /* Do not reclaim the symbols of the rule whose action triggered - this YYABORT or YYACCEPT. */ - YYPOPSTACK (yylen); - YY_STACK_PRINT (yyss, yyssp); - while (yyssp != yyss) - { - yydestruct ("Cleanup: popping", - yystos[*yyssp], yyvsp); - YYPOPSTACK (1); - } -#ifndef yyoverflow - if (yyss != yyssa) - YYSTACK_FREE (yyss); -#endif -#if YYERROR_VERBOSE - if (yymsg != yymsgbuf) - YYSTACK_FREE (yymsg); -#endif - return yyresult; -} -#line 300 "ts1.0_grammar.y" /* yacc.c:1906 */ - -void yyerror(const char* s) -{ - errors.set("unrecognized token"); -} diff --git a/RenderSystems/GL/src/nvparse/_ts1.0_parser.h b/RenderSystems/GL/src/nvparse/_ts1.0_parser.h deleted file mode 100644 index e2328fae33f..00000000000 --- a/RenderSystems/GL/src/nvparse/_ts1.0_parser.h +++ /dev/null @@ -1,121 +0,0 @@ -/* A Bison parser, made by GNU Bison 3.0.2. */ - -/* Bison interface for Yacc-like parsers in C - - Copyright (C) 1984, 1989-1990, 2000-2013 Free Software Foundation, Inc. - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . */ - -/* As a special exception, you may create a larger work that contains - part or all of the Bison parser skeleton and distribute that work - under terms of your choice, so long as that work isn't itself a - parser generator using the skeleton or a modified version thereof - as a parser skeleton. Alternatively, if you modify or redistribute - the parser skeleton itself, you may (at your option) remove this - special exception, which will cause the skeleton and the resulting - Bison output files to be licensed under the GNU General Public - License without this special exception. - - This special exception was added by the Free Software Foundation in - version 2.2 of Bison. */ - -#ifndef YY_TS10_TS1_0_PARSER_H_INCLUDED -# define YY_TS10_TS1_0_PARSER_H_INCLUDED -/* Debug traces. */ -#ifndef YYDEBUG -# define YYDEBUG 0 -#endif -#if YYDEBUG -extern int ts10_debug; -#endif - -/* Token type. */ -#ifndef YYTOKENTYPE -# define YYTOKENTYPE - enum yytokentype - { - floatValue = 258, - gequal = 259, - less = 260, - texVariable = 261, - expandString = 262, - openParen = 263, - closeParen = 264, - semicolon = 265, - comma = 266, - nop = 267, - texture_1d = 268, - texture_2d = 269, - texture_rectangle = 270, - texture_3d = 271, - texture_cube_map = 272, - cull_fragment = 273, - pass_through = 274, - offset_2d_scale = 275, - offset_2d = 276, - offset_rectangle_scale = 277, - offset_rectangle = 278, - dependent_ar = 279, - dependent_gb = 280, - dot_product_2d_1of2 = 281, - dot_product_2d_2of2 = 282, - dot_product_rectangle_1of2 = 283, - dot_product_rectangle_2of2 = 284, - dot_product_depth_replace_1of2 = 285, - dot_product_depth_replace_2of2 = 286, - dot_product_3d_1of3 = 287, - dot_product_3d_2of3 = 288, - dot_product_3d_3of3 = 289, - dot_product_cube_map_1of3 = 290, - dot_product_cube_map_2of3 = 291, - dot_product_cube_map_3of3 = 292, - dot_product_reflect_cube_map_eye_from_qs_1of3 = 293, - dot_product_reflect_cube_map_eye_from_qs_2of3 = 294, - dot_product_reflect_cube_map_eye_from_qs_3of3 = 295, - dot_product_reflect_cube_map_const_eye_1of3 = 296, - dot_product_reflect_cube_map_const_eye_2of3 = 297, - dot_product_reflect_cube_map_const_eye_3of3 = 298, - dot_product_cube_map_and_reflect_cube_map_eye_from_qs_1of3 = 299, - dot_product_cube_map_and_reflect_cube_map_eye_from_qs_2of3 = 300, - dot_product_cube_map_and_reflect_cube_map_eye_from_qs_3of3 = 301, - dot_product_cube_map_and_reflect_cube_map_const_eye_1of3 = 302, - dot_product_cube_map_and_reflect_cube_map_const_eye_2of3 = 303, - dot_product_cube_map_and_reflect_cube_map_const_eye_3of3 = 304 - }; -#endif - -/* Value type. */ -#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED -typedef union YYSTYPE YYSTYPE; -union YYSTYPE -{ -#line 18 "ts1.0_grammar.y" /* yacc.c:1909 */ - - float fval; - InstPtr inst; - InstListPtr instList; - MappedVariablePtr variable; - -#line 111 "_ts1.0_parser.h" /* yacc.c:1909 */ -}; -# define YYSTYPE_IS_TRIVIAL 1 -# define YYSTYPE_IS_DECLARED 1 -#endif - - -extern YYSTYPE ts10_lval; - -int ts10_parse (void); - -#endif /* !YY_TS10_TS1_0_PARSER_H_INCLUDED */ diff --git a/RenderSystems/GL/src/nvparse/_vs1.0_lexer.cpp b/RenderSystems/GL/src/nvparse/_vs1.0_lexer.cpp deleted file mode 100644 index 6a8ab678fe4..00000000000 --- a/RenderSystems/GL/src/nvparse/_vs1.0_lexer.cpp +++ /dev/null @@ -1,5050 +0,0 @@ -#define yy_create_buffer vs10__create_buffer -#define yy_delete_buffer vs10__delete_buffer -#define yy_scan_buffer vs10__scan_buffer -#define yy_scan_string vs10__scan_string -#define yy_scan_bytes vs10__scan_bytes -#define yy_flex_debug vs10__flex_debug -#define yy_init_buffer vs10__init_buffer -#define yy_flush_buffer vs10__flush_buffer -#define yy_load_buffer_state vs10__load_buffer_state -#define yy_switch_to_buffer vs10__switch_to_buffer -#define yyin vs10_in -#define yyleng vs10_leng -#define yylex vs10_lex -#define yyout vs10_out -#define yyrestart vs10_restart -#define yytext vs10_text -#define yywrap vs10_wrap - -#line 20 "_vs1.0_lexer.cpp" -/* A lexical scanner generated by flex */ - -/* Scanner skeleton version: - * $Header: /home/daffy/u0/vern/flex/RCS/flex.skl,v 2.91 96/09/10 16:58:48 vern Exp $ - */ - -#define FLEX_SCANNER -#define YY_FLEX_MAJOR_VERSION 2 -#define YY_FLEX_MINOR_VERSION 5 - -#include -#include - -/* cfront 1.2 defines "c_plusplus" instead of "__cplusplus" */ -#ifdef c_plusplus -#ifndef __cplusplus -#define __cplusplus -#endif -#endif - - -#ifdef __cplusplus - -#include -#ifndef _WIN32 -#include -#endif - -/* Use prototypes in function declarations. */ -#define YY_USE_PROTOS - -/* The "const" storage-class-modifier is valid. */ -#define YY_USE_CONST - -#else /* ! __cplusplus */ - -#if __STDC__ - -#define YY_USE_PROTOS -#define YY_USE_CONST - -#endif /* __STDC__ */ -#endif /* ! __cplusplus */ - -#ifdef __TURBOC__ - #pragma warn -rch - #pragma warn -use -#include -#include -#define YY_USE_CONST -#define YY_USE_PROTOS -#endif - -#ifdef YY_USE_CONST -#define yyconst const -#else -#define yyconst -#endif - - -#ifdef YY_USE_PROTOS -#define YY_PROTO(proto) proto -#else -#define YY_PROTO(proto) () -#endif - - -/* Returned upon end-of-file. */ -#define YY_NULL 0 - -/* Promotes a possibly negative, possibly signed char to an unsigned - * integer for use as an array index. If the signed char is negative, - * we want to instead treat it as an 8-bit unsigned char, hence the - * double cast. - */ -#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) - -/* Enter a start condition. This macro really ought to take a parameter, - * but we do it the disgusting crufty way forced on us by the ()-less - * definition of BEGIN. - */ -#define BEGIN yy_start = 1 + 2 * - -/* Translate the current start state into a value that can be later handed - * to BEGIN to return to the state. The YYSTATE alias is for lex - * compatibility. - */ -#define YY_START ((yy_start - 1) / 2) -#define YYSTATE YY_START - -/* Action number for EOF rule of a given start state. */ -#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) - -/* Special action meaning "start processing a new file". */ -#define YY_NEW_FILE yyrestart( yyin ) - -#define YY_END_OF_BUFFER_CHAR 0 - -/* Size of default input buffer. */ -#define YY_BUF_SIZE 16384 - -typedef struct yy_buffer_state *YY_BUFFER_STATE; - -extern int yyleng; -extern FILE *yyin, *yyout; - -#define EOB_ACT_CONTINUE_SCAN 0 -#define EOB_ACT_END_OF_FILE 1 -#define EOB_ACT_LAST_MATCH 2 - -/* The funky do-while in the following #define is used to turn the definition - * int a single C statement (which needs a semi-colon terminator). This - * avoids problems with code like: - * - * if ( condition_holds ) - * yyless( 5 ); - * else - * do_something_else(); - * - * Prior to using the do-while the compiler would get upset at the - * "else" because it interpreted the "if" statement as being all - * done when it reached the ';' after the yyless() call. - */ - -/* Return all but the first 'n' matched characters back to the input stream. */ - -#define yyless(n) \ - do \ - { \ - /* Undo effects of setting up yytext. */ \ - *yy_cp = yy_hold_char; \ - YY_RESTORE_YY_MORE_OFFSET \ - yy_c_buf_p = yy_cp = yy_bp + n - YY_MORE_ADJ; \ - YY_DO_BEFORE_ACTION; /* set up yytext again */ \ - } \ - while ( 0 ) - -#define unput(c) yyunput( c, yytext_ptr ) - -/* The following is because we cannot portably get our hands on size_t - * (without autoconf's help, which isn't available because we want - * flex-generated scanners to compile on their own). - */ -typedef unsigned int yy_size_t; - - -struct yy_buffer_state - { - FILE *yy_input_file; - - char *yy_ch_buf; /* input buffer */ - char *yy_buf_pos; /* current position in input buffer */ - - /* Size of input buffer in bytes, not including room for EOB - * characters. - */ - yy_size_t yy_buf_size; - - /* Number of characters read into yy_ch_buf, not including EOB - * characters. - */ - int yy_n_chars; - - /* Whether we "own" the buffer - i.e., we know we created it, - * and can realloc() it to grow it, and should free() it to - * delete it. - */ - int yy_is_our_buffer; - - /* Whether this is an "interactive" input source; if so, and - * if we're using stdio for input, then we want to use getc() - * instead of fread(), to make sure we stop fetching input after - * each newline. - */ - int yy_is_interactive; - - /* Whether we're considered to be at the beginning of a line. - * If so, '^' rules will be active on the next match, otherwise - * not. - */ - int yy_at_bol; - - /* Whether to try to fill the input buffer when we reach the - * end of it. - */ - int yy_fill_buffer; - - int yy_buffer_status; -#define YY_BUFFER_NEW 0 -#define YY_BUFFER_NORMAL 1 - /* When an EOF's been seen but there's still some text to process - * then we mark the buffer as YY_EOF_PENDING, to indicate that we - * shouldn't try reading from the input source any more. We might - * still have a bunch of tokens to match, though, because of - * possible backing-up. - * - * When we actually see the EOF, we change the status to "new" - * (via yyrestart()), so that the user can continue scanning by - * just pointing yyin at a new input file. - */ -#define YY_BUFFER_EOF_PENDING 2 - }; - -static YY_BUFFER_STATE yy_current_buffer = 0; - -/* We provide macros for accessing buffer states in case in the - * future we want to put the buffer states in a more general - * "scanner state". - */ -#define YY_CURRENT_BUFFER yy_current_buffer - - -/* yy_hold_char holds the character lost when yytext is formed. */ -static char yy_hold_char; - -static int yy_n_chars; /* number of characters read into yy_ch_buf */ - - -int yyleng; - -/* Points to current character in buffer. */ -static char *yy_c_buf_p = (char *) 0; -static int yy_init = 1; /* whether we need to initialize */ -static int yy_start = 0; /* start state number */ - -/* Flag which is used to allow yywrap()'s to do buffer switches - * instead of setting up a fresh yyin. A bit of a hack ... - */ -static int yy_did_buffer_switch_on_eof; - -void yyrestart YY_PROTO(( FILE *input_file )); - -void yy_switch_to_buffer YY_PROTO(( YY_BUFFER_STATE new_buffer )); -void yy_load_buffer_state YY_PROTO(( void )); -YY_BUFFER_STATE yy_create_buffer YY_PROTO(( FILE *file, int size )); -void yy_delete_buffer YY_PROTO(( YY_BUFFER_STATE b )); -void yy_init_buffer YY_PROTO(( YY_BUFFER_STATE b, FILE *file )); -void yy_flush_buffer YY_PROTO(( YY_BUFFER_STATE b )); -#define YY_FLUSH_BUFFER yy_flush_buffer( yy_current_buffer ) - -YY_BUFFER_STATE yy_scan_buffer YY_PROTO(( char *base, yy_size_t size )); -YY_BUFFER_STATE yy_scan_string YY_PROTO(( yyconst char *yy_str )); -YY_BUFFER_STATE yy_scan_bytes YY_PROTO(( yyconst char *bytes, int len )); - -static void *yy_flex_alloc YY_PROTO(( yy_size_t )); -static void *yy_flex_realloc YY_PROTO(( void *, yy_size_t )); -static void yy_flex_free YY_PROTO(( void * )); - -#define yy_new_buffer yy_create_buffer - -#define yy_set_interactive(is_interactive) \ - { \ - if ( ! yy_current_buffer ) \ - yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \ - yy_current_buffer->yy_is_interactive = is_interactive; \ - } - -#define yy_set_bol(at_bol) \ - { \ - if ( ! yy_current_buffer ) \ - yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \ - yy_current_buffer->yy_at_bol = at_bol; \ - } - -#define YY_AT_BOL() (yy_current_buffer->yy_at_bol) - - -#define YY_USES_REJECT -typedef unsigned char YY_CHAR; -FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0; -typedef int yy_state_type; -extern char *yytext; -#define yytext_ptr yytext - -static yy_state_type yy_get_previous_state YY_PROTO(( void )); -static yy_state_type yy_try_NUL_trans YY_PROTO(( yy_state_type current_state )); -static int yy_get_next_buffer YY_PROTO(( void )); -static void yy_fatal_error YY_PROTO(( yyconst char msg[] )); - -/* Done after the current pattern has been matched and before the - * corresponding action - sets up yytext. - */ -#define YY_DO_BEFORE_ACTION \ - yytext_ptr = yy_bp; \ - yyleng = (int) (yy_cp - yy_bp); \ - yy_hold_char = *yy_cp; \ - *yy_cp = '\0'; \ - yy_c_buf_p = yy_cp; - -#define YY_NUM_RULES 72 -#define YY_END_OF_BUFFER 73 -static yyconst short int yy_acclist[406] = - { 0, - 2, 2, 56, 56, 46, 46, 31, 31, 29, 29, - 73, 69, 71, 72, 64, 69, 71, 72, 66, 69, - 72, 71, 72, 71, 72, 63, 71, 72, 63, 71, - 72, 37, 63, 71, 72, 63, 71, 72, 36, 71, - 72, 13, 71, 72, 62, 71, 72, 62, 63, 71, - 72, 62, 71, 72, 62, 71, 72, 62, 71, 72, - 62, 71, 72, 62, 71, 72, 64, 69, 71, 72, - 16, 63, 71, 72, 72, 72, 22, 65, 72, 21, - 72, 23, 72, 72, 34, 72, 72, 20, 72, 68, - 70, 72, 68, 72, 70, 72, 67, 70, 72, 2, - - 72, 1, 72, 41, 72, 41, 42, 72, 56, 72, - 56, 72, 57, 72, 56, 72, 56, 72, 56, 72, - 50, 72, 46, 50, 72, 49, 72, 48, 72, 50, - 72, 47, 50, 72, 72, 72, 59, 72, 72, 72, - 61, 72, 72, 40, 72, 40, 62, 72, 39, 40, - 62, 72, 45, 72, 44, 45, 72, 43, 45, 72, - 72, 27, 72, 31, 72, 31, 72, 32, 72, 31, - 72, 29, 72, 30, 72, 51, 72, 64, 15, 17, - 14, 36, 13, 62, 62, 3, 62, 6, 62, 62, - 62, 62, 62, 5, 62, 4, 62, 62, 64, 16, - - 16, 19, 34, 20, 67, 2, 1, 41, 56, 56, - 56, 56, 17, 56, 56, 54, 56, 50, 46, 50, - 47, 50, 47, 50, 47, 59, 61, 60, 61, 39, - 39, 39, 62, 44, 27, 31, 31, 31, 31, 29, - 51, 53, 51, 51, 14, 12, 12, 62, 3, 12, - 3, 12, 6, 12, 6, 12, 8, 62, 62, 62, - 62, 7, 62, 5, 12, 5, 12, 4, 12, 4, - 12, 16, 56, 39, 62, 31, 31, 31, 52, 3, - 3, 6, 6, 8, 12, 8, 12, 9, 62, 10, - 62, 11, 62, 7, 12, 7, 12, 5, 5, 4, - - 4, 55, 56, 38, 39, 62, 31, 31, 26, 8, - 8, 9, 12, 9, 12, 10, 12, 10, 12, 11, - 12, 11, 12, 7, 7, 55, 56, 56, 55, 56, - 58, 59, 38, 39, 38, 39, 26, 31, 31, 26, - 26, 28, 9, 9, 10, 10, 11, 11, 35, 55, - 56, 55, 56, 55, 56, 55, 56, 26, 31, 31, - 26, 31, 28, 31, 26, 26, 26, 28, 28, 24, - 35, 35, 55, 56, 55, 56, 26, 31, 26, 31, - 26, 31, 28, 31, 31, 28, 31, 33, 26, 28, - 28, 28, 25, 26, 31, 28, 31, 28, 31, 28, - - 31, 28, 18, 28, 31 - } ; - -static yyconst short int yy_accept[330] = - { 0, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 2, 3, 3, - 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 8, 9, 10, 11, 11, - 11, 12, 15, 19, 22, 24, 26, 29, 32, 36, - 39, 42, 45, 48, 52, 55, 58, 61, 64, 67, - 71, 75, 76, 77, 80, 82, 84, 85, 87, 88, - 90, 93, 95, 97, 100, 102, 104, 106, 109, 111, - 113, 115, 117, 119, 121, 123, 126, 128, 130, 132, - 135, 136, 137, 139, 140, 141, 143, 144, 146, 149, - - 153, 155, 158, 161, 162, 164, 166, 168, 170, 172, - 174, 176, 178, 179, 179, 179, 179, 179, 179, 180, - 181, 182, 183, 184, 185, 186, 188, 190, 191, 192, - 193, 194, 196, 198, 199, 200, 201, 202, 202, 203, - 203, 204, 204, 205, 206, 207, 208, 209, 210, 211, - 212, 213, 215, 216, 217, 218, 219, 221, 223, 225, - 226, 226, 227, 227, 227, 227, 227, 228, 228, 230, - 231, 232, 234, 235, 235, 236, 237, 238, 239, 240, - 241, 243, 244, 244, 244, 245, 245, 245, 245, 245, - 245, 245, 246, 247, 249, 251, 253, 255, 257, 259, - - 260, 261, 262, 264, 266, 268, 270, 272, 272, 273, - 274, 274, 276, 277, 278, 279, 279, 280, 280, 280, - 280, 280, 280, 280, 281, 282, 283, 284, 286, 288, - 290, 292, 294, 296, 298, 299, 300, 301, 302, 302, - 304, 304, 307, 308, 309, 309, 310, 310, 310, 310, - 310, 311, 312, 314, 316, 318, 320, 322, 324, 325, - 326, 326, 328, 329, 331, 331, 333, 335, 337, 339, - 340, 340, 341, 341, 342, 343, 343, 343, 343, 344, - 345, 346, 347, 348, 349, 350, 352, 354, 356, 358, - 360, 361, 363, 365, 365, 366, 367, 368, 369, 369, - - 370, 371, 371, 371, 372, 373, 375, 377, 379, 381, - 383, 385, 386, 388, 389, 390, 391, 392, 393, 394, - 394, 396, 398, 400, 402, 403, 404, 406, 406 - } ; - -static yyconst int yy_ec[256] = - { 0, - 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 2, 4, 4, 5, 4, 6, 4, 4, 7, - 8, 9, 10, 11, 6, 12, 13, 14, 14, 14, - 14, 14, 14, 14, 14, 14, 14, 4, 15, 6, - 4, 6, 4, 4, 16, 16, 16, 17, 16, 18, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 19, - 16, 16, 16, 20, 16, 16, 16, 16, 16, 16, - 6, 21, 6, 4, 22, 4, 23, 16, 24, 25, - - 26, 27, 28, 16, 29, 16, 16, 30, 31, 32, - 33, 16, 16, 34, 35, 36, 37, 38, 39, 39, - 39, 39, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4 - } ; - -static yyconst int yy_meta[40] = - { 0, - 1, 2, 3, 1, 1, 1, 2, 1, 1, 1, - 4, 1, 1, 5, 1, 5, 5, 5, 5, 5, - 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5 - } ; - -static yyconst short int yy_base[369] = - { 0, - 0, 38, 764, 763, 761, 760, 759, 758, 757, 756, - 755, 754, 753, 752, 48, 69, 751, 750, 39, 84, - 86, 90, 93, 107, 41, 95, 44, 80, 122, 0, - 112, 160, 749, 748, 163, 167, 747, 746, 740, 739, - 746, 767, 100, 767, 767, 148, 767, 173, 767, 53, - 731, 0, 722, 0, 157, 164, 163, 170, 173, 186, - 187, 740, 767, 767, 767, 767, 739, 767, 738, 767, - 767, 767, 767, 0, 737, 767, 0, 0, 718, 191, - 767, 185, 195, 178, 0, 736, 767, 767, 724, 725, - 732, 198, 767, 199, 200, 767, 201, 767, 0, 211, - - 767, 732, 767, 730, 767, 0, 213, 767, 706, 0, - 767, 217, 221, 705, 704, 175, 201, 232, 767, 767, - 0, 715, 0, 234, 0, 237, 239, 241, 243, 245, - 255, 268, 270, 277, 281, 726, 272, 724, 767, 723, - 767, 722, 767, 0, 721, 767, 0, 702, 285, 283, - 228, 701, 291, 767, 43, 0, 719, 709, 708, 0, - 715, 767, 293, 222, 295, 206, 767, 208, 767, 298, - 767, 300, 715, 713, 767, 0, 303, 689, 232, 0, - 308, 711, 700, 709, 294, 679, 683, 674, 683, 282, - 683, 0, 767, 0, 314, 767, 322, 767, 324, 328, - - 330, 332, 339, 334, 767, 341, 767, 692, 703, 297, - 82, 345, 672, 668, 675, 692, 767, 661, 659, 651, - 644, 640, 630, 355, 767, 357, 767, 360, 767, 366, - 368, 370, 372, 767, 374, 767, 376, 767, 254, 378, - 379, 383, 629, 606, 599, 381, 603, 598, 593, 558, - 395, 767, 398, 767, 400, 767, 402, 767, 404, 767, - 502, 406, 374, 396, 410, 767, 412, 767, 416, 453, - 439, 420, 445, 336, 421, 452, 423, 395, 422, 767, - 435, 767, 437, 767, 439, 430, 431, 434, 454, 446, - 403, 351, 458, 408, 413, 417, 449, 461, 376, 453, - - 353, 343, 314, 475, 767, 466, 480, 457, 471, 475, - 483, 309, 476, 311, 479, 484, 487, 490, 250, 162, - 491, 494, 495, 498, 499, 115, 502, 767, 517, 522, - 527, 532, 537, 542, 547, 552, 557, 562, 567, 572, - 577, 582, 587, 592, 95, 89, 597, 602, 607, 40, - 612, 617, 622, 627, 632, 637, 642, 647, 652, 657, - 662, 667, 672, 677, 682, 687, 692, 697 - } ; - -static yyconst short int yy_def[369] = - { 0, - 328, 1, 329, 329, 330, 330, 330, 330, 330, 330, - 331, 331, 332, 332, 333, 333, 334, 334, 335, 335, - 336, 336, 337, 337, 338, 338, 339, 339, 328, 29, - 340, 340, 341, 341, 342, 342, 343, 343, 330, 330, - 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, - 328, 344, 345, 346, 345, 345, 345, 345, 345, 328, - 328, 347, 328, 328, 328, 328, 348, 328, 349, 328, - 328, 328, 328, 350, 351, 328, 352, 352, 353, 353, - 328, 353, 353, 353, 354, 354, 328, 328, 354, 355, - 356, 356, 328, 356, 357, 328, 357, 328, 346, 346, - - 328, 328, 328, 358, 328, 359, 359, 328, 359, 360, - 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, - 361, 328, 344, 345, 346, 345, 345, 345, 345, 345, - 345, 345, 345, 345, 328, 328, 328, 347, 328, 348, - 328, 349, 328, 350, 351, 328, 352, 353, 353, 353, - 353, 353, 353, 328, 353, 354, 354, 355, 355, 362, - 356, 328, 356, 356, 356, 357, 328, 357, 328, 328, - 328, 346, 328, 358, 328, 359, 359, 359, 359, 360, - 328, 328, 328, 363, 328, 328, 328, 328, 328, 328, - 328, 361, 328, 346, 328, 328, 328, 328, 345, 345, - - 345, 345, 345, 328, 328, 328, 328, 328, 328, 353, - 356, 346, 359, 359, 359, 363, 328, 328, 328, 328, - 328, 328, 328, 328, 328, 328, 328, 328, 328, 345, - 345, 345, 328, 328, 328, 328, 328, 328, 328, 353, - 356, 346, 359, 359, 328, 328, 328, 328, 328, 328, - 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, - 328, 353, 353, 364, 356, 328, 328, 328, 359, 359, - 328, 328, 328, 365, 328, 328, 328, 328, 328, 328, - 328, 328, 328, 328, 328, 364, 364, 364, 364, 359, - 359, 366, 359, 328, 365, 365, 365, 328, 328, 367, - - 328, 328, 328, 328, 328, 364, 364, 366, 366, 366, - 359, 359, 368, 328, 365, 367, 367, 367, 328, 328, - 366, 368, 368, 368, 367, 328, 368, 0, 328, 328, - 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, - 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, - 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, - 328, 328, 328, 328, 328, 328, 328, 328 - } ; - -static yyconst short int yy_nxt[807] = - { 0, - 42, 43, 44, 45, 46, 47, 47, 47, 47, 48, - 47, 49, 50, 51, 52, 53, 53, 53, 53, 53, - 45, 54, 55, 56, 53, 53, 53, 53, 53, 53, - 53, 53, 57, 58, 53, 53, 53, 59, 53, 60, - 63, 78, 92, 93, 144, 63, 96, 61, 71, 71, - 72, 73, 73, 73, 73, 73, 73, 73, 73, 73, - 73, 120, 73, 149, 97, 121, 94, 210, 73, 71, - 71, 72, 73, 73, 73, 73, 73, 73, 73, 73, - 73, 73, 96, 73, 162, 63, 78, 80, 81, 73, - 63, 80, 81, 125, 86, 87, 92, 93, 82, 124, - - 97, 113, 82, 88, 114, 89, 83, 90, 86, 87, - 83, 84, 241, 102, 63, 84, 326, 88, 103, 89, - 94, 90, 98, 98, 63, 98, 98, 98, 98, 98, - 98, 98, 98, 98, 98, 98, 98, 99, 99, 99, - 99, 99, 98, 99, 99, 99, 99, 99, 99, 99, - 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, - 100, 102, 63, 326, 107, 108, 103, 109, 107, 108, - 126, 109, 115, 116, 118, 119, 117, 127, 125, 128, - 129, 130, 131, 132, 125, 125, 133, 135, 137, 119, - 114, 125, 150, 152, 125, 136, 153, 154, 149, 163, - - 162, 162, 167, 169, 188, 149, 189, 134, 167, 155, - 169, 149, 170, 171, 177, 149, 151, 178, 181, 182, - 168, 168, 113, 164, 162, 114, 168, 190, 168, 183, - 165, 184, 191, 118, 119, 193, 193, 185, 195, 196, - 197, 198, 193, 193, 193, 193, 193, 193, 149, 172, - 126, 319, 127, 165, 199, 194, 193, 193, 194, 155, - 194, 214, 194, 215, 194, 261, 194, 239, 203, 204, - 205, 206, 207, 137, 119, 200, 194, 201, 193, 193, - 202, 132, 135, 133, 150, 114, 153, 154, 208, 194, - 136, 194, 153, 154, 163, 162, 182, 162, 194, 170, - - 171, 170, 171, 149, 177, 149, 221, 178, 151, 181, - 182, 149, 314, 222, 185, 224, 225, 149, 164, 211, - 183, 313, 184, 226, 227, 228, 229, 240, 185, 193, - 193, 193, 193, 193, 193, 235, 236, 199, 212, 320, - 233, 234, 237, 238, 319, 194, 170, 171, 296, 194, - 297, 194, 203, 194, 301, 230, 224, 225, 226, 227, - 194, 251, 252, 309, 231, 310, 232, 253, 254, 255, - 256, 257, 258, 259, 260, 235, 236, 237, 238, 262, - 265, 266, 272, 242, 267, 268, 264, 194, 300, 194, - 263, 194, 264, 273, 149, 274, 251, 252, 149, 279, - - 280, 281, 282, 283, 284, 259, 260, 262, 287, 314, - 288, 265, 266, 267, 268, 292, 289, 290, 263, 303, - 264, 272, 298, 279, 280, 296, 149, 297, 291, 315, - 292, 297, 273, 299, 274, 300, 281, 282, 283, 284, - 304, 305, 287, 306, 288, 288, 287, 290, 288, 302, - 289, 289, 285, 301, 289, 307, 154, 274, 291, 311, - 292, 296, 298, 297, 294, 317, 287, 318, 288, 309, - 312, 310, 313, 299, 289, 300, 304, 305, 306, 293, - 288, 307, 154, 321, 311, 310, 289, 309, 323, 310, - 324, 315, 287, 297, 288, 312, 317, 313, 318, 325, - - 289, 318, 317, 321, 318, 310, 323, 327, 324, 324, - 323, 325, 324, 318, 327, 285, 324, 62, 62, 62, - 62, 62, 63, 63, 63, 63, 63, 67, 67, 67, - 67, 67, 69, 69, 69, 69, 69, 74, 74, 74, - 74, 74, 75, 75, 75, 75, 75, 77, 77, 77, - 77, 77, 79, 79, 79, 79, 79, 85, 85, 85, - 85, 85, 91, 91, 91, 91, 91, 95, 95, 95, - 95, 95, 101, 101, 101, 101, 101, 104, 104, 104, - 104, 104, 106, 106, 106, 106, 106, 110, 110, 110, - 110, 110, 123, 123, 278, 123, 123, 138, 138, 138, - - 138, 138, 140, 140, 140, 140, 140, 142, 142, 142, - 142, 142, 145, 145, 145, 145, 145, 147, 277, 147, - 147, 147, 148, 148, 276, 148, 148, 156, 156, 275, - 271, 156, 159, 159, 270, 159, 159, 161, 161, 161, - 161, 161, 166, 166, 166, 166, 166, 174, 174, 174, - 174, 174, 176, 176, 269, 176, 176, 180, 180, 250, - 180, 180, 192, 192, 249, 192, 192, 160, 160, 248, - 160, 160, 216, 216, 216, 216, 216, 286, 286, 247, - 286, 286, 295, 295, 246, 295, 295, 308, 308, 245, - 308, 308, 316, 316, 217, 316, 316, 322, 322, 244, - - 322, 322, 243, 215, 209, 239, 223, 220, 219, 218, - 189, 217, 184, 182, 213, 175, 173, 162, 160, 160, - 157, 149, 149, 146, 143, 141, 139, 209, 122, 187, - 186, 179, 175, 173, 162, 160, 158, 157, 149, 146, - 143, 141, 139, 125, 122, 328, 112, 112, 111, 111, - 105, 105, 76, 76, 70, 70, 68, 68, 66, 66, - 65, 65, 64, 64, 63, 63, 41, 328, 328, 328, - 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, - 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, - 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, - - 328, 328, 328, 328, 328, 328 - } ; - -static yyconst short int yy_chk[807] = - { 0, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, - 19, 19, 25, 25, 350, 19, 27, 2, 15, 15, - 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, - 15, 50, 15, 155, 27, 50, 25, 155, 15, 16, - 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, - 16, 16, 28, 16, 211, 20, 20, 21, 21, 16, - 20, 22, 22, 346, 23, 23, 26, 26, 21, 345, - - 28, 43, 22, 23, 43, 23, 21, 23, 24, 24, - 22, 21, 211, 31, 31, 22, 326, 24, 31, 24, - 26, 24, 29, 29, 29, 29, 29, 29, 29, 29, - 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, - 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, - 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, - 29, 32, 32, 320, 35, 35, 32, 35, 36, 36, - 55, 36, 46, 46, 48, 48, 46, 56, 55, 57, - 57, 57, 57, 58, 57, 56, 59, 60, 61, 61, - 60, 58, 80, 82, 59, 60, 83, 83, 84, 92, - - 92, 94, 95, 97, 116, 82, 116, 59, 166, 84, - 168, 80, 100, 100, 107, 83, 80, 107, 112, 112, - 95, 97, 113, 92, 164, 113, 166, 117, 168, 112, - 94, 112, 117, 118, 118, 124, 124, 112, 126, 126, - 127, 127, 128, 128, 129, 129, 130, 130, 151, 100, - 126, 319, 127, 164, 128, 124, 131, 131, 126, 151, - 127, 179, 128, 179, 129, 239, 130, 239, 131, 132, - 132, 133, 133, 137, 137, 129, 131, 130, 134, 134, - 130, 132, 135, 133, 150, 135, 149, 149, 134, 132, - 135, 133, 153, 153, 163, 163, 185, 165, 134, 170, - - 170, 172, 172, 150, 177, 149, 190, 177, 150, 181, - 181, 153, 314, 190, 185, 195, 195, 210, 163, 165, - 181, 312, 181, 197, 197, 199, 199, 210, 181, 200, - 200, 201, 201, 202, 202, 204, 204, 199, 172, 303, - 203, 203, 206, 206, 302, 199, 212, 212, 274, 200, - 274, 201, 203, 202, 301, 200, 224, 224, 226, 226, - 203, 228, 228, 292, 201, 292, 202, 230, 230, 231, - 231, 232, 232, 233, 233, 235, 235, 237, 237, 240, - 241, 241, 246, 212, 242, 242, 263, 230, 299, 231, - 240, 232, 240, 246, 263, 246, 251, 251, 240, 253, - - 253, 255, 255, 257, 257, 259, 259, 262, 264, 294, - 264, 265, 265, 267, 267, 291, 264, 269, 262, 278, - 262, 272, 275, 279, 279, 295, 262, 295, 269, 296, - 269, 296, 272, 275, 272, 275, 281, 281, 283, 283, - 285, 285, 286, 287, 286, 287, 288, 290, 288, 277, - 286, 287, 285, 276, 288, 289, 289, 273, 290, 293, - 290, 297, 298, 297, 271, 300, 289, 300, 289, 308, - 293, 308, 293, 298, 289, 298, 304, 304, 306, 270, - 306, 307, 307, 309, 311, 309, 306, 310, 313, 310, - 313, 315, 307, 315, 307, 311, 316, 311, 316, 317, - - 307, 317, 318, 321, 318, 321, 322, 323, 322, 323, - 324, 325, 324, 325, 327, 261, 327, 329, 329, 329, - 329, 329, 330, 330, 330, 330, 330, 331, 331, 331, - 331, 331, 332, 332, 332, 332, 332, 333, 333, 333, - 333, 333, 334, 334, 334, 334, 334, 335, 335, 335, - 335, 335, 336, 336, 336, 336, 336, 337, 337, 337, - 337, 337, 338, 338, 338, 338, 338, 339, 339, 339, - 339, 339, 340, 340, 340, 340, 340, 341, 341, 341, - 341, 341, 342, 342, 342, 342, 342, 343, 343, 343, - 343, 343, 344, 344, 250, 344, 344, 347, 347, 347, - - 347, 347, 348, 348, 348, 348, 348, 349, 349, 349, - 349, 349, 351, 351, 351, 351, 351, 352, 249, 352, - 352, 352, 353, 353, 248, 353, 353, 354, 354, 247, - 245, 354, 355, 355, 244, 355, 355, 356, 356, 356, - 356, 356, 357, 357, 357, 357, 357, 358, 358, 358, - 358, 358, 359, 359, 243, 359, 359, 360, 360, 223, - 360, 360, 361, 361, 222, 361, 361, 362, 362, 221, - 362, 362, 363, 363, 363, 363, 363, 364, 364, 220, - 364, 364, 365, 365, 219, 365, 365, 366, 366, 218, - 366, 366, 367, 367, 216, 367, 367, 368, 368, 215, - - 368, 368, 214, 213, 209, 208, 191, 189, 188, 187, - 186, 184, 183, 182, 178, 174, 173, 161, 159, 158, - 157, 152, 148, 145, 142, 140, 138, 136, 122, 115, - 114, 109, 104, 102, 91, 90, 89, 86, 79, 75, - 69, 67, 62, 53, 51, 41, 40, 39, 38, 37, - 34, 33, 18, 17, 14, 13, 12, 11, 10, 9, - 8, 7, 6, 5, 4, 3, 328, 328, 328, 328, - 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, - 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, - 328, 328, 328, 328, 328, 328, 328, 328, 328, 328, - - 328, 328, 328, 328, 328, 328 - } ; - -static yy_state_type yy_state_buf[YY_BUF_SIZE + 2], *yy_state_ptr; -static char *yy_full_match; -static int yy_lp; -#define REJECT \ -{ \ -*yy_cp = yy_hold_char; /* undo effects of setting up yytext */ \ -yy_cp = yy_full_match; /* restore poss. backed-over text */ \ -++yy_lp; \ -goto find_rule; \ -} -#define yymore() yymore_used_but_not_detected -#define YY_MORE_ADJ 0 -#define YY_RESTORE_YY_MORE_OFFSET -char *yytext; -#line 1 "vs1.0_tokens.l" -#define INITIAL 0 -#define INCLUDE 1 -#define DEFINE 2 -#define DEFSTR 3 -#define DEFSPACE 4 -#define SKIPLINE 5 -#define EATCOMMENT 6 -#define EATSTRING 7 -#define SAVELINE 8 - -#define MACRONAME 9 -#define MACROBODY 10 -#define MACROPARM 11 -#define EATMACRO 12 -#define EATDEFINE 13 -#define MODIFIER 14 -#define MACROPARMSTART 15 - -#define IFDEFNAME 16 -#define IFDEFBODY 17 -#define ENDMACRO 18 -#define MACROPARMEND 19 - -#line 8 "vs1.0_tokens.l" - -#include -#include -#ifdef _WIN32 -#include -# ifdef __GNUC__ -# include -# include -# endif -#else -#include -#include -#define _stat stat -#define _open open -#define _O_RDONLY O_RDONLY -#define _fstat fstat -#define _close close -#define stricmp strcasecmp - -#endif -#include -#include -#include -#include "macro.h" -#include "nvparse_errors.h" -#include "vs1.0_inst_list.h" -#include "_vs1.0_parser.h" -#define yylineno line_number -#include "nvparse_externs.h" -#define YY_NO_UNPUT - -int line_incr; -void LexError(const char *format, ...); -void LexWarning(const char *format, ...); -char *ReadTextFile(const char * filename); - -unsigned int MakeRegisterMask(char *findName); -unsigned int FindSwizzleValue(char *swizzleText); - - -enum ERROR_VALUES { - ERROR_NONE = 0, - ERROR_MEMORY_ALLOC, - ERROR_FILE_OPEN, - ERROR_UNSUCCESSFUL_ASSEMBLE, - ERROR_TOO_MANY_PARMS, - ERROR_DEST_WRITE, - ERROR_LIST_OPEN, - ERROR_DEST_OPEN, - ERROR_NO_ARGUMENTS, - ERROR_MACRO_OVERRUN -}; - - - -//extern void GenSwitchFileNames(char *fileName); -//extern unsigned int gLinesAssembled; -unsigned int gLinesAssembled; - -#define YY_INPUT(buf,result,max_size) \ -{ \ - int c = *myin++; \ - result = (c == 0) ? YY_NULL : (buf[0] = c, 1); \ -} - -#define SAFEDELETEARRAY(x) if ((x) != NULL) \ - delete [] (x) -#define SAFEFREE(x) if ((x) != NULL) \ - free((x)) - -#define MAXREPLACESTRING 255 - -char gReplaceText[MAXREPLACESTRING+1]; - -// -// forward prototypes for macro functions -// -void MacroIncFunction(char *, unsigned int *, char **); -void MacroDecFunction(char *, unsigned int *, char **); -void MacroAddFunction(char *, unsigned int *, char **); -void MacroSubFunction(char *, unsigned int *, char **); - -MACROFUNCTIONS gMacroFunctions[] = { - { "inc(", MacroIncFunction }, - { "dec(", MacroDecFunction }, - { "add(", MacroAddFunction }, - { "sub(", MacroSubFunction } -}; - -#define NUM_MACRO_FUNCTIONS (sizeof(gMacroFunctions) / sizeof(MACROFUNCTIONS)) - -#define MAX_INCLUDE_DEPTH 1024 -typedef struct INCLUDEINFO -{ - char *fileName; - unsigned int lineNo; - YY_BUFFER_STATE buffer; - MACROENTRY *lastInvokeMacro; // save off in case nested macros. - MACROENTRY *lastParseMacro; // recursive macros - MACROTEXT *lastMacroLineParse; // save off for recursive lines of macros working on. - bool lastbInsideMacro; // save off for recursive macros - bool lastbInsideDefine; // save off for recursive macros/defines - bool lastbInsideInclude; - bool lastbProcessingIFDEF; // save off #define information -// FILE *fileHandle; - char *prevString; - char *nextString; -} INCLUDEINFO; - -INCLUDEINFO gIncludeStack[MAX_INCLUDE_DEPTH]; -int gIncludeStackIndex = 0; - -IFDEFINFO gIfDefStack[MAX_IFDEF_DEPTH]; -int gIfDefStackIndex = 0; - -unsigned int &base_linenumber = gIncludeStack[0].lineNo; - -bool gbInsideInclude = false; -bool gbProcessingBuiltIn = false; -bool gbProcessingDefine = false; -unsigned int gCountParen = 0; - -bool gbProcessingIFDEF = false; -bool gbIFDEF = false; -bool gbCompareDefine = false; -unsigned int gIfDefStartLine; - - -MACROENTRY *gLastMacro; -MACROENTRY *gInvokeMacro; -MACROENTRY *gTempMacro; // until all the parameters are read -MACROENTRY *FindMacro(char *macroName); -MACROENTRY *FindNMacro(char *macroName, unsigned int sLen); - -MACROFUNCTIONPTR gMacroCallFunction; - -const char *builtInMacros = "macro m3x2 reg1, reg2, reg3\n" - " dp3 %reg1.x, %reg2, %reg3\n" - " dp3 %reg1.y, %reg2, %inc(%reg3)\n" - "endm"; - -// -// local prototypes -// -void CleanUp(); -void ReplaceMacroParms(char *srcLine, char *destLine, - MACROENTRY *srcParms, MACROENTRY *invParms); - -MACROTEXT *SaveMacroText(char *srcText, MACROTEXT *lastMacroText); -void FreeMacroEntry(MACROENTRY *macEntry); -void EndMacroParms(); -char *FindAlphaNum(char *srcStr, unsigned int *sLen); -void DebugUnhandledState(); - - -unsigned int gCommentStartLine; -unsigned int gMacroStartLine; - -char *gCurFileName = NULL; - -#define MAXSAVELINE 4095 - -char gSaveLine[MAXSAVELINE+1]; -char gMacroLine[MAXSAVELINE+1]; - -#if 1 -#ifdef _DEBUG -#define ECHO DebugUnhandledState(); -#else -#define ECHO -#endif -#endif - -bool gbInsideMacro = false; // flag if we are doing a macro replace or not. -bool gbTempInsideMacro = false; -unsigned int gInvokeState = INITIAL; - - -MACROENTRY *gParseMacro; // which source macro entry we are using -MACROENTRY *gTempParseMacro; // temporary holder until parameters are received. -MACROTEXT *gMacroLineParse; // which line we are currently parsing inside the macro invocation - -enum OPCODETYPE -{ - TYPE_NONE = 0, - TYPE_VERTEX_SHADER = 1, - TYPE_PIXEL_SHADER = 2 -}; -typedef struct OPCODEMAP -{ - const char *string; // string for opcode - int tokenName; // name of the corresponding token - int numArguments; // number of arguments for opcode - float version; // minimum version supported in. - int opcodeTypeFlags; // whether opcode can be used in vertex shader or pixel shader - bool opcodeModify; // if opcode modifiers can be used - bool textureOpcode; // only outputs to the texture unit -} OPCODEMAP; - -#ifndef TRUE -#define TRUE true -#endif -#ifndef FALSE -#define FALSE false -#endif - -OPCODEMAP theOpcodes[] = { - { "add", ADD_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, - { "dp3", DP3_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, - { "dp4", DP4_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "dst", DST_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "exp", EXP_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "expp", EXPP_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "frc", FRC_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "lit", LIT_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "log", LOG_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "logp", LOGP_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "m3x2", M3X2_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "m3x3", M3X3_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "m3x4", M3X4_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "m4x3", M4X3_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "m4x4", M4X4_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "mad", MAD_INSTR, 4, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, - { "max", MAX_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "min", MIN_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "mov", MOV_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, - { "mul", MUL_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, - { "nop", NOP_INSTR, 0, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, - { "rcp", RCP_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "rsq", RSQ_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "sge", SGE_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "slt", SLT_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "sub", SUB_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, -}; - -#define NUMOPCODES (sizeof(theOpcodes) / sizeof(OPCODEMAP)) -OPCODEMAP *FindOpcode(char *findName); - - -#line 993 "_vs1.0_lexer.cpp" - -/* Macros after this point can all be overridden by user definitions in - * section 1. - */ - -#ifndef YY_SKIP_YYWRAP -#ifdef __cplusplus -extern "C" int yywrap YY_PROTO(( void )); -#else -extern int yywrap YY_PROTO(( void )); -#endif -#endif - -#ifndef YY_NO_UNPUT -static void yyunput YY_PROTO(( int c, char *buf_ptr )); -#endif - -#ifndef yytext_ptr -static void yy_flex_strncpy YY_PROTO(( char *, yyconst char *, int )); -#endif - -#ifdef YY_NEED_STRLEN -static int yy_flex_strlen YY_PROTO(( yyconst char * )); -#endif - -#ifndef YY_NO_INPUT -#ifdef __cplusplus -static int yyinput YY_PROTO(( void )); -#else -static int input YY_PROTO(( void )); -#endif -#endif - -#if YY_STACK_USED -static int yy_start_stack_ptr = 0; -static int yy_start_stack_depth = 0; -static int *yy_start_stack = 0; -#ifndef YY_NO_PUSH_STATE -static void yy_push_state YY_PROTO(( int new_state )); -#endif -#ifndef YY_NO_POP_STATE -static void yy_pop_state YY_PROTO(( void )); -#endif -#ifndef YY_NO_TOP_STATE -static int yy_top_state YY_PROTO(( void )); -#endif - -#else -#define YY_NO_PUSH_STATE 1 -#define YY_NO_POP_STATE 1 -#define YY_NO_TOP_STATE 1 -#endif - -#ifdef YY_MALLOC_DECL -YY_MALLOC_DECL -#else -#if __STDC__ -#ifndef __cplusplus -#include -#endif -#else -/* Just try to get by without declaring the routines. This will fail - * miserably on non-ANSI systems for which sizeof(size_t) != sizeof(int) - * or sizeof(void*) != sizeof(int). - */ -#endif -#endif - -/* Amount of stuff to slurp up with each read. */ -#ifndef YY_READ_BUF_SIZE -#define YY_READ_BUF_SIZE 8192 -#endif - -/* Copy whatever the last rule matched to the standard output. */ - -#ifndef ECHO -/* This used to be an fputs(), but since the string might contain NUL's, - * we now use fwrite(). - */ -#define ECHO (void) fwrite( yytext, yyleng, 1, yyout ) -#endif - -/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, - * is returned in "result". - */ -#ifndef YY_INPUT -#define YY_INPUT(buf,result,max_size) \ - if ( yy_current_buffer->yy_is_interactive ) \ - { \ - int c = '*', n; \ - for ( n = 0; n < max_size && \ - (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ - buf[n] = (char) c; \ - if ( c == '\n' ) \ - buf[n++] = (char) c; \ - if ( c == EOF && ferror( yyin ) ) \ - YY_FATAL_ERROR( "input in flex scanner failed" ); \ - result = n; \ - } \ - else \ - { \ - errno=0; \ - while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ - { \ - if( errno != EINTR) \ - { \ - YY_FATAL_ERROR( "input in flex scanner failed" ); \ - break; \ - } \ - errno=0; \ - clearerr(yyin); \ - } \ - } -#endif - -/* No semi-colon after return; correct usage is to write "yyterminate();" - - * we don't want an extra ';' after the "return" because that will cause - * some compilers to complain about unreachable statements. - */ -#ifndef yyterminate -#define yyterminate() return YY_NULL -#endif - -/* Number of entries by which start-condition stack grows. */ -#ifndef YY_START_STACK_INCR -#define YY_START_STACK_INCR 25 -#endif - -/* Report a fatal error. */ -#ifndef YY_FATAL_ERROR -#define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) -#endif - -/* Default declaration of generated scanner - a define so the user can - * easily add parameters. - */ -#ifndef YY_DECL -#define YY_DECL int yylex YY_PROTO(( void )) -#endif - -/* Code executed at the beginning of each rule, after yytext and yyleng - * have been set up. - */ -#ifndef YY_USER_ACTION -#define YY_USER_ACTION -#endif - -/* Code executed at the end of each rule. */ -#ifndef YY_BREAK -#define YY_BREAK break; -#endif - -#define YY_RULE_SETUP \ - if ( yyleng > 0 ) \ - yy_current_buffer->yy_at_bol = \ - (yytext[yyleng - 1] == '\n'); \ - YY_USER_ACTION - -YY_DECL - { - yy_state_type yy_current_state; - char *yy_cp, *yy_bp; - int yy_act; - -#line 261 "vs1.0_tokens.l" - - -#line 1161 "_vs1.0_lexer.cpp" - - if ( yy_init ) - { - yy_init = 0; - -#ifdef YY_USER_INIT - YY_USER_INIT; -#endif - - if ( ! yy_start ) - yy_start = 1; /* first start state */ - - if ( ! yyin ) - yyin = stdin; - - if ( ! yyout ) - yyout = stdout; - - if ( ! yy_current_buffer ) - yy_current_buffer = - yy_create_buffer( yyin, YY_BUF_SIZE ); - - yy_load_buffer_state(); - } - - while ( 1 ) /* loops until end-of-file is reached */ - { - yy_cp = yy_c_buf_p; - - /* Support of yytext. */ - *yy_cp = yy_hold_char; - - /* yy_bp points to the position in yy_ch_buf of the start of - * the current run. - */ - yy_bp = yy_cp; - - yy_current_state = yy_start; - yy_current_state += YY_AT_BOL(); - yy_state_ptr = yy_state_buf; - *yy_state_ptr++ = yy_current_state; -yy_match: - do - { - YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; - while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) - { - yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 329 ) - yy_c = yy_meta[(unsigned int) yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; - *yy_state_ptr++ = yy_current_state; - ++yy_cp; - } - while ( yy_base[yy_current_state] != 767 ); - -yy_find_action: - yy_current_state = *--yy_state_ptr; - yy_lp = yy_accept[yy_current_state]; -find_rule: /* we branch to this label when backing up */ - for ( ; ; ) /* until we find what rule we matched */ - { - if ( yy_lp && yy_lp < yy_accept[yy_current_state + 1] ) - { - yy_act = yy_acclist[yy_lp]; - { - yy_full_match = yy_cp; - break; - } - } - --yy_cp; - yy_current_state = *--yy_state_ptr; - yy_lp = yy_accept[yy_current_state]; - } - - YY_DO_BEFORE_ACTION; - - -do_action: /* This label is used only to access EOF actions. */ - - - switch ( yy_act ) - { /* beginning of action switch */ -case 1: -YY_RULE_SETUP -#line 263 "vs1.0_tokens.l" -{ - gbProcessingDefine = false; - gSaveLine[0] = '\0'; - strncat(gSaveLine, yytext, MAXSAVELINE); -// GenDebugLine(); - if (gbProcessingIFDEF && (gbCompareDefine != gbIFDEF)) - { - BEGIN(IFDEFBODY); - } - else - { - BEGIN(INITIAL); - } - yyless(0); -} - YY_BREAK -case 2: -YY_RULE_SETUP -#line 279 "vs1.0_tokens.l" -{ - gbProcessingDefine = false; - gSaveLine[0] = '\0'; - strncat(gSaveLine, yytext, MAXSAVELINE); -// GenDebugLine(); - if (gbProcessingIFDEF && (gbCompareDefine != gbIFDEF)) - { - BEGIN(IFDEFBODY); - } - else - { - BEGIN(INITIAL); - } - yyless(0); -} - YY_BREAK -case 3: -YY_RULE_SETUP -#line 295 "vs1.0_tokens.l" -{ -// fprintf( stderr, "%s", yytext ); - vs10_lval.reg.type = TYPE_ADDRESS_REG; - vs10_lval.reg.index = atoi(&yytext[1]); - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return REGISTER; -} - YY_BREAK -case 4: -YY_RULE_SETUP -#line 304 "vs1.0_tokens.l" -{ -// fprintf( stderr, "%s", yytext ); - vs10_lval.reg.type = TYPE_VERTEX_ATTRIB_REG; - vs10_lval.reg.index = atoi(&yytext[1]); - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return REGISTER; -} - YY_BREAK -case 5: -YY_RULE_SETUP -#line 313 "vs1.0_tokens.l" -{ -// fprintf( stderr, "%s", yytext ); - vs10_lval.reg.type = TYPE_TEMPORARY_REG; - vs10_lval.reg.index = atoi(&yytext[1]); - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return REGISTER; -} - YY_BREAK -case 6: -YY_RULE_SETUP -#line 322 "vs1.0_tokens.l" -{ -// fprintf( stderr, "%s", yytext ); - vs10_lval.reg.type = TYPE_CONSTANT_MEM_REG; - vs10_lval.reg.index = atoi(&yytext[1]); - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return REGISTER; -} - YY_BREAK -case 7: -YY_RULE_SETUP -#line 331 "vs1.0_tokens.l" -{ -// fprintf( stderr, "%s", yytext ); - vs10_lval.reg.type = TYPE_TEXTURE_RESULT_REG; - vs10_lval.reg.index = atoi(&yytext[2]); - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return REGISTER; -} - YY_BREAK -case 8: -YY_RULE_SETUP -#line 340 "vs1.0_tokens.l" -{ -// fprintf( stderr, "%s", yytext ); - vs10_lval.reg.type = TYPE_COLOR_RESULT_REG; - vs10_lval.reg.index = atoi(&yytext[2]); - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return REGISTER; -} - YY_BREAK -case 9: -YY_RULE_SETUP -#line 349 "vs1.0_tokens.l" -{ -// fprintf( stderr, "%s", yytext ); - vs10_lval.reg.type = TYPE_FOG_RESULT_REG; - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return REGISTER; -} - YY_BREAK -case 10: -YY_RULE_SETUP -#line 357 "vs1.0_tokens.l" -{ -// fprintf( stderr, "%s", yytext ); - vs10_lval.reg.type = TYPE_POSITION_RESULT_REG; - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return REGISTER; -} - YY_BREAK -case 11: -YY_RULE_SETUP -#line 365 "vs1.0_tokens.l" -{ -// fprintf( stderr, "%s", yytext ); - vs10_lval.reg.type = TYPE_POINTS_RESULT_REG; - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return REGISTER; -} - YY_BREAK -case 12: -YY_RULE_SETUP -#line 373 "vs1.0_tokens.l" -{ - - unsigned int offset; - - offset = strcspn(yytext, " \t\n_"); - yyless(offset); - - OPCODEMAP *opcodeMap = FindOpcode(yytext); - if ( opcodeMap != NULL ) - { -// fprintf( stderr, "%s\t", opcodeMap->string ); - return( opcodeMap->tokenName ); - } - else - { - gTempParseMacro = FindMacro(yytext); - - if (gTempParseMacro != NULL) - { - if (gIncludeStackIndex >= MAX_INCLUDE_DEPTH ) - { - LexError("macros nested too deeply"); - exit( 1 ); - } - - if (gTempParseMacro->firstMacroLines != NULL) - { - - gTempMacro = (MACROENTRY *)malloc(sizeof(MACROENTRY)); - if (gTempMacro == NULL) - { - LexError("Out of memory allocating MACROENTRY structure.\n"); - } - else - { - - gTempMacro->next = NULL; - gTempMacro->prev = NULL; - gTempMacro->macroName = NULL; - gTempMacro->firstMacroParms = NULL; - gTempMacro->lastMacroParms = NULL; - gTempMacro->firstMacroLines = NULL; - gTempMacro->lastMacroLines = NULL; - gTempMacro->numParms = 0; - gTempMacro->nLines = 0; - - gbTempInsideMacro = true; // flag we are currently doing a macro replace. - gInvokeState = YYSTATE; - if (gTempParseMacro->numParms > 0) - { - BEGIN(MACROPARMSTART); - } - else - { - EndMacroParms(); - gbTempInsideMacro = false; // no longer waiting for macro invocation - } - - - } - } - } - else - { -// fprintf( stderr, "Opcode: \"%s\" not found\n", yytext ); - REJECT; - } - } - - //unsigned int offset; - // - //INSTRMAP *opcodeMap; - // - //offset = strcspn(yytext, " \t\n_"); - //yyless(offset); - //opcodeMap = FindInstruction(yytext); - //if (opcodeMap == NULL) - //{ - // REJECT; - //} - // - //yylval.opcodeInfo.opcodeMap = opcodeMap; - // - //return OPCODE; -} - YY_BREAK -case 13: -YY_RULE_SETUP -#line 460 "vs1.0_tokens.l" -{ -// fprintf( stderr, "%s", yytext ); - char *cmt = new char[yyleng+1]; - strncpy( cmt, yytext, yyleng ); - cmt[0] = '#'; - cmt[yyleng] = '\0'; - vs10_lval.comment = cmt; - return COMMENT; -} - YY_BREAK -case 14: -YY_RULE_SETUP -#line 470 "vs1.0_tokens.l" -{ -// fprintf( stderr, "%s", yytext ); - char *cmt = new char[yyleng+1]; - strncpy( cmt+1, yytext+1, yyleng-1 ); - cmt[0] = '#'; - cmt[1] = ' '; - cmt[yyleng] = '\0'; - vs10_lval.comment = cmt; - return COMMENT; -} - YY_BREAK -case 15: -YY_RULE_SETUP -#line 481 "vs1.0_tokens.l" -{ - fprintf( stderr, "COISSUE found\n" ); - yyless(yyleng-1); - //return COISSUE; -} - YY_BREAK -case 16: -YY_RULE_SETUP -#line 487 "vs1.0_tokens.l" -{ - fprintf( stderr, "COISSUE found\n" ); - //return COISSUE; -} - YY_BREAK -case 17: -YY_RULE_SETUP -#line 492 "vs1.0_tokens.l" -{ - gCommentStartLine = yylineno; - yyless(0); - BEGIN(EATCOMMENT); -} - YY_BREAK -case 18: -YY_RULE_SETUP -#line 498 "vs1.0_tokens.l" -{ - BEGIN(INCLUDE); -} - YY_BREAK -case 19: -YY_RULE_SETUP -#line 502 "vs1.0_tokens.l" -{ /* got the include file name */ - -// FILE *newyyin; -char *newyyin; - char incFileName[1024]; - unsigned long sLen; - bool validFileName; - - if ( gIncludeStackIndex >= MAX_INCLUDE_DEPTH ) - { - LexError("Includes nested too deeply, aborting\n"); - exit( 1 ); - } - -// GenDebugLine(); -// GenListString(); - yylineno++; - gLinesAssembled++; - - validFileName = true; - // zap "" and <> - if ((yytext[0] == '"') || (yytext[0] == '<')) - { - char *endQuote; - endQuote = strchr(&yytext[1], yytext[0]); - sLen = (endQuote - yytext)-1; - if (endQuote == NULL) - { - LexError("Unable to open include file %s\n", incFileName); - BEGIN(INITIAL); - validFileName = false; - } - else - { - incFileName[0] ='\0'; - strncat(incFileName, &yytext[1], sLen); - } - } - else - { - strcpy(incFileName, yytext); - } - - if (validFileName) - { - sLen = strlen(incFileName); - if ((incFileName[sLen-1] == '"') || (incFileName[sLen-1] == '>')) - { - incFileName[sLen-1] = '\0'; - } - - - newyyin = ReadTextFile( incFileName ); -// newyyin = fopen( incFileName, "r" ); - - if ( ! newyyin ) - { - LexError("Unable to open include file %s\n", incFileName); - BEGIN(SAVELINE); - } - else - { - gIncludeStack[gIncludeStackIndex].fileName = gCurFileName; - gIncludeStack[gIncludeStackIndex].lineNo = yylineno; -// gIncludeStack[gIncludeStackIndex].fileHandle = yyin; - gIncludeStack[gIncludeStackIndex].prevString = myin; - gIncludeStack[gIncludeStackIndex].nextString = newyyin; - gIncludeStack[gIncludeStackIndex].lastInvokeMacro = gInvokeMacro; - gIncludeStack[gIncludeStackIndex].lastParseMacro = gParseMacro; - gIncludeStack[gIncludeStackIndex].lastMacroLineParse = gMacroLineParse; - gIncludeStack[gIncludeStackIndex].lastbInsideMacro = gbInsideMacro; - gIncludeStack[gIncludeStackIndex].lastbInsideInclude = gbInsideInclude; - gIncludeStack[gIncludeStackIndex].buffer = YY_CURRENT_BUFFER; - gIncludeStack[gIncludeStackIndex].lastbProcessingIFDEF = gbProcessingIFDEF; - gIncludeStackIndex++; - - gbProcessingIFDEF = false; - - gCurFileName = strdup(incFileName); -// yyin = newyyin; - myin = newyyin; - -// GenSwitchFileNames(gCurFileName); - - yylineno = 1; - - yy_switch_to_buffer(yy_create_buffer( yyin, YY_BUF_SIZE ) ); - - gbInsideInclude = true; - - BEGIN(SAVELINE); - } - } -} - YY_BREAK -case YY_STATE_EOF(EATCOMMENT): -#line 597 "vs1.0_tokens.l" -{ - LexError("End of file reached before end of comment started on line %d.\n", gCommentStartLine); - BEGIN(INITIAL); -} - YY_BREAK -case 20: -YY_RULE_SETUP -#line 602 "vs1.0_tokens.l" -{ - char *endComment; - unsigned int keepSize; - - strcpy(gSaveLine, yytext); - endComment = strstr(yytext, "*/"); - - char *cmt; - if (endComment != NULL) - { - keepSize = (endComment - yytext+2); - yyless(keepSize); - BEGIN(INITIAL); - - if ( yytext[0] == '/' && yytext[1] == '*' ) - { - cmt = new char[yyleng]; - strncpy( cmt+3, yytext+2, yyleng-2 ); - cmt[0] = '#'; - cmt[1] = ' '; - cmt[2] = ' '; - cmt[yyleng-1] = '\0'; - } - else - { - cmt = new char[yyleng]; - strncpy( cmt+1, yytext, yyleng-2 ); - cmt[0] = '#'; - cmt[yyleng-1] = '\0'; - } - vs10_lval.comment = cmt; - return COMMENT; - } - else - { -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; - - if ( yytext[0] == '/' && yytext[1] == '*' ) - { - cmt = new char[yyleng+2]; - strncpy( cmt+3, yytext+2, yyleng-2 ); - cmt[0] = '#'; - cmt[1] = ' '; - cmt[2] = ' '; - cmt[yyleng+1] = '\0'; - } - else - { - cmt = new char[yyleng+2]; - strncpy( cmt+1, yytext, yyleng ); - cmt[0] = '#'; - cmt[yyleng+1] = '\0'; - } - vs10_lval.comment = cmt; - return COMMENT; - } -} - YY_BREAK -case YY_STATE_EOF(DEFSTR): -#line 663 "vs1.0_tokens.l" -{ - LexError("#define was incomplete before end of file\n"); - BEGIN(INITIAL); -} - YY_BREAK -case YY_STATE_EOF(DEFINE): -#line 668 "vs1.0_tokens.l" -{ - LexError("#define was incomplete before end of file\n"); - BEGIN(INITIAL); -} - YY_BREAK -case YY_STATE_EOF(DEFSPACE): -#line 673 "vs1.0_tokens.l" -{ - LexError("#define was incomplete before end of file\n"); - BEGIN(INITIAL); -} - YY_BREAK -case YY_STATE_EOF(INCLUDE): -#line 678 "vs1.0_tokens.l" -{ - LexError("#include was incomplete before end of file\n"); - BEGIN(INITIAL); -} - YY_BREAK -case YY_STATE_EOF(MACROBODY): -#line 683 "vs1.0_tokens.l" -{ - LexError("End of file reached before end of #define or endm was found, macro started on line %d.\n", gMacroStartLine); - BEGIN(INITIAL); -} - YY_BREAK -case YY_STATE_EOF(IFDEFBODY): -#line 688 "vs1.0_tokens.l" -{ - LexError("End of file reached before #endif found, macro started on line %d.\n", gIfDefStartLine); - BEGIN(INITIAL); -} - YY_BREAK -case 21: -YY_RULE_SETUP -#line 693 "vs1.0_tokens.l" -{ - LexError("#define was incomplete before end of line\n"); - BEGIN(SAVELINE); -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; -} - YY_BREAK -case 22: -YY_RULE_SETUP -#line 702 "vs1.0_tokens.l" -{ - LexError("#define was incomplete before end of line\n"); - BEGIN(SAVELINE); -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; -} - YY_BREAK -case 23: -YY_RULE_SETUP -#line 711 "vs1.0_tokens.l" -{ - LexError("#define was incomplete before end of line\n"); - BEGIN(SAVELINE); -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; -} - YY_BREAK -case 24: -YY_RULE_SETUP -#line 720 "vs1.0_tokens.l" -{ - if (gIfDefStackIndex >= MAX_IFDEF_DEPTH) - { - LexError("Out of stack space for #ifdef, aborting.\n"); - exit( 1 ); - } - else - { - gIfDefStack[gIfDefStackIndex].lastbProcessingIFDEF = gbProcessingIFDEF; - gIfDefStack[gIfDefStackIndex].lastbIFDEF = gbIFDEF; - gIfDefStack[gIfDefStackIndex].lastbCompareDefine = gbCompareDefine; - gIfDefStack[gIfDefStackIndex].lastIfDefStartLine = gIfDefStartLine; - gIfDefStackIndex++; - gIfDefStartLine = yylineno; - - gbCompareDefine = true; - BEGIN(IFDEFNAME); - } -} - YY_BREAK -case 25: -YY_RULE_SETUP -#line 740 "vs1.0_tokens.l" -{ - if (gIfDefStackIndex >= MAX_IFDEF_DEPTH) - { - LexError("Out of stack space for #ifdef, aborting.\n"); - exit( 1 ); - } - else - { - gIfDefStack[gIfDefStackIndex].lastbProcessingIFDEF = gbProcessingIFDEF; - gIfDefStack[gIfDefStackIndex].lastbIFDEF = gbIFDEF; - gIfDefStack[gIfDefStackIndex].lastbCompareDefine = gbCompareDefine; - gIfDefStack[gIfDefStackIndex].lastIfDefStartLine = gIfDefStartLine; - gIfDefStackIndex++; - gIfDefStartLine = yylineno; - - gbCompareDefine = false; - BEGIN(IFDEFNAME); - } -} - YY_BREAK -case 26: -YY_RULE_SETUP -#line 760 "vs1.0_tokens.l" -{ - if (!gbProcessingIFDEF) - { - LexError("Unexpected #else found at line %d, skipping.\n", yylineno); - } - else - { - gbCompareDefine = !gbCompareDefine; - BEGIN(INITIAL); - } -} - YY_BREAK -case 27: -YY_RULE_SETUP -#line 772 "vs1.0_tokens.l" -{ - char *defineName; - unsigned int sLen; - - - defineName = FindAlphaNum(yytext, &sLen); - if (defineName == NULL) - { - defineName = strdup(yytext); - defineName[yyleng-1] = '\0'; // kill \n - LexWarning("Mangled name (%s) for #ifdef, assuming not defined.\n", defineName); - free(defineName); - gbIFDEF = false; - } - else - { - if (FindNMacro(defineName, sLen) != NULL) - { - gbIFDEF = true; - } - else - { - gbIFDEF = false; - } - } - - gbProcessingIFDEF = true; - if (gbIFDEF != gbCompareDefine) - { - BEGIN(IFDEFBODY); - } - else - { - BEGIN(SAVELINE); - } - -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; -} - YY_BREAK -case 28: -YY_RULE_SETUP -#line 814 "vs1.0_tokens.l" -{ - if (!gbProcessingIFDEF) - { - LexError("Unexpected #endif found at line %d, skipping.\n", yylineno); - } - else - { - gIfDefStackIndex--; - gbProcessingIFDEF = gIfDefStack[gIfDefStackIndex].lastbProcessingIFDEF; - gbIFDEF = gIfDefStack[gIfDefStackIndex].lastbIFDEF; - gbCompareDefine = gIfDefStack[gIfDefStackIndex].lastbCompareDefine; - gIfDefStartLine = gIfDefStack[gIfDefStackIndex].lastIfDefStartLine; - - } - - if (YYSTATE == IFDEFBODY) - { - strncpy(gSaveLine, yytext, MAXSAVELINE); - } - - BEGIN(ENDMACRO); - -} - YY_BREAK -case 29: -YY_RULE_SETUP -#line 838 "vs1.0_tokens.l" -{ - LexWarning("Garbage at end of #endif or endm will be ignored.\n"); -} - YY_BREAK -case 30: -YY_RULE_SETUP -#line 842 "vs1.0_tokens.l" -{ - BEGIN(SAVELINE); - return '\n'; -} - YY_BREAK -case YY_STATE_EOF(ENDMACRO): -#line 847 "vs1.0_tokens.l" -{ - BEGIN(INITIAL); -} - YY_BREAK -case 31: -YY_RULE_SETUP -#line 851 "vs1.0_tokens.l" -{ - // eat line, because we are not in a TRUE #ifdef, or FALSE #ifndef - strncpy(gSaveLine, yytext, MAXSAVELINE); -} - YY_BREAK -case 32: -YY_RULE_SETUP -#line 856 "vs1.0_tokens.l" -{ - strcat(gSaveLine, yytext); -// GenDebugLine(); -// GenListString(); - yylineno++; - gLinesAssembled++; -} - YY_BREAK -case 33: -YY_RULE_SETUP -#line 864 "vs1.0_tokens.l" -{ - gbProcessingDefine = true; - gMacroStartLine = yylineno; - gCountParen = 0; - BEGIN(MACRONAME); -} - YY_BREAK -case 34: -YY_RULE_SETUP -#line 871 "vs1.0_tokens.l" -{ - BEGIN(SAVELINE); -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; -} - YY_BREAK -case 35: -YY_RULE_SETUP -#line 879 "vs1.0_tokens.l" -{ -// unsigned int majorVersion; -// unsigned int minorVersion; -// int minorOffset; -// -// -// majorVersion = (unsigned int)(atoi(&yytext[3])); -// // skip "ps." + second '.' -// minorOffset = strcspn(&yytext[3], ".")+4; -// minorVersion = (unsigned int)(atoi(&yytext[minorOffset])); -// yylval.ival = D3DVS_VERSION(majorVersion, minorVersion); -// - -// fprintf( stderr, "%s", yytext ); - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return VERTEX_SHADER; -} - YY_BREAK -case 36: -YY_RULE_SETUP -#line 898 "vs1.0_tokens.l" -{ -// fprintf( stderr, "%s", yytext ); - vs10_lval.ival = atoi(yytext); - return INTVAL; -} - YY_BREAK -case 37: -YY_RULE_SETUP -#line 905 "vs1.0_tokens.l" -{ - BEGIN(MODIFIER); -//fprintf( stderr, "." ); - return yytext[0]; -} - YY_BREAK -case 38: -YY_RULE_SETUP -#line 911 "vs1.0_tokens.l" -{ -// fprintf( stderr, "%s", yytext ); - BEGIN(INITIAL); - - vs10_lval.mask[0] = tolower(yytext[0]); - vs10_lval.mask[1] = tolower(yytext[1]); - vs10_lval.mask[2] = tolower(yytext[2]); - vs10_lval.mask[3] = tolower(yytext[3]); - - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - - return XYZW_MODIFIER; - -#if 0 - char temp[6]; - - temp[0] = '\0'; - strncat(temp, yytext, 4); - strlwr(temp); - vs10_lval.lval = FindSwizzleValue(temp); - - BEGIN(INITIAL); - return SWIZZLE_MODIFIER; -#endif - -} - YY_BREAK -case 39: -YY_RULE_SETUP -#line 939 "vs1.0_tokens.l" -{ -// fprintf( stderr, "%s", yytext ); - BEGIN(INITIAL); - - int validLen = strspn(yytext, "xyzw"); - int i; - for ( i = 0; i < validLen; i++ ) - vs10_lval.mask[i] = tolower( yytext[i] ); - while ( i < 4 ) - { - vs10_lval.mask[i] = 0; - i++; - } - - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - - return XYZW_MODIFIER; - -#if 0 - //char temp[6]; - char *temp = new char[6]; - unsigned int registerMask; - unsigned int validLen; - - temp[0] = '\0'; - validLen = strspn(yytext, "xyzw"); - strncat(temp, yytext, validLen); - for ( int i = 0; i < validLen; i++ ) - temp[i] = tolower( temp[i] ); - registerMask = MakeRegisterMask(temp); - - if (registerMask != 0) - { - //vs10_lval.sval = temp; - vs10_lval.lval = registerMask; - BEGIN(INITIAL); - return XYZW_MODIFIER; - } - else - { - //vs10_lval.sval = temp; - vs10_lval.lval = FindSwizzleValue(temp); - BEGIN(INITIAL); - return SWIZZLE_MODIFIER; - } -#endif -} - YY_BREAK -case 40: -YY_RULE_SETUP -#line 988 "vs1.0_tokens.l" -{ - BEGIN(INITIAL); - yyless(0); -} - YY_BREAK -case 41: -YY_RULE_SETUP -#line 993 "vs1.0_tokens.l" -{ - /* setup and save off #define/macro name */ - if (FindMacro(yytext) != NULL) - { - LexWarning("Redefinition of #define/macro %s, ignoring.\n", yytext); - if (gbProcessingDefine) - { - BEGIN(EATDEFINE); - } - else - { - BEGIN(EATMACRO); - } - } - else - { - - BEGIN(MACROPARMSTART); - // %%%%% This should be setup to use memory pools - gTempMacro = (MACROENTRY *)malloc(sizeof(MACROENTRY)); - if (gTempMacro == NULL) - { - LexError("Out of memory for macro table.\n"); - if (gbProcessingDefine) - { - BEGIN(EATDEFINE); - } - else - { - BEGIN(EATMACRO); - } - } - else - { - gTempMacro->prev = gLastMacro; - gTempMacro->next = NULL; - - gTempMacro->firstMacroParms = NULL; - gTempMacro->lastMacroParms = NULL; - gTempMacro->firstMacroLines = NULL; - gTempMacro->lastMacroLines = NULL; - gTempMacro->numParms = 0; - gTempMacro->bIsDefine = gbProcessingDefine; - gTempMacro->nLines = 0; - - if (gCurFileName != NULL) - { - gTempMacro->fileName = strdup(gCurFileName); - } - else - { - gTempMacro->fileName = NULL; - } - - gTempMacro->lineNo = yylineno; - - /* %%%%% this should be set up in memory pools. */ - gTempMacro->macroName = (char *)malloc(strlen(yytext)+1); - if (gTempMacro->macroName == NULL) - { - LexError("Out of memory for string table.\n"); - SAFEFREE(gTempMacro); - if (gbProcessingDefine) - { - BEGIN(EATDEFINE); - } - else - { - BEGIN(EATMACRO); - } - } - else - { - strcpy(gTempMacro->macroName, yytext); - } - } - } -} - YY_BREAK -case 42: -YY_RULE_SETUP -#line 1072 "vs1.0_tokens.l" -{ - LexError("No macro name specified, skipping macro definition.\n"); - SAFEFREE(gTempMacro->fileName); - SAFEFREE(gTempMacro); - if (gbProcessingDefine) - { - BEGIN(EATDEFINE); - } - else - { - BEGIN(EATMACRO); - } - -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; -} - YY_BREAK -case 43: -YY_RULE_SETUP -#line 1091 "vs1.0_tokens.l" -{ - gCountParen++; -} - YY_BREAK -case 44: -YY_RULE_SETUP -#line 1095 "vs1.0_tokens.l" -{} - YY_BREAK -case 45: -YY_RULE_SETUP -#line 1097 "vs1.0_tokens.l" -{ - if (gbProcessingDefine && (gCountParen == 0)) - { - EndMacroParms(); - } - else - { - BEGIN(MACROPARM); - } - yyless(0); -} - YY_BREAK -case 46: -YY_RULE_SETUP -#line 1109 "vs1.0_tokens.l" -{ - if ((gCountParen == 0) && gbProcessingDefine) - { - EndMacroParms(); - } -} - YY_BREAK -case 47: -YY_RULE_SETUP -#line 1116 "vs1.0_tokens.l" -{ - if (gCountParen == 0) - { - EndMacroParms(); - } -} - YY_BREAK -case 48: -YY_RULE_SETUP -#line 1123 "vs1.0_tokens.l" -{} - YY_BREAK -case YY_STATE_EOF(MACROPARM): -#line 1125 "vs1.0_tokens.l" -{ - EndMacroParms(); -// GenDebugLine(); -// GenListString(); - yylineno++; - gLinesAssembled++; - BEGIN(INITIAL); -} - YY_BREAK -case 49: -YY_RULE_SETUP -#line 1134 "vs1.0_tokens.l" -{ - if (gbProcessingDefine && (gCountParen > 0)) - { - LexError("Malformed #define, skipping.\n"); - BEGIN(SAVELINE); - } - else - { - EndMacroParms(); -// GenDebugLine(); -// GenListString(); - yylineno++; - gLinesAssembled++; - if (gbProcessingDefine) - { - gbProcessingDefine = false; - BEGIN(SAVELINE); - } - } -} - YY_BREAK -case 50: -YY_RULE_SETUP -#line 1156 "vs1.0_tokens.l" -{ - - MACROTEXT *tMacro; - char *macroParmEnd; - unsigned int startOffset; - unsigned int leftParenCount; - unsigned int rightParenCount; - - // sheesh, we gotta count the parenthesis.... - macroParmEnd = yytext; - leftParenCount = 0; - rightParenCount = 0; - while (*macroParmEnd) - { - if (*macroParmEnd == ')') - { - rightParenCount++; - } - if (*macroParmEnd == '(') - { - leftParenCount++; - } - - macroParmEnd++; - } - - // if we found the last right parenthesis. - if (rightParenCount == leftParenCount+1) - { - // find if we got the last parenthesis on this line - macroParmEnd = strrchr(yytext, ')'); - yyless((macroParmEnd - yytext)); - BEGIN(MACROPARMEND); - } - - startOffset = strspn(yytext, " \t"); - - tMacro = SaveMacroText(&yytext[startOffset], gTempMacro->lastMacroParms); - if (tMacro == NULL) - { - LexError("Out of memory for string table for macro parameter(s).\n"); - FreeMacroEntry(gTempMacro); - BEGIN(EATMACRO); - } - else - { - // if first one wasn't set then set it - if (gTempMacro->firstMacroParms == NULL) - { - gTempMacro->firstMacroParms = tMacro; - } - - gTempMacro->lastMacroParms = tMacro; - - gTempMacro->numParms++; - } - -} - YY_BREAK -case 51: -YY_RULE_SETUP -#line 1215 "vs1.0_tokens.l" -{ - if (!gbProcessingDefine && !gbTempInsideMacro) - { - LexError("Malformed macro, skipping.\n"); - BEGIN(EATMACRO); - } - else - { - gCountParen--; - - // we can get multiple \n's here - while (yytext[yyleng-2] == '\n') - { - yyleng--; - } - yyless(yyleng); - - // if there isn't a \n on this line, macro starts on this line, - // not next, like in a macro definition - if (yytext[yyleng-1] != '\n') - { - EndMacroParms(); - } - else - { - if (yytext[yyleng-1] == '\n') - { - gTempMacro->lineNo++; - } - // count this line - gTempMacro->nLines++; -// GenDebugLine(); -// GenListString(); - EndMacroParms(); - if (!gbInsideMacro) - { - yylineno++; - } - - gLinesAssembled++; - } - - } -} - YY_BREAK -case 52: -YY_RULE_SETUP -#line 1260 "vs1.0_tokens.l" -{ - if (!gbProcessingDefine && !gbTempInsideMacro) - { - LexError("Malformed macro, skipping.\n"); - BEGIN(EATMACRO); - } - else - { - - // no matter what count this line - gTempMacro->nLines++; - gCountParen--; - EndMacroParms(); - if (!gbInsideMacro) - { - yylineno++; - } - - gLinesAssembled++; - } -} - YY_BREAK -case 53: -YY_RULE_SETUP -#line 1282 "vs1.0_tokens.l" -{ - if (!gbProcessingDefine && !gbTempInsideMacro) - { - LexError("Malformed macro, skipping.\n"); - BEGIN(EATMACRO); - } - else - { - gCountParen--; - if (gCountParen == 0) - { - // no matter what count this line - gTempMacro->nLines++; - EndMacroParms(); - if (!gbInsideMacro) - { - yylineno++; - } - - gLinesAssembled++; - } - else - { - REJECT; - } - } -} - YY_BREAK -case 54: -YY_RULE_SETUP -#line 1310 "vs1.0_tokens.l" -{ - MACROTEXT *tMacro; - unsigned int copyLen; - char *endLine; - - gSaveLine[0] ='\0'; - endLine = strchr(yytext, '\\'); - copyLen = (endLine - yytext); - if (copyLen > MAXSAVELINE) - { - copyLen = MAXSAVELINE; - } - - strncat(gSaveLine, yytext, copyLen); - strcat(gSaveLine, "\n"); - tMacro = SaveMacroText(gSaveLine, gLastMacro->lastMacroLines); - if (tMacro == NULL) - { - LexError("Out of memory for string table for macro parameter(s).\n"); - BEGIN(EATDEFINE); - } - else - { - gLastMacro->nLines++; - // if first one wasn't set then set it - if (gLastMacro->firstMacroLines == NULL) - { - gLastMacro->firstMacroLines = tMacro; - } - - gLastMacro->lastMacroLines = tMacro; - } - -// GenDebugLine(); -// GenListString(); - yylineno++; - gLinesAssembled++; -} - YY_BREAK -case 55: -YY_RULE_SETUP -#line 1349 "vs1.0_tokens.l" -{ - - strncpy(gSaveLine, yytext, MAXSAVELINE); - if (gbProcessingDefine) - { - LexError("Malformed #define, skipping.\n"); - } - - BEGIN(ENDMACRO); -} - YY_BREAK -case 56: -YY_RULE_SETUP -#line 1360 "vs1.0_tokens.l" -{ - MACROTEXT *tMacro; - - // check if processing #define and only one line, if not then append \n - if (!gbProcessingDefine || (gLastMacro->nLines >= 1)) - { - gSaveLine[0] = '\0'; - strncat(gSaveLine, yytext, MAXSAVELINE); - strcat(gSaveLine, "\n"); - tMacro = SaveMacroText(gSaveLine, gLastMacro->lastMacroLines); - gLastMacro->nLines++; - } - else if (gLastMacro->numParms > 0) // check if parameters were there - { - // if so, we need the '\n' appended - gMacroLine[0] = '\0'; - strncat(gMacroLine, yytext, MAXSAVELINE); - strcat(gMacroLine, "\n"); - tMacro = SaveMacroText(gMacroLine, gLastMacro->lastMacroLines); - gLastMacro->nLines++; - } - else // straight no newline macro replace - { - tMacro = SaveMacroText(yytext, gLastMacro->lastMacroLines); - } - - if (tMacro == NULL) - { - LexError("Out of memory for string table for macro parameter(s).\n"); - BEGIN(EATMACRO); - } - else - { - // if first one wasn't set then set it - if (gLastMacro->firstMacroLines == NULL) - { - gLastMacro->firstMacroLines = tMacro; - } - - gLastMacro->lastMacroLines = tMacro; - } -} - YY_BREAK -case 57: -YY_RULE_SETUP -#line 1403 "vs1.0_tokens.l" -{ - - MACROTEXT *tMacro; -// GenDebugLine(); -// GenListString(); - yylineno++; - gLinesAssembled++; - if (gbProcessingDefine) - { - gbProcessingDefine = false; - BEGIN(SAVELINE); - } - else - { - // this means \n by itself inside macro body - if (((yylineno-1) - gLastMacro->lineNo) != gLastMacro->nLines) - { - strcpy(gMacroLine, "\n"); - tMacro = SaveMacroText(gMacroLine, gLastMacro->lastMacroLines); - gLastMacro->nLines++; - - if (tMacro == NULL) - { - LexError("Out of memory for string table for macro parameter(s).\n"); - BEGIN(EATMACRO); - } - else - { - // if first one wasn't set then set it - if (gLastMacro->firstMacroLines == NULL) - { - gLastMacro->firstMacroLines = tMacro; - } - - gLastMacro->lastMacroLines = tMacro; - } - } - } -} - YY_BREAK -case 58: -YY_RULE_SETUP -#line 1443 "vs1.0_tokens.l" -{ - BEGIN(SAVELINE); -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; -} - YY_BREAK -case 59: -YY_RULE_SETUP -#line 1451 "vs1.0_tokens.l" -{ - strncpy(gSaveLine, yytext, MAXSAVELINE); -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; -} - YY_BREAK -case 60: -YY_RULE_SETUP -#line 1459 "vs1.0_tokens.l" -{ - strncpy(gSaveLine, yytext, MAXSAVELINE); -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; -} - YY_BREAK -case 61: -YY_RULE_SETUP -#line 1467 "vs1.0_tokens.l" -{ - strncpy(gSaveLine, yytext, MAXSAVELINE); -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; - BEGIN(SAVELINE); -} - YY_BREAK -case 62: -YY_RULE_SETUP -#line 1476 "vs1.0_tokens.l" -{ - - gTempParseMacro = FindMacro(yytext); - - if (gTempParseMacro != NULL) - { - if (gIncludeStackIndex >= MAX_INCLUDE_DEPTH ) - { - LexError("macros nested too deeply"); - exit( 1 ); - } - - if (gTempParseMacro->firstMacroLines != NULL) - { - - gTempMacro = (MACROENTRY *)malloc(sizeof(MACROENTRY)); - if (gTempMacro == NULL) - { - LexError("Out of memory allocating MACROENTRY structure.\n"); - } - else - { - - gTempMacro->next = NULL; - gTempMacro->prev = NULL; - gTempMacro->macroName = NULL; - gTempMacro->firstMacroParms = NULL; - gTempMacro->lastMacroParms = NULL; - gTempMacro->firstMacroLines = NULL; - gTempMacro->lastMacroLines = NULL; - gTempMacro->numParms = 0; - gTempMacro->nLines = 0; - - gbTempInsideMacro = true; // flag we are currently doing a macro replace. - gInvokeState = YYSTATE; - if (gTempParseMacro->numParms > 0) - { - BEGIN(MACROPARMSTART); - } - else - { - EndMacroParms(); - gbTempInsideMacro = false; // no longer waiting for macro invocation - } - } - } - } - else - { - BEGIN(INITIAL); - REJECT; - } -} - YY_BREAK -case 63: -YY_RULE_SETUP -#line 1530 "vs1.0_tokens.l" -{ -// fprintf( stderr, "%c ", yytext[0] ); - return yytext[0]; -} - YY_BREAK -case 64: -YY_RULE_SETUP -#line 1536 "vs1.0_tokens.l" -{} - YY_BREAK -case 65: -YY_RULE_SETUP -#line 1538 "vs1.0_tokens.l" -{ - LexError("Didn't find label string for #define.\n"); - BEGIN(SAVELINE); -// return '\n'; -} - YY_BREAK -case 66: -YY_RULE_SETUP -#line 1544 "vs1.0_tokens.l" -{ -//fprintf(stderr, "\n"); -// line_incr = 1; - line_incr++; - BEGIN(SAVELINE); - return '\n'; -} - YY_BREAK -case 67: -YY_RULE_SETUP -#line 1552 "vs1.0_tokens.l" -{ - BEGIN(INITIAL); -// fprintf( stderr, "%s", yytext ); - if (yyleng == 1) - return yytext[0]; - else - LexError("Unrecognized Token: %s\n", yytext); - return UNKNOWN_STRING; -} - YY_BREAK -case 68: -YY_RULE_SETUP -#line 1562 "vs1.0_tokens.l" -{ -// vs10_lval.ival = yytext[0]; - LexError("Illegal character: %d decimal.\n", yytext[0]); - return(ILLEGAL); -} - YY_BREAK -case 69: -YY_RULE_SETUP -#line 1568 "vs1.0_tokens.l" -{ -// vs10_lval.ival = yytext[0]; - LexError("Illegal character: %d decimal.\n", yytext[0]); - return(ILLEGAL); -} - YY_BREAK -case 70: -YY_RULE_SETUP -#line 1574 "vs1.0_tokens.l" -{ - return yytext[0]; -} - YY_BREAK -case 71: -YY_RULE_SETUP -#line 1578 "vs1.0_tokens.l" -{ - BEGIN(EATSTRING); - yyless(0); -} - YY_BREAK -case YY_STATE_EOF(INITIAL): -case YY_STATE_EOF(SKIPLINE): -case YY_STATE_EOF(EATSTRING): -case YY_STATE_EOF(SAVELINE): -case YY_STATE_EOF(MACRONAME): -case YY_STATE_EOF(EATMACRO): -case YY_STATE_EOF(EATDEFINE): -case YY_STATE_EOF(MODIFIER): -case YY_STATE_EOF(MACROPARMSTART): -case YY_STATE_EOF(IFDEFNAME): -case YY_STATE_EOF(MACROPARMEND): -#line 1583 "vs1.0_tokens.l" -{ - bool wasInMacro; - bool oneLiner; - char *macroText; - - wasInMacro = gbInsideMacro; - oneLiner = false; - - - // if we are inside the macro then do next line until their are no more - if (gbInsideMacro) - { - oneLiner = (gParseMacro->nLines == 0); - - // free the temporary parameter replaced line we were working on. - // get next line in macro text, if any - gMacroLineParse = gMacroLineParse->next; - // more lines to parse? - if (gMacroLineParse != NULL) - { - macroText = gMacroLine; - // if no replacement text, just use source line - if (gParseMacro->firstMacroParms == NULL) - { - macroText = gMacroLineParse->macroText; - } - else - { - // replace the macro parameters - ReplaceMacroParms(gMacroLineParse->macroText, gMacroLine, gParseMacro, gInvokeMacro); - } - -// if (gExpandMacros) -// { -// strcpy(gSaveLine, macroText); -// } - - BEGIN(INITIAL); - // and lex it. - yy_scan_string(macroText); - } - else - { - // no more lines in this macro, so free the working macro - SAFEFREE(gInvokeMacro); - // shut off flag for inside a macro replacement state. - gbInsideMacro = false; - } - } - - if (gbProcessingIFDEF && !wasInMacro) - { - LexError("End of file reached before #endif found, macro started on line %d.\n", gIfDefStartLine); - } - - if (!gbInsideMacro) - { - if ( gIncludeStackIndex == 0 ) - { - if (!gbProcessingBuiltIn) - CleanUp(); - return 0; -// return TOKEN_EOF; - } - else - { - yy_delete_buffer( YY_CURRENT_BUFFER ); - SAFEFREE(gCurFileName); -// SAFEDELETE(myin); -// SAFECLOSE(yyin); - } - - gIncludeStackIndex--; - SAFEDELETEARRAY( gIncludeStack[gIncludeStackIndex].nextString ); - yy_switch_to_buffer(gIncludeStack[gIncludeStackIndex].buffer ); - gCurFileName = gIncludeStack[gIncludeStackIndex].fileName; -// yyin = gIncludeStack[gIncludeStackIndex].fileHandle; - myin = gIncludeStack[gIncludeStackIndex].prevString; - yylineno = gIncludeStack[gIncludeStackIndex].lineNo; - gInvokeMacro = gIncludeStack[gIncludeStackIndex].lastInvokeMacro; - gParseMacro = gIncludeStack[gIncludeStackIndex].lastParseMacro; - gMacroLineParse = gIncludeStack[gIncludeStackIndex].lastMacroLineParse; - gbInsideInclude = gIncludeStack[gIncludeStackIndex].lastbInsideInclude; - gbInsideMacro = gIncludeStack[gIncludeStackIndex].lastbInsideMacro; - gbProcessingIFDEF = gIncludeStack[gIncludeStackIndex].lastbProcessingIFDEF; - - if (!gbInsideMacro && !oneLiner) - { -// GenSwitchFileNames(gCurFileName); - BEGIN(SAVELINE); - } - else - { - BEGIN(INITIAL); - } - - // gSaveLine was last line saved, before macro invocation - if (wasInMacro && !gbInsideMacro && !oneLiner) - { -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; - } - - } - -} - YY_BREAK -case 72: -YY_RULE_SETUP -#line 1692 "vs1.0_tokens.l" -ECHO; - YY_BREAK -#line 2919 "_vs1.0_lexer.cpp" - - case YY_END_OF_BUFFER: - { - /* Amount of text matched not including the EOB char. */ - int yy_amount_of_matched_text = (int) (yy_cp - yytext_ptr) - 1; - - /* Undo the effects of YY_DO_BEFORE_ACTION. */ - *yy_cp = yy_hold_char; - YY_RESTORE_YY_MORE_OFFSET - - if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_NEW ) - { - /* We're scanning a new file or input source. It's - * possible that this happened because the user - * just pointed yyin at a new source and called - * yylex(). If so, then we have to assure - * consistency between yy_current_buffer and our - * globals. Here is the right place to do so, because - * this is the first action (other than possibly a - * back-up) that will match for the new input source. - */ - yy_n_chars = yy_current_buffer->yy_n_chars; - yy_current_buffer->yy_input_file = yyin; - yy_current_buffer->yy_buffer_status = YY_BUFFER_NORMAL; - } - - /* Note that here we test for yy_c_buf_p "<=" to the position - * of the first EOB in the buffer, since yy_c_buf_p will - * already have been incremented past the NUL character - * (since all states make transitions on EOB to the - * end-of-buffer state). Contrast this with the test - * in input(). - */ - if ( yy_c_buf_p <= &yy_current_buffer->yy_ch_buf[yy_n_chars] ) - { /* This was really a NUL. */ - yy_state_type yy_next_state; - - yy_c_buf_p = yytext_ptr + yy_amount_of_matched_text; - - yy_current_state = yy_get_previous_state(); - - /* Okay, we're now positioned to make the NUL - * transition. We couldn't have - * yy_get_previous_state() go ahead and do it - * for us because it doesn't know how to deal - * with the possibility of jamming (and we don't - * want to build jamming into it because then it - * will run more slowly). - */ - - yy_next_state = yy_try_NUL_trans( yy_current_state ); - - yy_bp = yytext_ptr + YY_MORE_ADJ; - - if ( yy_next_state ) - { - /* Consume the NUL. */ - yy_cp = ++yy_c_buf_p; - yy_current_state = yy_next_state; - goto yy_match; - } - - else - { - yy_cp = yy_c_buf_p; - goto yy_find_action; - } - } - - else switch ( yy_get_next_buffer() ) - { - case EOB_ACT_END_OF_FILE: - { - yy_did_buffer_switch_on_eof = 0; - - if ( yywrap() ) - { - /* Note: because we've taken care in - * yy_get_next_buffer() to have set up - * yytext, we can now set up - * yy_c_buf_p so that if some total - * hoser (like flex itself) wants to - * call the scanner after we return the - * YY_NULL, it'll still work - another - * YY_NULL will get returned. - */ - yy_c_buf_p = yytext_ptr + YY_MORE_ADJ; - - yy_act = YY_STATE_EOF(YY_START); - goto do_action; - } - - else - { - if ( ! yy_did_buffer_switch_on_eof ) - YY_NEW_FILE; - } - break; - } - - case EOB_ACT_CONTINUE_SCAN: - yy_c_buf_p = - yytext_ptr + yy_amount_of_matched_text; - - yy_current_state = yy_get_previous_state(); - - yy_cp = yy_c_buf_p; - yy_bp = yytext_ptr + YY_MORE_ADJ; - goto yy_match; - - case EOB_ACT_LAST_MATCH: - yy_c_buf_p = - &yy_current_buffer->yy_ch_buf[yy_n_chars]; - - yy_current_state = yy_get_previous_state(); - - yy_cp = yy_c_buf_p; - yy_bp = yytext_ptr + YY_MORE_ADJ; - goto yy_find_action; - } - break; - } - - default: - YY_FATAL_ERROR( - "fatal flex scanner internal error--no action found" ); - } /* end of action switch */ - } /* end of scanning one token */ - } /* end of yylex */ - - -/* yy_get_next_buffer - try to read in a new buffer - * - * Returns a code representing an action: - * EOB_ACT_LAST_MATCH - - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position - * EOB_ACT_END_OF_FILE - end of file - */ - -static int yy_get_next_buffer() - { - char *dest = yy_current_buffer->yy_ch_buf; - char *source = yytext_ptr; - int number_to_move, i; - int ret_val; - - if ( yy_c_buf_p > &yy_current_buffer->yy_ch_buf[yy_n_chars + 1] ) - YY_FATAL_ERROR( - "fatal flex scanner internal error--end of buffer missed" ); - - if ( yy_current_buffer->yy_fill_buffer == 0 ) - { /* Don't try to fill the buffer, so this is an EOF. */ - if ( yy_c_buf_p - yytext_ptr - YY_MORE_ADJ == 1 ) - { - /* We matched a single character, the EOB, so - * treat this as a final EOF. - */ - return EOB_ACT_END_OF_FILE; - } - - else - { - /* We matched some text prior to the EOB, first - * process it. - */ - return EOB_ACT_LAST_MATCH; - } - } - - /* Try to read more data. */ - - /* First move last chars to start of buffer. */ - number_to_move = (int) (yy_c_buf_p - yytext_ptr) - 1; - - for ( i = 0; i < number_to_move; ++i ) - *(dest++) = *(source++); - - if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_EOF_PENDING ) - /* don't do the read, it's not guaranteed to return an EOF, - * just force an EOF - */ - yy_current_buffer->yy_n_chars = yy_n_chars = 0; - - else - { - int num_to_read = - yy_current_buffer->yy_buf_size - number_to_move - 1; - - while ( num_to_read <= 0 ) - { /* Not enough room in the buffer - grow it. */ -#ifdef YY_USES_REJECT - YY_FATAL_ERROR( -"input buffer overflow, can't enlarge buffer because scanner uses REJECT" ); -#else - - /* just a shorter name for the current buffer */ - YY_BUFFER_STATE b = yy_current_buffer; - - int yy_c_buf_p_offset = - (int) (yy_c_buf_p - b->yy_ch_buf); - - if ( b->yy_is_our_buffer ) - { - int new_size = b->yy_buf_size * 2; - - if ( new_size <= 0 ) - b->yy_buf_size += b->yy_buf_size / 8; - else - b->yy_buf_size *= 2; - - b->yy_ch_buf = (char *) - /* Include room in for 2 EOB chars. */ - yy_flex_realloc( (void *) b->yy_ch_buf, - b->yy_buf_size + 2 ); - } - else - /* Can't grow it, we don't own it. */ - b->yy_ch_buf = 0; - - if ( ! b->yy_ch_buf ) - YY_FATAL_ERROR( - "fatal error - scanner input buffer overflow" ); - - yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; - - num_to_read = yy_current_buffer->yy_buf_size - - number_to_move - 1; -#endif - } - - if ( num_to_read > YY_READ_BUF_SIZE ) - num_to_read = YY_READ_BUF_SIZE; - - /* Read in more data. */ - YY_INPUT( (&yy_current_buffer->yy_ch_buf[number_to_move]), - yy_n_chars, num_to_read ); - - yy_current_buffer->yy_n_chars = yy_n_chars; - } - - if ( yy_n_chars == 0 ) - { - if ( number_to_move == YY_MORE_ADJ ) - { - ret_val = EOB_ACT_END_OF_FILE; - yyrestart( yyin ); - } - - else - { - ret_val = EOB_ACT_LAST_MATCH; - yy_current_buffer->yy_buffer_status = - YY_BUFFER_EOF_PENDING; - } - } - - else - ret_val = EOB_ACT_CONTINUE_SCAN; - - yy_n_chars += number_to_move; - yy_current_buffer->yy_ch_buf[yy_n_chars] = YY_END_OF_BUFFER_CHAR; - yy_current_buffer->yy_ch_buf[yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; - - yytext_ptr = &yy_current_buffer->yy_ch_buf[0]; - - return ret_val; - } - - -/* yy_get_previous_state - get the state just before the EOB char was reached */ - -static yy_state_type yy_get_previous_state() - { - yy_state_type yy_current_state; - char *yy_cp; - - yy_current_state = yy_start; - yy_current_state += YY_AT_BOL(); - yy_state_ptr = yy_state_buf; - *yy_state_ptr++ = yy_current_state; - - for ( yy_cp = yytext_ptr + YY_MORE_ADJ; yy_cp < yy_c_buf_p; ++yy_cp ) - { - YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 4); - while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) - { - yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 329 ) - yy_c = yy_meta[(unsigned int) yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; - *yy_state_ptr++ = yy_current_state; - } - - return yy_current_state; - } - - -/* yy_try_NUL_trans - try to make a transition on the NUL character - * - * synopsis - * next_state = yy_try_NUL_trans( current_state ); - */ - -#ifdef YY_USE_PROTOS -static yy_state_type yy_try_NUL_trans( yy_state_type yy_current_state ) -#else -static yy_state_type yy_try_NUL_trans( yy_current_state ) -yy_state_type yy_current_state; -#endif - { - int yy_is_jam; - - YY_CHAR yy_c = 4; - while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) - { - yy_current_state = (int) yy_def[yy_current_state]; - if ( yy_current_state >= 329 ) - yy_c = yy_meta[(unsigned int) yy_c]; - } - yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; - yy_is_jam = (yy_current_state == 328); - if ( ! yy_is_jam ) - *yy_state_ptr++ = yy_current_state; - - return yy_is_jam ? 0 : yy_current_state; - } - - -#ifndef YY_NO_UNPUT -#ifdef YY_USE_PROTOS -static void yyunput( int c, char *yy_bp ) -#else -static void yyunput( c, yy_bp ) -int c; -char *yy_bp; -#endif - { - char *yy_cp = yy_c_buf_p; - - /* undo effects of setting up yytext */ - *yy_cp = yy_hold_char; - - if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 ) - { /* need to shift things up to make room */ - /* +2 for EOB chars. */ - int number_to_move = yy_n_chars + 2; - char *dest = &yy_current_buffer->yy_ch_buf[ - yy_current_buffer->yy_buf_size + 2]; - char *source = - &yy_current_buffer->yy_ch_buf[number_to_move]; - - while ( source > yy_current_buffer->yy_ch_buf ) - *--dest = *--source; - - yy_cp += (int) (dest - source); - yy_bp += (int) (dest - source); - yy_current_buffer->yy_n_chars = - yy_n_chars = yy_current_buffer->yy_buf_size; - - if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 ) - YY_FATAL_ERROR( "flex scanner push-back overflow" ); - } - - *--yy_cp = (char) c; - - - yytext_ptr = yy_bp; - yy_hold_char = *yy_cp; - yy_c_buf_p = yy_cp; - } -#endif /* ifndef YY_NO_UNPUT */ - - -#ifdef __cplusplus -static int yyinput() -#else -static int input() -#endif - { - int c; - - *yy_c_buf_p = yy_hold_char; - - if ( *yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) - { - /* yy_c_buf_p now points to the character we want to return. - * If this occurs *before* the EOB characters, then it's a - * valid NUL; if not, then we've hit the end of the buffer. - */ - if ( yy_c_buf_p < &yy_current_buffer->yy_ch_buf[yy_n_chars] ) - /* This was really a NUL. */ - *yy_c_buf_p = '\0'; - - else - { /* need more input */ - int offset = yy_c_buf_p - yytext_ptr; - ++yy_c_buf_p; - - switch ( yy_get_next_buffer() ) - { - case EOB_ACT_LAST_MATCH: - /* This happens because yy_g_n_b() - * sees that we've accumulated a - * token and flags that we need to - * try matching the token before - * proceeding. But for input(), - * there's no matching to consider. - * So convert the EOB_ACT_LAST_MATCH - * to EOB_ACT_END_OF_FILE. - */ - - /* Reset buffer status. */ - yyrestart( yyin ); - - /* fall through */ - - case EOB_ACT_END_OF_FILE: - { - if ( yywrap() ) - return EOF; - - if ( ! yy_did_buffer_switch_on_eof ) - YY_NEW_FILE; -#ifdef __cplusplus - return yyinput(); -#else - return input(); -#endif - } - - case EOB_ACT_CONTINUE_SCAN: - yy_c_buf_p = yytext_ptr + offset; - break; - } - } - } - - c = *(unsigned char *) yy_c_buf_p; /* cast for 8-bit char's */ - *yy_c_buf_p = '\0'; /* preserve yytext */ - yy_hold_char = *++yy_c_buf_p; - - yy_current_buffer->yy_at_bol = (c == '\n'); - - return c; - } - - -#ifdef YY_USE_PROTOS -void yyrestart( FILE *input_file ) -#else -void yyrestart( input_file ) -FILE *input_file; -#endif - { - if ( ! yy_current_buffer ) - yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); - - yy_init_buffer( yy_current_buffer, input_file ); - yy_load_buffer_state(); - } - - -#ifdef YY_USE_PROTOS -void yy_switch_to_buffer( YY_BUFFER_STATE new_buffer ) -#else -void yy_switch_to_buffer( new_buffer ) -YY_BUFFER_STATE new_buffer; -#endif - { - if ( yy_current_buffer == new_buffer ) - return; - - if ( yy_current_buffer ) - { - /* Flush out information for old buffer. */ - *yy_c_buf_p = yy_hold_char; - yy_current_buffer->yy_buf_pos = yy_c_buf_p; - yy_current_buffer->yy_n_chars = yy_n_chars; - } - - yy_current_buffer = new_buffer; - yy_load_buffer_state(); - - /* We don't actually know whether we did this switch during - * EOF (yywrap()) processing, but the only time this flag - * is looked at is after yywrap() is called, so it's safe - * to go ahead and always set it. - */ - yy_did_buffer_switch_on_eof = 1; - } - - -#ifdef YY_USE_PROTOS -void yy_load_buffer_state( void ) -#else -void yy_load_buffer_state() -#endif - { - yy_n_chars = yy_current_buffer->yy_n_chars; - yytext_ptr = yy_c_buf_p = yy_current_buffer->yy_buf_pos; - yyin = yy_current_buffer->yy_input_file; - yy_hold_char = *yy_c_buf_p; - } - - -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_create_buffer( FILE *file, int size ) -#else -YY_BUFFER_STATE yy_create_buffer( file, size ) -FILE *file; -int size; -#endif - { - YY_BUFFER_STATE b; - - b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) ); - if ( ! b ) - YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); - - b->yy_buf_size = size; - - /* yy_ch_buf has to be 2 characters longer than the size given because - * we need to put in 2 end-of-buffer characters. - */ - b->yy_ch_buf = (char *) yy_flex_alloc( b->yy_buf_size + 2 ); - if ( ! b->yy_ch_buf ) - YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); - - b->yy_is_our_buffer = 1; - - yy_init_buffer( b, file ); - - return b; - } - - -#ifdef YY_USE_PROTOS -void yy_delete_buffer( YY_BUFFER_STATE b ) -#else -void yy_delete_buffer( b ) -YY_BUFFER_STATE b; -#endif - { - if ( ! b ) - return; - - if ( b == yy_current_buffer ) - yy_current_buffer = (YY_BUFFER_STATE) 0; - - if ( b->yy_is_our_buffer ) - yy_flex_free( (void *) b->yy_ch_buf ); - - yy_flex_free( (void *) b ); - } - - -#ifndef _WIN32 -#include -#else -#ifndef YY_ALWAYS_INTERACTIVE -#ifndef YY_NEVER_INTERACTIVE -extern int isatty YY_PROTO(( int )); -#endif -#endif -#endif - -#ifdef YY_USE_PROTOS -void yy_init_buffer( YY_BUFFER_STATE b, FILE *file ) -#else -void yy_init_buffer( b, file ) -YY_BUFFER_STATE b; -FILE *file; -#endif - - - { - yy_flush_buffer( b ); - - b->yy_input_file = file; - b->yy_fill_buffer = 1; - -#if YY_ALWAYS_INTERACTIVE - b->yy_is_interactive = 1; -#else -#if YY_NEVER_INTERACTIVE - b->yy_is_interactive = 0; -#else - b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; -#endif -#endif - } - - -#ifdef YY_USE_PROTOS -void yy_flush_buffer( YY_BUFFER_STATE b ) -#else -void yy_flush_buffer( b ) -YY_BUFFER_STATE b; -#endif - - { - if ( ! b ) - return; - - b->yy_n_chars = 0; - - /* We always need two end-of-buffer characters. The first causes - * a transition to the end-of-buffer state. The second causes - * a jam in that state. - */ - b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; - b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; - - b->yy_buf_pos = &b->yy_ch_buf[0]; - - b->yy_at_bol = 1; - b->yy_buffer_status = YY_BUFFER_NEW; - - if ( b == yy_current_buffer ) - yy_load_buffer_state(); - } - - -#ifndef YY_NO_SCAN_BUFFER -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_scan_buffer( char *base, yy_size_t size ) -#else -YY_BUFFER_STATE yy_scan_buffer( base, size ) -char *base; -yy_size_t size; -#endif - { - YY_BUFFER_STATE b; - - if ( size < 2 || - base[size-2] != YY_END_OF_BUFFER_CHAR || - base[size-1] != YY_END_OF_BUFFER_CHAR ) - /* They forgot to leave room for the EOB's. */ - return 0; - - b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) ); - if ( ! b ) - YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); - - b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ - b->yy_buf_pos = b->yy_ch_buf = base; - b->yy_is_our_buffer = 0; - b->yy_input_file = 0; - b->yy_n_chars = b->yy_buf_size; - b->yy_is_interactive = 0; - b->yy_at_bol = 1; - b->yy_fill_buffer = 0; - b->yy_buffer_status = YY_BUFFER_NEW; - - yy_switch_to_buffer( b ); - - return b; - } -#endif - - -#ifndef YY_NO_SCAN_STRING -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_scan_string( yyconst char *yy_str ) -#else -YY_BUFFER_STATE yy_scan_string( yy_str ) -yyconst char *yy_str; -#endif - { - int len; - for ( len = 0; yy_str[len]; ++len ) - ; - - return yy_scan_bytes( yy_str, len ); - } -#endif - - -#ifndef YY_NO_SCAN_BYTES -#ifdef YY_USE_PROTOS -YY_BUFFER_STATE yy_scan_bytes( yyconst char *bytes, int len ) -#else -YY_BUFFER_STATE yy_scan_bytes( bytes, len ) -yyconst char *bytes; -int len; -#endif - { - YY_BUFFER_STATE b; - char *buf; - yy_size_t n; - int i; - - /* Get memory for full buffer, including space for trailing EOB's. */ - n = len + 2; - buf = (char *) yy_flex_alloc( n ); - if ( ! buf ) - YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); - - for ( i = 0; i < len; ++i ) - buf[i] = bytes[i]; - - buf[len] = buf[len+1] = YY_END_OF_BUFFER_CHAR; - - b = yy_scan_buffer( buf, n ); - if ( ! b ) - YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); - - /* It's okay to grow etc. this buffer, and we should throw it - * away when we're done. - */ - b->yy_is_our_buffer = 1; - - return b; - } -#endif - - -#ifndef YY_NO_PUSH_STATE -#ifdef YY_USE_PROTOS -static void yy_push_state( int new_state ) -#else -static void yy_push_state( new_state ) -int new_state; -#endif - { - if ( yy_start_stack_ptr >= yy_start_stack_depth ) - { - yy_size_t new_size; - - yy_start_stack_depth += YY_START_STACK_INCR; - new_size = yy_start_stack_depth * sizeof( int ); - - if ( ! yy_start_stack ) - yy_start_stack = (int *) yy_flex_alloc( new_size ); - - else - yy_start_stack = (int *) yy_flex_realloc( - (void *) yy_start_stack, new_size ); - - if ( ! yy_start_stack ) - YY_FATAL_ERROR( - "out of memory expanding start-condition stack" ); - } - - yy_start_stack[yy_start_stack_ptr++] = YY_START; - - BEGIN(new_state); - } -#endif - - -#ifndef YY_NO_POP_STATE -static void yy_pop_state() - { - if ( --yy_start_stack_ptr < 0 ) - YY_FATAL_ERROR( "start-condition stack underflow" ); - - BEGIN(yy_start_stack[yy_start_stack_ptr]); - } -#endif - - -#ifndef YY_NO_TOP_STATE -static int yy_top_state() - { - return yy_start_stack[yy_start_stack_ptr - 1]; - } -#endif - -#ifndef YY_EXIT_FAILURE -#define YY_EXIT_FAILURE 2 -#endif - -#ifdef YY_USE_PROTOS -static void yy_fatal_error( yyconst char msg[] ) -#else -static void yy_fatal_error( msg ) -char msg[]; -#endif - { - (void) fprintf( stderr, "%s\n", msg ); - exit( YY_EXIT_FAILURE ); - } - - - -/* Redefine yyless() so it works in section 3 code. */ - -#undef yyless -#define yyless(n) \ - do \ - { \ - /* Undo effects of setting up yytext. */ \ - yytext[yyleng] = yy_hold_char; \ - yy_c_buf_p = yytext + n; \ - yy_hold_char = *yy_c_buf_p; \ - *yy_c_buf_p = '\0'; \ - yyleng = n; \ - } \ - while ( 0 ) - - -/* Internal utility routines. */ - -#ifndef yytext_ptr -#ifdef YY_USE_PROTOS -static void yy_flex_strncpy( char *s1, yyconst char *s2, int n ) -#else -static void yy_flex_strncpy( s1, s2, n ) -char *s1; -yyconst char *s2; -int n; -#endif - { - int i; - for ( i = 0; i < n; ++i ) - s1[i] = s2[i]; - } -#endif - -#ifdef YY_NEED_STRLEN -#ifdef YY_USE_PROTOS -static int yy_flex_strlen( yyconst char *s ) -#else -static int yy_flex_strlen( s ) -yyconst char *s; -#endif - { - int n; - for ( n = 0; s[n]; ++n ) - ; - - return n; - } -#endif - - -#ifdef YY_USE_PROTOS -static void *yy_flex_alloc( yy_size_t size ) -#else -static void *yy_flex_alloc( size ) -yy_size_t size; -#endif - { - return (void *) malloc( size ); - } - -#ifdef YY_USE_PROTOS -static void *yy_flex_realloc( void *ptr, yy_size_t size ) -#else -static void *yy_flex_realloc( ptr, size ) -void *ptr; -yy_size_t size; -#endif - { - /* The cast to (char *) in the following accommodates both - * implementations that use char* generic pointers, and those - * that use void* generic pointers. It works with the latter - * because both ANSI C and C++ allow castless assignment from - * any pointer type to void*, and deal with argument conversions - * as though doing an assignment. - */ - return (void *) realloc( (char *) ptr, size ); - } - -#ifdef YY_USE_PROTOS -static void yy_flex_free( void *ptr ) -#else -static void yy_flex_free( ptr ) -void *ptr; -#endif - { - free( ptr ); - } - -#if YY_MAIN -int main() - { - yylex(); - return 0; - } -#endif -#line 1692 "vs1.0_tokens.l" - - - -//===================================================================== -// Function: FindNMacro -// Description: Look through macros and see if it had been predefined -// Parameters: findName = name to lookup -// sLen = # characters valid in source (findName) -// Returns: MACROENTRY * = pointer to macro entry if found -//===================================================================== -MACROENTRY *FindNMacro(char *findName, unsigned int sLen) -{ - MACROENTRY *curEntry; - - curEntry = gLastMacro; - while (curEntry != NULL) - { - if (strlen(curEntry->macroName) == sLen) - { - if (!strncmp(curEntry->macroName, findName, sLen)) - { - break; - } - } - - curEntry = curEntry->prev; - } - - return curEntry; - -} - -//===================================================================== -// Function: FindMacro -// Description: Look through macros and see if it had been predefined -// Parameters: findName = name to lookup -// Returns: MACROENTRY * = pointer to macro entry if found -//===================================================================== -MACROENTRY *FindMacro(char *findName) -{ - MACROENTRY *curEntry; - - curEntry = gLastMacro; - while (curEntry != NULL) - { - if (!strcmp(curEntry->macroName, findName)) - { - break; - } - - curEntry = curEntry->prev; - } - - return curEntry; - -} - -//===================================================================== -// Function: CleanUp -// Description: Clean up the #define strings -// Parameters: . -// Returns: . -//===================================================================== -void CleanUp() -{ - void *tPtr; - - // free up the macros that were alloced - while (gLastMacro != NULL) - { - - FreeMacroEntry(gLastMacro); - - tPtr = gLastMacro; - gLastMacro = gLastMacro->prev; - SAFEFREE(tPtr); - } - -} - -//===================================================================== -// Function: FreeMacroEntry -// Description: Frees up the macro entry data, (parms, lines of text) -// Parameters: macEntry = pointer to the MACROENTRY structure -// Returns: . -//===================================================================== -void FreeMacroEntry(MACROENTRY *macEntry) -{ - MACROTEXT *tText; - MACROTEXT *tNext; - - SAFEFREE(macEntry->macroName); - SAFEFREE(macEntry->fileName); - // free the macro lines that were alloced - tText = macEntry->lastMacroLines; - while (tText != NULL) - { - tNext = tText->prev; - SAFEFREE(tText); - tText = tNext; - } - - // free the text of the macro parms that were alloced - tText = macEntry->lastMacroParms; - while (tText != NULL) - { - tNext = tText->prev; - SAFEFREE(tText); - tText = tNext; - } -} - -//===================================================================== -// Function: CheckMacroFunctions -// Description: Find if this text is a builtin macro function -// Parameters: lookString = non-null terminated string of possible -// and if found set global macro function call -// Returns: . -//===================================================================== -void CheckMacroFunctions(char *lookString, unsigned int *recognizedLen, char **invString) -{ - - unsigned int i; - unsigned int sLen; - - for (i=0; i< NUM_MACRO_FUNCTIONS; i++) - { - sLen = strlen(gMacroFunctions[i].name); - if (!strncmp(gMacroFunctions[i].name, lookString, sLen)) - { - gMacroCallFunction = gMacroFunctions[i].function; - *recognizedLen = sLen; - *invString = NULL; - return; - } - } -} - -//===================================================================== -// Function: FindAlphaNum -// Description: Find a whole alpha numeric string, ie consists of -// [A-Za-z0-9_] only -// Parameters: srcStr = source string to search through. -// sLen = unsinged int pointer to length of string found -// Returns: pointer to found start of string. -// NULL if none. -//===================================================================== -char *FindAlphaNum(char *srcStr, unsigned int *sLen) -{ - char curChar; - char *foundStr; - - while (*srcStr != '\0') - { - curChar = toupper(*srcStr); - if ((curChar >= 'A') && (curChar <= 'Z')) - break; - - if ((curChar >= '0') && (curChar <='9')) - break; - - if (curChar == '_') - break; - - srcStr++; - } - - if (*srcStr == '\0') - { - return NULL; - } - - foundStr = srcStr; - - *sLen = 0; - // now search for end of string of [A-Za-z0-9_] - while (*srcStr != '\0') - { - curChar = toupper(*srcStr); - if ((curChar < 'A') || (curChar > 'Z')) - { - if ((curChar < '0') || (curChar > '9')) - { - if (curChar != '_') - break; - } - } - - (*sLen)++; - srcStr++; - } - - return foundStr; - -} - -//===================================================================== -// Function: FindDefineParm -// Description: Find if the MACROENTRY->macroText linked list contains -// replaceable parameters. -// Parameters: srcParms = pointer to MACROENTRY structure for source -// parameters -// invParms = MACROENTRY pointer to invocation parameters -// lookString = non-null terminated string of possible -// replaceable string -// recognizedLen = replacement string matched length -// invString = invocation string to replace with -// Returns: pointer to first character found in lookstring -//===================================================================== -char *FindDefineParm(MACROENTRY *srcParms, MACROENTRY *invParms, - char *lookString, unsigned int *recognizedLen, char **invString) -{ - MACROTEXT *srcText; - MACROTEXT *invText; - char *checkStr; - unsigned int checkLen = 0; - unsigned int sLen; - - checkStr = lookString; - *invString = NULL; - - // first search for first [A-Za-z0-9_] only string - checkStr = FindAlphaNum(lookString, &checkLen); - - while (checkStr != NULL) - { - // check all the #define parameters for match - srcText = srcParms->firstMacroParms; - invText = invParms->firstMacroParms; - while (srcText) - { - sLen = strlen(srcText->macroText); - // lengths should match - if (sLen == checkLen) - { - if (!strncmp(checkStr, srcText->macroText, checkLen)) - { - // it matched so return replacement text - *invString = invText->macroText; - // and length that we recognized - *recognizedLen = checkLen; - return checkStr; - } - } - - srcText = srcText->next; - invText = invText->next; - } - - // not found yet, so go to next string. - checkStr = FindAlphaNum(checkStr+checkLen, &checkLen); - } - - return NULL; -} - -//===================================================================== -// Function: FindReplaceParm -// Description: Find if the MACROENTRY->macroText linked list contains -// a replaceable parameters. -// Parameters: srcParms = pointer to MACROENTRY structure for source -// parameters -// invParms = MACROENTRY pointer to invocation parameters -// lookString = non-null terminated string of possible -// replaceable string -// recognizedLen = replacement string matched length -// invString = invocation string to replace with -// Returns: . -//===================================================================== -void FindReplaceParm(MACROENTRY *srcParms, MACROENTRY *invParms, - char *lookString, unsigned int *recognizedLen, char **invString) -{ - unsigned int sLen; - MACROTEXT *srcText; - MACROTEXT *invText; - - *recognizedLen = 0; - *invString = NULL; - - srcText = srcParms->firstMacroParms; - invText = invParms->firstMacroParms; - - if (srcText != NULL) - { - // go until srcText # strings ends - while (srcText != NULL) - { - sLen = strlen(srcText->macroText); - if (!strncmp(srcText->macroText, lookString, sLen)) - { - // found it so return src, replacement string - *recognizedLen = strlen(srcText->macroText); - *invString = invText->macroText; - // call function macro if it was invoked prior. - if (gMacroCallFunction != NULL) - { - gMacroCallFunction(lookString, recognizedLen, invString); - gMacroCallFunction = NULL; - } - return; - } - - srcText = srcText->next; - invText = invText->next; - } - } - - // ok, it wasn't found, look through builtin macro functions - CheckMacroFunctions(lookString, recognizedLen, invString); -} - -//===================================================================== -// Function: ReplaceMacroParms -// Description: Replace macro parameters when macro was defined, with -// those specified on the macro invocation line -// Parameters: srcLine = source line to replace src macro parms with -// destLine = destination line save to. -// invocation macro parameters. -// parseMacro = currently parsing macro entry -// invParms = invocation macro entry -// Returns: . -//===================================================================== -void ReplaceMacroParms(char *srcLine, char *destLine, - MACROENTRY *srcParms, MACROENTRY *invParms) -{ - char *findReplace; - char *invString; - unsigned int sLen; - unsigned int dLen; - unsigned int copyLen; - unsigned int subLen; - unsigned int recognizedLen; - - destLine[0]= '\0'; - - sLen = strlen(srcLine); - dLen = 0; - - while (sLen > 0) - { - // strtok might work better except it modifies the string, so - // kind of do my own.... - if (!srcParms->bIsDefine) - { - findReplace = strchr(srcLine, '%'); - if (findReplace != NULL) - { - // bypass % sign in findReplacement - findReplace++; - // figure out length of source before % - copyLen = (findReplace - srcLine)-1; - // check if there is a replacement string - FindReplaceParm(srcParms, invParms, findReplace, &recognizedLen, &invString); - } - else - { - strcat(destLine, srcLine); - return; - } - } - else - { - findReplace = FindDefineParm(srcParms, invParms, srcLine, &recognizedLen, &invString); - if (findReplace != NULL) - { - // figure out length of source before % - copyLen = findReplace - srcLine; - } - else - { - strcat(destLine, srcLine); - return; - } - } - - - if (invString != NULL) - { - // figure out how much we are going to substitute - subLen = strlen(invString); - } - else - { - subLen = 0; - } - - if ((dLen + copyLen + subLen) > MAXSAVELINE) - { - LexError("Macro string overrun.\n"); - CleanUp(); - exit(ERROR_MACRO_OVERRUN); - } - - if (copyLen > 0) - { - strncat(destLine, srcLine, copyLen); - dLen += copyLen; - } - - srcLine += copyLen; - sLen -= copyLen; - // in macro so skip % part of variable - if (!srcParms->bIsDefine) - { - // skip %, also - srcLine++; - sLen--; - } - - if (invString != NULL) - { - strcat(destLine, invString); - dLen += strlen(invString); - } - - srcLine += recognizedLen; - sLen -= recognizedLen; - } - -} - -//===================================================================== -// Function: SaveMacroText -// Description: Adds a string to a linked list of MACROTEXT structures -// Parameters: srcText = pointer to source text to save -// lastMacroText = last allocated, or NULL -// Returns: newly allocated MACROTEXT structure, or NULL -//===================================================================== -MACROTEXT *SaveMacroText(char *srcText, MACROTEXT *lastMacroText) -{ - MACROTEXT *curMacroText; - - curMacroText = (MACROTEXT *)malloc(sizeof(MACROTEXT)); - if (curMacroText == NULL) - { - return NULL; - } - else - { - // no next entry but set up previous with previously alloced macro parameter - curMacroText->next = NULL; - curMacroText->prev = lastMacroText; - - // if the macroParm pointer is null then we are the first allocated - // so if not set the last one allocate next pointer to newly allocated structure - if (lastMacroText != NULL) - { - lastMacroText->next = curMacroText; - } - - /* %%%%% this should be set up in memory pools. */ - curMacroText->macroText = strdup(srcText); - if (curMacroText->macroText == NULL) - { - SAFEFREE(curMacroText); - return NULL; - } - } - - return curMacroText; -} - -//===================================================================== -// Function: ParseBuiltInMacroParms -// Description: parse parameters of string and fill in MACROENTRY -// structure. -// Parameters: parsedMacro = pointer to MACROENTRY structure that gets -// filled in with parameter pointers and count -// parmStr = string to parse parameters from -// Returns: false if error -//===================================================================== -bool ParseBuiltInMacroParms(MACROENTRY *parsedMacro, char *parmStr) -{ - char *endStr; - char *foundParm; - MACROTEXT *prevMT; - MACROTEXT *curMT; - - parsedMacro->numParms = 0; - parsedMacro->firstMacroParms = NULL; - - foundParm = strdup(parmStr); - if (foundParm == NULL) - { - LexError("Out of memory parsing builtin macro parameters.\n"); - return false; - } - - // assume a ')' is on the end. - endStr = strrchr(foundParm, ')'); - if (endStr == NULL) - { - LexWarning("Ending parenthesis not found for macro %s.\n", parsedMacro->macroName); - endStr = foundParm + strlen(foundParm); - } - - prevMT = NULL; - // strip out and separate parameters - while (foundParm < endStr) - { - // allocate a macro text structure - curMT = (MACROTEXT *)malloc(sizeof(MACROTEXT)); - if (curMT == NULL) - { - free(parmStr); - LexError("Out of memory parsing builtin macro parameters.\n"); - return false; - } - curMT->next = NULL; - curMT->prev = prevMT; - parsedMacro->numParms++; - - if (prevMT != NULL) - { - prevMT->next = curMT; - } - else - { - parsedMacro->firstMacroParms = curMT; - } - - curMT->macroText = foundParm; - // search for next parameters, delimited by comma - foundParm = strchr(foundParm, ','); - if (foundParm == NULL) - { - foundParm = endStr; - *foundParm = '\0'; - } - else - { - // skip comma - *foundParm = '\0'; - foundParm++; - } - prevMT = curMT; - } - - return true; -} - -//===================================================================== -// Function: MacroMathFunction -// Description: Comes here after macro replacement is done to perform -// some mathematic function on parameter (macro replacement -// string (ie, register)) -// Parameters: invMacro = macroentry pointer containing macro information -// recognizedLen = # characters recoginized so far -// invStr = invoked replacement string so far -// mathStr = "-", "+", etc for mathematic function -// Returns: new recognizedLen, invStr, with incremented # -//===================================================================== -void MacroMathFunction(MACROENTRY *invMacro, unsigned int *recognizedLen, char **invStr, - const char *mathStr) -{ - char *numStartStr; - unsigned int sLen; - char numberStr[256]; - unsigned int number = 0; - char *operand; - - - // verify enough paramters to complete operation - if (invMacro->numParms != 2) - { - LexError("Two parameters are required for %s macro\n", invMacro->macroName); - return; - } - - // get second macro parm, which is add by amount. - operand = invMacro->firstMacroParms->next->macroText; - - // first find inner most bracket if any - numStartStr = strrchr(*invStr, ']'); - if (numStartStr == NULL) - { - numStartStr = strrchr(*invStr, ')'); - } - - if (numStartStr != NULL) - { - if ((strlen(*invStr)+strlen(operand)+1) > MAXREPLACESTRING) - { - LexError("Out of Temporary string replacement memory inside builtin macro %s\n", - invMacro->macroName); - } - else - { - sLen = (numStartStr - *invStr); - gReplaceText[0] = '\0'; - strncat(gReplaceText, *invStr, sLen); - strcat(gReplaceText, mathStr); - strcat(gReplaceText, operand); - strcat(gReplaceText, numStartStr); - *invStr = gReplaceText; - } - } - else - { - numStartStr = strpbrk(*invStr, "0123456789"); - if (numStartStr != NULL) - { - // put up to number we found - sLen = numStartStr - *invStr; - if (sLen > MAXREPLACESTRING) - goto ErrOut; - - gReplaceText[0] = '\0'; - strncat(gReplaceText, *invStr, sLen); - - switch (mathStr[0]) - { - case '-': - number = atoi(numStartStr)-atoi(operand); - break; - case '+': - number = atoi(numStartStr)+atoi(operand); - break; - } - sprintf(numberStr, "%d", number); - - if ((strlen(gReplaceText) + strlen(numberStr)) > MAXREPLACESTRING) - goto ErrOut; - - strcat(gReplaceText, numberStr); - - while ((*numStartStr != '\0') && (*numStartStr >= '0' && *numStartStr <= '9')) - numStartStr++; - - if ((strlen(gReplaceText) + strlen(numStartStr)) > MAXREPLACESTRING) - goto ErrOut; - - strcat(gReplaceText, numStartStr); - - *invStr = gReplaceText; - } - else - { - if ((strlen(*invStr)+strlen(operand)+1) > MAXREPLACESTRING) - { - LexError("Out of Temporary string replacement memory inside builtin macro %s\n", - invMacro->macroName); - } - else - { - sprintf(gReplaceText, "%s%s%s", *invStr, mathStr, operand); - *invStr = gReplaceText; - } - } - } - - - return; - -ErrOut: - LexError("Out of Temporary string replacement memory inside builtin macro %s\n", - invMacro->macroName); - // skip ')' - (*recognizedLen)++; -} - -//===================================================================== -// Function: MacroIncFunction -// Description: Comes here after macro replacement is done to increment -// macro replacement string (ie, register) -// Parameters: lookStr = string after '(', so we can get parameters -// recognizedLen = # characters recoginized so far -// invStr = invoked replacement string so far -// Returns: new recognizedLen, invStr, with incremented # -//===================================================================== -void MacroIncFunction(char *lookStr, unsigned int *recognizedLen, char **invStr) -{ - MACROENTRY tMEntry; - MACROTEXT parm1; - MACROTEXT parm2; - - tMEntry.macroName = (char *)"%inc()"; - tMEntry.numParms = 2; - tMEntry.firstMacroParms = &parm1; - parm1.prev = NULL; - parm1.next = &parm2; - parm1.macroText = *invStr; - parm2.prev = &parm1; - parm2.next = NULL; - parm2.macroText = (char *)"1"; - - MacroMathFunction(&tMEntry, recognizedLen, invStr, "+"); - // skip ')' - (*recognizedLen)++; -} - -//===================================================================== -// Function: MacroDecFunction -// Description: Comes here after macro replacement is done to decrement -// macro replacement string (ie, register) -// Parameters: lookStr = string after '(', so we can get parameters -// recognizedLen = # characters recoginized so far -// invStr = invoked replacement string so far -// Returns: new recognizedLen, invStr, with decremented # -//===================================================================== -void MacroDecFunction(char *lookStr, unsigned int *recognizedLen, char **invStr) -{ - MACROENTRY tMEntry; - MACROTEXT parm1; - MACROTEXT parm2; - - tMEntry.macroName = (char *)"%dec()"; - tMEntry.numParms = 2; - tMEntry.firstMacroParms = &parm1; - parm1.prev = NULL; - parm1.next = &parm2; - parm1.macroText = *invStr; - parm2.prev = &parm1; - parm2.next = NULL; - parm2.macroText = (char *)"1"; - - MacroMathFunction(&tMEntry, recognizedLen, invStr, "-"); - // skip ')' - (*recognizedLen)++; -} - -//===================================================================== -// Function: MacroAddFunction -// Description: Comes here after macro replacement is done to add -// macro replacement string (ie, register) -// Parameters: lookStr = string after '(', so we can get parameters -// recognizedLen = # characters recoginized so far -// invStr = invoked replacement string so far -// Returns: new recognizedLen, invStr, with incremented # -//===================================================================== -void MacroAddFunction(char *lookStr, unsigned int *recognizedLen, char **invStr) -{ - MACROENTRY tMEntry; - MACROTEXT *curMT; - MACROTEXT *nextMT; - unsigned int i; - - tMEntry.macroName = (char *)"%add()"; - if (strlen(lookStr) > MAXREPLACESTRING) - { - LexError("Out of Temporary string replacement memory inside builtin macro %add()\n"); - return; - } - if (ParseBuiltInMacroParms(&tMEntry, lookStr)) - { - MacroMathFunction(&tMEntry, recognizedLen, invStr, "+"); - // skip ',' strlen(parm2)+ ')' - (*recognizedLen) += strlen(tMEntry.firstMacroParms->next->macroText)+2; - } - - curMT = tMEntry.firstMacroParms; - // in this case only one string was allocated - free(curMT->macroText); - for (i=0; inext; - free(curMT); - curMT = nextMT; - } -} - -//===================================================================== -// Function: MacroSubFunction -// Description: Comes here after macro replacement is done to subtract -// macro replacement string (ie, register) -// Parameters: invParms, parameters that macro was invoked with -// recognizedLen = # characters recoginized so far -// invStr = invoked replacement string so far -// Returns: new recognizedLen, invStr, with incremented # -//===================================================================== -void MacroSubFunction(char *lookStr, unsigned int *recognizedLen, char **invStr) -{ - MACROENTRY tMEntry; - MACROTEXT *curMT; - MACROTEXT *nextMT; - unsigned int i; - - tMEntry.macroName = (char *)"%sub()"; - if (ParseBuiltInMacroParms(&tMEntry, lookStr)) - { - MacroMathFunction(&tMEntry, recognizedLen, invStr, "-"); - // skip ',' strlen(parm2)+ ')' - (*recognizedLen) += strlen(tMEntry.firstMacroParms->next->macroText)+2; - } - curMT = tMEntry.firstMacroParms; - // in this case only one string was allocated - free(curMT->macroText); - for (i=0; inext; - free(curMT); - curMT = nextMT; - } -} - -//===================================================================== -// Function: EndMacroParms -// Description: Does update and cleanup one end of macro parameters -// is reached -// Parameters: . -// Returns: . -//===================================================================== -void EndMacroParms() -{ - char *curFileName; - char *macroFileName; - char tempStr[1024]; - char *macroText; - - if (gbTempInsideMacro) - { - if (gTempParseMacro->numParms != gTempMacro->numParms) - { - LexError("Macro invocation number of parameters do not match macro definition, skipping\n"); - BEGIN(INITIAL); - SAFEFREE(gTempMacro); - } - else - { - // we got all the parameters for the MACRO invocation, so start inside - // the macro now, by saving off current state on stack - gIncludeStack[gIncludeStackIndex].lineNo = yylineno; - gIncludeStack[gIncludeStackIndex].fileName = gCurFileName; -// gIncludeStack[gIncludeStackIndex].fileHandle = yyin; -//fprintf( stderr, "Chris fix this code with myin stuff\n" ); - gIncludeStack[gIncludeStackIndex].prevString = myin; - gIncludeStack[gIncludeStackIndex].nextString = NULL; - gIncludeStack[gIncludeStackIndex].lastInvokeMacro = gInvokeMacro; - gIncludeStack[gIncludeStackIndex].lastParseMacro = gParseMacro; - gIncludeStack[gIncludeStackIndex].lastMacroLineParse = gMacroLineParse; - gIncludeStack[gIncludeStackIndex].lastbInsideMacro = gbInsideMacro; - gIncludeStack[gIncludeStackIndex].lastbInsideInclude = gbInsideInclude; - gIncludeStack[gIncludeStackIndex].buffer = YY_CURRENT_BUFFER; - gIncludeStack[gIncludeStackIndex].lastbProcessingIFDEF = gbProcessingIFDEF; - gIncludeStackIndex++; - - gParseMacro = gTempParseMacro; - gInvokeMacro = gTempMacro; - gbInsideMacro = gbTempInsideMacro; - - gbTempInsideMacro = false; - -// yyin = NULL; - myin = NULL; - curFileName = gCurFileName; - if (curFileName == NULL) - curFileName = (char *)""; - - macroFileName = gParseMacro->fileName; - if (macroFileName == NULL) - macroFileName = (char *)""; - - sprintf(tempStr, "%s(%d) : References ->\n%s", curFileName, yylineno, macroFileName); - gCurFileName = strdup(tempStr); - gMacroLineParse = gParseMacro->firstMacroLines; - - macroText = gMacroLine; - // if no replacement text, just use source line - if (gParseMacro->firstMacroParms == NULL) - { - macroText = gMacroLineParse->macroText; - } - else - { - // replace the macro parameters - ReplaceMacroParms(gMacroLineParse->macroText, gMacroLine, gParseMacro, gInvokeMacro); - } - - yylineno = gParseMacro->lineNo; - if (gParseMacro->nLines >= 1) - { - strcpy(gSaveLine, macroText); - } - -// if (gExpandMacros && (gParseMacro->nLines >= 1)) -// { -// // in case there is anything there dump it out -// GenDebugLine(); -// GenListString(); -// if (gInvokeMacro->nLines >= 1) -// GenSwitchFileNames(macroFileName); -// } - - BEGIN(gInvokeState); - yy_scan_string(macroText); - gInvokeState = INITIAL; - } - } - else - { - if (gLastMacro != NULL) - { - gLastMacro->next = gTempMacro; - } - gLastMacro = gTempMacro; - BEGIN(MACROBODY); - } -} - -//===================================================================== -// Function: FindSwizzleValue -// Description: see if valid swizzle value and return the bits -// Parameters: swizzleTex = pointer to characters to analyze -// Returns: unsigned int = bits for swizzle values, or 0 for error -//===================================================================== -unsigned int FindSwizzleValue(char *swizzleText) -{ - unsigned int swizzleBits; - unsigned int sLen; - unsigned int i; - unsigned int lastMask; - - sLen = strlen(swizzleText); - swizzleBits = 0; - lastMask = 0; - - for (i=0; i. */ - -/* As a special exception, you may create a larger work that contains - part or all of the Bison parser skeleton and distribute that work - under terms of your choice, so long as that work isn't itself a - parser generator using the skeleton or a modified version thereof - as a parser skeleton. Alternatively, if you modify or redistribute - the parser skeleton itself, you may (at your option) remove this - special exception, which will cause the skeleton and the resulting - Bison output files to be licensed under the GNU General Public - License without this special exception. - - This special exception was added by the Free Software Foundation in - version 2.2 of Bison. */ - -/* C LALR(1) parser skeleton written by Richard Stallman, by - simplifying the original so-called "semantic" parser. */ - -/* All symbols defined below should begin with yy or YY, to avoid - infringing on user name space. This should be done even for local - variables, as they might otherwise be expanded by user macros. - There are some unavoidable exceptions within include files to - define necessary library symbols; they are noted "INFRINGES ON - USER NAME SPACE" below. */ - -/* Identify Bison output. */ -#define YYBISON 1 - -/* Bison version. */ -#define YYBISON_VERSION "3.0.2" - -/* Skeleton name. */ -#define YYSKELETON_NAME "yacc.c" - -/* Pure parsers. */ -#define YYPURE 0 - -/* Push parsers. */ -#define YYPUSH 0 - -/* Pull parsers. */ -#define YYPULL 1 - - -/* Substitute the variable and function names. */ -#define yyparse vs10_parse -#define yylex vs10_lex -#define yyerror vs10_error -#define yydebug vs10_debug -#define yynerrs vs10_nerrs - -#define yylval vs10_lval -#define yychar vs10_char - -/* Copy the first part of user declarations. */ -#line 3 "vs1.0_grammar.y" /* yacc.c:339 */ - -void yyerror(const char *s); -int yylex(void); - -#include -#include - -#include -#include "vs1.0_inst_list.h" -#include "nvparse_errors.h" -#include "nvparse_externs.h" - -//extern bool gbTempInsideMacro; -//extern unsigned int &base_linenumber; -void LexError(const char *format, ...); -extern int line_incr; - -#define do_linenum_incr() { line_number+=line_incr; line_incr = 0; } -//int get_linenum() { return( gbTempInsideMacro ? base_linenumber : line_number ); } -int get_linenum() { return( line_number ); } - -#define YYDEBUG 1 - - -#line 99 "_vs1.0_parser.c" /* yacc.c:339 */ - -# ifndef YY_NULLPTR -# if defined __cplusplus && 201103L <= __cplusplus -# define YY_NULLPTR nullptr -# else -# define YY_NULLPTR 0 -# endif -# endif - -/* Enabling verbose error messages. */ -#ifdef YYERROR_VERBOSE -# undef YYERROR_VERBOSE -# define YYERROR_VERBOSE 1 -#else -# define YYERROR_VERBOSE 0 -#endif - -/* In a future release of Bison, this section will be replaced - by #include "_vs1.0_parser.h". */ -#ifndef YY_VS10_VS1_0_PARSER_H_INCLUDED -# define YY_VS10_VS1_0_PARSER_H_INCLUDED -/* Debug traces. */ -#ifndef YYDEBUG -# define YYDEBUG 0 -#endif -#if YYDEBUG -extern int vs10_debug; -#endif - -/* Token type. */ -#ifndef YYTOKENTYPE -# define YYTOKENTYPE - enum yytokentype - { - VERTEX_SHADER = 258, - ADD_INSTR = 259, - DP3_INSTR = 260, - DP4_INSTR = 261, - DST_INSTR = 262, - EXP_INSTR = 263, - EXPP_INSTR = 264, - FRC_INSTR = 265, - LIT_INSTR = 266, - LOG_INSTR = 267, - LOGP_INSTR = 268, - M3X2_INSTR = 269, - M3X3_INSTR = 270, - M3X4_INSTR = 271, - M4X3_INSTR = 272, - M4X4_INSTR = 273, - MAD_INSTR = 274, - MAX_INSTR = 275, - MIN_INSTR = 276, - MOV_INSTR = 277, - MUL_INSTR = 278, - NOP_INSTR = 279, - RCP_INSTR = 280, - RSQ_INSTR = 281, - SGE_INSTR = 282, - SLT_INSTR = 283, - SUB_INSTR = 284, - ILLEGAL = 285, - UNKNOWN_STRING = 286, - INTVAL = 287, - REGISTER = 288, - XYZW_MODIFIER = 289, - COMMENT = 290 - }; -#endif - -/* Value type. */ -#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED -typedef union YYSTYPE YYSTYPE; -union YYSTYPE -{ -#line 27 "vs1.0_grammar.y" /* yacc.c:355 */ - - int ival; - unsigned int lval; - float fval; - char mask[4]; - char *comment; - VS10Reg reg; - VS10InstPtr inst; - VS10InstListPtr instList; - -#line 186 "_vs1.0_parser.c" /* yacc.c:355 */ -}; -# define YYSTYPE_IS_TRIVIAL 1 -# define YYSTYPE_IS_DECLARED 1 -#endif - - -extern YYSTYPE vs10_lval; - -int vs10_parse (void); - -#endif /* !YY_VS10_VS1_0_PARSER_H_INCLUDED */ - -/* Copy the second part of user declarations. */ - -#line 201 "_vs1.0_parser.c" /* yacc.c:358 */ - -#ifdef short -# undef short -#endif - -#ifdef YYTYPE_UINT8 -typedef YYTYPE_UINT8 yytype_uint8; -#else -typedef unsigned char yytype_uint8; -#endif - -#ifdef YYTYPE_INT8 -typedef YYTYPE_INT8 yytype_int8; -#else -typedef signed char yytype_int8; -#endif - -#ifdef YYTYPE_UINT16 -typedef YYTYPE_UINT16 yytype_uint16; -#else -typedef unsigned short int yytype_uint16; -#endif - -#ifdef YYTYPE_INT16 -typedef YYTYPE_INT16 yytype_int16; -#else -typedef short int yytype_int16; -#endif - -#ifndef YYSIZE_T -# ifdef __SIZE_TYPE__ -# define YYSIZE_T __SIZE_TYPE__ -# elif defined size_t -# define YYSIZE_T size_t -# elif ! defined YYSIZE_T -# include /* INFRINGES ON USER NAME SPACE */ -# define YYSIZE_T size_t -# else -# define YYSIZE_T unsigned int -# endif -#endif - -#define YYSIZE_MAXIMUM ((YYSIZE_T) -1) - -#ifndef YY_ -# if defined YYENABLE_NLS && YYENABLE_NLS -# if ENABLE_NLS -# include /* INFRINGES ON USER NAME SPACE */ -# define YY_(Msgid) dgettext ("bison-runtime", Msgid) -# endif -# endif -# ifndef YY_ -# define YY_(Msgid) Msgid -# endif -#endif - -#ifndef YY_ATTRIBUTE -# if (defined __GNUC__ \ - && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \ - || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C -# define YY_ATTRIBUTE(Spec) __attribute__(Spec) -# else -# define YY_ATTRIBUTE(Spec) /* empty */ -# endif -#endif - -#ifndef YY_ATTRIBUTE_PURE -# define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__)) -#endif - -#ifndef YY_ATTRIBUTE_UNUSED -# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__)) -#endif - -#if !defined _Noreturn \ - && (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112) -# if defined _MSC_VER && 1200 <= _MSC_VER -# define _Noreturn __declspec (noreturn) -# else -# define _Noreturn YY_ATTRIBUTE ((__noreturn__)) -# endif -#endif - -/* Suppress unused-variable warnings by "using" E. */ -#if ! defined lint || defined __GNUC__ -# define YYUSE(E) ((void) (E)) -#else -# define YYUSE(E) /* empty */ -#endif - -#if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ -/* Suppress an incorrect diagnostic about yylval being uninitialized. */ -# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ - _Pragma ("GCC diagnostic push") \ - _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\ - _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") -# define YY_IGNORE_MAYBE_UNINITIALIZED_END \ - _Pragma ("GCC diagnostic pop") -#else -# define YY_INITIAL_VALUE(Value) Value -#endif -#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN -# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN -# define YY_IGNORE_MAYBE_UNINITIALIZED_END -#endif -#ifndef YY_INITIAL_VALUE -# define YY_INITIAL_VALUE(Value) /* Nothing. */ -#endif - - -#if ! defined yyoverflow || YYERROR_VERBOSE - -/* The parser invokes alloca or malloc; define the necessary symbols. */ - -# ifdef YYSTACK_USE_ALLOCA -# if YYSTACK_USE_ALLOCA -# ifdef __GNUC__ -# define YYSTACK_ALLOC __builtin_alloca -# elif defined __BUILTIN_VA_ARG_INCR -# include /* INFRINGES ON USER NAME SPACE */ -# elif defined _AIX -# define YYSTACK_ALLOC __alloca -# elif defined _MSC_VER -# include /* INFRINGES ON USER NAME SPACE */ -# define alloca _alloca -# else -# define YYSTACK_ALLOC alloca -# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS -# include /* INFRINGES ON USER NAME SPACE */ - /* Use EXIT_SUCCESS as a witness for stdlib.h. */ -# ifndef EXIT_SUCCESS -# define EXIT_SUCCESS 0 -# endif -# endif -# endif -# endif -# endif - -# ifdef YYSTACK_ALLOC - /* Pacify GCC's 'empty if-body' warning. */ -# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) -# ifndef YYSTACK_ALLOC_MAXIMUM - /* The OS might guarantee only one guard page at the bottom of the stack, - and a page size can be as small as 4096 bytes. So we cannot safely - invoke alloca (N) if N exceeds 4096. Use a slightly smaller number - to allow for a few compiler-allocated temporary stack slots. */ -# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ -# endif -# else -# define YYSTACK_ALLOC YYMALLOC -# define YYSTACK_FREE YYFREE -# ifndef YYSTACK_ALLOC_MAXIMUM -# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM -# endif -# if (defined __cplusplus && ! defined EXIT_SUCCESS \ - && ! ((defined YYMALLOC || defined malloc) \ - && (defined YYFREE || defined free))) -# include /* INFRINGES ON USER NAME SPACE */ -# ifndef EXIT_SUCCESS -# define EXIT_SUCCESS 0 -# endif -# endif -# ifndef YYMALLOC -# define YYMALLOC malloc -# if ! defined malloc && ! defined EXIT_SUCCESS -void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ -# endif -# endif -# ifndef YYFREE -# define YYFREE free -# if ! defined free && ! defined EXIT_SUCCESS -void free (void *); /* INFRINGES ON USER NAME SPACE */ -# endif -# endif -# endif -#endif /* ! defined yyoverflow || YYERROR_VERBOSE */ - - -#if (! defined yyoverflow \ - && (! defined __cplusplus \ - || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) - -/* A type that is properly aligned for any stack member. */ -union yyalloc -{ - yytype_int16 yyss_alloc; - YYSTYPE yyvs_alloc; -}; - -/* The size of the maximum gap between one aligned stack and the next. */ -# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) - -/* The size of an array large to enough to hold all stacks, each with - N elements. */ -# define YYSTACK_BYTES(N) \ - ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ - + YYSTACK_GAP_MAXIMUM) - -# define YYCOPY_NEEDED 1 - -/* Relocate STACK from its old location to the new one. The - local variables YYSIZE and YYSTACKSIZE give the old and new number of - elements in the stack, and YYPTR gives the new location of the - stack. Advance YYPTR to a properly aligned location for the next - stack. */ -# define YYSTACK_RELOCATE(Stack_alloc, Stack) \ - do \ - { \ - YYSIZE_T yynewbytes; \ - YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ - Stack = &yyptr->Stack_alloc; \ - yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ - yyptr += yynewbytes / sizeof (*yyptr); \ - } \ - while (0) - -#endif - -#if defined YYCOPY_NEEDED && YYCOPY_NEEDED -/* Copy COUNT objects from SRC to DST. The source and destination do - not overlap. */ -# ifndef YYCOPY -# if defined __GNUC__ && 1 < __GNUC__ -# define YYCOPY(Dst, Src, Count) \ - __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src))) -# else -# define YYCOPY(Dst, Src, Count) \ - do \ - { \ - YYSIZE_T yyi; \ - for (yyi = 0; yyi < (Count); yyi++) \ - (Dst)[yyi] = (Src)[yyi]; \ - } \ - while (0) -# endif -# endif -#endif /* !YYCOPY_NEEDED */ - -/* YYFINAL -- State number of the termination state. */ -#define YYFINAL 44 -/* YYLAST -- Last index in YYTABLE. */ -#define YYLAST 88 - -/* YYNTOKENS -- Number of terminals. */ -#define YYNTOKENS 44 -/* YYNNTS -- Number of nonterminals. */ -#define YYNNTS 18 -/* YYNRULES -- Number of rules. */ -#define YYNRULES 59 -/* YYNSTATES -- Number of states. */ -#define YYNSTATES 103 - -/* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned - by yylex, with out-of-bounds checking. */ -#define YYUNDEFTOK 2 -#define YYMAXUTOK 290 - -#define YYTRANSLATE(YYX) \ - ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) - -/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM - as returned by yylex, without out-of-bounds checking. */ -static const yytype_uint8 yytranslate[] = -{ - 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 36, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 43, 37, 38, 39, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 41, 2, 42, 2, 2, 2, 2, 2, 40, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, - 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, - 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, - 35 -}; - -#if YYDEBUG - /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ -static const yytype_uint16 yyrline[] = -{ - 0, 96, 96, 104, 110, 122, 127, 134, 135, 136, - 137, 138, 139, 143, 147, 153, 159, 169, 179, 189, - 200, 200, 204, 211, 246, 282, 287, 292, 297, 302, - 307, 314, 320, 326, 332, 339, 343, 349, 353, 357, - 361, 365, 369, 375, 381, 385, 389, 393, 397, 401, - 405, 409, 413, 417, 421, 425, 429, 433, 437, 443 -}; -#endif - -#if YYDEBUG || YYERROR_VERBOSE || 0 -/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. - First, the terminals, then, starting at YYNTOKENS, nonterminals. */ -static const char *const yytname[] = -{ - "$end", "error", "$undefined", "VERTEX_SHADER", "ADD_INSTR", - "DP3_INSTR", "DP4_INSTR", "DST_INSTR", "EXP_INSTR", "EXPP_INSTR", - "FRC_INSTR", "LIT_INSTR", "LOG_INSTR", "LOGP_INSTR", "M3X2_INSTR", - "M3X3_INSTR", "M3X4_INSTR", "M4X3_INSTR", "M4X4_INSTR", "MAD_INSTR", - "MAX_INSTR", "MIN_INSTR", "MOV_INSTR", "MUL_INSTR", "NOP_INSTR", - "RCP_INSTR", "RSQ_INSTR", "SGE_INSTR", "SLT_INSTR", "SUB_INSTR", - "ILLEGAL", "UNKNOWN_STRING", "INTVAL", "REGISTER", "XYZW_MODIFIER", - "COMMENT", "'\\n'", "','", "'-'", "'.'", "'c'", "'['", "']'", "'+'", - "$accept", "VS10Program", "InstSequence", "InstLine", "Instruction", - "VECTORopinstruction", "genericReg", "genReg", "constantReg", - "SCALARopinstruction", "UNARYopinstruction", "BINopinstruction", - "TRIopinstruction", "VECTORop", "SCALARop", "UNARYop", "BINop", "TRIop", YY_NULLPTR -}; -#endif - -# ifdef YYPRINT -/* YYTOKNUM[NUM] -- (External) token number corresponding to the - (internal) symbol number NUM (which must be that of a token). */ -static const yytype_uint16 yytoknum[] = -{ - 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, - 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, - 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, - 285, 286, 287, 288, 289, 290, 10, 44, 45, 46, - 99, 91, 93, 43 -}; -# endif - -#define YYPACT_NINF -41 - -#define yypact_value_is_default(Yystate) \ - (!!((Yystate) == (-41))) - -#define YYTABLE_NINF -1 - -#define yytable_value_is_error(Yytable_value) \ - 0 - - /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing - STATE-NUM. */ -static const yytype_int8 yypact[] = -{ - 52, -41, -41, -41, -41, -41, -41, -41, -41, -41, - -41, -41, -41, -41, -41, -41, -41, -41, -41, -41, - -41, -41, -41, -41, -41, -41, -41, -41, -41, -41, - 6, 52, -41, -41, -41, -41, -41, -41, -41, -29, - -29, -29, -29, -29, -41, -41, -41, -28, -31, -23, - -22, -41, -18, -12, -4, -3, -2, -25, -29, 1, - -29, -29, -29, -29, 2, 0, -15, 5, -41, -41, - -41, -41, 7, 8, -41, -41, 9, -41, 14, -13, - -29, -29, -27, 10, 13, -41, 16, -41, 12, -41, - 18, -41, -11, 11, -29, 40, -41, 19, -41, -41, - -41, 41, -41 -}; - - /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. - Performed when YYTABLE does not specify something else to do. Zero - means the default is an error. */ -static const yytype_uint8 yydefact[] = -{ - 0, 14, 45, 46, 47, 48, 39, 40, 43, 36, - 41, 42, 53, 54, 55, 56, 57, 59, 50, 49, - 35, 44, 12, 37, 38, 52, 51, 58, 13, 6, - 0, 2, 4, 5, 7, 8, 9, 10, 11, 0, - 0, 0, 0, 0, 1, 3, 20, 0, 0, 0, - 19, 21, 0, 0, 0, 0, 18, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 15, 17, - 31, 32, 0, 0, 16, 22, 0, 25, 0, 0, - 0, 0, 0, 0, 0, 27, 0, 33, 0, 23, - 0, 26, 0, 0, 0, 0, 29, 0, 28, 34, - 24, 0, 30 -}; - - /* YYPGOTO[NTERM-NUM]. */ -static const yytype_int8 yypgoto[] = -{ - -41, -41, -41, 53, -41, -41, -40, -8, -41, -41, - -41, -41, -41, -41, -41, -41, -41, -41 -}; - - /* YYDEFGOTO[NTERM-NUM]. */ -static const yytype_int8 yydefgoto[] = -{ - -1, 30, 31, 32, 33, 34, 49, 50, 51, 35, - 36, 37, 38, 39, 40, 41, 42, 43 -}; - - /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If - positive, shift that token. If negative, reduce the rule whose - number is the opposite. If YYTABLE_NINF, syntax error. */ -static const yytype_uint8 yytable[] = -{ - 52, 53, 54, 55, 46, 46, 44, 65, 66, 47, - 57, 48, 48, 67, 58, 89, 90, 59, 68, 60, - 70, 71, 72, 73, 76, 61, 84, 77, 78, 85, - 86, 96, 97, 62, 63, 69, 74, 64, 79, 56, - 87, 88, 75, 82, 80, 81, 83, 92, 93, 94, - 95, 101, 91, 98, 99, 1, 2, 3, 4, 5, - 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, - 26, 27, 100, 102, 45, 0, 0, 28, 29 -}; - -static const yytype_int8 yycheck[] = -{ - 40, 41, 42, 43, 33, 33, 0, 32, 33, 38, - 41, 40, 40, 38, 37, 42, 43, 39, 58, 37, - 60, 61, 62, 63, 39, 37, 39, 42, 43, 42, - 43, 42, 43, 37, 37, 34, 34, 39, 33, 47, - 80, 81, 42, 34, 37, 37, 32, 34, 32, 37, - 32, 32, 42, 42, 94, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, - 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, - 28, 29, 42, 42, 31, -1, -1, 35, 36 -}; - - /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing - symbol of state STATE-NUM. */ -static const yytype_uint8 yystos[] = -{ - 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, - 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, - 22, 23, 24, 25, 26, 27, 28, 29, 35, 36, - 45, 46, 47, 48, 49, 53, 54, 55, 56, 57, - 58, 59, 60, 61, 0, 47, 33, 38, 40, 50, - 51, 52, 50, 50, 50, 50, 51, 41, 37, 39, - 37, 37, 37, 37, 39, 32, 33, 38, 50, 34, - 50, 50, 50, 50, 34, 42, 39, 42, 43, 33, - 37, 37, 34, 32, 39, 42, 43, 50, 50, 42, - 43, 42, 34, 32, 37, 32, 42, 43, 42, 50, - 42, 32, 42 -}; - - /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ -static const yytype_uint8 yyr1[] = -{ - 0, 44, 45, 46, 46, 47, 47, 48, 48, 48, - 48, 48, 48, 48, 48, 49, 50, 50, 50, 50, - 51, 51, 52, 52, 52, 52, 52, 52, 52, 52, - 52, 53, 54, 55, 56, 57, 57, 58, 58, 58, - 58, 58, 58, 59, 60, 60, 60, 60, 60, 60, - 60, 60, 60, 60, 60, 60, 60, 60, 60, 61 -}; - - /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */ -static const yytype_uint8 yyr2[] = -{ - 0, 2, 1, 2, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 4, 4, 3, 2, 1, - 1, 1, 4, 6, 8, 4, 6, 5, 7, 7, - 9, 4, 4, 6, 8, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 -}; - - -#define yyerrok (yyerrstatus = 0) -#define yyclearin (yychar = YYEMPTY) -#define YYEMPTY (-2) -#define YYEOF 0 - -#define YYACCEPT goto yyacceptlab -#define YYABORT goto yyabortlab -#define YYERROR goto yyerrorlab - - -#define YYRECOVERING() (!!yyerrstatus) - -#define YYBACKUP(Token, Value) \ -do \ - if (yychar == YYEMPTY) \ - { \ - yychar = (Token); \ - yylval = (Value); \ - YYPOPSTACK (yylen); \ - yystate = *yyssp; \ - goto yybackup; \ - } \ - else \ - { \ - yyerror (YY_("syntax error: cannot back up")); \ - YYERROR; \ - } \ -while (0) - -/* Error token number */ -#define YYTERROR 1 -#define YYERRCODE 256 - - - -/* Enable debugging if requested. */ -#if YYDEBUG - -# ifndef YYFPRINTF -# include /* INFRINGES ON USER NAME SPACE */ -# define YYFPRINTF fprintf -# endif - -# define YYDPRINTF(Args) \ -do { \ - if (yydebug) \ - YYFPRINTF Args; \ -} while (0) - -/* This macro is provided for backward compatibility. */ -#ifndef YY_LOCATION_PRINT -# define YY_LOCATION_PRINT(File, Loc) ((void) 0) -#endif - - -# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ -do { \ - if (yydebug) \ - { \ - YYFPRINTF (stderr, "%s ", Title); \ - yy_symbol_print (stderr, \ - Type, Value); \ - YYFPRINTF (stderr, "\n"); \ - } \ -} while (0) - - -/*----------------------------------------. -| Print this symbol's value on YYOUTPUT. | -`----------------------------------------*/ - -static void -yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) -{ - FILE *yyo = yyoutput; - YYUSE (yyo); - if (!yyvaluep) - return; -# ifdef YYPRINT - if (yytype < YYNTOKENS) - YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); -# endif - YYUSE (yytype); -} - - -/*--------------------------------. -| Print this symbol on YYOUTPUT. | -`--------------------------------*/ - -static void -yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep) -{ - YYFPRINTF (yyoutput, "%s %s (", - yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]); - - yy_symbol_value_print (yyoutput, yytype, yyvaluep); - YYFPRINTF (yyoutput, ")"); -} - -/*------------------------------------------------------------------. -| yy_stack_print -- Print the state stack from its BOTTOM up to its | -| TOP (included). | -`------------------------------------------------------------------*/ - -static void -yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) -{ - YYFPRINTF (stderr, "Stack now"); - for (; yybottom <= yytop; yybottom++) - { - int yybot = *yybottom; - YYFPRINTF (stderr, " %d", yybot); - } - YYFPRINTF (stderr, "\n"); -} - -# define YY_STACK_PRINT(Bottom, Top) \ -do { \ - if (yydebug) \ - yy_stack_print ((Bottom), (Top)); \ -} while (0) - - -/*------------------------------------------------. -| Report that the YYRULE is going to be reduced. | -`------------------------------------------------*/ - -static void -yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule) -{ - unsigned long int yylno = yyrline[yyrule]; - int yynrhs = yyr2[yyrule]; - int yyi; - YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", - yyrule - 1, yylno); - /* The symbols being reduced. */ - for (yyi = 0; yyi < yynrhs; yyi++) - { - YYFPRINTF (stderr, " $%d = ", yyi + 1); - yy_symbol_print (stderr, - yystos[yyssp[yyi + 1 - yynrhs]], - &(yyvsp[(yyi + 1) - (yynrhs)]) - ); - YYFPRINTF (stderr, "\n"); - } -} - -# define YY_REDUCE_PRINT(Rule) \ -do { \ - if (yydebug) \ - yy_reduce_print (yyssp, yyvsp, Rule); \ -} while (0) - -/* Nonzero means print parse trace. It is left uninitialized so that - multiple parsers can coexist. */ -int yydebug; -#else /* !YYDEBUG */ -# define YYDPRINTF(Args) -# define YY_SYMBOL_PRINT(Title, Type, Value, Location) -# define YY_STACK_PRINT(Bottom, Top) -# define YY_REDUCE_PRINT(Rule) -#endif /* !YYDEBUG */ - - -/* YYINITDEPTH -- initial size of the parser's stacks. */ -#ifndef YYINITDEPTH -# define YYINITDEPTH 200 -#endif - -/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only - if the built-in stack extension method is used). - - Do not make this value too large; the results are undefined if - YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) - evaluated with infinite-precision integer arithmetic. */ - -#ifndef YYMAXDEPTH -# define YYMAXDEPTH 10000 -#endif - - -#if YYERROR_VERBOSE - -# ifndef yystrlen -# if defined __GLIBC__ && defined _STRING_H -# define yystrlen strlen -# else -/* Return the length of YYSTR. */ -static YYSIZE_T -yystrlen (const char *yystr) -{ - YYSIZE_T yylen; - for (yylen = 0; yystr[yylen]; yylen++) - continue; - return yylen; -} -# endif -# endif - -# ifndef yystpcpy -# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE -# define yystpcpy stpcpy -# else -/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in - YYDEST. */ -static char * -yystpcpy (char *yydest, const char *yysrc) -{ - char *yyd = yydest; - const char *yys = yysrc; - - while ((*yyd++ = *yys++) != '\0') - continue; - - return yyd - 1; -} -# endif -# endif - -# ifndef yytnamerr -/* Copy to YYRES the contents of YYSTR after stripping away unnecessary - quotes and backslashes, so that it's suitable for yyerror. The - heuristic is that double-quoting is unnecessary unless the string - contains an apostrophe, a comma, or backslash (other than - backslash-backslash). YYSTR is taken from yytname. If YYRES is - null, do not copy; instead, return the length of what the result - would have been. */ -static YYSIZE_T -yytnamerr (char *yyres, const char *yystr) -{ - if (*yystr == '"') - { - YYSIZE_T yyn = 0; - char const *yyp = yystr; - - for (;;) - switch (*++yyp) - { - case '\'': - case ',': - goto do_not_strip_quotes; - - case '\\': - if (*++yyp != '\\') - goto do_not_strip_quotes; - /* Fall through. */ - default: - if (yyres) - yyres[yyn] = *yyp; - yyn++; - break; - - case '"': - if (yyres) - yyres[yyn] = '\0'; - return yyn; - } - do_not_strip_quotes: ; - } - - if (! yyres) - return yystrlen (yystr); - - return yystpcpy (yyres, yystr) - yyres; -} -# endif - -/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message - about the unexpected token YYTOKEN for the state stack whose top is - YYSSP. - - Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is - not large enough to hold the message. In that case, also set - *YYMSG_ALLOC to the required number of bytes. Return 2 if the - required number of bytes is too large to store. */ -static int -yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg, - yytype_int16 *yyssp, int yytoken) -{ - YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]); - YYSIZE_T yysize = yysize0; - enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; - /* Internationalized format string. */ - const char *yyformat = YY_NULLPTR; - /* Arguments of yyformat. */ - char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; - /* Number of reported tokens (one for the "unexpected", one per - "expected"). */ - int yycount = 0; - - /* There are many possibilities here to consider: - - If this state is a consistent state with a default action, then - the only way this function was invoked is if the default action - is an error action. In that case, don't check for expected - tokens because there are none. - - The only way there can be no lookahead present (in yychar) is if - this state is a consistent state with a default action. Thus, - detecting the absence of a lookahead is sufficient to determine - that there is no unexpected or expected token to report. In that - case, just report a simple "syntax error". - - Don't assume there isn't a lookahead just because this state is a - consistent state with a default action. There might have been a - previous inconsistent state, consistent state with a non-default - action, or user semantic action that manipulated yychar. - - Of course, the expected token list depends on states to have - correct lookahead information, and it depends on the parser not - to perform extra reductions after fetching a lookahead from the - scanner and before detecting a syntax error. Thus, state merging - (from LALR or IELR) and default reductions corrupt the expected - token list. However, the list is correct for canonical LR with - one exception: it will still contain any token that will not be - accepted due to an error action in a later state. - */ - if (yytoken != YYEMPTY) - { - int yyn = yypact[*yyssp]; - yyarg[yycount++] = yytname[yytoken]; - if (!yypact_value_is_default (yyn)) - { - /* Start YYX at -YYN if negative to avoid negative indexes in - YYCHECK. In other words, skip the first -YYN actions for - this state because they are default actions. */ - int yyxbegin = yyn < 0 ? -yyn : 0; - /* Stay within bounds of both yycheck and yytname. */ - int yychecklim = YYLAST - yyn + 1; - int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; - int yyx; - - for (yyx = yyxbegin; yyx < yyxend; ++yyx) - if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR - && !yytable_value_is_error (yytable[yyx + yyn])) - { - if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) - { - yycount = 1; - yysize = yysize0; - break; - } - yyarg[yycount++] = yytname[yyx]; - { - YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]); - if (! (yysize <= yysize1 - && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) - return 2; - yysize = yysize1; - } - } - } - } - - switch (yycount) - { -# define YYCASE_(N, S) \ - case N: \ - yyformat = S; \ - break - YYCASE_(0, YY_("syntax error")); - YYCASE_(1, YY_("syntax error, unexpected %s")); - YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); - YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); - YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); - YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); -# undef YYCASE_ - } - - { - YYSIZE_T yysize1 = yysize + yystrlen (yyformat); - if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) - return 2; - yysize = yysize1; - } - - if (*yymsg_alloc < yysize) - { - *yymsg_alloc = 2 * yysize; - if (! (yysize <= *yymsg_alloc - && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) - *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; - return 1; - } - - /* Avoid sprintf, as that infringes on the user's name space. - Don't have undefined behavior even if the translation - produced a string with the wrong number of "%s"s. */ - { - char *yyp = *yymsg; - int yyi = 0; - while ((*yyp = *yyformat) != '\0') - if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) - { - yyp += yytnamerr (yyp, yyarg[yyi++]); - yyformat += 2; - } - else - { - yyp++; - yyformat++; - } - } - return 0; -} -#endif /* YYERROR_VERBOSE */ - -/*-----------------------------------------------. -| Release the memory associated to this symbol. | -`-----------------------------------------------*/ - -static void -yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep) -{ - YYUSE (yyvaluep); - if (!yymsg) - yymsg = "Deleting"; - YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); - - YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN - YYUSE (yytype); - YY_IGNORE_MAYBE_UNINITIALIZED_END -} - - - - -/* The lookahead symbol. */ -int yychar; - -/* The semantic value of the lookahead symbol. */ -YYSTYPE yylval; -/* Number of syntax errors so far. */ -int yynerrs; - - -/*----------. -| yyparse. | -`----------*/ - -int -yyparse (void) -{ - int yystate; - /* Number of tokens to shift before error messages enabled. */ - int yyerrstatus; - - /* The stacks and their tools: - 'yyss': related to states. - 'yyvs': related to semantic values. - - Refer to the stacks through separate pointers, to allow yyoverflow - to reallocate them elsewhere. */ - - /* The state stack. */ - yytype_int16 yyssa[YYINITDEPTH]; - yytype_int16 *yyss; - yytype_int16 *yyssp; - - /* The semantic value stack. */ - YYSTYPE yyvsa[YYINITDEPTH]; - YYSTYPE *yyvs; - YYSTYPE *yyvsp; - - YYSIZE_T yystacksize; - - int yyn; - int yyresult; - /* Lookahead token as an internal (translated) token number. */ - int yytoken = 0; - /* The variables used to return semantic value and location from the - action routines. */ - YYSTYPE yyval; - -#if YYERROR_VERBOSE - /* Buffer for error messages, and its allocated size. */ - char yymsgbuf[128]; - char *yymsg = yymsgbuf; - YYSIZE_T yymsg_alloc = sizeof yymsgbuf; -#endif - -#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) - - /* The number of symbols on the RHS of the reduced rule. - Keep to zero when no symbol should be popped. */ - int yylen = 0; - - yyssp = yyss = yyssa; - yyvsp = yyvs = yyvsa; - yystacksize = YYINITDEPTH; - - YYDPRINTF ((stderr, "Starting parse\n")); - - yystate = 0; - yyerrstatus = 0; - yynerrs = 0; - yychar = YYEMPTY; /* Cause a token to be read. */ - goto yysetstate; - -/*------------------------------------------------------------. -| yynewstate -- Push a new state, which is found in yystate. | -`------------------------------------------------------------*/ - yynewstate: - /* In all cases, when you get here, the value and location stacks - have just been pushed. So pushing a state here evens the stacks. */ - yyssp++; - - yysetstate: - *yyssp = yystate; - - if (yyss + yystacksize - 1 <= yyssp) - { - /* Get the current used size of the three stacks, in elements. */ - YYSIZE_T yysize = yyssp - yyss + 1; - -#ifdef yyoverflow - { - /* Give user a chance to reallocate the stack. Use copies of - these so that the &'s don't force the real ones into - memory. */ - YYSTYPE *yyvs1 = yyvs; - yytype_int16 *yyss1 = yyss; - - /* Each stack pointer address is followed by the size of the - data in use in that stack, in bytes. This used to be a - conditional around just the two extra args, but that might - be undefined if yyoverflow is a macro. */ - yyoverflow (YY_("memory exhausted"), - &yyss1, yysize * sizeof (*yyssp), - &yyvs1, yysize * sizeof (*yyvsp), - &yystacksize); - - yyss = yyss1; - yyvs = yyvs1; - } -#else /* no yyoverflow */ -# ifndef YYSTACK_RELOCATE - goto yyexhaustedlab; -# else - /* Extend the stack our own way. */ - if (YYMAXDEPTH <= yystacksize) - goto yyexhaustedlab; - yystacksize *= 2; - if (YYMAXDEPTH < yystacksize) - yystacksize = YYMAXDEPTH; - - { - yytype_int16 *yyss1 = yyss; - union yyalloc *yyptr = - (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); - if (! yyptr) - goto yyexhaustedlab; - YYSTACK_RELOCATE (yyss_alloc, yyss); - YYSTACK_RELOCATE (yyvs_alloc, yyvs); -# undef YYSTACK_RELOCATE - if (yyss1 != yyssa) - YYSTACK_FREE (yyss1); - } -# endif -#endif /* no yyoverflow */ - - yyssp = yyss + yysize - 1; - yyvsp = yyvs + yysize - 1; - - YYDPRINTF ((stderr, "Stack size increased to %lu\n", - (unsigned long int) yystacksize)); - - if (yyss + yystacksize - 1 <= yyssp) - YYABORT; - } - - YYDPRINTF ((stderr, "Entering state %d\n", yystate)); - - if (yystate == YYFINAL) - YYACCEPT; - - goto yybackup; - -/*-----------. -| yybackup. | -`-----------*/ -yybackup: - - /* Do appropriate processing given the current state. Read a - lookahead token if we need one and don't already have one. */ - - /* First try to decide what to do without reference to lookahead token. */ - yyn = yypact[yystate]; - if (yypact_value_is_default (yyn)) - goto yydefault; - - /* Not known => get a lookahead token if don't already have one. */ - - /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ - if (yychar == YYEMPTY) - { - YYDPRINTF ((stderr, "Reading a token: ")); - yychar = yylex (); - } - - if (yychar <= YYEOF) - { - yychar = yytoken = YYEOF; - YYDPRINTF ((stderr, "Now at end of input.\n")); - } - else - { - yytoken = YYTRANSLATE (yychar); - YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); - } - - /* If the proper action on seeing token YYTOKEN is to reduce or to - detect an error, take that action. */ - yyn += yytoken; - if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) - goto yydefault; - yyn = yytable[yyn]; - if (yyn <= 0) - { - if (yytable_value_is_error (yyn)) - goto yyerrlab; - yyn = -yyn; - goto yyreduce; - } - - /* Count tokens shifted since error; after three, turn off error - status. */ - if (yyerrstatus) - yyerrstatus--; - - /* Shift the lookahead token. */ - YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); - - /* Discard the shifted token. */ - yychar = YYEMPTY; - - yystate = yyn; - YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN - *++yyvsp = yylval; - YY_IGNORE_MAYBE_UNINITIALIZED_END - - goto yynewstate; - - -/*-----------------------------------------------------------. -| yydefault -- do the default action for the current state. | -`-----------------------------------------------------------*/ -yydefault: - yyn = yydefact[yystate]; - if (yyn == 0) - goto yyerrlab; - goto yyreduce; - - -/*-----------------------------. -| yyreduce -- Do a reduction. | -`-----------------------------*/ -yyreduce: - /* yyn is the number of a rule to reduce with. */ - yylen = yyr2[yyn]; - - /* If YYLEN is nonzero, implement the default value of the action: - '$$ = $1'. - - Otherwise, the following line sets YYVAL to garbage. - This behavior is undocumented and Bison - users should not rely upon it. Assigning to YYVAL - unconditionally makes the parser a bit smaller, and it avoids a - GCC warning that YYVAL may be used uninitialized. */ - yyval = yyvsp[1-yylen]; - - - YY_REDUCE_PRINT (yyn); - switch (yyn) - { - case 2: -#line 97 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyvsp[0].instList)->Validate(); - (yyvsp[0].instList)->Translate(); - delete (yyvsp[0].instList); - } -#line 1351 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 3: -#line 105 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - *((yyvsp[-1].instList)) += (yyvsp[0].inst); - delete (yyvsp[0].inst); - (yyval.instList) = (yyvsp[-1].instList); - } -#line 1361 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 4: -#line 111 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - VS10InstListPtr instList = new VS10InstList; - if ( (yyvsp[0].inst) != NULL ) - { - *instList += (yyvsp[0].inst); - delete (yyvsp[0].inst); - } - (yyval.instList) = instList; - } -#line 1375 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 5: -#line 123 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = (yyvsp[0].inst); - do_linenum_incr(); - } -#line 1384 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 6: -#line 128 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new VS10Inst( get_linenum() ); - do_linenum_incr(); - } -#line 1393 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 12: -#line 140 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new VS10Inst( get_linenum(), VS10_NOP ); - } -#line 1401 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 13: -#line 144 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new VS10Inst( get_linenum(), VS10_COMMENT, (yyvsp[0].comment) ); - } -#line 1409 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 14: -#line 148 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new VS10Inst( get_linenum(), VS10_HEADER ); - } -#line 1417 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 15: -#line 154 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new VS10Inst( get_linenum(), (yyvsp[-3].ival), (yyvsp[-2].reg), (yyvsp[0].reg) ); - } -#line 1425 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 16: -#line 160 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - VS10Reg reg; - reg = (yyvsp[-2].reg); - reg.sign = -1; - reg.type = (yyvsp[-2].reg).type; - reg.index = (yyvsp[-2].reg).index; - for ( int i = 0; i < 4; i++ ) reg.mask[i] = (yyvsp[0].mask)[i]; - (yyval.reg) = reg; - } -#line 1439 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 17: -#line 170 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - VS10Reg reg; - reg = (yyvsp[-2].reg); - reg.sign = 1; - reg.type = (yyvsp[-2].reg).type; - reg.index = (yyvsp[-2].reg).index; - for ( int i = 0; i < 4; i++ ) reg.mask[i] = (yyvsp[0].mask)[i]; - (yyval.reg) = reg; - } -#line 1453 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 18: -#line 180 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - VS10Reg reg; - reg = (yyvsp[0].reg); - reg.sign = -1; - reg.type = (yyvsp[0].reg).type; - reg.index = (yyvsp[0].reg).index; - for ( int i = 0; i < 4; i++ ) reg.mask[i] = 0; - (yyval.reg) = reg; - } -#line 1467 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 19: -#line 190 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - VS10Reg reg; - reg = (yyvsp[0].reg); - reg.sign = 1; - reg.type = (yyvsp[0].reg).type; - reg.index = (yyvsp[0].reg).index; - for ( int i = 0; i < 4; i++ ) reg.mask[i] = 0; - (yyval.reg) = reg; - } -#line 1481 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 21: -#line 201 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - } -#line 1488 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 22: -#line 205 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - VS10Reg reg; - reg.type = TYPE_CONSTANT_MEM_REG; - reg.index = (yyvsp[-1].ival); - (yyval.reg) = reg; - } -#line 1499 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 23: -#line 212 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - // Register is valid only if - // type = TYPE_ADDRESS_REG - // index = 0 - // len(mask) = 1 - // mask[0] = 'x' - VS10Reg reg; - (yyval.reg).type = TYPE_CONSTANT_A0_REG; - if ( (yyvsp[-3].reg).type != TYPE_ADDRESS_REG ) - { - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } - else if ( (yyvsp[-3].reg).index != 0 ) - { - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } - else - { - int len = 0; - while ( len < 2 ) - { - if ( (yyvsp[-1].mask)[len] == 0 ) - break; - len++; - } - if ( len != 1 || (yyvsp[-1].mask)[0] != 'x' ) - { - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } - - reg.type = TYPE_CONSTANT_A0_REG; - (yyval.reg) = reg; - } - } -#line 1538 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 24: -#line 247 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - // Register is valid only if - // type = TYPE_ADDRESS_REG - // index = 0 - // len(mask) = 1 - // mask[0] = 'x' - VS10Reg reg; - (yyval.reg).type = TYPE_CONSTANT_A0_OFFSET_REG; - if ( (yyvsp[-5].reg).type != TYPE_ADDRESS_REG ) - { - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } - else if ( (yyvsp[-5].reg).index != 0 ) - { - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } - else - { - int len = 0; - while ( len < 2 ) - { - if ( (yyvsp[-3].mask)[len] == 0 ) - break; - len++; - } - if ( len != 1 || (yyvsp[-3].mask)[0] != 'x' ) - { - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } - - reg.type = TYPE_CONSTANT_A0_OFFSET_REG; - reg.index = (yyvsp[-1].ival); - (yyval.reg) = reg; - } - } -#line 1578 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 25: -#line 283 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.reg).type = TYPE_CONSTANT_A0_REG; - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } -#line 1587 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 26: -#line 288 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.reg).type = TYPE_CONSTANT_A0_REG; - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } -#line 1596 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 27: -#line 293 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.reg).type = TYPE_CONSTANT_A0_REG; - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } -#line 1605 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 28: -#line 298 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.reg).type = TYPE_CONSTANT_A0_REG; - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } -#line 1614 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 29: -#line 303 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.reg).type = TYPE_CONSTANT_A0_REG; - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } -#line 1623 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 30: -#line 308 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.reg).type = TYPE_CONSTANT_A0_REG; - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } -#line 1632 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 31: -#line 315 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new VS10Inst( get_linenum(), (yyvsp[-3].ival), (yyvsp[-2].reg), (yyvsp[0].reg) ); - } -#line 1640 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 32: -#line 321 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new VS10Inst( get_linenum(), (yyvsp[-3].ival), (yyvsp[-2].reg), (yyvsp[0].reg) ); - } -#line 1648 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 33: -#line 327 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new VS10Inst( get_linenum(), (yyvsp[-5].ival), (yyvsp[-4].reg), (yyvsp[-2].reg), (yyvsp[0].reg) ); - } -#line 1656 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 34: -#line 334 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.inst) = new VS10Inst( get_linenum(), (yyvsp[-7].ival), (yyvsp[-6].reg), (yyvsp[-4].reg), (yyvsp[-2].reg), (yyvsp[0].reg) ); - } -#line 1664 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 35: -#line 340 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_MOV; - } -#line 1672 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 36: -#line 344 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_LIT; - } -#line 1680 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 37: -#line 350 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_RCP; - } -#line 1688 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 38: -#line 354 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_RSQ; - } -#line 1696 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 39: -#line 358 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_EXP; - } -#line 1704 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 40: -#line 362 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_EXPP; - } -#line 1712 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 41: -#line 366 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_LOG; - } -#line 1720 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 42: -#line 370 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_LOGP; - } -#line 1728 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 43: -#line 376 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_FRC; - } -#line 1736 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 44: -#line 382 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_MUL; - } -#line 1744 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 45: -#line 386 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_ADD; - } -#line 1752 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 46: -#line 390 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_DP3; - } -#line 1760 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 47: -#line 394 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_DP4; - } -#line 1768 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 48: -#line 398 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_DST; - } -#line 1776 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 49: -#line 402 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_MIN; - } -#line 1784 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 50: -#line 406 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_MAX; - } -#line 1792 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 51: -#line 410 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_SLT; - } -#line 1800 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 52: -#line 414 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_SGE; - } -#line 1808 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 53: -#line 418 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_M3X2; - } -#line 1816 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 54: -#line 422 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_M3X3; - } -#line 1824 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 55: -#line 426 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_M3X4; - } -#line 1832 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 56: -#line 430 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_M4X3; - } -#line 1840 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 57: -#line 434 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_M4X4; - } -#line 1848 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 58: -#line 438 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_SUB; - } -#line 1856 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - case 59: -#line 444 "vs1.0_grammar.y" /* yacc.c:1646 */ - { - (yyval.ival) = VS10_MAD; - } -#line 1864 "_vs1.0_parser.c" /* yacc.c:1646 */ - break; - - -#line 1868 "_vs1.0_parser.c" /* yacc.c:1646 */ - default: break; - } - /* User semantic actions sometimes alter yychar, and that requires - that yytoken be updated with the new translation. We take the - approach of translating immediately before every use of yytoken. - One alternative is translating here after every semantic action, - but that translation would be missed if the semantic action invokes - YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or - if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an - incorrect destructor might then be invoked immediately. In the - case of YYERROR or YYBACKUP, subsequent parser actions might lead - to an incorrect destructor call or verbose syntax error message - before the lookahead is translated. */ - YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); - - YYPOPSTACK (yylen); - yylen = 0; - YY_STACK_PRINT (yyss, yyssp); - - *++yyvsp = yyval; - - /* Now 'shift' the result of the reduction. Determine what state - that goes to, based on the state we popped back to and the rule - number reduced by. */ - - yyn = yyr1[yyn]; - - yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; - if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) - yystate = yytable[yystate]; - else - yystate = yydefgoto[yyn - YYNTOKENS]; - - goto yynewstate; - - -/*--------------------------------------. -| yyerrlab -- here on detecting error. | -`--------------------------------------*/ -yyerrlab: - /* Make sure we have latest lookahead translation. See comments at - user semantic actions for why this is necessary. */ - yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); - - /* If not already recovering from an error, report this error. */ - if (!yyerrstatus) - { - ++yynerrs; -#if ! YYERROR_VERBOSE - yyerror (YY_("syntax error")); -#else -# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ - yyssp, yytoken) - { - char const *yymsgp = YY_("syntax error"); - int yysyntax_error_status; - yysyntax_error_status = YYSYNTAX_ERROR; - if (yysyntax_error_status == 0) - yymsgp = yymsg; - else if (yysyntax_error_status == 1) - { - if (yymsg != yymsgbuf) - YYSTACK_FREE (yymsg); - yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); - if (!yymsg) - { - yymsg = yymsgbuf; - yymsg_alloc = sizeof yymsgbuf; - yysyntax_error_status = 2; - } - else - { - yysyntax_error_status = YYSYNTAX_ERROR; - yymsgp = yymsg; - } - } - yyerror (yymsgp); - if (yysyntax_error_status == 2) - goto yyexhaustedlab; - } -# undef YYSYNTAX_ERROR -#endif - } - - - - if (yyerrstatus == 3) - { - /* If just tried and failed to reuse lookahead token after an - error, discard it. */ - - if (yychar <= YYEOF) - { - /* Return failure if at end of input. */ - if (yychar == YYEOF) - YYABORT; - } - else - { - yydestruct ("Error: discarding", - yytoken, &yylval); - yychar = YYEMPTY; - } - } - - /* Else will try to reuse lookahead token after shifting the error - token. */ - goto yyerrlab1; - - -/*---------------------------------------------------. -| yyerrorlab -- error raised explicitly by YYERROR. | -`---------------------------------------------------*/ -yyerrorlab: - - /* Pacify compilers like GCC when the user code never invokes - YYERROR and the label yyerrorlab therefore never appears in user - code. */ - if (/*CONSTCOND*/ 0) - goto yyerrorlab; - - /* Do not reclaim the symbols of the rule whose action triggered - this YYERROR. */ - YYPOPSTACK (yylen); - yylen = 0; - YY_STACK_PRINT (yyss, yyssp); - yystate = *yyssp; - goto yyerrlab1; - - -/*-------------------------------------------------------------. -| yyerrlab1 -- common code for both syntax error and YYERROR. | -`-------------------------------------------------------------*/ -yyerrlab1: - yyerrstatus = 3; /* Each real token shifted decrements this. */ - - for (;;) - { - yyn = yypact[yystate]; - if (!yypact_value_is_default (yyn)) - { - yyn += YYTERROR; - if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) - { - yyn = yytable[yyn]; - if (0 < yyn) - break; - } - } - - /* Pop the current state because it cannot handle the error token. */ - if (yyssp == yyss) - YYABORT; - - - yydestruct ("Error: popping", - yystos[yystate], yyvsp); - YYPOPSTACK (1); - yystate = *yyssp; - YY_STACK_PRINT (yyss, yyssp); - } - - YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN - *++yyvsp = yylval; - YY_IGNORE_MAYBE_UNINITIALIZED_END - - - /* Shift the error token. */ - YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); - - yystate = yyn; - goto yynewstate; - - -/*-------------------------------------. -| yyacceptlab -- YYACCEPT comes here. | -`-------------------------------------*/ -yyacceptlab: - yyresult = 0; - goto yyreturn; - -/*-----------------------------------. -| yyabortlab -- YYABORT comes here. | -`-----------------------------------*/ -yyabortlab: - yyresult = 1; - goto yyreturn; - -#if !defined yyoverflow || YYERROR_VERBOSE -/*-------------------------------------------------. -| yyexhaustedlab -- memory exhaustion comes here. | -`-------------------------------------------------*/ -yyexhaustedlab: - yyerror (YY_("memory exhausted")); - yyresult = 2; - /* Fall through. */ -#endif - -yyreturn: - if (yychar != YYEMPTY) - { - /* Make sure we have latest lookahead translation. See comments at - user semantic actions for why this is necessary. */ - yytoken = YYTRANSLATE (yychar); - yydestruct ("Cleanup: discarding lookahead", - yytoken, &yylval); - } - /* Do not reclaim the symbols of the rule whose action triggered - this YYABORT or YYACCEPT. */ - YYPOPSTACK (yylen); - YY_STACK_PRINT (yyss, yyssp); - while (yyssp != yyss) - { - yydestruct ("Cleanup: popping", - yystos[*yyssp], yyvsp); - YYPOPSTACK (1); - } -#ifndef yyoverflow - if (yyss != yyssa) - YYSTACK_FREE (yyss); -#endif -#if YYERROR_VERBOSE - if (yymsg != yymsgbuf) - YYSTACK_FREE (yymsg); -#endif - return yyresult; -} -#line 450 "vs1.0_grammar.y" /* yacc.c:1906 */ - -void yyerror(const char* s) -{ - LexError( "Syntax Error.\n" ); - //errors.set(s); - //errors.set("unrecognized token"); -} diff --git a/RenderSystems/GL/src/nvparse/_vs1.0_parser.h b/RenderSystems/GL/src/nvparse/_vs1.0_parser.h deleted file mode 100644 index 126f19b4b4a..00000000000 --- a/RenderSystems/GL/src/nvparse/_vs1.0_parser.h +++ /dev/null @@ -1,111 +0,0 @@ -/* A Bison parser, made by GNU Bison 3.0.2. */ - -/* Bison interface for Yacc-like parsers in C - - Copyright (C) 1984, 1989-1990, 2000-2013 Free Software Foundation, Inc. - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . */ - -/* As a special exception, you may create a larger work that contains - part or all of the Bison parser skeleton and distribute that work - under terms of your choice, so long as that work isn't itself a - parser generator using the skeleton or a modified version thereof - as a parser skeleton. Alternatively, if you modify or redistribute - the parser skeleton itself, you may (at your option) remove this - special exception, which will cause the skeleton and the resulting - Bison output files to be licensed under the GNU General Public - License without this special exception. - - This special exception was added by the Free Software Foundation in - version 2.2 of Bison. */ - -#ifndef YY_VS10_VS1_0_PARSER_H_INCLUDED -# define YY_VS10_VS1_0_PARSER_H_INCLUDED -/* Debug traces. */ -#ifndef YYDEBUG -# define YYDEBUG 0 -#endif -#if YYDEBUG -extern int vs10_debug; -#endif - -/* Token type. */ -#ifndef YYTOKENTYPE -# define YYTOKENTYPE - enum yytokentype - { - VERTEX_SHADER = 258, - ADD_INSTR = 259, - DP3_INSTR = 260, - DP4_INSTR = 261, - DST_INSTR = 262, - EXP_INSTR = 263, - EXPP_INSTR = 264, - FRC_INSTR = 265, - LIT_INSTR = 266, - LOG_INSTR = 267, - LOGP_INSTR = 268, - M3X2_INSTR = 269, - M3X3_INSTR = 270, - M3X4_INSTR = 271, - M4X3_INSTR = 272, - M4X4_INSTR = 273, - MAD_INSTR = 274, - MAX_INSTR = 275, - MIN_INSTR = 276, - MOV_INSTR = 277, - MUL_INSTR = 278, - NOP_INSTR = 279, - RCP_INSTR = 280, - RSQ_INSTR = 281, - SGE_INSTR = 282, - SLT_INSTR = 283, - SUB_INSTR = 284, - ILLEGAL = 285, - UNKNOWN_STRING = 286, - INTVAL = 287, - REGISTER = 288, - XYZW_MODIFIER = 289, - COMMENT = 290 - }; -#endif - -/* Value type. */ -#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED -typedef union YYSTYPE YYSTYPE; -union YYSTYPE -{ -#line 27 "vs1.0_grammar.y" /* yacc.c:1909 */ - - int ival; - unsigned int lval; - float fval; - char mask[4]; - char *comment; - VS10Reg reg; - VS10InstPtr inst; - VS10InstListPtr instList; - -#line 101 "_vs1.0_parser.h" /* yacc.c:1909 */ -}; -# define YYSTYPE_IS_TRIVIAL 1 -# define YYSTYPE_IS_DECLARED 1 -#endif - - -extern YYSTYPE vs10_lval; - -int vs10_parse (void); - -#endif /* !YY_VS10_VS1_0_PARSER_H_INCLUDED */ diff --git a/RenderSystems/GL/src/nvparse/avp1.0_impl.cpp b/RenderSystems/GL/src/nvparse/avp1.0_impl.cpp deleted file mode 100644 index e809b3a604f..00000000000 --- a/RenderSystems/GL/src/nvparse/avp1.0_impl.cpp +++ /dev/null @@ -1,164 +0,0 @@ -#include "nvparse_errors.h" -#include "nvparse_externs.h" -#include -#include -#include - -using namespace std; - -namespace -{ - void LoadProgram( GLenum target, GLuint id, char *instring ); - GLint vpid; -} - - -bool is_avp10(const char * s) -{ - return ! strncmp(s, "!!ARBvp1.0", 10); -} - -bool avp10_init(char * s) -{ - static bool avpinit = false; - if (avpinit == false ) - { - /* - if(! glh_init_extensions("GL_ARB_vertex_program")) - { - errors.set("unable to initialize GL_ARB_vertex_program"); - return false; - } - else - { - */ - avpinit = true; - /* - } - */ - } - - errors.reset(); - line_number = 1; - myin = s; - - glGetProgramivARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_BINDING_ARB, &vpid); - - if ( vpid == 0 ) - { - char str[128]; - sprintf( str, "No vertex program id bound for nvparse() invocation. Bound id = %d\n", (int)vpid ); - errors.set( str ); - return false; - } - - return true; -} - -int avp10_parse() -{ - LoadProgram( GL_VERTEX_PROGRAM_ARB, vpid, myin ); - return 0; -} - -namespace -{ - //.----------------------------------------------------------------------------. - //| Function : LoadProgram | - //| Description: Load a program into GL, and report any errors encountered. | - //.----------------------------------------------------------------------------. - void LoadProgram( GLenum target, GLuint id, char *instring ) - { - GLint errPos; - GLenum errCode; - int len = strlen(instring); - - glBindProgramARB(target, id); - errCode = glGetError(); - - glProgramStringARB(target, - GL_PROGRAM_FORMAT_ASCII_ARB, - len, - instring); - - if ((errCode = glGetError()) != GL_NO_ERROR) - { - glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errPos); - if (errPos == -1) - return; - - int nlines = 1; - int nchar = 1; - int i; - for (i = 0; i < errPos; i++) - { - if (instring[i] == '\n') - { - nlines++; - nchar = 1; - } - else - { - nchar++; - } - } - int start = 0; - int end = 0; - int flag = ((instring[errPos]==';') | (instring[errPos-1]==';')) ? 1 : 0; - for (i = errPos; i >= 0; i--) - { - start = i; - if (flag && (start >= errPos-1)) - continue; - if (instring[i] == ';') - { - if (!flag) - { - start = i+1; - if (instring[start] == '\n') - start++; - } - break; - } - } - for (i = errPos; i < len; i++) - { - end = i; - if (instring[i] == ';' && end > start) - { - break; - } - } - if (errPos - start > 30) - { - start = errPos - 30; - } - if (end - errPos > 30) - { - end = errPos + 30; - } - - char substring[96]; - memset( substring, 0, 96 ); - strncpy( substring, &(instring[start]), end-start+1 ); - - char str[256]; - sprintf(str, "error at line %d character %d\n\"%s\"\n", nlines, nchar, substring); - int width = errPos-start; - - for (i = 0; i < width; i++) - { - strcat(str, " "); - } - - strcat(str, "|\n"); - for (i = 0; i < width; i++) - { - strcat(str, " "); - } - strcat(str, "^\n"); - - errors.set(str); - } - } -} diff --git a/RenderSystems/GL/src/nvparse/macro.h b/RenderSystems/GL/src/nvparse/macro.h deleted file mode 100644 index 2e0e359f3e8..00000000000 --- a/RenderSystems/GL/src/nvparse/macro.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifdef _WIN32 -#include -#else -#include -#endif -typedef struct MACROTEXT { - MACROTEXT *next; - MACROTEXT *prev; - char *macroText; -} MACROTEXT; - -typedef struct MACROENTRY -{ - MACROENTRY *next; - MACROENTRY *prev; - char *macroName; - MACROTEXT *firstMacroParms; - MACROTEXT *lastMacroParms; - MACROTEXT *firstMacroLines; - MACROTEXT *lastMacroLines; - unsigned int numParms; - char *fileName; - unsigned int lineNo; - unsigned int nLines; - bool bIsDefine; -} MACROENTRY; - -#define MAX_IFDEF_DEPTH 1024 -typedef struct IFDEFINFO -{ - bool lastbProcessingIFDEF; // save off for if we were processing #ifdef - bool lastbIFDEF; // wether ifdef was true or not - bool lastbCompareDefine; // wether we compare #ifdef or #ifndef - unsigned int lastIfDefStartLine; // where we started for this #ifdef -} IFDEFINFO; - - -typedef void (*MACROFUNCTIONPTR)(char *, unsigned int *, char **); - -typedef struct MACROFUNCTIONS { - const char *name; - MACROFUNCTIONPTR function; -} MACROFUNCTIONS; diff --git a/RenderSystems/GL/src/nvparse/nvparse.cpp b/RenderSystems/GL/src/nvparse/nvparse.cpp deleted file mode 100644 index 0f5812b0b98..00000000000 --- a/RenderSystems/GL/src/nvparse/nvparse.cpp +++ /dev/null @@ -1,210 +0,0 @@ -#ifdef _WIN32 -# define WIN32_LEAN_AND_MEAN -# if !defined(NOMINMAX) && defined(_MSC_VER) -# define NOMINMAX // required to stop windows.h messing up std::min -# endif -# include -#else -#include -#define strnicmp strncasecmp -#endif - -#include - -#include -#include -#include -#include - -#include "nvparse.h" -#include "nvparse_errors.h" - -//void yyinit(char*); -//int yyparse(void); - - -// RC1.0 -- register combiners 1.0 configuration -bool rc10_init(char *); -int rc10_parse(); -bool is_rc10(const char *); - -// TS1.0 -- texture shader 1.0 configuration -bool ts10_init(char *); -int ts10_parse(); -bool is_ts10(const char *); - -// ARBvp1.0 -- ARB vertex program -bool avp10_init(char *); -int avp10_parse(); -bool is_avp10(const char *); - -#if !defined(__APPLE__) -// VP1.0 -- vertex program -bool vp10_init(char *); -int vp10_parse(); -bool is_vp10(const char *); - -// VSP1.0 -- vertex state program -bool vsp10_init(char *); -int vsp10_parse(int vspid); -bool is_vsp10(const char *); - -// VCP1.0 -- vertex constant program -bool vcp10_init(char *); -int vcp10_parse(); -bool is_vcp10(const char *); - -// DX8 stuff - -// PS1.0 -- DX8 Pixel Shader 1.0 configuration -bool ps10_init(char *); -int ps10_parse(); -bool ps10_set_map(const std::vector& argv); -bool is_ps10(const char *); -const int* ps10_get_info(int* pcount); - -// VS1.0 -- DX8 Vertex Shader 1.0 -bool vs10_init(char *); -int vs10_parse(); -bool is_vs10(const char *); -void vs10_load_program(); -#endif - -nvparse_errors errors; -int line_number; -char * myin = 0; - -void nvparse(const char * input_string, int argc /* = 0 */,...) -{ - if (NULL == input_string) - { - errors.set("NULL string passed to nvparse"); - return; - } - - char * instring = strdup(input_string); - - // register combiners (1 and 2) - if(is_rc10(instring)) - { - if(rc10_init(instring)) - { - rc10_parse(); - } - } - - // texture shader - else if(is_ts10(instring)) - { - if(ts10_init(instring)) - { - ts10_parse(); - } - } - - // vertex program - else if(is_avp10(instring)) - { - if(avp10_init(instring)) - { - avp10_parse(); - } - } - -#if !defined(__APPLE__) - // vertex constant program - else if(is_vcp10(instring)) - { - if(vcp10_init(instring)) - { - vcp10_parse(); - } - } - - // vertex state program - else if(is_vsp10(instring)) - { - if(vsp10_init(instring)) - { - vsp10_parse(argc); - } - } - - // vertex program - else if(is_vp10(instring)) - { - if(vp10_init(instring)) - { - vp10_parse(); - } - } - - // DX8 vertex shader - else if ( is_vs10(instring) ) - { - if(vs10_init(instring)) - { - vs10_parse(); - vs10_load_program(); - } - - } - else if (is_ps10(instring)) - { - if(ps10_init(instring)) - { - va_list ap; - std::vector argv; - va_start(ap,argc); - for (int i=0;i - -#ifdef __cplusplus -extern "C" { -#endif - - - -void nvparse(const char * input_string, int argc = 0,...); -char** nvparse_get_errors(); -char** nvparse_print_errors(FILE *fp); -const int* nvparse_get_info(const char* input_string, int* pcount); -#ifdef __cplusplus -} -#endif - -#endif diff --git a/RenderSystems/GL/src/nvparse/nvparse_errors.cpp b/RenderSystems/GL/src/nvparse/nvparse_errors.cpp deleted file mode 100644 index 0f71957c5bf..00000000000 --- a/RenderSystems/GL/src/nvparse/nvparse_errors.cpp +++ /dev/null @@ -1,47 +0,0 @@ -#include -#include -#include - -#include "nvparse_errors.h" - - - -nvparse_errors::nvparse_errors() -{ - num_errors = 0; - reset(); -} - -nvparse_errors::~nvparse_errors() -{ - reset(); -} - - -void nvparse_errors::reset() -{ - for(int i=0; i < num_errors; i++) - free(elist[i]);//FIXME detail_nmap something is writing 0x2 to elist[1] blah! - for(int j=0; j <= NVPARSE_MAX_ERRORS; j++) - elist[j] = 0; - num_errors = 0; -} - -void nvparse_errors::set(const char * e) -{ - if(num_errors < NVPARSE_MAX_ERRORS) - elist[num_errors++] = strdup(e); -} - -void nvparse_errors::set(const char * e, int line_number) -{ - char buff[256]; - sprintf(buff, "error on line %d: %s", line_number, e); - if(num_errors < NVPARSE_MAX_ERRORS) - elist[num_errors++] = strdup(buff); -} - -char** nvparse_errors::get_errors() -{ - return elist; -} diff --git a/RenderSystems/GL/src/nvparse/nvparse_errors.h b/RenderSystems/GL/src/nvparse/nvparse_errors.h deleted file mode 100644 index 5426dac7936..00000000000 --- a/RenderSystems/GL/src/nvparse/nvparse_errors.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef _NVPARSE_ERRORS_H_ -#define _NVPARSE_ERRORS_H_ - -#ifdef _WIN32 - #pragma warning(disable:4786) // stupid symbol size limitation -#endif - -#define NVPARSE_MAX_ERRORS 32 -class nvparse_errors -{ -public: - nvparse_errors(); - ~nvparse_errors(); - - void reset(); - void set(const char * e); - void set(const char * e, int line_number); - char** get_errors(); - inline int get_num_errors() { return num_errors; } -private: - char* elist [NVPARSE_MAX_ERRORS+1]; - int num_errors; -}; - -#endif diff --git a/RenderSystems/GL/src/nvparse/nvparse_externs.h b/RenderSystems/GL/src/nvparse/nvparse_externs.h deleted file mode 100644 index 18f3040dea3..00000000000 --- a/RenderSystems/GL/src/nvparse/nvparse_externs.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef NVPARSE_EXTERNS_H -#define NVPARSE_EXTERNS_H - -extern nvparse_errors errors; -extern int line_number; -extern char * myin; - -#ifdef _WIN32 -#include -#endif -#include - -#endif diff --git a/RenderSystems/GL/src/nvparse/ps1.0__test_main.cpp b/RenderSystems/GL/src/nvparse/ps1.0__test_main.cpp deleted file mode 100644 index 152ba9a62cc..00000000000 --- a/RenderSystems/GL/src/nvparse/ps1.0__test_main.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/* - - This is a test app for the ps10 lexer/parser. - - Cass Everitt - 07-06-01 - -*/ -#include -#include -#include "nvparse_errors.h" - -#include - -#define GLH_EXT_SINGLE_FILE -#include - -using namespace std; - -bool ps10_init(char *); -int ps10_parse(void); - -nvparse_errors errors; -int line_number; -char * myin = 0; - -char * const * const nvparse_get_errors() -{ - return errors.get_errors(); -} - -char * const * const nvparse_print_errors(FILE * errfp) -{ - for (char * const * ep = nvparse_get_errors(); *ep; ep++) - { - const char * errstr = *ep; - fprintf(errfp, "%s\n", errstr); - } - return nvparse_get_errors(); -} - - -char * read_input_file(string filename) -{ - char buf[256]; - FILE * fp = fopen(filename.c_str(), "rb"); - if(! fp) - return 0; - string result; - while(fgets(buf, 255, fp) > 0) - { - result += buf; - } - fclose(fp); - char * r = new char[result.size()+1]; - strcpy(r, result.c_str()); - return r; -} - - -int main(int argc, char **argv) -{ -/* - char test_string[] = - "Ps.1.0 \n\n\n" - "def c0, 0.4, 1, 0, .2 ; diffuse \n" - "def c7, .3, .2, .1, 0 \n \n" - " \n" - "add r0, t0_bias, r1_bx2 \n" - "cnd r0, r0.a, t0, r1 \n" - "dp3 r0, t0, r1 \n" - "lrp r0, t0.a, t0, r1 \n" - "mad r0, t0.a, t0, r1 \n" - "mov r0.a, -r1.a \n" - "mul r0, t0, r1 \n" - "sub r0, t0, r1 \n" - ; -*/ -/* - char test_string[] = - "Ps.1.0 \n" - "def c0, 0.4, 1, 0, .2 \n" - "def c7, .3, .2, .1, 0 \n" - "add r0, t0_bias, r1_bx2 \n" - "cnd r0, r0.a, t0, r1 \n" - "dp3 r0, t0, r1 \n" - "lrp r0, t0.a, t0, r1 \n" - "mad r0, t0.a, t0, r1 \n" - "mov r0.a, -r1.a \n" - "mul r0, t0, r1 \n" - "sub r0, t0, r1 \n" - ; -*/ - char test_string[] = -"ps.1.1\n" -"tex t0\n" -"mul r1, t0, c0\n" -"mul r0, r1, v0\n" -"// End of program\n" - ; - - glutInit(&argc, argv); - glutInitDisplayMode(GLUT_DOUBLE|GLUT_DEPTH|GLUT_RGB); - glutCreateWindow("test window"); - - char * str; - if(argc == 2) - { - str = read_input_file(argv[1]); - } - else - { - str = test_string; - } - - line_number = 1; - - ps10_init(str); - - glNewList(GL_COMPILE_AND_EXECUTE, 1); - ps10_parse(); - glEndList(); - - char * err = (char *) gluErrorString(glGetError()); - - errors.set("spacer..."); - nvparse_print_errors(stderr); - - fprintf(stdout, "\n\nnvparse output: \n\n"); - fprintf(stdout, state_to_rc10() ); - - - return 0; -} diff --git a/RenderSystems/GL/src/nvparse/ps1.0_grammar.y b/RenderSystems/GL/src/nvparse/ps1.0_grammar.y deleted file mode 100644 index cce61206388..00000000000 --- a/RenderSystems/GL/src/nvparse/ps1.0_grammar.y +++ /dev/null @@ -1,314 +0,0 @@ -%start WholeEnchilada -%name-prefix "ps10_" -%{ - -/* - - This is a parser for the DX8 PS1.0 pixel shaders. I intend - to use it to set NV_texture_shader* and NV_register_combiners* - state in OpenGL, but the parse tree could be used for any - other purpose. - - Cass Everitt - 7-19-01 - -*/ - -void yyerror(const char* s); -int yylex ( void ); - -#ifdef _WIN32 -# include -#endif - -#include -#include - -#include "ps1.0_program.h" -#include "nvparse_errors.h" -#include "nvparse_externs.h" - -#include -#include - -using namespace std; -using namespace ps10; - -//#define DBG_MESG(msg, line) errors.set(msg, line) -#define DBG_MESG(msg, line) - - -%} -%union -{ - int ival; - float fval; - - string * sval; - constdef * cdef; - vector * consts; - vector * line; - list > * lines; -} - -%token HEADER NEWLINE -%token NUMBER -%token REG -%token DEF -%token ADDROP -%token BLENDOP - -%type Def -%type Defs -%type AddrOp BlendOp -%type AddrOps BlendOps -%type MaybePlus - - -%% - -WholeEnchilada : - - HEADER Newlines Defs AddrOps BlendOps - { - DBG_MESG("dbg: WholeEnchilada", line_number); - ps10::invoke($3, $4, $5); - } - | - - Newlines HEADER Newlines Defs AddrOps BlendOps - { - DBG_MESG("dbg: WholeEnchilada", line_number); - ps10::invoke($4, $5, $6); - } - | - - HEADER Newlines AddrOps BlendOps - { - DBG_MESG("dbg: WholeEnchilada", line_number); - ps10::invoke( 0, $3, $4); - } - | - - Newlines HEADER Newlines AddrOps BlendOps - { - DBG_MESG("dbg: WholeEnchilada", line_number); - ps10::invoke( 0, $4, $5); - } - | - - HEADER Newlines Defs BlendOps - { - DBG_MESG("dbg: WholeEnchilada", line_number); - ps10::invoke($3, 0, $4); - } - | - - Newlines HEADER Newlines Defs BlendOps - { - DBG_MESG("dbg: WholeEnchilada", line_number); - ps10::invoke($4, 0, $5); - } - | - - HEADER Newlines BlendOps - { - DBG_MESG("dbg: WholeEnchilada", line_number); - ps10::invoke( 0, 0, $3); - } - | - - Newlines HEADER Newlines BlendOps - { - DBG_MESG("dbg: WholeEnchilada", line_number); - ps10::invoke( 0, 0, $4); - } - ; - - -Defs : - - Def - { - $$ = new vector; - $$->push_back(* $1); - delete $1; - } - | - - Defs Def - { - $$ = $1; - $$->push_back(* $2); - delete $2; - } - ; - - - -Def : - - DEF REG ',' NUMBER ',' NUMBER ',' NUMBER ',' NUMBER Newlines - { - $$ = new constdef; - $$->reg = * $2; - $$->r = $4; - $$->g = $6; - $$->b = $8; - $$->a = $10; - delete $2; - } - ; - -AddrOps: - - AddrOp - { - $$ = new list >; - $$->push_back(* $1); - delete $1; - } - | - - AddrOps AddrOp - { - $$ = $1; - $$->push_back(* $2); - delete $2; - } - ; - - -AddrOp : - - ADDROP REG Newlines - { - $$ = new vector; - $$->push_back(* $1); - $$->push_back(* $2); - delete $1; - delete $2; - } - | - - ADDROP REG ',' REG Newlines - { - $$ = new vector; - $$->push_back(* $1); - $$->push_back(* $2); - $$->push_back(* $4); - delete $1; - delete $2; - delete $4; - } - | - - ADDROP REG ',' REG ',' REG Newlines - { - $$ = new vector; - $$->push_back(* $1); - $$->push_back(* $2); - $$->push_back(* $4); - $$->push_back(* $6); - delete $1; - delete $2; - delete $4; - delete $6; - } - ; - - -BlendOps: - - BlendOp - { - $$ = new list >; - $$->push_back(* $1); - delete $1; - } - | - - BlendOps BlendOp - { - $$ = $1; - $$->push_back(* $2); - delete $2; - } - ; - - -BlendOp : - - - MaybePlus BLENDOP REG ',' REG Newlines - { - $$ = new vector; - if ( $1 ) - $$->push_back("+"); - $$->push_back(* $2); - $$->push_back(* $3); - $$->push_back(* $5); - delete $2; - delete $3; - delete $5; - } - | - - MaybePlus BLENDOP REG ',' REG ',' REG Newlines - { - $$ = new vector; - if ( $1 ) - $$->push_back("+"); - $$->push_back(* $2); - $$->push_back(* $3); - $$->push_back(* $5); - $$->push_back(* $7); - delete $2; - delete $3; - delete $5; - delete $7; - } - | - - MaybePlus BLENDOP REG ',' REG ',' REG ',' REG Newlines - { - $$ = new vector; - if ( $1 ) - $$->push_back("+"); - $$->push_back(* $2); - $$->push_back(* $3); - $$->push_back(* $5); - $$->push_back(* $7); - $$->push_back(* $9); - delete $2; - delete $3; - delete $5; - delete $7; - delete $9; - } - ; - -MaybePlus : - /* empty */ - { $$=0; } - | - '+' - { $$=1; } - ; - -Newlines : - - NEWLINE - {} - | - - Newlines NEWLINE - {} - ; - -%% - -void yyerror(const char* s) -{ - errors.set("parser: syntax error", line_number); -} diff --git a/RenderSystems/GL/src/nvparse/ps1.0_program.cpp b/RenderSystems/GL/src/nvparse/ps1.0_program.cpp deleted file mode 100644 index 712cdd90ea2..00000000000 --- a/RenderSystems/GL/src/nvparse/ps1.0_program.cpp +++ /dev/null @@ -1,1024 +0,0 @@ -#include "ps1.0_program.h" - -#include "nvparse_errors.h" -#include "nvparse_externs.h" - -#include -#include -#include -#include -#include - - -using namespace std; -using namespace ps10; -struct ltstr -{ - bool operator()(const char* s1, const char* s2) const - { - return strcmp(s1, s2) < 0; - } -}; - -#define DBG_MESG(msg, line) errors.set(msg, line) -//#define DBG_MESG(msg, line) -namespace ps10 -{ - std::map > constToStageAndConstMap; - std::vector constToStageArray; - std::map stageToConstMap; // to keep track of which constants have been used up for this stage. - // r-value of 0 means none, r-value of 1 means c0 used, and r-value of 2 means both used. - //std::map constToStageMap; - std::map stageToTargetMap; - std::set alphaBlueRegisters; // Keeps track of whether the result of a register - // was a dp3, if a register is in this set, it means that if it is used a source for the alpha - // component the blue component should be used, and not the alpha component. - void SetFinalCombinerStage(); -} - -void RemoveFromAlphaBlue(std::string s) -{ - std::set::iterator iter = - ps10::alphaBlueRegisters.find(s.c_str()); - if (iter != alphaBlueRegisters.end()) - alphaBlueRegisters.erase(iter); -} - -/* -void AddToMap(string s, int stage) -{ - const char* cstr = s.c_str(); - if (cstr[0] == 'c') - { - int constNum = atoi(&cstr[1]); - if (constNum < 0 || constNum > 7) - return; - constToStageMap[constNum] = stage; - } -} -*/ - -bool AddToMap(string s, int stage, GLenum& constVal) -{ - const char* cstr = s.c_str(); - if (cstr[0] == 'c') - { - int constNum = atoi(&cstr[1]); - std::map::iterator iter = stageToConstMap.find(stage); - if (iter == stageToConstMap.end()) - { - // no constants used for this stage. - std::pair temp; - temp.first = stage; - temp.second = 0; - constToStageAndConstMap[constNum] = temp; - stageToConstMap[stage] = 0; - constVal = 0; - constToStageArray.push_back(constNum); - constToStageArray.push_back(stage); - constToStageArray.push_back(constVal); - } - else - { - int constUsed = (*iter).second; - if (constUsed >= 1) - return false; - else // const0 has been used, so use const1 for this stage. - { - std::pair temp; - temp.first = stage; - temp.second = 1; - constToStageAndConstMap[constNum] = temp; - stageToConstMap[stage] = 1; - constVal = 1; - constToStageArray.push_back(constNum); - constToStageArray.push_back(stage); - constToStageArray.push_back(constVal); - } - - } - } - constVal += GL_CONSTANT_COLOR0_NV; - return true; -} - -bool IsLegalTarget(int target) -{ - if (target == GL_TEXTURE_CUBE_MAP_ARB) - return true; - if (target == GL_TEXTURE_3D) - return true; -#if defined(GL_EXT_texture_rectangle) - if (target == GL_TEXTURE_RECTANGLE_EXT) - return true; -#elif defined(GL_NV_texture_rectangle) - if (target == GL_TEXTURE_RECTANGLE_NV) - return true; -#endif - if (target == GL_TEXTURE_2D) - return true; - if (target == GL_TEXTURE_1D) - return true; - return false; -} - -bool ps10_set_map(const std::vector& argv) -{ - if (argv.size() % 2 != 0) - { - errors.set("Odd number of arguments for texture target map."); - return false; - } - for (unsigned int i=0;i::iterator iter = stageToTargetMap.find(stage); - if (iter != stageToTargetMap.end()) - return (*iter).second; - // If no mapping set, use the current state. This will not work correctly, in general, - // if nvparse was invoked within a display list. - if(glIsEnabled(GL_TEXTURE_CUBE_MAP_ARB)) - return GL_TEXTURE_CUBE_MAP_ARB; - if(glIsEnabled(GL_TEXTURE_3D)) - return GL_TEXTURE_3D; -#if defined(GL_EXT_texture_rectangle) - if(glIsEnabled(GL_TEXTURE_RECTANGLE_EXT)) - return GL_TEXTURE_RECTANGLE_EXT; -#elif defined(GL_NV_texture_rectangle) - if(glIsEnabled(GL_TEXTURE_RECTANGLE_NV)) - return GL_TEXTURE_RECTANGLE_NV; -#endif - if(glIsEnabled(GL_TEXTURE_2D)) - return GL_TEXTURE_2D; - if(glIsEnabled(GL_TEXTURE_1D)) - return GL_TEXTURE_1D; - - //otherwise make the op none... - return GL_NONE; - } - - - - struct set_texture_shaders - { - set_texture_shaders(vector * cdef) - { - GLint activeTex = 0; - glGetIntegerv(GL_ACTIVE_TEXTURE, &activeTex); - for(stage = 0; stage < 4; stage++) - { - glActiveTextureARB(GL_TEXTURE0_ARB + stage); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_NONE); - } - stage = 0; - c = cdef; - - glActiveTextureARB(activeTex); - } - - void operator() (vector & instr) - { - if(stage > 3) - return; - GLint activeTex = 0; - glGetIntegerv(GL_ACTIVE_TEXTURE, &activeTex); - - glActiveTextureARB(GL_TEXTURE0_ARB + stage); - - string op = instr[0]; - if(op == "tex") - { - if(instr.size() != 2) - fprintf(stderr,"incorrect \"tex\" instruction, stage %d...\n", stage); - reg2stage[instr[1]] = stage; - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, get_tex_target(stage)); - } - else if(op == "texbem") - { - if(instr.size() != 3 || stage == 0) - fprintf(stderr,"incorrect \"texbem\" instruction, stage %d...\n", stage); - reg2stage[instr[1]] = stage; - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_OFFSET_TEXTURE_2D_NV); - if(reg2stage.count(instr[2]) == 0) - fprintf(stderr,"incorrect \"texbem\" instruction, stage %d...\n", stage); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + reg2stage[instr[2]]); - } - else if(op == "texbeml") - { - if(instr.size() != 3 || stage == 0) - fprintf(stderr,"incorrect \"texbeml\" instruction, stage %d...\n", stage); - reg2stage[instr[1]] = stage; - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_OFFSET_TEXTURE_SCALE_NV); - if(reg2stage.count(instr[2]) == 0) - fprintf(stderr,"incorrect \"texbeml\" instruction, stage %d...\n", stage); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + reg2stage[instr[2]]); - } - else if(op == "texcoord") - { - if(instr.size() != 2) - fprintf(stderr,"incorrect \"texcoord\" instruction, stage %d...\n", stage); - reg2stage[instr[1]] = stage; - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_PASS_THROUGH_NV); - } - else if(op == "texkill") - { - if(instr.size() != 2) - fprintf(stderr,"incorrect \"texkill\" instruction, stage %d...\n", stage); - reg2stage[instr[1]] = stage; - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_CULL_FRAGMENT_NV); - } - else if(op == "texm3x2pad") - { - if(instr.size() != 3 || stage == 0) - fprintf(stderr,"incorrect \"texm3x2pad\" instruction, stage %d...\n", stage); - reg2stage[instr[1]] = stage; - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_NV); - if(instr[2].find("_bx2") != string::npos) - { - instr[2].erase(instr[2].begin() + instr[2].find("_bx2"), instr[2].end()); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - } - if(reg2stage.count(instr[2]) == 0) - fprintf(stderr,"incorrect \"texm3x2pad\" instruction, stage %d...\n", stage); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + reg2stage[instr[2]]); - } - else if(op == "texm3x2tex") - { - if(instr.size() != 3 || stage == 0) - fprintf(stderr,"incorrect \"texm3x2tex\" instruction, stage %d...\n", stage); - reg2stage[instr[1]] = stage; - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_TEXTURE_2D_NV); - if(instr[2].find("_bx2") != string::npos) - { - instr[2].erase(instr[2].begin() + instr[2].find("_bx2"), instr[2].end()); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - } - if(reg2stage.count(instr[2]) == 0) - fprintf(stderr,"incorrect \"texm3x2tex\" instruction, stage %d...\n", stage); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + reg2stage[instr[2]]); - } - else if(op == "texm3x3pad") - { - if(instr.size() != 3 || stage == 0) - fprintf(stderr,"incorrect \"texm3x3pad\" instruction, stage %d...\n", stage); - reg2stage[instr[1]] = stage; - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_NV); - if(instr[2].find("_bx2") != string::npos) - { - instr[2].erase(instr[2].begin() + instr[2].find("_bx2"), instr[2].end()); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - } - if(reg2stage.count(instr[2]) == 0) - fprintf(stderr,"incorrect \"texm3x3pad\" instruction, stage %d...\n", stage); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + reg2stage[instr[2]]); - } - else if(op == "texm3x3tex") - { - if(instr.size() != 3 || stage == 0) - fprintf(stderr,"incorrect \"texm3x3tex\" instruction, stage %d...\n", stage); - reg2stage[instr[1]] = stage; - - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_TEXTURE_CUBE_MAP_NV); - - if(instr[2].find("_bx2") != string::npos) - { - instr[2].erase(instr[2].begin() + instr[2].find("_bx2"), instr[2].end()); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - } - if(reg2stage.count(instr[2]) == 0) - fprintf(stderr,"incorrect \"texm3x3tex\" instruction, stage %d...\n", stage); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + reg2stage[instr[2]]); - } - else if(op == "texm3x3spec") - { - if(instr.size() != 4 || stage == 0) - fprintf(stderr,"incorrect \"texm3x3spec\" instruction, stage %d...\n", stage); - reg2stage[instr[1]] = stage; - - if(! c) - return; - constdef cd; - for(int i = c->size()-1; i >= 0; i--) - { - cd = (*c)[i]; - if(cd.reg == "c0") - break; - } - - if(cd.reg != "c0" || instr[3] != "c0") - return; - GLfloat eye[4]; - eye[0] = cd.r; - eye[1] = cd.g; - eye[2] = cd.b; - eye[3] = cd.a; - - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_CONST_EYE_REFLECT_CUBE_MAP_NV); - glTexEnvfv(GL_TEXTURE_SHADER_NV, GL_CONST_EYE_NV, eye); - - if(instr[2].find("_bx2") != string::npos) - { - instr[2].erase(instr[2].begin() + instr[2].find("_bx2"), instr[2].end()); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - } - if(reg2stage.count(instr[2]) == 0) - fprintf(stderr,"incorrect \"texm3x3tex\" instruction, stage %d...\n", stage); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + reg2stage[instr[2]]); - } - else if(op == "texm3x3vspec") - { - if(instr.size() != 3 || stage == 0) - fprintf(stderr,"incorrect \"texm3x3vspec\" instruction, stage %d...\n", stage); - reg2stage[instr[1]] = stage; - - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_REFLECT_CUBE_MAP_NV); - - if(instr[2].find("_bx2") != string::npos) - { - instr[2].erase(instr[2].begin() + instr[2].find("_bx2"), instr[2].end()); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - } - if(reg2stage.count(instr[2]) == 0) - fprintf(stderr,"incorrect \"texm3x3tex\" instruction, stage %d...\n", stage); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + reg2stage[instr[2]]); - } - else if(op == "texreg2ar") - { - if(instr.size() != 3 || stage == 0) - fprintf(stderr,"incorrect \"texreg2ar\" instruction, stage %d...\n", stage); - reg2stage[instr[1]] = stage; - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DEPENDENT_AR_TEXTURE_2D_NV); - if(reg2stage.count(instr[2]) == 0) - fprintf(stderr,"incorrect \"texreg2ar\" instruction, stage %d...\n", stage); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + reg2stage[instr[2]]); - } - else if(op == "texreg2gb") - { - if(instr.size() != 3 || stage == 0) - fprintf(stderr,"incorrect \"texreg2gb\" instruction, stage %d...\n", stage); - reg2stage[instr[1]] = stage; - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DEPENDENT_GB_TEXTURE_2D_NV); - if(reg2stage.count(instr[2]) == 0) - fprintf(stderr,"incorrect \"texreg2gb\" instruction, stage %d...\n", stage); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + reg2stage[instr[2]]); - } - stage++; - glActiveTextureARB(activeTex); - } - - map reg2stage; - int stage; - vector * c; - }; - - GLenum reg_enum(string s, int stage) - { - /*if(s == "c0") - return GL_CONSTANT_COLOR0_NV; - else if(s == "c1") - return GL_CONSTANT_COLOR1_NV; - else if(s == "c2") - return GL_CONSTANT_COLOR0_NV; - else if(s == "c3") - return GL_CONSTANT_COLOR1_NV; - else if(s == "c4") - return GL_CONSTANT_COLOR0_NV; - else if(s == "c5") - return GL_CONSTANT_COLOR1_NV; - else if(s == "c6") - return GL_CONSTANT_COLOR0_NV; - else if(s == "c7") - return GL_CONSTANT_COLOR1_NV; - */ - if (s == "c0" || s == "c1" || s == "c2" || s == "c3" || - s == "c4" || s == "c5" || s == "c6" || s == "c7") - { - GLenum result; - if (!AddToMap(s,stage,result)) - errors.set("Illegal constant usage.",line_number); - // This is a pain, since the caller is a void and no check is made for errors. Sigh. - return result; - } - else if(s == "t0") - return GL_TEXTURE0_ARB; - else if(s == "t1") - return GL_TEXTURE1_ARB; - else if(s == "t2") - return GL_TEXTURE2_ARB; - else if(s == "t3") - return GL_TEXTURE3_ARB; - else if(s == "v0") - return GL_PRIMARY_COLOR_NV; - else if(s == "v1") - return GL_SECONDARY_COLOR_NV; - else if(s == "r0") - return GL_SPARE0_NV; - else if(s == "r1") - return GL_SPARE1_NV; - else // ?? - return GL_DISCARD_NV; - } - - struct src - { - src(string s, int stage, string *regname=NULL) - { - init(s, stage, regname); - } - - - void init(string s, int stage, string *regname=NULL) - { - arg = s; - comp = GL_RGB; - alphaComp = GL_ALPHA; - map = GL_SIGNED_IDENTITY_NV; - - string::size_type offset; - if( - (offset = s.find(".a")) != string::npos || - (offset = s.find(".w")) != string::npos - ) - { - comp = GL_ALPHA; - s.erase(offset, offset+2); - } - else if ((offset = s.find(".b")) != string::npos || - (offset = s.find(".z")) != string::npos) - { - alphaComp = GL_BLUE; - s.erase(offset,offset+2); - } - - bool negate = false; - - if(s[0] == '1') - { - s.erase(0, 1); - while(s[0] == ' ') - s.erase(0,1); - if(s[0] == '-') - s.erase(0,1); - while(s[0] == ' ') - s.erase(0,1); - map = GL_UNSIGNED_INVERT_NV; - } - else if(s[0] == '-') - { - s.erase(0, 1); - while(s[0] == ' ') - s.erase(0,1); - negate = true; - map = GL_UNSIGNED_INVERT_NV; - } - - bool half_bias = false; - bool expand = false; - if(s.find("_bias") != string::npos) - { - s.erase(s.find("_bias"), 5); - half_bias = true; - } - else if(s.find("_bx2") != string::npos) - { - s.erase(s.find("_bx2"), 4); - expand = true; - } - - if(expand) - { - if(negate) - map = GL_EXPAND_NEGATE_NV; - else - map = GL_EXPAND_NORMAL_NV; - } - else if(half_bias) - { - if(negate) - map = GL_HALF_BIAS_NEGATE_NV; - else - map = GL_HALF_BIAS_NORMAL_NV; - } - reg = reg_enum(s,stage); - - if (regname != NULL) - *regname = s; // return the bare register name - - - //alphaComp = GL_ALPHA; - std::set::iterator iter = - ps10::alphaBlueRegisters.find(s.c_str()); - if (iter != ps10::alphaBlueRegisters.end()) - alphaComp = GL_BLUE; - - } - - string arg; - GLenum reg; - GLenum map; - GLenum comp; - GLenum alphaComp; - }; - - - struct set_register_combiners - { - set_register_combiners() - { - // combiner = 0; - combiner = -1; - } - - void operator() (vector & instr) - { - string op; - GLenum scale = GL_NONE; - bool paired_instr = false; - int instr_base = 0; - if (instr[0]=="+") { - paired_instr = true; - instr_base = 1; - } - op = instr[instr_base]; - string::size_type offset; - if((offset = op.find("_x2")) != string::npos) - { - scale = GL_SCALE_BY_TWO_NV; - op.erase(op.begin()+offset, op.begin()+offset+3); - } - else if((offset = op.find("_x4")) != string::npos) - { - scale = GL_SCALE_BY_FOUR_NV; - op.erase(op.begin()+offset, op.begin()+offset+3); - } - else if((offset = op.find("_d2")) != string::npos) - { - scale = GL_SCALE_BY_ONE_HALF_NV; - op.erase(op.begin()+offset, op.begin()+offset+3); - } - - if((offset = op.find("_sat")) != string::npos) - { - op.erase(op.begin()+offset, op.begin()+offset+4); - } - - string dst = instr[1+instr_base]; - int mask = GL_RGBA; - if( - (offset = dst.find(".rgba")) != string::npos || - (offset = dst.find(".xyzw")) != string::npos - ) - { - dst.erase(offset, offset + 5); - } - else if( - (offset = dst.find(".rgb")) != string::npos || - (offset = dst.find(".xyz")) != string::npos - ) - { - dst.erase(offset, offset + 4); - mask = GL_RGB; - } - else if( - (offset = dst.find(".a")) != string::npos || - (offset = dst.find(".w")) != string::npos - ) - { - dst.erase(offset, offset + 2); - mask = GL_ALPHA; - } - - if (!paired_instr) - combiner++; - - GLenum dreg = reg_enum(dst,combiner); - GLenum C = GL_COMBINER0_NV + combiner; - - bool isAlphaBlue = false; // To keep track of whether the dst register's alpha was its blue value. - - if(op == "add" || op == "sub") - { - src a(instr[2+instr_base],combiner); - src b(instr[3+instr_base],combiner); - - if(mask == GL_RGBA || mask == GL_RGB) - { - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_A_NV, a.reg, a.map, a.comp); - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_B_NV, GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_RGB); - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_C_NV, b.reg, b.map, b.comp); - if(op == "add") - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_D_NV, GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_RGB); - else - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_D_NV, GL_ZERO, GL_EXPAND_NORMAL_NV, GL_RGB); - glCombinerOutputNV(C, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, dreg, scale, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - else if (!paired_instr) - { - glCombinerOutputNV(C, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - - if(mask == GL_RGBA || mask == GL_ALPHA) - { - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_A_NV, a.reg, a.map, a.alphaComp); - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_B_NV, GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_ALPHA); - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_C_NV, b.reg, b.map, b.alphaComp); - if(op == "add") - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_D_NV, GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_ALPHA); - else - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_D_NV, GL_ZERO, GL_EXPAND_NORMAL_NV, GL_ALPHA); - glCombinerOutputNV(C, GL_ALPHA, GL_DISCARD_NV, GL_DISCARD_NV, dreg, scale, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - else if (!paired_instr) - { - glCombinerOutputNV(C, GL_ALPHA, GL_DISCARD_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - } - else if(op == "cnd") - { - src a(instr[3+instr_base],combiner); - src b(instr[4+instr_base],combiner); - - if(instr[2+instr_base] != "r0.a" && instr[2+instr_base] != "r0.w") - {} // bad - if(mask == GL_RGBA || mask == GL_RGB) - { - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_A_NV, a.reg, a.map, a.comp); - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_B_NV, GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_RGB); - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_C_NV, b.reg, b.map, b.comp); - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_D_NV, GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_RGB); - glCombinerOutputNV(C, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, dreg, scale, GL_NONE, - GL_FALSE, GL_FALSE, GL_TRUE); - } - else if (!paired_instr) - { - glCombinerOutputNV(C, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - - if(mask == GL_RGBA || mask == GL_ALPHA) - { - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_A_NV, a.reg, a.map, a.alphaComp); - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_B_NV, GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_ALPHA); - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_C_NV, b.reg, b.map, b.alphaComp); - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_D_NV, GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_ALPHA); - glCombinerOutputNV(C, GL_ALPHA, GL_DISCARD_NV, GL_DISCARD_NV, dreg, scale, GL_NONE, - GL_FALSE, GL_FALSE, GL_TRUE); - } - else if (!paired_instr) - { - glCombinerOutputNV(C, GL_ALPHA, GL_DISCARD_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - } - else if(op == "dp3") - { - src a(instr[2+instr_base],combiner); - src b(instr[3+instr_base],combiner); - - if(mask == GL_RGBA || mask == GL_RGB) - { - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_A_NV, a.reg, a.map, a.comp); - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_B_NV, b.reg, b.map, b.comp); - glCombinerOutputNV(C, GL_RGB, dreg, GL_DISCARD_NV, GL_DISCARD_NV, scale, GL_NONE, - GL_TRUE, GL_FALSE, GL_FALSE); - } - else if (!paired_instr) - { - // ooh.. what to do here? - } - - if(mask == GL_RGBA || mask == GL_ALPHA) - { - // todo -- make next ref to dst.a actually ref dst.b since combiners can't write dp3 to the alpha channel - // Done by Ashu: Put this register in the alphaBlueRegister set. - isAlphaBlue = true; - ps10::alphaBlueRegisters.insert(dst.c_str()); - } - else if (!paired_instr) - { - glCombinerOutputNV(C, GL_ALPHA, GL_DISCARD_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - } - else if(op == "lrp") - { - src a(instr[2+instr_base],combiner); - src b(instr[3+instr_base],combiner); - src c(instr[4+instr_base],combiner); - - if(mask == GL_RGBA || mask == GL_RGB) - { - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_A_NV, a.reg, GL_UNSIGNED_IDENTITY_NV, a.comp); - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_B_NV, b.reg, b.map, b.comp); - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_C_NV, a.reg, GL_UNSIGNED_INVERT_NV, a.comp); - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_D_NV, c.reg, c.map, c.comp); - glCombinerOutputNV(C, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, dreg, scale, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - else if (!paired_instr) - { - glCombinerOutputNV(C, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - - if(mask == GL_RGBA || mask == GL_ALPHA) - { - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_A_NV, a.reg, GL_UNSIGNED_IDENTITY_NV, a.alphaComp); - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_B_NV, b.reg, b.map, b.alphaComp); - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_C_NV, a.reg, GL_UNSIGNED_INVERT_NV, a.alphaComp); - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_D_NV, c.reg, c.map, c.alphaComp); - glCombinerOutputNV(C, GL_ALPHA, GL_DISCARD_NV, GL_DISCARD_NV, dreg, scale, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - else if (!paired_instr) - { - glCombinerOutputNV(C, GL_ALPHA, GL_DISCARD_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - } - else if(op == "mad") - { - src a(instr[2+instr_base],combiner); - src b(instr[3+instr_base],combiner); - src c(instr[4+instr_base],combiner); - - if(mask == GL_RGBA || mask == GL_RGB) - { - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_A_NV, a.reg, a.map, a.comp); - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_B_NV, b.reg, b.map, b.comp); - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_C_NV, GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_RGB); - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_D_NV, c.reg, c.map, c.comp); - glCombinerOutputNV(C, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, dreg, scale, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - else if (!paired_instr) - { - glCombinerOutputNV(C, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - - if(mask == GL_RGBA || mask == GL_ALPHA) - { - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_A_NV, a.reg, a.map, a.alphaComp); - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_B_NV, b.reg, b.map, b.alphaComp); - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_C_NV, GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_ALPHA); - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_D_NV, c.reg, c.map, c.alphaComp); - glCombinerOutputNV(C, GL_ALPHA, GL_DISCARD_NV, GL_DISCARD_NV, dreg, scale, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - else if (!paired_instr) - { - glCombinerOutputNV(C, GL_ALPHA, GL_DISCARD_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - } - else if(op == "mov") - { - src a(instr[2+instr_base],combiner); - - if(mask == GL_RGBA || mask == GL_RGB) - { - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_A_NV, a.reg, a.map, a.comp); - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_B_NV, GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_RGB); - glCombinerOutputNV(C, GL_RGB, dreg, GL_DISCARD_NV, GL_DISCARD_NV, scale, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - else if (!paired_instr) - { - glCombinerOutputNV(C, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - - if(mask == GL_RGBA || mask == GL_ALPHA) - { - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_A_NV, a.reg, a.map, a.alphaComp); - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_B_NV, GL_ZERO, GL_UNSIGNED_INVERT_NV, GL_ALPHA); - glCombinerOutputNV(C, GL_ALPHA, dreg, GL_DISCARD_NV, GL_DISCARD_NV, scale, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - else if (!paired_instr) - { - glCombinerOutputNV(C, GL_ALPHA, GL_DISCARD_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - } - else if(op == "mul") - { - src a(instr[2+instr_base],combiner); - src b(instr[3+instr_base],combiner); - - if(mask == GL_RGBA || mask == GL_RGB) - { - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_A_NV, a.reg, a.map, a.comp); - glCombinerInputNV(C, GL_RGB, GL_VARIABLE_B_NV, b.reg, b.map, b.comp); - glCombinerOutputNV(C, GL_RGB, dreg, GL_DISCARD_NV, GL_DISCARD_NV, scale, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - else if (!paired_instr) - { - glCombinerOutputNV(C, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - - if(mask == GL_RGBA || mask == GL_ALPHA) - { - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_A_NV, a.reg, a.map, a.alphaComp); - glCombinerInputNV(C, GL_ALPHA, GL_VARIABLE_B_NV, b.reg, b.map, b.alphaComp); - glCombinerOutputNV(C, GL_ALPHA, dreg, GL_DISCARD_NV, GL_DISCARD_NV, scale, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - else if (!paired_instr) - { - glCombinerOutputNV(C, GL_ALPHA, GL_DISCARD_NV, GL_DISCARD_NV, GL_DISCARD_NV, GL_NONE, GL_NONE, - GL_FALSE, GL_FALSE, GL_FALSE); - } - } - // combiner++; - if (!isAlphaBlue) - RemoveFromAlphaBlue(dst); - } - - int combiner; - }; - - -} - -void ps10::SetFinalCombinerStage() -{ - glFinalCombinerInputNV(GL_VARIABLE_A_NV,GL_FOG,GL_UNSIGNED_IDENTITY_NV,GL_ALPHA); - glFinalCombinerInputNV(GL_VARIABLE_B_NV,GL_SPARE0_NV, - GL_UNSIGNED_IDENTITY_NV,GL_RGB); - glFinalCombinerInputNV(GL_VARIABLE_C_NV,GL_FOG,GL_UNSIGNED_IDENTITY_NV,GL_RGB); - glFinalCombinerInputNV(GL_VARIABLE_D_NV,GL_ZERO,GL_UNSIGNED_IDENTITY_NV,GL_RGB); - glFinalCombinerInputNV(GL_VARIABLE_E_NV,GL_ZERO,GL_UNSIGNED_IDENTITY_NV,GL_RGB); - glFinalCombinerInputNV(GL_VARIABLE_F_NV,GL_ZERO,GL_UNSIGNED_IDENTITY_NV,GL_RGB); - std::set::iterator iter = ps10::alphaBlueRegisters.find("r0"); - GLenum alphaComp = GL_ALPHA; - if (iter != ps10::alphaBlueRegisters.end()) - alphaComp = GL_BLUE; - glFinalCombinerInputNV(GL_VARIABLE_G_NV,GL_SPARE0_NV,GL_UNSIGNED_IDENTITY_NV,alphaComp); - // We can now clear alphaBlueRegisters for the next go around - alphaBlueRegisters.clear(); -} - -void ps10::invoke(vector * c, - list > * a, - list > * b) -{ - const_to_combiner_reg_mapping_count = 0; // Hansong - - GLint activeTex = 0; - glGetIntegerv(GL_ACTIVE_TEXTURE, &activeTex); - - glEnable(GL_PER_STAGE_CONSTANTS_NV); // should we require apps to do this? - if (c) - for_each(c->begin(), c->end(), set_constants()); - if (a) - for_each(a->begin(), a->end(), set_texture_shaders(c)); - glActiveTextureARB(GL_TEXTURE0_ARB); - int numCombiners = 0; - if(b) - { - list >::iterator it = b->begin(); - for (; it != b->end(); ++it) { - if ((*it)[0] != "+") - numCombiners++; - } - } - glCombinerParameteriNV(GL_NUM_GENERAL_COMBINERS_NV, numCombiners); - if(b) - for_each(b->begin(), b->end(), set_register_combiners()); - SetFinalCombinerStage(); - // We can clear the stageToTarget map now. - stageToTargetMap.clear(); - glActiveTextureARB(activeTex); -} - -// simple identification - just look for magic substring -// -- easy to break... -bool is_ps10(const char * s) -{ - if(strstr(s, "ps.1.0")) - return true; - if(strstr(s, "Ps.1.0")) - return true; - if(strstr(s, "ps.1.1")) - return true; - if(strstr(s, "Ps.1.1")) - return true; - return false; -} - -bool ps10::init_extensions() -{ - // register combiners - static bool rcinit = false; - if(rcinit == false) - { - /* - if(! glh_init_extensions("GL_NV_register_combiners")) - { - errors.set("unable to initialize GL_NV_register_combiners\n"); - return false; - } - else - { - */ - rcinit = true; - /* - } - */ - } - - // register combiners 2 - static bool rc2init = false; - if(rc2init == false) - { - /* - if( ! glh_init_extensions("GL_NV_register_combiners2")) - { - errors.set("unable to initialize GL_NV_register_combiners2\n"); - return false; - } - else - { - */ - rc2init = true; - /* - } - */ - } - - static bool tsinit = 0; - if (tsinit == false ) - { - /* - if(! glh_init_extensions( "GL_NV_texture_shader " "GL_ARB_multitexture " )) - { - errors.set("unable to initialize GL_NV_texture_shader\n"); - return false; - } - else - { - */ - tsinit = true; - /* - } - */ - } - constToStageAndConstMap.clear(); - constToStageArray.clear(); - stageToConstMap.clear(); - line_number = 1; - return true; -} - -const int* ps10_get_info(int* pcount) -{ - if (pcount) - *pcount = constToStageArray.size(); - return &(constToStageArray[0]); -} diff --git a/RenderSystems/GL/src/nvparse/ps1.0_program.h b/RenderSystems/GL/src/nvparse/ps1.0_program.h deleted file mode 100644 index 6214b9c4401..00000000000 --- a/RenderSystems/GL/src/nvparse/ps1.0_program.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef _PS10_PROGRAM_H -#define _PS10_PROGRAM_H - -#include "nvparse_errors.h" -#include "nvparse_externs.h" - -#include -#include -#include -#include - -namespace ps10 -{ - - struct constdef - { - std::string reg; - float r,g,b,a; - }; - - extern std::map > constToStageAndConstMap; - extern std::map stageToTargetMap; - void invoke(std::vector * c, - std::list > * a, - std::list > * b); - - bool init_extensions(); -} - -#endif diff --git a/RenderSystems/GL/src/nvparse/ps1.0_tokens.l b/RenderSystems/GL/src/nvparse/ps1.0_tokens.l deleted file mode 100644 index 4bd5e7e325f..00000000000 --- a/RenderSystems/GL/src/nvparse/ps1.0_tokens.l +++ /dev/null @@ -1,157 +0,0 @@ -/* definitions */ -digit [0-9] -char [a-zA-Z_.] -alphanum [0-9a-zA-Z_] - -%option prefix="ps10_" -%{ /* code to be included */ - -#include -#include -#include - -#include "ps1.0_program.h" - -using namespace std; -using namespace ps10; - -#include "_ps1.0_parser.h" - -#include "nvparse_errors.h" -#include "nvparse_externs.h" -#define YY_NO_UNPUT - -#define YY_INPUT(buf,result,max_size) \ -{ \ - int c = *myin++; \ - result = (c == 0) ? YY_NULL : (buf[0] = c, 1); \ -} - -#define YY_ALWAYS_INTERACTIVE 1 - -//#define DBG_MESG(msg, line) errors.set(msg, line) -#define DBG_MESG(msg, line) - -static char buf[80]; - - -%} - -%s DEFSTATE - -/* end of definitions */ -%% - -; | -\/\/ { - char ch; - while ((ch = yyinput()) != '\n') - ; - line_number++; - DBG_MESG("dbg: comment, NEWLINE", line_number-1); - return NEWLINE; - } - -[+-]?[0-9]+\.[0-9]* | -[+-]?[0-9]*\.[0-9]+ | -[+-]?[0-9]+ { - ps10_lval.fval = (float)atof(yytext); - // debug - DBG_MESG("dbg: NUMBER", line_number); - return NUMBER; - } - - - - -def { - // debug - DBG_MESG("dbg: DEF", line_number); - BEGIN DEFSTATE; - return DEF; - } - - -((1[ \t]*)?-[ \t]*)?r[01](\.a|\.b|\.w|\.rgb|\.xyz|_bias|_bx2)? | -((1[ \t]*)?-[ \t]*)?c[0-7](\.a|\.b|\.w|\.rgb|\.xyz|_bias|_bx2)? | -((1[ \t]*)?-[ \t]*)?t[0-3](\.a|\.b|\.w|\.rgb|\.xyz|_bias|_bx2)? | -((1[ \t]*)?-[ \t]*)?v[01](\.a|\.b|\.w|\.rgb|\.xyz|_bias|_bx2)? { - sprintf(buf, "dbg: REG = %s", yytext); - // debug - DBG_MESG(buf, line_number); - ps10_lval.sval = new string(yytext); - return REG; - } - -add(_x2|_x4|_d2)?(_sat)? | -cnd(_x2|_x4|_d2)?(_sat)? | -dp3(_x2|_x4|_d2)?(_sat)? | -lrp(_x2|_x4|_d2)?(_sat)? | -mad(_x2|_x4|_d2)?(_sat)? | -mov(_x2|_x4|_d2)?(_sat)? | -mul(_x2|_x4|_d2)?(_sat)? | -sub(_x2|_x4|_d2)?(_sat)? { - sprintf(buf, "dbg: BLENDOP = %s", yytext); - // debug - DBG_MESG(buf, line_number); - ps10_lval.sval = new string(yytext); - return BLENDOP; - } - -tex | -texbem | -texbeml | -texcoord | -texkill | -texm3x2pad | -texm3x2tex | -texreg2ar | -texreg2gb | -texm3x3pad | -texm3x3spec | -texm3x3tex | -texm3x3vspec { - sprintf(buf, "dbg: ADDROP = %s", yytext); - // debug - DBG_MESG(buf, line_number); - ps10_lval.sval = new string(yytext); - return ADDROP; - } - - - -([ \t]*\r?\n)+ { - line_number++; - BEGIN 0; - // debug - DBG_MESG("dbg: NEWLINE", line_number-1); - return NEWLINE; - } - -[ \t]+ { - } - -[Pp]s\.1.[01] { - return HEADER; - } - -. { - char buf[40]; - sprintf(buf, "character token == '%c'", *yytext); - DBG_MESG(buf, line_number); - return *yytext; - } - -%% -bool ps10_init(char* inputString) -{ - myin = inputString; - return init_extensions(); -} - -#ifndef ps10_wrap -int ps10_wrap(void) -{ - return(1); -} -#endif diff --git a/RenderSystems/GL/src/nvparse/rc1.0_combiners.cpp b/RenderSystems/GL/src/nvparse/rc1.0_combiners.cpp deleted file mode 100644 index 5d1c37d3e58..00000000000 --- a/RenderSystems/GL/src/nvparse/rc1.0_combiners.cpp +++ /dev/null @@ -1,90 +0,0 @@ -#include "rc1.0_combiners.h" -#include "nvparse_errors.h" -#include "nvparse_externs.h" -#include - -void CombinersStruct::Validate() -{ - if (2 == numConsts && - cc[0].reg.bits.name == cc[1].reg.bits.name) - errors.set("global constant set twice"); - - generals.Validate(numConsts, &cc[0]); - - final.Validate(); -} - -void CombinersStruct::Invoke() -{ - for (int i = 0; i < numConsts; i++) - glCombinerParameterfvNV(cc[i].reg.bits.name, &(cc[i].v[0])); - - generals.Invoke(); - - final.Invoke(); -} - -bool is_rc10(const char * s) -{ - return ! strncmp(s, "!!RC1.0", 7); -} - - -bool rc10_init_more() -{ - bool rcinit = false; - if(rcinit == false) - { - /* - if(! glh_init_extensions("GL_NV_register_combiners")) - { - errors.set("unable to initialize GL_NV_register_combiners\n"); - return false; - } - else - { - */ - rcinit = true; - /* - } - */ - } - - bool rc2init = false; - if(rc2init == false) - { - //glh_init_extensions("GL_NV_register_combiners2"); - // Don't fail if this doesn't initialize. - // We will run even if it doesn't exist. - rc2init = true; - } - - errors.reset(); - line_number = 1; - - return true; -} -/* - else if(!strncmp(instring, "!!RC1.0", 7)) - { - if(glCombinerParameterfvNV == 0) - { - if(! glh_init_extensions("GL_NV_register_combiners")) - { - errors.set("unable to initialize GL_NV_register_combiners\n"); - free(instring); - return; - } - } - if(glCombinerStageParameterfvNV == 0) - { - glh_init_extensions("GL_NV_register_combiners2"); - // Don't fail if this doesn't initialize. - // We will run even if it doesn't exist. - } - errors.reset(); - line_number = 1; - rc10_init(instring+7); - rc10_parse(); - } -*/ diff --git a/RenderSystems/GL/src/nvparse/rc1.0_combiners.h b/RenderSystems/GL/src/nvparse/rc1.0_combiners.h deleted file mode 100644 index 85c1c560c5c..00000000000 --- a/RenderSystems/GL/src/nvparse/rc1.0_combiners.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef _RC10_COMBINERS_H -#define _RC10_COMBINERS_H - -#include "rc1.0_general.h" -#include "rc1.0_final.h" - -class CombinersStruct { -public: - void Init(GeneralCombinersStruct _gcs, FinalCombinerStruct _fc, ConstColorStruct _cc0, ConstColorStruct _cc1) - { generals = _gcs; final = _fc; cc[0] = _cc0; cc[1] = _cc1; numConsts = 2;} - void Init(GeneralCombinersStruct _gcs, FinalCombinerStruct _fc, ConstColorStruct _cc0) - { generals = _gcs; final = _fc; cc[0] = _cc0; numConsts = 1;} - void Init(GeneralCombinersStruct _gcs, FinalCombinerStruct _fc) - { generals = _gcs; final = _fc; numConsts = 0;} - void Validate(); - void Invoke(); -private: - GeneralCombinersStruct generals; - FinalCombinerStruct final; - ConstColorStruct cc[2]; - int numConsts; -}; - -#endif diff --git a/RenderSystems/GL/src/nvparse/rc1.0_final.cpp b/RenderSystems/GL/src/nvparse/rc1.0_final.cpp deleted file mode 100644 index c6c2ff2bcfc..00000000000 --- a/RenderSystems/GL/src/nvparse/rc1.0_final.cpp +++ /dev/null @@ -1,157 +0,0 @@ -#include "rc1.0_final.h" -#include "nvparse_errors.h" -#include "nvparse_externs.h" - -void FinalRgbFunctionStruct::ZeroOut() -{ - RegisterEnum zero; - zero.word = RCP_ZERO; - a.Init(zero, GL_UNSIGNED_IDENTITY_NV); - b.Init(zero, GL_UNSIGNED_IDENTITY_NV); - c.Init(zero, GL_UNSIGNED_IDENTITY_NV); - d.Init(zero, GL_UNSIGNED_IDENTITY_NV); -} - -void FinalAlphaFunctionStruct::ZeroOut() -{ - RegisterEnum zero; - zero.word = RCP_ZERO; - g.Init(zero, GL_UNSIGNED_IDENTITY_NV); -} - -void FinalProductStruct::ZeroOut() -{ - RegisterEnum zero; - zero.word = RCP_ZERO; - e.Init(zero, GL_UNSIGNED_IDENTITY_NV); - f.Init(zero, GL_UNSIGNED_IDENTITY_NV); -} -void FinalCombinerStruct::Validate() -{ - if (hasProduct && - (GL_E_TIMES_F_NV == product.e.reg.bits.name || - GL_SPARE0_PLUS_SECONDARY_COLOR_NV == product.e.reg.bits.name || - GL_DISCARD_NV == product.e.reg.bits.name || - GL_E_TIMES_F_NV == product.f.reg.bits.name || - GL_SPARE0_PLUS_SECONDARY_COLOR_NV == product.f.reg.bits.name || - GL_DISCARD_NV == product.f.reg.bits.name)) - errors.set("invalid input register for final_product"); - - if (hasProduct && - (RCP_BLUE == product.e.reg.bits.channel || - RCP_BLUE == product.f.reg.bits.channel)) - errors.set("blue register used in final_product"); - - if (GL_E_TIMES_F_NV == alpha.g.reg.bits.name || - GL_SPARE0_PLUS_SECONDARY_COLOR_NV == alpha.g.reg.bits.name || - GL_DISCARD_NV == alpha.g.reg.bits.name) - errors.set("invalid input register for final alpha"); - - if (RCP_RGB == alpha.g.reg.bits.channel) - errors.set("rgb register used in final alpha"); - - if (GL_SPARE0_PLUS_SECONDARY_COLOR_NV == rgb.a.reg.bits.name && - GL_SPARE0_PLUS_SECONDARY_COLOR_NV != rgb.b.reg.bits.name && - GL_ZERO == rgb.c.reg.bits.name && GL_UNSIGNED_IDENTITY_NV == rgb.c.map) - { - MappedRegisterStruct temp; - temp = rgb.a; - rgb.a = rgb.b; - rgb.b = temp; - } - - if (GL_SPARE0_PLUS_SECONDARY_COLOR_NV == rgb.a.reg.bits.name && - GL_ZERO == rgb.b.reg.bits.name && GL_UNSIGNED_INVERT_NV == rgb.b.map && - GL_ZERO == rgb.c.reg.bits.name && GL_UNSIGNED_IDENTITY_NV == rgb.c.map && - GL_SPARE0_PLUS_SECONDARY_COLOR_NV != rgb.d.reg.bits.name) - { - MappedRegisterStruct temp; - temp = rgb.a; - rgb.a = rgb.d; - rgb.d = temp; - } - - if (GL_SPARE0_PLUS_SECONDARY_COLOR_NV == rgb.a.reg.bits.name || - GL_DISCARD_NV == rgb.a.reg.bits.name || - GL_DISCARD_NV == rgb.b.reg.bits.name || - GL_DISCARD_NV == rgb.c.reg.bits.name || - GL_DISCARD_NV == rgb.d.reg.bits.name) - errors.set("invalid input register for final rgb"); - - if (RCP_BLUE == rgb.a.reg.bits.channel || - RCP_BLUE == rgb.b.reg.bits.channel || - RCP_BLUE == rgb.c.reg.bits.channel || - RCP_BLUE == rgb.d.reg.bits.channel) - errors.set("blue register used in final rgb"); - - if ((GL_E_TIMES_F_NV == rgb.a.reg.bits.name || - GL_E_TIMES_F_NV == rgb.b.reg.bits.name || - GL_E_TIMES_F_NV == rgb.c.reg.bits.name || - GL_E_TIMES_F_NV == rgb.d.reg.bits.name) && !hasProduct) - errors.set("final_product used but not set"); - - if (RCP_NONE == rgb.a.reg.bits.channel) - rgb.a.reg.bits.channel = RCP_RGB; - if (RCP_NONE == rgb.b.reg.bits.channel) - rgb.b.reg.bits.channel = RCP_RGB; - if (RCP_NONE == rgb.c.reg.bits.channel) - rgb.c.reg.bits.channel = RCP_RGB; - if (RCP_NONE == rgb.d.reg.bits.channel) - rgb.d.reg.bits.channel = RCP_RGB; - if (RCP_NONE == product.e.reg.bits.channel) - product.e.reg.bits.channel = RCP_RGB; - if (RCP_NONE == product.f.reg.bits.channel) - product.f.reg.bits.channel = RCP_RGB; - if (RCP_NONE == alpha.g.reg.bits.channel) - alpha.g.reg.bits.channel = RCP_ALPHA; -} - -void FinalCombinerStruct::Invoke() -{ - if(clamp) - glCombinerParameteriNV(GL_COLOR_SUM_CLAMP_NV, GL_TRUE); - else - glCombinerParameteriNV(GL_COLOR_SUM_CLAMP_NV, GL_FALSE); - - glFinalCombinerInputNV( - GL_VARIABLE_A_NV, - rgb.a.reg.bits.name, - rgb.a.map, - MAP_CHANNEL(rgb.a.reg.bits.channel)); - - glFinalCombinerInputNV( - GL_VARIABLE_B_NV, - rgb.b.reg.bits.name, - rgb.b.map, - MAP_CHANNEL(rgb.b.reg.bits.channel)); - - glFinalCombinerInputNV( - GL_VARIABLE_C_NV, - rgb.c.reg.bits.name, - rgb.c.map, - MAP_CHANNEL(rgb.c.reg.bits.channel)); - - glFinalCombinerInputNV( - GL_VARIABLE_D_NV, - rgb.d.reg.bits.name, - rgb.d.map, - MAP_CHANNEL(rgb.d.reg.bits.channel)); - - glFinalCombinerInputNV( - GL_VARIABLE_E_NV, - product.e.reg.bits.name, - product.e.map, - MAP_CHANNEL(product.e.reg.bits.channel)); - - glFinalCombinerInputNV( - GL_VARIABLE_F_NV, - product.f.reg.bits.name, - product.f.map, - MAP_CHANNEL(product.f.reg.bits.channel)); - - glFinalCombinerInputNV( - GL_VARIABLE_G_NV, - alpha.g.reg.bits.name, - alpha.g.map, - MAP_CHANNEL(alpha.g.reg.bits.channel)); -} diff --git a/RenderSystems/GL/src/nvparse/rc1.0_final.h b/RenderSystems/GL/src/nvparse/rc1.0_final.h deleted file mode 100644 index 9d919cf0a9f..00000000000 --- a/RenderSystems/GL/src/nvparse/rc1.0_final.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef _RC10_FINAL_H -#define _RC10_FINAL_H - -#include "rc1.0_register.h" - -class FinalAlphaFunctionStruct { -public: - void Init(MappedRegisterStruct _g) { g = _g; } - void ZeroOut(); - MappedRegisterStruct g; -}; - -class FinalRgbFunctionStruct { -public: - void Init(MappedRegisterStruct _a, MappedRegisterStruct _b, MappedRegisterStruct _c, MappedRegisterStruct _d) - { a = _a; b = _b; c = _c; d = _d; } - void ZeroOut(); - MappedRegisterStruct a; - MappedRegisterStruct b; - MappedRegisterStruct c; - MappedRegisterStruct d; -}; - -class FinalProductStruct { -public: - void Init(MappedRegisterStruct _e, MappedRegisterStruct _f) { e = _e; f = _f; } - void ZeroOut(); - MappedRegisterStruct e; - MappedRegisterStruct f; -}; - -class FinalCombinerStruct { -public: - void Init(FinalRgbFunctionStruct _rgb, FinalAlphaFunctionStruct _alpha, int _clamp, FinalProductStruct _product) - { rgb = _rgb; alpha = _alpha; clamp = _clamp; product = _product; hasProduct = true;} - void Init(FinalRgbFunctionStruct _rgb, FinalAlphaFunctionStruct _alpha, int _clamp) - { rgb = _rgb; alpha = _alpha; clamp = _clamp; hasProduct = false; product.ZeroOut();} - - int hasProduct; - FinalProductStruct product; - int clamp; - FinalRgbFunctionStruct rgb; - FinalAlphaFunctionStruct alpha; - void Validate(); - void Invoke(); -}; - -#endif diff --git a/RenderSystems/GL/src/nvparse/rc1.0_general.cpp b/RenderSystems/GL/src/nvparse/rc1.0_general.cpp deleted file mode 100644 index 2e1a7a73963..00000000000 --- a/RenderSystems/GL/src/nvparse/rc1.0_general.cpp +++ /dev/null @@ -1,300 +0,0 @@ -#include "rc1.0_general.h" -#include "nvparse_errors.h" -#include "nvparse_externs.h" -#include - -void GeneralCombinersStruct::Validate(int numConsts, ConstColorStruct *pcc) -{ - GLint maxGCs; - glGetIntegerv(GL_MAX_GENERAL_COMBINERS_NV, &maxGCs); - if (num > maxGCs) { - char buffer[256]; - sprintf(buffer, "%d general combiners specified, only %d supported", num, (int)maxGCs); - errors.set(buffer); - num = maxGCs; - } - - if (0 == num) { - // Setup a "fake" general combiner 0 - general[0].ZeroOut(); - num = 1; - } - - localConsts = 0; - int i; - for (i = 0; i < num; i++) - localConsts += general[i].numConsts; - - if (localConsts > 0) - { - if (NULL == glCombinerStageParameterfvNV) - errors.set("local constant(s) specified, but not supported -- ignored"); - else - for (i = 0; i < num; i++) - general[i].SetUnusedLocalConsts(numConsts, pcc); - } - - for (i = 0; i < num; i++) - general[i].Validate(i); - - - for (; i < maxGCs; i++) - general[i].ZeroOut(); -} - -void GeneralCombinersStruct::Invoke() -{ - glCombinerParameteriNV(GL_NUM_GENERAL_COMBINERS_NV, num); - int i; - for (i = 0; i < num; i++) - general[i].Invoke(i); - - if (NULL != glCombinerStageParameterfvNV) { - if (localConsts > 0) - glEnable(GL_PER_STAGE_CONSTANTS_NV); - else - glDisable(GL_PER_STAGE_CONSTANTS_NV); - } - -} - -void GeneralCombinerStruct::ZeroOut() -{ - numPortions = 2; - numConsts = 0; - - portion[0].ZeroOut(); - portion[0].designator = RCP_RGB; - portion[1].ZeroOut(); - portion[1].designator = RCP_ALPHA; -} - - -void GeneralCombinerStruct::SetUnusedLocalConsts(int numGlobalConsts, ConstColorStruct *globalCCs) -{ - int i; - for (i = 0; i < numGlobalConsts; i++) { - bool constUsed = false; - int j; - for (j = 0; j < numConsts; j++) - constUsed |= (cc[j].reg.bits.name == globalCCs[i].reg.bits.name); - if (!constUsed) - cc[numConsts++] = globalCCs[i]; - } -} - - -void GeneralCombinerStruct::Validate(int stage) -{ - if (2 == numConsts && - cc[0].reg.bits.name == cc[1].reg.bits.name) - errors.set("local constant set twice"); - - switch (numPortions) - { - case 0: - portion[0].designator = RCP_RGB; - // Fallthru - case 1: - portion[1].designator = ((RCP_RGB == portion[0].designator) ? RCP_ALPHA : RCP_RGB); - // Fallthru - case 2: - if (portion[0].designator == portion[1].designator) - errors.set("portion declared twice"); - break; - } - int i; - for (i = 0; i < numPortions; i++) - portion[i].Validate(stage); - - for (; i < 2; i++) - portion[i].ZeroOut(); - -} - -void GeneralCombinerStruct::Invoke(int stage) -{ - int i; - - if (NULL != glCombinerStageParameterfvNV) - for (i = 0; i < numConsts; i++) - glCombinerStageParameterfvNV(GL_COMBINER0_NV + stage, cc[i].reg.bits.name, &(cc[i].v[0])); - - for (i = 0; i < 2; i++) - portion[i].Invoke(stage); -} - -void GeneralPortionStruct::Validate(int stage) -{ - gf.Validate(stage, designator); -} - -void GeneralPortionStruct::Invoke(int stage) -{ - gf.Invoke(stage, designator, bs); -} - -void GeneralPortionStruct::ZeroOut() -{ - gf.ZeroOut(); - bs.word = RCP_SCALE_BY_ONE; -} - -void GeneralFunctionStruct::ZeroOut() -{ - // Create mapped registers for zero and discard - MappedRegisterStruct unsignedZero; - RegisterEnum zero; - zero.word = RCP_ZERO; - unsignedZero.Init(zero); - - MappedRegisterStruct unsignedDiscard; - RegisterEnum discard; - discard.word = RCP_DISCARD; - unsignedDiscard.Init(discard); - - numOps = 3; - - op[0].op = RCP_MUL; - op[0].reg[0] = unsignedDiscard; - op[0].reg[1] = unsignedZero; - op[0].reg[2] = unsignedZero; - - op[1].op = RCP_MUL; - op[1].reg[0] = unsignedDiscard; - op[1].reg[1] = unsignedZero; - op[1].reg[2] = unsignedZero; - - op[2].op = RCP_SUM; - op[2].reg[0] = unsignedDiscard; - -} - -void GeneralFunctionStruct::Validate(int stage, int portion) -{ - int i; - for (i = 0; i < numOps; i++) - op[i].Validate(stage, portion); - // Check if multiple ops are writing to same register (and it's not DISCARD) - if (numOps > 1 && - op[0].reg[0].reg.bits.name == op[1].reg[0].reg.bits.name && - GL_DISCARD_NV != op[0].reg[0].reg.bits.name) - errors.set("writing to same register twice"); - if (numOps > 2 && - (op[0].reg[0].reg.bits.name == op[2].reg[0].reg.bits.name || - op[1].reg[0].reg.bits.name == op[2].reg[0].reg.bits.name) && - GL_DISCARD_NV != op[2].reg[0].reg.bits.name) - errors.set("writing to same register twice"); - - // Set unused outputs to discard, unused inputs to zero/unsigned_identity - if (numOps < 2) { - // Set C input to zero - op[1].reg[1].reg.bits.name = GL_ZERO; - op[1].reg[1].map = GL_UNSIGNED_IDENTITY_NV; - op[1].reg[1].reg.bits.channel = portion; - - // Set D input to zero - op[1].reg[2].reg.bits.name = GL_ZERO; - op[1].reg[2].map = GL_UNSIGNED_IDENTITY_NV; - op[1].reg[2].reg.bits.channel = portion; - - // Discard CD output - op[1].op = false; - op[1].reg[0].reg.bits.name = GL_DISCARD_NV; - } - - if (numOps < 3) { - // Discard muxSum output - op[2].reg[0].reg.bits.name = GL_DISCARD_NV; - op[2].op = RCP_SUM; - } -} - - -void GeneralFunctionStruct::Invoke(int stage, int portion, BiasScaleEnum bs) -{ - GLenum portionEnum = (RCP_RGB == portion) ? GL_RGB : GL_ALPHA; - - glCombinerInputNV(GL_COMBINER0_NV + stage, - portionEnum, - GL_VARIABLE_A_NV, - op[0].reg[1].reg.bits.name, - op[0].reg[1].map, - MAP_CHANNEL(op[0].reg[1].reg.bits.channel)); - - glCombinerInputNV(GL_COMBINER0_NV + stage, - portionEnum, - GL_VARIABLE_B_NV, - op[0].reg[2].reg.bits.name, - op[0].reg[2].map, - MAP_CHANNEL(op[0].reg[2].reg.bits.channel)); - - glCombinerInputNV(GL_COMBINER0_NV + stage, - portionEnum, - GL_VARIABLE_C_NV, - op[1].reg[1].reg.bits.name, - op[1].reg[1].map, - MAP_CHANNEL(op[1].reg[1].reg.bits.channel)); - - glCombinerInputNV(GL_COMBINER0_NV + stage, - portionEnum, - GL_VARIABLE_D_NV, - op[1].reg[2].reg.bits.name, - op[1].reg[2].map, - MAP_CHANNEL(op[1].reg[2].reg.bits.channel)); - - glCombinerOutputNV(GL_COMBINER0_NV + stage, - portionEnum, - op[0].reg[0].reg.bits.name, - op[1].reg[0].reg.bits.name, - op[2].reg[0].reg.bits.name, - bs.bits.scale, - bs.bits.bias, - op[0].op, - op[1].op, - (op[2].op == RCP_MUX) ? true : false); -} - -// This helper function assigns a channel to an undesignated input register -static void ConvertRegister(RegisterEnum& reg, int portion) -{ - if (RCP_NONE == reg.bits.channel) { - reg.bits.channel = portion; - if (GL_FOG == reg.bits.name && RCP_ALPHA == portion) - // Special case where fog alpha is final only, but RGB is not - reg.bits.finalOnly = true; - } -} - - -void OpStruct::Validate(int stage, int portion) -{ - int args = 1; - - if (RCP_DOT == op || RCP_MUL == op) - args = 3; - else - args = 1; - - if (reg[0].reg.bits.readOnly) - errors.set("writing to a read-only register"); - - if (RCP_ALPHA == portion && - RCP_DOT == op) - errors.set("dot used in alpha portion"); - int i; - for (i = 0; i < args; i++) { - ConvertRegister(reg[i].reg, portion); - if (reg[i].reg.bits.finalOnly) - errors.set("final register used in general combiner"); - if (RCP_RGB == portion && - RCP_BLUE == reg[i].reg.bits.channel) - errors.set("blue register used in rgb portion"); - if (RCP_ALPHA == portion && - RCP_RGB == reg[i].reg.bits.channel) - errors.set("rgb register used in alpha portion"); - if (i > 0 && - GL_DISCARD_NV == reg[i].reg.bits.name) - errors.set("reading from discard"); - } -} diff --git a/RenderSystems/GL/src/nvparse/rc1.0_general.h b/RenderSystems/GL/src/nvparse/rc1.0_general.h deleted file mode 100644 index 5431bce3b62..00000000000 --- a/RenderSystems/GL/src/nvparse/rc1.0_general.h +++ /dev/null @@ -1,107 +0,0 @@ -#ifndef _RC10_GENERAL_H -#define _RC10_GENERAL_H - -#include "rc1.0_register.h" -#include "nvparse_errors.h" -#include "nvparse_externs.h" - -enum { - RCP_MUL = 0, - RCP_DOT, - RCP_MUX, - RCP_SUM -}; - -class ConstColorStruct { -public: - void Init(RegisterEnum _reg, float _v0, float _v1, float _v2, float _v3) - { reg = _reg; v[0] = _v0; v[1] = _v1; v[2] = _v2; v[3] = _v3; } - RegisterEnum reg; - float v[4]; -}; - -class OpStruct { -public: - void Init(int _op, RegisterEnum _reg0, MappedRegisterStruct _reg1, MappedRegisterStruct _reg2) - { op = _op; reg[0].reg = _reg0; reg[1] = _reg1; reg[2] = _reg2; } - void Init(int _op, RegisterEnum _reg0) - { op = _op; reg[0].reg = _reg0; } - int op; - MappedRegisterStruct reg[3]; - void Validate(int stage, int portion); -}; - -class GeneralFunctionStruct { -public: - void Init(OpStruct _op0, OpStruct _op1, OpStruct _op2) { op[0] = _op0; op[1] = _op1; op[2] = _op2; numOps = 3; } - void Init(OpStruct _op0, OpStruct _op1) { op[0] = _op0; op[1] = _op1; numOps = 2; } - void Init(OpStruct _op0) { op[0] = _op0; numOps = 1; } - void Validate(int stage, int portion); - void Invoke(int stage, int portion, BiasScaleEnum bs); - void ZeroOut(); - int numOps; - OpStruct op[3]; -}; - - -class GeneralPortionStruct { -public: - void Init(int _designator, GeneralFunctionStruct _gf, BiasScaleEnum _bs) - { designator = _designator; gf = _gf; bs = _bs; } - - void Validate(int stage); - void Invoke(int stage); - void ZeroOut(); - int designator; - GeneralFunctionStruct gf; - BiasScaleEnum bs; -}; - -class GeneralCombinerStruct { -public: - void Init(GeneralPortionStruct _portion0, GeneralPortionStruct _portion1, ConstColorStruct _cc0, ConstColorStruct _cc1) - { portion[0] = _portion0; portion[1] = _portion1; numPortions = 2; cc[0] = _cc0; cc[1] = _cc1; numConsts = 2; } - void Init(GeneralPortionStruct _portion0, GeneralPortionStruct _portion1, ConstColorStruct _cc0) - { portion[0] = _portion0; portion[1] = _portion1; numPortions = 2; cc[0] = _cc0; numConsts = 1; } - void Init(GeneralPortionStruct _portion0, GeneralPortionStruct _portion1) - { portion[0] = _portion0; portion[1] = _portion1; numPortions = 2; numConsts = 0; } - - void Init(GeneralPortionStruct _portion0, ConstColorStruct _cc0, ConstColorStruct _cc1) - { portion[0] = _portion0; numPortions = 1; cc[0] = _cc0; cc[1] = _cc1; numConsts = 2; } - void Init(GeneralPortionStruct _portion0, ConstColorStruct _cc0) - { portion[0] = _portion0; numPortions = 1; cc[0] = _cc0; numConsts = 1; } - void Init(GeneralPortionStruct _portion0) - { portion[0] = _portion0; numPortions = 1; numConsts = 0; } - - void Validate(int stage); - void SetUnusedLocalConsts(int numGlobalConsts, ConstColorStruct *globalCCs); - void Invoke(int stage); - void ZeroOut(); - GeneralPortionStruct portion[2]; - int numPortions; - ConstColorStruct cc[2]; - int numConsts; -}; - -class GeneralCombinersStruct { -public: - void Init() {num = 0;} - void Init(GeneralCombinerStruct _gc) { num = 1; general[0] = _gc; } - GeneralCombinersStruct& operator+=(GeneralCombinerStruct& _gc) - { - if (num < RCP_NUM_GENERAL_COMBINERS) - general[num++] = _gc; - else - errors.set("Too many general combiners."); - return *this; - } - void Validate(int numConsts, ConstColorStruct *cc); - void Invoke(); - GeneralCombinerStruct general[RCP_NUM_GENERAL_COMBINERS]; - int num; -private: - int localConsts; -}; - - -#endif diff --git a/RenderSystems/GL/src/nvparse/rc1.0_grammar.y b/RenderSystems/GL/src/nvparse/rc1.0_grammar.y deleted file mode 100644 index 8ce50dd52ec..00000000000 --- a/RenderSystems/GL/src/nvparse/rc1.0_grammar.y +++ /dev/null @@ -1,683 +0,0 @@ -%start WholeEnchilada -%name-prefix "rc10_" -%{ -void yyerror(const char* s); -int yylex ( void ); - -#ifdef _WIN32 -# include -#endif - -#include -#include - -#include "rc1.0_combiners.h" -#include "nvparse_errors.h" -#include "nvparse_externs.h" - - -%} -%union { - int ival; - float fval; - RegisterEnum registerEnum; - BiasScaleEnum biasScaleEnum; - MappedRegisterStruct mappedRegisterStruct; - ConstColorStruct constColorStruct; - GeneralPortionStruct generalPortionStruct; - GeneralFunctionStruct generalFunctionStruct; - OpStruct opStruct; - GeneralCombinerStruct generalCombinerStruct; - GeneralCombinersStruct generalCombinersStruct; - FinalProductStruct finalProductStruct; - FinalRgbFunctionStruct finalRgbFunctionStruct; - FinalAlphaFunctionStruct finalAlphaFunctionStruct; - FinalCombinerStruct finalCombinerStruct; - CombinersStruct combinersStruct; -} - -%token regVariable constVariable color_sum final_product -%token expandString halfBiasString unsignedString unsignedInvertString muxString sumString -%token rgb_portion alpha_portion -%token openParen closeParen openBracket closeBracket semicolon comma -%token dot times minus equals plus -%token bias_by_negative_one_half_scale_by_two bias_by_negative_one_half -%token scale_by_one_half scale_by_two scale_by_four - -%token clamp_color_sum lerp -%token fragment_rgb fragment_alpha - -%token floatValue - -%type WholeEnchilada Combiners - -%type ConstColor -%type GeneralCombiner -%type GeneralCombiners -%type PortionDesignator -%type Mux Sum Dot Mul -%type GeneralPortion -%type GeneralFunction -%type BiasScale - -%type Register -%type GeneralMappedRegister FinalMappedRegister -%type FinalProduct -%type ClampColorSum -%type FinalRgbFunction -%type FinalAlphaFunction -%type FinalCombiner - -%% - -WholeEnchilada : Combiners - { - $1.Validate(); - $1.Invoke(); - } - ; - -Combiners : ConstColor GeneralCombiners FinalCombiner - { - CombinersStruct combinersStruct; - combinersStruct.Init($2, $3, $1); - $$ = combinersStruct; - } - | ConstColor ConstColor GeneralCombiners FinalCombiner - { - CombinersStruct combinersStruct; - combinersStruct.Init($3, $4, $1, $2); - $$ = combinersStruct; - } - | GeneralCombiners FinalCombiner - { - CombinersStruct combinersStruct; - combinersStruct.Init($1, $2); - $$ = combinersStruct; - } - | ConstColor FinalCombiner - { - GeneralCombinersStruct generalCombinersStruct; - generalCombinersStruct.Init(); - CombinersStruct combinersStruct; - combinersStruct.Init(generalCombinersStruct, $2, $1); - $$ = combinersStruct; - } - | ConstColor ConstColor FinalCombiner - { - GeneralCombinersStruct generalCombinersStruct; - generalCombinersStruct.Init(); - CombinersStruct combinersStruct; - combinersStruct.Init(generalCombinersStruct, $3, $1, $2); - $$ = combinersStruct; - } - | FinalCombiner - { - GeneralCombinersStruct generalCombinersStruct; - generalCombinersStruct.Init(); - CombinersStruct combinersStruct; - combinersStruct.Init(generalCombinersStruct, $1); - $$ = combinersStruct; - } - ; - -ConstColor : constVariable equals openParen floatValue comma floatValue comma floatValue comma floatValue closeParen semicolon - { - ConstColorStruct constColorStruct; - constColorStruct.Init($1, $4, $6, $8, $10); - $$ = constColorStruct; - } - ; - - -GeneralCombiners : GeneralCombiners GeneralCombiner - { - $1 += $2; - $$ = $1; - } - | GeneralCombiner - { - GeneralCombinersStruct generalCombinersStruct; - generalCombinersStruct.Init($1); - $$ = generalCombinersStruct; - } - ; - -GeneralCombiner : openBracket GeneralPortion GeneralPortion closeBracket - { - GeneralCombinerStruct generalCombinerStruct; - generalCombinerStruct.Init($2, $3); - $$ = generalCombinerStruct; - } - | openBracket ConstColor GeneralPortion GeneralPortion closeBracket - { - GeneralCombinerStruct generalCombinerStruct; - generalCombinerStruct.Init($3, $4, $2); - $$ = generalCombinerStruct; - } - | openBracket ConstColor ConstColor GeneralPortion GeneralPortion closeBracket - { - GeneralCombinerStruct generalCombinerStruct; - generalCombinerStruct.Init($4, $5, $2, $3); - $$ = generalCombinerStruct; - } - | openBracket GeneralPortion closeBracket - { - GeneralCombinerStruct generalCombinerStruct; - generalCombinerStruct.Init($2); - $$ = generalCombinerStruct; - } - | openBracket ConstColor GeneralPortion closeBracket - { - GeneralCombinerStruct generalCombinerStruct; - generalCombinerStruct.Init($3, $2); - $$ = generalCombinerStruct; - } - | openBracket ConstColor ConstColor GeneralPortion closeBracket - { - GeneralCombinerStruct generalCombinerStruct; - generalCombinerStruct.Init($4, $2, $3); - $$ = generalCombinerStruct; - } - ; - -GeneralPortion : PortionDesignator openBracket GeneralFunction BiasScale closeBracket - { - GeneralPortionStruct generalPortionStruct; - generalPortionStruct.Init($1, $3, $4); - $$ = generalPortionStruct; - } - | PortionDesignator openBracket GeneralFunction closeBracket - { - BiasScaleEnum noScale; - noScale.word = RCP_SCALE_BY_ONE; - GeneralPortionStruct generalPortionStruct; - generalPortionStruct.Init($1, $3, noScale); - $$ = generalPortionStruct; - } - ; - -PortionDesignator : rgb_portion - { - $$ = $1; - } - | alpha_portion - { - $$ = $1; - } - ; - -GeneralMappedRegister : Register - { - MappedRegisterStruct reg; - reg.Init($1, GL_SIGNED_IDENTITY_NV); - $$ = reg; - } - | minus Register - { - MappedRegisterStruct reg; - reg.Init($2, GL_SIGNED_NEGATE_NV); - $$ = reg; - } - | expandString openParen Register closeParen - { - MappedRegisterStruct reg; - reg.Init($3, GL_EXPAND_NORMAL_NV); - $$ = reg; - } - | minus expandString openParen Register closeParen - { - MappedRegisterStruct reg; - reg.Init($4, GL_EXPAND_NEGATE_NV); - $$ = reg; - } - | halfBiasString openParen Register closeParen - { - MappedRegisterStruct reg; - reg.Init($3, GL_HALF_BIAS_NORMAL_NV); - $$ = reg; - } - | minus halfBiasString openParen Register closeParen - { - MappedRegisterStruct reg; - reg.Init($4, GL_HALF_BIAS_NEGATE_NV); - $$ = reg; - } - | unsignedString openParen Register closeParen - { - MappedRegisterStruct reg; - reg.Init($3, GL_UNSIGNED_IDENTITY_NV); - $$ = reg; - } - | unsignedInvertString openParen Register closeParen - { - MappedRegisterStruct reg; - reg.Init($3, GL_UNSIGNED_INVERT_NV); - $$ = reg; - } - ; - -GeneralFunction : Dot Dot - { - GeneralFunctionStruct generalFunction; - generalFunction.Init($1, $2); - $$ = generalFunction; - } - | Dot Mul - { - GeneralFunctionStruct generalFunction; - generalFunction.Init($1, $2); - $$ = generalFunction; - } - | Mul Dot - { - GeneralFunctionStruct generalFunction; - generalFunction.Init($1, $2); - $$ = generalFunction; - } - | Dot - { - GeneralFunctionStruct generalFunction; - generalFunction.Init($1); - $$ = generalFunction; - } - | Mul Mul - { - GeneralFunctionStruct generalFunction; - generalFunction.Init($1, $2); - $$ = generalFunction; - } - | Mul Mul Mux - { - GeneralFunctionStruct generalFunction; - generalFunction.Init($1, $2, $3); - $$ = generalFunction; - } - | Mul Mul Sum - { - GeneralFunctionStruct generalFunction; - generalFunction.Init($1, $2, $3); - $$ = generalFunction; - } - | Mul - { - GeneralFunctionStruct generalFunction; - generalFunction.Init($1); - $$ = generalFunction; - } - ; - -Dot : Register equals GeneralMappedRegister dot GeneralMappedRegister semicolon - { - OpStruct dotFunction; - dotFunction.Init(RCP_DOT, $1, $3, $5); - $$ = dotFunction; - } - ; - -Mul : Register equals GeneralMappedRegister times GeneralMappedRegister semicolon - { - OpStruct mulFunction; - mulFunction.Init(RCP_MUL, $1, $3, $5); - $$ = mulFunction; - } - | Register equals GeneralMappedRegister semicolon - { - RegisterEnum zero; - zero.word = RCP_ZERO; - MappedRegisterStruct one; - one.Init(zero, GL_UNSIGNED_INVERT_NV); - OpStruct mulFunction; - mulFunction.Init(RCP_MUL, $1, $3, one); - $$ = mulFunction; - } - ; - -Mux : Register equals muxString openParen closeParen semicolon - { - OpStruct muxFunction; - muxFunction.Init(RCP_MUX, $1); - $$ = muxFunction; - } - ; - -Sum : Register equals sumString openParen closeParen semicolon - { - OpStruct sumFunction; - sumFunction.Init(RCP_SUM, $1); - $$ = sumFunction; - } - ; - -BiasScale : bias_by_negative_one_half_scale_by_two openParen closeParen semicolon - { - $$ = $1; - } - | bias_by_negative_one_half openParen closeParen semicolon - { - $$ = $1; - } - | scale_by_one_half openParen closeParen semicolon - { - $$ = $1; - } - | scale_by_two openParen closeParen semicolon - { - $$ = $1; - } - | scale_by_four openParen closeParen semicolon - { - $$ = $1; - } - ; - -FinalMappedRegister : Register - { - MappedRegisterStruct reg; - reg.Init($1, GL_UNSIGNED_IDENTITY_NV); - $$ = reg; - } - | unsignedString openParen Register closeParen - { - MappedRegisterStruct reg; - reg.Init($3, GL_UNSIGNED_IDENTITY_NV); - $$ = reg; - } - | unsignedInvertString openParen Register closeParen - { - MappedRegisterStruct reg; - reg.Init($3, GL_UNSIGNED_INVERT_NV); - $$ = reg; - } - | color_sum - { - MappedRegisterStruct reg; - reg.Init($1); - $$ = reg; - } - | unsignedString openParen color_sum closeParen - { - MappedRegisterStruct reg; - reg.Init($3, GL_UNSIGNED_IDENTITY_NV); - $$ = reg; - } - | unsignedInvertString openParen color_sum closeParen - { - MappedRegisterStruct reg; - reg.Init($3, GL_UNSIGNED_INVERT_NV); - $$ = reg; - } - | final_product - { - MappedRegisterStruct reg; - reg.Init($1); - $$ = reg; - } - | unsignedString openParen final_product closeParen - { - MappedRegisterStruct reg; - reg.Init($3, GL_UNSIGNED_IDENTITY_NV); - $$ = reg; - } - | unsignedInvertString openParen final_product closeParen - { - MappedRegisterStruct reg; - reg.Init($3, GL_UNSIGNED_INVERT_NV); - $$ = reg; - } - ; - -FinalCombiner : FinalAlphaFunction FinalRgbFunction - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init($2, $1, false); - $$ = finalCombinerStruct; - } - | ClampColorSum FinalAlphaFunction FinalRgbFunction - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init($3, $2, true); - $$ = finalCombinerStruct; - } - | FinalProduct FinalAlphaFunction FinalRgbFunction - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init($3, $2, false, $1); - $$ = finalCombinerStruct; - } - | ClampColorSum FinalProduct FinalAlphaFunction FinalRgbFunction - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init($4, $3, true, $2); - $$ = finalCombinerStruct; - } - | FinalProduct ClampColorSum FinalAlphaFunction FinalRgbFunction - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init($4, $3, true, $1); - $$ = finalCombinerStruct; - } - - | FinalRgbFunction FinalAlphaFunction - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init($1, $2, false); - $$ = finalCombinerStruct; - } - | ClampColorSum FinalRgbFunction FinalAlphaFunction - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init($2, $3, true); - $$ = finalCombinerStruct; - } - | FinalProduct FinalRgbFunction FinalAlphaFunction - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init($2, $3, false, $1); - $$ = finalCombinerStruct; - } - | ClampColorSum FinalProduct FinalRgbFunction FinalAlphaFunction - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init($3, $4, true, $2); - $$ = finalCombinerStruct; - } - | FinalProduct ClampColorSum FinalRgbFunction FinalAlphaFunction - { - FinalCombinerStruct finalCombinerStruct; - finalCombinerStruct.Init($3, $4, true, $1); - $$ = finalCombinerStruct; - } - - | FinalRgbFunction - { - FinalCombinerStruct finalCombinerStruct; - FinalAlphaFunctionStruct finalAlphaFunctionStruct; - finalAlphaFunctionStruct.ZeroOut(); - finalCombinerStruct.Init($1, finalAlphaFunctionStruct, false); - $$ = finalCombinerStruct; - } - | ClampColorSum FinalRgbFunction - { - FinalCombinerStruct finalCombinerStruct; - FinalAlphaFunctionStruct finalAlphaFunctionStruct; - finalAlphaFunctionStruct.ZeroOut(); - finalCombinerStruct.Init($2, finalAlphaFunctionStruct, true); - $$ = finalCombinerStruct; - } - | FinalProduct FinalRgbFunction - { - FinalCombinerStruct finalCombinerStruct; - FinalAlphaFunctionStruct finalAlphaFunctionStruct; - finalAlphaFunctionStruct.ZeroOut(); - finalCombinerStruct.Init($2, finalAlphaFunctionStruct, false, $1); - $$ = finalCombinerStruct; - } - | ClampColorSum FinalProduct FinalRgbFunction - { - FinalCombinerStruct finalCombinerStruct; - FinalAlphaFunctionStruct finalAlphaFunctionStruct; - finalAlphaFunctionStruct.ZeroOut(); - finalCombinerStruct.Init($3, finalAlphaFunctionStruct, true, $2); - $$ = finalCombinerStruct; - } - | FinalProduct ClampColorSum FinalRgbFunction - { - FinalCombinerStruct finalCombinerStruct; - FinalAlphaFunctionStruct finalAlphaFunctionStruct; - finalAlphaFunctionStruct.ZeroOut(); - finalCombinerStruct.Init($3, finalAlphaFunctionStruct, true, $1); - $$ = finalCombinerStruct; - } - - | FinalAlphaFunction - { - FinalCombinerStruct finalCombinerStruct; - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.ZeroOut(); - finalCombinerStruct.Init(finalRgbFunctionStruct, $1, false); - $$ = finalCombinerStruct; - } - | ClampColorSum FinalAlphaFunction - { - FinalCombinerStruct finalCombinerStruct; - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.ZeroOut(); - finalCombinerStruct.Init(finalRgbFunctionStruct, $2, true); - $$ = finalCombinerStruct; - } - | FinalProduct FinalAlphaFunction - { - FinalCombinerStruct finalCombinerStruct; - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.ZeroOut(); - finalCombinerStruct.Init(finalRgbFunctionStruct, $2, false, $1); - $$ = finalCombinerStruct; - } - | ClampColorSum FinalProduct FinalAlphaFunction - { - FinalCombinerStruct finalCombinerStruct; - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.ZeroOut(); - finalCombinerStruct.Init(finalRgbFunctionStruct, $3, true, $2); - $$ = finalCombinerStruct; - } - | FinalProduct ClampColorSum FinalAlphaFunction - { - FinalCombinerStruct finalCombinerStruct; - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.ZeroOut(); - finalCombinerStruct.Init(finalRgbFunctionStruct, $3, true, $1); - $$ = finalCombinerStruct; - } - ; - -ClampColorSum : clamp_color_sum openParen closeParen semicolon - { - $$ = $1; - } - ; - -FinalProduct : final_product equals FinalMappedRegister times FinalMappedRegister semicolon - { - FinalProductStruct finalProductStruct; - finalProductStruct.Init($3, $5); - $$ = finalProductStruct; - } - ; - -FinalRgbFunction : fragment_rgb equals lerp openParen FinalMappedRegister comma FinalMappedRegister comma FinalMappedRegister closeParen plus FinalMappedRegister semicolon - { - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.Init($5, $7, $9, $12); - $$ = finalRgbFunctionStruct; - } - | fragment_rgb equals FinalMappedRegister plus lerp openParen FinalMappedRegister comma FinalMappedRegister comma FinalMappedRegister closeParen semicolon - { - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.Init($7, $9, $11, $3); - $$ = finalRgbFunctionStruct; - } - | fragment_rgb equals lerp openParen FinalMappedRegister comma FinalMappedRegister comma FinalMappedRegister closeParen semicolon - { - RegisterEnum zero; - zero.word = RCP_ZERO; - MappedRegisterStruct reg; - reg.Init(zero, GL_UNSIGNED_IDENTITY_NV); - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.Init($5, $7, $9, reg); - $$ = finalRgbFunctionStruct; - } - | fragment_rgb equals FinalMappedRegister times FinalMappedRegister semicolon - { - RegisterEnum zero; - zero.word = RCP_ZERO; - MappedRegisterStruct reg1; - reg1.Init(zero, GL_UNSIGNED_IDENTITY_NV); - MappedRegisterStruct reg2; - reg2.Init(zero, GL_UNSIGNED_IDENTITY_NV); - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.Init($3, $5, reg1, reg2); - $$ = finalRgbFunctionStruct; - } - | fragment_rgb equals FinalMappedRegister times FinalMappedRegister plus FinalMappedRegister semicolon - { - RegisterEnum zero; - zero.word = RCP_ZERO; - MappedRegisterStruct reg1; - reg1.Init(zero, GL_UNSIGNED_IDENTITY_NV); - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.Init($3, $5, reg1, $7); - $$ = finalRgbFunctionStruct; - } - | fragment_rgb equals FinalMappedRegister semicolon - { - RegisterEnum zero; - zero.word = RCP_ZERO; - MappedRegisterStruct reg1; - reg1.Init(zero, GL_UNSIGNED_IDENTITY_NV); - MappedRegisterStruct reg2; - reg2.Init(zero, GL_UNSIGNED_IDENTITY_NV); - MappedRegisterStruct reg3; - reg3.Init(zero, GL_UNSIGNED_IDENTITY_NV); - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.Init(reg1, reg2, reg3, $3); - $$ = finalRgbFunctionStruct; - } - | fragment_rgb equals FinalMappedRegister plus FinalMappedRegister semicolon - { - RegisterEnum zero; - zero.word = RCP_ZERO; - MappedRegisterStruct reg2; - reg2.Init(zero, GL_UNSIGNED_INVERT_NV); - MappedRegisterStruct reg3; - reg3.Init(zero, GL_UNSIGNED_IDENTITY_NV); - FinalRgbFunctionStruct finalRgbFunctionStruct; - finalRgbFunctionStruct.Init($3, reg2, reg3, $5); - $$ = finalRgbFunctionStruct; - } - ; - -FinalAlphaFunction : fragment_alpha equals FinalMappedRegister semicolon - { - FinalAlphaFunctionStruct finalAlphaFunctionStruct; - finalAlphaFunctionStruct.Init($3); - $$ = finalAlphaFunctionStruct; - } - ; - -Register : constVariable - { - $$ = $1; - } - | regVariable - { - $$ = $1; - } - ; - -%% -void yyerror(const char* s) -{ - errors.set("unrecognized token"); -} diff --git a/RenderSystems/GL/src/nvparse/rc1.0_register.h b/RenderSystems/GL/src/nvparse/rc1.0_register.h deleted file mode 100644 index 5b79762a1cc..00000000000 --- a/RenderSystems/GL/src/nvparse/rc1.0_register.h +++ /dev/null @@ -1,204 +0,0 @@ -#ifndef _RC10_REGISTER_H -#define _RC10_REGISTER_H - -#include -#ifdef _WIN32 -#include -#endif -#include - -#define RCP_NUM_GENERAL_COMBINERS 8 - -#define RCP_RGB 0 -#define RCP_ALPHA 1 -#define RCP_BLUE 2 -#define RCP_NONE 3 - -typedef union _RegisterEnum { - struct { -#if BYTE_ORDER != BIG_ENDIAN - unsigned int name :16; // OpenGL enum for register - unsigned int channel : 2; // RCP_RGB, RCP_ALPHA, etc - unsigned int readOnly : 1; // true or false - unsigned int finalOnly : 1; // true or false - unsigned int unused :12; -#else - unsigned int unused :12; - unsigned int finalOnly : 1; // true or false - unsigned int readOnly : 1; // true or false - unsigned int channel : 2; // RCP_RGB, RCP_ALPHA, RCP_BLUE, RCP_NONE - unsigned int name :16; // OpenGL enum for register -#endif - } bits; - unsigned int word; -} RegisterEnum; -// No need for writeOnly flag, since DISCARD is the only register in that category - -// WARNING: Don't monkey with the above structure or this macro -// unless you're absolutely sure of what you're doing! -// This constant allocation makes validation *much* cleaner. -#define RCP_SET_REGISTER_ENUM(name, channel, readonly, finalonly) \ - ((finalonly << 19) | (readonly << 18) | (channel << 16) | name) - -#define RCP_FOG_RGB RCP_SET_REGISTER_ENUM(GL_FOG, RCP_RGB, 1, 0) -#define RCP_FOG_ALPHA RCP_SET_REGISTER_ENUM(GL_FOG, RCP_ALPHA, 1, 1) -#define RCP_FOG_BLUE RCP_SET_REGISTER_ENUM(GL_FOG, RCP_BLUE, 1, 0) -#define RCP_FOG RCP_SET_REGISTER_ENUM(GL_FOG, RCP_NONE, 1, 0) -#define RCP_PRIMARY_COLOR_RGB RCP_SET_REGISTER_ENUM(GL_PRIMARY_COLOR_NV, RCP_RGB, 0, 0) -#define RCP_PRIMARY_COLOR_ALPHA RCP_SET_REGISTER_ENUM(GL_PRIMARY_COLOR_NV, RCP_ALPHA, 0, 0) -#define RCP_PRIMARY_COLOR_BLUE RCP_SET_REGISTER_ENUM(GL_PRIMARY_COLOR_NV, RCP_BLUE, 0, 0) -#define RCP_PRIMARY_COLOR RCP_SET_REGISTER_ENUM(GL_PRIMARY_COLOR_NV, RCP_NONE, 0, 0) -#define RCP_SECONDARY_COLOR_RGB RCP_SET_REGISTER_ENUM(GL_SECONDARY_COLOR_NV, RCP_RGB, 0, 0) -#define RCP_SECONDARY_COLOR_ALPHA RCP_SET_REGISTER_ENUM(GL_SECONDARY_COLOR_NV, RCP_ALPHA, 0, 0) -#define RCP_SECONDARY_COLOR_BLUE RCP_SET_REGISTER_ENUM(GL_SECONDARY_COLOR_NV, RCP_BLUE, 0, 0) -#define RCP_SECONDARY_COLOR RCP_SET_REGISTER_ENUM(GL_SECONDARY_COLOR_NV, RCP_NONE, 0, 0) -#define RCP_SPARE0_RGB RCP_SET_REGISTER_ENUM(GL_SPARE0_NV, RCP_RGB, 0, 0) -#define RCP_SPARE0_ALPHA RCP_SET_REGISTER_ENUM(GL_SPARE0_NV, RCP_ALPHA, 0, 0) -#define RCP_SPARE0_BLUE RCP_SET_REGISTER_ENUM(GL_SPARE0_NV, RCP_BLUE, 0, 0) -#define RCP_SPARE0 RCP_SET_REGISTER_ENUM(GL_SPARE0_NV, RCP_NONE, 0, 0) -#define RCP_SPARE1_RGB RCP_SET_REGISTER_ENUM(GL_SPARE1_NV, RCP_RGB, 0, 0) -#define RCP_SPARE1_ALPHA RCP_SET_REGISTER_ENUM(GL_SPARE1_NV, RCP_ALPHA, 0, 0) -#define RCP_SPARE1_BLUE RCP_SET_REGISTER_ENUM(GL_SPARE1_NV, RCP_BLUE, 0, 0) -#define RCP_SPARE1 RCP_SET_REGISTER_ENUM(GL_SPARE1_NV, RCP_NONE, 0, 0) -#define RCP_TEXTURE0_RGB RCP_SET_REGISTER_ENUM(GL_TEXTURE0_ARB, RCP_RGB, 0, 0) -#define RCP_TEXTURE0_ALPHA RCP_SET_REGISTER_ENUM(GL_TEXTURE0_ARB, RCP_ALPHA, 0, 0) -#define RCP_TEXTURE0_BLUE RCP_SET_REGISTER_ENUM(GL_TEXTURE0_ARB, RCP_BLUE, 0, 0) -#define RCP_TEXTURE0 RCP_SET_REGISTER_ENUM(GL_TEXTURE0_ARB, RCP_NONE, 0, 0) -#define RCP_TEXTURE1_RGB RCP_SET_REGISTER_ENUM(GL_TEXTURE1_ARB, RCP_RGB, 0, 0) -#define RCP_TEXTURE1_ALPHA RCP_SET_REGISTER_ENUM(GL_TEXTURE1_ARB, RCP_ALPHA, 0, 0) -#define RCP_TEXTURE1_BLUE RCP_SET_REGISTER_ENUM(GL_TEXTURE1_ARB, RCP_BLUE, 0, 0) -#define RCP_TEXTURE1 RCP_SET_REGISTER_ENUM(GL_TEXTURE1_ARB, RCP_NONE, 0, 0) -#define RCP_TEXTURE2_RGB RCP_SET_REGISTER_ENUM(GL_TEXTURE2_ARB, RCP_RGB, 0, 0) -#define RCP_TEXTURE2_ALPHA RCP_SET_REGISTER_ENUM(GL_TEXTURE2_ARB, RCP_ALPHA, 0, 0) -#define RCP_TEXTURE2_BLUE RCP_SET_REGISTER_ENUM(GL_TEXTURE2_ARB, RCP_BLUE, 0, 0) -#define RCP_TEXTURE2 RCP_SET_REGISTER_ENUM(GL_TEXTURE2_ARB, RCP_NONE, 0, 0) -#define RCP_TEXTURE3_RGB RCP_SET_REGISTER_ENUM(GL_TEXTURE3_ARB, RCP_RGB, 0, 0) -#define RCP_TEXTURE3_ALPHA RCP_SET_REGISTER_ENUM(GL_TEXTURE3_ARB, RCP_ALPHA, 0, 0) -#define RCP_TEXTURE3_BLUE RCP_SET_REGISTER_ENUM(GL_TEXTURE3_ARB, RCP_BLUE, 0, 0) -#define RCP_TEXTURE3 RCP_SET_REGISTER_ENUM(GL_TEXTURE3_ARB, RCP_NONE, 0, 0) -#define RCP_CONST_COLOR0_RGB RCP_SET_REGISTER_ENUM(GL_CONSTANT_COLOR0_NV, RCP_RGB, 1, 0) -#define RCP_CONST_COLOR0_ALPHA RCP_SET_REGISTER_ENUM(GL_CONSTANT_COLOR0_NV, RCP_ALPHA, 1, 0) -#define RCP_CONST_COLOR0_BLUE RCP_SET_REGISTER_ENUM(GL_CONSTANT_COLOR0_NV, RCP_BLUE, 1, 0) -#define RCP_CONST_COLOR0 RCP_SET_REGISTER_ENUM(GL_CONSTANT_COLOR0_NV, RCP_NONE, 1, 0) -#define RCP_CONST_COLOR1_RGB RCP_SET_REGISTER_ENUM(GL_CONSTANT_COLOR1_NV, RCP_RGB, 1, 0) -#define RCP_CONST_COLOR1_ALPHA RCP_SET_REGISTER_ENUM(GL_CONSTANT_COLOR1_NV, RCP_ALPHA, 1, 0) -#define RCP_CONST_COLOR1_BLUE RCP_SET_REGISTER_ENUM(GL_CONSTANT_COLOR1_NV, RCP_BLUE, 1, 0) -#define RCP_CONST_COLOR1 RCP_SET_REGISTER_ENUM(GL_CONSTANT_COLOR1_NV, RCP_NONE, 1, 0) -#define RCP_ZERO_RGB RCP_SET_REGISTER_ENUM(GL_ZERO, RCP_RGB, 1, 0) -#define RCP_ZERO_ALPHA RCP_SET_REGISTER_ENUM(GL_ZERO, RCP_ALPHA, 1, 0) -#define RCP_ZERO_BLUE RCP_SET_REGISTER_ENUM(GL_ZERO, RCP_BLUE, 1, 0) -#define RCP_ZERO RCP_SET_REGISTER_ENUM(GL_ZERO, RCP_NONE, 1, 0) -#define RCP_ONE_RGB RCP_SET_REGISTER_ENUM(GL_ONE, RCP_RGB, 1, 0) -#define RCP_ONE_ALPHA RCP_SET_REGISTER_ENUM(GL_ONE, RCP_ALPHA, 1, 0) -#define RCP_ONE_BLUE RCP_SET_REGISTER_ENUM(GL_ONE, RCP_BLUE, 1, 0) -#define RCP_ONE RCP_SET_REGISTER_ENUM(GL_ONE, RCP_NONE, 1, 0) -#define RCP_DISCARD RCP_SET_REGISTER_ENUM(GL_DISCARD_NV, RCP_NONE, 0, 0) -#define RCP_FINAL_PRODUCT RCP_SET_REGISTER_ENUM(GL_E_TIMES_F_NV, RCP_NONE, 1, 1) -#define RCP_COLOR_SUM RCP_SET_REGISTER_ENUM(GL_SPARE0_PLUS_SECONDARY_COLOR_NV, RCP_NONE, 1, 1) - -#define MAP_CHANNEL(channel) ((RCP_RGB == (channel)) ? GL_RGB : (RCP_ALPHA == (channel) ? GL_ALPHA : GL_BLUE)) - -typedef union _BiasScaleEnum { - struct { -#if BYTE_ORDER != BIG_ENDIAN - unsigned int bias :16; // OpenGL enum for bias - unsigned int scale :16; // OpenGL enum for scale -#else - unsigned int scale :16; // OpenGL enum for scale - unsigned int bias :16; // OpenGL enum for bias -#endif - } bits; - unsigned int word; -} BiasScaleEnum; - -// WARNING: Don't monkey with the above structure or this macro -// unless you're absolutely sure of what you're doing! -// This constant allocation makes validation *much* cleaner. -#define RCP_SET_BIAS_SCALE_ENUM(bias, scale) ((scale << 16) | bias) - -#define RCP_BIAS_BY_NEGATIVE_ONE_HALF_SCALE_BY_TWO RCP_SET_BIAS_SCALE_ENUM(GL_BIAS_BY_NEGATIVE_ONE_HALF_NV, GL_SCALE_BY_TWO_NV) -#define RCP_BIAS_BY_NEGATIVE_ONE_HALF RCP_SET_BIAS_SCALE_ENUM(GL_BIAS_BY_NEGATIVE_ONE_HALF_NV, GL_NONE) -#define RCP_SCALE_BY_ONE_HALF RCP_SET_BIAS_SCALE_ENUM(GL_NONE, GL_SCALE_BY_ONE_HALF_NV) -#define RCP_SCALE_BY_ONE RCP_SET_BIAS_SCALE_ENUM(GL_NONE, GL_NONE) -#define RCP_SCALE_BY_TWO RCP_SET_BIAS_SCALE_ENUM(GL_NONE, GL_SCALE_BY_TWO_NV) -#define RCP_SCALE_BY_FOUR RCP_SET_BIAS_SCALE_ENUM(GL_NONE, GL_SCALE_BY_FOUR_NV) - -class MappedRegisterStruct { -public: - void Init(RegisterEnum _reg, int _map = GL_UNSIGNED_IDENTITY_NV) - { - if (RCP_ONE == _reg.word) { - _reg.word = RCP_ZERO; - switch (_map) { - case GL_UNSIGNED_IDENTITY_NV: - _map = GL_UNSIGNED_INVERT_NV; - break; - case GL_UNSIGNED_INVERT_NV: - _map = GL_UNSIGNED_IDENTITY_NV; - break; - case GL_EXPAND_NORMAL_NV: - _map = GL_UNSIGNED_INVERT_NV; - break; - case GL_EXPAND_NEGATE_NV: - _map = GL_EXPAND_NORMAL_NV; - break; - case GL_HALF_BIAS_NORMAL_NV: - _map = GL_HALF_BIAS_NEGATE_NV; - break; - case GL_HALF_BIAS_NEGATE_NV: - _map = GL_HALF_BIAS_NORMAL_NV; - break; - case GL_SIGNED_IDENTITY_NV: - _map = GL_UNSIGNED_INVERT_NV; - break; - case GL_SIGNED_NEGATE_NV: - _map = GL_EXPAND_NORMAL_NV; - break; - } - } - map = _map; - reg = _reg; - } - int map; - RegisterEnum reg; -}; - -#ifdef TEST_BIT_FIELDS - -class RegisterEnumTest { - public: - RegisterEnumTest() - { - RegisterEnum reg; - bool error = false; - - if (sizeof(reg.bits) != sizeof(reg.word)) - error = true; - - reg.word = 0; reg.bits.name = 0xFFFF; - if (RCP_SET_REGISTER_ENUM(0xFFFF, 0, 0, 0) != reg.word) - error = true; - - reg.word = 0; reg.bits.channel = 3; - if (RCP_SET_REGISTER_ENUM(0, 3, 0, 0) != reg.word) - error = true; - - reg.word = 0; reg.bits.readOnly = true; - if (RCP_SET_REGISTER_ENUM(0, 0, 1, 0) != reg.word) - error = true; - - reg.word = 0; reg.bits.finalOnly = true; - if (RCP_SET_REGISTER_ENUM(0, 0, 0, 1) != reg.word) - error = true; - - if (error) { - fprintf(stderr, "ERROR: Bit Fields were not compiled correctly in " __FILE__ "!\n"); - exit(1); - } - } -}; - -static RegisterEnumTest registerEnumTest; -#endif - -#endif diff --git a/RenderSystems/GL/src/nvparse/rc1.0_tokens.l b/RenderSystems/GL/src/nvparse/rc1.0_tokens.l deleted file mode 100644 index ac0e3244445..00000000000 --- a/RenderSystems/GL/src/nvparse/rc1.0_tokens.l +++ /dev/null @@ -1,405 +0,0 @@ -/* definitions */ -digit [0-9] -char [a-zA-Z_.] -alphanum [0-9a-zA-Z_] - -%option prefix="rc10_" -%{ /* code to be included */ - -#include -#include "rc1.0_combiners.h" -#include "_rc1.0_parser.h" - -#include "nvparse_errors.h" -#include "nvparse_externs.h" -#define YY_NO_UNPUT - -#define YY_INPUT(buf,result,max_size) \ -{ \ - result = 0; \ - while (*myin && result < max_size) \ - buf[result++] = *myin++; \ -} - -#define YY_ALWAYS_INTERACTIVE 1 - -%} -/* end of definitions */ -%% - -\/\* { - A: - switch (yyinput()) { - case '*': goto B; - case 0: errors.set("end-of-file in comment", line_number); break; - case '\n': line_number++; - default: goto A; - } - B: - switch (yyinput()) { - case '*': goto B; - case '/': break; - case 0: errors.set("end-of-file in comment", line_number); break; - case '\n': line_number++; - default: goto A; - } - } - -\/\/ { - char ch; - while ((ch = yyinput()) != '\n'); - if (ch == '\n') line_number++; - } - -\# { - char ch; - while ((ch = yyinput()) != '\n'); - if (ch == '\n') line_number++; - } - -!!RC1\.0 { /* eat header */ } - -fog\.rgb { - rc10_lval.registerEnum.word = RCP_FOG_RGB; - return(regVariable); - } -fog\.a { - rc10_lval.registerEnum.word = RCP_FOG_ALPHA; - return(regVariable); - } -fog\.b { - rc10_lval.registerEnum.word = RCP_FOG_BLUE; - return(regVariable); - } -fog { - rc10_lval.registerEnum.word = RCP_FOG; - return(regVariable); - } - -col0\.rgb { - rc10_lval.registerEnum.word = RCP_PRIMARY_COLOR_RGB; - return(regVariable); - } -col0\.a { - rc10_lval.registerEnum.word = RCP_PRIMARY_COLOR_ALPHA; - return(regVariable); - } -col0\.b { - rc10_lval.registerEnum.word = RCP_PRIMARY_COLOR_BLUE; - return(regVariable); - } -col0 { - rc10_lval.registerEnum.word = RCP_PRIMARY_COLOR; - return(regVariable); - } - -col1\.rgb { - rc10_lval.registerEnum.word = RCP_SECONDARY_COLOR_RGB; - return(regVariable); - } -col1\.a { - rc10_lval.registerEnum.word = RCP_SECONDARY_COLOR_ALPHA; - return(regVariable); - } -col1\.b { - rc10_lval.registerEnum.word = RCP_SECONDARY_COLOR_BLUE; - return(regVariable); - } -col1 { - rc10_lval.registerEnum.word = RCP_SECONDARY_COLOR; - return(regVariable); - } - -spare0\.rgb { - rc10_lval.registerEnum.word = RCP_SPARE0_RGB; - return(regVariable); - } -spare0\.a { - rc10_lval.registerEnum.word = RCP_SPARE0_ALPHA; - return(regVariable); - } -spare0\.b { - rc10_lval.registerEnum.word = RCP_SPARE0_BLUE; - return(regVariable); - } -spare0 { - rc10_lval.registerEnum.word = RCP_SPARE0; - return(regVariable); - } - -spare1\.rgb { - rc10_lval.registerEnum.word = RCP_SPARE1_RGB; - return(regVariable); - } -spare1\.a { - rc10_lval.registerEnum.word = RCP_SPARE1_ALPHA; - return(regVariable); - } -spare1\.b { - rc10_lval.registerEnum.word = RCP_SPARE1_BLUE; - return(regVariable); - } -spare1 { - rc10_lval.registerEnum.word = RCP_SPARE1; - return(regVariable); - } - -tex0\.rgb { - rc10_lval.registerEnum.word = RCP_TEXTURE0_RGB; - return(regVariable); - } -tex0\.a { - rc10_lval.registerEnum.word = RCP_TEXTURE0_ALPHA; - return(regVariable); - } -tex0\.b { - rc10_lval.registerEnum.word = RCP_TEXTURE0_BLUE; - return(regVariable); - } -tex0 { - rc10_lval.registerEnum.word = RCP_TEXTURE0; - return(regVariable); - } - -tex1\.rgb { - rc10_lval.registerEnum.word = RCP_TEXTURE1_RGB; - return(regVariable); - } -tex1\.a { - rc10_lval.registerEnum.word = RCP_TEXTURE1_ALPHA; - return(regVariable); - } -tex1\.b { - rc10_lval.registerEnum.word = RCP_TEXTURE1_BLUE; - return(regVariable); - } -tex1 { - rc10_lval.registerEnum.word = RCP_TEXTURE1; - return(regVariable); - } - -tex2\.rgb { - rc10_lval.registerEnum.word = RCP_TEXTURE2_RGB; - return(regVariable); - } -tex2\.a { - rc10_lval.registerEnum.word = RCP_TEXTURE2_ALPHA; - return(regVariable); - } -tex2\.b { - rc10_lval.registerEnum.word = RCP_TEXTURE2_BLUE; - return(regVariable); - } -tex2 { - rc10_lval.registerEnum.word = RCP_TEXTURE2; - return(regVariable); - } - -tex3\.rgb { - rc10_lval.registerEnum.word = RCP_TEXTURE3_RGB; - return(regVariable); - } -tex3\.a { - rc10_lval.registerEnum.word = RCP_TEXTURE3_ALPHA; - return(regVariable); - } -tex3\.b { - rc10_lval.registerEnum.word = RCP_TEXTURE3_BLUE; - return(regVariable); - } -tex3 { - rc10_lval.registerEnum.word = RCP_TEXTURE3; - return(regVariable); - } - -const0\.rgb { - rc10_lval.registerEnum.word = RCP_CONST_COLOR0_RGB; - return(regVariable); - } -const0\.a { - rc10_lval.registerEnum.word = RCP_CONST_COLOR0_ALPHA; - return(regVariable); - } -const0\.b { - rc10_lval.registerEnum.word = RCP_CONST_COLOR0_BLUE; - return(regVariable); - } -const0 { - rc10_lval.registerEnum.word = RCP_CONST_COLOR0; - return(constVariable); - } - -const1\.rgb { - rc10_lval.registerEnum.word = RCP_CONST_COLOR1_RGB; - return(regVariable); - } -const1\.a { - rc10_lval.registerEnum.word = RCP_CONST_COLOR1_ALPHA; - return(regVariable); - } -const1\.b { - rc10_lval.registerEnum.word = RCP_CONST_COLOR1_BLUE; - return(regVariable); - } -const1 { - rc10_lval.registerEnum.word = RCP_CONST_COLOR1; - return(constVariable); - } - -zero\.rgb { - rc10_lval.registerEnum.word = RCP_ZERO_RGB; - return(regVariable); - } -zero\.a { - rc10_lval.registerEnum.word = RCP_ZERO_ALPHA; - return(regVariable); - } -zero\.b { - rc10_lval.registerEnum.word = RCP_ZERO_BLUE; - return(regVariable); - } -zero { - rc10_lval.registerEnum.word = RCP_ZERO; - return(regVariable); - } - -one\.rgb { - rc10_lval.registerEnum.word = RCP_ONE_RGB; - return(regVariable); - } -one\.a { - rc10_lval.registerEnum.word = RCP_ONE_ALPHA; - return(regVariable); - } -one\.b { - rc10_lval.registerEnum.word = RCP_ONE_BLUE; - return(regVariable); - } -one { - rc10_lval.registerEnum.word = RCP_ONE; - return(regVariable); - } - -discard { - rc10_lval.registerEnum.word = RCP_DISCARD; - return(regVariable); - } - -out\.rgb return(fragment_rgb); -out\.a return(fragment_alpha); - -final_product { - rc10_lval.registerEnum.word = RCP_FINAL_PRODUCT; - return(final_product); - } - -color_sum { - rc10_lval.registerEnum.word = RCP_COLOR_SUM; - return(color_sum); - } - -expand return(expandString); -half_bias return(halfBiasString); -unsigned return(unsignedString); -unsigned_invert return(unsignedInvertString); -mux { - rc10_lval.ival = GL_TRUE; - return(muxString); - } - -sum { - rc10_lval.ival = GL_FALSE; - return(sumString); - } - -rgb { - rc10_lval.ival = RCP_RGB; - return(rgb_portion); - } -alpha { - rc10_lval.ival = RCP_ALPHA; - return(alpha_portion); - } - -clamp_color_sum { - rc10_lval.ival = true; - return(clamp_color_sum); - } -lerp return(lerp); - - -bias_by_negative_one_half_scale_by_two { - rc10_lval.biasScaleEnum.word = RCP_BIAS_BY_NEGATIVE_ONE_HALF_SCALE_BY_TWO; - return(bias_by_negative_one_half_scale_by_two); - } -bias_by_negative_one_half { - rc10_lval.biasScaleEnum.word = RCP_BIAS_BY_NEGATIVE_ONE_HALF; - return(bias_by_negative_one_half); - } -scale_by_one_half { - rc10_lval.biasScaleEnum.word = RCP_SCALE_BY_ONE_HALF; - return(scale_by_one_half); - } -scale_by_two { - rc10_lval.biasScaleEnum.word = RCP_SCALE_BY_TWO; - return(scale_by_two); - } -scale_by_four { - rc10_lval.biasScaleEnum.word = RCP_SCALE_BY_FOUR; - return(scale_by_four); - } - -[+-]?[0-9]+\.[0-9]* { - rc10_lval.fval = (float)atof(yytext); - return(floatValue); - } - -[+-]?[0-9]*\.[0-9]+ { - rc10_lval.fval = (float)atof(yytext); - return(floatValue); - } - -[+-]?[0-9]+ { - rc10_lval.fval = (float)atof(yytext); - return(floatValue); - } - -\{ return(openBracket); -\} return(closeBracket); -\( return(openParen); -\) return(closeParen); -; return(semicolon); -, return(comma); -\. return(dot); -\* return(times); -- return(minus); -\+ return(plus); -= return(equals); - -\r*\n { - line_number++; - } - -[ \t]+ {} - -{alphanum}+ { - errors.set("unrecognized token", line_number); - } - - -%% - -bool rc10_init_more(); - -bool rc10_init(char* inputString) -{ - myin = inputString; - return rc10_init_more(); -} - -#ifndef rc10_wrap -int rc10_wrap(void) -{ - return(1); -} -#endif diff --git a/RenderSystems/GL/src/nvparse/ts1.0_grammar.y b/RenderSystems/GL/src/nvparse/ts1.0_grammar.y deleted file mode 100644 index 88d328cd1e4..00000000000 --- a/RenderSystems/GL/src/nvparse/ts1.0_grammar.y +++ /dev/null @@ -1,304 +0,0 @@ -%start WholeEnchilada -%name-prefix "ts10_" -%{ -void yyerror(const char* s); -int yylex ( void ); - -#ifdef _WIN32 -# include -#endif -#include -#include -#include "ts1.0_inst.h" -#include "ts1.0_inst_list.h" -#include "nvparse_errors.h" -#include "nvparse_externs.h" - -%} -%union { - float fval; - InstPtr inst; - InstListPtr instList; - MappedVariablePtr variable; -} - -%token floatValue gequal less texVariable expandString -%token openParen closeParen semicolon comma -%token nop -%token texture_1d -%token texture_2d -%token texture_rectangle -%token texture_3d -%token texture_cube_map -%token cull_fragment -%token pass_through -%token offset_2d_scale -%token offset_2d -%token offset_rectangle_scale -%token offset_rectangle -%token dependent_ar -%token dependent_gb -%token dot_product_2d_1of2 -%token dot_product_2d_2of2 -%token dot_product_rectangle_1of2 -%token dot_product_rectangle_2of2 -%token dot_product_depth_replace_1of2 -%token dot_product_depth_replace_2of2 -%token dot_product_3d_1of3 -%token dot_product_3d_2of3 -%token dot_product_3d_3of3 -%token dot_product_cube_map_1of3 -%token dot_product_cube_map_2of3 -%token dot_product_cube_map_3of3 -%token dot_product_reflect_cube_map_eye_from_qs_1of3 -%token dot_product_reflect_cube_map_eye_from_qs_2of3 -%token dot_product_reflect_cube_map_eye_from_qs_3of3 -%token dot_product_reflect_cube_map_const_eye_1of3 -%token dot_product_reflect_cube_map_const_eye_2of3 -%token dot_product_reflect_cube_map_const_eye_3of3 -%token dot_product_cube_map_and_reflect_cube_map_eye_from_qs_1of3 -%token dot_product_cube_map_and_reflect_cube_map_eye_from_qs_2of3 -%token dot_product_cube_map_and_reflect_cube_map_eye_from_qs_3of3 -%token dot_product_cube_map_and_reflect_cube_map_const_eye_1of3 -%token dot_product_cube_map_and_reflect_cube_map_const_eye_2of3 -%token dot_product_cube_map_and_reflect_cube_map_const_eye_3of3 - -%type WholeEnchilada InstListDesc -%type InstDesc -%type MappedVariableDesc -%type CondDesc - -%% - -WholeEnchilada: InstListDesc - { - $1->Validate(); - $1->Invoke(); - delete $1; - } - ; - -InstListDesc: InstListDesc InstDesc semicolon - { - *($1) += $2; - delete $2; - $$ = $1; - } - | InstDesc semicolon - { - InstListPtr instList = new InstList; - *instList += $1; - delete $1; - $$ = instList; - } - ; - - -MappedVariableDesc: expandString openParen texVariable closeParen - { - $$ = new MappedVariable; - $$->var = $3; - $$->expand = true; - } - | texVariable - { - $$ = new MappedVariable; - $$->var = $1; - $$->expand = false; - } - ; - -InstDesc : nop openParen closeParen - { - $$ = new Inst(TSP_NOP); - } - | texture_1d openParen closeParen - { - $$ = new Inst(TSP_TEXTURE_1D); - } - | texture_2d openParen closeParen - { - $$ = new Inst(TSP_TEXTURE_2D); - } - | texture_rectangle openParen closeParen - { - $$ = new Inst(TSP_TEXTURE_RECTANGLE); - } - | texture_3d openParen closeParen - { - $$ = new Inst(TSP_TEXTURE_3D); - } - | texture_cube_map openParen closeParen - { - $$ = new Inst(TSP_TEXTURE_CUBE_MAP); - } - | cull_fragment openParen CondDesc comma CondDesc comma CondDesc comma CondDesc closeParen - { - $$ = new Inst(TSP_CULL_FRAGMENT, $3, $5, $7, $9); - } - | pass_through openParen closeParen - { - $$ = new Inst(TSP_PASS_THROUGH); - } - | offset_2d_scale openParen texVariable comma floatValue comma floatValue comma floatValue comma floatValue comma floatValue comma floatValue closeParen - { - $$ = new Inst(TSP_OFFSET_2D_SCALE, $3, $5, $7, $9, $11, $13, $15); - } - | offset_2d openParen texVariable comma floatValue comma floatValue comma floatValue comma floatValue closeParen - { - $$ = new Inst(TSP_OFFSET_2D, $3, $5, $7, $9, $11); - } - | offset_rectangle_scale openParen texVariable comma floatValue comma floatValue comma floatValue comma floatValue comma floatValue comma floatValue closeParen - { - $$ = new Inst(TSP_OFFSET_RECTANGLE_SCALE, $3, $5, $7, $9, $11, $13, $15); - } - | offset_rectangle openParen texVariable comma floatValue comma floatValue comma floatValue comma floatValue closeParen - { - $$ = new Inst(TSP_OFFSET_RECTANGLE, $3, $5, $7, $9, $11); - } - | dependent_ar openParen texVariable closeParen - { - $$ = new Inst(TSP_DEPENDENT_AR, $3); - } - | dependent_gb openParen texVariable closeParen - { - $$ = new Inst(TSP_DEPENDENT_GB, $3); - } - | dot_product_2d_1of2 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_2D_1_OF_2, $3); - delete $3; - } - | dot_product_2d_2of2 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_2D_2_OF_2, $3); - delete $3; - } - | dot_product_rectangle_1of2 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_RECTANGLE_1_OF_2, $3); - delete $3; - } - | dot_product_rectangle_2of2 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_RECTANGLE_2_OF_2, $3); - delete $3; - } - | dot_product_depth_replace_1of2 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_DEPTH_REPLACE_1_OF_2, $3); - delete $3; - } - | dot_product_depth_replace_2of2 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_DEPTH_REPLACE_2_OF_2, $3); - delete $3; - } - | dot_product_3d_1of3 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_3D_1_OF_3, $3); - delete $3; - } - | dot_product_3d_2of3 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_3D_2_OF_3, $3); - delete $3; - } - | dot_product_3d_3of3 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_3D_3_OF_3, $3); - delete $3; - } - | dot_product_cube_map_1of3 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_CUBE_MAP_1_OF_3, $3); - delete $3; - } - | dot_product_cube_map_2of3 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_CUBE_MAP_2_OF_3, $3); - delete $3; - } - | dot_product_cube_map_3of3 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_CUBE_MAP_3_OF_3, $3); - delete $3; - } - | dot_product_reflect_cube_map_eye_from_qs_1of3 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_EYE_FROM_QS_1_OF_3, $3); - delete $3; - } - | dot_product_reflect_cube_map_eye_from_qs_2of3 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_EYE_FROM_QS_2_OF_3, $3); - delete $3; - } - | dot_product_reflect_cube_map_eye_from_qs_3of3 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_EYE_FROM_QS_3_OF_3, $3); - delete $3; - } - | dot_product_reflect_cube_map_const_eye_1of3 openParen MappedVariableDesc comma floatValue comma floatValue comma floatValue closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_CONST_EYE_1_OF_3, $3, $5, $7, $9); - delete $3; - } - | dot_product_reflect_cube_map_const_eye_2of3 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_CONST_EYE_2_OF_3, $3); - delete $3; - } - | dot_product_reflect_cube_map_const_eye_3of3 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_CONST_EYE_3_OF_3, $3); - delete $3; - } - | dot_product_cube_map_and_reflect_cube_map_eye_from_qs_1of3 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_EYE_FROM_QS_1_OF_3, $3); - delete $3; - } - | dot_product_cube_map_and_reflect_cube_map_eye_from_qs_2of3 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_EYE_FROM_QS_2_OF_3, $3); - delete $3; - } - | dot_product_cube_map_and_reflect_cube_map_eye_from_qs_3of3 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_EYE_FROM_QS_3_OF_3, $3); - delete $3; - } - | dot_product_cube_map_and_reflect_cube_map_const_eye_1of3 openParen MappedVariableDesc comma floatValue comma floatValue comma floatValue closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_CONST_EYE_1_OF_3, $3, $5, $7, $9); - delete $3; - } - | dot_product_cube_map_and_reflect_cube_map_const_eye_2of3 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_CONST_EYE_2_OF_3, $3); - delete $3; - } - | dot_product_cube_map_and_reflect_cube_map_const_eye_3of3 openParen MappedVariableDesc closeParen - { - $$ = new Inst(TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_CONST_EYE_3_OF_3, $3); - delete $3; - } - ; - -CondDesc : gequal - { - $$ = $1; - } - | less - { - $$ = $1; - } - ; - - -%% -void yyerror(const char* s) -{ - errors.set("unrecognized token"); -} diff --git a/RenderSystems/GL/src/nvparse/ts1.0_inst.cpp b/RenderSystems/GL/src/nvparse/ts1.0_inst.cpp deleted file mode 100644 index a43d69e1d3b..00000000000 --- a/RenderSystems/GL/src/nvparse/ts1.0_inst.cpp +++ /dev/null @@ -1,293 +0,0 @@ -#include "ts1.0_inst.h" - -Inst::Inst(int inst, float arg0, float arg1, float arg2, float arg3, float arg4, float arg5, float arg6) -{ - opcode.word = inst; - expand = 0; - args[0] = arg0; - args[1] = arg1; - args[2] = arg2; - args[3] = arg3; - args[4] = arg4; - args[5] = arg5; - args[6] = arg6; -} - -Inst::Inst(int inst, MappedVariablePtr arg0, float arg1, float arg2, float arg3, float arg4, float arg5, float arg6) -{ - opcode.word = inst; - expand = arg0->expand; - args[0] = arg0->var; - args[1] = arg1; - args[2] = arg2; - args[3] = arg3; - args[4] = arg4; - args[5] = arg5; - args[6] = arg6; -} - -void Inst::Invoke() -{ - switch(opcode.word) { - case TSP_NOP: - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_NONE); - break; - case TSP_TEXTURE_1D: - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_TEXTURE_1D); - break; - case TSP_TEXTURE_2D: - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_TEXTURE_2D); - break; -#if defined(GL_EXT_texture_rectangle) - case TSP_TEXTURE_RECTANGLE: - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_TEXTURE_RECTANGLE_EXT); - break; -#elif defined(GL_NV_texture_rectangle) - case TSP_TEXTURE_RECTANGLE: - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_TEXTURE_RECTANGLE_NV); - break; -#else - case TSP_TEXTURE_RECTANGLE: - break; -#endif - case TSP_TEXTURE_3D: - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_TEXTURE_3D); - break; - case TSP_TEXTURE_CUBE_MAP: - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_TEXTURE_CUBE_MAP_ARB); - break; - case TSP_CULL_FRAGMENT: - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_CULL_FRAGMENT_NV); - glTexEnvfv(GL_TEXTURE_SHADER_NV, GL_CULL_MODES_NV, &args[0]); - break; - case TSP_PASS_THROUGH: - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_PASS_THROUGH_NV); - break; - case TSP_OFFSET_2D_SCALE: - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_OFFSET_TEXTURE_SCALE_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - glTexEnvfv(GL_TEXTURE_SHADER_NV, GL_OFFSET_TEXTURE_MATRIX_NV, &args[1]); - glTexEnvf(GL_TEXTURE_SHADER_NV, GL_OFFSET_TEXTURE_SCALE_NV, args[5]); - glTexEnvf(GL_TEXTURE_SHADER_NV, GL_OFFSET_TEXTURE_BIAS_NV, args[6]); - break; - case TSP_OFFSET_2D: - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_OFFSET_TEXTURE_2D_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - glTexEnvfv(GL_TEXTURE_SHADER_NV, GL_OFFSET_TEXTURE_MATRIX_NV, &args[1]); - break; - case TSP_OFFSET_RECTANGLE_SCALE: - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_OFFSET_TEXTURE_RECTANGLE_SCALE_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - glTexEnvfv(GL_TEXTURE_SHADER_NV, GL_OFFSET_TEXTURE_MATRIX_NV, &args[1]); - glTexEnvf(GL_TEXTURE_SHADER_NV, GL_OFFSET_TEXTURE_SCALE_NV, args[5]); - glTexEnvf(GL_TEXTURE_SHADER_NV, GL_OFFSET_TEXTURE_BIAS_NV, args[6]); - break; - case TSP_OFFSET_RECTANGLE: - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_OFFSET_TEXTURE_RECTANGLE_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - glTexEnvfv(GL_TEXTURE_SHADER_NV, GL_OFFSET_TEXTURE_MATRIX_NV, &args[1]); - break; - case TSP_DEPENDENT_AR: - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DEPENDENT_AR_TEXTURE_2D_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DEPENDENT_GB: - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DEPENDENT_GB_TEXTURE_2D_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_2D_1_OF_2: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_2D_2_OF_2: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_TEXTURE_2D_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_RECTANGLE_1_OF_2: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_RECTANGLE_2_OF_2: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_TEXTURE_RECTANGLE_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_DEPTH_REPLACE_1_OF_2: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_DEPTH_REPLACE_2_OF_2: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_DEPTH_REPLACE_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_3D_1_OF_3: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_3D_2_OF_3: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_3D_3_OF_3: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_TEXTURE_2D_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_CUBE_MAP_1_OF_3: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_CUBE_MAP_2_OF_3: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_CUBE_MAP_3_OF_3: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_TEXTURE_CUBE_MAP_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_EYE_FROM_QS_1_OF_3: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_EYE_FROM_QS_2_OF_3: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_EYE_FROM_QS_3_OF_3: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_REFLECT_CUBE_MAP_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_CONST_EYE_1_OF_3: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_CONST_EYE_2_OF_3: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_CONST_EYE_3_OF_3: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_CONST_EYE_REFLECT_CUBE_MAP_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - glTexEnvfv(GL_TEXTURE_SHADER_NV, GL_CONST_EYE_NV, &args[1]); - break; - case TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_EYE_FROM_QS_1_OF_3: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_EYE_FROM_QS_2_OF_3: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_DIFFUSE_CUBE_MAP_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_EYE_FROM_QS_3_OF_3: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_REFLECT_CUBE_MAP_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_CONST_EYE_1_OF_3: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_CONST_EYE_2_OF_3: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_DIFFUSE_CUBE_MAP_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - break; - case TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_CONST_EYE_3_OF_3: - if (expand) - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_EXPAND_NORMAL_NV); - else - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV, GL_UNSIGNED_IDENTITY_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_SHADER_OPERATION_NV, GL_DOT_PRODUCT_CONST_EYE_REFLECT_CUBE_MAP_NV); - glTexEnvi(GL_TEXTURE_SHADER_NV, GL_PREVIOUS_TEXTURE_INPUT_NV, GL_TEXTURE0_ARB + (int)args[0]); - glTexEnvfv(GL_TEXTURE_SHADER_NV, GL_CONST_EYE_NV, &args[1]); - break; - } -} diff --git a/RenderSystems/GL/src/nvparse/ts1.0_inst.h b/RenderSystems/GL/src/nvparse/ts1.0_inst.h deleted file mode 100644 index 02d7c43418a..00000000000 --- a/RenderSystems/GL/src/nvparse/ts1.0_inst.h +++ /dev/null @@ -1,143 +0,0 @@ -#ifndef _INST_H -#define _INST_H - -#define TSP_MAX_ARGS 7 -#define TSP_NUM_TEXTURE_UNITS 4 -#ifdef _WIN32 -#include -#endif -#include -#ifdef _WIN32 -# define BYTE_ORDER !BIG_ENDIAN -#endif -#include - -typedef union _InstructionEnum { - struct { -#if BYTE_ORDER != BIG_ENDIAN - unsigned int instruction :10; // instruction id - unsigned int stage : 4; // stage number - unsigned int dependent : 1; // dependent operation - unsigned int noOutput : 1; // no RGBA output -#else - unsigned int noOutput : 1; - unsigned int dependent : 1; - unsigned int stage : 4; - unsigned int instruction :10; -#endif - } bits; - unsigned int word; -} InstructionEnum; - -// WARNING: Don't monkey with the above structure or this macro -// unless you're absolutely sure of what you're doing! -// This constant allocation makes validation *much* cleaner. -#define TSP_SET_INSTRUCTION_ENUM(inst, st, dep, noout) \ - ((noout << 15) | (dep << 14) | (st << 10) | inst) - -#define TSP_NOP TSP_SET_INSTRUCTION_ENUM(0, 0, 0, 1) -#define TSP_TEXTURE_1D TSP_SET_INSTRUCTION_ENUM(1, 0, 0, 0) -#define TSP_TEXTURE_2D TSP_SET_INSTRUCTION_ENUM(2, 0, 0, 0) -#define TSP_TEXTURE_RECTANGLE TSP_SET_INSTRUCTION_ENUM(3, 0, 0, 0) -#define TSP_TEXTURE_3D TSP_SET_INSTRUCTION_ENUM(4, 0, 0, 0) -#define TSP_TEXTURE_CUBE_MAP TSP_SET_INSTRUCTION_ENUM(5, 0, 0, 0) -#define TSP_CULL_FRAGMENT TSP_SET_INSTRUCTION_ENUM(6, 0, 0, 1) -#define TSP_PASS_THROUGH TSP_SET_INSTRUCTION_ENUM(7, 0, 0, 0) -#define TSP_DEPENDENT_AR TSP_SET_INSTRUCTION_ENUM(8, 0, 1, 0) -#define TSP_DEPENDENT_GB TSP_SET_INSTRUCTION_ENUM(9, 0, 1, 0) -#define TSP_OFFSET_2D TSP_SET_INSTRUCTION_ENUM(10, 0, 1, 0) -#define TSP_OFFSET_2D_SCALE TSP_SET_INSTRUCTION_ENUM(11, 0, 1, 0) -#define TSP_OFFSET_RECTANGLE TSP_SET_INSTRUCTION_ENUM(12, 0, 1, 0) -#define TSP_OFFSET_RECTANGLE_SCALE TSP_SET_INSTRUCTION_ENUM(13, 0, 1, 0) - -#define TSP_DOT_PRODUCT_2D_1_OF_2 TSP_SET_INSTRUCTION_ENUM(14, 0, 1, 1) -#define TSP_DOT_PRODUCT_2D_2_OF_2 TSP_SET_INSTRUCTION_ENUM(14, 1, 1, 0) - -#define TSP_DOT_PRODUCT_RECTANGLE_1_OF_2 TSP_SET_INSTRUCTION_ENUM(15, 0, 1, 1) -#define TSP_DOT_PRODUCT_RECTANGLE_2_OF_2 TSP_SET_INSTRUCTION_ENUM(15, 1, 1, 0) - -#define TSP_DOT_PRODUCT_DEPTH_REPLACE_1_OF_2 TSP_SET_INSTRUCTION_ENUM(16, 0, 1, 1) -#define TSP_DOT_PRODUCT_DEPTH_REPLACE_2_OF_2 TSP_SET_INSTRUCTION_ENUM(16, 1, 1, 0) - -#define TSP_DOT_PRODUCT_3D_1_OF_3 TSP_SET_INSTRUCTION_ENUM(17, 0, 1, 1) -#define TSP_DOT_PRODUCT_3D_2_OF_3 TSP_SET_INSTRUCTION_ENUM(17, 1, 1, 1) -#define TSP_DOT_PRODUCT_3D_3_OF_3 TSP_SET_INSTRUCTION_ENUM(17, 2, 1, 0) - -#define TSP_DOT_PRODUCT_CUBE_MAP_1_OF_3 TSP_SET_INSTRUCTION_ENUM(18, 0, 1, 1) -#define TSP_DOT_PRODUCT_CUBE_MAP_2_OF_3 TSP_SET_INSTRUCTION_ENUM(18, 1, 1, 1) -#define TSP_DOT_PRODUCT_CUBE_MAP_3_OF_3 TSP_SET_INSTRUCTION_ENUM(18, 2, 1, 0) - -#define TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_EYE_FROM_QS_1_OF_3 TSP_SET_INSTRUCTION_ENUM(19, 0, 1, 1) -#define TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_EYE_FROM_QS_2_OF_3 TSP_SET_INSTRUCTION_ENUM(19, 1, 1, 1) -#define TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_EYE_FROM_QS_3_OF_3 TSP_SET_INSTRUCTION_ENUM(19, 2, 1, 0) - -#define TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_CONST_EYE_1_OF_3 TSP_SET_INSTRUCTION_ENUM(20, 0, 1, 1) -#define TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_CONST_EYE_2_OF_3 TSP_SET_INSTRUCTION_ENUM(20, 1, 1, 1) -#define TSP_DOT_PRODUCT_REFLECT_CUBE_MAP_CONST_EYE_3_OF_3 TSP_SET_INSTRUCTION_ENUM(20, 2, 1, 0) - -#define TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_EYE_FROM_QS_1_OF_3 TSP_SET_INSTRUCTION_ENUM(21, 0, 1, 1) -#define TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_EYE_FROM_QS_2_OF_3 TSP_SET_INSTRUCTION_ENUM(21, 1, 1, 0) -#define TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_EYE_FROM_QS_3_OF_3 TSP_SET_INSTRUCTION_ENUM(21, 2, 1, 0) - -#define TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_CONST_EYE_1_OF_3 TSP_SET_INSTRUCTION_ENUM(22, 0, 1, 1) -#define TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_CONST_EYE_2_OF_3 TSP_SET_INSTRUCTION_ENUM(22, 1, 1, 0) -#define TSP_DOT_PRODUCT_CUBE_MAP_AND_REFLECT_CUBE_MAP_CONST_EYE_3_OF_3 TSP_SET_INSTRUCTION_ENUM(22, 2, 1, 0) - -typedef struct _MappedVariable { - float var; - int expand; -} MappedVariable, *MappedVariablePtr; - -typedef class Inst { -public: - Inst(int inst, float arg0 = 0., float arg1 = 0., float arg2 = 0., float arg3 = 0., float arg4 = 0., float arg5 = 0., float arg6 = 0.); - Inst(int inst, MappedVariablePtr arg0, float arg1 = 0., float arg2 = 0., float arg3 = 0., float arg4 = 0., float arg5 = 0., float arg6 = 0.); - void Invoke(); - InstructionEnum opcode; - float args[TSP_MAX_ARGS]; -private: - int expand; -} Inst, *InstPtr; - -#ifdef TEST_BIT_FIELDS - -#include - -class InstructionEnumTest { - public: - InstructionEnumTest() - { - InstructionEnum inst; - bool error = false; - - if (sizeof(inst.bits) != sizeof(inst.word)) - error = true; - - inst.word = 0; inst.bits.instruction = 0x3FF; - if (TSP_SET_INSTRUCTION_ENUM(0x3FF, 0, 0, 0) != inst.word) - error = true; - - inst.word = 0; inst.bits.stage = 0x0F; - if (TSP_SET_INSTRUCTION_ENUM(0, 0x0F, 0, 0) != inst.word) - error = true; - - inst.word = 0; inst.bits.dependent = true; - if (TSP_SET_INSTRUCTION_ENUM(0, 0, 1, 0) != inst.word) - error = true; - - inst.word = 0; inst.bits.noOutput = true; - if (TSP_SET_INSTRUCTION_ENUM(0, 0, 0, 1) != inst.word) - error = true; - - if (error) { - fprintf(stderr, "ERROR: Bit Fields were not compiled correctly in " __FILE__ "!\n"); - exit(1); - } - } -}; - -static InstructionEnumTest instructionEnumTest; - -#endif /* TEST_BIT_FIELDS */ - -#endif diff --git a/RenderSystems/GL/src/nvparse/ts1.0_inst_list.cpp b/RenderSystems/GL/src/nvparse/ts1.0_inst_list.cpp deleted file mode 100644 index ded9825ba95..00000000000 --- a/RenderSystems/GL/src/nvparse/ts1.0_inst_list.cpp +++ /dev/null @@ -1,135 +0,0 @@ -#include "ts1.0_inst_list.h" -#include -#include -#include - -#include "nvparse_errors.h" -#include "nvparse_externs.h" - -const int instListInc = 4; - -InstList::InstList() -{ - size = 0; - max = instListInc; - list = (InstPtr)malloc(sizeof(Inst) * max); -} - -InstList::~InstList() -{ - free(list); -} - -int InstList::Size() -{ - return size; -} - -InstList& InstList::operator+=(InstPtr t) -{ - if (size == max) { - /* Extend list size by instListInc amount */ - max += instListInc; - list = (InstPtr)realloc(list, sizeof(Inst) * max); - } - list[size++] = *t; - return *this; -} - -void InstList::Invoke() -{ - int i; - GLint activeTex = 0; - glGetIntegerv(GL_ACTIVE_TEXTURE, &activeTex); - - for (i = 0; i < size; i++) { - // set active texture - glActiveTextureARB(GL_TEXTURE0_ARB + i); - list[i].Invoke(); - } - - glActiveTextureARB(activeTex); -} - -void InstList::Validate() -{ - if (size > TSP_NUM_TEXTURE_UNITS) - errors.set("too many instructions"); - int i; - for (i = 0; i < size; i++) { - int stage = list[i].opcode.bits.stage; - if (stage > i) - errors.set("prior stage missing"); - if (list[i].opcode.bits.instruction != list[i - stage].opcode.bits.instruction) - errors.set("stage mismatch"); - if (list[i].opcode.bits.dependent) { - int previousTexture = (int)list[i].args[0]; - if (previousTexture >= i - stage) - errors.set("invalid texture reference"); - if (list[previousTexture].opcode.bits.noOutput) - errors.set("no output on referenced texture"); - } - } - - // Assign remaining undesignated texture units to nop - for (; i < TSP_NUM_TEXTURE_UNITS; i++) { - InstPtr nopInst = new Inst(TSP_NOP); - *this += nopInst; - delete nopInst; - } -} - -bool is_ts10(const char * s) -{ - return ! strncmp(s, "!!TS1.0", 7); -} - -bool ts10_init_more() -{ - static bool tsinit = false; - if (tsinit == false ) - { - /* - if(! glh_init_extensions( "GL_NV_texture_shader " "GL_ARB_multitexture " )) - { - errors.set("unable to initialize GL_NV_texture_shader\n"); - return false; - } - else - { - */ - tsinit = true; - /* - } - */ - } - errors.reset(); - line_number = 1; - return true; -} - -/* - - else if(!strncmp(instring, "!!TS1.0", 7)) - { - if (tsinit == 0 ) - { - if(! glh_init_extensions( "GL_NV_texture_shader " "GL_ARB_multitexture " )) - { - errors.set("unable to initialize GL_NV_texture_shader\n"); - free(instring); - return; - } - else - { - tsinit = 1; - } - } - errors.reset(); - line_number = 1; - ts10_init(instring+7); - ts10_parse(); - } - - - */ diff --git a/RenderSystems/GL/src/nvparse/ts1.0_inst_list.h b/RenderSystems/GL/src/nvparse/ts1.0_inst_list.h deleted file mode 100644 index e94cb8c191b..00000000000 --- a/RenderSystems/GL/src/nvparse/ts1.0_inst_list.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef _InstList_h -#define _InstList_h - -#include "ts1.0_inst.h" - -typedef class InstList { -public: - InstList(); - ~InstList(); - int Size(); - InstList& operator+=(InstPtr t); - void Validate(); - void Invoke(); -private: - InstPtr list; - int size; - int max; -} *InstListPtr; - -#endif diff --git a/RenderSystems/GL/src/nvparse/ts1.0_tokens.l b/RenderSystems/GL/src/nvparse/ts1.0_tokens.l deleted file mode 100644 index 77145b7698f..00000000000 --- a/RenderSystems/GL/src/nvparse/ts1.0_tokens.l +++ /dev/null @@ -1,184 +0,0 @@ -/* definitions */ -digit [0-9] -char [a-zA-Z_.] -alphanum [0-9a-zA-Z_] -%option prefix="ts10_" -%{ /* code to be included */ -#include -#include "ts1.0_inst.h" -#include "ts1.0_inst_list.h" -#include "_ts1.0_parser.h" -#ifdef _WIN32 -# include -#endif -#include "nvparse_errors.h" -#include "nvparse_externs.h" -#define YY_NO_UNPUT - -#define YY_INPUT(buf,result,max_size) \ -{ \ - int c = *myin++; \ - result = (c == 0) ? YY_NULL : (buf[0] = c, 1); \ -} - -#define YY_ALWAYS_INTERACTIVE 1 - -%} -/* end of definitions */ -%% - -\/\* { - A: - switch (yyinput()) { - case '*': goto B; - case 0: errors.set("end-of-file in comment", line_number); break; - case '\n': line_number++; - default: goto A; - } - B: - switch (yyinput()) { - case '*': goto B; - case '/': break; - case 0: errors.set("end-of-file in comment", line_number); break; - case '\n': line_number++; - default: goto A; - } - } - -\/\/ { - char ch; - while ((ch = yyinput()) != '\n'); - if (ch == '\n') line_number++; - } - -\# { - char ch; - while ((ch = yyinput()) != '\n'); - if (ch == '\n') line_number++; - } - -\( return(openParen); -\) return(closeParen); -; return(semicolon); -, return(comma); - -!!TS1\.0 { /* eat header */ } - -tex0 { - ts10_lval.fval = (float)0; - return(texVariable); - } - -tex1 { - ts10_lval.fval = (float)1; - return(texVariable); - } - -tex2 { - ts10_lval.fval = (float)2; - return(texVariable); - } - -expand return(expandString); - -GEQUAL_TO_ZERO { - ts10_lval.fval = (float)GL_GEQUAL; - return (gequal); - } - -LESS_THAN_ZERO { - ts10_lval.fval = (float)GL_LESS; - return(less); - } - -nop return(nop); -texture_1d return(texture_1d); -texture_2d return(texture_2d); -texture_rectangle return(texture_rectangle); -texture_3d return(texture_3d); -texture_cube_map return(texture_cube_map); -cull_fragment return(cull_fragment); -pass_through return(pass_through); -offset_2d_scale return(offset_2d_scale); -offset_2d return(offset_2d); -offset_rectangle_scale return(offset_rectangle_scale); -offset_rectangle return(offset_rectangle); -dependent_ar return(dependent_ar); -dependent_gb return(dependent_gb); - -dot_product_2d_1of2 return(dot_product_2d_1of2); -dot_product_2d_2of2 return(dot_product_2d_2of2); - -dot_product_rectangle_1of2 return(dot_product_rectangle_1of2); -dot_product_rectangle_2of2 return(dot_product_rectangle_2of2); - -dot_product_depth_replace_1of2 return(dot_product_depth_replace_1of2); -dot_product_depth_replace_2of2 return(dot_product_depth_replace_2of2); - -dot_product_3d_1of3 return(dot_product_3d_1of3); -dot_product_3d_2of3 return(dot_product_3d_2of3); -dot_product_3d_3of3 return(dot_product_3d_3of3); - -dot_product_cube_map_1of3 return(dot_product_cube_map_1of3); -dot_product_cube_map_2of3 return(dot_product_cube_map_2of3); -dot_product_cube_map_3of3 return(dot_product_cube_map_3of3); - -dot_product_reflect_cube_map_eye_from_qs_1of3 return(dot_product_reflect_cube_map_eye_from_qs_1of3); -dot_product_reflect_cube_map_eye_from_qs_2of3 return(dot_product_reflect_cube_map_eye_from_qs_2of3); -dot_product_reflect_cube_map_eye_from_qs_3of3 return(dot_product_reflect_cube_map_eye_from_qs_3of3); - -dot_product_reflect_cube_map_const_eye_1of3 return(dot_product_reflect_cube_map_const_eye_1of3); -dot_product_reflect_cube_map_const_eye_2of3 return(dot_product_reflect_cube_map_const_eye_2of3); -dot_product_reflect_cube_map_const_eye_3of3 return(dot_product_reflect_cube_map_const_eye_3of3); - -dot_product_cube_map_and_reflect_cube_map_eye_from_qs_1of3 return(dot_product_cube_map_and_reflect_cube_map_eye_from_qs_1of3); -dot_product_cube_map_and_reflect_cube_map_eye_from_qs_2of3 return(dot_product_cube_map_and_reflect_cube_map_eye_from_qs_2of3); -dot_product_cube_map_and_reflect_cube_map_eye_from_qs_3of3 return(dot_product_cube_map_and_reflect_cube_map_eye_from_qs_3of3); - -dot_product_cube_map_and_reflect_cube_map_const_eye_1of3 return(dot_product_cube_map_and_reflect_cube_map_const_eye_1of3); -dot_product_cube_map_and_reflect_cube_map_const_eye_2of3 return(dot_product_cube_map_and_reflect_cube_map_const_eye_2of3); -dot_product_cube_map_and_reflect_cube_map_const_eye_3of3 return(dot_product_cube_map_and_reflect_cube_map_const_eye_3of3); - -[+-]?[0-9]+\.[0-9]* { - ts10_lval.fval = (float)atof(yytext); - return(floatValue); - } - -[+-]?[0-9]*\.[0-9]+ { - ts10_lval.fval = (float)atof(yytext); - return(floatValue); - } - -[+-]?[0-9]+ { - ts10_lval.fval = (float)atof(yytext); - return(floatValue); - } - -\r*\n { - line_number++; - } - -[ \t]+ {} - -{alphanum}+ { - errors.set("unrecognized token", line_number); - } - - -%% - -bool ts10_init_more(); - -bool ts10_init(char* inputString) -{ - myin = inputString; - return ts10_init_more(); -} - - -#ifndef ts10_wrap -int ts10_wrap(void) -{ - return(1); -} -#endif diff --git a/RenderSystems/GL/src/nvparse/vcp1.0_impl.cpp b/RenderSystems/GL/src/nvparse/vcp1.0_impl.cpp deleted file mode 100644 index 8131acde138..00000000000 --- a/RenderSystems/GL/src/nvparse/vcp1.0_impl.cpp +++ /dev/null @@ -1,354 +0,0 @@ -#include "nvparse_errors.h" -#include "nvparse_externs.h" -#include -#include -#include - -#ifndef _WIN32 -# define strnicmp strncasecmp -#endif - -using namespace std; - -namespace -{ - void ParseVertexProgramConstants( GLenum target, char *instring); - GLuint LookupTrackMatrix(char *matrixName); - GLuint LookupTrackMatrixTransform(char *matrixTransformName); -} - -bool is_vcp10(const char * s) -{ - return ! strncmp(s, "!!VCP1.0", 8); -} - -bool vcp10_init(char * s) -{ - static int vpinit = 0; - - if (vpinit == 0 ) - { - /* - if(! glh_init_extensions("GL_NV_vertex_program")) - { - errors.set("unable to initialize GL_NV_vertex_program"); - return false; - } - else - { - */ - vpinit = 1; - /* - } - */ - } - - errors.reset(); - line_number = 1; - - myin = s; - - return true; -} - -int vcp10_parse() -{ - // parse the constant declarations, setting their values in the GL. - ParseVertexProgramConstants( GL_VERTEX_PROGRAM_NV, myin); - return 0; -} - - -namespace -{ - - //.----------------------------------------------------------------------------. - //| Function : ParseVertexProgramConstants | - //| Description: Parse and set VP1.0 constant memory based on const | - //| directives. | - //| | - //| Format : c[XX] = (x, y, z, w); # where XXX is an integer 0-95. | - //| : c[XX] = TRACK(matrix, transform); # track a matrix | - //.----------------------------------------------------------------------------. - void ParseVertexProgramConstants(GLenum target, char *instring) - { - // don't overwrite the original string. - char *tmpstring = new char[strlen(instring)+1]; - strcpy(tmpstring, instring); - - char lineSeparator[] = "\n"; - //char wordSeparator[] = " \t"; - char error[256]; - char dummy[256]; - char *token; - - //iterate over the lines in the string - token = strtok(tmpstring, lineSeparator); - - // we assume the first line is the "!!VCP1.0 line". - if (token != NULL) - { - token = strtok(NULL, lineSeparator); - } - - int iLineCount = 1; // skip first line - - while (token != NULL) - { - iLineCount++; - - // if the first non-whitespace character is a #, this is a comment. Skip. - if (!sscanf(token, " #%s", dummy)) - { // not a comment. Is it a constant? - - // strip whitespace from the beginning of the string - int i; - for (i = 0; i < (int)strlen(token) && isspace(token[i]); i++); - token += i; - - if (strlen(token) > 0 && // this is not a blank line and - !strnicmp(token, "c[", 2)) // the first word is of the form "c[xx]", so its a constant. - { - int iConstID; - int iNumValuesAssigned; - char c[6]; - - iNumValuesAssigned = sscanf(token, " %c [ %d ] = %s ", &c[0], &iConstID, dummy); - - if (3 != iNumValuesAssigned || toupper(c[0]) != 'C') - { // error in constant directive. - sprintf(error, "error at line %d \n\"%s\"\n", iLineCount, token); - errors.set(error); - } - else if (!strnicmp(dummy, "track", 5)) - { // this is a TrackMatrix directive - char matrixName[256], matrixTransformName[256]; - - // the series of %c's are to make sure "track(" doesn't get glommed onto the matrixName - iNumValuesAssigned = sscanf(token, - " %c [ %d ] = %c%c%c%c%c ( %s %s ) ;", - &c[0], &iConstID, &c[1], &c[2], &c[3], &c[4], &c[5], - matrixName, matrixTransformName); - - if (iNumValuesAssigned < 8) - { - sprintf(error, "error at line %d \n\"%s\"\n", iLineCount, token); - errors.set(error); - } - else - { - char *buffer; - if (9 == iNumValuesAssigned) - { - // just need to remove any junk from the matrix names and IDs. - buffer = strstr(matrixName, ","); - if (buffer) - *buffer = 0; - - buffer = strstr(matrixTransformName, ")"); - if (buffer) - *buffer = 0; - } - else // 8 == iNumValuesAssigned - { - // have to split the two names, since they both were put into the matrixName - buffer = strstr(matrixName, ","); - if (buffer) - { - strcpy(matrixTransformName, buffer + 1); - *buffer = 0; - // get rid of paren at end of transform name, if it is there - buffer = strstr(matrixTransformName, ")"); - if (buffer) - *buffer = 0; - - } - else - { - sprintf(error, "error at line %d \n\"%s\"\n", iLineCount, token); - errors.set(error); - } - } - - // constant ID must be modulo 4. - if (0 != (iConstID % 4)) - { - sprintf(error, - "error at line %d \n\"%s\"\n\tglTrackMatrixNV address must be modulo 4\n", - iLineCount, token); - errors.set(error); - } - else if (iConstID < 0 || iConstID > 95) - { - sprintf(error, - "error at line %d \n\"%s\"\n\tConstant address out of range\n", - iLineCount, token); - errors.set(error); - } - else - { - // get the enum values for the specified matrices - GLuint iMatrixID = LookupTrackMatrix(matrixName); - GLuint iTransformID = LookupTrackMatrixTransform(matrixTransformName); - - if (0 == iMatrixID) - { - sprintf(error, - "error at line %d \n\"%s\"\n\tInvalid Matrix parameter in glTrackMatrixNV.\n", - iLineCount, token); - errors.set(error); - } - else if (0 == iTransformID) - { - sprintf(error, - "error at line %d \n\"%s\"\n\tInvalid Transform parameter in glTrackMatrixNV\n", - iLineCount, token); - errors.set(error); - } - else - { - // untrack any currently tracked matrix - glTrackMatrixNV(target, iConstID, GL_NONE, GL_IDENTITY_NV); - - // tell GL the matrix to track - glTrackMatrixNV(target, iConstID, iMatrixID, iTransformID); - } - } - } - } - else // this is a constant directive - { - float xyzw[4] = {0, 0, 0, 0}; - iNumValuesAssigned = sscanf(token, - " %c [ %d ] = ( %f , %f , %f , %f ) ; ", - &c[0], &iConstID, xyzw, xyzw + 1, xyzw + 2, xyzw + 3); - - if (6 != iNumValuesAssigned) - { // error in constant directive. - sprintf(error, "error at line %d \n\"%s\"\n", iLineCount, token); - errors.set(error); - } - else if (iConstID < 0 || iConstID > 95) - { - sprintf(error, - "error at line %d \n\"%s\"\n\tConstant address out of range\n", - iLineCount, token); - errors.set(error); - } - else - { - // Always set the closest matrix location to tracking NONE to avoid errors! - glTrackMatrixNV(target, iConstID - (iConstID % 4), GL_NONE, GL_IDENTITY_NV); - - // tell GL the constant values - glProgramParameter4fvNV(target, iConstID, xyzw); - } - } - } - } - - // get the next line - token = strtok(NULL, lineSeparator); - } -} - - -struct MatrixLookupEntry -{ - string name; - GLuint ID; -}; - - -//.----------------------------------------------------------------------------. -//| Function : LookupTrackMatrix | -//| Description: Returns the enumerated matrix name given a valid string | -//| or 0 if an unknown matrix is requested. | -//.----------------------------------------------------------------------------. -GLuint LookupTrackMatrix(char *matrixName) -{ - static bool bFirstTime = true; - static int iNumEntries = 14; - static MatrixLookupEntry* matrixLookupTable = new MatrixLookupEntry[iNumEntries]; - - if (bFirstTime) // build the lookup table - { - matrixLookupTable[0].name = "GL_NONE"; - matrixLookupTable[0].ID = GL_NONE; - matrixLookupTable[1].name = "GL_MODELVIEW"; - matrixLookupTable[1].ID = GL_MODELVIEW; - matrixLookupTable[2].name = "GL_PROJECTION"; - matrixLookupTable[2].ID = GL_PROJECTION; - matrixLookupTable[3].name = "GL_TEXTURE"; - matrixLookupTable[3].ID = GL_TEXTURE; - matrixLookupTable[4].name = "GL_COLOR"; - matrixLookupTable[4].ID = GL_COLOR; - matrixLookupTable[5].name = "GL_MODELVIEW_PROJECTION_NV"; - matrixLookupTable[5].ID = GL_MODELVIEW_PROJECTION_NV; - matrixLookupTable[6].name = "GL_MATRIX0_NV"; - matrixLookupTable[6].ID = GL_MATRIX0_NV; - matrixLookupTable[7].name = "GL_MATRIX1_NV"; - matrixLookupTable[7].ID = GL_MATRIX1_NV; - matrixLookupTable[8].name = "GL_MATRIX2_NV"; - matrixLookupTable[8].ID = GL_MATRIX2_NV; - matrixLookupTable[9].name = "GL_MATRIX3_NV"; - matrixLookupTable[9].ID = GL_MATRIX3_NV; - matrixLookupTable[10].name = "GL_MATRIX4_NV"; - matrixLookupTable[10].ID = GL_MATRIX4_NV; - matrixLookupTable[11].name = "GL_MATRIX5_NV"; - matrixLookupTable[11].ID = GL_MATRIX5_NV; - matrixLookupTable[12].name = "GL_MATRIX6_NV"; - matrixLookupTable[12].ID = GL_MATRIX6_NV; - matrixLookupTable[13].name = "GL_MATRIX7_NV"; - matrixLookupTable[13].ID = GL_MATRIX7_NV; - bFirstTime = false; - } - - for (int i = 0; i < iNumEntries; i++) - { - if (!strcmp(matrixName, matrixLookupTable[i].name.c_str())) - { - - return matrixLookupTable[i].ID; - } - } - - return 0; -} - -//.----------------------------------------------------------------------------. -//| Function : LookupTrackMatrixTransform | -//| Description: Returns the enumerated matrix transform name given a valid | -//| string name or 0 if an unknown transform is requested. | -//.----------------------------------------------------------------------------. -GLuint LookupTrackMatrixTransform(char *matrixTransformName) -{ - static bool bFirstTime = true; - static int iNumEntries = 4; - static MatrixLookupEntry* transformLookupTable = new MatrixLookupEntry[iNumEntries]; - - if (bFirstTime) - { - transformLookupTable[0].name = "GL_IDENTITY_NV"; - transformLookupTable[0].ID = GL_IDENTITY_NV; - transformLookupTable[1].name = "GL_INVERSE_NV"; - transformLookupTable[1].ID = GL_INVERSE_NV; - transformLookupTable[2].name = "GL_TRANSPOSE_NV"; - transformLookupTable[2].ID = GL_TRANSPOSE_NV; - transformLookupTable[3].name = "GL_INVERSE_TRANSPOSE_NV"; - transformLookupTable[3].ID = GL_INVERSE_TRANSPOSE_NV; - bFirstTime = false; - } - - for (int i = 0; i < iNumEntries; i++) - { - if (!strcmp( matrixTransformName, transformLookupTable[i].name.c_str())) - { - return transformLookupTable[i].ID; - } - } - - return 0; -} - -} diff --git a/RenderSystems/GL/src/nvparse/vp1.0_impl.cpp b/RenderSystems/GL/src/nvparse/vp1.0_impl.cpp deleted file mode 100644 index 15cc1d03c69..00000000000 --- a/RenderSystems/GL/src/nvparse/vp1.0_impl.cpp +++ /dev/null @@ -1,195 +0,0 @@ -#include "nvparse_errors.h" -#include "nvparse_externs.h" -#include -#include -#include - -using namespace std; - - -namespace -{ - void LoadProgram( GLenum target, GLuint id, char *instring ); - GLint vpid; -} - - -bool is_vp10(const char * s) -{ - return ! strncmp(s, "!!VP1.0", 7); -} - -bool vp10_init(char * s) -{ - static bool vpinit = false; - if (vpinit == false ) - { - /* - if(! glh_init_extensions("GL_NV_vertex_program")) - { - errors.set("unable to initialize GL_NV_vertex_program"); - return false; - } - else - { - */ - vpinit = true; - /* - } - */ - } - - errors.reset(); - line_number = 1; - myin = s; - - glGetIntegerv( GL_VERTEX_PROGRAM_BINDING_NV, &vpid ); - - if ( vpid == 0 ) - { - char str[128]; - sprintf( str, "No vertex program id bound for nvparse() invocation. Bound id = %d\n", (int)vpid ); - errors.set( str ); - return false; - } - - return true; -} - -int vp10_parse() -{ - LoadProgram( GL_VERTEX_PROGRAM_NV, vpid, myin ); - return 0; -} - -namespace -{ - //.----------------------------------------------------------------------------. - //| Function : LoadProgram | - //| Description: Load a program into GL, and report any errors encountered. | - //.----------------------------------------------------------------------------. - void LoadProgram( GLenum target, GLuint id, char *instring ) - { - GLint errPos; - GLenum errCode; - - int len = strlen(instring); - glLoadProgramNV( target, id, len, (const GLubyte *) instring ); - if ( (errCode = glGetError()) != GL_NO_ERROR ) - { - glGetIntegerv( GL_PROGRAM_ERROR_POSITION_NV, &errPos ); - if (errPos == -1) - return; - - int nlines = 1; - int nchar = 1; - int i; - for ( i = 0; i < errPos; i++ ) - { - if ( instring[i] == '\n' ) - { - nlines++; - nchar = 1; - } - else - { - nchar++; - } - } - int start = 0; - int end = 0; - int flag = ((instring[errPos]==';') | (instring[errPos-1]==';')) ? 1 : 0; - for ( i = errPos; i >= 0; i-- ) - { - start = i; - if ( flag && (start >= errPos-1) ) - continue; - if ( instring[i] == ';' ) - { - if ( !flag ) - { - start = i+1; - if ( instring[start] == '\n' ) - start++; - } - break; - } - } - for ( i = errPos; i < len; i++ ) - { - end = i; - if ( instring[i] == ';' && end > start) - { - break; - } - } - if ( errPos - start > 30 ) - { - start = errPos - 30; - } - if ( end - errPos > 30 ) - { - end = errPos + 30; - } - - char substring[96]; - memset( substring, 0, 96 ); - strncpy( substring, &(instring[start]), end-start+1 ); - char str[256]; - //sprintf( str, "error at line %d character %d\n \"%s\"\n", nlines, nchar, substring ); - sprintf( str, "error at line %d character %d\n\"%s\"\n", nlines, nchar, substring ); - int width = errPos-start; - for ( i = 0; i < width; i++ ) - { - strcat( str, " " ); - } - strcat( str, "|\n" ); - for ( i = 0; i < width; i++ ) - { - strcat( str, " " ); - } - strcat( str, "^\n" ); - - errors.set( str ); - } - } -} -/* else if(!strncmp(instring, "!!VP1.0", 7)) - { - if (vpinit == 0 ) - { - if(! glh_init_extensions("GL_NV_vertex_program")) - { - errors.set("unable to initialize GL_NV_vertex_program"); - free(instring); - return; - } - else - { - vpinit = 1; - } - } - - errors.reset(); - line_number = 1; - - int vpid; - glGetIntegerv( GL_VERTEX_PROGRAM_BINDING_NV, &vpid ); - - if ( glGetError() != GL_NO_ERROR ) - { - errors.set( "Previous GL_ERROR prior to vertex program parsing.\n" ); - } - - if ( vpid == 0 ) - { - char str[128]; - sprintf( str, "No vertex program id bound for nvparse() invocation. Bound id = %d\n", vpid ); - errors.set( str ); - } - else - { - LoadProgram( GL_VERTEX_PROGRAM_NV, vpid, instring ); - } - } - */ diff --git a/RenderSystems/GL/src/nvparse/vs1.0_grammar.y b/RenderSystems/GL/src/nvparse/vs1.0_grammar.y deleted file mode 100644 index bd2096b2219..00000000000 --- a/RenderSystems/GL/src/nvparse/vs1.0_grammar.y +++ /dev/null @@ -1,456 +0,0 @@ -%start VS10Program -%name-prefix "vs10_" -%{ -void yyerror(const char *s); -int yylex(void); - -#include -#include - -#include -#include "vs1.0_inst_list.h" -#include "nvparse_errors.h" -#include "nvparse_externs.h" - -//extern bool gbTempInsideMacro; -//extern unsigned int &base_linenumber; -void LexError(const char *format, ...); -extern int line_incr; - -#define do_linenum_incr() { line_number+=line_incr; line_incr = 0; } -//int get_linenum() { return( gbTempInsideMacro ? base_linenumber : line_number ); } -int get_linenum() { return( line_number ); } - -#define YYDEBUG 1 - -%} -%union { - int ival; - unsigned int lval; - float fval; - char mask[4]; - char *comment; - VS10Reg reg; - VS10InstPtr inst; - VS10InstListPtr instList; -}; - -%token VERTEX_SHADER - -%token ADD_INSTR -%token DP3_INSTR -%token DP4_INSTR -%token DST_INSTR -%token EXP_INSTR -%token EXPP_INSTR -%token FRC_INSTR -%token LIT_INSTR -%token LOG_INSTR -%token LOGP_INSTR -%token M3X2_INSTR -%token M3X3_INSTR -%token M3X4_INSTR -%token M4X3_INSTR -%token M4X4_INSTR -%token MAD_INSTR -%token MAX_INSTR -%token MIN_INSTR -%token MOV_INSTR -%token MUL_INSTR -%token NOP_INSTR -%token RCP_INSTR -%token RSQ_INSTR -%token SGE_INSTR -%token SLT_INSTR -%token SUB_INSTR - -%token ILLEGAL -%token UNKNOWN_STRING - -%token INTVAL -%token REGISTER -%token XYZW_MODIFIER -%token COMMENT - -%type InstSequence -%type InstLine -%type Instruction -%type VECTORopinstruction -%type SCALARopinstruction -%type UNARYopinstruction -%type BINopinstruction -%type TRIopinstruction -%type VECTORop -%type SCALARop -%type UNARYop -%type BINop -%type TRIop - -%type genericReg -%type genReg -%type constantReg - - -%% /*beginning of rules section */ - -VS10Program: InstSequence - { - $1->Validate(); - $1->Translate(); - delete $1; - } - ; - -InstSequence: InstSequence InstLine - { - *($1) += $2; - delete $2; - $$ = $1; - } - | InstLine - { - VS10InstListPtr instList = new VS10InstList; - if ( $1 != NULL ) - { - *instList += $1; - delete $1; - } - $$ = instList; - } - ; - -InstLine: Instruction - { - $$ = $1; - do_linenum_incr(); - } - | '\n' - { - $$ = new VS10Inst( get_linenum() ); - do_linenum_incr(); - } - ; - -Instruction: VECTORopinstruction - | SCALARopinstruction - | UNARYopinstruction - | BINopinstruction - | TRIopinstruction - | NOP_INSTR - { - $$ = new VS10Inst( get_linenum(), VS10_NOP ); - } - | COMMENT - { - $$ = new VS10Inst( get_linenum(), VS10_COMMENT, $1 ); - } - | VERTEX_SHADER - { - $$ = new VS10Inst( get_linenum(), VS10_HEADER ); - } - ; - -VECTORopinstruction: VECTORop genericReg ',' genericReg - { - $$ = new VS10Inst( get_linenum(), $1, $2, $4 ); - } - ; - -genericReg : '-' genReg '.' XYZW_MODIFIER - { - VS10Reg reg; - reg = $2; - reg.sign = -1; - reg.type = $2.type; - reg.index = $2.index; - for ( int i = 0; i < 4; i++ ) reg.mask[i] = $4[i]; - $$ = reg; - } - | genReg '.' XYZW_MODIFIER - { - VS10Reg reg; - reg = $1; - reg.sign = 1; - reg.type = $1.type; - reg.index = $1.index; - for ( int i = 0; i < 4; i++ ) reg.mask[i] = $3[i]; - $$ = reg; - } - | '-' genReg - { - VS10Reg reg; - reg = $2; - reg.sign = -1; - reg.type = $2.type; - reg.index = $2.index; - for ( int i = 0; i < 4; i++ ) reg.mask[i] = 0; - $$ = reg; - } - | genReg - { - VS10Reg reg; - reg = $1; - reg.sign = 1; - reg.type = $1.type; - reg.index = $1.index; - for ( int i = 0; i < 4; i++ ) reg.mask[i] = 0; - $$ = reg; - } - ; -genReg: REGISTER | constantReg - { - } - ; -constantReg: 'c' '[' INTVAL ']' - { - VS10Reg reg; - reg.type = TYPE_CONSTANT_MEM_REG; - reg.index = $3; - $$ = reg; - } - | 'c' '[' REGISTER '.' XYZW_MODIFIER ']' - { - // Register is valid only if - // type = TYPE_ADDRESS_REG - // index = 0 - // len(mask) = 1 - // mask[0] = 'x' - VS10Reg reg; - $$.type = TYPE_CONSTANT_A0_REG; - if ( $3.type != TYPE_ADDRESS_REG ) - { - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } - else if ( $3.index != 0 ) - { - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } - else - { - int len = 0; - while ( len < 2 ) - { - if ( $5[len] == 0 ) - break; - len++; - } - if ( len != 1 || $5[0] != 'x' ) - { - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } - - reg.type = TYPE_CONSTANT_A0_REG; - $$ = reg; - } - } - | 'c' '[' REGISTER '.' XYZW_MODIFIER '+' INTVAL ']' - { - // Register is valid only if - // type = TYPE_ADDRESS_REG - // index = 0 - // len(mask) = 1 - // mask[0] = 'x' - VS10Reg reg; - $$.type = TYPE_CONSTANT_A0_OFFSET_REG; - if ( $3.type != TYPE_ADDRESS_REG ) - { - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } - else if ( $3.index != 0 ) - { - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } - else - { - int len = 0; - while ( len < 2 ) - { - if ( $5[len] == 0 ) - break; - len++; - } - if ( len != 1 || $5[0] != 'x' ) - { - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } - - reg.type = TYPE_CONSTANT_A0_OFFSET_REG; - reg.index = $7; - $$ = reg; - } - } - | 'c' '[' REGISTER ']' - { - $$.type = TYPE_CONSTANT_A0_REG; - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } - | 'c' '[' REGISTER '+' INTVAL ']' - { - $$.type = TYPE_CONSTANT_A0_REG; - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } - | 'c' '[' '-' REGISTER ']' - { - $$.type = TYPE_CONSTANT_A0_REG; - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } - | 'c' '[' '-' REGISTER '+' INTVAL ']' - { - $$.type = TYPE_CONSTANT_A0_REG; - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } - | 'c' '[' '-' REGISTER '.' XYZW_MODIFIER ']' - { - $$.type = TYPE_CONSTANT_A0_REG; - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } - | 'c' '[' '-' REGISTER '.' XYZW_MODIFIER '+' INTVAL ']' - { - $$.type = TYPE_CONSTANT_A0_REG; - LexError( "constant register index must be:\t, a0.x, or a0.x + .\n" ); - } - ; - -SCALARopinstruction: SCALARop genericReg ',' genericReg - { - $$ = new VS10Inst( get_linenum(), $1, $2, $4 ); - } - ; - -UNARYopinstruction: UNARYop genericReg ',' genericReg - { - $$ = new VS10Inst( get_linenum(), $1, $2, $4 ); - } - ; - -BINopinstruction: BINop genericReg ',' genericReg ',' genericReg - { - $$ = new VS10Inst( get_linenum(), $1, $2, $4, $6 ); - } - ; - -TRIopinstruction: TRIop genericReg ',' - genericReg ',' genericReg ',' genericReg - { - $$ = new VS10Inst( get_linenum(), $1, $2, $4, $6, $8 ); - } - ; - -VECTORop: MOV_INSTR - { - $$ = VS10_MOV; - } - | LIT_INSTR - { - $$ = VS10_LIT; - } - ; - -SCALARop: RCP_INSTR - { - $$ = VS10_RCP; - } - | RSQ_INSTR - { - $$ = VS10_RSQ; - } - | EXP_INSTR - { - $$ = VS10_EXP; - } - | EXPP_INSTR - { - $$ = VS10_EXPP; - } - | LOG_INSTR - { - $$ = VS10_LOG; - } - | LOGP_INSTR - { - $$ = VS10_LOGP; - } - ; - -UNARYop: FRC_INSTR - { - $$ = VS10_FRC; - } - ; - -BINop: MUL_INSTR - { - $$ = VS10_MUL; - } - | ADD_INSTR - { - $$ = VS10_ADD; - } - | DP3_INSTR - { - $$ = VS10_DP3; - } - | DP4_INSTR - { - $$ = VS10_DP4; - } - | DST_INSTR - { - $$ = VS10_DST; - } - | MIN_INSTR - { - $$ = VS10_MIN; - } - | MAX_INSTR - { - $$ = VS10_MAX; - } - | SLT_INSTR - { - $$ = VS10_SLT; - } - | SGE_INSTR - { - $$ = VS10_SGE; - } - | M3X2_INSTR - { - $$ = VS10_M3X2; - } - | M3X3_INSTR - { - $$ = VS10_M3X3; - } - | M3X4_INSTR - { - $$ = VS10_M3X4; - } - | M4X3_INSTR - { - $$ = VS10_M4X3; - } - | M4X4_INSTR - { - $$ = VS10_M4X4; - } - | SUB_INSTR - { - $$ = VS10_SUB; - } - ; - -TRIop: MAD_INSTR - { - $$ = VS10_MAD; - } - ; - - -%% -void yyerror(const char* s) -{ - LexError( "Syntax Error.\n" ); - //errors.set(s); - //errors.set("unrecognized token"); -} diff --git a/RenderSystems/GL/src/nvparse/vs1.0_inst.cpp b/RenderSystems/GL/src/nvparse/vs1.0_inst.cpp deleted file mode 100644 index e33bb8e82eb..00000000000 --- a/RenderSystems/GL/src/nvparse/vs1.0_inst.cpp +++ /dev/null @@ -1,1476 +0,0 @@ -#ifdef WIN32 -#pragma warning(disable:4786) -#endif -#include "vs1.0_inst.h" -#include -#include -#include -#include -#include "nvparse_errors.h" -#include "nvparse_externs.h" - -std::string vs10_transstring; - -#if 0 -VS10Reg::VS10Reg() -{ - type = 0; - index = 0; - sign = 0; - mask = 0; -} - -VS10Reg::VS10Reg(const VS10Reg &r) -{ - type = r.type; - index = r.index; - sign = r.sign; - mask = r.mask; -} - -VS10Reg& VS10Reg::operator=(const VS10Reg &r) -{ - if ( this != &r ) - { - type = r.type; - index = r.index; - sign = r.sign; - mask = r.mask; - } - return *this; -} -#endif - -void VS10Reg::Init() -{ - type = 0; - index = -1; - sign = 0; - mask[0] = 'j'; - mask[1] = 'j'; - mask[2] = 'j'; - mask[3] = 'j'; -} - -int VS10Reg::ValidateIndex() -{ - switch( type ) - { - case TYPE_TEMPORARY_REG: - if ( index < 0 || index > 11 ) return 0; - else return 1; - break; - case TYPE_VERTEX_ATTRIB_REG: - if ( index < 0 || index > 15 ) return 0; - else return 1; - break; - case TYPE_ADDRESS_REG: - if ( index != 0 ) return 0; - else return 1; - break; - case TYPE_CONSTANT_MEM_REG: - if ( index < 0 || index > 95 ) return 0; - else return 1; - break; - case TYPE_CONSTANT_A0_REG: - case TYPE_CONSTANT_A0_OFFSET_REG: - return 1; - break; - case TYPE_POSITION_RESULT_REG: - return 1; - break; - case TYPE_COLOR_RESULT_REG: - if ( index < 0 || index > 1 ) return 0; - else return 1; - break; - case TYPE_TEXTURE_RESULT_REG: - if ( index < 0 || index > 3 ) return 0; - else return 1; - break; - case TYPE_FOG_RESULT_REG: - return 1; - break; - case TYPE_POINTS_RESULT_REG: - return 1; - break; - default: - errors.set( "VS10Reg::ValidateIndex() Internal Error: unknown register type\n" ); - return 1; - } - return 1; -} - -void VS10Reg::Translate() -{ - char str[16]; - - if ( sign == -1 ) - vs10_transstring.append( "-" ); - - switch ( type ) - { - case TYPE_TEMPORARY_REG: - sprintf( str, "R%d", index ); - vs10_transstring.append( str ); - break; - case TYPE_VERTEX_ATTRIB_REG: - sprintf( str, "v[%d]", index ); - vs10_transstring.append( str ); - break; - case TYPE_ADDRESS_REG: - sprintf( str, "A%d", index ); - vs10_transstring.append( str ); - break; - case TYPE_CONSTANT_MEM_REG: - sprintf( str, "c[%d]", index ); - vs10_transstring.append( str ); - break; - case TYPE_CONSTANT_A0_REG: - vs10_transstring.append( "c[ A0.x ]" ); - break; - case TYPE_CONSTANT_A0_OFFSET_REG: - sprintf( str, "c[ A0.x + %d ]", index ); - vs10_transstring.append( str ); - break; - case TYPE_POSITION_RESULT_REG: - vs10_transstring.append( "o[HPOS]" ); - break; - case TYPE_COLOR_RESULT_REG: - sprintf( str, "o[COL%d]", index ); - vs10_transstring.append( str ); - break; - case TYPE_TEXTURE_RESULT_REG: - sprintf( str, "o[TEX%d]", index ); - vs10_transstring.append( str ); - break; - case TYPE_FOG_RESULT_REG: - vs10_transstring.append( "o[FOGC]" ); - break; - case TYPE_POINTS_RESULT_REG: - vs10_transstring.append( "o[PSIZ]" ); - break; - default: - errors.set( "VS10Reg::Translate() Internal Error: unknown register type\n" ); - } - - if ( mask[0] != 0 ) - { - str[0] = '.'; - strncpy( str+1, mask, 4 ); - str[5] = 0; - vs10_transstring.append( str ); - } -} - -VS10Inst::~VS10Inst() -{ - if (comment != NULL ) delete [] comment; -} - -VS10Inst::VS10Inst() -{ - line = -1; - instid = -1; - dst.Init(); - src[0].Init(); - src[1].Init(); - src[2].Init(); - comment = NULL; -} - -VS10Inst::VS10Inst( int currline ) -{ - line = currline; - instid = -1; - dst.Init(); - src[0].Init(); - src[1].Init(); - src[2].Init(); - comment = NULL; -} - -VS10Inst::VS10Inst( const VS10Inst &inst ) -{ - line = inst.line; - instid = inst.instid; - dst = inst.dst; - src[0] = inst.src[0]; - src[1] = inst.src[1]; - src[2] = inst.src[2]; - if ( inst.comment == NULL ) - comment = NULL; - else - { - comment = new char[strlen(inst.comment)+1]; - strcpy( comment, inst.comment ); - } -} - -VS10Inst& VS10Inst::operator=(const VS10Inst &inst) -{ - if ( this != &inst ) - { - line = inst.line; - instid = inst.instid; - dst = inst.dst; - src[0] = inst.src[0]; - src[1] = inst.src[1]; - src[2] = inst.src[2]; - if ( inst.comment == NULL ) - comment = NULL; - else - { - comment = new char[strlen(inst.comment)+1]; - strcpy( comment, inst.comment ); - } - } - return *this; -} - - -VS10Inst::VS10Inst(int currline, int inst) -{ - line = currline; - instid = inst; - dst.Init(); - src[0].Init(); - src[1].Init(); - src[2].Init(); - comment = NULL; -} - -VS10Inst::VS10Inst(int currline, int inst, char *cmt) -{ - line = currline; - instid = inst; - dst.Init(); - src[0].Init(); - src[1].Init(); - src[2].Init(); - comment = cmt; -} - -VS10Inst::VS10Inst(int currline, int inst, VS10Reg dreg, VS10Reg src0) -{ - line = currline; - instid = inst; - dst = dreg; - src[0] = src0; - src[1].Init(); - src[2].Init(); - comment = NULL; -} - -VS10Inst::VS10Inst(int currline, int inst, VS10Reg dreg, VS10Reg src0, VS10Reg src1) -{ - line = currline; - instid = inst; - dst = dreg; - src[0] = src0; - src[1] = src1; - src[2].Init(); - comment = NULL; -} - -VS10Inst::VS10Inst(int currline, int inst, VS10Reg dreg, VS10Reg src0, VS10Reg src1, VS10Reg src2) -{ - line = currline; - instid = inst; - dst = dreg; - src[0] = src0; - src[1] = src1; - src[2] = src2; - comment = NULL; -} - -void VS10Inst::Validate( int &vsflag ) -{ - - // Handle comments, noops, and newlines. - if ( instid == VS10_COMMENT || instid == VS10_NOP || instid == -1 ) return; - - // Handle the header case. - if ( instid == VS10_HEADER ) - { - if ( vsflag == 0 ) - { - vsflag = 1; - return; - } - else - { - char temp[128]; - sprintf( temp, "(%d) Error: vs.1.0 token already encountered\n", line ); - errors.set( temp ); - return; - } - } - - // Validate register indices are valid. - ValidateRegIndices(); - - // Verify destination masking is valid. - ValidateDestMask(); - - // Verify source swizzling is valid. - ValidateSrcMasks(); - - // Verify destination register is writable. - ValidateDestWritable(); - - // Verify source registers are readable. - ValidateSrcReadable(); - - // Verify not reading from multiple vertex attributes or constants - ValidateReadPorts(); -} - -void VS10Inst::ValidateRegIndices() -{ - char temp[256]; - int result; - - // Destination register. - result = dst.ValidateIndex(); - if ( !result ) - { - sprintf( temp, "(%d) Error: destination register index out of range\n", line ); - errors.set( temp ); - } - - // Source register. - result = src[0].ValidateIndex(); - if ( !result ) - { - sprintf( temp, "(%d) Error: source register index out of range\n", line ); - errors.set( temp ); - } - - switch( instid ) - { - // Vector operations. - case VS10_MOV: - case VS10_LIT: - break; - - // Unary operations. - case VS10_FRC: - break; - - // Scalar operations. - case VS10_EXP: - case VS10_EXPP: - case VS10_LOG: - case VS10_LOGP: - case VS10_RCP: - case VS10_RSQ: - break; - - // Binary operations. - case VS10_ADD: - case VS10_DP3: - case VS10_DP4: - case VS10_DST: - case VS10_SGE: - case VS10_SLT: - case VS10_SUB: - case VS10_MAX: - case VS10_MIN: - case VS10_MUL: - result = src[1].ValidateIndex(); - if ( !result ) - { - sprintf( temp, "(%d) Error: second source register index out of range\n", line ); - errors.set( temp ); - } - break; - - case VS10_M3X2: - case VS10_M3X3: - case VS10_M3X4: - case VS10_M4X3: - case VS10_M4X4: - { - result = src[1].ValidateIndex(); - if ( !result ) - { - sprintf( temp, "(%d) Error: second source register index out of range\n", line ); - errors.set( temp ); - } - int orig; - orig = src[1].index; - switch( instid ) - { - case VS10_M3X2: - src[1].index = src[1].index + 1; - break; - case VS10_M3X3: - case VS10_M4X3: - src[1].index = src[1].index + 2; - break; - case VS10_M3X4: - case VS10_M4X4: - src[1].index = src[1].index + 3; - break; - } - result = src[1].ValidateIndex(); - src[1].index = orig; - if ( !result ) - { - sprintf( temp, "(%d) Error: macro expansion produces source register index out of range\n", line ); - errors.set( temp ); - } - } - break; - - // Trinary operations. - case VS10_MAD: - result = src[1].ValidateIndex(); - if ( !result ) - { - sprintf( temp, "(%d) Error: second source register index out of range\n", line ); - errors.set( temp ); - } - result = src[2].ValidateIndex(); - if ( !result ) - { - sprintf( temp, "(%d) Error: third source register index out of range\n", line ); - errors.set( temp ); - } - break; - default: - errors.set( "VS10Inst::ValidateRegIndices() Internal Error: unknown instruction type\n" ); - break; - } -} - -void VS10Inst::ValidateDestMask() -{ - char temp[256]; - typedef std::map MyMap; - typedef MyMap::value_type MyPair; - static const MyPair pairs[] = - { - MyPair('x',1), - MyPair('y',2), - MyPair('z',3), - MyPair('w',4), - }; - static const MyMap swizzleMap(pairs, pairs+(sizeof(pairs)/sizeof(pairs[0]))); - - if ( dst.mask[0] == 0 ) return; - int i = 1; - while ( i < 4 && dst.mask[i] != 0 ) - { - MyMap::const_iterator lastMaskIt = swizzleMap.find(dst.mask[i-1]); - MyMap::const_iterator curMaskIt = swizzleMap.find(dst.mask[i]); - if (lastMaskIt == swizzleMap.end() || curMaskIt == swizzleMap.end() || - lastMaskIt->second >= curMaskIt->second) -// if ( dst.mask[i-1] >= dst.mask[i] ) - { - char mask[5]; - strncpy( mask, dst.mask, 4 ); - mask[4] = 0; - sprintf( temp, "(%d) Error: destination register has invalid mask: %s\n", line, mask ); - errors.set( temp ); - break; - } - i++; - } -} - -void VS10Inst::ValidateSrcMasks() -{ - char temp[256]; - char mask[5]; - int len; - int i; - - switch( instid ) - { - // Vector operations. - case VS10_MOV: - case VS10_LIT: - strncpy( mask, src[0].mask, 4 ); - mask[4] = 0; - len = strlen( mask ); - if ( len != 1 ) - { - for ( i = len; i < 4; i++ ) - src[0].mask[i] = src[0].mask[len-1]; - } - break; - - // Unary operations. - case VS10_FRC: - strncpy( mask, src[0].mask, 4 ); - mask[4] = 0; - len = strlen( mask ); - if ( len != 1 ) - { - for ( i = len; i < 4; i++ ) - src[0].mask[i] = src[0].mask[len-1]; - } - break; - - // Scalar operations. - case VS10_EXP: - case VS10_EXPP: - case VS10_LOG: - case VS10_LOGP: - strncpy( mask, src[0].mask, 4 ); - mask[4] = 0; - len = strlen( mask ); - if( len != 1 ) - { - sprintf( temp, "(%d) Error: source register has invalid mask: %s\n", line, mask ); - errors.set( temp ); - } - break; - - case VS10_RCP: - case VS10_RSQ: - strncpy( mask, src[0].mask, 4 ); - mask[4] = 0; - len = strlen( mask ); - if( len != 0 && len != 1 ) - { - sprintf( temp, "(%d) Error: source register has invalid mask: %s\n", line, mask ); - errors.set( temp ); - } - if ( len == 0 ) - { - strcpy( src[0].mask, "w" ); - } - break; - - // Binary operations. - case VS10_ADD: - case VS10_DP3: - case VS10_DP4: - case VS10_DST: - case VS10_SGE: - case VS10_SLT: - case VS10_SUB: - case VS10_M3X2: - case VS10_M3X3: - case VS10_M3X4: - case VS10_M4X3: - case VS10_M4X4: - case VS10_MAX: - case VS10_MIN: - case VS10_MUL: - strncpy( mask, src[0].mask, 4 ); - mask[4] = 0; - len = strlen( mask ); - if ( len != 0 && len != 1 ) - { - for ( i = len; i < 4; i++ ) - src[0].mask[i] = src[0].mask[len-1]; - } - strncpy( mask, src[1].mask, 4 ); - mask[4] = 0; - len = strlen( mask ); - if ( len != 0 && len != 1 ) - { - for ( i = len; i < 4; i++ ) - src[1].mask[i] = src[1].mask[len-1]; - } - break; - - // Trinary operations. - case VS10_MAD: - strncpy( mask, src[0].mask, 4 ); - mask[4] = 0; - len = strlen( mask ); - if ( len != 0 && len != 1 ) - { - for ( i = len; i < 4; i++ ) - src[0].mask[i] = src[0].mask[len-1]; - } - strncpy( mask, src[1].mask, 4 ); - mask[4] = 0; - len = strlen( mask ); - if ( len != 0 && len != 1 ) - { - for ( i = len; i < 4; i++ ) - src[1].mask[i] = src[1].mask[len-1]; - } - strncpy( mask, src[2].mask, 4 ); - mask[4] = 0; - len = strlen( mask ); - if ( len != 0 && len != 1 ) - { - for ( i = len; i < 4; i++ ) - src[2].mask[i] = src[2].mask[len-1]; - } - break; - default: - errors.set( "VS10Inst::ValidateSrcMasks() Internal Error: unknown instruction type\n" ); - break; - } -} - -void VS10Inst::ValidateDestWritable() -{ - char temp[256]; - - switch ( dst.type ) - { - case TYPE_TEMPORARY_REG: - case TYPE_POSITION_RESULT_REG: - case TYPE_COLOR_RESULT_REG: - case TYPE_TEXTURE_RESULT_REG: - case TYPE_FOG_RESULT_REG: - case TYPE_POINTS_RESULT_REG: - break; - case TYPE_VERTEX_ATTRIB_REG: - case TYPE_CONSTANT_MEM_REG: - case TYPE_CONSTANT_A0_REG: - case TYPE_CONSTANT_A0_OFFSET_REG: - sprintf( temp, "(%d) Error: destination register is not writable\n", line ); - errors.set( temp ); - break; - case TYPE_ADDRESS_REG: - if ( instid != VS10_MOV ) - { - sprintf( temp, "(%d) Error: destination register is not writable using this instruction\n", line ); - errors.set( temp ); - } - break; - default: - errors.set( "VS10Inst::ValidateDestWritable() Internal Error: unknown register type\n" ); - } - - if ( instid == VS10_FRC && dst.type != TYPE_TEMPORARY_REG ) - { - sprintf( temp, "(%d) Error: destination register must be a temporary register\n", line ); - errors.set( temp ); - } -} - -void VS10Inst::ValidateSrcReadable() -{ - char temp[256]; - - // Source register. - switch( src[0].type ) - { - case TYPE_TEMPORARY_REG: - case TYPE_VERTEX_ATTRIB_REG: - case TYPE_CONSTANT_MEM_REG: - case TYPE_CONSTANT_A0_REG: - case TYPE_CONSTANT_A0_OFFSET_REG: - break; - case TYPE_ADDRESS_REG: - case TYPE_POSITION_RESULT_REG: - case TYPE_COLOR_RESULT_REG: - case TYPE_TEXTURE_RESULT_REG: - case TYPE_FOG_RESULT_REG: - case TYPE_POINTS_RESULT_REG: - sprintf( temp, "(%d) Error: source register is not readable\n", line ); - errors.set( temp ); - break; - default: - errors.set( "VS10Inst::ValidateSrcReadable() Internal Error: unknown register type\n" ); - } - - switch( instid ) - { - // Vector operations. - case VS10_MOV: - case VS10_LIT: - break; - - // Unary operations. - case VS10_FRC: - break; - - // Scalar operations. - case VS10_EXP: - case VS10_EXPP: - case VS10_LOG: - case VS10_LOGP: - case VS10_RCP: - case VS10_RSQ: - break; - - // Binary operations. - case VS10_ADD: - case VS10_DP3: - case VS10_DP4: - case VS10_DST: - case VS10_SGE: - case VS10_SLT: - case VS10_SUB: - case VS10_M3X2: - case VS10_M3X3: - case VS10_M3X4: - case VS10_M4X3: - case VS10_M4X4: - case VS10_MAX: - case VS10_MIN: - case VS10_MUL: - switch( src[1].type ) - { - case TYPE_TEMPORARY_REG: - case TYPE_VERTEX_ATTRIB_REG: - case TYPE_CONSTANT_MEM_REG: - case TYPE_CONSTANT_A0_REG: - case TYPE_CONSTANT_A0_OFFSET_REG: - break; - case TYPE_ADDRESS_REG: - case TYPE_POSITION_RESULT_REG: - case TYPE_COLOR_RESULT_REG: - case TYPE_TEXTURE_RESULT_REG: - case TYPE_FOG_RESULT_REG: - case TYPE_POINTS_RESULT_REG: - sprintf( temp, "(%d) Error: second source register is not readable\n", line ); - errors.set( temp ); - break; - default: - errors.set( "VS10Inst::ValidateSrcReadable() Internal Error: unknown register type\n" ); - } - break; - - // Trinary operations. - case VS10_MAD: - switch( src[1].type ) - { - case TYPE_TEMPORARY_REG: - case TYPE_VERTEX_ATTRIB_REG: - case TYPE_CONSTANT_MEM_REG: - case TYPE_CONSTANT_A0_REG: - case TYPE_CONSTANT_A0_OFFSET_REG: - break; - case TYPE_ADDRESS_REG: - case TYPE_POSITION_RESULT_REG: - case TYPE_COLOR_RESULT_REG: - case TYPE_TEXTURE_RESULT_REG: - case TYPE_FOG_RESULT_REG: - case TYPE_POINTS_RESULT_REG: - sprintf( temp, "(%d) Error: second source register is not readable\n", line ); - errors.set( temp ); - break; - default: - errors.set( "VS10Inst::ValidateSrcReadable() Internal Error: unknown register type\n" ); - } - switch( src[2].type ) - { - case TYPE_TEMPORARY_REG: - case TYPE_VERTEX_ATTRIB_REG: - case TYPE_CONSTANT_MEM_REG: - case TYPE_CONSTANT_A0_REG: - case TYPE_CONSTANT_A0_OFFSET_REG: - break; - case TYPE_ADDRESS_REG: - case TYPE_POSITION_RESULT_REG: - case TYPE_COLOR_RESULT_REG: - case TYPE_TEXTURE_RESULT_REG: - case TYPE_FOG_RESULT_REG: - case TYPE_POINTS_RESULT_REG: - sprintf( temp, "(%d) Error: third source register is not readable\n", line ); - errors.set( temp ); - break; - default: - errors.set( "VS10Inst::ValidateSrcReadable() Internal Error: unknown register type\n" ); - } - break; - default: - errors.set( "VS10Inst::ValidateSrcReadable() Internal Error: unknown register type\n" ); - break; - } -} - -void VS10Inst::ValidateReadPorts() -{ - int constidx[3]; - int attribidx[3]; - int i; - int acount; - int ccount; - char temp[256]; - - switch( instid ) - { - // Vector operations. - case VS10_MOV: - case VS10_LIT: - break; - - // Unary operations. - case VS10_FRC: - break; - - // Scalar operations. - case VS10_EXP: - case VS10_EXPP: - case VS10_LOG: - case VS10_LOGP: - case VS10_RCP: - case VS10_RSQ: - break; - - // Binary operations. - case VS10_ADD: - case VS10_DP3: - case VS10_DP4: - case VS10_DST: - case VS10_SGE: - case VS10_SLT: - case VS10_SUB: - case VS10_M3X2: - case VS10_M3X3: - case VS10_M3X4: - case VS10_M4X3: - case VS10_M4X4: - case VS10_MAX: - case VS10_MIN: - case VS10_MUL: - acount = 0; - ccount = 0; - for ( i = 0; i < 2; i++ ) - { - switch( src[i].type ) - { - case TYPE_VERTEX_ATTRIB_REG: - attribidx[acount] = src[i].index; - acount++; - break; - case TYPE_CONSTANT_MEM_REG: - constidx[ccount] = src[i].index; - ccount++; - break; - case TYPE_CONSTANT_A0_REG: - constidx[ccount] = 100 + src[i].index; - ccount++; - break; - case TYPE_CONSTANT_A0_OFFSET_REG: - constidx[ccount] = 200 + src[i].index; - ccount++; - break; - case TYPE_TEMPORARY_REG: - case TYPE_ADDRESS_REG: - case TYPE_POSITION_RESULT_REG: - case TYPE_COLOR_RESULT_REG: - case TYPE_TEXTURE_RESULT_REG: - case TYPE_FOG_RESULT_REG: - case TYPE_POINTS_RESULT_REG: - break; - default: - errors.set( "VS10Inst::ValidateReadPorts() Internal Error: unknown register type\n" ); - } - } - if ( acount == 2 ) - { - if ( attribidx[0] != attribidx[1] ) - { - sprintf( temp, "(%d) Error: multiple unique attribute registers accessed in this instruction\n", line ); - errors.set( temp ); - } - } - else if ( ccount == 2 ) - { - if ( constidx[0] != constidx[1] ) - { - sprintf( temp, "(%d) Error: multiple unique constant registers accessed in this instruction\n", line ); - errors.set( temp ); - } - } - break; - - // Trinary operations. - case VS10_MAD: - acount = 0; - ccount = 0; - for ( i = 0; i < 3; i++ ) - { - switch( src[i].type ) - { - case TYPE_VERTEX_ATTRIB_REG: - attribidx[acount] = src[i].index; - acount++; - break; - case TYPE_CONSTANT_MEM_REG: - constidx[ccount] = src[i].index; - ccount++; - break; - case TYPE_CONSTANT_A0_REG: - constidx[ccount] = 100 + src[i].index; - ccount++; - break; - case TYPE_CONSTANT_A0_OFFSET_REG: - constidx[ccount] = 200 + src[i].index; - ccount++; - break; - case TYPE_TEMPORARY_REG: - case TYPE_ADDRESS_REG: - case TYPE_POSITION_RESULT_REG: - case TYPE_COLOR_RESULT_REG: - case TYPE_TEXTURE_RESULT_REG: - case TYPE_FOG_RESULT_REG: - case TYPE_POINTS_RESULT_REG: - break; - default: - errors.set( "VS10Inst::ValidateReadPorts() Internal Error: unknown register type\n" ); - } - } - if ( acount == 3 ) - { - if ( attribidx[0] != attribidx[1] || attribidx[1] != attribidx[2] ) - { - sprintf( temp, "(%d) Error: multiple unique attribute registers accessed in this instruction\n", line ); - errors.set( temp ); - } - } - else if ( acount == 2 ) - { - if ( attribidx[0] != attribidx[1] ) - { - sprintf( temp, "(%d) Error: multiple unique attribute registers accessed in this instruction\n", line ); - errors.set( temp ); - } - } - else if ( ccount == 3 ) - { - if ( constidx[0] != constidx[1] || constidx[1] != constidx[2] ) - { - sprintf( temp, "(%d) Error: multiple unique constant registers accessed in this instruction\n", line ); - errors.set( temp ); - } - } - else if ( ccount == 2 ) - { - if ( constidx[0] != constidx[1] ) - { - sprintf( temp, "(%d) Error: multiple unique constant registers accessed in this instruction\n", line ); - errors.set( temp ); - } - } - break; - default: - errors.set( "VS10Inst::ValidateSrcReadable() Internal Error: unknown register type\n" ); - break; - } -} - -int VS10Inst::Translate() -{ - int flag; - int ninstr = 0; - -#if DEBUGGING_PURPOSES - char mystr[32]; - if ( instid == VS10_HEADER ) - { - sprintf( mystr, "%d:\tvs.1.0 (skip)\n", line ); - vs10_transstring.append( mystr ); - return 0; - } - sprintf( mystr, "%d:\t", line ); - vs10_transstring.append( mystr ); -#endif - - switch( instid ) - { - case VS10_ADD: - vs10_transstring.append( "ADD " ); - dst.Translate(); - vs10_transstring.append( ", " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - src[1].Translate(); - ninstr = 1; - break; - case VS10_DP3: - vs10_transstring.append( "DP3 " ); - dst.Translate(); - vs10_transstring.append( ", " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - src[1].Translate(); - ninstr = 1; - break; - case VS10_DP4: - vs10_transstring.append( "DP4 " ); - dst.Translate(); - vs10_transstring.append( ", " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - src[1].Translate(); - ninstr = 1; - break; - case VS10_DST: - vs10_transstring.append( "DST " ); - dst.Translate(); - vs10_transstring.append( ", " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - src[1].Translate(); - ninstr = 1; - break; - case VS10_EXP: - vs10_transstring.append( "EXP " ); - dst.Translate(); - vs10_transstring.append( ", " ); - src[0].Translate(); - ninstr = 1; - break; - case VS10_EXPP: - vs10_transstring.append( "EXP " ); - dst.Translate(); - vs10_transstring.append( ", " ); - src[0].Translate(); - ninstr = 1; - break; - case VS10_FRC: - char temp[128]; - sprintf( temp, "(%d) Error: FRC built-in macro not yet supported.\n", line ); - errors.set( temp ); - ninstr = 0; - break; - case VS10_LIT: - vs10_transstring.append( "LIT " ); - dst.Translate(); - vs10_transstring.append( ", " ); - src[0].Translate(); - ninstr = 1; - break; - case VS10_LOG: - vs10_transstring.append( "LOG " ); - dst.Translate(); - vs10_transstring.append( ", " ); - src[0].Translate(); - ninstr = 1; - break; - case VS10_LOGP: - vs10_transstring.append( "LOG " ); - dst.Translate(); - vs10_transstring.append( ", " ); - src[0].Translate(); - ninstr = 1; - break; - case VS10_M3X2: - case VS10_M3X3: - case VS10_M3X4: - if ( dst.mask[0] != 0 ) - { - ninstr = 0; - int i = 0; - while ( i < 4 && dst.mask[i] != 0 ) - { - if ( dst.mask[i] == 'x' ) - { - char oldval; - vs10_transstring.append( "DP3 " ); - oldval = dst.mask[0]; - dst.mask[0] = 0; - dst.Translate(); - dst.mask[0] = oldval; - vs10_transstring.append( ".x, " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - src[1].Translate(); - vs10_transstring.append( ";\n" ); - ninstr++; - } - if ( dst.mask[i] == 'y' ) - { - char oldval; - int oldindex; - vs10_transstring.append( "DP3 " ); - oldval = dst.mask[0]; - dst.mask[0] = 0; - dst.Translate(); - dst.mask[0] = oldval; - vs10_transstring.append( ".y, " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - oldindex = src[1].index; - src[1].index = src[1].index + 1; - src[1].Translate(); - src[1].index = oldindex; - vs10_transstring.append( ";\n" ); - ninstr++; - } - if ( dst.mask[i] == 'z' && (instid == VS10_M3X3 || instid == VS10_M3X4) ) - { - char oldval; - int oldindex; - vs10_transstring.append( "DP3 " ); - oldval = dst.mask[0]; - dst.mask[0] = 0; - dst.Translate(); - dst.mask[0] = oldval; - vs10_transstring.append( ".z, " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - oldindex = src[1].index; - src[1].index = src[1].index + 2; - src[1].Translate(); - src[1].index = oldindex; - vs10_transstring.append( ";\n" ); - ninstr++; - } - if ( dst.mask[i] == 'w' && instid == VS10_M3X4 ) - { - char oldval; - int oldindex; - vs10_transstring.append( "DP3 " ); - oldval = dst.mask[0]; - dst.mask[0] = 0; - dst.Translate(); - dst.mask[0] = oldval; - vs10_transstring.append( ".w, " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - oldindex = src[1].index; - src[1].index = src[1].index + 3; - src[1].Translate(); - src[1].index = oldindex; - vs10_transstring.append( ";\n" ); - ninstr++; - } - i++; - } - return ninstr; - } - else - { - ninstr = 0; - - char oldval; - int oldindex; - - vs10_transstring.append( "DP3 " ); - oldval = dst.mask[0]; - dst.mask[0] = 0; - dst.Translate(); - dst.mask[0] = oldval; - vs10_transstring.append( ".x, " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - src[1].Translate(); - vs10_transstring.append( ";\n" ); - ninstr++; - - vs10_transstring.append( "DP3 " ); - oldval = dst.mask[0]; - dst.mask[0] = 0; - dst.Translate(); - dst.mask[0] = oldval; - vs10_transstring.append( ".y, " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - oldindex = src[1].index; - src[1].index = src[1].index + 1; - src[1].Translate(); - src[1].index = oldindex; - vs10_transstring.append( ";\n" ); - ninstr++; - - if ( instid == VS10_M3X3 || instid == VS10_M3X4 ) - { - vs10_transstring.append( "DP3 " ); - oldval = dst.mask[0]; - dst.mask[0] = 0; - dst.Translate(); - dst.mask[0] = oldval; - vs10_transstring.append( ".z, " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - oldindex = src[1].index; - src[1].index = src[1].index + 2; - src[1].Translate(); - src[1].index = oldindex; - vs10_transstring.append( ";\n" ); - ninstr++; - } - - if ( instid == VS10_M3X4 ) - { - vs10_transstring.append( "DP3 " ); - oldval = dst.mask[0]; - dst.mask[0] = 0; - dst.Translate(); - dst.mask[0] = oldval; - vs10_transstring.append( ".w, " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - oldindex = src[1].index; - src[1].index = src[1].index + 3; - src[1].Translate(); - src[1].index = oldindex; - vs10_transstring.append( ";\n" ); - ninstr++; - } - return ninstr; - } - break; - case VS10_M4X3: - case VS10_M4X4: - if ( dst.mask[0] != 0 ) - { - ninstr = 0; - int i = 0; - while ( i < 4 && dst.mask[i] != 0 ) - { - if ( dst.mask[i] == 'x' ) - { - char oldval; - vs10_transstring.append( "DP4 " ); - oldval = dst.mask[0]; - dst.mask[0] = 0; - dst.Translate(); - dst.mask[0] = oldval; - vs10_transstring.append( ".x, " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - src[1].Translate(); - vs10_transstring.append( ";\n" ); - ninstr++; - } - if ( dst.mask[i] == 'y' ) - { - char oldval; - int oldindex; - vs10_transstring.append( "DP4 " ); - oldval = dst.mask[0]; - dst.mask[0] = 0; - dst.Translate(); - dst.mask[0] = oldval; - vs10_transstring.append( ".y, " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - oldindex = src[1].index; - src[1].index = src[1].index + 1; - src[1].Translate(); - src[1].index = oldindex; - vs10_transstring.append( ";\n" ); - ninstr++; - } - if ( dst.mask[i] == 'z' ) - { - char oldval; - int oldindex; - vs10_transstring.append( "DP4 " ); - oldval = dst.mask[0]; - dst.mask[0] = 0; - dst.Translate(); - dst.mask[0] = oldval; - vs10_transstring.append( ".z, " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - oldindex = src[1].index; - src[1].index = src[1].index + 2; - src[1].Translate(); - src[1].index = oldindex; - vs10_transstring.append( ";\n" ); - ninstr++; - } - if ( dst.mask[i] == 'w' && instid == VS10_M4X4 ) - { - char oldval; - int oldindex; - vs10_transstring.append( "DP4 " ); - oldval = dst.mask[0]; - dst.mask[0] = 0; - dst.Translate(); - dst.mask[0] = oldval; - vs10_transstring.append( ".w, " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - oldindex = src[1].index; - src[1].index = src[1].index + 3; - src[1].Translate(); - src[1].index = oldindex; - vs10_transstring.append( ";\n" ); - ninstr++; - } - i++; - } - return ninstr; - } - else - { - ninstr = 0; - - char oldval; - int oldindex; - - vs10_transstring.append( "DP4 " ); - oldval = dst.mask[0]; - dst.mask[0] = 0; - dst.Translate(); - dst.mask[0] = oldval; - vs10_transstring.append( ".x, " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - src[1].Translate(); - vs10_transstring.append( ";\n" ); - ninstr++; - - vs10_transstring.append( "DP4 " ); - oldval = dst.mask[0]; - dst.mask[0] = 0; - dst.Translate(); - dst.mask[0] = oldval; - vs10_transstring.append( ".y, " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - oldindex = src[1].index; - src[1].index = src[1].index + 1; - src[1].Translate(); - src[1].index = oldindex; - vs10_transstring.append( ";\n" ); - ninstr++; - - vs10_transstring.append( "DP4 " ); - oldval = dst.mask[0]; - dst.mask[0] = 0; - dst.Translate(); - dst.mask[0] = oldval; - vs10_transstring.append( ".z, " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - oldindex = src[1].index; - src[1].index = src[1].index + 2; - src[1].Translate(); - src[1].index = oldindex; - vs10_transstring.append( ";\n" ); - ninstr++; - - if ( instid == VS10_M4X4 ) - { - vs10_transstring.append( "DP4 " ); - oldval = dst.mask[0]; - dst.mask[0] = 0; - dst.Translate(); - dst.mask[0] = oldval; - vs10_transstring.append( ".w, " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - oldindex = src[1].index; - src[1].index = src[1].index + 3; - src[1].Translate(); - src[1].index = oldindex; - vs10_transstring.append( ";\n" ); - ninstr++; - } - return ninstr; - } - break; - case VS10_MAD: - vs10_transstring.append( "MAD " ); - dst.Translate(); - vs10_transstring.append( ", " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - src[1].Translate(); - vs10_transstring.append( ", " ); - src[2].Translate(); - ninstr = 1; - break; - case VS10_MAX: - vs10_transstring.append( "MAX " ); - dst.Translate(); - vs10_transstring.append( ", " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - src[1].Translate(); - ninstr = 1; - break; - case VS10_MIN: - vs10_transstring.append( "MIN " ); - dst.Translate(); - vs10_transstring.append( ", " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - src[1].Translate(); - ninstr = 1; - break; - case VS10_MOV: - if ( dst.type == TYPE_ADDRESS_REG ) - vs10_transstring.append( "ARL " ); - else - vs10_transstring.append( "MOV " ); - dst.Translate(); - vs10_transstring.append( ", " ); - src[0].Translate(); - ninstr = 1; - break; - case VS10_MUL: - vs10_transstring.append( "MUL " ); - dst.Translate(); - vs10_transstring.append( ", " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - src[1].Translate(); - ninstr = 1; - break; - case VS10_NOP: - return 0; - break; - case VS10_RCP: - vs10_transstring.append( "RCP " ); - dst.Translate(); - vs10_transstring.append( ", " ); - src[0].Translate(); - ninstr = 1; - break; - case VS10_RSQ: - vs10_transstring.append( "RSQ " ); - dst.Translate(); - vs10_transstring.append( ", " ); - src[0].Translate(); - ninstr = 1; - break; - case VS10_SGE: - vs10_transstring.append( "SGE " ); - dst.Translate(); - vs10_transstring.append( ", " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - src[1].Translate(); - ninstr = 1; - break; - case VS10_SLT: - vs10_transstring.append( "SLT " ); - dst.Translate(); - vs10_transstring.append( ", " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - src[1].Translate(); - ninstr = 1; - break; - case VS10_SUB: - vs10_transstring.append( "ADD " ); - dst.Translate(); - vs10_transstring.append( ", " ); - src[0].Translate(); - vs10_transstring.append( ", " ); - flag = src[1].sign; - if ( flag == -1 ) src[1].sign = 1; - else src[1].sign = -1; - src[1].Translate(); - src[1].sign = flag; - ninstr = 1; - break; - case VS10_COMMENT: - vs10_transstring.append( comment ); - return 0; - break; - case VS10_HEADER: - //vs10_transstring.append( "!!VP1.0\n" ); - return 0; - break; - case -1: - vs10_transstring.append( "\n" ); - return 0; - default: - errors.set( "VS10Inst::Translate() Internal Error: unknown instruction type\n" ); - } - - vs10_transstring.append( ";\n" ); - return ninstr; -} diff --git a/RenderSystems/GL/src/nvparse/vs1.0_inst.h b/RenderSystems/GL/src/nvparse/vs1.0_inst.h deleted file mode 100644 index bd20af64709..00000000000 --- a/RenderSystems/GL/src/nvparse/vs1.0_inst.h +++ /dev/null @@ -1,89 +0,0 @@ -#ifndef _VS10INST_H -#define _VS10INST_H - -#define VS10_ADD 1 -#define VS10_DP3 2 -#define VS10_DP4 3 -#define VS10_DST 4 -#define VS10_EXP 5 -#define VS10_EXPP 6 -#define VS10_FRC 7 -#define VS10_LIT 8 -#define VS10_LOG 9 -#define VS10_LOGP 10 -#define VS10_M3X2 11 -#define VS10_M3X3 12 -#define VS10_M3X4 13 -#define VS10_M4X3 14 -#define VS10_M4X4 15 -#define VS10_MAD 16 -#define VS10_MAX 17 -#define VS10_MIN 18 -#define VS10_MOV 19 -#define VS10_MUL 20 -#define VS10_NOP 21 -#define VS10_RCP 22 -#define VS10_RSQ 23 -#define VS10_SGE 24 -#define VS10_SLT 25 -#define VS10_SUB 26 -#define VS10_COMMENT 27 -#define VS10_HEADER 28 - -#define TYPE_TEMPORARY_REG 1 -#define TYPE_VERTEX_ATTRIB_REG 2 -#define TYPE_ADDRESS_REG 3 -#define TYPE_CONSTANT_MEM_REG 4 -#define TYPE_CONSTANT_A0_REG 5 -#define TYPE_CONSTANT_A0_OFFSET_REG 6 -#define TYPE_POSITION_RESULT_REG 7 -#define TYPE_COLOR_RESULT_REG 8 -#define TYPE_TEXTURE_RESULT_REG 9 -#define TYPE_FOG_RESULT_REG 10 -#define TYPE_POINTS_RESULT_REG 11 - -class VS10Reg { -public: -// VS10Reg(); -// VS10Reg(const VS10Reg &r); -// VS10Reg& operator=(const VS10Reg &r); - void Init(); - void Translate(); - int type; - int index; - int sign; - char mask[4]; - - int ValidateIndex(); -}; - -typedef class VS10Inst { -public: - ~VS10Inst(); - VS10Inst(); - VS10Inst(int currline); - VS10Inst(const VS10Inst &inst); - VS10Inst& operator=(const VS10Inst &inst); - VS10Inst(int currline, int inst); - VS10Inst(int currline, int inst, char *cmt); - VS10Inst(int currline, int inst, VS10Reg dreg, VS10Reg src0); - VS10Inst(int currline, int inst, VS10Reg dreg, VS10Reg src0, VS10Reg src1); - VS10Inst(int currline, int inst, VS10Reg dreg, VS10Reg src0, VS10Reg src1, VS10Reg src2); - void Validate( int &vsflag ); - int Translate(); - VS10Reg dst; - VS10Reg src[3]; -private: - int line; - int instid; - char *comment; - void ValidateRegIndices(); - void ValidateDestMask(); - void ValidateSrcMasks(); - void ValidateDestWritable(); - void ValidateSrcReadable(); - void ValidateReadPorts(); - -} *VS10InstPtr; - -#endif diff --git a/RenderSystems/GL/src/nvparse/vs1.0_inst_list.cpp b/RenderSystems/GL/src/nvparse/vs1.0_inst_list.cpp deleted file mode 100644 index a426f6df4a4..00000000000 --- a/RenderSystems/GL/src/nvparse/vs1.0_inst_list.cpp +++ /dev/null @@ -1,292 +0,0 @@ -#include "vs1.0_inst_list.h" -#include -#include -#include -#include -#include "nvparse_errors.h" -#include "nvparse_externs.h" -#include - -using namespace std; - -extern string vs10_transstring; - -#define MAX_NUM_INSTRUCTIONS 128 -#define INSTRUCTION_LIST_INC 128 - -VS10InstList::VS10InstList() -{ - size = 0; - max = INSTRUCTION_LIST_INC; - list = new VS10Inst[max]; -} - -VS10InstList::~VS10InstList() -{ - delete [] list; -} - -int VS10InstList::Size() -{ - return size; -} - -VS10InstList& VS10InstList::operator+=(VS10InstPtr t) -{ - if (size == max) { - // Extend list size by increment amount. - VS10InstPtr newlist; - max += INSTRUCTION_LIST_INC; - newlist = new VS10Inst[max]; - for ( int i = 0; i < size; i++ ) - newlist[i] = list[i]; - delete [] list; - list = newlist; - } - list[size++] = *t; - return *this; -} - -void VS10InstList::Translate() -{ - int ntranslated = 0; - - vs10_transstring.append( "!!VP1.0\n" ); - for (int i = 0; i < size; i++) - { - ntranslated += list[i].Translate(); - } - vs10_transstring.append( "END\n" ); - - if ( ntranslated > 128 ) - { - char str[256]; - sprintf( str, "Vertex Shader had more than 128 instructions. (Converted to: %d)\n", ntranslated ); - errors.set( str ); - } - //fprintf( stderr, "Converted vertex shader to vertex program with %d instructions.\n\n", ntranslated ); -} - -void VS10InstList::Validate() -{ - int vsflag = 0; - for ( int i = 0; i < size; i++ ) - { - list[i].Validate( vsflag ); - } -} - - - -namespace -{ - void LoadProgram( GLenum target, GLuint id, const char *instring ); - GLint vpid; -} - - - -bool is_vs10(const char *s) -{ - int len; - char *temp; - bool vshader_flag; - - temp = NULL; - len = strlen(s); - if ( len > 0 ) - temp = new char [len+1]; - for ( int k = 0; k < len; k++ ) - { - temp[k] = (char) tolower( (char) s[k] ); - } - if ( len == 0 ) - vshader_flag = false; - else - { - vshader_flag = ( NULL != strstr(temp, "vs.1.0") ) || - ( NULL != strstr(temp, "vs.1.1") ); - delete [] temp; - } - return vshader_flag; -} - -bool vs10_init_more() -{ - static bool vpinit = false; - if (vpinit == false ) - { - /* - if(! glh_init_extensions("GL_NV_vertex_program")) - { - errors.set("unable to initialize GL_NV_vertex_program"); - return false; - } - else - { - */ - vpinit = true; - /* - } - */ - } - - glGetIntegerv( GL_VERTEX_PROGRAM_BINDING_NV, &vpid ); - - if ( vpid == 0 ) - { - char str[128]; - sprintf( str, "No vertex program id bound for nvparse() invocation. Bound id = %d\n", (int)vpid ); - errors.set( str ); - return false; - } - errors.reset(); - line_number = 1; - vs10_transstring = ""; - return true; -} - -void vs10_load_program() -{ - // Only load the program if no errors occurred. - if ( errors.get_num_errors() == 0 ) - LoadProgram( GL_VERTEX_PROGRAM_NV, vpid, vs10_transstring.c_str() ); -} - - -namespace -{ - //.----------------------------------------------------------------------------. - //| Function : LoadProgram | - //| Description: Load a program into GL, and report any errors encountered. | - //.----------------------------------------------------------------------------. - void LoadProgram( GLenum target, GLuint id, const char *instring ) - { - GLint errPos; - GLenum errCode; - - int len = strlen(instring); - glLoadProgramNV( target, id, len, (const GLubyte *) instring ); - if ( (errCode = glGetError()) != GL_NO_ERROR ) - { - glGetIntegerv( GL_PROGRAM_ERROR_POSITION_NV, &errPos ); - - int nlines = 1; - int nchar = 1; - int i; - for ( i = 0; i < errPos; i++ ) - { - if ( instring[i] == '\n' ) - { - nlines++; - nchar = 1; - } - else - { - nchar++; - } - } - int start = 0; - int end = 0; - int flag = ((instring[errPos]==';') | (instring[errPos-1]==';')) ? 1 : 0; - for ( i = errPos; i >= 0; i-- ) - { - start = i; - if ( flag && (start >= errPos-1) ) - continue; - if ( instring[i] == ';' ) - { - if ( !flag ) - { - start = i+1; - if ( instring[start] == '\n' ) - start++; - } - break; - } - } - for ( i = errPos; i < len; i++ ) - { - end = i; - if ( instring[i] == ';' && end > start) - { - break; - } - } - if ( errPos - start > 30 ) - { - start = errPos - 30; - } - if ( end - errPos > 30 ) - { - end = errPos + 30; - } - - char substring[96]; - memset( substring, 0, 96 ); - strncpy( substring, &(instring[start]), end-start+1 ); - char str[256]; - //sprintf( str, "error at line %d character %d\n \"%s\"\n", nlines, nchar, substring ); - sprintf( str, "error at line %d character %d\n\"%s\"\n", nlines, nchar, substring ); - int width = errPos-start; - for ( i = 0; i < width; i++ ) - { - strcat( str, " " ); - } - strcat( str, "|\n" ); - for ( i = 0; i < width; i++ ) - { - strcat( str, " " ); - } - strcat( str, "^\n" ); - - errors.set( str ); - } - } -} - -/* - else if ( is_vs10(instring) ) - { - if (vpinit == 0 ) - { - if(! glh_init_extensions("GL_NV_vertex_program")) - { - errors.set("unable to initialize GL_NV_vertex_program"); - free(instring); - return; - } - else - { - vpinit = 1; - } - } - - if ( glGetError() != GL_NO_ERROR ) - { - errors.set( "Previous GL_ERROR prior to vertex shader parsing.\n" ); - } - - int vpid; - glGetIntegerv( GL_VERTEX_PROGRAM_BINDING_NV, &vpid ); - - if ( vpid == 0 ) - { - char str[128]; - sprintf( str, "No vertex program id bound for nvparse() invocation. Bound id = %d\n", vpid ); - errors.set( str ); - } - else - { - errors.reset(); - line_number = 1; - vs10_init(instring); - vs10_transstring = ""; - vs10_parse(); - //fprintf( stderr, "Converted text:\n%s\n\n\n", vs10_transstring.c_str() ); - LoadProgram( GL_VERTEX_PROGRAM_NV, vpid, (char *) vs10_transstring.c_str() ); - } - - } - -*/ diff --git a/RenderSystems/GL/src/nvparse/vs1.0_inst_list.h b/RenderSystems/GL/src/nvparse/vs1.0_inst_list.h deleted file mode 100644 index f7fc5ba4552..00000000000 --- a/RenderSystems/GL/src/nvparse/vs1.0_inst_list.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef _VS10_H -#define _VS10_H - -#define WRITEMASK_X 0x01 -#define WRITEMASK_Y 0x02 -#define WRITEMASK_Z 0x04 -#define WRITEMASK_W 0x08 - -#include "vs1.0_inst.h" - -typedef class VS10InstList { -public: - VS10InstList(); - ~VS10InstList(); - int Size(); - VS10InstList& operator+=(VS10InstPtr t); - void Validate(); - void Translate(); -private: - VS10InstPtr list; - int size; - int max; -} *VS10InstListPtr; - -#endif diff --git a/RenderSystems/GL/src/nvparse/vs1.0_tokens.l b/RenderSystems/GL/src/nvparse/vs1.0_tokens.l deleted file mode 100644 index d468866efc8..00000000000 --- a/RenderSystems/GL/src/nvparse/vs1.0_tokens.l +++ /dev/null @@ -1,2939 +0,0 @@ -%option prefix="vs10_" - -%x INCLUDE DEFINE DEFSTR DEFSPACE SKIPLINE EATCOMMENT EATSTRING SAVELINE -%x MACRONAME MACROBODY MACROPARM EATMACRO EATDEFINE MODIFIER MACROPARMSTART -%x IFDEFNAME IFDEFBODY ENDMACRO MACROPARMEND - -%{ - -#include -#include -#ifdef _WIN32 -#include -# ifdef __GNUC__ -# include -# include -# endif -#else -#include -#include -#define _stat stat -#define _open open -#define _O_RDONLY O_RDONLY -#define _fstat fstat -#define _close close -#define stricmp strcasecmp - -#endif -#include -#include -#include -#include "macro.h" -#include "nvparse_errors.h" -#include "vs1.0_inst_list.h" -#include "_vs1.0_parser.h" -#define yylineno line_number -#include "nvparse_externs.h" -#define YY_NO_UNPUT - -int line_incr; -void LexError(const char *format, ...); -void LexWarning(const char *format, ...); -char *ReadTextFile(const char * filename); - -unsigned int MakeRegisterMask(char *findName); -unsigned int FindSwizzleValue(char *swizzleText); - - -enum ERROR_VALUES { - ERROR_NONE = 0, - ERROR_MEMORY_ALLOC, - ERROR_FILE_OPEN, - ERROR_UNSUCCESSFUL_ASSEMBLE, - ERROR_TOO_MANY_PARMS, - ERROR_DEST_WRITE, - ERROR_LIST_OPEN, - ERROR_DEST_OPEN, - ERROR_NO_ARGUMENTS, - ERROR_MACRO_OVERRUN -}; - - - -//extern void GenSwitchFileNames(char *fileName); -//extern unsigned int gLinesAssembled; -unsigned int gLinesAssembled; - -#define YY_INPUT(buf,result,max_size) \ -{ \ - int c = *myin++; \ - result = (c == 0) ? YY_NULL : (buf[0] = c, 1); \ -} - -#define SAFEDELETEARRAY(x) if ((x) != NULL) \ - delete [] (x) -#define SAFEFREE(x) if ((x) != NULL) \ - free((x)) - -#define MAXREPLACESTRING 255 - -char gReplaceText[MAXREPLACESTRING+1]; - -// -// forward prototypes for macro functions -// -void MacroIncFunction(char *, unsigned int *, char **); -void MacroDecFunction(char *, unsigned int *, char **); -void MacroAddFunction(char *, unsigned int *, char **); -void MacroSubFunction(char *, unsigned int *, char **); - -MACROFUNCTIONS gMacroFunctions[] = { - { "inc(", MacroIncFunction }, - { "dec(", MacroDecFunction }, - { "add(", MacroAddFunction }, - { "sub(", MacroSubFunction } -}; - -#define NUM_MACRO_FUNCTIONS (sizeof(gMacroFunctions) / sizeof(MACROFUNCTIONS)) - -#define MAX_INCLUDE_DEPTH 1024 -typedef struct INCLUDEINFO -{ - char *fileName; - unsigned int lineNo; - YY_BUFFER_STATE buffer; - MACROENTRY *lastInvokeMacro; // save off in case nested macros. - MACROENTRY *lastParseMacro; // recursive macros - MACROTEXT *lastMacroLineParse; // save off for recursive lines of macros working on. - bool lastbInsideMacro; // save off for recursive macros - bool lastbInsideDefine; // save off for recursive macros/defines - bool lastbInsideInclude; - bool lastbProcessingIFDEF; // save off #define information -// FILE *fileHandle; - char *prevString; - char *nextString; -} INCLUDEINFO; - -INCLUDEINFO gIncludeStack[MAX_INCLUDE_DEPTH]; -int gIncludeStackIndex = 0; - -IFDEFINFO gIfDefStack[MAX_IFDEF_DEPTH]; -int gIfDefStackIndex = 0; - -unsigned int &base_linenumber = gIncludeStack[0].lineNo; - -bool gbInsideInclude = false; -bool gbProcessingBuiltIn = false; -bool gbProcessingDefine = false; -unsigned int gCountParen = 0; - -bool gbProcessingIFDEF = false; -bool gbIFDEF = false; -bool gbCompareDefine = false; -unsigned int gIfDefStartLine; - - -MACROENTRY *gLastMacro; -MACROENTRY *gInvokeMacro; -MACROENTRY *gTempMacro; // until all the parameters are read -MACROENTRY *FindMacro(char *macroName); -MACROENTRY *FindNMacro(char *macroName, unsigned int sLen); - -MACROFUNCTIONPTR gMacroCallFunction; - -const char *builtInMacros = "macro m3x2 reg1, reg2, reg3\n" - " dp3 %reg1.x, %reg2, %reg3\n" - " dp3 %reg1.y, %reg2, %inc(%reg3)\n" - "endm"; - -// -// local prototypes -// -void CleanUp(); -void ReplaceMacroParms(char *srcLine, char *destLine, - MACROENTRY *srcParms, MACROENTRY *invParms); - -MACROTEXT *SaveMacroText(char *srcText, MACROTEXT *lastMacroText); -void FreeMacroEntry(MACROENTRY *macEntry); -void EndMacroParms(); -char *FindAlphaNum(char *srcStr, unsigned int *sLen); -void DebugUnhandledState(); - - -unsigned int gCommentStartLine; -unsigned int gMacroStartLine; - -char *gCurFileName = NULL; - -#define MAXSAVELINE 4095 - -char gSaveLine[MAXSAVELINE+1]; -char gMacroLine[MAXSAVELINE+1]; - -#if 1 -#ifdef _DEBUG -#define ECHO DebugUnhandledState(); -#else -#define ECHO -#endif -#endif - -bool gbInsideMacro = false; // flag if we are doing a macro replace or not. -bool gbTempInsideMacro = false; -unsigned int gInvokeState = INITIAL; - - -MACROENTRY *gParseMacro; // which source macro entry we are using -MACROENTRY *gTempParseMacro; // temporary holder until parameters are received. -MACROTEXT *gMacroLineParse; // which line we are currently parsing inside the macro invocation - -enum OPCODETYPE -{ - TYPE_NONE = 0, - TYPE_VERTEX_SHADER = 1, - TYPE_PIXEL_SHADER = 2 -}; -typedef struct OPCODEMAP -{ - const char *string; // string for opcode - int tokenName; // name of the corresponding token - int numArguments; // number of arguments for opcode - float version; // minimum version supported in. - int opcodeTypeFlags; // whether opcode can be used in vertex shader or pixel shader - bool opcodeModify; // if opcode modifiers can be used - bool textureOpcode; // only outputs to the texture unit -} OPCODEMAP; - -#ifndef TRUE -#define TRUE true -#endif -#ifndef FALSE -#define FALSE false -#endif - -OPCODEMAP theOpcodes[] = { - { "add", ADD_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, - { "dp3", DP3_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, - { "dp4", DP4_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "dst", DST_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "exp", EXP_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "expp", EXPP_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "frc", FRC_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "lit", LIT_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "log", LOG_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "logp", LOGP_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "m3x2", M3X2_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "m3x3", M3X3_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "m3x4", M3X4_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "m4x3", M4X3_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "m4x4", M4X4_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "mad", MAD_INSTR, 4, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, - { "max", MAX_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "min", MIN_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "mov", MOV_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, - { "mul", MUL_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, - { "nop", NOP_INSTR, 0, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, - { "rcp", RCP_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "rsq", RSQ_INSTR, 2, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "sge", SGE_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "slt", SLT_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER, FALSE, FALSE }, - { "sub", SUB_INSTR, 3, 1.0f, TYPE_VERTEX_SHADER | TYPE_PIXEL_SHADER, TRUE, FALSE }, -}; - -#define NUMOPCODES (sizeof(theOpcodes) / sizeof(OPCODEMAP)) -OPCODEMAP *FindOpcode(char *findName); - - -%} - -digits ([0-9]+) -digit ([0-9]) -pt "." -sign [+-]? -exponent ([eE]{sign}{digits}) -alpha [a-zA-Z_] -alphadigs [a-zA-Z0-9_] -notAlphaDigs ([^a-zA-Z0-9_]) - -identifier {alpha}{alphadigs}* - - -%% - -.*\n { - gbProcessingDefine = false; - gSaveLine[0] = '\0'; - strncat(gSaveLine, yytext, MAXSAVELINE); -// GenDebugLine(); - if (gbProcessingIFDEF && (gbCompareDefine != gbIFDEF)) - { - BEGIN(IFDEFBODY); - } - else - { - BEGIN(INITIAL); - } - yyless(0); -} - -.* { - gbProcessingDefine = false; - gSaveLine[0] = '\0'; - strncat(gSaveLine, yytext, MAXSAVELINE); -// GenDebugLine(); - if (gbProcessingIFDEF && (gbCompareDefine != gbIFDEF)) - { - BEGIN(IFDEFBODY); - } - else - { - BEGIN(INITIAL); - } - yyless(0); -} - -a{digits}[ \t]*[\n]? { -// fprintf( stderr, "%s", yytext ); - vs10_lval.reg.type = TYPE_ADDRESS_REG; - vs10_lval.reg.index = atoi(&yytext[1]); - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return REGISTER; -} - -v{digits}[ \t]*[\n]? { -// fprintf( stderr, "%s", yytext ); - vs10_lval.reg.type = TYPE_VERTEX_ATTRIB_REG; - vs10_lval.reg.index = atoi(&yytext[1]); - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return REGISTER; -} - -r{digits}[ \t]*[\n]? { -// fprintf( stderr, "%s", yytext ); - vs10_lval.reg.type = TYPE_TEMPORARY_REG; - vs10_lval.reg.index = atoi(&yytext[1]); - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return REGISTER; -} - -c{digits}[ \t]*[\n]? { -// fprintf( stderr, "%s", yytext ); - vs10_lval.reg.type = TYPE_CONSTANT_MEM_REG; - vs10_lval.reg.index = atoi(&yytext[1]); - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return REGISTER; -} - -oT{digits}[ \t]*[\n]? { -// fprintf( stderr, "%s", yytext ); - vs10_lval.reg.type = TYPE_TEXTURE_RESULT_REG; - vs10_lval.reg.index = atoi(&yytext[2]); - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return REGISTER; -} - -oD{digits}[ \t]*[\n]? { -// fprintf( stderr, "%s", yytext ); - vs10_lval.reg.type = TYPE_COLOR_RESULT_REG; - vs10_lval.reg.index = atoi(&yytext[2]); - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return REGISTER; -} - -oFog[ \t]*[\n]? { -// fprintf( stderr, "%s", yytext ); - vs10_lval.reg.type = TYPE_FOG_RESULT_REG; - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return REGISTER; -} - -oPos[ \t]*[\n]? { -// fprintf( stderr, "%s", yytext ); - vs10_lval.reg.type = TYPE_POSITION_RESULT_REG; - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return REGISTER; -} - -oPts[ \t]*[\n]? { -// fprintf( stderr, "%s", yytext ); - vs10_lval.reg.type = TYPE_POINTS_RESULT_REG; - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return REGISTER; -} - -[a-zA-Z][a-zA-Z0-9]+[ \t\n_] { - - unsigned int offset; - - offset = strcspn(yytext, " \t\n_"); - yyless(offset); - - OPCODEMAP *opcodeMap = FindOpcode(yytext); - if ( opcodeMap != NULL ) - { -// fprintf( stderr, "%s\t", opcodeMap->string ); - return( opcodeMap->tokenName ); - } - else - { - gTempParseMacro = FindMacro(yytext); - - if (gTempParseMacro != NULL) - { - if (gIncludeStackIndex >= MAX_INCLUDE_DEPTH ) - { - LexError("macros nested too deeply"); - exit( 1 ); - } - - if (gTempParseMacro->firstMacroLines != NULL) - { - - gTempMacro = (MACROENTRY *)malloc(sizeof(MACROENTRY)); - if (gTempMacro == NULL) - { - LexError("Out of memory allocating MACROENTRY structure.\n"); - } - else - { - - gTempMacro->next = NULL; - gTempMacro->prev = NULL; - gTempMacro->macroName = NULL; - gTempMacro->firstMacroParms = NULL; - gTempMacro->lastMacroParms = NULL; - gTempMacro->firstMacroLines = NULL; - gTempMacro->lastMacroLines = NULL; - gTempMacro->numParms = 0; - gTempMacro->nLines = 0; - - gbTempInsideMacro = true; // flag we are currently doing a macro replace. - gInvokeState = YYSTATE; - if (gTempParseMacro->numParms > 0) - { - BEGIN(MACROPARMSTART); - } - else - { - EndMacroParms(); - gbTempInsideMacro = false; // no longer waiting for macro invocation - } - - - } - } - } - else - { -// fprintf( stderr, "Opcode: \"%s\" not found\n", yytext ); - REJECT; - } - } - - //unsigned int offset; - // - //INSTRMAP *opcodeMap; - // - //offset = strcspn(yytext, " \t\n_"); - //yyless(offset); - //opcodeMap = FindInstruction(yytext); - //if (opcodeMap == NULL) - //{ - // REJECT; - //} - // - //yylval.opcodeInfo.opcodeMap = opcodeMap; - // - //return OPCODE; -} - - -";".* { -// fprintf( stderr, "%s", yytext ); - char *cmt = new char[yyleng+1]; - strncpy( cmt, yytext, yyleng ); - cmt[0] = '#'; - cmt[yyleng] = '\0'; - vs10_lval.comment = cmt; - return COMMENT; -} - -"//".* { -// fprintf( stderr, "%s", yytext ); - char *cmt = new char[yyleng+1]; - strncpy( cmt+1, yytext+1, yyleng-1 ); - cmt[0] = '#'; - cmt[1] = ' '; - cmt[yyleng] = '\0'; - vs10_lval.comment = cmt; - return COMMENT; -} - -"+"[ \t]*\n { - fprintf( stderr, "COISSUE found\n" ); - yyless(yyleng-1); - //return COISSUE; -} - -^[ \t]*"+"[ \t]* { - fprintf( stderr, "COISSUE found\n" ); - //return COISSUE; -} - -"/*" { - gCommentStartLine = yylineno; - yyless(0); - BEGIN(EATCOMMENT); -} - -"#include"[ \t]+ { - BEGIN(INCLUDE); -} - -[^ \t].*\n { /* got the include file name */ - -// FILE *newyyin; -char *newyyin; - char incFileName[1024]; - unsigned long sLen; - bool validFileName; - - if ( gIncludeStackIndex >= MAX_INCLUDE_DEPTH ) - { - LexError("Includes nested too deeply, aborting\n"); - exit( 1 ); - } - -// GenDebugLine(); -// GenListString(); - yylineno++; - gLinesAssembled++; - - validFileName = true; - // zap "" and <> - if ((yytext[0] == '"') || (yytext[0] == '<')) - { - char *endQuote; - endQuote = strchr(&yytext[1], yytext[0]); - sLen = (endQuote - yytext)-1; - if (endQuote == NULL) - { - LexError("Unable to open include file %s\n", incFileName); - BEGIN(INITIAL); - validFileName = false; - } - else - { - incFileName[0] ='\0'; - strncat(incFileName, &yytext[1], sLen); - } - } - else - { - strcpy(incFileName, yytext); - } - - if (validFileName) - { - sLen = strlen(incFileName); - if ((incFileName[sLen-1] == '"') || (incFileName[sLen-1] == '>')) - { - incFileName[sLen-1] = '\0'; - } - - - newyyin = ReadTextFile( incFileName ); -// newyyin = fopen( incFileName, "r" ); - - if ( ! newyyin ) - { - LexError("Unable to open include file %s\n", incFileName); - BEGIN(SAVELINE); - } - else - { - gIncludeStack[gIncludeStackIndex].fileName = gCurFileName; - gIncludeStack[gIncludeStackIndex].lineNo = yylineno; -// gIncludeStack[gIncludeStackIndex].fileHandle = yyin; - gIncludeStack[gIncludeStackIndex].prevString = myin; - gIncludeStack[gIncludeStackIndex].nextString = newyyin; - gIncludeStack[gIncludeStackIndex].lastInvokeMacro = gInvokeMacro; - gIncludeStack[gIncludeStackIndex].lastParseMacro = gParseMacro; - gIncludeStack[gIncludeStackIndex].lastMacroLineParse = gMacroLineParse; - gIncludeStack[gIncludeStackIndex].lastbInsideMacro = gbInsideMacro; - gIncludeStack[gIncludeStackIndex].lastbInsideInclude = gbInsideInclude; - gIncludeStack[gIncludeStackIndex].buffer = YY_CURRENT_BUFFER; - gIncludeStack[gIncludeStackIndex].lastbProcessingIFDEF = gbProcessingIFDEF; - gIncludeStackIndex++; - - gbProcessingIFDEF = false; - - gCurFileName = strdup(incFileName); -// yyin = newyyin; - myin = newyyin; - -// GenSwitchFileNames(gCurFileName); - - yylineno = 1; - - yy_switch_to_buffer(yy_create_buffer( yyin, YY_BUF_SIZE ) ); - - gbInsideInclude = true; - - BEGIN(SAVELINE); - } - } -} - -<> { - LexError("End of file reached before end of comment started on line %d.\n", gCommentStartLine); - BEGIN(INITIAL); -} - -.*\n { - char *endComment; - unsigned int keepSize; - - strcpy(gSaveLine, yytext); - endComment = strstr(yytext, "*/"); - - char *cmt; - if (endComment != NULL) - { - keepSize = (endComment - yytext+2); - yyless(keepSize); - BEGIN(INITIAL); - - if ( yytext[0] == '/' && yytext[1] == '*' ) - { - cmt = new char[yyleng]; - strncpy( cmt+3, yytext+2, yyleng-2 ); - cmt[0] = '#'; - cmt[1] = ' '; - cmt[2] = ' '; - cmt[yyleng-1] = '\0'; - } - else - { - cmt = new char[yyleng]; - strncpy( cmt+1, yytext, yyleng-2 ); - cmt[0] = '#'; - cmt[yyleng-1] = '\0'; - } - vs10_lval.comment = cmt; - return COMMENT; - } - else - { -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; - - if ( yytext[0] == '/' && yytext[1] == '*' ) - { - cmt = new char[yyleng+2]; - strncpy( cmt+3, yytext+2, yyleng-2 ); - cmt[0] = '#'; - cmt[1] = ' '; - cmt[2] = ' '; - cmt[yyleng+1] = '\0'; - } - else - { - cmt = new char[yyleng+2]; - strncpy( cmt+1, yytext, yyleng ); - cmt[0] = '#'; - cmt[yyleng+1] = '\0'; - } - vs10_lval.comment = cmt; - return COMMENT; - } -} - -<> { - LexError("#define was incomplete before end of file\n"); - BEGIN(INITIAL); -} - -<> { - LexError("#define was incomplete before end of file\n"); - BEGIN(INITIAL); -} - -<> { - LexError("#define was incomplete before end of file\n"); - BEGIN(INITIAL); -} - -<> { - LexError("#include was incomplete before end of file\n"); - BEGIN(INITIAL); -} - -<> { - LexError("End of file reached before end of #define or endm was found, macro started on line %d.\n", gMacroStartLine); - BEGIN(INITIAL); -} - -<> { - LexError("End of file reached before #endif found, macro started on line %d.\n", gIfDefStartLine); - BEGIN(INITIAL); -} - -\n { - LexError("#define was incomplete before end of line\n"); - BEGIN(SAVELINE); -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; -} - -\n { - LexError("#define was incomplete before end of line\n"); - BEGIN(SAVELINE); -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; -} - -\n { - LexError("#define was incomplete before end of line\n"); - BEGIN(SAVELINE); -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; -} - -"#ifdef"[ \t]+ { - if (gIfDefStackIndex >= MAX_IFDEF_DEPTH) - { - LexError("Out of stack space for #ifdef, aborting.\n"); - exit( 1 ); - } - else - { - gIfDefStack[gIfDefStackIndex].lastbProcessingIFDEF = gbProcessingIFDEF; - gIfDefStack[gIfDefStackIndex].lastbIFDEF = gbIFDEF; - gIfDefStack[gIfDefStackIndex].lastbCompareDefine = gbCompareDefine; - gIfDefStack[gIfDefStackIndex].lastIfDefStartLine = gIfDefStartLine; - gIfDefStackIndex++; - gIfDefStartLine = yylineno; - - gbCompareDefine = true; - BEGIN(IFDEFNAME); - } -} - -"#ifndef"[ \t]+ { - if (gIfDefStackIndex >= MAX_IFDEF_DEPTH) - { - LexError("Out of stack space for #ifdef, aborting.\n"); - exit( 1 ); - } - else - { - gIfDefStack[gIfDefStackIndex].lastbProcessingIFDEF = gbProcessingIFDEF; - gIfDefStack[gIfDefStackIndex].lastbIFDEF = gbIFDEF; - gIfDefStack[gIfDefStackIndex].lastbCompareDefine = gbCompareDefine; - gIfDefStack[gIfDefStackIndex].lastIfDefStartLine = gIfDefStartLine; - gIfDefStackIndex++; - gIfDefStartLine = yylineno; - - gbCompareDefine = false; - BEGIN(IFDEFNAME); - } -} - -"#else"[ \t]*((";"|"//").*)* { - if (!gbProcessingIFDEF) - { - LexError("Unexpected #else found at line %d, skipping.\n", yylineno); - } - else - { - gbCompareDefine = !gbCompareDefine; - BEGIN(INITIAL); - } -} - -.*\n { - char *defineName; - unsigned int sLen; - - - defineName = FindAlphaNum(yytext, &sLen); - if (defineName == NULL) - { - defineName = strdup(yytext); - defineName[yyleng-1] = '\0'; // kill \n - LexWarning("Mangled name (%s) for #ifdef, assuming not defined.\n", defineName); - free(defineName); - gbIFDEF = false; - } - else - { - if (FindNMacro(defineName, sLen) != NULL) - { - gbIFDEF = true; - } - else - { - gbIFDEF = false; - } - } - - gbProcessingIFDEF = true; - if (gbIFDEF != gbCompareDefine) - { - BEGIN(IFDEFBODY); - } - else - { - BEGIN(SAVELINE); - } - -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; -} - -[ \t]*"#endif"[ \t]*((";"|"//").*)* { - if (!gbProcessingIFDEF) - { - LexError("Unexpected #endif found at line %d, skipping.\n", yylineno); - } - else - { - gIfDefStackIndex--; - gbProcessingIFDEF = gIfDefStack[gIfDefStackIndex].lastbProcessingIFDEF; - gbIFDEF = gIfDefStack[gIfDefStackIndex].lastbIFDEF; - gbCompareDefine = gIfDefStack[gIfDefStackIndex].lastbCompareDefine; - gIfDefStartLine = gIfDefStack[gIfDefStackIndex].lastIfDefStartLine; - - } - - if (YYSTATE == IFDEFBODY) - { - strncpy(gSaveLine, yytext, MAXSAVELINE); - } - - BEGIN(ENDMACRO); - -} - -.* { - LexWarning("Garbage at end of #endif or endm will be ignored.\n"); -} - -\n { - BEGIN(SAVELINE); - return '\n'; -} - -<> { - BEGIN(INITIAL); -} - -.* { - // eat line, because we are not in a TRUE #ifdef, or FALSE #ifndef - strncpy(gSaveLine, yytext, MAXSAVELINE); -} - -\n { - strcat(gSaveLine, yytext); -// GenDebugLine(); -// GenListString(); - yylineno++; - gLinesAssembled++; -} - -"#define"[ \t]+ { - gbProcessingDefine = true; - gMacroStartLine = yylineno; - gCountParen = 0; - BEGIN(MACRONAME); -} - -.*\n { - BEGIN(SAVELINE); -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; -} - -"vs."{digits}"."{digits}[ \t]*[\n]? { -// unsigned int majorVersion; -// unsigned int minorVersion; -// int minorOffset; -// -// -// majorVersion = (unsigned int)(atoi(&yytext[3])); -// // skip "ps." + second '.' -// minorOffset = strcspn(&yytext[3], ".")+4; -// minorVersion = (unsigned int)(atoi(&yytext[minorOffset])); -// yylval.ival = D3DVS_VERSION(majorVersion, minorVersion); -// - -// fprintf( stderr, "%s", yytext ); - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - return VERTEX_SHADER; -} - -{digits} { -// fprintf( stderr, "%s", yytext ); - vs10_lval.ival = atoi(yytext); - return INTVAL; -} - - -{pt} { - BEGIN(MODIFIER); -//fprintf( stderr, "." ); - return yytext[0]; -} - -[w-z][w-z][w-z][w-z][ \t]*[\n]? { -// fprintf( stderr, "%s", yytext ); - BEGIN(INITIAL); - - vs10_lval.mask[0] = tolower(yytext[0]); - vs10_lval.mask[1] = tolower(yytext[1]); - vs10_lval.mask[2] = tolower(yytext[2]); - vs10_lval.mask[3] = tolower(yytext[3]); - - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - - return XYZW_MODIFIER; - -#if 0 - char temp[6]; - - temp[0] = '\0'; - strncat(temp, yytext, 4); - strlwr(temp); - vs10_lval.lval = FindSwizzleValue(temp); - - BEGIN(INITIAL); - return SWIZZLE_MODIFIER; -#endif - -} - -[w-z][w-z]?[w-z]?[w-z]?[ \t]*[\n]? { -// fprintf( stderr, "%s", yytext ); - BEGIN(INITIAL); - - int validLen = strspn(yytext, "xyzw"); - int i; - for ( i = 0; i < validLen; i++ ) - vs10_lval.mask[i] = tolower( yytext[i] ); - while ( i < 4 ) - { - vs10_lval.mask[i] = 0; - i++; - } - - if ( yytext[yyleng-1] == '\n' ) - line_incr = 1; - - return XYZW_MODIFIER; - -#if 0 - //char temp[6]; - char *temp = new char[6]; - unsigned int registerMask; - unsigned int validLen; - - temp[0] = '\0'; - validLen = strspn(yytext, "xyzw"); - strncat(temp, yytext, validLen); - for ( int i = 0; i < validLen; i++ ) - temp[i] = tolower( temp[i] ); - registerMask = MakeRegisterMask(temp); - - if (registerMask != 0) - { - //vs10_lval.sval = temp; - vs10_lval.lval = registerMask; - BEGIN(INITIAL); - return XYZW_MODIFIER; - } - else - { - //vs10_lval.sval = temp; - vs10_lval.lval = FindSwizzleValue(temp); - BEGIN(INITIAL); - return SWIZZLE_MODIFIER; - } -#endif -} - -. { - BEGIN(INITIAL); - yyless(0); -} - -[^ \t(]+ { - /* setup and save off #define/macro name */ - if (FindMacro(yytext) != NULL) - { - LexWarning("Redefinition of #define/macro %s, ignoring.\n", yytext); - if (gbProcessingDefine) - { - BEGIN(EATDEFINE); - } - else - { - BEGIN(EATMACRO); - } - } - else - { - - BEGIN(MACROPARMSTART); - // %%%%% This should be setup to use memory pools - gTempMacro = (MACROENTRY *)malloc(sizeof(MACROENTRY)); - if (gTempMacro == NULL) - { - LexError("Out of memory for macro table.\n"); - if (gbProcessingDefine) - { - BEGIN(EATDEFINE); - } - else - { - BEGIN(EATMACRO); - } - } - else - { - gTempMacro->prev = gLastMacro; - gTempMacro->next = NULL; - - gTempMacro->firstMacroParms = NULL; - gTempMacro->lastMacroParms = NULL; - gTempMacro->firstMacroLines = NULL; - gTempMacro->lastMacroLines = NULL; - gTempMacro->numParms = 0; - gTempMacro->bIsDefine = gbProcessingDefine; - gTempMacro->nLines = 0; - - if (gCurFileName != NULL) - { - gTempMacro->fileName = strdup(gCurFileName); - } - else - { - gTempMacro->fileName = NULL; - } - - gTempMacro->lineNo = yylineno; - - /* %%%%% this should be set up in memory pools. */ - gTempMacro->macroName = (char *)malloc(strlen(yytext)+1); - if (gTempMacro->macroName == NULL) - { - LexError("Out of memory for string table.\n"); - SAFEFREE(gTempMacro); - if (gbProcessingDefine) - { - BEGIN(EATDEFINE); - } - else - { - BEGIN(EATMACRO); - } - } - else - { - strcpy(gTempMacro->macroName, yytext); - } - } - } -} - -\n { - LexError("No macro name specified, skipping macro definition.\n"); - SAFEFREE(gTempMacro->fileName); - SAFEFREE(gTempMacro); - if (gbProcessingDefine) - { - BEGIN(EATDEFINE); - } - else - { - BEGIN(EATMACRO); - } - -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; -} - -"(" { - gCountParen++; -} - -[ \t]+ {} - -. { - if (gbProcessingDefine && (gCountParen == 0)) - { - EndMacroParms(); - } - else - { - BEGIN(MACROPARM); - } - yyless(0); -} - -[ \t]* { - if ((gCountParen == 0) && gbProcessingDefine) - { - EndMacroParms(); - } -} - -(";"|"//").* { - if (gCountParen == 0) - { - EndMacroParms(); - } -} - -"," {} - -<> { - EndMacroParms(); -// GenDebugLine(); -// GenListString(); - yylineno++; - gLinesAssembled++; - BEGIN(INITIAL); -} - -\n { - if (gbProcessingDefine && (gCountParen > 0)) - { - LexError("Malformed #define, skipping.\n"); - BEGIN(SAVELINE); - } - else - { - EndMacroParms(); -// GenDebugLine(); -// GenListString(); - yylineno++; - gLinesAssembled++; - if (gbProcessingDefine) - { - gbProcessingDefine = false; - BEGIN(SAVELINE); - } - } -} - - -[^\n,]+ { - - MACROTEXT *tMacro; - char *macroParmEnd; - unsigned int startOffset; - unsigned int leftParenCount; - unsigned int rightParenCount; - - // sheesh, we gotta count the parenthesis.... - macroParmEnd = yytext; - leftParenCount = 0; - rightParenCount = 0; - while (*macroParmEnd) - { - if (*macroParmEnd == ')') - { - rightParenCount++; - } - if (*macroParmEnd == '(') - { - leftParenCount++; - } - - macroParmEnd++; - } - - // if we found the last right parenthesis. - if (rightParenCount == leftParenCount+1) - { - // find if we got the last parenthesis on this line - macroParmEnd = strrchr(yytext, ')'); - yyless((macroParmEnd - yytext)); - BEGIN(MACROPARMEND); - } - - startOffset = strspn(yytext, " \t"); - - tMacro = SaveMacroText(&yytext[startOffset], gTempMacro->lastMacroParms); - if (tMacro == NULL) - { - LexError("Out of memory for string table for macro parameter(s).\n"); - FreeMacroEntry(gTempMacro); - BEGIN(EATMACRO); - } - else - { - // if first one wasn't set then set it - if (gTempMacro->firstMacroParms == NULL) - { - gTempMacro->firstMacroParms = tMacro; - } - - gTempMacro->lastMacroParms = tMacro; - - gTempMacro->numParms++; - } - -} - -")"[ \t]*"\\"*\n* { - if (!gbProcessingDefine && !gbTempInsideMacro) - { - LexError("Malformed macro, skipping.\n"); - BEGIN(EATMACRO); - } - else - { - gCountParen--; - - // we can get multiple \n's here - while (yytext[yyleng-2] == '\n') - { - yyleng--; - } - yyless(yyleng); - - // if there isn't a \n on this line, macro starts on this line, - // not next, like in a macro definition - if (yytext[yyleng-1] != '\n') - { - EndMacroParms(); - } - else - { - if (yytext[yyleng-1] == '\n') - { - gTempMacro->lineNo++; - } - // count this line - gTempMacro->nLines++; -// GenDebugLine(); -// GenListString(); - EndMacroParms(); - if (!gbInsideMacro) - { - yylineno++; - } - - gLinesAssembled++; - } - - } -} - -")"[ \t]*(";"|"//").*\n { - if (!gbProcessingDefine && !gbTempInsideMacro) - { - LexError("Malformed macro, skipping.\n"); - BEGIN(EATMACRO); - } - else - { - - // no matter what count this line - gTempMacro->nLines++; - gCountParen--; - EndMacroParms(); - if (!gbInsideMacro) - { - yylineno++; - } - - gLinesAssembled++; - } -} - -")"[ \t]+ { - if (!gbProcessingDefine && !gbTempInsideMacro) - { - LexError("Malformed macro, skipping.\n"); - BEGIN(EATMACRO); - } - else - { - gCountParen--; - if (gCountParen == 0) - { - // no matter what count this line - gTempMacro->nLines++; - EndMacroParms(); - if (!gbInsideMacro) - { - yylineno++; - } - - gLinesAssembled++; - } - else - { - REJECT; - } - } -} - -.*"\\"[ \t]*\n { - MACROTEXT *tMacro; - unsigned int copyLen; - char *endLine; - - gSaveLine[0] ='\0'; - endLine = strchr(yytext, '\\'); - copyLen = (endLine - yytext); - if (copyLen > MAXSAVELINE) - { - copyLen = MAXSAVELINE; - } - - strncat(gSaveLine, yytext, copyLen); - strcat(gSaveLine, "\n"); - tMacro = SaveMacroText(gSaveLine, gLastMacro->lastMacroLines); - if (tMacro == NULL) - { - LexError("Out of memory for string table for macro parameter(s).\n"); - BEGIN(EATDEFINE); - } - else - { - gLastMacro->nLines++; - // if first one wasn't set then set it - if (gLastMacro->firstMacroLines == NULL) - { - gLastMacro->firstMacroLines = tMacro; - } - - gLastMacro->lastMacroLines = tMacro; - } - -// GenDebugLine(); -// GenListString(); - yylineno++; - gLinesAssembled++; -} - -[ \t]*"endm"[ \t]*((";"|"//").*)* { - - strncpy(gSaveLine, yytext, MAXSAVELINE); - if (gbProcessingDefine) - { - LexError("Malformed #define, skipping.\n"); - } - - BEGIN(ENDMACRO); -} - -[^\n]* { - MACROTEXT *tMacro; - - // check if processing #define and only one line, if not then append \n - if (!gbProcessingDefine || (gLastMacro->nLines >= 1)) - { - gSaveLine[0] = '\0'; - strncat(gSaveLine, yytext, MAXSAVELINE); - strcat(gSaveLine, "\n"); - tMacro = SaveMacroText(gSaveLine, gLastMacro->lastMacroLines); - gLastMacro->nLines++; - } - else if (gLastMacro->numParms > 0) // check if parameters were there - { - // if so, we need the '\n' appended - gMacroLine[0] = '\0'; - strncat(gMacroLine, yytext, MAXSAVELINE); - strcat(gMacroLine, "\n"); - tMacro = SaveMacroText(gMacroLine, gLastMacro->lastMacroLines); - gLastMacro->nLines++; - } - else // straight no newline macro replace - { - tMacro = SaveMacroText(yytext, gLastMacro->lastMacroLines); - } - - if (tMacro == NULL) - { - LexError("Out of memory for string table for macro parameter(s).\n"); - BEGIN(EATMACRO); - } - else - { - // if first one wasn't set then set it - if (gLastMacro->firstMacroLines == NULL) - { - gLastMacro->firstMacroLines = tMacro; - } - - gLastMacro->lastMacroLines = tMacro; - } -} - -\n { - - MACROTEXT *tMacro; -// GenDebugLine(); -// GenListString(); - yylineno++; - gLinesAssembled++; - if (gbProcessingDefine) - { - gbProcessingDefine = false; - BEGIN(SAVELINE); - } - else - { - // this means \n by itself inside macro body - if (((yylineno-1) - gLastMacro->lineNo) != gLastMacro->nLines) - { - strcpy(gMacroLine, "\n"); - tMacro = SaveMacroText(gMacroLine, gLastMacro->lastMacroLines); - gLastMacro->nLines++; - - if (tMacro == NULL) - { - LexError("Out of memory for string table for macro parameter(s).\n"); - BEGIN(EATMACRO); - } - else - { - // if first one wasn't set then set it - if (gLastMacro->firstMacroLines == NULL) - { - gLastMacro->firstMacroLines = tMacro; - } - - gLastMacro->lastMacroLines = tMacro; - } - } - } -} - -[ \t]*"endm"[ \t]*\n { - BEGIN(SAVELINE); -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; -} - -.*\n { - strncpy(gSaveLine, yytext, MAXSAVELINE); -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; -} - -.*"\\"\n { - strncpy(gSaveLine, yytext, MAXSAVELINE); -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; -} - -.*\n { - strncpy(gSaveLine, yytext, MAXSAVELINE); -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; - BEGIN(SAVELINE); -} - -{alpha}{alphadigs}* { - - gTempParseMacro = FindMacro(yytext); - - if (gTempParseMacro != NULL) - { - if (gIncludeStackIndex >= MAX_INCLUDE_DEPTH ) - { - LexError("macros nested too deeply"); - exit( 1 ); - } - - if (gTempParseMacro->firstMacroLines != NULL) - { - - gTempMacro = (MACROENTRY *)malloc(sizeof(MACROENTRY)); - if (gTempMacro == NULL) - { - LexError("Out of memory allocating MACROENTRY structure.\n"); - } - else - { - - gTempMacro->next = NULL; - gTempMacro->prev = NULL; - gTempMacro->macroName = NULL; - gTempMacro->firstMacroParms = NULL; - gTempMacro->lastMacroParms = NULL; - gTempMacro->firstMacroLines = NULL; - gTempMacro->lastMacroLines = NULL; - gTempMacro->numParms = 0; - gTempMacro->nLines = 0; - - gbTempInsideMacro = true; // flag we are currently doing a macro replace. - gInvokeState = YYSTATE; - if (gTempParseMacro->numParms > 0) - { - BEGIN(MACROPARMSTART); - } - else - { - EndMacroParms(); - gbTempInsideMacro = false; // no longer waiting for macro invocation - } - } - } - } - else - { - BEGIN(INITIAL); - REJECT; - } -} - -[,\[\]\-\+\(\)\*\<\>\/\%_\.] { -// fprintf( stderr, "%c ", yytext[0] ); - return yytext[0]; -} - - -[ \t]+ {} - -\n { - LexError("Didn't find label string for #define.\n"); - BEGIN(SAVELINE); -// return '\n'; -} - -"\n" { -//fprintf(stderr, "\n"); -// line_incr = 1; - line_incr++; - BEGIN(SAVELINE); - return '\n'; -} - -{alphadigs}+ { - BEGIN(INITIAL); -// fprintf( stderr, "%s", yytext ); - if (yyleng == 1) - return yytext[0]; - else - LexError("Unrecognized Token: %s\n", yytext); - return UNKNOWN_STRING; -} - -[\001-\040] { -// vs10_lval.ival = yytext[0]; - LexError("Illegal character: %d decimal.\n", yytext[0]); - return(ILLEGAL); -} - -[\001-\040] { -// vs10_lval.ival = yytext[0]; - LexError("Illegal character: %d decimal.\n", yytext[0]); - return(ILLEGAL); -} - -. { - return yytext[0]; -} - -. { - BEGIN(EATSTRING); - yyless(0); -} - -<> { - bool wasInMacro; - bool oneLiner; - char *macroText; - - wasInMacro = gbInsideMacro; - oneLiner = false; - - - // if we are inside the macro then do next line until their are no more - if (gbInsideMacro) - { - oneLiner = (gParseMacro->nLines == 0); - - // free the temporary parameter replaced line we were working on. - // get next line in macro text, if any - gMacroLineParse = gMacroLineParse->next; - // more lines to parse? - if (gMacroLineParse != NULL) - { - macroText = gMacroLine; - // if no replacement text, just use source line - if (gParseMacro->firstMacroParms == NULL) - { - macroText = gMacroLineParse->macroText; - } - else - { - // replace the macro parameters - ReplaceMacroParms(gMacroLineParse->macroText, gMacroLine, gParseMacro, gInvokeMacro); - } - -// if (gExpandMacros) -// { -// strcpy(gSaveLine, macroText); -// } - - BEGIN(INITIAL); - // and lex it. - yy_scan_string(macroText); - } - else - { - // no more lines in this macro, so free the working macro - SAFEFREE(gInvokeMacro); - // shut off flag for inside a macro replacement state. - gbInsideMacro = false; - } - } - - if (gbProcessingIFDEF && !wasInMacro) - { - LexError("End of file reached before #endif found, macro started on line %d.\n", gIfDefStartLine); - } - - if (!gbInsideMacro) - { - if ( gIncludeStackIndex == 0 ) - { - if (!gbProcessingBuiltIn) - CleanUp(); - return 0; -// return TOKEN_EOF; - } - else - { - yy_delete_buffer( YY_CURRENT_BUFFER ); - SAFEFREE(gCurFileName); -// SAFEDELETE(myin); -// SAFECLOSE(yyin); - } - - gIncludeStackIndex--; - SAFEDELETEARRAY( gIncludeStack[gIncludeStackIndex].nextString ); - yy_switch_to_buffer(gIncludeStack[gIncludeStackIndex].buffer ); - gCurFileName = gIncludeStack[gIncludeStackIndex].fileName; -// yyin = gIncludeStack[gIncludeStackIndex].fileHandle; - myin = gIncludeStack[gIncludeStackIndex].prevString; - yylineno = gIncludeStack[gIncludeStackIndex].lineNo; - gInvokeMacro = gIncludeStack[gIncludeStackIndex].lastInvokeMacro; - gParseMacro = gIncludeStack[gIncludeStackIndex].lastParseMacro; - gMacroLineParse = gIncludeStack[gIncludeStackIndex].lastMacroLineParse; - gbInsideInclude = gIncludeStack[gIncludeStackIndex].lastbInsideInclude; - gbInsideMacro = gIncludeStack[gIncludeStackIndex].lastbInsideMacro; - gbProcessingIFDEF = gIncludeStack[gIncludeStackIndex].lastbProcessingIFDEF; - - if (!gbInsideMacro && !oneLiner) - { -// GenSwitchFileNames(gCurFileName); - BEGIN(SAVELINE); - } - else - { - BEGIN(INITIAL); - } - - // gSaveLine was last line saved, before macro invocation - if (wasInMacro && !gbInsideMacro && !oneLiner) - { -// GenDebugLine(); -// GenListString(); - gLinesAssembled++; - yylineno++; - } - - } - -} - -%% - - -//===================================================================== -// Function: FindNMacro -// Description: Look through macros and see if it had been predefined -// Parameters: findName = name to lookup -// sLen = # characters valid in source (findName) -// Returns: MACROENTRY * = pointer to macro entry if found -//===================================================================== -MACROENTRY *FindNMacro(char *findName, unsigned int sLen) -{ - MACROENTRY *curEntry; - - curEntry = gLastMacro; - while (curEntry != NULL) - { - if (strlen(curEntry->macroName) == sLen) - { - if (!strncmp(curEntry->macroName, findName, sLen)) - { - break; - } - } - - curEntry = curEntry->prev; - } - - return curEntry; - -} - -//===================================================================== -// Function: FindMacro -// Description: Look through macros and see if it had been predefined -// Parameters: findName = name to lookup -// Returns: MACROENTRY * = pointer to macro entry if found -//===================================================================== -MACROENTRY *FindMacro(char *findName) -{ - MACROENTRY *curEntry; - - curEntry = gLastMacro; - while (curEntry != NULL) - { - if (!strcmp(curEntry->macroName, findName)) - { - break; - } - - curEntry = curEntry->prev; - } - - return curEntry; - -} - -//===================================================================== -// Function: CleanUp -// Description: Clean up the #define strings -// Parameters: . -// Returns: . -//===================================================================== -void CleanUp() -{ - void *tPtr; - - // free up the macros that were alloced - while (gLastMacro != NULL) - { - - FreeMacroEntry(gLastMacro); - - tPtr = gLastMacro; - gLastMacro = gLastMacro->prev; - SAFEFREE(tPtr); - } - -} - -//===================================================================== -// Function: FreeMacroEntry -// Description: Frees up the macro entry data, (parms, lines of text) -// Parameters: macEntry = pointer to the MACROENTRY structure -// Returns: . -//===================================================================== -void FreeMacroEntry(MACROENTRY *macEntry) -{ - MACROTEXT *tText; - MACROTEXT *tNext; - - SAFEFREE(macEntry->macroName); - SAFEFREE(macEntry->fileName); - // free the macro lines that were alloced - tText = macEntry->lastMacroLines; - while (tText != NULL) - { - tNext = tText->prev; - SAFEFREE(tText); - tText = tNext; - } - - // free the text of the macro parms that were alloced - tText = macEntry->lastMacroParms; - while (tText != NULL) - { - tNext = tText->prev; - SAFEFREE(tText); - tText = tNext; - } -} - -//===================================================================== -// Function: CheckMacroFunctions -// Description: Find if this text is a builtin macro function -// Parameters: lookString = non-null terminated string of possible -// and if found set global macro function call -// Returns: . -//===================================================================== -void CheckMacroFunctions(char *lookString, unsigned int *recognizedLen, char **invString) -{ - - unsigned int i; - unsigned int sLen; - - for (i=0; i< NUM_MACRO_FUNCTIONS; i++) - { - sLen = strlen(gMacroFunctions[i].name); - if (!strncmp(gMacroFunctions[i].name, lookString, sLen)) - { - gMacroCallFunction = gMacroFunctions[i].function; - *recognizedLen = sLen; - *invString = NULL; - return; - } - } -} - -//===================================================================== -// Function: FindAlphaNum -// Description: Find a whole alpha numeric string, ie consists of -// [A-Za-z0-9_] only -// Parameters: srcStr = source string to search through. -// sLen = unsinged int pointer to length of string found -// Returns: pointer to found start of string. -// NULL if none. -//===================================================================== -char *FindAlphaNum(char *srcStr, unsigned int *sLen) -{ - char curChar; - char *foundStr; - - while (*srcStr != '\0') - { - curChar = toupper(*srcStr); - if ((curChar >= 'A') && (curChar <= 'Z')) - break; - - if ((curChar >= '0') && (curChar <='9')) - break; - - if (curChar == '_') - break; - - srcStr++; - } - - if (*srcStr == '\0') - { - return NULL; - } - - foundStr = srcStr; - - *sLen = 0; - // now search for end of string of [A-Za-z0-9_] - while (*srcStr != '\0') - { - curChar = toupper(*srcStr); - if ((curChar < 'A') || (curChar > 'Z')) - { - if ((curChar < '0') || (curChar > '9')) - { - if (curChar != '_') - break; - } - } - - (*sLen)++; - srcStr++; - } - - return foundStr; - -} - -//===================================================================== -// Function: FindDefineParm -// Description: Find if the MACROENTRY->macroText linked list contains -// replaceable parameters. -// Parameters: srcParms = pointer to MACROENTRY structure for source -// parameters -// invParms = MACROENTRY pointer to invocation parameters -// lookString = non-null terminated string of possible -// replaceable string -// recognizedLen = replacement string matched length -// invString = invocation string to replace with -// Returns: pointer to first character found in lookstring -//===================================================================== -char *FindDefineParm(MACROENTRY *srcParms, MACROENTRY *invParms, - char *lookString, unsigned int *recognizedLen, char **invString) -{ - MACROTEXT *srcText; - MACROTEXT *invText; - char *checkStr; - unsigned int checkLen = 0; - unsigned int sLen; - - checkStr = lookString; - *invString = NULL; - - // first search for first [A-Za-z0-9_] only string - checkStr = FindAlphaNum(lookString, &checkLen); - - while (checkStr != NULL) - { - // check all the #define parameters for match - srcText = srcParms->firstMacroParms; - invText = invParms->firstMacroParms; - while (srcText) - { - sLen = strlen(srcText->macroText); - // lengths should match - if (sLen == checkLen) - { - if (!strncmp(checkStr, srcText->macroText, checkLen)) - { - // it matched so return replacement text - *invString = invText->macroText; - // and length that we recognized - *recognizedLen = checkLen; - return checkStr; - } - } - - srcText = srcText->next; - invText = invText->next; - } - - // not found yet, so go to next string. - checkStr = FindAlphaNum(checkStr+checkLen, &checkLen); - } - - return NULL; -} - -//===================================================================== -// Function: FindReplaceParm -// Description: Find if the MACROENTRY->macroText linked list contains -// a replaceable parameters. -// Parameters: srcParms = pointer to MACROENTRY structure for source -// parameters -// invParms = MACROENTRY pointer to invocation parameters -// lookString = non-null terminated string of possible -// replaceable string -// recognizedLen = replacement string matched length -// invString = invocation string to replace with -// Returns: . -//===================================================================== -void FindReplaceParm(MACROENTRY *srcParms, MACROENTRY *invParms, - char *lookString, unsigned int *recognizedLen, char **invString) -{ - unsigned int sLen; - MACROTEXT *srcText; - MACROTEXT *invText; - - *recognizedLen = 0; - *invString = NULL; - - srcText = srcParms->firstMacroParms; - invText = invParms->firstMacroParms; - - if (srcText != NULL) - { - // go until srcText # strings ends - while (srcText != NULL) - { - sLen = strlen(srcText->macroText); - if (!strncmp(srcText->macroText, lookString, sLen)) - { - // found it so return src, replacement string - *recognizedLen = strlen(srcText->macroText); - *invString = invText->macroText; - // call function macro if it was invoked prior. - if (gMacroCallFunction != NULL) - { - gMacroCallFunction(lookString, recognizedLen, invString); - gMacroCallFunction = NULL; - } - return; - } - - srcText = srcText->next; - invText = invText->next; - } - } - - // ok, it wasn't found, look through builtin macro functions - CheckMacroFunctions(lookString, recognizedLen, invString); -} - -//===================================================================== -// Function: ReplaceMacroParms -// Description: Replace macro parameters when macro was defined, with -// those specified on the macro invocation line -// Parameters: srcLine = source line to replace src macro parms with -// destLine = destination line save to. -// invocation macro parameters. -// parseMacro = currently parsing macro entry -// invParms = invocation macro entry -// Returns: . -//===================================================================== -void ReplaceMacroParms(char *srcLine, char *destLine, - MACROENTRY *srcParms, MACROENTRY *invParms) -{ - char *findReplace; - char *invString; - unsigned int sLen; - unsigned int dLen; - unsigned int copyLen; - unsigned int subLen; - unsigned int recognizedLen; - - destLine[0]= '\0'; - - sLen = strlen(srcLine); - dLen = 0; - - while (sLen > 0) - { - // strtok might work better except it modifies the string, so - // kind of do my own.... - if (!srcParms->bIsDefine) - { - findReplace = strchr(srcLine, '%'); - if (findReplace != NULL) - { - // bypass % sign in findReplacement - findReplace++; - // figure out length of source before % - copyLen = (findReplace - srcLine)-1; - // check if there is a replacement string - FindReplaceParm(srcParms, invParms, findReplace, &recognizedLen, &invString); - } - else - { - strcat(destLine, srcLine); - return; - } - } - else - { - findReplace = FindDefineParm(srcParms, invParms, srcLine, &recognizedLen, &invString); - if (findReplace != NULL) - { - // figure out length of source before % - copyLen = findReplace - srcLine; - } - else - { - strcat(destLine, srcLine); - return; - } - } - - - if (invString != NULL) - { - // figure out how much we are going to substitute - subLen = strlen(invString); - } - else - { - subLen = 0; - } - - if ((dLen + copyLen + subLen) > MAXSAVELINE) - { - LexError("Macro string overrun.\n"); - CleanUp(); - exit(ERROR_MACRO_OVERRUN); - } - - if (copyLen > 0) - { - strncat(destLine, srcLine, copyLen); - dLen += copyLen; - } - - srcLine += copyLen; - sLen -= copyLen; - // in macro so skip % part of variable - if (!srcParms->bIsDefine) - { - // skip %, also - srcLine++; - sLen--; - } - - if (invString != NULL) - { - strcat(destLine, invString); - dLen += strlen(invString); - } - - srcLine += recognizedLen; - sLen -= recognizedLen; - } - -} - -//===================================================================== -// Function: SaveMacroText -// Description: Adds a string to a linked list of MACROTEXT structures -// Parameters: srcText = pointer to source text to save -// lastMacroText = last allocated, or NULL -// Returns: newly allocated MACROTEXT structure, or NULL -//===================================================================== -MACROTEXT *SaveMacroText(char *srcText, MACROTEXT *lastMacroText) -{ - MACROTEXT *curMacroText; - - curMacroText = (MACROTEXT *)malloc(sizeof(MACROTEXT)); - if (curMacroText == NULL) - { - return NULL; - } - else - { - // no next entry but set up previous with previously alloced macro parameter - curMacroText->next = NULL; - curMacroText->prev = lastMacroText; - - // if the macroParm pointer is null then we are the first allocated - // so if not set the last one allocate next pointer to newly allocated structure - if (lastMacroText != NULL) - { - lastMacroText->next = curMacroText; - } - - /* %%%%% this should be set up in memory pools. */ - curMacroText->macroText = strdup(srcText); - if (curMacroText->macroText == NULL) - { - SAFEFREE(curMacroText); - return NULL; - } - } - - return curMacroText; -} - -//===================================================================== -// Function: ParseBuiltInMacroParms -// Description: parse parameters of string and fill in MACROENTRY -// structure. -// Parameters: parsedMacro = pointer to MACROENTRY structure that gets -// filled in with parameter pointers and count -// parmStr = string to parse parameters from -// Returns: false if error -//===================================================================== -bool ParseBuiltInMacroParms(MACROENTRY *parsedMacro, char *parmStr) -{ - char *endStr; - char *foundParm; - MACROTEXT *prevMT; - MACROTEXT *curMT; - - parsedMacro->numParms = 0; - parsedMacro->firstMacroParms = NULL; - - foundParm = strdup(parmStr); - if (foundParm == NULL) - { - LexError("Out of memory parsing builtin macro parameters.\n"); - return false; - } - - // assume a ')' is on the end. - endStr = strrchr(foundParm, ')'); - if (endStr == NULL) - { - LexWarning("Ending parenthesis not found for macro %s.\n", parsedMacro->macroName); - endStr = foundParm + strlen(foundParm); - } - - prevMT = NULL; - // strip out and separate parameters - while (foundParm < endStr) - { - // allocate a macro text structure - curMT = (MACROTEXT *)malloc(sizeof(MACROTEXT)); - if (curMT == NULL) - { - free(parmStr); - LexError("Out of memory parsing builtin macro parameters.\n"); - return false; - } - curMT->next = NULL; - curMT->prev = prevMT; - parsedMacro->numParms++; - - if (prevMT != NULL) - { - prevMT->next = curMT; - } - else - { - parsedMacro->firstMacroParms = curMT; - } - - curMT->macroText = foundParm; - // search for next parameters, delimited by comma - foundParm = strchr(foundParm, ','); - if (foundParm == NULL) - { - foundParm = endStr; - *foundParm = '\0'; - } - else - { - // skip comma - *foundParm = '\0'; - foundParm++; - } - prevMT = curMT; - } - - return true; -} - -//===================================================================== -// Function: MacroMathFunction -// Description: Comes here after macro replacement is done to perform -// some mathematic function on parameter (macro replacement -// string (ie, register)) -// Parameters: invMacro = macroentry pointer containing macro information -// recognizedLen = # characters recoginized so far -// invStr = invoked replacement string so far -// mathStr = "-", "+", etc for mathematic function -// Returns: new recognizedLen, invStr, with incremented # -//===================================================================== -void MacroMathFunction(MACROENTRY *invMacro, unsigned int *recognizedLen, char **invStr, - const char *mathStr) -{ - char *numStartStr; - unsigned int sLen; - char numberStr[256]; - unsigned int number = 0; - char *operand; - - - // verify enough paramters to complete operation - if (invMacro->numParms != 2) - { - LexError("Two parameters are required for %s macro\n", invMacro->macroName); - return; - } - - // get second macro parm, which is add by amount. - operand = invMacro->firstMacroParms->next->macroText; - - // first find inner most bracket if any - numStartStr = strrchr(*invStr, ']'); - if (numStartStr == NULL) - { - numStartStr = strrchr(*invStr, ')'); - } - - if (numStartStr != NULL) - { - if ((strlen(*invStr)+strlen(operand)+1) > MAXREPLACESTRING) - { - LexError("Out of Temporary string replacement memory inside builtin macro %s\n", - invMacro->macroName); - } - else - { - sLen = (numStartStr - *invStr); - gReplaceText[0] = '\0'; - strncat(gReplaceText, *invStr, sLen); - strcat(gReplaceText, mathStr); - strcat(gReplaceText, operand); - strcat(gReplaceText, numStartStr); - *invStr = gReplaceText; - } - } - else - { - numStartStr = strpbrk(*invStr, "0123456789"); - if (numStartStr != NULL) - { - // put up to number we found - sLen = numStartStr - *invStr; - if (sLen > MAXREPLACESTRING) - goto ErrOut; - - gReplaceText[0] = '\0'; - strncat(gReplaceText, *invStr, sLen); - - switch (mathStr[0]) - { - case '-': - number = atoi(numStartStr)-atoi(operand); - break; - case '+': - number = atoi(numStartStr)+atoi(operand); - break; - } - sprintf(numberStr, "%d", number); - - if ((strlen(gReplaceText) + strlen(numberStr)) > MAXREPLACESTRING) - goto ErrOut; - - strcat(gReplaceText, numberStr); - - while ((*numStartStr != '\0') && (*numStartStr >= '0' && *numStartStr <= '9')) - numStartStr++; - - if ((strlen(gReplaceText) + strlen(numStartStr)) > MAXREPLACESTRING) - goto ErrOut; - - strcat(gReplaceText, numStartStr); - - *invStr = gReplaceText; - } - else - { - if ((strlen(*invStr)+strlen(operand)+1) > MAXREPLACESTRING) - { - LexError("Out of Temporary string replacement memory inside builtin macro %s\n", - invMacro->macroName); - } - else - { - sprintf(gReplaceText, "%s%s%s", *invStr, mathStr, operand); - *invStr = gReplaceText; - } - } - } - - - return; - -ErrOut: - LexError("Out of Temporary string replacement memory inside builtin macro %s\n", - invMacro->macroName); - // skip ')' - (*recognizedLen)++; -} - -//===================================================================== -// Function: MacroIncFunction -// Description: Comes here after macro replacement is done to increment -// macro replacement string (ie, register) -// Parameters: lookStr = string after '(', so we can get parameters -// recognizedLen = # characters recoginized so far -// invStr = invoked replacement string so far -// Returns: new recognizedLen, invStr, with incremented # -//===================================================================== -void MacroIncFunction(char *lookStr, unsigned int *recognizedLen, char **invStr) -{ - MACROENTRY tMEntry; - MACROTEXT parm1; - MACROTEXT parm2; - - tMEntry.macroName = (char *)"%inc()"; - tMEntry.numParms = 2; - tMEntry.firstMacroParms = &parm1; - parm1.prev = NULL; - parm1.next = &parm2; - parm1.macroText = *invStr; - parm2.prev = &parm1; - parm2.next = NULL; - parm2.macroText = (char *)"1"; - - MacroMathFunction(&tMEntry, recognizedLen, invStr, "+"); - // skip ')' - (*recognizedLen)++; -} - -//===================================================================== -// Function: MacroDecFunction -// Description: Comes here after macro replacement is done to decrement -// macro replacement string (ie, register) -// Parameters: lookStr = string after '(', so we can get parameters -// recognizedLen = # characters recoginized so far -// invStr = invoked replacement string so far -// Returns: new recognizedLen, invStr, with decremented # -//===================================================================== -void MacroDecFunction(char *lookStr, unsigned int *recognizedLen, char **invStr) -{ - MACROENTRY tMEntry; - MACROTEXT parm1; - MACROTEXT parm2; - - tMEntry.macroName = (char *)"%dec()"; - tMEntry.numParms = 2; - tMEntry.firstMacroParms = &parm1; - parm1.prev = NULL; - parm1.next = &parm2; - parm1.macroText = *invStr; - parm2.prev = &parm1; - parm2.next = NULL; - parm2.macroText = (char *)"1"; - - MacroMathFunction(&tMEntry, recognizedLen, invStr, "-"); - // skip ')' - (*recognizedLen)++; -} - -//===================================================================== -// Function: MacroAddFunction -// Description: Comes here after macro replacement is done to add -// macro replacement string (ie, register) -// Parameters: lookStr = string after '(', so we can get parameters -// recognizedLen = # characters recoginized so far -// invStr = invoked replacement string so far -// Returns: new recognizedLen, invStr, with incremented # -//===================================================================== -void MacroAddFunction(char *lookStr, unsigned int *recognizedLen, char **invStr) -{ - MACROENTRY tMEntry; - MACROTEXT *curMT; - MACROTEXT *nextMT; - unsigned int i; - - tMEntry.macroName = (char *)"%add()"; - if (strlen(lookStr) > MAXREPLACESTRING) - { - LexError("Out of Temporary string replacement memory inside builtin macro %add()\n"); - return; - } - if (ParseBuiltInMacroParms(&tMEntry, lookStr)) - { - MacroMathFunction(&tMEntry, recognizedLen, invStr, "+"); - // skip ',' strlen(parm2)+ ')' - (*recognizedLen) += strlen(tMEntry.firstMacroParms->next->macroText)+2; - } - - curMT = tMEntry.firstMacroParms; - // in this case only one string was allocated - free(curMT->macroText); - for (i=0; inext; - free(curMT); - curMT = nextMT; - } -} - -//===================================================================== -// Function: MacroSubFunction -// Description: Comes here after macro replacement is done to subtract -// macro replacement string (ie, register) -// Parameters: invParms, parameters that macro was invoked with -// recognizedLen = # characters recoginized so far -// invStr = invoked replacement string so far -// Returns: new recognizedLen, invStr, with incremented # -//===================================================================== -void MacroSubFunction(char *lookStr, unsigned int *recognizedLen, char **invStr) -{ - MACROENTRY tMEntry; - MACROTEXT *curMT; - MACROTEXT *nextMT; - unsigned int i; - - tMEntry.macroName = (char *)"%sub()"; - if (ParseBuiltInMacroParms(&tMEntry, lookStr)) - { - MacroMathFunction(&tMEntry, recognizedLen, invStr, "-"); - // skip ',' strlen(parm2)+ ')' - (*recognizedLen) += strlen(tMEntry.firstMacroParms->next->macroText)+2; - } - curMT = tMEntry.firstMacroParms; - // in this case only one string was allocated - free(curMT->macroText); - for (i=0; inext; - free(curMT); - curMT = nextMT; - } -} - -//===================================================================== -// Function: EndMacroParms -// Description: Does update and cleanup one end of macro parameters -// is reached -// Parameters: . -// Returns: . -//===================================================================== -void EndMacroParms() -{ - char *curFileName; - char *macroFileName; - char tempStr[1024]; - char *macroText; - - if (gbTempInsideMacro) - { - if (gTempParseMacro->numParms != gTempMacro->numParms) - { - LexError("Macro invocation number of parameters do not match macro definition, skipping\n"); - BEGIN(INITIAL); - SAFEFREE(gTempMacro); - } - else - { - // we got all the parameters for the MACRO invocation, so start inside - // the macro now, by saving off current state on stack - gIncludeStack[gIncludeStackIndex].lineNo = yylineno; - gIncludeStack[gIncludeStackIndex].fileName = gCurFileName; -// gIncludeStack[gIncludeStackIndex].fileHandle = yyin; -//fprintf( stderr, "Chris fix this code with myin stuff\n" ); - gIncludeStack[gIncludeStackIndex].prevString = myin; - gIncludeStack[gIncludeStackIndex].nextString = NULL; - gIncludeStack[gIncludeStackIndex].lastInvokeMacro = gInvokeMacro; - gIncludeStack[gIncludeStackIndex].lastParseMacro = gParseMacro; - gIncludeStack[gIncludeStackIndex].lastMacroLineParse = gMacroLineParse; - gIncludeStack[gIncludeStackIndex].lastbInsideMacro = gbInsideMacro; - gIncludeStack[gIncludeStackIndex].lastbInsideInclude = gbInsideInclude; - gIncludeStack[gIncludeStackIndex].buffer = YY_CURRENT_BUFFER; - gIncludeStack[gIncludeStackIndex].lastbProcessingIFDEF = gbProcessingIFDEF; - gIncludeStackIndex++; - - gParseMacro = gTempParseMacro; - gInvokeMacro = gTempMacro; - gbInsideMacro = gbTempInsideMacro; - - gbTempInsideMacro = false; - -// yyin = NULL; - myin = NULL; - curFileName = gCurFileName; - if (curFileName == NULL) - curFileName = (char *)""; - - macroFileName = gParseMacro->fileName; - if (macroFileName == NULL) - macroFileName = (char *)""; - - sprintf(tempStr, "%s(%d) : References ->\n%s", curFileName, yylineno, macroFileName); - gCurFileName = strdup(tempStr); - gMacroLineParse = gParseMacro->firstMacroLines; - - macroText = gMacroLine; - // if no replacement text, just use source line - if (gParseMacro->firstMacroParms == NULL) - { - macroText = gMacroLineParse->macroText; - } - else - { - // replace the macro parameters - ReplaceMacroParms(gMacroLineParse->macroText, gMacroLine, gParseMacro, gInvokeMacro); - } - - yylineno = gParseMacro->lineNo; - if (gParseMacro->nLines >= 1) - { - strcpy(gSaveLine, macroText); - } - -// if (gExpandMacros && (gParseMacro->nLines >= 1)) -// { -// // in case there is anything there dump it out -// GenDebugLine(); -// GenListString(); -// if (gInvokeMacro->nLines >= 1) -// GenSwitchFileNames(macroFileName); -// } - - BEGIN(gInvokeState); - yy_scan_string(macroText); - gInvokeState = INITIAL; - } - } - else - { - if (gLastMacro != NULL) - { - gLastMacro->next = gTempMacro; - } - gLastMacro = gTempMacro; - BEGIN(MACROBODY); - } -} - -//===================================================================== -// Function: FindSwizzleValue -// Description: see if valid swizzle value and return the bits -// Parameters: swizzleTex = pointer to characters to analyze -// Returns: unsigned int = bits for swizzle values, or 0 for error -//===================================================================== -unsigned int FindSwizzleValue(char *swizzleText) -{ - unsigned int swizzleBits; - unsigned int sLen; - unsigned int i; - unsigned int lastMask; - - sLen = strlen(swizzleText); - swizzleBits = 0; - lastMask = 0; - - for (i=0; i -#include -#include - -using namespace std; - - -namespace -{ - void LoadProgram( GLenum target, GLuint id, char *instring ); -} - - -bool is_vsp10(const char * s) -{ - return ! strncmp(s, "!!VSP1.0", 8); -} - -bool vsp10_init(char * s) -{ - static bool vpinit = false; - if (vpinit == false ) - { - /* - if(! glh_init_extensions("GL_NV_vertex_program")) - { - errors.set("unable to initialize GL_NV_vertex_program"); - return false; - } - else - { - */ - vpinit = true; - /* - } - */ - } - - errors.reset(); - line_number = 1; - myin = s; - - return true; -} - -int vsp10_parse(int vpsid) -{ - LoadProgram( GL_VERTEX_STATE_PROGRAM_NV, vpsid, myin ); - return 0; -} - -namespace -{ - //.----------------------------------------------------------------------------. - //| Function : LoadProgram | - //| Description: Load a program into GL, and report any errors encountered. | - //.----------------------------------------------------------------------------. - void LoadProgram( GLenum target, GLuint id, char *instring ) - { - GLint errPos; - GLenum errCode; - - int len = strlen(instring); - glLoadProgramNV( target, id, len, (const GLubyte *) instring ); - if ( (errCode = glGetError()) != GL_NO_ERROR ) - { - glGetIntegerv( GL_PROGRAM_ERROR_POSITION_NV, &errPos ); - - int nlines = 1; - int nchar = 1; - int i; - for ( i = 0; i < errPos; i++ ) - { - if ( instring[i] == '\n' ) - { - nlines++; - nchar = 1; - } - else - { - nchar++; - } - } - int start = 0; - int end = 0; - int flag = ((instring[errPos]==';') | (instring[errPos-1]==';')) ? 1 : 0; - for ( i = errPos; i >= 0; i-- ) - { - start = i; - if ( flag && (start >= errPos-1) ) - continue; - if ( instring[i] == ';' ) - { - if ( !flag ) - { - start = i+1; - if ( instring[start] == '\n' ) - start++; - } - break; - } - } - for ( i = errPos; i < len; i++ ) - { - end = i; - if ( instring[i] == ';' && end > start) - { - break; - } - } - if ( errPos - start > 30 ) - { - start = errPos - 30; - } - if ( end - errPos > 30 ) - { - end = errPos + 30; - } - - char substring[96]; - memset( substring, 0, 96 ); - strncpy( substring, &(instring[start]), end-start+1 ); - char str[256]; - //sprintf( str, "error at line %d character %d\n \"%s\"\n", nlines, nchar, substring ); - sprintf( str, "error at line %d character %d\n\"%s\"\n", nlines, nchar, substring ); - int width = errPos-start; - for ( i = 0; i < width; i++ ) - { - strcat( str, " " ); - } - strcat( str, "|\n" ); - for ( i = 0; i < width; i++ ) - { - strcat( str, " " ); - } - strcat( str, "^\n" ); - - errors.set( str ); - } - } -} -/* -else if(!strncmp(instring, "!!VSP1.0", 8)) -{ -if (vpinit == 0 ) -{ -if(! glh_init_extensions("GL_NV_vertex_program")) -{ -errors.set("unable to initialize GL_NV_vertex_program"); -free(instring); -return; -} -else -{ -vpinit = 1; -} -} - - errors.reset(); - line_number = 1; - - va_list ap; - va_start(ap, input_string); - int vpsid = va_arg(ap,int); - va_end(ap); - - if ( glGetError() != GL_NO_ERROR ) - { - errors.set( "Previous GL_ERROR prior to vertex state program parsing." ); - } - - LoadProgram( GL_VERTEX_STATE_PROGRAM_NV, vpsid, instring ); - } - */ diff --git a/RenderSystems/GL3Plus/CMakeLists.txt b/RenderSystems/GL3Plus/CMakeLists.txt deleted file mode 100644 index 9cd789c834f..00000000000 --- a/RenderSystems/GL3Plus/CMakeLists.txt +++ /dev/null @@ -1,44 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure OpenGL 3+ RenderSystem build - -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES ${PROJECT_BINARY_DIR}/include/OgreGL3PlusExports.h) -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") -list(APPEND SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/gl3w.c") - -file(GLOB GLSL_HEADERS "${CMAKE_CURRENT_SOURCE_DIR}/src/GLSL/include/*.h") -file(GLOB GLSL_SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/src/GLSL/src/*.cpp") - -add_definitions(${OGRE_VISIBILITY_FLAGS}) - -if(OGRE_CONFIG_ENABLE_GL_STATE_CACHE_SUPPORT) - set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/src/OgreGL3PlusStateCacheManager.cpp - PROPERTIES COMPILE_DEFINITIONS OGRE_ENABLE_STATE_CACHE) -endif() -add_library(RenderSystem_GL3Plus ${OGRE_LIB_TYPE} ${HEADER_FILES} ${GLSL_HEADERS} ${GLSL_SOURCE} ${SOURCE_FILES}) -target_link_libraries(RenderSystem_GL3Plus PUBLIC OgreMain ${CMAKE_DL_LIBS} PRIVATE OgreGLSupport) -target_include_directories(RenderSystem_GL3Plus PUBLIC - "$" - $ - PRIVATE - "$") - -target_include_directories(RenderSystem_GL3Plus PUBLIC ${OPENGL_INCLUDE_DIR}) - -generate_export_header(RenderSystem_GL3Plus - EXPORT_MACRO_NAME _OgreGL3PlusExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreGL3PlusExports.h) - -ogre_config_framework(RenderSystem_GL3Plus) -ogre_config_plugin(RenderSystem_GL3Plus) - -install(FILES ${HEADER_FILES} ${GLSUPPORT_HEADERS} DESTINATION include/OGRE/RenderSystems/GL3Plus) -install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include/GL DESTINATION include/OGRE/RenderSystems/GL3Plus) diff --git a/RenderSystems/GL3Plus/include/GL/gl3w.h b/RenderSystems/GL3Plus/include/GL/gl3w.h deleted file mode 100644 index 071dad70428..00000000000 --- a/RenderSystems/GL3Plus/include/GL/gl3w.h +++ /dev/null @@ -1,2537 +0,0 @@ -/* - - This file was generated with gl3w_gen.cmake, part of glXXw - (hosted at https://github.com/paroj/glXXw-cmake) - - This is free and unencumbered software released into the public domain. - - Anyone is free to copy, modify, publish, use, compile, sell, or - distribute this software, either in source code form or as a compiled - binary, for any purpose, commercial or non-commercial, and by any - means. - - In jurisdictions that recognize copyright laws, the author or authors - of this software dedicate any and all copyright interest in the - software to the public domain. We make this dedication for the benefit - of the public at large and to the detriment of our heirs and - successors. We intend this dedication to be an overt act of - relinquishment in perpetuity of all present and future rights to this - software under copyright law. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. - -*/ - -#ifndef __gl3w_h_ -#define __gl3w_h_ - -#include - -#ifndef __gl_h_ -#define __gl_h_ -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -typedef void (*GL3WglProc)(void); -typedef GL3WglProc (*GL3WGetProcAddressProc)(const char *proc); - -/* gl3w api */ -int gl3wInit(void); -int gl3wInit2(GL3WGetProcAddressProc proc); -int gl3wIsSupported(int major, int minor); -GL3WglProc gl3wGetProcAddress(const char *proc); - -/* OpenGL functions */ -extern PFNGLACTIVEPROGRAMEXTPROC gl3wActiveProgramEXT; -extern PFNGLACTIVESHADERPROGRAMPROC gl3wActiveShaderProgram; -extern PFNGLACTIVETEXTUREPROC gl3wActiveTexture; -extern PFNGLAPPLYFRAMEBUFFERATTACHMENTCMAAINTELPROC gl3wApplyFramebufferAttachmentCMAAINTEL; -extern PFNGLATTACHSHADERPROC gl3wAttachShader; -extern PFNGLBEGINCONDITIONALRENDERPROC gl3wBeginConditionalRender; -extern PFNGLBEGINCONDITIONALRENDERNVPROC gl3wBeginConditionalRenderNV; -extern PFNGLBEGINPERFMONITORAMDPROC gl3wBeginPerfMonitorAMD; -extern PFNGLBEGINPERFQUERYINTELPROC gl3wBeginPerfQueryINTEL; -extern PFNGLBEGINQUERYPROC gl3wBeginQuery; -extern PFNGLBEGINQUERYINDEXEDPROC gl3wBeginQueryIndexed; -extern PFNGLBEGINTRANSFORMFEEDBACKPROC gl3wBeginTransformFeedback; -extern PFNGLBINDATTRIBLOCATIONPROC gl3wBindAttribLocation; -extern PFNGLBINDBUFFERPROC gl3wBindBuffer; -extern PFNGLBINDBUFFERBASEPROC gl3wBindBufferBase; -extern PFNGLBINDBUFFERRANGEPROC gl3wBindBufferRange; -extern PFNGLBINDBUFFERSBASEPROC gl3wBindBuffersBase; -extern PFNGLBINDBUFFERSRANGEPROC gl3wBindBuffersRange; -extern PFNGLBINDFRAGDATALOCATIONPROC gl3wBindFragDataLocation; -extern PFNGLBINDFRAGDATALOCATIONINDEXEDPROC gl3wBindFragDataLocationIndexed; -extern PFNGLBINDFRAMEBUFFERPROC gl3wBindFramebuffer; -extern PFNGLBINDIMAGETEXTUREPROC gl3wBindImageTexture; -extern PFNGLBINDIMAGETEXTURESPROC gl3wBindImageTextures; -extern PFNGLBINDMULTITEXTUREEXTPROC gl3wBindMultiTextureEXT; -extern PFNGLBINDPROGRAMPIPELINEPROC gl3wBindProgramPipeline; -extern PFNGLBINDRENDERBUFFERPROC gl3wBindRenderbuffer; -extern PFNGLBINDSAMPLERPROC gl3wBindSampler; -extern PFNGLBINDSAMPLERSPROC gl3wBindSamplers; -extern PFNGLBINDTEXTUREPROC gl3wBindTexture; -extern PFNGLBINDTEXTUREUNITPROC gl3wBindTextureUnit; -extern PFNGLBINDTEXTURESPROC gl3wBindTextures; -extern PFNGLBINDTRANSFORMFEEDBACKPROC gl3wBindTransformFeedback; -extern PFNGLBINDVERTEXARRAYPROC gl3wBindVertexArray; -extern PFNGLBINDVERTEXBUFFERPROC gl3wBindVertexBuffer; -extern PFNGLBINDVERTEXBUFFERSPROC gl3wBindVertexBuffers; -extern PFNGLBLENDBARRIERKHRPROC gl3wBlendBarrierKHR; -extern PFNGLBLENDBARRIERNVPROC gl3wBlendBarrierNV; -extern PFNGLBLENDCOLORPROC gl3wBlendColor; -extern PFNGLBLENDEQUATIONPROC gl3wBlendEquation; -extern PFNGLBLENDEQUATIONSEPARATEPROC gl3wBlendEquationSeparate; -extern PFNGLBLENDEQUATIONSEPARATEIPROC gl3wBlendEquationSeparatei; -extern PFNGLBLENDEQUATIONSEPARATEIARBPROC gl3wBlendEquationSeparateiARB; -extern PFNGLBLENDEQUATIONIPROC gl3wBlendEquationi; -extern PFNGLBLENDEQUATIONIARBPROC gl3wBlendEquationiARB; -extern PFNGLBLENDFUNCPROC gl3wBlendFunc; -extern PFNGLBLENDFUNCSEPARATEPROC gl3wBlendFuncSeparate; -extern PFNGLBLENDFUNCSEPARATEIPROC gl3wBlendFuncSeparatei; -extern PFNGLBLENDFUNCSEPARATEIARBPROC gl3wBlendFuncSeparateiARB; -extern PFNGLBLENDFUNCIPROC gl3wBlendFunci; -extern PFNGLBLENDFUNCIARBPROC gl3wBlendFunciARB; -extern PFNGLBLENDPARAMETERINVPROC gl3wBlendParameteriNV; -extern PFNGLBLITFRAMEBUFFERPROC gl3wBlitFramebuffer; -extern PFNGLBLITNAMEDFRAMEBUFFERPROC gl3wBlitNamedFramebuffer; -extern PFNGLBUFFERADDRESSRANGENVPROC gl3wBufferAddressRangeNV; -extern PFNGLBUFFERDATAPROC gl3wBufferData; -extern PFNGLBUFFERPAGECOMMITMENTARBPROC gl3wBufferPageCommitmentARB; -extern PFNGLBUFFERSTORAGEPROC gl3wBufferStorage; -extern PFNGLBUFFERSUBDATAPROC gl3wBufferSubData; -extern PFNGLCALLCOMMANDLISTNVPROC gl3wCallCommandListNV; -extern PFNGLCHECKFRAMEBUFFERSTATUSPROC gl3wCheckFramebufferStatus; -extern PFNGLCHECKNAMEDFRAMEBUFFERSTATUSPROC gl3wCheckNamedFramebufferStatus; -extern PFNGLCHECKNAMEDFRAMEBUFFERSTATUSEXTPROC gl3wCheckNamedFramebufferStatusEXT; -extern PFNGLCLAMPCOLORPROC gl3wClampColor; -extern PFNGLCLEARPROC gl3wClear; -extern PFNGLCLEARBUFFERDATAPROC gl3wClearBufferData; -extern PFNGLCLEARBUFFERSUBDATAPROC gl3wClearBufferSubData; -extern PFNGLCLEARBUFFERFIPROC gl3wClearBufferfi; -extern PFNGLCLEARBUFFERFVPROC gl3wClearBufferfv; -extern PFNGLCLEARBUFFERIVPROC gl3wClearBufferiv; -extern PFNGLCLEARBUFFERUIVPROC gl3wClearBufferuiv; -extern PFNGLCLEARCOLORPROC gl3wClearColor; -extern PFNGLCLEARDEPTHPROC gl3wClearDepth; -extern PFNGLCLEARDEPTHFPROC gl3wClearDepthf; -extern PFNGLCLEARNAMEDBUFFERDATAPROC gl3wClearNamedBufferData; -extern PFNGLCLEARNAMEDBUFFERDATAEXTPROC gl3wClearNamedBufferDataEXT; -extern PFNGLCLEARNAMEDBUFFERSUBDATAPROC gl3wClearNamedBufferSubData; -extern PFNGLCLEARNAMEDBUFFERSUBDATAEXTPROC gl3wClearNamedBufferSubDataEXT; -extern PFNGLCLEARNAMEDFRAMEBUFFERFIPROC gl3wClearNamedFramebufferfi; -extern PFNGLCLEARNAMEDFRAMEBUFFERFVPROC gl3wClearNamedFramebufferfv; -extern PFNGLCLEARNAMEDFRAMEBUFFERIVPROC gl3wClearNamedFramebufferiv; -extern PFNGLCLEARNAMEDFRAMEBUFFERUIVPROC gl3wClearNamedFramebufferuiv; -extern PFNGLCLEARSTENCILPROC gl3wClearStencil; -extern PFNGLCLEARTEXIMAGEPROC gl3wClearTexImage; -extern PFNGLCLEARTEXSUBIMAGEPROC gl3wClearTexSubImage; -extern PFNGLCLIENTATTRIBDEFAULTEXTPROC gl3wClientAttribDefaultEXT; -extern PFNGLCLIENTWAITSYNCPROC gl3wClientWaitSync; -extern PFNGLCLIPCONTROLPROC gl3wClipControl; -extern PFNGLCOLORFORMATNVPROC gl3wColorFormatNV; -extern PFNGLCOLORMASKPROC gl3wColorMask; -extern PFNGLCOLORMASKIPROC gl3wColorMaski; -extern PFNGLCOMMANDLISTSEGMENTSNVPROC gl3wCommandListSegmentsNV; -extern PFNGLCOMPILECOMMANDLISTNVPROC gl3wCompileCommandListNV; -extern PFNGLCOMPILESHADERPROC gl3wCompileShader; -extern PFNGLCOMPILESHADERINCLUDEARBPROC gl3wCompileShaderIncludeARB; -extern PFNGLCOMPRESSEDMULTITEXIMAGE1DEXTPROC gl3wCompressedMultiTexImage1DEXT; -extern PFNGLCOMPRESSEDMULTITEXIMAGE2DEXTPROC gl3wCompressedMultiTexImage2DEXT; -extern PFNGLCOMPRESSEDMULTITEXIMAGE3DEXTPROC gl3wCompressedMultiTexImage3DEXT; -extern PFNGLCOMPRESSEDMULTITEXSUBIMAGE1DEXTPROC gl3wCompressedMultiTexSubImage1DEXT; -extern PFNGLCOMPRESSEDMULTITEXSUBIMAGE2DEXTPROC gl3wCompressedMultiTexSubImage2DEXT; -extern PFNGLCOMPRESSEDMULTITEXSUBIMAGE3DEXTPROC gl3wCompressedMultiTexSubImage3DEXT; -extern PFNGLCOMPRESSEDTEXIMAGE1DPROC gl3wCompressedTexImage1D; -extern PFNGLCOMPRESSEDTEXIMAGE2DPROC gl3wCompressedTexImage2D; -extern PFNGLCOMPRESSEDTEXIMAGE3DPROC gl3wCompressedTexImage3D; -extern PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC gl3wCompressedTexSubImage1D; -extern PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC gl3wCompressedTexSubImage2D; -extern PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC gl3wCompressedTexSubImage3D; -extern PFNGLCOMPRESSEDTEXTUREIMAGE1DEXTPROC gl3wCompressedTextureImage1DEXT; -extern PFNGLCOMPRESSEDTEXTUREIMAGE2DEXTPROC gl3wCompressedTextureImage2DEXT; -extern PFNGLCOMPRESSEDTEXTUREIMAGE3DEXTPROC gl3wCompressedTextureImage3DEXT; -extern PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC gl3wCompressedTextureSubImage1D; -extern PFNGLCOMPRESSEDTEXTURESUBIMAGE1DEXTPROC gl3wCompressedTextureSubImage1DEXT; -extern PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC gl3wCompressedTextureSubImage2D; -extern PFNGLCOMPRESSEDTEXTURESUBIMAGE2DEXTPROC gl3wCompressedTextureSubImage2DEXT; -extern PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC gl3wCompressedTextureSubImage3D; -extern PFNGLCOMPRESSEDTEXTURESUBIMAGE3DEXTPROC gl3wCompressedTextureSubImage3DEXT; -extern PFNGLCONSERVATIVERASTERPARAMETERFNVPROC gl3wConservativeRasterParameterfNV; -extern PFNGLCONSERVATIVERASTERPARAMETERINVPROC gl3wConservativeRasterParameteriNV; -extern PFNGLCOPYBUFFERSUBDATAPROC gl3wCopyBufferSubData; -extern PFNGLCOPYIMAGESUBDATAPROC gl3wCopyImageSubData; -extern PFNGLCOPYMULTITEXIMAGE1DEXTPROC gl3wCopyMultiTexImage1DEXT; -extern PFNGLCOPYMULTITEXIMAGE2DEXTPROC gl3wCopyMultiTexImage2DEXT; -extern PFNGLCOPYMULTITEXSUBIMAGE1DEXTPROC gl3wCopyMultiTexSubImage1DEXT; -extern PFNGLCOPYMULTITEXSUBIMAGE2DEXTPROC gl3wCopyMultiTexSubImage2DEXT; -extern PFNGLCOPYMULTITEXSUBIMAGE3DEXTPROC gl3wCopyMultiTexSubImage3DEXT; -extern PFNGLCOPYNAMEDBUFFERSUBDATAPROC gl3wCopyNamedBufferSubData; -extern PFNGLCOPYPATHNVPROC gl3wCopyPathNV; -extern PFNGLCOPYTEXIMAGE1DPROC gl3wCopyTexImage1D; -extern PFNGLCOPYTEXIMAGE2DPROC gl3wCopyTexImage2D; -extern PFNGLCOPYTEXSUBIMAGE1DPROC gl3wCopyTexSubImage1D; -extern PFNGLCOPYTEXSUBIMAGE2DPROC gl3wCopyTexSubImage2D; -extern PFNGLCOPYTEXSUBIMAGE3DPROC gl3wCopyTexSubImage3D; -extern PFNGLCOPYTEXTUREIMAGE1DEXTPROC gl3wCopyTextureImage1DEXT; -extern PFNGLCOPYTEXTUREIMAGE2DEXTPROC gl3wCopyTextureImage2DEXT; -extern PFNGLCOPYTEXTURESUBIMAGE1DPROC gl3wCopyTextureSubImage1D; -extern PFNGLCOPYTEXTURESUBIMAGE1DEXTPROC gl3wCopyTextureSubImage1DEXT; -extern PFNGLCOPYTEXTURESUBIMAGE2DPROC gl3wCopyTextureSubImage2D; -extern PFNGLCOPYTEXTURESUBIMAGE2DEXTPROC gl3wCopyTextureSubImage2DEXT; -extern PFNGLCOPYTEXTURESUBIMAGE3DPROC gl3wCopyTextureSubImage3D; -extern PFNGLCOPYTEXTURESUBIMAGE3DEXTPROC gl3wCopyTextureSubImage3DEXT; -extern PFNGLCOVERFILLPATHINSTANCEDNVPROC gl3wCoverFillPathInstancedNV; -extern PFNGLCOVERFILLPATHNVPROC gl3wCoverFillPathNV; -extern PFNGLCOVERSTROKEPATHINSTANCEDNVPROC gl3wCoverStrokePathInstancedNV; -extern PFNGLCOVERSTROKEPATHNVPROC gl3wCoverStrokePathNV; -extern PFNGLCOVERAGEMODULATIONNVPROC gl3wCoverageModulationNV; -extern PFNGLCOVERAGEMODULATIONTABLENVPROC gl3wCoverageModulationTableNV; -extern PFNGLCREATEBUFFERSPROC gl3wCreateBuffers; -extern PFNGLCREATECOMMANDLISTSNVPROC gl3wCreateCommandListsNV; -extern PFNGLCREATEFRAMEBUFFERSPROC gl3wCreateFramebuffers; -extern PFNGLCREATEPERFQUERYINTELPROC gl3wCreatePerfQueryINTEL; -extern PFNGLCREATEPROGRAMPROC gl3wCreateProgram; -extern PFNGLCREATEPROGRAMPIPELINESPROC gl3wCreateProgramPipelines; -extern PFNGLCREATEQUERIESPROC gl3wCreateQueries; -extern PFNGLCREATERENDERBUFFERSPROC gl3wCreateRenderbuffers; -extern PFNGLCREATESAMPLERSPROC gl3wCreateSamplers; -extern PFNGLCREATESHADERPROC gl3wCreateShader; -extern PFNGLCREATESHADERPROGRAMEXTPROC gl3wCreateShaderProgramEXT; -extern PFNGLCREATESHADERPROGRAMVPROC gl3wCreateShaderProgramv; -extern PFNGLCREATESTATESNVPROC gl3wCreateStatesNV; -extern PFNGLCREATESYNCFROMCLEVENTARBPROC gl3wCreateSyncFromCLeventARB; -extern PFNGLCREATETEXTURESPROC gl3wCreateTextures; -extern PFNGLCREATETRANSFORMFEEDBACKSPROC gl3wCreateTransformFeedbacks; -extern PFNGLCREATEVERTEXARRAYSPROC gl3wCreateVertexArrays; -extern PFNGLCULLFACEPROC gl3wCullFace; -extern PFNGLDEBUGMESSAGECALLBACKPROC gl3wDebugMessageCallback; -extern PFNGLDEBUGMESSAGECALLBACKARBPROC gl3wDebugMessageCallbackARB; -extern PFNGLDEBUGMESSAGECONTROLPROC gl3wDebugMessageControl; -extern PFNGLDEBUGMESSAGECONTROLARBPROC gl3wDebugMessageControlARB; -extern PFNGLDEBUGMESSAGEINSERTPROC gl3wDebugMessageInsert; -extern PFNGLDEBUGMESSAGEINSERTARBPROC gl3wDebugMessageInsertARB; -extern PFNGLDELETEBUFFERSPROC gl3wDeleteBuffers; -extern PFNGLDELETECOMMANDLISTSNVPROC gl3wDeleteCommandListsNV; -extern PFNGLDELETEFRAMEBUFFERSPROC gl3wDeleteFramebuffers; -extern PFNGLDELETENAMEDSTRINGARBPROC gl3wDeleteNamedStringARB; -extern PFNGLDELETEPATHSNVPROC gl3wDeletePathsNV; -extern PFNGLDELETEPERFMONITORSAMDPROC gl3wDeletePerfMonitorsAMD; -extern PFNGLDELETEPERFQUERYINTELPROC gl3wDeletePerfQueryINTEL; -extern PFNGLDELETEPROGRAMPROC gl3wDeleteProgram; -extern PFNGLDELETEPROGRAMPIPELINESPROC gl3wDeleteProgramPipelines; -extern PFNGLDELETEQUERIESPROC gl3wDeleteQueries; -extern PFNGLDELETERENDERBUFFERSPROC gl3wDeleteRenderbuffers; -extern PFNGLDELETESAMPLERSPROC gl3wDeleteSamplers; -extern PFNGLDELETESHADERPROC gl3wDeleteShader; -extern PFNGLDELETESTATESNVPROC gl3wDeleteStatesNV; -extern PFNGLDELETESYNCPROC gl3wDeleteSync; -extern PFNGLDELETETEXTURESPROC gl3wDeleteTextures; -extern PFNGLDELETETRANSFORMFEEDBACKSPROC gl3wDeleteTransformFeedbacks; -extern PFNGLDELETEVERTEXARRAYSPROC gl3wDeleteVertexArrays; -extern PFNGLDEPTHFUNCPROC gl3wDepthFunc; -extern PFNGLDEPTHMASKPROC gl3wDepthMask; -extern PFNGLDEPTHRANGEPROC gl3wDepthRange; -extern PFNGLDEPTHRANGEARRAYVPROC gl3wDepthRangeArrayv; -extern PFNGLDEPTHRANGEINDEXEDPROC gl3wDepthRangeIndexed; -extern PFNGLDEPTHRANGEFPROC gl3wDepthRangef; -extern PFNGLDETACHSHADERPROC gl3wDetachShader; -extern PFNGLDISABLEPROC gl3wDisable; -extern PFNGLDISABLECLIENTSTATEINDEXEDEXTPROC gl3wDisableClientStateIndexedEXT; -extern PFNGLDISABLECLIENTSTATEIEXTPROC gl3wDisableClientStateiEXT; -extern PFNGLDISABLEINDEXEDEXTPROC gl3wDisableIndexedEXT; -extern PFNGLDISABLEVERTEXARRAYATTRIBPROC gl3wDisableVertexArrayAttrib; -extern PFNGLDISABLEVERTEXARRAYATTRIBEXTPROC gl3wDisableVertexArrayAttribEXT; -extern PFNGLDISABLEVERTEXARRAYEXTPROC gl3wDisableVertexArrayEXT; -extern PFNGLDISABLEVERTEXATTRIBARRAYPROC gl3wDisableVertexAttribArray; -extern PFNGLDISABLEIPROC gl3wDisablei; -extern PFNGLDISPATCHCOMPUTEPROC gl3wDispatchCompute; -extern PFNGLDISPATCHCOMPUTEGROUPSIZEARBPROC gl3wDispatchComputeGroupSizeARB; -extern PFNGLDISPATCHCOMPUTEINDIRECTPROC gl3wDispatchComputeIndirect; -extern PFNGLDRAWARRAYSPROC gl3wDrawArrays; -extern PFNGLDRAWARRAYSINDIRECTPROC gl3wDrawArraysIndirect; -extern PFNGLDRAWARRAYSINSTANCEDPROC gl3wDrawArraysInstanced; -extern PFNGLDRAWARRAYSINSTANCEDARBPROC gl3wDrawArraysInstancedARB; -extern PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC gl3wDrawArraysInstancedBaseInstance; -extern PFNGLDRAWARRAYSINSTANCEDEXTPROC gl3wDrawArraysInstancedEXT; -extern PFNGLDRAWBUFFERPROC gl3wDrawBuffer; -extern PFNGLDRAWBUFFERSPROC gl3wDrawBuffers; -extern PFNGLDRAWCOMMANDSADDRESSNVPROC gl3wDrawCommandsAddressNV; -extern PFNGLDRAWCOMMANDSNVPROC gl3wDrawCommandsNV; -extern PFNGLDRAWCOMMANDSSTATESADDRESSNVPROC gl3wDrawCommandsStatesAddressNV; -extern PFNGLDRAWCOMMANDSSTATESNVPROC gl3wDrawCommandsStatesNV; -extern PFNGLDRAWELEMENTSPROC gl3wDrawElements; -extern PFNGLDRAWELEMENTSBASEVERTEXPROC gl3wDrawElementsBaseVertex; -extern PFNGLDRAWELEMENTSINDIRECTPROC gl3wDrawElementsIndirect; -extern PFNGLDRAWELEMENTSINSTANCEDPROC gl3wDrawElementsInstanced; -extern PFNGLDRAWELEMENTSINSTANCEDARBPROC gl3wDrawElementsInstancedARB; -extern PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC gl3wDrawElementsInstancedBaseInstance; -extern PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC gl3wDrawElementsInstancedBaseVertex; -extern PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC gl3wDrawElementsInstancedBaseVertexBaseInstance; -extern PFNGLDRAWELEMENTSINSTANCEDEXTPROC gl3wDrawElementsInstancedEXT; -extern PFNGLDRAWRANGEELEMENTSPROC gl3wDrawRangeElements; -extern PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC gl3wDrawRangeElementsBaseVertex; -extern PFNGLDRAWTRANSFORMFEEDBACKPROC gl3wDrawTransformFeedback; -extern PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC gl3wDrawTransformFeedbackInstanced; -extern PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC gl3wDrawTransformFeedbackStream; -extern PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC gl3wDrawTransformFeedbackStreamInstanced; -extern PFNGLDRAWVKIMAGENVPROC gl3wDrawVkImageNV; -extern PFNGLEDGEFLAGFORMATNVPROC gl3wEdgeFlagFormatNV; -extern PFNGLENABLEPROC gl3wEnable; -extern PFNGLENABLECLIENTSTATEINDEXEDEXTPROC gl3wEnableClientStateIndexedEXT; -extern PFNGLENABLECLIENTSTATEIEXTPROC gl3wEnableClientStateiEXT; -extern PFNGLENABLEINDEXEDEXTPROC gl3wEnableIndexedEXT; -extern PFNGLENABLEVERTEXARRAYATTRIBPROC gl3wEnableVertexArrayAttrib; -extern PFNGLENABLEVERTEXARRAYATTRIBEXTPROC gl3wEnableVertexArrayAttribEXT; -extern PFNGLENABLEVERTEXARRAYEXTPROC gl3wEnableVertexArrayEXT; -extern PFNGLENABLEVERTEXATTRIBARRAYPROC gl3wEnableVertexAttribArray; -extern PFNGLENABLEIPROC gl3wEnablei; -extern PFNGLENDCONDITIONALRENDERPROC gl3wEndConditionalRender; -extern PFNGLENDCONDITIONALRENDERNVPROC gl3wEndConditionalRenderNV; -extern PFNGLENDPERFMONITORAMDPROC gl3wEndPerfMonitorAMD; -extern PFNGLENDPERFQUERYINTELPROC gl3wEndPerfQueryINTEL; -extern PFNGLENDQUERYPROC gl3wEndQuery; -extern PFNGLENDQUERYINDEXEDPROC gl3wEndQueryIndexed; -extern PFNGLENDTRANSFORMFEEDBACKPROC gl3wEndTransformFeedback; -extern PFNGLEVALUATEDEPTHVALUESARBPROC gl3wEvaluateDepthValuesARB; -extern PFNGLFENCESYNCPROC gl3wFenceSync; -extern PFNGLFINISHPROC gl3wFinish; -extern PFNGLFLUSHPROC gl3wFlush; -extern PFNGLFLUSHMAPPEDBUFFERRANGEPROC gl3wFlushMappedBufferRange; -extern PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEPROC gl3wFlushMappedNamedBufferRange; -extern PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEEXTPROC gl3wFlushMappedNamedBufferRangeEXT; -extern PFNGLFOGCOORDFORMATNVPROC gl3wFogCoordFormatNV; -extern PFNGLFRAGMENTCOVERAGECOLORNVPROC gl3wFragmentCoverageColorNV; -extern PFNGLFRAMEBUFFERDRAWBUFFEREXTPROC gl3wFramebufferDrawBufferEXT; -extern PFNGLFRAMEBUFFERDRAWBUFFERSEXTPROC gl3wFramebufferDrawBuffersEXT; -extern PFNGLFRAMEBUFFERPARAMETERIPROC gl3wFramebufferParameteri; -extern PFNGLFRAMEBUFFERREADBUFFEREXTPROC gl3wFramebufferReadBufferEXT; -extern PFNGLFRAMEBUFFERRENDERBUFFERPROC gl3wFramebufferRenderbuffer; -extern PFNGLFRAMEBUFFERSAMPLELOCATIONSFVARBPROC gl3wFramebufferSampleLocationsfvARB; -extern PFNGLFRAMEBUFFERSAMPLELOCATIONSFVNVPROC gl3wFramebufferSampleLocationsfvNV; -extern PFNGLFRAMEBUFFERTEXTUREPROC gl3wFramebufferTexture; -extern PFNGLFRAMEBUFFERTEXTURE1DPROC gl3wFramebufferTexture1D; -extern PFNGLFRAMEBUFFERTEXTURE2DPROC gl3wFramebufferTexture2D; -extern PFNGLFRAMEBUFFERTEXTURE3DPROC gl3wFramebufferTexture3D; -extern PFNGLFRAMEBUFFERTEXTUREARBPROC gl3wFramebufferTextureARB; -extern PFNGLFRAMEBUFFERTEXTUREFACEARBPROC gl3wFramebufferTextureFaceARB; -extern PFNGLFRAMEBUFFERTEXTURELAYERPROC gl3wFramebufferTextureLayer; -extern PFNGLFRAMEBUFFERTEXTURELAYERARBPROC gl3wFramebufferTextureLayerARB; -extern PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC gl3wFramebufferTextureMultiviewOVR; -extern PFNGLFRONTFACEPROC gl3wFrontFace; -extern PFNGLGENBUFFERSPROC gl3wGenBuffers; -extern PFNGLGENFRAMEBUFFERSPROC gl3wGenFramebuffers; -extern PFNGLGENPATHSNVPROC gl3wGenPathsNV; -extern PFNGLGENPERFMONITORSAMDPROC gl3wGenPerfMonitorsAMD; -extern PFNGLGENPROGRAMPIPELINESPROC gl3wGenProgramPipelines; -extern PFNGLGENQUERIESPROC gl3wGenQueries; -extern PFNGLGENRENDERBUFFERSPROC gl3wGenRenderbuffers; -extern PFNGLGENSAMPLERSPROC gl3wGenSamplers; -extern PFNGLGENTEXTURESPROC gl3wGenTextures; -extern PFNGLGENTRANSFORMFEEDBACKSPROC gl3wGenTransformFeedbacks; -extern PFNGLGENVERTEXARRAYSPROC gl3wGenVertexArrays; -extern PFNGLGENERATEMIPMAPPROC gl3wGenerateMipmap; -extern PFNGLGENERATEMULTITEXMIPMAPEXTPROC gl3wGenerateMultiTexMipmapEXT; -extern PFNGLGENERATETEXTUREMIPMAPPROC gl3wGenerateTextureMipmap; -extern PFNGLGENERATETEXTUREMIPMAPEXTPROC gl3wGenerateTextureMipmapEXT; -extern PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC gl3wGetActiveAtomicCounterBufferiv; -extern PFNGLGETACTIVEATTRIBPROC gl3wGetActiveAttrib; -extern PFNGLGETACTIVESUBROUTINENAMEPROC gl3wGetActiveSubroutineName; -extern PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC gl3wGetActiveSubroutineUniformName; -extern PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC gl3wGetActiveSubroutineUniformiv; -extern PFNGLGETACTIVEUNIFORMPROC gl3wGetActiveUniform; -extern PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC gl3wGetActiveUniformBlockName; -extern PFNGLGETACTIVEUNIFORMBLOCKIVPROC gl3wGetActiveUniformBlockiv; -extern PFNGLGETACTIVEUNIFORMNAMEPROC gl3wGetActiveUniformName; -extern PFNGLGETACTIVEUNIFORMSIVPROC gl3wGetActiveUniformsiv; -extern PFNGLGETATTACHEDSHADERSPROC gl3wGetAttachedShaders; -extern PFNGLGETATTRIBLOCATIONPROC gl3wGetAttribLocation; -extern PFNGLGETBOOLEANINDEXEDVEXTPROC gl3wGetBooleanIndexedvEXT; -extern PFNGLGETBOOLEANI_VPROC gl3wGetBooleani_v; -extern PFNGLGETBOOLEANVPROC gl3wGetBooleanv; -extern PFNGLGETBUFFERPARAMETERI64VPROC gl3wGetBufferParameteri64v; -extern PFNGLGETBUFFERPARAMETERIVPROC gl3wGetBufferParameteriv; -extern PFNGLGETBUFFERPARAMETERUI64VNVPROC gl3wGetBufferParameterui64vNV; -extern PFNGLGETBUFFERPOINTERVPROC gl3wGetBufferPointerv; -extern PFNGLGETBUFFERSUBDATAPROC gl3wGetBufferSubData; -extern PFNGLGETCOMMANDHEADERNVPROC gl3wGetCommandHeaderNV; -extern PFNGLGETCOMPRESSEDMULTITEXIMAGEEXTPROC gl3wGetCompressedMultiTexImageEXT; -extern PFNGLGETCOMPRESSEDTEXIMAGEPROC gl3wGetCompressedTexImage; -extern PFNGLGETCOMPRESSEDTEXTUREIMAGEPROC gl3wGetCompressedTextureImage; -extern PFNGLGETCOMPRESSEDTEXTUREIMAGEEXTPROC gl3wGetCompressedTextureImageEXT; -extern PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC gl3wGetCompressedTextureSubImage; -extern PFNGLGETCOVERAGEMODULATIONTABLENVPROC gl3wGetCoverageModulationTableNV; -extern PFNGLGETDEBUGMESSAGELOGPROC gl3wGetDebugMessageLog; -extern PFNGLGETDEBUGMESSAGELOGARBPROC gl3wGetDebugMessageLogARB; -extern PFNGLGETDOUBLEINDEXEDVEXTPROC gl3wGetDoubleIndexedvEXT; -extern PFNGLGETDOUBLEI_VPROC gl3wGetDoublei_v; -extern PFNGLGETDOUBLEI_VEXTPROC gl3wGetDoublei_vEXT; -extern PFNGLGETDOUBLEVPROC gl3wGetDoublev; -extern PFNGLGETERRORPROC gl3wGetError; -extern PFNGLGETFIRSTPERFQUERYIDINTELPROC gl3wGetFirstPerfQueryIdINTEL; -extern PFNGLGETFLOATINDEXEDVEXTPROC gl3wGetFloatIndexedvEXT; -extern PFNGLGETFLOATI_VPROC gl3wGetFloati_v; -extern PFNGLGETFLOATI_VEXTPROC gl3wGetFloati_vEXT; -extern PFNGLGETFLOATVPROC gl3wGetFloatv; -extern PFNGLGETFRAGDATAINDEXPROC gl3wGetFragDataIndex; -extern PFNGLGETFRAGDATALOCATIONPROC gl3wGetFragDataLocation; -extern PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC gl3wGetFramebufferAttachmentParameteriv; -extern PFNGLGETFRAMEBUFFERPARAMETERIVPROC gl3wGetFramebufferParameteriv; -extern PFNGLGETFRAMEBUFFERPARAMETERIVEXTPROC gl3wGetFramebufferParameterivEXT; -extern PFNGLGETGRAPHICSRESETSTATUSPROC gl3wGetGraphicsResetStatus; -extern PFNGLGETGRAPHICSRESETSTATUSARBPROC gl3wGetGraphicsResetStatusARB; -extern PFNGLGETIMAGEHANDLEARBPROC gl3wGetImageHandleARB; -extern PFNGLGETIMAGEHANDLENVPROC gl3wGetImageHandleNV; -extern PFNGLGETINTEGER64I_VPROC gl3wGetInteger64i_v; -extern PFNGLGETINTEGER64VPROC gl3wGetInteger64v; -extern PFNGLGETINTEGERINDEXEDVEXTPROC gl3wGetIntegerIndexedvEXT; -extern PFNGLGETINTEGERI_VPROC gl3wGetIntegeri_v; -extern PFNGLGETINTEGERUI64I_VNVPROC gl3wGetIntegerui64i_vNV; -extern PFNGLGETINTEGERUI64VNVPROC gl3wGetIntegerui64vNV; -extern PFNGLGETINTEGERVPROC gl3wGetIntegerv; -extern PFNGLGETINTERNALFORMATSAMPLEIVNVPROC gl3wGetInternalformatSampleivNV; -extern PFNGLGETINTERNALFORMATI64VPROC gl3wGetInternalformati64v; -extern PFNGLGETINTERNALFORMATIVPROC gl3wGetInternalformativ; -extern PFNGLGETMULTITEXENVFVEXTPROC gl3wGetMultiTexEnvfvEXT; -extern PFNGLGETMULTITEXENVIVEXTPROC gl3wGetMultiTexEnvivEXT; -extern PFNGLGETMULTITEXGENDVEXTPROC gl3wGetMultiTexGendvEXT; -extern PFNGLGETMULTITEXGENFVEXTPROC gl3wGetMultiTexGenfvEXT; -extern PFNGLGETMULTITEXGENIVEXTPROC gl3wGetMultiTexGenivEXT; -extern PFNGLGETMULTITEXIMAGEEXTPROC gl3wGetMultiTexImageEXT; -extern PFNGLGETMULTITEXLEVELPARAMETERFVEXTPROC gl3wGetMultiTexLevelParameterfvEXT; -extern PFNGLGETMULTITEXLEVELPARAMETERIVEXTPROC gl3wGetMultiTexLevelParameterivEXT; -extern PFNGLGETMULTITEXPARAMETERIIVEXTPROC gl3wGetMultiTexParameterIivEXT; -extern PFNGLGETMULTITEXPARAMETERIUIVEXTPROC gl3wGetMultiTexParameterIuivEXT; -extern PFNGLGETMULTITEXPARAMETERFVEXTPROC gl3wGetMultiTexParameterfvEXT; -extern PFNGLGETMULTITEXPARAMETERIVEXTPROC gl3wGetMultiTexParameterivEXT; -extern PFNGLGETMULTISAMPLEFVPROC gl3wGetMultisamplefv; -extern PFNGLGETNAMEDBUFFERPARAMETERI64VPROC gl3wGetNamedBufferParameteri64v; -extern PFNGLGETNAMEDBUFFERPARAMETERIVPROC gl3wGetNamedBufferParameteriv; -extern PFNGLGETNAMEDBUFFERPARAMETERIVEXTPROC gl3wGetNamedBufferParameterivEXT; -extern PFNGLGETNAMEDBUFFERPARAMETERUI64VNVPROC gl3wGetNamedBufferParameterui64vNV; -extern PFNGLGETNAMEDBUFFERPOINTERVPROC gl3wGetNamedBufferPointerv; -extern PFNGLGETNAMEDBUFFERPOINTERVEXTPROC gl3wGetNamedBufferPointervEXT; -extern PFNGLGETNAMEDBUFFERSUBDATAPROC gl3wGetNamedBufferSubData; -extern PFNGLGETNAMEDBUFFERSUBDATAEXTPROC gl3wGetNamedBufferSubDataEXT; -extern PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC gl3wGetNamedFramebufferAttachmentParameteriv; -extern PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC gl3wGetNamedFramebufferAttachmentParameterivEXT; -extern PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVPROC gl3wGetNamedFramebufferParameteriv; -extern PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVEXTPROC gl3wGetNamedFramebufferParameterivEXT; -extern PFNGLGETNAMEDPROGRAMLOCALPARAMETERIIVEXTPROC gl3wGetNamedProgramLocalParameterIivEXT; -extern PFNGLGETNAMEDPROGRAMLOCALPARAMETERIUIVEXTPROC gl3wGetNamedProgramLocalParameterIuivEXT; -extern PFNGLGETNAMEDPROGRAMLOCALPARAMETERDVEXTPROC gl3wGetNamedProgramLocalParameterdvEXT; -extern PFNGLGETNAMEDPROGRAMLOCALPARAMETERFVEXTPROC gl3wGetNamedProgramLocalParameterfvEXT; -extern PFNGLGETNAMEDPROGRAMSTRINGEXTPROC gl3wGetNamedProgramStringEXT; -extern PFNGLGETNAMEDPROGRAMIVEXTPROC gl3wGetNamedProgramivEXT; -extern PFNGLGETNAMEDRENDERBUFFERPARAMETERIVPROC gl3wGetNamedRenderbufferParameteriv; -extern PFNGLGETNAMEDRENDERBUFFERPARAMETERIVEXTPROC gl3wGetNamedRenderbufferParameterivEXT; -extern PFNGLGETNAMEDSTRINGARBPROC gl3wGetNamedStringARB; -extern PFNGLGETNAMEDSTRINGIVARBPROC gl3wGetNamedStringivARB; -extern PFNGLGETNEXTPERFQUERYIDINTELPROC gl3wGetNextPerfQueryIdINTEL; -extern PFNGLGETOBJECTLABELPROC gl3wGetObjectLabel; -extern PFNGLGETOBJECTLABELEXTPROC gl3wGetObjectLabelEXT; -extern PFNGLGETOBJECTPTRLABELPROC gl3wGetObjectPtrLabel; -extern PFNGLGETPATHCOMMANDSNVPROC gl3wGetPathCommandsNV; -extern PFNGLGETPATHCOORDSNVPROC gl3wGetPathCoordsNV; -extern PFNGLGETPATHDASHARRAYNVPROC gl3wGetPathDashArrayNV; -extern PFNGLGETPATHLENGTHNVPROC gl3wGetPathLengthNV; -extern PFNGLGETPATHMETRICRANGENVPROC gl3wGetPathMetricRangeNV; -extern PFNGLGETPATHMETRICSNVPROC gl3wGetPathMetricsNV; -extern PFNGLGETPATHPARAMETERFVNVPROC gl3wGetPathParameterfvNV; -extern PFNGLGETPATHPARAMETERIVNVPROC gl3wGetPathParameterivNV; -extern PFNGLGETPATHSPACINGNVPROC gl3wGetPathSpacingNV; -extern PFNGLGETPERFCOUNTERINFOINTELPROC gl3wGetPerfCounterInfoINTEL; -extern PFNGLGETPERFMONITORCOUNTERDATAAMDPROC gl3wGetPerfMonitorCounterDataAMD; -extern PFNGLGETPERFMONITORCOUNTERINFOAMDPROC gl3wGetPerfMonitorCounterInfoAMD; -extern PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC gl3wGetPerfMonitorCounterStringAMD; -extern PFNGLGETPERFMONITORCOUNTERSAMDPROC gl3wGetPerfMonitorCountersAMD; -extern PFNGLGETPERFMONITORGROUPSTRINGAMDPROC gl3wGetPerfMonitorGroupStringAMD; -extern PFNGLGETPERFMONITORGROUPSAMDPROC gl3wGetPerfMonitorGroupsAMD; -extern PFNGLGETPERFQUERYDATAINTELPROC gl3wGetPerfQueryDataINTEL; -extern PFNGLGETPERFQUERYIDBYNAMEINTELPROC gl3wGetPerfQueryIdByNameINTEL; -extern PFNGLGETPERFQUERYINFOINTELPROC gl3wGetPerfQueryInfoINTEL; -extern PFNGLGETPOINTERINDEXEDVEXTPROC gl3wGetPointerIndexedvEXT; -extern PFNGLGETPOINTERI_VEXTPROC gl3wGetPointeri_vEXT; -extern PFNGLGETPOINTERVPROC gl3wGetPointerv; -extern PFNGLGETPROGRAMBINARYPROC gl3wGetProgramBinary; -extern PFNGLGETPROGRAMINFOLOGPROC gl3wGetProgramInfoLog; -extern PFNGLGETPROGRAMINTERFACEIVPROC gl3wGetProgramInterfaceiv; -extern PFNGLGETPROGRAMPIPELINEINFOLOGPROC gl3wGetProgramPipelineInfoLog; -extern PFNGLGETPROGRAMPIPELINEIVPROC gl3wGetProgramPipelineiv; -extern PFNGLGETPROGRAMRESOURCEINDEXPROC gl3wGetProgramResourceIndex; -extern PFNGLGETPROGRAMRESOURCELOCATIONPROC gl3wGetProgramResourceLocation; -extern PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC gl3wGetProgramResourceLocationIndex; -extern PFNGLGETPROGRAMRESOURCENAMEPROC gl3wGetProgramResourceName; -extern PFNGLGETPROGRAMRESOURCEFVNVPROC gl3wGetProgramResourcefvNV; -extern PFNGLGETPROGRAMRESOURCEIVPROC gl3wGetProgramResourceiv; -extern PFNGLGETPROGRAMSTAGEIVPROC gl3wGetProgramStageiv; -extern PFNGLGETPROGRAMIVPROC gl3wGetProgramiv; -extern PFNGLGETQUERYBUFFEROBJECTI64VPROC gl3wGetQueryBufferObjecti64v; -extern PFNGLGETQUERYBUFFEROBJECTIVPROC gl3wGetQueryBufferObjectiv; -extern PFNGLGETQUERYBUFFEROBJECTUI64VPROC gl3wGetQueryBufferObjectui64v; -extern PFNGLGETQUERYBUFFEROBJECTUIVPROC gl3wGetQueryBufferObjectuiv; -extern PFNGLGETQUERYINDEXEDIVPROC gl3wGetQueryIndexediv; -extern PFNGLGETQUERYOBJECTI64VPROC gl3wGetQueryObjecti64v; -extern PFNGLGETQUERYOBJECTIVPROC gl3wGetQueryObjectiv; -extern PFNGLGETQUERYOBJECTUI64VPROC gl3wGetQueryObjectui64v; -extern PFNGLGETQUERYOBJECTUIVPROC gl3wGetQueryObjectuiv; -extern PFNGLGETQUERYIVPROC gl3wGetQueryiv; -extern PFNGLGETRENDERBUFFERPARAMETERIVPROC gl3wGetRenderbufferParameteriv; -extern PFNGLGETSAMPLERPARAMETERIIVPROC gl3wGetSamplerParameterIiv; -extern PFNGLGETSAMPLERPARAMETERIUIVPROC gl3wGetSamplerParameterIuiv; -extern PFNGLGETSAMPLERPARAMETERFVPROC gl3wGetSamplerParameterfv; -extern PFNGLGETSAMPLERPARAMETERIVPROC gl3wGetSamplerParameteriv; -extern PFNGLGETSHADERINFOLOGPROC gl3wGetShaderInfoLog; -extern PFNGLGETSHADERPRECISIONFORMATPROC gl3wGetShaderPrecisionFormat; -extern PFNGLGETSHADERSOURCEPROC gl3wGetShaderSource; -extern PFNGLGETSHADERIVPROC gl3wGetShaderiv; -extern PFNGLGETSTAGEINDEXNVPROC gl3wGetStageIndexNV; -extern PFNGLGETSTRINGPROC gl3wGetString; -extern PFNGLGETSTRINGIPROC gl3wGetStringi; -extern PFNGLGETSUBROUTINEINDEXPROC gl3wGetSubroutineIndex; -extern PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC gl3wGetSubroutineUniformLocation; -extern PFNGLGETSYNCIVPROC gl3wGetSynciv; -extern PFNGLGETTEXIMAGEPROC gl3wGetTexImage; -extern PFNGLGETTEXLEVELPARAMETERFVPROC gl3wGetTexLevelParameterfv; -extern PFNGLGETTEXLEVELPARAMETERIVPROC gl3wGetTexLevelParameteriv; -extern PFNGLGETTEXPARAMETERIIVPROC gl3wGetTexParameterIiv; -extern PFNGLGETTEXPARAMETERIUIVPROC gl3wGetTexParameterIuiv; -extern PFNGLGETTEXPARAMETERFVPROC gl3wGetTexParameterfv; -extern PFNGLGETTEXPARAMETERIVPROC gl3wGetTexParameteriv; -extern PFNGLGETTEXTUREHANDLEARBPROC gl3wGetTextureHandleARB; -extern PFNGLGETTEXTUREHANDLENVPROC gl3wGetTextureHandleNV; -extern PFNGLGETTEXTUREIMAGEPROC gl3wGetTextureImage; -extern PFNGLGETTEXTUREIMAGEEXTPROC gl3wGetTextureImageEXT; -extern PFNGLGETTEXTURELEVELPARAMETERFVPROC gl3wGetTextureLevelParameterfv; -extern PFNGLGETTEXTURELEVELPARAMETERFVEXTPROC gl3wGetTextureLevelParameterfvEXT; -extern PFNGLGETTEXTURELEVELPARAMETERIVPROC gl3wGetTextureLevelParameteriv; -extern PFNGLGETTEXTURELEVELPARAMETERIVEXTPROC gl3wGetTextureLevelParameterivEXT; -extern PFNGLGETTEXTUREPARAMETERIIVPROC gl3wGetTextureParameterIiv; -extern PFNGLGETTEXTUREPARAMETERIIVEXTPROC gl3wGetTextureParameterIivEXT; -extern PFNGLGETTEXTUREPARAMETERIUIVPROC gl3wGetTextureParameterIuiv; -extern PFNGLGETTEXTUREPARAMETERIUIVEXTPROC gl3wGetTextureParameterIuivEXT; -extern PFNGLGETTEXTUREPARAMETERFVPROC gl3wGetTextureParameterfv; -extern PFNGLGETTEXTUREPARAMETERFVEXTPROC gl3wGetTextureParameterfvEXT; -extern PFNGLGETTEXTUREPARAMETERIVPROC gl3wGetTextureParameteriv; -extern PFNGLGETTEXTUREPARAMETERIVEXTPROC gl3wGetTextureParameterivEXT; -extern PFNGLGETTEXTURESAMPLERHANDLEARBPROC gl3wGetTextureSamplerHandleARB; -extern PFNGLGETTEXTURESAMPLERHANDLENVPROC gl3wGetTextureSamplerHandleNV; -extern PFNGLGETTEXTURESUBIMAGEPROC gl3wGetTextureSubImage; -extern PFNGLGETTRANSFORMFEEDBACKVARYINGPROC gl3wGetTransformFeedbackVarying; -extern PFNGLGETTRANSFORMFEEDBACKI64_VPROC gl3wGetTransformFeedbacki64_v; -extern PFNGLGETTRANSFORMFEEDBACKI_VPROC gl3wGetTransformFeedbacki_v; -extern PFNGLGETTRANSFORMFEEDBACKIVPROC gl3wGetTransformFeedbackiv; -extern PFNGLGETUNIFORMBLOCKINDEXPROC gl3wGetUniformBlockIndex; -extern PFNGLGETUNIFORMINDICESPROC gl3wGetUniformIndices; -extern PFNGLGETUNIFORMLOCATIONPROC gl3wGetUniformLocation; -extern PFNGLGETUNIFORMSUBROUTINEUIVPROC gl3wGetUniformSubroutineuiv; -extern PFNGLGETUNIFORMDVPROC gl3wGetUniformdv; -extern PFNGLGETUNIFORMFVPROC gl3wGetUniformfv; -extern PFNGLGETUNIFORMI64VARBPROC gl3wGetUniformi64vARB; -extern PFNGLGETUNIFORMI64VNVPROC gl3wGetUniformi64vNV; -extern PFNGLGETUNIFORMIVPROC gl3wGetUniformiv; -extern PFNGLGETUNIFORMUI64VARBPROC gl3wGetUniformui64vARB; -extern PFNGLGETUNIFORMUI64VNVPROC gl3wGetUniformui64vNV; -extern PFNGLGETUNIFORMUIVPROC gl3wGetUniformuiv; -extern PFNGLGETVERTEXARRAYINDEXED64IVPROC gl3wGetVertexArrayIndexed64iv; -extern PFNGLGETVERTEXARRAYINDEXEDIVPROC gl3wGetVertexArrayIndexediv; -extern PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC gl3wGetVertexArrayIntegeri_vEXT; -extern PFNGLGETVERTEXARRAYINTEGERVEXTPROC gl3wGetVertexArrayIntegervEXT; -extern PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC gl3wGetVertexArrayPointeri_vEXT; -extern PFNGLGETVERTEXARRAYPOINTERVEXTPROC gl3wGetVertexArrayPointervEXT; -extern PFNGLGETVERTEXARRAYIVPROC gl3wGetVertexArrayiv; -extern PFNGLGETVERTEXATTRIBIIVPROC gl3wGetVertexAttribIiv; -extern PFNGLGETVERTEXATTRIBIUIVPROC gl3wGetVertexAttribIuiv; -extern PFNGLGETVERTEXATTRIBLDVPROC gl3wGetVertexAttribLdv; -extern PFNGLGETVERTEXATTRIBLI64VNVPROC gl3wGetVertexAttribLi64vNV; -extern PFNGLGETVERTEXATTRIBLUI64VARBPROC gl3wGetVertexAttribLui64vARB; -extern PFNGLGETVERTEXATTRIBLUI64VNVPROC gl3wGetVertexAttribLui64vNV; -extern PFNGLGETVERTEXATTRIBPOINTERVPROC gl3wGetVertexAttribPointerv; -extern PFNGLGETVERTEXATTRIBDVPROC gl3wGetVertexAttribdv; -extern PFNGLGETVERTEXATTRIBFVPROC gl3wGetVertexAttribfv; -extern PFNGLGETVERTEXATTRIBIVPROC gl3wGetVertexAttribiv; -extern PFNGLGETVKPROCADDRNVPROC gl3wGetVkProcAddrNV; -extern PFNGLGETNCOMPRESSEDTEXIMAGEPROC gl3wGetnCompressedTexImage; -extern PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC gl3wGetnCompressedTexImageARB; -extern PFNGLGETNTEXIMAGEPROC gl3wGetnTexImage; -extern PFNGLGETNTEXIMAGEARBPROC gl3wGetnTexImageARB; -extern PFNGLGETNUNIFORMDVPROC gl3wGetnUniformdv; -extern PFNGLGETNUNIFORMDVARBPROC gl3wGetnUniformdvARB; -extern PFNGLGETNUNIFORMFVPROC gl3wGetnUniformfv; -extern PFNGLGETNUNIFORMFVARBPROC gl3wGetnUniformfvARB; -extern PFNGLGETNUNIFORMI64VARBPROC gl3wGetnUniformi64vARB; -extern PFNGLGETNUNIFORMIVPROC gl3wGetnUniformiv; -extern PFNGLGETNUNIFORMIVARBPROC gl3wGetnUniformivARB; -extern PFNGLGETNUNIFORMUI64VARBPROC gl3wGetnUniformui64vARB; -extern PFNGLGETNUNIFORMUIVPROC gl3wGetnUniformuiv; -extern PFNGLGETNUNIFORMUIVARBPROC gl3wGetnUniformuivARB; -extern PFNGLHINTPROC gl3wHint; -extern PFNGLINDEXFORMATNVPROC gl3wIndexFormatNV; -extern PFNGLINSERTEVENTMARKEREXTPROC gl3wInsertEventMarkerEXT; -extern PFNGLINTERPOLATEPATHSNVPROC gl3wInterpolatePathsNV; -extern PFNGLINVALIDATEBUFFERDATAPROC gl3wInvalidateBufferData; -extern PFNGLINVALIDATEBUFFERSUBDATAPROC gl3wInvalidateBufferSubData; -extern PFNGLINVALIDATEFRAMEBUFFERPROC gl3wInvalidateFramebuffer; -extern PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC gl3wInvalidateNamedFramebufferData; -extern PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC gl3wInvalidateNamedFramebufferSubData; -extern PFNGLINVALIDATESUBFRAMEBUFFERPROC gl3wInvalidateSubFramebuffer; -extern PFNGLINVALIDATETEXIMAGEPROC gl3wInvalidateTexImage; -extern PFNGLINVALIDATETEXSUBIMAGEPROC gl3wInvalidateTexSubImage; -extern PFNGLISBUFFERPROC gl3wIsBuffer; -extern PFNGLISBUFFERRESIDENTNVPROC gl3wIsBufferResidentNV; -extern PFNGLISCOMMANDLISTNVPROC gl3wIsCommandListNV; -extern PFNGLISENABLEDPROC gl3wIsEnabled; -extern PFNGLISENABLEDINDEXEDEXTPROC gl3wIsEnabledIndexedEXT; -extern PFNGLISENABLEDIPROC gl3wIsEnabledi; -extern PFNGLISFRAMEBUFFERPROC gl3wIsFramebuffer; -extern PFNGLISIMAGEHANDLERESIDENTARBPROC gl3wIsImageHandleResidentARB; -extern PFNGLISIMAGEHANDLERESIDENTNVPROC gl3wIsImageHandleResidentNV; -extern PFNGLISNAMEDBUFFERRESIDENTNVPROC gl3wIsNamedBufferResidentNV; -extern PFNGLISNAMEDSTRINGARBPROC gl3wIsNamedStringARB; -extern PFNGLISPATHNVPROC gl3wIsPathNV; -extern PFNGLISPOINTINFILLPATHNVPROC gl3wIsPointInFillPathNV; -extern PFNGLISPOINTINSTROKEPATHNVPROC gl3wIsPointInStrokePathNV; -extern PFNGLISPROGRAMPROC gl3wIsProgram; -extern PFNGLISPROGRAMPIPELINEPROC gl3wIsProgramPipeline; -extern PFNGLISQUERYPROC gl3wIsQuery; -extern PFNGLISRENDERBUFFERPROC gl3wIsRenderbuffer; -extern PFNGLISSAMPLERPROC gl3wIsSampler; -extern PFNGLISSHADERPROC gl3wIsShader; -extern PFNGLISSTATENVPROC gl3wIsStateNV; -extern PFNGLISSYNCPROC gl3wIsSync; -extern PFNGLISTEXTUREPROC gl3wIsTexture; -extern PFNGLISTEXTUREHANDLERESIDENTARBPROC gl3wIsTextureHandleResidentARB; -extern PFNGLISTEXTUREHANDLERESIDENTNVPROC gl3wIsTextureHandleResidentNV; -extern PFNGLISTRANSFORMFEEDBACKPROC gl3wIsTransformFeedback; -extern PFNGLISVERTEXARRAYPROC gl3wIsVertexArray; -extern PFNGLLABELOBJECTEXTPROC gl3wLabelObjectEXT; -extern PFNGLLINEWIDTHPROC gl3wLineWidth; -extern PFNGLLINKPROGRAMPROC gl3wLinkProgram; -extern PFNGLLISTDRAWCOMMANDSSTATESCLIENTNVPROC gl3wListDrawCommandsStatesClientNV; -extern PFNGLLOGICOPPROC gl3wLogicOp; -extern PFNGLMAKEBUFFERNONRESIDENTNVPROC gl3wMakeBufferNonResidentNV; -extern PFNGLMAKEBUFFERRESIDENTNVPROC gl3wMakeBufferResidentNV; -extern PFNGLMAKEIMAGEHANDLENONRESIDENTARBPROC gl3wMakeImageHandleNonResidentARB; -extern PFNGLMAKEIMAGEHANDLENONRESIDENTNVPROC gl3wMakeImageHandleNonResidentNV; -extern PFNGLMAKEIMAGEHANDLERESIDENTARBPROC gl3wMakeImageHandleResidentARB; -extern PFNGLMAKEIMAGEHANDLERESIDENTNVPROC gl3wMakeImageHandleResidentNV; -extern PFNGLMAKENAMEDBUFFERNONRESIDENTNVPROC gl3wMakeNamedBufferNonResidentNV; -extern PFNGLMAKENAMEDBUFFERRESIDENTNVPROC gl3wMakeNamedBufferResidentNV; -extern PFNGLMAKETEXTUREHANDLENONRESIDENTARBPROC gl3wMakeTextureHandleNonResidentARB; -extern PFNGLMAKETEXTUREHANDLENONRESIDENTNVPROC gl3wMakeTextureHandleNonResidentNV; -extern PFNGLMAKETEXTUREHANDLERESIDENTARBPROC gl3wMakeTextureHandleResidentARB; -extern PFNGLMAKETEXTUREHANDLERESIDENTNVPROC gl3wMakeTextureHandleResidentNV; -extern PFNGLMAPBUFFERPROC gl3wMapBuffer; -extern PFNGLMAPBUFFERRANGEPROC gl3wMapBufferRange; -extern PFNGLMAPNAMEDBUFFERPROC gl3wMapNamedBuffer; -extern PFNGLMAPNAMEDBUFFEREXTPROC gl3wMapNamedBufferEXT; -extern PFNGLMAPNAMEDBUFFERRANGEPROC gl3wMapNamedBufferRange; -extern PFNGLMAPNAMEDBUFFERRANGEEXTPROC gl3wMapNamedBufferRangeEXT; -extern PFNGLMATRIXFRUSTUMEXTPROC gl3wMatrixFrustumEXT; -extern PFNGLMATRIXLOAD3X2FNVPROC gl3wMatrixLoad3x2fNV; -extern PFNGLMATRIXLOAD3X3FNVPROC gl3wMatrixLoad3x3fNV; -extern PFNGLMATRIXLOADIDENTITYEXTPROC gl3wMatrixLoadIdentityEXT; -extern PFNGLMATRIXLOADTRANSPOSE3X3FNVPROC gl3wMatrixLoadTranspose3x3fNV; -extern PFNGLMATRIXLOADTRANSPOSEDEXTPROC gl3wMatrixLoadTransposedEXT; -extern PFNGLMATRIXLOADTRANSPOSEFEXTPROC gl3wMatrixLoadTransposefEXT; -extern PFNGLMATRIXLOADDEXTPROC gl3wMatrixLoaddEXT; -extern PFNGLMATRIXLOADFEXTPROC gl3wMatrixLoadfEXT; -extern PFNGLMATRIXMULT3X2FNVPROC gl3wMatrixMult3x2fNV; -extern PFNGLMATRIXMULT3X3FNVPROC gl3wMatrixMult3x3fNV; -extern PFNGLMATRIXMULTTRANSPOSE3X3FNVPROC gl3wMatrixMultTranspose3x3fNV; -extern PFNGLMATRIXMULTTRANSPOSEDEXTPROC gl3wMatrixMultTransposedEXT; -extern PFNGLMATRIXMULTTRANSPOSEFEXTPROC gl3wMatrixMultTransposefEXT; -extern PFNGLMATRIXMULTDEXTPROC gl3wMatrixMultdEXT; -extern PFNGLMATRIXMULTFEXTPROC gl3wMatrixMultfEXT; -extern PFNGLMATRIXORTHOEXTPROC gl3wMatrixOrthoEXT; -extern PFNGLMATRIXPOPEXTPROC gl3wMatrixPopEXT; -extern PFNGLMATRIXPUSHEXTPROC gl3wMatrixPushEXT; -extern PFNGLMATRIXROTATEDEXTPROC gl3wMatrixRotatedEXT; -extern PFNGLMATRIXROTATEFEXTPROC gl3wMatrixRotatefEXT; -extern PFNGLMATRIXSCALEDEXTPROC gl3wMatrixScaledEXT; -extern PFNGLMATRIXSCALEFEXTPROC gl3wMatrixScalefEXT; -extern PFNGLMATRIXTRANSLATEDEXTPROC gl3wMatrixTranslatedEXT; -extern PFNGLMATRIXTRANSLATEFEXTPROC gl3wMatrixTranslatefEXT; -extern PFNGLMAXSHADERCOMPILERTHREADSARBPROC gl3wMaxShaderCompilerThreadsARB; -extern PFNGLMEMORYBARRIERPROC gl3wMemoryBarrier; -extern PFNGLMEMORYBARRIERBYREGIONPROC gl3wMemoryBarrierByRegion; -extern PFNGLMINSAMPLESHADINGPROC gl3wMinSampleShading; -extern PFNGLMINSAMPLESHADINGARBPROC gl3wMinSampleShadingARB; -extern PFNGLMULTIDRAWARRAYSPROC gl3wMultiDrawArrays; -extern PFNGLMULTIDRAWARRAYSINDIRECTPROC gl3wMultiDrawArraysIndirect; -extern PFNGLMULTIDRAWARRAYSINDIRECTBINDLESSCOUNTNVPROC gl3wMultiDrawArraysIndirectBindlessCountNV; -extern PFNGLMULTIDRAWARRAYSINDIRECTBINDLESSNVPROC gl3wMultiDrawArraysIndirectBindlessNV; -extern PFNGLMULTIDRAWARRAYSINDIRECTCOUNTPROC gl3wMultiDrawArraysIndirectCount; -extern PFNGLMULTIDRAWARRAYSINDIRECTCOUNTARBPROC gl3wMultiDrawArraysIndirectCountARB; -extern PFNGLMULTIDRAWELEMENTSPROC gl3wMultiDrawElements; -extern PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC gl3wMultiDrawElementsBaseVertex; -extern PFNGLMULTIDRAWELEMENTSINDIRECTPROC gl3wMultiDrawElementsIndirect; -extern PFNGLMULTIDRAWELEMENTSINDIRECTBINDLESSCOUNTNVPROC gl3wMultiDrawElementsIndirectBindlessCountNV; -extern PFNGLMULTIDRAWELEMENTSINDIRECTBINDLESSNVPROC gl3wMultiDrawElementsIndirectBindlessNV; -extern PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTPROC gl3wMultiDrawElementsIndirectCount; -extern PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTARBPROC gl3wMultiDrawElementsIndirectCountARB; -extern PFNGLMULTITEXBUFFEREXTPROC gl3wMultiTexBufferEXT; -extern PFNGLMULTITEXCOORDPOINTEREXTPROC gl3wMultiTexCoordPointerEXT; -extern PFNGLMULTITEXENVFEXTPROC gl3wMultiTexEnvfEXT; -extern PFNGLMULTITEXENVFVEXTPROC gl3wMultiTexEnvfvEXT; -extern PFNGLMULTITEXENVIEXTPROC gl3wMultiTexEnviEXT; -extern PFNGLMULTITEXENVIVEXTPROC gl3wMultiTexEnvivEXT; -extern PFNGLMULTITEXGENDEXTPROC gl3wMultiTexGendEXT; -extern PFNGLMULTITEXGENDVEXTPROC gl3wMultiTexGendvEXT; -extern PFNGLMULTITEXGENFEXTPROC gl3wMultiTexGenfEXT; -extern PFNGLMULTITEXGENFVEXTPROC gl3wMultiTexGenfvEXT; -extern PFNGLMULTITEXGENIEXTPROC gl3wMultiTexGeniEXT; -extern PFNGLMULTITEXGENIVEXTPROC gl3wMultiTexGenivEXT; -extern PFNGLMULTITEXIMAGE1DEXTPROC gl3wMultiTexImage1DEXT; -extern PFNGLMULTITEXIMAGE2DEXTPROC gl3wMultiTexImage2DEXT; -extern PFNGLMULTITEXIMAGE3DEXTPROC gl3wMultiTexImage3DEXT; -extern PFNGLMULTITEXPARAMETERIIVEXTPROC gl3wMultiTexParameterIivEXT; -extern PFNGLMULTITEXPARAMETERIUIVEXTPROC gl3wMultiTexParameterIuivEXT; -extern PFNGLMULTITEXPARAMETERFEXTPROC gl3wMultiTexParameterfEXT; -extern PFNGLMULTITEXPARAMETERFVEXTPROC gl3wMultiTexParameterfvEXT; -extern PFNGLMULTITEXPARAMETERIEXTPROC gl3wMultiTexParameteriEXT; -extern PFNGLMULTITEXPARAMETERIVEXTPROC gl3wMultiTexParameterivEXT; -extern PFNGLMULTITEXRENDERBUFFEREXTPROC gl3wMultiTexRenderbufferEXT; -extern PFNGLMULTITEXSUBIMAGE1DEXTPROC gl3wMultiTexSubImage1DEXT; -extern PFNGLMULTITEXSUBIMAGE2DEXTPROC gl3wMultiTexSubImage2DEXT; -extern PFNGLMULTITEXSUBIMAGE3DEXTPROC gl3wMultiTexSubImage3DEXT; -extern PFNGLNAMEDBUFFERDATAPROC gl3wNamedBufferData; -extern PFNGLNAMEDBUFFERDATAEXTPROC gl3wNamedBufferDataEXT; -extern PFNGLNAMEDBUFFERPAGECOMMITMENTARBPROC gl3wNamedBufferPageCommitmentARB; -extern PFNGLNAMEDBUFFERPAGECOMMITMENTEXTPROC gl3wNamedBufferPageCommitmentEXT; -extern PFNGLNAMEDBUFFERSTORAGEPROC gl3wNamedBufferStorage; -extern PFNGLNAMEDBUFFERSTORAGEEXTPROC gl3wNamedBufferStorageEXT; -extern PFNGLNAMEDBUFFERSUBDATAPROC gl3wNamedBufferSubData; -extern PFNGLNAMEDBUFFERSUBDATAEXTPROC gl3wNamedBufferSubDataEXT; -extern PFNGLNAMEDCOPYBUFFERSUBDATAEXTPROC gl3wNamedCopyBufferSubDataEXT; -extern PFNGLNAMEDFRAMEBUFFERDRAWBUFFERPROC gl3wNamedFramebufferDrawBuffer; -extern PFNGLNAMEDFRAMEBUFFERDRAWBUFFERSPROC gl3wNamedFramebufferDrawBuffers; -extern PFNGLNAMEDFRAMEBUFFERPARAMETERIPROC gl3wNamedFramebufferParameteri; -extern PFNGLNAMEDFRAMEBUFFERPARAMETERIEXTPROC gl3wNamedFramebufferParameteriEXT; -extern PFNGLNAMEDFRAMEBUFFERREADBUFFERPROC gl3wNamedFramebufferReadBuffer; -extern PFNGLNAMEDFRAMEBUFFERRENDERBUFFERPROC gl3wNamedFramebufferRenderbuffer; -extern PFNGLNAMEDFRAMEBUFFERRENDERBUFFEREXTPROC gl3wNamedFramebufferRenderbufferEXT; -extern PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVARBPROC gl3wNamedFramebufferSampleLocationsfvARB; -extern PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVNVPROC gl3wNamedFramebufferSampleLocationsfvNV; -extern PFNGLNAMEDFRAMEBUFFERTEXTUREPROC gl3wNamedFramebufferTexture; -extern PFNGLNAMEDFRAMEBUFFERTEXTURE1DEXTPROC gl3wNamedFramebufferTexture1DEXT; -extern PFNGLNAMEDFRAMEBUFFERTEXTURE2DEXTPROC gl3wNamedFramebufferTexture2DEXT; -extern PFNGLNAMEDFRAMEBUFFERTEXTURE3DEXTPROC gl3wNamedFramebufferTexture3DEXT; -extern PFNGLNAMEDFRAMEBUFFERTEXTUREEXTPROC gl3wNamedFramebufferTextureEXT; -extern PFNGLNAMEDFRAMEBUFFERTEXTUREFACEEXTPROC gl3wNamedFramebufferTextureFaceEXT; -extern PFNGLNAMEDFRAMEBUFFERTEXTURELAYERPROC gl3wNamedFramebufferTextureLayer; -extern PFNGLNAMEDFRAMEBUFFERTEXTURELAYEREXTPROC gl3wNamedFramebufferTextureLayerEXT; -extern PFNGLNAMEDPROGRAMLOCALPARAMETER4DEXTPROC gl3wNamedProgramLocalParameter4dEXT; -extern PFNGLNAMEDPROGRAMLOCALPARAMETER4DVEXTPROC gl3wNamedProgramLocalParameter4dvEXT; -extern PFNGLNAMEDPROGRAMLOCALPARAMETER4FEXTPROC gl3wNamedProgramLocalParameter4fEXT; -extern PFNGLNAMEDPROGRAMLOCALPARAMETER4FVEXTPROC gl3wNamedProgramLocalParameter4fvEXT; -extern PFNGLNAMEDPROGRAMLOCALPARAMETERI4IEXTPROC gl3wNamedProgramLocalParameterI4iEXT; -extern PFNGLNAMEDPROGRAMLOCALPARAMETERI4IVEXTPROC gl3wNamedProgramLocalParameterI4ivEXT; -extern PFNGLNAMEDPROGRAMLOCALPARAMETERI4UIEXTPROC gl3wNamedProgramLocalParameterI4uiEXT; -extern PFNGLNAMEDPROGRAMLOCALPARAMETERI4UIVEXTPROC gl3wNamedProgramLocalParameterI4uivEXT; -extern PFNGLNAMEDPROGRAMLOCALPARAMETERS4FVEXTPROC gl3wNamedProgramLocalParameters4fvEXT; -extern PFNGLNAMEDPROGRAMLOCALPARAMETERSI4IVEXTPROC gl3wNamedProgramLocalParametersI4ivEXT; -extern PFNGLNAMEDPROGRAMLOCALPARAMETERSI4UIVEXTPROC gl3wNamedProgramLocalParametersI4uivEXT; -extern PFNGLNAMEDPROGRAMSTRINGEXTPROC gl3wNamedProgramStringEXT; -extern PFNGLNAMEDRENDERBUFFERSTORAGEPROC gl3wNamedRenderbufferStorage; -extern PFNGLNAMEDRENDERBUFFERSTORAGEEXTPROC gl3wNamedRenderbufferStorageEXT; -extern PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC gl3wNamedRenderbufferStorageMultisample; -extern PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLECOVERAGEEXTPROC gl3wNamedRenderbufferStorageMultisampleCoverageEXT; -extern PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC gl3wNamedRenderbufferStorageMultisampleEXT; -extern PFNGLNAMEDSTRINGARBPROC gl3wNamedStringARB; -extern PFNGLNORMALFORMATNVPROC gl3wNormalFormatNV; -extern PFNGLOBJECTLABELPROC gl3wObjectLabel; -extern PFNGLOBJECTPTRLABELPROC gl3wObjectPtrLabel; -extern PFNGLPATCHPARAMETERFVPROC gl3wPatchParameterfv; -extern PFNGLPATCHPARAMETERIPROC gl3wPatchParameteri; -extern PFNGLPATHCOMMANDSNVPROC gl3wPathCommandsNV; -extern PFNGLPATHCOORDSNVPROC gl3wPathCoordsNV; -extern PFNGLPATHCOVERDEPTHFUNCNVPROC gl3wPathCoverDepthFuncNV; -extern PFNGLPATHDASHARRAYNVPROC gl3wPathDashArrayNV; -extern PFNGLPATHGLYPHINDEXARRAYNVPROC gl3wPathGlyphIndexArrayNV; -extern PFNGLPATHGLYPHINDEXRANGENVPROC gl3wPathGlyphIndexRangeNV; -extern PFNGLPATHGLYPHRANGENVPROC gl3wPathGlyphRangeNV; -extern PFNGLPATHGLYPHSNVPROC gl3wPathGlyphsNV; -extern PFNGLPATHMEMORYGLYPHINDEXARRAYNVPROC gl3wPathMemoryGlyphIndexArrayNV; -extern PFNGLPATHPARAMETERFNVPROC gl3wPathParameterfNV; -extern PFNGLPATHPARAMETERFVNVPROC gl3wPathParameterfvNV; -extern PFNGLPATHPARAMETERINVPROC gl3wPathParameteriNV; -extern PFNGLPATHPARAMETERIVNVPROC gl3wPathParameterivNV; -extern PFNGLPATHSTENCILDEPTHOFFSETNVPROC gl3wPathStencilDepthOffsetNV; -extern PFNGLPATHSTENCILFUNCNVPROC gl3wPathStencilFuncNV; -extern PFNGLPATHSTRINGNVPROC gl3wPathStringNV; -extern PFNGLPATHSUBCOMMANDSNVPROC gl3wPathSubCommandsNV; -extern PFNGLPATHSUBCOORDSNVPROC gl3wPathSubCoordsNV; -extern PFNGLPAUSETRANSFORMFEEDBACKPROC gl3wPauseTransformFeedback; -extern PFNGLPIXELSTOREFPROC gl3wPixelStoref; -extern PFNGLPIXELSTOREIPROC gl3wPixelStorei; -extern PFNGLPOINTALONGPATHNVPROC gl3wPointAlongPathNV; -extern PFNGLPOINTPARAMETERFPROC gl3wPointParameterf; -extern PFNGLPOINTPARAMETERFVPROC gl3wPointParameterfv; -extern PFNGLPOINTPARAMETERIPROC gl3wPointParameteri; -extern PFNGLPOINTPARAMETERIVPROC gl3wPointParameteriv; -extern PFNGLPOINTSIZEPROC gl3wPointSize; -extern PFNGLPOLYGONMODEPROC gl3wPolygonMode; -extern PFNGLPOLYGONOFFSETPROC gl3wPolygonOffset; -extern PFNGLPOLYGONOFFSETCLAMPPROC gl3wPolygonOffsetClamp; -extern PFNGLPOLYGONOFFSETCLAMPEXTPROC gl3wPolygonOffsetClampEXT; -extern PFNGLPOPDEBUGGROUPPROC gl3wPopDebugGroup; -extern PFNGLPOPGROUPMARKEREXTPROC gl3wPopGroupMarkerEXT; -extern PFNGLPRIMITIVEBOUNDINGBOXARBPROC gl3wPrimitiveBoundingBoxARB; -extern PFNGLPRIMITIVERESTARTINDEXPROC gl3wPrimitiveRestartIndex; -extern PFNGLPROGRAMBINARYPROC gl3wProgramBinary; -extern PFNGLPROGRAMPARAMETERIPROC gl3wProgramParameteri; -extern PFNGLPROGRAMPARAMETERIARBPROC gl3wProgramParameteriARB; -extern PFNGLPROGRAMPATHFRAGMENTINPUTGENNVPROC gl3wProgramPathFragmentInputGenNV; -extern PFNGLPROGRAMUNIFORM1DPROC gl3wProgramUniform1d; -extern PFNGLPROGRAMUNIFORM1DEXTPROC gl3wProgramUniform1dEXT; -extern PFNGLPROGRAMUNIFORM1DVPROC gl3wProgramUniform1dv; -extern PFNGLPROGRAMUNIFORM1DVEXTPROC gl3wProgramUniform1dvEXT; -extern PFNGLPROGRAMUNIFORM1FPROC gl3wProgramUniform1f; -extern PFNGLPROGRAMUNIFORM1FEXTPROC gl3wProgramUniform1fEXT; -extern PFNGLPROGRAMUNIFORM1FVPROC gl3wProgramUniform1fv; -extern PFNGLPROGRAMUNIFORM1FVEXTPROC gl3wProgramUniform1fvEXT; -extern PFNGLPROGRAMUNIFORM1IPROC gl3wProgramUniform1i; -extern PFNGLPROGRAMUNIFORM1I64ARBPROC gl3wProgramUniform1i64ARB; -extern PFNGLPROGRAMUNIFORM1I64NVPROC gl3wProgramUniform1i64NV; -extern PFNGLPROGRAMUNIFORM1I64VARBPROC gl3wProgramUniform1i64vARB; -extern PFNGLPROGRAMUNIFORM1I64VNVPROC gl3wProgramUniform1i64vNV; -extern PFNGLPROGRAMUNIFORM1IEXTPROC gl3wProgramUniform1iEXT; -extern PFNGLPROGRAMUNIFORM1IVPROC gl3wProgramUniform1iv; -extern PFNGLPROGRAMUNIFORM1IVEXTPROC gl3wProgramUniform1ivEXT; -extern PFNGLPROGRAMUNIFORM1UIPROC gl3wProgramUniform1ui; -extern PFNGLPROGRAMUNIFORM1UI64ARBPROC gl3wProgramUniform1ui64ARB; -extern PFNGLPROGRAMUNIFORM1UI64NVPROC gl3wProgramUniform1ui64NV; -extern PFNGLPROGRAMUNIFORM1UI64VARBPROC gl3wProgramUniform1ui64vARB; -extern PFNGLPROGRAMUNIFORM1UI64VNVPROC gl3wProgramUniform1ui64vNV; -extern PFNGLPROGRAMUNIFORM1UIEXTPROC gl3wProgramUniform1uiEXT; -extern PFNGLPROGRAMUNIFORM1UIVPROC gl3wProgramUniform1uiv; -extern PFNGLPROGRAMUNIFORM1UIVEXTPROC gl3wProgramUniform1uivEXT; -extern PFNGLPROGRAMUNIFORM2DPROC gl3wProgramUniform2d; -extern PFNGLPROGRAMUNIFORM2DEXTPROC gl3wProgramUniform2dEXT; -extern PFNGLPROGRAMUNIFORM2DVPROC gl3wProgramUniform2dv; -extern PFNGLPROGRAMUNIFORM2DVEXTPROC gl3wProgramUniform2dvEXT; -extern PFNGLPROGRAMUNIFORM2FPROC gl3wProgramUniform2f; -extern PFNGLPROGRAMUNIFORM2FEXTPROC gl3wProgramUniform2fEXT; -extern PFNGLPROGRAMUNIFORM2FVPROC gl3wProgramUniform2fv; -extern PFNGLPROGRAMUNIFORM2FVEXTPROC gl3wProgramUniform2fvEXT; -extern PFNGLPROGRAMUNIFORM2IPROC gl3wProgramUniform2i; -extern PFNGLPROGRAMUNIFORM2I64ARBPROC gl3wProgramUniform2i64ARB; -extern PFNGLPROGRAMUNIFORM2I64NVPROC gl3wProgramUniform2i64NV; -extern PFNGLPROGRAMUNIFORM2I64VARBPROC gl3wProgramUniform2i64vARB; -extern PFNGLPROGRAMUNIFORM2I64VNVPROC gl3wProgramUniform2i64vNV; -extern PFNGLPROGRAMUNIFORM2IEXTPROC gl3wProgramUniform2iEXT; -extern PFNGLPROGRAMUNIFORM2IVPROC gl3wProgramUniform2iv; -extern PFNGLPROGRAMUNIFORM2IVEXTPROC gl3wProgramUniform2ivEXT; -extern PFNGLPROGRAMUNIFORM2UIPROC gl3wProgramUniform2ui; -extern PFNGLPROGRAMUNIFORM2UI64ARBPROC gl3wProgramUniform2ui64ARB; -extern PFNGLPROGRAMUNIFORM2UI64NVPROC gl3wProgramUniform2ui64NV; -extern PFNGLPROGRAMUNIFORM2UI64VARBPROC gl3wProgramUniform2ui64vARB; -extern PFNGLPROGRAMUNIFORM2UI64VNVPROC gl3wProgramUniform2ui64vNV; -extern PFNGLPROGRAMUNIFORM2UIEXTPROC gl3wProgramUniform2uiEXT; -extern PFNGLPROGRAMUNIFORM2UIVPROC gl3wProgramUniform2uiv; -extern PFNGLPROGRAMUNIFORM2UIVEXTPROC gl3wProgramUniform2uivEXT; -extern PFNGLPROGRAMUNIFORM3DPROC gl3wProgramUniform3d; -extern PFNGLPROGRAMUNIFORM3DEXTPROC gl3wProgramUniform3dEXT; -extern PFNGLPROGRAMUNIFORM3DVPROC gl3wProgramUniform3dv; -extern PFNGLPROGRAMUNIFORM3DVEXTPROC gl3wProgramUniform3dvEXT; -extern PFNGLPROGRAMUNIFORM3FPROC gl3wProgramUniform3f; -extern PFNGLPROGRAMUNIFORM3FEXTPROC gl3wProgramUniform3fEXT; -extern PFNGLPROGRAMUNIFORM3FVPROC gl3wProgramUniform3fv; -extern PFNGLPROGRAMUNIFORM3FVEXTPROC gl3wProgramUniform3fvEXT; -extern PFNGLPROGRAMUNIFORM3IPROC gl3wProgramUniform3i; -extern PFNGLPROGRAMUNIFORM3I64ARBPROC gl3wProgramUniform3i64ARB; -extern PFNGLPROGRAMUNIFORM3I64NVPROC gl3wProgramUniform3i64NV; -extern PFNGLPROGRAMUNIFORM3I64VARBPROC gl3wProgramUniform3i64vARB; -extern PFNGLPROGRAMUNIFORM3I64VNVPROC gl3wProgramUniform3i64vNV; -extern PFNGLPROGRAMUNIFORM3IEXTPROC gl3wProgramUniform3iEXT; -extern PFNGLPROGRAMUNIFORM3IVPROC gl3wProgramUniform3iv; -extern PFNGLPROGRAMUNIFORM3IVEXTPROC gl3wProgramUniform3ivEXT; -extern PFNGLPROGRAMUNIFORM3UIPROC gl3wProgramUniform3ui; -extern PFNGLPROGRAMUNIFORM3UI64ARBPROC gl3wProgramUniform3ui64ARB; -extern PFNGLPROGRAMUNIFORM3UI64NVPROC gl3wProgramUniform3ui64NV; -extern PFNGLPROGRAMUNIFORM3UI64VARBPROC gl3wProgramUniform3ui64vARB; -extern PFNGLPROGRAMUNIFORM3UI64VNVPROC gl3wProgramUniform3ui64vNV; -extern PFNGLPROGRAMUNIFORM3UIEXTPROC gl3wProgramUniform3uiEXT; -extern PFNGLPROGRAMUNIFORM3UIVPROC gl3wProgramUniform3uiv; -extern PFNGLPROGRAMUNIFORM3UIVEXTPROC gl3wProgramUniform3uivEXT; -extern PFNGLPROGRAMUNIFORM4DPROC gl3wProgramUniform4d; -extern PFNGLPROGRAMUNIFORM4DEXTPROC gl3wProgramUniform4dEXT; -extern PFNGLPROGRAMUNIFORM4DVPROC gl3wProgramUniform4dv; -extern PFNGLPROGRAMUNIFORM4DVEXTPROC gl3wProgramUniform4dvEXT; -extern PFNGLPROGRAMUNIFORM4FPROC gl3wProgramUniform4f; -extern PFNGLPROGRAMUNIFORM4FEXTPROC gl3wProgramUniform4fEXT; -extern PFNGLPROGRAMUNIFORM4FVPROC gl3wProgramUniform4fv; -extern PFNGLPROGRAMUNIFORM4FVEXTPROC gl3wProgramUniform4fvEXT; -extern PFNGLPROGRAMUNIFORM4IPROC gl3wProgramUniform4i; -extern PFNGLPROGRAMUNIFORM4I64ARBPROC gl3wProgramUniform4i64ARB; -extern PFNGLPROGRAMUNIFORM4I64NVPROC gl3wProgramUniform4i64NV; -extern PFNGLPROGRAMUNIFORM4I64VARBPROC gl3wProgramUniform4i64vARB; -extern PFNGLPROGRAMUNIFORM4I64VNVPROC gl3wProgramUniform4i64vNV; -extern PFNGLPROGRAMUNIFORM4IEXTPROC gl3wProgramUniform4iEXT; -extern PFNGLPROGRAMUNIFORM4IVPROC gl3wProgramUniform4iv; -extern PFNGLPROGRAMUNIFORM4IVEXTPROC gl3wProgramUniform4ivEXT; -extern PFNGLPROGRAMUNIFORM4UIPROC gl3wProgramUniform4ui; -extern PFNGLPROGRAMUNIFORM4UI64ARBPROC gl3wProgramUniform4ui64ARB; -extern PFNGLPROGRAMUNIFORM4UI64NVPROC gl3wProgramUniform4ui64NV; -extern PFNGLPROGRAMUNIFORM4UI64VARBPROC gl3wProgramUniform4ui64vARB; -extern PFNGLPROGRAMUNIFORM4UI64VNVPROC gl3wProgramUniform4ui64vNV; -extern PFNGLPROGRAMUNIFORM4UIEXTPROC gl3wProgramUniform4uiEXT; -extern PFNGLPROGRAMUNIFORM4UIVPROC gl3wProgramUniform4uiv; -extern PFNGLPROGRAMUNIFORM4UIVEXTPROC gl3wProgramUniform4uivEXT; -extern PFNGLPROGRAMUNIFORMHANDLEUI64ARBPROC gl3wProgramUniformHandleui64ARB; -extern PFNGLPROGRAMUNIFORMHANDLEUI64NVPROC gl3wProgramUniformHandleui64NV; -extern PFNGLPROGRAMUNIFORMHANDLEUI64VARBPROC gl3wProgramUniformHandleui64vARB; -extern PFNGLPROGRAMUNIFORMHANDLEUI64VNVPROC gl3wProgramUniformHandleui64vNV; -extern PFNGLPROGRAMUNIFORMMATRIX2DVPROC gl3wProgramUniformMatrix2dv; -extern PFNGLPROGRAMUNIFORMMATRIX2DVEXTPROC gl3wProgramUniformMatrix2dvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX2FVPROC gl3wProgramUniformMatrix2fv; -extern PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC gl3wProgramUniformMatrix2fvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC gl3wProgramUniformMatrix2x3dv; -extern PFNGLPROGRAMUNIFORMMATRIX2X3DVEXTPROC gl3wProgramUniformMatrix2x3dvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC gl3wProgramUniformMatrix2x3fv; -extern PFNGLPROGRAMUNIFORMMATRIX2X3FVEXTPROC gl3wProgramUniformMatrix2x3fvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC gl3wProgramUniformMatrix2x4dv; -extern PFNGLPROGRAMUNIFORMMATRIX2X4DVEXTPROC gl3wProgramUniformMatrix2x4dvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC gl3wProgramUniformMatrix2x4fv; -extern PFNGLPROGRAMUNIFORMMATRIX2X4FVEXTPROC gl3wProgramUniformMatrix2x4fvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX3DVPROC gl3wProgramUniformMatrix3dv; -extern PFNGLPROGRAMUNIFORMMATRIX3DVEXTPROC gl3wProgramUniformMatrix3dvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX3FVPROC gl3wProgramUniformMatrix3fv; -extern PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC gl3wProgramUniformMatrix3fvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC gl3wProgramUniformMatrix3x2dv; -extern PFNGLPROGRAMUNIFORMMATRIX3X2DVEXTPROC gl3wProgramUniformMatrix3x2dvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC gl3wProgramUniformMatrix3x2fv; -extern PFNGLPROGRAMUNIFORMMATRIX3X2FVEXTPROC gl3wProgramUniformMatrix3x2fvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC gl3wProgramUniformMatrix3x4dv; -extern PFNGLPROGRAMUNIFORMMATRIX3X4DVEXTPROC gl3wProgramUniformMatrix3x4dvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC gl3wProgramUniformMatrix3x4fv; -extern PFNGLPROGRAMUNIFORMMATRIX3X4FVEXTPROC gl3wProgramUniformMatrix3x4fvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX4DVPROC gl3wProgramUniformMatrix4dv; -extern PFNGLPROGRAMUNIFORMMATRIX4DVEXTPROC gl3wProgramUniformMatrix4dvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX4FVPROC gl3wProgramUniformMatrix4fv; -extern PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC gl3wProgramUniformMatrix4fvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC gl3wProgramUniformMatrix4x2dv; -extern PFNGLPROGRAMUNIFORMMATRIX4X2DVEXTPROC gl3wProgramUniformMatrix4x2dvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC gl3wProgramUniformMatrix4x2fv; -extern PFNGLPROGRAMUNIFORMMATRIX4X2FVEXTPROC gl3wProgramUniformMatrix4x2fvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC gl3wProgramUniformMatrix4x3dv; -extern PFNGLPROGRAMUNIFORMMATRIX4X3DVEXTPROC gl3wProgramUniformMatrix4x3dvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC gl3wProgramUniformMatrix4x3fv; -extern PFNGLPROGRAMUNIFORMMATRIX4X3FVEXTPROC gl3wProgramUniformMatrix4x3fvEXT; -extern PFNGLPROGRAMUNIFORMUI64NVPROC gl3wProgramUniformui64NV; -extern PFNGLPROGRAMUNIFORMUI64VNVPROC gl3wProgramUniformui64vNV; -extern PFNGLPROVOKINGVERTEXPROC gl3wProvokingVertex; -extern PFNGLPUSHCLIENTATTRIBDEFAULTEXTPROC gl3wPushClientAttribDefaultEXT; -extern PFNGLPUSHDEBUGGROUPPROC gl3wPushDebugGroup; -extern PFNGLPUSHGROUPMARKEREXTPROC gl3wPushGroupMarkerEXT; -extern PFNGLQUERYCOUNTERPROC gl3wQueryCounter; -extern PFNGLRASTERSAMPLESEXTPROC gl3wRasterSamplesEXT; -extern PFNGLREADBUFFERPROC gl3wReadBuffer; -extern PFNGLREADPIXELSPROC gl3wReadPixels; -extern PFNGLREADNPIXELSPROC gl3wReadnPixels; -extern PFNGLREADNPIXELSARBPROC gl3wReadnPixelsARB; -extern PFNGLRELEASESHADERCOMPILERPROC gl3wReleaseShaderCompiler; -extern PFNGLRENDERBUFFERSTORAGEPROC gl3wRenderbufferStorage; -extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC gl3wRenderbufferStorageMultisample; -extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLECOVERAGENVPROC gl3wRenderbufferStorageMultisampleCoverageNV; -extern PFNGLRESOLVEDEPTHVALUESNVPROC gl3wResolveDepthValuesNV; -extern PFNGLRESUMETRANSFORMFEEDBACKPROC gl3wResumeTransformFeedback; -extern PFNGLSAMPLECOVERAGEPROC gl3wSampleCoverage; -extern PFNGLSAMPLEMASKIPROC gl3wSampleMaski; -extern PFNGLSAMPLERPARAMETERIIVPROC gl3wSamplerParameterIiv; -extern PFNGLSAMPLERPARAMETERIUIVPROC gl3wSamplerParameterIuiv; -extern PFNGLSAMPLERPARAMETERFPROC gl3wSamplerParameterf; -extern PFNGLSAMPLERPARAMETERFVPROC gl3wSamplerParameterfv; -extern PFNGLSAMPLERPARAMETERIPROC gl3wSamplerParameteri; -extern PFNGLSAMPLERPARAMETERIVPROC gl3wSamplerParameteriv; -extern PFNGLSCISSORPROC gl3wScissor; -extern PFNGLSCISSORARRAYVPROC gl3wScissorArrayv; -extern PFNGLSCISSORINDEXEDPROC gl3wScissorIndexed; -extern PFNGLSCISSORINDEXEDVPROC gl3wScissorIndexedv; -extern PFNGLSECONDARYCOLORFORMATNVPROC gl3wSecondaryColorFormatNV; -extern PFNGLSELECTPERFMONITORCOUNTERSAMDPROC gl3wSelectPerfMonitorCountersAMD; -extern PFNGLSHADERBINARYPROC gl3wShaderBinary; -extern PFNGLSHADERSOURCEPROC gl3wShaderSource; -extern PFNGLSHADERSTORAGEBLOCKBINDINGPROC gl3wShaderStorageBlockBinding; -extern PFNGLSIGNALVKFENCENVPROC gl3wSignalVkFenceNV; -extern PFNGLSIGNALVKSEMAPHORENVPROC gl3wSignalVkSemaphoreNV; -extern PFNGLSPECIALIZESHADERPROC gl3wSpecializeShader; -extern PFNGLSPECIALIZESHADERARBPROC gl3wSpecializeShaderARB; -extern PFNGLSTATECAPTURENVPROC gl3wStateCaptureNV; -extern PFNGLSTENCILFILLPATHINSTANCEDNVPROC gl3wStencilFillPathInstancedNV; -extern PFNGLSTENCILFILLPATHNVPROC gl3wStencilFillPathNV; -extern PFNGLSTENCILFUNCPROC gl3wStencilFunc; -extern PFNGLSTENCILFUNCSEPARATEPROC gl3wStencilFuncSeparate; -extern PFNGLSTENCILMASKPROC gl3wStencilMask; -extern PFNGLSTENCILMASKSEPARATEPROC gl3wStencilMaskSeparate; -extern PFNGLSTENCILOPPROC gl3wStencilOp; -extern PFNGLSTENCILOPSEPARATEPROC gl3wStencilOpSeparate; -extern PFNGLSTENCILSTROKEPATHINSTANCEDNVPROC gl3wStencilStrokePathInstancedNV; -extern PFNGLSTENCILSTROKEPATHNVPROC gl3wStencilStrokePathNV; -extern PFNGLSTENCILTHENCOVERFILLPATHINSTANCEDNVPROC gl3wStencilThenCoverFillPathInstancedNV; -extern PFNGLSTENCILTHENCOVERFILLPATHNVPROC gl3wStencilThenCoverFillPathNV; -extern PFNGLSTENCILTHENCOVERSTROKEPATHINSTANCEDNVPROC gl3wStencilThenCoverStrokePathInstancedNV; -extern PFNGLSTENCILTHENCOVERSTROKEPATHNVPROC gl3wStencilThenCoverStrokePathNV; -extern PFNGLSUBPIXELPRECISIONBIASNVPROC gl3wSubpixelPrecisionBiasNV; -extern PFNGLTEXBUFFERPROC gl3wTexBuffer; -extern PFNGLTEXBUFFERARBPROC gl3wTexBufferARB; -extern PFNGLTEXBUFFERRANGEPROC gl3wTexBufferRange; -extern PFNGLTEXCOORDFORMATNVPROC gl3wTexCoordFormatNV; -extern PFNGLTEXIMAGE1DPROC gl3wTexImage1D; -extern PFNGLTEXIMAGE2DPROC gl3wTexImage2D; -extern PFNGLTEXIMAGE2DMULTISAMPLEPROC gl3wTexImage2DMultisample; -extern PFNGLTEXIMAGE3DPROC gl3wTexImage3D; -extern PFNGLTEXIMAGE3DMULTISAMPLEPROC gl3wTexImage3DMultisample; -extern PFNGLTEXPAGECOMMITMENTARBPROC gl3wTexPageCommitmentARB; -extern PFNGLTEXPARAMETERIIVPROC gl3wTexParameterIiv; -extern PFNGLTEXPARAMETERIUIVPROC gl3wTexParameterIuiv; -extern PFNGLTEXPARAMETERFPROC gl3wTexParameterf; -extern PFNGLTEXPARAMETERFVPROC gl3wTexParameterfv; -extern PFNGLTEXPARAMETERIPROC gl3wTexParameteri; -extern PFNGLTEXPARAMETERIVPROC gl3wTexParameteriv; -extern PFNGLTEXSTORAGE1DPROC gl3wTexStorage1D; -extern PFNGLTEXSTORAGE2DPROC gl3wTexStorage2D; -extern PFNGLTEXSTORAGE2DMULTISAMPLEPROC gl3wTexStorage2DMultisample; -extern PFNGLTEXSTORAGE3DPROC gl3wTexStorage3D; -extern PFNGLTEXSTORAGE3DMULTISAMPLEPROC gl3wTexStorage3DMultisample; -extern PFNGLTEXSUBIMAGE1DPROC gl3wTexSubImage1D; -extern PFNGLTEXSUBIMAGE2DPROC gl3wTexSubImage2D; -extern PFNGLTEXSUBIMAGE3DPROC gl3wTexSubImage3D; -extern PFNGLTEXTUREBARRIERPROC gl3wTextureBarrier; -extern PFNGLTEXTUREBARRIERNVPROC gl3wTextureBarrierNV; -extern PFNGLTEXTUREBUFFERPROC gl3wTextureBuffer; -extern PFNGLTEXTUREBUFFEREXTPROC gl3wTextureBufferEXT; -extern PFNGLTEXTUREBUFFERRANGEPROC gl3wTextureBufferRange; -extern PFNGLTEXTUREBUFFERRANGEEXTPROC gl3wTextureBufferRangeEXT; -extern PFNGLTEXTUREIMAGE1DEXTPROC gl3wTextureImage1DEXT; -extern PFNGLTEXTUREIMAGE2DEXTPROC gl3wTextureImage2DEXT; -extern PFNGLTEXTUREIMAGE3DEXTPROC gl3wTextureImage3DEXT; -extern PFNGLTEXTUREPAGECOMMITMENTEXTPROC gl3wTexturePageCommitmentEXT; -extern PFNGLTEXTUREPARAMETERIIVPROC gl3wTextureParameterIiv; -extern PFNGLTEXTUREPARAMETERIIVEXTPROC gl3wTextureParameterIivEXT; -extern PFNGLTEXTUREPARAMETERIUIVPROC gl3wTextureParameterIuiv; -extern PFNGLTEXTUREPARAMETERIUIVEXTPROC gl3wTextureParameterIuivEXT; -extern PFNGLTEXTUREPARAMETERFPROC gl3wTextureParameterf; -extern PFNGLTEXTUREPARAMETERFEXTPROC gl3wTextureParameterfEXT; -extern PFNGLTEXTUREPARAMETERFVPROC gl3wTextureParameterfv; -extern PFNGLTEXTUREPARAMETERFVEXTPROC gl3wTextureParameterfvEXT; -extern PFNGLTEXTUREPARAMETERIPROC gl3wTextureParameteri; -extern PFNGLTEXTUREPARAMETERIEXTPROC gl3wTextureParameteriEXT; -extern PFNGLTEXTUREPARAMETERIVPROC gl3wTextureParameteriv; -extern PFNGLTEXTUREPARAMETERIVEXTPROC gl3wTextureParameterivEXT; -extern PFNGLTEXTURERENDERBUFFEREXTPROC gl3wTextureRenderbufferEXT; -extern PFNGLTEXTURESTORAGE1DPROC gl3wTextureStorage1D; -extern PFNGLTEXTURESTORAGE1DEXTPROC gl3wTextureStorage1DEXT; -extern PFNGLTEXTURESTORAGE2DPROC gl3wTextureStorage2D; -extern PFNGLTEXTURESTORAGE2DEXTPROC gl3wTextureStorage2DEXT; -extern PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC gl3wTextureStorage2DMultisample; -extern PFNGLTEXTURESTORAGE2DMULTISAMPLEEXTPROC gl3wTextureStorage2DMultisampleEXT; -extern PFNGLTEXTURESTORAGE3DPROC gl3wTextureStorage3D; -extern PFNGLTEXTURESTORAGE3DEXTPROC gl3wTextureStorage3DEXT; -extern PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC gl3wTextureStorage3DMultisample; -extern PFNGLTEXTURESTORAGE3DMULTISAMPLEEXTPROC gl3wTextureStorage3DMultisampleEXT; -extern PFNGLTEXTURESUBIMAGE1DPROC gl3wTextureSubImage1D; -extern PFNGLTEXTURESUBIMAGE1DEXTPROC gl3wTextureSubImage1DEXT; -extern PFNGLTEXTURESUBIMAGE2DPROC gl3wTextureSubImage2D; -extern PFNGLTEXTURESUBIMAGE2DEXTPROC gl3wTextureSubImage2DEXT; -extern PFNGLTEXTURESUBIMAGE3DPROC gl3wTextureSubImage3D; -extern PFNGLTEXTURESUBIMAGE3DEXTPROC gl3wTextureSubImage3DEXT; -extern PFNGLTEXTUREVIEWPROC gl3wTextureView; -extern PFNGLTRANSFORMFEEDBACKBUFFERBASEPROC gl3wTransformFeedbackBufferBase; -extern PFNGLTRANSFORMFEEDBACKBUFFERRANGEPROC gl3wTransformFeedbackBufferRange; -extern PFNGLTRANSFORMFEEDBACKVARYINGSPROC gl3wTransformFeedbackVaryings; -extern PFNGLTRANSFORMPATHNVPROC gl3wTransformPathNV; -extern PFNGLUNIFORM1DPROC gl3wUniform1d; -extern PFNGLUNIFORM1DVPROC gl3wUniform1dv; -extern PFNGLUNIFORM1FPROC gl3wUniform1f; -extern PFNGLUNIFORM1FVPROC gl3wUniform1fv; -extern PFNGLUNIFORM1IPROC gl3wUniform1i; -extern PFNGLUNIFORM1I64ARBPROC gl3wUniform1i64ARB; -extern PFNGLUNIFORM1I64NVPROC gl3wUniform1i64NV; -extern PFNGLUNIFORM1I64VARBPROC gl3wUniform1i64vARB; -extern PFNGLUNIFORM1I64VNVPROC gl3wUniform1i64vNV; -extern PFNGLUNIFORM1IVPROC gl3wUniform1iv; -extern PFNGLUNIFORM1UIPROC gl3wUniform1ui; -extern PFNGLUNIFORM1UI64ARBPROC gl3wUniform1ui64ARB; -extern PFNGLUNIFORM1UI64NVPROC gl3wUniform1ui64NV; -extern PFNGLUNIFORM1UI64VARBPROC gl3wUniform1ui64vARB; -extern PFNGLUNIFORM1UI64VNVPROC gl3wUniform1ui64vNV; -extern PFNGLUNIFORM1UIVPROC gl3wUniform1uiv; -extern PFNGLUNIFORM2DPROC gl3wUniform2d; -extern PFNGLUNIFORM2DVPROC gl3wUniform2dv; -extern PFNGLUNIFORM2FPROC gl3wUniform2f; -extern PFNGLUNIFORM2FVPROC gl3wUniform2fv; -extern PFNGLUNIFORM2IPROC gl3wUniform2i; -extern PFNGLUNIFORM2I64ARBPROC gl3wUniform2i64ARB; -extern PFNGLUNIFORM2I64NVPROC gl3wUniform2i64NV; -extern PFNGLUNIFORM2I64VARBPROC gl3wUniform2i64vARB; -extern PFNGLUNIFORM2I64VNVPROC gl3wUniform2i64vNV; -extern PFNGLUNIFORM2IVPROC gl3wUniform2iv; -extern PFNGLUNIFORM2UIPROC gl3wUniform2ui; -extern PFNGLUNIFORM2UI64ARBPROC gl3wUniform2ui64ARB; -extern PFNGLUNIFORM2UI64NVPROC gl3wUniform2ui64NV; -extern PFNGLUNIFORM2UI64VARBPROC gl3wUniform2ui64vARB; -extern PFNGLUNIFORM2UI64VNVPROC gl3wUniform2ui64vNV; -extern PFNGLUNIFORM2UIVPROC gl3wUniform2uiv; -extern PFNGLUNIFORM3DPROC gl3wUniform3d; -extern PFNGLUNIFORM3DVPROC gl3wUniform3dv; -extern PFNGLUNIFORM3FPROC gl3wUniform3f; -extern PFNGLUNIFORM3FVPROC gl3wUniform3fv; -extern PFNGLUNIFORM3IPROC gl3wUniform3i; -extern PFNGLUNIFORM3I64ARBPROC gl3wUniform3i64ARB; -extern PFNGLUNIFORM3I64NVPROC gl3wUniform3i64NV; -extern PFNGLUNIFORM3I64VARBPROC gl3wUniform3i64vARB; -extern PFNGLUNIFORM3I64VNVPROC gl3wUniform3i64vNV; -extern PFNGLUNIFORM3IVPROC gl3wUniform3iv; -extern PFNGLUNIFORM3UIPROC gl3wUniform3ui; -extern PFNGLUNIFORM3UI64ARBPROC gl3wUniform3ui64ARB; -extern PFNGLUNIFORM3UI64NVPROC gl3wUniform3ui64NV; -extern PFNGLUNIFORM3UI64VARBPROC gl3wUniform3ui64vARB; -extern PFNGLUNIFORM3UI64VNVPROC gl3wUniform3ui64vNV; -extern PFNGLUNIFORM3UIVPROC gl3wUniform3uiv; -extern PFNGLUNIFORM4DPROC gl3wUniform4d; -extern PFNGLUNIFORM4DVPROC gl3wUniform4dv; -extern PFNGLUNIFORM4FPROC gl3wUniform4f; -extern PFNGLUNIFORM4FVPROC gl3wUniform4fv; -extern PFNGLUNIFORM4IPROC gl3wUniform4i; -extern PFNGLUNIFORM4I64ARBPROC gl3wUniform4i64ARB; -extern PFNGLUNIFORM4I64NVPROC gl3wUniform4i64NV; -extern PFNGLUNIFORM4I64VARBPROC gl3wUniform4i64vARB; -extern PFNGLUNIFORM4I64VNVPROC gl3wUniform4i64vNV; -extern PFNGLUNIFORM4IVPROC gl3wUniform4iv; -extern PFNGLUNIFORM4UIPROC gl3wUniform4ui; -extern PFNGLUNIFORM4UI64ARBPROC gl3wUniform4ui64ARB; -extern PFNGLUNIFORM4UI64NVPROC gl3wUniform4ui64NV; -extern PFNGLUNIFORM4UI64VARBPROC gl3wUniform4ui64vARB; -extern PFNGLUNIFORM4UI64VNVPROC gl3wUniform4ui64vNV; -extern PFNGLUNIFORM4UIVPROC gl3wUniform4uiv; -extern PFNGLUNIFORMBLOCKBINDINGPROC gl3wUniformBlockBinding; -extern PFNGLUNIFORMHANDLEUI64ARBPROC gl3wUniformHandleui64ARB; -extern PFNGLUNIFORMHANDLEUI64NVPROC gl3wUniformHandleui64NV; -extern PFNGLUNIFORMHANDLEUI64VARBPROC gl3wUniformHandleui64vARB; -extern PFNGLUNIFORMHANDLEUI64VNVPROC gl3wUniformHandleui64vNV; -extern PFNGLUNIFORMMATRIX2DVPROC gl3wUniformMatrix2dv; -extern PFNGLUNIFORMMATRIX2FVPROC gl3wUniformMatrix2fv; -extern PFNGLUNIFORMMATRIX2X3DVPROC gl3wUniformMatrix2x3dv; -extern PFNGLUNIFORMMATRIX2X3FVPROC gl3wUniformMatrix2x3fv; -extern PFNGLUNIFORMMATRIX2X4DVPROC gl3wUniformMatrix2x4dv; -extern PFNGLUNIFORMMATRIX2X4FVPROC gl3wUniformMatrix2x4fv; -extern PFNGLUNIFORMMATRIX3DVPROC gl3wUniformMatrix3dv; -extern PFNGLUNIFORMMATRIX3FVPROC gl3wUniformMatrix3fv; -extern PFNGLUNIFORMMATRIX3X2DVPROC gl3wUniformMatrix3x2dv; -extern PFNGLUNIFORMMATRIX3X2FVPROC gl3wUniformMatrix3x2fv; -extern PFNGLUNIFORMMATRIX3X4DVPROC gl3wUniformMatrix3x4dv; -extern PFNGLUNIFORMMATRIX3X4FVPROC gl3wUniformMatrix3x4fv; -extern PFNGLUNIFORMMATRIX4DVPROC gl3wUniformMatrix4dv; -extern PFNGLUNIFORMMATRIX4FVPROC gl3wUniformMatrix4fv; -extern PFNGLUNIFORMMATRIX4X2DVPROC gl3wUniformMatrix4x2dv; -extern PFNGLUNIFORMMATRIX4X2FVPROC gl3wUniformMatrix4x2fv; -extern PFNGLUNIFORMMATRIX4X3DVPROC gl3wUniformMatrix4x3dv; -extern PFNGLUNIFORMMATRIX4X3FVPROC gl3wUniformMatrix4x3fv; -extern PFNGLUNIFORMSUBROUTINESUIVPROC gl3wUniformSubroutinesuiv; -extern PFNGLUNIFORMUI64NVPROC gl3wUniformui64NV; -extern PFNGLUNIFORMUI64VNVPROC gl3wUniformui64vNV; -extern PFNGLUNMAPBUFFERPROC gl3wUnmapBuffer; -extern PFNGLUNMAPNAMEDBUFFERPROC gl3wUnmapNamedBuffer; -extern PFNGLUNMAPNAMEDBUFFEREXTPROC gl3wUnmapNamedBufferEXT; -extern PFNGLUSEPROGRAMPROC gl3wUseProgram; -extern PFNGLUSEPROGRAMSTAGESPROC gl3wUseProgramStages; -extern PFNGLUSESHADERPROGRAMEXTPROC gl3wUseShaderProgramEXT; -extern PFNGLVALIDATEPROGRAMPROC gl3wValidateProgram; -extern PFNGLVALIDATEPROGRAMPIPELINEPROC gl3wValidateProgramPipeline; -extern PFNGLVERTEXARRAYATTRIBBINDINGPROC gl3wVertexArrayAttribBinding; -extern PFNGLVERTEXARRAYATTRIBFORMATPROC gl3wVertexArrayAttribFormat; -extern PFNGLVERTEXARRAYATTRIBIFORMATPROC gl3wVertexArrayAttribIFormat; -extern PFNGLVERTEXARRAYATTRIBLFORMATPROC gl3wVertexArrayAttribLFormat; -extern PFNGLVERTEXARRAYBINDVERTEXBUFFEREXTPROC gl3wVertexArrayBindVertexBufferEXT; -extern PFNGLVERTEXARRAYBINDINGDIVISORPROC gl3wVertexArrayBindingDivisor; -extern PFNGLVERTEXARRAYCOLOROFFSETEXTPROC gl3wVertexArrayColorOffsetEXT; -extern PFNGLVERTEXARRAYEDGEFLAGOFFSETEXTPROC gl3wVertexArrayEdgeFlagOffsetEXT; -extern PFNGLVERTEXARRAYELEMENTBUFFERPROC gl3wVertexArrayElementBuffer; -extern PFNGLVERTEXARRAYFOGCOORDOFFSETEXTPROC gl3wVertexArrayFogCoordOffsetEXT; -extern PFNGLVERTEXARRAYINDEXOFFSETEXTPROC gl3wVertexArrayIndexOffsetEXT; -extern PFNGLVERTEXARRAYMULTITEXCOORDOFFSETEXTPROC gl3wVertexArrayMultiTexCoordOffsetEXT; -extern PFNGLVERTEXARRAYNORMALOFFSETEXTPROC gl3wVertexArrayNormalOffsetEXT; -extern PFNGLVERTEXARRAYSECONDARYCOLOROFFSETEXTPROC gl3wVertexArraySecondaryColorOffsetEXT; -extern PFNGLVERTEXARRAYTEXCOORDOFFSETEXTPROC gl3wVertexArrayTexCoordOffsetEXT; -extern PFNGLVERTEXARRAYVERTEXATTRIBBINDINGEXTPROC gl3wVertexArrayVertexAttribBindingEXT; -extern PFNGLVERTEXARRAYVERTEXATTRIBDIVISOREXTPROC gl3wVertexArrayVertexAttribDivisorEXT; -extern PFNGLVERTEXARRAYVERTEXATTRIBFORMATEXTPROC gl3wVertexArrayVertexAttribFormatEXT; -extern PFNGLVERTEXARRAYVERTEXATTRIBIFORMATEXTPROC gl3wVertexArrayVertexAttribIFormatEXT; -extern PFNGLVERTEXARRAYVERTEXATTRIBIOFFSETEXTPROC gl3wVertexArrayVertexAttribIOffsetEXT; -extern PFNGLVERTEXARRAYVERTEXATTRIBLFORMATEXTPROC gl3wVertexArrayVertexAttribLFormatEXT; -extern PFNGLVERTEXARRAYVERTEXATTRIBLOFFSETEXTPROC gl3wVertexArrayVertexAttribLOffsetEXT; -extern PFNGLVERTEXARRAYVERTEXATTRIBOFFSETEXTPROC gl3wVertexArrayVertexAttribOffsetEXT; -extern PFNGLVERTEXARRAYVERTEXBINDINGDIVISOREXTPROC gl3wVertexArrayVertexBindingDivisorEXT; -extern PFNGLVERTEXARRAYVERTEXBUFFERPROC gl3wVertexArrayVertexBuffer; -extern PFNGLVERTEXARRAYVERTEXBUFFERSPROC gl3wVertexArrayVertexBuffers; -extern PFNGLVERTEXARRAYVERTEXOFFSETEXTPROC gl3wVertexArrayVertexOffsetEXT; -extern PFNGLVERTEXATTRIB1DPROC gl3wVertexAttrib1d; -extern PFNGLVERTEXATTRIB1DVPROC gl3wVertexAttrib1dv; -extern PFNGLVERTEXATTRIB1FPROC gl3wVertexAttrib1f; -extern PFNGLVERTEXATTRIB1FVPROC gl3wVertexAttrib1fv; -extern PFNGLVERTEXATTRIB1SPROC gl3wVertexAttrib1s; -extern PFNGLVERTEXATTRIB1SVPROC gl3wVertexAttrib1sv; -extern PFNGLVERTEXATTRIB2DPROC gl3wVertexAttrib2d; -extern PFNGLVERTEXATTRIB2DVPROC gl3wVertexAttrib2dv; -extern PFNGLVERTEXATTRIB2FPROC gl3wVertexAttrib2f; -extern PFNGLVERTEXATTRIB2FVPROC gl3wVertexAttrib2fv; -extern PFNGLVERTEXATTRIB2SPROC gl3wVertexAttrib2s; -extern PFNGLVERTEXATTRIB2SVPROC gl3wVertexAttrib2sv; -extern PFNGLVERTEXATTRIB3DPROC gl3wVertexAttrib3d; -extern PFNGLVERTEXATTRIB3DVPROC gl3wVertexAttrib3dv; -extern PFNGLVERTEXATTRIB3FPROC gl3wVertexAttrib3f; -extern PFNGLVERTEXATTRIB3FVPROC gl3wVertexAttrib3fv; -extern PFNGLVERTEXATTRIB3SPROC gl3wVertexAttrib3s; -extern PFNGLVERTEXATTRIB3SVPROC gl3wVertexAttrib3sv; -extern PFNGLVERTEXATTRIB4NBVPROC gl3wVertexAttrib4Nbv; -extern PFNGLVERTEXATTRIB4NIVPROC gl3wVertexAttrib4Niv; -extern PFNGLVERTEXATTRIB4NSVPROC gl3wVertexAttrib4Nsv; -extern PFNGLVERTEXATTRIB4NUBPROC gl3wVertexAttrib4Nub; -extern PFNGLVERTEXATTRIB4NUBVPROC gl3wVertexAttrib4Nubv; -extern PFNGLVERTEXATTRIB4NUIVPROC gl3wVertexAttrib4Nuiv; -extern PFNGLVERTEXATTRIB4NUSVPROC gl3wVertexAttrib4Nusv; -extern PFNGLVERTEXATTRIB4BVPROC gl3wVertexAttrib4bv; -extern PFNGLVERTEXATTRIB4DPROC gl3wVertexAttrib4d; -extern PFNGLVERTEXATTRIB4DVPROC gl3wVertexAttrib4dv; -extern PFNGLVERTEXATTRIB4FPROC gl3wVertexAttrib4f; -extern PFNGLVERTEXATTRIB4FVPROC gl3wVertexAttrib4fv; -extern PFNGLVERTEXATTRIB4IVPROC gl3wVertexAttrib4iv; -extern PFNGLVERTEXATTRIB4SPROC gl3wVertexAttrib4s; -extern PFNGLVERTEXATTRIB4SVPROC gl3wVertexAttrib4sv; -extern PFNGLVERTEXATTRIB4UBVPROC gl3wVertexAttrib4ubv; -extern PFNGLVERTEXATTRIB4UIVPROC gl3wVertexAttrib4uiv; -extern PFNGLVERTEXATTRIB4USVPROC gl3wVertexAttrib4usv; -extern PFNGLVERTEXATTRIBBINDINGPROC gl3wVertexAttribBinding; -extern PFNGLVERTEXATTRIBDIVISORPROC gl3wVertexAttribDivisor; -extern PFNGLVERTEXATTRIBDIVISORARBPROC gl3wVertexAttribDivisorARB; -extern PFNGLVERTEXATTRIBFORMATPROC gl3wVertexAttribFormat; -extern PFNGLVERTEXATTRIBFORMATNVPROC gl3wVertexAttribFormatNV; -extern PFNGLVERTEXATTRIBI1IPROC gl3wVertexAttribI1i; -extern PFNGLVERTEXATTRIBI1IVPROC gl3wVertexAttribI1iv; -extern PFNGLVERTEXATTRIBI1UIPROC gl3wVertexAttribI1ui; -extern PFNGLVERTEXATTRIBI1UIVPROC gl3wVertexAttribI1uiv; -extern PFNGLVERTEXATTRIBI2IPROC gl3wVertexAttribI2i; -extern PFNGLVERTEXATTRIBI2IVPROC gl3wVertexAttribI2iv; -extern PFNGLVERTEXATTRIBI2UIPROC gl3wVertexAttribI2ui; -extern PFNGLVERTEXATTRIBI2UIVPROC gl3wVertexAttribI2uiv; -extern PFNGLVERTEXATTRIBI3IPROC gl3wVertexAttribI3i; -extern PFNGLVERTEXATTRIBI3IVPROC gl3wVertexAttribI3iv; -extern PFNGLVERTEXATTRIBI3UIPROC gl3wVertexAttribI3ui; -extern PFNGLVERTEXATTRIBI3UIVPROC gl3wVertexAttribI3uiv; -extern PFNGLVERTEXATTRIBI4BVPROC gl3wVertexAttribI4bv; -extern PFNGLVERTEXATTRIBI4IPROC gl3wVertexAttribI4i; -extern PFNGLVERTEXATTRIBI4IVPROC gl3wVertexAttribI4iv; -extern PFNGLVERTEXATTRIBI4SVPROC gl3wVertexAttribI4sv; -extern PFNGLVERTEXATTRIBI4UBVPROC gl3wVertexAttribI4ubv; -extern PFNGLVERTEXATTRIBI4UIPROC gl3wVertexAttribI4ui; -extern PFNGLVERTEXATTRIBI4UIVPROC gl3wVertexAttribI4uiv; -extern PFNGLVERTEXATTRIBI4USVPROC gl3wVertexAttribI4usv; -extern PFNGLVERTEXATTRIBIFORMATPROC gl3wVertexAttribIFormat; -extern PFNGLVERTEXATTRIBIFORMATNVPROC gl3wVertexAttribIFormatNV; -extern PFNGLVERTEXATTRIBIPOINTERPROC gl3wVertexAttribIPointer; -extern PFNGLVERTEXATTRIBL1DPROC gl3wVertexAttribL1d; -extern PFNGLVERTEXATTRIBL1DVPROC gl3wVertexAttribL1dv; -extern PFNGLVERTEXATTRIBL1I64NVPROC gl3wVertexAttribL1i64NV; -extern PFNGLVERTEXATTRIBL1I64VNVPROC gl3wVertexAttribL1i64vNV; -extern PFNGLVERTEXATTRIBL1UI64ARBPROC gl3wVertexAttribL1ui64ARB; -extern PFNGLVERTEXATTRIBL1UI64NVPROC gl3wVertexAttribL1ui64NV; -extern PFNGLVERTEXATTRIBL1UI64VARBPROC gl3wVertexAttribL1ui64vARB; -extern PFNGLVERTEXATTRIBL1UI64VNVPROC gl3wVertexAttribL1ui64vNV; -extern PFNGLVERTEXATTRIBL2DPROC gl3wVertexAttribL2d; -extern PFNGLVERTEXATTRIBL2DVPROC gl3wVertexAttribL2dv; -extern PFNGLVERTEXATTRIBL2I64NVPROC gl3wVertexAttribL2i64NV; -extern PFNGLVERTEXATTRIBL2I64VNVPROC gl3wVertexAttribL2i64vNV; -extern PFNGLVERTEXATTRIBL2UI64NVPROC gl3wVertexAttribL2ui64NV; -extern PFNGLVERTEXATTRIBL2UI64VNVPROC gl3wVertexAttribL2ui64vNV; -extern PFNGLVERTEXATTRIBL3DPROC gl3wVertexAttribL3d; -extern PFNGLVERTEXATTRIBL3DVPROC gl3wVertexAttribL3dv; -extern PFNGLVERTEXATTRIBL3I64NVPROC gl3wVertexAttribL3i64NV; -extern PFNGLVERTEXATTRIBL3I64VNVPROC gl3wVertexAttribL3i64vNV; -extern PFNGLVERTEXATTRIBL3UI64NVPROC gl3wVertexAttribL3ui64NV; -extern PFNGLVERTEXATTRIBL3UI64VNVPROC gl3wVertexAttribL3ui64vNV; -extern PFNGLVERTEXATTRIBL4DPROC gl3wVertexAttribL4d; -extern PFNGLVERTEXATTRIBL4DVPROC gl3wVertexAttribL4dv; -extern PFNGLVERTEXATTRIBL4I64NVPROC gl3wVertexAttribL4i64NV; -extern PFNGLVERTEXATTRIBL4I64VNVPROC gl3wVertexAttribL4i64vNV; -extern PFNGLVERTEXATTRIBL4UI64NVPROC gl3wVertexAttribL4ui64NV; -extern PFNGLVERTEXATTRIBL4UI64VNVPROC gl3wVertexAttribL4ui64vNV; -extern PFNGLVERTEXATTRIBLFORMATPROC gl3wVertexAttribLFormat; -extern PFNGLVERTEXATTRIBLFORMATNVPROC gl3wVertexAttribLFormatNV; -extern PFNGLVERTEXATTRIBLPOINTERPROC gl3wVertexAttribLPointer; -extern PFNGLVERTEXATTRIBP1UIPROC gl3wVertexAttribP1ui; -extern PFNGLVERTEXATTRIBP1UIVPROC gl3wVertexAttribP1uiv; -extern PFNGLVERTEXATTRIBP2UIPROC gl3wVertexAttribP2ui; -extern PFNGLVERTEXATTRIBP2UIVPROC gl3wVertexAttribP2uiv; -extern PFNGLVERTEXATTRIBP3UIPROC gl3wVertexAttribP3ui; -extern PFNGLVERTEXATTRIBP3UIVPROC gl3wVertexAttribP3uiv; -extern PFNGLVERTEXATTRIBP4UIPROC gl3wVertexAttribP4ui; -extern PFNGLVERTEXATTRIBP4UIVPROC gl3wVertexAttribP4uiv; -extern PFNGLVERTEXATTRIBPOINTERPROC gl3wVertexAttribPointer; -extern PFNGLVERTEXBINDINGDIVISORPROC gl3wVertexBindingDivisor; -extern PFNGLVERTEXFORMATNVPROC gl3wVertexFormatNV; -extern PFNGLVIEWPORTPROC gl3wViewport; -extern PFNGLVIEWPORTARRAYVPROC gl3wViewportArrayv; -extern PFNGLVIEWPORTINDEXEDFPROC gl3wViewportIndexedf; -extern PFNGLVIEWPORTINDEXEDFVPROC gl3wViewportIndexedfv; -extern PFNGLVIEWPORTPOSITIONWSCALENVPROC gl3wViewportPositionWScaleNV; -extern PFNGLVIEWPORTSWIZZLENVPROC gl3wViewportSwizzleNV; -extern PFNGLWAITSYNCPROC gl3wWaitSync; -extern PFNGLWAITVKSEMAPHORENVPROC gl3wWaitVkSemaphoreNV; -extern PFNGLWEIGHTPATHSNVPROC gl3wWeightPathsNV; -extern PFNGLWINDOWRECTANGLESEXTPROC gl3wWindowRectanglesEXT; -#define glActiveProgramEXT gl3wActiveProgramEXT -#define glActiveShaderProgram gl3wActiveShaderProgram -#define glActiveTexture gl3wActiveTexture -#define glApplyFramebufferAttachmentCMAAINTEL gl3wApplyFramebufferAttachmentCMAAINTEL -#define glAttachShader gl3wAttachShader -#define glBeginConditionalRender gl3wBeginConditionalRender -#define glBeginConditionalRenderNV gl3wBeginConditionalRenderNV -#define glBeginPerfMonitorAMD gl3wBeginPerfMonitorAMD -#define glBeginPerfQueryINTEL gl3wBeginPerfQueryINTEL -#define glBeginQuery gl3wBeginQuery -#define glBeginQueryIndexed gl3wBeginQueryIndexed -#define glBeginTransformFeedback gl3wBeginTransformFeedback -#define glBindAttribLocation gl3wBindAttribLocation -#define glBindBuffer gl3wBindBuffer -#define glBindBufferBase gl3wBindBufferBase -#define glBindBufferRange gl3wBindBufferRange -#define glBindBuffersBase gl3wBindBuffersBase -#define glBindBuffersRange gl3wBindBuffersRange -#define glBindFragDataLocation gl3wBindFragDataLocation -#define glBindFragDataLocationIndexed gl3wBindFragDataLocationIndexed -#define glBindFramebuffer gl3wBindFramebuffer -#define glBindImageTexture gl3wBindImageTexture -#define glBindImageTextures gl3wBindImageTextures -#define glBindMultiTextureEXT gl3wBindMultiTextureEXT -#define glBindProgramPipeline gl3wBindProgramPipeline -#define glBindRenderbuffer gl3wBindRenderbuffer -#define glBindSampler gl3wBindSampler -#define glBindSamplers gl3wBindSamplers -#define glBindTexture gl3wBindTexture -#define glBindTextureUnit gl3wBindTextureUnit -#define glBindTextures gl3wBindTextures -#define glBindTransformFeedback gl3wBindTransformFeedback -#define glBindVertexArray gl3wBindVertexArray -#define glBindVertexBuffer gl3wBindVertexBuffer -#define glBindVertexBuffers gl3wBindVertexBuffers -#define glBlendBarrierKHR gl3wBlendBarrierKHR -#define glBlendBarrierNV gl3wBlendBarrierNV -#define glBlendColor gl3wBlendColor -#define glBlendEquation gl3wBlendEquation -#define glBlendEquationSeparate gl3wBlendEquationSeparate -#define glBlendEquationSeparatei gl3wBlendEquationSeparatei -#define glBlendEquationSeparateiARB gl3wBlendEquationSeparateiARB -#define glBlendEquationi gl3wBlendEquationi -#define glBlendEquationiARB gl3wBlendEquationiARB -#define glBlendFunc gl3wBlendFunc -#define glBlendFuncSeparate gl3wBlendFuncSeparate -#define glBlendFuncSeparatei gl3wBlendFuncSeparatei -#define glBlendFuncSeparateiARB gl3wBlendFuncSeparateiARB -#define glBlendFunci gl3wBlendFunci -#define glBlendFunciARB gl3wBlendFunciARB -#define glBlendParameteriNV gl3wBlendParameteriNV -#define glBlitFramebuffer gl3wBlitFramebuffer -#define glBlitNamedFramebuffer gl3wBlitNamedFramebuffer -#define glBufferAddressRangeNV gl3wBufferAddressRangeNV -#define glBufferData gl3wBufferData -#define glBufferPageCommitmentARB gl3wBufferPageCommitmentARB -#define glBufferStorage gl3wBufferStorage -#define glBufferSubData gl3wBufferSubData -#define glCallCommandListNV gl3wCallCommandListNV -#define glCheckFramebufferStatus gl3wCheckFramebufferStatus -#define glCheckNamedFramebufferStatus gl3wCheckNamedFramebufferStatus -#define glCheckNamedFramebufferStatusEXT gl3wCheckNamedFramebufferStatusEXT -#define glClampColor gl3wClampColor -#define glClear gl3wClear -#define glClearBufferData gl3wClearBufferData -#define glClearBufferSubData gl3wClearBufferSubData -#define glClearBufferfi gl3wClearBufferfi -#define glClearBufferfv gl3wClearBufferfv -#define glClearBufferiv gl3wClearBufferiv -#define glClearBufferuiv gl3wClearBufferuiv -#define glClearColor gl3wClearColor -#define glClearDepth gl3wClearDepth -#define glClearDepthf gl3wClearDepthf -#define glClearNamedBufferData gl3wClearNamedBufferData -#define glClearNamedBufferDataEXT gl3wClearNamedBufferDataEXT -#define glClearNamedBufferSubData gl3wClearNamedBufferSubData -#define glClearNamedBufferSubDataEXT gl3wClearNamedBufferSubDataEXT -#define glClearNamedFramebufferfi gl3wClearNamedFramebufferfi -#define glClearNamedFramebufferfv gl3wClearNamedFramebufferfv -#define glClearNamedFramebufferiv gl3wClearNamedFramebufferiv -#define glClearNamedFramebufferuiv gl3wClearNamedFramebufferuiv -#define glClearStencil gl3wClearStencil -#define glClearTexImage gl3wClearTexImage -#define glClearTexSubImage gl3wClearTexSubImage -#define glClientAttribDefaultEXT gl3wClientAttribDefaultEXT -#define glClientWaitSync gl3wClientWaitSync -#define glClipControl gl3wClipControl -#define glColorFormatNV gl3wColorFormatNV -#define glColorMask gl3wColorMask -#define glColorMaski gl3wColorMaski -#define glCommandListSegmentsNV gl3wCommandListSegmentsNV -#define glCompileCommandListNV gl3wCompileCommandListNV -#define glCompileShader gl3wCompileShader -#define glCompileShaderIncludeARB gl3wCompileShaderIncludeARB -#define glCompressedMultiTexImage1DEXT gl3wCompressedMultiTexImage1DEXT -#define glCompressedMultiTexImage2DEXT gl3wCompressedMultiTexImage2DEXT -#define glCompressedMultiTexImage3DEXT gl3wCompressedMultiTexImage3DEXT -#define glCompressedMultiTexSubImage1DEXT gl3wCompressedMultiTexSubImage1DEXT -#define glCompressedMultiTexSubImage2DEXT gl3wCompressedMultiTexSubImage2DEXT -#define glCompressedMultiTexSubImage3DEXT gl3wCompressedMultiTexSubImage3DEXT -#define glCompressedTexImage1D gl3wCompressedTexImage1D -#define glCompressedTexImage2D gl3wCompressedTexImage2D -#define glCompressedTexImage3D gl3wCompressedTexImage3D -#define glCompressedTexSubImage1D gl3wCompressedTexSubImage1D -#define glCompressedTexSubImage2D gl3wCompressedTexSubImage2D -#define glCompressedTexSubImage3D gl3wCompressedTexSubImage3D -#define glCompressedTextureImage1DEXT gl3wCompressedTextureImage1DEXT -#define glCompressedTextureImage2DEXT gl3wCompressedTextureImage2DEXT -#define glCompressedTextureImage3DEXT gl3wCompressedTextureImage3DEXT -#define glCompressedTextureSubImage1D gl3wCompressedTextureSubImage1D -#define glCompressedTextureSubImage1DEXT gl3wCompressedTextureSubImage1DEXT -#define glCompressedTextureSubImage2D gl3wCompressedTextureSubImage2D -#define glCompressedTextureSubImage2DEXT gl3wCompressedTextureSubImage2DEXT -#define glCompressedTextureSubImage3D gl3wCompressedTextureSubImage3D -#define glCompressedTextureSubImage3DEXT gl3wCompressedTextureSubImage3DEXT -#define glConservativeRasterParameterfNV gl3wConservativeRasterParameterfNV -#define glConservativeRasterParameteriNV gl3wConservativeRasterParameteriNV -#define glCopyBufferSubData gl3wCopyBufferSubData -#define glCopyImageSubData gl3wCopyImageSubData -#define glCopyMultiTexImage1DEXT gl3wCopyMultiTexImage1DEXT -#define glCopyMultiTexImage2DEXT gl3wCopyMultiTexImage2DEXT -#define glCopyMultiTexSubImage1DEXT gl3wCopyMultiTexSubImage1DEXT -#define glCopyMultiTexSubImage2DEXT gl3wCopyMultiTexSubImage2DEXT -#define glCopyMultiTexSubImage3DEXT gl3wCopyMultiTexSubImage3DEXT -#define glCopyNamedBufferSubData gl3wCopyNamedBufferSubData -#define glCopyPathNV gl3wCopyPathNV -#define glCopyTexImage1D gl3wCopyTexImage1D -#define glCopyTexImage2D gl3wCopyTexImage2D -#define glCopyTexSubImage1D gl3wCopyTexSubImage1D -#define glCopyTexSubImage2D gl3wCopyTexSubImage2D -#define glCopyTexSubImage3D gl3wCopyTexSubImage3D -#define glCopyTextureImage1DEXT gl3wCopyTextureImage1DEXT -#define glCopyTextureImage2DEXT gl3wCopyTextureImage2DEXT -#define glCopyTextureSubImage1D gl3wCopyTextureSubImage1D -#define glCopyTextureSubImage1DEXT gl3wCopyTextureSubImage1DEXT -#define glCopyTextureSubImage2D gl3wCopyTextureSubImage2D -#define glCopyTextureSubImage2DEXT gl3wCopyTextureSubImage2DEXT -#define glCopyTextureSubImage3D gl3wCopyTextureSubImage3D -#define glCopyTextureSubImage3DEXT gl3wCopyTextureSubImage3DEXT -#define glCoverFillPathInstancedNV gl3wCoverFillPathInstancedNV -#define glCoverFillPathNV gl3wCoverFillPathNV -#define glCoverStrokePathInstancedNV gl3wCoverStrokePathInstancedNV -#define glCoverStrokePathNV gl3wCoverStrokePathNV -#define glCoverageModulationNV gl3wCoverageModulationNV -#define glCoverageModulationTableNV gl3wCoverageModulationTableNV -#define glCreateBuffers gl3wCreateBuffers -#define glCreateCommandListsNV gl3wCreateCommandListsNV -#define glCreateFramebuffers gl3wCreateFramebuffers -#define glCreatePerfQueryINTEL gl3wCreatePerfQueryINTEL -#define glCreateProgram gl3wCreateProgram -#define glCreateProgramPipelines gl3wCreateProgramPipelines -#define glCreateQueries gl3wCreateQueries -#define glCreateRenderbuffers gl3wCreateRenderbuffers -#define glCreateSamplers gl3wCreateSamplers -#define glCreateShader gl3wCreateShader -#define glCreateShaderProgramEXT gl3wCreateShaderProgramEXT -#define glCreateShaderProgramv gl3wCreateShaderProgramv -#define glCreateStatesNV gl3wCreateStatesNV -#define glCreateSyncFromCLeventARB gl3wCreateSyncFromCLeventARB -#define glCreateTextures gl3wCreateTextures -#define glCreateTransformFeedbacks gl3wCreateTransformFeedbacks -#define glCreateVertexArrays gl3wCreateVertexArrays -#define glCullFace gl3wCullFace -#define glDebugMessageCallback gl3wDebugMessageCallback -#define glDebugMessageCallbackARB gl3wDebugMessageCallbackARB -#define glDebugMessageControl gl3wDebugMessageControl -#define glDebugMessageControlARB gl3wDebugMessageControlARB -#define glDebugMessageInsert gl3wDebugMessageInsert -#define glDebugMessageInsertARB gl3wDebugMessageInsertARB -#define glDeleteBuffers gl3wDeleteBuffers -#define glDeleteCommandListsNV gl3wDeleteCommandListsNV -#define glDeleteFramebuffers gl3wDeleteFramebuffers -#define glDeleteNamedStringARB gl3wDeleteNamedStringARB -#define glDeletePathsNV gl3wDeletePathsNV -#define glDeletePerfMonitorsAMD gl3wDeletePerfMonitorsAMD -#define glDeletePerfQueryINTEL gl3wDeletePerfQueryINTEL -#define glDeleteProgram gl3wDeleteProgram -#define glDeleteProgramPipelines gl3wDeleteProgramPipelines -#define glDeleteQueries gl3wDeleteQueries -#define glDeleteRenderbuffers gl3wDeleteRenderbuffers -#define glDeleteSamplers gl3wDeleteSamplers -#define glDeleteShader gl3wDeleteShader -#define glDeleteStatesNV gl3wDeleteStatesNV -#define glDeleteSync gl3wDeleteSync -#define glDeleteTextures gl3wDeleteTextures -#define glDeleteTransformFeedbacks gl3wDeleteTransformFeedbacks -#define glDeleteVertexArrays gl3wDeleteVertexArrays -#define glDepthFunc gl3wDepthFunc -#define glDepthMask gl3wDepthMask -#define glDepthRange gl3wDepthRange -#define glDepthRangeArrayv gl3wDepthRangeArrayv -#define glDepthRangeIndexed gl3wDepthRangeIndexed -#define glDepthRangef gl3wDepthRangef -#define glDetachShader gl3wDetachShader -#define glDisable gl3wDisable -#define glDisableClientStateIndexedEXT gl3wDisableClientStateIndexedEXT -#define glDisableClientStateiEXT gl3wDisableClientStateiEXT -#define glDisableIndexedEXT gl3wDisableIndexedEXT -#define glDisableVertexArrayAttrib gl3wDisableVertexArrayAttrib -#define glDisableVertexArrayAttribEXT gl3wDisableVertexArrayAttribEXT -#define glDisableVertexArrayEXT gl3wDisableVertexArrayEXT -#define glDisableVertexAttribArray gl3wDisableVertexAttribArray -#define glDisablei gl3wDisablei -#define glDispatchCompute gl3wDispatchCompute -#define glDispatchComputeGroupSizeARB gl3wDispatchComputeGroupSizeARB -#define glDispatchComputeIndirect gl3wDispatchComputeIndirect -#define glDrawArrays gl3wDrawArrays -#define glDrawArraysIndirect gl3wDrawArraysIndirect -#define glDrawArraysInstanced gl3wDrawArraysInstanced -#define glDrawArraysInstancedARB gl3wDrawArraysInstancedARB -#define glDrawArraysInstancedBaseInstance gl3wDrawArraysInstancedBaseInstance -#define glDrawArraysInstancedEXT gl3wDrawArraysInstancedEXT -#define glDrawBuffer gl3wDrawBuffer -#define glDrawBuffers gl3wDrawBuffers -#define glDrawCommandsAddressNV gl3wDrawCommandsAddressNV -#define glDrawCommandsNV gl3wDrawCommandsNV -#define glDrawCommandsStatesAddressNV gl3wDrawCommandsStatesAddressNV -#define glDrawCommandsStatesNV gl3wDrawCommandsStatesNV -#define glDrawElements gl3wDrawElements -#define glDrawElementsBaseVertex gl3wDrawElementsBaseVertex -#define glDrawElementsIndirect gl3wDrawElementsIndirect -#define glDrawElementsInstanced gl3wDrawElementsInstanced -#define glDrawElementsInstancedARB gl3wDrawElementsInstancedARB -#define glDrawElementsInstancedBaseInstance gl3wDrawElementsInstancedBaseInstance -#define glDrawElementsInstancedBaseVertex gl3wDrawElementsInstancedBaseVertex -#define glDrawElementsInstancedBaseVertexBaseInstance gl3wDrawElementsInstancedBaseVertexBaseInstance -#define glDrawElementsInstancedEXT gl3wDrawElementsInstancedEXT -#define glDrawRangeElements gl3wDrawRangeElements -#define glDrawRangeElementsBaseVertex gl3wDrawRangeElementsBaseVertex -#define glDrawTransformFeedback gl3wDrawTransformFeedback -#define glDrawTransformFeedbackInstanced gl3wDrawTransformFeedbackInstanced -#define glDrawTransformFeedbackStream gl3wDrawTransformFeedbackStream -#define glDrawTransformFeedbackStreamInstanced gl3wDrawTransformFeedbackStreamInstanced -#define glDrawVkImageNV gl3wDrawVkImageNV -#define glEdgeFlagFormatNV gl3wEdgeFlagFormatNV -#define glEnable gl3wEnable -#define glEnableClientStateIndexedEXT gl3wEnableClientStateIndexedEXT -#define glEnableClientStateiEXT gl3wEnableClientStateiEXT -#define glEnableIndexedEXT gl3wEnableIndexedEXT -#define glEnableVertexArrayAttrib gl3wEnableVertexArrayAttrib -#define glEnableVertexArrayAttribEXT gl3wEnableVertexArrayAttribEXT -#define glEnableVertexArrayEXT gl3wEnableVertexArrayEXT -#define glEnableVertexAttribArray gl3wEnableVertexAttribArray -#define glEnablei gl3wEnablei -#define glEndConditionalRender gl3wEndConditionalRender -#define glEndConditionalRenderNV gl3wEndConditionalRenderNV -#define glEndPerfMonitorAMD gl3wEndPerfMonitorAMD -#define glEndPerfQueryINTEL gl3wEndPerfQueryINTEL -#define glEndQuery gl3wEndQuery -#define glEndQueryIndexed gl3wEndQueryIndexed -#define glEndTransformFeedback gl3wEndTransformFeedback -#define glEvaluateDepthValuesARB gl3wEvaluateDepthValuesARB -#define glFenceSync gl3wFenceSync -#define glFinish gl3wFinish -#define glFlush gl3wFlush -#define glFlushMappedBufferRange gl3wFlushMappedBufferRange -#define glFlushMappedNamedBufferRange gl3wFlushMappedNamedBufferRange -#define glFlushMappedNamedBufferRangeEXT gl3wFlushMappedNamedBufferRangeEXT -#define glFogCoordFormatNV gl3wFogCoordFormatNV -#define glFragmentCoverageColorNV gl3wFragmentCoverageColorNV -#define glFramebufferDrawBufferEXT gl3wFramebufferDrawBufferEXT -#define glFramebufferDrawBuffersEXT gl3wFramebufferDrawBuffersEXT -#define glFramebufferParameteri gl3wFramebufferParameteri -#define glFramebufferReadBufferEXT gl3wFramebufferReadBufferEXT -#define glFramebufferRenderbuffer gl3wFramebufferRenderbuffer -#define glFramebufferSampleLocationsfvARB gl3wFramebufferSampleLocationsfvARB -#define glFramebufferSampleLocationsfvNV gl3wFramebufferSampleLocationsfvNV -#define glFramebufferTexture gl3wFramebufferTexture -#define glFramebufferTexture1D gl3wFramebufferTexture1D -#define glFramebufferTexture2D gl3wFramebufferTexture2D -#define glFramebufferTexture3D gl3wFramebufferTexture3D -#define glFramebufferTextureARB gl3wFramebufferTextureARB -#define glFramebufferTextureFaceARB gl3wFramebufferTextureFaceARB -#define glFramebufferTextureLayer gl3wFramebufferTextureLayer -#define glFramebufferTextureLayerARB gl3wFramebufferTextureLayerARB -#define glFramebufferTextureMultiviewOVR gl3wFramebufferTextureMultiviewOVR -#define glFrontFace gl3wFrontFace -#define glGenBuffers gl3wGenBuffers -#define glGenFramebuffers gl3wGenFramebuffers -#define glGenPathsNV gl3wGenPathsNV -#define glGenPerfMonitorsAMD gl3wGenPerfMonitorsAMD -#define glGenProgramPipelines gl3wGenProgramPipelines -#define glGenQueries gl3wGenQueries -#define glGenRenderbuffers gl3wGenRenderbuffers -#define glGenSamplers gl3wGenSamplers -#define glGenTextures gl3wGenTextures -#define glGenTransformFeedbacks gl3wGenTransformFeedbacks -#define glGenVertexArrays gl3wGenVertexArrays -#define glGenerateMipmap gl3wGenerateMipmap -#define glGenerateMultiTexMipmapEXT gl3wGenerateMultiTexMipmapEXT -#define glGenerateTextureMipmap gl3wGenerateTextureMipmap -#define glGenerateTextureMipmapEXT gl3wGenerateTextureMipmapEXT -#define glGetActiveAtomicCounterBufferiv gl3wGetActiveAtomicCounterBufferiv -#define glGetActiveAttrib gl3wGetActiveAttrib -#define glGetActiveSubroutineName gl3wGetActiveSubroutineName -#define glGetActiveSubroutineUniformName gl3wGetActiveSubroutineUniformName -#define glGetActiveSubroutineUniformiv gl3wGetActiveSubroutineUniformiv -#define glGetActiveUniform gl3wGetActiveUniform -#define glGetActiveUniformBlockName gl3wGetActiveUniformBlockName -#define glGetActiveUniformBlockiv gl3wGetActiveUniformBlockiv -#define glGetActiveUniformName gl3wGetActiveUniformName -#define glGetActiveUniformsiv gl3wGetActiveUniformsiv -#define glGetAttachedShaders gl3wGetAttachedShaders -#define glGetAttribLocation gl3wGetAttribLocation -#define glGetBooleanIndexedvEXT gl3wGetBooleanIndexedvEXT -#define glGetBooleani_v gl3wGetBooleani_v -#define glGetBooleanv gl3wGetBooleanv -#define glGetBufferParameteri64v gl3wGetBufferParameteri64v -#define glGetBufferParameteriv gl3wGetBufferParameteriv -#define glGetBufferParameterui64vNV gl3wGetBufferParameterui64vNV -#define glGetBufferPointerv gl3wGetBufferPointerv -#define glGetBufferSubData gl3wGetBufferSubData -#define glGetCommandHeaderNV gl3wGetCommandHeaderNV -#define glGetCompressedMultiTexImageEXT gl3wGetCompressedMultiTexImageEXT -#define glGetCompressedTexImage gl3wGetCompressedTexImage -#define glGetCompressedTextureImage gl3wGetCompressedTextureImage -#define glGetCompressedTextureImageEXT gl3wGetCompressedTextureImageEXT -#define glGetCompressedTextureSubImage gl3wGetCompressedTextureSubImage -#define glGetCoverageModulationTableNV gl3wGetCoverageModulationTableNV -#define glGetDebugMessageLog gl3wGetDebugMessageLog -#define glGetDebugMessageLogARB gl3wGetDebugMessageLogARB -#define glGetDoubleIndexedvEXT gl3wGetDoubleIndexedvEXT -#define glGetDoublei_v gl3wGetDoublei_v -#define glGetDoublei_vEXT gl3wGetDoublei_vEXT -#define glGetDoublev gl3wGetDoublev -#define glGetError gl3wGetError -#define glGetFirstPerfQueryIdINTEL gl3wGetFirstPerfQueryIdINTEL -#define glGetFloatIndexedvEXT gl3wGetFloatIndexedvEXT -#define glGetFloati_v gl3wGetFloati_v -#define glGetFloati_vEXT gl3wGetFloati_vEXT -#define glGetFloatv gl3wGetFloatv -#define glGetFragDataIndex gl3wGetFragDataIndex -#define glGetFragDataLocation gl3wGetFragDataLocation -#define glGetFramebufferAttachmentParameteriv gl3wGetFramebufferAttachmentParameteriv -#define glGetFramebufferParameteriv gl3wGetFramebufferParameteriv -#define glGetFramebufferParameterivEXT gl3wGetFramebufferParameterivEXT -#define glGetGraphicsResetStatus gl3wGetGraphicsResetStatus -#define glGetGraphicsResetStatusARB gl3wGetGraphicsResetStatusARB -#define glGetImageHandleARB gl3wGetImageHandleARB -#define glGetImageHandleNV gl3wGetImageHandleNV -#define glGetInteger64i_v gl3wGetInteger64i_v -#define glGetInteger64v gl3wGetInteger64v -#define glGetIntegerIndexedvEXT gl3wGetIntegerIndexedvEXT -#define glGetIntegeri_v gl3wGetIntegeri_v -#define glGetIntegerui64i_vNV gl3wGetIntegerui64i_vNV -#define glGetIntegerui64vNV gl3wGetIntegerui64vNV -#define glGetIntegerv gl3wGetIntegerv -#define glGetInternalformatSampleivNV gl3wGetInternalformatSampleivNV -#define glGetInternalformati64v gl3wGetInternalformati64v -#define glGetInternalformativ gl3wGetInternalformativ -#define glGetMultiTexEnvfvEXT gl3wGetMultiTexEnvfvEXT -#define glGetMultiTexEnvivEXT gl3wGetMultiTexEnvivEXT -#define glGetMultiTexGendvEXT gl3wGetMultiTexGendvEXT -#define glGetMultiTexGenfvEXT gl3wGetMultiTexGenfvEXT -#define glGetMultiTexGenivEXT gl3wGetMultiTexGenivEXT -#define glGetMultiTexImageEXT gl3wGetMultiTexImageEXT -#define glGetMultiTexLevelParameterfvEXT gl3wGetMultiTexLevelParameterfvEXT -#define glGetMultiTexLevelParameterivEXT gl3wGetMultiTexLevelParameterivEXT -#define glGetMultiTexParameterIivEXT gl3wGetMultiTexParameterIivEXT -#define glGetMultiTexParameterIuivEXT gl3wGetMultiTexParameterIuivEXT -#define glGetMultiTexParameterfvEXT gl3wGetMultiTexParameterfvEXT -#define glGetMultiTexParameterivEXT gl3wGetMultiTexParameterivEXT -#define glGetMultisamplefv gl3wGetMultisamplefv -#define glGetNamedBufferParameteri64v gl3wGetNamedBufferParameteri64v -#define glGetNamedBufferParameteriv gl3wGetNamedBufferParameteriv -#define glGetNamedBufferParameterivEXT gl3wGetNamedBufferParameterivEXT -#define glGetNamedBufferParameterui64vNV gl3wGetNamedBufferParameterui64vNV -#define glGetNamedBufferPointerv gl3wGetNamedBufferPointerv -#define glGetNamedBufferPointervEXT gl3wGetNamedBufferPointervEXT -#define glGetNamedBufferSubData gl3wGetNamedBufferSubData -#define glGetNamedBufferSubDataEXT gl3wGetNamedBufferSubDataEXT -#define glGetNamedFramebufferAttachmentParameteriv gl3wGetNamedFramebufferAttachmentParameteriv -#define glGetNamedFramebufferAttachmentParameterivEXT gl3wGetNamedFramebufferAttachmentParameterivEXT -#define glGetNamedFramebufferParameteriv gl3wGetNamedFramebufferParameteriv -#define glGetNamedFramebufferParameterivEXT gl3wGetNamedFramebufferParameterivEXT -#define glGetNamedProgramLocalParameterIivEXT gl3wGetNamedProgramLocalParameterIivEXT -#define glGetNamedProgramLocalParameterIuivEXT gl3wGetNamedProgramLocalParameterIuivEXT -#define glGetNamedProgramLocalParameterdvEXT gl3wGetNamedProgramLocalParameterdvEXT -#define glGetNamedProgramLocalParameterfvEXT gl3wGetNamedProgramLocalParameterfvEXT -#define glGetNamedProgramStringEXT gl3wGetNamedProgramStringEXT -#define glGetNamedProgramivEXT gl3wGetNamedProgramivEXT -#define glGetNamedRenderbufferParameteriv gl3wGetNamedRenderbufferParameteriv -#define glGetNamedRenderbufferParameterivEXT gl3wGetNamedRenderbufferParameterivEXT -#define glGetNamedStringARB gl3wGetNamedStringARB -#define glGetNamedStringivARB gl3wGetNamedStringivARB -#define glGetNextPerfQueryIdINTEL gl3wGetNextPerfQueryIdINTEL -#define glGetObjectLabel gl3wGetObjectLabel -#define glGetObjectLabelEXT gl3wGetObjectLabelEXT -#define glGetObjectPtrLabel gl3wGetObjectPtrLabel -#define glGetPathCommandsNV gl3wGetPathCommandsNV -#define glGetPathCoordsNV gl3wGetPathCoordsNV -#define glGetPathDashArrayNV gl3wGetPathDashArrayNV -#define glGetPathLengthNV gl3wGetPathLengthNV -#define glGetPathMetricRangeNV gl3wGetPathMetricRangeNV -#define glGetPathMetricsNV gl3wGetPathMetricsNV -#define glGetPathParameterfvNV gl3wGetPathParameterfvNV -#define glGetPathParameterivNV gl3wGetPathParameterivNV -#define glGetPathSpacingNV gl3wGetPathSpacingNV -#define glGetPerfCounterInfoINTEL gl3wGetPerfCounterInfoINTEL -#define glGetPerfMonitorCounterDataAMD gl3wGetPerfMonitorCounterDataAMD -#define glGetPerfMonitorCounterInfoAMD gl3wGetPerfMonitorCounterInfoAMD -#define glGetPerfMonitorCounterStringAMD gl3wGetPerfMonitorCounterStringAMD -#define glGetPerfMonitorCountersAMD gl3wGetPerfMonitorCountersAMD -#define glGetPerfMonitorGroupStringAMD gl3wGetPerfMonitorGroupStringAMD -#define glGetPerfMonitorGroupsAMD gl3wGetPerfMonitorGroupsAMD -#define glGetPerfQueryDataINTEL gl3wGetPerfQueryDataINTEL -#define glGetPerfQueryIdByNameINTEL gl3wGetPerfQueryIdByNameINTEL -#define glGetPerfQueryInfoINTEL gl3wGetPerfQueryInfoINTEL -#define glGetPointerIndexedvEXT gl3wGetPointerIndexedvEXT -#define glGetPointeri_vEXT gl3wGetPointeri_vEXT -#define glGetPointerv gl3wGetPointerv -#define glGetProgramBinary gl3wGetProgramBinary -#define glGetProgramInfoLog gl3wGetProgramInfoLog -#define glGetProgramInterfaceiv gl3wGetProgramInterfaceiv -#define glGetProgramPipelineInfoLog gl3wGetProgramPipelineInfoLog -#define glGetProgramPipelineiv gl3wGetProgramPipelineiv -#define glGetProgramResourceIndex gl3wGetProgramResourceIndex -#define glGetProgramResourceLocation gl3wGetProgramResourceLocation -#define glGetProgramResourceLocationIndex gl3wGetProgramResourceLocationIndex -#define glGetProgramResourceName gl3wGetProgramResourceName -#define glGetProgramResourcefvNV gl3wGetProgramResourcefvNV -#define glGetProgramResourceiv gl3wGetProgramResourceiv -#define glGetProgramStageiv gl3wGetProgramStageiv -#define glGetProgramiv gl3wGetProgramiv -#define glGetQueryBufferObjecti64v gl3wGetQueryBufferObjecti64v -#define glGetQueryBufferObjectiv gl3wGetQueryBufferObjectiv -#define glGetQueryBufferObjectui64v gl3wGetQueryBufferObjectui64v -#define glGetQueryBufferObjectuiv gl3wGetQueryBufferObjectuiv -#define glGetQueryIndexediv gl3wGetQueryIndexediv -#define glGetQueryObjecti64v gl3wGetQueryObjecti64v -#define glGetQueryObjectiv gl3wGetQueryObjectiv -#define glGetQueryObjectui64v gl3wGetQueryObjectui64v -#define glGetQueryObjectuiv gl3wGetQueryObjectuiv -#define glGetQueryiv gl3wGetQueryiv -#define glGetRenderbufferParameteriv gl3wGetRenderbufferParameteriv -#define glGetSamplerParameterIiv gl3wGetSamplerParameterIiv -#define glGetSamplerParameterIuiv gl3wGetSamplerParameterIuiv -#define glGetSamplerParameterfv gl3wGetSamplerParameterfv -#define glGetSamplerParameteriv gl3wGetSamplerParameteriv -#define glGetShaderInfoLog gl3wGetShaderInfoLog -#define glGetShaderPrecisionFormat gl3wGetShaderPrecisionFormat -#define glGetShaderSource gl3wGetShaderSource -#define glGetShaderiv gl3wGetShaderiv -#define glGetStageIndexNV gl3wGetStageIndexNV -#define glGetString gl3wGetString -#define glGetStringi gl3wGetStringi -#define glGetSubroutineIndex gl3wGetSubroutineIndex -#define glGetSubroutineUniformLocation gl3wGetSubroutineUniformLocation -#define glGetSynciv gl3wGetSynciv -#define glGetTexImage gl3wGetTexImage -#define glGetTexLevelParameterfv gl3wGetTexLevelParameterfv -#define glGetTexLevelParameteriv gl3wGetTexLevelParameteriv -#define glGetTexParameterIiv gl3wGetTexParameterIiv -#define glGetTexParameterIuiv gl3wGetTexParameterIuiv -#define glGetTexParameterfv gl3wGetTexParameterfv -#define glGetTexParameteriv gl3wGetTexParameteriv -#define glGetTextureHandleARB gl3wGetTextureHandleARB -#define glGetTextureHandleNV gl3wGetTextureHandleNV -#define glGetTextureImage gl3wGetTextureImage -#define glGetTextureImageEXT gl3wGetTextureImageEXT -#define glGetTextureLevelParameterfv gl3wGetTextureLevelParameterfv -#define glGetTextureLevelParameterfvEXT gl3wGetTextureLevelParameterfvEXT -#define glGetTextureLevelParameteriv gl3wGetTextureLevelParameteriv -#define glGetTextureLevelParameterivEXT gl3wGetTextureLevelParameterivEXT -#define glGetTextureParameterIiv gl3wGetTextureParameterIiv -#define glGetTextureParameterIivEXT gl3wGetTextureParameterIivEXT -#define glGetTextureParameterIuiv gl3wGetTextureParameterIuiv -#define glGetTextureParameterIuivEXT gl3wGetTextureParameterIuivEXT -#define glGetTextureParameterfv gl3wGetTextureParameterfv -#define glGetTextureParameterfvEXT gl3wGetTextureParameterfvEXT -#define glGetTextureParameteriv gl3wGetTextureParameteriv -#define glGetTextureParameterivEXT gl3wGetTextureParameterivEXT -#define glGetTextureSamplerHandleARB gl3wGetTextureSamplerHandleARB -#define glGetTextureSamplerHandleNV gl3wGetTextureSamplerHandleNV -#define glGetTextureSubImage gl3wGetTextureSubImage -#define glGetTransformFeedbackVarying gl3wGetTransformFeedbackVarying -#define glGetTransformFeedbacki64_v gl3wGetTransformFeedbacki64_v -#define glGetTransformFeedbacki_v gl3wGetTransformFeedbacki_v -#define glGetTransformFeedbackiv gl3wGetTransformFeedbackiv -#define glGetUniformBlockIndex gl3wGetUniformBlockIndex -#define glGetUniformIndices gl3wGetUniformIndices -#define glGetUniformLocation gl3wGetUniformLocation -#define glGetUniformSubroutineuiv gl3wGetUniformSubroutineuiv -#define glGetUniformdv gl3wGetUniformdv -#define glGetUniformfv gl3wGetUniformfv -#define glGetUniformi64vARB gl3wGetUniformi64vARB -#define glGetUniformi64vNV gl3wGetUniformi64vNV -#define glGetUniformiv gl3wGetUniformiv -#define glGetUniformui64vARB gl3wGetUniformui64vARB -#define glGetUniformui64vNV gl3wGetUniformui64vNV -#define glGetUniformuiv gl3wGetUniformuiv -#define glGetVertexArrayIndexed64iv gl3wGetVertexArrayIndexed64iv -#define glGetVertexArrayIndexediv gl3wGetVertexArrayIndexediv -#define glGetVertexArrayIntegeri_vEXT gl3wGetVertexArrayIntegeri_vEXT -#define glGetVertexArrayIntegervEXT gl3wGetVertexArrayIntegervEXT -#define glGetVertexArrayPointeri_vEXT gl3wGetVertexArrayPointeri_vEXT -#define glGetVertexArrayPointervEXT gl3wGetVertexArrayPointervEXT -#define glGetVertexArrayiv gl3wGetVertexArrayiv -#define glGetVertexAttribIiv gl3wGetVertexAttribIiv -#define glGetVertexAttribIuiv gl3wGetVertexAttribIuiv -#define glGetVertexAttribLdv gl3wGetVertexAttribLdv -#define glGetVertexAttribLi64vNV gl3wGetVertexAttribLi64vNV -#define glGetVertexAttribLui64vARB gl3wGetVertexAttribLui64vARB -#define glGetVertexAttribLui64vNV gl3wGetVertexAttribLui64vNV -#define glGetVertexAttribPointerv gl3wGetVertexAttribPointerv -#define glGetVertexAttribdv gl3wGetVertexAttribdv -#define glGetVertexAttribfv gl3wGetVertexAttribfv -#define glGetVertexAttribiv gl3wGetVertexAttribiv -#define glGetVkProcAddrNV gl3wGetVkProcAddrNV -#define glGetnCompressedTexImage gl3wGetnCompressedTexImage -#define glGetnCompressedTexImageARB gl3wGetnCompressedTexImageARB -#define glGetnTexImage gl3wGetnTexImage -#define glGetnTexImageARB gl3wGetnTexImageARB -#define glGetnUniformdv gl3wGetnUniformdv -#define glGetnUniformdvARB gl3wGetnUniformdvARB -#define glGetnUniformfv gl3wGetnUniformfv -#define glGetnUniformfvARB gl3wGetnUniformfvARB -#define glGetnUniformi64vARB gl3wGetnUniformi64vARB -#define glGetnUniformiv gl3wGetnUniformiv -#define glGetnUniformivARB gl3wGetnUniformivARB -#define glGetnUniformui64vARB gl3wGetnUniformui64vARB -#define glGetnUniformuiv gl3wGetnUniformuiv -#define glGetnUniformuivARB gl3wGetnUniformuivARB -#define glHint gl3wHint -#define glIndexFormatNV gl3wIndexFormatNV -#define glInsertEventMarkerEXT gl3wInsertEventMarkerEXT -#define glInterpolatePathsNV gl3wInterpolatePathsNV -#define glInvalidateBufferData gl3wInvalidateBufferData -#define glInvalidateBufferSubData gl3wInvalidateBufferSubData -#define glInvalidateFramebuffer gl3wInvalidateFramebuffer -#define glInvalidateNamedFramebufferData gl3wInvalidateNamedFramebufferData -#define glInvalidateNamedFramebufferSubData gl3wInvalidateNamedFramebufferSubData -#define glInvalidateSubFramebuffer gl3wInvalidateSubFramebuffer -#define glInvalidateTexImage gl3wInvalidateTexImage -#define glInvalidateTexSubImage gl3wInvalidateTexSubImage -#define glIsBuffer gl3wIsBuffer -#define glIsBufferResidentNV gl3wIsBufferResidentNV -#define glIsCommandListNV gl3wIsCommandListNV -#define glIsEnabled gl3wIsEnabled -#define glIsEnabledIndexedEXT gl3wIsEnabledIndexedEXT -#define glIsEnabledi gl3wIsEnabledi -#define glIsFramebuffer gl3wIsFramebuffer -#define glIsImageHandleResidentARB gl3wIsImageHandleResidentARB -#define glIsImageHandleResidentNV gl3wIsImageHandleResidentNV -#define glIsNamedBufferResidentNV gl3wIsNamedBufferResidentNV -#define glIsNamedStringARB gl3wIsNamedStringARB -#define glIsPathNV gl3wIsPathNV -#define glIsPointInFillPathNV gl3wIsPointInFillPathNV -#define glIsPointInStrokePathNV gl3wIsPointInStrokePathNV -#define glIsProgram gl3wIsProgram -#define glIsProgramPipeline gl3wIsProgramPipeline -#define glIsQuery gl3wIsQuery -#define glIsRenderbuffer gl3wIsRenderbuffer -#define glIsSampler gl3wIsSampler -#define glIsShader gl3wIsShader -#define glIsStateNV gl3wIsStateNV -#define glIsSync gl3wIsSync -#define glIsTexture gl3wIsTexture -#define glIsTextureHandleResidentARB gl3wIsTextureHandleResidentARB -#define glIsTextureHandleResidentNV gl3wIsTextureHandleResidentNV -#define glIsTransformFeedback gl3wIsTransformFeedback -#define glIsVertexArray gl3wIsVertexArray -#define glLabelObjectEXT gl3wLabelObjectEXT -#define glLineWidth gl3wLineWidth -#define glLinkProgram gl3wLinkProgram -#define glListDrawCommandsStatesClientNV gl3wListDrawCommandsStatesClientNV -#define glLogicOp gl3wLogicOp -#define glMakeBufferNonResidentNV gl3wMakeBufferNonResidentNV -#define glMakeBufferResidentNV gl3wMakeBufferResidentNV -#define glMakeImageHandleNonResidentARB gl3wMakeImageHandleNonResidentARB -#define glMakeImageHandleNonResidentNV gl3wMakeImageHandleNonResidentNV -#define glMakeImageHandleResidentARB gl3wMakeImageHandleResidentARB -#define glMakeImageHandleResidentNV gl3wMakeImageHandleResidentNV -#define glMakeNamedBufferNonResidentNV gl3wMakeNamedBufferNonResidentNV -#define glMakeNamedBufferResidentNV gl3wMakeNamedBufferResidentNV -#define glMakeTextureHandleNonResidentARB gl3wMakeTextureHandleNonResidentARB -#define glMakeTextureHandleNonResidentNV gl3wMakeTextureHandleNonResidentNV -#define glMakeTextureHandleResidentARB gl3wMakeTextureHandleResidentARB -#define glMakeTextureHandleResidentNV gl3wMakeTextureHandleResidentNV -#define glMapBuffer gl3wMapBuffer -#define glMapBufferRange gl3wMapBufferRange -#define glMapNamedBuffer gl3wMapNamedBuffer -#define glMapNamedBufferEXT gl3wMapNamedBufferEXT -#define glMapNamedBufferRange gl3wMapNamedBufferRange -#define glMapNamedBufferRangeEXT gl3wMapNamedBufferRangeEXT -#define glMatrixFrustumEXT gl3wMatrixFrustumEXT -#define glMatrixLoad3x2fNV gl3wMatrixLoad3x2fNV -#define glMatrixLoad3x3fNV gl3wMatrixLoad3x3fNV -#define glMatrixLoadIdentityEXT gl3wMatrixLoadIdentityEXT -#define glMatrixLoadTranspose3x3fNV gl3wMatrixLoadTranspose3x3fNV -#define glMatrixLoadTransposedEXT gl3wMatrixLoadTransposedEXT -#define glMatrixLoadTransposefEXT gl3wMatrixLoadTransposefEXT -#define glMatrixLoaddEXT gl3wMatrixLoaddEXT -#define glMatrixLoadfEXT gl3wMatrixLoadfEXT -#define glMatrixMult3x2fNV gl3wMatrixMult3x2fNV -#define glMatrixMult3x3fNV gl3wMatrixMult3x3fNV -#define glMatrixMultTranspose3x3fNV gl3wMatrixMultTranspose3x3fNV -#define glMatrixMultTransposedEXT gl3wMatrixMultTransposedEXT -#define glMatrixMultTransposefEXT gl3wMatrixMultTransposefEXT -#define glMatrixMultdEXT gl3wMatrixMultdEXT -#define glMatrixMultfEXT gl3wMatrixMultfEXT -#define glMatrixOrthoEXT gl3wMatrixOrthoEXT -#define glMatrixPopEXT gl3wMatrixPopEXT -#define glMatrixPushEXT gl3wMatrixPushEXT -#define glMatrixRotatedEXT gl3wMatrixRotatedEXT -#define glMatrixRotatefEXT gl3wMatrixRotatefEXT -#define glMatrixScaledEXT gl3wMatrixScaledEXT -#define glMatrixScalefEXT gl3wMatrixScalefEXT -#define glMatrixTranslatedEXT gl3wMatrixTranslatedEXT -#define glMatrixTranslatefEXT gl3wMatrixTranslatefEXT -#define glMaxShaderCompilerThreadsARB gl3wMaxShaderCompilerThreadsARB -#define glMemoryBarrier gl3wMemoryBarrier -#define glMemoryBarrierByRegion gl3wMemoryBarrierByRegion -#define glMinSampleShading gl3wMinSampleShading -#define glMinSampleShadingARB gl3wMinSampleShadingARB -#define glMultiDrawArrays gl3wMultiDrawArrays -#define glMultiDrawArraysIndirect gl3wMultiDrawArraysIndirect -#define glMultiDrawArraysIndirectBindlessCountNV gl3wMultiDrawArraysIndirectBindlessCountNV -#define glMultiDrawArraysIndirectBindlessNV gl3wMultiDrawArraysIndirectBindlessNV -#define glMultiDrawArraysIndirectCount gl3wMultiDrawArraysIndirectCount -#define glMultiDrawArraysIndirectCountARB gl3wMultiDrawArraysIndirectCountARB -#define glMultiDrawElements gl3wMultiDrawElements -#define glMultiDrawElementsBaseVertex gl3wMultiDrawElementsBaseVertex -#define glMultiDrawElementsIndirect gl3wMultiDrawElementsIndirect -#define glMultiDrawElementsIndirectBindlessCountNV gl3wMultiDrawElementsIndirectBindlessCountNV -#define glMultiDrawElementsIndirectBindlessNV gl3wMultiDrawElementsIndirectBindlessNV -#define glMultiDrawElementsIndirectCount gl3wMultiDrawElementsIndirectCount -#define glMultiDrawElementsIndirectCountARB gl3wMultiDrawElementsIndirectCountARB -#define glMultiTexBufferEXT gl3wMultiTexBufferEXT -#define glMultiTexCoordPointerEXT gl3wMultiTexCoordPointerEXT -#define glMultiTexEnvfEXT gl3wMultiTexEnvfEXT -#define glMultiTexEnvfvEXT gl3wMultiTexEnvfvEXT -#define glMultiTexEnviEXT gl3wMultiTexEnviEXT -#define glMultiTexEnvivEXT gl3wMultiTexEnvivEXT -#define glMultiTexGendEXT gl3wMultiTexGendEXT -#define glMultiTexGendvEXT gl3wMultiTexGendvEXT -#define glMultiTexGenfEXT gl3wMultiTexGenfEXT -#define glMultiTexGenfvEXT gl3wMultiTexGenfvEXT -#define glMultiTexGeniEXT gl3wMultiTexGeniEXT -#define glMultiTexGenivEXT gl3wMultiTexGenivEXT -#define glMultiTexImage1DEXT gl3wMultiTexImage1DEXT -#define glMultiTexImage2DEXT gl3wMultiTexImage2DEXT -#define glMultiTexImage3DEXT gl3wMultiTexImage3DEXT -#define glMultiTexParameterIivEXT gl3wMultiTexParameterIivEXT -#define glMultiTexParameterIuivEXT gl3wMultiTexParameterIuivEXT -#define glMultiTexParameterfEXT gl3wMultiTexParameterfEXT -#define glMultiTexParameterfvEXT gl3wMultiTexParameterfvEXT -#define glMultiTexParameteriEXT gl3wMultiTexParameteriEXT -#define glMultiTexParameterivEXT gl3wMultiTexParameterivEXT -#define glMultiTexRenderbufferEXT gl3wMultiTexRenderbufferEXT -#define glMultiTexSubImage1DEXT gl3wMultiTexSubImage1DEXT -#define glMultiTexSubImage2DEXT gl3wMultiTexSubImage2DEXT -#define glMultiTexSubImage3DEXT gl3wMultiTexSubImage3DEXT -#define glNamedBufferData gl3wNamedBufferData -#define glNamedBufferDataEXT gl3wNamedBufferDataEXT -#define glNamedBufferPageCommitmentARB gl3wNamedBufferPageCommitmentARB -#define glNamedBufferPageCommitmentEXT gl3wNamedBufferPageCommitmentEXT -#define glNamedBufferStorage gl3wNamedBufferStorage -#define glNamedBufferStorageEXT gl3wNamedBufferStorageEXT -#define glNamedBufferSubData gl3wNamedBufferSubData -#define glNamedBufferSubDataEXT gl3wNamedBufferSubDataEXT -#define glNamedCopyBufferSubDataEXT gl3wNamedCopyBufferSubDataEXT -#define glNamedFramebufferDrawBuffer gl3wNamedFramebufferDrawBuffer -#define glNamedFramebufferDrawBuffers gl3wNamedFramebufferDrawBuffers -#define glNamedFramebufferParameteri gl3wNamedFramebufferParameteri -#define glNamedFramebufferParameteriEXT gl3wNamedFramebufferParameteriEXT -#define glNamedFramebufferReadBuffer gl3wNamedFramebufferReadBuffer -#define glNamedFramebufferRenderbuffer gl3wNamedFramebufferRenderbuffer -#define glNamedFramebufferRenderbufferEXT gl3wNamedFramebufferRenderbufferEXT -#define glNamedFramebufferSampleLocationsfvARB gl3wNamedFramebufferSampleLocationsfvARB -#define glNamedFramebufferSampleLocationsfvNV gl3wNamedFramebufferSampleLocationsfvNV -#define glNamedFramebufferTexture gl3wNamedFramebufferTexture -#define glNamedFramebufferTexture1DEXT gl3wNamedFramebufferTexture1DEXT -#define glNamedFramebufferTexture2DEXT gl3wNamedFramebufferTexture2DEXT -#define glNamedFramebufferTexture3DEXT gl3wNamedFramebufferTexture3DEXT -#define glNamedFramebufferTextureEXT gl3wNamedFramebufferTextureEXT -#define glNamedFramebufferTextureFaceEXT gl3wNamedFramebufferTextureFaceEXT -#define glNamedFramebufferTextureLayer gl3wNamedFramebufferTextureLayer -#define glNamedFramebufferTextureLayerEXT gl3wNamedFramebufferTextureLayerEXT -#define glNamedProgramLocalParameter4dEXT gl3wNamedProgramLocalParameter4dEXT -#define glNamedProgramLocalParameter4dvEXT gl3wNamedProgramLocalParameter4dvEXT -#define glNamedProgramLocalParameter4fEXT gl3wNamedProgramLocalParameter4fEXT -#define glNamedProgramLocalParameter4fvEXT gl3wNamedProgramLocalParameter4fvEXT -#define glNamedProgramLocalParameterI4iEXT gl3wNamedProgramLocalParameterI4iEXT -#define glNamedProgramLocalParameterI4ivEXT gl3wNamedProgramLocalParameterI4ivEXT -#define glNamedProgramLocalParameterI4uiEXT gl3wNamedProgramLocalParameterI4uiEXT -#define glNamedProgramLocalParameterI4uivEXT gl3wNamedProgramLocalParameterI4uivEXT -#define glNamedProgramLocalParameters4fvEXT gl3wNamedProgramLocalParameters4fvEXT -#define glNamedProgramLocalParametersI4ivEXT gl3wNamedProgramLocalParametersI4ivEXT -#define glNamedProgramLocalParametersI4uivEXT gl3wNamedProgramLocalParametersI4uivEXT -#define glNamedProgramStringEXT gl3wNamedProgramStringEXT -#define glNamedRenderbufferStorage gl3wNamedRenderbufferStorage -#define glNamedRenderbufferStorageEXT gl3wNamedRenderbufferStorageEXT -#define glNamedRenderbufferStorageMultisample gl3wNamedRenderbufferStorageMultisample -#define glNamedRenderbufferStorageMultisampleCoverageEXT gl3wNamedRenderbufferStorageMultisampleCoverageEXT -#define glNamedRenderbufferStorageMultisampleEXT gl3wNamedRenderbufferStorageMultisampleEXT -#define glNamedStringARB gl3wNamedStringARB -#define glNormalFormatNV gl3wNormalFormatNV -#define glObjectLabel gl3wObjectLabel -#define glObjectPtrLabel gl3wObjectPtrLabel -#define glPatchParameterfv gl3wPatchParameterfv -#define glPatchParameteri gl3wPatchParameteri -#define glPathCommandsNV gl3wPathCommandsNV -#define glPathCoordsNV gl3wPathCoordsNV -#define glPathCoverDepthFuncNV gl3wPathCoverDepthFuncNV -#define glPathDashArrayNV gl3wPathDashArrayNV -#define glPathGlyphIndexArrayNV gl3wPathGlyphIndexArrayNV -#define glPathGlyphIndexRangeNV gl3wPathGlyphIndexRangeNV -#define glPathGlyphRangeNV gl3wPathGlyphRangeNV -#define glPathGlyphsNV gl3wPathGlyphsNV -#define glPathMemoryGlyphIndexArrayNV gl3wPathMemoryGlyphIndexArrayNV -#define glPathParameterfNV gl3wPathParameterfNV -#define glPathParameterfvNV gl3wPathParameterfvNV -#define glPathParameteriNV gl3wPathParameteriNV -#define glPathParameterivNV gl3wPathParameterivNV -#define glPathStencilDepthOffsetNV gl3wPathStencilDepthOffsetNV -#define glPathStencilFuncNV gl3wPathStencilFuncNV -#define glPathStringNV gl3wPathStringNV -#define glPathSubCommandsNV gl3wPathSubCommandsNV -#define glPathSubCoordsNV gl3wPathSubCoordsNV -#define glPauseTransformFeedback gl3wPauseTransformFeedback -#define glPixelStoref gl3wPixelStoref -#define glPixelStorei gl3wPixelStorei -#define glPointAlongPathNV gl3wPointAlongPathNV -#define glPointParameterf gl3wPointParameterf -#define glPointParameterfv gl3wPointParameterfv -#define glPointParameteri gl3wPointParameteri -#define glPointParameteriv gl3wPointParameteriv -#define glPointSize gl3wPointSize -#define glPolygonMode gl3wPolygonMode -#define glPolygonOffset gl3wPolygonOffset -#define glPolygonOffsetClamp gl3wPolygonOffsetClamp -#define glPolygonOffsetClampEXT gl3wPolygonOffsetClampEXT -#define glPopDebugGroup gl3wPopDebugGroup -#define glPopGroupMarkerEXT gl3wPopGroupMarkerEXT -#define glPrimitiveBoundingBoxARB gl3wPrimitiveBoundingBoxARB -#define glPrimitiveRestartIndex gl3wPrimitiveRestartIndex -#define glProgramBinary gl3wProgramBinary -#define glProgramParameteri gl3wProgramParameteri -#define glProgramParameteriARB gl3wProgramParameteriARB -#define glProgramPathFragmentInputGenNV gl3wProgramPathFragmentInputGenNV -#define glProgramUniform1d gl3wProgramUniform1d -#define glProgramUniform1dEXT gl3wProgramUniform1dEXT -#define glProgramUniform1dv gl3wProgramUniform1dv -#define glProgramUniform1dvEXT gl3wProgramUniform1dvEXT -#define glProgramUniform1f gl3wProgramUniform1f -#define glProgramUniform1fEXT gl3wProgramUniform1fEXT -#define glProgramUniform1fv gl3wProgramUniform1fv -#define glProgramUniform1fvEXT gl3wProgramUniform1fvEXT -#define glProgramUniform1i gl3wProgramUniform1i -#define glProgramUniform1i64ARB gl3wProgramUniform1i64ARB -#define glProgramUniform1i64NV gl3wProgramUniform1i64NV -#define glProgramUniform1i64vARB gl3wProgramUniform1i64vARB -#define glProgramUniform1i64vNV gl3wProgramUniform1i64vNV -#define glProgramUniform1iEXT gl3wProgramUniform1iEXT -#define glProgramUniform1iv gl3wProgramUniform1iv -#define glProgramUniform1ivEXT gl3wProgramUniform1ivEXT -#define glProgramUniform1ui gl3wProgramUniform1ui -#define glProgramUniform1ui64ARB gl3wProgramUniform1ui64ARB -#define glProgramUniform1ui64NV gl3wProgramUniform1ui64NV -#define glProgramUniform1ui64vARB gl3wProgramUniform1ui64vARB -#define glProgramUniform1ui64vNV gl3wProgramUniform1ui64vNV -#define glProgramUniform1uiEXT gl3wProgramUniform1uiEXT -#define glProgramUniform1uiv gl3wProgramUniform1uiv -#define glProgramUniform1uivEXT gl3wProgramUniform1uivEXT -#define glProgramUniform2d gl3wProgramUniform2d -#define glProgramUniform2dEXT gl3wProgramUniform2dEXT -#define glProgramUniform2dv gl3wProgramUniform2dv -#define glProgramUniform2dvEXT gl3wProgramUniform2dvEXT -#define glProgramUniform2f gl3wProgramUniform2f -#define glProgramUniform2fEXT gl3wProgramUniform2fEXT -#define glProgramUniform2fv gl3wProgramUniform2fv -#define glProgramUniform2fvEXT gl3wProgramUniform2fvEXT -#define glProgramUniform2i gl3wProgramUniform2i -#define glProgramUniform2i64ARB gl3wProgramUniform2i64ARB -#define glProgramUniform2i64NV gl3wProgramUniform2i64NV -#define glProgramUniform2i64vARB gl3wProgramUniform2i64vARB -#define glProgramUniform2i64vNV gl3wProgramUniform2i64vNV -#define glProgramUniform2iEXT gl3wProgramUniform2iEXT -#define glProgramUniform2iv gl3wProgramUniform2iv -#define glProgramUniform2ivEXT gl3wProgramUniform2ivEXT -#define glProgramUniform2ui gl3wProgramUniform2ui -#define glProgramUniform2ui64ARB gl3wProgramUniform2ui64ARB -#define glProgramUniform2ui64NV gl3wProgramUniform2ui64NV -#define glProgramUniform2ui64vARB gl3wProgramUniform2ui64vARB -#define glProgramUniform2ui64vNV gl3wProgramUniform2ui64vNV -#define glProgramUniform2uiEXT gl3wProgramUniform2uiEXT -#define glProgramUniform2uiv gl3wProgramUniform2uiv -#define glProgramUniform2uivEXT gl3wProgramUniform2uivEXT -#define glProgramUniform3d gl3wProgramUniform3d -#define glProgramUniform3dEXT gl3wProgramUniform3dEXT -#define glProgramUniform3dv gl3wProgramUniform3dv -#define glProgramUniform3dvEXT gl3wProgramUniform3dvEXT -#define glProgramUniform3f gl3wProgramUniform3f -#define glProgramUniform3fEXT gl3wProgramUniform3fEXT -#define glProgramUniform3fv gl3wProgramUniform3fv -#define glProgramUniform3fvEXT gl3wProgramUniform3fvEXT -#define glProgramUniform3i gl3wProgramUniform3i -#define glProgramUniform3i64ARB gl3wProgramUniform3i64ARB -#define glProgramUniform3i64NV gl3wProgramUniform3i64NV -#define glProgramUniform3i64vARB gl3wProgramUniform3i64vARB -#define glProgramUniform3i64vNV gl3wProgramUniform3i64vNV -#define glProgramUniform3iEXT gl3wProgramUniform3iEXT -#define glProgramUniform3iv gl3wProgramUniform3iv -#define glProgramUniform3ivEXT gl3wProgramUniform3ivEXT -#define glProgramUniform3ui gl3wProgramUniform3ui -#define glProgramUniform3ui64ARB gl3wProgramUniform3ui64ARB -#define glProgramUniform3ui64NV gl3wProgramUniform3ui64NV -#define glProgramUniform3ui64vARB gl3wProgramUniform3ui64vARB -#define glProgramUniform3ui64vNV gl3wProgramUniform3ui64vNV -#define glProgramUniform3uiEXT gl3wProgramUniform3uiEXT -#define glProgramUniform3uiv gl3wProgramUniform3uiv -#define glProgramUniform3uivEXT gl3wProgramUniform3uivEXT -#define glProgramUniform4d gl3wProgramUniform4d -#define glProgramUniform4dEXT gl3wProgramUniform4dEXT -#define glProgramUniform4dv gl3wProgramUniform4dv -#define glProgramUniform4dvEXT gl3wProgramUniform4dvEXT -#define glProgramUniform4f gl3wProgramUniform4f -#define glProgramUniform4fEXT gl3wProgramUniform4fEXT -#define glProgramUniform4fv gl3wProgramUniform4fv -#define glProgramUniform4fvEXT gl3wProgramUniform4fvEXT -#define glProgramUniform4i gl3wProgramUniform4i -#define glProgramUniform4i64ARB gl3wProgramUniform4i64ARB -#define glProgramUniform4i64NV gl3wProgramUniform4i64NV -#define glProgramUniform4i64vARB gl3wProgramUniform4i64vARB -#define glProgramUniform4i64vNV gl3wProgramUniform4i64vNV -#define glProgramUniform4iEXT gl3wProgramUniform4iEXT -#define glProgramUniform4iv gl3wProgramUniform4iv -#define glProgramUniform4ivEXT gl3wProgramUniform4ivEXT -#define glProgramUniform4ui gl3wProgramUniform4ui -#define glProgramUniform4ui64ARB gl3wProgramUniform4ui64ARB -#define glProgramUniform4ui64NV gl3wProgramUniform4ui64NV -#define glProgramUniform4ui64vARB gl3wProgramUniform4ui64vARB -#define glProgramUniform4ui64vNV gl3wProgramUniform4ui64vNV -#define glProgramUniform4uiEXT gl3wProgramUniform4uiEXT -#define glProgramUniform4uiv gl3wProgramUniform4uiv -#define glProgramUniform4uivEXT gl3wProgramUniform4uivEXT -#define glProgramUniformHandleui64ARB gl3wProgramUniformHandleui64ARB -#define glProgramUniformHandleui64NV gl3wProgramUniformHandleui64NV -#define glProgramUniformHandleui64vARB gl3wProgramUniformHandleui64vARB -#define glProgramUniformHandleui64vNV gl3wProgramUniformHandleui64vNV -#define glProgramUniformMatrix2dv gl3wProgramUniformMatrix2dv -#define glProgramUniformMatrix2dvEXT gl3wProgramUniformMatrix2dvEXT -#define glProgramUniformMatrix2fv gl3wProgramUniformMatrix2fv -#define glProgramUniformMatrix2fvEXT gl3wProgramUniformMatrix2fvEXT -#define glProgramUniformMatrix2x3dv gl3wProgramUniformMatrix2x3dv -#define glProgramUniformMatrix2x3dvEXT gl3wProgramUniformMatrix2x3dvEXT -#define glProgramUniformMatrix2x3fv gl3wProgramUniformMatrix2x3fv -#define glProgramUniformMatrix2x3fvEXT gl3wProgramUniformMatrix2x3fvEXT -#define glProgramUniformMatrix2x4dv gl3wProgramUniformMatrix2x4dv -#define glProgramUniformMatrix2x4dvEXT gl3wProgramUniformMatrix2x4dvEXT -#define glProgramUniformMatrix2x4fv gl3wProgramUniformMatrix2x4fv -#define glProgramUniformMatrix2x4fvEXT gl3wProgramUniformMatrix2x4fvEXT -#define glProgramUniformMatrix3dv gl3wProgramUniformMatrix3dv -#define glProgramUniformMatrix3dvEXT gl3wProgramUniformMatrix3dvEXT -#define glProgramUniformMatrix3fv gl3wProgramUniformMatrix3fv -#define glProgramUniformMatrix3fvEXT gl3wProgramUniformMatrix3fvEXT -#define glProgramUniformMatrix3x2dv gl3wProgramUniformMatrix3x2dv -#define glProgramUniformMatrix3x2dvEXT gl3wProgramUniformMatrix3x2dvEXT -#define glProgramUniformMatrix3x2fv gl3wProgramUniformMatrix3x2fv -#define glProgramUniformMatrix3x2fvEXT gl3wProgramUniformMatrix3x2fvEXT -#define glProgramUniformMatrix3x4dv gl3wProgramUniformMatrix3x4dv -#define glProgramUniformMatrix3x4dvEXT gl3wProgramUniformMatrix3x4dvEXT -#define glProgramUniformMatrix3x4fv gl3wProgramUniformMatrix3x4fv -#define glProgramUniformMatrix3x4fvEXT gl3wProgramUniformMatrix3x4fvEXT -#define glProgramUniformMatrix4dv gl3wProgramUniformMatrix4dv -#define glProgramUniformMatrix4dvEXT gl3wProgramUniformMatrix4dvEXT -#define glProgramUniformMatrix4fv gl3wProgramUniformMatrix4fv -#define glProgramUniformMatrix4fvEXT gl3wProgramUniformMatrix4fvEXT -#define glProgramUniformMatrix4x2dv gl3wProgramUniformMatrix4x2dv -#define glProgramUniformMatrix4x2dvEXT gl3wProgramUniformMatrix4x2dvEXT -#define glProgramUniformMatrix4x2fv gl3wProgramUniformMatrix4x2fv -#define glProgramUniformMatrix4x2fvEXT gl3wProgramUniformMatrix4x2fvEXT -#define glProgramUniformMatrix4x3dv gl3wProgramUniformMatrix4x3dv -#define glProgramUniformMatrix4x3dvEXT gl3wProgramUniformMatrix4x3dvEXT -#define glProgramUniformMatrix4x3fv gl3wProgramUniformMatrix4x3fv -#define glProgramUniformMatrix4x3fvEXT gl3wProgramUniformMatrix4x3fvEXT -#define glProgramUniformui64NV gl3wProgramUniformui64NV -#define glProgramUniformui64vNV gl3wProgramUniformui64vNV -#define glProvokingVertex gl3wProvokingVertex -#define glPushClientAttribDefaultEXT gl3wPushClientAttribDefaultEXT -#define glPushDebugGroup gl3wPushDebugGroup -#define glPushGroupMarkerEXT gl3wPushGroupMarkerEXT -#define glQueryCounter gl3wQueryCounter -#define glRasterSamplesEXT gl3wRasterSamplesEXT -#define glReadBuffer gl3wReadBuffer -#define glReadPixels gl3wReadPixels -#define glReadnPixels gl3wReadnPixels -#define glReadnPixelsARB gl3wReadnPixelsARB -#define glReleaseShaderCompiler gl3wReleaseShaderCompiler -#define glRenderbufferStorage gl3wRenderbufferStorage -#define glRenderbufferStorageMultisample gl3wRenderbufferStorageMultisample -#define glRenderbufferStorageMultisampleCoverageNV gl3wRenderbufferStorageMultisampleCoverageNV -#define glResolveDepthValuesNV gl3wResolveDepthValuesNV -#define glResumeTransformFeedback gl3wResumeTransformFeedback -#define glSampleCoverage gl3wSampleCoverage -#define glSampleMaski gl3wSampleMaski -#define glSamplerParameterIiv gl3wSamplerParameterIiv -#define glSamplerParameterIuiv gl3wSamplerParameterIuiv -#define glSamplerParameterf gl3wSamplerParameterf -#define glSamplerParameterfv gl3wSamplerParameterfv -#define glSamplerParameteri gl3wSamplerParameteri -#define glSamplerParameteriv gl3wSamplerParameteriv -#define glScissor gl3wScissor -#define glScissorArrayv gl3wScissorArrayv -#define glScissorIndexed gl3wScissorIndexed -#define glScissorIndexedv gl3wScissorIndexedv -#define glSecondaryColorFormatNV gl3wSecondaryColorFormatNV -#define glSelectPerfMonitorCountersAMD gl3wSelectPerfMonitorCountersAMD -#define glShaderBinary gl3wShaderBinary -#define glShaderSource gl3wShaderSource -#define glShaderStorageBlockBinding gl3wShaderStorageBlockBinding -#define glSignalVkFenceNV gl3wSignalVkFenceNV -#define glSignalVkSemaphoreNV gl3wSignalVkSemaphoreNV -#define glSpecializeShader gl3wSpecializeShader -#define glSpecializeShaderARB gl3wSpecializeShaderARB -#define glStateCaptureNV gl3wStateCaptureNV -#define glStencilFillPathInstancedNV gl3wStencilFillPathInstancedNV -#define glStencilFillPathNV gl3wStencilFillPathNV -#define glStencilFunc gl3wStencilFunc -#define glStencilFuncSeparate gl3wStencilFuncSeparate -#define glStencilMask gl3wStencilMask -#define glStencilMaskSeparate gl3wStencilMaskSeparate -#define glStencilOp gl3wStencilOp -#define glStencilOpSeparate gl3wStencilOpSeparate -#define glStencilStrokePathInstancedNV gl3wStencilStrokePathInstancedNV -#define glStencilStrokePathNV gl3wStencilStrokePathNV -#define glStencilThenCoverFillPathInstancedNV gl3wStencilThenCoverFillPathInstancedNV -#define glStencilThenCoverFillPathNV gl3wStencilThenCoverFillPathNV -#define glStencilThenCoverStrokePathInstancedNV gl3wStencilThenCoverStrokePathInstancedNV -#define glStencilThenCoverStrokePathNV gl3wStencilThenCoverStrokePathNV -#define glSubpixelPrecisionBiasNV gl3wSubpixelPrecisionBiasNV -#define glTexBuffer gl3wTexBuffer -#define glTexBufferARB gl3wTexBufferARB -#define glTexBufferRange gl3wTexBufferRange -#define glTexCoordFormatNV gl3wTexCoordFormatNV -#define glTexImage1D gl3wTexImage1D -#define glTexImage2D gl3wTexImage2D -#define glTexImage2DMultisample gl3wTexImage2DMultisample -#define glTexImage3D gl3wTexImage3D -#define glTexImage3DMultisample gl3wTexImage3DMultisample -#define glTexPageCommitmentARB gl3wTexPageCommitmentARB -#define glTexParameterIiv gl3wTexParameterIiv -#define glTexParameterIuiv gl3wTexParameterIuiv -#define glTexParameterf gl3wTexParameterf -#define glTexParameterfv gl3wTexParameterfv -#define glTexParameteri gl3wTexParameteri -#define glTexParameteriv gl3wTexParameteriv -#define glTexStorage1D gl3wTexStorage1D -#define glTexStorage2D gl3wTexStorage2D -#define glTexStorage2DMultisample gl3wTexStorage2DMultisample -#define glTexStorage3D gl3wTexStorage3D -#define glTexStorage3DMultisample gl3wTexStorage3DMultisample -#define glTexSubImage1D gl3wTexSubImage1D -#define glTexSubImage2D gl3wTexSubImage2D -#define glTexSubImage3D gl3wTexSubImage3D -#define glTextureBarrier gl3wTextureBarrier -#define glTextureBarrierNV gl3wTextureBarrierNV -#define glTextureBuffer gl3wTextureBuffer -#define glTextureBufferEXT gl3wTextureBufferEXT -#define glTextureBufferRange gl3wTextureBufferRange -#define glTextureBufferRangeEXT gl3wTextureBufferRangeEXT -#define glTextureImage1DEXT gl3wTextureImage1DEXT -#define glTextureImage2DEXT gl3wTextureImage2DEXT -#define glTextureImage3DEXT gl3wTextureImage3DEXT -#define glTexturePageCommitmentEXT gl3wTexturePageCommitmentEXT -#define glTextureParameterIiv gl3wTextureParameterIiv -#define glTextureParameterIivEXT gl3wTextureParameterIivEXT -#define glTextureParameterIuiv gl3wTextureParameterIuiv -#define glTextureParameterIuivEXT gl3wTextureParameterIuivEXT -#define glTextureParameterf gl3wTextureParameterf -#define glTextureParameterfEXT gl3wTextureParameterfEXT -#define glTextureParameterfv gl3wTextureParameterfv -#define glTextureParameterfvEXT gl3wTextureParameterfvEXT -#define glTextureParameteri gl3wTextureParameteri -#define glTextureParameteriEXT gl3wTextureParameteriEXT -#define glTextureParameteriv gl3wTextureParameteriv -#define glTextureParameterivEXT gl3wTextureParameterivEXT -#define glTextureRenderbufferEXT gl3wTextureRenderbufferEXT -#define glTextureStorage1D gl3wTextureStorage1D -#define glTextureStorage1DEXT gl3wTextureStorage1DEXT -#define glTextureStorage2D gl3wTextureStorage2D -#define glTextureStorage2DEXT gl3wTextureStorage2DEXT -#define glTextureStorage2DMultisample gl3wTextureStorage2DMultisample -#define glTextureStorage2DMultisampleEXT gl3wTextureStorage2DMultisampleEXT -#define glTextureStorage3D gl3wTextureStorage3D -#define glTextureStorage3DEXT gl3wTextureStorage3DEXT -#define glTextureStorage3DMultisample gl3wTextureStorage3DMultisample -#define glTextureStorage3DMultisampleEXT gl3wTextureStorage3DMultisampleEXT -#define glTextureSubImage1D gl3wTextureSubImage1D -#define glTextureSubImage1DEXT gl3wTextureSubImage1DEXT -#define glTextureSubImage2D gl3wTextureSubImage2D -#define glTextureSubImage2DEXT gl3wTextureSubImage2DEXT -#define glTextureSubImage3D gl3wTextureSubImage3D -#define glTextureSubImage3DEXT gl3wTextureSubImage3DEXT -#define glTextureView gl3wTextureView -#define glTransformFeedbackBufferBase gl3wTransformFeedbackBufferBase -#define glTransformFeedbackBufferRange gl3wTransformFeedbackBufferRange -#define glTransformFeedbackVaryings gl3wTransformFeedbackVaryings -#define glTransformPathNV gl3wTransformPathNV -#define glUniform1d gl3wUniform1d -#define glUniform1dv gl3wUniform1dv -#define glUniform1f gl3wUniform1f -#define glUniform1fv gl3wUniform1fv -#define glUniform1i gl3wUniform1i -#define glUniform1i64ARB gl3wUniform1i64ARB -#define glUniform1i64NV gl3wUniform1i64NV -#define glUniform1i64vARB gl3wUniform1i64vARB -#define glUniform1i64vNV gl3wUniform1i64vNV -#define glUniform1iv gl3wUniform1iv -#define glUniform1ui gl3wUniform1ui -#define glUniform1ui64ARB gl3wUniform1ui64ARB -#define glUniform1ui64NV gl3wUniform1ui64NV -#define glUniform1ui64vARB gl3wUniform1ui64vARB -#define glUniform1ui64vNV gl3wUniform1ui64vNV -#define glUniform1uiv gl3wUniform1uiv -#define glUniform2d gl3wUniform2d -#define glUniform2dv gl3wUniform2dv -#define glUniform2f gl3wUniform2f -#define glUniform2fv gl3wUniform2fv -#define glUniform2i gl3wUniform2i -#define glUniform2i64ARB gl3wUniform2i64ARB -#define glUniform2i64NV gl3wUniform2i64NV -#define glUniform2i64vARB gl3wUniform2i64vARB -#define glUniform2i64vNV gl3wUniform2i64vNV -#define glUniform2iv gl3wUniform2iv -#define glUniform2ui gl3wUniform2ui -#define glUniform2ui64ARB gl3wUniform2ui64ARB -#define glUniform2ui64NV gl3wUniform2ui64NV -#define glUniform2ui64vARB gl3wUniform2ui64vARB -#define glUniform2ui64vNV gl3wUniform2ui64vNV -#define glUniform2uiv gl3wUniform2uiv -#define glUniform3d gl3wUniform3d -#define glUniform3dv gl3wUniform3dv -#define glUniform3f gl3wUniform3f -#define glUniform3fv gl3wUniform3fv -#define glUniform3i gl3wUniform3i -#define glUniform3i64ARB gl3wUniform3i64ARB -#define glUniform3i64NV gl3wUniform3i64NV -#define glUniform3i64vARB gl3wUniform3i64vARB -#define glUniform3i64vNV gl3wUniform3i64vNV -#define glUniform3iv gl3wUniform3iv -#define glUniform3ui gl3wUniform3ui -#define glUniform3ui64ARB gl3wUniform3ui64ARB -#define glUniform3ui64NV gl3wUniform3ui64NV -#define glUniform3ui64vARB gl3wUniform3ui64vARB -#define glUniform3ui64vNV gl3wUniform3ui64vNV -#define glUniform3uiv gl3wUniform3uiv -#define glUniform4d gl3wUniform4d -#define glUniform4dv gl3wUniform4dv -#define glUniform4f gl3wUniform4f -#define glUniform4fv gl3wUniform4fv -#define glUniform4i gl3wUniform4i -#define glUniform4i64ARB gl3wUniform4i64ARB -#define glUniform4i64NV gl3wUniform4i64NV -#define glUniform4i64vARB gl3wUniform4i64vARB -#define glUniform4i64vNV gl3wUniform4i64vNV -#define glUniform4iv gl3wUniform4iv -#define glUniform4ui gl3wUniform4ui -#define glUniform4ui64ARB gl3wUniform4ui64ARB -#define glUniform4ui64NV gl3wUniform4ui64NV -#define glUniform4ui64vARB gl3wUniform4ui64vARB -#define glUniform4ui64vNV gl3wUniform4ui64vNV -#define glUniform4uiv gl3wUniform4uiv -#define glUniformBlockBinding gl3wUniformBlockBinding -#define glUniformHandleui64ARB gl3wUniformHandleui64ARB -#define glUniformHandleui64NV gl3wUniformHandleui64NV -#define glUniformHandleui64vARB gl3wUniformHandleui64vARB -#define glUniformHandleui64vNV gl3wUniformHandleui64vNV -#define glUniformMatrix2dv gl3wUniformMatrix2dv -#define glUniformMatrix2fv gl3wUniformMatrix2fv -#define glUniformMatrix2x3dv gl3wUniformMatrix2x3dv -#define glUniformMatrix2x3fv gl3wUniformMatrix2x3fv -#define glUniformMatrix2x4dv gl3wUniformMatrix2x4dv -#define glUniformMatrix2x4fv gl3wUniformMatrix2x4fv -#define glUniformMatrix3dv gl3wUniformMatrix3dv -#define glUniformMatrix3fv gl3wUniformMatrix3fv -#define glUniformMatrix3x2dv gl3wUniformMatrix3x2dv -#define glUniformMatrix3x2fv gl3wUniformMatrix3x2fv -#define glUniformMatrix3x4dv gl3wUniformMatrix3x4dv -#define glUniformMatrix3x4fv gl3wUniformMatrix3x4fv -#define glUniformMatrix4dv gl3wUniformMatrix4dv -#define glUniformMatrix4fv gl3wUniformMatrix4fv -#define glUniformMatrix4x2dv gl3wUniformMatrix4x2dv -#define glUniformMatrix4x2fv gl3wUniformMatrix4x2fv -#define glUniformMatrix4x3dv gl3wUniformMatrix4x3dv -#define glUniformMatrix4x3fv gl3wUniformMatrix4x3fv -#define glUniformSubroutinesuiv gl3wUniformSubroutinesuiv -#define glUniformui64NV gl3wUniformui64NV -#define glUniformui64vNV gl3wUniformui64vNV -#define glUnmapBuffer gl3wUnmapBuffer -#define glUnmapNamedBuffer gl3wUnmapNamedBuffer -#define glUnmapNamedBufferEXT gl3wUnmapNamedBufferEXT -#define glUseProgram gl3wUseProgram -#define glUseProgramStages gl3wUseProgramStages -#define glUseShaderProgramEXT gl3wUseShaderProgramEXT -#define glValidateProgram gl3wValidateProgram -#define glValidateProgramPipeline gl3wValidateProgramPipeline -#define glVertexArrayAttribBinding gl3wVertexArrayAttribBinding -#define glVertexArrayAttribFormat gl3wVertexArrayAttribFormat -#define glVertexArrayAttribIFormat gl3wVertexArrayAttribIFormat -#define glVertexArrayAttribLFormat gl3wVertexArrayAttribLFormat -#define glVertexArrayBindVertexBufferEXT gl3wVertexArrayBindVertexBufferEXT -#define glVertexArrayBindingDivisor gl3wVertexArrayBindingDivisor -#define glVertexArrayColorOffsetEXT gl3wVertexArrayColorOffsetEXT -#define glVertexArrayEdgeFlagOffsetEXT gl3wVertexArrayEdgeFlagOffsetEXT -#define glVertexArrayElementBuffer gl3wVertexArrayElementBuffer -#define glVertexArrayFogCoordOffsetEXT gl3wVertexArrayFogCoordOffsetEXT -#define glVertexArrayIndexOffsetEXT gl3wVertexArrayIndexOffsetEXT -#define glVertexArrayMultiTexCoordOffsetEXT gl3wVertexArrayMultiTexCoordOffsetEXT -#define glVertexArrayNormalOffsetEXT gl3wVertexArrayNormalOffsetEXT -#define glVertexArraySecondaryColorOffsetEXT gl3wVertexArraySecondaryColorOffsetEXT -#define glVertexArrayTexCoordOffsetEXT gl3wVertexArrayTexCoordOffsetEXT -#define glVertexArrayVertexAttribBindingEXT gl3wVertexArrayVertexAttribBindingEXT -#define glVertexArrayVertexAttribDivisorEXT gl3wVertexArrayVertexAttribDivisorEXT -#define glVertexArrayVertexAttribFormatEXT gl3wVertexArrayVertexAttribFormatEXT -#define glVertexArrayVertexAttribIFormatEXT gl3wVertexArrayVertexAttribIFormatEXT -#define glVertexArrayVertexAttribIOffsetEXT gl3wVertexArrayVertexAttribIOffsetEXT -#define glVertexArrayVertexAttribLFormatEXT gl3wVertexArrayVertexAttribLFormatEXT -#define glVertexArrayVertexAttribLOffsetEXT gl3wVertexArrayVertexAttribLOffsetEXT -#define glVertexArrayVertexAttribOffsetEXT gl3wVertexArrayVertexAttribOffsetEXT -#define glVertexArrayVertexBindingDivisorEXT gl3wVertexArrayVertexBindingDivisorEXT -#define glVertexArrayVertexBuffer gl3wVertexArrayVertexBuffer -#define glVertexArrayVertexBuffers gl3wVertexArrayVertexBuffers -#define glVertexArrayVertexOffsetEXT gl3wVertexArrayVertexOffsetEXT -#define glVertexAttrib1d gl3wVertexAttrib1d -#define glVertexAttrib1dv gl3wVertexAttrib1dv -#define glVertexAttrib1f gl3wVertexAttrib1f -#define glVertexAttrib1fv gl3wVertexAttrib1fv -#define glVertexAttrib1s gl3wVertexAttrib1s -#define glVertexAttrib1sv gl3wVertexAttrib1sv -#define glVertexAttrib2d gl3wVertexAttrib2d -#define glVertexAttrib2dv gl3wVertexAttrib2dv -#define glVertexAttrib2f gl3wVertexAttrib2f -#define glVertexAttrib2fv gl3wVertexAttrib2fv -#define glVertexAttrib2s gl3wVertexAttrib2s -#define glVertexAttrib2sv gl3wVertexAttrib2sv -#define glVertexAttrib3d gl3wVertexAttrib3d -#define glVertexAttrib3dv gl3wVertexAttrib3dv -#define glVertexAttrib3f gl3wVertexAttrib3f -#define glVertexAttrib3fv gl3wVertexAttrib3fv -#define glVertexAttrib3s gl3wVertexAttrib3s -#define glVertexAttrib3sv gl3wVertexAttrib3sv -#define glVertexAttrib4Nbv gl3wVertexAttrib4Nbv -#define glVertexAttrib4Niv gl3wVertexAttrib4Niv -#define glVertexAttrib4Nsv gl3wVertexAttrib4Nsv -#define glVertexAttrib4Nub gl3wVertexAttrib4Nub -#define glVertexAttrib4Nubv gl3wVertexAttrib4Nubv -#define glVertexAttrib4Nuiv gl3wVertexAttrib4Nuiv -#define glVertexAttrib4Nusv gl3wVertexAttrib4Nusv -#define glVertexAttrib4bv gl3wVertexAttrib4bv -#define glVertexAttrib4d gl3wVertexAttrib4d -#define glVertexAttrib4dv gl3wVertexAttrib4dv -#define glVertexAttrib4f gl3wVertexAttrib4f -#define glVertexAttrib4fv gl3wVertexAttrib4fv -#define glVertexAttrib4iv gl3wVertexAttrib4iv -#define glVertexAttrib4s gl3wVertexAttrib4s -#define glVertexAttrib4sv gl3wVertexAttrib4sv -#define glVertexAttrib4ubv gl3wVertexAttrib4ubv -#define glVertexAttrib4uiv gl3wVertexAttrib4uiv -#define glVertexAttrib4usv gl3wVertexAttrib4usv -#define glVertexAttribBinding gl3wVertexAttribBinding -#define glVertexAttribDivisor gl3wVertexAttribDivisor -#define glVertexAttribDivisorARB gl3wVertexAttribDivisorARB -#define glVertexAttribFormat gl3wVertexAttribFormat -#define glVertexAttribFormatNV gl3wVertexAttribFormatNV -#define glVertexAttribI1i gl3wVertexAttribI1i -#define glVertexAttribI1iv gl3wVertexAttribI1iv -#define glVertexAttribI1ui gl3wVertexAttribI1ui -#define glVertexAttribI1uiv gl3wVertexAttribI1uiv -#define glVertexAttribI2i gl3wVertexAttribI2i -#define glVertexAttribI2iv gl3wVertexAttribI2iv -#define glVertexAttribI2ui gl3wVertexAttribI2ui -#define glVertexAttribI2uiv gl3wVertexAttribI2uiv -#define glVertexAttribI3i gl3wVertexAttribI3i -#define glVertexAttribI3iv gl3wVertexAttribI3iv -#define glVertexAttribI3ui gl3wVertexAttribI3ui -#define glVertexAttribI3uiv gl3wVertexAttribI3uiv -#define glVertexAttribI4bv gl3wVertexAttribI4bv -#define glVertexAttribI4i gl3wVertexAttribI4i -#define glVertexAttribI4iv gl3wVertexAttribI4iv -#define glVertexAttribI4sv gl3wVertexAttribI4sv -#define glVertexAttribI4ubv gl3wVertexAttribI4ubv -#define glVertexAttribI4ui gl3wVertexAttribI4ui -#define glVertexAttribI4uiv gl3wVertexAttribI4uiv -#define glVertexAttribI4usv gl3wVertexAttribI4usv -#define glVertexAttribIFormat gl3wVertexAttribIFormat -#define glVertexAttribIFormatNV gl3wVertexAttribIFormatNV -#define glVertexAttribIPointer gl3wVertexAttribIPointer -#define glVertexAttribL1d gl3wVertexAttribL1d -#define glVertexAttribL1dv gl3wVertexAttribL1dv -#define glVertexAttribL1i64NV gl3wVertexAttribL1i64NV -#define glVertexAttribL1i64vNV gl3wVertexAttribL1i64vNV -#define glVertexAttribL1ui64ARB gl3wVertexAttribL1ui64ARB -#define glVertexAttribL1ui64NV gl3wVertexAttribL1ui64NV -#define glVertexAttribL1ui64vARB gl3wVertexAttribL1ui64vARB -#define glVertexAttribL1ui64vNV gl3wVertexAttribL1ui64vNV -#define glVertexAttribL2d gl3wVertexAttribL2d -#define glVertexAttribL2dv gl3wVertexAttribL2dv -#define glVertexAttribL2i64NV gl3wVertexAttribL2i64NV -#define glVertexAttribL2i64vNV gl3wVertexAttribL2i64vNV -#define glVertexAttribL2ui64NV gl3wVertexAttribL2ui64NV -#define glVertexAttribL2ui64vNV gl3wVertexAttribL2ui64vNV -#define glVertexAttribL3d gl3wVertexAttribL3d -#define glVertexAttribL3dv gl3wVertexAttribL3dv -#define glVertexAttribL3i64NV gl3wVertexAttribL3i64NV -#define glVertexAttribL3i64vNV gl3wVertexAttribL3i64vNV -#define glVertexAttribL3ui64NV gl3wVertexAttribL3ui64NV -#define glVertexAttribL3ui64vNV gl3wVertexAttribL3ui64vNV -#define glVertexAttribL4d gl3wVertexAttribL4d -#define glVertexAttribL4dv gl3wVertexAttribL4dv -#define glVertexAttribL4i64NV gl3wVertexAttribL4i64NV -#define glVertexAttribL4i64vNV gl3wVertexAttribL4i64vNV -#define glVertexAttribL4ui64NV gl3wVertexAttribL4ui64NV -#define glVertexAttribL4ui64vNV gl3wVertexAttribL4ui64vNV -#define glVertexAttribLFormat gl3wVertexAttribLFormat -#define glVertexAttribLFormatNV gl3wVertexAttribLFormatNV -#define glVertexAttribLPointer gl3wVertexAttribLPointer -#define glVertexAttribP1ui gl3wVertexAttribP1ui -#define glVertexAttribP1uiv gl3wVertexAttribP1uiv -#define glVertexAttribP2ui gl3wVertexAttribP2ui -#define glVertexAttribP2uiv gl3wVertexAttribP2uiv -#define glVertexAttribP3ui gl3wVertexAttribP3ui -#define glVertexAttribP3uiv gl3wVertexAttribP3uiv -#define glVertexAttribP4ui gl3wVertexAttribP4ui -#define glVertexAttribP4uiv gl3wVertexAttribP4uiv -#define glVertexAttribPointer gl3wVertexAttribPointer -#define glVertexBindingDivisor gl3wVertexBindingDivisor -#define glVertexFormatNV gl3wVertexFormatNV -#define glViewport gl3wViewport -#define glViewportArrayv gl3wViewportArrayv -#define glViewportIndexedf gl3wViewportIndexedf -#define glViewportIndexedfv gl3wViewportIndexedfv -#define glViewportPositionWScaleNV gl3wViewportPositionWScaleNV -#define glViewportSwizzleNV gl3wViewportSwizzleNV -#define glWaitSync gl3wWaitSync -#define glWaitVkSemaphoreNV gl3wWaitVkSemaphoreNV -#define glWeightPathsNV gl3wWeightPathsNV -#define glWindowRectanglesEXT gl3wWindowRectanglesEXT - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/RenderSystems/GL3Plus/include/GL/glcorearb.h b/RenderSystems/GL3Plus/include/GL/glcorearb.h deleted file mode 100644 index 071b0c56135..00000000000 --- a/RenderSystems/GL3Plus/include/GL/glcorearb.h +++ /dev/null @@ -1,5653 +0,0 @@ -#ifndef __glcorearb_h_ -#define __glcorearb_h_ 1 - -#ifdef __cplusplus -extern "C" { -#endif - -/* -** Copyright (c) 2013-2017 The Khronos Group Inc. -** -** Permission is hereby granted, free of charge, to any person obtaining a -** copy of this software and/or associated documentation files (the -** "Materials"), to deal in the Materials without restriction, including -** without limitation the rights to use, copy, modify, merge, publish, -** distribute, sublicense, and/or sell copies of the Materials, and to -** permit persons to whom the Materials are furnished to do so, subject to -** the following conditions: -** -** The above copyright notice and this permission notice shall be included -** in all copies or substantial portions of the Materials. -** -** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. -*/ -/* -** This header is generated from the Khronos OpenGL / OpenGL ES XML -** API Registry. The current version of the Registry, generator scripts -** used to make the header, and the header can be found at -** https://github.com/KhronosGroup/OpenGL-Registry -*/ - -#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN 1 -#endif -#include -#endif - -#ifndef APIENTRY -#define APIENTRY -#endif -#ifndef APIENTRYP -#define APIENTRYP APIENTRY * -#endif -#ifndef GLAPI -#define GLAPI extern -#endif - -/* glcorearb.h is for use with OpenGL core profile implementations. -** It should should be placed in the same directory as gl.h and -** included as . -** -** glcorearb.h includes only APIs in the latest OpenGL core profile -** implementation together with APIs in newer ARB extensions which -** can be supported by the core profile. It does not, and never will -** include functionality removed from the core profile, such as -** fixed-function vertex and fragment processing. -** -** Do not #include both and either of or -** in the same source file. -*/ - -/* Generated C header for: - * API: gl - * Profile: core - * Versions considered: .* - * Versions emitted: .* - * Default extensions included: glcore - * Additional extensions included: _nomatch_^ - * Extensions removed: _nomatch_^ - */ - -#ifndef GL_VERSION_1_0 -#define GL_VERSION_1_0 1 -typedef void GLvoid; -typedef unsigned int GLenum; -typedef float GLfloat; -typedef int GLint; -typedef int GLsizei; -typedef unsigned int GLbitfield; -typedef double GLdouble; -typedef unsigned int GLuint; -typedef unsigned char GLboolean; -typedef unsigned char GLubyte; -#define GL_DEPTH_BUFFER_BIT 0x00000100 -#define GL_STENCIL_BUFFER_BIT 0x00000400 -#define GL_COLOR_BUFFER_BIT 0x00004000 -#define GL_FALSE 0 -#define GL_TRUE 1 -#define GL_POINTS 0x0000 -#define GL_LINES 0x0001 -#define GL_LINE_LOOP 0x0002 -#define GL_LINE_STRIP 0x0003 -#define GL_TRIANGLES 0x0004 -#define GL_TRIANGLE_STRIP 0x0005 -#define GL_TRIANGLE_FAN 0x0006 -#define GL_QUADS 0x0007 -#define GL_NEVER 0x0200 -#define GL_LESS 0x0201 -#define GL_EQUAL 0x0202 -#define GL_LEQUAL 0x0203 -#define GL_GREATER 0x0204 -#define GL_NOTEQUAL 0x0205 -#define GL_GEQUAL 0x0206 -#define GL_ALWAYS 0x0207 -#define GL_ZERO 0 -#define GL_ONE 1 -#define GL_SRC_COLOR 0x0300 -#define GL_ONE_MINUS_SRC_COLOR 0x0301 -#define GL_SRC_ALPHA 0x0302 -#define GL_ONE_MINUS_SRC_ALPHA 0x0303 -#define GL_DST_ALPHA 0x0304 -#define GL_ONE_MINUS_DST_ALPHA 0x0305 -#define GL_DST_COLOR 0x0306 -#define GL_ONE_MINUS_DST_COLOR 0x0307 -#define GL_SRC_ALPHA_SATURATE 0x0308 -#define GL_NONE 0 -#define GL_FRONT_LEFT 0x0400 -#define GL_FRONT_RIGHT 0x0401 -#define GL_BACK_LEFT 0x0402 -#define GL_BACK_RIGHT 0x0403 -#define GL_FRONT 0x0404 -#define GL_BACK 0x0405 -#define GL_LEFT 0x0406 -#define GL_RIGHT 0x0407 -#define GL_FRONT_AND_BACK 0x0408 -#define GL_NO_ERROR 0 -#define GL_INVALID_ENUM 0x0500 -#define GL_INVALID_VALUE 0x0501 -#define GL_INVALID_OPERATION 0x0502 -#define GL_OUT_OF_MEMORY 0x0505 -#define GL_CW 0x0900 -#define GL_CCW 0x0901 -#define GL_POINT_SIZE 0x0B11 -#define GL_POINT_SIZE_RANGE 0x0B12 -#define GL_POINT_SIZE_GRANULARITY 0x0B13 -#define GL_LINE_SMOOTH 0x0B20 -#define GL_LINE_WIDTH 0x0B21 -#define GL_LINE_WIDTH_RANGE 0x0B22 -#define GL_LINE_WIDTH_GRANULARITY 0x0B23 -#define GL_POLYGON_MODE 0x0B40 -#define GL_POLYGON_SMOOTH 0x0B41 -#define GL_CULL_FACE 0x0B44 -#define GL_CULL_FACE_MODE 0x0B45 -#define GL_FRONT_FACE 0x0B46 -#define GL_DEPTH_RANGE 0x0B70 -#define GL_DEPTH_TEST 0x0B71 -#define GL_DEPTH_WRITEMASK 0x0B72 -#define GL_DEPTH_CLEAR_VALUE 0x0B73 -#define GL_DEPTH_FUNC 0x0B74 -#define GL_STENCIL_TEST 0x0B90 -#define GL_STENCIL_CLEAR_VALUE 0x0B91 -#define GL_STENCIL_FUNC 0x0B92 -#define GL_STENCIL_VALUE_MASK 0x0B93 -#define GL_STENCIL_FAIL 0x0B94 -#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 -#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 -#define GL_STENCIL_REF 0x0B97 -#define GL_STENCIL_WRITEMASK 0x0B98 -#define GL_VIEWPORT 0x0BA2 -#define GL_DITHER 0x0BD0 -#define GL_BLEND_DST 0x0BE0 -#define GL_BLEND_SRC 0x0BE1 -#define GL_BLEND 0x0BE2 -#define GL_LOGIC_OP_MODE 0x0BF0 -#define GL_DRAW_BUFFER 0x0C01 -#define GL_READ_BUFFER 0x0C02 -#define GL_SCISSOR_BOX 0x0C10 -#define GL_SCISSOR_TEST 0x0C11 -#define GL_COLOR_CLEAR_VALUE 0x0C22 -#define GL_COLOR_WRITEMASK 0x0C23 -#define GL_DOUBLEBUFFER 0x0C32 -#define GL_STEREO 0x0C33 -#define GL_LINE_SMOOTH_HINT 0x0C52 -#define GL_POLYGON_SMOOTH_HINT 0x0C53 -#define GL_UNPACK_SWAP_BYTES 0x0CF0 -#define GL_UNPACK_LSB_FIRST 0x0CF1 -#define GL_UNPACK_ROW_LENGTH 0x0CF2 -#define GL_UNPACK_SKIP_ROWS 0x0CF3 -#define GL_UNPACK_SKIP_PIXELS 0x0CF4 -#define GL_UNPACK_ALIGNMENT 0x0CF5 -#define GL_PACK_SWAP_BYTES 0x0D00 -#define GL_PACK_LSB_FIRST 0x0D01 -#define GL_PACK_ROW_LENGTH 0x0D02 -#define GL_PACK_SKIP_ROWS 0x0D03 -#define GL_PACK_SKIP_PIXELS 0x0D04 -#define GL_PACK_ALIGNMENT 0x0D05 -#define GL_MAX_TEXTURE_SIZE 0x0D33 -#define GL_MAX_VIEWPORT_DIMS 0x0D3A -#define GL_SUBPIXEL_BITS 0x0D50 -#define GL_TEXTURE_1D 0x0DE0 -#define GL_TEXTURE_2D 0x0DE1 -#define GL_TEXTURE_WIDTH 0x1000 -#define GL_TEXTURE_HEIGHT 0x1001 -#define GL_TEXTURE_BORDER_COLOR 0x1004 -#define GL_DONT_CARE 0x1100 -#define GL_FASTEST 0x1101 -#define GL_NICEST 0x1102 -#define GL_BYTE 0x1400 -#define GL_UNSIGNED_BYTE 0x1401 -#define GL_SHORT 0x1402 -#define GL_UNSIGNED_SHORT 0x1403 -#define GL_INT 0x1404 -#define GL_UNSIGNED_INT 0x1405 -#define GL_FLOAT 0x1406 -#define GL_STACK_OVERFLOW 0x0503 -#define GL_STACK_UNDERFLOW 0x0504 -#define GL_CLEAR 0x1500 -#define GL_AND 0x1501 -#define GL_AND_REVERSE 0x1502 -#define GL_COPY 0x1503 -#define GL_AND_INVERTED 0x1504 -#define GL_NOOP 0x1505 -#define GL_XOR 0x1506 -#define GL_OR 0x1507 -#define GL_NOR 0x1508 -#define GL_EQUIV 0x1509 -#define GL_INVERT 0x150A -#define GL_OR_REVERSE 0x150B -#define GL_COPY_INVERTED 0x150C -#define GL_OR_INVERTED 0x150D -#define GL_NAND 0x150E -#define GL_SET 0x150F -#define GL_TEXTURE 0x1702 -#define GL_COLOR 0x1800 -#define GL_DEPTH 0x1801 -#define GL_STENCIL 0x1802 -#define GL_STENCIL_INDEX 0x1901 -#define GL_DEPTH_COMPONENT 0x1902 -#define GL_RED 0x1903 -#define GL_GREEN 0x1904 -#define GL_BLUE 0x1905 -#define GL_ALPHA 0x1906 -#define GL_RGB 0x1907 -#define GL_RGBA 0x1908 -#define GL_POINT 0x1B00 -#define GL_LINE 0x1B01 -#define GL_FILL 0x1B02 -#define GL_KEEP 0x1E00 -#define GL_REPLACE 0x1E01 -#define GL_INCR 0x1E02 -#define GL_DECR 0x1E03 -#define GL_VENDOR 0x1F00 -#define GL_RENDERER 0x1F01 -#define GL_VERSION 0x1F02 -#define GL_EXTENSIONS 0x1F03 -#define GL_NEAREST 0x2600 -#define GL_LINEAR 0x2601 -#define GL_NEAREST_MIPMAP_NEAREST 0x2700 -#define GL_LINEAR_MIPMAP_NEAREST 0x2701 -#define GL_NEAREST_MIPMAP_LINEAR 0x2702 -#define GL_LINEAR_MIPMAP_LINEAR 0x2703 -#define GL_TEXTURE_MAG_FILTER 0x2800 -#define GL_TEXTURE_MIN_FILTER 0x2801 -#define GL_TEXTURE_WRAP_S 0x2802 -#define GL_TEXTURE_WRAP_T 0x2803 -#define GL_REPEAT 0x2901 -typedef void (APIENTRYP PFNGLCULLFACEPROC) (GLenum mode); -typedef void (APIENTRYP PFNGLFRONTFACEPROC) (GLenum mode); -typedef void (APIENTRYP PFNGLHINTPROC) (GLenum target, GLenum mode); -typedef void (APIENTRYP PFNGLLINEWIDTHPROC) (GLfloat width); -typedef void (APIENTRYP PFNGLPOINTSIZEPROC) (GLfloat size); -typedef void (APIENTRYP PFNGLPOLYGONMODEPROC) (GLenum face, GLenum mode); -typedef void (APIENTRYP PFNGLSCISSORPROC) (GLint x, GLint y, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLTEXPARAMETERFPROC) (GLenum target, GLenum pname, GLfloat param); -typedef void (APIENTRYP PFNGLTEXPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params); -typedef void (APIENTRYP PFNGLTEXPARAMETERIPROC) (GLenum target, GLenum pname, GLint param); -typedef void (APIENTRYP PFNGLTEXPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params); -typedef void (APIENTRYP PFNGLTEXIMAGE1DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLTEXIMAGE2DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLDRAWBUFFERPROC) (GLenum buf); -typedef void (APIENTRYP PFNGLCLEARPROC) (GLbitfield mask); -typedef void (APIENTRYP PFNGLCLEARCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); -typedef void (APIENTRYP PFNGLCLEARSTENCILPROC) (GLint s); -typedef void (APIENTRYP PFNGLCLEARDEPTHPROC) (GLdouble depth); -typedef void (APIENTRYP PFNGLSTENCILMASKPROC) (GLuint mask); -typedef void (APIENTRYP PFNGLCOLORMASKPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); -typedef void (APIENTRYP PFNGLDEPTHMASKPROC) (GLboolean flag); -typedef void (APIENTRYP PFNGLDISABLEPROC) (GLenum cap); -typedef void (APIENTRYP PFNGLENABLEPROC) (GLenum cap); -typedef void (APIENTRYP PFNGLFINISHPROC) (void); -typedef void (APIENTRYP PFNGLFLUSHPROC) (void); -typedef void (APIENTRYP PFNGLBLENDFUNCPROC) (GLenum sfactor, GLenum dfactor); -typedef void (APIENTRYP PFNGLLOGICOPPROC) (GLenum opcode); -typedef void (APIENTRYP PFNGLSTENCILFUNCPROC) (GLenum func, GLint ref, GLuint mask); -typedef void (APIENTRYP PFNGLSTENCILOPPROC) (GLenum fail, GLenum zfail, GLenum zpass); -typedef void (APIENTRYP PFNGLDEPTHFUNCPROC) (GLenum func); -typedef void (APIENTRYP PFNGLPIXELSTOREFPROC) (GLenum pname, GLfloat param); -typedef void (APIENTRYP PFNGLPIXELSTOREIPROC) (GLenum pname, GLint param); -typedef void (APIENTRYP PFNGLREADBUFFERPROC) (GLenum src); -typedef void (APIENTRYP PFNGLREADPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); -typedef void (APIENTRYP PFNGLGETBOOLEANVPROC) (GLenum pname, GLboolean *data); -typedef void (APIENTRYP PFNGLGETDOUBLEVPROC) (GLenum pname, GLdouble *data); -typedef GLenum (APIENTRYP PFNGLGETERRORPROC) (void); -typedef void (APIENTRYP PFNGLGETFLOATVPROC) (GLenum pname, GLfloat *data); -typedef void (APIENTRYP PFNGLGETINTEGERVPROC) (GLenum pname, GLint *data); -typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGPROC) (GLenum name); -typedef void (APIENTRYP PFNGLGETTEXIMAGEPROC) (GLenum target, GLint level, GLenum format, GLenum type, void *pixels); -typedef void (APIENTRYP PFNGLGETTEXPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); -typedef void (APIENTRYP PFNGLGETTEXPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERFVPROC) (GLenum target, GLint level, GLenum pname, GLfloat *params); -typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERIVPROC) (GLenum target, GLint level, GLenum pname, GLint *params); -typedef GLboolean (APIENTRYP PFNGLISENABLEDPROC) (GLenum cap); -typedef void (APIENTRYP PFNGLDEPTHRANGEPROC) (GLdouble near, GLdouble far); -typedef void (APIENTRYP PFNGLVIEWPORTPROC) (GLint x, GLint y, GLsizei width, GLsizei height); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glCullFace (GLenum mode); -GLAPI void APIENTRY glFrontFace (GLenum mode); -GLAPI void APIENTRY glHint (GLenum target, GLenum mode); -GLAPI void APIENTRY glLineWidth (GLfloat width); -GLAPI void APIENTRY glPointSize (GLfloat size); -GLAPI void APIENTRY glPolygonMode (GLenum face, GLenum mode); -GLAPI void APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height); -GLAPI void APIENTRY glTexParameterf (GLenum target, GLenum pname, GLfloat param); -GLAPI void APIENTRY glTexParameterfv (GLenum target, GLenum pname, const GLfloat *params); -GLAPI void APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param); -GLAPI void APIENTRY glTexParameteriv (GLenum target, GLenum pname, const GLint *params); -GLAPI void APIENTRY glTexImage1D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glDrawBuffer (GLenum buf); -GLAPI void APIENTRY glClear (GLbitfield mask); -GLAPI void APIENTRY glClearColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); -GLAPI void APIENTRY glClearStencil (GLint s); -GLAPI void APIENTRY glClearDepth (GLdouble depth); -GLAPI void APIENTRY glStencilMask (GLuint mask); -GLAPI void APIENTRY glColorMask (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); -GLAPI void APIENTRY glDepthMask (GLboolean flag); -GLAPI void APIENTRY glDisable (GLenum cap); -GLAPI void APIENTRY glEnable (GLenum cap); -GLAPI void APIENTRY glFinish (void); -GLAPI void APIENTRY glFlush (void); -GLAPI void APIENTRY glBlendFunc (GLenum sfactor, GLenum dfactor); -GLAPI void APIENTRY glLogicOp (GLenum opcode); -GLAPI void APIENTRY glStencilFunc (GLenum func, GLint ref, GLuint mask); -GLAPI void APIENTRY glStencilOp (GLenum fail, GLenum zfail, GLenum zpass); -GLAPI void APIENTRY glDepthFunc (GLenum func); -GLAPI void APIENTRY glPixelStoref (GLenum pname, GLfloat param); -GLAPI void APIENTRY glPixelStorei (GLenum pname, GLint param); -GLAPI void APIENTRY glReadBuffer (GLenum src); -GLAPI void APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); -GLAPI void APIENTRY glGetBooleanv (GLenum pname, GLboolean *data); -GLAPI void APIENTRY glGetDoublev (GLenum pname, GLdouble *data); -GLAPI GLenum APIENTRY glGetError (void); -GLAPI void APIENTRY glGetFloatv (GLenum pname, GLfloat *data); -GLAPI void APIENTRY glGetIntegerv (GLenum pname, GLint *data); -GLAPI const GLubyte *APIENTRY glGetString (GLenum name); -GLAPI void APIENTRY glGetTexImage (GLenum target, GLint level, GLenum format, GLenum type, void *pixels); -GLAPI void APIENTRY glGetTexParameterfv (GLenum target, GLenum pname, GLfloat *params); -GLAPI void APIENTRY glGetTexParameteriv (GLenum target, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetTexLevelParameterfv (GLenum target, GLint level, GLenum pname, GLfloat *params); -GLAPI void APIENTRY glGetTexLevelParameteriv (GLenum target, GLint level, GLenum pname, GLint *params); -GLAPI GLboolean APIENTRY glIsEnabled (GLenum cap); -GLAPI void APIENTRY glDepthRange (GLdouble near, GLdouble far); -GLAPI void APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height); -#endif -#endif /* GL_VERSION_1_0 */ - -#ifndef GL_VERSION_1_1 -#define GL_VERSION_1_1 1 -typedef float GLclampf; -typedef double GLclampd; -#define GL_COLOR_LOGIC_OP 0x0BF2 -#define GL_POLYGON_OFFSET_UNITS 0x2A00 -#define GL_POLYGON_OFFSET_POINT 0x2A01 -#define GL_POLYGON_OFFSET_LINE 0x2A02 -#define GL_POLYGON_OFFSET_FILL 0x8037 -#define GL_POLYGON_OFFSET_FACTOR 0x8038 -#define GL_TEXTURE_BINDING_1D 0x8068 -#define GL_TEXTURE_BINDING_2D 0x8069 -#define GL_TEXTURE_INTERNAL_FORMAT 0x1003 -#define GL_TEXTURE_RED_SIZE 0x805C -#define GL_TEXTURE_GREEN_SIZE 0x805D -#define GL_TEXTURE_BLUE_SIZE 0x805E -#define GL_TEXTURE_ALPHA_SIZE 0x805F -#define GL_DOUBLE 0x140A -#define GL_PROXY_TEXTURE_1D 0x8063 -#define GL_PROXY_TEXTURE_2D 0x8064 -#define GL_R3_G3_B2 0x2A10 -#define GL_RGB4 0x804F -#define GL_RGB5 0x8050 -#define GL_RGB8 0x8051 -#define GL_RGB10 0x8052 -#define GL_RGB12 0x8053 -#define GL_RGB16 0x8054 -#define GL_RGBA2 0x8055 -#define GL_RGBA4 0x8056 -#define GL_RGB5_A1 0x8057 -#define GL_RGBA8 0x8058 -#define GL_RGB10_A2 0x8059 -#define GL_RGBA12 0x805A -#define GL_RGBA16 0x805B -#define GL_VERTEX_ARRAY 0x8074 -typedef void (APIENTRYP PFNGLDRAWARRAYSPROC) (GLenum mode, GLint first, GLsizei count); -typedef void (APIENTRYP PFNGLDRAWELEMENTSPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices); -typedef void (APIENTRYP PFNGLGETPOINTERVPROC) (GLenum pname, void **params); -typedef void (APIENTRYP PFNGLPOLYGONOFFSETPROC) (GLfloat factor, GLfloat units); -typedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); -typedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); -typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); -typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLBINDTEXTUREPROC) (GLenum target, GLuint texture); -typedef void (APIENTRYP PFNGLDELETETEXTURESPROC) (GLsizei n, const GLuint *textures); -typedef void (APIENTRYP PFNGLGENTEXTURESPROC) (GLsizei n, GLuint *textures); -typedef GLboolean (APIENTRYP PFNGLISTEXTUREPROC) (GLuint texture); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glDrawArrays (GLenum mode, GLint first, GLsizei count); -GLAPI void APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const void *indices); -GLAPI void APIENTRY glGetPointerv (GLenum pname, void **params); -GLAPI void APIENTRY glPolygonOffset (GLfloat factor, GLfloat units); -GLAPI void APIENTRY glCopyTexImage1D (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); -GLAPI void APIENTRY glCopyTexImage2D (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); -GLAPI void APIENTRY glCopyTexSubImage1D (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); -GLAPI void APIENTRY glCopyTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); -GLAPI void APIENTRY glTexSubImage1D (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glBindTexture (GLenum target, GLuint texture); -GLAPI void APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures); -GLAPI void APIENTRY glGenTextures (GLsizei n, GLuint *textures); -GLAPI GLboolean APIENTRY glIsTexture (GLuint texture); -#endif -#endif /* GL_VERSION_1_1 */ - -#ifndef GL_VERSION_1_2 -#define GL_VERSION_1_2 1 -#define GL_UNSIGNED_BYTE_3_3_2 0x8032 -#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 -#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 -#define GL_UNSIGNED_INT_8_8_8_8 0x8035 -#define GL_UNSIGNED_INT_10_10_10_2 0x8036 -#define GL_TEXTURE_BINDING_3D 0x806A -#define GL_PACK_SKIP_IMAGES 0x806B -#define GL_PACK_IMAGE_HEIGHT 0x806C -#define GL_UNPACK_SKIP_IMAGES 0x806D -#define GL_UNPACK_IMAGE_HEIGHT 0x806E -#define GL_TEXTURE_3D 0x806F -#define GL_PROXY_TEXTURE_3D 0x8070 -#define GL_TEXTURE_DEPTH 0x8071 -#define GL_TEXTURE_WRAP_R 0x8072 -#define GL_MAX_3D_TEXTURE_SIZE 0x8073 -#define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 -#define GL_UNSIGNED_SHORT_5_6_5 0x8363 -#define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 -#define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 -#define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 -#define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 -#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 -#define GL_BGR 0x80E0 -#define GL_BGRA 0x80E1 -#define GL_MAX_ELEMENTS_VERTICES 0x80E8 -#define GL_MAX_ELEMENTS_INDICES 0x80E9 -#define GL_CLAMP_TO_EDGE 0x812F -#define GL_TEXTURE_MIN_LOD 0x813A -#define GL_TEXTURE_MAX_LOD 0x813B -#define GL_TEXTURE_BASE_LEVEL 0x813C -#define GL_TEXTURE_MAX_LEVEL 0x813D -#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 -#define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 -#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 -#define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23 -#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E -typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); -typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glDrawRangeElements (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); -GLAPI void APIENTRY glTexImage3D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glCopyTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); -#endif -#endif /* GL_VERSION_1_2 */ - -#ifndef GL_VERSION_1_3 -#define GL_VERSION_1_3 1 -#define GL_TEXTURE0 0x84C0 -#define GL_TEXTURE1 0x84C1 -#define GL_TEXTURE2 0x84C2 -#define GL_TEXTURE3 0x84C3 -#define GL_TEXTURE4 0x84C4 -#define GL_TEXTURE5 0x84C5 -#define GL_TEXTURE6 0x84C6 -#define GL_TEXTURE7 0x84C7 -#define GL_TEXTURE8 0x84C8 -#define GL_TEXTURE9 0x84C9 -#define GL_TEXTURE10 0x84CA -#define GL_TEXTURE11 0x84CB -#define GL_TEXTURE12 0x84CC -#define GL_TEXTURE13 0x84CD -#define GL_TEXTURE14 0x84CE -#define GL_TEXTURE15 0x84CF -#define GL_TEXTURE16 0x84D0 -#define GL_TEXTURE17 0x84D1 -#define GL_TEXTURE18 0x84D2 -#define GL_TEXTURE19 0x84D3 -#define GL_TEXTURE20 0x84D4 -#define GL_TEXTURE21 0x84D5 -#define GL_TEXTURE22 0x84D6 -#define GL_TEXTURE23 0x84D7 -#define GL_TEXTURE24 0x84D8 -#define GL_TEXTURE25 0x84D9 -#define GL_TEXTURE26 0x84DA -#define GL_TEXTURE27 0x84DB -#define GL_TEXTURE28 0x84DC -#define GL_TEXTURE29 0x84DD -#define GL_TEXTURE30 0x84DE -#define GL_TEXTURE31 0x84DF -#define GL_ACTIVE_TEXTURE 0x84E0 -#define GL_MULTISAMPLE 0x809D -#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E -#define GL_SAMPLE_ALPHA_TO_ONE 0x809F -#define GL_SAMPLE_COVERAGE 0x80A0 -#define GL_SAMPLE_BUFFERS 0x80A8 -#define GL_SAMPLES 0x80A9 -#define GL_SAMPLE_COVERAGE_VALUE 0x80AA -#define GL_SAMPLE_COVERAGE_INVERT 0x80AB -#define GL_TEXTURE_CUBE_MAP 0x8513 -#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A -#define GL_PROXY_TEXTURE_CUBE_MAP 0x851B -#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C -#define GL_COMPRESSED_RGB 0x84ED -#define GL_COMPRESSED_RGBA 0x84EE -#define GL_TEXTURE_COMPRESSION_HINT 0x84EF -#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0 -#define GL_TEXTURE_COMPRESSED 0x86A1 -#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 -#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 -#define GL_CLAMP_TO_BORDER 0x812D -typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture); -typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLfloat value, GLboolean invert); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); -typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint level, void *img); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glActiveTexture (GLenum texture); -GLAPI void APIENTRY glSampleCoverage (GLfloat value, GLboolean invert); -GLAPI void APIENTRY glCompressedTexImage3D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); -GLAPI void APIENTRY glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); -GLAPI void APIENTRY glCompressedTexImage1D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); -GLAPI void APIENTRY glCompressedTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); -GLAPI void APIENTRY glCompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); -GLAPI void APIENTRY glCompressedTexSubImage1D (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); -GLAPI void APIENTRY glGetCompressedTexImage (GLenum target, GLint level, void *img); -#endif -#endif /* GL_VERSION_1_3 */ - -#ifndef GL_VERSION_1_4 -#define GL_VERSION_1_4 1 -#define GL_BLEND_DST_RGB 0x80C8 -#define GL_BLEND_SRC_RGB 0x80C9 -#define GL_BLEND_DST_ALPHA 0x80CA -#define GL_BLEND_SRC_ALPHA 0x80CB -#define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 -#define GL_DEPTH_COMPONENT16 0x81A5 -#define GL_DEPTH_COMPONENT24 0x81A6 -#define GL_DEPTH_COMPONENT32 0x81A7 -#define GL_MIRRORED_REPEAT 0x8370 -#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD -#define GL_TEXTURE_LOD_BIAS 0x8501 -#define GL_INCR_WRAP 0x8507 -#define GL_DECR_WRAP 0x8508 -#define GL_TEXTURE_DEPTH_SIZE 0x884A -#define GL_TEXTURE_COMPARE_MODE 0x884C -#define GL_TEXTURE_COMPARE_FUNC 0x884D -#define GL_FUNC_ADD 0x8006 -#define GL_FUNC_SUBTRACT 0x800A -#define GL_FUNC_REVERSE_SUBTRACT 0x800B -#define GL_MIN 0x8007 -#define GL_MAX 0x8008 -#define GL_CONSTANT_COLOR 0x8001 -#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 -#define GL_CONSTANT_ALPHA 0x8003 -#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 -typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); -typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei drawcount); -typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount); -typedef void (APIENTRYP PFNGLPOINTPARAMETERFPROC) (GLenum pname, GLfloat param); -typedef void (APIENTRYP PFNGLPOINTPARAMETERFVPROC) (GLenum pname, const GLfloat *params); -typedef void (APIENTRYP PFNGLPOINTPARAMETERIPROC) (GLenum pname, GLint param); -typedef void (APIENTRYP PFNGLPOINTPARAMETERIVPROC) (GLenum pname, const GLint *params); -typedef void (APIENTRYP PFNGLBLENDCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); -typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); -GLAPI void APIENTRY glMultiDrawArrays (GLenum mode, const GLint *first, const GLsizei *count, GLsizei drawcount); -GLAPI void APIENTRY glMultiDrawElements (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount); -GLAPI void APIENTRY glPointParameterf (GLenum pname, GLfloat param); -GLAPI void APIENTRY glPointParameterfv (GLenum pname, const GLfloat *params); -GLAPI void APIENTRY glPointParameteri (GLenum pname, GLint param); -GLAPI void APIENTRY glPointParameteriv (GLenum pname, const GLint *params); -GLAPI void APIENTRY glBlendColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); -GLAPI void APIENTRY glBlendEquation (GLenum mode); -#endif -#endif /* GL_VERSION_1_4 */ - -#ifndef GL_VERSION_1_5 -#define GL_VERSION_1_5 1 -#include -typedef ptrdiff_t GLsizeiptr; -typedef ptrdiff_t GLintptr; -#define GL_BUFFER_SIZE 0x8764 -#define GL_BUFFER_USAGE 0x8765 -#define GL_QUERY_COUNTER_BITS 0x8864 -#define GL_CURRENT_QUERY 0x8865 -#define GL_QUERY_RESULT 0x8866 -#define GL_QUERY_RESULT_AVAILABLE 0x8867 -#define GL_ARRAY_BUFFER 0x8892 -#define GL_ELEMENT_ARRAY_BUFFER 0x8893 -#define GL_ARRAY_BUFFER_BINDING 0x8894 -#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 -#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F -#define GL_READ_ONLY 0x88B8 -#define GL_WRITE_ONLY 0x88B9 -#define GL_READ_WRITE 0x88BA -#define GL_BUFFER_ACCESS 0x88BB -#define GL_BUFFER_MAPPED 0x88BC -#define GL_BUFFER_MAP_POINTER 0x88BD -#define GL_STREAM_DRAW 0x88E0 -#define GL_STREAM_READ 0x88E1 -#define GL_STREAM_COPY 0x88E2 -#define GL_STATIC_DRAW 0x88E4 -#define GL_STATIC_READ 0x88E5 -#define GL_STATIC_COPY 0x88E6 -#define GL_DYNAMIC_DRAW 0x88E8 -#define GL_DYNAMIC_READ 0x88E9 -#define GL_DYNAMIC_COPY 0x88EA -#define GL_SAMPLES_PASSED 0x8914 -#define GL_SRC1_ALPHA 0x8589 -typedef void (APIENTRYP PFNGLGENQUERIESPROC) (GLsizei n, GLuint *ids); -typedef void (APIENTRYP PFNGLDELETEQUERIESPROC) (GLsizei n, const GLuint *ids); -typedef GLboolean (APIENTRYP PFNGLISQUERYPROC) (GLuint id); -typedef void (APIENTRYP PFNGLBEGINQUERYPROC) (GLenum target, GLuint id); -typedef void (APIENTRYP PFNGLENDQUERYPROC) (GLenum target); -typedef void (APIENTRYP PFNGLGETQUERYIVPROC) (GLenum target, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC) (GLuint id, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC) (GLuint id, GLenum pname, GLuint *params); -typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer); -typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers); -typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers); -typedef GLboolean (APIENTRYP PFNGLISBUFFERPROC) (GLuint buffer); -typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage); -typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); -typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, void *data); -typedef void *(APIENTRYP PFNGLMAPBUFFERPROC) (GLenum target, GLenum access); -typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC) (GLenum target); -typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC) (GLenum target, GLenum pname, void **params); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glGenQueries (GLsizei n, GLuint *ids); -GLAPI void APIENTRY glDeleteQueries (GLsizei n, const GLuint *ids); -GLAPI GLboolean APIENTRY glIsQuery (GLuint id); -GLAPI void APIENTRY glBeginQuery (GLenum target, GLuint id); -GLAPI void APIENTRY glEndQuery (GLenum target); -GLAPI void APIENTRY glGetQueryiv (GLenum target, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetQueryObjectiv (GLuint id, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetQueryObjectuiv (GLuint id, GLenum pname, GLuint *params); -GLAPI void APIENTRY glBindBuffer (GLenum target, GLuint buffer); -GLAPI void APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers); -GLAPI void APIENTRY glGenBuffers (GLsizei n, GLuint *buffers); -GLAPI GLboolean APIENTRY glIsBuffer (GLuint buffer); -GLAPI void APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void *data, GLenum usage); -GLAPI void APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); -GLAPI void APIENTRY glGetBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, void *data); -GLAPI void *APIENTRY glMapBuffer (GLenum target, GLenum access); -GLAPI GLboolean APIENTRY glUnmapBuffer (GLenum target); -GLAPI void APIENTRY glGetBufferParameteriv (GLenum target, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetBufferPointerv (GLenum target, GLenum pname, void **params); -#endif -#endif /* GL_VERSION_1_5 */ - -#ifndef GL_VERSION_2_0 -#define GL_VERSION_2_0 1 -typedef char GLchar; -typedef short GLshort; -typedef signed char GLbyte; -typedef unsigned short GLushort; -#define GL_BLEND_EQUATION_RGB 0x8009 -#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 -#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 -#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 -#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 -#define GL_CURRENT_VERTEX_ATTRIB 0x8626 -#define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642 -#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 -#define GL_STENCIL_BACK_FUNC 0x8800 -#define GL_STENCIL_BACK_FAIL 0x8801 -#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 -#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 -#define GL_MAX_DRAW_BUFFERS 0x8824 -#define GL_DRAW_BUFFER0 0x8825 -#define GL_DRAW_BUFFER1 0x8826 -#define GL_DRAW_BUFFER2 0x8827 -#define GL_DRAW_BUFFER3 0x8828 -#define GL_DRAW_BUFFER4 0x8829 -#define GL_DRAW_BUFFER5 0x882A -#define GL_DRAW_BUFFER6 0x882B -#define GL_DRAW_BUFFER7 0x882C -#define GL_DRAW_BUFFER8 0x882D -#define GL_DRAW_BUFFER9 0x882E -#define GL_DRAW_BUFFER10 0x882F -#define GL_DRAW_BUFFER11 0x8830 -#define GL_DRAW_BUFFER12 0x8831 -#define GL_DRAW_BUFFER13 0x8832 -#define GL_DRAW_BUFFER14 0x8833 -#define GL_DRAW_BUFFER15 0x8834 -#define GL_BLEND_EQUATION_ALPHA 0x883D -#define GL_MAX_VERTEX_ATTRIBS 0x8869 -#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A -#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 -#define GL_FRAGMENT_SHADER 0x8B30 -#define GL_VERTEX_SHADER 0x8B31 -#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 -#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A -#define GL_MAX_VARYING_FLOATS 0x8B4B -#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C -#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D -#define GL_SHADER_TYPE 0x8B4F -#define GL_FLOAT_VEC2 0x8B50 -#define GL_FLOAT_VEC3 0x8B51 -#define GL_FLOAT_VEC4 0x8B52 -#define GL_INT_VEC2 0x8B53 -#define GL_INT_VEC3 0x8B54 -#define GL_INT_VEC4 0x8B55 -#define GL_BOOL 0x8B56 -#define GL_BOOL_VEC2 0x8B57 -#define GL_BOOL_VEC3 0x8B58 -#define GL_BOOL_VEC4 0x8B59 -#define GL_FLOAT_MAT2 0x8B5A -#define GL_FLOAT_MAT3 0x8B5B -#define GL_FLOAT_MAT4 0x8B5C -#define GL_SAMPLER_1D 0x8B5D -#define GL_SAMPLER_2D 0x8B5E -#define GL_SAMPLER_3D 0x8B5F -#define GL_SAMPLER_CUBE 0x8B60 -#define GL_SAMPLER_1D_SHADOW 0x8B61 -#define GL_SAMPLER_2D_SHADOW 0x8B62 -#define GL_DELETE_STATUS 0x8B80 -#define GL_COMPILE_STATUS 0x8B81 -#define GL_LINK_STATUS 0x8B82 -#define GL_VALIDATE_STATUS 0x8B83 -#define GL_INFO_LOG_LENGTH 0x8B84 -#define GL_ATTACHED_SHADERS 0x8B85 -#define GL_ACTIVE_UNIFORMS 0x8B86 -#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 -#define GL_SHADER_SOURCE_LENGTH 0x8B88 -#define GL_ACTIVE_ATTRIBUTES 0x8B89 -#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A -#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B -#define GL_SHADING_LANGUAGE_VERSION 0x8B8C -#define GL_CURRENT_PROGRAM 0x8B8D -#define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0 -#define GL_LOWER_LEFT 0x8CA1 -#define GL_UPPER_LEFT 0x8CA2 -#define GL_STENCIL_BACK_REF 0x8CA3 -#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 -#define GL_STENCIL_BACK_WRITEMASK 0x8CA5 -typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha); -typedef void (APIENTRYP PFNGLDRAWBUFFERSPROC) (GLsizei n, const GLenum *bufs); -typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); -typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC) (GLenum face, GLenum func, GLint ref, GLuint mask); -typedef void (APIENTRYP PFNGLSTENCILMASKSEPARATEPROC) (GLenum face, GLuint mask); -typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader); -typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONPROC) (GLuint program, GLuint index, const GLchar *name); -typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader); -typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void); -typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type); -typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program); -typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader); -typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader); -typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index); -typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index); -typedef void (APIENTRYP PFNGLGETACTIVEATTRIBPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); -typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); -typedef void (APIENTRYP PFNGLGETATTACHEDSHADERSPROC) (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); -typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name); -typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); -typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); -typedef void (APIENTRYP PFNGLGETSHADERSOURCEPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); -typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name); -typedef void (APIENTRYP PFNGLGETUNIFORMFVPROC) (GLuint program, GLint location, GLfloat *params); -typedef void (APIENTRYP PFNGLGETUNIFORMIVPROC) (GLuint program, GLint location, GLint *params); -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVPROC) (GLuint index, GLenum pname, GLdouble *params); -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVPROC) (GLuint index, GLenum pname, GLfloat *params); -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer); -typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program); -typedef GLboolean (APIENTRYP PFNGLISSHADERPROC) (GLuint shader); -typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program); -typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); -typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program); -typedef void (APIENTRYP PFNGLUNIFORM1FPROC) (GLint location, GLfloat v0); -typedef void (APIENTRYP PFNGLUNIFORM2FPROC) (GLint location, GLfloat v0, GLfloat v1); -typedef void (APIENTRYP PFNGLUNIFORM3FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); -typedef void (APIENTRYP PFNGLUNIFORM4FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); -typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0); -typedef void (APIENTRYP PFNGLUNIFORM2IPROC) (GLint location, GLint v0, GLint v1); -typedef void (APIENTRYP PFNGLUNIFORM3IPROC) (GLint location, GLint v0, GLint v1, GLint v2); -typedef void (APIENTRYP PFNGLUNIFORM4IPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); -typedef void (APIENTRYP PFNGLUNIFORM1FVPROC) (GLint location, GLsizei count, const GLfloat *value); -typedef void (APIENTRYP PFNGLUNIFORM2FVPROC) (GLint location, GLsizei count, const GLfloat *value); -typedef void (APIENTRYP PFNGLUNIFORM3FVPROC) (GLint location, GLsizei count, const GLfloat *value); -typedef void (APIENTRYP PFNGLUNIFORM4FVPROC) (GLint location, GLsizei count, const GLfloat *value); -typedef void (APIENTRYP PFNGLUNIFORM1IVPROC) (GLint location, GLsizei count, const GLint *value); -typedef void (APIENTRYP PFNGLUNIFORM2IVPROC) (GLint location, GLsizei count, const GLint *value); -typedef void (APIENTRYP PFNGLUNIFORM3IVPROC) (GLint location, GLsizei count, const GLint *value); -typedef void (APIENTRYP PFNGLUNIFORM4IVPROC) (GLint location, GLsizei count, const GLint *value); -typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC) (GLuint program); -typedef void (APIENTRYP PFNGLVERTEXATTRIB1DPROC) (GLuint index, GLdouble x); -typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVPROC) (GLuint index, const GLdouble *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB1FPROC) (GLuint index, GLfloat x); -typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVPROC) (GLuint index, const GLfloat *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB1SPROC) (GLuint index, GLshort x); -typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVPROC) (GLuint index, const GLshort *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB2DPROC) (GLuint index, GLdouble x, GLdouble y); -typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVPROC) (GLuint index, const GLdouble *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB2FPROC) (GLuint index, GLfloat x, GLfloat y); -typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVPROC) (GLuint index, const GLfloat *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB2SPROC) (GLuint index, GLshort x, GLshort y); -typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVPROC) (GLuint index, const GLshort *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB3DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); -typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVPROC) (GLuint index, const GLdouble *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB3FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); -typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVPROC) (GLuint index, const GLfloat *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB3SPROC) (GLuint index, GLshort x, GLshort y, GLshort z); -typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVPROC) (GLuint index, const GLshort *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVPROC) (GLuint index, const GLbyte *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVPROC) (GLuint index, const GLint *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVPROC) (GLuint index, const GLshort *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC) (GLuint index, const GLubyte *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC) (GLuint index, const GLuint *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC) (GLuint index, const GLushort *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVPROC) (GLuint index, const GLbyte *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB4DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); -typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVPROC) (GLuint index, const GLdouble *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB4FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); -typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVPROC) (GLuint index, const GLfloat *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVPROC) (GLuint index, const GLint *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB4SPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); -typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVPROC) (GLuint index, const GLshort *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVPROC) (GLuint index, const GLubyte *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVPROC) (GLuint index, const GLuint *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVPROC) (GLuint index, const GLushort *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha); -GLAPI void APIENTRY glDrawBuffers (GLsizei n, const GLenum *bufs); -GLAPI void APIENTRY glStencilOpSeparate (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); -GLAPI void APIENTRY glStencilFuncSeparate (GLenum face, GLenum func, GLint ref, GLuint mask); -GLAPI void APIENTRY glStencilMaskSeparate (GLenum face, GLuint mask); -GLAPI void APIENTRY glAttachShader (GLuint program, GLuint shader); -GLAPI void APIENTRY glBindAttribLocation (GLuint program, GLuint index, const GLchar *name); -GLAPI void APIENTRY glCompileShader (GLuint shader); -GLAPI GLuint APIENTRY glCreateProgram (void); -GLAPI GLuint APIENTRY glCreateShader (GLenum type); -GLAPI void APIENTRY glDeleteProgram (GLuint program); -GLAPI void APIENTRY glDeleteShader (GLuint shader); -GLAPI void APIENTRY glDetachShader (GLuint program, GLuint shader); -GLAPI void APIENTRY glDisableVertexAttribArray (GLuint index); -GLAPI void APIENTRY glEnableVertexAttribArray (GLuint index); -GLAPI void APIENTRY glGetActiveAttrib (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); -GLAPI void APIENTRY glGetActiveUniform (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); -GLAPI void APIENTRY glGetAttachedShaders (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); -GLAPI GLint APIENTRY glGetAttribLocation (GLuint program, const GLchar *name); -GLAPI void APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); -GLAPI void APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); -GLAPI void APIENTRY glGetShaderSource (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); -GLAPI GLint APIENTRY glGetUniformLocation (GLuint program, const GLchar *name); -GLAPI void APIENTRY glGetUniformfv (GLuint program, GLint location, GLfloat *params); -GLAPI void APIENTRY glGetUniformiv (GLuint program, GLint location, GLint *params); -GLAPI void APIENTRY glGetVertexAttribdv (GLuint index, GLenum pname, GLdouble *params); -GLAPI void APIENTRY glGetVertexAttribfv (GLuint index, GLenum pname, GLfloat *params); -GLAPI void APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void **pointer); -GLAPI GLboolean APIENTRY glIsProgram (GLuint program); -GLAPI GLboolean APIENTRY glIsShader (GLuint shader); -GLAPI void APIENTRY glLinkProgram (GLuint program); -GLAPI void APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); -GLAPI void APIENTRY glUseProgram (GLuint program); -GLAPI void APIENTRY glUniform1f (GLint location, GLfloat v0); -GLAPI void APIENTRY glUniform2f (GLint location, GLfloat v0, GLfloat v1); -GLAPI void APIENTRY glUniform3f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); -GLAPI void APIENTRY glUniform4f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); -GLAPI void APIENTRY glUniform1i (GLint location, GLint v0); -GLAPI void APIENTRY glUniform2i (GLint location, GLint v0, GLint v1); -GLAPI void APIENTRY glUniform3i (GLint location, GLint v0, GLint v1, GLint v2); -GLAPI void APIENTRY glUniform4i (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); -GLAPI void APIENTRY glUniform1fv (GLint location, GLsizei count, const GLfloat *value); -GLAPI void APIENTRY glUniform2fv (GLint location, GLsizei count, const GLfloat *value); -GLAPI void APIENTRY glUniform3fv (GLint location, GLsizei count, const GLfloat *value); -GLAPI void APIENTRY glUniform4fv (GLint location, GLsizei count, const GLfloat *value); -GLAPI void APIENTRY glUniform1iv (GLint location, GLsizei count, const GLint *value); -GLAPI void APIENTRY glUniform2iv (GLint location, GLsizei count, const GLint *value); -GLAPI void APIENTRY glUniform3iv (GLint location, GLsizei count, const GLint *value); -GLAPI void APIENTRY glUniform4iv (GLint location, GLsizei count, const GLint *value); -GLAPI void APIENTRY glUniformMatrix2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glUniformMatrix3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glValidateProgram (GLuint program); -GLAPI void APIENTRY glVertexAttrib1d (GLuint index, GLdouble x); -GLAPI void APIENTRY glVertexAttrib1dv (GLuint index, const GLdouble *v); -GLAPI void APIENTRY glVertexAttrib1f (GLuint index, GLfloat x); -GLAPI void APIENTRY glVertexAttrib1fv (GLuint index, const GLfloat *v); -GLAPI void APIENTRY glVertexAttrib1s (GLuint index, GLshort x); -GLAPI void APIENTRY glVertexAttrib1sv (GLuint index, const GLshort *v); -GLAPI void APIENTRY glVertexAttrib2d (GLuint index, GLdouble x, GLdouble y); -GLAPI void APIENTRY glVertexAttrib2dv (GLuint index, const GLdouble *v); -GLAPI void APIENTRY glVertexAttrib2f (GLuint index, GLfloat x, GLfloat y); -GLAPI void APIENTRY glVertexAttrib2fv (GLuint index, const GLfloat *v); -GLAPI void APIENTRY glVertexAttrib2s (GLuint index, GLshort x, GLshort y); -GLAPI void APIENTRY glVertexAttrib2sv (GLuint index, const GLshort *v); -GLAPI void APIENTRY glVertexAttrib3d (GLuint index, GLdouble x, GLdouble y, GLdouble z); -GLAPI void APIENTRY glVertexAttrib3dv (GLuint index, const GLdouble *v); -GLAPI void APIENTRY glVertexAttrib3f (GLuint index, GLfloat x, GLfloat y, GLfloat z); -GLAPI void APIENTRY glVertexAttrib3fv (GLuint index, const GLfloat *v); -GLAPI void APIENTRY glVertexAttrib3s (GLuint index, GLshort x, GLshort y, GLshort z); -GLAPI void APIENTRY glVertexAttrib3sv (GLuint index, const GLshort *v); -GLAPI void APIENTRY glVertexAttrib4Nbv (GLuint index, const GLbyte *v); -GLAPI void APIENTRY glVertexAttrib4Niv (GLuint index, const GLint *v); -GLAPI void APIENTRY glVertexAttrib4Nsv (GLuint index, const GLshort *v); -GLAPI void APIENTRY glVertexAttrib4Nub (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); -GLAPI void APIENTRY glVertexAttrib4Nubv (GLuint index, const GLubyte *v); -GLAPI void APIENTRY glVertexAttrib4Nuiv (GLuint index, const GLuint *v); -GLAPI void APIENTRY glVertexAttrib4Nusv (GLuint index, const GLushort *v); -GLAPI void APIENTRY glVertexAttrib4bv (GLuint index, const GLbyte *v); -GLAPI void APIENTRY glVertexAttrib4d (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); -GLAPI void APIENTRY glVertexAttrib4dv (GLuint index, const GLdouble *v); -GLAPI void APIENTRY glVertexAttrib4f (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); -GLAPI void APIENTRY glVertexAttrib4fv (GLuint index, const GLfloat *v); -GLAPI void APIENTRY glVertexAttrib4iv (GLuint index, const GLint *v); -GLAPI void APIENTRY glVertexAttrib4s (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); -GLAPI void APIENTRY glVertexAttrib4sv (GLuint index, const GLshort *v); -GLAPI void APIENTRY glVertexAttrib4ubv (GLuint index, const GLubyte *v); -GLAPI void APIENTRY glVertexAttrib4uiv (GLuint index, const GLuint *v); -GLAPI void APIENTRY glVertexAttrib4usv (GLuint index, const GLushort *v); -GLAPI void APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); -#endif -#endif /* GL_VERSION_2_0 */ - -#ifndef GL_VERSION_2_1 -#define GL_VERSION_2_1 1 -#define GL_PIXEL_PACK_BUFFER 0x88EB -#define GL_PIXEL_UNPACK_BUFFER 0x88EC -#define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED -#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF -#define GL_FLOAT_MAT2x3 0x8B65 -#define GL_FLOAT_MAT2x4 0x8B66 -#define GL_FLOAT_MAT3x2 0x8B67 -#define GL_FLOAT_MAT3x4 0x8B68 -#define GL_FLOAT_MAT4x2 0x8B69 -#define GL_FLOAT_MAT4x3 0x8B6A -#define GL_SRGB 0x8C40 -#define GL_SRGB8 0x8C41 -#define GL_SRGB_ALPHA 0x8C42 -#define GL_SRGB8_ALPHA8 0x8C43 -#define GL_COMPRESSED_SRGB 0x8C48 -#define GL_COMPRESSED_SRGB_ALPHA 0x8C49 -typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glUniformMatrix2x3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glUniformMatrix3x2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glUniformMatrix2x4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glUniformMatrix4x2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glUniformMatrix3x4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glUniformMatrix4x3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -#endif -#endif /* GL_VERSION_2_1 */ - -#ifndef GL_VERSION_3_0 -#define GL_VERSION_3_0 1 -typedef unsigned short GLhalf; -#define GL_COMPARE_REF_TO_TEXTURE 0x884E -#define GL_CLIP_DISTANCE0 0x3000 -#define GL_CLIP_DISTANCE1 0x3001 -#define GL_CLIP_DISTANCE2 0x3002 -#define GL_CLIP_DISTANCE3 0x3003 -#define GL_CLIP_DISTANCE4 0x3004 -#define GL_CLIP_DISTANCE5 0x3005 -#define GL_CLIP_DISTANCE6 0x3006 -#define GL_CLIP_DISTANCE7 0x3007 -#define GL_MAX_CLIP_DISTANCES 0x0D32 -#define GL_MAJOR_VERSION 0x821B -#define GL_MINOR_VERSION 0x821C -#define GL_NUM_EXTENSIONS 0x821D -#define GL_CONTEXT_FLAGS 0x821E -#define GL_COMPRESSED_RED 0x8225 -#define GL_COMPRESSED_RG 0x8226 -#define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x00000001 -#define GL_RGBA32F 0x8814 -#define GL_RGB32F 0x8815 -#define GL_RGBA16F 0x881A -#define GL_RGB16F 0x881B -#define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD -#define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF -#define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 -#define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 -#define GL_CLAMP_READ_COLOR 0x891C -#define GL_FIXED_ONLY 0x891D -#define GL_MAX_VARYING_COMPONENTS 0x8B4B -#define GL_TEXTURE_1D_ARRAY 0x8C18 -#define GL_PROXY_TEXTURE_1D_ARRAY 0x8C19 -#define GL_TEXTURE_2D_ARRAY 0x8C1A -#define GL_PROXY_TEXTURE_2D_ARRAY 0x8C1B -#define GL_TEXTURE_BINDING_1D_ARRAY 0x8C1C -#define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D -#define GL_R11F_G11F_B10F 0x8C3A -#define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B -#define GL_RGB9_E5 0x8C3D -#define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E -#define GL_TEXTURE_SHARED_SIZE 0x8C3F -#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 -#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F -#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 -#define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 -#define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 -#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 -#define GL_PRIMITIVES_GENERATED 0x8C87 -#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 -#define GL_RASTERIZER_DISCARD 0x8C89 -#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A -#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B -#define GL_INTERLEAVED_ATTRIBS 0x8C8C -#define GL_SEPARATE_ATTRIBS 0x8C8D -#define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E -#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F -#define GL_RGBA32UI 0x8D70 -#define GL_RGB32UI 0x8D71 -#define GL_RGBA16UI 0x8D76 -#define GL_RGB16UI 0x8D77 -#define GL_RGBA8UI 0x8D7C -#define GL_RGB8UI 0x8D7D -#define GL_RGBA32I 0x8D82 -#define GL_RGB32I 0x8D83 -#define GL_RGBA16I 0x8D88 -#define GL_RGB16I 0x8D89 -#define GL_RGBA8I 0x8D8E -#define GL_RGB8I 0x8D8F -#define GL_RED_INTEGER 0x8D94 -#define GL_GREEN_INTEGER 0x8D95 -#define GL_BLUE_INTEGER 0x8D96 -#define GL_RGB_INTEGER 0x8D98 -#define GL_RGBA_INTEGER 0x8D99 -#define GL_BGR_INTEGER 0x8D9A -#define GL_BGRA_INTEGER 0x8D9B -#define GL_SAMPLER_1D_ARRAY 0x8DC0 -#define GL_SAMPLER_2D_ARRAY 0x8DC1 -#define GL_SAMPLER_1D_ARRAY_SHADOW 0x8DC3 -#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 -#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 -#define GL_UNSIGNED_INT_VEC2 0x8DC6 -#define GL_UNSIGNED_INT_VEC3 0x8DC7 -#define GL_UNSIGNED_INT_VEC4 0x8DC8 -#define GL_INT_SAMPLER_1D 0x8DC9 -#define GL_INT_SAMPLER_2D 0x8DCA -#define GL_INT_SAMPLER_3D 0x8DCB -#define GL_INT_SAMPLER_CUBE 0x8DCC -#define GL_INT_SAMPLER_1D_ARRAY 0x8DCE -#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF -#define GL_UNSIGNED_INT_SAMPLER_1D 0x8DD1 -#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 -#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 -#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 -#define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY 0x8DD6 -#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 -#define GL_QUERY_WAIT 0x8E13 -#define GL_QUERY_NO_WAIT 0x8E14 -#define GL_QUERY_BY_REGION_WAIT 0x8E15 -#define GL_QUERY_BY_REGION_NO_WAIT 0x8E16 -#define GL_BUFFER_ACCESS_FLAGS 0x911F -#define GL_BUFFER_MAP_LENGTH 0x9120 -#define GL_BUFFER_MAP_OFFSET 0x9121 -#define GL_DEPTH_COMPONENT32F 0x8CAC -#define GL_DEPTH32F_STENCIL8 0x8CAD -#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD -#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 -#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 -#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 -#define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 -#define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 -#define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 -#define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 -#define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 -#define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 -#define GL_FRAMEBUFFER_DEFAULT 0x8218 -#define GL_FRAMEBUFFER_UNDEFINED 0x8219 -#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A -#define GL_MAX_RENDERBUFFER_SIZE 0x84E8 -#define GL_DEPTH_STENCIL 0x84F9 -#define GL_UNSIGNED_INT_24_8 0x84FA -#define GL_DEPTH24_STENCIL8 0x88F0 -#define GL_TEXTURE_STENCIL_SIZE 0x88F1 -#define GL_TEXTURE_RED_TYPE 0x8C10 -#define GL_TEXTURE_GREEN_TYPE 0x8C11 -#define GL_TEXTURE_BLUE_TYPE 0x8C12 -#define GL_TEXTURE_ALPHA_TYPE 0x8C13 -#define GL_TEXTURE_DEPTH_TYPE 0x8C16 -#define GL_UNSIGNED_NORMALIZED 0x8C17 -#define GL_FRAMEBUFFER_BINDING 0x8CA6 -#define GL_DRAW_FRAMEBUFFER_BINDING 0x8CA6 -#define GL_RENDERBUFFER_BINDING 0x8CA7 -#define GL_READ_FRAMEBUFFER 0x8CA8 -#define GL_DRAW_FRAMEBUFFER 0x8CA9 -#define GL_READ_FRAMEBUFFER_BINDING 0x8CAA -#define GL_RENDERBUFFER_SAMPLES 0x8CAB -#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 -#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 -#define GL_FRAMEBUFFER_COMPLETE 0x8CD5 -#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 -#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 -#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER 0x8CDB -#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER 0x8CDC -#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD -#define GL_MAX_COLOR_ATTACHMENTS 0x8CDF -#define GL_COLOR_ATTACHMENT0 0x8CE0 -#define GL_COLOR_ATTACHMENT1 0x8CE1 -#define GL_COLOR_ATTACHMENT2 0x8CE2 -#define GL_COLOR_ATTACHMENT3 0x8CE3 -#define GL_COLOR_ATTACHMENT4 0x8CE4 -#define GL_COLOR_ATTACHMENT5 0x8CE5 -#define GL_COLOR_ATTACHMENT6 0x8CE6 -#define GL_COLOR_ATTACHMENT7 0x8CE7 -#define GL_COLOR_ATTACHMENT8 0x8CE8 -#define GL_COLOR_ATTACHMENT9 0x8CE9 -#define GL_COLOR_ATTACHMENT10 0x8CEA -#define GL_COLOR_ATTACHMENT11 0x8CEB -#define GL_COLOR_ATTACHMENT12 0x8CEC -#define GL_COLOR_ATTACHMENT13 0x8CED -#define GL_COLOR_ATTACHMENT14 0x8CEE -#define GL_COLOR_ATTACHMENT15 0x8CEF -#define GL_COLOR_ATTACHMENT16 0x8CF0 -#define GL_COLOR_ATTACHMENT17 0x8CF1 -#define GL_COLOR_ATTACHMENT18 0x8CF2 -#define GL_COLOR_ATTACHMENT19 0x8CF3 -#define GL_COLOR_ATTACHMENT20 0x8CF4 -#define GL_COLOR_ATTACHMENT21 0x8CF5 -#define GL_COLOR_ATTACHMENT22 0x8CF6 -#define GL_COLOR_ATTACHMENT23 0x8CF7 -#define GL_COLOR_ATTACHMENT24 0x8CF8 -#define GL_COLOR_ATTACHMENT25 0x8CF9 -#define GL_COLOR_ATTACHMENT26 0x8CFA -#define GL_COLOR_ATTACHMENT27 0x8CFB -#define GL_COLOR_ATTACHMENT28 0x8CFC -#define GL_COLOR_ATTACHMENT29 0x8CFD -#define GL_COLOR_ATTACHMENT30 0x8CFE -#define GL_COLOR_ATTACHMENT31 0x8CFF -#define GL_DEPTH_ATTACHMENT 0x8D00 -#define GL_STENCIL_ATTACHMENT 0x8D20 -#define GL_FRAMEBUFFER 0x8D40 -#define GL_RENDERBUFFER 0x8D41 -#define GL_RENDERBUFFER_WIDTH 0x8D42 -#define GL_RENDERBUFFER_HEIGHT 0x8D43 -#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 -#define GL_STENCIL_INDEX1 0x8D46 -#define GL_STENCIL_INDEX4 0x8D47 -#define GL_STENCIL_INDEX8 0x8D48 -#define GL_STENCIL_INDEX16 0x8D49 -#define GL_RENDERBUFFER_RED_SIZE 0x8D50 -#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 -#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 -#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 -#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 -#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 -#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 -#define GL_MAX_SAMPLES 0x8D57 -#define GL_FRAMEBUFFER_SRGB 0x8DB9 -#define GL_HALF_FLOAT 0x140B -#define GL_MAP_READ_BIT 0x0001 -#define GL_MAP_WRITE_BIT 0x0002 -#define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 -#define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 -#define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 -#define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 -#define GL_COMPRESSED_RED_RGTC1 0x8DBB -#define GL_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC -#define GL_COMPRESSED_RG_RGTC2 0x8DBD -#define GL_COMPRESSED_SIGNED_RG_RGTC2 0x8DBE -#define GL_RG 0x8227 -#define GL_RG_INTEGER 0x8228 -#define GL_R8 0x8229 -#define GL_R16 0x822A -#define GL_RG8 0x822B -#define GL_RG16 0x822C -#define GL_R16F 0x822D -#define GL_R32F 0x822E -#define GL_RG16F 0x822F -#define GL_RG32F 0x8230 -#define GL_R8I 0x8231 -#define GL_R8UI 0x8232 -#define GL_R16I 0x8233 -#define GL_R16UI 0x8234 -#define GL_R32I 0x8235 -#define GL_R32UI 0x8236 -#define GL_RG8I 0x8237 -#define GL_RG8UI 0x8238 -#define GL_RG16I 0x8239 -#define GL_RG16UI 0x823A -#define GL_RG32I 0x823B -#define GL_RG32UI 0x823C -#define GL_VERTEX_ARRAY_BINDING 0x85B5 -typedef void (APIENTRYP PFNGLCOLORMASKIPROC) (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); -typedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC) (GLenum target, GLuint index, GLboolean *data); -typedef void (APIENTRYP PFNGLGETINTEGERI_VPROC) (GLenum target, GLuint index, GLint *data); -typedef void (APIENTRYP PFNGLENABLEIPROC) (GLenum target, GLuint index); -typedef void (APIENTRYP PFNGLDISABLEIPROC) (GLenum target, GLuint index); -typedef GLboolean (APIENTRYP PFNGLISENABLEDIPROC) (GLenum target, GLuint index); -typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKPROC) (GLenum primitiveMode); -typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKPROC) (void); -typedef void (APIENTRYP PFNGLBINDBUFFERRANGEPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); -typedef void (APIENTRYP PFNGLBINDBUFFERBASEPROC) (GLenum target, GLuint index, GLuint buffer); -typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSPROC) (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); -typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); -typedef void (APIENTRYP PFNGLCLAMPCOLORPROC) (GLenum target, GLenum clamp); -typedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERPROC) (GLuint id, GLenum mode); -typedef void (APIENTRYP PFNGLENDCONDITIONALRENDERPROC) (void); -typedef void (APIENTRYP PFNGLVERTEXATTRIBIPOINTERPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIIVPROC) (GLuint index, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIUIVPROC) (GLuint index, GLenum pname, GLuint *params); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IPROC) (GLuint index, GLint x); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IPROC) (GLuint index, GLint x, GLint y); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IPROC) (GLuint index, GLint x, GLint y, GLint z); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IPROC) (GLuint index, GLint x, GLint y, GLint z, GLint w); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIPROC) (GLuint index, GLuint x); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIPROC) (GLuint index, GLuint x, GLuint y); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIPROC) (GLuint index, GLuint x, GLuint y, GLuint z); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIPROC) (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IVPROC) (GLuint index, const GLint *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IVPROC) (GLuint index, const GLint *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IVPROC) (GLuint index, const GLint *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IVPROC) (GLuint index, const GLint *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIVPROC) (GLuint index, const GLuint *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIVPROC) (GLuint index, const GLuint *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIVPROC) (GLuint index, const GLuint *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIVPROC) (GLuint index, const GLuint *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI4BVPROC) (GLuint index, const GLbyte *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI4SVPROC) (GLuint index, const GLshort *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UBVPROC) (GLuint index, const GLubyte *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBI4USVPROC) (GLuint index, const GLushort *v); -typedef void (APIENTRYP PFNGLGETUNIFORMUIVPROC) (GLuint program, GLint location, GLuint *params); -typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONPROC) (GLuint program, GLuint color, const GLchar *name); -typedef GLint (APIENTRYP PFNGLGETFRAGDATALOCATIONPROC) (GLuint program, const GLchar *name); -typedef void (APIENTRYP PFNGLUNIFORM1UIPROC) (GLint location, GLuint v0); -typedef void (APIENTRYP PFNGLUNIFORM2UIPROC) (GLint location, GLuint v0, GLuint v1); -typedef void (APIENTRYP PFNGLUNIFORM3UIPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2); -typedef void (APIENTRYP PFNGLUNIFORM4UIPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); -typedef void (APIENTRYP PFNGLUNIFORM1UIVPROC) (GLint location, GLsizei count, const GLuint *value); -typedef void (APIENTRYP PFNGLUNIFORM2UIVPROC) (GLint location, GLsizei count, const GLuint *value); -typedef void (APIENTRYP PFNGLUNIFORM3UIVPROC) (GLint location, GLsizei count, const GLuint *value); -typedef void (APIENTRYP PFNGLUNIFORM4UIVPROC) (GLint location, GLsizei count, const GLuint *value); -typedef void (APIENTRYP PFNGLTEXPARAMETERIIVPROC) (GLenum target, GLenum pname, const GLint *params); -typedef void (APIENTRYP PFNGLTEXPARAMETERIUIVPROC) (GLenum target, GLenum pname, const GLuint *params); -typedef void (APIENTRYP PFNGLGETTEXPARAMETERIIVPROC) (GLenum target, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETTEXPARAMETERIUIVPROC) (GLenum target, GLenum pname, GLuint *params); -typedef void (APIENTRYP PFNGLCLEARBUFFERIVPROC) (GLenum buffer, GLint drawbuffer, const GLint *value); -typedef void (APIENTRYP PFNGLCLEARBUFFERUIVPROC) (GLenum buffer, GLint drawbuffer, const GLuint *value); -typedef void (APIENTRYP PFNGLCLEARBUFFERFVPROC) (GLenum buffer, GLint drawbuffer, const GLfloat *value); -typedef void (APIENTRYP PFNGLCLEARBUFFERFIPROC) (GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); -typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGIPROC) (GLenum name, GLuint index); -typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFERPROC) (GLuint renderbuffer); -typedef void (APIENTRYP PFNGLBINDRENDERBUFFERPROC) (GLenum target, GLuint renderbuffer); -typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSPROC) (GLsizei n, const GLuint *renderbuffers); -typedef void (APIENTRYP PFNGLGENRENDERBUFFERSPROC) (GLsizei n, GLuint *renderbuffers); -typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); -typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFERPROC) (GLuint framebuffer); -typedef void (APIENTRYP PFNGLBINDFRAMEBUFFERPROC) (GLenum target, GLuint framebuffer); -typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSPROC) (GLsizei n, const GLuint *framebuffers); -typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSPROC) (GLsizei n, GLuint *framebuffers); -typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSPROC) (GLenum target); -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); -typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFERPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); -typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGENERATEMIPMAPPROC) (GLenum target); -typedef void (APIENTRYP PFNGLBLITFRAMEBUFFERPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); -typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); -typedef void *(APIENTRYP PFNGLMAPBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); -typedef void (APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length); -typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC) (GLuint array); -typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint *arrays); -typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays); -typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYPROC) (GLuint array); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glColorMaski (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); -GLAPI void APIENTRY glGetBooleani_v (GLenum target, GLuint index, GLboolean *data); -GLAPI void APIENTRY glGetIntegeri_v (GLenum target, GLuint index, GLint *data); -GLAPI void APIENTRY glEnablei (GLenum target, GLuint index); -GLAPI void APIENTRY glDisablei (GLenum target, GLuint index); -GLAPI GLboolean APIENTRY glIsEnabledi (GLenum target, GLuint index); -GLAPI void APIENTRY glBeginTransformFeedback (GLenum primitiveMode); -GLAPI void APIENTRY glEndTransformFeedback (void); -GLAPI void APIENTRY glBindBufferRange (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); -GLAPI void APIENTRY glBindBufferBase (GLenum target, GLuint index, GLuint buffer); -GLAPI void APIENTRY glTransformFeedbackVaryings (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); -GLAPI void APIENTRY glGetTransformFeedbackVarying (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); -GLAPI void APIENTRY glClampColor (GLenum target, GLenum clamp); -GLAPI void APIENTRY glBeginConditionalRender (GLuint id, GLenum mode); -GLAPI void APIENTRY glEndConditionalRender (void); -GLAPI void APIENTRY glVertexAttribIPointer (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); -GLAPI void APIENTRY glGetVertexAttribIiv (GLuint index, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetVertexAttribIuiv (GLuint index, GLenum pname, GLuint *params); -GLAPI void APIENTRY glVertexAttribI1i (GLuint index, GLint x); -GLAPI void APIENTRY glVertexAttribI2i (GLuint index, GLint x, GLint y); -GLAPI void APIENTRY glVertexAttribI3i (GLuint index, GLint x, GLint y, GLint z); -GLAPI void APIENTRY glVertexAttribI4i (GLuint index, GLint x, GLint y, GLint z, GLint w); -GLAPI void APIENTRY glVertexAttribI1ui (GLuint index, GLuint x); -GLAPI void APIENTRY glVertexAttribI2ui (GLuint index, GLuint x, GLuint y); -GLAPI void APIENTRY glVertexAttribI3ui (GLuint index, GLuint x, GLuint y, GLuint z); -GLAPI void APIENTRY glVertexAttribI4ui (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); -GLAPI void APIENTRY glVertexAttribI1iv (GLuint index, const GLint *v); -GLAPI void APIENTRY glVertexAttribI2iv (GLuint index, const GLint *v); -GLAPI void APIENTRY glVertexAttribI3iv (GLuint index, const GLint *v); -GLAPI void APIENTRY glVertexAttribI4iv (GLuint index, const GLint *v); -GLAPI void APIENTRY glVertexAttribI1uiv (GLuint index, const GLuint *v); -GLAPI void APIENTRY glVertexAttribI2uiv (GLuint index, const GLuint *v); -GLAPI void APIENTRY glVertexAttribI3uiv (GLuint index, const GLuint *v); -GLAPI void APIENTRY glVertexAttribI4uiv (GLuint index, const GLuint *v); -GLAPI void APIENTRY glVertexAttribI4bv (GLuint index, const GLbyte *v); -GLAPI void APIENTRY glVertexAttribI4sv (GLuint index, const GLshort *v); -GLAPI void APIENTRY glVertexAttribI4ubv (GLuint index, const GLubyte *v); -GLAPI void APIENTRY glVertexAttribI4usv (GLuint index, const GLushort *v); -GLAPI void APIENTRY glGetUniformuiv (GLuint program, GLint location, GLuint *params); -GLAPI void APIENTRY glBindFragDataLocation (GLuint program, GLuint color, const GLchar *name); -GLAPI GLint APIENTRY glGetFragDataLocation (GLuint program, const GLchar *name); -GLAPI void APIENTRY glUniform1ui (GLint location, GLuint v0); -GLAPI void APIENTRY glUniform2ui (GLint location, GLuint v0, GLuint v1); -GLAPI void APIENTRY glUniform3ui (GLint location, GLuint v0, GLuint v1, GLuint v2); -GLAPI void APIENTRY glUniform4ui (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); -GLAPI void APIENTRY glUniform1uiv (GLint location, GLsizei count, const GLuint *value); -GLAPI void APIENTRY glUniform2uiv (GLint location, GLsizei count, const GLuint *value); -GLAPI void APIENTRY glUniform3uiv (GLint location, GLsizei count, const GLuint *value); -GLAPI void APIENTRY glUniform4uiv (GLint location, GLsizei count, const GLuint *value); -GLAPI void APIENTRY glTexParameterIiv (GLenum target, GLenum pname, const GLint *params); -GLAPI void APIENTRY glTexParameterIuiv (GLenum target, GLenum pname, const GLuint *params); -GLAPI void APIENTRY glGetTexParameterIiv (GLenum target, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetTexParameterIuiv (GLenum target, GLenum pname, GLuint *params); -GLAPI void APIENTRY glClearBufferiv (GLenum buffer, GLint drawbuffer, const GLint *value); -GLAPI void APIENTRY glClearBufferuiv (GLenum buffer, GLint drawbuffer, const GLuint *value); -GLAPI void APIENTRY glClearBufferfv (GLenum buffer, GLint drawbuffer, const GLfloat *value); -GLAPI void APIENTRY glClearBufferfi (GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); -GLAPI const GLubyte *APIENTRY glGetStringi (GLenum name, GLuint index); -GLAPI GLboolean APIENTRY glIsRenderbuffer (GLuint renderbuffer); -GLAPI void APIENTRY glBindRenderbuffer (GLenum target, GLuint renderbuffer); -GLAPI void APIENTRY glDeleteRenderbuffers (GLsizei n, const GLuint *renderbuffers); -GLAPI void APIENTRY glGenRenderbuffers (GLsizei n, GLuint *renderbuffers); -GLAPI void APIENTRY glRenderbufferStorage (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); -GLAPI void APIENTRY glGetRenderbufferParameteriv (GLenum target, GLenum pname, GLint *params); -GLAPI GLboolean APIENTRY glIsFramebuffer (GLuint framebuffer); -GLAPI void APIENTRY glBindFramebuffer (GLenum target, GLuint framebuffer); -GLAPI void APIENTRY glDeleteFramebuffers (GLsizei n, const GLuint *framebuffers); -GLAPI void APIENTRY glGenFramebuffers (GLsizei n, GLuint *framebuffers); -GLAPI GLenum APIENTRY glCheckFramebufferStatus (GLenum target); -GLAPI void APIENTRY glFramebufferTexture1D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); -GLAPI void APIENTRY glFramebufferTexture2D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); -GLAPI void APIENTRY glFramebufferTexture3D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); -GLAPI void APIENTRY glFramebufferRenderbuffer (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); -GLAPI void APIENTRY glGetFramebufferAttachmentParameteriv (GLenum target, GLenum attachment, GLenum pname, GLint *params); -GLAPI void APIENTRY glGenerateMipmap (GLenum target); -GLAPI void APIENTRY glBlitFramebuffer (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); -GLAPI void APIENTRY glRenderbufferStorageMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -GLAPI void APIENTRY glFramebufferTextureLayer (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); -GLAPI void *APIENTRY glMapBufferRange (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); -GLAPI void APIENTRY glFlushMappedBufferRange (GLenum target, GLintptr offset, GLsizeiptr length); -GLAPI void APIENTRY glBindVertexArray (GLuint array); -GLAPI void APIENTRY glDeleteVertexArrays (GLsizei n, const GLuint *arrays); -GLAPI void APIENTRY glGenVertexArrays (GLsizei n, GLuint *arrays); -GLAPI GLboolean APIENTRY glIsVertexArray (GLuint array); -#endif -#endif /* GL_VERSION_3_0 */ - -#ifndef GL_VERSION_3_1 -#define GL_VERSION_3_1 1 -#define GL_SAMPLER_2D_RECT 0x8B63 -#define GL_SAMPLER_2D_RECT_SHADOW 0x8B64 -#define GL_SAMPLER_BUFFER 0x8DC2 -#define GL_INT_SAMPLER_2D_RECT 0x8DCD -#define GL_INT_SAMPLER_BUFFER 0x8DD0 -#define GL_UNSIGNED_INT_SAMPLER_2D_RECT 0x8DD5 -#define GL_UNSIGNED_INT_SAMPLER_BUFFER 0x8DD8 -#define GL_TEXTURE_BUFFER 0x8C2A -#define GL_MAX_TEXTURE_BUFFER_SIZE 0x8C2B -#define GL_TEXTURE_BINDING_BUFFER 0x8C2C -#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING 0x8C2D -#define GL_TEXTURE_RECTANGLE 0x84F5 -#define GL_TEXTURE_BINDING_RECTANGLE 0x84F6 -#define GL_PROXY_TEXTURE_RECTANGLE 0x84F7 -#define GL_MAX_RECTANGLE_TEXTURE_SIZE 0x84F8 -#define GL_R8_SNORM 0x8F94 -#define GL_RG8_SNORM 0x8F95 -#define GL_RGB8_SNORM 0x8F96 -#define GL_RGBA8_SNORM 0x8F97 -#define GL_R16_SNORM 0x8F98 -#define GL_RG16_SNORM 0x8F99 -#define GL_RGB16_SNORM 0x8F9A -#define GL_RGBA16_SNORM 0x8F9B -#define GL_SIGNED_NORMALIZED 0x8F9C -#define GL_PRIMITIVE_RESTART 0x8F9D -#define GL_PRIMITIVE_RESTART_INDEX 0x8F9E -#define GL_COPY_READ_BUFFER 0x8F36 -#define GL_COPY_WRITE_BUFFER 0x8F37 -#define GL_UNIFORM_BUFFER 0x8A11 -#define GL_UNIFORM_BUFFER_BINDING 0x8A28 -#define GL_UNIFORM_BUFFER_START 0x8A29 -#define GL_UNIFORM_BUFFER_SIZE 0x8A2A -#define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B -#define GL_MAX_GEOMETRY_UNIFORM_BLOCKS 0x8A2C -#define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D -#define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E -#define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F -#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 -#define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 -#define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS 0x8A32 -#define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 -#define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 -#define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 -#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 -#define GL_UNIFORM_TYPE 0x8A37 -#define GL_UNIFORM_SIZE 0x8A38 -#define GL_UNIFORM_NAME_LENGTH 0x8A39 -#define GL_UNIFORM_BLOCK_INDEX 0x8A3A -#define GL_UNIFORM_OFFSET 0x8A3B -#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C -#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D -#define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E -#define GL_UNIFORM_BLOCK_BINDING 0x8A3F -#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 -#define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 -#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 -#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 -#define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 -#define GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER 0x8A45 -#define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 -#define GL_INVALID_INDEX 0xFFFFFFFFu -typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDPROC) (GLenum mode, GLint first, GLsizei count, GLsizei instancecount); -typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount); -typedef void (APIENTRYP PFNGLTEXBUFFERPROC) (GLenum target, GLenum internalformat, GLuint buffer); -typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXPROC) (GLuint index); -typedef void (APIENTRYP PFNGLCOPYBUFFERSUBDATAPROC) (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); -typedef void (APIENTRYP PFNGLGETUNIFORMINDICESPROC) (GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices); -typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMSIVPROC) (GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMNAMEPROC) (GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName); -typedef GLuint (APIENTRYP PFNGLGETUNIFORMBLOCKINDEXPROC) (GLuint program, const GLchar *uniformBlockName); -typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKIVPROC) (GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC) (GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); -typedef void (APIENTRYP PFNGLUNIFORMBLOCKBINDINGPROC) (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glDrawArraysInstanced (GLenum mode, GLint first, GLsizei count, GLsizei instancecount); -GLAPI void APIENTRY glDrawElementsInstanced (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount); -GLAPI void APIENTRY glTexBuffer (GLenum target, GLenum internalformat, GLuint buffer); -GLAPI void APIENTRY glPrimitiveRestartIndex (GLuint index); -GLAPI void APIENTRY glCopyBufferSubData (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); -GLAPI void APIENTRY glGetUniformIndices (GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices); -GLAPI void APIENTRY glGetActiveUniformsiv (GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetActiveUniformName (GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName); -GLAPI GLuint APIENTRY glGetUniformBlockIndex (GLuint program, const GLchar *uniformBlockName); -GLAPI void APIENTRY glGetActiveUniformBlockiv (GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetActiveUniformBlockName (GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); -GLAPI void APIENTRY glUniformBlockBinding (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); -#endif -#endif /* GL_VERSION_3_1 */ - -#ifndef GL_VERSION_3_2 -#define GL_VERSION_3_2 1 -typedef struct __GLsync *GLsync; -#ifndef GLEXT_64_TYPES_DEFINED -/* This code block is duplicated in glxext.h, so must be protected */ -#define GLEXT_64_TYPES_DEFINED -/* Define int32_t, int64_t, and uint64_t types for UST/MSC */ -/* (as used in the GL_EXT_timer_query extension). */ -#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L -#include -#elif defined(__sun__) || defined(__digital__) -#include -#if defined(__STDC__) -#if defined(__arch64__) || defined(_LP64) -typedef long int int64_t; -typedef unsigned long int uint64_t; -#else -typedef long long int int64_t; -typedef unsigned long long int uint64_t; -#endif /* __arch64__ */ -#endif /* __STDC__ */ -#elif defined( __VMS ) || defined(__sgi) -#include -#elif defined(__SCO__) || defined(__USLC__) -#include -#elif defined(__UNIXOS2__) || defined(__SOL64__) -typedef long int int32_t; -typedef long long int int64_t; -typedef unsigned long long int uint64_t; -#elif defined(_WIN32) && defined(__GNUC__) -#include -#elif defined(_WIN32) -typedef __int32 int32_t; -typedef __int64 int64_t; -typedef unsigned __int64 uint64_t; -#else -/* Fallback if nothing above works */ -#include -#endif -#endif -typedef uint64_t GLuint64; -typedef int64_t GLint64; -#define GL_CONTEXT_CORE_PROFILE_BIT 0x00000001 -#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 -#define GL_LINES_ADJACENCY 0x000A -#define GL_LINE_STRIP_ADJACENCY 0x000B -#define GL_TRIANGLES_ADJACENCY 0x000C -#define GL_TRIANGLE_STRIP_ADJACENCY 0x000D -#define GL_PROGRAM_POINT_SIZE 0x8642 -#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS 0x8C29 -#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED 0x8DA7 -#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS 0x8DA8 -#define GL_GEOMETRY_SHADER 0x8DD9 -#define GL_GEOMETRY_VERTICES_OUT 0x8916 -#define GL_GEOMETRY_INPUT_TYPE 0x8917 -#define GL_GEOMETRY_OUTPUT_TYPE 0x8918 -#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS 0x8DDF -#define GL_MAX_GEOMETRY_OUTPUT_VERTICES 0x8DE0 -#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS 0x8DE1 -#define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122 -#define GL_MAX_GEOMETRY_INPUT_COMPONENTS 0x9123 -#define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS 0x9124 -#define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125 -#define GL_CONTEXT_PROFILE_MASK 0x9126 -#define GL_DEPTH_CLAMP 0x864F -#define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION 0x8E4C -#define GL_FIRST_VERTEX_CONVENTION 0x8E4D -#define GL_LAST_VERTEX_CONVENTION 0x8E4E -#define GL_PROVOKING_VERTEX 0x8E4F -#define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F -#define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111 -#define GL_OBJECT_TYPE 0x9112 -#define GL_SYNC_CONDITION 0x9113 -#define GL_SYNC_STATUS 0x9114 -#define GL_SYNC_FLAGS 0x9115 -#define GL_SYNC_FENCE 0x9116 -#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 -#define GL_UNSIGNALED 0x9118 -#define GL_SIGNALED 0x9119 -#define GL_ALREADY_SIGNALED 0x911A -#define GL_TIMEOUT_EXPIRED 0x911B -#define GL_CONDITION_SATISFIED 0x911C -#define GL_WAIT_FAILED 0x911D -#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull -#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 -#define GL_SAMPLE_POSITION 0x8E50 -#define GL_SAMPLE_MASK 0x8E51 -#define GL_SAMPLE_MASK_VALUE 0x8E52 -#define GL_MAX_SAMPLE_MASK_WORDS 0x8E59 -#define GL_TEXTURE_2D_MULTISAMPLE 0x9100 -#define GL_PROXY_TEXTURE_2D_MULTISAMPLE 0x9101 -#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102 -#define GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9103 -#define GL_TEXTURE_BINDING_2D_MULTISAMPLE 0x9104 -#define GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY 0x9105 -#define GL_TEXTURE_SAMPLES 0x9106 -#define GL_TEXTURE_FIXED_SAMPLE_LOCATIONS 0x9107 -#define GL_SAMPLER_2D_MULTISAMPLE 0x9108 -#define GL_INT_SAMPLER_2D_MULTISAMPLE 0x9109 -#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A -#define GL_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910B -#define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910C -#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910D -#define GL_MAX_COLOR_TEXTURE_SAMPLES 0x910E -#define GL_MAX_DEPTH_TEXTURE_SAMPLES 0x910F -#define GL_MAX_INTEGER_SAMPLES 0x9110 -typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); -typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); -typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); -typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount, const GLint *basevertex); -typedef void (APIENTRYP PFNGLPROVOKINGVERTEXPROC) (GLenum mode); -typedef GLsync (APIENTRYP PFNGLFENCESYNCPROC) (GLenum condition, GLbitfield flags); -typedef GLboolean (APIENTRYP PFNGLISSYNCPROC) (GLsync sync); -typedef void (APIENTRYP PFNGLDELETESYNCPROC) (GLsync sync); -typedef GLenum (APIENTRYP PFNGLCLIENTWAITSYNCPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout); -typedef void (APIENTRYP PFNGLWAITSYNCPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout); -typedef void (APIENTRYP PFNGLGETINTEGER64VPROC) (GLenum pname, GLint64 *data); -typedef void (APIENTRYP PFNGLGETSYNCIVPROC) (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); -typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC) (GLenum target, GLuint index, GLint64 *data); -typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERI64VPROC) (GLenum target, GLenum pname, GLint64 *params); -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level); -typedef void (APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); -typedef void (APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); -typedef void (APIENTRYP PFNGLGETMULTISAMPLEFVPROC) (GLenum pname, GLuint index, GLfloat *val); -typedef void (APIENTRYP PFNGLSAMPLEMASKIPROC) (GLuint maskNumber, GLbitfield mask); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glDrawElementsBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); -GLAPI void APIENTRY glDrawRangeElementsBaseVertex (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); -GLAPI void APIENTRY glDrawElementsInstancedBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); -GLAPI void APIENTRY glMultiDrawElementsBaseVertex (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount, const GLint *basevertex); -GLAPI void APIENTRY glProvokingVertex (GLenum mode); -GLAPI GLsync APIENTRY glFenceSync (GLenum condition, GLbitfield flags); -GLAPI GLboolean APIENTRY glIsSync (GLsync sync); -GLAPI void APIENTRY glDeleteSync (GLsync sync); -GLAPI GLenum APIENTRY glClientWaitSync (GLsync sync, GLbitfield flags, GLuint64 timeout); -GLAPI void APIENTRY glWaitSync (GLsync sync, GLbitfield flags, GLuint64 timeout); -GLAPI void APIENTRY glGetInteger64v (GLenum pname, GLint64 *data); -GLAPI void APIENTRY glGetSynciv (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); -GLAPI void APIENTRY glGetInteger64i_v (GLenum target, GLuint index, GLint64 *data); -GLAPI void APIENTRY glGetBufferParameteri64v (GLenum target, GLenum pname, GLint64 *params); -GLAPI void APIENTRY glFramebufferTexture (GLenum target, GLenum attachment, GLuint texture, GLint level); -GLAPI void APIENTRY glTexImage2DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); -GLAPI void APIENTRY glTexImage3DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); -GLAPI void APIENTRY glGetMultisamplefv (GLenum pname, GLuint index, GLfloat *val); -GLAPI void APIENTRY glSampleMaski (GLuint maskNumber, GLbitfield mask); -#endif -#endif /* GL_VERSION_3_2 */ - -#ifndef GL_VERSION_3_3 -#define GL_VERSION_3_3 1 -#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE -#define GL_SRC1_COLOR 0x88F9 -#define GL_ONE_MINUS_SRC1_COLOR 0x88FA -#define GL_ONE_MINUS_SRC1_ALPHA 0x88FB -#define GL_MAX_DUAL_SOURCE_DRAW_BUFFERS 0x88FC -#define GL_ANY_SAMPLES_PASSED 0x8C2F -#define GL_SAMPLER_BINDING 0x8919 -#define GL_RGB10_A2UI 0x906F -#define GL_TEXTURE_SWIZZLE_R 0x8E42 -#define GL_TEXTURE_SWIZZLE_G 0x8E43 -#define GL_TEXTURE_SWIZZLE_B 0x8E44 -#define GL_TEXTURE_SWIZZLE_A 0x8E45 -#define GL_TEXTURE_SWIZZLE_RGBA 0x8E46 -#define GL_TIME_ELAPSED 0x88BF -#define GL_TIMESTAMP 0x8E28 -#define GL_INT_2_10_10_10_REV 0x8D9F -typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONINDEXEDPROC) (GLuint program, GLuint colorNumber, GLuint index, const GLchar *name); -typedef GLint (APIENTRYP PFNGLGETFRAGDATAINDEXPROC) (GLuint program, const GLchar *name); -typedef void (APIENTRYP PFNGLGENSAMPLERSPROC) (GLsizei count, GLuint *samplers); -typedef void (APIENTRYP PFNGLDELETESAMPLERSPROC) (GLsizei count, const GLuint *samplers); -typedef GLboolean (APIENTRYP PFNGLISSAMPLERPROC) (GLuint sampler); -typedef void (APIENTRYP PFNGLBINDSAMPLERPROC) (GLuint unit, GLuint sampler); -typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIPROC) (GLuint sampler, GLenum pname, GLint param); -typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIVPROC) (GLuint sampler, GLenum pname, const GLint *param); -typedef void (APIENTRYP PFNGLSAMPLERPARAMETERFPROC) (GLuint sampler, GLenum pname, GLfloat param); -typedef void (APIENTRYP PFNGLSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum pname, const GLfloat *param); -typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIIVPROC) (GLuint sampler, GLenum pname, const GLint *param); -typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIUIVPROC) (GLuint sampler, GLenum pname, const GLuint *param); -typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIVPROC) (GLuint sampler, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIIVPROC) (GLuint sampler, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum pname, GLfloat *params); -typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIUIVPROC) (GLuint sampler, GLenum pname, GLuint *params); -typedef void (APIENTRYP PFNGLQUERYCOUNTERPROC) (GLuint id, GLenum target); -typedef void (APIENTRYP PFNGLGETQUERYOBJECTI64VPROC) (GLuint id, GLenum pname, GLint64 *params); -typedef void (APIENTRYP PFNGLGETQUERYOBJECTUI64VPROC) (GLuint id, GLenum pname, GLuint64 *params); -typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORPROC) (GLuint index, GLuint divisor); -typedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value); -typedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); -typedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value); -typedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); -typedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value); -typedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); -typedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value); -typedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glBindFragDataLocationIndexed (GLuint program, GLuint colorNumber, GLuint index, const GLchar *name); -GLAPI GLint APIENTRY glGetFragDataIndex (GLuint program, const GLchar *name); -GLAPI void APIENTRY glGenSamplers (GLsizei count, GLuint *samplers); -GLAPI void APIENTRY glDeleteSamplers (GLsizei count, const GLuint *samplers); -GLAPI GLboolean APIENTRY glIsSampler (GLuint sampler); -GLAPI void APIENTRY glBindSampler (GLuint unit, GLuint sampler); -GLAPI void APIENTRY glSamplerParameteri (GLuint sampler, GLenum pname, GLint param); -GLAPI void APIENTRY glSamplerParameteriv (GLuint sampler, GLenum pname, const GLint *param); -GLAPI void APIENTRY glSamplerParameterf (GLuint sampler, GLenum pname, GLfloat param); -GLAPI void APIENTRY glSamplerParameterfv (GLuint sampler, GLenum pname, const GLfloat *param); -GLAPI void APIENTRY glSamplerParameterIiv (GLuint sampler, GLenum pname, const GLint *param); -GLAPI void APIENTRY glSamplerParameterIuiv (GLuint sampler, GLenum pname, const GLuint *param); -GLAPI void APIENTRY glGetSamplerParameteriv (GLuint sampler, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetSamplerParameterIiv (GLuint sampler, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetSamplerParameterfv (GLuint sampler, GLenum pname, GLfloat *params); -GLAPI void APIENTRY glGetSamplerParameterIuiv (GLuint sampler, GLenum pname, GLuint *params); -GLAPI void APIENTRY glQueryCounter (GLuint id, GLenum target); -GLAPI void APIENTRY glGetQueryObjecti64v (GLuint id, GLenum pname, GLint64 *params); -GLAPI void APIENTRY glGetQueryObjectui64v (GLuint id, GLenum pname, GLuint64 *params); -GLAPI void APIENTRY glVertexAttribDivisor (GLuint index, GLuint divisor); -GLAPI void APIENTRY glVertexAttribP1ui (GLuint index, GLenum type, GLboolean normalized, GLuint value); -GLAPI void APIENTRY glVertexAttribP1uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); -GLAPI void APIENTRY glVertexAttribP2ui (GLuint index, GLenum type, GLboolean normalized, GLuint value); -GLAPI void APIENTRY glVertexAttribP2uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); -GLAPI void APIENTRY glVertexAttribP3ui (GLuint index, GLenum type, GLboolean normalized, GLuint value); -GLAPI void APIENTRY glVertexAttribP3uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); -GLAPI void APIENTRY glVertexAttribP4ui (GLuint index, GLenum type, GLboolean normalized, GLuint value); -GLAPI void APIENTRY glVertexAttribP4uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); -#endif -#endif /* GL_VERSION_3_3 */ - -#ifndef GL_VERSION_4_0 -#define GL_VERSION_4_0 1 -#define GL_SAMPLE_SHADING 0x8C36 -#define GL_MIN_SAMPLE_SHADING_VALUE 0x8C37 -#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5E -#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5F -#define GL_TEXTURE_CUBE_MAP_ARRAY 0x9009 -#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY 0x900A -#define GL_PROXY_TEXTURE_CUBE_MAP_ARRAY 0x900B -#define GL_SAMPLER_CUBE_MAP_ARRAY 0x900C -#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW 0x900D -#define GL_INT_SAMPLER_CUBE_MAP_ARRAY 0x900E -#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY 0x900F -#define GL_DRAW_INDIRECT_BUFFER 0x8F3F -#define GL_DRAW_INDIRECT_BUFFER_BINDING 0x8F43 -#define GL_GEOMETRY_SHADER_INVOCATIONS 0x887F -#define GL_MAX_GEOMETRY_SHADER_INVOCATIONS 0x8E5A -#define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET 0x8E5B -#define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET 0x8E5C -#define GL_FRAGMENT_INTERPOLATION_OFFSET_BITS 0x8E5D -#define GL_MAX_VERTEX_STREAMS 0x8E71 -#define GL_DOUBLE_VEC2 0x8FFC -#define GL_DOUBLE_VEC3 0x8FFD -#define GL_DOUBLE_VEC4 0x8FFE -#define GL_DOUBLE_MAT2 0x8F46 -#define GL_DOUBLE_MAT3 0x8F47 -#define GL_DOUBLE_MAT4 0x8F48 -#define GL_DOUBLE_MAT2x3 0x8F49 -#define GL_DOUBLE_MAT2x4 0x8F4A -#define GL_DOUBLE_MAT3x2 0x8F4B -#define GL_DOUBLE_MAT3x4 0x8F4C -#define GL_DOUBLE_MAT4x2 0x8F4D -#define GL_DOUBLE_MAT4x3 0x8F4E -#define GL_ACTIVE_SUBROUTINES 0x8DE5 -#define GL_ACTIVE_SUBROUTINE_UNIFORMS 0x8DE6 -#define GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS 0x8E47 -#define GL_ACTIVE_SUBROUTINE_MAX_LENGTH 0x8E48 -#define GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH 0x8E49 -#define GL_MAX_SUBROUTINES 0x8DE7 -#define GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS 0x8DE8 -#define GL_NUM_COMPATIBLE_SUBROUTINES 0x8E4A -#define GL_COMPATIBLE_SUBROUTINES 0x8E4B -#define GL_PATCHES 0x000E -#define GL_PATCH_VERTICES 0x8E72 -#define GL_PATCH_DEFAULT_INNER_LEVEL 0x8E73 -#define GL_PATCH_DEFAULT_OUTER_LEVEL 0x8E74 -#define GL_TESS_CONTROL_OUTPUT_VERTICES 0x8E75 -#define GL_TESS_GEN_MODE 0x8E76 -#define GL_TESS_GEN_SPACING 0x8E77 -#define GL_TESS_GEN_VERTEX_ORDER 0x8E78 -#define GL_TESS_GEN_POINT_MODE 0x8E79 -#define GL_ISOLINES 0x8E7A -#define GL_FRACTIONAL_ODD 0x8E7B -#define GL_FRACTIONAL_EVEN 0x8E7C -#define GL_MAX_PATCH_VERTICES 0x8E7D -#define GL_MAX_TESS_GEN_LEVEL 0x8E7E -#define GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E7F -#define GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E80 -#define GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS 0x8E81 -#define GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS 0x8E82 -#define GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS 0x8E83 -#define GL_MAX_TESS_PATCH_COMPONENTS 0x8E84 -#define GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS 0x8E85 -#define GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS 0x8E86 -#define GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS 0x8E89 -#define GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS 0x8E8A -#define GL_MAX_TESS_CONTROL_INPUT_COMPONENTS 0x886C -#define GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS 0x886D -#define GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E1E -#define GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E1F -#define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER 0x84F0 -#define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER 0x84F1 -#define GL_TESS_EVALUATION_SHADER 0x8E87 -#define GL_TESS_CONTROL_SHADER 0x8E88 -#define GL_TRANSFORM_FEEDBACK 0x8E22 -#define GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED 0x8E23 -#define GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE 0x8E24 -#define GL_TRANSFORM_FEEDBACK_BINDING 0x8E25 -#define GL_MAX_TRANSFORM_FEEDBACK_BUFFERS 0x8E70 -typedef void (APIENTRYP PFNGLMINSAMPLESHADINGPROC) (GLfloat value); -typedef void (APIENTRYP PFNGLBLENDEQUATIONIPROC) (GLuint buf, GLenum mode); -typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEIPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha); -typedef void (APIENTRYP PFNGLBLENDFUNCIPROC) (GLuint buf, GLenum src, GLenum dst); -typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEIPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); -typedef void (APIENTRYP PFNGLDRAWARRAYSINDIRECTPROC) (GLenum mode, const void *indirect); -typedef void (APIENTRYP PFNGLDRAWELEMENTSINDIRECTPROC) (GLenum mode, GLenum type, const void *indirect); -typedef void (APIENTRYP PFNGLUNIFORM1DPROC) (GLint location, GLdouble x); -typedef void (APIENTRYP PFNGLUNIFORM2DPROC) (GLint location, GLdouble x, GLdouble y); -typedef void (APIENTRYP PFNGLUNIFORM3DPROC) (GLint location, GLdouble x, GLdouble y, GLdouble z); -typedef void (APIENTRYP PFNGLUNIFORM4DPROC) (GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); -typedef void (APIENTRYP PFNGLUNIFORM1DVPROC) (GLint location, GLsizei count, const GLdouble *value); -typedef void (APIENTRYP PFNGLUNIFORM2DVPROC) (GLint location, GLsizei count, const GLdouble *value); -typedef void (APIENTRYP PFNGLUNIFORM3DVPROC) (GLint location, GLsizei count, const GLdouble *value); -typedef void (APIENTRYP PFNGLUNIFORM4DVPROC) (GLint location, GLsizei count, const GLdouble *value); -typedef void (APIENTRYP PFNGLUNIFORMMATRIX2DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLUNIFORMMATRIX3DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLUNIFORMMATRIX4DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLGETUNIFORMDVPROC) (GLuint program, GLint location, GLdouble *params); -typedef GLint (APIENTRYP PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC) (GLuint program, GLenum shadertype, const GLchar *name); -typedef GLuint (APIENTRYP PFNGLGETSUBROUTINEINDEXPROC) (GLuint program, GLenum shadertype, const GLchar *name); -typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC) (GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint *values); -typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC) (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name); -typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINENAMEPROC) (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name); -typedef void (APIENTRYP PFNGLUNIFORMSUBROUTINESUIVPROC) (GLenum shadertype, GLsizei count, const GLuint *indices); -typedef void (APIENTRYP PFNGLGETUNIFORMSUBROUTINEUIVPROC) (GLenum shadertype, GLint location, GLuint *params); -typedef void (APIENTRYP PFNGLGETPROGRAMSTAGEIVPROC) (GLuint program, GLenum shadertype, GLenum pname, GLint *values); -typedef void (APIENTRYP PFNGLPATCHPARAMETERIPROC) (GLenum pname, GLint value); -typedef void (APIENTRYP PFNGLPATCHPARAMETERFVPROC) (GLenum pname, const GLfloat *values); -typedef void (APIENTRYP PFNGLBINDTRANSFORMFEEDBACKPROC) (GLenum target, GLuint id); -typedef void (APIENTRYP PFNGLDELETETRANSFORMFEEDBACKSPROC) (GLsizei n, const GLuint *ids); -typedef void (APIENTRYP PFNGLGENTRANSFORMFEEDBACKSPROC) (GLsizei n, GLuint *ids); -typedef GLboolean (APIENTRYP PFNGLISTRANSFORMFEEDBACKPROC) (GLuint id); -typedef void (APIENTRYP PFNGLPAUSETRANSFORMFEEDBACKPROC) (void); -typedef void (APIENTRYP PFNGLRESUMETRANSFORMFEEDBACKPROC) (void); -typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKPROC) (GLenum mode, GLuint id); -typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC) (GLenum mode, GLuint id, GLuint stream); -typedef void (APIENTRYP PFNGLBEGINQUERYINDEXEDPROC) (GLenum target, GLuint index, GLuint id); -typedef void (APIENTRYP PFNGLENDQUERYINDEXEDPROC) (GLenum target, GLuint index); -typedef void (APIENTRYP PFNGLGETQUERYINDEXEDIVPROC) (GLenum target, GLuint index, GLenum pname, GLint *params); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glMinSampleShading (GLfloat value); -GLAPI void APIENTRY glBlendEquationi (GLuint buf, GLenum mode); -GLAPI void APIENTRY glBlendEquationSeparatei (GLuint buf, GLenum modeRGB, GLenum modeAlpha); -GLAPI void APIENTRY glBlendFunci (GLuint buf, GLenum src, GLenum dst); -GLAPI void APIENTRY glBlendFuncSeparatei (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); -GLAPI void APIENTRY glDrawArraysIndirect (GLenum mode, const void *indirect); -GLAPI void APIENTRY glDrawElementsIndirect (GLenum mode, GLenum type, const void *indirect); -GLAPI void APIENTRY glUniform1d (GLint location, GLdouble x); -GLAPI void APIENTRY glUniform2d (GLint location, GLdouble x, GLdouble y); -GLAPI void APIENTRY glUniform3d (GLint location, GLdouble x, GLdouble y, GLdouble z); -GLAPI void APIENTRY glUniform4d (GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); -GLAPI void APIENTRY glUniform1dv (GLint location, GLsizei count, const GLdouble *value); -GLAPI void APIENTRY glUniform2dv (GLint location, GLsizei count, const GLdouble *value); -GLAPI void APIENTRY glUniform3dv (GLint location, GLsizei count, const GLdouble *value); -GLAPI void APIENTRY glUniform4dv (GLint location, GLsizei count, const GLdouble *value); -GLAPI void APIENTRY glUniformMatrix2dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glUniformMatrix3dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glUniformMatrix4dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glUniformMatrix2x3dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glUniformMatrix2x4dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glUniformMatrix3x2dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glUniformMatrix3x4dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glUniformMatrix4x2dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glUniformMatrix4x3dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glGetUniformdv (GLuint program, GLint location, GLdouble *params); -GLAPI GLint APIENTRY glGetSubroutineUniformLocation (GLuint program, GLenum shadertype, const GLchar *name); -GLAPI GLuint APIENTRY glGetSubroutineIndex (GLuint program, GLenum shadertype, const GLchar *name); -GLAPI void APIENTRY glGetActiveSubroutineUniformiv (GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint *values); -GLAPI void APIENTRY glGetActiveSubroutineUniformName (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name); -GLAPI void APIENTRY glGetActiveSubroutineName (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name); -GLAPI void APIENTRY glUniformSubroutinesuiv (GLenum shadertype, GLsizei count, const GLuint *indices); -GLAPI void APIENTRY glGetUniformSubroutineuiv (GLenum shadertype, GLint location, GLuint *params); -GLAPI void APIENTRY glGetProgramStageiv (GLuint program, GLenum shadertype, GLenum pname, GLint *values); -GLAPI void APIENTRY glPatchParameteri (GLenum pname, GLint value); -GLAPI void APIENTRY glPatchParameterfv (GLenum pname, const GLfloat *values); -GLAPI void APIENTRY glBindTransformFeedback (GLenum target, GLuint id); -GLAPI void APIENTRY glDeleteTransformFeedbacks (GLsizei n, const GLuint *ids); -GLAPI void APIENTRY glGenTransformFeedbacks (GLsizei n, GLuint *ids); -GLAPI GLboolean APIENTRY glIsTransformFeedback (GLuint id); -GLAPI void APIENTRY glPauseTransformFeedback (void); -GLAPI void APIENTRY glResumeTransformFeedback (void); -GLAPI void APIENTRY glDrawTransformFeedback (GLenum mode, GLuint id); -GLAPI void APIENTRY glDrawTransformFeedbackStream (GLenum mode, GLuint id, GLuint stream); -GLAPI void APIENTRY glBeginQueryIndexed (GLenum target, GLuint index, GLuint id); -GLAPI void APIENTRY glEndQueryIndexed (GLenum target, GLuint index); -GLAPI void APIENTRY glGetQueryIndexediv (GLenum target, GLuint index, GLenum pname, GLint *params); -#endif -#endif /* GL_VERSION_4_0 */ - -#ifndef GL_VERSION_4_1 -#define GL_VERSION_4_1 1 -#define GL_FIXED 0x140C -#define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A -#define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B -#define GL_LOW_FLOAT 0x8DF0 -#define GL_MEDIUM_FLOAT 0x8DF1 -#define GL_HIGH_FLOAT 0x8DF2 -#define GL_LOW_INT 0x8DF3 -#define GL_MEDIUM_INT 0x8DF4 -#define GL_HIGH_INT 0x8DF5 -#define GL_SHADER_COMPILER 0x8DFA -#define GL_SHADER_BINARY_FORMATS 0x8DF8 -#define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9 -#define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB -#define GL_MAX_VARYING_VECTORS 0x8DFC -#define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD -#define GL_RGB565 0x8D62 -#define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 0x8257 -#define GL_PROGRAM_BINARY_LENGTH 0x8741 -#define GL_NUM_PROGRAM_BINARY_FORMATS 0x87FE -#define GL_PROGRAM_BINARY_FORMATS 0x87FF -#define GL_VERTEX_SHADER_BIT 0x00000001 -#define GL_FRAGMENT_SHADER_BIT 0x00000002 -#define GL_GEOMETRY_SHADER_BIT 0x00000004 -#define GL_TESS_CONTROL_SHADER_BIT 0x00000008 -#define GL_TESS_EVALUATION_SHADER_BIT 0x00000010 -#define GL_ALL_SHADER_BITS 0xFFFFFFFF -#define GL_PROGRAM_SEPARABLE 0x8258 -#define GL_ACTIVE_PROGRAM 0x8259 -#define GL_PROGRAM_PIPELINE_BINDING 0x825A -#define GL_MAX_VIEWPORTS 0x825B -#define GL_VIEWPORT_SUBPIXEL_BITS 0x825C -#define GL_VIEWPORT_BOUNDS_RANGE 0x825D -#define GL_LAYER_PROVOKING_VERTEX 0x825E -#define GL_VIEWPORT_INDEX_PROVOKING_VERTEX 0x825F -#define GL_UNDEFINED_VERTEX 0x8260 -typedef void (APIENTRYP PFNGLRELEASESHADERCOMPILERPROC) (void); -typedef void (APIENTRYP PFNGLSHADERBINARYPROC) (GLsizei count, const GLuint *shaders, GLenum binaryformat, const void *binary, GLsizei length); -typedef void (APIENTRYP PFNGLGETSHADERPRECISIONFORMATPROC) (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision); -typedef void (APIENTRYP PFNGLDEPTHRANGEFPROC) (GLfloat n, GLfloat f); -typedef void (APIENTRYP PFNGLCLEARDEPTHFPROC) (GLfloat d); -typedef void (APIENTRYP PFNGLGETPROGRAMBINARYPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); -typedef void (APIENTRYP PFNGLPROGRAMBINARYPROC) (GLuint program, GLenum binaryFormat, const void *binary, GLsizei length); -typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIPROC) (GLuint program, GLenum pname, GLint value); -typedef void (APIENTRYP PFNGLUSEPROGRAMSTAGESPROC) (GLuint pipeline, GLbitfield stages, GLuint program); -typedef void (APIENTRYP PFNGLACTIVESHADERPROGRAMPROC) (GLuint pipeline, GLuint program); -typedef GLuint (APIENTRYP PFNGLCREATESHADERPROGRAMVPROC) (GLenum type, GLsizei count, const GLchar *const*strings); -typedef void (APIENTRYP PFNGLBINDPROGRAMPIPELINEPROC) (GLuint pipeline); -typedef void (APIENTRYP PFNGLDELETEPROGRAMPIPELINESPROC) (GLsizei n, const GLuint *pipelines); -typedef void (APIENTRYP PFNGLGENPROGRAMPIPELINESPROC) (GLsizei n, GLuint *pipelines); -typedef GLboolean (APIENTRYP PFNGLISPROGRAMPIPELINEPROC) (GLuint pipeline); -typedef void (APIENTRYP PFNGLGETPROGRAMPIPELINEIVPROC) (GLuint pipeline, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IPROC) (GLuint program, GLint location, GLint v0); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FPROC) (GLuint program, GLint location, GLfloat v0); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DPROC) (GLuint program, GLint location, GLdouble v0); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIPROC) (GLuint program, GLint location, GLuint v0); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IPROC) (GLuint program, GLint location, GLint v0, GLint v1); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DPROC) (GLuint program, GLint location, GLdouble v0, GLdouble v1); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIPROC) (GLuint program, GLint location, GLuint v0, GLuint v1); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DPROC) (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DPROC) (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPIPELINEPROC) (GLuint pipeline); -typedef void (APIENTRYP PFNGLGETPROGRAMPIPELINEINFOLOGPROC) (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DPROC) (GLuint index, GLdouble x); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DPROC) (GLuint index, GLdouble x, GLdouble y); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DVPROC) (GLuint index, const GLdouble *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DVPROC) (GLuint index, const GLdouble *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DVPROC) (GLuint index, const GLdouble *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DVPROC) (GLuint index, const GLdouble *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBLPOINTERPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLDVPROC) (GLuint index, GLenum pname, GLdouble *params); -typedef void (APIENTRYP PFNGLVIEWPORTARRAYVPROC) (GLuint first, GLsizei count, const GLfloat *v); -typedef void (APIENTRYP PFNGLVIEWPORTINDEXEDFPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h); -typedef void (APIENTRYP PFNGLVIEWPORTINDEXEDFVPROC) (GLuint index, const GLfloat *v); -typedef void (APIENTRYP PFNGLSCISSORARRAYVPROC) (GLuint first, GLsizei count, const GLint *v); -typedef void (APIENTRYP PFNGLSCISSORINDEXEDPROC) (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLSCISSORINDEXEDVPROC) (GLuint index, const GLint *v); -typedef void (APIENTRYP PFNGLDEPTHRANGEARRAYVPROC) (GLuint first, GLsizei count, const GLdouble *v); -typedef void (APIENTRYP PFNGLDEPTHRANGEINDEXEDPROC) (GLuint index, GLdouble n, GLdouble f); -typedef void (APIENTRYP PFNGLGETFLOATI_VPROC) (GLenum target, GLuint index, GLfloat *data); -typedef void (APIENTRYP PFNGLGETDOUBLEI_VPROC) (GLenum target, GLuint index, GLdouble *data); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glReleaseShaderCompiler (void); -GLAPI void APIENTRY glShaderBinary (GLsizei count, const GLuint *shaders, GLenum binaryformat, const void *binary, GLsizei length); -GLAPI void APIENTRY glGetShaderPrecisionFormat (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision); -GLAPI void APIENTRY glDepthRangef (GLfloat n, GLfloat f); -GLAPI void APIENTRY glClearDepthf (GLfloat d); -GLAPI void APIENTRY glGetProgramBinary (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); -GLAPI void APIENTRY glProgramBinary (GLuint program, GLenum binaryFormat, const void *binary, GLsizei length); -GLAPI void APIENTRY glProgramParameteri (GLuint program, GLenum pname, GLint value); -GLAPI void APIENTRY glUseProgramStages (GLuint pipeline, GLbitfield stages, GLuint program); -GLAPI void APIENTRY glActiveShaderProgram (GLuint pipeline, GLuint program); -GLAPI GLuint APIENTRY glCreateShaderProgramv (GLenum type, GLsizei count, const GLchar *const*strings); -GLAPI void APIENTRY glBindProgramPipeline (GLuint pipeline); -GLAPI void APIENTRY glDeleteProgramPipelines (GLsizei n, const GLuint *pipelines); -GLAPI void APIENTRY glGenProgramPipelines (GLsizei n, GLuint *pipelines); -GLAPI GLboolean APIENTRY glIsProgramPipeline (GLuint pipeline); -GLAPI void APIENTRY glGetProgramPipelineiv (GLuint pipeline, GLenum pname, GLint *params); -GLAPI void APIENTRY glProgramUniform1i (GLuint program, GLint location, GLint v0); -GLAPI void APIENTRY glProgramUniform1iv (GLuint program, GLint location, GLsizei count, const GLint *value); -GLAPI void APIENTRY glProgramUniform1f (GLuint program, GLint location, GLfloat v0); -GLAPI void APIENTRY glProgramUniform1fv (GLuint program, GLint location, GLsizei count, const GLfloat *value); -GLAPI void APIENTRY glProgramUniform1d (GLuint program, GLint location, GLdouble v0); -GLAPI void APIENTRY glProgramUniform1dv (GLuint program, GLint location, GLsizei count, const GLdouble *value); -GLAPI void APIENTRY glProgramUniform1ui (GLuint program, GLint location, GLuint v0); -GLAPI void APIENTRY glProgramUniform1uiv (GLuint program, GLint location, GLsizei count, const GLuint *value); -GLAPI void APIENTRY glProgramUniform2i (GLuint program, GLint location, GLint v0, GLint v1); -GLAPI void APIENTRY glProgramUniform2iv (GLuint program, GLint location, GLsizei count, const GLint *value); -GLAPI void APIENTRY glProgramUniform2f (GLuint program, GLint location, GLfloat v0, GLfloat v1); -GLAPI void APIENTRY glProgramUniform2fv (GLuint program, GLint location, GLsizei count, const GLfloat *value); -GLAPI void APIENTRY glProgramUniform2d (GLuint program, GLint location, GLdouble v0, GLdouble v1); -GLAPI void APIENTRY glProgramUniform2dv (GLuint program, GLint location, GLsizei count, const GLdouble *value); -GLAPI void APIENTRY glProgramUniform2ui (GLuint program, GLint location, GLuint v0, GLuint v1); -GLAPI void APIENTRY glProgramUniform2uiv (GLuint program, GLint location, GLsizei count, const GLuint *value); -GLAPI void APIENTRY glProgramUniform3i (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); -GLAPI void APIENTRY glProgramUniform3iv (GLuint program, GLint location, GLsizei count, const GLint *value); -GLAPI void APIENTRY glProgramUniform3f (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); -GLAPI void APIENTRY glProgramUniform3fv (GLuint program, GLint location, GLsizei count, const GLfloat *value); -GLAPI void APIENTRY glProgramUniform3d (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2); -GLAPI void APIENTRY glProgramUniform3dv (GLuint program, GLint location, GLsizei count, const GLdouble *value); -GLAPI void APIENTRY glProgramUniform3ui (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); -GLAPI void APIENTRY glProgramUniform3uiv (GLuint program, GLint location, GLsizei count, const GLuint *value); -GLAPI void APIENTRY glProgramUniform4i (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); -GLAPI void APIENTRY glProgramUniform4iv (GLuint program, GLint location, GLsizei count, const GLint *value); -GLAPI void APIENTRY glProgramUniform4f (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); -GLAPI void APIENTRY glProgramUniform4fv (GLuint program, GLint location, GLsizei count, const GLfloat *value); -GLAPI void APIENTRY glProgramUniform4d (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3); -GLAPI void APIENTRY glProgramUniform4dv (GLuint program, GLint location, GLsizei count, const GLdouble *value); -GLAPI void APIENTRY glProgramUniform4ui (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); -GLAPI void APIENTRY glProgramUniform4uiv (GLuint program, GLint location, GLsizei count, const GLuint *value); -GLAPI void APIENTRY glProgramUniformMatrix2fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glProgramUniformMatrix3fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glProgramUniformMatrix4fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glProgramUniformMatrix2dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glProgramUniformMatrix3dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glProgramUniformMatrix4dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glProgramUniformMatrix2x3fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glProgramUniformMatrix3x2fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glProgramUniformMatrix2x4fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glProgramUniformMatrix4x2fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glProgramUniformMatrix3x4fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glProgramUniformMatrix4x3fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glProgramUniformMatrix2x3dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glProgramUniformMatrix3x2dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glProgramUniformMatrix2x4dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glProgramUniformMatrix4x2dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glProgramUniformMatrix3x4dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glProgramUniformMatrix4x3dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glValidateProgramPipeline (GLuint pipeline); -GLAPI void APIENTRY glGetProgramPipelineInfoLog (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog); -GLAPI void APIENTRY glVertexAttribL1d (GLuint index, GLdouble x); -GLAPI void APIENTRY glVertexAttribL2d (GLuint index, GLdouble x, GLdouble y); -GLAPI void APIENTRY glVertexAttribL3d (GLuint index, GLdouble x, GLdouble y, GLdouble z); -GLAPI void APIENTRY glVertexAttribL4d (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); -GLAPI void APIENTRY glVertexAttribL1dv (GLuint index, const GLdouble *v); -GLAPI void APIENTRY glVertexAttribL2dv (GLuint index, const GLdouble *v); -GLAPI void APIENTRY glVertexAttribL3dv (GLuint index, const GLdouble *v); -GLAPI void APIENTRY glVertexAttribL4dv (GLuint index, const GLdouble *v); -GLAPI void APIENTRY glVertexAttribLPointer (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); -GLAPI void APIENTRY glGetVertexAttribLdv (GLuint index, GLenum pname, GLdouble *params); -GLAPI void APIENTRY glViewportArrayv (GLuint first, GLsizei count, const GLfloat *v); -GLAPI void APIENTRY glViewportIndexedf (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h); -GLAPI void APIENTRY glViewportIndexedfv (GLuint index, const GLfloat *v); -GLAPI void APIENTRY glScissorArrayv (GLuint first, GLsizei count, const GLint *v); -GLAPI void APIENTRY glScissorIndexed (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height); -GLAPI void APIENTRY glScissorIndexedv (GLuint index, const GLint *v); -GLAPI void APIENTRY glDepthRangeArrayv (GLuint first, GLsizei count, const GLdouble *v); -GLAPI void APIENTRY glDepthRangeIndexed (GLuint index, GLdouble n, GLdouble f); -GLAPI void APIENTRY glGetFloati_v (GLenum target, GLuint index, GLfloat *data); -GLAPI void APIENTRY glGetDoublei_v (GLenum target, GLuint index, GLdouble *data); -#endif -#endif /* GL_VERSION_4_1 */ - -#ifndef GL_VERSION_4_2 -#define GL_VERSION_4_2 1 -#define GL_COPY_READ_BUFFER_BINDING 0x8F36 -#define GL_COPY_WRITE_BUFFER_BINDING 0x8F37 -#define GL_TRANSFORM_FEEDBACK_ACTIVE 0x8E24 -#define GL_TRANSFORM_FEEDBACK_PAUSED 0x8E23 -#define GL_UNPACK_COMPRESSED_BLOCK_WIDTH 0x9127 -#define GL_UNPACK_COMPRESSED_BLOCK_HEIGHT 0x9128 -#define GL_UNPACK_COMPRESSED_BLOCK_DEPTH 0x9129 -#define GL_UNPACK_COMPRESSED_BLOCK_SIZE 0x912A -#define GL_PACK_COMPRESSED_BLOCK_WIDTH 0x912B -#define GL_PACK_COMPRESSED_BLOCK_HEIGHT 0x912C -#define GL_PACK_COMPRESSED_BLOCK_DEPTH 0x912D -#define GL_PACK_COMPRESSED_BLOCK_SIZE 0x912E -#define GL_NUM_SAMPLE_COUNTS 0x9380 -#define GL_MIN_MAP_BUFFER_ALIGNMENT 0x90BC -#define GL_ATOMIC_COUNTER_BUFFER 0x92C0 -#define GL_ATOMIC_COUNTER_BUFFER_BINDING 0x92C1 -#define GL_ATOMIC_COUNTER_BUFFER_START 0x92C2 -#define GL_ATOMIC_COUNTER_BUFFER_SIZE 0x92C3 -#define GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE 0x92C4 -#define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS 0x92C5 -#define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES 0x92C6 -#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER 0x92C7 -#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER 0x92C8 -#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER 0x92C9 -#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER 0x92CA -#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER 0x92CB -#define GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS 0x92CC -#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS 0x92CD -#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS 0x92CE -#define GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS 0x92CF -#define GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS 0x92D0 -#define GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS 0x92D1 -#define GL_MAX_VERTEX_ATOMIC_COUNTERS 0x92D2 -#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS 0x92D3 -#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS 0x92D4 -#define GL_MAX_GEOMETRY_ATOMIC_COUNTERS 0x92D5 -#define GL_MAX_FRAGMENT_ATOMIC_COUNTERS 0x92D6 -#define GL_MAX_COMBINED_ATOMIC_COUNTERS 0x92D7 -#define GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE 0x92D8 -#define GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS 0x92DC -#define GL_ACTIVE_ATOMIC_COUNTER_BUFFERS 0x92D9 -#define GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX 0x92DA -#define GL_UNSIGNED_INT_ATOMIC_COUNTER 0x92DB -#define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001 -#define GL_ELEMENT_ARRAY_BARRIER_BIT 0x00000002 -#define GL_UNIFORM_BARRIER_BIT 0x00000004 -#define GL_TEXTURE_FETCH_BARRIER_BIT 0x00000008 -#define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020 -#define GL_COMMAND_BARRIER_BIT 0x00000040 -#define GL_PIXEL_BUFFER_BARRIER_BIT 0x00000080 -#define GL_TEXTURE_UPDATE_BARRIER_BIT 0x00000100 -#define GL_BUFFER_UPDATE_BARRIER_BIT 0x00000200 -#define GL_FRAMEBUFFER_BARRIER_BIT 0x00000400 -#define GL_TRANSFORM_FEEDBACK_BARRIER_BIT 0x00000800 -#define GL_ATOMIC_COUNTER_BARRIER_BIT 0x00001000 -#define GL_ALL_BARRIER_BITS 0xFFFFFFFF -#define GL_MAX_IMAGE_UNITS 0x8F38 -#define GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS 0x8F39 -#define GL_IMAGE_BINDING_NAME 0x8F3A -#define GL_IMAGE_BINDING_LEVEL 0x8F3B -#define GL_IMAGE_BINDING_LAYERED 0x8F3C -#define GL_IMAGE_BINDING_LAYER 0x8F3D -#define GL_IMAGE_BINDING_ACCESS 0x8F3E -#define GL_IMAGE_1D 0x904C -#define GL_IMAGE_2D 0x904D -#define GL_IMAGE_3D 0x904E -#define GL_IMAGE_2D_RECT 0x904F -#define GL_IMAGE_CUBE 0x9050 -#define GL_IMAGE_BUFFER 0x9051 -#define GL_IMAGE_1D_ARRAY 0x9052 -#define GL_IMAGE_2D_ARRAY 0x9053 -#define GL_IMAGE_CUBE_MAP_ARRAY 0x9054 -#define GL_IMAGE_2D_MULTISAMPLE 0x9055 -#define GL_IMAGE_2D_MULTISAMPLE_ARRAY 0x9056 -#define GL_INT_IMAGE_1D 0x9057 -#define GL_INT_IMAGE_2D 0x9058 -#define GL_INT_IMAGE_3D 0x9059 -#define GL_INT_IMAGE_2D_RECT 0x905A -#define GL_INT_IMAGE_CUBE 0x905B -#define GL_INT_IMAGE_BUFFER 0x905C -#define GL_INT_IMAGE_1D_ARRAY 0x905D -#define GL_INT_IMAGE_2D_ARRAY 0x905E -#define GL_INT_IMAGE_CUBE_MAP_ARRAY 0x905F -#define GL_INT_IMAGE_2D_MULTISAMPLE 0x9060 -#define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x9061 -#define GL_UNSIGNED_INT_IMAGE_1D 0x9062 -#define GL_UNSIGNED_INT_IMAGE_2D 0x9063 -#define GL_UNSIGNED_INT_IMAGE_3D 0x9064 -#define GL_UNSIGNED_INT_IMAGE_2D_RECT 0x9065 -#define GL_UNSIGNED_INT_IMAGE_CUBE 0x9066 -#define GL_UNSIGNED_INT_IMAGE_BUFFER 0x9067 -#define GL_UNSIGNED_INT_IMAGE_1D_ARRAY 0x9068 -#define GL_UNSIGNED_INT_IMAGE_2D_ARRAY 0x9069 -#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY 0x906A -#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE 0x906B -#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x906C -#define GL_MAX_IMAGE_SAMPLES 0x906D -#define GL_IMAGE_BINDING_FORMAT 0x906E -#define GL_IMAGE_FORMAT_COMPATIBILITY_TYPE 0x90C7 -#define GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE 0x90C8 -#define GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS 0x90C9 -#define GL_MAX_VERTEX_IMAGE_UNIFORMS 0x90CA -#define GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS 0x90CB -#define GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS 0x90CC -#define GL_MAX_GEOMETRY_IMAGE_UNIFORMS 0x90CD -#define GL_MAX_FRAGMENT_IMAGE_UNIFORMS 0x90CE -#define GL_MAX_COMBINED_IMAGE_UNIFORMS 0x90CF -#define GL_COMPRESSED_RGBA_BPTC_UNORM 0x8E8C -#define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM 0x8E8D -#define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT 0x8E8E -#define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT 0x8E8F -#define GL_TEXTURE_IMMUTABLE_FORMAT 0x912F -typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC) (GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance); -typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance); -typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance); -typedef void (APIENTRYP PFNGLGETINTERNALFORMATIVPROC) (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params); -typedef void (APIENTRYP PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC) (GLuint program, GLuint bufferIndex, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLBINDIMAGETEXTUREPROC) (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format); -typedef void (APIENTRYP PFNGLMEMORYBARRIERPROC) (GLbitfield barriers); -typedef void (APIENTRYP PFNGLTEXSTORAGE1DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); -typedef void (APIENTRYP PFNGLTEXSTORAGE2DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLTEXSTORAGE3DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); -typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC) (GLenum mode, GLuint id, GLsizei instancecount); -typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC) (GLenum mode, GLuint id, GLuint stream, GLsizei instancecount); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glDrawArraysInstancedBaseInstance (GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance); -GLAPI void APIENTRY glDrawElementsInstancedBaseInstance (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance); -GLAPI void APIENTRY glDrawElementsInstancedBaseVertexBaseInstance (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance); -GLAPI void APIENTRY glGetInternalformativ (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params); -GLAPI void APIENTRY glGetActiveAtomicCounterBufferiv (GLuint program, GLuint bufferIndex, GLenum pname, GLint *params); -GLAPI void APIENTRY glBindImageTexture (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format); -GLAPI void APIENTRY glMemoryBarrier (GLbitfield barriers); -GLAPI void APIENTRY glTexStorage1D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); -GLAPI void APIENTRY glTexStorage2D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); -GLAPI void APIENTRY glTexStorage3D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); -GLAPI void APIENTRY glDrawTransformFeedbackInstanced (GLenum mode, GLuint id, GLsizei instancecount); -GLAPI void APIENTRY glDrawTransformFeedbackStreamInstanced (GLenum mode, GLuint id, GLuint stream, GLsizei instancecount); -#endif -#endif /* GL_VERSION_4_2 */ - -#ifndef GL_VERSION_4_3 -#define GL_VERSION_4_3 1 -typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); -#define GL_NUM_SHADING_LANGUAGE_VERSIONS 0x82E9 -#define GL_VERTEX_ATTRIB_ARRAY_LONG 0x874E -#define GL_COMPRESSED_RGB8_ETC2 0x9274 -#define GL_COMPRESSED_SRGB8_ETC2 0x9275 -#define GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276 -#define GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9277 -#define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 -#define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279 -#define GL_COMPRESSED_R11_EAC 0x9270 -#define GL_COMPRESSED_SIGNED_R11_EAC 0x9271 -#define GL_COMPRESSED_RG11_EAC 0x9272 -#define GL_COMPRESSED_SIGNED_RG11_EAC 0x9273 -#define GL_PRIMITIVE_RESTART_FIXED_INDEX 0x8D69 -#define GL_ANY_SAMPLES_PASSED_CONSERVATIVE 0x8D6A -#define GL_MAX_ELEMENT_INDEX 0x8D6B -#define GL_COMPUTE_SHADER 0x91B9 -#define GL_MAX_COMPUTE_UNIFORM_BLOCKS 0x91BB -#define GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS 0x91BC -#define GL_MAX_COMPUTE_IMAGE_UNIFORMS 0x91BD -#define GL_MAX_COMPUTE_SHARED_MEMORY_SIZE 0x8262 -#define GL_MAX_COMPUTE_UNIFORM_COMPONENTS 0x8263 -#define GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS 0x8264 -#define GL_MAX_COMPUTE_ATOMIC_COUNTERS 0x8265 -#define GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS 0x8266 -#define GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS 0x90EB -#define GL_MAX_COMPUTE_WORK_GROUP_COUNT 0x91BE -#define GL_MAX_COMPUTE_WORK_GROUP_SIZE 0x91BF -#define GL_COMPUTE_WORK_GROUP_SIZE 0x8267 -#define GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER 0x90EC -#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER 0x90ED -#define GL_DISPATCH_INDIRECT_BUFFER 0x90EE -#define GL_DISPATCH_INDIRECT_BUFFER_BINDING 0x90EF -#define GL_COMPUTE_SHADER_BIT 0x00000020 -#define GL_DEBUG_OUTPUT_SYNCHRONOUS 0x8242 -#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH 0x8243 -#define GL_DEBUG_CALLBACK_FUNCTION 0x8244 -#define GL_DEBUG_CALLBACK_USER_PARAM 0x8245 -#define GL_DEBUG_SOURCE_API 0x8246 -#define GL_DEBUG_SOURCE_WINDOW_SYSTEM 0x8247 -#define GL_DEBUG_SOURCE_SHADER_COMPILER 0x8248 -#define GL_DEBUG_SOURCE_THIRD_PARTY 0x8249 -#define GL_DEBUG_SOURCE_APPLICATION 0x824A -#define GL_DEBUG_SOURCE_OTHER 0x824B -#define GL_DEBUG_TYPE_ERROR 0x824C -#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR 0x824D -#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR 0x824E -#define GL_DEBUG_TYPE_PORTABILITY 0x824F -#define GL_DEBUG_TYPE_PERFORMANCE 0x8250 -#define GL_DEBUG_TYPE_OTHER 0x8251 -#define GL_MAX_DEBUG_MESSAGE_LENGTH 0x9143 -#define GL_MAX_DEBUG_LOGGED_MESSAGES 0x9144 -#define GL_DEBUG_LOGGED_MESSAGES 0x9145 -#define GL_DEBUG_SEVERITY_HIGH 0x9146 -#define GL_DEBUG_SEVERITY_MEDIUM 0x9147 -#define GL_DEBUG_SEVERITY_LOW 0x9148 -#define GL_DEBUG_TYPE_MARKER 0x8268 -#define GL_DEBUG_TYPE_PUSH_GROUP 0x8269 -#define GL_DEBUG_TYPE_POP_GROUP 0x826A -#define GL_DEBUG_SEVERITY_NOTIFICATION 0x826B -#define GL_MAX_DEBUG_GROUP_STACK_DEPTH 0x826C -#define GL_DEBUG_GROUP_STACK_DEPTH 0x826D -#define GL_BUFFER 0x82E0 -#define GL_SHADER 0x82E1 -#define GL_PROGRAM 0x82E2 -#define GL_QUERY 0x82E3 -#define GL_PROGRAM_PIPELINE 0x82E4 -#define GL_SAMPLER 0x82E6 -#define GL_MAX_LABEL_LENGTH 0x82E8 -#define GL_DEBUG_OUTPUT 0x92E0 -#define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002 -#define GL_MAX_UNIFORM_LOCATIONS 0x826E -#define GL_FRAMEBUFFER_DEFAULT_WIDTH 0x9310 -#define GL_FRAMEBUFFER_DEFAULT_HEIGHT 0x9311 -#define GL_FRAMEBUFFER_DEFAULT_LAYERS 0x9312 -#define GL_FRAMEBUFFER_DEFAULT_SAMPLES 0x9313 -#define GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS 0x9314 -#define GL_MAX_FRAMEBUFFER_WIDTH 0x9315 -#define GL_MAX_FRAMEBUFFER_HEIGHT 0x9316 -#define GL_MAX_FRAMEBUFFER_LAYERS 0x9317 -#define GL_MAX_FRAMEBUFFER_SAMPLES 0x9318 -#define GL_INTERNALFORMAT_SUPPORTED 0x826F -#define GL_INTERNALFORMAT_PREFERRED 0x8270 -#define GL_INTERNALFORMAT_RED_SIZE 0x8271 -#define GL_INTERNALFORMAT_GREEN_SIZE 0x8272 -#define GL_INTERNALFORMAT_BLUE_SIZE 0x8273 -#define GL_INTERNALFORMAT_ALPHA_SIZE 0x8274 -#define GL_INTERNALFORMAT_DEPTH_SIZE 0x8275 -#define GL_INTERNALFORMAT_STENCIL_SIZE 0x8276 -#define GL_INTERNALFORMAT_SHARED_SIZE 0x8277 -#define GL_INTERNALFORMAT_RED_TYPE 0x8278 -#define GL_INTERNALFORMAT_GREEN_TYPE 0x8279 -#define GL_INTERNALFORMAT_BLUE_TYPE 0x827A -#define GL_INTERNALFORMAT_ALPHA_TYPE 0x827B -#define GL_INTERNALFORMAT_DEPTH_TYPE 0x827C -#define GL_INTERNALFORMAT_STENCIL_TYPE 0x827D -#define GL_MAX_WIDTH 0x827E -#define GL_MAX_HEIGHT 0x827F -#define GL_MAX_DEPTH 0x8280 -#define GL_MAX_LAYERS 0x8281 -#define GL_MAX_COMBINED_DIMENSIONS 0x8282 -#define GL_COLOR_COMPONENTS 0x8283 -#define GL_DEPTH_COMPONENTS 0x8284 -#define GL_STENCIL_COMPONENTS 0x8285 -#define GL_COLOR_RENDERABLE 0x8286 -#define GL_DEPTH_RENDERABLE 0x8287 -#define GL_STENCIL_RENDERABLE 0x8288 -#define GL_FRAMEBUFFER_RENDERABLE 0x8289 -#define GL_FRAMEBUFFER_RENDERABLE_LAYERED 0x828A -#define GL_FRAMEBUFFER_BLEND 0x828B -#define GL_READ_PIXELS 0x828C -#define GL_READ_PIXELS_FORMAT 0x828D -#define GL_READ_PIXELS_TYPE 0x828E -#define GL_TEXTURE_IMAGE_FORMAT 0x828F -#define GL_TEXTURE_IMAGE_TYPE 0x8290 -#define GL_GET_TEXTURE_IMAGE_FORMAT 0x8291 -#define GL_GET_TEXTURE_IMAGE_TYPE 0x8292 -#define GL_MIPMAP 0x8293 -#define GL_MANUAL_GENERATE_MIPMAP 0x8294 -#define GL_AUTO_GENERATE_MIPMAP 0x8295 -#define GL_COLOR_ENCODING 0x8296 -#define GL_SRGB_READ 0x8297 -#define GL_SRGB_WRITE 0x8298 -#define GL_FILTER 0x829A -#define GL_VERTEX_TEXTURE 0x829B -#define GL_TESS_CONTROL_TEXTURE 0x829C -#define GL_TESS_EVALUATION_TEXTURE 0x829D -#define GL_GEOMETRY_TEXTURE 0x829E -#define GL_FRAGMENT_TEXTURE 0x829F -#define GL_COMPUTE_TEXTURE 0x82A0 -#define GL_TEXTURE_SHADOW 0x82A1 -#define GL_TEXTURE_GATHER 0x82A2 -#define GL_TEXTURE_GATHER_SHADOW 0x82A3 -#define GL_SHADER_IMAGE_LOAD 0x82A4 -#define GL_SHADER_IMAGE_STORE 0x82A5 -#define GL_SHADER_IMAGE_ATOMIC 0x82A6 -#define GL_IMAGE_TEXEL_SIZE 0x82A7 -#define GL_IMAGE_COMPATIBILITY_CLASS 0x82A8 -#define GL_IMAGE_PIXEL_FORMAT 0x82A9 -#define GL_IMAGE_PIXEL_TYPE 0x82AA -#define GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST 0x82AC -#define GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST 0x82AD -#define GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE 0x82AE -#define GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE 0x82AF -#define GL_TEXTURE_COMPRESSED_BLOCK_WIDTH 0x82B1 -#define GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT 0x82B2 -#define GL_TEXTURE_COMPRESSED_BLOCK_SIZE 0x82B3 -#define GL_CLEAR_BUFFER 0x82B4 -#define GL_TEXTURE_VIEW 0x82B5 -#define GL_VIEW_COMPATIBILITY_CLASS 0x82B6 -#define GL_FULL_SUPPORT 0x82B7 -#define GL_CAVEAT_SUPPORT 0x82B8 -#define GL_IMAGE_CLASS_4_X_32 0x82B9 -#define GL_IMAGE_CLASS_2_X_32 0x82BA -#define GL_IMAGE_CLASS_1_X_32 0x82BB -#define GL_IMAGE_CLASS_4_X_16 0x82BC -#define GL_IMAGE_CLASS_2_X_16 0x82BD -#define GL_IMAGE_CLASS_1_X_16 0x82BE -#define GL_IMAGE_CLASS_4_X_8 0x82BF -#define GL_IMAGE_CLASS_2_X_8 0x82C0 -#define GL_IMAGE_CLASS_1_X_8 0x82C1 -#define GL_IMAGE_CLASS_11_11_10 0x82C2 -#define GL_IMAGE_CLASS_10_10_10_2 0x82C3 -#define GL_VIEW_CLASS_128_BITS 0x82C4 -#define GL_VIEW_CLASS_96_BITS 0x82C5 -#define GL_VIEW_CLASS_64_BITS 0x82C6 -#define GL_VIEW_CLASS_48_BITS 0x82C7 -#define GL_VIEW_CLASS_32_BITS 0x82C8 -#define GL_VIEW_CLASS_24_BITS 0x82C9 -#define GL_VIEW_CLASS_16_BITS 0x82CA -#define GL_VIEW_CLASS_8_BITS 0x82CB -#define GL_VIEW_CLASS_S3TC_DXT1_RGB 0x82CC -#define GL_VIEW_CLASS_S3TC_DXT1_RGBA 0x82CD -#define GL_VIEW_CLASS_S3TC_DXT3_RGBA 0x82CE -#define GL_VIEW_CLASS_S3TC_DXT5_RGBA 0x82CF -#define GL_VIEW_CLASS_RGTC1_RED 0x82D0 -#define GL_VIEW_CLASS_RGTC2_RG 0x82D1 -#define GL_VIEW_CLASS_BPTC_UNORM 0x82D2 -#define GL_VIEW_CLASS_BPTC_FLOAT 0x82D3 -#define GL_UNIFORM 0x92E1 -#define GL_UNIFORM_BLOCK 0x92E2 -#define GL_PROGRAM_INPUT 0x92E3 -#define GL_PROGRAM_OUTPUT 0x92E4 -#define GL_BUFFER_VARIABLE 0x92E5 -#define GL_SHADER_STORAGE_BLOCK 0x92E6 -#define GL_VERTEX_SUBROUTINE 0x92E8 -#define GL_TESS_CONTROL_SUBROUTINE 0x92E9 -#define GL_TESS_EVALUATION_SUBROUTINE 0x92EA -#define GL_GEOMETRY_SUBROUTINE 0x92EB -#define GL_FRAGMENT_SUBROUTINE 0x92EC -#define GL_COMPUTE_SUBROUTINE 0x92ED -#define GL_VERTEX_SUBROUTINE_UNIFORM 0x92EE -#define GL_TESS_CONTROL_SUBROUTINE_UNIFORM 0x92EF -#define GL_TESS_EVALUATION_SUBROUTINE_UNIFORM 0x92F0 -#define GL_GEOMETRY_SUBROUTINE_UNIFORM 0x92F1 -#define GL_FRAGMENT_SUBROUTINE_UNIFORM 0x92F2 -#define GL_COMPUTE_SUBROUTINE_UNIFORM 0x92F3 -#define GL_TRANSFORM_FEEDBACK_VARYING 0x92F4 -#define GL_ACTIVE_RESOURCES 0x92F5 -#define GL_MAX_NAME_LENGTH 0x92F6 -#define GL_MAX_NUM_ACTIVE_VARIABLES 0x92F7 -#define GL_MAX_NUM_COMPATIBLE_SUBROUTINES 0x92F8 -#define GL_NAME_LENGTH 0x92F9 -#define GL_TYPE 0x92FA -#define GL_ARRAY_SIZE 0x92FB -#define GL_OFFSET 0x92FC -#define GL_BLOCK_INDEX 0x92FD -#define GL_ARRAY_STRIDE 0x92FE -#define GL_MATRIX_STRIDE 0x92FF -#define GL_IS_ROW_MAJOR 0x9300 -#define GL_ATOMIC_COUNTER_BUFFER_INDEX 0x9301 -#define GL_BUFFER_BINDING 0x9302 -#define GL_BUFFER_DATA_SIZE 0x9303 -#define GL_NUM_ACTIVE_VARIABLES 0x9304 -#define GL_ACTIVE_VARIABLES 0x9305 -#define GL_REFERENCED_BY_VERTEX_SHADER 0x9306 -#define GL_REFERENCED_BY_TESS_CONTROL_SHADER 0x9307 -#define GL_REFERENCED_BY_TESS_EVALUATION_SHADER 0x9308 -#define GL_REFERENCED_BY_GEOMETRY_SHADER 0x9309 -#define GL_REFERENCED_BY_FRAGMENT_SHADER 0x930A -#define GL_REFERENCED_BY_COMPUTE_SHADER 0x930B -#define GL_TOP_LEVEL_ARRAY_SIZE 0x930C -#define GL_TOP_LEVEL_ARRAY_STRIDE 0x930D -#define GL_LOCATION 0x930E -#define GL_LOCATION_INDEX 0x930F -#define GL_IS_PER_PATCH 0x92E7 -#define GL_SHADER_STORAGE_BUFFER 0x90D2 -#define GL_SHADER_STORAGE_BUFFER_BINDING 0x90D3 -#define GL_SHADER_STORAGE_BUFFER_START 0x90D4 -#define GL_SHADER_STORAGE_BUFFER_SIZE 0x90D5 -#define GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS 0x90D6 -#define GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS 0x90D7 -#define GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS 0x90D8 -#define GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS 0x90D9 -#define GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS 0x90DA -#define GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS 0x90DB -#define GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS 0x90DC -#define GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS 0x90DD -#define GL_MAX_SHADER_STORAGE_BLOCK_SIZE 0x90DE -#define GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT 0x90DF -#define GL_SHADER_STORAGE_BARRIER_BIT 0x00002000 -#define GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES 0x8F39 -#define GL_DEPTH_STENCIL_TEXTURE_MODE 0x90EA -#define GL_TEXTURE_BUFFER_OFFSET 0x919D -#define GL_TEXTURE_BUFFER_SIZE 0x919E -#define GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT 0x919F -#define GL_TEXTURE_VIEW_MIN_LEVEL 0x82DB -#define GL_TEXTURE_VIEW_NUM_LEVELS 0x82DC -#define GL_TEXTURE_VIEW_MIN_LAYER 0x82DD -#define GL_TEXTURE_VIEW_NUM_LAYERS 0x82DE -#define GL_TEXTURE_IMMUTABLE_LEVELS 0x82DF -#define GL_VERTEX_ATTRIB_BINDING 0x82D4 -#define GL_VERTEX_ATTRIB_RELATIVE_OFFSET 0x82D5 -#define GL_VERTEX_BINDING_DIVISOR 0x82D6 -#define GL_VERTEX_BINDING_OFFSET 0x82D7 -#define GL_VERTEX_BINDING_STRIDE 0x82D8 -#define GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET 0x82D9 -#define GL_MAX_VERTEX_ATTRIB_BINDINGS 0x82DA -#define GL_VERTEX_BINDING_BUFFER 0x8F4F -typedef void (APIENTRYP PFNGLCLEARBUFFERDATAPROC) (GLenum target, GLenum internalformat, GLenum format, GLenum type, const void *data); -typedef void (APIENTRYP PFNGLCLEARBUFFERSUBDATAPROC) (GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); -typedef void (APIENTRYP PFNGLDISPATCHCOMPUTEPROC) (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z); -typedef void (APIENTRYP PFNGLDISPATCHCOMPUTEINDIRECTPROC) (GLintptr indirect); -typedef void (APIENTRYP PFNGLCOPYIMAGESUBDATAPROC) (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); -typedef void (APIENTRYP PFNGLFRAMEBUFFERPARAMETERIPROC) (GLenum target, GLenum pname, GLint param); -typedef void (APIENTRYP PFNGLGETFRAMEBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETINTERNALFORMATI64VPROC) (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint64 *params); -typedef void (APIENTRYP PFNGLINVALIDATETEXSUBIMAGEPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth); -typedef void (APIENTRYP PFNGLINVALIDATETEXIMAGEPROC) (GLuint texture, GLint level); -typedef void (APIENTRYP PFNGLINVALIDATEBUFFERSUBDATAPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length); -typedef void (APIENTRYP PFNGLINVALIDATEBUFFERDATAPROC) (GLuint buffer); -typedef void (APIENTRYP PFNGLINVALIDATEFRAMEBUFFERPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments); -typedef void (APIENTRYP PFNGLINVALIDATESUBFRAMEBUFFERPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTPROC) (GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride); -typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei drawcount, GLsizei stride); -typedef void (APIENTRYP PFNGLGETPROGRAMINTERFACEIVPROC) (GLuint program, GLenum programInterface, GLenum pname, GLint *params); -typedef GLuint (APIENTRYP PFNGLGETPROGRAMRESOURCEINDEXPROC) (GLuint program, GLenum programInterface, const GLchar *name); -typedef void (APIENTRYP PFNGLGETPROGRAMRESOURCENAMEPROC) (GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); -typedef void (APIENTRYP PFNGLGETPROGRAMRESOURCEIVPROC) (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLint *params); -typedef GLint (APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONPROC) (GLuint program, GLenum programInterface, const GLchar *name); -typedef GLint (APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC) (GLuint program, GLenum programInterface, const GLchar *name); -typedef void (APIENTRYP PFNGLSHADERSTORAGEBLOCKBINDINGPROC) (GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding); -typedef void (APIENTRYP PFNGLTEXBUFFERRANGEPROC) (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); -typedef void (APIENTRYP PFNGLTEXSTORAGE2DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); -typedef void (APIENTRYP PFNGLTEXSTORAGE3DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); -typedef void (APIENTRYP PFNGLTEXTUREVIEWPROC) (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); -typedef void (APIENTRYP PFNGLBINDVERTEXBUFFERPROC) (GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); -typedef void (APIENTRYP PFNGLVERTEXATTRIBFORMATPROC) (GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); -typedef void (APIENTRYP PFNGLVERTEXATTRIBIFORMATPROC) (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); -typedef void (APIENTRYP PFNGLVERTEXATTRIBLFORMATPROC) (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); -typedef void (APIENTRYP PFNGLVERTEXATTRIBBINDINGPROC) (GLuint attribindex, GLuint bindingindex); -typedef void (APIENTRYP PFNGLVERTEXBINDINGDIVISORPROC) (GLuint bindingindex, GLuint divisor); -typedef void (APIENTRYP PFNGLDEBUGMESSAGECONTROLPROC) (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); -typedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTPROC) (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); -typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKPROC) (GLDEBUGPROC callback, const void *userParam); -typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGPROC) (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); -typedef void (APIENTRYP PFNGLPUSHDEBUGGROUPPROC) (GLenum source, GLuint id, GLsizei length, const GLchar *message); -typedef void (APIENTRYP PFNGLPOPDEBUGGROUPPROC) (void); -typedef void (APIENTRYP PFNGLOBJECTLABELPROC) (GLenum identifier, GLuint name, GLsizei length, const GLchar *label); -typedef void (APIENTRYP PFNGLGETOBJECTLABELPROC) (GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label); -typedef void (APIENTRYP PFNGLOBJECTPTRLABELPROC) (const void *ptr, GLsizei length, const GLchar *label); -typedef void (APIENTRYP PFNGLGETOBJECTPTRLABELPROC) (const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glClearBufferData (GLenum target, GLenum internalformat, GLenum format, GLenum type, const void *data); -GLAPI void APIENTRY glClearBufferSubData (GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); -GLAPI void APIENTRY glDispatchCompute (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z); -GLAPI void APIENTRY glDispatchComputeIndirect (GLintptr indirect); -GLAPI void APIENTRY glCopyImageSubData (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); -GLAPI void APIENTRY glFramebufferParameteri (GLenum target, GLenum pname, GLint param); -GLAPI void APIENTRY glGetFramebufferParameteriv (GLenum target, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetInternalformati64v (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint64 *params); -GLAPI void APIENTRY glInvalidateTexSubImage (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth); -GLAPI void APIENTRY glInvalidateTexImage (GLuint texture, GLint level); -GLAPI void APIENTRY glInvalidateBufferSubData (GLuint buffer, GLintptr offset, GLsizeiptr length); -GLAPI void APIENTRY glInvalidateBufferData (GLuint buffer); -GLAPI void APIENTRY glInvalidateFramebuffer (GLenum target, GLsizei numAttachments, const GLenum *attachments); -GLAPI void APIENTRY glInvalidateSubFramebuffer (GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); -GLAPI void APIENTRY glMultiDrawArraysIndirect (GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride); -GLAPI void APIENTRY glMultiDrawElementsIndirect (GLenum mode, GLenum type, const void *indirect, GLsizei drawcount, GLsizei stride); -GLAPI void APIENTRY glGetProgramInterfaceiv (GLuint program, GLenum programInterface, GLenum pname, GLint *params); -GLAPI GLuint APIENTRY glGetProgramResourceIndex (GLuint program, GLenum programInterface, const GLchar *name); -GLAPI void APIENTRY glGetProgramResourceName (GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); -GLAPI void APIENTRY glGetProgramResourceiv (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLint *params); -GLAPI GLint APIENTRY glGetProgramResourceLocation (GLuint program, GLenum programInterface, const GLchar *name); -GLAPI GLint APIENTRY glGetProgramResourceLocationIndex (GLuint program, GLenum programInterface, const GLchar *name); -GLAPI void APIENTRY glShaderStorageBlockBinding (GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding); -GLAPI void APIENTRY glTexBufferRange (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); -GLAPI void APIENTRY glTexStorage2DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); -GLAPI void APIENTRY glTexStorage3DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); -GLAPI void APIENTRY glTextureView (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); -GLAPI void APIENTRY glBindVertexBuffer (GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); -GLAPI void APIENTRY glVertexAttribFormat (GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); -GLAPI void APIENTRY glVertexAttribIFormat (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); -GLAPI void APIENTRY glVertexAttribLFormat (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); -GLAPI void APIENTRY glVertexAttribBinding (GLuint attribindex, GLuint bindingindex); -GLAPI void APIENTRY glVertexBindingDivisor (GLuint bindingindex, GLuint divisor); -GLAPI void APIENTRY glDebugMessageControl (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); -GLAPI void APIENTRY glDebugMessageInsert (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); -GLAPI void APIENTRY glDebugMessageCallback (GLDEBUGPROC callback, const void *userParam); -GLAPI GLuint APIENTRY glGetDebugMessageLog (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); -GLAPI void APIENTRY glPushDebugGroup (GLenum source, GLuint id, GLsizei length, const GLchar *message); -GLAPI void APIENTRY glPopDebugGroup (void); -GLAPI void APIENTRY glObjectLabel (GLenum identifier, GLuint name, GLsizei length, const GLchar *label); -GLAPI void APIENTRY glGetObjectLabel (GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label); -GLAPI void APIENTRY glObjectPtrLabel (const void *ptr, GLsizei length, const GLchar *label); -GLAPI void APIENTRY glGetObjectPtrLabel (const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label); -#endif -#endif /* GL_VERSION_4_3 */ - -#ifndef GL_VERSION_4_4 -#define GL_VERSION_4_4 1 -#define GL_MAX_VERTEX_ATTRIB_STRIDE 0x82E5 -#define GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED 0x8221 -#define GL_TEXTURE_BUFFER_BINDING 0x8C2A -#define GL_MAP_PERSISTENT_BIT 0x0040 -#define GL_MAP_COHERENT_BIT 0x0080 -#define GL_DYNAMIC_STORAGE_BIT 0x0100 -#define GL_CLIENT_STORAGE_BIT 0x0200 -#define GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT 0x00004000 -#define GL_BUFFER_IMMUTABLE_STORAGE 0x821F -#define GL_BUFFER_STORAGE_FLAGS 0x8220 -#define GL_CLEAR_TEXTURE 0x9365 -#define GL_LOCATION_COMPONENT 0x934A -#define GL_TRANSFORM_FEEDBACK_BUFFER_INDEX 0x934B -#define GL_TRANSFORM_FEEDBACK_BUFFER_STRIDE 0x934C -#define GL_QUERY_BUFFER 0x9192 -#define GL_QUERY_BUFFER_BARRIER_BIT 0x00008000 -#define GL_QUERY_BUFFER_BINDING 0x9193 -#define GL_QUERY_RESULT_NO_WAIT 0x9194 -#define GL_MIRROR_CLAMP_TO_EDGE 0x8743 -typedef void (APIENTRYP PFNGLBUFFERSTORAGEPROC) (GLenum target, GLsizeiptr size, const void *data, GLbitfield flags); -typedef void (APIENTRYP PFNGLCLEARTEXIMAGEPROC) (GLuint texture, GLint level, GLenum format, GLenum type, const void *data); -typedef void (APIENTRYP PFNGLCLEARTEXSUBIMAGEPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *data); -typedef void (APIENTRYP PFNGLBINDBUFFERSBASEPROC) (GLenum target, GLuint first, GLsizei count, const GLuint *buffers); -typedef void (APIENTRYP PFNGLBINDBUFFERSRANGEPROC) (GLenum target, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizeiptr *sizes); -typedef void (APIENTRYP PFNGLBINDTEXTURESPROC) (GLuint first, GLsizei count, const GLuint *textures); -typedef void (APIENTRYP PFNGLBINDSAMPLERSPROC) (GLuint first, GLsizei count, const GLuint *samplers); -typedef void (APIENTRYP PFNGLBINDIMAGETEXTURESPROC) (GLuint first, GLsizei count, const GLuint *textures); -typedef void (APIENTRYP PFNGLBINDVERTEXBUFFERSPROC) (GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glBufferStorage (GLenum target, GLsizeiptr size, const void *data, GLbitfield flags); -GLAPI void APIENTRY glClearTexImage (GLuint texture, GLint level, GLenum format, GLenum type, const void *data); -GLAPI void APIENTRY glClearTexSubImage (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *data); -GLAPI void APIENTRY glBindBuffersBase (GLenum target, GLuint first, GLsizei count, const GLuint *buffers); -GLAPI void APIENTRY glBindBuffersRange (GLenum target, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizeiptr *sizes); -GLAPI void APIENTRY glBindTextures (GLuint first, GLsizei count, const GLuint *textures); -GLAPI void APIENTRY glBindSamplers (GLuint first, GLsizei count, const GLuint *samplers); -GLAPI void APIENTRY glBindImageTextures (GLuint first, GLsizei count, const GLuint *textures); -GLAPI void APIENTRY glBindVertexBuffers (GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); -#endif -#endif /* GL_VERSION_4_4 */ - -#ifndef GL_VERSION_4_5 -#define GL_VERSION_4_5 1 -#define GL_CONTEXT_LOST 0x0507 -#define GL_NEGATIVE_ONE_TO_ONE 0x935E -#define GL_ZERO_TO_ONE 0x935F -#define GL_CLIP_ORIGIN 0x935C -#define GL_CLIP_DEPTH_MODE 0x935D -#define GL_QUERY_WAIT_INVERTED 0x8E17 -#define GL_QUERY_NO_WAIT_INVERTED 0x8E18 -#define GL_QUERY_BY_REGION_WAIT_INVERTED 0x8E19 -#define GL_QUERY_BY_REGION_NO_WAIT_INVERTED 0x8E1A -#define GL_MAX_CULL_DISTANCES 0x82F9 -#define GL_MAX_COMBINED_CLIP_AND_CULL_DISTANCES 0x82FA -#define GL_TEXTURE_TARGET 0x1006 -#define GL_QUERY_TARGET 0x82EA -#define GL_GUILTY_CONTEXT_RESET 0x8253 -#define GL_INNOCENT_CONTEXT_RESET 0x8254 -#define GL_UNKNOWN_CONTEXT_RESET 0x8255 -#define GL_RESET_NOTIFICATION_STRATEGY 0x8256 -#define GL_LOSE_CONTEXT_ON_RESET 0x8252 -#define GL_NO_RESET_NOTIFICATION 0x8261 -#define GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT 0x00000004 -#define GL_CONTEXT_RELEASE_BEHAVIOR 0x82FB -#define GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH 0x82FC -typedef void (APIENTRYP PFNGLCLIPCONTROLPROC) (GLenum origin, GLenum depth); -typedef void (APIENTRYP PFNGLCREATETRANSFORMFEEDBACKSPROC) (GLsizei n, GLuint *ids); -typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKBUFFERBASEPROC) (GLuint xfb, GLuint index, GLuint buffer); -typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKBUFFERRANGEPROC) (GLuint xfb, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); -typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKIVPROC) (GLuint xfb, GLenum pname, GLint *param); -typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint *param); -typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI64_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint64 *param); -typedef void (APIENTRYP PFNGLCREATEBUFFERSPROC) (GLsizei n, GLuint *buffers); -typedef void (APIENTRYP PFNGLNAMEDBUFFERSTORAGEPROC) (GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags); -typedef void (APIENTRYP PFNGLNAMEDBUFFERDATAPROC) (GLuint buffer, GLsizeiptr size, const void *data, GLenum usage); -typedef void (APIENTRYP PFNGLNAMEDBUFFERSUBDATAPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); -typedef void (APIENTRYP PFNGLCOPYNAMEDBUFFERSUBDATAPROC) (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); -typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERDATAPROC) (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data); -typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERSUBDATAPROC) (GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); -typedef void *(APIENTRYP PFNGLMAPNAMEDBUFFERPROC) (GLuint buffer, GLenum access); -typedef void *(APIENTRYP PFNGLMAPNAMEDBUFFERRANGEPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access); -typedef GLboolean (APIENTRYP PFNGLUNMAPNAMEDBUFFERPROC) (GLuint buffer); -typedef void (APIENTRYP PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length); -typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERIVPROC) (GLuint buffer, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERI64VPROC) (GLuint buffer, GLenum pname, GLint64 *params); -typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPOINTERVPROC) (GLuint buffer, GLenum pname, void **params); -typedef void (APIENTRYP PFNGLGETNAMEDBUFFERSUBDATAPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, void *data); -typedef void (APIENTRYP PFNGLCREATEFRAMEBUFFERSPROC) (GLsizei n, GLuint *framebuffers); -typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERRENDERBUFFERPROC) (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); -typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERPARAMETERIPROC) (GLuint framebuffer, GLenum pname, GLint param); -typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTUREPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); -typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURELAYERPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); -typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERDRAWBUFFERPROC) (GLuint framebuffer, GLenum buf); -typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERDRAWBUFFERSPROC) (GLuint framebuffer, GLsizei n, const GLenum *bufs); -typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERREADBUFFERPROC) (GLuint framebuffer, GLenum src); -typedef void (APIENTRYP PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC) (GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments); -typedef void (APIENTRYP PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC) (GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERIVPROC) (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLint *value); -typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERUIVPROC) (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLuint *value); -typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERFVPROC) (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLfloat *value); -typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERFIPROC) (GLuint framebuffer, GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); -typedef void (APIENTRYP PFNGLBLITNAMEDFRAMEBUFFERPROC) (GLuint readFramebuffer, GLuint drawFramebuffer, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); -typedef GLenum (APIENTRYP PFNGLCHECKNAMEDFRAMEBUFFERSTATUSPROC) (GLuint framebuffer, GLenum target); -typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVPROC) (GLuint framebuffer, GLenum pname, GLint *param); -typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC) (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLCREATERENDERBUFFERSPROC) (GLsizei n, GLuint *renderbuffers); -typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEPROC) (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC) (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLGETNAMEDRENDERBUFFERPARAMETERIVPROC) (GLuint renderbuffer, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLCREATETEXTURESPROC) (GLenum target, GLsizei n, GLuint *textures); -typedef void (APIENTRYP PFNGLTEXTUREBUFFERPROC) (GLuint texture, GLenum internalformat, GLuint buffer); -typedef void (APIENTRYP PFNGLTEXTUREBUFFERRANGEPROC) (GLuint texture, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); -typedef void (APIENTRYP PFNGLTEXTURESTORAGE1DPROC) (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width); -typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DPROC) (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DPROC) (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); -typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC) (GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); -typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC) (GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); -typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE1DPROC) (GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE2DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE3DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC) (GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); -typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE1DPROC) (GLuint texture, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); -typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE2DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE3DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFPROC) (GLuint texture, GLenum pname, GLfloat param); -typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFVPROC) (GLuint texture, GLenum pname, const GLfloat *param); -typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIPROC) (GLuint texture, GLenum pname, GLint param); -typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIIVPROC) (GLuint texture, GLenum pname, const GLint *params); -typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIUIVPROC) (GLuint texture, GLenum pname, const GLuint *params); -typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIVPROC) (GLuint texture, GLenum pname, const GLint *param); -typedef void (APIENTRYP PFNGLGENERATETEXTUREMIPMAPPROC) (GLuint texture); -typedef void (APIENTRYP PFNGLBINDTEXTUREUNITPROC) (GLuint unit, GLuint texture); -typedef void (APIENTRYP PFNGLGETTEXTUREIMAGEPROC) (GLuint texture, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); -typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXTUREIMAGEPROC) (GLuint texture, GLint level, GLsizei bufSize, void *pixels); -typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERFVPROC) (GLuint texture, GLint level, GLenum pname, GLfloat *params); -typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERIVPROC) (GLuint texture, GLint level, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERFVPROC) (GLuint texture, GLenum pname, GLfloat *params); -typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIIVPROC) (GLuint texture, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIUIVPROC) (GLuint texture, GLenum pname, GLuint *params); -typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIVPROC) (GLuint texture, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLCREATEVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays); -typedef void (APIENTRYP PFNGLDISABLEVERTEXARRAYATTRIBPROC) (GLuint vaobj, GLuint index); -typedef void (APIENTRYP PFNGLENABLEVERTEXARRAYATTRIBPROC) (GLuint vaobj, GLuint index); -typedef void (APIENTRYP PFNGLVERTEXARRAYELEMENTBUFFERPROC) (GLuint vaobj, GLuint buffer); -typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXBUFFERPROC) (GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); -typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXBUFFERSPROC) (GLuint vaobj, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); -typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBBINDINGPROC) (GLuint vaobj, GLuint attribindex, GLuint bindingindex); -typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBFORMATPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); -typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBIFORMATPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); -typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBLFORMATPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); -typedef void (APIENTRYP PFNGLVERTEXARRAYBINDINGDIVISORPROC) (GLuint vaobj, GLuint bindingindex, GLuint divisor); -typedef void (APIENTRYP PFNGLGETVERTEXARRAYIVPROC) (GLuint vaobj, GLenum pname, GLint *param); -typedef void (APIENTRYP PFNGLGETVERTEXARRAYINDEXEDIVPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint *param); -typedef void (APIENTRYP PFNGLGETVERTEXARRAYINDEXED64IVPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint64 *param); -typedef void (APIENTRYP PFNGLCREATESAMPLERSPROC) (GLsizei n, GLuint *samplers); -typedef void (APIENTRYP PFNGLCREATEPROGRAMPIPELINESPROC) (GLsizei n, GLuint *pipelines); -typedef void (APIENTRYP PFNGLCREATEQUERIESPROC) (GLenum target, GLsizei n, GLuint *ids); -typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTI64VPROC) (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); -typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTIVPROC) (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); -typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTUI64VPROC) (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); -typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTUIVPROC) (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); -typedef void (APIENTRYP PFNGLMEMORYBARRIERBYREGIONPROC) (GLbitfield barriers); -typedef void (APIENTRYP PFNGLGETTEXTURESUBIMAGEPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLsizei bufSize, void *pixels); -typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei bufSize, void *pixels); -typedef GLenum (APIENTRYP PFNGLGETGRAPHICSRESETSTATUSPROC) (void); -typedef void (APIENTRYP PFNGLGETNCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint lod, GLsizei bufSize, void *pixels); -typedef void (APIENTRYP PFNGLGETNTEXIMAGEPROC) (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); -typedef void (APIENTRYP PFNGLGETNUNIFORMDVPROC) (GLuint program, GLint location, GLsizei bufSize, GLdouble *params); -typedef void (APIENTRYP PFNGLGETNUNIFORMFVPROC) (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); -typedef void (APIENTRYP PFNGLGETNUNIFORMIVPROC) (GLuint program, GLint location, GLsizei bufSize, GLint *params); -typedef void (APIENTRYP PFNGLGETNUNIFORMUIVPROC) (GLuint program, GLint location, GLsizei bufSize, GLuint *params); -typedef void (APIENTRYP PFNGLREADNPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); -typedef void (APIENTRYP PFNGLTEXTUREBARRIERPROC) (void); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glClipControl (GLenum origin, GLenum depth); -GLAPI void APIENTRY glCreateTransformFeedbacks (GLsizei n, GLuint *ids); -GLAPI void APIENTRY glTransformFeedbackBufferBase (GLuint xfb, GLuint index, GLuint buffer); -GLAPI void APIENTRY glTransformFeedbackBufferRange (GLuint xfb, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); -GLAPI void APIENTRY glGetTransformFeedbackiv (GLuint xfb, GLenum pname, GLint *param); -GLAPI void APIENTRY glGetTransformFeedbacki_v (GLuint xfb, GLenum pname, GLuint index, GLint *param); -GLAPI void APIENTRY glGetTransformFeedbacki64_v (GLuint xfb, GLenum pname, GLuint index, GLint64 *param); -GLAPI void APIENTRY glCreateBuffers (GLsizei n, GLuint *buffers); -GLAPI void APIENTRY glNamedBufferStorage (GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags); -GLAPI void APIENTRY glNamedBufferData (GLuint buffer, GLsizeiptr size, const void *data, GLenum usage); -GLAPI void APIENTRY glNamedBufferSubData (GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); -GLAPI void APIENTRY glCopyNamedBufferSubData (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); -GLAPI void APIENTRY glClearNamedBufferData (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data); -GLAPI void APIENTRY glClearNamedBufferSubData (GLuint buffer, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); -GLAPI void *APIENTRY glMapNamedBuffer (GLuint buffer, GLenum access); -GLAPI void *APIENTRY glMapNamedBufferRange (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access); -GLAPI GLboolean APIENTRY glUnmapNamedBuffer (GLuint buffer); -GLAPI void APIENTRY glFlushMappedNamedBufferRange (GLuint buffer, GLintptr offset, GLsizeiptr length); -GLAPI void APIENTRY glGetNamedBufferParameteriv (GLuint buffer, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetNamedBufferParameteri64v (GLuint buffer, GLenum pname, GLint64 *params); -GLAPI void APIENTRY glGetNamedBufferPointerv (GLuint buffer, GLenum pname, void **params); -GLAPI void APIENTRY glGetNamedBufferSubData (GLuint buffer, GLintptr offset, GLsizeiptr size, void *data); -GLAPI void APIENTRY glCreateFramebuffers (GLsizei n, GLuint *framebuffers); -GLAPI void APIENTRY glNamedFramebufferRenderbuffer (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); -GLAPI void APIENTRY glNamedFramebufferParameteri (GLuint framebuffer, GLenum pname, GLint param); -GLAPI void APIENTRY glNamedFramebufferTexture (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); -GLAPI void APIENTRY glNamedFramebufferTextureLayer (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); -GLAPI void APIENTRY glNamedFramebufferDrawBuffer (GLuint framebuffer, GLenum buf); -GLAPI void APIENTRY glNamedFramebufferDrawBuffers (GLuint framebuffer, GLsizei n, const GLenum *bufs); -GLAPI void APIENTRY glNamedFramebufferReadBuffer (GLuint framebuffer, GLenum src); -GLAPI void APIENTRY glInvalidateNamedFramebufferData (GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments); -GLAPI void APIENTRY glInvalidateNamedFramebufferSubData (GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); -GLAPI void APIENTRY glClearNamedFramebufferiv (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLint *value); -GLAPI void APIENTRY glClearNamedFramebufferuiv (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLuint *value); -GLAPI void APIENTRY glClearNamedFramebufferfv (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLfloat *value); -GLAPI void APIENTRY glClearNamedFramebufferfi (GLuint framebuffer, GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); -GLAPI void APIENTRY glBlitNamedFramebuffer (GLuint readFramebuffer, GLuint drawFramebuffer, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); -GLAPI GLenum APIENTRY glCheckNamedFramebufferStatus (GLuint framebuffer, GLenum target); -GLAPI void APIENTRY glGetNamedFramebufferParameteriv (GLuint framebuffer, GLenum pname, GLint *param); -GLAPI void APIENTRY glGetNamedFramebufferAttachmentParameteriv (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params); -GLAPI void APIENTRY glCreateRenderbuffers (GLsizei n, GLuint *renderbuffers); -GLAPI void APIENTRY glNamedRenderbufferStorage (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); -GLAPI void APIENTRY glNamedRenderbufferStorageMultisample (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -GLAPI void APIENTRY glGetNamedRenderbufferParameteriv (GLuint renderbuffer, GLenum pname, GLint *params); -GLAPI void APIENTRY glCreateTextures (GLenum target, GLsizei n, GLuint *textures); -GLAPI void APIENTRY glTextureBuffer (GLuint texture, GLenum internalformat, GLuint buffer); -GLAPI void APIENTRY glTextureBufferRange (GLuint texture, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); -GLAPI void APIENTRY glTextureStorage1D (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width); -GLAPI void APIENTRY glTextureStorage2D (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); -GLAPI void APIENTRY glTextureStorage3D (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); -GLAPI void APIENTRY glTextureStorage2DMultisample (GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); -GLAPI void APIENTRY glTextureStorage3DMultisample (GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); -GLAPI void APIENTRY glTextureSubImage1D (GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glTextureSubImage2D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glTextureSubImage3D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glCompressedTextureSubImage1D (GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); -GLAPI void APIENTRY glCompressedTextureSubImage2D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); -GLAPI void APIENTRY glCompressedTextureSubImage3D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); -GLAPI void APIENTRY glCopyTextureSubImage1D (GLuint texture, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); -GLAPI void APIENTRY glCopyTextureSubImage2D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); -GLAPI void APIENTRY glCopyTextureSubImage3D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); -GLAPI void APIENTRY glTextureParameterf (GLuint texture, GLenum pname, GLfloat param); -GLAPI void APIENTRY glTextureParameterfv (GLuint texture, GLenum pname, const GLfloat *param); -GLAPI void APIENTRY glTextureParameteri (GLuint texture, GLenum pname, GLint param); -GLAPI void APIENTRY glTextureParameterIiv (GLuint texture, GLenum pname, const GLint *params); -GLAPI void APIENTRY glTextureParameterIuiv (GLuint texture, GLenum pname, const GLuint *params); -GLAPI void APIENTRY glTextureParameteriv (GLuint texture, GLenum pname, const GLint *param); -GLAPI void APIENTRY glGenerateTextureMipmap (GLuint texture); -GLAPI void APIENTRY glBindTextureUnit (GLuint unit, GLuint texture); -GLAPI void APIENTRY glGetTextureImage (GLuint texture, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); -GLAPI void APIENTRY glGetCompressedTextureImage (GLuint texture, GLint level, GLsizei bufSize, void *pixels); -GLAPI void APIENTRY glGetTextureLevelParameterfv (GLuint texture, GLint level, GLenum pname, GLfloat *params); -GLAPI void APIENTRY glGetTextureLevelParameteriv (GLuint texture, GLint level, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetTextureParameterfv (GLuint texture, GLenum pname, GLfloat *params); -GLAPI void APIENTRY glGetTextureParameterIiv (GLuint texture, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetTextureParameterIuiv (GLuint texture, GLenum pname, GLuint *params); -GLAPI void APIENTRY glGetTextureParameteriv (GLuint texture, GLenum pname, GLint *params); -GLAPI void APIENTRY glCreateVertexArrays (GLsizei n, GLuint *arrays); -GLAPI void APIENTRY glDisableVertexArrayAttrib (GLuint vaobj, GLuint index); -GLAPI void APIENTRY glEnableVertexArrayAttrib (GLuint vaobj, GLuint index); -GLAPI void APIENTRY glVertexArrayElementBuffer (GLuint vaobj, GLuint buffer); -GLAPI void APIENTRY glVertexArrayVertexBuffer (GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); -GLAPI void APIENTRY glVertexArrayVertexBuffers (GLuint vaobj, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); -GLAPI void APIENTRY glVertexArrayAttribBinding (GLuint vaobj, GLuint attribindex, GLuint bindingindex); -GLAPI void APIENTRY glVertexArrayAttribFormat (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); -GLAPI void APIENTRY glVertexArrayAttribIFormat (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); -GLAPI void APIENTRY glVertexArrayAttribLFormat (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); -GLAPI void APIENTRY glVertexArrayBindingDivisor (GLuint vaobj, GLuint bindingindex, GLuint divisor); -GLAPI void APIENTRY glGetVertexArrayiv (GLuint vaobj, GLenum pname, GLint *param); -GLAPI void APIENTRY glGetVertexArrayIndexediv (GLuint vaobj, GLuint index, GLenum pname, GLint *param); -GLAPI void APIENTRY glGetVertexArrayIndexed64iv (GLuint vaobj, GLuint index, GLenum pname, GLint64 *param); -GLAPI void APIENTRY glCreateSamplers (GLsizei n, GLuint *samplers); -GLAPI void APIENTRY glCreateProgramPipelines (GLsizei n, GLuint *pipelines); -GLAPI void APIENTRY glCreateQueries (GLenum target, GLsizei n, GLuint *ids); -GLAPI void APIENTRY glGetQueryBufferObjecti64v (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); -GLAPI void APIENTRY glGetQueryBufferObjectiv (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); -GLAPI void APIENTRY glGetQueryBufferObjectui64v (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); -GLAPI void APIENTRY glGetQueryBufferObjectuiv (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); -GLAPI void APIENTRY glMemoryBarrierByRegion (GLbitfield barriers); -GLAPI void APIENTRY glGetTextureSubImage (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLsizei bufSize, void *pixels); -GLAPI void APIENTRY glGetCompressedTextureSubImage (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei bufSize, void *pixels); -GLAPI GLenum APIENTRY glGetGraphicsResetStatus (void); -GLAPI void APIENTRY glGetnCompressedTexImage (GLenum target, GLint lod, GLsizei bufSize, void *pixels); -GLAPI void APIENTRY glGetnTexImage (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); -GLAPI void APIENTRY glGetnUniformdv (GLuint program, GLint location, GLsizei bufSize, GLdouble *params); -GLAPI void APIENTRY glGetnUniformfv (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); -GLAPI void APIENTRY glGetnUniformiv (GLuint program, GLint location, GLsizei bufSize, GLint *params); -GLAPI void APIENTRY glGetnUniformuiv (GLuint program, GLint location, GLsizei bufSize, GLuint *params); -GLAPI void APIENTRY glReadnPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); -GLAPI void APIENTRY glTextureBarrier (void); -#endif -#endif /* GL_VERSION_4_5 */ - -#ifndef GL_VERSION_4_6 -#define GL_VERSION_4_6 1 -#define GL_SHADER_BINARY_FORMAT_SPIR_V 0x9551 -#define GL_SPIR_V_BINARY 0x9552 -#define GL_PARAMETER_BUFFER 0x80EE -#define GL_PARAMETER_BUFFER_BINDING 0x80EF -#define GL_CONTEXT_FLAG_NO_ERROR_BIT 0x00000008 -#define GL_VERTICES_SUBMITTED 0x82EE -#define GL_PRIMITIVES_SUBMITTED 0x82EF -#define GL_VERTEX_SHADER_INVOCATIONS 0x82F0 -#define GL_TESS_CONTROL_SHADER_PATCHES 0x82F1 -#define GL_TESS_EVALUATION_SHADER_INVOCATIONS 0x82F2 -#define GL_GEOMETRY_SHADER_PRIMITIVES_EMITTED 0x82F3 -#define GL_FRAGMENT_SHADER_INVOCATIONS 0x82F4 -#define GL_COMPUTE_SHADER_INVOCATIONS 0x82F5 -#define GL_CLIPPING_INPUT_PRIMITIVES 0x82F6 -#define GL_CLIPPING_OUTPUT_PRIMITIVES 0x82F7 -#define GL_POLYGON_OFFSET_CLAMP 0x8E1B -#define GL_SPIR_V_EXTENSIONS 0x9553 -#define GL_NUM_SPIR_V_EXTENSIONS 0x9554 -#define GL_TEXTURE_MAX_ANISOTROPY 0x84FE -#define GL_MAX_TEXTURE_MAX_ANISOTROPY 0x84FF -#define GL_TRANSFORM_FEEDBACK_OVERFLOW 0x82EC -#define GL_TRANSFORM_FEEDBACK_STREAM_OVERFLOW 0x82ED -typedef void (APIENTRYP PFNGLSPECIALIZESHADERPROC) (GLuint shader, const GLchar *pEntryPoint, GLuint numSpecializationConstants, const GLuint *pConstantIndex, const GLuint *pConstantValue); -typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTCOUNTPROC) (GLenum mode, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); -typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTPROC) (GLenum mode, GLenum type, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); -typedef void (APIENTRYP PFNGLPOLYGONOFFSETCLAMPPROC) (GLfloat factor, GLfloat units, GLfloat clamp); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glSpecializeShader (GLuint shader, const GLchar *pEntryPoint, GLuint numSpecializationConstants, const GLuint *pConstantIndex, const GLuint *pConstantValue); -GLAPI void APIENTRY glMultiDrawArraysIndirectCount (GLenum mode, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); -GLAPI void APIENTRY glMultiDrawElementsIndirectCount (GLenum mode, GLenum type, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); -GLAPI void APIENTRY glPolygonOffsetClamp (GLfloat factor, GLfloat units, GLfloat clamp); -#endif -#endif /* GL_VERSION_4_6 */ - -#ifndef GL_ARB_ES2_compatibility -#define GL_ARB_ES2_compatibility 1 -#endif /* GL_ARB_ES2_compatibility */ - -#ifndef GL_ARB_ES3_1_compatibility -#define GL_ARB_ES3_1_compatibility 1 -#endif /* GL_ARB_ES3_1_compatibility */ - -#ifndef GL_ARB_ES3_2_compatibility -#define GL_ARB_ES3_2_compatibility 1 -#define GL_PRIMITIVE_BOUNDING_BOX_ARB 0x92BE -#define GL_MULTISAMPLE_LINE_WIDTH_RANGE_ARB 0x9381 -#define GL_MULTISAMPLE_LINE_WIDTH_GRANULARITY_ARB 0x9382 -typedef void (APIENTRYP PFNGLPRIMITIVEBOUNDINGBOXARBPROC) (GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glPrimitiveBoundingBoxARB (GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW); -#endif -#endif /* GL_ARB_ES3_2_compatibility */ - -#ifndef GL_ARB_ES3_compatibility -#define GL_ARB_ES3_compatibility 1 -#endif /* GL_ARB_ES3_compatibility */ - -#ifndef GL_ARB_arrays_of_arrays -#define GL_ARB_arrays_of_arrays 1 -#endif /* GL_ARB_arrays_of_arrays */ - -#ifndef GL_ARB_base_instance -#define GL_ARB_base_instance 1 -#endif /* GL_ARB_base_instance */ - -#ifndef GL_ARB_bindless_texture -#define GL_ARB_bindless_texture 1 -typedef uint64_t GLuint64EXT; -#define GL_UNSIGNED_INT64_ARB 0x140F -typedef GLuint64 (APIENTRYP PFNGLGETTEXTUREHANDLEARBPROC) (GLuint texture); -typedef GLuint64 (APIENTRYP PFNGLGETTEXTURESAMPLERHANDLEARBPROC) (GLuint texture, GLuint sampler); -typedef void (APIENTRYP PFNGLMAKETEXTUREHANDLERESIDENTARBPROC) (GLuint64 handle); -typedef void (APIENTRYP PFNGLMAKETEXTUREHANDLENONRESIDENTARBPROC) (GLuint64 handle); -typedef GLuint64 (APIENTRYP PFNGLGETIMAGEHANDLEARBPROC) (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); -typedef void (APIENTRYP PFNGLMAKEIMAGEHANDLERESIDENTARBPROC) (GLuint64 handle, GLenum access); -typedef void (APIENTRYP PFNGLMAKEIMAGEHANDLENONRESIDENTARBPROC) (GLuint64 handle); -typedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64ARBPROC) (GLint location, GLuint64 value); -typedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64VARBPROC) (GLint location, GLsizei count, const GLuint64 *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64ARBPROC) (GLuint program, GLint location, GLuint64 value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *values); -typedef GLboolean (APIENTRYP PFNGLISTEXTUREHANDLERESIDENTARBPROC) (GLuint64 handle); -typedef GLboolean (APIENTRYP PFNGLISIMAGEHANDLERESIDENTARBPROC) (GLuint64 handle); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64ARBPROC) (GLuint index, GLuint64EXT x); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64VARBPROC) (GLuint index, const GLuint64EXT *v); -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLUI64VARBPROC) (GLuint index, GLenum pname, GLuint64EXT *params); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI GLuint64 APIENTRY glGetTextureHandleARB (GLuint texture); -GLAPI GLuint64 APIENTRY glGetTextureSamplerHandleARB (GLuint texture, GLuint sampler); -GLAPI void APIENTRY glMakeTextureHandleResidentARB (GLuint64 handle); -GLAPI void APIENTRY glMakeTextureHandleNonResidentARB (GLuint64 handle); -GLAPI GLuint64 APIENTRY glGetImageHandleARB (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); -GLAPI void APIENTRY glMakeImageHandleResidentARB (GLuint64 handle, GLenum access); -GLAPI void APIENTRY glMakeImageHandleNonResidentARB (GLuint64 handle); -GLAPI void APIENTRY glUniformHandleui64ARB (GLint location, GLuint64 value); -GLAPI void APIENTRY glUniformHandleui64vARB (GLint location, GLsizei count, const GLuint64 *value); -GLAPI void APIENTRY glProgramUniformHandleui64ARB (GLuint program, GLint location, GLuint64 value); -GLAPI void APIENTRY glProgramUniformHandleui64vARB (GLuint program, GLint location, GLsizei count, const GLuint64 *values); -GLAPI GLboolean APIENTRY glIsTextureHandleResidentARB (GLuint64 handle); -GLAPI GLboolean APIENTRY glIsImageHandleResidentARB (GLuint64 handle); -GLAPI void APIENTRY glVertexAttribL1ui64ARB (GLuint index, GLuint64EXT x); -GLAPI void APIENTRY glVertexAttribL1ui64vARB (GLuint index, const GLuint64EXT *v); -GLAPI void APIENTRY glGetVertexAttribLui64vARB (GLuint index, GLenum pname, GLuint64EXT *params); -#endif -#endif /* GL_ARB_bindless_texture */ - -#ifndef GL_ARB_blend_func_extended -#define GL_ARB_blend_func_extended 1 -#endif /* GL_ARB_blend_func_extended */ - -#ifndef GL_ARB_buffer_storage -#define GL_ARB_buffer_storage 1 -#endif /* GL_ARB_buffer_storage */ - -#ifndef GL_ARB_cl_event -#define GL_ARB_cl_event 1 -struct _cl_context; -struct _cl_event; -#define GL_SYNC_CL_EVENT_ARB 0x8240 -#define GL_SYNC_CL_EVENT_COMPLETE_ARB 0x8241 -typedef GLsync (APIENTRYP PFNGLCREATESYNCFROMCLEVENTARBPROC) (struct _cl_context *context, struct _cl_event *event, GLbitfield flags); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI GLsync APIENTRY glCreateSyncFromCLeventARB (struct _cl_context *context, struct _cl_event *event, GLbitfield flags); -#endif -#endif /* GL_ARB_cl_event */ - -#ifndef GL_ARB_clear_buffer_object -#define GL_ARB_clear_buffer_object 1 -#endif /* GL_ARB_clear_buffer_object */ - -#ifndef GL_ARB_clear_texture -#define GL_ARB_clear_texture 1 -#endif /* GL_ARB_clear_texture */ - -#ifndef GL_ARB_clip_control -#define GL_ARB_clip_control 1 -#endif /* GL_ARB_clip_control */ - -#ifndef GL_ARB_compressed_texture_pixel_storage -#define GL_ARB_compressed_texture_pixel_storage 1 -#endif /* GL_ARB_compressed_texture_pixel_storage */ - -#ifndef GL_ARB_compute_shader -#define GL_ARB_compute_shader 1 -#endif /* GL_ARB_compute_shader */ - -#ifndef GL_ARB_compute_variable_group_size -#define GL_ARB_compute_variable_group_size 1 -#define GL_MAX_COMPUTE_VARIABLE_GROUP_INVOCATIONS_ARB 0x9344 -#define GL_MAX_COMPUTE_FIXED_GROUP_INVOCATIONS_ARB 0x90EB -#define GL_MAX_COMPUTE_VARIABLE_GROUP_SIZE_ARB 0x9345 -#define GL_MAX_COMPUTE_FIXED_GROUP_SIZE_ARB 0x91BF -typedef void (APIENTRYP PFNGLDISPATCHCOMPUTEGROUPSIZEARBPROC) (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z, GLuint group_size_x, GLuint group_size_y, GLuint group_size_z); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glDispatchComputeGroupSizeARB (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z, GLuint group_size_x, GLuint group_size_y, GLuint group_size_z); -#endif -#endif /* GL_ARB_compute_variable_group_size */ - -#ifndef GL_ARB_conditional_render_inverted -#define GL_ARB_conditional_render_inverted 1 -#endif /* GL_ARB_conditional_render_inverted */ - -#ifndef GL_ARB_conservative_depth -#define GL_ARB_conservative_depth 1 -#endif /* GL_ARB_conservative_depth */ - -#ifndef GL_ARB_copy_buffer -#define GL_ARB_copy_buffer 1 -#endif /* GL_ARB_copy_buffer */ - -#ifndef GL_ARB_copy_image -#define GL_ARB_copy_image 1 -#endif /* GL_ARB_copy_image */ - -#ifndef GL_ARB_cull_distance -#define GL_ARB_cull_distance 1 -#endif /* GL_ARB_cull_distance */ - -#ifndef GL_ARB_debug_output -#define GL_ARB_debug_output 1 -typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); -#define GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB 0x8242 -#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_ARB 0x8243 -#define GL_DEBUG_CALLBACK_FUNCTION_ARB 0x8244 -#define GL_DEBUG_CALLBACK_USER_PARAM_ARB 0x8245 -#define GL_DEBUG_SOURCE_API_ARB 0x8246 -#define GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB 0x8247 -#define GL_DEBUG_SOURCE_SHADER_COMPILER_ARB 0x8248 -#define GL_DEBUG_SOURCE_THIRD_PARTY_ARB 0x8249 -#define GL_DEBUG_SOURCE_APPLICATION_ARB 0x824A -#define GL_DEBUG_SOURCE_OTHER_ARB 0x824B -#define GL_DEBUG_TYPE_ERROR_ARB 0x824C -#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB 0x824D -#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB 0x824E -#define GL_DEBUG_TYPE_PORTABILITY_ARB 0x824F -#define GL_DEBUG_TYPE_PERFORMANCE_ARB 0x8250 -#define GL_DEBUG_TYPE_OTHER_ARB 0x8251 -#define GL_MAX_DEBUG_MESSAGE_LENGTH_ARB 0x9143 -#define GL_MAX_DEBUG_LOGGED_MESSAGES_ARB 0x9144 -#define GL_DEBUG_LOGGED_MESSAGES_ARB 0x9145 -#define GL_DEBUG_SEVERITY_HIGH_ARB 0x9146 -#define GL_DEBUG_SEVERITY_MEDIUM_ARB 0x9147 -#define GL_DEBUG_SEVERITY_LOW_ARB 0x9148 -typedef void (APIENTRYP PFNGLDEBUGMESSAGECONTROLARBPROC) (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); -typedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTARBPROC) (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); -typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKARBPROC) (GLDEBUGPROCARB callback, const void *userParam); -typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGARBPROC) (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glDebugMessageControlARB (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); -GLAPI void APIENTRY glDebugMessageInsertARB (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); -GLAPI void APIENTRY glDebugMessageCallbackARB (GLDEBUGPROCARB callback, const void *userParam); -GLAPI GLuint APIENTRY glGetDebugMessageLogARB (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); -#endif -#endif /* GL_ARB_debug_output */ - -#ifndef GL_ARB_depth_buffer_float -#define GL_ARB_depth_buffer_float 1 -#endif /* GL_ARB_depth_buffer_float */ - -#ifndef GL_ARB_depth_clamp -#define GL_ARB_depth_clamp 1 -#endif /* GL_ARB_depth_clamp */ - -#ifndef GL_ARB_derivative_control -#define GL_ARB_derivative_control 1 -#endif /* GL_ARB_derivative_control */ - -#ifndef GL_ARB_direct_state_access -#define GL_ARB_direct_state_access 1 -#endif /* GL_ARB_direct_state_access */ - -#ifndef GL_ARB_draw_buffers_blend -#define GL_ARB_draw_buffers_blend 1 -typedef void (APIENTRYP PFNGLBLENDEQUATIONIARBPROC) (GLuint buf, GLenum mode); -typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEIARBPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha); -typedef void (APIENTRYP PFNGLBLENDFUNCIARBPROC) (GLuint buf, GLenum src, GLenum dst); -typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEIARBPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glBlendEquationiARB (GLuint buf, GLenum mode); -GLAPI void APIENTRY glBlendEquationSeparateiARB (GLuint buf, GLenum modeRGB, GLenum modeAlpha); -GLAPI void APIENTRY glBlendFunciARB (GLuint buf, GLenum src, GLenum dst); -GLAPI void APIENTRY glBlendFuncSeparateiARB (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); -#endif -#endif /* GL_ARB_draw_buffers_blend */ - -#ifndef GL_ARB_draw_elements_base_vertex -#define GL_ARB_draw_elements_base_vertex 1 -#endif /* GL_ARB_draw_elements_base_vertex */ - -#ifndef GL_ARB_draw_indirect -#define GL_ARB_draw_indirect 1 -#endif /* GL_ARB_draw_indirect */ - -#ifndef GL_ARB_draw_instanced -#define GL_ARB_draw_instanced 1 -typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDARBPROC) (GLenum mode, GLint first, GLsizei count, GLsizei primcount); -typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDARBPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glDrawArraysInstancedARB (GLenum mode, GLint first, GLsizei count, GLsizei primcount); -GLAPI void APIENTRY glDrawElementsInstancedARB (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); -#endif -#endif /* GL_ARB_draw_instanced */ - -#ifndef GL_ARB_enhanced_layouts -#define GL_ARB_enhanced_layouts 1 -#endif /* GL_ARB_enhanced_layouts */ - -#ifndef GL_ARB_explicit_attrib_location -#define GL_ARB_explicit_attrib_location 1 -#endif /* GL_ARB_explicit_attrib_location */ - -#ifndef GL_ARB_explicit_uniform_location -#define GL_ARB_explicit_uniform_location 1 -#endif /* GL_ARB_explicit_uniform_location */ - -#ifndef GL_ARB_fragment_coord_conventions -#define GL_ARB_fragment_coord_conventions 1 -#endif /* GL_ARB_fragment_coord_conventions */ - -#ifndef GL_ARB_fragment_layer_viewport -#define GL_ARB_fragment_layer_viewport 1 -#endif /* GL_ARB_fragment_layer_viewport */ - -#ifndef GL_ARB_fragment_shader_interlock -#define GL_ARB_fragment_shader_interlock 1 -#endif /* GL_ARB_fragment_shader_interlock */ - -#ifndef GL_ARB_framebuffer_no_attachments -#define GL_ARB_framebuffer_no_attachments 1 -#endif /* GL_ARB_framebuffer_no_attachments */ - -#ifndef GL_ARB_framebuffer_object -#define GL_ARB_framebuffer_object 1 -#endif /* GL_ARB_framebuffer_object */ - -#ifndef GL_ARB_framebuffer_sRGB -#define GL_ARB_framebuffer_sRGB 1 -#endif /* GL_ARB_framebuffer_sRGB */ - -#ifndef GL_ARB_geometry_shader4 -#define GL_ARB_geometry_shader4 1 -#define GL_LINES_ADJACENCY_ARB 0x000A -#define GL_LINE_STRIP_ADJACENCY_ARB 0x000B -#define GL_TRIANGLES_ADJACENCY_ARB 0x000C -#define GL_TRIANGLE_STRIP_ADJACENCY_ARB 0x000D -#define GL_PROGRAM_POINT_SIZE_ARB 0x8642 -#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_ARB 0x8C29 -#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_ARB 0x8DA7 -#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_ARB 0x8DA8 -#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_ARB 0x8DA9 -#define GL_GEOMETRY_SHADER_ARB 0x8DD9 -#define GL_GEOMETRY_VERTICES_OUT_ARB 0x8DDA -#define GL_GEOMETRY_INPUT_TYPE_ARB 0x8DDB -#define GL_GEOMETRY_OUTPUT_TYPE_ARB 0x8DDC -#define GL_MAX_GEOMETRY_VARYING_COMPONENTS_ARB 0x8DDD -#define GL_MAX_VERTEX_VARYING_COMPONENTS_ARB 0x8DDE -#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_ARB 0x8DDF -#define GL_MAX_GEOMETRY_OUTPUT_VERTICES_ARB 0x8DE0 -#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_ARB 0x8DE1 -typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIARBPROC) (GLuint program, GLenum pname, GLint value); -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level); -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREFACEARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glProgramParameteriARB (GLuint program, GLenum pname, GLint value); -GLAPI void APIENTRY glFramebufferTextureARB (GLenum target, GLenum attachment, GLuint texture, GLint level); -GLAPI void APIENTRY glFramebufferTextureLayerARB (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); -GLAPI void APIENTRY glFramebufferTextureFaceARB (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face); -#endif -#endif /* GL_ARB_geometry_shader4 */ - -#ifndef GL_ARB_get_program_binary -#define GL_ARB_get_program_binary 1 -#endif /* GL_ARB_get_program_binary */ - -#ifndef GL_ARB_get_texture_sub_image -#define GL_ARB_get_texture_sub_image 1 -#endif /* GL_ARB_get_texture_sub_image */ - -#ifndef GL_ARB_gl_spirv -#define GL_ARB_gl_spirv 1 -#define GL_SHADER_BINARY_FORMAT_SPIR_V_ARB 0x9551 -#define GL_SPIR_V_BINARY_ARB 0x9552 -typedef void (APIENTRYP PFNGLSPECIALIZESHADERARBPROC) (GLuint shader, const GLchar *pEntryPoint, GLuint numSpecializationConstants, const GLuint *pConstantIndex, const GLuint *pConstantValue); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glSpecializeShaderARB (GLuint shader, const GLchar *pEntryPoint, GLuint numSpecializationConstants, const GLuint *pConstantIndex, const GLuint *pConstantValue); -#endif -#endif /* GL_ARB_gl_spirv */ - -#ifndef GL_ARB_gpu_shader5 -#define GL_ARB_gpu_shader5 1 -#endif /* GL_ARB_gpu_shader5 */ - -#ifndef GL_ARB_gpu_shader_fp64 -#define GL_ARB_gpu_shader_fp64 1 -#endif /* GL_ARB_gpu_shader_fp64 */ - -#ifndef GL_ARB_gpu_shader_int64 -#define GL_ARB_gpu_shader_int64 1 -#define GL_INT64_ARB 0x140E -#define GL_INT64_VEC2_ARB 0x8FE9 -#define GL_INT64_VEC3_ARB 0x8FEA -#define GL_INT64_VEC4_ARB 0x8FEB -#define GL_UNSIGNED_INT64_VEC2_ARB 0x8FF5 -#define GL_UNSIGNED_INT64_VEC3_ARB 0x8FF6 -#define GL_UNSIGNED_INT64_VEC4_ARB 0x8FF7 -typedef void (APIENTRYP PFNGLUNIFORM1I64ARBPROC) (GLint location, GLint64 x); -typedef void (APIENTRYP PFNGLUNIFORM2I64ARBPROC) (GLint location, GLint64 x, GLint64 y); -typedef void (APIENTRYP PFNGLUNIFORM3I64ARBPROC) (GLint location, GLint64 x, GLint64 y, GLint64 z); -typedef void (APIENTRYP PFNGLUNIFORM4I64ARBPROC) (GLint location, GLint64 x, GLint64 y, GLint64 z, GLint64 w); -typedef void (APIENTRYP PFNGLUNIFORM1I64VARBPROC) (GLint location, GLsizei count, const GLint64 *value); -typedef void (APIENTRYP PFNGLUNIFORM2I64VARBPROC) (GLint location, GLsizei count, const GLint64 *value); -typedef void (APIENTRYP PFNGLUNIFORM3I64VARBPROC) (GLint location, GLsizei count, const GLint64 *value); -typedef void (APIENTRYP PFNGLUNIFORM4I64VARBPROC) (GLint location, GLsizei count, const GLint64 *value); -typedef void (APIENTRYP PFNGLUNIFORM1UI64ARBPROC) (GLint location, GLuint64 x); -typedef void (APIENTRYP PFNGLUNIFORM2UI64ARBPROC) (GLint location, GLuint64 x, GLuint64 y); -typedef void (APIENTRYP PFNGLUNIFORM3UI64ARBPROC) (GLint location, GLuint64 x, GLuint64 y, GLuint64 z); -typedef void (APIENTRYP PFNGLUNIFORM4UI64ARBPROC) (GLint location, GLuint64 x, GLuint64 y, GLuint64 z, GLuint64 w); -typedef void (APIENTRYP PFNGLUNIFORM1UI64VARBPROC) (GLint location, GLsizei count, const GLuint64 *value); -typedef void (APIENTRYP PFNGLUNIFORM2UI64VARBPROC) (GLint location, GLsizei count, const GLuint64 *value); -typedef void (APIENTRYP PFNGLUNIFORM3UI64VARBPROC) (GLint location, GLsizei count, const GLuint64 *value); -typedef void (APIENTRYP PFNGLUNIFORM4UI64VARBPROC) (GLint location, GLsizei count, const GLuint64 *value); -typedef void (APIENTRYP PFNGLGETUNIFORMI64VARBPROC) (GLuint program, GLint location, GLint64 *params); -typedef void (APIENTRYP PFNGLGETUNIFORMUI64VARBPROC) (GLuint program, GLint location, GLuint64 *params); -typedef void (APIENTRYP PFNGLGETNUNIFORMI64VARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLint64 *params); -typedef void (APIENTRYP PFNGLGETNUNIFORMUI64VARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLuint64 *params); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1I64ARBPROC) (GLuint program, GLint location, GLint64 x); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2I64ARBPROC) (GLuint program, GLint location, GLint64 x, GLint64 y); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3I64ARBPROC) (GLuint program, GLint location, GLint64 x, GLint64 y, GLint64 z); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4I64ARBPROC) (GLuint program, GLint location, GLint64 x, GLint64 y, GLint64 z, GLint64 w); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1I64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLint64 *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2I64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLint64 *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3I64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLint64 *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4I64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLint64 *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UI64ARBPROC) (GLuint program, GLint location, GLuint64 x); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UI64ARBPROC) (GLuint program, GLint location, GLuint64 x, GLuint64 y); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UI64ARBPROC) (GLuint program, GLint location, GLuint64 x, GLuint64 y, GLuint64 z); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UI64ARBPROC) (GLuint program, GLint location, GLuint64 x, GLuint64 y, GLuint64 z, GLuint64 w); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UI64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UI64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UI64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UI64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *value); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glUniform1i64ARB (GLint location, GLint64 x); -GLAPI void APIENTRY glUniform2i64ARB (GLint location, GLint64 x, GLint64 y); -GLAPI void APIENTRY glUniform3i64ARB (GLint location, GLint64 x, GLint64 y, GLint64 z); -GLAPI void APIENTRY glUniform4i64ARB (GLint location, GLint64 x, GLint64 y, GLint64 z, GLint64 w); -GLAPI void APIENTRY glUniform1i64vARB (GLint location, GLsizei count, const GLint64 *value); -GLAPI void APIENTRY glUniform2i64vARB (GLint location, GLsizei count, const GLint64 *value); -GLAPI void APIENTRY glUniform3i64vARB (GLint location, GLsizei count, const GLint64 *value); -GLAPI void APIENTRY glUniform4i64vARB (GLint location, GLsizei count, const GLint64 *value); -GLAPI void APIENTRY glUniform1ui64ARB (GLint location, GLuint64 x); -GLAPI void APIENTRY glUniform2ui64ARB (GLint location, GLuint64 x, GLuint64 y); -GLAPI void APIENTRY glUniform3ui64ARB (GLint location, GLuint64 x, GLuint64 y, GLuint64 z); -GLAPI void APIENTRY glUniform4ui64ARB (GLint location, GLuint64 x, GLuint64 y, GLuint64 z, GLuint64 w); -GLAPI void APIENTRY glUniform1ui64vARB (GLint location, GLsizei count, const GLuint64 *value); -GLAPI void APIENTRY glUniform2ui64vARB (GLint location, GLsizei count, const GLuint64 *value); -GLAPI void APIENTRY glUniform3ui64vARB (GLint location, GLsizei count, const GLuint64 *value); -GLAPI void APIENTRY glUniform4ui64vARB (GLint location, GLsizei count, const GLuint64 *value); -GLAPI void APIENTRY glGetUniformi64vARB (GLuint program, GLint location, GLint64 *params); -GLAPI void APIENTRY glGetUniformui64vARB (GLuint program, GLint location, GLuint64 *params); -GLAPI void APIENTRY glGetnUniformi64vARB (GLuint program, GLint location, GLsizei bufSize, GLint64 *params); -GLAPI void APIENTRY glGetnUniformui64vARB (GLuint program, GLint location, GLsizei bufSize, GLuint64 *params); -GLAPI void APIENTRY glProgramUniform1i64ARB (GLuint program, GLint location, GLint64 x); -GLAPI void APIENTRY glProgramUniform2i64ARB (GLuint program, GLint location, GLint64 x, GLint64 y); -GLAPI void APIENTRY glProgramUniform3i64ARB (GLuint program, GLint location, GLint64 x, GLint64 y, GLint64 z); -GLAPI void APIENTRY glProgramUniform4i64ARB (GLuint program, GLint location, GLint64 x, GLint64 y, GLint64 z, GLint64 w); -GLAPI void APIENTRY glProgramUniform1i64vARB (GLuint program, GLint location, GLsizei count, const GLint64 *value); -GLAPI void APIENTRY glProgramUniform2i64vARB (GLuint program, GLint location, GLsizei count, const GLint64 *value); -GLAPI void APIENTRY glProgramUniform3i64vARB (GLuint program, GLint location, GLsizei count, const GLint64 *value); -GLAPI void APIENTRY glProgramUniform4i64vARB (GLuint program, GLint location, GLsizei count, const GLint64 *value); -GLAPI void APIENTRY glProgramUniform1ui64ARB (GLuint program, GLint location, GLuint64 x); -GLAPI void APIENTRY glProgramUniform2ui64ARB (GLuint program, GLint location, GLuint64 x, GLuint64 y); -GLAPI void APIENTRY glProgramUniform3ui64ARB (GLuint program, GLint location, GLuint64 x, GLuint64 y, GLuint64 z); -GLAPI void APIENTRY glProgramUniform4ui64ARB (GLuint program, GLint location, GLuint64 x, GLuint64 y, GLuint64 z, GLuint64 w); -GLAPI void APIENTRY glProgramUniform1ui64vARB (GLuint program, GLint location, GLsizei count, const GLuint64 *value); -GLAPI void APIENTRY glProgramUniform2ui64vARB (GLuint program, GLint location, GLsizei count, const GLuint64 *value); -GLAPI void APIENTRY glProgramUniform3ui64vARB (GLuint program, GLint location, GLsizei count, const GLuint64 *value); -GLAPI void APIENTRY glProgramUniform4ui64vARB (GLuint program, GLint location, GLsizei count, const GLuint64 *value); -#endif -#endif /* GL_ARB_gpu_shader_int64 */ - -#ifndef GL_ARB_half_float_vertex -#define GL_ARB_half_float_vertex 1 -#endif /* GL_ARB_half_float_vertex */ - -#ifndef GL_ARB_imaging -#define GL_ARB_imaging 1 -#define GL_BLEND_COLOR 0x8005 -#define GL_BLEND_EQUATION 0x8009 -#endif /* GL_ARB_imaging */ - -#ifndef GL_ARB_indirect_parameters -#define GL_ARB_indirect_parameters 1 -#define GL_PARAMETER_BUFFER_ARB 0x80EE -#define GL_PARAMETER_BUFFER_BINDING_ARB 0x80EF -typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTCOUNTARBPROC) (GLenum mode, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); -typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTARBPROC) (GLenum mode, GLenum type, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glMultiDrawArraysIndirectCountARB (GLenum mode, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); -GLAPI void APIENTRY glMultiDrawElementsIndirectCountARB (GLenum mode, GLenum type, const void *indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); -#endif -#endif /* GL_ARB_indirect_parameters */ - -#ifndef GL_ARB_instanced_arrays -#define GL_ARB_instanced_arrays 1 -#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ARB 0x88FE -typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORARBPROC) (GLuint index, GLuint divisor); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glVertexAttribDivisorARB (GLuint index, GLuint divisor); -#endif -#endif /* GL_ARB_instanced_arrays */ - -#ifndef GL_ARB_internalformat_query -#define GL_ARB_internalformat_query 1 -#endif /* GL_ARB_internalformat_query */ - -#ifndef GL_ARB_internalformat_query2 -#define GL_ARB_internalformat_query2 1 -#define GL_SRGB_DECODE_ARB 0x8299 -#endif /* GL_ARB_internalformat_query2 */ - -#ifndef GL_ARB_invalidate_subdata -#define GL_ARB_invalidate_subdata 1 -#endif /* GL_ARB_invalidate_subdata */ - -#ifndef GL_ARB_map_buffer_alignment -#define GL_ARB_map_buffer_alignment 1 -#endif /* GL_ARB_map_buffer_alignment */ - -#ifndef GL_ARB_map_buffer_range -#define GL_ARB_map_buffer_range 1 -#endif /* GL_ARB_map_buffer_range */ - -#ifndef GL_ARB_multi_bind -#define GL_ARB_multi_bind 1 -#endif /* GL_ARB_multi_bind */ - -#ifndef GL_ARB_multi_draw_indirect -#define GL_ARB_multi_draw_indirect 1 -#endif /* GL_ARB_multi_draw_indirect */ - -#ifndef GL_ARB_occlusion_query2 -#define GL_ARB_occlusion_query2 1 -#endif /* GL_ARB_occlusion_query2 */ - -#ifndef GL_ARB_parallel_shader_compile -#define GL_ARB_parallel_shader_compile 1 -#define GL_MAX_SHADER_COMPILER_THREADS_ARB 0x91B0 -#define GL_COMPLETION_STATUS_ARB 0x91B1 -typedef void (APIENTRYP PFNGLMAXSHADERCOMPILERTHREADSARBPROC) (GLuint count); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glMaxShaderCompilerThreadsARB (GLuint count); -#endif -#endif /* GL_ARB_parallel_shader_compile */ - -#ifndef GL_ARB_pipeline_statistics_query -#define GL_ARB_pipeline_statistics_query 1 -#define GL_VERTICES_SUBMITTED_ARB 0x82EE -#define GL_PRIMITIVES_SUBMITTED_ARB 0x82EF -#define GL_VERTEX_SHADER_INVOCATIONS_ARB 0x82F0 -#define GL_TESS_CONTROL_SHADER_PATCHES_ARB 0x82F1 -#define GL_TESS_EVALUATION_SHADER_INVOCATIONS_ARB 0x82F2 -#define GL_GEOMETRY_SHADER_PRIMITIVES_EMITTED_ARB 0x82F3 -#define GL_FRAGMENT_SHADER_INVOCATIONS_ARB 0x82F4 -#define GL_COMPUTE_SHADER_INVOCATIONS_ARB 0x82F5 -#define GL_CLIPPING_INPUT_PRIMITIVES_ARB 0x82F6 -#define GL_CLIPPING_OUTPUT_PRIMITIVES_ARB 0x82F7 -#endif /* GL_ARB_pipeline_statistics_query */ - -#ifndef GL_ARB_pixel_buffer_object -#define GL_ARB_pixel_buffer_object 1 -#define GL_PIXEL_PACK_BUFFER_ARB 0x88EB -#define GL_PIXEL_UNPACK_BUFFER_ARB 0x88EC -#define GL_PIXEL_PACK_BUFFER_BINDING_ARB 0x88ED -#define GL_PIXEL_UNPACK_BUFFER_BINDING_ARB 0x88EF -#endif /* GL_ARB_pixel_buffer_object */ - -#ifndef GL_ARB_polygon_offset_clamp -#define GL_ARB_polygon_offset_clamp 1 -#endif /* GL_ARB_polygon_offset_clamp */ - -#ifndef GL_ARB_post_depth_coverage -#define GL_ARB_post_depth_coverage 1 -#endif /* GL_ARB_post_depth_coverage */ - -#ifndef GL_ARB_program_interface_query -#define GL_ARB_program_interface_query 1 -#endif /* GL_ARB_program_interface_query */ - -#ifndef GL_ARB_provoking_vertex -#define GL_ARB_provoking_vertex 1 -#endif /* GL_ARB_provoking_vertex */ - -#ifndef GL_ARB_query_buffer_object -#define GL_ARB_query_buffer_object 1 -#endif /* GL_ARB_query_buffer_object */ - -#ifndef GL_ARB_robust_buffer_access_behavior -#define GL_ARB_robust_buffer_access_behavior 1 -#endif /* GL_ARB_robust_buffer_access_behavior */ - -#ifndef GL_ARB_robustness -#define GL_ARB_robustness 1 -#define GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB 0x00000004 -#define GL_LOSE_CONTEXT_ON_RESET_ARB 0x8252 -#define GL_GUILTY_CONTEXT_RESET_ARB 0x8253 -#define GL_INNOCENT_CONTEXT_RESET_ARB 0x8254 -#define GL_UNKNOWN_CONTEXT_RESET_ARB 0x8255 -#define GL_RESET_NOTIFICATION_STRATEGY_ARB 0x8256 -#define GL_NO_RESET_NOTIFICATION_ARB 0x8261 -typedef GLenum (APIENTRYP PFNGLGETGRAPHICSRESETSTATUSARBPROC) (void); -typedef void (APIENTRYP PFNGLGETNTEXIMAGEARBPROC) (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *img); -typedef void (APIENTRYP PFNGLREADNPIXELSARBPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); -typedef void (APIENTRYP PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint lod, GLsizei bufSize, void *img); -typedef void (APIENTRYP PFNGLGETNUNIFORMFVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); -typedef void (APIENTRYP PFNGLGETNUNIFORMIVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLint *params); -typedef void (APIENTRYP PFNGLGETNUNIFORMUIVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLuint *params); -typedef void (APIENTRYP PFNGLGETNUNIFORMDVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLdouble *params); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI GLenum APIENTRY glGetGraphicsResetStatusARB (void); -GLAPI void APIENTRY glGetnTexImageARB (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *img); -GLAPI void APIENTRY glReadnPixelsARB (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); -GLAPI void APIENTRY glGetnCompressedTexImageARB (GLenum target, GLint lod, GLsizei bufSize, void *img); -GLAPI void APIENTRY glGetnUniformfvARB (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); -GLAPI void APIENTRY glGetnUniformivARB (GLuint program, GLint location, GLsizei bufSize, GLint *params); -GLAPI void APIENTRY glGetnUniformuivARB (GLuint program, GLint location, GLsizei bufSize, GLuint *params); -GLAPI void APIENTRY glGetnUniformdvARB (GLuint program, GLint location, GLsizei bufSize, GLdouble *params); -#endif -#endif /* GL_ARB_robustness */ - -#ifndef GL_ARB_robustness_isolation -#define GL_ARB_robustness_isolation 1 -#endif /* GL_ARB_robustness_isolation */ - -#ifndef GL_ARB_sample_locations -#define GL_ARB_sample_locations 1 -#define GL_SAMPLE_LOCATION_SUBPIXEL_BITS_ARB 0x933D -#define GL_SAMPLE_LOCATION_PIXEL_GRID_WIDTH_ARB 0x933E -#define GL_SAMPLE_LOCATION_PIXEL_GRID_HEIGHT_ARB 0x933F -#define GL_PROGRAMMABLE_SAMPLE_LOCATION_TABLE_SIZE_ARB 0x9340 -#define GL_SAMPLE_LOCATION_ARB 0x8E50 -#define GL_PROGRAMMABLE_SAMPLE_LOCATION_ARB 0x9341 -#define GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_ARB 0x9342 -#define GL_FRAMEBUFFER_SAMPLE_LOCATION_PIXEL_GRID_ARB 0x9343 -typedef void (APIENTRYP PFNGLFRAMEBUFFERSAMPLELOCATIONSFVARBPROC) (GLenum target, GLuint start, GLsizei count, const GLfloat *v); -typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVARBPROC) (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); -typedef void (APIENTRYP PFNGLEVALUATEDEPTHVALUESARBPROC) (void); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glFramebufferSampleLocationsfvARB (GLenum target, GLuint start, GLsizei count, const GLfloat *v); -GLAPI void APIENTRY glNamedFramebufferSampleLocationsfvARB (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); -GLAPI void APIENTRY glEvaluateDepthValuesARB (void); -#endif -#endif /* GL_ARB_sample_locations */ - -#ifndef GL_ARB_sample_shading -#define GL_ARB_sample_shading 1 -#define GL_SAMPLE_SHADING_ARB 0x8C36 -#define GL_MIN_SAMPLE_SHADING_VALUE_ARB 0x8C37 -typedef void (APIENTRYP PFNGLMINSAMPLESHADINGARBPROC) (GLfloat value); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glMinSampleShadingARB (GLfloat value); -#endif -#endif /* GL_ARB_sample_shading */ - -#ifndef GL_ARB_sampler_objects -#define GL_ARB_sampler_objects 1 -#endif /* GL_ARB_sampler_objects */ - -#ifndef GL_ARB_seamless_cube_map -#define GL_ARB_seamless_cube_map 1 -#endif /* GL_ARB_seamless_cube_map */ - -#ifndef GL_ARB_seamless_cubemap_per_texture -#define GL_ARB_seamless_cubemap_per_texture 1 -#endif /* GL_ARB_seamless_cubemap_per_texture */ - -#ifndef GL_ARB_separate_shader_objects -#define GL_ARB_separate_shader_objects 1 -#endif /* GL_ARB_separate_shader_objects */ - -#ifndef GL_ARB_shader_atomic_counter_ops -#define GL_ARB_shader_atomic_counter_ops 1 -#endif /* GL_ARB_shader_atomic_counter_ops */ - -#ifndef GL_ARB_shader_atomic_counters -#define GL_ARB_shader_atomic_counters 1 -#endif /* GL_ARB_shader_atomic_counters */ - -#ifndef GL_ARB_shader_ballot -#define GL_ARB_shader_ballot 1 -#endif /* GL_ARB_shader_ballot */ - -#ifndef GL_ARB_shader_bit_encoding -#define GL_ARB_shader_bit_encoding 1 -#endif /* GL_ARB_shader_bit_encoding */ - -#ifndef GL_ARB_shader_clock -#define GL_ARB_shader_clock 1 -#endif /* GL_ARB_shader_clock */ - -#ifndef GL_ARB_shader_draw_parameters -#define GL_ARB_shader_draw_parameters 1 -#endif /* GL_ARB_shader_draw_parameters */ - -#ifndef GL_ARB_shader_group_vote -#define GL_ARB_shader_group_vote 1 -#endif /* GL_ARB_shader_group_vote */ - -#ifndef GL_ARB_shader_image_load_store -#define GL_ARB_shader_image_load_store 1 -#endif /* GL_ARB_shader_image_load_store */ - -#ifndef GL_ARB_shader_image_size -#define GL_ARB_shader_image_size 1 -#endif /* GL_ARB_shader_image_size */ - -#ifndef GL_ARB_shader_precision -#define GL_ARB_shader_precision 1 -#endif /* GL_ARB_shader_precision */ - -#ifndef GL_ARB_shader_stencil_export -#define GL_ARB_shader_stencil_export 1 -#endif /* GL_ARB_shader_stencil_export */ - -#ifndef GL_ARB_shader_storage_buffer_object -#define GL_ARB_shader_storage_buffer_object 1 -#endif /* GL_ARB_shader_storage_buffer_object */ - -#ifndef GL_ARB_shader_subroutine -#define GL_ARB_shader_subroutine 1 -#endif /* GL_ARB_shader_subroutine */ - -#ifndef GL_ARB_shader_texture_image_samples -#define GL_ARB_shader_texture_image_samples 1 -#endif /* GL_ARB_shader_texture_image_samples */ - -#ifndef GL_ARB_shader_viewport_layer_array -#define GL_ARB_shader_viewport_layer_array 1 -#endif /* GL_ARB_shader_viewport_layer_array */ - -#ifndef GL_ARB_shading_language_420pack -#define GL_ARB_shading_language_420pack 1 -#endif /* GL_ARB_shading_language_420pack */ - -#ifndef GL_ARB_shading_language_include -#define GL_ARB_shading_language_include 1 -#define GL_SHADER_INCLUDE_ARB 0x8DAE -#define GL_NAMED_STRING_LENGTH_ARB 0x8DE9 -#define GL_NAMED_STRING_TYPE_ARB 0x8DEA -typedef void (APIENTRYP PFNGLNAMEDSTRINGARBPROC) (GLenum type, GLint namelen, const GLchar *name, GLint stringlen, const GLchar *string); -typedef void (APIENTRYP PFNGLDELETENAMEDSTRINGARBPROC) (GLint namelen, const GLchar *name); -typedef void (APIENTRYP PFNGLCOMPILESHADERINCLUDEARBPROC) (GLuint shader, GLsizei count, const GLchar *const*path, const GLint *length); -typedef GLboolean (APIENTRYP PFNGLISNAMEDSTRINGARBPROC) (GLint namelen, const GLchar *name); -typedef void (APIENTRYP PFNGLGETNAMEDSTRINGARBPROC) (GLint namelen, const GLchar *name, GLsizei bufSize, GLint *stringlen, GLchar *string); -typedef void (APIENTRYP PFNGLGETNAMEDSTRINGIVARBPROC) (GLint namelen, const GLchar *name, GLenum pname, GLint *params); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glNamedStringARB (GLenum type, GLint namelen, const GLchar *name, GLint stringlen, const GLchar *string); -GLAPI void APIENTRY glDeleteNamedStringARB (GLint namelen, const GLchar *name); -GLAPI void APIENTRY glCompileShaderIncludeARB (GLuint shader, GLsizei count, const GLchar *const*path, const GLint *length); -GLAPI GLboolean APIENTRY glIsNamedStringARB (GLint namelen, const GLchar *name); -GLAPI void APIENTRY glGetNamedStringARB (GLint namelen, const GLchar *name, GLsizei bufSize, GLint *stringlen, GLchar *string); -GLAPI void APIENTRY glGetNamedStringivARB (GLint namelen, const GLchar *name, GLenum pname, GLint *params); -#endif -#endif /* GL_ARB_shading_language_include */ - -#ifndef GL_ARB_shading_language_packing -#define GL_ARB_shading_language_packing 1 -#endif /* GL_ARB_shading_language_packing */ - -#ifndef GL_ARB_sparse_buffer -#define GL_ARB_sparse_buffer 1 -#define GL_SPARSE_STORAGE_BIT_ARB 0x0400 -#define GL_SPARSE_BUFFER_PAGE_SIZE_ARB 0x82F8 -typedef void (APIENTRYP PFNGLBUFFERPAGECOMMITMENTARBPROC) (GLenum target, GLintptr offset, GLsizeiptr size, GLboolean commit); -typedef void (APIENTRYP PFNGLNAMEDBUFFERPAGECOMMITMENTEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, GLboolean commit); -typedef void (APIENTRYP PFNGLNAMEDBUFFERPAGECOMMITMENTARBPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, GLboolean commit); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glBufferPageCommitmentARB (GLenum target, GLintptr offset, GLsizeiptr size, GLboolean commit); -GLAPI void APIENTRY glNamedBufferPageCommitmentEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, GLboolean commit); -GLAPI void APIENTRY glNamedBufferPageCommitmentARB (GLuint buffer, GLintptr offset, GLsizeiptr size, GLboolean commit); -#endif -#endif /* GL_ARB_sparse_buffer */ - -#ifndef GL_ARB_sparse_texture -#define GL_ARB_sparse_texture 1 -#define GL_TEXTURE_SPARSE_ARB 0x91A6 -#define GL_VIRTUAL_PAGE_SIZE_INDEX_ARB 0x91A7 -#define GL_NUM_SPARSE_LEVELS_ARB 0x91AA -#define GL_NUM_VIRTUAL_PAGE_SIZES_ARB 0x91A8 -#define GL_VIRTUAL_PAGE_SIZE_X_ARB 0x9195 -#define GL_VIRTUAL_PAGE_SIZE_Y_ARB 0x9196 -#define GL_VIRTUAL_PAGE_SIZE_Z_ARB 0x9197 -#define GL_MAX_SPARSE_TEXTURE_SIZE_ARB 0x9198 -#define GL_MAX_SPARSE_3D_TEXTURE_SIZE_ARB 0x9199 -#define GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS_ARB 0x919A -#define GL_SPARSE_TEXTURE_FULL_ARRAY_CUBE_MIPMAPS_ARB 0x91A9 -typedef void (APIENTRYP PFNGLTEXPAGECOMMITMENTARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glTexPageCommitmentARB (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit); -#endif -#endif /* GL_ARB_sparse_texture */ - -#ifndef GL_ARB_sparse_texture2 -#define GL_ARB_sparse_texture2 1 -#endif /* GL_ARB_sparse_texture2 */ - -#ifndef GL_ARB_sparse_texture_clamp -#define GL_ARB_sparse_texture_clamp 1 -#endif /* GL_ARB_sparse_texture_clamp */ - -#ifndef GL_ARB_spirv_extensions -#define GL_ARB_spirv_extensions 1 -#endif /* GL_ARB_spirv_extensions */ - -#ifndef GL_ARB_stencil_texturing -#define GL_ARB_stencil_texturing 1 -#endif /* GL_ARB_stencil_texturing */ - -#ifndef GL_ARB_sync -#define GL_ARB_sync 1 -#endif /* GL_ARB_sync */ - -#ifndef GL_ARB_tessellation_shader -#define GL_ARB_tessellation_shader 1 -#endif /* GL_ARB_tessellation_shader */ - -#ifndef GL_ARB_texture_barrier -#define GL_ARB_texture_barrier 1 -#endif /* GL_ARB_texture_barrier */ - -#ifndef GL_ARB_texture_border_clamp -#define GL_ARB_texture_border_clamp 1 -#define GL_CLAMP_TO_BORDER_ARB 0x812D -#endif /* GL_ARB_texture_border_clamp */ - -#ifndef GL_ARB_texture_buffer_object -#define GL_ARB_texture_buffer_object 1 -#define GL_TEXTURE_BUFFER_ARB 0x8C2A -#define GL_MAX_TEXTURE_BUFFER_SIZE_ARB 0x8C2B -#define GL_TEXTURE_BINDING_BUFFER_ARB 0x8C2C -#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING_ARB 0x8C2D -#define GL_TEXTURE_BUFFER_FORMAT_ARB 0x8C2E -typedef void (APIENTRYP PFNGLTEXBUFFERARBPROC) (GLenum target, GLenum internalformat, GLuint buffer); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glTexBufferARB (GLenum target, GLenum internalformat, GLuint buffer); -#endif -#endif /* GL_ARB_texture_buffer_object */ - -#ifndef GL_ARB_texture_buffer_object_rgb32 -#define GL_ARB_texture_buffer_object_rgb32 1 -#endif /* GL_ARB_texture_buffer_object_rgb32 */ - -#ifndef GL_ARB_texture_buffer_range -#define GL_ARB_texture_buffer_range 1 -#endif /* GL_ARB_texture_buffer_range */ - -#ifndef GL_ARB_texture_compression_bptc -#define GL_ARB_texture_compression_bptc 1 -#define GL_COMPRESSED_RGBA_BPTC_UNORM_ARB 0x8E8C -#define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB 0x8E8D -#define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB 0x8E8E -#define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB 0x8E8F -#endif /* GL_ARB_texture_compression_bptc */ - -#ifndef GL_ARB_texture_compression_rgtc -#define GL_ARB_texture_compression_rgtc 1 -#endif /* GL_ARB_texture_compression_rgtc */ - -#ifndef GL_ARB_texture_cube_map_array -#define GL_ARB_texture_cube_map_array 1 -#define GL_TEXTURE_CUBE_MAP_ARRAY_ARB 0x9009 -#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB 0x900A -#define GL_PROXY_TEXTURE_CUBE_MAP_ARRAY_ARB 0x900B -#define GL_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900C -#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_ARB 0x900D -#define GL_INT_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900E -#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900F -#endif /* GL_ARB_texture_cube_map_array */ - -#ifndef GL_ARB_texture_filter_anisotropic -#define GL_ARB_texture_filter_anisotropic 1 -#endif /* GL_ARB_texture_filter_anisotropic */ - -#ifndef GL_ARB_texture_filter_minmax -#define GL_ARB_texture_filter_minmax 1 -#define GL_TEXTURE_REDUCTION_MODE_ARB 0x9366 -#define GL_WEIGHTED_AVERAGE_ARB 0x9367 -#endif /* GL_ARB_texture_filter_minmax */ - -#ifndef GL_ARB_texture_gather -#define GL_ARB_texture_gather 1 -#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5E -#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5F -#define GL_MAX_PROGRAM_TEXTURE_GATHER_COMPONENTS_ARB 0x8F9F -#endif /* GL_ARB_texture_gather */ - -#ifndef GL_ARB_texture_mirror_clamp_to_edge -#define GL_ARB_texture_mirror_clamp_to_edge 1 -#endif /* GL_ARB_texture_mirror_clamp_to_edge */ - -#ifndef GL_ARB_texture_mirrored_repeat -#define GL_ARB_texture_mirrored_repeat 1 -#define GL_MIRRORED_REPEAT_ARB 0x8370 -#endif /* GL_ARB_texture_mirrored_repeat */ - -#ifndef GL_ARB_texture_multisample -#define GL_ARB_texture_multisample 1 -#endif /* GL_ARB_texture_multisample */ - -#ifndef GL_ARB_texture_non_power_of_two -#define GL_ARB_texture_non_power_of_two 1 -#endif /* GL_ARB_texture_non_power_of_two */ - -#ifndef GL_ARB_texture_query_levels -#define GL_ARB_texture_query_levels 1 -#endif /* GL_ARB_texture_query_levels */ - -#ifndef GL_ARB_texture_query_lod -#define GL_ARB_texture_query_lod 1 -#endif /* GL_ARB_texture_query_lod */ - -#ifndef GL_ARB_texture_rg -#define GL_ARB_texture_rg 1 -#endif /* GL_ARB_texture_rg */ - -#ifndef GL_ARB_texture_rgb10_a2ui -#define GL_ARB_texture_rgb10_a2ui 1 -#endif /* GL_ARB_texture_rgb10_a2ui */ - -#ifndef GL_ARB_texture_stencil8 -#define GL_ARB_texture_stencil8 1 -#endif /* GL_ARB_texture_stencil8 */ - -#ifndef GL_ARB_texture_storage -#define GL_ARB_texture_storage 1 -#endif /* GL_ARB_texture_storage */ - -#ifndef GL_ARB_texture_storage_multisample -#define GL_ARB_texture_storage_multisample 1 -#endif /* GL_ARB_texture_storage_multisample */ - -#ifndef GL_ARB_texture_swizzle -#define GL_ARB_texture_swizzle 1 -#endif /* GL_ARB_texture_swizzle */ - -#ifndef GL_ARB_texture_view -#define GL_ARB_texture_view 1 -#endif /* GL_ARB_texture_view */ - -#ifndef GL_ARB_timer_query -#define GL_ARB_timer_query 1 -#endif /* GL_ARB_timer_query */ - -#ifndef GL_ARB_transform_feedback2 -#define GL_ARB_transform_feedback2 1 -#endif /* GL_ARB_transform_feedback2 */ - -#ifndef GL_ARB_transform_feedback3 -#define GL_ARB_transform_feedback3 1 -#endif /* GL_ARB_transform_feedback3 */ - -#ifndef GL_ARB_transform_feedback_instanced -#define GL_ARB_transform_feedback_instanced 1 -#endif /* GL_ARB_transform_feedback_instanced */ - -#ifndef GL_ARB_transform_feedback_overflow_query -#define GL_ARB_transform_feedback_overflow_query 1 -#define GL_TRANSFORM_FEEDBACK_OVERFLOW_ARB 0x82EC -#define GL_TRANSFORM_FEEDBACK_STREAM_OVERFLOW_ARB 0x82ED -#endif /* GL_ARB_transform_feedback_overflow_query */ - -#ifndef GL_ARB_uniform_buffer_object -#define GL_ARB_uniform_buffer_object 1 -#endif /* GL_ARB_uniform_buffer_object */ - -#ifndef GL_ARB_vertex_array_bgra -#define GL_ARB_vertex_array_bgra 1 -#endif /* GL_ARB_vertex_array_bgra */ - -#ifndef GL_ARB_vertex_array_object -#define GL_ARB_vertex_array_object 1 -#endif /* GL_ARB_vertex_array_object */ - -#ifndef GL_ARB_vertex_attrib_64bit -#define GL_ARB_vertex_attrib_64bit 1 -#endif /* GL_ARB_vertex_attrib_64bit */ - -#ifndef GL_ARB_vertex_attrib_binding -#define GL_ARB_vertex_attrib_binding 1 -#endif /* GL_ARB_vertex_attrib_binding */ - -#ifndef GL_ARB_vertex_type_10f_11f_11f_rev -#define GL_ARB_vertex_type_10f_11f_11f_rev 1 -#endif /* GL_ARB_vertex_type_10f_11f_11f_rev */ - -#ifndef GL_ARB_vertex_type_2_10_10_10_rev -#define GL_ARB_vertex_type_2_10_10_10_rev 1 -#endif /* GL_ARB_vertex_type_2_10_10_10_rev */ - -#ifndef GL_ARB_viewport_array -#define GL_ARB_viewport_array 1 -#endif /* GL_ARB_viewport_array */ - -#ifndef GL_KHR_blend_equation_advanced -#define GL_KHR_blend_equation_advanced 1 -#define GL_MULTIPLY_KHR 0x9294 -#define GL_SCREEN_KHR 0x9295 -#define GL_OVERLAY_KHR 0x9296 -#define GL_DARKEN_KHR 0x9297 -#define GL_LIGHTEN_KHR 0x9298 -#define GL_COLORDODGE_KHR 0x9299 -#define GL_COLORBURN_KHR 0x929A -#define GL_HARDLIGHT_KHR 0x929B -#define GL_SOFTLIGHT_KHR 0x929C -#define GL_DIFFERENCE_KHR 0x929E -#define GL_EXCLUSION_KHR 0x92A0 -#define GL_HSL_HUE_KHR 0x92AD -#define GL_HSL_SATURATION_KHR 0x92AE -#define GL_HSL_COLOR_KHR 0x92AF -#define GL_HSL_LUMINOSITY_KHR 0x92B0 -typedef void (APIENTRYP PFNGLBLENDBARRIERKHRPROC) (void); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glBlendBarrierKHR (void); -#endif -#endif /* GL_KHR_blend_equation_advanced */ - -#ifndef GL_KHR_blend_equation_advanced_coherent -#define GL_KHR_blend_equation_advanced_coherent 1 -#define GL_BLEND_ADVANCED_COHERENT_KHR 0x9285 -#endif /* GL_KHR_blend_equation_advanced_coherent */ - -#ifndef GL_KHR_context_flush_control -#define GL_KHR_context_flush_control 1 -#endif /* GL_KHR_context_flush_control */ - -#ifndef GL_KHR_debug -#define GL_KHR_debug 1 -#endif /* GL_KHR_debug */ - -#ifndef GL_KHR_no_error -#define GL_KHR_no_error 1 -#define GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR 0x00000008 -#endif /* GL_KHR_no_error */ - -#ifndef GL_KHR_robust_buffer_access_behavior -#define GL_KHR_robust_buffer_access_behavior 1 -#endif /* GL_KHR_robust_buffer_access_behavior */ - -#ifndef GL_KHR_robustness -#define GL_KHR_robustness 1 -#define GL_CONTEXT_ROBUST_ACCESS 0x90F3 -#endif /* GL_KHR_robustness */ - -#ifndef GL_KHR_texture_compression_astc_hdr -#define GL_KHR_texture_compression_astc_hdr 1 -#define GL_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93B0 -#define GL_COMPRESSED_RGBA_ASTC_5x4_KHR 0x93B1 -#define GL_COMPRESSED_RGBA_ASTC_5x5_KHR 0x93B2 -#define GL_COMPRESSED_RGBA_ASTC_6x5_KHR 0x93B3 -#define GL_COMPRESSED_RGBA_ASTC_6x6_KHR 0x93B4 -#define GL_COMPRESSED_RGBA_ASTC_8x5_KHR 0x93B5 -#define GL_COMPRESSED_RGBA_ASTC_8x6_KHR 0x93B6 -#define GL_COMPRESSED_RGBA_ASTC_8x8_KHR 0x93B7 -#define GL_COMPRESSED_RGBA_ASTC_10x5_KHR 0x93B8 -#define GL_COMPRESSED_RGBA_ASTC_10x6_KHR 0x93B9 -#define GL_COMPRESSED_RGBA_ASTC_10x8_KHR 0x93BA -#define GL_COMPRESSED_RGBA_ASTC_10x10_KHR 0x93BB -#define GL_COMPRESSED_RGBA_ASTC_12x10_KHR 0x93BC -#define GL_COMPRESSED_RGBA_ASTC_12x12_KHR 0x93BD -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR 0x93D0 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR 0x93D1 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR 0x93D2 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR 0x93D3 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR 0x93D4 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR 0x93D5 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR 0x93D6 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR 0x93D7 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR 0x93D8 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR 0x93D9 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR 0x93DA -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR 0x93DB -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR 0x93DC -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR 0x93DD -#endif /* GL_KHR_texture_compression_astc_hdr */ - -#ifndef GL_KHR_texture_compression_astc_ldr -#define GL_KHR_texture_compression_astc_ldr 1 -#endif /* GL_KHR_texture_compression_astc_ldr */ - -#ifndef GL_KHR_texture_compression_astc_sliced_3d -#define GL_KHR_texture_compression_astc_sliced_3d 1 -#endif /* GL_KHR_texture_compression_astc_sliced_3d */ - -#ifndef GL_AMD_performance_monitor -#define GL_AMD_performance_monitor 1 -#define GL_COUNTER_TYPE_AMD 0x8BC0 -#define GL_COUNTER_RANGE_AMD 0x8BC1 -#define GL_UNSIGNED_INT64_AMD 0x8BC2 -#define GL_PERCENTAGE_AMD 0x8BC3 -#define GL_PERFMON_RESULT_AVAILABLE_AMD 0x8BC4 -#define GL_PERFMON_RESULT_SIZE_AMD 0x8BC5 -#define GL_PERFMON_RESULT_AMD 0x8BC6 -typedef void (APIENTRYP PFNGLGETPERFMONITORGROUPSAMDPROC) (GLint *numGroups, GLsizei groupsSize, GLuint *groups); -typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERSAMDPROC) (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters); -typedef void (APIENTRYP PFNGLGETPERFMONITORGROUPSTRINGAMDPROC) (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString); -typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC) (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString); -typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERINFOAMDPROC) (GLuint group, GLuint counter, GLenum pname, void *data); -typedef void (APIENTRYP PFNGLGENPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors); -typedef void (APIENTRYP PFNGLDELETEPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors); -typedef void (APIENTRYP PFNGLSELECTPERFMONITORCOUNTERSAMDPROC) (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *counterList); -typedef void (APIENTRYP PFNGLBEGINPERFMONITORAMDPROC) (GLuint monitor); -typedef void (APIENTRYP PFNGLENDPERFMONITORAMDPROC) (GLuint monitor); -typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERDATAAMDPROC) (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glGetPerfMonitorGroupsAMD (GLint *numGroups, GLsizei groupsSize, GLuint *groups); -GLAPI void APIENTRY glGetPerfMonitorCountersAMD (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters); -GLAPI void APIENTRY glGetPerfMonitorGroupStringAMD (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString); -GLAPI void APIENTRY glGetPerfMonitorCounterStringAMD (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString); -GLAPI void APIENTRY glGetPerfMonitorCounterInfoAMD (GLuint group, GLuint counter, GLenum pname, void *data); -GLAPI void APIENTRY glGenPerfMonitorsAMD (GLsizei n, GLuint *monitors); -GLAPI void APIENTRY glDeletePerfMonitorsAMD (GLsizei n, GLuint *monitors); -GLAPI void APIENTRY glSelectPerfMonitorCountersAMD (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *counterList); -GLAPI void APIENTRY glBeginPerfMonitorAMD (GLuint monitor); -GLAPI void APIENTRY glEndPerfMonitorAMD (GLuint monitor); -GLAPI void APIENTRY glGetPerfMonitorCounterDataAMD (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten); -#endif -#endif /* GL_AMD_performance_monitor */ - -#ifndef GL_APPLE_rgb_422 -#define GL_APPLE_rgb_422 1 -#define GL_RGB_422_APPLE 0x8A1F -#define GL_UNSIGNED_SHORT_8_8_APPLE 0x85BA -#define GL_UNSIGNED_SHORT_8_8_REV_APPLE 0x85BB -#define GL_RGB_RAW_422_APPLE 0x8A51 -#endif /* GL_APPLE_rgb_422 */ - -#ifndef GL_EXT_debug_label -#define GL_EXT_debug_label 1 -#define GL_PROGRAM_PIPELINE_OBJECT_EXT 0x8A4F -#define GL_PROGRAM_OBJECT_EXT 0x8B40 -#define GL_SHADER_OBJECT_EXT 0x8B48 -#define GL_BUFFER_OBJECT_EXT 0x9151 -#define GL_QUERY_OBJECT_EXT 0x9153 -#define GL_VERTEX_ARRAY_OBJECT_EXT 0x9154 -typedef void (APIENTRYP PFNGLLABELOBJECTEXTPROC) (GLenum type, GLuint object, GLsizei length, const GLchar *label); -typedef void (APIENTRYP PFNGLGETOBJECTLABELEXTPROC) (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glLabelObjectEXT (GLenum type, GLuint object, GLsizei length, const GLchar *label); -GLAPI void APIENTRY glGetObjectLabelEXT (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label); -#endif -#endif /* GL_EXT_debug_label */ - -#ifndef GL_EXT_debug_marker -#define GL_EXT_debug_marker 1 -typedef void (APIENTRYP PFNGLINSERTEVENTMARKEREXTPROC) (GLsizei length, const GLchar *marker); -typedef void (APIENTRYP PFNGLPUSHGROUPMARKEREXTPROC) (GLsizei length, const GLchar *marker); -typedef void (APIENTRYP PFNGLPOPGROUPMARKEREXTPROC) (void); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glInsertEventMarkerEXT (GLsizei length, const GLchar *marker); -GLAPI void APIENTRY glPushGroupMarkerEXT (GLsizei length, const GLchar *marker); -GLAPI void APIENTRY glPopGroupMarkerEXT (void); -#endif -#endif /* GL_EXT_debug_marker */ - -#ifndef GL_EXT_direct_state_access -#define GL_EXT_direct_state_access 1 -#define GL_PROGRAM_MATRIX_EXT 0x8E2D -#define GL_TRANSPOSE_PROGRAM_MATRIX_EXT 0x8E2E -#define GL_PROGRAM_MATRIX_STACK_DEPTH_EXT 0x8E2F -typedef void (APIENTRYP PFNGLMATRIXLOADFEXTPROC) (GLenum mode, const GLfloat *m); -typedef void (APIENTRYP PFNGLMATRIXLOADDEXTPROC) (GLenum mode, const GLdouble *m); -typedef void (APIENTRYP PFNGLMATRIXMULTFEXTPROC) (GLenum mode, const GLfloat *m); -typedef void (APIENTRYP PFNGLMATRIXMULTDEXTPROC) (GLenum mode, const GLdouble *m); -typedef void (APIENTRYP PFNGLMATRIXLOADIDENTITYEXTPROC) (GLenum mode); -typedef void (APIENTRYP PFNGLMATRIXROTATEFEXTPROC) (GLenum mode, GLfloat angle, GLfloat x, GLfloat y, GLfloat z); -typedef void (APIENTRYP PFNGLMATRIXROTATEDEXTPROC) (GLenum mode, GLdouble angle, GLdouble x, GLdouble y, GLdouble z); -typedef void (APIENTRYP PFNGLMATRIXSCALEFEXTPROC) (GLenum mode, GLfloat x, GLfloat y, GLfloat z); -typedef void (APIENTRYP PFNGLMATRIXSCALEDEXTPROC) (GLenum mode, GLdouble x, GLdouble y, GLdouble z); -typedef void (APIENTRYP PFNGLMATRIXTRANSLATEFEXTPROC) (GLenum mode, GLfloat x, GLfloat y, GLfloat z); -typedef void (APIENTRYP PFNGLMATRIXTRANSLATEDEXTPROC) (GLenum mode, GLdouble x, GLdouble y, GLdouble z); -typedef void (APIENTRYP PFNGLMATRIXFRUSTUMEXTPROC) (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); -typedef void (APIENTRYP PFNGLMATRIXORTHOEXTPROC) (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); -typedef void (APIENTRYP PFNGLMATRIXPOPEXTPROC) (GLenum mode); -typedef void (APIENTRYP PFNGLMATRIXPUSHEXTPROC) (GLenum mode); -typedef void (APIENTRYP PFNGLCLIENTATTRIBDEFAULTEXTPROC) (GLbitfield mask); -typedef void (APIENTRYP PFNGLPUSHCLIENTATTRIBDEFAULTEXTPROC) (GLbitfield mask); -typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLfloat param); -typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLfloat *params); -typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLint param); -typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLint *params); -typedef void (APIENTRYP PFNGLTEXTUREIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLCOPYTEXTUREIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); -typedef void (APIENTRYP PFNGLCOPYTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); -typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); -typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLGETTEXTUREIMAGEEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum format, GLenum type, void *pixels); -typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLfloat *params); -typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum pname, GLfloat *params); -typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLTEXTUREIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLBINDMULTITEXTUREEXTPROC) (GLenum texunit, GLenum target, GLuint texture); -typedef void (APIENTRYP PFNGLMULTITEXCOORDPOINTEREXTPROC) (GLenum texunit, GLint size, GLenum type, GLsizei stride, const void *pointer); -typedef void (APIENTRYP PFNGLMULTITEXENVFEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat param); -typedef void (APIENTRYP PFNGLMULTITEXENVFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params); -typedef void (APIENTRYP PFNGLMULTITEXENVIEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint param); -typedef void (APIENTRYP PFNGLMULTITEXENVIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLint *params); -typedef void (APIENTRYP PFNGLMULTITEXGENDEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLdouble param); -typedef void (APIENTRYP PFNGLMULTITEXGENDVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, const GLdouble *params); -typedef void (APIENTRYP PFNGLMULTITEXGENFEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLfloat param); -typedef void (APIENTRYP PFNGLMULTITEXGENFVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, const GLfloat *params); -typedef void (APIENTRYP PFNGLMULTITEXGENIEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLint param); -typedef void (APIENTRYP PFNGLMULTITEXGENIVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, const GLint *params); -typedef void (APIENTRYP PFNGLGETMULTITEXENVFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat *params); -typedef void (APIENTRYP PFNGLGETMULTITEXENVIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETMULTITEXGENDVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLdouble *params); -typedef void (APIENTRYP PFNGLGETMULTITEXGENFVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLfloat *params); -typedef void (APIENTRYP PFNGLGETMULTITEXGENIVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint param); -typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLint *params); -typedef void (APIENTRYP PFNGLMULTITEXPARAMETERFEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat param); -typedef void (APIENTRYP PFNGLMULTITEXPARAMETERFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params); -typedef void (APIENTRYP PFNGLMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLCOPYMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); -typedef void (APIENTRYP PFNGLCOPYMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); -typedef void (APIENTRYP PFNGLCOPYMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); -typedef void (APIENTRYP PFNGLCOPYMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLGETMULTITEXIMAGEEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum format, GLenum type, void *pixels); -typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat *params); -typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETMULTITEXLEVELPARAMETERFVEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum pname, GLfloat *params); -typedef void (APIENTRYP PFNGLGETMULTITEXLEVELPARAMETERIVEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLMULTITEXIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); -typedef void (APIENTRYP PFNGLCOPYMULTITEXSUBIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLENABLECLIENTSTATEINDEXEDEXTPROC) (GLenum array, GLuint index); -typedef void (APIENTRYP PFNGLDISABLECLIENTSTATEINDEXEDEXTPROC) (GLenum array, GLuint index); -typedef void (APIENTRYP PFNGLGETFLOATINDEXEDVEXTPROC) (GLenum target, GLuint index, GLfloat *data); -typedef void (APIENTRYP PFNGLGETDOUBLEINDEXEDVEXTPROC) (GLenum target, GLuint index, GLdouble *data); -typedef void (APIENTRYP PFNGLGETPOINTERINDEXEDVEXTPROC) (GLenum target, GLuint index, void **data); -typedef void (APIENTRYP PFNGLENABLEINDEXEDEXTPROC) (GLenum target, GLuint index); -typedef void (APIENTRYP PFNGLDISABLEINDEXEDEXTPROC) (GLenum target, GLuint index); -typedef GLboolean (APIENTRYP PFNGLISENABLEDINDEXEDEXTPROC) (GLenum target, GLuint index); -typedef void (APIENTRYP PFNGLGETINTEGERINDEXEDVEXTPROC) (GLenum target, GLuint index, GLint *data); -typedef void (APIENTRYP PFNGLGETBOOLEANINDEXEDVEXTPROC) (GLenum target, GLuint index, GLboolean *data); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits); -typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits); -typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXTUREIMAGEEXTPROC) (GLuint texture, GLenum target, GLint lod, void *img); -typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits); -typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits); -typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits); -typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits); -typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits); -typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits); -typedef void (APIENTRYP PFNGLGETCOMPRESSEDMULTITEXIMAGEEXTPROC) (GLenum texunit, GLenum target, GLint lod, void *img); -typedef void (APIENTRYP PFNGLMATRIXLOADTRANSPOSEFEXTPROC) (GLenum mode, const GLfloat *m); -typedef void (APIENTRYP PFNGLMATRIXLOADTRANSPOSEDEXTPROC) (GLenum mode, const GLdouble *m); -typedef void (APIENTRYP PFNGLMATRIXMULTTRANSPOSEFEXTPROC) (GLenum mode, const GLfloat *m); -typedef void (APIENTRYP PFNGLMATRIXMULTTRANSPOSEDEXTPROC) (GLenum mode, const GLdouble *m); -typedef void (APIENTRYP PFNGLNAMEDBUFFERDATAEXTPROC) (GLuint buffer, GLsizeiptr size, const void *data, GLenum usage); -typedef void (APIENTRYP PFNGLNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); -typedef void *(APIENTRYP PFNGLMAPNAMEDBUFFEREXTPROC) (GLuint buffer, GLenum access); -typedef GLboolean (APIENTRYP PFNGLUNMAPNAMEDBUFFEREXTPROC) (GLuint buffer); -typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERIVEXTPROC) (GLuint buffer, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPOINTERVEXTPROC) (GLuint buffer, GLenum pname, void **params); -typedef void (APIENTRYP PFNGLGETNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, void *data); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FEXTPROC) (GLuint program, GLint location, GLfloat v0); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IEXTPROC) (GLuint program, GLint location, GLint v0); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (APIENTRYP PFNGLTEXTUREBUFFEREXTPROC) (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer); -typedef void (APIENTRYP PFNGLMULTITEXBUFFEREXTPROC) (GLenum texunit, GLenum target, GLenum internalformat, GLuint buffer); -typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLint *params); -typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIUIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLuint *params); -typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIUIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLuint *params); -typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLint *params); -typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIUIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLuint *params); -typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERIIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERIUIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLuint *params); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIEXTPROC) (GLuint program, GLint location, GLuint v0); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); -typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERS4FVEXTPROC) (GLuint program, GLenum target, GLuint index, GLsizei count, const GLfloat *params); -typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4IEXTPROC) (GLuint program, GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); -typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4IVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLint *params); -typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERSI4IVEXTPROC) (GLuint program, GLenum target, GLuint index, GLsizei count, const GLint *params); -typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4UIEXTPROC) (GLuint program, GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); -typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4UIVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLuint *params); -typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERSI4UIVEXTPROC) (GLuint program, GLenum target, GLuint index, GLsizei count, const GLuint *params); -typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERIIVEXTPROC) (GLuint program, GLenum target, GLuint index, GLint *params); -typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERIUIVEXTPROC) (GLuint program, GLenum target, GLuint index, GLuint *params); -typedef void (APIENTRYP PFNGLENABLECLIENTSTATEIEXTPROC) (GLenum array, GLuint index); -typedef void (APIENTRYP PFNGLDISABLECLIENTSTATEIEXTPROC) (GLenum array, GLuint index); -typedef void (APIENTRYP PFNGLGETFLOATI_VEXTPROC) (GLenum pname, GLuint index, GLfloat *params); -typedef void (APIENTRYP PFNGLGETDOUBLEI_VEXTPROC) (GLenum pname, GLuint index, GLdouble *params); -typedef void (APIENTRYP PFNGLGETPOINTERI_VEXTPROC) (GLenum pname, GLuint index, void **params); -typedef void (APIENTRYP PFNGLNAMEDPROGRAMSTRINGEXTPROC) (GLuint program, GLenum target, GLenum format, GLsizei len, const void *string); -typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4DEXTPROC) (GLuint program, GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); -typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4DVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLdouble *params); -typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4FEXTPROC) (GLuint program, GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); -typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4FVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLfloat *params); -typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERDVEXTPROC) (GLuint program, GLenum target, GLuint index, GLdouble *params); -typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERFVEXTPROC) (GLuint program, GLenum target, GLuint index, GLfloat *params); -typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMIVEXTPROC) (GLuint program, GLenum target, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMSTRINGEXTPROC) (GLuint program, GLenum target, GLenum pname, void *string); -typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEEXTPROC) (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLGETNAMEDRENDERBUFFERPARAMETERIVEXTPROC) (GLuint renderbuffer, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLECOVERAGEEXTPROC) (GLuint renderbuffer, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); -typedef GLenum (APIENTRYP PFNGLCHECKNAMEDFRAMEBUFFERSTATUSEXTPROC) (GLuint framebuffer, GLenum target); -typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURE1DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level); -typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURE2DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level); -typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURE3DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); -typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERRENDERBUFFEREXTPROC) (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); -typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLGENERATETEXTUREMIPMAPEXTPROC) (GLuint texture, GLenum target); -typedef void (APIENTRYP PFNGLGENERATEMULTITEXMIPMAPEXTPROC) (GLenum texunit, GLenum target); -typedef void (APIENTRYP PFNGLFRAMEBUFFERDRAWBUFFEREXTPROC) (GLuint framebuffer, GLenum mode); -typedef void (APIENTRYP PFNGLFRAMEBUFFERDRAWBUFFERSEXTPROC) (GLuint framebuffer, GLsizei n, const GLenum *bufs); -typedef void (APIENTRYP PFNGLFRAMEBUFFERREADBUFFEREXTPROC) (GLuint framebuffer, GLenum mode); -typedef void (APIENTRYP PFNGLGETFRAMEBUFFERPARAMETERIVEXTPROC) (GLuint framebuffer, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLNAMEDCOPYBUFFERSUBDATAEXTPROC) (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); -typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTUREEXTPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); -typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURELAYEREXTPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); -typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTUREFACEEXTPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLenum face); -typedef void (APIENTRYP PFNGLTEXTURERENDERBUFFEREXTPROC) (GLuint texture, GLenum target, GLuint renderbuffer); -typedef void (APIENTRYP PFNGLMULTITEXRENDERBUFFEREXTPROC) (GLenum texunit, GLenum target, GLuint renderbuffer); -typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); -typedef void (APIENTRYP PFNGLVERTEXARRAYCOLOROFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); -typedef void (APIENTRYP PFNGLVERTEXARRAYEDGEFLAGOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLsizei stride, GLintptr offset); -typedef void (APIENTRYP PFNGLVERTEXARRAYINDEXOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); -typedef void (APIENTRYP PFNGLVERTEXARRAYNORMALOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); -typedef void (APIENTRYP PFNGLVERTEXARRAYTEXCOORDOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); -typedef void (APIENTRYP PFNGLVERTEXARRAYMULTITEXCOORDOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum texunit, GLint size, GLenum type, GLsizei stride, GLintptr offset); -typedef void (APIENTRYP PFNGLVERTEXARRAYFOGCOORDOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); -typedef void (APIENTRYP PFNGLVERTEXARRAYSECONDARYCOLOROFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); -typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offset); -typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBIOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); -typedef void (APIENTRYP PFNGLENABLEVERTEXARRAYEXTPROC) (GLuint vaobj, GLenum array); -typedef void (APIENTRYP PFNGLDISABLEVERTEXARRAYEXTPROC) (GLuint vaobj, GLenum array); -typedef void (APIENTRYP PFNGLENABLEVERTEXARRAYATTRIBEXTPROC) (GLuint vaobj, GLuint index); -typedef void (APIENTRYP PFNGLDISABLEVERTEXARRAYATTRIBEXTPROC) (GLuint vaobj, GLuint index); -typedef void (APIENTRYP PFNGLGETVERTEXARRAYINTEGERVEXTPROC) (GLuint vaobj, GLenum pname, GLint *param); -typedef void (APIENTRYP PFNGLGETVERTEXARRAYPOINTERVEXTPROC) (GLuint vaobj, GLenum pname, void **param); -typedef void (APIENTRYP PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint *param); -typedef void (APIENTRYP PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, void **param); -typedef void *(APIENTRYP PFNGLMAPNAMEDBUFFERRANGEEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access); -typedef void (APIENTRYP PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length); -typedef void (APIENTRYP PFNGLNAMEDBUFFERSTORAGEEXTPROC) (GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags); -typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERDATAEXTPROC) (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data); -typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLenum internalformat, GLsizeiptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); -typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERPARAMETERIEXTPROC) (GLuint framebuffer, GLenum pname, GLint param); -typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVEXTPROC) (GLuint framebuffer, GLenum pname, GLint *params); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DEXTPROC) (GLuint program, GLint location, GLdouble x); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DEXTPROC) (GLuint program, GLint location, GLdouble x, GLdouble y); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DEXTPROC) (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DEXTPROC) (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -typedef void (APIENTRYP PFNGLTEXTUREBUFFERRANGEEXTPROC) (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); -typedef void (APIENTRYP PFNGLTEXTURESTORAGE1DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); -typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); -typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); -typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DMULTISAMPLEEXTPROC) (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); -typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DMULTISAMPLEEXTPROC) (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); -typedef void (APIENTRYP PFNGLVERTEXARRAYBINDVERTEXBUFFEREXTPROC) (GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); -typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBFORMATEXTPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); -typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBIFORMATEXTPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); -typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBLFORMATEXTPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); -typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBBINDINGEXTPROC) (GLuint vaobj, GLuint attribindex, GLuint bindingindex); -typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXBINDINGDIVISOREXTPROC) (GLuint vaobj, GLuint bindingindex, GLuint divisor); -typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBLOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); -typedef void (APIENTRYP PFNGLTEXTUREPAGECOMMITMENTEXTPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit); -typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBDIVISOREXTPROC) (GLuint vaobj, GLuint index, GLuint divisor); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glMatrixLoadfEXT (GLenum mode, const GLfloat *m); -GLAPI void APIENTRY glMatrixLoaddEXT (GLenum mode, const GLdouble *m); -GLAPI void APIENTRY glMatrixMultfEXT (GLenum mode, const GLfloat *m); -GLAPI void APIENTRY glMatrixMultdEXT (GLenum mode, const GLdouble *m); -GLAPI void APIENTRY glMatrixLoadIdentityEXT (GLenum mode); -GLAPI void APIENTRY glMatrixRotatefEXT (GLenum mode, GLfloat angle, GLfloat x, GLfloat y, GLfloat z); -GLAPI void APIENTRY glMatrixRotatedEXT (GLenum mode, GLdouble angle, GLdouble x, GLdouble y, GLdouble z); -GLAPI void APIENTRY glMatrixScalefEXT (GLenum mode, GLfloat x, GLfloat y, GLfloat z); -GLAPI void APIENTRY glMatrixScaledEXT (GLenum mode, GLdouble x, GLdouble y, GLdouble z); -GLAPI void APIENTRY glMatrixTranslatefEXT (GLenum mode, GLfloat x, GLfloat y, GLfloat z); -GLAPI void APIENTRY glMatrixTranslatedEXT (GLenum mode, GLdouble x, GLdouble y, GLdouble z); -GLAPI void APIENTRY glMatrixFrustumEXT (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); -GLAPI void APIENTRY glMatrixOrthoEXT (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); -GLAPI void APIENTRY glMatrixPopEXT (GLenum mode); -GLAPI void APIENTRY glMatrixPushEXT (GLenum mode); -GLAPI void APIENTRY glClientAttribDefaultEXT (GLbitfield mask); -GLAPI void APIENTRY glPushClientAttribDefaultEXT (GLbitfield mask); -GLAPI void APIENTRY glTextureParameterfEXT (GLuint texture, GLenum target, GLenum pname, GLfloat param); -GLAPI void APIENTRY glTextureParameterfvEXT (GLuint texture, GLenum target, GLenum pname, const GLfloat *params); -GLAPI void APIENTRY glTextureParameteriEXT (GLuint texture, GLenum target, GLenum pname, GLint param); -GLAPI void APIENTRY glTextureParameterivEXT (GLuint texture, GLenum target, GLenum pname, const GLint *params); -GLAPI void APIENTRY glTextureImage1DEXT (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glCopyTextureImage1DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); -GLAPI void APIENTRY glCopyTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); -GLAPI void APIENTRY glCopyTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); -GLAPI void APIENTRY glCopyTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); -GLAPI void APIENTRY glGetTextureImageEXT (GLuint texture, GLenum target, GLint level, GLenum format, GLenum type, void *pixels); -GLAPI void APIENTRY glGetTextureParameterfvEXT (GLuint texture, GLenum target, GLenum pname, GLfloat *params); -GLAPI void APIENTRY glGetTextureParameterivEXT (GLuint texture, GLenum target, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetTextureLevelParameterfvEXT (GLuint texture, GLenum target, GLint level, GLenum pname, GLfloat *params); -GLAPI void APIENTRY glGetTextureLevelParameterivEXT (GLuint texture, GLenum target, GLint level, GLenum pname, GLint *params); -GLAPI void APIENTRY glTextureImage3DEXT (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glTextureSubImage3DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glCopyTextureSubImage3DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); -GLAPI void APIENTRY glBindMultiTextureEXT (GLenum texunit, GLenum target, GLuint texture); -GLAPI void APIENTRY glMultiTexCoordPointerEXT (GLenum texunit, GLint size, GLenum type, GLsizei stride, const void *pointer); -GLAPI void APIENTRY glMultiTexEnvfEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat param); -GLAPI void APIENTRY glMultiTexEnvfvEXT (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params); -GLAPI void APIENTRY glMultiTexEnviEXT (GLenum texunit, GLenum target, GLenum pname, GLint param); -GLAPI void APIENTRY glMultiTexEnvivEXT (GLenum texunit, GLenum target, GLenum pname, const GLint *params); -GLAPI void APIENTRY glMultiTexGendEXT (GLenum texunit, GLenum coord, GLenum pname, GLdouble param); -GLAPI void APIENTRY glMultiTexGendvEXT (GLenum texunit, GLenum coord, GLenum pname, const GLdouble *params); -GLAPI void APIENTRY glMultiTexGenfEXT (GLenum texunit, GLenum coord, GLenum pname, GLfloat param); -GLAPI void APIENTRY glMultiTexGenfvEXT (GLenum texunit, GLenum coord, GLenum pname, const GLfloat *params); -GLAPI void APIENTRY glMultiTexGeniEXT (GLenum texunit, GLenum coord, GLenum pname, GLint param); -GLAPI void APIENTRY glMultiTexGenivEXT (GLenum texunit, GLenum coord, GLenum pname, const GLint *params); -GLAPI void APIENTRY glGetMultiTexEnvfvEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat *params); -GLAPI void APIENTRY glGetMultiTexEnvivEXT (GLenum texunit, GLenum target, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetMultiTexGendvEXT (GLenum texunit, GLenum coord, GLenum pname, GLdouble *params); -GLAPI void APIENTRY glGetMultiTexGenfvEXT (GLenum texunit, GLenum coord, GLenum pname, GLfloat *params); -GLAPI void APIENTRY glGetMultiTexGenivEXT (GLenum texunit, GLenum coord, GLenum pname, GLint *params); -GLAPI void APIENTRY glMultiTexParameteriEXT (GLenum texunit, GLenum target, GLenum pname, GLint param); -GLAPI void APIENTRY glMultiTexParameterivEXT (GLenum texunit, GLenum target, GLenum pname, const GLint *params); -GLAPI void APIENTRY glMultiTexParameterfEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat param); -GLAPI void APIENTRY glMultiTexParameterfvEXT (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params); -GLAPI void APIENTRY glMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glCopyMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); -GLAPI void APIENTRY glCopyMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); -GLAPI void APIENTRY glCopyMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); -GLAPI void APIENTRY glCopyMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); -GLAPI void APIENTRY glGetMultiTexImageEXT (GLenum texunit, GLenum target, GLint level, GLenum format, GLenum type, void *pixels); -GLAPI void APIENTRY glGetMultiTexParameterfvEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat *params); -GLAPI void APIENTRY glGetMultiTexParameterivEXT (GLenum texunit, GLenum target, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetMultiTexLevelParameterfvEXT (GLenum texunit, GLenum target, GLint level, GLenum pname, GLfloat *params); -GLAPI void APIENTRY glGetMultiTexLevelParameterivEXT (GLenum texunit, GLenum target, GLint level, GLenum pname, GLint *params); -GLAPI void APIENTRY glMultiTexImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glMultiTexSubImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); -GLAPI void APIENTRY glCopyMultiTexSubImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); -GLAPI void APIENTRY glEnableClientStateIndexedEXT (GLenum array, GLuint index); -GLAPI void APIENTRY glDisableClientStateIndexedEXT (GLenum array, GLuint index); -GLAPI void APIENTRY glGetFloatIndexedvEXT (GLenum target, GLuint index, GLfloat *data); -GLAPI void APIENTRY glGetDoubleIndexedvEXT (GLenum target, GLuint index, GLdouble *data); -GLAPI void APIENTRY glGetPointerIndexedvEXT (GLenum target, GLuint index, void **data); -GLAPI void APIENTRY glEnableIndexedEXT (GLenum target, GLuint index); -GLAPI void APIENTRY glDisableIndexedEXT (GLenum target, GLuint index); -GLAPI GLboolean APIENTRY glIsEnabledIndexedEXT (GLenum target, GLuint index); -GLAPI void APIENTRY glGetIntegerIndexedvEXT (GLenum target, GLuint index, GLint *data); -GLAPI void APIENTRY glGetBooleanIndexedvEXT (GLenum target, GLuint index, GLboolean *data); -GLAPI void APIENTRY glCompressedTextureImage3DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits); -GLAPI void APIENTRY glCompressedTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits); -GLAPI void APIENTRY glCompressedTextureImage1DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits); -GLAPI void APIENTRY glCompressedTextureSubImage3DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits); -GLAPI void APIENTRY glCompressedTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits); -GLAPI void APIENTRY glCompressedTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits); -GLAPI void APIENTRY glGetCompressedTextureImageEXT (GLuint texture, GLenum target, GLint lod, void *img); -GLAPI void APIENTRY glCompressedMultiTexImage3DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits); -GLAPI void APIENTRY glCompressedMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits); -GLAPI void APIENTRY glCompressedMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits); -GLAPI void APIENTRY glCompressedMultiTexSubImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits); -GLAPI void APIENTRY glCompressedMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits); -GLAPI void APIENTRY glCompressedMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits); -GLAPI void APIENTRY glGetCompressedMultiTexImageEXT (GLenum texunit, GLenum target, GLint lod, void *img); -GLAPI void APIENTRY glMatrixLoadTransposefEXT (GLenum mode, const GLfloat *m); -GLAPI void APIENTRY glMatrixLoadTransposedEXT (GLenum mode, const GLdouble *m); -GLAPI void APIENTRY glMatrixMultTransposefEXT (GLenum mode, const GLfloat *m); -GLAPI void APIENTRY glMatrixMultTransposedEXT (GLenum mode, const GLdouble *m); -GLAPI void APIENTRY glNamedBufferDataEXT (GLuint buffer, GLsizeiptr size, const void *data, GLenum usage); -GLAPI void APIENTRY glNamedBufferSubDataEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); -GLAPI void *APIENTRY glMapNamedBufferEXT (GLuint buffer, GLenum access); -GLAPI GLboolean APIENTRY glUnmapNamedBufferEXT (GLuint buffer); -GLAPI void APIENTRY glGetNamedBufferParameterivEXT (GLuint buffer, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetNamedBufferPointervEXT (GLuint buffer, GLenum pname, void **params); -GLAPI void APIENTRY glGetNamedBufferSubDataEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, void *data); -GLAPI void APIENTRY glProgramUniform1fEXT (GLuint program, GLint location, GLfloat v0); -GLAPI void APIENTRY glProgramUniform2fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1); -GLAPI void APIENTRY glProgramUniform3fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); -GLAPI void APIENTRY glProgramUniform4fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); -GLAPI void APIENTRY glProgramUniform1iEXT (GLuint program, GLint location, GLint v0); -GLAPI void APIENTRY glProgramUniform2iEXT (GLuint program, GLint location, GLint v0, GLint v1); -GLAPI void APIENTRY glProgramUniform3iEXT (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); -GLAPI void APIENTRY glProgramUniform4iEXT (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); -GLAPI void APIENTRY glProgramUniform1fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); -GLAPI void APIENTRY glProgramUniform2fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); -GLAPI void APIENTRY glProgramUniform3fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); -GLAPI void APIENTRY glProgramUniform4fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); -GLAPI void APIENTRY glProgramUniform1ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); -GLAPI void APIENTRY glProgramUniform2ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); -GLAPI void APIENTRY glProgramUniform3ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); -GLAPI void APIENTRY glProgramUniform4ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); -GLAPI void APIENTRY glProgramUniformMatrix2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glProgramUniformMatrix3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glProgramUniformMatrix4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glProgramUniformMatrix2x3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glProgramUniformMatrix3x2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glProgramUniformMatrix2x4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glProgramUniformMatrix4x2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glProgramUniformMatrix3x4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glProgramUniformMatrix4x3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GLAPI void APIENTRY glTextureBufferEXT (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer); -GLAPI void APIENTRY glMultiTexBufferEXT (GLenum texunit, GLenum target, GLenum internalformat, GLuint buffer); -GLAPI void APIENTRY glTextureParameterIivEXT (GLuint texture, GLenum target, GLenum pname, const GLint *params); -GLAPI void APIENTRY glTextureParameterIuivEXT (GLuint texture, GLenum target, GLenum pname, const GLuint *params); -GLAPI void APIENTRY glGetTextureParameterIivEXT (GLuint texture, GLenum target, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetTextureParameterIuivEXT (GLuint texture, GLenum target, GLenum pname, GLuint *params); -GLAPI void APIENTRY glMultiTexParameterIivEXT (GLenum texunit, GLenum target, GLenum pname, const GLint *params); -GLAPI void APIENTRY glMultiTexParameterIuivEXT (GLenum texunit, GLenum target, GLenum pname, const GLuint *params); -GLAPI void APIENTRY glGetMultiTexParameterIivEXT (GLenum texunit, GLenum target, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetMultiTexParameterIuivEXT (GLenum texunit, GLenum target, GLenum pname, GLuint *params); -GLAPI void APIENTRY glProgramUniform1uiEXT (GLuint program, GLint location, GLuint v0); -GLAPI void APIENTRY glProgramUniform2uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1); -GLAPI void APIENTRY glProgramUniform3uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); -GLAPI void APIENTRY glProgramUniform4uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); -GLAPI void APIENTRY glProgramUniform1uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); -GLAPI void APIENTRY glProgramUniform2uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); -GLAPI void APIENTRY glProgramUniform3uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); -GLAPI void APIENTRY glProgramUniform4uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); -GLAPI void APIENTRY glNamedProgramLocalParameters4fvEXT (GLuint program, GLenum target, GLuint index, GLsizei count, const GLfloat *params); -GLAPI void APIENTRY glNamedProgramLocalParameterI4iEXT (GLuint program, GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); -GLAPI void APIENTRY glNamedProgramLocalParameterI4ivEXT (GLuint program, GLenum target, GLuint index, const GLint *params); -GLAPI void APIENTRY glNamedProgramLocalParametersI4ivEXT (GLuint program, GLenum target, GLuint index, GLsizei count, const GLint *params); -GLAPI void APIENTRY glNamedProgramLocalParameterI4uiEXT (GLuint program, GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); -GLAPI void APIENTRY glNamedProgramLocalParameterI4uivEXT (GLuint program, GLenum target, GLuint index, const GLuint *params); -GLAPI void APIENTRY glNamedProgramLocalParametersI4uivEXT (GLuint program, GLenum target, GLuint index, GLsizei count, const GLuint *params); -GLAPI void APIENTRY glGetNamedProgramLocalParameterIivEXT (GLuint program, GLenum target, GLuint index, GLint *params); -GLAPI void APIENTRY glGetNamedProgramLocalParameterIuivEXT (GLuint program, GLenum target, GLuint index, GLuint *params); -GLAPI void APIENTRY glEnableClientStateiEXT (GLenum array, GLuint index); -GLAPI void APIENTRY glDisableClientStateiEXT (GLenum array, GLuint index); -GLAPI void APIENTRY glGetFloati_vEXT (GLenum pname, GLuint index, GLfloat *params); -GLAPI void APIENTRY glGetDoublei_vEXT (GLenum pname, GLuint index, GLdouble *params); -GLAPI void APIENTRY glGetPointeri_vEXT (GLenum pname, GLuint index, void **params); -GLAPI void APIENTRY glNamedProgramStringEXT (GLuint program, GLenum target, GLenum format, GLsizei len, const void *string); -GLAPI void APIENTRY glNamedProgramLocalParameter4dEXT (GLuint program, GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); -GLAPI void APIENTRY glNamedProgramLocalParameter4dvEXT (GLuint program, GLenum target, GLuint index, const GLdouble *params); -GLAPI void APIENTRY glNamedProgramLocalParameter4fEXT (GLuint program, GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); -GLAPI void APIENTRY glNamedProgramLocalParameter4fvEXT (GLuint program, GLenum target, GLuint index, const GLfloat *params); -GLAPI void APIENTRY glGetNamedProgramLocalParameterdvEXT (GLuint program, GLenum target, GLuint index, GLdouble *params); -GLAPI void APIENTRY glGetNamedProgramLocalParameterfvEXT (GLuint program, GLenum target, GLuint index, GLfloat *params); -GLAPI void APIENTRY glGetNamedProgramivEXT (GLuint program, GLenum target, GLenum pname, GLint *params); -GLAPI void APIENTRY glGetNamedProgramStringEXT (GLuint program, GLenum target, GLenum pname, void *string); -GLAPI void APIENTRY glNamedRenderbufferStorageEXT (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); -GLAPI void APIENTRY glGetNamedRenderbufferParameterivEXT (GLuint renderbuffer, GLenum pname, GLint *params); -GLAPI void APIENTRY glNamedRenderbufferStorageMultisampleEXT (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -GLAPI void APIENTRY glNamedRenderbufferStorageMultisampleCoverageEXT (GLuint renderbuffer, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); -GLAPI GLenum APIENTRY glCheckNamedFramebufferStatusEXT (GLuint framebuffer, GLenum target); -GLAPI void APIENTRY glNamedFramebufferTexture1DEXT (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level); -GLAPI void APIENTRY glNamedFramebufferTexture2DEXT (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level); -GLAPI void APIENTRY glNamedFramebufferTexture3DEXT (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); -GLAPI void APIENTRY glNamedFramebufferRenderbufferEXT (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); -GLAPI void APIENTRY glGetNamedFramebufferAttachmentParameterivEXT (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params); -GLAPI void APIENTRY glGenerateTextureMipmapEXT (GLuint texture, GLenum target); -GLAPI void APIENTRY glGenerateMultiTexMipmapEXT (GLenum texunit, GLenum target); -GLAPI void APIENTRY glFramebufferDrawBufferEXT (GLuint framebuffer, GLenum mode); -GLAPI void APIENTRY glFramebufferDrawBuffersEXT (GLuint framebuffer, GLsizei n, const GLenum *bufs); -GLAPI void APIENTRY glFramebufferReadBufferEXT (GLuint framebuffer, GLenum mode); -GLAPI void APIENTRY glGetFramebufferParameterivEXT (GLuint framebuffer, GLenum pname, GLint *params); -GLAPI void APIENTRY glNamedCopyBufferSubDataEXT (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); -GLAPI void APIENTRY glNamedFramebufferTextureEXT (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); -GLAPI void APIENTRY glNamedFramebufferTextureLayerEXT (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); -GLAPI void APIENTRY glNamedFramebufferTextureFaceEXT (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLenum face); -GLAPI void APIENTRY glTextureRenderbufferEXT (GLuint texture, GLenum target, GLuint renderbuffer); -GLAPI void APIENTRY glMultiTexRenderbufferEXT (GLenum texunit, GLenum target, GLuint renderbuffer); -GLAPI void APIENTRY glVertexArrayVertexOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); -GLAPI void APIENTRY glVertexArrayColorOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); -GLAPI void APIENTRY glVertexArrayEdgeFlagOffsetEXT (GLuint vaobj, GLuint buffer, GLsizei stride, GLintptr offset); -GLAPI void APIENTRY glVertexArrayIndexOffsetEXT (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); -GLAPI void APIENTRY glVertexArrayNormalOffsetEXT (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); -GLAPI void APIENTRY glVertexArrayTexCoordOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); -GLAPI void APIENTRY glVertexArrayMultiTexCoordOffsetEXT (GLuint vaobj, GLuint buffer, GLenum texunit, GLint size, GLenum type, GLsizei stride, GLintptr offset); -GLAPI void APIENTRY glVertexArrayFogCoordOffsetEXT (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); -GLAPI void APIENTRY glVertexArraySecondaryColorOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); -GLAPI void APIENTRY glVertexArrayVertexAttribOffsetEXT (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offset); -GLAPI void APIENTRY glVertexArrayVertexAttribIOffsetEXT (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); -GLAPI void APIENTRY glEnableVertexArrayEXT (GLuint vaobj, GLenum array); -GLAPI void APIENTRY glDisableVertexArrayEXT (GLuint vaobj, GLenum array); -GLAPI void APIENTRY glEnableVertexArrayAttribEXT (GLuint vaobj, GLuint index); -GLAPI void APIENTRY glDisableVertexArrayAttribEXT (GLuint vaobj, GLuint index); -GLAPI void APIENTRY glGetVertexArrayIntegervEXT (GLuint vaobj, GLenum pname, GLint *param); -GLAPI void APIENTRY glGetVertexArrayPointervEXT (GLuint vaobj, GLenum pname, void **param); -GLAPI void APIENTRY glGetVertexArrayIntegeri_vEXT (GLuint vaobj, GLuint index, GLenum pname, GLint *param); -GLAPI void APIENTRY glGetVertexArrayPointeri_vEXT (GLuint vaobj, GLuint index, GLenum pname, void **param); -GLAPI void *APIENTRY glMapNamedBufferRangeEXT (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access); -GLAPI void APIENTRY glFlushMappedNamedBufferRangeEXT (GLuint buffer, GLintptr offset, GLsizeiptr length); -GLAPI void APIENTRY glNamedBufferStorageEXT (GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags); -GLAPI void APIENTRY glClearNamedBufferDataEXT (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data); -GLAPI void APIENTRY glClearNamedBufferSubDataEXT (GLuint buffer, GLenum internalformat, GLsizeiptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); -GLAPI void APIENTRY glNamedFramebufferParameteriEXT (GLuint framebuffer, GLenum pname, GLint param); -GLAPI void APIENTRY glGetNamedFramebufferParameterivEXT (GLuint framebuffer, GLenum pname, GLint *params); -GLAPI void APIENTRY glProgramUniform1dEXT (GLuint program, GLint location, GLdouble x); -GLAPI void APIENTRY glProgramUniform2dEXT (GLuint program, GLint location, GLdouble x, GLdouble y); -GLAPI void APIENTRY glProgramUniform3dEXT (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z); -GLAPI void APIENTRY glProgramUniform4dEXT (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); -GLAPI void APIENTRY glProgramUniform1dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value); -GLAPI void APIENTRY glProgramUniform2dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value); -GLAPI void APIENTRY glProgramUniform3dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value); -GLAPI void APIENTRY glProgramUniform4dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value); -GLAPI void APIENTRY glProgramUniformMatrix2dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glProgramUniformMatrix3dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glProgramUniformMatrix4dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glProgramUniformMatrix2x3dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glProgramUniformMatrix2x4dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glProgramUniformMatrix3x2dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glProgramUniformMatrix3x4dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glProgramUniformMatrix4x2dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glProgramUniformMatrix4x3dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); -GLAPI void APIENTRY glTextureBufferRangeEXT (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); -GLAPI void APIENTRY glTextureStorage1DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); -GLAPI void APIENTRY glTextureStorage2DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); -GLAPI void APIENTRY glTextureStorage3DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); -GLAPI void APIENTRY glTextureStorage2DMultisampleEXT (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); -GLAPI void APIENTRY glTextureStorage3DMultisampleEXT (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); -GLAPI void APIENTRY glVertexArrayBindVertexBufferEXT (GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); -GLAPI void APIENTRY glVertexArrayVertexAttribFormatEXT (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); -GLAPI void APIENTRY glVertexArrayVertexAttribIFormatEXT (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); -GLAPI void APIENTRY glVertexArrayVertexAttribLFormatEXT (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); -GLAPI void APIENTRY glVertexArrayVertexAttribBindingEXT (GLuint vaobj, GLuint attribindex, GLuint bindingindex); -GLAPI void APIENTRY glVertexArrayVertexBindingDivisorEXT (GLuint vaobj, GLuint bindingindex, GLuint divisor); -GLAPI void APIENTRY glVertexArrayVertexAttribLOffsetEXT (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); -GLAPI void APIENTRY glTexturePageCommitmentEXT (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit); -GLAPI void APIENTRY glVertexArrayVertexAttribDivisorEXT (GLuint vaobj, GLuint index, GLuint divisor); -#endif -#endif /* GL_EXT_direct_state_access */ - -#ifndef GL_EXT_draw_instanced -#define GL_EXT_draw_instanced 1 -typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDEXTPROC) (GLenum mode, GLint start, GLsizei count, GLsizei primcount); -typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glDrawArraysInstancedEXT (GLenum mode, GLint start, GLsizei count, GLsizei primcount); -GLAPI void APIENTRY glDrawElementsInstancedEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); -#endif -#endif /* GL_EXT_draw_instanced */ - -#ifndef GL_EXT_polygon_offset_clamp -#define GL_EXT_polygon_offset_clamp 1 -#define GL_POLYGON_OFFSET_CLAMP_EXT 0x8E1B -typedef void (APIENTRYP PFNGLPOLYGONOFFSETCLAMPEXTPROC) (GLfloat factor, GLfloat units, GLfloat clamp); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glPolygonOffsetClampEXT (GLfloat factor, GLfloat units, GLfloat clamp); -#endif -#endif /* GL_EXT_polygon_offset_clamp */ - -#ifndef GL_EXT_post_depth_coverage -#define GL_EXT_post_depth_coverage 1 -#endif /* GL_EXT_post_depth_coverage */ - -#ifndef GL_EXT_raster_multisample -#define GL_EXT_raster_multisample 1 -#define GL_RASTER_MULTISAMPLE_EXT 0x9327 -#define GL_RASTER_SAMPLES_EXT 0x9328 -#define GL_MAX_RASTER_SAMPLES_EXT 0x9329 -#define GL_RASTER_FIXED_SAMPLE_LOCATIONS_EXT 0x932A -#define GL_MULTISAMPLE_RASTERIZATION_ALLOWED_EXT 0x932B -#define GL_EFFECTIVE_RASTER_SAMPLES_EXT 0x932C -typedef void (APIENTRYP PFNGLRASTERSAMPLESEXTPROC) (GLuint samples, GLboolean fixedsamplelocations); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glRasterSamplesEXT (GLuint samples, GLboolean fixedsamplelocations); -#endif -#endif /* GL_EXT_raster_multisample */ - -#ifndef GL_EXT_separate_shader_objects -#define GL_EXT_separate_shader_objects 1 -#define GL_ACTIVE_PROGRAM_EXT 0x8B8D -typedef void (APIENTRYP PFNGLUSESHADERPROGRAMEXTPROC) (GLenum type, GLuint program); -typedef void (APIENTRYP PFNGLACTIVEPROGRAMEXTPROC) (GLuint program); -typedef GLuint (APIENTRYP PFNGLCREATESHADERPROGRAMEXTPROC) (GLenum type, const GLchar *string); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glUseShaderProgramEXT (GLenum type, GLuint program); -GLAPI void APIENTRY glActiveProgramEXT (GLuint program); -GLAPI GLuint APIENTRY glCreateShaderProgramEXT (GLenum type, const GLchar *string); -#endif -#endif /* GL_EXT_separate_shader_objects */ - -#ifndef GL_EXT_shader_integer_mix -#define GL_EXT_shader_integer_mix 1 -#endif /* GL_EXT_shader_integer_mix */ - -#ifndef GL_EXT_texture_compression_s3tc -#define GL_EXT_texture_compression_s3tc 1 -#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 -#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 -#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 -#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 -#endif /* GL_EXT_texture_compression_s3tc */ - -#ifndef GL_EXT_texture_filter_minmax -#define GL_EXT_texture_filter_minmax 1 -#endif /* GL_EXT_texture_filter_minmax */ - -#ifndef GL_EXT_texture_sRGB_decode -#define GL_EXT_texture_sRGB_decode 1 -#define GL_TEXTURE_SRGB_DECODE_EXT 0x8A48 -#define GL_DECODE_EXT 0x8A49 -#define GL_SKIP_DECODE_EXT 0x8A4A -#endif /* GL_EXT_texture_sRGB_decode */ - -#ifndef GL_EXT_window_rectangles -#define GL_EXT_window_rectangles 1 -#define GL_INCLUSIVE_EXT 0x8F10 -#define GL_EXCLUSIVE_EXT 0x8F11 -#define GL_WINDOW_RECTANGLE_EXT 0x8F12 -#define GL_WINDOW_RECTANGLE_MODE_EXT 0x8F13 -#define GL_MAX_WINDOW_RECTANGLES_EXT 0x8F14 -#define GL_NUM_WINDOW_RECTANGLES_EXT 0x8F15 -typedef void (APIENTRYP PFNGLWINDOWRECTANGLESEXTPROC) (GLenum mode, GLsizei count, const GLint *box); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glWindowRectanglesEXT (GLenum mode, GLsizei count, const GLint *box); -#endif -#endif /* GL_EXT_window_rectangles */ - -#ifndef GL_INTEL_conservative_rasterization -#define GL_INTEL_conservative_rasterization 1 -#define GL_CONSERVATIVE_RASTERIZATION_INTEL 0x83FE -#endif /* GL_INTEL_conservative_rasterization */ - -#ifndef GL_INTEL_framebuffer_CMAA -#define GL_INTEL_framebuffer_CMAA 1 -typedef void (APIENTRYP PFNGLAPPLYFRAMEBUFFERATTACHMENTCMAAINTELPROC) (void); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glApplyFramebufferAttachmentCMAAINTEL (void); -#endif -#endif /* GL_INTEL_framebuffer_CMAA */ - -#ifndef GL_INTEL_performance_query -#define GL_INTEL_performance_query 1 -#define GL_PERFQUERY_SINGLE_CONTEXT_INTEL 0x00000000 -#define GL_PERFQUERY_GLOBAL_CONTEXT_INTEL 0x00000001 -#define GL_PERFQUERY_WAIT_INTEL 0x83FB -#define GL_PERFQUERY_FLUSH_INTEL 0x83FA -#define GL_PERFQUERY_DONOT_FLUSH_INTEL 0x83F9 -#define GL_PERFQUERY_COUNTER_EVENT_INTEL 0x94F0 -#define GL_PERFQUERY_COUNTER_DURATION_NORM_INTEL 0x94F1 -#define GL_PERFQUERY_COUNTER_DURATION_RAW_INTEL 0x94F2 -#define GL_PERFQUERY_COUNTER_THROUGHPUT_INTEL 0x94F3 -#define GL_PERFQUERY_COUNTER_RAW_INTEL 0x94F4 -#define GL_PERFQUERY_COUNTER_TIMESTAMP_INTEL 0x94F5 -#define GL_PERFQUERY_COUNTER_DATA_UINT32_INTEL 0x94F8 -#define GL_PERFQUERY_COUNTER_DATA_UINT64_INTEL 0x94F9 -#define GL_PERFQUERY_COUNTER_DATA_FLOAT_INTEL 0x94FA -#define GL_PERFQUERY_COUNTER_DATA_DOUBLE_INTEL 0x94FB -#define GL_PERFQUERY_COUNTER_DATA_BOOL32_INTEL 0x94FC -#define GL_PERFQUERY_QUERY_NAME_LENGTH_MAX_INTEL 0x94FD -#define GL_PERFQUERY_COUNTER_NAME_LENGTH_MAX_INTEL 0x94FE -#define GL_PERFQUERY_COUNTER_DESC_LENGTH_MAX_INTEL 0x94FF -#define GL_PERFQUERY_GPA_EXTENDED_COUNTERS_INTEL 0x9500 -typedef void (APIENTRYP PFNGLBEGINPERFQUERYINTELPROC) (GLuint queryHandle); -typedef void (APIENTRYP PFNGLCREATEPERFQUERYINTELPROC) (GLuint queryId, GLuint *queryHandle); -typedef void (APIENTRYP PFNGLDELETEPERFQUERYINTELPROC) (GLuint queryHandle); -typedef void (APIENTRYP PFNGLENDPERFQUERYINTELPROC) (GLuint queryHandle); -typedef void (APIENTRYP PFNGLGETFIRSTPERFQUERYIDINTELPROC) (GLuint *queryId); -typedef void (APIENTRYP PFNGLGETNEXTPERFQUERYIDINTELPROC) (GLuint queryId, GLuint *nextQueryId); -typedef void (APIENTRYP PFNGLGETPERFCOUNTERINFOINTELPROC) (GLuint queryId, GLuint counterId, GLuint counterNameLength, GLchar *counterName, GLuint counterDescLength, GLchar *counterDesc, GLuint *counterOffset, GLuint *counterDataSize, GLuint *counterTypeEnum, GLuint *counterDataTypeEnum, GLuint64 *rawCounterMaxValue); -typedef void (APIENTRYP PFNGLGETPERFQUERYDATAINTELPROC) (GLuint queryHandle, GLuint flags, GLsizei dataSize, GLvoid *data, GLuint *bytesWritten); -typedef void (APIENTRYP PFNGLGETPERFQUERYIDBYNAMEINTELPROC) (GLchar *queryName, GLuint *queryId); -typedef void (APIENTRYP PFNGLGETPERFQUERYINFOINTELPROC) (GLuint queryId, GLuint queryNameLength, GLchar *queryName, GLuint *dataSize, GLuint *noCounters, GLuint *noInstances, GLuint *capsMask); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glBeginPerfQueryINTEL (GLuint queryHandle); -GLAPI void APIENTRY glCreatePerfQueryINTEL (GLuint queryId, GLuint *queryHandle); -GLAPI void APIENTRY glDeletePerfQueryINTEL (GLuint queryHandle); -GLAPI void APIENTRY glEndPerfQueryINTEL (GLuint queryHandle); -GLAPI void APIENTRY glGetFirstPerfQueryIdINTEL (GLuint *queryId); -GLAPI void APIENTRY glGetNextPerfQueryIdINTEL (GLuint queryId, GLuint *nextQueryId); -GLAPI void APIENTRY glGetPerfCounterInfoINTEL (GLuint queryId, GLuint counterId, GLuint counterNameLength, GLchar *counterName, GLuint counterDescLength, GLchar *counterDesc, GLuint *counterOffset, GLuint *counterDataSize, GLuint *counterTypeEnum, GLuint *counterDataTypeEnum, GLuint64 *rawCounterMaxValue); -GLAPI void APIENTRY glGetPerfQueryDataINTEL (GLuint queryHandle, GLuint flags, GLsizei dataSize, GLvoid *data, GLuint *bytesWritten); -GLAPI void APIENTRY glGetPerfQueryIdByNameINTEL (GLchar *queryName, GLuint *queryId); -GLAPI void APIENTRY glGetPerfQueryInfoINTEL (GLuint queryId, GLuint queryNameLength, GLchar *queryName, GLuint *dataSize, GLuint *noCounters, GLuint *noInstances, GLuint *capsMask); -#endif -#endif /* GL_INTEL_performance_query */ - -#ifndef GL_NV_bindless_multi_draw_indirect -#define GL_NV_bindless_multi_draw_indirect 1 -typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTBINDLESSNVPROC) (GLenum mode, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount); -typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTBINDLESSNVPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glMultiDrawArraysIndirectBindlessNV (GLenum mode, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount); -GLAPI void APIENTRY glMultiDrawElementsIndirectBindlessNV (GLenum mode, GLenum type, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount); -#endif -#endif /* GL_NV_bindless_multi_draw_indirect */ - -#ifndef GL_NV_bindless_multi_draw_indirect_count -#define GL_NV_bindless_multi_draw_indirect_count 1 -typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTBINDLESSCOUNTNVPROC) (GLenum mode, const void *indirect, GLsizei drawCount, GLsizei maxDrawCount, GLsizei stride, GLint vertexBufferCount); -typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTBINDLESSCOUNTNVPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei drawCount, GLsizei maxDrawCount, GLsizei stride, GLint vertexBufferCount); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glMultiDrawArraysIndirectBindlessCountNV (GLenum mode, const void *indirect, GLsizei drawCount, GLsizei maxDrawCount, GLsizei stride, GLint vertexBufferCount); -GLAPI void APIENTRY glMultiDrawElementsIndirectBindlessCountNV (GLenum mode, GLenum type, const void *indirect, GLsizei drawCount, GLsizei maxDrawCount, GLsizei stride, GLint vertexBufferCount); -#endif -#endif /* GL_NV_bindless_multi_draw_indirect_count */ - -#ifndef GL_NV_bindless_texture -#define GL_NV_bindless_texture 1 -typedef GLuint64 (APIENTRYP PFNGLGETTEXTUREHANDLENVPROC) (GLuint texture); -typedef GLuint64 (APIENTRYP PFNGLGETTEXTURESAMPLERHANDLENVPROC) (GLuint texture, GLuint sampler); -typedef void (APIENTRYP PFNGLMAKETEXTUREHANDLERESIDENTNVPROC) (GLuint64 handle); -typedef void (APIENTRYP PFNGLMAKETEXTUREHANDLENONRESIDENTNVPROC) (GLuint64 handle); -typedef GLuint64 (APIENTRYP PFNGLGETIMAGEHANDLENVPROC) (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); -typedef void (APIENTRYP PFNGLMAKEIMAGEHANDLERESIDENTNVPROC) (GLuint64 handle, GLenum access); -typedef void (APIENTRYP PFNGLMAKEIMAGEHANDLENONRESIDENTNVPROC) (GLuint64 handle); -typedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64NVPROC) (GLint location, GLuint64 value); -typedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64VNVPROC) (GLint location, GLsizei count, const GLuint64 *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64NVPROC) (GLuint program, GLint location, GLuint64 value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *values); -typedef GLboolean (APIENTRYP PFNGLISTEXTUREHANDLERESIDENTNVPROC) (GLuint64 handle); -typedef GLboolean (APIENTRYP PFNGLISIMAGEHANDLERESIDENTNVPROC) (GLuint64 handle); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI GLuint64 APIENTRY glGetTextureHandleNV (GLuint texture); -GLAPI GLuint64 APIENTRY glGetTextureSamplerHandleNV (GLuint texture, GLuint sampler); -GLAPI void APIENTRY glMakeTextureHandleResidentNV (GLuint64 handle); -GLAPI void APIENTRY glMakeTextureHandleNonResidentNV (GLuint64 handle); -GLAPI GLuint64 APIENTRY glGetImageHandleNV (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); -GLAPI void APIENTRY glMakeImageHandleResidentNV (GLuint64 handle, GLenum access); -GLAPI void APIENTRY glMakeImageHandleNonResidentNV (GLuint64 handle); -GLAPI void APIENTRY glUniformHandleui64NV (GLint location, GLuint64 value); -GLAPI void APIENTRY glUniformHandleui64vNV (GLint location, GLsizei count, const GLuint64 *value); -GLAPI void APIENTRY glProgramUniformHandleui64NV (GLuint program, GLint location, GLuint64 value); -GLAPI void APIENTRY glProgramUniformHandleui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64 *values); -GLAPI GLboolean APIENTRY glIsTextureHandleResidentNV (GLuint64 handle); -GLAPI GLboolean APIENTRY glIsImageHandleResidentNV (GLuint64 handle); -#endif -#endif /* GL_NV_bindless_texture */ - -#ifndef GL_NV_blend_equation_advanced -#define GL_NV_blend_equation_advanced 1 -#define GL_BLEND_OVERLAP_NV 0x9281 -#define GL_BLEND_PREMULTIPLIED_SRC_NV 0x9280 -#define GL_BLUE_NV 0x1905 -#define GL_COLORBURN_NV 0x929A -#define GL_COLORDODGE_NV 0x9299 -#define GL_CONJOINT_NV 0x9284 -#define GL_CONTRAST_NV 0x92A1 -#define GL_DARKEN_NV 0x9297 -#define GL_DIFFERENCE_NV 0x929E -#define GL_DISJOINT_NV 0x9283 -#define GL_DST_ATOP_NV 0x928F -#define GL_DST_IN_NV 0x928B -#define GL_DST_NV 0x9287 -#define GL_DST_OUT_NV 0x928D -#define GL_DST_OVER_NV 0x9289 -#define GL_EXCLUSION_NV 0x92A0 -#define GL_GREEN_NV 0x1904 -#define GL_HARDLIGHT_NV 0x929B -#define GL_HARDMIX_NV 0x92A9 -#define GL_HSL_COLOR_NV 0x92AF -#define GL_HSL_HUE_NV 0x92AD -#define GL_HSL_LUMINOSITY_NV 0x92B0 -#define GL_HSL_SATURATION_NV 0x92AE -#define GL_INVERT_OVG_NV 0x92B4 -#define GL_INVERT_RGB_NV 0x92A3 -#define GL_LIGHTEN_NV 0x9298 -#define GL_LINEARBURN_NV 0x92A5 -#define GL_LINEARDODGE_NV 0x92A4 -#define GL_LINEARLIGHT_NV 0x92A7 -#define GL_MINUS_CLAMPED_NV 0x92B3 -#define GL_MINUS_NV 0x929F -#define GL_MULTIPLY_NV 0x9294 -#define GL_OVERLAY_NV 0x9296 -#define GL_PINLIGHT_NV 0x92A8 -#define GL_PLUS_CLAMPED_ALPHA_NV 0x92B2 -#define GL_PLUS_CLAMPED_NV 0x92B1 -#define GL_PLUS_DARKER_NV 0x9292 -#define GL_PLUS_NV 0x9291 -#define GL_RED_NV 0x1903 -#define GL_SCREEN_NV 0x9295 -#define GL_SOFTLIGHT_NV 0x929C -#define GL_SRC_ATOP_NV 0x928E -#define GL_SRC_IN_NV 0x928A -#define GL_SRC_NV 0x9286 -#define GL_SRC_OUT_NV 0x928C -#define GL_SRC_OVER_NV 0x9288 -#define GL_UNCORRELATED_NV 0x9282 -#define GL_VIVIDLIGHT_NV 0x92A6 -#define GL_XOR_NV 0x1506 -typedef void (APIENTRYP PFNGLBLENDPARAMETERINVPROC) (GLenum pname, GLint value); -typedef void (APIENTRYP PFNGLBLENDBARRIERNVPROC) (void); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glBlendParameteriNV (GLenum pname, GLint value); -GLAPI void APIENTRY glBlendBarrierNV (void); -#endif -#endif /* GL_NV_blend_equation_advanced */ - -#ifndef GL_NV_blend_equation_advanced_coherent -#define GL_NV_blend_equation_advanced_coherent 1 -#define GL_BLEND_ADVANCED_COHERENT_NV 0x9285 -#endif /* GL_NV_blend_equation_advanced_coherent */ - -#ifndef GL_NV_blend_minmax_factor -#define GL_NV_blend_minmax_factor 1 -#define GL_FACTOR_MIN_AMD 0x901C -#define GL_FACTOR_MAX_AMD 0x901D -#endif /* GL_NV_blend_minmax_factor */ - -#ifndef GL_NV_clip_space_w_scaling -#define GL_NV_clip_space_w_scaling 1 -#define GL_VIEWPORT_POSITION_W_SCALE_NV 0x937C -#define GL_VIEWPORT_POSITION_W_SCALE_X_COEFF_NV 0x937D -#define GL_VIEWPORT_POSITION_W_SCALE_Y_COEFF_NV 0x937E -typedef void (APIENTRYP PFNGLVIEWPORTPOSITIONWSCALENVPROC) (GLuint index, GLfloat xcoeff, GLfloat ycoeff); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glViewportPositionWScaleNV (GLuint index, GLfloat xcoeff, GLfloat ycoeff); -#endif -#endif /* GL_NV_clip_space_w_scaling */ - -#ifndef GL_NV_command_list -#define GL_NV_command_list 1 -#define GL_TERMINATE_SEQUENCE_COMMAND_NV 0x0000 -#define GL_NOP_COMMAND_NV 0x0001 -#define GL_DRAW_ELEMENTS_COMMAND_NV 0x0002 -#define GL_DRAW_ARRAYS_COMMAND_NV 0x0003 -#define GL_DRAW_ELEMENTS_STRIP_COMMAND_NV 0x0004 -#define GL_DRAW_ARRAYS_STRIP_COMMAND_NV 0x0005 -#define GL_DRAW_ELEMENTS_INSTANCED_COMMAND_NV 0x0006 -#define GL_DRAW_ARRAYS_INSTANCED_COMMAND_NV 0x0007 -#define GL_ELEMENT_ADDRESS_COMMAND_NV 0x0008 -#define GL_ATTRIBUTE_ADDRESS_COMMAND_NV 0x0009 -#define GL_UNIFORM_ADDRESS_COMMAND_NV 0x000A -#define GL_BLEND_COLOR_COMMAND_NV 0x000B -#define GL_STENCIL_REF_COMMAND_NV 0x000C -#define GL_LINE_WIDTH_COMMAND_NV 0x000D -#define GL_POLYGON_OFFSET_COMMAND_NV 0x000E -#define GL_ALPHA_REF_COMMAND_NV 0x000F -#define GL_VIEWPORT_COMMAND_NV 0x0010 -#define GL_SCISSOR_COMMAND_NV 0x0011 -#define GL_FRONT_FACE_COMMAND_NV 0x0012 -typedef void (APIENTRYP PFNGLCREATESTATESNVPROC) (GLsizei n, GLuint *states); -typedef void (APIENTRYP PFNGLDELETESTATESNVPROC) (GLsizei n, const GLuint *states); -typedef GLboolean (APIENTRYP PFNGLISSTATENVPROC) (GLuint state); -typedef void (APIENTRYP PFNGLSTATECAPTURENVPROC) (GLuint state, GLenum mode); -typedef GLuint (APIENTRYP PFNGLGETCOMMANDHEADERNVPROC) (GLenum tokenID, GLuint size); -typedef GLushort (APIENTRYP PFNGLGETSTAGEINDEXNVPROC) (GLenum shadertype); -typedef void (APIENTRYP PFNGLDRAWCOMMANDSNVPROC) (GLenum primitiveMode, GLuint buffer, const GLintptr *indirects, const GLsizei *sizes, GLuint count); -typedef void (APIENTRYP PFNGLDRAWCOMMANDSADDRESSNVPROC) (GLenum primitiveMode, const GLuint64 *indirects, const GLsizei *sizes, GLuint count); -typedef void (APIENTRYP PFNGLDRAWCOMMANDSSTATESNVPROC) (GLuint buffer, const GLintptr *indirects, const GLsizei *sizes, const GLuint *states, const GLuint *fbos, GLuint count); -typedef void (APIENTRYP PFNGLDRAWCOMMANDSSTATESADDRESSNVPROC) (const GLuint64 *indirects, const GLsizei *sizes, const GLuint *states, const GLuint *fbos, GLuint count); -typedef void (APIENTRYP PFNGLCREATECOMMANDLISTSNVPROC) (GLsizei n, GLuint *lists); -typedef void (APIENTRYP PFNGLDELETECOMMANDLISTSNVPROC) (GLsizei n, const GLuint *lists); -typedef GLboolean (APIENTRYP PFNGLISCOMMANDLISTNVPROC) (GLuint list); -typedef void (APIENTRYP PFNGLLISTDRAWCOMMANDSSTATESCLIENTNVPROC) (GLuint list, GLuint segment, const void **indirects, const GLsizei *sizes, const GLuint *states, const GLuint *fbos, GLuint count); -typedef void (APIENTRYP PFNGLCOMMANDLISTSEGMENTSNVPROC) (GLuint list, GLuint segments); -typedef void (APIENTRYP PFNGLCOMPILECOMMANDLISTNVPROC) (GLuint list); -typedef void (APIENTRYP PFNGLCALLCOMMANDLISTNVPROC) (GLuint list); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glCreateStatesNV (GLsizei n, GLuint *states); -GLAPI void APIENTRY glDeleteStatesNV (GLsizei n, const GLuint *states); -GLAPI GLboolean APIENTRY glIsStateNV (GLuint state); -GLAPI void APIENTRY glStateCaptureNV (GLuint state, GLenum mode); -GLAPI GLuint APIENTRY glGetCommandHeaderNV (GLenum tokenID, GLuint size); -GLAPI GLushort APIENTRY glGetStageIndexNV (GLenum shadertype); -GLAPI void APIENTRY glDrawCommandsNV (GLenum primitiveMode, GLuint buffer, const GLintptr *indirects, const GLsizei *sizes, GLuint count); -GLAPI void APIENTRY glDrawCommandsAddressNV (GLenum primitiveMode, const GLuint64 *indirects, const GLsizei *sizes, GLuint count); -GLAPI void APIENTRY glDrawCommandsStatesNV (GLuint buffer, const GLintptr *indirects, const GLsizei *sizes, const GLuint *states, const GLuint *fbos, GLuint count); -GLAPI void APIENTRY glDrawCommandsStatesAddressNV (const GLuint64 *indirects, const GLsizei *sizes, const GLuint *states, const GLuint *fbos, GLuint count); -GLAPI void APIENTRY glCreateCommandListsNV (GLsizei n, GLuint *lists); -GLAPI void APIENTRY glDeleteCommandListsNV (GLsizei n, const GLuint *lists); -GLAPI GLboolean APIENTRY glIsCommandListNV (GLuint list); -GLAPI void APIENTRY glListDrawCommandsStatesClientNV (GLuint list, GLuint segment, const void **indirects, const GLsizei *sizes, const GLuint *states, const GLuint *fbos, GLuint count); -GLAPI void APIENTRY glCommandListSegmentsNV (GLuint list, GLuint segments); -GLAPI void APIENTRY glCompileCommandListNV (GLuint list); -GLAPI void APIENTRY glCallCommandListNV (GLuint list); -#endif -#endif /* GL_NV_command_list */ - -#ifndef GL_NV_conditional_render -#define GL_NV_conditional_render 1 -#define GL_QUERY_WAIT_NV 0x8E13 -#define GL_QUERY_NO_WAIT_NV 0x8E14 -#define GL_QUERY_BY_REGION_WAIT_NV 0x8E15 -#define GL_QUERY_BY_REGION_NO_WAIT_NV 0x8E16 -typedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERNVPROC) (GLuint id, GLenum mode); -typedef void (APIENTRYP PFNGLENDCONDITIONALRENDERNVPROC) (void); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glBeginConditionalRenderNV (GLuint id, GLenum mode); -GLAPI void APIENTRY glEndConditionalRenderNV (void); -#endif -#endif /* GL_NV_conditional_render */ - -#ifndef GL_NV_conservative_raster -#define GL_NV_conservative_raster 1 -#define GL_CONSERVATIVE_RASTERIZATION_NV 0x9346 -#define GL_SUBPIXEL_PRECISION_BIAS_X_BITS_NV 0x9347 -#define GL_SUBPIXEL_PRECISION_BIAS_Y_BITS_NV 0x9348 -#define GL_MAX_SUBPIXEL_PRECISION_BIAS_BITS_NV 0x9349 -typedef void (APIENTRYP PFNGLSUBPIXELPRECISIONBIASNVPROC) (GLuint xbits, GLuint ybits); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glSubpixelPrecisionBiasNV (GLuint xbits, GLuint ybits); -#endif -#endif /* GL_NV_conservative_raster */ - -#ifndef GL_NV_conservative_raster_dilate -#define GL_NV_conservative_raster_dilate 1 -#define GL_CONSERVATIVE_RASTER_DILATE_NV 0x9379 -#define GL_CONSERVATIVE_RASTER_DILATE_RANGE_NV 0x937A -#define GL_CONSERVATIVE_RASTER_DILATE_GRANULARITY_NV 0x937B -typedef void (APIENTRYP PFNGLCONSERVATIVERASTERPARAMETERFNVPROC) (GLenum pname, GLfloat value); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glConservativeRasterParameterfNV (GLenum pname, GLfloat value); -#endif -#endif /* GL_NV_conservative_raster_dilate */ - -#ifndef GL_NV_conservative_raster_pre_snap_triangles -#define GL_NV_conservative_raster_pre_snap_triangles 1 -#define GL_CONSERVATIVE_RASTER_MODE_NV 0x954D -#define GL_CONSERVATIVE_RASTER_MODE_POST_SNAP_NV 0x954E -#define GL_CONSERVATIVE_RASTER_MODE_PRE_SNAP_TRIANGLES_NV 0x954F -typedef void (APIENTRYP PFNGLCONSERVATIVERASTERPARAMETERINVPROC) (GLenum pname, GLint param); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glConservativeRasterParameteriNV (GLenum pname, GLint param); -#endif -#endif /* GL_NV_conservative_raster_pre_snap_triangles */ - -#ifndef GL_NV_draw_vulkan_image -#define GL_NV_draw_vulkan_image 1 -typedef void (APIENTRY *GLVULKANPROCNV)(void); -typedef void (APIENTRYP PFNGLDRAWVKIMAGENVPROC) (GLuint64 vkImage, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1); -typedef GLVULKANPROCNV (APIENTRYP PFNGLGETVKPROCADDRNVPROC) (const GLchar *name); -typedef void (APIENTRYP PFNGLWAITVKSEMAPHORENVPROC) (GLuint64 vkSemaphore); -typedef void (APIENTRYP PFNGLSIGNALVKSEMAPHORENVPROC) (GLuint64 vkSemaphore); -typedef void (APIENTRYP PFNGLSIGNALVKFENCENVPROC) (GLuint64 vkFence); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glDrawVkImageNV (GLuint64 vkImage, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1); -GLAPI GLVULKANPROCNV APIENTRY glGetVkProcAddrNV (const GLchar *name); -GLAPI void APIENTRY glWaitVkSemaphoreNV (GLuint64 vkSemaphore); -GLAPI void APIENTRY glSignalVkSemaphoreNV (GLuint64 vkSemaphore); -GLAPI void APIENTRY glSignalVkFenceNV (GLuint64 vkFence); -#endif -#endif /* GL_NV_draw_vulkan_image */ - -#ifndef GL_NV_fill_rectangle -#define GL_NV_fill_rectangle 1 -#define GL_FILL_RECTANGLE_NV 0x933C -#endif /* GL_NV_fill_rectangle */ - -#ifndef GL_NV_fragment_coverage_to_color -#define GL_NV_fragment_coverage_to_color 1 -#define GL_FRAGMENT_COVERAGE_TO_COLOR_NV 0x92DD -#define GL_FRAGMENT_COVERAGE_COLOR_NV 0x92DE -typedef void (APIENTRYP PFNGLFRAGMENTCOVERAGECOLORNVPROC) (GLuint color); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glFragmentCoverageColorNV (GLuint color); -#endif -#endif /* GL_NV_fragment_coverage_to_color */ - -#ifndef GL_NV_fragment_shader_interlock -#define GL_NV_fragment_shader_interlock 1 -#endif /* GL_NV_fragment_shader_interlock */ - -#ifndef GL_NV_framebuffer_mixed_samples -#define GL_NV_framebuffer_mixed_samples 1 -#define GL_COVERAGE_MODULATION_TABLE_NV 0x9331 -#define GL_COLOR_SAMPLES_NV 0x8E20 -#define GL_DEPTH_SAMPLES_NV 0x932D -#define GL_STENCIL_SAMPLES_NV 0x932E -#define GL_MIXED_DEPTH_SAMPLES_SUPPORTED_NV 0x932F -#define GL_MIXED_STENCIL_SAMPLES_SUPPORTED_NV 0x9330 -#define GL_COVERAGE_MODULATION_NV 0x9332 -#define GL_COVERAGE_MODULATION_TABLE_SIZE_NV 0x9333 -typedef void (APIENTRYP PFNGLCOVERAGEMODULATIONTABLENVPROC) (GLsizei n, const GLfloat *v); -typedef void (APIENTRYP PFNGLGETCOVERAGEMODULATIONTABLENVPROC) (GLsizei bufsize, GLfloat *v); -typedef void (APIENTRYP PFNGLCOVERAGEMODULATIONNVPROC) (GLenum components); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glCoverageModulationTableNV (GLsizei n, const GLfloat *v); -GLAPI void APIENTRY glGetCoverageModulationTableNV (GLsizei bufsize, GLfloat *v); -GLAPI void APIENTRY glCoverageModulationNV (GLenum components); -#endif -#endif /* GL_NV_framebuffer_mixed_samples */ - -#ifndef GL_NV_framebuffer_multisample_coverage -#define GL_NV_framebuffer_multisample_coverage 1 -#define GL_RENDERBUFFER_COVERAGE_SAMPLES_NV 0x8CAB -#define GL_RENDERBUFFER_COLOR_SAMPLES_NV 0x8E10 -#define GL_MAX_MULTISAMPLE_COVERAGE_MODES_NV 0x8E11 -#define GL_MULTISAMPLE_COVERAGE_MODES_NV 0x8E12 -typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLECOVERAGENVPROC) (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glRenderbufferStorageMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); -#endif -#endif /* GL_NV_framebuffer_multisample_coverage */ - -#ifndef GL_NV_geometry_shader_passthrough -#define GL_NV_geometry_shader_passthrough 1 -#endif /* GL_NV_geometry_shader_passthrough */ - -#ifndef GL_NV_gpu_shader5 -#define GL_NV_gpu_shader5 1 -typedef int64_t GLint64EXT; -#define GL_INT64_NV 0x140E -#define GL_UNSIGNED_INT64_NV 0x140F -#define GL_INT8_NV 0x8FE0 -#define GL_INT8_VEC2_NV 0x8FE1 -#define GL_INT8_VEC3_NV 0x8FE2 -#define GL_INT8_VEC4_NV 0x8FE3 -#define GL_INT16_NV 0x8FE4 -#define GL_INT16_VEC2_NV 0x8FE5 -#define GL_INT16_VEC3_NV 0x8FE6 -#define GL_INT16_VEC4_NV 0x8FE7 -#define GL_INT64_VEC2_NV 0x8FE9 -#define GL_INT64_VEC3_NV 0x8FEA -#define GL_INT64_VEC4_NV 0x8FEB -#define GL_UNSIGNED_INT8_NV 0x8FEC -#define GL_UNSIGNED_INT8_VEC2_NV 0x8FED -#define GL_UNSIGNED_INT8_VEC3_NV 0x8FEE -#define GL_UNSIGNED_INT8_VEC4_NV 0x8FEF -#define GL_UNSIGNED_INT16_NV 0x8FF0 -#define GL_UNSIGNED_INT16_VEC2_NV 0x8FF1 -#define GL_UNSIGNED_INT16_VEC3_NV 0x8FF2 -#define GL_UNSIGNED_INT16_VEC4_NV 0x8FF3 -#define GL_UNSIGNED_INT64_VEC2_NV 0x8FF5 -#define GL_UNSIGNED_INT64_VEC3_NV 0x8FF6 -#define GL_UNSIGNED_INT64_VEC4_NV 0x8FF7 -#define GL_FLOAT16_NV 0x8FF8 -#define GL_FLOAT16_VEC2_NV 0x8FF9 -#define GL_FLOAT16_VEC3_NV 0x8FFA -#define GL_FLOAT16_VEC4_NV 0x8FFB -typedef void (APIENTRYP PFNGLUNIFORM1I64NVPROC) (GLint location, GLint64EXT x); -typedef void (APIENTRYP PFNGLUNIFORM2I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y); -typedef void (APIENTRYP PFNGLUNIFORM3I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); -typedef void (APIENTRYP PFNGLUNIFORM4I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); -typedef void (APIENTRYP PFNGLUNIFORM1I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); -typedef void (APIENTRYP PFNGLUNIFORM2I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); -typedef void (APIENTRYP PFNGLUNIFORM3I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); -typedef void (APIENTRYP PFNGLUNIFORM4I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); -typedef void (APIENTRYP PFNGLUNIFORM1UI64NVPROC) (GLint location, GLuint64EXT x); -typedef void (APIENTRYP PFNGLUNIFORM2UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y); -typedef void (APIENTRYP PFNGLUNIFORM3UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); -typedef void (APIENTRYP PFNGLUNIFORM4UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); -typedef void (APIENTRYP PFNGLUNIFORM1UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); -typedef void (APIENTRYP PFNGLUNIFORM2UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); -typedef void (APIENTRYP PFNGLUNIFORM3UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); -typedef void (APIENTRYP PFNGLUNIFORM4UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); -typedef void (APIENTRYP PFNGLGETUNIFORMI64VNVPROC) (GLuint program, GLint location, GLint64EXT *params); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1I64NVPROC) (GLuint program, GLint location, GLint64EXT x); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glUniform1i64NV (GLint location, GLint64EXT x); -GLAPI void APIENTRY glUniform2i64NV (GLint location, GLint64EXT x, GLint64EXT y); -GLAPI void APIENTRY glUniform3i64NV (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); -GLAPI void APIENTRY glUniform4i64NV (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); -GLAPI void APIENTRY glUniform1i64vNV (GLint location, GLsizei count, const GLint64EXT *value); -GLAPI void APIENTRY glUniform2i64vNV (GLint location, GLsizei count, const GLint64EXT *value); -GLAPI void APIENTRY glUniform3i64vNV (GLint location, GLsizei count, const GLint64EXT *value); -GLAPI void APIENTRY glUniform4i64vNV (GLint location, GLsizei count, const GLint64EXT *value); -GLAPI void APIENTRY glUniform1ui64NV (GLint location, GLuint64EXT x); -GLAPI void APIENTRY glUniform2ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y); -GLAPI void APIENTRY glUniform3ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); -GLAPI void APIENTRY glUniform4ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); -GLAPI void APIENTRY glUniform1ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); -GLAPI void APIENTRY glUniform2ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); -GLAPI void APIENTRY glUniform3ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); -GLAPI void APIENTRY glUniform4ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); -GLAPI void APIENTRY glGetUniformi64vNV (GLuint program, GLint location, GLint64EXT *params); -GLAPI void APIENTRY glProgramUniform1i64NV (GLuint program, GLint location, GLint64EXT x); -GLAPI void APIENTRY glProgramUniform2i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y); -GLAPI void APIENTRY glProgramUniform3i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); -GLAPI void APIENTRY glProgramUniform4i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); -GLAPI void APIENTRY glProgramUniform1i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); -GLAPI void APIENTRY glProgramUniform2i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); -GLAPI void APIENTRY glProgramUniform3i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); -GLAPI void APIENTRY glProgramUniform4i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); -GLAPI void APIENTRY glProgramUniform1ui64NV (GLuint program, GLint location, GLuint64EXT x); -GLAPI void APIENTRY glProgramUniform2ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y); -GLAPI void APIENTRY glProgramUniform3ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); -GLAPI void APIENTRY glProgramUniform4ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); -GLAPI void APIENTRY glProgramUniform1ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); -GLAPI void APIENTRY glProgramUniform2ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); -GLAPI void APIENTRY glProgramUniform3ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); -GLAPI void APIENTRY glProgramUniform4ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); -#endif -#endif /* GL_NV_gpu_shader5 */ - -#ifndef GL_NV_internalformat_sample_query -#define GL_NV_internalformat_sample_query 1 -#define GL_MULTISAMPLES_NV 0x9371 -#define GL_SUPERSAMPLE_SCALE_X_NV 0x9372 -#define GL_SUPERSAMPLE_SCALE_Y_NV 0x9373 -#define GL_CONFORMANT_NV 0x9374 -typedef void (APIENTRYP PFNGLGETINTERNALFORMATSAMPLEIVNVPROC) (GLenum target, GLenum internalformat, GLsizei samples, GLenum pname, GLsizei bufSize, GLint *params); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glGetInternalformatSampleivNV (GLenum target, GLenum internalformat, GLsizei samples, GLenum pname, GLsizei bufSize, GLint *params); -#endif -#endif /* GL_NV_internalformat_sample_query */ - -#ifndef GL_NV_path_rendering -#define GL_NV_path_rendering 1 -#define GL_PATH_FORMAT_SVG_NV 0x9070 -#define GL_PATH_FORMAT_PS_NV 0x9071 -#define GL_STANDARD_FONT_NAME_NV 0x9072 -#define GL_SYSTEM_FONT_NAME_NV 0x9073 -#define GL_FILE_NAME_NV 0x9074 -#define GL_PATH_STROKE_WIDTH_NV 0x9075 -#define GL_PATH_END_CAPS_NV 0x9076 -#define GL_PATH_INITIAL_END_CAP_NV 0x9077 -#define GL_PATH_TERMINAL_END_CAP_NV 0x9078 -#define GL_PATH_JOIN_STYLE_NV 0x9079 -#define GL_PATH_MITER_LIMIT_NV 0x907A -#define GL_PATH_DASH_CAPS_NV 0x907B -#define GL_PATH_INITIAL_DASH_CAP_NV 0x907C -#define GL_PATH_TERMINAL_DASH_CAP_NV 0x907D -#define GL_PATH_DASH_OFFSET_NV 0x907E -#define GL_PATH_CLIENT_LENGTH_NV 0x907F -#define GL_PATH_FILL_MODE_NV 0x9080 -#define GL_PATH_FILL_MASK_NV 0x9081 -#define GL_PATH_FILL_COVER_MODE_NV 0x9082 -#define GL_PATH_STROKE_COVER_MODE_NV 0x9083 -#define GL_PATH_STROKE_MASK_NV 0x9084 -#define GL_COUNT_UP_NV 0x9088 -#define GL_COUNT_DOWN_NV 0x9089 -#define GL_PATH_OBJECT_BOUNDING_BOX_NV 0x908A -#define GL_CONVEX_HULL_NV 0x908B -#define GL_BOUNDING_BOX_NV 0x908D -#define GL_TRANSLATE_X_NV 0x908E -#define GL_TRANSLATE_Y_NV 0x908F -#define GL_TRANSLATE_2D_NV 0x9090 -#define GL_TRANSLATE_3D_NV 0x9091 -#define GL_AFFINE_2D_NV 0x9092 -#define GL_AFFINE_3D_NV 0x9094 -#define GL_TRANSPOSE_AFFINE_2D_NV 0x9096 -#define GL_TRANSPOSE_AFFINE_3D_NV 0x9098 -#define GL_UTF8_NV 0x909A -#define GL_UTF16_NV 0x909B -#define GL_BOUNDING_BOX_OF_BOUNDING_BOXES_NV 0x909C -#define GL_PATH_COMMAND_COUNT_NV 0x909D -#define GL_PATH_COORD_COUNT_NV 0x909E -#define GL_PATH_DASH_ARRAY_COUNT_NV 0x909F -#define GL_PATH_COMPUTED_LENGTH_NV 0x90A0 -#define GL_PATH_FILL_BOUNDING_BOX_NV 0x90A1 -#define GL_PATH_STROKE_BOUNDING_BOX_NV 0x90A2 -#define GL_SQUARE_NV 0x90A3 -#define GL_ROUND_NV 0x90A4 -#define GL_TRIANGULAR_NV 0x90A5 -#define GL_BEVEL_NV 0x90A6 -#define GL_MITER_REVERT_NV 0x90A7 -#define GL_MITER_TRUNCATE_NV 0x90A8 -#define GL_SKIP_MISSING_GLYPH_NV 0x90A9 -#define GL_USE_MISSING_GLYPH_NV 0x90AA -#define GL_PATH_ERROR_POSITION_NV 0x90AB -#define GL_ACCUM_ADJACENT_PAIRS_NV 0x90AD -#define GL_ADJACENT_PAIRS_NV 0x90AE -#define GL_FIRST_TO_REST_NV 0x90AF -#define GL_PATH_GEN_MODE_NV 0x90B0 -#define GL_PATH_GEN_COEFF_NV 0x90B1 -#define GL_PATH_GEN_COMPONENTS_NV 0x90B3 -#define GL_PATH_STENCIL_FUNC_NV 0x90B7 -#define GL_PATH_STENCIL_REF_NV 0x90B8 -#define GL_PATH_STENCIL_VALUE_MASK_NV 0x90B9 -#define GL_PATH_STENCIL_DEPTH_OFFSET_FACTOR_NV 0x90BD -#define GL_PATH_STENCIL_DEPTH_OFFSET_UNITS_NV 0x90BE -#define GL_PATH_COVER_DEPTH_FUNC_NV 0x90BF -#define GL_PATH_DASH_OFFSET_RESET_NV 0x90B4 -#define GL_MOVE_TO_RESETS_NV 0x90B5 -#define GL_MOVE_TO_CONTINUES_NV 0x90B6 -#define GL_CLOSE_PATH_NV 0x00 -#define GL_MOVE_TO_NV 0x02 -#define GL_RELATIVE_MOVE_TO_NV 0x03 -#define GL_LINE_TO_NV 0x04 -#define GL_RELATIVE_LINE_TO_NV 0x05 -#define GL_HORIZONTAL_LINE_TO_NV 0x06 -#define GL_RELATIVE_HORIZONTAL_LINE_TO_NV 0x07 -#define GL_VERTICAL_LINE_TO_NV 0x08 -#define GL_RELATIVE_VERTICAL_LINE_TO_NV 0x09 -#define GL_QUADRATIC_CURVE_TO_NV 0x0A -#define GL_RELATIVE_QUADRATIC_CURVE_TO_NV 0x0B -#define GL_CUBIC_CURVE_TO_NV 0x0C -#define GL_RELATIVE_CUBIC_CURVE_TO_NV 0x0D -#define GL_SMOOTH_QUADRATIC_CURVE_TO_NV 0x0E -#define GL_RELATIVE_SMOOTH_QUADRATIC_CURVE_TO_NV 0x0F -#define GL_SMOOTH_CUBIC_CURVE_TO_NV 0x10 -#define GL_RELATIVE_SMOOTH_CUBIC_CURVE_TO_NV 0x11 -#define GL_SMALL_CCW_ARC_TO_NV 0x12 -#define GL_RELATIVE_SMALL_CCW_ARC_TO_NV 0x13 -#define GL_SMALL_CW_ARC_TO_NV 0x14 -#define GL_RELATIVE_SMALL_CW_ARC_TO_NV 0x15 -#define GL_LARGE_CCW_ARC_TO_NV 0x16 -#define GL_RELATIVE_LARGE_CCW_ARC_TO_NV 0x17 -#define GL_LARGE_CW_ARC_TO_NV 0x18 -#define GL_RELATIVE_LARGE_CW_ARC_TO_NV 0x19 -#define GL_RESTART_PATH_NV 0xF0 -#define GL_DUP_FIRST_CUBIC_CURVE_TO_NV 0xF2 -#define GL_DUP_LAST_CUBIC_CURVE_TO_NV 0xF4 -#define GL_RECT_NV 0xF6 -#define GL_CIRCULAR_CCW_ARC_TO_NV 0xF8 -#define GL_CIRCULAR_CW_ARC_TO_NV 0xFA -#define GL_CIRCULAR_TANGENT_ARC_TO_NV 0xFC -#define GL_ARC_TO_NV 0xFE -#define GL_RELATIVE_ARC_TO_NV 0xFF -#define GL_BOLD_BIT_NV 0x01 -#define GL_ITALIC_BIT_NV 0x02 -#define GL_GLYPH_WIDTH_BIT_NV 0x01 -#define GL_GLYPH_HEIGHT_BIT_NV 0x02 -#define GL_GLYPH_HORIZONTAL_BEARING_X_BIT_NV 0x04 -#define GL_GLYPH_HORIZONTAL_BEARING_Y_BIT_NV 0x08 -#define GL_GLYPH_HORIZONTAL_BEARING_ADVANCE_BIT_NV 0x10 -#define GL_GLYPH_VERTICAL_BEARING_X_BIT_NV 0x20 -#define GL_GLYPH_VERTICAL_BEARING_Y_BIT_NV 0x40 -#define GL_GLYPH_VERTICAL_BEARING_ADVANCE_BIT_NV 0x80 -#define GL_GLYPH_HAS_KERNING_BIT_NV 0x100 -#define GL_FONT_X_MIN_BOUNDS_BIT_NV 0x00010000 -#define GL_FONT_Y_MIN_BOUNDS_BIT_NV 0x00020000 -#define GL_FONT_X_MAX_BOUNDS_BIT_NV 0x00040000 -#define GL_FONT_Y_MAX_BOUNDS_BIT_NV 0x00080000 -#define GL_FONT_UNITS_PER_EM_BIT_NV 0x00100000 -#define GL_FONT_ASCENDER_BIT_NV 0x00200000 -#define GL_FONT_DESCENDER_BIT_NV 0x00400000 -#define GL_FONT_HEIGHT_BIT_NV 0x00800000 -#define GL_FONT_MAX_ADVANCE_WIDTH_BIT_NV 0x01000000 -#define GL_FONT_MAX_ADVANCE_HEIGHT_BIT_NV 0x02000000 -#define GL_FONT_UNDERLINE_POSITION_BIT_NV 0x04000000 -#define GL_FONT_UNDERLINE_THICKNESS_BIT_NV 0x08000000 -#define GL_FONT_HAS_KERNING_BIT_NV 0x10000000 -#define GL_ROUNDED_RECT_NV 0xE8 -#define GL_RELATIVE_ROUNDED_RECT_NV 0xE9 -#define GL_ROUNDED_RECT2_NV 0xEA -#define GL_RELATIVE_ROUNDED_RECT2_NV 0xEB -#define GL_ROUNDED_RECT4_NV 0xEC -#define GL_RELATIVE_ROUNDED_RECT4_NV 0xED -#define GL_ROUNDED_RECT8_NV 0xEE -#define GL_RELATIVE_ROUNDED_RECT8_NV 0xEF -#define GL_RELATIVE_RECT_NV 0xF7 -#define GL_FONT_GLYPHS_AVAILABLE_NV 0x9368 -#define GL_FONT_TARGET_UNAVAILABLE_NV 0x9369 -#define GL_FONT_UNAVAILABLE_NV 0x936A -#define GL_FONT_UNINTELLIGIBLE_NV 0x936B -#define GL_CONIC_CURVE_TO_NV 0x1A -#define GL_RELATIVE_CONIC_CURVE_TO_NV 0x1B -#define GL_FONT_NUM_GLYPH_INDICES_BIT_NV 0x20000000 -#define GL_STANDARD_FONT_FORMAT_NV 0x936C -#define GL_PATH_PROJECTION_NV 0x1701 -#define GL_PATH_MODELVIEW_NV 0x1700 -#define GL_PATH_MODELVIEW_STACK_DEPTH_NV 0x0BA3 -#define GL_PATH_MODELVIEW_MATRIX_NV 0x0BA6 -#define GL_PATH_MAX_MODELVIEW_STACK_DEPTH_NV 0x0D36 -#define GL_PATH_TRANSPOSE_MODELVIEW_MATRIX_NV 0x84E3 -#define GL_PATH_PROJECTION_STACK_DEPTH_NV 0x0BA4 -#define GL_PATH_PROJECTION_MATRIX_NV 0x0BA7 -#define GL_PATH_MAX_PROJECTION_STACK_DEPTH_NV 0x0D38 -#define GL_PATH_TRANSPOSE_PROJECTION_MATRIX_NV 0x84E4 -#define GL_FRAGMENT_INPUT_NV 0x936D -typedef GLuint (APIENTRYP PFNGLGENPATHSNVPROC) (GLsizei range); -typedef void (APIENTRYP PFNGLDELETEPATHSNVPROC) (GLuint path, GLsizei range); -typedef GLboolean (APIENTRYP PFNGLISPATHNVPROC) (GLuint path); -typedef void (APIENTRYP PFNGLPATHCOMMANDSNVPROC) (GLuint path, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); -typedef void (APIENTRYP PFNGLPATHCOORDSNVPROC) (GLuint path, GLsizei numCoords, GLenum coordType, const void *coords); -typedef void (APIENTRYP PFNGLPATHSUBCOMMANDSNVPROC) (GLuint path, GLsizei commandStart, GLsizei commandsToDelete, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); -typedef void (APIENTRYP PFNGLPATHSUBCOORDSNVPROC) (GLuint path, GLsizei coordStart, GLsizei numCoords, GLenum coordType, const void *coords); -typedef void (APIENTRYP PFNGLPATHSTRINGNVPROC) (GLuint path, GLenum format, GLsizei length, const void *pathString); -typedef void (APIENTRYP PFNGLPATHGLYPHSNVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLsizei numGlyphs, GLenum type, const void *charcodes, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); -typedef void (APIENTRYP PFNGLPATHGLYPHRANGENVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyph, GLsizei numGlyphs, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); -typedef void (APIENTRYP PFNGLWEIGHTPATHSNVPROC) (GLuint resultPath, GLsizei numPaths, const GLuint *paths, const GLfloat *weights); -typedef void (APIENTRYP PFNGLCOPYPATHNVPROC) (GLuint resultPath, GLuint srcPath); -typedef void (APIENTRYP PFNGLINTERPOLATEPATHSNVPROC) (GLuint resultPath, GLuint pathA, GLuint pathB, GLfloat weight); -typedef void (APIENTRYP PFNGLTRANSFORMPATHNVPROC) (GLuint resultPath, GLuint srcPath, GLenum transformType, const GLfloat *transformValues); -typedef void (APIENTRYP PFNGLPATHPARAMETERIVNVPROC) (GLuint path, GLenum pname, const GLint *value); -typedef void (APIENTRYP PFNGLPATHPARAMETERINVPROC) (GLuint path, GLenum pname, GLint value); -typedef void (APIENTRYP PFNGLPATHPARAMETERFVNVPROC) (GLuint path, GLenum pname, const GLfloat *value); -typedef void (APIENTRYP PFNGLPATHPARAMETERFNVPROC) (GLuint path, GLenum pname, GLfloat value); -typedef void (APIENTRYP PFNGLPATHDASHARRAYNVPROC) (GLuint path, GLsizei dashCount, const GLfloat *dashArray); -typedef void (APIENTRYP PFNGLPATHSTENCILFUNCNVPROC) (GLenum func, GLint ref, GLuint mask); -typedef void (APIENTRYP PFNGLPATHSTENCILDEPTHOFFSETNVPROC) (GLfloat factor, GLfloat units); -typedef void (APIENTRYP PFNGLSTENCILFILLPATHNVPROC) (GLuint path, GLenum fillMode, GLuint mask); -typedef void (APIENTRYP PFNGLSTENCILSTROKEPATHNVPROC) (GLuint path, GLint reference, GLuint mask); -typedef void (APIENTRYP PFNGLSTENCILFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum transformType, const GLfloat *transformValues); -typedef void (APIENTRYP PFNGLSTENCILSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum transformType, const GLfloat *transformValues); -typedef void (APIENTRYP PFNGLPATHCOVERDEPTHFUNCNVPROC) (GLenum func); -typedef void (APIENTRYP PFNGLCOVERFILLPATHNVPROC) (GLuint path, GLenum coverMode); -typedef void (APIENTRYP PFNGLCOVERSTROKEPATHNVPROC) (GLuint path, GLenum coverMode); -typedef void (APIENTRYP PFNGLCOVERFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); -typedef void (APIENTRYP PFNGLCOVERSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); -typedef void (APIENTRYP PFNGLGETPATHPARAMETERIVNVPROC) (GLuint path, GLenum pname, GLint *value); -typedef void (APIENTRYP PFNGLGETPATHPARAMETERFVNVPROC) (GLuint path, GLenum pname, GLfloat *value); -typedef void (APIENTRYP PFNGLGETPATHCOMMANDSNVPROC) (GLuint path, GLubyte *commands); -typedef void (APIENTRYP PFNGLGETPATHCOORDSNVPROC) (GLuint path, GLfloat *coords); -typedef void (APIENTRYP PFNGLGETPATHDASHARRAYNVPROC) (GLuint path, GLfloat *dashArray); -typedef void (APIENTRYP PFNGLGETPATHMETRICSNVPROC) (GLbitfield metricQueryMask, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLsizei stride, GLfloat *metrics); -typedef void (APIENTRYP PFNGLGETPATHMETRICRANGENVPROC) (GLbitfield metricQueryMask, GLuint firstPathName, GLsizei numPaths, GLsizei stride, GLfloat *metrics); -typedef void (APIENTRYP PFNGLGETPATHSPACINGNVPROC) (GLenum pathListMode, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLfloat advanceScale, GLfloat kerningScale, GLenum transformType, GLfloat *returnedSpacing); -typedef GLboolean (APIENTRYP PFNGLISPOINTINFILLPATHNVPROC) (GLuint path, GLuint mask, GLfloat x, GLfloat y); -typedef GLboolean (APIENTRYP PFNGLISPOINTINSTROKEPATHNVPROC) (GLuint path, GLfloat x, GLfloat y); -typedef GLfloat (APIENTRYP PFNGLGETPATHLENGTHNVPROC) (GLuint path, GLsizei startSegment, GLsizei numSegments); -typedef GLboolean (APIENTRYP PFNGLPOINTALONGPATHNVPROC) (GLuint path, GLsizei startSegment, GLsizei numSegments, GLfloat distance, GLfloat *x, GLfloat *y, GLfloat *tangentX, GLfloat *tangentY); -typedef void (APIENTRYP PFNGLMATRIXLOAD3X2FNVPROC) (GLenum matrixMode, const GLfloat *m); -typedef void (APIENTRYP PFNGLMATRIXLOAD3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); -typedef void (APIENTRYP PFNGLMATRIXLOADTRANSPOSE3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); -typedef void (APIENTRYP PFNGLMATRIXMULT3X2FNVPROC) (GLenum matrixMode, const GLfloat *m); -typedef void (APIENTRYP PFNGLMATRIXMULT3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); -typedef void (APIENTRYP PFNGLMATRIXMULTTRANSPOSE3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); -typedef void (APIENTRYP PFNGLSTENCILTHENCOVERFILLPATHNVPROC) (GLuint path, GLenum fillMode, GLuint mask, GLenum coverMode); -typedef void (APIENTRYP PFNGLSTENCILTHENCOVERSTROKEPATHNVPROC) (GLuint path, GLint reference, GLuint mask, GLenum coverMode); -typedef void (APIENTRYP PFNGLSTENCILTHENCOVERFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); -typedef void (APIENTRYP PFNGLSTENCILTHENCOVERSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); -typedef GLenum (APIENTRYP PFNGLPATHGLYPHINDEXRANGENVPROC) (GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint pathParameterTemplate, GLfloat emScale, GLuint baseAndCount[2]); -typedef GLenum (APIENTRYP PFNGLPATHGLYPHINDEXARRAYNVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); -typedef GLenum (APIENTRYP PFNGLPATHMEMORYGLYPHINDEXARRAYNVPROC) (GLuint firstPathName, GLenum fontTarget, GLsizeiptr fontSize, const void *fontData, GLsizei faceIndex, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); -typedef void (APIENTRYP PFNGLPROGRAMPATHFRAGMENTINPUTGENNVPROC) (GLuint program, GLint location, GLenum genMode, GLint components, const GLfloat *coeffs); -typedef void (APIENTRYP PFNGLGETPROGRAMRESOURCEFVNVPROC) (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLfloat *params); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI GLuint APIENTRY glGenPathsNV (GLsizei range); -GLAPI void APIENTRY glDeletePathsNV (GLuint path, GLsizei range); -GLAPI GLboolean APIENTRY glIsPathNV (GLuint path); -GLAPI void APIENTRY glPathCommandsNV (GLuint path, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); -GLAPI void APIENTRY glPathCoordsNV (GLuint path, GLsizei numCoords, GLenum coordType, const void *coords); -GLAPI void APIENTRY glPathSubCommandsNV (GLuint path, GLsizei commandStart, GLsizei commandsToDelete, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); -GLAPI void APIENTRY glPathSubCoordsNV (GLuint path, GLsizei coordStart, GLsizei numCoords, GLenum coordType, const void *coords); -GLAPI void APIENTRY glPathStringNV (GLuint path, GLenum format, GLsizei length, const void *pathString); -GLAPI void APIENTRY glPathGlyphsNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLsizei numGlyphs, GLenum type, const void *charcodes, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); -GLAPI void APIENTRY glPathGlyphRangeNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyph, GLsizei numGlyphs, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); -GLAPI void APIENTRY glWeightPathsNV (GLuint resultPath, GLsizei numPaths, const GLuint *paths, const GLfloat *weights); -GLAPI void APIENTRY glCopyPathNV (GLuint resultPath, GLuint srcPath); -GLAPI void APIENTRY glInterpolatePathsNV (GLuint resultPath, GLuint pathA, GLuint pathB, GLfloat weight); -GLAPI void APIENTRY glTransformPathNV (GLuint resultPath, GLuint srcPath, GLenum transformType, const GLfloat *transformValues); -GLAPI void APIENTRY glPathParameterivNV (GLuint path, GLenum pname, const GLint *value); -GLAPI void APIENTRY glPathParameteriNV (GLuint path, GLenum pname, GLint value); -GLAPI void APIENTRY glPathParameterfvNV (GLuint path, GLenum pname, const GLfloat *value); -GLAPI void APIENTRY glPathParameterfNV (GLuint path, GLenum pname, GLfloat value); -GLAPI void APIENTRY glPathDashArrayNV (GLuint path, GLsizei dashCount, const GLfloat *dashArray); -GLAPI void APIENTRY glPathStencilFuncNV (GLenum func, GLint ref, GLuint mask); -GLAPI void APIENTRY glPathStencilDepthOffsetNV (GLfloat factor, GLfloat units); -GLAPI void APIENTRY glStencilFillPathNV (GLuint path, GLenum fillMode, GLuint mask); -GLAPI void APIENTRY glStencilStrokePathNV (GLuint path, GLint reference, GLuint mask); -GLAPI void APIENTRY glStencilFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum transformType, const GLfloat *transformValues); -GLAPI void APIENTRY glStencilStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum transformType, const GLfloat *transformValues); -GLAPI void APIENTRY glPathCoverDepthFuncNV (GLenum func); -GLAPI void APIENTRY glCoverFillPathNV (GLuint path, GLenum coverMode); -GLAPI void APIENTRY glCoverStrokePathNV (GLuint path, GLenum coverMode); -GLAPI void APIENTRY glCoverFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); -GLAPI void APIENTRY glCoverStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); -GLAPI void APIENTRY glGetPathParameterivNV (GLuint path, GLenum pname, GLint *value); -GLAPI void APIENTRY glGetPathParameterfvNV (GLuint path, GLenum pname, GLfloat *value); -GLAPI void APIENTRY glGetPathCommandsNV (GLuint path, GLubyte *commands); -GLAPI void APIENTRY glGetPathCoordsNV (GLuint path, GLfloat *coords); -GLAPI void APIENTRY glGetPathDashArrayNV (GLuint path, GLfloat *dashArray); -GLAPI void APIENTRY glGetPathMetricsNV (GLbitfield metricQueryMask, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLsizei stride, GLfloat *metrics); -GLAPI void APIENTRY glGetPathMetricRangeNV (GLbitfield metricQueryMask, GLuint firstPathName, GLsizei numPaths, GLsizei stride, GLfloat *metrics); -GLAPI void APIENTRY glGetPathSpacingNV (GLenum pathListMode, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLfloat advanceScale, GLfloat kerningScale, GLenum transformType, GLfloat *returnedSpacing); -GLAPI GLboolean APIENTRY glIsPointInFillPathNV (GLuint path, GLuint mask, GLfloat x, GLfloat y); -GLAPI GLboolean APIENTRY glIsPointInStrokePathNV (GLuint path, GLfloat x, GLfloat y); -GLAPI GLfloat APIENTRY glGetPathLengthNV (GLuint path, GLsizei startSegment, GLsizei numSegments); -GLAPI GLboolean APIENTRY glPointAlongPathNV (GLuint path, GLsizei startSegment, GLsizei numSegments, GLfloat distance, GLfloat *x, GLfloat *y, GLfloat *tangentX, GLfloat *tangentY); -GLAPI void APIENTRY glMatrixLoad3x2fNV (GLenum matrixMode, const GLfloat *m); -GLAPI void APIENTRY glMatrixLoad3x3fNV (GLenum matrixMode, const GLfloat *m); -GLAPI void APIENTRY glMatrixLoadTranspose3x3fNV (GLenum matrixMode, const GLfloat *m); -GLAPI void APIENTRY glMatrixMult3x2fNV (GLenum matrixMode, const GLfloat *m); -GLAPI void APIENTRY glMatrixMult3x3fNV (GLenum matrixMode, const GLfloat *m); -GLAPI void APIENTRY glMatrixMultTranspose3x3fNV (GLenum matrixMode, const GLfloat *m); -GLAPI void APIENTRY glStencilThenCoverFillPathNV (GLuint path, GLenum fillMode, GLuint mask, GLenum coverMode); -GLAPI void APIENTRY glStencilThenCoverStrokePathNV (GLuint path, GLint reference, GLuint mask, GLenum coverMode); -GLAPI void APIENTRY glStencilThenCoverFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); -GLAPI void APIENTRY glStencilThenCoverStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); -GLAPI GLenum APIENTRY glPathGlyphIndexRangeNV (GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint pathParameterTemplate, GLfloat emScale, GLuint baseAndCount[2]); -GLAPI GLenum APIENTRY glPathGlyphIndexArrayNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); -GLAPI GLenum APIENTRY glPathMemoryGlyphIndexArrayNV (GLuint firstPathName, GLenum fontTarget, GLsizeiptr fontSize, const void *fontData, GLsizei faceIndex, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); -GLAPI void APIENTRY glProgramPathFragmentInputGenNV (GLuint program, GLint location, GLenum genMode, GLint components, const GLfloat *coeffs); -GLAPI void APIENTRY glGetProgramResourcefvNV (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLfloat *params); -#endif -#endif /* GL_NV_path_rendering */ - -#ifndef GL_NV_path_rendering_shared_edge -#define GL_NV_path_rendering_shared_edge 1 -#define GL_SHARED_EDGE_NV 0xC0 -#endif /* GL_NV_path_rendering_shared_edge */ - -#ifndef GL_NV_sample_locations -#define GL_NV_sample_locations 1 -#define GL_SAMPLE_LOCATION_SUBPIXEL_BITS_NV 0x933D -#define GL_SAMPLE_LOCATION_PIXEL_GRID_WIDTH_NV 0x933E -#define GL_SAMPLE_LOCATION_PIXEL_GRID_HEIGHT_NV 0x933F -#define GL_PROGRAMMABLE_SAMPLE_LOCATION_TABLE_SIZE_NV 0x9340 -#define GL_SAMPLE_LOCATION_NV 0x8E50 -#define GL_PROGRAMMABLE_SAMPLE_LOCATION_NV 0x9341 -#define GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_NV 0x9342 -#define GL_FRAMEBUFFER_SAMPLE_LOCATION_PIXEL_GRID_NV 0x9343 -typedef void (APIENTRYP PFNGLFRAMEBUFFERSAMPLELOCATIONSFVNVPROC) (GLenum target, GLuint start, GLsizei count, const GLfloat *v); -typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVNVPROC) (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); -typedef void (APIENTRYP PFNGLRESOLVEDEPTHVALUESNVPROC) (void); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glFramebufferSampleLocationsfvNV (GLenum target, GLuint start, GLsizei count, const GLfloat *v); -GLAPI void APIENTRY glNamedFramebufferSampleLocationsfvNV (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); -GLAPI void APIENTRY glResolveDepthValuesNV (void); -#endif -#endif /* GL_NV_sample_locations */ - -#ifndef GL_NV_sample_mask_override_coverage -#define GL_NV_sample_mask_override_coverage 1 -#endif /* GL_NV_sample_mask_override_coverage */ - -#ifndef GL_NV_shader_atomic_counters -#define GL_NV_shader_atomic_counters 1 -#endif /* GL_NV_shader_atomic_counters */ - -#ifndef GL_NV_shader_atomic_float -#define GL_NV_shader_atomic_float 1 -#endif /* GL_NV_shader_atomic_float */ - -#ifndef GL_NV_shader_atomic_float64 -#define GL_NV_shader_atomic_float64 1 -#endif /* GL_NV_shader_atomic_float64 */ - -#ifndef GL_NV_shader_atomic_fp16_vector -#define GL_NV_shader_atomic_fp16_vector 1 -#endif /* GL_NV_shader_atomic_fp16_vector */ - -#ifndef GL_NV_shader_atomic_int64 -#define GL_NV_shader_atomic_int64 1 -#endif /* GL_NV_shader_atomic_int64 */ - -#ifndef GL_NV_shader_buffer_load -#define GL_NV_shader_buffer_load 1 -#define GL_BUFFER_GPU_ADDRESS_NV 0x8F1D -#define GL_GPU_ADDRESS_NV 0x8F34 -#define GL_MAX_SHADER_BUFFER_ADDRESS_NV 0x8F35 -typedef void (APIENTRYP PFNGLMAKEBUFFERRESIDENTNVPROC) (GLenum target, GLenum access); -typedef void (APIENTRYP PFNGLMAKEBUFFERNONRESIDENTNVPROC) (GLenum target); -typedef GLboolean (APIENTRYP PFNGLISBUFFERRESIDENTNVPROC) (GLenum target); -typedef void (APIENTRYP PFNGLMAKENAMEDBUFFERRESIDENTNVPROC) (GLuint buffer, GLenum access); -typedef void (APIENTRYP PFNGLMAKENAMEDBUFFERNONRESIDENTNVPROC) (GLuint buffer); -typedef GLboolean (APIENTRYP PFNGLISNAMEDBUFFERRESIDENTNVPROC) (GLuint buffer); -typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERUI64VNVPROC) (GLenum target, GLenum pname, GLuint64EXT *params); -typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERUI64VNVPROC) (GLuint buffer, GLenum pname, GLuint64EXT *params); -typedef void (APIENTRYP PFNGLGETINTEGERUI64VNVPROC) (GLenum value, GLuint64EXT *result); -typedef void (APIENTRYP PFNGLUNIFORMUI64NVPROC) (GLint location, GLuint64EXT value); -typedef void (APIENTRYP PFNGLUNIFORMUI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); -typedef void (APIENTRYP PFNGLGETUNIFORMUI64VNVPROC) (GLuint program, GLint location, GLuint64EXT *params); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMUI64NVPROC) (GLuint program, GLint location, GLuint64EXT value); -typedef void (APIENTRYP PFNGLPROGRAMUNIFORMUI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glMakeBufferResidentNV (GLenum target, GLenum access); -GLAPI void APIENTRY glMakeBufferNonResidentNV (GLenum target); -GLAPI GLboolean APIENTRY glIsBufferResidentNV (GLenum target); -GLAPI void APIENTRY glMakeNamedBufferResidentNV (GLuint buffer, GLenum access); -GLAPI void APIENTRY glMakeNamedBufferNonResidentNV (GLuint buffer); -GLAPI GLboolean APIENTRY glIsNamedBufferResidentNV (GLuint buffer); -GLAPI void APIENTRY glGetBufferParameterui64vNV (GLenum target, GLenum pname, GLuint64EXT *params); -GLAPI void APIENTRY glGetNamedBufferParameterui64vNV (GLuint buffer, GLenum pname, GLuint64EXT *params); -GLAPI void APIENTRY glGetIntegerui64vNV (GLenum value, GLuint64EXT *result); -GLAPI void APIENTRY glUniformui64NV (GLint location, GLuint64EXT value); -GLAPI void APIENTRY glUniformui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); -GLAPI void APIENTRY glGetUniformui64vNV (GLuint program, GLint location, GLuint64EXT *params); -GLAPI void APIENTRY glProgramUniformui64NV (GLuint program, GLint location, GLuint64EXT value); -GLAPI void APIENTRY glProgramUniformui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); -#endif -#endif /* GL_NV_shader_buffer_load */ - -#ifndef GL_NV_shader_buffer_store -#define GL_NV_shader_buffer_store 1 -#define GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV 0x00000010 -#endif /* GL_NV_shader_buffer_store */ - -#ifndef GL_NV_shader_thread_group -#define GL_NV_shader_thread_group 1 -#define GL_WARP_SIZE_NV 0x9339 -#define GL_WARPS_PER_SM_NV 0x933A -#define GL_SM_COUNT_NV 0x933B -#endif /* GL_NV_shader_thread_group */ - -#ifndef GL_NV_shader_thread_shuffle -#define GL_NV_shader_thread_shuffle 1 -#endif /* GL_NV_shader_thread_shuffle */ - -#ifndef GL_NV_stereo_view_rendering -#define GL_NV_stereo_view_rendering 1 -#endif /* GL_NV_stereo_view_rendering */ - -#ifndef GL_NV_texture_barrier -#define GL_NV_texture_barrier 1 -typedef void (APIENTRYP PFNGLTEXTUREBARRIERNVPROC) (void); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glTextureBarrierNV (void); -#endif -#endif /* GL_NV_texture_barrier */ - -#ifndef GL_NV_texture_rectangle_compressed -#define GL_NV_texture_rectangle_compressed 1 -#endif /* GL_NV_texture_rectangle_compressed */ - -#ifndef GL_NV_uniform_buffer_unified_memory -#define GL_NV_uniform_buffer_unified_memory 1 -#define GL_UNIFORM_BUFFER_UNIFIED_NV 0x936E -#define GL_UNIFORM_BUFFER_ADDRESS_NV 0x936F -#define GL_UNIFORM_BUFFER_LENGTH_NV 0x9370 -#endif /* GL_NV_uniform_buffer_unified_memory */ - -#ifndef GL_NV_vertex_attrib_integer_64bit -#define GL_NV_vertex_attrib_integer_64bit 1 -typedef void (APIENTRYP PFNGLVERTEXATTRIBL1I64NVPROC) (GLuint index, GLint64EXT x); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL2I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL3I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL4I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL1I64VNVPROC) (GLuint index, const GLint64EXT *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL2I64VNVPROC) (GLuint index, const GLint64EXT *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL3I64VNVPROC) (GLuint index, const GLint64EXT *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL4I64VNVPROC) (GLuint index, const GLint64EXT *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64NVPROC) (GLuint index, GLuint64EXT x); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL2UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL3UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL4UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64VNVPROC) (GLuint index, const GLuint64EXT *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL2UI64VNVPROC) (GLuint index, const GLuint64EXT *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL3UI64VNVPROC) (GLuint index, const GLuint64EXT *v); -typedef void (APIENTRYP PFNGLVERTEXATTRIBL4UI64VNVPROC) (GLuint index, const GLuint64EXT *v); -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLI64VNVPROC) (GLuint index, GLenum pname, GLint64EXT *params); -typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLUI64VNVPROC) (GLuint index, GLenum pname, GLuint64EXT *params); -typedef void (APIENTRYP PFNGLVERTEXATTRIBLFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLsizei stride); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glVertexAttribL1i64NV (GLuint index, GLint64EXT x); -GLAPI void APIENTRY glVertexAttribL2i64NV (GLuint index, GLint64EXT x, GLint64EXT y); -GLAPI void APIENTRY glVertexAttribL3i64NV (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z); -GLAPI void APIENTRY glVertexAttribL4i64NV (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); -GLAPI void APIENTRY glVertexAttribL1i64vNV (GLuint index, const GLint64EXT *v); -GLAPI void APIENTRY glVertexAttribL2i64vNV (GLuint index, const GLint64EXT *v); -GLAPI void APIENTRY glVertexAttribL3i64vNV (GLuint index, const GLint64EXT *v); -GLAPI void APIENTRY glVertexAttribL4i64vNV (GLuint index, const GLint64EXT *v); -GLAPI void APIENTRY glVertexAttribL1ui64NV (GLuint index, GLuint64EXT x); -GLAPI void APIENTRY glVertexAttribL2ui64NV (GLuint index, GLuint64EXT x, GLuint64EXT y); -GLAPI void APIENTRY glVertexAttribL3ui64NV (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); -GLAPI void APIENTRY glVertexAttribL4ui64NV (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); -GLAPI void APIENTRY glVertexAttribL1ui64vNV (GLuint index, const GLuint64EXT *v); -GLAPI void APIENTRY glVertexAttribL2ui64vNV (GLuint index, const GLuint64EXT *v); -GLAPI void APIENTRY glVertexAttribL3ui64vNV (GLuint index, const GLuint64EXT *v); -GLAPI void APIENTRY glVertexAttribL4ui64vNV (GLuint index, const GLuint64EXT *v); -GLAPI void APIENTRY glGetVertexAttribLi64vNV (GLuint index, GLenum pname, GLint64EXT *params); -GLAPI void APIENTRY glGetVertexAttribLui64vNV (GLuint index, GLenum pname, GLuint64EXT *params); -GLAPI void APIENTRY glVertexAttribLFormatNV (GLuint index, GLint size, GLenum type, GLsizei stride); -#endif -#endif /* GL_NV_vertex_attrib_integer_64bit */ - -#ifndef GL_NV_vertex_buffer_unified_memory -#define GL_NV_vertex_buffer_unified_memory 1 -#define GL_VERTEX_ATTRIB_ARRAY_UNIFIED_NV 0x8F1E -#define GL_ELEMENT_ARRAY_UNIFIED_NV 0x8F1F -#define GL_VERTEX_ATTRIB_ARRAY_ADDRESS_NV 0x8F20 -#define GL_VERTEX_ARRAY_ADDRESS_NV 0x8F21 -#define GL_NORMAL_ARRAY_ADDRESS_NV 0x8F22 -#define GL_COLOR_ARRAY_ADDRESS_NV 0x8F23 -#define GL_INDEX_ARRAY_ADDRESS_NV 0x8F24 -#define GL_TEXTURE_COORD_ARRAY_ADDRESS_NV 0x8F25 -#define GL_EDGE_FLAG_ARRAY_ADDRESS_NV 0x8F26 -#define GL_SECONDARY_COLOR_ARRAY_ADDRESS_NV 0x8F27 -#define GL_FOG_COORD_ARRAY_ADDRESS_NV 0x8F28 -#define GL_ELEMENT_ARRAY_ADDRESS_NV 0x8F29 -#define GL_VERTEX_ATTRIB_ARRAY_LENGTH_NV 0x8F2A -#define GL_VERTEX_ARRAY_LENGTH_NV 0x8F2B -#define GL_NORMAL_ARRAY_LENGTH_NV 0x8F2C -#define GL_COLOR_ARRAY_LENGTH_NV 0x8F2D -#define GL_INDEX_ARRAY_LENGTH_NV 0x8F2E -#define GL_TEXTURE_COORD_ARRAY_LENGTH_NV 0x8F2F -#define GL_EDGE_FLAG_ARRAY_LENGTH_NV 0x8F30 -#define GL_SECONDARY_COLOR_ARRAY_LENGTH_NV 0x8F31 -#define GL_FOG_COORD_ARRAY_LENGTH_NV 0x8F32 -#define GL_ELEMENT_ARRAY_LENGTH_NV 0x8F33 -#define GL_DRAW_INDIRECT_UNIFIED_NV 0x8F40 -#define GL_DRAW_INDIRECT_ADDRESS_NV 0x8F41 -#define GL_DRAW_INDIRECT_LENGTH_NV 0x8F42 -typedef void (APIENTRYP PFNGLBUFFERADDRESSRANGENVPROC) (GLenum pname, GLuint index, GLuint64EXT address, GLsizeiptr length); -typedef void (APIENTRYP PFNGLVERTEXFORMATNVPROC) (GLint size, GLenum type, GLsizei stride); -typedef void (APIENTRYP PFNGLNORMALFORMATNVPROC) (GLenum type, GLsizei stride); -typedef void (APIENTRYP PFNGLCOLORFORMATNVPROC) (GLint size, GLenum type, GLsizei stride); -typedef void (APIENTRYP PFNGLINDEXFORMATNVPROC) (GLenum type, GLsizei stride); -typedef void (APIENTRYP PFNGLTEXCOORDFORMATNVPROC) (GLint size, GLenum type, GLsizei stride); -typedef void (APIENTRYP PFNGLEDGEFLAGFORMATNVPROC) (GLsizei stride); -typedef void (APIENTRYP PFNGLSECONDARYCOLORFORMATNVPROC) (GLint size, GLenum type, GLsizei stride); -typedef void (APIENTRYP PFNGLFOGCOORDFORMATNVPROC) (GLenum type, GLsizei stride); -typedef void (APIENTRYP PFNGLVERTEXATTRIBFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride); -typedef void (APIENTRYP PFNGLVERTEXATTRIBIFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLsizei stride); -typedef void (APIENTRYP PFNGLGETINTEGERUI64I_VNVPROC) (GLenum value, GLuint index, GLuint64EXT *result); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glBufferAddressRangeNV (GLenum pname, GLuint index, GLuint64EXT address, GLsizeiptr length); -GLAPI void APIENTRY glVertexFormatNV (GLint size, GLenum type, GLsizei stride); -GLAPI void APIENTRY glNormalFormatNV (GLenum type, GLsizei stride); -GLAPI void APIENTRY glColorFormatNV (GLint size, GLenum type, GLsizei stride); -GLAPI void APIENTRY glIndexFormatNV (GLenum type, GLsizei stride); -GLAPI void APIENTRY glTexCoordFormatNV (GLint size, GLenum type, GLsizei stride); -GLAPI void APIENTRY glEdgeFlagFormatNV (GLsizei stride); -GLAPI void APIENTRY glSecondaryColorFormatNV (GLint size, GLenum type, GLsizei stride); -GLAPI void APIENTRY glFogCoordFormatNV (GLenum type, GLsizei stride); -GLAPI void APIENTRY glVertexAttribFormatNV (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride); -GLAPI void APIENTRY glVertexAttribIFormatNV (GLuint index, GLint size, GLenum type, GLsizei stride); -GLAPI void APIENTRY glGetIntegerui64i_vNV (GLenum value, GLuint index, GLuint64EXT *result); -#endif -#endif /* GL_NV_vertex_buffer_unified_memory */ - -#ifndef GL_NV_viewport_array2 -#define GL_NV_viewport_array2 1 -#endif /* GL_NV_viewport_array2 */ - -#ifndef GL_NV_viewport_swizzle -#define GL_NV_viewport_swizzle 1 -#define GL_VIEWPORT_SWIZZLE_POSITIVE_X_NV 0x9350 -#define GL_VIEWPORT_SWIZZLE_NEGATIVE_X_NV 0x9351 -#define GL_VIEWPORT_SWIZZLE_POSITIVE_Y_NV 0x9352 -#define GL_VIEWPORT_SWIZZLE_NEGATIVE_Y_NV 0x9353 -#define GL_VIEWPORT_SWIZZLE_POSITIVE_Z_NV 0x9354 -#define GL_VIEWPORT_SWIZZLE_NEGATIVE_Z_NV 0x9355 -#define GL_VIEWPORT_SWIZZLE_POSITIVE_W_NV 0x9356 -#define GL_VIEWPORT_SWIZZLE_NEGATIVE_W_NV 0x9357 -#define GL_VIEWPORT_SWIZZLE_X_NV 0x9358 -#define GL_VIEWPORT_SWIZZLE_Y_NV 0x9359 -#define GL_VIEWPORT_SWIZZLE_Z_NV 0x935A -#define GL_VIEWPORT_SWIZZLE_W_NV 0x935B -typedef void (APIENTRYP PFNGLVIEWPORTSWIZZLENVPROC) (GLuint index, GLenum swizzlex, GLenum swizzley, GLenum swizzlez, GLenum swizzlew); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glViewportSwizzleNV (GLuint index, GLenum swizzlex, GLenum swizzley, GLenum swizzlez, GLenum swizzlew); -#endif -#endif /* GL_NV_viewport_swizzle */ - -#ifndef GL_OVR_multiview -#define GL_OVR_multiview 1 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR 0x9630 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR 0x9632 -#define GL_MAX_VIEWS_OVR 0x9631 -#define GL_FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR 0x9633 -typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews); -#ifdef GL_GLEXT_PROTOTYPES -GLAPI void APIENTRY glFramebufferTextureMultiviewOVR (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews); -#endif -#endif /* GL_OVR_multiview */ - -#ifndef GL_OVR_multiview2 -#define GL_OVR_multiview2 1 -#endif /* GL_OVR_multiview2 */ - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/RenderSystems/GL3Plus/include/OgreGL3PlusFBOMultiRenderTarget.h b/RenderSystems/GL3Plus/include/OgreGL3PlusFBOMultiRenderTarget.h deleted file mode 100644 index e98968aabe1..00000000000 --- a/RenderSystems/GL3Plus/include/OgreGL3PlusFBOMultiRenderTarget.h +++ /dev/null @@ -1,64 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GL3PlusMULTIRENDERTARGET_H__ -#define __GL3PlusMULTIRENDERTARGET_H__ - -#include "OgreGL3PlusFrameBufferObject.h" - -namespace Ogre { - - class GL3PlusFBOManager; - - /** MultiRenderTarget for OpenGL - */ - class _OgreGL3PlusExport GL3PlusFBOMultiRenderTarget : public MultiRenderTarget, public GLRenderTarget - { - public: - GL3PlusFBOMultiRenderTarget(GL3PlusFBOManager *manager, const String &name); - ~GL3PlusFBOMultiRenderTarget(); - - void getCustomAttribute( const String& name, void *pData ) override; - GLContext* getContext() const override { return fbo.getContext(); } - GLFrameBufferObjectCommon* getFBO() override { return &fbo; } - - bool requiresTextureFlipping() const override { return true; } - - /// Override so we can attach the depth buffer to the FBO - bool attachDepthBuffer( DepthBuffer *depthBuffer ) override; - void detachDepthBuffer() override; - void _detachDepthBuffer() override; - private: - void bindSurfaceImpl(size_t attachment, RenderTexture *target) override; - void unbindSurfaceImpl(size_t attachment) override; - GL3PlusFrameBufferObject fbo; - }; - -} - -#endif // __GL3PlusMULTIRENDERTARGET_H__ diff --git a/RenderSystems/GL3Plus/include/OgreGL3PlusFBORenderTexture.h b/RenderSystems/GL3Plus/include/OgreGL3PlusFBORenderTexture.h deleted file mode 100644 index c45ba5dba2a..00000000000 --- a/RenderSystems/GL3Plus/include/OgreGL3PlusFBORenderTexture.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#ifndef __OgreGL3PlusFBORTT_H__ -#define __OgreGL3PlusFBORTT_H__ - -#include "OgreGLRenderTexture.h" -#include "OgreGLContext.h" -#include "OgreGL3PlusFrameBufferObject.h" - -namespace Ogre { - class GL3PlusFBOManager; - class GL3PlusRenderBuffer; - class GL3PlusStateCacheManager; - - /** RenderTexture for GL FBO - */ - class _OgreGL3PlusExport GL3PlusFBORenderTexture : public GLRenderTexture - { - public: - GL3PlusFBORenderTexture(GL3PlusFBOManager *manager, const String &name, const GLSurfaceDesc &target, bool writeGamma, uint fsaa); - - void getCustomAttribute(const String& name, void* pData) override; - - /// Override needed to deal with multisample buffers - void swapBuffers() override; - - /// Override so we can attach the depth buffer to the FBO - bool attachDepthBuffer( DepthBuffer *depthBuffer ) override; - void detachDepthBuffer() override; - void _detachDepthBuffer() override; - - GLContext* getContext() const override { return mFB.getContext(); } - GLFrameBufferObjectCommon* getFBO() override { return &mFB; } - protected: - GL3PlusFrameBufferObject mFB; - }; - - /** Factory for GL Frame Buffer Objects, and related things. - */ - class _OgreGL3PlusExport GL3PlusFBOManager: public GL3PlusRTTManager - { - public: - GL3PlusFBOManager(GL3PlusRenderSystem* renderSystem); - ~GL3PlusFBOManager(); - - /** Get best depth and stencil supported for given internalFormat - */ - void getBestDepthStencil(PixelFormat internalFormat, GLenum *depthFormat, GLenum *stencilFormat) override; - - /** Create a texture rendertarget object - */ - GL3PlusFBORenderTexture *createRenderTexture(const String &name, - const GLSurfaceDesc &target, bool writeGamma, uint fsaa) override; - - /** Request a render buffer. If format is GL_NONE, return a zero buffer. - */ - GLSurfaceDesc requestRenderBuffer(GLenum format, uint32 width, uint32 height, uint fsaa); - - GL3PlusStateCacheManager* getStateCacheManager(); - private: - GL3PlusRenderSystem* mRenderSystem; - - /** Detect allowed FBO formats */ - void detectFBOFormats(); - GLuint _tryFormat(GLenum depthFormat, GLenum stencilFormat); - bool _tryPackedFormat(GLenum packedFormat); - void _createTempFramebuffer(GLuint internalFormat, GLuint fmt, GLenum dataType, GLuint &fb, GLuint &tid); - }; -} - -#endif diff --git a/RenderSystems/GL3Plus/include/OgreGL3PlusFrameBufferObject.h b/RenderSystems/GL3Plus/include/OgreGL3PlusFrameBufferObject.h deleted file mode 100644 index 33d9e77c9c5..00000000000 --- a/RenderSystems/GL3Plus/include/OgreGL3PlusFrameBufferObject.h +++ /dev/null @@ -1,71 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OgreGL3PlusFBO_H__ -#define __OgreGL3PlusFBO_H__ - -#include "OgreGL3PlusPrerequisites.h" -#include "OgreGLRenderTexture.h" -#include "OgreGLContext.h" - -namespace Ogre { - - class GL3PlusFBOManager; - - /** Frame Buffer Object abstraction. - */ - class _OgreGL3PlusExport GL3PlusFrameBufferObject : public GLFrameBufferObjectCommon - { - public: - GL3PlusFrameBufferObject(GL3PlusFBOManager *manager, uint fsaa); - ~GL3PlusFrameBufferObject(); - - bool bind(bool recreateIfNeeded) override; - - /** Swap buffers - only useful when using multisample buffers. - */ - void swapBuffers(); - - /** This function acts very similar to @see GL3PlusFBORenderTexture::attachDepthBuffer - The difference between D3D & OGL is that D3D setups the DepthBuffer before rendering, - while OGL setups the DepthBuffer per FBO. So the DepthBuffer (RenderBuffer) needs to - be attached for OGL. - */ - void attachDepthBuffer( DepthBuffer *depthBuffer ); - void detachDepthBuffer(); - - GL3PlusFBOManager *getManager() { return mManager; } - private: - GL3PlusFBOManager *mManager; - GLSurfaceDesc mMultisampleColourBuffer; - - void initialise() override; - }; - -} - -#endif diff --git a/RenderSystems/GL3Plus/include/OgreGL3PlusHardwareBuffer.h b/RenderSystems/GL3Plus/include/OgreGL3PlusHardwareBuffer.h deleted file mode 100644 index dfc8fd20c96..00000000000 --- a/RenderSystems/GL3Plus/include/OgreGL3PlusHardwareBuffer.h +++ /dev/null @@ -1,74 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GL3PlusHARDWAREBUFFER_H__ -#define __GL3PlusHARDWAREBUFFER_H__ - -#include "OgreGL3PlusPrerequisites.h" -#include "OgreHardwareBuffer.h" - -namespace Ogre { - class GL3PlusHardwareBuffer : public HardwareBuffer - { - private: - GLenum mTarget; - GLuint mBufferId; - GL3PlusRenderSystem* mRenderSystem; - - // for UBO/ SSBO - GLint mBindingPoint; - - /// Utility function to get the correct GL usage based on HBU's - static GLenum getGLUsage(uint32 usage); - - void writeDataImpl(size_t offset, size_t length, const void* pSource, bool discardWholeBuffer); - public: - void* lockImpl(size_t offset, size_t length, LockOptions options) override; - void unlockImpl() override; - - GL3PlusHardwareBuffer(GLenum target, size_t sizeInBytes, uint32 usage, bool useShadowBuffer = false); - ~GL3PlusHardwareBuffer(); - - void readData(size_t offset, size_t length, void* pDest) override; - - void writeData(size_t offset, size_t length, const void* pSource, bool discardWholeBuffer) override; - - void copyData(HardwareBuffer& srcBuffer, size_t srcOffset, size_t dstOffset, size_t length, - bool discardWholeBuffer) override; - - void _updateFromShadow() override; - - GLuint getGLBufferId(void) const { return mBufferId; } - - GLenum getTarget() const { return mTarget; } - - void setGLBufferBinding(GLint binding); - GLint getGLBufferBinding(void) const { return mBindingPoint; } - void bind() { setGLBufferBinding(mBindingPoint); } - }; -} -#endif // __GL3PlusHARDWAREBUFFER_H__ diff --git a/RenderSystems/GL3Plus/include/OgreGL3PlusHardwareBufferManager.h b/RenderSystems/GL3Plus/include/OgreGL3PlusHardwareBufferManager.h deleted file mode 100644 index 9fe19d4b5d7..00000000000 --- a/RenderSystems/GL3Plus/include/OgreGL3PlusHardwareBufferManager.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#ifndef __GL3PlusHardwareBufferManager_H__ -#define __GL3PlusHardwareBufferManager_H__ - -#include "OgreGL3PlusPrerequisites.h" -#include "OgreHardwareBufferManager.h" - -namespace Ogre { - - /** Implementation of HardwareBufferManager for OpenGL. */ - class _OgreGL3PlusExport GL3PlusHardwareBufferManager : public HardwareBufferManager - { - protected: - GL3PlusRenderSystem* mRenderSystem; - - size_t mUniformBufferCount; - size_t mShaderStorageBufferCount; - - VertexDeclaration* createVertexDeclarationImpl(void) override; - public: - GL3PlusHardwareBufferManager(); - ~GL3PlusHardwareBufferManager(); - /// Creates a vertex buffer - HardwareVertexBufferSharedPtr createVertexBuffer(size_t vertexSize, - size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer = false) override; - /// Create a hardware vertex buffer - HardwareIndexBufferSharedPtr createIndexBuffer( - HardwareIndexBuffer::IndexType itype, size_t numIndexes, - HardwareBuffer::Usage usage, bool useShadowBuffer = false) override; - /// Create a uniform buffer - HardwareBufferPtr createUniformBuffer(size_t sizeBytes, HardwareBufferUsage usage = HBU_CPU_TO_GPU, - bool useShadowBuffer = false) override; - - /// Create a shader storage buffer. - HardwareBufferPtr createShaderStorageBuffer(size_t sizeBytes, - HardwareBufferUsage usage = HBU_CPU_TO_GPU, - bool useShadowBuffer = false); - - /// Create a render to vertex buffer - RenderToVertexBufferSharedPtr createRenderToVertexBuffer() override; - - size_t getUniformBufferCount() { return mUniformBufferCount; } - size_t getShaderStorageBufferCount() { return mShaderStorageBufferCount; } - - /// Utility function to get the correct GL type based on VET's - static GLenum getGLType(VertexElementType type); - - void notifyContextDestroyed(GLContext* context); - }; -} - -#endif diff --git a/RenderSystems/GL3Plus/include/OgreGL3PlusHardwareOcclusionQuery.h b/RenderSystems/GL3Plus/include/OgreGL3PlusHardwareOcclusionQuery.h deleted file mode 100644 index a5fe9f5029a..00000000000 --- a/RenderSystems/GL3Plus/include/OgreGL3PlusHardwareOcclusionQuery.h +++ /dev/null @@ -1,95 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -/* -The nVidia occlusion query extension is defined in glext.h so you don't -need anything else. You do need to look up the function, we provide a -GL3PlusSupport class to do this, which has platform implementations for -getProcAddress. Check the way that extensions like glActiveTextureARB are -initialised and used in glRenderSystem and copy what is done there. - - To do: fix so dx7 and DX9 checks and flags if HW Occlusion is supported - See the openGl dito for ideas what to do. -*/ - -#ifndef __GL3PlusHARDWAREOCCLUSIONQUERY_H__ -#define __GL3PlusHARDWAREOCCLUSIONQUERY_H__ - -#include "OgreGL3PlusPrerequisites.h" -#include "OgreHardwareOcclusionQuery.h" - - -namespace Ogre { - - -// If you use multiple rendering passes you can test only the first pass and all other passes don't have to be rendered -// if the first pass result has too few pixels visible. - -// Be sure to render all occluder first and whats out so the RenderQue don't switch places on -// the occluding objects and the tested objects because it thinks it's more effective.. - - -/** - * This is a class that is the base class of the query class for - * hardware occlusion. - * - * @author Lee Sandberg email: lee@abcmedia.se - * Updated on 13/9/2005 by Tuan Kuranes email: tuan.kuranes@free.fr - */ - -class _OgreGL3PlusExport GL3PlusHardwareOcclusionQuery : public HardwareOcclusionQuery -{ -//---------------------------------------------------------------------- -// Public methods -//-- -public: - /** - * Default object constructor - * - */ - GL3PlusHardwareOcclusionQuery(); - /** - * Object destructor - */ - ~GL3PlusHardwareOcclusionQuery(); - - //------------------------------------------------------------------ - // Occlusion query functions (see base class documentation for this) - //-- - void beginOcclusionQuery() override; - void endOcclusionQuery() override; - bool pullOcclusionQuery(unsigned int* NumOfFragments) override; - bool isStillOutstanding(void) override; - - private: - GLuint mQueryID; -}; - -} - -#endif diff --git a/RenderSystems/GL3Plus/include/OgreGL3PlusHardwarePixelBuffer.h b/RenderSystems/GL3Plus/include/OgreGL3PlusHardwarePixelBuffer.h deleted file mode 100644 index 84c6bf9b730..00000000000 --- a/RenderSystems/GL3Plus/include/OgreGL3PlusHardwarePixelBuffer.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#ifndef __GL3PlusHardwarePixelBuffer_H__ -#define __GL3PlusHardwarePixelBuffer_H__ - -#include "OgreGL3PlusPrerequisites.h" -#include "OgreGLHardwarePixelBufferCommon.h" - -namespace Ogre { - /** Renderbuffer surface. - */ - class GL3PlusRenderBuffer: public GLHardwarePixelBufferCommon - { - void blitFromMemory(const PixelBox& src, const Box& dstBox) override { OgreAssertDbg(false, "Not supported"); } - void blitToMemory(const Box& srcBox, const PixelBox& dst) override { OgreAssertDbg(false, "Not supported"); } - GL3PlusRenderSystem* mRenderSystem; - public: - GL3PlusRenderBuffer(GLenum format, uint32 width, uint32 height, GLsizei numSamples); - ~GL3PlusRenderBuffer(); - - void bindToFramebuffer(uint32 attachment, uint32 zoffset) override; - - protected: - // In case this is a render buffer - GLuint mRenderbufferID; - }; -} - -#endif diff --git a/RenderSystems/GL3Plus/include/OgreGL3PlusPixelFormat.h b/RenderSystems/GL3Plus/include/OgreGL3PlusPixelFormat.h deleted file mode 100644 index e075ceffdbd..00000000000 --- a/RenderSystems/GL3Plus/include/OgreGL3PlusPixelFormat.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#ifndef __GL3PlusPIXELFORMAT_H__ -#define __GL3PlusPIXELFORMAT_H__ - -#include "OgreGL3PlusPrerequisites.h" -#include "OgrePixelFormat.h" - -namespace Ogre { - - /** - * Class to do pixel format mapping between GL and OGRE - */ - class _OgreGL3PlusExport GL3PlusPixelUtil - { - public: - /** Takes the OGRE pixel format and returns the appropriate GL one - @return a GLenum describing the format, or 0 if there is no exactly matching - one (and conversion is needed) - */ - static GLenum getGLOriginFormat(PixelFormat format); - - /** Takes the OGRE pixel format and returns type that must be provided - to GL as data type for reading it into the GPU - @return a GLenum describing the data type, or 0 if there is no exactly matching - one (and conversion is needed) - */ - static GLenum getGLOriginDataType(PixelFormat format); - - /** Takes the OGRE pixel format and returns the type that must be provided - to GL as internal format. GL_NONE if no match exists. - @param format The pixel format - @param hwGamma Whether a hardware gamma-corrected version is requested - */ - static GLenum getGLInternalFormat(PixelFormat format, bool hwGamma = false); - - /** Takes the OGRE pixel format and returns the type that must be provided - to GL as internal format for image load/store. GL_NONE if no match exists. - @param format The pixel format - */ - static GLenum getGLImageInternalFormat(PixelFormat format); - - /** Takes the OGRE pixel format and returns the type that must be provided - to GL as internal format for image load/store. If no match exists, - returns the closest match. - @param format The pixel format - */ - static GLenum getClosestGLImageInternalFormat(PixelFormat format); - - /** Function to get the closest matching OGRE format to an internal GL format. To be - precise, the format will be chosen that is most efficient to transfer to the card - without losing precision. - @remarks It is valid for this function to always return PF_A8R8G8B8. - */ - static PixelFormat getClosestOGREFormat(GLenum format); - }; -} - -#endif diff --git a/RenderSystems/GL3Plus/include/OgreGL3PlusPlugin.h b/RenderSystems/GL3Plus/include/OgreGL3PlusPlugin.h deleted file mode 100644 index 0acffa968f5..00000000000 --- a/RenderSystems/GL3Plus/include/OgreGL3PlusPlugin.h +++ /dev/null @@ -1,64 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GL3PlusPlugin_H__ -#define __GL3PlusPlugin_H__ - -#include "OgrePlugin.h" -#include "OgreGL3PlusExports.h" - -namespace Ogre -{ - class GL3PlusRenderSystem; - - /** Plugin instance for GL3Plus Manager */ - class _OgreGL3PlusExport GL3PlusPlugin : public Plugin - { - public: - GL3PlusPlugin(); - - - /// @copydoc Plugin::getName - const String& getName() const override; - - /// @copydoc Plugin::install - void install() override; - - /// @copydoc Plugin::initialise - void initialise() override; - - /// @copydoc Plugin::shutdown - void shutdown() override; - - /// @copydoc Plugin::uninstall - void uninstall() override; - protected: - GL3PlusRenderSystem* mRenderSystem; - }; -} - -#endif diff --git a/RenderSystems/GL3Plus/include/OgreGL3PlusPrerequisites.h b/RenderSystems/GL3Plus/include/OgreGL3PlusPrerequisites.h deleted file mode 100644 index 9cfa578385c..00000000000 --- a/RenderSystems/GL3Plus/include/OgreGL3PlusPrerequisites.h +++ /dev/null @@ -1,102 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GL3PlusPrerequisites_H__ -#define __GL3PlusPrerequisites_H__ - -#include "OgrePrerequisites.h" - -namespace Ogre { - // Forward declarations - class GLContext; - class GLRTTManager; - typedef GLContext GL3PlusContext; - typedef GLRTTManager GL3PlusRTTManager; - class GL3PlusRenderSystem; - class GL3PlusStateCacheManager; - class GLNativeSupport; - class GL3PlusTexture; - class GL3PlusTextureManager; - class GL3PlusFBOManager; - class GL3PlusHardwarePixelBuffer; - class GL3PlusRenderBuffer; - - class GLSLShader; - - typedef shared_ptr GLSLShaderPtr; - typedef shared_ptr GL3PlusTexturePtr; -} - -#if (OGRE_PLATFORM == OGRE_PLATFORM_WIN32) -# ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN 1 -# endif -# ifndef NOMINMAX -# define NOMINMAX // required to stop windows.h messing up std::min -# endif -#endif - -#include - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -# define __PRETTY_FUNCTION__ __FUNCTION__ -#endif - -#define ENABLE_GL_CHECK 0 - -#if ENABLE_GL_CHECK -#include "OgreLogManager.h" -#define OGRE_CHECK_GL_ERROR(glFunc) \ -{ \ - glFunc; \ - int e = glGetError(); \ - if (e != 0) \ - { \ - const char * errorString = ""; \ - switch(e) \ - { \ - case GL_INVALID_ENUM: errorString = "GL_INVALID_ENUM"; break; \ - case GL_INVALID_VALUE: errorString = "GL_INVALID_VALUE"; break; \ - case GL_INVALID_OPERATION: errorString = "GL_INVALID_OPERATION"; break; \ - case GL_INVALID_FRAMEBUFFER_OPERATION: errorString = "GL_INVALID_FRAMEBUFFER_OPERATION"; break; \ - case GL_OUT_OF_MEMORY: errorString = "GL_OUT_OF_MEMORY"; break; \ - default: break; \ - } \ - String funcname = #glFunc; \ - funcname = funcname.substr(0, funcname.find('(')); \ - LogManager::getSingleton().logError(StringUtil::format("%s failed with %s in %s at %s(%d)", \ - funcname.c_str(), errorString, __FUNCTION__, \ - __FILE__, __LINE__)); \ - } \ -} -#else -# define OGRE_CHECK_GL_ERROR(glFunc) { glFunc; } -#endif - -#include "OgreGL3PlusExports.h" - -#endif //#ifndef __GL3PlusPrerequisites_H__ diff --git a/RenderSystems/GL3Plus/include/OgreGL3PlusRenderSystem.h b/RenderSystems/GL3Plus/include/OgreGL3PlusRenderSystem.h deleted file mode 100644 index d2957747acf..00000000000 --- a/RenderSystems/GL3Plus/include/OgreGL3PlusRenderSystem.h +++ /dev/null @@ -1,248 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#ifndef __GL3PlusRenderSystem_H__ -#define __GL3PlusRenderSystem_H__ - -#include "OgreGL3PlusPrerequisites.h" - -#include "OgreMaterialManager.h" -#include "OgreRenderWindow.h" -#include "OgreGLRenderSystemCommon.h" -#include "OgreGL3PlusStateCacheManager.h" - -#include - -namespace Ogre { - /** \addtogroup RenderSystems RenderSystems - * @{ - */ - /** \defgroup GL3Plus GL3Plus - * Implementation of GL 3 as a rendering system. - * @{ - */ - class GLSLShaderManager; - class GLSLProgram; - class GLSLProgramManager; - class HardwareBufferManager; - - /** - Implementation of GL 3 as a rendering system. - */ - class _OgreGL3PlusExport GL3PlusRenderSystem : public GLRenderSystemCommon - { - friend class GL3PlusSampler; - private: - typedef std::unordered_map BindBufferMap; - - /// Last min & mip filtering options, so we can combine them - FilterOptions mMinFilter; - FilterOptions mMipFilter; - - /// Holds texture type settings for every stage - GLenum mTextureTypes[OGRE_MAX_TEXTURE_LAYERS]; - - GLint mLargestSupportedAnisotropy; - - /// Store last depth write state - bool mDepthWrite; - - /// Store last stencil mask state - uint32 mStencilWriteMask; - - // statecaches are per context - GL3PlusStateCacheManager* mStateCacheManager; - - GLSLProgramManager* mProgramManager; - HighLevelGpuProgramFactory* mGLSLShaderFactory; - HighLevelGpuProgramFactory* mSPIRVShaderFactory; - HardwareBufferManager* mHardwareBufferManager; - - /** These variables are used for caching RenderSystem state. - They are cached because OpenGL state changes can be quite expensive, - which is especially important on mobile or embedded systems. - */ - GLenum mActiveTextureUnit; - BindBufferMap mActiveBufferMap; - - /// Check if the GL system has already been initialised - bool mGLInitialised; - - bool mSeparateShaderObjectsEnabled; - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - /// @copydoc RenderSystem::setDrawBuffer - virtual bool setDrawBuffer(ColourBufferType colourBuffer); -#endif - - std::array mCurrentShader; - - GLenum getBlendMode(SceneBlendFactor ogreBlend) const; - - void bindVertexElementToGpu(const VertexElement& elem, - const HardwareVertexBufferSharedPtr& vertexBuffer, - const size_t vertexStart) override; - /** Initialises GL extensions, must be done AFTER the GL context has been - established. - */ - void initialiseExtensions(); - public: - // Default constructor / destructor - GL3PlusRenderSystem(); - ~GL3PlusRenderSystem(); - - // ---------------------------------- - // Overridden RenderSystem functions - // ---------------------------------- - - const String& getName(void) const override; - - void _initialise() override; - - void initConfigOptions() override; - - RenderSystemCapabilities* createRenderSystemCapabilities() const override; - - void initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary) override; - - void shutdown(void) override; - - /// @copydoc RenderSystem::_createRenderWindow - RenderWindow* _createRenderWindow(const String &name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams = 0) override; - - /// @copydoc RenderSystem::_createDepthBufferFor - DepthBuffer* _createDepthBufferFor( RenderTarget *renderTarget ) override; - - /// @copydoc RenderSystem::createMultiRenderTarget - MultiRenderTarget * createMultiRenderTarget(const String & name) override; - - - void destroyRenderWindow(const String& name) override; - - // ----------------------------- - // Low-level overridden members - // ----------------------------- - void _setTexture(size_t unit, bool enabled, const TexturePtr &tex) override; - - void _setSampler(size_t unit, Sampler& sampler) override; - - void _setLineWidth(float width) override; - - void _setViewport(Viewport *vp) override; - - void _endFrame(void) override; - - void _setCullingMode(CullingMode mode) override; - - void _setDepthClamp(bool enable) override; - - void _setDepthBufferParams(bool depthTest = true, bool depthWrite = true, CompareFunction depthFunction = CMPF_LESS_EQUAL) override; - - void _setDepthBias(float constantBias, float slopeScaleBias) override; - - void setColourBlendState(const ColourBlendState& state) override; - - void _setPolygonMode(PolygonMode level) override; - - void setStencilState(const StencilState& state) override; - - void _dispatchCompute(const Vector3i& workgroupDim) override; - - void _render(const RenderOperation& op) override; - - void _getDepthStencilFormatFor(PixelFormat internalColourFormat, - uint32* depthFormat, - uint32* stencilFormat) override; - - void setScissorTest(bool enabled, const Rect& rect = Rect()) override; - - void clearFrameBuffer(unsigned int buffers, - const ColourValue& colour = ColourValue::Black, - float depth = 1.0f, unsigned short stencil = 0) override; - HardwareOcclusionQuery* createHardwareOcclusionQuery(void) override; - - // ---------------------------------- - // GL3PlusRenderSystem specific members - // ---------------------------------- - GL3PlusStateCacheManager * _getStateCacheManager() { return mStateCacheManager; } - - /** Create VAO on current context */ - uint32 _createVao() override; - /** Bind VAO, context should be equal to current context, as VAOs are not shared */ - void _bindVao(GLContext* context, uint32 vao) override; - /** Destroy VAO immediately or defer if it was created on other context */ - void _destroyVao(GLContext* context, uint32 vao) override; - /** Destroy FBO immediately or defer if it was created on other context */ - void _destroyFbo(GLContext* context, uint32 fbo) override; - - /** Unregister a render target->context mapping. If the context of target - is the current context, change the context to the main context so it - can be destroyed safely. - - @note This is automatically called by the destructor of - GL3PlusContext. - */ - void _unregisterContext(GL3PlusContext *context) override; - /** Switch GL context, dealing with involved internal cached states too - */ - void _switchContext(GL3PlusContext *context); - void _oneTimeContextInitialization() override; - void initialiseContext(RenderWindow* primary); - /** - * Set current render target to target, enabling its GL context if needed - */ - void _setRenderTarget(RenderTarget *target) override; - - static GLint convertCompareFunction(CompareFunction func); - static GLint convertStencilOp(StencilOperation op, bool invert = false); - - void bindGpuProgram(GpuProgram* prg) override; - void unbindGpuProgram(GpuProgramType gptype) override; - void bindGpuProgramParameters(GpuProgramType gptype, const GpuProgramParametersPtr& params, uint16 mask) override; - - /// @copydoc RenderSystem::_setAlphaRejectSettings - void _setAlphaRejectSettings( CompareFunction func, unsigned char value, bool alphaToCoverage ) override; - - /// @copydoc RenderSystem::beginProfileEvent - void beginProfileEvent( const String &eventName ) override; - - /// @copydoc RenderSystem::endProfileEvent - void endProfileEvent( void ) override; - - /// @copydoc RenderSystem::markProfileEvent - void markProfileEvent( const String &eventName ) override; - - /** @copydoc RenderTarget::copyContentsToMemory */ - void _copyContentsToMemory(Viewport* vp, const Box& src, const PixelBox &dst, RenderWindow::FrameBuffer buffer) override; - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/RenderSystems/GL3Plus/include/OgreGL3PlusRenderToVertexBuffer.h b/RenderSystems/GL3Plus/include/OgreGL3PlusRenderToVertexBuffer.h deleted file mode 100644 index 6751f36c5e7..00000000000 --- a/RenderSystems/GL3Plus/include/OgreGL3PlusRenderToVertexBuffer.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#ifndef __GL3PlusRenderToVertexBuffer_H__ -#define __GL3PlusRenderToVertexBuffer_H__ - -#include "OgreGLRenderToVertexBufferCommon.h" -#include "OgreGL3PlusPrerequisites.h" - -namespace Ogre { - class GL3PlusRenderToVertexBuffer : public GLRenderToVertexBufferCommon - { - public: - GL3PlusRenderToVertexBuffer(); - virtual ~GL3PlusRenderToVertexBuffer(); - - /** Update the contents of this vertex buffer by rendering - */ - void update(SceneManager* sceneMgr) override; - protected: - /* size_t mSourceBufferIndex; */ - std::vector feedbackVariableNames; - size_t mTargetBufferIndex; - GLuint mPrimitivesDrawnQuery; - bool mFeedbackActive; - bool mFirstUpdate; - // GL4+ - // GLuint mFeedbackObject; - - void bindVerticesOutput(Pass* pass); - }; -} - -#endif diff --git a/RenderSystems/GL3Plus/include/OgreGL3PlusStateCacheManager.h b/RenderSystems/GL3Plus/include/OgreGL3PlusStateCacheManager.h deleted file mode 100644 index 28e956cd4bd..00000000000 --- a/RenderSystems/GL3Plus/include/OgreGL3PlusStateCacheManager.h +++ /dev/null @@ -1,208 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GL3PlusStateCacheManager_H__ -#define __GL3PlusStateCacheManager_H__ - -#include "OgreGL3PlusPrerequisites.h" -#include "OgreGLStateCacheManagerCommon.h" -#include "OgreStdHeaders.h" - -namespace Ogre -{ - class _OgreGL3PlusExport GL3PlusStateCacheManager : public GLStateCacheManagerCommon - { - protected: - /* These variables are used for caching OpenGL state. - They are cached because state changes can be quite expensive, - which is especially important on mobile or embedded systems. - */ - - /// Stores the currently bound draw frame buffer value - GLuint mActiveDrawFrameBuffer; - /// Stores the currently bound read frame buffer value - GLuint mActiveReadFrameBuffer; - /// Stores the currently bound vertex array object - GLuint mActiveVertexArray; - /// Stores the current polygon rendering mode - GLenum mPolygonMode; - /// Stores the last bound texture id - GLuint mLastBoundTexID; - /// Stores the currently bound separable program pipeline - GLuint mActiveProgramPipeline; - public: - GL3PlusStateCacheManager(void); - - /// See GL3PlusStateCacheManager.initializeCache. - void initializeCache(); - - /** Clears all cached values - */ - void clearCache(); - - - /** Bind an OpenGL frame buffer. - @param target The buffer target. - @param buffer The buffer ID. - */ - void bindGLFrameBuffer(GLenum target,GLuint buffer); - - /** Bind an OpenGL frame buffer. - @param buffer The buffer ID. - */ - void bindGLRenderBuffer(GLuint buffer); - - /** Bind an OpenGL buffer of any type. - @param target The buffer target. - @param buffer The buffer ID. - */ - void bindGLBuffer(GLenum target, GLuint buffer); - - /** Delete an OpenGL frame buffer. - @param target The buffer target. - @param buffer The buffer ID. - */ - void deleteGLFrameBuffer(GLenum target, GLuint buffer); - - /** Delete an OpenGL render buffer. - @param buffer The buffer ID. - */ - void deleteGLRenderBuffer(GLuint buffer); - /** Delete an OpenGL buffer of any type. - @param target The buffer target. - @param buffer The buffer ID. - */ - void deleteGLBuffer(GLenum target, GLuint buffer); - - /** Bind an OpenGL Vertex array object. - @param vao The vertex array object ID. - */ - void bindGLVertexArray(GLuint vao); - - void deleteGLVertexArray(GLuint vao); - - /** Bind an OpenGL texture of any type. - @param target The texture target. - @param texture The texture ID. - */ - void bindGLTexture(GLenum target, GLuint texture); - - /** Invalidates the state associated with a particular texture ID. - @param texture The texture ID. - */ - void invalidateStateForTexture(GLuint texture); - - /** Sets an integer parameter value per texture target. - @param target The texture target. - @param pname The parameter name. - @param param The parameter value. - */ - void setTexParameteri(GLenum target, GLenum pname, GLint param); - - /** Activate an OpenGL texture unit. - @param unit The texture unit to activate. - @return Whether or not the texture unit was successfully activated. - */ - bool activateGLTextureUnit(size_t unit); - - /// Set the blend equation for RGB and alpha separately. - void setBlendEquation(GLenum eqRGB, GLenum eqA); - - /// Set the blend function for RGB and alpha separately. - void setBlendFunc(GLenum source, GLenum dest, GLenum sourceA, GLenum destA); - - /** Sets the current depth mask setting. - @param mask The depth mask to use. - */ - void setDepthMask(GLboolean mask); - - /** Gets the current depth test function. - @return The current depth test function. - */ - GLenum getDepthFunc(void) const { return mDepthFunc; } - - /** Sets the current depth test function. - @param func The depth test function to use. - */ - void setDepthFunc(GLenum func); - - /** Gets the clear depth in the range from [0..1]. - @return The current clearing depth. - */ - GLclampf getClearDepth(void) const { return mClearDepth; } - - /** Sets the clear depth in the range from [0..1]. - @param depth The clear depth to use. - */ - void setClearDepth(GLclampf depth); - - /** Sets the color to clear to. - @param red The red component. - @param green The green component. - @param blue The blue component. - @param alpha The alpha component. - */ - void setClearColour(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); - - /** Sets the current colour mask. - @param red The red component. - @param green The green component. - @param blue The blue component. - @param alpha The alpha component. - */ - void setColourMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); - - /** Sets the stencil mask. - @param mask The stencil mask to use - */ - void setStencilMask(GLuint mask); - - /** Enables a piece of OpenGL functionality. - */ - void setEnabled(GLenum flag, bool enabled); - - /** Sets the current polygon rendering mode. - @param mode The polygon mode to use. - */ - void setPolygonMode(GLenum mode); - - /** Sets the face culling setting. - @param face The face culling mode to use. - */ - void setCullFace(GLenum face); - - /** Bind an OpenGL separable program pipeline - @param handle The handle to the program pipeline - */ - void bindGLProgramPipeline(GLuint handle); - - void setViewport(const Rect& r); - }; -} - -#endif diff --git a/RenderSystems/GL3Plus/include/OgreGL3PlusTexture.h b/RenderSystems/GL3Plus/include/OgreGL3PlusTexture.h deleted file mode 100644 index 02b7cda713e..00000000000 --- a/RenderSystems/GL3Plus/include/OgreGL3PlusTexture.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#ifndef __GL3PlusTexture_H__ -#define __GL3PlusTexture_H__ - -#include "OgreGL3PlusPrerequisites.h" -#include "OgrePlatform.h" -#include "OgreRenderTexture.h" -#include "OgreGLTextureCommon.h" -#include "OgreHardwarePixelBuffer.h" - -namespace Ogre { - class _OgreGL3PlusExport GL3PlusTexture : public GLTextureCommon - { - public: - // Constructor - GL3PlusTexture(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - GL3PlusRenderSystem* renderSystem); - - virtual ~GL3PlusTexture(); - - // Takes the OGRE texture type (1d/2d/3d/cube) and returns the appropriate GL one - GLenum getGL3PlusTextureTarget(void) const; - - void createShaderAccessPoint(uint bindPoint, TextureAccess access = TA_READ_WRITE, - int mipmapLevel = 0, int textureArrayIndex = 0, - PixelFormat format = PF_UNKNOWN) override; - protected: - /// @copydoc Texture::createInternalResourcesImpl - void createInternalResourcesImpl(void) override; - /// @copydoc Resource::freeInternalResourcesImpl - void freeInternalResourcesImpl(void) override; - - /** internal method, create GL3PlusHardwarePixelBuffers for every face and - mipmap level. This method must be called after the GL texture object was created, - the number of mipmaps was set (GL_TEXTURE_MAX_LEVEL) and glTexImageXD was called to - actually allocate the buffer - */ - void _createSurfaceList(); - - private: - GL3PlusRenderSystem* mRenderSystem; - }; -} - -#endif diff --git a/RenderSystems/GL3Plus/include/OgreGL3PlusTextureBuffer.h b/RenderSystems/GL3Plus/include/OgreGL3PlusTextureBuffer.h deleted file mode 100644 index 3709cc73495..00000000000 --- a/RenderSystems/GL3Plus/include/OgreGL3PlusTextureBuffer.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#ifndef __GL3PlusTextureBuffer_H__ -#define __GL3PlusTextureBuffer_H__ - -#include "OgreGL3PlusHardwarePixelBuffer.h" - -namespace Ogre { - - /** Texture surface. - */ - class _OgreGL3PlusExport GL3PlusTextureBuffer: public GLHardwarePixelBufferCommon - { - GL3PlusRenderSystem* mRenderSystem; - public: - /** Texture constructor */ - GL3PlusTextureBuffer(GL3PlusTexture* parent, GLint face, GLint level, uint32 width, - uint32 height, uint32 depth); - ~GL3PlusTextureBuffer(); - - void bindToFramebuffer(uint32 attachment, uint32 zoffset) override; - - /// Upload a box of pixels to this buffer on the card. - void upload(const PixelBox &data, const Box &dest) override; - - /// Download a box of pixels from the card. - void download(const PixelBox &data) override; - - /// Hardware implementation of blitFromMemory. - void blitFromMemory(const PixelBox &src_orig, const Box &dstBox) override; - - /// Copy from framebuffer. - void copyFromFramebuffer(uint32 zoffset); - - /// @copydoc HardwarePixelBuffer::blit - void blit(const HardwarePixelBufferSharedPtr &src, - const Box &srcBox, const Box &dstBox) override; - - void blitToMemory(const Box &srcBox, const PixelBox &dst) override; - protected: - // Blitting implementation - void blitFromTexture(GL3PlusTextureBuffer* src, const Box& srcBox, const Box& dstBox); - void _blitFromMemory(const PixelBox& src, const Box& dst); - // In case this is a texture level. - GLenum mTarget; - // Same as mTarget in case of GL_TEXTURE_xD, but cubemap face - // for cubemaps. - GLenum mFaceTarget; - GLuint mTextureID; - GLint mLevel; - - void _bindToFramebuffer(GLenum attachment, uint32 zoffset, GLenum which); - }; - -} - -#endif diff --git a/RenderSystems/GL3Plus/include/OgreGL3PlusTextureManager.h b/RenderSystems/GL3Plus/include/OgreGL3PlusTextureManager.h deleted file mode 100644 index 323f77e6ecc..00000000000 --- a/RenderSystems/GL3Plus/include/OgreGL3PlusTextureManager.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#ifndef __GL3PlusTextureManager_H__ -#define __GL3PlusTextureManager_H__ - -#include "OgreGL3PlusPrerequisites.h" -#include "OgreTextureManager.h" -#include "OgreGL3PlusTexture.h" - -#include - -namespace Ogre { - typedef std::vector GL3PlusTexturePtrList; - typedef std::vector TexturePtrList; - - class _OgreGL3PlusExport GL3PlusSampler : public Sampler - { - public: - GL3PlusSampler(GL3PlusRenderSystem* rs); - ~GL3PlusSampler(); - void bind(uint32 unit); - static GLint getCombinedMinMipFilter(FilterOptions min, FilterOptions mip); - static GLint getTextureAddressingMode(TextureAddressingMode tam); - private: - uint32 mSamplerId; - }; - - /** GL3Plus-specific implementation of a TextureManager */ - class _OgreGL3PlusExport GL3PlusTextureManager : public TextureManager - { - public: - GL3PlusTextureManager(GL3PlusRenderSystem* renderSystem); - virtual ~GL3PlusTextureManager(); - - /// @copydoc TextureManager::getNativeFormat - PixelFormat getNativeFormat(TextureType ttype, PixelFormat format, int usage) override; - - // void bindImages(); - - /* TexturePtr createManual(const String & name, const String& group, */ - /* TextureType texType, uint width, uint height, uint depth, int numMipmaps, */ - /* PixelFormat format, int usage, ManualResourceLoader* loader, bool hwGamma, */ - /* uint fsaa, const String& fsaaHint); */ - - protected: - /// @copydoc ResourceManager::createImpl - Resource* createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams) override; - - GL3PlusRenderSystem* mRenderSystem; - - SamplerPtr _createSamplerImpl() override; - - private: - /// Register a texture as an image texture used in image load/store. - // void registerImage(TexturePtr texture); - - /// Collection of textures associated with image load/store variables. - // TexturePtrList mImages; - }; -} - -#endif diff --git a/RenderSystems/GL3Plus/include/OgreSPIRVShaderFactory.h b/RenderSystems/GL3Plus/include/OgreSPIRVShaderFactory.h deleted file mode 100644 index ddd336ed4b5..00000000000 --- a/RenderSystems/GL3Plus/include/OgreSPIRVShaderFactory.h +++ /dev/null @@ -1,65 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __SPIRVGpuProgramManager_H__ -#define __SPIRVGpuProgramManager_H__ - -#include "OgreGL3PlusPrerequisites.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreGLSLShader.h" - -namespace Ogre { - -class _OgreGL3PlusExport SPIRVShader : public GLSLShader -{ -public: - SPIRVShader(ResourceManager* creator, const String& name, ResourceHandle handle, const String& group, bool isManual, - ManualResourceLoader* loader); - virtual ~SPIRVShader(); - - const String& getLanguage(void) const override; -protected: - void compileSource() override; -}; - -class _OgreGL3PlusExport SPIRVShaderFactory: public HighLevelGpuProgramFactory -{ -public: - SPIRVShaderFactory(); - ~SPIRVShaderFactory(); - /// Get the name of the language this factory creates shaders for. - const String& getLanguage(void) const override; - /// Create an instance of GLSLProgram. - GpuProgram* create(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) override; -}; - -} //namespace Ogre - -#endif //__GLGpuProgramManager_H__ diff --git a/RenderSystems/GL3Plus/src/GLSL/include/OgreGLSLExtSupport.h b/RenderSystems/GL3Plus/src/GLSL/include/OgreGLSLExtSupport.h deleted file mode 100644 index affb6778631..00000000000 --- a/RenderSystems/GL3Plus/src/GLSL/include/OgreGLSLExtSupport.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - - - -#ifndef __GLSLExtSupport_H__ -#define __GLSLExtSupport_H__ - -#include "OgreGL3PlusPrerequisites.h" - -// -// OpenGL Shading Language (GLSL) entry points -// -namespace Ogre -{ - /** If there is a message in GL info log then post it in the Ogre Log - @param msg The info log message string is appended to this string - @param obj The GL object that is used to retrieve the info log - */ - String logObjectInfo(const String& msg, GLuint obj); - - /// just return the info without logging it - String getObjectInfo(GLuint obj); - -} // namespace Ogre - -#endif // __GLSLExtSupport_H__ diff --git a/RenderSystems/GL3Plus/src/GLSL/include/OgreGLSLMonolithicProgram.h b/RenderSystems/GL3Plus/src/GLSL/include/OgreGLSLMonolithicProgram.h deleted file mode 100644 index dfb3dd76b5c..00000000000 --- a/RenderSystems/GL3Plus/src/GLSL/include/OgreGLSLMonolithicProgram.h +++ /dev/null @@ -1,80 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#ifndef __GLSLMonolithicProgram_H__ -#define __GLSLMonolithicProgram_H__ - -#include "OgreGL3PlusPrerequisites.h" -#include "OgreGpuProgram.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreGL3PlusHardwareBuffer.h" -#include "OgreGLSLProgram.h" - -namespace Ogre { - - class GLSLShader; - - /** Model of OpenGL program object created using the glLinkProgram - method of linking. - - Linking using glLinkProgram is supported by OpenGL 2.0 and up, - but does not allow hot-swapping shaders without recompiling - the program object like GLSLSeparableProgram can. Hence the name - 'monolithic'. - */ - class _OgreGL3PlusExport GLSLMonolithicProgram : public GLSLProgram - { - protected: - /// Compiles and links the vertex and fragment programs - void compileAndLink(void) override; - - void buildGLUniformReferences(void); - - public: - /// Constructor should only be used by GLSLMonolithicProgramManager - explicit GLSLMonolithicProgram(const GLShaderList& shaders); - ~GLSLMonolithicProgram(void); - - /** Makes a program object active by making sure it is linked - and then putting it in use. - */ - void activate(void) override; - - /** Updates program object uniforms using data from - GpuProgramParameters. normally called by - GLSLShader::bindParameters() just before rendering - occurs. - */ - void updateUniforms(GpuProgramParametersSharedPtr params, uint16 mask, GpuProgramType fromProgType) override; - - void updateAtomicCounters(const GpuProgramParametersSharedPtr& params, uint16 mask, - GpuProgramType fromProgType) {} - }; - -} - -#endif // __GLSLMonolithicProgram_H__ diff --git a/RenderSystems/GL3Plus/src/GLSL/include/OgreGLSLProgram.h b/RenderSystems/GL3Plus/src/GLSL/include/OgreGLSLProgram.h deleted file mode 100644 index 5f2f10c479a..00000000000 --- a/RenderSystems/GL3Plus/src/GLSL/include/OgreGLSLProgram.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#ifndef __GLSLProgram_H__ -#define __GLSLProgram_H__ - -#include "OgreGL3PlusPrerequisites.h" -#include "OgreGpuProgram.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreGL3PlusHardwareBuffer.h" -#include "OgreGLSLProgramCommon.h" -#include "OgreGLSLShader.h" - -namespace Ogre { - - /** C++ encapsulation of GLSL program object. - */ - class _OgreGL3PlusExport GLSLProgram : public GLSLProgramCommon - { - public: - static void bindFixedAttributes(GLuint program); - - /// Get the the binary data of a program from the microcode cache - static bool getMicrocodeFromCache(uint32 id, GLuint programHandle); - - /// add the microcode to the cache - static void writeMicrocodeToCache(uint32 id, GLuint programHandle); - - void setTransformFeedbackVaryings(const std::vector& nameStrings); - protected: - /// Constructor should only be used by GLSLMonolithicProgramManager and GLSLSeparableProgramManager - GLSLProgram(const GLShaderList& shaders); - }; - - -} - -#endif // __GLSLProgram_H__ diff --git a/RenderSystems/GL3Plus/src/GLSL/include/OgreGLSLProgramManager.h b/RenderSystems/GL3Plus/src/GLSL/include/OgreGLSLProgramManager.h deleted file mode 100644 index 8b9b623829b..00000000000 --- a/RenderSystems/GL3Plus/src/GLSL/include/OgreGLSLProgramManager.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#ifndef __GLSLProgramManager_H__ -#define __GLSLProgramManager_H__ - -#include "OgreGL3PlusPrerequisites.h" -#include "OgreGLSLProgramManagerCommon.h" -#include "OgreGLSLShader.h" -#include "OgreGLSLProgram.h" -#include "OgreGLSLExtSupport.h" - -namespace Ogre { - - /** Ogre assumes that there are separate vertex and fragment - programs to deal with but GLSL has one program object that - represents the active vertex and fragment shader objects - during a rendering state. GLSL Vertex and fragment shader - objects are compiled separately and then attached to a program - object and then the program object is linked. Since Ogre can - only handle one vertex program and one fragment program being - active in a pass, the GLSL Link Program Manager does the same. - The GLSL Link program manager acts as a state machine and - activates a program object based on the active vertex and - fragment program. Previously created program objects are - stored along with a unique key in a hash_map for quick - retrieval the next time the program object is required. - */ - class _OgreGL3PlusExport GLSLProgramManager : public GLSLProgramManagerCommon, public Singleton - { - protected: - GL3PlusRenderSystem* mRenderSystem; - - /** Find the data source definition for a given uniform name - and reference. Return true if found and pair the reference - with its data source. */ - static bool findUniformDataSource( - const String& paramName, - const GpuConstantDefinitionMap* (&constantDefs)[6], - GLUniformReference& refToUpdate); - public: - - GLSLProgramManager(GL3PlusRenderSystem* renderSystem); - ~GLSLProgramManager(); - - /** Get the program object that links the two active shader - objects together if a program object was not already - created and linked a new one is created and linked - @note this method does NOT link seperable programs. - */ - GLSLProgram* getActiveProgram(void); - - /** Populate a list of uniforms based on an OpenGL program object. - */ - void extractUniformsFromProgram( - GLuint programObject, - const GpuConstantDefinitionMap* (&constantDefs)[6], - GLUniformReferenceList& uniformList); - - GL3PlusStateCacheManager* getStateCacheManager(); - - static GLSLProgramManager& getSingleton(void); - static GLSLProgramManager* getSingletonPtr(void); - }; - -} - -#endif // __GLSLProgramManager_H__ diff --git a/RenderSystems/GL3Plus/src/GLSL/include/OgreGLSLSeparableProgram.h b/RenderSystems/GL3Plus/src/GLSL/include/OgreGLSLSeparableProgram.h deleted file mode 100644 index 65fec8d22de..00000000000 --- a/RenderSystems/GL3Plus/src/GLSL/include/OgreGLSLSeparableProgram.h +++ /dev/null @@ -1,105 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#ifndef __GLSLSeparableProgram_H__ -#define __GLSLSeparableProgram_H__ - -#include "OgreGL3PlusPrerequisites.h" -#include "OgreGLSLProgram.h" - -namespace Ogre -{ - //TODO Need to check that the shaders are being reused rather than - // destroyed and then recompiled. - - /** Specialisation of GLSLProgram to provide support for separable - programs via the OpenGL program pipeline. - - Separable programs consist of shader objects which have been - individually linked. This allows for invidual shaders in a - program pipeline to be swapped without recompiling the program - object, as would be necessary with monolithic programs. This - is especially useful in the common case of only entities which - change only a few of the shaders in the pipeline while leaving - the rest the same. - - - GLSL has no target assembler or entry point specification like - DirectX 9 HLSL. Vertex and Fragment shaders only have one - entry point called "main". When a shader is compiled, - microcode is generated but can not be accessed by the - application. - - GLSL also does not provide assembler low level output after - compiling. The GL Render system assumes that the Gpu program - is a GL Gpu program so GLSLSeparableProgram will create a - GL3PlusShader for the low level implementation. The GLProgram - class will create a shader and program object and compile the - source but will not create a pipeline object. It's up to - GLGpuProgram class to request a program pipeline object to - link the program object to. - - @note - GLSL supportsn multiple modular shader objects that can be - attached to one program object to form a single shader. This - is supported through the "attach" material script command. - All the modules to be attached are listed on the same line as - the attach command separated by white space. - */ - class _OgreGL3PlusExport GLSLSeparableProgram : public GLSLProgram - { - public: - /// Constructor should only be used by GLSLSeparableProgramManager. - explicit GLSLSeparableProgram(const GLShaderList& shaders); - ~GLSLSeparableProgram(); - - /** Updates program pipeline object uniforms using named and - indexed parameter data from GpuProgramParameters. - normally called by GLSLShader::bindProgramParameters() - just before rendering occurs. - */ - void updateUniforms(GpuProgramParametersSharedPtr params, - uint16 mask, GpuProgramType fromProgType) override; - - /** Makes a program pipeline object active by making sure it - is linked and then putting it in use. - */ - void activate(void) override; - - protected: - /// GL handle for pipeline object. - GLuint mGLProgramPipelineHandle; - - /// Compiles and links the separate programs. - void compileAndLink(void) override; - - void getMicrocodeFromCache(void); - void getIndividualProgramMicrocodeFromCache(GLSLShader* program); - }; -} - -#endif diff --git a/RenderSystems/GL3Plus/src/GLSL/include/OgreGLSLShader.h b/RenderSystems/GL3Plus/src/GLSL/include/OgreGLSLShader.h deleted file mode 100644 index 993b7ee7a75..00000000000 --- a/RenderSystems/GL3Plus/src/GLSL/include/OgreGLSLShader.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#ifndef __GLSLShader_H__ -#define __GLSLShader_H__ - -#include "OgreGL3PlusPrerequisites.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreGLSLShaderCommon.h" -#include "OgreRenderOperation.h" - -namespace Ogre { - - class GLUniformCache; - class GLSLShader : public GLSLShaderCommon - { - public: - GLSLShader(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader); - ~GLSLShader(); - - void attachToProgramObject(const GLuint programObject) override; - void detachFromProgramObject(const GLuint programObject) override; - - bool linkSeparable() override; - - void setSamplerBinding(bool enable) { mHasSamplerBinding = enable; } - bool getSamplerBinding() const { return mHasSamplerBinding; } - - const HardwareBufferPtr& getDefaultBuffer() const { return mDefaultBuffer; } - - /// Overridden from GpuProgram - const String& getLanguage(void) const override; - protected: - void loadFromSource() override; - /// Internal unload implementation, must be implemented by subclasses - void unloadHighLevelImpl(void) override; - /// Populate the passed parameters with name->index map, must be overridden - void buildConstantDefinitions() override; - /// Add boiler plate code and preprocessor extras, then - /// submit shader source to OpenGL. - virtual void compileSource(); - - /// @param block uniform block to consider. -1 for non-UBO uniforms - void extractUniforms(int block = -1) const; - void extractBufferBlocks(GLenum type) const; - - mutable HardwareBufferPtr mDefaultBuffer; - bool mHasSamplerBinding; - }; - - /** Factory class for GLSL shaders. - */ - class GLSLShaderFactory : public HighLevelGpuProgramFactory - { - public: - /// Get the name of the language this factory creates shaders for. - const String& getLanguage(void) const override; - /// Create an instance of GLSLProgram. - GpuProgram* create(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) override; - }; -} - -#endif // __GLSLShader_H__ diff --git a/RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLExtSupport.cpp b/RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLExtSupport.cpp deleted file mode 100644 index 9f358a0dc03..00000000000 --- a/RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLExtSupport.cpp +++ /dev/null @@ -1,120 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGLSLExtSupport.h" -#include "OgreLogManager.h" -#include "OgreRoot.h" - -namespace Ogre { - - String logObjectInfo(const String& msg, GLuint obj) - { - String logMessage = getObjectInfo(obj); - - if (logMessage.empty()) - return msg; - - logMessage = msg + "\n" + logMessage; - - LogManager::getSingleton().logMessage(LML_CRITICAL, logMessage); - - return logMessage; - } - - String getObjectInfo(GLuint obj) - { - String logMessage; - - // Invalid object. - if (obj <= 0) - { - return logMessage; - } - - GLint infologLength = 0; - - GLboolean isShader = glIsShader(obj); - GLboolean isProgramPipeline = - Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability( - RSC_SEPARATE_SHADER_OBJECTS) && - glIsProgramPipeline(obj); - GLboolean isProgram = glIsProgram(obj); - - if (isShader) - { - OGRE_CHECK_GL_ERROR(glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &infologLength)); - } - else if (isProgramPipeline) - { - //FIXME Crashes on NVIDIA? See GL3+ GSoC forum - // posts around 2013-11-25. - OGRE_CHECK_GL_ERROR(glGetProgramPipelineiv(obj, GL_INFO_LOG_LENGTH, &infologLength)); - } - else if (isProgram) - { - OGRE_CHECK_GL_ERROR(glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &infologLength)); - } - - // No info log available. - // if (infologLength <= 1) - if (infologLength < 1) - { - return ""; - } - - GLint charsWritten = 0; - - char * infoLog = new char [infologLength]; - infoLog[0] = 0; - - if (isShader) - { - OGRE_CHECK_GL_ERROR(glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog)); - } - else if (isProgramPipeline) - { - OGRE_CHECK_GL_ERROR(glGetProgramPipelineInfoLog(obj, infologLength, &charsWritten, infoLog)); - } - else if (isProgram) - { - OGRE_CHECK_GL_ERROR(glGetProgramInfoLog(obj, infologLength, &charsWritten, infoLog)); - } - - if (strlen(infoLog) > 0) - { - logMessage = String(infoLog); - } - delete [] infoLog; - - StringUtil::trim(logMessage, false, true); - - return logMessage; - } - - -} diff --git a/RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLMonolithicProgram.cpp b/RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLMonolithicProgram.cpp deleted file mode 100644 index a549c69554e..00000000000 --- a/RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLMonolithicProgram.cpp +++ /dev/null @@ -1,325 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGLSLMonolithicProgram.h" -#include "OgreGLSLExtSupport.h" -#include "OgreGLSLShader.h" -#include "OgreGLSLProgramManager.h" -#include "OgreGL3PlusRenderSystem.h" -#include "OgreStringVector.h" -#include "OgreLogManager.h" -#include "OgreGpuProgramManager.h" -#include "OgreStringConverter.h" - -namespace Ogre { - - GLSLMonolithicProgram::GLSLMonolithicProgram(const GLShaderList& shaders) - : GLSLProgram(shaders) - { - } - - - GLSLMonolithicProgram::~GLSLMonolithicProgram(void) - { - OGRE_CHECK_GL_ERROR(glDeleteProgram(mGLProgramHandle)); - } - - void GLSLMonolithicProgram::activate(void) - { - if (!mLinked) - { - uint32 hash = getCombinedHash(); - - if(mGLProgramHandle == 0) - { - OGRE_CHECK_GL_ERROR(mGLProgramHandle = glCreateProgram()); - } - - mLinked = getMicrocodeFromCache(hash, mGLProgramHandle); - if (!mLinked) - { - // Something must have changed since the program binaries - // were cached away. Fallback to source shader loading path, - // and then retrieve and cache new program binaries once again. - compileAndLink(); - } - - buildGLUniformReferences(); - } - - if (mLinked) - { - OGRE_CHECK_GL_ERROR(glUseProgram(mGLProgramHandle)); - } - } - - - void GLSLMonolithicProgram::compileAndLink() - { - for (auto shader : mShaders) - { - if(!shader) continue; - - shader->attachToProgramObject(mGLProgramHandle); - } - - bindFixedAttributes(mGLProgramHandle); - - // the link - OGRE_CHECK_GL_ERROR(glLinkProgram( mGLProgramHandle )); - OGRE_CHECK_GL_ERROR(glGetProgramiv( mGLProgramHandle, GL_LINK_STATUS, &mLinked )); - - logObjectInfo( getCombinedName() + String(" GLSL link result : "), mGLProgramHandle ); - - if(glIsProgram(mGLProgramHandle)) - { - OGRE_CHECK_GL_ERROR(glValidateProgram(mGLProgramHandle)); - } - logObjectInfo( getCombinedName() + String(" GLSL validation result : "), mGLProgramHandle ); - - if(mLinked) - { - writeMicrocodeToCache(getCombinedHash(), mGLProgramHandle); - } - } - - - void GLSLMonolithicProgram::buildGLUniformReferences(void) - { - if (mUniformRefsBuilt) - { - return; - } - - // order must match GpuProgramType - const GpuConstantDefinitionMap* params[6] = { NULL }; - - for (int i = 0; i < 6; i++) - { - if (!mShaders[i]) - continue; - - params[i] = &(mShaders[i]->getConstantDefinitions().map); - } - - // Do we know how many shared params there are yet? Or if there are any blocks defined? - GLSLProgramManager::getSingleton().extractUniformsFromProgram(mGLProgramHandle, params, - mGLUniformReferences); - - mUniformRefsBuilt = true; - } - - - void GLSLMonolithicProgram::updateUniforms(GpuProgramParametersSharedPtr params, - uint16 mask, GpuProgramType fromProgType) - { - // Iterate through uniform reference list and update uniform values - GLUniformReferenceIterator currentUniform = mGLUniformReferences.begin(); - GLUniformReferenceIterator endUniform = mGLUniformReferences.end(); - - // determine if we need to transpose matrices when binding - bool transpose = !mShaders[fromProgType] || mShaders[fromProgType]->getColumnMajorMatrices(); - - for (;currentUniform != endUniform; ++currentUniform) - { - // Only pull values from buffer it's supposed to be in (vertex or fragment) - // This method will be called twice, once for vertex program params, - // and once for fragment program params. - if (fromProgType == currentUniform->mSourceProgType) - { - const GpuConstantDefinition* def = currentUniform->mConstantDef; - if (def->variability & mask) - { - GLsizei glArraySize = (GLsizei)def->arraySize; - - // Get the index in the parameter real list - switch (def->constType) - { - case GCT_FLOAT1: - OGRE_CHECK_GL_ERROR(glUniform1fv(currentUniform->mLocation, glArraySize, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_FLOAT2: - OGRE_CHECK_GL_ERROR(glUniform2fv(currentUniform->mLocation, glArraySize, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_FLOAT3: - OGRE_CHECK_GL_ERROR(glUniform3fv(currentUniform->mLocation, glArraySize, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_FLOAT4: - OGRE_CHECK_GL_ERROR(glUniform4fv(currentUniform->mLocation, glArraySize, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_DOUBLE1: - OGRE_CHECK_GL_ERROR(glUniform1dv(currentUniform->mLocation, glArraySize, - params->getDoublePointer(def->physicalIndex))); - break; - case GCT_DOUBLE2: - OGRE_CHECK_GL_ERROR(glUniform2dv(currentUniform->mLocation, glArraySize, - params->getDoublePointer(def->physicalIndex))); - break; - case GCT_DOUBLE3: - OGRE_CHECK_GL_ERROR(glUniform3dv(currentUniform->mLocation, glArraySize, - params->getDoublePointer(def->physicalIndex))); - break; - case GCT_DOUBLE4: - OGRE_CHECK_GL_ERROR(glUniform4dv(currentUniform->mLocation, glArraySize, - params->getDoublePointer(def->physicalIndex))); - break; - case GCT_MATRIX_DOUBLE_2X2: - OGRE_CHECK_GL_ERROR(glUniformMatrix2dv(currentUniform->mLocation, glArraySize, - transpose, params->getDoublePointer(def->physicalIndex))); - break; - case GCT_MATRIX_DOUBLE_2X3: - OGRE_CHECK_GL_ERROR(glUniformMatrix2x3dv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getDoublePointer(def->physicalIndex))); - break; - case GCT_MATRIX_DOUBLE_2X4: - OGRE_CHECK_GL_ERROR(glUniformMatrix2x4dv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getDoublePointer(def->physicalIndex))); - break; - case GCT_MATRIX_DOUBLE_3X2: - OGRE_CHECK_GL_ERROR(glUniformMatrix3x2dv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getDoublePointer(def->physicalIndex))); - break; - case GCT_MATRIX_DOUBLE_3X3: - OGRE_CHECK_GL_ERROR(glUniformMatrix3dv(currentUniform->mLocation, glArraySize, - transpose, params->getDoublePointer(def->physicalIndex))); - break; - case GCT_MATRIX_DOUBLE_3X4: - OGRE_CHECK_GL_ERROR(glUniformMatrix3x4dv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getDoublePointer(def->physicalIndex))); - break; - case GCT_MATRIX_DOUBLE_4X2: - OGRE_CHECK_GL_ERROR(glUniformMatrix4x2dv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getDoublePointer(def->physicalIndex))); - break; - case GCT_MATRIX_DOUBLE_4X3: - OGRE_CHECK_GL_ERROR(glUniformMatrix4x3dv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getDoublePointer(def->physicalIndex))); - break; - case GCT_MATRIX_DOUBLE_4X4: - OGRE_CHECK_GL_ERROR(glUniformMatrix4dv(currentUniform->mLocation, glArraySize, - transpose, params->getDoublePointer(def->physicalIndex))); - break; - case GCT_MATRIX_2X2: - OGRE_CHECK_GL_ERROR(glUniformMatrix2fv(currentUniform->mLocation, glArraySize, - transpose, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_2X3: - OGRE_CHECK_GL_ERROR(glUniformMatrix2x3fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_2X4: - OGRE_CHECK_GL_ERROR(glUniformMatrix2x4fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_3X2: - OGRE_CHECK_GL_ERROR(glUniformMatrix3x2fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_3X3: - OGRE_CHECK_GL_ERROR(glUniformMatrix3fv(currentUniform->mLocation, glArraySize, - transpose, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_3X4: - OGRE_CHECK_GL_ERROR(glUniformMatrix3x4fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_4X2: - OGRE_CHECK_GL_ERROR(glUniformMatrix4x2fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_4X3: - OGRE_CHECK_GL_ERROR(glUniformMatrix4x3fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_4X4: - OGRE_CHECK_GL_ERROR(glUniformMatrix4fv(currentUniform->mLocation, glArraySize, - transpose, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_SAMPLER1D: - case GCT_SAMPLER1DSHADOW: - case GCT_SAMPLER2D: - case GCT_SAMPLER2DSHADOW: - case GCT_SAMPLER2DARRAY: - case GCT_SAMPLER3D: - case GCT_SAMPLERCUBE: - // Samplers handled like 1-element ints, but use register storage - OGRE_CHECK_GL_ERROR(glUniform1iv(currentUniform->mLocation, glArraySize, - (GLint*)params->getRegPointer(def->physicalIndex))); - break; - case GCT_INT1: - OGRE_CHECK_GL_ERROR(glUniform1iv(currentUniform->mLocation, glArraySize, - (GLint*)params->getIntPointer(def->physicalIndex))); - break; - case GCT_INT2: - OGRE_CHECK_GL_ERROR(glUniform2iv(currentUniform->mLocation, glArraySize, - (GLint*)params->getIntPointer(def->physicalIndex))); - break; - case GCT_INT3: - OGRE_CHECK_GL_ERROR(glUniform3iv(currentUniform->mLocation, glArraySize, - (GLint*)params->getIntPointer(def->physicalIndex))); - break; - case GCT_INT4: - OGRE_CHECK_GL_ERROR(glUniform4iv(currentUniform->mLocation, glArraySize, - (GLint*)params->getIntPointer(def->physicalIndex))); - break; - case GCT_UINT1: - case GCT_BOOL1: - OGRE_CHECK_GL_ERROR(glUniform1uiv(currentUniform->mLocation, glArraySize, - (GLuint*)params->getUnsignedIntPointer(def->physicalIndex))); - break; - case GCT_UINT2: - case GCT_BOOL2: - OGRE_CHECK_GL_ERROR(glUniform2uiv(currentUniform->mLocation, glArraySize, - (GLuint*)params->getUnsignedIntPointer(def->physicalIndex))); - break; - case GCT_UINT3: - case GCT_BOOL3: - OGRE_CHECK_GL_ERROR(glUniform3uiv(currentUniform->mLocation, glArraySize, - (GLuint*)params->getUnsignedIntPointer(def->physicalIndex))); - break; - case GCT_UINT4: - case GCT_BOOL4: - OGRE_CHECK_GL_ERROR(glUniform4uiv(currentUniform->mLocation, glArraySize, - (GLuint*)params->getUnsignedIntPointer(def->physicalIndex))); - break; - default: - break; - - } // End switch - - } // Variability & mask - } // fromProgType == currentUniform->mSourceProgType - - } // End for - } - -} // namespace Ogre diff --git a/RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLProgram.cpp b/RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLProgram.cpp deleted file mode 100644 index d895a8574f9..00000000000 --- a/RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLProgram.cpp +++ /dev/null @@ -1,181 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGLSLProgram.h" -#include "OgreGLSLShader.h" -#include "OgreGpuProgramManager.h" -#include "OgreGLSLShader.h" -#include "OgreRoot.h" -#include "OgreGLSLExtSupport.h" -#include "OgreLogManager.h" - -namespace Ogre { - - GLSLProgram::GLSLProgram(const GLShaderList& shaders) - : GLSLProgramCommon(shaders) - { - } - - void GLSLProgram::bindFixedAttributes(GLuint program) - { - GLint maxAttribs = Root::getSingleton().getRenderSystem()->getCapabilities()->getNumVertexAttributes(); - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE - // must query active attributes on OSX to avoid warning spam - OGRE_CHECK_GL_ERROR(glLinkProgram( program )); -#endif - - size_t numAttribs = sizeof(msCustomAttributes) / sizeof(CustomAttribute); - for (size_t i = 0; i < numAttribs; ++i) - { - const CustomAttribute& a = msCustomAttributes[i]; - if (a.attrib < maxAttribs) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE - if(glGetAttribLocation(program, a.name) == -1) continue; -#endif - OGRE_CHECK_GL_ERROR(glBindAttribLocation(program, a.attrib, a.name)); - } - } - } - - void GLSLProgram::setTransformFeedbackVaryings(const std::vector& nameStrings) - { - // Get program object ID. - GLuint programId; - if (Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) - { - //TODO include tessellation stages - auto glslGpuProgram = mShaders[GPT_GEOMETRY_PROGRAM]; - if (!glslGpuProgram) - glslGpuProgram = mShaders[GPT_VERTEX_PROGRAM]; - - programId = glslGpuProgram->getGLProgramHandle(); - - // force re-link - GpuProgramManager::getSingleton().removeMicrocodeFromCache(glslGpuProgram->_getHash()); - glslGpuProgram->resetLinked(); - } - else - { - programId = getGLProgramHandle(); - - // force re-link - GpuProgramManager::getSingleton().removeMicrocodeFromCache(getCombinedHash()); - } - mLinked = false; - - // Convert to const char * for GL - std::vector names; - names.reserve(nameStrings.size()); -for (const auto & nameString : nameStrings) - { - names.push_back(nameString.c_str()); - } - - // TODO replace glTransformFeedbackVaryings with in-shader specification (GL 4.4) - OGRE_CHECK_GL_ERROR(glTransformFeedbackVaryings(programId, nameStrings.size(), &names[0], - GL_INTERLEAVED_ATTRIBS)); - -#if OGRE_DEBUG_MODE - activate(); - // Check if varyings were successfully set. - GLchar Name[64]; - GLsizei Length(0); - GLsizei Size(0); - GLenum Type(0); - // bool Validated = false; - for (size_t i = 0; i < nameStrings.size(); i++) - { - OGRE_CHECK_GL_ERROR( - glGetTransformFeedbackVarying(programId, i, 64, &Length, &Size, &Type, Name)); - LogManager::getSingleton().stream() << "Varying " << i << ": " << Name << " " << Length - << " " << Size << " " << Type; - // Validated = (Size == 1) && (Type == GL_FLOAT_VEC3); - // std::cout << Validated << " " << GL_FLOAT_VEC3 << std::endl; - } -#endif - } - - bool GLSLProgram::getMicrocodeFromCache(uint32 id, GLuint programHandle) - { - if (!GpuProgramManager::canGetCompiledShaderBuffer()) - return false; - - if (!GpuProgramManager::getSingleton().isMicrocodeAvailableInCache(id)) - return false; - - GpuProgramManager::Microcode cacheMicrocode = - GpuProgramManager::getSingleton().getMicrocodeFromCache(id); - - cacheMicrocode->seek(0); - - // Turns out we need this param when loading. - GLenum binaryFormat = 0; - cacheMicrocode->read(&binaryFormat, sizeof(GLenum)); - - // Get size of binary. - GLint binaryLength = static_cast(cacheMicrocode->size() - sizeof(GLenum)); - - // Load binary. - OGRE_CHECK_GL_ERROR(glProgramBinary(programHandle, - binaryFormat, - cacheMicrocode->getCurrentPtr(), - binaryLength)); - - GLint success = 0; - OGRE_CHECK_GL_ERROR(glGetProgramiv(programHandle, GL_LINK_STATUS, &success)); - - if(!success) - logObjectInfo("could not load from cache", programHandle); - - return success; - } - - void GLSLProgram::writeMicrocodeToCache(uint32 id, GLuint programHandle) - { - if (!GpuProgramManager::getSingleton().getSaveMicrocodesToCache()) - return; - - // get buffer size - GLint binaryLength = 0; - OGRE_CHECK_GL_ERROR(glGetProgramiv(programHandle, GL_PROGRAM_BINARY_LENGTH, &binaryLength)); - - // create microcode - auto newMicrocode = GpuProgramManager::createMicrocode(binaryLength + sizeof(GLenum)); - - // get binary - OGRE_CHECK_GL_ERROR(glGetProgramBinary(programHandle, binaryLength, NULL, - (GLenum*)newMicrocode->getPtr(), - newMicrocode->getPtr() + sizeof(GLenum))); - - // add to the microcode to the cache - GpuProgramManager::getSingleton().addMicrocodeToCache(id, newMicrocode); - } - -} // namespace Ogre diff --git a/RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLProgramManager.cpp b/RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLProgramManager.cpp deleted file mode 100644 index da255e6797e..00000000000 --- a/RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLProgramManager.cpp +++ /dev/null @@ -1,228 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGLSLProgramManager.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreGLSLShader.h" -#include "OgreGpuProgramManager.h" -#include "OgreGL3PlusHardwareBufferManager.h" -#include "OgreGL3PlusRenderSystem.h" -#include "OgreRoot.h" - -#include "OgreGLSLMonolithicProgram.h" -#include "OgreGLSLSeparableProgram.h" - -namespace Ogre { - - template<> GLSLProgramManager* Singleton::msSingleton = 0; - - - GLSLProgramManager* GLSLProgramManager::getSingletonPtr(void) - { - return msSingleton; - } - - - GLSLProgramManager& GLSLProgramManager::getSingleton(void) - { - assert(msSingleton); - return (*msSingleton); - } - - GLSLProgramManager::GLSLProgramManager(GL3PlusRenderSystem* renderSystem) - : mRenderSystem(renderSystem) - { - } - - GLSLProgramManager::~GLSLProgramManager(void) {} - - GL3PlusStateCacheManager* GLSLProgramManager::getStateCacheManager() - { - return mRenderSystem->_getStateCacheManager(); - } - - GLSLProgram* GLSLProgramManager::getActiveProgram(void) - { - // If there is an active link program then return it. - if (mActiveProgram) - return static_cast(mActiveProgram); - - // No active link program so find one or make a new one. - // Is there an active key? - uint32 activeKey = 0; - for(auto shader : mActiveShader) - { - if(!shader) continue; - - // overwrite as compute shaders are not part of the pipeline - if(shader->getType() == GPT_COMPUTE_PROGRAM) - activeKey = 0; - - activeKey = HashCombine(activeKey, shader->getShaderID()); - } - - // Only return a link program object if a program exists. - if (activeKey > 0) - { - // Find the key in the hash map. - ProgramIterator programFound = mPrograms.find(activeKey); - // Program object not found for key so need to create it. - if (programFound == mPrograms.end()) - { - if (mRenderSystem->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) - { - mActiveProgram = new GLSLSeparableProgram(mActiveShader); - } - else - { - mActiveProgram = new GLSLMonolithicProgram(mActiveShader); - } - - mPrograms[activeKey] = mActiveProgram; - } - else - { - // Found a link program in map container so make it active. - mActiveProgram = static_cast(programFound->second); - } - } - - // Make the program object active. - if (mActiveProgram) - mActiveProgram->activate(); - - return static_cast(mActiveProgram); - } - - void GLSLProgramManager::extractUniformsFromProgram(GLuint programObject, - const GpuConstantDefinitionMap* (&constantDefs)[6], - GLUniformReferenceList& uniformList) - { -#define uniformLength 200 - // GLint uniformLength = 0; - // glGetProgramiv(programObject, GL_ACTIVE_UNIFORM_MAX_LENGTH, &uniformLength); - - char uniformName[uniformLength] = {0}; - GLUniformReference newGLUniformReference; - - - // Get the number of active uniforms, including atomic - // counters and uniforms contained in uniform blocks. - GLint uniformCount = 0; - OGRE_CHECK_GL_ERROR(glGetProgramiv(programObject, GL_ACTIVE_UNIFORMS, &uniformCount)); - - // Scan through the active uniforms and add them to the reference list. - for (GLuint index = 0; index < (GLuint)uniformCount; index++) - { - GLint arraySize; - GLenum glType; - OGRE_CHECK_GL_ERROR(glGetActiveUniform(programObject, index, uniformLength, NULL, - &arraySize, &glType, uniformName)); - OGRE_CHECK_GL_ERROR(newGLUniformReference.mLocation = glGetUniformLocation(programObject, uniformName)); - - if(!validateParam(uniformName, arraySize, constantDefs, newGLUniformReference)) - continue; - uniformList.push_back(newGLUniformReference); - } - - // FIXME Ogre materials need a new shared param that is associated with an entity. - // This could be impemented as a switch-like statement inside shared_params: - - // Now deal with uniform blocks - auto& hbm = static_cast(HardwareBufferManager::getSingleton()); - GLint blockCount = 0; - OGRE_CHECK_GL_ERROR(glGetProgramiv(programObject, GL_ACTIVE_UNIFORM_BLOCKS, &blockCount)); - - for (int index = 0; index < blockCount; index++) - { - OGRE_CHECK_GL_ERROR(glGetActiveUniformBlockName(programObject, index, uniformLength, NULL, uniformName)); - - // Map uniform block to binding point of GL buffer of - // shared param bearing the same name. - GpuSharedParametersPtr blockSharedParams = GpuProgramManager::getSingleton().getSharedParameters(uniformName); - - HardwareBufferPtr hwGlBuffer = blockSharedParams->_getHardwareBuffer(); - if (!hwGlBuffer) - { - // Create buffer and add entry to buffer map. - GLint blockSize; - OGRE_CHECK_GL_ERROR(glGetActiveUniformBlockiv(programObject, index, GL_UNIFORM_BLOCK_DATA_SIZE, &blockSize)); - - auto binding = hbm.getUniformBufferCount(); - hwGlBuffer = hbm.createUniformBuffer(blockSize); - static_cast(hwGlBuffer.get())->setGLBufferBinding(int(binding)); - - blockSharedParams->_setHardwareBuffer(hwGlBuffer); - } - - OGRE_CHECK_GL_ERROR(glUniformBlockBinding( - programObject, index, static_cast(hwGlBuffer.get())->getGLBufferBinding())); - } - - // Now deal with shader storage blocks - if (mRenderSystem->hasMinGLVersion(4, 3) || mRenderSystem->checkExtension("GL_ARB_program_interface_query")) - { - OGRE_CHECK_GL_ERROR(glGetProgramInterfaceiv(programObject, GL_SHADER_STORAGE_BLOCK, GL_ACTIVE_RESOURCES, &blockCount)); - - //TODO error if GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS > # shader_storage_blocks - // do same for other buffers - - for (int index = 0; index < blockCount; index++) - { - OGRE_CHECK_GL_ERROR(glGetProgramResourceName(programObject, GL_SHADER_STORAGE_BLOCK, index, uniformLength, NULL, uniformName)); - - // Map uniform block to binding point of GL buffer of - // shared param bearing the same name. - - GpuSharedParametersPtr blockSharedParams = GpuProgramManager::getSingleton().getSharedParameters(uniformName); - - HardwareBufferPtr hwGlBuffer = blockSharedParams->_getHardwareBuffer(); - if (!hwGlBuffer) - { - // Create buffer and add entry to buffer map. - GLint blockSize; - // const GLenum properties [2] = {GL_BUFFER_DATA_SIZE, GL_BUFFER_BINDING}; - GLenum properties[] = {GL_BUFFER_DATA_SIZE}; - OGRE_CHECK_GL_ERROR(glGetProgramResourceiv(programObject, GL_SHADER_STORAGE_BLOCK, index, 1, properties, 1, NULL, &blockSize)); - //TODO Implement shared param access param in materials (R, W, R+W) - - auto binding = hbm.getShaderStorageBufferCount(); - hwGlBuffer = hbm.createShaderStorageBuffer(blockSize); - static_cast(hwGlBuffer.get())->setGLBufferBinding(binding); - - blockSharedParams->_setHardwareBuffer(hwGlBuffer); - } - - OGRE_CHECK_GL_ERROR(glShaderStorageBlockBinding( - programObject, index, - static_cast(hwGlBuffer.get())->getGLBufferBinding())); - } - } - } -} diff --git a/RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLSeparableProgram.cpp b/RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLSeparableProgram.cpp deleted file mode 100644 index f22f44f7a42..00000000000 --- a/RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLSeparableProgram.cpp +++ /dev/null @@ -1,305 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGLSLSeparableProgram.h" -#include "OgreStringConverter.h" -#include "OgreGLSLShader.h" -#include "OgreGLSLProgramManager.h" -#include "OgreGpuProgramManager.h" -#include "OgreGLUtil.h" -#include "OgreLogManager.h" -#include "OgreGLUniformCache.h" -#include "OgreGL3PlusStateCacheManager.h" - -namespace Ogre -{ - GLSLSeparableProgram::GLSLSeparableProgram(const GLShaderList& shaders) : - GLSLProgram(shaders) - { - } - - GLSLSeparableProgram::~GLSLSeparableProgram() - { - OGRE_CHECK_GL_ERROR(glDeleteProgramPipelines(1, &mGLProgramPipelineHandle)); - } - - void GLSLSeparableProgram::compileAndLink() - { - // Ensure no monolithic programs are in use. - OGRE_CHECK_GL_ERROR(glUseProgram(0)); - OGRE_CHECK_GL_ERROR(glGenProgramPipelines(1, &mGLProgramPipelineHandle)); - - mLinked = true; - - for (auto s : mShaders) - { - if(!s) continue; - - if(!s->linkSeparable()) - { - mLinked = false; - return; - } - } - - GLenum ogre2gltype[GPT_COUNT] = { - GL_VERTEX_SHADER_BIT, - GL_FRAGMENT_SHADER_BIT, - GL_GEOMETRY_SHADER_BIT, - GL_TESS_EVALUATION_SHADER_BIT, - GL_TESS_CONTROL_SHADER_BIT, - GL_COMPUTE_SHADER_BIT - }; - - for (auto s : mShaders) - { - if(!s) continue; - - OGRE_CHECK_GL_ERROR(glUseProgramStages(mGLProgramPipelineHandle, ogre2gltype[s->getType()], - s->getGLProgramHandle())); - } - - // Validate pipeline - OGRE_CHECK_GL_ERROR(glValidateProgramPipeline(mGLProgramPipelineHandle)); - logObjectInfo( getCombinedName() + String("GLSL program pipeline validation result: "), mGLProgramPipelineHandle ); - - // if (getGLSupport()->checkExtension("GL_KHR_debug") || gl3wIsSupported(4, 3)) - // glObjectLabel(GL_PROGRAM_PIPELINE, mGLProgramPipelineHandle, 0, - // (mVertexShader->getName() + "/" + mFragmentShader->getName()).c_str()); - } - - void GLSLSeparableProgram::activate(void) - { - if (!mLinked) - { - compileAndLink(); - } - - if (mLinked) - { - GLSLProgramManager::getSingleton().getStateCacheManager()->bindGLProgramPipeline(mGLProgramPipelineHandle); - } - } - - void GLSLSeparableProgram::updateUniforms(GpuProgramParametersSharedPtr params, - uint16 mask, GpuProgramType fromProgType) - { - // determine if we need to transpose matrices when binding - bool transpose = !mShaders[fromProgType] || mShaders[fromProgType]->getColumnMajorMatrices(); - - OgreAssert(mShaders[fromProgType], "invalid program type"); - GLuint progID = mShaders[fromProgType]->getGLProgramHandle(); - GLUniformCache* uniformCache = mShaders[fromProgType]->getUniformCache(); - - bool usesUBO = false; - if(const auto& ubo = static_cast(mShaders[fromProgType])->getDefaultBuffer()) - { - // we ignore ma - ubo->writeData(0, ubo->getSizeInBytes(), params->getConstantList().data(), true); - static_cast(ubo.get())->bind(); - usesUBO = true; - } - - // Iterate through uniform reference list and update uniform values - for (const auto& it : params->getConstantDefinitions().map) - { - const GpuConstantDefinition* def = &it.second; - if ((def->variability & mask) == 0) // masked - continue; - - GLsizei glArraySize = (GLsizei)def->arraySize; - - if(usesUBO && !def->isSampler()) - continue; // already handled above - - void* val = def->isSampler() ? (void*)params->getRegPointer(def->physicalIndex) - : (void*)params->getFloatPointer(def->physicalIndex); - bool shouldUpdate = - uniformCache->updateUniform(def->logicalIndex, val, def->elementSize * def->arraySize * 4); - if (!shouldUpdate) - continue; - - // Get the index in the parameter real list - switch (def->constType) - { - case GCT_FLOAT1: - OGRE_CHECK_GL_ERROR(glProgramUniform1fv(progID, def->logicalIndex, glArraySize, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_FLOAT2: - OGRE_CHECK_GL_ERROR(glProgramUniform2fv(progID, def->logicalIndex, glArraySize, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_FLOAT3: - OGRE_CHECK_GL_ERROR(glProgramUniform3fv(progID, def->logicalIndex, glArraySize, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_FLOAT4: - OGRE_CHECK_GL_ERROR(glProgramUniform4fv(progID, def->logicalIndex, glArraySize, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_2X2: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix2fv(progID, def->logicalIndex, glArraySize, transpose, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_3X3: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix3fv(progID, def->logicalIndex, glArraySize, transpose, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_4X4: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix4fv(progID, def->logicalIndex, glArraySize, transpose, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_SAMPLER1D: - case GCT_SAMPLER1DSHADOW: - case GCT_SAMPLER2D: - case GCT_SAMPLER2DSHADOW: - case GCT_SAMPLER2DARRAY: - case GCT_SAMPLER3D: - case GCT_SAMPLERCUBE: - // Samplers handled like 1-element ints - case GCT_INT1: - OGRE_CHECK_GL_ERROR(glProgramUniform1iv(progID, def->logicalIndex, glArraySize, - (int*)val)); - break; - case GCT_INT2: - OGRE_CHECK_GL_ERROR(glProgramUniform2iv(progID, def->logicalIndex, glArraySize, - params->getIntPointer(def->physicalIndex))); - break; - case GCT_INT3: - OGRE_CHECK_GL_ERROR(glProgramUniform3iv(progID, def->logicalIndex, glArraySize, - params->getIntPointer(def->physicalIndex))); - break; - case GCT_INT4: - OGRE_CHECK_GL_ERROR(glProgramUniform4iv(progID, def->logicalIndex, glArraySize, - params->getIntPointer(def->physicalIndex))); - break; - case GCT_MATRIX_2X3: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix2x3fv(progID, def->logicalIndex, glArraySize, GL_FALSE, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_2X4: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix2x4fv(progID, def->logicalIndex, glArraySize, GL_FALSE, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_3X2: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix3x2fv(progID, def->logicalIndex, glArraySize, GL_FALSE, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_3X4: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix3x4fv(progID, def->logicalIndex, glArraySize, GL_FALSE, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_4X2: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix4x2fv(progID, def->logicalIndex, glArraySize, GL_FALSE, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_4X3: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix4x3fv(progID, def->logicalIndex, glArraySize, GL_FALSE, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_DOUBLE1: - OGRE_CHECK_GL_ERROR(glProgramUniform1dv(progID, def->logicalIndex, glArraySize, - params->getDoublePointer(def->physicalIndex))); - break; - case GCT_DOUBLE2: - OGRE_CHECK_GL_ERROR(glProgramUniform2dv(progID, def->logicalIndex, glArraySize, - params->getDoublePointer(def->physicalIndex))); - break; - case GCT_DOUBLE3: - OGRE_CHECK_GL_ERROR(glProgramUniform3dv(progID, def->logicalIndex, glArraySize, - params->getDoublePointer(def->physicalIndex))); - break; - case GCT_DOUBLE4: - OGRE_CHECK_GL_ERROR(glProgramUniform4dv(progID, def->logicalIndex, glArraySize, - params->getDoublePointer(def->physicalIndex))); - break; - case GCT_MATRIX_DOUBLE_2X2: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix2dv(progID, def->logicalIndex, glArraySize, transpose, - params->getDoublePointer(def->physicalIndex))); - break; - case GCT_MATRIX_DOUBLE_3X3: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix3dv(progID, def->logicalIndex, glArraySize, transpose, - params->getDoublePointer(def->physicalIndex))); - break; - case GCT_MATRIX_DOUBLE_4X4: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix4dv(progID, def->logicalIndex, glArraySize, transpose, - params->getDoublePointer(def->physicalIndex))); - break; - case GCT_MATRIX_DOUBLE_2X3: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix2x3dv(progID, def->logicalIndex, glArraySize, transpose, - params->getDoublePointer(def->physicalIndex))); - break; - case GCT_MATRIX_DOUBLE_2X4: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix2x4dv(progID, def->logicalIndex, glArraySize, transpose, - params->getDoublePointer(def->physicalIndex))); - break; - case GCT_MATRIX_DOUBLE_3X2: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix3x2dv(progID, def->logicalIndex, glArraySize, transpose, - params->getDoublePointer(def->physicalIndex))); - break; - case GCT_MATRIX_DOUBLE_3X4: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix3x4dv(progID, def->logicalIndex, glArraySize, transpose, - params->getDoublePointer(def->physicalIndex))); - break; - case GCT_MATRIX_DOUBLE_4X2: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix4x2dv(progID, def->logicalIndex, glArraySize, transpose, - params->getDoublePointer(def->physicalIndex))); - break; - case GCT_MATRIX_DOUBLE_4X3: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix4x3dv(progID, def->logicalIndex, glArraySize, transpose, - params->getDoublePointer(def->physicalIndex))); - break; - case GCT_UINT1: - case GCT_BOOL1: - OGRE_CHECK_GL_ERROR(glProgramUniform1uiv(progID, def->logicalIndex, glArraySize, - params->getUnsignedIntPointer(def->physicalIndex))); - break; - case GCT_UINT2: - case GCT_BOOL2: - OGRE_CHECK_GL_ERROR(glProgramUniform2uiv(progID, def->logicalIndex, glArraySize, - params->getUnsignedIntPointer(def->physicalIndex))); - break; - case GCT_UINT3: - case GCT_BOOL3: - OGRE_CHECK_GL_ERROR(glProgramUniform3uiv(progID, def->logicalIndex, glArraySize, - params->getUnsignedIntPointer(def->physicalIndex))); - break; - case GCT_UINT4: - case GCT_BOOL4: - OGRE_CHECK_GL_ERROR(glProgramUniform4uiv(progID, def->logicalIndex, glArraySize, - params->getUnsignedIntPointer(def->physicalIndex))); - break; - - default: - break; - - } // End switch - } // End for - } -} diff --git a/RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLShader.cpp b/RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLShader.cpp deleted file mode 100644 index b6a755a2b13..00000000000 --- a/RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLShader.cpp +++ /dev/null @@ -1,710 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#include "OgreGpuProgram.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreLogManager.h" -#include "OgreRoot.h" -#include "OgreStringConverter.h" -#include "OgreGpuProgramManager.h" - -#include "OgreGLSLShader.h" - -#include "OgreGLSLPreprocessor.h" -#include "OgreGLSLProgramManager.h" -#include "OgreGLUtil.h" -#include "OgreGLUniformCache.h" - -#include "OgreGL3PlusHardwareBufferManager.h" - -namespace Ogre { - - /// Command object for setting the maximum output vertices (geometry shader only) - class CmdHasSamplersBinding : public ParamCommand - { - public: - String doGet(const void* target) const override - { - return StringConverter::toString(static_cast(target)->getSamplerBinding()); - } - void doSet(void* target, const String& val) override - { - static_cast(target)->setSamplerBinding(StringConverter::parseBool(val)); - } - }; - static CmdHasSamplersBinding msCmdHasSamplerBinding; - - /** Convert GL uniform size and type to OGRE constant types - and associate uniform definitions together. */ - static void convertGLUniformtoOgreType(GLenum gltype, GpuConstantDefinition& defToUpdate) - { - // Note GLSL never packs rows into float4's (from an API perspective anyway) - // therefore all values are tight in the buffer. - //TODO Should the rest of the above enum types be included here? - switch (gltype) - { - case GL_FLOAT: - defToUpdate.constType = GCT_FLOAT1; - break; - case GL_FLOAT_VEC2: - defToUpdate.constType = GCT_FLOAT2; - break; - case GL_FLOAT_VEC3: - defToUpdate.constType = GCT_FLOAT3; - break; - case GL_FLOAT_VEC4: - defToUpdate.constType = GCT_FLOAT4; - break; - case GL_IMAGE_1D: //TODO should be its own type? - case GL_SAMPLER_1D: - case GL_SAMPLER_1D_ARRAY: - case GL_INT_SAMPLER_1D: - case GL_INT_SAMPLER_1D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_1D: - case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: - // need to record samplers for GLSL - defToUpdate.constType = GCT_SAMPLER1D; - break; - case GL_IMAGE_2D: //TODO should be its own type? - case GL_IMAGE_2D_RECT: - case GL_SAMPLER_2D: - case GL_SAMPLER_2D_RECT: // TODO: Move these to a new type?? - case GL_INT_SAMPLER_2D_RECT: - case GL_UNSIGNED_INT_SAMPLER_2D_RECT: - case GL_SAMPLER_2D_ARRAY: - case GL_INT_SAMPLER_2D: - case GL_INT_SAMPLER_2D_ARRAY: - case GL_UNSIGNED_INT_SAMPLER_2D: - case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: - defToUpdate.constType = GCT_SAMPLER2D; - break; - case GL_IMAGE_3D: //TODO should be its own type? - case GL_SAMPLER_3D: - case GL_INT_SAMPLER_3D: - case GL_UNSIGNED_INT_SAMPLER_3D: - defToUpdate.constType = GCT_SAMPLER3D; - break; - case GL_SAMPLER_CUBE: - case GL_SAMPLER_CUBE_SHADOW: - case GL_INT_SAMPLER_CUBE: - case GL_UNSIGNED_INT_SAMPLER_CUBE: - defToUpdate.constType = GCT_SAMPLERCUBE; - break; - case GL_SAMPLER_1D_SHADOW: - case GL_SAMPLER_1D_ARRAY_SHADOW: - defToUpdate.constType = GCT_SAMPLER1DSHADOW; - break; - case GL_SAMPLER_2D_SHADOW: - case GL_SAMPLER_2D_RECT_SHADOW: - case GL_SAMPLER_2D_ARRAY_SHADOW: - defToUpdate.constType = GCT_SAMPLER2DSHADOW; - break; - case GL_INT: - defToUpdate.constType = GCT_INT1; - break; - case GL_INT_VEC2: - defToUpdate.constType = GCT_INT2; - break; - case GL_INT_VEC3: - defToUpdate.constType = GCT_INT3; - break; - case GL_INT_VEC4: - defToUpdate.constType = GCT_INT4; - break; - case GL_FLOAT_MAT2: - defToUpdate.constType = GCT_MATRIX_2X2; - break; - case GL_FLOAT_MAT3: - defToUpdate.constType = GCT_MATRIX_3X3; - break; - case GL_FLOAT_MAT4: - defToUpdate.constType = GCT_MATRIX_4X4; - break; - case GL_FLOAT_MAT2x3: - defToUpdate.constType = GCT_MATRIX_2X3; - break; - case GL_FLOAT_MAT3x2: - defToUpdate.constType = GCT_MATRIX_3X2; - break; - case GL_FLOAT_MAT2x4: - defToUpdate.constType = GCT_MATRIX_2X4; - break; - case GL_FLOAT_MAT4x2: - defToUpdate.constType = GCT_MATRIX_4X2; - break; - case GL_FLOAT_MAT3x4: - defToUpdate.constType = GCT_MATRIX_3X4; - break; - case GL_FLOAT_MAT4x3: - defToUpdate.constType = GCT_MATRIX_4X3; - break; - case GL_DOUBLE: - defToUpdate.constType = GCT_DOUBLE1; - break; - case GL_DOUBLE_VEC2: - defToUpdate.constType = GCT_DOUBLE2; - break; - case GL_DOUBLE_VEC3: - defToUpdate.constType = GCT_DOUBLE3; - break; - case GL_DOUBLE_VEC4: - defToUpdate.constType = GCT_DOUBLE4; - break; - case GL_DOUBLE_MAT2: - defToUpdate.constType = GCT_MATRIX_DOUBLE_2X2; - break; - case GL_DOUBLE_MAT3: - defToUpdate.constType = GCT_MATRIX_DOUBLE_3X3; - break; - case GL_DOUBLE_MAT4: - defToUpdate.constType = GCT_MATRIX_DOUBLE_4X4; - break; - case GL_DOUBLE_MAT2x3: - defToUpdate.constType = GCT_MATRIX_DOUBLE_2X3; - break; - case GL_DOUBLE_MAT3x2: - defToUpdate.constType = GCT_MATRIX_DOUBLE_3X2; - break; - case GL_DOUBLE_MAT2x4: - defToUpdate.constType = GCT_MATRIX_DOUBLE_2X4; - break; - case GL_DOUBLE_MAT4x2: - defToUpdate.constType = GCT_MATRIX_DOUBLE_4X2; - break; - case GL_DOUBLE_MAT3x4: - defToUpdate.constType = GCT_MATRIX_DOUBLE_3X4; - break; - case GL_DOUBLE_MAT4x3: - defToUpdate.constType = GCT_MATRIX_DOUBLE_4X3; - break; - case GL_UNSIGNED_INT: - case GL_UNSIGNED_INT_ATOMIC_COUNTER: //TODO should be its own type? - defToUpdate.constType = GCT_UINT1; - break; - case GL_UNSIGNED_INT_VEC2: - defToUpdate.constType = GCT_UINT2; - break; - case GL_UNSIGNED_INT_VEC3: - defToUpdate.constType = GCT_UINT3; - break; - case GL_UNSIGNED_INT_VEC4: - defToUpdate.constType = GCT_UINT4; - break; - case GL_BOOL: - defToUpdate.constType = GCT_BOOL1; - break; - case GL_BOOL_VEC2: - defToUpdate.constType = GCT_BOOL2; - break; - case GL_BOOL_VEC3: - defToUpdate.constType = GCT_BOOL3; - break; - case GL_BOOL_VEC4: - defToUpdate.constType = GCT_BOOL4; - break; - default: - defToUpdate.constType = GCT_UNKNOWN; - break; - } - } - - /// Get OpenGL GLSL shader type from OGRE GPU program type. - static GLenum getGLShaderType(GpuProgramType programType) - { - switch (programType) - { - case GPT_VERTEX_PROGRAM: - return GL_VERTEX_SHADER; - case GPT_HULL_PROGRAM: - return GL_TESS_CONTROL_SHADER; - case GPT_DOMAIN_PROGRAM: - return GL_TESS_EVALUATION_SHADER; - case GPT_GEOMETRY_PROGRAM: - return GL_GEOMETRY_SHADER; - case GPT_FRAGMENT_PROGRAM: - return GL_FRAGMENT_SHADER; - case GPT_COMPUTE_PROGRAM: - return GL_COMPUTE_SHADER; - } - - return 0; - } - - GLSLShader::GLSLShader( - ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - : GLSLShaderCommon(creator, name, handle, group, isManual, loader) - { - if (createParamDictionary("GLSLShader")) - { - setupBaseParamDictionary(); - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter("attach", &msCmdAttach); - dict->addParameter("column_major_matrices", &msCmdColumnMajorMatrices); - dict->addParameter("has_sampler_binding", &msCmdHasSamplerBinding); - } - - mHasSamplerBinding = false; - // There is nothing to load - mLoadFromFile = false; - } - - GLSLShader::~GLSLShader() - { - // Have to call this here rather than in Resource destructor - // since calling virtual methods in base destructors causes crash - if (isLoaded()) - { - unload(); - } - else - { - unloadHighLevel(); - } - } - - void GLSLShader::compileSource() - { - if (mSource.empty()) - return; - - const RenderSystemCapabilities* rsc = Root::getSingleton().getRenderSystem()->getCapabilities(); - - bool clipDistBug = - ((OGRE_PLATFORM == OGRE_PLATFORM_WIN32) || (OGRE_PLATFORM == OGRE_PLATFORM_WINRT)) && - rsc->getVendor() == GPU_INTEL; - - size_t versionPos = mSource.find("#version"); - size_t belowVersionPos = 0; - - if(versionPos != String::npos) - { - belowVersionPos = mSource.find('\n', versionPos) + 1; - } - - // OSX driver only supports glsl150+ in core profile - bool shouldUpgradeToVersion150 = !rsc->isShaderProfileSupported("glsl130") && mShaderVersion < 150; - - // Add standard shader input and output blocks, if missing. - // Assume blocks are missing if gl_Position is missing. - if (rsc->hasCapability(RSC_GLSL_SSO_REDECLARE) && (mSource.find("vec4 gl_Position") == String::npos)) - { - size_t mainPos = mSource.find("void main"); - // Only add blocks if shader is not a child - // shader, i.e. has a main function. - if (mainPos != String::npos) - { - String clipDistDecl = clipDistBug ? "float gl_ClipDistance[1];" : "float gl_ClipDistance[];"; - String inBlock = "in gl_PerVertex\n{\nvec4 gl_Position;\nfloat gl_PointSize;\n"+clipDistDecl+"\n} gl_in[];\n\n"; - String outBlock = "out gl_PerVertex\n{\nvec4 gl_Position;\nfloat gl_PointSize;\n"+clipDistDecl+"\n};\n\n"; - - if (mShaderVersion >= 150 || shouldUpgradeToVersion150) - { - switch (mType) - { - case GPT_VERTEX_PROGRAM: - mSource.insert(belowVersionPos, outBlock); - break; - case GPT_GEOMETRY_PROGRAM: - mSource.insert(belowVersionPos, outBlock); - mSource.insert(belowVersionPos, inBlock); - break; - case GPT_DOMAIN_PROGRAM: - mSource.insert(belowVersionPos, outBlock); - mSource.insert(belowVersionPos, inBlock); - break; - case GPT_HULL_PROGRAM: - mSource.insert(belowVersionPos, outBlock.substr(0, outBlock.size() - 3) + " gl_out[];\n\n"); - mSource.insert(belowVersionPos, inBlock); - break; - case GPT_FRAGMENT_PROGRAM: - case GPT_COMPUTE_PROGRAM: - // Fragment and compute shaders do - // not have standard blocks. - break; - } - } - else if(mType == GPT_VERTEX_PROGRAM && mShaderVersion >= 130) // shaderVersion < 150, means we only have vertex shaders - { - // TODO: can we have SSO with GLSL < 130? - mSource.insert(belowVersionPos, "out vec4 gl_Position;\nout float gl_PointSize;\nout "+clipDistDecl+"\n\n"); - } - } - } - - if(shouldUpgradeToVersion150) - { - if(belowVersionPos != 0) - mSource = mSource.erase(0, belowVersionPos); // drop old definition - - // automatically upgrade to glsl150. thank you apple. - const char* prefixFp = - "#version 150\n" - "#define varying in\n"; - const char* prefixVp = - "#version 150\n" - "#define attribute in\n" - "#define varying out\n"; - - mSource.insert(0, mType == GPT_FRAGMENT_PROGRAM ? prefixFp : prefixVp); - } - - // Submit shader source. - const char *source = mSource.c_str(); - OGRE_CHECK_GL_ERROR(glShaderSource(mGLShaderHandle, 1, &source, NULL)); - OGRE_CHECK_GL_ERROR(glCompileShader(mGLShaderHandle)); - } - - bool GLSLShader::linkSeparable() - { - if(mCompileError) - return false; - - if(mLinked) - return true; - - OGRE_CHECK_GL_ERROR(glProgramParameteri(mGLProgramHandle, GL_PROGRAM_SEPARABLE, GL_TRUE)); - OGRE_CHECK_GL_ERROR(glProgramParameteri(mGLProgramHandle, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE)); - - uint32 hash = _getHash(); - - // Use precompiled program if possible. - mLinked = GLSLProgram::getMicrocodeFromCache(hash, mGLProgramHandle); - - // Compilation needed if precompiled program is - // unavailable or failed to link. - if (!mLinked) - { - if( mType == GPT_VERTEX_PROGRAM ) - GLSLProgram::bindFixedAttributes( mGLProgramHandle ); - - attachToProgramObject(mGLProgramHandle); - OGRE_CHECK_GL_ERROR(glLinkProgram(mGLProgramHandle)); - OGRE_CHECK_GL_ERROR(glGetProgramiv(mGLProgramHandle, GL_LINK_STATUS, &mLinked)); - - // Binary cache needs an update. - GLSLProgram::writeMicrocodeToCache(hash, mGLProgramHandle); - } - - if(!mLinked) - { - logObjectInfo( mName + String(" - GLSL program result : "), mGLProgramHandle ); - return false; - } - - return true; - } - - void GLSLShader::loadFromSource() - { - // Create shader object. - GLenum GLShaderType = getGLShaderType(mType); - OGRE_CHECK_GL_ERROR(mGLShaderHandle = glCreateShader(GLShaderType)); - - auto caps = Root::getSingleton().getRenderSystem()->getCapabilities(); - - if (caps->hasCapability(RSC_DEBUG)) - OGRE_CHECK_GL_ERROR(glObjectLabel(GL_SHADER, mGLShaderHandle, -1, mName.c_str())); - - compileSource(); - - // Check for compile errors - int compiled = 0; - OGRE_CHECK_GL_ERROR(glGetShaderiv(mGLShaderHandle, GL_COMPILE_STATUS, &compiled)); - - String compileInfo = getObjectInfo(mGLShaderHandle); - - // also create program object - if (compiled && caps->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) - { - OGRE_CHECK_GL_ERROR(mGLProgramHandle = glCreateProgram()); - // do not attempt to link attach only shaders - if(mSyntaxCode == "gl_spirv" || (mSource.find("void main") != String::npos)) - compiled = linkSeparable(); - } - - if (!compiled) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, getResourceLogName() + " " + compileInfo, "compile"); - - // probably we have warnings - if (!compileInfo.empty()) - LogManager::getSingleton().stream(LML_WARNING) << getResourceLogName() << " " << compileInfo; - } - - void GLSLShader::unloadHighLevelImpl(void) - { - OGRE_CHECK_GL_ERROR(glDeleteShader(mGLShaderHandle)); - - if (mGLProgramHandle) - { - OGRE_CHECK_GL_ERROR(glDeleteProgram(mGLProgramHandle)); - } - - // destroy all programs using this shader - GLSLProgramManager::getSingletonPtr()->destroyAllByShader(this); - - mGLShaderHandle = 0; - mGLProgramHandle = 0; - mLinked = 0; - } - - void GLSLShader::extractUniforms(int block) const - { - GLint numUniforms = 0; - OGRE_CHECK_GL_ERROR(glGetProgramInterfaceiv(mGLProgramHandle, GL_UNIFORM, GL_ACTIVE_RESOURCES, &numUniforms)); - - const GLenum properties[6] = {GL_BLOCK_INDEX, GL_TYPE, GL_NAME_LENGTH, GL_LOCATION, GL_ARRAY_SIZE, GL_OFFSET}; - for (int unif = 0; unif < numUniforms; ++unif) - { - GLint values[6]; - OGRE_CHECK_GL_ERROR( - glGetProgramResourceiv(mGLProgramHandle, GL_UNIFORM, unif, 6, properties, 6, NULL, values)); - - // Skip any uniforms that are in a different block or atomic_uints - if (values[0] != block || (block == -1 && values[3] == -1)) - continue; - - GpuConstantDefinition def; - def.logicalIndex = values[3]; - def.arraySize = values[4]; - - std::vector nameData(values[2]); - OGRE_CHECK_GL_ERROR(glGetProgramResourceName(mGLProgramHandle, GL_UNIFORM, unif, values[2], - NULL, &nameData[0])); - String name(nameData.begin(), nameData.end() - 1); - - // If the uniform name ends with "]" then its an array element uniform - if (name.back() == ']') - { - name.resize(name.size() - 3); - } - - // Complete def and add - // increment physical buffer location - - convertGLUniformtoOgreType(values[1], def); - // GL doesn't pad - def.elementSize = GpuConstantDefinition::getElementSize(def.constType, false); - - // also allow index based referencing - GpuLogicalIndexUse use; - - if (def.isFloat() || def.isDouble() || def.isInt() || def.isUnsignedInt() || def.isBool()) - { - def.physicalIndex = block > -1 ? values[5] : mConstantDefs->bufferSize * 4; - mConstantDefs->bufferSize += def.arraySize * def.elementSize; - - if (values[3] != -1) - { - use.physicalIndex = def.physicalIndex; - use.currentSize = def.arraySize * def.elementSize; - mLogicalToPhysical->map.emplace(def.logicalIndex, use); - - // warn if there is a default value, that we would overwrite - std::vector val(use.currentSize); - OGRE_CHECK_GL_ERROR(glGetUniformiv(mGLProgramHandle, def.logicalIndex, val.data())); - if (val != std::vector(use.currentSize)) - LogManager::getSingleton().logWarning("Default value of uniform '" + name + - "' is ignored in " + getResourceLogName()); - } - } - else if(def.isSampler()) - { - if(mHasSamplerBinding) - continue; - def.physicalIndex = mConstantDefs->registerCount; - mConstantDefs->registerCount += def.arraySize * def.elementSize; - // no index based referencing - } - else - { - LogManager::getSingleton().logError("Could not parse type of GLSL Uniform: '" + name + - "' in file " + getResourceLogName()); - } - mConstantDefs->map.emplace(name, def); - } - } - - void GLSLShader::extractBufferBlocks(GLenum type) const - { - GLint numBlocks = 0; - OGRE_CHECK_GL_ERROR(glGetProgramInterfaceiv(mGLProgramHandle, type, GL_ACTIVE_RESOURCES, &numBlocks)); - - auto& hbm = static_cast(HardwareBufferManager::getSingleton()); - - const GLenum blockProperties[3] = {GL_NUM_ACTIVE_VARIABLES, GL_NAME_LENGTH, GL_BUFFER_DATA_SIZE}; - for(int blockIdx = 0; blockIdx < numBlocks; ++blockIdx) - { - GLint values[3]; - OGRE_CHECK_GL_ERROR(glGetProgramResourceiv(mGLProgramHandle, type, blockIdx, 3, blockProperties, - 3, NULL, values)); - if(values[0] == 0) continue; - - std::vector nameData(values[1]); - OGRE_CHECK_GL_ERROR(glGetProgramResourceName(mGLProgramHandle, type, blockIdx, - values[1], NULL, &nameData[0])); - String name(nameData.begin(), nameData.end() - 1); - - if (name == "OgreUniforms") // default buffer - { - extractUniforms(blockIdx); - int binding = int(mType); - if (binding > 1) - LogManager::getSingleton().logWarning( - getResourceLogName() + - " - using a UBO in this shader type will alias with shared_params"); - - mDefaultBuffer = hbm.createUniformBuffer(values[2]); - static_cast(mDefaultBuffer.get())->setGLBufferBinding(binding); - OGRE_CHECK_GL_ERROR(glUniformBlockBinding(mGLProgramHandle, blockIdx, binding)); - continue; - } - - auto blockSharedParams = GpuProgramManager::getSingleton().getSharedParameters(name); - - HardwareBufferPtr hwGlBuffer = blockSharedParams->_getHardwareBuffer(); - if(!hwGlBuffer) - { - size_t binding = 0; - if(type == GL_UNIFORM_BLOCK) - { - binding = hbm.getUniformBufferCount() + 2; // slots 0 & 1 are reserved for defaultbuffer - hwGlBuffer = hbm.createUniformBuffer(values[2]); - } - else - { - binding = hbm.getShaderStorageBufferCount(); - hwGlBuffer = hbm.createShaderStorageBuffer(values[2]); - } - - static_cast(hwGlBuffer.get())->setGLBufferBinding(int(binding)); - blockSharedParams->_setHardwareBuffer(hwGlBuffer); - } - - int binding = static_cast(hwGlBuffer.get())->getGLBufferBinding(); - - if(type == GL_UNIFORM_BLOCK) - { - OGRE_CHECK_GL_ERROR(glUniformBlockBinding(mGLProgramHandle, blockIdx, binding)); - } - else - { - OGRE_CHECK_GL_ERROR(glShaderStorageBlockBinding(mGLProgramHandle, blockIdx, binding)); - } - } - } - - void GLSLShader::buildConstantDefinitions() - { - createParameterMappingStructures(true); - auto caps = Root::getSingleton().getRenderSystem()->getCapabilities(); - - if(caps->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) - { - extractUniforms(); - extractBufferBlocks(GL_UNIFORM_BLOCK); - extractBufferBlocks(GL_SHADER_STORAGE_BLOCK); - return; - } - - mLogicalToPhysical.reset(); - - // We need an accurate list of all the uniforms in the shader, but we - // can't get at them until we link all the shaders into a program object. - // Therefore instead parse the source code manually and extract the uniforms. - GLSLProgramManager::getSingleton().extractUniformsFromGLSL(mSource, *mConstantDefs, getResourceLogName()); - - - // Also parse any attached sources. - for (auto childShader : mAttachedGLSLPrograms) - { - GLSLProgramManager::getSingleton().extractUniformsFromGLSL( - childShader->getSource(), *mConstantDefs, childShader->getName()); - } - - if(!mHasSamplerBinding) - return; - - // drop samplers from constant definitions - for(auto it = mConstantDefs->map.begin(); it != mConstantDefs->map.end();) - { - if(it->second.isSampler()) - it = mConstantDefs->map.erase(it); - else - ++it; - } - } - - void GLSLShader::attachToProgramObject(const GLuint programObject) - { - // attach child objects - for (auto childShader : mAttachedGLSLPrograms) - { - childShader->attachToProgramObject(programObject); - } - OGRE_CHECK_GL_ERROR(glAttachShader(programObject, mGLShaderHandle)); - } - - - void GLSLShader::detachFromProgramObject(const GLuint programObject) - { - OGRE_CHECK_GL_ERROR(glDetachShader(programObject, mGLShaderHandle)); - logObjectInfo( "Error detaching " + mName + " shader object from GLSL Program Object", programObject); - // attach child objects - GLSLProgramContainerIterator childprogramcurrent = mAttachedGLSLPrograms.begin(); - GLSLProgramContainerIterator childprogramend = mAttachedGLSLPrograms.end(); - - while (childprogramcurrent != childprogramend) - { - GLSLShaderCommon* childShader = *childprogramcurrent; - childShader->detachFromProgramObject(programObject); - ++childprogramcurrent; - } - } - - static const String language = "glsl"; - - const String& GLSLShader::getLanguage(void) const - { - return language; - } - - const String& GLSLShaderFactory::getLanguage(void) const - { - return language; - } - - GpuProgram* GLSLShaderFactory::create( - ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - { - return OGRE_NEW GLSLShader(creator, name, handle, group, isManual, loader); - } -} diff --git a/RenderSystems/GL3Plus/src/OgreGL3PlusEngineDll.cpp b/RenderSystems/GL3Plus/src/OgreGL3PlusEngineDll.cpp deleted file mode 100644 index 810e504a6bd..00000000000 --- a/RenderSystems/GL3Plus/src/OgreGL3PlusEngineDll.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreRoot.h" -#include "OgreGL3PlusPrerequisites.h" -#include "OgreGL3PlusPlugin.h" - -#ifndef OGRE_STATIC_LIB - -namespace Ogre -{ - static GL3PlusPlugin* plugin; - - extern "C" void _OgreGL3PlusExport dllStartPlugin(void); - extern "C" void _OgreGL3PlusExport dllStopPlugin(void); - - extern "C" void _OgreGL3PlusExport dllStartPlugin(void) - { - plugin = OGRE_NEW GL3PlusPlugin(); - Root::getSingleton().installPlugin(plugin); - } - - extern "C" void _OgreGL3PlusExport dllStopPlugin(void) - { - Root::getSingleton().uninstallPlugin(plugin); - OGRE_DELETE plugin; - } -} - -#endif diff --git a/RenderSystems/GL3Plus/src/OgreGL3PlusFBOMultiRenderTarget.cpp b/RenderSystems/GL3Plus/src/OgreGL3PlusFBOMultiRenderTarget.cpp deleted file mode 100644 index 64af8cc112e..00000000000 --- a/RenderSystems/GL3Plus/src/OgreGL3PlusFBOMultiRenderTarget.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGL3PlusFBOMultiRenderTarget.h" - -namespace Ogre { - - GL3PlusFBOMultiRenderTarget::GL3PlusFBOMultiRenderTarget(GL3PlusFBOManager *manager, const String &name): - MultiRenderTarget(name), - fbo(manager, 0 /* TODO: multisampling on MRTs? */) - { - } - - GL3PlusFBOMultiRenderTarget::~GL3PlusFBOMultiRenderTarget() - { - } - - void GL3PlusFBOMultiRenderTarget::bindSurfaceImpl(size_t attachment, RenderTexture *target) - { - // Check if the render target is in the rendertarget->FBO map - auto fbobj = dynamic_cast(target)->getFBO(); - assert(fbobj); - fbo.bindSurface(attachment, fbobj->getSurface(0)); - - // Set width and height - mWidth = fbo.getWidth(); - mHeight = fbo.getHeight(); - } - - void GL3PlusFBOMultiRenderTarget::unbindSurfaceImpl(size_t attachment) - { - fbo.unbindSurface(attachment); - - // Set width and height - mWidth = fbo.getWidth(); - mHeight = fbo.getHeight(); - } - - void GL3PlusFBOMultiRenderTarget::getCustomAttribute( const String& name, void *pData ) - { - if(name == GLRenderTexture::CustomAttributeString_FBO) - { - *static_cast(pData) = &fbo; - } - else if(name == GLRenderTexture::CustomAttributeString_GLCONTEXT) - { - *static_cast(pData) = fbo.getContext(); - } - } - - bool GL3PlusFBOMultiRenderTarget::attachDepthBuffer( DepthBuffer *depthBuffer ) - { - bool result; - if( (result = MultiRenderTarget::attachDepthBuffer( depthBuffer )) ) - fbo.attachDepthBuffer( depthBuffer ); - - return result; - } - - void GL3PlusFBOMultiRenderTarget::detachDepthBuffer() - { - fbo.detachDepthBuffer(); - MultiRenderTarget::detachDepthBuffer(); - } - - void GL3PlusFBOMultiRenderTarget::_detachDepthBuffer() - { - fbo.detachDepthBuffer(); - MultiRenderTarget::_detachDepthBuffer(); - } - - -} diff --git a/RenderSystems/GL3Plus/src/OgreGL3PlusFBORenderTexture.cpp b/RenderSystems/GL3Plus/src/OgreGL3PlusFBORenderTexture.cpp deleted file mode 100644 index 0c5a12932ce..00000000000 --- a/RenderSystems/GL3Plus/src/OgreGL3PlusFBORenderTexture.cpp +++ /dev/null @@ -1,502 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#include "OgreGL3PlusPrerequisites.h" - -#include "OgreGL3PlusFBORenderTexture.h" -#include "OgreGL3PlusPixelFormat.h" -#include "OgreLogManager.h" -#include "OgreGL3PlusHardwarePixelBuffer.h" -#include "OgreGL3PlusFBOMultiRenderTarget.h" -#include "OgreGL3PlusRenderSystem.h" -#include "OgreGL3PlusStateCacheManager.h" - -namespace Ogre { - - GL3PlusFBORenderTexture::GL3PlusFBORenderTexture( - GL3PlusFBOManager *manager, const String &name, - const GLSurfaceDesc &target, bool writeGamma, uint fsaa): - GLRenderTexture(name, target, writeGamma, fsaa), - mFB(manager, fsaa) - { - // Bind target to surface 0 and initialise - mFB.bindSurface(0, target); - - // Get attributes - mWidth = mFB.getWidth(); - mHeight = mFB.getHeight(); - } - - void GL3PlusFBORenderTexture::getCustomAttribute(const String& name, void* pData) - { - if(name == GLRenderTexture::CustomAttributeString_FBO) - { - *static_cast(pData) = &mFB; - } - else if(name == GLRenderTexture::CustomAttributeString_GLCONTEXT) - { - *static_cast(pData) = getContext(); - } - else if (name == "GL_FBOID") - { - *static_cast(pData) = mFB.getGLFBOID(); - } - else if (name == "GL_MULTISAMPLEFBOID") - { - *static_cast(pData) = mFB.getGLMultisampleFBOID(); - } - } - - void GL3PlusFBORenderTexture::swapBuffers() - { - mFB.swapBuffers(); - } - - bool GL3PlusFBORenderTexture::attachDepthBuffer( DepthBuffer *depthBuffer ) - { - bool result; - if( (result = GLRenderTexture::attachDepthBuffer( depthBuffer )) ) - mFB.attachDepthBuffer( depthBuffer ); - - return result; - } - - void GL3PlusFBORenderTexture::detachDepthBuffer() - { - mFB.detachDepthBuffer(); - GLRenderTexture::detachDepthBuffer(); - } - - void GL3PlusFBORenderTexture::_detachDepthBuffer() - { - mFB.detachDepthBuffer(); - GLRenderTexture::_detachDepthBuffer(); - } - - // Size of probe texture -#define PROBE_SIZE 16 - - // Stencil and depth formats to be tried - static const GLenum stencilFormats[] = - { - GL_NONE, // No stencil - GL_STENCIL_INDEX1, - GL_STENCIL_INDEX4, - GL_STENCIL_INDEX8, - GL_STENCIL_INDEX16 - }; - static const uchar stencilBits[] = - { - 0, 1, 4, 8, 16 - }; -#define STENCILFORMAT_COUNT (sizeof(stencilFormats)/sizeof(GLenum)) - - static const GLenum depthFormats[] = - { - GL_NONE, - GL_DEPTH_COMPONENT16, - GL_DEPTH_COMPONENT24, // Prefer 24 bit depth - GL_DEPTH_COMPONENT32, - GL_DEPTH_COMPONENT32F, - GL_DEPTH24_STENCIL8, // Packed depth / stencil - GL_DEPTH32F_STENCIL8 - }; - static const uchar depthBits[] = - { - 0,16,24,32,32,24,32 - }; -#define DEPTHFORMAT_COUNT (sizeof(depthFormats)/sizeof(GLenum)) - - GL3PlusFBOManager::GL3PlusFBOManager(GL3PlusRenderSystem* renderSystem) : mRenderSystem(renderSystem) - { - detectFBOFormats(); - } - - GL3PlusFBOManager::~GL3PlusFBOManager() - { - if(!mRenderBufferMap.empty()) - { - LogManager::getSingleton().logWarning("GL3PlusFBOManager destructor called, but not all renderbuffers were released."); - } - } - - GL3PlusStateCacheManager* GL3PlusFBOManager::getStateCacheManager() - { - return mRenderSystem->_getStateCacheManager(); - } - - void GL3PlusFBOManager::_createTempFramebuffer(GLuint internalFormat, GLuint fmt, GLenum dataType, GLuint &fb, GLuint &tid) - { - OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &fb)); - mRenderSystem->_getStateCacheManager()->bindGLFrameBuffer( GL_DRAW_FRAMEBUFFER, fb ); - if (fmt != GL_NONE) - { - if (tid) - { - OGRE_CHECK_GL_ERROR(glDeleteTextures(1, &tid)); - mRenderSystem->_getStateCacheManager()->invalidateStateForTexture( tid ); - } - - // Create and attach texture - OGRE_CHECK_GL_ERROR(glGenTextures(1, &tid)); - mRenderSystem->_getStateCacheManager()->bindGLTexture( GL_TEXTURE_2D, tid ); - - // Set some default parameters - OGRE_CHECK_GL_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0)); - OGRE_CHECK_GL_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0)); - OGRE_CHECK_GL_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)); - OGRE_CHECK_GL_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); - OGRE_CHECK_GL_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); - OGRE_CHECK_GL_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); - - OGRE_CHECK_GL_ERROR(glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, PROBE_SIZE, PROBE_SIZE, 0, fmt, dataType, 0)); - - OGRE_CHECK_GL_ERROR(glFramebufferTexture2D( - GL_DRAW_FRAMEBUFFER, fmt == GL_DEPTH_COMPONENT ? GL_DEPTH_ATTACHMENT : GL_COLOR_ATTACHMENT0, - GL_TEXTURE_2D, tid, 0)); - } - else - { - // Draw to nowhere -- stencil/depth only - OGRE_CHECK_GL_ERROR(glDrawBuffer(GL_NONE)); - OGRE_CHECK_GL_ERROR(glReadBuffer(GL_NONE)); - } - } - - /** Try a certain FBO format, and return the status. Also sets mDepthRB and mStencilRB. - @returns true if this combo is supported - false if this combo is not supported - */ - GLuint GL3PlusFBOManager::_tryFormat(GLenum depthFormat, GLenum stencilFormat) - { - GLuint status, depthRB = 0, stencilRB = 0; - - if (depthFormat != GL_NONE) - { - // Generate depth renderbuffer - OGRE_CHECK_GL_ERROR(glGenRenderbuffers(1, &depthRB)); - - // Bind it to FBO - mRenderSystem->_getStateCacheManager()->bindGLRenderBuffer( depthRB ); - - // Allocate storage for depth buffer - OGRE_CHECK_GL_ERROR(glRenderbufferStorage(GL_RENDERBUFFER, depthFormat, - PROBE_SIZE, PROBE_SIZE)); - - // Attach depth - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRB)); - } - - if (stencilFormat != GL_NONE) - { - // Generate stencil renderbuffer - OGRE_CHECK_GL_ERROR(glGenRenderbuffers(1, &stencilRB)); - // Bind it to FBO - mRenderSystem->_getStateCacheManager()->bindGLRenderBuffer( stencilRB ); - - // Allocate storage for stencil buffer - OGRE_CHECK_GL_ERROR(glRenderbufferStorage(GL_RENDERBUFFER, stencilFormat, PROBE_SIZE, PROBE_SIZE)); - - // Attach stencil - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, - GL_RENDERBUFFER, stencilRB)); - } - - OGRE_CHECK_GL_ERROR(status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER)); - - // If status is negative, clean up - // Detach and destroy - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0)); - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0)); - - if (depthRB) - mRenderSystem->_getStateCacheManager()->deleteGLRenderBuffer(depthRB); - - if (stencilRB) - mRenderSystem->_getStateCacheManager()->deleteGLRenderBuffer(stencilRB); - - return status == GL_FRAMEBUFFER_COMPLETE; - } - - /** Try a certain packed depth/stencil format, and return the status. - @return true if this combo is supported - false if this combo is not supported - */ - bool GL3PlusFBOManager::_tryPackedFormat(GLenum packedFormat) - { - GLuint packedRB; - - // Generate renderbuffer - OGRE_CHECK_GL_ERROR(glGenRenderbuffers(1, &packedRB)); - - // Bind it to FBO - mRenderSystem->_getStateCacheManager()->bindGLRenderBuffer( packedRB ); - - // Allocate storage for buffer - OGRE_CHECK_GL_ERROR(glRenderbufferStorage(GL_RENDERBUFFER, packedFormat, PROBE_SIZE, PROBE_SIZE)); - - // Attach depth - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, - GL_RENDERBUFFER, packedRB)); - - // Attach stencil - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, - GL_RENDERBUFFER, packedRB)); - - GLuint status; - OGRE_CHECK_GL_ERROR(status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER)); - - // Detach and destroy - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0)); - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0)); - mRenderSystem->_getStateCacheManager()->deleteGLRenderBuffer(packedRB); - - return status == GL_FRAMEBUFFER_COMPLETE; - } - - /** Detect which internal formats are allowed as RTT - Also detect what combinations of stencil and depth are allowed with this internal - format. - */ - void GL3PlusFBOManager::detectFBOFormats() - { - // is glGetInternalformativ supported? - // core since GL 4.2: see https://www.opengl.org/wiki/GLAPI/glGetInternalformat - // NOTE! GL_FRAMEBUFFER_RENDERABLE is supported only if the GL version is 4.3 or higher - bool hasInternalFormatQuery = mRenderSystem->hasMinGLVersion(4, 3) || mRenderSystem->checkExtension("GL_ARB_internalformat_query2"); - - // Try all formats, and report which ones work as target - GLuint fb = 0, tid = 0; - - bool formatSupported; - GLint params; - - for(int x = 0; x < PF_COUNT; ++x) - { - mProps[x].valid = false; - - // Fetch GL format token - GLenum internalFormat = GL3PlusPixelUtil::getGLInternalFormat((PixelFormat)x); - GLenum originFormat = GL3PlusPixelUtil::getGLOriginFormat((PixelFormat)x); - GLenum dataType = GL3PlusPixelUtil::getGLOriginDataType((PixelFormat)x); - if(internalFormat == GL_NONE && x != 0) - continue; - - // No test for compressed formats - if(PixelUtil::isCompressed((PixelFormat)x)) - continue; - - if (hasInternalFormatQuery) { - OGRE_CHECK_GL_ERROR( - glGetInternalformativ(GL_RENDERBUFFER, internalFormat, GL_FRAMEBUFFER_RENDERABLE, 1, ¶ms)); - formatSupported = params == GL_FULL_SUPPORT; - } else { - // Create and attach framebuffer - _createTempFramebuffer(internalFormat, originFormat, dataType, fb, tid); - - // Check status - GLuint status; - OGRE_CHECK_GL_ERROR(status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER)); - formatSupported = status == GL_FRAMEBUFFER_COMPLETE; - } - - // Ignore status in case of fmt==GL_NONE, because no implementation will accept - // a buffer without *any* attachment. Buffers with only stencil and depth attachment - // might still be supported, so we must continue probing. - if(internalFormat == GL_NONE || formatSupported) - { - mProps[x].valid = true; - StringStream str; - str << "FBO " << PixelUtil::getFormatName((PixelFormat)x) - << " depth/stencil support: "; - - // For each depth/stencil formats - for (uchar depth = 0; depth < DEPTHFORMAT_COUNT; ++depth) - { - if ((depthFormats[depth] != GL_DEPTH24_STENCIL8) && (depthFormats[depth] != GL_DEPTH32F_STENCIL8)) - { - // General depth/stencil combination - - if(hasInternalFormatQuery) { - OGRE_CHECK_GL_ERROR( - glGetInternalformativ(GL_RENDERBUFFER, depthFormats[depth], GL_FRAMEBUFFER_RENDERABLE, 1, ¶ms)); - - // skip unsupported depth unless it is GL_NONE, as we still want D0Sxx formats - if(params != GL_FULL_SUPPORT && depthFormats[depth] != GL_NONE) { - continue; - } - } - - for (uchar stencil = 0; stencil < STENCILFORMAT_COUNT; ++stencil) - { - // StringStream l; - // l << "Trying " << PixelUtil::getFormatName((PixelFormat)x) - // << " D" << depthBits[depth] - // << "S" << stencilBits[stencil]; - // LogManager::getSingleton().logMessage(l.str()); - - if (hasInternalFormatQuery) { - OGRE_CHECK_GL_ERROR( - glGetInternalformativ( GL_RENDERBUFFER, stencilFormats[stencil], GL_FRAMEBUFFER_RENDERABLE, 1, ¶ms)); - - // skip unsupported stencil unless it is GL_NONE, as we still want DxxS0 formats - formatSupported = params == GL_FULL_SUPPORT || stencilFormats[stencil] == GL_NONE; - } else { - formatSupported = _tryFormat(depthFormats[depth], stencilFormats[stencil]) != 0; - } - - if (formatSupported) - { - // Add mode to allowed modes - str << StringUtil::format("D%dS%d ", depthBits[depth], stencilBits[stencil]); - FormatProperties::Mode mode = {depth, stencil}; - mProps[x].modes.push_back(mode); - } - } - } - else - { - // Packed depth/stencil format - if (hasInternalFormatQuery) { - OGRE_CHECK_GL_ERROR( - glGetInternalformativ( GL_RENDERBUFFER, depthFormats[depth], GL_FRAMEBUFFER_RENDERABLE, 1, ¶ms)); - - formatSupported = params == GL_FULL_SUPPORT; - } else { - formatSupported = _tryPackedFormat(depthFormats[depth]); - } - - if (formatSupported) - { - // Add mode to allowed modes - str << "Packed-D" << int(depthBits[depth]) << "S8 "; - FormatProperties::Mode mode = {depth, 0}; // stencil unused - mProps[x].modes.push_back(mode); - } - } - } - LogManager::getSingleton().logMessage(str.str()); - } - - if (!hasInternalFormatQuery) { - // Delete texture and framebuffer - mRenderSystem->_getStateCacheManager()->bindGLFrameBuffer( GL_DRAW_FRAMEBUFFER, 0 ); - mRenderSystem->_getStateCacheManager()->deleteGLRenderBuffer(fb); - - if (internalFormat != GL_NONE) - { - OGRE_CHECK_GL_ERROR(glDeleteTextures(1, &tid)); - mRenderSystem->_getStateCacheManager()->invalidateStateForTexture( tid ); - tid = 0; - } - } - } - - String fmtstring = ""; - for(size_t x = 0; x < PF_COUNT; ++x) - { - if(mProps[x].valid) - fmtstring += PixelUtil::getFormatName((PixelFormat)x)+" "; - } - LogManager::getSingleton().logMessage("[GL] : Valid FBO targets " + fmtstring); - } - - void GL3PlusFBOManager::getBestDepthStencil(PixelFormat internalFormat, GLenum *depthFormat, GLenum *stencilFormat) - { - const FormatProperties &props = mProps[internalFormat]; - // Decide what stencil and depth formats to use - // [best supported for internal format] - size_t bestmode=0; - int bestscore=-1; - bool requestDepthOnly = PixelUtil::isDepth(internalFormat); - for(size_t mode=0; modebestscore) - { - bestscore = desirability; - bestmode = mode; - } - } - *depthFormat = depthFormats[props.modes[bestmode].depth]; - *stencilFormat = requestDepthOnly ? 0 : stencilFormats[props.modes[bestmode].stencil]; - } - - GL3PlusFBORenderTexture *GL3PlusFBOManager::createRenderTexture(const String &name, - const GLSurfaceDesc &target, bool writeGamma, uint fsaa) - { - GL3PlusFBORenderTexture *retval = new GL3PlusFBORenderTexture(this, name, target, writeGamma, fsaa); - return retval; - } - - GLSurfaceDesc GL3PlusFBOManager::requestRenderBuffer(GLenum format, uint32 width, uint32 height, uint fsaa) - { - GLSurfaceDesc retval; - retval.buffer = 0; // Return 0 buffer if GL_NONE is requested - if(format != GL_NONE) - { - RBFormat key(format, width, height, fsaa); - RenderBufferMap::iterator it = mRenderBufferMap.find(key); - if(it != mRenderBufferMap.end()) - { - retval.buffer = it->second.buffer; - retval.zoffset = 0; - retval.numSamples = fsaa; - // Increase refcount - ++it->second.refcount; - } - else - { - // New one - GL3PlusRenderBuffer *rb = new GL3PlusRenderBuffer(format, width, height, fsaa); - mRenderBufferMap[key] = RBRef(rb); - retval.buffer = rb; - retval.zoffset = 0; - retval.numSamples = fsaa; - } - } - // std::cerr << "Requested renderbuffer with format " << std::hex << format << std::dec << " of " << width << "x" << height << " :" << retval.buffer << std::endl; - return retval; - } - -} diff --git a/RenderSystems/GL3Plus/src/OgreGL3PlusFrameBufferObject.cpp b/RenderSystems/GL3Plus/src/OgreGL3PlusFrameBufferObject.cpp deleted file mode 100644 index 0796d9925b8..00000000000 --- a/RenderSystems/GL3Plus/src/OgreGL3PlusFrameBufferObject.cpp +++ /dev/null @@ -1,313 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGL3PlusFrameBufferObject.h" -#include "OgreGL3PlusHardwarePixelBuffer.h" -#include "OgreGL3PlusFBORenderTexture.h" -#include "OgreGLDepthBufferCommon.h" -#include "OgreGL3PlusStateCacheManager.h" -#include "OgreGLRenderSystemCommon.h" -#include "OgreRoot.h" - -namespace Ogre { - - - GL3PlusFrameBufferObject::GL3PlusFrameBufferObject(GL3PlusFBOManager *manager, uint fsaa): - GLFrameBufferObjectCommon(fsaa), mManager(manager) - { - // Generate framebuffer object - OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mFB)); - - // Check samples supported - mManager->getStateCacheManager()->bindGLFrameBuffer( GL_FRAMEBUFFER, mFB ); - - GLint maxSamples; - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_SAMPLES, &maxSamples)); - mNumSamples = std::min(mNumSamples, (GLsizei)maxSamples); - - // Will we need a second FBO to do multisampling? - if (mNumSamples) - { - OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mMultisampleFB)); - } - else - { - mMultisampleFB = 0; - } - } - - GL3PlusFrameBufferObject::~GL3PlusFrameBufferObject() - { - mManager->releaseRenderBuffer(mDepth); - mManager->releaseRenderBuffer(mStencil); - mManager->releaseRenderBuffer(mMultisampleColourBuffer); - // Delete framebuffer object - if(mContext && mFB) - { - GLRenderSystemCommon* rs = static_cast(Root::getSingleton().getRenderSystem()); - rs->_destroyFbo(mContext, mFB); - - if (mMultisampleFB) - rs->_destroyFbo(mContext, mMultisampleFB); - } - } - - void GL3PlusFrameBufferObject::initialise() - { - assert(mContext == (static_cast(Root::getSingleton().getRenderSystem()))->_getCurrentContext()); - - // Release depth and stencil, if they were bound - mManager->releaseRenderBuffer(mDepth); - mManager->releaseRenderBuffer(mStencil); - mManager->releaseRenderBuffer(mMultisampleColourBuffer); - // First buffer must be bound - if(!mColour[0].buffer) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Attachment 0 must have surface attached", - "GL3PlusFrameBufferObject::initialise"); - } - - // If we're doing multisampling, then we need another FBO which contains a - // renderbuffer which is set up to multisample, and we'll blit it to the final - // FBO afterwards to perform the multisample resolve. In that case, the - // mMultisampleFB is bound during rendering and is the one with a depth/stencil - - // Store basic stats - uint32 width = mColour[0].buffer->getWidth(); - uint32 height = mColour[0].buffer->getHeight(); - GLuint format = mColour[0].buffer->getGLFormat(); - ushort maxSupportedMRTs = Root::getSingleton().getRenderSystem()->getCapabilities()->getNumMultiRenderTargets(); - - // Bind simple buffer to add colour attachments - mManager->getStateCacheManager()->bindGLFrameBuffer( GL_FRAMEBUFFER, mFB ); - - // Bind all attachment points to frame buffer - for(unsigned int x = 0; x < maxSupportedMRTs; ++x) - { - if(mColour[x].buffer) - { - bool isDepth = PixelUtil::isDepth(mColour[x].buffer->getFormat()); - - if(mColour[x].buffer->getWidth() != width || mColour[x].buffer->getHeight() != height) - { - StringStream ss; - ss << "Attachment " << x << " has incompatible size "; - ss << mColour[x].buffer->getWidth() << "x" << mColour[x].buffer->getHeight(); - ss << ". It must be of the same as the size of surface 0, "; - ss << width << "x" << height; - ss << "."; - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GL3PlusFrameBufferObject::initialise"); - } - - mColour[x].buffer->bindToFramebuffer( - isDepth ? GL_DEPTH_ATTACHMENT : (GL_COLOR_ATTACHMENT0 + x), mColour[x].zoffset); - } - else - { - // Detach - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0+x, GL_RENDERBUFFER, 0)); - } - } - - // Now deal with depth / stencil - if (mMultisampleFB && !PixelUtil::isDepth(getFormat())) - { - // Bind multisample buffer - mManager->getStateCacheManager()->bindGLFrameBuffer( GL_FRAMEBUFFER, mMultisampleFB ); - - // Create AA render buffer (colour) - // note, this can be shared too because we blit it to the final FBO - // right after the render is finished - mMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples); - - // Attach it, because we won't be attaching below and non-multisample has - // actually been attached to other FBO - mMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0, - mMultisampleColourBuffer.zoffset); - - // depth & stencil will be dealt with below - } - - // Depth buffer is not handled here anymore. - // See GL3PlusFrameBufferObject::attachDepthBuffer() & RenderSystem::setDepthBufferFor() - - // Do glDrawBuffer calls - GLenum bufs[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; - GLsizei n=0; - for(unsigned int x=0; xgetFormat()); - - bufs[x] = isDepth ? GL_NONE : (GL_COLOR_ATTACHMENT0 + x); - // Keep highest used buffer + 1 - if(!isDepth) - n = x+1; - } - else - { - bufs[x] = GL_NONE; - } - } - - // Drawbuffer extension supported, use it - OGRE_CHECK_GL_ERROR(glDrawBuffers(n, bufs)); - - // Check status - GLuint status; - OGRE_CHECK_GL_ERROR(status = glCheckFramebufferStatus(GL_FRAMEBUFFER)); - - // Bind main buffer - mManager->getStateCacheManager()->bindGLFrameBuffer( GL_FRAMEBUFFER, 0 ); - - switch(status) - { - case GL_FRAMEBUFFER_COMPLETE: - // All is good - break; - case GL_FRAMEBUFFER_UNSUPPORTED: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "All framebuffer formats with this texture internal format unsupported", - "GL3PlusFrameBufferObject::initialise"); - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Framebuffer incomplete or other FBO status error", - "GL3PlusFrameBufferObject::initialise"); - } - - } - - bool GL3PlusFrameBufferObject::bind(bool recreateIfNeeded) - { - GLRenderSystemCommon* rs = static_cast(Root::getSingleton().getRenderSystem()); - GLContext* currentContext = rs->_getCurrentContext(); - if(mContext && mContext != currentContext) // FBO is unusable with current context, destroy it - { - if(mFB != 0) - rs->_destroyFbo(mContext, mFB); - if(mMultisampleFB != 0) - rs->_destroyFbo(mContext, mMultisampleFB); - - mContext = 0; - mFB = 0; - mMultisampleFB = 0; - } - - if(!mContext && recreateIfNeeded) // create FBO lazy or recreate after destruction - { - mContext = currentContext; - - // Generate framebuffer object - OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mFB)); - - // Check samples supported - mManager->getStateCacheManager()->bindGLFrameBuffer( GL_FRAMEBUFFER, mFB ); - - GLint maxSamples; - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_SAMPLES, &maxSamples)); - mNumSamples = std::min(mNumSamples, (GLsizei)maxSamples); - - // Will we need a second FBO to do multisampling? - if (mNumSamples) - { - OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mMultisampleFB)); - } - else - { - mMultisampleFB = 0; - } - - // Re-initialise - if(mColour[0].buffer) - initialise(); - } - - if(mContext) - mManager->getStateCacheManager()->bindGLFrameBuffer(GL_FRAMEBUFFER, mMultisampleFB ? mMultisampleFB : mFB); - - return mContext != 0; - } - - void GL3PlusFrameBufferObject::swapBuffers() - { - if (mMultisampleFB) - { - GLint oldfb = 0; - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldfb)); - - // Blit from multisample buffer to final buffer, triggers resolve - uint32 width = mColour[0].buffer->getWidth(); - uint32 height = mColour[0].buffer->getHeight(); - mManager->getStateCacheManager()->bindGLFrameBuffer( GL_READ_FRAMEBUFFER, mMultisampleFB ); - mManager->getStateCacheManager()->bindGLFrameBuffer( GL_DRAW_FRAMEBUFFER, mFB ); - - OGRE_CHECK_GL_ERROR(glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST)); - // Unbind - mManager->getStateCacheManager()->bindGLFrameBuffer( GL_FRAMEBUFFER, oldfb ); - } - } - - void GL3PlusFrameBufferObject::attachDepthBuffer( DepthBuffer *depthBuffer ) - { - bind(true); // recreate FBO if unusable with current context, bind it - - GLDepthBufferCommon *glDepthBuffer = static_cast(depthBuffer); - if( glDepthBuffer ) - { - auto *depthBuf = glDepthBuffer->getDepthBuffer(); - auto *stencilBuf = glDepthBuffer->getStencilBuffer(); - - // Attach depth buffer, if it has one. - if( depthBuf ) - depthBuf->bindToFramebuffer( GL_DEPTH_ATTACHMENT, 0 ); - // Attach stencil buffer, if it has one. - if( stencilBuf ) - stencilBuf->bindToFramebuffer( GL_STENCIL_ATTACHMENT, 0 ); - } - else - { - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, - GL_RENDERBUFFER, 0)); - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, - GL_RENDERBUFFER, 0)); - } - } - - void GL3PlusFrameBufferObject::detachDepthBuffer() - { - if(bind(false)) // bind or destroy FBO if it is unusable with current context - { - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0 )); - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0 )); - } - } - -} diff --git a/RenderSystems/GL3Plus/src/OgreGL3PlusHardwareBuffer.cpp b/RenderSystems/GL3Plus/src/OgreGL3PlusHardwareBuffer.cpp deleted file mode 100644 index c00174081a9..00000000000 --- a/RenderSystems/GL3Plus/src/OgreGL3PlusHardwareBuffer.cpp +++ /dev/null @@ -1,210 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGL3PlusHardwareBuffer.h" - -#include -#include "OgreRoot.h" -#include "OgreGL3PlusRenderSystem.h" -#include "OgreGL3PlusStateCacheManager.h" -#include "OgreDefaultHardwareBufferManager.h" - -namespace Ogre { - - GL3PlusHardwareBuffer::GL3PlusHardwareBuffer(GLenum target, size_t sizeInBytes, uint32 usage, bool useShadowBuffer) - : HardwareBuffer(usage, useShadowBuffer), mTarget(target) - { - mSizeInBytes = sizeInBytes; - mRenderSystem = static_cast(Root::getSingleton().getRenderSystem()); - - OGRE_CHECK_GL_ERROR(glGenBuffers(1, &mBufferId)); - - if (!mBufferId) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Cannot create GL buffer"); - } - mRenderSystem->_getStateCacheManager()->bindGLBuffer(mTarget, mBufferId); - OGRE_CHECK_GL_ERROR(glBufferData(mTarget, mSizeInBytes, NULL, getGLUsage(mUsage))); - - if (useShadowBuffer) - { - mShadowBuffer = std::make_unique(mSizeInBytes); - } - } - - GL3PlusHardwareBuffer::~GL3PlusHardwareBuffer() - { - if(GL3PlusStateCacheManager* stateCacheManager = mRenderSystem->_getStateCacheManager()) - stateCacheManager->deleteGLBuffer(mTarget,mBufferId); - } - - void* GL3PlusHardwareBuffer::lockImpl(size_t offset, size_t length, LockOptions options) - { - GLenum access = 0; - - // Use glMapBuffer - mRenderSystem->_getStateCacheManager()->bindGLBuffer(mTarget,mBufferId); - - bool writeOnly = - options == HardwareBuffer::HBL_WRITE_ONLY || - ((mUsage & HBU_DETAIL_WRITE_ONLY) && - options != HardwareBuffer::HBL_READ_ONLY && options != HardwareBuffer::HBL_NORMAL); - - if (writeOnly) - { - if(options == HBL_DISCARD) - OGRE_CHECK_GL_ERROR(glBufferData(mTarget, mSizeInBytes, NULL, getGLUsage(mUsage))); - - access |= GL_MAP_WRITE_BIT; - if(options == HBL_NO_OVERWRITE) - access |= GL_MAP_UNSYNCHRONIZED_BIT; - } - else if (options == HardwareBuffer::HBL_READ_ONLY) - access |= GL_MAP_READ_BIT; - else - access |= GL_MAP_READ_BIT | GL_MAP_WRITE_BIT; - - // FIXME: Big stall here - // NOTE: Stall happens, when using modern drivers, with multi threading enabled driver - void* pBuffer; - OGRE_CHECK_GL_ERROR(pBuffer = glMapBufferRange(mTarget, offset, length, access)); - - if(pBuffer == 0) - { - OGRE_EXCEPT( - Exception::ERR_INTERNAL_ERROR, - StringUtil::format("failed to lock %zu bytes at %zu of total %zu bytes", length, offset, mSizeInBytes)); - } - - // pBuffer is already offsetted in glMapBufferRange - return pBuffer; - } - - void GL3PlusHardwareBuffer::unlockImpl() - { - mRenderSystem->_getStateCacheManager()->bindGLBuffer(mTarget, mBufferId); - - GLboolean mapped; - OGRE_CHECK_GL_ERROR(mapped = glUnmapBuffer(mTarget)); - if(!mapped) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Buffer data corrupted, please reload", - "GL3PlusHardwareBuffer::unlock"); - } - } - - void GL3PlusHardwareBuffer::readData(size_t offset, size_t length, void* pDest) - { - if (mShadowBuffer) - { - mShadowBuffer->readData(offset, length, pDest); - return; - } - - // get data from the real buffer - mRenderSystem->_getStateCacheManager()->bindGLBuffer(mTarget, mBufferId); - - OGRE_CHECK_GL_ERROR(glGetBufferSubData(mTarget, offset, length, pDest)); - } - - void GL3PlusHardwareBuffer::writeData(size_t offset, size_t length, const void* pSource, - bool discardWholeBuffer) - { - if (mShadowBuffer) - { - mShadowBuffer->writeData(offset, length, pSource, discardWholeBuffer); - } - - writeDataImpl(offset, length, pSource, discardWholeBuffer); - } - - void GL3PlusHardwareBuffer::writeDataImpl(size_t offset, size_t length, const void* pSource, - bool discardWholeBuffer) - { - mRenderSystem->_getStateCacheManager()->bindGLBuffer(mTarget, mBufferId); - - if (offset == 0 && length == mSizeInBytes) - { - OGRE_CHECK_GL_ERROR(glBufferData(mTarget, mSizeInBytes, pSource, getGLUsage(mUsage))); - } - else - { - if (discardWholeBuffer) - { - OGRE_CHECK_GL_ERROR(glBufferData(mTarget, mSizeInBytes, NULL, getGLUsage(mUsage))); - } - - OGRE_CHECK_GL_ERROR(glBufferSubData(mTarget, offset, length, pSource)); - } - } - - void GL3PlusHardwareBuffer::_updateFromShadow(void) - { - if (mShadowBuffer && mShadowUpdated && !mSuppressHardwareUpdate) - { - HardwareBufferLockGuard shadowLock(mShadowBuffer.get(), mLockStart, mLockSize, HBL_READ_ONLY); - writeDataImpl(mLockStart, mLockSize, shadowLock.pData, false); - - mShadowUpdated = false; - } - } - - void GL3PlusHardwareBuffer::copyData(HardwareBuffer& srcBuffer, size_t srcOffset, size_t dstOffset, - size_t length, bool discardWholeBuffer) - { - if (mShadowBuffer) - { - mShadowBuffer->copyData(srcBuffer, srcOffset, dstOffset, length, discardWholeBuffer); - } - - // Do it the fast way. - mRenderSystem->_getStateCacheManager()->bindGLBuffer( - GL_COPY_READ_BUFFER, static_cast(srcBuffer).getGLBufferId()); - mRenderSystem->_getStateCacheManager()->bindGLBuffer(GL_COPY_WRITE_BUFFER, mBufferId); - - OGRE_CHECK_GL_ERROR(glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, srcOffset, dstOffset, length)); - - mRenderSystem->_getStateCacheManager()->bindGLBuffer(GL_COPY_READ_BUFFER, 0); - mRenderSystem->_getStateCacheManager()->bindGLBuffer(GL_COPY_WRITE_BUFFER, 0); - } - - GLenum GL3PlusHardwareBuffer::getGLUsage(uint32 usage) - { - return (usage == HBU_GPU_TO_CPU) ? GL_STATIC_READ - : (usage == HBU_GPU_ONLY) ? GL_STATIC_DRAW : GL_DYNAMIC_DRAW; - } - - void GL3PlusHardwareBuffer::setGLBufferBinding(GLint binding) - { - mBindingPoint = binding; - - // Attach the buffer to the binding index. - OGRE_CHECK_GL_ERROR(glBindBufferBase(mTarget, mBindingPoint, mBufferId)); - } -} diff --git a/RenderSystems/GL3Plus/src/OgreGL3PlusHardwareBufferManager.cpp b/RenderSystems/GL3Plus/src/OgreGL3PlusHardwareBufferManager.cpp deleted file mode 100644 index 5baca08787b..00000000000 --- a/RenderSystems/GL3Plus/src/OgreGL3PlusHardwareBufferManager.cpp +++ /dev/null @@ -1,156 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGL3PlusHardwareBufferManager.h" -#include "OgreGL3PlusHardwareBuffer.h" -#include "OgreGL3PlusRenderToVertexBuffer.h" -#include "OgreGL3PlusRenderSystem.h" -#include "OgreRoot.h" -#include "OgreGLVertexArrayObject.h" - -namespace Ogre { - GL3PlusHardwareBufferManager::GL3PlusHardwareBufferManager() : mUniformBufferCount(0), mShaderStorageBufferCount(0) - { - mRenderSystem = static_cast(Root::getSingleton().getRenderSystem()); - } - - GL3PlusHardwareBufferManager::~GL3PlusHardwareBufferManager() - { - destroyAllDeclarations(); - destroyAllBindings(); - } - - void GL3PlusHardwareBufferManager::notifyContextDestroyed(GLContext* context) - { - OGRE_LOCK_MUTEX(mVertexDeclarationsMutex); - for(auto& d : mVertexDeclarations) - static_cast(d)->notifyContextDestroyed(context); - } - - HardwareVertexBufferSharedPtr - GL3PlusHardwareBufferManager::createVertexBuffer(size_t vertexSize, - size_t numVerts, - HardwareBuffer::Usage usage, - bool useShadowBuffer) - { - auto impl = new GL3PlusHardwareBuffer(GL_ARRAY_BUFFER, vertexSize * numVerts, usage, useShadowBuffer); - auto buf = std::make_shared(this, vertexSize, numVerts, impl); - { - OGRE_LOCK_MUTEX(mVertexBuffersMutex); - mVertexBuffers.insert(buf.get()); - } - return buf; - } - - HardwareIndexBufferSharedPtr GL3PlusHardwareBufferManager::createIndexBuffer(HardwareIndexBuffer::IndexType itype, - size_t numIndexes, - HardwareBuffer::Usage usage, - bool useShadowBuffer) - { - // Calculate the size of the indexes - auto indexSize = HardwareIndexBuffer::indexSize(itype); - auto impl = new GL3PlusHardwareBuffer(GL_ELEMENT_ARRAY_BUFFER, indexSize * numIndexes, usage, useShadowBuffer); - - return std::make_shared(this, itype, numIndexes, impl); - } - - HardwareBufferPtr GL3PlusHardwareBufferManager::createUniformBuffer(size_t sizeBytes, HardwareBufferUsage usage, bool useShadowBuffer) - { - mUniformBufferCount++; - return std::make_shared(GL_UNIFORM_BUFFER, sizeBytes, usage, useShadowBuffer); - } - - HardwareBufferPtr GL3PlusHardwareBufferManager::createShaderStorageBuffer(size_t sizeBytes, HardwareBufferUsage usage, bool useShadowBuffer) - { - mShaderStorageBufferCount++; - return std::make_shared(GL_SHADER_STORAGE_BUFFER, sizeBytes, usage, useShadowBuffer); - } - - RenderToVertexBufferSharedPtr GL3PlusHardwareBufferManager::createRenderToVertexBuffer() - { - return RenderToVertexBufferSharedPtr(new GL3PlusRenderToVertexBuffer); - } - - VertexDeclaration* GL3PlusHardwareBufferManager::createVertexDeclarationImpl(void) - { - return OGRE_NEW GLVertexArrayObject(); - } - - GLenum GL3PlusHardwareBufferManager::getGLType(VertexElementType type) - { - switch(type) - { - case VET_FLOAT1: - case VET_FLOAT2: - case VET_FLOAT3: - case VET_FLOAT4: - return GL_FLOAT; - case VET_DOUBLE1: - case VET_DOUBLE2: - case VET_DOUBLE3: - case VET_DOUBLE4: - return GL_DOUBLE; - case VET_INT1: - case VET_INT2: - case VET_INT3: - case VET_INT4: - return GL_INT; - case VET_UINT1: - case VET_UINT2: - case VET_UINT3: - case VET_UINT4: - return GL_UNSIGNED_INT; - case VET_SHORT1: - case VET_SHORT2: - case VET_SHORT3: - case VET_SHORT4: - case VET_SHORT2_NORM: - case VET_SHORT4_NORM: - return GL_SHORT; - case VET_USHORT1: - case VET_USHORT2: - case VET_USHORT3: - case VET_USHORT4: - case VET_USHORT2_NORM: - case VET_USHORT4_NORM: - return GL_UNSIGNED_SHORT; - case VET_UBYTE4: - case VET_UBYTE4_NORM: - case _DETAIL_SWAP_RB: - return GL_UNSIGNED_BYTE; - case VET_BYTE4: - case VET_BYTE4_NORM: - return GL_BYTE; - case VET_INT_10_10_10_2_NORM: - return GL_INT_2_10_10_10_REV; - }; - - OgreAssert(false, "unknown Vertex Element Type"); - return 0; - } -} diff --git a/RenderSystems/GL3Plus/src/OgreGL3PlusHardwareOcclusionQuery.cpp b/RenderSystems/GL3Plus/src/OgreGL3PlusHardwareOcclusionQuery.cpp deleted file mode 100644 index 5f9bc3a52a6..00000000000 --- a/RenderSystems/GL3Plus/src/OgreGL3PlusHardwareOcclusionQuery.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGL3PlusHardwareOcclusionQuery.h" -#include "OgreLogManager.h" - -namespace Ogre { - - /** - * This is the base class of the query class for - * hardware occlusion testing. - * - * @author Lee Sandberg email: lee@abcmedia.se - * - * Updated on 12/7/2004 by Chris McGuirk - * - Implemented ARB_occlusion_query - * Updated on 13/9/2005 by Tuan Kuranes email: tuan.kuranes@free.fr - * Updated on 19/3/2012 by David Rogers to ARB_occlusion_query2 - */ - - /** - * Default object constructor - * - */ - GL3PlusHardwareOcclusionQuery::GL3PlusHardwareOcclusionQuery() - { - // Check for hardware occlusion support - OGRE_CHECK_GL_ERROR(glGenQueries(1, &mQueryID )); - } - - /** - * Object destructor - */ - GL3PlusHardwareOcclusionQuery::~GL3PlusHardwareOcclusionQuery() - { - OGRE_CHECK_GL_ERROR(glDeleteQueries(1, &mQueryID)); - } - - void GL3PlusHardwareOcclusionQuery::beginOcclusionQuery() - { - OGRE_CHECK_GL_ERROR(glBeginQuery(GL_ANY_SAMPLES_PASSED, mQueryID)); - } - - void GL3PlusHardwareOcclusionQuery::endOcclusionQuery() - { - OGRE_CHECK_GL_ERROR(glEndQuery(GL_ANY_SAMPLES_PASSED)); - } - - bool GL3PlusHardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments ) - { - OGRE_CHECK_GL_ERROR(glGetQueryObjectuiv(mQueryID, GL_QUERY_RESULT, (GLuint*)NumOfFragments)); - mPixelCount = *NumOfFragments; - return true; - } - - bool GL3PlusHardwareOcclusionQuery::isStillOutstanding(void) - { - GLuint available = GL_FALSE; - - OGRE_CHECK_GL_ERROR(glGetQueryObjectuiv(mQueryID, GL_QUERY_RESULT_AVAILABLE, &available)); - - // GL_TRUE means a wait would occur - return !(available == GL_TRUE); - } - -} diff --git a/RenderSystems/GL3Plus/src/OgreGL3PlusHardwarePixelBuffer.cpp b/RenderSystems/GL3Plus/src/OgreGL3PlusHardwarePixelBuffer.cpp deleted file mode 100644 index dfcffd4588b..00000000000 --- a/RenderSystems/GL3Plus/src/OgreGL3PlusHardwarePixelBuffer.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ - -#include "OgreRenderSystem.h" -#include "OgreGL3PlusHardwareBufferManager.h" -#include "OgreGL3PlusHardwarePixelBuffer.h" -#include "OgreGL3PlusPixelFormat.h" -#include "OgreGL3PlusFBORenderTexture.h" -#include "OgreGL3PlusStateCacheManager.h" -#include "OgreGL3PlusRenderSystem.h" - -#include "OgreRoot.h" -#include "OgreGLSLProgramManager.h" -#include "OgreGLSLMonolithicProgram.h" -#include "OgreGLSLSeparableProgram.h" - -namespace Ogre { - GL3PlusRenderBuffer::GL3PlusRenderBuffer( - GLenum format, uint32 width, uint32 height, GLsizei numSamples) - : GLHardwarePixelBufferCommon( - width, height, 1, - GL3PlusPixelUtil::getClosestOGREFormat(format), HBU_GPU_ONLY), - mRenderbufferID(0) - { - mGLInternalFormat = format; - // Generate renderbuffer - OGRE_CHECK_GL_ERROR(glGenRenderbuffers(1, &mRenderbufferID)); - - mRenderSystem = static_cast(Root::getSingleton().getRenderSystem()); - // Bind it to FBO - mRenderSystem->_getStateCacheManager()->bindGLRenderBuffer( mRenderbufferID ); - - // Allocate storage for depth buffer - if (numSamples > 0) - { - OGRE_CHECK_GL_ERROR(glRenderbufferStorageMultisample(GL_RENDERBUFFER, - numSamples, format, width, height)); - } - else - { - OGRE_CHECK_GL_ERROR(glRenderbufferStorage(GL_RENDERBUFFER, format, - width, height)); - } - } - - GL3PlusRenderBuffer::~GL3PlusRenderBuffer() - { - // Delete renderbuffer - if(GL3PlusStateCacheManager* stateCacheManager = mRenderSystem->_getStateCacheManager()) - stateCacheManager->deleteGLRenderBuffer(mRenderbufferID); - } - - void GL3PlusRenderBuffer::bindToFramebuffer(uint32 attachment, uint32 zoffset) - { - assert(zoffset < mDepth); - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, - GL_RENDERBUFFER, mRenderbufferID)); - } - - -} diff --git a/RenderSystems/GL3Plus/src/OgreGL3PlusPixelFormat.cpp b/RenderSystems/GL3Plus/src/OgreGL3PlusPixelFormat.cpp deleted file mode 100644 index c101f81a10c..00000000000 --- a/RenderSystems/GL3Plus/src/OgreGL3PlusPixelFormat.cpp +++ /dev/null @@ -1,386 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGL3PlusPixelFormat.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" - -#ifndef GL_EXT_texture_compression_s3tc -#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 -#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 -#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 -#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 -#endif - -#ifndef GL_EXT_texture_sRGB -#define GL_SRGB_EXT 0x8C40 -#define GL_SRGB8_EXT 0x8C41 -#define GL_SRGB_ALPHA_EXT 0x8C42 -#define GL_SRGB8_ALPHA8_EXT 0x8C43 -#define GL_SLUMINANCE_ALPHA_EXT 0x8C44 -#define GL_SLUMINANCE8_ALPHA8_EXT 0x8C45 -#define GL_SLUMINANCE_EXT 0x8C46 -#define GL_SLUMINANCE8_EXT 0x8C47 -#define GL_COMPRESSED_SRGB_EXT 0x8C48 -#define GL_COMPRESSED_SRGB_ALPHA_EXT 0x8C49 -#define GL_COMPRESSED_SLUMINANCE_EXT 0x8C4A -#define GL_COMPRESSED_SLUMINANCE_ALPHA_EXT 0x8C4B -#define GL_COMPRESSED_SRGB_S3TC_DXT1_EXT 0x8C4C -#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT 0x8C4D -#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT 0x8C4E -#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT 0x8C4F -#endif - - -namespace Ogre { - - struct GLPixelFormatDescription { - GLenum format; - GLenum type; - GLenum internalFormat; - }; - - static GLPixelFormatDescription _pixelFormats[] = { - {GL_NONE}, // PF_UNKNOWN - {GL_RED, GL_UNSIGNED_BYTE, GL_R8}, // PF_L8 - {GL_RED, GL_UNSIGNED_SHORT, GL_R16}, // PF_L16 - {GL_RED, GL_UNSIGNED_BYTE, GL_R8}, // PF_A8 - {GL_RG, GL_UNSIGNED_BYTE, GL_RG8}, // PF_BYTE_LA - {GL_RGB, GL_UNSIGNED_SHORT_5_6_5, GL_RGB5}, // PF_R5G6B5 - {GL_BGR, GL_UNSIGNED_SHORT_5_6_5, GL_RGB5}, // PF_B5G6R5 - {GL_BGRA, GL_UNSIGNED_SHORT_4_4_4_4_REV, GL_RGBA4}, // PF_A4R4G4B4 - {GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, GL_RGB5_A1},// PF_A1R5G5B5 -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - {GL_RGB, GL_UNSIGNED_BYTE, GL_RGB8}, // PF_R8G8B8 - {GL_BGR, GL_UNSIGNED_BYTE, GL_RGB8}, // PF_B8G8R8 -#else - {GL_BGR, GL_UNSIGNED_BYTE, GL_RGB8}, // PF_R8G8B8 - {GL_RGB, GL_UNSIGNED_BYTE, GL_RGB8}, // PF_B8G8R8 -#endif - {GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, GL_RGBA8}, // PF_A8R8G8B8 - {GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, GL_RGBA8}, // PF_A8B8G8R8 - {GL_BGRA, GL_UNSIGNED_INT_8_8_8_8, GL_RGBA8}, // PF_B8G8R8A8 - {GL_BGRA_INTEGER, GL_UNSIGNED_INT_2_10_10_10_REV, GL_RGB10_A2UI}, // PF_A2R10G10B10 - {GL_RGBA_INTEGER, GL_UNSIGNED_INT_2_10_10_10_REV, GL_RGB10_A2UI}, // PF_A2B10G10R10 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT},// PF_DXT1 - {GL_NONE}, // PF_DXT2 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT},// PF_DXT3 - {GL_NONE}, // PF_DXT4 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT},// PF_DXT5 - {GL_RGB, GL_HALF_FLOAT, GL_RGB16F}, // PF_FLOAT16_RGB - {GL_RGBA, GL_HALF_FLOAT, GL_RGBA16F}, // PF_FLOAT16_RGBA - {GL_RGB, GL_FLOAT, GL_RGB32F}, // PF_FLOAT32_RGB - {GL_RGBA, GL_FLOAT, GL_RGBA32F}, // PF_FLOAT32_RGBA - {GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, GL_RGBA8}, // PF_X8R8G8B8 - {GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, GL_RGBA8}, // PF_X8B8G8R8 - {GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, GL_RGBA8}, // PF_R8G8B8A8 - {GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, GL_DEPTH_COMPONENT16}, // PF_DEPTH16 - {GL_RGBA, GL_UNSIGNED_SHORT, GL_RGBA16}, // PF_SHORT_RGBA - {GL_RGB, GL_UNSIGNED_BYTE_3_3_2, GL_R3_G3_B2}, // PF_R3G3B2 - {GL_RED, GL_HALF_FLOAT, GL_R16F}, // PF_FLOAT16_R - {GL_RED, GL_FLOAT, GL_R32F}, // PF_FLOAT32_R - {GL_RG, GL_UNSIGNED_SHORT, GL_RG16}, // PF_SHORT_GR - {GL_RG, GL_HALF_FLOAT, GL_RG16F}, // PF_FLOAT16_GR - {GL_RG, GL_FLOAT, GL_RG32F}, // PF_FLOAT32_GR - {GL_RGB, GL_UNSIGNED_SHORT, GL_RGB16}, // PF_SHORT_RGB - {GL_NONE}, // PF_PVRTC_RGB2 - {GL_NONE}, // PF_PVRTC_RGBA2 - {GL_NONE}, // PF_PVRTC_RGB4 - {GL_NONE}, // PF_PVRTC_RGBA4 - {GL_NONE}, // PF_PVRTC2_2BPP - {GL_NONE}, // PF_PVRTC2_4BPP - {GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, GL_R11F_G11F_B10F}, // PF_R11G11B10_FLOAT - {GL_RED_INTEGER, GL_UNSIGNED_BYTE, GL_R8UI}, // PF_R8_UINT - {GL_RG_INTEGER, GL_UNSIGNED_BYTE, GL_RG8UI}, // PF_R8G8_UINT - {GL_RGB_INTEGER, GL_UNSIGNED_BYTE, GL_RGB8UI}, // PF_R8G8B8_UINT - {GL_RGBA_INTEGER, GL_UNSIGNED_BYTE, GL_RGBA8UI}, // PF_R8G8B8A8_UINT - {GL_RED_INTEGER, GL_UNSIGNED_SHORT, GL_R16UI}, // PF_R16_UINT - {GL_RG_INTEGER, GL_UNSIGNED_SHORT, GL_RG16UI}, // PF_R16G16_UINT - {GL_RGB_INTEGER, GL_UNSIGNED_SHORT, GL_RGB16UI}, // PF_R16G16B16_UINT - {GL_RGBA_INTEGER, GL_UNSIGNED_SHORT, GL_RGBA16UI}, // PF_R16G16B16A16_UINT - {GL_RED_INTEGER, GL_UNSIGNED_INT, GL_R32UI}, // PF_R32_UINT - {GL_RG_INTEGER, GL_UNSIGNED_INT, GL_RG32UI}, // PF_R32G32_UINT - {GL_RGB_INTEGER, GL_UNSIGNED_INT, GL_RGB32UI}, // PF_R32G32B32_UINT - {GL_RGBA_INTEGER, GL_UNSIGNED_INT, GL_RGBA32UI}, // PF_R32G32B32A32_UINT - {GL_RED_INTEGER, GL_BYTE, GL_R8I}, // PF_R8_SINT - {GL_RG_INTEGER, GL_BYTE, GL_RG8I}, // PF_R8G8_SINT - {GL_RGB_INTEGER, GL_BYTE, GL_RGB8I}, // PF_R8G8B8_SINT - {GL_RGBA_INTEGER, GL_BYTE, GL_RGBA8I}, // PF_R8G8B8A8_SINT - {GL_RED_INTEGER, GL_SHORT, GL_R16I}, // PF_R16_SINT - {GL_RG_INTEGER, GL_SHORT, GL_RG16I}, // PF_R16G16_SINT - {GL_RGB_INTEGER, GL_SHORT, GL_RGB16I}, // PF_R16G16B16_SINT - {GL_RGBA_INTEGER, GL_SHORT, GL_RGBA16I}, // PF_R16G16B16A16_SINT - {GL_RED_INTEGER, GL_INT, GL_R32I}, // PF_R32_SINT - {GL_RG_INTEGER, GL_INT, GL_RG32I}, // PF_R32G32_SINT - {GL_RGB_INTEGER, GL_INT, GL_RGB32I}, // PF_R32G32B32_SINT - {GL_RGBA_INTEGER, GL_INT, GL_RGBA32I}, // PF_R32G32B32A32_SINT - {GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV, GL_RGB9_E5}, // PF_R9G9B9E5_SHAREDEXP - {GL_NONE, GL_NONE, GL_COMPRESSED_RED_RGTC1}, // PF_BC4_UNORM - {GL_NONE, GL_NONE, GL_COMPRESSED_SIGNED_RED_RGTC1}, // PF_BC4_SNORM - {GL_NONE, GL_NONE, GL_COMPRESSED_RG_RGTC2}, // PF_BC5_UNORM - {GL_NONE, GL_NONE, GL_COMPRESSED_SIGNED_RG_RGTC2}, // PF_BC5_SNORM - {GL_NONE, GL_NONE, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB},// PF_BC6H_UF16 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB}, // PF_BC6H_SF16 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_BPTC_UNORM_ARB}, // PF_BC7_UNORM - {GL_RED, GL_UNSIGNED_BYTE, GL_R8}, // PF_R8 - {GL_RG, GL_UNSIGNED_BYTE, GL_RG8}, // PF_RG8 - {GL_RED, GL_UNSIGNED_BYTE, GL_R8_SNORM}, // PF_R8_SNORM - {GL_RG, GL_UNSIGNED_BYTE, GL_RG8_SNORM}, // PF_RG8_SNORM - {GL_RGB, GL_UNSIGNED_BYTE, GL_RGB8_SNORM}, // PF_RGB8_SNORM - {GL_RGBA, GL_UNSIGNED_BYTE, GL_RGBA8_SNORM}, // PF_RGBA8_SNORM - {GL_RED, GL_UNSIGNED_SHORT, GL_R16_SNORM}, // PF_R16_SNORM - {GL_RG, GL_UNSIGNED_SHORT, GL_RG16_SNORM}, // PF_RG16_SNORM - {GL_RGB, GL_UNSIGNED_SHORT, GL_RGB16_SNORM}, // PF_RGB16_SNORM - {GL_RGBA, GL_UNSIGNED_SHORT, GL_RGBA16_SNORM}, // PF_RGBA16_SNORM - {GL_NONE}, // PF_ETC1_RGB8 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGB8_ETC2}, // PF_ETC2_RGB8 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA8_ETC2_EAC}, // PF_ETC2_RGBA8 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2},// PF_ETC2_RGB8A1 - {GL_NONE}, // PF_ATC_RGB - {GL_NONE}, // PF_ATC_RGBA_EXPLICIT_ALPHA - {GL_NONE}, // PF_ATC_RGBA_INTERPOLATED_ALPHA - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_4x4_KHR}, // PF_ASTC_RGBA_4X4_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_5x4_KHR}, // PF_ASTC_RGBA_5X4_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_5x5_KHR}, // PF_ASTC_RGBA_5X5_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_6x5_KHR}, // PF_ASTC_RGBA_6X5_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_6x6_KHR}, // PF_ASTC_RGBA_6X6_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_8x5_KHR}, // PF_ASTC_RGBA_8X5_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_8x6_KHR}, // PF_ASTC_RGBA_8X6_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_8x8_KHR}, // PF_ASTC_RGBA_8X8_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_10x5_KHR},// PF_ASTC_RGBA_10X5_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_10x6_KHR},// PF_ASTC_RGBA_10X6_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_10x8_KHR},// PF_ASTC_RGBA_10X8_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_10x10_KHR},// PF_ASTC_RGBA_10X10_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_12x10_KHR},// PF_ASTC_RGBA_12X10_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_12x12_KHR},// PF_ASTC_RGBA_12X12_LDR - {GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, GL_DEPTH_COMPONENT32}, // PF_DEPTH32 - {GL_DEPTH_COMPONENT, GL_FLOAT, GL_DEPTH_COMPONENT32F}, // PF_DEPTH32F - {GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, GL_DEPTH24_STENCIL8}, // PF_DEPTH24_STENCIL8 - }; - - GLenum GL3PlusPixelUtil::getGLOriginFormat(PixelFormat pf) - { - static_assert(sizeof(_pixelFormats)/sizeof(GLPixelFormatDescription) == PF_COUNT, "Did you add a new format?"); - return _pixelFormats[pf].format; - } - - GLenum GL3PlusPixelUtil::getGLOriginDataType(PixelFormat pf) - { - return _pixelFormats[pf].type; - } - - GLenum GL3PlusPixelUtil::getGLInternalFormat(PixelFormat pf, bool hwGamma) - { - GLenum ret = _pixelFormats[pf].internalFormat; - - if(!hwGamma) - return ret; - - switch(ret) - { - case GL_RGB8: - return GL_SRGB8; - case GL_RGBA8: - return GL_SRGB8_ALPHA8; - case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: - return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; - case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: - return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; - case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: - return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; - case GL_COMPRESSED_RGBA_BPTC_UNORM_ARB: - return GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB; - case GL_COMPRESSED_RGBA_ASTC_4x4_KHR: - case GL_COMPRESSED_RGBA_ASTC_5x4_KHR: - case GL_COMPRESSED_RGBA_ASTC_5x5_KHR: - case GL_COMPRESSED_RGBA_ASTC_6x5_KHR: - case GL_COMPRESSED_RGBA_ASTC_6x6_KHR: - case GL_COMPRESSED_RGBA_ASTC_8x5_KHR: - case GL_COMPRESSED_RGBA_ASTC_8x6_KHR: - case GL_COMPRESSED_RGBA_ASTC_8x8_KHR: - case GL_COMPRESSED_RGBA_ASTC_10x5_KHR: - case GL_COMPRESSED_RGBA_ASTC_10x6_KHR: - case GL_COMPRESSED_RGBA_ASTC_10x8_KHR: - case GL_COMPRESSED_RGBA_ASTC_10x10_KHR: - case GL_COMPRESSED_RGBA_ASTC_12x10_KHR: - case GL_COMPRESSED_RGBA_ASTC_12x12_KHR: - return ret + 0x20; // ASTC SRGBA format offset - default: - return ret; - } - } - - GLenum GL3PlusPixelUtil::getGLImageInternalFormat(PixelFormat format) - { - switch(format) - { - case PF_L8: - case PF_A8: - return GL_R8; - case PF_L16: - return GL_R16; - case PF_BYTE_LA: - return GL_RG8; - case PF_A8R8G8B8: - case PF_B8G8R8A8: - case PF_A8B8G8R8: - case PF_R8G8B8A8: - return GL_RGBA8; - case PF_A2R10G10B10: - case PF_A2B10G10R10: - //return GL_RGB10_A2UI; - return GL_RGB10_A2; - case PF_FLOAT16_R: - return GL_R16F; - case PF_FLOAT16_GR: - return GL_RG16F; - case PF_FLOAT16_RGBA: - return GL_RGBA16F; - case PF_FLOAT32_R: - return GL_R32F; - case PF_FLOAT32_GR: - return GL_RG32F; - case PF_FLOAT32_RGBA: - return GL_RGBA32F; - case PF_SHORT_RGBA: - return GL_RGBA16; - case PF_SHORT_GR: - return GL_RG16; - case PF_R11G11B10_FLOAT: - return GL_R11F_G11F_B10F; - case PF_R8_UINT: - return GL_R8UI; - case PF_R8G8_UINT: - return GL_RG8UI; - case PF_R8G8B8A8_UINT: - return GL_RGBA8UI; - case PF_R16_UINT: - return GL_R16UI; - case PF_R16G16_UINT: - return GL_RG16UI; - case PF_R16G16B16A16_UINT: - return GL_RGBA16UI; - case PF_R32_UINT: - return GL_R32UI; - case PF_R32G32_UINT: - return GL_RG32UI; - case PF_R32G32B32A32_UINT: - return GL_RGBA32UI; - case PF_R8_SINT: - return GL_R8I; - case PF_R8G8_SINT: - return GL_RG8I; - case PF_R8G8B8_SINT: - return GL_RG8I; - case PF_R16_SINT: - return GL_R16I; - case PF_R16G16_SINT: - return GL_RG16I; - case PF_R16G16B16A16_SINT: - return GL_RGBA16I; - case PF_R32_SINT: - return GL_R32I; - case PF_R32G32_SINT: - return GL_RG32I; - case PF_R32G32B32A32_SINT: - return GL_RGBA32I; - case PF_R8G8_SNORM: - return GL_RG8_SNORM; - case PF_R16_SNORM: - return GL_R16_SNORM; - case PF_R16G16_SNORM: - return GL_RG16_SNORM; - case PF_R16G16B16A16_SNORM: - return GL_RGBA16_SNORM; - case PF_R8G8B8A8_SNORM: - return GL_RGBA8_SNORM; - - default: - return GL_NONE; - } - } - - - GLenum GL3PlusPixelUtil::getClosestGLImageInternalFormat(PixelFormat format) - { - GLenum GLformat = getGLImageInternalFormat(format); - return (format == GL_NONE ? GL_RGBA8 : GLformat); - } - - - PixelFormat GL3PlusPixelUtil::getClosestOGREFormat(GLenum format) - { - switch(format) - { - case GL_DEPTH_COMPONENT24: - case GL_DEPTH_COMPONENT: - return PF_DEPTH16; - case GL_DEPTH_COMPONENT32: - return PF_DEPTH32; - case GL_DEPTH_COMPONENT32F: - return PF_DEPTH32F; - case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: - return PF_DXT1; - case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: - return PF_DXT3; - case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: - return PF_DXT5; - case GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB: - return PF_BC7_UNORM; - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: - return PixelFormat(int(PF_ASTC_RGBA_4X4_LDR) + - (format - GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR)); - case GL_SRGB8: - case GL_RGB8: // prefer native endian byte format - return PF_BYTE_RGB; - case GL_SRGB8_ALPHA8: - case GL_RGBA8: // prefer native endian byte format - return PF_BYTE_RGBA; - }; - - for(int pf = 0; pf < PF_COUNT; pf++) { - if(_pixelFormats[pf].internalFormat == format) - return (PixelFormat)pf; - } - - return PF_BYTE_RGBA; - } -} diff --git a/RenderSystems/GL3Plus/src/OgreGL3PlusPlugin.cpp b/RenderSystems/GL3Plus/src/OgreGL3PlusPlugin.cpp deleted file mode 100644 index 8ed07505584..00000000000 --- a/RenderSystems/GL3Plus/src/OgreGL3PlusPlugin.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGL3PlusPlugin.h" -#include "OgreRoot.h" -#include "OgreGL3PlusRenderSystem.h" - -namespace Ogre -{ - const String sPluginName = "GL 3+ RenderSystem"; - - GL3PlusPlugin::GL3PlusPlugin() - : mRenderSystem(0) - { - - } - - const String& GL3PlusPlugin::getName() const - { - return sPluginName; - } - - void GL3PlusPlugin::install() - { - mRenderSystem = OGRE_NEW GL3PlusRenderSystem(); - - Root::getSingleton().addRenderSystem(mRenderSystem); - } - - void GL3PlusPlugin::initialise() - { - // nothing to do - } - - void GL3PlusPlugin::shutdown() - { - // nothing to do - } - - void GL3PlusPlugin::uninstall() - { - OGRE_DELETE mRenderSystem; - mRenderSystem = 0; - } -} diff --git a/RenderSystems/GL3Plus/src/OgreGL3PlusRenderSystem.cpp b/RenderSystems/GL3Plus/src/OgreGL3PlusRenderSystem.cpp deleted file mode 100644 index b794d3cceab..00000000000 --- a/RenderSystems/GL3Plus/src/OgreGL3PlusRenderSystem.cpp +++ /dev/null @@ -1,1808 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGL3PlusRenderSystem.h" - -#include "OgreGLUtil.h" -#include "OgreRenderSystem.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreGL3PlusTextureManager.h" -#include "OgreGL3PlusHardwareBuffer.h" -#include "OgreGLSLShader.h" -#include "OgreGpuProgramManager.h" -#include "OgreException.h" -#include "OgreGLSLExtSupport.h" -#include "OgreGL3PlusHardwareOcclusionQuery.h" -#include "OgreGLDepthBufferCommon.h" -#include "OgreGL3PlusHardwarePixelBuffer.h" -#include "OgreGLContext.h" -#include "OgreGL3PlusFBORenderTexture.h" -#include "OgreGL3PlusHardwareBufferManager.h" -#include "OgreGLSLProgramManager.h" -#include "OgreGLSLSeparableProgram.h" -#include "OgreGLVertexArrayObject.h" -#include "OgreRoot.h" -#include "OgreConfig.h" -#include "OgreViewport.h" -#include "OgreGL3PlusPixelFormat.h" -#include "OgreGL3PlusStateCacheManager.h" -#include "OgreGLSLProgramCommon.h" -#include "OgreGL3PlusFBOMultiRenderTarget.h" -#include "OgreSPIRVShaderFactory.h" - - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE -extern "C" void glFlushRenderAPPLE(); -#endif - -#ifndef GL_EXT_texture_filter_anisotropic -#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE -#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF -#endif - -static void APIENTRY GLDebugCallback(GLenum source, - GLenum type, - GLuint id, - GLenum severity, - GLsizei length, - const GLchar* message, - const GLvoid* userParam) -{ - const char *debSource = "", *debType = "", *debSev = ""; - - auto lml = Ogre::LML_NORMAL; - - if (source == GL_DEBUG_SOURCE_API) - debSource = "OpenGL"; - else if (source == GL_DEBUG_SOURCE_WINDOW_SYSTEM) - debSource = "Windows"; - else if (source == GL_DEBUG_SOURCE_SHADER_COMPILER) - debSource = "Shader Compiler"; - else if (source == GL_DEBUG_SOURCE_THIRD_PARTY) - debSource = "Third Party"; - else if (source == GL_DEBUG_SOURCE_APPLICATION) - debSource = "Application"; - else if (source == GL_DEBUG_SOURCE_OTHER) - debSource = "Other"; - - if (type == GL_DEBUG_TYPE_ERROR) - debType = "error"; - else if (type == GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR) - debType = "deprecated behavior"; - else if (type == GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR) - debType = "undefined behavior"; - else if (type == GL_DEBUG_TYPE_PORTABILITY) - debType = "portability"; - else if (type == GL_DEBUG_TYPE_PERFORMANCE) - debType = "performance"; - else if (type == GL_DEBUG_TYPE_OTHER) - debType = "message"; - - if (severity == GL_DEBUG_SEVERITY_HIGH) - { - debSev = "high"; - lml = Ogre::LML_CRITICAL; - } - else if (severity == GL_DEBUG_SEVERITY_MEDIUM) - { - debSev = "medium"; - lml = Ogre::LML_WARNING; - } - else if (severity == GL_DEBUG_SEVERITY_LOW) - debSev = "low"; - else if (severity == GL_DEBUG_SEVERITY_NOTIFICATION) - debSev = "note"; - - Ogre::LogManager::getSingleton().stream(lml) << debSource << ":" << debType << "(" << debSev << ") - " << message; -} - -namespace Ogre { - - static GLNativeSupport* glsupport; - static GL3WglProc get_proc(const char* proc) { - return (GL3WglProc)glsupport->getProcAddress(proc); - } - - GL3PlusRenderSystem::GL3PlusRenderSystem() - : mDepthWrite(true), - mStencilWriteMask(0xFFFFFFFF), - mStateCacheManager(0), - mProgramManager(0), - mGLSLShaderFactory(0), - mSPIRVShaderFactory(0), - mHardwareBufferManager(0), - mActiveTextureUnit(0) - { - size_t i; - - LogManager::getSingleton().logMessage(getName() + " created."); - - // Get our GLSupport - mGLSupport = getGLSupport(); - glsupport = mGLSupport; - - initConfigOptions(); - - for (i = 0; i < OGRE_MAX_TEXTURE_LAYERS; i++) - { - // Dummy value - mTextureTypes[i] = 0; - } - - mActiveRenderTarget = 0; - mCurrentContext = 0; - mMainContext = 0; - mGLInitialised = false; - mMinFilter = FO_LINEAR; - mMipFilter = FO_POINT; - mCurrentShader.fill(NULL); - mLargestSupportedAnisotropy = 1; - mRTTManager = NULL; - mSeparateShaderObjectsEnabled = false; - } - - GL3PlusRenderSystem::~GL3PlusRenderSystem() - { - shutdown(); - - if (mGLSupport) - OGRE_DELETE mGLSupport; - } - - const String& GL3PlusRenderSystem::getName(void) const - { - static String strName("OpenGL 3+ Rendering Subsystem"); - return strName; - } - - void GL3PlusRenderSystem::_initialise() - { - RenderSystem::_initialise(); - mGLSupport->start(); - } - - void GL3PlusRenderSystem::initConfigOptions() - { - GLRenderSystemCommon::initConfigOptions(); - - ConfigOption opt; - opt.name = "Reversed Z-Buffer"; - opt.possibleValues = {"No", "Yes"}; - opt.currentValue = opt.possibleValues[0]; - opt.immutable = false; - - mOptions[opt.name] = opt; - - opt.name = "Separate Shader Objects"; - opt.possibleValues = {"No", "Yes"}; - opt.currentValue = opt.possibleValues[1]; - opt.immutable = false; - - mOptions[opt.name] = opt; - - opt.name = "Debug Layer"; - opt.possibleValues = {"Off", "On"}; - opt.currentValue = opt.possibleValues[0]; - opt.immutable = false; - - mOptions[opt.name] = opt; - } - - RenderSystemCapabilities* GL3PlusRenderSystem::createRenderSystemCapabilities() const - { - RenderSystemCapabilities* rsc = OGRE_NEW RenderSystemCapabilities(); - - rsc->setCategoryRelevant(CAPS_CATEGORY_GL, true); - rsc->setDriverVersion(mDriverVersion); - - const char* deviceName = (const char*)glGetString(GL_RENDERER); - if (deviceName) - { - rsc->setDeviceName(deviceName); - } - - rsc->setRenderSystemName(getName()); - rsc->setVendor(mVendor); - - // Check for hardware mipmapping support. - rsc->setCapability(RSC_AUTOMIPMAP_COMPRESSED); - - // Multitexturing support and set number of texture units - GLint units; - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &units)); - rsc->setNumTextureUnits(std::min(OGRE_MAX_TEXTURE_LAYERS, units)); - - glGetIntegerv( GL_MAX_VERTEX_ATTRIBS , &units); - rsc->setNumVertexAttributes(units); - - // Check for Anisotropy support - if (checkExtension("GL_EXT_texture_filter_anisotropic")) - { - GLfloat maxAnisotropy = 0; - OGRE_CHECK_GL_ERROR(glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maxAnisotropy)); - rsc->setMaxSupportedAnisotropy(maxAnisotropy); - rsc->setCapability(RSC_ANISOTROPY); - } - - // Point sprites - rsc->setCapability(RSC_POINT_SPRITES); - - // Check for hardware stencil support and set bit depth - rsc->setCapability(RSC_HWSTENCIL); - rsc->setCapability(RSC_TWO_SIDED_STENCIL); - - rsc->setCapability(RSC_HW_GAMMA); - - // Vertex Buffer Objects are always supported - rsc->setCapability(RSC_MAPBUFFER); - rsc->setCapability(RSC_32BIT_INDEX); - - // Vertex Array Objects are supported in 3.0 - rsc->setCapability(RSC_VAO); - - // Check for texture compression - rsc->setCapability(RSC_TEXTURE_COMPRESSION); - - // Check for dxt compression - if (checkExtension("GL_EXT_texture_compression_s3tc")) - { - rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT); - } - - // Check for etc compression - if (hasMinGLVersion(4, 3) || checkExtension("GL_ARB_ES3_compatibility")) - { - rsc->setCapability(RSC_TEXTURE_COMPRESSION_ETC2); - } - - // Check for vtc compression - if (checkExtension("GL_NV_texture_compression_vtc")) - { - rsc->setCapability(RSC_TEXTURE_COMPRESSION_VTC); - } - - // RGTC(BC4/BC5) is supported by the 3.0 spec - rsc->setCapability(RSC_TEXTURE_COMPRESSION_BC4_BC5); - - // BPTC(BC6H/BC7) is supported by the extension or OpenGL 4.2 or higher - if (hasMinGLVersion(4, 2) || checkExtension("GL_ARB_texture_compression_bptc")) - { - rsc->setCapability(RSC_TEXTURE_COMPRESSION_BC6H_BC7); - } - - if (checkExtension("WEBGL_compressed_texture_astc") || - checkExtension("GL_KHR_texture_compression_astc_ldr")) - rsc->setCapability(RSC_TEXTURE_COMPRESSION_ASTC); - - rsc->setCapability(RSC_HWRENDER_TO_TEXTURE); - // Probe number of draw buffers - // Only makes sense with FBO support, so probe here - GLint buffers; - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_DRAW_BUFFERS, &buffers)); - rsc->setNumMultiRenderTargets(std::min(buffers, (GLint)OGRE_MAX_MULTIPLE_RENDER_TARGETS)); - - // Stencil wrapping - rsc->setCapability(RSC_STENCIL_WRAP); - - // Check for non-power-of-2 texture support - rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES); - - // Check for SSBO support - if (hasMinGLVersion(4, 3) || checkExtension("GL_ARB_shader_storage_buffer_object")) - rsc->setCapability(RSC_READ_WRITE_BUFFERS); - - // As are user clipping planes - rsc->setCapability(RSC_USER_CLIP_PLANES); - - // So are 1D & 3D textures - rsc->setCapability(RSC_TEXTURE_1D); - rsc->setCapability(RSC_TEXTURE_3D); - rsc->setCapability(RSC_TEXTURE_2D_ARRAY); - - rsc->setCapability(RSC_DEPTH_CLAMP); - - // Check for hardware occlusion support - rsc->setCapability(RSC_HWOCCLUSION); - - // Point size - GLfloat psRange[2] = {0.0, 0.0}; - OGRE_CHECK_GL_ERROR(glGetFloatv(GL_POINT_SIZE_RANGE, psRange)); - rsc->setMaxPointSize(psRange[1]); - - // GLSL is always supported in GL - // TODO: Deprecate this profile name in favor of versioned names - rsc->addShaderProfile("glsl"); - - // Support for specific shader profiles - bool limitedOSXCoreProfile = OGRE_PLATFORM == OGRE_PLATFORM_APPLE && hasMinGLVersion(3, 2); - - for (uint16 ver = getNativeShadingLanguageVersion(); ver >= 400; ver -= 10) - rsc->addShaderProfile("glsl" + StringConverter::toString(ver)); - - if (getNativeShadingLanguageVersion() >= 330) - rsc->addShaderProfile("glsl330"); - if (getNativeShadingLanguageVersion() >= 150) - rsc->addShaderProfile("glsl150"); - if (getNativeShadingLanguageVersion() >= 140 && !limitedOSXCoreProfile) - rsc->addShaderProfile("glsl140"); - if (getNativeShadingLanguageVersion() >= 130 && !limitedOSXCoreProfile) - rsc->addShaderProfile("glsl130"); - - if (mSeparateShaderObjectsEnabled && - (hasMinGLVersion(4, 3) || - (checkExtension("GL_ARB_separate_shader_objects") && checkExtension("GL_ARB_program_interface_query")))) - { - rsc->setCapability(RSC_SEPARATE_SHADER_OBJECTS); - rsc->setCapability(RSC_GLSL_SSO_REDECLARE); - } - - if (checkExtension("GL_ARB_gl_spirv") && rsc->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) - rsc->addShaderProfile("gl_spirv"); - - // Mesa 11.2 does not behave according to spec and throws a "gl_Position redefined" - if(rsc->getDeviceName().find("Mesa") != String::npos) { - rsc->unsetCapability(RSC_GLSL_SSO_REDECLARE); - } - - // Vertex/Fragment Programs - rsc->setCapability(RSC_VERTEX_PROGRAM); - - GLint constantCount = 0; - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS, &constantCount)); - rsc->setVertexProgramConstantFloatCount((Ogre::ushort)constantCount/4); - - // Fragment Program Properties - constantCount = 0; - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, &constantCount)); - rsc->setFragmentProgramConstantFloatCount((Ogre::ushort)constantCount/4); - - // Geometry Program Properties - rsc->setCapability(RSC_GEOMETRY_PROGRAM); - - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_COMPONENTS, &constantCount)); - rsc->setGeometryProgramConstantFloatCount(constantCount/4); - - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES, &constantCount)); - rsc->setGeometryProgramNumOutputVertices(constantCount/4); - - // Tessellation Program Properties - if (hasMinGLVersion(4, 0) || checkExtension("GL_ARB_tessellation_shader")) - { - rsc->setCapability(RSC_TESSELLATION_HULL_PROGRAM); - rsc->setCapability(RSC_TESSELLATION_DOMAIN_PROGRAM); - - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS, &constantCount)); - // float params - rsc->setTessellationHullProgramConstantFloatCount(constantCount/4); - - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS, &constantCount)); - // float params - rsc->setTessellationDomainProgramConstantFloatCount(constantCount/4); - } - - // Compute Program Properties - if (hasMinGLVersion(4, 3) || checkExtension("GL_ARB_compute_shader")) - { - rsc->setCapability(RSC_COMPUTE_PROGRAM); - - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_COMPUTE_UNIFORM_COMPONENTS, &constantCount)); - rsc->setComputeProgramConstantFloatCount(constantCount); - - //TODO we should also check max workgroup count & size - // OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_COMPUTE_WORK_GROUP_SIZE, &workgroupCount)); - // OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS, &workgroupInvocations)); - } - - if (hasMinGLVersion(4, 1) || checkExtension("GL_ARB_get_program_binary")) - { - GLint formats = 0; - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS, &formats)); - - if (formats > 0) - rsc->setCapability(RSC_CAN_GET_COMPILED_SHADER_BUFFER); - } - - rsc->setCapability(RSC_VERTEX_FORMAT_INT_10_10_10_2); - rsc->setCapability(RSC_VERTEX_BUFFER_INSTANCE_DATA); - - // Check for Float textures - rsc->setCapability(RSC_TEXTURE_FLOAT); - - // OpenGL 3.0 requires a minimum of 16 texture image units - units = std::max(16, units); - - rsc->setNumVertexTextureUnits(static_cast(units)); - rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH); - - // Mipmap LOD biasing? - rsc->setCapability(RSC_MIPMAP_LOD_BIAS); - - // Alpha to coverage always 'supported' when MSAA is available - // although card may ignore it if it doesn't specifically support A2C - rsc->setCapability(RSC_ALPHA_TO_COVERAGE); - - // Check if render to vertex buffer (transform feedback in OpenGL) - rsc->setCapability(RSC_HWRENDER_TO_VERTEX_BUFFER); - - if (hasMinGLVersion(4, 3) || checkExtension("GL_KHR_debug")) - rsc->setCapability(RSC_DEBUG); - - if( hasMinGLVersion(4, 3) || checkExtension("GL_ARB_ES3_compatibility")) - rsc->setCapability(RSC_PRIMITIVE_RESTART); - - GLfloat lineWidth[2] = {1, 1}; - glGetFloatv(GL_ALIASED_LINE_WIDTH_RANGE, lineWidth); - if(lineWidth[1] != 1 && lineWidth[1] != lineWidth[0]) - rsc->setCapability(RSC_WIDE_LINES); - - return rsc; - } - - void GL3PlusRenderSystem::initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary) - { - mProgramManager = new GLSLProgramManager(this); - // Create GLSL shader factory - mGLSLShaderFactory = new GLSLShaderFactory(); - HighLevelGpuProgramManager::getSingleton().addFactory(mGLSLShaderFactory); - mSPIRVShaderFactory = new SPIRVShaderFactory(); - HighLevelGpuProgramManager::getSingleton().addFactory(mSPIRVShaderFactory); - - // Use VBO's by default - mHardwareBufferManager = new GL3PlusHardwareBufferManager(); - - // Use FBO's for RTT, PBuffers and Copy are no longer supported - // Create FBO manager - mRTTManager = new GL3PlusFBOManager(this); - caps->setCapability(RSC_RTT_DEPTHBUFFER_RESOLUTION_LESSEQUAL); - - // Create the texture manager - mTextureManager = new GL3PlusTextureManager(this); - - mGLInitialised = true; - } - - void GL3PlusRenderSystem::shutdown(void) - { - RenderSystem::shutdown(); - - // Remove from manager safely - if (auto progMgr = HighLevelGpuProgramManager::getSingletonPtr()) - { - if(mGLSLShaderFactory) - progMgr->removeFactory(mGLSLShaderFactory); - - if(mSPIRVShaderFactory) - progMgr->removeFactory(mSPIRVShaderFactory); - } - - OGRE_DELETE mGLSLShaderFactory; - mGLSLShaderFactory = 0; - - OGRE_DELETE mSPIRVShaderFactory; - mSPIRVShaderFactory = 0; - - // Delete extra threads contexts - for (auto pCurContext : mBackgroundContextList) - { - pCurContext->releaseContext(); - OGRE_DELETE pCurContext; - } - mBackgroundContextList.clear(); - - // Deleting the GPU program manager and hardware buffer manager. Has to be done before the mGLSupport->stop(). - delete mProgramManager; - mProgramManager = NULL; - - OGRE_DELETE mHardwareBufferManager; - mHardwareBufferManager = 0; - - OGRE_DELETE mRTTManager; - mRTTManager = 0; - - OGRE_DELETE mTextureManager; - mTextureManager = 0; - - - mGLSupport->stop(); - - // delete mTextureManager; - // mTextureManager = 0; - - mGLInitialised = 0; - - // RenderSystem::shutdown(); - } - - RenderWindow* GL3PlusRenderSystem::_createRenderWindow(const String &name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams) - { - RenderSystem::_createRenderWindow(name, width, height, fullScreen, miscParams); - - // Create the window - RenderWindow* win = mGLSupport->newWindow(name, width, height, fullScreen, miscParams); - attachRenderTarget((Ogre::RenderTarget&) *win); - - if (!mGLInitialised) - { - initialiseContext(win); - - const char* shadingLangVersion = (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION); - StringVector tokens = StringUtil::split(shadingLangVersion, ". "); - mNativeShadingLanguageVersion = (StringConverter::parseUnsignedInt(tokens[0]) * 100) + StringConverter::parseUnsignedInt(tokens[1]); - - auto it = mOptions.find("Reversed Z-Buffer"); - if (it != mOptions.end()) - { - mIsReverseDepthBufferEnabled = StringConverter::parseBool(it->second.currentValue); - - if(mIsReverseDepthBufferEnabled && !hasMinGLVersion(4, 5) && !checkExtension("GL_ARB_clip_control")) - { - mIsReverseDepthBufferEnabled = false; - LogManager::getSingleton().logWarning("Reversed Z-Buffer was requested, but it is not supported. Disabling."); - } - } - - it = mOptions.find("Separate Shader Objects"); - if (it != mOptions.end()) - { - mSeparateShaderObjectsEnabled = StringConverter::parseBool(it->second.currentValue); - } - - // Initialise GL after the first window has been created - // TODO: fire this from emulation options, and don't duplicate Real and Current capabilities - mRealCapabilities = createRenderSystemCapabilities(); - - // use real capabilities if custom capabilities are not available - if (!mUseCustomCapabilities) - mCurrentCapabilities = mRealCapabilities; - - fireEvent("RenderSystemCapabilitiesCreated"); - - initialiseFromRenderSystemCapabilities(mCurrentCapabilities, (RenderTarget *) win); - - // Initialise the main context - _oneTimeContextInitialization(); - if (mCurrentContext) - mCurrentContext->setInitialized(); - } - - if ( win->getDepthBufferPool() != DepthBuffer::POOL_NO_DEPTH ) - { - // Unlike D3D9, OGL doesn't allow sharing the main depth buffer, so keep them separate. - GL3PlusContext *windowContext = dynamic_cast(win)->getContext(); - auto depthBuffer = - new GLDepthBufferCommon(DepthBuffer::POOL_DEFAULT, this, windowContext, 0, 0, win, true); - - mDepthBufferPool[depthBuffer->getPoolId()].push_back( depthBuffer ); - - win->attachDepthBuffer( depthBuffer ); - } - - return win; - } - - - DepthBuffer* GL3PlusRenderSystem::_createDepthBufferFor( RenderTarget *renderTarget ) - { - if ( auto fbo = dynamic_cast(renderTarget)->getFBO() ) - { - // Find best depth & stencil format suited for the RT's format. - GLuint depthFormat, stencilFormat; - _getDepthStencilFormatFor(fbo->getFormat(), &depthFormat, &stencilFormat); - - GL3PlusRenderBuffer *depthBuffer = new GL3PlusRenderBuffer( depthFormat, fbo->getWidth(), - fbo->getHeight(), fbo->getFSAA() ); - - GL3PlusRenderBuffer *stencilBuffer = NULL; - if ( depthFormat == GL_DEPTH24_STENCIL8 || depthFormat == GL_DEPTH32F_STENCIL8) - { - // If we have a packed format, the stencilBuffer is the same as the depthBuffer - stencilBuffer = depthBuffer; - } - else if(stencilFormat) - { - stencilBuffer = new GL3PlusRenderBuffer( stencilFormat, fbo->getWidth(), - fbo->getHeight(), fbo->getFSAA() ); - } - - return new GLDepthBufferCommon(0, this, mCurrentContext, depthBuffer, stencilBuffer, - renderTarget, false); - } - - return NULL; - } - - MultiRenderTarget* GL3PlusRenderSystem::createMultiRenderTarget(const String & name) - { - MultiRenderTarget* retval = - new GL3PlusFBOMultiRenderTarget(static_cast(mRTTManager), name); - attachRenderTarget(*retval); - return retval; - } - - void GL3PlusRenderSystem::destroyRenderWindow(const String& name) - { - // Find it to remove from list. - RenderTarget* pWin = detachRenderTarget(name); - OgreAssert(pWin, "unknown RenderWindow name"); - - GL3PlusContext *windowContext = dynamic_cast(pWin)->getContext(); - - // 1 Window <-> 1 Context, should be always true. - assert( windowContext ); - - bool bFound = false; - // Find the depth buffer from this window and remove it. - DepthBufferMap::iterator itMap = mDepthBufferPool.begin(); - DepthBufferMap::iterator enMap = mDepthBufferPool.end(); - - while( itMap != enMap && !bFound ) - { - DepthBufferVec::iterator itor = itMap->second.begin(); - DepthBufferVec::iterator end = itMap->second.end(); - - while( itor != end ) - { - // A DepthBuffer with no depth & stencil pointers is a dummy one, - // look for the one that matches the same GL context. - auto depthBuffer = static_cast(*itor); - GL3PlusContext *glContext = depthBuffer->getGLContext(); - - if ( glContext == windowContext && - (depthBuffer->getDepthBuffer() || depthBuffer->getStencilBuffer()) ) - { - bFound = true; - - delete *itor; - itMap->second.erase( itor ); - break; - } - ++itor; - } - - ++itMap; - } - - delete pWin; - } - - void GL3PlusRenderSystem::_setTexture(size_t stage, bool enabled, const TexturePtr &texPtr) - { - mStateCacheManager->activateGLTextureUnit(stage); - if (enabled) - { - GL3PlusTexturePtr tex = static_pointer_cast(texPtr); - - // Note used - tex->touch(); - mTextureTypes[stage] = tex->getGL3PlusTextureTarget(); - - mStateCacheManager->bindGLTexture( mTextureTypes[stage], tex->getGLID() ); - } - else - { - // Bind zero texture. - mStateCacheManager->bindGLTexture(GL_TEXTURE_2D, 0); - } - } - - void GL3PlusRenderSystem::_setSampler(size_t unit, Sampler& sampler) - { - static_cast(sampler).bind(unit); - } - - void GL3PlusRenderSystem::_setLineWidth(float width) - { - OGRE_CHECK_GL_ERROR(glLineWidth(width)); - } - - GLenum GL3PlusRenderSystem::getBlendMode(SceneBlendFactor ogreBlend) const - { - switch (ogreBlend) - { - case SBF_ONE: - return GL_ONE; - case SBF_ZERO: - return GL_ZERO; - case SBF_DEST_COLOUR: - return GL_DST_COLOR; - case SBF_SOURCE_COLOUR: - return GL_SRC_COLOR; - case SBF_ONE_MINUS_DEST_COLOUR: - return GL_ONE_MINUS_DST_COLOR; - case SBF_ONE_MINUS_SOURCE_COLOUR: - return GL_ONE_MINUS_SRC_COLOR; - case SBF_DEST_ALPHA: - return GL_DST_ALPHA; - case SBF_SOURCE_ALPHA: - return GL_SRC_ALPHA; - case SBF_ONE_MINUS_DEST_ALPHA: - return GL_ONE_MINUS_DST_ALPHA; - case SBF_ONE_MINUS_SOURCE_ALPHA: - return GL_ONE_MINUS_SRC_ALPHA; - }; - - // To keep compiler happy. - return GL_ONE; - } - - void GL3PlusRenderSystem::_setAlphaRejectSettings(CompareFunction func, unsigned char value, bool alphaToCoverage) - { - mStateCacheManager->setEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE, (func != CMPF_ALWAYS_PASS) && alphaToCoverage); - } - - void GL3PlusRenderSystem::_setViewport(Viewport *vp) - { - // Check if viewport is different - if (!vp) - { - mActiveViewport = NULL; - _setRenderTarget(NULL); - } - - else if (vp != mActiveViewport || vp->_isUpdated()) - { - RenderTarget* target; - - target = vp->getTarget(); - _setRenderTarget(target); - mActiveViewport = vp; - - // Calculate the "lower-left" corner of the viewport - Rect vpRect = vp->getActualDimensions(); - if (!target->requiresTextureFlipping()) - { - // Convert "upper-left" corner to "lower-left" - std::swap(vpRect.top, vpRect.bottom); - vpRect.top = target->getHeight() - vpRect.top; - vpRect.bottom = target->getHeight() - vpRect.bottom; - } - mStateCacheManager->setViewport(vpRect); - - vp->_clearUpdatedFlag(); - } - } - - void GL3PlusRenderSystem::_endFrame(void) - { - // unbind GPU programs at end of frame - // this is mostly to avoid holding bound programs that might get deleted - // outside via the resource manager - unbindGpuProgram(GPT_VERTEX_PROGRAM); - unbindGpuProgram(GPT_FRAGMENT_PROGRAM); - unbindGpuProgram(GPT_GEOMETRY_PROGRAM); - - if (mDriverVersion.major >= 4) - { - unbindGpuProgram(GPT_HULL_PROGRAM); - unbindGpuProgram(GPT_DOMAIN_PROGRAM); - if (mDriverVersion.minor >= 3) - unbindGpuProgram(GPT_COMPUTE_PROGRAM); - } - } - - void GL3PlusRenderSystem::_setCullingMode(CullingMode mode) - { - mCullingMode = mode; - - GLenum cullMode; - bool flip = flipFrontFace(); - OGRE_CHECK_GL_ERROR(glFrontFace(flip ? GL_CW : GL_CCW)); - - switch( mode ) - { - case CULL_NONE: - mStateCacheManager->setEnabled( GL_CULL_FACE, false ); - return; - case CULL_CLOCKWISE: - cullMode = GL_BACK; - break; - case CULL_ANTICLOCKWISE: - cullMode = GL_FRONT; - break; - } - - mStateCacheManager->setEnabled( GL_CULL_FACE, true ); - mStateCacheManager->setCullFace( cullMode ); - } - - void GL3PlusRenderSystem::_setDepthClamp(bool enable) - { - mStateCacheManager->setEnabled(GL_DEPTH_CLAMP, enable); - } - - void GL3PlusRenderSystem::_setDepthBufferParams(bool depthTest, bool depthWrite, CompareFunction depthFunction) - { - if (depthTest) - { - mStateCacheManager->setClearDepth(isReverseDepthBufferEnabled() ? 0.0f : 1.0f); - } - mStateCacheManager->setEnabled(GL_DEPTH_TEST, depthTest); - mStateCacheManager->setDepthMask( depthWrite ); - // Store for reference in _beginFrame - mDepthWrite = depthWrite; - if(isReverseDepthBufferEnabled()) - depthFunction = reverseCompareFunction(depthFunction); - mStateCacheManager->setDepthFunc(convertCompareFunction(depthFunction)); - } - - void GL3PlusRenderSystem::_setDepthBias(float constantBias, float slopeScaleBias) - { - bool enable = constantBias != 0 || slopeScaleBias != 0; - mStateCacheManager->setEnabled(GL_POLYGON_OFFSET_FILL, enable); - mStateCacheManager->setEnabled(GL_POLYGON_OFFSET_POINT, enable); - mStateCacheManager->setEnabled(GL_POLYGON_OFFSET_LINE, enable); - - if (enable) - { - if(isReverseDepthBufferEnabled()) - { - slopeScaleBias *= -1; - constantBias *= -1; - } - - glPolygonOffset(-slopeScaleBias, -constantBias); - } - } - static GLenum getBlendOp(SceneBlendOperation op) - { - switch (op) - { - case SBO_ADD: - return GL_FUNC_ADD; - case SBO_SUBTRACT: - return GL_FUNC_SUBTRACT; - case SBO_REVERSE_SUBTRACT: - return GL_FUNC_REVERSE_SUBTRACT; - case SBO_MIN: - return GL_MIN; - case SBO_MAX: - return GL_MAX; - } - return GL_FUNC_ADD; - } - void GL3PlusRenderSystem::setColourBlendState(const ColourBlendState& state) - { - // record this - mCurrentBlend = state; - - if (state.blendingEnabled()) - { - mStateCacheManager->setEnabled(GL_BLEND, true); - mStateCacheManager->setBlendFunc( - getBlendMode(state.sourceFactor), getBlendMode(state.destFactor), - getBlendMode(state.sourceFactorAlpha), getBlendMode(state.destFactorAlpha)); - } - else - { - mStateCacheManager->setEnabled(GL_BLEND, false); - } - - mStateCacheManager->setBlendEquation(getBlendOp(state.operation), getBlendOp(state.alphaOperation)); - mStateCacheManager->setColourMask(state.writeR, state.writeG, state.writeB, state.writeA); - } - - HardwareOcclusionQuery* GL3PlusRenderSystem::createHardwareOcclusionQuery(void) - { - GL3PlusHardwareOcclusionQuery* ret = new GL3PlusHardwareOcclusionQuery(); - mHwOcclusionQueries.push_back(ret); - return ret; - } - - void GL3PlusRenderSystem::_setPolygonMode(PolygonMode level) - { - switch(level) - { - case PM_POINTS: - mStateCacheManager->setPolygonMode(GL_POINT); - break; - case PM_WIREFRAME: - mStateCacheManager->setPolygonMode(GL_LINE); - break; - case PM_SOLID: - mStateCacheManager->setPolygonMode(GL_FILL); - break; - } - } - - void GL3PlusRenderSystem::setStencilState(const StencilState& state) - { - mStateCacheManager->setEnabled(GL_STENCIL_TEST, state.enabled); - - if(!state.enabled) - return; - bool flip = false; - mStencilWriteMask = state.writeMask; - - auto compareOp = convertCompareFunction(state.compareOp); - - if (state.twoSidedOperation) - { - // Back - OGRE_CHECK_GL_ERROR(glStencilMaskSeparate(GL_BACK, state.writeMask)); - OGRE_CHECK_GL_ERROR(glStencilFuncSeparate(GL_BACK, compareOp, state.referenceValue, state.compareMask)); - OGRE_CHECK_GL_ERROR(glStencilOpSeparate(GL_BACK, - convertStencilOp(state.stencilFailOp, !flip), - convertStencilOp(state.depthFailOp, !flip), - convertStencilOp(state.depthStencilPassOp, !flip))); - - // Front - OGRE_CHECK_GL_ERROR(glStencilMaskSeparate(GL_FRONT, state.writeMask)); - OGRE_CHECK_GL_ERROR(glStencilFuncSeparate(GL_FRONT, compareOp, state.referenceValue, state.compareMask)); - OGRE_CHECK_GL_ERROR(glStencilOpSeparate(GL_FRONT, - convertStencilOp(state.stencilFailOp, flip), - convertStencilOp(state.depthFailOp, flip), - convertStencilOp(state.depthStencilPassOp, flip))); - } - else - { - mStateCacheManager->setStencilMask(state.writeMask); - OGRE_CHECK_GL_ERROR(glStencilFunc(compareOp, state.referenceValue, state.compareMask)); - OGRE_CHECK_GL_ERROR(glStencilOp( - convertStencilOp(state.stencilFailOp, flip), - convertStencilOp(state.depthFailOp, flip), - convertStencilOp(state.depthStencilPassOp, flip))); - } - } - - void GL3PlusRenderSystem::_dispatchCompute(const Vector3i& workgroupDim) - { - // if(mComputeProgramExecutions <= compute_execution_cap) - - //FIXME give user control over when and what memory barriers are created - // if (mPreComputeMemoryBarrier) - OGRE_CHECK_GL_ERROR(glMemoryBarrier(GL_ALL_BARRIER_BITS)); - OGRE_CHECK_GL_ERROR(glDispatchCompute(workgroupDim[0], workgroupDim[1], workgroupDim[2])); - // if (mPostComputeMemoryBarrier) - // OGRE_CHECK_GL_ERROR(glMemoryBarrier(toGL(MB_TEXTURE))); - // if (compute_execution_cap > 0) - // mComputeProgramExecutions++; - } - - void GL3PlusRenderSystem::_render(const RenderOperation& op) - { - // Call super class. - RenderSystem::_render(op); - - if (!mProgramManager->getActiveProgram()) - { - LogManager::getSingleton().logError("Failed to create shader program."); - } - - GLVertexArrayObject* vao = - static_cast(op.vertexData->vertexDeclaration); - // Bind VAO (set of per-vertex attributes: position, normal, etc.). - vao->bind(this); - bool updateVAO = vao->needsUpdate(op.vertexData->vertexBufferBinding, 0); - - if (updateVAO) - vao->bindToGpu(this, op.vertexData->vertexBufferBinding, 0); - - // We treat index buffer binding inside VAO as volatile, always updating and never relying onto it, - // as one shared vertex buffer could be rendered with several index buffers, from submeshes and/or LODs - if (op.useIndexes) - mStateCacheManager->bindGLBuffer(GL_ELEMENT_ARRAY_BUFFER, - op.indexData->indexBuffer->_getImpl()->getGLBufferId()); - - auto numberOfInstances = op.numberOfInstances; - - // Determine the correct primitive type to render. - GLint primType; - switch (op.operationType) - { - case RenderOperation::OT_POINT_LIST: - primType = GL_POINTS; - break; - case RenderOperation::OT_LINE_LIST: - primType = GL_LINES; - break; - case RenderOperation::OT_LINE_LIST_ADJ: - primType = GL_LINES_ADJACENCY; - break; - case RenderOperation::OT_LINE_STRIP: - primType = GL_LINE_STRIP; - break; - case RenderOperation::OT_LINE_STRIP_ADJ: - primType = GL_LINE_STRIP_ADJACENCY; - break; - default: - case RenderOperation::OT_TRIANGLE_LIST: - primType = GL_TRIANGLES; - break; - case RenderOperation::OT_TRIANGLE_LIST_ADJ: - primType = GL_TRIANGLES_ADJACENCY; - break; - case RenderOperation::OT_TRIANGLE_STRIP: - primType = GL_TRIANGLE_STRIP; - break; - case RenderOperation::OT_TRIANGLE_STRIP_ADJ: - primType = GL_TRIANGLE_STRIP_ADJACENCY; - break; - case RenderOperation::OT_TRIANGLE_FAN: - primType = GL_TRIANGLE_FAN; - break; - } - - // Render to screen! - if (mCurrentShader[GPT_DOMAIN_PROGRAM]) - { - // Tessellation shader special case. - // Note: Only evaluation (domain) shaders are required. - - // GLuint primCount = 0; - // // Useful primitives for tessellation - // switch( op.operationType ) - // { - // case RenderOperation::OT_LINE_LIST: - // primCount = (GLuint)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) / 2; - // break; - - // case RenderOperation::OT_LINE_STRIP: - // primCount = (GLuint)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) - 1; - // break; - - // case RenderOperation::OT_TRIANGLE_LIST: - // primCount = (GLuint)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount); - // //primCount = (GLuint)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) / 3; - // break; - - // case RenderOperation::OT_TRIANGLE_STRIP: - // primCount = (GLuint)(op.useIndexes ? op.indexData->indexCount : op.vertexData->vertexCount) - 2; - // break; - // default: - // break; - // } - - // These are set via shader in DX11, SV_InsideTessFactor and SV_OutsideTessFactor - // Hardcoding for the sample - // float patchLevel(1.f); - // OGRE_CHECK_GL_ERROR(glPatchParameterfv(GL_PATCH_DEFAULT_INNER_LEVEL, &patchLevel)); - // OGRE_CHECK_GL_ERROR(glPatchParameterfv(GL_PATCH_DEFAULT_OUTER_LEVEL, &patchLevel)); - // OGRE_CHECK_GL_ERROR(glPatchParameteri(GL_PATCH_VERTICES, op.vertexData->vertexCount)); - - if (op.useIndexes) - { - void *pBufferData = VBO_BUFFER_OFFSET(op.indexData->indexStart * - op.indexData->indexBuffer->getIndexSize()); - GLenum indexType = (op.indexData->indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT; - OGRE_CHECK_GL_ERROR(glDrawElementsBaseVertex(GL_PATCHES, op.indexData->indexCount, indexType, pBufferData, op.vertexData->vertexStart)); - //OGRE_CHECK_GL_ERROR(glDrawElements(GL_PATCHES, op.indexData->indexCount, indexType, pBufferData)); - // OGRE_CHECK_GL_ERROR(glDrawArraysInstanced(GL_PATCHES, 0, primCount, 1)); - } - else - { - OGRE_CHECK_GL_ERROR(glDrawArrays(GL_PATCHES, op.vertexData->vertexStart, op.vertexData->vertexCount)); - //OGRE_CHECK_GL_ERROR(glDrawArrays(GL_PATCHES, 0, primCount)); - // OGRE_CHECK_GL_ERROR(glDrawArraysInstanced(GL_PATCHES, 0, primCount, 1)); - } - } - else if (op.useIndexes) - { - void *pBufferData = VBO_BUFFER_OFFSET(op.indexData->indexStart * - op.indexData->indexBuffer->getIndexSize()); - - GLenum indexType = (op.indexData->indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT; - - do - { - if (numberOfInstances > 1) - { - OGRE_CHECK_GL_ERROR(glDrawElementsInstancedBaseVertex(primType, op.indexData->indexCount, indexType, - pBufferData, numberOfInstances, - op.vertexData->vertexStart)); - } - else - { - OGRE_CHECK_GL_ERROR(glDrawElementsBaseVertex(primType, op.indexData->indexCount, indexType, - pBufferData, op.vertexData->vertexStart)); - } - } while (updatePassIterationRenderState()); - } - else - { - do - { - if (numberOfInstances > 1) - { - OGRE_CHECK_GL_ERROR(glDrawArraysInstanced(primType, op.vertexData->vertexStart, - op.vertexData->vertexCount, numberOfInstances)); - } - else - { - OGRE_CHECK_GL_ERROR(glDrawArrays(primType, op.vertexData->vertexStart, op.vertexData->vertexCount)); - } - } while (updatePassIterationRenderState()); - } - - // Do not unbind the vertex array object - // VAOs > 0 are selected each time before usage - // VAO #0 is not supported in Core profiles, and WOULD NOT be used by Ogre even in compatibility profiles - } - - void GL3PlusRenderSystem::_getDepthStencilFormatFor(PixelFormat internalColourFormat, - uint32* depthFormat, - uint32* stencilFormat) - { - if (isReverseDepthBufferEnabled()) - { - *depthFormat = GL_DEPTH_COMPONENT32F; - *stencilFormat = GL_NONE; - } - else - { - static_cast(mRTTManager)->getBestDepthStencil( - internalColourFormat, depthFormat, stencilFormat); - } - } - - void GL3PlusRenderSystem::setScissorTest(bool enabled, const Rect& rect) - { - mStateCacheManager->setEnabled(GL_SCISSOR_TEST, enabled); - - if (!enabled) - return; - - // If request texture flipping, use "upper-left", otherwise use "lower-left" - bool flipping = mActiveRenderTarget->requiresTextureFlipping(); - - // GL measures from the bottom, not the top - long targetHeight = mActiveRenderTarget->getHeight(); - long top = flipping ? rect.top : targetHeight - rect.bottom; - // NB GL uses width / height rather than right / bottom - OGRE_CHECK_GL_ERROR(glScissor(rect.left, top, rect.width(), rect.height())); - } - - void GL3PlusRenderSystem::clearFrameBuffer(unsigned int buffers, - const ColourValue& colour, - float depth, unsigned short stencil) - { - bool colourMask = - !(mCurrentBlend.writeR && mCurrentBlend.writeG && mCurrentBlend.writeB && mCurrentBlend.writeA); - - GLbitfield flags = 0; - if (buffers & FBT_COLOUR) - { - flags |= GL_COLOR_BUFFER_BIT; - // Enable buffer for writing if it isn't - if (colourMask) - { - mStateCacheManager->setColourMask(true, true, true, true); - } - mStateCacheManager->setClearColour(colour.r, colour.g, colour.b, colour.a); - } - if (buffers & FBT_DEPTH) - { - flags |= GL_DEPTH_BUFFER_BIT; - // Enable buffer for writing if it isn't - if (!mDepthWrite) - { - mStateCacheManager->setDepthMask( GL_TRUE ); - } - - if (isReverseDepthBufferEnabled()) - { - depth = 1.0f - 0.5f * (depth + 1.0f); - } - - mStateCacheManager->setClearDepth(depth); - } - if (buffers & FBT_STENCIL) - { - flags |= GL_STENCIL_BUFFER_BIT; - // Enable buffer for writing if it isn't - mStateCacheManager->setStencilMask(0xFFFFFFFF); - OGRE_CHECK_GL_ERROR(glClearStencil(stencil)); - } - - - Rect vpRect = mActiveViewport->getActualDimensions(); - bool needScissorBox = - vpRect != Rect(0, 0, mActiveRenderTarget->getWidth(), mActiveRenderTarget->getHeight()); - if (needScissorBox) - { - // Should be enable scissor test due the clear region is - // relied on scissor box bounds. - setScissorTest(true, vpRect); - } - - // Clear buffers - OGRE_CHECK_GL_ERROR(glClear(flags)); - - // Restore scissor test - if (needScissorBox) - { - setScissorTest(false, vpRect); - } - - // Reset buffer write state - if (!mDepthWrite && (buffers & FBT_DEPTH)) - { - mStateCacheManager->setDepthMask( GL_FALSE ); - } - - if (colourMask && (buffers & FBT_COLOUR)) - { - mStateCacheManager->setColourMask(mCurrentBlend.writeR, mCurrentBlend.writeG, - mCurrentBlend.writeB, mCurrentBlend.writeA); - } - - if (buffers & FBT_STENCIL) - { - mStateCacheManager->setStencilMask(mStencilWriteMask); - } - } - - void GL3PlusRenderSystem::_switchContext(GL3PlusContext *context) - { - // Unbind GPU programs and rebind to new context later, because - // scene manager treat render system as ONE 'context' ONLY, and it - // cached the GPU programs using state. - for(auto shader : mCurrentShader) - { - if(!shader) continue; - mProgramManager->setActiveShader(shader->getType(), NULL); - } - - // Disable textures - _disableTextureUnitsFrom(0); - - // It's ready for switching - if (mCurrentContext!=context) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE - // NSGLContext::makeCurrentContext does not flush automatically. everybody else does. - glFlushRenderAPPLE(); -#endif - mCurrentContext->endCurrent(); - mCurrentContext = context; - } - mCurrentContext->setCurrent(); - - mStateCacheManager = mCurrentContext->createOrRetrieveStateCacheManager(); - _completeDeferredVaoFboDestruction(); - - // Check if the context has already done one-time initialisation - if (!mCurrentContext->getInitialized()) - { - _oneTimeContextInitialization(); - mCurrentContext->setInitialized(); - } - - // Rebind GPU programs to new context - for(auto shader : mCurrentShader) - { - if(!shader) continue; - mProgramManager->setActiveShader(shader->getType(), shader); - } - - // Must reset depth/colour write mask to according with user desired, otherwise, - // clearFrameBuffer would be wrong because the value we are recorded may be - // difference with the really state stored in GL context. - mStateCacheManager->setDepthMask(mDepthWrite); - mStateCacheManager->setColourMask(mCurrentBlend.writeR, mCurrentBlend.writeG, - mCurrentBlend.writeB, mCurrentBlend.writeA); - mStateCacheManager->setStencilMask(mStencilWriteMask); - } - - void GL3PlusRenderSystem::_unregisterContext(GL3PlusContext *context) - { - static_cast(HardwareBufferManager::getSingletonPtr())->notifyContextDestroyed(context); - - for(auto & rt : mRenderTargets) - { - if(auto target = dynamic_cast(rt.second)) - { - if(auto fbo = target->getFBO()) - fbo->notifyContextDestroyed(context); - } - } - - if (mCurrentContext == context) - { - // Change the context to something else so that a valid context - // remains active. When this is the main context being unregistered, - // we set the main context to 0. - if (mCurrentContext != mMainContext) - { - _switchContext(mMainContext); - } - else - { - /// No contexts remain - mCurrentContext->endCurrent(); - mCurrentContext = 0; - mMainContext = 0; - mStateCacheManager = 0; - } - } - } - - uint32 GL3PlusRenderSystem::_createVao() - { - uint32 vao = 0; - OGRE_CHECK_GL_ERROR(glGenVertexArrays(1, &vao)); - return vao; - } - - void GL3PlusRenderSystem::_destroyVao(GLContext* context, uint32 vao) - { - if(context != mCurrentContext) - context->_getVaoDeferredForDestruction().push_back(vao); - else - _getStateCacheManager()->deleteGLVertexArray(vao); - } - - void GL3PlusRenderSystem::_destroyFbo(GLContext* context, uint32 fbo) - { - if(context != mCurrentContext) - context->_getFboDeferredForDestruction().push_back(fbo); - else - _getStateCacheManager()->deleteGLFrameBuffer(GL_FRAMEBUFFER, fbo); - } - - void GL3PlusRenderSystem::_bindVao(GLContext* context, uint32 vao) - { - OgreAssert(context == mCurrentContext, "VAO used in wrong OpenGL context"); - _getStateCacheManager()->bindGLVertexArray(vao); - } - - void GL3PlusRenderSystem::_oneTimeContextInitialization() - { - OGRE_CHECK_GL_ERROR(glDisable(GL_DITHER)); - - // Check for FSAA - // Enable the extension if it was enabled by the GL3PlusSupport - int fsaa_active = false; - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_SAMPLE_BUFFERS, (GLint*)&fsaa_active)); - if (fsaa_active) - { - OGRE_CHECK_GL_ERROR(glEnable(GL_MULTISAMPLE)); - } - - if (checkExtension("GL_EXT_texture_filter_anisotropic")) - { - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &mLargestSupportedAnisotropy)); - } - - // Enable seamless cube maps - OGRE_CHECK_GL_ERROR(glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS)); - // Set provoking vertex convention - OGRE_CHECK_GL_ERROR(glProvokingVertex(GL_FIRST_VERTEX_CONVENTION)); - - auto it = mOptions.find("Debug Layer"); - bool debugEnabled = false; - if (it != mOptions.end()) - { - debugEnabled = StringConverter::parseBool(it->second.currentValue); - } - - if (debugEnabled && getCapabilities()->hasCapability(RSC_DEBUG)) - { - OGRE_CHECK_GL_ERROR(glEnable(GL_DEBUG_OUTPUT)); - OGRE_CHECK_GL_ERROR(glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS)); - OGRE_CHECK_GL_ERROR(glDebugMessageCallbackARB(&GLDebugCallback, NULL)); - OGRE_CHECK_GL_ERROR(glDebugMessageControlARB(GL_DEBUG_SOURCE_API, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, NULL, GL_FALSE)); - } - - if(getCapabilities()->hasCapability(RSC_PRIMITIVE_RESTART)) - { - OGRE_CHECK_GL_ERROR(glEnable(GL_PRIMITIVE_RESTART_FIXED_INDEX)); - } - - glEnable(GL_PROGRAM_POINT_SIZE); - - if(getCapabilities()->getVendor() == GPU_NVIDIA) - { - // bug in NVIDIA driver, see e.g. - // https://www.opengl.org/discussion_boards/showthread.php/168217-gl_PointCoord-and-OpenGL-3-1-GLSL-1-4 - glEnable(0x8861); // GL_POINT_SPRITE - glGetError(); // clear the error that it generates nevertheless.. - } - - if (isReverseDepthBufferEnabled()) - { - // We want depth to range from 0 to 1 to increase precision. - glClipControl(GL_LOWER_LEFT, GL_ZERO_TO_ONE); - } - } - - void GL3PlusRenderSystem::initialiseContext(RenderWindow* primary) - { - // Set main and current context - mMainContext = dynamic_cast(primary)->getContext(); - mCurrentContext = mMainContext; - - // Set primary context as active - if (mCurrentContext) - mCurrentContext->setCurrent(); - - // Initialise GL3W - if (gl3wInit2(get_proc)) { // gl3wInit() fails if GL3.0 is not supported - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "OpenGL 3.0 is not supported"); - } - - // Setup GL3PlusSupport - initialiseExtensions(); - - OgreAssert(hasMinGLVersion(3, 3), "OpenGL 3.3 is not supported"); - - mStateCacheManager = mCurrentContext->createOrRetrieveStateCacheManager(); - - LogManager::getSingleton().logMessage("**************************************"); - LogManager::getSingleton().logMessage("*** OpenGL 3+ Renderer Started ***"); - LogManager::getSingleton().logMessage("**************************************"); - } - - void GL3PlusRenderSystem::_setRenderTarget(RenderTarget *target) - { - mActiveRenderTarget = target; - if (auto gltarget = dynamic_cast(target)) - { - // Switch context if different from current one - GL3PlusContext *newContext = gltarget->getContext(); - if (newContext && mCurrentContext != newContext) - { - _switchContext(newContext); - } - - // Check the FBO's depth buffer status - auto depthBuffer = static_cast(target->getDepthBuffer()); - - if ( target->getDepthBufferPool() != DepthBuffer::POOL_NO_DEPTH && - (!depthBuffer || depthBuffer->getGLContext() != mCurrentContext ) ) - { - // Depth is automatically managed and there is no depth buffer attached to this RT - // or the Current context doesn't match the one this Depth buffer was created with - setDepthBufferFor( target ); - } - - /* Bind a certain render target if it is a FBO. If it is not a FBO, bind the - main frame buffer. - */ - if(auto fbo = gltarget->getFBO()) - fbo->bind(true); - else - _getStateCacheManager()->bindGLFrameBuffer( GL_FRAMEBUFFER, 0 ); - - // Enable / disable sRGB states - if (target->isHardwareGammaEnabled()) - { - OGRE_CHECK_GL_ERROR(glEnable(GL_FRAMEBUFFER_SRGB)); - - // Note: could test GL_FRAMEBUFFER_SRGB_CAPABLE here before - // enabling, but GL spec says incapable surfaces ignore the setting - // anyway. We test the capability to enable isHardwareGammaEnabled. - } - else - { - OGRE_CHECK_GL_ERROR(glDisable(GL_FRAMEBUFFER_SRGB)); - } - } - } - - GLint GL3PlusRenderSystem::convertCompareFunction(CompareFunction func) - { - switch(func) - { - case CMPF_ALWAYS_FAIL: - return GL_NEVER; - case CMPF_ALWAYS_PASS: - return GL_ALWAYS; - case CMPF_LESS: - return GL_LESS; - case CMPF_LESS_EQUAL: - return GL_LEQUAL; - case CMPF_EQUAL: - return GL_EQUAL; - case CMPF_NOT_EQUAL: - return GL_NOTEQUAL; - case CMPF_GREATER_EQUAL: - return GL_GEQUAL; - case CMPF_GREATER: - return GL_GREATER; - } - // To keep compiler happy - return GL_ALWAYS; - } - - GLint GL3PlusRenderSystem::convertStencilOp(StencilOperation op, bool invert) - { - switch(op) - { - case SOP_KEEP: - return GL_KEEP; - case SOP_ZERO: - return GL_ZERO; - case SOP_REPLACE: - return GL_REPLACE; - case SOP_INCREMENT: - return invert ? GL_DECR : GL_INCR; - case SOP_DECREMENT: - return invert ? GL_INCR : GL_DECR; - case SOP_INCREMENT_WRAP: - return invert ? GL_DECR_WRAP : GL_INCR_WRAP; - case SOP_DECREMENT_WRAP: - return invert ? GL_INCR_WRAP : GL_DECR_WRAP; - case SOP_INVERT: - return GL_INVERT; - }; - // to keep compiler happy - return SOP_KEEP; - } - - - void GL3PlusRenderSystem::bindGpuProgram(GpuProgram* prg) - { - GLSLShader* glprg = static_cast(prg); - - mCurrentShader[glprg->getType()] = glprg; - // Bind the program - mProgramManager->setActiveShader(glprg->getType(), glprg); - - RenderSystem::bindGpuProgram(prg); - - // TextureManager::ResourceMapIterator resource = TextureManager::getSingletonPtr()->getResourceIterator(); - - // while(resource.hasMoreElements()) - // { - // TextureManager::ResourceMapPtr resource_map = resource.getNext(); - // resource_map.getResourceType(); - // } - - // //FIXME Either a new TextureShaderUsage enum needs to be introduced, - // // or additional TextureUsages must be created. See OgreTexture.h - // if (tex->getUsage() == TU_DYNAMIC_SHADER) - // { - // // OGRE_CHECK_GL_ERROR(glBindImageTexture(0, mTextureID, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA8)); - // OGRE_CHECK_GL_ERROR(glBindImageTexture(0, tex->getGLID(), 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA8)); - // } - } - - void GL3PlusRenderSystem::unbindGpuProgram(GpuProgramType gptype) - { - mProgramManager->setActiveShader(gptype, NULL); - mActiveParameters[gptype].reset(); - mCurrentShader[gptype] = NULL; - - RenderSystem::unbindGpuProgram(gptype); - } - - void GL3PlusRenderSystem::bindGpuProgramParameters(GpuProgramType gptype, const GpuProgramParametersPtr& params, uint16 mask) - { - mActiveParameters[gptype] = params; - - GLSLProgram* program = NULL; - - // Link can throw exceptions, ignore them at this point. - try - { - program = mProgramManager->getActiveProgram(); - } - catch (InvalidParametersException& e) - { - LogManager::getSingleton().logError("binding shared parameters failed: " + e.getDescription()); - return; - } - catch (Exception&) - { - return; - } - - if (mask & (uint16)GPV_GLOBAL) - { - params->_updateSharedParams(); - } - - // Pass on parameters from params to program object uniforms. - program->updateUniforms(params, mask, gptype); - - // FIXME This needs to be moved somewhere texture specific. - // Update image bindings for image load/store - // static_cast(mTextureManager)->bindImages(); - } - - void GL3PlusRenderSystem::beginProfileEvent( const String &eventName ) - { - if (getCapabilities()->hasCapability(RSC_DEBUG)) - OGRE_CHECK_GL_ERROR(glPushDebugGroup(GL_DEBUG_SOURCE_THIRD_PARTY, 0, -1, eventName.c_str())); - } - - - void GL3PlusRenderSystem::endProfileEvent( void ) - { - if (getCapabilities()->hasCapability(RSC_DEBUG)) - OGRE_CHECK_GL_ERROR(glPopDebugGroup()); - } - - - void GL3PlusRenderSystem::markProfileEvent( const String &eventName ) - { - if ( eventName.empty() ) - return; - - if (getCapabilities()->hasCapability(RSC_DEBUG)) - glDebugMessageInsert(GL_DEBUG_SOURCE_THIRD_PARTY, - GL_DEBUG_TYPE_PERFORMANCE, - 0, - GL_DEBUG_SEVERITY_LOW, - -1, - eventName.c_str()); - } - - void GL3PlusRenderSystem::bindVertexElementToGpu(const VertexElement& elem, - const HardwareVertexBufferSharedPtr& vertexBuffer, - const size_t vertexStart) - { - VertexElementSemantic sem = elem.getSemantic(); - unsigned short elemIndex = elem.getIndex(); - - GLuint attrib = (GLuint)GLSLProgramCommon::getFixedAttributeIndex(sem, elemIndex); - - const GL3PlusHardwareBuffer* hwGlBuffer = vertexBuffer->_getImpl(); - mStateCacheManager->bindGLBuffer(GL_ARRAY_BUFFER, hwGlBuffer->getGLBufferId()); - void* pBufferData = VBO_BUFFER_OFFSET(elem.getOffset() + vertexStart * vertexBuffer->getVertexSize()); - - if (vertexBuffer->isInstanceData()) - { - OGRE_CHECK_GL_ERROR(glVertexAttribDivisor(attrib, vertexBuffer->getInstanceDataStepRate())); - } - - unsigned short typeCount = VertexElement::getTypeCount(elem.getType()); - GLboolean normalised = GL_FALSE; - switch(elem.getType()) - { - case VET_UBYTE4_NORM: - case VET_SHORT2_NORM: - case VET_USHORT2_NORM: - case VET_SHORT4_NORM: - case VET_USHORT4_NORM: - case VET_INT_10_10_10_2_NORM: - normalised = GL_TRUE; - break; - default: - break; - }; - - switch(elem.getBaseType(elem.getType())) - { - default: - case VET_FLOAT1: - OGRE_CHECK_GL_ERROR(glVertexAttribPointer(attrib, - typeCount, - GL3PlusHardwareBufferManager::getGLType(elem.getType()), - normalised, - static_cast(vertexBuffer->getVertexSize()), - pBufferData)); - break; - case VET_DOUBLE1: - OGRE_CHECK_GL_ERROR(glVertexAttribLPointer(attrib, - typeCount, - GL3PlusHardwareBufferManager::getGLType(elem.getType()), - static_cast(vertexBuffer->getVertexSize()), - pBufferData)); - break; - } - - // If this attribute hasn't been enabled, do so and keep a record of it. - OGRE_CHECK_GL_ERROR(glEnableVertexAttribArray(attrib)); - } -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - bool GL3PlusRenderSystem::setDrawBuffer(ColourBufferType colourBuffer) - { - bool result = true; - - switch (colourBuffer) - { - case CBT_BACK: - OGRE_CHECK_GL_ERROR(glDrawBuffer(GL_BACK)); - break; - case CBT_BACK_LEFT: - OGRE_CHECK_GL_ERROR(glDrawBuffer(GL_BACK_LEFT)); - break; - case CBT_BACK_RIGHT: - OGRE_CHECK_GL_ERROR(glDrawBuffer(GL_BACK_RIGHT)); -// break; - default: - result = false; - } - - return result; - } -#endif - - void GL3PlusRenderSystem::_copyContentsToMemory(Viewport* vp, const Box& src, const PixelBox &dst, RenderWindow::FrameBuffer buffer) - { - GLenum format = GL3PlusPixelUtil::getGLOriginFormat(dst.format); - GLenum type = GL3PlusPixelUtil::getGLOriginDataType(dst.format); - - if ((format == GL_NONE) || (type == 0)) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Unsupported format", "GL3PlusRenderSystem::_copyContentsToMemory"); - } - - // Switch context if different from current one - _setViewport(vp); - - if(dst.getWidth() != dst.rowPitch) - glPixelStorei(GL_PACK_ROW_LENGTH, dst.rowPitch); - // Must change the packing to ensure no overruns! - glPixelStorei(GL_PACK_ALIGNMENT, 1); - - uint32_t height = vp->getTarget()->getHeight(); - - glReadBuffer((buffer == RenderWindow::FB_FRONT)? GL_FRONT : GL_BACK); - glReadPixels((GLint)src.left, (GLint)(height - src.bottom), - (GLsizei)dst.getWidth(), (GLsizei)dst.getHeight(), - format, type, dst.getTopLeftFrontPixelPtr()); - - // restore default alignment - glPixelStorei(GL_PACK_ALIGNMENT, 4); - glPixelStorei(GL_PACK_ROW_LENGTH, 0); - - PixelUtil::bulkPixelVerticalFlip(dst); - } - - void GL3PlusRenderSystem::initialiseExtensions(void) - { - // get driver version. - // this is the recommended way for GL3 see: https://www.opengl.org/wiki/Get_Context_Info - glGetIntegerv(GL_MAJOR_VERSION, &mDriverVersion.major); - glGetIntegerv(GL_MINOR_VERSION, &mDriverVersion.minor); - - LogManager::getSingleton().logMessage("GL_VERSION = " + mDriverVersion.toString()); - - // Get vendor - const GLubyte* pcVendor = glGetString(GL_VENDOR); - String tmpStr = (const char*)pcVendor; - LogManager::getSingleton().logMessage("GL_VENDOR = " + tmpStr); - mVendor = RenderSystemCapabilities::vendorFromString(tmpStr.substr(0, tmpStr.find(' '))); - - // Get renderer - const GLubyte* pcRenderer = glGetString(GL_RENDERER); - tmpStr = (const char*)pcRenderer; - LogManager::getSingleton().logMessage("GL_RENDERER = " + tmpStr); - - // Set extension list - Log::Stream log = LogManager::getSingleton().stream(); - String str; - - GLint numExt; - glGetIntegerv(GL_NUM_EXTENSIONS, &numExt); - - log << "GL_EXTENSIONS = "; - for(int i = 0; i < numExt; i++) - { - const GLubyte* pcExt = glGetStringi(GL_EXTENSIONS, i); - assert(pcExt && "Problems getting GL extension string using glGetString"); - str = String((const char*)pcExt); - log << str << " "; - mExtensionList.insert(str); - } - } -} diff --git a/RenderSystems/GL3Plus/src/OgreGL3PlusRenderToVertexBuffer.cpp b/RenderSystems/GL3Plus/src/OgreGL3PlusRenderToVertexBuffer.cpp deleted file mode 100644 index 069c9609dc6..00000000000 --- a/RenderSystems/GL3Plus/src/OgreGL3PlusRenderToVertexBuffer.cpp +++ /dev/null @@ -1,182 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGL3PlusRenderToVertexBuffer.h" -#include "OgreHardwareBufferManager.h" -#include "OgreRenderable.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" -#include "OgreGLSLProgramManager.h" -#include "OgreGLSLShader.h" - -namespace Ogre { - - GL3PlusRenderToVertexBuffer::GL3PlusRenderToVertexBuffer() - : mTargetBufferIndex(0) - , mFirstUpdate(true) - { - mVertexBuffers[0].reset(); - mVertexBuffers[1].reset(); - - // Create query objects. - OGRE_CHECK_GL_ERROR(glGenQueries(1, &mPrimitivesDrawnQuery)); - - //TODO GL4+ - // glGenTransformFeedbacks(1, mFeedbackObject); - } - - - GL3PlusRenderToVertexBuffer::~GL3PlusRenderToVertexBuffer() - { - OGRE_CHECK_GL_ERROR(glDeleteQueries(1, &mPrimitivesDrawnQuery)); - } - - - static GLint getR2VBPrimitiveType(RenderOperation::OperationType operationType) - { - switch (operationType) - { - case RenderOperation::OT_POINT_LIST: - return GL_POINTS; - case RenderOperation::OT_LINE_LIST: - return GL_LINES; - case RenderOperation::OT_TRIANGLE_LIST: - return GL_TRIANGLES; - //TODO Add other RenderOperation allowed when no GS present. - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "GL RenderToVertexBuffer" - "can only output point lists, line lists, or triangle lists", - "OgreGL3PlusRenderToVertexBuffer::getR2VBPrimitiveType"); - } - } - - void GL3PlusRenderToVertexBuffer::bindVerticesOutput(Pass* pass) - { - VertexDeclaration* declaration = mVertexData->vertexDeclaration; - size_t elemCount = declaration->getElementCount(); - - if (elemCount == 0) - return; - - //TODO GL4+ glBindTransformFeedback - - // Dynamically determine shader output variable names. - std::vector nameStrings; - - for (uint e = 0; e < elemCount; e++) - { - const VertexElement* element = declaration->getElement(e); - String name = getSemanticVaryingName(element->getSemantic(), element->getIndex()); - nameStrings.push_back(name); - } - - GLSLProgram* program = GLSLProgramManager::getSingleton().getActiveProgram(); - - program->setTransformFeedbackVaryings(nameStrings); - } - - - void GL3PlusRenderToVertexBuffer::update(SceneManager* sceneMgr) - { - // size_t bufSize = mVertexData->vertexDeclaration->getVertexSize(0) * mMaxVertexCount; - // if (!mVertexBuffers[0] || mVertexBuffers[0]->getSizeInBytes() != bufSize) - // { - // // Buffers don't match. Need to reallocate. - // mResetRequested = true; - // } - - Ogre::Pass* r2vbPass = derivePass(sceneMgr); - - if (mFirstUpdate) - { - bindVerticesOutput(r2vbPass); - mFirstUpdate = false; - } - - if (!mVertexBuffers[mTargetBufferIndex] || - mVertexBuffers[mTargetBufferIndex]->getSizeInBytes() < - mVertexData->vertexDeclaration->getVertexSize(0) * mMaxVertexCount) - { - reallocateBuffer(mTargetBufferIndex); - } - - // Disable rasterization. - OGRE_CHECK_GL_ERROR(glEnable(GL_RASTERIZER_DISCARD)); - - // Bind source vertex array + target tranform feedback buffer. - auto targetVertexBuffer = mVertexBuffers[mTargetBufferIndex]->_getImpl(); - // OGRE_CHECK_GL_ERROR(glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, VertexBuffer[mTargetBufferIndex])); - OGRE_CHECK_GL_ERROR(glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, targetVertexBuffer->getGLBufferId())); - // OGRE_CHECK_GL_ERROR(glBindVertexArray(VertexArray[mSourceBufferIndex])); - - GLSLProgramManager::getSingleton().getActiveProgram()->activate(); - - // 'Render' data to the transform buffer. - OGRE_CHECK_GL_ERROR(glBeginQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN, mPrimitivesDrawnQuery)); - OGRE_CHECK_GL_ERROR(glBeginTransformFeedback(getR2VBPrimitiveType(mOperationType))); - - RenderOperation renderOp; - if (mResetRequested || mResetsEveryUpdate) - { - // Use source data to render to first buffer. - mSourceRenderable->getRenderOperation(renderOp); - } - else - { - // Use current front buffer to render to back buffer. - this->getRenderOperation(renderOp); - } - - RenderSystem* targetRenderSystem = Root::getSingleton().getRenderSystem(); - targetRenderSystem->_render(renderOp); - // OGRE_CHECK_GL_ERROR(glDrawArrays(GL_POINTS, 0, 1)); - - //TODO GL4+ - //glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, mFeedbackObject); - //glDrawTransformFeedback(getR2VBPrimitiveType(mOperationType), mFeedbackObject); - - OGRE_CHECK_GL_ERROR(glEndTransformFeedback()); - OGRE_CHECK_GL_ERROR(glEndQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN)); - - // Read back query results. - GLuint primitivesWritten; - OGRE_CHECK_GL_ERROR(glGetQueryObjectuiv(mPrimitivesDrawnQuery, GL_QUERY_RESULT, &primitivesWritten)); - mVertexData->vertexCount = primitivesWritten * getVertexCountPerPrimitive(mOperationType); - - // Switch the vertex binding. - mVertexData->vertexBufferBinding->unsetAllBindings(); - mVertexData->vertexBufferBinding->setBinding(0, mVertexBuffers[mTargetBufferIndex]); - mTargetBufferIndex = mTargetBufferIndex == 0 ? 1 : 0; - - // Enable rasterization. - OGRE_CHECK_GL_ERROR(glDisable(GL_RASTERIZER_DISCARD)); - - // Clear the reset flag. - mResetRequested = false; - } -} diff --git a/RenderSystems/GL3Plus/src/OgreGL3PlusStateCacheManager.cpp b/RenderSystems/GL3Plus/src/OgreGL3PlusStateCacheManager.cpp deleted file mode 100644 index 5ee9d2988a4..00000000000 --- a/RenderSystems/GL3Plus/src/OgreGL3PlusStateCacheManager.cpp +++ /dev/null @@ -1,531 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ - -#include "OgreGL3PlusStateCacheManager.h" -#include "OgreGL3PlusRenderSystem.h" -#include "OgreRoot.h" - -// performance critical state -// this one is per-context and can be unconditionally cached -// without breaking multi-context scenarios -#define OGRE_ENABLE_STATE_CACHE_CRITICAL - -namespace Ogre { - - GL3PlusStateCacheManager::GL3PlusStateCacheManager(void) - { - clearCache(); - } - - void GL3PlusStateCacheManager::initializeCache() - { - glBlendEquation(GL_FUNC_ADD); - - glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD); - - glBlendFunc(GL_ONE, GL_ZERO); - - glCullFace(mCullFace); - - glDepthFunc(mDepthFunc); - - glDepthMask(mDepthMask); - - glStencilMask(mStencilMask); - - glClearDepth(mClearDepth); - - glBindTexture(GL_TEXTURE_2D, 0); - - glBindBuffer(GL_ARRAY_BUFFER, 0); - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - - glBindFramebuffer(GL_FRAMEBUFFER, 0); - - glBindRenderbuffer(GL_RENDERBUFFER, 0); - - glActiveTexture(GL_TEXTURE0); - - glClearColor(mClearColour[0], mClearColour[1], mClearColour[2], mClearColour[3]); - - glColorMask(mColourMask[0], mColourMask[1], mColourMask[2], mColourMask[3]); - - glPolygonMode(GL_FRONT_AND_BACK, mPolygonMode); - } - - void GL3PlusStateCacheManager::clearCache() - { - mDepthMask = GL_TRUE; - mBlendEquationRGB = GL_FUNC_ADD; - mBlendEquationAlpha = GL_FUNC_ADD; - mCullFace = GL_BACK; - mDepthFunc = GL_LESS; - mStencilMask = 0xFFFFFFFF; - mActiveTextureUnit = 0; - mClearDepth = 1.0f; - mLastBoundTexID = 0; - - mPolygonMode = GL_FILL; - - // Initialize our cache variables and also the GL so that the - // stored values match the GL state - mBlendFuncSource = GL_ONE; - mBlendFuncDest = GL_ZERO; - - mClearColour[0] = mClearColour[1] = mClearColour[2] = mClearColour[3] = 0.0f; - mColourMask[0] = mColourMask[1] = mColourMask[2] = mColourMask[3] = GL_TRUE; - -#ifdef OGRE_ENABLE_STATE_CACHE - mEnableVector.reserve(25); - mEnableVector.clear(); -#endif - mActiveBufferMap.clear(); - mTexUnitsMap.clear(); - - mActiveDrawFrameBuffer=0; - mActiveReadFrameBuffer=0; - - mActiveVertexArray = 0; - } - - void GL3PlusStateCacheManager::bindGLFrameBuffer(GLenum target,GLuint buffer) - { -#ifdef OGRE_ENABLE_STATE_CACHE - bool update = false; - - //GL_FRAMEBUFFER sets both GL_DRAW_FRAMEBUFFER and GL_READ_FRAMEBUFFER - if(target==GL_FRAMEBUFFER) - { - if( buffer != mActiveDrawFrameBuffer - || buffer != mActiveReadFrameBuffer) - { - update = true; - mActiveReadFrameBuffer=buffer; - mActiveDrawFrameBuffer=buffer; - } - } - else if( target == GL_DRAW_FRAMEBUFFER) - { - if(buffer != mActiveDrawFrameBuffer) - { - update = true; - mActiveDrawFrameBuffer=buffer; - } - } - else if( target == GL_READ_FRAMEBUFFER) - { - if(buffer != mActiveReadFrameBuffer) - { - update = true; - mActiveReadFrameBuffer=buffer; - } - } - - // Update GL - if(update) -#endif - { - OGRE_CHECK_GL_ERROR(glBindFramebuffer(target, buffer)); - } - } - void GL3PlusStateCacheManager::bindGLRenderBuffer(GLuint buffer) - { -#ifdef OGRE_ENABLE_STATE_CACHE - auto ret = mActiveBufferMap.emplace(GL_RENDERBUFFER, buffer); - if(ret.first->second != buffer) // Update the cached value if needed - { - ret.first->second = buffer; - ret.second = true; - } - - // Update GL - if(ret.second) -#endif - { - OGRE_CHECK_GL_ERROR(glBindRenderbuffer(GL_RENDERBUFFER, buffer)); - } - } - - void GL3PlusStateCacheManager::bindGLBuffer(GLenum target, GLuint buffer) - { -#ifdef OGRE_ENABLE_STATE_CACHE - auto ret = mActiveBufferMap.emplace(target, buffer); - if(ret.first->second != buffer) // Update the cached value if needed - { - ret.first->second = buffer; - ret.second = true; - } - - // Update GL - if(ret.second) -#endif - { - OGRE_CHECK_GL_ERROR(glBindBuffer(target, buffer)); - } - - } - void GL3PlusStateCacheManager::deleteGLFrameBuffer(GLenum target, GLuint buffer) - { - // Buffer name 0 is reserved and we should never try to delete it - if(buffer == 0) - return; - - //always delete the buffer, even if not currently bound - OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &buffer)); - -#ifdef OGRE_ENABLE_STATE_CACHE - if (buffer == mActiveDrawFrameBuffer ) - { - // Currently bound read frame buffer is being deleted, update the cached values to 0, - mActiveDrawFrameBuffer = 0; - } - if ( buffer == mActiveReadFrameBuffer) - { - // Currently bound read frame buffer is being deleted, update the cached values to 0, - mActiveReadFrameBuffer = 0; - } -#endif - } - void GL3PlusStateCacheManager::deleteGLRenderBuffer(GLuint buffer) - { - // Buffer name 0 is reserved and we should never try to delete it - if(buffer == 0) - return; - - //always delete the buffer, even if not currently bound - OGRE_CHECK_GL_ERROR(glDeleteRenderbuffers(1, &buffer)); - -#ifdef OGRE_ENABLE_STATE_CACHE - BindBufferMap::iterator i = mActiveBufferMap.find(GL_RENDERBUFFER); - if (i != mActiveBufferMap.end() && ((*i).second == buffer)) - { - // Currently bound render buffer is being deleted, update the cached value to 0, - // which it likely the buffer that will be bound by the driver. - // An update will be forced next time we try to bind on this target. - (*i).second = 0; - } -#endif - } - void GL3PlusStateCacheManager::deleteGLBuffer(GLenum target, GLuint buffer) - { - // Buffer name 0 is reserved and we should never try to delete it - if(buffer == 0) - return; - - //always delete the buffer, even if not currently bound - OGRE_CHECK_GL_ERROR(glDeleteBuffers(1, &buffer)); - -#ifdef OGRE_ENABLE_STATE_CACHE - BindBufferMap::iterator i = mActiveBufferMap.find(target); - - if (i != mActiveBufferMap.end() && ((*i).second == buffer)) - { - // Currently bound buffer is being deleted, update the cached value to 0, - // which it likely the buffer that will be bound by the driver. - // An update will be forced next time we try to bind on this target. - (*i).second = 0; - } -#endif - } - - void GL3PlusStateCacheManager::bindGLVertexArray(GLuint vao) - { -#ifdef OGRE_ENABLE_STATE_CACHE_CRITICAL // multi-context is handled by GLVertexArrayObject::bind - if(mActiveVertexArray != vao) - { - mActiveVertexArray = vao; - OGRE_CHECK_GL_ERROR(glBindVertexArray(vao)); - //we also need to clear the cached GL_ELEMENT_ARRAY_BUFFER value, as it is invalidated by glBindVertexArray - mActiveBufferMap[GL_ELEMENT_ARRAY_BUFFER] = 0; - } -#else - OGRE_CHECK_GL_ERROR(glBindVertexArray(vao)); -#endif - } - - void GL3PlusStateCacheManager::deleteGLVertexArray(GLuint vao) - { -#ifdef OGRE_ENABLE_STATE_CACHE_CRITICAL - if(mActiveVertexArray == vao) - { - mActiveVertexArray = 0; - //we also need to clear the cached GL_ELEMENT_ARRAY_BUFFER value, as it is invalidated by glBindVertexArray - mActiveBufferMap[GL_ELEMENT_ARRAY_BUFFER] = 0; - } -#endif - OGRE_CHECK_GL_ERROR(glDeleteVertexArrays(1, &vao)); - } - - void GL3PlusStateCacheManager::invalidateStateForTexture(GLuint texture) - { -#ifdef OGRE_ENABLE_STATE_CACHE - mTexUnitsMap.erase(texture); -#endif - } - - // TODO: Store as high/low bits of a GLuint, use vector instead of map for TexParameteriMap - void GL3PlusStateCacheManager::setTexParameteri(GLenum target, GLenum pname, GLint param) - { -#ifdef OGRE_ENABLE_STATE_CACHE - // Check if we have a map entry for this texture id. If not, create a blank one and insert it. - TexUnitsMap::iterator it = mTexUnitsMap.find(mLastBoundTexID); - if (it == mTexUnitsMap.end()) - { - TexParameteriMap unit; - mTexUnitsMap[mLastBoundTexID] = unit; - - // Update the iterator - it = mTexUnitsMap.find(mLastBoundTexID); - } - - // Get a local copy of the parameter map and search for this parameter - TexParameteriMap &myMap = (*it).second; - auto ret = myMap.emplace(pname, param); - TexParameteriMap::iterator i = ret.first; - - // Update the cached value if needed - if((*i).second != param || ret.second) - { - (*i).second = param; - - // Update GL - OGRE_CHECK_GL_ERROR(glTexParameteri(target, pname, param)); - } -#else - OGRE_CHECK_GL_ERROR(glTexParameteri(target, pname, param)); -#endif - } - - void GL3PlusStateCacheManager::bindGLTexture(GLenum target, GLuint texture) - { -#ifdef OGRE_ENABLE_STATE_CACHE - mLastBoundTexID = texture; -#endif - - // Update GL - OGRE_CHECK_GL_ERROR(glBindTexture(target, texture)); - } - - bool GL3PlusStateCacheManager::activateGLTextureUnit(size_t unit) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if (mActiveTextureUnit == unit) - return true; -#endif - - OGRE_CHECK_GL_ERROR(glActiveTexture(GL_TEXTURE0 + unit)); - mActiveTextureUnit = unit; - return true; - } - - void GL3PlusStateCacheManager::setBlendFunc(GLenum source, GLenum dest, GLenum sourceA, GLenum destA) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mBlendFuncSource != source || mBlendFuncDest != dest || sourceA != mBlendFuncSourceAlpha || destA != mBlendFuncDestAlpha ) -#endif - { - mBlendFuncSource = source; - mBlendFuncDest = dest; - mBlendFuncSourceAlpha = sourceA; - mBlendFuncDestAlpha = destA; - - OGRE_CHECK_GL_ERROR(glBlendFuncSeparate(source, dest, sourceA, destA)); - } - } - - void GL3PlusStateCacheManager::setDepthMask(GLboolean mask) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mDepthMask != mask) -#endif - { - mDepthMask = mask; - - OGRE_CHECK_GL_ERROR(glDepthMask(mask)); - } - } - - void GL3PlusStateCacheManager::setDepthFunc(GLenum func) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mDepthFunc != func) -#endif - { - mDepthFunc = func; - - OGRE_CHECK_GL_ERROR(glDepthFunc(func)); - } - } - - void GL3PlusStateCacheManager::setClearDepth(GLclampf depth) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mClearDepth != depth) -#endif - { - mClearDepth = depth; - - OGRE_CHECK_GL_ERROR(glClearDepth(depth)); - } - } - - void GL3PlusStateCacheManager::setClearColour(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if((mClearColour[0] != red) || - (mClearColour[1] != green) || - (mClearColour[2] != blue) || - (mClearColour[3] != alpha)) -#endif - { - mClearColour[0] = red; - mClearColour[1] = green; - mClearColour[2] = blue; - mClearColour[3] = alpha; - - OGRE_CHECK_GL_ERROR(glClearColor(mClearColour[0], mClearColour[1], mClearColour[2], mClearColour[3])); - } - } - - void GL3PlusStateCacheManager::setColourMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if((mColourMask[0] != red) || - (mColourMask[1] != green) || - (mColourMask[2] != blue) || - (mColourMask[3] != alpha)) -#endif - { - mColourMask[0] = red; - mColourMask[1] = green; - mColourMask[2] = blue; - mColourMask[3] = alpha; - - OGRE_CHECK_GL_ERROR(glColorMask(mColourMask[0], mColourMask[1], mColourMask[2], mColourMask[3])); - } - } - - void GL3PlusStateCacheManager::setStencilMask(GLuint mask) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mStencilMask != mask) -#endif - { - mStencilMask = mask; - - OGRE_CHECK_GL_ERROR(glStencilMask(mask)); - } - } - - void GL3PlusStateCacheManager::setEnabled(GLenum flag, bool enabled) - { -#ifdef OGRE_ENABLE_STATE_CACHE - auto iter = std::find(mEnableVector.begin(), mEnableVector.end(), flag); - bool was_enabled = iter != mEnableVector.end(); - - if(was_enabled == enabled) - return; // no change - - if(!enabled) - { - mEnableVector.erase(iter); - } - else - { - mEnableVector.push_back(flag); - } -#endif - if (!enabled) - { - OGRE_CHECK_GL_ERROR(glDisable(flag)); - } - else - { - OGRE_CHECK_GL_ERROR(glEnable(flag)); - } - } - - void GL3PlusStateCacheManager::setViewport(const Rect& r) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mViewport != r) -#endif - { - mViewport = r; - OGRE_CHECK_GL_ERROR(glViewport(r.left, r.top, r.width(), r.height())); - } - } - - void GL3PlusStateCacheManager::setCullFace(GLenum face) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mCullFace != face) -#endif - { - mCullFace = face; - - glCullFace(face); - } - } - - void GL3PlusStateCacheManager::setBlendEquation(GLenum eqRGB, GLenum eqAlpha) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mBlendEquationRGB != eqRGB || mBlendEquationAlpha != eqAlpha) -#endif - { - mBlendEquationRGB = eqRGB; - mBlendEquationAlpha = eqAlpha; - - OGRE_CHECK_GL_ERROR(glBlendEquationSeparate(eqRGB, eqAlpha)); - } - } - - void GL3PlusStateCacheManager::setPolygonMode(GLenum mode) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if (mPolygonMode != mode) -#endif - { - mPolygonMode = mode; - OGRE_CHECK_GL_ERROR(glPolygonMode(GL_FRONT_AND_BACK, mPolygonMode)); - } - } - - void GL3PlusStateCacheManager::bindGLProgramPipeline(GLuint handle) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mActiveProgramPipeline != handle) -#endif - { - mActiveProgramPipeline = handle; - OGRE_CHECK_GL_ERROR(glBindProgramPipeline(mActiveProgramPipeline)); - } - } -} diff --git a/RenderSystems/GL3Plus/src/OgreGL3PlusTexture.cpp b/RenderSystems/GL3Plus/src/OgreGL3PlusTexture.cpp deleted file mode 100644 index 6caa2f58be3..00000000000 --- a/RenderSystems/GL3Plus/src/OgreGL3PlusTexture.cpp +++ /dev/null @@ -1,416 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGL3PlusTexture.h" -#include "OgreGL3PlusPixelFormat.h" -#include "OgreGL3PlusRenderSystem.h" -#include "OgreGL3PlusHardwareBufferManager.h" -#include "OgreGL3PlusHardwarePixelBuffer.h" -#include "OgreGL3PlusTextureBuffer.h" -#include "OgreGL3PlusStateCacheManager.h" -#include "OgreGLUtil.h" -#include "OgreRoot.h" -#include "OgreBitwise.h" -#include "OgreTextureManager.h" - -namespace Ogre { - GL3PlusTexture::GL3PlusTexture(ResourceManager* creator, const String& name, - ResourceHandle handle, const String& group, bool isManual, - ManualResourceLoader* loader, GL3PlusRenderSystem* renderSystem) - : GLTextureCommon(creator, name, handle, group, isManual, loader), - mRenderSystem(renderSystem) - { - mMipmapsHardwareGenerated = true; - } - - GL3PlusTexture::~GL3PlusTexture() - { - // have to call this here rather than in Resource destructor - // since calling virtual methods in base destructors causes crash - unload(); - } - - GLenum GL3PlusTexture::getGL3PlusTextureTarget(void) const - { - switch (mTextureType) - { - case TEX_TYPE_1D: - return GL_TEXTURE_1D; - case TEX_TYPE_2D: - return GL_TEXTURE_2D; - case TEX_TYPE_3D: - return GL_TEXTURE_3D; - case TEX_TYPE_CUBE_MAP: - return GL_TEXTURE_CUBE_MAP; - case TEX_TYPE_2D_ARRAY: - return GL_TEXTURE_2D_ARRAY; - default: - return 0; - }; - } - - // Creation / loading methods - void GL3PlusTexture::createInternalResourcesImpl(void) - { - // set HardwareBuffer::Usage for TU_RENDERTARGET if nothing else specified - if((mUsage & TU_RENDERTARGET) && (mUsage & ~TU_RENDERTARGET) == 0) - mUsage |= HardwareBuffer::HBU_DYNAMIC; - - // Adjust format if required. - mFormat = TextureManager::getSingleton().getNativeFormat(mTextureType, mFormat, mUsage); - - // Create a texture object and identify its GL type. - OGRE_CHECK_GL_ERROR(glGenTextures(1, &mTextureID)); - GLenum texTarget = getGL3PlusTextureTarget(); - - // Calculate size for all mip levels of the texture. - uint32 width, height, depth; - - if ((mWidth * PixelUtil::getNumElemBytes(mFormat)) & 3) { - // Standard alignment of 4 is not right for some formats. - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_ALIGNMENT, 1)); - } - - // Bind texture object to its type, making it the active texture object - // for that type. - mRenderSystem->_getStateCacheManager()->bindGLTexture( texTarget, mTextureID ); - - if (mRenderSystem->getCapabilities()->hasCapability(RSC_DEBUG)) - OGRE_CHECK_GL_ERROR(glObjectLabel(GL_TEXTURE, mTextureID, -1, mName.c_str())); - - mRenderSystem->_getStateCacheManager()->setTexParameteri(texTarget, GL_TEXTURE_BASE_LEVEL, 0); - mRenderSystem->_getStateCacheManager()->setTexParameteri(texTarget, GL_TEXTURE_MAX_LEVEL, mNumMipmaps); - - // Set up texture swizzling. - typedef std::array SwizzleMask; - SwizzleMask swizzleMask; - - if (PixelUtil::isLuminance(mFormat)) - { - if (PixelUtil::getComponentCount(mFormat) == 2) - { - swizzleMask = SwizzleMask{GL_RED, GL_RED, GL_RED, GL_GREEN}; - } - else - { - swizzleMask = SwizzleMask{GL_RED, GL_RED, GL_RED, GL_ONE}; - } - } - else if(mFormat == PF_A8) - { - swizzleMask = SwizzleMask{GL_ZERO, GL_ZERO, GL_ZERO, GL_RED}; - } - else - { - swizzleMask = SwizzleMask{GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}; - } - OGRE_CHECK_GL_ERROR(glTexParameteriv(texTarget, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask.data())); - - GLenum format = GL3PlusPixelUtil::getGLInternalFormat(mFormat, mHwGamma); - GLenum datatype = GL3PlusPixelUtil::getGLOriginDataType(mFormat); - width = mWidth; - height = mHeight; - depth = mDepth; - - // Allocate texture storage so that glTexSubImageXD can be - // used to upload the texture. - if (PixelUtil::isCompressed(mFormat)) - { - // Compressed formats - GLsizei size; - - for (uint32 mip = 0; mip <= mNumMipmaps; mip++) - { - size = static_cast(PixelUtil::getMemorySize(width, height, depth, mFormat)); - // std::stringstream str; - // str << "GL3PlusTexture::create - " << StringConverter::toString(mTextureID) - // << " bytes: " << StringConverter::toString(PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat)) - // << " Mip: " + StringConverter::toString(mip) - // << " Width: " << StringConverter::toString(width) - // << " Height: " << StringConverter::toString(height) - // << " Format " << PixelUtil::getFormatName(mFormat) - // << " Internal Format: 0x" << std::hex << format - // << " Origin Format: 0x" << std::hex << GL3PlusPixelUtil::getGLOriginFormat(mFormat) - // << " Data type: 0x" << std::hex << datatype; - // LogManager::getSingleton().logMessage(LML_NORMAL, str.str()); - - switch(mTextureType) - { - case TEX_TYPE_1D: - OGRE_CHECK_GL_ERROR(glCompressedTexImage1D(GL_TEXTURE_1D, mip, format, - width, 0, - size, NULL)); - break; - case TEX_TYPE_2D: - OGRE_CHECK_GL_ERROR(glCompressedTexImage2D(GL_TEXTURE_2D, - mip, - format, - width, height, - 0, - size, - NULL)); - break; - case TEX_TYPE_2D_ARRAY: - case TEX_TYPE_3D: - OGRE_CHECK_GL_ERROR(glCompressedTexImage3D(texTarget, mip, format, - width, height, depth, 0, - size, NULL)); - break; - case TEX_TYPE_CUBE_MAP: - for(int face = 0; face < 6; face++) { - OGRE_CHECK_GL_ERROR(glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, format, - width, height, 0, - size, NULL)); - } - break; - default: - break; - }; - - if (width > 1) - { - width = width / 2; - } - if (height > 1) - { - height = height / 2; - } - if (depth > 1 && mTextureType != TEX_TYPE_2D_ARRAY) - { - depth = depth / 2; - } - } - } - else - { - if (mRenderSystem->hasMinGLVersion(4, 2) || mRenderSystem->checkExtension("GL_ARB_texture_storage")) - { - switch(mTextureType) - { - case TEX_TYPE_1D: - OGRE_CHECK_GL_ERROR(glTexStorage1D(GL_TEXTURE_1D, GLsizei(mNumMipmaps+1), format, GLsizei(width))); - break; - case TEX_TYPE_2D: - case TEX_TYPE_CUBE_MAP: - OGRE_CHECK_GL_ERROR(glTexStorage2D(texTarget, GLsizei(mNumMipmaps+1), format, GLsizei(width), GLsizei(height))); - break; - case TEX_TYPE_2D_ARRAY: - case TEX_TYPE_3D: - OGRE_CHECK_GL_ERROR(glTexStorage3D(texTarget, GLsizei(mNumMipmaps+1), format, GLsizei(width), GLsizei(height), GLsizei(depth))); - break; - case TEX_TYPE_EXTERNAL_OES: - OGRE_EXCEPT( - Exception::ERR_RENDERINGAPI_ERROR, - "Attempt to store texture for unsupported TEX_TYPE_EXTERNAL_OES, should never happen", - "GL3PlusTexture::createInternalResourcesImpl" - ); - break; - } - } - else - { - GLenum originFormat = GL3PlusPixelUtil::getGLOriginFormat(mFormat); - - // Run through this process to pregenerate mipmap pyramid - for(uint32 mip = 0; mip <= mNumMipmaps; mip++) - { - // std::stringstream str; - // str << "GL3PlusTexture::create - " << StringConverter::toString(mTextureID) - // << " bytes: " << StringConverter::toString(PixelUtil::getMemorySize(width, height, depth, mFormat)) - // << " Mip: " + StringConverter::toString(mip) - // << " Width: " << StringConverter::toString(width) - // << " Height: " << StringConverter::toString(height) - // << " Format " << PixelUtil::getFormatName(mFormat) - // << " Internal Format: 0x" << std::hex << format - // << " Origin Format: 0x" << std::hex << GL3PlusPixelUtil::getGLOriginFormat(mFormat) - // << " Data type: 0x" << std::hex << datatype; - // LogManager::getSingleton().logMessage(LML_NORMAL, str.str()); - - // Normal formats - switch(mTextureType) - { - case TEX_TYPE_1D: - OGRE_CHECK_GL_ERROR(glTexImage1D(GL_TEXTURE_1D, mip, format, - width, 0, - originFormat, datatype, NULL)); - break; - case TEX_TYPE_2D: - OGRE_CHECK_GL_ERROR(glTexImage2D(texTarget, - mip, - format, - width, height, - 0, - originFormat, - datatype, NULL)); - break; - case TEX_TYPE_3D: - case TEX_TYPE_2D_ARRAY: - OGRE_CHECK_GL_ERROR(glTexImage3D(texTarget, mip, format, - width, height, depth, 0, - originFormat, datatype, NULL)); - break; - case TEX_TYPE_CUBE_MAP: - for(int face = 0; face < 6; face++) { - OGRE_CHECK_GL_ERROR(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, format, - width, height, 0, - originFormat, datatype, NULL)); - } - break; - case TEX_TYPE_EXTERNAL_OES: - OGRE_EXCEPT( - Exception::ERR_RENDERINGAPI_ERROR, - "Attempt to create mipmaps for unsupported TEX_TYPE_EXTERNAL_OES, should never happen", - "GL3PlusTexture::createInternalResourcesImpl" - ); - break; - default: - break; - }; - - if (width > 1) - { - width = width / 2; - } - if (height > 1) - { - height = height / 2; - } - if (depth > 1 && mTextureType != TEX_TYPE_2D_ARRAY) - { - depth = depth / 2; - } - } - } - } - - // Reset unpack alignment to defaults - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_ALIGNMENT, 4)); - - _createSurfaceList(); - - // Generate mipmaps after all texture levels have been loaded - // This is required for compressed formats such as DXT - if (PixelUtil::isCompressed(mFormat) && mUsage & TU_AUTOMIPMAP) - { - OGRE_CHECK_GL_ERROR(glGenerateMipmap(getGL3PlusTextureTarget())); - } - - // Get final internal format. - mFormat = getBuffer(0,0)->getFormat(); - } - - void GL3PlusTexture::freeInternalResourcesImpl() - { - if (GL3PlusStateCacheManager* stateCacheManager = mRenderSystem->_getStateCacheManager()) - { - OGRE_CHECK_GL_ERROR(glDeleteTextures(1, &mTextureID)); - stateCacheManager->invalidateStateForTexture(mTextureID); - } - } - - void GL3PlusTexture::_createSurfaceList() - { - mSurfaceList.clear(); - - uint32 depth = mDepth; - for (uint8 face = 0; face < getNumFaces(); face++) - { - uint32 width = mWidth; - uint32 height = mHeight; - - for (uint32 mip = 0; mip <= getNumMipmaps(); mip++) - { - auto buf = std::make_shared(this, face, mip, width, height, depth); - mSurfaceList.push_back(buf); - - if (width > 1) - width = width / 2; - if (height > 1) - height = height / 2; - if (depth > 1 && mTextureType != TEX_TYPE_2D_ARRAY) - depth = depth / 2; - } - } - } - - void GL3PlusTexture::createShaderAccessPoint(uint bindPoint, TextureAccess access, - int mipmapLevel, int textureArrayIndex, - PixelFormat format) - { - GLenum GlAccess = 0; - - switch (access) - { - case TA_READ: - GlAccess = GL_READ_ONLY; - break; - case TA_WRITE: - GlAccess = GL_WRITE_ONLY; - break; - case TA_READ_WRITE: - GlAccess = GL_READ_WRITE; - break; - } - - if (format == PF_UNKNOWN) format = mFormat; - GLenum GlFormat = GL3PlusPixelUtil::getClosestGLImageInternalFormat(format); - GLboolean isArrayTexture = mTextureType == TEX_TYPE_2D_ARRAY; - - // TODO - // * add memory barrier - // * material script access (can have multiple instances for a single texture_unit) - // shader_access [] [] [] [] - // shader_access 2 read_write 0 0 PF_UINT32_R - // binding point - location to bind for shader access; for OpenGL this must be unique and is not related to texture binding point - // access - give the shader read, write, or read_write privileges [default read_write] - // mipmap level - texture mipmap level to use [default 0] - // texture array layer - layer of texture array to use: 'all', or layer number (if not layered, just use 0) [default 0] - // format - texture format to be read in shader; for OpenGL this may be different than bound texture format - not sure about DX11 [default same format as texture] - // Note that for OpenGL the shader access (image) binding point - // must be specified, it is NOT the same as the texture binding point, - // and it must be unique among textures in this pass. - // * enforce binding point uniqueness by checking against - // image binding point allocation list in GL3PlusTextureManager - // * generalize for other render systems by introducing vitual method in Texture - // for (image in mImages) - // { - // OGRE_CHECK_GL_ERROR( - // glBindImageTexture( - // mImageBind, mTextureID, - // mMipmapLevel, - // mLayered.find('all') != str::npos ? GL_TRUE : GL_FALSE, mLayer, - // mImageAccess (READ, WRITE, READ_WRITE), - // toImageFormat(mFormatInShader))); //GL_RGBA8)); //GL_R32UI)); GL_READ_WRITE - if (mRenderSystem->hasMinGLVersion(4, 2) || mRenderSystem->checkExtension("GL_ARB_shader_image_load_store")) - { - OGRE_CHECK_GL_ERROR(glBindImageTexture(bindPoint, mTextureID, mipmapLevel, isArrayTexture, textureArrayIndex, GlAccess, GlFormat)); - } - } - - -} diff --git a/RenderSystems/GL3Plus/src/OgreGL3PlusTextureBuffer.cpp b/RenderSystems/GL3Plus/src/OgreGL3PlusTextureBuffer.cpp deleted file mode 100644 index 773d1d09207..00000000000 --- a/RenderSystems/GL3Plus/src/OgreGL3PlusTextureBuffer.cpp +++ /dev/null @@ -1,575 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGL3PlusRenderSystem.h" -#include "OgreRoot.h" - -#include "OgreTextureManager.h" - -#include "OgreGL3PlusHardwareBufferManager.h" -#include "OgreGL3PlusHardwarePixelBuffer.h" -#include "OgreGL3PlusTextureBuffer.h" -#include "OgreGL3PlusPixelFormat.h" -#include "OgreGL3PlusFBORenderTexture.h" -#include "OgreGL3PlusStateCacheManager.h" - -#include "OgreGLSLMonolithicProgram.h" -#include "OgreGLSLProgramManager.h" -#include "OgreGLSLSeparableProgram.h" - -#include "OgreGL3PlusTexture.h" - -namespace Ogre { - - GL3PlusTextureBuffer::GL3PlusTextureBuffer(GL3PlusTexture* parent, - GLint face, GLint level, uint32 width, uint32 height, - uint32 depth) - : GLHardwarePixelBufferCommon(width, height, depth, parent->getFormat(), (Usage)parent->getUsage()), - mTarget(parent->getGL3PlusTextureTarget()), mTextureID(parent->getGLID()), mLevel(level) - { - mRenderSystem = static_cast(Root::getSingleton().getRenderSystem()); - // Get face identifier - mFaceTarget = mTarget; - if (mTarget == GL_TEXTURE_CUBE_MAP) - mFaceTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + face; - - // Get format - mGLInternalFormat = GL3PlusPixelUtil::getGLInternalFormat(mFormat, parent->isHardwareGammaEnabled()); - - // Log a message - // std::stringstream str; - // str << "GL3PlusHardwarePixelBuffer constructed for texture: " << mTextureID - // << " bytes: " << mSizeInBytes - // << " face: " << mFace << " level: " << mLevel - // << " width: " << mWidth << " height: "<< mHeight << " depth: " << mDepth - // << " format: " << PixelUtil::getFormatName(mFormat) - // << "(internal 0x" << std::hex << value << ")"; - // LogManager::getSingleton().logMessage(LML_NORMAL, str.str()); - - // Set up a pixel box - mBuffer = PixelBox(mWidth, mHeight, mDepth, mFormat); - - if (mWidth==0 || mHeight==0 || mDepth==0) - // We are invalid, do not allocate a buffer - return; - - // Is this a render target? - if (mUsage & TU_RENDERTARGET) - { - // Create render target for each slice - mSliceTRT.reserve(mDepth); - for(uint32 zoffset=0; zoffsetgetName(); - GLSurfaceDesc surface; - surface.buffer = this; - surface.zoffset = zoffset; - RenderTexture* trt = GL3PlusRTTManager::getSingleton().createRenderTexture( - name, surface, parent->isHardwareGammaEnabled(), parent->getFSAA()); - mSliceTRT.push_back(trt); - Root::getSingleton().getRenderSystem()->attachRenderTarget(*mSliceTRT[zoffset]); - } - } - } - - - GL3PlusTextureBuffer::~GL3PlusTextureBuffer() - { - } - - - void GL3PlusTextureBuffer::upload(const PixelBox &data, const Box &dest) - { - mRenderSystem->_getStateCacheManager()->bindGLTexture( mTarget, mTextureID ); - - // PBOs have no advantage with this usage pattern - // see: https://www.khronos.org/opengl/wiki/Pixel_Buffer_Object -#ifdef USE_PBO - // Calculate size for all mip levels of the texture. - size_t dataSize = data.getConsecutiveSize(); - GL3PlusHardwareBuffer buffer(GL_PIXEL_UNPACK_BUFFER, dataSize, mUsage); - buffer.writeData(0, dataSize, data.data, false); - - PixelBox tmp(data.getWidth(), data.getHeight(), data.getHeight(), data.format); - tmp.data = buffer.lockImpl(0, dataSize, HardwareBuffer::HBL_DISCARD); - PixelUtil::bulkPixelConversion(data, tmp); - buffer.unlockImpl(dataSize); - - // std::stringstream str; - // str << "GL3PlusHardwarePixelBuffer::upload: " << mTextureID - // << " pixel buffer: " << buffer.getGLBufferId() - // << " bytes: " << mSizeInBytes - // << " dest depth: " << dest.getDepth() - // << " dest front: " << dest.front - // << " datasize: " << dataSize - // << " face: " << mFace << " level: " << mLevel - // << " width: " << mWidth << " height: "<< mHeight << " depth: " << mDepth - // << " format: " << PixelUtil::getFormatName(mFormat); - // LogManager::getSingleton().logMessage(LML_NORMAL, str.str()); - - void* pdata = NULL; -#else - void* pdata = data.getTopLeftFrontPixelPtr(); -#endif - - if (PixelUtil::isCompressed(data.format)) - { - if (data.format != mFormat || !data.isConsecutive()) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Compressed images must be consecutive and in the designated source format", - "GL3PlusTextureBuffer::upload"); - - GLenum format = GL3PlusPixelUtil::getGLInternalFormat(mFormat); - // Data must be consecutive and at beginning of buffer as - // PixelStorei not allowed for compressed formats. - switch(mTarget) - { - case GL_TEXTURE_1D: - // Some systems (e.g. old Apple) don't like compressed - // subimage calls so prefer non-sub versions. - OGRE_CHECK_GL_ERROR(glCompressedTexSubImage1D( - GL_TEXTURE_1D, mLevel, - dest.left, - dest.getWidth(), - format, data.getConsecutiveSize(), - pdata)); - break; - case GL_TEXTURE_2D: - case GL_TEXTURE_CUBE_MAP: - case GL_TEXTURE_RECTANGLE: - OGRE_CHECK_GL_ERROR(glCompressedTexSubImage2D( - mFaceTarget, mLevel, - dest.left, dest.top, - dest.getWidth(), dest.getHeight(), - format, data.getConsecutiveSize(), - pdata)); - break; - case GL_TEXTURE_3D: - case GL_TEXTURE_2D_ARRAY: - OGRE_CHECK_GL_ERROR(glCompressedTexSubImage3D( - mTarget, mLevel, - dest.left, dest.top, dest.front, - dest.getWidth(), dest.getHeight(), dest.getDepth(), - format, data.getConsecutiveSize(), - pdata)); - break; - } - - } - else - { -#ifndef USE_PBO - if (data.getWidth() != data.rowPitch) - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_ROW_LENGTH, data.rowPitch)); - if (data.getHeight() * data.getWidth() != data.slicePitch) - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, (data.slicePitch/data.getWidth()))); -#endif - if ((data.getWidth()*PixelUtil::getNumElemBytes(data.format)) & 3) { - // Standard alignment of 4 is not right. - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_ALIGNMENT, 1)); - } - - GLenum type = GL3PlusPixelUtil::getGLOriginDataType(data.format); - - if (PixelUtil::isDepth(data.format)) - { - switch (GL3PlusPixelUtil::getGLInternalFormat(data.format)) - { - case GL_DEPTH_COMPONENT16: - type = GL_UNSIGNED_SHORT; - break; - - default: - case GL_DEPTH_COMPONENT24: - case GL_DEPTH_COMPONENT32: - type = GL_UNSIGNED_INT; - break; - - case GL_DEPTH_COMPONENT32F: - type = GL_FLOAT; - break; - } - } - - switch(mTarget) - { - case GL_TEXTURE_1D: - OGRE_CHECK_GL_ERROR(glTexSubImage1D( - GL_TEXTURE_1D, mLevel, - dest.left, - dest.getWidth(), - GL3PlusPixelUtil::getGLOriginFormat(data.format), - type, - pdata)); - break; - case GL_TEXTURE_2D: - case GL_TEXTURE_CUBE_MAP: - case GL_TEXTURE_RECTANGLE: - OGRE_CHECK_GL_ERROR(glTexSubImage2D( - mFaceTarget, mLevel, - dest.left, dest.top, - dest.getWidth(), dest.getHeight(), - GL3PlusPixelUtil::getGLOriginFormat(data.format), - type, - pdata)); - break; - case GL_TEXTURE_3D: - case GL_TEXTURE_2D_ARRAY: - OGRE_CHECK_GL_ERROR(glTexSubImage3D( - mTarget, mLevel, - dest.left, dest.top, dest.front, - dest.getWidth(), dest.getHeight(), dest.getDepth(), - GL3PlusPixelUtil::getGLOriginFormat(data.format), - type, - pdata)); - break; - } - } - - // TU_AUTOMIPMAP is only enabled when there are no custom mips - // so we do not have to care about overwriting - if ((mUsage & TU_AUTOMIPMAP) && (mLevel == 0)) - { - OGRE_CHECK_GL_ERROR(glGenerateMipmap(mTarget)); - } - - // Restore defaults. - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)); - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0)); - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_ALIGNMENT, 4)); - } - - - void GL3PlusTextureBuffer::download(const PixelBox &data) - { - if (data.getSize() != getSize()) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "only download of entire buffer is supported by GL", - "GL3PlusTextureBuffer::download"); - - // Download data to PBO - GL3PlusHardwareBuffer buffer(GL_PIXEL_PACK_BUFFER, data.getConsecutiveSize(), HBU_GPU_TO_CPU); - - // std::stringstream str; - // str << "GL3PlusHardwarePixelBuffer::download: " << mTextureID - // << " pixel buffer: " << mBufferId - // << " bytes: " << mSizeInBytes - // << " face: " << mFace << " level: " << mLevel - // << " width: " << mWidth << " height: "<< mHeight << " depth: " << mDepth - // << " format: " << PixelUtil::getFormatName(mFormat); - // LogManager::getSingleton().logMessage(LML_NORMAL, str.str()); - - mRenderSystem->_getStateCacheManager()->bindGLTexture(mTarget, mTextureID); - - if (PixelUtil::isCompressed(data.format)) - { - if (data.format != mFormat || !data.isConsecutive()) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Compressed images must be consecutive, in the source format", - "GL3PlusTextureBuffer::download"); - // Data must be consecutive and at beginning of buffer as PixelStorei not allowed - // for compressed formate - OGRE_CHECK_GL_ERROR(glGetCompressedTexImage(mFaceTarget, mLevel, 0)); - } - else - { - if ((data.getWidth()*PixelUtil::getNumElemBytes(data.format)) & 3) { - // Standard alignment of 4 is not right - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_PACK_ALIGNMENT, 1)); - } - // We can only get the entire texture - OGRE_CHECK_GL_ERROR(glGetTexImage(mFaceTarget, mLevel, - GL3PlusPixelUtil::getGLOriginFormat(data.format), - GL3PlusPixelUtil::getGLOriginDataType(data.format), - 0)); - - // Restore defaults - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_PACK_ALIGNMENT, 4)); - } - - // Copy to destination buffer - if(data.isConsecutive()) - buffer.readData(0, data.getConsecutiveSize(), data.getTopLeftFrontPixelPtr()); - else - { - size_t srcOffset = 0, elemSizeInBytes = PixelUtil::getNumElemBytes(data.format); - for(size_t z = 0; z < mDepth; ++z) - for(size_t y = 0; y < mHeight; ++y) - { - buffer.readData(srcOffset, mWidth * elemSizeInBytes, - (uint8*)data.getTopLeftFrontPixelPtr() + (z * data.slicePitch + y * data.rowPitch) * elemSizeInBytes); - srcOffset += mWidth * elemSizeInBytes; - } - } - } - - - void GL3PlusTextureBuffer::bindToFramebuffer(uint32 attachment, uint32 zoffset) - { - // Delegate the framebuffer binding to a more specific function - // This call retains the original implementation using GL_FRAMEBUFFER (aka GL_DRAW_FRAMEBUFFER) - _bindToFramebuffer(attachment, zoffset, GL_DRAW_FRAMEBUFFER); - } - - - void GL3PlusTextureBuffer::copyFromFramebuffer(uint32 zoffset) - { - mRenderSystem->_getStateCacheManager()->bindGLTexture(mTarget, mTextureID); - switch(mTarget) - { - case GL_TEXTURE_1D: - OGRE_CHECK_GL_ERROR(glCopyTexSubImage1D(mFaceTarget, mLevel, 0, 0, 0, mWidth)); - break; - case GL_TEXTURE_2D: - case GL_TEXTURE_CUBE_MAP: - case GL_TEXTURE_RECTANGLE: - OGRE_CHECK_GL_ERROR(glCopyTexSubImage2D(mFaceTarget, mLevel, 0, 0, 0, 0, mWidth, mHeight)); - break; - case GL_TEXTURE_3D: - case GL_TEXTURE_2D_ARRAY: - OGRE_CHECK_GL_ERROR(glCopyTexSubImage3D(mFaceTarget, mLevel, 0, 0, zoffset, 0, 0, mWidth, mHeight)); - break; - } - } - - - void GL3PlusTextureBuffer::blit(const HardwarePixelBufferSharedPtr &src, const Box &srcBox, const Box &dstBox) - { - GL3PlusTextureBuffer *srct = static_cast(src.get()); - // Check for FBO support first - if (GLRTTManager::getSingleton().checkFormat(mFormat)) - { - blitFromTexture(srct, srcBox, dstBox); - } - else - { - GLHardwarePixelBufferCommon::blit(src, srcBox, dstBox); - } - } - - void GL3PlusTextureBuffer::blitFromTexture(GL3PlusTextureBuffer *src, const Box &srcBox, const Box &dstBox) - { - // std::cerr << "GL3PlusTextureBuffer::blitFromTexture " << - // src->mTextureID << ":" << srcBox.left << "," << srcBox.top << "," << srcBox.right << "," << srcBox.bottom << " " << - // mTextureID << ":" << dstBox.left << "," << dstBox.top << "," << dstBox.right << "," << dstBox.bottom << std::endl; - GLenum filtering = GL_LINEAR; - - // Set filtering modes depending on the dimensions and source - if (srcBox.getSize()==dstBox.getSize()) - { - // Dimensions match -- use nearest filtering (fastest and pixel correct) - filtering = GL_NEAREST; - } - - // Store old binding so it can be restored later - GLint oldfb; - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldfb)); - - // Set up temporary FBOs - GLuint tempFBO[2] = { 0, 0 }; - OGRE_CHECK_GL_ERROR(glGenFramebuffers(2, tempFBO)); - mRenderSystem->_getStateCacheManager()->bindGLFrameBuffer( GL_DRAW_FRAMEBUFFER, tempFBO[0] ); - mRenderSystem->_getStateCacheManager()->bindGLFrameBuffer( GL_READ_FRAMEBUFFER, tempFBO[1] ); - - bool isDepth = PixelUtil::isDepth(mFormat); - - // Process each destination slice - for(uint32 slice = dstBox.front; slice < dstBox.back; ++slice) - { - // Bind directly - bindToFramebuffer(isDepth ? GL_DEPTH_ATTACHMENT : GL_COLOR_ATTACHMENT0, slice); - - OGRE_CHECK_GL_ERROR(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER)); - - GLbitfield mask = 0; - - // Bind the appropriate source texture to the read framebuffer - src->_bindToFramebuffer(isDepth ? GL_DEPTH_ATTACHMENT : GL_COLOR_ATTACHMENT0, slice, - GL_READ_FRAMEBUFFER); - if (isDepth) - { - // Depth framebuffer sources can only be blit with nearest filtering - filtering = GL_NEAREST; - mask |= GL_DEPTH_BUFFER_BIT; - } - else - { - OGRE_CHECK_GL_ERROR(glReadBuffer(GL_COLOR_ATTACHMENT0)); - mask |= GL_COLOR_BUFFER_BIT; - } - - OGRE_CHECK_GL_ERROR(glCheckFramebufferStatus(GL_READ_FRAMEBUFFER)); - - // Perform blit from the source texture bound to read framebuffer to - // this texture bound to draw framebuffer using the pixel coorinates. - // Sampling ouside the source box is implicitly handled using GL_CLAMP_TO_EDGE. - OGRE_CHECK_GL_ERROR(glBlitFramebuffer(srcBox.left, srcBox.top, srcBox.right, srcBox.bottom, - dstBox.left, dstBox.top, dstBox.right, dstBox.bottom, - mask, filtering)); - } - - - // Generate mipmaps - if (mUsage & TU_AUTOMIPMAP) - { - mRenderSystem->_getStateCacheManager()->bindGLTexture( mTarget, mTextureID ); - OGRE_CHECK_GL_ERROR(glGenerateMipmap(mTarget)); - } - - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( - GL_DRAW_FRAMEBUFFER, isDepth ? GL_DEPTH_ATTACHMENT : GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, 0)); - - // Reset read buffer/framebuffer - OGRE_CHECK_GL_ERROR(glReadBuffer(GL_NONE)); - mRenderSystem->_getStateCacheManager()->bindGLFrameBuffer( GL_READ_FRAMEBUFFER, 0 ); - - // Restore old framebuffer - mRenderSystem->_getStateCacheManager()->bindGLFrameBuffer( GL_DRAW_FRAMEBUFFER, oldfb); - - mRenderSystem->_getStateCacheManager()->deleteGLFrameBuffer(GL_FRAMEBUFFER, tempFBO[0]); - mRenderSystem->_getStateCacheManager()->deleteGLFrameBuffer(GL_FRAMEBUFFER, tempFBO[1]); - } - - void GL3PlusTextureBuffer::_bindToFramebuffer(GLenum attachment, uint32 zoffset, GLenum which) - { - assert(zoffset < mDepth); - assert(which == GL_READ_FRAMEBUFFER || which == GL_DRAW_FRAMEBUFFER || which == GL_FRAMEBUFFER); - - mRenderSystem->_getStateCacheManager()->bindGLTexture( mTarget, mTextureID ); - switch(mTarget) - { - case GL_TEXTURE_1D: - case GL_TEXTURE_2D: - case GL_TEXTURE_RECTANGLE: - OGRE_CHECK_GL_ERROR(glFramebufferTexture(which, attachment, - mTextureID, mLevel)); - break; - case GL_TEXTURE_CUBE_MAP: - OGRE_CHECK_GL_ERROR(glFramebufferTexture2D(which, GL_COLOR_ATTACHMENT0, - mFaceTarget, mTextureID, mLevel)); - break; - case GL_TEXTURE_3D: - case GL_TEXTURE_2D_ARRAY: - OGRE_CHECK_GL_ERROR(glFramebufferTexture3D(which, attachment, - mFaceTarget, mTextureID, mLevel, zoffset)); - break; - } - } - - - // blitFromMemory doing hardware bilinear scaling - void GL3PlusTextureBuffer::blitFromMemory(const PixelBox &src, const Box &dstBox) - { - if (!mBuffer.contains(dstBox)) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Destination box out of range"); - - // Fall back to normal GLHardwarePixelBuffer::blitFromMemory in case - // the source dimensions match the destination ones, in which case no scaling is needed - if (src.getSize() == dstBox.getSize()) - { - _blitFromMemory(src, dstBox); - return; - } - - TextureType type = (src.getDepth() != 1) ? TEX_TYPE_3D : TEX_TYPE_2D; - - // no mipmaps. blitFromTexture does not use them - TexturePtr tex = TextureManager::getSingleton().createManual( - "GLBlitFromMemoryTMP", ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, type, - src.getWidth(), src.getHeight(), src.getDepth(), 0, src.format); - - // Upload data to 0,0,0 in temporary texture - Box tempTarget(src.getSize()); - tex->getBuffer()->blitFromMemory(src, tempTarget); - - // Blit from texture - blit(tex->getBuffer(), tempTarget, dstBox); - - // Delete temp texture - TextureManager::getSingleton().remove(tex); - } - void GL3PlusTextureBuffer::_blitFromMemory(const PixelBox &src, const Box& dst) - { - PixelBox converted; - - if (GL3PlusPixelUtil::getGLInternalFormat(src.format) == 0) - { - // Extents match, but format is not accepted as valid - // source format for GL. Do conversion in temporary buffer. - allocateBuffer(); - converted = mBuffer.getSubVolume(src); - PixelUtil::bulkPixelConversion(src, converted); - } - else - { - // No conversion needed. - converted = src; - } - - upload(converted, dst); - freeBuffer(); - } - - void GL3PlusTextureBuffer::blitToMemory(const Box &srcBox, const PixelBox &dst) - { - if (!mBuffer.contains(srcBox)) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "source box out of range", - "GL3PlusHardwarePixelBuffer::blitToMemory"); - } - - if (srcBox.getOrigin() == Vector3i(0, 0 ,0) && - srcBox.getSize() == getSize() && - dst.getSize() == getSize() && - GL3PlusPixelUtil::getGLInternalFormat(dst.format) != 0) - { - // The direct case: the user wants the entire texture in a format supported by GL - // so we don't need an intermediate buffer - download(dst); - } - else - { - // Use buffer for intermediate copy - allocateBuffer(); - // Download entire buffer - download(mBuffer); - if(srcBox.getSize() != dst.getSize()) - { - // We need scaling - Image::scale(mBuffer.getSubVolume(srcBox), dst, Image::FILTER_BILINEAR); - } - else - { - // Just copy the bit that we need - PixelUtil::bulkPixelConversion(mBuffer.getSubVolume(srcBox), dst); - } - freeBuffer(); - } - } -} diff --git a/RenderSystems/GL3Plus/src/OgreGL3PlusTextureManager.cpp b/RenderSystems/GL3Plus/src/OgreGL3PlusTextureManager.cpp deleted file mode 100644 index 82d5488eea2..00000000000 --- a/RenderSystems/GL3Plus/src/OgreGL3PlusTextureManager.cpp +++ /dev/null @@ -1,277 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGL3PlusTextureManager.h" -#include "OgreGL3PlusStateCacheManager.h" -#include "OgreGL3PlusRenderSystem.h" -#include "OgreGLRenderTexture.h" -#include "OgreRoot.h" -#include "OgreGL3PlusPixelFormat.h" - -#ifndef GL_EXT_texture_filter_anisotropic -#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE -#endif - -namespace Ogre { - GLint GL3PlusSampler::getCombinedMinMipFilter(FilterOptions min, FilterOptions mip) - { - switch(min) - { - case FO_ANISOTROPIC: - case FO_LINEAR: - switch (mip) - { - case FO_ANISOTROPIC: - case FO_LINEAR: - // linear min, linear mip - return GL_LINEAR_MIPMAP_LINEAR; - case FO_POINT: - // linear min, point mip - return GL_LINEAR_MIPMAP_NEAREST; - case FO_NONE: - // linear min, no mip - return GL_LINEAR; - } - break; - case FO_POINT: - case FO_NONE: - switch (mip) - { - case FO_ANISOTROPIC: - case FO_LINEAR: - // nearest min, linear mip - return GL_NEAREST_MIPMAP_LINEAR; - case FO_POINT: - // nearest min, point mip - return GL_NEAREST_MIPMAP_NEAREST; - case FO_NONE: - // nearest min, no mip - return GL_NEAREST; - } - break; - } - - // should never get here - return 0; - } - - GLint GL3PlusSampler::getTextureAddressingMode(TextureAddressingMode tam) - { - switch (tam) - { - default: - case TextureUnitState::TAM_WRAP: - return GL_REPEAT; - case TextureUnitState::TAM_MIRROR: - return GL_MIRRORED_REPEAT; - case TextureUnitState::TAM_CLAMP: - return GL_CLAMP_TO_EDGE; - case TextureUnitState::TAM_BORDER: - return GL_CLAMP_TO_BORDER; - } - } - - GL3PlusSampler::GL3PlusSampler(GL3PlusRenderSystem* rs) : mSamplerId(0) - { - glGenSamplers(1, &mSamplerId); - } - GL3PlusSampler::~GL3PlusSampler() - { - glDeleteSamplers(1, &mSamplerId); - } - void GL3PlusSampler::bind(uint32 unit) - { - OGRE_CHECK_GL_ERROR(glBindSampler(unit, mSamplerId)); - - if(!mDirty) - return; - - OGRE_CHECK_GL_ERROR(glSamplerParameteri(mSamplerId, GL_TEXTURE_WRAP_S, - getTextureAddressingMode(mAddressMode.u))); - OGRE_CHECK_GL_ERROR(glSamplerParameteri(mSamplerId, GL_TEXTURE_WRAP_T, - getTextureAddressingMode(mAddressMode.v))); - OGRE_CHECK_GL_ERROR(glSamplerParameteri(mSamplerId, GL_TEXTURE_WRAP_R, - getTextureAddressingMode(mAddressMode.w))); - - bool reversedZ = Root::getSingleton().getRenderSystem()->isReverseDepthBufferEnabled(); - - if (mAddressMode.u == TAM_BORDER || mAddressMode.v == TAM_BORDER || mAddressMode.w == TAM_BORDER) - { - auto borderColour = (reversedZ && mCompareEnabled) ? ColourValue::White - mBorderColour : mBorderColour; - OGRE_CHECK_GL_ERROR(glSamplerParameterfv( mSamplerId, GL_TEXTURE_BORDER_COLOR, borderColour.ptr())); - } - OGRE_CHECK_GL_ERROR(glSamplerParameterf(mSamplerId, GL_TEXTURE_LOD_BIAS, mMipmapBias)); - - auto caps = Root::getSingleton().getRenderSystem()->getCapabilities(); - if (caps->hasCapability(RSC_ANISOTROPY)) - OGRE_CHECK_GL_ERROR( - glSamplerParameteri(mSamplerId, GL_TEXTURE_MAX_ANISOTROPY_EXT, - std::min(caps->getMaxSupportedAnisotropy(), mMaxAniso))); - - OGRE_CHECK_GL_ERROR( - glSamplerParameteri(mSamplerId, GL_TEXTURE_COMPARE_MODE, - mCompareEnabled ? GL_COMPARE_REF_TO_TEXTURE : GL_NONE)); - - auto cmpFunc = mCompareFunc; - if(reversedZ) - cmpFunc = GL3PlusRenderSystem::reverseCompareFunction(cmpFunc); - - OGRE_CHECK_GL_ERROR( - glSamplerParameteri(mSamplerId, GL_TEXTURE_COMPARE_FUNC, - GL3PlusRenderSystem::convertCompareFunction(cmpFunc))); - - // Combine with existing mip filter - OGRE_CHECK_GL_ERROR(glSamplerParameteri(mSamplerId, GL_TEXTURE_MIN_FILTER, - getCombinedMinMipFilter(mMinFilter, mMipFilter))); - - switch (mMagFilter) - { - case FO_ANISOTROPIC: // GL treats linear and aniso the same - case FO_LINEAR: - OGRE_CHECK_GL_ERROR(glSamplerParameteri(mSamplerId, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); - break; - case FO_POINT: - case FO_NONE: - OGRE_CHECK_GL_ERROR(glSamplerParameteri(mSamplerId, GL_TEXTURE_MAG_FILTER, GL_NEAREST)); - break; - } - - mDirty = false; - } - - GL3PlusTextureManager::GL3PlusTextureManager(GL3PlusRenderSystem* renderSystem) - : TextureManager(), mRenderSystem(renderSystem) - { - // Register with group manager - ResourceGroupManager::getSingleton()._registerResourceManager(mResourceType, this); - } - - GL3PlusTextureManager::~GL3PlusTextureManager() - { - // Unregister with group manager - ResourceGroupManager::getSingleton()._unregisterResourceManager(mResourceType); - } - - Resource* GL3PlusTextureManager::createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, - ManualResourceLoader* loader, - const NameValuePairList* createParams) - { - return new GL3PlusTexture(this, name, handle, group, isManual, loader, mRenderSystem); - } - - SamplerPtr GL3PlusTextureManager::_createSamplerImpl() - { - return std::make_shared(mRenderSystem); - } - - // TexturePtr GL3PlusTextureManager::createManual(const String & name, const String& group, - // TextureType texType, uint width, uint height, uint depth, int numMipmaps, - // PixelFormat format, int usage, ManualResourceLoader* loader, bool hwGamma, - // uint fsaa, const String& fsaaHint) - // { - // TexturePtr texture = TextureManager::createManual( - // name, group, texType, - // width, height, depth, numMipmaps, - // format, usage, loader, hwGamma, - // fsaa, fsaaHint); - - // if (texture->getUsage() == TU_DYNAMIC_SHADER) - // { - // registerImage(texture); - // } - - // return texture; - // } - - - PixelFormat GL3PlusTextureManager::getNativeFormat(TextureType ttype, PixelFormat format, int usage) - { - // Adjust requested parameters to capabilities - const RenderSystemCapabilities *caps = Root::getSingleton().getRenderSystem()->getCapabilities(); - - // Check compressed texture support - // if a compressed format not supported, revert to PF_A8R8G8B8 - if(PixelUtil::isCompressed(format) && - !caps->hasCapability( RSC_TEXTURE_COMPRESSION_DXT )) - { - return PF_BYTE_RGBA; - } - // if floating point textures not supported, revert to PF_A8R8G8B8 - if (PixelUtil::isFloatingPoint(format) && - !caps->hasCapability(RSC_TEXTURE_FLOAT)) - { - return PF_BYTE_RGBA; - } - - // Check if this is a valid rendertarget format - if (usage & TU_RENDERTARGET) - { - /// Get closest supported alternative - /// If mFormat is supported it's returned - return GL3PlusRTTManager::getSingleton().getSupportedAlternative(format); - } - - if(GL3PlusPixelUtil::getGLInternalFormat(format) == GL_NONE) - { - return PF_BYTE_RGBA; - } - - // Supported - return format; - } - - // void GL3PlusTextureManager::registerImage(TexturePtr texture) - // { - // mImages.push_back(texture); - // } - - //FIXME Should this become a standard Texture class feature? - // void GL3PlusTextureManager::bindImages() - // { - // //FIXME currently produces a GL_INVALID_OPERATION, so temporarily run once - // // static bool images_bound = false; - - // TexturePtrList::iterator texture = mImages.begin(); - // TexturePtrList::iterator end = mImages.end(); - - // // if (!images_bound && !mImages.empty()) { - // for (; texture != end; texture++) - // { - // //std::cout << "IMAGE LOAD/STORE" << std::endl; - // GL3PlusTexturePtr tex = texture->staticCast(); - // //TODO This needs to be redone so that: - // // * binding point (first parameter) and possibly other parameters come from shader - // // * simple conversion of shader format to GLenum format - // // * material scripts can create images - // //OGRE_CHECK_GL_ERROR(glBindImageTexture(0, tex->getGLID(), 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA8)); - // } - // // images_bound = true; - // // } - // } -} diff --git a/RenderSystems/GL3Plus/src/OgreSPIRVShaderFactory.cpp b/RenderSystems/GL3Plus/src/OgreSPIRVShaderFactory.cpp deleted file mode 100644 index 02b1c38295f..00000000000 --- a/RenderSystems/GL3Plus/src/OgreSPIRVShaderFactory.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreSPIRVShaderFactory.h" -#include "OgreLogManager.h" -#include "OgreGLSLExtSupport.h" - - -namespace Ogre { - -SPIRVShader::SPIRVShader(ResourceManager* creator, const String& name, ResourceHandle handle, const String& group, - bool isManual, ManualResourceLoader* loader) - : GLSLShader(creator, name, handle, group, isManual, loader) -{ - if (createParamDictionary("SPIRVGpuProgram")) - { - setupBaseParamDictionary(); - } -} - -SPIRVShader::~SPIRVShader() -{ - // have to call this here reather than in Resource destructor - // since calling virtual methods in base destructors causes crash - unloadHighLevel(); -} - -const String& SPIRVShader::getLanguage(void) const -{ - static String language = "gl_spirv"; - return language; -} - -void SPIRVShader::compileSource(void) -{ - OGRE_CHECK_GL_ERROR(glShaderBinary(1, &mGLShaderHandle, GL_SHADER_BINARY_FORMAT_SPIR_V, mSource.data(), mSource.size())); - OGRE_CHECK_GL_ERROR(glSpecializeShader(mGLShaderHandle, mEntryPoint.c_str(), 0, NULL, NULL)); -} - -SPIRVShaderFactory::SPIRVShaderFactory() -{ - -} - -SPIRVShaderFactory::~SPIRVShaderFactory() -{ - -} - -const String& SPIRVShaderFactory::getLanguage(void) const -{ - static String language = "gl_spirv"; - return language; -} - -GpuProgram* SPIRVShaderFactory::create(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) -{ - return OGRE_NEW SPIRVShader(creator, name, handle, group, isManual, loader); -} -} diff --git a/RenderSystems/GL3Plus/src/gl3w.c b/RenderSystems/GL3Plus/src/gl3w.c deleted file mode 100644 index 66401e70ef7..00000000000 --- a/RenderSystems/GL3Plus/src/gl3w.c +++ /dev/null @@ -1,2641 +0,0 @@ -/* - - This file was generated with gl3w_gen.cmake, part of glXXw - (hosted at https://github.com/paroj/glXXw-cmake) - - This is free and unencumbered software released into the public domain. - - Anyone is free to copy, modify, publish, use, compile, sell, or - distribute this software, either in source code form or as a compiled - binary, for any purpose, commercial or non-commercial, and by any - means. - - In jurisdictions that recognize copyright laws, the author or authors - of this software dedicate any and all copyright interest in the - software to the public domain. We make this dedication for the benefit - of the public at large and to the detriment of our heirs and - successors. We intend this dedication to be an overt act of - relinquishment in perpetuity of all present and future rights to this - software under copyright law. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. - -*/ - -#include - -#ifdef _WIN32 -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN 1 -#endif -#include - -static HMODULE libgl; -static PROC (__stdcall *wgl_get_proc_address)(LPCSTR); - -static void open_libgl(void) -{ - libgl = LoadLibraryA("opengl32.dll"); - *(void **)(&wgl_get_proc_address) = GetProcAddress(libgl, "wglGetProcAddress"); -} - -static void close_libgl(void) -{ - FreeLibrary(libgl); -} - -static GL3WglProc get_proc(const char *proc) -{ - GL3WglProc res; - - res = (GL3WglProc)wgl_get_proc_address(proc); - if (!res) - res = (GL3WglProc)GetProcAddress(libgl, proc); - return res; -} -#elif defined(__APPLE__) || defined(__APPLE_CC__) -#include - -static void *libgl; - -static void open_libgl(void) -{ - libgl = dlopen("/System/Library/Frameworks/OpenGL.framework/OpenGL", RTLD_LAZY | RTLD_LOCAL); -} - -static void close_libgl(void) -{ - dlclose(libgl); -} - -static GL3WglProc get_proc(const char *proc) -{ - GL3WglProc res; - - *(void **)(&res) = dlsym(libgl, proc); - return res; -} -#else -#include - -typedef GL3WglProc (*PFNGLXGETPROCADDRESSPROC)(const GLubyte *); -static void *libgl; -static PFNGLXGETPROCADDRESSPROC glx_get_proc_address; - -static void open_libgl(void) -{ - libgl = dlopen("libGL.so.1", RTLD_LAZY | RTLD_LOCAL); - *(void **)(&glx_get_proc_address) = dlsym(libgl, "glXGetProcAddressARB"); -} - -static void close_libgl(void) -{ - dlclose(libgl); -} - -static GL3WglProc get_proc(const char *proc) -{ - GL3WglProc res; - - res = glx_get_proc_address((const GLubyte *)proc); - if (!res) - *(void **)(&res) = dlsym(libgl, proc); - return res; -} -#endif - -static struct { - int major, minor; -} version; - -static int parse_version(void) -{ - if (!glGetIntegerv) - return -1; - - glGetIntegerv(GL_MAJOR_VERSION, &version.major); - glGetIntegerv(GL_MINOR_VERSION, &version.minor); - - if (version.major < 3) - return -1; - return 0; -} - -static void load_procs(GL3WGetProcAddressProc proc); - -int gl3wInit(void) -{ - open_libgl(); - load_procs(get_proc); - close_libgl(); - return parse_version(); -} - -int gl3wInit2(GL3WGetProcAddressProc proc) -{ - load_procs(proc); - return parse_version(); -} - -int gl3wIsSupported(int major, int minor) -{ - if (major < 3) - return 0; - if (version.major == major) - return version.minor >= minor; - return version.major >= major; -} - -GL3WglProc gl3wGetProcAddress(const char *proc) -{ - return get_proc(proc); -} - -PFNGLACTIVEPROGRAMEXTPROC gl3wActiveProgramEXT; -PFNGLACTIVESHADERPROGRAMPROC gl3wActiveShaderProgram; -PFNGLACTIVETEXTUREPROC gl3wActiveTexture; -PFNGLAPPLYFRAMEBUFFERATTACHMENTCMAAINTELPROC gl3wApplyFramebufferAttachmentCMAAINTEL; -PFNGLATTACHSHADERPROC gl3wAttachShader; -PFNGLBEGINCONDITIONALRENDERPROC gl3wBeginConditionalRender; -PFNGLBEGINCONDITIONALRENDERNVPROC gl3wBeginConditionalRenderNV; -PFNGLBEGINPERFMONITORAMDPROC gl3wBeginPerfMonitorAMD; -PFNGLBEGINPERFQUERYINTELPROC gl3wBeginPerfQueryINTEL; -PFNGLBEGINQUERYPROC gl3wBeginQuery; -PFNGLBEGINQUERYINDEXEDPROC gl3wBeginQueryIndexed; -PFNGLBEGINTRANSFORMFEEDBACKPROC gl3wBeginTransformFeedback; -PFNGLBINDATTRIBLOCATIONPROC gl3wBindAttribLocation; -PFNGLBINDBUFFERPROC gl3wBindBuffer; -PFNGLBINDBUFFERBASEPROC gl3wBindBufferBase; -PFNGLBINDBUFFERRANGEPROC gl3wBindBufferRange; -PFNGLBINDBUFFERSBASEPROC gl3wBindBuffersBase; -PFNGLBINDBUFFERSRANGEPROC gl3wBindBuffersRange; -PFNGLBINDFRAGDATALOCATIONPROC gl3wBindFragDataLocation; -PFNGLBINDFRAGDATALOCATIONINDEXEDPROC gl3wBindFragDataLocationIndexed; -PFNGLBINDFRAMEBUFFERPROC gl3wBindFramebuffer; -PFNGLBINDIMAGETEXTUREPROC gl3wBindImageTexture; -PFNGLBINDIMAGETEXTURESPROC gl3wBindImageTextures; -PFNGLBINDMULTITEXTUREEXTPROC gl3wBindMultiTextureEXT; -PFNGLBINDPROGRAMPIPELINEPROC gl3wBindProgramPipeline; -PFNGLBINDRENDERBUFFERPROC gl3wBindRenderbuffer; -PFNGLBINDSAMPLERPROC gl3wBindSampler; -PFNGLBINDSAMPLERSPROC gl3wBindSamplers; -PFNGLBINDTEXTUREPROC gl3wBindTexture; -PFNGLBINDTEXTUREUNITPROC gl3wBindTextureUnit; -PFNGLBINDTEXTURESPROC gl3wBindTextures; -PFNGLBINDTRANSFORMFEEDBACKPROC gl3wBindTransformFeedback; -PFNGLBINDVERTEXARRAYPROC gl3wBindVertexArray; -PFNGLBINDVERTEXBUFFERPROC gl3wBindVertexBuffer; -PFNGLBINDVERTEXBUFFERSPROC gl3wBindVertexBuffers; -PFNGLBLENDBARRIERKHRPROC gl3wBlendBarrierKHR; -PFNGLBLENDBARRIERNVPROC gl3wBlendBarrierNV; -PFNGLBLENDCOLORPROC gl3wBlendColor; -PFNGLBLENDEQUATIONPROC gl3wBlendEquation; -PFNGLBLENDEQUATIONSEPARATEPROC gl3wBlendEquationSeparate; -PFNGLBLENDEQUATIONSEPARATEIPROC gl3wBlendEquationSeparatei; -PFNGLBLENDEQUATIONSEPARATEIARBPROC gl3wBlendEquationSeparateiARB; -PFNGLBLENDEQUATIONIPROC gl3wBlendEquationi; -PFNGLBLENDEQUATIONIARBPROC gl3wBlendEquationiARB; -PFNGLBLENDFUNCPROC gl3wBlendFunc; -PFNGLBLENDFUNCSEPARATEPROC gl3wBlendFuncSeparate; -PFNGLBLENDFUNCSEPARATEIPROC gl3wBlendFuncSeparatei; -PFNGLBLENDFUNCSEPARATEIARBPROC gl3wBlendFuncSeparateiARB; -PFNGLBLENDFUNCIPROC gl3wBlendFunci; -PFNGLBLENDFUNCIARBPROC gl3wBlendFunciARB; -PFNGLBLENDPARAMETERINVPROC gl3wBlendParameteriNV; -PFNGLBLITFRAMEBUFFERPROC gl3wBlitFramebuffer; -PFNGLBLITNAMEDFRAMEBUFFERPROC gl3wBlitNamedFramebuffer; -PFNGLBUFFERADDRESSRANGENVPROC gl3wBufferAddressRangeNV; -PFNGLBUFFERDATAPROC gl3wBufferData; -PFNGLBUFFERPAGECOMMITMENTARBPROC gl3wBufferPageCommitmentARB; -PFNGLBUFFERSTORAGEPROC gl3wBufferStorage; -PFNGLBUFFERSUBDATAPROC gl3wBufferSubData; -PFNGLCALLCOMMANDLISTNVPROC gl3wCallCommandListNV; -PFNGLCHECKFRAMEBUFFERSTATUSPROC gl3wCheckFramebufferStatus; -PFNGLCHECKNAMEDFRAMEBUFFERSTATUSPROC gl3wCheckNamedFramebufferStatus; -PFNGLCHECKNAMEDFRAMEBUFFERSTATUSEXTPROC gl3wCheckNamedFramebufferStatusEXT; -PFNGLCLAMPCOLORPROC gl3wClampColor; -PFNGLCLEARPROC gl3wClear; -PFNGLCLEARBUFFERDATAPROC gl3wClearBufferData; -PFNGLCLEARBUFFERSUBDATAPROC gl3wClearBufferSubData; -PFNGLCLEARBUFFERFIPROC gl3wClearBufferfi; -PFNGLCLEARBUFFERFVPROC gl3wClearBufferfv; -PFNGLCLEARBUFFERIVPROC gl3wClearBufferiv; -PFNGLCLEARBUFFERUIVPROC gl3wClearBufferuiv; -PFNGLCLEARCOLORPROC gl3wClearColor; -PFNGLCLEARDEPTHPROC gl3wClearDepth; -PFNGLCLEARDEPTHFPROC gl3wClearDepthf; -PFNGLCLEARNAMEDBUFFERDATAPROC gl3wClearNamedBufferData; -PFNGLCLEARNAMEDBUFFERDATAEXTPROC gl3wClearNamedBufferDataEXT; -PFNGLCLEARNAMEDBUFFERSUBDATAPROC gl3wClearNamedBufferSubData; -PFNGLCLEARNAMEDBUFFERSUBDATAEXTPROC gl3wClearNamedBufferSubDataEXT; -PFNGLCLEARNAMEDFRAMEBUFFERFIPROC gl3wClearNamedFramebufferfi; -PFNGLCLEARNAMEDFRAMEBUFFERFVPROC gl3wClearNamedFramebufferfv; -PFNGLCLEARNAMEDFRAMEBUFFERIVPROC gl3wClearNamedFramebufferiv; -PFNGLCLEARNAMEDFRAMEBUFFERUIVPROC gl3wClearNamedFramebufferuiv; -PFNGLCLEARSTENCILPROC gl3wClearStencil; -PFNGLCLEARTEXIMAGEPROC gl3wClearTexImage; -PFNGLCLEARTEXSUBIMAGEPROC gl3wClearTexSubImage; -PFNGLCLIENTATTRIBDEFAULTEXTPROC gl3wClientAttribDefaultEXT; -PFNGLCLIENTWAITSYNCPROC gl3wClientWaitSync; -PFNGLCLIPCONTROLPROC gl3wClipControl; -PFNGLCOLORFORMATNVPROC gl3wColorFormatNV; -PFNGLCOLORMASKPROC gl3wColorMask; -PFNGLCOLORMASKIPROC gl3wColorMaski; -PFNGLCOMMANDLISTSEGMENTSNVPROC gl3wCommandListSegmentsNV; -PFNGLCOMPILECOMMANDLISTNVPROC gl3wCompileCommandListNV; -PFNGLCOMPILESHADERPROC gl3wCompileShader; -PFNGLCOMPILESHADERINCLUDEARBPROC gl3wCompileShaderIncludeARB; -PFNGLCOMPRESSEDMULTITEXIMAGE1DEXTPROC gl3wCompressedMultiTexImage1DEXT; -PFNGLCOMPRESSEDMULTITEXIMAGE2DEXTPROC gl3wCompressedMultiTexImage2DEXT; -PFNGLCOMPRESSEDMULTITEXIMAGE3DEXTPROC gl3wCompressedMultiTexImage3DEXT; -PFNGLCOMPRESSEDMULTITEXSUBIMAGE1DEXTPROC gl3wCompressedMultiTexSubImage1DEXT; -PFNGLCOMPRESSEDMULTITEXSUBIMAGE2DEXTPROC gl3wCompressedMultiTexSubImage2DEXT; -PFNGLCOMPRESSEDMULTITEXSUBIMAGE3DEXTPROC gl3wCompressedMultiTexSubImage3DEXT; -PFNGLCOMPRESSEDTEXIMAGE1DPROC gl3wCompressedTexImage1D; -PFNGLCOMPRESSEDTEXIMAGE2DPROC gl3wCompressedTexImage2D; -PFNGLCOMPRESSEDTEXIMAGE3DPROC gl3wCompressedTexImage3D; -PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC gl3wCompressedTexSubImage1D; -PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC gl3wCompressedTexSubImage2D; -PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC gl3wCompressedTexSubImage3D; -PFNGLCOMPRESSEDTEXTUREIMAGE1DEXTPROC gl3wCompressedTextureImage1DEXT; -PFNGLCOMPRESSEDTEXTUREIMAGE2DEXTPROC gl3wCompressedTextureImage2DEXT; -PFNGLCOMPRESSEDTEXTUREIMAGE3DEXTPROC gl3wCompressedTextureImage3DEXT; -PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC gl3wCompressedTextureSubImage1D; -PFNGLCOMPRESSEDTEXTURESUBIMAGE1DEXTPROC gl3wCompressedTextureSubImage1DEXT; -PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC gl3wCompressedTextureSubImage2D; -PFNGLCOMPRESSEDTEXTURESUBIMAGE2DEXTPROC gl3wCompressedTextureSubImage2DEXT; -PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC gl3wCompressedTextureSubImage3D; -PFNGLCOMPRESSEDTEXTURESUBIMAGE3DEXTPROC gl3wCompressedTextureSubImage3DEXT; -PFNGLCONSERVATIVERASTERPARAMETERFNVPROC gl3wConservativeRasterParameterfNV; -PFNGLCONSERVATIVERASTERPARAMETERINVPROC gl3wConservativeRasterParameteriNV; -PFNGLCOPYBUFFERSUBDATAPROC gl3wCopyBufferSubData; -PFNGLCOPYIMAGESUBDATAPROC gl3wCopyImageSubData; -PFNGLCOPYMULTITEXIMAGE1DEXTPROC gl3wCopyMultiTexImage1DEXT; -PFNGLCOPYMULTITEXIMAGE2DEXTPROC gl3wCopyMultiTexImage2DEXT; -PFNGLCOPYMULTITEXSUBIMAGE1DEXTPROC gl3wCopyMultiTexSubImage1DEXT; -PFNGLCOPYMULTITEXSUBIMAGE2DEXTPROC gl3wCopyMultiTexSubImage2DEXT; -PFNGLCOPYMULTITEXSUBIMAGE3DEXTPROC gl3wCopyMultiTexSubImage3DEXT; -PFNGLCOPYNAMEDBUFFERSUBDATAPROC gl3wCopyNamedBufferSubData; -PFNGLCOPYPATHNVPROC gl3wCopyPathNV; -PFNGLCOPYTEXIMAGE1DPROC gl3wCopyTexImage1D; -PFNGLCOPYTEXIMAGE2DPROC gl3wCopyTexImage2D; -PFNGLCOPYTEXSUBIMAGE1DPROC gl3wCopyTexSubImage1D; -PFNGLCOPYTEXSUBIMAGE2DPROC gl3wCopyTexSubImage2D; -PFNGLCOPYTEXSUBIMAGE3DPROC gl3wCopyTexSubImage3D; -PFNGLCOPYTEXTUREIMAGE1DEXTPROC gl3wCopyTextureImage1DEXT; -PFNGLCOPYTEXTUREIMAGE2DEXTPROC gl3wCopyTextureImage2DEXT; -PFNGLCOPYTEXTURESUBIMAGE1DPROC gl3wCopyTextureSubImage1D; -PFNGLCOPYTEXTURESUBIMAGE1DEXTPROC gl3wCopyTextureSubImage1DEXT; -PFNGLCOPYTEXTURESUBIMAGE2DPROC gl3wCopyTextureSubImage2D; -PFNGLCOPYTEXTURESUBIMAGE2DEXTPROC gl3wCopyTextureSubImage2DEXT; -PFNGLCOPYTEXTURESUBIMAGE3DPROC gl3wCopyTextureSubImage3D; -PFNGLCOPYTEXTURESUBIMAGE3DEXTPROC gl3wCopyTextureSubImage3DEXT; -PFNGLCOVERFILLPATHINSTANCEDNVPROC gl3wCoverFillPathInstancedNV; -PFNGLCOVERFILLPATHNVPROC gl3wCoverFillPathNV; -PFNGLCOVERSTROKEPATHINSTANCEDNVPROC gl3wCoverStrokePathInstancedNV; -PFNGLCOVERSTROKEPATHNVPROC gl3wCoverStrokePathNV; -PFNGLCOVERAGEMODULATIONNVPROC gl3wCoverageModulationNV; -PFNGLCOVERAGEMODULATIONTABLENVPROC gl3wCoverageModulationTableNV; -PFNGLCREATEBUFFERSPROC gl3wCreateBuffers; -PFNGLCREATECOMMANDLISTSNVPROC gl3wCreateCommandListsNV; -PFNGLCREATEFRAMEBUFFERSPROC gl3wCreateFramebuffers; -PFNGLCREATEPERFQUERYINTELPROC gl3wCreatePerfQueryINTEL; -PFNGLCREATEPROGRAMPROC gl3wCreateProgram; -PFNGLCREATEPROGRAMPIPELINESPROC gl3wCreateProgramPipelines; -PFNGLCREATEQUERIESPROC gl3wCreateQueries; -PFNGLCREATERENDERBUFFERSPROC gl3wCreateRenderbuffers; -PFNGLCREATESAMPLERSPROC gl3wCreateSamplers; -PFNGLCREATESHADERPROC gl3wCreateShader; -PFNGLCREATESHADERPROGRAMEXTPROC gl3wCreateShaderProgramEXT; -PFNGLCREATESHADERPROGRAMVPROC gl3wCreateShaderProgramv; -PFNGLCREATESTATESNVPROC gl3wCreateStatesNV; -PFNGLCREATESYNCFROMCLEVENTARBPROC gl3wCreateSyncFromCLeventARB; -PFNGLCREATETEXTURESPROC gl3wCreateTextures; -PFNGLCREATETRANSFORMFEEDBACKSPROC gl3wCreateTransformFeedbacks; -PFNGLCREATEVERTEXARRAYSPROC gl3wCreateVertexArrays; -PFNGLCULLFACEPROC gl3wCullFace; -PFNGLDEBUGMESSAGECALLBACKPROC gl3wDebugMessageCallback; -PFNGLDEBUGMESSAGECALLBACKARBPROC gl3wDebugMessageCallbackARB; -PFNGLDEBUGMESSAGECONTROLPROC gl3wDebugMessageControl; -PFNGLDEBUGMESSAGECONTROLARBPROC gl3wDebugMessageControlARB; -PFNGLDEBUGMESSAGEINSERTPROC gl3wDebugMessageInsert; -PFNGLDEBUGMESSAGEINSERTARBPROC gl3wDebugMessageInsertARB; -PFNGLDELETEBUFFERSPROC gl3wDeleteBuffers; -PFNGLDELETECOMMANDLISTSNVPROC gl3wDeleteCommandListsNV; -PFNGLDELETEFRAMEBUFFERSPROC gl3wDeleteFramebuffers; -PFNGLDELETENAMEDSTRINGARBPROC gl3wDeleteNamedStringARB; -PFNGLDELETEPATHSNVPROC gl3wDeletePathsNV; -PFNGLDELETEPERFMONITORSAMDPROC gl3wDeletePerfMonitorsAMD; -PFNGLDELETEPERFQUERYINTELPROC gl3wDeletePerfQueryINTEL; -PFNGLDELETEPROGRAMPROC gl3wDeleteProgram; -PFNGLDELETEPROGRAMPIPELINESPROC gl3wDeleteProgramPipelines; -PFNGLDELETEQUERIESPROC gl3wDeleteQueries; -PFNGLDELETERENDERBUFFERSPROC gl3wDeleteRenderbuffers; -PFNGLDELETESAMPLERSPROC gl3wDeleteSamplers; -PFNGLDELETESHADERPROC gl3wDeleteShader; -PFNGLDELETESTATESNVPROC gl3wDeleteStatesNV; -PFNGLDELETESYNCPROC gl3wDeleteSync; -PFNGLDELETETEXTURESPROC gl3wDeleteTextures; -PFNGLDELETETRANSFORMFEEDBACKSPROC gl3wDeleteTransformFeedbacks; -PFNGLDELETEVERTEXARRAYSPROC gl3wDeleteVertexArrays; -PFNGLDEPTHFUNCPROC gl3wDepthFunc; -PFNGLDEPTHMASKPROC gl3wDepthMask; -PFNGLDEPTHRANGEPROC gl3wDepthRange; -PFNGLDEPTHRANGEARRAYVPROC gl3wDepthRangeArrayv; -PFNGLDEPTHRANGEINDEXEDPROC gl3wDepthRangeIndexed; -PFNGLDEPTHRANGEFPROC gl3wDepthRangef; -PFNGLDETACHSHADERPROC gl3wDetachShader; -PFNGLDISABLEPROC gl3wDisable; -PFNGLDISABLECLIENTSTATEINDEXEDEXTPROC gl3wDisableClientStateIndexedEXT; -PFNGLDISABLECLIENTSTATEIEXTPROC gl3wDisableClientStateiEXT; -PFNGLDISABLEINDEXEDEXTPROC gl3wDisableIndexedEXT; -PFNGLDISABLEVERTEXARRAYATTRIBPROC gl3wDisableVertexArrayAttrib; -PFNGLDISABLEVERTEXARRAYATTRIBEXTPROC gl3wDisableVertexArrayAttribEXT; -PFNGLDISABLEVERTEXARRAYEXTPROC gl3wDisableVertexArrayEXT; -PFNGLDISABLEVERTEXATTRIBARRAYPROC gl3wDisableVertexAttribArray; -PFNGLDISABLEIPROC gl3wDisablei; -PFNGLDISPATCHCOMPUTEPROC gl3wDispatchCompute; -PFNGLDISPATCHCOMPUTEGROUPSIZEARBPROC gl3wDispatchComputeGroupSizeARB; -PFNGLDISPATCHCOMPUTEINDIRECTPROC gl3wDispatchComputeIndirect; -PFNGLDRAWARRAYSPROC gl3wDrawArrays; -PFNGLDRAWARRAYSINDIRECTPROC gl3wDrawArraysIndirect; -PFNGLDRAWARRAYSINSTANCEDPROC gl3wDrawArraysInstanced; -PFNGLDRAWARRAYSINSTANCEDARBPROC gl3wDrawArraysInstancedARB; -PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC gl3wDrawArraysInstancedBaseInstance; -PFNGLDRAWARRAYSINSTANCEDEXTPROC gl3wDrawArraysInstancedEXT; -PFNGLDRAWBUFFERPROC gl3wDrawBuffer; -PFNGLDRAWBUFFERSPROC gl3wDrawBuffers; -PFNGLDRAWCOMMANDSADDRESSNVPROC gl3wDrawCommandsAddressNV; -PFNGLDRAWCOMMANDSNVPROC gl3wDrawCommandsNV; -PFNGLDRAWCOMMANDSSTATESADDRESSNVPROC gl3wDrawCommandsStatesAddressNV; -PFNGLDRAWCOMMANDSSTATESNVPROC gl3wDrawCommandsStatesNV; -PFNGLDRAWELEMENTSPROC gl3wDrawElements; -PFNGLDRAWELEMENTSBASEVERTEXPROC gl3wDrawElementsBaseVertex; -PFNGLDRAWELEMENTSINDIRECTPROC gl3wDrawElementsIndirect; -PFNGLDRAWELEMENTSINSTANCEDPROC gl3wDrawElementsInstanced; -PFNGLDRAWELEMENTSINSTANCEDARBPROC gl3wDrawElementsInstancedARB; -PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC gl3wDrawElementsInstancedBaseInstance; -PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC gl3wDrawElementsInstancedBaseVertex; -PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC gl3wDrawElementsInstancedBaseVertexBaseInstance; -PFNGLDRAWELEMENTSINSTANCEDEXTPROC gl3wDrawElementsInstancedEXT; -PFNGLDRAWRANGEELEMENTSPROC gl3wDrawRangeElements; -PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC gl3wDrawRangeElementsBaseVertex; -PFNGLDRAWTRANSFORMFEEDBACKPROC gl3wDrawTransformFeedback; -PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC gl3wDrawTransformFeedbackInstanced; -PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC gl3wDrawTransformFeedbackStream; -PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC gl3wDrawTransformFeedbackStreamInstanced; -PFNGLDRAWVKIMAGENVPROC gl3wDrawVkImageNV; -PFNGLEDGEFLAGFORMATNVPROC gl3wEdgeFlagFormatNV; -PFNGLENABLEPROC gl3wEnable; -PFNGLENABLECLIENTSTATEINDEXEDEXTPROC gl3wEnableClientStateIndexedEXT; -PFNGLENABLECLIENTSTATEIEXTPROC gl3wEnableClientStateiEXT; -PFNGLENABLEINDEXEDEXTPROC gl3wEnableIndexedEXT; -PFNGLENABLEVERTEXARRAYATTRIBPROC gl3wEnableVertexArrayAttrib; -PFNGLENABLEVERTEXARRAYATTRIBEXTPROC gl3wEnableVertexArrayAttribEXT; -PFNGLENABLEVERTEXARRAYEXTPROC gl3wEnableVertexArrayEXT; -PFNGLENABLEVERTEXATTRIBARRAYPROC gl3wEnableVertexAttribArray; -PFNGLENABLEIPROC gl3wEnablei; -PFNGLENDCONDITIONALRENDERPROC gl3wEndConditionalRender; -PFNGLENDCONDITIONALRENDERNVPROC gl3wEndConditionalRenderNV; -PFNGLENDPERFMONITORAMDPROC gl3wEndPerfMonitorAMD; -PFNGLENDPERFQUERYINTELPROC gl3wEndPerfQueryINTEL; -PFNGLENDQUERYPROC gl3wEndQuery; -PFNGLENDQUERYINDEXEDPROC gl3wEndQueryIndexed; -PFNGLENDTRANSFORMFEEDBACKPROC gl3wEndTransformFeedback; -PFNGLEVALUATEDEPTHVALUESARBPROC gl3wEvaluateDepthValuesARB; -PFNGLFENCESYNCPROC gl3wFenceSync; -PFNGLFINISHPROC gl3wFinish; -PFNGLFLUSHPROC gl3wFlush; -PFNGLFLUSHMAPPEDBUFFERRANGEPROC gl3wFlushMappedBufferRange; -PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEPROC gl3wFlushMappedNamedBufferRange; -PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEEXTPROC gl3wFlushMappedNamedBufferRangeEXT; -PFNGLFOGCOORDFORMATNVPROC gl3wFogCoordFormatNV; -PFNGLFRAGMENTCOVERAGECOLORNVPROC gl3wFragmentCoverageColorNV; -PFNGLFRAMEBUFFERDRAWBUFFEREXTPROC gl3wFramebufferDrawBufferEXT; -PFNGLFRAMEBUFFERDRAWBUFFERSEXTPROC gl3wFramebufferDrawBuffersEXT; -PFNGLFRAMEBUFFERPARAMETERIPROC gl3wFramebufferParameteri; -PFNGLFRAMEBUFFERREADBUFFEREXTPROC gl3wFramebufferReadBufferEXT; -PFNGLFRAMEBUFFERRENDERBUFFERPROC gl3wFramebufferRenderbuffer; -PFNGLFRAMEBUFFERSAMPLELOCATIONSFVARBPROC gl3wFramebufferSampleLocationsfvARB; -PFNGLFRAMEBUFFERSAMPLELOCATIONSFVNVPROC gl3wFramebufferSampleLocationsfvNV; -PFNGLFRAMEBUFFERTEXTUREPROC gl3wFramebufferTexture; -PFNGLFRAMEBUFFERTEXTURE1DPROC gl3wFramebufferTexture1D; -PFNGLFRAMEBUFFERTEXTURE2DPROC gl3wFramebufferTexture2D; -PFNGLFRAMEBUFFERTEXTURE3DPROC gl3wFramebufferTexture3D; -PFNGLFRAMEBUFFERTEXTUREARBPROC gl3wFramebufferTextureARB; -PFNGLFRAMEBUFFERTEXTUREFACEARBPROC gl3wFramebufferTextureFaceARB; -PFNGLFRAMEBUFFERTEXTURELAYERPROC gl3wFramebufferTextureLayer; -PFNGLFRAMEBUFFERTEXTURELAYERARBPROC gl3wFramebufferTextureLayerARB; -PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC gl3wFramebufferTextureMultiviewOVR; -PFNGLFRONTFACEPROC gl3wFrontFace; -PFNGLGENBUFFERSPROC gl3wGenBuffers; -PFNGLGENFRAMEBUFFERSPROC gl3wGenFramebuffers; -PFNGLGENPATHSNVPROC gl3wGenPathsNV; -PFNGLGENPERFMONITORSAMDPROC gl3wGenPerfMonitorsAMD; -PFNGLGENPROGRAMPIPELINESPROC gl3wGenProgramPipelines; -PFNGLGENQUERIESPROC gl3wGenQueries; -PFNGLGENRENDERBUFFERSPROC gl3wGenRenderbuffers; -PFNGLGENSAMPLERSPROC gl3wGenSamplers; -PFNGLGENTEXTURESPROC gl3wGenTextures; -PFNGLGENTRANSFORMFEEDBACKSPROC gl3wGenTransformFeedbacks; -PFNGLGENVERTEXARRAYSPROC gl3wGenVertexArrays; -PFNGLGENERATEMIPMAPPROC gl3wGenerateMipmap; -PFNGLGENERATEMULTITEXMIPMAPEXTPROC gl3wGenerateMultiTexMipmapEXT; -PFNGLGENERATETEXTUREMIPMAPPROC gl3wGenerateTextureMipmap; -PFNGLGENERATETEXTUREMIPMAPEXTPROC gl3wGenerateTextureMipmapEXT; -PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC gl3wGetActiveAtomicCounterBufferiv; -PFNGLGETACTIVEATTRIBPROC gl3wGetActiveAttrib; -PFNGLGETACTIVESUBROUTINENAMEPROC gl3wGetActiveSubroutineName; -PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC gl3wGetActiveSubroutineUniformName; -PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC gl3wGetActiveSubroutineUniformiv; -PFNGLGETACTIVEUNIFORMPROC gl3wGetActiveUniform; -PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC gl3wGetActiveUniformBlockName; -PFNGLGETACTIVEUNIFORMBLOCKIVPROC gl3wGetActiveUniformBlockiv; -PFNGLGETACTIVEUNIFORMNAMEPROC gl3wGetActiveUniformName; -PFNGLGETACTIVEUNIFORMSIVPROC gl3wGetActiveUniformsiv; -PFNGLGETATTACHEDSHADERSPROC gl3wGetAttachedShaders; -PFNGLGETATTRIBLOCATIONPROC gl3wGetAttribLocation; -PFNGLGETBOOLEANINDEXEDVEXTPROC gl3wGetBooleanIndexedvEXT; -PFNGLGETBOOLEANI_VPROC gl3wGetBooleani_v; -PFNGLGETBOOLEANVPROC gl3wGetBooleanv; -PFNGLGETBUFFERPARAMETERI64VPROC gl3wGetBufferParameteri64v; -PFNGLGETBUFFERPARAMETERIVPROC gl3wGetBufferParameteriv; -PFNGLGETBUFFERPARAMETERUI64VNVPROC gl3wGetBufferParameterui64vNV; -PFNGLGETBUFFERPOINTERVPROC gl3wGetBufferPointerv; -PFNGLGETBUFFERSUBDATAPROC gl3wGetBufferSubData; -PFNGLGETCOMMANDHEADERNVPROC gl3wGetCommandHeaderNV; -PFNGLGETCOMPRESSEDMULTITEXIMAGEEXTPROC gl3wGetCompressedMultiTexImageEXT; -PFNGLGETCOMPRESSEDTEXIMAGEPROC gl3wGetCompressedTexImage; -PFNGLGETCOMPRESSEDTEXTUREIMAGEPROC gl3wGetCompressedTextureImage; -PFNGLGETCOMPRESSEDTEXTUREIMAGEEXTPROC gl3wGetCompressedTextureImageEXT; -PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC gl3wGetCompressedTextureSubImage; -PFNGLGETCOVERAGEMODULATIONTABLENVPROC gl3wGetCoverageModulationTableNV; -PFNGLGETDEBUGMESSAGELOGPROC gl3wGetDebugMessageLog; -PFNGLGETDEBUGMESSAGELOGARBPROC gl3wGetDebugMessageLogARB; -PFNGLGETDOUBLEINDEXEDVEXTPROC gl3wGetDoubleIndexedvEXT; -PFNGLGETDOUBLEI_VPROC gl3wGetDoublei_v; -PFNGLGETDOUBLEI_VEXTPROC gl3wGetDoublei_vEXT; -PFNGLGETDOUBLEVPROC gl3wGetDoublev; -PFNGLGETERRORPROC gl3wGetError; -PFNGLGETFIRSTPERFQUERYIDINTELPROC gl3wGetFirstPerfQueryIdINTEL; -PFNGLGETFLOATINDEXEDVEXTPROC gl3wGetFloatIndexedvEXT; -PFNGLGETFLOATI_VPROC gl3wGetFloati_v; -PFNGLGETFLOATI_VEXTPROC gl3wGetFloati_vEXT; -PFNGLGETFLOATVPROC gl3wGetFloatv; -PFNGLGETFRAGDATAINDEXPROC gl3wGetFragDataIndex; -PFNGLGETFRAGDATALOCATIONPROC gl3wGetFragDataLocation; -PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC gl3wGetFramebufferAttachmentParameteriv; -PFNGLGETFRAMEBUFFERPARAMETERIVPROC gl3wGetFramebufferParameteriv; -PFNGLGETFRAMEBUFFERPARAMETERIVEXTPROC gl3wGetFramebufferParameterivEXT; -PFNGLGETGRAPHICSRESETSTATUSPROC gl3wGetGraphicsResetStatus; -PFNGLGETGRAPHICSRESETSTATUSARBPROC gl3wGetGraphicsResetStatusARB; -PFNGLGETIMAGEHANDLEARBPROC gl3wGetImageHandleARB; -PFNGLGETIMAGEHANDLENVPROC gl3wGetImageHandleNV; -PFNGLGETINTEGER64I_VPROC gl3wGetInteger64i_v; -PFNGLGETINTEGER64VPROC gl3wGetInteger64v; -PFNGLGETINTEGERINDEXEDVEXTPROC gl3wGetIntegerIndexedvEXT; -PFNGLGETINTEGERI_VPROC gl3wGetIntegeri_v; -PFNGLGETINTEGERUI64I_VNVPROC gl3wGetIntegerui64i_vNV; -PFNGLGETINTEGERUI64VNVPROC gl3wGetIntegerui64vNV; -PFNGLGETINTEGERVPROC gl3wGetIntegerv; -PFNGLGETINTERNALFORMATSAMPLEIVNVPROC gl3wGetInternalformatSampleivNV; -PFNGLGETINTERNALFORMATI64VPROC gl3wGetInternalformati64v; -PFNGLGETINTERNALFORMATIVPROC gl3wGetInternalformativ; -PFNGLGETMULTITEXENVFVEXTPROC gl3wGetMultiTexEnvfvEXT; -PFNGLGETMULTITEXENVIVEXTPROC gl3wGetMultiTexEnvivEXT; -PFNGLGETMULTITEXGENDVEXTPROC gl3wGetMultiTexGendvEXT; -PFNGLGETMULTITEXGENFVEXTPROC gl3wGetMultiTexGenfvEXT; -PFNGLGETMULTITEXGENIVEXTPROC gl3wGetMultiTexGenivEXT; -PFNGLGETMULTITEXIMAGEEXTPROC gl3wGetMultiTexImageEXT; -PFNGLGETMULTITEXLEVELPARAMETERFVEXTPROC gl3wGetMultiTexLevelParameterfvEXT; -PFNGLGETMULTITEXLEVELPARAMETERIVEXTPROC gl3wGetMultiTexLevelParameterivEXT; -PFNGLGETMULTITEXPARAMETERIIVEXTPROC gl3wGetMultiTexParameterIivEXT; -PFNGLGETMULTITEXPARAMETERIUIVEXTPROC gl3wGetMultiTexParameterIuivEXT; -PFNGLGETMULTITEXPARAMETERFVEXTPROC gl3wGetMultiTexParameterfvEXT; -PFNGLGETMULTITEXPARAMETERIVEXTPROC gl3wGetMultiTexParameterivEXT; -PFNGLGETMULTISAMPLEFVPROC gl3wGetMultisamplefv; -PFNGLGETNAMEDBUFFERPARAMETERI64VPROC gl3wGetNamedBufferParameteri64v; -PFNGLGETNAMEDBUFFERPARAMETERIVPROC gl3wGetNamedBufferParameteriv; -PFNGLGETNAMEDBUFFERPARAMETERIVEXTPROC gl3wGetNamedBufferParameterivEXT; -PFNGLGETNAMEDBUFFERPARAMETERUI64VNVPROC gl3wGetNamedBufferParameterui64vNV; -PFNGLGETNAMEDBUFFERPOINTERVPROC gl3wGetNamedBufferPointerv; -PFNGLGETNAMEDBUFFERPOINTERVEXTPROC gl3wGetNamedBufferPointervEXT; -PFNGLGETNAMEDBUFFERSUBDATAPROC gl3wGetNamedBufferSubData; -PFNGLGETNAMEDBUFFERSUBDATAEXTPROC gl3wGetNamedBufferSubDataEXT; -PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC gl3wGetNamedFramebufferAttachmentParameteriv; -PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC gl3wGetNamedFramebufferAttachmentParameterivEXT; -PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVPROC gl3wGetNamedFramebufferParameteriv; -PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVEXTPROC gl3wGetNamedFramebufferParameterivEXT; -PFNGLGETNAMEDPROGRAMLOCALPARAMETERIIVEXTPROC gl3wGetNamedProgramLocalParameterIivEXT; -PFNGLGETNAMEDPROGRAMLOCALPARAMETERIUIVEXTPROC gl3wGetNamedProgramLocalParameterIuivEXT; -PFNGLGETNAMEDPROGRAMLOCALPARAMETERDVEXTPROC gl3wGetNamedProgramLocalParameterdvEXT; -PFNGLGETNAMEDPROGRAMLOCALPARAMETERFVEXTPROC gl3wGetNamedProgramLocalParameterfvEXT; -PFNGLGETNAMEDPROGRAMSTRINGEXTPROC gl3wGetNamedProgramStringEXT; -PFNGLGETNAMEDPROGRAMIVEXTPROC gl3wGetNamedProgramivEXT; -PFNGLGETNAMEDRENDERBUFFERPARAMETERIVPROC gl3wGetNamedRenderbufferParameteriv; -PFNGLGETNAMEDRENDERBUFFERPARAMETERIVEXTPROC gl3wGetNamedRenderbufferParameterivEXT; -PFNGLGETNAMEDSTRINGARBPROC gl3wGetNamedStringARB; -PFNGLGETNAMEDSTRINGIVARBPROC gl3wGetNamedStringivARB; -PFNGLGETNEXTPERFQUERYIDINTELPROC gl3wGetNextPerfQueryIdINTEL; -PFNGLGETOBJECTLABELPROC gl3wGetObjectLabel; -PFNGLGETOBJECTLABELEXTPROC gl3wGetObjectLabelEXT; -PFNGLGETOBJECTPTRLABELPROC gl3wGetObjectPtrLabel; -PFNGLGETPATHCOMMANDSNVPROC gl3wGetPathCommandsNV; -PFNGLGETPATHCOORDSNVPROC gl3wGetPathCoordsNV; -PFNGLGETPATHDASHARRAYNVPROC gl3wGetPathDashArrayNV; -PFNGLGETPATHLENGTHNVPROC gl3wGetPathLengthNV; -PFNGLGETPATHMETRICRANGENVPROC gl3wGetPathMetricRangeNV; -PFNGLGETPATHMETRICSNVPROC gl3wGetPathMetricsNV; -PFNGLGETPATHPARAMETERFVNVPROC gl3wGetPathParameterfvNV; -PFNGLGETPATHPARAMETERIVNVPROC gl3wGetPathParameterivNV; -PFNGLGETPATHSPACINGNVPROC gl3wGetPathSpacingNV; -PFNGLGETPERFCOUNTERINFOINTELPROC gl3wGetPerfCounterInfoINTEL; -PFNGLGETPERFMONITORCOUNTERDATAAMDPROC gl3wGetPerfMonitorCounterDataAMD; -PFNGLGETPERFMONITORCOUNTERINFOAMDPROC gl3wGetPerfMonitorCounterInfoAMD; -PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC gl3wGetPerfMonitorCounterStringAMD; -PFNGLGETPERFMONITORCOUNTERSAMDPROC gl3wGetPerfMonitorCountersAMD; -PFNGLGETPERFMONITORGROUPSTRINGAMDPROC gl3wGetPerfMonitorGroupStringAMD; -PFNGLGETPERFMONITORGROUPSAMDPROC gl3wGetPerfMonitorGroupsAMD; -PFNGLGETPERFQUERYDATAINTELPROC gl3wGetPerfQueryDataINTEL; -PFNGLGETPERFQUERYIDBYNAMEINTELPROC gl3wGetPerfQueryIdByNameINTEL; -PFNGLGETPERFQUERYINFOINTELPROC gl3wGetPerfQueryInfoINTEL; -PFNGLGETPOINTERINDEXEDVEXTPROC gl3wGetPointerIndexedvEXT; -PFNGLGETPOINTERI_VEXTPROC gl3wGetPointeri_vEXT; -PFNGLGETPOINTERVPROC gl3wGetPointerv; -PFNGLGETPROGRAMBINARYPROC gl3wGetProgramBinary; -PFNGLGETPROGRAMINFOLOGPROC gl3wGetProgramInfoLog; -PFNGLGETPROGRAMINTERFACEIVPROC gl3wGetProgramInterfaceiv; -PFNGLGETPROGRAMPIPELINEINFOLOGPROC gl3wGetProgramPipelineInfoLog; -PFNGLGETPROGRAMPIPELINEIVPROC gl3wGetProgramPipelineiv; -PFNGLGETPROGRAMRESOURCEINDEXPROC gl3wGetProgramResourceIndex; -PFNGLGETPROGRAMRESOURCELOCATIONPROC gl3wGetProgramResourceLocation; -PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC gl3wGetProgramResourceLocationIndex; -PFNGLGETPROGRAMRESOURCENAMEPROC gl3wGetProgramResourceName; -PFNGLGETPROGRAMRESOURCEFVNVPROC gl3wGetProgramResourcefvNV; -PFNGLGETPROGRAMRESOURCEIVPROC gl3wGetProgramResourceiv; -PFNGLGETPROGRAMSTAGEIVPROC gl3wGetProgramStageiv; -PFNGLGETPROGRAMIVPROC gl3wGetProgramiv; -PFNGLGETQUERYBUFFEROBJECTI64VPROC gl3wGetQueryBufferObjecti64v; -PFNGLGETQUERYBUFFEROBJECTIVPROC gl3wGetQueryBufferObjectiv; -PFNGLGETQUERYBUFFEROBJECTUI64VPROC gl3wGetQueryBufferObjectui64v; -PFNGLGETQUERYBUFFEROBJECTUIVPROC gl3wGetQueryBufferObjectuiv; -PFNGLGETQUERYINDEXEDIVPROC gl3wGetQueryIndexediv; -PFNGLGETQUERYOBJECTI64VPROC gl3wGetQueryObjecti64v; -PFNGLGETQUERYOBJECTIVPROC gl3wGetQueryObjectiv; -PFNGLGETQUERYOBJECTUI64VPROC gl3wGetQueryObjectui64v; -PFNGLGETQUERYOBJECTUIVPROC gl3wGetQueryObjectuiv; -PFNGLGETQUERYIVPROC gl3wGetQueryiv; -PFNGLGETRENDERBUFFERPARAMETERIVPROC gl3wGetRenderbufferParameteriv; -PFNGLGETSAMPLERPARAMETERIIVPROC gl3wGetSamplerParameterIiv; -PFNGLGETSAMPLERPARAMETERIUIVPROC gl3wGetSamplerParameterIuiv; -PFNGLGETSAMPLERPARAMETERFVPROC gl3wGetSamplerParameterfv; -PFNGLGETSAMPLERPARAMETERIVPROC gl3wGetSamplerParameteriv; -PFNGLGETSHADERINFOLOGPROC gl3wGetShaderInfoLog; -PFNGLGETSHADERPRECISIONFORMATPROC gl3wGetShaderPrecisionFormat; -PFNGLGETSHADERSOURCEPROC gl3wGetShaderSource; -PFNGLGETSHADERIVPROC gl3wGetShaderiv; -PFNGLGETSTAGEINDEXNVPROC gl3wGetStageIndexNV; -PFNGLGETSTRINGPROC gl3wGetString; -PFNGLGETSTRINGIPROC gl3wGetStringi; -PFNGLGETSUBROUTINEINDEXPROC gl3wGetSubroutineIndex; -PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC gl3wGetSubroutineUniformLocation; -PFNGLGETSYNCIVPROC gl3wGetSynciv; -PFNGLGETTEXIMAGEPROC gl3wGetTexImage; -PFNGLGETTEXLEVELPARAMETERFVPROC gl3wGetTexLevelParameterfv; -PFNGLGETTEXLEVELPARAMETERIVPROC gl3wGetTexLevelParameteriv; -PFNGLGETTEXPARAMETERIIVPROC gl3wGetTexParameterIiv; -PFNGLGETTEXPARAMETERIUIVPROC gl3wGetTexParameterIuiv; -PFNGLGETTEXPARAMETERFVPROC gl3wGetTexParameterfv; -PFNGLGETTEXPARAMETERIVPROC gl3wGetTexParameteriv; -PFNGLGETTEXTUREHANDLEARBPROC gl3wGetTextureHandleARB; -PFNGLGETTEXTUREHANDLENVPROC gl3wGetTextureHandleNV; -PFNGLGETTEXTUREIMAGEPROC gl3wGetTextureImage; -PFNGLGETTEXTUREIMAGEEXTPROC gl3wGetTextureImageEXT; -PFNGLGETTEXTURELEVELPARAMETERFVPROC gl3wGetTextureLevelParameterfv; -PFNGLGETTEXTURELEVELPARAMETERFVEXTPROC gl3wGetTextureLevelParameterfvEXT; -PFNGLGETTEXTURELEVELPARAMETERIVPROC gl3wGetTextureLevelParameteriv; -PFNGLGETTEXTURELEVELPARAMETERIVEXTPROC gl3wGetTextureLevelParameterivEXT; -PFNGLGETTEXTUREPARAMETERIIVPROC gl3wGetTextureParameterIiv; -PFNGLGETTEXTUREPARAMETERIIVEXTPROC gl3wGetTextureParameterIivEXT; -PFNGLGETTEXTUREPARAMETERIUIVPROC gl3wGetTextureParameterIuiv; -PFNGLGETTEXTUREPARAMETERIUIVEXTPROC gl3wGetTextureParameterIuivEXT; -PFNGLGETTEXTUREPARAMETERFVPROC gl3wGetTextureParameterfv; -PFNGLGETTEXTUREPARAMETERFVEXTPROC gl3wGetTextureParameterfvEXT; -PFNGLGETTEXTUREPARAMETERIVPROC gl3wGetTextureParameteriv; -PFNGLGETTEXTUREPARAMETERIVEXTPROC gl3wGetTextureParameterivEXT; -PFNGLGETTEXTURESAMPLERHANDLEARBPROC gl3wGetTextureSamplerHandleARB; -PFNGLGETTEXTURESAMPLERHANDLENVPROC gl3wGetTextureSamplerHandleNV; -PFNGLGETTEXTURESUBIMAGEPROC gl3wGetTextureSubImage; -PFNGLGETTRANSFORMFEEDBACKVARYINGPROC gl3wGetTransformFeedbackVarying; -PFNGLGETTRANSFORMFEEDBACKI64_VPROC gl3wGetTransformFeedbacki64_v; -PFNGLGETTRANSFORMFEEDBACKI_VPROC gl3wGetTransformFeedbacki_v; -PFNGLGETTRANSFORMFEEDBACKIVPROC gl3wGetTransformFeedbackiv; -PFNGLGETUNIFORMBLOCKINDEXPROC gl3wGetUniformBlockIndex; -PFNGLGETUNIFORMINDICESPROC gl3wGetUniformIndices; -PFNGLGETUNIFORMLOCATIONPROC gl3wGetUniformLocation; -PFNGLGETUNIFORMSUBROUTINEUIVPROC gl3wGetUniformSubroutineuiv; -PFNGLGETUNIFORMDVPROC gl3wGetUniformdv; -PFNGLGETUNIFORMFVPROC gl3wGetUniformfv; -PFNGLGETUNIFORMI64VARBPROC gl3wGetUniformi64vARB; -PFNGLGETUNIFORMI64VNVPROC gl3wGetUniformi64vNV; -PFNGLGETUNIFORMIVPROC gl3wGetUniformiv; -PFNGLGETUNIFORMUI64VARBPROC gl3wGetUniformui64vARB; -PFNGLGETUNIFORMUI64VNVPROC gl3wGetUniformui64vNV; -PFNGLGETUNIFORMUIVPROC gl3wGetUniformuiv; -PFNGLGETVERTEXARRAYINDEXED64IVPROC gl3wGetVertexArrayIndexed64iv; -PFNGLGETVERTEXARRAYINDEXEDIVPROC gl3wGetVertexArrayIndexediv; -PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC gl3wGetVertexArrayIntegeri_vEXT; -PFNGLGETVERTEXARRAYINTEGERVEXTPROC gl3wGetVertexArrayIntegervEXT; -PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC gl3wGetVertexArrayPointeri_vEXT; -PFNGLGETVERTEXARRAYPOINTERVEXTPROC gl3wGetVertexArrayPointervEXT; -PFNGLGETVERTEXARRAYIVPROC gl3wGetVertexArrayiv; -PFNGLGETVERTEXATTRIBIIVPROC gl3wGetVertexAttribIiv; -PFNGLGETVERTEXATTRIBIUIVPROC gl3wGetVertexAttribIuiv; -PFNGLGETVERTEXATTRIBLDVPROC gl3wGetVertexAttribLdv; -PFNGLGETVERTEXATTRIBLI64VNVPROC gl3wGetVertexAttribLi64vNV; -PFNGLGETVERTEXATTRIBLUI64VARBPROC gl3wGetVertexAttribLui64vARB; -PFNGLGETVERTEXATTRIBLUI64VNVPROC gl3wGetVertexAttribLui64vNV; -PFNGLGETVERTEXATTRIBPOINTERVPROC gl3wGetVertexAttribPointerv; -PFNGLGETVERTEXATTRIBDVPROC gl3wGetVertexAttribdv; -PFNGLGETVERTEXATTRIBFVPROC gl3wGetVertexAttribfv; -PFNGLGETVERTEXATTRIBIVPROC gl3wGetVertexAttribiv; -PFNGLGETVKPROCADDRNVPROC gl3wGetVkProcAddrNV; -PFNGLGETNCOMPRESSEDTEXIMAGEPROC gl3wGetnCompressedTexImage; -PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC gl3wGetnCompressedTexImageARB; -PFNGLGETNTEXIMAGEPROC gl3wGetnTexImage; -PFNGLGETNTEXIMAGEARBPROC gl3wGetnTexImageARB; -PFNGLGETNUNIFORMDVPROC gl3wGetnUniformdv; -PFNGLGETNUNIFORMDVARBPROC gl3wGetnUniformdvARB; -PFNGLGETNUNIFORMFVPROC gl3wGetnUniformfv; -PFNGLGETNUNIFORMFVARBPROC gl3wGetnUniformfvARB; -PFNGLGETNUNIFORMI64VARBPROC gl3wGetnUniformi64vARB; -PFNGLGETNUNIFORMIVPROC gl3wGetnUniformiv; -PFNGLGETNUNIFORMIVARBPROC gl3wGetnUniformivARB; -PFNGLGETNUNIFORMUI64VARBPROC gl3wGetnUniformui64vARB; -PFNGLGETNUNIFORMUIVPROC gl3wGetnUniformuiv; -PFNGLGETNUNIFORMUIVARBPROC gl3wGetnUniformuivARB; -PFNGLHINTPROC gl3wHint; -PFNGLINDEXFORMATNVPROC gl3wIndexFormatNV; -PFNGLINSERTEVENTMARKEREXTPROC gl3wInsertEventMarkerEXT; -PFNGLINTERPOLATEPATHSNVPROC gl3wInterpolatePathsNV; -PFNGLINVALIDATEBUFFERDATAPROC gl3wInvalidateBufferData; -PFNGLINVALIDATEBUFFERSUBDATAPROC gl3wInvalidateBufferSubData; -PFNGLINVALIDATEFRAMEBUFFERPROC gl3wInvalidateFramebuffer; -PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC gl3wInvalidateNamedFramebufferData; -PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC gl3wInvalidateNamedFramebufferSubData; -PFNGLINVALIDATESUBFRAMEBUFFERPROC gl3wInvalidateSubFramebuffer; -PFNGLINVALIDATETEXIMAGEPROC gl3wInvalidateTexImage; -PFNGLINVALIDATETEXSUBIMAGEPROC gl3wInvalidateTexSubImage; -PFNGLISBUFFERPROC gl3wIsBuffer; -PFNGLISBUFFERRESIDENTNVPROC gl3wIsBufferResidentNV; -PFNGLISCOMMANDLISTNVPROC gl3wIsCommandListNV; -PFNGLISENABLEDPROC gl3wIsEnabled; -PFNGLISENABLEDINDEXEDEXTPROC gl3wIsEnabledIndexedEXT; -PFNGLISENABLEDIPROC gl3wIsEnabledi; -PFNGLISFRAMEBUFFERPROC gl3wIsFramebuffer; -PFNGLISIMAGEHANDLERESIDENTARBPROC gl3wIsImageHandleResidentARB; -PFNGLISIMAGEHANDLERESIDENTNVPROC gl3wIsImageHandleResidentNV; -PFNGLISNAMEDBUFFERRESIDENTNVPROC gl3wIsNamedBufferResidentNV; -PFNGLISNAMEDSTRINGARBPROC gl3wIsNamedStringARB; -PFNGLISPATHNVPROC gl3wIsPathNV; -PFNGLISPOINTINFILLPATHNVPROC gl3wIsPointInFillPathNV; -PFNGLISPOINTINSTROKEPATHNVPROC gl3wIsPointInStrokePathNV; -PFNGLISPROGRAMPROC gl3wIsProgram; -PFNGLISPROGRAMPIPELINEPROC gl3wIsProgramPipeline; -PFNGLISQUERYPROC gl3wIsQuery; -PFNGLISRENDERBUFFERPROC gl3wIsRenderbuffer; -PFNGLISSAMPLERPROC gl3wIsSampler; -PFNGLISSHADERPROC gl3wIsShader; -PFNGLISSTATENVPROC gl3wIsStateNV; -PFNGLISSYNCPROC gl3wIsSync; -PFNGLISTEXTUREPROC gl3wIsTexture; -PFNGLISTEXTUREHANDLERESIDENTARBPROC gl3wIsTextureHandleResidentARB; -PFNGLISTEXTUREHANDLERESIDENTNVPROC gl3wIsTextureHandleResidentNV; -PFNGLISTRANSFORMFEEDBACKPROC gl3wIsTransformFeedback; -PFNGLISVERTEXARRAYPROC gl3wIsVertexArray; -PFNGLLABELOBJECTEXTPROC gl3wLabelObjectEXT; -PFNGLLINEWIDTHPROC gl3wLineWidth; -PFNGLLINKPROGRAMPROC gl3wLinkProgram; -PFNGLLISTDRAWCOMMANDSSTATESCLIENTNVPROC gl3wListDrawCommandsStatesClientNV; -PFNGLLOGICOPPROC gl3wLogicOp; -PFNGLMAKEBUFFERNONRESIDENTNVPROC gl3wMakeBufferNonResidentNV; -PFNGLMAKEBUFFERRESIDENTNVPROC gl3wMakeBufferResidentNV; -PFNGLMAKEIMAGEHANDLENONRESIDENTARBPROC gl3wMakeImageHandleNonResidentARB; -PFNGLMAKEIMAGEHANDLENONRESIDENTNVPROC gl3wMakeImageHandleNonResidentNV; -PFNGLMAKEIMAGEHANDLERESIDENTARBPROC gl3wMakeImageHandleResidentARB; -PFNGLMAKEIMAGEHANDLERESIDENTNVPROC gl3wMakeImageHandleResidentNV; -PFNGLMAKENAMEDBUFFERNONRESIDENTNVPROC gl3wMakeNamedBufferNonResidentNV; -PFNGLMAKENAMEDBUFFERRESIDENTNVPROC gl3wMakeNamedBufferResidentNV; -PFNGLMAKETEXTUREHANDLENONRESIDENTARBPROC gl3wMakeTextureHandleNonResidentARB; -PFNGLMAKETEXTUREHANDLENONRESIDENTNVPROC gl3wMakeTextureHandleNonResidentNV; -PFNGLMAKETEXTUREHANDLERESIDENTARBPROC gl3wMakeTextureHandleResidentARB; -PFNGLMAKETEXTUREHANDLERESIDENTNVPROC gl3wMakeTextureHandleResidentNV; -PFNGLMAPBUFFERPROC gl3wMapBuffer; -PFNGLMAPBUFFERRANGEPROC gl3wMapBufferRange; -PFNGLMAPNAMEDBUFFERPROC gl3wMapNamedBuffer; -PFNGLMAPNAMEDBUFFEREXTPROC gl3wMapNamedBufferEXT; -PFNGLMAPNAMEDBUFFERRANGEPROC gl3wMapNamedBufferRange; -PFNGLMAPNAMEDBUFFERRANGEEXTPROC gl3wMapNamedBufferRangeEXT; -PFNGLMATRIXFRUSTUMEXTPROC gl3wMatrixFrustumEXT; -PFNGLMATRIXLOAD3X2FNVPROC gl3wMatrixLoad3x2fNV; -PFNGLMATRIXLOAD3X3FNVPROC gl3wMatrixLoad3x3fNV; -PFNGLMATRIXLOADIDENTITYEXTPROC gl3wMatrixLoadIdentityEXT; -PFNGLMATRIXLOADTRANSPOSE3X3FNVPROC gl3wMatrixLoadTranspose3x3fNV; -PFNGLMATRIXLOADTRANSPOSEDEXTPROC gl3wMatrixLoadTransposedEXT; -PFNGLMATRIXLOADTRANSPOSEFEXTPROC gl3wMatrixLoadTransposefEXT; -PFNGLMATRIXLOADDEXTPROC gl3wMatrixLoaddEXT; -PFNGLMATRIXLOADFEXTPROC gl3wMatrixLoadfEXT; -PFNGLMATRIXMULT3X2FNVPROC gl3wMatrixMult3x2fNV; -PFNGLMATRIXMULT3X3FNVPROC gl3wMatrixMult3x3fNV; -PFNGLMATRIXMULTTRANSPOSE3X3FNVPROC gl3wMatrixMultTranspose3x3fNV; -PFNGLMATRIXMULTTRANSPOSEDEXTPROC gl3wMatrixMultTransposedEXT; -PFNGLMATRIXMULTTRANSPOSEFEXTPROC gl3wMatrixMultTransposefEXT; -PFNGLMATRIXMULTDEXTPROC gl3wMatrixMultdEXT; -PFNGLMATRIXMULTFEXTPROC gl3wMatrixMultfEXT; -PFNGLMATRIXORTHOEXTPROC gl3wMatrixOrthoEXT; -PFNGLMATRIXPOPEXTPROC gl3wMatrixPopEXT; -PFNGLMATRIXPUSHEXTPROC gl3wMatrixPushEXT; -PFNGLMATRIXROTATEDEXTPROC gl3wMatrixRotatedEXT; -PFNGLMATRIXROTATEFEXTPROC gl3wMatrixRotatefEXT; -PFNGLMATRIXSCALEDEXTPROC gl3wMatrixScaledEXT; -PFNGLMATRIXSCALEFEXTPROC gl3wMatrixScalefEXT; -PFNGLMATRIXTRANSLATEDEXTPROC gl3wMatrixTranslatedEXT; -PFNGLMATRIXTRANSLATEFEXTPROC gl3wMatrixTranslatefEXT; -PFNGLMAXSHADERCOMPILERTHREADSARBPROC gl3wMaxShaderCompilerThreadsARB; -PFNGLMEMORYBARRIERPROC gl3wMemoryBarrier; -PFNGLMEMORYBARRIERBYREGIONPROC gl3wMemoryBarrierByRegion; -PFNGLMINSAMPLESHADINGPROC gl3wMinSampleShading; -PFNGLMINSAMPLESHADINGARBPROC gl3wMinSampleShadingARB; -PFNGLMULTIDRAWARRAYSPROC gl3wMultiDrawArrays; -PFNGLMULTIDRAWARRAYSINDIRECTPROC gl3wMultiDrawArraysIndirect; -PFNGLMULTIDRAWARRAYSINDIRECTBINDLESSCOUNTNVPROC gl3wMultiDrawArraysIndirectBindlessCountNV; -PFNGLMULTIDRAWARRAYSINDIRECTBINDLESSNVPROC gl3wMultiDrawArraysIndirectBindlessNV; -PFNGLMULTIDRAWARRAYSINDIRECTCOUNTPROC gl3wMultiDrawArraysIndirectCount; -PFNGLMULTIDRAWARRAYSINDIRECTCOUNTARBPROC gl3wMultiDrawArraysIndirectCountARB; -PFNGLMULTIDRAWELEMENTSPROC gl3wMultiDrawElements; -PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC gl3wMultiDrawElementsBaseVertex; -PFNGLMULTIDRAWELEMENTSINDIRECTPROC gl3wMultiDrawElementsIndirect; -PFNGLMULTIDRAWELEMENTSINDIRECTBINDLESSCOUNTNVPROC gl3wMultiDrawElementsIndirectBindlessCountNV; -PFNGLMULTIDRAWELEMENTSINDIRECTBINDLESSNVPROC gl3wMultiDrawElementsIndirectBindlessNV; -PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTPROC gl3wMultiDrawElementsIndirectCount; -PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTARBPROC gl3wMultiDrawElementsIndirectCountARB; -PFNGLMULTITEXBUFFEREXTPROC gl3wMultiTexBufferEXT; -PFNGLMULTITEXCOORDPOINTEREXTPROC gl3wMultiTexCoordPointerEXT; -PFNGLMULTITEXENVFEXTPROC gl3wMultiTexEnvfEXT; -PFNGLMULTITEXENVFVEXTPROC gl3wMultiTexEnvfvEXT; -PFNGLMULTITEXENVIEXTPROC gl3wMultiTexEnviEXT; -PFNGLMULTITEXENVIVEXTPROC gl3wMultiTexEnvivEXT; -PFNGLMULTITEXGENDEXTPROC gl3wMultiTexGendEXT; -PFNGLMULTITEXGENDVEXTPROC gl3wMultiTexGendvEXT; -PFNGLMULTITEXGENFEXTPROC gl3wMultiTexGenfEXT; -PFNGLMULTITEXGENFVEXTPROC gl3wMultiTexGenfvEXT; -PFNGLMULTITEXGENIEXTPROC gl3wMultiTexGeniEXT; -PFNGLMULTITEXGENIVEXTPROC gl3wMultiTexGenivEXT; -PFNGLMULTITEXIMAGE1DEXTPROC gl3wMultiTexImage1DEXT; -PFNGLMULTITEXIMAGE2DEXTPROC gl3wMultiTexImage2DEXT; -PFNGLMULTITEXIMAGE3DEXTPROC gl3wMultiTexImage3DEXT; -PFNGLMULTITEXPARAMETERIIVEXTPROC gl3wMultiTexParameterIivEXT; -PFNGLMULTITEXPARAMETERIUIVEXTPROC gl3wMultiTexParameterIuivEXT; -PFNGLMULTITEXPARAMETERFEXTPROC gl3wMultiTexParameterfEXT; -PFNGLMULTITEXPARAMETERFVEXTPROC gl3wMultiTexParameterfvEXT; -PFNGLMULTITEXPARAMETERIEXTPROC gl3wMultiTexParameteriEXT; -PFNGLMULTITEXPARAMETERIVEXTPROC gl3wMultiTexParameterivEXT; -PFNGLMULTITEXRENDERBUFFEREXTPROC gl3wMultiTexRenderbufferEXT; -PFNGLMULTITEXSUBIMAGE1DEXTPROC gl3wMultiTexSubImage1DEXT; -PFNGLMULTITEXSUBIMAGE2DEXTPROC gl3wMultiTexSubImage2DEXT; -PFNGLMULTITEXSUBIMAGE3DEXTPROC gl3wMultiTexSubImage3DEXT; -PFNGLNAMEDBUFFERDATAPROC gl3wNamedBufferData; -PFNGLNAMEDBUFFERDATAEXTPROC gl3wNamedBufferDataEXT; -PFNGLNAMEDBUFFERPAGECOMMITMENTARBPROC gl3wNamedBufferPageCommitmentARB; -PFNGLNAMEDBUFFERPAGECOMMITMENTEXTPROC gl3wNamedBufferPageCommitmentEXT; -PFNGLNAMEDBUFFERSTORAGEPROC gl3wNamedBufferStorage; -PFNGLNAMEDBUFFERSTORAGEEXTPROC gl3wNamedBufferStorageEXT; -PFNGLNAMEDBUFFERSUBDATAPROC gl3wNamedBufferSubData; -PFNGLNAMEDBUFFERSUBDATAEXTPROC gl3wNamedBufferSubDataEXT; -PFNGLNAMEDCOPYBUFFERSUBDATAEXTPROC gl3wNamedCopyBufferSubDataEXT; -PFNGLNAMEDFRAMEBUFFERDRAWBUFFERPROC gl3wNamedFramebufferDrawBuffer; -PFNGLNAMEDFRAMEBUFFERDRAWBUFFERSPROC gl3wNamedFramebufferDrawBuffers; -PFNGLNAMEDFRAMEBUFFERPARAMETERIPROC gl3wNamedFramebufferParameteri; -PFNGLNAMEDFRAMEBUFFERPARAMETERIEXTPROC gl3wNamedFramebufferParameteriEXT; -PFNGLNAMEDFRAMEBUFFERREADBUFFERPROC gl3wNamedFramebufferReadBuffer; -PFNGLNAMEDFRAMEBUFFERRENDERBUFFERPROC gl3wNamedFramebufferRenderbuffer; -PFNGLNAMEDFRAMEBUFFERRENDERBUFFEREXTPROC gl3wNamedFramebufferRenderbufferEXT; -PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVARBPROC gl3wNamedFramebufferSampleLocationsfvARB; -PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVNVPROC gl3wNamedFramebufferSampleLocationsfvNV; -PFNGLNAMEDFRAMEBUFFERTEXTUREPROC gl3wNamedFramebufferTexture; -PFNGLNAMEDFRAMEBUFFERTEXTURE1DEXTPROC gl3wNamedFramebufferTexture1DEXT; -PFNGLNAMEDFRAMEBUFFERTEXTURE2DEXTPROC gl3wNamedFramebufferTexture2DEXT; -PFNGLNAMEDFRAMEBUFFERTEXTURE3DEXTPROC gl3wNamedFramebufferTexture3DEXT; -PFNGLNAMEDFRAMEBUFFERTEXTUREEXTPROC gl3wNamedFramebufferTextureEXT; -PFNGLNAMEDFRAMEBUFFERTEXTUREFACEEXTPROC gl3wNamedFramebufferTextureFaceEXT; -PFNGLNAMEDFRAMEBUFFERTEXTURELAYERPROC gl3wNamedFramebufferTextureLayer; -PFNGLNAMEDFRAMEBUFFERTEXTURELAYEREXTPROC gl3wNamedFramebufferTextureLayerEXT; -PFNGLNAMEDPROGRAMLOCALPARAMETER4DEXTPROC gl3wNamedProgramLocalParameter4dEXT; -PFNGLNAMEDPROGRAMLOCALPARAMETER4DVEXTPROC gl3wNamedProgramLocalParameter4dvEXT; -PFNGLNAMEDPROGRAMLOCALPARAMETER4FEXTPROC gl3wNamedProgramLocalParameter4fEXT; -PFNGLNAMEDPROGRAMLOCALPARAMETER4FVEXTPROC gl3wNamedProgramLocalParameter4fvEXT; -PFNGLNAMEDPROGRAMLOCALPARAMETERI4IEXTPROC gl3wNamedProgramLocalParameterI4iEXT; -PFNGLNAMEDPROGRAMLOCALPARAMETERI4IVEXTPROC gl3wNamedProgramLocalParameterI4ivEXT; -PFNGLNAMEDPROGRAMLOCALPARAMETERI4UIEXTPROC gl3wNamedProgramLocalParameterI4uiEXT; -PFNGLNAMEDPROGRAMLOCALPARAMETERI4UIVEXTPROC gl3wNamedProgramLocalParameterI4uivEXT; -PFNGLNAMEDPROGRAMLOCALPARAMETERS4FVEXTPROC gl3wNamedProgramLocalParameters4fvEXT; -PFNGLNAMEDPROGRAMLOCALPARAMETERSI4IVEXTPROC gl3wNamedProgramLocalParametersI4ivEXT; -PFNGLNAMEDPROGRAMLOCALPARAMETERSI4UIVEXTPROC gl3wNamedProgramLocalParametersI4uivEXT; -PFNGLNAMEDPROGRAMSTRINGEXTPROC gl3wNamedProgramStringEXT; -PFNGLNAMEDRENDERBUFFERSTORAGEPROC gl3wNamedRenderbufferStorage; -PFNGLNAMEDRENDERBUFFERSTORAGEEXTPROC gl3wNamedRenderbufferStorageEXT; -PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC gl3wNamedRenderbufferStorageMultisample; -PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLECOVERAGEEXTPROC gl3wNamedRenderbufferStorageMultisampleCoverageEXT; -PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC gl3wNamedRenderbufferStorageMultisampleEXT; -PFNGLNAMEDSTRINGARBPROC gl3wNamedStringARB; -PFNGLNORMALFORMATNVPROC gl3wNormalFormatNV; -PFNGLOBJECTLABELPROC gl3wObjectLabel; -PFNGLOBJECTPTRLABELPROC gl3wObjectPtrLabel; -PFNGLPATCHPARAMETERFVPROC gl3wPatchParameterfv; -PFNGLPATCHPARAMETERIPROC gl3wPatchParameteri; -PFNGLPATHCOMMANDSNVPROC gl3wPathCommandsNV; -PFNGLPATHCOORDSNVPROC gl3wPathCoordsNV; -PFNGLPATHCOVERDEPTHFUNCNVPROC gl3wPathCoverDepthFuncNV; -PFNGLPATHDASHARRAYNVPROC gl3wPathDashArrayNV; -PFNGLPATHGLYPHINDEXARRAYNVPROC gl3wPathGlyphIndexArrayNV; -PFNGLPATHGLYPHINDEXRANGENVPROC gl3wPathGlyphIndexRangeNV; -PFNGLPATHGLYPHRANGENVPROC gl3wPathGlyphRangeNV; -PFNGLPATHGLYPHSNVPROC gl3wPathGlyphsNV; -PFNGLPATHMEMORYGLYPHINDEXARRAYNVPROC gl3wPathMemoryGlyphIndexArrayNV; -PFNGLPATHPARAMETERFNVPROC gl3wPathParameterfNV; -PFNGLPATHPARAMETERFVNVPROC gl3wPathParameterfvNV; -PFNGLPATHPARAMETERINVPROC gl3wPathParameteriNV; -PFNGLPATHPARAMETERIVNVPROC gl3wPathParameterivNV; -PFNGLPATHSTENCILDEPTHOFFSETNVPROC gl3wPathStencilDepthOffsetNV; -PFNGLPATHSTENCILFUNCNVPROC gl3wPathStencilFuncNV; -PFNGLPATHSTRINGNVPROC gl3wPathStringNV; -PFNGLPATHSUBCOMMANDSNVPROC gl3wPathSubCommandsNV; -PFNGLPATHSUBCOORDSNVPROC gl3wPathSubCoordsNV; -PFNGLPAUSETRANSFORMFEEDBACKPROC gl3wPauseTransformFeedback; -PFNGLPIXELSTOREFPROC gl3wPixelStoref; -PFNGLPIXELSTOREIPROC gl3wPixelStorei; -PFNGLPOINTALONGPATHNVPROC gl3wPointAlongPathNV; -PFNGLPOINTPARAMETERFPROC gl3wPointParameterf; -PFNGLPOINTPARAMETERFVPROC gl3wPointParameterfv; -PFNGLPOINTPARAMETERIPROC gl3wPointParameteri; -PFNGLPOINTPARAMETERIVPROC gl3wPointParameteriv; -PFNGLPOINTSIZEPROC gl3wPointSize; -PFNGLPOLYGONMODEPROC gl3wPolygonMode; -PFNGLPOLYGONOFFSETPROC gl3wPolygonOffset; -PFNGLPOLYGONOFFSETCLAMPPROC gl3wPolygonOffsetClamp; -PFNGLPOLYGONOFFSETCLAMPEXTPROC gl3wPolygonOffsetClampEXT; -PFNGLPOPDEBUGGROUPPROC gl3wPopDebugGroup; -PFNGLPOPGROUPMARKEREXTPROC gl3wPopGroupMarkerEXT; -PFNGLPRIMITIVEBOUNDINGBOXARBPROC gl3wPrimitiveBoundingBoxARB; -PFNGLPRIMITIVERESTARTINDEXPROC gl3wPrimitiveRestartIndex; -PFNGLPROGRAMBINARYPROC gl3wProgramBinary; -PFNGLPROGRAMPARAMETERIPROC gl3wProgramParameteri; -PFNGLPROGRAMPARAMETERIARBPROC gl3wProgramParameteriARB; -PFNGLPROGRAMPATHFRAGMENTINPUTGENNVPROC gl3wProgramPathFragmentInputGenNV; -PFNGLPROGRAMUNIFORM1DPROC gl3wProgramUniform1d; -PFNGLPROGRAMUNIFORM1DEXTPROC gl3wProgramUniform1dEXT; -PFNGLPROGRAMUNIFORM1DVPROC gl3wProgramUniform1dv; -PFNGLPROGRAMUNIFORM1DVEXTPROC gl3wProgramUniform1dvEXT; -PFNGLPROGRAMUNIFORM1FPROC gl3wProgramUniform1f; -PFNGLPROGRAMUNIFORM1FEXTPROC gl3wProgramUniform1fEXT; -PFNGLPROGRAMUNIFORM1FVPROC gl3wProgramUniform1fv; -PFNGLPROGRAMUNIFORM1FVEXTPROC gl3wProgramUniform1fvEXT; -PFNGLPROGRAMUNIFORM1IPROC gl3wProgramUniform1i; -PFNGLPROGRAMUNIFORM1I64ARBPROC gl3wProgramUniform1i64ARB; -PFNGLPROGRAMUNIFORM1I64NVPROC gl3wProgramUniform1i64NV; -PFNGLPROGRAMUNIFORM1I64VARBPROC gl3wProgramUniform1i64vARB; -PFNGLPROGRAMUNIFORM1I64VNVPROC gl3wProgramUniform1i64vNV; -PFNGLPROGRAMUNIFORM1IEXTPROC gl3wProgramUniform1iEXT; -PFNGLPROGRAMUNIFORM1IVPROC gl3wProgramUniform1iv; -PFNGLPROGRAMUNIFORM1IVEXTPROC gl3wProgramUniform1ivEXT; -PFNGLPROGRAMUNIFORM1UIPROC gl3wProgramUniform1ui; -PFNGLPROGRAMUNIFORM1UI64ARBPROC gl3wProgramUniform1ui64ARB; -PFNGLPROGRAMUNIFORM1UI64NVPROC gl3wProgramUniform1ui64NV; -PFNGLPROGRAMUNIFORM1UI64VARBPROC gl3wProgramUniform1ui64vARB; -PFNGLPROGRAMUNIFORM1UI64VNVPROC gl3wProgramUniform1ui64vNV; -PFNGLPROGRAMUNIFORM1UIEXTPROC gl3wProgramUniform1uiEXT; -PFNGLPROGRAMUNIFORM1UIVPROC gl3wProgramUniform1uiv; -PFNGLPROGRAMUNIFORM1UIVEXTPROC gl3wProgramUniform1uivEXT; -PFNGLPROGRAMUNIFORM2DPROC gl3wProgramUniform2d; -PFNGLPROGRAMUNIFORM2DEXTPROC gl3wProgramUniform2dEXT; -PFNGLPROGRAMUNIFORM2DVPROC gl3wProgramUniform2dv; -PFNGLPROGRAMUNIFORM2DVEXTPROC gl3wProgramUniform2dvEXT; -PFNGLPROGRAMUNIFORM2FPROC gl3wProgramUniform2f; -PFNGLPROGRAMUNIFORM2FEXTPROC gl3wProgramUniform2fEXT; -PFNGLPROGRAMUNIFORM2FVPROC gl3wProgramUniform2fv; -PFNGLPROGRAMUNIFORM2FVEXTPROC gl3wProgramUniform2fvEXT; -PFNGLPROGRAMUNIFORM2IPROC gl3wProgramUniform2i; -PFNGLPROGRAMUNIFORM2I64ARBPROC gl3wProgramUniform2i64ARB; -PFNGLPROGRAMUNIFORM2I64NVPROC gl3wProgramUniform2i64NV; -PFNGLPROGRAMUNIFORM2I64VARBPROC gl3wProgramUniform2i64vARB; -PFNGLPROGRAMUNIFORM2I64VNVPROC gl3wProgramUniform2i64vNV; -PFNGLPROGRAMUNIFORM2IEXTPROC gl3wProgramUniform2iEXT; -PFNGLPROGRAMUNIFORM2IVPROC gl3wProgramUniform2iv; -PFNGLPROGRAMUNIFORM2IVEXTPROC gl3wProgramUniform2ivEXT; -PFNGLPROGRAMUNIFORM2UIPROC gl3wProgramUniform2ui; -PFNGLPROGRAMUNIFORM2UI64ARBPROC gl3wProgramUniform2ui64ARB; -PFNGLPROGRAMUNIFORM2UI64NVPROC gl3wProgramUniform2ui64NV; -PFNGLPROGRAMUNIFORM2UI64VARBPROC gl3wProgramUniform2ui64vARB; -PFNGLPROGRAMUNIFORM2UI64VNVPROC gl3wProgramUniform2ui64vNV; -PFNGLPROGRAMUNIFORM2UIEXTPROC gl3wProgramUniform2uiEXT; -PFNGLPROGRAMUNIFORM2UIVPROC gl3wProgramUniform2uiv; -PFNGLPROGRAMUNIFORM2UIVEXTPROC gl3wProgramUniform2uivEXT; -PFNGLPROGRAMUNIFORM3DPROC gl3wProgramUniform3d; -PFNGLPROGRAMUNIFORM3DEXTPROC gl3wProgramUniform3dEXT; -PFNGLPROGRAMUNIFORM3DVPROC gl3wProgramUniform3dv; -PFNGLPROGRAMUNIFORM3DVEXTPROC gl3wProgramUniform3dvEXT; -PFNGLPROGRAMUNIFORM3FPROC gl3wProgramUniform3f; -PFNGLPROGRAMUNIFORM3FEXTPROC gl3wProgramUniform3fEXT; -PFNGLPROGRAMUNIFORM3FVPROC gl3wProgramUniform3fv; -PFNGLPROGRAMUNIFORM3FVEXTPROC gl3wProgramUniform3fvEXT; -PFNGLPROGRAMUNIFORM3IPROC gl3wProgramUniform3i; -PFNGLPROGRAMUNIFORM3I64ARBPROC gl3wProgramUniform3i64ARB; -PFNGLPROGRAMUNIFORM3I64NVPROC gl3wProgramUniform3i64NV; -PFNGLPROGRAMUNIFORM3I64VARBPROC gl3wProgramUniform3i64vARB; -PFNGLPROGRAMUNIFORM3I64VNVPROC gl3wProgramUniform3i64vNV; -PFNGLPROGRAMUNIFORM3IEXTPROC gl3wProgramUniform3iEXT; -PFNGLPROGRAMUNIFORM3IVPROC gl3wProgramUniform3iv; -PFNGLPROGRAMUNIFORM3IVEXTPROC gl3wProgramUniform3ivEXT; -PFNGLPROGRAMUNIFORM3UIPROC gl3wProgramUniform3ui; -PFNGLPROGRAMUNIFORM3UI64ARBPROC gl3wProgramUniform3ui64ARB; -PFNGLPROGRAMUNIFORM3UI64NVPROC gl3wProgramUniform3ui64NV; -PFNGLPROGRAMUNIFORM3UI64VARBPROC gl3wProgramUniform3ui64vARB; -PFNGLPROGRAMUNIFORM3UI64VNVPROC gl3wProgramUniform3ui64vNV; -PFNGLPROGRAMUNIFORM3UIEXTPROC gl3wProgramUniform3uiEXT; -PFNGLPROGRAMUNIFORM3UIVPROC gl3wProgramUniform3uiv; -PFNGLPROGRAMUNIFORM3UIVEXTPROC gl3wProgramUniform3uivEXT; -PFNGLPROGRAMUNIFORM4DPROC gl3wProgramUniform4d; -PFNGLPROGRAMUNIFORM4DEXTPROC gl3wProgramUniform4dEXT; -PFNGLPROGRAMUNIFORM4DVPROC gl3wProgramUniform4dv; -PFNGLPROGRAMUNIFORM4DVEXTPROC gl3wProgramUniform4dvEXT; -PFNGLPROGRAMUNIFORM4FPROC gl3wProgramUniform4f; -PFNGLPROGRAMUNIFORM4FEXTPROC gl3wProgramUniform4fEXT; -PFNGLPROGRAMUNIFORM4FVPROC gl3wProgramUniform4fv; -PFNGLPROGRAMUNIFORM4FVEXTPROC gl3wProgramUniform4fvEXT; -PFNGLPROGRAMUNIFORM4IPROC gl3wProgramUniform4i; -PFNGLPROGRAMUNIFORM4I64ARBPROC gl3wProgramUniform4i64ARB; -PFNGLPROGRAMUNIFORM4I64NVPROC gl3wProgramUniform4i64NV; -PFNGLPROGRAMUNIFORM4I64VARBPROC gl3wProgramUniform4i64vARB; -PFNGLPROGRAMUNIFORM4I64VNVPROC gl3wProgramUniform4i64vNV; -PFNGLPROGRAMUNIFORM4IEXTPROC gl3wProgramUniform4iEXT; -PFNGLPROGRAMUNIFORM4IVPROC gl3wProgramUniform4iv; -PFNGLPROGRAMUNIFORM4IVEXTPROC gl3wProgramUniform4ivEXT; -PFNGLPROGRAMUNIFORM4UIPROC gl3wProgramUniform4ui; -PFNGLPROGRAMUNIFORM4UI64ARBPROC gl3wProgramUniform4ui64ARB; -PFNGLPROGRAMUNIFORM4UI64NVPROC gl3wProgramUniform4ui64NV; -PFNGLPROGRAMUNIFORM4UI64VARBPROC gl3wProgramUniform4ui64vARB; -PFNGLPROGRAMUNIFORM4UI64VNVPROC gl3wProgramUniform4ui64vNV; -PFNGLPROGRAMUNIFORM4UIEXTPROC gl3wProgramUniform4uiEXT; -PFNGLPROGRAMUNIFORM4UIVPROC gl3wProgramUniform4uiv; -PFNGLPROGRAMUNIFORM4UIVEXTPROC gl3wProgramUniform4uivEXT; -PFNGLPROGRAMUNIFORMHANDLEUI64ARBPROC gl3wProgramUniformHandleui64ARB; -PFNGLPROGRAMUNIFORMHANDLEUI64NVPROC gl3wProgramUniformHandleui64NV; -PFNGLPROGRAMUNIFORMHANDLEUI64VARBPROC gl3wProgramUniformHandleui64vARB; -PFNGLPROGRAMUNIFORMHANDLEUI64VNVPROC gl3wProgramUniformHandleui64vNV; -PFNGLPROGRAMUNIFORMMATRIX2DVPROC gl3wProgramUniformMatrix2dv; -PFNGLPROGRAMUNIFORMMATRIX2DVEXTPROC gl3wProgramUniformMatrix2dvEXT; -PFNGLPROGRAMUNIFORMMATRIX2FVPROC gl3wProgramUniformMatrix2fv; -PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC gl3wProgramUniformMatrix2fvEXT; -PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC gl3wProgramUniformMatrix2x3dv; -PFNGLPROGRAMUNIFORMMATRIX2X3DVEXTPROC gl3wProgramUniformMatrix2x3dvEXT; -PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC gl3wProgramUniformMatrix2x3fv; -PFNGLPROGRAMUNIFORMMATRIX2X3FVEXTPROC gl3wProgramUniformMatrix2x3fvEXT; -PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC gl3wProgramUniformMatrix2x4dv; -PFNGLPROGRAMUNIFORMMATRIX2X4DVEXTPROC gl3wProgramUniformMatrix2x4dvEXT; -PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC gl3wProgramUniformMatrix2x4fv; -PFNGLPROGRAMUNIFORMMATRIX2X4FVEXTPROC gl3wProgramUniformMatrix2x4fvEXT; -PFNGLPROGRAMUNIFORMMATRIX3DVPROC gl3wProgramUniformMatrix3dv; -PFNGLPROGRAMUNIFORMMATRIX3DVEXTPROC gl3wProgramUniformMatrix3dvEXT; -PFNGLPROGRAMUNIFORMMATRIX3FVPROC gl3wProgramUniformMatrix3fv; -PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC gl3wProgramUniformMatrix3fvEXT; -PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC gl3wProgramUniformMatrix3x2dv; -PFNGLPROGRAMUNIFORMMATRIX3X2DVEXTPROC gl3wProgramUniformMatrix3x2dvEXT; -PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC gl3wProgramUniformMatrix3x2fv; -PFNGLPROGRAMUNIFORMMATRIX3X2FVEXTPROC gl3wProgramUniformMatrix3x2fvEXT; -PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC gl3wProgramUniformMatrix3x4dv; -PFNGLPROGRAMUNIFORMMATRIX3X4DVEXTPROC gl3wProgramUniformMatrix3x4dvEXT; -PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC gl3wProgramUniformMatrix3x4fv; -PFNGLPROGRAMUNIFORMMATRIX3X4FVEXTPROC gl3wProgramUniformMatrix3x4fvEXT; -PFNGLPROGRAMUNIFORMMATRIX4DVPROC gl3wProgramUniformMatrix4dv; -PFNGLPROGRAMUNIFORMMATRIX4DVEXTPROC gl3wProgramUniformMatrix4dvEXT; -PFNGLPROGRAMUNIFORMMATRIX4FVPROC gl3wProgramUniformMatrix4fv; -PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC gl3wProgramUniformMatrix4fvEXT; -PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC gl3wProgramUniformMatrix4x2dv; -PFNGLPROGRAMUNIFORMMATRIX4X2DVEXTPROC gl3wProgramUniformMatrix4x2dvEXT; -PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC gl3wProgramUniformMatrix4x2fv; -PFNGLPROGRAMUNIFORMMATRIX4X2FVEXTPROC gl3wProgramUniformMatrix4x2fvEXT; -PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC gl3wProgramUniformMatrix4x3dv; -PFNGLPROGRAMUNIFORMMATRIX4X3DVEXTPROC gl3wProgramUniformMatrix4x3dvEXT; -PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC gl3wProgramUniformMatrix4x3fv; -PFNGLPROGRAMUNIFORMMATRIX4X3FVEXTPROC gl3wProgramUniformMatrix4x3fvEXT; -PFNGLPROGRAMUNIFORMUI64NVPROC gl3wProgramUniformui64NV; -PFNGLPROGRAMUNIFORMUI64VNVPROC gl3wProgramUniformui64vNV; -PFNGLPROVOKINGVERTEXPROC gl3wProvokingVertex; -PFNGLPUSHCLIENTATTRIBDEFAULTEXTPROC gl3wPushClientAttribDefaultEXT; -PFNGLPUSHDEBUGGROUPPROC gl3wPushDebugGroup; -PFNGLPUSHGROUPMARKEREXTPROC gl3wPushGroupMarkerEXT; -PFNGLQUERYCOUNTERPROC gl3wQueryCounter; -PFNGLRASTERSAMPLESEXTPROC gl3wRasterSamplesEXT; -PFNGLREADBUFFERPROC gl3wReadBuffer; -PFNGLREADPIXELSPROC gl3wReadPixels; -PFNGLREADNPIXELSPROC gl3wReadnPixels; -PFNGLREADNPIXELSARBPROC gl3wReadnPixelsARB; -PFNGLRELEASESHADERCOMPILERPROC gl3wReleaseShaderCompiler; -PFNGLRENDERBUFFERSTORAGEPROC gl3wRenderbufferStorage; -PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC gl3wRenderbufferStorageMultisample; -PFNGLRENDERBUFFERSTORAGEMULTISAMPLECOVERAGENVPROC gl3wRenderbufferStorageMultisampleCoverageNV; -PFNGLRESOLVEDEPTHVALUESNVPROC gl3wResolveDepthValuesNV; -PFNGLRESUMETRANSFORMFEEDBACKPROC gl3wResumeTransformFeedback; -PFNGLSAMPLECOVERAGEPROC gl3wSampleCoverage; -PFNGLSAMPLEMASKIPROC gl3wSampleMaski; -PFNGLSAMPLERPARAMETERIIVPROC gl3wSamplerParameterIiv; -PFNGLSAMPLERPARAMETERIUIVPROC gl3wSamplerParameterIuiv; -PFNGLSAMPLERPARAMETERFPROC gl3wSamplerParameterf; -PFNGLSAMPLERPARAMETERFVPROC gl3wSamplerParameterfv; -PFNGLSAMPLERPARAMETERIPROC gl3wSamplerParameteri; -PFNGLSAMPLERPARAMETERIVPROC gl3wSamplerParameteriv; -PFNGLSCISSORPROC gl3wScissor; -PFNGLSCISSORARRAYVPROC gl3wScissorArrayv; -PFNGLSCISSORINDEXEDPROC gl3wScissorIndexed; -PFNGLSCISSORINDEXEDVPROC gl3wScissorIndexedv; -PFNGLSECONDARYCOLORFORMATNVPROC gl3wSecondaryColorFormatNV; -PFNGLSELECTPERFMONITORCOUNTERSAMDPROC gl3wSelectPerfMonitorCountersAMD; -PFNGLSHADERBINARYPROC gl3wShaderBinary; -PFNGLSHADERSOURCEPROC gl3wShaderSource; -PFNGLSHADERSTORAGEBLOCKBINDINGPROC gl3wShaderStorageBlockBinding; -PFNGLSIGNALVKFENCENVPROC gl3wSignalVkFenceNV; -PFNGLSIGNALVKSEMAPHORENVPROC gl3wSignalVkSemaphoreNV; -PFNGLSPECIALIZESHADERPROC gl3wSpecializeShader; -PFNGLSPECIALIZESHADERARBPROC gl3wSpecializeShaderARB; -PFNGLSTATECAPTURENVPROC gl3wStateCaptureNV; -PFNGLSTENCILFILLPATHINSTANCEDNVPROC gl3wStencilFillPathInstancedNV; -PFNGLSTENCILFILLPATHNVPROC gl3wStencilFillPathNV; -PFNGLSTENCILFUNCPROC gl3wStencilFunc; -PFNGLSTENCILFUNCSEPARATEPROC gl3wStencilFuncSeparate; -PFNGLSTENCILMASKPROC gl3wStencilMask; -PFNGLSTENCILMASKSEPARATEPROC gl3wStencilMaskSeparate; -PFNGLSTENCILOPPROC gl3wStencilOp; -PFNGLSTENCILOPSEPARATEPROC gl3wStencilOpSeparate; -PFNGLSTENCILSTROKEPATHINSTANCEDNVPROC gl3wStencilStrokePathInstancedNV; -PFNGLSTENCILSTROKEPATHNVPROC gl3wStencilStrokePathNV; -PFNGLSTENCILTHENCOVERFILLPATHINSTANCEDNVPROC gl3wStencilThenCoverFillPathInstancedNV; -PFNGLSTENCILTHENCOVERFILLPATHNVPROC gl3wStencilThenCoverFillPathNV; -PFNGLSTENCILTHENCOVERSTROKEPATHINSTANCEDNVPROC gl3wStencilThenCoverStrokePathInstancedNV; -PFNGLSTENCILTHENCOVERSTROKEPATHNVPROC gl3wStencilThenCoverStrokePathNV; -PFNGLSUBPIXELPRECISIONBIASNVPROC gl3wSubpixelPrecisionBiasNV; -PFNGLTEXBUFFERPROC gl3wTexBuffer; -PFNGLTEXBUFFERARBPROC gl3wTexBufferARB; -PFNGLTEXBUFFERRANGEPROC gl3wTexBufferRange; -PFNGLTEXCOORDFORMATNVPROC gl3wTexCoordFormatNV; -PFNGLTEXIMAGE1DPROC gl3wTexImage1D; -PFNGLTEXIMAGE2DPROC gl3wTexImage2D; -PFNGLTEXIMAGE2DMULTISAMPLEPROC gl3wTexImage2DMultisample; -PFNGLTEXIMAGE3DPROC gl3wTexImage3D; -PFNGLTEXIMAGE3DMULTISAMPLEPROC gl3wTexImage3DMultisample; -PFNGLTEXPAGECOMMITMENTARBPROC gl3wTexPageCommitmentARB; -PFNGLTEXPARAMETERIIVPROC gl3wTexParameterIiv; -PFNGLTEXPARAMETERIUIVPROC gl3wTexParameterIuiv; -PFNGLTEXPARAMETERFPROC gl3wTexParameterf; -PFNGLTEXPARAMETERFVPROC gl3wTexParameterfv; -PFNGLTEXPARAMETERIPROC gl3wTexParameteri; -PFNGLTEXPARAMETERIVPROC gl3wTexParameteriv; -PFNGLTEXSTORAGE1DPROC gl3wTexStorage1D; -PFNGLTEXSTORAGE2DPROC gl3wTexStorage2D; -PFNGLTEXSTORAGE2DMULTISAMPLEPROC gl3wTexStorage2DMultisample; -PFNGLTEXSTORAGE3DPROC gl3wTexStorage3D; -PFNGLTEXSTORAGE3DMULTISAMPLEPROC gl3wTexStorage3DMultisample; -PFNGLTEXSUBIMAGE1DPROC gl3wTexSubImage1D; -PFNGLTEXSUBIMAGE2DPROC gl3wTexSubImage2D; -PFNGLTEXSUBIMAGE3DPROC gl3wTexSubImage3D; -PFNGLTEXTUREBARRIERPROC gl3wTextureBarrier; -PFNGLTEXTUREBARRIERNVPROC gl3wTextureBarrierNV; -PFNGLTEXTUREBUFFERPROC gl3wTextureBuffer; -PFNGLTEXTUREBUFFEREXTPROC gl3wTextureBufferEXT; -PFNGLTEXTUREBUFFERRANGEPROC gl3wTextureBufferRange; -PFNGLTEXTUREBUFFERRANGEEXTPROC gl3wTextureBufferRangeEXT; -PFNGLTEXTUREIMAGE1DEXTPROC gl3wTextureImage1DEXT; -PFNGLTEXTUREIMAGE2DEXTPROC gl3wTextureImage2DEXT; -PFNGLTEXTUREIMAGE3DEXTPROC gl3wTextureImage3DEXT; -PFNGLTEXTUREPAGECOMMITMENTEXTPROC gl3wTexturePageCommitmentEXT; -PFNGLTEXTUREPARAMETERIIVPROC gl3wTextureParameterIiv; -PFNGLTEXTUREPARAMETERIIVEXTPROC gl3wTextureParameterIivEXT; -PFNGLTEXTUREPARAMETERIUIVPROC gl3wTextureParameterIuiv; -PFNGLTEXTUREPARAMETERIUIVEXTPROC gl3wTextureParameterIuivEXT; -PFNGLTEXTUREPARAMETERFPROC gl3wTextureParameterf; -PFNGLTEXTUREPARAMETERFEXTPROC gl3wTextureParameterfEXT; -PFNGLTEXTUREPARAMETERFVPROC gl3wTextureParameterfv; -PFNGLTEXTUREPARAMETERFVEXTPROC gl3wTextureParameterfvEXT; -PFNGLTEXTUREPARAMETERIPROC gl3wTextureParameteri; -PFNGLTEXTUREPARAMETERIEXTPROC gl3wTextureParameteriEXT; -PFNGLTEXTUREPARAMETERIVPROC gl3wTextureParameteriv; -PFNGLTEXTUREPARAMETERIVEXTPROC gl3wTextureParameterivEXT; -PFNGLTEXTURERENDERBUFFEREXTPROC gl3wTextureRenderbufferEXT; -PFNGLTEXTURESTORAGE1DPROC gl3wTextureStorage1D; -PFNGLTEXTURESTORAGE1DEXTPROC gl3wTextureStorage1DEXT; -PFNGLTEXTURESTORAGE2DPROC gl3wTextureStorage2D; -PFNGLTEXTURESTORAGE2DEXTPROC gl3wTextureStorage2DEXT; -PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC gl3wTextureStorage2DMultisample; -PFNGLTEXTURESTORAGE2DMULTISAMPLEEXTPROC gl3wTextureStorage2DMultisampleEXT; -PFNGLTEXTURESTORAGE3DPROC gl3wTextureStorage3D; -PFNGLTEXTURESTORAGE3DEXTPROC gl3wTextureStorage3DEXT; -PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC gl3wTextureStorage3DMultisample; -PFNGLTEXTURESTORAGE3DMULTISAMPLEEXTPROC gl3wTextureStorage3DMultisampleEXT; -PFNGLTEXTURESUBIMAGE1DPROC gl3wTextureSubImage1D; -PFNGLTEXTURESUBIMAGE1DEXTPROC gl3wTextureSubImage1DEXT; -PFNGLTEXTURESUBIMAGE2DPROC gl3wTextureSubImage2D; -PFNGLTEXTURESUBIMAGE2DEXTPROC gl3wTextureSubImage2DEXT; -PFNGLTEXTURESUBIMAGE3DPROC gl3wTextureSubImage3D; -PFNGLTEXTURESUBIMAGE3DEXTPROC gl3wTextureSubImage3DEXT; -PFNGLTEXTUREVIEWPROC gl3wTextureView; -PFNGLTRANSFORMFEEDBACKBUFFERBASEPROC gl3wTransformFeedbackBufferBase; -PFNGLTRANSFORMFEEDBACKBUFFERRANGEPROC gl3wTransformFeedbackBufferRange; -PFNGLTRANSFORMFEEDBACKVARYINGSPROC gl3wTransformFeedbackVaryings; -PFNGLTRANSFORMPATHNVPROC gl3wTransformPathNV; -PFNGLUNIFORM1DPROC gl3wUniform1d; -PFNGLUNIFORM1DVPROC gl3wUniform1dv; -PFNGLUNIFORM1FPROC gl3wUniform1f; -PFNGLUNIFORM1FVPROC gl3wUniform1fv; -PFNGLUNIFORM1IPROC gl3wUniform1i; -PFNGLUNIFORM1I64ARBPROC gl3wUniform1i64ARB; -PFNGLUNIFORM1I64NVPROC gl3wUniform1i64NV; -PFNGLUNIFORM1I64VARBPROC gl3wUniform1i64vARB; -PFNGLUNIFORM1I64VNVPROC gl3wUniform1i64vNV; -PFNGLUNIFORM1IVPROC gl3wUniform1iv; -PFNGLUNIFORM1UIPROC gl3wUniform1ui; -PFNGLUNIFORM1UI64ARBPROC gl3wUniform1ui64ARB; -PFNGLUNIFORM1UI64NVPROC gl3wUniform1ui64NV; -PFNGLUNIFORM1UI64VARBPROC gl3wUniform1ui64vARB; -PFNGLUNIFORM1UI64VNVPROC gl3wUniform1ui64vNV; -PFNGLUNIFORM1UIVPROC gl3wUniform1uiv; -PFNGLUNIFORM2DPROC gl3wUniform2d; -PFNGLUNIFORM2DVPROC gl3wUniform2dv; -PFNGLUNIFORM2FPROC gl3wUniform2f; -PFNGLUNIFORM2FVPROC gl3wUniform2fv; -PFNGLUNIFORM2IPROC gl3wUniform2i; -PFNGLUNIFORM2I64ARBPROC gl3wUniform2i64ARB; -PFNGLUNIFORM2I64NVPROC gl3wUniform2i64NV; -PFNGLUNIFORM2I64VARBPROC gl3wUniform2i64vARB; -PFNGLUNIFORM2I64VNVPROC gl3wUniform2i64vNV; -PFNGLUNIFORM2IVPROC gl3wUniform2iv; -PFNGLUNIFORM2UIPROC gl3wUniform2ui; -PFNGLUNIFORM2UI64ARBPROC gl3wUniform2ui64ARB; -PFNGLUNIFORM2UI64NVPROC gl3wUniform2ui64NV; -PFNGLUNIFORM2UI64VARBPROC gl3wUniform2ui64vARB; -PFNGLUNIFORM2UI64VNVPROC gl3wUniform2ui64vNV; -PFNGLUNIFORM2UIVPROC gl3wUniform2uiv; -PFNGLUNIFORM3DPROC gl3wUniform3d; -PFNGLUNIFORM3DVPROC gl3wUniform3dv; -PFNGLUNIFORM3FPROC gl3wUniform3f; -PFNGLUNIFORM3FVPROC gl3wUniform3fv; -PFNGLUNIFORM3IPROC gl3wUniform3i; -PFNGLUNIFORM3I64ARBPROC gl3wUniform3i64ARB; -PFNGLUNIFORM3I64NVPROC gl3wUniform3i64NV; -PFNGLUNIFORM3I64VARBPROC gl3wUniform3i64vARB; -PFNGLUNIFORM3I64VNVPROC gl3wUniform3i64vNV; -PFNGLUNIFORM3IVPROC gl3wUniform3iv; -PFNGLUNIFORM3UIPROC gl3wUniform3ui; -PFNGLUNIFORM3UI64ARBPROC gl3wUniform3ui64ARB; -PFNGLUNIFORM3UI64NVPROC gl3wUniform3ui64NV; -PFNGLUNIFORM3UI64VARBPROC gl3wUniform3ui64vARB; -PFNGLUNIFORM3UI64VNVPROC gl3wUniform3ui64vNV; -PFNGLUNIFORM3UIVPROC gl3wUniform3uiv; -PFNGLUNIFORM4DPROC gl3wUniform4d; -PFNGLUNIFORM4DVPROC gl3wUniform4dv; -PFNGLUNIFORM4FPROC gl3wUniform4f; -PFNGLUNIFORM4FVPROC gl3wUniform4fv; -PFNGLUNIFORM4IPROC gl3wUniform4i; -PFNGLUNIFORM4I64ARBPROC gl3wUniform4i64ARB; -PFNGLUNIFORM4I64NVPROC gl3wUniform4i64NV; -PFNGLUNIFORM4I64VARBPROC gl3wUniform4i64vARB; -PFNGLUNIFORM4I64VNVPROC gl3wUniform4i64vNV; -PFNGLUNIFORM4IVPROC gl3wUniform4iv; -PFNGLUNIFORM4UIPROC gl3wUniform4ui; -PFNGLUNIFORM4UI64ARBPROC gl3wUniform4ui64ARB; -PFNGLUNIFORM4UI64NVPROC gl3wUniform4ui64NV; -PFNGLUNIFORM4UI64VARBPROC gl3wUniform4ui64vARB; -PFNGLUNIFORM4UI64VNVPROC gl3wUniform4ui64vNV; -PFNGLUNIFORM4UIVPROC gl3wUniform4uiv; -PFNGLUNIFORMBLOCKBINDINGPROC gl3wUniformBlockBinding; -PFNGLUNIFORMHANDLEUI64ARBPROC gl3wUniformHandleui64ARB; -PFNGLUNIFORMHANDLEUI64NVPROC gl3wUniformHandleui64NV; -PFNGLUNIFORMHANDLEUI64VARBPROC gl3wUniformHandleui64vARB; -PFNGLUNIFORMHANDLEUI64VNVPROC gl3wUniformHandleui64vNV; -PFNGLUNIFORMMATRIX2DVPROC gl3wUniformMatrix2dv; -PFNGLUNIFORMMATRIX2FVPROC gl3wUniformMatrix2fv; -PFNGLUNIFORMMATRIX2X3DVPROC gl3wUniformMatrix2x3dv; -PFNGLUNIFORMMATRIX2X3FVPROC gl3wUniformMatrix2x3fv; -PFNGLUNIFORMMATRIX2X4DVPROC gl3wUniformMatrix2x4dv; -PFNGLUNIFORMMATRIX2X4FVPROC gl3wUniformMatrix2x4fv; -PFNGLUNIFORMMATRIX3DVPROC gl3wUniformMatrix3dv; -PFNGLUNIFORMMATRIX3FVPROC gl3wUniformMatrix3fv; -PFNGLUNIFORMMATRIX3X2DVPROC gl3wUniformMatrix3x2dv; -PFNGLUNIFORMMATRIX3X2FVPROC gl3wUniformMatrix3x2fv; -PFNGLUNIFORMMATRIX3X4DVPROC gl3wUniformMatrix3x4dv; -PFNGLUNIFORMMATRIX3X4FVPROC gl3wUniformMatrix3x4fv; -PFNGLUNIFORMMATRIX4DVPROC gl3wUniformMatrix4dv; -PFNGLUNIFORMMATRIX4FVPROC gl3wUniformMatrix4fv; -PFNGLUNIFORMMATRIX4X2DVPROC gl3wUniformMatrix4x2dv; -PFNGLUNIFORMMATRIX4X2FVPROC gl3wUniformMatrix4x2fv; -PFNGLUNIFORMMATRIX4X3DVPROC gl3wUniformMatrix4x3dv; -PFNGLUNIFORMMATRIX4X3FVPROC gl3wUniformMatrix4x3fv; -PFNGLUNIFORMSUBROUTINESUIVPROC gl3wUniformSubroutinesuiv; -PFNGLUNIFORMUI64NVPROC gl3wUniformui64NV; -PFNGLUNIFORMUI64VNVPROC gl3wUniformui64vNV; -PFNGLUNMAPBUFFERPROC gl3wUnmapBuffer; -PFNGLUNMAPNAMEDBUFFERPROC gl3wUnmapNamedBuffer; -PFNGLUNMAPNAMEDBUFFEREXTPROC gl3wUnmapNamedBufferEXT; -PFNGLUSEPROGRAMPROC gl3wUseProgram; -PFNGLUSEPROGRAMSTAGESPROC gl3wUseProgramStages; -PFNGLUSESHADERPROGRAMEXTPROC gl3wUseShaderProgramEXT; -PFNGLVALIDATEPROGRAMPROC gl3wValidateProgram; -PFNGLVALIDATEPROGRAMPIPELINEPROC gl3wValidateProgramPipeline; -PFNGLVERTEXARRAYATTRIBBINDINGPROC gl3wVertexArrayAttribBinding; -PFNGLVERTEXARRAYATTRIBFORMATPROC gl3wVertexArrayAttribFormat; -PFNGLVERTEXARRAYATTRIBIFORMATPROC gl3wVertexArrayAttribIFormat; -PFNGLVERTEXARRAYATTRIBLFORMATPROC gl3wVertexArrayAttribLFormat; -PFNGLVERTEXARRAYBINDVERTEXBUFFEREXTPROC gl3wVertexArrayBindVertexBufferEXT; -PFNGLVERTEXARRAYBINDINGDIVISORPROC gl3wVertexArrayBindingDivisor; -PFNGLVERTEXARRAYCOLOROFFSETEXTPROC gl3wVertexArrayColorOffsetEXT; -PFNGLVERTEXARRAYEDGEFLAGOFFSETEXTPROC gl3wVertexArrayEdgeFlagOffsetEXT; -PFNGLVERTEXARRAYELEMENTBUFFERPROC gl3wVertexArrayElementBuffer; -PFNGLVERTEXARRAYFOGCOORDOFFSETEXTPROC gl3wVertexArrayFogCoordOffsetEXT; -PFNGLVERTEXARRAYINDEXOFFSETEXTPROC gl3wVertexArrayIndexOffsetEXT; -PFNGLVERTEXARRAYMULTITEXCOORDOFFSETEXTPROC gl3wVertexArrayMultiTexCoordOffsetEXT; -PFNGLVERTEXARRAYNORMALOFFSETEXTPROC gl3wVertexArrayNormalOffsetEXT; -PFNGLVERTEXARRAYSECONDARYCOLOROFFSETEXTPROC gl3wVertexArraySecondaryColorOffsetEXT; -PFNGLVERTEXARRAYTEXCOORDOFFSETEXTPROC gl3wVertexArrayTexCoordOffsetEXT; -PFNGLVERTEXARRAYVERTEXATTRIBBINDINGEXTPROC gl3wVertexArrayVertexAttribBindingEXT; -PFNGLVERTEXARRAYVERTEXATTRIBDIVISOREXTPROC gl3wVertexArrayVertexAttribDivisorEXT; -PFNGLVERTEXARRAYVERTEXATTRIBFORMATEXTPROC gl3wVertexArrayVertexAttribFormatEXT; -PFNGLVERTEXARRAYVERTEXATTRIBIFORMATEXTPROC gl3wVertexArrayVertexAttribIFormatEXT; -PFNGLVERTEXARRAYVERTEXATTRIBIOFFSETEXTPROC gl3wVertexArrayVertexAttribIOffsetEXT; -PFNGLVERTEXARRAYVERTEXATTRIBLFORMATEXTPROC gl3wVertexArrayVertexAttribLFormatEXT; -PFNGLVERTEXARRAYVERTEXATTRIBLOFFSETEXTPROC gl3wVertexArrayVertexAttribLOffsetEXT; -PFNGLVERTEXARRAYVERTEXATTRIBOFFSETEXTPROC gl3wVertexArrayVertexAttribOffsetEXT; -PFNGLVERTEXARRAYVERTEXBINDINGDIVISOREXTPROC gl3wVertexArrayVertexBindingDivisorEXT; -PFNGLVERTEXARRAYVERTEXBUFFERPROC gl3wVertexArrayVertexBuffer; -PFNGLVERTEXARRAYVERTEXBUFFERSPROC gl3wVertexArrayVertexBuffers; -PFNGLVERTEXARRAYVERTEXOFFSETEXTPROC gl3wVertexArrayVertexOffsetEXT; -PFNGLVERTEXATTRIB1DPROC gl3wVertexAttrib1d; -PFNGLVERTEXATTRIB1DVPROC gl3wVertexAttrib1dv; -PFNGLVERTEXATTRIB1FPROC gl3wVertexAttrib1f; -PFNGLVERTEXATTRIB1FVPROC gl3wVertexAttrib1fv; -PFNGLVERTEXATTRIB1SPROC gl3wVertexAttrib1s; -PFNGLVERTEXATTRIB1SVPROC gl3wVertexAttrib1sv; -PFNGLVERTEXATTRIB2DPROC gl3wVertexAttrib2d; -PFNGLVERTEXATTRIB2DVPROC gl3wVertexAttrib2dv; -PFNGLVERTEXATTRIB2FPROC gl3wVertexAttrib2f; -PFNGLVERTEXATTRIB2FVPROC gl3wVertexAttrib2fv; -PFNGLVERTEXATTRIB2SPROC gl3wVertexAttrib2s; -PFNGLVERTEXATTRIB2SVPROC gl3wVertexAttrib2sv; -PFNGLVERTEXATTRIB3DPROC gl3wVertexAttrib3d; -PFNGLVERTEXATTRIB3DVPROC gl3wVertexAttrib3dv; -PFNGLVERTEXATTRIB3FPROC gl3wVertexAttrib3f; -PFNGLVERTEXATTRIB3FVPROC gl3wVertexAttrib3fv; -PFNGLVERTEXATTRIB3SPROC gl3wVertexAttrib3s; -PFNGLVERTEXATTRIB3SVPROC gl3wVertexAttrib3sv; -PFNGLVERTEXATTRIB4NBVPROC gl3wVertexAttrib4Nbv; -PFNGLVERTEXATTRIB4NIVPROC gl3wVertexAttrib4Niv; -PFNGLVERTEXATTRIB4NSVPROC gl3wVertexAttrib4Nsv; -PFNGLVERTEXATTRIB4NUBPROC gl3wVertexAttrib4Nub; -PFNGLVERTEXATTRIB4NUBVPROC gl3wVertexAttrib4Nubv; -PFNGLVERTEXATTRIB4NUIVPROC gl3wVertexAttrib4Nuiv; -PFNGLVERTEXATTRIB4NUSVPROC gl3wVertexAttrib4Nusv; -PFNGLVERTEXATTRIB4BVPROC gl3wVertexAttrib4bv; -PFNGLVERTEXATTRIB4DPROC gl3wVertexAttrib4d; -PFNGLVERTEXATTRIB4DVPROC gl3wVertexAttrib4dv; -PFNGLVERTEXATTRIB4FPROC gl3wVertexAttrib4f; -PFNGLVERTEXATTRIB4FVPROC gl3wVertexAttrib4fv; -PFNGLVERTEXATTRIB4IVPROC gl3wVertexAttrib4iv; -PFNGLVERTEXATTRIB4SPROC gl3wVertexAttrib4s; -PFNGLVERTEXATTRIB4SVPROC gl3wVertexAttrib4sv; -PFNGLVERTEXATTRIB4UBVPROC gl3wVertexAttrib4ubv; -PFNGLVERTEXATTRIB4UIVPROC gl3wVertexAttrib4uiv; -PFNGLVERTEXATTRIB4USVPROC gl3wVertexAttrib4usv; -PFNGLVERTEXATTRIBBINDINGPROC gl3wVertexAttribBinding; -PFNGLVERTEXATTRIBDIVISORPROC gl3wVertexAttribDivisor; -PFNGLVERTEXATTRIBDIVISORARBPROC gl3wVertexAttribDivisorARB; -PFNGLVERTEXATTRIBFORMATPROC gl3wVertexAttribFormat; -PFNGLVERTEXATTRIBFORMATNVPROC gl3wVertexAttribFormatNV; -PFNGLVERTEXATTRIBI1IPROC gl3wVertexAttribI1i; -PFNGLVERTEXATTRIBI1IVPROC gl3wVertexAttribI1iv; -PFNGLVERTEXATTRIBI1UIPROC gl3wVertexAttribI1ui; -PFNGLVERTEXATTRIBI1UIVPROC gl3wVertexAttribI1uiv; -PFNGLVERTEXATTRIBI2IPROC gl3wVertexAttribI2i; -PFNGLVERTEXATTRIBI2IVPROC gl3wVertexAttribI2iv; -PFNGLVERTEXATTRIBI2UIPROC gl3wVertexAttribI2ui; -PFNGLVERTEXATTRIBI2UIVPROC gl3wVertexAttribI2uiv; -PFNGLVERTEXATTRIBI3IPROC gl3wVertexAttribI3i; -PFNGLVERTEXATTRIBI3IVPROC gl3wVertexAttribI3iv; -PFNGLVERTEXATTRIBI3UIPROC gl3wVertexAttribI3ui; -PFNGLVERTEXATTRIBI3UIVPROC gl3wVertexAttribI3uiv; -PFNGLVERTEXATTRIBI4BVPROC gl3wVertexAttribI4bv; -PFNGLVERTEXATTRIBI4IPROC gl3wVertexAttribI4i; -PFNGLVERTEXATTRIBI4IVPROC gl3wVertexAttribI4iv; -PFNGLVERTEXATTRIBI4SVPROC gl3wVertexAttribI4sv; -PFNGLVERTEXATTRIBI4UBVPROC gl3wVertexAttribI4ubv; -PFNGLVERTEXATTRIBI4UIPROC gl3wVertexAttribI4ui; -PFNGLVERTEXATTRIBI4UIVPROC gl3wVertexAttribI4uiv; -PFNGLVERTEXATTRIBI4USVPROC gl3wVertexAttribI4usv; -PFNGLVERTEXATTRIBIFORMATPROC gl3wVertexAttribIFormat; -PFNGLVERTEXATTRIBIFORMATNVPROC gl3wVertexAttribIFormatNV; -PFNGLVERTEXATTRIBIPOINTERPROC gl3wVertexAttribIPointer; -PFNGLVERTEXATTRIBL1DPROC gl3wVertexAttribL1d; -PFNGLVERTEXATTRIBL1DVPROC gl3wVertexAttribL1dv; -PFNGLVERTEXATTRIBL1I64NVPROC gl3wVertexAttribL1i64NV; -PFNGLVERTEXATTRIBL1I64VNVPROC gl3wVertexAttribL1i64vNV; -PFNGLVERTEXATTRIBL1UI64ARBPROC gl3wVertexAttribL1ui64ARB; -PFNGLVERTEXATTRIBL1UI64NVPROC gl3wVertexAttribL1ui64NV; -PFNGLVERTEXATTRIBL1UI64VARBPROC gl3wVertexAttribL1ui64vARB; -PFNGLVERTEXATTRIBL1UI64VNVPROC gl3wVertexAttribL1ui64vNV; -PFNGLVERTEXATTRIBL2DPROC gl3wVertexAttribL2d; -PFNGLVERTEXATTRIBL2DVPROC gl3wVertexAttribL2dv; -PFNGLVERTEXATTRIBL2I64NVPROC gl3wVertexAttribL2i64NV; -PFNGLVERTEXATTRIBL2I64VNVPROC gl3wVertexAttribL2i64vNV; -PFNGLVERTEXATTRIBL2UI64NVPROC gl3wVertexAttribL2ui64NV; -PFNGLVERTEXATTRIBL2UI64VNVPROC gl3wVertexAttribL2ui64vNV; -PFNGLVERTEXATTRIBL3DPROC gl3wVertexAttribL3d; -PFNGLVERTEXATTRIBL3DVPROC gl3wVertexAttribL3dv; -PFNGLVERTEXATTRIBL3I64NVPROC gl3wVertexAttribL3i64NV; -PFNGLVERTEXATTRIBL3I64VNVPROC gl3wVertexAttribL3i64vNV; -PFNGLVERTEXATTRIBL3UI64NVPROC gl3wVertexAttribL3ui64NV; -PFNGLVERTEXATTRIBL3UI64VNVPROC gl3wVertexAttribL3ui64vNV; -PFNGLVERTEXATTRIBL4DPROC gl3wVertexAttribL4d; -PFNGLVERTEXATTRIBL4DVPROC gl3wVertexAttribL4dv; -PFNGLVERTEXATTRIBL4I64NVPROC gl3wVertexAttribL4i64NV; -PFNGLVERTEXATTRIBL4I64VNVPROC gl3wVertexAttribL4i64vNV; -PFNGLVERTEXATTRIBL4UI64NVPROC gl3wVertexAttribL4ui64NV; -PFNGLVERTEXATTRIBL4UI64VNVPROC gl3wVertexAttribL4ui64vNV; -PFNGLVERTEXATTRIBLFORMATPROC gl3wVertexAttribLFormat; -PFNGLVERTEXATTRIBLFORMATNVPROC gl3wVertexAttribLFormatNV; -PFNGLVERTEXATTRIBLPOINTERPROC gl3wVertexAttribLPointer; -PFNGLVERTEXATTRIBP1UIPROC gl3wVertexAttribP1ui; -PFNGLVERTEXATTRIBP1UIVPROC gl3wVertexAttribP1uiv; -PFNGLVERTEXATTRIBP2UIPROC gl3wVertexAttribP2ui; -PFNGLVERTEXATTRIBP2UIVPROC gl3wVertexAttribP2uiv; -PFNGLVERTEXATTRIBP3UIPROC gl3wVertexAttribP3ui; -PFNGLVERTEXATTRIBP3UIVPROC gl3wVertexAttribP3uiv; -PFNGLVERTEXATTRIBP4UIPROC gl3wVertexAttribP4ui; -PFNGLVERTEXATTRIBP4UIVPROC gl3wVertexAttribP4uiv; -PFNGLVERTEXATTRIBPOINTERPROC gl3wVertexAttribPointer; -PFNGLVERTEXBINDINGDIVISORPROC gl3wVertexBindingDivisor; -PFNGLVERTEXFORMATNVPROC gl3wVertexFormatNV; -PFNGLVIEWPORTPROC gl3wViewport; -PFNGLVIEWPORTARRAYVPROC gl3wViewportArrayv; -PFNGLVIEWPORTINDEXEDFPROC gl3wViewportIndexedf; -PFNGLVIEWPORTINDEXEDFVPROC gl3wViewportIndexedfv; -PFNGLVIEWPORTPOSITIONWSCALENVPROC gl3wViewportPositionWScaleNV; -PFNGLVIEWPORTSWIZZLENVPROC gl3wViewportSwizzleNV; -PFNGLWAITSYNCPROC gl3wWaitSync; -PFNGLWAITVKSEMAPHORENVPROC gl3wWaitVkSemaphoreNV; -PFNGLWEIGHTPATHSNVPROC gl3wWeightPathsNV; -PFNGLWINDOWRECTANGLESEXTPROC gl3wWindowRectanglesEXT; - -static void load_procs(GL3WGetProcAddressProc proc) -{ - gl3wActiveProgramEXT = (PFNGLACTIVEPROGRAMEXTPROC)proc("glActiveProgramEXT"); - gl3wActiveShaderProgram = (PFNGLACTIVESHADERPROGRAMPROC)proc("glActiveShaderProgram"); - gl3wActiveTexture = (PFNGLACTIVETEXTUREPROC)proc("glActiveTexture"); - gl3wApplyFramebufferAttachmentCMAAINTEL = (PFNGLAPPLYFRAMEBUFFERATTACHMENTCMAAINTELPROC)proc("glApplyFramebufferAttachmentCMAAINTEL"); - gl3wAttachShader = (PFNGLATTACHSHADERPROC)proc("glAttachShader"); - gl3wBeginConditionalRender = (PFNGLBEGINCONDITIONALRENDERPROC)proc("glBeginConditionalRender"); - gl3wBeginConditionalRenderNV = (PFNGLBEGINCONDITIONALRENDERNVPROC)proc("glBeginConditionalRenderNV"); - gl3wBeginPerfMonitorAMD = (PFNGLBEGINPERFMONITORAMDPROC)proc("glBeginPerfMonitorAMD"); - gl3wBeginPerfQueryINTEL = (PFNGLBEGINPERFQUERYINTELPROC)proc("glBeginPerfQueryINTEL"); - gl3wBeginQuery = (PFNGLBEGINQUERYPROC)proc("glBeginQuery"); - gl3wBeginQueryIndexed = (PFNGLBEGINQUERYINDEXEDPROC)proc("glBeginQueryIndexed"); - gl3wBeginTransformFeedback = (PFNGLBEGINTRANSFORMFEEDBACKPROC)proc("glBeginTransformFeedback"); - gl3wBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)proc("glBindAttribLocation"); - gl3wBindBuffer = (PFNGLBINDBUFFERPROC)proc("glBindBuffer"); - gl3wBindBufferBase = (PFNGLBINDBUFFERBASEPROC)proc("glBindBufferBase"); - gl3wBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)proc("glBindBufferRange"); - gl3wBindBuffersBase = (PFNGLBINDBUFFERSBASEPROC)proc("glBindBuffersBase"); - gl3wBindBuffersRange = (PFNGLBINDBUFFERSRANGEPROC)proc("glBindBuffersRange"); - gl3wBindFragDataLocation = (PFNGLBINDFRAGDATALOCATIONPROC)proc("glBindFragDataLocation"); - gl3wBindFragDataLocationIndexed = (PFNGLBINDFRAGDATALOCATIONINDEXEDPROC)proc("glBindFragDataLocationIndexed"); - gl3wBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)proc("glBindFramebuffer"); - gl3wBindImageTexture = (PFNGLBINDIMAGETEXTUREPROC)proc("glBindImageTexture"); - gl3wBindImageTextures = (PFNGLBINDIMAGETEXTURESPROC)proc("glBindImageTextures"); - gl3wBindMultiTextureEXT = (PFNGLBINDMULTITEXTUREEXTPROC)proc("glBindMultiTextureEXT"); - gl3wBindProgramPipeline = (PFNGLBINDPROGRAMPIPELINEPROC)proc("glBindProgramPipeline"); - gl3wBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)proc("glBindRenderbuffer"); - gl3wBindSampler = (PFNGLBINDSAMPLERPROC)proc("glBindSampler"); - gl3wBindSamplers = (PFNGLBINDSAMPLERSPROC)proc("glBindSamplers"); - gl3wBindTexture = (PFNGLBINDTEXTUREPROC)proc("glBindTexture"); - gl3wBindTextureUnit = (PFNGLBINDTEXTUREUNITPROC)proc("glBindTextureUnit"); - gl3wBindTextures = (PFNGLBINDTEXTURESPROC)proc("glBindTextures"); - gl3wBindTransformFeedback = (PFNGLBINDTRANSFORMFEEDBACKPROC)proc("glBindTransformFeedback"); - gl3wBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)proc("glBindVertexArray"); - gl3wBindVertexBuffer = (PFNGLBINDVERTEXBUFFERPROC)proc("glBindVertexBuffer"); - gl3wBindVertexBuffers = (PFNGLBINDVERTEXBUFFERSPROC)proc("glBindVertexBuffers"); - gl3wBlendBarrierKHR = (PFNGLBLENDBARRIERKHRPROC)proc("glBlendBarrierKHR"); - gl3wBlendBarrierNV = (PFNGLBLENDBARRIERNVPROC)proc("glBlendBarrierNV"); - gl3wBlendColor = (PFNGLBLENDCOLORPROC)proc("glBlendColor"); - gl3wBlendEquation = (PFNGLBLENDEQUATIONPROC)proc("glBlendEquation"); - gl3wBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)proc("glBlendEquationSeparate"); - gl3wBlendEquationSeparatei = (PFNGLBLENDEQUATIONSEPARATEIPROC)proc("glBlendEquationSeparatei"); - gl3wBlendEquationSeparateiARB = (PFNGLBLENDEQUATIONSEPARATEIARBPROC)proc("glBlendEquationSeparateiARB"); - gl3wBlendEquationi = (PFNGLBLENDEQUATIONIPROC)proc("glBlendEquationi"); - gl3wBlendEquationiARB = (PFNGLBLENDEQUATIONIARBPROC)proc("glBlendEquationiARB"); - gl3wBlendFunc = (PFNGLBLENDFUNCPROC)proc("glBlendFunc"); - gl3wBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)proc("glBlendFuncSeparate"); - gl3wBlendFuncSeparatei = (PFNGLBLENDFUNCSEPARATEIPROC)proc("glBlendFuncSeparatei"); - gl3wBlendFuncSeparateiARB = (PFNGLBLENDFUNCSEPARATEIARBPROC)proc("glBlendFuncSeparateiARB"); - gl3wBlendFunci = (PFNGLBLENDFUNCIPROC)proc("glBlendFunci"); - gl3wBlendFunciARB = (PFNGLBLENDFUNCIARBPROC)proc("glBlendFunciARB"); - gl3wBlendParameteriNV = (PFNGLBLENDPARAMETERINVPROC)proc("glBlendParameteriNV"); - gl3wBlitFramebuffer = (PFNGLBLITFRAMEBUFFERPROC)proc("glBlitFramebuffer"); - gl3wBlitNamedFramebuffer = (PFNGLBLITNAMEDFRAMEBUFFERPROC)proc("glBlitNamedFramebuffer"); - gl3wBufferAddressRangeNV = (PFNGLBUFFERADDRESSRANGENVPROC)proc("glBufferAddressRangeNV"); - gl3wBufferData = (PFNGLBUFFERDATAPROC)proc("glBufferData"); - gl3wBufferPageCommitmentARB = (PFNGLBUFFERPAGECOMMITMENTARBPROC)proc("glBufferPageCommitmentARB"); - gl3wBufferStorage = (PFNGLBUFFERSTORAGEPROC)proc("glBufferStorage"); - gl3wBufferSubData = (PFNGLBUFFERSUBDATAPROC)proc("glBufferSubData"); - gl3wCallCommandListNV = (PFNGLCALLCOMMANDLISTNVPROC)proc("glCallCommandListNV"); - gl3wCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)proc("glCheckFramebufferStatus"); - gl3wCheckNamedFramebufferStatus = (PFNGLCHECKNAMEDFRAMEBUFFERSTATUSPROC)proc("glCheckNamedFramebufferStatus"); - gl3wCheckNamedFramebufferStatusEXT = (PFNGLCHECKNAMEDFRAMEBUFFERSTATUSEXTPROC)proc("glCheckNamedFramebufferStatusEXT"); - gl3wClampColor = (PFNGLCLAMPCOLORPROC)proc("glClampColor"); - gl3wClear = (PFNGLCLEARPROC)proc("glClear"); - gl3wClearBufferData = (PFNGLCLEARBUFFERDATAPROC)proc("glClearBufferData"); - gl3wClearBufferSubData = (PFNGLCLEARBUFFERSUBDATAPROC)proc("glClearBufferSubData"); - gl3wClearBufferfi = (PFNGLCLEARBUFFERFIPROC)proc("glClearBufferfi"); - gl3wClearBufferfv = (PFNGLCLEARBUFFERFVPROC)proc("glClearBufferfv"); - gl3wClearBufferiv = (PFNGLCLEARBUFFERIVPROC)proc("glClearBufferiv"); - gl3wClearBufferuiv = (PFNGLCLEARBUFFERUIVPROC)proc("glClearBufferuiv"); - gl3wClearColor = (PFNGLCLEARCOLORPROC)proc("glClearColor"); - gl3wClearDepth = (PFNGLCLEARDEPTHPROC)proc("glClearDepth"); - gl3wClearDepthf = (PFNGLCLEARDEPTHFPROC)proc("glClearDepthf"); - gl3wClearNamedBufferData = (PFNGLCLEARNAMEDBUFFERDATAPROC)proc("glClearNamedBufferData"); - gl3wClearNamedBufferDataEXT = (PFNGLCLEARNAMEDBUFFERDATAEXTPROC)proc("glClearNamedBufferDataEXT"); - gl3wClearNamedBufferSubData = (PFNGLCLEARNAMEDBUFFERSUBDATAPROC)proc("glClearNamedBufferSubData"); - gl3wClearNamedBufferSubDataEXT = (PFNGLCLEARNAMEDBUFFERSUBDATAEXTPROC)proc("glClearNamedBufferSubDataEXT"); - gl3wClearNamedFramebufferfi = (PFNGLCLEARNAMEDFRAMEBUFFERFIPROC)proc("glClearNamedFramebufferfi"); - gl3wClearNamedFramebufferfv = (PFNGLCLEARNAMEDFRAMEBUFFERFVPROC)proc("glClearNamedFramebufferfv"); - gl3wClearNamedFramebufferiv = (PFNGLCLEARNAMEDFRAMEBUFFERIVPROC)proc("glClearNamedFramebufferiv"); - gl3wClearNamedFramebufferuiv = (PFNGLCLEARNAMEDFRAMEBUFFERUIVPROC)proc("glClearNamedFramebufferuiv"); - gl3wClearStencil = (PFNGLCLEARSTENCILPROC)proc("glClearStencil"); - gl3wClearTexImage = (PFNGLCLEARTEXIMAGEPROC)proc("glClearTexImage"); - gl3wClearTexSubImage = (PFNGLCLEARTEXSUBIMAGEPROC)proc("glClearTexSubImage"); - gl3wClientAttribDefaultEXT = (PFNGLCLIENTATTRIBDEFAULTEXTPROC)proc("glClientAttribDefaultEXT"); - gl3wClientWaitSync = (PFNGLCLIENTWAITSYNCPROC)proc("glClientWaitSync"); - gl3wClipControl = (PFNGLCLIPCONTROLPROC)proc("glClipControl"); - gl3wColorFormatNV = (PFNGLCOLORFORMATNVPROC)proc("glColorFormatNV"); - gl3wColorMask = (PFNGLCOLORMASKPROC)proc("glColorMask"); - gl3wColorMaski = (PFNGLCOLORMASKIPROC)proc("glColorMaski"); - gl3wCommandListSegmentsNV = (PFNGLCOMMANDLISTSEGMENTSNVPROC)proc("glCommandListSegmentsNV"); - gl3wCompileCommandListNV = (PFNGLCOMPILECOMMANDLISTNVPROC)proc("glCompileCommandListNV"); - gl3wCompileShader = (PFNGLCOMPILESHADERPROC)proc("glCompileShader"); - gl3wCompileShaderIncludeARB = (PFNGLCOMPILESHADERINCLUDEARBPROC)proc("glCompileShaderIncludeARB"); - gl3wCompressedMultiTexImage1DEXT = (PFNGLCOMPRESSEDMULTITEXIMAGE1DEXTPROC)proc("glCompressedMultiTexImage1DEXT"); - gl3wCompressedMultiTexImage2DEXT = (PFNGLCOMPRESSEDMULTITEXIMAGE2DEXTPROC)proc("glCompressedMultiTexImage2DEXT"); - gl3wCompressedMultiTexImage3DEXT = (PFNGLCOMPRESSEDMULTITEXIMAGE3DEXTPROC)proc("glCompressedMultiTexImage3DEXT"); - gl3wCompressedMultiTexSubImage1DEXT = (PFNGLCOMPRESSEDMULTITEXSUBIMAGE1DEXTPROC)proc("glCompressedMultiTexSubImage1DEXT"); - gl3wCompressedMultiTexSubImage2DEXT = (PFNGLCOMPRESSEDMULTITEXSUBIMAGE2DEXTPROC)proc("glCompressedMultiTexSubImage2DEXT"); - gl3wCompressedMultiTexSubImage3DEXT = (PFNGLCOMPRESSEDMULTITEXSUBIMAGE3DEXTPROC)proc("glCompressedMultiTexSubImage3DEXT"); - gl3wCompressedTexImage1D = (PFNGLCOMPRESSEDTEXIMAGE1DPROC)proc("glCompressedTexImage1D"); - gl3wCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)proc("glCompressedTexImage2D"); - gl3wCompressedTexImage3D = (PFNGLCOMPRESSEDTEXIMAGE3DPROC)proc("glCompressedTexImage3D"); - gl3wCompressedTexSubImage1D = (PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)proc("glCompressedTexSubImage1D"); - gl3wCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)proc("glCompressedTexSubImage2D"); - gl3wCompressedTexSubImage3D = (PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)proc("glCompressedTexSubImage3D"); - gl3wCompressedTextureImage1DEXT = (PFNGLCOMPRESSEDTEXTUREIMAGE1DEXTPROC)proc("glCompressedTextureImage1DEXT"); - gl3wCompressedTextureImage2DEXT = (PFNGLCOMPRESSEDTEXTUREIMAGE2DEXTPROC)proc("glCompressedTextureImage2DEXT"); - gl3wCompressedTextureImage3DEXT = (PFNGLCOMPRESSEDTEXTUREIMAGE3DEXTPROC)proc("glCompressedTextureImage3DEXT"); - gl3wCompressedTextureSubImage1D = (PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC)proc("glCompressedTextureSubImage1D"); - gl3wCompressedTextureSubImage1DEXT = (PFNGLCOMPRESSEDTEXTURESUBIMAGE1DEXTPROC)proc("glCompressedTextureSubImage1DEXT"); - gl3wCompressedTextureSubImage2D = (PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC)proc("glCompressedTextureSubImage2D"); - gl3wCompressedTextureSubImage2DEXT = (PFNGLCOMPRESSEDTEXTURESUBIMAGE2DEXTPROC)proc("glCompressedTextureSubImage2DEXT"); - gl3wCompressedTextureSubImage3D = (PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC)proc("glCompressedTextureSubImage3D"); - gl3wCompressedTextureSubImage3DEXT = (PFNGLCOMPRESSEDTEXTURESUBIMAGE3DEXTPROC)proc("glCompressedTextureSubImage3DEXT"); - gl3wConservativeRasterParameterfNV = (PFNGLCONSERVATIVERASTERPARAMETERFNVPROC)proc("glConservativeRasterParameterfNV"); - gl3wConservativeRasterParameteriNV = (PFNGLCONSERVATIVERASTERPARAMETERINVPROC)proc("glConservativeRasterParameteriNV"); - gl3wCopyBufferSubData = (PFNGLCOPYBUFFERSUBDATAPROC)proc("glCopyBufferSubData"); - gl3wCopyImageSubData = (PFNGLCOPYIMAGESUBDATAPROC)proc("glCopyImageSubData"); - gl3wCopyMultiTexImage1DEXT = (PFNGLCOPYMULTITEXIMAGE1DEXTPROC)proc("glCopyMultiTexImage1DEXT"); - gl3wCopyMultiTexImage2DEXT = (PFNGLCOPYMULTITEXIMAGE2DEXTPROC)proc("glCopyMultiTexImage2DEXT"); - gl3wCopyMultiTexSubImage1DEXT = (PFNGLCOPYMULTITEXSUBIMAGE1DEXTPROC)proc("glCopyMultiTexSubImage1DEXT"); - gl3wCopyMultiTexSubImage2DEXT = (PFNGLCOPYMULTITEXSUBIMAGE2DEXTPROC)proc("glCopyMultiTexSubImage2DEXT"); - gl3wCopyMultiTexSubImage3DEXT = (PFNGLCOPYMULTITEXSUBIMAGE3DEXTPROC)proc("glCopyMultiTexSubImage3DEXT"); - gl3wCopyNamedBufferSubData = (PFNGLCOPYNAMEDBUFFERSUBDATAPROC)proc("glCopyNamedBufferSubData"); - gl3wCopyPathNV = (PFNGLCOPYPATHNVPROC)proc("glCopyPathNV"); - gl3wCopyTexImage1D = (PFNGLCOPYTEXIMAGE1DPROC)proc("glCopyTexImage1D"); - gl3wCopyTexImage2D = (PFNGLCOPYTEXIMAGE2DPROC)proc("glCopyTexImage2D"); - gl3wCopyTexSubImage1D = (PFNGLCOPYTEXSUBIMAGE1DPROC)proc("glCopyTexSubImage1D"); - gl3wCopyTexSubImage2D = (PFNGLCOPYTEXSUBIMAGE2DPROC)proc("glCopyTexSubImage2D"); - gl3wCopyTexSubImage3D = (PFNGLCOPYTEXSUBIMAGE3DPROC)proc("glCopyTexSubImage3D"); - gl3wCopyTextureImage1DEXT = (PFNGLCOPYTEXTUREIMAGE1DEXTPROC)proc("glCopyTextureImage1DEXT"); - gl3wCopyTextureImage2DEXT = (PFNGLCOPYTEXTUREIMAGE2DEXTPROC)proc("glCopyTextureImage2DEXT"); - gl3wCopyTextureSubImage1D = (PFNGLCOPYTEXTURESUBIMAGE1DPROC)proc("glCopyTextureSubImage1D"); - gl3wCopyTextureSubImage1DEXT = (PFNGLCOPYTEXTURESUBIMAGE1DEXTPROC)proc("glCopyTextureSubImage1DEXT"); - gl3wCopyTextureSubImage2D = (PFNGLCOPYTEXTURESUBIMAGE2DPROC)proc("glCopyTextureSubImage2D"); - gl3wCopyTextureSubImage2DEXT = (PFNGLCOPYTEXTURESUBIMAGE2DEXTPROC)proc("glCopyTextureSubImage2DEXT"); - gl3wCopyTextureSubImage3D = (PFNGLCOPYTEXTURESUBIMAGE3DPROC)proc("glCopyTextureSubImage3D"); - gl3wCopyTextureSubImage3DEXT = (PFNGLCOPYTEXTURESUBIMAGE3DEXTPROC)proc("glCopyTextureSubImage3DEXT"); - gl3wCoverFillPathInstancedNV = (PFNGLCOVERFILLPATHINSTANCEDNVPROC)proc("glCoverFillPathInstancedNV"); - gl3wCoverFillPathNV = (PFNGLCOVERFILLPATHNVPROC)proc("glCoverFillPathNV"); - gl3wCoverStrokePathInstancedNV = (PFNGLCOVERSTROKEPATHINSTANCEDNVPROC)proc("glCoverStrokePathInstancedNV"); - gl3wCoverStrokePathNV = (PFNGLCOVERSTROKEPATHNVPROC)proc("glCoverStrokePathNV"); - gl3wCoverageModulationNV = (PFNGLCOVERAGEMODULATIONNVPROC)proc("glCoverageModulationNV"); - gl3wCoverageModulationTableNV = (PFNGLCOVERAGEMODULATIONTABLENVPROC)proc("glCoverageModulationTableNV"); - gl3wCreateBuffers = (PFNGLCREATEBUFFERSPROC)proc("glCreateBuffers"); - gl3wCreateCommandListsNV = (PFNGLCREATECOMMANDLISTSNVPROC)proc("glCreateCommandListsNV"); - gl3wCreateFramebuffers = (PFNGLCREATEFRAMEBUFFERSPROC)proc("glCreateFramebuffers"); - gl3wCreatePerfQueryINTEL = (PFNGLCREATEPERFQUERYINTELPROC)proc("glCreatePerfQueryINTEL"); - gl3wCreateProgram = (PFNGLCREATEPROGRAMPROC)proc("glCreateProgram"); - gl3wCreateProgramPipelines = (PFNGLCREATEPROGRAMPIPELINESPROC)proc("glCreateProgramPipelines"); - gl3wCreateQueries = (PFNGLCREATEQUERIESPROC)proc("glCreateQueries"); - gl3wCreateRenderbuffers = (PFNGLCREATERENDERBUFFERSPROC)proc("glCreateRenderbuffers"); - gl3wCreateSamplers = (PFNGLCREATESAMPLERSPROC)proc("glCreateSamplers"); - gl3wCreateShader = (PFNGLCREATESHADERPROC)proc("glCreateShader"); - gl3wCreateShaderProgramEXT = (PFNGLCREATESHADERPROGRAMEXTPROC)proc("glCreateShaderProgramEXT"); - gl3wCreateShaderProgramv = (PFNGLCREATESHADERPROGRAMVPROC)proc("glCreateShaderProgramv"); - gl3wCreateStatesNV = (PFNGLCREATESTATESNVPROC)proc("glCreateStatesNV"); - gl3wCreateSyncFromCLeventARB = (PFNGLCREATESYNCFROMCLEVENTARBPROC)proc("glCreateSyncFromCLeventARB"); - gl3wCreateTextures = (PFNGLCREATETEXTURESPROC)proc("glCreateTextures"); - gl3wCreateTransformFeedbacks = (PFNGLCREATETRANSFORMFEEDBACKSPROC)proc("glCreateTransformFeedbacks"); - gl3wCreateVertexArrays = (PFNGLCREATEVERTEXARRAYSPROC)proc("glCreateVertexArrays"); - gl3wCullFace = (PFNGLCULLFACEPROC)proc("glCullFace"); - gl3wDebugMessageCallback = (PFNGLDEBUGMESSAGECALLBACKPROC)proc("glDebugMessageCallback"); - gl3wDebugMessageCallbackARB = (PFNGLDEBUGMESSAGECALLBACKARBPROC)proc("glDebugMessageCallbackARB"); - gl3wDebugMessageControl = (PFNGLDEBUGMESSAGECONTROLPROC)proc("glDebugMessageControl"); - gl3wDebugMessageControlARB = (PFNGLDEBUGMESSAGECONTROLARBPROC)proc("glDebugMessageControlARB"); - gl3wDebugMessageInsert = (PFNGLDEBUGMESSAGEINSERTPROC)proc("glDebugMessageInsert"); - gl3wDebugMessageInsertARB = (PFNGLDEBUGMESSAGEINSERTARBPROC)proc("glDebugMessageInsertARB"); - gl3wDeleteBuffers = (PFNGLDELETEBUFFERSPROC)proc("glDeleteBuffers"); - gl3wDeleteCommandListsNV = (PFNGLDELETECOMMANDLISTSNVPROC)proc("glDeleteCommandListsNV"); - gl3wDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)proc("glDeleteFramebuffers"); - gl3wDeleteNamedStringARB = (PFNGLDELETENAMEDSTRINGARBPROC)proc("glDeleteNamedStringARB"); - gl3wDeletePathsNV = (PFNGLDELETEPATHSNVPROC)proc("glDeletePathsNV"); - gl3wDeletePerfMonitorsAMD = (PFNGLDELETEPERFMONITORSAMDPROC)proc("glDeletePerfMonitorsAMD"); - gl3wDeletePerfQueryINTEL = (PFNGLDELETEPERFQUERYINTELPROC)proc("glDeletePerfQueryINTEL"); - gl3wDeleteProgram = (PFNGLDELETEPROGRAMPROC)proc("glDeleteProgram"); - gl3wDeleteProgramPipelines = (PFNGLDELETEPROGRAMPIPELINESPROC)proc("glDeleteProgramPipelines"); - gl3wDeleteQueries = (PFNGLDELETEQUERIESPROC)proc("glDeleteQueries"); - gl3wDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)proc("glDeleteRenderbuffers"); - gl3wDeleteSamplers = (PFNGLDELETESAMPLERSPROC)proc("glDeleteSamplers"); - gl3wDeleteShader = (PFNGLDELETESHADERPROC)proc("glDeleteShader"); - gl3wDeleteStatesNV = (PFNGLDELETESTATESNVPROC)proc("glDeleteStatesNV"); - gl3wDeleteSync = (PFNGLDELETESYNCPROC)proc("glDeleteSync"); - gl3wDeleteTextures = (PFNGLDELETETEXTURESPROC)proc("glDeleteTextures"); - gl3wDeleteTransformFeedbacks = (PFNGLDELETETRANSFORMFEEDBACKSPROC)proc("glDeleteTransformFeedbacks"); - gl3wDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)proc("glDeleteVertexArrays"); - gl3wDepthFunc = (PFNGLDEPTHFUNCPROC)proc("glDepthFunc"); - gl3wDepthMask = (PFNGLDEPTHMASKPROC)proc("glDepthMask"); - gl3wDepthRange = (PFNGLDEPTHRANGEPROC)proc("glDepthRange"); - gl3wDepthRangeArrayv = (PFNGLDEPTHRANGEARRAYVPROC)proc("glDepthRangeArrayv"); - gl3wDepthRangeIndexed = (PFNGLDEPTHRANGEINDEXEDPROC)proc("glDepthRangeIndexed"); - gl3wDepthRangef = (PFNGLDEPTHRANGEFPROC)proc("glDepthRangef"); - gl3wDetachShader = (PFNGLDETACHSHADERPROC)proc("glDetachShader"); - gl3wDisable = (PFNGLDISABLEPROC)proc("glDisable"); - gl3wDisableClientStateIndexedEXT = (PFNGLDISABLECLIENTSTATEINDEXEDEXTPROC)proc("glDisableClientStateIndexedEXT"); - gl3wDisableClientStateiEXT = (PFNGLDISABLECLIENTSTATEIEXTPROC)proc("glDisableClientStateiEXT"); - gl3wDisableIndexedEXT = (PFNGLDISABLEINDEXEDEXTPROC)proc("glDisableIndexedEXT"); - gl3wDisableVertexArrayAttrib = (PFNGLDISABLEVERTEXARRAYATTRIBPROC)proc("glDisableVertexArrayAttrib"); - gl3wDisableVertexArrayAttribEXT = (PFNGLDISABLEVERTEXARRAYATTRIBEXTPROC)proc("glDisableVertexArrayAttribEXT"); - gl3wDisableVertexArrayEXT = (PFNGLDISABLEVERTEXARRAYEXTPROC)proc("glDisableVertexArrayEXT"); - gl3wDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)proc("glDisableVertexAttribArray"); - gl3wDisablei = (PFNGLDISABLEIPROC)proc("glDisablei"); - gl3wDispatchCompute = (PFNGLDISPATCHCOMPUTEPROC)proc("glDispatchCompute"); - gl3wDispatchComputeGroupSizeARB = (PFNGLDISPATCHCOMPUTEGROUPSIZEARBPROC)proc("glDispatchComputeGroupSizeARB"); - gl3wDispatchComputeIndirect = (PFNGLDISPATCHCOMPUTEINDIRECTPROC)proc("glDispatchComputeIndirect"); - gl3wDrawArrays = (PFNGLDRAWARRAYSPROC)proc("glDrawArrays"); - gl3wDrawArraysIndirect = (PFNGLDRAWARRAYSINDIRECTPROC)proc("glDrawArraysIndirect"); - gl3wDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDPROC)proc("glDrawArraysInstanced"); - gl3wDrawArraysInstancedARB = (PFNGLDRAWARRAYSINSTANCEDARBPROC)proc("glDrawArraysInstancedARB"); - gl3wDrawArraysInstancedBaseInstance = (PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC)proc("glDrawArraysInstancedBaseInstance"); - gl3wDrawArraysInstancedEXT = (PFNGLDRAWARRAYSINSTANCEDEXTPROC)proc("glDrawArraysInstancedEXT"); - gl3wDrawBuffer = (PFNGLDRAWBUFFERPROC)proc("glDrawBuffer"); - gl3wDrawBuffers = (PFNGLDRAWBUFFERSPROC)proc("glDrawBuffers"); - gl3wDrawCommandsAddressNV = (PFNGLDRAWCOMMANDSADDRESSNVPROC)proc("glDrawCommandsAddressNV"); - gl3wDrawCommandsNV = (PFNGLDRAWCOMMANDSNVPROC)proc("glDrawCommandsNV"); - gl3wDrawCommandsStatesAddressNV = (PFNGLDRAWCOMMANDSSTATESADDRESSNVPROC)proc("glDrawCommandsStatesAddressNV"); - gl3wDrawCommandsStatesNV = (PFNGLDRAWCOMMANDSSTATESNVPROC)proc("glDrawCommandsStatesNV"); - gl3wDrawElements = (PFNGLDRAWELEMENTSPROC)proc("glDrawElements"); - gl3wDrawElementsBaseVertex = (PFNGLDRAWELEMENTSBASEVERTEXPROC)proc("glDrawElementsBaseVertex"); - gl3wDrawElementsIndirect = (PFNGLDRAWELEMENTSINDIRECTPROC)proc("glDrawElementsIndirect"); - gl3wDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDPROC)proc("glDrawElementsInstanced"); - gl3wDrawElementsInstancedARB = (PFNGLDRAWELEMENTSINSTANCEDARBPROC)proc("glDrawElementsInstancedARB"); - gl3wDrawElementsInstancedBaseInstance = (PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC)proc("glDrawElementsInstancedBaseInstance"); - gl3wDrawElementsInstancedBaseVertex = (PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)proc("glDrawElementsInstancedBaseVertex"); - gl3wDrawElementsInstancedBaseVertexBaseInstance = (PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC)proc("glDrawElementsInstancedBaseVertexBaseInstance"); - gl3wDrawElementsInstancedEXT = (PFNGLDRAWELEMENTSINSTANCEDEXTPROC)proc("glDrawElementsInstancedEXT"); - gl3wDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC)proc("glDrawRangeElements"); - gl3wDrawRangeElementsBaseVertex = (PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)proc("glDrawRangeElementsBaseVertex"); - gl3wDrawTransformFeedback = (PFNGLDRAWTRANSFORMFEEDBACKPROC)proc("glDrawTransformFeedback"); - gl3wDrawTransformFeedbackInstanced = (PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC)proc("glDrawTransformFeedbackInstanced"); - gl3wDrawTransformFeedbackStream = (PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC)proc("glDrawTransformFeedbackStream"); - gl3wDrawTransformFeedbackStreamInstanced = (PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC)proc("glDrawTransformFeedbackStreamInstanced"); - gl3wDrawVkImageNV = (PFNGLDRAWVKIMAGENVPROC)proc("glDrawVkImageNV"); - gl3wEdgeFlagFormatNV = (PFNGLEDGEFLAGFORMATNVPROC)proc("glEdgeFlagFormatNV"); - gl3wEnable = (PFNGLENABLEPROC)proc("glEnable"); - gl3wEnableClientStateIndexedEXT = (PFNGLENABLECLIENTSTATEINDEXEDEXTPROC)proc("glEnableClientStateIndexedEXT"); - gl3wEnableClientStateiEXT = (PFNGLENABLECLIENTSTATEIEXTPROC)proc("glEnableClientStateiEXT"); - gl3wEnableIndexedEXT = (PFNGLENABLEINDEXEDEXTPROC)proc("glEnableIndexedEXT"); - gl3wEnableVertexArrayAttrib = (PFNGLENABLEVERTEXARRAYATTRIBPROC)proc("glEnableVertexArrayAttrib"); - gl3wEnableVertexArrayAttribEXT = (PFNGLENABLEVERTEXARRAYATTRIBEXTPROC)proc("glEnableVertexArrayAttribEXT"); - gl3wEnableVertexArrayEXT = (PFNGLENABLEVERTEXARRAYEXTPROC)proc("glEnableVertexArrayEXT"); - gl3wEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)proc("glEnableVertexAttribArray"); - gl3wEnablei = (PFNGLENABLEIPROC)proc("glEnablei"); - gl3wEndConditionalRender = (PFNGLENDCONDITIONALRENDERPROC)proc("glEndConditionalRender"); - gl3wEndConditionalRenderNV = (PFNGLENDCONDITIONALRENDERNVPROC)proc("glEndConditionalRenderNV"); - gl3wEndPerfMonitorAMD = (PFNGLENDPERFMONITORAMDPROC)proc("glEndPerfMonitorAMD"); - gl3wEndPerfQueryINTEL = (PFNGLENDPERFQUERYINTELPROC)proc("glEndPerfQueryINTEL"); - gl3wEndQuery = (PFNGLENDQUERYPROC)proc("glEndQuery"); - gl3wEndQueryIndexed = (PFNGLENDQUERYINDEXEDPROC)proc("glEndQueryIndexed"); - gl3wEndTransformFeedback = (PFNGLENDTRANSFORMFEEDBACKPROC)proc("glEndTransformFeedback"); - gl3wEvaluateDepthValuesARB = (PFNGLEVALUATEDEPTHVALUESARBPROC)proc("glEvaluateDepthValuesARB"); - gl3wFenceSync = (PFNGLFENCESYNCPROC)proc("glFenceSync"); - gl3wFinish = (PFNGLFINISHPROC)proc("glFinish"); - gl3wFlush = (PFNGLFLUSHPROC)proc("glFlush"); - gl3wFlushMappedBufferRange = (PFNGLFLUSHMAPPEDBUFFERRANGEPROC)proc("glFlushMappedBufferRange"); - gl3wFlushMappedNamedBufferRange = (PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEPROC)proc("glFlushMappedNamedBufferRange"); - gl3wFlushMappedNamedBufferRangeEXT = (PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEEXTPROC)proc("glFlushMappedNamedBufferRangeEXT"); - gl3wFogCoordFormatNV = (PFNGLFOGCOORDFORMATNVPROC)proc("glFogCoordFormatNV"); - gl3wFragmentCoverageColorNV = (PFNGLFRAGMENTCOVERAGECOLORNVPROC)proc("glFragmentCoverageColorNV"); - gl3wFramebufferDrawBufferEXT = (PFNGLFRAMEBUFFERDRAWBUFFEREXTPROC)proc("glFramebufferDrawBufferEXT"); - gl3wFramebufferDrawBuffersEXT = (PFNGLFRAMEBUFFERDRAWBUFFERSEXTPROC)proc("glFramebufferDrawBuffersEXT"); - gl3wFramebufferParameteri = (PFNGLFRAMEBUFFERPARAMETERIPROC)proc("glFramebufferParameteri"); - gl3wFramebufferReadBufferEXT = (PFNGLFRAMEBUFFERREADBUFFEREXTPROC)proc("glFramebufferReadBufferEXT"); - gl3wFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)proc("glFramebufferRenderbuffer"); - gl3wFramebufferSampleLocationsfvARB = (PFNGLFRAMEBUFFERSAMPLELOCATIONSFVARBPROC)proc("glFramebufferSampleLocationsfvARB"); - gl3wFramebufferSampleLocationsfvNV = (PFNGLFRAMEBUFFERSAMPLELOCATIONSFVNVPROC)proc("glFramebufferSampleLocationsfvNV"); - gl3wFramebufferTexture = (PFNGLFRAMEBUFFERTEXTUREPROC)proc("glFramebufferTexture"); - gl3wFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC)proc("glFramebufferTexture1D"); - gl3wFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)proc("glFramebufferTexture2D"); - gl3wFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC)proc("glFramebufferTexture3D"); - gl3wFramebufferTextureARB = (PFNGLFRAMEBUFFERTEXTUREARBPROC)proc("glFramebufferTextureARB"); - gl3wFramebufferTextureFaceARB = (PFNGLFRAMEBUFFERTEXTUREFACEARBPROC)proc("glFramebufferTextureFaceARB"); - gl3wFramebufferTextureLayer = (PFNGLFRAMEBUFFERTEXTURELAYERPROC)proc("glFramebufferTextureLayer"); - gl3wFramebufferTextureLayerARB = (PFNGLFRAMEBUFFERTEXTURELAYERARBPROC)proc("glFramebufferTextureLayerARB"); - gl3wFramebufferTextureMultiviewOVR = (PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC)proc("glFramebufferTextureMultiviewOVR"); - gl3wFrontFace = (PFNGLFRONTFACEPROC)proc("glFrontFace"); - gl3wGenBuffers = (PFNGLGENBUFFERSPROC)proc("glGenBuffers"); - gl3wGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)proc("glGenFramebuffers"); - gl3wGenPathsNV = (PFNGLGENPATHSNVPROC)proc("glGenPathsNV"); - gl3wGenPerfMonitorsAMD = (PFNGLGENPERFMONITORSAMDPROC)proc("glGenPerfMonitorsAMD"); - gl3wGenProgramPipelines = (PFNGLGENPROGRAMPIPELINESPROC)proc("glGenProgramPipelines"); - gl3wGenQueries = (PFNGLGENQUERIESPROC)proc("glGenQueries"); - gl3wGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)proc("glGenRenderbuffers"); - gl3wGenSamplers = (PFNGLGENSAMPLERSPROC)proc("glGenSamplers"); - gl3wGenTextures = (PFNGLGENTEXTURESPROC)proc("glGenTextures"); - gl3wGenTransformFeedbacks = (PFNGLGENTRANSFORMFEEDBACKSPROC)proc("glGenTransformFeedbacks"); - gl3wGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)proc("glGenVertexArrays"); - gl3wGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)proc("glGenerateMipmap"); - gl3wGenerateMultiTexMipmapEXT = (PFNGLGENERATEMULTITEXMIPMAPEXTPROC)proc("glGenerateMultiTexMipmapEXT"); - gl3wGenerateTextureMipmap = (PFNGLGENERATETEXTUREMIPMAPPROC)proc("glGenerateTextureMipmap"); - gl3wGenerateTextureMipmapEXT = (PFNGLGENERATETEXTUREMIPMAPEXTPROC)proc("glGenerateTextureMipmapEXT"); - gl3wGetActiveAtomicCounterBufferiv = (PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC)proc("glGetActiveAtomicCounterBufferiv"); - gl3wGetActiveAttrib = (PFNGLGETACTIVEATTRIBPROC)proc("glGetActiveAttrib"); - gl3wGetActiveSubroutineName = (PFNGLGETACTIVESUBROUTINENAMEPROC)proc("glGetActiveSubroutineName"); - gl3wGetActiveSubroutineUniformName = (PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC)proc("glGetActiveSubroutineUniformName"); - gl3wGetActiveSubroutineUniformiv = (PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC)proc("glGetActiveSubroutineUniformiv"); - gl3wGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)proc("glGetActiveUniform"); - gl3wGetActiveUniformBlockName = (PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)proc("glGetActiveUniformBlockName"); - gl3wGetActiveUniformBlockiv = (PFNGLGETACTIVEUNIFORMBLOCKIVPROC)proc("glGetActiveUniformBlockiv"); - gl3wGetActiveUniformName = (PFNGLGETACTIVEUNIFORMNAMEPROC)proc("glGetActiveUniformName"); - gl3wGetActiveUniformsiv = (PFNGLGETACTIVEUNIFORMSIVPROC)proc("glGetActiveUniformsiv"); - gl3wGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC)proc("glGetAttachedShaders"); - gl3wGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)proc("glGetAttribLocation"); - gl3wGetBooleanIndexedvEXT = (PFNGLGETBOOLEANINDEXEDVEXTPROC)proc("glGetBooleanIndexedvEXT"); - gl3wGetBooleani_v = (PFNGLGETBOOLEANI_VPROC)proc("glGetBooleani_v"); - gl3wGetBooleanv = (PFNGLGETBOOLEANVPROC)proc("glGetBooleanv"); - gl3wGetBufferParameteri64v = (PFNGLGETBUFFERPARAMETERI64VPROC)proc("glGetBufferParameteri64v"); - gl3wGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVPROC)proc("glGetBufferParameteriv"); - gl3wGetBufferParameterui64vNV = (PFNGLGETBUFFERPARAMETERUI64VNVPROC)proc("glGetBufferParameterui64vNV"); - gl3wGetBufferPointerv = (PFNGLGETBUFFERPOINTERVPROC)proc("glGetBufferPointerv"); - gl3wGetBufferSubData = (PFNGLGETBUFFERSUBDATAPROC)proc("glGetBufferSubData"); - gl3wGetCommandHeaderNV = (PFNGLGETCOMMANDHEADERNVPROC)proc("glGetCommandHeaderNV"); - gl3wGetCompressedMultiTexImageEXT = (PFNGLGETCOMPRESSEDMULTITEXIMAGEEXTPROC)proc("glGetCompressedMultiTexImageEXT"); - gl3wGetCompressedTexImage = (PFNGLGETCOMPRESSEDTEXIMAGEPROC)proc("glGetCompressedTexImage"); - gl3wGetCompressedTextureImage = (PFNGLGETCOMPRESSEDTEXTUREIMAGEPROC)proc("glGetCompressedTextureImage"); - gl3wGetCompressedTextureImageEXT = (PFNGLGETCOMPRESSEDTEXTUREIMAGEEXTPROC)proc("glGetCompressedTextureImageEXT"); - gl3wGetCompressedTextureSubImage = (PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC)proc("glGetCompressedTextureSubImage"); - gl3wGetCoverageModulationTableNV = (PFNGLGETCOVERAGEMODULATIONTABLENVPROC)proc("glGetCoverageModulationTableNV"); - gl3wGetDebugMessageLog = (PFNGLGETDEBUGMESSAGELOGPROC)proc("glGetDebugMessageLog"); - gl3wGetDebugMessageLogARB = (PFNGLGETDEBUGMESSAGELOGARBPROC)proc("glGetDebugMessageLogARB"); - gl3wGetDoubleIndexedvEXT = (PFNGLGETDOUBLEINDEXEDVEXTPROC)proc("glGetDoubleIndexedvEXT"); - gl3wGetDoublei_v = (PFNGLGETDOUBLEI_VPROC)proc("glGetDoublei_v"); - gl3wGetDoublei_vEXT = (PFNGLGETDOUBLEI_VEXTPROC)proc("glGetDoublei_vEXT"); - gl3wGetDoublev = (PFNGLGETDOUBLEVPROC)proc("glGetDoublev"); - gl3wGetError = (PFNGLGETERRORPROC)proc("glGetError"); - gl3wGetFirstPerfQueryIdINTEL = (PFNGLGETFIRSTPERFQUERYIDINTELPROC)proc("glGetFirstPerfQueryIdINTEL"); - gl3wGetFloatIndexedvEXT = (PFNGLGETFLOATINDEXEDVEXTPROC)proc("glGetFloatIndexedvEXT"); - gl3wGetFloati_v = (PFNGLGETFLOATI_VPROC)proc("glGetFloati_v"); - gl3wGetFloati_vEXT = (PFNGLGETFLOATI_VEXTPROC)proc("glGetFloati_vEXT"); - gl3wGetFloatv = (PFNGLGETFLOATVPROC)proc("glGetFloatv"); - gl3wGetFragDataIndex = (PFNGLGETFRAGDATAINDEXPROC)proc("glGetFragDataIndex"); - gl3wGetFragDataLocation = (PFNGLGETFRAGDATALOCATIONPROC)proc("glGetFragDataLocation"); - gl3wGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)proc("glGetFramebufferAttachmentParameteriv"); - gl3wGetFramebufferParameteriv = (PFNGLGETFRAMEBUFFERPARAMETERIVPROC)proc("glGetFramebufferParameteriv"); - gl3wGetFramebufferParameterivEXT = (PFNGLGETFRAMEBUFFERPARAMETERIVEXTPROC)proc("glGetFramebufferParameterivEXT"); - gl3wGetGraphicsResetStatus = (PFNGLGETGRAPHICSRESETSTATUSPROC)proc("glGetGraphicsResetStatus"); - gl3wGetGraphicsResetStatusARB = (PFNGLGETGRAPHICSRESETSTATUSARBPROC)proc("glGetGraphicsResetStatusARB"); - gl3wGetImageHandleARB = (PFNGLGETIMAGEHANDLEARBPROC)proc("glGetImageHandleARB"); - gl3wGetImageHandleNV = (PFNGLGETIMAGEHANDLENVPROC)proc("glGetImageHandleNV"); - gl3wGetInteger64i_v = (PFNGLGETINTEGER64I_VPROC)proc("glGetInteger64i_v"); - gl3wGetInteger64v = (PFNGLGETINTEGER64VPROC)proc("glGetInteger64v"); - gl3wGetIntegerIndexedvEXT = (PFNGLGETINTEGERINDEXEDVEXTPROC)proc("glGetIntegerIndexedvEXT"); - gl3wGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)proc("glGetIntegeri_v"); - gl3wGetIntegerui64i_vNV = (PFNGLGETINTEGERUI64I_VNVPROC)proc("glGetIntegerui64i_vNV"); - gl3wGetIntegerui64vNV = (PFNGLGETINTEGERUI64VNVPROC)proc("glGetIntegerui64vNV"); - gl3wGetIntegerv = (PFNGLGETINTEGERVPROC)proc("glGetIntegerv"); - gl3wGetInternalformatSampleivNV = (PFNGLGETINTERNALFORMATSAMPLEIVNVPROC)proc("glGetInternalformatSampleivNV"); - gl3wGetInternalformati64v = (PFNGLGETINTERNALFORMATI64VPROC)proc("glGetInternalformati64v"); - gl3wGetInternalformativ = (PFNGLGETINTERNALFORMATIVPROC)proc("glGetInternalformativ"); - gl3wGetMultiTexEnvfvEXT = (PFNGLGETMULTITEXENVFVEXTPROC)proc("glGetMultiTexEnvfvEXT"); - gl3wGetMultiTexEnvivEXT = (PFNGLGETMULTITEXENVIVEXTPROC)proc("glGetMultiTexEnvivEXT"); - gl3wGetMultiTexGendvEXT = (PFNGLGETMULTITEXGENDVEXTPROC)proc("glGetMultiTexGendvEXT"); - gl3wGetMultiTexGenfvEXT = (PFNGLGETMULTITEXGENFVEXTPROC)proc("glGetMultiTexGenfvEXT"); - gl3wGetMultiTexGenivEXT = (PFNGLGETMULTITEXGENIVEXTPROC)proc("glGetMultiTexGenivEXT"); - gl3wGetMultiTexImageEXT = (PFNGLGETMULTITEXIMAGEEXTPROC)proc("glGetMultiTexImageEXT"); - gl3wGetMultiTexLevelParameterfvEXT = (PFNGLGETMULTITEXLEVELPARAMETERFVEXTPROC)proc("glGetMultiTexLevelParameterfvEXT"); - gl3wGetMultiTexLevelParameterivEXT = (PFNGLGETMULTITEXLEVELPARAMETERIVEXTPROC)proc("glGetMultiTexLevelParameterivEXT"); - gl3wGetMultiTexParameterIivEXT = (PFNGLGETMULTITEXPARAMETERIIVEXTPROC)proc("glGetMultiTexParameterIivEXT"); - gl3wGetMultiTexParameterIuivEXT = (PFNGLGETMULTITEXPARAMETERIUIVEXTPROC)proc("glGetMultiTexParameterIuivEXT"); - gl3wGetMultiTexParameterfvEXT = (PFNGLGETMULTITEXPARAMETERFVEXTPROC)proc("glGetMultiTexParameterfvEXT"); - gl3wGetMultiTexParameterivEXT = (PFNGLGETMULTITEXPARAMETERIVEXTPROC)proc("glGetMultiTexParameterivEXT"); - gl3wGetMultisamplefv = (PFNGLGETMULTISAMPLEFVPROC)proc("glGetMultisamplefv"); - gl3wGetNamedBufferParameteri64v = (PFNGLGETNAMEDBUFFERPARAMETERI64VPROC)proc("glGetNamedBufferParameteri64v"); - gl3wGetNamedBufferParameteriv = (PFNGLGETNAMEDBUFFERPARAMETERIVPROC)proc("glGetNamedBufferParameteriv"); - gl3wGetNamedBufferParameterivEXT = (PFNGLGETNAMEDBUFFERPARAMETERIVEXTPROC)proc("glGetNamedBufferParameterivEXT"); - gl3wGetNamedBufferParameterui64vNV = (PFNGLGETNAMEDBUFFERPARAMETERUI64VNVPROC)proc("glGetNamedBufferParameterui64vNV"); - gl3wGetNamedBufferPointerv = (PFNGLGETNAMEDBUFFERPOINTERVPROC)proc("glGetNamedBufferPointerv"); - gl3wGetNamedBufferPointervEXT = (PFNGLGETNAMEDBUFFERPOINTERVEXTPROC)proc("glGetNamedBufferPointervEXT"); - gl3wGetNamedBufferSubData = (PFNGLGETNAMEDBUFFERSUBDATAPROC)proc("glGetNamedBufferSubData"); - gl3wGetNamedBufferSubDataEXT = (PFNGLGETNAMEDBUFFERSUBDATAEXTPROC)proc("glGetNamedBufferSubDataEXT"); - gl3wGetNamedFramebufferAttachmentParameteriv = (PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC)proc("glGetNamedFramebufferAttachmentParameteriv"); - gl3wGetNamedFramebufferAttachmentParameterivEXT = (PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC)proc("glGetNamedFramebufferAttachmentParameterivEXT"); - gl3wGetNamedFramebufferParameteriv = (PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVPROC)proc("glGetNamedFramebufferParameteriv"); - gl3wGetNamedFramebufferParameterivEXT = (PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVEXTPROC)proc("glGetNamedFramebufferParameterivEXT"); - gl3wGetNamedProgramLocalParameterIivEXT = (PFNGLGETNAMEDPROGRAMLOCALPARAMETERIIVEXTPROC)proc("glGetNamedProgramLocalParameterIivEXT"); - gl3wGetNamedProgramLocalParameterIuivEXT = (PFNGLGETNAMEDPROGRAMLOCALPARAMETERIUIVEXTPROC)proc("glGetNamedProgramLocalParameterIuivEXT"); - gl3wGetNamedProgramLocalParameterdvEXT = (PFNGLGETNAMEDPROGRAMLOCALPARAMETERDVEXTPROC)proc("glGetNamedProgramLocalParameterdvEXT"); - gl3wGetNamedProgramLocalParameterfvEXT = (PFNGLGETNAMEDPROGRAMLOCALPARAMETERFVEXTPROC)proc("glGetNamedProgramLocalParameterfvEXT"); - gl3wGetNamedProgramStringEXT = (PFNGLGETNAMEDPROGRAMSTRINGEXTPROC)proc("glGetNamedProgramStringEXT"); - gl3wGetNamedProgramivEXT = (PFNGLGETNAMEDPROGRAMIVEXTPROC)proc("glGetNamedProgramivEXT"); - gl3wGetNamedRenderbufferParameteriv = (PFNGLGETNAMEDRENDERBUFFERPARAMETERIVPROC)proc("glGetNamedRenderbufferParameteriv"); - gl3wGetNamedRenderbufferParameterivEXT = (PFNGLGETNAMEDRENDERBUFFERPARAMETERIVEXTPROC)proc("glGetNamedRenderbufferParameterivEXT"); - gl3wGetNamedStringARB = (PFNGLGETNAMEDSTRINGARBPROC)proc("glGetNamedStringARB"); - gl3wGetNamedStringivARB = (PFNGLGETNAMEDSTRINGIVARBPROC)proc("glGetNamedStringivARB"); - gl3wGetNextPerfQueryIdINTEL = (PFNGLGETNEXTPERFQUERYIDINTELPROC)proc("glGetNextPerfQueryIdINTEL"); - gl3wGetObjectLabel = (PFNGLGETOBJECTLABELPROC)proc("glGetObjectLabel"); - gl3wGetObjectLabelEXT = (PFNGLGETOBJECTLABELEXTPROC)proc("glGetObjectLabelEXT"); - gl3wGetObjectPtrLabel = (PFNGLGETOBJECTPTRLABELPROC)proc("glGetObjectPtrLabel"); - gl3wGetPathCommandsNV = (PFNGLGETPATHCOMMANDSNVPROC)proc("glGetPathCommandsNV"); - gl3wGetPathCoordsNV = (PFNGLGETPATHCOORDSNVPROC)proc("glGetPathCoordsNV"); - gl3wGetPathDashArrayNV = (PFNGLGETPATHDASHARRAYNVPROC)proc("glGetPathDashArrayNV"); - gl3wGetPathLengthNV = (PFNGLGETPATHLENGTHNVPROC)proc("glGetPathLengthNV"); - gl3wGetPathMetricRangeNV = (PFNGLGETPATHMETRICRANGENVPROC)proc("glGetPathMetricRangeNV"); - gl3wGetPathMetricsNV = (PFNGLGETPATHMETRICSNVPROC)proc("glGetPathMetricsNV"); - gl3wGetPathParameterfvNV = (PFNGLGETPATHPARAMETERFVNVPROC)proc("glGetPathParameterfvNV"); - gl3wGetPathParameterivNV = (PFNGLGETPATHPARAMETERIVNVPROC)proc("glGetPathParameterivNV"); - gl3wGetPathSpacingNV = (PFNGLGETPATHSPACINGNVPROC)proc("glGetPathSpacingNV"); - gl3wGetPerfCounterInfoINTEL = (PFNGLGETPERFCOUNTERINFOINTELPROC)proc("glGetPerfCounterInfoINTEL"); - gl3wGetPerfMonitorCounterDataAMD = (PFNGLGETPERFMONITORCOUNTERDATAAMDPROC)proc("glGetPerfMonitorCounterDataAMD"); - gl3wGetPerfMonitorCounterInfoAMD = (PFNGLGETPERFMONITORCOUNTERINFOAMDPROC)proc("glGetPerfMonitorCounterInfoAMD"); - gl3wGetPerfMonitorCounterStringAMD = (PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC)proc("glGetPerfMonitorCounterStringAMD"); - gl3wGetPerfMonitorCountersAMD = (PFNGLGETPERFMONITORCOUNTERSAMDPROC)proc("glGetPerfMonitorCountersAMD"); - gl3wGetPerfMonitorGroupStringAMD = (PFNGLGETPERFMONITORGROUPSTRINGAMDPROC)proc("glGetPerfMonitorGroupStringAMD"); - gl3wGetPerfMonitorGroupsAMD = (PFNGLGETPERFMONITORGROUPSAMDPROC)proc("glGetPerfMonitorGroupsAMD"); - gl3wGetPerfQueryDataINTEL = (PFNGLGETPERFQUERYDATAINTELPROC)proc("glGetPerfQueryDataINTEL"); - gl3wGetPerfQueryIdByNameINTEL = (PFNGLGETPERFQUERYIDBYNAMEINTELPROC)proc("glGetPerfQueryIdByNameINTEL"); - gl3wGetPerfQueryInfoINTEL = (PFNGLGETPERFQUERYINFOINTELPROC)proc("glGetPerfQueryInfoINTEL"); - gl3wGetPointerIndexedvEXT = (PFNGLGETPOINTERINDEXEDVEXTPROC)proc("glGetPointerIndexedvEXT"); - gl3wGetPointeri_vEXT = (PFNGLGETPOINTERI_VEXTPROC)proc("glGetPointeri_vEXT"); - gl3wGetPointerv = (PFNGLGETPOINTERVPROC)proc("glGetPointerv"); - gl3wGetProgramBinary = (PFNGLGETPROGRAMBINARYPROC)proc("glGetProgramBinary"); - gl3wGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)proc("glGetProgramInfoLog"); - gl3wGetProgramInterfaceiv = (PFNGLGETPROGRAMINTERFACEIVPROC)proc("glGetProgramInterfaceiv"); - gl3wGetProgramPipelineInfoLog = (PFNGLGETPROGRAMPIPELINEINFOLOGPROC)proc("glGetProgramPipelineInfoLog"); - gl3wGetProgramPipelineiv = (PFNGLGETPROGRAMPIPELINEIVPROC)proc("glGetProgramPipelineiv"); - gl3wGetProgramResourceIndex = (PFNGLGETPROGRAMRESOURCEINDEXPROC)proc("glGetProgramResourceIndex"); - gl3wGetProgramResourceLocation = (PFNGLGETPROGRAMRESOURCELOCATIONPROC)proc("glGetProgramResourceLocation"); - gl3wGetProgramResourceLocationIndex = (PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC)proc("glGetProgramResourceLocationIndex"); - gl3wGetProgramResourceName = (PFNGLGETPROGRAMRESOURCENAMEPROC)proc("glGetProgramResourceName"); - gl3wGetProgramResourcefvNV = (PFNGLGETPROGRAMRESOURCEFVNVPROC)proc("glGetProgramResourcefvNV"); - gl3wGetProgramResourceiv = (PFNGLGETPROGRAMRESOURCEIVPROC)proc("glGetProgramResourceiv"); - gl3wGetProgramStageiv = (PFNGLGETPROGRAMSTAGEIVPROC)proc("glGetProgramStageiv"); - gl3wGetProgramiv = (PFNGLGETPROGRAMIVPROC)proc("glGetProgramiv"); - gl3wGetQueryBufferObjecti64v = (PFNGLGETQUERYBUFFEROBJECTI64VPROC)proc("glGetQueryBufferObjecti64v"); - gl3wGetQueryBufferObjectiv = (PFNGLGETQUERYBUFFEROBJECTIVPROC)proc("glGetQueryBufferObjectiv"); - gl3wGetQueryBufferObjectui64v = (PFNGLGETQUERYBUFFEROBJECTUI64VPROC)proc("glGetQueryBufferObjectui64v"); - gl3wGetQueryBufferObjectuiv = (PFNGLGETQUERYBUFFEROBJECTUIVPROC)proc("glGetQueryBufferObjectuiv"); - gl3wGetQueryIndexediv = (PFNGLGETQUERYINDEXEDIVPROC)proc("glGetQueryIndexediv"); - gl3wGetQueryObjecti64v = (PFNGLGETQUERYOBJECTI64VPROC)proc("glGetQueryObjecti64v"); - gl3wGetQueryObjectiv = (PFNGLGETQUERYOBJECTIVPROC)proc("glGetQueryObjectiv"); - gl3wGetQueryObjectui64v = (PFNGLGETQUERYOBJECTUI64VPROC)proc("glGetQueryObjectui64v"); - gl3wGetQueryObjectuiv = (PFNGLGETQUERYOBJECTUIVPROC)proc("glGetQueryObjectuiv"); - gl3wGetQueryiv = (PFNGLGETQUERYIVPROC)proc("glGetQueryiv"); - gl3wGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)proc("glGetRenderbufferParameteriv"); - gl3wGetSamplerParameterIiv = (PFNGLGETSAMPLERPARAMETERIIVPROC)proc("glGetSamplerParameterIiv"); - gl3wGetSamplerParameterIuiv = (PFNGLGETSAMPLERPARAMETERIUIVPROC)proc("glGetSamplerParameterIuiv"); - gl3wGetSamplerParameterfv = (PFNGLGETSAMPLERPARAMETERFVPROC)proc("glGetSamplerParameterfv"); - gl3wGetSamplerParameteriv = (PFNGLGETSAMPLERPARAMETERIVPROC)proc("glGetSamplerParameteriv"); - gl3wGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)proc("glGetShaderInfoLog"); - gl3wGetShaderPrecisionFormat = (PFNGLGETSHADERPRECISIONFORMATPROC)proc("glGetShaderPrecisionFormat"); - gl3wGetShaderSource = (PFNGLGETSHADERSOURCEPROC)proc("glGetShaderSource"); - gl3wGetShaderiv = (PFNGLGETSHADERIVPROC)proc("glGetShaderiv"); - gl3wGetStageIndexNV = (PFNGLGETSTAGEINDEXNVPROC)proc("glGetStageIndexNV"); - gl3wGetString = (PFNGLGETSTRINGPROC)proc("glGetString"); - gl3wGetStringi = (PFNGLGETSTRINGIPROC)proc("glGetStringi"); - gl3wGetSubroutineIndex = (PFNGLGETSUBROUTINEINDEXPROC)proc("glGetSubroutineIndex"); - gl3wGetSubroutineUniformLocation = (PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC)proc("glGetSubroutineUniformLocation"); - gl3wGetSynciv = (PFNGLGETSYNCIVPROC)proc("glGetSynciv"); - gl3wGetTexImage = (PFNGLGETTEXIMAGEPROC)proc("glGetTexImage"); - gl3wGetTexLevelParameterfv = (PFNGLGETTEXLEVELPARAMETERFVPROC)proc("glGetTexLevelParameterfv"); - gl3wGetTexLevelParameteriv = (PFNGLGETTEXLEVELPARAMETERIVPROC)proc("glGetTexLevelParameteriv"); - gl3wGetTexParameterIiv = (PFNGLGETTEXPARAMETERIIVPROC)proc("glGetTexParameterIiv"); - gl3wGetTexParameterIuiv = (PFNGLGETTEXPARAMETERIUIVPROC)proc("glGetTexParameterIuiv"); - gl3wGetTexParameterfv = (PFNGLGETTEXPARAMETERFVPROC)proc("glGetTexParameterfv"); - gl3wGetTexParameteriv = (PFNGLGETTEXPARAMETERIVPROC)proc("glGetTexParameteriv"); - gl3wGetTextureHandleARB = (PFNGLGETTEXTUREHANDLEARBPROC)proc("glGetTextureHandleARB"); - gl3wGetTextureHandleNV = (PFNGLGETTEXTUREHANDLENVPROC)proc("glGetTextureHandleNV"); - gl3wGetTextureImage = (PFNGLGETTEXTUREIMAGEPROC)proc("glGetTextureImage"); - gl3wGetTextureImageEXT = (PFNGLGETTEXTUREIMAGEEXTPROC)proc("glGetTextureImageEXT"); - gl3wGetTextureLevelParameterfv = (PFNGLGETTEXTURELEVELPARAMETERFVPROC)proc("glGetTextureLevelParameterfv"); - gl3wGetTextureLevelParameterfvEXT = (PFNGLGETTEXTURELEVELPARAMETERFVEXTPROC)proc("glGetTextureLevelParameterfvEXT"); - gl3wGetTextureLevelParameteriv = (PFNGLGETTEXTURELEVELPARAMETERIVPROC)proc("glGetTextureLevelParameteriv"); - gl3wGetTextureLevelParameterivEXT = (PFNGLGETTEXTURELEVELPARAMETERIVEXTPROC)proc("glGetTextureLevelParameterivEXT"); - gl3wGetTextureParameterIiv = (PFNGLGETTEXTUREPARAMETERIIVPROC)proc("glGetTextureParameterIiv"); - gl3wGetTextureParameterIivEXT = (PFNGLGETTEXTUREPARAMETERIIVEXTPROC)proc("glGetTextureParameterIivEXT"); - gl3wGetTextureParameterIuiv = (PFNGLGETTEXTUREPARAMETERIUIVPROC)proc("glGetTextureParameterIuiv"); - gl3wGetTextureParameterIuivEXT = (PFNGLGETTEXTUREPARAMETERIUIVEXTPROC)proc("glGetTextureParameterIuivEXT"); - gl3wGetTextureParameterfv = (PFNGLGETTEXTUREPARAMETERFVPROC)proc("glGetTextureParameterfv"); - gl3wGetTextureParameterfvEXT = (PFNGLGETTEXTUREPARAMETERFVEXTPROC)proc("glGetTextureParameterfvEXT"); - gl3wGetTextureParameteriv = (PFNGLGETTEXTUREPARAMETERIVPROC)proc("glGetTextureParameteriv"); - gl3wGetTextureParameterivEXT = (PFNGLGETTEXTUREPARAMETERIVEXTPROC)proc("glGetTextureParameterivEXT"); - gl3wGetTextureSamplerHandleARB = (PFNGLGETTEXTURESAMPLERHANDLEARBPROC)proc("glGetTextureSamplerHandleARB"); - gl3wGetTextureSamplerHandleNV = (PFNGLGETTEXTURESAMPLERHANDLENVPROC)proc("glGetTextureSamplerHandleNV"); - gl3wGetTextureSubImage = (PFNGLGETTEXTURESUBIMAGEPROC)proc("glGetTextureSubImage"); - gl3wGetTransformFeedbackVarying = (PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)proc("glGetTransformFeedbackVarying"); - gl3wGetTransformFeedbacki64_v = (PFNGLGETTRANSFORMFEEDBACKI64_VPROC)proc("glGetTransformFeedbacki64_v"); - gl3wGetTransformFeedbacki_v = (PFNGLGETTRANSFORMFEEDBACKI_VPROC)proc("glGetTransformFeedbacki_v"); - gl3wGetTransformFeedbackiv = (PFNGLGETTRANSFORMFEEDBACKIVPROC)proc("glGetTransformFeedbackiv"); - gl3wGetUniformBlockIndex = (PFNGLGETUNIFORMBLOCKINDEXPROC)proc("glGetUniformBlockIndex"); - gl3wGetUniformIndices = (PFNGLGETUNIFORMINDICESPROC)proc("glGetUniformIndices"); - gl3wGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)proc("glGetUniformLocation"); - gl3wGetUniformSubroutineuiv = (PFNGLGETUNIFORMSUBROUTINEUIVPROC)proc("glGetUniformSubroutineuiv"); - gl3wGetUniformdv = (PFNGLGETUNIFORMDVPROC)proc("glGetUniformdv"); - gl3wGetUniformfv = (PFNGLGETUNIFORMFVPROC)proc("glGetUniformfv"); - gl3wGetUniformi64vARB = (PFNGLGETUNIFORMI64VARBPROC)proc("glGetUniformi64vARB"); - gl3wGetUniformi64vNV = (PFNGLGETUNIFORMI64VNVPROC)proc("glGetUniformi64vNV"); - gl3wGetUniformiv = (PFNGLGETUNIFORMIVPROC)proc("glGetUniformiv"); - gl3wGetUniformui64vARB = (PFNGLGETUNIFORMUI64VARBPROC)proc("glGetUniformui64vARB"); - gl3wGetUniformui64vNV = (PFNGLGETUNIFORMUI64VNVPROC)proc("glGetUniformui64vNV"); - gl3wGetUniformuiv = (PFNGLGETUNIFORMUIVPROC)proc("glGetUniformuiv"); - gl3wGetVertexArrayIndexed64iv = (PFNGLGETVERTEXARRAYINDEXED64IVPROC)proc("glGetVertexArrayIndexed64iv"); - gl3wGetVertexArrayIndexediv = (PFNGLGETVERTEXARRAYINDEXEDIVPROC)proc("glGetVertexArrayIndexediv"); - gl3wGetVertexArrayIntegeri_vEXT = (PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC)proc("glGetVertexArrayIntegeri_vEXT"); - gl3wGetVertexArrayIntegervEXT = (PFNGLGETVERTEXARRAYINTEGERVEXTPROC)proc("glGetVertexArrayIntegervEXT"); - gl3wGetVertexArrayPointeri_vEXT = (PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC)proc("glGetVertexArrayPointeri_vEXT"); - gl3wGetVertexArrayPointervEXT = (PFNGLGETVERTEXARRAYPOINTERVEXTPROC)proc("glGetVertexArrayPointervEXT"); - gl3wGetVertexArrayiv = (PFNGLGETVERTEXARRAYIVPROC)proc("glGetVertexArrayiv"); - gl3wGetVertexAttribIiv = (PFNGLGETVERTEXATTRIBIIVPROC)proc("glGetVertexAttribIiv"); - gl3wGetVertexAttribIuiv = (PFNGLGETVERTEXATTRIBIUIVPROC)proc("glGetVertexAttribIuiv"); - gl3wGetVertexAttribLdv = (PFNGLGETVERTEXATTRIBLDVPROC)proc("glGetVertexAttribLdv"); - gl3wGetVertexAttribLi64vNV = (PFNGLGETVERTEXATTRIBLI64VNVPROC)proc("glGetVertexAttribLi64vNV"); - gl3wGetVertexAttribLui64vARB = (PFNGLGETVERTEXATTRIBLUI64VARBPROC)proc("glGetVertexAttribLui64vARB"); - gl3wGetVertexAttribLui64vNV = (PFNGLGETVERTEXATTRIBLUI64VNVPROC)proc("glGetVertexAttribLui64vNV"); - gl3wGetVertexAttribPointerv = (PFNGLGETVERTEXATTRIBPOINTERVPROC)proc("glGetVertexAttribPointerv"); - gl3wGetVertexAttribdv = (PFNGLGETVERTEXATTRIBDVPROC)proc("glGetVertexAttribdv"); - gl3wGetVertexAttribfv = (PFNGLGETVERTEXATTRIBFVPROC)proc("glGetVertexAttribfv"); - gl3wGetVertexAttribiv = (PFNGLGETVERTEXATTRIBIVPROC)proc("glGetVertexAttribiv"); - gl3wGetVkProcAddrNV = (PFNGLGETVKPROCADDRNVPROC)proc("glGetVkProcAddrNV"); - gl3wGetnCompressedTexImage = (PFNGLGETNCOMPRESSEDTEXIMAGEPROC)proc("glGetnCompressedTexImage"); - gl3wGetnCompressedTexImageARB = (PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC)proc("glGetnCompressedTexImageARB"); - gl3wGetnTexImage = (PFNGLGETNTEXIMAGEPROC)proc("glGetnTexImage"); - gl3wGetnTexImageARB = (PFNGLGETNTEXIMAGEARBPROC)proc("glGetnTexImageARB"); - gl3wGetnUniformdv = (PFNGLGETNUNIFORMDVPROC)proc("glGetnUniformdv"); - gl3wGetnUniformdvARB = (PFNGLGETNUNIFORMDVARBPROC)proc("glGetnUniformdvARB"); - gl3wGetnUniformfv = (PFNGLGETNUNIFORMFVPROC)proc("glGetnUniformfv"); - gl3wGetnUniformfvARB = (PFNGLGETNUNIFORMFVARBPROC)proc("glGetnUniformfvARB"); - gl3wGetnUniformi64vARB = (PFNGLGETNUNIFORMI64VARBPROC)proc("glGetnUniformi64vARB"); - gl3wGetnUniformiv = (PFNGLGETNUNIFORMIVPROC)proc("glGetnUniformiv"); - gl3wGetnUniformivARB = (PFNGLGETNUNIFORMIVARBPROC)proc("glGetnUniformivARB"); - gl3wGetnUniformui64vARB = (PFNGLGETNUNIFORMUI64VARBPROC)proc("glGetnUniformui64vARB"); - gl3wGetnUniformuiv = (PFNGLGETNUNIFORMUIVPROC)proc("glGetnUniformuiv"); - gl3wGetnUniformuivARB = (PFNGLGETNUNIFORMUIVARBPROC)proc("glGetnUniformuivARB"); - gl3wHint = (PFNGLHINTPROC)proc("glHint"); - gl3wIndexFormatNV = (PFNGLINDEXFORMATNVPROC)proc("glIndexFormatNV"); - gl3wInsertEventMarkerEXT = (PFNGLINSERTEVENTMARKEREXTPROC)proc("glInsertEventMarkerEXT"); - gl3wInterpolatePathsNV = (PFNGLINTERPOLATEPATHSNVPROC)proc("glInterpolatePathsNV"); - gl3wInvalidateBufferData = (PFNGLINVALIDATEBUFFERDATAPROC)proc("glInvalidateBufferData"); - gl3wInvalidateBufferSubData = (PFNGLINVALIDATEBUFFERSUBDATAPROC)proc("glInvalidateBufferSubData"); - gl3wInvalidateFramebuffer = (PFNGLINVALIDATEFRAMEBUFFERPROC)proc("glInvalidateFramebuffer"); - gl3wInvalidateNamedFramebufferData = (PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC)proc("glInvalidateNamedFramebufferData"); - gl3wInvalidateNamedFramebufferSubData = (PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC)proc("glInvalidateNamedFramebufferSubData"); - gl3wInvalidateSubFramebuffer = (PFNGLINVALIDATESUBFRAMEBUFFERPROC)proc("glInvalidateSubFramebuffer"); - gl3wInvalidateTexImage = (PFNGLINVALIDATETEXIMAGEPROC)proc("glInvalidateTexImage"); - gl3wInvalidateTexSubImage = (PFNGLINVALIDATETEXSUBIMAGEPROC)proc("glInvalidateTexSubImage"); - gl3wIsBuffer = (PFNGLISBUFFERPROC)proc("glIsBuffer"); - gl3wIsBufferResidentNV = (PFNGLISBUFFERRESIDENTNVPROC)proc("glIsBufferResidentNV"); - gl3wIsCommandListNV = (PFNGLISCOMMANDLISTNVPROC)proc("glIsCommandListNV"); - gl3wIsEnabled = (PFNGLISENABLEDPROC)proc("glIsEnabled"); - gl3wIsEnabledIndexedEXT = (PFNGLISENABLEDINDEXEDEXTPROC)proc("glIsEnabledIndexedEXT"); - gl3wIsEnabledi = (PFNGLISENABLEDIPROC)proc("glIsEnabledi"); - gl3wIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)proc("glIsFramebuffer"); - gl3wIsImageHandleResidentARB = (PFNGLISIMAGEHANDLERESIDENTARBPROC)proc("glIsImageHandleResidentARB"); - gl3wIsImageHandleResidentNV = (PFNGLISIMAGEHANDLERESIDENTNVPROC)proc("glIsImageHandleResidentNV"); - gl3wIsNamedBufferResidentNV = (PFNGLISNAMEDBUFFERRESIDENTNVPROC)proc("glIsNamedBufferResidentNV"); - gl3wIsNamedStringARB = (PFNGLISNAMEDSTRINGARBPROC)proc("glIsNamedStringARB"); - gl3wIsPathNV = (PFNGLISPATHNVPROC)proc("glIsPathNV"); - gl3wIsPointInFillPathNV = (PFNGLISPOINTINFILLPATHNVPROC)proc("glIsPointInFillPathNV"); - gl3wIsPointInStrokePathNV = (PFNGLISPOINTINSTROKEPATHNVPROC)proc("glIsPointInStrokePathNV"); - gl3wIsProgram = (PFNGLISPROGRAMPROC)proc("glIsProgram"); - gl3wIsProgramPipeline = (PFNGLISPROGRAMPIPELINEPROC)proc("glIsProgramPipeline"); - gl3wIsQuery = (PFNGLISQUERYPROC)proc("glIsQuery"); - gl3wIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)proc("glIsRenderbuffer"); - gl3wIsSampler = (PFNGLISSAMPLERPROC)proc("glIsSampler"); - gl3wIsShader = (PFNGLISSHADERPROC)proc("glIsShader"); - gl3wIsStateNV = (PFNGLISSTATENVPROC)proc("glIsStateNV"); - gl3wIsSync = (PFNGLISSYNCPROC)proc("glIsSync"); - gl3wIsTexture = (PFNGLISTEXTUREPROC)proc("glIsTexture"); - gl3wIsTextureHandleResidentARB = (PFNGLISTEXTUREHANDLERESIDENTARBPROC)proc("glIsTextureHandleResidentARB"); - gl3wIsTextureHandleResidentNV = (PFNGLISTEXTUREHANDLERESIDENTNVPROC)proc("glIsTextureHandleResidentNV"); - gl3wIsTransformFeedback = (PFNGLISTRANSFORMFEEDBACKPROC)proc("glIsTransformFeedback"); - gl3wIsVertexArray = (PFNGLISVERTEXARRAYPROC)proc("glIsVertexArray"); - gl3wLabelObjectEXT = (PFNGLLABELOBJECTEXTPROC)proc("glLabelObjectEXT"); - gl3wLineWidth = (PFNGLLINEWIDTHPROC)proc("glLineWidth"); - gl3wLinkProgram = (PFNGLLINKPROGRAMPROC)proc("glLinkProgram"); - gl3wListDrawCommandsStatesClientNV = (PFNGLLISTDRAWCOMMANDSSTATESCLIENTNVPROC)proc("glListDrawCommandsStatesClientNV"); - gl3wLogicOp = (PFNGLLOGICOPPROC)proc("glLogicOp"); - gl3wMakeBufferNonResidentNV = (PFNGLMAKEBUFFERNONRESIDENTNVPROC)proc("glMakeBufferNonResidentNV"); - gl3wMakeBufferResidentNV = (PFNGLMAKEBUFFERRESIDENTNVPROC)proc("glMakeBufferResidentNV"); - gl3wMakeImageHandleNonResidentARB = (PFNGLMAKEIMAGEHANDLENONRESIDENTARBPROC)proc("glMakeImageHandleNonResidentARB"); - gl3wMakeImageHandleNonResidentNV = (PFNGLMAKEIMAGEHANDLENONRESIDENTNVPROC)proc("glMakeImageHandleNonResidentNV"); - gl3wMakeImageHandleResidentARB = (PFNGLMAKEIMAGEHANDLERESIDENTARBPROC)proc("glMakeImageHandleResidentARB"); - gl3wMakeImageHandleResidentNV = (PFNGLMAKEIMAGEHANDLERESIDENTNVPROC)proc("glMakeImageHandleResidentNV"); - gl3wMakeNamedBufferNonResidentNV = (PFNGLMAKENAMEDBUFFERNONRESIDENTNVPROC)proc("glMakeNamedBufferNonResidentNV"); - gl3wMakeNamedBufferResidentNV = (PFNGLMAKENAMEDBUFFERRESIDENTNVPROC)proc("glMakeNamedBufferResidentNV"); - gl3wMakeTextureHandleNonResidentARB = (PFNGLMAKETEXTUREHANDLENONRESIDENTARBPROC)proc("glMakeTextureHandleNonResidentARB"); - gl3wMakeTextureHandleNonResidentNV = (PFNGLMAKETEXTUREHANDLENONRESIDENTNVPROC)proc("glMakeTextureHandleNonResidentNV"); - gl3wMakeTextureHandleResidentARB = (PFNGLMAKETEXTUREHANDLERESIDENTARBPROC)proc("glMakeTextureHandleResidentARB"); - gl3wMakeTextureHandleResidentNV = (PFNGLMAKETEXTUREHANDLERESIDENTNVPROC)proc("glMakeTextureHandleResidentNV"); - gl3wMapBuffer = (PFNGLMAPBUFFERPROC)proc("glMapBuffer"); - gl3wMapBufferRange = (PFNGLMAPBUFFERRANGEPROC)proc("glMapBufferRange"); - gl3wMapNamedBuffer = (PFNGLMAPNAMEDBUFFERPROC)proc("glMapNamedBuffer"); - gl3wMapNamedBufferEXT = (PFNGLMAPNAMEDBUFFEREXTPROC)proc("glMapNamedBufferEXT"); - gl3wMapNamedBufferRange = (PFNGLMAPNAMEDBUFFERRANGEPROC)proc("glMapNamedBufferRange"); - gl3wMapNamedBufferRangeEXT = (PFNGLMAPNAMEDBUFFERRANGEEXTPROC)proc("glMapNamedBufferRangeEXT"); - gl3wMatrixFrustumEXT = (PFNGLMATRIXFRUSTUMEXTPROC)proc("glMatrixFrustumEXT"); - gl3wMatrixLoad3x2fNV = (PFNGLMATRIXLOAD3X2FNVPROC)proc("glMatrixLoad3x2fNV"); - gl3wMatrixLoad3x3fNV = (PFNGLMATRIXLOAD3X3FNVPROC)proc("glMatrixLoad3x3fNV"); - gl3wMatrixLoadIdentityEXT = (PFNGLMATRIXLOADIDENTITYEXTPROC)proc("glMatrixLoadIdentityEXT"); - gl3wMatrixLoadTranspose3x3fNV = (PFNGLMATRIXLOADTRANSPOSE3X3FNVPROC)proc("glMatrixLoadTranspose3x3fNV"); - gl3wMatrixLoadTransposedEXT = (PFNGLMATRIXLOADTRANSPOSEDEXTPROC)proc("glMatrixLoadTransposedEXT"); - gl3wMatrixLoadTransposefEXT = (PFNGLMATRIXLOADTRANSPOSEFEXTPROC)proc("glMatrixLoadTransposefEXT"); - gl3wMatrixLoaddEXT = (PFNGLMATRIXLOADDEXTPROC)proc("glMatrixLoaddEXT"); - gl3wMatrixLoadfEXT = (PFNGLMATRIXLOADFEXTPROC)proc("glMatrixLoadfEXT"); - gl3wMatrixMult3x2fNV = (PFNGLMATRIXMULT3X2FNVPROC)proc("glMatrixMult3x2fNV"); - gl3wMatrixMult3x3fNV = (PFNGLMATRIXMULT3X3FNVPROC)proc("glMatrixMult3x3fNV"); - gl3wMatrixMultTranspose3x3fNV = (PFNGLMATRIXMULTTRANSPOSE3X3FNVPROC)proc("glMatrixMultTranspose3x3fNV"); - gl3wMatrixMultTransposedEXT = (PFNGLMATRIXMULTTRANSPOSEDEXTPROC)proc("glMatrixMultTransposedEXT"); - gl3wMatrixMultTransposefEXT = (PFNGLMATRIXMULTTRANSPOSEFEXTPROC)proc("glMatrixMultTransposefEXT"); - gl3wMatrixMultdEXT = (PFNGLMATRIXMULTDEXTPROC)proc("glMatrixMultdEXT"); - gl3wMatrixMultfEXT = (PFNGLMATRIXMULTFEXTPROC)proc("glMatrixMultfEXT"); - gl3wMatrixOrthoEXT = (PFNGLMATRIXORTHOEXTPROC)proc("glMatrixOrthoEXT"); - gl3wMatrixPopEXT = (PFNGLMATRIXPOPEXTPROC)proc("glMatrixPopEXT"); - gl3wMatrixPushEXT = (PFNGLMATRIXPUSHEXTPROC)proc("glMatrixPushEXT"); - gl3wMatrixRotatedEXT = (PFNGLMATRIXROTATEDEXTPROC)proc("glMatrixRotatedEXT"); - gl3wMatrixRotatefEXT = (PFNGLMATRIXROTATEFEXTPROC)proc("glMatrixRotatefEXT"); - gl3wMatrixScaledEXT = (PFNGLMATRIXSCALEDEXTPROC)proc("glMatrixScaledEXT"); - gl3wMatrixScalefEXT = (PFNGLMATRIXSCALEFEXTPROC)proc("glMatrixScalefEXT"); - gl3wMatrixTranslatedEXT = (PFNGLMATRIXTRANSLATEDEXTPROC)proc("glMatrixTranslatedEXT"); - gl3wMatrixTranslatefEXT = (PFNGLMATRIXTRANSLATEFEXTPROC)proc("glMatrixTranslatefEXT"); - gl3wMaxShaderCompilerThreadsARB = (PFNGLMAXSHADERCOMPILERTHREADSARBPROC)proc("glMaxShaderCompilerThreadsARB"); - gl3wMemoryBarrier = (PFNGLMEMORYBARRIERPROC)proc("glMemoryBarrier"); - gl3wMemoryBarrierByRegion = (PFNGLMEMORYBARRIERBYREGIONPROC)proc("glMemoryBarrierByRegion"); - gl3wMinSampleShading = (PFNGLMINSAMPLESHADINGPROC)proc("glMinSampleShading"); - gl3wMinSampleShadingARB = (PFNGLMINSAMPLESHADINGARBPROC)proc("glMinSampleShadingARB"); - gl3wMultiDrawArrays = (PFNGLMULTIDRAWARRAYSPROC)proc("glMultiDrawArrays"); - gl3wMultiDrawArraysIndirect = (PFNGLMULTIDRAWARRAYSINDIRECTPROC)proc("glMultiDrawArraysIndirect"); - gl3wMultiDrawArraysIndirectBindlessCountNV = (PFNGLMULTIDRAWARRAYSINDIRECTBINDLESSCOUNTNVPROC)proc("glMultiDrawArraysIndirectBindlessCountNV"); - gl3wMultiDrawArraysIndirectBindlessNV = (PFNGLMULTIDRAWARRAYSINDIRECTBINDLESSNVPROC)proc("glMultiDrawArraysIndirectBindlessNV"); - gl3wMultiDrawArraysIndirectCount = (PFNGLMULTIDRAWARRAYSINDIRECTCOUNTPROC)proc("glMultiDrawArraysIndirectCount"); - gl3wMultiDrawArraysIndirectCountARB = (PFNGLMULTIDRAWARRAYSINDIRECTCOUNTARBPROC)proc("glMultiDrawArraysIndirectCountARB"); - gl3wMultiDrawElements = (PFNGLMULTIDRAWELEMENTSPROC)proc("glMultiDrawElements"); - gl3wMultiDrawElementsBaseVertex = (PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)proc("glMultiDrawElementsBaseVertex"); - gl3wMultiDrawElementsIndirect = (PFNGLMULTIDRAWELEMENTSINDIRECTPROC)proc("glMultiDrawElementsIndirect"); - gl3wMultiDrawElementsIndirectBindlessCountNV = (PFNGLMULTIDRAWELEMENTSINDIRECTBINDLESSCOUNTNVPROC)proc("glMultiDrawElementsIndirectBindlessCountNV"); - gl3wMultiDrawElementsIndirectBindlessNV = (PFNGLMULTIDRAWELEMENTSINDIRECTBINDLESSNVPROC)proc("glMultiDrawElementsIndirectBindlessNV"); - gl3wMultiDrawElementsIndirectCount = (PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTPROC)proc("glMultiDrawElementsIndirectCount"); - gl3wMultiDrawElementsIndirectCountARB = (PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTARBPROC)proc("glMultiDrawElementsIndirectCountARB"); - gl3wMultiTexBufferEXT = (PFNGLMULTITEXBUFFEREXTPROC)proc("glMultiTexBufferEXT"); - gl3wMultiTexCoordPointerEXT = (PFNGLMULTITEXCOORDPOINTEREXTPROC)proc("glMultiTexCoordPointerEXT"); - gl3wMultiTexEnvfEXT = (PFNGLMULTITEXENVFEXTPROC)proc("glMultiTexEnvfEXT"); - gl3wMultiTexEnvfvEXT = (PFNGLMULTITEXENVFVEXTPROC)proc("glMultiTexEnvfvEXT"); - gl3wMultiTexEnviEXT = (PFNGLMULTITEXENVIEXTPROC)proc("glMultiTexEnviEXT"); - gl3wMultiTexEnvivEXT = (PFNGLMULTITEXENVIVEXTPROC)proc("glMultiTexEnvivEXT"); - gl3wMultiTexGendEXT = (PFNGLMULTITEXGENDEXTPROC)proc("glMultiTexGendEXT"); - gl3wMultiTexGendvEXT = (PFNGLMULTITEXGENDVEXTPROC)proc("glMultiTexGendvEXT"); - gl3wMultiTexGenfEXT = (PFNGLMULTITEXGENFEXTPROC)proc("glMultiTexGenfEXT"); - gl3wMultiTexGenfvEXT = (PFNGLMULTITEXGENFVEXTPROC)proc("glMultiTexGenfvEXT"); - gl3wMultiTexGeniEXT = (PFNGLMULTITEXGENIEXTPROC)proc("glMultiTexGeniEXT"); - gl3wMultiTexGenivEXT = (PFNGLMULTITEXGENIVEXTPROC)proc("glMultiTexGenivEXT"); - gl3wMultiTexImage1DEXT = (PFNGLMULTITEXIMAGE1DEXTPROC)proc("glMultiTexImage1DEXT"); - gl3wMultiTexImage2DEXT = (PFNGLMULTITEXIMAGE2DEXTPROC)proc("glMultiTexImage2DEXT"); - gl3wMultiTexImage3DEXT = (PFNGLMULTITEXIMAGE3DEXTPROC)proc("glMultiTexImage3DEXT"); - gl3wMultiTexParameterIivEXT = (PFNGLMULTITEXPARAMETERIIVEXTPROC)proc("glMultiTexParameterIivEXT"); - gl3wMultiTexParameterIuivEXT = (PFNGLMULTITEXPARAMETERIUIVEXTPROC)proc("glMultiTexParameterIuivEXT"); - gl3wMultiTexParameterfEXT = (PFNGLMULTITEXPARAMETERFEXTPROC)proc("glMultiTexParameterfEXT"); - gl3wMultiTexParameterfvEXT = (PFNGLMULTITEXPARAMETERFVEXTPROC)proc("glMultiTexParameterfvEXT"); - gl3wMultiTexParameteriEXT = (PFNGLMULTITEXPARAMETERIEXTPROC)proc("glMultiTexParameteriEXT"); - gl3wMultiTexParameterivEXT = (PFNGLMULTITEXPARAMETERIVEXTPROC)proc("glMultiTexParameterivEXT"); - gl3wMultiTexRenderbufferEXT = (PFNGLMULTITEXRENDERBUFFEREXTPROC)proc("glMultiTexRenderbufferEXT"); - gl3wMultiTexSubImage1DEXT = (PFNGLMULTITEXSUBIMAGE1DEXTPROC)proc("glMultiTexSubImage1DEXT"); - gl3wMultiTexSubImage2DEXT = (PFNGLMULTITEXSUBIMAGE2DEXTPROC)proc("glMultiTexSubImage2DEXT"); - gl3wMultiTexSubImage3DEXT = (PFNGLMULTITEXSUBIMAGE3DEXTPROC)proc("glMultiTexSubImage3DEXT"); - gl3wNamedBufferData = (PFNGLNAMEDBUFFERDATAPROC)proc("glNamedBufferData"); - gl3wNamedBufferDataEXT = (PFNGLNAMEDBUFFERDATAEXTPROC)proc("glNamedBufferDataEXT"); - gl3wNamedBufferPageCommitmentARB = (PFNGLNAMEDBUFFERPAGECOMMITMENTARBPROC)proc("glNamedBufferPageCommitmentARB"); - gl3wNamedBufferPageCommitmentEXT = (PFNGLNAMEDBUFFERPAGECOMMITMENTEXTPROC)proc("glNamedBufferPageCommitmentEXT"); - gl3wNamedBufferStorage = (PFNGLNAMEDBUFFERSTORAGEPROC)proc("glNamedBufferStorage"); - gl3wNamedBufferStorageEXT = (PFNGLNAMEDBUFFERSTORAGEEXTPROC)proc("glNamedBufferStorageEXT"); - gl3wNamedBufferSubData = (PFNGLNAMEDBUFFERSUBDATAPROC)proc("glNamedBufferSubData"); - gl3wNamedBufferSubDataEXT = (PFNGLNAMEDBUFFERSUBDATAEXTPROC)proc("glNamedBufferSubDataEXT"); - gl3wNamedCopyBufferSubDataEXT = (PFNGLNAMEDCOPYBUFFERSUBDATAEXTPROC)proc("glNamedCopyBufferSubDataEXT"); - gl3wNamedFramebufferDrawBuffer = (PFNGLNAMEDFRAMEBUFFERDRAWBUFFERPROC)proc("glNamedFramebufferDrawBuffer"); - gl3wNamedFramebufferDrawBuffers = (PFNGLNAMEDFRAMEBUFFERDRAWBUFFERSPROC)proc("glNamedFramebufferDrawBuffers"); - gl3wNamedFramebufferParameteri = (PFNGLNAMEDFRAMEBUFFERPARAMETERIPROC)proc("glNamedFramebufferParameteri"); - gl3wNamedFramebufferParameteriEXT = (PFNGLNAMEDFRAMEBUFFERPARAMETERIEXTPROC)proc("glNamedFramebufferParameteriEXT"); - gl3wNamedFramebufferReadBuffer = (PFNGLNAMEDFRAMEBUFFERREADBUFFERPROC)proc("glNamedFramebufferReadBuffer"); - gl3wNamedFramebufferRenderbuffer = (PFNGLNAMEDFRAMEBUFFERRENDERBUFFERPROC)proc("glNamedFramebufferRenderbuffer"); - gl3wNamedFramebufferRenderbufferEXT = (PFNGLNAMEDFRAMEBUFFERRENDERBUFFEREXTPROC)proc("glNamedFramebufferRenderbufferEXT"); - gl3wNamedFramebufferSampleLocationsfvARB = (PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVARBPROC)proc("glNamedFramebufferSampleLocationsfvARB"); - gl3wNamedFramebufferSampleLocationsfvNV = (PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVNVPROC)proc("glNamedFramebufferSampleLocationsfvNV"); - gl3wNamedFramebufferTexture = (PFNGLNAMEDFRAMEBUFFERTEXTUREPROC)proc("glNamedFramebufferTexture"); - gl3wNamedFramebufferTexture1DEXT = (PFNGLNAMEDFRAMEBUFFERTEXTURE1DEXTPROC)proc("glNamedFramebufferTexture1DEXT"); - gl3wNamedFramebufferTexture2DEXT = (PFNGLNAMEDFRAMEBUFFERTEXTURE2DEXTPROC)proc("glNamedFramebufferTexture2DEXT"); - gl3wNamedFramebufferTexture3DEXT = (PFNGLNAMEDFRAMEBUFFERTEXTURE3DEXTPROC)proc("glNamedFramebufferTexture3DEXT"); - gl3wNamedFramebufferTextureEXT = (PFNGLNAMEDFRAMEBUFFERTEXTUREEXTPROC)proc("glNamedFramebufferTextureEXT"); - gl3wNamedFramebufferTextureFaceEXT = (PFNGLNAMEDFRAMEBUFFERTEXTUREFACEEXTPROC)proc("glNamedFramebufferTextureFaceEXT"); - gl3wNamedFramebufferTextureLayer = (PFNGLNAMEDFRAMEBUFFERTEXTURELAYERPROC)proc("glNamedFramebufferTextureLayer"); - gl3wNamedFramebufferTextureLayerEXT = (PFNGLNAMEDFRAMEBUFFERTEXTURELAYEREXTPROC)proc("glNamedFramebufferTextureLayerEXT"); - gl3wNamedProgramLocalParameter4dEXT = (PFNGLNAMEDPROGRAMLOCALPARAMETER4DEXTPROC)proc("glNamedProgramLocalParameter4dEXT"); - gl3wNamedProgramLocalParameter4dvEXT = (PFNGLNAMEDPROGRAMLOCALPARAMETER4DVEXTPROC)proc("glNamedProgramLocalParameter4dvEXT"); - gl3wNamedProgramLocalParameter4fEXT = (PFNGLNAMEDPROGRAMLOCALPARAMETER4FEXTPROC)proc("glNamedProgramLocalParameter4fEXT"); - gl3wNamedProgramLocalParameter4fvEXT = (PFNGLNAMEDPROGRAMLOCALPARAMETER4FVEXTPROC)proc("glNamedProgramLocalParameter4fvEXT"); - gl3wNamedProgramLocalParameterI4iEXT = (PFNGLNAMEDPROGRAMLOCALPARAMETERI4IEXTPROC)proc("glNamedProgramLocalParameterI4iEXT"); - gl3wNamedProgramLocalParameterI4ivEXT = (PFNGLNAMEDPROGRAMLOCALPARAMETERI4IVEXTPROC)proc("glNamedProgramLocalParameterI4ivEXT"); - gl3wNamedProgramLocalParameterI4uiEXT = (PFNGLNAMEDPROGRAMLOCALPARAMETERI4UIEXTPROC)proc("glNamedProgramLocalParameterI4uiEXT"); - gl3wNamedProgramLocalParameterI4uivEXT = (PFNGLNAMEDPROGRAMLOCALPARAMETERI4UIVEXTPROC)proc("glNamedProgramLocalParameterI4uivEXT"); - gl3wNamedProgramLocalParameters4fvEXT = (PFNGLNAMEDPROGRAMLOCALPARAMETERS4FVEXTPROC)proc("glNamedProgramLocalParameters4fvEXT"); - gl3wNamedProgramLocalParametersI4ivEXT = (PFNGLNAMEDPROGRAMLOCALPARAMETERSI4IVEXTPROC)proc("glNamedProgramLocalParametersI4ivEXT"); - gl3wNamedProgramLocalParametersI4uivEXT = (PFNGLNAMEDPROGRAMLOCALPARAMETERSI4UIVEXTPROC)proc("glNamedProgramLocalParametersI4uivEXT"); - gl3wNamedProgramStringEXT = (PFNGLNAMEDPROGRAMSTRINGEXTPROC)proc("glNamedProgramStringEXT"); - gl3wNamedRenderbufferStorage = (PFNGLNAMEDRENDERBUFFERSTORAGEPROC)proc("glNamedRenderbufferStorage"); - gl3wNamedRenderbufferStorageEXT = (PFNGLNAMEDRENDERBUFFERSTORAGEEXTPROC)proc("glNamedRenderbufferStorageEXT"); - gl3wNamedRenderbufferStorageMultisample = (PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC)proc("glNamedRenderbufferStorageMultisample"); - gl3wNamedRenderbufferStorageMultisampleCoverageEXT = (PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLECOVERAGEEXTPROC)proc("glNamedRenderbufferStorageMultisampleCoverageEXT"); - gl3wNamedRenderbufferStorageMultisampleEXT = (PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC)proc("glNamedRenderbufferStorageMultisampleEXT"); - gl3wNamedStringARB = (PFNGLNAMEDSTRINGARBPROC)proc("glNamedStringARB"); - gl3wNormalFormatNV = (PFNGLNORMALFORMATNVPROC)proc("glNormalFormatNV"); - gl3wObjectLabel = (PFNGLOBJECTLABELPROC)proc("glObjectLabel"); - gl3wObjectPtrLabel = (PFNGLOBJECTPTRLABELPROC)proc("glObjectPtrLabel"); - gl3wPatchParameterfv = (PFNGLPATCHPARAMETERFVPROC)proc("glPatchParameterfv"); - gl3wPatchParameteri = (PFNGLPATCHPARAMETERIPROC)proc("glPatchParameteri"); - gl3wPathCommandsNV = (PFNGLPATHCOMMANDSNVPROC)proc("glPathCommandsNV"); - gl3wPathCoordsNV = (PFNGLPATHCOORDSNVPROC)proc("glPathCoordsNV"); - gl3wPathCoverDepthFuncNV = (PFNGLPATHCOVERDEPTHFUNCNVPROC)proc("glPathCoverDepthFuncNV"); - gl3wPathDashArrayNV = (PFNGLPATHDASHARRAYNVPROC)proc("glPathDashArrayNV"); - gl3wPathGlyphIndexArrayNV = (PFNGLPATHGLYPHINDEXARRAYNVPROC)proc("glPathGlyphIndexArrayNV"); - gl3wPathGlyphIndexRangeNV = (PFNGLPATHGLYPHINDEXRANGENVPROC)proc("glPathGlyphIndexRangeNV"); - gl3wPathGlyphRangeNV = (PFNGLPATHGLYPHRANGENVPROC)proc("glPathGlyphRangeNV"); - gl3wPathGlyphsNV = (PFNGLPATHGLYPHSNVPROC)proc("glPathGlyphsNV"); - gl3wPathMemoryGlyphIndexArrayNV = (PFNGLPATHMEMORYGLYPHINDEXARRAYNVPROC)proc("glPathMemoryGlyphIndexArrayNV"); - gl3wPathParameterfNV = (PFNGLPATHPARAMETERFNVPROC)proc("glPathParameterfNV"); - gl3wPathParameterfvNV = (PFNGLPATHPARAMETERFVNVPROC)proc("glPathParameterfvNV"); - gl3wPathParameteriNV = (PFNGLPATHPARAMETERINVPROC)proc("glPathParameteriNV"); - gl3wPathParameterivNV = (PFNGLPATHPARAMETERIVNVPROC)proc("glPathParameterivNV"); - gl3wPathStencilDepthOffsetNV = (PFNGLPATHSTENCILDEPTHOFFSETNVPROC)proc("glPathStencilDepthOffsetNV"); - gl3wPathStencilFuncNV = (PFNGLPATHSTENCILFUNCNVPROC)proc("glPathStencilFuncNV"); - gl3wPathStringNV = (PFNGLPATHSTRINGNVPROC)proc("glPathStringNV"); - gl3wPathSubCommandsNV = (PFNGLPATHSUBCOMMANDSNVPROC)proc("glPathSubCommandsNV"); - gl3wPathSubCoordsNV = (PFNGLPATHSUBCOORDSNVPROC)proc("glPathSubCoordsNV"); - gl3wPauseTransformFeedback = (PFNGLPAUSETRANSFORMFEEDBACKPROC)proc("glPauseTransformFeedback"); - gl3wPixelStoref = (PFNGLPIXELSTOREFPROC)proc("glPixelStoref"); - gl3wPixelStorei = (PFNGLPIXELSTOREIPROC)proc("glPixelStorei"); - gl3wPointAlongPathNV = (PFNGLPOINTALONGPATHNVPROC)proc("glPointAlongPathNV"); - gl3wPointParameterf = (PFNGLPOINTPARAMETERFPROC)proc("glPointParameterf"); - gl3wPointParameterfv = (PFNGLPOINTPARAMETERFVPROC)proc("glPointParameterfv"); - gl3wPointParameteri = (PFNGLPOINTPARAMETERIPROC)proc("glPointParameteri"); - gl3wPointParameteriv = (PFNGLPOINTPARAMETERIVPROC)proc("glPointParameteriv"); - gl3wPointSize = (PFNGLPOINTSIZEPROC)proc("glPointSize"); - gl3wPolygonMode = (PFNGLPOLYGONMODEPROC)proc("glPolygonMode"); - gl3wPolygonOffset = (PFNGLPOLYGONOFFSETPROC)proc("glPolygonOffset"); - gl3wPolygonOffsetClamp = (PFNGLPOLYGONOFFSETCLAMPPROC)proc("glPolygonOffsetClamp"); - gl3wPolygonOffsetClampEXT = (PFNGLPOLYGONOFFSETCLAMPEXTPROC)proc("glPolygonOffsetClampEXT"); - gl3wPopDebugGroup = (PFNGLPOPDEBUGGROUPPROC)proc("glPopDebugGroup"); - gl3wPopGroupMarkerEXT = (PFNGLPOPGROUPMARKEREXTPROC)proc("glPopGroupMarkerEXT"); - gl3wPrimitiveBoundingBoxARB = (PFNGLPRIMITIVEBOUNDINGBOXARBPROC)proc("glPrimitiveBoundingBoxARB"); - gl3wPrimitiveRestartIndex = (PFNGLPRIMITIVERESTARTINDEXPROC)proc("glPrimitiveRestartIndex"); - gl3wProgramBinary = (PFNGLPROGRAMBINARYPROC)proc("glProgramBinary"); - gl3wProgramParameteri = (PFNGLPROGRAMPARAMETERIPROC)proc("glProgramParameteri"); - gl3wProgramParameteriARB = (PFNGLPROGRAMPARAMETERIARBPROC)proc("glProgramParameteriARB"); - gl3wProgramPathFragmentInputGenNV = (PFNGLPROGRAMPATHFRAGMENTINPUTGENNVPROC)proc("glProgramPathFragmentInputGenNV"); - gl3wProgramUniform1d = (PFNGLPROGRAMUNIFORM1DPROC)proc("glProgramUniform1d"); - gl3wProgramUniform1dEXT = (PFNGLPROGRAMUNIFORM1DEXTPROC)proc("glProgramUniform1dEXT"); - gl3wProgramUniform1dv = (PFNGLPROGRAMUNIFORM1DVPROC)proc("glProgramUniform1dv"); - gl3wProgramUniform1dvEXT = (PFNGLPROGRAMUNIFORM1DVEXTPROC)proc("glProgramUniform1dvEXT"); - gl3wProgramUniform1f = (PFNGLPROGRAMUNIFORM1FPROC)proc("glProgramUniform1f"); - gl3wProgramUniform1fEXT = (PFNGLPROGRAMUNIFORM1FEXTPROC)proc("glProgramUniform1fEXT"); - gl3wProgramUniform1fv = (PFNGLPROGRAMUNIFORM1FVPROC)proc("glProgramUniform1fv"); - gl3wProgramUniform1fvEXT = (PFNGLPROGRAMUNIFORM1FVEXTPROC)proc("glProgramUniform1fvEXT"); - gl3wProgramUniform1i = (PFNGLPROGRAMUNIFORM1IPROC)proc("glProgramUniform1i"); - gl3wProgramUniform1i64ARB = (PFNGLPROGRAMUNIFORM1I64ARBPROC)proc("glProgramUniform1i64ARB"); - gl3wProgramUniform1i64NV = (PFNGLPROGRAMUNIFORM1I64NVPROC)proc("glProgramUniform1i64NV"); - gl3wProgramUniform1i64vARB = (PFNGLPROGRAMUNIFORM1I64VARBPROC)proc("glProgramUniform1i64vARB"); - gl3wProgramUniform1i64vNV = (PFNGLPROGRAMUNIFORM1I64VNVPROC)proc("glProgramUniform1i64vNV"); - gl3wProgramUniform1iEXT = (PFNGLPROGRAMUNIFORM1IEXTPROC)proc("glProgramUniform1iEXT"); - gl3wProgramUniform1iv = (PFNGLPROGRAMUNIFORM1IVPROC)proc("glProgramUniform1iv"); - gl3wProgramUniform1ivEXT = (PFNGLPROGRAMUNIFORM1IVEXTPROC)proc("glProgramUniform1ivEXT"); - gl3wProgramUniform1ui = (PFNGLPROGRAMUNIFORM1UIPROC)proc("glProgramUniform1ui"); - gl3wProgramUniform1ui64ARB = (PFNGLPROGRAMUNIFORM1UI64ARBPROC)proc("glProgramUniform1ui64ARB"); - gl3wProgramUniform1ui64NV = (PFNGLPROGRAMUNIFORM1UI64NVPROC)proc("glProgramUniform1ui64NV"); - gl3wProgramUniform1ui64vARB = (PFNGLPROGRAMUNIFORM1UI64VARBPROC)proc("glProgramUniform1ui64vARB"); - gl3wProgramUniform1ui64vNV = (PFNGLPROGRAMUNIFORM1UI64VNVPROC)proc("glProgramUniform1ui64vNV"); - gl3wProgramUniform1uiEXT = (PFNGLPROGRAMUNIFORM1UIEXTPROC)proc("glProgramUniform1uiEXT"); - gl3wProgramUniform1uiv = (PFNGLPROGRAMUNIFORM1UIVPROC)proc("glProgramUniform1uiv"); - gl3wProgramUniform1uivEXT = (PFNGLPROGRAMUNIFORM1UIVEXTPROC)proc("glProgramUniform1uivEXT"); - gl3wProgramUniform2d = (PFNGLPROGRAMUNIFORM2DPROC)proc("glProgramUniform2d"); - gl3wProgramUniform2dEXT = (PFNGLPROGRAMUNIFORM2DEXTPROC)proc("glProgramUniform2dEXT"); - gl3wProgramUniform2dv = (PFNGLPROGRAMUNIFORM2DVPROC)proc("glProgramUniform2dv"); - gl3wProgramUniform2dvEXT = (PFNGLPROGRAMUNIFORM2DVEXTPROC)proc("glProgramUniform2dvEXT"); - gl3wProgramUniform2f = (PFNGLPROGRAMUNIFORM2FPROC)proc("glProgramUniform2f"); - gl3wProgramUniform2fEXT = (PFNGLPROGRAMUNIFORM2FEXTPROC)proc("glProgramUniform2fEXT"); - gl3wProgramUniform2fv = (PFNGLPROGRAMUNIFORM2FVPROC)proc("glProgramUniform2fv"); - gl3wProgramUniform2fvEXT = (PFNGLPROGRAMUNIFORM2FVEXTPROC)proc("glProgramUniform2fvEXT"); - gl3wProgramUniform2i = (PFNGLPROGRAMUNIFORM2IPROC)proc("glProgramUniform2i"); - gl3wProgramUniform2i64ARB = (PFNGLPROGRAMUNIFORM2I64ARBPROC)proc("glProgramUniform2i64ARB"); - gl3wProgramUniform2i64NV = (PFNGLPROGRAMUNIFORM2I64NVPROC)proc("glProgramUniform2i64NV"); - gl3wProgramUniform2i64vARB = (PFNGLPROGRAMUNIFORM2I64VARBPROC)proc("glProgramUniform2i64vARB"); - gl3wProgramUniform2i64vNV = (PFNGLPROGRAMUNIFORM2I64VNVPROC)proc("glProgramUniform2i64vNV"); - gl3wProgramUniform2iEXT = (PFNGLPROGRAMUNIFORM2IEXTPROC)proc("glProgramUniform2iEXT"); - gl3wProgramUniform2iv = (PFNGLPROGRAMUNIFORM2IVPROC)proc("glProgramUniform2iv"); - gl3wProgramUniform2ivEXT = (PFNGLPROGRAMUNIFORM2IVEXTPROC)proc("glProgramUniform2ivEXT"); - gl3wProgramUniform2ui = (PFNGLPROGRAMUNIFORM2UIPROC)proc("glProgramUniform2ui"); - gl3wProgramUniform2ui64ARB = (PFNGLPROGRAMUNIFORM2UI64ARBPROC)proc("glProgramUniform2ui64ARB"); - gl3wProgramUniform2ui64NV = (PFNGLPROGRAMUNIFORM2UI64NVPROC)proc("glProgramUniform2ui64NV"); - gl3wProgramUniform2ui64vARB = (PFNGLPROGRAMUNIFORM2UI64VARBPROC)proc("glProgramUniform2ui64vARB"); - gl3wProgramUniform2ui64vNV = (PFNGLPROGRAMUNIFORM2UI64VNVPROC)proc("glProgramUniform2ui64vNV"); - gl3wProgramUniform2uiEXT = (PFNGLPROGRAMUNIFORM2UIEXTPROC)proc("glProgramUniform2uiEXT"); - gl3wProgramUniform2uiv = (PFNGLPROGRAMUNIFORM2UIVPROC)proc("glProgramUniform2uiv"); - gl3wProgramUniform2uivEXT = (PFNGLPROGRAMUNIFORM2UIVEXTPROC)proc("glProgramUniform2uivEXT"); - gl3wProgramUniform3d = (PFNGLPROGRAMUNIFORM3DPROC)proc("glProgramUniform3d"); - gl3wProgramUniform3dEXT = (PFNGLPROGRAMUNIFORM3DEXTPROC)proc("glProgramUniform3dEXT"); - gl3wProgramUniform3dv = (PFNGLPROGRAMUNIFORM3DVPROC)proc("glProgramUniform3dv"); - gl3wProgramUniform3dvEXT = (PFNGLPROGRAMUNIFORM3DVEXTPROC)proc("glProgramUniform3dvEXT"); - gl3wProgramUniform3f = (PFNGLPROGRAMUNIFORM3FPROC)proc("glProgramUniform3f"); - gl3wProgramUniform3fEXT = (PFNGLPROGRAMUNIFORM3FEXTPROC)proc("glProgramUniform3fEXT"); - gl3wProgramUniform3fv = (PFNGLPROGRAMUNIFORM3FVPROC)proc("glProgramUniform3fv"); - gl3wProgramUniform3fvEXT = (PFNGLPROGRAMUNIFORM3FVEXTPROC)proc("glProgramUniform3fvEXT"); - gl3wProgramUniform3i = (PFNGLPROGRAMUNIFORM3IPROC)proc("glProgramUniform3i"); - gl3wProgramUniform3i64ARB = (PFNGLPROGRAMUNIFORM3I64ARBPROC)proc("glProgramUniform3i64ARB"); - gl3wProgramUniform3i64NV = (PFNGLPROGRAMUNIFORM3I64NVPROC)proc("glProgramUniform3i64NV"); - gl3wProgramUniform3i64vARB = (PFNGLPROGRAMUNIFORM3I64VARBPROC)proc("glProgramUniform3i64vARB"); - gl3wProgramUniform3i64vNV = (PFNGLPROGRAMUNIFORM3I64VNVPROC)proc("glProgramUniform3i64vNV"); - gl3wProgramUniform3iEXT = (PFNGLPROGRAMUNIFORM3IEXTPROC)proc("glProgramUniform3iEXT"); - gl3wProgramUniform3iv = (PFNGLPROGRAMUNIFORM3IVPROC)proc("glProgramUniform3iv"); - gl3wProgramUniform3ivEXT = (PFNGLPROGRAMUNIFORM3IVEXTPROC)proc("glProgramUniform3ivEXT"); - gl3wProgramUniform3ui = (PFNGLPROGRAMUNIFORM3UIPROC)proc("glProgramUniform3ui"); - gl3wProgramUniform3ui64ARB = (PFNGLPROGRAMUNIFORM3UI64ARBPROC)proc("glProgramUniform3ui64ARB"); - gl3wProgramUniform3ui64NV = (PFNGLPROGRAMUNIFORM3UI64NVPROC)proc("glProgramUniform3ui64NV"); - gl3wProgramUniform3ui64vARB = (PFNGLPROGRAMUNIFORM3UI64VARBPROC)proc("glProgramUniform3ui64vARB"); - gl3wProgramUniform3ui64vNV = (PFNGLPROGRAMUNIFORM3UI64VNVPROC)proc("glProgramUniform3ui64vNV"); - gl3wProgramUniform3uiEXT = (PFNGLPROGRAMUNIFORM3UIEXTPROC)proc("glProgramUniform3uiEXT"); - gl3wProgramUniform3uiv = (PFNGLPROGRAMUNIFORM3UIVPROC)proc("glProgramUniform3uiv"); - gl3wProgramUniform3uivEXT = (PFNGLPROGRAMUNIFORM3UIVEXTPROC)proc("glProgramUniform3uivEXT"); - gl3wProgramUniform4d = (PFNGLPROGRAMUNIFORM4DPROC)proc("glProgramUniform4d"); - gl3wProgramUniform4dEXT = (PFNGLPROGRAMUNIFORM4DEXTPROC)proc("glProgramUniform4dEXT"); - gl3wProgramUniform4dv = (PFNGLPROGRAMUNIFORM4DVPROC)proc("glProgramUniform4dv"); - gl3wProgramUniform4dvEXT = (PFNGLPROGRAMUNIFORM4DVEXTPROC)proc("glProgramUniform4dvEXT"); - gl3wProgramUniform4f = (PFNGLPROGRAMUNIFORM4FPROC)proc("glProgramUniform4f"); - gl3wProgramUniform4fEXT = (PFNGLPROGRAMUNIFORM4FEXTPROC)proc("glProgramUniform4fEXT"); - gl3wProgramUniform4fv = (PFNGLPROGRAMUNIFORM4FVPROC)proc("glProgramUniform4fv"); - gl3wProgramUniform4fvEXT = (PFNGLPROGRAMUNIFORM4FVEXTPROC)proc("glProgramUniform4fvEXT"); - gl3wProgramUniform4i = (PFNGLPROGRAMUNIFORM4IPROC)proc("glProgramUniform4i"); - gl3wProgramUniform4i64ARB = (PFNGLPROGRAMUNIFORM4I64ARBPROC)proc("glProgramUniform4i64ARB"); - gl3wProgramUniform4i64NV = (PFNGLPROGRAMUNIFORM4I64NVPROC)proc("glProgramUniform4i64NV"); - gl3wProgramUniform4i64vARB = (PFNGLPROGRAMUNIFORM4I64VARBPROC)proc("glProgramUniform4i64vARB"); - gl3wProgramUniform4i64vNV = (PFNGLPROGRAMUNIFORM4I64VNVPROC)proc("glProgramUniform4i64vNV"); - gl3wProgramUniform4iEXT = (PFNGLPROGRAMUNIFORM4IEXTPROC)proc("glProgramUniform4iEXT"); - gl3wProgramUniform4iv = (PFNGLPROGRAMUNIFORM4IVPROC)proc("glProgramUniform4iv"); - gl3wProgramUniform4ivEXT = (PFNGLPROGRAMUNIFORM4IVEXTPROC)proc("glProgramUniform4ivEXT"); - gl3wProgramUniform4ui = (PFNGLPROGRAMUNIFORM4UIPROC)proc("glProgramUniform4ui"); - gl3wProgramUniform4ui64ARB = (PFNGLPROGRAMUNIFORM4UI64ARBPROC)proc("glProgramUniform4ui64ARB"); - gl3wProgramUniform4ui64NV = (PFNGLPROGRAMUNIFORM4UI64NVPROC)proc("glProgramUniform4ui64NV"); - gl3wProgramUniform4ui64vARB = (PFNGLPROGRAMUNIFORM4UI64VARBPROC)proc("glProgramUniform4ui64vARB"); - gl3wProgramUniform4ui64vNV = (PFNGLPROGRAMUNIFORM4UI64VNVPROC)proc("glProgramUniform4ui64vNV"); - gl3wProgramUniform4uiEXT = (PFNGLPROGRAMUNIFORM4UIEXTPROC)proc("glProgramUniform4uiEXT"); - gl3wProgramUniform4uiv = (PFNGLPROGRAMUNIFORM4UIVPROC)proc("glProgramUniform4uiv"); - gl3wProgramUniform4uivEXT = (PFNGLPROGRAMUNIFORM4UIVEXTPROC)proc("glProgramUniform4uivEXT"); - gl3wProgramUniformHandleui64ARB = (PFNGLPROGRAMUNIFORMHANDLEUI64ARBPROC)proc("glProgramUniformHandleui64ARB"); - gl3wProgramUniformHandleui64NV = (PFNGLPROGRAMUNIFORMHANDLEUI64NVPROC)proc("glProgramUniformHandleui64NV"); - gl3wProgramUniformHandleui64vARB = (PFNGLPROGRAMUNIFORMHANDLEUI64VARBPROC)proc("glProgramUniformHandleui64vARB"); - gl3wProgramUniformHandleui64vNV = (PFNGLPROGRAMUNIFORMHANDLEUI64VNVPROC)proc("glProgramUniformHandleui64vNV"); - gl3wProgramUniformMatrix2dv = (PFNGLPROGRAMUNIFORMMATRIX2DVPROC)proc("glProgramUniformMatrix2dv"); - gl3wProgramUniformMatrix2dvEXT = (PFNGLPROGRAMUNIFORMMATRIX2DVEXTPROC)proc("glProgramUniformMatrix2dvEXT"); - gl3wProgramUniformMatrix2fv = (PFNGLPROGRAMUNIFORMMATRIX2FVPROC)proc("glProgramUniformMatrix2fv"); - gl3wProgramUniformMatrix2fvEXT = (PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC)proc("glProgramUniformMatrix2fvEXT"); - gl3wProgramUniformMatrix2x3dv = (PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC)proc("glProgramUniformMatrix2x3dv"); - gl3wProgramUniformMatrix2x3dvEXT = (PFNGLPROGRAMUNIFORMMATRIX2X3DVEXTPROC)proc("glProgramUniformMatrix2x3dvEXT"); - gl3wProgramUniformMatrix2x3fv = (PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC)proc("glProgramUniformMatrix2x3fv"); - gl3wProgramUniformMatrix2x3fvEXT = (PFNGLPROGRAMUNIFORMMATRIX2X3FVEXTPROC)proc("glProgramUniformMatrix2x3fvEXT"); - gl3wProgramUniformMatrix2x4dv = (PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC)proc("glProgramUniformMatrix2x4dv"); - gl3wProgramUniformMatrix2x4dvEXT = (PFNGLPROGRAMUNIFORMMATRIX2X4DVEXTPROC)proc("glProgramUniformMatrix2x4dvEXT"); - gl3wProgramUniformMatrix2x4fv = (PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC)proc("glProgramUniformMatrix2x4fv"); - gl3wProgramUniformMatrix2x4fvEXT = (PFNGLPROGRAMUNIFORMMATRIX2X4FVEXTPROC)proc("glProgramUniformMatrix2x4fvEXT"); - gl3wProgramUniformMatrix3dv = (PFNGLPROGRAMUNIFORMMATRIX3DVPROC)proc("glProgramUniformMatrix3dv"); - gl3wProgramUniformMatrix3dvEXT = (PFNGLPROGRAMUNIFORMMATRIX3DVEXTPROC)proc("glProgramUniformMatrix3dvEXT"); - gl3wProgramUniformMatrix3fv = (PFNGLPROGRAMUNIFORMMATRIX3FVPROC)proc("glProgramUniformMatrix3fv"); - gl3wProgramUniformMatrix3fvEXT = (PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC)proc("glProgramUniformMatrix3fvEXT"); - gl3wProgramUniformMatrix3x2dv = (PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC)proc("glProgramUniformMatrix3x2dv"); - gl3wProgramUniformMatrix3x2dvEXT = (PFNGLPROGRAMUNIFORMMATRIX3X2DVEXTPROC)proc("glProgramUniformMatrix3x2dvEXT"); - gl3wProgramUniformMatrix3x2fv = (PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC)proc("glProgramUniformMatrix3x2fv"); - gl3wProgramUniformMatrix3x2fvEXT = (PFNGLPROGRAMUNIFORMMATRIX3X2FVEXTPROC)proc("glProgramUniformMatrix3x2fvEXT"); - gl3wProgramUniformMatrix3x4dv = (PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC)proc("glProgramUniformMatrix3x4dv"); - gl3wProgramUniformMatrix3x4dvEXT = (PFNGLPROGRAMUNIFORMMATRIX3X4DVEXTPROC)proc("glProgramUniformMatrix3x4dvEXT"); - gl3wProgramUniformMatrix3x4fv = (PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC)proc("glProgramUniformMatrix3x4fv"); - gl3wProgramUniformMatrix3x4fvEXT = (PFNGLPROGRAMUNIFORMMATRIX3X4FVEXTPROC)proc("glProgramUniformMatrix3x4fvEXT"); - gl3wProgramUniformMatrix4dv = (PFNGLPROGRAMUNIFORMMATRIX4DVPROC)proc("glProgramUniformMatrix4dv"); - gl3wProgramUniformMatrix4dvEXT = (PFNGLPROGRAMUNIFORMMATRIX4DVEXTPROC)proc("glProgramUniformMatrix4dvEXT"); - gl3wProgramUniformMatrix4fv = (PFNGLPROGRAMUNIFORMMATRIX4FVPROC)proc("glProgramUniformMatrix4fv"); - gl3wProgramUniformMatrix4fvEXT = (PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC)proc("glProgramUniformMatrix4fvEXT"); - gl3wProgramUniformMatrix4x2dv = (PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC)proc("glProgramUniformMatrix4x2dv"); - gl3wProgramUniformMatrix4x2dvEXT = (PFNGLPROGRAMUNIFORMMATRIX4X2DVEXTPROC)proc("glProgramUniformMatrix4x2dvEXT"); - gl3wProgramUniformMatrix4x2fv = (PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC)proc("glProgramUniformMatrix4x2fv"); - gl3wProgramUniformMatrix4x2fvEXT = (PFNGLPROGRAMUNIFORMMATRIX4X2FVEXTPROC)proc("glProgramUniformMatrix4x2fvEXT"); - gl3wProgramUniformMatrix4x3dv = (PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC)proc("glProgramUniformMatrix4x3dv"); - gl3wProgramUniformMatrix4x3dvEXT = (PFNGLPROGRAMUNIFORMMATRIX4X3DVEXTPROC)proc("glProgramUniformMatrix4x3dvEXT"); - gl3wProgramUniformMatrix4x3fv = (PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC)proc("glProgramUniformMatrix4x3fv"); - gl3wProgramUniformMatrix4x3fvEXT = (PFNGLPROGRAMUNIFORMMATRIX4X3FVEXTPROC)proc("glProgramUniformMatrix4x3fvEXT"); - gl3wProgramUniformui64NV = (PFNGLPROGRAMUNIFORMUI64NVPROC)proc("glProgramUniformui64NV"); - gl3wProgramUniformui64vNV = (PFNGLPROGRAMUNIFORMUI64VNVPROC)proc("glProgramUniformui64vNV"); - gl3wProvokingVertex = (PFNGLPROVOKINGVERTEXPROC)proc("glProvokingVertex"); - gl3wPushClientAttribDefaultEXT = (PFNGLPUSHCLIENTATTRIBDEFAULTEXTPROC)proc("glPushClientAttribDefaultEXT"); - gl3wPushDebugGroup = (PFNGLPUSHDEBUGGROUPPROC)proc("glPushDebugGroup"); - gl3wPushGroupMarkerEXT = (PFNGLPUSHGROUPMARKEREXTPROC)proc("glPushGroupMarkerEXT"); - gl3wQueryCounter = (PFNGLQUERYCOUNTERPROC)proc("glQueryCounter"); - gl3wRasterSamplesEXT = (PFNGLRASTERSAMPLESEXTPROC)proc("glRasterSamplesEXT"); - gl3wReadBuffer = (PFNGLREADBUFFERPROC)proc("glReadBuffer"); - gl3wReadPixels = (PFNGLREADPIXELSPROC)proc("glReadPixels"); - gl3wReadnPixels = (PFNGLREADNPIXELSPROC)proc("glReadnPixels"); - gl3wReadnPixelsARB = (PFNGLREADNPIXELSARBPROC)proc("glReadnPixelsARB"); - gl3wReleaseShaderCompiler = (PFNGLRELEASESHADERCOMPILERPROC)proc("glReleaseShaderCompiler"); - gl3wRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)proc("glRenderbufferStorage"); - gl3wRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)proc("glRenderbufferStorageMultisample"); - gl3wRenderbufferStorageMultisampleCoverageNV = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLECOVERAGENVPROC)proc("glRenderbufferStorageMultisampleCoverageNV"); - gl3wResolveDepthValuesNV = (PFNGLRESOLVEDEPTHVALUESNVPROC)proc("glResolveDepthValuesNV"); - gl3wResumeTransformFeedback = (PFNGLRESUMETRANSFORMFEEDBACKPROC)proc("glResumeTransformFeedback"); - gl3wSampleCoverage = (PFNGLSAMPLECOVERAGEPROC)proc("glSampleCoverage"); - gl3wSampleMaski = (PFNGLSAMPLEMASKIPROC)proc("glSampleMaski"); - gl3wSamplerParameterIiv = (PFNGLSAMPLERPARAMETERIIVPROC)proc("glSamplerParameterIiv"); - gl3wSamplerParameterIuiv = (PFNGLSAMPLERPARAMETERIUIVPROC)proc("glSamplerParameterIuiv"); - gl3wSamplerParameterf = (PFNGLSAMPLERPARAMETERFPROC)proc("glSamplerParameterf"); - gl3wSamplerParameterfv = (PFNGLSAMPLERPARAMETERFVPROC)proc("glSamplerParameterfv"); - gl3wSamplerParameteri = (PFNGLSAMPLERPARAMETERIPROC)proc("glSamplerParameteri"); - gl3wSamplerParameteriv = (PFNGLSAMPLERPARAMETERIVPROC)proc("glSamplerParameteriv"); - gl3wScissor = (PFNGLSCISSORPROC)proc("glScissor"); - gl3wScissorArrayv = (PFNGLSCISSORARRAYVPROC)proc("glScissorArrayv"); - gl3wScissorIndexed = (PFNGLSCISSORINDEXEDPROC)proc("glScissorIndexed"); - gl3wScissorIndexedv = (PFNGLSCISSORINDEXEDVPROC)proc("glScissorIndexedv"); - gl3wSecondaryColorFormatNV = (PFNGLSECONDARYCOLORFORMATNVPROC)proc("glSecondaryColorFormatNV"); - gl3wSelectPerfMonitorCountersAMD = (PFNGLSELECTPERFMONITORCOUNTERSAMDPROC)proc("glSelectPerfMonitorCountersAMD"); - gl3wShaderBinary = (PFNGLSHADERBINARYPROC)proc("glShaderBinary"); - gl3wShaderSource = (PFNGLSHADERSOURCEPROC)proc("glShaderSource"); - gl3wShaderStorageBlockBinding = (PFNGLSHADERSTORAGEBLOCKBINDINGPROC)proc("glShaderStorageBlockBinding"); - gl3wSignalVkFenceNV = (PFNGLSIGNALVKFENCENVPROC)proc("glSignalVkFenceNV"); - gl3wSignalVkSemaphoreNV = (PFNGLSIGNALVKSEMAPHORENVPROC)proc("glSignalVkSemaphoreNV"); - gl3wSpecializeShader = (PFNGLSPECIALIZESHADERPROC)proc("glSpecializeShader"); - gl3wSpecializeShaderARB = (PFNGLSPECIALIZESHADERARBPROC)proc("glSpecializeShaderARB"); - gl3wStateCaptureNV = (PFNGLSTATECAPTURENVPROC)proc("glStateCaptureNV"); - gl3wStencilFillPathInstancedNV = (PFNGLSTENCILFILLPATHINSTANCEDNVPROC)proc("glStencilFillPathInstancedNV"); - gl3wStencilFillPathNV = (PFNGLSTENCILFILLPATHNVPROC)proc("glStencilFillPathNV"); - gl3wStencilFunc = (PFNGLSTENCILFUNCPROC)proc("glStencilFunc"); - gl3wStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)proc("glStencilFuncSeparate"); - gl3wStencilMask = (PFNGLSTENCILMASKPROC)proc("glStencilMask"); - gl3wStencilMaskSeparate = (PFNGLSTENCILMASKSEPARATEPROC)proc("glStencilMaskSeparate"); - gl3wStencilOp = (PFNGLSTENCILOPPROC)proc("glStencilOp"); - gl3wStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)proc("glStencilOpSeparate"); - gl3wStencilStrokePathInstancedNV = (PFNGLSTENCILSTROKEPATHINSTANCEDNVPROC)proc("glStencilStrokePathInstancedNV"); - gl3wStencilStrokePathNV = (PFNGLSTENCILSTROKEPATHNVPROC)proc("glStencilStrokePathNV"); - gl3wStencilThenCoverFillPathInstancedNV = (PFNGLSTENCILTHENCOVERFILLPATHINSTANCEDNVPROC)proc("glStencilThenCoverFillPathInstancedNV"); - gl3wStencilThenCoverFillPathNV = (PFNGLSTENCILTHENCOVERFILLPATHNVPROC)proc("glStencilThenCoverFillPathNV"); - gl3wStencilThenCoverStrokePathInstancedNV = (PFNGLSTENCILTHENCOVERSTROKEPATHINSTANCEDNVPROC)proc("glStencilThenCoverStrokePathInstancedNV"); - gl3wStencilThenCoverStrokePathNV = (PFNGLSTENCILTHENCOVERSTROKEPATHNVPROC)proc("glStencilThenCoverStrokePathNV"); - gl3wSubpixelPrecisionBiasNV = (PFNGLSUBPIXELPRECISIONBIASNVPROC)proc("glSubpixelPrecisionBiasNV"); - gl3wTexBuffer = (PFNGLTEXBUFFERPROC)proc("glTexBuffer"); - gl3wTexBufferARB = (PFNGLTEXBUFFERARBPROC)proc("glTexBufferARB"); - gl3wTexBufferRange = (PFNGLTEXBUFFERRANGEPROC)proc("glTexBufferRange"); - gl3wTexCoordFormatNV = (PFNGLTEXCOORDFORMATNVPROC)proc("glTexCoordFormatNV"); - gl3wTexImage1D = (PFNGLTEXIMAGE1DPROC)proc("glTexImage1D"); - gl3wTexImage2D = (PFNGLTEXIMAGE2DPROC)proc("glTexImage2D"); - gl3wTexImage2DMultisample = (PFNGLTEXIMAGE2DMULTISAMPLEPROC)proc("glTexImage2DMultisample"); - gl3wTexImage3D = (PFNGLTEXIMAGE3DPROC)proc("glTexImage3D"); - gl3wTexImage3DMultisample = (PFNGLTEXIMAGE3DMULTISAMPLEPROC)proc("glTexImage3DMultisample"); - gl3wTexPageCommitmentARB = (PFNGLTEXPAGECOMMITMENTARBPROC)proc("glTexPageCommitmentARB"); - gl3wTexParameterIiv = (PFNGLTEXPARAMETERIIVPROC)proc("glTexParameterIiv"); - gl3wTexParameterIuiv = (PFNGLTEXPARAMETERIUIVPROC)proc("glTexParameterIuiv"); - gl3wTexParameterf = (PFNGLTEXPARAMETERFPROC)proc("glTexParameterf"); - gl3wTexParameterfv = (PFNGLTEXPARAMETERFVPROC)proc("glTexParameterfv"); - gl3wTexParameteri = (PFNGLTEXPARAMETERIPROC)proc("glTexParameteri"); - gl3wTexParameteriv = (PFNGLTEXPARAMETERIVPROC)proc("glTexParameteriv"); - gl3wTexStorage1D = (PFNGLTEXSTORAGE1DPROC)proc("glTexStorage1D"); - gl3wTexStorage2D = (PFNGLTEXSTORAGE2DPROC)proc("glTexStorage2D"); - gl3wTexStorage2DMultisample = (PFNGLTEXSTORAGE2DMULTISAMPLEPROC)proc("glTexStorage2DMultisample"); - gl3wTexStorage3D = (PFNGLTEXSTORAGE3DPROC)proc("glTexStorage3D"); - gl3wTexStorage3DMultisample = (PFNGLTEXSTORAGE3DMULTISAMPLEPROC)proc("glTexStorage3DMultisample"); - gl3wTexSubImage1D = (PFNGLTEXSUBIMAGE1DPROC)proc("glTexSubImage1D"); - gl3wTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC)proc("glTexSubImage2D"); - gl3wTexSubImage3D = (PFNGLTEXSUBIMAGE3DPROC)proc("glTexSubImage3D"); - gl3wTextureBarrier = (PFNGLTEXTUREBARRIERPROC)proc("glTextureBarrier"); - gl3wTextureBarrierNV = (PFNGLTEXTUREBARRIERNVPROC)proc("glTextureBarrierNV"); - gl3wTextureBuffer = (PFNGLTEXTUREBUFFERPROC)proc("glTextureBuffer"); - gl3wTextureBufferEXT = (PFNGLTEXTUREBUFFEREXTPROC)proc("glTextureBufferEXT"); - gl3wTextureBufferRange = (PFNGLTEXTUREBUFFERRANGEPROC)proc("glTextureBufferRange"); - gl3wTextureBufferRangeEXT = (PFNGLTEXTUREBUFFERRANGEEXTPROC)proc("glTextureBufferRangeEXT"); - gl3wTextureImage1DEXT = (PFNGLTEXTUREIMAGE1DEXTPROC)proc("glTextureImage1DEXT"); - gl3wTextureImage2DEXT = (PFNGLTEXTUREIMAGE2DEXTPROC)proc("glTextureImage2DEXT"); - gl3wTextureImage3DEXT = (PFNGLTEXTUREIMAGE3DEXTPROC)proc("glTextureImage3DEXT"); - gl3wTexturePageCommitmentEXT = (PFNGLTEXTUREPAGECOMMITMENTEXTPROC)proc("glTexturePageCommitmentEXT"); - gl3wTextureParameterIiv = (PFNGLTEXTUREPARAMETERIIVPROC)proc("glTextureParameterIiv"); - gl3wTextureParameterIivEXT = (PFNGLTEXTUREPARAMETERIIVEXTPROC)proc("glTextureParameterIivEXT"); - gl3wTextureParameterIuiv = (PFNGLTEXTUREPARAMETERIUIVPROC)proc("glTextureParameterIuiv"); - gl3wTextureParameterIuivEXT = (PFNGLTEXTUREPARAMETERIUIVEXTPROC)proc("glTextureParameterIuivEXT"); - gl3wTextureParameterf = (PFNGLTEXTUREPARAMETERFPROC)proc("glTextureParameterf"); - gl3wTextureParameterfEXT = (PFNGLTEXTUREPARAMETERFEXTPROC)proc("glTextureParameterfEXT"); - gl3wTextureParameterfv = (PFNGLTEXTUREPARAMETERFVPROC)proc("glTextureParameterfv"); - gl3wTextureParameterfvEXT = (PFNGLTEXTUREPARAMETERFVEXTPROC)proc("glTextureParameterfvEXT"); - gl3wTextureParameteri = (PFNGLTEXTUREPARAMETERIPROC)proc("glTextureParameteri"); - gl3wTextureParameteriEXT = (PFNGLTEXTUREPARAMETERIEXTPROC)proc("glTextureParameteriEXT"); - gl3wTextureParameteriv = (PFNGLTEXTUREPARAMETERIVPROC)proc("glTextureParameteriv"); - gl3wTextureParameterivEXT = (PFNGLTEXTUREPARAMETERIVEXTPROC)proc("glTextureParameterivEXT"); - gl3wTextureRenderbufferEXT = (PFNGLTEXTURERENDERBUFFEREXTPROC)proc("glTextureRenderbufferEXT"); - gl3wTextureStorage1D = (PFNGLTEXTURESTORAGE1DPROC)proc("glTextureStorage1D"); - gl3wTextureStorage1DEXT = (PFNGLTEXTURESTORAGE1DEXTPROC)proc("glTextureStorage1DEXT"); - gl3wTextureStorage2D = (PFNGLTEXTURESTORAGE2DPROC)proc("glTextureStorage2D"); - gl3wTextureStorage2DEXT = (PFNGLTEXTURESTORAGE2DEXTPROC)proc("glTextureStorage2DEXT"); - gl3wTextureStorage2DMultisample = (PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC)proc("glTextureStorage2DMultisample"); - gl3wTextureStorage2DMultisampleEXT = (PFNGLTEXTURESTORAGE2DMULTISAMPLEEXTPROC)proc("glTextureStorage2DMultisampleEXT"); - gl3wTextureStorage3D = (PFNGLTEXTURESTORAGE3DPROC)proc("glTextureStorage3D"); - gl3wTextureStorage3DEXT = (PFNGLTEXTURESTORAGE3DEXTPROC)proc("glTextureStorage3DEXT"); - gl3wTextureStorage3DMultisample = (PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC)proc("glTextureStorage3DMultisample"); - gl3wTextureStorage3DMultisampleEXT = (PFNGLTEXTURESTORAGE3DMULTISAMPLEEXTPROC)proc("glTextureStorage3DMultisampleEXT"); - gl3wTextureSubImage1D = (PFNGLTEXTURESUBIMAGE1DPROC)proc("glTextureSubImage1D"); - gl3wTextureSubImage1DEXT = (PFNGLTEXTURESUBIMAGE1DEXTPROC)proc("glTextureSubImage1DEXT"); - gl3wTextureSubImage2D = (PFNGLTEXTURESUBIMAGE2DPROC)proc("glTextureSubImage2D"); - gl3wTextureSubImage2DEXT = (PFNGLTEXTURESUBIMAGE2DEXTPROC)proc("glTextureSubImage2DEXT"); - gl3wTextureSubImage3D = (PFNGLTEXTURESUBIMAGE3DPROC)proc("glTextureSubImage3D"); - gl3wTextureSubImage3DEXT = (PFNGLTEXTURESUBIMAGE3DEXTPROC)proc("glTextureSubImage3DEXT"); - gl3wTextureView = (PFNGLTEXTUREVIEWPROC)proc("glTextureView"); - gl3wTransformFeedbackBufferBase = (PFNGLTRANSFORMFEEDBACKBUFFERBASEPROC)proc("glTransformFeedbackBufferBase"); - gl3wTransformFeedbackBufferRange = (PFNGLTRANSFORMFEEDBACKBUFFERRANGEPROC)proc("glTransformFeedbackBufferRange"); - gl3wTransformFeedbackVaryings = (PFNGLTRANSFORMFEEDBACKVARYINGSPROC)proc("glTransformFeedbackVaryings"); - gl3wTransformPathNV = (PFNGLTRANSFORMPATHNVPROC)proc("glTransformPathNV"); - gl3wUniform1d = (PFNGLUNIFORM1DPROC)proc("glUniform1d"); - gl3wUniform1dv = (PFNGLUNIFORM1DVPROC)proc("glUniform1dv"); - gl3wUniform1f = (PFNGLUNIFORM1FPROC)proc("glUniform1f"); - gl3wUniform1fv = (PFNGLUNIFORM1FVPROC)proc("glUniform1fv"); - gl3wUniform1i = (PFNGLUNIFORM1IPROC)proc("glUniform1i"); - gl3wUniform1i64ARB = (PFNGLUNIFORM1I64ARBPROC)proc("glUniform1i64ARB"); - gl3wUniform1i64NV = (PFNGLUNIFORM1I64NVPROC)proc("glUniform1i64NV"); - gl3wUniform1i64vARB = (PFNGLUNIFORM1I64VARBPROC)proc("glUniform1i64vARB"); - gl3wUniform1i64vNV = (PFNGLUNIFORM1I64VNVPROC)proc("glUniform1i64vNV"); - gl3wUniform1iv = (PFNGLUNIFORM1IVPROC)proc("glUniform1iv"); - gl3wUniform1ui = (PFNGLUNIFORM1UIPROC)proc("glUniform1ui"); - gl3wUniform1ui64ARB = (PFNGLUNIFORM1UI64ARBPROC)proc("glUniform1ui64ARB"); - gl3wUniform1ui64NV = (PFNGLUNIFORM1UI64NVPROC)proc("glUniform1ui64NV"); - gl3wUniform1ui64vARB = (PFNGLUNIFORM1UI64VARBPROC)proc("glUniform1ui64vARB"); - gl3wUniform1ui64vNV = (PFNGLUNIFORM1UI64VNVPROC)proc("glUniform1ui64vNV"); - gl3wUniform1uiv = (PFNGLUNIFORM1UIVPROC)proc("glUniform1uiv"); - gl3wUniform2d = (PFNGLUNIFORM2DPROC)proc("glUniform2d"); - gl3wUniform2dv = (PFNGLUNIFORM2DVPROC)proc("glUniform2dv"); - gl3wUniform2f = (PFNGLUNIFORM2FPROC)proc("glUniform2f"); - gl3wUniform2fv = (PFNGLUNIFORM2FVPROC)proc("glUniform2fv"); - gl3wUniform2i = (PFNGLUNIFORM2IPROC)proc("glUniform2i"); - gl3wUniform2i64ARB = (PFNGLUNIFORM2I64ARBPROC)proc("glUniform2i64ARB"); - gl3wUniform2i64NV = (PFNGLUNIFORM2I64NVPROC)proc("glUniform2i64NV"); - gl3wUniform2i64vARB = (PFNGLUNIFORM2I64VARBPROC)proc("glUniform2i64vARB"); - gl3wUniform2i64vNV = (PFNGLUNIFORM2I64VNVPROC)proc("glUniform2i64vNV"); - gl3wUniform2iv = (PFNGLUNIFORM2IVPROC)proc("glUniform2iv"); - gl3wUniform2ui = (PFNGLUNIFORM2UIPROC)proc("glUniform2ui"); - gl3wUniform2ui64ARB = (PFNGLUNIFORM2UI64ARBPROC)proc("glUniform2ui64ARB"); - gl3wUniform2ui64NV = (PFNGLUNIFORM2UI64NVPROC)proc("glUniform2ui64NV"); - gl3wUniform2ui64vARB = (PFNGLUNIFORM2UI64VARBPROC)proc("glUniform2ui64vARB"); - gl3wUniform2ui64vNV = (PFNGLUNIFORM2UI64VNVPROC)proc("glUniform2ui64vNV"); - gl3wUniform2uiv = (PFNGLUNIFORM2UIVPROC)proc("glUniform2uiv"); - gl3wUniform3d = (PFNGLUNIFORM3DPROC)proc("glUniform3d"); - gl3wUniform3dv = (PFNGLUNIFORM3DVPROC)proc("glUniform3dv"); - gl3wUniform3f = (PFNGLUNIFORM3FPROC)proc("glUniform3f"); - gl3wUniform3fv = (PFNGLUNIFORM3FVPROC)proc("glUniform3fv"); - gl3wUniform3i = (PFNGLUNIFORM3IPROC)proc("glUniform3i"); - gl3wUniform3i64ARB = (PFNGLUNIFORM3I64ARBPROC)proc("glUniform3i64ARB"); - gl3wUniform3i64NV = (PFNGLUNIFORM3I64NVPROC)proc("glUniform3i64NV"); - gl3wUniform3i64vARB = (PFNGLUNIFORM3I64VARBPROC)proc("glUniform3i64vARB"); - gl3wUniform3i64vNV = (PFNGLUNIFORM3I64VNVPROC)proc("glUniform3i64vNV"); - gl3wUniform3iv = (PFNGLUNIFORM3IVPROC)proc("glUniform3iv"); - gl3wUniform3ui = (PFNGLUNIFORM3UIPROC)proc("glUniform3ui"); - gl3wUniform3ui64ARB = (PFNGLUNIFORM3UI64ARBPROC)proc("glUniform3ui64ARB"); - gl3wUniform3ui64NV = (PFNGLUNIFORM3UI64NVPROC)proc("glUniform3ui64NV"); - gl3wUniform3ui64vARB = (PFNGLUNIFORM3UI64VARBPROC)proc("glUniform3ui64vARB"); - gl3wUniform3ui64vNV = (PFNGLUNIFORM3UI64VNVPROC)proc("glUniform3ui64vNV"); - gl3wUniform3uiv = (PFNGLUNIFORM3UIVPROC)proc("glUniform3uiv"); - gl3wUniform4d = (PFNGLUNIFORM4DPROC)proc("glUniform4d"); - gl3wUniform4dv = (PFNGLUNIFORM4DVPROC)proc("glUniform4dv"); - gl3wUniform4f = (PFNGLUNIFORM4FPROC)proc("glUniform4f"); - gl3wUniform4fv = (PFNGLUNIFORM4FVPROC)proc("glUniform4fv"); - gl3wUniform4i = (PFNGLUNIFORM4IPROC)proc("glUniform4i"); - gl3wUniform4i64ARB = (PFNGLUNIFORM4I64ARBPROC)proc("glUniform4i64ARB"); - gl3wUniform4i64NV = (PFNGLUNIFORM4I64NVPROC)proc("glUniform4i64NV"); - gl3wUniform4i64vARB = (PFNGLUNIFORM4I64VARBPROC)proc("glUniform4i64vARB"); - gl3wUniform4i64vNV = (PFNGLUNIFORM4I64VNVPROC)proc("glUniform4i64vNV"); - gl3wUniform4iv = (PFNGLUNIFORM4IVPROC)proc("glUniform4iv"); - gl3wUniform4ui = (PFNGLUNIFORM4UIPROC)proc("glUniform4ui"); - gl3wUniform4ui64ARB = (PFNGLUNIFORM4UI64ARBPROC)proc("glUniform4ui64ARB"); - gl3wUniform4ui64NV = (PFNGLUNIFORM4UI64NVPROC)proc("glUniform4ui64NV"); - gl3wUniform4ui64vARB = (PFNGLUNIFORM4UI64VARBPROC)proc("glUniform4ui64vARB"); - gl3wUniform4ui64vNV = (PFNGLUNIFORM4UI64VNVPROC)proc("glUniform4ui64vNV"); - gl3wUniform4uiv = (PFNGLUNIFORM4UIVPROC)proc("glUniform4uiv"); - gl3wUniformBlockBinding = (PFNGLUNIFORMBLOCKBINDINGPROC)proc("glUniformBlockBinding"); - gl3wUniformHandleui64ARB = (PFNGLUNIFORMHANDLEUI64ARBPROC)proc("glUniformHandleui64ARB"); - gl3wUniformHandleui64NV = (PFNGLUNIFORMHANDLEUI64NVPROC)proc("glUniformHandleui64NV"); - gl3wUniformHandleui64vARB = (PFNGLUNIFORMHANDLEUI64VARBPROC)proc("glUniformHandleui64vARB"); - gl3wUniformHandleui64vNV = (PFNGLUNIFORMHANDLEUI64VNVPROC)proc("glUniformHandleui64vNV"); - gl3wUniformMatrix2dv = (PFNGLUNIFORMMATRIX2DVPROC)proc("glUniformMatrix2dv"); - gl3wUniformMatrix2fv = (PFNGLUNIFORMMATRIX2FVPROC)proc("glUniformMatrix2fv"); - gl3wUniformMatrix2x3dv = (PFNGLUNIFORMMATRIX2X3DVPROC)proc("glUniformMatrix2x3dv"); - gl3wUniformMatrix2x3fv = (PFNGLUNIFORMMATRIX2X3FVPROC)proc("glUniformMatrix2x3fv"); - gl3wUniformMatrix2x4dv = (PFNGLUNIFORMMATRIX2X4DVPROC)proc("glUniformMatrix2x4dv"); - gl3wUniformMatrix2x4fv = (PFNGLUNIFORMMATRIX2X4FVPROC)proc("glUniformMatrix2x4fv"); - gl3wUniformMatrix3dv = (PFNGLUNIFORMMATRIX3DVPROC)proc("glUniformMatrix3dv"); - gl3wUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)proc("glUniformMatrix3fv"); - gl3wUniformMatrix3x2dv = (PFNGLUNIFORMMATRIX3X2DVPROC)proc("glUniformMatrix3x2dv"); - gl3wUniformMatrix3x2fv = (PFNGLUNIFORMMATRIX3X2FVPROC)proc("glUniformMatrix3x2fv"); - gl3wUniformMatrix3x4dv = (PFNGLUNIFORMMATRIX3X4DVPROC)proc("glUniformMatrix3x4dv"); - gl3wUniformMatrix3x4fv = (PFNGLUNIFORMMATRIX3X4FVPROC)proc("glUniformMatrix3x4fv"); - gl3wUniformMatrix4dv = (PFNGLUNIFORMMATRIX4DVPROC)proc("glUniformMatrix4dv"); - gl3wUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)proc("glUniformMatrix4fv"); - gl3wUniformMatrix4x2dv = (PFNGLUNIFORMMATRIX4X2DVPROC)proc("glUniformMatrix4x2dv"); - gl3wUniformMatrix4x2fv = (PFNGLUNIFORMMATRIX4X2FVPROC)proc("glUniformMatrix4x2fv"); - gl3wUniformMatrix4x3dv = (PFNGLUNIFORMMATRIX4X3DVPROC)proc("glUniformMatrix4x3dv"); - gl3wUniformMatrix4x3fv = (PFNGLUNIFORMMATRIX4X3FVPROC)proc("glUniformMatrix4x3fv"); - gl3wUniformSubroutinesuiv = (PFNGLUNIFORMSUBROUTINESUIVPROC)proc("glUniformSubroutinesuiv"); - gl3wUniformui64NV = (PFNGLUNIFORMUI64NVPROC)proc("glUniformui64NV"); - gl3wUniformui64vNV = (PFNGLUNIFORMUI64VNVPROC)proc("glUniformui64vNV"); - gl3wUnmapBuffer = (PFNGLUNMAPBUFFERPROC)proc("glUnmapBuffer"); - gl3wUnmapNamedBuffer = (PFNGLUNMAPNAMEDBUFFERPROC)proc("glUnmapNamedBuffer"); - gl3wUnmapNamedBufferEXT = (PFNGLUNMAPNAMEDBUFFEREXTPROC)proc("glUnmapNamedBufferEXT"); - gl3wUseProgram = (PFNGLUSEPROGRAMPROC)proc("glUseProgram"); - gl3wUseProgramStages = (PFNGLUSEPROGRAMSTAGESPROC)proc("glUseProgramStages"); - gl3wUseShaderProgramEXT = (PFNGLUSESHADERPROGRAMEXTPROC)proc("glUseShaderProgramEXT"); - gl3wValidateProgram = (PFNGLVALIDATEPROGRAMPROC)proc("glValidateProgram"); - gl3wValidateProgramPipeline = (PFNGLVALIDATEPROGRAMPIPELINEPROC)proc("glValidateProgramPipeline"); - gl3wVertexArrayAttribBinding = (PFNGLVERTEXARRAYATTRIBBINDINGPROC)proc("glVertexArrayAttribBinding"); - gl3wVertexArrayAttribFormat = (PFNGLVERTEXARRAYATTRIBFORMATPROC)proc("glVertexArrayAttribFormat"); - gl3wVertexArrayAttribIFormat = (PFNGLVERTEXARRAYATTRIBIFORMATPROC)proc("glVertexArrayAttribIFormat"); - gl3wVertexArrayAttribLFormat = (PFNGLVERTEXARRAYATTRIBLFORMATPROC)proc("glVertexArrayAttribLFormat"); - gl3wVertexArrayBindVertexBufferEXT = (PFNGLVERTEXARRAYBINDVERTEXBUFFEREXTPROC)proc("glVertexArrayBindVertexBufferEXT"); - gl3wVertexArrayBindingDivisor = (PFNGLVERTEXARRAYBINDINGDIVISORPROC)proc("glVertexArrayBindingDivisor"); - gl3wVertexArrayColorOffsetEXT = (PFNGLVERTEXARRAYCOLOROFFSETEXTPROC)proc("glVertexArrayColorOffsetEXT"); - gl3wVertexArrayEdgeFlagOffsetEXT = (PFNGLVERTEXARRAYEDGEFLAGOFFSETEXTPROC)proc("glVertexArrayEdgeFlagOffsetEXT"); - gl3wVertexArrayElementBuffer = (PFNGLVERTEXARRAYELEMENTBUFFERPROC)proc("glVertexArrayElementBuffer"); - gl3wVertexArrayFogCoordOffsetEXT = (PFNGLVERTEXARRAYFOGCOORDOFFSETEXTPROC)proc("glVertexArrayFogCoordOffsetEXT"); - gl3wVertexArrayIndexOffsetEXT = (PFNGLVERTEXARRAYINDEXOFFSETEXTPROC)proc("glVertexArrayIndexOffsetEXT"); - gl3wVertexArrayMultiTexCoordOffsetEXT = (PFNGLVERTEXARRAYMULTITEXCOORDOFFSETEXTPROC)proc("glVertexArrayMultiTexCoordOffsetEXT"); - gl3wVertexArrayNormalOffsetEXT = (PFNGLVERTEXARRAYNORMALOFFSETEXTPROC)proc("glVertexArrayNormalOffsetEXT"); - gl3wVertexArraySecondaryColorOffsetEXT = (PFNGLVERTEXARRAYSECONDARYCOLOROFFSETEXTPROC)proc("glVertexArraySecondaryColorOffsetEXT"); - gl3wVertexArrayTexCoordOffsetEXT = (PFNGLVERTEXARRAYTEXCOORDOFFSETEXTPROC)proc("glVertexArrayTexCoordOffsetEXT"); - gl3wVertexArrayVertexAttribBindingEXT = (PFNGLVERTEXARRAYVERTEXATTRIBBINDINGEXTPROC)proc("glVertexArrayVertexAttribBindingEXT"); - gl3wVertexArrayVertexAttribDivisorEXT = (PFNGLVERTEXARRAYVERTEXATTRIBDIVISOREXTPROC)proc("glVertexArrayVertexAttribDivisorEXT"); - gl3wVertexArrayVertexAttribFormatEXT = (PFNGLVERTEXARRAYVERTEXATTRIBFORMATEXTPROC)proc("glVertexArrayVertexAttribFormatEXT"); - gl3wVertexArrayVertexAttribIFormatEXT = (PFNGLVERTEXARRAYVERTEXATTRIBIFORMATEXTPROC)proc("glVertexArrayVertexAttribIFormatEXT"); - gl3wVertexArrayVertexAttribIOffsetEXT = (PFNGLVERTEXARRAYVERTEXATTRIBIOFFSETEXTPROC)proc("glVertexArrayVertexAttribIOffsetEXT"); - gl3wVertexArrayVertexAttribLFormatEXT = (PFNGLVERTEXARRAYVERTEXATTRIBLFORMATEXTPROC)proc("glVertexArrayVertexAttribLFormatEXT"); - gl3wVertexArrayVertexAttribLOffsetEXT = (PFNGLVERTEXARRAYVERTEXATTRIBLOFFSETEXTPROC)proc("glVertexArrayVertexAttribLOffsetEXT"); - gl3wVertexArrayVertexAttribOffsetEXT = (PFNGLVERTEXARRAYVERTEXATTRIBOFFSETEXTPROC)proc("glVertexArrayVertexAttribOffsetEXT"); - gl3wVertexArrayVertexBindingDivisorEXT = (PFNGLVERTEXARRAYVERTEXBINDINGDIVISOREXTPROC)proc("glVertexArrayVertexBindingDivisorEXT"); - gl3wVertexArrayVertexBuffer = (PFNGLVERTEXARRAYVERTEXBUFFERPROC)proc("glVertexArrayVertexBuffer"); - gl3wVertexArrayVertexBuffers = (PFNGLVERTEXARRAYVERTEXBUFFERSPROC)proc("glVertexArrayVertexBuffers"); - gl3wVertexArrayVertexOffsetEXT = (PFNGLVERTEXARRAYVERTEXOFFSETEXTPROC)proc("glVertexArrayVertexOffsetEXT"); - gl3wVertexAttrib1d = (PFNGLVERTEXATTRIB1DPROC)proc("glVertexAttrib1d"); - gl3wVertexAttrib1dv = (PFNGLVERTEXATTRIB1DVPROC)proc("glVertexAttrib1dv"); - gl3wVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC)proc("glVertexAttrib1f"); - gl3wVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC)proc("glVertexAttrib1fv"); - gl3wVertexAttrib1s = (PFNGLVERTEXATTRIB1SPROC)proc("glVertexAttrib1s"); - gl3wVertexAttrib1sv = (PFNGLVERTEXATTRIB1SVPROC)proc("glVertexAttrib1sv"); - gl3wVertexAttrib2d = (PFNGLVERTEXATTRIB2DPROC)proc("glVertexAttrib2d"); - gl3wVertexAttrib2dv = (PFNGLVERTEXATTRIB2DVPROC)proc("glVertexAttrib2dv"); - gl3wVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC)proc("glVertexAttrib2f"); - gl3wVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC)proc("glVertexAttrib2fv"); - gl3wVertexAttrib2s = (PFNGLVERTEXATTRIB2SPROC)proc("glVertexAttrib2s"); - gl3wVertexAttrib2sv = (PFNGLVERTEXATTRIB2SVPROC)proc("glVertexAttrib2sv"); - gl3wVertexAttrib3d = (PFNGLVERTEXATTRIB3DPROC)proc("glVertexAttrib3d"); - gl3wVertexAttrib3dv = (PFNGLVERTEXATTRIB3DVPROC)proc("glVertexAttrib3dv"); - gl3wVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC)proc("glVertexAttrib3f"); - gl3wVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC)proc("glVertexAttrib3fv"); - gl3wVertexAttrib3s = (PFNGLVERTEXATTRIB3SPROC)proc("glVertexAttrib3s"); - gl3wVertexAttrib3sv = (PFNGLVERTEXATTRIB3SVPROC)proc("glVertexAttrib3sv"); - gl3wVertexAttrib4Nbv = (PFNGLVERTEXATTRIB4NBVPROC)proc("glVertexAttrib4Nbv"); - gl3wVertexAttrib4Niv = (PFNGLVERTEXATTRIB4NIVPROC)proc("glVertexAttrib4Niv"); - gl3wVertexAttrib4Nsv = (PFNGLVERTEXATTRIB4NSVPROC)proc("glVertexAttrib4Nsv"); - gl3wVertexAttrib4Nub = (PFNGLVERTEXATTRIB4NUBPROC)proc("glVertexAttrib4Nub"); - gl3wVertexAttrib4Nubv = (PFNGLVERTEXATTRIB4NUBVPROC)proc("glVertexAttrib4Nubv"); - gl3wVertexAttrib4Nuiv = (PFNGLVERTEXATTRIB4NUIVPROC)proc("glVertexAttrib4Nuiv"); - gl3wVertexAttrib4Nusv = (PFNGLVERTEXATTRIB4NUSVPROC)proc("glVertexAttrib4Nusv"); - gl3wVertexAttrib4bv = (PFNGLVERTEXATTRIB4BVPROC)proc("glVertexAttrib4bv"); - gl3wVertexAttrib4d = (PFNGLVERTEXATTRIB4DPROC)proc("glVertexAttrib4d"); - gl3wVertexAttrib4dv = (PFNGLVERTEXATTRIB4DVPROC)proc("glVertexAttrib4dv"); - gl3wVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC)proc("glVertexAttrib4f"); - gl3wVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC)proc("glVertexAttrib4fv"); - gl3wVertexAttrib4iv = (PFNGLVERTEXATTRIB4IVPROC)proc("glVertexAttrib4iv"); - gl3wVertexAttrib4s = (PFNGLVERTEXATTRIB4SPROC)proc("glVertexAttrib4s"); - gl3wVertexAttrib4sv = (PFNGLVERTEXATTRIB4SVPROC)proc("glVertexAttrib4sv"); - gl3wVertexAttrib4ubv = (PFNGLVERTEXATTRIB4UBVPROC)proc("glVertexAttrib4ubv"); - gl3wVertexAttrib4uiv = (PFNGLVERTEXATTRIB4UIVPROC)proc("glVertexAttrib4uiv"); - gl3wVertexAttrib4usv = (PFNGLVERTEXATTRIB4USVPROC)proc("glVertexAttrib4usv"); - gl3wVertexAttribBinding = (PFNGLVERTEXATTRIBBINDINGPROC)proc("glVertexAttribBinding"); - gl3wVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISORPROC)proc("glVertexAttribDivisor"); - gl3wVertexAttribDivisorARB = (PFNGLVERTEXATTRIBDIVISORARBPROC)proc("glVertexAttribDivisorARB"); - gl3wVertexAttribFormat = (PFNGLVERTEXATTRIBFORMATPROC)proc("glVertexAttribFormat"); - gl3wVertexAttribFormatNV = (PFNGLVERTEXATTRIBFORMATNVPROC)proc("glVertexAttribFormatNV"); - gl3wVertexAttribI1i = (PFNGLVERTEXATTRIBI1IPROC)proc("glVertexAttribI1i"); - gl3wVertexAttribI1iv = (PFNGLVERTEXATTRIBI1IVPROC)proc("glVertexAttribI1iv"); - gl3wVertexAttribI1ui = (PFNGLVERTEXATTRIBI1UIPROC)proc("glVertexAttribI1ui"); - gl3wVertexAttribI1uiv = (PFNGLVERTEXATTRIBI1UIVPROC)proc("glVertexAttribI1uiv"); - gl3wVertexAttribI2i = (PFNGLVERTEXATTRIBI2IPROC)proc("glVertexAttribI2i"); - gl3wVertexAttribI2iv = (PFNGLVERTEXATTRIBI2IVPROC)proc("glVertexAttribI2iv"); - gl3wVertexAttribI2ui = (PFNGLVERTEXATTRIBI2UIPROC)proc("glVertexAttribI2ui"); - gl3wVertexAttribI2uiv = (PFNGLVERTEXATTRIBI2UIVPROC)proc("glVertexAttribI2uiv"); - gl3wVertexAttribI3i = (PFNGLVERTEXATTRIBI3IPROC)proc("glVertexAttribI3i"); - gl3wVertexAttribI3iv = (PFNGLVERTEXATTRIBI3IVPROC)proc("glVertexAttribI3iv"); - gl3wVertexAttribI3ui = (PFNGLVERTEXATTRIBI3UIPROC)proc("glVertexAttribI3ui"); - gl3wVertexAttribI3uiv = (PFNGLVERTEXATTRIBI3UIVPROC)proc("glVertexAttribI3uiv"); - gl3wVertexAttribI4bv = (PFNGLVERTEXATTRIBI4BVPROC)proc("glVertexAttribI4bv"); - gl3wVertexAttribI4i = (PFNGLVERTEXATTRIBI4IPROC)proc("glVertexAttribI4i"); - gl3wVertexAttribI4iv = (PFNGLVERTEXATTRIBI4IVPROC)proc("glVertexAttribI4iv"); - gl3wVertexAttribI4sv = (PFNGLVERTEXATTRIBI4SVPROC)proc("glVertexAttribI4sv"); - gl3wVertexAttribI4ubv = (PFNGLVERTEXATTRIBI4UBVPROC)proc("glVertexAttribI4ubv"); - gl3wVertexAttribI4ui = (PFNGLVERTEXATTRIBI4UIPROC)proc("glVertexAttribI4ui"); - gl3wVertexAttribI4uiv = (PFNGLVERTEXATTRIBI4UIVPROC)proc("glVertexAttribI4uiv"); - gl3wVertexAttribI4usv = (PFNGLVERTEXATTRIBI4USVPROC)proc("glVertexAttribI4usv"); - gl3wVertexAttribIFormat = (PFNGLVERTEXATTRIBIFORMATPROC)proc("glVertexAttribIFormat"); - gl3wVertexAttribIFormatNV = (PFNGLVERTEXATTRIBIFORMATNVPROC)proc("glVertexAttribIFormatNV"); - gl3wVertexAttribIPointer = (PFNGLVERTEXATTRIBIPOINTERPROC)proc("glVertexAttribIPointer"); - gl3wVertexAttribL1d = (PFNGLVERTEXATTRIBL1DPROC)proc("glVertexAttribL1d"); - gl3wVertexAttribL1dv = (PFNGLVERTEXATTRIBL1DVPROC)proc("glVertexAttribL1dv"); - gl3wVertexAttribL1i64NV = (PFNGLVERTEXATTRIBL1I64NVPROC)proc("glVertexAttribL1i64NV"); - gl3wVertexAttribL1i64vNV = (PFNGLVERTEXATTRIBL1I64VNVPROC)proc("glVertexAttribL1i64vNV"); - gl3wVertexAttribL1ui64ARB = (PFNGLVERTEXATTRIBL1UI64ARBPROC)proc("glVertexAttribL1ui64ARB"); - gl3wVertexAttribL1ui64NV = (PFNGLVERTEXATTRIBL1UI64NVPROC)proc("glVertexAttribL1ui64NV"); - gl3wVertexAttribL1ui64vARB = (PFNGLVERTEXATTRIBL1UI64VARBPROC)proc("glVertexAttribL1ui64vARB"); - gl3wVertexAttribL1ui64vNV = (PFNGLVERTEXATTRIBL1UI64VNVPROC)proc("glVertexAttribL1ui64vNV"); - gl3wVertexAttribL2d = (PFNGLVERTEXATTRIBL2DPROC)proc("glVertexAttribL2d"); - gl3wVertexAttribL2dv = (PFNGLVERTEXATTRIBL2DVPROC)proc("glVertexAttribL2dv"); - gl3wVertexAttribL2i64NV = (PFNGLVERTEXATTRIBL2I64NVPROC)proc("glVertexAttribL2i64NV"); - gl3wVertexAttribL2i64vNV = (PFNGLVERTEXATTRIBL2I64VNVPROC)proc("glVertexAttribL2i64vNV"); - gl3wVertexAttribL2ui64NV = (PFNGLVERTEXATTRIBL2UI64NVPROC)proc("glVertexAttribL2ui64NV"); - gl3wVertexAttribL2ui64vNV = (PFNGLVERTEXATTRIBL2UI64VNVPROC)proc("glVertexAttribL2ui64vNV"); - gl3wVertexAttribL3d = (PFNGLVERTEXATTRIBL3DPROC)proc("glVertexAttribL3d"); - gl3wVertexAttribL3dv = (PFNGLVERTEXATTRIBL3DVPROC)proc("glVertexAttribL3dv"); - gl3wVertexAttribL3i64NV = (PFNGLVERTEXATTRIBL3I64NVPROC)proc("glVertexAttribL3i64NV"); - gl3wVertexAttribL3i64vNV = (PFNGLVERTEXATTRIBL3I64VNVPROC)proc("glVertexAttribL3i64vNV"); - gl3wVertexAttribL3ui64NV = (PFNGLVERTEXATTRIBL3UI64NVPROC)proc("glVertexAttribL3ui64NV"); - gl3wVertexAttribL3ui64vNV = (PFNGLVERTEXATTRIBL3UI64VNVPROC)proc("glVertexAttribL3ui64vNV"); - gl3wVertexAttribL4d = (PFNGLVERTEXATTRIBL4DPROC)proc("glVertexAttribL4d"); - gl3wVertexAttribL4dv = (PFNGLVERTEXATTRIBL4DVPROC)proc("glVertexAttribL4dv"); - gl3wVertexAttribL4i64NV = (PFNGLVERTEXATTRIBL4I64NVPROC)proc("glVertexAttribL4i64NV"); - gl3wVertexAttribL4i64vNV = (PFNGLVERTEXATTRIBL4I64VNVPROC)proc("glVertexAttribL4i64vNV"); - gl3wVertexAttribL4ui64NV = (PFNGLVERTEXATTRIBL4UI64NVPROC)proc("glVertexAttribL4ui64NV"); - gl3wVertexAttribL4ui64vNV = (PFNGLVERTEXATTRIBL4UI64VNVPROC)proc("glVertexAttribL4ui64vNV"); - gl3wVertexAttribLFormat = (PFNGLVERTEXATTRIBLFORMATPROC)proc("glVertexAttribLFormat"); - gl3wVertexAttribLFormatNV = (PFNGLVERTEXATTRIBLFORMATNVPROC)proc("glVertexAttribLFormatNV"); - gl3wVertexAttribLPointer = (PFNGLVERTEXATTRIBLPOINTERPROC)proc("glVertexAttribLPointer"); - gl3wVertexAttribP1ui = (PFNGLVERTEXATTRIBP1UIPROC)proc("glVertexAttribP1ui"); - gl3wVertexAttribP1uiv = (PFNGLVERTEXATTRIBP1UIVPROC)proc("glVertexAttribP1uiv"); - gl3wVertexAttribP2ui = (PFNGLVERTEXATTRIBP2UIPROC)proc("glVertexAttribP2ui"); - gl3wVertexAttribP2uiv = (PFNGLVERTEXATTRIBP2UIVPROC)proc("glVertexAttribP2uiv"); - gl3wVertexAttribP3ui = (PFNGLVERTEXATTRIBP3UIPROC)proc("glVertexAttribP3ui"); - gl3wVertexAttribP3uiv = (PFNGLVERTEXATTRIBP3UIVPROC)proc("glVertexAttribP3uiv"); - gl3wVertexAttribP4ui = (PFNGLVERTEXATTRIBP4UIPROC)proc("glVertexAttribP4ui"); - gl3wVertexAttribP4uiv = (PFNGLVERTEXATTRIBP4UIVPROC)proc("glVertexAttribP4uiv"); - gl3wVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)proc("glVertexAttribPointer"); - gl3wVertexBindingDivisor = (PFNGLVERTEXBINDINGDIVISORPROC)proc("glVertexBindingDivisor"); - gl3wVertexFormatNV = (PFNGLVERTEXFORMATNVPROC)proc("glVertexFormatNV"); - gl3wViewport = (PFNGLVIEWPORTPROC)proc("glViewport"); - gl3wViewportArrayv = (PFNGLVIEWPORTARRAYVPROC)proc("glViewportArrayv"); - gl3wViewportIndexedf = (PFNGLVIEWPORTINDEXEDFPROC)proc("glViewportIndexedf"); - gl3wViewportIndexedfv = (PFNGLVIEWPORTINDEXEDFVPROC)proc("glViewportIndexedfv"); - gl3wViewportPositionWScaleNV = (PFNGLVIEWPORTPOSITIONWSCALENVPROC)proc("glViewportPositionWScaleNV"); - gl3wViewportSwizzleNV = (PFNGLVIEWPORTSWIZZLENVPROC)proc("glViewportSwizzleNV"); - gl3wWaitSync = (PFNGLWAITSYNCPROC)proc("glWaitSync"); - gl3wWaitVkSemaphoreNV = (PFNGLWAITVKSEMAPHORENVPROC)proc("glWaitVkSemaphoreNV"); - gl3wWeightPathsNV = (PFNGLWEIGHTPATHSNVPROC)proc("glWeightPathsNV"); - gl3wWindowRectanglesEXT = (PFNGLWINDOWRECTANGLESEXTPROC)proc("glWindowRectanglesEXT"); -} diff --git a/RenderSystems/GLES2/CMakeLists.txt b/RenderSystems/GLES2/CMakeLists.txt deleted file mode 100644 index 94fcb89d7df..00000000000 --- a/RenderSystems/GLES2/CMakeLists.txt +++ /dev/null @@ -1,96 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure OpenGL ES 2.0 RenderSystem build - -# GLSL-Optimizer -find_package(GLSLOptimizer QUIET) -macro_log_feature(GLSL_Optimizer_FOUND "GLSL Optimizer" "GLSL Optimizer" "http://github.com/aras-p/glsl-optimizer/") - -# HLSL2GLSL -find_package(HLSL2GLSL QUIET) -macro_log_feature(HLSL2GLSL_FOUND "HLSL2GLSL" "HLSL2GLSL" "http://hlsl2glslfork.googlecode.com/") - -file(GLOB HEADER_FILES "include/*.h") -list(APPEND HEADER_FILES - ${PROJECT_BINARY_DIR}/include/OgreGLES2Exports.h - ${PROJECT_BINARY_DIR}/include/OgreGLES2Config.h) -file(GLOB SOURCE_FILES "src/*.cpp") -list(APPEND SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/glesw.c") - -file(GLOB GLSLES_FILES "src/GLSLES/include/*.h" "src/GLSLES/src/*.cpp") - -list(REMOVE_ITEM GLSLES_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/GLSLES/src/OgreGLSLESCgProgram.cpp") -list(REMOVE_ITEM GLSLES_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/GLSLES/src/OgreGLSLESCgProgramFactory.cpp") - -set(GLESW_HEADER_INSTALL "GLES3") -file(GLOB GLESW_HEADERS "include/GLES3/*.h") -file(GLOB KHR_HEADERS "include/KHR/*.h") - -if(OGRE_CONFIG_ENABLE_GL_STATE_CACHE_SUPPORT) - set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/src/OgreGLES2StateCacheManager.cpp - PROPERTIES COMPILE_DEFINITIONS OGRE_ENABLE_STATE_CACHE) -endif() - -if (OGRE_CONFIG_ENABLE_GLES2_CG_SUPPORT) - list(APPEND GLSLES_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/src/GLSLES/src/OgreGLSLESCgProgram.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/src/GLSLES/src/OgreGLSLESCgProgramFactory.cpp - ) -endif (OGRE_CONFIG_ENABLE_GLES2_CG_SUPPORT) - -# Add system specific settings -if (APPLE) - add_definitions(-DGLES_SILENCE_DEPRECATION) - file(GLOB PLATFORM_HEADERS "include/EAGL/*.h") - file(GLOB PLATFORM_SOURCES "src/EAGL/*.mm") - - include_directories(src/EAGL include/EAGL) - set(PLATFORM_HEADER_INSTALL "APPLE") -endif () - -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/src/GLSLES/include) - -add_library(RenderSystem_GLES2 ${OGRE_LIB_TYPE} ${HEADER_FILES} ${GLESW_HEADERS} ${KHR_HEADERS} ${PLATFORM_HEADERS} ${SOURCE_FILES} ${PLATFORM_SOURCES} ${GLSLES_FILES}) -target_link_libraries(RenderSystem_GLES2 PUBLIC OgreMain ${CMAKE_DL_LIBS} PRIVATE OgreGLSupport) -target_include_directories(RenderSystem_GLES2 PUBLIC - "$" - $) - -if (OGRE_CONFIG_ENABLE_GLES2_GLSL_OPTIMISER) - target_link_libraries(RenderSystem_GLES2 ${GLSL_Optimizer_LIBRARIES}) -endif () - -if (OGRE_CONFIG_ENABLE_GLES2_CG_SUPPORT) - target_include_directories(RenderSystem_GLES2 PUBLIC ${HLSL2GLSL_INCLUDE_DIRS}) - target_link_libraries(RenderSystem_GLES2 ${HLSL2GLSL_LIBRARIES}) -endif () - -if (NOT OGRE_STATIC) - set_target_properties(RenderSystem_GLES2 PROPERTIES - COMPILE_DEFINITIONS OGRE_GLES2PLUGIN_EXPORTS - ) -endif () - -if (OGRE_CONFIG_THREADS) - target_link_libraries(RenderSystem_GLES2 ${OGRE_THREAD_LIBRARIES}) -endif () - -generate_export_header(RenderSystem_GLES2 - EXPORT_MACRO_NAME _OgreGLES2Export - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreGLES2Exports.h) - -ogre_config_plugin(RenderSystem_GLES2) - -install(FILES ${HEADER_FILES} ${GLSUPPORT_HEADERS} DESTINATION include/OGRE/RenderSystems/GLES2) -install(FILES "include/GLES2/gl2ext.h" DESTINATION include/OGRE/RenderSystems/GLES2/GLES2) -install(FILES ${GLESW_HEADERS} DESTINATION include/OGRE/RenderSystems/GLES2/${GLESW_HEADER_INSTALL}) -install(FILES ${KHR_HEADERS} DESTINATION include/OGRE/RenderSystems/GLES2/KHR) -install(FILES ${PLATFORM_HEADERS} DESTINATION include/OGRE/RenderSystems/GLES2/${PLATFORM_HEADER_INSTALL}) -install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/src/GLSLES/include/ DESTINATION include/OGRE/RenderSystems/GLES2/GLSLES) diff --git a/RenderSystems/GLES2/include/EAGL/OgreEAGL2Support.h b/RenderSystems/GLES2/include/EAGL/OgreEAGL2Support.h deleted file mode 100644 index cade258c148..00000000000 --- a/RenderSystems/GLES2/include/EAGL/OgreEAGL2Support.h +++ /dev/null @@ -1,75 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __EAGL2Support_H__ -#define __EAGL2Support_H__ - -#include "OgreGLNativeSupport.h" - -#ifdef __OBJC__ -// Forward declarations -@class CAEAGLLayer; -@class UIWindow; -@class NSString; -typedef UIWindow *NativeWindowType; -#endif - -namespace Ogre { - class EAGL2Window; - class EAGLES2Context; - - class _OgrePrivate EAGL2Support : public GLNativeSupport - { - public: - EAGL2Support(); - virtual ~EAGL2Support(); - - void start(void); - void stop(void); - ConfigOptionMap getConfigOptions(); - CFDictionaryRef chooseGLConfig(const GLint *attribList, GLint *nElements); - GLint getGLConfigAttrib(CFDictionaryRef fbConfig, GLint attribute, GLint *value); - void * getProcAddress(const char* name) const; - - RenderWindow * newWindow(const String& name, - unsigned int width, unsigned int height, - bool fullScreen, - const NameValuePairList *miscParams = 0); - -#ifdef __OBJC__ - bool portraitIsSupported(void); - bool interfaceOrientationIsSupported(NSString *orientation); - - EAGLES2Context * createNewContext(CAEAGLLayer *drawable, EAGLSharegroup *group) const; - CFDictionaryRef getGLConfigFromContext(EAGLES2Context context); -#endif - CFDictionaryRef selectGLConfig(const int* minAttribs, const int *maxAttribs); - }; -} - -#endif diff --git a/RenderSystems/GLES2/include/EAGL/OgreEAGL2View.h b/RenderSystems/GLES2/include/EAGL/OgreEAGL2View.h deleted file mode 100644 index 49a4cb9b73d..00000000000 --- a/RenderSystems/GLES2/include/EAGL/OgreEAGL2View.h +++ /dev/null @@ -1,48 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __EAGL2View_H__ -#define __EAGL2View_H__ - -#include "OgreString.h" - -#ifdef __OBJC__ - -#import - -@interface EAGL2View : UIView { - Ogre::String mWindowName; -} - -@property (nonatomic,assign) Ogre::String mWindowName; - -@end - -#endif - -#endif diff --git a/RenderSystems/GLES2/include/EAGL/OgreEAGL2ViewController.h b/RenderSystems/GLES2/include/EAGL/OgreEAGL2ViewController.h deleted file mode 100644 index 46865095eda..00000000000 --- a/RenderSystems/GLES2/include/EAGL/OgreEAGL2ViewController.h +++ /dev/null @@ -1,46 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __EAGL2ViewController_H__ -#define __EAGL2ViewController_H__ - -#import -#import "OgreRoot.h" -#import "OgreEAGL2Support.h" - -using namespace Ogre; - -@interface EAGL2ViewController : UIViewController { - EAGL2Support *mGLSupport; -} - -@property (assign) EAGL2Support *mGLSupport; - -@end - -#endif diff --git a/RenderSystems/GLES2/include/EAGL/OgreEAGL2Window.h b/RenderSystems/GLES2/include/EAGL/OgreEAGL2Window.h deleted file mode 100644 index a411a5f1fb1..00000000000 --- a/RenderSystems/GLES2/include/EAGL/OgreEAGL2Window.h +++ /dev/null @@ -1,119 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __EAGL2Window_H__ -#define __EAGL2Window_H__ - -#include "OgreRenderWindow.h" -#include "OgreGLRenderTarget.h" -#include "OgreEAGLES2Context.h" - -#ifdef __OBJC__ -#import "OgreEAGL2View.h" -#import "OgreEAGL2ViewController.h" - -// Forward declarations -@class CAEAGLLayer; - -// Define the native window type -typedef UIWindow *NativeWindowType; - -#endif - -namespace Ogre { - class EAGL2Support; - - class _OgrePrivate EAGL2Window : public RenderWindow, public GLRenderTarget - { - protected: - bool mVisible; - bool mHidden; - /// Is this using an external window handle? - bool mIsExternal; - /// Is this using an external view handle? - bool mUsingExternalView; - /// Is this using an external view controller handle? - bool mUsingExternalViewController; - - // iOS 4 content scaling - bool mIsContentScalingSupported; - float mContentScalingFactor; - - EAGL2Support* mGLSupport; - EAGLES2Context* mContext; -#ifdef __OBJC__ - NativeWindowType mWindow; - EAGL2View *mView; - EAGL2ViewController *mViewController; -#else - void *mWindowPlaceholder; - void *mViewPlaceholder; - void *mViewControllerPlaceholder; -#endif - - void createNativeWindow(uint widthPt, uint heightPt, const NameValuePairList *miscParams); - void resize(unsigned int widthPt, unsigned int heightPt); - void windowMovedOrResized(); - int _getPixelFromPoint(float viewPt) { return mIsContentScalingSupported ? (int)viewPt * mContentScalingFactor : (int)viewPt; } - - public: - EAGL2Window(EAGL2Support* glsupport); - virtual ~EAGL2Window(); - - float getViewPointToPixelScale() { return mIsContentScalingSupported ? mContentScalingFactor : 1.0f; } - void create(const String& name, unsigned int widthPt, unsigned int heightPt, - bool fullScreen, const NameValuePairList *miscParams); - - void destroy(void); - bool isVisible(void) const { return mVisible; } - void setVisible(bool visible) { mVisible = visible; } - bool isHidden(void) const { return mHidden; } - void setHidden(bool hidden); - void setClosed(bool closed) { mClosed = closed; } - void swapBuffers(); - void copyContentsToMemory(const Box& src, const PixelBox &dst, FrameBuffer buffer); - PixelFormat suggestPixelFormat() const { return PF_BYTE_RGBA; } - - /** - - * Get custom attribute; the following attributes are valid: - * WINDOW The NativeWindowType target for rendering. - * VIEW The EAGLView object that is drawn into. - * VIEWCONTROLLER The UIViewController used for handling view rotation. - * GLCONTEXT The Ogre GLContext used for rendering. - * SHAREGROUP The EAGLShareGroup object associated with the main context. - */ - virtual void getCustomAttribute(const String& name, void* pData); - - bool requiresTextureFlipping() const { return false; } - - virtual GLContext* getContext() const { return mContext; } - }; -} - -#endif diff --git a/RenderSystems/GLES2/include/EAGL/OgreEAGLES2Context.h b/RenderSystems/GLES2/include/EAGL/OgreEAGLES2Context.h deleted file mode 100644 index 843814904ad..00000000000 --- a/RenderSystems/GLES2/include/EAGL/OgreEAGLES2Context.h +++ /dev/null @@ -1,88 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __EAGLES2Context_H__ -#define __EAGLES2Context_H__ - -#include "OgreGLES2Prerequisites.h" -#include "OgreGLContext.h" - -#ifdef __OBJC__ -# import -#endif - -namespace Ogre { - - class _OgrePrivate EAGLES2Context : public GLContext - { - protected: -#ifdef __OBJC__ - CAEAGLLayer *mDrawable; - EAGLContext *mContext; -#else - void *mDrawablePlaceholder; - void *mContextPlaceholder; -#endif - - public: -#ifdef __OBJC__ - EAGLES2Context(CAEAGLLayer *drawable, EAGLSharegroup *group); - CAEAGLLayer * getDrawable() const; - EAGLContext * getContext() const; -#endif - virtual ~EAGLES2Context(); - - virtual void setCurrent(); - virtual void endCurrent(); - virtual GLContext * clone() const; - - bool createFramebuffer(); - void destroyFramebuffer(); - - /* The pixel dimensions of the backbuffer */ - GLint mBackingWidth; - GLint mBackingHeight; - - /* OpenGL names for the renderbuffer and framebuffers used to render to this view */ - GLuint mViewRenderbuffer; - GLuint mViewFramebuffer; - - /* OpenGL name for the depth buffer that is attached to viewFramebuffer, if it exists (0 if it does not exist) */ - GLuint mDepthRenderbuffer; - - bool mIsMultiSampleSupported; - GLsizei mNumSamples; - GLuint mSampleFramebuffer; - GLuint mSampleRenderbuffer; - - /// Mask of buffers who contents can be discarded if GL_EXT_discard_framebuffer is supported - unsigned int mDiscardBuffers; - }; -} - -#endif diff --git a/RenderSystems/GLES2/include/GLES2/gl2ext.h b/RenderSystems/GLES2/include/GLES2/gl2ext.h deleted file mode 100644 index 40f091637b0..00000000000 --- a/RenderSystems/GLES2/include/GLES2/gl2ext.h +++ /dev/null @@ -1,2988 +0,0 @@ -#ifndef __gl2ext_h_ -#define __gl2ext_h_ 1 - -#ifdef __cplusplus -extern "C" { -#endif - -/* -** Copyright (c) 2013-2015 The Khronos Group Inc. -** -** Permission is hereby granted, free of charge, to any person obtaining a -** copy of this software and/or associated documentation files (the -** "Materials"), to deal in the Materials without restriction, including -** without limitation the rights to use, copy, modify, merge, publish, -** distribute, sublicense, and/or sell copies of the Materials, and to -** permit persons to whom the Materials are furnished to do so, subject to -** the following conditions: -** -** The above copyright notice and this permission notice shall be included -** in all copies or substantial portions of the Materials. -** -** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. -*/ -/* -** This header is generated from the Khronos OpenGL / OpenGL ES XML -** API Registry. The current version of the Registry, generator scripts -** used to make the header, and the header can be found at -** http://www.opengl.org/registry/ -** -** Khronos $Revision: 32347 $ on $Date: 2016-01-08 03:01:49 -0800 (Fri, 08 Jan 2016) $ -*/ - -#ifndef GL_APIENTRYP -#define GL_APIENTRYP GL_APIENTRY* -#endif - -/* Generated on date 20160108 */ - -/* Generated C header for: - * API: gles2 - * Profile: common - * Versions considered: 2\.[0-9] - * Versions emitted: _nomatch_^ - * Default extensions included: gles2 - * Additional extensions included: _nomatch_^ - * Extensions removed: _nomatch_^ - */ - -#ifndef GL_KHR_blend_equation_advanced -#define GL_KHR_blend_equation_advanced 1 -#define GL_MULTIPLY_KHR 0x9294 -#define GL_SCREEN_KHR 0x9295 -#define GL_OVERLAY_KHR 0x9296 -#define GL_DARKEN_KHR 0x9297 -#define GL_LIGHTEN_KHR 0x9298 -#define GL_COLORDODGE_KHR 0x9299 -#define GL_COLORBURN_KHR 0x929A -#define GL_HARDLIGHT_KHR 0x929B -#define GL_SOFTLIGHT_KHR 0x929C -#define GL_DIFFERENCE_KHR 0x929E -#define GL_EXCLUSION_KHR 0x92A0 -#define GL_HSL_HUE_KHR 0x92AD -#define GL_HSL_SATURATION_KHR 0x92AE -#define GL_HSL_COLOR_KHR 0x92AF -#define GL_HSL_LUMINOSITY_KHR 0x92B0 -typedef void (GL_APIENTRYP PFNGLBLENDBARRIERKHRPROC) (void); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glBlendBarrierKHR (void); -#endif -#endif /* GL_KHR_blend_equation_advanced */ - -#ifndef GL_KHR_blend_equation_advanced_coherent -#define GL_KHR_blend_equation_advanced_coherent 1 -#define GL_BLEND_ADVANCED_COHERENT_KHR 0x9285 -#endif /* GL_KHR_blend_equation_advanced_coherent */ - -#ifndef GL_KHR_context_flush_control -#define GL_KHR_context_flush_control 1 -#define GL_CONTEXT_RELEASE_BEHAVIOR_KHR 0x82FB -#define GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_KHR 0x82FC -#endif /* GL_KHR_context_flush_control */ - -#ifndef GL_KHR_debug -#define GL_KHR_debug 1 -typedef void (GL_APIENTRY *GLDEBUGPROCKHR)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); -#define GL_SAMPLER 0x82E6 -#define GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR 0x8242 -#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_KHR 0x8243 -#define GL_DEBUG_CALLBACK_FUNCTION_KHR 0x8244 -#define GL_DEBUG_CALLBACK_USER_PARAM_KHR 0x8245 -#define GL_DEBUG_SOURCE_API_KHR 0x8246 -#define GL_DEBUG_SOURCE_WINDOW_SYSTEM_KHR 0x8247 -#define GL_DEBUG_SOURCE_SHADER_COMPILER_KHR 0x8248 -#define GL_DEBUG_SOURCE_THIRD_PARTY_KHR 0x8249 -#define GL_DEBUG_SOURCE_APPLICATION_KHR 0x824A -#define GL_DEBUG_SOURCE_OTHER_KHR 0x824B -#define GL_DEBUG_TYPE_ERROR_KHR 0x824C -#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_KHR 0x824D -#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_KHR 0x824E -#define GL_DEBUG_TYPE_PORTABILITY_KHR 0x824F -#define GL_DEBUG_TYPE_PERFORMANCE_KHR 0x8250 -#define GL_DEBUG_TYPE_OTHER_KHR 0x8251 -#define GL_DEBUG_TYPE_MARKER_KHR 0x8268 -#define GL_DEBUG_TYPE_PUSH_GROUP_KHR 0x8269 -#define GL_DEBUG_TYPE_POP_GROUP_KHR 0x826A -#define GL_DEBUG_SEVERITY_NOTIFICATION_KHR 0x826B -#define GL_MAX_DEBUG_GROUP_STACK_DEPTH_KHR 0x826C -#define GL_DEBUG_GROUP_STACK_DEPTH_KHR 0x826D -#define GL_BUFFER_KHR 0x82E0 -#define GL_SHADER_KHR 0x82E1 -#define GL_PROGRAM_KHR 0x82E2 -#define GL_VERTEX_ARRAY_KHR 0x8074 -#define GL_QUERY_KHR 0x82E3 -#define GL_PROGRAM_PIPELINE_KHR 0x82E4 -#define GL_SAMPLER_KHR 0x82E6 -#define GL_MAX_LABEL_LENGTH_KHR 0x82E8 -#define GL_MAX_DEBUG_MESSAGE_LENGTH_KHR 0x9143 -#define GL_MAX_DEBUG_LOGGED_MESSAGES_KHR 0x9144 -#define GL_DEBUG_LOGGED_MESSAGES_KHR 0x9145 -#define GL_DEBUG_SEVERITY_HIGH_KHR 0x9146 -#define GL_DEBUG_SEVERITY_MEDIUM_KHR 0x9147 -#define GL_DEBUG_SEVERITY_LOW_KHR 0x9148 -#define GL_DEBUG_OUTPUT_KHR 0x92E0 -#define GL_CONTEXT_FLAG_DEBUG_BIT_KHR 0x00000002 -#define GL_STACK_OVERFLOW_KHR 0x0503 -#define GL_STACK_UNDERFLOW_KHR 0x0504 -typedef void (GL_APIENTRYP PFNGLDEBUGMESSAGECONTROLKHRPROC) (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); -typedef void (GL_APIENTRYP PFNGLDEBUGMESSAGEINSERTKHRPROC) (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); -typedef void (GL_APIENTRYP PFNGLDEBUGMESSAGECALLBACKKHRPROC) (GLDEBUGPROCKHR callback, const void *userParam); -typedef GLuint (GL_APIENTRYP PFNGLGETDEBUGMESSAGELOGKHRPROC) (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); -typedef void (GL_APIENTRYP PFNGLPUSHDEBUGGROUPKHRPROC) (GLenum source, GLuint id, GLsizei length, const GLchar *message); -typedef void (GL_APIENTRYP PFNGLPOPDEBUGGROUPKHRPROC) (void); -typedef void (GL_APIENTRYP PFNGLOBJECTLABELKHRPROC) (GLenum identifier, GLuint name, GLsizei length, const GLchar *label); -typedef void (GL_APIENTRYP PFNGLGETOBJECTLABELKHRPROC) (GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label); -typedef void (GL_APIENTRYP PFNGLOBJECTPTRLABELKHRPROC) (const void *ptr, GLsizei length, const GLchar *label); -typedef void (GL_APIENTRYP PFNGLGETOBJECTPTRLABELKHRPROC) (const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label); -typedef void (GL_APIENTRYP PFNGLGETPOINTERVKHRPROC) (GLenum pname, void **params); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glDebugMessageControlKHR (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); -GL_APICALL void GL_APIENTRY glDebugMessageInsertKHR (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); -GL_APICALL void GL_APIENTRY glDebugMessageCallbackKHR (GLDEBUGPROCKHR callback, const void *userParam); -GL_APICALL GLuint GL_APIENTRY glGetDebugMessageLogKHR (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); -GL_APICALL void GL_APIENTRY glPushDebugGroupKHR (GLenum source, GLuint id, GLsizei length, const GLchar *message); -GL_APICALL void GL_APIENTRY glPopDebugGroupKHR (void); -GL_APICALL void GL_APIENTRY glObjectLabelKHR (GLenum identifier, GLuint name, GLsizei length, const GLchar *label); -GL_APICALL void GL_APIENTRY glGetObjectLabelKHR (GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label); -GL_APICALL void GL_APIENTRY glObjectPtrLabelKHR (const void *ptr, GLsizei length, const GLchar *label); -GL_APICALL void GL_APIENTRY glGetObjectPtrLabelKHR (const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label); -GL_APICALL void GL_APIENTRY glGetPointervKHR (GLenum pname, void **params); -#endif -#endif /* GL_KHR_debug */ - -#ifndef GL_KHR_no_error -#define GL_KHR_no_error 1 -#define GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR 0x00000008 -#endif /* GL_KHR_no_error */ - -#ifndef GL_KHR_robust_buffer_access_behavior -#define GL_KHR_robust_buffer_access_behavior 1 -#endif /* GL_KHR_robust_buffer_access_behavior */ - -#ifndef GL_KHR_robustness -#define GL_KHR_robustness 1 -#define GL_CONTEXT_ROBUST_ACCESS_KHR 0x90F3 -#define GL_LOSE_CONTEXT_ON_RESET_KHR 0x8252 -#define GL_GUILTY_CONTEXT_RESET_KHR 0x8253 -#define GL_INNOCENT_CONTEXT_RESET_KHR 0x8254 -#define GL_UNKNOWN_CONTEXT_RESET_KHR 0x8255 -#define GL_RESET_NOTIFICATION_STRATEGY_KHR 0x8256 -#define GL_NO_RESET_NOTIFICATION_KHR 0x8261 -#define GL_CONTEXT_LOST_KHR 0x0507 -typedef GLenum (GL_APIENTRYP PFNGLGETGRAPHICSRESETSTATUSKHRPROC) (void); -typedef void (GL_APIENTRYP PFNGLREADNPIXELSKHRPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); -typedef void (GL_APIENTRYP PFNGLGETNUNIFORMFVKHRPROC) (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); -typedef void (GL_APIENTRYP PFNGLGETNUNIFORMIVKHRPROC) (GLuint program, GLint location, GLsizei bufSize, GLint *params); -typedef void (GL_APIENTRYP PFNGLGETNUNIFORMUIVKHRPROC) (GLuint program, GLint location, GLsizei bufSize, GLuint *params); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL GLenum GL_APIENTRY glGetGraphicsResetStatusKHR (void); -GL_APICALL void GL_APIENTRY glReadnPixelsKHR (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); -GL_APICALL void GL_APIENTRY glGetnUniformfvKHR (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); -GL_APICALL void GL_APIENTRY glGetnUniformivKHR (GLuint program, GLint location, GLsizei bufSize, GLint *params); -GL_APICALL void GL_APIENTRY glGetnUniformuivKHR (GLuint program, GLint location, GLsizei bufSize, GLuint *params); -#endif -#endif /* GL_KHR_robustness */ - -#ifndef GL_KHR_texture_compression_astc_hdr -#define GL_KHR_texture_compression_astc_hdr 1 -#define GL_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93B0 -#define GL_COMPRESSED_RGBA_ASTC_5x4_KHR 0x93B1 -#define GL_COMPRESSED_RGBA_ASTC_5x5_KHR 0x93B2 -#define GL_COMPRESSED_RGBA_ASTC_6x5_KHR 0x93B3 -#define GL_COMPRESSED_RGBA_ASTC_6x6_KHR 0x93B4 -#define GL_COMPRESSED_RGBA_ASTC_8x5_KHR 0x93B5 -#define GL_COMPRESSED_RGBA_ASTC_8x6_KHR 0x93B6 -#define GL_COMPRESSED_RGBA_ASTC_8x8_KHR 0x93B7 -#define GL_COMPRESSED_RGBA_ASTC_10x5_KHR 0x93B8 -#define GL_COMPRESSED_RGBA_ASTC_10x6_KHR 0x93B9 -#define GL_COMPRESSED_RGBA_ASTC_10x8_KHR 0x93BA -#define GL_COMPRESSED_RGBA_ASTC_10x10_KHR 0x93BB -#define GL_COMPRESSED_RGBA_ASTC_12x10_KHR 0x93BC -#define GL_COMPRESSED_RGBA_ASTC_12x12_KHR 0x93BD -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR 0x93D0 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR 0x93D1 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR 0x93D2 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR 0x93D3 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR 0x93D4 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR 0x93D5 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR 0x93D6 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR 0x93D7 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR 0x93D8 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR 0x93D9 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR 0x93DA -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR 0x93DB -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR 0x93DC -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR 0x93DD -#endif /* GL_KHR_texture_compression_astc_hdr */ - -#ifndef GL_KHR_texture_compression_astc_ldr -#define GL_KHR_texture_compression_astc_ldr 1 -#endif /* GL_KHR_texture_compression_astc_ldr */ - -#ifndef GL_KHR_texture_compression_astc_sliced_3d -#define GL_KHR_texture_compression_astc_sliced_3d 1 -#endif /* GL_KHR_texture_compression_astc_sliced_3d */ - -#ifndef GL_OES_EGL_image -#define GL_OES_EGL_image 1 -typedef void *GLeglImageOES; -typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC) (GLenum target, GLeglImageOES image); -typedef void (GL_APIENTRYP PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC) (GLenum target, GLeglImageOES image); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glEGLImageTargetTexture2DOES (GLenum target, GLeglImageOES image); -GL_APICALL void GL_APIENTRY glEGLImageTargetRenderbufferStorageOES (GLenum target, GLeglImageOES image); -#endif -#endif /* GL_OES_EGL_image */ - -#ifndef GL_OES_EGL_image_external -#define GL_OES_EGL_image_external 1 -#define GL_TEXTURE_EXTERNAL_OES 0x8D65 -#define GL_TEXTURE_BINDING_EXTERNAL_OES 0x8D67 -#define GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES 0x8D68 -#define GL_SAMPLER_EXTERNAL_OES 0x8D66 -#endif /* GL_OES_EGL_image_external */ - -#ifndef GL_OES_EGL_image_external_essl3 -#define GL_OES_EGL_image_external_essl3 1 -#endif /* GL_OES_EGL_image_external_essl3 */ - -#ifndef GL_OES_compressed_ETC1_RGB8_sub_texture -#define GL_OES_compressed_ETC1_RGB8_sub_texture 1 -#endif /* GL_OES_compressed_ETC1_RGB8_sub_texture */ - -#ifndef GL_OES_compressed_ETC1_RGB8_texture -#define GL_OES_compressed_ETC1_RGB8_texture 1 -#define GL_ETC1_RGB8_OES 0x8D64 -#endif /* GL_OES_compressed_ETC1_RGB8_texture */ - -#ifndef GL_OES_compressed_paletted_texture -#define GL_OES_compressed_paletted_texture 1 -#define GL_PALETTE4_RGB8_OES 0x8B90 -#define GL_PALETTE4_RGBA8_OES 0x8B91 -#define GL_PALETTE4_R5_G6_B5_OES 0x8B92 -#define GL_PALETTE4_RGBA4_OES 0x8B93 -#define GL_PALETTE4_RGB5_A1_OES 0x8B94 -#define GL_PALETTE8_RGB8_OES 0x8B95 -#define GL_PALETTE8_RGBA8_OES 0x8B96 -#define GL_PALETTE8_R5_G6_B5_OES 0x8B97 -#define GL_PALETTE8_RGBA4_OES 0x8B98 -#define GL_PALETTE8_RGB5_A1_OES 0x8B99 -#endif /* GL_OES_compressed_paletted_texture */ - -#ifndef GL_OES_copy_image -#define GL_OES_copy_image 1 -typedef void (GL_APIENTRYP PFNGLCOPYIMAGESUBDATAOESPROC) (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glCopyImageSubDataOES (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); -#endif -#endif /* GL_OES_copy_image */ - -#ifndef GL_OES_depth24 -#define GL_OES_depth24 1 -#define GL_DEPTH_COMPONENT24_OES 0x81A6 -#endif /* GL_OES_depth24 */ - -#ifndef GL_OES_depth32 -#define GL_OES_depth32 1 -#define GL_DEPTH_COMPONENT32_OES 0x81A7 -#endif /* GL_OES_depth32 */ - -#ifndef GL_OES_depth_texture -#define GL_OES_depth_texture 1 -#endif /* GL_OES_depth_texture */ - -#ifndef GL_OES_draw_buffers_indexed -#define GL_OES_draw_buffers_indexed 1 -#define GL_MIN 0x8007 -#define GL_MAX 0x8008 -typedef void (GL_APIENTRYP PFNGLENABLEIOESPROC) (GLenum target, GLuint index); -typedef void (GL_APIENTRYP PFNGLDISABLEIOESPROC) (GLenum target, GLuint index); -typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONIOESPROC) (GLuint buf, GLenum mode); -typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONSEPARATEIOESPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha); -typedef void (GL_APIENTRYP PFNGLBLENDFUNCIOESPROC) (GLuint buf, GLenum src, GLenum dst); -typedef void (GL_APIENTRYP PFNGLBLENDFUNCSEPARATEIOESPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); -typedef void (GL_APIENTRYP PFNGLCOLORMASKIOESPROC) (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); -typedef GLboolean (GL_APIENTRYP PFNGLISENABLEDIOESPROC) (GLenum target, GLuint index); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glEnableiOES (GLenum target, GLuint index); -GL_APICALL void GL_APIENTRY glDisableiOES (GLenum target, GLuint index); -GL_APICALL void GL_APIENTRY glBlendEquationiOES (GLuint buf, GLenum mode); -GL_APICALL void GL_APIENTRY glBlendEquationSeparateiOES (GLuint buf, GLenum modeRGB, GLenum modeAlpha); -GL_APICALL void GL_APIENTRY glBlendFunciOES (GLuint buf, GLenum src, GLenum dst); -GL_APICALL void GL_APIENTRY glBlendFuncSeparateiOES (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); -GL_APICALL void GL_APIENTRY glColorMaskiOES (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); -GL_APICALL GLboolean GL_APIENTRY glIsEnablediOES (GLenum target, GLuint index); -#endif -#endif /* GL_OES_draw_buffers_indexed */ - -#ifndef GL_OES_draw_elements_base_vertex -#define GL_OES_draw_elements_base_vertex 1 -typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXOESPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); -typedef void (GL_APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXOESPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); -typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXOESPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); -typedef void (GL_APIENTRYP PFNGLMULTIDRAWELEMENTSBASEVERTEXOESPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount, const GLint *basevertex); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glDrawElementsBaseVertexOES (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); -GL_APICALL void GL_APIENTRY glDrawRangeElementsBaseVertexOES (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); -GL_APICALL void GL_APIENTRY glDrawElementsInstancedBaseVertexOES (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); -GL_APICALL void GL_APIENTRY glMultiDrawElementsBaseVertexOES (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount, const GLint *basevertex); -#endif -#endif /* GL_OES_draw_elements_base_vertex */ - -#ifndef GL_OES_element_index_uint -#define GL_OES_element_index_uint 1 -#endif /* GL_OES_element_index_uint */ - -#ifndef GL_OES_fbo_render_mipmap -#define GL_OES_fbo_render_mipmap 1 -#endif /* GL_OES_fbo_render_mipmap */ - -#ifndef GL_OES_fragment_precision_high -#define GL_OES_fragment_precision_high 1 -#endif /* GL_OES_fragment_precision_high */ - -#ifndef GL_OES_geometry_point_size -#define GL_OES_geometry_point_size 1 -#endif /* GL_OES_geometry_point_size */ - -#ifndef GL_OES_geometry_shader -#define GL_OES_geometry_shader 1 -#define GL_GEOMETRY_SHADER_OES 0x8DD9 -#define GL_GEOMETRY_SHADER_BIT_OES 0x00000004 -#define GL_GEOMETRY_LINKED_VERTICES_OUT_OES 0x8916 -#define GL_GEOMETRY_LINKED_INPUT_TYPE_OES 0x8917 -#define GL_GEOMETRY_LINKED_OUTPUT_TYPE_OES 0x8918 -#define GL_GEOMETRY_SHADER_INVOCATIONS_OES 0x887F -#define GL_LAYER_PROVOKING_VERTEX_OES 0x825E -#define GL_LINES_ADJACENCY_OES 0x000A -#define GL_LINE_STRIP_ADJACENCY_OES 0x000B -#define GL_TRIANGLES_ADJACENCY_OES 0x000C -#define GL_TRIANGLE_STRIP_ADJACENCY_OES 0x000D -#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_OES 0x8DDF -#define GL_MAX_GEOMETRY_UNIFORM_BLOCKS_OES 0x8A2C -#define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS_OES 0x8A32 -#define GL_MAX_GEOMETRY_INPUT_COMPONENTS_OES 0x9123 -#define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS_OES 0x9124 -#define GL_MAX_GEOMETRY_OUTPUT_VERTICES_OES 0x8DE0 -#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_OES 0x8DE1 -#define GL_MAX_GEOMETRY_SHADER_INVOCATIONS_OES 0x8E5A -#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_OES 0x8C29 -#define GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS_OES 0x92CF -#define GL_MAX_GEOMETRY_ATOMIC_COUNTERS_OES 0x92D5 -#define GL_MAX_GEOMETRY_IMAGE_UNIFORMS_OES 0x90CD -#define GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS_OES 0x90D7 -#define GL_FIRST_VERTEX_CONVENTION_OES 0x8E4D -#define GL_LAST_VERTEX_CONVENTION_OES 0x8E4E -#define GL_UNDEFINED_VERTEX_OES 0x8260 -#define GL_PRIMITIVES_GENERATED_OES 0x8C87 -#define GL_FRAMEBUFFER_DEFAULT_LAYERS_OES 0x9312 -#define GL_MAX_FRAMEBUFFER_LAYERS_OES 0x9317 -#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_OES 0x8DA8 -#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_OES 0x8DA7 -#define GL_REFERENCED_BY_GEOMETRY_SHADER_OES 0x9309 -typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTUREOESPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glFramebufferTextureOES (GLenum target, GLenum attachment, GLuint texture, GLint level); -#endif -#endif /* GL_OES_geometry_shader */ - -#ifndef GL_OES_get_program_binary -#define GL_OES_get_program_binary 1 -#define GL_PROGRAM_BINARY_LENGTH_OES 0x8741 -#define GL_NUM_PROGRAM_BINARY_FORMATS_OES 0x87FE -#define GL_PROGRAM_BINARY_FORMATS_OES 0x87FF -typedef void (GL_APIENTRYP PFNGLGETPROGRAMBINARYOESPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); -typedef void (GL_APIENTRYP PFNGLPROGRAMBINARYOESPROC) (GLuint program, GLenum binaryFormat, const void *binary, GLint length); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glGetProgramBinaryOES (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); -GL_APICALL void GL_APIENTRY glProgramBinaryOES (GLuint program, GLenum binaryFormat, const void *binary, GLint length); -#endif -#endif /* GL_OES_get_program_binary */ - -#ifndef GL_OES_gpu_shader5 -#define GL_OES_gpu_shader5 1 -#endif /* GL_OES_gpu_shader5 */ - -#ifndef GL_OES_mapbuffer -#define GL_OES_mapbuffer 1 -#define GL_WRITE_ONLY_OES 0x88B9 -#define GL_BUFFER_ACCESS_OES 0x88BB -#define GL_BUFFER_MAPPED_OES 0x88BC -#define GL_BUFFER_MAP_POINTER_OES 0x88BD -typedef void *(GL_APIENTRYP PFNGLMAPBUFFEROESPROC) (GLenum target, GLenum access); -typedef GLboolean (GL_APIENTRYP PFNGLUNMAPBUFFEROESPROC) (GLenum target); -typedef void (GL_APIENTRYP PFNGLGETBUFFERPOINTERVOESPROC) (GLenum target, GLenum pname, void **params); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void *GL_APIENTRY glMapBufferOES (GLenum target, GLenum access); -GL_APICALL GLboolean GL_APIENTRY glUnmapBufferOES (GLenum target); -GL_APICALL void GL_APIENTRY glGetBufferPointervOES (GLenum target, GLenum pname, void **params); -#endif -#endif /* GL_OES_mapbuffer */ - -#ifndef GL_OES_packed_depth_stencil -#define GL_OES_packed_depth_stencil 1 -#define GL_DEPTH_STENCIL_OES 0x84F9 -#define GL_UNSIGNED_INT_24_8_OES 0x84FA -#define GL_DEPTH24_STENCIL8_OES 0x88F0 -#endif /* GL_OES_packed_depth_stencil */ - -#ifndef GL_OES_primitive_bounding_box -#define GL_OES_primitive_bounding_box 1 -#define GL_PRIMITIVE_BOUNDING_BOX_OES 0x92BE -typedef void (GL_APIENTRYP PFNGLPRIMITIVEBOUNDINGBOXOESPROC) (GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glPrimitiveBoundingBoxOES (GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW); -#endif -#endif /* GL_OES_primitive_bounding_box */ - -#ifndef GL_OES_required_internalformat -#define GL_OES_required_internalformat 1 -#define GL_ALPHA8_OES 0x803C -#define GL_DEPTH_COMPONENT16_OES 0x81A5 -#define GL_LUMINANCE4_ALPHA4_OES 0x8043 -#define GL_LUMINANCE8_ALPHA8_OES 0x8045 -#define GL_LUMINANCE8_OES 0x8040 -#define GL_RGBA4_OES 0x8056 -#define GL_RGB5_A1_OES 0x8057 -#define GL_RGB565_OES 0x8D62 -#define GL_RGB8_OES 0x8051 -#define GL_RGBA8_OES 0x8058 -#define GL_RGB10_EXT 0x8052 -#define GL_RGB10_A2_EXT 0x8059 -#endif /* GL_OES_required_internalformat */ - -#ifndef GL_OES_rgb8_rgba8 -#define GL_OES_rgb8_rgba8 1 -#endif /* GL_OES_rgb8_rgba8 */ - -#ifndef GL_OES_sample_shading -#define GL_OES_sample_shading 1 -#define GL_SAMPLE_SHADING_OES 0x8C36 -#define GL_MIN_SAMPLE_SHADING_VALUE_OES 0x8C37 -typedef void (GL_APIENTRYP PFNGLMINSAMPLESHADINGOESPROC) (GLfloat value); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glMinSampleShadingOES (GLfloat value); -#endif -#endif /* GL_OES_sample_shading */ - -#ifndef GL_OES_sample_variables -#define GL_OES_sample_variables 1 -#endif /* GL_OES_sample_variables */ - -#ifndef GL_OES_shader_image_atomic -#define GL_OES_shader_image_atomic 1 -#endif /* GL_OES_shader_image_atomic */ - -#ifndef GL_OES_shader_io_blocks -#define GL_OES_shader_io_blocks 1 -#endif /* GL_OES_shader_io_blocks */ - -#ifndef GL_OES_shader_multisample_interpolation -#define GL_OES_shader_multisample_interpolation 1 -#define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET_OES 0x8E5B -#define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET_OES 0x8E5C -#define GL_FRAGMENT_INTERPOLATION_OFFSET_BITS_OES 0x8E5D -#endif /* GL_OES_shader_multisample_interpolation */ - -#ifndef GL_OES_standard_derivatives -#define GL_OES_standard_derivatives 1 -#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES 0x8B8B -#endif /* GL_OES_standard_derivatives */ - -#ifndef GL_OES_stencil1 -#define GL_OES_stencil1 1 -#define GL_STENCIL_INDEX1_OES 0x8D46 -#endif /* GL_OES_stencil1 */ - -#ifndef GL_OES_stencil4 -#define GL_OES_stencil4 1 -#define GL_STENCIL_INDEX4_OES 0x8D47 -#endif /* GL_OES_stencil4 */ - -#ifndef GL_OES_surfaceless_context -#define GL_OES_surfaceless_context 1 -#define GL_FRAMEBUFFER_UNDEFINED_OES 0x8219 -#endif /* GL_OES_surfaceless_context */ - -#ifndef GL_OES_tessellation_point_size -#define GL_OES_tessellation_point_size 1 -#endif /* GL_OES_tessellation_point_size */ - -#ifndef GL_OES_tessellation_shader -#define GL_OES_tessellation_shader 1 -#define GL_PATCHES_OES 0x000E -#define GL_PATCH_VERTICES_OES 0x8E72 -#define GL_TESS_CONTROL_OUTPUT_VERTICES_OES 0x8E75 -#define GL_TESS_GEN_MODE_OES 0x8E76 -#define GL_TESS_GEN_SPACING_OES 0x8E77 -#define GL_TESS_GEN_VERTEX_ORDER_OES 0x8E78 -#define GL_TESS_GEN_POINT_MODE_OES 0x8E79 -#define GL_ISOLINES_OES 0x8E7A -#define GL_QUADS_OES 0x0007 -#define GL_FRACTIONAL_ODD_OES 0x8E7B -#define GL_FRACTIONAL_EVEN_OES 0x8E7C -#define GL_MAX_PATCH_VERTICES_OES 0x8E7D -#define GL_MAX_TESS_GEN_LEVEL_OES 0x8E7E -#define GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS_OES 0x8E7F -#define GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS_OES 0x8E80 -#define GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS_OES 0x8E81 -#define GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS_OES 0x8E82 -#define GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS_OES 0x8E83 -#define GL_MAX_TESS_PATCH_COMPONENTS_OES 0x8E84 -#define GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS_OES 0x8E85 -#define GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS_OES 0x8E86 -#define GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS_OES 0x8E89 -#define GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS_OES 0x8E8A -#define GL_MAX_TESS_CONTROL_INPUT_COMPONENTS_OES 0x886C -#define GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS_OES 0x886D -#define GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS_OES 0x8E1E -#define GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS_OES 0x8E1F -#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS_OES 0x92CD -#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS_OES 0x92CE -#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS_OES 0x92D3 -#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS_OES 0x92D4 -#define GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS_OES 0x90CB -#define GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS_OES 0x90CC -#define GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS_OES 0x90D8 -#define GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS_OES 0x90D9 -#define GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED_OES 0x8221 -#define GL_IS_PER_PATCH_OES 0x92E7 -#define GL_REFERENCED_BY_TESS_CONTROL_SHADER_OES 0x9307 -#define GL_REFERENCED_BY_TESS_EVALUATION_SHADER_OES 0x9308 -#define GL_TESS_CONTROL_SHADER_OES 0x8E88 -#define GL_TESS_EVALUATION_SHADER_OES 0x8E87 -#define GL_TESS_CONTROL_SHADER_BIT_OES 0x00000008 -#define GL_TESS_EVALUATION_SHADER_BIT_OES 0x00000010 -typedef void (GL_APIENTRYP PFNGLPATCHPARAMETERIOESPROC) (GLenum pname, GLint value); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glPatchParameteriOES (GLenum pname, GLint value); -#endif -#endif /* GL_OES_tessellation_shader */ - -#ifndef GL_OES_texture_3D -#define GL_OES_texture_3D 1 -#define GL_TEXTURE_WRAP_R_OES 0x8072 -#define GL_TEXTURE_3D_OES 0x806F -#define GL_TEXTURE_BINDING_3D_OES 0x806A -#define GL_MAX_3D_TEXTURE_SIZE_OES 0x8073 -#define GL_SAMPLER_3D_OES 0x8B5F -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_OES 0x8CD4 -typedef void (GL_APIENTRYP PFNGLTEXIMAGE3DOESPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); -typedef void (GL_APIENTRYP PFNGLTEXSUBIMAGE3DOESPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); -typedef void (GL_APIENTRYP PFNGLCOPYTEXSUBIMAGE3DOESPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); -typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DOESPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); -typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DOESPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); -typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DOESPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glTexImage3DOES (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); -GL_APICALL void GL_APIENTRY glTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); -GL_APICALL void GL_APIENTRY glCopyTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); -GL_APICALL void GL_APIENTRY glCompressedTexImage3DOES (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); -GL_APICALL void GL_APIENTRY glCompressedTexSubImage3DOES (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); -GL_APICALL void GL_APIENTRY glFramebufferTexture3DOES (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); -#endif -#endif /* GL_OES_texture_3D */ - -#ifndef GL_OES_texture_border_clamp -#define GL_OES_texture_border_clamp 1 -#define GL_TEXTURE_BORDER_COLOR_OES 0x1004 -#define GL_CLAMP_TO_BORDER_OES 0x812D -typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIIVOESPROC) (GLenum target, GLenum pname, const GLint *params); -typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIUIVOESPROC) (GLenum target, GLenum pname, const GLuint *params); -typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERIIVOESPROC) (GLenum target, GLenum pname, GLint *params); -typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERIUIVOESPROC) (GLenum target, GLenum pname, GLuint *params); -typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERIIVOESPROC) (GLuint sampler, GLenum pname, const GLint *param); -typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERIUIVOESPROC) (GLuint sampler, GLenum pname, const GLuint *param); -typedef void (GL_APIENTRYP PFNGLGETSAMPLERPARAMETERIIVOESPROC) (GLuint sampler, GLenum pname, GLint *params); -typedef void (GL_APIENTRYP PFNGLGETSAMPLERPARAMETERIUIVOESPROC) (GLuint sampler, GLenum pname, GLuint *params); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glTexParameterIivOES (GLenum target, GLenum pname, const GLint *params); -GL_APICALL void GL_APIENTRY glTexParameterIuivOES (GLenum target, GLenum pname, const GLuint *params); -GL_APICALL void GL_APIENTRY glGetTexParameterIivOES (GLenum target, GLenum pname, GLint *params); -GL_APICALL void GL_APIENTRY glGetTexParameterIuivOES (GLenum target, GLenum pname, GLuint *params); -GL_APICALL void GL_APIENTRY glSamplerParameterIivOES (GLuint sampler, GLenum pname, const GLint *param); -GL_APICALL void GL_APIENTRY glSamplerParameterIuivOES (GLuint sampler, GLenum pname, const GLuint *param); -GL_APICALL void GL_APIENTRY glGetSamplerParameterIivOES (GLuint sampler, GLenum pname, GLint *params); -GL_APICALL void GL_APIENTRY glGetSamplerParameterIuivOES (GLuint sampler, GLenum pname, GLuint *params); -#endif -#endif /* GL_OES_texture_border_clamp */ - -#ifndef GL_OES_texture_buffer -#define GL_OES_texture_buffer 1 -#define GL_TEXTURE_BUFFER_OES 0x8C2A -#define GL_TEXTURE_BUFFER_BINDING_OES 0x8C2A -#define GL_MAX_TEXTURE_BUFFER_SIZE_OES 0x8C2B -#define GL_TEXTURE_BINDING_BUFFER_OES 0x8C2C -#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING_OES 0x8C2D -#define GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT_OES 0x919F -#define GL_SAMPLER_BUFFER_OES 0x8DC2 -#define GL_INT_SAMPLER_BUFFER_OES 0x8DD0 -#define GL_UNSIGNED_INT_SAMPLER_BUFFER_OES 0x8DD8 -#define GL_IMAGE_BUFFER_OES 0x9051 -#define GL_INT_IMAGE_BUFFER_OES 0x905C -#define GL_UNSIGNED_INT_IMAGE_BUFFER_OES 0x9067 -#define GL_TEXTURE_BUFFER_OFFSET_OES 0x919D -#define GL_TEXTURE_BUFFER_SIZE_OES 0x919E -typedef void (GL_APIENTRYP PFNGLTEXBUFFEROESPROC) (GLenum target, GLenum internalformat, GLuint buffer); -typedef void (GL_APIENTRYP PFNGLTEXBUFFERRANGEOESPROC) (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glTexBufferOES (GLenum target, GLenum internalformat, GLuint buffer); -GL_APICALL void GL_APIENTRY glTexBufferRangeOES (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); -#endif -#endif /* GL_OES_texture_buffer */ - -#ifndef GL_OES_texture_compression_astc -#define GL_OES_texture_compression_astc 1 -#define GL_COMPRESSED_RGBA_ASTC_3x3x3_OES 0x93C0 -#define GL_COMPRESSED_RGBA_ASTC_4x3x3_OES 0x93C1 -#define GL_COMPRESSED_RGBA_ASTC_4x4x3_OES 0x93C2 -#define GL_COMPRESSED_RGBA_ASTC_4x4x4_OES 0x93C3 -#define GL_COMPRESSED_RGBA_ASTC_5x4x4_OES 0x93C4 -#define GL_COMPRESSED_RGBA_ASTC_5x5x4_OES 0x93C5 -#define GL_COMPRESSED_RGBA_ASTC_5x5x5_OES 0x93C6 -#define GL_COMPRESSED_RGBA_ASTC_6x5x5_OES 0x93C7 -#define GL_COMPRESSED_RGBA_ASTC_6x6x5_OES 0x93C8 -#define GL_COMPRESSED_RGBA_ASTC_6x6x6_OES 0x93C9 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_3x3x3_OES 0x93E0 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x3x3_OES 0x93E1 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4x3_OES 0x93E2 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4x4_OES 0x93E3 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4x4_OES 0x93E4 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5x4_OES 0x93E5 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5x5_OES 0x93E6 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5x5_OES 0x93E7 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6x5_OES 0x93E8 -#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6x6_OES 0x93E9 -#endif /* GL_OES_texture_compression_astc */ - -#ifndef GL_OES_texture_cube_map_array -#define GL_OES_texture_cube_map_array 1 -#define GL_TEXTURE_CUBE_MAP_ARRAY_OES 0x9009 -#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_OES 0x900A -#define GL_SAMPLER_CUBE_MAP_ARRAY_OES 0x900C -#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_OES 0x900D -#define GL_INT_SAMPLER_CUBE_MAP_ARRAY_OES 0x900E -#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_OES 0x900F -#define GL_IMAGE_CUBE_MAP_ARRAY_OES 0x9054 -#define GL_INT_IMAGE_CUBE_MAP_ARRAY_OES 0x905F -#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY_OES 0x906A -#endif /* GL_OES_texture_cube_map_array */ - -#ifndef GL_OES_texture_float -#define GL_OES_texture_float 1 -#endif /* GL_OES_texture_float */ - -#ifndef GL_OES_texture_float_linear -#define GL_OES_texture_float_linear 1 -#endif /* GL_OES_texture_float_linear */ - -#ifndef GL_OES_texture_half_float -#define GL_OES_texture_half_float 1 -#define GL_HALF_FLOAT_OES 0x8D61 -#endif /* GL_OES_texture_half_float */ - -#ifndef GL_OES_texture_half_float_linear -#define GL_OES_texture_half_float_linear 1 -#endif /* GL_OES_texture_half_float_linear */ - -#ifndef GL_OES_texture_npot -#define GL_OES_texture_npot 1 -#endif /* GL_OES_texture_npot */ - -#ifndef GL_OES_texture_stencil8 -#define GL_OES_texture_stencil8 1 -#define GL_STENCIL_INDEX_OES 0x1901 -#define GL_STENCIL_INDEX8_OES 0x8D48 -#endif /* GL_OES_texture_stencil8 */ - -#ifndef GL_OES_texture_storage_multisample_2d_array -#define GL_OES_texture_storage_multisample_2d_array 1 -#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY_OES 0x9102 -#define GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY_OES 0x9105 -#define GL_SAMPLER_2D_MULTISAMPLE_ARRAY_OES 0x910B -#define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY_OES 0x910C -#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY_OES 0x910D -typedef void (GL_APIENTRYP PFNGLTEXSTORAGE3DMULTISAMPLEOESPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glTexStorage3DMultisampleOES (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); -#endif -#endif /* GL_OES_texture_storage_multisample_2d_array */ - -#ifndef GL_OES_texture_view -#define GL_OES_texture_view 1 -#define GL_TEXTURE_VIEW_MIN_LEVEL_OES 0x82DB -#define GL_TEXTURE_VIEW_NUM_LEVELS_OES 0x82DC -#define GL_TEXTURE_VIEW_MIN_LAYER_OES 0x82DD -#define GL_TEXTURE_VIEW_NUM_LAYERS_OES 0x82DE -#define GL_TEXTURE_IMMUTABLE_LEVELS 0x82DF -typedef void (GL_APIENTRYP PFNGLTEXTUREVIEWOESPROC) (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glTextureViewOES (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); -#endif -#endif /* GL_OES_texture_view */ - -#ifndef GL_OES_vertex_array_object -#define GL_OES_vertex_array_object 1 -#define GL_VERTEX_ARRAY_BINDING_OES 0x85B5 -typedef void (GL_APIENTRYP PFNGLBINDVERTEXARRAYOESPROC) (GLuint array); -typedef void (GL_APIENTRYP PFNGLDELETEVERTEXARRAYSOESPROC) (GLsizei n, const GLuint *arrays); -typedef void (GL_APIENTRYP PFNGLGENVERTEXARRAYSOESPROC) (GLsizei n, GLuint *arrays); -typedef GLboolean (GL_APIENTRYP PFNGLISVERTEXARRAYOESPROC) (GLuint array); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glBindVertexArrayOES (GLuint array); -GL_APICALL void GL_APIENTRY glDeleteVertexArraysOES (GLsizei n, const GLuint *arrays); -GL_APICALL void GL_APIENTRY glGenVertexArraysOES (GLsizei n, GLuint *arrays); -GL_APICALL GLboolean GL_APIENTRY glIsVertexArrayOES (GLuint array); -#endif -#endif /* GL_OES_vertex_array_object */ - -#ifndef GL_OES_vertex_half_float -#define GL_OES_vertex_half_float 1 -#endif /* GL_OES_vertex_half_float */ - -#ifndef GL_OES_vertex_type_10_10_10_2 -#define GL_OES_vertex_type_10_10_10_2 1 -#define GL_UNSIGNED_INT_10_10_10_2_OES 0x8DF6 -#define GL_INT_10_10_10_2_OES 0x8DF7 -#endif /* GL_OES_vertex_type_10_10_10_2 */ - -#ifndef GL_AMD_compressed_3DC_texture -#define GL_AMD_compressed_3DC_texture 1 -#define GL_3DC_X_AMD 0x87F9 -#define GL_3DC_XY_AMD 0x87FA -#endif /* GL_AMD_compressed_3DC_texture */ - -#ifndef GL_AMD_compressed_ATC_texture -#define GL_AMD_compressed_ATC_texture 1 -#define GL_ATC_RGB_AMD 0x8C92 -#define GL_ATC_RGBA_EXPLICIT_ALPHA_AMD 0x8C93 -#define GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE -#endif /* GL_AMD_compressed_ATC_texture */ - -#ifndef GL_AMD_performance_monitor -#define GL_AMD_performance_monitor 1 -#define GL_COUNTER_TYPE_AMD 0x8BC0 -#define GL_COUNTER_RANGE_AMD 0x8BC1 -#define GL_UNSIGNED_INT64_AMD 0x8BC2 -#define GL_PERCENTAGE_AMD 0x8BC3 -#define GL_PERFMON_RESULT_AVAILABLE_AMD 0x8BC4 -#define GL_PERFMON_RESULT_SIZE_AMD 0x8BC5 -#define GL_PERFMON_RESULT_AMD 0x8BC6 -typedef void (GL_APIENTRYP PFNGLGETPERFMONITORGROUPSAMDPROC) (GLint *numGroups, GLsizei groupsSize, GLuint *groups); -typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERSAMDPROC) (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters); -typedef void (GL_APIENTRYP PFNGLGETPERFMONITORGROUPSTRINGAMDPROC) (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString); -typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC) (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString); -typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERINFOAMDPROC) (GLuint group, GLuint counter, GLenum pname, void *data); -typedef void (GL_APIENTRYP PFNGLGENPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors); -typedef void (GL_APIENTRYP PFNGLDELETEPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors); -typedef void (GL_APIENTRYP PFNGLSELECTPERFMONITORCOUNTERSAMDPROC) (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *counterList); -typedef void (GL_APIENTRYP PFNGLBEGINPERFMONITORAMDPROC) (GLuint monitor); -typedef void (GL_APIENTRYP PFNGLENDPERFMONITORAMDPROC) (GLuint monitor); -typedef void (GL_APIENTRYP PFNGLGETPERFMONITORCOUNTERDATAAMDPROC) (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glGetPerfMonitorGroupsAMD (GLint *numGroups, GLsizei groupsSize, GLuint *groups); -GL_APICALL void GL_APIENTRY glGetPerfMonitorCountersAMD (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters); -GL_APICALL void GL_APIENTRY glGetPerfMonitorGroupStringAMD (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString); -GL_APICALL void GL_APIENTRY glGetPerfMonitorCounterStringAMD (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString); -GL_APICALL void GL_APIENTRY glGetPerfMonitorCounterInfoAMD (GLuint group, GLuint counter, GLenum pname, void *data); -GL_APICALL void GL_APIENTRY glGenPerfMonitorsAMD (GLsizei n, GLuint *monitors); -GL_APICALL void GL_APIENTRY glDeletePerfMonitorsAMD (GLsizei n, GLuint *monitors); -GL_APICALL void GL_APIENTRY glSelectPerfMonitorCountersAMD (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *counterList); -GL_APICALL void GL_APIENTRY glBeginPerfMonitorAMD (GLuint monitor); -GL_APICALL void GL_APIENTRY glEndPerfMonitorAMD (GLuint monitor); -GL_APICALL void GL_APIENTRY glGetPerfMonitorCounterDataAMD (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten); -#endif -#endif /* GL_AMD_performance_monitor */ - -#ifndef GL_AMD_program_binary_Z400 -#define GL_AMD_program_binary_Z400 1 -#define GL_Z400_BINARY_AMD 0x8740 -#endif /* GL_AMD_program_binary_Z400 */ - -#ifndef GL_ANDROID_extension_pack_es31a -#define GL_ANDROID_extension_pack_es31a 1 -#endif /* GL_ANDROID_extension_pack_es31a */ - -#ifndef GL_ANGLE_depth_texture -#define GL_ANGLE_depth_texture 1 -#endif /* GL_ANGLE_depth_texture */ - -#ifndef GL_ANGLE_framebuffer_blit -#define GL_ANGLE_framebuffer_blit 1 -#define GL_READ_FRAMEBUFFER_ANGLE 0x8CA8 -#define GL_DRAW_FRAMEBUFFER_ANGLE 0x8CA9 -#define GL_DRAW_FRAMEBUFFER_BINDING_ANGLE 0x8CA6 -#define GL_READ_FRAMEBUFFER_BINDING_ANGLE 0x8CAA -typedef void (GL_APIENTRYP PFNGLBLITFRAMEBUFFERANGLEPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glBlitFramebufferANGLE (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); -#endif -#endif /* GL_ANGLE_framebuffer_blit */ - -#ifndef GL_ANGLE_framebuffer_multisample -#define GL_ANGLE_framebuffer_multisample 1 -#define GL_RENDERBUFFER_SAMPLES_ANGLE 0x8CAB -#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_ANGLE 0x8D56 -#define GL_MAX_SAMPLES_ANGLE 0x8D57 -typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEANGLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleANGLE (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -#endif -#endif /* GL_ANGLE_framebuffer_multisample */ - -#ifndef GL_ANGLE_instanced_arrays -#define GL_ANGLE_instanced_arrays 1 -#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE 0x88FE -typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINSTANCEDANGLEPROC) (GLenum mode, GLint first, GLsizei count, GLsizei primcount); -typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDANGLEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); -typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBDIVISORANGLEPROC) (GLuint index, GLuint divisor); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glDrawArraysInstancedANGLE (GLenum mode, GLint first, GLsizei count, GLsizei primcount); -GL_APICALL void GL_APIENTRY glDrawElementsInstancedANGLE (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); -GL_APICALL void GL_APIENTRY glVertexAttribDivisorANGLE (GLuint index, GLuint divisor); -#endif -#endif /* GL_ANGLE_instanced_arrays */ - -#ifndef GL_ANGLE_pack_reverse_row_order -#define GL_ANGLE_pack_reverse_row_order 1 -#define GL_PACK_REVERSE_ROW_ORDER_ANGLE 0x93A4 -#endif /* GL_ANGLE_pack_reverse_row_order */ - -#ifndef GL_ANGLE_program_binary -#define GL_ANGLE_program_binary 1 -#define GL_PROGRAM_BINARY_ANGLE 0x93A6 -#endif /* GL_ANGLE_program_binary */ - -#ifndef GL_ANGLE_texture_compression_dxt3 -#define GL_ANGLE_texture_compression_dxt3 1 -#define GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE 0x83F2 -#endif /* GL_ANGLE_texture_compression_dxt3 */ - -#ifndef GL_ANGLE_texture_compression_dxt5 -#define GL_ANGLE_texture_compression_dxt5 1 -#define GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE 0x83F3 -#endif /* GL_ANGLE_texture_compression_dxt5 */ - -#ifndef GL_ANGLE_texture_usage -#define GL_ANGLE_texture_usage 1 -#define GL_TEXTURE_USAGE_ANGLE 0x93A2 -#define GL_FRAMEBUFFER_ATTACHMENT_ANGLE 0x93A3 -#endif /* GL_ANGLE_texture_usage */ - -#ifndef GL_ANGLE_translated_shader_source -#define GL_ANGLE_translated_shader_source 1 -#define GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE 0x93A0 -typedef void (GL_APIENTRYP PFNGLGETTRANSLATEDSHADERSOURCEANGLEPROC) (GLuint shader, GLsizei bufsize, GLsizei *length, GLchar *source); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glGetTranslatedShaderSourceANGLE (GLuint shader, GLsizei bufsize, GLsizei *length, GLchar *source); -#endif -#endif /* GL_ANGLE_translated_shader_source */ - -#ifndef GL_APPLE_clip_distance -#define GL_APPLE_clip_distance 1 -#define GL_MAX_CLIP_DISTANCES_APPLE 0x0D32 -#define GL_CLIP_DISTANCE0_APPLE 0x3000 -#define GL_CLIP_DISTANCE1_APPLE 0x3001 -#define GL_CLIP_DISTANCE2_APPLE 0x3002 -#define GL_CLIP_DISTANCE3_APPLE 0x3003 -#define GL_CLIP_DISTANCE4_APPLE 0x3004 -#define GL_CLIP_DISTANCE5_APPLE 0x3005 -#define GL_CLIP_DISTANCE6_APPLE 0x3006 -#define GL_CLIP_DISTANCE7_APPLE 0x3007 -#endif /* GL_APPLE_clip_distance */ - -#ifndef GL_APPLE_color_buffer_packed_float -#define GL_APPLE_color_buffer_packed_float 1 -#endif /* GL_APPLE_color_buffer_packed_float */ - -#ifndef GL_APPLE_copy_texture_levels -#define GL_APPLE_copy_texture_levels 1 -typedef void (GL_APIENTRYP PFNGLCOPYTEXTURELEVELSAPPLEPROC) (GLuint destinationTexture, GLuint sourceTexture, GLint sourceBaseLevel, GLsizei sourceLevelCount); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glCopyTextureLevelsAPPLE (GLuint destinationTexture, GLuint sourceTexture, GLint sourceBaseLevel, GLsizei sourceLevelCount); -#endif -#endif /* GL_APPLE_copy_texture_levels */ - -#ifndef GL_APPLE_framebuffer_multisample -#define GL_APPLE_framebuffer_multisample 1 -#define GL_RENDERBUFFER_SAMPLES_APPLE 0x8CAB -#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_APPLE 0x8D56 -#define GL_MAX_SAMPLES_APPLE 0x8D57 -#define GL_READ_FRAMEBUFFER_APPLE 0x8CA8 -#define GL_DRAW_FRAMEBUFFER_APPLE 0x8CA9 -#define GL_DRAW_FRAMEBUFFER_BINDING_APPLE 0x8CA6 -#define GL_READ_FRAMEBUFFER_BINDING_APPLE 0x8CAA -typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEAPPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -typedef void (GL_APIENTRYP PFNGLRESOLVEMULTISAMPLEFRAMEBUFFERAPPLEPROC) (void); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleAPPLE (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -GL_APICALL void GL_APIENTRY glResolveMultisampleFramebufferAPPLE (void); -#endif -#endif /* GL_APPLE_framebuffer_multisample */ - -#ifndef GL_APPLE_rgb_422 -#define GL_APPLE_rgb_422 1 -#define GL_RGB_422_APPLE 0x8A1F -#define GL_UNSIGNED_SHORT_8_8_APPLE 0x85BA -#define GL_UNSIGNED_SHORT_8_8_REV_APPLE 0x85BB -#define GL_RGB_RAW_422_APPLE 0x8A51 -#endif /* GL_APPLE_rgb_422 */ - -#ifndef GL_APPLE_sync -#define GL_APPLE_sync 1 -#define GL_SYNC_OBJECT_APPLE 0x8A53 -#define GL_MAX_SERVER_WAIT_TIMEOUT_APPLE 0x9111 -#define GL_OBJECT_TYPE_APPLE 0x9112 -#define GL_SYNC_CONDITION_APPLE 0x9113 -#define GL_SYNC_STATUS_APPLE 0x9114 -#define GL_SYNC_FLAGS_APPLE 0x9115 -#define GL_SYNC_FENCE_APPLE 0x9116 -#define GL_SYNC_GPU_COMMANDS_COMPLETE_APPLE 0x9117 -#define GL_UNSIGNALED_APPLE 0x9118 -#define GL_SIGNALED_APPLE 0x9119 -#define GL_ALREADY_SIGNALED_APPLE 0x911A -#define GL_TIMEOUT_EXPIRED_APPLE 0x911B -#define GL_CONDITION_SATISFIED_APPLE 0x911C -#define GL_WAIT_FAILED_APPLE 0x911D -#define GL_SYNC_FLUSH_COMMANDS_BIT_APPLE 0x00000001 -#define GL_TIMEOUT_IGNORED_APPLE 0xFFFFFFFFFFFFFFFFull -typedef GLsync (GL_APIENTRYP PFNGLFENCESYNCAPPLEPROC) (GLenum condition, GLbitfield flags); -typedef GLboolean (GL_APIENTRYP PFNGLISSYNCAPPLEPROC) (GLsync sync); -typedef void (GL_APIENTRYP PFNGLDELETESYNCAPPLEPROC) (GLsync sync); -typedef GLenum (GL_APIENTRYP PFNGLCLIENTWAITSYNCAPPLEPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout); -typedef void (GL_APIENTRYP PFNGLWAITSYNCAPPLEPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout); -typedef void (GL_APIENTRYP PFNGLGETINTEGER64VAPPLEPROC) (GLenum pname, GLint64 *params); -typedef void (GL_APIENTRYP PFNGLGETSYNCIVAPPLEPROC) (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL GLsync GL_APIENTRY glFenceSyncAPPLE (GLenum condition, GLbitfield flags); -GL_APICALL GLboolean GL_APIENTRY glIsSyncAPPLE (GLsync sync); -GL_APICALL void GL_APIENTRY glDeleteSyncAPPLE (GLsync sync); -GL_APICALL GLenum GL_APIENTRY glClientWaitSyncAPPLE (GLsync sync, GLbitfield flags, GLuint64 timeout); -GL_APICALL void GL_APIENTRY glWaitSyncAPPLE (GLsync sync, GLbitfield flags, GLuint64 timeout); -GL_APICALL void GL_APIENTRY glGetInteger64vAPPLE (GLenum pname, GLint64 *params); -GL_APICALL void GL_APIENTRY glGetSyncivAPPLE (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); -#endif -#endif /* GL_APPLE_sync */ - -#ifndef GL_APPLE_texture_format_BGRA8888 -#define GL_APPLE_texture_format_BGRA8888 1 -#define GL_BGRA_EXT 0x80E1 -#define GL_BGRA8_EXT 0x93A1 -#endif /* GL_APPLE_texture_format_BGRA8888 */ - -#ifndef GL_APPLE_texture_max_level -#define GL_APPLE_texture_max_level 1 -#define GL_TEXTURE_MAX_LEVEL_APPLE 0x813D -#endif /* GL_APPLE_texture_max_level */ - -#ifndef GL_APPLE_texture_packed_float -#define GL_APPLE_texture_packed_float 1 -#define GL_UNSIGNED_INT_10F_11F_11F_REV_APPLE 0x8C3B -#define GL_UNSIGNED_INT_5_9_9_9_REV_APPLE 0x8C3E -#define GL_R11F_G11F_B10F_APPLE 0x8C3A -#define GL_RGB9_E5_APPLE 0x8C3D -#endif /* GL_APPLE_texture_packed_float */ - -#ifndef GL_ARM_mali_program_binary -#define GL_ARM_mali_program_binary 1 -#define GL_MALI_PROGRAM_BINARY_ARM 0x8F61 -#endif /* GL_ARM_mali_program_binary */ - -#ifndef GL_ARM_mali_shader_binary -#define GL_ARM_mali_shader_binary 1 -#define GL_MALI_SHADER_BINARY_ARM 0x8F60 -#endif /* GL_ARM_mali_shader_binary */ - -#ifndef GL_ARM_rgba8 -#define GL_ARM_rgba8 1 -#endif /* GL_ARM_rgba8 */ - -#ifndef GL_ARM_shader_framebuffer_fetch -#define GL_ARM_shader_framebuffer_fetch 1 -#define GL_FETCH_PER_SAMPLE_ARM 0x8F65 -#define GL_FRAGMENT_SHADER_FRAMEBUFFER_FETCH_MRT_ARM 0x8F66 -#endif /* GL_ARM_shader_framebuffer_fetch */ - -#ifndef GL_ARM_shader_framebuffer_fetch_depth_stencil -#define GL_ARM_shader_framebuffer_fetch_depth_stencil 1 -#endif /* GL_ARM_shader_framebuffer_fetch_depth_stencil */ - -#ifndef GL_DMP_program_binary -#define GL_DMP_program_binary 1 -#define GL_SMAPHS30_PROGRAM_BINARY_DMP 0x9251 -#define GL_SMAPHS_PROGRAM_BINARY_DMP 0x9252 -#define GL_DMP_PROGRAM_BINARY_DMP 0x9253 -#endif /* GL_DMP_program_binary */ - -#ifndef GL_DMP_shader_binary -#define GL_DMP_shader_binary 1 -#define GL_SHADER_BINARY_DMP 0x9250 -#endif /* GL_DMP_shader_binary */ - -#ifndef GL_EXT_YUV_target -#define GL_EXT_YUV_target 1 -#define GL_SAMPLER_EXTERNAL_2D_Y2Y_EXT 0x8BE7 -#endif /* GL_EXT_YUV_target */ - -#ifndef GL_EXT_base_instance -#define GL_EXT_base_instance 1 -typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEEXTPROC) (GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance); -typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance); -typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glDrawArraysInstancedBaseInstanceEXT (GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance); -GL_APICALL void GL_APIENTRY glDrawElementsInstancedBaseInstanceEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance); -GL_APICALL void GL_APIENTRY glDrawElementsInstancedBaseVertexBaseInstanceEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance); -#endif -#endif /* GL_EXT_base_instance */ - -#ifndef GL_EXT_blend_func_extended -#define GL_EXT_blend_func_extended 1 -#define GL_SRC1_COLOR_EXT 0x88F9 -#define GL_SRC1_ALPHA_EXT 0x8589 -#define GL_ONE_MINUS_SRC1_COLOR_EXT 0x88FA -#define GL_ONE_MINUS_SRC1_ALPHA_EXT 0x88FB -#define GL_SRC_ALPHA_SATURATE_EXT 0x0308 -#define GL_LOCATION_INDEX_EXT 0x930F -#define GL_MAX_DUAL_SOURCE_DRAW_BUFFERS_EXT 0x88FC -typedef void (GL_APIENTRYP PFNGLBINDFRAGDATALOCATIONINDEXEDEXTPROC) (GLuint program, GLuint colorNumber, GLuint index, const GLchar *name); -typedef void (GL_APIENTRYP PFNGLBINDFRAGDATALOCATIONEXTPROC) (GLuint program, GLuint color, const GLchar *name); -typedef GLint (GL_APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONINDEXEXTPROC) (GLuint program, GLenum programInterface, const GLchar *name); -typedef GLint (GL_APIENTRYP PFNGLGETFRAGDATAINDEXEXTPROC) (GLuint program, const GLchar *name); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glBindFragDataLocationIndexedEXT (GLuint program, GLuint colorNumber, GLuint index, const GLchar *name); -GL_APICALL void GL_APIENTRY glBindFragDataLocationEXT (GLuint program, GLuint color, const GLchar *name); -GL_APICALL GLint GL_APIENTRY glGetProgramResourceLocationIndexEXT (GLuint program, GLenum programInterface, const GLchar *name); -GL_APICALL GLint GL_APIENTRY glGetFragDataIndexEXT (GLuint program, const GLchar *name); -#endif -#endif /* GL_EXT_blend_func_extended */ - -#ifndef GL_EXT_blend_minmax -#define GL_EXT_blend_minmax 1 -#define GL_MIN_EXT 0x8007 -#define GL_MAX_EXT 0x8008 -#endif /* GL_EXT_blend_minmax */ - -#ifndef GL_EXT_buffer_storage -#define GL_EXT_buffer_storage 1 -#define GL_MAP_READ_BIT 0x0001 -#define GL_MAP_WRITE_BIT 0x0002 -#define GL_MAP_PERSISTENT_BIT_EXT 0x0040 -#define GL_MAP_COHERENT_BIT_EXT 0x0080 -#define GL_DYNAMIC_STORAGE_BIT_EXT 0x0100 -#define GL_CLIENT_STORAGE_BIT_EXT 0x0200 -#define GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT_EXT 0x00004000 -#define GL_BUFFER_IMMUTABLE_STORAGE_EXT 0x821F -#define GL_BUFFER_STORAGE_FLAGS_EXT 0x8220 -typedef void (GL_APIENTRYP PFNGLBUFFERSTORAGEEXTPROC) (GLenum target, GLsizeiptr size, const void *data, GLbitfield flags); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glBufferStorageEXT (GLenum target, GLsizeiptr size, const void *data, GLbitfield flags); -#endif -#endif /* GL_EXT_buffer_storage */ - -#ifndef GL_EXT_color_buffer_float -#define GL_EXT_color_buffer_float 1 -#endif /* GL_EXT_color_buffer_float */ - -#ifndef GL_EXT_color_buffer_half_float -#define GL_EXT_color_buffer_half_float 1 -#define GL_RGBA16F_EXT 0x881A -#define GL_RGB16F_EXT 0x881B -#define GL_RG16F_EXT 0x822F -#define GL_R16F_EXT 0x822D -#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT 0x8211 -#define GL_UNSIGNED_NORMALIZED_EXT 0x8C17 -#endif /* GL_EXT_color_buffer_half_float */ - -#ifndef GL_EXT_copy_image -#define GL_EXT_copy_image 1 -typedef void (GL_APIENTRYP PFNGLCOPYIMAGESUBDATAEXTPROC) (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glCopyImageSubDataEXT (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); -#endif -#endif /* GL_EXT_copy_image */ - -#ifndef GL_EXT_debug_label -#define GL_EXT_debug_label 1 -#define GL_PROGRAM_PIPELINE_OBJECT_EXT 0x8A4F -#define GL_PROGRAM_OBJECT_EXT 0x8B40 -#define GL_SHADER_OBJECT_EXT 0x8B48 -#define GL_BUFFER_OBJECT_EXT 0x9151 -#define GL_QUERY_OBJECT_EXT 0x9153 -#define GL_VERTEX_ARRAY_OBJECT_EXT 0x9154 -#define GL_TRANSFORM_FEEDBACK 0x8E22 -typedef void (GL_APIENTRYP PFNGLLABELOBJECTEXTPROC) (GLenum type, GLuint object, GLsizei length, const GLchar *label); -typedef void (GL_APIENTRYP PFNGLGETOBJECTLABELEXTPROC) (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glLabelObjectEXT (GLenum type, GLuint object, GLsizei length, const GLchar *label); -GL_APICALL void GL_APIENTRY glGetObjectLabelEXT (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label); -#endif -#endif /* GL_EXT_debug_label */ - -#ifndef GL_EXT_debug_marker -#define GL_EXT_debug_marker 1 -typedef void (GL_APIENTRYP PFNGLINSERTEVENTMARKEREXTPROC) (GLsizei length, const GLchar *marker); -typedef void (GL_APIENTRYP PFNGLPUSHGROUPMARKEREXTPROC) (GLsizei length, const GLchar *marker); -typedef void (GL_APIENTRYP PFNGLPOPGROUPMARKEREXTPROC) (void); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glInsertEventMarkerEXT (GLsizei length, const GLchar *marker); -GL_APICALL void GL_APIENTRY glPushGroupMarkerEXT (GLsizei length, const GLchar *marker); -GL_APICALL void GL_APIENTRY glPopGroupMarkerEXT (void); -#endif -#endif /* GL_EXT_debug_marker */ - -#ifndef GL_EXT_discard_framebuffer -#define GL_EXT_discard_framebuffer 1 -#define GL_COLOR_EXT 0x1800 -#define GL_DEPTH_EXT 0x1801 -#define GL_STENCIL_EXT 0x1802 -typedef void (GL_APIENTRYP PFNGLDISCARDFRAMEBUFFEREXTPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glDiscardFramebufferEXT (GLenum target, GLsizei numAttachments, const GLenum *attachments); -#endif -#endif /* GL_EXT_discard_framebuffer */ - -#ifndef GL_EXT_disjoint_timer_query -#define GL_EXT_disjoint_timer_query 1 -#define GL_QUERY_COUNTER_BITS_EXT 0x8864 -#define GL_CURRENT_QUERY_EXT 0x8865 -#define GL_QUERY_RESULT_EXT 0x8866 -#define GL_QUERY_RESULT_AVAILABLE_EXT 0x8867 -#define GL_TIME_ELAPSED_EXT 0x88BF -#define GL_TIMESTAMP_EXT 0x8E28 -#define GL_GPU_DISJOINT_EXT 0x8FBB -typedef void (GL_APIENTRYP PFNGLGENQUERIESEXTPROC) (GLsizei n, GLuint *ids); -typedef void (GL_APIENTRYP PFNGLDELETEQUERIESEXTPROC) (GLsizei n, const GLuint *ids); -typedef GLboolean (GL_APIENTRYP PFNGLISQUERYEXTPROC) (GLuint id); -typedef void (GL_APIENTRYP PFNGLBEGINQUERYEXTPROC) (GLenum target, GLuint id); -typedef void (GL_APIENTRYP PFNGLENDQUERYEXTPROC) (GLenum target); -typedef void (GL_APIENTRYP PFNGLQUERYCOUNTEREXTPROC) (GLuint id, GLenum target); -typedef void (GL_APIENTRYP PFNGLGETQUERYIVEXTPROC) (GLenum target, GLenum pname, GLint *params); -typedef void (GL_APIENTRYP PFNGLGETQUERYOBJECTIVEXTPROC) (GLuint id, GLenum pname, GLint *params); -typedef void (GL_APIENTRYP PFNGLGETQUERYOBJECTUIVEXTPROC) (GLuint id, GLenum pname, GLuint *params); -typedef void (GL_APIENTRYP PFNGLGETQUERYOBJECTI64VEXTPROC) (GLuint id, GLenum pname, GLint64 *params); -typedef void (GL_APIENTRYP PFNGLGETQUERYOBJECTUI64VEXTPROC) (GLuint id, GLenum pname, GLuint64 *params); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glGenQueriesEXT (GLsizei n, GLuint *ids); -GL_APICALL void GL_APIENTRY glDeleteQueriesEXT (GLsizei n, const GLuint *ids); -GL_APICALL GLboolean GL_APIENTRY glIsQueryEXT (GLuint id); -GL_APICALL void GL_APIENTRY glBeginQueryEXT (GLenum target, GLuint id); -GL_APICALL void GL_APIENTRY glEndQueryEXT (GLenum target); -GL_APICALL void GL_APIENTRY glQueryCounterEXT (GLuint id, GLenum target); -GL_APICALL void GL_APIENTRY glGetQueryivEXT (GLenum target, GLenum pname, GLint *params); -GL_APICALL void GL_APIENTRY glGetQueryObjectivEXT (GLuint id, GLenum pname, GLint *params); -GL_APICALL void GL_APIENTRY glGetQueryObjectuivEXT (GLuint id, GLenum pname, GLuint *params); -GL_APICALL void GL_APIENTRY glGetQueryObjecti64vEXT (GLuint id, GLenum pname, GLint64 *params); -GL_APICALL void GL_APIENTRY glGetQueryObjectui64vEXT (GLuint id, GLenum pname, GLuint64 *params); -#endif -#endif /* GL_EXT_disjoint_timer_query */ - -#ifndef GL_EXT_draw_buffers -#define GL_EXT_draw_buffers 1 -#define GL_MAX_COLOR_ATTACHMENTS_EXT 0x8CDF -#define GL_MAX_DRAW_BUFFERS_EXT 0x8824 -#define GL_DRAW_BUFFER0_EXT 0x8825 -#define GL_DRAW_BUFFER1_EXT 0x8826 -#define GL_DRAW_BUFFER2_EXT 0x8827 -#define GL_DRAW_BUFFER3_EXT 0x8828 -#define GL_DRAW_BUFFER4_EXT 0x8829 -#define GL_DRAW_BUFFER5_EXT 0x882A -#define GL_DRAW_BUFFER6_EXT 0x882B -#define GL_DRAW_BUFFER7_EXT 0x882C -#define GL_DRAW_BUFFER8_EXT 0x882D -#define GL_DRAW_BUFFER9_EXT 0x882E -#define GL_DRAW_BUFFER10_EXT 0x882F -#define GL_DRAW_BUFFER11_EXT 0x8830 -#define GL_DRAW_BUFFER12_EXT 0x8831 -#define GL_DRAW_BUFFER13_EXT 0x8832 -#define GL_DRAW_BUFFER14_EXT 0x8833 -#define GL_DRAW_BUFFER15_EXT 0x8834 -#define GL_COLOR_ATTACHMENT0_EXT 0x8CE0 -#define GL_COLOR_ATTACHMENT1_EXT 0x8CE1 -#define GL_COLOR_ATTACHMENT2_EXT 0x8CE2 -#define GL_COLOR_ATTACHMENT3_EXT 0x8CE3 -#define GL_COLOR_ATTACHMENT4_EXT 0x8CE4 -#define GL_COLOR_ATTACHMENT5_EXT 0x8CE5 -#define GL_COLOR_ATTACHMENT6_EXT 0x8CE6 -#define GL_COLOR_ATTACHMENT7_EXT 0x8CE7 -#define GL_COLOR_ATTACHMENT8_EXT 0x8CE8 -#define GL_COLOR_ATTACHMENT9_EXT 0x8CE9 -#define GL_COLOR_ATTACHMENT10_EXT 0x8CEA -#define GL_COLOR_ATTACHMENT11_EXT 0x8CEB -#define GL_COLOR_ATTACHMENT12_EXT 0x8CEC -#define GL_COLOR_ATTACHMENT13_EXT 0x8CED -#define GL_COLOR_ATTACHMENT14_EXT 0x8CEE -#define GL_COLOR_ATTACHMENT15_EXT 0x8CEF -typedef void (GL_APIENTRYP PFNGLDRAWBUFFERSEXTPROC) (GLsizei n, const GLenum *bufs); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glDrawBuffersEXT (GLsizei n, const GLenum *bufs); -#endif -#endif /* GL_EXT_draw_buffers */ - -#ifndef GL_EXT_draw_buffers_indexed -#define GL_EXT_draw_buffers_indexed 1 -typedef void (GL_APIENTRYP PFNGLENABLEIEXTPROC) (GLenum target, GLuint index); -typedef void (GL_APIENTRYP PFNGLDISABLEIEXTPROC) (GLenum target, GLuint index); -typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONIEXTPROC) (GLuint buf, GLenum mode); -typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONSEPARATEIEXTPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha); -typedef void (GL_APIENTRYP PFNGLBLENDFUNCIEXTPROC) (GLuint buf, GLenum src, GLenum dst); -typedef void (GL_APIENTRYP PFNGLBLENDFUNCSEPARATEIEXTPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); -typedef void (GL_APIENTRYP PFNGLCOLORMASKIEXTPROC) (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); -typedef GLboolean (GL_APIENTRYP PFNGLISENABLEDIEXTPROC) (GLenum target, GLuint index); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glEnableiEXT (GLenum target, GLuint index); -GL_APICALL void GL_APIENTRY glDisableiEXT (GLenum target, GLuint index); -GL_APICALL void GL_APIENTRY glBlendEquationiEXT (GLuint buf, GLenum mode); -GL_APICALL void GL_APIENTRY glBlendEquationSeparateiEXT (GLuint buf, GLenum modeRGB, GLenum modeAlpha); -GL_APICALL void GL_APIENTRY glBlendFunciEXT (GLuint buf, GLenum src, GLenum dst); -GL_APICALL void GL_APIENTRY glBlendFuncSeparateiEXT (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); -GL_APICALL void GL_APIENTRY glColorMaskiEXT (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); -GL_APICALL GLboolean GL_APIENTRY glIsEnablediEXT (GLenum target, GLuint index); -#endif -#endif /* GL_EXT_draw_buffers_indexed */ - -#ifndef GL_EXT_draw_elements_base_vertex -#define GL_EXT_draw_elements_base_vertex 1 -typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); -typedef void (GL_APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXEXTPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); -typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); -typedef void (GL_APIENTRYP PFNGLMULTIDRAWELEMENTSBASEVERTEXEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount, const GLint *basevertex); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glDrawElementsBaseVertexEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); -GL_APICALL void GL_APIENTRY glDrawRangeElementsBaseVertexEXT (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); -GL_APICALL void GL_APIENTRY glDrawElementsInstancedBaseVertexEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); -GL_APICALL void GL_APIENTRY glMultiDrawElementsBaseVertexEXT (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount, const GLint *basevertex); -#endif -#endif /* GL_EXT_draw_elements_base_vertex */ - -#ifndef GL_EXT_draw_instanced -#define GL_EXT_draw_instanced 1 -typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINSTANCEDEXTPROC) (GLenum mode, GLint start, GLsizei count, GLsizei primcount); -typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glDrawArraysInstancedEXT (GLenum mode, GLint start, GLsizei count, GLsizei primcount); -GL_APICALL void GL_APIENTRY glDrawElementsInstancedEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); -#endif -#endif /* GL_EXT_draw_instanced */ - -#ifndef GL_EXT_float_blend -#define GL_EXT_float_blend 1 -#endif /* GL_EXT_float_blend */ - -#ifndef GL_EXT_geometry_point_size -#define GL_EXT_geometry_point_size 1 -#endif /* GL_EXT_geometry_point_size */ - -#ifndef GL_EXT_geometry_shader -#define GL_EXT_geometry_shader 1 -#define GL_GEOMETRY_SHADER_EXT 0x8DD9 -#define GL_GEOMETRY_SHADER_BIT_EXT 0x00000004 -#define GL_GEOMETRY_LINKED_VERTICES_OUT_EXT 0x8916 -#define GL_GEOMETRY_LINKED_INPUT_TYPE_EXT 0x8917 -#define GL_GEOMETRY_LINKED_OUTPUT_TYPE_EXT 0x8918 -#define GL_GEOMETRY_SHADER_INVOCATIONS_EXT 0x887F -#define GL_LAYER_PROVOKING_VERTEX_EXT 0x825E -#define GL_LINES_ADJACENCY_EXT 0x000A -#define GL_LINE_STRIP_ADJACENCY_EXT 0x000B -#define GL_TRIANGLES_ADJACENCY_EXT 0x000C -#define GL_TRIANGLE_STRIP_ADJACENCY_EXT 0x000D -#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT 0x8DDF -#define GL_MAX_GEOMETRY_UNIFORM_BLOCKS_EXT 0x8A2C -#define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS_EXT 0x8A32 -#define GL_MAX_GEOMETRY_INPUT_COMPONENTS_EXT 0x9123 -#define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS_EXT 0x9124 -#define GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT 0x8DE0 -#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_EXT 0x8DE1 -#define GL_MAX_GEOMETRY_SHADER_INVOCATIONS_EXT 0x8E5A -#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_EXT 0x8C29 -#define GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS_EXT 0x92CF -#define GL_MAX_GEOMETRY_ATOMIC_COUNTERS_EXT 0x92D5 -#define GL_MAX_GEOMETRY_IMAGE_UNIFORMS_EXT 0x90CD -#define GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS_EXT 0x90D7 -#define GL_FIRST_VERTEX_CONVENTION_EXT 0x8E4D -#define GL_LAST_VERTEX_CONVENTION_EXT 0x8E4E -#define GL_UNDEFINED_VERTEX_EXT 0x8260 -#define GL_PRIMITIVES_GENERATED_EXT 0x8C87 -#define GL_FRAMEBUFFER_DEFAULT_LAYERS_EXT 0x9312 -#define GL_MAX_FRAMEBUFFER_LAYERS_EXT 0x9317 -#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_EXT 0x8DA8 -#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_EXT 0x8DA7 -#define GL_REFERENCED_BY_GEOMETRY_SHADER_EXT 0x9309 -typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTUREEXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glFramebufferTextureEXT (GLenum target, GLenum attachment, GLuint texture, GLint level); -#endif -#endif /* GL_EXT_geometry_shader */ - -#ifndef GL_EXT_gpu_shader5 -#define GL_EXT_gpu_shader5 1 -#endif /* GL_EXT_gpu_shader5 */ - -#ifndef GL_EXT_instanced_arrays -#define GL_EXT_instanced_arrays 1 -#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR_EXT 0x88FE -typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBDIVISOREXTPROC) (GLuint index, GLuint divisor); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glVertexAttribDivisorEXT (GLuint index, GLuint divisor); -#endif -#endif /* GL_EXT_instanced_arrays */ - -#ifndef GL_EXT_map_buffer_range -#define GL_EXT_map_buffer_range 1 -#define GL_MAP_READ_BIT_EXT 0x0001 -#define GL_MAP_WRITE_BIT_EXT 0x0002 -#define GL_MAP_INVALIDATE_RANGE_BIT_EXT 0x0004 -#define GL_MAP_INVALIDATE_BUFFER_BIT_EXT 0x0008 -#define GL_MAP_FLUSH_EXPLICIT_BIT_EXT 0x0010 -#define GL_MAP_UNSYNCHRONIZED_BIT_EXT 0x0020 -typedef void *(GL_APIENTRYP PFNGLMAPBUFFERRANGEEXTPROC) (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); -typedef void (GL_APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEEXTPROC) (GLenum target, GLintptr offset, GLsizeiptr length); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void *GL_APIENTRY glMapBufferRangeEXT (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); -GL_APICALL void GL_APIENTRY glFlushMappedBufferRangeEXT (GLenum target, GLintptr offset, GLsizeiptr length); -#endif -#endif /* GL_EXT_map_buffer_range */ - -#ifndef GL_EXT_multi_draw_arrays -#define GL_EXT_multi_draw_arrays 1 -typedef void (GL_APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount); -typedef void (GL_APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glMultiDrawArraysEXT (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount); -GL_APICALL void GL_APIENTRY glMultiDrawElementsEXT (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount); -#endif -#endif /* GL_EXT_multi_draw_arrays */ - -#ifndef GL_EXT_multi_draw_indirect -#define GL_EXT_multi_draw_indirect 1 -typedef void (GL_APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTEXTPROC) (GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride); -typedef void (GL_APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTEXTPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei drawcount, GLsizei stride); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glMultiDrawArraysIndirectEXT (GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride); -GL_APICALL void GL_APIENTRY glMultiDrawElementsIndirectEXT (GLenum mode, GLenum type, const void *indirect, GLsizei drawcount, GLsizei stride); -#endif -#endif /* GL_EXT_multi_draw_indirect */ - -#ifndef GL_EXT_multisampled_compatibility -#define GL_EXT_multisampled_compatibility 1 -#define GL_MULTISAMPLE_EXT 0x809D -#define GL_SAMPLE_ALPHA_TO_ONE_EXT 0x809F -#endif /* GL_EXT_multisampled_compatibility */ - -#ifndef GL_EXT_multisampled_render_to_texture -#define GL_EXT_multisampled_render_to_texture 1 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT 0x8D6C -#define GL_RENDERBUFFER_SAMPLES_EXT 0x8CAB -#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT 0x8D56 -#define GL_MAX_SAMPLES_EXT 0x8D57 -typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleEXT (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -GL_APICALL void GL_APIENTRY glFramebufferTexture2DMultisampleEXT (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples); -#endif -#endif /* GL_EXT_multisampled_render_to_texture */ - -#ifndef GL_EXT_multiview_draw_buffers -#define GL_EXT_multiview_draw_buffers 1 -#define GL_COLOR_ATTACHMENT_EXT 0x90F0 -#define GL_MULTIVIEW_EXT 0x90F1 -#define GL_DRAW_BUFFER_EXT 0x0C01 -#define GL_READ_BUFFER_EXT 0x0C02 -#define GL_MAX_MULTIVIEW_BUFFERS_EXT 0x90F2 -typedef void (GL_APIENTRYP PFNGLREADBUFFERINDEXEDEXTPROC) (GLenum src, GLint index); -typedef void (GL_APIENTRYP PFNGLDRAWBUFFERSINDEXEDEXTPROC) (GLint n, const GLenum *location, const GLint *indices); -typedef void (GL_APIENTRYP PFNGLGETINTEGERI_VEXTPROC) (GLenum target, GLuint index, GLint *data); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glReadBufferIndexedEXT (GLenum src, GLint index); -GL_APICALL void GL_APIENTRY glDrawBuffersIndexedEXT (GLint n, const GLenum *location, const GLint *indices); -GL_APICALL void GL_APIENTRY glGetIntegeri_vEXT (GLenum target, GLuint index, GLint *data); -#endif -#endif /* GL_EXT_multiview_draw_buffers */ - -#ifndef GL_EXT_occlusion_query_boolean -#define GL_EXT_occlusion_query_boolean 1 -#define GL_ANY_SAMPLES_PASSED_EXT 0x8C2F -#define GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT 0x8D6A -#endif /* GL_EXT_occlusion_query_boolean */ - -#ifndef GL_EXT_polygon_offset_clamp -#define GL_EXT_polygon_offset_clamp 1 -#define GL_POLYGON_OFFSET_CLAMP_EXT 0x8E1B -typedef void (GL_APIENTRYP PFNGLPOLYGONOFFSETCLAMPEXTPROC) (GLfloat factor, GLfloat units, GLfloat clamp); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glPolygonOffsetClampEXT (GLfloat factor, GLfloat units, GLfloat clamp); -#endif -#endif /* GL_EXT_polygon_offset_clamp */ - -#ifndef GL_EXT_post_depth_coverage -#define GL_EXT_post_depth_coverage 1 -#endif /* GL_EXT_post_depth_coverage */ - -#ifndef GL_EXT_primitive_bounding_box -#define GL_EXT_primitive_bounding_box 1 -#define GL_PRIMITIVE_BOUNDING_BOX_EXT 0x92BE -typedef void (GL_APIENTRYP PFNGLPRIMITIVEBOUNDINGBOXEXTPROC) (GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glPrimitiveBoundingBoxEXT (GLfloat minX, GLfloat minY, GLfloat minZ, GLfloat minW, GLfloat maxX, GLfloat maxY, GLfloat maxZ, GLfloat maxW); -#endif -#endif /* GL_EXT_primitive_bounding_box */ - -#ifndef GL_EXT_pvrtc_sRGB -#define GL_EXT_pvrtc_sRGB 1 -#define GL_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT 0x8A54 -#define GL_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT 0x8A55 -#define GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT 0x8A56 -#define GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT 0x8A57 -#define GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV2_IMG 0x93F0 -#define GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV2_IMG 0x93F1 -#endif /* GL_EXT_pvrtc_sRGB */ - -#ifndef GL_EXT_raster_multisample -#define GL_EXT_raster_multisample 1 -#define GL_RASTER_MULTISAMPLE_EXT 0x9327 -#define GL_RASTER_SAMPLES_EXT 0x9328 -#define GL_MAX_RASTER_SAMPLES_EXT 0x9329 -#define GL_RASTER_FIXED_SAMPLE_LOCATIONS_EXT 0x932A -#define GL_MULTISAMPLE_RASTERIZATION_ALLOWED_EXT 0x932B -#define GL_EFFECTIVE_RASTER_SAMPLES_EXT 0x932C -typedef void (GL_APIENTRYP PFNGLRASTERSAMPLESEXTPROC) (GLuint samples, GLboolean fixedsamplelocations); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glRasterSamplesEXT (GLuint samples, GLboolean fixedsamplelocations); -#endif -#endif /* GL_EXT_raster_multisample */ - -#ifndef GL_EXT_read_format_bgra -#define GL_EXT_read_format_bgra 1 -#define GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT 0x8365 -#define GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT 0x8366 -#endif /* GL_EXT_read_format_bgra */ - -#ifndef GL_EXT_render_snorm -#define GL_EXT_render_snorm 1 -#define GL_R8_SNORM 0x8F94 -#define GL_RG8_SNORM 0x8F95 -#define GL_RGBA8_SNORM 0x8F97 -#define GL_R16_SNORM_EXT 0x8F98 -#define GL_RG16_SNORM_EXT 0x8F99 -#define GL_RGBA16_SNORM_EXT 0x8F9B -#endif /* GL_EXT_render_snorm */ - -#ifndef GL_EXT_robustness -#define GL_EXT_robustness 1 -#define GL_GUILTY_CONTEXT_RESET_EXT 0x8253 -#define GL_INNOCENT_CONTEXT_RESET_EXT 0x8254 -#define GL_UNKNOWN_CONTEXT_RESET_EXT 0x8255 -#define GL_CONTEXT_ROBUST_ACCESS_EXT 0x90F3 -#define GL_RESET_NOTIFICATION_STRATEGY_EXT 0x8256 -#define GL_LOSE_CONTEXT_ON_RESET_EXT 0x8252 -#define GL_NO_RESET_NOTIFICATION_EXT 0x8261 -typedef GLenum (GL_APIENTRYP PFNGLGETGRAPHICSRESETSTATUSEXTPROC) (void); -typedef void (GL_APIENTRYP PFNGLREADNPIXELSEXTPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); -typedef void (GL_APIENTRYP PFNGLGETNUNIFORMFVEXTPROC) (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); -typedef void (GL_APIENTRYP PFNGLGETNUNIFORMIVEXTPROC) (GLuint program, GLint location, GLsizei bufSize, GLint *params); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL GLenum GL_APIENTRY glGetGraphicsResetStatusEXT (void); -GL_APICALL void GL_APIENTRY glReadnPixelsEXT (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); -GL_APICALL void GL_APIENTRY glGetnUniformfvEXT (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); -GL_APICALL void GL_APIENTRY glGetnUniformivEXT (GLuint program, GLint location, GLsizei bufSize, GLint *params); -#endif -#endif /* GL_EXT_robustness */ - -#ifndef GL_EXT_sRGB -#define GL_EXT_sRGB 1 -#define GL_SRGB_EXT 0x8C40 -#define GL_SRGB_ALPHA_EXT 0x8C42 -#define GL_SRGB8_ALPHA8_EXT 0x8C43 -#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT 0x8210 -#endif /* GL_EXT_sRGB */ - -#ifndef GL_EXT_sRGB_write_control -#define GL_EXT_sRGB_write_control 1 -#define GL_FRAMEBUFFER_SRGB_EXT 0x8DB9 -#endif /* GL_EXT_sRGB_write_control */ - -#ifndef GL_EXT_separate_shader_objects -#define GL_EXT_separate_shader_objects 1 -#define GL_ACTIVE_PROGRAM_EXT 0x8259 -#define GL_VERTEX_SHADER_BIT_EXT 0x00000001 -#define GL_FRAGMENT_SHADER_BIT_EXT 0x00000002 -#define GL_ALL_SHADER_BITS_EXT 0xFFFFFFFF -#define GL_PROGRAM_SEPARABLE_EXT 0x8258 -#define GL_PROGRAM_PIPELINE_BINDING_EXT 0x825A -typedef void (GL_APIENTRYP PFNGLACTIVESHADERPROGRAMEXTPROC) (GLuint pipeline, GLuint program); -typedef void (GL_APIENTRYP PFNGLBINDPROGRAMPIPELINEEXTPROC) (GLuint pipeline); -typedef GLuint (GL_APIENTRYP PFNGLCREATESHADERPROGRAMVEXTPROC) (GLenum type, GLsizei count, const GLchar **strings); -typedef void (GL_APIENTRYP PFNGLDELETEPROGRAMPIPELINESEXTPROC) (GLsizei n, const GLuint *pipelines); -typedef void (GL_APIENTRYP PFNGLGENPROGRAMPIPELINESEXTPROC) (GLsizei n, GLuint *pipelines); -typedef void (GL_APIENTRYP PFNGLGETPROGRAMPIPELINEINFOLOGEXTPROC) (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog); -typedef void (GL_APIENTRYP PFNGLGETPROGRAMPIPELINEIVEXTPROC) (GLuint pipeline, GLenum pname, GLint *params); -typedef GLboolean (GL_APIENTRYP PFNGLISPROGRAMPIPELINEEXTPROC) (GLuint pipeline); -typedef void (GL_APIENTRYP PFNGLPROGRAMPARAMETERIEXTPROC) (GLuint program, GLenum pname, GLint value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1FEXTPROC) (GLuint program, GLint location, GLfloat v0); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1IEXTPROC) (GLuint program, GLint location, GLint v0); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLUSEPROGRAMSTAGESEXTPROC) (GLuint pipeline, GLbitfield stages, GLuint program); -typedef void (GL_APIENTRYP PFNGLVALIDATEPROGRAMPIPELINEEXTPROC) (GLuint pipeline); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1UIEXTPROC) (GLuint program, GLint location, GLuint v0); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM1UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM2UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM3UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORM4UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glActiveShaderProgramEXT (GLuint pipeline, GLuint program); -GL_APICALL void GL_APIENTRY glBindProgramPipelineEXT (GLuint pipeline); -GL_APICALL GLuint GL_APIENTRY glCreateShaderProgramvEXT (GLenum type, GLsizei count, const GLchar **strings); -GL_APICALL void GL_APIENTRY glDeleteProgramPipelinesEXT (GLsizei n, const GLuint *pipelines); -GL_APICALL void GL_APIENTRY glGenProgramPipelinesEXT (GLsizei n, GLuint *pipelines); -GL_APICALL void GL_APIENTRY glGetProgramPipelineInfoLogEXT (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog); -GL_APICALL void GL_APIENTRY glGetProgramPipelineivEXT (GLuint pipeline, GLenum pname, GLint *params); -GL_APICALL GLboolean GL_APIENTRY glIsProgramPipelineEXT (GLuint pipeline); -GL_APICALL void GL_APIENTRY glProgramParameteriEXT (GLuint program, GLenum pname, GLint value); -GL_APICALL void GL_APIENTRY glProgramUniform1fEXT (GLuint program, GLint location, GLfloat v0); -GL_APICALL void GL_APIENTRY glProgramUniform1fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); -GL_APICALL void GL_APIENTRY glProgramUniform1iEXT (GLuint program, GLint location, GLint v0); -GL_APICALL void GL_APIENTRY glProgramUniform1ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); -GL_APICALL void GL_APIENTRY glProgramUniform2fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1); -GL_APICALL void GL_APIENTRY glProgramUniform2fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); -GL_APICALL void GL_APIENTRY glProgramUniform2iEXT (GLuint program, GLint location, GLint v0, GLint v1); -GL_APICALL void GL_APIENTRY glProgramUniform2ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); -GL_APICALL void GL_APIENTRY glProgramUniform3fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); -GL_APICALL void GL_APIENTRY glProgramUniform3fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); -GL_APICALL void GL_APIENTRY glProgramUniform3iEXT (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); -GL_APICALL void GL_APIENTRY glProgramUniform3ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); -GL_APICALL void GL_APIENTRY glProgramUniform4fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); -GL_APICALL void GL_APIENTRY glProgramUniform4fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); -GL_APICALL void GL_APIENTRY glProgramUniform4iEXT (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); -GL_APICALL void GL_APIENTRY glProgramUniform4ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); -GL_APICALL void GL_APIENTRY glProgramUniformMatrix2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glProgramUniformMatrix3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glProgramUniformMatrix4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glUseProgramStagesEXT (GLuint pipeline, GLbitfield stages, GLuint program); -GL_APICALL void GL_APIENTRY glValidateProgramPipelineEXT (GLuint pipeline); -GL_APICALL void GL_APIENTRY glProgramUniform1uiEXT (GLuint program, GLint location, GLuint v0); -GL_APICALL void GL_APIENTRY glProgramUniform2uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1); -GL_APICALL void GL_APIENTRY glProgramUniform3uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); -GL_APICALL void GL_APIENTRY glProgramUniform4uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); -GL_APICALL void GL_APIENTRY glProgramUniform1uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); -GL_APICALL void GL_APIENTRY glProgramUniform2uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); -GL_APICALL void GL_APIENTRY glProgramUniform3uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); -GL_APICALL void GL_APIENTRY glProgramUniform4uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); -GL_APICALL void GL_APIENTRY glProgramUniformMatrix2x3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glProgramUniformMatrix3x2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glProgramUniformMatrix2x4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glProgramUniformMatrix4x2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glProgramUniformMatrix3x4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glProgramUniformMatrix4x3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -#endif -#endif /* GL_EXT_separate_shader_objects */ - -#ifndef GL_EXT_shader_framebuffer_fetch -#define GL_EXT_shader_framebuffer_fetch 1 -#define GL_FRAGMENT_SHADER_DISCARDS_SAMPLES_EXT 0x8A52 -#endif /* GL_EXT_shader_framebuffer_fetch */ - -#ifndef GL_EXT_shader_group_vote -#define GL_EXT_shader_group_vote 1 -#endif /* GL_EXT_shader_group_vote */ - -#ifndef GL_EXT_shader_implicit_conversions -#define GL_EXT_shader_implicit_conversions 1 -#endif /* GL_EXT_shader_implicit_conversions */ - -#ifndef GL_EXT_shader_integer_mix -#define GL_EXT_shader_integer_mix 1 -#endif /* GL_EXT_shader_integer_mix */ - -#ifndef GL_EXT_shader_io_blocks -#define GL_EXT_shader_io_blocks 1 -#endif /* GL_EXT_shader_io_blocks */ - -#ifndef GL_EXT_shader_pixel_local_storage -#define GL_EXT_shader_pixel_local_storage 1 -#define GL_MAX_SHADER_PIXEL_LOCAL_STORAGE_FAST_SIZE_EXT 0x8F63 -#define GL_MAX_SHADER_PIXEL_LOCAL_STORAGE_SIZE_EXT 0x8F67 -#define GL_SHADER_PIXEL_LOCAL_STORAGE_EXT 0x8F64 -#endif /* GL_EXT_shader_pixel_local_storage */ - -#ifndef GL_EXT_shader_pixel_local_storage2 -#define GL_EXT_shader_pixel_local_storage2 1 -#define GL_MAX_SHADER_COMBINED_LOCAL_STORAGE_FAST_SIZE_EXT 0x9650 -#define GL_MAX_SHADER_COMBINED_LOCAL_STORAGE_SIZE_EXT 0x9651 -#define GL_FRAMEBUFFER_INCOMPLETE_INSUFFICIENT_SHADER_COMBINED_LOCAL_STORAGE_EXT 0x9652 -typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERPIXELLOCALSTORAGESIZEEXTPROC) (GLuint target, GLsizei size); -typedef GLsizei (GL_APIENTRYP PFNGLGETFRAMEBUFFERPIXELLOCALSTORAGESIZEEXTPROC) (GLuint target); -typedef void (GL_APIENTRYP PFNGLCLEARPIXELLOCALSTORAGEUIEXTPROC) (GLsizei offset, GLsizei n, const GLuint *values); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glFramebufferPixelLocalStorageSizeEXT (GLuint target, GLsizei size); -GL_APICALL GLsizei GL_APIENTRY glGetFramebufferPixelLocalStorageSizeEXT (GLuint target); -GL_APICALL void GL_APIENTRY glClearPixelLocalStorageuiEXT (GLsizei offset, GLsizei n, const GLuint *values); -#endif -#endif /* GL_EXT_shader_pixel_local_storage2 */ - -#ifndef GL_EXT_shader_texture_lod -#define GL_EXT_shader_texture_lod 1 -#endif /* GL_EXT_shader_texture_lod */ - -#ifndef GL_EXT_shadow_samplers -#define GL_EXT_shadow_samplers 1 -#define GL_TEXTURE_COMPARE_MODE_EXT 0x884C -#define GL_TEXTURE_COMPARE_FUNC_EXT 0x884D -#define GL_COMPARE_REF_TO_TEXTURE_EXT 0x884E -#define GL_SAMPLER_2D_SHADOW_EXT 0x8B62 -#endif /* GL_EXT_shadow_samplers */ - -#ifndef GL_EXT_sparse_texture -#define GL_EXT_sparse_texture 1 -#define GL_TEXTURE_SPARSE_EXT 0x91A6 -#define GL_VIRTUAL_PAGE_SIZE_INDEX_EXT 0x91A7 -#define GL_NUM_SPARSE_LEVELS_EXT 0x91AA -#define GL_NUM_VIRTUAL_PAGE_SIZES_EXT 0x91A8 -#define GL_VIRTUAL_PAGE_SIZE_X_EXT 0x9195 -#define GL_VIRTUAL_PAGE_SIZE_Y_EXT 0x9196 -#define GL_VIRTUAL_PAGE_SIZE_Z_EXT 0x9197 -#define GL_TEXTURE_2D_ARRAY 0x8C1A -#define GL_TEXTURE_3D 0x806F -#define GL_MAX_SPARSE_TEXTURE_SIZE_EXT 0x9198 -#define GL_MAX_SPARSE_3D_TEXTURE_SIZE_EXT 0x9199 -#define GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS_EXT 0x919A -#define GL_SPARSE_TEXTURE_FULL_ARRAY_CUBE_MIPMAPS_EXT 0x91A9 -typedef void (GL_APIENTRYP PFNGLTEXPAGECOMMITMENTEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glTexPageCommitmentEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean commit); -#endif -#endif /* GL_EXT_sparse_texture */ - -#ifndef GL_EXT_tessellation_point_size -#define GL_EXT_tessellation_point_size 1 -#endif /* GL_EXT_tessellation_point_size */ - -#ifndef GL_EXT_tessellation_shader -#define GL_EXT_tessellation_shader 1 -#define GL_PATCHES_EXT 0x000E -#define GL_PATCH_VERTICES_EXT 0x8E72 -#define GL_TESS_CONTROL_OUTPUT_VERTICES_EXT 0x8E75 -#define GL_TESS_GEN_MODE_EXT 0x8E76 -#define GL_TESS_GEN_SPACING_EXT 0x8E77 -#define GL_TESS_GEN_VERTEX_ORDER_EXT 0x8E78 -#define GL_TESS_GEN_POINT_MODE_EXT 0x8E79 -#define GL_ISOLINES_EXT 0x8E7A -#define GL_QUADS_EXT 0x0007 -#define GL_FRACTIONAL_ODD_EXT 0x8E7B -#define GL_FRACTIONAL_EVEN_EXT 0x8E7C -#define GL_MAX_PATCH_VERTICES_EXT 0x8E7D -#define GL_MAX_TESS_GEN_LEVEL_EXT 0x8E7E -#define GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS_EXT 0x8E7F -#define GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS_EXT 0x8E80 -#define GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS_EXT 0x8E81 -#define GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS_EXT 0x8E82 -#define GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS_EXT 0x8E83 -#define GL_MAX_TESS_PATCH_COMPONENTS_EXT 0x8E84 -#define GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS_EXT 0x8E85 -#define GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS_EXT 0x8E86 -#define GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS_EXT 0x8E89 -#define GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS_EXT 0x8E8A -#define GL_MAX_TESS_CONTROL_INPUT_COMPONENTS_EXT 0x886C -#define GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS_EXT 0x886D -#define GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS_EXT 0x8E1E -#define GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS_EXT 0x8E1F -#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS_EXT 0x92CD -#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS_EXT 0x92CE -#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS_EXT 0x92D3 -#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS_EXT 0x92D4 -#define GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS_EXT 0x90CB -#define GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS_EXT 0x90CC -#define GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS_EXT 0x90D8 -#define GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS_EXT 0x90D9 -#define GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED 0x8221 -#define GL_IS_PER_PATCH_EXT 0x92E7 -#define GL_REFERENCED_BY_TESS_CONTROL_SHADER_EXT 0x9307 -#define GL_REFERENCED_BY_TESS_EVALUATION_SHADER_EXT 0x9308 -#define GL_TESS_CONTROL_SHADER_EXT 0x8E88 -#define GL_TESS_EVALUATION_SHADER_EXT 0x8E87 -#define GL_TESS_CONTROL_SHADER_BIT_EXT 0x00000008 -#define GL_TESS_EVALUATION_SHADER_BIT_EXT 0x00000010 -typedef void (GL_APIENTRYP PFNGLPATCHPARAMETERIEXTPROC) (GLenum pname, GLint value); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glPatchParameteriEXT (GLenum pname, GLint value); -#endif -#endif /* GL_EXT_tessellation_shader */ - -#ifndef GL_EXT_texture_border_clamp -#define GL_EXT_texture_border_clamp 1 -#define GL_TEXTURE_BORDER_COLOR_EXT 0x1004 -#define GL_CLAMP_TO_BORDER_EXT 0x812D -typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIIVEXTPROC) (GLenum target, GLenum pname, const GLint *params); -typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIUIVEXTPROC) (GLenum target, GLenum pname, const GLuint *params); -typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERIIVEXTPROC) (GLenum target, GLenum pname, GLint *params); -typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERIUIVEXTPROC) (GLenum target, GLenum pname, GLuint *params); -typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERIIVEXTPROC) (GLuint sampler, GLenum pname, const GLint *param); -typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERIUIVEXTPROC) (GLuint sampler, GLenum pname, const GLuint *param); -typedef void (GL_APIENTRYP PFNGLGETSAMPLERPARAMETERIIVEXTPROC) (GLuint sampler, GLenum pname, GLint *params); -typedef void (GL_APIENTRYP PFNGLGETSAMPLERPARAMETERIUIVEXTPROC) (GLuint sampler, GLenum pname, GLuint *params); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glTexParameterIivEXT (GLenum target, GLenum pname, const GLint *params); -GL_APICALL void GL_APIENTRY glTexParameterIuivEXT (GLenum target, GLenum pname, const GLuint *params); -GL_APICALL void GL_APIENTRY glGetTexParameterIivEXT (GLenum target, GLenum pname, GLint *params); -GL_APICALL void GL_APIENTRY glGetTexParameterIuivEXT (GLenum target, GLenum pname, GLuint *params); -GL_APICALL void GL_APIENTRY glSamplerParameterIivEXT (GLuint sampler, GLenum pname, const GLint *param); -GL_APICALL void GL_APIENTRY glSamplerParameterIuivEXT (GLuint sampler, GLenum pname, const GLuint *param); -GL_APICALL void GL_APIENTRY glGetSamplerParameterIivEXT (GLuint sampler, GLenum pname, GLint *params); -GL_APICALL void GL_APIENTRY glGetSamplerParameterIuivEXT (GLuint sampler, GLenum pname, GLuint *params); -#endif -#endif /* GL_EXT_texture_border_clamp */ - -#ifndef GL_EXT_texture_buffer -#define GL_EXT_texture_buffer 1 -#define GL_TEXTURE_BUFFER_EXT 0x8C2A -#define GL_TEXTURE_BUFFER_BINDING_EXT 0x8C2A -#define GL_MAX_TEXTURE_BUFFER_SIZE_EXT 0x8C2B -#define GL_TEXTURE_BINDING_BUFFER_EXT 0x8C2C -#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING_EXT 0x8C2D -#define GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT_EXT 0x919F -#define GL_SAMPLER_BUFFER_EXT 0x8DC2 -#define GL_INT_SAMPLER_BUFFER_EXT 0x8DD0 -#define GL_UNSIGNED_INT_SAMPLER_BUFFER_EXT 0x8DD8 -#define GL_IMAGE_BUFFER_EXT 0x9051 -#define GL_INT_IMAGE_BUFFER_EXT 0x905C -#define GL_UNSIGNED_INT_IMAGE_BUFFER_EXT 0x9067 -#define GL_TEXTURE_BUFFER_OFFSET_EXT 0x919D -#define GL_TEXTURE_BUFFER_SIZE_EXT 0x919E -typedef void (GL_APIENTRYP PFNGLTEXBUFFEREXTPROC) (GLenum target, GLenum internalformat, GLuint buffer); -typedef void (GL_APIENTRYP PFNGLTEXBUFFERRANGEEXTPROC) (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glTexBufferEXT (GLenum target, GLenum internalformat, GLuint buffer); -GL_APICALL void GL_APIENTRY glTexBufferRangeEXT (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); -#endif -#endif /* GL_EXT_texture_buffer */ - -#ifndef GL_EXT_texture_compression_dxt1 -#define GL_EXT_texture_compression_dxt1 1 -#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 -#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 -#endif /* GL_EXT_texture_compression_dxt1 */ - -#ifndef GL_EXT_texture_compression_s3tc -#define GL_EXT_texture_compression_s3tc 1 -#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 -#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 -#endif /* GL_EXT_texture_compression_s3tc */ - -#ifndef GL_EXT_texture_cube_map_array -#define GL_EXT_texture_cube_map_array 1 -#define GL_TEXTURE_CUBE_MAP_ARRAY_EXT 0x9009 -#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_EXT 0x900A -#define GL_SAMPLER_CUBE_MAP_ARRAY_EXT 0x900C -#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_EXT 0x900D -#define GL_INT_SAMPLER_CUBE_MAP_ARRAY_EXT 0x900E -#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_EXT 0x900F -#define GL_IMAGE_CUBE_MAP_ARRAY_EXT 0x9054 -#define GL_INT_IMAGE_CUBE_MAP_ARRAY_EXT 0x905F -#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY_EXT 0x906A -#endif /* GL_EXT_texture_cube_map_array */ - -#ifndef GL_EXT_texture_filter_anisotropic -#define GL_EXT_texture_filter_anisotropic 1 -#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE -#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF -#endif /* GL_EXT_texture_filter_anisotropic */ - -#ifndef GL_EXT_texture_filter_minmax -#define GL_EXT_texture_filter_minmax 1 -#endif /* GL_EXT_texture_filter_minmax */ - -#ifndef GL_EXT_texture_format_BGRA8888 -#define GL_EXT_texture_format_BGRA8888 1 -#endif /* GL_EXT_texture_format_BGRA8888 */ - -#ifndef GL_EXT_texture_norm16 -#define GL_EXT_texture_norm16 1 -#define GL_R16_EXT 0x822A -#define GL_RG16_EXT 0x822C -#define GL_RGBA16_EXT 0x805B -#define GL_RGB16_EXT 0x8054 -#define GL_RGB16_SNORM_EXT 0x8F9A -#endif /* GL_EXT_texture_norm16 */ - -#ifndef GL_EXT_texture_rg -#define GL_EXT_texture_rg 1 -#define GL_RED_EXT 0x1903 -#define GL_RG_EXT 0x8227 -#define GL_R8_EXT 0x8229 -#define GL_RG8_EXT 0x822B -#endif /* GL_EXT_texture_rg */ - -#ifndef GL_EXT_texture_sRGB_R8 -#define GL_EXT_texture_sRGB_R8 1 -#define GL_SR8_EXT 0x8FBD -#endif /* GL_EXT_texture_sRGB_R8 */ - -#ifndef GL_EXT_texture_sRGB_RG8 -#define GL_EXT_texture_sRGB_RG8 1 -#define GL_SRG8_EXT 0x8FBE -#endif /* GL_EXT_texture_sRGB_RG8 */ - -#ifndef GL_EXT_texture_sRGB_decode -#define GL_EXT_texture_sRGB_decode 1 -#define GL_TEXTURE_SRGB_DECODE_EXT 0x8A48 -#define GL_DECODE_EXT 0x8A49 -#define GL_SKIP_DECODE_EXT 0x8A4A -#endif /* GL_EXT_texture_sRGB_decode */ - -#ifndef GL_EXT_texture_storage -#define GL_EXT_texture_storage 1 -#define GL_TEXTURE_IMMUTABLE_FORMAT_EXT 0x912F -#define GL_ALPHA8_EXT 0x803C -#define GL_LUMINANCE8_EXT 0x8040 -#define GL_LUMINANCE8_ALPHA8_EXT 0x8045 -#define GL_RGBA32F_EXT 0x8814 -#define GL_RGB32F_EXT 0x8815 -#define GL_ALPHA32F_EXT 0x8816 -#define GL_LUMINANCE32F_EXT 0x8818 -#define GL_LUMINANCE_ALPHA32F_EXT 0x8819 -#define GL_ALPHA16F_EXT 0x881C -#define GL_LUMINANCE16F_EXT 0x881E -#define GL_LUMINANCE_ALPHA16F_EXT 0x881F -#define GL_R32F_EXT 0x822E -#define GL_RG32F_EXT 0x8230 -typedef void (GL_APIENTRYP PFNGLTEXSTORAGE1DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); -typedef void (GL_APIENTRYP PFNGLTEXSTORAGE2DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); -typedef void (GL_APIENTRYP PFNGLTEXSTORAGE3DEXTPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); -typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGE1DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); -typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGE2DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); -typedef void (GL_APIENTRYP PFNGLTEXTURESTORAGE3DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glTexStorage1DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); -GL_APICALL void GL_APIENTRY glTexStorage2DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); -GL_APICALL void GL_APIENTRY glTexStorage3DEXT (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); -GL_APICALL void GL_APIENTRY glTextureStorage1DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); -GL_APICALL void GL_APIENTRY glTextureStorage2DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); -GL_APICALL void GL_APIENTRY glTextureStorage3DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); -#endif -#endif /* GL_EXT_texture_storage */ - -#ifndef GL_EXT_texture_type_2_10_10_10_REV -#define GL_EXT_texture_type_2_10_10_10_REV 1 -#define GL_UNSIGNED_INT_2_10_10_10_REV_EXT 0x8368 -#endif /* GL_EXT_texture_type_2_10_10_10_REV */ - -#ifndef GL_EXT_texture_view -#define GL_EXT_texture_view 1 -#define GL_TEXTURE_VIEW_MIN_LEVEL_EXT 0x82DB -#define GL_TEXTURE_VIEW_NUM_LEVELS_EXT 0x82DC -#define GL_TEXTURE_VIEW_MIN_LAYER_EXT 0x82DD -#define GL_TEXTURE_VIEW_NUM_LAYERS_EXT 0x82DE -typedef void (GL_APIENTRYP PFNGLTEXTUREVIEWEXTPROC) (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glTextureViewEXT (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); -#endif -#endif /* GL_EXT_texture_view */ - -#ifndef GL_EXT_unpack_subimage -#define GL_EXT_unpack_subimage 1 -#define GL_UNPACK_ROW_LENGTH_EXT 0x0CF2 -#define GL_UNPACK_SKIP_ROWS_EXT 0x0CF3 -#define GL_UNPACK_SKIP_PIXELS_EXT 0x0CF4 -#endif /* GL_EXT_unpack_subimage */ - -#ifndef GL_FJ_shader_binary_GCCSO -#define GL_FJ_shader_binary_GCCSO 1 -#define GL_GCCSO_SHADER_BINARY_FJ 0x9260 -#endif /* GL_FJ_shader_binary_GCCSO */ - -#ifndef GL_IMG_framebuffer_downsample -#define GL_IMG_framebuffer_downsample 1 -#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_AND_DOWNSAMPLE_IMG 0x913C -#define GL_NUM_DOWNSAMPLE_SCALES_IMG 0x913D -#define GL_DOWNSAMPLE_SCALES_IMG 0x913E -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SCALE_IMG 0x913F -typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DDOWNSAMPLEIMGPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint xscale, GLint yscale); -typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERDOWNSAMPLEIMGPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer, GLint xscale, GLint yscale); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glFramebufferTexture2DDownsampleIMG (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint xscale, GLint yscale); -GL_APICALL void GL_APIENTRY glFramebufferTextureLayerDownsampleIMG (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer, GLint xscale, GLint yscale); -#endif -#endif /* GL_IMG_framebuffer_downsample */ - -#ifndef GL_IMG_multisampled_render_to_texture -#define GL_IMG_multisampled_render_to_texture 1 -#define GL_RENDERBUFFER_SAMPLES_IMG 0x9133 -#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_IMG 0x9134 -#define GL_MAX_SAMPLES_IMG 0x9135 -#define GL_TEXTURE_SAMPLES_IMG 0x9136 -typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEIMGPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEIMGPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleIMG (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -GL_APICALL void GL_APIENTRY glFramebufferTexture2DMultisampleIMG (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples); -#endif -#endif /* GL_IMG_multisampled_render_to_texture */ - -#ifndef GL_IMG_program_binary -#define GL_IMG_program_binary 1 -#define GL_SGX_PROGRAM_BINARY_IMG 0x9130 -#endif /* GL_IMG_program_binary */ - -#ifndef GL_IMG_read_format -#define GL_IMG_read_format 1 -#define GL_BGRA_IMG 0x80E1 -#define GL_UNSIGNED_SHORT_4_4_4_4_REV_IMG 0x8365 -#endif /* GL_IMG_read_format */ - -#ifndef GL_IMG_shader_binary -#define GL_IMG_shader_binary 1 -#define GL_SGX_BINARY_IMG 0x8C0A -#endif /* GL_IMG_shader_binary */ - -#ifndef GL_IMG_texture_compression_pvrtc -#define GL_IMG_texture_compression_pvrtc 1 -#define GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00 -#define GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG 0x8C01 -#define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02 -#define GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG 0x8C03 -#endif /* GL_IMG_texture_compression_pvrtc */ - -#ifndef GL_IMG_texture_compression_pvrtc2 -#define GL_IMG_texture_compression_pvrtc2 1 -#define GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG 0x9137 -#define GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG 0x9138 -#endif /* GL_IMG_texture_compression_pvrtc2 */ - -#ifndef GL_IMG_texture_filter_cubic -#define GL_IMG_texture_filter_cubic 1 -#define GL_CUBIC_IMG 0x9139 -#define GL_CUBIC_MIPMAP_NEAREST_IMG 0x913A -#define GL_CUBIC_MIPMAP_LINEAR_IMG 0x913B -#endif /* GL_IMG_texture_filter_cubic */ - -#ifndef GL_INTEL_framebuffer_CMAA -#define GL_INTEL_framebuffer_CMAA 1 -typedef void (GL_APIENTRYP PFNGLAPPLYFRAMEBUFFERATTACHMENTCMAAINTELPROC) (void); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glApplyFramebufferAttachmentCMAAINTEL (void); -#endif -#endif /* GL_INTEL_framebuffer_CMAA */ - -#ifndef GL_INTEL_performance_query -#define GL_INTEL_performance_query 1 -#define GL_PERFQUERY_SINGLE_CONTEXT_INTEL 0x00000000 -#define GL_PERFQUERY_GLOBAL_CONTEXT_INTEL 0x00000001 -#define GL_PERFQUERY_WAIT_INTEL 0x83FB -#define GL_PERFQUERY_FLUSH_INTEL 0x83FA -#define GL_PERFQUERY_DONOT_FLUSH_INTEL 0x83F9 -#define GL_PERFQUERY_COUNTER_EVENT_INTEL 0x94F0 -#define GL_PERFQUERY_COUNTER_DURATION_NORM_INTEL 0x94F1 -#define GL_PERFQUERY_COUNTER_DURATION_RAW_INTEL 0x94F2 -#define GL_PERFQUERY_COUNTER_THROUGHPUT_INTEL 0x94F3 -#define GL_PERFQUERY_COUNTER_RAW_INTEL 0x94F4 -#define GL_PERFQUERY_COUNTER_TIMESTAMP_INTEL 0x94F5 -#define GL_PERFQUERY_COUNTER_DATA_UINT32_INTEL 0x94F8 -#define GL_PERFQUERY_COUNTER_DATA_UINT64_INTEL 0x94F9 -#define GL_PERFQUERY_COUNTER_DATA_FLOAT_INTEL 0x94FA -#define GL_PERFQUERY_COUNTER_DATA_DOUBLE_INTEL 0x94FB -#define GL_PERFQUERY_COUNTER_DATA_BOOL32_INTEL 0x94FC -#define GL_PERFQUERY_QUERY_NAME_LENGTH_MAX_INTEL 0x94FD -#define GL_PERFQUERY_COUNTER_NAME_LENGTH_MAX_INTEL 0x94FE -#define GL_PERFQUERY_COUNTER_DESC_LENGTH_MAX_INTEL 0x94FF -#define GL_PERFQUERY_GPA_EXTENDED_COUNTERS_INTEL 0x9500 -typedef void (GL_APIENTRYP PFNGLBEGINPERFQUERYINTELPROC) (GLuint queryHandle); -typedef void (GL_APIENTRYP PFNGLCREATEPERFQUERYINTELPROC) (GLuint queryId, GLuint *queryHandle); -typedef void (GL_APIENTRYP PFNGLDELETEPERFQUERYINTELPROC) (GLuint queryHandle); -typedef void (GL_APIENTRYP PFNGLENDPERFQUERYINTELPROC) (GLuint queryHandle); -typedef void (GL_APIENTRYP PFNGLGETFIRSTPERFQUERYIDINTELPROC) (GLuint *queryId); -typedef void (GL_APIENTRYP PFNGLGETNEXTPERFQUERYIDINTELPROC) (GLuint queryId, GLuint *nextQueryId); -typedef void (GL_APIENTRYP PFNGLGETPERFCOUNTERINFOINTELPROC) (GLuint queryId, GLuint counterId, GLuint counterNameLength, GLchar *counterName, GLuint counterDescLength, GLchar *counterDesc, GLuint *counterOffset, GLuint *counterDataSize, GLuint *counterTypeEnum, GLuint *counterDataTypeEnum, GLuint64 *rawCounterMaxValue); -typedef void (GL_APIENTRYP PFNGLGETPERFQUERYDATAINTELPROC) (GLuint queryHandle, GLuint flags, GLsizei dataSize, GLvoid *data, GLuint *bytesWritten); -typedef void (GL_APIENTRYP PFNGLGETPERFQUERYIDBYNAMEINTELPROC) (GLchar *queryName, GLuint *queryId); -typedef void (GL_APIENTRYP PFNGLGETPERFQUERYINFOINTELPROC) (GLuint queryId, GLuint queryNameLength, GLchar *queryName, GLuint *dataSize, GLuint *noCounters, GLuint *noInstances, GLuint *capsMask); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glBeginPerfQueryINTEL (GLuint queryHandle); -GL_APICALL void GL_APIENTRY glCreatePerfQueryINTEL (GLuint queryId, GLuint *queryHandle); -GL_APICALL void GL_APIENTRY glDeletePerfQueryINTEL (GLuint queryHandle); -GL_APICALL void GL_APIENTRY glEndPerfQueryINTEL (GLuint queryHandle); -GL_APICALL void GL_APIENTRY glGetFirstPerfQueryIdINTEL (GLuint *queryId); -GL_APICALL void GL_APIENTRY glGetNextPerfQueryIdINTEL (GLuint queryId, GLuint *nextQueryId); -GL_APICALL void GL_APIENTRY glGetPerfCounterInfoINTEL (GLuint queryId, GLuint counterId, GLuint counterNameLength, GLchar *counterName, GLuint counterDescLength, GLchar *counterDesc, GLuint *counterOffset, GLuint *counterDataSize, GLuint *counterTypeEnum, GLuint *counterDataTypeEnum, GLuint64 *rawCounterMaxValue); -GL_APICALL void GL_APIENTRY glGetPerfQueryDataINTEL (GLuint queryHandle, GLuint flags, GLsizei dataSize, GLvoid *data, GLuint *bytesWritten); -GL_APICALL void GL_APIENTRY glGetPerfQueryIdByNameINTEL (GLchar *queryName, GLuint *queryId); -GL_APICALL void GL_APIENTRY glGetPerfQueryInfoINTEL (GLuint queryId, GLuint queryNameLength, GLchar *queryName, GLuint *dataSize, GLuint *noCounters, GLuint *noInstances, GLuint *capsMask); -#endif -#endif /* GL_INTEL_performance_query */ - -#ifndef GL_NV_bindless_texture -#define GL_NV_bindless_texture 1 -typedef GLuint64 (GL_APIENTRYP PFNGLGETTEXTUREHANDLENVPROC) (GLuint texture); -typedef GLuint64 (GL_APIENTRYP PFNGLGETTEXTURESAMPLERHANDLENVPROC) (GLuint texture, GLuint sampler); -typedef void (GL_APIENTRYP PFNGLMAKETEXTUREHANDLERESIDENTNVPROC) (GLuint64 handle); -typedef void (GL_APIENTRYP PFNGLMAKETEXTUREHANDLENONRESIDENTNVPROC) (GLuint64 handle); -typedef GLuint64 (GL_APIENTRYP PFNGLGETIMAGEHANDLENVPROC) (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); -typedef void (GL_APIENTRYP PFNGLMAKEIMAGEHANDLERESIDENTNVPROC) (GLuint64 handle, GLenum access); -typedef void (GL_APIENTRYP PFNGLMAKEIMAGEHANDLENONRESIDENTNVPROC) (GLuint64 handle); -typedef void (GL_APIENTRYP PFNGLUNIFORMHANDLEUI64NVPROC) (GLint location, GLuint64 value); -typedef void (GL_APIENTRYP PFNGLUNIFORMHANDLEUI64VNVPROC) (GLint location, GLsizei count, const GLuint64 *value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64NVPROC) (GLuint program, GLint location, GLuint64 value); -typedef void (GL_APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *values); -typedef GLboolean (GL_APIENTRYP PFNGLISTEXTUREHANDLERESIDENTNVPROC) (GLuint64 handle); -typedef GLboolean (GL_APIENTRYP PFNGLISIMAGEHANDLERESIDENTNVPROC) (GLuint64 handle); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL GLuint64 GL_APIENTRY glGetTextureHandleNV (GLuint texture); -GL_APICALL GLuint64 GL_APIENTRY glGetTextureSamplerHandleNV (GLuint texture, GLuint sampler); -GL_APICALL void GL_APIENTRY glMakeTextureHandleResidentNV (GLuint64 handle); -GL_APICALL void GL_APIENTRY glMakeTextureHandleNonResidentNV (GLuint64 handle); -GL_APICALL GLuint64 GL_APIENTRY glGetImageHandleNV (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); -GL_APICALL void GL_APIENTRY glMakeImageHandleResidentNV (GLuint64 handle, GLenum access); -GL_APICALL void GL_APIENTRY glMakeImageHandleNonResidentNV (GLuint64 handle); -GL_APICALL void GL_APIENTRY glUniformHandleui64NV (GLint location, GLuint64 value); -GL_APICALL void GL_APIENTRY glUniformHandleui64vNV (GLint location, GLsizei count, const GLuint64 *value); -GL_APICALL void GL_APIENTRY glProgramUniformHandleui64NV (GLuint program, GLint location, GLuint64 value); -GL_APICALL void GL_APIENTRY glProgramUniformHandleui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64 *values); -GL_APICALL GLboolean GL_APIENTRY glIsTextureHandleResidentNV (GLuint64 handle); -GL_APICALL GLboolean GL_APIENTRY glIsImageHandleResidentNV (GLuint64 handle); -#endif -#endif /* GL_NV_bindless_texture */ - -#ifndef GL_NV_blend_equation_advanced -#define GL_NV_blend_equation_advanced 1 -#define GL_BLEND_OVERLAP_NV 0x9281 -#define GL_BLEND_PREMULTIPLIED_SRC_NV 0x9280 -#define GL_BLUE_NV 0x1905 -#define GL_COLORBURN_NV 0x929A -#define GL_COLORDODGE_NV 0x9299 -#define GL_CONJOINT_NV 0x9284 -#define GL_CONTRAST_NV 0x92A1 -#define GL_DARKEN_NV 0x9297 -#define GL_DIFFERENCE_NV 0x929E -#define GL_DISJOINT_NV 0x9283 -#define GL_DST_ATOP_NV 0x928F -#define GL_DST_IN_NV 0x928B -#define GL_DST_NV 0x9287 -#define GL_DST_OUT_NV 0x928D -#define GL_DST_OVER_NV 0x9289 -#define GL_EXCLUSION_NV 0x92A0 -#define GL_GREEN_NV 0x1904 -#define GL_HARDLIGHT_NV 0x929B -#define GL_HARDMIX_NV 0x92A9 -#define GL_HSL_COLOR_NV 0x92AF -#define GL_HSL_HUE_NV 0x92AD -#define GL_HSL_LUMINOSITY_NV 0x92B0 -#define GL_HSL_SATURATION_NV 0x92AE -#define GL_INVERT_OVG_NV 0x92B4 -#define GL_INVERT_RGB_NV 0x92A3 -#define GL_LIGHTEN_NV 0x9298 -#define GL_LINEARBURN_NV 0x92A5 -#define GL_LINEARDODGE_NV 0x92A4 -#define GL_LINEARLIGHT_NV 0x92A7 -#define GL_MINUS_CLAMPED_NV 0x92B3 -#define GL_MINUS_NV 0x929F -#define GL_MULTIPLY_NV 0x9294 -#define GL_OVERLAY_NV 0x9296 -#define GL_PINLIGHT_NV 0x92A8 -#define GL_PLUS_CLAMPED_ALPHA_NV 0x92B2 -#define GL_PLUS_CLAMPED_NV 0x92B1 -#define GL_PLUS_DARKER_NV 0x9292 -#define GL_PLUS_NV 0x9291 -#define GL_RED_NV 0x1903 -#define GL_SCREEN_NV 0x9295 -#define GL_SOFTLIGHT_NV 0x929C -#define GL_SRC_ATOP_NV 0x928E -#define GL_SRC_IN_NV 0x928A -#define GL_SRC_NV 0x9286 -#define GL_SRC_OUT_NV 0x928C -#define GL_SRC_OVER_NV 0x9288 -#define GL_UNCORRELATED_NV 0x9282 -#define GL_VIVIDLIGHT_NV 0x92A6 -#define GL_XOR_NV 0x1506 -typedef void (GL_APIENTRYP PFNGLBLENDPARAMETERINVPROC) (GLenum pname, GLint value); -typedef void (GL_APIENTRYP PFNGLBLENDBARRIERNVPROC) (void); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glBlendParameteriNV (GLenum pname, GLint value); -GL_APICALL void GL_APIENTRY glBlendBarrierNV (void); -#endif -#endif /* GL_NV_blend_equation_advanced */ - -#ifndef GL_NV_blend_equation_advanced_coherent -#define GL_NV_blend_equation_advanced_coherent 1 -#define GL_BLEND_ADVANCED_COHERENT_NV 0x9285 -#endif /* GL_NV_blend_equation_advanced_coherent */ - -#ifndef GL_NV_conditional_render -#define GL_NV_conditional_render 1 -#define GL_QUERY_WAIT_NV 0x8E13 -#define GL_QUERY_NO_WAIT_NV 0x8E14 -#define GL_QUERY_BY_REGION_WAIT_NV 0x8E15 -#define GL_QUERY_BY_REGION_NO_WAIT_NV 0x8E16 -typedef void (GL_APIENTRYP PFNGLBEGINCONDITIONALRENDERNVPROC) (GLuint id, GLenum mode); -typedef void (GL_APIENTRYP PFNGLENDCONDITIONALRENDERNVPROC) (void); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glBeginConditionalRenderNV (GLuint id, GLenum mode); -GL_APICALL void GL_APIENTRY glEndConditionalRenderNV (void); -#endif -#endif /* GL_NV_conditional_render */ - -#ifndef GL_NV_conservative_raster -#define GL_NV_conservative_raster 1 -#define GL_CONSERVATIVE_RASTERIZATION_NV 0x9346 -#define GL_SUBPIXEL_PRECISION_BIAS_X_BITS_NV 0x9347 -#define GL_SUBPIXEL_PRECISION_BIAS_Y_BITS_NV 0x9348 -#define GL_MAX_SUBPIXEL_PRECISION_BIAS_BITS_NV 0x9349 -typedef void (GL_APIENTRYP PFNGLSUBPIXELPRECISIONBIASNVPROC) (GLuint xbits, GLuint ybits); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glSubpixelPrecisionBiasNV (GLuint xbits, GLuint ybits); -#endif -#endif /* GL_NV_conservative_raster */ - -#ifndef GL_NV_copy_buffer -#define GL_NV_copy_buffer 1 -#define GL_COPY_READ_BUFFER_NV 0x8F36 -#define GL_COPY_WRITE_BUFFER_NV 0x8F37 -typedef void (GL_APIENTRYP PFNGLCOPYBUFFERSUBDATANVPROC) (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glCopyBufferSubDataNV (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); -#endif -#endif /* GL_NV_copy_buffer */ - -#ifndef GL_NV_coverage_sample -#define GL_NV_coverage_sample 1 -#define GL_COVERAGE_COMPONENT_NV 0x8ED0 -#define GL_COVERAGE_COMPONENT4_NV 0x8ED1 -#define GL_COVERAGE_ATTACHMENT_NV 0x8ED2 -#define GL_COVERAGE_BUFFERS_NV 0x8ED3 -#define GL_COVERAGE_SAMPLES_NV 0x8ED4 -#define GL_COVERAGE_ALL_FRAGMENTS_NV 0x8ED5 -#define GL_COVERAGE_EDGE_FRAGMENTS_NV 0x8ED6 -#define GL_COVERAGE_AUTOMATIC_NV 0x8ED7 -#define GL_COVERAGE_BUFFER_BIT_NV 0x00008000 -typedef void (GL_APIENTRYP PFNGLCOVERAGEMASKNVPROC) (GLboolean mask); -typedef void (GL_APIENTRYP PFNGLCOVERAGEOPERATIONNVPROC) (GLenum operation); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glCoverageMaskNV (GLboolean mask); -GL_APICALL void GL_APIENTRY glCoverageOperationNV (GLenum operation); -#endif -#endif /* GL_NV_coverage_sample */ - -#ifndef GL_NV_depth_nonlinear -#define GL_NV_depth_nonlinear 1 -#define GL_DEPTH_COMPONENT16_NONLINEAR_NV 0x8E2C -#endif /* GL_NV_depth_nonlinear */ - -#ifndef GL_NV_draw_buffers -#define GL_NV_draw_buffers 1 -#define GL_MAX_DRAW_BUFFERS_NV 0x8824 -#define GL_DRAW_BUFFER0_NV 0x8825 -#define GL_DRAW_BUFFER1_NV 0x8826 -#define GL_DRAW_BUFFER2_NV 0x8827 -#define GL_DRAW_BUFFER3_NV 0x8828 -#define GL_DRAW_BUFFER4_NV 0x8829 -#define GL_DRAW_BUFFER5_NV 0x882A -#define GL_DRAW_BUFFER6_NV 0x882B -#define GL_DRAW_BUFFER7_NV 0x882C -#define GL_DRAW_BUFFER8_NV 0x882D -#define GL_DRAW_BUFFER9_NV 0x882E -#define GL_DRAW_BUFFER10_NV 0x882F -#define GL_DRAW_BUFFER11_NV 0x8830 -#define GL_DRAW_BUFFER12_NV 0x8831 -#define GL_DRAW_BUFFER13_NV 0x8832 -#define GL_DRAW_BUFFER14_NV 0x8833 -#define GL_DRAW_BUFFER15_NV 0x8834 -#define GL_COLOR_ATTACHMENT0_NV 0x8CE0 -#define GL_COLOR_ATTACHMENT1_NV 0x8CE1 -#define GL_COLOR_ATTACHMENT2_NV 0x8CE2 -#define GL_COLOR_ATTACHMENT3_NV 0x8CE3 -#define GL_COLOR_ATTACHMENT4_NV 0x8CE4 -#define GL_COLOR_ATTACHMENT5_NV 0x8CE5 -#define GL_COLOR_ATTACHMENT6_NV 0x8CE6 -#define GL_COLOR_ATTACHMENT7_NV 0x8CE7 -#define GL_COLOR_ATTACHMENT8_NV 0x8CE8 -#define GL_COLOR_ATTACHMENT9_NV 0x8CE9 -#define GL_COLOR_ATTACHMENT10_NV 0x8CEA -#define GL_COLOR_ATTACHMENT11_NV 0x8CEB -#define GL_COLOR_ATTACHMENT12_NV 0x8CEC -#define GL_COLOR_ATTACHMENT13_NV 0x8CED -#define GL_COLOR_ATTACHMENT14_NV 0x8CEE -#define GL_COLOR_ATTACHMENT15_NV 0x8CEF -typedef void (GL_APIENTRYP PFNGLDRAWBUFFERSNVPROC) (GLsizei n, const GLenum *bufs); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glDrawBuffersNV (GLsizei n, const GLenum *bufs); -#endif -#endif /* GL_NV_draw_buffers */ - -#ifndef GL_NV_draw_instanced -#define GL_NV_draw_instanced 1 -typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINSTANCEDNVPROC) (GLenum mode, GLint first, GLsizei count, GLsizei primcount); -typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDNVPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glDrawArraysInstancedNV (GLenum mode, GLint first, GLsizei count, GLsizei primcount); -GL_APICALL void GL_APIENTRY glDrawElementsInstancedNV (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); -#endif -#endif /* GL_NV_draw_instanced */ - -#ifndef GL_NV_explicit_attrib_location -#define GL_NV_explicit_attrib_location 1 -#endif /* GL_NV_explicit_attrib_location */ - -#ifndef GL_NV_fbo_color_attachments -#define GL_NV_fbo_color_attachments 1 -#define GL_MAX_COLOR_ATTACHMENTS_NV 0x8CDF -#endif /* GL_NV_fbo_color_attachments */ - -#ifndef GL_NV_fence -#define GL_NV_fence 1 -#define GL_ALL_COMPLETED_NV 0x84F2 -#define GL_FENCE_STATUS_NV 0x84F3 -#define GL_FENCE_CONDITION_NV 0x84F4 -typedef void (GL_APIENTRYP PFNGLDELETEFENCESNVPROC) (GLsizei n, const GLuint *fences); -typedef void (GL_APIENTRYP PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fences); -typedef GLboolean (GL_APIENTRYP PFNGLISFENCENVPROC) (GLuint fence); -typedef GLboolean (GL_APIENTRYP PFNGLTESTFENCENVPROC) (GLuint fence); -typedef void (GL_APIENTRYP PFNGLGETFENCEIVNVPROC) (GLuint fence, GLenum pname, GLint *params); -typedef void (GL_APIENTRYP PFNGLFINISHFENCENVPROC) (GLuint fence); -typedef void (GL_APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glDeleteFencesNV (GLsizei n, const GLuint *fences); -GL_APICALL void GL_APIENTRY glGenFencesNV (GLsizei n, GLuint *fences); -GL_APICALL GLboolean GL_APIENTRY glIsFenceNV (GLuint fence); -GL_APICALL GLboolean GL_APIENTRY glTestFenceNV (GLuint fence); -GL_APICALL void GL_APIENTRY glGetFenceivNV (GLuint fence, GLenum pname, GLint *params); -GL_APICALL void GL_APIENTRY glFinishFenceNV (GLuint fence); -GL_APICALL void GL_APIENTRY glSetFenceNV (GLuint fence, GLenum condition); -#endif -#endif /* GL_NV_fence */ - -#ifndef GL_NV_fill_rectangle -#define GL_NV_fill_rectangle 1 -#define GL_FILL_RECTANGLE_NV 0x933C -#endif /* GL_NV_fill_rectangle */ - -#ifndef GL_NV_fragment_coverage_to_color -#define GL_NV_fragment_coverage_to_color 1 -#define GL_FRAGMENT_COVERAGE_TO_COLOR_NV 0x92DD -#define GL_FRAGMENT_COVERAGE_COLOR_NV 0x92DE -typedef void (GL_APIENTRYP PFNGLFRAGMENTCOVERAGECOLORNVPROC) (GLuint color); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glFragmentCoverageColorNV (GLuint color); -#endif -#endif /* GL_NV_fragment_coverage_to_color */ - -#ifndef GL_NV_fragment_shader_interlock -#define GL_NV_fragment_shader_interlock 1 -#endif /* GL_NV_fragment_shader_interlock */ - -#ifndef GL_NV_framebuffer_blit -#define GL_NV_framebuffer_blit 1 -#define GL_READ_FRAMEBUFFER_NV 0x8CA8 -#define GL_DRAW_FRAMEBUFFER_NV 0x8CA9 -#define GL_DRAW_FRAMEBUFFER_BINDING_NV 0x8CA6 -#define GL_READ_FRAMEBUFFER_BINDING_NV 0x8CAA -typedef void (GL_APIENTRYP PFNGLBLITFRAMEBUFFERNVPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glBlitFramebufferNV (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); -#endif -#endif /* GL_NV_framebuffer_blit */ - -#ifndef GL_NV_framebuffer_mixed_samples -#define GL_NV_framebuffer_mixed_samples 1 -#define GL_COVERAGE_MODULATION_TABLE_NV 0x9331 -#define GL_COLOR_SAMPLES_NV 0x8E20 -#define GL_DEPTH_SAMPLES_NV 0x932D -#define GL_STENCIL_SAMPLES_NV 0x932E -#define GL_MIXED_DEPTH_SAMPLES_SUPPORTED_NV 0x932F -#define GL_MIXED_STENCIL_SAMPLES_SUPPORTED_NV 0x9330 -#define GL_COVERAGE_MODULATION_NV 0x9332 -#define GL_COVERAGE_MODULATION_TABLE_SIZE_NV 0x9333 -typedef void (GL_APIENTRYP PFNGLCOVERAGEMODULATIONTABLENVPROC) (GLsizei n, const GLfloat *v); -typedef void (GL_APIENTRYP PFNGLGETCOVERAGEMODULATIONTABLENVPROC) (GLsizei bufsize, GLfloat *v); -typedef void (GL_APIENTRYP PFNGLCOVERAGEMODULATIONNVPROC) (GLenum components); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glCoverageModulationTableNV (GLsizei n, const GLfloat *v); -GL_APICALL void GL_APIENTRY glGetCoverageModulationTableNV (GLsizei bufsize, GLfloat *v); -GL_APICALL void GL_APIENTRY glCoverageModulationNV (GLenum components); -#endif -#endif /* GL_NV_framebuffer_mixed_samples */ - -#ifndef GL_NV_framebuffer_multisample -#define GL_NV_framebuffer_multisample 1 -#define GL_RENDERBUFFER_SAMPLES_NV 0x8CAB -#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_NV 0x8D56 -#define GL_MAX_SAMPLES_NV 0x8D57 -typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLENVPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisampleNV (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -#endif -#endif /* GL_NV_framebuffer_multisample */ - -#ifndef GL_NV_generate_mipmap_sRGB -#define GL_NV_generate_mipmap_sRGB 1 -#endif /* GL_NV_generate_mipmap_sRGB */ - -#ifndef GL_NV_geometry_shader_passthrough -#define GL_NV_geometry_shader_passthrough 1 -#endif /* GL_NV_geometry_shader_passthrough */ - -#ifndef GL_NV_image_formats -#define GL_NV_image_formats 1 -#endif /* GL_NV_image_formats */ - -#ifndef GL_NV_instanced_arrays -#define GL_NV_instanced_arrays 1 -#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR_NV 0x88FE -typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBDIVISORNVPROC) (GLuint index, GLuint divisor); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glVertexAttribDivisorNV (GLuint index, GLuint divisor); -#endif -#endif /* GL_NV_instanced_arrays */ - -#ifndef GL_NV_internalformat_sample_query -#define GL_NV_internalformat_sample_query 1 -#define GL_TEXTURE_2D_MULTISAMPLE 0x9100 -#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102 -#define GL_MULTISAMPLES_NV 0x9371 -#define GL_SUPERSAMPLE_SCALE_X_NV 0x9372 -#define GL_SUPERSAMPLE_SCALE_Y_NV 0x9373 -#define GL_CONFORMANT_NV 0x9374 -typedef void (GL_APIENTRYP PFNGLGETINTERNALFORMATSAMPLEIVNVPROC) (GLenum target, GLenum internalformat, GLsizei samples, GLenum pname, GLsizei bufSize, GLint *params); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glGetInternalformatSampleivNV (GLenum target, GLenum internalformat, GLsizei samples, GLenum pname, GLsizei bufSize, GLint *params); -#endif -#endif /* GL_NV_internalformat_sample_query */ - -#ifndef GL_NV_non_square_matrices -#define GL_NV_non_square_matrices 1 -#define GL_FLOAT_MAT2x3_NV 0x8B65 -#define GL_FLOAT_MAT2x4_NV 0x8B66 -#define GL_FLOAT_MAT3x2_NV 0x8B67 -#define GL_FLOAT_MAT3x4_NV 0x8B68 -#define GL_FLOAT_MAT4x2_NV 0x8B69 -#define GL_FLOAT_MAT4x3_NV 0x8B6A -typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX2X3FVNVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX3X2FVNVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX2X4FVNVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX4X2FVNVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX3X4FVNVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX4X3FVNVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glUniformMatrix2x3fvNV (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glUniformMatrix3x2fvNV (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glUniformMatrix2x4fvNV (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glUniformMatrix4x2fvNV (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glUniformMatrix3x4fvNV (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glUniformMatrix4x3fvNV (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -#endif -#endif /* GL_NV_non_square_matrices */ - -#ifndef GL_NV_path_rendering -#define GL_NV_path_rendering 1 -#define GL_PATH_FORMAT_SVG_NV 0x9070 -#define GL_PATH_FORMAT_PS_NV 0x9071 -#define GL_STANDARD_FONT_NAME_NV 0x9072 -#define GL_SYSTEM_FONT_NAME_NV 0x9073 -#define GL_FILE_NAME_NV 0x9074 -#define GL_PATH_STROKE_WIDTH_NV 0x9075 -#define GL_PATH_END_CAPS_NV 0x9076 -#define GL_PATH_INITIAL_END_CAP_NV 0x9077 -#define GL_PATH_TERMINAL_END_CAP_NV 0x9078 -#define GL_PATH_JOIN_STYLE_NV 0x9079 -#define GL_PATH_MITER_LIMIT_NV 0x907A -#define GL_PATH_DASH_CAPS_NV 0x907B -#define GL_PATH_INITIAL_DASH_CAP_NV 0x907C -#define GL_PATH_TERMINAL_DASH_CAP_NV 0x907D -#define GL_PATH_DASH_OFFSET_NV 0x907E -#define GL_PATH_CLIENT_LENGTH_NV 0x907F -#define GL_PATH_FILL_MODE_NV 0x9080 -#define GL_PATH_FILL_MASK_NV 0x9081 -#define GL_PATH_FILL_COVER_MODE_NV 0x9082 -#define GL_PATH_STROKE_COVER_MODE_NV 0x9083 -#define GL_PATH_STROKE_MASK_NV 0x9084 -#define GL_COUNT_UP_NV 0x9088 -#define GL_COUNT_DOWN_NV 0x9089 -#define GL_PATH_OBJECT_BOUNDING_BOX_NV 0x908A -#define GL_CONVEX_HULL_NV 0x908B -#define GL_BOUNDING_BOX_NV 0x908D -#define GL_TRANSLATE_X_NV 0x908E -#define GL_TRANSLATE_Y_NV 0x908F -#define GL_TRANSLATE_2D_NV 0x9090 -#define GL_TRANSLATE_3D_NV 0x9091 -#define GL_AFFINE_2D_NV 0x9092 -#define GL_AFFINE_3D_NV 0x9094 -#define GL_TRANSPOSE_AFFINE_2D_NV 0x9096 -#define GL_TRANSPOSE_AFFINE_3D_NV 0x9098 -#define GL_UTF8_NV 0x909A -#define GL_UTF16_NV 0x909B -#define GL_BOUNDING_BOX_OF_BOUNDING_BOXES_NV 0x909C -#define GL_PATH_COMMAND_COUNT_NV 0x909D -#define GL_PATH_COORD_COUNT_NV 0x909E -#define GL_PATH_DASH_ARRAY_COUNT_NV 0x909F -#define GL_PATH_COMPUTED_LENGTH_NV 0x90A0 -#define GL_PATH_FILL_BOUNDING_BOX_NV 0x90A1 -#define GL_PATH_STROKE_BOUNDING_BOX_NV 0x90A2 -#define GL_SQUARE_NV 0x90A3 -#define GL_ROUND_NV 0x90A4 -#define GL_TRIANGULAR_NV 0x90A5 -#define GL_BEVEL_NV 0x90A6 -#define GL_MITER_REVERT_NV 0x90A7 -#define GL_MITER_TRUNCATE_NV 0x90A8 -#define GL_SKIP_MISSING_GLYPH_NV 0x90A9 -#define GL_USE_MISSING_GLYPH_NV 0x90AA -#define GL_PATH_ERROR_POSITION_NV 0x90AB -#define GL_ACCUM_ADJACENT_PAIRS_NV 0x90AD -#define GL_ADJACENT_PAIRS_NV 0x90AE -#define GL_FIRST_TO_REST_NV 0x90AF -#define GL_PATH_GEN_MODE_NV 0x90B0 -#define GL_PATH_GEN_COEFF_NV 0x90B1 -#define GL_PATH_GEN_COMPONENTS_NV 0x90B3 -#define GL_PATH_STENCIL_FUNC_NV 0x90B7 -#define GL_PATH_STENCIL_REF_NV 0x90B8 -#define GL_PATH_STENCIL_VALUE_MASK_NV 0x90B9 -#define GL_PATH_STENCIL_DEPTH_OFFSET_FACTOR_NV 0x90BD -#define GL_PATH_STENCIL_DEPTH_OFFSET_UNITS_NV 0x90BE -#define GL_PATH_COVER_DEPTH_FUNC_NV 0x90BF -#define GL_PATH_DASH_OFFSET_RESET_NV 0x90B4 -#define GL_MOVE_TO_RESETS_NV 0x90B5 -#define GL_MOVE_TO_CONTINUES_NV 0x90B6 -#define GL_CLOSE_PATH_NV 0x00 -#define GL_MOVE_TO_NV 0x02 -#define GL_RELATIVE_MOVE_TO_NV 0x03 -#define GL_LINE_TO_NV 0x04 -#define GL_RELATIVE_LINE_TO_NV 0x05 -#define GL_HORIZONTAL_LINE_TO_NV 0x06 -#define GL_RELATIVE_HORIZONTAL_LINE_TO_NV 0x07 -#define GL_VERTICAL_LINE_TO_NV 0x08 -#define GL_RELATIVE_VERTICAL_LINE_TO_NV 0x09 -#define GL_QUADRATIC_CURVE_TO_NV 0x0A -#define GL_RELATIVE_QUADRATIC_CURVE_TO_NV 0x0B -#define GL_CUBIC_CURVE_TO_NV 0x0C -#define GL_RELATIVE_CUBIC_CURVE_TO_NV 0x0D -#define GL_SMOOTH_QUADRATIC_CURVE_TO_NV 0x0E -#define GL_RELATIVE_SMOOTH_QUADRATIC_CURVE_TO_NV 0x0F -#define GL_SMOOTH_CUBIC_CURVE_TO_NV 0x10 -#define GL_RELATIVE_SMOOTH_CUBIC_CURVE_TO_NV 0x11 -#define GL_SMALL_CCW_ARC_TO_NV 0x12 -#define GL_RELATIVE_SMALL_CCW_ARC_TO_NV 0x13 -#define GL_SMALL_CW_ARC_TO_NV 0x14 -#define GL_RELATIVE_SMALL_CW_ARC_TO_NV 0x15 -#define GL_LARGE_CCW_ARC_TO_NV 0x16 -#define GL_RELATIVE_LARGE_CCW_ARC_TO_NV 0x17 -#define GL_LARGE_CW_ARC_TO_NV 0x18 -#define GL_RELATIVE_LARGE_CW_ARC_TO_NV 0x19 -#define GL_RESTART_PATH_NV 0xF0 -#define GL_DUP_FIRST_CUBIC_CURVE_TO_NV 0xF2 -#define GL_DUP_LAST_CUBIC_CURVE_TO_NV 0xF4 -#define GL_RECT_NV 0xF6 -#define GL_CIRCULAR_CCW_ARC_TO_NV 0xF8 -#define GL_CIRCULAR_CW_ARC_TO_NV 0xFA -#define GL_CIRCULAR_TANGENT_ARC_TO_NV 0xFC -#define GL_ARC_TO_NV 0xFE -#define GL_RELATIVE_ARC_TO_NV 0xFF -#define GL_BOLD_BIT_NV 0x01 -#define GL_ITALIC_BIT_NV 0x02 -#define GL_GLYPH_WIDTH_BIT_NV 0x01 -#define GL_GLYPH_HEIGHT_BIT_NV 0x02 -#define GL_GLYPH_HORIZONTAL_BEARING_X_BIT_NV 0x04 -#define GL_GLYPH_HORIZONTAL_BEARING_Y_BIT_NV 0x08 -#define GL_GLYPH_HORIZONTAL_BEARING_ADVANCE_BIT_NV 0x10 -#define GL_GLYPH_VERTICAL_BEARING_X_BIT_NV 0x20 -#define GL_GLYPH_VERTICAL_BEARING_Y_BIT_NV 0x40 -#define GL_GLYPH_VERTICAL_BEARING_ADVANCE_BIT_NV 0x80 -#define GL_GLYPH_HAS_KERNING_BIT_NV 0x100 -#define GL_FONT_X_MIN_BOUNDS_BIT_NV 0x00010000 -#define GL_FONT_Y_MIN_BOUNDS_BIT_NV 0x00020000 -#define GL_FONT_X_MAX_BOUNDS_BIT_NV 0x00040000 -#define GL_FONT_Y_MAX_BOUNDS_BIT_NV 0x00080000 -#define GL_FONT_UNITS_PER_EM_BIT_NV 0x00100000 -#define GL_FONT_ASCENDER_BIT_NV 0x00200000 -#define GL_FONT_DESCENDER_BIT_NV 0x00400000 -#define GL_FONT_HEIGHT_BIT_NV 0x00800000 -#define GL_FONT_MAX_ADVANCE_WIDTH_BIT_NV 0x01000000 -#define GL_FONT_MAX_ADVANCE_HEIGHT_BIT_NV 0x02000000 -#define GL_FONT_UNDERLINE_POSITION_BIT_NV 0x04000000 -#define GL_FONT_UNDERLINE_THICKNESS_BIT_NV 0x08000000 -#define GL_FONT_HAS_KERNING_BIT_NV 0x10000000 -#define GL_ROUNDED_RECT_NV 0xE8 -#define GL_RELATIVE_ROUNDED_RECT_NV 0xE9 -#define GL_ROUNDED_RECT2_NV 0xEA -#define GL_RELATIVE_ROUNDED_RECT2_NV 0xEB -#define GL_ROUNDED_RECT4_NV 0xEC -#define GL_RELATIVE_ROUNDED_RECT4_NV 0xED -#define GL_ROUNDED_RECT8_NV 0xEE -#define GL_RELATIVE_ROUNDED_RECT8_NV 0xEF -#define GL_RELATIVE_RECT_NV 0xF7 -#define GL_FONT_GLYPHS_AVAILABLE_NV 0x9368 -#define GL_FONT_TARGET_UNAVAILABLE_NV 0x9369 -#define GL_FONT_UNAVAILABLE_NV 0x936A -#define GL_FONT_UNINTELLIGIBLE_NV 0x936B -#define GL_CONIC_CURVE_TO_NV 0x1A -#define GL_RELATIVE_CONIC_CURVE_TO_NV 0x1B -#define GL_FONT_NUM_GLYPH_INDICES_BIT_NV 0x20000000 -#define GL_STANDARD_FONT_FORMAT_NV 0x936C -#define GL_PATH_PROJECTION_NV 0x1701 -#define GL_PATH_MODELVIEW_NV 0x1700 -#define GL_PATH_MODELVIEW_STACK_DEPTH_NV 0x0BA3 -#define GL_PATH_MODELVIEW_MATRIX_NV 0x0BA6 -#define GL_PATH_MAX_MODELVIEW_STACK_DEPTH_NV 0x0D36 -#define GL_PATH_TRANSPOSE_MODELVIEW_MATRIX_NV 0x84E3 -#define GL_PATH_PROJECTION_STACK_DEPTH_NV 0x0BA4 -#define GL_PATH_PROJECTION_MATRIX_NV 0x0BA7 -#define GL_PATH_MAX_PROJECTION_STACK_DEPTH_NV 0x0D38 -#define GL_PATH_TRANSPOSE_PROJECTION_MATRIX_NV 0x84E4 -#define GL_FRAGMENT_INPUT_NV 0x936D -typedef GLuint (GL_APIENTRYP PFNGLGENPATHSNVPROC) (GLsizei range); -typedef void (GL_APIENTRYP PFNGLDELETEPATHSNVPROC) (GLuint path, GLsizei range); -typedef GLboolean (GL_APIENTRYP PFNGLISPATHNVPROC) (GLuint path); -typedef void (GL_APIENTRYP PFNGLPATHCOMMANDSNVPROC) (GLuint path, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); -typedef void (GL_APIENTRYP PFNGLPATHCOORDSNVPROC) (GLuint path, GLsizei numCoords, GLenum coordType, const void *coords); -typedef void (GL_APIENTRYP PFNGLPATHSUBCOMMANDSNVPROC) (GLuint path, GLsizei commandStart, GLsizei commandsToDelete, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); -typedef void (GL_APIENTRYP PFNGLPATHSUBCOORDSNVPROC) (GLuint path, GLsizei coordStart, GLsizei numCoords, GLenum coordType, const void *coords); -typedef void (GL_APIENTRYP PFNGLPATHSTRINGNVPROC) (GLuint path, GLenum format, GLsizei length, const void *pathString); -typedef void (GL_APIENTRYP PFNGLPATHGLYPHSNVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLsizei numGlyphs, GLenum type, const void *charcodes, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); -typedef void (GL_APIENTRYP PFNGLPATHGLYPHRANGENVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyph, GLsizei numGlyphs, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); -typedef void (GL_APIENTRYP PFNGLWEIGHTPATHSNVPROC) (GLuint resultPath, GLsizei numPaths, const GLuint *paths, const GLfloat *weights); -typedef void (GL_APIENTRYP PFNGLCOPYPATHNVPROC) (GLuint resultPath, GLuint srcPath); -typedef void (GL_APIENTRYP PFNGLINTERPOLATEPATHSNVPROC) (GLuint resultPath, GLuint pathA, GLuint pathB, GLfloat weight); -typedef void (GL_APIENTRYP PFNGLTRANSFORMPATHNVPROC) (GLuint resultPath, GLuint srcPath, GLenum transformType, const GLfloat *transformValues); -typedef void (GL_APIENTRYP PFNGLPATHPARAMETERIVNVPROC) (GLuint path, GLenum pname, const GLint *value); -typedef void (GL_APIENTRYP PFNGLPATHPARAMETERINVPROC) (GLuint path, GLenum pname, GLint value); -typedef void (GL_APIENTRYP PFNGLPATHPARAMETERFVNVPROC) (GLuint path, GLenum pname, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLPATHPARAMETERFNVPROC) (GLuint path, GLenum pname, GLfloat value); -typedef void (GL_APIENTRYP PFNGLPATHDASHARRAYNVPROC) (GLuint path, GLsizei dashCount, const GLfloat *dashArray); -typedef void (GL_APIENTRYP PFNGLPATHSTENCILFUNCNVPROC) (GLenum func, GLint ref, GLuint mask); -typedef void (GL_APIENTRYP PFNGLPATHSTENCILDEPTHOFFSETNVPROC) (GLfloat factor, GLfloat units); -typedef void (GL_APIENTRYP PFNGLSTENCILFILLPATHNVPROC) (GLuint path, GLenum fillMode, GLuint mask); -typedef void (GL_APIENTRYP PFNGLSTENCILSTROKEPATHNVPROC) (GLuint path, GLint reference, GLuint mask); -typedef void (GL_APIENTRYP PFNGLSTENCILFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum transformType, const GLfloat *transformValues); -typedef void (GL_APIENTRYP PFNGLSTENCILSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum transformType, const GLfloat *transformValues); -typedef void (GL_APIENTRYP PFNGLPATHCOVERDEPTHFUNCNVPROC) (GLenum func); -typedef void (GL_APIENTRYP PFNGLCOVERFILLPATHNVPROC) (GLuint path, GLenum coverMode); -typedef void (GL_APIENTRYP PFNGLCOVERSTROKEPATHNVPROC) (GLuint path, GLenum coverMode); -typedef void (GL_APIENTRYP PFNGLCOVERFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); -typedef void (GL_APIENTRYP PFNGLCOVERSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); -typedef void (GL_APIENTRYP PFNGLGETPATHPARAMETERIVNVPROC) (GLuint path, GLenum pname, GLint *value); -typedef void (GL_APIENTRYP PFNGLGETPATHPARAMETERFVNVPROC) (GLuint path, GLenum pname, GLfloat *value); -typedef void (GL_APIENTRYP PFNGLGETPATHCOMMANDSNVPROC) (GLuint path, GLubyte *commands); -typedef void (GL_APIENTRYP PFNGLGETPATHCOORDSNVPROC) (GLuint path, GLfloat *coords); -typedef void (GL_APIENTRYP PFNGLGETPATHDASHARRAYNVPROC) (GLuint path, GLfloat *dashArray); -typedef void (GL_APIENTRYP PFNGLGETPATHMETRICSNVPROC) (GLbitfield metricQueryMask, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLsizei stride, GLfloat *metrics); -typedef void (GL_APIENTRYP PFNGLGETPATHMETRICRANGENVPROC) (GLbitfield metricQueryMask, GLuint firstPathName, GLsizei numPaths, GLsizei stride, GLfloat *metrics); -typedef void (GL_APIENTRYP PFNGLGETPATHSPACINGNVPROC) (GLenum pathListMode, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLfloat advanceScale, GLfloat kerningScale, GLenum transformType, GLfloat *returnedSpacing); -typedef GLboolean (GL_APIENTRYP PFNGLISPOINTINFILLPATHNVPROC) (GLuint path, GLuint mask, GLfloat x, GLfloat y); -typedef GLboolean (GL_APIENTRYP PFNGLISPOINTINSTROKEPATHNVPROC) (GLuint path, GLfloat x, GLfloat y); -typedef GLfloat (GL_APIENTRYP PFNGLGETPATHLENGTHNVPROC) (GLuint path, GLsizei startSegment, GLsizei numSegments); -typedef GLboolean (GL_APIENTRYP PFNGLPOINTALONGPATHNVPROC) (GLuint path, GLsizei startSegment, GLsizei numSegments, GLfloat distance, GLfloat *x, GLfloat *y, GLfloat *tangentX, GLfloat *tangentY); -typedef void (GL_APIENTRYP PFNGLMATRIXLOAD3X2FNVPROC) (GLenum matrixMode, const GLfloat *m); -typedef void (GL_APIENTRYP PFNGLMATRIXLOAD3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); -typedef void (GL_APIENTRYP PFNGLMATRIXLOADTRANSPOSE3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); -typedef void (GL_APIENTRYP PFNGLMATRIXMULT3X2FNVPROC) (GLenum matrixMode, const GLfloat *m); -typedef void (GL_APIENTRYP PFNGLMATRIXMULT3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); -typedef void (GL_APIENTRYP PFNGLMATRIXMULTTRANSPOSE3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); -typedef void (GL_APIENTRYP PFNGLSTENCILTHENCOVERFILLPATHNVPROC) (GLuint path, GLenum fillMode, GLuint mask, GLenum coverMode); -typedef void (GL_APIENTRYP PFNGLSTENCILTHENCOVERSTROKEPATHNVPROC) (GLuint path, GLint reference, GLuint mask, GLenum coverMode); -typedef void (GL_APIENTRYP PFNGLSTENCILTHENCOVERFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); -typedef void (GL_APIENTRYP PFNGLSTENCILTHENCOVERSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); -typedef GLenum (GL_APIENTRYP PFNGLPATHGLYPHINDEXRANGENVPROC) (GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint pathParameterTemplate, GLfloat emScale, GLuint baseAndCount[2]); -typedef GLenum (GL_APIENTRYP PFNGLPATHGLYPHINDEXARRAYNVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); -typedef GLenum (GL_APIENTRYP PFNGLPATHMEMORYGLYPHINDEXARRAYNVPROC) (GLuint firstPathName, GLenum fontTarget, GLsizeiptr fontSize, const void *fontData, GLsizei faceIndex, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); -typedef void (GL_APIENTRYP PFNGLPROGRAMPATHFRAGMENTINPUTGENNVPROC) (GLuint program, GLint location, GLenum genMode, GLint components, const GLfloat *coeffs); -typedef void (GL_APIENTRYP PFNGLGETPROGRAMRESOURCEFVNVPROC) (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLfloat *params); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL GLuint GL_APIENTRY glGenPathsNV (GLsizei range); -GL_APICALL void GL_APIENTRY glDeletePathsNV (GLuint path, GLsizei range); -GL_APICALL GLboolean GL_APIENTRY glIsPathNV (GLuint path); -GL_APICALL void GL_APIENTRY glPathCommandsNV (GLuint path, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); -GL_APICALL void GL_APIENTRY glPathCoordsNV (GLuint path, GLsizei numCoords, GLenum coordType, const void *coords); -GL_APICALL void GL_APIENTRY glPathSubCommandsNV (GLuint path, GLsizei commandStart, GLsizei commandsToDelete, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); -GL_APICALL void GL_APIENTRY glPathSubCoordsNV (GLuint path, GLsizei coordStart, GLsizei numCoords, GLenum coordType, const void *coords); -GL_APICALL void GL_APIENTRY glPathStringNV (GLuint path, GLenum format, GLsizei length, const void *pathString); -GL_APICALL void GL_APIENTRY glPathGlyphsNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLsizei numGlyphs, GLenum type, const void *charcodes, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); -GL_APICALL void GL_APIENTRY glPathGlyphRangeNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyph, GLsizei numGlyphs, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); -GL_APICALL void GL_APIENTRY glWeightPathsNV (GLuint resultPath, GLsizei numPaths, const GLuint *paths, const GLfloat *weights); -GL_APICALL void GL_APIENTRY glCopyPathNV (GLuint resultPath, GLuint srcPath); -GL_APICALL void GL_APIENTRY glInterpolatePathsNV (GLuint resultPath, GLuint pathA, GLuint pathB, GLfloat weight); -GL_APICALL void GL_APIENTRY glTransformPathNV (GLuint resultPath, GLuint srcPath, GLenum transformType, const GLfloat *transformValues); -GL_APICALL void GL_APIENTRY glPathParameterivNV (GLuint path, GLenum pname, const GLint *value); -GL_APICALL void GL_APIENTRY glPathParameteriNV (GLuint path, GLenum pname, GLint value); -GL_APICALL void GL_APIENTRY glPathParameterfvNV (GLuint path, GLenum pname, const GLfloat *value); -GL_APICALL void GL_APIENTRY glPathParameterfNV (GLuint path, GLenum pname, GLfloat value); -GL_APICALL void GL_APIENTRY glPathDashArrayNV (GLuint path, GLsizei dashCount, const GLfloat *dashArray); -GL_APICALL void GL_APIENTRY glPathStencilFuncNV (GLenum func, GLint ref, GLuint mask); -GL_APICALL void GL_APIENTRY glPathStencilDepthOffsetNV (GLfloat factor, GLfloat units); -GL_APICALL void GL_APIENTRY glStencilFillPathNV (GLuint path, GLenum fillMode, GLuint mask); -GL_APICALL void GL_APIENTRY glStencilStrokePathNV (GLuint path, GLint reference, GLuint mask); -GL_APICALL void GL_APIENTRY glStencilFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum transformType, const GLfloat *transformValues); -GL_APICALL void GL_APIENTRY glStencilStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum transformType, const GLfloat *transformValues); -GL_APICALL void GL_APIENTRY glPathCoverDepthFuncNV (GLenum func); -GL_APICALL void GL_APIENTRY glCoverFillPathNV (GLuint path, GLenum coverMode); -GL_APICALL void GL_APIENTRY glCoverStrokePathNV (GLuint path, GLenum coverMode); -GL_APICALL void GL_APIENTRY glCoverFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); -GL_APICALL void GL_APIENTRY glCoverStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); -GL_APICALL void GL_APIENTRY glGetPathParameterivNV (GLuint path, GLenum pname, GLint *value); -GL_APICALL void GL_APIENTRY glGetPathParameterfvNV (GLuint path, GLenum pname, GLfloat *value); -GL_APICALL void GL_APIENTRY glGetPathCommandsNV (GLuint path, GLubyte *commands); -GL_APICALL void GL_APIENTRY glGetPathCoordsNV (GLuint path, GLfloat *coords); -GL_APICALL void GL_APIENTRY glGetPathDashArrayNV (GLuint path, GLfloat *dashArray); -GL_APICALL void GL_APIENTRY glGetPathMetricsNV (GLbitfield metricQueryMask, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLsizei stride, GLfloat *metrics); -GL_APICALL void GL_APIENTRY glGetPathMetricRangeNV (GLbitfield metricQueryMask, GLuint firstPathName, GLsizei numPaths, GLsizei stride, GLfloat *metrics); -GL_APICALL void GL_APIENTRY glGetPathSpacingNV (GLenum pathListMode, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLfloat advanceScale, GLfloat kerningScale, GLenum transformType, GLfloat *returnedSpacing); -GL_APICALL GLboolean GL_APIENTRY glIsPointInFillPathNV (GLuint path, GLuint mask, GLfloat x, GLfloat y); -GL_APICALL GLboolean GL_APIENTRY glIsPointInStrokePathNV (GLuint path, GLfloat x, GLfloat y); -GL_APICALL GLfloat GL_APIENTRY glGetPathLengthNV (GLuint path, GLsizei startSegment, GLsizei numSegments); -GL_APICALL GLboolean GL_APIENTRY glPointAlongPathNV (GLuint path, GLsizei startSegment, GLsizei numSegments, GLfloat distance, GLfloat *x, GLfloat *y, GLfloat *tangentX, GLfloat *tangentY); -GL_APICALL void GL_APIENTRY glMatrixLoad3x2fNV (GLenum matrixMode, const GLfloat *m); -GL_APICALL void GL_APIENTRY glMatrixLoad3x3fNV (GLenum matrixMode, const GLfloat *m); -GL_APICALL void GL_APIENTRY glMatrixLoadTranspose3x3fNV (GLenum matrixMode, const GLfloat *m); -GL_APICALL void GL_APIENTRY glMatrixMult3x2fNV (GLenum matrixMode, const GLfloat *m); -GL_APICALL void GL_APIENTRY glMatrixMult3x3fNV (GLenum matrixMode, const GLfloat *m); -GL_APICALL void GL_APIENTRY glMatrixMultTranspose3x3fNV (GLenum matrixMode, const GLfloat *m); -GL_APICALL void GL_APIENTRY glStencilThenCoverFillPathNV (GLuint path, GLenum fillMode, GLuint mask, GLenum coverMode); -GL_APICALL void GL_APIENTRY glStencilThenCoverStrokePathNV (GLuint path, GLint reference, GLuint mask, GLenum coverMode); -GL_APICALL void GL_APIENTRY glStencilThenCoverFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); -GL_APICALL void GL_APIENTRY glStencilThenCoverStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); -GL_APICALL GLenum GL_APIENTRY glPathGlyphIndexRangeNV (GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint pathParameterTemplate, GLfloat emScale, GLuint baseAndCount[2]); -GL_APICALL GLenum GL_APIENTRY glPathGlyphIndexArrayNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); -GL_APICALL GLenum GL_APIENTRY glPathMemoryGlyphIndexArrayNV (GLuint firstPathName, GLenum fontTarget, GLsizeiptr fontSize, const void *fontData, GLsizei faceIndex, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); -GL_APICALL void GL_APIENTRY glProgramPathFragmentInputGenNV (GLuint program, GLint location, GLenum genMode, GLint components, const GLfloat *coeffs); -GL_APICALL void GL_APIENTRY glGetProgramResourcefvNV (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLfloat *params); -#endif -#endif /* GL_NV_path_rendering */ - -#ifndef GL_NV_path_rendering_shared_edge -#define GL_NV_path_rendering_shared_edge 1 -#define GL_SHARED_EDGE_NV 0xC0 -#endif /* GL_NV_path_rendering_shared_edge */ - -#ifndef GL_NV_polygon_mode -#define GL_NV_polygon_mode 1 -#define GL_POLYGON_MODE_NV 0x0B40 -#define GL_POLYGON_OFFSET_POINT_NV 0x2A01 -#define GL_POLYGON_OFFSET_LINE_NV 0x2A02 -#define GL_POINT_NV 0x1B00 -#define GL_LINE_NV 0x1B01 -#define GL_FILL_NV 0x1B02 -typedef void (GL_APIENTRYP PFNGLPOLYGONMODENVPROC) (GLenum face, GLenum mode); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glPolygonModeNV (GLenum face, GLenum mode); -#endif -#endif /* GL_NV_polygon_mode */ - -#ifndef GL_NV_read_buffer -#define GL_NV_read_buffer 1 -#define GL_READ_BUFFER_NV 0x0C02 -typedef void (GL_APIENTRYP PFNGLREADBUFFERNVPROC) (GLenum mode); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glReadBufferNV (GLenum mode); -#endif -#endif /* GL_NV_read_buffer */ - -#ifndef GL_NV_read_buffer_front -#define GL_NV_read_buffer_front 1 -#endif /* GL_NV_read_buffer_front */ - -#ifndef GL_NV_read_depth -#define GL_NV_read_depth 1 -#endif /* GL_NV_read_depth */ - -#ifndef GL_NV_read_depth_stencil -#define GL_NV_read_depth_stencil 1 -#endif /* GL_NV_read_depth_stencil */ - -#ifndef GL_NV_read_stencil -#define GL_NV_read_stencil 1 -#endif /* GL_NV_read_stencil */ - -#ifndef GL_NV_sRGB_formats -#define GL_NV_sRGB_formats 1 -#define GL_SLUMINANCE_NV 0x8C46 -#define GL_SLUMINANCE_ALPHA_NV 0x8C44 -#define GL_SRGB8_NV 0x8C41 -#define GL_SLUMINANCE8_NV 0x8C47 -#define GL_SLUMINANCE8_ALPHA8_NV 0x8C45 -#define GL_COMPRESSED_SRGB_S3TC_DXT1_NV 0x8C4C -#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV 0x8C4D -#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV 0x8C4E -#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV 0x8C4F -#define GL_ETC1_SRGB8_NV 0x88EE -#endif /* GL_NV_sRGB_formats */ - -#ifndef GL_NV_sample_locations -#define GL_NV_sample_locations 1 -#define GL_SAMPLE_LOCATION_SUBPIXEL_BITS_NV 0x933D -#define GL_SAMPLE_LOCATION_PIXEL_GRID_WIDTH_NV 0x933E -#define GL_SAMPLE_LOCATION_PIXEL_GRID_HEIGHT_NV 0x933F -#define GL_PROGRAMMABLE_SAMPLE_LOCATION_TABLE_SIZE_NV 0x9340 -#define GL_SAMPLE_LOCATION_NV 0x8E50 -#define GL_PROGRAMMABLE_SAMPLE_LOCATION_NV 0x9341 -#define GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_NV 0x9342 -#define GL_FRAMEBUFFER_SAMPLE_LOCATION_PIXEL_GRID_NV 0x9343 -typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERSAMPLELOCATIONSFVNVPROC) (GLenum target, GLuint start, GLsizei count, const GLfloat *v); -typedef void (GL_APIENTRYP PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVNVPROC) (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); -typedef void (GL_APIENTRYP PFNGLRESOLVEDEPTHVALUESNVPROC) (void); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glFramebufferSampleLocationsfvNV (GLenum target, GLuint start, GLsizei count, const GLfloat *v); -GL_APICALL void GL_APIENTRY glNamedFramebufferSampleLocationsfvNV (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); -GL_APICALL void GL_APIENTRY glResolveDepthValuesNV (void); -#endif -#endif /* GL_NV_sample_locations */ - -#ifndef GL_NV_sample_mask_override_coverage -#define GL_NV_sample_mask_override_coverage 1 -#endif /* GL_NV_sample_mask_override_coverage */ - -#ifndef GL_NV_shader_noperspective_interpolation -#define GL_NV_shader_noperspective_interpolation 1 -#endif /* GL_NV_shader_noperspective_interpolation */ - -#ifndef GL_NV_shadow_samplers_array -#define GL_NV_shadow_samplers_array 1 -#define GL_SAMPLER_2D_ARRAY_SHADOW_NV 0x8DC4 -#endif /* GL_NV_shadow_samplers_array */ - -#ifndef GL_NV_shadow_samplers_cube -#define GL_NV_shadow_samplers_cube 1 -#define GL_SAMPLER_CUBE_SHADOW_NV 0x8DC5 -#endif /* GL_NV_shadow_samplers_cube */ - -#ifndef GL_NV_texture_border_clamp -#define GL_NV_texture_border_clamp 1 -#define GL_TEXTURE_BORDER_COLOR_NV 0x1004 -#define GL_CLAMP_TO_BORDER_NV 0x812D -#endif /* GL_NV_texture_border_clamp */ - -#ifndef GL_NV_texture_compression_s3tc_update -#define GL_NV_texture_compression_s3tc_update 1 -#endif /* GL_NV_texture_compression_s3tc_update */ - -#ifndef GL_NV_texture_npot_2D_mipmap -#define GL_NV_texture_npot_2D_mipmap 1 -#endif /* GL_NV_texture_npot_2D_mipmap */ - -#ifndef GL_NV_viewport_array -#define GL_NV_viewport_array 1 -#define GL_MAX_VIEWPORTS_NV 0x825B -#define GL_VIEWPORT_SUBPIXEL_BITS_NV 0x825C -#define GL_VIEWPORT_BOUNDS_RANGE_NV 0x825D -#define GL_VIEWPORT_INDEX_PROVOKING_VERTEX_NV 0x825F -typedef void (GL_APIENTRYP PFNGLVIEWPORTARRAYVNVPROC) (GLuint first, GLsizei count, const GLfloat *v); -typedef void (GL_APIENTRYP PFNGLVIEWPORTINDEXEDFNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h); -typedef void (GL_APIENTRYP PFNGLVIEWPORTINDEXEDFVNVPROC) (GLuint index, const GLfloat *v); -typedef void (GL_APIENTRYP PFNGLSCISSORARRAYVNVPROC) (GLuint first, GLsizei count, const GLint *v); -typedef void (GL_APIENTRYP PFNGLSCISSORINDEXEDNVPROC) (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height); -typedef void (GL_APIENTRYP PFNGLSCISSORINDEXEDVNVPROC) (GLuint index, const GLint *v); -typedef void (GL_APIENTRYP PFNGLDEPTHRANGEARRAYFVNVPROC) (GLuint first, GLsizei count, const GLfloat *v); -typedef void (GL_APIENTRYP PFNGLDEPTHRANGEINDEXEDFNVPROC) (GLuint index, GLfloat n, GLfloat f); -typedef void (GL_APIENTRYP PFNGLGETFLOATI_VNVPROC) (GLenum target, GLuint index, GLfloat *data); -typedef void (GL_APIENTRYP PFNGLENABLEINVPROC) (GLenum target, GLuint index); -typedef void (GL_APIENTRYP PFNGLDISABLEINVPROC) (GLenum target, GLuint index); -typedef GLboolean (GL_APIENTRYP PFNGLISENABLEDINVPROC) (GLenum target, GLuint index); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glViewportArrayvNV (GLuint first, GLsizei count, const GLfloat *v); -GL_APICALL void GL_APIENTRY glViewportIndexedfNV (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h); -GL_APICALL void GL_APIENTRY glViewportIndexedfvNV (GLuint index, const GLfloat *v); -GL_APICALL void GL_APIENTRY glScissorArrayvNV (GLuint first, GLsizei count, const GLint *v); -GL_APICALL void GL_APIENTRY glScissorIndexedNV (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height); -GL_APICALL void GL_APIENTRY glScissorIndexedvNV (GLuint index, const GLint *v); -GL_APICALL void GL_APIENTRY glDepthRangeArrayfvNV (GLuint first, GLsizei count, const GLfloat *v); -GL_APICALL void GL_APIENTRY glDepthRangeIndexedfNV (GLuint index, GLfloat n, GLfloat f); -GL_APICALL void GL_APIENTRY glGetFloati_vNV (GLenum target, GLuint index, GLfloat *data); -GL_APICALL void GL_APIENTRY glEnableiNV (GLenum target, GLuint index); -GL_APICALL void GL_APIENTRY glDisableiNV (GLenum target, GLuint index); -GL_APICALL GLboolean GL_APIENTRY glIsEnablediNV (GLenum target, GLuint index); -#endif -#endif /* GL_NV_viewport_array */ - -#ifndef GL_NV_viewport_array2 -#define GL_NV_viewport_array2 1 -#endif /* GL_NV_viewport_array2 */ - -#ifndef GL_OVR_multiview -#define GL_OVR_multiview 1 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR 0x9630 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR 0x9632 -#define GL_MAX_VIEWS_OVR 0x9631 -typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glFramebufferTextureMultiviewOVR (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews); -#endif -#endif /* GL_OVR_multiview */ - -#ifndef GL_OVR_multiview2 -#define GL_OVR_multiview2 1 -#endif /* GL_OVR_multiview2 */ - -#ifndef GL_OVR_multiview_multisampled_render_to_texture -#define GL_OVR_multiview_multisampled_render_to_texture 1 -typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTUREMULTISAMPLEMULTIVIEWOVRPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLsizei samples, GLint baseViewIndex, GLsizei numViews); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glFramebufferTextureMultisampleMultiviewOVR (GLenum target, GLenum attachment, GLuint texture, GLint level, GLsizei samples, GLint baseViewIndex, GLsizei numViews); -#endif -#endif /* GL_OVR_multiview_multisampled_render_to_texture */ - -#ifndef GL_QCOM_alpha_test -#define GL_QCOM_alpha_test 1 -#define GL_ALPHA_TEST_QCOM 0x0BC0 -#define GL_ALPHA_TEST_FUNC_QCOM 0x0BC1 -#define GL_ALPHA_TEST_REF_QCOM 0x0BC2 -typedef void (GL_APIENTRYP PFNGLALPHAFUNCQCOMPROC) (GLenum func, GLclampf ref); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glAlphaFuncQCOM (GLenum func, GLclampf ref); -#endif -#endif /* GL_QCOM_alpha_test */ - -#ifndef GL_QCOM_binning_control -#define GL_QCOM_binning_control 1 -#define GL_BINNING_CONTROL_HINT_QCOM 0x8FB0 -#define GL_CPU_OPTIMIZED_QCOM 0x8FB1 -#define GL_GPU_OPTIMIZED_QCOM 0x8FB2 -#define GL_RENDER_DIRECT_TO_FRAMEBUFFER_QCOM 0x8FB3 -#endif /* GL_QCOM_binning_control */ - -#ifndef GL_QCOM_driver_control -#define GL_QCOM_driver_control 1 -typedef void (GL_APIENTRYP PFNGLGETDRIVERCONTROLSQCOMPROC) (GLint *num, GLsizei size, GLuint *driverControls); -typedef void (GL_APIENTRYP PFNGLGETDRIVERCONTROLSTRINGQCOMPROC) (GLuint driverControl, GLsizei bufSize, GLsizei *length, GLchar *driverControlString); -typedef void (GL_APIENTRYP PFNGLENABLEDRIVERCONTROLQCOMPROC) (GLuint driverControl); -typedef void (GL_APIENTRYP PFNGLDISABLEDRIVERCONTROLQCOMPROC) (GLuint driverControl); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glGetDriverControlsQCOM (GLint *num, GLsizei size, GLuint *driverControls); -GL_APICALL void GL_APIENTRY glGetDriverControlStringQCOM (GLuint driverControl, GLsizei bufSize, GLsizei *length, GLchar *driverControlString); -GL_APICALL void GL_APIENTRY glEnableDriverControlQCOM (GLuint driverControl); -GL_APICALL void GL_APIENTRY glDisableDriverControlQCOM (GLuint driverControl); -#endif -#endif /* GL_QCOM_driver_control */ - -#ifndef GL_QCOM_extended_get -#define GL_QCOM_extended_get 1 -#define GL_TEXTURE_WIDTH_QCOM 0x8BD2 -#define GL_TEXTURE_HEIGHT_QCOM 0x8BD3 -#define GL_TEXTURE_DEPTH_QCOM 0x8BD4 -#define GL_TEXTURE_INTERNAL_FORMAT_QCOM 0x8BD5 -#define GL_TEXTURE_FORMAT_QCOM 0x8BD6 -#define GL_TEXTURE_TYPE_QCOM 0x8BD7 -#define GL_TEXTURE_IMAGE_VALID_QCOM 0x8BD8 -#define GL_TEXTURE_NUM_LEVELS_QCOM 0x8BD9 -#define GL_TEXTURE_TARGET_QCOM 0x8BDA -#define GL_TEXTURE_OBJECT_VALID_QCOM 0x8BDB -#define GL_STATE_RESTORE 0x8BDC -typedef void (GL_APIENTRYP PFNGLEXTGETTEXTURESQCOMPROC) (GLuint *textures, GLint maxTextures, GLint *numTextures); -typedef void (GL_APIENTRYP PFNGLEXTGETBUFFERSQCOMPROC) (GLuint *buffers, GLint maxBuffers, GLint *numBuffers); -typedef void (GL_APIENTRYP PFNGLEXTGETRENDERBUFFERSQCOMPROC) (GLuint *renderbuffers, GLint maxRenderbuffers, GLint *numRenderbuffers); -typedef void (GL_APIENTRYP PFNGLEXTGETFRAMEBUFFERSQCOMPROC) (GLuint *framebuffers, GLint maxFramebuffers, GLint *numFramebuffers); -typedef void (GL_APIENTRYP PFNGLEXTGETTEXLEVELPARAMETERIVQCOMPROC) (GLuint texture, GLenum face, GLint level, GLenum pname, GLint *params); -typedef void (GL_APIENTRYP PFNGLEXTTEXOBJECTSTATEOVERRIDEIQCOMPROC) (GLenum target, GLenum pname, GLint param); -typedef void (GL_APIENTRYP PFNGLEXTGETTEXSUBIMAGEQCOMPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, void *texels); -typedef void (GL_APIENTRYP PFNGLEXTGETBUFFERPOINTERVQCOMPROC) (GLenum target, void **params); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glExtGetTexturesQCOM (GLuint *textures, GLint maxTextures, GLint *numTextures); -GL_APICALL void GL_APIENTRY glExtGetBuffersQCOM (GLuint *buffers, GLint maxBuffers, GLint *numBuffers); -GL_APICALL void GL_APIENTRY glExtGetRenderbuffersQCOM (GLuint *renderbuffers, GLint maxRenderbuffers, GLint *numRenderbuffers); -GL_APICALL void GL_APIENTRY glExtGetFramebuffersQCOM (GLuint *framebuffers, GLint maxFramebuffers, GLint *numFramebuffers); -GL_APICALL void GL_APIENTRY glExtGetTexLevelParameterivQCOM (GLuint texture, GLenum face, GLint level, GLenum pname, GLint *params); -GL_APICALL void GL_APIENTRY glExtTexObjectStateOverrideiQCOM (GLenum target, GLenum pname, GLint param); -GL_APICALL void GL_APIENTRY glExtGetTexSubImageQCOM (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, void *texels); -GL_APICALL void GL_APIENTRY glExtGetBufferPointervQCOM (GLenum target, void **params); -#endif -#endif /* GL_QCOM_extended_get */ - -#ifndef GL_QCOM_extended_get2 -#define GL_QCOM_extended_get2 1 -typedef void (GL_APIENTRYP PFNGLEXTGETSHADERSQCOMPROC) (GLuint *shaders, GLint maxShaders, GLint *numShaders); -typedef void (GL_APIENTRYP PFNGLEXTGETPROGRAMSQCOMPROC) (GLuint *programs, GLint maxPrograms, GLint *numPrograms); -typedef GLboolean (GL_APIENTRYP PFNGLEXTISPROGRAMBINARYQCOMPROC) (GLuint program); -typedef void (GL_APIENTRYP PFNGLEXTGETPROGRAMBINARYSOURCEQCOMPROC) (GLuint program, GLenum shadertype, GLchar *source, GLint *length); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glExtGetShadersQCOM (GLuint *shaders, GLint maxShaders, GLint *numShaders); -GL_APICALL void GL_APIENTRY glExtGetProgramsQCOM (GLuint *programs, GLint maxPrograms, GLint *numPrograms); -GL_APICALL GLboolean GL_APIENTRY glExtIsProgramBinaryQCOM (GLuint program); -GL_APICALL void GL_APIENTRY glExtGetProgramBinarySourceQCOM (GLuint program, GLenum shadertype, GLchar *source, GLint *length); -#endif -#endif /* GL_QCOM_extended_get2 */ - -#ifndef GL_QCOM_perfmon_global_mode -#define GL_QCOM_perfmon_global_mode 1 -#define GL_PERFMON_GLOBAL_MODE_QCOM 0x8FA0 -#endif /* GL_QCOM_perfmon_global_mode */ - -#ifndef GL_QCOM_tiled_rendering -#define GL_QCOM_tiled_rendering 1 -#define GL_COLOR_BUFFER_BIT0_QCOM 0x00000001 -#define GL_COLOR_BUFFER_BIT1_QCOM 0x00000002 -#define GL_COLOR_BUFFER_BIT2_QCOM 0x00000004 -#define GL_COLOR_BUFFER_BIT3_QCOM 0x00000008 -#define GL_COLOR_BUFFER_BIT4_QCOM 0x00000010 -#define GL_COLOR_BUFFER_BIT5_QCOM 0x00000020 -#define GL_COLOR_BUFFER_BIT6_QCOM 0x00000040 -#define GL_COLOR_BUFFER_BIT7_QCOM 0x00000080 -#define GL_DEPTH_BUFFER_BIT0_QCOM 0x00000100 -#define GL_DEPTH_BUFFER_BIT1_QCOM 0x00000200 -#define GL_DEPTH_BUFFER_BIT2_QCOM 0x00000400 -#define GL_DEPTH_BUFFER_BIT3_QCOM 0x00000800 -#define GL_DEPTH_BUFFER_BIT4_QCOM 0x00001000 -#define GL_DEPTH_BUFFER_BIT5_QCOM 0x00002000 -#define GL_DEPTH_BUFFER_BIT6_QCOM 0x00004000 -#define GL_DEPTH_BUFFER_BIT7_QCOM 0x00008000 -#define GL_STENCIL_BUFFER_BIT0_QCOM 0x00010000 -#define GL_STENCIL_BUFFER_BIT1_QCOM 0x00020000 -#define GL_STENCIL_BUFFER_BIT2_QCOM 0x00040000 -#define GL_STENCIL_BUFFER_BIT3_QCOM 0x00080000 -#define GL_STENCIL_BUFFER_BIT4_QCOM 0x00100000 -#define GL_STENCIL_BUFFER_BIT5_QCOM 0x00200000 -#define GL_STENCIL_BUFFER_BIT6_QCOM 0x00400000 -#define GL_STENCIL_BUFFER_BIT7_QCOM 0x00800000 -#define GL_MULTISAMPLE_BUFFER_BIT0_QCOM 0x01000000 -#define GL_MULTISAMPLE_BUFFER_BIT1_QCOM 0x02000000 -#define GL_MULTISAMPLE_BUFFER_BIT2_QCOM 0x04000000 -#define GL_MULTISAMPLE_BUFFER_BIT3_QCOM 0x08000000 -#define GL_MULTISAMPLE_BUFFER_BIT4_QCOM 0x10000000 -#define GL_MULTISAMPLE_BUFFER_BIT5_QCOM 0x20000000 -#define GL_MULTISAMPLE_BUFFER_BIT6_QCOM 0x40000000 -#define GL_MULTISAMPLE_BUFFER_BIT7_QCOM 0x80000000 -typedef void (GL_APIENTRYP PFNGLSTARTTILINGQCOMPROC) (GLuint x, GLuint y, GLuint width, GLuint height, GLbitfield preserveMask); -typedef void (GL_APIENTRYP PFNGLENDTILINGQCOMPROC) (GLbitfield preserveMask); -#ifdef GL_GLEXT_PROTOTYPES -GL_APICALL void GL_APIENTRY glStartTilingQCOM (GLuint x, GLuint y, GLuint width, GLuint height, GLbitfield preserveMask); -GL_APICALL void GL_APIENTRY glEndTilingQCOM (GLbitfield preserveMask); -#endif -#endif /* GL_QCOM_tiled_rendering */ - -#ifndef GL_QCOM_writeonly_rendering -#define GL_QCOM_writeonly_rendering 1 -#define GL_WRITEONLY_RENDERING_QCOM 0x8823 -#endif /* GL_QCOM_writeonly_rendering */ - -#ifndef GL_VIV_shader_binary -#define GL_VIV_shader_binary 1 -#define GL_SHADER_BINARY_VIV 0x8FC4 -#endif /* GL_VIV_shader_binary */ - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/RenderSystems/GLES2/include/GLES3/gl3.h b/RenderSystems/GLES2/include/GLES3/gl3.h deleted file mode 100644 index d29f4307eba..00000000000 --- a/RenderSystems/GLES2/include/GLES3/gl3.h +++ /dev/null @@ -1,1211 +0,0 @@ -#ifndef __gl3_h_ -#define __gl3_h_ 1 - -#ifdef __cplusplus -extern "C" { -#endif - -/* -** Copyright (c) 2013-2017 The Khronos Group Inc. -** -** Permission is hereby granted, free of charge, to any person obtaining a -** copy of this software and/or associated documentation files (the -** "Materials"), to deal in the Materials without restriction, including -** without limitation the rights to use, copy, modify, merge, publish, -** distribute, sublicense, and/or sell copies of the Materials, and to -** permit persons to whom the Materials are furnished to do so, subject to -** the following conditions: -** -** The above copyright notice and this permission notice shall be included -** in all copies or substantial portions of the Materials. -** -** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. -*/ -/* -** This header is generated from the Khronos OpenGL / OpenGL ES XML -** API Registry. The current version of the Registry, generator scripts -** used to make the header, and the header can be found at -** https://github.com/KhronosGroup/OpenGL-Registry -*/ - -#include - -#ifndef GL_APIENTRYP -#define GL_APIENTRYP GL_APIENTRY* -#endif - -#ifndef GL_GLES_PROTOTYPES -#define GL_GLES_PROTOTYPES 1 -#endif - -/* Generated on date 20170209 */ - -/* Generated C header for: - * API: gles2 - * Profile: common - * Versions considered: 2\.[0-9]|3\.0 - * Versions emitted: .* - * Default extensions included: None - * Additional extensions included: _nomatch_^ - * Extensions removed: _nomatch_^ - */ - -#ifndef GL_ES_VERSION_2_0 -#define GL_ES_VERSION_2_0 1 -#include -typedef khronos_int8_t GLbyte; -typedef khronos_float_t GLclampf; -typedef khronos_int32_t GLfixed; -typedef short GLshort; -typedef unsigned short GLushort; -typedef void GLvoid; -typedef struct __GLsync *GLsync; -typedef khronos_int64_t GLint64; -typedef khronos_uint64_t GLuint64; -typedef unsigned int GLenum; -typedef unsigned int GLuint; -typedef char GLchar; -typedef khronos_float_t GLfloat; -typedef khronos_ssize_t GLsizeiptr; -typedef khronos_intptr_t GLintptr; -typedef unsigned int GLbitfield; -typedef int GLint; -typedef unsigned char GLboolean; -typedef int GLsizei; -typedef khronos_uint8_t GLubyte; -#define GL_DEPTH_BUFFER_BIT 0x00000100 -#define GL_STENCIL_BUFFER_BIT 0x00000400 -#define GL_COLOR_BUFFER_BIT 0x00004000 -#define GL_FALSE 0 -#define GL_TRUE 1 -#define GL_POINTS 0x0000 -#define GL_LINES 0x0001 -#define GL_LINE_LOOP 0x0002 -#define GL_LINE_STRIP 0x0003 -#define GL_TRIANGLES 0x0004 -#define GL_TRIANGLE_STRIP 0x0005 -#define GL_TRIANGLE_FAN 0x0006 -#define GL_ZERO 0 -#define GL_ONE 1 -#define GL_SRC_COLOR 0x0300 -#define GL_ONE_MINUS_SRC_COLOR 0x0301 -#define GL_SRC_ALPHA 0x0302 -#define GL_ONE_MINUS_SRC_ALPHA 0x0303 -#define GL_DST_ALPHA 0x0304 -#define GL_ONE_MINUS_DST_ALPHA 0x0305 -#define GL_DST_COLOR 0x0306 -#define GL_ONE_MINUS_DST_COLOR 0x0307 -#define GL_SRC_ALPHA_SATURATE 0x0308 -#define GL_FUNC_ADD 0x8006 -#define GL_BLEND_EQUATION 0x8009 -#define GL_BLEND_EQUATION_RGB 0x8009 -#define GL_BLEND_EQUATION_ALPHA 0x883D -#define GL_FUNC_SUBTRACT 0x800A -#define GL_FUNC_REVERSE_SUBTRACT 0x800B -#define GL_BLEND_DST_RGB 0x80C8 -#define GL_BLEND_SRC_RGB 0x80C9 -#define GL_BLEND_DST_ALPHA 0x80CA -#define GL_BLEND_SRC_ALPHA 0x80CB -#define GL_CONSTANT_COLOR 0x8001 -#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 -#define GL_CONSTANT_ALPHA 0x8003 -#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 -#define GL_BLEND_COLOR 0x8005 -#define GL_ARRAY_BUFFER 0x8892 -#define GL_ELEMENT_ARRAY_BUFFER 0x8893 -#define GL_ARRAY_BUFFER_BINDING 0x8894 -#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 -#define GL_STREAM_DRAW 0x88E0 -#define GL_STATIC_DRAW 0x88E4 -#define GL_DYNAMIC_DRAW 0x88E8 -#define GL_BUFFER_SIZE 0x8764 -#define GL_BUFFER_USAGE 0x8765 -#define GL_CURRENT_VERTEX_ATTRIB 0x8626 -#define GL_FRONT 0x0404 -#define GL_BACK 0x0405 -#define GL_FRONT_AND_BACK 0x0408 -#define GL_TEXTURE_2D 0x0DE1 -#define GL_CULL_FACE 0x0B44 -#define GL_BLEND 0x0BE2 -#define GL_DITHER 0x0BD0 -#define GL_STENCIL_TEST 0x0B90 -#define GL_DEPTH_TEST 0x0B71 -#define GL_SCISSOR_TEST 0x0C11 -#define GL_POLYGON_OFFSET_FILL 0x8037 -#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E -#define GL_SAMPLE_COVERAGE 0x80A0 -#define GL_NO_ERROR 0 -#define GL_INVALID_ENUM 0x0500 -#define GL_INVALID_VALUE 0x0501 -#define GL_INVALID_OPERATION 0x0502 -#define GL_OUT_OF_MEMORY 0x0505 -#define GL_CW 0x0900 -#define GL_CCW 0x0901 -#define GL_LINE_WIDTH 0x0B21 -#define GL_ALIASED_POINT_SIZE_RANGE 0x846D -#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E -#define GL_CULL_FACE_MODE 0x0B45 -#define GL_FRONT_FACE 0x0B46 -#define GL_DEPTH_RANGE 0x0B70 -#define GL_DEPTH_WRITEMASK 0x0B72 -#define GL_DEPTH_CLEAR_VALUE 0x0B73 -#define GL_DEPTH_FUNC 0x0B74 -#define GL_STENCIL_CLEAR_VALUE 0x0B91 -#define GL_STENCIL_FUNC 0x0B92 -#define GL_STENCIL_FAIL 0x0B94 -#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 -#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 -#define GL_STENCIL_REF 0x0B97 -#define GL_STENCIL_VALUE_MASK 0x0B93 -#define GL_STENCIL_WRITEMASK 0x0B98 -#define GL_STENCIL_BACK_FUNC 0x8800 -#define GL_STENCIL_BACK_FAIL 0x8801 -#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 -#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 -#define GL_STENCIL_BACK_REF 0x8CA3 -#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 -#define GL_STENCIL_BACK_WRITEMASK 0x8CA5 -#define GL_VIEWPORT 0x0BA2 -#define GL_SCISSOR_BOX 0x0C10 -#define GL_COLOR_CLEAR_VALUE 0x0C22 -#define GL_COLOR_WRITEMASK 0x0C23 -#define GL_UNPACK_ALIGNMENT 0x0CF5 -#define GL_PACK_ALIGNMENT 0x0D05 -#define GL_MAX_TEXTURE_SIZE 0x0D33 -#define GL_MAX_VIEWPORT_DIMS 0x0D3A -#define GL_SUBPIXEL_BITS 0x0D50 -#define GL_RED_BITS 0x0D52 -#define GL_GREEN_BITS 0x0D53 -#define GL_BLUE_BITS 0x0D54 -#define GL_ALPHA_BITS 0x0D55 -#define GL_DEPTH_BITS 0x0D56 -#define GL_STENCIL_BITS 0x0D57 -#define GL_POLYGON_OFFSET_UNITS 0x2A00 -#define GL_POLYGON_OFFSET_FACTOR 0x8038 -#define GL_TEXTURE_BINDING_2D 0x8069 -#define GL_SAMPLE_BUFFERS 0x80A8 -#define GL_SAMPLES 0x80A9 -#define GL_SAMPLE_COVERAGE_VALUE 0x80AA -#define GL_SAMPLE_COVERAGE_INVERT 0x80AB -#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 -#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 -#define GL_DONT_CARE 0x1100 -#define GL_FASTEST 0x1101 -#define GL_NICEST 0x1102 -#define GL_GENERATE_MIPMAP_HINT 0x8192 -#define GL_BYTE 0x1400 -#define GL_UNSIGNED_BYTE 0x1401 -#define GL_SHORT 0x1402 -#define GL_UNSIGNED_SHORT 0x1403 -#define GL_INT 0x1404 -#define GL_UNSIGNED_INT 0x1405 -#define GL_FLOAT 0x1406 -#define GL_FIXED 0x140C -#define GL_DEPTH_COMPONENT 0x1902 -#define GL_ALPHA 0x1906 -#define GL_RGB 0x1907 -#define GL_RGBA 0x1908 -#define GL_LUMINANCE 0x1909 -#define GL_LUMINANCE_ALPHA 0x190A -#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 -#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 -#define GL_UNSIGNED_SHORT_5_6_5 0x8363 -#define GL_FRAGMENT_SHADER 0x8B30 -#define GL_VERTEX_SHADER 0x8B31 -#define GL_MAX_VERTEX_ATTRIBS 0x8869 -#define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB -#define GL_MAX_VARYING_VECTORS 0x8DFC -#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D -#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C -#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 -#define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD -#define GL_SHADER_TYPE 0x8B4F -#define GL_DELETE_STATUS 0x8B80 -#define GL_LINK_STATUS 0x8B82 -#define GL_VALIDATE_STATUS 0x8B83 -#define GL_ATTACHED_SHADERS 0x8B85 -#define GL_ACTIVE_UNIFORMS 0x8B86 -#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 -#define GL_ACTIVE_ATTRIBUTES 0x8B89 -#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A -#define GL_SHADING_LANGUAGE_VERSION 0x8B8C -#define GL_CURRENT_PROGRAM 0x8B8D -#define GL_NEVER 0x0200 -#define GL_LESS 0x0201 -#define GL_EQUAL 0x0202 -#define GL_LEQUAL 0x0203 -#define GL_GREATER 0x0204 -#define GL_NOTEQUAL 0x0205 -#define GL_GEQUAL 0x0206 -#define GL_ALWAYS 0x0207 -#define GL_KEEP 0x1E00 -#define GL_REPLACE 0x1E01 -#define GL_INCR 0x1E02 -#define GL_DECR 0x1E03 -#define GL_INVERT 0x150A -#define GL_INCR_WRAP 0x8507 -#define GL_DECR_WRAP 0x8508 -#define GL_VENDOR 0x1F00 -#define GL_RENDERER 0x1F01 -#define GL_VERSION 0x1F02 -#define GL_EXTENSIONS 0x1F03 -#define GL_NEAREST 0x2600 -#define GL_LINEAR 0x2601 -#define GL_NEAREST_MIPMAP_NEAREST 0x2700 -#define GL_LINEAR_MIPMAP_NEAREST 0x2701 -#define GL_NEAREST_MIPMAP_LINEAR 0x2702 -#define GL_LINEAR_MIPMAP_LINEAR 0x2703 -#define GL_TEXTURE_MAG_FILTER 0x2800 -#define GL_TEXTURE_MIN_FILTER 0x2801 -#define GL_TEXTURE_WRAP_S 0x2802 -#define GL_TEXTURE_WRAP_T 0x2803 -#define GL_TEXTURE 0x1702 -#define GL_TEXTURE_CUBE_MAP 0x8513 -#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A -#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C -#define GL_TEXTURE0 0x84C0 -#define GL_TEXTURE1 0x84C1 -#define GL_TEXTURE2 0x84C2 -#define GL_TEXTURE3 0x84C3 -#define GL_TEXTURE4 0x84C4 -#define GL_TEXTURE5 0x84C5 -#define GL_TEXTURE6 0x84C6 -#define GL_TEXTURE7 0x84C7 -#define GL_TEXTURE8 0x84C8 -#define GL_TEXTURE9 0x84C9 -#define GL_TEXTURE10 0x84CA -#define GL_TEXTURE11 0x84CB -#define GL_TEXTURE12 0x84CC -#define GL_TEXTURE13 0x84CD -#define GL_TEXTURE14 0x84CE -#define GL_TEXTURE15 0x84CF -#define GL_TEXTURE16 0x84D0 -#define GL_TEXTURE17 0x84D1 -#define GL_TEXTURE18 0x84D2 -#define GL_TEXTURE19 0x84D3 -#define GL_TEXTURE20 0x84D4 -#define GL_TEXTURE21 0x84D5 -#define GL_TEXTURE22 0x84D6 -#define GL_TEXTURE23 0x84D7 -#define GL_TEXTURE24 0x84D8 -#define GL_TEXTURE25 0x84D9 -#define GL_TEXTURE26 0x84DA -#define GL_TEXTURE27 0x84DB -#define GL_TEXTURE28 0x84DC -#define GL_TEXTURE29 0x84DD -#define GL_TEXTURE30 0x84DE -#define GL_TEXTURE31 0x84DF -#define GL_ACTIVE_TEXTURE 0x84E0 -#define GL_REPEAT 0x2901 -#define GL_CLAMP_TO_EDGE 0x812F -#define GL_MIRRORED_REPEAT 0x8370 -#define GL_FLOAT_VEC2 0x8B50 -#define GL_FLOAT_VEC3 0x8B51 -#define GL_FLOAT_VEC4 0x8B52 -#define GL_INT_VEC2 0x8B53 -#define GL_INT_VEC3 0x8B54 -#define GL_INT_VEC4 0x8B55 -#define GL_BOOL 0x8B56 -#define GL_BOOL_VEC2 0x8B57 -#define GL_BOOL_VEC3 0x8B58 -#define GL_BOOL_VEC4 0x8B59 -#define GL_FLOAT_MAT2 0x8B5A -#define GL_FLOAT_MAT3 0x8B5B -#define GL_FLOAT_MAT4 0x8B5C -#define GL_SAMPLER_2D 0x8B5E -#define GL_SAMPLER_CUBE 0x8B60 -#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 -#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 -#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 -#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 -#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A -#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 -#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F -#define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A -#define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B -#define GL_COMPILE_STATUS 0x8B81 -#define GL_INFO_LOG_LENGTH 0x8B84 -#define GL_SHADER_SOURCE_LENGTH 0x8B88 -#define GL_SHADER_COMPILER 0x8DFA -#define GL_SHADER_BINARY_FORMATS 0x8DF8 -#define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9 -#define GL_LOW_FLOAT 0x8DF0 -#define GL_MEDIUM_FLOAT 0x8DF1 -#define GL_HIGH_FLOAT 0x8DF2 -#define GL_LOW_INT 0x8DF3 -#define GL_MEDIUM_INT 0x8DF4 -#define GL_HIGH_INT 0x8DF5 -#define GL_FRAMEBUFFER 0x8D40 -#define GL_RENDERBUFFER 0x8D41 -#define GL_RGBA4 0x8056 -#define GL_RGB5_A1 0x8057 -#define GL_RGB565 0x8D62 -#define GL_DEPTH_COMPONENT16 0x81A5 -#define GL_STENCIL_INDEX8 0x8D48 -#define GL_RENDERBUFFER_WIDTH 0x8D42 -#define GL_RENDERBUFFER_HEIGHT 0x8D43 -#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 -#define GL_RENDERBUFFER_RED_SIZE 0x8D50 -#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 -#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 -#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 -#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 -#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 -#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 -#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 -#define GL_COLOR_ATTACHMENT0 0x8CE0 -#define GL_DEPTH_ATTACHMENT 0x8D00 -#define GL_STENCIL_ATTACHMENT 0x8D20 -#define GL_NONE 0 -#define GL_FRAMEBUFFER_COMPLETE 0x8CD5 -#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 -#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 -#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS 0x8CD9 -#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD -#define GL_FRAMEBUFFER_BINDING 0x8CA6 -#define GL_RENDERBUFFER_BINDING 0x8CA7 -#define GL_MAX_RENDERBUFFER_SIZE 0x84E8 -#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 -typedef void (GL_APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture); -typedef void (GL_APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader); -typedef void (GL_APIENTRYP PFNGLBINDATTRIBLOCATIONPROC) (GLuint program, GLuint index, const GLchar *name); -typedef void (GL_APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer); -typedef void (GL_APIENTRYP PFNGLBINDFRAMEBUFFERPROC) (GLenum target, GLuint framebuffer); -typedef void (GL_APIENTRYP PFNGLBINDRENDERBUFFERPROC) (GLenum target, GLuint renderbuffer); -typedef void (GL_APIENTRYP PFNGLBINDTEXTUREPROC) (GLenum target, GLuint texture); -typedef void (GL_APIENTRYP PFNGLBLENDCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); -typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode); -typedef void (GL_APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha); -typedef void (GL_APIENTRYP PFNGLBLENDFUNCPROC) (GLenum sfactor, GLenum dfactor); -typedef void (GL_APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); -typedef void (GL_APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage); -typedef void (GL_APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); -typedef GLenum (GL_APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSPROC) (GLenum target); -typedef void (GL_APIENTRYP PFNGLCLEARPROC) (GLbitfield mask); -typedef void (GL_APIENTRYP PFNGLCLEARCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); -typedef void (GL_APIENTRYP PFNGLCLEARDEPTHFPROC) (GLfloat d); -typedef void (GL_APIENTRYP PFNGLCLEARSTENCILPROC) (GLint s); -typedef void (GL_APIENTRYP PFNGLCOLORMASKPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); -typedef void (GL_APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader); -typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); -typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); -typedef void (GL_APIENTRYP PFNGLCOPYTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); -typedef void (GL_APIENTRYP PFNGLCOPYTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); -typedef GLuint (GL_APIENTRYP PFNGLCREATEPROGRAMPROC) (void); -typedef GLuint (GL_APIENTRYP PFNGLCREATESHADERPROC) (GLenum type); -typedef void (GL_APIENTRYP PFNGLCULLFACEPROC) (GLenum mode); -typedef void (GL_APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers); -typedef void (GL_APIENTRYP PFNGLDELETEFRAMEBUFFERSPROC) (GLsizei n, const GLuint *framebuffers); -typedef void (GL_APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program); -typedef void (GL_APIENTRYP PFNGLDELETERENDERBUFFERSPROC) (GLsizei n, const GLuint *renderbuffers); -typedef void (GL_APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader); -typedef void (GL_APIENTRYP PFNGLDELETETEXTURESPROC) (GLsizei n, const GLuint *textures); -typedef void (GL_APIENTRYP PFNGLDEPTHFUNCPROC) (GLenum func); -typedef void (GL_APIENTRYP PFNGLDEPTHMASKPROC) (GLboolean flag); -typedef void (GL_APIENTRYP PFNGLDEPTHRANGEFPROC) (GLfloat n, GLfloat f); -typedef void (GL_APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader); -typedef void (GL_APIENTRYP PFNGLDISABLEPROC) (GLenum cap); -typedef void (GL_APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index); -typedef void (GL_APIENTRYP PFNGLDRAWARRAYSPROC) (GLenum mode, GLint first, GLsizei count); -typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices); -typedef void (GL_APIENTRYP PFNGLENABLEPROC) (GLenum cap); -typedef void (GL_APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index); -typedef void (GL_APIENTRYP PFNGLFINISHPROC) (void); -typedef void (GL_APIENTRYP PFNGLFLUSHPROC) (void); -typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFERPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); -typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); -typedef void (GL_APIENTRYP PFNGLFRONTFACEPROC) (GLenum mode); -typedef void (GL_APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers); -typedef void (GL_APIENTRYP PFNGLGENERATEMIPMAPPROC) (GLenum target); -typedef void (GL_APIENTRYP PFNGLGENFRAMEBUFFERSPROC) (GLsizei n, GLuint *framebuffers); -typedef void (GL_APIENTRYP PFNGLGENRENDERBUFFERSPROC) (GLsizei n, GLuint *renderbuffers); -typedef void (GL_APIENTRYP PFNGLGENTEXTURESPROC) (GLsizei n, GLuint *textures); -typedef void (GL_APIENTRYP PFNGLGETACTIVEATTRIBPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); -typedef void (GL_APIENTRYP PFNGLGETACTIVEUNIFORMPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); -typedef void (GL_APIENTRYP PFNGLGETATTACHEDSHADERSPROC) (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); -typedef GLint (GL_APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name); -typedef void (GL_APIENTRYP PFNGLGETBOOLEANVPROC) (GLenum pname, GLboolean *data); -typedef void (GL_APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); -typedef GLenum (GL_APIENTRYP PFNGLGETERRORPROC) (void); -typedef void (GL_APIENTRYP PFNGLGETFLOATVPROC) (GLenum pname, GLfloat *data); -typedef void (GL_APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params); -typedef void (GL_APIENTRYP PFNGLGETINTEGERVPROC) (GLenum pname, GLint *data); -typedef void (GL_APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params); -typedef void (GL_APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); -typedef void (GL_APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); -typedef void (GL_APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params); -typedef void (GL_APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); -typedef void (GL_APIENTRYP PFNGLGETSHADERPRECISIONFORMATPROC) (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision); -typedef void (GL_APIENTRYP PFNGLGETSHADERSOURCEPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); -typedef const GLubyte *(GL_APIENTRYP PFNGLGETSTRINGPROC) (GLenum name); -typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); -typedef void (GL_APIENTRYP PFNGLGETTEXPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); -typedef void (GL_APIENTRYP PFNGLGETUNIFORMFVPROC) (GLuint program, GLint location, GLfloat *params); -typedef void (GL_APIENTRYP PFNGLGETUNIFORMIVPROC) (GLuint program, GLint location, GLint *params); -typedef GLint (GL_APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name); -typedef void (GL_APIENTRYP PFNGLGETVERTEXATTRIBFVPROC) (GLuint index, GLenum pname, GLfloat *params); -typedef void (GL_APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params); -typedef void (GL_APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer); -typedef void (GL_APIENTRYP PFNGLHINTPROC) (GLenum target, GLenum mode); -typedef GLboolean (GL_APIENTRYP PFNGLISBUFFERPROC) (GLuint buffer); -typedef GLboolean (GL_APIENTRYP PFNGLISENABLEDPROC) (GLenum cap); -typedef GLboolean (GL_APIENTRYP PFNGLISFRAMEBUFFERPROC) (GLuint framebuffer); -typedef GLboolean (GL_APIENTRYP PFNGLISPROGRAMPROC) (GLuint program); -typedef GLboolean (GL_APIENTRYP PFNGLISRENDERBUFFERPROC) (GLuint renderbuffer); -typedef GLboolean (GL_APIENTRYP PFNGLISSHADERPROC) (GLuint shader); -typedef GLboolean (GL_APIENTRYP PFNGLISTEXTUREPROC) (GLuint texture); -typedef void (GL_APIENTRYP PFNGLLINEWIDTHPROC) (GLfloat width); -typedef void (GL_APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program); -typedef void (GL_APIENTRYP PFNGLPIXELSTOREIPROC) (GLenum pname, GLint param); -typedef void (GL_APIENTRYP PFNGLPOLYGONOFFSETPROC) (GLfloat factor, GLfloat units); -typedef void (GL_APIENTRYP PFNGLREADPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); -typedef void (GL_APIENTRYP PFNGLRELEASESHADERCOMPILERPROC) (void); -typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); -typedef void (GL_APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLfloat value, GLboolean invert); -typedef void (GL_APIENTRYP PFNGLSCISSORPROC) (GLint x, GLint y, GLsizei width, GLsizei height); -typedef void (GL_APIENTRYP PFNGLSHADERBINARYPROC) (GLsizei count, const GLuint *shaders, GLenum binaryformat, const void *binary, GLsizei length); -typedef void (GL_APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); -typedef void (GL_APIENTRYP PFNGLSTENCILFUNCPROC) (GLenum func, GLint ref, GLuint mask); -typedef void (GL_APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC) (GLenum face, GLenum func, GLint ref, GLuint mask); -typedef void (GL_APIENTRYP PFNGLSTENCILMASKPROC) (GLuint mask); -typedef void (GL_APIENTRYP PFNGLSTENCILMASKSEPARATEPROC) (GLenum face, GLuint mask); -typedef void (GL_APIENTRYP PFNGLSTENCILOPPROC) (GLenum fail, GLenum zfail, GLenum zpass); -typedef void (GL_APIENTRYP PFNGLSTENCILOPSEPARATEPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); -typedef void (GL_APIENTRYP PFNGLTEXIMAGE2DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); -typedef void (GL_APIENTRYP PFNGLTEXPARAMETERFPROC) (GLenum target, GLenum pname, GLfloat param); -typedef void (GL_APIENTRYP PFNGLTEXPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params); -typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIPROC) (GLenum target, GLenum pname, GLint param); -typedef void (GL_APIENTRYP PFNGLTEXPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params); -typedef void (GL_APIENTRYP PFNGLTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); -typedef void (GL_APIENTRYP PFNGLUNIFORM1FPROC) (GLint location, GLfloat v0); -typedef void (GL_APIENTRYP PFNGLUNIFORM1FVPROC) (GLint location, GLsizei count, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0); -typedef void (GL_APIENTRYP PFNGLUNIFORM1IVPROC) (GLint location, GLsizei count, const GLint *value); -typedef void (GL_APIENTRYP PFNGLUNIFORM2FPROC) (GLint location, GLfloat v0, GLfloat v1); -typedef void (GL_APIENTRYP PFNGLUNIFORM2FVPROC) (GLint location, GLsizei count, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLUNIFORM2IPROC) (GLint location, GLint v0, GLint v1); -typedef void (GL_APIENTRYP PFNGLUNIFORM2IVPROC) (GLint location, GLsizei count, const GLint *value); -typedef void (GL_APIENTRYP PFNGLUNIFORM3FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); -typedef void (GL_APIENTRYP PFNGLUNIFORM3FVPROC) (GLint location, GLsizei count, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLUNIFORM3IPROC) (GLint location, GLint v0, GLint v1, GLint v2); -typedef void (GL_APIENTRYP PFNGLUNIFORM3IVPROC) (GLint location, GLsizei count, const GLint *value); -typedef void (GL_APIENTRYP PFNGLUNIFORM4FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); -typedef void (GL_APIENTRYP PFNGLUNIFORM4FVPROC) (GLint location, GLsizei count, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLUNIFORM4IPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); -typedef void (GL_APIENTRYP PFNGLUNIFORM4IVPROC) (GLint location, GLsizei count, const GLint *value); -typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program); -typedef void (GL_APIENTRYP PFNGLVALIDATEPROGRAMPROC) (GLuint program); -typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB1FPROC) (GLuint index, GLfloat x); -typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB1FVPROC) (GLuint index, const GLfloat *v); -typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB2FPROC) (GLuint index, GLfloat x, GLfloat y); -typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB2FVPROC) (GLuint index, const GLfloat *v); -typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB3FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); -typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB3FVPROC) (GLuint index, const GLfloat *v); -typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB4FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); -typedef void (GL_APIENTRYP PFNGLVERTEXATTRIB4FVPROC) (GLuint index, const GLfloat *v); -typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); -typedef void (GL_APIENTRYP PFNGLVIEWPORTPROC) (GLint x, GLint y, GLsizei width, GLsizei height); -#if GL_GLES_PROTOTYPES -GL_APICALL void GL_APIENTRY glActiveTexture (GLenum texture); -GL_APICALL void GL_APIENTRY glAttachShader (GLuint program, GLuint shader); -GL_APICALL void GL_APIENTRY glBindAttribLocation (GLuint program, GLuint index, const GLchar *name); -GL_APICALL void GL_APIENTRY glBindBuffer (GLenum target, GLuint buffer); -GL_APICALL void GL_APIENTRY glBindFramebuffer (GLenum target, GLuint framebuffer); -GL_APICALL void GL_APIENTRY glBindRenderbuffer (GLenum target, GLuint renderbuffer); -GL_APICALL void GL_APIENTRY glBindTexture (GLenum target, GLuint texture); -GL_APICALL void GL_APIENTRY glBlendColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); -GL_APICALL void GL_APIENTRY glBlendEquation (GLenum mode); -GL_APICALL void GL_APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha); -GL_APICALL void GL_APIENTRY glBlendFunc (GLenum sfactor, GLenum dfactor); -GL_APICALL void GL_APIENTRY glBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); -GL_APICALL void GL_APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void *data, GLenum usage); -GL_APICALL void GL_APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); -GL_APICALL GLenum GL_APIENTRY glCheckFramebufferStatus (GLenum target); -GL_APICALL void GL_APIENTRY glClear (GLbitfield mask); -GL_APICALL void GL_APIENTRY glClearColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); -GL_APICALL void GL_APIENTRY glClearDepthf (GLfloat d); -GL_APICALL void GL_APIENTRY glClearStencil (GLint s); -GL_APICALL void GL_APIENTRY glColorMask (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); -GL_APICALL void GL_APIENTRY glCompileShader (GLuint shader); -GL_APICALL void GL_APIENTRY glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); -GL_APICALL void GL_APIENTRY glCompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); -GL_APICALL void GL_APIENTRY glCopyTexImage2D (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); -GL_APICALL void GL_APIENTRY glCopyTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); -GL_APICALL GLuint GL_APIENTRY glCreateProgram (void); -GL_APICALL GLuint GL_APIENTRY glCreateShader (GLenum type); -GL_APICALL void GL_APIENTRY glCullFace (GLenum mode); -GL_APICALL void GL_APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers); -GL_APICALL void GL_APIENTRY glDeleteFramebuffers (GLsizei n, const GLuint *framebuffers); -GL_APICALL void GL_APIENTRY glDeleteProgram (GLuint program); -GL_APICALL void GL_APIENTRY glDeleteRenderbuffers (GLsizei n, const GLuint *renderbuffers); -GL_APICALL void GL_APIENTRY glDeleteShader (GLuint shader); -GL_APICALL void GL_APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures); -GL_APICALL void GL_APIENTRY glDepthFunc (GLenum func); -GL_APICALL void GL_APIENTRY glDepthMask (GLboolean flag); -GL_APICALL void GL_APIENTRY glDepthRangef (GLfloat n, GLfloat f); -GL_APICALL void GL_APIENTRY glDetachShader (GLuint program, GLuint shader); -GL_APICALL void GL_APIENTRY glDisable (GLenum cap); -GL_APICALL void GL_APIENTRY glDisableVertexAttribArray (GLuint index); -GL_APICALL void GL_APIENTRY glDrawArrays (GLenum mode, GLint first, GLsizei count); -GL_APICALL void GL_APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const void *indices); -GL_APICALL void GL_APIENTRY glEnable (GLenum cap); -GL_APICALL void GL_APIENTRY glEnableVertexAttribArray (GLuint index); -GL_APICALL void GL_APIENTRY glFinish (void); -GL_APICALL void GL_APIENTRY glFlush (void); -GL_APICALL void GL_APIENTRY glFramebufferRenderbuffer (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); -GL_APICALL void GL_APIENTRY glFramebufferTexture2D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); -GL_APICALL void GL_APIENTRY glFrontFace (GLenum mode); -GL_APICALL void GL_APIENTRY glGenBuffers (GLsizei n, GLuint *buffers); -GL_APICALL void GL_APIENTRY glGenerateMipmap (GLenum target); -GL_APICALL void GL_APIENTRY glGenFramebuffers (GLsizei n, GLuint *framebuffers); -GL_APICALL void GL_APIENTRY glGenRenderbuffers (GLsizei n, GLuint *renderbuffers); -GL_APICALL void GL_APIENTRY glGenTextures (GLsizei n, GLuint *textures); -GL_APICALL void GL_APIENTRY glGetActiveAttrib (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); -GL_APICALL void GL_APIENTRY glGetActiveUniform (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); -GL_APICALL void GL_APIENTRY glGetAttachedShaders (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); -GL_APICALL GLint GL_APIENTRY glGetAttribLocation (GLuint program, const GLchar *name); -GL_APICALL void GL_APIENTRY glGetBooleanv (GLenum pname, GLboolean *data); -GL_APICALL void GL_APIENTRY glGetBufferParameteriv (GLenum target, GLenum pname, GLint *params); -GL_APICALL GLenum GL_APIENTRY glGetError (void); -GL_APICALL void GL_APIENTRY glGetFloatv (GLenum pname, GLfloat *data); -GL_APICALL void GL_APIENTRY glGetFramebufferAttachmentParameteriv (GLenum target, GLenum attachment, GLenum pname, GLint *params); -GL_APICALL void GL_APIENTRY glGetIntegerv (GLenum pname, GLint *data); -GL_APICALL void GL_APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params); -GL_APICALL void GL_APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); -GL_APICALL void GL_APIENTRY glGetRenderbufferParameteriv (GLenum target, GLenum pname, GLint *params); -GL_APICALL void GL_APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params); -GL_APICALL void GL_APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); -GL_APICALL void GL_APIENTRY glGetShaderPrecisionFormat (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision); -GL_APICALL void GL_APIENTRY glGetShaderSource (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); -GL_APICALL const GLubyte *GL_APIENTRY glGetString (GLenum name); -GL_APICALL void GL_APIENTRY glGetTexParameterfv (GLenum target, GLenum pname, GLfloat *params); -GL_APICALL void GL_APIENTRY glGetTexParameteriv (GLenum target, GLenum pname, GLint *params); -GL_APICALL void GL_APIENTRY glGetUniformfv (GLuint program, GLint location, GLfloat *params); -GL_APICALL void GL_APIENTRY glGetUniformiv (GLuint program, GLint location, GLint *params); -GL_APICALL GLint GL_APIENTRY glGetUniformLocation (GLuint program, const GLchar *name); -GL_APICALL void GL_APIENTRY glGetVertexAttribfv (GLuint index, GLenum pname, GLfloat *params); -GL_APICALL void GL_APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint *params); -GL_APICALL void GL_APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void **pointer); -GL_APICALL void GL_APIENTRY glHint (GLenum target, GLenum mode); -GL_APICALL GLboolean GL_APIENTRY glIsBuffer (GLuint buffer); -GL_APICALL GLboolean GL_APIENTRY glIsEnabled (GLenum cap); -GL_APICALL GLboolean GL_APIENTRY glIsFramebuffer (GLuint framebuffer); -GL_APICALL GLboolean GL_APIENTRY glIsProgram (GLuint program); -GL_APICALL GLboolean GL_APIENTRY glIsRenderbuffer (GLuint renderbuffer); -GL_APICALL GLboolean GL_APIENTRY glIsShader (GLuint shader); -GL_APICALL GLboolean GL_APIENTRY glIsTexture (GLuint texture); -GL_APICALL void GL_APIENTRY glLineWidth (GLfloat width); -GL_APICALL void GL_APIENTRY glLinkProgram (GLuint program); -GL_APICALL void GL_APIENTRY glPixelStorei (GLenum pname, GLint param); -GL_APICALL void GL_APIENTRY glPolygonOffset (GLfloat factor, GLfloat units); -GL_APICALL void GL_APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); -GL_APICALL void GL_APIENTRY glReleaseShaderCompiler (void); -GL_APICALL void GL_APIENTRY glRenderbufferStorage (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); -GL_APICALL void GL_APIENTRY glSampleCoverage (GLfloat value, GLboolean invert); -GL_APICALL void GL_APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height); -GL_APICALL void GL_APIENTRY glShaderBinary (GLsizei count, const GLuint *shaders, GLenum binaryformat, const void *binary, GLsizei length); -GL_APICALL void GL_APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); -GL_APICALL void GL_APIENTRY glStencilFunc (GLenum func, GLint ref, GLuint mask); -GL_APICALL void GL_APIENTRY glStencilFuncSeparate (GLenum face, GLenum func, GLint ref, GLuint mask); -GL_APICALL void GL_APIENTRY glStencilMask (GLuint mask); -GL_APICALL void GL_APIENTRY glStencilMaskSeparate (GLenum face, GLuint mask); -GL_APICALL void GL_APIENTRY glStencilOp (GLenum fail, GLenum zfail, GLenum zpass); -GL_APICALL void GL_APIENTRY glStencilOpSeparate (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); -GL_APICALL void GL_APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); -GL_APICALL void GL_APIENTRY glTexParameterf (GLenum target, GLenum pname, GLfloat param); -GL_APICALL void GL_APIENTRY glTexParameterfv (GLenum target, GLenum pname, const GLfloat *params); -GL_APICALL void GL_APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param); -GL_APICALL void GL_APIENTRY glTexParameteriv (GLenum target, GLenum pname, const GLint *params); -GL_APICALL void GL_APIENTRY glTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); -GL_APICALL void GL_APIENTRY glUniform1f (GLint location, GLfloat v0); -GL_APICALL void GL_APIENTRY glUniform1fv (GLint location, GLsizei count, const GLfloat *value); -GL_APICALL void GL_APIENTRY glUniform1i (GLint location, GLint v0); -GL_APICALL void GL_APIENTRY glUniform1iv (GLint location, GLsizei count, const GLint *value); -GL_APICALL void GL_APIENTRY glUniform2f (GLint location, GLfloat v0, GLfloat v1); -GL_APICALL void GL_APIENTRY glUniform2fv (GLint location, GLsizei count, const GLfloat *value); -GL_APICALL void GL_APIENTRY glUniform2i (GLint location, GLint v0, GLint v1); -GL_APICALL void GL_APIENTRY glUniform2iv (GLint location, GLsizei count, const GLint *value); -GL_APICALL void GL_APIENTRY glUniform3f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); -GL_APICALL void GL_APIENTRY glUniform3fv (GLint location, GLsizei count, const GLfloat *value); -GL_APICALL void GL_APIENTRY glUniform3i (GLint location, GLint v0, GLint v1, GLint v2); -GL_APICALL void GL_APIENTRY glUniform3iv (GLint location, GLsizei count, const GLint *value); -GL_APICALL void GL_APIENTRY glUniform4f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); -GL_APICALL void GL_APIENTRY glUniform4fv (GLint location, GLsizei count, const GLfloat *value); -GL_APICALL void GL_APIENTRY glUniform4i (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); -GL_APICALL void GL_APIENTRY glUniform4iv (GLint location, GLsizei count, const GLint *value); -GL_APICALL void GL_APIENTRY glUniformMatrix2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glUniformMatrix3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glUseProgram (GLuint program); -GL_APICALL void GL_APIENTRY glValidateProgram (GLuint program); -GL_APICALL void GL_APIENTRY glVertexAttrib1f (GLuint index, GLfloat x); -GL_APICALL void GL_APIENTRY glVertexAttrib1fv (GLuint index, const GLfloat *v); -GL_APICALL void GL_APIENTRY glVertexAttrib2f (GLuint index, GLfloat x, GLfloat y); -GL_APICALL void GL_APIENTRY glVertexAttrib2fv (GLuint index, const GLfloat *v); -GL_APICALL void GL_APIENTRY glVertexAttrib3f (GLuint index, GLfloat x, GLfloat y, GLfloat z); -GL_APICALL void GL_APIENTRY glVertexAttrib3fv (GLuint index, const GLfloat *v); -GL_APICALL void GL_APIENTRY glVertexAttrib4f (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); -GL_APICALL void GL_APIENTRY glVertexAttrib4fv (GLuint index, const GLfloat *v); -GL_APICALL void GL_APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); -GL_APICALL void GL_APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height); -#endif -#endif /* GL_ES_VERSION_2_0 */ - -#ifndef GL_ES_VERSION_3_0 -#define GL_ES_VERSION_3_0 1 -typedef unsigned short GLhalf; -#define GL_READ_BUFFER 0x0C02 -#define GL_UNPACK_ROW_LENGTH 0x0CF2 -#define GL_UNPACK_SKIP_ROWS 0x0CF3 -#define GL_UNPACK_SKIP_PIXELS 0x0CF4 -#define GL_PACK_ROW_LENGTH 0x0D02 -#define GL_PACK_SKIP_ROWS 0x0D03 -#define GL_PACK_SKIP_PIXELS 0x0D04 -#define GL_COLOR 0x1800 -#define GL_DEPTH 0x1801 -#define GL_STENCIL 0x1802 -#define GL_RED 0x1903 -#define GL_RGB8 0x8051 -#define GL_RGBA8 0x8058 -#define GL_RGB10_A2 0x8059 -#define GL_TEXTURE_BINDING_3D 0x806A -#define GL_UNPACK_SKIP_IMAGES 0x806D -#define GL_UNPACK_IMAGE_HEIGHT 0x806E -#define GL_TEXTURE_3D 0x806F -#define GL_TEXTURE_WRAP_R 0x8072 -#define GL_MAX_3D_TEXTURE_SIZE 0x8073 -#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 -#define GL_MAX_ELEMENTS_VERTICES 0x80E8 -#define GL_MAX_ELEMENTS_INDICES 0x80E9 -#define GL_TEXTURE_MIN_LOD 0x813A -#define GL_TEXTURE_MAX_LOD 0x813B -#define GL_TEXTURE_BASE_LEVEL 0x813C -#define GL_TEXTURE_MAX_LEVEL 0x813D -#define GL_MIN 0x8007 -#define GL_MAX 0x8008 -#define GL_DEPTH_COMPONENT24 0x81A6 -#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD -#define GL_TEXTURE_COMPARE_MODE 0x884C -#define GL_TEXTURE_COMPARE_FUNC 0x884D -#define GL_CURRENT_QUERY 0x8865 -#define GL_QUERY_RESULT 0x8866 -#define GL_QUERY_RESULT_AVAILABLE 0x8867 -#define GL_BUFFER_MAPPED 0x88BC -#define GL_BUFFER_MAP_POINTER 0x88BD -#define GL_STREAM_READ 0x88E1 -#define GL_STREAM_COPY 0x88E2 -#define GL_STATIC_READ 0x88E5 -#define GL_STATIC_COPY 0x88E6 -#define GL_DYNAMIC_READ 0x88E9 -#define GL_DYNAMIC_COPY 0x88EA -#define GL_MAX_DRAW_BUFFERS 0x8824 -#define GL_DRAW_BUFFER0 0x8825 -#define GL_DRAW_BUFFER1 0x8826 -#define GL_DRAW_BUFFER2 0x8827 -#define GL_DRAW_BUFFER3 0x8828 -#define GL_DRAW_BUFFER4 0x8829 -#define GL_DRAW_BUFFER5 0x882A -#define GL_DRAW_BUFFER6 0x882B -#define GL_DRAW_BUFFER7 0x882C -#define GL_DRAW_BUFFER8 0x882D -#define GL_DRAW_BUFFER9 0x882E -#define GL_DRAW_BUFFER10 0x882F -#define GL_DRAW_BUFFER11 0x8830 -#define GL_DRAW_BUFFER12 0x8831 -#define GL_DRAW_BUFFER13 0x8832 -#define GL_DRAW_BUFFER14 0x8833 -#define GL_DRAW_BUFFER15 0x8834 -#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 -#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A -#define GL_SAMPLER_3D 0x8B5F -#define GL_SAMPLER_2D_SHADOW 0x8B62 -#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B -#define GL_PIXEL_PACK_BUFFER 0x88EB -#define GL_PIXEL_UNPACK_BUFFER 0x88EC -#define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED -#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF -#define GL_FLOAT_MAT2x3 0x8B65 -#define GL_FLOAT_MAT2x4 0x8B66 -#define GL_FLOAT_MAT3x2 0x8B67 -#define GL_FLOAT_MAT3x4 0x8B68 -#define GL_FLOAT_MAT4x2 0x8B69 -#define GL_FLOAT_MAT4x3 0x8B6A -#define GL_SRGB 0x8C40 -#define GL_SRGB8 0x8C41 -#define GL_SRGB8_ALPHA8 0x8C43 -#define GL_COMPARE_REF_TO_TEXTURE 0x884E -#define GL_MAJOR_VERSION 0x821B -#define GL_MINOR_VERSION 0x821C -#define GL_NUM_EXTENSIONS 0x821D -#define GL_RGBA32F 0x8814 -#define GL_RGB32F 0x8815 -#define GL_RGBA16F 0x881A -#define GL_RGB16F 0x881B -#define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD -#define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF -#define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 -#define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 -#define GL_MAX_VARYING_COMPONENTS 0x8B4B -#define GL_TEXTURE_2D_ARRAY 0x8C1A -#define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D -#define GL_R11F_G11F_B10F 0x8C3A -#define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B -#define GL_RGB9_E5 0x8C3D -#define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E -#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 -#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F -#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 -#define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 -#define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 -#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 -#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 -#define GL_RASTERIZER_DISCARD 0x8C89 -#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A -#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B -#define GL_INTERLEAVED_ATTRIBS 0x8C8C -#define GL_SEPARATE_ATTRIBS 0x8C8D -#define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E -#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F -#define GL_RGBA32UI 0x8D70 -#define GL_RGB32UI 0x8D71 -#define GL_RGBA16UI 0x8D76 -#define GL_RGB16UI 0x8D77 -#define GL_RGBA8UI 0x8D7C -#define GL_RGB8UI 0x8D7D -#define GL_RGBA32I 0x8D82 -#define GL_RGB32I 0x8D83 -#define GL_RGBA16I 0x8D88 -#define GL_RGB16I 0x8D89 -#define GL_RGBA8I 0x8D8E -#define GL_RGB8I 0x8D8F -#define GL_RED_INTEGER 0x8D94 -#define GL_RGB_INTEGER 0x8D98 -#define GL_RGBA_INTEGER 0x8D99 -#define GL_SAMPLER_2D_ARRAY 0x8DC1 -#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 -#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 -#define GL_UNSIGNED_INT_VEC2 0x8DC6 -#define GL_UNSIGNED_INT_VEC3 0x8DC7 -#define GL_UNSIGNED_INT_VEC4 0x8DC8 -#define GL_INT_SAMPLER_2D 0x8DCA -#define GL_INT_SAMPLER_3D 0x8DCB -#define GL_INT_SAMPLER_CUBE 0x8DCC -#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF -#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 -#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 -#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 -#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 -#define GL_BUFFER_ACCESS_FLAGS 0x911F -#define GL_BUFFER_MAP_LENGTH 0x9120 -#define GL_BUFFER_MAP_OFFSET 0x9121 -#define GL_DEPTH_COMPONENT32F 0x8CAC -#define GL_DEPTH32F_STENCIL8 0x8CAD -#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD -#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 -#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 -#define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 -#define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 -#define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 -#define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 -#define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 -#define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 -#define GL_FRAMEBUFFER_DEFAULT 0x8218 -#define GL_FRAMEBUFFER_UNDEFINED 0x8219 -#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A -#define GL_DEPTH_STENCIL 0x84F9 -#define GL_UNSIGNED_INT_24_8 0x84FA -#define GL_DEPTH24_STENCIL8 0x88F0 -#define GL_UNSIGNED_NORMALIZED 0x8C17 -#define GL_DRAW_FRAMEBUFFER_BINDING 0x8CA6 -#define GL_READ_FRAMEBUFFER 0x8CA8 -#define GL_DRAW_FRAMEBUFFER 0x8CA9 -#define GL_READ_FRAMEBUFFER_BINDING 0x8CAA -#define GL_RENDERBUFFER_SAMPLES 0x8CAB -#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 -#define GL_MAX_COLOR_ATTACHMENTS 0x8CDF -#define GL_COLOR_ATTACHMENT1 0x8CE1 -#define GL_COLOR_ATTACHMENT2 0x8CE2 -#define GL_COLOR_ATTACHMENT3 0x8CE3 -#define GL_COLOR_ATTACHMENT4 0x8CE4 -#define GL_COLOR_ATTACHMENT5 0x8CE5 -#define GL_COLOR_ATTACHMENT6 0x8CE6 -#define GL_COLOR_ATTACHMENT7 0x8CE7 -#define GL_COLOR_ATTACHMENT8 0x8CE8 -#define GL_COLOR_ATTACHMENT9 0x8CE9 -#define GL_COLOR_ATTACHMENT10 0x8CEA -#define GL_COLOR_ATTACHMENT11 0x8CEB -#define GL_COLOR_ATTACHMENT12 0x8CEC -#define GL_COLOR_ATTACHMENT13 0x8CED -#define GL_COLOR_ATTACHMENT14 0x8CEE -#define GL_COLOR_ATTACHMENT15 0x8CEF -#define GL_COLOR_ATTACHMENT16 0x8CF0 -#define GL_COLOR_ATTACHMENT17 0x8CF1 -#define GL_COLOR_ATTACHMENT18 0x8CF2 -#define GL_COLOR_ATTACHMENT19 0x8CF3 -#define GL_COLOR_ATTACHMENT20 0x8CF4 -#define GL_COLOR_ATTACHMENT21 0x8CF5 -#define GL_COLOR_ATTACHMENT22 0x8CF6 -#define GL_COLOR_ATTACHMENT23 0x8CF7 -#define GL_COLOR_ATTACHMENT24 0x8CF8 -#define GL_COLOR_ATTACHMENT25 0x8CF9 -#define GL_COLOR_ATTACHMENT26 0x8CFA -#define GL_COLOR_ATTACHMENT27 0x8CFB -#define GL_COLOR_ATTACHMENT28 0x8CFC -#define GL_COLOR_ATTACHMENT29 0x8CFD -#define GL_COLOR_ATTACHMENT30 0x8CFE -#define GL_COLOR_ATTACHMENT31 0x8CFF -#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 -#define GL_MAX_SAMPLES 0x8D57 -#define GL_HALF_FLOAT 0x140B -#define GL_MAP_READ_BIT 0x0001 -#define GL_MAP_WRITE_BIT 0x0002 -#define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 -#define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 -#define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 -#define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 -#define GL_RG 0x8227 -#define GL_RG_INTEGER 0x8228 -#define GL_R8 0x8229 -#define GL_RG8 0x822B -#define GL_R16F 0x822D -#define GL_R32F 0x822E -#define GL_RG16F 0x822F -#define GL_RG32F 0x8230 -#define GL_R8I 0x8231 -#define GL_R8UI 0x8232 -#define GL_R16I 0x8233 -#define GL_R16UI 0x8234 -#define GL_R32I 0x8235 -#define GL_R32UI 0x8236 -#define GL_RG8I 0x8237 -#define GL_RG8UI 0x8238 -#define GL_RG16I 0x8239 -#define GL_RG16UI 0x823A -#define GL_RG32I 0x823B -#define GL_RG32UI 0x823C -#define GL_VERTEX_ARRAY_BINDING 0x85B5 -#define GL_R8_SNORM 0x8F94 -#define GL_RG8_SNORM 0x8F95 -#define GL_RGB8_SNORM 0x8F96 -#define GL_RGBA8_SNORM 0x8F97 -#define GL_SIGNED_NORMALIZED 0x8F9C -#define GL_PRIMITIVE_RESTART_FIXED_INDEX 0x8D69 -#define GL_COPY_READ_BUFFER 0x8F36 -#define GL_COPY_WRITE_BUFFER 0x8F37 -#define GL_COPY_READ_BUFFER_BINDING 0x8F36 -#define GL_COPY_WRITE_BUFFER_BINDING 0x8F37 -#define GL_UNIFORM_BUFFER 0x8A11 -#define GL_UNIFORM_BUFFER_BINDING 0x8A28 -#define GL_UNIFORM_BUFFER_START 0x8A29 -#define GL_UNIFORM_BUFFER_SIZE 0x8A2A -#define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B -#define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D -#define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E -#define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F -#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 -#define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 -#define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 -#define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 -#define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 -#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 -#define GL_UNIFORM_TYPE 0x8A37 -#define GL_UNIFORM_SIZE 0x8A38 -#define GL_UNIFORM_NAME_LENGTH 0x8A39 -#define GL_UNIFORM_BLOCK_INDEX 0x8A3A -#define GL_UNIFORM_OFFSET 0x8A3B -#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C -#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D -#define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E -#define GL_UNIFORM_BLOCK_BINDING 0x8A3F -#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 -#define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 -#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 -#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 -#define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 -#define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 -#define GL_INVALID_INDEX 0xFFFFFFFFu -#define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122 -#define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125 -#define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111 -#define GL_OBJECT_TYPE 0x9112 -#define GL_SYNC_CONDITION 0x9113 -#define GL_SYNC_STATUS 0x9114 -#define GL_SYNC_FLAGS 0x9115 -#define GL_SYNC_FENCE 0x9116 -#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 -#define GL_UNSIGNALED 0x9118 -#define GL_SIGNALED 0x9119 -#define GL_ALREADY_SIGNALED 0x911A -#define GL_TIMEOUT_EXPIRED 0x911B -#define GL_CONDITION_SATISFIED 0x911C -#define GL_WAIT_FAILED 0x911D -#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 -#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull -#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE -#define GL_ANY_SAMPLES_PASSED 0x8C2F -#define GL_ANY_SAMPLES_PASSED_CONSERVATIVE 0x8D6A -#define GL_SAMPLER_BINDING 0x8919 -#define GL_RGB10_A2UI 0x906F -#define GL_TEXTURE_SWIZZLE_R 0x8E42 -#define GL_TEXTURE_SWIZZLE_G 0x8E43 -#define GL_TEXTURE_SWIZZLE_B 0x8E44 -#define GL_TEXTURE_SWIZZLE_A 0x8E45 -#define GL_GREEN 0x1904 -#define GL_BLUE 0x1905 -#define GL_INT_2_10_10_10_REV 0x8D9F -#define GL_TRANSFORM_FEEDBACK 0x8E22 -#define GL_TRANSFORM_FEEDBACK_PAUSED 0x8E23 -#define GL_TRANSFORM_FEEDBACK_ACTIVE 0x8E24 -#define GL_TRANSFORM_FEEDBACK_BINDING 0x8E25 -#define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 0x8257 -#define GL_PROGRAM_BINARY_LENGTH 0x8741 -#define GL_NUM_PROGRAM_BINARY_FORMATS 0x87FE -#define GL_PROGRAM_BINARY_FORMATS 0x87FF -#define GL_COMPRESSED_R11_EAC 0x9270 -#define GL_COMPRESSED_SIGNED_R11_EAC 0x9271 -#define GL_COMPRESSED_RG11_EAC 0x9272 -#define GL_COMPRESSED_SIGNED_RG11_EAC 0x9273 -#define GL_COMPRESSED_RGB8_ETC2 0x9274 -#define GL_COMPRESSED_SRGB8_ETC2 0x9275 -#define GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276 -#define GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9277 -#define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 -#define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279 -#define GL_TEXTURE_IMMUTABLE_FORMAT 0x912F -#define GL_MAX_ELEMENT_INDEX 0x8D6B -#define GL_NUM_SAMPLE_COUNTS 0x9380 -#define GL_TEXTURE_IMMUTABLE_LEVELS 0x82DF -typedef void (GL_APIENTRYP PFNGLREADBUFFERPROC) (GLenum src); -typedef void (GL_APIENTRYP PFNGLDRAWRANGEELEMENTSPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); -typedef void (GL_APIENTRYP PFNGLTEXIMAGE3DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); -typedef void (GL_APIENTRYP PFNGLTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); -typedef void (GL_APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); -typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); -typedef void (GL_APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); -typedef void (GL_APIENTRYP PFNGLGENQUERIESPROC) (GLsizei n, GLuint *ids); -typedef void (GL_APIENTRYP PFNGLDELETEQUERIESPROC) (GLsizei n, const GLuint *ids); -typedef GLboolean (GL_APIENTRYP PFNGLISQUERYPROC) (GLuint id); -typedef void (GL_APIENTRYP PFNGLBEGINQUERYPROC) (GLenum target, GLuint id); -typedef void (GL_APIENTRYP PFNGLENDQUERYPROC) (GLenum target); -typedef void (GL_APIENTRYP PFNGLGETQUERYIVPROC) (GLenum target, GLenum pname, GLint *params); -typedef void (GL_APIENTRYP PFNGLGETQUERYOBJECTUIVPROC) (GLuint id, GLenum pname, GLuint *params); -typedef GLboolean (GL_APIENTRYP PFNGLUNMAPBUFFERPROC) (GLenum target); -typedef void (GL_APIENTRYP PFNGLGETBUFFERPOINTERVPROC) (GLenum target, GLenum pname, void **params); -typedef void (GL_APIENTRYP PFNGLDRAWBUFFERSPROC) (GLsizei n, const GLenum *bufs); -typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX2X3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX3X2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX2X4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX4X2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX3X4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLUNIFORMMATRIX4X3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLBLITFRAMEBUFFERPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); -typedef void (GL_APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -typedef void (GL_APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); -typedef void *(GL_APIENTRYP PFNGLMAPBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); -typedef void (GL_APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length); -typedef void (GL_APIENTRYP PFNGLBINDVERTEXARRAYPROC) (GLuint array); -typedef void (GL_APIENTRYP PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint *arrays); -typedef void (GL_APIENTRYP PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays); -typedef GLboolean (GL_APIENTRYP PFNGLISVERTEXARRAYPROC) (GLuint array); -typedef void (GL_APIENTRYP PFNGLGETINTEGERI_VPROC) (GLenum target, GLuint index, GLint *data); -typedef void (GL_APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKPROC) (GLenum primitiveMode); -typedef void (GL_APIENTRYP PFNGLENDTRANSFORMFEEDBACKPROC) (void); -typedef void (GL_APIENTRYP PFNGLBINDBUFFERRANGEPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); -typedef void (GL_APIENTRYP PFNGLBINDBUFFERBASEPROC) (GLenum target, GLuint index, GLuint buffer); -typedef void (GL_APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSPROC) (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); -typedef void (GL_APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); -typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBIPOINTERPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); -typedef void (GL_APIENTRYP PFNGLGETVERTEXATTRIBIIVPROC) (GLuint index, GLenum pname, GLint *params); -typedef void (GL_APIENTRYP PFNGLGETVERTEXATTRIBIUIVPROC) (GLuint index, GLenum pname, GLuint *params); -typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBI4IPROC) (GLuint index, GLint x, GLint y, GLint z, GLint w); -typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBI4UIPROC) (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); -typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBI4IVPROC) (GLuint index, const GLint *v); -typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBI4UIVPROC) (GLuint index, const GLuint *v); -typedef void (GL_APIENTRYP PFNGLGETUNIFORMUIVPROC) (GLuint program, GLint location, GLuint *params); -typedef GLint (GL_APIENTRYP PFNGLGETFRAGDATALOCATIONPROC) (GLuint program, const GLchar *name); -typedef void (GL_APIENTRYP PFNGLUNIFORM1UIPROC) (GLint location, GLuint v0); -typedef void (GL_APIENTRYP PFNGLUNIFORM2UIPROC) (GLint location, GLuint v0, GLuint v1); -typedef void (GL_APIENTRYP PFNGLUNIFORM3UIPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2); -typedef void (GL_APIENTRYP PFNGLUNIFORM4UIPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); -typedef void (GL_APIENTRYP PFNGLUNIFORM1UIVPROC) (GLint location, GLsizei count, const GLuint *value); -typedef void (GL_APIENTRYP PFNGLUNIFORM2UIVPROC) (GLint location, GLsizei count, const GLuint *value); -typedef void (GL_APIENTRYP PFNGLUNIFORM3UIVPROC) (GLint location, GLsizei count, const GLuint *value); -typedef void (GL_APIENTRYP PFNGLUNIFORM4UIVPROC) (GLint location, GLsizei count, const GLuint *value); -typedef void (GL_APIENTRYP PFNGLCLEARBUFFERIVPROC) (GLenum buffer, GLint drawbuffer, const GLint *value); -typedef void (GL_APIENTRYP PFNGLCLEARBUFFERUIVPROC) (GLenum buffer, GLint drawbuffer, const GLuint *value); -typedef void (GL_APIENTRYP PFNGLCLEARBUFFERFVPROC) (GLenum buffer, GLint drawbuffer, const GLfloat *value); -typedef void (GL_APIENTRYP PFNGLCLEARBUFFERFIPROC) (GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); -typedef const GLubyte *(GL_APIENTRYP PFNGLGETSTRINGIPROC) (GLenum name, GLuint index); -typedef void (GL_APIENTRYP PFNGLCOPYBUFFERSUBDATAPROC) (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); -typedef void (GL_APIENTRYP PFNGLGETUNIFORMINDICESPROC) (GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices); -typedef void (GL_APIENTRYP PFNGLGETACTIVEUNIFORMSIVPROC) (GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); -typedef GLuint (GL_APIENTRYP PFNGLGETUNIFORMBLOCKINDEXPROC) (GLuint program, const GLchar *uniformBlockName); -typedef void (GL_APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKIVPROC) (GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); -typedef void (GL_APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC) (GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); -typedef void (GL_APIENTRYP PFNGLUNIFORMBLOCKBINDINGPROC) (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); -typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINSTANCEDPROC) (GLenum mode, GLint first, GLsizei count, GLsizei instancecount); -typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount); -typedef GLsync (GL_APIENTRYP PFNGLFENCESYNCPROC) (GLenum condition, GLbitfield flags); -typedef GLboolean (GL_APIENTRYP PFNGLISSYNCPROC) (GLsync sync); -typedef void (GL_APIENTRYP PFNGLDELETESYNCPROC) (GLsync sync); -typedef GLenum (GL_APIENTRYP PFNGLCLIENTWAITSYNCPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout); -typedef void (GL_APIENTRYP PFNGLWAITSYNCPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout); -typedef void (GL_APIENTRYP PFNGLGETINTEGER64VPROC) (GLenum pname, GLint64 *data); -typedef void (GL_APIENTRYP PFNGLGETSYNCIVPROC) (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); -typedef void (GL_APIENTRYP PFNGLGETINTEGER64I_VPROC) (GLenum target, GLuint index, GLint64 *data); -typedef void (GL_APIENTRYP PFNGLGETBUFFERPARAMETERI64VPROC) (GLenum target, GLenum pname, GLint64 *params); -typedef void (GL_APIENTRYP PFNGLGENSAMPLERSPROC) (GLsizei count, GLuint *samplers); -typedef void (GL_APIENTRYP PFNGLDELETESAMPLERSPROC) (GLsizei count, const GLuint *samplers); -typedef GLboolean (GL_APIENTRYP PFNGLISSAMPLERPROC) (GLuint sampler); -typedef void (GL_APIENTRYP PFNGLBINDSAMPLERPROC) (GLuint unit, GLuint sampler); -typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERIPROC) (GLuint sampler, GLenum pname, GLint param); -typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERIVPROC) (GLuint sampler, GLenum pname, const GLint *param); -typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERFPROC) (GLuint sampler, GLenum pname, GLfloat param); -typedef void (GL_APIENTRYP PFNGLSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum pname, const GLfloat *param); -typedef void (GL_APIENTRYP PFNGLGETSAMPLERPARAMETERIVPROC) (GLuint sampler, GLenum pname, GLint *params); -typedef void (GL_APIENTRYP PFNGLGETSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum pname, GLfloat *params); -typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBDIVISORPROC) (GLuint index, GLuint divisor); -typedef void (GL_APIENTRYP PFNGLBINDTRANSFORMFEEDBACKPROC) (GLenum target, GLuint id); -typedef void (GL_APIENTRYP PFNGLDELETETRANSFORMFEEDBACKSPROC) (GLsizei n, const GLuint *ids); -typedef void (GL_APIENTRYP PFNGLGENTRANSFORMFEEDBACKSPROC) (GLsizei n, GLuint *ids); -typedef GLboolean (GL_APIENTRYP PFNGLISTRANSFORMFEEDBACKPROC) (GLuint id); -typedef void (GL_APIENTRYP PFNGLPAUSETRANSFORMFEEDBACKPROC) (void); -typedef void (GL_APIENTRYP PFNGLRESUMETRANSFORMFEEDBACKPROC) (void); -typedef void (GL_APIENTRYP PFNGLGETPROGRAMBINARYPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); -typedef void (GL_APIENTRYP PFNGLPROGRAMBINARYPROC) (GLuint program, GLenum binaryFormat, const void *binary, GLsizei length); -typedef void (GL_APIENTRYP PFNGLPROGRAMPARAMETERIPROC) (GLuint program, GLenum pname, GLint value); -typedef void (GL_APIENTRYP PFNGLINVALIDATEFRAMEBUFFERPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments); -typedef void (GL_APIENTRYP PFNGLINVALIDATESUBFRAMEBUFFERPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); -typedef void (GL_APIENTRYP PFNGLTEXSTORAGE2DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); -typedef void (GL_APIENTRYP PFNGLTEXSTORAGE3DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); -typedef void (GL_APIENTRYP PFNGLGETINTERNALFORMATIVPROC) (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params); -#if GL_GLES_PROTOTYPES -GL_APICALL void GL_APIENTRY glReadBuffer (GLenum src); -GL_APICALL void GL_APIENTRY glDrawRangeElements (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); -GL_APICALL void GL_APIENTRY glTexImage3D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); -GL_APICALL void GL_APIENTRY glTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); -GL_APICALL void GL_APIENTRY glCopyTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); -GL_APICALL void GL_APIENTRY glCompressedTexImage3D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); -GL_APICALL void GL_APIENTRY glCompressedTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); -GL_APICALL void GL_APIENTRY glGenQueries (GLsizei n, GLuint *ids); -GL_APICALL void GL_APIENTRY glDeleteQueries (GLsizei n, const GLuint *ids); -GL_APICALL GLboolean GL_APIENTRY glIsQuery (GLuint id); -GL_APICALL void GL_APIENTRY glBeginQuery (GLenum target, GLuint id); -GL_APICALL void GL_APIENTRY glEndQuery (GLenum target); -GL_APICALL void GL_APIENTRY glGetQueryiv (GLenum target, GLenum pname, GLint *params); -GL_APICALL void GL_APIENTRY glGetQueryObjectuiv (GLuint id, GLenum pname, GLuint *params); -GL_APICALL GLboolean GL_APIENTRY glUnmapBuffer (GLenum target); -GL_APICALL void GL_APIENTRY glGetBufferPointerv (GLenum target, GLenum pname, void **params); -GL_APICALL void GL_APIENTRY glDrawBuffers (GLsizei n, const GLenum *bufs); -GL_APICALL void GL_APIENTRY glUniformMatrix2x3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glUniformMatrix3x2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glUniformMatrix2x4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glUniformMatrix4x2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glUniformMatrix3x4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glUniformMatrix4x3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); -GL_APICALL void GL_APIENTRY glBlitFramebuffer (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); -GL_APICALL void GL_APIENTRY glRenderbufferStorageMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); -GL_APICALL void GL_APIENTRY glFramebufferTextureLayer (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); -GL_APICALL void *GL_APIENTRY glMapBufferRange (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); -GL_APICALL void GL_APIENTRY glFlushMappedBufferRange (GLenum target, GLintptr offset, GLsizeiptr length); -GL_APICALL void GL_APIENTRY glBindVertexArray (GLuint array); -GL_APICALL void GL_APIENTRY glDeleteVertexArrays (GLsizei n, const GLuint *arrays); -GL_APICALL void GL_APIENTRY glGenVertexArrays (GLsizei n, GLuint *arrays); -GL_APICALL GLboolean GL_APIENTRY glIsVertexArray (GLuint array); -GL_APICALL void GL_APIENTRY glGetIntegeri_v (GLenum target, GLuint index, GLint *data); -GL_APICALL void GL_APIENTRY glBeginTransformFeedback (GLenum primitiveMode); -GL_APICALL void GL_APIENTRY glEndTransformFeedback (void); -GL_APICALL void GL_APIENTRY glBindBufferRange (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); -GL_APICALL void GL_APIENTRY glBindBufferBase (GLenum target, GLuint index, GLuint buffer); -GL_APICALL void GL_APIENTRY glTransformFeedbackVaryings (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); -GL_APICALL void GL_APIENTRY glGetTransformFeedbackVarying (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); -GL_APICALL void GL_APIENTRY glVertexAttribIPointer (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); -GL_APICALL void GL_APIENTRY glGetVertexAttribIiv (GLuint index, GLenum pname, GLint *params); -GL_APICALL void GL_APIENTRY glGetVertexAttribIuiv (GLuint index, GLenum pname, GLuint *params); -GL_APICALL void GL_APIENTRY glVertexAttribI4i (GLuint index, GLint x, GLint y, GLint z, GLint w); -GL_APICALL void GL_APIENTRY glVertexAttribI4ui (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); -GL_APICALL void GL_APIENTRY glVertexAttribI4iv (GLuint index, const GLint *v); -GL_APICALL void GL_APIENTRY glVertexAttribI4uiv (GLuint index, const GLuint *v); -GL_APICALL void GL_APIENTRY glGetUniformuiv (GLuint program, GLint location, GLuint *params); -GL_APICALL GLint GL_APIENTRY glGetFragDataLocation (GLuint program, const GLchar *name); -GL_APICALL void GL_APIENTRY glUniform1ui (GLint location, GLuint v0); -GL_APICALL void GL_APIENTRY glUniform2ui (GLint location, GLuint v0, GLuint v1); -GL_APICALL void GL_APIENTRY glUniform3ui (GLint location, GLuint v0, GLuint v1, GLuint v2); -GL_APICALL void GL_APIENTRY glUniform4ui (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); -GL_APICALL void GL_APIENTRY glUniform1uiv (GLint location, GLsizei count, const GLuint *value); -GL_APICALL void GL_APIENTRY glUniform2uiv (GLint location, GLsizei count, const GLuint *value); -GL_APICALL void GL_APIENTRY glUniform3uiv (GLint location, GLsizei count, const GLuint *value); -GL_APICALL void GL_APIENTRY glUniform4uiv (GLint location, GLsizei count, const GLuint *value); -GL_APICALL void GL_APIENTRY glClearBufferiv (GLenum buffer, GLint drawbuffer, const GLint *value); -GL_APICALL void GL_APIENTRY glClearBufferuiv (GLenum buffer, GLint drawbuffer, const GLuint *value); -GL_APICALL void GL_APIENTRY glClearBufferfv (GLenum buffer, GLint drawbuffer, const GLfloat *value); -GL_APICALL void GL_APIENTRY glClearBufferfi (GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); -GL_APICALL const GLubyte *GL_APIENTRY glGetStringi (GLenum name, GLuint index); -GL_APICALL void GL_APIENTRY glCopyBufferSubData (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); -GL_APICALL void GL_APIENTRY glGetUniformIndices (GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices); -GL_APICALL void GL_APIENTRY glGetActiveUniformsiv (GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); -GL_APICALL GLuint GL_APIENTRY glGetUniformBlockIndex (GLuint program, const GLchar *uniformBlockName); -GL_APICALL void GL_APIENTRY glGetActiveUniformBlockiv (GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); -GL_APICALL void GL_APIENTRY glGetActiveUniformBlockName (GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); -GL_APICALL void GL_APIENTRY glUniformBlockBinding (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); -GL_APICALL void GL_APIENTRY glDrawArraysInstanced (GLenum mode, GLint first, GLsizei count, GLsizei instancecount); -GL_APICALL void GL_APIENTRY glDrawElementsInstanced (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount); -GL_APICALL GLsync GL_APIENTRY glFenceSync (GLenum condition, GLbitfield flags); -GL_APICALL GLboolean GL_APIENTRY glIsSync (GLsync sync); -GL_APICALL void GL_APIENTRY glDeleteSync (GLsync sync); -GL_APICALL GLenum GL_APIENTRY glClientWaitSync (GLsync sync, GLbitfield flags, GLuint64 timeout); -GL_APICALL void GL_APIENTRY glWaitSync (GLsync sync, GLbitfield flags, GLuint64 timeout); -GL_APICALL void GL_APIENTRY glGetInteger64v (GLenum pname, GLint64 *data); -GL_APICALL void GL_APIENTRY glGetSynciv (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); -GL_APICALL void GL_APIENTRY glGetInteger64i_v (GLenum target, GLuint index, GLint64 *data); -GL_APICALL void GL_APIENTRY glGetBufferParameteri64v (GLenum target, GLenum pname, GLint64 *params); -GL_APICALL void GL_APIENTRY glGenSamplers (GLsizei count, GLuint *samplers); -GL_APICALL void GL_APIENTRY glDeleteSamplers (GLsizei count, const GLuint *samplers); -GL_APICALL GLboolean GL_APIENTRY glIsSampler (GLuint sampler); -GL_APICALL void GL_APIENTRY glBindSampler (GLuint unit, GLuint sampler); -GL_APICALL void GL_APIENTRY glSamplerParameteri (GLuint sampler, GLenum pname, GLint param); -GL_APICALL void GL_APIENTRY glSamplerParameteriv (GLuint sampler, GLenum pname, const GLint *param); -GL_APICALL void GL_APIENTRY glSamplerParameterf (GLuint sampler, GLenum pname, GLfloat param); -GL_APICALL void GL_APIENTRY glSamplerParameterfv (GLuint sampler, GLenum pname, const GLfloat *param); -GL_APICALL void GL_APIENTRY glGetSamplerParameteriv (GLuint sampler, GLenum pname, GLint *params); -GL_APICALL void GL_APIENTRY glGetSamplerParameterfv (GLuint sampler, GLenum pname, GLfloat *params); -GL_APICALL void GL_APIENTRY glVertexAttribDivisor (GLuint index, GLuint divisor); -GL_APICALL void GL_APIENTRY glBindTransformFeedback (GLenum target, GLuint id); -GL_APICALL void GL_APIENTRY glDeleteTransformFeedbacks (GLsizei n, const GLuint *ids); -GL_APICALL void GL_APIENTRY glGenTransformFeedbacks (GLsizei n, GLuint *ids); -GL_APICALL GLboolean GL_APIENTRY glIsTransformFeedback (GLuint id); -GL_APICALL void GL_APIENTRY glPauseTransformFeedback (void); -GL_APICALL void GL_APIENTRY glResumeTransformFeedback (void); -GL_APICALL void GL_APIENTRY glGetProgramBinary (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); -GL_APICALL void GL_APIENTRY glProgramBinary (GLuint program, GLenum binaryFormat, const void *binary, GLsizei length); -GL_APICALL void GL_APIENTRY glProgramParameteri (GLuint program, GLenum pname, GLint value); -GL_APICALL void GL_APIENTRY glInvalidateFramebuffer (GLenum target, GLsizei numAttachments, const GLenum *attachments); -GL_APICALL void GL_APIENTRY glInvalidateSubFramebuffer (GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); -GL_APICALL void GL_APIENTRY glTexStorage2D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); -GL_APICALL void GL_APIENTRY glTexStorage3D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); -GL_APICALL void GL_APIENTRY glGetInternalformativ (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params); -#endif -#endif /* GL_ES_VERSION_3_0 */ - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/RenderSystems/GLES2/include/GLES3/gl3platform.h b/RenderSystems/GLES2/include/GLES3/gl3platform.h deleted file mode 100644 index 1bd1a850fa6..00000000000 --- a/RenderSystems/GLES2/include/GLES3/gl3platform.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef __gl3platform_h_ -#define __gl3platform_h_ - -/* $Revision: 18437 $ on $Date:: 2012-07-08 23:31:39 -0700 #$ */ - -/* - * This document is licensed under the SGI Free Software B License Version - * 2.0. For details, see http://oss.sgi.com/projects/FreeB/ . - */ - -/* Platform-specific types and definitions for OpenGL ES 3.X gl3.h - * - * Adopters may modify khrplatform.h and this file to suit their platform. - * You are encouraged to submit all modifications to the Khronos group so that - * they can be included in future versions of this file. Please submit changes - * by sending them to the public Khronos Bugzilla (http://khronos.org/bugzilla) - * by filing a bug against product "OpenGL-ES" component "Registry". - */ - -#include - -#ifndef GL_APICALL -#define GL_APICALL KHRONOS_APICALL -#endif - -#ifndef GL_APIENTRY -#define GL_APIENTRY KHRONOS_APIENTRY -#endif - -#endif /* __gl3platform_h_ */ diff --git a/RenderSystems/GLES2/include/GLES3/glesw.h b/RenderSystems/GLES2/include/GLES3/glesw.h deleted file mode 100644 index 93ec961d372..00000000000 --- a/RenderSystems/GLES2/include/GLES3/glesw.h +++ /dev/null @@ -1,1294 +0,0 @@ -/* - - This file was generated with glesw_gen.cmake, part of glXXw - (hosted at https://github.com/paroj/glXXw-cmake) - - This is free and unencumbered software released into the public domain. - - Anyone is free to copy, modify, publish, use, compile, sell, or - distribute this software, either in source code form or as a compiled - binary, for any purpose, commercial or non-commercial, and by any - means. - - In jurisdictions that recognize copyright laws, the author or authors - of this software dedicate any and all copyright interest in the - software to the public domain. We make this dedication for the benefit - of the public at large and to the detriment of our heirs and - successors. We intend this dedication to be an overt act of - relinquishment in perpetuity of all present and future rights to this - software under copyright law. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. - -*/ - -#ifndef __glesw_h_ -#define __glesw_h_ - -#include -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef void (*GLESWglProc)(void); -typedef GLESWglProc (*GLESWGetProcAddressProc)(const char *proc); - -/* glesw api */ -int gleswInit(void); -int gleswInit2(GLESWGetProcAddressProc proc); -int gleswIsSupported(int major, int minor); -GLESWglProc gleswGetProcAddress(const char *proc); - -/* OpenGL functions */ -extern PFNGLACTIVESHADERPROGRAMEXTPROC gleswActiveShaderProgramEXT; -extern PFNGLACTIVETEXTUREPROC gleswActiveTexture; -extern PFNGLALPHAFUNCQCOMPROC gleswAlphaFuncQCOM; -extern PFNGLAPPLYFRAMEBUFFERATTACHMENTCMAAINTELPROC gleswApplyFramebufferAttachmentCMAAINTEL; -extern PFNGLATTACHSHADERPROC gleswAttachShader; -extern PFNGLBEGINCONDITIONALRENDERNVPROC gleswBeginConditionalRenderNV; -extern PFNGLBEGINPERFMONITORAMDPROC gleswBeginPerfMonitorAMD; -extern PFNGLBEGINPERFQUERYINTELPROC gleswBeginPerfQueryINTEL; -extern PFNGLBEGINQUERYPROC gleswBeginQuery; -extern PFNGLBEGINQUERYEXTPROC gleswBeginQueryEXT; -extern PFNGLBEGINTRANSFORMFEEDBACKPROC gleswBeginTransformFeedback; -extern PFNGLBINDATTRIBLOCATIONPROC gleswBindAttribLocation; -extern PFNGLBINDBUFFERPROC gleswBindBuffer; -extern PFNGLBINDBUFFERBASEPROC gleswBindBufferBase; -extern PFNGLBINDBUFFERRANGEPROC gleswBindBufferRange; -extern PFNGLBINDFRAGDATALOCATIONEXTPROC gleswBindFragDataLocationEXT; -extern PFNGLBINDFRAGDATALOCATIONINDEXEDEXTPROC gleswBindFragDataLocationIndexedEXT; -extern PFNGLBINDFRAMEBUFFERPROC gleswBindFramebuffer; -extern PFNGLBINDPROGRAMPIPELINEEXTPROC gleswBindProgramPipelineEXT; -extern PFNGLBINDRENDERBUFFERPROC gleswBindRenderbuffer; -extern PFNGLBINDSAMPLERPROC gleswBindSampler; -extern PFNGLBINDTEXTUREPROC gleswBindTexture; -extern PFNGLBINDTRANSFORMFEEDBACKPROC gleswBindTransformFeedback; -extern PFNGLBINDVERTEXARRAYPROC gleswBindVertexArray; -extern PFNGLBINDVERTEXARRAYOESPROC gleswBindVertexArrayOES; -extern PFNGLBLENDBARRIERKHRPROC gleswBlendBarrierKHR; -extern PFNGLBLENDBARRIERNVPROC gleswBlendBarrierNV; -extern PFNGLBLENDCOLORPROC gleswBlendColor; -extern PFNGLBLENDEQUATIONPROC gleswBlendEquation; -extern PFNGLBLENDEQUATIONSEPARATEPROC gleswBlendEquationSeparate; -extern PFNGLBLENDEQUATIONSEPARATEIEXTPROC gleswBlendEquationSeparateiEXT; -extern PFNGLBLENDEQUATIONSEPARATEIOESPROC gleswBlendEquationSeparateiOES; -extern PFNGLBLENDEQUATIONIEXTPROC gleswBlendEquationiEXT; -extern PFNGLBLENDEQUATIONIOESPROC gleswBlendEquationiOES; -extern PFNGLBLENDFUNCPROC gleswBlendFunc; -extern PFNGLBLENDFUNCSEPARATEPROC gleswBlendFuncSeparate; -extern PFNGLBLENDFUNCSEPARATEIEXTPROC gleswBlendFuncSeparateiEXT; -extern PFNGLBLENDFUNCSEPARATEIOESPROC gleswBlendFuncSeparateiOES; -extern PFNGLBLENDFUNCIEXTPROC gleswBlendFunciEXT; -extern PFNGLBLENDFUNCIOESPROC gleswBlendFunciOES; -extern PFNGLBLENDPARAMETERINVPROC gleswBlendParameteriNV; -extern PFNGLBLITFRAMEBUFFERPROC gleswBlitFramebuffer; -extern PFNGLBLITFRAMEBUFFERANGLEPROC gleswBlitFramebufferANGLE; -extern PFNGLBLITFRAMEBUFFERNVPROC gleswBlitFramebufferNV; -extern PFNGLBUFFERDATAPROC gleswBufferData; -extern PFNGLBUFFERSTORAGEEXTPROC gleswBufferStorageEXT; -extern PFNGLBUFFERSUBDATAPROC gleswBufferSubData; -extern PFNGLCHECKFRAMEBUFFERSTATUSPROC gleswCheckFramebufferStatus; -extern PFNGLCLEARPROC gleswClear; -extern PFNGLCLEARBUFFERFIPROC gleswClearBufferfi; -extern PFNGLCLEARBUFFERFVPROC gleswClearBufferfv; -extern PFNGLCLEARBUFFERIVPROC gleswClearBufferiv; -extern PFNGLCLEARBUFFERUIVPROC gleswClearBufferuiv; -extern PFNGLCLEARCOLORPROC gleswClearColor; -extern PFNGLCLEARDEPTHFPROC gleswClearDepthf; -extern PFNGLCLEARPIXELLOCALSTORAGEUIEXTPROC gleswClearPixelLocalStorageuiEXT; -extern PFNGLCLEARSTENCILPROC gleswClearStencil; -extern PFNGLCLIENTWAITSYNCPROC gleswClientWaitSync; -extern PFNGLCLIENTWAITSYNCAPPLEPROC gleswClientWaitSyncAPPLE; -extern PFNGLCOLORMASKPROC gleswColorMask; -extern PFNGLCOLORMASKIEXTPROC gleswColorMaskiEXT; -extern PFNGLCOLORMASKIOESPROC gleswColorMaskiOES; -extern PFNGLCOMPILESHADERPROC gleswCompileShader; -extern PFNGLCOMPRESSEDTEXIMAGE2DPROC gleswCompressedTexImage2D; -extern PFNGLCOMPRESSEDTEXIMAGE3DPROC gleswCompressedTexImage3D; -extern PFNGLCOMPRESSEDTEXIMAGE3DOESPROC gleswCompressedTexImage3DOES; -extern PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC gleswCompressedTexSubImage2D; -extern PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC gleswCompressedTexSubImage3D; -extern PFNGLCOMPRESSEDTEXSUBIMAGE3DOESPROC gleswCompressedTexSubImage3DOES; -extern PFNGLCOPYBUFFERSUBDATAPROC gleswCopyBufferSubData; -extern PFNGLCOPYBUFFERSUBDATANVPROC gleswCopyBufferSubDataNV; -extern PFNGLCOPYIMAGESUBDATAEXTPROC gleswCopyImageSubDataEXT; -extern PFNGLCOPYIMAGESUBDATAOESPROC gleswCopyImageSubDataOES; -extern PFNGLCOPYPATHNVPROC gleswCopyPathNV; -extern PFNGLCOPYTEXIMAGE2DPROC gleswCopyTexImage2D; -extern PFNGLCOPYTEXSUBIMAGE2DPROC gleswCopyTexSubImage2D; -extern PFNGLCOPYTEXSUBIMAGE3DPROC gleswCopyTexSubImage3D; -extern PFNGLCOPYTEXSUBIMAGE3DOESPROC gleswCopyTexSubImage3DOES; -extern PFNGLCOPYTEXTURELEVELSAPPLEPROC gleswCopyTextureLevelsAPPLE; -extern PFNGLCOVERFILLPATHINSTANCEDNVPROC gleswCoverFillPathInstancedNV; -extern PFNGLCOVERFILLPATHNVPROC gleswCoverFillPathNV; -extern PFNGLCOVERSTROKEPATHINSTANCEDNVPROC gleswCoverStrokePathInstancedNV; -extern PFNGLCOVERSTROKEPATHNVPROC gleswCoverStrokePathNV; -extern PFNGLCOVERAGEMASKNVPROC gleswCoverageMaskNV; -extern PFNGLCOVERAGEMODULATIONNVPROC gleswCoverageModulationNV; -extern PFNGLCOVERAGEMODULATIONTABLENVPROC gleswCoverageModulationTableNV; -extern PFNGLCOVERAGEOPERATIONNVPROC gleswCoverageOperationNV; -extern PFNGLCREATEPERFQUERYINTELPROC gleswCreatePerfQueryINTEL; -extern PFNGLCREATEPROGRAMPROC gleswCreateProgram; -extern PFNGLCREATESHADERPROC gleswCreateShader; -extern PFNGLCREATESHADERPROGRAMVEXTPROC gleswCreateShaderProgramvEXT; -extern PFNGLCULLFACEPROC gleswCullFace; -extern PFNGLDEBUGMESSAGECALLBACKKHRPROC gleswDebugMessageCallbackKHR; -extern PFNGLDEBUGMESSAGECONTROLKHRPROC gleswDebugMessageControlKHR; -extern PFNGLDEBUGMESSAGEINSERTKHRPROC gleswDebugMessageInsertKHR; -extern PFNGLDELETEBUFFERSPROC gleswDeleteBuffers; -extern PFNGLDELETEFENCESNVPROC gleswDeleteFencesNV; -extern PFNGLDELETEFRAMEBUFFERSPROC gleswDeleteFramebuffers; -extern PFNGLDELETEPATHSNVPROC gleswDeletePathsNV; -extern PFNGLDELETEPERFMONITORSAMDPROC gleswDeletePerfMonitorsAMD; -extern PFNGLDELETEPERFQUERYINTELPROC gleswDeletePerfQueryINTEL; -extern PFNGLDELETEPROGRAMPROC gleswDeleteProgram; -extern PFNGLDELETEPROGRAMPIPELINESEXTPROC gleswDeleteProgramPipelinesEXT; -extern PFNGLDELETEQUERIESPROC gleswDeleteQueries; -extern PFNGLDELETEQUERIESEXTPROC gleswDeleteQueriesEXT; -extern PFNGLDELETERENDERBUFFERSPROC gleswDeleteRenderbuffers; -extern PFNGLDELETESAMPLERSPROC gleswDeleteSamplers; -extern PFNGLDELETESHADERPROC gleswDeleteShader; -extern PFNGLDELETESYNCPROC gleswDeleteSync; -extern PFNGLDELETESYNCAPPLEPROC gleswDeleteSyncAPPLE; -extern PFNGLDELETETEXTURESPROC gleswDeleteTextures; -extern PFNGLDELETETRANSFORMFEEDBACKSPROC gleswDeleteTransformFeedbacks; -extern PFNGLDELETEVERTEXARRAYSPROC gleswDeleteVertexArrays; -extern PFNGLDELETEVERTEXARRAYSOESPROC gleswDeleteVertexArraysOES; -extern PFNGLDEPTHFUNCPROC gleswDepthFunc; -extern PFNGLDEPTHMASKPROC gleswDepthMask; -extern PFNGLDEPTHRANGEARRAYFVNVPROC gleswDepthRangeArrayfvNV; -extern PFNGLDEPTHRANGEINDEXEDFNVPROC gleswDepthRangeIndexedfNV; -extern PFNGLDEPTHRANGEFPROC gleswDepthRangef; -extern PFNGLDETACHSHADERPROC gleswDetachShader; -extern PFNGLDISABLEPROC gleswDisable; -extern PFNGLDISABLEDRIVERCONTROLQCOMPROC gleswDisableDriverControlQCOM; -extern PFNGLDISABLEVERTEXATTRIBARRAYPROC gleswDisableVertexAttribArray; -extern PFNGLDISABLEIEXTPROC gleswDisableiEXT; -extern PFNGLDISABLEINVPROC gleswDisableiNV; -extern PFNGLDISABLEIOESPROC gleswDisableiOES; -extern PFNGLDISCARDFRAMEBUFFEREXTPROC gleswDiscardFramebufferEXT; -extern PFNGLDRAWARRAYSPROC gleswDrawArrays; -extern PFNGLDRAWARRAYSINSTANCEDPROC gleswDrawArraysInstanced; -extern PFNGLDRAWARRAYSINSTANCEDANGLEPROC gleswDrawArraysInstancedANGLE; -extern PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEEXTPROC gleswDrawArraysInstancedBaseInstanceEXT; -extern PFNGLDRAWARRAYSINSTANCEDEXTPROC gleswDrawArraysInstancedEXT; -extern PFNGLDRAWARRAYSINSTANCEDNVPROC gleswDrawArraysInstancedNV; -extern PFNGLDRAWBUFFERSPROC gleswDrawBuffers; -extern PFNGLDRAWBUFFERSEXTPROC gleswDrawBuffersEXT; -extern PFNGLDRAWBUFFERSINDEXEDEXTPROC gleswDrawBuffersIndexedEXT; -extern PFNGLDRAWBUFFERSNVPROC gleswDrawBuffersNV; -extern PFNGLDRAWELEMENTSPROC gleswDrawElements; -extern PFNGLDRAWELEMENTSBASEVERTEXEXTPROC gleswDrawElementsBaseVertexEXT; -extern PFNGLDRAWELEMENTSBASEVERTEXOESPROC gleswDrawElementsBaseVertexOES; -extern PFNGLDRAWELEMENTSINSTANCEDPROC gleswDrawElementsInstanced; -extern PFNGLDRAWELEMENTSINSTANCEDANGLEPROC gleswDrawElementsInstancedANGLE; -extern PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEEXTPROC gleswDrawElementsInstancedBaseInstanceEXT; -extern PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEEXTPROC gleswDrawElementsInstancedBaseVertexBaseInstanceEXT; -extern PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXEXTPROC gleswDrawElementsInstancedBaseVertexEXT; -extern PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXOESPROC gleswDrawElementsInstancedBaseVertexOES; -extern PFNGLDRAWELEMENTSINSTANCEDEXTPROC gleswDrawElementsInstancedEXT; -extern PFNGLDRAWELEMENTSINSTANCEDNVPROC gleswDrawElementsInstancedNV; -extern PFNGLDRAWRANGEELEMENTSPROC gleswDrawRangeElements; -extern PFNGLDRAWRANGEELEMENTSBASEVERTEXEXTPROC gleswDrawRangeElementsBaseVertexEXT; -extern PFNGLDRAWRANGEELEMENTSBASEVERTEXOESPROC gleswDrawRangeElementsBaseVertexOES; -extern PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC gleswEGLImageTargetRenderbufferStorageOES; -extern PFNGLEGLIMAGETARGETTEXTURE2DOESPROC gleswEGLImageTargetTexture2DOES; -extern PFNGLENABLEPROC gleswEnable; -extern PFNGLENABLEDRIVERCONTROLQCOMPROC gleswEnableDriverControlQCOM; -extern PFNGLENABLEVERTEXATTRIBARRAYPROC gleswEnableVertexAttribArray; -extern PFNGLENABLEIEXTPROC gleswEnableiEXT; -extern PFNGLENABLEINVPROC gleswEnableiNV; -extern PFNGLENABLEIOESPROC gleswEnableiOES; -extern PFNGLENDCONDITIONALRENDERNVPROC gleswEndConditionalRenderNV; -extern PFNGLENDPERFMONITORAMDPROC gleswEndPerfMonitorAMD; -extern PFNGLENDPERFQUERYINTELPROC gleswEndPerfQueryINTEL; -extern PFNGLENDQUERYPROC gleswEndQuery; -extern PFNGLENDQUERYEXTPROC gleswEndQueryEXT; -extern PFNGLENDTILINGQCOMPROC gleswEndTilingQCOM; -extern PFNGLENDTRANSFORMFEEDBACKPROC gleswEndTransformFeedback; -extern PFNGLEXTGETBUFFERPOINTERVQCOMPROC gleswExtGetBufferPointervQCOM; -extern PFNGLEXTGETBUFFERSQCOMPROC gleswExtGetBuffersQCOM; -extern PFNGLEXTGETFRAMEBUFFERSQCOMPROC gleswExtGetFramebuffersQCOM; -extern PFNGLEXTGETPROGRAMBINARYSOURCEQCOMPROC gleswExtGetProgramBinarySourceQCOM; -extern PFNGLEXTGETPROGRAMSQCOMPROC gleswExtGetProgramsQCOM; -extern PFNGLEXTGETRENDERBUFFERSQCOMPROC gleswExtGetRenderbuffersQCOM; -extern PFNGLEXTGETSHADERSQCOMPROC gleswExtGetShadersQCOM; -extern PFNGLEXTGETTEXLEVELPARAMETERIVQCOMPROC gleswExtGetTexLevelParameterivQCOM; -extern PFNGLEXTGETTEXSUBIMAGEQCOMPROC gleswExtGetTexSubImageQCOM; -extern PFNGLEXTGETTEXTURESQCOMPROC gleswExtGetTexturesQCOM; -extern PFNGLEXTISPROGRAMBINARYQCOMPROC gleswExtIsProgramBinaryQCOM; -extern PFNGLEXTTEXOBJECTSTATEOVERRIDEIQCOMPROC gleswExtTexObjectStateOverrideiQCOM; -extern PFNGLFENCESYNCPROC gleswFenceSync; -extern PFNGLFENCESYNCAPPLEPROC gleswFenceSyncAPPLE; -extern PFNGLFINISHPROC gleswFinish; -extern PFNGLFINISHFENCENVPROC gleswFinishFenceNV; -extern PFNGLFLUSHPROC gleswFlush; -extern PFNGLFLUSHMAPPEDBUFFERRANGEPROC gleswFlushMappedBufferRange; -extern PFNGLFLUSHMAPPEDBUFFERRANGEEXTPROC gleswFlushMappedBufferRangeEXT; -extern PFNGLFRAGMENTCOVERAGECOLORNVPROC gleswFragmentCoverageColorNV; -extern PFNGLFRAMEBUFFERPIXELLOCALSTORAGESIZEEXTPROC gleswFramebufferPixelLocalStorageSizeEXT; -extern PFNGLFRAMEBUFFERRENDERBUFFERPROC gleswFramebufferRenderbuffer; -extern PFNGLFRAMEBUFFERSAMPLELOCATIONSFVNVPROC gleswFramebufferSampleLocationsfvNV; -extern PFNGLFRAMEBUFFERTEXTURE2DPROC gleswFramebufferTexture2D; -extern PFNGLFRAMEBUFFERTEXTURE2DDOWNSAMPLEIMGPROC gleswFramebufferTexture2DDownsampleIMG; -extern PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEEXTPROC gleswFramebufferTexture2DMultisampleEXT; -extern PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEIMGPROC gleswFramebufferTexture2DMultisampleIMG; -extern PFNGLFRAMEBUFFERTEXTURE3DOESPROC gleswFramebufferTexture3DOES; -extern PFNGLFRAMEBUFFERTEXTUREEXTPROC gleswFramebufferTextureEXT; -extern PFNGLFRAMEBUFFERTEXTURELAYERPROC gleswFramebufferTextureLayer; -extern PFNGLFRAMEBUFFERTEXTURELAYERDOWNSAMPLEIMGPROC gleswFramebufferTextureLayerDownsampleIMG; -extern PFNGLFRAMEBUFFERTEXTUREMULTISAMPLEMULTIVIEWOVRPROC gleswFramebufferTextureMultisampleMultiviewOVR; -extern PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC gleswFramebufferTextureMultiviewOVR; -extern PFNGLFRAMEBUFFERTEXTUREOESPROC gleswFramebufferTextureOES; -extern PFNGLFRONTFACEPROC gleswFrontFace; -extern PFNGLGENBUFFERSPROC gleswGenBuffers; -extern PFNGLGENFENCESNVPROC gleswGenFencesNV; -extern PFNGLGENFRAMEBUFFERSPROC gleswGenFramebuffers; -extern PFNGLGENPATHSNVPROC gleswGenPathsNV; -extern PFNGLGENPERFMONITORSAMDPROC gleswGenPerfMonitorsAMD; -extern PFNGLGENPROGRAMPIPELINESEXTPROC gleswGenProgramPipelinesEXT; -extern PFNGLGENQUERIESPROC gleswGenQueries; -extern PFNGLGENQUERIESEXTPROC gleswGenQueriesEXT; -extern PFNGLGENRENDERBUFFERSPROC gleswGenRenderbuffers; -extern PFNGLGENSAMPLERSPROC gleswGenSamplers; -extern PFNGLGENTEXTURESPROC gleswGenTextures; -extern PFNGLGENTRANSFORMFEEDBACKSPROC gleswGenTransformFeedbacks; -extern PFNGLGENVERTEXARRAYSPROC gleswGenVertexArrays; -extern PFNGLGENVERTEXARRAYSOESPROC gleswGenVertexArraysOES; -extern PFNGLGENERATEMIPMAPPROC gleswGenerateMipmap; -extern PFNGLGETACTIVEATTRIBPROC gleswGetActiveAttrib; -extern PFNGLGETACTIVEUNIFORMPROC gleswGetActiveUniform; -extern PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC gleswGetActiveUniformBlockName; -extern PFNGLGETACTIVEUNIFORMBLOCKIVPROC gleswGetActiveUniformBlockiv; -extern PFNGLGETACTIVEUNIFORMSIVPROC gleswGetActiveUniformsiv; -extern PFNGLGETATTACHEDSHADERSPROC gleswGetAttachedShaders; -extern PFNGLGETATTRIBLOCATIONPROC gleswGetAttribLocation; -extern PFNGLGETBOOLEANVPROC gleswGetBooleanv; -extern PFNGLGETBUFFERPARAMETERI64VPROC gleswGetBufferParameteri64v; -extern PFNGLGETBUFFERPARAMETERIVPROC gleswGetBufferParameteriv; -extern PFNGLGETBUFFERPOINTERVPROC gleswGetBufferPointerv; -extern PFNGLGETBUFFERPOINTERVOESPROC gleswGetBufferPointervOES; -extern PFNGLGETCOVERAGEMODULATIONTABLENVPROC gleswGetCoverageModulationTableNV; -extern PFNGLGETDEBUGMESSAGELOGKHRPROC gleswGetDebugMessageLogKHR; -extern PFNGLGETDRIVERCONTROLSTRINGQCOMPROC gleswGetDriverControlStringQCOM; -extern PFNGLGETDRIVERCONTROLSQCOMPROC gleswGetDriverControlsQCOM; -extern PFNGLGETERRORPROC gleswGetError; -extern PFNGLGETFENCEIVNVPROC gleswGetFenceivNV; -extern PFNGLGETFIRSTPERFQUERYIDINTELPROC gleswGetFirstPerfQueryIdINTEL; -extern PFNGLGETFLOATI_VNVPROC gleswGetFloati_vNV; -extern PFNGLGETFLOATVPROC gleswGetFloatv; -extern PFNGLGETFRAGDATAINDEXEXTPROC gleswGetFragDataIndexEXT; -extern PFNGLGETFRAGDATALOCATIONPROC gleswGetFragDataLocation; -extern PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC gleswGetFramebufferAttachmentParameteriv; -extern PFNGLGETFRAMEBUFFERPIXELLOCALSTORAGESIZEEXTPROC gleswGetFramebufferPixelLocalStorageSizeEXT; -extern PFNGLGETGRAPHICSRESETSTATUSEXTPROC gleswGetGraphicsResetStatusEXT; -extern PFNGLGETGRAPHICSRESETSTATUSKHRPROC gleswGetGraphicsResetStatusKHR; -extern PFNGLGETIMAGEHANDLENVPROC gleswGetImageHandleNV; -extern PFNGLGETINTEGER64I_VPROC gleswGetInteger64i_v; -extern PFNGLGETINTEGER64VPROC gleswGetInteger64v; -extern PFNGLGETINTEGER64VAPPLEPROC gleswGetInteger64vAPPLE; -extern PFNGLGETINTEGERI_VPROC gleswGetIntegeri_v; -extern PFNGLGETINTEGERI_VEXTPROC gleswGetIntegeri_vEXT; -extern PFNGLGETINTEGERVPROC gleswGetIntegerv; -extern PFNGLGETINTERNALFORMATSAMPLEIVNVPROC gleswGetInternalformatSampleivNV; -extern PFNGLGETINTERNALFORMATIVPROC gleswGetInternalformativ; -extern PFNGLGETNEXTPERFQUERYIDINTELPROC gleswGetNextPerfQueryIdINTEL; -extern PFNGLGETOBJECTLABELEXTPROC gleswGetObjectLabelEXT; -extern PFNGLGETOBJECTLABELKHRPROC gleswGetObjectLabelKHR; -extern PFNGLGETOBJECTPTRLABELKHRPROC gleswGetObjectPtrLabelKHR; -extern PFNGLGETPATHCOMMANDSNVPROC gleswGetPathCommandsNV; -extern PFNGLGETPATHCOORDSNVPROC gleswGetPathCoordsNV; -extern PFNGLGETPATHDASHARRAYNVPROC gleswGetPathDashArrayNV; -extern PFNGLGETPATHLENGTHNVPROC gleswGetPathLengthNV; -extern PFNGLGETPATHMETRICRANGENVPROC gleswGetPathMetricRangeNV; -extern PFNGLGETPATHMETRICSNVPROC gleswGetPathMetricsNV; -extern PFNGLGETPATHPARAMETERFVNVPROC gleswGetPathParameterfvNV; -extern PFNGLGETPATHPARAMETERIVNVPROC gleswGetPathParameterivNV; -extern PFNGLGETPATHSPACINGNVPROC gleswGetPathSpacingNV; -extern PFNGLGETPERFCOUNTERINFOINTELPROC gleswGetPerfCounterInfoINTEL; -extern PFNGLGETPERFMONITORCOUNTERDATAAMDPROC gleswGetPerfMonitorCounterDataAMD; -extern PFNGLGETPERFMONITORCOUNTERINFOAMDPROC gleswGetPerfMonitorCounterInfoAMD; -extern PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC gleswGetPerfMonitorCounterStringAMD; -extern PFNGLGETPERFMONITORCOUNTERSAMDPROC gleswGetPerfMonitorCountersAMD; -extern PFNGLGETPERFMONITORGROUPSTRINGAMDPROC gleswGetPerfMonitorGroupStringAMD; -extern PFNGLGETPERFMONITORGROUPSAMDPROC gleswGetPerfMonitorGroupsAMD; -extern PFNGLGETPERFQUERYDATAINTELPROC gleswGetPerfQueryDataINTEL; -extern PFNGLGETPERFQUERYIDBYNAMEINTELPROC gleswGetPerfQueryIdByNameINTEL; -extern PFNGLGETPERFQUERYINFOINTELPROC gleswGetPerfQueryInfoINTEL; -extern PFNGLGETPOINTERVKHRPROC gleswGetPointervKHR; -extern PFNGLGETPROGRAMBINARYPROC gleswGetProgramBinary; -extern PFNGLGETPROGRAMBINARYOESPROC gleswGetProgramBinaryOES; -extern PFNGLGETPROGRAMINFOLOGPROC gleswGetProgramInfoLog; -extern PFNGLGETPROGRAMPIPELINEINFOLOGEXTPROC gleswGetProgramPipelineInfoLogEXT; -extern PFNGLGETPROGRAMPIPELINEIVEXTPROC gleswGetProgramPipelineivEXT; -extern PFNGLGETPROGRAMRESOURCELOCATIONINDEXEXTPROC gleswGetProgramResourceLocationIndexEXT; -extern PFNGLGETPROGRAMRESOURCEFVNVPROC gleswGetProgramResourcefvNV; -extern PFNGLGETPROGRAMIVPROC gleswGetProgramiv; -extern PFNGLGETQUERYOBJECTI64VEXTPROC gleswGetQueryObjecti64vEXT; -extern PFNGLGETQUERYOBJECTIVEXTPROC gleswGetQueryObjectivEXT; -extern PFNGLGETQUERYOBJECTUI64VEXTPROC gleswGetQueryObjectui64vEXT; -extern PFNGLGETQUERYOBJECTUIVPROC gleswGetQueryObjectuiv; -extern PFNGLGETQUERYOBJECTUIVEXTPROC gleswGetQueryObjectuivEXT; -extern PFNGLGETQUERYIVPROC gleswGetQueryiv; -extern PFNGLGETQUERYIVEXTPROC gleswGetQueryivEXT; -extern PFNGLGETRENDERBUFFERPARAMETERIVPROC gleswGetRenderbufferParameteriv; -extern PFNGLGETSAMPLERPARAMETERIIVEXTPROC gleswGetSamplerParameterIivEXT; -extern PFNGLGETSAMPLERPARAMETERIIVOESPROC gleswGetSamplerParameterIivOES; -extern PFNGLGETSAMPLERPARAMETERIUIVEXTPROC gleswGetSamplerParameterIuivEXT; -extern PFNGLGETSAMPLERPARAMETERIUIVOESPROC gleswGetSamplerParameterIuivOES; -extern PFNGLGETSAMPLERPARAMETERFVPROC gleswGetSamplerParameterfv; -extern PFNGLGETSAMPLERPARAMETERIVPROC gleswGetSamplerParameteriv; -extern PFNGLGETSHADERINFOLOGPROC gleswGetShaderInfoLog; -extern PFNGLGETSHADERPRECISIONFORMATPROC gleswGetShaderPrecisionFormat; -extern PFNGLGETSHADERSOURCEPROC gleswGetShaderSource; -extern PFNGLGETSHADERIVPROC gleswGetShaderiv; -extern PFNGLGETSTRINGPROC gleswGetString; -extern PFNGLGETSTRINGIPROC gleswGetStringi; -extern PFNGLGETSYNCIVPROC gleswGetSynciv; -extern PFNGLGETSYNCIVAPPLEPROC gleswGetSyncivAPPLE; -extern PFNGLGETTEXPARAMETERIIVEXTPROC gleswGetTexParameterIivEXT; -extern PFNGLGETTEXPARAMETERIIVOESPROC gleswGetTexParameterIivOES; -extern PFNGLGETTEXPARAMETERIUIVEXTPROC gleswGetTexParameterIuivEXT; -extern PFNGLGETTEXPARAMETERIUIVOESPROC gleswGetTexParameterIuivOES; -extern PFNGLGETTEXPARAMETERFVPROC gleswGetTexParameterfv; -extern PFNGLGETTEXPARAMETERIVPROC gleswGetTexParameteriv; -extern PFNGLGETTEXTUREHANDLENVPROC gleswGetTextureHandleNV; -extern PFNGLGETTEXTURESAMPLERHANDLENVPROC gleswGetTextureSamplerHandleNV; -extern PFNGLGETTRANSFORMFEEDBACKVARYINGPROC gleswGetTransformFeedbackVarying; -extern PFNGLGETTRANSLATEDSHADERSOURCEANGLEPROC gleswGetTranslatedShaderSourceANGLE; -extern PFNGLGETUNIFORMBLOCKINDEXPROC gleswGetUniformBlockIndex; -extern PFNGLGETUNIFORMINDICESPROC gleswGetUniformIndices; -extern PFNGLGETUNIFORMLOCATIONPROC gleswGetUniformLocation; -extern PFNGLGETUNIFORMFVPROC gleswGetUniformfv; -extern PFNGLGETUNIFORMIVPROC gleswGetUniformiv; -extern PFNGLGETUNIFORMUIVPROC gleswGetUniformuiv; -extern PFNGLGETVERTEXATTRIBIIVPROC gleswGetVertexAttribIiv; -extern PFNGLGETVERTEXATTRIBIUIVPROC gleswGetVertexAttribIuiv; -extern PFNGLGETVERTEXATTRIBPOINTERVPROC gleswGetVertexAttribPointerv; -extern PFNGLGETVERTEXATTRIBFVPROC gleswGetVertexAttribfv; -extern PFNGLGETVERTEXATTRIBIVPROC gleswGetVertexAttribiv; -extern PFNGLGETNUNIFORMFVEXTPROC gleswGetnUniformfvEXT; -extern PFNGLGETNUNIFORMFVKHRPROC gleswGetnUniformfvKHR; -extern PFNGLGETNUNIFORMIVEXTPROC gleswGetnUniformivEXT; -extern PFNGLGETNUNIFORMIVKHRPROC gleswGetnUniformivKHR; -extern PFNGLGETNUNIFORMUIVKHRPROC gleswGetnUniformuivKHR; -extern PFNGLHINTPROC gleswHint; -extern PFNGLINSERTEVENTMARKEREXTPROC gleswInsertEventMarkerEXT; -extern PFNGLINTERPOLATEPATHSNVPROC gleswInterpolatePathsNV; -extern PFNGLINVALIDATEFRAMEBUFFERPROC gleswInvalidateFramebuffer; -extern PFNGLINVALIDATESUBFRAMEBUFFERPROC gleswInvalidateSubFramebuffer; -extern PFNGLISBUFFERPROC gleswIsBuffer; -extern PFNGLISENABLEDPROC gleswIsEnabled; -extern PFNGLISENABLEDIEXTPROC gleswIsEnablediEXT; -extern PFNGLISENABLEDINVPROC gleswIsEnablediNV; -extern PFNGLISENABLEDIOESPROC gleswIsEnablediOES; -extern PFNGLISFENCENVPROC gleswIsFenceNV; -extern PFNGLISFRAMEBUFFERPROC gleswIsFramebuffer; -extern PFNGLISIMAGEHANDLERESIDENTNVPROC gleswIsImageHandleResidentNV; -extern PFNGLISPATHNVPROC gleswIsPathNV; -extern PFNGLISPOINTINFILLPATHNVPROC gleswIsPointInFillPathNV; -extern PFNGLISPOINTINSTROKEPATHNVPROC gleswIsPointInStrokePathNV; -extern PFNGLISPROGRAMPROC gleswIsProgram; -extern PFNGLISPROGRAMPIPELINEEXTPROC gleswIsProgramPipelineEXT; -extern PFNGLISQUERYPROC gleswIsQuery; -extern PFNGLISQUERYEXTPROC gleswIsQueryEXT; -extern PFNGLISRENDERBUFFERPROC gleswIsRenderbuffer; -extern PFNGLISSAMPLERPROC gleswIsSampler; -extern PFNGLISSHADERPROC gleswIsShader; -extern PFNGLISSYNCPROC gleswIsSync; -extern PFNGLISSYNCAPPLEPROC gleswIsSyncAPPLE; -extern PFNGLISTEXTUREPROC gleswIsTexture; -extern PFNGLISTEXTUREHANDLERESIDENTNVPROC gleswIsTextureHandleResidentNV; -extern PFNGLISTRANSFORMFEEDBACKPROC gleswIsTransformFeedback; -extern PFNGLISVERTEXARRAYPROC gleswIsVertexArray; -extern PFNGLISVERTEXARRAYOESPROC gleswIsVertexArrayOES; -extern PFNGLLABELOBJECTEXTPROC gleswLabelObjectEXT; -extern PFNGLLINEWIDTHPROC gleswLineWidth; -extern PFNGLLINKPROGRAMPROC gleswLinkProgram; -extern PFNGLMAKEIMAGEHANDLENONRESIDENTNVPROC gleswMakeImageHandleNonResidentNV; -extern PFNGLMAKEIMAGEHANDLERESIDENTNVPROC gleswMakeImageHandleResidentNV; -extern PFNGLMAKETEXTUREHANDLENONRESIDENTNVPROC gleswMakeTextureHandleNonResidentNV; -extern PFNGLMAKETEXTUREHANDLERESIDENTNVPROC gleswMakeTextureHandleResidentNV; -extern PFNGLMAPBUFFEROESPROC gleswMapBufferOES; -extern PFNGLMAPBUFFERRANGEPROC gleswMapBufferRange; -extern PFNGLMAPBUFFERRANGEEXTPROC gleswMapBufferRangeEXT; -extern PFNGLMATRIXLOAD3X2FNVPROC gleswMatrixLoad3x2fNV; -extern PFNGLMATRIXLOAD3X3FNVPROC gleswMatrixLoad3x3fNV; -extern PFNGLMATRIXLOADTRANSPOSE3X3FNVPROC gleswMatrixLoadTranspose3x3fNV; -extern PFNGLMATRIXMULT3X2FNVPROC gleswMatrixMult3x2fNV; -extern PFNGLMATRIXMULT3X3FNVPROC gleswMatrixMult3x3fNV; -extern PFNGLMATRIXMULTTRANSPOSE3X3FNVPROC gleswMatrixMultTranspose3x3fNV; -extern PFNGLMINSAMPLESHADINGOESPROC gleswMinSampleShadingOES; -extern PFNGLMULTIDRAWARRAYSEXTPROC gleswMultiDrawArraysEXT; -extern PFNGLMULTIDRAWARRAYSINDIRECTEXTPROC gleswMultiDrawArraysIndirectEXT; -extern PFNGLMULTIDRAWELEMENTSBASEVERTEXEXTPROC gleswMultiDrawElementsBaseVertexEXT; -extern PFNGLMULTIDRAWELEMENTSBASEVERTEXOESPROC gleswMultiDrawElementsBaseVertexOES; -extern PFNGLMULTIDRAWELEMENTSEXTPROC gleswMultiDrawElementsEXT; -extern PFNGLMULTIDRAWELEMENTSINDIRECTEXTPROC gleswMultiDrawElementsIndirectEXT; -extern PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVNVPROC gleswNamedFramebufferSampleLocationsfvNV; -extern PFNGLOBJECTLABELKHRPROC gleswObjectLabelKHR; -extern PFNGLOBJECTPTRLABELKHRPROC gleswObjectPtrLabelKHR; -extern PFNGLPATCHPARAMETERIEXTPROC gleswPatchParameteriEXT; -extern PFNGLPATCHPARAMETERIOESPROC gleswPatchParameteriOES; -extern PFNGLPATHCOMMANDSNVPROC gleswPathCommandsNV; -extern PFNGLPATHCOORDSNVPROC gleswPathCoordsNV; -extern PFNGLPATHCOVERDEPTHFUNCNVPROC gleswPathCoverDepthFuncNV; -extern PFNGLPATHDASHARRAYNVPROC gleswPathDashArrayNV; -extern PFNGLPATHGLYPHINDEXARRAYNVPROC gleswPathGlyphIndexArrayNV; -extern PFNGLPATHGLYPHINDEXRANGENVPROC gleswPathGlyphIndexRangeNV; -extern PFNGLPATHGLYPHRANGENVPROC gleswPathGlyphRangeNV; -extern PFNGLPATHGLYPHSNVPROC gleswPathGlyphsNV; -extern PFNGLPATHMEMORYGLYPHINDEXARRAYNVPROC gleswPathMemoryGlyphIndexArrayNV; -extern PFNGLPATHPARAMETERFNVPROC gleswPathParameterfNV; -extern PFNGLPATHPARAMETERFVNVPROC gleswPathParameterfvNV; -extern PFNGLPATHPARAMETERINVPROC gleswPathParameteriNV; -extern PFNGLPATHPARAMETERIVNVPROC gleswPathParameterivNV; -extern PFNGLPATHSTENCILDEPTHOFFSETNVPROC gleswPathStencilDepthOffsetNV; -extern PFNGLPATHSTENCILFUNCNVPROC gleswPathStencilFuncNV; -extern PFNGLPATHSTRINGNVPROC gleswPathStringNV; -extern PFNGLPATHSUBCOMMANDSNVPROC gleswPathSubCommandsNV; -extern PFNGLPATHSUBCOORDSNVPROC gleswPathSubCoordsNV; -extern PFNGLPAUSETRANSFORMFEEDBACKPROC gleswPauseTransformFeedback; -extern PFNGLPIXELSTOREIPROC gleswPixelStorei; -extern PFNGLPOINTALONGPATHNVPROC gleswPointAlongPathNV; -extern PFNGLPOLYGONMODENVPROC gleswPolygonModeNV; -extern PFNGLPOLYGONOFFSETPROC gleswPolygonOffset; -extern PFNGLPOLYGONOFFSETCLAMPEXTPROC gleswPolygonOffsetClampEXT; -extern PFNGLPOPDEBUGGROUPKHRPROC gleswPopDebugGroupKHR; -extern PFNGLPOPGROUPMARKEREXTPROC gleswPopGroupMarkerEXT; -extern PFNGLPRIMITIVEBOUNDINGBOXEXTPROC gleswPrimitiveBoundingBoxEXT; -extern PFNGLPRIMITIVEBOUNDINGBOXOESPROC gleswPrimitiveBoundingBoxOES; -extern PFNGLPROGRAMBINARYPROC gleswProgramBinary; -extern PFNGLPROGRAMBINARYOESPROC gleswProgramBinaryOES; -extern PFNGLPROGRAMPARAMETERIPROC gleswProgramParameteri; -extern PFNGLPROGRAMPARAMETERIEXTPROC gleswProgramParameteriEXT; -extern PFNGLPROGRAMPATHFRAGMENTINPUTGENNVPROC gleswProgramPathFragmentInputGenNV; -extern PFNGLPROGRAMUNIFORM1FEXTPROC gleswProgramUniform1fEXT; -extern PFNGLPROGRAMUNIFORM1FVEXTPROC gleswProgramUniform1fvEXT; -extern PFNGLPROGRAMUNIFORM1IEXTPROC gleswProgramUniform1iEXT; -extern PFNGLPROGRAMUNIFORM1IVEXTPROC gleswProgramUniform1ivEXT; -extern PFNGLPROGRAMUNIFORM1UIEXTPROC gleswProgramUniform1uiEXT; -extern PFNGLPROGRAMUNIFORM1UIVEXTPROC gleswProgramUniform1uivEXT; -extern PFNGLPROGRAMUNIFORM2FEXTPROC gleswProgramUniform2fEXT; -extern PFNGLPROGRAMUNIFORM2FVEXTPROC gleswProgramUniform2fvEXT; -extern PFNGLPROGRAMUNIFORM2IEXTPROC gleswProgramUniform2iEXT; -extern PFNGLPROGRAMUNIFORM2IVEXTPROC gleswProgramUniform2ivEXT; -extern PFNGLPROGRAMUNIFORM2UIEXTPROC gleswProgramUniform2uiEXT; -extern PFNGLPROGRAMUNIFORM2UIVEXTPROC gleswProgramUniform2uivEXT; -extern PFNGLPROGRAMUNIFORM3FEXTPROC gleswProgramUniform3fEXT; -extern PFNGLPROGRAMUNIFORM3FVEXTPROC gleswProgramUniform3fvEXT; -extern PFNGLPROGRAMUNIFORM3IEXTPROC gleswProgramUniform3iEXT; -extern PFNGLPROGRAMUNIFORM3IVEXTPROC gleswProgramUniform3ivEXT; -extern PFNGLPROGRAMUNIFORM3UIEXTPROC gleswProgramUniform3uiEXT; -extern PFNGLPROGRAMUNIFORM3UIVEXTPROC gleswProgramUniform3uivEXT; -extern PFNGLPROGRAMUNIFORM4FEXTPROC gleswProgramUniform4fEXT; -extern PFNGLPROGRAMUNIFORM4FVEXTPROC gleswProgramUniform4fvEXT; -extern PFNGLPROGRAMUNIFORM4IEXTPROC gleswProgramUniform4iEXT; -extern PFNGLPROGRAMUNIFORM4IVEXTPROC gleswProgramUniform4ivEXT; -extern PFNGLPROGRAMUNIFORM4UIEXTPROC gleswProgramUniform4uiEXT; -extern PFNGLPROGRAMUNIFORM4UIVEXTPROC gleswProgramUniform4uivEXT; -extern PFNGLPROGRAMUNIFORMHANDLEUI64NVPROC gleswProgramUniformHandleui64NV; -extern PFNGLPROGRAMUNIFORMHANDLEUI64VNVPROC gleswProgramUniformHandleui64vNV; -extern PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC gleswProgramUniformMatrix2fvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX2X3FVEXTPROC gleswProgramUniformMatrix2x3fvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX2X4FVEXTPROC gleswProgramUniformMatrix2x4fvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC gleswProgramUniformMatrix3fvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX3X2FVEXTPROC gleswProgramUniformMatrix3x2fvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX3X4FVEXTPROC gleswProgramUniformMatrix3x4fvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC gleswProgramUniformMatrix4fvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX4X2FVEXTPROC gleswProgramUniformMatrix4x2fvEXT; -extern PFNGLPROGRAMUNIFORMMATRIX4X3FVEXTPROC gleswProgramUniformMatrix4x3fvEXT; -extern PFNGLPUSHDEBUGGROUPKHRPROC gleswPushDebugGroupKHR; -extern PFNGLPUSHGROUPMARKEREXTPROC gleswPushGroupMarkerEXT; -extern PFNGLQUERYCOUNTEREXTPROC gleswQueryCounterEXT; -extern PFNGLRASTERSAMPLESEXTPROC gleswRasterSamplesEXT; -extern PFNGLREADBUFFERPROC gleswReadBuffer; -extern PFNGLREADBUFFERINDEXEDEXTPROC gleswReadBufferIndexedEXT; -extern PFNGLREADBUFFERNVPROC gleswReadBufferNV; -extern PFNGLREADPIXELSPROC gleswReadPixels; -extern PFNGLREADNPIXELSEXTPROC gleswReadnPixelsEXT; -extern PFNGLREADNPIXELSKHRPROC gleswReadnPixelsKHR; -extern PFNGLRELEASESHADERCOMPILERPROC gleswReleaseShaderCompiler; -extern PFNGLRENDERBUFFERSTORAGEPROC gleswRenderbufferStorage; -extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC gleswRenderbufferStorageMultisample; -extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLEANGLEPROC gleswRenderbufferStorageMultisampleANGLE; -extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLEAPPLEPROC gleswRenderbufferStorageMultisampleAPPLE; -extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC gleswRenderbufferStorageMultisampleEXT; -extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLEIMGPROC gleswRenderbufferStorageMultisampleIMG; -extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLENVPROC gleswRenderbufferStorageMultisampleNV; -extern PFNGLRESOLVEDEPTHVALUESNVPROC gleswResolveDepthValuesNV; -extern PFNGLRESOLVEMULTISAMPLEFRAMEBUFFERAPPLEPROC gleswResolveMultisampleFramebufferAPPLE; -extern PFNGLRESUMETRANSFORMFEEDBACKPROC gleswResumeTransformFeedback; -extern PFNGLSAMPLECOVERAGEPROC gleswSampleCoverage; -extern PFNGLSAMPLERPARAMETERIIVEXTPROC gleswSamplerParameterIivEXT; -extern PFNGLSAMPLERPARAMETERIIVOESPROC gleswSamplerParameterIivOES; -extern PFNGLSAMPLERPARAMETERIUIVEXTPROC gleswSamplerParameterIuivEXT; -extern PFNGLSAMPLERPARAMETERIUIVOESPROC gleswSamplerParameterIuivOES; -extern PFNGLSAMPLERPARAMETERFPROC gleswSamplerParameterf; -extern PFNGLSAMPLERPARAMETERFVPROC gleswSamplerParameterfv; -extern PFNGLSAMPLERPARAMETERIPROC gleswSamplerParameteri; -extern PFNGLSAMPLERPARAMETERIVPROC gleswSamplerParameteriv; -extern PFNGLSCISSORPROC gleswScissor; -extern PFNGLSCISSORARRAYVNVPROC gleswScissorArrayvNV; -extern PFNGLSCISSORINDEXEDNVPROC gleswScissorIndexedNV; -extern PFNGLSCISSORINDEXEDVNVPROC gleswScissorIndexedvNV; -extern PFNGLSELECTPERFMONITORCOUNTERSAMDPROC gleswSelectPerfMonitorCountersAMD; -extern PFNGLSETFENCENVPROC gleswSetFenceNV; -extern PFNGLSHADERBINARYPROC gleswShaderBinary; -extern PFNGLSHADERSOURCEPROC gleswShaderSource; -extern PFNGLSTARTTILINGQCOMPROC gleswStartTilingQCOM; -extern PFNGLSTENCILFILLPATHINSTANCEDNVPROC gleswStencilFillPathInstancedNV; -extern PFNGLSTENCILFILLPATHNVPROC gleswStencilFillPathNV; -extern PFNGLSTENCILFUNCPROC gleswStencilFunc; -extern PFNGLSTENCILFUNCSEPARATEPROC gleswStencilFuncSeparate; -extern PFNGLSTENCILMASKPROC gleswStencilMask; -extern PFNGLSTENCILMASKSEPARATEPROC gleswStencilMaskSeparate; -extern PFNGLSTENCILOPPROC gleswStencilOp; -extern PFNGLSTENCILOPSEPARATEPROC gleswStencilOpSeparate; -extern PFNGLSTENCILSTROKEPATHINSTANCEDNVPROC gleswStencilStrokePathInstancedNV; -extern PFNGLSTENCILSTROKEPATHNVPROC gleswStencilStrokePathNV; -extern PFNGLSTENCILTHENCOVERFILLPATHINSTANCEDNVPROC gleswStencilThenCoverFillPathInstancedNV; -extern PFNGLSTENCILTHENCOVERFILLPATHNVPROC gleswStencilThenCoverFillPathNV; -extern PFNGLSTENCILTHENCOVERSTROKEPATHINSTANCEDNVPROC gleswStencilThenCoverStrokePathInstancedNV; -extern PFNGLSTENCILTHENCOVERSTROKEPATHNVPROC gleswStencilThenCoverStrokePathNV; -extern PFNGLSUBPIXELPRECISIONBIASNVPROC gleswSubpixelPrecisionBiasNV; -extern PFNGLTESTFENCENVPROC gleswTestFenceNV; -extern PFNGLTEXBUFFEREXTPROC gleswTexBufferEXT; -extern PFNGLTEXBUFFEROESPROC gleswTexBufferOES; -extern PFNGLTEXBUFFERRANGEEXTPROC gleswTexBufferRangeEXT; -extern PFNGLTEXBUFFERRANGEOESPROC gleswTexBufferRangeOES; -extern PFNGLTEXIMAGE2DPROC gleswTexImage2D; -extern PFNGLTEXIMAGE3DPROC gleswTexImage3D; -extern PFNGLTEXIMAGE3DOESPROC gleswTexImage3DOES; -extern PFNGLTEXPAGECOMMITMENTEXTPROC gleswTexPageCommitmentEXT; -extern PFNGLTEXPARAMETERIIVEXTPROC gleswTexParameterIivEXT; -extern PFNGLTEXPARAMETERIIVOESPROC gleswTexParameterIivOES; -extern PFNGLTEXPARAMETERIUIVEXTPROC gleswTexParameterIuivEXT; -extern PFNGLTEXPARAMETERIUIVOESPROC gleswTexParameterIuivOES; -extern PFNGLTEXPARAMETERFPROC gleswTexParameterf; -extern PFNGLTEXPARAMETERFVPROC gleswTexParameterfv; -extern PFNGLTEXPARAMETERIPROC gleswTexParameteri; -extern PFNGLTEXPARAMETERIVPROC gleswTexParameteriv; -extern PFNGLTEXSTORAGE1DEXTPROC gleswTexStorage1DEXT; -extern PFNGLTEXSTORAGE2DPROC gleswTexStorage2D; -extern PFNGLTEXSTORAGE2DEXTPROC gleswTexStorage2DEXT; -extern PFNGLTEXSTORAGE3DPROC gleswTexStorage3D; -extern PFNGLTEXSTORAGE3DEXTPROC gleswTexStorage3DEXT; -extern PFNGLTEXSTORAGE3DMULTISAMPLEOESPROC gleswTexStorage3DMultisampleOES; -extern PFNGLTEXSUBIMAGE2DPROC gleswTexSubImage2D; -extern PFNGLTEXSUBIMAGE3DPROC gleswTexSubImage3D; -extern PFNGLTEXSUBIMAGE3DOESPROC gleswTexSubImage3DOES; -extern PFNGLTEXTURESTORAGE1DEXTPROC gleswTextureStorage1DEXT; -extern PFNGLTEXTURESTORAGE2DEXTPROC gleswTextureStorage2DEXT; -extern PFNGLTEXTURESTORAGE3DEXTPROC gleswTextureStorage3DEXT; -extern PFNGLTEXTUREVIEWEXTPROC gleswTextureViewEXT; -extern PFNGLTEXTUREVIEWOESPROC gleswTextureViewOES; -extern PFNGLTRANSFORMFEEDBACKVARYINGSPROC gleswTransformFeedbackVaryings; -extern PFNGLTRANSFORMPATHNVPROC gleswTransformPathNV; -extern PFNGLUNIFORM1FPROC gleswUniform1f; -extern PFNGLUNIFORM1FVPROC gleswUniform1fv; -extern PFNGLUNIFORM1IPROC gleswUniform1i; -extern PFNGLUNIFORM1IVPROC gleswUniform1iv; -extern PFNGLUNIFORM1UIPROC gleswUniform1ui; -extern PFNGLUNIFORM1UIVPROC gleswUniform1uiv; -extern PFNGLUNIFORM2FPROC gleswUniform2f; -extern PFNGLUNIFORM2FVPROC gleswUniform2fv; -extern PFNGLUNIFORM2IPROC gleswUniform2i; -extern PFNGLUNIFORM2IVPROC gleswUniform2iv; -extern PFNGLUNIFORM2UIPROC gleswUniform2ui; -extern PFNGLUNIFORM2UIVPROC gleswUniform2uiv; -extern PFNGLUNIFORM3FPROC gleswUniform3f; -extern PFNGLUNIFORM3FVPROC gleswUniform3fv; -extern PFNGLUNIFORM3IPROC gleswUniform3i; -extern PFNGLUNIFORM3IVPROC gleswUniform3iv; -extern PFNGLUNIFORM3UIPROC gleswUniform3ui; -extern PFNGLUNIFORM3UIVPROC gleswUniform3uiv; -extern PFNGLUNIFORM4FPROC gleswUniform4f; -extern PFNGLUNIFORM4FVPROC gleswUniform4fv; -extern PFNGLUNIFORM4IPROC gleswUniform4i; -extern PFNGLUNIFORM4IVPROC gleswUniform4iv; -extern PFNGLUNIFORM4UIPROC gleswUniform4ui; -extern PFNGLUNIFORM4UIVPROC gleswUniform4uiv; -extern PFNGLUNIFORMBLOCKBINDINGPROC gleswUniformBlockBinding; -extern PFNGLUNIFORMHANDLEUI64NVPROC gleswUniformHandleui64NV; -extern PFNGLUNIFORMHANDLEUI64VNVPROC gleswUniformHandleui64vNV; -extern PFNGLUNIFORMMATRIX2FVPROC gleswUniformMatrix2fv; -extern PFNGLUNIFORMMATRIX2X3FVPROC gleswUniformMatrix2x3fv; -extern PFNGLUNIFORMMATRIX2X3FVNVPROC gleswUniformMatrix2x3fvNV; -extern PFNGLUNIFORMMATRIX2X4FVPROC gleswUniformMatrix2x4fv; -extern PFNGLUNIFORMMATRIX2X4FVNVPROC gleswUniformMatrix2x4fvNV; -extern PFNGLUNIFORMMATRIX3FVPROC gleswUniformMatrix3fv; -extern PFNGLUNIFORMMATRIX3X2FVPROC gleswUniformMatrix3x2fv; -extern PFNGLUNIFORMMATRIX3X2FVNVPROC gleswUniformMatrix3x2fvNV; -extern PFNGLUNIFORMMATRIX3X4FVPROC gleswUniformMatrix3x4fv; -extern PFNGLUNIFORMMATRIX3X4FVNVPROC gleswUniformMatrix3x4fvNV; -extern PFNGLUNIFORMMATRIX4FVPROC gleswUniformMatrix4fv; -extern PFNGLUNIFORMMATRIX4X2FVPROC gleswUniformMatrix4x2fv; -extern PFNGLUNIFORMMATRIX4X2FVNVPROC gleswUniformMatrix4x2fvNV; -extern PFNGLUNIFORMMATRIX4X3FVPROC gleswUniformMatrix4x3fv; -extern PFNGLUNIFORMMATRIX4X3FVNVPROC gleswUniformMatrix4x3fvNV; -extern PFNGLUNMAPBUFFERPROC gleswUnmapBuffer; -extern PFNGLUNMAPBUFFEROESPROC gleswUnmapBufferOES; -extern PFNGLUSEPROGRAMPROC gleswUseProgram; -extern PFNGLUSEPROGRAMSTAGESEXTPROC gleswUseProgramStagesEXT; -extern PFNGLVALIDATEPROGRAMPROC gleswValidateProgram; -extern PFNGLVALIDATEPROGRAMPIPELINEEXTPROC gleswValidateProgramPipelineEXT; -extern PFNGLVERTEXATTRIB1FPROC gleswVertexAttrib1f; -extern PFNGLVERTEXATTRIB1FVPROC gleswVertexAttrib1fv; -extern PFNGLVERTEXATTRIB2FPROC gleswVertexAttrib2f; -extern PFNGLVERTEXATTRIB2FVPROC gleswVertexAttrib2fv; -extern PFNGLVERTEXATTRIB3FPROC gleswVertexAttrib3f; -extern PFNGLVERTEXATTRIB3FVPROC gleswVertexAttrib3fv; -extern PFNGLVERTEXATTRIB4FPROC gleswVertexAttrib4f; -extern PFNGLVERTEXATTRIB4FVPROC gleswVertexAttrib4fv; -extern PFNGLVERTEXATTRIBDIVISORPROC gleswVertexAttribDivisor; -extern PFNGLVERTEXATTRIBDIVISORANGLEPROC gleswVertexAttribDivisorANGLE; -extern PFNGLVERTEXATTRIBDIVISOREXTPROC gleswVertexAttribDivisorEXT; -extern PFNGLVERTEXATTRIBDIVISORNVPROC gleswVertexAttribDivisorNV; -extern PFNGLVERTEXATTRIBI4IPROC gleswVertexAttribI4i; -extern PFNGLVERTEXATTRIBI4IVPROC gleswVertexAttribI4iv; -extern PFNGLVERTEXATTRIBI4UIPROC gleswVertexAttribI4ui; -extern PFNGLVERTEXATTRIBI4UIVPROC gleswVertexAttribI4uiv; -extern PFNGLVERTEXATTRIBIPOINTERPROC gleswVertexAttribIPointer; -extern PFNGLVERTEXATTRIBPOINTERPROC gleswVertexAttribPointer; -extern PFNGLVIEWPORTPROC gleswViewport; -extern PFNGLVIEWPORTARRAYVNVPROC gleswViewportArrayvNV; -extern PFNGLVIEWPORTINDEXEDFNVPROC gleswViewportIndexedfNV; -extern PFNGLVIEWPORTINDEXEDFVNVPROC gleswViewportIndexedfvNV; -extern PFNGLWAITSYNCPROC gleswWaitSync; -extern PFNGLWAITSYNCAPPLEPROC gleswWaitSyncAPPLE; -extern PFNGLWEIGHTPATHSNVPROC gleswWeightPathsNV; -#define glActiveShaderProgramEXT gleswActiveShaderProgramEXT -#define glActiveTexture gleswActiveTexture -#define glAlphaFuncQCOM gleswAlphaFuncQCOM -#define glApplyFramebufferAttachmentCMAAINTEL gleswApplyFramebufferAttachmentCMAAINTEL -#define glAttachShader gleswAttachShader -#define glBeginConditionalRenderNV gleswBeginConditionalRenderNV -#define glBeginPerfMonitorAMD gleswBeginPerfMonitorAMD -#define glBeginPerfQueryINTEL gleswBeginPerfQueryINTEL -#define glBeginQuery gleswBeginQuery -#define glBeginQueryEXT gleswBeginQueryEXT -#define glBeginTransformFeedback gleswBeginTransformFeedback -#define glBindAttribLocation gleswBindAttribLocation -#define glBindBuffer gleswBindBuffer -#define glBindBufferBase gleswBindBufferBase -#define glBindBufferRange gleswBindBufferRange -#define glBindFragDataLocationEXT gleswBindFragDataLocationEXT -#define glBindFragDataLocationIndexedEXT gleswBindFragDataLocationIndexedEXT -#define glBindFramebuffer gleswBindFramebuffer -#define glBindProgramPipelineEXT gleswBindProgramPipelineEXT -#define glBindRenderbuffer gleswBindRenderbuffer -#define glBindSampler gleswBindSampler -#define glBindTexture gleswBindTexture -#define glBindTransformFeedback gleswBindTransformFeedback -#define glBindVertexArray gleswBindVertexArray -#define glBindVertexArrayOES gleswBindVertexArrayOES -#define glBlendBarrierKHR gleswBlendBarrierKHR -#define glBlendBarrierNV gleswBlendBarrierNV -#define glBlendColor gleswBlendColor -#define glBlendEquation gleswBlendEquation -#define glBlendEquationSeparate gleswBlendEquationSeparate -#define glBlendEquationSeparateiEXT gleswBlendEquationSeparateiEXT -#define glBlendEquationSeparateiOES gleswBlendEquationSeparateiOES -#define glBlendEquationiEXT gleswBlendEquationiEXT -#define glBlendEquationiOES gleswBlendEquationiOES -#define glBlendFunc gleswBlendFunc -#define glBlendFuncSeparate gleswBlendFuncSeparate -#define glBlendFuncSeparateiEXT gleswBlendFuncSeparateiEXT -#define glBlendFuncSeparateiOES gleswBlendFuncSeparateiOES -#define glBlendFunciEXT gleswBlendFunciEXT -#define glBlendFunciOES gleswBlendFunciOES -#define glBlendParameteriNV gleswBlendParameteriNV -#define glBlitFramebuffer gleswBlitFramebuffer -#define glBlitFramebufferANGLE gleswBlitFramebufferANGLE -#define glBlitFramebufferNV gleswBlitFramebufferNV -#define glBufferData gleswBufferData -#define glBufferStorageEXT gleswBufferStorageEXT -#define glBufferSubData gleswBufferSubData -#define glCheckFramebufferStatus gleswCheckFramebufferStatus -#define glClear gleswClear -#define glClearBufferfi gleswClearBufferfi -#define glClearBufferfv gleswClearBufferfv -#define glClearBufferiv gleswClearBufferiv -#define glClearBufferuiv gleswClearBufferuiv -#define glClearColor gleswClearColor -#define glClearDepthf gleswClearDepthf -#define glClearPixelLocalStorageuiEXT gleswClearPixelLocalStorageuiEXT -#define glClearStencil gleswClearStencil -#define glClientWaitSync gleswClientWaitSync -#define glClientWaitSyncAPPLE gleswClientWaitSyncAPPLE -#define glColorMask gleswColorMask -#define glColorMaskiEXT gleswColorMaskiEXT -#define glColorMaskiOES gleswColorMaskiOES -#define glCompileShader gleswCompileShader -#define glCompressedTexImage2D gleswCompressedTexImage2D -#define glCompressedTexImage3D gleswCompressedTexImage3D -#define glCompressedTexImage3DOES gleswCompressedTexImage3DOES -#define glCompressedTexSubImage2D gleswCompressedTexSubImage2D -#define glCompressedTexSubImage3D gleswCompressedTexSubImage3D -#define glCompressedTexSubImage3DOES gleswCompressedTexSubImage3DOES -#define glCopyBufferSubData gleswCopyBufferSubData -#define glCopyBufferSubDataNV gleswCopyBufferSubDataNV -#define glCopyImageSubDataEXT gleswCopyImageSubDataEXT -#define glCopyImageSubDataOES gleswCopyImageSubDataOES -#define glCopyPathNV gleswCopyPathNV -#define glCopyTexImage2D gleswCopyTexImage2D -#define glCopyTexSubImage2D gleswCopyTexSubImage2D -#define glCopyTexSubImage3D gleswCopyTexSubImage3D -#define glCopyTexSubImage3DOES gleswCopyTexSubImage3DOES -#define glCopyTextureLevelsAPPLE gleswCopyTextureLevelsAPPLE -#define glCoverFillPathInstancedNV gleswCoverFillPathInstancedNV -#define glCoverFillPathNV gleswCoverFillPathNV -#define glCoverStrokePathInstancedNV gleswCoverStrokePathInstancedNV -#define glCoverStrokePathNV gleswCoverStrokePathNV -#define glCoverageMaskNV gleswCoverageMaskNV -#define glCoverageModulationNV gleswCoverageModulationNV -#define glCoverageModulationTableNV gleswCoverageModulationTableNV -#define glCoverageOperationNV gleswCoverageOperationNV -#define glCreatePerfQueryINTEL gleswCreatePerfQueryINTEL -#define glCreateProgram gleswCreateProgram -#define glCreateShader gleswCreateShader -#define glCreateShaderProgramvEXT gleswCreateShaderProgramvEXT -#define glCullFace gleswCullFace -#define glDebugMessageCallbackKHR gleswDebugMessageCallbackKHR -#define glDebugMessageControlKHR gleswDebugMessageControlKHR -#define glDebugMessageInsertKHR gleswDebugMessageInsertKHR -#define glDeleteBuffers gleswDeleteBuffers -#define glDeleteFencesNV gleswDeleteFencesNV -#define glDeleteFramebuffers gleswDeleteFramebuffers -#define glDeletePathsNV gleswDeletePathsNV -#define glDeletePerfMonitorsAMD gleswDeletePerfMonitorsAMD -#define glDeletePerfQueryINTEL gleswDeletePerfQueryINTEL -#define glDeleteProgram gleswDeleteProgram -#define glDeleteProgramPipelinesEXT gleswDeleteProgramPipelinesEXT -#define glDeleteQueries gleswDeleteQueries -#define glDeleteQueriesEXT gleswDeleteQueriesEXT -#define glDeleteRenderbuffers gleswDeleteRenderbuffers -#define glDeleteSamplers gleswDeleteSamplers -#define glDeleteShader gleswDeleteShader -#define glDeleteSync gleswDeleteSync -#define glDeleteSyncAPPLE gleswDeleteSyncAPPLE -#define glDeleteTextures gleswDeleteTextures -#define glDeleteTransformFeedbacks gleswDeleteTransformFeedbacks -#define glDeleteVertexArrays gleswDeleteVertexArrays -#define glDeleteVertexArraysOES gleswDeleteVertexArraysOES -#define glDepthFunc gleswDepthFunc -#define glDepthMask gleswDepthMask -#define glDepthRangeArrayfvNV gleswDepthRangeArrayfvNV -#define glDepthRangeIndexedfNV gleswDepthRangeIndexedfNV -#define glDepthRangef gleswDepthRangef -#define glDetachShader gleswDetachShader -#define glDisable gleswDisable -#define glDisableDriverControlQCOM gleswDisableDriverControlQCOM -#define glDisableVertexAttribArray gleswDisableVertexAttribArray -#define glDisableiEXT gleswDisableiEXT -#define glDisableiNV gleswDisableiNV -#define glDisableiOES gleswDisableiOES -#define glDiscardFramebufferEXT gleswDiscardFramebufferEXT -#define glDrawArrays gleswDrawArrays -#define glDrawArraysInstanced gleswDrawArraysInstanced -#define glDrawArraysInstancedANGLE gleswDrawArraysInstancedANGLE -#define glDrawArraysInstancedBaseInstanceEXT gleswDrawArraysInstancedBaseInstanceEXT -#define glDrawArraysInstancedEXT gleswDrawArraysInstancedEXT -#define glDrawArraysInstancedNV gleswDrawArraysInstancedNV -#define glDrawBuffers gleswDrawBuffers -#define glDrawBuffersEXT gleswDrawBuffersEXT -#define glDrawBuffersIndexedEXT gleswDrawBuffersIndexedEXT -#define glDrawBuffersNV gleswDrawBuffersNV -#define glDrawElements gleswDrawElements -#define glDrawElementsBaseVertexEXT gleswDrawElementsBaseVertexEXT -#define glDrawElementsBaseVertexOES gleswDrawElementsBaseVertexOES -#define glDrawElementsInstanced gleswDrawElementsInstanced -#define glDrawElementsInstancedANGLE gleswDrawElementsInstancedANGLE -#define glDrawElementsInstancedBaseInstanceEXT gleswDrawElementsInstancedBaseInstanceEXT -#define glDrawElementsInstancedBaseVertexBaseInstanceEXT gleswDrawElementsInstancedBaseVertexBaseInstanceEXT -#define glDrawElementsInstancedBaseVertexEXT gleswDrawElementsInstancedBaseVertexEXT -#define glDrawElementsInstancedBaseVertexOES gleswDrawElementsInstancedBaseVertexOES -#define glDrawElementsInstancedEXT gleswDrawElementsInstancedEXT -#define glDrawElementsInstancedNV gleswDrawElementsInstancedNV -#define glDrawRangeElements gleswDrawRangeElements -#define glDrawRangeElementsBaseVertexEXT gleswDrawRangeElementsBaseVertexEXT -#define glDrawRangeElementsBaseVertexOES gleswDrawRangeElementsBaseVertexOES -#define glEGLImageTargetRenderbufferStorageOES gleswEGLImageTargetRenderbufferStorageOES -#define glEGLImageTargetTexture2DOES gleswEGLImageTargetTexture2DOES -#define glEnable gleswEnable -#define glEnableDriverControlQCOM gleswEnableDriverControlQCOM -#define glEnableVertexAttribArray gleswEnableVertexAttribArray -#define glEnableiEXT gleswEnableiEXT -#define glEnableiNV gleswEnableiNV -#define glEnableiOES gleswEnableiOES -#define glEndConditionalRenderNV gleswEndConditionalRenderNV -#define glEndPerfMonitorAMD gleswEndPerfMonitorAMD -#define glEndPerfQueryINTEL gleswEndPerfQueryINTEL -#define glEndQuery gleswEndQuery -#define glEndQueryEXT gleswEndQueryEXT -#define glEndTilingQCOM gleswEndTilingQCOM -#define glEndTransformFeedback gleswEndTransformFeedback -#define glExtGetBufferPointervQCOM gleswExtGetBufferPointervQCOM -#define glExtGetBuffersQCOM gleswExtGetBuffersQCOM -#define glExtGetFramebuffersQCOM gleswExtGetFramebuffersQCOM -#define glExtGetProgramBinarySourceQCOM gleswExtGetProgramBinarySourceQCOM -#define glExtGetProgramsQCOM gleswExtGetProgramsQCOM -#define glExtGetRenderbuffersQCOM gleswExtGetRenderbuffersQCOM -#define glExtGetShadersQCOM gleswExtGetShadersQCOM -#define glExtGetTexLevelParameterivQCOM gleswExtGetTexLevelParameterivQCOM -#define glExtGetTexSubImageQCOM gleswExtGetTexSubImageQCOM -#define glExtGetTexturesQCOM gleswExtGetTexturesQCOM -#define glExtIsProgramBinaryQCOM gleswExtIsProgramBinaryQCOM -#define glExtTexObjectStateOverrideiQCOM gleswExtTexObjectStateOverrideiQCOM -#define glFenceSync gleswFenceSync -#define glFenceSyncAPPLE gleswFenceSyncAPPLE -#define glFinish gleswFinish -#define glFinishFenceNV gleswFinishFenceNV -#define glFlush gleswFlush -#define glFlushMappedBufferRange gleswFlushMappedBufferRange -#define glFlushMappedBufferRangeEXT gleswFlushMappedBufferRangeEXT -#define glFragmentCoverageColorNV gleswFragmentCoverageColorNV -#define glFramebufferPixelLocalStorageSizeEXT gleswFramebufferPixelLocalStorageSizeEXT -#define glFramebufferRenderbuffer gleswFramebufferRenderbuffer -#define glFramebufferSampleLocationsfvNV gleswFramebufferSampleLocationsfvNV -#define glFramebufferTexture2D gleswFramebufferTexture2D -#define glFramebufferTexture2DDownsampleIMG gleswFramebufferTexture2DDownsampleIMG -#define glFramebufferTexture2DMultisampleEXT gleswFramebufferTexture2DMultisampleEXT -#define glFramebufferTexture2DMultisampleIMG gleswFramebufferTexture2DMultisampleIMG -#define glFramebufferTexture3DOES gleswFramebufferTexture3DOES -#define glFramebufferTextureEXT gleswFramebufferTextureEXT -#define glFramebufferTextureLayer gleswFramebufferTextureLayer -#define glFramebufferTextureLayerDownsampleIMG gleswFramebufferTextureLayerDownsampleIMG -#define glFramebufferTextureMultisampleMultiviewOVR gleswFramebufferTextureMultisampleMultiviewOVR -#define glFramebufferTextureMultiviewOVR gleswFramebufferTextureMultiviewOVR -#define glFramebufferTextureOES gleswFramebufferTextureOES -#define glFrontFace gleswFrontFace -#define glGenBuffers gleswGenBuffers -#define glGenFencesNV gleswGenFencesNV -#define glGenFramebuffers gleswGenFramebuffers -#define glGenPathsNV gleswGenPathsNV -#define glGenPerfMonitorsAMD gleswGenPerfMonitorsAMD -#define glGenProgramPipelinesEXT gleswGenProgramPipelinesEXT -#define glGenQueries gleswGenQueries -#define glGenQueriesEXT gleswGenQueriesEXT -#define glGenRenderbuffers gleswGenRenderbuffers -#define glGenSamplers gleswGenSamplers -#define glGenTextures gleswGenTextures -#define glGenTransformFeedbacks gleswGenTransformFeedbacks -#define glGenVertexArrays gleswGenVertexArrays -#define glGenVertexArraysOES gleswGenVertexArraysOES -#define glGenerateMipmap gleswGenerateMipmap -#define glGetActiveAttrib gleswGetActiveAttrib -#define glGetActiveUniform gleswGetActiveUniform -#define glGetActiveUniformBlockName gleswGetActiveUniformBlockName -#define glGetActiveUniformBlockiv gleswGetActiveUniformBlockiv -#define glGetActiveUniformsiv gleswGetActiveUniformsiv -#define glGetAttachedShaders gleswGetAttachedShaders -#define glGetAttribLocation gleswGetAttribLocation -#define glGetBooleanv gleswGetBooleanv -#define glGetBufferParameteri64v gleswGetBufferParameteri64v -#define glGetBufferParameteriv gleswGetBufferParameteriv -#define glGetBufferPointerv gleswGetBufferPointerv -#define glGetBufferPointervOES gleswGetBufferPointervOES -#define glGetCoverageModulationTableNV gleswGetCoverageModulationTableNV -#define glGetDebugMessageLogKHR gleswGetDebugMessageLogKHR -#define glGetDriverControlStringQCOM gleswGetDriverControlStringQCOM -#define glGetDriverControlsQCOM gleswGetDriverControlsQCOM -#define glGetError gleswGetError -#define glGetFenceivNV gleswGetFenceivNV -#define glGetFirstPerfQueryIdINTEL gleswGetFirstPerfQueryIdINTEL -#define glGetFloati_vNV gleswGetFloati_vNV -#define glGetFloatv gleswGetFloatv -#define glGetFragDataIndexEXT gleswGetFragDataIndexEXT -#define glGetFragDataLocation gleswGetFragDataLocation -#define glGetFramebufferAttachmentParameteriv gleswGetFramebufferAttachmentParameteriv -#define glGetFramebufferPixelLocalStorageSizeEXT gleswGetFramebufferPixelLocalStorageSizeEXT -#define glGetGraphicsResetStatusEXT gleswGetGraphicsResetStatusEXT -#define glGetGraphicsResetStatusKHR gleswGetGraphicsResetStatusKHR -#define glGetImageHandleNV gleswGetImageHandleNV -#define glGetInteger64i_v gleswGetInteger64i_v -#define glGetInteger64v gleswGetInteger64v -#define glGetInteger64vAPPLE gleswGetInteger64vAPPLE -#define glGetIntegeri_v gleswGetIntegeri_v -#define glGetIntegeri_vEXT gleswGetIntegeri_vEXT -#define glGetIntegerv gleswGetIntegerv -#define glGetInternalformatSampleivNV gleswGetInternalformatSampleivNV -#define glGetInternalformativ gleswGetInternalformativ -#define glGetNextPerfQueryIdINTEL gleswGetNextPerfQueryIdINTEL -#define glGetObjectLabelEXT gleswGetObjectLabelEXT -#define glGetObjectLabelKHR gleswGetObjectLabelKHR -#define glGetObjectPtrLabelKHR gleswGetObjectPtrLabelKHR -#define glGetPathCommandsNV gleswGetPathCommandsNV -#define glGetPathCoordsNV gleswGetPathCoordsNV -#define glGetPathDashArrayNV gleswGetPathDashArrayNV -#define glGetPathLengthNV gleswGetPathLengthNV -#define glGetPathMetricRangeNV gleswGetPathMetricRangeNV -#define glGetPathMetricsNV gleswGetPathMetricsNV -#define glGetPathParameterfvNV gleswGetPathParameterfvNV -#define glGetPathParameterivNV gleswGetPathParameterivNV -#define glGetPathSpacingNV gleswGetPathSpacingNV -#define glGetPerfCounterInfoINTEL gleswGetPerfCounterInfoINTEL -#define glGetPerfMonitorCounterDataAMD gleswGetPerfMonitorCounterDataAMD -#define glGetPerfMonitorCounterInfoAMD gleswGetPerfMonitorCounterInfoAMD -#define glGetPerfMonitorCounterStringAMD gleswGetPerfMonitorCounterStringAMD -#define glGetPerfMonitorCountersAMD gleswGetPerfMonitorCountersAMD -#define glGetPerfMonitorGroupStringAMD gleswGetPerfMonitorGroupStringAMD -#define glGetPerfMonitorGroupsAMD gleswGetPerfMonitorGroupsAMD -#define glGetPerfQueryDataINTEL gleswGetPerfQueryDataINTEL -#define glGetPerfQueryIdByNameINTEL gleswGetPerfQueryIdByNameINTEL -#define glGetPerfQueryInfoINTEL gleswGetPerfQueryInfoINTEL -#define glGetPointervKHR gleswGetPointervKHR -#define glGetProgramBinary gleswGetProgramBinary -#define glGetProgramBinaryOES gleswGetProgramBinaryOES -#define glGetProgramInfoLog gleswGetProgramInfoLog -#define glGetProgramPipelineInfoLogEXT gleswGetProgramPipelineInfoLogEXT -#define glGetProgramPipelineivEXT gleswGetProgramPipelineivEXT -#define glGetProgramResourceLocationIndexEXT gleswGetProgramResourceLocationIndexEXT -#define glGetProgramResourcefvNV gleswGetProgramResourcefvNV -#define glGetProgramiv gleswGetProgramiv -#define glGetQueryObjecti64vEXT gleswGetQueryObjecti64vEXT -#define glGetQueryObjectivEXT gleswGetQueryObjectivEXT -#define glGetQueryObjectui64vEXT gleswGetQueryObjectui64vEXT -#define glGetQueryObjectuiv gleswGetQueryObjectuiv -#define glGetQueryObjectuivEXT gleswGetQueryObjectuivEXT -#define glGetQueryiv gleswGetQueryiv -#define glGetQueryivEXT gleswGetQueryivEXT -#define glGetRenderbufferParameteriv gleswGetRenderbufferParameteriv -#define glGetSamplerParameterIivEXT gleswGetSamplerParameterIivEXT -#define glGetSamplerParameterIivOES gleswGetSamplerParameterIivOES -#define glGetSamplerParameterIuivEXT gleswGetSamplerParameterIuivEXT -#define glGetSamplerParameterIuivOES gleswGetSamplerParameterIuivOES -#define glGetSamplerParameterfv gleswGetSamplerParameterfv -#define glGetSamplerParameteriv gleswGetSamplerParameteriv -#define glGetShaderInfoLog gleswGetShaderInfoLog -#define glGetShaderPrecisionFormat gleswGetShaderPrecisionFormat -#define glGetShaderSource gleswGetShaderSource -#define glGetShaderiv gleswGetShaderiv -#define glGetString gleswGetString -#define glGetStringi gleswGetStringi -#define glGetSynciv gleswGetSynciv -#define glGetSyncivAPPLE gleswGetSyncivAPPLE -#define glGetTexParameterIivEXT gleswGetTexParameterIivEXT -#define glGetTexParameterIivOES gleswGetTexParameterIivOES -#define glGetTexParameterIuivEXT gleswGetTexParameterIuivEXT -#define glGetTexParameterIuivOES gleswGetTexParameterIuivOES -#define glGetTexParameterfv gleswGetTexParameterfv -#define glGetTexParameteriv gleswGetTexParameteriv -#define glGetTextureHandleNV gleswGetTextureHandleNV -#define glGetTextureSamplerHandleNV gleswGetTextureSamplerHandleNV -#define glGetTransformFeedbackVarying gleswGetTransformFeedbackVarying -#define glGetTranslatedShaderSourceANGLE gleswGetTranslatedShaderSourceANGLE -#define glGetUniformBlockIndex gleswGetUniformBlockIndex -#define glGetUniformIndices gleswGetUniformIndices -#define glGetUniformLocation gleswGetUniformLocation -#define glGetUniformfv gleswGetUniformfv -#define glGetUniformiv gleswGetUniformiv -#define glGetUniformuiv gleswGetUniformuiv -#define glGetVertexAttribIiv gleswGetVertexAttribIiv -#define glGetVertexAttribIuiv gleswGetVertexAttribIuiv -#define glGetVertexAttribPointerv gleswGetVertexAttribPointerv -#define glGetVertexAttribfv gleswGetVertexAttribfv -#define glGetVertexAttribiv gleswGetVertexAttribiv -#define glGetnUniformfvEXT gleswGetnUniformfvEXT -#define glGetnUniformfvKHR gleswGetnUniformfvKHR -#define glGetnUniformivEXT gleswGetnUniformivEXT -#define glGetnUniformivKHR gleswGetnUniformivKHR -#define glGetnUniformuivKHR gleswGetnUniformuivKHR -#define glHint gleswHint -#define glInsertEventMarkerEXT gleswInsertEventMarkerEXT -#define glInterpolatePathsNV gleswInterpolatePathsNV -#define glInvalidateFramebuffer gleswInvalidateFramebuffer -#define glInvalidateSubFramebuffer gleswInvalidateSubFramebuffer -#define glIsBuffer gleswIsBuffer -#define glIsEnabled gleswIsEnabled -#define glIsEnablediEXT gleswIsEnablediEXT -#define glIsEnablediNV gleswIsEnablediNV -#define glIsEnablediOES gleswIsEnablediOES -#define glIsFenceNV gleswIsFenceNV -#define glIsFramebuffer gleswIsFramebuffer -#define glIsImageHandleResidentNV gleswIsImageHandleResidentNV -#define glIsPathNV gleswIsPathNV -#define glIsPointInFillPathNV gleswIsPointInFillPathNV -#define glIsPointInStrokePathNV gleswIsPointInStrokePathNV -#define glIsProgram gleswIsProgram -#define glIsProgramPipelineEXT gleswIsProgramPipelineEXT -#define glIsQuery gleswIsQuery -#define glIsQueryEXT gleswIsQueryEXT -#define glIsRenderbuffer gleswIsRenderbuffer -#define glIsSampler gleswIsSampler -#define glIsShader gleswIsShader -#define glIsSync gleswIsSync -#define glIsSyncAPPLE gleswIsSyncAPPLE -#define glIsTexture gleswIsTexture -#define glIsTextureHandleResidentNV gleswIsTextureHandleResidentNV -#define glIsTransformFeedback gleswIsTransformFeedback -#define glIsVertexArray gleswIsVertexArray -#define glIsVertexArrayOES gleswIsVertexArrayOES -#define glLabelObjectEXT gleswLabelObjectEXT -#define glLineWidth gleswLineWidth -#define glLinkProgram gleswLinkProgram -#define glMakeImageHandleNonResidentNV gleswMakeImageHandleNonResidentNV -#define glMakeImageHandleResidentNV gleswMakeImageHandleResidentNV -#define glMakeTextureHandleNonResidentNV gleswMakeTextureHandleNonResidentNV -#define glMakeTextureHandleResidentNV gleswMakeTextureHandleResidentNV -#define glMapBufferOES gleswMapBufferOES -#define glMapBufferRange gleswMapBufferRange -#define glMapBufferRangeEXT gleswMapBufferRangeEXT -#define glMatrixLoad3x2fNV gleswMatrixLoad3x2fNV -#define glMatrixLoad3x3fNV gleswMatrixLoad3x3fNV -#define glMatrixLoadTranspose3x3fNV gleswMatrixLoadTranspose3x3fNV -#define glMatrixMult3x2fNV gleswMatrixMult3x2fNV -#define glMatrixMult3x3fNV gleswMatrixMult3x3fNV -#define glMatrixMultTranspose3x3fNV gleswMatrixMultTranspose3x3fNV -#define glMinSampleShadingOES gleswMinSampleShadingOES -#define glMultiDrawArraysEXT gleswMultiDrawArraysEXT -#define glMultiDrawArraysIndirectEXT gleswMultiDrawArraysIndirectEXT -#define glMultiDrawElementsBaseVertexEXT gleswMultiDrawElementsBaseVertexEXT -#define glMultiDrawElementsBaseVertexOES gleswMultiDrawElementsBaseVertexOES -#define glMultiDrawElementsEXT gleswMultiDrawElementsEXT -#define glMultiDrawElementsIndirectEXT gleswMultiDrawElementsIndirectEXT -#define glNamedFramebufferSampleLocationsfvNV gleswNamedFramebufferSampleLocationsfvNV -#define glObjectLabelKHR gleswObjectLabelKHR -#define glObjectPtrLabelKHR gleswObjectPtrLabelKHR -#define glPatchParameteriEXT gleswPatchParameteriEXT -#define glPatchParameteriOES gleswPatchParameteriOES -#define glPathCommandsNV gleswPathCommandsNV -#define glPathCoordsNV gleswPathCoordsNV -#define glPathCoverDepthFuncNV gleswPathCoverDepthFuncNV -#define glPathDashArrayNV gleswPathDashArrayNV -#define glPathGlyphIndexArrayNV gleswPathGlyphIndexArrayNV -#define glPathGlyphIndexRangeNV gleswPathGlyphIndexRangeNV -#define glPathGlyphRangeNV gleswPathGlyphRangeNV -#define glPathGlyphsNV gleswPathGlyphsNV -#define glPathMemoryGlyphIndexArrayNV gleswPathMemoryGlyphIndexArrayNV -#define glPathParameterfNV gleswPathParameterfNV -#define glPathParameterfvNV gleswPathParameterfvNV -#define glPathParameteriNV gleswPathParameteriNV -#define glPathParameterivNV gleswPathParameterivNV -#define glPathStencilDepthOffsetNV gleswPathStencilDepthOffsetNV -#define glPathStencilFuncNV gleswPathStencilFuncNV -#define glPathStringNV gleswPathStringNV -#define glPathSubCommandsNV gleswPathSubCommandsNV -#define glPathSubCoordsNV gleswPathSubCoordsNV -#define glPauseTransformFeedback gleswPauseTransformFeedback -#define glPixelStorei gleswPixelStorei -#define glPointAlongPathNV gleswPointAlongPathNV -#define glPolygonModeNV gleswPolygonModeNV -#define glPolygonOffset gleswPolygonOffset -#define glPolygonOffsetClampEXT gleswPolygonOffsetClampEXT -#define glPopDebugGroupKHR gleswPopDebugGroupKHR -#define glPopGroupMarkerEXT gleswPopGroupMarkerEXT -#define glPrimitiveBoundingBoxEXT gleswPrimitiveBoundingBoxEXT -#define glPrimitiveBoundingBoxOES gleswPrimitiveBoundingBoxOES -#define glProgramBinary gleswProgramBinary -#define glProgramBinaryOES gleswProgramBinaryOES -#define glProgramParameteri gleswProgramParameteri -#define glProgramParameteriEXT gleswProgramParameteriEXT -#define glProgramPathFragmentInputGenNV gleswProgramPathFragmentInputGenNV -#define glProgramUniform1fEXT gleswProgramUniform1fEXT -#define glProgramUniform1fvEXT gleswProgramUniform1fvEXT -#define glProgramUniform1iEXT gleswProgramUniform1iEXT -#define glProgramUniform1ivEXT gleswProgramUniform1ivEXT -#define glProgramUniform1uiEXT gleswProgramUniform1uiEXT -#define glProgramUniform1uivEXT gleswProgramUniform1uivEXT -#define glProgramUniform2fEXT gleswProgramUniform2fEXT -#define glProgramUniform2fvEXT gleswProgramUniform2fvEXT -#define glProgramUniform2iEXT gleswProgramUniform2iEXT -#define glProgramUniform2ivEXT gleswProgramUniform2ivEXT -#define glProgramUniform2uiEXT gleswProgramUniform2uiEXT -#define glProgramUniform2uivEXT gleswProgramUniform2uivEXT -#define glProgramUniform3fEXT gleswProgramUniform3fEXT -#define glProgramUniform3fvEXT gleswProgramUniform3fvEXT -#define glProgramUniform3iEXT gleswProgramUniform3iEXT -#define glProgramUniform3ivEXT gleswProgramUniform3ivEXT -#define glProgramUniform3uiEXT gleswProgramUniform3uiEXT -#define glProgramUniform3uivEXT gleswProgramUniform3uivEXT -#define glProgramUniform4fEXT gleswProgramUniform4fEXT -#define glProgramUniform4fvEXT gleswProgramUniform4fvEXT -#define glProgramUniform4iEXT gleswProgramUniform4iEXT -#define glProgramUniform4ivEXT gleswProgramUniform4ivEXT -#define glProgramUniform4uiEXT gleswProgramUniform4uiEXT -#define glProgramUniform4uivEXT gleswProgramUniform4uivEXT -#define glProgramUniformHandleui64NV gleswProgramUniformHandleui64NV -#define glProgramUniformHandleui64vNV gleswProgramUniformHandleui64vNV -#define glProgramUniformMatrix2fvEXT gleswProgramUniformMatrix2fvEXT -#define glProgramUniformMatrix2x3fvEXT gleswProgramUniformMatrix2x3fvEXT -#define glProgramUniformMatrix2x4fvEXT gleswProgramUniformMatrix2x4fvEXT -#define glProgramUniformMatrix3fvEXT gleswProgramUniformMatrix3fvEXT -#define glProgramUniformMatrix3x2fvEXT gleswProgramUniformMatrix3x2fvEXT -#define glProgramUniformMatrix3x4fvEXT gleswProgramUniformMatrix3x4fvEXT -#define glProgramUniformMatrix4fvEXT gleswProgramUniformMatrix4fvEXT -#define glProgramUniformMatrix4x2fvEXT gleswProgramUniformMatrix4x2fvEXT -#define glProgramUniformMatrix4x3fvEXT gleswProgramUniformMatrix4x3fvEXT -#define glPushDebugGroupKHR gleswPushDebugGroupKHR -#define glPushGroupMarkerEXT gleswPushGroupMarkerEXT -#define glQueryCounterEXT gleswQueryCounterEXT -#define glRasterSamplesEXT gleswRasterSamplesEXT -#define glReadBuffer gleswReadBuffer -#define glReadBufferIndexedEXT gleswReadBufferIndexedEXT -#define glReadBufferNV gleswReadBufferNV -#define glReadPixels gleswReadPixels -#define glReadnPixelsEXT gleswReadnPixelsEXT -#define glReadnPixelsKHR gleswReadnPixelsKHR -#define glReleaseShaderCompiler gleswReleaseShaderCompiler -#define glRenderbufferStorage gleswRenderbufferStorage -#define glRenderbufferStorageMultisample gleswRenderbufferStorageMultisample -#define glRenderbufferStorageMultisampleANGLE gleswRenderbufferStorageMultisampleANGLE -#define glRenderbufferStorageMultisampleAPPLE gleswRenderbufferStorageMultisampleAPPLE -#define glRenderbufferStorageMultisampleEXT gleswRenderbufferStorageMultisampleEXT -#define glRenderbufferStorageMultisampleIMG gleswRenderbufferStorageMultisampleIMG -#define glRenderbufferStorageMultisampleNV gleswRenderbufferStorageMultisampleNV -#define glResolveDepthValuesNV gleswResolveDepthValuesNV -#define glResolveMultisampleFramebufferAPPLE gleswResolveMultisampleFramebufferAPPLE -#define glResumeTransformFeedback gleswResumeTransformFeedback -#define glSampleCoverage gleswSampleCoverage -#define glSamplerParameterIivEXT gleswSamplerParameterIivEXT -#define glSamplerParameterIivOES gleswSamplerParameterIivOES -#define glSamplerParameterIuivEXT gleswSamplerParameterIuivEXT -#define glSamplerParameterIuivOES gleswSamplerParameterIuivOES -#define glSamplerParameterf gleswSamplerParameterf -#define glSamplerParameterfv gleswSamplerParameterfv -#define glSamplerParameteri gleswSamplerParameteri -#define glSamplerParameteriv gleswSamplerParameteriv -#define glScissor gleswScissor -#define glScissorArrayvNV gleswScissorArrayvNV -#define glScissorIndexedNV gleswScissorIndexedNV -#define glScissorIndexedvNV gleswScissorIndexedvNV -#define glSelectPerfMonitorCountersAMD gleswSelectPerfMonitorCountersAMD -#define glSetFenceNV gleswSetFenceNV -#define glShaderBinary gleswShaderBinary -#define glShaderSource gleswShaderSource -#define glStartTilingQCOM gleswStartTilingQCOM -#define glStencilFillPathInstancedNV gleswStencilFillPathInstancedNV -#define glStencilFillPathNV gleswStencilFillPathNV -#define glStencilFunc gleswStencilFunc -#define glStencilFuncSeparate gleswStencilFuncSeparate -#define glStencilMask gleswStencilMask -#define glStencilMaskSeparate gleswStencilMaskSeparate -#define glStencilOp gleswStencilOp -#define glStencilOpSeparate gleswStencilOpSeparate -#define glStencilStrokePathInstancedNV gleswStencilStrokePathInstancedNV -#define glStencilStrokePathNV gleswStencilStrokePathNV -#define glStencilThenCoverFillPathInstancedNV gleswStencilThenCoverFillPathInstancedNV -#define glStencilThenCoverFillPathNV gleswStencilThenCoverFillPathNV -#define glStencilThenCoverStrokePathInstancedNV gleswStencilThenCoverStrokePathInstancedNV -#define glStencilThenCoverStrokePathNV gleswStencilThenCoverStrokePathNV -#define glSubpixelPrecisionBiasNV gleswSubpixelPrecisionBiasNV -#define glTestFenceNV gleswTestFenceNV -#define glTexBufferEXT gleswTexBufferEXT -#define glTexBufferOES gleswTexBufferOES -#define glTexBufferRangeEXT gleswTexBufferRangeEXT -#define glTexBufferRangeOES gleswTexBufferRangeOES -#define glTexImage2D gleswTexImage2D -#define glTexImage3D gleswTexImage3D -#define glTexImage3DOES gleswTexImage3DOES -#define glTexPageCommitmentEXT gleswTexPageCommitmentEXT -#define glTexParameterIivEXT gleswTexParameterIivEXT -#define glTexParameterIivOES gleswTexParameterIivOES -#define glTexParameterIuivEXT gleswTexParameterIuivEXT -#define glTexParameterIuivOES gleswTexParameterIuivOES -#define glTexParameterf gleswTexParameterf -#define glTexParameterfv gleswTexParameterfv -#define glTexParameteri gleswTexParameteri -#define glTexParameteriv gleswTexParameteriv -#define glTexStorage1DEXT gleswTexStorage1DEXT -#define glTexStorage2D gleswTexStorage2D -#define glTexStorage2DEXT gleswTexStorage2DEXT -#define glTexStorage3D gleswTexStorage3D -#define glTexStorage3DEXT gleswTexStorage3DEXT -#define glTexStorage3DMultisampleOES gleswTexStorage3DMultisampleOES -#define glTexSubImage2D gleswTexSubImage2D -#define glTexSubImage3D gleswTexSubImage3D -#define glTexSubImage3DOES gleswTexSubImage3DOES -#define glTextureStorage1DEXT gleswTextureStorage1DEXT -#define glTextureStorage2DEXT gleswTextureStorage2DEXT -#define glTextureStorage3DEXT gleswTextureStorage3DEXT -#define glTextureViewEXT gleswTextureViewEXT -#define glTextureViewOES gleswTextureViewOES -#define glTransformFeedbackVaryings gleswTransformFeedbackVaryings -#define glTransformPathNV gleswTransformPathNV -#define glUniform1f gleswUniform1f -#define glUniform1fv gleswUniform1fv -#define glUniform1i gleswUniform1i -#define glUniform1iv gleswUniform1iv -#define glUniform1ui gleswUniform1ui -#define glUniform1uiv gleswUniform1uiv -#define glUniform2f gleswUniform2f -#define glUniform2fv gleswUniform2fv -#define glUniform2i gleswUniform2i -#define glUniform2iv gleswUniform2iv -#define glUniform2ui gleswUniform2ui -#define glUniform2uiv gleswUniform2uiv -#define glUniform3f gleswUniform3f -#define glUniform3fv gleswUniform3fv -#define glUniform3i gleswUniform3i -#define glUniform3iv gleswUniform3iv -#define glUniform3ui gleswUniform3ui -#define glUniform3uiv gleswUniform3uiv -#define glUniform4f gleswUniform4f -#define glUniform4fv gleswUniform4fv -#define glUniform4i gleswUniform4i -#define glUniform4iv gleswUniform4iv -#define glUniform4ui gleswUniform4ui -#define glUniform4uiv gleswUniform4uiv -#define glUniformBlockBinding gleswUniformBlockBinding -#define glUniformHandleui64NV gleswUniformHandleui64NV -#define glUniformHandleui64vNV gleswUniformHandleui64vNV -#define glUniformMatrix2fv gleswUniformMatrix2fv -#define glUniformMatrix2x3fv gleswUniformMatrix2x3fv -#define glUniformMatrix2x3fvNV gleswUniformMatrix2x3fvNV -#define glUniformMatrix2x4fv gleswUniformMatrix2x4fv -#define glUniformMatrix2x4fvNV gleswUniformMatrix2x4fvNV -#define glUniformMatrix3fv gleswUniformMatrix3fv -#define glUniformMatrix3x2fv gleswUniformMatrix3x2fv -#define glUniformMatrix3x2fvNV gleswUniformMatrix3x2fvNV -#define glUniformMatrix3x4fv gleswUniformMatrix3x4fv -#define glUniformMatrix3x4fvNV gleswUniformMatrix3x4fvNV -#define glUniformMatrix4fv gleswUniformMatrix4fv -#define glUniformMatrix4x2fv gleswUniformMatrix4x2fv -#define glUniformMatrix4x2fvNV gleswUniformMatrix4x2fvNV -#define glUniformMatrix4x3fv gleswUniformMatrix4x3fv -#define glUniformMatrix4x3fvNV gleswUniformMatrix4x3fvNV -#define glUnmapBuffer gleswUnmapBuffer -#define glUnmapBufferOES gleswUnmapBufferOES -#define glUseProgram gleswUseProgram -#define glUseProgramStagesEXT gleswUseProgramStagesEXT -#define glValidateProgram gleswValidateProgram -#define glValidateProgramPipelineEXT gleswValidateProgramPipelineEXT -#define glVertexAttrib1f gleswVertexAttrib1f -#define glVertexAttrib1fv gleswVertexAttrib1fv -#define glVertexAttrib2f gleswVertexAttrib2f -#define glVertexAttrib2fv gleswVertexAttrib2fv -#define glVertexAttrib3f gleswVertexAttrib3f -#define glVertexAttrib3fv gleswVertexAttrib3fv -#define glVertexAttrib4f gleswVertexAttrib4f -#define glVertexAttrib4fv gleswVertexAttrib4fv -#define glVertexAttribDivisor gleswVertexAttribDivisor -#define glVertexAttribDivisorANGLE gleswVertexAttribDivisorANGLE -#define glVertexAttribDivisorEXT gleswVertexAttribDivisorEXT -#define glVertexAttribDivisorNV gleswVertexAttribDivisorNV -#define glVertexAttribI4i gleswVertexAttribI4i -#define glVertexAttribI4iv gleswVertexAttribI4iv -#define glVertexAttribI4ui gleswVertexAttribI4ui -#define glVertexAttribI4uiv gleswVertexAttribI4uiv -#define glVertexAttribIPointer gleswVertexAttribIPointer -#define glVertexAttribPointer gleswVertexAttribPointer -#define glViewport gleswViewport -#define glViewportArrayvNV gleswViewportArrayvNV -#define glViewportIndexedfNV gleswViewportIndexedfNV -#define glViewportIndexedfvNV gleswViewportIndexedfvNV -#define glWaitSync gleswWaitSync -#define glWaitSyncAPPLE gleswWaitSyncAPPLE -#define glWeightPathsNV gleswWeightPathsNV - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/RenderSystems/GLES2/include/KHR/khrplatform.h b/RenderSystems/GLES2/include/KHR/khrplatform.h deleted file mode 100644 index 5b4c7b58fe4..00000000000 --- a/RenderSystems/GLES2/include/KHR/khrplatform.h +++ /dev/null @@ -1,269 +0,0 @@ -#ifndef __khrplatform_h_ -#define __khrplatform_h_ - -/* -** Copyright (c) 2008-2009 The Khronos Group Inc. -** -** Permission is hereby granted, free of charge, to any person obtaining a -** copy of this software and/or associated documentation files (the -** "Materials"), to deal in the Materials without restriction, including -** without limitation the rights to use, copy, modify, merge, publish, -** distribute, sublicense, and/or sell copies of the Materials, and to -** permit persons to whom the Materials are furnished to do so, subject to -** the following conditions: -** -** The above copyright notice and this permission notice shall be included -** in all copies or substantial portions of the Materials. -** -** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. -*/ - -/* Khronos platform-specific types and definitions. - * - * $Revision: 9356 $ on $Date: 2009-10-21 02:52:25 -0700 (Wed, 21 Oct 2009) $ - * - * Adopters may modify this file to suit their platform. Adopters are - * encouraged to submit platform specific modifications to the Khronos - * group so that they can be included in future versions of this file. - * Please submit changes by sending them to the public Khronos Bugzilla - * (http://khronos.org/bugzilla) by filing a bug against product - * "Khronos (general)" component "Registry". - * - * A predefined template which fills in some of the bug fields can be - * reached using http://tinyurl.com/khrplatform-h-bugreport, but you - * must create a Bugzilla login first. - * - * - * See the Implementer's Guidelines for information about where this file - * should be located on your system and for more details of its use: - * http://www.khronos.org/registry/implementers_guide.pdf - * - * This file should be included as - * #include - * by Khronos client API header files that use its types and defines. - * - * The types in khrplatform.h should only be used to define API-specific types. - * - * Types defined in khrplatform.h: - * khronos_int8_t signed 8 bit - * khronos_uint8_t unsigned 8 bit - * khronos_int16_t signed 16 bit - * khronos_uint16_t unsigned 16 bit - * khronos_int32_t signed 32 bit - * khronos_uint32_t unsigned 32 bit - * khronos_int64_t signed 64 bit - * khronos_uint64_t unsigned 64 bit - * khronos_intptr_t signed same number of bits as a pointer - * khronos_uintptr_t unsigned same number of bits as a pointer - * khronos_ssize_t signed size - * khronos_usize_t unsigned size - * khronos_float_t signed 32 bit floating point - * khronos_time_ns_t unsigned 64 bit time in nanoseconds - * khronos_utime_nanoseconds_t unsigned time interval or absolute time in - * nanoseconds - * khronos_stime_nanoseconds_t signed time interval in nanoseconds - * khronos_boolean_enum_t enumerated boolean type. This should - * only be used as a base type when a client API's boolean type is - * an enum. Client APIs which use an integer or other type for - * booleans cannot use this as the base type for their boolean. - * - * Tokens defined in khrplatform.h: - * - * KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values. - * - * KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0. - * KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0. - * - * Calling convention macros defined in this file: - * KHRONOS_APICALL - * KHRONOS_APIENTRY - * KHRONOS_APIATTRIBUTES - * - * These may be used in function prototypes as: - * - * KHRONOS_APICALL void KHRONOS_APIENTRY funcname( - * int arg1, - * int arg2) KHRONOS_APIATTRIBUTES; - */ - -/*------------------------------------------------------------------------- - * Definition of KHRONOS_APICALL - *------------------------------------------------------------------------- - * This precedes the return type of the function in the function prototype. - */ -#if defined(_WIN32) && !defined(__SCITECH_SNAP__) && !defined(ANDROID) -# define KHRONOS_APICALL __declspec(dllimport) -#elif defined (__SYMBIAN32__) -# define KHRONOS_APICALL IMPORT_C -#else -# define KHRONOS_APICALL -#endif - -/*------------------------------------------------------------------------- - * Definition of KHRONOS_APIENTRY - *------------------------------------------------------------------------- - * This follows the return type of the function and precedes the function - * name in the function prototype. - */ -#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__) && !defined(ANDROID) - /* Win32 but not WinCE */ -# define KHRONOS_APIENTRY __stdcall -#else -# define KHRONOS_APIENTRY -#endif - -/*------------------------------------------------------------------------- - * Definition of KHRONOS_APIATTRIBUTES - *------------------------------------------------------------------------- - * This follows the closing parenthesis of the function prototype arguments. - */ -#if defined (__ARMCC_2__) -#define KHRONOS_APIATTRIBUTES __softfp -#else -#define KHRONOS_APIATTRIBUTES -#endif - -/*------------------------------------------------------------------------- - * basic type definitions - *-----------------------------------------------------------------------*/ -#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__) - - -/* - * Using - */ -#include -typedef int32_t khronos_int32_t; -typedef uint32_t khronos_uint32_t; -typedef int64_t khronos_int64_t; -typedef uint64_t khronos_uint64_t; -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 - -#elif defined(__VMS ) || defined(__sgi) - -/* - * Using - */ -#include -typedef int32_t khronos_int32_t; -typedef uint32_t khronos_uint32_t; -typedef int64_t khronos_int64_t; -typedef uint64_t khronos_uint64_t; -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 - -#elif defined(_WIN32) && !defined(__SCITECH_SNAP__) && !defined(ANDROID) - -/* - * Win32 - */ -typedef __int32 khronos_int32_t; -typedef unsigned __int32 khronos_uint32_t; -typedef __int64 khronos_int64_t; -typedef unsigned __int64 khronos_uint64_t; -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 - -#elif defined(__sun__) || defined(__digital__) - -/* - * Sun or Digital - */ -typedef int khronos_int32_t; -typedef unsigned int khronos_uint32_t; -#if defined(__arch64__) || defined(_LP64) -typedef long int khronos_int64_t; -typedef unsigned long int khronos_uint64_t; -#else -typedef long long int khronos_int64_t; -typedef unsigned long long int khronos_uint64_t; -#endif /* __arch64__ */ -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 - -#elif 0 - -/* - * Hypothetical platform with no float or int64 support - */ -typedef int khronos_int32_t; -typedef unsigned int khronos_uint32_t; -#define KHRONOS_SUPPORT_INT64 0 -#define KHRONOS_SUPPORT_FLOAT 0 - -#else - -/* - * Generic fallback - */ -#include -typedef int32_t khronos_int32_t; -typedef uint32_t khronos_uint32_t; -typedef int64_t khronos_int64_t; -typedef uint64_t khronos_uint64_t; -#define KHRONOS_SUPPORT_INT64 1 -#define KHRONOS_SUPPORT_FLOAT 1 - -#endif - - -/* - * Types that are (so far) the same on all platforms - */ -typedef signed char khronos_int8_t; -typedef unsigned char khronos_uint8_t; -typedef signed short int khronos_int16_t; -typedef unsigned short int khronos_uint16_t; -typedef signed long int khronos_intptr_t; -typedef unsigned long int khronos_uintptr_t; -typedef signed long int khronos_ssize_t; -typedef unsigned long int khronos_usize_t; - -#if KHRONOS_SUPPORT_FLOAT -/* - * Float type - */ -typedef float khronos_float_t; -#endif - -#if KHRONOS_SUPPORT_INT64 -/* Time types - * - * These types can be used to represent a time interval in nanoseconds or - * an absolute Unadjusted System Time. Unadjusted System Time is the number - * of nanoseconds since some arbitrary system event (e.g. since the last - * time the system booted). The Unadjusted System Time is an unsigned - * 64 bit value that wraps back to 0 every 584 years. Time intervals - * may be either signed or unsigned. - */ -typedef khronos_uint64_t khronos_utime_nanoseconds_t; -typedef khronos_int64_t khronos_stime_nanoseconds_t; -#endif - -/* - * Dummy value used to pad enum types to 32 bits. - */ -#ifndef KHRONOS_MAX_ENUM -#define KHRONOS_MAX_ENUM 0x7FFFFFFF -#endif - -/* - * Enumerated boolean type - * - * Values other than zero should be considered to be true. Therefore - * comparisons should not be made against KHRONOS_TRUE. - */ -typedef enum { - KHRONOS_FALSE = 0, - KHRONOS_TRUE = 1, - KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM -} khronos_boolean_enum_t; - -#endif /* __khrplatform_h_ */ diff --git a/RenderSystems/GLES2/include/OgreGLES2FBOMultiRenderTarget.h b/RenderSystems/GLES2/include/OgreGLES2FBOMultiRenderTarget.h deleted file mode 100644 index f3f7dce81ce..00000000000 --- a/RenderSystems/GLES2/include/OgreGLES2FBOMultiRenderTarget.h +++ /dev/null @@ -1,64 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLES2MULTIRENDERTARGET_H__ -#define __GLES2MULTIRENDERTARGET_H__ - -#include "OgreGLES2FrameBufferObject.h" - -namespace Ogre { - - class GLES2FBOManager; - - /** MultiRenderTarget for GL ES 2.x. - */ - class _OgreGLES2Export GLES2FBOMultiRenderTarget : public MultiRenderTarget, public GLRenderTarget - { - public: - GLES2FBOMultiRenderTarget(GLES2FBOManager *manager, const String &name); - ~GLES2FBOMultiRenderTarget(); - - void getCustomAttribute( const String& name, void *pData ) override; - GLContext* getContext() const override { return fbo.getContext(); } - GLFrameBufferObjectCommon* getFBO() override { return &fbo; } - - bool requiresTextureFlipping() const override { return true; } - - /// Override so we can attach the depth buffer to the FBO - bool attachDepthBuffer( DepthBuffer *depthBuffer ) override; - void detachDepthBuffer() override; - void _detachDepthBuffer() override; - private: - void bindSurfaceImpl(size_t attachment, RenderTexture *target) override; - void unbindSurfaceImpl(size_t attachment) override; - GLES2FrameBufferObject fbo; - }; - -} - -#endif // __GLES2MULTIRENDERTARGET_H__ diff --git a/RenderSystems/GLES2/include/OgreGLES2FBORenderTexture.h b/RenderSystems/GLES2/include/OgreGLES2FBORenderTexture.h deleted file mode 100644 index 74c8456552d..00000000000 --- a/RenderSystems/GLES2/include/OgreGLES2FBORenderTexture.h +++ /dev/null @@ -1,121 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OgreGLES2FBORTT_H__ -#define __OgreGLES2FBORTT_H__ - -#include "OgreGLES2FrameBufferObject.h" -#include "OgreGLES2ManagedResource.h" -#include "OgreGLRenderTexture.h" -#include "OgreGLContext.h" - -namespace Ogre { - class GLES2FBOManager; - class GLES2RenderBuffer; - - /** RenderTexture for GL ES 2 FBO - */ - class _OgreGLES2Export GLES2FBORenderTexture: public GLRenderTexture MANAGED_RESOURCE - { - public: - GLES2FBORenderTexture(GLES2FBOManager *manager, const String &name, const GLSurfaceDesc &target, bool writeGamma, uint fsaa); - - void getCustomAttribute(const String& name, void* pData) override; - - /// Override needed to deal with multisample buffers - void swapBuffers() override; - - /// Override so we can attach the depth buffer to the FBO - bool attachDepthBuffer( DepthBuffer *depthBuffer ) override; - void detachDepthBuffer() override; - void _detachDepthBuffer() override; - - GLContext* getContext() const override { return mFB.getContext(); } - GLFrameBufferObjectCommon* getFBO() override { return &mFB; } - protected: - GLES2FrameBufferObject mFB; - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - /** See AndroidResource. */ - void notifyOnContextLost() override; - - /** See AndroidResource. */ - void notifyOnContextReset() override; -#endif - }; - - /** Factory for GL ES 2 Frame Buffer Objects, and related things. - */ - class _OgreGLES2Export GLES2FBOManager: public GLRTTManager - { - public: - GLES2FBOManager(); - ~GLES2FBOManager(); - - /** Bind a certain render target if it is a FBO. If it is not a FBO, bind the - main frame buffer. - */ - void bind(RenderTarget *target) override; - - /** Get best depth and stencil supported for given internalFormat - */ - void getBestDepthStencil(PixelFormat internalFormat, uint32 *depthFormat, uint32 *stencilFormat) override; - - GLES2FBORenderTexture *createRenderTexture(const String &name, - const GLSurfaceDesc &target, bool writeGamma, uint fsaa) override; - - /** Request a render buffer. If format is GL_NONE, return a zero buffer. - */ - GLSurfaceDesc requestRenderBuffer(GLenum format, uint32 width, uint32 height, uint fsaa); - - /** Get a FBO without depth/stencil for temporary use, like blitting between textures. - */ - GLuint getTemporaryFBO() { return mTempFBO; } - - /** Detects all supported fbo's and recreates the tempory fbo */ - void _reload(); - - GLint getMaxFSAASamples() { return mMaxFSAASamples; } - - private: - // map(format, sizex, sizey) -> [GLSurface*,refcount] - - /** Temporary FBO identifier - */ - GLuint mTempFBO; - - GLint mMaxFSAASamples; - - /** Detect allowed FBO formats */ - void detectFBOFormats(); - GLuint _tryFormat(GLenum depthFormat, GLenum stencilFormat); - bool _tryPackedFormat(GLenum packedFormat); - void _createTempFramebuffer(GLuint internalFormat, GLuint fmt, GLenum dataType, GLuint &fb, GLuint &tid); - }; -} - -#endif diff --git a/RenderSystems/GLES2/include/OgreGLES2FrameBufferObject.h b/RenderSystems/GLES2/include/OgreGLES2FrameBufferObject.h deleted file mode 100644 index 3ad41dd6e4b..00000000000 --- a/RenderSystems/GLES2/include/OgreGLES2FrameBufferObject.h +++ /dev/null @@ -1,80 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OgreGLES2FBO_H__ -#define __OgreGLES2FBO_H__ - -#include "OgreGLRenderTexture.h" -#include "OgreGLContext.h" -#include "OgreGLES2ManagedResource.h" - -namespace Ogre { - - class GLES2FBOManager; - - /** Frame Buffer Object abstraction. - */ - class _OgreGLES2Export GLES2FrameBufferObject : public GLFrameBufferObjectCommon - { - public: - GLES2FrameBufferObject(GLES2FBOManager *manager, uint fsaa); - ~GLES2FrameBufferObject(); - - bool bind(bool recreateIfNeeded) override; - - /** Swap buffers - only useful when using multisample buffers. - */ - void swapBuffers(); - - /** This function acts very similar to @see GLES2FBORenderTexture::attachDepthBuffer - The difference between D3D & OGL is that D3D setups the DepthBuffer before rendering, - while OGL setups the DepthBuffer per FBO. So the DepthBuffer (RenderBuffer) needs to - be attached for OGL. - */ - void attachDepthBuffer( DepthBuffer *depthBuffer ); - void detachDepthBuffer(); - - GLES2FBOManager *getManager() { return mManager; } - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - /** See AndroidResource. */ - void notifyOnContextLost(); - - /** See AndroidResource. */ - void notifyOnContextReset(const GLSurfaceDesc &target); -#endif - - private: - GLES2FBOManager *mManager; - GLSurfaceDesc mMultisampleColourBuffer; - - void initialise() override; - }; - -} - -#endif diff --git a/RenderSystems/GLES2/include/OgreGLES2HardwareBuffer.h b/RenderSystems/GLES2/include/OgreGLES2HardwareBuffer.h deleted file mode 100644 index ab7a9c66dc7..00000000000 --- a/RenderSystems/GLES2/include/OgreGLES2HardwareBuffer.h +++ /dev/null @@ -1,86 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLES2HardwareBuffer_H__ -#define __GLES2HardwareBuffer_H__ - -#include "OgreGLES2Prerequisites.h" -#include "OgreHardwareBuffer.h" -#include "OgreGLES2ManagedResource.h" - -namespace Ogre { - class GLES2RenderSystem; - class GLES2HardwareBuffer : public HardwareBuffer MANAGED_RESOURCE - { - private: - GLenum mTarget; - GLuint mBufferId; - GLES2RenderSystem* mRenderSystem; - - // for UBO/ SSBO - GLint mBindingPoint; - - /// Utility function to get the correct GL usage based on HBU's - static GLenum getGLUsage(uint32 usage); - - void writeDataImpl(size_t offset, size_t length, const void* pSource, bool discardWholeBuffer); - public: - void createBuffer(); - - void destroyBuffer(); - - void* lockImpl(size_t offset, size_t length, HardwareBuffer::LockOptions options) override; - - void unlockImpl() override; - - GLES2HardwareBuffer(GLenum target, size_t sizeInBytes, GLenum usage, bool useShadowBuffer); - ~GLES2HardwareBuffer(); - - void readData(size_t offset, size_t length, void* pDest) override; - - void writeData(size_t offset, size_t length, const void* pSource, - bool discardWholeBuffer = false) override; - - void copyData(HardwareBuffer& srcBuffer, size_t srcOffset, size_t dstOffset, size_t length, - bool discardWholeBuffer) override; - - void _updateFromShadow() override; - - GLuint getGLBufferId(void) const { return mBufferId; } - - void setGLBufferBinding(GLint binding); - GLint getGLBufferBinding(void) const { return mBindingPoint; } - -#if HANDLE_CONTEXT_LOSS - void notifyOnContextLost() override; - void notifyOnContextReset() override; -#endif - }; -} - -#endif diff --git a/RenderSystems/GLES2/include/OgreGLES2HardwareBufferManager.h b/RenderSystems/GLES2/include/OgreGLES2HardwareBufferManager.h deleted file mode 100644 index b050b2c34c4..00000000000 --- a/RenderSystems/GLES2/include/OgreGLES2HardwareBufferManager.h +++ /dev/null @@ -1,68 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLES2HardwareBufferManager_H__ -#define __GLES2HardwareBufferManager_H__ - -#include "OgreGLES2Prerequisites.h" -#include "OgreHardwareBufferManager.h" -#include "OgreGLES2RenderSystem.h" - -namespace Ogre { - class GLES2StateCacheManager; - - /** Implementation of HardwareBufferManager for OpenGL ES. */ - class _OgreGLES2Export GLES2HardwareBufferManager : public HardwareBufferManager - { - protected: - GLES2RenderSystem* mRenderSystem; - /// Internal method for creates a new vertex declaration, may be overridden by certain rendering APIs - VertexDeclaration* createVertexDeclarationImpl(void) override; - public: - GLES2HardwareBufferManager(); - virtual ~GLES2HardwareBufferManager(); - /// Creates a vertex buffer - HardwareVertexBufferSharedPtr createVertexBuffer(size_t vertexSize, - size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer = false) override; - /// Create a hardware vertex buffer - HardwareIndexBufferSharedPtr createIndexBuffer( - HardwareIndexBuffer::IndexType itype, size_t numIndexes, - HardwareBuffer::Usage usage, bool useShadowBuffer = false) override; - /// Create a render to vertex buffer - RenderToVertexBufferSharedPtr createRenderToVertexBuffer() override; - /// Create a uniform buffer - HardwareBufferPtr createUniformBuffer(size_t sizeBytes, HardwareBufferUsage usage, - bool useShadowBuffer) override; - /// Utility function to get the correct GL type based on VET's - static GLenum getGLType(VertexElementType type); - - void notifyContextDestroyed(GLContext* context); - }; -} - -#endif diff --git a/RenderSystems/GLES2/include/OgreGLES2HardwareOcclusionQuery.h b/RenderSystems/GLES2/include/OgreGLES2HardwareOcclusionQuery.h deleted file mode 100644 index 44fe56b217e..00000000000 --- a/RenderSystems/GLES2/include/OgreGLES2HardwareOcclusionQuery.h +++ /dev/null @@ -1,96 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLES2HARDWAREOCCLUSIONQUERY_H__ -#define __GLES2HARDWAREOCCLUSIONQUERY_H__ - -#include "OgreGLES2Prerequisites.h" -#include "OgreHardwareOcclusionQuery.h" -#include "OgreGLES2ManagedResource.h" - -namespace Ogre { - - -// If you use multiple rendering passes you can test only the first pass and all other passes don't have to be rendered -// if the first pass result has too few pixels visible. - -// Be sure to render all occluder first and whats out so the RenderQue don't switch places on -// the occluding objects and the tested objects because it thinks it's more effective.. - -class _OgreGLES2Export GLES2HardwareOcclusionQuery : public HardwareOcclusionQuery MANAGED_RESOURCE -{ -//---------------------------------------------------------------------- -// Public methods -//-- -public: - /** - * Default object constructor - * - */ - GLES2HardwareOcclusionQuery(); - /** - * Object destructor - */ - ~GLES2HardwareOcclusionQuery(); - - //------------------------------------------------------------------ - // Occlusion query functions (see base class documentation for this) - //-- - void beginOcclusionQuery() override; - void endOcclusionQuery() override; - bool pullOcclusionQuery( unsigned int* NumOfFragments) override; - bool isStillOutstanding(void) override; - - -//---------------------------------------------------------------------- -// private members -//-- -private: - - GLuint mQueryID; - - void createQuery(); - - void destroyQuery(); - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN -protected: - - /** See AndroidResource. */ - void notifyOnContextLost() override; - - /** See AndroidResource. */ - void notifyOnContextReset() override; -#endif - -}; - -} - -#endif - diff --git a/RenderSystems/GLES2/include/OgreGLES2HardwarePixelBuffer.h b/RenderSystems/GLES2/include/OgreGLES2HardwarePixelBuffer.h deleted file mode 100644 index 368c4bbe9b1..00000000000 --- a/RenderSystems/GLES2/include/OgreGLES2HardwarePixelBuffer.h +++ /dev/null @@ -1,101 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLES2HardwarePixelBuffer_H__ -#define __GLES2HardwarePixelBuffer_H__ - -#include "OgreGLES2Prerequisites.h" -#include "OgreGLHardwarePixelBufferCommon.h" - -namespace Ogre { - class GLES2TextureBuffer: public GLHardwarePixelBufferCommon - { - public: - /** Texture constructor */ - GLES2TextureBuffer(GLES2Texture* parent, GLint face, GLint level, GLint width, - GLint height, GLint depth); - virtual ~GLES2TextureBuffer(); - - void bindToFramebuffer(uint32 attachment, uint32 zoffset) override; - - /// Upload a box of pixels to this buffer on the card - void upload(const PixelBox &data, const Box &dest) override; - - /// Download a box of pixels from the card - void download(const PixelBox &data) override; - - /// Hardware implementation of blitFromMemory - void blitFromMemory(const PixelBox &src_orig, const Box &dstBox) override; - - // Copy from framebuffer - void copyFromFramebuffer(size_t zoffset); - - /// @copydoc HardwarePixelBuffer::blit - void blit(const HardwarePixelBufferSharedPtr &src, const Box &srcBox, const Box &dstBox) override; - void blitToMemory(const Box &srcBox, const PixelBox &dst) override; - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - // Friends. - protected: - friend class GLES2Texture; - - void updateTextureId(GLuint textureID); -#endif - - protected: - // Blitting implementation - void blitFromTexture(GLES2TextureBuffer *src, const Box &srcBox, const Box &dstBox); - void _blitFromMemory(const PixelBox &src, const Box &dst); - - // In case this is a texture level - GLenum mTarget; - GLenum mFaceTarget; // same as mTarget in case of GL_TEXTURE_xD, but cubemap face for cubemaps - GLuint mTextureID; - GLint mLevel; - - void buildMipmaps(const PixelBox &data); - }; - - class GLES2RenderBuffer: public GLHardwarePixelBufferCommon - { - void blitFromMemory(const PixelBox& src, const Box& dstBox) override { OgreAssertDbg(false, "Not supported"); } - void blitToMemory(const Box& srcBox, const PixelBox& dst) override { OgreAssertDbg(false, "Not supported"); } - public: - GLES2RenderBuffer(GLenum format, uint32 width, uint32 height, GLsizei numSamples); - virtual ~GLES2RenderBuffer(); - - void bindToFramebuffer(uint32 attachment, uint32 zoffset) override; - - protected: - // In case this is a render buffer - GLuint mRenderbufferID; - GLsizei mNumSamples; - }; -} - -#endif diff --git a/RenderSystems/GLES2/include/OgreGLES2ManagedResource.h b/RenderSystems/GLES2/include/OgreGLES2ManagedResource.h deleted file mode 100644 index 1e0a16e011f..00000000000 --- a/RenderSystems/GLES2/include/OgreGLES2ManagedResource.h +++ /dev/null @@ -1,71 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLES2ManagedResource_H__ -#define __GLES2ManagedResource_H__ - -#include "OgreGLES2Prerequisites.h" - -namespace Ogre { - -#define HANDLE_CONTEXT_LOSS (OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN) - -#if HANDLE_CONTEXT_LOSS -# define MANAGED_RESOURCE , public GLES2ManagedResource -# define MANAGED_RESOURCE_SINGLE : public GLES2ManagedResource - - class EGLContext; - - /** Represents a GLES2 rendering resource. - Provide unified interface to - handle various device states. - */ - class _OgrePrivate GLES2ManagedResource - { - - // Interface. - public: - - // Called immediately after the Android context has entered a lost state. - virtual void notifyOnContextLost() {} - - // Called immediately after the Android context has been reset. - virtual void notifyOnContextReset() {} - - public: - GLES2ManagedResource(); - virtual ~GLES2ManagedResource(); - }; - -#else -# define MANAGED_RESOURCE -# define MANAGED_RESOURCE_SINGLE -#endif - -} - -#endif diff --git a/RenderSystems/GLES2/include/OgreGLES2ManagedResourceManager.h b/RenderSystems/GLES2/include/OgreGLES2ManagedResourceManager.h deleted file mode 100644 index 37787486e3a..00000000000 --- a/RenderSystems/GLES2/include/OgreGLES2ManagedResourceManager.h +++ /dev/null @@ -1,81 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLES2ManagedResourceManager_H__ -#define __GLES2ManagedResourceManager_H__ - -#include "OgreGLES2Prerequisites.h" - -namespace Ogre { - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - - class EGLContext; - class GLES2ManagedResource; - - class _OgrePrivate GLES2ManagedResourceManager : public ResourceAlloc - { - // Interface. - public: - - // Called immediately after the Android context has entered a lost state. - void notifyOnContextLost(); - - // Called immediately after the Android context has been reset. - void notifyOnContextReset(); - - GLES2ManagedResourceManager(); - ~GLES2ManagedResourceManager(); - - // Friends. - protected: - friend class GLES2ManagedResource; - - // Types. - protected: - typedef std::vector ResourceContainer; - typedef ResourceContainer::iterator ResourceContainerIterator; - - // Protected methods. - protected: - - // Called when new resource created. - void _notifyResourceCreated (GLES2ManagedResource* pResource); - - // Called when resource is about to be destroyed. - void _notifyResourceDestroyed (GLES2ManagedResource* pResource); - - // Attributes. - protected: - ResourceContainer mResources; - }; - -#endif - -} - -#endif diff --git a/RenderSystems/GLES2/include/OgreGLES2PixelFormat.h b/RenderSystems/GLES2/include/OgreGLES2PixelFormat.h deleted file mode 100644 index 7e447a57991..00000000000 --- a/RenderSystems/GLES2/include/OgreGLES2PixelFormat.h +++ /dev/null @@ -1,74 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLES2PixelFormat_H__ -#define __GLES2PixelFormat_H__ - -#include "OgreGLES2Prerequisites.h" -#include "OgrePixelFormat.h" - -namespace Ogre { - /** - * Class to do pixel format mapping between GL and OGRE - */ - class _OgreGLES2Export GLES2PixelUtil - { - public: - /// use sized pixel formats. (to be used with GLES3) - static void useSizedFormats(); - - /** Takes the OGRE pixel format and returns the appropriate GL one - @returns a GLenum describing the format, or 0 if there is no exactly matching - one (and conversion is needed) - */ - static GLenum getGLOriginFormat(PixelFormat mFormat); - - /** Takes the OGRE pixel format and returns type that must be provided - to GL as data type for reading it into the GPU - @returns a GLenum describing the data type, or 0 if there is no exactly matching - one (and conversion is needed) - */ - static GLenum getGLOriginDataType(PixelFormat mFormat); - - /** Takes the OGRE pixel format and returns the type that must be provided - to GL as internal format. GL_NONE if no match exists. - @param mFormat The pixel format - @param hwGamma Whether a hardware gamma-corrected version is requested - */ - static GLenum getGLInternalFormat(PixelFormat mFormat, bool hwGamma = false); - - /** Function to get the closest matching OGRE format to an internal GL format. To be - precise, the format will be chosen that is most efficient to transfer to the card - without losing precision. - @remarks It is valid for this function to always return PF_A8R8G8B8. - */ - static PixelFormat getClosestOGREFormat(GLenum fmt); - }; -} - -#endif diff --git a/RenderSystems/GLES2/include/OgreGLES2Plugin.h b/RenderSystems/GLES2/include/OgreGLES2Plugin.h deleted file mode 100644 index 922300eab8a..00000000000 --- a/RenderSystems/GLES2/include/OgreGLES2Plugin.h +++ /dev/null @@ -1,66 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLES2Plugin_H__ -#define __GLES2Plugin_H__ - -#include "OgrePlugin.h" -#include "OgreGLES2Exports.h" - -namespace Ogre -{ - class GLES2RenderSystem; - - /** Plugin instance for GL ES 2 Manager */ - class _OgreGLES2Export GLES2Plugin : public Plugin - { - - public: - GLES2Plugin(); - - /// @copydoc Plugin::getName - const String& getName() const override; - - /// @copydoc Plugin::install - void install() override; - - /// @copydoc Plugin::initialise - void initialise() override; - - /// @copydoc Plugin::shutdown - void shutdown() override; - - /// @copydoc Plugin::uninstall - void uninstall() override; - protected: - GLES2RenderSystem* mRenderSystem; - - }; -} - -#endif diff --git a/RenderSystems/GLES2/include/OgreGLES2Prerequisites.h b/RenderSystems/GLES2/include/OgreGLES2Prerequisites.h deleted file mode 100644 index f68af7eb86f..00000000000 --- a/RenderSystems/GLES2/include/OgreGLES2Prerequisites.h +++ /dev/null @@ -1,122 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLES2Prerequisites_H__ -#define __GLES2Prerequisites_H__ - -#include "OgrePrerequisites.h" - -#include "OgreGLES2Exports.h" -#include "OgreGLES2Config.h" - -namespace Ogre { - class GLContext; - typedef GLContext GLES2Context; -} - -#include - -#if (OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS) -# ifdef __OBJC__ -# include -# endif -#elif (OGRE_PLATFORM == OGRE_PLATFORM_WIN32) -# ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN 1 -# endif -# ifndef NOMINMAX -# define NOMINMAX // required to stop windows.h messing up std::min -# endif -#endif - -#if (OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS) -namespace Ogre { -extern float EAGLCurrentOSVersion; -} -#define OGRE_IF_IOS_VERSION_IS_GREATER_THAN(vers) \ - if(EAGLCurrentOSVersion >= vers) -#else -#define OGRE_IF_IOS_VERSION_IS_GREATER_THAN(vers) -#endif - -#define getGLES2RenderSystem() dynamic_cast(Root::getSingleton().getRenderSystem()) - -// Copy this definition from desktop GL. Used for polygon modes. -#ifndef GL_FILL -# define GL_FILL 0x1B02 -#endif - -namespace Ogre { - class GLNativeSupport; - class GLES2GpuProgram; - class GLES2Texture; - typedef shared_ptr GLES2GpuProgramPtr; - typedef shared_ptr GLES2TexturePtr; -}; - -#if OGRE_NO_GLES3_SUPPORT == 0 -#undef GL_DEPTH_COMPONENT32_OES -#define GL_DEPTH_COMPONENT32_OES GL_DEPTH_COMPONENT32F -#endif - -#if (OGRE_PLATFORM == OGRE_PLATFORM_WIN32) -// an error in all windows gles sdks... -# undef GL_OES_get_program_binary -#endif - -#define ENABLE_GL_CHECK 0 - -#if ENABLE_GL_CHECK -#include "OgreLogManager.h" -#define OGRE_CHECK_GL_ERROR(glFunc) \ -{ \ - glFunc; \ - int e = glGetError(); \ - if (e != 0) \ - { \ - const char * errorString = ""; \ - switch(e) \ - { \ - case GL_INVALID_ENUM: errorString = "GL_INVALID_ENUM"; break; \ - case GL_INVALID_VALUE: errorString = "GL_INVALID_VALUE"; break; \ - case GL_INVALID_OPERATION: errorString = "GL_INVALID_OPERATION"; break; \ - case GL_OUT_OF_MEMORY: errorString = "GL_OUT_OF_MEMORY"; break; \ - default: break; \ - } \ - String funcname = #glFunc; \ - funcname = funcname.substr(0, funcname.find('(')); \ - LogManager::getSingleton().logError(StringUtil::format("%s failed with %s in %s at %s(%d)", \ - funcname.c_str(), errorString, __FUNCTION__, \ - __FILE__, __LINE__)); \ - } \ -} -#else -# define OGRE_CHECK_GL_ERROR(glFunc) { glFunc; } -#endif - -#endif diff --git a/RenderSystems/GLES2/include/OgreGLES2RenderSystem.h b/RenderSystems/GLES2/include/OgreGLES2RenderSystem.h deleted file mode 100644 index 4a618d88bec..00000000000 --- a/RenderSystems/GLES2/include/OgreGLES2RenderSystem.h +++ /dev/null @@ -1,241 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLES2RenderSystem_H__ -#define __GLES2RenderSystem_H__ - -#include "OgreGLES2Prerequisites.h" - -#include "OgreMaterialManager.h" -#include "OgreRenderSystem.h" -#include "OgreGLSLESProgram.h" -#include "OgreGLRenderSystemCommon.h" - -namespace Ogre { - /** \addtogroup RenderSystems RenderSystems - * @{ - */ - /** \defgroup GLES2 GLES2 - * Implementation of GL ES 2.x as a rendering system. - * @{ - */ - class GLES2FBOManager; - class GLSLESProgramCommon; - class GLSLESProgramManager; - class GLSLESProgramFactory; - class GLES2StateCacheManager; -#if !OGRE_NO_GLES2_CG_SUPPORT - class GLSLESCgProgramFactory; -#endif - class HardwareBufferManager; -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - class GLES2ManagedResourceManager; -#endif - - /** - Implementation of GL ES 2.x as a rendering system. - */ - class _OgreGLES2Export GLES2RenderSystem : public GLRenderSystemCommon - { - private: - /// Last min & mip filtering options, so we can combine them - FilterOptions mMinFilter; - FilterOptions mMipFilter; - - /// Holds texture type settings for every stage - GLenum mTextureTypes[OGRE_MAX_TEXTURE_LAYERS]; - - /// State cache manager which responsible to reduce redundant state changes - GLES2StateCacheManager* mStateCacheManager; - - GLSLESProgramManager* mProgramManager; - GLSLESProgramFactory* mGLSLESProgramFactory; -#if !OGRE_NO_GLES2_CG_SUPPORT - GLSLESCgProgramFactory* mGLSLESCgProgramFactory; -#endif - HardwareBufferManager* mHardwareBufferManager; - - /// Check if the GL system has already been initialised - bool mGLInitialised; - - // local data member of _render that were moved here to improve performance - // (save allocations) - std::vector mRenderAttribsBound; - std::vector mRenderInstanceAttribsBound; - - GLenum mPolygonMode; - - GLSLESProgram* mCurrentVertexProgram; - GLSLESProgram* mCurrentFragmentProgram; - - GLenum getBlendMode(SceneBlendFactor ogreBlend) const; - void bindVertexElementToGpu(const VertexElement& elem, - const HardwareVertexBufferSharedPtr& vertexBuffer, - const size_t vertexStart) override; - - /** Initialises GL extensions, must be done AFTER the GL context has been - established. - */ - void initialiseExtensions(); - - // Mipmap count of the actual bounded texture - size_t mCurTexMipCount; - - public: - // Default constructor / destructor - GLES2RenderSystem(); - virtual ~GLES2RenderSystem(); - - // ---------------------------------- - // Overridden RenderSystem functions - // ---------------------------------- - - const String& getName(void) const override; - - void _initialise() override; - - RenderSystemCapabilities* createRenderSystemCapabilities() const override; - - void initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary) override; - - void shutdown(void) override; - - /// @copydoc RenderSystem::_createRenderWindow - RenderWindow* _createRenderWindow(const String &name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams = 0) override; - - /// @copydoc RenderSystem::_createDepthBufferFor - DepthBuffer* _createDepthBufferFor( RenderTarget *renderTarget ) override; - - /// @copydoc RenderSystem::createMultiRenderTarget - MultiRenderTarget * createMultiRenderTarget(const String & name) override; - - - void destroyRenderWindow(const String& name) override; - - // ----------------------------- - // Low-level overridden members - // ----------------------------- - void _setTexture(size_t unit, bool enabled, const TexturePtr &tex) override; - - void _setSampler(size_t unit, Sampler& sampler) override; - - void _setLineWidth(float width) override; - - void _setViewport(Viewport *vp) override; - - void _endFrame(void) override; - - void _setCullingMode(CullingMode mode) override; - - void _setDepthBufferParams(bool depthTest = true, bool depthWrite = true, CompareFunction depthFunction = CMPF_LESS_EQUAL) override; - - void _setDepthBias(float constantBias, float slopeScaleBias) override; - - void setColourBlendState(const ColourBlendState& state) override; - - void _setPolygonMode(PolygonMode level) override; - - void setStencilState(const StencilState& state) override; - - void _render(const RenderOperation& op) override; - - void setScissorTest(bool enabled, const Rect& rect = Rect()) override; - - void clearFrameBuffer(unsigned int buffers, - const ColourValue& colour = ColourValue::Black, - float depth = 1.0f, unsigned short stencil = 0) override; - HardwareOcclusionQuery* createHardwareOcclusionQuery(void) override; - - // ---------------------------------- - // GLES2RenderSystem specific members - // ---------------------------------- - GLES2StateCacheManager * _getStateCacheManager() { return mStateCacheManager; } - - /** Create VAO on current context */ - uint32 _createVao() override; - /** Bind VAO, context should be equal to current context, as VAOs are not shared */ - void _bindVao(GLContext* context, uint32 vao) override; - /** Destroy VAO immediately or defer if it was created on other context */ - void _destroyVao(GLContext* context, uint32 vao) override; - /** Destroy FBO immediately or defer if it was created on other context */ - void _destroyFbo(GLContext* context, uint32 fbo) override; - - /** Unregister a render target->context mapping. If the context of target - is the current context, change the context to the main context so it - can be destroyed safely. - - @note This is automatically called by the destructor of - GLContext. - */ - void _unregisterContext(GLContext *context) override; - /** Switch GL context, dealing with involved internal cached states too - */ - void _switchContext(GLContext *context); - void _oneTimeContextInitialization() override; - void initialiseContext(RenderWindow* primary); - /** - * Set current render target to target, enabling its GL context if needed - */ - void _setRenderTarget(RenderTarget *target) override; - - GLint convertCompareFunction(CompareFunction func) const; - GLint convertStencilOp(StencilOperation op, bool invert = false) const; - - void bindGpuProgram(GpuProgram* prg) override; - void unbindGpuProgram(GpuProgramType gptype) override; - void bindGpuProgramParameters(GpuProgramType gptype, const GpuProgramParametersPtr& params, uint16 mask) override; - - /// @copydoc RenderSystem::_setAlphaRejectSettings - void _setAlphaRejectSettings( CompareFunction func, unsigned char value, bool alphaToCoverage ) override; - - void _destroyDepthBuffer(RenderTarget* pRenderWnd); - - /// @copydoc RenderSystem::beginProfileEvent - void beginProfileEvent( const String &eventName ) override; - - /// @copydoc RenderSystem::endProfileEvent - void endProfileEvent( void ) override; - - /// @copydoc RenderSystem::markProfileEvent - void markProfileEvent( const String &eventName ) override; - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - void resetRenderer(RenderWindow* pRenderWnd) override; - - void notifyOnContextLost() override; - - static GLES2ManagedResourceManager* getResourceManager(); - private: - static GLES2ManagedResourceManager* mResourceManager; -#endif - void _copyContentsToMemory(Viewport* vp, const Box& src, const PixelBox& dst, RenderWindow::FrameBuffer buffer) override; - }; -} - -#endif diff --git a/RenderSystems/GLES2/include/OgreGLES2RenderToVertexBuffer.h b/RenderSystems/GLES2/include/OgreGLES2RenderToVertexBuffer.h deleted file mode 100644 index 7fa4e9cd42a..00000000000 --- a/RenderSystems/GLES2/include/OgreGLES2RenderToVertexBuffer.h +++ /dev/null @@ -1,54 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLES2RenderToVertexBuffer_H__ -#define __GLES2RenderToVertexBuffer_H__ - -#include "OgreGLRenderToVertexBufferCommon.h" -#include "OgreGLES2Prerequisites.h" - -namespace Ogre { - class GLES2RenderToVertexBuffer : public GLRenderToVertexBufferCommon - { - public: - /** C'tor */ - GLES2RenderToVertexBuffer(); - /** D'tor */ - virtual ~GLES2RenderToVertexBuffer(); - - /** - Update the contents of this vertex buffer by rendering - */ - void update(SceneManager* sceneMgr) override; - protected: - void bindVerticesOutput(Pass* pass); - GLuint mPrimitivesDrawnQuery; - bool mFeedbackActive; - }; -} - -#endif diff --git a/RenderSystems/GLES2/include/OgreGLES2StateCacheManager.h b/RenderSystems/GLES2/include/OgreGLES2StateCacheManager.h deleted file mode 100644 index 02eb6bffe41..00000000000 --- a/RenderSystems/GLES2/include/OgreGLES2StateCacheManager.h +++ /dev/null @@ -1,158 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLES2StateCacheManager_H__ -#define __GLES2StateCacheManager_H__ - -#include "OgreGLES2Prerequisites.h" -#include "OgreGLStateCacheManagerCommon.h" - -namespace Ogre -{ - class _OgreGLES2Export GLES2StateCacheManager : public GLStateCacheManagerCommon - { - protected: - /// Stores the currently bound vertex array object - GLuint mActiveVertexArray; - /// Stores the last bound texture id - GLuint mLastBoundTexID; - public: - GLES2StateCacheManager(void); - - /** Initialize our cache variables and sets the - GL states on the current context. - */ - void initializeCache(); - - /** Clears all cached values - */ - void clearCache(); - - /** Bind an OpenGL buffer of any type. - @param target The buffer target. - @param buffer The buffer ID. - */ - void bindGLBuffer(GLenum target, GLuint buffer); - - /** Delete an OpenGL buffer of any type. - @param target The buffer target. - @param buffer The buffer ID. - */ - void deleteGLBuffer(GLenum target, GLuint buffer); - - /** Bind an OpenGL Vertex array object. - @param vao The vertex array object ID. - */ - void bindGLVertexArray(GLuint vao); - - /** Bind an OpenGL texture of any type. - @param target The texture target. - @param texture The texture ID. - */ - void bindGLTexture(GLenum target, GLuint texture); - - /** Invalidates the state associated with a particular texture ID. - @param texture The texture ID. - */ - void invalidateStateForTexture(GLuint texture); - - /** Sets an integer parameter value per texture target. - @param target The texture target. - @param pname The parameter name. - @param param The parameter value. - */ - void setTexParameteri(GLenum target, GLenum pname, GLint param); - - /** Activate an OpenGL texture unit. - @param unit The texture unit to activate. - @return Whether or not the texture unit was successfully activated. - */ - bool activateGLTextureUnit(size_t unit); - - /// Set the blend equation for RGB and alpha separately. - void setBlendEquation(GLenum eqRGB, GLenum eqA); - - /// Set the blend function for RGB and alpha separately. - void setBlendFunc(GLenum source, GLenum dest, GLenum sourceA, GLenum destA); - - /** Sets the current depth mask setting. - @param mask The depth mask to use. - */ - void setDepthMask(GLboolean mask); - - /** Sets the current depth test function. - @param func The depth test function to use. - */ - void setDepthFunc(GLenum func); - - /** Sets the clear depth in the range from [0..1]. - @param depth The clear depth to use. - */ - void setClearDepth(GLclampf depth); - - /** Sets the color to clear to. - @param red The red component. - @param green The green component. - @param blue The blue component. - @param alpha The alpha component. - */ - void setClearColour(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); - - /** Sets the current colour mask. - @param red The red component. - @param green The green component. - @param blue The blue component. - @param alpha The alpha component. - */ - void setColourMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); - - /** Sets the stencil mask. - @param mask The stencil mask to use - */ - void setStencilMask(GLuint mask); - - /** Enables a piece of OpenGL functionality. - @param flag The function to enable. - */ - void setEnabled(GLenum flag); - - /** Disables a piece of OpenGL functionality. - @param flag The function to disable. - */ - void setDisabled(GLenum flag); - - /** Sets the face culling setting. - @param face The face culling mode to use. - */ - void setCullFace(GLenum face); - - void setViewport(const Rect& r); - }; -} - -#endif diff --git a/RenderSystems/GLES2/include/OgreGLES2Texture.h b/RenderSystems/GLES2/include/OgreGLES2Texture.h deleted file mode 100644 index d61bd0b14fb..00000000000 --- a/RenderSystems/GLES2/include/OgreGLES2Texture.h +++ /dev/null @@ -1,84 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLES2Texture_H__ -#define __GLES2Texture_H__ - -#include "OgreGLES2Prerequisites.h" -#include "OgreGLNativeSupport.h" -#include "OgrePlatform.h" -#include "OgreRenderTexture.h" -#include "OgreGLTextureCommon.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreGLES2ManagedResource.h" -#include "OgreGLES2RenderSystem.h" - -namespace Ogre { - class _OgreGLES2Export GLES2Texture : public GLTextureCommon MANAGED_RESOURCE - { - public: - // Constructor - GLES2Texture(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - GLES2RenderSystem* renderSystem); - - virtual ~GLES2Texture(); - - // Takes the OGRE texture type (1d/2d/3d/cube) and returns the appropriate GL one - GLenum getGLES2TextureTarget(void) const; - - protected: - /// @copydoc Texture::createInternalResourcesImpl - void createInternalResourcesImpl(void) override; - /// @copydoc Texture::freeInternalResourcesImpl - void freeInternalResourcesImpl(void) override; - - /** Internal method, create GLHardwarePixelBuffers for every face and - mipmap level. This method must be called after the GL texture object was created, - the number of mipmaps was set (GL_TEXTURE_MAX_LEVEL) and glTexImageXD was called to - actually allocate the buffer - */ - void _createSurfaceList(); - - /// Create gl texture - void _createGLTexResource(); - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - /** See AndroidResource. */ - void notifyOnContextLost() override; - - /** See AndroidResource. */ - void notifyOnContextReset() override; -#endif - - private: - GLES2RenderSystem* mRenderSystem; - }; -} - -#endif diff --git a/RenderSystems/GLES2/include/OgreGLES2TextureManager.h b/RenderSystems/GLES2/include/OgreGLES2TextureManager.h deleted file mode 100644 index 40acd330460..00000000000 --- a/RenderSystems/GLES2/include/OgreGLES2TextureManager.h +++ /dev/null @@ -1,63 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLES2TextureManager_H__ -#define __GLES2TextureManager_H__ - -#include "OgreGLES2Prerequisites.h" -#include "OgreTextureManager.h" -#include "OgreGLES2Texture.h" -#include "OgreGLNativeSupport.h" - -namespace Ogre { - /** GL ES-specific implementation of a TextureManager */ - class _OgreGLES2Export GLES2TextureManager : public TextureManager - { - public: - GLES2TextureManager(GLES2RenderSystem* renderSystem); - virtual ~GLES2TextureManager(); - - /// @copydoc TextureManager::getNativeFormat - PixelFormat getNativeFormat(TextureType ttype, PixelFormat format, int usage) override; - - /// @copydoc TextureManager::isHardwareFilteringSupported - bool isHardwareFilteringSupported(TextureType ttype, PixelFormat format, int usage, - bool preciseFormatOnly = false) override; - protected: - friend class GLES2RenderSystem; - - /// @copydoc ResourceManager::createImpl - Resource* createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams) override; - - GLES2RenderSystem* mRenderSystem; - }; -} - -#endif diff --git a/RenderSystems/GLES2/src/EAGL/ARCMacros.h b/RenderSystems/GLES2/src/EAGL/ARCMacros.h deleted file mode 100644 index 89e6f4768ec..00000000000 --- a/RenderSystems/GLES2/src/EAGL/ARCMacros.h +++ /dev/null @@ -1,59 +0,0 @@ -// -// ARCMacros.h -// -// Created by John Blanco on 1/28/2011. -// Rapture In Venice releases all rights to this code. Feel free use and/or copy it openly and freely! -// - -#if !defined(__clang__) || __clang_major__ < 3 - #ifndef __bridge - #define __bridge - #endif - - #ifndef __bridge_retain - #define __bridge_retain - #endif - - #ifndef __bridge_retained - #define __bridge_retained - #endif - - #ifndef __autoreleasing - #define __autoreleasing - #endif - - #ifndef __strong - #define __strong - #endif - - #ifndef __unsafe_unretained - #define __unsafe_unretained - #endif - - #ifndef __weak - #define __weak - #endif -#endif - -#if __has_feature(objc_arc) - #define SAFE_ARC_PROP_RETAIN strong - #define SAFE_ARC_RETAIN(x) (x) - #define SAFE_ARC_RELEASE(x) - #define SAFE_ARC_AUTORELEASE(x) (x) - #define SAFE_ARC_BLOCK_COPY(x) (x) - #define SAFE_ARC_BLOCK_RELEASE(x) - #define SAFE_ARC_SUPER_DEALLOC() - #define SAFE_ARC_AUTORELEASE_POOL_START() @autoreleasepool { - #define SAFE_ARC_AUTORELEASE_POOL_END() } -#else - #define SAFE_ARC_PROP_RETAIN retain - #define SAFE_ARC_RETAIN(x) ([(x) retain]) - #define SAFE_ARC_RELEASE(x) ([(x) release]) - #define SAFE_ARC_AUTORELEASE(x) ([(x) autorelease]) - #define SAFE_ARC_BLOCK_COPY(x) (Block_copy(x)) - #define SAFE_ARC_BLOCK_RELEASE(x) (Block_release(x)) - #define SAFE_ARC_SUPER_DEALLOC() ([super dealloc]) - #define SAFE_ARC_AUTORELEASE_POOL_START() NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - #define SAFE_ARC_AUTORELEASE_POOL_END() [pool release]; -#endif - diff --git a/RenderSystems/GLES2/src/EAGL/OgreEAGL2Support.mm b/RenderSystems/GLES2/src/EAGL/OgreEAGL2Support.mm deleted file mode 100644 index f73672e4acb..00000000000 --- a/RenderSystems/GLES2/src/EAGL/OgreEAGL2Support.mm +++ /dev/null @@ -1,216 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreRoot.h" - -#include "OgreRenderSystem.h" -#include "OgreLogManager.h" -#include "OgreEAGLES2Context.h" - -#include "OgreEAGL2Support.h" -#include "OgreEAGL2Window.h" - -#import - -namespace Ogre { - float EAGLCurrentOSVersion; - - GLNativeSupport* getGLSupport(int = 0) - { - return new EAGL2Support(); - } - - EAGL2Support::EAGL2Support() : GLNativeSupport(CONTEXT_ES) - { - EAGLCurrentOSVersion = [[[UIDevice currentDevice] systemVersion] floatValue]; - } - - EAGL2Support::~EAGL2Support() - { - } - - ConfigOptionMap EAGL2Support::getConfigOptions(void) - { - ConfigOptionMap mOptions; - ConfigOption optContentScalingFactor; - - // Get the application frame size. On all iPhones(including iPhone 4) this will be 320 x 480 - // The iPad, at least with iPhone OS 3.2 will report 768 x 1024 - CGSize screenSize = [[UIScreen mainScreen] bounds].size; - mVideoModes.push_back({uint32(screenSize.width), uint32(screenSize.height), 0}); - mVideoModes.push_back({320, 480, 0}); - mVideoModes.push_back({320, 568, 0}); - mVideoModes.push_back({768, 1024, 0}); - - optContentScalingFactor.name = "Content Scaling Factor"; - optContentScalingFactor.possibleValues.push_back( "1.0" ); - optContentScalingFactor.possibleValues.push_back( "1.33" ); - optContentScalingFactor.possibleValues.push_back( "1.5" ); - optContentScalingFactor.possibleValues.push_back( "2.0" ); - optContentScalingFactor.currentValue = StringConverter::toString([UIScreen mainScreen].scale); - optContentScalingFactor.immutable = false; - - mFSAALevels.push_back(0); - mFSAALevels.push_back(2); - mFSAALevels.push_back(4); - mFSAALevels.push_back(8); - - mOptions[optContentScalingFactor.name] = optContentScalingFactor; - - return mOptions; - } - - CFDictionaryRef EAGL2Support::chooseGLConfig(const GLint *attribList, GLint *nElements) - { - // TODO: DJR - implement - CFDictionaryRef configs = NULL; - - return configs; - } - - GLint EAGL2Support::getGLConfigAttrib(CFDictionaryRef glConfig, GLint attribute, GLint *value) - { - // TODO: DJR - implement - GLint status = 0; - - return status; - } - - CFDictionaryRef EAGL2Support::getGLConfigFromContext(EAGLES2Context context) - { - // TODO: DJR - implement - CFDictionaryRef glConfig = 0; - - return glConfig; - } - - //------------------------------------------------------------------------ - // A helper class for the implementation of selectFBConfig - //------------------------------------------------------------------------ - class GLConfigAttribs - { - public: - GLConfigAttribs(const int* attribs) - { - for (int i = 0; attribs[2*i] != 0; i++) - { - fields[attribs[2*i]] = attribs[2*i+1]; - } - } - - void load(EAGL2Support* const glSupport, CFDictionaryRef glConfig) - { - std::map::iterator it; - - for (it = fields.begin(); it != fields.end(); it++) - { - it->second = 0; - - glSupport->getGLConfigAttrib(glConfig, it->first, &it->second); - } - } - - bool operator>(GLConfigAttribs& alternative) - { - return false; - } - - std::map fields; - }; - - CFDictionaryRef EAGL2Support::selectGLConfig(const int* minAttribs, const int *maxAttribs) - { - // TODO: DJR - implement - CFDictionaryRef glConfig = 0; - int nConfigs = 0;//, config; - - glConfig = chooseGLConfig(minAttribs, &nConfigs); - - if (!nConfigs) - { - return 0; - } - - return glConfig; - } - - RenderWindow * EAGL2Support::newWindow(const String &name, - unsigned int width, unsigned int height, - bool fullScreen, - const NameValuePairList *miscParams) - { - EAGL2Window *window = OGRE_NEW EAGL2Window(this); - window->create(name, width, height, fullScreen, miscParams); - - return window; - } - - EAGLES2Context * EAGL2Support::createNewContext(CAEAGLLayer *drawable, EAGLSharegroup *group) const - { - EAGLES2Context *context = new EAGLES2Context(drawable, group); - if (context == NULL) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to create new context"); - return context; - } - - // Initialise GL3W - if (glGetError == NULL && gleswInit()) - LogManager::getSingleton().logMessage("Failed to initialize GL3W"); - - return context; - } - - void * EAGL2Support::getProcAddress(const char* name) const - { - return (void*)gleswGetProcAddress(name); - } - - void EAGL2Support::start() - { - } - - void EAGL2Support::stop() - { - } - - bool EAGL2Support::interfaceOrientationIsSupported(NSString *orientation) - { - NSArray *supportedOrientations = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UISupportedInterfaceOrientations"]; - - return [supportedOrientations containsObject:orientation]; - } - - bool EAGL2Support::portraitIsSupported() - { - NSArray *supportedOrientations = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UISupportedInterfaceOrientations"]; - - return ([supportedOrientations containsObject:@"UIInterfaceOrientationPortrait"] || - [supportedOrientations containsObject:@"UIInterfaceOrientationPortraitUpsideDown"]); - } -} diff --git a/RenderSystems/GLES2/src/EAGL/OgreEAGL2View.mm b/RenderSystems/GLES2/src/EAGL/OgreEAGL2View.mm deleted file mode 100644 index 070f258bda3..00000000000 --- a/RenderSystems/GLES2/src/EAGL/OgreEAGL2View.mm +++ /dev/null @@ -1,85 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ---------------------------------------------------------------------------*/ - -#include "OgreEAGL2View.h" - -#include "OgreRoot.h" -#include "OgreCamera.h" -#include "OgreRenderWindow.h" -#include "OgreGLES2RenderSystem.h" -#include "OgreViewport.h" - -#import -#import -#import - -using namespace Ogre; - -@implementation EAGL2View - -@synthesize mWindowName; - -- (NSString *)description -{ - return [NSString stringWithFormat:@"EAGL2View frame dimensions x: %.0f y: %.0f w: %.0f h: %.0f", - [self frame].origin.x, - [self frame].origin.y, - [self frame].size.width, - [self frame].size.height]; -} - -+ (Class)layerClass -{ - return [CAEAGLLayer class]; -} - -- (void)layoutSubviews -{ - [super layoutSubviews]; - - // Get the window using the name that we saved - RenderWindow *window = static_cast(Root::getSingleton().getRenderSystem()->getRenderTarget(mWindowName)); - - if(window != NULL) - { - // Resize underlying frame buffer - window->windowMovedOrResized(); - - // After rotation the aspect ratio of the viewport has changed, update that as well. - if(window->getNumViewports() > 0) - { - // Get the view size and initialize temp variables - unsigned int width = (uint)self.bounds.size.width; - unsigned int height = (uint)self.bounds.size.height; - - Ogre::Viewport *viewPort = window->getViewport(0); - viewPort->getCamera()->setAspectRatio((Real) width / (Real) height); - } - } -} - -@end diff --git a/RenderSystems/GLES2/src/EAGL/OgreEAGL2ViewController.mm b/RenderSystems/GLES2/src/EAGL/OgreEAGL2ViewController.mm deleted file mode 100644 index 9265c32d2d0..00000000000 --- a/RenderSystems/GLES2/src/EAGL/OgreEAGL2ViewController.mm +++ /dev/null @@ -1,101 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#import "OgreEAGL2ViewController.h" -#include "ARCMacros.h" - -using namespace Ogre; - -@implementation EAGL2ViewController - -@synthesize mGLSupport; - -- (id)init -{ - if ((self = [super initWithNibName:nil bundle:nil])) - { - } - return self; -} - -- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil -{ - if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) - { - } - return self; -} - -- (void)dealloc -{ - SAFE_ARC_SUPER_DEALLOC(); -} - -- (void)didReceiveMemoryWarning -{ - // Releases the view if it doesn't have a superview. - [super didReceiveMemoryWarning]; -} - -- (void)loadView -{ - [super loadView]; -} - -- (void)viewDidLoad -{ - [super viewDidLoad]; -} - -- (void)viewDidUnload -{ - [super viewDidUnload]; -} - -- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation -{ - NSString *rotateToOrientation = @""; - if(interfaceOrientation == UIInterfaceOrientationPortrait) - rotateToOrientation = @"UIInterfaceOrientationPortrait"; - else if(interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) - rotateToOrientation = @"UIInterfaceOrientationPortraitUpsideDown"; - else if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft) - rotateToOrientation = @"UIInterfaceOrientationLandscapeLeft"; - else if(interfaceOrientation == UIInterfaceOrientationLandscapeRight) - rotateToOrientation = @"UIInterfaceOrientationLandscapeRight"; - - // Inform the view that it needs to call layoutSubviews - [self.view setNeedsDisplay]; - - if(mGLSupport->interfaceOrientationIsSupported(rotateToOrientation)) - return YES; - else - return NO; -} - -@end diff --git a/RenderSystems/GLES2/src/EAGL/OgreEAGL2Window.mm b/RenderSystems/GLES2/src/EAGL/OgreEAGL2Window.mm deleted file mode 100644 index f670d0de49d..00000000000 --- a/RenderSystems/GLES2/src/EAGL/OgreEAGL2Window.mm +++ /dev/null @@ -1,534 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ---------------------------------------------------------------------------*/ - -#include "OgreEAGL2Window.h" - -#include "OgreEAGL2Support.h" -#include "OgreEAGLES2Context.h" - -#include "OgreRoot.h" -#include "OgreGLES2RenderSystem.h" -#include "OgreGLES2PixelFormat.h" -#include "OgreViewport.h" -#include "OgreLogManager.h" -#include - -#import -#import -#include "ARCMacros.h" -#include "OgreDepthBuffer.h" - -namespace Ogre { - - struct EAGLContextGuard - { - EAGLContextGuard(EAGLContext* ctx) : mPrevContext([EAGLContext currentContext]) { if(ctx != mPrevContext) [EAGLContext setCurrentContext:ctx]; } - ~EAGLContextGuard() { [EAGLContext setCurrentContext:mPrevContext]; } - private: - EAGLContext *mPrevContext; - }; - - - EAGL2Window::EAGL2Window(EAGL2Support *glsupport) - : mVisible(false), - mHidden(false), - mIsExternal(false), - mUsingExternalView(false), - mUsingExternalViewController(false), - mIsContentScalingSupported(EAGLCurrentOSVersion >= 4.0), - mContentScalingFactor(1.0), - mGLSupport(glsupport), - mContext(NULL), - mWindow(nil), - mView(nil), - mViewController(nil) - { - mIsFullScreen = true; - mActive = true; - mHwGamma = false; - mDepthBufferPoolId = DepthBuffer::POOL_NO_DEPTH; - } - - EAGL2Window::~EAGL2Window() - { - destroy(); - - if (mContext != NULL) - { - OGRE_DELETE mContext; - } - - mContext = NULL; - } - - void EAGL2Window::destroy(void) - { - if (mClosed) - { - return; - } - - mClosed = true; - mActive = false; - - if (!mIsExternal) - { - SAFE_ARC_RELEASE(mWindow); - mWindow = nil; - } - - if(!mUsingExternalViewController) - SAFE_ARC_RELEASE(mViewController); - } - - void EAGL2Window::setHidden(bool hidden) - { - mHidden = hidden; - if (!mIsExternal) - { - [mWindow setHidden:hidden]; - } - } - - void EAGL2Window::resize(unsigned int widthPt, unsigned int heightPt) - { - if(!mWindow) return; - - Real widthPx = _getPixelFromPoint(widthPt); - Real heightPx = _getPixelFromPoint(heightPt); - - // Check if the window size really changed - if(mWidth == widthPx && mHeight == heightPx) - return; - - // Destroy and recreate the framebuffer with new dimensions - EAGLContextGuard ctx_guard(mContext->getContext()); - - mContext->destroyFramebuffer(); - - mWidth = widthPx; - mHeight = heightPx; - - mContext->createFramebuffer(); - - for (ViewportList::iterator it = mViewportList.begin(); it != mViewportList.end(); ++it) - { - (*it).second->_updateDimensions(); - } - } - - void EAGL2Window::windowMovedOrResized() - { - CGRect frame = [mView frame]; - CGFloat width = _getPixelFromPoint(frame.size.width); - CGFloat height = _getPixelFromPoint(frame.size.height); - CGFloat left = _getPixelFromPoint(frame.origin.x); - CGFloat top = _getPixelFromPoint(frame.origin.y); - - if(mWidth == width && mHeight == height && mLeft == left && mTop == top) - return; - - EAGLContextGuard ctx_guard(mContext->getContext()); - mContext->destroyFramebuffer(); - - mWidth = width; - mHeight = height; - mLeft = left; - mTop = top; - - mContext->createFramebuffer(); - - for (ViewportList::iterator it = mViewportList.begin(); it != mViewportList.end(); ++it) - { - (*it).second->_updateDimensions(); - } - } - - void EAGL2Window::createNativeWindow(uint widthPt, uint heightPt, const NameValuePairList *miscParams) - { - // This method is called from within create() and after parameters have been parsed. - // If the window, view or view controller objects are nil at this point, it is safe - // to assume that external handles are either not being used or are invalid and - // we can create our own. - SAFE_ARC_AUTORELEASE_POOL_START() - - // Set us up with an external window, or create our own. - if(!mIsExternal) - { - mWindow = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, widthPt, heightPt)]; - } - - OgreAssert(mWindow || mUsingExternalViewController, "EAGL2Window: Failed to obtain required native window"); - - // Set up the view - if(!mUsingExternalView) - { - mView = [[EAGL2View alloc] initWithFrame:CGRectMake(0, 0, widthPt, heightPt)]; - mView.opaque = YES; - - // Use the default scale factor of the screen - // See Apple's documentation on supporting high resolution devices for more info - mView.contentScaleFactor = mContentScalingFactor; - } - - OgreAssert(mView != nil, "EAGL2Window: Failed to create view"); - - [mView setMWindowName:mName]; - - OgreAssert([mView.layer isKindOfClass:[CAEAGLLayer class]], "EAGL2Window: View's Core Animation layer is not a CAEAGLLayer. This is a requirement for using OpenGL ES for drawing."); - - CAEAGLLayer *eaglLayer = (CAEAGLLayer *)mView.layer; - OgreAssert(eaglLayer != nil, "EAGL2Window: Failed to retrieve a pointer to the view's Core Animation layer"); - - BOOL retainedBacking = NO; - NameValuePairList::const_iterator option; - if ((option = miscParams->find("retainedBacking")) != miscParams->end()) - { - retainedBacking = StringConverter::parseBool(option->second); - } - - eaglLayer.opaque = YES; - eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys: - [NSNumber numberWithBool:retainedBacking], kEAGLDrawablePropertyRetainedBacking, - kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil]; - // Set up the view controller - if(!mUsingExternalViewController) - { - mViewController = [[EAGL2ViewController alloc] init]; - } - - OgreAssert(mViewController != nil, "EAGL2Window: Failed to create view controller"); - - if(mViewController.view != mView) - mViewController.view = mView; - - GLRenderSystemCommon *rs = static_cast(Root::getSingleton().getRenderSystem()); - EAGLSharegroup *group = nil; - if ((option = miscParams->find("externalSharegroup")) != miscParams->end()) - { - group = (__bridge EAGLSharegroup *)(void*)StringConverter::parseSizeT(option->second); - LogManager::getSingleton().logMessage("iOS: Using an external EAGLSharegroup"); - } - else - { - if(EAGLES2Context* mainContext = (EAGLES2Context*)rs->_getMainContext()) - group = mainContext->getContext().sharegroup; - } - - mContext = mGLSupport->createNewContext(eaglLayer, group); - - mContext->mIsMultiSampleSupported = rs->hasMinGLVersion(3, 0); - mContext->mNumSamples = mFSAA; - - OgreAssert(mContext != nil, "EAGL2Window: Failed to create OpenGL ES context"); - - mViewController.mGLSupport = mGLSupport; - - if(!mUsingExternalViewController) - { - [mWindow addSubview:mViewController.view]; - mWindow.rootViewController = mViewController; - [mWindow makeKeyAndVisible]; - } - - if(!mUsingExternalView) - SAFE_ARC_RELEASE(mView); - - // Obtain effective view size and scale - CGSize sz = mView.frame.size; - mContentScalingFactor = mView.contentScaleFactor; - mWidth = _getPixelFromPoint(sz.width); - mHeight = _getPixelFromPoint(sz.height); - - mContext->createFramebuffer(); - - // If content scaling is supported, the window size will be smaller than the GL pixel buffer - // used to render. Report the buffer size for reference. - StringStream ss; - - ss << "iOS: Window created " << widthPt << " x " << heightPt - << " with backing store size " << mContext->mBackingWidth << " x " << mContext->mBackingHeight - << " using content scaling factor " << std::fixed << std::setprecision(1) << getViewPointToPixelScale(); - LogManager::getSingleton().logMessage(ss.str()); - - SAFE_ARC_AUTORELEASE_POOL_END() - } - - void EAGL2Window::create(const String& name, uint widthPt, uint heightPt, - bool fullScreen, const NameValuePairList *miscParams) - { - short frequency = 0; - bool vsync = false; - int left = 0; - int top = 0; - - mIsFullScreen = fullScreen; - mName = name; - - if (miscParams) - { - NameValuePairList::const_iterator opt; - NameValuePairList::const_iterator end = miscParams->end(); - - // Note: Some platforms support AA inside ordinary windows - if ((opt = miscParams->find("FSAA")) != end) - { - mFSAA = StringConverter::parseUnsignedInt(opt->second); - } - - if ((opt = miscParams->find("displayFrequency")) != end) - { - frequency = (short)StringConverter::parseInt(opt->second); - } - - if ((opt = miscParams->find("contentScalingFactor")) != end) - { - mContentScalingFactor = StringConverter::parseReal(opt->second); - } - - if ((opt = miscParams->find("vsync")) != end) - { - vsync = StringConverter::parseBool(opt->second); - } - - if ((opt = miscParams->find("left")) != end) - { - left = StringConverter::parseInt(opt->second); - } - - if ((opt = miscParams->find("top")) != end) - { - top = StringConverter::parseInt(opt->second); - } - - if ((opt = miscParams->find("title")) != end) - { - mName = opt->second; - } - - if ((opt = miscParams->find("externalWindowHandle")) != end) - { - mWindow = (__bridge UIWindow *)(void*)StringConverter::parseSizeT(opt->second); - mIsExternal = true; - LogManager::getSingleton().logMessage("iOS: Using an external window handle"); - } - - if ((opt = miscParams->find("externalViewHandle")) != end) - { - mView = (__bridge EAGL2View *)(void*)StringConverter::parseSizeT(opt->second); - mUsingExternalView = true; - LogManager::getSingleton().logMessage("iOS: Using an external view handle"); - } - - if ((opt = miscParams->find("externalViewControllerHandle")) != end) - { - mViewController = (__bridge EAGL2ViewController *)(void*)StringConverter::parseSizeT(opt->second); - if(mViewController.view != nil) - mView = (EAGL2View *)mViewController.view; - mUsingExternalViewController = true; - LogManager::getSingleton().logMessage("iOS: Using an external view controller handle"); - } - } - - createNativeWindow(widthPt, heightPt, miscParams); - - left = top = 0; - mLeft = left; - mTop = top; - - mActive = true; - mVisible = true; - mClosed = false; - } - - void EAGL2Window::swapBuffers() - { - if (mClosed) - { - return; - } - - unsigned int attachmentCount = 0; - GLenum attachments[3]; - unsigned int buffers = mContext->mDiscardBuffers; - - if((buffers & FBT_COLOUR) && mContext->mIsMultiSampleSupported && mContext->mNumSamples > 0) - { - attachments[attachmentCount++] = GL_COLOR_ATTACHMENT0; - } - if(buffers & FBT_DEPTH) - { - attachments[attachmentCount++] = GL_DEPTH_ATTACHMENT; - } - if(buffers & FBT_STENCIL) - { - attachments[attachmentCount++] = GL_STENCIL_ATTACHMENT; - } - if(mContext->mIsMultiSampleSupported && mContext->mNumSamples > 0) - { - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mContext->mViewFramebuffer)); - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_READ_FRAMEBUFFER, mContext->mSampleFramebuffer)); - OGRE_CHECK_GL_ERROR(glBlitFramebuffer(0, 0, mWidth, mHeight, 0, 0, mWidth, mHeight, GL_COLOR_BUFFER_BIT, GL_NEAREST)); - OGRE_CHECK_GL_ERROR(glInvalidateFramebuffer(GL_READ_FRAMEBUFFER, attachmentCount, attachments)); - } - else - { - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mContext->mViewFramebuffer)); - OGRE_CHECK_GL_ERROR(glInvalidateFramebuffer(GL_FRAMEBUFFER, attachmentCount, attachments)); - } - - OGRE_CHECK_GL_ERROR(glBindRenderbuffer(GL_RENDERBUFFER, mContext->mViewRenderbuffer)); - if ([mContext->getContext() presentRenderbuffer:GL_RENDERBUFFER] == NO) - { - glGetError(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to swap buffers in "); - } - } - - void EAGL2Window::getCustomAttribute( const String& name, void* pData ) - { - if( name == "GLCONTEXT" ) - { - *static_cast(pData) = mContext; - return; - } - - if( name == "GLFBO" ) - { - *static_cast(pData) = (mContext->mIsMultiSampleSupported && mContext->mNumSamples>0) ? mContext->mSampleFramebuffer : mContext->mViewFramebuffer; - return; - } - - if( name == "SHAREGROUP" ) - { - *(void**)(pData) = (__bridge void*)mContext->getContext().sharegroup; - return; - } - - if( name == "WINDOW" ) - { - *(void**)(pData) = (__bridge void*)mWindow; - return; - } - - if( name == "VIEW" ) - { - *(void**)(pData) = (__bridge void*)mViewController.view; - return; - } - - if( name == "VIEWCONTROLLER" ) - { - *(void**)(pData) = (__bridge void*)mViewController; - return; - } - } - - void EAGL2Window::copyContentsToMemory(const Box& src, const PixelBox &dst, FrameBuffer buffer) - { - if(src.right > mWidth || src.bottom > mHeight || src.front != 0 || src.back != 1 - || dst.getWidth() != src.getWidth() || dst.getHeight() != src.getHeight() || dst.getDepth() != 1 - || dst.getWidth() != dst.rowPitch /* GLES2 does not support GL_PACK_ROW_LENGTH, nor iOS supports GL_NV_pack_subimage */) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Invalid box."); - } - - if (buffer == FB_AUTO) - { - buffer = mIsFullScreen ? FB_FRONT : FB_BACK; - } - - // Switch context if different from current one - RenderSystem* rsys = Root::getSingleton().getRenderSystem(); - rsys->_setViewport(this->getViewport(0)); - - OGRE_CHECK_GL_ERROR(glBindRenderbuffer(GL_RENDERBUFFER, mContext->mViewRenderbuffer)); - - // The following code is adapted from Apple Technical Q & A QA1704 - // http://developer.apple.com/library/ios/#qa/qa1704/_index.html - NSInteger width = dst.getWidth(), height = dst.getHeight(); - NSInteger dataLength = width * height * PixelUtil::getComponentCount(dst.format); - GLubyte *data = (GLubyte*)malloc(dataLength * sizeof(GLubyte)); - GLenum format = GLES2PixelUtil::getGLOriginFormat(dst.format); - GLenum type = GLES2PixelUtil::getGLOriginDataType(dst.format); - - GLint currentFBO = 0; - GLuint sampleFramebuffer = 0; - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_FRAMEBUFFER_BINDING, ¤tFBO)); - OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &sampleFramebuffer)); - - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_READ_FRAMEBUFFER, sampleFramebuffer)); - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, currentFBO)); - OGRE_CHECK_GL_ERROR(glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST)); - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, currentFBO)); - - // Read pixel data from the framebuffer - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_PACK_ALIGNMENT, 1)); - OGRE_CHECK_GL_ERROR(glReadPixels((GLint)src.left, (GLint)(mHeight - src.bottom), - (GLsizei)width, (GLsizei)height, - format, type, data)); - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_PACK_ALIGNMENT, 4)); - - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, currentFBO)); - OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &sampleFramebuffer)); - - // Create a CGImage with the pixel data - // If your OpenGL ES content is opaque, use kCGImageAlphaNoneSkipLast to ignore the alpha channel - // otherwise, use kCGImageAlphaPremultipliedLast - CGDataProviderRef ref = CGDataProviderCreateWithData(NULL, data, dataLength, NULL); - CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB(); - CGImageRef iref = CGImageCreate(width, height, 8, PixelUtil::getNumElemBits(dst.format), - width * PixelUtil::getComponentCount(dst.format), colorspace, - kCGBitmapByteOrderDefault, - ref, NULL, YES, kCGRenderingIntentDefault); - - // OpenGL ES measures data in PIXELS - // Create a graphics context with the target size measured in POINTS - NSInteger widthInPoints = 0, heightInPoints = 0; - - // Set the scale parameter to your OpenGL ES view's contentScaleFactor - // so that you get a high-resolution snapshot when its value is greater than 1.0 - CGFloat scale = mView.contentScaleFactor; - widthInPoints = width / scale; - heightInPoints = height / scale; - UIGraphicsBeginImageContextWithOptions(CGSizeMake(widthInPoints, heightInPoints), NO, scale); - - CGContextRef context = UIGraphicsGetCurrentContext(); - CGContextSetBlendMode(context, kCGBlendModeCopy); - CGContextDrawImage(context, CGRectMake(0.0, 0.0, widthInPoints, heightInPoints), iref); - - // Retrieve the UIImage from the current context - memcpy(dst.data, CGBitmapContextGetData(context), CGBitmapContextGetBytesPerRow(context) * height); // TODO: support dst.rowPitch != dst.getWidth() case - UIGraphicsEndImageContext(); - - // Clean up - free(data); - CFRelease(ref); - CFRelease(colorspace); - CGImageRelease(iref); - } -} diff --git a/RenderSystems/GLES2/src/EAGL/OgreEAGLES2Context.mm b/RenderSystems/GLES2/src/EAGL/OgreEAGLES2Context.mm deleted file mode 100644 index 4f16c051718..00000000000 --- a/RenderSystems/GLES2/src/EAGL/OgreEAGLES2Context.mm +++ /dev/null @@ -1,249 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreEAGLES2Context.h" -#include "OgreEAGL2Support.h" -#include "OgreGLES2RenderSystem.h" -#include "OgreRoot.h" -#include "ARCMacros.h" - -namespace Ogre { - EAGLES2Context::EAGLES2Context(CAEAGLLayer *drawable, EAGLSharegroup *group) - : - mBackingWidth(0), - mBackingHeight(0), - mViewRenderbuffer(0), - mViewFramebuffer(0), - mDepthRenderbuffer(0), - mIsMultiSampleSupported(false), - mNumSamples(0), - mSampleFramebuffer(0), - mSampleRenderbuffer(0) - { - - mDrawable = SAFE_ARC_RETAIN(drawable); - - for(EAGLRenderingAPI renderingAPI : {kEAGLRenderingAPIOpenGLES3, kEAGLRenderingAPIOpenGLES2}) - { - // If the group argument is not NULL, then we assume that an externally created EAGLSharegroup - // is to be used and a context is created using that group. - if(group) - { - mContext = [[EAGLContext alloc] initWithAPI:renderingAPI sharegroup:group]; - } - else - { - mContext = [[EAGLContext alloc] initWithAPI:renderingAPI]; - } - if(mContext) - break; - } - - if (!mContext || ![EAGLContext setCurrentContext:mContext]) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Unable to create a suitable EAGLContext"); - } - -#ifdef __IPHONE_7_1 - OGRE_IF_IOS_VERSION_IS_GREATER_THAN(7.1) - { - [mContext setMultiThreaded:YES]; - } -#endif - } - - EAGLES2Context::~EAGLES2Context() - { - GLRenderSystemCommon *rs = - static_cast(Root::getSingleton().getRenderSystem()); - - rs->_unregisterContext(this); - - destroyFramebuffer(); - - if ([EAGLContext currentContext] == mContext) - { - [EAGLContext setCurrentContext:nil]; - } - - SAFE_ARC_RELEASE(mContext); - SAFE_ARC_RELEASE(mDrawable); - } - - bool EAGLES2Context::createFramebuffer() - { - GLES2RenderSystem *rs = static_cast(Root::getSingleton().getRenderSystem()); - bool packedDepthStencil = rs->hasMinGLVersion(3, 0) || rs->checkExtension("GL_OES_packed_depth_stencil"); - - destroyFramebuffer(); - - OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mViewFramebuffer)); - OGRE_CHECK_GL_ERROR(glGenRenderbuffers(1, &mViewRenderbuffer)); - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mViewFramebuffer)); - OGRE_CHECK_GL_ERROR(glBindRenderbuffer(GL_RENDERBUFFER, mViewRenderbuffer)); - OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_FRAMEBUFFER, mViewFramebuffer, 0, "View Framebuffer")); - OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_RENDERBUFFER, mViewRenderbuffer, 0, "View Renderbuffer")); - - if(![mContext renderbufferStorage:GL_RENDERBUFFER fromDrawable:(id) mDrawable]) - { - glGetError(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Failed to bind the drawable to a renderbuffer object"); - return false; - } - - OGRE_CHECK_GL_ERROR(glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &mBackingWidth)); - OGRE_CHECK_GL_ERROR(glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &mBackingHeight)); - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, mViewRenderbuffer)); - - if(mIsMultiSampleSupported && mNumSamples > 0) - { - // Determine how many MSAA samples to use - GLint maxSamplesAllowed; - glGetIntegerv(GL_MAX_SAMPLES_APPLE, &maxSamplesAllowed); - int samplesToUse = (mNumSamples > maxSamplesAllowed) ? maxSamplesAllowed : mNumSamples; - - // Create the FSAA framebuffer (offscreen) - OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mSampleFramebuffer)); - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mSampleFramebuffer)); - OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_FRAMEBUFFER, mSampleFramebuffer, 0, "FSAA Framebuffer")); - - /* Create the offscreen MSAA color buffer. - * After rendering, the contents of this will be blitted into mFSAAFramebuffer */ - OGRE_CHECK_GL_ERROR(glGenRenderbuffers(1, &mSampleRenderbuffer)); - OGRE_CHECK_GL_ERROR(glBindRenderbuffer(GL_RENDERBUFFER, mSampleRenderbuffer)); - OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_RENDERBUFFER, mSampleRenderbuffer, 0, "FSAA Colour Renderbuffer")); - OGRE_CHECK_GL_ERROR(glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, samplesToUse, GL_RGBA8_OES, mBackingWidth, mBackingHeight)); - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, mSampleRenderbuffer)); - - // Create the FSAA depth buffer - OGRE_CHECK_GL_ERROR(glGenRenderbuffers(1, &mDepthRenderbuffer)); - OGRE_CHECK_GL_ERROR(glBindRenderbuffer(GL_RENDERBUFFER, mDepthRenderbuffer)); - OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_RENDERBUFFER, mDepthRenderbuffer, 0, "Depth Renderbuffer")); - OGRE_CHECK_GL_ERROR(glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, samplesToUse, packedDepthStencil ? GL_DEPTH24_STENCIL8_OES : GL_DEPTH_COMPONENT16, mBackingWidth, mBackingHeight)); - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, mDepthRenderbuffer)); - if(packedDepthStencil) - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, mDepthRenderbuffer)); - - // Validate the FSAA framebuffer - if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) - { - glGetError(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Failed to make a complete FSAA framebuffer object"); - return false; - } - } - else - { - OGRE_CHECK_GL_ERROR(glGenRenderbuffers(1, &mDepthRenderbuffer)); - OGRE_CHECK_GL_ERROR(glBindRenderbuffer(GL_RENDERBUFFER, mDepthRenderbuffer)); - OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_RENDERBUFFER, mDepthRenderbuffer, 0, "Depth Renderbuffer")); - OGRE_CHECK_GL_ERROR(glRenderbufferStorage(GL_RENDERBUFFER, packedDepthStencil ? GL_DEPTH24_STENCIL8_OES : GL_DEPTH_COMPONENT16, mBackingWidth, mBackingHeight)); - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, mDepthRenderbuffer)); - if(packedDepthStencil) - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, mDepthRenderbuffer)); - } - - OGRE_CHECK_GL_ERROR(glBindRenderbuffer(GL_RENDERBUFFER, mViewRenderbuffer)); - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mViewFramebuffer)); - if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) - { - glGetError(); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Failed to make a complete framebuffer object"); - return false; - } - - return true; - } - - void EAGLES2Context::destroyFramebuffer() - { - if(mViewFramebuffer) - { - OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mViewFramebuffer)); - mViewFramebuffer = 0; - } - - if(mViewRenderbuffer) - { - OGRE_CHECK_GL_ERROR(glDeleteRenderbuffers(1, &mViewRenderbuffer)); - mViewRenderbuffer = 0; - } - - if(mSampleRenderbuffer) - { - OGRE_CHECK_GL_ERROR(glDeleteRenderbuffers(1, &mSampleRenderbuffer)); - mSampleRenderbuffer = 0; - } - - if(mSampleFramebuffer) - { - OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mSampleFramebuffer)); - mSampleFramebuffer = 0; - } - - if(mDepthRenderbuffer) - { - OGRE_CHECK_GL_ERROR(glDeleteRenderbuffers(1, &mDepthRenderbuffer)); - mDepthRenderbuffer = 0; - } - } - - void EAGLES2Context::setCurrent() - { - BOOL ret = [EAGLContext setCurrentContext:mContext]; - if (!ret) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Failed to make context current"); - } - } - - void EAGLES2Context::endCurrent() - { - [EAGLContext setCurrentContext:nil]; - } - - GLContext * EAGLES2Context::clone() const - { - return new EAGLES2Context(mDrawable, [mContext sharegroup]); - } - - CAEAGLLayer * EAGLES2Context::getDrawable() const - { - return mDrawable; - } - - EAGLContext * EAGLES2Context::getContext() const - { - return mContext; - } -} diff --git a/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESCgProgram.h b/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESCgProgram.h deleted file mode 100644 index 53379e0d8c0..00000000000 --- a/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESCgProgram.h +++ /dev/null @@ -1,81 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLSLESCgProgram_H__ -#define __GLSLESCgProgram_H__ - -#include "OgreGLSLESProgram.h" -#include "OgreStringVector.h" - -namespace Ogre { - /** Specialisation of HighLevelGpuProgram to provide support for CG - - Cg programs will be converted to GLSL - */ - class _OgreGLES2Export GLSLESCgProgram : public GLSLESProgram - { - public: - /// Command object for setting profiles - class CmdProfiles : public ParamCommand - { - public: - String doGet(const void* target) const; - void doSet(void* target, const String& val); - }; - - GLSLESCgProgram(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader); - ~GLSLESCgProgram(); - - - /// Overridden from GLSLESProgram - void loadFromSource(void); - - /// Overridden from GLSLESProgram - const String& getLanguage(void) const; - - /** Sets the entry point for this program ie the first method called. */ - void setEntryPoint(const String& entryPoint) { mEntryPoint = entryPoint; } - /** Gets the entry point defined for this program. */ - const String& getEntryPoint(void) const { return mEntryPoint; } - /** Sets the Cg profiles which can be supported by the program. */ - void setProfiles(const StringVector& profiles); - /** Gets the Cg profiles which can be supported by the program. */ - const StringVector& getProfiles(void) const { return mProfiles; } - protected: - static CmdProfiles msCmdProfiles; - StringVector mProfiles; - - // check if syntax is supported - bool isSyntaxSupported(); - // deletes the key word ": register(xx)" that hlsl2glsl doesn't know to handle - String deleteRegisterFromCg(const String& inSource); - }; -} - -#endif // __GLSLESCgProgram_H__ diff --git a/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESCgProgramFactory.h b/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESCgProgramFactory.h deleted file mode 100644 index 753a06e29c2..00000000000 --- a/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESCgProgramFactory.h +++ /dev/null @@ -1,53 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - - -#ifndef __GLSLESCgProgramFactory_H__ -#define __GLSLESCgProgramFactory_H__ - -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreGLSLESExtSupport.h" - -namespace Ogre -{ - /** Factory class for GLSL ES programs. */ - class _OgreGLES2Export GLSLESCgProgramFactory : public HighLevelGpuProgramFactory - { - protected: - static String sLanguageName; - public: - GLSLESCgProgramFactory(); - virtual ~GLSLESCgProgramFactory(); - - const String& getLanguage(void) const; - HighLevelGpuProgram* create(ResourceManager* creator, const String& name, ResourceHandle handle, const String& group, bool isManual, ManualResourceLoader* loader); - void destroy(HighLevelGpuProgram* prog); - }; -} - -#endif // __GLSLESCgProgramFactory_H__ diff --git a/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESExtSupport.h b/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESExtSupport.h deleted file mode 100644 index 1d39cf07b71..00000000000 --- a/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESExtSupport.h +++ /dev/null @@ -1,54 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - - - -#ifndef __GLSLESExtSupport_H__ -#define __GLSLESExtSupport_H__ - -#include "OgreGLES2Prerequisites.h" - -// -// OpenGL Shading Language ES entry points -// -namespace Ogre -{ -namespace GLSLES { - /** If there is a message in GL info log then post it in the Ogre Log - @param msg The info log message string is appended to this string - @param obj The GL object that is used to retrieve the info log - */ - String logObjectInfo(const String& msg, GLuint obj); - - /// just return the info without logging it - String getObjectInfo(GLuint obj); - -} -} // namespace Ogre - -#endif // __GLSLESExtSupport_H__ diff --git a/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESLinkProgram.h b/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESLinkProgram.h deleted file mode 100644 index 4b131b9c8fc..00000000000 --- a/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESLinkProgram.h +++ /dev/null @@ -1,74 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLSLESLinkProgram_H__ -#define __GLSLESLinkProgram_H__ - -#include "OgreGLES2Prerequisites.h" -#include "OgreGpuProgram.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreGLSLESProgramCommon.h" -#include "OgreGLES2ManagedResource.h" - -namespace Ogre { - - class GLSLESGpuProgram; - - /** C++ encapsulation of GLSL ES Program Object - - */ - - class _OgreGLES2Export GLSLESLinkProgram : public GLSLESProgramCommon - { - protected: - /// Compiles and links the vertex and fragment programs - void compileAndLink(void) override; - - void buildGLUniformReferences(void); - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - void notifyOnContextLost() override; -#endif - - public: - /// Constructor should only be used by GLSLESLinkProgramManager - explicit GLSLESLinkProgram(const GLShaderList& shaders); - virtual ~GLSLESLinkProgram(void); - - /** Makes a program object active by making sure it is linked and then putting it in use. - */ - void activate(void) override; - - /** Updates program object uniforms using data from GpuProgramParameters. - normally called by GLSLESGpuProgram::bindParameters() just before rendering occurs. - */ - void updateUniforms(GpuProgramParametersSharedPtr params, uint16 mask, GpuProgramType fromProgType) override; - }; - -} - -#endif // __GLSLESLinkProgram_H__ diff --git a/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESProgram.h b/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESProgram.h deleted file mode 100644 index 16cc8f9d7dd..00000000000 --- a/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESProgram.h +++ /dev/null @@ -1,127 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLSLESProgram_H__ -#define __GLSLESProgram_H__ - -#include "OgreGLES2Prerequisites.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreGLSLShaderCommon.h" -#include "OgreGLES2ManagedResource.h" - -namespace Ogre { - class _OgreGLES2Export GLSLESProgram : public GLSLShaderCommon MANAGED_RESOURCE - { - public: -#if !OGRE_NO_GLES2_GLSL_OPTIMISER - /// Command object for running the GLSL optimiser - class CmdOptimisation : public ParamCommand - { - public: - String doGet(const void* target) const; - void doSet(void* target, const String& val); - }; -#endif - GLSLESProgram(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader); - ~GLSLESProgram(); - - void attachToProgramObject( const GLuint programObject ) override; - void detachFromProgramObject( const GLuint programObject ) override; - -#if !OGRE_NO_GLES2_GLSL_OPTIMISER - /// Sets if the GLSL optimiser is enabled. - void setOptimiserEnabled(bool enabled); - /// Gets if the GLSL optimiser is enabled. - bool getOptimiserEnabled(void) const { return mOptimiserEnabled; } - - /// Sets if the GLSL source has been optimised successfully - void setIsOptimised(bool flag) { mIsOptimised = flag; } - /// Gets if the GLSL source has been optimised successfully - bool getIsOptimised(void) { return mIsOptimised; } - - /// Sets the optimised GLSL source - void setOptimisedSource(const String& src) { mOptimisedSource = src; } - /// Gets he optimised GLSL source - String getOptimisedSource(void) { return mOptimisedSource; } -#endif - - /// Overridden from GpuProgram - const String& getLanguage(void) const override; - /// Overridden from GpuProgram - GpuProgramParametersSharedPtr createParameters(void) override; - - bool linkSeparable() override; - - protected: -#if !OGRE_NO_GLES2_GLSL_OPTIMISER - static CmdOptimisation msCmdOptimisation; -#endif - - void loadFromSource() override; - /// Internal unload implementation, must be implemented by subclasses - void unloadHighLevelImpl(void) override; - - /// Populate the passed parameters with name->index map, must be overridden - void buildConstantDefinitions() override; - /** check the compile result for an error with default precision - and recompile if needed. - some glsl compilers return an error default precision is set to types other then - int or float, this function test a failed compile result for the error, - delete the needed lines from the source if needed then try to re-compile. - */ - void checkAndFixInvalidDefaultPrecisionError( String &message ); - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - void notifyOnContextLost() override; - void notifyOnContextReset() override; -#endif - - private: -#if !OGRE_NO_GLES2_GLSL_OPTIMISER - /// Flag indicating if shader has been successfully optimised - bool mIsOptimised; - bool mOptimiserEnabled; - /// The optmised source of the program (may be blank until the shader is optmisied) - String mOptimisedSource; -#endif - }; - - /** Factory class for GLSL ES programs. */ - class GLSLESProgramFactory : public HighLevelGpuProgramFactory - { - public: - /// Get the name of the language this factory creates programs for - const String& getLanguage(void) const override; - /// Create an instance of GLSLESProgram - GpuProgram* create(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) override; - }; -} - -#endif // __GLSLESProgram_H__ diff --git a/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESProgramCommon.h b/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESProgramCommon.h deleted file mode 100644 index c22a9de885b..00000000000 --- a/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESProgramCommon.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#ifndef __GLSLESProgramCommon_H__ -#define __GLSLESProgramCommon_H__ - -#include "OgreGLES2Prerequisites.h" -#include "OgreGpuProgram.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreGLUniformCache.h" -#include "OgreGLSLProgramCommon.h" -#include "OgreGLSLESProgram.h" - -namespace Ogre { - /** C++ encapsulation of GLSL ES Program Object - - */ - - class _OgreGLES2Export GLSLESProgramCommon : public GLSLProgramCommon MANAGED_RESOURCE - { - protected: -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - void notifyOnContextLost() override; - - void notifyOnContextReset() override; -#endif - /// Constructor should only be used by GLSLESLinkProgramManager and GLSLESProgramPipelineManager - GLSLESProgramCommon(const GLShaderList& shaders); - public: - /// Get the the binary data of a program from the microcode cache - static bool getMicrocodeFromCache(uint32 id, GLuint programHandle); - static void _writeToCache(uint32 id, GLuint programHandle); - static void bindFixedAttributes(GLuint program); - }; -} - -#endif // __GLSLESProgramCommon_H__ diff --git a/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESProgramManager.h b/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESProgramManager.h deleted file mode 100644 index 2bf098b3a6f..00000000000 --- a/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESProgramManager.h +++ /dev/null @@ -1,98 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLSLESProgramManagerCommon_H__ -#define __GLSLESProgramManagerCommon_H__ - -#include "OgreGLES2Prerequisites.h" -#include "OgreGLSLProgramManagerCommon.h" -#include "OgreGLSLESProgramCommon.h" -#include "OgreGLSLESExtSupport.h" - -#if !OGRE_NO_GLES2_GLSL_OPTIMISER -# include "glsl_optimizer.h" -#endif - -namespace Ogre { - - /** Ogre assumes that there are separate vertex and fragment programs to deal with but - GLSL ES has one program object that represents the active vertex and fragment shader objects - during a rendering state. GLSL Vertex and fragment - shader objects are compiled separately and then attached to a program object and then the - program object is linked. Since Ogre can only handle one vertex program and one fragment - program being active in a pass, the GLSL ES Link Program Manager does the same. The GLSL ES Link - program manager acts as a state machine and activates a program object based on the active - vertex and fragment program. Previously created program objects are stored along with a unique - key in a hash_map for quick retrieval the next time the program object is required. - */ - class _OgreGLES2Export GLSLESProgramManager : public GLSLProgramManagerCommon, public Singleton - { - protected: -#if !OGRE_NO_GLES2_GLSL_OPTIMISER - struct glslopt_ctx *mGLSLOptimiserContext; -#endif - public: - - GLSLESProgramManager(void); - ~GLSLESProgramManager(void); - - /** - Get the program object that links the two active shader objects together - if a program object was not already created and linked a new one is created and linked - */ - GLSLESProgramCommon* getActiveProgram(void); - -#if !OGRE_NO_GLES2_GLSL_OPTIMISER - /** - - */ - void optimiseShaderSource(GLSLESGpuProgram* gpuProgram); -#endif - - /** Populate a list of uniforms based on a program object. - @param programObject Handle to the program object to query - @param vertexConstantDefs Definition of the constants extracted from the - vertex program, used to match up physical buffer indexes with program - uniforms. May be null if there is no vertex program. - @param fragmentConstantDefs Definition of the constants extracted from the - fragment program, used to match up physical buffer indexes with program - uniforms. May be null if there is no fragment program. - @param list The list to populate (will not be cleared before adding, clear - it yourself before calling this if that's what you want). - */ - static void extractUniforms(GLuint programObject, - const GpuConstantDefinitionMap* vertexConstantDefs, - const GpuConstantDefinitionMap* fragmentConstantDefs, - GLUniformReferenceList& list); - - static GLSLESProgramManager& getSingleton(void); - static GLSLESProgramManager* getSingletonPtr(void); - }; - -} - -#endif // __GLSLESProgramManagerCommon_H__ diff --git a/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESProgramPipeline.h b/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESProgramPipeline.h deleted file mode 100644 index b44aa6ae348..00000000000 --- a/RenderSystems/GLES2/src/GLSLES/include/OgreGLSLESProgramPipeline.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#ifndef __GLSLESProgramPipeline_H__ -#define __GLSLESProgramPipeline_H__ - -#include "OgreGLES2Prerequisites.h" -#include "OgreGLSLESProgramCommon.h" - -namespace Ogre -{ - /** Specialisation of HighLevelGpuProgram to provide support for OpenGL - Shader Language (GLSL ES) for OpenGL ES 2.0. - - GLSL ES has no target assembler or entry point specification like DirectX 9 HLSL. - Vertex and Fragment shaders only have one entry point called "main". - When a shader is compiled, microcode is generated but can not be accessed by - the application. - GLSL ES also does not provide assembler low level output after compiling. The GL ES Render - system assumes that the Gpu program is a GL Gpu program so GLSLESProgramPipeline will create a - GLSLESGpuProgram that is subclassed from GLES2GpuProgram for the low level implementation. - The GLES2Program class will create a shader and program object and compile the source but will - not create a pipeline object. It's up to GLES2GpuProgram class to request a program pipeline object - to link the program object to. - - @note - GLSL ES supports multiple modular shader objects that can be attached to one program - object to form a single shader. This is supported through the "attach" material script - command. All the modules to be attached are listed on the same line as the attach command - separated by white space. - */ - class _OgreGLES2Export GLSLESProgramPipeline : public GLSLESProgramCommon - { - public: - /// Constructor should only be used by GLSLESProgramPipelineManager - explicit GLSLESProgramPipeline(const GLShaderList& shaders); - virtual ~GLSLESProgramPipeline(); - - /** Updates program pipeline object uniforms using data from GpuProgramParameters. - normally called by GLSLESGpuProgram::bindParameters() just before rendering occurs. - */ - void updateUniforms(GpuProgramParametersSharedPtr params, uint16 mask, GpuProgramType fromProgType) override; - - /** Makes a program pipeline object active by making sure it is linked and then putting it in use. - */ - void activate(void) override; - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - void notifyOnContextLost() override; -#endif - - protected: - /// Compiles and links the separate vertex and fragment programs - void compileAndLink(void) override; - - /// Build uniform references from active named uniforms - virtual void buildGLUniformReferences(void); - }; -} - -#endif diff --git a/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESCgProgram.cpp b/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESCgProgram.cpp deleted file mode 100644 index 967088c713d..00000000000 --- a/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESCgProgram.cpp +++ /dev/null @@ -1,334 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreGLSLESCgProgram.h" -#include "OgreResourceGroupManager.h" -#include "OgreStringConverter.h" -#include "OgreGpuProgramManager.h" -#include "OgreLogManager.h" -#include "hlsl2glsl.h" // use the code from here: http://code.google.com/p/hlsl2glslfork/ - -namespace Ogre { - - //----------------------------------------------------------------------- - GLSLESCgProgram::CmdProfiles GLSLESCgProgram::msCmdProfiles; - //----------------------------------------------------------------------- - // for use with Hlsl2Glsl_SetUserAttributeNames to map ogre att names - EAttribSemantic gAttribSemantic[] = { - EAttrSemPosition, - EAttrSemNormal, - EAttrSemColor0, - EAttrSemColor1, - EAttrSemColor2, - EAttrSemColor3, - EAttrSemTex0, - EAttrSemTex1, - EAttrSemTex2, - EAttrSemTex3, - EAttrSemTex4, - EAttrSemTex5, - EAttrSemTex6, - EAttrSemTex7, - EAttrSemTex8, - EAttrSemTex9, - EAttrSemTangent, - EAttrSemBinormal, - EAttrSemBlendWeight, - EAttrSemBlendIndices - }; - int gNumberOfAttribSemantic = sizeof(gAttribSemantic) / sizeof(EAttribSemantic); - - // for use with Hlsl2Glsl_SetUserAttributeNames to map ogre att names - const char* gAttribString[] = { - "vertex", - "normal", - "colour", - "colour1", - "colour2", - "colour3", - "uv", - "uv1", - "uv2", - "uv3", - "uv4", - "uv5", - "uv6", - "uv7", - "uv8", - "uv9", - "tangent", - "binormal", - "blendWeights", - "blendIndices" - }; - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - GLSLESCgProgram::GLSLESCgProgram(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - : GLSLESProgram(creator, name, handle, group, isManual, loader) - { - - // Add parameter "entry_point" and "profiles" to the material serializer dictionary - if (createParamDictionary("GLSLESCgProgram")) - { - setupBaseParamDictionary(); - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter(ParameterDef("profiles", - "Space-separated list of Cg profiles supported by this profile.", - PT_STRING),&msCmdProfiles); - - } - } - //--------------------------------------------------------------------------- - GLSLESCgProgram::~GLSLESCgProgram() - { - } - //----------------------------------------------------------------------- - String GLSLESCgProgram::deleteRegisterFromCg(const String& inSource) - { -#define REGISTER_STRING ": register" - String outSource; - // output will be at least this big - outSource.reserve(inSource.length()); - - size_t startMarker = 0; - size_t i = inSource.find(REGISTER_STRING); - while (i != String::npos) - { - size_t registerPos = i; - size_t afterRegisterPos = registerPos + 8; - size_t newLineBefore = inSource.rfind("\n", registerPos); - - // check we're not in a comment - size_t lineCommentIt = inSource.rfind("//", registerPos); - if (lineCommentIt != String::npos) - { - if (newLineBefore == String::npos || lineCommentIt > newLineBefore) - { - // commented - i = inSource.find(REGISTER_STRING, afterRegisterPos); - continue; - } - - } - size_t blockCommentIt = inSource.rfind("/*", registerPos); - if (blockCommentIt != String::npos) - { - size_t closeCommentIt = inSource.rfind("*/", registerPos); - if (closeCommentIt == String::npos || closeCommentIt < blockCommentIt) - { - // commented - i = inSource.find(REGISTER_STRING, afterRegisterPos); - continue; - } - - } - - // find following newline (or EOF) - size_t newLineAfter = inSource.find("\n", afterRegisterPos); - // find register file string container - String endDelimiter = "\""; - size_t startIt = inSource.find("\"", afterRegisterPos); - if (startIt == String::npos || startIt > newLineAfter) - { - // try <> - startIt = inSource.find("(", afterRegisterPos); - if (startIt == String::npos || startIt > newLineAfter) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Badly formed register directive (expected () in file " - + mFilename + ": " + inSource.substr(registerPos, newLineAfter-registerPos), - "GLSLESCgProgram::deleteRegisterFromCg"); - } - else - { - endDelimiter = ")"; - } - } - size_t endIt = inSource.find(endDelimiter, startIt+1); - if (endIt == String::npos || endIt <= startIt) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Badly formed register directive (expected " + endDelimiter + ") in file " - + mFilename + ": " + inSource.substr(registerPos, newLineAfter-registerPos), - "GLSLESCgProgram::deleteRegisterFromCg"); - } - - // delete the register - if (newLineBefore != String::npos && registerPos >= startMarker) - outSource.append(inSource.substr(startMarker, registerPos-startMarker)); - - startMarker = endIt + 1; - - if (startMarker != String::npos) - i = inSource.find(REGISTER_STRING, startMarker); - else - i = String::npos; - - } - // copy any remaining characters - outSource.append(inSource.substr(startMarker)); - - return outSource; - } - //----------------------------------------------------------------------- - void GLSLESCgProgram::loadFromSource( void ) - { - GLSLESProgram::prepareImpl(); // loads + preprocesses source - - // check if syntax is supported - if (!isSyntaxSupported()) - { - mSource = ""; - LogManager::getSingleton().logMessage( - "File:" + mFilename + - " has unsupported syntax for hlsl2glsl."); - return; - } - - // delete ": register(xx)" that hlsl2glsl doesn't know to handle - String sourceToUse = deleteRegisterFromCg(sourceToUse); - - - // select the program type - EShLanguage lang = EShLangCount; - switch(getType()) - { - case GPT_VERTEX_PROGRAM: - lang = EShLangVertex; - break; - case GPT_FRAGMENT_PROGRAM: - lang = EShLangFragment; - break; - default: - mSource = ""; - LogManager::getSingleton().logMessage( - "File:" + mFilename + - " has unsupported program type."); - return; - } - - - int options = 0; - // options |= ETranslateOpUsePrecision; this option doesn't work good with the ogre glsl parameter parser - - // create the parser - ShHandle parser = Hlsl2Glsl_ConstructCompiler(lang); - - // set the user attribute to be ogre's - Hlsl2Glsl_SetUserAttributeNames (parser, gAttribSemantic, gAttribString, gNumberOfAttribSemantic); - - int res = 0; - // parse the file - res = Hlsl2Glsl_Parse(parser, sourceToUse.c_str(), ETargetGLSL_ES_100, nullptr, options); - // convert from cg to glsl - res = res && Hlsl2Glsl_Translate(parser, mEntryPoint.c_str(), ETargetGLSL_ES_100, options); - - // check for error - if (res == 0) - { - const char* parserErrors = Hlsl2Glsl_GetInfoLog(parser); - - LogManager::getSingleton().logMessage( - "File:" + mFilename + - " failed to convert from Cg to glsl with the following errors:\n" + parserErrors); - - Hlsl2Glsl_DestructCompiler(parser); - - mSource = ""; - return; - } - - - String glslSource; - // add the glsl precision thing - glslSource = glslSource + "#version 100\n"; - glslSource = glslSource + "precision mediump int;\n"; - glslSource = glslSource + "precision mediump float;\n"; - //glslSource = glslSource + "precision lowp sampler2D;\n"; - //glslSource = glslSource + "precision lowp samplerCube;\n"; - - // get the glsl code from the parser - glslSource = glslSource + Hlsl2Glsl_GetShader(parser); - - // update mSource to now be glsl code - mSource = glslSource; - - // delete the parser - Hlsl2Glsl_DestructCompiler(parser); - - } - //----------------------------------------------------------------------- - const String& GLSLESCgProgram::getLanguage( void ) const - { - static const String language = "cg"; - - return language; - } - //----------------------------------------------------------------------- - void GLSLESCgProgram::setProfiles( const StringVector& profiles ) - { - mProfiles.clear(); - StringVector::const_iterator i, iend; - iend = profiles.end(); - for (i = profiles.begin(); i != iend; ++i) - { - mProfiles.push_back(*i); - } - } - //----------------------------------------------------------------------- - bool GLSLESCgProgram::isSyntaxSupported() - { - bool syntaxSupported = false; - StringVector::iterator i, iend; - iend = mProfiles.end(); - GpuProgramManager& gpuMgr = GpuProgramManager::getSingleton(); - for (i = mProfiles.begin(); i != iend; ++i) - { - if (gpuMgr.isSyntaxSupported(*i)) - { - syntaxSupported = true; - break; - } - } - return syntaxSupported; - } - //----------------------------------------------------------------------- - String GLSLESCgProgram::CmdProfiles::doGet(const void *target) const - { - return StringConverter::toString( - static_cast(target)->getProfiles() ); - } - void GLSLESCgProgram::CmdProfiles::doSet(void *target, const String& val) - { - static_cast(target)->setProfiles(StringUtil::split(val)); - } - //----------------------------------------------------------------------- - -} diff --git a/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESCgProgramFactory.cpp b/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESCgProgramFactory.cpp deleted file mode 100644 index a5a7d33c180..00000000000 --- a/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESCgProgramFactory.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLSLESCgProgramFactory.h" -#include "OgreGLSLESCgProgram.h" -#include "hlsl2glsl.h" // use the code from here: http://code.google.com/p/hlsl2glslfork/ - -namespace Ogre { - //----------------------------------------------------------------------- - String GLSLESCgProgramFactory::sLanguageName = "cg"; - //----------------------------------------------------------------------- - GLSLESCgProgramFactory::GLSLESCgProgramFactory() - { - Hlsl2Glsl_Initialize(); - } - //----------------------------------------------------------------------- - GLSLESCgProgramFactory::~GLSLESCgProgramFactory() - { - Hlsl2Glsl_Shutdown(); - } - //----------------------------------------------------------------------- - const String& GLSLESCgProgramFactory::getLanguage(void) const - { - return sLanguageName; - } - //----------------------------------------------------------------------- - HighLevelGpuProgram* GLSLESCgProgramFactory::create(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - { - return OGRE_NEW GLSLESCgProgram(creator, name, handle, group, isManual, loader); - } - //----------------------------------------------------------------------- - void GLSLESCgProgramFactory::destroy(HighLevelGpuProgram* prog) - { - OGRE_DELETE prog; - } - - -} diff --git a/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESExtSupport.cpp b/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESExtSupport.cpp deleted file mode 100644 index c28cf2b067f..00000000000 --- a/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESExtSupport.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLSLESExtSupport.h" -#include "OgreLogManager.h" -#include "OgreRoot.h" -#include "OgreGLUtil.h" -#include "OgreGLES2RenderSystem.h" - -namespace Ogre -{ - namespace GLSLES { - String logObjectInfo(const String& msg, GLuint obj) - { - String logMessage = getObjectInfo(obj); - - if (logMessage.empty()) - return msg; - - logMessage = msg + "\n" + logMessage; - - LogManager::getSingleton().logMessage(LML_CRITICAL, logMessage); - - return logMessage; - } - - String getObjectInfo(const GLuint obj) - { - String logMessage; - - if (obj > 0) - { - GLint infologLength = 0; - - if(glIsShader(obj)) - { - OGRE_CHECK_GL_ERROR(glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &infologLength)); - } - else if(glIsProgram(obj)) - { - OGRE_CHECK_GL_ERROR(glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &infologLength)); - } - - else if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) - { - if(glIsProgramPipelineEXT(obj)) - OGRE_CHECK_GL_ERROR(glGetProgramPipelineivEXT(obj, GL_INFO_LOG_LENGTH, &infologLength)); - } - - if (infologLength > 1) - { - GLint charsWritten = 0; - - char * infoLog = new char [infologLength]; - infoLog[0] = 0; - - if(glIsShader(obj)) - { - OGRE_CHECK_GL_ERROR(glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog)); - } - else if(glIsProgram(obj)) - { - OGRE_CHECK_GL_ERROR(glGetProgramInfoLog(obj, infologLength, &charsWritten, infoLog)); - } - else if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) - { - if(glIsProgramPipelineEXT(obj)) - OGRE_CHECK_GL_ERROR(glGetProgramPipelineInfoLogEXT(obj, infologLength, &charsWritten, infoLog)); - } - - if (strlen(infoLog) > 0) - { - logMessage = String(infoLog); - } - - delete [] infoLog; - - StringUtil::trim(logMessage, false, true); - } - } - - return logMessage; - } - - } -} // namespace Ogre diff --git a/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESLinkProgram.cpp b/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESLinkProgram.cpp deleted file mode 100644 index 5cb052037b5..00000000000 --- a/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESLinkProgram.cpp +++ /dev/null @@ -1,314 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLSLESLinkProgram.h" -#include "OgreGLSLESProgram.h" -#include "OgreGLSLESProgramManager.h" -#include "OgreLogManager.h" -#include "OgreGpuProgramManager.h" -#include "OgreStringConverter.h" -#include "OgreRoot.h" -#include "OgreGLUtil.h" -#include "OgreGLES2RenderSystem.h" -#include "OgreGLNativeSupport.h" - -namespace Ogre { - - //----------------------------------------------------------------------- - GLSLESLinkProgram::GLSLESLinkProgram(const GLShaderList& shaders) - : GLSLESProgramCommon(shaders) - { - } - - //----------------------------------------------------------------------- - GLSLESLinkProgram::~GLSLESLinkProgram(void) - { - OGRE_CHECK_GL_ERROR(glDeleteProgram(mGLProgramHandle)); - } - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - void GLSLESLinkProgram::notifyOnContextLost() - { - OGRE_CHECK_GL_ERROR(glDeleteProgram(mGLProgramHandle)); - mGLProgramHandle = 0; - GLSLESProgramCommon::notifyOnContextLost(); - } -#endif - //----------------------------------------------------------------------- - void GLSLESLinkProgram::activate(void) - { - if (!mLinked) - { - glGetError(); // Clean up the error. Otherwise will flood log. - - OGRE_CHECK_GL_ERROR(mGLProgramHandle = glCreateProgram()); - - uint32 hash = getCombinedHash(); - mLinked = getMicrocodeFromCache(hash, mGLProgramHandle); - if (!mLinked) - { -#if !OGRE_NO_GLES2_GLSL_OPTIMISER - // Check CmdParams for each shader type to see if we should optimize - if(mVertexProgram) - { - String paramStr = mVertexProgram->getGLSLProgram()->getParameter("use_optimiser"); - if((paramStr == "true") || paramStr.empty()) - { - GLSLESLinkProgramManager::getSingleton().optimiseShaderSource(mVertexProgram); - } - } - - if(mFragmentProgram) - { - String paramStr = mFragmentProgram->getGLSLProgram()->getParameter("use_optimiser"); - if((paramStr == "true") || paramStr.empty()) - { - GLSLESLinkProgramManager::getSingleton().optimiseShaderSource(mFragmentProgram); - } - } -#endif - compileAndLink(); - -#if !OGRE_NO_GLES2_GLSL_OPTIMISER - // TODO: we will never reach this - move to GLSLESProgram - // Try it again when we used the optimised versions - if(mVertexProgram->getGLSLProgram()->getOptimiserEnabled() && - mFragmentProgram->getGLSLProgram()->getOptimiserEnabled()) - { - LogManager::getSingleton().stream() << "Try not optimised shader."; - mVertexProgram->getGLSLProgram()->setOptimiserEnabled(false); - mFragmentProgram->getGLSLProgram()->setOptimiserEnabled(false); - compileAndLink(); - } -#endif - } - - buildGLUniformReferences(); - } - - if (mLinked) - { - OGRE_CHECK_GL_ERROR(glUseProgram( mGLProgramHandle )); - } - } - - //----------------------------------------------------------------------- - void GLSLESLinkProgram::compileAndLink() - { - uint32 hash = getCombinedHash(); - - // attach Vertex Program - mShaders[GPT_VERTEX_PROGRAM]->attachToProgramObject(mGLProgramHandle); - // attach Fragment Program - mShaders[GPT_FRAGMENT_PROGRAM]->attachToProgramObject(mGLProgramHandle); - - bindFixedAttributes( mGLProgramHandle ); - - // The link - OGRE_CHECK_GL_ERROR(glLinkProgram( mGLProgramHandle )); - OGRE_CHECK_GL_ERROR(glGetProgramiv( mGLProgramHandle, GL_LINK_STATUS, &mLinked )); - - GLSLES::logObjectInfo( getCombinedName() + String("GLSL link result : "), mGLProgramHandle ); - - const RenderSystemCapabilities* caps = Root::getSingleton().getRenderSystem()->getCapabilities(); - - if(caps->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) - { - if(glIsProgramPipelineEXT(mGLProgramHandle)) - glValidateProgramPipelineEXT(mGLProgramHandle); - } - else if(glIsProgram(mGLProgramHandle)) - { - glValidateProgram(mGLProgramHandle); - } - - GLSLES::logObjectInfo( getCombinedName() + String(" GLSL validation result : "), mGLProgramHandle ); - - if(mLinked) - { - _writeToCache(hash, mGLProgramHandle); - } - } - - //----------------------------------------------------------------------- - void GLSLESLinkProgram::buildGLUniformReferences(void) - { - if (!mUniformRefsBuilt) - { - const GpuConstantDefinitionMap* vertParams = 0; - const GpuConstantDefinitionMap* fragParams = 0; - if (mShaders[GPT_VERTEX_PROGRAM]) - { - vertParams = &(mShaders[GPT_VERTEX_PROGRAM]->getConstantDefinitions().map); - } - if (mShaders[GPT_FRAGMENT_PROGRAM]) - { - fragParams = &(mShaders[GPT_FRAGMENT_PROGRAM]->getConstantDefinitions().map); - } - - GLSLESProgramManager::extractUniforms(mGLProgramHandle, vertParams, fragParams, - mGLUniformReferences); - - mUniformRefsBuilt = true; - } - } - - //----------------------------------------------------------------------- - void GLSLESLinkProgram::updateUniforms(GpuProgramParametersSharedPtr params, - uint16 mask, GpuProgramType fromProgType) - { - // Iterate through uniform reference list and update uniform values - GLUniformReferenceIterator currentUniform = mGLUniformReferences.begin(); - GLUniformReferenceIterator endUniform = mGLUniformReferences.end(); - - for (;currentUniform != endUniform; ++currentUniform) - { - // Only pull values from buffer it's supposed to be in (vertex or fragment) - // This method will be called twice, once for vertex program params, - // and once for fragment program params. - if (fromProgType == currentUniform->mSourceProgType) - { - const GpuConstantDefinition* def = currentUniform->mConstantDef; - if (def->variability & mask) - { - GLsizei glArraySize = (GLsizei)def->arraySize; - - // this is a monolitic program so we can use the cache of any attached shader - GLUniformCache* uniformCache = mShaders[GPT_VERTEX_PROGRAM]->getUniformCache(); - void* val = def->isSampler() ? (void*)params->getRegPointer(def->physicalIndex) - : (void*)params->getFloatPointer(def->physicalIndex); - - bool shouldUpdate = uniformCache->updateUniform(currentUniform->mLocation, val, - def->elementSize * glArraySize * 4); - if(!shouldUpdate) - continue; - - // Get the index in the parameter real list - switch (def->constType) - { - case GCT_FLOAT1: - OGRE_CHECK_GL_ERROR(glUniform1fv(currentUniform->mLocation, glArraySize, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_FLOAT2: - OGRE_CHECK_GL_ERROR(glUniform2fv(currentUniform->mLocation, glArraySize, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_FLOAT3: - OGRE_CHECK_GL_ERROR(glUniform3fv(currentUniform->mLocation, glArraySize, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_FLOAT4: - OGRE_CHECK_GL_ERROR(glUniform4fv(currentUniform->mLocation, glArraySize, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_2X2: - OGRE_CHECK_GL_ERROR(glUniformMatrix2fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_3X3: - OGRE_CHECK_GL_ERROR(glUniformMatrix3fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_4X4: - OGRE_CHECK_GL_ERROR(glUniformMatrix4fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_2X3: - OGRE_CHECK_GL_ERROR(glUniformMatrix2x3fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_2X4: - OGRE_CHECK_GL_ERROR(glUniformMatrix2x4fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_3X2: - OGRE_CHECK_GL_ERROR(glUniformMatrix3x2fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_3X4: - OGRE_CHECK_GL_ERROR(glUniformMatrix3x4fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_4X2: - OGRE_CHECK_GL_ERROR(glUniformMatrix4x2fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_4X3: - OGRE_CHECK_GL_ERROR(glUniformMatrix4x3fv(currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_SAMPLER1D: - case GCT_SAMPLER1DSHADOW: - case GCT_SAMPLER2D: - case GCT_SAMPLER2DSHADOW: - case GCT_SAMPLER3D: - case GCT_SAMPLERCUBE: - case GCT_SAMPLER2DARRAY: - // Samplers handled like 1-element ints - case GCT_INT1: - OGRE_CHECK_GL_ERROR(glUniform1iv(currentUniform->mLocation, glArraySize, - (GLint*)val)); - break; - case GCT_INT2: - OGRE_CHECK_GL_ERROR(glUniform2iv(currentUniform->mLocation, glArraySize, - (GLint*)params->getIntPointer(def->physicalIndex))); - break; - case GCT_INT3: - OGRE_CHECK_GL_ERROR(glUniform3iv(currentUniform->mLocation, glArraySize, - (GLint*)params->getIntPointer(def->physicalIndex))); - break; - case GCT_INT4: - OGRE_CHECK_GL_ERROR(glUniform4iv(currentUniform->mLocation, glArraySize, - (GLint*)params->getIntPointer(def->physicalIndex))); - break; - case GCT_UNKNOWN: - case GCT_SPECIALIZATION: - case GCT_DOUBLE1: - case GCT_DOUBLE2: - case GCT_DOUBLE3: - case GCT_DOUBLE4: - case GCT_MATRIX_DOUBLE_2X2: - case GCT_MATRIX_DOUBLE_2X3: - case GCT_MATRIX_DOUBLE_2X4: - case GCT_MATRIX_DOUBLE_3X2: - case GCT_MATRIX_DOUBLE_3X3: - case GCT_MATRIX_DOUBLE_3X4: - case GCT_MATRIX_DOUBLE_4X2: - case GCT_MATRIX_DOUBLE_4X3: - case GCT_MATRIX_DOUBLE_4X4: - default: - break; - - } // End switch - } // Variability & mask - } // fromProgType == currentUniform->mSourceProgType - - } // End for - } -} // namespace Ogre diff --git a/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESProgram.cpp b/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESProgram.cpp deleted file mode 100644 index 9a4a2b43922..00000000000 --- a/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESProgram.cpp +++ /dev/null @@ -1,326 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreGLES2Prerequisites.h" -#include "OgreGpuProgram.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreLogManager.h" -#include "OgreRoot.h" -#include "OgreStringConverter.h" -#include "OgreGLUtil.h" -#include "OgreGLES2RenderSystem.h" -#include "OgreGLNativeSupport.h" - -#include "OgreGLSLESProgram.h" -#include "OgreGLSLESProgramManager.h" -#include "OgreGLSLPreprocessor.h" - -namespace Ogre { - //----------------------------------------------------------------------- -#if !OGRE_NO_GLES2_GLSL_OPTIMISER - GLSLESProgram::CmdOptimisation GLSLESProgram::msCmdOptimisation; -#endif - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - GLSLESProgram::GLSLESProgram(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - : GLSLShaderCommon(creator, name, handle, group, isManual, loader) -#if !OGRE_NO_GLES2_GLSL_OPTIMISER - , mIsOptimised(false) - , mOptimiserEnabled(false) -#endif - { - if (createParamDictionary("GLSLESProgram")) - { - setupBaseParamDictionary(); -#if !OGRE_NO_GLES2_GLSL_OPTIMISER - ParamDictionary* dict = getParamDictionary(); - dict->addParameter(ParameterDef("use_optimiser", - "Should the GLSL optimiser be used. Default is false.", - PT_BOOL),&msCmdOptimisation); -#endif - } - // There is nothing to load - mLoadFromFile = false; - } - //--------------------------------------------------------------------------- - GLSLESProgram::~GLSLESProgram() - { - // Have to call this here reather than in Resource destructor - // since calling virtual methods in base destructors causes crash - if (isLoaded()) - { - unload(); - } - else - { - unloadHighLevel(); - } - } - //--------------------------------------------------------------------------- -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - void GLSLESProgram::notifyOnContextLost() - { - unloadHighLevelImpl(); - } - - void GLSLESProgram::notifyOnContextReset() - { - try { - loadFromSource(); - } - catch(Exception& e) - { - // we already compiled this once, this should not happen - LogManager::getSingleton().stream(LML_WARNING) << e.what(); - } - } -#endif - bool GLSLESProgram::linkSeparable() - { - if(mLinked) - return true; - - uint32 hash = _getHash(); - - if (GLSLESProgramCommon::getMicrocodeFromCache(hash, mGLProgramHandle)) - { - mLinked = true; - } - else - { - if( mType == GPT_VERTEX_PROGRAM ) - GLSLESProgramCommon::bindFixedAttributes( mGLProgramHandle ); - - OGRE_CHECK_GL_ERROR(glProgramParameteriEXT(mGLProgramHandle, GL_PROGRAM_SEPARABLE_EXT, GL_TRUE)); - attachToProgramObject(mGLProgramHandle); - OGRE_CHECK_GL_ERROR(glLinkProgram(mGLProgramHandle)); - OGRE_CHECK_GL_ERROR(glGetProgramiv(mGLProgramHandle, GL_LINK_STATUS, &mLinked)); - - GLSLES::logObjectInfo( mName + String("GLSL vertex program result : "), mGLProgramHandle ); - - GLSLESProgramCommon::_writeToCache(hash, mGLProgramHandle); - } - - return mLinked; - } - - void GLSLESProgram::loadFromSource() - { - const RenderSystemCapabilities* caps = Root::getSingleton().getRenderSystem()->getCapabilities(); - - // Only create a shader object if glsl es is supported - if (isSupported()) - { - // Create shader object - GLenum shaderType = 0x0000; - if (mType == GPT_VERTEX_PROGRAM) - { - shaderType = GL_VERTEX_SHADER; - } - else if (mType == GPT_FRAGMENT_PROGRAM) - { - shaderType = GL_FRAGMENT_SHADER; - } - OGRE_CHECK_GL_ERROR(mGLShaderHandle = glCreateShader(shaderType)); - - if(caps->hasCapability(RSC_DEBUG)) - { - glLabelObjectEXT(GL_SHADER_OBJECT_EXT, mGLShaderHandle, 0, mName.c_str()); - } - - // also create program object - if (caps->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) - { - OGRE_CHECK_GL_ERROR(mGLProgramHandle = glCreateProgram()); - } - } - - // Add preprocessor extras and main source - if (!mSource.empty()) - { - size_t versionPos = mSource.find("#version"); - size_t belowVersionPos = 0; - - if(versionPos != String::npos) - { - belowVersionPos = mSource.find('\n', versionPos) + 1; - } - - // insert precision qualifier for improved compatibility - if(mType == GPT_FRAGMENT_PROGRAM && mSource.find("precision ") == String::npos) - mSource.insert(belowVersionPos, "precision mediump float;\n"); - - // Fix up the source in case someone forgot to redeclare gl_Position - if (caps->hasCapability(RSC_GLSL_SSO_REDECLARE) && mType == GPT_VERTEX_PROGRAM) - { - if(mShaderVersion >= 300) { - // Check that it's missing and that this shader has a main function, ie. not a child shader. - if(mSource.find("out highp vec4 gl_Position") == String::npos) - { - mSource.insert(belowVersionPos, "out highp vec4 gl_Position;\nout highp float gl_PointSize;\n"); - } - if(mSource.find("#extension GL_EXT_separate_shader_objects : require") == String::npos) - { - mSource.insert(belowVersionPos, "#extension GL_EXT_separate_shader_objects : require\n"); - } - } - } - -#if !OGRE_NO_GLES2_GLSL_OPTIMISER - const char *source = (getOptimiserEnabled() && getIsOptimised()) ? mOptimisedSource.c_str() : mSource.c_str(); -#else - const char *source = mSource.c_str(); -#endif - - OGRE_CHECK_GL_ERROR(glShaderSource(mGLShaderHandle, 1, &source, NULL)); - } - - OGRE_CHECK_GL_ERROR(glCompileShader(mGLShaderHandle)); - - // Check for compile errors - int compiled; - OGRE_CHECK_GL_ERROR(glGetShaderiv(mGLShaderHandle, GL_COMPILE_STATUS, &compiled)); - - String compileInfo = GLSLES::getObjectInfo(mGLShaderHandle); - - if (!compiled) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, getResourceLogName() + " " + compileInfo, "compile"); - - // probably we have warnings - if (!compileInfo.empty()) - LogManager::getSingleton().stream(LML_WARNING) << getResourceLogName() << " " << compileInfo; - } - -#if !OGRE_NO_GLES2_GLSL_OPTIMISER - //----------------------------------------------------------------------- - void GLSLESProgram::setOptimiserEnabled(bool enabled) - { - if(mOptimiserEnabled != enabled && mOptimiserEnabled && mCompiled == 1) - { - OGRE_CHECK_GL_ERROR(glDeleteShader(mGLShaderHandle)); - - if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) - { - OGRE_CHECK_GL_ERROR(glDeleteProgram(mGLProgramHandle)); - } - - mGLShaderHandle = 0; - mGLProgramHandle = 0; - mCompiled = 0; - } - mOptimiserEnabled = enabled; - } -#endif - //----------------------------------------------------------------------- - void GLSLESProgram::unloadHighLevelImpl(void) - { - if (isSupported()) - { -// LogManager::getSingleton().logMessage("Deleting shader " + StringConverter::toString(mGLShaderHandle) + -// " and program " + StringConverter::toString(mGLProgramHandle)); - OGRE_CHECK_GL_ERROR(glDeleteShader(mGLShaderHandle)); - - if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) - { - OGRE_CHECK_GL_ERROR(glDeleteProgram(mGLProgramHandle)); - } - // destroy all programs using this shader - GLSLESProgramManager::getSingletonPtr()->destroyAllByShader(this); - - - mGLShaderHandle = 0; - mGLProgramHandle = 0; - mLinked = 0; - } - } - //----------------------------------------------------------------------- - void GLSLESProgram::buildConstantDefinitions() - { - // We need an accurate list of all the uniforms in the shader, but we - // can't get at them until we link all the shaders into a program object. - - // Therefore instead, parse the source code manually and extract the uniforms - createParameterMappingStructures(true); - mLogicalToPhysical.reset(); - GLSLESProgramManager::getSingleton().extractUniformsFromGLSL(mSource, *mConstantDefs, getResourceLogName()); - } - - //----------------------------------------------------------------------- -#if !OGRE_NO_GLES2_GLSL_OPTIMISER - String GLSLESProgram::CmdOptimisation::doGet(const void *target) const - { - return StringConverter::toString(static_cast(target)->getOptimiserEnabled()); - } - void GLSLESProgram::CmdOptimisation::doSet(void *target, const String& val) - { - static_cast(target)->setOptimiserEnabled(StringConverter::parseBool(val)); - } -#endif - //----------------------------------------------------------------------- - void GLSLESProgram::attachToProgramObject( const GLuint programObject ) - { -// LogManager::getSingleton().logMessage("Attaching shader " + StringConverter::toString(mGLShaderHandle) + -// " to program " + StringConverter::toString(programObject)); - OGRE_CHECK_GL_ERROR(glAttachShader(programObject, mGLShaderHandle)); - } - //----------------------------------------------------------------------- - void GLSLESProgram::detachFromProgramObject( const GLuint programObject ) - { -// LogManager::getSingleton().logMessage("Detaching shader " + StringConverter::toString(mGLShaderHandle) + -// " to program " + StringConverter::toString(programObject)); - OGRE_CHECK_GL_ERROR(glDetachShader(programObject, mGLShaderHandle)); - } - - static const String language = "glsles"; - //----------------------------------------------------------------------- - const String& GLSLESProgram::getLanguage(void) const - { - return language; - } - //----------------------------------------------------------------------- - Ogre::GpuProgramParametersSharedPtr GLSLESProgram::createParameters( void ) - { - GpuProgramParametersSharedPtr params = HighLevelGpuProgram::createParameters(); - params->setTransposeMatrices(true); - return params; - } - - //----------------------------------------------------------------------- - const String& GLSLESProgramFactory::getLanguage(void) const - { - return language; - } - //----------------------------------------------------------------------- - GpuProgram* GLSLESProgramFactory::create(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - { - return OGRE_NEW GLSLESProgram(creator, name, handle, group, isManual, loader); - } -} diff --git a/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESProgramCommon.cpp b/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESProgramCommon.cpp deleted file mode 100644 index 16cc4d6326c..00000000000 --- a/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESProgramCommon.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ - -#include "OgreGLSLESProgramCommon.h" -#include "OgreGLSLESProgram.h" -#include "OgreGpuProgramManager.h" -#include "OgreGLUtil.h" -#include "OgreGLES2RenderSystem.h" -#include "OgreRoot.h" -#include "OgreGLNativeSupport.h" - -namespace Ogre { - - //----------------------------------------------------------------------- - GLSLESProgramCommon::GLSLESProgramCommon(const GLShaderList& shaders) - : GLSLProgramCommon(shaders) - { - } - - void GLSLESProgramCommon::bindFixedAttributes(GLuint program) - { - GLint maxAttribs = Root::getSingleton().getRenderSystem()->getCapabilities()->getNumVertexAttributes(); - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - // must query active attributes on OSX to avoid warning spam - OGRE_CHECK_GL_ERROR(glLinkProgram( program )); -#endif - - size_t numAttribs = sizeof(msCustomAttributes) / sizeof(CustomAttribute); - for (size_t i = 0; i < numAttribs; ++i) - { - const CustomAttribute& a = msCustomAttributes[i]; - if (a.attrib < maxAttribs) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - if(glGetAttribLocation(program, a.name) == -1) continue; -#endif - OGRE_CHECK_GL_ERROR(glBindAttribLocation(program, a.attrib, a.name)); - } - } - } - - //----------------------------------------------------------------------- - bool GLSLESProgramCommon::getMicrocodeFromCache(uint32 id, GLuint programHandle) - { - if (!GpuProgramManager::canGetCompiledShaderBuffer()) - return false; - - if (!GpuProgramManager::getSingleton().isMicrocodeAvailableInCache(id)) - return false; - - GpuProgramManager::Microcode cacheMicrocode = GpuProgramManager::getSingleton().getMicrocodeFromCache(id); - - // turns out we need this param when loading - GLenum binaryFormat = 0; - - cacheMicrocode->seek(0); - - // get size of binary - cacheMicrocode->read(&binaryFormat, sizeof(GLenum)); - - if(!Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_CAN_GET_COMPILED_SHADER_BUFFER)) - return false; - - GLint binaryLength = static_cast(cacheMicrocode->size() - sizeof(GLenum)); - - // load binary - OGRE_CHECK_GL_ERROR(glProgramBinaryOES(programHandle, - binaryFormat, - cacheMicrocode->getCurrentPtr(), - binaryLength)); - - GLint success = 0; - OGRE_CHECK_GL_ERROR(glGetProgramiv(programHandle, GL_LINK_STATUS, &success)); - - return success; - } - void GLSLESProgramCommon::_writeToCache(uint32 id, GLuint programHandle) - { - if(!GpuProgramManager::canGetCompiledShaderBuffer()) - return; - - if(!GpuProgramManager::getSingleton().getSaveMicrocodesToCache()) - return; - - // Add to the microcode to the cache - // Get buffer size - GLint binaryLength = 0; - OGRE_CHECK_GL_ERROR(glGetProgramiv(programHandle, GL_PROGRAM_BINARY_LENGTH_OES, &binaryLength)); - - // Create microcode - auto newMicrocode = GpuProgramManager::createMicrocode(static_cast(binaryLength + sizeof(GLenum))); - - // Get binary - OGRE_CHECK_GL_ERROR(glGetProgramBinaryOES(programHandle, binaryLength, NULL, (GLenum *)newMicrocode->getPtr(), - newMicrocode->getPtr() + sizeof(GLenum))); - - // Add to the microcode to the cache - GpuProgramManager::getSingleton().addMicrocodeToCache(id, newMicrocode); - } - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - void GLSLESProgramCommon::notifyOnContextLost() - { - mLinked = false; - mUniformRefsBuilt = false; - for(auto s : mShaders) - { - if(s) s->getUniformCache()->clearCache(); - } - } - - void GLSLESProgramCommon::notifyOnContextReset() - { - activate(); - } -#endif -} // namespace Ogre diff --git a/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESProgramManager.cpp b/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESProgramManager.cpp deleted file mode 100644 index 10c7127355c..00000000000 --- a/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESProgramManager.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLSLESProgramManager.h" -#include "OgreGLSLESProgram.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreGpuProgramManager.h" -#include "OgreHardwareBufferManager.h" -#include "OgreGLSLESProgram.h" - -#include "OgreGLSLESLinkProgram.h" -#include "OgreGLSLESProgramPipeline.h" - -#include "OgreRoot.h" - -namespace Ogre { - - //----------------------------------------------------------------------- - template<> GLSLESProgramManager* Singleton::msSingleton = 0; - - //----------------------------------------------------------------------- - GLSLESProgramManager* GLSLESProgramManager::getSingletonPtr(void) - { - return msSingleton; - } - - //----------------------------------------------------------------------- - GLSLESProgramManager& GLSLESProgramManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - - //----------------------------------------------------------------------- - GLSLESProgramManager::GLSLESProgramManager(void) - { - -#if !OGRE_NO_GLES2_GLSL_OPTIMISER -#if OGRE_NO_GLES3_SUPPORT == 0 - mGLSLOptimiserContext = glslopt_initialize(kGlslTargetOpenGLES30); -#else - mGLSLOptimiserContext = glslopt_initialize(kGlslTargetOpenGLES20); -#endif -#endif - } - - //----------------------------------------------------------------------- - GLSLESProgramManager::~GLSLESProgramManager(void) - { -#if !OGRE_NO_GLES2_GLSL_OPTIMISER - if(mGLSLOptimiserContext) - { - glslopt_cleanup(mGLSLOptimiserContext); - mGLSLOptimiserContext = NULL; - } -#endif - } - - //----------------------------------------------------------------------- - GLSLESProgramCommon* GLSLESProgramManager::getActiveProgram(void) - { - // If there is an active link program then return it - if (mActiveProgram) - return static_cast(mActiveProgram);; - - // No active link program so find one or make a new one - // Is there an active key? - uint32 activeKey = 0; - for(auto shader : mActiveShader) - { - if(!shader) continue; - activeKey = HashCombine(activeKey, shader->getShaderID()); - } - - // Only return a link program object if a vertex or fragment program exist - if (activeKey > 0) - { - // Find the key in the hash map - ProgramIterator programFound = mPrograms.find(activeKey); - // Program object not found for key so need to create it - if (programFound == mPrograms.end()) - { - if (Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability( - RSC_SEPARATE_SHADER_OBJECTS)) - { - mActiveProgram = new GLSLESProgramPipeline(mActiveShader); - } - else - { - mActiveProgram = new GLSLESLinkProgram(mActiveShader); - } - - mPrograms[activeKey] = mActiveProgram; - } - else - { - // Found a link program in map container so make it active - mActiveProgram = static_cast(programFound->second); - } - - } - // Make the program object active - if (mActiveProgram) mActiveProgram->activate(); - - return static_cast(mActiveProgram); - } - -#if !OGRE_NO_GLES2_GLSL_OPTIMISER - void GLSLESProgramManager::optimiseShaderSource(GLSLESGpuProgram* gpuProgram) - { - if(!gpuProgram->getGLSLProgram()->getIsOptimised()) - { - GpuProgramType gpuType = gpuProgram->getType(); - const glslopt_shader_type shaderType = (gpuType == GPT_VERTEX_PROGRAM) ? kGlslOptShaderVertex : kGlslOptShaderFragment; - String shaderSource = gpuProgram->getGLSLProgram()->getSource(); - glslopt_shader* shader = glslopt_optimize(mGLSLOptimiserContext, shaderType, shaderSource.c_str(), 0); - - StringStream os; - if(glslopt_get_status(shader)) - { - const String source = glslopt_get_output(shader); - gpuProgram->getGLSLProgram()->setOptimisedSource(source); - gpuProgram->getGLSLProgram()->setIsOptimised(true); - } - else - { - LogManager::getSingleton().logMessage("Error from GLSL Optimiser, disabling optimisation for program: " + gpuProgram->getName()); - gpuProgram->getGLSLProgram()->setParameter("use_optimiser", "false"); - //LogManager::getSingleton().logMessage(String(glslopt_get_log(shader))); - //LogManager::getSingleton().logMessage("Original Shader"); - //LogManager::getSingleton().logMessage(gpuProgram->getGLSLProgram()->getSource()); - //LogManager::getSingleton().logMessage("Optimized Shader"); - //LogManager::getSingleton().logMessage(os.str()); - } - glslopt_shader_delete(shader); - } - } -#endif - - //--------------------------------------------------------------------- - void GLSLESProgramManager::extractUniforms(GLuint programObject, - const GpuConstantDefinitionMap* vertexConstantDefs, - const GpuConstantDefinitionMap* fragmentConstantDefs, - GLUniformReferenceList& list) - { - // Scan through the active uniforms and add them to the reference list - GLint uniformCount = 0; - #define uniformLength 200 - char uniformName[uniformLength] = {0}; - - GLUniformReference newGLUniformReference; - - // Get the number of active uniforms - OGRE_CHECK_GL_ERROR(glGetProgramiv(programObject, GL_ACTIVE_UNIFORMS, &uniformCount)); - - const GpuConstantDefinitionMap* params[6] = { vertexConstantDefs, fragmentConstantDefs }; - - // Loop over each of the active uniforms, and add them to the reference container - // only do this for user defined uniforms, ignore built in gl state uniforms - for (GLuint index = 0; index < (GLuint)uniformCount; index++) - { - GLint arraySize = 0; - GLenum glType = GL_NONE; - OGRE_CHECK_GL_ERROR(glGetActiveUniform(programObject, index, uniformLength, NULL, - &arraySize, &glType, uniformName)); - - // Don't add built in uniforms - newGLUniformReference.mLocation = glGetUniformLocation(programObject, uniformName); - - if(!validateParam(uniformName, arraySize, params, newGLUniformReference)) - continue; - list.push_back(newGLUniformReference); - } - -#if 0 // needs updating to GL3Plus code - // Now deal with uniform blocks - - GLint blockCount = 0; - - OGRE_CHECK_GL_ERROR(glGetProgramiv(programObject, GL_ACTIVE_UNIFORM_BLOCKS, &blockCount)); - - for (int index = 0; index < blockCount; index++) - { - OGRE_CHECK_GL_ERROR(glGetActiveUniformBlockName(programObject, index, uniformLength, NULL, uniformName)); - - GpuSharedParametersPtr blockSharedParams = GpuProgramManager::getSingleton().getSharedParameters(uniformName); - - GLint blockSize, blockBinding; - OGRE_CHECK_GL_ERROR(glGetActiveUniformBlockiv(programObject, index, GL_UNIFORM_BLOCK_DATA_SIZE, &blockSize)); - OGRE_CHECK_GL_ERROR(glGetActiveUniformBlockiv(programObject, index, GL_UNIFORM_BLOCK_BINDING, &blockBinding)); - HardwareUniformBufferSharedPtr newUniformBuffer = HardwareBufferManager::getSingleton().createUniformBuffer(blockSize, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE, false, uniformName); - - GLES2HardwareUniformBuffer* hwGlBuffer = static_cast(newUniformBuffer.get()); - hwGlBuffer->setGLBufferBinding(blockBinding); - sharedList.push_back(newUniformBuffer); - } -#endif - } -} diff --git a/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESProgramPipeline.cpp b/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESProgramPipeline.cpp deleted file mode 100644 index 2dc754aa214..00000000000 --- a/RenderSystems/GLES2/src/GLSLES/src/OgreGLSLESProgramPipeline.cpp +++ /dev/null @@ -1,294 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ - -#include "OgreGLSLESProgramPipeline.h" -#include "OgreStringConverter.h" -#include "OgreGLSLESProgram.h" -#include "OgreGLSLESProgramManager.h" -#include "OgreGpuProgramManager.h" -#include "OgreGLES2RenderSystem.h" -#include "OgreGLUniformCache.h" -#include "OgreHardwareBufferManager.h" -#include "OgreGLUtil.h" -#include "OgreRoot.h" -#include "OgreGLNativeSupport.h" - -namespace Ogre -{ - GLSLESProgramPipeline::GLSLESProgramPipeline(const GLShaderList& shaders) : - GLSLESProgramCommon(shaders) { } - - GLSLESProgramPipeline::~GLSLESProgramPipeline() - { - OGRE_CHECK_GL_ERROR(glDeleteProgramPipelinesEXT(1, &mGLProgramHandle)); - } - - void GLSLESProgramPipeline::compileAndLink() - { - OGRE_CHECK_GL_ERROR(glGenProgramPipelinesEXT(1, &mGLProgramHandle)); - //OGRE_CHECK_GL_ERROR(glBindProgramPipelineEXT(mGLProgramHandle)); - - mLinked = true; - // Compile and attach Vertex Program - if(mShaders[GPT_VERTEX_PROGRAM]) - { - mLinked = mLinked && mShaders[GPT_VERTEX_PROGRAM]->linkSeparable(); - } - - // Compile and attach Fragment Program - if(mShaders[GPT_FRAGMENT_PROGRAM]) - { - mLinked = mLinked && mShaders[GPT_FRAGMENT_PROGRAM]->linkSeparable(); - } - - if(mLinked) - { - if(mShaders[GPT_VERTEX_PROGRAM]) - { - OGRE_CHECK_GL_ERROR(glUseProgramStagesEXT(mGLProgramHandle, GL_VERTEX_SHADER_BIT_EXT, mShaders[GPT_VERTEX_PROGRAM]->getGLProgramHandle())); - } - if(mShaders[GPT_FRAGMENT_PROGRAM]) - { - OGRE_CHECK_GL_ERROR(glUseProgramStagesEXT(mGLProgramHandle, GL_FRAGMENT_SHADER_BIT_EXT, mShaders[GPT_FRAGMENT_PROGRAM]->getGLProgramHandle())); - } - - // Validate pipeline - GLSLES::logObjectInfo( getCombinedName() + String("GLSL program pipeline result : "), mGLProgramHandle ); - if(mShaders[GPT_VERTEX_PROGRAM] && mShaders[GPT_FRAGMENT_PROGRAM] && Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_DEBUG)) - { - glLabelObjectEXT(GL_PROGRAM_PIPELINE_OBJECT_EXT, mGLProgramHandle, 0, - (mShaders[GPT_VERTEX_PROGRAM]->getName() + "/" + mShaders[GPT_FRAGMENT_PROGRAM]->getName()).c_str()); - } - } - } - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - void GLSLESProgramPipeline::notifyOnContextLost() - { - OGRE_CHECK_GL_ERROR(glDeleteProgramPipelinesEXT(1, &mGLProgramHandle)); - mGLProgramHandle = 0; - GLSLESProgramCommon::notifyOnContextLost(); - } -#endif - - //----------------------------------------------------------------------- - void GLSLESProgramPipeline::activate(void) - { - if (!mLinked) - { - glGetError(); // Clean up the error. Otherwise will flood log. - -#if !OGRE_NO_GLES2_GLSL_OPTIMISER - // Check CmdParams for each shader type to see if we should optimise - if(mVertexProgram) - { - String paramStr = mVertexProgram->getGLSLProgram()->getParameter("use_optimiser"); - if((paramStr == "true") || paramStr.empty()) - { - GLSLESProgramPipelineManager::getSingleton().optimiseShaderSource(mVertexProgram); - } - } - - if(mFragmentProgram) - { - String paramStr = mFragmentProgram->getGLSLProgram()->getParameter("use_optimiser"); - if((paramStr == "true") || paramStr.empty()) - { - GLSLESProgramPipelineManager::getSingleton().optimiseShaderSource(mFragmentProgram); - } - } -#endif - compileAndLink(); - - buildGLUniformReferences(); - } - - if (mLinked) - { - OGRE_CHECK_GL_ERROR(glBindProgramPipelineEXT(mGLProgramHandle)); - } - } - - //----------------------------------------------------------------------- - void GLSLESProgramPipeline::buildGLUniformReferences(void) - { - if (!mUniformRefsBuilt) - { - const GpuConstantDefinitionMap* vertParams = 0; - const GpuConstantDefinitionMap* fragParams = 0; - if (mShaders[GPT_VERTEX_PROGRAM]) - { - vertParams = &(mShaders[GPT_VERTEX_PROGRAM]->getConstantDefinitions().map); - GLSLESProgramManager::extractUniforms(mShaders[GPT_VERTEX_PROGRAM]->getGLProgramHandle(), - vertParams, NULL, mGLUniformReferences); - } - if (mShaders[GPT_FRAGMENT_PROGRAM]) - { - fragParams = &(mShaders[GPT_FRAGMENT_PROGRAM]->getConstantDefinitions().map); - GLSLESProgramManager::extractUniforms(mShaders[GPT_FRAGMENT_PROGRAM]->getGLProgramHandle(), NULL, - fragParams, mGLUniformReferences); - } - - mUniformRefsBuilt = true; - } - } - - //----------------------------------------------------------------------- - void GLSLESProgramPipeline::updateUniforms(GpuProgramParametersSharedPtr params, - uint16 mask, GpuProgramType fromProgType) - { - OgreAssert(mShaders[fromProgType], "invalid program type"); - GLuint progID = mShaders[fromProgType]->getGLProgramHandle(); - GLUniformCache* uniformCache = mShaders[fromProgType]->getUniformCache(); - - // Iterate through uniform reference list and update uniform values - GLUniformReferenceIterator currentUniform = mGLUniformReferences.begin(); - GLUniformReferenceIterator endUniform = mGLUniformReferences.end(); - for (;currentUniform != endUniform; ++currentUniform) - { - // Only pull values from buffer it's supposed to be in (vertex or fragment) - // This method will be called twice, once for vertex program params, - // and once for fragment program params. - if (fromProgType == currentUniform->mSourceProgType) - { - const GpuConstantDefinition* def = currentUniform->mConstantDef; - if (def->variability & mask) - { - GLsizei glArraySize = (GLsizei)def->arraySize; - void* val = def->isSampler() ? (void*)params->getRegPointer(def->physicalIndex) - : (void*)params->getFloatPointer(def->physicalIndex); - - bool shouldUpdate = uniformCache->updateUniform(currentUniform->mLocation, val, - def->elementSize * def->arraySize * 4); - if(!shouldUpdate) - continue; - - // Get the index in the parameter real list - switch (def->constType) - { - case GCT_FLOAT1: - OGRE_CHECK_GL_ERROR(glProgramUniform1fvEXT(progID, currentUniform->mLocation, glArraySize, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_FLOAT2: - OGRE_CHECK_GL_ERROR(glProgramUniform2fvEXT(progID, currentUniform->mLocation, glArraySize, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_FLOAT3: - OGRE_CHECK_GL_ERROR(glProgramUniform3fvEXT(progID, currentUniform->mLocation, glArraySize, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_FLOAT4: - OGRE_CHECK_GL_ERROR(glProgramUniform4fvEXT(progID, currentUniform->mLocation, glArraySize, - params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_2X2: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix2fvEXT(progID, currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_3X3: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix3fvEXT(progID, currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_4X4: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix4fvEXT(progID, currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_SAMPLER1D: - case GCT_SAMPLER1DSHADOW: - case GCT_SAMPLER2D: - case GCT_SAMPLER2DSHADOW: - case GCT_SAMPLER3D: - case GCT_SAMPLERCUBE: - case GCT_SAMPLER2DARRAY: - // Samplers handled like 1-element ints - case GCT_INT1: - OGRE_CHECK_GL_ERROR(glProgramUniform1ivEXT(progID, currentUniform->mLocation, glArraySize, - (int*)val)); - break; - case GCT_INT2: - OGRE_CHECK_GL_ERROR(glProgramUniform2ivEXT(progID, currentUniform->mLocation, glArraySize, - params->getIntPointer(def->physicalIndex))); - break; - case GCT_INT3: - OGRE_CHECK_GL_ERROR(glProgramUniform3ivEXT(progID, currentUniform->mLocation, glArraySize, - params->getIntPointer(def->physicalIndex))); - break; - case GCT_INT4: - OGRE_CHECK_GL_ERROR(glProgramUniform4ivEXT(progID, currentUniform->mLocation, glArraySize, - params->getIntPointer(def->physicalIndex))); - break; - case GCT_MATRIX_2X3: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix2x3fvEXT(progID, currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_2X4: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix2x4fvEXT(progID, currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_3X2: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix3x2fvEXT(progID, currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_3X4: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix3x4fvEXT(progID, currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_4X2: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix4x2fvEXT(progID, currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_MATRIX_4X3: - OGRE_CHECK_GL_ERROR(glProgramUniformMatrix4x3fvEXT(progID, currentUniform->mLocation, glArraySize, - GL_FALSE, params->getFloatPointer(def->physicalIndex))); - break; - case GCT_UNKNOWN: - case GCT_SPECIALIZATION: - case GCT_DOUBLE1: - case GCT_DOUBLE2: - case GCT_DOUBLE3: - case GCT_DOUBLE4: - case GCT_MATRIX_DOUBLE_2X2: - case GCT_MATRIX_DOUBLE_2X3: - case GCT_MATRIX_DOUBLE_2X4: - case GCT_MATRIX_DOUBLE_3X2: - case GCT_MATRIX_DOUBLE_3X3: - case GCT_MATRIX_DOUBLE_3X4: - case GCT_MATRIX_DOUBLE_4X2: - case GCT_MATRIX_DOUBLE_4X3: - case GCT_MATRIX_DOUBLE_4X4: - default: - break; - - } // End switch - } // Variability & mask - } // fromProgType == currentUniform->mSourceProgType - - } // End for - } -} diff --git a/RenderSystems/GLES2/src/OgreGLES2EngineDll.cpp b/RenderSystems/GLES2/src/OgreGLES2EngineDll.cpp deleted file mode 100644 index 4d1cd9bd0e3..00000000000 --- a/RenderSystems/GLES2/src/OgreGLES2EngineDll.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreRoot.h" -#include "OgreGLES2Prerequisites.h" -#include "OgreGLES2Plugin.h" - -namespace Ogre { - static GLES2Plugin* plugin; - extern "C" void _OgreGLES2Export dllStartPlugin(void); - extern "C" void _OgreGLES2Export dllStopPlugin(void); - - extern "C" void _OgreGLES2Export dllStartPlugin(void) - { - plugin = OGRE_NEW GLES2Plugin(); - Root::getSingleton().installPlugin(plugin); - } - - extern "C" void _OgreGLES2Export dllStopPlugin(void) - { - Root::getSingleton().uninstallPlugin(plugin); - OGRE_DELETE plugin; - } -} diff --git a/RenderSystems/GLES2/src/OgreGLES2FBOMultiRenderTarget.cpp b/RenderSystems/GLES2/src/OgreGLES2FBOMultiRenderTarget.cpp deleted file mode 100644 index 6525046bc0e..00000000000 --- a/RenderSystems/GLES2/src/OgreGLES2FBOMultiRenderTarget.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLES2FBOMultiRenderTarget.h" -#include "OgreLogManager.h" - -namespace Ogre { - - GLES2FBOMultiRenderTarget::GLES2FBOMultiRenderTarget(GLES2FBOManager *manager, const String &name): - MultiRenderTarget(name), - fbo(manager, 0 /* TODO: multisampling on MRTs? */) - { - } - GLES2FBOMultiRenderTarget::~GLES2FBOMultiRenderTarget() - { - } - - void GLES2FBOMultiRenderTarget::bindSurfaceImpl(size_t attachment, RenderTexture *target) - { - /// Check if the render target is in the rendertarget->FBO map - auto *fbobj = dynamic_cast(target)->getFBO(); - assert(fbobj); - fbo.bindSurface(attachment, fbobj->getSurface(0)); - - // Set width and height - mWidth = fbo.getWidth(); - mHeight = fbo.getHeight(); - } - - void GLES2FBOMultiRenderTarget::unbindSurfaceImpl(size_t attachment) - { - fbo.unbindSurface(attachment); - - // Set width and height - mWidth = fbo.getWidth(); - mHeight = fbo.getHeight(); - } - - void GLES2FBOMultiRenderTarget::getCustomAttribute( const String& name, void *pData ) - { - if(name == GLRenderTexture::CustomAttributeString_FBO) - { - *static_cast(pData) = &fbo; - } - else if(name == GLRenderTexture::CustomAttributeString_GLCONTEXT) - { - *static_cast(pData) = fbo.getContext(); - } - } - //----------------------------------------------------------------------------- - bool GLES2FBOMultiRenderTarget::attachDepthBuffer( DepthBuffer *depthBuffer ) - { - bool result; - if( (result = MultiRenderTarget::attachDepthBuffer( depthBuffer )) ) - fbo.attachDepthBuffer( depthBuffer ); - - return result; - } - //----------------------------------------------------------------------------- - void GLES2FBOMultiRenderTarget::detachDepthBuffer() - { - fbo.detachDepthBuffer(); - MultiRenderTarget::detachDepthBuffer(); - } - //----------------------------------------------------------------------------- - void GLES2FBOMultiRenderTarget::_detachDepthBuffer() - { - fbo.detachDepthBuffer(); - MultiRenderTarget::_detachDepthBuffer(); - } -} diff --git a/RenderSystems/GLES2/src/OgreGLES2FBORenderTexture.cpp b/RenderSystems/GLES2/src/OgreGLES2FBORenderTexture.cpp deleted file mode 100644 index 8d8069d4d3b..00000000000 --- a/RenderSystems/GLES2/src/OgreGLES2FBORenderTexture.cpp +++ /dev/null @@ -1,550 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLES2FBORenderTexture.h" -#include "OgreGLES2PixelFormat.h" -#include "OgreLogManager.h" -#include "OgreGLES2HardwarePixelBuffer.h" -#include "OgreGLES2FBOMultiRenderTarget.h" -#include "OgreRoot.h" -#include "OgreGLES2RenderSystem.h" -#include "OgreGLUtil.h" -#include "OgreGLNativeSupport.h" - -namespace Ogre { - -//----------------------------------------------------------------------------- - GLES2FBORenderTexture::GLES2FBORenderTexture(GLES2FBOManager *manager, const String &name, - const GLSurfaceDesc &target, bool writeGamma, uint fsaa): - GLRenderTexture(name, target, writeGamma, std::min(manager->getMaxFSAASamples(), (int)fsaa)), - mFB(manager, mFSAA) - { - // Bind target to surface 0 and initialise - mFB.bindSurface(0, target); - - // Get attributes - mWidth = mFB.getWidth(); - mHeight = mFB.getHeight(); - } - - void GLES2FBORenderTexture::getCustomAttribute(const String& name, void* pData) - { - if(name == GLRenderTexture::CustomAttributeString_FBO) - { - *static_cast(pData) = &mFB; - } - else if(name == GLRenderTexture::CustomAttributeString_GLCONTEXT) - { - *static_cast(pData) = mFB.getContext(); - } - } - - void GLES2FBORenderTexture::swapBuffers() - { - mFB.swapBuffers(); - } - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - void GLES2FBORenderTexture::notifyOnContextLost() - { - mFB.notifyOnContextLost(); - } - - void GLES2FBORenderTexture::notifyOnContextReset() - { - GLSurfaceDesc target; - target.buffer = static_cast(mBuffer); - target.zoffset = mZOffset; - - mFB.notifyOnContextReset(target); - - static_cast(Ogre::Root::getSingletonPtr()->getRenderSystem())->_createDepthBufferFor(this); - } -#endif - - //----------------------------------------------------------------------------- - bool GLES2FBORenderTexture::attachDepthBuffer( DepthBuffer *depthBuffer ) - { - bool result; - if( (result = GLRenderTexture::attachDepthBuffer( depthBuffer )) ) - mFB.attachDepthBuffer( depthBuffer ); - - return result; - } - //----------------------------------------------------------------------------- - void GLES2FBORenderTexture::detachDepthBuffer() - { - mFB.detachDepthBuffer(); - GLRenderTexture::detachDepthBuffer(); - } - //----------------------------------------------------------------------------- - void GLES2FBORenderTexture::_detachDepthBuffer() - { - mFB.detachDepthBuffer(); - GLRenderTexture::_detachDepthBuffer(); - } - - // Size of probe texture - #define PROBE_SIZE 16 - - // Stencil and depth formats to be tried - static const GLenum stencilFormats[] = - { - GL_NONE, // No stencil - GL_STENCIL_INDEX1_OES, - GL_STENCIL_INDEX4_OES, - GL_STENCIL_INDEX8 - }; - static const uchar stencilBits[] = - { - 0, - 1, - 4, - 8 - }; - #define STENCILFORMAT_COUNT (sizeof(stencilFormats)/sizeof(GLenum)) - - static const GLenum depthFormats[] = - { - GL_NONE, - GL_DEPTH_COMPONENT16 - , GL_DEPTH_COMPONENT24_OES // Prefer 24 bit depth - , GL_DEPTH_COMPONENT32_OES - , GL_DEPTH24_STENCIL8_OES // Packed depth / stencil - , GL_DEPTH32F_STENCIL8 - }; - static const uchar depthBits[] = - { - 0 - ,16 - ,24 - ,32 - ,24 - ,32 - }; - #define DEPTHFORMAT_COUNT (sizeof(depthFormats)/sizeof(GLenum)) - - GLES2FBOManager::GLES2FBOManager() : mMaxFSAASamples(0) - { - detectFBOFormats(); - - OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mTempFBO)); - - // Check multisampling if supported - if(getGLES2RenderSystem()->hasMinGLVersion(3, 0)) - { - // Check samples supported - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_SAMPLES_APPLE, &mMaxFSAASamples)); - } - } - - GLES2FBOManager::~GLES2FBOManager() - { - if(!mRenderBufferMap.empty()) - { - LogManager::getSingleton().logWarning("GLES2FBOManager destructor called, but not all renderbuffers were released."); - } - - OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mTempFBO)); - } - - void GLES2FBOManager::_reload() - { - OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mTempFBO)); - - detectFBOFormats(); - - OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mTempFBO)); - } - - void GLES2FBOManager::_createTempFramebuffer(GLuint internalFormat, GLuint fmt, GLenum type, GLuint &fb, GLuint &tid) - { - // Create and attach framebuffer - glGenFramebuffers(1, &fb); - glBindFramebuffer(GL_FRAMEBUFFER, fb); - if (internalFormat != GL_NONE) - { - if (tid) - glDeleteTextures(1, &tid); - - // Create and attach texture - glGenTextures(1, &tid); - glBindTexture(GL_TEXTURE_2D, tid); - - // Set some default parameters - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, PROBE_SIZE, PROBE_SIZE, 0, fmt, type, 0); - glFramebufferTexture2D(GL_FRAMEBUFFER, - fmt == GL_DEPTH_COMPONENT ? GL_DEPTH_ATTACHMENT : GL_COLOR_ATTACHMENT0, - GL_TEXTURE_2D, tid, 0); - } - } - - /** Try a certain FBO format, and return the status. Also sets mDepthRB and mStencilRB. - @returns true if this combo is supported - false if this combo is not supported - */ - GLuint GLES2FBOManager::_tryFormat(GLenum depthFormat, GLenum stencilFormat) - { - GLuint status, depthRB = 0, stencilRB = 0; - - if(depthFormat != GL_NONE) - { - // Generate depth renderbuffer - glGenRenderbuffers(1, &depthRB); - - // Bind it to FBO - glBindRenderbuffer(GL_RENDERBUFFER, depthRB); - - // Allocate storage for depth buffer - glRenderbufferStorage(GL_RENDERBUFFER, depthFormat, - PROBE_SIZE, PROBE_SIZE); - - // Attach depth - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRB); - } - - // Stencil buffers aren't available on iOS - if(stencilFormat != GL_NONE) - { - // Generate stencil renderbuffer - glGenRenderbuffers(1, &stencilRB); - - // Bind it to FBO - glBindRenderbuffer(GL_RENDERBUFFER, stencilRB); - - // Allocate storage for stencil buffer - glRenderbufferStorage(GL_RENDERBUFFER, stencilFormat, PROBE_SIZE, PROBE_SIZE); - - // Attach stencil - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, - GL_RENDERBUFFER, stencilRB); - } - - status = glCheckFramebufferStatus(GL_FRAMEBUFFER); - - // If status is negative, clean up - // Detach and destroy - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0); - - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0); - - if (depthRB) - glDeleteRenderbuffers(1, &depthRB); - - if (stencilRB) - glDeleteRenderbuffers(1, &stencilRB); - - return status == GL_FRAMEBUFFER_COMPLETE; - } - - /** Try a certain packed depth/stencil format, and return the status. - @returns true if this combo is supported - false if this combo is not supported - */ - bool GLES2FBOManager::_tryPackedFormat(GLenum packedFormat) - { - GLuint packedRB; - - // Generate renderbuffer - glGenRenderbuffers(1, &packedRB); - - // Bind it to FBO - glBindRenderbuffer(GL_RENDERBUFFER, packedRB); - - // Allocate storage for buffer - glRenderbufferStorage(GL_RENDERBUFFER, packedFormat, PROBE_SIZE, PROBE_SIZE); - - // Attach depth - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, - GL_RENDERBUFFER, packedRB); - - // Attach stencil - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, - GL_RENDERBUFFER, packedRB); - - GLuint status = glCheckFramebufferStatus(GL_FRAMEBUFFER); - - // Detach and destroy - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0); - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0); - glDeleteRenderbuffers(1, &packedRB); - - return status == GL_FRAMEBUFFER_COMPLETE; - } - - /** Detect which internal formats are allowed as RTT - Also detect what combinations of stencil and depth are allowed with this internal - format. - */ - void GLES2FBOManager::detectFBOFormats() - { - GLES2RenderSystem* rs = getGLES2RenderSystem(); - bool hasGLES3 = rs->hasMinGLVersion(3, 0); -#if OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - memset(mProps, 0, sizeof(mProps)); - - // TODO: Fix that probing all formats slows down startup not just on the web also on Android / iOS - mProps[PF_A8B8G8R8].valid = true; - FormatProperties::Mode mode = {1, 0}; - mProps[PF_A8B8G8R8].modes.push_back(mode); - - if(hasGLES3) - { - mProps[PF_DEPTH16].valid = true; - mProps[PF_DEPTH16].modes.push_back(mode); - } - LogManager::getSingleton().logMessage("[GLES2] : detectFBOFormats is disabled on this platform (due performance reasons)"); -#else - // Try all formats, and report which ones work as target - GLuint fb = 0, tid = 0; - - const size_t depthCount = hasGLES3 ? DEPTHFORMAT_COUNT : DEPTHFORMAT_COUNT - 1; // 32_8 is not available on GLES2 - const uchar stencilStep = hasGLES3 ? 3 : 1; // 1 and 4 bit not available on GLES3 - - for(size_t x = 0; x < PF_COUNT; ++x) - { - mProps[x].valid = false; - - // Fetch GL format token - GLint internalFormat = GLES2PixelUtil::getGLInternalFormat((PixelFormat)x); - GLenum fmt = GLES2PixelUtil::getGLOriginFormat((PixelFormat)x); - GLenum type = GLES2PixelUtil::getGLOriginDataType((PixelFormat)x); - - // Note: letting PF_UNKNOWN pass here is for pure depth/ stencil formats - // however there are reports that this crashes some unspecified android devices - if((internalFormat == GL_NONE || fmt == GL_NONE || type == GL_NONE) && (x != 0)) - continue; - - // not color-renderable in GLES - if(fmt == GL_BGRA_EXT) - continue; - - // No test for compressed formats - if(PixelUtil::isCompressed((PixelFormat)x)) - continue; - - // Create and attach framebuffer - _createTempFramebuffer(internalFormat, fmt, type, fb, tid); - - // Ignore status in case of fmt==GL_NONE, because no implementation will accept - // a buffer without *any* attachment. Buffers with only stencil and depth attachment - // might still be supported, so we must continue probing. - if(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE) - { - mProps[x].valid = true; - StringStream str; - str << "FBO " << PixelUtil::getFormatName((PixelFormat)x) - << " depth/stencil support: "; - - // For each depth/stencil formats - for (uchar depth = 0; depth < depthCount; ++depth) - { - if (depthFormats[depth] != GL_DEPTH24_STENCIL8 && depthFormats[depth] != GL_DEPTH32F_STENCIL8) - { - // General depth/stencil combination - - for (uchar stencil = 0; stencil < STENCILFORMAT_COUNT; stencil += stencilStep) - { -// StringStream l; -// l << "Trying " << PixelUtil::getFormatName((PixelFormat)x) -// << " D" << depthBits[depth] -// << "S" << stencilBits[stencil]; -// LogManager::getSingleton().logMessage(l.str()); - - if (_tryFormat(depthFormats[depth], stencilFormats[stencil])) - { - // Add mode to allowed modes - str << StringUtil::format("D%dS%d ", depthBits[depth], stencilBits[stencil]); - FormatProperties::Mode mode; - mode.depth = depth; - mode.stencil = stencil; - mProps[x].modes.push_back(mode); - } - else - { - // There is a small edge case that FBO is trashed during the test - // on some drivers resulting in undefined behavior - glBindFramebuffer(GL_FRAMEBUFFER, 0); - glDeleteFramebuffers(1, &fb); - - _createTempFramebuffer(internalFormat, fmt, type, fb, tid); - } - } - } - else if(hasGLES3 || rs->checkExtension("GL_OES_packed_depth_stencil") ) - { - // Packed depth/stencil format - if (_tryPackedFormat(depthFormats[depth])) - { - // Add mode to allowed modes - str << "Packed-D" << int(depthBits[depth]) << "S8 "; - FormatProperties::Mode mode; - mode.depth = depth; - mode.stencil = 0; // unuse - mProps[x].modes.push_back(mode); - } - else - { - // There is a small edge case that FBO is trashed during the test - // on some drivers resulting in undefined behavior - glBindFramebuffer(GL_FRAMEBUFFER, 0); - glDeleteFramebuffers(1, &fb); - - _createTempFramebuffer(internalFormat, fmt, type, fb, tid); - } - } - } - LogManager::getSingleton().logMessage(str.str()); - } - - // Delete texture and framebuffer - glBindFramebuffer(GL_FRAMEBUFFER, 0); - glDeleteFramebuffers(1, &fb); - - if (internalFormat != GL_NONE) - { - glDeleteTextures(1, &tid); - tid = 0; - } - } - - // Clear any errors - glGetError(); -#endif - String fmtstring; - for(size_t x = 0; x < PF_COUNT; ++x) - { - if(mProps[x].valid) - fmtstring += PixelUtil::getFormatName((PixelFormat)x)+" "; - } - LogManager::getSingleton().logMessage("[GLES2] : Valid FBO targets " + fmtstring); - - } - - void GLES2FBOManager::getBestDepthStencil(PixelFormat internalFormat, GLenum *depthFormat, GLenum *stencilFormat) - { - const FormatProperties &props = mProps[internalFormat]; - if (props.modes.size() == 0 ) { - *depthFormat = 0; - *stencilFormat = 0; - return; - } - // Decide what stencil and depth formats to use - // [best supported for internal format] - size_t bestmode = 0; - int bestscore = -1; - bool requestDepthOnly = PixelUtil::isDepth(internalFormat); - - for(size_t mode = 0; mode < props.modes.size(); mode++) - { - int desirability = 0; - // Find most desirable mode - // desirability == 0 if no depth, no stencil - // desirability == 1000...2000 if no depth, stencil - // desirability == 2000...3000 if depth, no stencil - // desirability == 3000+ if depth and stencil - // beyond this, the total number of bits (stencil+depth) is maximised - if(props.modes[mode].stencil && !requestDepthOnly) - desirability += 1000; - if(props.modes[mode].depth) - desirability += 2000; - if(depthBits[props.modes[mode].depth]==24) // Prefer 24 bit for now - desirability += 500; - if(depthFormats[props.modes[mode].depth] == GL_DEPTH24_STENCIL8_OES) // Prefer 24/8 packed - desirability += 5000; - if(depthFormats[props.modes[mode].depth] == GL_DEPTH32F_STENCIL8) // Prefer 32F/8 packed - desirability += 5000; - desirability += stencilBits[props.modes[mode].stencil] + depthBits[props.modes[mode].depth]; - - if(desirability > bestscore) - { - bestscore = desirability; - bestmode = mode; - } - } - *depthFormat = depthFormats[props.modes[bestmode].depth]; - *stencilFormat = requestDepthOnly ? 0 : stencilFormats[props.modes[bestmode].stencil]; - } - - GLES2FBORenderTexture *GLES2FBOManager::createRenderTexture(const String &name, - const GLSurfaceDesc &target, bool writeGamma, uint fsaa) - { - GLES2FBORenderTexture *retval = new GLES2FBORenderTexture(this, name, target, writeGamma, fsaa); - return retval; - } - - void GLES2FBOManager::bind(RenderTarget *target) - { - if(auto fbo = dynamic_cast(target)->getFBO()) - fbo->bind(true); - else - { - // Non-multisampled screen buffer is FBO #1 on iOS, multisampled is yet another, - // so give the target ability to influence decision which FBO to use - GLuint mainfbo = 0; -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - target->getCustomAttribute("GLFBO", &mainfbo); -#endif - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mainfbo)); - } - } - - GLSurfaceDesc GLES2FBOManager::requestRenderBuffer(GLenum format, uint32 width, uint32 height, uint fsaa) - { - GLSurfaceDesc retval; - retval.buffer = 0; // Return 0 buffer if GL_NONE is requested - if(format != GL_NONE) - { - RBFormat key(format, width, height, fsaa); - RenderBufferMap::iterator it = mRenderBufferMap.find(key); - if(it != mRenderBufferMap.end()) - { - retval.buffer = it->second.buffer; - retval.zoffset = 0; - retval.numSamples = fsaa; - // Increase refcount - ++it->second.refcount; - } - else - { - // New one - GLES2RenderBuffer *rb = OGRE_NEW GLES2RenderBuffer(format, width, height, fsaa); - mRenderBufferMap[key] = RBRef(rb); - retval.buffer = rb; - retval.zoffset = 0; - retval.numSamples = fsaa; - } - } -// std::cerr << "Requested renderbuffer with format " << std::hex << format << std::dec << " of " << width << "x" << height << " :" << retval.buffer << std::endl; - return retval; - } -} diff --git a/RenderSystems/GLES2/src/OgreGLES2FrameBufferObject.cpp b/RenderSystems/GLES2/src/OgreGLES2FrameBufferObject.cpp deleted file mode 100644 index a923b091259..00000000000 --- a/RenderSystems/GLES2/src/OgreGLES2FrameBufferObject.cpp +++ /dev/null @@ -1,343 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLES2FrameBufferObject.h" -#include "OgreGLES2HardwarePixelBuffer.h" -#include "OgreGLES2FBORenderTexture.h" -#include "OgreGLDepthBufferCommon.h" -#include "OgreGLUtil.h" -#include "OgreRoot.h" -#include "OgreGLES2RenderSystem.h" -#include "OgreGLNativeSupport.h" - -namespace Ogre { - -//----------------------------------------------------------------------------- - GLES2FrameBufferObject::GLES2FrameBufferObject(GLES2FBOManager *manager, uint fsaa): - GLFrameBufferObjectCommon(fsaa), mManager(manager) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - GLint oldfb = 0; - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldfb)); -#endif - GLES2RenderSystem* rs = getGLES2RenderSystem(); - mContext = rs->_getCurrentContext(); - - // Generate framebuffer object - OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mFB)); - - mNumSamples = std::min(mNumSamples, manager->getMaxFSAASamples()); - - // Will we need a second FBO to do multisampling? - if (mNumSamples) - { - OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mMultisampleFB)); - } - else - { - mMultisampleFB = 0; - } - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, oldfb)); -#endif - } - - GLES2FrameBufferObject::~GLES2FrameBufferObject() - { - mManager->releaseRenderBuffer(mDepth); - mManager->releaseRenderBuffer(mStencil); - mManager->releaseRenderBuffer(mMultisampleColourBuffer); - // Delete framebuffer object - if(mContext && mFB) - { - GLRenderSystemCommon* rs = static_cast(Root::getSingleton().getRenderSystem()); - rs->_destroyFbo(mContext, mFB); - - if (mMultisampleFB) - rs->_destroyFbo(mContext, mMultisampleFB); - } - } - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - void GLES2FrameBufferObject::notifyOnContextLost() - { - mManager->releaseRenderBuffer(mDepth); - mManager->releaseRenderBuffer(mStencil); - mManager->releaseRenderBuffer(mMultisampleColourBuffer); - - OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mFB)); - - if (mMultisampleFB) - OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mMultisampleFB)); - } - - void GLES2FrameBufferObject::notifyOnContextReset(const GLSurfaceDesc &target) - { - // Generate framebuffer object - OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mFB)); - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB)); - - // Bind target to surface 0 and initialise - bindSurface(0, target); - } -#endif - - void GLES2FrameBufferObject::initialise() - { - GLES2RenderSystem* rs = getGLES2RenderSystem(); - assert(mContext == rs->_getCurrentContext()); - - // Release depth and stencil, if they were bound - mManager->releaseRenderBuffer(mDepth); - mManager->releaseRenderBuffer(mStencil); - mManager->releaseRenderBuffer(mMultisampleColourBuffer); - // First buffer must be bound - if(!mColour[0].buffer) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Attachment 0 must have surface attached", - "GLES2FrameBufferObject::initialise"); - } - - // If we're doing multisampling, then we need another FBO which contains a - // renderbuffer which is set up to multisample, and we'll blit it to the final - // FBO afterwards to perform the multisample resolve. In that case, the - // mMultisampleFB is bound during rendering and is the one with a depth/stencil - - // Store basic stats - uint32 width = mColour[0].buffer->getWidth(); - uint32 height = mColour[0].buffer->getHeight(); - GLuint format = mColour[0].buffer->getGLFormat(); - ushort maxSupportedMRTs = rs->getCapabilities()->getNumMultiRenderTargets(); - - // Bind simple buffer to add colour attachments - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB)); - - // Bind all attachment points to frame buffer - for(unsigned int x = 0; x < maxSupportedMRTs; ++x) - { - if(mColour[x].buffer) - { - bool isDepth = PixelUtil::isDepth(mColour[x].buffer->getFormat()); - if(mColour[x].buffer->getWidth() != width || mColour[x].buffer->getHeight() != height) - { - StringStream ss; - ss << "Attachment " << x << " has incompatible size "; - ss << mColour[x].buffer->getWidth() << "x" << mColour[x].buffer->getHeight(); - ss << ". It must be of the same as the size of surface 0, "; - ss << width << "x" << height; - ss << "."; - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLES2FrameBufferObject::initialise"); - } - - mColour[x].buffer->bindToFramebuffer( - isDepth ? GL_DEPTH_ATTACHMENT : (GL_COLOR_ATTACHMENT0 + x), mColour[x].zoffset); - } - else - { - // Detach - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, static_cast(GL_COLOR_ATTACHMENT0+x), GL_RENDERBUFFER, 0)); - } - } - - // Now deal with depth / stencil - if (mMultisampleFB && !PixelUtil::isDepth(getFormat())) - { - // Bind multisample buffer - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB)); - - // Create AA render buffer (colour) - // note, this can be shared too because we blit it to the final FBO - // right after the render is finished - mMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples); - - // Attach it, because we won't be attaching below and non-multisample has - // actually been attached to other FBO - mMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0, - mMultisampleColourBuffer.zoffset); - - // depth & stencil will be dealt with below - } - - // Depth buffer is not handled here anymore. - // See GLES2FrameBufferObject::attachDepthBuffer() & RenderSystem::setDepthBufferFor() - - if(rs->hasMinGLVersion(3, 0) && OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN) // ED on Emscripten - { - GLenum bufs[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; - GLsizei n=0; - for(unsigned int x=0; xgetFormat()); - bufs[x] = isDepth ? GL_NONE : (GL_COLOR_ATTACHMENT0 + x); - // Keep highest used buffer + 1 - if(!isDepth) - n = x+1; - } - else - { - bufs[x] = GL_NONE; - } - } - - // Drawbuffer extension supported, use it - OGRE_CHECK_GL_ERROR(glDrawBuffers(n, bufs)); - } - // Check status - GLuint status; - OGRE_CHECK_GL_ERROR(status = glCheckFramebufferStatus(GL_FRAMEBUFFER)); - - // Bind main buffer -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - // The screen buffer is 1 on iOS - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 1)); -#else - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 0)); -#endif - - switch(status) - { - case GL_FRAMEBUFFER_COMPLETE: - // All is good - break; - case GL_FRAMEBUFFER_UNSUPPORTED: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "All framebuffer formats with this texture internal format unsupported", - "GLES2FrameBufferObject::initialise"); - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Framebuffer incomplete or other FBO status error", - "GLES2FrameBufferObject::initialise"); - } - - } - - bool GLES2FrameBufferObject::bind(bool recreateIfNeeded) - { - GLRenderSystemCommon* rs = static_cast(Root::getSingleton().getRenderSystem()); - GLContext* currentContext = rs->_getCurrentContext(); - if(mContext && mContext != currentContext) // FBO is unusable with current context, destroy it - { - if(mFB != 0) - rs->_destroyFbo(mContext, mFB); - if(mMultisampleFB != 0) - rs->_destroyFbo(mContext, mMultisampleFB); - - mContext = 0; - mFB = 0; - mMultisampleFB = 0; - } - - if(!mContext && recreateIfNeeded) // create FBO lazy or recreate after destruction - { - mContext = currentContext; - - // Generate framebuffer object - OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mFB)); - - // Will we need a second FBO to do multisampling? - if (mNumSamples) - { - OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mMultisampleFB)); - } - else - { - mMultisampleFB = 0; - } - - // Re-initialise - if(mColour[0].buffer) - initialise(); - } - - if(mContext) - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB ? mMultisampleFB : mFB)); - - return mContext != 0; - } - - void GLES2FrameBufferObject::swapBuffers() - { - if (mMultisampleFB) - { - GLint oldfb = 0; - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldfb)); - - // Blit from multisample buffer to final buffer, triggers resolve - uint32 width = mColour[0].buffer->getWidth(); - uint32 height = mColour[0].buffer->getHeight(); - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_READ_FRAMEBUFFER, mMultisampleFB)); - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mFB)); - OGRE_CHECK_GL_ERROR(glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST)); - // Unbind - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, oldfb)); - } - } - - void GLES2FrameBufferObject::attachDepthBuffer( DepthBuffer *depthBuffer ) - { - bind(true); // recreate FBO if unusable with current context, bind it - - auto glDepthBuffer = static_cast(depthBuffer); - - if( glDepthBuffer ) - { - auto *depthBuf = glDepthBuffer->getDepthBuffer(); - auto *stencilBuf = glDepthBuffer->getStencilBuffer(); - - //Attach depth buffer, if it has one. - if( depthBuf ) - depthBuf->bindToFramebuffer( GL_DEPTH_ATTACHMENT, 0 ); - - //Attach stencil buffer, if it has one. - if( stencilBuf ) - stencilBuf->bindToFramebuffer( GL_STENCIL_ATTACHMENT, 0 ); - } - else - { - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, - GL_RENDERBUFFER, 0)); - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, - GL_RENDERBUFFER, 0)); - } - } - //----------------------------------------------------------------------------- - void GLES2FrameBufferObject::detachDepthBuffer() - { - if(bind(false)) // bind or destroy FBO if unusable with current context - { - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0 )); - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0 )); - } - } -//----------------------------------------------------------------------------- -} diff --git a/RenderSystems/GLES2/src/OgreGLES2HardwareBuffer.cpp b/RenderSystems/GLES2/src/OgreGLES2HardwareBuffer.cpp deleted file mode 100644 index 389e67f0f22..00000000000 --- a/RenderSystems/GLES2/src/OgreGLES2HardwareBuffer.cpp +++ /dev/null @@ -1,253 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLES2HardwareBuffer.h" - -#include -#include "OgreRoot.h" -#include "OgreGLES2RenderSystem.h" -#include "OgreGLES2StateCacheManager.h" -#include "OgreDefaultHardwareBufferManager.h" - -namespace Ogre { - GLES2HardwareBuffer::GLES2HardwareBuffer(GLenum target, size_t sizeInBytes, uint32 usage, bool useShadowBuffer) - : HardwareBuffer(usage, useShadowBuffer || HANDLE_CONTEXT_LOSS), mTarget(target) - { - mSizeInBytes = sizeInBytes; - mRenderSystem = static_cast(Root::getSingleton().getRenderSystem()); - createBuffer(); - - if (useShadowBuffer || HANDLE_CONTEXT_LOSS) - { - mShadowBuffer = std::make_unique(mSizeInBytes); - } - } - - GLES2HardwareBuffer::~GLES2HardwareBuffer() - { - destroyBuffer(); - } - - void GLES2HardwareBuffer::createBuffer() - { - OGRE_CHECK_GL_ERROR(glGenBuffers(1, &mBufferId)); - - if (!mBufferId) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Cannot create GL ES buffer", - "GLES2HardwareBuffer::createBuffer"); - } - - mRenderSystem->_getStateCacheManager()->bindGLBuffer(mTarget, mBufferId); - OGRE_CHECK_GL_ERROR(glBufferData(mTarget, mSizeInBytes, NULL, getGLUsage(mUsage))); - } - - void GLES2HardwareBuffer::destroyBuffer() - { - // Delete the cached value - if(GLES2StateCacheManager* stateCacheManager = mRenderSystem->_getStateCacheManager()) - stateCacheManager->deleteGLBuffer(mTarget, mBufferId); - } - - void* GLES2HardwareBuffer::lockImpl(size_t offset, size_t length, - HardwareBuffer::LockOptions options) - { - GLenum access = 0; - - // Use glMapBuffer - mRenderSystem->_getStateCacheManager()->bindGLBuffer(mTarget, mBufferId); - - bool writeOnly = - options == HardwareBuffer::HBL_WRITE_ONLY || - ((mUsage & HBU_DETAIL_WRITE_ONLY) && - options != HardwareBuffer::HBL_READ_ONLY && options != HardwareBuffer::HBL_NORMAL); - - void* pBuffer = NULL; - if(mRenderSystem->getCapabilities()->hasCapability(RSC_MAPBUFFER)) - { - if (writeOnly) - { - access = GL_MAP_WRITE_BIT_EXT; - if (options == HBL_NO_OVERWRITE) - access |= GL_MAP_UNSYNCHRONIZED_BIT_EXT; - if (options == HBL_DISCARD) - OGRE_CHECK_GL_ERROR(glBufferData(mTarget, mSizeInBytes, NULL, getGLUsage(mUsage))); - } - else if (options == HardwareBuffer::HBL_READ_ONLY) - access = GL_MAP_READ_BIT_EXT; - else - access = GL_MAP_READ_BIT_EXT | GL_MAP_WRITE_BIT_EXT; - - OGRE_CHECK_GL_ERROR(pBuffer = glMapBufferRangeEXT(mTarget, offset, length, access)); - } - - if (!pBuffer) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Buffer: Out of memory", - "GLES2HardwareBuffer::lock"); - } - - // pBuffer is already offsetted in glMapBufferRange - return static_cast(pBuffer); - } - - void GLES2HardwareBuffer::unlockImpl() - { - mRenderSystem->_getStateCacheManager()->bindGLBuffer(mTarget, mBufferId); - - if(mRenderSystem->getCapabilities()->hasCapability(RSC_MAPBUFFER)) { - GLboolean mapped; - OGRE_CHECK_GL_ERROR(mapped = glUnmapBufferOES(mTarget)); - if(!mapped) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Buffer data corrupted, please reload", - "GLES2HardwareBuffer::unlock"); - } - } - } - - void GLES2HardwareBuffer::readData(size_t offset, size_t length, void* pDest) - { - if (mShadowBuffer) - { - mShadowBuffer->readData(offset, length, pDest); - return; - } - - OgreAssert(mRenderSystem->getCapabilities()->hasCapability(RSC_MAPBUFFER), - "Read hardware buffer is not supported"); - - mRenderSystem->_getStateCacheManager()->bindGLBuffer(mTarget, mBufferId); - // Map the buffer range then copy out of it into our destination buffer - void* srcData; - OGRE_CHECK_GL_ERROR(srcData = glMapBufferRangeEXT(mTarget, offset, length, GL_MAP_READ_BIT_EXT)); - memcpy(pDest, srcData, length); - - // Unmap the buffer since we are done. - GLboolean mapped; - OGRE_CHECK_GL_ERROR(mapped = glUnmapBufferOES(mTarget)); - if(!mapped) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Buffer data corrupted, please reload", - "GLES2HardwareBuffer::readData"); - } - } - - void GLES2HardwareBuffer::writeData(size_t offset, size_t length, const void* pSource, - bool discardWholeBuffer) - { - if (mShadowBuffer) - { - mShadowBuffer->writeData(offset, length, pSource, discardWholeBuffer); - } - - writeDataImpl(offset, length, pSource, discardWholeBuffer); - } - - void GLES2HardwareBuffer::writeDataImpl(size_t offset, size_t length, const void* pSource, - bool discardWholeBuffer) - { - mRenderSystem->_getStateCacheManager()->bindGLBuffer(mTarget, mBufferId); - - if (offset == 0 && length == mSizeInBytes) - { - OGRE_CHECK_GL_ERROR(glBufferData(mTarget, mSizeInBytes, pSource, getGLUsage(mUsage))); - } - else - { - if(discardWholeBuffer) - { - OGRE_CHECK_GL_ERROR(glBufferData(mTarget, mSizeInBytes, NULL, getGLUsage(mUsage))); - } - - OGRE_CHECK_GL_ERROR(glBufferSubData(mTarget, offset, length, pSource)); - } - } - - void GLES2HardwareBuffer::copyData(HardwareBuffer& srcBuffer, size_t srcOffset, size_t dstOffset, - size_t length, bool discardWholeBuffer) - { - if(!mRenderSystem->hasMinGLVersion(3, 0)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "GLES3 needed"); - - if (mShadowBuffer) - { - mShadowBuffer->copyData(srcBuffer, srcOffset, dstOffset, length, discardWholeBuffer); - } - - // Do it the fast way. - OGRE_CHECK_GL_ERROR(glBindBuffer(GL_COPY_READ_BUFFER, - static_cast(srcBuffer).getGLBufferId())); - OGRE_CHECK_GL_ERROR(glBindBuffer(GL_COPY_WRITE_BUFFER, mBufferId)); - - OGRE_CHECK_GL_ERROR(glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, srcOffset, dstOffset, length)); - - OGRE_CHECK_GL_ERROR(glBindBuffer(GL_COPY_READ_BUFFER, 0)); - OGRE_CHECK_GL_ERROR(glBindBuffer(GL_COPY_WRITE_BUFFER, 0)); - } - - GLenum GLES2HardwareBuffer::getGLUsage(unsigned int usage) - { - return (usage == HBU_GPU_TO_CPU) ? GL_STATIC_READ - : (usage == HBU_GPU_ONLY) ? GL_STATIC_DRAW : GL_DYNAMIC_DRAW; - } - - void GLES2HardwareBuffer::_updateFromShadow(void) - { - if (mShadowBuffer && mShadowUpdated && !mSuppressHardwareUpdate) - { - HardwareBufferLockGuard shadowLock(mShadowBuffer.get(), mLockStart, mLockSize, HBL_READ_ONLY); - writeDataImpl(mLockStart, mLockSize, shadowLock.pData, false); - - mShadowUpdated = false; - } - } - - void GLES2HardwareBuffer::setGLBufferBinding(GLint binding) - { - mBindingPoint = binding; - - // Attach the buffer to the UBO binding - OGRE_CHECK_GL_ERROR(glBindBufferBase(mTarget, mBindingPoint, mBufferId)); - } - -#if HANDLE_CONTEXT_LOSS - void GLES2HardwareBuffer::notifyOnContextLost() - { - destroyBuffer(); - } - - void GLES2HardwareBuffer::notifyOnContextReset() - { - createBuffer(); - mShadowUpdated = true; - _updateFromShadow(); - } -#endif -} diff --git a/RenderSystems/GLES2/src/OgreGLES2HardwareBufferManager.cpp b/RenderSystems/GLES2/src/OgreGLES2HardwareBufferManager.cpp deleted file mode 100644 index 342beaa0802..00000000000 --- a/RenderSystems/GLES2/src/OgreGLES2HardwareBufferManager.cpp +++ /dev/null @@ -1,169 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLES2HardwareBufferManager.h" -#include "OgreGLES2HardwareBuffer.h" -#include "OgreGLES2RenderToVertexBuffer.h" -#include "OgreGLES2RenderSystem.h" -#include "OgreGLVertexArrayObject.h" -#include "OgreGLUtil.h" -#include "OgreRoot.h" - -namespace Ogre { - //----------------------------------------------------------------------- - GLES2HardwareBufferManager::GLES2HardwareBufferManager() - { - mRenderSystem = getGLES2RenderSystem(); - } - - GLES2HardwareBufferManager::~GLES2HardwareBufferManager() - { - destroyAllDeclarations(); - destroyAllBindings(); - } - - void GLES2HardwareBufferManager::notifyContextDestroyed(GLContext* context) - { - OGRE_LOCK_MUTEX(mVertexDeclarationsMutex); - for(auto& d : mVertexDeclarations) - static_cast(d)->notifyContextDestroyed(context); - } - - HardwareVertexBufferSharedPtr - GLES2HardwareBufferManager::createVertexBuffer(size_t vertexSize, - size_t numVerts, - HardwareBuffer::Usage usage, - bool useShadowBuffer) - { - if(!mRenderSystem->getCapabilities()->hasCapability(RSC_MAPBUFFER)) - useShadowBuffer = true; - - auto impl = new GLES2HardwareBuffer(GL_ARRAY_BUFFER, vertexSize * numVerts, usage, useShadowBuffer); - auto buf = std::make_shared(this, vertexSize, numVerts, impl); - { - OGRE_LOCK_MUTEX(mVertexBuffersMutex); - mVertexBuffers.insert(buf.get()); - } - return buf; - } - - HardwareIndexBufferSharedPtr GLES2HardwareBufferManager::createIndexBuffer(HardwareIndexBuffer::IndexType itype, - size_t numIndexes, - HardwareBuffer::Usage usage, - bool useShadowBuffer) - { - if(!mRenderSystem->getCapabilities()->hasCapability(RSC_MAPBUFFER)) - useShadowBuffer = true; - - auto indexSize = HardwareIndexBuffer::indexSize(itype); - auto impl = new GLES2HardwareBuffer(GL_ELEMENT_ARRAY_BUFFER, indexSize * numIndexes, usage, useShadowBuffer); - - return std::make_shared(this, itype, numIndexes, impl); - } - - RenderToVertexBufferSharedPtr GLES2HardwareBufferManager::createRenderToVertexBuffer() - { - if(mRenderSystem->hasMinGLVersion(3, 0)) - return RenderToVertexBufferSharedPtr(new GLES2RenderToVertexBuffer()); - - // not supported - return RenderToVertexBufferSharedPtr(); - } - - VertexDeclaration* GLES2HardwareBufferManager::createVertexDeclarationImpl(void) - { - return OGRE_NEW GLVertexArrayObject(); - } - - GLenum GLES2HardwareBufferManager::getGLType(VertexElementType type) - { - switch(type) - { - case VET_FLOAT1: - case VET_FLOAT2: - case VET_FLOAT3: - case VET_FLOAT4: - return GL_FLOAT; - case VET_SHORT1: - case VET_SHORT2: - case VET_SHORT3: - case VET_SHORT4: - case VET_SHORT2_NORM: - case VET_SHORT4_NORM: - return GL_SHORT; - case VET_UBYTE4: - case VET_UBYTE4_NORM: - case _DETAIL_SWAP_RB: - return GL_UNSIGNED_BYTE; - case VET_BYTE4: - case VET_BYTE4_NORM: - return GL_BYTE; - case VET_INT1: - case VET_INT2: - case VET_INT3: - case VET_INT4: - return GL_INT; - case VET_UINT1: - case VET_UINT2: - case VET_UINT3: - case VET_UINT4: - return GL_UNSIGNED_INT; - case VET_USHORT1: - case VET_USHORT2: - case VET_USHORT3: - case VET_USHORT4: - case VET_USHORT2_NORM: - case VET_USHORT4_NORM: - return GL_UNSIGNED_SHORT; - case VET_DOUBLE1: - case VET_DOUBLE2: - case VET_DOUBLE3: - case VET_DOUBLE4: - return 0; - case VET_INT_10_10_10_2_NORM: - return GL_INT_2_10_10_10_REV; - }; - - OgreAssert(false, "unknown Vertex Element Type"); - return 0; - } - - //--------------------------------------------------------------------- - HardwareBufferPtr GLES2HardwareBufferManager::createUniformBuffer( size_t sizeBytes, HardwareBufferUsage usage, bool useShadowBuffer) - { - if (!mRenderSystem->hasMinGLVersion(3, 0)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "GLES2 does not support uniform buffer objects"); - } - - auto impl = new GLES2HardwareBuffer(GL_UNIFORM_BUFFER, sizeBytes, usage, useShadowBuffer); - auto buf = HardwareBufferPtr(impl); - return buf; - } - -} diff --git a/RenderSystems/GLES2/src/OgreGLES2HardwareOcclusionQuery.cpp b/RenderSystems/GLES2/src/OgreGLES2HardwareOcclusionQuery.cpp deleted file mode 100644 index eb64f30eb81..00000000000 --- a/RenderSystems/GLES2/src/OgreGLES2HardwareOcclusionQuery.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLES2HardwareOcclusionQuery.h" -#include "OgreLogManager.h" -#include "OgreException.h" -#include "OgreRoot.h" -#include "OgreGLES2RenderSystem.h" -#include "OgreGLUtil.h" - -namespace Ogre { - -//------------------------------------------------------------------ -/** - * Default object constructor - * - */ -GLES2HardwareOcclusionQuery::GLES2HardwareOcclusionQuery() -{ - createQuery(); -} -//------------------------------------------------------------------ -/** - * Object destructor - */ -GLES2HardwareOcclusionQuery::~GLES2HardwareOcclusionQuery() -{ - destroyQuery(); -} -//------------------------------------------------------------------ -void GLES2HardwareOcclusionQuery::createQuery() -{ - OGRE_CHECK_GL_ERROR(glGenQueriesEXT(1, &mQueryID)); -} -//------------------------------------------------------------------ -void GLES2HardwareOcclusionQuery::destroyQuery() -{ - OGRE_CHECK_GL_ERROR(glDeleteQueriesEXT(1, &mQueryID)); -} -//------------------------------------------------------------------ -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN -void GLES2HardwareOcclusionQuery::notifyOnContextLost() -{ - destroyQuery(); -} -//------------------------------------------------------------------ -void GLES2HardwareOcclusionQuery::notifyOnContextReset() -{ - createQuery(); -} -#endif -//------------------------------------------------------------------ -void GLES2HardwareOcclusionQuery::beginOcclusionQuery() -{ - OGRE_CHECK_GL_ERROR(glBeginQueryEXT(GL_ANY_SAMPLES_PASSED_EXT, mQueryID)); -} -//------------------------------------------------------------------ -void GLES2HardwareOcclusionQuery::endOcclusionQuery() -{ - OGRE_CHECK_GL_ERROR(glEndQueryEXT(GL_ANY_SAMPLES_PASSED_EXT)); -} -//------------------------------------------------------------------ -bool GLES2HardwareOcclusionQuery::pullOcclusionQuery( unsigned int* NumOfFragments ) -{ - OGRE_CHECK_GL_ERROR(glGetQueryObjectuivEXT(mQueryID, GL_QUERY_RESULT_EXT, (GLuint*)NumOfFragments)); - mPixelCount = *NumOfFragments; - return true; -} -//------------------------------------------------------------------ -bool GLES2HardwareOcclusionQuery::isStillOutstanding(void) -{ - GLuint available = GL_FALSE; - - OGRE_CHECK_GL_ERROR(glGetQueryObjectuivEXT(mQueryID, GL_QUERY_RESULT_AVAILABLE_EXT, &available)); - - // GL_TRUE means a wait would occur - return !(available == GL_TRUE); -} - -} diff --git a/RenderSystems/GLES2/src/OgreGLES2HardwarePixelBuffer.cpp b/RenderSystems/GLES2/src/OgreGLES2HardwarePixelBuffer.cpp deleted file mode 100644 index 663dc69bfe9..00000000000 --- a/RenderSystems/GLES2/src/OgreGLES2HardwarePixelBuffer.cpp +++ /dev/null @@ -1,507 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLES2HardwareBufferManager.h" -#include "OgreGLES2HardwarePixelBuffer.h" - -#include "OgreTextureManager.h" - -#include "OgreGLES2PixelFormat.h" -#include "OgreGLES2FBORenderTexture.h" -#include "OgreGLUtil.h" -#include "OgreGLES2RenderSystem.h" -#include "OgreGLES2StateCacheManager.h" -#include "OgreRoot.h" -#include "OgreGLSLESProgramManager.h" -#include "OgreGLSLESLinkProgram.h" -#include "OgreGLSLESProgramPipeline.h" -#include "OgreBitwise.h" -#include "OgreGLNativeSupport.h" -#include "OgreGLES2HardwareBuffer.h" -#include "OgreGLES2Texture.h" -#include "OgreLogManager.h" - -namespace Ogre { - void GLES2TextureBuffer::_blitFromMemory(const PixelBox &src, const Box &dst) - { - if (!mBuffer.contains(dst)) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Destination box out of range", - "GLES2HardwarePixelBuffer::blitFromMemory"); - } - - PixelBox converted; - - if (src.format != mFormat) - { - // Extents match, but format is not accepted as valid source format for GL - // do conversion in temporary buffer - allocateBuffer(); - converted = mBuffer.getSubVolume(src); - PixelUtil::bulkPixelConversion(src, converted); - } - else - { - // No conversion needed - converted = src; - } - - upload(converted, dst); - freeBuffer(); - } - - void GLES2TextureBuffer::blitToMemory(const Box &srcBox, const PixelBox &dst) - { - if (!mBuffer.contains(srcBox)) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "source box out of range", - "GLES2HardwarePixelBuffer::blitToMemory"); - } - - if (srcBox.getOrigin() == Vector3i(0, 0 ,0) && - srcBox.getSize() == getSize() && - dst.getSize() == getSize() && - GLES2PixelUtil::getGLInternalFormat(dst.format) != 0) - { - // The direct case: the user wants the entire texture in a format supported by GL - // so we don't need an intermediate buffer - download(dst); - } - else - { - // Use buffer for intermediate copy - allocateBuffer(); - // Download entire buffer - download(mBuffer); - if(srcBox.getSize() != dst.getSize()) - { - // We need scaling - Image::scale(mBuffer.getSubVolume(srcBox), dst, Image::FILTER_BILINEAR); - } - else - { - // Just copy the bit that we need - PixelUtil::bulkPixelConversion(mBuffer.getSubVolume(srcBox), dst); - } - freeBuffer(); - } - } - - // TextureBuffer - GLES2TextureBuffer::GLES2TextureBuffer(GLES2Texture* parent, GLint face, GLint level, - GLint width, GLint height, GLint depth) - : GLHardwarePixelBufferCommon(width, height, depth, parent->getFormat(), (Usage)parent->getUsage()), - mTarget(parent->getGLES2TextureTarget()), mTextureID(parent->getGLID()), - mLevel(level) - { - // Get face identifier - mFaceTarget = mTarget; - if(mTarget == GL_TEXTURE_CUBE_MAP) - mFaceTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + face; - - mGLInternalFormat = - GLES2PixelUtil::getGLInternalFormat(mFormat, parent->isHardwareGammaEnabled()); - - // Set up a pixel box - mBuffer = PixelBox(mWidth, mHeight, mDepth, mFormat); - - if (mWidth==0 || mHeight==0 || mDepth==0) - // We are invalid, do not allocate a buffer - return; - - // Is this a render target? - if (mUsage & TU_RENDERTARGET) - { - // Create render target for each slice - mSliceTRT.reserve(mDepth); - for(uint32 zoffset=0; zoffsetgetName(); - GLSurfaceDesc surface; - surface.buffer = this; - surface.zoffset = zoffset; - RenderTexture* trt = GLRTTManager::getSingleton().createRenderTexture( - name, surface, parent->isHardwareGammaEnabled(), parent->getFSAA()); - mSliceTRT.push_back(trt); - Root::getSingleton().getRenderSystem()->attachRenderTarget(*mSliceTRT[zoffset]); - } - } - } - - GLES2TextureBuffer::~GLES2TextureBuffer() - { - } - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - void GLES2TextureBuffer::updateTextureId(GLuint textureID) - { - mTextureID = textureID; - } -#endif - - void GLES2TextureBuffer::upload(const PixelBox &data, const Box &dest) - { - GLES2RenderSystem* rs = getGLES2RenderSystem(); - - rs->_getStateCacheManager()->bindGLTexture(mTarget, mTextureID); - - bool hasGLES30 = rs->hasMinGLVersion(3, 0); - // PBO handling is broken -#if 0// OGRE_NO_GLES3_SUPPORT == 0 - // Calculate size for all mip levels of the texture - size_t dataSize = 0; - if(mTarget == GL_TEXTURE_2D_ARRAY) - { - dataSize = PixelUtil::getMemorySize(dest.getWidth(), dest.getHeight(), dest.getDepth(), data.format); - } - else - { - dataSize = PixelUtil::getMemorySize(data.getWidth(), data.getHeight(), mDepth, data.format); - } - - // Upload data to PBO - GLES2HardwareBuffer buffer(GL_PIXEL_UNPACK_BUFFER, dataSize, mUsage); - buffer.writeData(0, dataSize, data.data, false); - - void* pdata = NULL; -#else - void* pdata = data.getTopLeftFrontPixelPtr(); -#endif - - if (PixelUtil::isCompressed(data.format)) - { - if(data.format != mFormat || !data.isConsecutive()) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Compressed images must be consecutive, in the source format", - "GLES2TextureBuffer::upload"); - - GLenum format = GLES2PixelUtil::getGLInternalFormat(mFormat); - // Data must be consecutive and at beginning of buffer as PixelStorei not allowed - // for compressed formats - switch(mTarget) { - case GL_TEXTURE_2D: - case GL_TEXTURE_CUBE_MAP: - OGRE_CHECK_GL_ERROR(glCompressedTexSubImage2D(mFaceTarget, mLevel, - dest.left, dest.top, - dest.getWidth(), dest.getHeight(), - format, data.getConsecutiveSize(), - pdata)); - break; - case GL_TEXTURE_2D_ARRAY: - if(!hasGLES30) - break; - OGRE_FALLTHROUGH; - case GL_TEXTURE_3D_OES: - OGRE_CHECK_GL_ERROR(glCompressedTexSubImage3DOES(mTarget, mLevel, - dest.left, dest.top, dest.front, - dest.getWidth(), dest.getHeight(), dest.getDepth(), - format, data.getConsecutiveSize(), - pdata)); - break; - } - } - else - { - if (data.getWidth() != data.rowPitch) - { - if(!hasGLES30) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Unsupported texture format", - "GLES2TextureBuffer::upload"); - - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_ROW_LENGTH, data.rowPitch)) - } - - if (data.getHeight() * data.getWidth() != data.slicePitch) - { - if(!hasGLES30) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Unsupported texture format", - "GLES2TextureBuffer::upload"); - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, (data.slicePitch/data.getWidth()))); - } - - if((data.getWidth()*PixelUtil::getNumElemBytes(data.format)) & 3) { - // Standard alignment of 4 is not right - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_ALIGNMENT, 1)); - } - - switch(mTarget) { - case GL_TEXTURE_2D: - case GL_TEXTURE_CUBE_MAP: - OGRE_CHECK_GL_ERROR(glTexSubImage2D(mFaceTarget, mLevel, - dest.left, dest.top, - dest.getWidth(), dest.getHeight(), - GLES2PixelUtil::getGLOriginFormat(data.format), GLES2PixelUtil::getGLOriginDataType(data.format), - pdata)); - break; - case GL_TEXTURE_2D_ARRAY: - if(!hasGLES30) - break; - OGRE_FALLTHROUGH; - case GL_TEXTURE_3D_OES: - OGRE_CHECK_GL_ERROR(glTexSubImage3DOES( - mTarget, mLevel, - dest.left, dest.top, dest.front, - dest.getWidth(), dest.getHeight(), dest.getDepth(), - GLES2PixelUtil::getGLOriginFormat(data.format), GLES2PixelUtil::getGLOriginDataType(data.format), - pdata)); - break; - } - - // TU_AUTOMIPMAP is only enabled when there are no custom mips - // so we do not have to care about overwriting - if ((mUsage & TU_AUTOMIPMAP) && (mLevel == 0) - && (hasGLES30 || mTarget == GL_TEXTURE_2D || mTarget == GL_TEXTURE_CUBE_MAP)) - { - OGRE_CHECK_GL_ERROR(glGenerateMipmap(mTarget)); - } - } - - // Restore defaults - if(hasGLES30) { - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)); - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_IMAGE_HEIGHT, 0)); - } - - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_UNPACK_ALIGNMENT, 4)); - } - - //----------------------------------------------------------------------------- - void GLES2TextureBuffer::download(const PixelBox &data) - { - if(data.getSize() != getSize()) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "only download of entire buffer is supported by GL ES", - "GLES2TextureBuffer::download"); - - if(PixelUtil::isCompressed(data.format)) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Compressed images cannot be downloaded by GL ES", - "GLES2TextureBuffer::download"); - } - - if((data.getWidth()*PixelUtil::getNumElemBytes(data.format)) & 3) { - // Standard alignment of 4 is not right - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_PACK_ALIGNMENT, 1)); - } - - GLint currentFBO = 0; - GLuint tempFBO = 0; - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_FRAMEBUFFER_BINDING, ¤tFBO)); - OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &tempFBO)); - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, tempFBO)); - - // Construct a temp PixelBox that is RGBA because GL_RGBA/GL_UNSIGNED_BYTE is the only combination that is - // guaranteed to work on all platforms. - size_t sizeInBytes = PixelUtil::getMemorySize(data.getWidth(), data.getHeight(), data.getDepth(), PF_A8B8G8R8); - PixelBox tempBox = PixelBox(data.getWidth(), data.getHeight(), data.getDepth(), PF_A8B8G8R8); - tempBox.data = new uint8[sizeInBytes]; - - switch (mTarget) - { - case GL_TEXTURE_2D: - case GL_TEXTURE_CUBE_MAP: - OGRE_CHECK_GL_ERROR(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mTextureID, 0)); - OGRE_CHECK_GL_ERROR(glCheckFramebufferStatus(GL_FRAMEBUFFER)); - OGRE_CHECK_GL_ERROR(glReadPixels(0, 0, data.getWidth(), data.getHeight(), - GL_RGBA, - GL_UNSIGNED_BYTE, - tempBox.data)); - break; - } - - PixelUtil::bulkPixelConversion(tempBox, data); - - delete[] tempBox.data; - tempBox.data = 0; - - // Restore defaults - OGRE_CHECK_GL_ERROR(glPixelStorei(GL_PACK_ALIGNMENT, 4)); - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, currentFBO)); - OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &tempFBO)); - } - - //----------------------------------------------------------------------------- - void GLES2TextureBuffer::bindToFramebuffer(uint32 attachment, uint32 zoffset) - { - assert(zoffset < mDepth); - OGRE_CHECK_GL_ERROR(glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, - mFaceTarget, mTextureID, mLevel)); - } - - void GLES2TextureBuffer::copyFromFramebuffer(size_t zoffset) - { - getGLES2RenderSystem()->_getStateCacheManager()->bindGLTexture(mTarget, mTextureID); - OGRE_CHECK_GL_ERROR(glCopyTexSubImage2D(mFaceTarget, mLevel, 0, 0, 0, 0, mWidth, mHeight)); - } - - //----------------------------------------------------------------------------- - void GLES2TextureBuffer::blit(const HardwarePixelBufferSharedPtr &src, const Box &srcBox, const Box &dstBox) - { - GLES2TextureBuffer *srct = static_cast(src.get()); - if ((srcBox.getWidth() == dstBox.getWidth() && srcBox.getHeight() == dstBox.getHeight() && - srcBox.getDepth() == 1)) - { - blitFromTexture(srct, srcBox, dstBox); - } - else - { - GLHardwarePixelBufferCommon::blit(src, srcBox, dstBox); - } - } - - //----------------------------------------------------------------------------- - void GLES2TextureBuffer::blitFromTexture(GLES2TextureBuffer *src, const Box &srcBox, const Box &dstBox) - { - GLES2RenderSystem* rs = getGLES2RenderSystem(); - - // Store old binding so it can be restored later - GLint oldfb; - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldfb)); - - // Set up temporary FBO - GLuint tempFBO; - OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &tempFBO)); - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, tempFBO)); - - src->bindToFramebuffer(GL_COLOR_ATTACHMENT0, 0); - rs->_getStateCacheManager()->bindGLTexture(mTarget, mTextureID); - - switch (mTarget) - { - case GL_TEXTURE_2D: - case GL_TEXTURE_CUBE_MAP: - OGRE_CHECK_GL_ERROR(glCopyTexSubImage2D(mFaceTarget, mLevel, dstBox.left, dstBox.top, - srcBox.left, srcBox.top, dstBox.getWidth(), - dstBox.getHeight())); - break; - case GL_TEXTURE_3D: - case GL_TEXTURE_2D_ARRAY: - // Process each destination slice - for (uint32 slice = dstBox.front; slice < dstBox.back; ++slice) - { - OGRE_CHECK_GL_ERROR(glCopyTexSubImage3D(mFaceTarget, mLevel, dstBox.left, dstBox.top, slice, - srcBox.left, srcBox.top, dstBox.getWidth(), - dstBox.getHeight())); - } - break; - } - - // Restore old framebuffer - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, oldfb)); - OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &tempFBO)); - - // Generate mipmaps - if (mUsage & TU_AUTOMIPMAP) - { - OGRE_CHECK_GL_ERROR(glGenerateMipmap(mTarget)); - } - } - //----------------------------------------------------------------------------- - // blitFromMemory doing hardware trilinear scaling - void GLES2TextureBuffer::blitFromMemory(const PixelBox &src, const Box &dstBox) - { - // Fall back to normal GLHardwarePixelBuffer::blitFromMemory in case - // the source dimensions match the destination ones, in which case no scaling is needed - // FIXME: always uses software path, as blitFromTexture is not implemented - if(true || - (src.getSize() == dstBox.getSize())) - { - _blitFromMemory(src, dstBox); - return; - } - if(!mBuffer.contains(dstBox)) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Destination box out of range", - "GLES2TextureBuffer::blitFromMemory"); - - TextureType type = (src.getDepth() != 1) ? TEX_TYPE_3D : TEX_TYPE_2D; - - // Set automatic mipmap generation; nice for minimisation - TexturePtr tex = TextureManager::getSingleton().createManual( - "GLBlitFromMemoryTMP", ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, type, - src.getWidth(), src.getHeight(), src.getDepth(), MIP_UNLIMITED, src.format); - - // Upload data to 0,0,0 in temporary texture - Box tempTarget(src.getSize()); - tex->getBuffer()->blitFromMemory(src); - - // Blit from texture - blit(tex->getBuffer(), tempTarget, dstBox); - - // Delete temp texture - TextureManager::getSingleton().remove(tex); - } - - //********* GLES2RenderBuffer - //----------------------------------------------------------------------------- - GLES2RenderBuffer::GLES2RenderBuffer(GLenum format, uint32 width, uint32 height, GLsizei numSamples): - GLHardwarePixelBufferCommon(width, height, 1, GLES2PixelUtil::getClosestOGREFormat(format), HBU_GPU_ONLY) - { - GLES2RenderSystem* rs = getGLES2RenderSystem(); - - mGLInternalFormat = format; - mNumSamples = numSamples; - - // Generate renderbuffer - OGRE_CHECK_GL_ERROR(glGenRenderbuffers(1, &mRenderbufferID)); - - // Bind it to FBO - OGRE_CHECK_GL_ERROR(glBindRenderbuffer(GL_RENDERBUFFER, mRenderbufferID)); - - // Allocate storage for depth buffer - if (mNumSamples > 0) - { - if(rs->hasMinGLVersion(3, 0) || rs->checkExtension("GL_APPLE_framebuffer_multisample")) - { - OGRE_CHECK_GL_ERROR(glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, - mNumSamples, mGLInternalFormat, mWidth, mHeight)); - } - } - else - { - OGRE_CHECK_GL_ERROR(glRenderbufferStorage(GL_RENDERBUFFER, mGLInternalFormat, - mWidth, mHeight)); - } - } - //----------------------------------------------------------------------------- - GLES2RenderBuffer::~GLES2RenderBuffer() - { - OGRE_CHECK_GL_ERROR(glDeleteRenderbuffers(1, &mRenderbufferID)); - } - //----------------------------------------------------------------------------- - void GLES2RenderBuffer::bindToFramebuffer(uint32 attachment, uint32 zoffset) - { - assert(zoffset < mDepth); - OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, - GL_RENDERBUFFER, mRenderbufferID)); - } -} diff --git a/RenderSystems/GLES2/src/OgreGLES2ManagedResource.cpp b/RenderSystems/GLES2/src/OgreGLES2ManagedResource.cpp deleted file mode 100644 index 296da201b64..00000000000 --- a/RenderSystems/GLES2/src/OgreGLES2ManagedResource.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLES2ManagedResource.h" -#include "OgreGLES2ManagedResourceManager.h" -#include "OgreGLES2RenderSystem.h" - -namespace Ogre -{ - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - - GLES2ManagedResource::GLES2ManagedResource() - { - GLES2RenderSystem::getResourceManager()->_notifyResourceCreated(static_cast(this)); - } - - GLES2ManagedResource::~GLES2ManagedResource() - { - GLES2RenderSystem::getResourceManager()->_notifyResourceDestroyed(static_cast(this)); - } - - #endif - -} diff --git a/RenderSystems/GLES2/src/OgreGLES2ManagedResourceManager.cpp b/RenderSystems/GLES2/src/OgreGLES2ManagedResourceManager.cpp deleted file mode 100644 index de87a0df8a1..00000000000 --- a/RenderSystems/GLES2/src/OgreGLES2ManagedResourceManager.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreGLES2ManagedResource.h" -#include "OgreGLES2ManagedResourceManager.h" - -namespace Ogre -{ - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - - //----------------------------------------------------------------------- - GLES2ManagedResourceManager::GLES2ManagedResourceManager() - { - } - //----------------------------------------------------------------------- - GLES2ManagedResourceManager::~GLES2ManagedResourceManager() - { - - } - //----------------------------------------------------------------------- - void GLES2ManagedResourceManager::notifyOnContextLost() - { - for (auto& r : mResources) - r->notifyOnContextLost(); - } - //----------------------------------------------------------------------- - void GLES2ManagedResourceManager::notifyOnContextReset() - { - for (auto& r : mResources) - r->notifyOnContextReset(); - } - //----------------------------------------------------------------------- - void GLES2ManagedResourceManager::_notifyResourceCreated(GLES2ManagedResource* pResource) - { - mResources.push_back(pResource); - } - //----------------------------------------------------------------------- - void GLES2ManagedResourceManager::_notifyResourceDestroyed(GLES2ManagedResource* pResource) - { - ResourceContainerIterator it = std::find( mResources.begin(), mResources.end(), pResource ); - if(it != mResources.end()) - mResources.erase(it); - } - -#endif - -} diff --git a/RenderSystems/GLES2/src/OgreGLES2PixelFormat.cpp b/RenderSystems/GLES2/src/OgreGLES2PixelFormat.cpp deleted file mode 100644 index 7e1578e238e..00000000000 --- a/RenderSystems/GLES2/src/OgreGLES2PixelFormat.cpp +++ /dev/null @@ -1,375 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLES2PixelFormat.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" -#include "OgreBitwise.h" -#include "OgreLogManager.h" - -namespace Ogre { - struct GLPixelFormatDescription { - GLenum format; - GLenum type; - GLenum internalFormat; - }; - - static GLPixelFormatDescription _pixelFormatsSized[] = { - {GL_NONE}, // PF_UNKNOWN - {GL_RED, GL_UNSIGNED_BYTE, GL_R8}, // PF_L8 - {GL_RED, GL_UNSIGNED_SHORT, GL_R16UI}, // PF_L16 - {GL_RED, GL_UNSIGNED_BYTE, GL_R8}, // PF_A8 - {GL_RG, GL_UNSIGNED_BYTE, GL_RG8}, // PF_BYTE_LA - {GL_RGB, GL_UNSIGNED_SHORT_5_6_5, GL_RGB565}, // PF_R5G6B5 - {GL_NONE}, // PF_B5G6R5 - {GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, GL_RGBA4}, // PF_A4R4G4B4, todo: reversed? - {GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, GL_RGB5_A1}, // PF_A1R5G5B5, todo: reversed? -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - {GL_RGB, GL_UNSIGNED_BYTE, GL_RGB8}, // PF_R8G8B8 - {GL_NONE}, // PF_B8G8R8 - {GL_NONE}, // PF_A8R8G8B8 - {GL_NONE}, // PF_A8B8G8R8 - {GL_BGRA_EXT, GL_UNSIGNED_BYTE, GL_BGRA8_EXT}, // PF_B8G8R8A8 -#else - {GL_NONE}, // PF_R8G8B8 - {GL_RGB, GL_UNSIGNED_BYTE, GL_RGB8}, // PF_B8G8R8 - {GL_BGRA_EXT, GL_UNSIGNED_BYTE, GL_BGRA8_EXT}, // PF_A8R8G8B8 - {GL_RGBA, GL_UNSIGNED_BYTE, GL_RGBA8}, // PF_A8B8G8R8 - {GL_NONE}, // PF_B8G8R8A8 -#endif - {GL_NONE}, // PF_A2R10G10B10 - {GL_RGBA_INTEGER, GL_UNSIGNED_INT_2_10_10_10_REV, GL_RGB10_A2UI},// PF_A2B10G10R10 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT},// PF_DXT1 - {GL_NONE}, // PF_DXT2 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT},// PF_DXT3 - {GL_NONE}, // PF_DXT4 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT},// PF_DXT5 - {GL_RGB, GL_HALF_FLOAT, GL_RGB16F}, // PF_FLOAT16_RGB - {GL_RGBA, GL_HALF_FLOAT, GL_RGBA16F}, // PF_FLOAT16_RGBA - {GL_RGB, GL_FLOAT, GL_RGB32F}, // PF_FLOAT32_RGB - {GL_RGBA, GL_FLOAT, GL_RGBA32F}, // PF_FLOAT32_RGBA -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - {GL_NONE}, // PF_X8R8G8B8 - {GL_NONE}, // PF_X8B8G8R8 - {GL_RGBA, GL_UNSIGNED_BYTE, GL_RGBA8}, // PF_R8G8B8A8 -#else - {GL_BGRA_EXT, GL_UNSIGNED_BYTE, GL_BGRA8_EXT}, // PF_X8R8G8B8 - {GL_RGBA, GL_UNSIGNED_BYTE, GL_RGBA8}, // PF_X8B8G8R8 - {GL_NONE}, // PF_R8G8B8A8 -#endif - {GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, GL_DEPTH_COMPONENT16}, // PF_DEPTH16 - {GL_RGBA, GL_UNSIGNED_SHORT, GL_RGBA16UI}, // PF_SHORT_RGBA - {GL_NONE}, // PF_R3G3B2 - {GL_RED, GL_HALF_FLOAT, GL_R16F}, // PF_FLOAT16_R - {GL_RED, GL_FLOAT, GL_R32F}, // PF_FLOAT32_R - {GL_RG, GL_UNSIGNED_SHORT, GL_RG16UI}, // PF_SHORT_GR - {GL_RG, GL_HALF_FLOAT, GL_RG16F}, // PF_FLOAT16_GR - {GL_RG, GL_FLOAT, GL_RG32F}, // PF_FLOAT32_GR - {GL_RGB, GL_UNSIGNED_SHORT, GL_RGB16UI}, // PF_SHORT_RGB - {GL_NONE, GL_NONE, GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG}, // PF_PVRTC_RGB2 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG},// PF_PVRTC_RGBA2 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG}, // PF_PVRTC_RGB4 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG},// PF_PVRTC_RGBA4 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG},// PF_PVRTC2_2BPP - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG},// PF_PVRTC2_4BPP - {GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, GL_R11F_G11F_B10F}, // PF_R11G11B10_FLOAT, todo: reversed? - {GL_RED_INTEGER, GL_UNSIGNED_BYTE, GL_R8UI}, // PF_R8_UINT - {GL_RG_INTEGER, GL_UNSIGNED_BYTE, GL_RG8UI}, // PF_R8G8_UINT - {GL_RGB_INTEGER, GL_UNSIGNED_BYTE, GL_RGB8UI}, // PF_R8G8B8_UINT - {GL_RGBA_INTEGER, GL_UNSIGNED_BYTE, GL_RGBA8UI}, // PF_R8G8B8A8_UINT - {GL_RED_INTEGER, GL_UNSIGNED_SHORT, GL_R16UI}, // PF_R16_UINT - {GL_RG_INTEGER, GL_UNSIGNED_SHORT, GL_RG16UI}, // PF_R16G16_UINT - {GL_RGB_INTEGER, GL_UNSIGNED_SHORT, GL_RGB16UI}, // PF_R16G16B16_UINT - {GL_RGBA_INTEGER, GL_UNSIGNED_SHORT, GL_RGBA16UI}, // PF_R16G16B16A16_UINT - {GL_RED_INTEGER, GL_UNSIGNED_INT, GL_R32UI}, // PF_R32_UINT - {GL_RG_INTEGER, GL_UNSIGNED_INT, GL_RG32UI}, // PF_R32G32_UINT - {GL_RGB_INTEGER, GL_UNSIGNED_INT, GL_RGB32UI}, // PF_R32G32B32_UINT - {GL_RGBA_INTEGER, GL_UNSIGNED_INT, GL_RGBA32UI}, // PF_R32G32B32A32_UINT - {GL_RED_INTEGER, GL_BYTE, GL_R8I}, // PF_R8_SINT - {GL_RG_INTEGER, GL_BYTE, GL_RG8I}, // PF_R8G8_SINT - {GL_RGB_INTEGER, GL_BYTE, GL_RGB8I}, // PF_R8G8B8_SINT - {GL_RGBA_INTEGER, GL_BYTE, GL_RGBA8I}, // PF_R8G8B8A8_SINT - {GL_RED_INTEGER, GL_SHORT, GL_R16I}, // PF_R16_SINT - {GL_RG_INTEGER, GL_SHORT, GL_RG16I}, // PF_R16G16_SINT - {GL_RGB_INTEGER, GL_SHORT, GL_RGB16I}, // PF_R16G16B16_SINT - {GL_RGBA_INTEGER, GL_SHORT, GL_RGBA16I}, // PF_R16G16B16A16_SINT - {GL_RED_INTEGER, GL_INT, GL_R32I}, // PF_R32_SINT - {GL_RG_INTEGER, GL_INT, GL_RG32I}, // PF_R32G32_SINT - {GL_RGB_INTEGER, GL_INT, GL_RGB32I}, // PF_R32G32B32_SINT - {GL_RGBA_INTEGER, GL_INT, GL_RGBA32I}, // PF_R32G32B32A32_SINT - {GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV, GL_RGB9_E5}, // PF_R9G9B9E5_SHAREDEXP - {GL_NONE}, // PF_BC4_UNORM - {GL_NONE}, // PF_BC4_SNORM - {GL_NONE}, // PF_BC5_UNORM - {GL_NONE}, // PF_BC5_SNORM - {GL_NONE}, // PF_BC6H_UF16 - {GL_NONE}, // PF_BC6H_SF16 - {GL_NONE}, // PF_BC7_UNORM - {GL_RED_EXT, GL_UNSIGNED_BYTE, GL_R8_EXT}, // PF_R8 - {GL_RG_EXT, GL_UNSIGNED_BYTE, GL_RG8_EXT}, // PF_RG8 - {GL_RED, GL_UNSIGNED_BYTE, GL_R8_SNORM}, // PF_R8_SNORM - {GL_RG, GL_UNSIGNED_BYTE, GL_RG8_SNORM}, // PF_RG8_SNORM - {GL_RGB, GL_UNSIGNED_BYTE, GL_RGB8_SNORM}, // PF_RGB8_SNORM - {GL_RGBA, GL_UNSIGNED_BYTE, GL_RGBA8_SNORM}, // PF_RGBA8_SNORM - {GL_RED, GL_UNSIGNED_SHORT, GL_R16_SNORM_EXT}, // PF_R16_SNORM - {GL_RG, GL_UNSIGNED_SHORT, GL_RG16_SNORM_EXT}, // PF_RG16_SNORM - {GL_RGB, GL_UNSIGNED_SHORT, GL_RGB16_SNORM_EXT}, // PF_RGB16_SNORM - {GL_RGBA, GL_UNSIGNED_SHORT, GL_RGBA16_SNORM_EXT}, // PF_RGBA16_SNORM - // the rest are compressed formats that are same - }; - - static GLPixelFormatDescription _pixelFormats[] = { - {GL_NONE}, // PF_UNKNOWN - {GL_LUMINANCE, GL_UNSIGNED_BYTE, GL_LUMINANCE}, // PF_L8 - {GL_NONE}, // PF_L16 - {GL_ALPHA, GL_UNSIGNED_BYTE, GL_ALPHA}, // PF_A8 - {GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, GL_LUMINANCE_ALPHA},// PF_BYTE_LA - {GL_RGB, GL_UNSIGNED_SHORT_5_6_5, GL_RGB}, // PF_R5G6B5 - {GL_NONE}, // PF_B5G6R5 - {GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, GL_RGBA}, // PF_A4R4G4B4, todo: reversed? - {GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, GL_RGBA}, // PF_A1R5G5B5, todo: reversed? -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - {GL_RGB, GL_UNSIGNED_BYTE, GL_RGB}, // PF_R8G8B8 - {GL_NONE}, // PF_B8G8R8 - {GL_NONE}, // PF_A8R8G8B8 - {GL_NONE}, // PF_A8B8G8R8 - {GL_BGRA_EXT, GL_UNSIGNED_BYTE, GL_BGRA_EXT}, // PF_B8G8R8A8 -#else - {GL_NONE}, // PF_R8G8B8 - {GL_RGB, GL_UNSIGNED_BYTE, GL_RGB}, // PF_B8G8R8 - {GL_BGRA_EXT, GL_UNSIGNED_BYTE, GL_BGRA_EXT}, // PF_A8R8G8B8 - {GL_RGBA, GL_UNSIGNED_BYTE, GL_RGBA}, // PF_A8B8G8R8 - {GL_NONE}, // PF_B8G8R8A8 -#endif - {GL_NONE}, // PF_A2R10G10B10 - {GL_RGBA_INTEGER, GL_UNSIGNED_INT_2_10_10_10_REV, GL_RGB10_A2UI}, // PF_A2B10G10R10 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT},// PF_DXT1 - {GL_NONE}, // PF_DXT2 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT},// PF_DXT3 - {GL_NONE}, // PF_DXT4 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT},// PF_DXT5 - {GL_RGB, GL_HALF_FLOAT_OES, GL_RGB}, // PF_FLOAT16_RGB - {GL_RGBA, GL_HALF_FLOAT_OES, GL_RGBA}, // PF_FLOAT16_RGBA - {GL_RGB, GL_FLOAT, GL_RGB}, // PF_FLOAT32_RGB - {GL_RGBA, GL_FLOAT, GL_RGBA}, // PF_FLOAT32_RGBA -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - {GL_NONE}, // PF_X8R8G8B8 - {GL_NONE}, // PF_X8B8G8R8 - {GL_RGBA, GL_UNSIGNED_BYTE, GL_RGBA}, // PF_R8G8B8A8 -#else - {GL_BGRA_EXT, GL_UNSIGNED_BYTE, GL_BGRA_EXT}, // PF_X8R8G8B8 - {GL_RGBA, GL_UNSIGNED_BYTE, GL_RGBA}, // PF_X8B8G8R8 - {GL_NONE}, // PF_R8G8B8A8 -#endif - {GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, GL_DEPTH_COMPONENT16}, // PF_DEPTH16 - {GL_NONE}, // PF_SHORT_RGBA - {GL_NONE}, // PF_R3G3B2 - {GL_RED, GL_HALF_FLOAT_OES, GL_R16F}, // PF_FLOAT16_R - {GL_RED, GL_FLOAT, GL_R32F}, // PF_FLOAT32_R - {GL_NONE}, // PF_SHORT_GR - {GL_RG, GL_HALF_FLOAT_OES, GL_RG16F}, // PF_FLOAT16_GR - {GL_RG, GL_FLOAT, GL_RG32F}, // PF_FLOAT32_GR - {GL_NONE}, // PF_SHORT_RGB - {GL_NONE, GL_NONE, GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG}, // PF_PVRTC_RGB2 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG},// PF_PVRTC_RGBA2 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG}, // PF_PVRTC_RGB4 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG},// PF_PVRTC_RGBA4 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG},// PF_PVRTC2_2BPP - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG},// PF_PVRTC2_4BPP - {GL_NONE}, // PF_R11G11B10_FLOAT - {GL_NONE}, // PF_R8_UINT - {GL_NONE}, // PF_R8G8_UINT - {GL_NONE}, // PF_R8G8B8_UINT - {GL_NONE}, // PF_R8G8B8A8_UINT - {GL_NONE}, // PF_R16_UINT - {GL_NONE}, // PF_R16G16_UINT - {GL_NONE}, // PF_R16G16B16_UINT - {GL_NONE}, // PF_R16G16B16A16_UINT - {GL_NONE}, // PF_R32_UINT - {GL_NONE}, // PF_R32G32_UINT - {GL_NONE}, // PF_R32G32B32_UINT - {GL_NONE}, // PF_R32G32B32A32_UINT - {GL_NONE}, // PF_R8_SINT - {GL_NONE}, // PF_R8G8_SINT - {GL_NONE}, // PF_R8G8B8_SINT - {GL_NONE}, // PF_R8G8B8A8_SINT - {GL_NONE}, // PF_R16_SINT - {GL_NONE}, // PF_R16G16_SINT - {GL_NONE}, // PF_R16G16B16_SINT - {GL_NONE}, // PF_R16G16B16A16_SINT - {GL_NONE}, // PF_R32_SINT - {GL_NONE}, // PF_R32G32_SINT - {GL_NONE}, // PF_R32G32B32_SINT - {GL_NONE}, // PF_R32G32B32A32_SINT - {GL_NONE}, // PF_R9G9B9E5_SHAREDEXP - {GL_NONE}, // PF_BC4_UNORM - {GL_NONE}, // PF_BC4_SNORM - {GL_NONE}, // PF_BC5_UNORM - {GL_NONE}, // PF_BC5_SNORM - {GL_NONE}, // PF_BC6H_UF16 - {GL_NONE}, // PF_BC6H_SF16 - {GL_NONE}, // PF_BC7_UNORM - {GL_RED_EXT, GL_UNSIGNED_BYTE, GL_RED_EXT}, // PF_R8 - {GL_RG_EXT, GL_UNSIGNED_BYTE, GL_RG_EXT}, // PF_RG8 - {GL_NONE}, // PF_R8_SNORM - {GL_NONE}, // PF_RG8_SNORM - {GL_NONE}, // PF_RGB8_SNORM - {GL_NONE}, // PF_RGBA8_SNORM - {GL_NONE}, // PF_R16_SNORM - {GL_NONE}, // PF_RG16_SNORM - {GL_NONE}, // PF_RGB16_SNORM - {GL_NONE}, // PF_RGBA16_SNORM - {GL_NONE, GL_NONE, GL_ETC1_RGB8_OES}, // PF_ETC1_RGB8 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGB8_ETC2}, // PF_ETC2_RGB8 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA8_ETC2_EAC}, // PF_ETC2_RGBA8 - {GL_NONE, GL_NONE, GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2},// PF_ETC2_RGB8A1 - {GL_NONE, GL_NONE, GL_ATC_RGB_AMD}, // PF_ATC_RGB - {GL_NONE, GL_NONE, GL_ATC_RGBA_EXPLICIT_ALPHA_AMD}, // PF_ATC_RGBA_EXPLICIT_ALPHA - {GL_NONE, GL_NONE, GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD}, // PF_ATC_RGBA_INTERPOLATED_ALPHA - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_4x4_KHR}, // PF_ASTC_RGBA_4X4_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_5x4_KHR}, // PF_ASTC_RGBA_5X4_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_5x5_KHR}, // PF_ASTC_RGBA_5X5_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_6x5_KHR}, // PF_ASTC_RGBA_6X5_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_6x6_KHR}, // PF_ASTC_RGBA_6X6_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_8x5_KHR}, // PF_ASTC_RGBA_8X5_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_8x6_KHR}, // PF_ASTC_RGBA_8X6_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_8x8_KHR}, // PF_ASTC_RGBA_8X8_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_10x5_KHR},// PF_ASTC_RGBA_10X5_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_10x6_KHR},// PF_ASTC_RGBA_10X6_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_10x8_KHR},// PF_ASTC_RGBA_10X8_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_10x10_KHR},// PF_ASTC_RGBA_10X10_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_12x10_KHR},// PF_ASTC_RGBA_12X10_LDR - {GL_NONE, GL_NONE, GL_COMPRESSED_RGBA_ASTC_12x12_KHR},// PF_ASTC_RGBA_12X12_LDR - {GL_NONE, GL_NONE, GL_NONE}, // PF_DEPTH32 - {GL_NONE, GL_NONE, GL_NONE}, // PF_DEPTH32F - {GL_NONE, GL_NONE, GL_NONE}, // PF_DEPTH24_STENCIL8 - }; - - void GLES2PixelUtil::useSizedFormats() - { - memcpy(_pixelFormats, _pixelFormatsSized, sizeof(_pixelFormatsSized)); -#if OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - // disable formats that require swizzling - _pixelFormats[PF_L8].internalFormat = GL_NONE; - _pixelFormats[PF_L16].internalFormat = GL_NONE; - _pixelFormats[PF_BYTE_LA].internalFormat = GL_NONE; -#endif - } - - //----------------------------------------------------------------------------- - GLenum GLES2PixelUtil::getGLOriginFormat(PixelFormat pf) - { - static_assert(sizeof(_pixelFormats)/sizeof(GLPixelFormatDescription) == PF_COUNT, "Did you add a new format?"); - return _pixelFormats[pf].format; - } - //----------------------------------------------------------------------------- - GLenum GLES2PixelUtil::getGLOriginDataType(PixelFormat pf) - { - return _pixelFormats[pf].type; - } - - //----------------------------------------------------------------------------- - GLenum GLES2PixelUtil::getGLInternalFormat(PixelFormat pf, bool hwGamma) - { - GLenum ret = _pixelFormats[pf].internalFormat; - - if(!hwGamma) - return ret; - - switch(ret) - { - case GL_RGB8: - return GL_SRGB8; - case GL_RGBA8: - return GL_SRGB8_ALPHA8; - case GL_COMPRESSED_RGBA_ASTC_4x4_KHR: - case GL_COMPRESSED_RGBA_ASTC_5x4_KHR: - case GL_COMPRESSED_RGBA_ASTC_5x5_KHR: - case GL_COMPRESSED_RGBA_ASTC_6x5_KHR: - case GL_COMPRESSED_RGBA_ASTC_6x6_KHR: - case GL_COMPRESSED_RGBA_ASTC_8x5_KHR: - case GL_COMPRESSED_RGBA_ASTC_8x6_KHR: - case GL_COMPRESSED_RGBA_ASTC_8x8_KHR: - case GL_COMPRESSED_RGBA_ASTC_10x5_KHR: - case GL_COMPRESSED_RGBA_ASTC_10x6_KHR: - case GL_COMPRESSED_RGBA_ASTC_10x8_KHR: - case GL_COMPRESSED_RGBA_ASTC_10x10_KHR: - case GL_COMPRESSED_RGBA_ASTC_12x10_KHR: - case GL_COMPRESSED_RGBA_ASTC_12x12_KHR: - return ret + 0x20; // ASTC SRGBA format offset - default: - return ret; - } - } - //----------------------------------------------------------------------------- - PixelFormat GLES2PixelUtil::getClosestOGREFormat(GLenum format) - { - switch(format) - { - case GL_DEPTH24_STENCIL8_OES: - case GL_DEPTH_COMPONENT24_OES: - case GL_DEPTH_COMPONENT32_OES: - case GL_DEPTH_COMPONENT16: - case GL_DEPTH_COMPONENT: - return PF_DEPTH16; - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR: - case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: - return PixelFormat(int(PF_ASTC_RGBA_4X4_LDR) + - (format - GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR)); - case GL_SRGB8: - case GL_RGB8: - case GL_RGB: - return PF_BYTE_RGB; - case GL_SRGB8_ALPHA8: - case GL_RGBA8: - case GL_RGBA: // prefer native endian byte format - return PF_BYTE_RGBA; - }; - - for(int pf = 0; pf < PF_COUNT; pf++) { - if(_pixelFormats[pf].internalFormat == format) { - return (PixelFormat)pf; - } - } - - LogManager::getSingleton().stream() << "Unhandled Pixel format: 0x" << std::hex << format; - return PF_BYTE_RGBA; - } -} diff --git a/RenderSystems/GLES2/src/OgreGLES2Plugin.cpp b/RenderSystems/GLES2/src/OgreGLES2Plugin.cpp deleted file mode 100644 index 84b742b1842..00000000000 --- a/RenderSystems/GLES2/src/OgreGLES2Plugin.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLES2Plugin.h" -#include "OgreRoot.h" -#include "OgreGLES2RenderSystem.h" - -namespace Ogre { - static const String sPluginName = "OpenGL ES 2.0 RenderSystem"; - - GLES2Plugin::GLES2Plugin() - : mRenderSystem(0) - { - } - - const String& GLES2Plugin::getName() const - { - return sPluginName; - } - - void GLES2Plugin::install() - { - mRenderSystem = OGRE_NEW GLES2RenderSystem(); - - Root::getSingleton().addRenderSystem(mRenderSystem); - } - - void GLES2Plugin::initialise() - { - // nothing to do - } - - void GLES2Plugin::shutdown() - { - // nothing to do - } - - void GLES2Plugin::uninstall() - { - OGRE_DELETE mRenderSystem; - mRenderSystem = 0; - } -} diff --git a/RenderSystems/GLES2/src/OgreGLES2RenderSystem.cpp b/RenderSystems/GLES2/src/OgreGLES2RenderSystem.cpp deleted file mode 100644 index 73dbf2b11c6..00000000000 --- a/RenderSystems/GLES2/src/OgreGLES2RenderSystem.cpp +++ /dev/null @@ -1,1823 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#define NOMINMAX -#include "OgreGLES2RenderSystem.h" -#include "OgreGLES2TextureManager.h" -#include "OgreGLDepthBufferCommon.h" -#include "OgreGLES2HardwarePixelBuffer.h" -#include "OgreGLES2HardwareBufferManager.h" -#include "OgreGLES2HardwareBuffer.h" -#include "OgreGpuProgramManager.h" -#include "OgreGLUtil.h" -#include "OgreGLES2FBORenderTexture.h" -#include "OgreGLES2HardwareOcclusionQuery.h" -#include "OgreGLVertexArrayObject.h" -#include "OgreRoot.h" -#include "OgreViewport.h" -#include "OgreLogManager.h" -#if !OGRE_NO_GLES2_CG_SUPPORT -#include "OgreGLSLESCgProgramFactory.h" -#endif -#include "OgreGLSLESLinkProgram.h" -#include "OgreGLSLESProgramManager.h" -#include "OgreGLSLESProgramPipeline.h" -#include "OgreGLES2StateCacheManager.h" -#include "OgreRenderWindow.h" -#include "OgreGLES2PixelFormat.h" -#include "OgreGLES2FBOMultiRenderTarget.h" - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS -#include "OgreEAGLES2Context.h" -#endif - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN -# include "OgreGLES2ManagedResourceManager.h" -Ogre::GLES2ManagedResourceManager* Ogre::GLES2RenderSystem::mResourceManager = NULL; -#endif - -#ifndef GL_PACK_ROW_LENGTH_NV -#define GL_PACK_ROW_LENGTH_NV 0x0D02 -#endif - -using namespace std; - -static void gl2ext_to_gl3core() { - glUnmapBufferOES = glUnmapBuffer; - glRenderbufferStorageMultisampleAPPLE = glRenderbufferStorageMultisample; - - glGenQueriesEXT = glGenQueries; - glDeleteQueriesEXT = glDeleteQueries; - glBeginQueryEXT = glBeginQuery; - glEndQueryEXT = glEndQuery; - glGetQueryObjectuivEXT = glGetQueryObjectuiv; - - glMapBufferRangeEXT = glMapBufferRange; - glFlushMappedBufferRangeEXT = glFlushMappedBufferRange; - - glTexImage3DOES = (PFNGLTEXIMAGE3DOESPROC)glTexImage3D; - glCompressedTexImage3DOES = glCompressedTexImage3D; - glTexSubImage3DOES = glTexSubImage3D; - glCompressedTexSubImage3DOES = glCompressedTexSubImage3D; - - glFenceSyncAPPLE = glFenceSync; - glClientWaitSyncAPPLE = glClientWaitSync; - glDeleteSyncAPPLE = glDeleteSync; - - glProgramBinaryOES = glProgramBinary; - glGetProgramBinaryOES = glGetProgramBinary; - - glDrawElementsInstancedEXT = glDrawElementsInstanced; - glDrawArraysInstancedEXT = glDrawArraysInstanced; - glVertexAttribDivisorEXT = glVertexAttribDivisor; - glBindVertexArrayOES = glBindVertexArray; - glGenVertexArraysOES = glGenVertexArrays; - glDeleteVertexArraysOES = glDeleteVertexArrays; -} - -namespace Ogre { - -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS && OGRE_PLATFORM != OGRE_PLATFORM_ANDROID - static GLNativeSupport* glsupport; - static GLESWglProc get_proc(const char* proc) { - return (GLESWglProc)glsupport->getProcAddress(proc); - } -#endif - - static GLint getCombinedMinMipFilter(FilterOptions min, FilterOptions mip) - { - switch(min) - { - case FO_ANISOTROPIC: - case FO_LINEAR: - switch (mip) - { - case FO_ANISOTROPIC: - case FO_LINEAR: - // linear min, linear mip - return GL_LINEAR_MIPMAP_LINEAR; - case FO_POINT: - // linear min, point mip - return GL_LINEAR_MIPMAP_NEAREST; - case FO_NONE: - // linear min, no mip - return GL_LINEAR; - } - break; - case FO_POINT: - case FO_NONE: - switch (mip) - { - case FO_ANISOTROPIC: - case FO_LINEAR: - // nearest min, linear mip - return GL_NEAREST_MIPMAP_LINEAR; - case FO_POINT: - // nearest min, point mip - return GL_NEAREST_MIPMAP_NEAREST; - case FO_NONE: - // nearest min, no mip - return GL_NEAREST; - } - break; - } - - // should never get here - return 0; - } - - GLES2RenderSystem::GLES2RenderSystem() - : mStateCacheManager(0), - mProgramManager(0), - mGLSLESProgramFactory(0), -#if !OGRE_NO_GLES2_CG_SUPPORT - mGLSLESCgProgramFactory(0), -#endif - mHardwareBufferManager(0), - mCurTexMipCount(0) - { - size_t i; - - LogManager::getSingleton().logMessage(getName() + " created."); - - mRenderAttribsBound.reserve(100); - mRenderInstanceAttribsBound.reserve(100); - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - mResourceManager = OGRE_NEW GLES2ManagedResourceManager(); -#endif - - mGLSupport = getGLSupport(GLNativeSupport::CONTEXT_ES); - -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS && OGRE_PLATFORM != OGRE_PLATFORM_ANDROID && OGRE_PLATFORM != OGRE_PLATFORM_WIN32 - glsupport = mGLSupport; -#endif - - initConfigOptions(); - - for (i = 0; i < OGRE_MAX_TEXTURE_LAYERS; i++) - { - // Dummy value - mTextureTypes[i] = 0; - } - - mActiveRenderTarget = 0; - mCurrentContext = 0; - mMainContext = 0; - mGLInitialised = false; - mMinFilter = FO_LINEAR; - mMipFilter = FO_POINT; - mPolygonMode = GL_FILL; - mCurrentVertexProgram = 0; - mCurrentFragmentProgram = 0; - mRTTManager = NULL; - } - - GLES2RenderSystem::~GLES2RenderSystem() - { - shutdown(); - - OGRE_DELETE mGLSupport; - mGLSupport = 0; - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - if (mResourceManager != NULL) - { - OGRE_DELETE mResourceManager; - mResourceManager = NULL; - } -#endif - } - - const String& GLES2RenderSystem::getName(void) const - { - static String strName("OpenGL ES 2.x Rendering Subsystem"); - return strName; - } - - void GLES2RenderSystem::_initialise() - { - RenderSystem::_initialise(); - - mGLSupport->start(); - // Create the texture manager - mTextureManager = OGRE_NEW GLES2TextureManager(this); - } - - RenderSystemCapabilities* GLES2RenderSystem::createRenderSystemCapabilities() const - { - RenderSystemCapabilities* rsc = OGRE_NEW RenderSystemCapabilities(); - - rsc->setCategoryRelevant(CAPS_CATEGORY_GL, true); - rsc->setDriverVersion(mDriverVersion); - - const char* deviceName = (const char*)glGetString(GL_RENDERER); - if (deviceName) - { - rsc->setDeviceName(deviceName); - } - - rsc->setRenderSystemName(getName()); - rsc->setVendor(mVendor); - - // Multitexturing support and set number of texture units - GLint units; - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &units)); - rsc->setNumTextureUnits(std::min(OGRE_MAX_TEXTURE_LAYERS, units)); - - glGetIntegerv( GL_MAX_VERTEX_ATTRIBS , &units); - rsc->setNumVertexAttributes(units); - - // Check for hardware stencil support and set bit depth - GLint stencil; - - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_STENCIL_BITS, &stencil)); - - if(stencil) - { - rsc->setCapability(RSC_HWSTENCIL); - rsc->setCapability(RSC_TWO_SIDED_STENCIL); - } - - if(hasMinGLVersion(3, 0) || - (checkExtension("GL_EXT_sRGB") && checkExtension("GL_NV_sRGB_formats"))) - rsc->setCapability(RSC_HW_GAMMA); - - // Vertex Buffer Objects are always supported by OpenGL ES - if(hasMinGLVersion(3, 0) || checkExtension("GL_OES_element_index_uint")) - rsc->setCapability(RSC_32BIT_INDEX); - - // Check for hardware occlusion support - if(hasMinGLVersion(3, 0) || checkExtension("GL_EXT_occlusion_query_boolean")) - { - rsc->setCapability(RSC_HWOCCLUSION); - } - - // OpenGL ES - Check for these extensions too - // For 2.0, http://www.khronos.org/registry/gles/api/2.0/gl2ext.h - - if (checkExtension("GL_IMG_texture_compression_pvrtc") || - checkExtension("GL_EXT_texture_compression_dxt1") || - checkExtension("GL_EXT_texture_compression_s3tc") || - checkExtension("GL_OES_compressed_ETC1_RGB8_texture") || - checkExtension("GL_AMD_compressed_ATC_texture") || - checkExtension("WEBGL_compressed_texture_s3tc") || - checkExtension("WEBGL_compressed_texture_atc") || - checkExtension("WEBGL_compressed_texture_pvrtc") || - checkExtension("WEBGL_compressed_texture_etc1") || - checkExtension("WEBGL_compressed_texture_astc") || - checkExtension("GL_KHR_texture_compression_astc_ldr")) - - { - rsc->setCapability(RSC_TEXTURE_COMPRESSION); - - if(checkExtension("GL_IMG_texture_compression_pvrtc") || - checkExtension("GL_IMG_texture_compression_pvrtc2") || - checkExtension("WEBGL_compressed_texture_pvrtc")) - rsc->setCapability(RSC_TEXTURE_COMPRESSION_PVRTC); - - if((checkExtension("GL_EXT_texture_compression_dxt1") && - checkExtension("GL_EXT_texture_compression_s3tc")) || - checkExtension("WEBGL_compressed_texture_s3tc")) - rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT); - - if(checkExtension("GL_OES_compressed_ETC1_RGB8_texture") || - checkExtension("WEBGL_compressed_texture_etc1")) - rsc->setCapability(RSC_TEXTURE_COMPRESSION_ETC1); - - if(hasMinGLVersion(3, 0)) - rsc->setCapability(RSC_TEXTURE_COMPRESSION_ETC2); - - if(checkExtension("GL_AMD_compressed_ATC_texture") || - checkExtension("WEBGL_compressed_texture_atc")) - rsc->setCapability(RSC_TEXTURE_COMPRESSION_ATC); - - if(checkExtension("WEBGL_compressed_texture_astc") || - checkExtension("GL_KHR_texture_compression_astc_ldr")) - rsc->setCapability(RSC_TEXTURE_COMPRESSION_ASTC); - } - - // Check for Anisotropy support - if (checkExtension("GL_EXT_texture_filter_anisotropic")) - { - GLfloat maxAnisotropy = 0; - OGRE_CHECK_GL_ERROR(glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maxAnisotropy)); - rsc->setMaxSupportedAnisotropy(maxAnisotropy); - rsc->setCapability(RSC_ANISOTROPY); - } - - rsc->setCapability(RSC_HWRENDER_TO_TEXTURE); - if (hasMinGLVersion(3, 0)) - { - // Probe number of draw buffers - // Only makes sense with FBO support, so probe here - GLint buffers; - glGetIntegerv(GL_MAX_DRAW_BUFFERS, &buffers); - rsc->setNumMultiRenderTargets( - std::min(buffers, (GLint)OGRE_MAX_MULTIPLE_RENDER_TARGETS)); - } - else - { - rsc->setNumMultiRenderTargets(1); - } - - // Stencil wrapping - rsc->setCapability(RSC_STENCIL_WRAP); - - // Point size - GLfloat psRange[2] = {0.0, 0.0}; - OGRE_CHECK_GL_ERROR(glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, psRange)); - rsc->setMaxPointSize(psRange[1]); - - // Point sprites - rsc->setCapability(RSC_POINT_SPRITES); - - // GLSL ES is always supported in GL ES 2 - rsc->addShaderProfile("glsles"); - if (getNativeShadingLanguageVersion() >= 320) - rsc->addShaderProfile("glsl320es"); - if (getNativeShadingLanguageVersion() >= 310) - rsc->addShaderProfile("glsl310es"); - if (getNativeShadingLanguageVersion() >= 300) - rsc->addShaderProfile("glsl300es"); - -#if !OGRE_NO_GLES2_CG_SUPPORT - rsc->addShaderProfile("cg"); - rsc->addShaderProfile("ps_2_0"); - rsc->addShaderProfile("vs_2_0"); -#endif - - // Vertex/Fragment Programs - rsc->setCapability(RSC_VERTEX_PROGRAM); - - // Separate shader objects - OGRE_IF_IOS_VERSION_IS_GREATER_THAN(5.0) - if(checkExtension("GL_EXT_separate_shader_objects")) - { - // this relaxes shader matching rules and requires slightly different GLSL declaration - // however our usage pattern does not benefit from this and driver support is quite poor - // so disable it for now (see below) - /*rsc->setCapability(RSC_SEPARATE_SHADER_OBJECTS); - rsc->setCapability(RSC_GLSL_SSO_REDECLARE);*/ - } - - // Mesa 11.2 does not behave according to spec and throws a "gl_Position redefined" - if(rsc->getDeviceName().find("Mesa") != String::npos) { - rsc->unsetCapability(RSC_GLSL_SSO_REDECLARE); - } - - GLfloat floatConstantCount = 0; - glGetFloatv(GL_MAX_VERTEX_UNIFORM_VECTORS, &floatConstantCount); - rsc->setVertexProgramConstantFloatCount((Ogre::ushort)floatConstantCount); - - // Fragment Program Properties - floatConstantCount = 0; - glGetFloatv(GL_MAX_FRAGMENT_UNIFORM_VECTORS, &floatConstantCount); - rsc->setFragmentProgramConstantFloatCount((Ogre::ushort)floatConstantCount); - - // Check for Float textures - if(hasMinGLVersion(3, 0) || checkExtension("GL_OES_texture_float") || checkExtension("GL_OES_texture_half_float")) - rsc->setCapability(RSC_TEXTURE_FLOAT); - - if(hasMinGLVersion(3, 0) || checkExtension("GL_OES_texture_3D")) - rsc->setCapability(RSC_TEXTURE_3D); - - if(hasMinGLVersion(3, 0)) - rsc->setCapability(RSC_TEXTURE_2D_ARRAY); - - // ES 3 always supports NPOT textures - if(hasMinGLVersion(3, 0) || checkExtension("GL_OES_texture_npot") || checkExtension("GL_ARB_texture_non_power_of_two")) - { - rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES); - rsc->setNonPOW2TexturesLimited(false); - } - else if(checkExtension("GL_APPLE_texture_2D_limited_npot")) - { - rsc->setNonPOW2TexturesLimited(true); - } - - // Alpha to coverage always 'supported' when MSAA is available - // although card may ignore it if it doesn't specifically support A2C - rsc->setCapability(RSC_ALPHA_TO_COVERAGE); - - // No point sprites, so no size - rsc->setMaxPointSize(0.f); - - if (hasMinGLVersion(3, 0) || - (checkExtension("GL_OES_vertex_array_object") && OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN)) - rsc->setCapability(RSC_VAO); - - if (hasMinGLVersion(3, 0) || checkExtension("GL_OES_get_program_binary")) - { - // http://www.khronos.org/registry/gles/extensions/OES/OES_get_program_binary.txt - GLint formats; - OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS_OES, &formats)); - - if(formats > 0) - rsc->setCapability(RSC_CAN_GET_COMPILED_SHADER_BUFFER); - } - - if(hasMinGLVersion(3, 0)) - rsc->setCapability(RSC_VERTEX_FORMAT_INT_10_10_10_2); - - if (hasMinGLVersion(3, 0) || checkExtension("GL_EXT_instanced_arrays")) - { - rsc->setCapability(RSC_VERTEX_BUFFER_INSTANCE_DATA); - } - else if(checkExtension("GL_ANGLE_instanced_arrays")) - { - rsc->setCapability(RSC_VERTEX_BUFFER_INSTANCE_DATA); - glDrawElementsInstancedEXT = glDrawElementsInstancedANGLE; - glDrawArraysInstancedEXT = glDrawArraysInstancedANGLE; - glVertexAttribDivisorEXT = glVertexAttribDivisorANGLE; - } - - if (checkExtension("GL_EXT_debug_marker") && - checkExtension("GL_EXT_debug_label")) - { - OGRE_IF_IOS_VERSION_IS_GREATER_THAN(5.0) - rsc->setCapability(RSC_DEBUG); - } - - if ((hasMinGLVersion(3, 0) && OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN) || - checkExtension("GL_EXT_map_buffer_range")) - { - rsc->setCapability(RSC_MAPBUFFER); - } - - if(hasMinGLVersion(3, 0)) - { - // Check if render to vertex buffer (transform feedback in OpenGL) - rsc->setCapability(RSC_HWRENDER_TO_VERTEX_BUFFER); - - rsc->setCapability(RSC_PRIMITIVE_RESTART); - } - - GLfloat lineWidth[2] = {1, 1}; - glGetFloatv(GL_ALIASED_LINE_WIDTH_RANGE, lineWidth); - if(lineWidth[1] != 1 && lineWidth[1] != lineWidth[0]) - rsc->setCapability(RSC_WIDE_LINES); - - return rsc; - } - - void GLES2RenderSystem::initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary) - { - if(caps->getNumVertexAttributes() < 16) - GLSLProgramCommon::useTightAttributeLayout(); - - mProgramManager = new GLSLESProgramManager(); - - mGLSLESProgramFactory = OGRE_NEW GLSLESProgramFactory(); - HighLevelGpuProgramManager::getSingleton().addFactory(mGLSLESProgramFactory); - -#if !OGRE_NO_GLES2_CG_SUPPORT - mGLSLESCgProgramFactory = OGRE_NEW GLSLESCgProgramFactory(); - HighLevelGpuProgramManager::getSingleton().addFactory(mGLSLESCgProgramFactory); -#endif - - // Use VBO's by default - mHardwareBufferManager = OGRE_NEW GLES2HardwareBufferManager(); - - // Create FBO manager - mRTTManager = new GLES2FBOManager(); - - mGLInitialised = true; - } - - void GLES2RenderSystem::shutdown(void) - { - - // Deleting the GLSL program factory - if (mGLSLESProgramFactory) - { - // Remove from manager safely - if (HighLevelGpuProgramManager::getSingletonPtr()) - HighLevelGpuProgramManager::getSingleton().removeFactory(mGLSLESProgramFactory); - OGRE_DELETE mGLSLESProgramFactory; - mGLSLESProgramFactory = 0; - } - -#if !OGRE_NO_GLES2_CG_SUPPORT - // Deleting the GLSL program factory - if (mGLSLESCgProgramFactory) - { - // Remove from manager safely - if (HighLevelGpuProgramManager::getSingletonPtr()) - HighLevelGpuProgramManager::getSingleton().removeFactory(mGLSLESCgProgramFactory); - OGRE_DELETE mGLSLESCgProgramFactory; - mGLSLESCgProgramFactory = 0; - } -#endif - // Delete extra threads contexts - for (auto pCurContext : mBackgroundContextList) - { - pCurContext->releaseContext(); - OGRE_DELETE pCurContext; - } - mBackgroundContextList.clear(); - - // Deleting the GPU program manager and hardware buffer manager. Has to be done before the mGLSupport->stop(). - delete mProgramManager; - mProgramManager = NULL; - - OGRE_DELETE mHardwareBufferManager; - mHardwareBufferManager = 0; - - delete mRTTManager; - mRTTManager = 0; - - OGRE_DELETE mTextureManager; - mTextureManager = 0; - - RenderSystem::shutdown(); - - mGLSupport->stop(); - - mGLInitialised = 0; - } - - RenderWindow* GLES2RenderSystem::_createRenderWindow(const String &name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams) - { - RenderSystem::_createRenderWindow(name, width, height, fullScreen, miscParams); - - // Create the window - RenderWindow* win = mGLSupport->newWindow(name, width, height, fullScreen, miscParams); - attachRenderTarget((Ogre::RenderTarget&) *win); - - if (!mGLInitialised) - { - initialiseContext(win); - - // Get the shader language version - const char* shadingLangVersion = (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION); - LogManager::getSingleton().logMessage("Shading language version: " + String(shadingLangVersion)); - StringVector tokens = StringUtil::split(shadingLangVersion, ". "); - size_t i = 0; - - // iOS reports the GLSL version with a whole bunch of non-digit characters so we have to find where the version starts. - for(; i < tokens.size(); i++) - { - if (isdigit(*tokens[i].c_str())) - break; - } - mNativeShadingLanguageVersion = (StringConverter::parseUnsignedInt(tokens[i]) * 100) + StringConverter::parseUnsignedInt(tokens[i+1]); - if (mNativeShadingLanguageVersion < 100) // Emscripten + MS IE/Edge reports an experimental WebGL version (e.g. 0.96) which causes a compile error - mNativeShadingLanguageVersion = 100; - - // Initialise GL after the first window has been created - // TODO: fire this from emulation options, and don't duplicate Real and Current capabilities - mRealCapabilities = createRenderSystemCapabilities(); - - // use real capabilities if custom capabilities are not available - if (!mUseCustomCapabilities) - mCurrentCapabilities = mRealCapabilities; - - fireEvent("RenderSystemCapabilitiesCreated"); - - initialiseFromRenderSystemCapabilities(mCurrentCapabilities, (RenderTarget *) win); - - // Initialise the main context - _oneTimeContextInitialization(); - if (mCurrentContext) - mCurrentContext->setInitialized(); - } - - if( win->getDepthBufferPool() != DepthBuffer::POOL_NO_DEPTH ) - { - // Unlike D3D9, OGL doesn't allow sharing the main depth buffer, so keep them separate. - GLContext *windowContext = dynamic_cast(win)->getContext(); - auto depthBuffer = - new GLDepthBufferCommon(DepthBuffer::POOL_DEFAULT, this, windowContext, 0, 0, win, true); - - mDepthBufferPool[depthBuffer->getPoolId()].push_back( depthBuffer ); - - win->attachDepthBuffer( depthBuffer ); - } - - return win; - } - - //--------------------------------------------------------------------- - DepthBuffer* GLES2RenderSystem::_createDepthBufferFor( RenderTarget *renderTarget ) - { - if( auto fbo = dynamic_cast(renderTarget)->getFBO() ) - { - // Find best depth & stencil format suited for the RT's format - GLuint depthFormat, stencilFormat; - mRTTManager->getBestDepthStencil(fbo->getFormat(), &depthFormat, &stencilFormat); - - GLES2RenderBuffer *depthBuffer = OGRE_NEW GLES2RenderBuffer( depthFormat, fbo->getWidth(), - fbo->getHeight(), fbo->getFSAA() ); - - GLES2RenderBuffer *stencilBuffer = NULL; - if (depthFormat == GL_DEPTH32F_STENCIL8 || depthFormat == GL_DEPTH24_STENCIL8_OES) - { - // If we have a packed format, the stencilBuffer is the same as the depthBuffer - stencilBuffer = depthBuffer; - } - else if(stencilFormat) - { - stencilBuffer = new GLES2RenderBuffer( stencilFormat, fbo->getWidth(), - fbo->getHeight(), fbo->getFSAA() ); - } - - return new GLDepthBufferCommon(0, this, mCurrentContext, depthBuffer, stencilBuffer, - renderTarget, false); - } - - return NULL; - } - - MultiRenderTarget* GLES2RenderSystem::createMultiRenderTarget(const String & name) - { - MultiRenderTarget* retval = - new GLES2FBOMultiRenderTarget(static_cast(mRTTManager), name); - attachRenderTarget(*retval); - return retval; - } - - void GLES2RenderSystem::destroyRenderWindow(const String& name) - { - // Find it to remove from list. - RenderTarget* pWin = detachRenderTarget(name); - OgreAssert(pWin, "unknown RenderWindow name"); - - _destroyDepthBuffer(pWin); - OGRE_DELETE pWin; - } - - void GLES2RenderSystem::_destroyDepthBuffer(RenderTarget* pWin) - { - GLContext *windowContext = dynamic_cast(pWin)->getContext(); - - // 1 Window <-> 1 Context, should be always true - assert( windowContext ); - - bool bFound = false; - // Find the depth buffer from this window and remove it. - DepthBufferMap::iterator itMap = mDepthBufferPool.begin(); - DepthBufferMap::iterator enMap = mDepthBufferPool.end(); - - while( itMap != enMap && !bFound ) - { - DepthBufferVec::iterator itor = itMap->second.begin(); - DepthBufferVec::iterator end = itMap->second.end(); - - while( itor != end ) - { - // A DepthBuffer with no depth & stencil pointers is a dummy one, - // look for the one that matches the same GL context - auto depthBuffer = static_cast(*itor); - GLContext *glContext = depthBuffer->getGLContext(); - - if( glContext == windowContext && - (depthBuffer->getDepthBuffer() || depthBuffer->getStencilBuffer()) ) - { - bFound = true; - - delete *itor; - itMap->second.erase( itor ); - break; - } - ++itor; - } - - ++itMap; - } - } - - void GLES2RenderSystem::_setTexture(size_t stage, bool enabled, const TexturePtr &texPtr) - { - mStateCacheManager->activateGLTextureUnit(stage); - if (enabled) - { - GLES2TexturePtr tex = static_pointer_cast(texPtr); - - mCurTexMipCount = 0; - - // Note used - tex->touch(); - mTextureTypes[stage] = tex->getGLES2TextureTarget(); - mCurTexMipCount = tex->getNumMipmaps(); - - mStateCacheManager->bindGLTexture(mTextureTypes[stage], tex->getGLID()); - } - else - { - // Bind zero texture - mStateCacheManager->bindGLTexture(GL_TEXTURE_2D, 0); - } - } - - static int getTextureAddressingMode(TextureAddressingMode tam, bool hasBorderClamp = true) - { - switch (tam) - { - case TAM_BORDER: - if (hasBorderClamp) - return GL_CLAMP_TO_BORDER_EXT; - OGRE_FALLTHROUGH; - case TAM_CLAMP: - return GL_CLAMP_TO_EDGE; - case TAM_MIRROR: - return GL_MIRRORED_REPEAT; - case TAM_WRAP: - default: - return GL_REPEAT; - } - } - - void GLES2RenderSystem::_setSampler(size_t unit, Sampler& sampler) - { - mStateCacheManager->activateGLTextureUnit(unit); - - GLenum target = mTextureTypes[unit]; - - const Sampler::UVWAddressingMode& uvw = sampler.getAddressingMode(); - - bool hasBorderClamp = hasMinGLVersion(3, 2) || checkExtension("GL_EXT_texture_border_clamp") || - checkExtension("GL_OES_texture_border_clamp"); - - mStateCacheManager->setTexParameteri(target, GL_TEXTURE_WRAP_S, getTextureAddressingMode(uvw.u, hasBorderClamp)); - mStateCacheManager->setTexParameteri(target, GL_TEXTURE_WRAP_T, getTextureAddressingMode(uvw.v, hasBorderClamp)); - if(getCapabilities()->hasCapability(RSC_TEXTURE_3D)) - mStateCacheManager->setTexParameteri(target, GL_TEXTURE_WRAP_R, getTextureAddressingMode(uvw.w, hasBorderClamp)); - - if ((uvw.u == TAM_BORDER || uvw.v == TAM_BORDER || uvw.w == TAM_BORDER) && hasBorderClamp) - OGRE_CHECK_GL_ERROR(glTexParameterfv( target, GL_TEXTURE_BORDER_COLOR_EXT, sampler.getBorderColour().ptr())); - - // only via shader.. - // OGRE_CHECK_GL_ERROR(glTexParameterf(target, GL_TEXTURE_LOD_BIAS, sampler.getTextureMipmapBias())); - - if (mCurrentCapabilities->hasCapability(RSC_ANISOTROPY)) - mStateCacheManager->setTexParameteri( - target, GL_TEXTURE_MAX_ANISOTROPY_EXT, - std::min(getCapabilities()->getMaxSupportedAnisotropy(), sampler.getAnisotropy())); - - if(hasMinGLVersion(3, 0)) - { - mStateCacheManager->setTexParameteri(target, GL_TEXTURE_COMPARE_MODE, - sampler.getCompareEnabled() ? GL_COMPARE_REF_TO_TEXTURE - : GL_NONE); - if(sampler.getCompareEnabled()) - mStateCacheManager->setTexParameteri(target, GL_TEXTURE_COMPARE_FUNC, - convertCompareFunction(sampler.getCompareFunction())); - } - - // Combine with existing mip filter - mStateCacheManager->setTexParameteri( - target, GL_TEXTURE_MIN_FILTER, - getCombinedMinMipFilter(sampler.getFiltering(FT_MIN), sampler.getFiltering(FT_MIP))); - - switch (sampler.getFiltering(FT_MAG)) - { - case FO_ANISOTROPIC: // GL treats linear and aniso the same - case FO_LINEAR: - mStateCacheManager->setTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - break; - case FO_POINT: - case FO_NONE: - mStateCacheManager->setTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - break; - } - } - - void GLES2RenderSystem::_setLineWidth(float width) - { - OGRE_CHECK_GL_ERROR(glLineWidth(width)); - } - - GLenum GLES2RenderSystem::getBlendMode(SceneBlendFactor ogreBlend) const - { - switch (ogreBlend) - { - case SBF_ONE: - return GL_ONE; - case SBF_ZERO: - return GL_ZERO; - case SBF_DEST_COLOUR: - return GL_DST_COLOR; - case SBF_SOURCE_COLOUR: - return GL_SRC_COLOR; - case SBF_ONE_MINUS_DEST_COLOUR: - return GL_ONE_MINUS_DST_COLOR; - case SBF_ONE_MINUS_SOURCE_COLOUR: - return GL_ONE_MINUS_SRC_COLOR; - case SBF_DEST_ALPHA: - return GL_DST_ALPHA; - case SBF_SOURCE_ALPHA: - return GL_SRC_ALPHA; - case SBF_ONE_MINUS_DEST_ALPHA: - return GL_ONE_MINUS_DST_ALPHA; - case SBF_ONE_MINUS_SOURCE_ALPHA: - return GL_ONE_MINUS_SRC_ALPHA; - }; - - // To keep compiler happy - return GL_ONE; - } - - void GLES2RenderSystem::_setAlphaRejectSettings(CompareFunction func, unsigned char value, bool alphaToCoverage) - { - if (getCapabilities()->hasCapability(RSC_ALPHA_TO_COVERAGE)) - { - if ((func != CMPF_ALWAYS_PASS) && alphaToCoverage) - mStateCacheManager->setEnabled(GL_SAMPLE_ALPHA_TO_COVERAGE); - else - mStateCacheManager->setDisabled(GL_SAMPLE_ALPHA_TO_COVERAGE); - } - } - - void GLES2RenderSystem::_setViewport(Viewport *vp) - { - // Check if viewport is different - if (!vp) - { - mActiveViewport = NULL; - _setRenderTarget(NULL); - } - else if (vp != mActiveViewport || vp->_isUpdated()) - { - RenderTarget* target; - - target = vp->getTarget(); - _setRenderTarget(target); - mActiveViewport = vp; - - // Calculate the "lower-left" corner of the viewport - Rect vpRect = vp->getActualDimensions(); - if (!target->requiresTextureFlipping()) - { - // Convert "upper-left" corner to "lower-left" - std::swap(vpRect.top, vpRect.bottom); - vpRect.top = target->getHeight() - vpRect.top; - vpRect.bottom = target->getHeight() - vpRect.bottom; - } - - mStateCacheManager->setViewport(vpRect); - - vp->_clearUpdatedFlag(); - } -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - else - { - // On iOS RenderWindow is FBO based, renders to multisampled FBO and then resolves - // to non-multisampled FBO, therefore we need to restore FBO binding even when - // rendering to the same viewport. - RenderTarget* target = vp->getTarget(); - mRTTManager->bind(target); - } -#endif - } - - void GLES2RenderSystem::_endFrame(void) - { - // unbind GPU programs at end of frame - // this is mostly to avoid holding bound programs that might get deleted - // outside via the resource manager - unbindGpuProgram(GPT_VERTEX_PROGRAM); - unbindGpuProgram(GPT_FRAGMENT_PROGRAM); - } - - void GLES2RenderSystem::_setCullingMode(CullingMode mode) - { - mCullingMode = mode; - // NB: Because two-sided stencil API dependence of the front face, we must - // use the same 'winding' for the front face everywhere. As the OGRE default - // culling mode is clockwise, we also treat anticlockwise winding as front - // face for consistently. On the assumption that, we can't change the front - // face by glFrontFace anywhere. - - GLenum cullMode; - bool flip = flipFrontFace(); - OGRE_CHECK_GL_ERROR(glFrontFace(flip ? GL_CW : GL_CCW)); - - switch (mode) - { - case CULL_NONE: - mStateCacheManager->setDisabled(GL_CULL_FACE); - return; - case CULL_CLOCKWISE: - cullMode = GL_BACK; - break; - case CULL_ANTICLOCKWISE: - cullMode = GL_FRONT; - break; - } - - mStateCacheManager->setEnabled(GL_CULL_FACE); - mStateCacheManager->setCullFace(cullMode); - } - - void GLES2RenderSystem::_setDepthBufferParams(bool depthTest, bool depthWrite, CompareFunction depthFunction) - { - if (depthTest) - { - mStateCacheManager->setClearDepth(1.0f); - mStateCacheManager->setEnabled(GL_DEPTH_TEST); - } - else - { - mStateCacheManager->setDisabled(GL_DEPTH_TEST); - } - mStateCacheManager->setDepthMask(depthWrite); - mStateCacheManager->setDepthFunc(convertCompareFunction(depthFunction)); - } - - void GLES2RenderSystem::_setDepthBias(float constantBias, float slopeScaleBias) - { - if (constantBias != 0 || slopeScaleBias != 0) - { - mStateCacheManager->setEnabled(GL_POLYGON_OFFSET_FILL); - OGRE_CHECK_GL_ERROR(glPolygonOffset(-slopeScaleBias, -constantBias)); - } - else - { - mStateCacheManager->setDisabled(GL_POLYGON_OFFSET_FILL); - } - } - static GLenum getBlendOp(SceneBlendOperation op, bool hasMinMax) - { - switch (op) - { - case SBO_ADD: - return GL_FUNC_ADD; - case SBO_SUBTRACT: - return GL_FUNC_SUBTRACT; - case SBO_REVERSE_SUBTRACT: - return GL_FUNC_REVERSE_SUBTRACT; - case SBO_MIN: - return hasMinMax ? GL_MIN : GL_FUNC_ADD; - case SBO_MAX: - return hasMinMax ? GL_MAX : GL_FUNC_ADD; - } - return GL_FUNC_ADD; - } - void GLES2RenderSystem::setColourBlendState(const ColourBlendState& state) - { - // record this - mCurrentBlend = state; - - if (state.blendingEnabled()) - { - mStateCacheManager->setEnabled(GL_BLEND); - mStateCacheManager->setBlendFunc( - getBlendMode(state.sourceFactor), getBlendMode(state.destFactor), - getBlendMode(state.sourceFactorAlpha), getBlendMode(state.destFactorAlpha)); - } - else - { - mStateCacheManager->setDisabled(GL_BLEND); - } - - bool hasMinMax = hasMinGLVersion(3, 0) || checkExtension("GL_EXT_blend_minmax"); - mStateCacheManager->setBlendEquation(getBlendOp(state.operation, hasMinMax), - getBlendOp(state.alphaOperation, hasMinMax)); - mStateCacheManager->setColourMask(state.writeR, state.writeG, state.writeB, state.writeA); - } - - //--------------------------------------------------------------------- - HardwareOcclusionQuery* GLES2RenderSystem::createHardwareOcclusionQuery(void) - { - if(hasMinGLVersion(3, 0) || checkExtension("GL_EXT_occlusion_query_boolean")) - { - GLES2HardwareOcclusionQuery* ret = new GLES2HardwareOcclusionQuery(); - mHwOcclusionQueries.push_back(ret); - return ret; - } - else - { - return NULL; - } - } - - void GLES2RenderSystem::_setPolygonMode(PolygonMode level) - { - switch(level) - { - case PM_POINTS: - mPolygonMode = GL_POINTS; - break; - case PM_WIREFRAME: - mPolygonMode = GL_LINE_STRIP; - break; - default: - case PM_SOLID: - mPolygonMode = GL_FILL; - break; - } - } - - void GLES2RenderSystem::setStencilState(const StencilState& state) - { - if (state.enabled) - { - mStateCacheManager->setEnabled(GL_STENCIL_TEST); - } - else - { - mStateCacheManager->setDisabled(GL_STENCIL_TEST); - return; - } - - bool flip = false; - - auto compareOp = convertCompareFunction(state.compareOp); - - if (state.twoSidedOperation) - { - // Back - OGRE_CHECK_GL_ERROR(glStencilMaskSeparate(GL_BACK, state.writeMask)); - OGRE_CHECK_GL_ERROR(glStencilFuncSeparate(GL_BACK, compareOp, state.referenceValue, state.compareMask)); - OGRE_CHECK_GL_ERROR(glStencilOpSeparate(GL_BACK, - convertStencilOp(state.stencilFailOp, !flip), - convertStencilOp(state.depthFailOp, !flip), - convertStencilOp(state.depthStencilPassOp, !flip))); - - // Front - OGRE_CHECK_GL_ERROR(glStencilMaskSeparate(GL_FRONT, state.writeMask)); - OGRE_CHECK_GL_ERROR(glStencilFuncSeparate(GL_FRONT, compareOp, state.referenceValue, state.compareMask)); - OGRE_CHECK_GL_ERROR(glStencilOpSeparate(GL_FRONT, - convertStencilOp(state.stencilFailOp, flip), - convertStencilOp(state.depthFailOp, flip), - convertStencilOp(state.depthStencilPassOp, flip))); - } - else - { - flip = false; - mStateCacheManager->setStencilMask(state.writeMask); - OGRE_CHECK_GL_ERROR(glStencilFunc(compareOp, state.referenceValue, state.compareMask)); - OGRE_CHECK_GL_ERROR(glStencilOp( - convertStencilOp(state.stencilFailOp, flip), - convertStencilOp(state.depthFailOp, flip), - convertStencilOp(state.depthStencilPassOp, flip))); - } - } - - void GLES2RenderSystem::_render(const RenderOperation& op) - { - // Call super class - RenderSystem::_render(op); - - void* pBufferData = 0; - - GLVertexArrayObject* vao = static_cast(op.vertexData->vertexDeclaration); - - bool updateVAO = true; - if(getCapabilities()->hasCapability(RSC_VAO)) - { - vao->bind(this); - updateVAO = vao->needsUpdate(op.vertexData->vertexBufferBinding, - op.vertexData->vertexStart); - } - - if (updateVAO) - vao->bindToGpu(this, op.vertexData->vertexBufferBinding, op.vertexData->vertexStart); - - // We treat index buffer binding inside VAO as volatile, always updating and never relying onto it, - // as one shared vertex buffer could be rendered with several index buffers, from submeshes and/or LODs - if (op.useIndexes) - mStateCacheManager->bindGLBuffer(GL_ELEMENT_ARRAY_BUFFER, - op.indexData->indexBuffer->_getImpl()->getGLBufferId()); - - - size_t numberOfInstances = 0; - if (getCapabilities()->hasCapability(RSC_VERTEX_BUFFER_INSTANCE_DATA)) - { - numberOfInstances = op.numberOfInstances; - } - - // Find the correct type to render - GLint primType; - switch (op.operationType) - { - case RenderOperation::OT_POINT_LIST: - primType = GL_POINTS; - break; - case RenderOperation::OT_LINE_LIST: - primType = GL_LINES; - break; - case RenderOperation::OT_LINE_STRIP: - primType = GL_LINE_STRIP; - break; - default: - case RenderOperation::OT_TRIANGLE_LIST: - primType = GL_TRIANGLES; - break; - case RenderOperation::OT_TRIANGLE_STRIP: - primType = GL_TRIANGLE_STRIP; - break; - case RenderOperation::OT_TRIANGLE_FAN: - primType = GL_TRIANGLE_FAN; - break; - } - - GLenum polyMode = mPolygonMode; - if (op.useIndexes) - { - pBufferData = VBO_BUFFER_OFFSET(op.indexData->indexStart * - op.indexData->indexBuffer->getIndexSize()); - - GLenum indexType = (op.indexData->indexBuffer->getType() == HardwareIndexBuffer::IT_16BIT) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT; - - do - { - if(numberOfInstances > 1) - { - OGRE_CHECK_GL_ERROR(glDrawElementsInstancedEXT((polyMode == GL_FILL) ? primType : polyMode, static_cast(op.indexData->indexCount), indexType, pBufferData, static_cast(numberOfInstances))); - } - else - { - OGRE_CHECK_GL_ERROR(glDrawElements((polyMode == GL_FILL) ? primType : polyMode, static_cast(op.indexData->indexCount), indexType, pBufferData)); - } - - } while (updatePassIterationRenderState()); - } - else - { - do - { - if(numberOfInstances > 1) - { - OGRE_CHECK_GL_ERROR(glDrawArraysInstancedEXT((polyMode == GL_FILL) ? primType : polyMode, 0, static_cast(op.vertexData->vertexCount), static_cast(numberOfInstances))); - } - else - { - OGRE_CHECK_GL_ERROR(glDrawArrays((polyMode == GL_FILL) ? primType : polyMode, 0, static_cast(op.vertexData->vertexCount))); - } - } while (updatePassIterationRenderState()); - } - - if(getCapabilities()->hasCapability(RSC_VAO)) - { - // Do not unbind the vertex array object if VAOs are supported - // VAOs > 0 are selected each time before usage - // VAO #0 WOULD BE explicitly selected by Ogre before usage - } - else // VAOs are not supported, we should clear scratch 'VAO #0' - { - // Unbind all attributes - for(std::vector::iterator ai = mRenderAttribsBound.begin(); ai != mRenderAttribsBound.end(); ++ai) - OGRE_CHECK_GL_ERROR(glDisableVertexAttribArray(*ai)); - - // Unbind any instance attributes - for (std::vector::iterator ai = mRenderInstanceAttribsBound.begin(); ai != mRenderInstanceAttribsBound.end(); ++ai) - OGRE_CHECK_GL_ERROR(glVertexAttribDivisorEXT(*ai, 0)); - } - mRenderAttribsBound.clear(); - mRenderInstanceAttribsBound.clear(); - } - - void GLES2RenderSystem::setScissorTest(bool enabled, const Rect& rect) - { - if (!enabled) - { - mStateCacheManager->setDisabled(GL_SCISSOR_TEST); - return; - } - - mStateCacheManager->setEnabled(GL_SCISSOR_TEST); - - // If request texture flipping, use "upper-left", otherwise use "lower-left" - bool flipping = mActiveRenderTarget->requiresTextureFlipping(); - - // GL measures from the bottom, not the top - long targetHeight = mActiveRenderTarget->getHeight(); - long top = flipping ? rect.top : targetHeight - rect.bottom; - // NB GL uses width / height rather than right / bottom - OGRE_CHECK_GL_ERROR(glScissor(rect.left, top, rect.width(), rect.height())); - } - - void GLES2RenderSystem::clearFrameBuffer(unsigned int buffers, - const ColourValue& colour, - float depth, unsigned short stencil) - { - uchar* colourWrite = mStateCacheManager->getColourMask(); - bool colourMask = !colourWrite[0] || !colourWrite[1] || - !colourWrite[2] || !colourWrite[3]; - GLuint stencilMask = mStateCacheManager->getStencilMask(); - GLbitfield flags = 0; - - if (buffers & FBT_COLOUR) - { - flags |= GL_COLOR_BUFFER_BIT; - // Enable buffer for writing if it isn't - if (colourMask) - { - mStateCacheManager->setColourMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); - } - mStateCacheManager->setClearColour(colour.r, colour.g, colour.b, colour.a); - } - if (buffers & FBT_DEPTH) - { - flags |= GL_DEPTH_BUFFER_BIT; - // Enable buffer for writing if it isn't - mStateCacheManager->setDepthMask(GL_TRUE); - mStateCacheManager->setClearDepth(depth); - } - if (buffers & FBT_STENCIL) - { - flags |= GL_STENCIL_BUFFER_BIT; - // Enable buffer for writing if it isn't - mStateCacheManager->setStencilMask(0xFFFFFFFF); - OGRE_CHECK_GL_ERROR(glClearStencil(stencil)); - } - - Rect vpRect = mActiveViewport->getActualDimensions(); - bool needScissorBox = - vpRect != Rect(0, 0, mActiveRenderTarget->getWidth(), mActiveRenderTarget->getHeight()); - if (needScissorBox) - { - // Should be enable scissor test due the clear region is - // relied on scissor box bounds. - setScissorTest(true, vpRect); - } - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - static_cast(mCurrentContext)->mDiscardBuffers = buffers; -#endif - - // Clear buffers - OGRE_CHECK_GL_ERROR(glClear(flags)); - - // Restore scissor test - if (needScissorBox) - { - setScissorTest(false); - } - - // Reset buffer write state - if (!mStateCacheManager->getDepthMask() && (buffers & FBT_DEPTH)) - { - mStateCacheManager->setDepthMask(GL_FALSE); - } - - if (colourMask && (buffers & FBT_COLOUR)) - { - mStateCacheManager->setColourMask(colourWrite[0], colourWrite[1], colourWrite[2], colourWrite[3]); - } - - if (buffers & FBT_STENCIL) - { - mStateCacheManager->setStencilMask(stencilMask); - } - } - - void GLES2RenderSystem::_switchContext(GLContext *context) - { - // Unbind GPU programs and rebind to new context later, because - // scene manager treat render system as ONE 'context' ONLY, and it - // cached the GPU programs using state. - if (mCurrentVertexProgram) - mProgramManager->setActiveShader(GPT_VERTEX_PROGRAM, NULL); - if (mCurrentFragmentProgram) - mProgramManager->setActiveShader(GPT_FRAGMENT_PROGRAM, NULL); - - // Disable textures - _disableTextureUnitsFrom(0); - - // It's ready for switching - if (mCurrentContext!=context) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - // EAGLContext::setCurrentContext does not flush automatically. everybody else does. - // see https://developer.apple.com/library/content/qa/qa1612/_index.html - glFlush(); -#endif - mCurrentContext->endCurrent(); - mCurrentContext = context; - } - mCurrentContext->setCurrent(); - - mStateCacheManager = mCurrentContext->createOrRetrieveStateCacheManager(); - _completeDeferredVaoFboDestruction(); - - // Check if the context has already done one-time initialisation - if (!mCurrentContext->getInitialized()) - { - _oneTimeContextInitialization(); - mCurrentContext->setInitialized(); - } - - // Rebind GPU programs to new context - if (mCurrentVertexProgram) - mProgramManager->setActiveShader(GPT_VERTEX_PROGRAM, mCurrentVertexProgram); - if (mCurrentFragmentProgram) - mProgramManager->setActiveShader(GPT_FRAGMENT_PROGRAM, mCurrentFragmentProgram); - - // Must reset depth/colour write mask to according with user desired, otherwise, - // clearFrameBuffer would be wrong because the value we are recorded may be - // difference with the really state stored in GL context. - uchar* colourWrite = mStateCacheManager->getColourMask(); - GLuint stencilMask = mStateCacheManager->getStencilMask(); - GLboolean depthMask = mStateCacheManager->getDepthMask(); - mStateCacheManager->setStencilMask(stencilMask); - mStateCacheManager->setColourMask(colourWrite[0], colourWrite[1], colourWrite[2], colourWrite[3]); - mStateCacheManager->setDepthMask(depthMask); - } - - void GLES2RenderSystem::_unregisterContext(GLContext *context) - { - if(HardwareBufferManager::getSingletonPtr()) - static_cast(HardwareBufferManager::getSingletonPtr())->notifyContextDestroyed(context); - - for(RenderTargetMap::iterator it = mRenderTargets.begin(); it!=mRenderTargets.end(); ++it) - { - if(auto target = dynamic_cast(it->second)) - { - if(auto fbo = target->getFBO()) - fbo->notifyContextDestroyed(context); - } - } - - if (mCurrentContext == context) - { - // Change the context to something else so that a valid context - // remains active. When this is the main context being unregistered, - // we set the main context to 0. - if (mCurrentContext != mMainContext) - { - _switchContext(mMainContext); - } - else - { - // No contexts remain - mCurrentContext->endCurrent(); - mCurrentContext = 0; - mMainContext = 0; - mStateCacheManager = 0; - } - } - } - - uint32 GLES2RenderSystem::_createVao() - { - uint32 vao = 0; - if(getCapabilities()->hasCapability(RSC_VAO)) - OGRE_CHECK_GL_ERROR(glGenVertexArraysOES(1, &vao)); - return vao; - } - - void GLES2RenderSystem::_destroyVao(GLContext* context, uint32 vao) - { - if(context != mCurrentContext) - context->_getVaoDeferredForDestruction().push_back(vao); - else - OGRE_CHECK_GL_ERROR(glDeleteVertexArraysOES(1, &vao)); - } - - void GLES2RenderSystem::_destroyFbo(GLContext* context, uint32 fbo) - { - if(context != mCurrentContext) - context->_getFboDeferredForDestruction().push_back(fbo); - else - OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &fbo)); - } - - void GLES2RenderSystem::_bindVao(GLContext* context, uint32 vao) - { - OgreAssert(context == mCurrentContext, "VAO used in wrong OpenGL context"); - _getStateCacheManager()->bindGLVertexArray(vao); - } - - void GLES2RenderSystem::_oneTimeContextInitialization() - { - mStateCacheManager->setDisabled(GL_DITHER); - - if(!getCapabilities()->hasCapability(RSC_PRIMITIVE_RESTART)) - return; - - // Enable primitive restarting with fixed indices depending upon the data type - // https://www.khronos.org/registry/webgl/specs/latest/2.0/#NO_PRIMITIVE_RESTART_FIXED_INDEX -#if OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN - OGRE_CHECK_GL_ERROR(glEnable(GL_PRIMITIVE_RESTART_FIXED_INDEX)); -#endif - } - - void GLES2RenderSystem::initialiseContext(RenderWindow* primary) - { - // Set main and current context - mMainContext = dynamic_cast(primary)->getContext(); - mCurrentContext = mMainContext; - - // Set primary context as active - if (mCurrentContext) - mCurrentContext->setCurrent(); - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS || OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - // ios: EAGL2Support redirects to glesw for get_proc. Overwriting it there would create an infinite loop - // android: eglGetProcAddress fails in some cases (e.g. Virtual Device), whereas dlsym always works. - if (glGetError == NULL && gleswInit()) -#else - if (gleswInit2(get_proc)) -#endif - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Could not initialize glesw", - "GLES2RenderSystem::initialiseContext"); - } - - // Setup GLSupport - initialiseExtensions(); - - mStateCacheManager = mCurrentContext->createOrRetrieveStateCacheManager(); - - if(hasMinGLVersion(3, 0)) { - gl2ext_to_gl3core(); - GLES2PixelUtil::useSizedFormats(); - } - - LogManager::getSingleton().logMessage("**************************************"); - LogManager::getSingleton().logMessage("*** OpenGL ES 2.x Renderer Started ***"); - LogManager::getSingleton().logMessage("**************************************"); - } - - void GLES2RenderSystem::_setRenderTarget(RenderTarget *target) - { - mActiveRenderTarget = target; - if (target && mRTTManager) - { - // Switch context if different from current one - GLContext *newContext = dynamic_cast(target)->getContext(); - if (newContext && mCurrentContext != newContext) - { - _switchContext(newContext); - } - - // Check the FBO's depth buffer status - auto depthBuffer = static_cast(target->getDepthBuffer()); - - if( target->getDepthBufferPool() != DepthBuffer::POOL_NO_DEPTH && - (!depthBuffer || depthBuffer->getGLContext() != mCurrentContext ) ) - { - // Depth is automatically managed and there is no depth buffer attached to this RT - // or the Current context doesn't match the one this Depth buffer was created with - setDepthBufferFor( target ); - } - - // Bind frame buffer object - mRTTManager->bind(target); - } - } - - GLint GLES2RenderSystem::convertCompareFunction(CompareFunction func) const - { - switch(func) - { - case CMPF_ALWAYS_FAIL: - return GL_NEVER; - case CMPF_ALWAYS_PASS: - return GL_ALWAYS; - case CMPF_LESS: - return GL_LESS; - case CMPF_LESS_EQUAL: - return GL_LEQUAL; - case CMPF_EQUAL: - return GL_EQUAL; - case CMPF_NOT_EQUAL: - return GL_NOTEQUAL; - case CMPF_GREATER_EQUAL: - return GL_GEQUAL; - case CMPF_GREATER: - return GL_GREATER; - }; - // To keep compiler happy - return GL_ALWAYS; - } - - GLint GLES2RenderSystem::convertStencilOp(StencilOperation op, bool invert) const - { - switch(op) - { - case SOP_KEEP: - return GL_KEEP; - case SOP_ZERO: - return GL_ZERO; - case SOP_REPLACE: - return GL_REPLACE; - case SOP_INCREMENT: - return invert ? GL_DECR : GL_INCR; - case SOP_DECREMENT: - return invert ? GL_INCR : GL_DECR; - case SOP_INCREMENT_WRAP: - return invert ? GL_DECR_WRAP : GL_INCR_WRAP; - case SOP_DECREMENT_WRAP: - return invert ? GL_INCR_WRAP : GL_DECR_WRAP; - case SOP_INVERT: - return GL_INVERT; - }; - // to keep compiler happy - return SOP_KEEP; - } - - //--------------------------------------------------------------------- - void GLES2RenderSystem::bindGpuProgram(GpuProgram* prg) - { - if (!prg) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Null program bound.", - "GLES2RenderSystem::bindGpuProgram"); - } - - GLSLESProgram* glprg = static_cast(prg); - - switch (glprg->getType()) - { - case GPT_VERTEX_PROGRAM: - mCurrentVertexProgram = glprg; - break; - - case GPT_FRAGMENT_PROGRAM: - mCurrentFragmentProgram = glprg; - break; - default: - break; - } - - // Bind the program - mProgramManager->setActiveShader(glprg->getType(), glprg); - - RenderSystem::bindGpuProgram(prg); - } - - void GLES2RenderSystem::unbindGpuProgram(GpuProgramType gptype) - { - mProgramManager->setActiveShader(gptype, NULL); - mActiveParameters[gptype].reset(); - - if (gptype == GPT_VERTEX_PROGRAM && mCurrentVertexProgram) - { - mCurrentVertexProgram = 0; - } - else if (gptype == GPT_FRAGMENT_PROGRAM && mCurrentFragmentProgram) - { - mCurrentFragmentProgram = 0; - } - RenderSystem::unbindGpuProgram(gptype); - } - - void GLES2RenderSystem::bindGpuProgramParameters(GpuProgramType gptype, const GpuProgramParametersPtr& params, uint16 mask) - { - mActiveParameters[gptype] = params; - - GLSLESProgramCommon* program = NULL; - - // Link can throw exceptions, ignore them at this point - try - { - program = mProgramManager->getActiveProgram(); - // Pass on parameters from params to program object uniforms - program->updateUniforms(params, mask, gptype); - } - catch (Exception& e) - { - return; - } - - if (mask & (uint16)GPV_GLOBAL) - { - params->_updateSharedParams(); - } - } - - //--------------------------------------------------------------------- - void GLES2RenderSystem::beginProfileEvent( const String &eventName ) - { - if(getCapabilities()->hasCapability(RSC_DEBUG)) - glPushGroupMarkerEXT(0, eventName.c_str()); - } - //--------------------------------------------------------------------- - void GLES2RenderSystem::endProfileEvent( void ) - { - if(getCapabilities()->hasCapability(RSC_DEBUG)) - glPopGroupMarkerEXT(); - } - //--------------------------------------------------------------------- - void GLES2RenderSystem::markProfileEvent( const String &eventName ) - { - if( eventName.empty() ) - return; - - if(getCapabilities()->hasCapability(RSC_DEBUG)) - glInsertEventMarkerEXT(0, eventName.c_str()); - } - //--------------------------------------------------------------------- -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - void GLES2RenderSystem::notifyOnContextLost() { - static_cast(HardwareBufferManager::getSingletonPtr())->notifyContextDestroyed(mCurrentContext); - GLES2RenderSystem::mResourceManager->notifyOnContextLost(); - } - - void GLES2RenderSystem::resetRenderer(RenderWindow* win) - { - LogManager::getSingleton().logMessage("********************************************"); - LogManager::getSingleton().logMessage("*** OpenGL ES 2.x Reset Renderer Started ***"); - LogManager::getSingleton().logMessage("********************************************"); - - initialiseContext(win); - - static_cast(mRTTManager)->_reload(); - - _destroyDepthBuffer(win); - - auto depthBuffer = - new GLDepthBufferCommon(DepthBuffer::POOL_DEFAULT, this, mMainContext, 0, 0, win, true); - - mDepthBufferPool[depthBuffer->getPoolId()].push_back( depthBuffer ); - win->attachDepthBuffer( depthBuffer ); - - GLES2RenderSystem::mResourceManager->notifyOnContextReset(); - - mStateCacheManager->clearCache(); - _setViewport(NULL); - _setRenderTarget(win); - } - - GLES2ManagedResourceManager* GLES2RenderSystem::getResourceManager() - { - return GLES2RenderSystem::mResourceManager; - } -#endif - - void GLES2RenderSystem::bindVertexElementToGpu( - const VertexElement& elem, const HardwareVertexBufferSharedPtr& vertexBuffer, - const size_t vertexStart) - { - VertexElementSemantic sem = elem.getSemantic(); - unsigned short elemIndex = elem.getIndex(); - - const GLES2HardwareBuffer* hwGlBuffer = vertexBuffer->_getImpl(); - - mStateCacheManager->bindGLBuffer(GL_ARRAY_BUFFER, hwGlBuffer->getGLBufferId()); - void* pBufferData = VBO_BUFFER_OFFSET(elem.getOffset() + vertexStart * vertexBuffer->getVertexSize()); - - unsigned short typeCount = VertexElement::getTypeCount(elem.getType()); - GLboolean normalised = GL_FALSE; - GLuint attrib = 0; - - attrib = (GLuint)GLSLProgramCommon::getFixedAttributeIndex(sem, elemIndex); - - if(getCapabilities()->hasCapability(RSC_VERTEX_BUFFER_INSTANCE_DATA)) - { - if (mCurrentVertexProgram) - { - if (vertexBuffer->isInstanceData()) - { - OGRE_CHECK_GL_ERROR(glVertexAttribDivisorEXT(attrib, static_cast(vertexBuffer->getInstanceDataStepRate()))); - mRenderInstanceAttribsBound.push_back(attrib); - } - } - } - - switch(elem.getType()) - { - case VET_UBYTE4_NORM: - case VET_SHORT2_NORM: - case VET_USHORT2_NORM: - case VET_SHORT4_NORM: - case VET_USHORT4_NORM: - normalised = GL_TRUE; - break; - default: - break; - }; - - OGRE_CHECK_GL_ERROR(glVertexAttribPointer(attrib, - typeCount, - GLES2HardwareBufferManager::getGLType(elem.getType()), - normalised, - static_cast(vertexBuffer->getVertexSize()), - pBufferData)); - - OGRE_CHECK_GL_ERROR(glEnableVertexAttribArray(attrib)); - mRenderAttribsBound.push_back(attrib); - } - - void GLES2RenderSystem::_copyContentsToMemory(Viewport* vp, const Box& src, const PixelBox& dst, - RenderWindow::FrameBuffer buffer) { - GLenum format = GLES2PixelUtil::getGLOriginFormat(dst.format); - GLenum type = GLES2PixelUtil::getGLOriginDataType(dst.format); - - if (dst.format != PF_BYTE_RGBA) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Unsupported format.", - "GLES2RenderSystem::_copyContentsToMemory" ); - } - - bool hasPackImage = hasMinGLVersion(3, 0) || checkExtension("GL_NV_pack_subimage"); - OgreAssert(dst.getWidth() == dst.rowPitch || hasPackImage, "GL_PACK_ROW_LENGTH not supported"); - - // Switch context if different from current one - _setViewport(vp); - - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 0)); - - if(dst.getWidth() != dst.rowPitch && hasPackImage) - glPixelStorei(GL_PACK_ROW_LENGTH_NV, dst.rowPitch); - - // Must change the packing to ensure no overruns! - glPixelStorei(GL_PACK_ALIGNMENT, 1); - - if(hasMinGLVersion(3, 0)) { - glReadBuffer((buffer == RenderWindow::FB_FRONT) ? GL_FRONT : GL_BACK); - } - - uint32_t height = vp->getTarget()->getHeight(); - - glReadPixels((GLint)src.left, (GLint)(height - src.bottom), - (GLsizei)dst.getWidth(), (GLsizei)dst.getHeight(), - format, type, dst.getTopLeftFrontPixelPtr()); - - // restore default alignment - glPixelStorei(GL_PACK_ALIGNMENT, 4); - glPixelStorei(GL_PACK_ROW_LENGTH_NV, 0); - - PixelUtil::bulkPixelVerticalFlip(dst); - } - - void GLES2RenderSystem::initialiseExtensions(void) - { - String tmpStr; -#if 1 - // Set version string - const GLubyte* pcVer = glGetString(GL_VERSION); - assert(pcVer && "Problems getting GL version string using glGetString"); - tmpStr = (const char*)pcVer; - - // format explained here: - // https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGetString.xml - size_t offset = sizeof("OpenGL ES ") - 1; - if(tmpStr.length() > offset) { - mDriverVersion.fromString(tmpStr.substr(offset, tmpStr.find(' ', offset))); - } -#else - // GLES3 way, but should work with ES2 as well, so disabled for now - glGetIntegerv(GL_MAJOR_VERSION, &mVersion.major); - glGetIntegerv(GL_MINOR_VERSION, &mVersion.minor); -#endif - - LogManager::getSingleton().logMessage("GL_VERSION = " + mDriverVersion.toString()); - - - // Get vendor - const GLubyte* pcVendor = glGetString(GL_VENDOR); - tmpStr = (const char*)pcVendor; - LogManager::getSingleton().logMessage("GL_VENDOR = " + tmpStr); - mVendor = RenderSystemCapabilities::vendorFromString(tmpStr.substr(0, tmpStr.find(' '))); - - // Get renderer - const GLubyte* pcRenderer = glGetString(GL_RENDERER); - tmpStr = (const char*)pcRenderer; - LogManager::getSingleton().logMessage("GL_RENDERER = " + tmpStr); - - // Set extension list - StringStream ext; - String str; - - const GLubyte* pcExt = glGetString(GL_EXTENSIONS); - OgreAssert(pcExt, "Problems getting GL extension string using glGetString"); - ext << pcExt; - - Log::Stream log = LogManager::getSingleton().stream(); - log << "GL_EXTENSIONS = "; - while (ext >> str) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - // emscripten gives us both prefixed (GL_) and unprefixed (EXT_) forms - // use prefixed form (GL_EXT) unless its a WebGL extension (WEBGL_) - if ((str.substr(0, 3) != "GL_" && str.substr(0, 6) != "WEBGL_") || str.substr(0, 9) == "GL_WEBGL_") - continue; -#endif - log << str << " "; - mExtensionList.insert(str); - } - } -} diff --git a/RenderSystems/GLES2/src/OgreGLES2RenderToVertexBuffer.cpp b/RenderSystems/GLES2/src/OgreGLES2RenderToVertexBuffer.cpp deleted file mode 100644 index e4afb5527c1..00000000000 --- a/RenderSystems/GLES2/src/OgreGLES2RenderToVertexBuffer.cpp +++ /dev/null @@ -1,181 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLES2RenderToVertexBuffer.h" - -#include "OgreHardwareBufferManager.h" -#include "OgreGLES2HardwareBuffer.h" -#include "OgreRenderable.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" -#include "OgreGLSLESProgramManager.h" - -namespace Ogre { -//----------------------------------------------------------------------------- - static GLint getR2VBPrimitiveType(RenderOperation::OperationType operationType) - { - switch (operationType) - { - case RenderOperation::OT_POINT_LIST: - return GL_POINTS; - case RenderOperation::OT_LINE_LIST: - return GL_LINES; - case RenderOperation::OT_TRIANGLE_LIST: - return GL_TRIANGLES; - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "GL RenderToVertexBuffer" - "can only output point lists, line lists, or triangle lists", - "OgreGLES2RenderToVertexBuffer::getR2VBPrimitiveType"); - } - } -//----------------------------------------------------------------------------- - GLES2RenderToVertexBuffer::GLES2RenderToVertexBuffer() - { - mVertexBuffers[0].reset(); - mVertexBuffers[1].reset(); - - // Create query objects - OGRE_CHECK_GL_ERROR(glGenQueries(1, &mPrimitivesDrawnQuery)); - } -//----------------------------------------------------------------------------- - GLES2RenderToVertexBuffer::~GLES2RenderToVertexBuffer() - { - OGRE_CHECK_GL_ERROR(glDeleteQueries(1, &mPrimitivesDrawnQuery)); - } -//----------------------------------------------------------------------------- - void GLES2RenderToVertexBuffer::update(SceneManager* sceneMgr) - { - size_t bufSize = mVertexData->vertexDeclaration->getVertexSize(0) * mMaxVertexCount; - if (!mVertexBuffers[0] || mVertexBuffers[0]->getSizeInBytes() != bufSize) - { - // Buffers don't match. Need to reallocate. - mResetRequested = true; - } - - Ogre::Pass* r2vbPass = derivePass(sceneMgr); - - bindVerticesOutput(r2vbPass); - - RenderOperation renderOp; - auto targetBufferIndex = mTargetBufferIndex; - if (mResetRequested || mResetsEveryUpdate) - { - // Use source data to render to first buffer - mSourceRenderable->getRenderOperation(renderOp); - } - else - { - // Use current front buffer to render to back buffer - this->getRenderOperation(renderOp); - } - - if (!mVertexBuffers[targetBufferIndex] || - mVertexBuffers[targetBufferIndex]->getSizeInBytes() != bufSize) - { - reallocateBuffer(targetBufferIndex); - } - - auto vertexBuffer = mVertexBuffers[targetBufferIndex]->_getImpl(); -/* if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS)) - { - GLSLESProgramPipeline* programPipeline = - GLSLESProgramPipelineManager::getSingleton().getActiveProgramPipeline(); - programPipeline->getVertexArrayObject()->bind(); - } - else - { - GLSLESLinkProgram* linkProgram = GLSLESLinkProgramManager::getSingleton().getActiveLinkProgram(); - linkProgram->getVertexArrayObject()->bind(); - } - */ - // Bind the target buffer - OGRE_CHECK_GL_ERROR(glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, vertexBuffer->getGLBufferId())); - - // Disable rasterization - OGRE_CHECK_GL_ERROR(glEnable(GL_RASTERIZER_DISCARD)); - - RenderSystem* targetRenderSystem = Root::getSingleton().getRenderSystem(); - // Draw the object - OGRE_CHECK_GL_ERROR(glBeginQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN, mPrimitivesDrawnQuery)); - - OGRE_CHECK_GL_ERROR(glBeginTransformFeedback(getR2VBPrimitiveType(mOperationType))); - - targetRenderSystem->_render(renderOp); - - OGRE_CHECK_GL_ERROR(glEndTransformFeedback()); - - // Finish the query - OGRE_CHECK_GL_ERROR(glEndQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN)); - - OGRE_CHECK_GL_ERROR(glDisable(GL_RASTERIZER_DISCARD)); - - // Read back query results - GLuint primitivesWritten; - OGRE_CHECK_GL_ERROR(glGetQueryObjectuiv(mPrimitivesDrawnQuery, GL_QUERY_RESULT, &primitivesWritten)); - mVertexData->vertexCount = primitivesWritten * getVertexCountPerPrimitive(mOperationType); - - // Switch the vertex binding - mVertexData->vertexBufferBinding->unsetAllBindings(); - mVertexData->vertexBufferBinding->setBinding(0, mVertexBuffers[targetBufferIndex]); - mTargetBufferIndex = mTargetBufferIndex == 0 ? 1 : 0; - - // Enable rasterization - OGRE_CHECK_GL_ERROR(glDisable(GL_RASTERIZER_DISCARD)); - - // Clear the reset flag - mResetRequested = false; - } -//----------------------------------------------------------------------------- - void GLES2RenderToVertexBuffer::bindVerticesOutput(Pass* pass) - { - VertexDeclaration* declaration = mVertexData->vertexDeclaration; - size_t elemCount = declaration->getElementCount(); - - if (elemCount > 0) - { - GLuint linkProgramId = 0; - // Have GLSL shaders, using varying attributes - GLSLESProgramCommon* linkProgram = GLSLESProgramManager::getSingleton().getActiveProgram(); - linkProgramId = linkProgram->getGLProgramHandle(); - - // Note: 64 is the minimum number of interleaved attributes allowed by GL_EXT_transform_feedback - // So we are using it. Otherwise we could query during rendersystem initialisation and use a dynamic sized array. - // But that would require C99. - const GLchar *names[64]; - for (unsigned short e = 0; e < elemCount; e++) - { - const VertexElement* element = declaration->getElement(e); - String varyingName = getSemanticVaryingName(element->getSemantic(), element->getIndex()); - names[e] = varyingName.c_str(); - } - - OGRE_CHECK_GL_ERROR(glTransformFeedbackVaryings(linkProgramId, elemCount, names, GL_INTERLEAVED_ATTRIBS)); - OGRE_CHECK_GL_ERROR(glLinkProgram(linkProgramId)); - } - } -} diff --git a/RenderSystems/GLES2/src/OgreGLES2StateCacheManager.cpp b/RenderSystems/GLES2/src/OgreGLES2StateCacheManager.cpp deleted file mode 100644 index 217ed3e0143..00000000000 --- a/RenderSystems/GLES2/src/OgreGLES2StateCacheManager.cpp +++ /dev/null @@ -1,404 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ - -#include "OgreGLES2StateCacheManager.h" -#include "OgreGLES2RenderSystem.h" -#include "OgreRoot.h" - -namespace Ogre { - - GLES2StateCacheManager::GLES2StateCacheManager(void) - { - clearCache(); - } - - void GLES2StateCacheManager::initializeCache() - { - OGRE_CHECK_GL_ERROR(glBlendEquation(GL_FUNC_ADD)); - - OGRE_CHECK_GL_ERROR(glBlendFunc(GL_ONE, GL_ZERO)); - - OGRE_CHECK_GL_ERROR(glCullFace(mCullFace)); - - OGRE_CHECK_GL_ERROR(glDepthFunc(mDepthFunc)); - - OGRE_CHECK_GL_ERROR(glDepthMask(mDepthMask)); - - OGRE_CHECK_GL_ERROR(glStencilMask(mStencilMask)); - - OGRE_CHECK_GL_ERROR(glClearDepthf(mClearDepth)); - - OGRE_CHECK_GL_ERROR(glBindTexture(GL_TEXTURE_2D, 0)); - - OGRE_CHECK_GL_ERROR(glBindBuffer(GL_ARRAY_BUFFER, 0)); - - OGRE_CHECK_GL_ERROR(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)); - - OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 0)); - - OGRE_CHECK_GL_ERROR(glBindRenderbuffer(GL_RENDERBUFFER, 0)); - - OGRE_CHECK_GL_ERROR(glActiveTexture(GL_TEXTURE0)); - - OGRE_CHECK_GL_ERROR(glClearColor(mClearColour[0], mClearColour[1], mClearColour[2], mClearColour[3])); - - OGRE_CHECK_GL_ERROR(glColorMask(mColourMask[0], mColourMask[1], mColourMask[2], mColourMask[3])); - } - - void GLES2StateCacheManager::clearCache() - { - mDepthMask = GL_TRUE; - mBlendEquationRGB = GL_FUNC_ADD; - mBlendEquationAlpha = GL_FUNC_ADD; - mCullFace = GL_BACK; - mDepthFunc = GL_LESS; - mStencilMask = 0xFFFFFFFF; - mActiveTextureUnit = 0; - mClearDepth = 1.0f; - mLastBoundTexID = 0; - - // Initialize our cache variables and also the GL so that the - // stored values match the GL state - mBlendFuncSource = GL_ONE; - mBlendFuncDest = GL_ZERO; - mBlendFuncSourceAlpha = GL_ONE; - mBlendFuncDestAlpha = GL_ZERO; - - mClearColour[0] = mClearColour[1] = mClearColour[2] = mClearColour[3] = 0.0f; - mColourMask[0] = mColourMask[1] = mColourMask[2] = mColourMask[3] = GL_TRUE; - - mActiveVertexArray = 0; - -#ifdef OGRE_ENABLE_STATE_CACHE - mEnableVector.reserve(25); - mEnableVector.clear(); - mActiveBufferMap.clear(); - mTexUnitsMap.clear(); -#endif - } - - void GLES2StateCacheManager::bindGLBuffer(GLenum target, GLuint buffer) - { -#ifdef OGRE_ENABLE_STATE_CACHE - auto ret = mActiveBufferMap.emplace(target, buffer); - if(ret.first->second != buffer) // Update the cached value if needed - { - ret.first->second = buffer; - ret.second = true; - } - - // Update GL - if(ret.second) -#endif - { - if(target == GL_FRAMEBUFFER) - { - OgreAssert(false, "not implemented"); - } - else if(target == GL_RENDERBUFFER) - { - OGRE_CHECK_GL_ERROR(glBindRenderbuffer(target, buffer)); - } - else - { - OGRE_CHECK_GL_ERROR(glBindBuffer(target, buffer)); - } - } - } - - void GLES2StateCacheManager::deleteGLBuffer(GLenum target, GLuint buffer) - { - // Buffer name 0 is reserved and we should never try to delete it - if(buffer == 0) - return; - - if(target == GL_FRAMEBUFFER) - { - OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &buffer)); - } - else if(target == GL_RENDERBUFFER) - { - OGRE_CHECK_GL_ERROR(glDeleteRenderbuffers(1, &buffer)); - } - else - { - OGRE_CHECK_GL_ERROR(glDeleteBuffers(1, &buffer)); - } - -#ifdef OGRE_ENABLE_STATE_CACHE - BindBufferMap::iterator i = mActiveBufferMap.find(target); - - if (i != mActiveBufferMap.end() && ((*i).second == buffer)) - { - // Currently bound buffer is being deleted, update the cached value to 0, - // which it likely the buffer that will be bound by the driver. - // An update will be forced next time we try to bind on this target. - (*i).second = 0; - } -#endif - } - - void GLES2StateCacheManager::bindGLVertexArray(GLuint vao) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mActiveVertexArray != vao) - { - mActiveVertexArray = vao; - OGRE_CHECK_GL_ERROR(glBindVertexArrayOES(vao)); - //we also need to clear the cached GL_ELEMENT_ARRAY_BUFFER value, as it is invalidated by glBindVertexArray - mActiveBufferMap[GL_ELEMENT_ARRAY_BUFFER] = 0; - } -#else - OGRE_CHECK_GL_ERROR(glBindVertexArrayOES(vao)); -#endif - } - - void GLES2StateCacheManager::invalidateStateForTexture(GLuint texture) - { -#ifdef OGRE_ENABLE_STATE_CACHE - mTexUnitsMap.erase(texture); -#endif - } - - // TODO: Store as high/low bits of a GLuint, use vector instead of map for TexParameteriMap - void GLES2StateCacheManager::setTexParameteri(GLenum target, GLenum pname, GLint param) - { -#ifdef OGRE_ENABLE_STATE_CACHE - // Check if we have a map entry for this texture id. If not, create a blank one and insert it. - TexUnitsMap::iterator it = mTexUnitsMap.find(mLastBoundTexID); - if (it == mTexUnitsMap.end()) - { - TexParameteriMap unit; - mTexUnitsMap[mLastBoundTexID] = unit; - - // Update the iterator - it = mTexUnitsMap.find(mLastBoundTexID); - } - - // Get a local copy of the parameter map and search for this parameter - TexParameteriMap &myMap = (*it).second; - auto ret = myMap.emplace(pname, param); - TexParameteriMap::iterator i = ret.first; - - // Update the cached value if needed - if((*i).second != param || ret.second) - { - (*i).second = param; - - // Update GL - OGRE_CHECK_GL_ERROR(glTexParameteri(target, pname, param)); - } -#else - OGRE_CHECK_GL_ERROR(glTexParameteri(target, pname, param)); -#endif - } - - void GLES2StateCacheManager::bindGLTexture(GLenum target, GLuint texture) - { - mLastBoundTexID = texture; - - // Update GL - OGRE_CHECK_GL_ERROR(glBindTexture(target, texture)); - } - - bool GLES2StateCacheManager::activateGLTextureUnit(size_t unit) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if (mActiveTextureUnit == unit) - return true; -#endif - - OGRE_CHECK_GL_ERROR(glActiveTexture(GL_TEXTURE0 + unit)); - mActiveTextureUnit = unit; - return true; - } - - void GLES2StateCacheManager::setBlendFunc(GLenum source, GLenum dest, GLenum sourceA, GLenum destA) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mBlendFuncSource != source || mBlendFuncDest != dest || sourceA != mBlendFuncSourceAlpha || destA != mBlendFuncDestAlpha ) -#endif - { - mBlendFuncSource = source; - mBlendFuncDest = dest; - mBlendFuncSourceAlpha = sourceA; - mBlendFuncDestAlpha = destA; - - OGRE_CHECK_GL_ERROR(glBlendFuncSeparate(source, dest, sourceA, destA)); - } - } - - void GLES2StateCacheManager::setBlendEquation(GLenum eqRGB, GLenum eqAlpha) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mBlendEquationRGB != eqRGB || mBlendEquationAlpha != eqAlpha) -#endif - { - mBlendEquationRGB = eqRGB; - mBlendEquationAlpha = eqAlpha; - - OGRE_CHECK_GL_ERROR(glBlendEquationSeparate(eqRGB, eqAlpha)); - } - } - - void GLES2StateCacheManager::setDepthMask(GLboolean mask) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mDepthMask != mask) -#endif - { - mDepthMask = mask; - - OGRE_CHECK_GL_ERROR(glDepthMask(mask)); - } - } - - void GLES2StateCacheManager::setDepthFunc(GLenum func) - { - if(mDepthFunc != func) - { - mDepthFunc = func; - - OGRE_CHECK_GL_ERROR(glDepthFunc(func)); - } - } - - void GLES2StateCacheManager::setClearDepth(GLclampf depth) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mClearDepth != depth) -#endif - { - mClearDepth = depth; - - OGRE_CHECK_GL_ERROR(glClearDepthf(depth)); - } - } - - void GLES2StateCacheManager::setClearColour(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if((mClearColour[0] != red) || - (mClearColour[1] != green) || - (mClearColour[2] != blue) || - (mClearColour[3] != alpha)) -#endif - { - mClearColour[0] = red; - mClearColour[1] = green; - mClearColour[2] = blue; - mClearColour[3] = alpha; - - OGRE_CHECK_GL_ERROR(glClearColor(mClearColour[0], mClearColour[1], mClearColour[2], mClearColour[3])); - } - } - - void GLES2StateCacheManager::setColourMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if((mColourMask[0] != red) || - (mColourMask[1] != green) || - (mColourMask[2] != blue) || - (mColourMask[3] != alpha)) -#endif - { - mColourMask[0] = red; - mColourMask[1] = green; - mColourMask[2] = blue; - mColourMask[3] = alpha; - - OGRE_CHECK_GL_ERROR(glColorMask(mColourMask[0], mColourMask[1], mColourMask[2], mColourMask[3])); - } - } - - void GLES2StateCacheManager::setStencilMask(GLuint mask) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mStencilMask != mask) -#endif - { - mStencilMask = mask; - - OGRE_CHECK_GL_ERROR(glStencilMask(mask)); - } - } - - void GLES2StateCacheManager::setEnabled(GLenum flag) - { -#ifdef OGRE_ENABLE_STATE_CACHE - bool found = std::find(mEnableVector.begin(), mEnableVector.end(), flag) != mEnableVector.end(); - if(!found) - { - mEnableVector.push_back(flag); - - OGRE_CHECK_GL_ERROR(glEnable(flag)); - } -#else - OGRE_CHECK_GL_ERROR(glEnable(flag)); -#endif - } - - void GLES2StateCacheManager::setDisabled(GLenum flag) - { -#ifdef OGRE_ENABLE_STATE_CACHE - auto iter = std::find(mEnableVector.begin(), mEnableVector.end(), flag); - if(iter != mEnableVector.end()) - { - mEnableVector.erase(iter); - - OGRE_CHECK_GL_ERROR(glDisable(flag)); - } -#else - OGRE_CHECK_GL_ERROR(glDisable(flag)); -#endif - } - - void GLES2StateCacheManager::setCullFace(GLenum face) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mCullFace != face) -#endif - { - mCullFace = face; - - OGRE_CHECK_GL_ERROR(glCullFace(face)); - } - } - - void GLES2StateCacheManager::setViewport(const Rect& r) - { -#ifdef OGRE_ENABLE_STATE_CACHE - if(mViewport != r) -#endif - { - mViewport = r; - OGRE_CHECK_GL_ERROR(glViewport(r.left, r.top, r.width(), r.height())); - } - } - -} diff --git a/RenderSystems/GLES2/src/OgreGLES2Texture.cpp b/RenderSystems/GLES2/src/OgreGLES2Texture.cpp deleted file mode 100644 index b1bd3c10c3c..00000000000 --- a/RenderSystems/GLES2/src/OgreGLES2Texture.cpp +++ /dev/null @@ -1,383 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLES2Texture.h" -#include "OgreGLES2PixelFormat.h" -#include "OgreGLES2HardwarePixelBuffer.h" -#include "OgreGLES2StateCacheManager.h" -#include "OgreRoot.h" -#include "OgreBitwise.h" -#include "OgreTextureManager.h" -#include "OgreLogManager.h" - -namespace Ogre { - GLES2Texture::GLES2Texture(ResourceManager* creator, const String& name, - ResourceHandle handle, const String& group, bool isManual, - ManualResourceLoader* loader, GLES2RenderSystem* renderSystem) - : GLTextureCommon(creator, name, handle, group, isManual, loader), - mRenderSystem(renderSystem) - { - } - - GLES2Texture::~GLES2Texture() - { - // have to call this here rather than in Resource destructor - // since calling virtual methods in base destructors causes crash - unload(); - } - - GLenum GLES2Texture::getGLES2TextureTarget(void) const - { - switch(mTextureType) - { - case TEX_TYPE_1D: - case TEX_TYPE_2D: - return GL_TEXTURE_2D; - case TEX_TYPE_CUBE_MAP: - return GL_TEXTURE_CUBE_MAP; - case TEX_TYPE_3D: - return GL_TEXTURE_3D_OES; - case TEX_TYPE_2D_ARRAY: - return GL_TEXTURE_2D_ARRAY; - case TEX_TYPE_EXTERNAL_OES: - return GL_TEXTURE_EXTERNAL_OES; - default: - return 0; - }; - } - - void GLES2Texture::_createGLTexResource() - { - const RenderSystemCapabilities *renderCaps = - Root::getSingleton().getRenderSystem()->getCapabilities(); - - const bool nonPowerOfTwoSupported = renderCaps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES) || - ( renderCaps->getNonPOW2TexturesLimited() && - mNumRequestedMipmaps == 0 ); - - if( !nonPowerOfTwoSupported ) - { - // Convert to nearest power-of-two size if required - mWidth = Bitwise::firstPO2From(mWidth); - mHeight = Bitwise::firstPO2From(mHeight); - mDepth = Bitwise::firstPO2From(mDepth); - } - - // set HardwareBuffer::Usage for TU_RENDERTARGET if nothing else specified - if((mUsage & TU_RENDERTARGET) && (mUsage & ~TU_RENDERTARGET) == 0) - mUsage |= HardwareBuffer::HBU_DYNAMIC; - - // Adjust format if required - mFormat = TextureManager::getSingleton().getNativeFormat(mTextureType, mFormat, mUsage); - GLenum texTarget = getGLES2TextureTarget(); - - // Generate texture name - OGRE_CHECK_GL_ERROR(glGenTextures(1, &mTextureID)); - - // Set texture type - mRenderSystem->_getStateCacheManager()->bindGLTexture(texTarget, mTextureID); - - if (renderCaps->hasCapability(RSC_DEBUG)) - OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_TEXTURE, mTextureID, -1, mName.c_str())); - - // If we can do automip generation and the user desires this, do so - mMipmapsHardwareGenerated = !PixelUtil::isCompressed(mFormat); - - // glGenerateMipmap require all mip levels to be prepared. So override how many this texture has. - if((mUsage & TU_AUTOMIPMAP) && mMipmapsHardwareGenerated && mNumRequestedMipmaps) - mNumMipmaps = getMaxMipmaps(); - - if(mRenderSystem->hasMinGLVersion(3, 0) || mRenderSystem->checkExtension("GL_APPLE_texture_max_level")) - mRenderSystem->_getStateCacheManager()->setTexParameteri(texTarget, GL_TEXTURE_MAX_LEVEL_APPLE, mNumRequestedMipmaps ? mNumMipmaps + 1 : 0); - - if(mTextureType == TEX_TYPE_EXTERNAL_OES && mNumRequestedMipmaps > 0) { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Mipmaps are not available for TEX_TYPE_EXTERNAL_OES", "GLES2Texture::_createGLTexResource"); - } - - bool hasGLES30 = mRenderSystem->hasMinGLVersion(3, 0); - - // Set up texture swizzling (not available in WebGL2) - if (hasGLES30 && (OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN)) - { - if(PixelUtil::isLuminance(mFormat)) - { - if (PixelUtil::getComponentCount(mFormat) == 2) - { - OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_R, GL_RED)); - OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_G, GL_RED)); - OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_B, GL_RED)); - OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_A, GL_GREEN)); - } - else - { - OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_R, GL_RED)); - OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_G, GL_RED)); - OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_B, GL_RED)); - OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_A, GL_ONE)); - } - } - else if(mFormat == PF_A8) - { - OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_R, GL_ZERO)); - OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_G, GL_ZERO)); - OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_B, GL_ZERO)); - OGRE_CHECK_GL_ERROR(glTexParameteri(texTarget, GL_TEXTURE_SWIZZLE_A, GL_RED)); - } - } - - // Allocate internal buffer so that glTexSubImageXD can be used - // Internal format - GLenum format = GLES2PixelUtil::getGLOriginFormat(mFormat); - GLenum internalformat = GLES2PixelUtil::getGLInternalFormat(mFormat, mHwGamma); - uint32 width = mWidth; - uint32 height = mHeight; - uint32 depth = mDepth; - - if (PixelUtil::isCompressed(mFormat)) - { - // Compressed formats - GLsizei size = static_cast(PixelUtil::getMemorySize(mWidth, mHeight, mDepth, mFormat)); - - // Provide temporary buffer filled with zeroes as glCompressedTexImageXD does not - // accept a 0 pointer like normal glTexImageXD - // Run through this process for every mipmap to pregenerate mipmap pyramid - - std::vector tmpdata(size); - for (uint32 mip = 0; mip <= mNumMipmaps; mip++) - { - size = static_cast(PixelUtil::getMemorySize(width, height, depth, mFormat)); - - switch(mTextureType) - { - case TEX_TYPE_1D: - case TEX_TYPE_2D: - OGRE_CHECK_GL_ERROR(glCompressedTexImage2D(GL_TEXTURE_2D, - mip, - internalformat, - width, height, - 0, - size, - &tmpdata[0])); - break; - case TEX_TYPE_CUBE_MAP: - for(int face = 0; face < 6; face++) { - OGRE_CHECK_GL_ERROR(glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, internalformat, - width, height, 0, - size, &tmpdata[0])); - } - break; - case TEX_TYPE_2D_ARRAY: - if(!hasGLES30) - break; - OGRE_FALLTHROUGH; - case TEX_TYPE_3D: - glCompressedTexImage3DOES(texTarget, mip, format, - width, height, depth, 0, - size, &tmpdata[0]); - break; - case TEX_TYPE_EXTERNAL_OES: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Attempt to create mipmap for TEX_TYPE_EXTERNAL_OES, should never happen", "GLES2Texture::_createGLTexResource"); - }; - - if(width > 1) - { - width = width / 2; - } - if(height > 1) - { - height = height / 2; - } - if(depth > 1 && mTextureType != TEX_TYPE_2D_ARRAY) - { - depth = depth / 2; - } - } - return; - } - - if(hasGLES30) - { - switch(mTextureType) - { - case TEX_TYPE_1D: - case TEX_TYPE_2D: - case TEX_TYPE_CUBE_MAP: - OGRE_CHECK_GL_ERROR(glTexStorage2D(texTarget, GLsizei(mNumMipmaps+1), internalformat, GLsizei(width), GLsizei(height))); - break; - case TEX_TYPE_2D_ARRAY: - case TEX_TYPE_3D: - OGRE_CHECK_GL_ERROR(glTexStorage3D(texTarget, GLsizei(mNumMipmaps+1), internalformat, GLsizei(width), GLsizei(height), GLsizei(depth))); - break; - case TEX_TYPE_EXTERNAL_OES: - // Not available for TEX_TYPE_EXTERNAL_OES - break; - } - return; - } - GLenum datatype = GLES2PixelUtil::getGLOriginDataType(mFormat); - - // Run through this process to pregenerate mipmap pyramid - for(uint32 mip = 0; mip <= mNumMipmaps; mip++) - { - // Normal formats - switch(mTextureType) - { - case TEX_TYPE_1D: - case TEX_TYPE_2D: - OGRE_CHECK_GL_ERROR(glTexImage2D(GL_TEXTURE_2D, - mip, - internalformat, - width, height, - 0, - format, - datatype, 0)); - break; - case TEX_TYPE_2D_ARRAY: - if(!hasGLES30) - break; - OGRE_FALLTHROUGH; - case TEX_TYPE_3D: - OGRE_CHECK_GL_ERROR(glTexImage3DOES(texTarget, - mip, - internalformat, - width, height, depth, - 0, - format, - datatype, 0)); - break; - case TEX_TYPE_CUBE_MAP: - for(int face = 0; face < 6; face++) { - OGRE_CHECK_GL_ERROR(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mip, internalformat, - width, height, 0, - format, datatype, 0)); - } - break; - default: - break; - }; - - if (width > 1) - { - width = Bitwise::firstPO2From(width / 2); - } - if (height > 1) - { - height = Bitwise::firstPO2From(height / 2); - } - } - } - - // Creation / loading methods - void GLES2Texture::createInternalResourcesImpl(void) - { - _createGLTexResource(); - - _createSurfaceList(); - - // Get final internal format - mFormat = getBuffer(0,0)->getFormat(); - } - - void GLES2Texture::freeInternalResourcesImpl() - { - if (GLES2StateCacheManager* stateCacheManager = mRenderSystem->_getStateCacheManager()) - { - OGRE_CHECK_GL_ERROR(glDeleteTextures(1, &mTextureID)); - stateCacheManager->invalidateStateForTexture(mTextureID); - } - mTextureID = 0; - } - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - void GLES2Texture::notifyOnContextLost() - { - if (!isManuallyLoaded()) - { - unloadImpl(); - } - else - { - OGRE_CHECK_GL_ERROR(glDeleteTextures(1, &mTextureID)); - mTextureID = 0; - } - } - - void GLES2Texture::notifyOnContextReset() - { - if (!isManuallyLoaded()) - { - reload(); - } - else - { - preLoadImpl(); - - _createGLTexResource(); - - for(size_t i = 0; i < mSurfaceList.size(); i++) - { - static_cast(mSurfaceList[i].get())->updateTextureId(mTextureID); - } - - if (mLoader) - { - mLoader->loadResource(this); - } - - postLoadImpl(); - } - } -#endif - - void GLES2Texture::_createSurfaceList() - { - mSurfaceList.clear(); - - uint32 depth = mDepth; - - // For all faces and mipmaps, store surfaces as HardwarePixelBufferSharedPtr - for (size_t face = 0; face < getNumFaces(); face++) - { - uint32 width = mWidth; - uint32 height = mHeight; - - for (uint32 mip = 0; mip <= getNumMipmaps(); mip++) - { - auto buf = std::make_shared(this, int(face), mip, width, height, depth); - mSurfaceList.push_back(buf); - - if (width > 1) - width = width / 2; - if (height > 1) - height = height / 2; - if (depth > 1 && mTextureType != TEX_TYPE_2D_ARRAY) - depth = depth / 2; - } - } - } -} diff --git a/RenderSystems/GLES2/src/OgreGLES2TextureManager.cpp b/RenderSystems/GLES2/src/OgreGLES2TextureManager.cpp deleted file mode 100644 index ff832887a70..00000000000 --- a/RenderSystems/GLES2/src/OgreGLES2TextureManager.cpp +++ /dev/null @@ -1,109 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLES2TextureManager.h" -#include "OgreGLRenderTexture.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" -#include "OgreGLES2StateCacheManager.h" -#include "OgreGLES2PixelFormat.h" - -namespace Ogre { - GLES2TextureManager::GLES2TextureManager(GLES2RenderSystem* renderSystem) - : TextureManager(), mRenderSystem(renderSystem) - { - // Register with group manager - ResourceGroupManager::getSingleton()._registerResourceManager(mResourceType, this); - } - - GLES2TextureManager::~GLES2TextureManager() - { - // Unregister with group manager - ResourceGroupManager::getSingleton()._unregisterResourceManager(mResourceType); - } - - Resource* GLES2TextureManager::createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, - ManualResourceLoader* loader, - const NameValuePairList* createParams) - { - return OGRE_NEW GLES2Texture(this, name, handle, group, isManual, loader, mRenderSystem); - } - - PixelFormat GLES2TextureManager::getNativeFormat(TextureType ttype, PixelFormat format, int usage) - { - // Adjust requested parameters to capabilities - const RenderSystemCapabilities *caps = Root::getSingleton().getRenderSystem()->getCapabilities(); - - // Check compressed texture support - // if a compressed format not supported, revert to PF_A8R8G8B8 - if (PixelUtil::isCompressed(format) && - !caps->hasCapability(RSC_TEXTURE_COMPRESSION)) - { - return PF_BYTE_RGBA; - } - // if floating point textures not supported, revert to PF_A8R8G8B8 - if (PixelUtil::isFloatingPoint(format) && - !caps->hasCapability(RSC_TEXTURE_FLOAT)) - { - return PF_BYTE_RGBA; - } - - // Check if this is a valid rendertarget format - if (usage & TU_RENDERTARGET) - { - /// Get closest supported alternative - /// If mFormat is supported it's returned - return GLRTTManager::getSingleton().getSupportedAlternative(format); - } - - // format not supported by GLES2: e.g. BGR - if(GLES2PixelUtil::getGLInternalFormat(format) == GL_NONE) - { - return PF_BYTE_RGBA; - } - - // Supported - return format; - } - - bool GLES2TextureManager::isHardwareFilteringSupported(TextureType ttype, PixelFormat format, int usage, - bool preciseFormatOnly) - { - // precise format check - if (!TextureManager::isHardwareFilteringSupported(ttype, format, usage, preciseFormatOnly)) - return false; - - // Assume non-floating point is supported always - if (!PixelUtil::isFloatingPoint(getNativeFormat(ttype, format, usage))) - return true; - - // check for floating point extension - return mRenderSystem->checkExtension("GL_OES_texture_float_linear"); - } -} diff --git a/RenderSystems/GLES2/src/glesw.c b/RenderSystems/GLES2/src/glesw.c deleted file mode 100644 index 205f1e79a1b..00000000000 --- a/RenderSystems/GLES2/src/glesw.c +++ /dev/null @@ -1,1407 +0,0 @@ -/* - - This file was generated with glesw_gen.cmake, part of glXXw - (hosted at https://github.com/paroj/glXXw-cmake) - - This is free and unencumbered software released into the public domain. - - Anyone is free to copy, modify, publish, use, compile, sell, or - distribute this software, either in source code form or as a compiled - binary, for any purpose, commercial or non-commercial, and by any - means. - - In jurisdictions that recognize copyright laws, the author or authors - of this software dedicate any and all copyright interest in the - software to the public domain. We make this dedication for the benefit - of the public at large and to the detriment of our heirs and - successors. We intend this dedication to be an overt act of - relinquishment in perpetuity of all present and future rights to this - software under copyright law. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR - OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, - ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - OTHER DEALINGS IN THE SOFTWARE. - -*/ - -#include -#include - -#ifdef _WIN32 -#define WIN32_LEAN_AND_MEAN 1 -#include - -static HMODULE libgl; -static PROC (__stdcall *wgl_get_proc_address)(LPCSTR); - -static void open_libgl(void) -{ - libgl = LoadLibraryA("opengl32.dll"); - *(void **)(&wgl_get_proc_address) = GetProcAddress(libgl, "wglGetProcAddress"); -} - -static void close_libgl(void) -{ - FreeLibrary(libgl); -} - -static GLESWglProc get_proc(const char *proc) -{ - GLESWglProc res; - - res = (GLESWglProc)wgl_get_proc_address(proc); - if (!res) - res = (GLESWglProc)GetProcAddress(libgl, proc); - return res; -} -#elif defined(__APPLE__) || defined(__APPLE_CC__) -#include - -CFBundleRef bundle; -CFURLRef bundleURL; - -static void open_libgl(void) -{ - bundle = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.opengles")); // we are always linked to OpenGLES.framework statically, so it is already loaded and could be found by id - assert(bundle != NULL); - - CFRetain(bundle); - bundleURL = CFBundleCopyBundleURL(bundle); -} - -static void close_libgl(void) -{ - CFRelease(bundle); - CFRelease(bundleURL); -} - -static GLESWglProc get_proc(const char *proc) -{ - GLESWglProc res; - - CFStringRef procname = CFStringCreateWithCString(kCFAllocatorDefault, proc, - kCFStringEncodingASCII); - *(void **)(&res) = CFBundleGetFunctionPointerForName(bundle, procname); - CFRelease(procname); - return res; -} -#elif defined(__EMSCRIPTEN__) -#include -static void open_libgl() {} -static void close_libgl() {} -static GLESWglProc get_proc(const char *proc) -{ - return (GLESWglProc)eglGetProcAddress(proc); -} -#else -#include - -static void *libgl; - -static void open_libgl(void) -{ - libgl = dlopen("libGLESv2.so", RTLD_LAZY | RTLD_GLOBAL); -} - -static void close_libgl(void) -{ - dlclose(libgl); -} - -static GLESWglProc get_proc(const char *proc) -{ - return dlsym(libgl, proc); -} -#endif - -static struct { - int major, minor; -} version; - -static int parse_version(void) -{ - if (!glGetString) - return -1; - - const char* pcVer = (const char*)glGetString(GL_VERSION); - sscanf(pcVer, "OpenGL ES %u.%u", &version.major, &version.minor); - - if (version.major < 2) - return -1; - return 0; -} - -static void load_procs(GLESWGetProcAddressProc proc); - -int gleswInit(void) -{ - open_libgl(); - load_procs(get_proc); - close_libgl(); - return parse_version(); -} - -int gleswInit2(GLESWGetProcAddressProc proc) -{ - load_procs(proc); - return parse_version(); -} - -int gleswIsSupported(int major, int minor) -{ - if (major < 2) - return 0; - if (version.major == major) - return version.minor >= minor; - return version.major >= major; -} - -GLESWglProc gleswGetProcAddress(const char *proc) -{ - return get_proc(proc); -} - -PFNGLACTIVESHADERPROGRAMEXTPROC gleswActiveShaderProgramEXT; -PFNGLACTIVETEXTUREPROC gleswActiveTexture; -PFNGLALPHAFUNCQCOMPROC gleswAlphaFuncQCOM; -PFNGLAPPLYFRAMEBUFFERATTACHMENTCMAAINTELPROC gleswApplyFramebufferAttachmentCMAAINTEL; -PFNGLATTACHSHADERPROC gleswAttachShader; -PFNGLBEGINCONDITIONALRENDERNVPROC gleswBeginConditionalRenderNV; -PFNGLBEGINPERFMONITORAMDPROC gleswBeginPerfMonitorAMD; -PFNGLBEGINPERFQUERYINTELPROC gleswBeginPerfQueryINTEL; -PFNGLBEGINQUERYPROC gleswBeginQuery; -PFNGLBEGINQUERYEXTPROC gleswBeginQueryEXT; -PFNGLBEGINTRANSFORMFEEDBACKPROC gleswBeginTransformFeedback; -PFNGLBINDATTRIBLOCATIONPROC gleswBindAttribLocation; -PFNGLBINDBUFFERPROC gleswBindBuffer; -PFNGLBINDBUFFERBASEPROC gleswBindBufferBase; -PFNGLBINDBUFFERRANGEPROC gleswBindBufferRange; -PFNGLBINDFRAGDATALOCATIONEXTPROC gleswBindFragDataLocationEXT; -PFNGLBINDFRAGDATALOCATIONINDEXEDEXTPROC gleswBindFragDataLocationIndexedEXT; -PFNGLBINDFRAMEBUFFERPROC gleswBindFramebuffer; -PFNGLBINDPROGRAMPIPELINEEXTPROC gleswBindProgramPipelineEXT; -PFNGLBINDRENDERBUFFERPROC gleswBindRenderbuffer; -PFNGLBINDSAMPLERPROC gleswBindSampler; -PFNGLBINDTEXTUREPROC gleswBindTexture; -PFNGLBINDTRANSFORMFEEDBACKPROC gleswBindTransformFeedback; -PFNGLBINDVERTEXARRAYPROC gleswBindVertexArray; -PFNGLBINDVERTEXARRAYOESPROC gleswBindVertexArrayOES; -PFNGLBLENDBARRIERKHRPROC gleswBlendBarrierKHR; -PFNGLBLENDBARRIERNVPROC gleswBlendBarrierNV; -PFNGLBLENDCOLORPROC gleswBlendColor; -PFNGLBLENDEQUATIONPROC gleswBlendEquation; -PFNGLBLENDEQUATIONSEPARATEPROC gleswBlendEquationSeparate; -PFNGLBLENDEQUATIONSEPARATEIEXTPROC gleswBlendEquationSeparateiEXT; -PFNGLBLENDEQUATIONSEPARATEIOESPROC gleswBlendEquationSeparateiOES; -PFNGLBLENDEQUATIONIEXTPROC gleswBlendEquationiEXT; -PFNGLBLENDEQUATIONIOESPROC gleswBlendEquationiOES; -PFNGLBLENDFUNCPROC gleswBlendFunc; -PFNGLBLENDFUNCSEPARATEPROC gleswBlendFuncSeparate; -PFNGLBLENDFUNCSEPARATEIEXTPROC gleswBlendFuncSeparateiEXT; -PFNGLBLENDFUNCSEPARATEIOESPROC gleswBlendFuncSeparateiOES; -PFNGLBLENDFUNCIEXTPROC gleswBlendFunciEXT; -PFNGLBLENDFUNCIOESPROC gleswBlendFunciOES; -PFNGLBLENDPARAMETERINVPROC gleswBlendParameteriNV; -PFNGLBLITFRAMEBUFFERPROC gleswBlitFramebuffer; -PFNGLBLITFRAMEBUFFERANGLEPROC gleswBlitFramebufferANGLE; -PFNGLBLITFRAMEBUFFERNVPROC gleswBlitFramebufferNV; -PFNGLBUFFERDATAPROC gleswBufferData; -PFNGLBUFFERSTORAGEEXTPROC gleswBufferStorageEXT; -PFNGLBUFFERSUBDATAPROC gleswBufferSubData; -PFNGLCHECKFRAMEBUFFERSTATUSPROC gleswCheckFramebufferStatus; -PFNGLCLEARPROC gleswClear; -PFNGLCLEARBUFFERFIPROC gleswClearBufferfi; -PFNGLCLEARBUFFERFVPROC gleswClearBufferfv; -PFNGLCLEARBUFFERIVPROC gleswClearBufferiv; -PFNGLCLEARBUFFERUIVPROC gleswClearBufferuiv; -PFNGLCLEARCOLORPROC gleswClearColor; -PFNGLCLEARDEPTHFPROC gleswClearDepthf; -PFNGLCLEARPIXELLOCALSTORAGEUIEXTPROC gleswClearPixelLocalStorageuiEXT; -PFNGLCLEARSTENCILPROC gleswClearStencil; -PFNGLCLIENTWAITSYNCPROC gleswClientWaitSync; -PFNGLCLIENTWAITSYNCAPPLEPROC gleswClientWaitSyncAPPLE; -PFNGLCOLORMASKPROC gleswColorMask; -PFNGLCOLORMASKIEXTPROC gleswColorMaskiEXT; -PFNGLCOLORMASKIOESPROC gleswColorMaskiOES; -PFNGLCOMPILESHADERPROC gleswCompileShader; -PFNGLCOMPRESSEDTEXIMAGE2DPROC gleswCompressedTexImage2D; -PFNGLCOMPRESSEDTEXIMAGE3DPROC gleswCompressedTexImage3D; -PFNGLCOMPRESSEDTEXIMAGE3DOESPROC gleswCompressedTexImage3DOES; -PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC gleswCompressedTexSubImage2D; -PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC gleswCompressedTexSubImage3D; -PFNGLCOMPRESSEDTEXSUBIMAGE3DOESPROC gleswCompressedTexSubImage3DOES; -PFNGLCOPYBUFFERSUBDATAPROC gleswCopyBufferSubData; -PFNGLCOPYBUFFERSUBDATANVPROC gleswCopyBufferSubDataNV; -PFNGLCOPYIMAGESUBDATAEXTPROC gleswCopyImageSubDataEXT; -PFNGLCOPYIMAGESUBDATAOESPROC gleswCopyImageSubDataOES; -PFNGLCOPYPATHNVPROC gleswCopyPathNV; -PFNGLCOPYTEXIMAGE2DPROC gleswCopyTexImage2D; -PFNGLCOPYTEXSUBIMAGE2DPROC gleswCopyTexSubImage2D; -PFNGLCOPYTEXSUBIMAGE3DPROC gleswCopyTexSubImage3D; -PFNGLCOPYTEXSUBIMAGE3DOESPROC gleswCopyTexSubImage3DOES; -PFNGLCOPYTEXTURELEVELSAPPLEPROC gleswCopyTextureLevelsAPPLE; -PFNGLCOVERFILLPATHINSTANCEDNVPROC gleswCoverFillPathInstancedNV; -PFNGLCOVERFILLPATHNVPROC gleswCoverFillPathNV; -PFNGLCOVERSTROKEPATHINSTANCEDNVPROC gleswCoverStrokePathInstancedNV; -PFNGLCOVERSTROKEPATHNVPROC gleswCoverStrokePathNV; -PFNGLCOVERAGEMASKNVPROC gleswCoverageMaskNV; -PFNGLCOVERAGEMODULATIONNVPROC gleswCoverageModulationNV; -PFNGLCOVERAGEMODULATIONTABLENVPROC gleswCoverageModulationTableNV; -PFNGLCOVERAGEOPERATIONNVPROC gleswCoverageOperationNV; -PFNGLCREATEPERFQUERYINTELPROC gleswCreatePerfQueryINTEL; -PFNGLCREATEPROGRAMPROC gleswCreateProgram; -PFNGLCREATESHADERPROC gleswCreateShader; -PFNGLCREATESHADERPROGRAMVEXTPROC gleswCreateShaderProgramvEXT; -PFNGLCULLFACEPROC gleswCullFace; -PFNGLDEBUGMESSAGECALLBACKKHRPROC gleswDebugMessageCallbackKHR; -PFNGLDEBUGMESSAGECONTROLKHRPROC gleswDebugMessageControlKHR; -PFNGLDEBUGMESSAGEINSERTKHRPROC gleswDebugMessageInsertKHR; -PFNGLDELETEBUFFERSPROC gleswDeleteBuffers; -PFNGLDELETEFENCESNVPROC gleswDeleteFencesNV; -PFNGLDELETEFRAMEBUFFERSPROC gleswDeleteFramebuffers; -PFNGLDELETEPATHSNVPROC gleswDeletePathsNV; -PFNGLDELETEPERFMONITORSAMDPROC gleswDeletePerfMonitorsAMD; -PFNGLDELETEPERFQUERYINTELPROC gleswDeletePerfQueryINTEL; -PFNGLDELETEPROGRAMPROC gleswDeleteProgram; -PFNGLDELETEPROGRAMPIPELINESEXTPROC gleswDeleteProgramPipelinesEXT; -PFNGLDELETEQUERIESPROC gleswDeleteQueries; -PFNGLDELETEQUERIESEXTPROC gleswDeleteQueriesEXT; -PFNGLDELETERENDERBUFFERSPROC gleswDeleteRenderbuffers; -PFNGLDELETESAMPLERSPROC gleswDeleteSamplers; -PFNGLDELETESHADERPROC gleswDeleteShader; -PFNGLDELETESYNCPROC gleswDeleteSync; -PFNGLDELETESYNCAPPLEPROC gleswDeleteSyncAPPLE; -PFNGLDELETETEXTURESPROC gleswDeleteTextures; -PFNGLDELETETRANSFORMFEEDBACKSPROC gleswDeleteTransformFeedbacks; -PFNGLDELETEVERTEXARRAYSPROC gleswDeleteVertexArrays; -PFNGLDELETEVERTEXARRAYSOESPROC gleswDeleteVertexArraysOES; -PFNGLDEPTHFUNCPROC gleswDepthFunc; -PFNGLDEPTHMASKPROC gleswDepthMask; -PFNGLDEPTHRANGEARRAYFVNVPROC gleswDepthRangeArrayfvNV; -PFNGLDEPTHRANGEINDEXEDFNVPROC gleswDepthRangeIndexedfNV; -PFNGLDEPTHRANGEFPROC gleswDepthRangef; -PFNGLDETACHSHADERPROC gleswDetachShader; -PFNGLDISABLEPROC gleswDisable; -PFNGLDISABLEDRIVERCONTROLQCOMPROC gleswDisableDriverControlQCOM; -PFNGLDISABLEVERTEXATTRIBARRAYPROC gleswDisableVertexAttribArray; -PFNGLDISABLEIEXTPROC gleswDisableiEXT; -PFNGLDISABLEINVPROC gleswDisableiNV; -PFNGLDISABLEIOESPROC gleswDisableiOES; -PFNGLDISCARDFRAMEBUFFEREXTPROC gleswDiscardFramebufferEXT; -PFNGLDRAWARRAYSPROC gleswDrawArrays; -PFNGLDRAWARRAYSINSTANCEDPROC gleswDrawArraysInstanced; -PFNGLDRAWARRAYSINSTANCEDANGLEPROC gleswDrawArraysInstancedANGLE; -PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEEXTPROC gleswDrawArraysInstancedBaseInstanceEXT; -PFNGLDRAWARRAYSINSTANCEDEXTPROC gleswDrawArraysInstancedEXT; -PFNGLDRAWARRAYSINSTANCEDNVPROC gleswDrawArraysInstancedNV; -PFNGLDRAWBUFFERSPROC gleswDrawBuffers; -PFNGLDRAWBUFFERSEXTPROC gleswDrawBuffersEXT; -PFNGLDRAWBUFFERSINDEXEDEXTPROC gleswDrawBuffersIndexedEXT; -PFNGLDRAWBUFFERSNVPROC gleswDrawBuffersNV; -PFNGLDRAWELEMENTSPROC gleswDrawElements; -PFNGLDRAWELEMENTSBASEVERTEXEXTPROC gleswDrawElementsBaseVertexEXT; -PFNGLDRAWELEMENTSBASEVERTEXOESPROC gleswDrawElementsBaseVertexOES; -PFNGLDRAWELEMENTSINSTANCEDPROC gleswDrawElementsInstanced; -PFNGLDRAWELEMENTSINSTANCEDANGLEPROC gleswDrawElementsInstancedANGLE; -PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEEXTPROC gleswDrawElementsInstancedBaseInstanceEXT; -PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEEXTPROC gleswDrawElementsInstancedBaseVertexBaseInstanceEXT; -PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXEXTPROC gleswDrawElementsInstancedBaseVertexEXT; -PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXOESPROC gleswDrawElementsInstancedBaseVertexOES; -PFNGLDRAWELEMENTSINSTANCEDEXTPROC gleswDrawElementsInstancedEXT; -PFNGLDRAWELEMENTSINSTANCEDNVPROC gleswDrawElementsInstancedNV; -PFNGLDRAWRANGEELEMENTSPROC gleswDrawRangeElements; -PFNGLDRAWRANGEELEMENTSBASEVERTEXEXTPROC gleswDrawRangeElementsBaseVertexEXT; -PFNGLDRAWRANGEELEMENTSBASEVERTEXOESPROC gleswDrawRangeElementsBaseVertexOES; -PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC gleswEGLImageTargetRenderbufferStorageOES; -PFNGLEGLIMAGETARGETTEXTURE2DOESPROC gleswEGLImageTargetTexture2DOES; -PFNGLENABLEPROC gleswEnable; -PFNGLENABLEDRIVERCONTROLQCOMPROC gleswEnableDriverControlQCOM; -PFNGLENABLEVERTEXATTRIBARRAYPROC gleswEnableVertexAttribArray; -PFNGLENABLEIEXTPROC gleswEnableiEXT; -PFNGLENABLEINVPROC gleswEnableiNV; -PFNGLENABLEIOESPROC gleswEnableiOES; -PFNGLENDCONDITIONALRENDERNVPROC gleswEndConditionalRenderNV; -PFNGLENDPERFMONITORAMDPROC gleswEndPerfMonitorAMD; -PFNGLENDPERFQUERYINTELPROC gleswEndPerfQueryINTEL; -PFNGLENDQUERYPROC gleswEndQuery; -PFNGLENDQUERYEXTPROC gleswEndQueryEXT; -PFNGLENDTILINGQCOMPROC gleswEndTilingQCOM; -PFNGLENDTRANSFORMFEEDBACKPROC gleswEndTransformFeedback; -PFNGLEXTGETBUFFERPOINTERVQCOMPROC gleswExtGetBufferPointervQCOM; -PFNGLEXTGETBUFFERSQCOMPROC gleswExtGetBuffersQCOM; -PFNGLEXTGETFRAMEBUFFERSQCOMPROC gleswExtGetFramebuffersQCOM; -PFNGLEXTGETPROGRAMBINARYSOURCEQCOMPROC gleswExtGetProgramBinarySourceQCOM; -PFNGLEXTGETPROGRAMSQCOMPROC gleswExtGetProgramsQCOM; -PFNGLEXTGETRENDERBUFFERSQCOMPROC gleswExtGetRenderbuffersQCOM; -PFNGLEXTGETSHADERSQCOMPROC gleswExtGetShadersQCOM; -PFNGLEXTGETTEXLEVELPARAMETERIVQCOMPROC gleswExtGetTexLevelParameterivQCOM; -PFNGLEXTGETTEXSUBIMAGEQCOMPROC gleswExtGetTexSubImageQCOM; -PFNGLEXTGETTEXTURESQCOMPROC gleswExtGetTexturesQCOM; -PFNGLEXTISPROGRAMBINARYQCOMPROC gleswExtIsProgramBinaryQCOM; -PFNGLEXTTEXOBJECTSTATEOVERRIDEIQCOMPROC gleswExtTexObjectStateOverrideiQCOM; -PFNGLFENCESYNCPROC gleswFenceSync; -PFNGLFENCESYNCAPPLEPROC gleswFenceSyncAPPLE; -PFNGLFINISHPROC gleswFinish; -PFNGLFINISHFENCENVPROC gleswFinishFenceNV; -PFNGLFLUSHPROC gleswFlush; -PFNGLFLUSHMAPPEDBUFFERRANGEPROC gleswFlushMappedBufferRange; -PFNGLFLUSHMAPPEDBUFFERRANGEEXTPROC gleswFlushMappedBufferRangeEXT; -PFNGLFRAGMENTCOVERAGECOLORNVPROC gleswFragmentCoverageColorNV; -PFNGLFRAMEBUFFERPIXELLOCALSTORAGESIZEEXTPROC gleswFramebufferPixelLocalStorageSizeEXT; -PFNGLFRAMEBUFFERRENDERBUFFERPROC gleswFramebufferRenderbuffer; -PFNGLFRAMEBUFFERSAMPLELOCATIONSFVNVPROC gleswFramebufferSampleLocationsfvNV; -PFNGLFRAMEBUFFERTEXTURE2DPROC gleswFramebufferTexture2D; -PFNGLFRAMEBUFFERTEXTURE2DDOWNSAMPLEIMGPROC gleswFramebufferTexture2DDownsampleIMG; -PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEEXTPROC gleswFramebufferTexture2DMultisampleEXT; -PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEIMGPROC gleswFramebufferTexture2DMultisampleIMG; -PFNGLFRAMEBUFFERTEXTURE3DOESPROC gleswFramebufferTexture3DOES; -PFNGLFRAMEBUFFERTEXTUREEXTPROC gleswFramebufferTextureEXT; -PFNGLFRAMEBUFFERTEXTURELAYERPROC gleswFramebufferTextureLayer; -PFNGLFRAMEBUFFERTEXTURELAYERDOWNSAMPLEIMGPROC gleswFramebufferTextureLayerDownsampleIMG; -PFNGLFRAMEBUFFERTEXTUREMULTISAMPLEMULTIVIEWOVRPROC gleswFramebufferTextureMultisampleMultiviewOVR; -PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC gleswFramebufferTextureMultiviewOVR; -PFNGLFRAMEBUFFERTEXTUREOESPROC gleswFramebufferTextureOES; -PFNGLFRONTFACEPROC gleswFrontFace; -PFNGLGENBUFFERSPROC gleswGenBuffers; -PFNGLGENFENCESNVPROC gleswGenFencesNV; -PFNGLGENFRAMEBUFFERSPROC gleswGenFramebuffers; -PFNGLGENPATHSNVPROC gleswGenPathsNV; -PFNGLGENPERFMONITORSAMDPROC gleswGenPerfMonitorsAMD; -PFNGLGENPROGRAMPIPELINESEXTPROC gleswGenProgramPipelinesEXT; -PFNGLGENQUERIESPROC gleswGenQueries; -PFNGLGENQUERIESEXTPROC gleswGenQueriesEXT; -PFNGLGENRENDERBUFFERSPROC gleswGenRenderbuffers; -PFNGLGENSAMPLERSPROC gleswGenSamplers; -PFNGLGENTEXTURESPROC gleswGenTextures; -PFNGLGENTRANSFORMFEEDBACKSPROC gleswGenTransformFeedbacks; -PFNGLGENVERTEXARRAYSPROC gleswGenVertexArrays; -PFNGLGENVERTEXARRAYSOESPROC gleswGenVertexArraysOES; -PFNGLGENERATEMIPMAPPROC gleswGenerateMipmap; -PFNGLGETACTIVEATTRIBPROC gleswGetActiveAttrib; -PFNGLGETACTIVEUNIFORMPROC gleswGetActiveUniform; -PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC gleswGetActiveUniformBlockName; -PFNGLGETACTIVEUNIFORMBLOCKIVPROC gleswGetActiveUniformBlockiv; -PFNGLGETACTIVEUNIFORMSIVPROC gleswGetActiveUniformsiv; -PFNGLGETATTACHEDSHADERSPROC gleswGetAttachedShaders; -PFNGLGETATTRIBLOCATIONPROC gleswGetAttribLocation; -PFNGLGETBOOLEANVPROC gleswGetBooleanv; -PFNGLGETBUFFERPARAMETERI64VPROC gleswGetBufferParameteri64v; -PFNGLGETBUFFERPARAMETERIVPROC gleswGetBufferParameteriv; -PFNGLGETBUFFERPOINTERVPROC gleswGetBufferPointerv; -PFNGLGETBUFFERPOINTERVOESPROC gleswGetBufferPointervOES; -PFNGLGETCOVERAGEMODULATIONTABLENVPROC gleswGetCoverageModulationTableNV; -PFNGLGETDEBUGMESSAGELOGKHRPROC gleswGetDebugMessageLogKHR; -PFNGLGETDRIVERCONTROLSTRINGQCOMPROC gleswGetDriverControlStringQCOM; -PFNGLGETDRIVERCONTROLSQCOMPROC gleswGetDriverControlsQCOM; -PFNGLGETERRORPROC gleswGetError; -PFNGLGETFENCEIVNVPROC gleswGetFenceivNV; -PFNGLGETFIRSTPERFQUERYIDINTELPROC gleswGetFirstPerfQueryIdINTEL; -PFNGLGETFLOATI_VNVPROC gleswGetFloati_vNV; -PFNGLGETFLOATVPROC gleswGetFloatv; -PFNGLGETFRAGDATAINDEXEXTPROC gleswGetFragDataIndexEXT; -PFNGLGETFRAGDATALOCATIONPROC gleswGetFragDataLocation; -PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC gleswGetFramebufferAttachmentParameteriv; -PFNGLGETFRAMEBUFFERPIXELLOCALSTORAGESIZEEXTPROC gleswGetFramebufferPixelLocalStorageSizeEXT; -PFNGLGETGRAPHICSRESETSTATUSEXTPROC gleswGetGraphicsResetStatusEXT; -PFNGLGETGRAPHICSRESETSTATUSKHRPROC gleswGetGraphicsResetStatusKHR; -PFNGLGETIMAGEHANDLENVPROC gleswGetImageHandleNV; -PFNGLGETINTEGER64I_VPROC gleswGetInteger64i_v; -PFNGLGETINTEGER64VPROC gleswGetInteger64v; -PFNGLGETINTEGER64VAPPLEPROC gleswGetInteger64vAPPLE; -PFNGLGETINTEGERI_VPROC gleswGetIntegeri_v; -PFNGLGETINTEGERI_VEXTPROC gleswGetIntegeri_vEXT; -PFNGLGETINTEGERVPROC gleswGetIntegerv; -PFNGLGETINTERNALFORMATSAMPLEIVNVPROC gleswGetInternalformatSampleivNV; -PFNGLGETINTERNALFORMATIVPROC gleswGetInternalformativ; -PFNGLGETNEXTPERFQUERYIDINTELPROC gleswGetNextPerfQueryIdINTEL; -PFNGLGETOBJECTLABELEXTPROC gleswGetObjectLabelEXT; -PFNGLGETOBJECTLABELKHRPROC gleswGetObjectLabelKHR; -PFNGLGETOBJECTPTRLABELKHRPROC gleswGetObjectPtrLabelKHR; -PFNGLGETPATHCOMMANDSNVPROC gleswGetPathCommandsNV; -PFNGLGETPATHCOORDSNVPROC gleswGetPathCoordsNV; -PFNGLGETPATHDASHARRAYNVPROC gleswGetPathDashArrayNV; -PFNGLGETPATHLENGTHNVPROC gleswGetPathLengthNV; -PFNGLGETPATHMETRICRANGENVPROC gleswGetPathMetricRangeNV; -PFNGLGETPATHMETRICSNVPROC gleswGetPathMetricsNV; -PFNGLGETPATHPARAMETERFVNVPROC gleswGetPathParameterfvNV; -PFNGLGETPATHPARAMETERIVNVPROC gleswGetPathParameterivNV; -PFNGLGETPATHSPACINGNVPROC gleswGetPathSpacingNV; -PFNGLGETPERFCOUNTERINFOINTELPROC gleswGetPerfCounterInfoINTEL; -PFNGLGETPERFMONITORCOUNTERDATAAMDPROC gleswGetPerfMonitorCounterDataAMD; -PFNGLGETPERFMONITORCOUNTERINFOAMDPROC gleswGetPerfMonitorCounterInfoAMD; -PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC gleswGetPerfMonitorCounterStringAMD; -PFNGLGETPERFMONITORCOUNTERSAMDPROC gleswGetPerfMonitorCountersAMD; -PFNGLGETPERFMONITORGROUPSTRINGAMDPROC gleswGetPerfMonitorGroupStringAMD; -PFNGLGETPERFMONITORGROUPSAMDPROC gleswGetPerfMonitorGroupsAMD; -PFNGLGETPERFQUERYDATAINTELPROC gleswGetPerfQueryDataINTEL; -PFNGLGETPERFQUERYIDBYNAMEINTELPROC gleswGetPerfQueryIdByNameINTEL; -PFNGLGETPERFQUERYINFOINTELPROC gleswGetPerfQueryInfoINTEL; -PFNGLGETPOINTERVKHRPROC gleswGetPointervKHR; -PFNGLGETPROGRAMBINARYPROC gleswGetProgramBinary; -PFNGLGETPROGRAMBINARYOESPROC gleswGetProgramBinaryOES; -PFNGLGETPROGRAMINFOLOGPROC gleswGetProgramInfoLog; -PFNGLGETPROGRAMPIPELINEINFOLOGEXTPROC gleswGetProgramPipelineInfoLogEXT; -PFNGLGETPROGRAMPIPELINEIVEXTPROC gleswGetProgramPipelineivEXT; -PFNGLGETPROGRAMRESOURCELOCATIONINDEXEXTPROC gleswGetProgramResourceLocationIndexEXT; -PFNGLGETPROGRAMRESOURCEFVNVPROC gleswGetProgramResourcefvNV; -PFNGLGETPROGRAMIVPROC gleswGetProgramiv; -PFNGLGETQUERYOBJECTI64VEXTPROC gleswGetQueryObjecti64vEXT; -PFNGLGETQUERYOBJECTIVEXTPROC gleswGetQueryObjectivEXT; -PFNGLGETQUERYOBJECTUI64VEXTPROC gleswGetQueryObjectui64vEXT; -PFNGLGETQUERYOBJECTUIVPROC gleswGetQueryObjectuiv; -PFNGLGETQUERYOBJECTUIVEXTPROC gleswGetQueryObjectuivEXT; -PFNGLGETQUERYIVPROC gleswGetQueryiv; -PFNGLGETQUERYIVEXTPROC gleswGetQueryivEXT; -PFNGLGETRENDERBUFFERPARAMETERIVPROC gleswGetRenderbufferParameteriv; -PFNGLGETSAMPLERPARAMETERIIVEXTPROC gleswGetSamplerParameterIivEXT; -PFNGLGETSAMPLERPARAMETERIIVOESPROC gleswGetSamplerParameterIivOES; -PFNGLGETSAMPLERPARAMETERIUIVEXTPROC gleswGetSamplerParameterIuivEXT; -PFNGLGETSAMPLERPARAMETERIUIVOESPROC gleswGetSamplerParameterIuivOES; -PFNGLGETSAMPLERPARAMETERFVPROC gleswGetSamplerParameterfv; -PFNGLGETSAMPLERPARAMETERIVPROC gleswGetSamplerParameteriv; -PFNGLGETSHADERINFOLOGPROC gleswGetShaderInfoLog; -PFNGLGETSHADERPRECISIONFORMATPROC gleswGetShaderPrecisionFormat; -PFNGLGETSHADERSOURCEPROC gleswGetShaderSource; -PFNGLGETSHADERIVPROC gleswGetShaderiv; -PFNGLGETSTRINGPROC gleswGetString; -PFNGLGETSTRINGIPROC gleswGetStringi; -PFNGLGETSYNCIVPROC gleswGetSynciv; -PFNGLGETSYNCIVAPPLEPROC gleswGetSyncivAPPLE; -PFNGLGETTEXPARAMETERIIVEXTPROC gleswGetTexParameterIivEXT; -PFNGLGETTEXPARAMETERIIVOESPROC gleswGetTexParameterIivOES; -PFNGLGETTEXPARAMETERIUIVEXTPROC gleswGetTexParameterIuivEXT; -PFNGLGETTEXPARAMETERIUIVOESPROC gleswGetTexParameterIuivOES; -PFNGLGETTEXPARAMETERFVPROC gleswGetTexParameterfv; -PFNGLGETTEXPARAMETERIVPROC gleswGetTexParameteriv; -PFNGLGETTEXTUREHANDLENVPROC gleswGetTextureHandleNV; -PFNGLGETTEXTURESAMPLERHANDLENVPROC gleswGetTextureSamplerHandleNV; -PFNGLGETTRANSFORMFEEDBACKVARYINGPROC gleswGetTransformFeedbackVarying; -PFNGLGETTRANSLATEDSHADERSOURCEANGLEPROC gleswGetTranslatedShaderSourceANGLE; -PFNGLGETUNIFORMBLOCKINDEXPROC gleswGetUniformBlockIndex; -PFNGLGETUNIFORMINDICESPROC gleswGetUniformIndices; -PFNGLGETUNIFORMLOCATIONPROC gleswGetUniformLocation; -PFNGLGETUNIFORMFVPROC gleswGetUniformfv; -PFNGLGETUNIFORMIVPROC gleswGetUniformiv; -PFNGLGETUNIFORMUIVPROC gleswGetUniformuiv; -PFNGLGETVERTEXATTRIBIIVPROC gleswGetVertexAttribIiv; -PFNGLGETVERTEXATTRIBIUIVPROC gleswGetVertexAttribIuiv; -PFNGLGETVERTEXATTRIBPOINTERVPROC gleswGetVertexAttribPointerv; -PFNGLGETVERTEXATTRIBFVPROC gleswGetVertexAttribfv; -PFNGLGETVERTEXATTRIBIVPROC gleswGetVertexAttribiv; -PFNGLGETNUNIFORMFVEXTPROC gleswGetnUniformfvEXT; -PFNGLGETNUNIFORMFVKHRPROC gleswGetnUniformfvKHR; -PFNGLGETNUNIFORMIVEXTPROC gleswGetnUniformivEXT; -PFNGLGETNUNIFORMIVKHRPROC gleswGetnUniformivKHR; -PFNGLGETNUNIFORMUIVKHRPROC gleswGetnUniformuivKHR; -PFNGLHINTPROC gleswHint; -PFNGLINSERTEVENTMARKEREXTPROC gleswInsertEventMarkerEXT; -PFNGLINTERPOLATEPATHSNVPROC gleswInterpolatePathsNV; -PFNGLINVALIDATEFRAMEBUFFERPROC gleswInvalidateFramebuffer; -PFNGLINVALIDATESUBFRAMEBUFFERPROC gleswInvalidateSubFramebuffer; -PFNGLISBUFFERPROC gleswIsBuffer; -PFNGLISENABLEDPROC gleswIsEnabled; -PFNGLISENABLEDIEXTPROC gleswIsEnablediEXT; -PFNGLISENABLEDINVPROC gleswIsEnablediNV; -PFNGLISENABLEDIOESPROC gleswIsEnablediOES; -PFNGLISFENCENVPROC gleswIsFenceNV; -PFNGLISFRAMEBUFFERPROC gleswIsFramebuffer; -PFNGLISIMAGEHANDLERESIDENTNVPROC gleswIsImageHandleResidentNV; -PFNGLISPATHNVPROC gleswIsPathNV; -PFNGLISPOINTINFILLPATHNVPROC gleswIsPointInFillPathNV; -PFNGLISPOINTINSTROKEPATHNVPROC gleswIsPointInStrokePathNV; -PFNGLISPROGRAMPROC gleswIsProgram; -PFNGLISPROGRAMPIPELINEEXTPROC gleswIsProgramPipelineEXT; -PFNGLISQUERYPROC gleswIsQuery; -PFNGLISQUERYEXTPROC gleswIsQueryEXT; -PFNGLISRENDERBUFFERPROC gleswIsRenderbuffer; -PFNGLISSAMPLERPROC gleswIsSampler; -PFNGLISSHADERPROC gleswIsShader; -PFNGLISSYNCPROC gleswIsSync; -PFNGLISSYNCAPPLEPROC gleswIsSyncAPPLE; -PFNGLISTEXTUREPROC gleswIsTexture; -PFNGLISTEXTUREHANDLERESIDENTNVPROC gleswIsTextureHandleResidentNV; -PFNGLISTRANSFORMFEEDBACKPROC gleswIsTransformFeedback; -PFNGLISVERTEXARRAYPROC gleswIsVertexArray; -PFNGLISVERTEXARRAYOESPROC gleswIsVertexArrayOES; -PFNGLLABELOBJECTEXTPROC gleswLabelObjectEXT; -PFNGLLINEWIDTHPROC gleswLineWidth; -PFNGLLINKPROGRAMPROC gleswLinkProgram; -PFNGLMAKEIMAGEHANDLENONRESIDENTNVPROC gleswMakeImageHandleNonResidentNV; -PFNGLMAKEIMAGEHANDLERESIDENTNVPROC gleswMakeImageHandleResidentNV; -PFNGLMAKETEXTUREHANDLENONRESIDENTNVPROC gleswMakeTextureHandleNonResidentNV; -PFNGLMAKETEXTUREHANDLERESIDENTNVPROC gleswMakeTextureHandleResidentNV; -PFNGLMAPBUFFEROESPROC gleswMapBufferOES; -PFNGLMAPBUFFERRANGEPROC gleswMapBufferRange; -PFNGLMAPBUFFERRANGEEXTPROC gleswMapBufferRangeEXT; -PFNGLMATRIXLOAD3X2FNVPROC gleswMatrixLoad3x2fNV; -PFNGLMATRIXLOAD3X3FNVPROC gleswMatrixLoad3x3fNV; -PFNGLMATRIXLOADTRANSPOSE3X3FNVPROC gleswMatrixLoadTranspose3x3fNV; -PFNGLMATRIXMULT3X2FNVPROC gleswMatrixMult3x2fNV; -PFNGLMATRIXMULT3X3FNVPROC gleswMatrixMult3x3fNV; -PFNGLMATRIXMULTTRANSPOSE3X3FNVPROC gleswMatrixMultTranspose3x3fNV; -PFNGLMINSAMPLESHADINGOESPROC gleswMinSampleShadingOES; -PFNGLMULTIDRAWARRAYSEXTPROC gleswMultiDrawArraysEXT; -PFNGLMULTIDRAWARRAYSINDIRECTEXTPROC gleswMultiDrawArraysIndirectEXT; -PFNGLMULTIDRAWELEMENTSBASEVERTEXEXTPROC gleswMultiDrawElementsBaseVertexEXT; -PFNGLMULTIDRAWELEMENTSBASEVERTEXOESPROC gleswMultiDrawElementsBaseVertexOES; -PFNGLMULTIDRAWELEMENTSEXTPROC gleswMultiDrawElementsEXT; -PFNGLMULTIDRAWELEMENTSINDIRECTEXTPROC gleswMultiDrawElementsIndirectEXT; -PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVNVPROC gleswNamedFramebufferSampleLocationsfvNV; -PFNGLOBJECTLABELKHRPROC gleswObjectLabelKHR; -PFNGLOBJECTPTRLABELKHRPROC gleswObjectPtrLabelKHR; -PFNGLPATCHPARAMETERIEXTPROC gleswPatchParameteriEXT; -PFNGLPATCHPARAMETERIOESPROC gleswPatchParameteriOES; -PFNGLPATHCOMMANDSNVPROC gleswPathCommandsNV; -PFNGLPATHCOORDSNVPROC gleswPathCoordsNV; -PFNGLPATHCOVERDEPTHFUNCNVPROC gleswPathCoverDepthFuncNV; -PFNGLPATHDASHARRAYNVPROC gleswPathDashArrayNV; -PFNGLPATHGLYPHINDEXARRAYNVPROC gleswPathGlyphIndexArrayNV; -PFNGLPATHGLYPHINDEXRANGENVPROC gleswPathGlyphIndexRangeNV; -PFNGLPATHGLYPHRANGENVPROC gleswPathGlyphRangeNV; -PFNGLPATHGLYPHSNVPROC gleswPathGlyphsNV; -PFNGLPATHMEMORYGLYPHINDEXARRAYNVPROC gleswPathMemoryGlyphIndexArrayNV; -PFNGLPATHPARAMETERFNVPROC gleswPathParameterfNV; -PFNGLPATHPARAMETERFVNVPROC gleswPathParameterfvNV; -PFNGLPATHPARAMETERINVPROC gleswPathParameteriNV; -PFNGLPATHPARAMETERIVNVPROC gleswPathParameterivNV; -PFNGLPATHSTENCILDEPTHOFFSETNVPROC gleswPathStencilDepthOffsetNV; -PFNGLPATHSTENCILFUNCNVPROC gleswPathStencilFuncNV; -PFNGLPATHSTRINGNVPROC gleswPathStringNV; -PFNGLPATHSUBCOMMANDSNVPROC gleswPathSubCommandsNV; -PFNGLPATHSUBCOORDSNVPROC gleswPathSubCoordsNV; -PFNGLPAUSETRANSFORMFEEDBACKPROC gleswPauseTransformFeedback; -PFNGLPIXELSTOREIPROC gleswPixelStorei; -PFNGLPOINTALONGPATHNVPROC gleswPointAlongPathNV; -PFNGLPOLYGONMODENVPROC gleswPolygonModeNV; -PFNGLPOLYGONOFFSETPROC gleswPolygonOffset; -PFNGLPOLYGONOFFSETCLAMPEXTPROC gleswPolygonOffsetClampEXT; -PFNGLPOPDEBUGGROUPKHRPROC gleswPopDebugGroupKHR; -PFNGLPOPGROUPMARKEREXTPROC gleswPopGroupMarkerEXT; -PFNGLPRIMITIVEBOUNDINGBOXEXTPROC gleswPrimitiveBoundingBoxEXT; -PFNGLPRIMITIVEBOUNDINGBOXOESPROC gleswPrimitiveBoundingBoxOES; -PFNGLPROGRAMBINARYPROC gleswProgramBinary; -PFNGLPROGRAMBINARYOESPROC gleswProgramBinaryOES; -PFNGLPROGRAMPARAMETERIPROC gleswProgramParameteri; -PFNGLPROGRAMPARAMETERIEXTPROC gleswProgramParameteriEXT; -PFNGLPROGRAMPATHFRAGMENTINPUTGENNVPROC gleswProgramPathFragmentInputGenNV; -PFNGLPROGRAMUNIFORM1FEXTPROC gleswProgramUniform1fEXT; -PFNGLPROGRAMUNIFORM1FVEXTPROC gleswProgramUniform1fvEXT; -PFNGLPROGRAMUNIFORM1IEXTPROC gleswProgramUniform1iEXT; -PFNGLPROGRAMUNIFORM1IVEXTPROC gleswProgramUniform1ivEXT; -PFNGLPROGRAMUNIFORM1UIEXTPROC gleswProgramUniform1uiEXT; -PFNGLPROGRAMUNIFORM1UIVEXTPROC gleswProgramUniform1uivEXT; -PFNGLPROGRAMUNIFORM2FEXTPROC gleswProgramUniform2fEXT; -PFNGLPROGRAMUNIFORM2FVEXTPROC gleswProgramUniform2fvEXT; -PFNGLPROGRAMUNIFORM2IEXTPROC gleswProgramUniform2iEXT; -PFNGLPROGRAMUNIFORM2IVEXTPROC gleswProgramUniform2ivEXT; -PFNGLPROGRAMUNIFORM2UIEXTPROC gleswProgramUniform2uiEXT; -PFNGLPROGRAMUNIFORM2UIVEXTPROC gleswProgramUniform2uivEXT; -PFNGLPROGRAMUNIFORM3FEXTPROC gleswProgramUniform3fEXT; -PFNGLPROGRAMUNIFORM3FVEXTPROC gleswProgramUniform3fvEXT; -PFNGLPROGRAMUNIFORM3IEXTPROC gleswProgramUniform3iEXT; -PFNGLPROGRAMUNIFORM3IVEXTPROC gleswProgramUniform3ivEXT; -PFNGLPROGRAMUNIFORM3UIEXTPROC gleswProgramUniform3uiEXT; -PFNGLPROGRAMUNIFORM3UIVEXTPROC gleswProgramUniform3uivEXT; -PFNGLPROGRAMUNIFORM4FEXTPROC gleswProgramUniform4fEXT; -PFNGLPROGRAMUNIFORM4FVEXTPROC gleswProgramUniform4fvEXT; -PFNGLPROGRAMUNIFORM4IEXTPROC gleswProgramUniform4iEXT; -PFNGLPROGRAMUNIFORM4IVEXTPROC gleswProgramUniform4ivEXT; -PFNGLPROGRAMUNIFORM4UIEXTPROC gleswProgramUniform4uiEXT; -PFNGLPROGRAMUNIFORM4UIVEXTPROC gleswProgramUniform4uivEXT; -PFNGLPROGRAMUNIFORMHANDLEUI64NVPROC gleswProgramUniformHandleui64NV; -PFNGLPROGRAMUNIFORMHANDLEUI64VNVPROC gleswProgramUniformHandleui64vNV; -PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC gleswProgramUniformMatrix2fvEXT; -PFNGLPROGRAMUNIFORMMATRIX2X3FVEXTPROC gleswProgramUniformMatrix2x3fvEXT; -PFNGLPROGRAMUNIFORMMATRIX2X4FVEXTPROC gleswProgramUniformMatrix2x4fvEXT; -PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC gleswProgramUniformMatrix3fvEXT; -PFNGLPROGRAMUNIFORMMATRIX3X2FVEXTPROC gleswProgramUniformMatrix3x2fvEXT; -PFNGLPROGRAMUNIFORMMATRIX3X4FVEXTPROC gleswProgramUniformMatrix3x4fvEXT; -PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC gleswProgramUniformMatrix4fvEXT; -PFNGLPROGRAMUNIFORMMATRIX4X2FVEXTPROC gleswProgramUniformMatrix4x2fvEXT; -PFNGLPROGRAMUNIFORMMATRIX4X3FVEXTPROC gleswProgramUniformMatrix4x3fvEXT; -PFNGLPUSHDEBUGGROUPKHRPROC gleswPushDebugGroupKHR; -PFNGLPUSHGROUPMARKEREXTPROC gleswPushGroupMarkerEXT; -PFNGLQUERYCOUNTEREXTPROC gleswQueryCounterEXT; -PFNGLRASTERSAMPLESEXTPROC gleswRasterSamplesEXT; -PFNGLREADBUFFERPROC gleswReadBuffer; -PFNGLREADBUFFERINDEXEDEXTPROC gleswReadBufferIndexedEXT; -PFNGLREADBUFFERNVPROC gleswReadBufferNV; -PFNGLREADPIXELSPROC gleswReadPixels; -PFNGLREADNPIXELSEXTPROC gleswReadnPixelsEXT; -PFNGLREADNPIXELSKHRPROC gleswReadnPixelsKHR; -PFNGLRELEASESHADERCOMPILERPROC gleswReleaseShaderCompiler; -PFNGLRENDERBUFFERSTORAGEPROC gleswRenderbufferStorage; -PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC gleswRenderbufferStorageMultisample; -PFNGLRENDERBUFFERSTORAGEMULTISAMPLEANGLEPROC gleswRenderbufferStorageMultisampleANGLE; -PFNGLRENDERBUFFERSTORAGEMULTISAMPLEAPPLEPROC gleswRenderbufferStorageMultisampleAPPLE; -PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC gleswRenderbufferStorageMultisampleEXT; -PFNGLRENDERBUFFERSTORAGEMULTISAMPLEIMGPROC gleswRenderbufferStorageMultisampleIMG; -PFNGLRENDERBUFFERSTORAGEMULTISAMPLENVPROC gleswRenderbufferStorageMultisampleNV; -PFNGLRESOLVEDEPTHVALUESNVPROC gleswResolveDepthValuesNV; -PFNGLRESOLVEMULTISAMPLEFRAMEBUFFERAPPLEPROC gleswResolveMultisampleFramebufferAPPLE; -PFNGLRESUMETRANSFORMFEEDBACKPROC gleswResumeTransformFeedback; -PFNGLSAMPLECOVERAGEPROC gleswSampleCoverage; -PFNGLSAMPLERPARAMETERIIVEXTPROC gleswSamplerParameterIivEXT; -PFNGLSAMPLERPARAMETERIIVOESPROC gleswSamplerParameterIivOES; -PFNGLSAMPLERPARAMETERIUIVEXTPROC gleswSamplerParameterIuivEXT; -PFNGLSAMPLERPARAMETERIUIVOESPROC gleswSamplerParameterIuivOES; -PFNGLSAMPLERPARAMETERFPROC gleswSamplerParameterf; -PFNGLSAMPLERPARAMETERFVPROC gleswSamplerParameterfv; -PFNGLSAMPLERPARAMETERIPROC gleswSamplerParameteri; -PFNGLSAMPLERPARAMETERIVPROC gleswSamplerParameteriv; -PFNGLSCISSORPROC gleswScissor; -PFNGLSCISSORARRAYVNVPROC gleswScissorArrayvNV; -PFNGLSCISSORINDEXEDNVPROC gleswScissorIndexedNV; -PFNGLSCISSORINDEXEDVNVPROC gleswScissorIndexedvNV; -PFNGLSELECTPERFMONITORCOUNTERSAMDPROC gleswSelectPerfMonitorCountersAMD; -PFNGLSETFENCENVPROC gleswSetFenceNV; -PFNGLSHADERBINARYPROC gleswShaderBinary; -PFNGLSHADERSOURCEPROC gleswShaderSource; -PFNGLSTARTTILINGQCOMPROC gleswStartTilingQCOM; -PFNGLSTENCILFILLPATHINSTANCEDNVPROC gleswStencilFillPathInstancedNV; -PFNGLSTENCILFILLPATHNVPROC gleswStencilFillPathNV; -PFNGLSTENCILFUNCPROC gleswStencilFunc; -PFNGLSTENCILFUNCSEPARATEPROC gleswStencilFuncSeparate; -PFNGLSTENCILMASKPROC gleswStencilMask; -PFNGLSTENCILMASKSEPARATEPROC gleswStencilMaskSeparate; -PFNGLSTENCILOPPROC gleswStencilOp; -PFNGLSTENCILOPSEPARATEPROC gleswStencilOpSeparate; -PFNGLSTENCILSTROKEPATHINSTANCEDNVPROC gleswStencilStrokePathInstancedNV; -PFNGLSTENCILSTROKEPATHNVPROC gleswStencilStrokePathNV; -PFNGLSTENCILTHENCOVERFILLPATHINSTANCEDNVPROC gleswStencilThenCoverFillPathInstancedNV; -PFNGLSTENCILTHENCOVERFILLPATHNVPROC gleswStencilThenCoverFillPathNV; -PFNGLSTENCILTHENCOVERSTROKEPATHINSTANCEDNVPROC gleswStencilThenCoverStrokePathInstancedNV; -PFNGLSTENCILTHENCOVERSTROKEPATHNVPROC gleswStencilThenCoverStrokePathNV; -PFNGLSUBPIXELPRECISIONBIASNVPROC gleswSubpixelPrecisionBiasNV; -PFNGLTESTFENCENVPROC gleswTestFenceNV; -PFNGLTEXBUFFEREXTPROC gleswTexBufferEXT; -PFNGLTEXBUFFEROESPROC gleswTexBufferOES; -PFNGLTEXBUFFERRANGEEXTPROC gleswTexBufferRangeEXT; -PFNGLTEXBUFFERRANGEOESPROC gleswTexBufferRangeOES; -PFNGLTEXIMAGE2DPROC gleswTexImage2D; -PFNGLTEXIMAGE3DPROC gleswTexImage3D; -PFNGLTEXIMAGE3DOESPROC gleswTexImage3DOES; -PFNGLTEXPAGECOMMITMENTEXTPROC gleswTexPageCommitmentEXT; -PFNGLTEXPARAMETERIIVEXTPROC gleswTexParameterIivEXT; -PFNGLTEXPARAMETERIIVOESPROC gleswTexParameterIivOES; -PFNGLTEXPARAMETERIUIVEXTPROC gleswTexParameterIuivEXT; -PFNGLTEXPARAMETERIUIVOESPROC gleswTexParameterIuivOES; -PFNGLTEXPARAMETERFPROC gleswTexParameterf; -PFNGLTEXPARAMETERFVPROC gleswTexParameterfv; -PFNGLTEXPARAMETERIPROC gleswTexParameteri; -PFNGLTEXPARAMETERIVPROC gleswTexParameteriv; -PFNGLTEXSTORAGE1DEXTPROC gleswTexStorage1DEXT; -PFNGLTEXSTORAGE2DPROC gleswTexStorage2D; -PFNGLTEXSTORAGE2DEXTPROC gleswTexStorage2DEXT; -PFNGLTEXSTORAGE3DPROC gleswTexStorage3D; -PFNGLTEXSTORAGE3DEXTPROC gleswTexStorage3DEXT; -PFNGLTEXSTORAGE3DMULTISAMPLEOESPROC gleswTexStorage3DMultisampleOES; -PFNGLTEXSUBIMAGE2DPROC gleswTexSubImage2D; -PFNGLTEXSUBIMAGE3DPROC gleswTexSubImage3D; -PFNGLTEXSUBIMAGE3DOESPROC gleswTexSubImage3DOES; -PFNGLTEXTURESTORAGE1DEXTPROC gleswTextureStorage1DEXT; -PFNGLTEXTURESTORAGE2DEXTPROC gleswTextureStorage2DEXT; -PFNGLTEXTURESTORAGE3DEXTPROC gleswTextureStorage3DEXT; -PFNGLTEXTUREVIEWEXTPROC gleswTextureViewEXT; -PFNGLTEXTUREVIEWOESPROC gleswTextureViewOES; -PFNGLTRANSFORMFEEDBACKVARYINGSPROC gleswTransformFeedbackVaryings; -PFNGLTRANSFORMPATHNVPROC gleswTransformPathNV; -PFNGLUNIFORM1FPROC gleswUniform1f; -PFNGLUNIFORM1FVPROC gleswUniform1fv; -PFNGLUNIFORM1IPROC gleswUniform1i; -PFNGLUNIFORM1IVPROC gleswUniform1iv; -PFNGLUNIFORM1UIPROC gleswUniform1ui; -PFNGLUNIFORM1UIVPROC gleswUniform1uiv; -PFNGLUNIFORM2FPROC gleswUniform2f; -PFNGLUNIFORM2FVPROC gleswUniform2fv; -PFNGLUNIFORM2IPROC gleswUniform2i; -PFNGLUNIFORM2IVPROC gleswUniform2iv; -PFNGLUNIFORM2UIPROC gleswUniform2ui; -PFNGLUNIFORM2UIVPROC gleswUniform2uiv; -PFNGLUNIFORM3FPROC gleswUniform3f; -PFNGLUNIFORM3FVPROC gleswUniform3fv; -PFNGLUNIFORM3IPROC gleswUniform3i; -PFNGLUNIFORM3IVPROC gleswUniform3iv; -PFNGLUNIFORM3UIPROC gleswUniform3ui; -PFNGLUNIFORM3UIVPROC gleswUniform3uiv; -PFNGLUNIFORM4FPROC gleswUniform4f; -PFNGLUNIFORM4FVPROC gleswUniform4fv; -PFNGLUNIFORM4IPROC gleswUniform4i; -PFNGLUNIFORM4IVPROC gleswUniform4iv; -PFNGLUNIFORM4UIPROC gleswUniform4ui; -PFNGLUNIFORM4UIVPROC gleswUniform4uiv; -PFNGLUNIFORMBLOCKBINDINGPROC gleswUniformBlockBinding; -PFNGLUNIFORMHANDLEUI64NVPROC gleswUniformHandleui64NV; -PFNGLUNIFORMHANDLEUI64VNVPROC gleswUniformHandleui64vNV; -PFNGLUNIFORMMATRIX2FVPROC gleswUniformMatrix2fv; -PFNGLUNIFORMMATRIX2X3FVPROC gleswUniformMatrix2x3fv; -PFNGLUNIFORMMATRIX2X3FVNVPROC gleswUniformMatrix2x3fvNV; -PFNGLUNIFORMMATRIX2X4FVPROC gleswUniformMatrix2x4fv; -PFNGLUNIFORMMATRIX2X4FVNVPROC gleswUniformMatrix2x4fvNV; -PFNGLUNIFORMMATRIX3FVPROC gleswUniformMatrix3fv; -PFNGLUNIFORMMATRIX3X2FVPROC gleswUniformMatrix3x2fv; -PFNGLUNIFORMMATRIX3X2FVNVPROC gleswUniformMatrix3x2fvNV; -PFNGLUNIFORMMATRIX3X4FVPROC gleswUniformMatrix3x4fv; -PFNGLUNIFORMMATRIX3X4FVNVPROC gleswUniformMatrix3x4fvNV; -PFNGLUNIFORMMATRIX4FVPROC gleswUniformMatrix4fv; -PFNGLUNIFORMMATRIX4X2FVPROC gleswUniformMatrix4x2fv; -PFNGLUNIFORMMATRIX4X2FVNVPROC gleswUniformMatrix4x2fvNV; -PFNGLUNIFORMMATRIX4X3FVPROC gleswUniformMatrix4x3fv; -PFNGLUNIFORMMATRIX4X3FVNVPROC gleswUniformMatrix4x3fvNV; -PFNGLUNMAPBUFFERPROC gleswUnmapBuffer; -PFNGLUNMAPBUFFEROESPROC gleswUnmapBufferOES; -PFNGLUSEPROGRAMPROC gleswUseProgram; -PFNGLUSEPROGRAMSTAGESEXTPROC gleswUseProgramStagesEXT; -PFNGLVALIDATEPROGRAMPROC gleswValidateProgram; -PFNGLVALIDATEPROGRAMPIPELINEEXTPROC gleswValidateProgramPipelineEXT; -PFNGLVERTEXATTRIB1FPROC gleswVertexAttrib1f; -PFNGLVERTEXATTRIB1FVPROC gleswVertexAttrib1fv; -PFNGLVERTEXATTRIB2FPROC gleswVertexAttrib2f; -PFNGLVERTEXATTRIB2FVPROC gleswVertexAttrib2fv; -PFNGLVERTEXATTRIB3FPROC gleswVertexAttrib3f; -PFNGLVERTEXATTRIB3FVPROC gleswVertexAttrib3fv; -PFNGLVERTEXATTRIB4FPROC gleswVertexAttrib4f; -PFNGLVERTEXATTRIB4FVPROC gleswVertexAttrib4fv; -PFNGLVERTEXATTRIBDIVISORPROC gleswVertexAttribDivisor; -PFNGLVERTEXATTRIBDIVISORANGLEPROC gleswVertexAttribDivisorANGLE; -PFNGLVERTEXATTRIBDIVISOREXTPROC gleswVertexAttribDivisorEXT; -PFNGLVERTEXATTRIBDIVISORNVPROC gleswVertexAttribDivisorNV; -PFNGLVERTEXATTRIBI4IPROC gleswVertexAttribI4i; -PFNGLVERTEXATTRIBI4IVPROC gleswVertexAttribI4iv; -PFNGLVERTEXATTRIBI4UIPROC gleswVertexAttribI4ui; -PFNGLVERTEXATTRIBI4UIVPROC gleswVertexAttribI4uiv; -PFNGLVERTEXATTRIBIPOINTERPROC gleswVertexAttribIPointer; -PFNGLVERTEXATTRIBPOINTERPROC gleswVertexAttribPointer; -PFNGLVIEWPORTPROC gleswViewport; -PFNGLVIEWPORTARRAYVNVPROC gleswViewportArrayvNV; -PFNGLVIEWPORTINDEXEDFNVPROC gleswViewportIndexedfNV; -PFNGLVIEWPORTINDEXEDFVNVPROC gleswViewportIndexedfvNV; -PFNGLWAITSYNCPROC gleswWaitSync; -PFNGLWAITSYNCAPPLEPROC gleswWaitSyncAPPLE; -PFNGLWEIGHTPATHSNVPROC gleswWeightPathsNV; - -static void load_procs(GLESWGetProcAddressProc proc) -{ - gleswActiveShaderProgramEXT = (PFNGLACTIVESHADERPROGRAMEXTPROC)proc("glActiveShaderProgramEXT"); - gleswActiveTexture = (PFNGLACTIVETEXTUREPROC)proc("glActiveTexture"); - gleswAlphaFuncQCOM = (PFNGLALPHAFUNCQCOMPROC)proc("glAlphaFuncQCOM"); - gleswApplyFramebufferAttachmentCMAAINTEL = (PFNGLAPPLYFRAMEBUFFERATTACHMENTCMAAINTELPROC)proc("glApplyFramebufferAttachmentCMAAINTEL"); - gleswAttachShader = (PFNGLATTACHSHADERPROC)proc("glAttachShader"); - gleswBeginConditionalRenderNV = (PFNGLBEGINCONDITIONALRENDERNVPROC)proc("glBeginConditionalRenderNV"); - gleswBeginPerfMonitorAMD = (PFNGLBEGINPERFMONITORAMDPROC)proc("glBeginPerfMonitorAMD"); - gleswBeginPerfQueryINTEL = (PFNGLBEGINPERFQUERYINTELPROC)proc("glBeginPerfQueryINTEL"); - gleswBeginQuery = (PFNGLBEGINQUERYPROC)proc("glBeginQuery"); - gleswBeginQueryEXT = (PFNGLBEGINQUERYEXTPROC)proc("glBeginQueryEXT"); - gleswBeginTransformFeedback = (PFNGLBEGINTRANSFORMFEEDBACKPROC)proc("glBeginTransformFeedback"); - gleswBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)proc("glBindAttribLocation"); - gleswBindBuffer = (PFNGLBINDBUFFERPROC)proc("glBindBuffer"); - gleswBindBufferBase = (PFNGLBINDBUFFERBASEPROC)proc("glBindBufferBase"); - gleswBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)proc("glBindBufferRange"); - gleswBindFragDataLocationEXT = (PFNGLBINDFRAGDATALOCATIONEXTPROC)proc("glBindFragDataLocationEXT"); - gleswBindFragDataLocationIndexedEXT = (PFNGLBINDFRAGDATALOCATIONINDEXEDEXTPROC)proc("glBindFragDataLocationIndexedEXT"); - gleswBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)proc("glBindFramebuffer"); - gleswBindProgramPipelineEXT = (PFNGLBINDPROGRAMPIPELINEEXTPROC)proc("glBindProgramPipelineEXT"); - gleswBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)proc("glBindRenderbuffer"); - gleswBindSampler = (PFNGLBINDSAMPLERPROC)proc("glBindSampler"); - gleswBindTexture = (PFNGLBINDTEXTUREPROC)proc("glBindTexture"); - gleswBindTransformFeedback = (PFNGLBINDTRANSFORMFEEDBACKPROC)proc("glBindTransformFeedback"); - gleswBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)proc("glBindVertexArray"); - gleswBindVertexArrayOES = (PFNGLBINDVERTEXARRAYOESPROC)proc("glBindVertexArrayOES"); - gleswBlendBarrierKHR = (PFNGLBLENDBARRIERKHRPROC)proc("glBlendBarrierKHR"); - gleswBlendBarrierNV = (PFNGLBLENDBARRIERNVPROC)proc("glBlendBarrierNV"); - gleswBlendColor = (PFNGLBLENDCOLORPROC)proc("glBlendColor"); - gleswBlendEquation = (PFNGLBLENDEQUATIONPROC)proc("glBlendEquation"); - gleswBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)proc("glBlendEquationSeparate"); - gleswBlendEquationSeparateiEXT = (PFNGLBLENDEQUATIONSEPARATEIEXTPROC)proc("glBlendEquationSeparateiEXT"); - gleswBlendEquationSeparateiOES = (PFNGLBLENDEQUATIONSEPARATEIOESPROC)proc("glBlendEquationSeparateiOES"); - gleswBlendEquationiEXT = (PFNGLBLENDEQUATIONIEXTPROC)proc("glBlendEquationiEXT"); - gleswBlendEquationiOES = (PFNGLBLENDEQUATIONIOESPROC)proc("glBlendEquationiOES"); - gleswBlendFunc = (PFNGLBLENDFUNCPROC)proc("glBlendFunc"); - gleswBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)proc("glBlendFuncSeparate"); - gleswBlendFuncSeparateiEXT = (PFNGLBLENDFUNCSEPARATEIEXTPROC)proc("glBlendFuncSeparateiEXT"); - gleswBlendFuncSeparateiOES = (PFNGLBLENDFUNCSEPARATEIOESPROC)proc("glBlendFuncSeparateiOES"); - gleswBlendFunciEXT = (PFNGLBLENDFUNCIEXTPROC)proc("glBlendFunciEXT"); - gleswBlendFunciOES = (PFNGLBLENDFUNCIOESPROC)proc("glBlendFunciOES"); - gleswBlendParameteriNV = (PFNGLBLENDPARAMETERINVPROC)proc("glBlendParameteriNV"); - gleswBlitFramebuffer = (PFNGLBLITFRAMEBUFFERPROC)proc("glBlitFramebuffer"); - gleswBlitFramebufferANGLE = (PFNGLBLITFRAMEBUFFERANGLEPROC)proc("glBlitFramebufferANGLE"); - gleswBlitFramebufferNV = (PFNGLBLITFRAMEBUFFERNVPROC)proc("glBlitFramebufferNV"); - gleswBufferData = (PFNGLBUFFERDATAPROC)proc("glBufferData"); - gleswBufferStorageEXT = (PFNGLBUFFERSTORAGEEXTPROC)proc("glBufferStorageEXT"); - gleswBufferSubData = (PFNGLBUFFERSUBDATAPROC)proc("glBufferSubData"); - gleswCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)proc("glCheckFramebufferStatus"); - gleswClear = (PFNGLCLEARPROC)proc("glClear"); - gleswClearBufferfi = (PFNGLCLEARBUFFERFIPROC)proc("glClearBufferfi"); - gleswClearBufferfv = (PFNGLCLEARBUFFERFVPROC)proc("glClearBufferfv"); - gleswClearBufferiv = (PFNGLCLEARBUFFERIVPROC)proc("glClearBufferiv"); - gleswClearBufferuiv = (PFNGLCLEARBUFFERUIVPROC)proc("glClearBufferuiv"); - gleswClearColor = (PFNGLCLEARCOLORPROC)proc("glClearColor"); - gleswClearDepthf = (PFNGLCLEARDEPTHFPROC)proc("glClearDepthf"); - gleswClearPixelLocalStorageuiEXT = (PFNGLCLEARPIXELLOCALSTORAGEUIEXTPROC)proc("glClearPixelLocalStorageuiEXT"); - gleswClearStencil = (PFNGLCLEARSTENCILPROC)proc("glClearStencil"); - gleswClientWaitSync = (PFNGLCLIENTWAITSYNCPROC)proc("glClientWaitSync"); - gleswClientWaitSyncAPPLE = (PFNGLCLIENTWAITSYNCAPPLEPROC)proc("glClientWaitSyncAPPLE"); - gleswColorMask = (PFNGLCOLORMASKPROC)proc("glColorMask"); - gleswColorMaskiEXT = (PFNGLCOLORMASKIEXTPROC)proc("glColorMaskiEXT"); - gleswColorMaskiOES = (PFNGLCOLORMASKIOESPROC)proc("glColorMaskiOES"); - gleswCompileShader = (PFNGLCOMPILESHADERPROC)proc("glCompileShader"); - gleswCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)proc("glCompressedTexImage2D"); - gleswCompressedTexImage3D = (PFNGLCOMPRESSEDTEXIMAGE3DPROC)proc("glCompressedTexImage3D"); - gleswCompressedTexImage3DOES = (PFNGLCOMPRESSEDTEXIMAGE3DOESPROC)proc("glCompressedTexImage3DOES"); - gleswCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)proc("glCompressedTexSubImage2D"); - gleswCompressedTexSubImage3D = (PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)proc("glCompressedTexSubImage3D"); - gleswCompressedTexSubImage3DOES = (PFNGLCOMPRESSEDTEXSUBIMAGE3DOESPROC)proc("glCompressedTexSubImage3DOES"); - gleswCopyBufferSubData = (PFNGLCOPYBUFFERSUBDATAPROC)proc("glCopyBufferSubData"); - gleswCopyBufferSubDataNV = (PFNGLCOPYBUFFERSUBDATANVPROC)proc("glCopyBufferSubDataNV"); - gleswCopyImageSubDataEXT = (PFNGLCOPYIMAGESUBDATAEXTPROC)proc("glCopyImageSubDataEXT"); - gleswCopyImageSubDataOES = (PFNGLCOPYIMAGESUBDATAOESPROC)proc("glCopyImageSubDataOES"); - gleswCopyPathNV = (PFNGLCOPYPATHNVPROC)proc("glCopyPathNV"); - gleswCopyTexImage2D = (PFNGLCOPYTEXIMAGE2DPROC)proc("glCopyTexImage2D"); - gleswCopyTexSubImage2D = (PFNGLCOPYTEXSUBIMAGE2DPROC)proc("glCopyTexSubImage2D"); - gleswCopyTexSubImage3D = (PFNGLCOPYTEXSUBIMAGE3DPROC)proc("glCopyTexSubImage3D"); - gleswCopyTexSubImage3DOES = (PFNGLCOPYTEXSUBIMAGE3DOESPROC)proc("glCopyTexSubImage3DOES"); - gleswCopyTextureLevelsAPPLE = (PFNGLCOPYTEXTURELEVELSAPPLEPROC)proc("glCopyTextureLevelsAPPLE"); - gleswCoverFillPathInstancedNV = (PFNGLCOVERFILLPATHINSTANCEDNVPROC)proc("glCoverFillPathInstancedNV"); - gleswCoverFillPathNV = (PFNGLCOVERFILLPATHNVPROC)proc("glCoverFillPathNV"); - gleswCoverStrokePathInstancedNV = (PFNGLCOVERSTROKEPATHINSTANCEDNVPROC)proc("glCoverStrokePathInstancedNV"); - gleswCoverStrokePathNV = (PFNGLCOVERSTROKEPATHNVPROC)proc("glCoverStrokePathNV"); - gleswCoverageMaskNV = (PFNGLCOVERAGEMASKNVPROC)proc("glCoverageMaskNV"); - gleswCoverageModulationNV = (PFNGLCOVERAGEMODULATIONNVPROC)proc("glCoverageModulationNV"); - gleswCoverageModulationTableNV = (PFNGLCOVERAGEMODULATIONTABLENVPROC)proc("glCoverageModulationTableNV"); - gleswCoverageOperationNV = (PFNGLCOVERAGEOPERATIONNVPROC)proc("glCoverageOperationNV"); - gleswCreatePerfQueryINTEL = (PFNGLCREATEPERFQUERYINTELPROC)proc("glCreatePerfQueryINTEL"); - gleswCreateProgram = (PFNGLCREATEPROGRAMPROC)proc("glCreateProgram"); - gleswCreateShader = (PFNGLCREATESHADERPROC)proc("glCreateShader"); - gleswCreateShaderProgramvEXT = (PFNGLCREATESHADERPROGRAMVEXTPROC)proc("glCreateShaderProgramvEXT"); - gleswCullFace = (PFNGLCULLFACEPROC)proc("glCullFace"); - gleswDebugMessageCallbackKHR = (PFNGLDEBUGMESSAGECALLBACKKHRPROC)proc("glDebugMessageCallbackKHR"); - gleswDebugMessageControlKHR = (PFNGLDEBUGMESSAGECONTROLKHRPROC)proc("glDebugMessageControlKHR"); - gleswDebugMessageInsertKHR = (PFNGLDEBUGMESSAGEINSERTKHRPROC)proc("glDebugMessageInsertKHR"); - gleswDeleteBuffers = (PFNGLDELETEBUFFERSPROC)proc("glDeleteBuffers"); - gleswDeleteFencesNV = (PFNGLDELETEFENCESNVPROC)proc("glDeleteFencesNV"); - gleswDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)proc("glDeleteFramebuffers"); - gleswDeletePathsNV = (PFNGLDELETEPATHSNVPROC)proc("glDeletePathsNV"); - gleswDeletePerfMonitorsAMD = (PFNGLDELETEPERFMONITORSAMDPROC)proc("glDeletePerfMonitorsAMD"); - gleswDeletePerfQueryINTEL = (PFNGLDELETEPERFQUERYINTELPROC)proc("glDeletePerfQueryINTEL"); - gleswDeleteProgram = (PFNGLDELETEPROGRAMPROC)proc("glDeleteProgram"); - gleswDeleteProgramPipelinesEXT = (PFNGLDELETEPROGRAMPIPELINESEXTPROC)proc("glDeleteProgramPipelinesEXT"); - gleswDeleteQueries = (PFNGLDELETEQUERIESPROC)proc("glDeleteQueries"); - gleswDeleteQueriesEXT = (PFNGLDELETEQUERIESEXTPROC)proc("glDeleteQueriesEXT"); - gleswDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)proc("glDeleteRenderbuffers"); - gleswDeleteSamplers = (PFNGLDELETESAMPLERSPROC)proc("glDeleteSamplers"); - gleswDeleteShader = (PFNGLDELETESHADERPROC)proc("glDeleteShader"); - gleswDeleteSync = (PFNGLDELETESYNCPROC)proc("glDeleteSync"); - gleswDeleteSyncAPPLE = (PFNGLDELETESYNCAPPLEPROC)proc("glDeleteSyncAPPLE"); - gleswDeleteTextures = (PFNGLDELETETEXTURESPROC)proc("glDeleteTextures"); - gleswDeleteTransformFeedbacks = (PFNGLDELETETRANSFORMFEEDBACKSPROC)proc("glDeleteTransformFeedbacks"); - gleswDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)proc("glDeleteVertexArrays"); - gleswDeleteVertexArraysOES = (PFNGLDELETEVERTEXARRAYSOESPROC)proc("glDeleteVertexArraysOES"); - gleswDepthFunc = (PFNGLDEPTHFUNCPROC)proc("glDepthFunc"); - gleswDepthMask = (PFNGLDEPTHMASKPROC)proc("glDepthMask"); - gleswDepthRangeArrayfvNV = (PFNGLDEPTHRANGEARRAYFVNVPROC)proc("glDepthRangeArrayfvNV"); - gleswDepthRangeIndexedfNV = (PFNGLDEPTHRANGEINDEXEDFNVPROC)proc("glDepthRangeIndexedfNV"); - gleswDepthRangef = (PFNGLDEPTHRANGEFPROC)proc("glDepthRangef"); - gleswDetachShader = (PFNGLDETACHSHADERPROC)proc("glDetachShader"); - gleswDisable = (PFNGLDISABLEPROC)proc("glDisable"); - gleswDisableDriverControlQCOM = (PFNGLDISABLEDRIVERCONTROLQCOMPROC)proc("glDisableDriverControlQCOM"); - gleswDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)proc("glDisableVertexAttribArray"); - gleswDisableiEXT = (PFNGLDISABLEIEXTPROC)proc("glDisableiEXT"); - gleswDisableiNV = (PFNGLDISABLEINVPROC)proc("glDisableiNV"); - gleswDisableiOES = (PFNGLDISABLEIOESPROC)proc("glDisableiOES"); - gleswDiscardFramebufferEXT = (PFNGLDISCARDFRAMEBUFFEREXTPROC)proc("glDiscardFramebufferEXT"); - gleswDrawArrays = (PFNGLDRAWARRAYSPROC)proc("glDrawArrays"); - gleswDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDPROC)proc("glDrawArraysInstanced"); - gleswDrawArraysInstancedANGLE = (PFNGLDRAWARRAYSINSTANCEDANGLEPROC)proc("glDrawArraysInstancedANGLE"); - gleswDrawArraysInstancedBaseInstanceEXT = (PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEEXTPROC)proc("glDrawArraysInstancedBaseInstanceEXT"); - gleswDrawArraysInstancedEXT = (PFNGLDRAWARRAYSINSTANCEDEXTPROC)proc("glDrawArraysInstancedEXT"); - gleswDrawArraysInstancedNV = (PFNGLDRAWARRAYSINSTANCEDNVPROC)proc("glDrawArraysInstancedNV"); - gleswDrawBuffers = (PFNGLDRAWBUFFERSPROC)proc("glDrawBuffers"); - gleswDrawBuffersEXT = (PFNGLDRAWBUFFERSEXTPROC)proc("glDrawBuffersEXT"); - gleswDrawBuffersIndexedEXT = (PFNGLDRAWBUFFERSINDEXEDEXTPROC)proc("glDrawBuffersIndexedEXT"); - gleswDrawBuffersNV = (PFNGLDRAWBUFFERSNVPROC)proc("glDrawBuffersNV"); - gleswDrawElements = (PFNGLDRAWELEMENTSPROC)proc("glDrawElements"); - gleswDrawElementsBaseVertexEXT = (PFNGLDRAWELEMENTSBASEVERTEXEXTPROC)proc("glDrawElementsBaseVertexEXT"); - gleswDrawElementsBaseVertexOES = (PFNGLDRAWELEMENTSBASEVERTEXOESPROC)proc("glDrawElementsBaseVertexOES"); - gleswDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDPROC)proc("glDrawElementsInstanced"); - gleswDrawElementsInstancedANGLE = (PFNGLDRAWELEMENTSINSTANCEDANGLEPROC)proc("glDrawElementsInstancedANGLE"); - gleswDrawElementsInstancedBaseInstanceEXT = (PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEEXTPROC)proc("glDrawElementsInstancedBaseInstanceEXT"); - gleswDrawElementsInstancedBaseVertexBaseInstanceEXT = (PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEEXTPROC)proc("glDrawElementsInstancedBaseVertexBaseInstanceEXT"); - gleswDrawElementsInstancedBaseVertexEXT = (PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXEXTPROC)proc("glDrawElementsInstancedBaseVertexEXT"); - gleswDrawElementsInstancedBaseVertexOES = (PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXOESPROC)proc("glDrawElementsInstancedBaseVertexOES"); - gleswDrawElementsInstancedEXT = (PFNGLDRAWELEMENTSINSTANCEDEXTPROC)proc("glDrawElementsInstancedEXT"); - gleswDrawElementsInstancedNV = (PFNGLDRAWELEMENTSINSTANCEDNVPROC)proc("glDrawElementsInstancedNV"); - gleswDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC)proc("glDrawRangeElements"); - gleswDrawRangeElementsBaseVertexEXT = (PFNGLDRAWRANGEELEMENTSBASEVERTEXEXTPROC)proc("glDrawRangeElementsBaseVertexEXT"); - gleswDrawRangeElementsBaseVertexOES = (PFNGLDRAWRANGEELEMENTSBASEVERTEXOESPROC)proc("glDrawRangeElementsBaseVertexOES"); - gleswEGLImageTargetRenderbufferStorageOES = (PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC)proc("glEGLImageTargetRenderbufferStorageOES"); - gleswEGLImageTargetTexture2DOES = (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)proc("glEGLImageTargetTexture2DOES"); - gleswEnable = (PFNGLENABLEPROC)proc("glEnable"); - gleswEnableDriverControlQCOM = (PFNGLENABLEDRIVERCONTROLQCOMPROC)proc("glEnableDriverControlQCOM"); - gleswEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)proc("glEnableVertexAttribArray"); - gleswEnableiEXT = (PFNGLENABLEIEXTPROC)proc("glEnableiEXT"); - gleswEnableiNV = (PFNGLENABLEINVPROC)proc("glEnableiNV"); - gleswEnableiOES = (PFNGLENABLEIOESPROC)proc("glEnableiOES"); - gleswEndConditionalRenderNV = (PFNGLENDCONDITIONALRENDERNVPROC)proc("glEndConditionalRenderNV"); - gleswEndPerfMonitorAMD = (PFNGLENDPERFMONITORAMDPROC)proc("glEndPerfMonitorAMD"); - gleswEndPerfQueryINTEL = (PFNGLENDPERFQUERYINTELPROC)proc("glEndPerfQueryINTEL"); - gleswEndQuery = (PFNGLENDQUERYPROC)proc("glEndQuery"); - gleswEndQueryEXT = (PFNGLENDQUERYEXTPROC)proc("glEndQueryEXT"); - gleswEndTilingQCOM = (PFNGLENDTILINGQCOMPROC)proc("glEndTilingQCOM"); - gleswEndTransformFeedback = (PFNGLENDTRANSFORMFEEDBACKPROC)proc("glEndTransformFeedback"); - gleswExtGetBufferPointervQCOM = (PFNGLEXTGETBUFFERPOINTERVQCOMPROC)proc("glExtGetBufferPointervQCOM"); - gleswExtGetBuffersQCOM = (PFNGLEXTGETBUFFERSQCOMPROC)proc("glExtGetBuffersQCOM"); - gleswExtGetFramebuffersQCOM = (PFNGLEXTGETFRAMEBUFFERSQCOMPROC)proc("glExtGetFramebuffersQCOM"); - gleswExtGetProgramBinarySourceQCOM = (PFNGLEXTGETPROGRAMBINARYSOURCEQCOMPROC)proc("glExtGetProgramBinarySourceQCOM"); - gleswExtGetProgramsQCOM = (PFNGLEXTGETPROGRAMSQCOMPROC)proc("glExtGetProgramsQCOM"); - gleswExtGetRenderbuffersQCOM = (PFNGLEXTGETRENDERBUFFERSQCOMPROC)proc("glExtGetRenderbuffersQCOM"); - gleswExtGetShadersQCOM = (PFNGLEXTGETSHADERSQCOMPROC)proc("glExtGetShadersQCOM"); - gleswExtGetTexLevelParameterivQCOM = (PFNGLEXTGETTEXLEVELPARAMETERIVQCOMPROC)proc("glExtGetTexLevelParameterivQCOM"); - gleswExtGetTexSubImageQCOM = (PFNGLEXTGETTEXSUBIMAGEQCOMPROC)proc("glExtGetTexSubImageQCOM"); - gleswExtGetTexturesQCOM = (PFNGLEXTGETTEXTURESQCOMPROC)proc("glExtGetTexturesQCOM"); - gleswExtIsProgramBinaryQCOM = (PFNGLEXTISPROGRAMBINARYQCOMPROC)proc("glExtIsProgramBinaryQCOM"); - gleswExtTexObjectStateOverrideiQCOM = (PFNGLEXTTEXOBJECTSTATEOVERRIDEIQCOMPROC)proc("glExtTexObjectStateOverrideiQCOM"); - gleswFenceSync = (PFNGLFENCESYNCPROC)proc("glFenceSync"); - gleswFenceSyncAPPLE = (PFNGLFENCESYNCAPPLEPROC)proc("glFenceSyncAPPLE"); - gleswFinish = (PFNGLFINISHPROC)proc("glFinish"); - gleswFinishFenceNV = (PFNGLFINISHFENCENVPROC)proc("glFinishFenceNV"); - gleswFlush = (PFNGLFLUSHPROC)proc("glFlush"); - gleswFlushMappedBufferRange = (PFNGLFLUSHMAPPEDBUFFERRANGEPROC)proc("glFlushMappedBufferRange"); - gleswFlushMappedBufferRangeEXT = (PFNGLFLUSHMAPPEDBUFFERRANGEEXTPROC)proc("glFlushMappedBufferRangeEXT"); - gleswFragmentCoverageColorNV = (PFNGLFRAGMENTCOVERAGECOLORNVPROC)proc("glFragmentCoverageColorNV"); - gleswFramebufferPixelLocalStorageSizeEXT = (PFNGLFRAMEBUFFERPIXELLOCALSTORAGESIZEEXTPROC)proc("glFramebufferPixelLocalStorageSizeEXT"); - gleswFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)proc("glFramebufferRenderbuffer"); - gleswFramebufferSampleLocationsfvNV = (PFNGLFRAMEBUFFERSAMPLELOCATIONSFVNVPROC)proc("glFramebufferSampleLocationsfvNV"); - gleswFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)proc("glFramebufferTexture2D"); - gleswFramebufferTexture2DDownsampleIMG = (PFNGLFRAMEBUFFERTEXTURE2DDOWNSAMPLEIMGPROC)proc("glFramebufferTexture2DDownsampleIMG"); - gleswFramebufferTexture2DMultisampleEXT = (PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEEXTPROC)proc("glFramebufferTexture2DMultisampleEXT"); - gleswFramebufferTexture2DMultisampleIMG = (PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEIMGPROC)proc("glFramebufferTexture2DMultisampleIMG"); - gleswFramebufferTexture3DOES = (PFNGLFRAMEBUFFERTEXTURE3DOESPROC)proc("glFramebufferTexture3DOES"); - gleswFramebufferTextureEXT = (PFNGLFRAMEBUFFERTEXTUREEXTPROC)proc("glFramebufferTextureEXT"); - gleswFramebufferTextureLayer = (PFNGLFRAMEBUFFERTEXTURELAYERPROC)proc("glFramebufferTextureLayer"); - gleswFramebufferTextureLayerDownsampleIMG = (PFNGLFRAMEBUFFERTEXTURELAYERDOWNSAMPLEIMGPROC)proc("glFramebufferTextureLayerDownsampleIMG"); - gleswFramebufferTextureMultisampleMultiviewOVR = (PFNGLFRAMEBUFFERTEXTUREMULTISAMPLEMULTIVIEWOVRPROC)proc("glFramebufferTextureMultisampleMultiviewOVR"); - gleswFramebufferTextureMultiviewOVR = (PFNGLFRAMEBUFFERTEXTUREMULTIVIEWOVRPROC)proc("glFramebufferTextureMultiviewOVR"); - gleswFramebufferTextureOES = (PFNGLFRAMEBUFFERTEXTUREOESPROC)proc("glFramebufferTextureOES"); - gleswFrontFace = (PFNGLFRONTFACEPROC)proc("glFrontFace"); - gleswGenBuffers = (PFNGLGENBUFFERSPROC)proc("glGenBuffers"); - gleswGenFencesNV = (PFNGLGENFENCESNVPROC)proc("glGenFencesNV"); - gleswGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)proc("glGenFramebuffers"); - gleswGenPathsNV = (PFNGLGENPATHSNVPROC)proc("glGenPathsNV"); - gleswGenPerfMonitorsAMD = (PFNGLGENPERFMONITORSAMDPROC)proc("glGenPerfMonitorsAMD"); - gleswGenProgramPipelinesEXT = (PFNGLGENPROGRAMPIPELINESEXTPROC)proc("glGenProgramPipelinesEXT"); - gleswGenQueries = (PFNGLGENQUERIESPROC)proc("glGenQueries"); - gleswGenQueriesEXT = (PFNGLGENQUERIESEXTPROC)proc("glGenQueriesEXT"); - gleswGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)proc("glGenRenderbuffers"); - gleswGenSamplers = (PFNGLGENSAMPLERSPROC)proc("glGenSamplers"); - gleswGenTextures = (PFNGLGENTEXTURESPROC)proc("glGenTextures"); - gleswGenTransformFeedbacks = (PFNGLGENTRANSFORMFEEDBACKSPROC)proc("glGenTransformFeedbacks"); - gleswGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)proc("glGenVertexArrays"); - gleswGenVertexArraysOES = (PFNGLGENVERTEXARRAYSOESPROC)proc("glGenVertexArraysOES"); - gleswGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)proc("glGenerateMipmap"); - gleswGetActiveAttrib = (PFNGLGETACTIVEATTRIBPROC)proc("glGetActiveAttrib"); - gleswGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)proc("glGetActiveUniform"); - gleswGetActiveUniformBlockName = (PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)proc("glGetActiveUniformBlockName"); - gleswGetActiveUniformBlockiv = (PFNGLGETACTIVEUNIFORMBLOCKIVPROC)proc("glGetActiveUniformBlockiv"); - gleswGetActiveUniformsiv = (PFNGLGETACTIVEUNIFORMSIVPROC)proc("glGetActiveUniformsiv"); - gleswGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC)proc("glGetAttachedShaders"); - gleswGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)proc("glGetAttribLocation"); - gleswGetBooleanv = (PFNGLGETBOOLEANVPROC)proc("glGetBooleanv"); - gleswGetBufferParameteri64v = (PFNGLGETBUFFERPARAMETERI64VPROC)proc("glGetBufferParameteri64v"); - gleswGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVPROC)proc("glGetBufferParameteriv"); - gleswGetBufferPointerv = (PFNGLGETBUFFERPOINTERVPROC)proc("glGetBufferPointerv"); - gleswGetBufferPointervOES = (PFNGLGETBUFFERPOINTERVOESPROC)proc("glGetBufferPointervOES"); - gleswGetCoverageModulationTableNV = (PFNGLGETCOVERAGEMODULATIONTABLENVPROC)proc("glGetCoverageModulationTableNV"); - gleswGetDebugMessageLogKHR = (PFNGLGETDEBUGMESSAGELOGKHRPROC)proc("glGetDebugMessageLogKHR"); - gleswGetDriverControlStringQCOM = (PFNGLGETDRIVERCONTROLSTRINGQCOMPROC)proc("glGetDriverControlStringQCOM"); - gleswGetDriverControlsQCOM = (PFNGLGETDRIVERCONTROLSQCOMPROC)proc("glGetDriverControlsQCOM"); - gleswGetError = (PFNGLGETERRORPROC)proc("glGetError"); - gleswGetFenceivNV = (PFNGLGETFENCEIVNVPROC)proc("glGetFenceivNV"); - gleswGetFirstPerfQueryIdINTEL = (PFNGLGETFIRSTPERFQUERYIDINTELPROC)proc("glGetFirstPerfQueryIdINTEL"); - gleswGetFloati_vNV = (PFNGLGETFLOATI_VNVPROC)proc("glGetFloati_vNV"); - gleswGetFloatv = (PFNGLGETFLOATVPROC)proc("glGetFloatv"); - gleswGetFragDataIndexEXT = (PFNGLGETFRAGDATAINDEXEXTPROC)proc("glGetFragDataIndexEXT"); - gleswGetFragDataLocation = (PFNGLGETFRAGDATALOCATIONPROC)proc("glGetFragDataLocation"); - gleswGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)proc("glGetFramebufferAttachmentParameteriv"); - gleswGetFramebufferPixelLocalStorageSizeEXT = (PFNGLGETFRAMEBUFFERPIXELLOCALSTORAGESIZEEXTPROC)proc("glGetFramebufferPixelLocalStorageSizeEXT"); - gleswGetGraphicsResetStatusEXT = (PFNGLGETGRAPHICSRESETSTATUSEXTPROC)proc("glGetGraphicsResetStatusEXT"); - gleswGetGraphicsResetStatusKHR = (PFNGLGETGRAPHICSRESETSTATUSKHRPROC)proc("glGetGraphicsResetStatusKHR"); - gleswGetImageHandleNV = (PFNGLGETIMAGEHANDLENVPROC)proc("glGetImageHandleNV"); - gleswGetInteger64i_v = (PFNGLGETINTEGER64I_VPROC)proc("glGetInteger64i_v"); - gleswGetInteger64v = (PFNGLGETINTEGER64VPROC)proc("glGetInteger64v"); - gleswGetInteger64vAPPLE = (PFNGLGETINTEGER64VAPPLEPROC)proc("glGetInteger64vAPPLE"); - gleswGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)proc("glGetIntegeri_v"); - gleswGetIntegeri_vEXT = (PFNGLGETINTEGERI_VEXTPROC)proc("glGetIntegeri_vEXT"); - gleswGetIntegerv = (PFNGLGETINTEGERVPROC)proc("glGetIntegerv"); - gleswGetInternalformatSampleivNV = (PFNGLGETINTERNALFORMATSAMPLEIVNVPROC)proc("glGetInternalformatSampleivNV"); - gleswGetInternalformativ = (PFNGLGETINTERNALFORMATIVPROC)proc("glGetInternalformativ"); - gleswGetNextPerfQueryIdINTEL = (PFNGLGETNEXTPERFQUERYIDINTELPROC)proc("glGetNextPerfQueryIdINTEL"); - gleswGetObjectLabelEXT = (PFNGLGETOBJECTLABELEXTPROC)proc("glGetObjectLabelEXT"); - gleswGetObjectLabelKHR = (PFNGLGETOBJECTLABELKHRPROC)proc("glGetObjectLabelKHR"); - gleswGetObjectPtrLabelKHR = (PFNGLGETOBJECTPTRLABELKHRPROC)proc("glGetObjectPtrLabelKHR"); - gleswGetPathCommandsNV = (PFNGLGETPATHCOMMANDSNVPROC)proc("glGetPathCommandsNV"); - gleswGetPathCoordsNV = (PFNGLGETPATHCOORDSNVPROC)proc("glGetPathCoordsNV"); - gleswGetPathDashArrayNV = (PFNGLGETPATHDASHARRAYNVPROC)proc("glGetPathDashArrayNV"); - gleswGetPathLengthNV = (PFNGLGETPATHLENGTHNVPROC)proc("glGetPathLengthNV"); - gleswGetPathMetricRangeNV = (PFNGLGETPATHMETRICRANGENVPROC)proc("glGetPathMetricRangeNV"); - gleswGetPathMetricsNV = (PFNGLGETPATHMETRICSNVPROC)proc("glGetPathMetricsNV"); - gleswGetPathParameterfvNV = (PFNGLGETPATHPARAMETERFVNVPROC)proc("glGetPathParameterfvNV"); - gleswGetPathParameterivNV = (PFNGLGETPATHPARAMETERIVNVPROC)proc("glGetPathParameterivNV"); - gleswGetPathSpacingNV = (PFNGLGETPATHSPACINGNVPROC)proc("glGetPathSpacingNV"); - gleswGetPerfCounterInfoINTEL = (PFNGLGETPERFCOUNTERINFOINTELPROC)proc("glGetPerfCounterInfoINTEL"); - gleswGetPerfMonitorCounterDataAMD = (PFNGLGETPERFMONITORCOUNTERDATAAMDPROC)proc("glGetPerfMonitorCounterDataAMD"); - gleswGetPerfMonitorCounterInfoAMD = (PFNGLGETPERFMONITORCOUNTERINFOAMDPROC)proc("glGetPerfMonitorCounterInfoAMD"); - gleswGetPerfMonitorCounterStringAMD = (PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC)proc("glGetPerfMonitorCounterStringAMD"); - gleswGetPerfMonitorCountersAMD = (PFNGLGETPERFMONITORCOUNTERSAMDPROC)proc("glGetPerfMonitorCountersAMD"); - gleswGetPerfMonitorGroupStringAMD = (PFNGLGETPERFMONITORGROUPSTRINGAMDPROC)proc("glGetPerfMonitorGroupStringAMD"); - gleswGetPerfMonitorGroupsAMD = (PFNGLGETPERFMONITORGROUPSAMDPROC)proc("glGetPerfMonitorGroupsAMD"); - gleswGetPerfQueryDataINTEL = (PFNGLGETPERFQUERYDATAINTELPROC)proc("glGetPerfQueryDataINTEL"); - gleswGetPerfQueryIdByNameINTEL = (PFNGLGETPERFQUERYIDBYNAMEINTELPROC)proc("glGetPerfQueryIdByNameINTEL"); - gleswGetPerfQueryInfoINTEL = (PFNGLGETPERFQUERYINFOINTELPROC)proc("glGetPerfQueryInfoINTEL"); - gleswGetPointervKHR = (PFNGLGETPOINTERVKHRPROC)proc("glGetPointervKHR"); - gleswGetProgramBinary = (PFNGLGETPROGRAMBINARYPROC)proc("glGetProgramBinary"); - gleswGetProgramBinaryOES = (PFNGLGETPROGRAMBINARYOESPROC)proc("glGetProgramBinaryOES"); - gleswGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)proc("glGetProgramInfoLog"); - gleswGetProgramPipelineInfoLogEXT = (PFNGLGETPROGRAMPIPELINEINFOLOGEXTPROC)proc("glGetProgramPipelineInfoLogEXT"); - gleswGetProgramPipelineivEXT = (PFNGLGETPROGRAMPIPELINEIVEXTPROC)proc("glGetProgramPipelineivEXT"); - gleswGetProgramResourceLocationIndexEXT = (PFNGLGETPROGRAMRESOURCELOCATIONINDEXEXTPROC)proc("glGetProgramResourceLocationIndexEXT"); - gleswGetProgramResourcefvNV = (PFNGLGETPROGRAMRESOURCEFVNVPROC)proc("glGetProgramResourcefvNV"); - gleswGetProgramiv = (PFNGLGETPROGRAMIVPROC)proc("glGetProgramiv"); - gleswGetQueryObjecti64vEXT = (PFNGLGETQUERYOBJECTI64VEXTPROC)proc("glGetQueryObjecti64vEXT"); - gleswGetQueryObjectivEXT = (PFNGLGETQUERYOBJECTIVEXTPROC)proc("glGetQueryObjectivEXT"); - gleswGetQueryObjectui64vEXT = (PFNGLGETQUERYOBJECTUI64VEXTPROC)proc("glGetQueryObjectui64vEXT"); - gleswGetQueryObjectuiv = (PFNGLGETQUERYOBJECTUIVPROC)proc("glGetQueryObjectuiv"); - gleswGetQueryObjectuivEXT = (PFNGLGETQUERYOBJECTUIVEXTPROC)proc("glGetQueryObjectuivEXT"); - gleswGetQueryiv = (PFNGLGETQUERYIVPROC)proc("glGetQueryiv"); - gleswGetQueryivEXT = (PFNGLGETQUERYIVEXTPROC)proc("glGetQueryivEXT"); - gleswGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)proc("glGetRenderbufferParameteriv"); - gleswGetSamplerParameterIivEXT = (PFNGLGETSAMPLERPARAMETERIIVEXTPROC)proc("glGetSamplerParameterIivEXT"); - gleswGetSamplerParameterIivOES = (PFNGLGETSAMPLERPARAMETERIIVOESPROC)proc("glGetSamplerParameterIivOES"); - gleswGetSamplerParameterIuivEXT = (PFNGLGETSAMPLERPARAMETERIUIVEXTPROC)proc("glGetSamplerParameterIuivEXT"); - gleswGetSamplerParameterIuivOES = (PFNGLGETSAMPLERPARAMETERIUIVOESPROC)proc("glGetSamplerParameterIuivOES"); - gleswGetSamplerParameterfv = (PFNGLGETSAMPLERPARAMETERFVPROC)proc("glGetSamplerParameterfv"); - gleswGetSamplerParameteriv = (PFNGLGETSAMPLERPARAMETERIVPROC)proc("glGetSamplerParameteriv"); - gleswGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)proc("glGetShaderInfoLog"); - gleswGetShaderPrecisionFormat = (PFNGLGETSHADERPRECISIONFORMATPROC)proc("glGetShaderPrecisionFormat"); - gleswGetShaderSource = (PFNGLGETSHADERSOURCEPROC)proc("glGetShaderSource"); - gleswGetShaderiv = (PFNGLGETSHADERIVPROC)proc("glGetShaderiv"); - gleswGetString = (PFNGLGETSTRINGPROC)proc("glGetString"); - gleswGetStringi = (PFNGLGETSTRINGIPROC)proc("glGetStringi"); - gleswGetSynciv = (PFNGLGETSYNCIVPROC)proc("glGetSynciv"); - gleswGetSyncivAPPLE = (PFNGLGETSYNCIVAPPLEPROC)proc("glGetSyncivAPPLE"); - gleswGetTexParameterIivEXT = (PFNGLGETTEXPARAMETERIIVEXTPROC)proc("glGetTexParameterIivEXT"); - gleswGetTexParameterIivOES = (PFNGLGETTEXPARAMETERIIVOESPROC)proc("glGetTexParameterIivOES"); - gleswGetTexParameterIuivEXT = (PFNGLGETTEXPARAMETERIUIVEXTPROC)proc("glGetTexParameterIuivEXT"); - gleswGetTexParameterIuivOES = (PFNGLGETTEXPARAMETERIUIVOESPROC)proc("glGetTexParameterIuivOES"); - gleswGetTexParameterfv = (PFNGLGETTEXPARAMETERFVPROC)proc("glGetTexParameterfv"); - gleswGetTexParameteriv = (PFNGLGETTEXPARAMETERIVPROC)proc("glGetTexParameteriv"); - gleswGetTextureHandleNV = (PFNGLGETTEXTUREHANDLENVPROC)proc("glGetTextureHandleNV"); - gleswGetTextureSamplerHandleNV = (PFNGLGETTEXTURESAMPLERHANDLENVPROC)proc("glGetTextureSamplerHandleNV"); - gleswGetTransformFeedbackVarying = (PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)proc("glGetTransformFeedbackVarying"); - gleswGetTranslatedShaderSourceANGLE = (PFNGLGETTRANSLATEDSHADERSOURCEANGLEPROC)proc("glGetTranslatedShaderSourceANGLE"); - gleswGetUniformBlockIndex = (PFNGLGETUNIFORMBLOCKINDEXPROC)proc("glGetUniformBlockIndex"); - gleswGetUniformIndices = (PFNGLGETUNIFORMINDICESPROC)proc("glGetUniformIndices"); - gleswGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)proc("glGetUniformLocation"); - gleswGetUniformfv = (PFNGLGETUNIFORMFVPROC)proc("glGetUniformfv"); - gleswGetUniformiv = (PFNGLGETUNIFORMIVPROC)proc("glGetUniformiv"); - gleswGetUniformuiv = (PFNGLGETUNIFORMUIVPROC)proc("glGetUniformuiv"); - gleswGetVertexAttribIiv = (PFNGLGETVERTEXATTRIBIIVPROC)proc("glGetVertexAttribIiv"); - gleswGetVertexAttribIuiv = (PFNGLGETVERTEXATTRIBIUIVPROC)proc("glGetVertexAttribIuiv"); - gleswGetVertexAttribPointerv = (PFNGLGETVERTEXATTRIBPOINTERVPROC)proc("glGetVertexAttribPointerv"); - gleswGetVertexAttribfv = (PFNGLGETVERTEXATTRIBFVPROC)proc("glGetVertexAttribfv"); - gleswGetVertexAttribiv = (PFNGLGETVERTEXATTRIBIVPROC)proc("glGetVertexAttribiv"); - gleswGetnUniformfvEXT = (PFNGLGETNUNIFORMFVEXTPROC)proc("glGetnUniformfvEXT"); - gleswGetnUniformfvKHR = (PFNGLGETNUNIFORMFVKHRPROC)proc("glGetnUniformfvKHR"); - gleswGetnUniformivEXT = (PFNGLGETNUNIFORMIVEXTPROC)proc("glGetnUniformivEXT"); - gleswGetnUniformivKHR = (PFNGLGETNUNIFORMIVKHRPROC)proc("glGetnUniformivKHR"); - gleswGetnUniformuivKHR = (PFNGLGETNUNIFORMUIVKHRPROC)proc("glGetnUniformuivKHR"); - gleswHint = (PFNGLHINTPROC)proc("glHint"); - gleswInsertEventMarkerEXT = (PFNGLINSERTEVENTMARKEREXTPROC)proc("glInsertEventMarkerEXT"); - gleswInterpolatePathsNV = (PFNGLINTERPOLATEPATHSNVPROC)proc("glInterpolatePathsNV"); - gleswInvalidateFramebuffer = (PFNGLINVALIDATEFRAMEBUFFERPROC)proc("glInvalidateFramebuffer"); - gleswInvalidateSubFramebuffer = (PFNGLINVALIDATESUBFRAMEBUFFERPROC)proc("glInvalidateSubFramebuffer"); - gleswIsBuffer = (PFNGLISBUFFERPROC)proc("glIsBuffer"); - gleswIsEnabled = (PFNGLISENABLEDPROC)proc("glIsEnabled"); - gleswIsEnablediEXT = (PFNGLISENABLEDIEXTPROC)proc("glIsEnablediEXT"); - gleswIsEnablediNV = (PFNGLISENABLEDINVPROC)proc("glIsEnablediNV"); - gleswIsEnablediOES = (PFNGLISENABLEDIOESPROC)proc("glIsEnablediOES"); - gleswIsFenceNV = (PFNGLISFENCENVPROC)proc("glIsFenceNV"); - gleswIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)proc("glIsFramebuffer"); - gleswIsImageHandleResidentNV = (PFNGLISIMAGEHANDLERESIDENTNVPROC)proc("glIsImageHandleResidentNV"); - gleswIsPathNV = (PFNGLISPATHNVPROC)proc("glIsPathNV"); - gleswIsPointInFillPathNV = (PFNGLISPOINTINFILLPATHNVPROC)proc("glIsPointInFillPathNV"); - gleswIsPointInStrokePathNV = (PFNGLISPOINTINSTROKEPATHNVPROC)proc("glIsPointInStrokePathNV"); - gleswIsProgram = (PFNGLISPROGRAMPROC)proc("glIsProgram"); - gleswIsProgramPipelineEXT = (PFNGLISPROGRAMPIPELINEEXTPROC)proc("glIsProgramPipelineEXT"); - gleswIsQuery = (PFNGLISQUERYPROC)proc("glIsQuery"); - gleswIsQueryEXT = (PFNGLISQUERYEXTPROC)proc("glIsQueryEXT"); - gleswIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)proc("glIsRenderbuffer"); - gleswIsSampler = (PFNGLISSAMPLERPROC)proc("glIsSampler"); - gleswIsShader = (PFNGLISSHADERPROC)proc("glIsShader"); - gleswIsSync = (PFNGLISSYNCPROC)proc("glIsSync"); - gleswIsSyncAPPLE = (PFNGLISSYNCAPPLEPROC)proc("glIsSyncAPPLE"); - gleswIsTexture = (PFNGLISTEXTUREPROC)proc("glIsTexture"); - gleswIsTextureHandleResidentNV = (PFNGLISTEXTUREHANDLERESIDENTNVPROC)proc("glIsTextureHandleResidentNV"); - gleswIsTransformFeedback = (PFNGLISTRANSFORMFEEDBACKPROC)proc("glIsTransformFeedback"); - gleswIsVertexArray = (PFNGLISVERTEXARRAYPROC)proc("glIsVertexArray"); - gleswIsVertexArrayOES = (PFNGLISVERTEXARRAYOESPROC)proc("glIsVertexArrayOES"); - gleswLabelObjectEXT = (PFNGLLABELOBJECTEXTPROC)proc("glLabelObjectEXT"); - gleswLineWidth = (PFNGLLINEWIDTHPROC)proc("glLineWidth"); - gleswLinkProgram = (PFNGLLINKPROGRAMPROC)proc("glLinkProgram"); - gleswMakeImageHandleNonResidentNV = (PFNGLMAKEIMAGEHANDLENONRESIDENTNVPROC)proc("glMakeImageHandleNonResidentNV"); - gleswMakeImageHandleResidentNV = (PFNGLMAKEIMAGEHANDLERESIDENTNVPROC)proc("glMakeImageHandleResidentNV"); - gleswMakeTextureHandleNonResidentNV = (PFNGLMAKETEXTUREHANDLENONRESIDENTNVPROC)proc("glMakeTextureHandleNonResidentNV"); - gleswMakeTextureHandleResidentNV = (PFNGLMAKETEXTUREHANDLERESIDENTNVPROC)proc("glMakeTextureHandleResidentNV"); - gleswMapBufferOES = (PFNGLMAPBUFFEROESPROC)proc("glMapBufferOES"); - gleswMapBufferRange = (PFNGLMAPBUFFERRANGEPROC)proc("glMapBufferRange"); - gleswMapBufferRangeEXT = (PFNGLMAPBUFFERRANGEEXTPROC)proc("glMapBufferRangeEXT"); - gleswMatrixLoad3x2fNV = (PFNGLMATRIXLOAD3X2FNVPROC)proc("glMatrixLoad3x2fNV"); - gleswMatrixLoad3x3fNV = (PFNGLMATRIXLOAD3X3FNVPROC)proc("glMatrixLoad3x3fNV"); - gleswMatrixLoadTranspose3x3fNV = (PFNGLMATRIXLOADTRANSPOSE3X3FNVPROC)proc("glMatrixLoadTranspose3x3fNV"); - gleswMatrixMult3x2fNV = (PFNGLMATRIXMULT3X2FNVPROC)proc("glMatrixMult3x2fNV"); - gleswMatrixMult3x3fNV = (PFNGLMATRIXMULT3X3FNVPROC)proc("glMatrixMult3x3fNV"); - gleswMatrixMultTranspose3x3fNV = (PFNGLMATRIXMULTTRANSPOSE3X3FNVPROC)proc("glMatrixMultTranspose3x3fNV"); - gleswMinSampleShadingOES = (PFNGLMINSAMPLESHADINGOESPROC)proc("glMinSampleShadingOES"); - gleswMultiDrawArraysEXT = (PFNGLMULTIDRAWARRAYSEXTPROC)proc("glMultiDrawArraysEXT"); - gleswMultiDrawArraysIndirectEXT = (PFNGLMULTIDRAWARRAYSINDIRECTEXTPROC)proc("glMultiDrawArraysIndirectEXT"); - gleswMultiDrawElementsBaseVertexEXT = (PFNGLMULTIDRAWELEMENTSBASEVERTEXEXTPROC)proc("glMultiDrawElementsBaseVertexEXT"); - gleswMultiDrawElementsBaseVertexOES = (PFNGLMULTIDRAWELEMENTSBASEVERTEXOESPROC)proc("glMultiDrawElementsBaseVertexOES"); - gleswMultiDrawElementsEXT = (PFNGLMULTIDRAWELEMENTSEXTPROC)proc("glMultiDrawElementsEXT"); - gleswMultiDrawElementsIndirectEXT = (PFNGLMULTIDRAWELEMENTSINDIRECTEXTPROC)proc("glMultiDrawElementsIndirectEXT"); - gleswNamedFramebufferSampleLocationsfvNV = (PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVNVPROC)proc("glNamedFramebufferSampleLocationsfvNV"); - gleswObjectLabelKHR = (PFNGLOBJECTLABELKHRPROC)proc("glObjectLabelKHR"); - gleswObjectPtrLabelKHR = (PFNGLOBJECTPTRLABELKHRPROC)proc("glObjectPtrLabelKHR"); - gleswPatchParameteriEXT = (PFNGLPATCHPARAMETERIEXTPROC)proc("glPatchParameteriEXT"); - gleswPatchParameteriOES = (PFNGLPATCHPARAMETERIOESPROC)proc("glPatchParameteriOES"); - gleswPathCommandsNV = (PFNGLPATHCOMMANDSNVPROC)proc("glPathCommandsNV"); - gleswPathCoordsNV = (PFNGLPATHCOORDSNVPROC)proc("glPathCoordsNV"); - gleswPathCoverDepthFuncNV = (PFNGLPATHCOVERDEPTHFUNCNVPROC)proc("glPathCoverDepthFuncNV"); - gleswPathDashArrayNV = (PFNGLPATHDASHARRAYNVPROC)proc("glPathDashArrayNV"); - gleswPathGlyphIndexArrayNV = (PFNGLPATHGLYPHINDEXARRAYNVPROC)proc("glPathGlyphIndexArrayNV"); - gleswPathGlyphIndexRangeNV = (PFNGLPATHGLYPHINDEXRANGENVPROC)proc("glPathGlyphIndexRangeNV"); - gleswPathGlyphRangeNV = (PFNGLPATHGLYPHRANGENVPROC)proc("glPathGlyphRangeNV"); - gleswPathGlyphsNV = (PFNGLPATHGLYPHSNVPROC)proc("glPathGlyphsNV"); - gleswPathMemoryGlyphIndexArrayNV = (PFNGLPATHMEMORYGLYPHINDEXARRAYNVPROC)proc("glPathMemoryGlyphIndexArrayNV"); - gleswPathParameterfNV = (PFNGLPATHPARAMETERFNVPROC)proc("glPathParameterfNV"); - gleswPathParameterfvNV = (PFNGLPATHPARAMETERFVNVPROC)proc("glPathParameterfvNV"); - gleswPathParameteriNV = (PFNGLPATHPARAMETERINVPROC)proc("glPathParameteriNV"); - gleswPathParameterivNV = (PFNGLPATHPARAMETERIVNVPROC)proc("glPathParameterivNV"); - gleswPathStencilDepthOffsetNV = (PFNGLPATHSTENCILDEPTHOFFSETNVPROC)proc("glPathStencilDepthOffsetNV"); - gleswPathStencilFuncNV = (PFNGLPATHSTENCILFUNCNVPROC)proc("glPathStencilFuncNV"); - gleswPathStringNV = (PFNGLPATHSTRINGNVPROC)proc("glPathStringNV"); - gleswPathSubCommandsNV = (PFNGLPATHSUBCOMMANDSNVPROC)proc("glPathSubCommandsNV"); - gleswPathSubCoordsNV = (PFNGLPATHSUBCOORDSNVPROC)proc("glPathSubCoordsNV"); - gleswPauseTransformFeedback = (PFNGLPAUSETRANSFORMFEEDBACKPROC)proc("glPauseTransformFeedback"); - gleswPixelStorei = (PFNGLPIXELSTOREIPROC)proc("glPixelStorei"); - gleswPointAlongPathNV = (PFNGLPOINTALONGPATHNVPROC)proc("glPointAlongPathNV"); - gleswPolygonModeNV = (PFNGLPOLYGONMODENVPROC)proc("glPolygonModeNV"); - gleswPolygonOffset = (PFNGLPOLYGONOFFSETPROC)proc("glPolygonOffset"); - gleswPolygonOffsetClampEXT = (PFNGLPOLYGONOFFSETCLAMPEXTPROC)proc("glPolygonOffsetClampEXT"); - gleswPopDebugGroupKHR = (PFNGLPOPDEBUGGROUPKHRPROC)proc("glPopDebugGroupKHR"); - gleswPopGroupMarkerEXT = (PFNGLPOPGROUPMARKEREXTPROC)proc("glPopGroupMarkerEXT"); - gleswPrimitiveBoundingBoxEXT = (PFNGLPRIMITIVEBOUNDINGBOXEXTPROC)proc("glPrimitiveBoundingBoxEXT"); - gleswPrimitiveBoundingBoxOES = (PFNGLPRIMITIVEBOUNDINGBOXOESPROC)proc("glPrimitiveBoundingBoxOES"); - gleswProgramBinary = (PFNGLPROGRAMBINARYPROC)proc("glProgramBinary"); - gleswProgramBinaryOES = (PFNGLPROGRAMBINARYOESPROC)proc("glProgramBinaryOES"); - gleswProgramParameteri = (PFNGLPROGRAMPARAMETERIPROC)proc("glProgramParameteri"); - gleswProgramParameteriEXT = (PFNGLPROGRAMPARAMETERIEXTPROC)proc("glProgramParameteriEXT"); - gleswProgramPathFragmentInputGenNV = (PFNGLPROGRAMPATHFRAGMENTINPUTGENNVPROC)proc("glProgramPathFragmentInputGenNV"); - gleswProgramUniform1fEXT = (PFNGLPROGRAMUNIFORM1FEXTPROC)proc("glProgramUniform1fEXT"); - gleswProgramUniform1fvEXT = (PFNGLPROGRAMUNIFORM1FVEXTPROC)proc("glProgramUniform1fvEXT"); - gleswProgramUniform1iEXT = (PFNGLPROGRAMUNIFORM1IEXTPROC)proc("glProgramUniform1iEXT"); - gleswProgramUniform1ivEXT = (PFNGLPROGRAMUNIFORM1IVEXTPROC)proc("glProgramUniform1ivEXT"); - gleswProgramUniform1uiEXT = (PFNGLPROGRAMUNIFORM1UIEXTPROC)proc("glProgramUniform1uiEXT"); - gleswProgramUniform1uivEXT = (PFNGLPROGRAMUNIFORM1UIVEXTPROC)proc("glProgramUniform1uivEXT"); - gleswProgramUniform2fEXT = (PFNGLPROGRAMUNIFORM2FEXTPROC)proc("glProgramUniform2fEXT"); - gleswProgramUniform2fvEXT = (PFNGLPROGRAMUNIFORM2FVEXTPROC)proc("glProgramUniform2fvEXT"); - gleswProgramUniform2iEXT = (PFNGLPROGRAMUNIFORM2IEXTPROC)proc("glProgramUniform2iEXT"); - gleswProgramUniform2ivEXT = (PFNGLPROGRAMUNIFORM2IVEXTPROC)proc("glProgramUniform2ivEXT"); - gleswProgramUniform2uiEXT = (PFNGLPROGRAMUNIFORM2UIEXTPROC)proc("glProgramUniform2uiEXT"); - gleswProgramUniform2uivEXT = (PFNGLPROGRAMUNIFORM2UIVEXTPROC)proc("glProgramUniform2uivEXT"); - gleswProgramUniform3fEXT = (PFNGLPROGRAMUNIFORM3FEXTPROC)proc("glProgramUniform3fEXT"); - gleswProgramUniform3fvEXT = (PFNGLPROGRAMUNIFORM3FVEXTPROC)proc("glProgramUniform3fvEXT"); - gleswProgramUniform3iEXT = (PFNGLPROGRAMUNIFORM3IEXTPROC)proc("glProgramUniform3iEXT"); - gleswProgramUniform3ivEXT = (PFNGLPROGRAMUNIFORM3IVEXTPROC)proc("glProgramUniform3ivEXT"); - gleswProgramUniform3uiEXT = (PFNGLPROGRAMUNIFORM3UIEXTPROC)proc("glProgramUniform3uiEXT"); - gleswProgramUniform3uivEXT = (PFNGLPROGRAMUNIFORM3UIVEXTPROC)proc("glProgramUniform3uivEXT"); - gleswProgramUniform4fEXT = (PFNGLPROGRAMUNIFORM4FEXTPROC)proc("glProgramUniform4fEXT"); - gleswProgramUniform4fvEXT = (PFNGLPROGRAMUNIFORM4FVEXTPROC)proc("glProgramUniform4fvEXT"); - gleswProgramUniform4iEXT = (PFNGLPROGRAMUNIFORM4IEXTPROC)proc("glProgramUniform4iEXT"); - gleswProgramUniform4ivEXT = (PFNGLPROGRAMUNIFORM4IVEXTPROC)proc("glProgramUniform4ivEXT"); - gleswProgramUniform4uiEXT = (PFNGLPROGRAMUNIFORM4UIEXTPROC)proc("glProgramUniform4uiEXT"); - gleswProgramUniform4uivEXT = (PFNGLPROGRAMUNIFORM4UIVEXTPROC)proc("glProgramUniform4uivEXT"); - gleswProgramUniformHandleui64NV = (PFNGLPROGRAMUNIFORMHANDLEUI64NVPROC)proc("glProgramUniformHandleui64NV"); - gleswProgramUniformHandleui64vNV = (PFNGLPROGRAMUNIFORMHANDLEUI64VNVPROC)proc("glProgramUniformHandleui64vNV"); - gleswProgramUniformMatrix2fvEXT = (PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC)proc("glProgramUniformMatrix2fvEXT"); - gleswProgramUniformMatrix2x3fvEXT = (PFNGLPROGRAMUNIFORMMATRIX2X3FVEXTPROC)proc("glProgramUniformMatrix2x3fvEXT"); - gleswProgramUniformMatrix2x4fvEXT = (PFNGLPROGRAMUNIFORMMATRIX2X4FVEXTPROC)proc("glProgramUniformMatrix2x4fvEXT"); - gleswProgramUniformMatrix3fvEXT = (PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC)proc("glProgramUniformMatrix3fvEXT"); - gleswProgramUniformMatrix3x2fvEXT = (PFNGLPROGRAMUNIFORMMATRIX3X2FVEXTPROC)proc("glProgramUniformMatrix3x2fvEXT"); - gleswProgramUniformMatrix3x4fvEXT = (PFNGLPROGRAMUNIFORMMATRIX3X4FVEXTPROC)proc("glProgramUniformMatrix3x4fvEXT"); - gleswProgramUniformMatrix4fvEXT = (PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC)proc("glProgramUniformMatrix4fvEXT"); - gleswProgramUniformMatrix4x2fvEXT = (PFNGLPROGRAMUNIFORMMATRIX4X2FVEXTPROC)proc("glProgramUniformMatrix4x2fvEXT"); - gleswProgramUniformMatrix4x3fvEXT = (PFNGLPROGRAMUNIFORMMATRIX4X3FVEXTPROC)proc("glProgramUniformMatrix4x3fvEXT"); - gleswPushDebugGroupKHR = (PFNGLPUSHDEBUGGROUPKHRPROC)proc("glPushDebugGroupKHR"); - gleswPushGroupMarkerEXT = (PFNGLPUSHGROUPMARKEREXTPROC)proc("glPushGroupMarkerEXT"); - gleswQueryCounterEXT = (PFNGLQUERYCOUNTEREXTPROC)proc("glQueryCounterEXT"); - gleswRasterSamplesEXT = (PFNGLRASTERSAMPLESEXTPROC)proc("glRasterSamplesEXT"); - gleswReadBuffer = (PFNGLREADBUFFERPROC)proc("glReadBuffer"); - gleswReadBufferIndexedEXT = (PFNGLREADBUFFERINDEXEDEXTPROC)proc("glReadBufferIndexedEXT"); - gleswReadBufferNV = (PFNGLREADBUFFERNVPROC)proc("glReadBufferNV"); - gleswReadPixels = (PFNGLREADPIXELSPROC)proc("glReadPixels"); - gleswReadnPixelsEXT = (PFNGLREADNPIXELSEXTPROC)proc("glReadnPixelsEXT"); - gleswReadnPixelsKHR = (PFNGLREADNPIXELSKHRPROC)proc("glReadnPixelsKHR"); - gleswReleaseShaderCompiler = (PFNGLRELEASESHADERCOMPILERPROC)proc("glReleaseShaderCompiler"); - gleswRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)proc("glRenderbufferStorage"); - gleswRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)proc("glRenderbufferStorageMultisample"); - gleswRenderbufferStorageMultisampleANGLE = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEANGLEPROC)proc("glRenderbufferStorageMultisampleANGLE"); - gleswRenderbufferStorageMultisampleAPPLE = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEAPPLEPROC)proc("glRenderbufferStorageMultisampleAPPLE"); - gleswRenderbufferStorageMultisampleEXT = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC)proc("glRenderbufferStorageMultisampleEXT"); - gleswRenderbufferStorageMultisampleIMG = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEIMGPROC)proc("glRenderbufferStorageMultisampleIMG"); - gleswRenderbufferStorageMultisampleNV = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLENVPROC)proc("glRenderbufferStorageMultisampleNV"); - gleswResolveDepthValuesNV = (PFNGLRESOLVEDEPTHVALUESNVPROC)proc("glResolveDepthValuesNV"); - gleswResolveMultisampleFramebufferAPPLE = (PFNGLRESOLVEMULTISAMPLEFRAMEBUFFERAPPLEPROC)proc("glResolveMultisampleFramebufferAPPLE"); - gleswResumeTransformFeedback = (PFNGLRESUMETRANSFORMFEEDBACKPROC)proc("glResumeTransformFeedback"); - gleswSampleCoverage = (PFNGLSAMPLECOVERAGEPROC)proc("glSampleCoverage"); - gleswSamplerParameterIivEXT = (PFNGLSAMPLERPARAMETERIIVEXTPROC)proc("glSamplerParameterIivEXT"); - gleswSamplerParameterIivOES = (PFNGLSAMPLERPARAMETERIIVOESPROC)proc("glSamplerParameterIivOES"); - gleswSamplerParameterIuivEXT = (PFNGLSAMPLERPARAMETERIUIVEXTPROC)proc("glSamplerParameterIuivEXT"); - gleswSamplerParameterIuivOES = (PFNGLSAMPLERPARAMETERIUIVOESPROC)proc("glSamplerParameterIuivOES"); - gleswSamplerParameterf = (PFNGLSAMPLERPARAMETERFPROC)proc("glSamplerParameterf"); - gleswSamplerParameterfv = (PFNGLSAMPLERPARAMETERFVPROC)proc("glSamplerParameterfv"); - gleswSamplerParameteri = (PFNGLSAMPLERPARAMETERIPROC)proc("glSamplerParameteri"); - gleswSamplerParameteriv = (PFNGLSAMPLERPARAMETERIVPROC)proc("glSamplerParameteriv"); - gleswScissor = (PFNGLSCISSORPROC)proc("glScissor"); - gleswScissorArrayvNV = (PFNGLSCISSORARRAYVNVPROC)proc("glScissorArrayvNV"); - gleswScissorIndexedNV = (PFNGLSCISSORINDEXEDNVPROC)proc("glScissorIndexedNV"); - gleswScissorIndexedvNV = (PFNGLSCISSORINDEXEDVNVPROC)proc("glScissorIndexedvNV"); - gleswSelectPerfMonitorCountersAMD = (PFNGLSELECTPERFMONITORCOUNTERSAMDPROC)proc("glSelectPerfMonitorCountersAMD"); - gleswSetFenceNV = (PFNGLSETFENCENVPROC)proc("glSetFenceNV"); - gleswShaderBinary = (PFNGLSHADERBINARYPROC)proc("glShaderBinary"); - gleswShaderSource = (PFNGLSHADERSOURCEPROC)proc("glShaderSource"); - gleswStartTilingQCOM = (PFNGLSTARTTILINGQCOMPROC)proc("glStartTilingQCOM"); - gleswStencilFillPathInstancedNV = (PFNGLSTENCILFILLPATHINSTANCEDNVPROC)proc("glStencilFillPathInstancedNV"); - gleswStencilFillPathNV = (PFNGLSTENCILFILLPATHNVPROC)proc("glStencilFillPathNV"); - gleswStencilFunc = (PFNGLSTENCILFUNCPROC)proc("glStencilFunc"); - gleswStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)proc("glStencilFuncSeparate"); - gleswStencilMask = (PFNGLSTENCILMASKPROC)proc("glStencilMask"); - gleswStencilMaskSeparate = (PFNGLSTENCILMASKSEPARATEPROC)proc("glStencilMaskSeparate"); - gleswStencilOp = (PFNGLSTENCILOPPROC)proc("glStencilOp"); - gleswStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)proc("glStencilOpSeparate"); - gleswStencilStrokePathInstancedNV = (PFNGLSTENCILSTROKEPATHINSTANCEDNVPROC)proc("glStencilStrokePathInstancedNV"); - gleswStencilStrokePathNV = (PFNGLSTENCILSTROKEPATHNVPROC)proc("glStencilStrokePathNV"); - gleswStencilThenCoverFillPathInstancedNV = (PFNGLSTENCILTHENCOVERFILLPATHINSTANCEDNVPROC)proc("glStencilThenCoverFillPathInstancedNV"); - gleswStencilThenCoverFillPathNV = (PFNGLSTENCILTHENCOVERFILLPATHNVPROC)proc("glStencilThenCoverFillPathNV"); - gleswStencilThenCoverStrokePathInstancedNV = (PFNGLSTENCILTHENCOVERSTROKEPATHINSTANCEDNVPROC)proc("glStencilThenCoverStrokePathInstancedNV"); - gleswStencilThenCoverStrokePathNV = (PFNGLSTENCILTHENCOVERSTROKEPATHNVPROC)proc("glStencilThenCoverStrokePathNV"); - gleswSubpixelPrecisionBiasNV = (PFNGLSUBPIXELPRECISIONBIASNVPROC)proc("glSubpixelPrecisionBiasNV"); - gleswTestFenceNV = (PFNGLTESTFENCENVPROC)proc("glTestFenceNV"); - gleswTexBufferEXT = (PFNGLTEXBUFFEREXTPROC)proc("glTexBufferEXT"); - gleswTexBufferOES = (PFNGLTEXBUFFEROESPROC)proc("glTexBufferOES"); - gleswTexBufferRangeEXT = (PFNGLTEXBUFFERRANGEEXTPROC)proc("glTexBufferRangeEXT"); - gleswTexBufferRangeOES = (PFNGLTEXBUFFERRANGEOESPROC)proc("glTexBufferRangeOES"); - gleswTexImage2D = (PFNGLTEXIMAGE2DPROC)proc("glTexImage2D"); - gleswTexImage3D = (PFNGLTEXIMAGE3DPROC)proc("glTexImage3D"); - gleswTexImage3DOES = (PFNGLTEXIMAGE3DOESPROC)proc("glTexImage3DOES"); - gleswTexPageCommitmentEXT = (PFNGLTEXPAGECOMMITMENTEXTPROC)proc("glTexPageCommitmentEXT"); - gleswTexParameterIivEXT = (PFNGLTEXPARAMETERIIVEXTPROC)proc("glTexParameterIivEXT"); - gleswTexParameterIivOES = (PFNGLTEXPARAMETERIIVOESPROC)proc("glTexParameterIivOES"); - gleswTexParameterIuivEXT = (PFNGLTEXPARAMETERIUIVEXTPROC)proc("glTexParameterIuivEXT"); - gleswTexParameterIuivOES = (PFNGLTEXPARAMETERIUIVOESPROC)proc("glTexParameterIuivOES"); - gleswTexParameterf = (PFNGLTEXPARAMETERFPROC)proc("glTexParameterf"); - gleswTexParameterfv = (PFNGLTEXPARAMETERFVPROC)proc("glTexParameterfv"); - gleswTexParameteri = (PFNGLTEXPARAMETERIPROC)proc("glTexParameteri"); - gleswTexParameteriv = (PFNGLTEXPARAMETERIVPROC)proc("glTexParameteriv"); - gleswTexStorage1DEXT = (PFNGLTEXSTORAGE1DEXTPROC)proc("glTexStorage1DEXT"); - gleswTexStorage2D = (PFNGLTEXSTORAGE2DPROC)proc("glTexStorage2D"); - gleswTexStorage2DEXT = (PFNGLTEXSTORAGE2DEXTPROC)proc("glTexStorage2DEXT"); - gleswTexStorage3D = (PFNGLTEXSTORAGE3DPROC)proc("glTexStorage3D"); - gleswTexStorage3DEXT = (PFNGLTEXSTORAGE3DEXTPROC)proc("glTexStorage3DEXT"); - gleswTexStorage3DMultisampleOES = (PFNGLTEXSTORAGE3DMULTISAMPLEOESPROC)proc("glTexStorage3DMultisampleOES"); - gleswTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC)proc("glTexSubImage2D"); - gleswTexSubImage3D = (PFNGLTEXSUBIMAGE3DPROC)proc("glTexSubImage3D"); - gleswTexSubImage3DOES = (PFNGLTEXSUBIMAGE3DOESPROC)proc("glTexSubImage3DOES"); - gleswTextureStorage1DEXT = (PFNGLTEXTURESTORAGE1DEXTPROC)proc("glTextureStorage1DEXT"); - gleswTextureStorage2DEXT = (PFNGLTEXTURESTORAGE2DEXTPROC)proc("glTextureStorage2DEXT"); - gleswTextureStorage3DEXT = (PFNGLTEXTURESTORAGE3DEXTPROC)proc("glTextureStorage3DEXT"); - gleswTextureViewEXT = (PFNGLTEXTUREVIEWEXTPROC)proc("glTextureViewEXT"); - gleswTextureViewOES = (PFNGLTEXTUREVIEWOESPROC)proc("glTextureViewOES"); - gleswTransformFeedbackVaryings = (PFNGLTRANSFORMFEEDBACKVARYINGSPROC)proc("glTransformFeedbackVaryings"); - gleswTransformPathNV = (PFNGLTRANSFORMPATHNVPROC)proc("glTransformPathNV"); - gleswUniform1f = (PFNGLUNIFORM1FPROC)proc("glUniform1f"); - gleswUniform1fv = (PFNGLUNIFORM1FVPROC)proc("glUniform1fv"); - gleswUniform1i = (PFNGLUNIFORM1IPROC)proc("glUniform1i"); - gleswUniform1iv = (PFNGLUNIFORM1IVPROC)proc("glUniform1iv"); - gleswUniform1ui = (PFNGLUNIFORM1UIPROC)proc("glUniform1ui"); - gleswUniform1uiv = (PFNGLUNIFORM1UIVPROC)proc("glUniform1uiv"); - gleswUniform2f = (PFNGLUNIFORM2FPROC)proc("glUniform2f"); - gleswUniform2fv = (PFNGLUNIFORM2FVPROC)proc("glUniform2fv"); - gleswUniform2i = (PFNGLUNIFORM2IPROC)proc("glUniform2i"); - gleswUniform2iv = (PFNGLUNIFORM2IVPROC)proc("glUniform2iv"); - gleswUniform2ui = (PFNGLUNIFORM2UIPROC)proc("glUniform2ui"); - gleswUniform2uiv = (PFNGLUNIFORM2UIVPROC)proc("glUniform2uiv"); - gleswUniform3f = (PFNGLUNIFORM3FPROC)proc("glUniform3f"); - gleswUniform3fv = (PFNGLUNIFORM3FVPROC)proc("glUniform3fv"); - gleswUniform3i = (PFNGLUNIFORM3IPROC)proc("glUniform3i"); - gleswUniform3iv = (PFNGLUNIFORM3IVPROC)proc("glUniform3iv"); - gleswUniform3ui = (PFNGLUNIFORM3UIPROC)proc("glUniform3ui"); - gleswUniform3uiv = (PFNGLUNIFORM3UIVPROC)proc("glUniform3uiv"); - gleswUniform4f = (PFNGLUNIFORM4FPROC)proc("glUniform4f"); - gleswUniform4fv = (PFNGLUNIFORM4FVPROC)proc("glUniform4fv"); - gleswUniform4i = (PFNGLUNIFORM4IPROC)proc("glUniform4i"); - gleswUniform4iv = (PFNGLUNIFORM4IVPROC)proc("glUniform4iv"); - gleswUniform4ui = (PFNGLUNIFORM4UIPROC)proc("glUniform4ui"); - gleswUniform4uiv = (PFNGLUNIFORM4UIVPROC)proc("glUniform4uiv"); - gleswUniformBlockBinding = (PFNGLUNIFORMBLOCKBINDINGPROC)proc("glUniformBlockBinding"); - gleswUniformHandleui64NV = (PFNGLUNIFORMHANDLEUI64NVPROC)proc("glUniformHandleui64NV"); - gleswUniformHandleui64vNV = (PFNGLUNIFORMHANDLEUI64VNVPROC)proc("glUniformHandleui64vNV"); - gleswUniformMatrix2fv = (PFNGLUNIFORMMATRIX2FVPROC)proc("glUniformMatrix2fv"); - gleswUniformMatrix2x3fv = (PFNGLUNIFORMMATRIX2X3FVPROC)proc("glUniformMatrix2x3fv"); - gleswUniformMatrix2x3fvNV = (PFNGLUNIFORMMATRIX2X3FVNVPROC)proc("glUniformMatrix2x3fvNV"); - gleswUniformMatrix2x4fv = (PFNGLUNIFORMMATRIX2X4FVPROC)proc("glUniformMatrix2x4fv"); - gleswUniformMatrix2x4fvNV = (PFNGLUNIFORMMATRIX2X4FVNVPROC)proc("glUniformMatrix2x4fvNV"); - gleswUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)proc("glUniformMatrix3fv"); - gleswUniformMatrix3x2fv = (PFNGLUNIFORMMATRIX3X2FVPROC)proc("glUniformMatrix3x2fv"); - gleswUniformMatrix3x2fvNV = (PFNGLUNIFORMMATRIX3X2FVNVPROC)proc("glUniformMatrix3x2fvNV"); - gleswUniformMatrix3x4fv = (PFNGLUNIFORMMATRIX3X4FVPROC)proc("glUniformMatrix3x4fv"); - gleswUniformMatrix3x4fvNV = (PFNGLUNIFORMMATRIX3X4FVNVPROC)proc("glUniformMatrix3x4fvNV"); - gleswUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)proc("glUniformMatrix4fv"); - gleswUniformMatrix4x2fv = (PFNGLUNIFORMMATRIX4X2FVPROC)proc("glUniformMatrix4x2fv"); - gleswUniformMatrix4x2fvNV = (PFNGLUNIFORMMATRIX4X2FVNVPROC)proc("glUniformMatrix4x2fvNV"); - gleswUniformMatrix4x3fv = (PFNGLUNIFORMMATRIX4X3FVPROC)proc("glUniformMatrix4x3fv"); - gleswUniformMatrix4x3fvNV = (PFNGLUNIFORMMATRIX4X3FVNVPROC)proc("glUniformMatrix4x3fvNV"); - gleswUnmapBuffer = (PFNGLUNMAPBUFFERPROC)proc("glUnmapBuffer"); - gleswUnmapBufferOES = (PFNGLUNMAPBUFFEROESPROC)proc("glUnmapBufferOES"); - gleswUseProgram = (PFNGLUSEPROGRAMPROC)proc("glUseProgram"); - gleswUseProgramStagesEXT = (PFNGLUSEPROGRAMSTAGESEXTPROC)proc("glUseProgramStagesEXT"); - gleswValidateProgram = (PFNGLVALIDATEPROGRAMPROC)proc("glValidateProgram"); - gleswValidateProgramPipelineEXT = (PFNGLVALIDATEPROGRAMPIPELINEEXTPROC)proc("glValidateProgramPipelineEXT"); - gleswVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC)proc("glVertexAttrib1f"); - gleswVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC)proc("glVertexAttrib1fv"); - gleswVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC)proc("glVertexAttrib2f"); - gleswVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC)proc("glVertexAttrib2fv"); - gleswVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC)proc("glVertexAttrib3f"); - gleswVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC)proc("glVertexAttrib3fv"); - gleswVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC)proc("glVertexAttrib4f"); - gleswVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC)proc("glVertexAttrib4fv"); - gleswVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISORPROC)proc("glVertexAttribDivisor"); - gleswVertexAttribDivisorANGLE = (PFNGLVERTEXATTRIBDIVISORANGLEPROC)proc("glVertexAttribDivisorANGLE"); - gleswVertexAttribDivisorEXT = (PFNGLVERTEXATTRIBDIVISOREXTPROC)proc("glVertexAttribDivisorEXT"); - gleswVertexAttribDivisorNV = (PFNGLVERTEXATTRIBDIVISORNVPROC)proc("glVertexAttribDivisorNV"); - gleswVertexAttribI4i = (PFNGLVERTEXATTRIBI4IPROC)proc("glVertexAttribI4i"); - gleswVertexAttribI4iv = (PFNGLVERTEXATTRIBI4IVPROC)proc("glVertexAttribI4iv"); - gleswVertexAttribI4ui = (PFNGLVERTEXATTRIBI4UIPROC)proc("glVertexAttribI4ui"); - gleswVertexAttribI4uiv = (PFNGLVERTEXATTRIBI4UIVPROC)proc("glVertexAttribI4uiv"); - gleswVertexAttribIPointer = (PFNGLVERTEXATTRIBIPOINTERPROC)proc("glVertexAttribIPointer"); - gleswVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)proc("glVertexAttribPointer"); - gleswViewport = (PFNGLVIEWPORTPROC)proc("glViewport"); - gleswViewportArrayvNV = (PFNGLVIEWPORTARRAYVNVPROC)proc("glViewportArrayvNV"); - gleswViewportIndexedfNV = (PFNGLVIEWPORTINDEXEDFNVPROC)proc("glViewportIndexedfNV"); - gleswViewportIndexedfvNV = (PFNGLVIEWPORTINDEXEDFVNVPROC)proc("glViewportIndexedfvNV"); - gleswWaitSync = (PFNGLWAITSYNCPROC)proc("glWaitSync"); - gleswWaitSyncAPPLE = (PFNGLWAITSYNCAPPLEPROC)proc("glWaitSyncAPPLE"); - gleswWeightPathsNV = (PFNGLWEIGHTPATHSNVPROC)proc("glWeightPathsNV"); -} diff --git a/RenderSystems/GLSupport/CMakeLists.txt b/RenderSystems/GLSupport/CMakeLists.txt deleted file mode 100644 index c567c16bac0..00000000000 --- a/RenderSystems/GLSupport/CMakeLists.txt +++ /dev/null @@ -1,126 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure OpenGL Support build - -# Add platform specific settings - -if(EGL_FOUND) - cmake_dependent_option(OGRE_GLSUPPORT_USE_EGL "use EGL for GL Context Creation instead of GLX/ WGL" TRUE "NOT WIN32" FALSE) -endif() - -if(ANDROID) - file(GLOB PLATFORM_HEADERS "include/EGL/Android/*.h" "include/EGL/*.h") - file(GLOB PLATFORM_SOURCES "src/EGL/Android/*.cpp" "src/EGL/*.cpp") - - set(NATIVE_INCLUDES - ${CMAKE_CURRENT_SOURCE_DIR}/include/EGL - ${CMAKE_CURRENT_SOURCE_DIR}/include/EGL/Android) -elseif (EMSCRIPTEN) - file(GLOB PLATFORM_HEADERS "include/EGL/Emscripten/*.h" "include/EGL/*.h") - file(GLOB PLATFORM_SOURCES "src/EGL/Emscripten/*.cpp" "src/EGL/*.cpp") - - set(NATIVE_INCLUDES - ${CMAKE_CURRENT_SOURCE_DIR}/include/EGL - ${CMAKE_CURRENT_SOURCE_DIR}/include/EGL/Emscripten) -elseif (WIN32) - if(OGRE_GLSUPPORT_USE_EGL) - file(GLOB PLATFORM_HEADERS "include/EGL/WIN32/*.h" "include/EGL/*.h") - file(GLOB PLATFORM_SOURCES "src/EGL/WIN32/*.cpp" "src/EGL/*.cpp") - - set(NATIVE_INCLUDES - ${CMAKE_CURRENT_SOURCE_DIR}/include/EGL - ${CMAKE_CURRENT_SOURCE_DIR}/include/EGL/WIN32) - else() - file(GLOB PLATFORM_HEADERS "include/win32/*.h") - file(GLOB PLATFORM_SOURCES "src/win32/*.cpp") - - set(NATIVE_INCLUDES - ${CMAKE_CURRENT_SOURCE_DIR}/include/win32) - - set(PLATFORM_LIBS ${OPENGL_gl_LIBRARY}) - endif() -elseif(APPLE_IOS) - # only works with GLES2 - no shared components here. -elseif (APPLE) - file(GLOB PLATFORM_HEADERS "include/OSX/*.h") - file(GLOB PLATFORM_SOURCES "src/OSX/*.mm") - - # ignore usage of deprecated OSX API for now - add_definitions(-Wno-deprecated-declarations) - - set_source_files_properties("src/OSX/OgreOSXGL3PlusSupport.mm" - PROPERTIES COMPILE_FLAGS "-Wno-cast-qual") - - set(NATIVE_INCLUDES - ${CMAKE_CURRENT_SOURCE_DIR}/include/OSX - ${PROJECT_SOURCE_DIR}/OgreMain/include/OSX) - set(PLATFORM_LIBS "-framework AppKit" ${OPENGL_gl_LIBRARY}) -elseif (UNIX) - if(OGRE_GLSUPPORT_USE_EGL) - file(GLOB PLATFORM_HEADERS "include/EGL/X11/*.h" "include/EGL/*.h") - file(GLOB PLATFORM_SOURCES "src/EGL/X11/*.cpp" "src/EGL/*.cpp" "src/X11/*.cpp") - - set(NATIVE_INCLUDES - ${CMAKE_CURRENT_SOURCE_DIR}/include/EGL - ${CMAKE_CURRENT_SOURCE_DIR}/include/EGL/X11) - set(PLATFORM_LIBS ${X11_LIBRARIES} ${X11_Xrandr_LIB} ${EGL_LIBRARIES}) - else() - file(GLOB PLATFORM_HEADERS "include/GLX/*.h") - file(GLOB PLATFORM_SOURCES "src/GLX/*.cpp" "src/X11/*.cpp") - - set(NATIVE_INCLUDES - ${CMAKE_CURRENT_SOURCE_DIR}/include/GLX - ${OPENGL_INCLUDE_DIR}) - - if(NOT OPENGL_glx_LIBRARY) - set(OPENGL_glx_LIBRARY ${OPENGL_gl_LIBRARY}) - endif() - - set(PLATFORM_LIBS ${X11_LIBRARIES} ${X11_Xrandr_LIB} ${OPENGL_glx_LIBRARY}) - endif() - list(APPEND NATIVE_INCLUDES "${CMAKE_CURRENT_SOURCE_DIR}/src/X11/") -endif () - -file(GLOB GLSUPPORT_HEADERS "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -set(GLSUPPORT_HEADERS ${GLSUPPORT_HEADERS} ${PROJECT_BINARY_DIR}/include/OgreGLSupportPrerequisites.h PARENT_SCOPE) - -file(GLOB GLSL_SOURCES src/GLSL/*.cpp) - -if(OGRE_CONFIG_ENABLE_GL_STATE_CACHE_SUPPORT) - set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/src/OgreGLUniformCache.cpp - PROPERTIES COMPILE_DEFINITIONS OGRE_ENABLE_STATE_CACHE) -endif() - -add_library(OgreGLSupport STATIC - ${GLSUPPORT_HEADERS} ${PLATFORM_HEADERS} ${PLATFORM_SOURCES} ${GLSL_SOURCES} - src/OgreGLRenderSystemCommon.cpp - src/OgreGLTextureCommon.cpp - src/OgreGLDepthBufferCommon.cpp - src/OgreGLRenderTexture.cpp - src/OgreGLRenderToVertexBufferCommon.cpp - src/OgreGLHardwarePixelBufferCommon.cpp - src/OgreGLUniformCache.cpp - src/OgreGLVertexArrayObject.cpp - src/OgreGLWindow.cpp -) -target_link_libraries(OgreGLSupport PUBLIC OgreMain PRIVATE ${PLATFORM_LIBS}) -target_include_directories(OgreGLSupport PUBLIC - "$" - "$" - PRIVATE "$") - -set_property(TARGET OgreGLSupport PROPERTY POSITION_INDEPENDENT_CODE ON) -generate_export_header(OgreGLSupport - EXPORT_MACRO_NAME _OgreGLExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreGLSupportPrerequisites.h) - -if(OGRE_STATIC) - ogre_config_lib(OgreGLSupport TRUE) -endif() diff --git a/RenderSystems/GLSupport/include/EGL/Android/OgreAndroidEGLSupport.h b/RenderSystems/GLSupport/include/EGL/Android/OgreAndroidEGLSupport.h deleted file mode 100644 index 0e7be760c62..00000000000 --- a/RenderSystems/GLSupport/include/EGL/Android/OgreAndroidEGLSupport.h +++ /dev/null @@ -1,50 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __AndroidEGLSupport_H__ -#define __AndroidEGLSupport_H__ - -#include "OgreEGLSupport.h" - -namespace Ogre { - class _OgrePrivate AndroidEGLSupport : public EGLSupport - { - public: - AndroidEGLSupport(); - virtual ~AndroidEGLSupport(); - - ConfigOptionMap getConfigOptions() override; - - RenderWindow* newWindow(const String& name, - unsigned int width, unsigned int height, - bool fullScreen, - const NameValuePairList *miscParams = 0) override; - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/EGL/Android/OgreAndroidEGLWindow.h b/RenderSystems/GLSupport/include/EGL/Android/OgreAndroidEGLWindow.h deleted file mode 100644 index 25f51c67780..00000000000 --- a/RenderSystems/GLSupport/include/EGL/Android/OgreAndroidEGLWindow.h +++ /dev/null @@ -1,73 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __AndroidEGLWindow_H__ -#define __AndroidEGLWindow_H__ - -#include "OgreEGLWindow.h" -#include "OgreAndroidEGLSupport.h" -#include "android/configuration.h" - -#ifndef EGL_COVERAGE_BUFFERS_NV -#define EGL_COVERAGE_BUFFERS_NV 0x30E0 -#endif - -#ifndef EGL_COVERAGE_SAMPLES_NV -#define EGL_COVERAGE_SAMPLES_NV 0x30E1 -#endif - -namespace Ogre { - class _OgrePrivate AndroidEGLWindow : public EGLWindow - { - private: - int mMaxBufferSize; - int mMinBufferSize; - int mMaxDepthSize; - int mMaxStencilSize; - int mMSAA; - int mCSAA; - bool mPreserveContext; - float mScale; - - protected: - void resize(unsigned int width, unsigned int height) override; - void windowMovedOrResized() override; - - public: - AndroidEGLWindow(AndroidEGLSupport* glsupport); - void create(const String& name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams) override; - - float getViewPointToPixelScale() override { return mScale; } - - void _notifySurfaceDestroyed() override; - void _notifySurfaceCreated(void* window, void* config) override; - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/EGL/Emscripten/OgreEmscriptenEGLSupport.h b/RenderSystems/GLSupport/include/EGL/Emscripten/OgreEmscriptenEGLSupport.h deleted file mode 100644 index 99881a11dbc..00000000000 --- a/RenderSystems/GLSupport/include/EGL/Emscripten/OgreEmscriptenEGLSupport.h +++ /dev/null @@ -1,51 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __EmscriptenEGLSupport_H__ -#define __EmscriptenEGLSupport_H__ - -#include "OgreEGLSupport.h" - -namespace Ogre { - class _OgrePrivate EmscriptenEGLSupport : public EGLSupport - { - public: - EmscriptenEGLSupport(); - virtual ~EmscriptenEGLSupport(); - - virtual RenderWindow* newWindow(const String& name, - unsigned int width, unsigned int height, - bool fullScreen, - const NameValuePairList *miscParams = 0); - - virtual EGLConfig* chooseGLConfig(const EGLint* attribList, - EGLint *nElements); - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/EGL/Emscripten/OgreEmscriptenEGLWindow.h b/RenderSystems/GLSupport/include/EGL/Emscripten/OgreEmscriptenEGLWindow.h deleted file mode 100644 index 38ea56d9bd8..00000000000 --- a/RenderSystems/GLSupport/include/EGL/Emscripten/OgreEmscriptenEGLWindow.h +++ /dev/null @@ -1,81 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __EmscriptenEGLWindow_H__ -#define __EmscriptenEGLWindow_H__ - -#include "OgreEGLWindow.h" -#include "OgreEmscriptenEGLSupport.h" -#include - - -#ifndef EGL_COVERAGE_BUFFERS_NV -#define EGL_COVERAGE_BUFFERS_NV 0x30E0 -#endif - -#ifndef EGL_COVERAGE_SAMPLES_NV -#define EGL_COVERAGE_SAMPLES_NV 0x30E1 -#endif - -namespace Ogre { - class _OgrePrivate EmscriptenEGLWindow : public EGLWindow - { - private: - int mMaxBufferSize; - int mMinBufferSize; - int mMaxDepthSize; - int mMaxStencilSize; - int mMSAA; - int mCSAA; - int mOldWidth; - int mOldHeight; - String mCanvasSelector; - - protected: - void resize(unsigned int width, unsigned int height) override; - void windowMovedOrResized() override; - void switchFullScreen(bool fullscreen) override; - - static EM_BOOL canvasWindowResized(int eventType, const EmscriptenUiEvent *uiEvent, void *userData); - static EM_BOOL fullscreenCallback(int eventType, const EmscriptenFullscreenChangeEvent* event, void* userData); - static EM_BOOL contextLostCallback(int eventType, const void *reserved, void *userData); - static EM_BOOL contextRestoredCallback(int eventType, const void *reserved, void *userData); - - public: - EmscriptenEGLWindow(EmscriptenEGLSupport* glsupport); - virtual ~EmscriptenEGLWindow(); - void create(const String& name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams) override; - - void _notifySurfaceDestroyed() override; - void _notifySurfaceCreated(void* window, void* config = NULL) override; - void swapBuffers() override; - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/EGL/OgreEGLContext.h b/RenderSystems/GLSupport/include/EGL/OgreEGLContext.h deleted file mode 100644 index 7e8c7ccc6d7..00000000000 --- a/RenderSystems/GLSupport/include/EGL/OgreEGLContext.h +++ /dev/null @@ -1,72 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2008 Renato Araujo Oliveira Filho -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __EGLContext_H__ -#define __EGLContext_H__ - -#include "OgreGLContext.h" -#include - -namespace Ogre { - class EGLSupport; - - class _OgrePrivate EGLContext : public GLContext - { - ::EGLConfig mConfig; - const EGLSupport* mGLSupport; - ::EGLSurface mDrawable; - ::EGLContext mContext; - EGLDisplay mEglDisplay; - bool mExternalContext; - - public: - EGLContext(EGLDisplay eglDisplay, const EGLSupport* glsupport, ::EGLConfig fbconfig, ::EGLSurface drawable, ::EGLContext external); - - ~EGLContext(); - - void _createInternalResources(EGLDisplay eglDisplay, ::EGLConfig glconfig, ::EGLSurface drawable, ::EGLContext shareContext); - void _destroyInternalResources(); - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - void _updateInternalResources(EGLDisplay eglDisplay, ::EGLConfig glconfig, ::EGLSurface drawable); -#endif - - void setCurrent() override; - void endCurrent() override; - - GLContext* clone() const override { - return new EGLContext(mEglDisplay, mGLSupport, mConfig, mDrawable, NULL); - } - - EGLSurface getDrawable() const; - }; -} - -#endif - diff --git a/RenderSystems/GLSupport/include/EGL/OgreEGLRenderTexture.h b/RenderSystems/GLSupport/include/EGL/OgreEGLRenderTexture.h deleted file mode 100644 index abe5d7fc925..00000000000 --- a/RenderSystems/GLSupport/include/EGL/OgreEGLRenderTexture.h +++ /dev/null @@ -1,59 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2008 Renato Araujo Oliveira Filho -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __EGLRenderTexture_H__ -#define __EGLRenderTexture_H__ - -#include "OgrePrerequisites.h" -#include "OgreGLPBuffer.h" -#include "OgreEGLContext.h" -#include "OgreEGLSupport.h" - -namespace Ogre -{ - class GLContext; - class EGLSupport; - class EGLContext; - - class _OgrePrivate EGLPBuffer : public GLPBuffer - { - protected: - EGLSupport* mGLSupport; - EGLContext* mContext; - ::EGLDisplay mGlDisplay; - ::EGLSurface mEglDrawable; - public: - EGLPBuffer(EGLSupport* glsupport, PixelComponentType format, uint32 width, uint32 height); - virtual ~EGLPBuffer(); - - GLContext *getContext() const override { return mContext; } - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/EGL/OgreEGLSupport.h b/RenderSystems/GLSupport/include/EGL/OgreEGLSupport.h deleted file mode 100644 index e4c0c3ccbde..00000000000 --- a/RenderSystems/GLSupport/include/EGL/OgreEGLSupport.h +++ /dev/null @@ -1,106 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2008 Renato Araujo Oliveira Filho -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __EGLSupport_H__ -#define __EGLSupport_H__ - - -#include "OgreGLNativeSupport.h" -#include -#include "OgreEGLWindow.h" -#include "OgreLogManager.h" - -#define ENABLE_EGL_CHECK 0 - -#if ENABLE_EGL_CHECK - #define EGL_CHECK_ERROR \ - { \ - int e = eglGetError(); \ - if ((e != 0) && (e != EGL_SUCCESS))\ - { \ - char msgBuf[4096]; \ - sprintf(msgBuf, "EGL error 0x%04X in %s at line %i\n", e, __PRETTY_FUNCTION__, __LINE__); \ - LogManager::getSingleton().logMessage(msgBuf); \ - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, msgBuf, __PRETTY_FUNCTION__); \ - } \ - } -#else - #define EGL_CHECK_ERROR {} -#endif - -namespace Ogre { - class _OgrePrivate EGLSupport : public GLNativeSupport - { - protected: - EGLDisplay mGLDisplay; - NativeDisplayType mNativeDisplay; - - bool mIsExternalDisplay; - - VideoMode mOriginalMode; - VideoMode mCurrentMode; - - EGLint mEGLMajor, mEGLMinor; - - bool hasEGL15; - void initialiseExtensions(); - public: - EGLSupport(int profile); - - void start(void) override; - void stop(void) override; - - EGLDisplay getGLDisplay(void); - void setGLDisplay(EGLDisplay val); - EGLConfig* chooseGLConfig(const EGLint *attribList, EGLint *nElements); - EGLConfig* getConfigs(EGLint *nElements); - EGLBoolean getGLConfigAttrib(EGLConfig fbConfig, EGLint attribute, EGLint *value); - void* getProcAddress(const char* name) const override; - ::EGLContext createNewContext(EGLDisplay eglDisplay, ::EGLConfig glconfig, ::EGLContext shareList) const; - - RenderWindow* newWindow(const String& name, - unsigned int width, unsigned int height, - bool fullScreen, - const NameValuePairList *miscParams = 0) override { - return NULL; - } - - GLPBuffer* createPBuffer(PixelComponentType format, size_t width, size_t height) override; - - ::EGLConfig getGLConfigFromContext(::EGLContext context); - ::EGLConfig selectGLConfig (const EGLint* minAttribs, const EGLint *maxAttribs); - void switchMode(void); - virtual void switchMode(uint& width, uint& height, short& frequency) {} - // virtual GLPBuffer* createPBuffer(PixelComponentType format, - // size_t width, size_t height) = 0; -// NativeDisplayType getNativeDisplay(); - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/EGL/OgreEGLWindow.h b/RenderSystems/GLSupport/include/EGL/OgreEGLWindow.h deleted file mode 100644 index b3780c2e673..00000000000 --- a/RenderSystems/GLSupport/include/EGL/OgreEGLWindow.h +++ /dev/null @@ -1,89 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2008 Renato Araujo Oliveira Filho -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __EGLWindow_H__ -#define __EGLWindow_H__ - -#include "OgreGLWindow.h" -#include "OgreEGLSupport.h" -#include "OgreEGLContext.h" - -namespace Ogre { - class _OgrePrivate EGLWindow : public GLWindow - { - private: - protected: - EGLSupport* mGLSupport; - NativeWindowType mWindow; - NativeDisplayType mNativeDisplay; - ::EGLDisplay mEglDisplay; - - - ::EGLConfig mEglConfig; - ::EGLSurface mEglSurface; - - ::EGLSurface createSurfaceFromWindow(::EGLDisplay display, NativeWindowType win); - - virtual void switchFullScreen(bool fullscreen) {} - EGLContext * createEGLContext(::EGLContext external = NULL) const { - return new EGLContext(mEglDisplay, mGLSupport, mEglConfig, mEglSurface, external); - } - - void windowMovedOrResized() override {} - - void finaliseWindow(); - public: - EGLWindow(EGLSupport* glsupport); - virtual ~EGLWindow(); - - // default, PBuffer based, implementation - void create(const String& name, unsigned int width, unsigned int height, bool fullScreen, - const NameValuePairList* miscParams) override; - - void resize(unsigned int width, unsigned int height) override {} - - void setFullscreen (bool fullscreen, uint width, uint height) override; - void destroy(void) override; - void swapBuffers() override; - void setVSyncEnabled(bool vsync) override; - - /** - - * Get custom attribute; the following attributes are valid: - * WINDOW The X NativeWindowType target for rendering. - * GLCONTEXT The Ogre GLContext used for rendering. - * DISPLAY EGLDisplay connection behind that context. - */ - void getCustomAttribute(const String& name, void* pData) override; - - PixelFormat suggestPixelFormat() const override; - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/EGL/WIN32/OgreWin32EGLSupport.h b/RenderSystems/GLSupport/include/EGL/WIN32/OgreWin32EGLSupport.h deleted file mode 100644 index 3995fedb959..00000000000 --- a/RenderSystems/GLSupport/include/EGL/WIN32/OgreWin32EGLSupport.h +++ /dev/null @@ -1,66 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2008 Renato Araujo Oliveira Filho -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __WIN32EGLSupport_H__ -#define __WIN32EGLSupport_H__ - - -#include "OgreEGLSupport.h" - -namespace Ogre { - class _OgrePrivate Win32EGLSupport : public EGLSupport - { - protected: - - //Removed createEGLWindow because it was easier to just call - //new Win32EGLWindow in the code to get the native version - //virtual EGLWindow* createEGLWindow( EGLSupport * support); - - public: - Win32EGLSupport(int profile); - virtual ~Win32EGLSupport(); - - //virtual GLESPBuffer* createPBuffer(PixelComponentType format, - // size_t width, size_t height); - - RenderWindow* newWindow(const String& name, - unsigned int width, unsigned int height, - bool fullScreen, - const NameValuePairList *miscParams = 0); - - //Moved getNativeDisplay to native class - NativeDisplayType getNativeDisplay(); - - //This sets up the native variables then calls EGLSupport::getGLDisplay - EGLDisplay getGLDisplay(); - - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/EGL/WIN32/OgreWin32EGLWindow.h b/RenderSystems/GLSupport/include/EGL/WIN32/OgreWin32EGLWindow.h deleted file mode 100644 index fe8ac858d53..00000000000 --- a/RenderSystems/GLSupport/include/EGL/WIN32/OgreWin32EGLWindow.h +++ /dev/null @@ -1,53 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2008 Renato Araujo Oliveira Filho -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Win32EGLWindow_H__ -#define __Win32EGLWindow_H__ - -#include "OgreEGLWindow.h" -#include "OgreWin32EGLSupport.h" - -namespace Ogre { - class _OgrePrivate Win32EGLWindow : public EGLWindow - { - uint32 mColourDepth; - protected: - void createNativeWindow( int &left, int &top, uint &width, uint &height, String &title ); - virtual void resize(unsigned int width, unsigned int height); - virtual void windowMovedOrResized(); - - public: - Win32EGLWindow(Win32EGLSupport* glsupport); - void create(const String& name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams); - - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/EGL/X11/OgreX11EGLSupport.h b/RenderSystems/GLSupport/include/EGL/X11/OgreX11EGLSupport.h deleted file mode 100644 index b6cc520827f..00000000000 --- a/RenderSystems/GLSupport/include/EGL/X11/OgreX11EGLSupport.h +++ /dev/null @@ -1,80 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2008 Renato Araujo Oliveira Filho -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __X11EGLSupport_H__ -#define __X11EGLSupport_H__ - -// Tell EGL that we are using X11 (to select the appropriate definitions) -#define USE_X11 - -#include "OgreEGLSupport.h" - -#ifndef Status -#define Status int -#endif -#include -#include -// #include -#include -#include - -namespace Ogre { - class _OgrePrivate X11EGLSupport : public EGLSupport - { - protected: - - //removed createEGLWindow because it was easier to just use - // new X11EGLWindow in the code to get the native version. - //virtual EGLWindow* createEGLWindow( EGLSupport * support); - - public: - X11EGLSupport(int profile); - virtual ~X11EGLSupport(); - - NativeDisplayType getNativeDisplay(void); - XVisualInfo *getVisualFromFBConfig(::EGLConfig glConfig); - Atom mAtomDeleteWindow; - Atom mAtomFullScreen; - Atom mAtomState; - - // This just sets the native variables needed by EGLSupport::getGLDisplay - //Then it calls EGLSupport::getDLDisplay to do the rest of the work. - EGLDisplay getGLDisplay(); - - //Moved this here from EGLSupport because maybe it should be more native. - RenderWindow* newWindow(const String& name, - unsigned int width, unsigned int height, - bool fullScreen, - const NameValuePairList *miscParams = 0) override; - - }; -} - -#endif - diff --git a/RenderSystems/GLSupport/include/EGL/X11/OgreX11EGLWindow.h b/RenderSystems/GLSupport/include/EGL/X11/OgreX11EGLWindow.h deleted file mode 100644 index cefe57d6025..00000000000 --- a/RenderSystems/GLSupport/include/EGL/X11/OgreX11EGLWindow.h +++ /dev/null @@ -1,76 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2008 Renato Araujo Oliveira Filho -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __X11EGLWindow_H__ -#define __X11EGLWindow_H__ - -#include "OgreEGLWindow.h" -#include "OgreX11EGLSupport.h" - -namespace Ogre { - class _OgrePrivate X11EGLWindow : public EGLWindow - { - protected: - X11EGLSupport* mGLSupport; - - //Changed these variables back to Window type because - //it seems they are not used outside this class. - Window mParentWindow; - Window mExternalWindow; - void getLeftAndTopFromNativeWindow(int & left, int & top, uint width, uint height); - void initNativeCreatedWindow(const NameValuePairList *miscParams); - void createNativeWindow( int &left, int &top, uint &width, uint &height, String &title ); - void reposition(int left, int top) override; - void resize(unsigned int width, unsigned int height) override; - void windowMovedOrResized() override; - void switchFullScreen(bool fullscreen) override; - - - public: - X11EGLWindow(X11EGLSupport* glsupport); - virtual ~X11EGLWindow(); - - /** - - * Get custom attribute; the following attributes are valid: - * XDISPLAY The X Display connection behind that context. - * XWINDOW The X NativeWindowType connection behind that context. - * ATOM The X Atom used in client delete events. - */ - void getCustomAttribute(const String& name, void* pData) override; - - void setFullscreen (bool fullscreen, uint width, uint height) override; - - //Moved this from EGLWindow because it has some native calls. - void create(const String& name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams) override; - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/GLSL/OgreGLSLPreprocessor.h b/RenderSystems/GLSupport/include/GLSL/OgreGLSLPreprocessor.h deleted file mode 100644 index d87a01b7ccc..00000000000 --- a/RenderSystems/GLSupport/include/GLSL/OgreGLSLPreprocessor.h +++ /dev/null @@ -1,510 +0,0 @@ -/** - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#ifndef __OGRE_CPREPROCESSOR_H__ -#define __OGRE_CPREPROCESSOR_H__ - -#include "OgrePlatform.h" -#include -#include -#include -#include - -namespace Ogre { - - /** - * This is a simplistic C/C++-like preprocessor. - * It takes an non-zero-terminated string on input and outputs a - * non-zero-terminated string buffer. - * - * This preprocessor was designed specifically for GLSL shaders, so - * if you want to use it for other purposes you might want to check - * if the feature set it provides is enough for you. - * - * Here's a list of supported features: - * - Fast memory allocation-less operation (mostly). - * - Line continuation (backslash-newline) is swallowed. - * - Line numeration is fully preserved by inserting empty lines where - * required. This is crucial if, say, GLSL compiler reports you an error - * with a line number. - * - @c \#define: Parametrized and non-parametrized macros. Invoking a macro with - * less arguments than it takes assignes empty values to missing arguments. - * - @c \#undef: Forget defined macros - * - @c \#ifdef / @c \#ifndef / @c \#else / @c \#endif: Conditional suppression of parts of code. - * - @c \#if: Supports numeric expression of any complexity, also supports the - * defined() pseudo-function. - */ - class CPreprocessor - { - /** - * A input token. - * - * For performance reasons most tokens will point to portions of the - * input stream, so no unneeded memory allocation is done. However, - * in some cases we must allocate different memory for token storage, - * in this case this is signalled by setting the Allocated member - * to non-zero in which case the destructor will know that it must - * free memory on object destruction. - * - * Again for performance reasons we use malloc/realloc/free here because - * C++-style new[] lacks the realloc() counterpart. - */ - class Token - { - public: - enum Kind - { - TK_EOS, // End of input stream - TK_ERROR, // An error has been encountered - TK_WHITESPACE, // A whitespace span (but not newline) - TK_NEWLINE, // A single newline (CR & LF) - TK_LINECONT, // Line continuation ('\' followed by LF) - TK_NUMBER, // A number - TK_KEYWORD, // A keyword - TK_PUNCTUATION, // A punctuation character - TK_DIRECTIVE, // A preprocessor directive - TK_STRING, // A string - TK_COMMENT, // A block comment - TK_LINECOMMENT, // A line comment - TK_TEXT // An unparsed text (cannot be returned from GetToken()) - }; - - /// Token type - Kind Type; - /// True if string was allocated (and must be freed) - mutable size_t Allocated; - union - { - /// A pointer somewhere into the input buffer - const char *String; - /// A memory-allocated string - char *Buffer; - }; - /// Token length in bytes - size_t Length; - - Token () : Allocated (0), String (NULL), Length(0) - { } - - Token (Kind iType) : Type (iType), Allocated (0), String (NULL), Length(0) - { } - - Token (Kind iType, const char *iString, size_t iLength) : - Type (iType), Allocated (0), String (iString), Length (iLength) - { } - - Token (const Token &iOther) - { - Type = iOther.Type; - Allocated = iOther.Allocated; - iOther.Allocated = 0; // !!! not quite correct but effective - String = iOther.String; - Length = iOther.Length; - } - - ~Token () - { if (Allocated) free (Buffer); } - - /// Assignment operator - Token &operator = (const Token &iOther) - { - if (Allocated) free (Buffer); - Type = iOther.Type; - Allocated = iOther.Allocated; - iOther.Allocated = 0; // !!! not quite correct but effective - String = iOther.String; - Length = iOther.Length; - return *this; - } - - /// Append a string to this token - void Append (const char *iString, size_t iLength); - - /// Append a token to this token - void Append (const Token &iOther); - - /// Append given number of newlines to this token - void AppendNL (int iCount); - - /// Count number of newlines in this token - int CountNL (); - - /// Get the numeric value of the token - bool GetValue (long &oValue) const; - - /// Set the numeric value of the token - void SetValue (long iValue); - - /// Test two tokens for equality - bool operator == (const Token &iOther) - { - if (iOther.Length != Length) - return false; - return (memcmp (String, iOther.String, Length) == 0); - } - }; - - /// A macro definition - class Macro - { - public: - /// Macro name - Token Name; - /// The names of the arguments - std::vector Args; - /// The macro value - Token Value; - /// Unparsed macro body (keeps the whole raw unparsed macro body) - Token Body; - /// A pointer to function implementation (if macro is really a func) - Token (*ExpandFunc) (CPreprocessor *iParent, const std::vector& iArgs); - /// true if macro expansion is in progress - bool Expanding; - - Macro(const Token& iName) : Name(iName), ExpandFunc(NULL), Expanding(false) {} - - // Macro(Macro&&) = default; // TODO unsupported by VS2013 - - /// Expand the macro value (will not work for functions) - Token Expand (const std::vector& iArgs, std::forward_list& iMacros); - }; - - friend class CPreprocessor::Macro; - - /// The current source text input - const char *Source; - /// The end of the source text - const char *SourceEnd; - /// Current line number - int Line; - /// True if we are at beginning of line - bool BOL; - /// Are we expanding a macro? - bool SupplimentaryExpand; - /// A stack of 32 booleans packed into one value :) - unsigned EnableOutput; - unsigned EnableElif; - /// The list of macros defined so far - std::forward_list MacroList; - - /** - * Private constructor to re-parse a single token. - */ - CPreprocessor (const Token &iToken, int iLine); - - /** - * Stateless tokenizer: Parse the input text and return the next token. - * @param iExpand - * If true, macros will be expanded to their values - * @return - * The next token from the input stream - */ - Token GetToken (bool iExpand); - - /** - * Handle a preprocessor directive. - * @param iToken - * The whole preprocessor directive line (until EOL) - * @param iLine - * The line where the directive begins (for error reports) - * @return - * The last input token that was not proceeded. - */ - Token HandleDirective (Token &iToken, int iLine); - - /** - * Handle a #define directive. - * @param iBody - * The body of the directive (everything after the directive - * until end of line). - * @param iLine - * The line where the directive begins (for error reports) - * @return - * true if everything went ok, false if not - */ - bool HandleDefine (Token &iBody, int iLine); - - /** - * Undefine a previously defined macro - * @param iBody - * The body of the directive (everything after the directive - * until end of line). - * @param iLine - * The line where the directive begins (for error reports) - * @return - * true if everything went ok, false if not - */ - bool HandleUnDef (Token &iBody, int iLine); - - /** - * Handle an #ifdef directive. - * @param iBody - * The body of the directive (everything after the directive - * until end of line). - * @param iLine - * The line where the directive begins (for error reports) - * @return - * true if everything went ok, false if not - */ - bool HandleIfDef (Token &iBody, int iLine); - - /** - * Handle an #if directive. - * @param iBody - * The body of the directive (everything after the directive - * until end of line). - * @param iLine - * The line where the directive begins (for error reports) - * @return - * true if everything went ok, false if not - */ - bool HandleIf (Token &iBody, int iLine); - - /// @overload - bool HandleIf(bool val, int iLine); - - /** - * Handle an #elif directive. - * @param iBody - * The body of the directive (everything after the directive - * until end of line). - * @param iLine - * The line where the directive begins (for error reports) - * @return - * true if everything went ok, false if not - */ - bool HandleElif (Token &iBody, int iLine); - - /** - * Handle an #else directive. - * @param iBody - * The body of the directive (everything after the directive - * until end of line). - * @param iLine - * The line where the directive begins (for error reports) - * @return - * true if everything went ok, false if not - */ - bool HandleElse (Token &iBody, int iLine); - - /** - * Handle an #endif directive. - * @param iBody - * The body of the directive (everything after the directive - * until end of line). - * @param iLine - * The line where the directive begins (for error reports) - * @return - * true if everything went ok, false if not - */ - bool HandleEndIf (Token &iBody, int iLine); - - /** - * Get a single function argument until next ',' or ')'. - * @param oArg - * The argument is returned in this variable. - * @param iExpand - * If false, parameters are not expanded and no expressions are - * allowed; only a single keyword is expected per argument. - * @param shouldAppendArg - * When true, the argument will be appended the word word __arg_ - * e.g. #define myMacro(x) --> #define myMacro(x__arg_) - * This workaround a bug where calling myMacro( x ) would cause - * issues. - * @return - * The first unhandled token after argument. - */ - Token GetArgument (Token &oArg, bool iExpand, bool shouldAppendArg); - - /** - * Get all the arguments of a macro: '(' arg1 { ',' arg2 { ',' ... }} ')' - * @param oArgs - * This is set to a pointer to an array of parsed arguments. - * @param shouldAppendArg - * See GetArgument. - * @param iExpand - * If false, parameters are not expanded and no expressions are - * allowed; only a single keyword is expected per argument. - */ - Token GetArguments (std::vector& oArgs, bool iExpand, bool shouldAppendArg); - - /** - * Parse an expression, compute it and return the result. - * @param oResult - * A token containing the result of expression - * @param iLine - * The line at which the expression starts (for error reports) - * @param iOpPriority - * Operator priority (at which operator we will stop if - * proceeding recursively -- used internally. Parser stops - * when it encounters an operator with higher or equal priority). - * @return - * The last unhandled token after the expression - */ - Token GetExpression (Token &oResult, int iLine, int iOpPriority = 0); - - /** - * Get the numeric value of a token. - * If the token was produced by expanding a macro, we will get - * an TEXT token which can contain a whole expression; in this - * case we will call GetExpression to parse it. Otherwise we - * just call the token's GetValue() method. - * @param iToken - * The token to get the numeric value of - * @param oValue - * The variable to put the value into - * @param iLine - * The line where the directive begins (for error reports) - * @return - * true if ok, false if not - */ - bool GetValue (const Token &iToken, long &oValue, int iLine); - - /// @overload - /// same as above, but considers the defined() function - bool GetValueDef(const Token &iToken, long &oValue, int iLine); - - /** - * Expand the given macro, if it exists. - * If macro has arguments, they are collected from source stream. - * @param iToken - * A KEYWORD token containing the (possible) macro name. - * @return - * The expanded token or iToken if it is not a macro - */ - Token ExpandMacro (const Token &iToken); - - /** - * Check if a macro is defined, and if so, return it - * @param iToken - * Macro name - * @return - * The macro object or NULL if a macro with this name does not exist - */ - Macro *IsDefined (const Token &iToken); - - /** - * The implementation of the defined() preprocessor function - * @param iParent - * The parent preprocessor object - * @param iArgs - * The arguments themselves - * @return - * The return value encapsulated in a token - */ - static Token ExpandDefined (CPreprocessor *iParent, const std::vector& iArgs); - - /** - * Parse the input string and return a token containing the whole output. - * @param iSource - * The source text enclosed in a token - * @return - * The output text enclosed in a token - */ - Token Parse (const Token &iSource); - - /** - * Call the error handler - * @param iLine - * The line at which the error happened. - * @param iError - * The error string. - * @param iToken - * If not NULL contains the erroneous token - */ - void Error (int iLine, const char *iError, const Token *iToken = NULL); - - public: - /// Create an empty preprocessor object - CPreprocessor(); - - /// Destroy the preprocessor object - virtual ~CPreprocessor (); - - /** - * Define a macro without parameters. - * @param iMacroName - * The name of the defined macro - * @param iMacroNameLen - * The length of the name of the defined macro - * @param iMacroValue - * The value of the defined macro - * @param iMacroValueLen - * The length of the value of the defined macro - */ - void Define (const char *iMacroName, size_t iMacroNameLen, - const char *iMacroValue, size_t iMacroValueLen); - - /** - * Define a symbolical macro. - * @param iMacroName - * The name of the defined macro - * @param iMacroNameLen - * The length of the name of the defined macro - */ - void Define (const char *iMacroName, size_t iMacroNameLen); - - /** - * Undefine a macro. - * @param iMacroName - * The name of the macro to undefine - * @param iMacroNameLen - * The length of the name of the macro to undefine - * @return - * true if the macro has been undefined, false if macro doesn't exist - */ - bool Undef (const char *iMacroName, size_t iMacroNameLen); - - /** - * Parse the input string and return a newly-allocated output string. - * @note - * The returned preprocessed string is NOT zero-terminated - * (just like the input string). - * @param iSource - * The source text - * @param iLength - * The length of the source text in characters - * @param oLength - * The length of the output string. - * @return - * The output from preprocessor, allocated with malloc(). - * The parser can actually allocate more than needed for performance - * reasons, but this should not be a problem unless you will want - * to store the returned pointer for long time in which case you - * might want to realloc() it. - * If an error has been encountered, the function returns NULL. - * In some cases the function may return an unallocated address - * that's *inside* the source buffer. You must free() the result - * string only if the returned address is not inside the source text. - */ - char *Parse (const char *iSource, size_t iLength, size_t &oLength); - }; - -} // namespace Ogre - -#endif // __OGRE_CPREPROCESSOR_H__ diff --git a/RenderSystems/GLSupport/include/GLSL/OgreGLSLProgramCommon.h b/RenderSystems/GLSupport/include/GLSL/OgreGLSLProgramCommon.h deleted file mode 100644 index 8ed7a29a700..00000000000 --- a/RenderSystems/GLSupport/include/GLSL/OgreGLSLProgramCommon.h +++ /dev/null @@ -1,118 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef RENDERSYSTEMS_GLSUPPORT_INCLUDE_GLSL_OGREGLSLPROGRAMCOMMON_H_ -#define RENDERSYSTEMS_GLSUPPORT_INCLUDE_GLSL_OGREGLSLPROGRAMCOMMON_H_ - -#include "OgreGLSupportPrerequisites.h" -#include "OgreConfig.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreGLSLShaderCommon.h" - -#include - -namespace Ogre -{ -/// Structure used to keep track of named uniforms in the linked program object -struct GLUniformReference -{ - /// GL location handle - int mLocation; - /// Which type of program params will this value come from? - GpuProgramType mSourceProgType; - /// The constant definition it relates to - const GpuConstantDefinition* mConstantDef; -}; -typedef std::vector GLUniformReferenceList; -typedef GLUniformReferenceList::iterator GLUniformReferenceIterator; - -typedef std::array GLShaderList; - -class GLSLProgramCommon -{ -public: - explicit GLSLProgramCommon(const GLShaderList& shaders); - virtual ~GLSLProgramCommon() {} - - /// Get the GL Handle for the program object - uint getGLProgramHandle(void) const { return mGLProgramHandle; } - - /** Makes a program object active by making sure it is linked and then putting it in use. - */ - virtual void activate(void) = 0; - - /// query if the program is using the given shader - bool isUsingShader(GLSLShaderCommon* shader) const { return mShaders[shader->getType()] == shader; } - - /** Updates program object uniforms using data from GpuProgramParameters. - Normally called by GLSLShader::bindParameters() just before rendering occurs. - */ - virtual void updateUniforms(GpuProgramParametersPtr params, uint16 mask, GpuProgramType fromProgType) = 0; - - /** Get the fixed attribute bindings normally used by GL for a semantic. */ - static int32 getFixedAttributeIndex(VertexElementSemantic semantic, uint index); - - /** - * use alternate vertex attribute layout using only 8 vertex attributes - * - * For "Vivante GC1000" and "VideoCore IV" (notably in Raspberry Pi) on GLES2 - */ - static void useTightAttributeLayout(); -protected: - /// Container of uniform references that are active in the program object - GLUniformReferenceList mGLUniformReferences; - - /// Linked shaders - GLShaderList mShaders; - - /// Flag to indicate that uniform references have already been built - bool mUniformRefsBuilt; - /// GL handle for the program object - uint mGLProgramHandle; - /// Flag indicating that the program or pipeline object has been successfully linked - int mLinked; - - /// Compiles and links the vertex and fragment programs - virtual void compileAndLink(void) = 0; - - uint32 getCombinedHash(); - String getCombinedName(); - - /// Name / attribute list - struct CustomAttribute - { - const char* name; - int32 attrib; - VertexElementSemantic semantic; - }; - static CustomAttribute msCustomAttributes[17]; -}; - -} /* namespace Ogre */ - -#endif /* RENDERSYSTEMS_GLSUPPORT_INCLUDE_GLSL_OGREGLSLPROGRAMCOMMON_H_ */ diff --git a/RenderSystems/GLSupport/include/GLSL/OgreGLSLProgramManagerCommon.h b/RenderSystems/GLSupport/include/GLSL/OgreGLSLProgramManagerCommon.h deleted file mode 100644 index 9696829b221..00000000000 --- a/RenderSystems/GLSupport/include/GLSL/OgreGLSLProgramManagerCommon.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#ifndef __GLSLProgramManagerCommon_H__ -#define __GLSLProgramManagerCommon_H__ - -#include "OgreGLSupportPrerequisites.h" -#include "OgreString.h" -#include "OgreGpuProgramParams.h" -#include "OgreGLSLProgramCommon.h" - -namespace Ogre { - class GLSLShaderCommon; - - /** Ogre assumes that there are separate programs to deal with but - GLSL has one program object that represents the active shader - objects during a rendering state. GLSL shader objects are - compiled separately and then attached to a program object and - then the program object is linked. Since Ogre can only handle - one program being active in a pass, the GLSL Link Program - Manager does the same. The GLSL Link program manager acts as - a state machine and activates a program object based on the - active programs. Previously created program objects are - stored along with a unique key in a hash_map for quick - retrieval the next time the program object is required. - */ - class GLSLProgramManagerCommon - { - protected: - typedef std::map StringToEnumMap; - StringToEnumMap mTypeEnumMap; - - /** Parse an individual uniform from a GLSL source file and - store it in a GpuNamedConstant. */ - void parseGLSLUniform(String line, GpuNamedConstants& defs, const String& filename); - - /// checks whether the param with the given name should be added to the uniforms list - static bool validateParam(String paramName, uint32 numActiveArrayElements, - const GpuConstantDefinitionMap* (&constantDefs)[6], GLUniformReference& refToUpdate); - - typedef std::map ProgramMap; - typedef ProgramMap::iterator ProgramIterator; - - /// container holding previously created program objects - ProgramMap mPrograms; - - /// Active shader objects defining the active program object. - GLShaderList mActiveShader; - /// active objects defining the active rendering gpu state - GLSLProgramCommon* mActiveProgram; - public: - GLSLProgramManagerCommon(); - virtual ~GLSLProgramManagerCommon(); - - /** Populate a list of uniforms based on GLSL source and store - them in GpuNamedConstants. - @param src Reference to the source code. - @param constantDefs The defs to populate (will - not be cleared before adding, clear it yourself before - calling this if that's what you want). - @param filename The file name this came from, for logging errors. - */ - void extractUniformsFromGLSL( - const String& src, GpuNamedConstants& constantDefs, const String& filename); - - /// Destroy all programs which referencing this shader - void destroyAllByShader(GLSLShaderCommon* shader); - - /** Set the shader for the next rendering state. - The active program object will be cleared. - */ - void setActiveShader(GpuProgramType type, GLSLShaderCommon* shader); - }; - -} - -#endif // __GLSLProgramManagerCommon_H__ diff --git a/RenderSystems/GLSupport/include/GLSL/OgreGLSLShaderCommon.h b/RenderSystems/GLSupport/include/GLSL/OgreGLSLShaderCommon.h deleted file mode 100644 index 11b4dc80eb4..00000000000 --- a/RenderSystems/GLSupport/include/GLSL/OgreGLSLShaderCommon.h +++ /dev/null @@ -1,152 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLSLShaderCommon_H__ -#define __GLSLShaderCommon_H__ - -#include "OgreGLSupportPrerequisites.h" -#include "OgreHighLevelGpuProgram.h" -#include "OgreRenderOperation.h" -#include "OgreGLUniformCache.h" - -namespace Ogre { - /** Specialisation of HighLevelGpuProgram to provide support for OpenGL - Shader Language (GLSL). - - GLSL has no target assembler or entry point specification like DirectX 9 HLSL. - Vertex and Fragment shaders only have one entry point called "main". - When a shader is compiled, microcode is generated but can not be accessed by - the application. - GLSL also does not provide assembler low level output after compiling. Therefore the GLSLShader will also stand in - for the low level implementation. - The GLSLProgram class will create a shader object and compile the source but will not - create a program object. It's up to the GLSLProgramManager to request a program object to link the shader object to. - - @note - GLSL supports multiple modular shader objects that can be attached to one program - object to form a single shader. This is supported through the "attach" material script - command. All the modules to be attached are listed on the same line as the attach command - separated by white space. - - */ - class GLSLShaderCommon : public HighLevelGpuProgram - { - public: - /// Command object for attaching another GLSL Program - class CmdAttach : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& shaderNames) override; - }; - /// Command object for setting matrix packing in column-major order - class CmdColumnMajorMatrices : public ParamCommand - { - public: - String doGet(const void* target) const override; - void doSet(void* target, const String& val) override; - }; - - GLSLShaderCommon(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader); - - virtual void attachToProgramObject(const uint programObject) = 0; - virtual void detachFromProgramObject(const uint programObject) = 0; - - String getAttachedShaderNames() const { return mAttachedShaderNames; } - - /// Overridden - /** Attach another GLSL Shader to this one. */ - void attachChildShader(const String& name); - - /** Sets whether matrix packing in column-major order. */ - void setColumnMajorMatrices(bool columnMajor) { mColumnMajorMatrices = columnMajor; } - /** Gets whether matrix packed in column-major order. */ - bool getColumnMajorMatrices(void) const { return mColumnMajorMatrices; } - - /// Only used for separable programs. - virtual bool linkSeparable() { return false; } - - /// reset link status of separable program - void resetLinked() { mLinked = 0; } - - /// Get the OGRE assigned shader ID. - uint getShaderID(void) const { return mShaderID; } - - /// If we are using program pipelines, the OpenGL program handle - uint getGLProgramHandle() const { return mGLProgramHandle; } - - /// Get the uniform cache for this shader - GLUniformCache* getUniformCache(){return &mUniformCache;} - - /// GLSL does not provide access to the low level code of the shader, so use this shader for binding as well - GpuProgram* _getBindingDelegate(void) override { return this; } - protected: - /// GLSL does not provide access to the low level implementation of the shader, so this method s a no-op - void createLowLevelImpl() override {} - - static CmdAttach msCmdAttach; - static CmdColumnMajorMatrices msCmdColumnMajorMatrices; - - String getResourceLogName() const; - - void prepareImpl(void) override; - - /// Attached Shader names - String mAttachedShaderNames; - /// Container of attached programs - typedef std::vector< GLSLShaderCommon* > GLSLProgramContainer; - typedef GLSLProgramContainer::iterator GLSLProgramContainerIterator; - GLSLProgramContainer mAttachedGLSLPrograms; - /// Matrix in column major pack format? - bool mColumnMajorMatrices; - - /** Flag indicating that the shader has been successfully - linked. - Only used for separable programs. */ - int mLinked; - - /// OGRE assigned shader ID. - uint mShaderID; - - /// GL handle for shader object. - uint mGLShaderHandle; - /// GL handle for program object the shader is bound to. - uint mGLProgramHandle; - - int mShaderVersion; - - /// Pointer to the uniform cache for this shader - GLUniformCache mUniformCache; - - /// Keep track of the number of shaders created. - static uint mShaderCount; - }; -} - -#endif // __GLSLProgramCommon_H__ diff --git a/RenderSystems/GLSupport/include/GLX/OgreGLXContext.h b/RenderSystems/GLSupport/include/GLX/OgreGLXContext.h deleted file mode 100644 index fb8dc00177c..00000000000 --- a/RenderSystems/GLSupport/include/GLX/OgreGLXContext.h +++ /dev/null @@ -1,62 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OgreGLXContext_H__ -#define __OgreGLXContext_H__ - -#include "OgreGLContext.h" -#include "OgreGLXGLSupport.h" - -namespace Ogre { - - class _OgrePrivate GLXContext: public GLContext - { - public: - GLXContext(GLXGLSupport* glsupport, ::GLXFBConfig fbconfig, ::GLXDrawable drawable, ::GLXContext context = 0); - - virtual ~GLXContext(); - - /// @copydoc GLContext::setCurrent - virtual void setCurrent(); - - /// @copydoc GLContext::endCurrent - virtual void endCurrent(); - - /// @copydoc GLContext::clone - GLContext* clone() const; - - ::GLXDrawable mDrawable; - ::GLXContext mContext; - - private: - ::GLXFBConfig mFBConfig; - GLXGLSupport* mGLSupport; - bool mExternalContext; - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/GLX/OgreGLXGLSupport.h b/RenderSystems/GLSupport/include/GLX/OgreGLXGLSupport.h deleted file mode 100644 index e520700fca3..00000000000 --- a/RenderSystems/GLSupport/include/GLX/OgreGLXGLSupport.h +++ /dev/null @@ -1,172 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#ifndef OGRE_GLXGLSupport_H -#define OGRE_GLXGLSupport_H - -#include "OgreGLNativeSupport.h" - -#define GLX_GLXEXT_PROTOTYPES -#include -#include - -namespace Ogre { - - class _OgreGLExport GLXGLSupport : public GLNativeSupport - { - public: - GLXGLSupport(int profile); - ~GLXGLSupport(); - - Atom mAtomDeleteWindow; - Atom mAtomFullScreen; - Atom mAtomState; - - /// @copydoc RenderSystem::createRenderWindow - RenderWindow* newWindow(const String &name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams = 0); - - /// @copydoc GLNativeSupport::createPBuffer - GLPBuffer* createPBuffer(PixelComponentType format, size_t width, size_t height); - - /** @copydoc see GLNativeSupport::start */ - void start(); - - /** @copydoc see GLNativeSupport::stop */ - void stop(); - - /** @copydoc see GLNativeSupport::initialiseExtensions */ - void initialiseExtensions(); - - /** @copydoc see GLNativeSupport::getProcAddress */ - void* getProcAddress(const char* procname) const; - - // The remaining functions are internal to the GLX Rendersystem: - - /** - * Get the Display connection used for rendering - * - * This function establishes the initial connection when necessary. - * - * @returns Display connection - */ - Display* getGLDisplay(void); - - /** - * Get the Display connection used for window management & events - * - * @returns Display connection - */ - Display* getXDisplay(void); - - /** - * Switch video modes - * - * @param width Receiver for requested and final width - * @param height Receiver for requested and final drawable height - * @param height Receiver for requested and final drawable frequency - */ - void switchMode (uint& width, uint& height, short& frequency); - - /** - * Switch back to original video mode - */ - void switchMode (void); - - /** - * Get the GLXFBConfig used to create a ::GLXContext - * - * @param drawable GLXContext - * @returns GLXFBConfig used to create the context - */ - GLXFBConfig getFBConfigFromContext (::GLXContext context); - - /** - * Get the GLXFBConfig used to create a GLXDrawable. - * Caveat: GLX version 1.3 is needed when the drawable is a GLXPixmap - * - * @param drawable GLXDrawable - * @param width Receiver for the drawable width - * @param height Receiver for the drawable height - * @returns GLXFBConfig used to create the drawable - */ - GLXFBConfig getFBConfigFromDrawable (GLXDrawable drawable, unsigned int *width, unsigned int *height); - - /** - * Select an FBConfig given a list of required and a list of desired properties - * - * @param minAttribs FBConfig attributes that must be provided with minimum values - * @param maxAttribs FBConfig attributes that are desirable with maximum values - * @returns GLXFBConfig with attributes or 0 when unsupported. - */ - GLXFBConfig selectFBConfig(const int *minAttribs, const int *maxAttribs); - - /** - * Gets a GLXFBConfig compatible with a VisualID - * - * Some platforms fail to implement glXGetFBconfigFromVisualSGIX as - * part of the GLX_SGIX_fbconfig extension, but this portable - * alternative suffices for the creation of compatible contexts. - * - * @param visualid VisualID - * @returns FBConfig for VisualID - */ - GLXFBConfig getFBConfigFromVisualID(VisualID visualid); - - /** - * Portable replacement for glXChooseFBConfig - */ - GLXFBConfig* chooseFBConfig(const GLint *attribList, GLint *nElements); - - /** - * Portable replacement for glXCreateNewContext - */ - ::GLXContext createNewContext(GLXFBConfig fbConfig, GLint renderType, ::GLXContext shareList, GLboolean direct) const; - - /** - * Portable replacement for glXGetFBConfigAttrib - */ - GLint getFBConfigAttrib(GLXFBConfig fbConfig, GLint attribute, GLint *value); - - /** - * Portable replacement for glXGetVisualFromFBConfig - */ - XVisualInfo* getVisualFromFBConfig(GLXFBConfig fbConfig); - - private: - Display* mGLDisplay; // used for GL/GLX commands - Display* mXDisplay; // used for other X commands and events - bool mIsExternalDisplay; - - VideoMode mOriginalMode; - VideoMode mCurrentMode; - - int mGLXVerMajor, mGLXVerMinor; - }; -} - -#endif // OGRE_GLXGLSupport_H diff --git a/RenderSystems/GLSupport/include/GLX/OgreGLXRenderTexture.h b/RenderSystems/GLSupport/include/GLX/OgreGLXRenderTexture.h deleted file mode 100644 index 78da1598765..00000000000 --- a/RenderSystems/GLSupport/include/GLX/OgreGLXRenderTexture.h +++ /dev/null @@ -1,52 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __GLXRenderTexture_H__ -#define __GLXRenderTexture_H__ - -#include "OgrePrerequisites.h" - -#include "OgreGLPBuffer.h" -#include "OgreGLXContext.h" -#include "OgreGLXGLSupport.h" - -namespace Ogre -{ - class _OgrePrivate GLXPBuffer : public GLPBuffer - { - public: - GLXPBuffer(GLXGLSupport* glsupport, PixelComponentType format, size_t width, size_t height); - ~GLXPBuffer(); - - GLContext *getContext() const; - - protected: - GLXContext* mContext; - GLXGLSupport* mGLSupport; - }; -} -#endif diff --git a/RenderSystems/GLSupport/include/GLX/OgreGLXWindow.h b/RenderSystems/GLSupport/include/GLX/OgreGLXWindow.h deleted file mode 100644 index c171e84afc9..00000000000 --- a/RenderSystems/GLSupport/include/GLX/OgreGLXWindow.h +++ /dev/null @@ -1,93 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLXWindow_H__ -#define __GLXWindow_H__ - -#include "OgreGLWindow.h" - -#include - -namespace Ogre -{ - class GLXGLSupport; - - class _OgrePrivate GLXWindow : public GLWindow - { - public: - GLXWindow(GLXGLSupport* glsupport); - ~GLXWindow(); - - void create(const String& name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams); - - /** @copydoc see RenderWindow::setFullscreen */ - void setFullscreen (bool fullscreen, uint width, uint height); - - /** @copydoc see RenderWindow::destroy */ - void destroy(void); - - /** @copydoc see RenderWindow::setHidden */ - void setHidden(bool hidden); - - /** @copydoc see RenderWindow::setVSyncEnabled */ - void setVSyncEnabled(bool vsync); - - /** @copydoc see RenderWindow::reposition */ - void reposition(int left, int top); - - /** @copydoc see RenderWindow::resize */ - void resize(unsigned int width, unsigned int height); - - /** @copydoc see RenderWindow::windowMovedOrResized */ - void windowMovedOrResized(); - - /** @copydoc see RenderWindow::swapBuffers */ - void swapBuffers(); - - /** - - * Get custom attribute; the following attributes are valid: - * WINDOW The X Window target for rendering. - * GLCONTEXT The Ogre GLContext used for rendering. - * DISPLAY The X Display connection behind that context. - * DISPLAYNAME The X Server name for the connected display. - * ATOM The X Atom used in client delete events. - */ - void getCustomAttribute(const String& name, void* pData); - - PixelFormat suggestPixelFormat() const; - - private: - GLXGLSupport* mGLSupport; - ::Window mWindow; - void switchFullScreen(bool fullscreen); - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/OSX/OgreOSXCocoaContext.h b/RenderSystems/GLSupport/include/OSX/OgreOSXCocoaContext.h deleted file mode 100644 index 00e3f7eba05..00000000000 --- a/RenderSystems/GLSupport/include/OSX/OgreOSXCocoaContext.h +++ /dev/null @@ -1,70 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OgreOSXCocoaContext_H__ -#define __OgreOSXCocoaContext_H__ - -#include "OgreGLContext.h" -#include "OgrePrerequisites.h" - -#import - -namespace Ogre { - - class _OgreGLExport CocoaContext : public GLContext, public GeneralAllocatedObject - { - public: - CocoaContext(NSOpenGLContext *context, NSOpenGLPixelFormat *pixelFormat); - - virtual ~CocoaContext(); - - /** See GLContext */ - virtual void setCurrent(); - /** - * This is called before another context is made current. By default, - * nothing is done here. - */ - virtual void endCurrent(); - /** Create a new context based on the same window/pbuffer as this - context - mostly useful for additional threads. - @note The caller is responsible for deleting the returned context. - */ - virtual GLContext* clone() const; - - /** Grab the NSOpenGLContext if it exists */ - NSOpenGLContext* getContext(); - - /** Grab the NSOpenGLPixelFormat if it exists */ - NSOpenGLPixelFormat* getPixelFormat(); - - private: - NSOpenGLContext* mNSGLContext; - NSOpenGLPixelFormat *mNSGLPixelFormat; - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/OSX/OgreOSXCocoaView.h b/RenderSystems/GLSupport/include/OSX/OgreOSXCocoaView.h deleted file mode 100644 index fba1f8a8c63..00000000000 --- a/RenderSystems/GLSupport/include/OSX/OgreOSXCocoaView.h +++ /dev/null @@ -1,51 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __OSXCocoaView_H__ -#define __OSXCocoaView_H__ - -#include "OgreRenderWindow.h" -#include - -@interface OgreGLView : NSView -{ - Ogre::RenderWindow *window; -} - -- (id)initWithFrame:(NSRect)f; -- (id)initWithGLOSXWindow:(Ogre::RenderWindow*)w; - -- (void)setOgreWindow:(Ogre::RenderWindow*)w; -- (Ogre::RenderWindow*)ogreWindow; - -- (void)setFrameSize:(NSSize)s; - -@end - -#endif - diff --git a/RenderSystems/GLSupport/include/OSX/OgreOSXCocoaWindow.h b/RenderSystems/GLSupport/include/OSX/OgreOSXCocoaWindow.h deleted file mode 100644 index 3ddeb923779..00000000000 --- a/RenderSystems/GLSupport/include/OSX/OgreOSXCocoaWindow.h +++ /dev/null @@ -1,109 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __OSXCocoaWindow_H__ -#define __OSXCocoaWindow_H__ - -#include "OgreOSXCocoaContext.h" - -#include -#include -#include "OgreOSXCocoaView.h" -#include "OgreGLWindow.h" - -typedef NSUInteger NSWindowStyleMask; // NSWindowStyleMask was declared only since OSX 10.12 SDK - -@interface OgreGLWindow : NSWindow - -@end - -namespace Ogre { - class _OgreGLExport CocoaWindow : public GLWindow - { - private: - NSWindow *mWindow; - NSView *mView; - NSOpenGLContext *mGLContext; - NSOpenGLPixelFormat *mGLPixelFormat; - CVDisplayLinkRef mDisplayLink; - NSPoint mWindowOriginPt; - - bool mHasResized; - String mWindowTitle; - bool mUseOgreGLView; - float mContentScalingFactor; - NSWindowStyleMask mStyleMask; - - int _getPixelFromPoint(int viewPt) const; - void _setWindowParameters(unsigned int widthPt, unsigned int heightPt); - - public: - CocoaWindow(); - ~CocoaWindow(); - - NSView* ogreView() const { return mView; } - NSWindow* ogreWindow() const { return mWindow; } - NSOpenGLContext* nsopenGLContext() const { return mGLContext; } - GLContext* getContext() const { return mContext; } - void createWithView(OgreGLView *view); - - /** @copydoc see RenderWindow::getViewPointToPixelScale */ - float getViewPointToPixelScale(); - /** Overridden - see RenderWindow */ - void create(const String& name, unsigned int widthPt, unsigned int heightPt, - bool fullScreen, const NameValuePairList *miscParams); - /** Overridden - see RenderWindow */ - void destroy(void); - /** @copydoc see RenderWindow::setHidden */ - void setHidden(bool hidden); - /** @copydoc see RenderWindow::setVSyncEnabled */ - void setVSyncEnabled(bool vsync); - /** Overridden - see RenderWindow */ - void reposition(int leftPt, int topPt); - /** Overridden - see RenderWindow */ - void resize(unsigned int widthPt, unsigned int heightPt); - /** Overridden - see RenderWindow */ - void swapBuffers(); - /** Overridden - see RenderWindow */ - virtual void setFullscreen(bool fullScreen, unsigned int widthPt, unsigned int heightPt); - /** Overridden - see RenderWindow */ - virtual unsigned int getWidth(void) const; - /** Overridden - see RenderWindow */ - virtual unsigned int getHeight(void) const; - /** Overridden - see RenderWindow */ - void windowMovedOrResized(void); - void windowHasResized(void); - void createNewWindow(unsigned int width, unsigned int height, String title); - void createWindowFromExternal(NSView *viewRef); - - void getCustomAttribute( const String& name, void* pData ); - }; -} - -#endif - diff --git a/RenderSystems/GLSupport/include/OSX/OgreOSXGLSupport.h b/RenderSystems/GLSupport/include/OSX/OgreOSXGLSupport.h deleted file mode 100644 index 3426d41a123..00000000000 --- a/RenderSystems/GLSupport/include/OSX/OgreOSXGLSupport.h +++ /dev/null @@ -1,75 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef OGRE_OSXGLSupport_H -#define OGRE_OSXGLSupport_H - -#include "OgreGLNativeSupport.h" -#include - -namespace Ogre -{ - -class OSXGLSupport : public GLNativeSupport -{ -public: - OSXGLSupport(int profile) : GLNativeSupport(profile) {} - ~OSXGLSupport() {} - - ConfigOptionMap getConfigOptions(); - - /// @copydoc RenderSystem::createRenderWindow - virtual RenderWindow* newWindow( const String &name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams = 0 ); - - /** - * Start anything special - */ - void start(); - - /** - * Stop anything special - */ - void stop(); - - /** - * Get the address of a function - */ - void* getProcAddress( const char *name ) const; - - // Core Foundation Array callback function for sorting, must be static for the function ptr - static CFComparisonResult _compareModes (const void *val1, const void *val2, void *context); - // Core Fondation Dictionary helper functions, also static for ease of use in above static - static Boolean _getDictionaryBoolean(CFDictionaryRef dict, const void* key); - static long _getDictionaryLong(CFDictionaryRef dict, const void* key); - -}; - -} // namespace Ogre - -#endif // OGRE_OSXGLSupport_H diff --git a/RenderSystems/GLSupport/include/OSX/OgreOSXRenderTexture.h b/RenderSystems/GLSupport/include/OSX/OgreOSXRenderTexture.h deleted file mode 100644 index dfbe6265d2e..00000000000 --- a/RenderSystems/GLSupport/include/OSX/OgreOSXRenderTexture.h +++ /dev/null @@ -1,57 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OSXRenderTexture_H__ -#define __OSXRenderTexture_H__ - -#include "OgrePrerequisites.h" - -#include "OgreGLPBuffer.h" -#include "OgreOSXCocoaContext.h" - -namespace Ogre -{ - class OSXPBuffer : public GLPBuffer, public GeneralAllocatedObject - { - public: - OSXPBuffer(PixelComponentType format, uint32 width, uint32 height ); - ~OSXPBuffer(); - - GLContext *getContext() const; - - protected: - void createPBuffer(); - void destroyPBuffer(); - - private: - AGLPbuffer mPBuffer; - AGLContext mAGLContext; - OSXCocoaContext* mContext; - }; -} -#endif - diff --git a/RenderSystems/GLSupport/include/OgreGLContext.h b/RenderSystems/GLSupport/include/OgreGLContext.h deleted file mode 100644 index 0478d206d6f..00000000000 --- a/RenderSystems/GLSupport/include/OgreGLContext.h +++ /dev/null @@ -1,99 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OgreGLContext_H__ -#define __OgreGLContext_H__ - -#include "OgreGLSupportPrerequisites.h" -#include "OgreGLStateCacheManagerCommon.h" -#include "OgreSharedPtr.h" - -namespace Ogre { - - /** - * Class that encapsulates an GL context. (IE a window/pbuffer). This is a - * virtual base class which should be implemented in a GLSupport. - * This object can also be used to cache renderstate if we decide to do so - * in the future. - */ - class _OgreGLExport GLContext - { - public: - GLContext() : initialized(false) {} - virtual ~GLContext() {} - - /** - * Enable the context. All subsequent rendering commands will go here. - */ - virtual void setCurrent() = 0; - /** - * This is called before another context is made current. By default, - * nothing is done here. - */ - virtual void endCurrent() = 0; - - bool getInitialized() { return initialized; }; - void setInitialized() { initialized = true; }; - - /** Create a new context based on the same window/pbuffer as this - context - mostly useful for additional threads. - @note The caller is responsible for deleting the returned context. - */ - virtual GLContext* clone() const OGRE_NODISCARD = 0; - - /** - * Release the render context. - */ - virtual void releaseContext() {} - - /** - * Get the state cache manager, creating it on demand - */ - template - StateCacheManager* createOrRetrieveStateCacheManager() { - if(!mStateCacheManager) { - StateCacheManager* stateCache = OGRE_NEW StateCacheManager; - stateCache->initializeCache(); - mStateCacheManager = SharedPtr(stateCache); - } - return static_cast(mStateCacheManager.get()); - } - - /// VAOs deferred for destruction in proper GL context - std::vector& _getVaoDeferredForDestruction() { return mVaoDeferredForDestruction; } - /// FBOs deferred for destruction in proper GL context - std::vector& _getFboDeferredForDestruction() { return mFboDeferredForDestruction; } - - protected: - bool initialized; - SharedPtr mStateCacheManager; - std::vector mVaoDeferredForDestruction; - std::vector mFboDeferredForDestruction; - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/OgreGLDepthBufferCommon.h b/RenderSystems/GLSupport/include/OgreGLDepthBufferCommon.h deleted file mode 100644 index 5ad74b021c4..00000000000 --- a/RenderSystems/GLSupport/include/OgreGLDepthBufferCommon.h +++ /dev/null @@ -1,48 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. - -#ifndef RENDERSYSTEMS_GLSUPPORT_INCLUDE_OGREGLDEPTHBUFFERCOMMON_H_ -#define RENDERSYSTEMS_GLSUPPORT_INCLUDE_OGREGLDEPTHBUFFERCOMMON_H_ - -#include "OgreGLSupportPrerequisites.h" -#include "OgreDepthBuffer.h" -#include "OgreGLContext.h" -#include "OgreGLRenderSystemCommon.h" -#include "OgreGLHardwarePixelBufferCommon.h" - -namespace Ogre -{ - /** - OpenGL supports 3 different methods: FBO, pbuffer & Copy. - Each one has it's own limitations. Non-FBO methods are solved using "dummy" DepthBuffers. - That is, a DepthBuffer pointer is attached to the RenderTarget (for the sake of consistency) - but it doesn't actually contain a Depth surface/renderbuffer (mDepthBuffer & mStencilBuffer are - null pointers all the time) Those dummy DepthBuffers are identified thanks to their GL context. - Note that FBOs don't allow sharing with the main window's depth buffer. Therefore even - when FBO is enabled, a dummy DepthBuffer is still used to manage the windows. - */ - class GLDepthBufferCommon : public DepthBuffer - { - public: - GLDepthBufferCommon(uint16 poolId, GLRenderSystemCommon* renderSystem, GLContext* creatorContext, - GLHardwarePixelBufferCommon* depth, GLHardwarePixelBufferCommon* stencil, - const RenderTarget* target, bool isManual); - - virtual ~GLDepthBufferCommon(); - - bool isCompatible( RenderTarget *renderTarget ) const override; - - GLContext* getGLContext() const { return mCreatorContext; } - GLHardwarePixelBufferCommon* getDepthBuffer() const { return mDepthBuffer; } - GLHardwarePixelBufferCommon* getStencilBuffer() const { return mStencilBuffer; } - - protected: - GLContext *mCreatorContext; - GLHardwarePixelBufferCommon *mDepthBuffer; - GLHardwarePixelBufferCommon *mStencilBuffer; - GLRenderSystemCommon *mRenderSystem; - }; -} // namespace Ogre - -#endif diff --git a/RenderSystems/GLSupport/include/OgreGLHardwarePixelBufferCommon.h b/RenderSystems/GLSupport/include/OgreGLHardwarePixelBufferCommon.h deleted file mode 100644 index 4361d9d062b..00000000000 --- a/RenderSystems/GLSupport/include/OgreGLHardwarePixelBufferCommon.h +++ /dev/null @@ -1,80 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef RENDERSYSTEMS_GLSUPPORT_INCLUDE_OGREGLHARDWAREPIXELBUFFERCOMMON_H_ -#define RENDERSYSTEMS_GLSUPPORT_INCLUDE_OGREGLHARDWAREPIXELBUFFERCOMMON_H_ - -#include "OgreGLSupportPrerequisites.h" -#include "OgreTexture.h" -#include "OgreHardwarePixelBuffer.h" - -namespace Ogre -{ - -class _OgreGLExport GLHardwarePixelBufferCommon : public HardwarePixelBuffer -{ -protected: - /// Lock a box - PixelBox lockImpl(const Box &lockBox, LockOptions options) override; - - /// Unlock a box - void unlockImpl(void) override; - - // Internal buffer; either on-card or in system memory, freed/allocated on demand - // depending on buffer usage - PixelBox mBuffer; - uint32 mGLInternalFormat; // GL internal format - - // Buffer allocation/freeage - void allocateBuffer(); - - void freeBuffer(); - - // Upload a box of pixels to this buffer on the card - virtual void upload(const PixelBox &data, const Box &dest); - - // Download a box of pixels from the card - virtual void download(const PixelBox &data); -public: - /// Should be called by HardwareBufferManager - GLHardwarePixelBufferCommon(uint32 mWidth, uint32 mHeight, uint32 mDepth, - PixelFormat mFormat, - HardwareBuffer::Usage usage); - - virtual ~GLHardwarePixelBufferCommon(); - - /** Bind surface to frame buffer. Needs FBO extension. - */ - virtual void bindToFramebuffer(uint32 attachment, uint32 zoffset); - - uint32 getGLFormat() { return mGLInternalFormat; } -}; - -} /* namespace Ogre */ - -#endif /* RENDERSYSTEMS_GLSUPPORT_INCLUDE_OGREGLHARDWAREPIXELBUFFERCOMMON_H_ */ diff --git a/RenderSystems/GLSupport/include/OgreGLNativeSupport.h b/RenderSystems/GLSupport/include/OgreGLNativeSupport.h deleted file mode 100644 index ea9bfb0ac13..00000000000 --- a/RenderSystems/GLSupport/include/OgreGLNativeSupport.h +++ /dev/null @@ -1,118 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLNativeSupport_H__ -#define __GLNativeSupport_H__ - -#include "OgreGLSupportPrerequisites.h" -#include "OgreConfigOptionMap.h" -#include "OgrePixelFormat.h" -#include "OgreException.h" -#include "OgreGLRenderSystemCommon.h" - -namespace Ogre -{ - class GLPBuffer; - - struct VideoMode { - uint32 width; - uint32 height; - int16 refreshRate; - uint8 bpp; - - String getDescription() const; - }; - typedef std::vector VideoModes; - - /** - * provides OpenGL Context creation using GLX, WGL, EGL, Cocoa - */ - class _OgreGLExport GLNativeSupport - { - public: - typedef std::set ExtensionList; - - enum ContextProfile { - CONTEXT_CORE = 1, - CONTEXT_COMPATIBILITY = 2, - CONTEXT_ES = 4 - }; - - GLNativeSupport(int profile) : mContextProfile(ContextProfile(profile)) {} - virtual ~GLNativeSupport() {} - - /// @copydoc RenderSystem::_createRenderWindow - virtual RenderWindow* newWindow(const String &name, - unsigned int width, unsigned int height, - bool fullScreen, - const NameValuePairList *miscParams = 0) = 0; - - virtual GLPBuffer* createPBuffer(PixelComponentType format, size_t width, size_t height) { - return NULL; - } - - /** - * Get the address of a function - */ - virtual void *getProcAddress(const char* procname) const = 0; - - bool checkExtension(const String& ext) const { - return extensionList.find(ext) != extensionList.end(); - } - - /** - * Start anything special - */ - virtual void start() = 0; - /** - * Stop anything special - */ - virtual void stop() = 0; - - /** - * Add any special config values to the system. - */ - virtual ConfigOptionMap getConfigOptions() { return ConfigOptionMap(); } - - const std::vector& getFSAALevels() const { return mFSAALevels; } - const VideoModes& getVideoModes() const { return mVideoModes; } - - ContextProfile getContextProfile() const { return mContextProfile; } - protected: - // Allowed video modes - VideoModes mVideoModes; - std::vector mFSAALevels; - - // Supported platform extensions (e.g EGL_*, GLX_*) - ExtensionList extensionList; - - ContextProfile mContextProfile; - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/OgreGLPBuffer.h b/RenderSystems/GLSupport/include/OgreGLPBuffer.h deleted file mode 100755 index ee89ccfc91d..00000000000 --- a/RenderSystems/GLSupport/include/OgreGLPBuffer.h +++ /dev/null @@ -1,57 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLPBUFFER_H__ -#define __GLPBUFFER_H__ - -#include "OgreGLSupportPrerequisites.h" -#include "OgreGLRenderTarget.h" - -namespace Ogre { - /** An off-screen rendering context. These contexts are always RGBA for simplicity, speed and - convience, but the component format is configurable. - */ - class _OgreGLExport GLPBuffer : public GLRenderTarget - { - public: - GLPBuffer(PixelComponentType format, uint32 width, uint32 height) - : mFormat(format), mWidth(width), mHeight(height) {} - virtual ~GLPBuffer() {} - - PixelComponentType getFormat() { return mFormat; } - uint32 getWidth() { return mWidth; } - uint32 getHeight() { return mHeight; } - - protected: - PixelComponentType mFormat; - uint32 mWidth, mHeight; - }; - -} - -#endif // __GLPBRENDERTEXTURE_H__ diff --git a/RenderSystems/GLSupport/include/OgreGLRenderSystemCommon.h b/RenderSystems/GLSupport/include/OgreGLRenderSystemCommon.h deleted file mode 100644 index 4fad6473d10..00000000000 --- a/RenderSystems/GLSupport/include/OgreGLRenderSystemCommon.h +++ /dev/null @@ -1,159 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OgreGLRenderSystemCommon_H__ -#define __OgreGLRenderSystemCommon_H__ - -#include "OgreGLSupportPrerequisites.h" -#include "OgreRenderSystem.h" -#include "OgreRenderWindow.h" - -// Convenience macro from ARB_vertex_buffer_object spec -#define VBO_BUFFER_OFFSET(i) ((char *)size_t(i)) - -namespace Ogre { - class GLContext; - class GLSLProgramCommon; - class GLNativeSupport; - class GLRTTManager; - - class _OgreGLExport GLRenderSystemCommon : public RenderSystem - { - protected: - /* The main GL context - main thread only */ - GLContext* mMainContext; - - /* The current GL context - main thread only */ - GLContext* mCurrentContext; - - // GL support class, used for creating windows etc. - GLNativeSupport* mGLSupport; - - // This contains the complete list of supported extensions - std::set mExtensionList; - GPUVendor mVendor; - - /** Manager object for creating render textures. - Direct render to texture via FBO is preferable - to pbuffers, which depend on the GL support used and are generally - unwieldy and slow. However, FBO support for stencil buffers is poor. - */ - GLRTTManager *mRTTManager; - - void initConfigOptions() override; - void refreshConfig(); - - typedef std::list GLContextList; - /// List of background thread contexts - GLContextList mBackgroundContextList; - OGRE_MUTEX(mThreadInitMutex); - - /** One time initialization for the RenderState of a context. Things that - only need to be set once, like the LightingModel can be defined here. - */ - virtual void _oneTimeContextInitialization() = 0; - public: - /** - Specific options: - - | Key | Default | Description | - |-----|---------------|---------| - | Reversed Z-Buffer | false | Use reverse depth buffer to improve depth precision (GL3+ only) | - | Separate Shader Objects | false | Compile shaders individually instad of using monolithic programs. Better introspection. Allows mixing GLSL and SPIRV shaders (GL3+ only) | - | Fixed Pipeline Enabled | true | Use fixed function units where possible. Disable to test migration to shader-only pipeline (GL only) | - */ - void setConfigOption(const String &name, const String &value) override; - - virtual ~GLRenderSystemCommon() {} - - /** @copydoc RenderTarget::copyContentsToMemory */ - virtual void _copyContentsToMemory(Viewport* vp, const Box& src, const PixelBox& dst, - RenderWindow::FrameBuffer buffer) = 0; - - /** Returns the main context */ - GLContext* _getMainContext() { return mMainContext; } - - /** Returns the current context */ - GLContext* _getCurrentContext() { return mCurrentContext; } - - /** - * Check if GL Version is supported - */ - bool hasMinGLVersion(int major, int minor) const; - - /** - * Check if an extension is available - */ - bool checkExtension(const String& ext) const; - - /** Unregister a render target->context mapping. If the context of target - is the current context, change the context to the main context so it - can be destroyed safely. - - @note This is automatically called by the destructor of - GLContext. - */ - virtual void _unregisterContext(GLContext *context) = 0; - - virtual void bindVertexElementToGpu(const VertexElement& elem, - const HardwareVertexBufferSharedPtr& vertexBuffer, - const size_t vertexStart) = 0; - - Real getMinimumDepthInputValue(void) override { return -1.0f; } // Range [-1.0f, 1.0f] - Real getMaximumDepthInputValue(void) override { return 1.0f; } // Range [-1.0f, 1.0f] - - void _convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest, bool) override; - - /// Mimics D3D9RenderSystem::_getDepthStencilFormatFor, if no FBO RTT manager, outputs GL_NONE - virtual void _getDepthStencilFormatFor(PixelFormat internalColourFormat, - uint32* depthFormat, - uint32* stencilFormat); - - /** Create VAO on current context */ - virtual uint32 _createVao() { return 0; } - /** Bind VAO, context should be equal to current context, as VAOs are not shared */ - virtual void _bindVao(GLContext* context, uint32 vao) {} - /** Destroy VAO immediately or defer if it was created on other context */ - virtual void _destroyVao(GLContext* context, uint32 vao) {} - /** Destroy FBO immediately or defer if it was created on other context */ - virtual void _destroyFbo(GLContext* context, uint32 fbo) {} - /** Complete destruction of VAOs and FBOs deferred while creator context was not current */ - void _completeDeferredVaoFboDestruction(); - - void registerThread() override; - void unregisterThread() override; - void preExtraThreadsStarted() override; - void postExtraThreadsStarted() override; - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - virtual void resetRenderer(RenderWindow* pRenderWnd) = 0; - virtual void notifyOnContextLost() = 0; -#endif - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/OgreGLRenderTarget.h b/RenderSystems/GLSupport/include/OgreGLRenderTarget.h deleted file mode 100644 index 92d4044f0ad..00000000000 --- a/RenderSystems/GLSupport/include/OgreGLRenderTarget.h +++ /dev/null @@ -1,27 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. - -#ifndef RENDERSYSTEMS_GLSUPPORT_INCLUDE_OGREGLRENDERTARGET_H_ -#define RENDERSYSTEMS_GLSUPPORT_INCLUDE_OGREGLRENDERTARGET_H_ - -#include "OgreGLSupportPrerequisites.h" - -namespace Ogre -{ -class GLContext; -class GLFrameBufferObjectCommon; - -class _OgrePrivate GLRenderTarget -{ -public: - virtual ~GLRenderTarget() {} - - /** Get the GL context that needs to be active to render to this target - */ - virtual GLContext* getContext() const = 0; - virtual GLFrameBufferObjectCommon* getFBO() { return NULL; } -}; -} // namespace Ogre - -#endif /* RENDERSYSTEMS_GLSUPPORT_INCLUDE_OGREGLRENDERTARGET_H_ */ diff --git a/RenderSystems/GLSupport/include/OgreGLRenderTexture.h b/RenderSystems/GLSupport/include/OgreGLRenderTexture.h deleted file mode 100644 index 42e3bed7c37..00000000000 --- a/RenderSystems/GLSupport/include/OgreGLRenderTexture.h +++ /dev/null @@ -1,242 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#ifndef __GLRENDERTEXTURE_H__ -#define __GLRENDERTEXTURE_H__ - -#include "OgreGLSupportPrerequisites.h" -#include "OgreRenderTexture.h" -#include "OgreSingleton.h" -#include "OgreGLRenderTarget.h" - -namespace Ogre { - class GLHardwarePixelBufferCommon; - - /** GL surface descriptor. Points to a 2D surface that can be rendered to. - */ - struct _OgrePrivate GLSurfaceDesc - { - public: - GLHardwarePixelBufferCommon *buffer; - uint32 zoffset; - uint numSamples; - - GLSurfaceDesc() : buffer(0), zoffset(0), numSamples(0) {} - }; - - /// Frame Buffer Object abstraction - class _OgreGLExport GLFrameBufferObjectCommon - { - public: - GLFrameBufferObjectCommon(int32 fsaa); - virtual ~GLFrameBufferObjectCommon() {} - - /** Bind FrameBufferObject. Attempt to bind on incompatible GL context will cause FBO destruction and optional recreation. - */ - virtual bool bind(bool recreateIfNeeded) = 0; - - /** Bind a surface to a certain attachment point. - attachment: 0..OGRE_MAX_MULTIPLE_RENDER_TARGETS-1 - */ - void bindSurface(size_t attachment, const GLSurfaceDesc &target); - /** Unbind attachment - */ - void unbindSurface(size_t attachment); - - /// Accessors - int32 getFSAA() const { return mNumSamples; } - uint32 getWidth() const; - uint32 getHeight() const; - PixelFormat getFormat() const; - - GLContext* getContext() const { return mContext; } - /// Get the GL id for the FBO - uint32 getGLFBOID() const { return mFB; } - /// Get the GL id for the multisample FBO - uint32 getGLMultisampleFBOID() const { return mMultisampleFB; } - - const GLSurfaceDesc &getSurface(size_t attachment) const { return mColour[attachment]; } - - void notifyContextDestroyed(GLContext* context) { if(mContext == context) { mContext = 0; mFB = 0; mMultisampleFB = 0; } } - protected: - GLSurfaceDesc mDepth; - GLSurfaceDesc mStencil; - // Arbitrary number of texture surfaces - GLSurfaceDesc mColour[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; - /// Context that was used to create FBO. It could already be destroyed, so do not dereference this field blindly - GLContext* mContext; - uint32 mFB; - uint32 mMultisampleFB; - int32 mNumSamples; - - /** Initialise object (find suitable depth and stencil format). - Must be called every time the bindings change. - It fails with an exception (ERR_INVALIDPARAMS) if: - - Attachment point 0 has no binding - - Not all bound surfaces have the same size - - Not all bound surfaces have the same internal format - */ - virtual void initialise() = 0; - }; - - /** Base class for GL Render Textures - */ - class _OgreGLExport GLRenderTexture : public RenderTexture, public GLRenderTarget - { - public: - GLRenderTexture(const String &name, const GLSurfaceDesc &target, bool writeGamma, uint fsaa); - bool requiresTextureFlipping() const override { return true; } - - static const String CustomAttributeString_FBO; - static const String CustomAttributeString_TARGET; - static const String CustomAttributeString_GLCONTEXT; - }; - - /** Manager/factory for RenderTextures. - */ - class _OgreGLExport GLRTTManager : public Singleton - { - public: - GLRTTManager(); - virtual ~GLRTTManager(); - - /** Create a texture rendertarget object - */ - virtual RenderTexture *createRenderTexture(const String &name, const GLSurfaceDesc &target, bool writeGamma, uint fsaa) = 0; - - /** Release a render buffer. Ignore silently if surface.buffer is 0. - */ - void releaseRenderBuffer(const GLSurfaceDesc &surface); - - /** Check if a certain format is usable as FBO rendertarget format - */ - bool checkFormat(PixelFormat format) { return mProps[format].valid; } - - /** Bind a certain render target. - @note only needed for FBO RTTs - */ - virtual void bind(RenderTarget *target) {} - - /** Unbind a certain render target. This is called before binding another RenderTarget, and - before the context is switched. It can be used to do a copy, or just be a noop if direct - binding is used. - @note only needed for Copying or PBuffer RTTs - */ - virtual void unbind(RenderTarget *target) {} - - virtual void getBestDepthStencil(PixelFormat internalFormat, uint32 *depthFormat, uint32 *stencilFormat) - { - *depthFormat = 0; - *stencilFormat = 0; - } - - /** Get the closest supported alternative format. If format is supported, returns format. - */ - PixelFormat getSupportedAlternative(PixelFormat format); - - /// @copydoc Singleton::getSingleton() - static GLRTTManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static GLRTTManager* getSingletonPtr(void); - protected: - /** Frame Buffer Object properties for a certain texture format. - */ - struct FormatProperties - { - bool valid; // This format can be used as RTT (FBO) - - /** Allowed modes/properties for this pixel format - */ - struct Mode - { - uchar depth; // Depth format (0=no depth) - uchar stencil; // Stencil format (0=no stencil) - }; - - std::vector modes; - }; - /** Properties for all internal formats defined by OGRE - */ - FormatProperties mProps[PF_COUNT]; - - /** Stencil and depth renderbuffers of the same format are re-used between surfaces of the - same size and format. This can save a lot of memory when a large amount of rendertargets - are used. - */ - struct RBFormat - { - RBFormat(uint inFormat, size_t inWidth, size_t inHeight, uint fsaa) - : format(inFormat), width(inWidth), height(inHeight), samples(fsaa) - { - } - RBFormat() {} - uint format; - size_t width; - size_t height; - uint samples; - // Overloaded comparison operator for usage in map - bool operator < (const RBFormat &other) const - { - if(format < other.format) - { - return true; - } - else if(format == other.format) - { - if(width < other.width) - { - return true; - } - else if(width == other.width) - { - if(height < other.height) - return true; - else if (height == other.height) - { - if (samples < other.samples) - return true; - } - } - } - return false; - } - }; - struct RBRef - { - RBRef() {} - RBRef(GLHardwarePixelBufferCommon* inBuffer) : buffer(inBuffer), refcount(1) {} - GLHardwarePixelBufferCommon* buffer; - size_t refcount; - }; - typedef std::map RenderBufferMap; - RenderBufferMap mRenderBufferMap; - }; - -} - -#endif diff --git a/RenderSystems/GLSupport/include/OgreGLRenderToVertexBufferCommon.h b/RenderSystems/GLSupport/include/OgreGLRenderToVertexBufferCommon.h deleted file mode 100644 index 49c8d743f85..00000000000 --- a/RenderSystems/GLSupport/include/OgreGLRenderToVertexBufferCommon.h +++ /dev/null @@ -1,23 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#ifndef RENDERSYSTEMS_GLSUPPORT_OGREGLRENDERTOVERTEXBUFFERCOMMON_H_ -#define RENDERSYSTEMS_GLSUPPORT_OGREGLRENDERTOVERTEXBUFFERCOMMON_H_ - -#include "OgreRenderToVertexBuffer.h" - -namespace Ogre { - -class GLRenderToVertexBufferCommon : public RenderToVertexBuffer -{ -protected: - void reallocateBuffer(uint8 index); - static String getSemanticVaryingName(VertexElementSemantic semantic, unsigned short index); - static uint32 getVertexCountPerPrimitive(RenderOperation::OperationType operationType); -}; - -} /* namespace Ogre */ - -#endif /* RENDERSYSTEMS_GLSUPPORT_OGREGLRENDERTOVERTEXBUFFERCOMMON_H_ */ diff --git a/RenderSystems/GLSupport/include/OgreGLStateCacheManagerCommon.h b/RenderSystems/GLSupport/include/OgreGLStateCacheManagerCommon.h deleted file mode 100644 index 06f6c482030..00000000000 --- a/RenderSystems/GLSupport/include/OgreGLStateCacheManagerCommon.h +++ /dev/null @@ -1,119 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLStateCacheManagerCommon_H__ -#define __GLStateCacheManagerCommon_H__ - -#include "OgrePrerequisites.h" -#include "OgreGLSupportPrerequisites.h" -#include "OgreCommon.h" - -namespace Ogre -{ - typedef GeneralAllocatedObject StateCacheAlloc; - - /** An in memory cache of the OpenGL state. - - State changes can be particularly expensive time wise. This is because - a change requires OpenGL to re-evaluate and update the state machine. - Because of the general purpose nature of OGRE we often set the state for - a specific texture, material, buffer, etc. But this may be the same as the - current status of the state machine and is therefore redundant and causes - unnecessary work to be performed by OpenGL. - - Instead we are caching the state so that we can check whether it actually - does need to be updated. This leads to improved performance all around and - can be somewhat dramatic in some cases. - - @warning caching does not work with multiple windows, sharing the same context. - They will erroneously get different state caches. - */ - class _OgreGLExport GLStateCacheManagerCommon : public StateCacheAlloc - { - protected: - typedef std::unordered_map BindBufferMap; - typedef std::unordered_map TexParameteriMap; - typedef std::unordered_map TexUnitsMap; - - /* These variables are used for caching OpenGL state. - They are cached because state changes can be quite expensive, - which is especially important on mobile or embedded systems. - */ - - /// Array of each OpenGL feature that is enabled i.e. blending, depth test, etc. - std::vector mEnableVector; - /// Stores the current clear colour - float mClearColour[4]; - /// Stores the current depth clearing colour - float mClearDepth; - /// Stores the current colour write mask - uchar mColourMask[4]; - /// Stores the current depth write mask - uchar mDepthMask; - /// Stores the current stencil mask - uint32 mStencilMask; - /// Viewport origin and size - Rect mViewport; - /// A map of different buffer types and the currently bound buffer for each type - BindBufferMap mActiveBufferMap; - /// Stores the current face culling setting - uint32 mCullFace; - /// Stores the current depth test function - uint32 mDepthFunc; - /// Stores the current blend equation - uint32 mBlendEquationRGB; - uint32 mBlendEquationAlpha; - uint32 mBlendFuncSource; - uint32 mBlendFuncDest; - uint32 mBlendFuncSourceAlpha; - uint32 mBlendFuncDestAlpha; - /// Stores the currently active texture unit - size_t mActiveTextureUnit; - /// A map of texture parameters for each texture unit - TexUnitsMap mTexUnitsMap; - public: - virtual ~GLStateCacheManagerCommon() {} - - /** Gets the current colour mask setting. - @return An array containing the mask in RGBA order. - */ - uchar* getColourMask() { return mColourMask; } - - /** Gets the current depth mask setting. - @return The current depth mask. - */ - uchar getDepthMask() const { return mDepthMask; } - - /** Gets the current stencil mask. - @return The stencil mask. - */ - uint32 getStencilMask(void) const { return mStencilMask; } - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/OgreGLTextureCommon.h b/RenderSystems/GLSupport/include/OgreGLTextureCommon.h deleted file mode 100644 index e16ee5ce76a..00000000000 --- a/RenderSystems/GLSupport/include/OgreGLTextureCommon.h +++ /dev/null @@ -1,58 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef RENDERSYSTEMS_GLSUPPORT_INCLUDE_OGREGLTEXTURECOMMON_H_ -#define RENDERSYSTEMS_GLSUPPORT_INCLUDE_OGREGLTEXTURECOMMON_H_ - -#include "OgreGLSupportPrerequisites.h" -#include "OgreTexture.h" -#include "OgreHardwarePixelBuffer.h" - -namespace Ogre -{ - -class _OgreGLExport GLTextureCommon : public Texture -{ -public: - GLTextureCommon(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - : Texture(creator, name, handle, group, isManual, loader), mTextureID(0) - { - } - - uint getGLID() const { return mTextureID; } - - void getCustomAttribute(const String& name, void* pData) override; - -protected: - uint mTextureID; -}; - -} /* namespace Ogre */ - -#endif /* RENDERSYSTEMS_GLSUPPORT_INCLUDE_OGREGLTEXTURECOMMON_H_ */ diff --git a/RenderSystems/GLSupport/include/OgreGLUniformCache.h b/RenderSystems/GLSupport/include/OgreGLUniformCache.h deleted file mode 100644 index 307ef149ff8..00000000000 --- a/RenderSystems/GLSupport/include/OgreGLUniformCache.h +++ /dev/null @@ -1,60 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLUniformCache_H__ -#define __GLUniformCache_H__ - -#include "OgrePrerequisites.h" -#include "OgreGLSupportPrerequisites.h" - -typedef Ogre::GeneralAllocatedObject UniformCacheAlloc; - -namespace Ogre -{ - /** An in memory cache of the OpenGL uniforms. */ - class _OgreGLExport GLUniformCache : public UniformCacheAlloc - { - protected: - typedef std::unordered_map UniformMap; - - /// A map of uniform names and a hash of their values - UniformMap mUniformValueMap; - - public: - /** Clears all cached values - */ - void clearCache(); - - /** Update a uniform - @return A boolean value indicating whether this uniform needs to be updated in the GL. - */ - bool updateUniform(int location, const void *value, int length); - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/OgreGLUtil.h b/RenderSystems/GLSupport/include/OgreGLUtil.h deleted file mode 100644 index 19932feae7e..00000000000 --- a/RenderSystems/GLSupport/include/OgreGLUtil.h +++ /dev/null @@ -1,38 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef INCL_OGRE_GLUTIL_H -#define INCL_OGRE_GLUTIL_H - -#include "OgreGLNativeSupport.h" - -namespace Ogre { -_OgreGLExport GLNativeSupport* getGLSupport(int profile = GLNativeSupport::CONTEXT_CORE); -} - -#endif // INCL_OGRE_GLUTIL_H diff --git a/RenderSystems/GLSupport/include/OgreGLVertexArrayObject.h b/RenderSystems/GLSupport/include/OgreGLVertexArrayObject.h deleted file mode 100644 index c2f0ff9c50f..00000000000 --- a/RenderSystems/GLSupport/include/OgreGLVertexArrayObject.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#ifndef __GLVERTEXARRAYOBJECT_H__ -#define __GLVERTEXARRAYOBJECT_H__ - -#include "OgreHardwareVertexBuffer.h" - -namespace Ogre { - class GLContext; - class GLSLProgramCommon; - class GLRenderSystemCommon; - - /** Specialisation of VertexDeclaration for OpenGL Vertex Array Object usage */ - class GLVertexArrayObject : public VertexDeclaration - { - protected: - /// Context that was used to create VAO. It could already be destroyed, so do not dereference this field blindly - GLContext* mCreatorContext; - /// VAOs are not shared between contexts, nor even could be destroyed using the wrong context. - uint32 mVAO; - bool mNeedsUpdate; - - std::vector > mAttribsBound; - std::vector mInstanceAttribsBound; - size_t mVertexStart; - - void notifyChanged() override { mNeedsUpdate = true; } - public: - GLVertexArrayObject(); - ~GLVertexArrayObject(); - void notifyContextDestroyed(GLContext* context) { if(mCreatorContext == context) { mCreatorContext = 0; mVAO = 0; } } - void bind(GLRenderSystemCommon* rs); - bool needsUpdate(VertexBufferBinding* vertexBufferBinding, size_t vertexStart); - void bindToGpu(GLRenderSystemCommon* rs, VertexBufferBinding* vertexBufferBinding, size_t vertexStart); - }; - -} - -#endif diff --git a/RenderSystems/GLSupport/include/OgreGLWindow.h b/RenderSystems/GLSupport/include/OgreGLWindow.h deleted file mode 100644 index 9c4fdb74395..00000000000 --- a/RenderSystems/GLSupport/include/OgreGLWindow.h +++ /dev/null @@ -1,65 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __GLWindow_H__ -#define __GLWindow_H__ - -#include "OgreRenderWindow.h" -#include "OgreGLRenderTarget.h" - -namespace Ogre -{ - class _OgrePrivate GLWindow : public RenderWindow, public GLRenderTarget - { - public: - GLWindow(); - - bool isVisible(void) const override { return mVisible; } - void setVisible(bool visible) override { mVisible = visible; } - bool isHidden(void) const override { return mHidden; } - - bool isVSyncEnabled() const override { return mVSync; } - void setVSyncInterval(unsigned int interval) override; - - void copyContentsToMemory(const Box& src, const PixelBox &dst, FrameBuffer buffer) override; - bool requiresTextureFlipping() const override { return false; } - GLContext* getContext() const override { return mContext; } - - protected: - bool mVisible; - bool mHidden; - bool mIsTopLevel; - bool mIsExternal; - bool mIsExternalGLControl; - bool mVSync; - - GLContext* mContext; - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/win32/GL/wglext.h b/RenderSystems/GLSupport/include/win32/GL/wglext.h deleted file mode 100644 index 335a95384e1..00000000000 --- a/RenderSystems/GLSupport/include/win32/GL/wglext.h +++ /dev/null @@ -1,943 +0,0 @@ -#ifndef __wglext_h_ -#define __wglext_h_ - -#ifdef __cplusplus -extern "C" { -#endif - -/* -** Copyright (c) 2007-2013 The Khronos Group Inc. -** -** Permission is hereby granted, free of charge, to any person obtaining a -** copy of this software and/or associated documentation files (the -** "Materials"), to deal in the Materials without restriction, including -** without limitation the rights to use, copy, modify, merge, publish, -** distribute, sublicense, and/or sell copies of the Materials, and to -** permit persons to whom the Materials are furnished to do so, subject to -** the following conditions: -** -** The above copyright notice and this permission notice shall be included -** in all copies or substantial portions of the Materials. -** -** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. -*/ - -/* Function declaration macros - to move into glplatform.h */ - -#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) -#define WIN32_LEAN_AND_MEAN 1 -#include -#endif - -#ifndef APIENTRY -#define APIENTRY -#endif -#ifndef APIENTRYP -#define APIENTRYP APIENTRY * -#endif -#ifndef GLAPI -#define GLAPI extern -#endif - -/*************************************************************/ - -/* Header file version number */ -/* wglext.h last updated 2012/01/04 */ -/* Current version at http://www.opengl.org/registry/ */ -#define WGL_WGLEXT_VERSION 24 - -#ifndef WGL_ARB_buffer_region -#define WGL_FRONT_COLOR_BUFFER_BIT_ARB 0x00000001 -#define WGL_BACK_COLOR_BUFFER_BIT_ARB 0x00000002 -#define WGL_DEPTH_BUFFER_BIT_ARB 0x00000004 -#define WGL_STENCIL_BUFFER_BIT_ARB 0x00000008 -#endif - -#ifndef WGL_ARB_multisample -#define WGL_SAMPLE_BUFFERS_ARB 0x2041 -#define WGL_SAMPLES_ARB 0x2042 -#endif - -#ifndef WGL_ARB_extensions_string -#endif - -#ifndef WGL_ARB_pixel_format -#define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000 -#define WGL_DRAW_TO_WINDOW_ARB 0x2001 -#define WGL_DRAW_TO_BITMAP_ARB 0x2002 -#define WGL_ACCELERATION_ARB 0x2003 -#define WGL_NEED_PALETTE_ARB 0x2004 -#define WGL_NEED_SYSTEM_PALETTE_ARB 0x2005 -#define WGL_SWAP_LAYER_BUFFERS_ARB 0x2006 -#define WGL_SWAP_METHOD_ARB 0x2007 -#define WGL_NUMBER_OVERLAYS_ARB 0x2008 -#define WGL_NUMBER_UNDERLAYS_ARB 0x2009 -#define WGL_TRANSPARENT_ARB 0x200A -#define WGL_TRANSPARENT_RED_VALUE_ARB 0x2037 -#define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038 -#define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039 -#define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A -#define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B -#define WGL_SHARE_DEPTH_ARB 0x200C -#define WGL_SHARE_STENCIL_ARB 0x200D -#define WGL_SHARE_ACCUM_ARB 0x200E -#define WGL_SUPPORT_GDI_ARB 0x200F -#define WGL_SUPPORT_OPENGL_ARB 0x2010 -#define WGL_DOUBLE_BUFFER_ARB 0x2011 -#define WGL_STEREO_ARB 0x2012 -#define WGL_PIXEL_TYPE_ARB 0x2013 -#define WGL_COLOR_BITS_ARB 0x2014 -#define WGL_RED_BITS_ARB 0x2015 -#define WGL_RED_SHIFT_ARB 0x2016 -#define WGL_GREEN_BITS_ARB 0x2017 -#define WGL_GREEN_SHIFT_ARB 0x2018 -#define WGL_BLUE_BITS_ARB 0x2019 -#define WGL_BLUE_SHIFT_ARB 0x201A -#define WGL_ALPHA_BITS_ARB 0x201B -#define WGL_ALPHA_SHIFT_ARB 0x201C -#define WGL_ACCUM_BITS_ARB 0x201D -#define WGL_ACCUM_RED_BITS_ARB 0x201E -#define WGL_ACCUM_GREEN_BITS_ARB 0x201F -#define WGL_ACCUM_BLUE_BITS_ARB 0x2020 -#define WGL_ACCUM_ALPHA_BITS_ARB 0x2021 -#define WGL_DEPTH_BITS_ARB 0x2022 -#define WGL_STENCIL_BITS_ARB 0x2023 -#define WGL_AUX_BUFFERS_ARB 0x2024 -#define WGL_NO_ACCELERATION_ARB 0x2025 -#define WGL_GENERIC_ACCELERATION_ARB 0x2026 -#define WGL_FULL_ACCELERATION_ARB 0x2027 -#define WGL_SWAP_EXCHANGE_ARB 0x2028 -#define WGL_SWAP_COPY_ARB 0x2029 -#define WGL_SWAP_UNDEFINED_ARB 0x202A -#define WGL_TYPE_RGBA_ARB 0x202B -#define WGL_TYPE_COLORINDEX_ARB 0x202C -#endif - -#ifndef WGL_ARB_make_current_read -#define ERROR_INVALID_PIXEL_TYPE_ARB 0x2043 -#define ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB 0x2054 -#endif - -#ifndef WGL_ARB_pbuffer -#define WGL_DRAW_TO_PBUFFER_ARB 0x202D -#define WGL_MAX_PBUFFER_PIXELS_ARB 0x202E -#define WGL_MAX_PBUFFER_WIDTH_ARB 0x202F -#define WGL_MAX_PBUFFER_HEIGHT_ARB 0x2030 -#define WGL_PBUFFER_LARGEST_ARB 0x2033 -#define WGL_PBUFFER_WIDTH_ARB 0x2034 -#define WGL_PBUFFER_HEIGHT_ARB 0x2035 -#define WGL_PBUFFER_LOST_ARB 0x2036 -#endif - -#ifndef WGL_ARB_render_texture -#define WGL_BIND_TO_TEXTURE_RGB_ARB 0x2070 -#define WGL_BIND_TO_TEXTURE_RGBA_ARB 0x2071 -#define WGL_TEXTURE_FORMAT_ARB 0x2072 -#define WGL_TEXTURE_TARGET_ARB 0x2073 -#define WGL_MIPMAP_TEXTURE_ARB 0x2074 -#define WGL_TEXTURE_RGB_ARB 0x2075 -#define WGL_TEXTURE_RGBA_ARB 0x2076 -#define WGL_NO_TEXTURE_ARB 0x2077 -#define WGL_TEXTURE_CUBE_MAP_ARB 0x2078 -#define WGL_TEXTURE_1D_ARB 0x2079 -#define WGL_TEXTURE_2D_ARB 0x207A -#define WGL_MIPMAP_LEVEL_ARB 0x207B -#define WGL_CUBE_MAP_FACE_ARB 0x207C -#define WGL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x207D -#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x207E -#define WGL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x207F -#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x2080 -#define WGL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x2081 -#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x2082 -#define WGL_FRONT_LEFT_ARB 0x2083 -#define WGL_FRONT_RIGHT_ARB 0x2084 -#define WGL_BACK_LEFT_ARB 0x2085 -#define WGL_BACK_RIGHT_ARB 0x2086 -#define WGL_AUX0_ARB 0x2087 -#define WGL_AUX1_ARB 0x2088 -#define WGL_AUX2_ARB 0x2089 -#define WGL_AUX3_ARB 0x208A -#define WGL_AUX4_ARB 0x208B -#define WGL_AUX5_ARB 0x208C -#define WGL_AUX6_ARB 0x208D -#define WGL_AUX7_ARB 0x208E -#define WGL_AUX8_ARB 0x208F -#define WGL_AUX9_ARB 0x2090 -#endif - -#ifndef WGL_ARB_pixel_format_float -#define WGL_TYPE_RGBA_FLOAT_ARB 0x21A0 -#endif - -#ifndef WGL_ARB_framebuffer_sRGB -#define WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20A9 -#endif - -#ifndef WGL_ARB_create_context -#define WGL_CONTEXT_DEBUG_BIT_ARB 0x00000001 -#define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002 -#define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091 -#define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092 -#define WGL_CONTEXT_LAYER_PLANE_ARB 0x2093 -#define WGL_CONTEXT_FLAGS_ARB 0x2094 -#define ERROR_INVALID_VERSION_ARB 0x2095 -#endif - -#ifndef WGL_ARB_create_context_profile -#define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126 -#define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001 -#define WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002 -#define ERROR_INVALID_PROFILE_ARB 0x2096 -#endif - -#ifndef WGL_ARB_create_context_robustness -#define WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB 0x00000004 -#define WGL_LOSE_CONTEXT_ON_RESET_ARB 0x8252 -#define WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB 0x8256 -#define WGL_NO_RESET_NOTIFICATION_ARB 0x8261 -#endif - -#ifndef WGL_EXT_make_current_read -#define ERROR_INVALID_PIXEL_TYPE_EXT 0x2043 -#endif - -#ifndef WGL_EXT_pixel_format -#define WGL_NUMBER_PIXEL_FORMATS_EXT 0x2000 -#define WGL_DRAW_TO_WINDOW_EXT 0x2001 -#define WGL_DRAW_TO_BITMAP_EXT 0x2002 -#define WGL_ACCELERATION_EXT 0x2003 -#define WGL_NEED_PALETTE_EXT 0x2004 -#define WGL_NEED_SYSTEM_PALETTE_EXT 0x2005 -#define WGL_SWAP_LAYER_BUFFERS_EXT 0x2006 -#define WGL_SWAP_METHOD_EXT 0x2007 -#define WGL_NUMBER_OVERLAYS_EXT 0x2008 -#define WGL_NUMBER_UNDERLAYS_EXT 0x2009 -#define WGL_TRANSPARENT_EXT 0x200A -#define WGL_TRANSPARENT_VALUE_EXT 0x200B -#define WGL_SHARE_DEPTH_EXT 0x200C -#define WGL_SHARE_STENCIL_EXT 0x200D -#define WGL_SHARE_ACCUM_EXT 0x200E -#define WGL_SUPPORT_GDI_EXT 0x200F -#define WGL_SUPPORT_OPENGL_EXT 0x2010 -#define WGL_DOUBLE_BUFFER_EXT 0x2011 -#define WGL_STEREO_EXT 0x2012 -#define WGL_PIXEL_TYPE_EXT 0x2013 -#define WGL_COLOR_BITS_EXT 0x2014 -#define WGL_RED_BITS_EXT 0x2015 -#define WGL_RED_SHIFT_EXT 0x2016 -#define WGL_GREEN_BITS_EXT 0x2017 -#define WGL_GREEN_SHIFT_EXT 0x2018 -#define WGL_BLUE_BITS_EXT 0x2019 -#define WGL_BLUE_SHIFT_EXT 0x201A -#define WGL_ALPHA_BITS_EXT 0x201B -#define WGL_ALPHA_SHIFT_EXT 0x201C -#define WGL_ACCUM_BITS_EXT 0x201D -#define WGL_ACCUM_RED_BITS_EXT 0x201E -#define WGL_ACCUM_GREEN_BITS_EXT 0x201F -#define WGL_ACCUM_BLUE_BITS_EXT 0x2020 -#define WGL_ACCUM_ALPHA_BITS_EXT 0x2021 -#define WGL_DEPTH_BITS_EXT 0x2022 -#define WGL_STENCIL_BITS_EXT 0x2023 -#define WGL_AUX_BUFFERS_EXT 0x2024 -#define WGL_NO_ACCELERATION_EXT 0x2025 -#define WGL_GENERIC_ACCELERATION_EXT 0x2026 -#define WGL_FULL_ACCELERATION_EXT 0x2027 -#define WGL_SWAP_EXCHANGE_EXT 0x2028 -#define WGL_SWAP_COPY_EXT 0x2029 -#define WGL_SWAP_UNDEFINED_EXT 0x202A -#define WGL_TYPE_RGBA_EXT 0x202B -#define WGL_TYPE_COLORINDEX_EXT 0x202C -#endif - -#ifndef WGL_EXT_pbuffer -#define WGL_DRAW_TO_PBUFFER_EXT 0x202D -#define WGL_MAX_PBUFFER_PIXELS_EXT 0x202E -#define WGL_MAX_PBUFFER_WIDTH_EXT 0x202F -#define WGL_MAX_PBUFFER_HEIGHT_EXT 0x2030 -#define WGL_OPTIMAL_PBUFFER_WIDTH_EXT 0x2031 -#define WGL_OPTIMAL_PBUFFER_HEIGHT_EXT 0x2032 -#define WGL_PBUFFER_LARGEST_EXT 0x2033 -#define WGL_PBUFFER_WIDTH_EXT 0x2034 -#define WGL_PBUFFER_HEIGHT_EXT 0x2035 -#endif - -#ifndef WGL_EXT_depth_float -#define WGL_DEPTH_FLOAT_EXT 0x2040 -#endif - -#ifndef WGL_3DFX_multisample -#define WGL_SAMPLE_BUFFERS_3DFX 0x2060 -#define WGL_SAMPLES_3DFX 0x2061 -#endif - -#ifndef WGL_EXT_multisample -#define WGL_SAMPLE_BUFFERS_EXT 0x2041 -#define WGL_SAMPLES_EXT 0x2042 -#endif - -#ifndef WGL_I3D_digital_video_control -#define WGL_DIGITAL_VIDEO_CURSOR_ALPHA_FRAMEBUFFER_I3D 0x2050 -#define WGL_DIGITAL_VIDEO_CURSOR_ALPHA_VALUE_I3D 0x2051 -#define WGL_DIGITAL_VIDEO_CURSOR_INCLUDED_I3D 0x2052 -#define WGL_DIGITAL_VIDEO_GAMMA_CORRECTED_I3D 0x2053 -#endif - -#ifndef WGL_I3D_gamma -#define WGL_GAMMA_TABLE_SIZE_I3D 0x204E -#define WGL_GAMMA_EXCLUDE_DESKTOP_I3D 0x204F -#endif - -#ifndef WGL_I3D_genlock -#define WGL_GENLOCK_SOURCE_MULTIVIEW_I3D 0x2044 -#define WGL_GENLOCK_SOURCE_EXTENAL_SYNC_I3D 0x2045 -#define WGL_GENLOCK_SOURCE_EXTENAL_FIELD_I3D 0x2046 -#define WGL_GENLOCK_SOURCE_EXTENAL_TTL_I3D 0x2047 -#define WGL_GENLOCK_SOURCE_DIGITAL_SYNC_I3D 0x2048 -#define WGL_GENLOCK_SOURCE_DIGITAL_FIELD_I3D 0x2049 -#define WGL_GENLOCK_SOURCE_EDGE_FALLING_I3D 0x204A -#define WGL_GENLOCK_SOURCE_EDGE_RISING_I3D 0x204B -#define WGL_GENLOCK_SOURCE_EDGE_BOTH_I3D 0x204C -#endif - -#ifndef WGL_I3D_image_buffer -#define WGL_IMAGE_BUFFER_MIN_ACCESS_I3D 0x00000001 -#define WGL_IMAGE_BUFFER_LOCK_I3D 0x00000002 -#endif - -#ifndef WGL_I3D_swap_frame_lock -#endif - -#ifndef WGL_NV_render_depth_texture -#define WGL_BIND_TO_TEXTURE_DEPTH_NV 0x20A3 -#define WGL_BIND_TO_TEXTURE_RECTANGLE_DEPTH_NV 0x20A4 -#define WGL_DEPTH_TEXTURE_FORMAT_NV 0x20A5 -#define WGL_TEXTURE_DEPTH_COMPONENT_NV 0x20A6 -#define WGL_DEPTH_COMPONENT_NV 0x20A7 -#endif - -#ifndef WGL_NV_render_texture_rectangle -#define WGL_BIND_TO_TEXTURE_RECTANGLE_RGB_NV 0x20A0 -#define WGL_BIND_TO_TEXTURE_RECTANGLE_RGBA_NV 0x20A1 -#define WGL_TEXTURE_RECTANGLE_NV 0x20A2 -#endif - -#ifndef WGL_ATI_pixel_format_float -#define WGL_TYPE_RGBA_FLOAT_ATI 0x21A0 -#endif - -#ifndef WGL_NV_float_buffer -#define WGL_FLOAT_COMPONENTS_NV 0x20B0 -#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_R_NV 0x20B1 -#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RG_NV 0x20B2 -#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGB_NV 0x20B3 -#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGBA_NV 0x20B4 -#define WGL_TEXTURE_FLOAT_R_NV 0x20B5 -#define WGL_TEXTURE_FLOAT_RG_NV 0x20B6 -#define WGL_TEXTURE_FLOAT_RGB_NV 0x20B7 -#define WGL_TEXTURE_FLOAT_RGBA_NV 0x20B8 -#endif - -#ifndef WGL_3DL_stereo_control -#define WGL_STEREO_EMITTER_ENABLE_3DL 0x2055 -#define WGL_STEREO_EMITTER_DISABLE_3DL 0x2056 -#define WGL_STEREO_POLARITY_NORMAL_3DL 0x2057 -#define WGL_STEREO_POLARITY_INVERT_3DL 0x2058 -#endif - -#ifndef WGL_EXT_pixel_format_packed_float -#define WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT 0x20A8 -#endif - -#ifndef WGL_EXT_framebuffer_sRGB -#define WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT 0x20A9 -#endif - -#ifndef WGL_NV_present_video -#define WGL_NUM_VIDEO_SLOTS_NV 0x20F0 -#endif - -#ifndef WGL_NV_video_out -#define WGL_BIND_TO_VIDEO_RGB_NV 0x20C0 -#define WGL_BIND_TO_VIDEO_RGBA_NV 0x20C1 -#define WGL_BIND_TO_VIDEO_RGB_AND_DEPTH_NV 0x20C2 -#define WGL_VIDEO_OUT_COLOR_NV 0x20C3 -#define WGL_VIDEO_OUT_ALPHA_NV 0x20C4 -#define WGL_VIDEO_OUT_DEPTH_NV 0x20C5 -#define WGL_VIDEO_OUT_COLOR_AND_ALPHA_NV 0x20C6 -#define WGL_VIDEO_OUT_COLOR_AND_DEPTH_NV 0x20C7 -#define WGL_VIDEO_OUT_FRAME 0x20C8 -#define WGL_VIDEO_OUT_FIELD_1 0x20C9 -#define WGL_VIDEO_OUT_FIELD_2 0x20CA -#define WGL_VIDEO_OUT_STACKED_FIELDS_1_2 0x20CB -#define WGL_VIDEO_OUT_STACKED_FIELDS_2_1 0x20CC -#endif - -#ifndef WGL_NV_swap_group -#endif - -#ifndef WGL_NV_gpu_affinity -#define WGL_ERROR_INCOMPATIBLE_AFFINITY_MASKS_NV 0x20D0 -#define WGL_ERROR_MISSING_AFFINITY_MASK_NV 0x20D1 -#endif - -#ifndef WGL_AMD_gpu_association -#define WGL_GPU_VENDOR_AMD 0x1F00 -#define WGL_GPU_RENDERER_STRING_AMD 0x1F01 -#define WGL_GPU_OPENGL_VERSION_STRING_AMD 0x1F02 -#define WGL_GPU_FASTEST_TARGET_GPUS_AMD 0x21A2 -#define WGL_GPU_RAM_AMD 0x21A3 -#define WGL_GPU_CLOCK_AMD 0x21A4 -#define WGL_GPU_NUM_PIPES_AMD 0x21A5 -#define WGL_GPU_NUM_SIMD_AMD 0x21A6 -#define WGL_GPU_NUM_RB_AMD 0x21A7 -#define WGL_GPU_NUM_SPI_AMD 0x21A8 -#endif - -#ifndef WGL_NV_video_capture -#define WGL_UNIQUE_ID_NV 0x20CE -#define WGL_NUM_VIDEO_CAPTURE_SLOTS_NV 0x20CF -#endif - -#ifndef WGL_NV_copy_image -#endif - -#ifndef WGL_NV_multisample_coverage -#define WGL_COVERAGE_SAMPLES_NV 0x2042 -#define WGL_COLOR_SAMPLES_NV 0x20B9 -#endif - -#ifndef WGL_EXT_create_context_es2_profile -#define WGL_CONTEXT_ES2_PROFILE_BIT_EXT 0x00000004 -#endif - -#ifndef WGL_NV_DX_interop -#define WGL_ACCESS_READ_ONLY_NV 0x00000000 -#define WGL_ACCESS_READ_WRITE_NV 0x00000001 -#define WGL_ACCESS_WRITE_DISCARD_NV 0x00000002 -#endif - -#ifndef WGL_NV_DX_interop2 -#endif - -#ifndef WGL_EXT_swap_control_tear -#endif - - -/*************************************************************/ - -#ifndef WGL_ARB_pbuffer -DECLARE_HANDLE(HPBUFFERARB); -#endif -#ifndef WGL_EXT_pbuffer -DECLARE_HANDLE(HPBUFFEREXT); -#endif -#ifndef WGL_NV_present_video -DECLARE_HANDLE(HVIDEOOUTPUTDEVICENV); -#endif -#ifndef WGL_NV_video_output -DECLARE_HANDLE(HPVIDEODEV); -#endif -#ifndef WGL_NV_gpu_affinity -DECLARE_HANDLE(HPGPUNV); -DECLARE_HANDLE(HGPUNV); - -typedef struct _GPU_DEVICE { - DWORD cb; - CHAR DeviceName[32]; - CHAR DeviceString[128]; - DWORD Flags; - RECT rcVirtualScreen; -} GPU_DEVICE, *PGPU_DEVICE; -#endif -#ifndef WGL_NV_video_capture -DECLARE_HANDLE(HVIDEOINPUTDEVICENV); -#endif - -#ifndef WGL_ARB_buffer_region -#define WGL_ARB_buffer_region 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern HANDLE WINAPI wglCreateBufferRegionARB (HDC hDC, int iLayerPlane, UINT uType); -extern VOID WINAPI wglDeleteBufferRegionARB (HANDLE hRegion); -extern BOOL WINAPI wglSaveBufferRegionARB (HANDLE hRegion, int x, int y, int width, int height); -extern BOOL WINAPI wglRestoreBufferRegionARB (HANDLE hRegion, int x, int y, int width, int height, int xSrc, int ySrc); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef HANDLE (WINAPI * PFNWGLCREATEBUFFERREGIONARBPROC) (HDC hDC, int iLayerPlane, UINT uType); -typedef VOID (WINAPI * PFNWGLDELETEBUFFERREGIONARBPROC) (HANDLE hRegion); -typedef BOOL (WINAPI * PFNWGLSAVEBUFFERREGIONARBPROC) (HANDLE hRegion, int x, int y, int width, int height); -typedef BOOL (WINAPI * PFNWGLRESTOREBUFFERREGIONARBPROC) (HANDLE hRegion, int x, int y, int width, int height, int xSrc, int ySrc); -#endif - -#ifndef WGL_ARB_multisample -#define WGL_ARB_multisample 1 -#endif - -#ifndef WGL_ARB_extensions_string -#define WGL_ARB_extensions_string 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern const char * WINAPI wglGetExtensionsStringARB (HDC hdc); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef const char * (WINAPI * PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc); -#endif - -#ifndef WGL_ARB_pixel_format -#define WGL_ARB_pixel_format 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern BOOL WINAPI wglGetPixelFormatAttribivARB (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues); -extern BOOL WINAPI wglGetPixelFormatAttribfvARB (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues); -extern BOOL WINAPI wglChoosePixelFormatARB (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues); -typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBFVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues); -typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats); -#endif - -#ifndef WGL_ARB_make_current_read -#define WGL_ARB_make_current_read 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern BOOL WINAPI wglMakeContextCurrentARB (HDC hDrawDC, HDC hReadDC, HGLRC hglrc); -extern HDC WINAPI wglGetCurrentReadDCARB (void); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef BOOL (WINAPI * PFNWGLMAKECONTEXTCURRENTARBPROC) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc); -typedef HDC (WINAPI * PFNWGLGETCURRENTREADDCARBPROC) (void); -#endif - -#ifndef WGL_ARB_pbuffer -#define WGL_ARB_pbuffer 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern HPBUFFERARB WINAPI wglCreatePbufferARB (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList); -extern HDC WINAPI wglGetPbufferDCARB (HPBUFFERARB hPbuffer); -extern int WINAPI wglReleasePbufferDCARB (HPBUFFERARB hPbuffer, HDC hDC); -extern BOOL WINAPI wglDestroyPbufferARB (HPBUFFERARB hPbuffer); -extern BOOL WINAPI wglQueryPbufferARB (HPBUFFERARB hPbuffer, int iAttribute, int *piValue); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef HPBUFFERARB (WINAPI * PFNWGLCREATEPBUFFERARBPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList); -typedef HDC (WINAPI * PFNWGLGETPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer); -typedef int (WINAPI * PFNWGLRELEASEPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer, HDC hDC); -typedef BOOL (WINAPI * PFNWGLDESTROYPBUFFERARBPROC) (HPBUFFERARB hPbuffer); -typedef BOOL (WINAPI * PFNWGLQUERYPBUFFERARBPROC) (HPBUFFERARB hPbuffer, int iAttribute, int *piValue); -#endif - -#ifndef WGL_ARB_render_texture -#define WGL_ARB_render_texture 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern BOOL WINAPI wglBindTexImageARB (HPBUFFERARB hPbuffer, int iBuffer); -extern BOOL WINAPI wglReleaseTexImageARB (HPBUFFERARB hPbuffer, int iBuffer); -extern BOOL WINAPI wglSetPbufferAttribARB (HPBUFFERARB hPbuffer, const int *piAttribList); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef BOOL (WINAPI * PFNWGLBINDTEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer); -typedef BOOL (WINAPI * PFNWGLRELEASETEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer); -typedef BOOL (WINAPI * PFNWGLSETPBUFFERATTRIBARBPROC) (HPBUFFERARB hPbuffer, const int *piAttribList); -#endif - -#ifndef WGL_ARB_pixel_format_float -#define WGL_ARB_pixel_format_float 1 -#endif - -#ifndef WGL_ARB_framebuffer_sRGB -#define WGL_ARB_framebuffer_sRGB 1 -#endif - -#ifndef WGL_ARB_create_context -#define WGL_ARB_create_context 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern HGLRC WINAPI wglCreateContextAttribsARB (HDC hDC, HGLRC hShareContext, const int *attribList); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC) (HDC hDC, HGLRC hShareContext, const int *attribList); -#endif - -#ifndef WGL_ARB_create_context_profile -#define WGL_ARB_create_context_profile 1 -#endif - -#ifndef WGL_ARB_create_context_robustness -#define WGL_ARB_create_context_robustness 1 -#endif - -#ifndef WGL_EXT_display_color_table -#define WGL_EXT_display_color_table 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern GLboolean WINAPI wglCreateDisplayColorTableEXT (GLushort id); -extern GLboolean WINAPI wglLoadDisplayColorTableEXT (const GLushort *table, GLuint length); -extern GLboolean WINAPI wglBindDisplayColorTableEXT (GLushort id); -extern VOID WINAPI wglDestroyDisplayColorTableEXT (GLushort id); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef GLboolean (WINAPI * PFNWGLCREATEDISPLAYCOLORTABLEEXTPROC) (GLushort id); -typedef GLboolean (WINAPI * PFNWGLLOADDISPLAYCOLORTABLEEXTPROC) (const GLushort *table, GLuint length); -typedef GLboolean (WINAPI * PFNWGLBINDDISPLAYCOLORTABLEEXTPROC) (GLushort id); -typedef VOID (WINAPI * PFNWGLDESTROYDISPLAYCOLORTABLEEXTPROC) (GLushort id); -#endif - -#ifndef WGL_EXT_extensions_string -#define WGL_EXT_extensions_string 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern const char * WINAPI wglGetExtensionsStringEXT (void); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef const char * (WINAPI * PFNWGLGETEXTENSIONSSTRINGEXTPROC) (void); -#endif - -#ifndef WGL_EXT_make_current_read -#define WGL_EXT_make_current_read 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern BOOL WINAPI wglMakeContextCurrentEXT (HDC hDrawDC, HDC hReadDC, HGLRC hglrc); -extern HDC WINAPI wglGetCurrentReadDCEXT (void); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef BOOL (WINAPI * PFNWGLMAKECONTEXTCURRENTEXTPROC) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc); -typedef HDC (WINAPI * PFNWGLGETCURRENTREADDCEXTPROC) (void); -#endif - -#ifndef WGL_EXT_pbuffer -#define WGL_EXT_pbuffer 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern HPBUFFEREXT WINAPI wglCreatePbufferEXT (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList); -extern HDC WINAPI wglGetPbufferDCEXT (HPBUFFEREXT hPbuffer); -extern int WINAPI wglReleasePbufferDCEXT (HPBUFFEREXT hPbuffer, HDC hDC); -extern BOOL WINAPI wglDestroyPbufferEXT (HPBUFFEREXT hPbuffer); -extern BOOL WINAPI wglQueryPbufferEXT (HPBUFFEREXT hPbuffer, int iAttribute, int *piValue); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef HPBUFFEREXT (WINAPI * PFNWGLCREATEPBUFFEREXTPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList); -typedef HDC (WINAPI * PFNWGLGETPBUFFERDCEXTPROC) (HPBUFFEREXT hPbuffer); -typedef int (WINAPI * PFNWGLRELEASEPBUFFERDCEXTPROC) (HPBUFFEREXT hPbuffer, HDC hDC); -typedef BOOL (WINAPI * PFNWGLDESTROYPBUFFEREXTPROC) (HPBUFFEREXT hPbuffer); -typedef BOOL (WINAPI * PFNWGLQUERYPBUFFEREXTPROC) (HPBUFFEREXT hPbuffer, int iAttribute, int *piValue); -#endif - -#ifndef WGL_EXT_pixel_format -#define WGL_EXT_pixel_format 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern BOOL WINAPI wglGetPixelFormatAttribivEXT (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, int *piValues); -extern BOOL WINAPI wglGetPixelFormatAttribfvEXT (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, FLOAT *pfValues); -extern BOOL WINAPI wglChoosePixelFormatEXT (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVEXTPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, int *piValues); -typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBFVEXTPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, FLOAT *pfValues); -typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATEXTPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats); -#endif - -#ifndef WGL_EXT_swap_control -#define WGL_EXT_swap_control 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern BOOL WINAPI wglSwapIntervalEXT (int interval); -extern int WINAPI wglGetSwapIntervalEXT (void); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval); -typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void); -#endif - -#ifndef WGL_EXT_depth_float -#define WGL_EXT_depth_float 1 -#endif - -#ifndef WGL_NV_vertex_array_range -#define WGL_NV_vertex_array_range 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern void* WINAPI wglAllocateMemoryNV (GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority); -extern void WINAPI wglFreeMemoryNV (void *pointer); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef void* (WINAPI * PFNWGLALLOCATEMEMORYNVPROC) (GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority); -typedef void (WINAPI * PFNWGLFREEMEMORYNVPROC) (void *pointer); -#endif - -#ifndef WGL_3DFX_multisample -#define WGL_3DFX_multisample 1 -#endif - -#ifndef WGL_EXT_multisample -#define WGL_EXT_multisample 1 -#endif - -#ifndef WGL_OML_sync_control -#define WGL_OML_sync_control 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern BOOL WINAPI wglGetSyncValuesOML (HDC hdc, INT64 *ust, INT64 *msc, INT64 *sbc); -extern BOOL WINAPI wglGetMscRateOML (HDC hdc, INT32 *numerator, INT32 *denominator); -extern INT64 WINAPI wglSwapBuffersMscOML (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder); -extern INT64 WINAPI wglSwapLayerBuffersMscOML (HDC hdc, int fuPlanes, INT64 target_msc, INT64 divisor, INT64 remainder); -extern BOOL WINAPI wglWaitForMscOML (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder, INT64 *ust, INT64 *msc, INT64 *sbc); -extern BOOL WINAPI wglWaitForSbcOML (HDC hdc, INT64 target_sbc, INT64 *ust, INT64 *msc, INT64 *sbc); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef BOOL (WINAPI * PFNWGLGETSYNCVALUESOMLPROC) (HDC hdc, INT64 *ust, INT64 *msc, INT64 *sbc); -typedef BOOL (WINAPI * PFNWGLGETMSCRATEOMLPROC) (HDC hdc, INT32 *numerator, INT32 *denominator); -typedef INT64 (WINAPI * PFNWGLSWAPBUFFERSMSCOMLPROC) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder); -typedef INT64 (WINAPI * PFNWGLSWAPLAYERBUFFERSMSCOMLPROC) (HDC hdc, int fuPlanes, INT64 target_msc, INT64 divisor, INT64 remainder); -typedef BOOL (WINAPI * PFNWGLWAITFORMSCOMLPROC) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder, INT64 *ust, INT64 *msc, INT64 *sbc); -typedef BOOL (WINAPI * PFNWGLWAITFORSBCOMLPROC) (HDC hdc, INT64 target_sbc, INT64 *ust, INT64 *msc, INT64 *sbc); -#endif - -#ifndef WGL_I3D_digital_video_control -#define WGL_I3D_digital_video_control 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern BOOL WINAPI wglGetDigitalVideoParametersI3D (HDC hDC, int iAttribute, int *piValue); -extern BOOL WINAPI wglSetDigitalVideoParametersI3D (HDC hDC, int iAttribute, const int *piValue); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef BOOL (WINAPI * PFNWGLGETDIGITALVIDEOPARAMETERSI3DPROC) (HDC hDC, int iAttribute, int *piValue); -typedef BOOL (WINAPI * PFNWGLSETDIGITALVIDEOPARAMETERSI3DPROC) (HDC hDC, int iAttribute, const int *piValue); -#endif - -#ifndef WGL_I3D_gamma -#define WGL_I3D_gamma 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern BOOL WINAPI wglGetGammaTableParametersI3D (HDC hDC, int iAttribute, int *piValue); -extern BOOL WINAPI wglSetGammaTableParametersI3D (HDC hDC, int iAttribute, const int *piValue); -extern BOOL WINAPI wglGetGammaTableI3D (HDC hDC, int iEntries, USHORT *puRed, USHORT *puGreen, USHORT *puBlue); -extern BOOL WINAPI wglSetGammaTableI3D (HDC hDC, int iEntries, const USHORT *puRed, const USHORT *puGreen, const USHORT *puBlue); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef BOOL (WINAPI * PFNWGLGETGAMMATABLEPARAMETERSI3DPROC) (HDC hDC, int iAttribute, int *piValue); -typedef BOOL (WINAPI * PFNWGLSETGAMMATABLEPARAMETERSI3DPROC) (HDC hDC, int iAttribute, const int *piValue); -typedef BOOL (WINAPI * PFNWGLGETGAMMATABLEI3DPROC) (HDC hDC, int iEntries, USHORT *puRed, USHORT *puGreen, USHORT *puBlue); -typedef BOOL (WINAPI * PFNWGLSETGAMMATABLEI3DPROC) (HDC hDC, int iEntries, const USHORT *puRed, const USHORT *puGreen, const USHORT *puBlue); -#endif - -#ifndef WGL_I3D_genlock -#define WGL_I3D_genlock 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern BOOL WINAPI wglEnableGenlockI3D (HDC hDC); -extern BOOL WINAPI wglDisableGenlockI3D (HDC hDC); -extern BOOL WINAPI wglIsEnabledGenlockI3D (HDC hDC, BOOL *pFlag); -extern BOOL WINAPI wglGenlockSourceI3D (HDC hDC, UINT uSource); -extern BOOL WINAPI wglGetGenlockSourceI3D (HDC hDC, UINT *uSource); -extern BOOL WINAPI wglGenlockSourceEdgeI3D (HDC hDC, UINT uEdge); -extern BOOL WINAPI wglGetGenlockSourceEdgeI3D (HDC hDC, UINT *uEdge); -extern BOOL WINAPI wglGenlockSampleRateI3D (HDC hDC, UINT uRate); -extern BOOL WINAPI wglGetGenlockSampleRateI3D (HDC hDC, UINT *uRate); -extern BOOL WINAPI wglGenlockSourceDelayI3D (HDC hDC, UINT uDelay); -extern BOOL WINAPI wglGetGenlockSourceDelayI3D (HDC hDC, UINT *uDelay); -extern BOOL WINAPI wglQueryGenlockMaxSourceDelayI3D (HDC hDC, UINT *uMaxLineDelay, UINT *uMaxPixelDelay); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef BOOL (WINAPI * PFNWGLENABLEGENLOCKI3DPROC) (HDC hDC); -typedef BOOL (WINAPI * PFNWGLDISABLEGENLOCKI3DPROC) (HDC hDC); -typedef BOOL (WINAPI * PFNWGLISENABLEDGENLOCKI3DPROC) (HDC hDC, BOOL *pFlag); -typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEI3DPROC) (HDC hDC, UINT uSource); -typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEI3DPROC) (HDC hDC, UINT *uSource); -typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEEDGEI3DPROC) (HDC hDC, UINT uEdge); -typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEEDGEI3DPROC) (HDC hDC, UINT *uEdge); -typedef BOOL (WINAPI * PFNWGLGENLOCKSAMPLERATEI3DPROC) (HDC hDC, UINT uRate); -typedef BOOL (WINAPI * PFNWGLGETGENLOCKSAMPLERATEI3DPROC) (HDC hDC, UINT *uRate); -typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEDELAYI3DPROC) (HDC hDC, UINT uDelay); -typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEDELAYI3DPROC) (HDC hDC, UINT *uDelay); -typedef BOOL (WINAPI * PFNWGLQUERYGENLOCKMAXSOURCEDELAYI3DPROC) (HDC hDC, UINT *uMaxLineDelay, UINT *uMaxPixelDelay); -#endif - -#ifndef WGL_I3D_image_buffer -#define WGL_I3D_image_buffer 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern LPVOID WINAPI wglCreateImageBufferI3D (HDC hDC, DWORD dwSize, UINT uFlags); -extern BOOL WINAPI wglDestroyImageBufferI3D (HDC hDC, LPVOID pAddress); -extern BOOL WINAPI wglAssociateImageBufferEventsI3D (HDC hDC, const HANDLE *pEvent, const LPVOID *pAddress, const DWORD *pSize, UINT count); -extern BOOL WINAPI wglReleaseImageBufferEventsI3D (HDC hDC, const LPVOID *pAddress, UINT count); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef LPVOID (WINAPI * PFNWGLCREATEIMAGEBUFFERI3DPROC) (HDC hDC, DWORD dwSize, UINT uFlags); -typedef BOOL (WINAPI * PFNWGLDESTROYIMAGEBUFFERI3DPROC) (HDC hDC, LPVOID pAddress); -typedef BOOL (WINAPI * PFNWGLASSOCIATEIMAGEBUFFEREVENTSI3DPROC) (HDC hDC, const HANDLE *pEvent, const LPVOID *pAddress, const DWORD *pSize, UINT count); -typedef BOOL (WINAPI * PFNWGLRELEASEIMAGEBUFFEREVENTSI3DPROC) (HDC hDC, const LPVOID *pAddress, UINT count); -#endif - -#ifndef WGL_I3D_swap_frame_lock -#define WGL_I3D_swap_frame_lock 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern BOOL WINAPI wglEnableFrameLockI3D (void); -extern BOOL WINAPI wglDisableFrameLockI3D (void); -extern BOOL WINAPI wglIsEnabledFrameLockI3D (BOOL *pFlag); -extern BOOL WINAPI wglQueryFrameLockMasterI3D (BOOL *pFlag); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef BOOL (WINAPI * PFNWGLENABLEFRAMELOCKI3DPROC) (void); -typedef BOOL (WINAPI * PFNWGLDISABLEFRAMELOCKI3DPROC) (void); -typedef BOOL (WINAPI * PFNWGLISENABLEDFRAMELOCKI3DPROC) (BOOL *pFlag); -typedef BOOL (WINAPI * PFNWGLQUERYFRAMELOCKMASTERI3DPROC) (BOOL *pFlag); -#endif - -#ifndef WGL_I3D_swap_frame_usage -#define WGL_I3D_swap_frame_usage 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern BOOL WINAPI wglGetFrameUsageI3D (float *pUsage); -extern BOOL WINAPI wglBeginFrameTrackingI3D (void); -extern BOOL WINAPI wglEndFrameTrackingI3D (void); -extern BOOL WINAPI wglQueryFrameTrackingI3D (DWORD *pFrameCount, DWORD *pMissedFrames, float *pLastMissedUsage); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef BOOL (WINAPI * PFNWGLGETFRAMEUSAGEI3DPROC) (float *pUsage); -typedef BOOL (WINAPI * PFNWGLBEGINFRAMETRACKINGI3DPROC) (void); -typedef BOOL (WINAPI * PFNWGLENDFRAMETRACKINGI3DPROC) (void); -typedef BOOL (WINAPI * PFNWGLQUERYFRAMETRACKINGI3DPROC) (DWORD *pFrameCount, DWORD *pMissedFrames, float *pLastMissedUsage); -#endif - -#ifndef WGL_ATI_pixel_format_float -#define WGL_ATI_pixel_format_float 1 -#endif - -#ifndef WGL_NV_float_buffer -#define WGL_NV_float_buffer 1 -#endif - -#ifndef WGL_3DL_stereo_control -#define WGL_3DL_stereo_control 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern BOOL WINAPI wglSetStereoEmitterState3DL (HDC hDC, UINT uState); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef BOOL (WINAPI * PFNWGLSETSTEREOEMITTERSTATE3DLPROC) (HDC hDC, UINT uState); -#endif - -#ifndef WGL_EXT_pixel_format_packed_float -#define WGL_EXT_pixel_format_packed_float 1 -#endif - -#ifndef WGL_EXT_framebuffer_sRGB -#define WGL_EXT_framebuffer_sRGB 1 -#endif - -#ifndef WGL_NV_present_video -#define WGL_NV_present_video 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern int WINAPI wglEnumerateVideoDevicesNV (HDC hDC, HVIDEOOUTPUTDEVICENV *phDeviceList); -extern BOOL WINAPI wglBindVideoDeviceNV (HDC hDC, unsigned int uVideoSlot, HVIDEOOUTPUTDEVICENV hVideoDevice, const int *piAttribList); -extern BOOL WINAPI wglQueryCurrentContextNV (int iAttribute, int *piValue); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef int (WINAPI * PFNWGLENUMERATEVIDEODEVICESNVPROC) (HDC hDC, HVIDEOOUTPUTDEVICENV *phDeviceList); -typedef BOOL (WINAPI * PFNWGLBINDVIDEODEVICENVPROC) (HDC hDC, unsigned int uVideoSlot, HVIDEOOUTPUTDEVICENV hVideoDevice, const int *piAttribList); -typedef BOOL (WINAPI * PFNWGLQUERYCURRENTCONTEXTNVPROC) (int iAttribute, int *piValue); -#endif - -#ifndef WGL_NV_video_output -#define WGL_NV_video_output 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern BOOL WINAPI wglGetVideoDeviceNV (HDC hDC, int numDevices, HPVIDEODEV *hVideoDevice); -extern BOOL WINAPI wglReleaseVideoDeviceNV (HPVIDEODEV hVideoDevice); -extern BOOL WINAPI wglBindVideoImageNV (HPVIDEODEV hVideoDevice, HPBUFFERARB hPbuffer, int iVideoBuffer); -extern BOOL WINAPI wglReleaseVideoImageNV (HPBUFFERARB hPbuffer, int iVideoBuffer); -extern BOOL WINAPI wglSendPbufferToVideoNV (HPBUFFERARB hPbuffer, int iBufferType, unsigned long *pulCounterPbuffer, BOOL bBlock); -extern BOOL WINAPI wglGetVideoInfoNV (HPVIDEODEV hpVideoDevice, unsigned long *pulCounterOutputPbuffer, unsigned long *pulCounterOutputVideo); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef BOOL (WINAPI * PFNWGLGETVIDEODEVICENVPROC) (HDC hDC, int numDevices, HPVIDEODEV *hVideoDevice); -typedef BOOL (WINAPI * PFNWGLRELEASEVIDEODEVICENVPROC) (HPVIDEODEV hVideoDevice); -typedef BOOL (WINAPI * PFNWGLBINDVIDEOIMAGENVPROC) (HPVIDEODEV hVideoDevice, HPBUFFERARB hPbuffer, int iVideoBuffer); -typedef BOOL (WINAPI * PFNWGLRELEASEVIDEOIMAGENVPROC) (HPBUFFERARB hPbuffer, int iVideoBuffer); -typedef BOOL (WINAPI * PFNWGLSENDPBUFFERTOVIDEONVPROC) (HPBUFFERARB hPbuffer, int iBufferType, unsigned long *pulCounterPbuffer, BOOL bBlock); -typedef BOOL (WINAPI * PFNWGLGETVIDEOINFONVPROC) (HPVIDEODEV hpVideoDevice, unsigned long *pulCounterOutputPbuffer, unsigned long *pulCounterOutputVideo); -#endif - -#ifndef WGL_NV_swap_group -#define WGL_NV_swap_group 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern BOOL WINAPI wglJoinSwapGroupNV (HDC hDC, GLuint group); -extern BOOL WINAPI wglBindSwapBarrierNV (GLuint group, GLuint barrier); -extern BOOL WINAPI wglQuerySwapGroupNV (HDC hDC, GLuint *group, GLuint *barrier); -extern BOOL WINAPI wglQueryMaxSwapGroupsNV (HDC hDC, GLuint *maxGroups, GLuint *maxBarriers); -extern BOOL WINAPI wglQueryFrameCountNV (HDC hDC, GLuint *count); -extern BOOL WINAPI wglResetFrameCountNV (HDC hDC); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef BOOL (WINAPI * PFNWGLJOINSWAPGROUPNVPROC) (HDC hDC, GLuint group); -typedef BOOL (WINAPI * PFNWGLBINDSWAPBARRIERNVPROC) (GLuint group, GLuint barrier); -typedef BOOL (WINAPI * PFNWGLQUERYSWAPGROUPNVPROC) (HDC hDC, GLuint *group, GLuint *barrier); -typedef BOOL (WINAPI * PFNWGLQUERYMAXSWAPGROUPSNVPROC) (HDC hDC, GLuint *maxGroups, GLuint *maxBarriers); -typedef BOOL (WINAPI * PFNWGLQUERYFRAMECOUNTNVPROC) (HDC hDC, GLuint *count); -typedef BOOL (WINAPI * PFNWGLRESETFRAMECOUNTNVPROC) (HDC hDC); -#endif - -#ifndef WGL_NV_gpu_affinity -#define WGL_NV_gpu_affinity 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern BOOL WINAPI wglEnumGpusNV (UINT iGpuIndex, HGPUNV *phGpu); -extern BOOL WINAPI wglEnumGpuDevicesNV (HGPUNV hGpu, UINT iDeviceIndex, PGPU_DEVICE lpGpuDevice); -extern HDC WINAPI wglCreateAffinityDCNV (const HGPUNV *phGpuList); -extern BOOL WINAPI wglEnumGpusFromAffinityDCNV (HDC hAffinityDC, UINT iGpuIndex, HGPUNV *hGpu); -extern BOOL WINAPI wglDeleteDCNV (HDC hdc); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef BOOL (WINAPI * PFNWGLENUMGPUSNVPROC) (UINT iGpuIndex, HGPUNV *phGpu); -typedef BOOL (WINAPI * PFNWGLENUMGPUDEVICESNVPROC) (HGPUNV hGpu, UINT iDeviceIndex, PGPU_DEVICE lpGpuDevice); -typedef HDC (WINAPI * PFNWGLCREATEAFFINITYDCNVPROC) (const HGPUNV *phGpuList); -typedef BOOL (WINAPI * PFNWGLENUMGPUSFROMAFFINITYDCNVPROC) (HDC hAffinityDC, UINT iGpuIndex, HGPUNV *hGpu); -typedef BOOL (WINAPI * PFNWGLDELETEDCNVPROC) (HDC hdc); -#endif - -#ifndef WGL_AMD_gpu_association -#define WGL_AMD_gpu_association 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern UINT WINAPI wglGetGPUIDsAMD (UINT maxCount, UINT *ids); -extern INT WINAPI wglGetGPUInfoAMD (UINT id, int property, GLenum dataType, UINT size, void *data); -extern UINT WINAPI wglGetContextGPUIDAMD (HGLRC hglrc); -extern HGLRC WINAPI wglCreateAssociatedContextAMD (UINT id); -extern HGLRC WINAPI wglCreateAssociatedContextAttribsAMD (UINT id, HGLRC hShareContext, const int *attribList); -extern BOOL WINAPI wglDeleteAssociatedContextAMD (HGLRC hglrc); -extern BOOL WINAPI wglMakeAssociatedContextCurrentAMD (HGLRC hglrc); -extern HGLRC WINAPI wglGetCurrentAssociatedContextAMD (void); -extern VOID WINAPI wglBlitContextFramebufferAMD (HGLRC dstCtx, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef UINT (WINAPI * PFNWGLGETGPUIDSAMDPROC) (UINT maxCount, UINT *ids); -typedef INT (WINAPI * PFNWGLGETGPUINFOAMDPROC) (UINT id, int property, GLenum dataType, UINT size, void *data); -typedef UINT (WINAPI * PFNWGLGETCONTEXTGPUIDAMDPROC) (HGLRC hglrc); -typedef HGLRC (WINAPI * PFNWGLCREATEASSOCIATEDCONTEXTAMDPROC) (UINT id); -typedef HGLRC (WINAPI * PFNWGLCREATEASSOCIATEDCONTEXTATTRIBSAMDPROC) (UINT id, HGLRC hShareContext, const int *attribList); -typedef BOOL (WINAPI * PFNWGLDELETEASSOCIATEDCONTEXTAMDPROC) (HGLRC hglrc); -typedef BOOL (WINAPI * PFNWGLMAKEASSOCIATEDCONTEXTCURRENTAMDPROC) (HGLRC hglrc); -typedef HGLRC (WINAPI * PFNWGLGETCURRENTASSOCIATEDCONTEXTAMDPROC) (void); -typedef VOID (WINAPI * PFNWGLBLITCONTEXTFRAMEBUFFERAMDPROC) (HGLRC dstCtx, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); -#endif - -#ifndef WGL_NV_video_capture -#define WGL_NV_video_capture 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern BOOL WINAPI wglBindVideoCaptureDeviceNV (UINT uVideoSlot, HVIDEOINPUTDEVICENV hDevice); -extern UINT WINAPI wglEnumerateVideoCaptureDevicesNV (HDC hDc, HVIDEOINPUTDEVICENV *phDeviceList); -extern BOOL WINAPI wglLockVideoCaptureDeviceNV (HDC hDc, HVIDEOINPUTDEVICENV hDevice); -extern BOOL WINAPI wglQueryVideoCaptureDeviceNV (HDC hDc, HVIDEOINPUTDEVICENV hDevice, int iAttribute, int *piValue); -extern BOOL WINAPI wglReleaseVideoCaptureDeviceNV (HDC hDc, HVIDEOINPUTDEVICENV hDevice); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef BOOL (WINAPI * PFNWGLBINDVIDEOCAPTUREDEVICENVPROC) (UINT uVideoSlot, HVIDEOINPUTDEVICENV hDevice); -typedef UINT (WINAPI * PFNWGLENUMERATEVIDEOCAPTUREDEVICESNVPROC) (HDC hDc, HVIDEOINPUTDEVICENV *phDeviceList); -typedef BOOL (WINAPI * PFNWGLLOCKVIDEOCAPTUREDEVICENVPROC) (HDC hDc, HVIDEOINPUTDEVICENV hDevice); -typedef BOOL (WINAPI * PFNWGLQUERYVIDEOCAPTUREDEVICENVPROC) (HDC hDc, HVIDEOINPUTDEVICENV hDevice, int iAttribute, int *piValue); -typedef BOOL (WINAPI * PFNWGLRELEASEVIDEOCAPTUREDEVICENVPROC) (HDC hDc, HVIDEOINPUTDEVICENV hDevice); -#endif - -#ifndef WGL_NV_copy_image -#define WGL_NV_copy_image 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern BOOL WINAPI wglCopyImageSubDataNV (HGLRC hSrcRC, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, HGLRC hDstRC, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef BOOL (WINAPI * PFNWGLCOPYIMAGESUBDATANVPROC) (HGLRC hSrcRC, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, HGLRC hDstRC, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth); -#endif - -#ifndef WGL_NV_multisample_coverage -#define WGL_NV_multisample_coverage 1 -#endif - -#ifndef WGL_NV_DX_interop -#define WGL_NV_DX_interop 1 -#ifdef WGL_WGLEXT_PROTOTYPES -extern BOOL WINAPI wglDXSetResourceShareHandleNV (void *dxObject, HANDLE shareHandle); -extern HANDLE WINAPI wglDXOpenDeviceNV (void *dxDevice); -extern BOOL WINAPI wglDXCloseDeviceNV (HANDLE hDevice); -extern HANDLE WINAPI wglDXRegisterObjectNV (HANDLE hDevice, void *dxObject, GLuint name, GLenum type, GLenum access); -extern BOOL WINAPI wglDXUnregisterObjectNV (HANDLE hDevice, HANDLE hObject); -extern BOOL WINAPI wglDXObjectAccessNV (HANDLE hObject, GLenum access); -extern BOOL WINAPI wglDXLockObjectsNV (HANDLE hDevice, GLint count, HANDLE *hObjects); -extern BOOL WINAPI wglDXUnlockObjectsNV (HANDLE hDevice, GLint count, HANDLE *hObjects); -#endif /* WGL_WGLEXT_PROTOTYPES */ -typedef BOOL (WINAPI * PFNWGLDXSETRESOURCESHAREHANDLENVPROC) (void *dxObject, HANDLE shareHandle); -typedef HANDLE (WINAPI * PFNWGLDXOPENDEVICENVPROC) (void *dxDevice); -typedef BOOL (WINAPI * PFNWGLDXCLOSEDEVICENVPROC) (HANDLE hDevice); -typedef HANDLE (WINAPI * PFNWGLDXREGISTEROBJECTNVPROC) (HANDLE hDevice, void *dxObject, GLuint name, GLenum type, GLenum access); -typedef BOOL (WINAPI * PFNWGLDXUNREGISTEROBJECTNVPROC) (HANDLE hDevice, HANDLE hObject); -typedef BOOL (WINAPI * PFNWGLDXOBJECTACCESSNVPROC) (HANDLE hObject, GLenum access); -typedef BOOL (WINAPI * PFNWGLDXLOCKOBJECTSNVPROC) (HANDLE hDevice, GLint count, HANDLE *hObjects); -typedef BOOL (WINAPI * PFNWGLDXUNLOCKOBJECTSNVPROC) (HANDLE hDevice, GLint count, HANDLE *hObjects); -#endif - -#ifndef WGL_NV_DX_interop2 -#define WGL_NV_DX_interop2 1 -#endif - -#ifndef WGL_EXT_swap_control_tear -#define WGL_EXT_swap_control_tear 1 -#endif - - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/RenderSystems/GLSupport/include/win32/OgreWin32Context.h b/RenderSystems/GLSupport/include/win32/OgreWin32Context.h deleted file mode 100644 index ecc050feb5e..00000000000 --- a/RenderSystems/GLSupport/include/win32/OgreWin32Context.h +++ /dev/null @@ -1,60 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OgreW32Context_H__ -#define __OgreW32Context_H__ - -#include "OgreWin32Prerequisites.h" -#include "OgreGLContext.h" - -namespace Ogre { - - class _OgreGLExport Win32Context: public GLContext - { - public: - Win32Context(HDC HDC, - HGLRC Glrc, - Win32GLSupport &glsupport); - virtual ~Win32Context(); - - /** See GLContext */ - virtual void setCurrent(); - /** See GLContext */ - virtual void endCurrent(); - /// @copydoc GLContext::clone - GLContext* clone() const; - - virtual void releaseContext(); - - protected: - HDC mHDC; - HGLRC mGlrc; - Win32GLSupport &mGLSupport; - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/win32/OgreWin32GLSupport.h b/RenderSystems/GLSupport/include/win32/OgreWin32GLSupport.h deleted file mode 100644 index 3b92ae51b64..00000000000 --- a/RenderSystems/GLSupport/include/win32/OgreWin32GLSupport.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#ifndef __OgreWin32GLSupport_H__ -#define __OgreWin32GLSupport_H__ - -#include "OgreWin32Prerequisites.h" -#include "OgreGLNativeSupport.h" - -namespace Ogre -{ - - class _OgreGLExport Win32GLSupport : public GLNativeSupport - { - public: - Win32GLSupport(int profile); - - ConfigOptionMap getConfigOptions(); - - /// @copydoc RenderSystem::_createRenderWindow - virtual RenderWindow* newWindow(const String &name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams = 0); - - - /** - * Start anything special - */ - void start(); - /** - * Stop anything special - */ - void stop(); - - /** - * Get the address of a function - */ - void* getProcAddress(const char* procname) const; - - /** - * Initialise extensions - */ - virtual void initialiseExtensions(); - - - bool selectPixelFormat(HDC hdc, int colourDepth, int multisample, bool hwGamma, bool stereo); - - HGLRC createNewContext(HDC hdc, HGLRC shareList); - private: - Win32Window *mInitialWindow; - bool mHasPixelFormatARB; - bool mHasMultisample; - bool mHasHardwareGamma; - PFNWGLCHOOSEPIXELFORMATARBPROC mWglChoosePixelFormat; - - struct DisplayMonitorInfo - { - HMONITOR hMonitor; - MONITORINFOEX monitorInfoEx; - }; - - typedef std::vector DisplayMonitorInfoList; - typedef DisplayMonitorInfoList::iterator DisplayMonitorInfoIterator; - - DisplayMonitorInfoList mMonitorInfoList; - - void initialiseWGL(); - static LRESULT CALLBACK dummyWndProc(HWND hwnd, UINT umsg, WPARAM wp, LPARAM lp); - static BOOL CALLBACK sCreateMonitorsInfoEnumProc(HMONITOR hMonitor, HDC hdcMonitor, - LPRECT lprcMonitor, LPARAM dwData); - }; - -} - -#endif diff --git a/RenderSystems/GLSupport/include/win32/OgreWin32Prerequisites.h b/RenderSystems/GLSupport/include/win32/OgreWin32Prerequisites.h deleted file mode 100644 index 3007a2092ec..00000000000 --- a/RenderSystems/GLSupport/include/win32/OgreWin32Prerequisites.h +++ /dev/null @@ -1,71 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __OgreWin32Prerequisites_H__ -#define __OgreWin32Prerequisites_H__ - -#include "OgrePlatform.h" -#include -#include -#define WGL_WGLEXT_PROTOTYPES - -/* copy base GL types her to avoid gl header dependancy */ -typedef unsigned int GLenum; -typedef unsigned char GLboolean; -typedef unsigned int GLbitfield; -typedef signed char GLbyte; -typedef short GLshort; -typedef int GLint; -typedef int GLsizei; -typedef unsigned char GLubyte; -typedef unsigned short GLushort; -typedef unsigned int GLuint; -typedef unsigned short GLhalf; -typedef float GLfloat; -typedef float GLclampf; -typedef double GLdouble; -typedef double GLclampd; -typedef void GLvoid; - -#include - -#include "OgreGLSupportPrerequisites.h" -#include "OgrePrerequisites.h" - -namespace Ogre { - // Forward declarations - class Win32GLSupport; - class Win32Window; - class Win32Context; - - - // Useful error method implemented in Win32GLSupport - String translateWGLError(); -} - - -#endif diff --git a/RenderSystems/GLSupport/include/win32/OgreWin32RenderTexture.h b/RenderSystems/GLSupport/include/win32/OgreWin32RenderTexture.h deleted file mode 100644 index 41e52c60b0c..00000000000 --- a/RenderSystems/GLSupport/include/win32/OgreWin32RenderTexture.h +++ /dev/null @@ -1,55 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Win32RT_H__ -#define __Win32RT_H__ - -#include "OgreWin32Prerequisites.h" -#include "OgreWin32Context.h" -#include "OgreGLPBuffer.h" - -namespace Ogre { - class _OgreGLExport Win32PBuffer : public GLPBuffer - { - public: - Win32PBuffer(PixelComponentType format, size_t width, size_t height, Win32GLSupport &glsupport); - ~Win32PBuffer(); - - GLContext *getContext() const { return mContext; } - protected: - void createPBuffer(); - void destroyPBuffer(); - - HDC mHDC; - HGLRC mGlrc; - HPBUFFERARB mPBuffer; - Win32Context *mContext; - }; -} - -#endif diff --git a/RenderSystems/GLSupport/include/win32/OgreWin32Window.h b/RenderSystems/GLSupport/include/win32/OgreWin32Window.h deleted file mode 100644 index 8dc774abe12..00000000000 --- a/RenderSystems/GLSupport/include/win32/OgreWin32Window.h +++ /dev/null @@ -1,94 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __Win32Window_H__ -#define __Win32Window_H__ - -#include "OgreWin32Prerequisites.h" -#include "OgreGLWindow.h" - -namespace Ogre { - class _OgreGLExport Win32Window : public GLWindow - { - public: - Win32Window(Win32GLSupport &glsupport); - ~Win32Window(); - - void create(const String& name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams); - void setFullscreen(bool fullScreen, unsigned int width, unsigned int height); - void destroy(void); - bool isActive(void) const; - bool isVisible() const; - void setHidden(bool hidden); - void setVSyncEnabled(bool vsync); - void reposition(int left, int top); - void resize(unsigned int width, unsigned int height); - void swapBuffers(); - - HWND getWindowHandle() const { return mHWnd; } - HDC getHDC() const { return mHDC; } - - // Method for dealing with resize / move & 3d library - virtual void windowMovedOrResized(void); - - void getCustomAttribute( const String& name, void* pData ); - - /** Used to set the active state of the render target. - */ - virtual void setActive( bool state ); - - void adjustWindow(unsigned int clientWidth, unsigned int clientHeight, - unsigned int* winWidth, unsigned int* winHeight); - - protected: - - void switchMode(uint width, uint height, uint frequency); - - /** Update the window rect. */ - void updateWindowRect(); - - /** Return the target window style depending on the fullscreen parameter. */ - DWORD getWindowStyle(bool fullScreen) const { if (fullScreen) return mFullscreenWinStyle; return mWindowedWinStyle; } - - protected: - Win32GLSupport &mGLSupport; - HWND mHWnd; // Win32 Window handle - HDC mHDC; - HGLRC mGlrc; - char* mDeviceName; - bool mOwnsGLContext; - bool mSizing; - int mDisplayFrequency; // fullscreen only, to restore display - uint32 mColourDepth; - DWORD mWindowedWinStyle; // Windowed mode window style flags. - DWORD mFullscreenWinStyle; // Fullscreen mode window style flags. - }; -} - -#endif diff --git a/RenderSystems/GLSupport/src/EGL/Android/OgreAndroidEGLSupport.cpp b/RenderSystems/GLSupport/src/EGL/Android/OgreAndroidEGLSupport.cpp deleted file mode 100644 index be903ed0834..00000000000 --- a/RenderSystems/GLSupport/src/EGL/Android/OgreAndroidEGLSupport.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreRoot.h" - -#include "OgreAndroidEGLSupport.h" -#include "OgreAndroidEGLWindow.h" -#include "OgreGLUtil.h" - -namespace Ogre { - - GLNativeSupport* getGLSupport(int) - { - return new AndroidEGLSupport(); - } - - AndroidEGLSupport::AndroidEGLSupport() : EGLSupport(CONTEXT_ES) - { - mNativeDisplay = EGL_DEFAULT_DISPLAY; - mGLDisplay = getGLDisplay(); - } - - ConfigOptionMap AndroidEGLSupport::getConfigOptions() - { - ConfigOptionMap mOptions = EGLSupport::getConfigOptions(); - ConfigOption optOrientation; - optOrientation.name = "Orientation"; - optOrientation.immutable = false; - optOrientation.possibleValues.push_back("Landscape"); - optOrientation.possibleValues.push_back("Portrait"); - optOrientation.currentValue = optOrientation.possibleValues[0]; - mOptions[optOrientation.name] = optOrientation; - - ConfigOption optScaling; - optScaling.name = "Content Scaling Factor"; - optScaling.immutable = false; - optScaling.possibleValues.push_back("1"); - optScaling.currentValue = optScaling.possibleValues[0]; - mOptions[optScaling.name] = optScaling; - - return mOptions; - } - - AndroidEGLSupport::~AndroidEGLSupport() - { - - } - - RenderWindow* AndroidEGLSupport::newWindow( const String &name, unsigned int width, unsigned int height, bool fullScreen, const NameValuePairList *miscParams) - { - AndroidEGLWindow* window = new AndroidEGLWindow(this); - window->create(name, width, height, fullScreen, miscParams); - - return window; - } -} diff --git a/RenderSystems/GLSupport/src/EGL/Android/OgreAndroidEGLWindow.cpp b/RenderSystems/GLSupport/src/EGL/Android/OgreAndroidEGLWindow.cpp deleted file mode 100644 index 8c875176aaa..00000000000 --- a/RenderSystems/GLSupport/src/EGL/Android/OgreAndroidEGLWindow.cpp +++ /dev/null @@ -1,393 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreRoot.h" -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" - -#include "OgreGLRenderSystemCommon.h" - -#include "OgreAndroidEGLSupport.h" -#include "OgreAndroidEGLWindow.h" -#include "OgreViewport.h" - -#include - -#include -#include -#include - -namespace Ogre { - AndroidEGLWindow::AndroidEGLWindow(AndroidEGLSupport *glsupport) - : EGLWindow(glsupport), - mMaxBufferSize(32), - mMinBufferSize(16), - mMaxDepthSize(16), - mMaxStencilSize(0), - mMSAA(0), - mCSAA(0), - mPreserveContext(false), - mScale(1.0f) - { - } - - void AndroidEGLWindow::resize(uint width, uint height) - { - width *= mScale; - height *= mScale; - - if (!mActive || (mWidth == width && mHeight == height)) - return; - - mWidth = width; - mHeight = height; - - // Notify viewports of resize - ViewportList::iterator it = mViewportList.begin(); - while (it != mViewportList.end()) - (*it++).second->_updateDimensions(); - - EGLint format; - eglGetConfigAttrib(mEglDisplay, mEglConfig, EGL_NATIVE_VISUAL_ID, &format); - EGL_CHECK_ERROR - - if (mScale != 1.0f) - { - ANativeWindow_setBuffersGeometry(mWindow, mWidth, mHeight, format); - } - else - { - ANativeWindow_setBuffersGeometry(mWindow, 0, 0, format); - } - } - - void AndroidEGLWindow::windowMovedOrResized() - { - if(mActive) - { - int nwidth = ANativeWindow_getWidth(mWindow); - int nheight = ANativeWindow_getHeight(mWindow); - - resize(nwidth, nheight); - } - } - - void AndroidEGLWindow::create(const String& name, uint width, uint height, - bool fullScreen, const NameValuePairList *miscParams) - { - mName = name; - mWidth = width; - mHeight = height; - mLeft = 0; - mTop = 0; - mIsFullScreen = fullScreen; - void* eglContext = NULL; - AConfiguration* config = NULL; - bool preserveContextOpt = false; - - if (miscParams) - { - NameValuePairList::const_iterator opt; - NameValuePairList::const_iterator end = miscParams->end(); - - if ((opt = miscParams->find("currentGLContext")) != end && - StringConverter::parseBool(opt->second)) - { - eglContext = eglGetCurrentContext(); - if (!eglContext) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "currentGLContext was specified with no current GL context", - "EGLWindow::create"); - } - - mEglDisplay = eglGetCurrentDisplay(); - } - - if((opt = miscParams->find("externalWindowHandle")) != end) - { - mWindow = (ANativeWindow*)(Ogre::StringConverter::parseSizeT(opt->second)); - } - - if((opt = miscParams->find("androidConfig")) != end) - { - config = (AConfiguration*)(Ogre::StringConverter::parseSizeT(opt->second)); - } - - if((opt = miscParams->find("maxColourBufferSize")) != end) - { - mMaxBufferSize = Ogre::StringConverter::parseInt(opt->second); - } - - if((opt = miscParams->find("maxDepthBufferSize")) != end) - { - mMaxDepthSize = Ogre::StringConverter::parseInt(opt->second); - } - - if((opt = miscParams->find("maxStencilBufferSize")) != end) - { - mMaxStencilSize = Ogre::StringConverter::parseInt(opt->second); - } - - if((opt = miscParams->find("minColourBufferSize")) != end) - { - mMinBufferSize = Ogre::StringConverter::parseInt(opt->second); - if (mMinBufferSize > mMaxBufferSize) mMinBufferSize = mMaxBufferSize; - } - - if((opt = miscParams->find("FSAA")) != end) - { - mMSAA = Ogre::StringConverter::parseInt(opt->second); - } - - if((opt = miscParams->find("CSAA")) != end) - { - mCSAA = Ogre::StringConverter::parseInt(opt->second); - } - - if ((opt = miscParams->find("preserveContext")) != end && - StringConverter::parseBool(opt->second)) - { - preserveContextOpt = true; - } - - if ((opt = miscParams->find("externalGLControl")) != end) - { - mIsExternalGLControl = StringConverter::parseBool(opt->second); - } - - if ((opt = miscParams->find("contentScalingFactor")) != end) - { - mScale = 1.0f / Ogre::StringConverter::parseReal(opt->second); - } - } - - if (!mEglConfig && eglContext) - { - mEglConfig = mGLSupport->getGLConfigFromContext(eglContext); - - if (!mEglConfig) - { - // This should never happen. - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Unexpected failure to determine a EGLFBConfig", - "EGLWindow::create"); - } - } - - if (!mEglConfig) - { - _notifySurfaceCreated(mWindow, config); - mHwGamma = false; - } - - mContext = createEGLContext(eglContext); - mContext->setCurrent(); - - eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, (EGLint*)&mWidth); - eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, (EGLint*)&mHeight); - EGL_CHECK_ERROR - - mPreserveContext = preserveContextOpt; - - finaliseWindow(); - } - - void AndroidEGLWindow::_notifySurfaceDestroyed() - { - if(mClosed) - return; - - if (!mPreserveContext) - { - mContext->setCurrent(); - - static_cast(Root::getSingletonPtr()->getRenderSystem())->notifyOnContextLost(); - static_cast(mContext)->_destroyInternalResources(); - } - - eglDestroySurface(mEglDisplay, mEglSurface); - EGL_CHECK_ERROR - mEglSurface = 0; - - if (!mPreserveContext) - { - eglTerminate(mEglDisplay); - EGL_CHECK_ERROR - mEglDisplay = 0; - } - - mActive = false; - mVisible = false; - mClosed = true; - } - - void AndroidEGLWindow::_notifySurfaceCreated(void* window, void* config) - { - mWindow = reinterpret_cast(window); - - if (mPreserveContext) - { - mEglDisplay = mGLSupport->getGLDisplay(); - - EGLint format; - eglGetConfigAttrib(mEglDisplay, mEglConfig, EGL_NATIVE_VISUAL_ID, &format); - EGL_CHECK_ERROR - - if (mScale != 1.0f) - { - int nwidth = (int)((float)ANativeWindow_getWidth(mWindow) * mScale); - int nheight = (int)((float)ANativeWindow_getHeight(mWindow) * mScale); - ANativeWindow_setBuffersGeometry(mWindow, nwidth, nheight, format); - } - else - { - ANativeWindow_setBuffersGeometry(mWindow, 0, 0, format); - } - - mEglSurface = createSurfaceFromWindow(mEglDisplay, mWindow); - static_cast(mContext)->_updateInternalResources(mEglDisplay, mEglConfig, mEglSurface); - } - else - { - int minAttribs[] = { - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - EGL_BUFFER_SIZE, mMinBufferSize, - EGL_DEPTH_SIZE, 16, - EGL_NONE - }; - - int maxAttribs[] = { - EGL_BUFFER_SIZE, mMaxBufferSize, - EGL_DEPTH_SIZE, mMaxDepthSize, - EGL_STENCIL_SIZE, mMaxStencilSize, - EGL_NONE - }; - - bool bAASuccess = false; - if (mCSAA) - { - try - { - int CSAAminAttribs[] = { - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - EGL_BUFFER_SIZE, mMinBufferSize, - EGL_DEPTH_SIZE, 16, - EGL_COVERAGE_BUFFERS_NV, 1, - EGL_COVERAGE_SAMPLES_NV, mCSAA, - EGL_NONE - }; - int CSAAmaxAttribs[] = { - EGL_BUFFER_SIZE, mMaxBufferSize, - EGL_DEPTH_SIZE, mMaxDepthSize, - EGL_STENCIL_SIZE, mMaxStencilSize, - EGL_COVERAGE_BUFFERS_NV, 1, - EGL_COVERAGE_SAMPLES_NV, mCSAA, - EGL_NONE - }; - mEglConfig = mGLSupport->selectGLConfig(CSAAminAttribs, CSAAmaxAttribs); - bAASuccess = true; - } - catch (Exception& e) - { - LogManager::getSingleton().logMessage("AndroidEGLWindow::_createInternalResources: setting CSAA failed"); - } - } - - if (mMSAA && !bAASuccess) - { - try - { - int MSAAminAttribs[] = { - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - EGL_BUFFER_SIZE, mMinBufferSize, - EGL_DEPTH_SIZE, 16, - EGL_SAMPLE_BUFFERS, 1, - EGL_SAMPLES, mMSAA, - EGL_NONE - }; - int MSAAmaxAttribs[] = { - EGL_BUFFER_SIZE, mMaxBufferSize, - EGL_DEPTH_SIZE, mMaxDepthSize, - EGL_STENCIL_SIZE, mMaxStencilSize, - EGL_SAMPLE_BUFFERS, 1, - EGL_SAMPLES, mMSAA, - EGL_NONE - }; - mEglConfig = mGLSupport->selectGLConfig(MSAAminAttribs, MSAAmaxAttribs); - bAASuccess = true; - } - catch (Exception& e) - { - LogManager::getSingleton().logMessage("AndroidEGLWindow::_createInternalResources: setting MSAA failed"); - } - } - - mEglDisplay = mGLSupport->getGLDisplay(); - if (!bAASuccess) mEglConfig = mGLSupport->selectGLConfig(minAttribs, maxAttribs); - - EGLint format; - eglGetConfigAttrib(mEglDisplay, mEglConfig, EGL_NATIVE_VISUAL_ID, &format); - EGL_CHECK_ERROR - - if (mScale != 1.0f) - { - int nwidth = (int)((float)ANativeWindow_getWidth(mWindow) * mScale); - int nheight = (int)((float)ANativeWindow_getHeight(mWindow) * mScale); - ANativeWindow_setBuffersGeometry(mWindow, nwidth, nheight, format); - } - else - { - ANativeWindow_setBuffersGeometry(mWindow, 0, 0, format); - } - - mEglSurface = createSurfaceFromWindow(mEglDisplay, mWindow); - - if (config) - { - bool isLandscape = (int)AConfiguration_getOrientation((AConfiguration*)config) == 2; - Root::getSingletonPtr()->getRenderSystem()->setConfigOption("Orientation", isLandscape ? "Landscape" : "Portrait"); - } - } - - if(mContext) - { - mActive = true; - mVisible = true; - mClosed = false; - - if (!mPreserveContext) - { - static_cast(mContext)->_createInternalResources(mEglDisplay, mEglConfig, mEglSurface, NULL); - - static_cast(Root::getSingletonPtr()->getRenderSystem())->resetRenderer(this); - } - } - } -} diff --git a/RenderSystems/GLSupport/src/EGL/Emscripten/OgreEmscriptenEGLSupport.cpp b/RenderSystems/GLSupport/src/EGL/Emscripten/OgreEmscriptenEGLSupport.cpp deleted file mode 100644 index 3982b5b3007..00000000000 --- a/RenderSystems/GLSupport/src/EGL/Emscripten/OgreEmscriptenEGLSupport.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreRoot.h" - -#include "OgreEmscriptenEGLSupport.h" -#include "OgreEmscriptenEGLWindow.h" - -#include "OgreGLUtil.h" - -namespace Ogre { - GLNativeSupport* getGLSupport(int) - { - return new EmscriptenEGLSupport(); - } - - EmscriptenEGLSupport::EmscriptenEGLSupport() : EGLSupport(GLNativeSupport::CONTEXT_ES) - { - mNativeDisplay = EGL_DEFAULT_DISPLAY; - mGLDisplay = getGLDisplay(); - } - - EmscriptenEGLSupport::~EmscriptenEGLSupport() - { - } - - RenderWindow* EmscriptenEGLSupport::newWindow( const String &name, unsigned int width, unsigned int height, bool fullScreen, const NameValuePairList *miscParams) - { - EmscriptenEGLWindow* window = new EmscriptenEGLWindow(this); - window->create(name, width, height, fullScreen, miscParams); - - return window; - } - - EGLConfig* EmscriptenEGLSupport::chooseGLConfig(const EGLint *attribList, EGLint *nElements) - { - // Emscripten eglChooseConfig: Implemented as a stub, but this function does not do searching/filtering, - // and is at the moment identical to eglGetConfigs - EGLConfig* configs = EGLSupport::chooseGLConfig(attribList, nElements); - - for(int config = 0; config < *nElements; ++config) - { - for(int attrib = 0; attribList[attrib] != EGL_NONE; attrib += 2) - { - EGLint value; - if (eglGetConfigAttrib(mGLDisplay, configs[config], attribList[attrib], &value) == EGL_FALSE) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Failed to get config attribute"); - - *nElements = 0; - free(configs); - return 0; - } - - bool passed = true; - EGLint test = attribList[attrib + 1]; - - switch(attribList[attrib]) - { - case EGL_ALPHA_MASK_SIZE: - case EGL_ALPHA_SIZE: - case EGL_BLUE_SIZE: - case EGL_BUFFER_SIZE: - case EGL_DEPTH_SIZE: - case EGL_GREEN_SIZE: - case EGL_LUMINANCE_SIZE: - case EGL_RED_SIZE: - case EGL_SAMPLE_BUFFERS: - case EGL_SAMPLES: - case EGL_STENCIL_SIZE: - { - if(value < test) - { - passed = false; - } - } - break; - case EGL_COLOR_BUFFER_TYPE: - case EGL_LEVEL: - case EGL_TRANSPARENT_TYPE: - { - if(value != test) - { - passed = false; - } - } - break; - case EGL_CONFORMANT: - case EGL_RENDERABLE_TYPE: - case EGL_SURFACE_TYPE: - { - if (test & ~value) - { - passed = false; - } - } - break; - case EGL_MATCH_NATIVE_PIXMAP: - { - if (test != EGL_NONE) - { - passed = false; - } - } - break; - default: - break; - } - - if (!passed) - { - // Shift all later configs up one - --*nElements; - for(int i = config; i < *nElements; ++i) - { - configs[i] = configs[i + 1]; - } - --config; - break; - } - } - } - return configs; - } -} diff --git a/RenderSystems/GLSupport/src/EGL/Emscripten/OgreEmscriptenEGLWindow.cpp b/RenderSystems/GLSupport/src/EGL/Emscripten/OgreEmscriptenEGLWindow.cpp deleted file mode 100644 index ff2f9666c78..00000000000 --- a/RenderSystems/GLSupport/src/EGL/Emscripten/OgreEmscriptenEGLWindow.cpp +++ /dev/null @@ -1,392 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreRoot.h" -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" - -#include "OgreGLRenderSystemCommon.h" - -#include "OgreEmscriptenEGLSupport.h" -#include "OgreEmscriptenEGLWindow.h" -#include "OgreViewport.h" - -#include -#include -#include - -namespace Ogre { - EmscriptenEGLWindow::EmscriptenEGLWindow(EmscriptenEGLSupport *glsupport) - : EGLWindow(glsupport), - mMaxBufferSize(32), - mMinBufferSize(16), - mMaxDepthSize(16), - mMaxStencilSize(0), - mMSAA(0), - mCSAA(0) - { - // already handled by resize - emscripten_set_fullscreenchange_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, (void*)this, 1, &EmscriptenEGLWindow::fullscreenCallback); - emscripten_set_webglcontextlost_callback("#canvas", (void*)this, 1, &EmscriptenEGLWindow::contextLostCallback); - emscripten_set_webglcontextrestored_callback("#canvas", (void*)this, 1, &EmscriptenEGLWindow::contextRestoredCallback); - emscripten_set_resize_callback("#canvas", (void*)this, 1, &EmscriptenEGLWindow::canvasWindowResized); - } - - EmscriptenEGLWindow::~EmscriptenEGLWindow() - { - emscripten_set_fullscreenchange_callback("#canvas", NULL, 0, NULL); - emscripten_set_resize_callback("#canvas", NULL, 0, NULL); - emscripten_set_webglcontextlost_callback("#canvas", NULL, 0, NULL); - emscripten_set_webglcontextrestored_callback("#canvas", NULL, 0, NULL); - } - - void EmscriptenEGLWindow::resize(uint width, uint height) - { - mWidth = width; - mHeight = height; - - - EMSCRIPTEN_RESULT result = emscripten_set_canvas_element_size(mCanvasSelector.c_str(), width, height); - // This is a workaroud for issue: https://github.com/emscripten-core/emscripten/issues/3283. - // The setTimeout of 0 will ensure that this code is runs on the next JSEventLoop. - EM_ASM(setTimeout(function(){var canvas = document.getElementById('canvas'); canvas.width = $0; canvas.height = $1;}, 0), width, height); - - if(result < 0) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Unexpected failure at emscripten_set_canvas_element_size with selector=" + mCanvasSelector, - "EmscriptenEGLWindow::resize"); - } - - - LogManager::getSingleton().logMessage("EmscriptenEGLWindow::resize "+mCanvasSelector+" w:" + Ogre::StringConverter::toString(mWidth) + " h:" + Ogre::StringConverter::toString(mHeight)); - - // Notify viewports of resize - ViewportList::iterator it = mViewportList.begin(); - while( it != mViewportList.end() ) - (*it++).second->_updateDimensions(); - } - - void EmscriptenEGLWindow::windowMovedOrResized() - { - if(!mActive) return; - - int w, h; - emscripten_get_canvas_element_size(mCanvasSelector.c_str(), &w, &h); - mWidth = w; - mHeight = h; - - // Notify viewports of resize - ViewportList::iterator it = mViewportList.begin(); - while( it != mViewportList.end() ) - (*it++).second->_updateDimensions(); - } - - void EmscriptenEGLWindow::switchFullScreen(bool fullscreen) - { - if(fullscreen) - emscripten_request_fullscreen(NULL, 1); - else - emscripten_exit_fullscreen(); - } - - void EmscriptenEGLWindow::create(const String& name, uint width, uint height, - bool fullScreen, const NameValuePairList *miscParams) - { - mName = name; - mWidth = width; - mHeight = height; - mLeft = 0; - mTop = 0; - mCanvasSelector = "#canvas"; - void* eglContext = nullptr; - - if (miscParams) - { - NameValuePairList::const_iterator opt; - NameValuePairList::const_iterator end = miscParams->end(); - - if ((opt = miscParams->find("currentGLContext")) != end && - StringConverter::parseBool(opt->second)) - { - eglContext = eglGetCurrentContext(); - if (eglContext) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "currentGLContext was specified with no current GL context", - "EGLWindow::create"); - } - - eglContext = eglGetCurrentContext(); - } - - if((opt = miscParams->find("maxColourBufferSize")) != end) - { - mMaxBufferSize = Ogre::StringConverter::parseInt(opt->second); - } - - if((opt = miscParams->find("maxDepthBufferSize")) != end) - { - mMaxDepthSize = Ogre::StringConverter::parseInt(opt->second); - } - - if((opt = miscParams->find("maxStencilBufferSize")) != end) - { - mMaxStencilSize = Ogre::StringConverter::parseInt(opt->second); - } - - if((opt = miscParams->find("minColourBufferSize")) != end) - { - mMinBufferSize = Ogre::StringConverter::parseInt(opt->second); - if (mMinBufferSize > mMaxBufferSize) mMinBufferSize = mMaxBufferSize; - } - - if((opt = miscParams->find("FSAA")) != end) - { - mMSAA = Ogre::StringConverter::parseInt(opt->second); - } - - if((opt = miscParams->find("CSAA")) != end) - { - mCSAA = Ogre::StringConverter::parseInt(opt->second); - } - - if ((opt = miscParams->find("externalWindowHandle")) != end || - (opt = miscParams->find("parentWindowHandle")) != end) - { - mCanvasSelector = opt->second; - } - } - - if (!mEglConfig && eglContext) - { - mEglConfig = mGLSupport->getGLConfigFromContext(eglContext); - - if (!mEglConfig) - { - // This should never happen. - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Unexpected failure to determine a EGLFBConfig", - "EGLWindow::create"); - } - } - - if (!mEglConfig) - { - _notifySurfaceCreated(&mWindow); - mHwGamma = false; - } - - mContext = createEGLContext(eglContext); - mContext->setCurrent(); - EMSCRIPTEN_RESULT result = emscripten_set_canvas_element_size(mCanvasSelector.c_str(), width, height); - - if(result < 0) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Unexpected failure at emscripten_set_canvas_element_size with selector=" + mCanvasSelector , - "EmscriptenEGLWindow::create"); - } - - mOldWidth = width; - mOldHeight = height; - if(fullScreen) - switchFullScreen(true); - - EGL_CHECK_ERROR - - mActive = true; - mVisible = true; - mClosed = false; - } - - int EmscriptenEGLWindow::contextLostCallback(int eventType, const void *reserved, void *userData) - { - Ogre::EmscriptenEGLWindow* thiz = static_cast(userData); - thiz->_notifySurfaceDestroyed(); - return 0; - } - - int EmscriptenEGLWindow::contextRestoredCallback(int eventType, const void *reserved, void *userData) - { - Ogre::EmscriptenEGLWindow* thiz = static_cast(userData); - thiz->_notifySurfaceCreated(&thiz->mWindow); - return 0; - } - - void EmscriptenEGLWindow::_notifySurfaceDestroyed() - { - mContext->setCurrent(); - - static_cast(Root::getSingleton().getRenderSystem())->notifyOnContextLost(); - static_cast(mContext)->_destroyInternalResources(); - - eglDestroySurface(mEglDisplay, mEglSurface); - EGL_CHECK_ERROR - - eglTerminate(mEglDisplay); - EGL_CHECK_ERROR - - mEglDisplay = 0; - mEglSurface = 0; - - mActive = false; - mVisible = false; - mClosed = true; - } - - void EmscriptenEGLWindow::_notifySurfaceCreated(void* window, void*) - { - mWindow = *reinterpret_cast(window); - - int minAttribs[] = { - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - EGL_BUFFER_SIZE, mMinBufferSize, - EGL_DEPTH_SIZE, 16, - EGL_NONE - }; - - int maxAttribs[] = { - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - EGL_BUFFER_SIZE, mMaxBufferSize, - EGL_DEPTH_SIZE, mMaxDepthSize, - EGL_STENCIL_SIZE, mMaxStencilSize, - EGL_NONE - }; - - bool bAASuccess = false; - if (mCSAA) - { - try - { - int CSAAminAttribs[] = { - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - EGL_BUFFER_SIZE, mMinBufferSize, - EGL_DEPTH_SIZE, 16, - EGL_COVERAGE_BUFFERS_NV, 1, - EGL_COVERAGE_SAMPLES_NV, mCSAA, - EGL_NONE - }; - int CSAAmaxAttribs[] = { - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - EGL_BUFFER_SIZE, mMaxBufferSize, - EGL_DEPTH_SIZE, mMaxDepthSize, - EGL_STENCIL_SIZE, mMaxStencilSize, - EGL_COVERAGE_BUFFERS_NV, 1, - EGL_COVERAGE_SAMPLES_NV, mCSAA, - EGL_NONE - }; - mEglConfig = mGLSupport->selectGLConfig(CSAAminAttribs, CSAAmaxAttribs); - bAASuccess = true; - } - catch (Exception& e) - { - LogManager::getSingleton().logMessage("EmscriptenEGLWindow::_createInternalResources: setting CSAA failed"); - } - } - - if (mMSAA && !bAASuccess) - { - try - { - int MSAAminAttribs[] = { - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - EGL_BUFFER_SIZE, mMinBufferSize, - EGL_DEPTH_SIZE, 16, - EGL_SAMPLE_BUFFERS, 1, - EGL_SAMPLES, mMSAA, - EGL_NONE - }; - int MSAAmaxAttribs[] = { - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - EGL_BUFFER_SIZE, mMaxBufferSize, - EGL_DEPTH_SIZE, mMaxDepthSize, - EGL_STENCIL_SIZE, mMaxStencilSize, - EGL_SAMPLE_BUFFERS, 1, - EGL_SAMPLES, mMSAA, - EGL_NONE - }; - mEglConfig = mGLSupport->selectGLConfig(MSAAminAttribs, MSAAmaxAttribs); - bAASuccess = true; - } - catch (Exception& e) - { - LogManager::getSingleton().logMessage("EmscriptenEGLWindow::_createInternalResources: setting MSAA failed"); - } - } - - mEglDisplay = mGLSupport->getGLDisplay(); - if (!bAASuccess) mEglConfig = mGLSupport->selectGLConfig(minAttribs, maxAttribs); - - mEglSurface = createSurfaceFromWindow(mEglDisplay, mWindow); - - if(mContext) - { - mActive = true; - mVisible = true; - mClosed = false; - - static_cast(mContext)->_createInternalResources(mEglDisplay, mEglConfig, mEglSurface, nullptr); - - static_cast(Ogre::Root::getSingleton().getRenderSystem())->resetRenderer(this); - } - } - - void EmscriptenEGLWindow::swapBuffers() - { - // Not used on emscripten - } - - EM_BOOL EmscriptenEGLWindow::canvasWindowResized(int eventType, const EmscriptenUiEvent *event, void *userData) - { - EmscriptenEGLWindow* thiz = static_cast(userData); - thiz->windowMovedOrResized(); - return EMSCRIPTEN_RESULT_SUCCESS; - } - - EM_BOOL EmscriptenEGLWindow::fullscreenCallback(int eventType, const EmscriptenFullscreenChangeEvent* event, void* userData) - { - EmscriptenEGLWindow* thiz = static_cast(userData); - - thiz->mIsFullScreen = event->isFullscreen; - if (event->isFullscreen) - { - thiz->mOldWidth = thiz->mWidth; - thiz->mOldHeight = thiz->mHeight; - thiz->resize(event->screenWidth, event->screenHeight); - } - else - { - thiz->resize(thiz->mOldWidth, thiz->mOldHeight); - } - - thiz->windowMovedOrResized(); - return EMSCRIPTEN_RESULT_SUCCESS; - } -} diff --git a/RenderSystems/GLSupport/src/EGL/OgreEGLContext.cpp b/RenderSystems/GLSupport/src/EGL/OgreEGLContext.cpp deleted file mode 100644 index 9277d4eb125..00000000000 --- a/RenderSystems/GLSupport/src/EGL/OgreEGLContext.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2008 Renato Araujo Oliveira Filho -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreGLRenderSystemCommon.h" - -#include "OgreEGLSupport.h" -#include "OgreEGLContext.h" - -#include "OgreRoot.h" - -#include "OgreLogManager.h" - -extern "C" { -int gleswInit(void); -} - -namespace Ogre { - EGLContext::EGLContext(EGLDisplay eglDisplay, - const EGLSupport* glsupport, - ::EGLConfig glconfig, - ::EGLSurface drawable, - ::EGLContext external) - : mGLSupport(glsupport), - mContext(0), - mExternalContext(false) - { - assert(drawable); - GLRenderSystemCommon* renderSystem = static_cast(Root::getSingleton().getRenderSystem()); - EGLContext* mainContext = static_cast(renderSystem->_getMainContext()); - ::EGLContext shareContext = (::EGLContext) 0; - - if (mainContext) - { - shareContext = mainContext->mContext; - } - - if (external) - { - mContext = external; - mExternalContext = true; - } - - _createInternalResources(eglDisplay, glconfig, drawable, shareContext); - } - - EGLContext::~EGLContext() - { - GLRenderSystemCommon *rs = - static_cast(Root::getSingleton().getRenderSystem()); - try { - _destroyInternalResources(); - } catch(RenderingAPIException&) { - // EGL_CHECK_ERROR might throw - // just ignore as it will get logged anyway. - } - - rs->_unregisterContext(this); - } - - void EGLContext::_createInternalResources(EGLDisplay eglDisplay, ::EGLConfig glconfig, ::EGLSurface drawable, ::EGLContext shareContext) - { - mDrawable = drawable; - mConfig = glconfig; - mEglDisplay = eglDisplay; - - if(!mExternalContext) - mContext = mGLSupport->createNewContext(mEglDisplay, mConfig, shareContext); - - if (!mContext) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to obtain an EGLContext"); - } - - setCurrent(); - } - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - void EGLContext::_updateInternalResources(EGLDisplay eglDisplay, ::EGLConfig glconfig, ::EGLSurface drawable) - { - mDrawable = drawable; - mConfig = glconfig; - mEglDisplay = eglDisplay; - - setCurrent(); - - // Initialise GL3W - if (gleswInit()) - LogManager::getSingleton().logMessage("Failed to initialize GL3W"); - } -#endif - - void EGLContext::_destroyInternalResources() - { - endCurrent(); - - if (!mExternalContext) - { - eglDestroyContext(mEglDisplay, mContext); - EGL_CHECK_ERROR - } - - mContext = NULL; - } - - void EGLContext::setCurrent() - { - if(eglGetCurrentSurface(EGL_DRAW) == mDrawable) - return; - - EGLBoolean ret = eglMakeCurrent(mEglDisplay, - mDrawable, mDrawable, mContext); - EGL_CHECK_ERROR - if (!ret) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to make context current"); - } - } - - void EGLContext::endCurrent() - { - eglMakeCurrent(mEglDisplay, 0, 0, 0); - EGL_CHECK_ERROR - } - - EGLSurface EGLContext::getDrawable() const - { - return mDrawable; - } -} diff --git a/RenderSystems/GLSupport/src/EGL/OgreEGLRenderTexture.cpp b/RenderSystems/GLSupport/src/EGL/OgreEGLRenderTexture.cpp deleted file mode 100644 index 0ddc4d8badf..00000000000 --- a/RenderSystems/GLSupport/src/EGL/OgreEGLRenderTexture.cpp +++ /dev/null @@ -1,152 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2008 Renato Araujo Oliveira Filho -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#if 1 -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreRoot.h" -#include "OgreStringConverter.h" - -#include "OgreEGLRenderTexture.h" -#include "OgreEGLContext.h" -#include "OgreEGLSupport.h" - -#include -#include - -namespace Ogre { - EGLPBuffer::EGLPBuffer(EGLSupport* glsupport, PixelComponentType format, - uint32 width, uint32 height) - : GLPBuffer(format, width, height) - { - mGLSupport = glsupport; - mGlDisplay = mGLSupport->getGLDisplay(); - - mEglDrawable = 0; - ::EGLConfig glConfig = 0; - - int bits = 0; - - switch (mFormat) - { - case PCT_BYTE: - bits = 8; - break; - - case PCT_SHORT: - case PCT_FLOAT16: - bits = 16; - break; - - case PCT_FLOAT32: - bits = 32; - break; - - default: - break; - } - - if (mFormat == PCT_FLOAT16 || mFormat == PCT_FLOAT32) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, - "No support for Floating point PBuffers", - "EGLRenderTexture::initEGLPBuffer"); - } - - int minAttribs[] = { - EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, - EGL_DEPTH_SIZE, 16, - EGL_NONE - }; - - int maxAttribs[] = { - EGL_RED_SIZE, bits, - EGL_GREEN_SIZE, bits, - EGL_BLUE_SIZE, bits, - EGL_ALPHA_SIZE, bits, - EGL_STENCIL_SIZE, INT_MAX, - EGL_NONE - }; - - int pBufferAttribs[] = { - // First we specify the width of the surface... - EGL_WIDTH, (int)mWidth, - // ...then the height of the surface... - EGL_HEIGHT, (int)mHeight, - /* ... then we specify the target for the texture - that will be created when the pbuffer is created...*/ - EGL_TEXTURE_TARGET, EGL_TEXTURE_2D, - /*..then the format of the texture that will be created - when the pBuffer is bound to a texture...*/ - EGL_TEXTURE_FORMAT, EGL_TEXTURE_RGBA, - // The final thing is EGL_NONE which signifies the end. - EGL_NONE - }; - - - glConfig = mGLSupport->selectGLConfig(minAttribs, maxAttribs); - - EGL_CHECK_ERROR; - mEglDrawable = eglCreatePbufferSurface(mGlDisplay, glConfig, pBufferAttribs); - EGL_CHECK_ERROR; - - if (!glConfig || !mEglDrawable) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Unable to create Pbuffer", - "EGLPBuffer::EGLPBuffer"); - } - EGLint glConfigID; - EGLint iWidth, iHeight; - - eglGetConfigAttrib(mGlDisplay, glConfig, EGL_CONFIG_ID, &glConfigID); - EGL_CHECK_ERROR; - eglQuerySurface(mGlDisplay, mEglDrawable, EGL_WIDTH, &iWidth); - EGL_CHECK_ERROR; - eglQuerySurface(mGlDisplay, mEglDrawable, EGL_HEIGHT, &iHeight); - EGL_CHECK_ERROR; - - mWidth = iWidth; - mHeight = iHeight; - LogManager::getSingleton().logMessage(LML_NORMAL, "EGLPBuffer::create used final dimensions " + StringConverter::toString(mWidth) + " x " + StringConverter::toString(mHeight)); - LogManager::getSingleton().logMessage("EGLPBuffer::create used FBConfigID " + StringConverter::toString(glConfigID)); - - mContext = new EGLContext(mGlDisplay, mGLSupport, glConfig, mEglDrawable, NULL); - } - - EGLPBuffer::~EGLPBuffer() - { - eglDestroySurface(mGlDisplay, mEglDrawable); - delete mContext; - LogManager::getSingleton().logMessage(LML_NORMAL, "EGLPBuffer::PBuffer destroyed"); - } - - -} -#endif diff --git a/RenderSystems/GLSupport/src/EGL/OgreEGLSupport.cpp b/RenderSystems/GLSupport/src/EGL/OgreEGLSupport.cpp deleted file mode 100755 index 01a63f15dfb..00000000000 --- a/RenderSystems/GLSupport/src/EGL/OgreEGLSupport.cpp +++ /dev/null @@ -1,427 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2008 Renato Araujo Oliveira Filho -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreRoot.h" - -#include "OgreRenderSystem.h" - -#include "OgreEGLSupport.h" -#include "OgreEGLWindow.h" -#if OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN -#include "OgreEGLRenderTexture.h" -#endif - -#ifndef EGL_VERSION_1_5 -#define EGL_CONTEXT_MAJOR_VERSION EGL_CONTEXT_CLIENT_VERSION -#define EGL_CONTEXT_MINOR_VERSION EGL_NONE -#endif - -#include - -namespace Ogre { - - - EGLSupport::EGLSupport(int profile) - : GLNativeSupport(profile), mGLDisplay(0), - mNativeDisplay(EGL_DEFAULT_DISPLAY), hasEGL15(false) - { - } - - EGLDisplay EGLSupport::getGLDisplay(void) - { -#if defined(EGL_VERSION_1_5) && OGRE_PLATFORM != OGRE_PLATFORM_ANDROID && OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN - static auto eglQueryDevicesEXT = (PFNEGLQUERYDEVICESEXTPROC)eglGetProcAddress("eglQueryDevicesEXT"); - static auto eglQueryDeviceStringEXT = - (PFNEGLQUERYDEVICESTRINGEXTPROC)eglGetProcAddress("eglQueryDeviceStringEXT"); - - if(eglQueryDevicesEXT && mNativeDisplay == EGL_DEFAULT_DISPLAY) - { - int numDevices; - eglQueryDevicesEXT(0, NULL, &numDevices); - EGL_CHECK_ERROR - std::vector devices(numDevices); - eglQueryDevicesEXT(numDevices, devices.data(), &numDevices); - - EGLAttrib attribs[] = {EGL_NONE}; - for(auto dev : devices) - { - EGLDisplay display = eglGetPlatformDisplay(EGL_PLATFORM_DEVICE_EXT, dev, attribs); - EGL_CHECK_ERROR - - if(display != EGL_NO_DISPLAY && !mGLDisplay) - { - mGLDisplay = display; - const char* exts = eglQueryDeviceStringEXT(dev, EGL_EXTENSIONS); - LogManager::getSingleton().stream() << "EGL: using default display. Device extensions: " << exts; - break; - } - } - } - else -#endif - { - mGLDisplay = eglGetDisplay(mNativeDisplay); - EGL_CHECK_ERROR - } - - if(mGLDisplay == EGL_NO_DISPLAY) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn`t get EGLDisplay"); - } - - if (eglInitialize(mGLDisplay, &mEGLMajor, &mEGLMinor) == EGL_FALSE) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Couldn`t initialize EGLDisplay ", - "EGLSupport::getGLDisplay"); - } - EGL_CHECK_ERROR - - return mGLDisplay; - } - - EGLConfig* EGLSupport::chooseGLConfig(const EGLint *attribList, EGLint *nElements) - { - EGLConfig *configs; - - if (eglChooseConfig(mGLDisplay, attribList, NULL, 0, nElements) == EGL_FALSE) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config"); - - *nElements = 0; - return 0; - } - EGL_CHECK_ERROR - configs = (EGLConfig*) malloc(*nElements * sizeof(EGLConfig)); - if (eglChooseConfig(mGLDisplay, attribList, configs, *nElements, nElements) == EGL_FALSE) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config"); - - *nElements = 0; - free(configs); - return 0; - } - EGL_CHECK_ERROR - return configs; - } - - EGLConfig* EGLSupport::getConfigs(EGLint *nElements) - { - EGLConfig *configs; - - if (eglGetConfigs(mGLDisplay, NULL, 0, nElements) == EGL_FALSE) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config"); - - *nElements = 0; - return 0; - } - EGL_CHECK_ERROR - configs = (EGLConfig*) malloc(*nElements * sizeof(EGLConfig)); - if (eglGetConfigs(mGLDisplay, configs, *nElements, nElements) == EGL_FALSE) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config"); - - *nElements = 0; - free(configs); - return 0; - } - EGL_CHECK_ERROR - return configs; - } - - EGLBoolean EGLSupport::getGLConfigAttrib(EGLConfig glConfig, EGLint attribute, EGLint *value) - { - EGLBoolean status; - - status = eglGetConfigAttrib(mGLDisplay, glConfig, attribute, value); - EGL_CHECK_ERROR - return status; - } - - void* EGLSupport::getProcAddress(const char* name) const - { - return (void*)eglGetProcAddress(name); - } - - ::EGLConfig EGLSupport::getGLConfigFromContext(::EGLContext context) - { - ::EGLConfig glConfig; - EGLint id = 0; - ::EGLConfig *configs; - EGLint numConfigs; - - if (eglQueryContext(mGLDisplay, context, EGL_CONFIG_ID, &id) == EGL_FALSE) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to get config from context"); - return 0; - } - EGL_CHECK_ERROR - configs = getConfigs(&numConfigs); - glConfig = configs[id]; - free(configs); - return glConfig; - } - - //------------------------------------------------------------------------ - // A helper class for the implementation of selectFBConfig - //------------------------------------------------------------------------ - class GLConfigAttribs - { - public: - GLConfigAttribs(const int* attribs) - { - fields[EGL_CONFIG_CAVEAT] = EGL_NONE; - - for (int i = 0; attribs[2*i] != EGL_NONE; i++) - { - fields[attribs[2*i]] = attribs[2*i+1]; - } - } - - void load(EGLSupport* const glSupport, EGLConfig glConfig) - { - for (auto& f : fields) - { - f.second = EGL_NONE; - glSupport->getGLConfigAttrib(glConfig, f.first, &f.second); - } - } - - bool operator>(GLConfigAttribs& alternative) - { - // Caveats are best avoided, but might be needed for anti-aliasing - if (fields[EGL_CONFIG_CAVEAT] != alternative.fields[EGL_CONFIG_CAVEAT]) - { - if (fields[EGL_CONFIG_CAVEAT] == EGL_SLOW_CONFIG) - { - return false; - } - - if (fields.find(EGL_SAMPLES) != fields.end() && - fields[EGL_SAMPLES] < alternative.fields[EGL_SAMPLES]) - { - return false; - } - } - - for (auto& f : fields) - { - if (f.first != EGL_CONFIG_CAVEAT && - fields[f.first] > alternative.fields[f.first]) - { - return true; - } - } - - return false; - } - - std::map fields; - }; - - ::EGLConfig EGLSupport::selectGLConfig(const int* minAttribs, const int *maxAttribs) - { - EGLConfig *glConfigs; - EGLConfig glConfig = 0; - int config, nConfigs = 0; - - glConfigs = chooseGLConfig(minAttribs, &nConfigs); - - if (!nConfigs) - { - glConfigs = getConfigs(&nConfigs); - } - - if (!nConfigs) - { - return 0; - } - - glConfig = glConfigs[0]; - - if (maxAttribs) - { - GLConfigAttribs maximum(maxAttribs); - GLConfigAttribs best(maxAttribs); - GLConfigAttribs candidate(maxAttribs); - - best.load(this, glConfig); - - for (config = 1; config < nConfigs; config++) - { - candidate.load(this, glConfigs[config]); - - if (candidate > maximum) - { - continue; - } - - if (candidate > best) - { - glConfig = glConfigs[config]; - - best.load(this, glConfig); - } - } - } - - free(glConfigs); - return glConfig; - } - - void EGLSupport::switchMode(void) - { - return switchMode(mOriginalMode.width, - mOriginalMode.height, mOriginalMode.refreshRate); - } - - ::EGLContext EGLSupport::createNewContext(EGLDisplay eglDisplay, - ::EGLConfig glconfig, - ::EGLContext shareList) const - { - EGLint contextAttrs[] = { - EGL_CONTEXT_MAJOR_VERSION, 3, - EGL_CONTEXT_MINOR_VERSION, 2, - EGL_NONE, EGL_NONE, - EGL_NONE - }; - - if (!eglBindAPI(mContextProfile == CONTEXT_ES ? EGL_OPENGL_ES_API : EGL_OPENGL_API)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "eglBindAPI failed"); - } - - if(mContextProfile != CONTEXT_ES) { - contextAttrs[1] = 4; - contextAttrs[3] = 6; - -#ifdef EGL_VERSION_1_5 - contextAttrs[4] = EGL_CONTEXT_OPENGL_PROFILE_MASK; - contextAttrs[5] = EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT; - if(mContextProfile == CONTEXT_COMPATIBILITY) - { - contextAttrs[1] = 3; // MESA 20.2.6 always gives us core if we request 4.x - contextAttrs[3] = 0; - contextAttrs[5] = EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT; - } -#endif - } - - if(!hasEGL15) - { - contextAttrs[2] = EGL_NONE; // skips following attributes - contextAttrs[3] = 0; - } - - ::EGLContext context = (::EGLContext)0; - - // find maximal supported context version - while(!context && (contextAttrs[1] >= 1)) - { - context = eglCreateContext(eglDisplay, glconfig, shareList, contextAttrs); - EGL_CHECK_ERROR - contextAttrs[1] -= contextAttrs[3] == 0; // only decrement if minor == 0 - - if(hasEGL15) - contextAttrs[3] = (contextAttrs[3] - 1 + 7) % 7; // decrement: -1 -> 6 - } - - if (!context) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to create EGL context"); - return 0; - } - - return context; - } - - void EGLSupport::start() - { - LogManager::getSingleton().logMessage( - "******************************\n" - "*** Starting EGL Subsystem ***\n" - "******************************"); - initialiseExtensions(); - } - - void EGLSupport::stop() - { - eglTerminate(mGLDisplay); - EGL_CHECK_ERROR - } - - void EGLSupport::initialiseExtensions() { - assert (mGLDisplay); - - const char* propStr = eglQueryString(mGLDisplay, EGL_VENDOR); - LogManager::getSingleton().stream() << "EGL_VENDOR = " << propStr; - - propStr = eglQueryString(mGLDisplay, EGL_VERSION); - LogManager::getSingleton().stream() << "EGL_VERSION = " << propStr; - - hasEGL15 = String(propStr).find("1.5") != String::npos; - - StringStream ext; - - // client extensions - propStr = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS); - if(propStr) // NULL = failure case - ext << propStr << " "; - - // display extension - propStr = eglQueryString(mGLDisplay, EGL_EXTENSIONS); - ext << propStr; - - LogManager::getSingleton().stream() << "EGL_EXTENSIONS = " << ext.str(); - - String instr; - while(ext >> instr) - { - extensionList.insert(instr); - } - } - - void EGLSupport::setGLDisplay( EGLDisplay val ) - { - mGLDisplay = val; - } - - GLPBuffer* EGLSupport::createPBuffer( PixelComponentType format, size_t width, size_t height ) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - return nullptr; -#else - return new EGLPBuffer(this, format, width, height); -#endif - } -} diff --git a/RenderSystems/GLSupport/src/EGL/OgreEGLWindow.cpp b/RenderSystems/GLSupport/src/EGL/OgreEGLWindow.cpp deleted file mode 100644 index 0c5d9323e51..00000000000 --- a/RenderSystems/GLSupport/src/EGL/OgreEGLWindow.cpp +++ /dev/null @@ -1,278 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2008 Renato Araujo Oliveira Filho -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ---------------------------------------------------------------------------*/ - -#include "OgreRoot.h" -#include "OgreException.h" -#include "OgreStringConverter.h" - -#include "OgreGLRenderSystemCommon.h" - -#include "OgreEGLSupport.h" -#include "OgreEGLWindow.h" -#include "OgreEGLContext.h" - -#include - -namespace Ogre { - EGLWindow::EGLWindow(EGLSupport *glsupport) - : GLWindow(), mGLSupport(glsupport), - mWindow(0), - mNativeDisplay(EGL_DEFAULT_DISPLAY), - mEglDisplay(EGL_NO_DISPLAY), - mEglConfig(0), - mEglSurface(0) - { - mActive = true;//todo - } - - EGLWindow::~EGLWindow() - { - destroy(); - - if (mContext) - { - delete mContext; - } - - mContext = 0; - } - - void EGLWindow::destroy(void) - { - if (mClosed) - { - return; - } - - mClosed = true; - mActive = false; - - if (mIsFullScreen) - { - mGLSupport->switchMode(); - switchFullScreen(false); - } - } - - void EGLWindow::setFullscreen(bool fullscreen, uint width, uint height) - { - short frequency = 0; - - if (mClosed || !mIsTopLevel) - { - return; - } - - if (fullscreen == mIsFullScreen && width == mWidth && height == mHeight) - { - return; - } - if (fullscreen) - { - mGLSupport->switchMode(width, height, frequency); - } - else - { - mGLSupport->switchMode(); - } - - if (mIsFullScreen != fullscreen) - { - switchFullScreen(fullscreen); - } - - if (!mIsFullScreen) - { - resize(width, height); - reposition(mLeft, mTop); - } - } - - void EGLWindow::swapBuffers() - { - if (mClosed || mIsExternalGLControl) - { - return; - } - mContext->setCurrent(); - if (eglSwapBuffers(mEglDisplay, mEglSurface) == EGL_FALSE) - { - EGL_CHECK_ERROR - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to SwapBuffers"); - } - } - - void EGLWindow::getCustomAttribute( const String& name, void* pData ) - { - if (name == "DISPLAY") - { - *static_cast(pData) = mEglDisplay; - return; - } - else if (name == "GLCONTEXT") - { - *static_cast(pData) = mContext; - return; - } - else if (name == "WINDOW") - { - *static_cast(pData) = mWindow; - return; - } - } - - PixelFormat EGLWindow::suggestPixelFormat() const - { - return mGLSupport->getContextProfile() == GLNativeSupport::CONTEXT_ES ? PF_BYTE_RGBA : PF_BYTE_RGB; - } - - void EGLWindow::create(const String& name, unsigned int width, unsigned int height, bool fullScreen, - const NameValuePairList* miscParams) - { -#if OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN - int samples = 0; - - if (miscParams) - { - NameValuePairList::const_iterator opt; - if ((opt = miscParams->find("FSAA")) != miscParams->end()) - { - samples = StringConverter::parseUnsignedInt(opt->second); - } - } - - int minAttribs[] = { - EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, - EGL_BLUE_SIZE, 5, - EGL_GREEN_SIZE, 6, - EGL_RED_SIZE, 5, - EGL_DEPTH_SIZE, 16, - EGL_NONE - }; - - int maxAttribs[] = { - EGL_RED_SIZE, 8, - EGL_GREEN_SIZE, 8, - EGL_BLUE_SIZE, 8, - EGL_DEPTH_SIZE, 24, - EGL_ALPHA_SIZE, 8, - EGL_STENCIL_SIZE, 8, - EGL_SAMPLE_BUFFERS, 1, - EGL_SAMPLES, samples, - EGL_NONE - }; - - mEglConfig = mGLSupport->selectGLConfig(minAttribs, maxAttribs); - mEglDisplay = mGLSupport->getGLDisplay(); - - int pbufferAttribs[] = { - EGL_WIDTH, int(width), - EGL_HEIGHT, int(height), - EGL_NONE, - }; - - mEglSurface = eglCreatePbufferSurface(mEglDisplay, mEglConfig, pbufferAttribs); - mContext = createEGLContext(NULL); - mIsExternalGLControl = true; // dont want swapBuffers - mName = name; - mWidth = width; - mHeight = height; - - finaliseWindow(); -#endif - } - - ::EGLSurface EGLWindow::createSurfaceFromWindow(::EGLDisplay display, - NativeWindowType win) - { - ::EGLSurface surface; - -#if OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN - int* gamma_attribs = NULL; -#else - int gamma_attribs[] = {EGL_GL_COLORSPACE_KHR, EGL_GL_COLORSPACE_SRGB_KHR, EGL_NONE}; -#endif - mHwGamma = mHwGamma && mGLSupport->checkExtension("EGL_KHR_gl_colorspace"); - - surface = eglCreateWindowSurface(display, mEglConfig, (EGLNativeWindowType)win, mHwGamma ? gamma_attribs : NULL); - EGL_CHECK_ERROR - - if (surface == EGL_NO_SURFACE) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Fail to create EGLSurface based on NativeWindowType"); - } - return surface; - } - - void EGLWindow::setVSyncEnabled(bool vsync) { - mVSync = vsync; - // we need to make our context current to set vsync - // store previous context to restore when finished. - ::EGLSurface oldRead = eglGetCurrentSurface(EGL_READ); - EGL_CHECK_ERROR - ::EGLSurface oldDraw = eglGetCurrentSurface(EGL_DRAW); - EGL_CHECK_ERROR - ::EGLContext oldContext = eglGetCurrentContext(); - EGL_CHECK_ERROR - ::EGLDisplay dpy = mGLSupport->getGLDisplay(); - - mContext->setCurrent(); - - if (! mIsExternalGLControl ) - { - eglSwapInterval(dpy, vsync ? mVSyncInterval : 0); - EGL_CHECK_ERROR - } - - mContext->endCurrent(); - - eglMakeCurrent (dpy, oldDraw, oldRead, oldContext); - EGL_CHECK_ERROR - } - - void EGLWindow::finaliseWindow() - { - // query selected config - int Rsz, Gsz, Bsz, Asz, fsaa; - mGLSupport->getGLConfigAttrib(mEglConfig, EGL_RED_SIZE, &Rsz); - mGLSupport->getGLConfigAttrib(mEglConfig, EGL_BLUE_SIZE, &Gsz); - mGLSupport->getGLConfigAttrib(mEglConfig, EGL_GREEN_SIZE, &Bsz); - mGLSupport->getGLConfigAttrib(mEglConfig, EGL_ALPHA_SIZE, &Asz); - mGLSupport->getGLConfigAttrib(mEglConfig, EGL_SAMPLES, &fsaa); - - LogManager::getSingleton().logMessage( - StringUtil::format("EGLWindow: colourBufferSize=%d/%d/%d/%d gamma=%d FSAA=%d", Rsz, Bsz, Gsz, - Asz, mHwGamma, fsaa)); - - mActive = true; - mVisible = true; - mFSAA = fsaa; - mClosed = false; - } -} diff --git a/RenderSystems/GLSupport/src/EGL/WIN32/OgreWin32EGLSupport.cpp b/RenderSystems/GLSupport/src/EGL/WIN32/OgreWin32EGLSupport.cpp deleted file mode 100644 index e5c1acc7c75..00000000000 --- a/RenderSystems/GLSupport/src/EGL/WIN32/OgreWin32EGLSupport.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2008 Renato Araujo Oliveira Filho -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreRoot.h" - -#include "OgreWin32EGLSupport.h" -#include "OgreWin32EGLWindow.h" - -#include "OgreGLUtil.h" - -namespace Ogre { - GLNativeSupport* getGLSupport(int profile) - { - return new Win32EGLSupport(profile); - } - - Win32EGLSupport::Win32EGLSupport(int profile) - : EGLSupport(profile) - { - //RECT windowRect; - //GetClientRect(mNativeDisplay, &windowRect); - mNativeDisplay = getNativeDisplay(); - mGLDisplay = getGLDisplay(); - - // Video mode possibilities - DEVMODE DevMode; - DevMode.dmSize = sizeof(DEVMODE); - for (DWORD i = 0; EnumDisplaySettings(NULL, i, &DevMode); ++i) - { - if (DevMode.dmBitsPerPel < 16) - continue; - - mCurrentMode.width = DevMode.dmPelsWidth; - mCurrentMode.height = DevMode.dmPelsHeight; - mCurrentMode.refreshRate = 0; - mOriginalMode = mCurrentMode; - mVideoModes.push_back(mCurrentMode); - } - - EGLConfig *glConfigs; - int config, nConfigs = 0; - - EGLint const attrib_list[] = { - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - EGL_BUFFER_SIZE, 32, - EGL_DEPTH_SIZE, 24, - EGL_STENCIL_SIZE, 8, - EGL_NONE - }; - - glConfigs = chooseGLConfig(attrib_list, &nConfigs); - - for (config = 0; config < nConfigs; config++) - { - int caveat, samples; - - getGLConfigAttrib(glConfigs[config], EGL_CONFIG_CAVEAT, &caveat); - - if (caveat != EGL_SLOW_CONFIG) - { - getGLConfigAttrib(glConfigs[config], EGL_SAMPLES, &samples); - mFSAALevels.push_back(short(samples)); - } - } - - free(glConfigs); - } - - Win32EGLSupport::~Win32EGLSupport() - { - - } - - //Removed createEGLWindow because it was easier to call new Win32EGLWindow - //directly to get the native version. -// EGLWindow* Win32EGLSupport::createEGLWindow( EGLSupport * support ) -// { -// return new Win32EGLWindow(support); -// } - - //Moved to native from EGLSupport - RenderWindow* Win32EGLSupport::newWindow(const String &name, - unsigned int width, unsigned int height, - bool fullScreen, - const NameValuePairList *miscParams) - { -// EGLWindow* window = createEGLWindow(this); - - Win32EGLWindow* window = new Win32EGLWindow(this); - window->create(name, width, height, fullScreen, miscParams); - - return window; - } - - //Moved to native from EGLSupport - NativeDisplayType Win32EGLSupport::getNativeDisplay() - { - return EGL_DEFAULT_DISPLAY; // TODO - } - - //Win32EGLSupport::getGLDisplay sets up the native variable - //then calls EGLSupport::getGLDisplay - EGLDisplay Win32EGLSupport::getGLDisplay() - { - if (!mGLDisplay) - { - mNativeDisplay = getNativeDisplay(); - return EGLSupport::getGLDisplay(); - } - return mGLDisplay; - } - - -} diff --git a/RenderSystems/GLSupport/src/EGL/WIN32/OgreWin32EGLWindow.cpp b/RenderSystems/GLSupport/src/EGL/WIN32/OgreWin32EGLWindow.cpp deleted file mode 100644 index fde8548886d..00000000000 --- a/RenderSystems/GLSupport/src/EGL/WIN32/OgreWin32EGLWindow.cpp +++ /dev/null @@ -1,451 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2008 Renato Araujo Oliveira Filho -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ---------------------------------------------------------------------------*/ - -#include "OgreRoot.h" -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" - -#include "OgreViewport.h" - -#include "OgreWin32EGLSupport.h" -#include "OgreWin32EGLWindow.h" - -#include -#include -#include - - -namespace Ogre { - Win32EGLWindow::Win32EGLWindow(Win32EGLSupport *glsupport) - : EGLWindow(glsupport) - { - mGLSupport = glsupport; - mNativeDisplay = glsupport->getNativeDisplay(); - } - - void Win32EGLWindow::createNativeWindow( int &left, int &top, uint &width, uint &height, String &title ) - { - // destroy current window, if any - if (mWindow) - destroy(); - - HINSTANCE hInst = NULL; - static const TCHAR staticVar; - GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, &staticVar, &hInst); - - mWindow = 0; - mClosed = false; - mColourDepth = mIsFullScreen? 32 : GetDeviceCaps(GetDC(0), BITSPIXEL); - HWND parent = 0; - bool vsync = false; - String border; - bool outerSize = false; - bool hwGamma = false; - int monitorIndex = -1; - HMONITOR hMonitor = NULL; - - - if (!mIsExternal) - { - DWORD dwStyle = WS_VISIBLE | WS_CLIPCHILDREN; - DWORD dwStyleEx = 0; - MONITORINFOEX monitorInfoEx; - RECT rc; - - // If we didn't specified the adapter index, or if it didn't find it - if (hMonitor == NULL) - { - POINT windowAnchorPoint; - - // Fill in anchor point. - windowAnchorPoint.x = left; - windowAnchorPoint.y = top; - - - // Get the nearest monitor to this window. - hMonitor = MonitorFromPoint(windowAnchorPoint, MONITOR_DEFAULTTONEAREST); - } - - // Get the target monitor info - memset(&monitorInfoEx, 0, sizeof(MONITORINFOEX)); - monitorInfoEx.cbSize = sizeof(MONITORINFOEX); - GetMonitorInfo(hMonitor, &monitorInfoEx); - - //size_t devNameLen = strlen(monitorInfoEx.szDevice); - //mDeviceName = new char[devNameLen + 1]; - - //strcpy(mDeviceName, monitorInfoEx.szDevice); - - - // No specified top left -> Center the window in the middle of the monitor - if (left == -1 || top == -1) - { - int screenw = monitorInfoEx.rcMonitor.right - monitorInfoEx.rcMonitor.left; - int screenh = monitorInfoEx.rcMonitor.bottom - monitorInfoEx.rcMonitor.top; - - SetRect(&rc, 0, 0, width, height); - AdjustWindowRect(&rc, dwStyle, false); - - // clamp window dimensions to screen size - int outerw = (rc.right-rc.left < screenw)? rc.right-rc.left : screenw; - int outerh = (rc.bottom-rc.top < screenh)? rc.bottom-rc.top : screenh; - - if (left == -1) - left = monitorInfoEx.rcMonitor.left + (screenw - outerw) / 2; - else if (monitorIndex != -1) - left += monitorInfoEx.rcMonitor.left; - - if (top == -1) - top = monitorInfoEx.rcMonitor.top + (screenh - outerh) / 2; - else if (monitorIndex != -1) - top += monitorInfoEx.rcMonitor.top; - } - else if (monitorIndex != -1) - { - left += monitorInfoEx.rcMonitor.left; - top += monitorInfoEx.rcMonitor.top; - } - - mWidth = width; - mHeight = height; - mTop = top; - mLeft = left; - - if (mIsFullScreen) - { - dwStyle |= WS_POPUP; - dwStyleEx |= WS_EX_TOPMOST; - mTop = monitorInfoEx.rcMonitor.top; - mLeft = monitorInfoEx.rcMonitor.left; - } - else - { - if (parent) - { - dwStyle |= WS_CHILD; - } - else - { - if (border == "none") - dwStyle |= WS_POPUP; - else if (border == "fixed") - dwStyle |= WS_OVERLAPPED | WS_BORDER | WS_CAPTION | - WS_SYSMENU | WS_MINIMIZEBOX; - else - dwStyle |= WS_OVERLAPPEDWINDOW; - } - - int screenw = GetSystemMetrics(SM_CXSCREEN); - int screenh = GetSystemMetrics(SM_CYSCREEN); - - if (!outerSize) - { - // Calculate window dimensions required - // to get the requested client area - SetRect(&rc, 0, 0, mWidth, mHeight); - AdjustWindowRect(&rc, dwStyle, false); - mWidth = rc.right - rc.left; - mHeight = rc.bottom - rc.top; - - // Clamp window rect to the nearest display monitor. - if (mLeft < monitorInfoEx.rcMonitor.left) - mLeft = monitorInfoEx.rcMonitor.left; - - if (mTop < monitorInfoEx.rcMonitor.top) - mTop = monitorInfoEx.rcMonitor.top; - - if ((int)mWidth > monitorInfoEx.rcMonitor.right - mLeft) - mWidth = monitorInfoEx.rcMonitor.right - mLeft; - - if ((int)mHeight > monitorInfoEx.rcMonitor.bottom - mTop) - mHeight = monitorInfoEx.rcMonitor.bottom - mTop; - } - } - - // register class and create window - WNDCLASS wc = { CS_OWNDC, DefWindowProc, 0, 0, hInst, - LoadIcon(NULL, IDI_APPLICATION), LoadCursor(NULL, IDC_ARROW), - (HBRUSH)GetStockObject(BLACK_BRUSH), NULL, "OgreGLES2Window" }; - RegisterClass(&wc); - - if (mIsFullScreen) - { - DEVMODE displayDeviceMode; - - memset(&displayDeviceMode, 0, sizeof(displayDeviceMode)); - displayDeviceMode.dmSize = sizeof(DEVMODE); - displayDeviceMode.dmBitsPerPel = mColourDepth; - displayDeviceMode.dmPelsWidth = mWidth; - displayDeviceMode.dmPelsHeight = mHeight; - displayDeviceMode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; -/* - if (mDisplayFrequency) - { - displayDeviceMode.dmDisplayFrequency = mDisplayFrequency; - displayDeviceMode.dmFields |= DM_DISPLAYFREQUENCY; - if (ChangeDisplaySettingsEx(mDeviceName, &displayDeviceMode, NULL, CDS_FULLSCREEN | CDS_TEST, NULL) != DISP_CHANGE_SUCCESSFUL) - { - LogManager::getSingleton().logMessage(LML_NORMAL, "ChangeDisplaySettings with user display frequency failed"); - displayDeviceMode.dmFields ^= DM_DISPLAYFREQUENCY; - } - } - if (ChangeDisplaySettingsEx(mDeviceName, &displayDeviceMode, NULL, CDS_FULLSCREEN, NULL) != DISP_CHANGE_SUCCESSFUL) - LogManager::getSingleton().logMessage(LML_CRITICAL, "ChangeDisplaySettings failed"); -*/ - - } - // Pass pointer to self as WM_CREATE parameter - mWindow = CreateWindowEx(dwStyleEx, "OgreGLES2Window", title.c_str(), - dwStyle, mLeft, mTop, mWidth, mHeight, parent, 0, hInst, this); - - LogManager::getSingleton().stream() - << "Created Win32Window '" - << mName << "' : " << mWidth << "x" << mHeight - << ", " << mColourDepth << "bpp"; - - } - - RECT rc; - // top and left represent outer window position - GetWindowRect(mWindow, &rc); - mTop = rc.top; - mLeft = rc.left; - // width and height represent drawable area only - GetClientRect(mWindow, &rc); - mWidth = rc.right; - mHeight = rc.bottom; - - mNativeDisplay = GetDC(mWindow); - mEglDisplay = eglGetDisplay(mNativeDisplay); - - // fallback for some emulations - if (mEglDisplay == EGL_NO_DISPLAY) - { - mEglDisplay = eglGetDisplay( EGL_DEFAULT_DISPLAY ); - } - - eglInitialize(mEglDisplay, NULL, NULL); - - eglBindAPI(EGL_OPENGL_ES_API); - - mGLSupport->setGLDisplay(mEglDisplay); - mEglSurface = createSurfaceFromWindow(mEglDisplay, mWindow); - - - } - - void Win32EGLWindow::resize( unsigned int width, unsigned int height ) - { - // Case window resized. - if (width != mWidth || height != mHeight) - { - mWidth = rc.right - rc.left; - mHeight = rc.bottom - rc.top; - - // Notify viewports of resize - ViewportList::iterator it = mViewportList.begin(); - while( it != mViewportList.end() ) - (*it++).second->_updateDimensions(); - } - } - - void Win32EGLWindow::windowMovedOrResized() - { - if (!mWindow || IsIconic(mWindow)) - return; - - RECT rc; - BOOL result; - - // Update top left parameters - result = GetWindowRect(mWindow, &rc); - if (result == FALSE) - { - mTop = 0; - mLeft = 0; - mWidth = 0; - mHeight = 0; - return; - } - - mTop = rc.top; - mLeft = rc.left; - - // width and height represent drawable area only - result = GetClientRect(mWindow, &rc); - if (result == FALSE) - { - mTop = 0; - mLeft = 0; - mWidth = 0; - mHeight = 0; - return; - } - unsigned int width = rc.right - rc.left; - unsigned int height = rc.bottom - rc.top; - - resize(width, height); - } - - void Win32EGLWindow::create(const String& name, uint width, uint height, - bool fullScreen, const NameValuePairList *miscParams) - { - String title = name; - uint samples = 0; - int gamma; - short frequency = 0; - bool vsync = false; - ::EGLContext eglContext = 0; - int left = 0; - int top = 0; - - mIsFullScreen = fullScreen; - - if (miscParams) - { - NameValuePairList::const_iterator opt; - NameValuePairList::const_iterator end = miscParams->end(); - - if ((opt = miscParams->find("currentGLContext")) != end && - StringConverter::parseBool(opt->second)) - { - eglContext = eglGetCurrentContext(); - if (!eglContext) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "currentGLContext was specified with no current GL context", - "EGLWindow::create"); - } - - mEglDisplay = eglGetCurrentDisplay(); - } - - // Note: Some platforms support AA inside ordinary windows - if ((opt = miscParams->find("FSAA")) != end) - { - samples = StringConverter::parseUnsignedInt(opt->second); - } - - if ((opt = miscParams->find("displayFrequency")) != end) - { - frequency = (short)StringConverter::parseInt(opt->second); - } - - if ((opt = miscParams->find("vsync")) != end) - { - vsync = StringConverter::parseBool(opt->second); - } - - if ((opt = miscParams->find("gamma")) != end) - { - gamma = StringConverter::parseBool(opt->second); - } - - if ((opt = miscParams->find("left")) != end) - { - left = StringConverter::parseInt(opt->second); - } - - if ((opt = miscParams->find("top")) != end) - { - top = StringConverter::parseInt(opt->second); - } - - if ((opt = miscParams->find("title")) != end) - { - title = opt->second; - } - - if ((opt = miscParams->find("externalGLControl")) != end) - { - mIsExternalGLControl = StringConverter::parseBool(opt->second); - } - } - - if (!mEglConfig && eglContext) - { - mEglConfig = mGLSupport->getGLConfigFromContext(eglContext); - - if (!mEglConfig) - { - // This should never happen. - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Unexpected failure to determine a EGLFBConfig", - "EGLWindow::create"); - } - } - - if (!mEglConfig) - { - int minAttribs[] = { - EGL_LEVEL, 0, - EGL_DEPTH_SIZE, 16, - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - EGL_NATIVE_RENDERABLE, EGL_FALSE, - EGL_DEPTH_SIZE, EGL_DONT_CARE, - EGL_NONE - }; - - int maxAttribs[] = { - EGL_SAMPLES, samples, - EGL_STENCIL_SIZE, INT_MAX, - EGL_NONE - }; - - mEglConfig = mGLSupport->selectGLConfig(minAttribs, maxAttribs); - mHwGamma = false; - } - - if (!mIsTopLevel) - { - mIsFullScreen = false; - left = top = 0; - } - - if (mIsFullScreen) - { - mGLSupport->switchMode (width, height, frequency); - } - - createNativeWindow(left, top, width, height, title); - - mContext = createEGLContext(eglContext); - mContext->setCurrent(); - - mName = name; - mWidth = width; - mHeight = height; - mLeft = left; - mTop = top; - - finaliseWindow(); - } - -} diff --git a/RenderSystems/GLSupport/src/EGL/X11/OgreX11EGLSupport.cpp b/RenderSystems/GLSupport/src/EGL/X11/OgreX11EGLSupport.cpp deleted file mode 100644 index 780dcb81918..00000000000 --- a/RenderSystems/GLSupport/src/EGL/X11/OgreX11EGLSupport.cpp +++ /dev/null @@ -1,192 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2008 Renato Araujo Oliveira Filho -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreRoot.h" - -#include "OgreX11EGLSupport.h" -#include "OgreX11EGLWindow.h" -#include "OgreX11.h" - -#include "OgreGLUtil.h" - -namespace Ogre { - GLNativeSupport* getGLSupport(int profile) - { - return new X11EGLSupport(profile); - } - - X11EGLSupport::X11EGLSupport(int profile) : EGLSupport(profile) - { - // A connection that might be shared with the application for GL rendering: - mGLDisplay = getGLDisplay(); - - // A connection that is NOT shared to enable independent event processing: - mNativeDisplay = getNativeDisplay(); - - - if(mNativeDisplay == EGL_DEFAULT_DISPLAY) - { - // fake video mode - mCurrentMode.width = 0; - mCurrentMode.height = 0; - mCurrentMode.refreshRate = 0; - mVideoModes.push_back(mCurrentMode); - } - else - { - getXVideoModes(mNativeDisplay, mCurrentMode, mVideoModes); - } - - if(mVideoModes.empty()) // none of the above worked - { - mCurrentMode.width = DisplayWidth(mNativeDisplay, DefaultScreen(mNativeDisplay)); - mCurrentMode.height = DisplayHeight(mNativeDisplay, DefaultScreen(mNativeDisplay)); - mCurrentMode.refreshRate = 0; - mVideoModes.push_back(mCurrentMode); - } - - mOriginalMode = mCurrentMode; - - EGLConfig *glConfigs; - int config, nConfigs = 0; - - glConfigs = chooseGLConfig(NULL, &nConfigs); - - for (config = 0; config < nConfigs; config++) - { - int caveat, samples; - - getGLConfigAttrib(glConfigs[config], EGL_CONFIG_CAVEAT, &caveat); - - if (caveat != EGL_SLOW_CONFIG) - { - getGLConfigAttrib(glConfigs[config], EGL_SAMPLES, &samples); - mFSAALevels.push_back(samples); - } - } - - free(glConfigs); - } - - X11EGLSupport::~X11EGLSupport() - { - if (mNativeDisplay) - { - XCloseDisplay((Display*)mNativeDisplay); - } - - if (mGLDisplay) - { - eglTerminate(mGLDisplay); - } - } - - NativeDisplayType X11EGLSupport::getNativeDisplay() - { - if (!mNativeDisplay) - { - mNativeDisplay = getXDisplay(NULL, mAtomDeleteWindow, mAtomFullScreen, mAtomState); - - if (mNativeDisplay == EGL_DEFAULT_DISPLAY) - { - LogManager::getSingleton().logWarning("Couldn't open X display"); - return mNativeDisplay; - } - } - - return mNativeDisplay; - } - - XVisualInfo *X11EGLSupport::getVisualFromFBConfig(::EGLConfig glConfig) - { - XVisualInfo *vi, tmp; - int vid, n; - ::EGLDisplay glDisplay; - - glDisplay = getGLDisplay(); - mNativeDisplay = getNativeDisplay(); - - if (eglGetConfigAttrib(glDisplay, glConfig, EGL_NATIVE_VISUAL_ID, &vid) == EGL_FALSE) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to get VISUAL_ID from glConfig"); - return 0; - } - EGL_CHECK_ERROR - - if (vid == 0) - { - const int screen_number = DefaultScreen(mNativeDisplay); - Visual *v = DefaultVisual((Display*)mNativeDisplay, screen_number); - vid = XVisualIDFromVisual(v); - } - - tmp.visualid = vid; - vi = 0; - vi = XGetVisualInfo((Display*)mNativeDisplay, - VisualIDMask, - &tmp, &n); - if (vi == 0) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to get X11 VISUAL"); - return 0; - } - - return vi; - } - - RenderWindow* X11EGLSupport::newWindow(const String &name, - unsigned int width, unsigned int height, - bool fullScreen, - const NameValuePairList *miscParams) - { - EGLWindow* window = - mNativeDisplay == EGL_DEFAULT_DISPLAY ? new EGLWindow(this) : new X11EGLWindow(this); - window->create(name, width, height, fullScreen, miscParams); - - return window; - } - - //X11EGLSupport::getGLDisplay sets up the native variable - //then calls EGLSupport::getGLDisplay - EGLDisplay X11EGLSupport::getGLDisplay() - { - if (!mGLDisplay) - { - if(!mNativeDisplay) - mNativeDisplay = getNativeDisplay(); - return EGLSupport::getGLDisplay(); - } - return mGLDisplay; - } - -} - diff --git a/RenderSystems/GLSupport/src/EGL/X11/OgreX11EGLWindow.cpp b/RenderSystems/GLSupport/src/EGL/X11/OgreX11EGLWindow.cpp deleted file mode 100644 index 5238cab1e1e..00000000000 --- a/RenderSystems/GLSupport/src/EGL/X11/OgreX11EGLWindow.cpp +++ /dev/null @@ -1,376 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2008 Renato Araujo Oliveira Filho -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ---------------------------------------------------------------------------*/ - -#include "OgreRoot.h" -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreViewport.h" - -#include "OgreX11EGLSupport.h" -#include "OgreX11EGLWindow.h" -#include "OgreX11.h" - -namespace Ogre { - X11EGLWindow::X11EGLWindow(X11EGLSupport *glsupport) - : EGLWindow(glsupport) - //, mParentWindow(glsupport) todo - { - mGLSupport = glsupport; - mNativeDisplay = glsupport->getNativeDisplay(); - } - - X11EGLWindow::~X11EGLWindow() - { - mNativeDisplay = mGLSupport->getNativeDisplay(); - - if (mWindow && mIsTopLevel) - { - destroyXWindow(mNativeDisplay, mWindow); - } - - mWindow = 0; - } - - void X11EGLWindow::getCustomAttribute( const String& name, void* pData ) - { - EGLWindow::getCustomAttribute(name, pData); - if (name == "ATOM") - { - *static_cast< ::Atom* >(pData) = mGLSupport->mAtomDeleteWindow; - return; - } - else if (name == "XDISPLAY") - { - *static_cast(pData) = mGLSupport->getNativeDisplay(); - return; - } - else if (name == "XWINDOW") - { - *static_cast(pData) = mWindow; - return; - } - - } - - void X11EGLWindow::getLeftAndTopFromNativeWindow( int & left, int & top, uint width, uint height ) - { - left = DisplayWidth((Display*)mNativeDisplay, DefaultScreen(mNativeDisplay))/2 - width/2; - top = DisplayHeight((Display*)mNativeDisplay, DefaultScreen(mNativeDisplay))/2 - height/2; - } - - void X11EGLWindow::initNativeCreatedWindow(const NameValuePairList *miscParams) - { - mNativeDisplay = mGLSupport->getNativeDisplay(); - mParentWindow = DefaultRootWindow((Display*)mNativeDisplay); - - if (miscParams) - { - NameValuePairList::const_iterator opt; - NameValuePairList::const_iterator end = miscParams->end(); - - if ((opt = miscParams->find("parentWindowHandle")) != end || - (opt = miscParams->find("externalWindowHandle")) != end) - { - StringVector tokens = StringUtil::split(opt->second, " :"); - - if (tokens.size() >= 3) - { - // deprecated display:screen:xid:visualinfo format - mParentWindow = (Window)StringConverter::parseSizeT(tokens[2]); - } - else - { - // xid format - mParentWindow = (Window)StringConverter::parseSizeT(tokens[0]); - } - } - } - - validateParentWindow(mNativeDisplay, mParentWindow); - - mIsTopLevel = (!mIsExternal && mParentWindow == DefaultRootWindow((Display*)mNativeDisplay)); - - } - - void X11EGLWindow::createNativeWindow( int &left, int &top, uint &width, uint &height, String &title ) - { - mEglDisplay = mGLSupport->getGLDisplay();//todo - XVisualInfo *visualInfo = mGLSupport->getVisualFromFBConfig(mEglConfig); - - // Create window on server - mWindow = createXWindow(mNativeDisplay, mParentWindow, visualInfo, left, top, width, height, - mGLSupport->mAtomFullScreen, mIsFullScreen); - - if (mIsTopLevel) - { - finaliseTopLevel(mNativeDisplay, mWindow, left, top, width, height, title, mGLSupport->mAtomDeleteWindow); - } - - mEglSurface = createSurfaceFromWindow(mGLSupport->getGLDisplay(), mWindow); - - XMapWindow((Display*)mNativeDisplay, (Window)mWindow); - - if (mIsFullScreen) - { - switchFullScreen(true); - } - - XFlush((Display*)mNativeDisplay); - } - - void X11EGLWindow::setFullscreen( bool fullscreen, uint width, uint height ) - { - if (mIsFullScreen != fullscreen && mGLSupport->mAtomFullScreen == None) - { - // Without WM support it is best to give up. - LogManager::getSingleton().logMessage("EGLWindow::switchFullScreen: Your WM has no fullscreen support"); - return; - } - EGLWindow::setFullscreen(fullscreen, width, height); - } - - void X11EGLWindow::reposition( int left, int top ) - { - if (mClosed || ! mIsTopLevel) - { - return; - } - - XMoveWindow((Display*)mGLSupport->getNativeDisplay(), (Window)mWindow, left, top); - } - - void X11EGLWindow::resize(uint width, uint height) - { - if (mClosed) - { - return; - } - - if (mWidth == width && mHeight == height) - { - return; - } - - if (width != 0 && height != 0) - { - if (!mIsTopLevel) - { - XResizeWindow(mGLSupport->getNativeDisplay(), mWindow, width, height); - XFlush(mGLSupport->getNativeDisplay()); - } - - mWidth = width; - mHeight = height; - - for (auto & it : mViewportList) - it.second->_updateDimensions(); - } - } - - void X11EGLWindow::windowMovedOrResized() - { - if (mClosed || !mWindow) - return; - - uint width, height; - queryRect(mNativeDisplay, mWindow, mLeft, mTop, width, height, mIsTopLevel && !mIsFullScreen); - resize(width, height); - } - void X11EGLWindow::switchFullScreen(bool fullscreen) - { - if (mGLSupport->mAtomFullScreen != None) - { - XClientMessageEvent xMessage; - - xMessage.type = ClientMessage; - xMessage.serial = 0; - xMessage.send_event = True; - xMessage.window = (Window)mWindow; - xMessage.message_type = mGLSupport->mAtomState; - xMessage.format = 32; - xMessage.data.l[0] = (fullscreen ? 1 : 0); - xMessage.data.l[1] = mGLSupport->mAtomFullScreen; - xMessage.data.l[2] = 0; - - XSendEvent((Display*)mNativeDisplay, DefaultRootWindow((Display*)mNativeDisplay), False, - SubstructureRedirectMask | SubstructureNotifyMask, - (XEvent*)&xMessage); - - mIsFullScreen = fullscreen; - } - } - - - //Moved EGLWindow::create to native source because it has native calls in it - void X11EGLWindow::create(const String& name, uint width, uint height, - bool fullScreen, const NameValuePairList *miscParams) - { - String title = name; - int samples = 0; - short frequency = 0; - bool vsync = false; - ::EGLContext eglContext = NULL; - int left = 0; - int top = 0; - - unsigned int vsyncInterval = 1; - - mNativeDisplay = mGLSupport->getNativeDisplay(); - getLeftAndTopFromNativeWindow(left, top, width, height); - - mIsFullScreen = fullScreen; - - if (miscParams) - { - NameValuePairList::const_iterator opt; - NameValuePairList::const_iterator end = miscParams->end(); - - if ((opt = miscParams->find("currentGLContext")) != end && - StringConverter::parseBool(opt->second)) - { - eglContext = eglGetCurrentContext(); - EGL_CHECK_ERROR - if (!eglContext) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "currentGLContext was specified with no current GL context", - "EGLWindow::create"); - } - - mEglDisplay = eglGetCurrentDisplay(); - EGL_CHECK_ERROR - } - - // Note: Some platforms support AA inside ordinary windows - if ((opt = miscParams->find("FSAA")) != end) - { - samples = StringConverter::parseUnsignedInt(opt->second); - } - - if ((opt = miscParams->find("displayFrequency")) != end) - { - frequency = (short)StringConverter::parseInt(opt->second); - } - - if ((opt = miscParams->find("vsync")) != end) - { - vsync = StringConverter::parseBool(opt->second); - } - - if((opt = miscParams->find("vsyncInterval")) != end) - vsyncInterval = StringConverter::parseUnsignedInt(opt->second); - - if ((opt = miscParams->find("gamma")) != end) - { - mHwGamma = StringConverter::parseBool(opt->second); - } - - if ((opt = miscParams->find("left")) != end) - { - left = StringConverter::parseInt(opt->second); - } - - if ((opt = miscParams->find("top")) != end) - { - top = StringConverter::parseInt(opt->second); - } - - if ((opt = miscParams->find("title")) != end) - { - title = opt->second; - } - - if ((opt = miscParams->find("externalGLControl")) != end) - { - mIsExternalGLControl = StringConverter::parseBool(opt->second); - } - } - - initNativeCreatedWindow(miscParams); - - if (!mEglConfig) - { - int minAttribs[] = { - EGL_RED_SIZE, 5, - EGL_GREEN_SIZE, 6, - EGL_BLUE_SIZE, 5, - EGL_DEPTH_SIZE, 16, - EGL_SAMPLES, 0, - EGL_ALPHA_SIZE, EGL_DONT_CARE, - EGL_STENCIL_SIZE, EGL_DONT_CARE, - EGL_SAMPLE_BUFFERS, 0, - EGL_NONE - }; - - int maxAttribs[] = { - EGL_RED_SIZE, 8, - EGL_GREEN_SIZE, 8, - EGL_BLUE_SIZE, 8, - EGL_DEPTH_SIZE, 24, - EGL_ALPHA_SIZE, 8, - EGL_STENCIL_SIZE, 8, - EGL_SAMPLE_BUFFERS, 1, - EGL_SAMPLES, samples, - EGL_NONE - }; - - mEglConfig = mGLSupport->selectGLConfig(minAttribs, maxAttribs); - } - - if (!mIsTopLevel) - { - mIsFullScreen = false; - left = top = 0; - } - - if (mIsFullScreen) - { - mGLSupport->switchMode (width, height, frequency); - } - - createNativeWindow(left, top, width, height, title); - - mContext = createEGLContext(eglContext); - - // apply vsync settings. call setVSyncInterval first to avoid - // setting vsync more than once. - setVSyncInterval(vsyncInterval); - setVSyncEnabled(vsync); - - mName = name; - mWidth = width; - mHeight = height; - mLeft = left; - mTop = top; - - finaliseWindow(); - } - -} - diff --git a/RenderSystems/GLSupport/src/GLSL/OgreGLSLPreprocessor.cpp b/RenderSystems/GLSupport/src/GLSL/OgreGLSLPreprocessor.cpp deleted file mode 100644 index 766756c6cda..00000000000 --- a/RenderSystems/GLSupport/src/GLSL/OgreGLSLPreprocessor.cpp +++ /dev/null @@ -1,1406 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGLSLPreprocessor.h" -#include "OgreLogManager.h" - -#include -#include -#include - -namespace Ogre { - - // Limit max number of macro arguments to this -#define MAX_MACRO_ARGS 16 - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 && !defined( __MINGW32__ ) -#define snprintf _snprintf -#endif - - /// Return closest power of two not smaller than given number - static size_t ClosestPow2 (size_t x) - { - if (!(x & (x - 1))) - return x; - while (x & (x + 1)) - x |= (x + 1); - return x + 1; - } - - void CPreprocessor::Token::Append (const char *iString, size_t iLength) - { - Token t (Token::TK_TEXT, iString, iLength); - Append (t); - } - - void CPreprocessor::Token::Append (const Token &iOther) - { - if (!iOther.String) - return; - - if (!String) - { - String = iOther.String; - Length = iOther.Length; - Allocated = iOther.Allocated; - iOther.Allocated = 0; // !!! not quite correct but effective - return; - } - - if (Allocated) - { - size_t new_alloc = ClosestPow2 (Length + iOther.Length); - if (new_alloc < 64) - new_alloc = 64; - if (new_alloc != Allocated) - { - Allocated = new_alloc; - Buffer = (char *)realloc (Buffer, Allocated); - } - } - else if (String + Length != iOther.String) - { - Allocated = ClosestPow2 (Length + iOther.Length); - if (Allocated < 64) - Allocated = 64; - char *newstr = (char *)malloc (Allocated); - memcpy (newstr, String, Length); - Buffer = newstr; - } - - if (Allocated) - memcpy (Buffer + Length, iOther.String, iOther.Length); - Length += iOther.Length; - } - - bool CPreprocessor::Token::GetValue (long &oValue) const - { - long val = 0; - size_t i = 0; - - while (isspace (String [i])) - i++; - - long base = 10; - if (String [i] == '0') - { - if (Length > i + 1 && String [i + 1] == 'x') - base = 16, i += 2; - else - base = 8; - } - - for (; i < Length; i++) - { - int c = int (String [i]); - if (isspace (c)) - // Possible end of number - break; - - if (c >= 'a' && c <= 'z') - c -= ('a' - 'A'); - - c -= '0'; - if (c < 0) - return false; - - if (c > 9) - c -= ('A' - '9' - 1); - - if (c >= base) - return false; - - val = (val * base) + c; - } - - // Check that all other characters are just spaces - for (; i < Length; i++) - if (!isspace (String [i])) - return false; - - oValue = val; - return true; - } - - - void CPreprocessor::Token::SetValue (long iValue) - { - static char tmp [21]; - int len = snprintf (tmp, sizeof (tmp), "%ld", iValue); - Length = 0; - Append (tmp, len); - Type = TK_NUMBER; - } - - - void CPreprocessor::Token::AppendNL (int iCount) - { - static const char newlines [8] = - { '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n' }; - - while (iCount > 8) - { - Append (newlines, 8); - iCount -= 8; - } - if (iCount > 0) - Append (newlines, iCount); - } - - - int CPreprocessor::Token::CountNL () - { - if (Type == TK_EOS || Type == TK_ERROR) - return 0; - - const char *s = String; - size_t l = Length; - int c = 0; - while (l > 0) - { - const char *n = (const char *)memchr (s, '\n', l); - if (!n) - return c; - c++; - l -= (n - s + 1); - s = n + 1; - } - return c; - } - - CPreprocessor::Token CPreprocessor::Macro::Expand(const std::vector& iArgs, - std::forward_list& iMacros) - { - Expanding = true; - - CPreprocessor cpp; - cpp.SupplimentaryExpand = true; - std::swap(cpp.MacroList, iMacros); - - // Define a new macro for every argument - size_t i; - for (i = 0; i < iArgs.size(); i++) - cpp.Define (Args [i].String, Args [i].Length, - iArgs [i].String, iArgs [i].Length); - // The rest arguments are empty - for (; i < Args.size(); i++) - cpp.Define (Args [i].String, Args [i].Length, "", 0); - - Token xt; - // make sure that no one down the line sets Value.Allocated = 0 - Token new_xt = Token(Token::TK_TEXT, Value.String, Value.Length); - bool first = true; - do { - xt = new_xt; - // Now run the macro expansion through the supplimentary preprocessor - new_xt = cpp.Parse (xt); - - // Remove the extra macros we have defined, only needed once. - if (first) { - first = false; - for (int j = Args.size() - 1; j >= 0; j--) - cpp.Undef (Args [j].String, Args [j].Length); - } - // Repeat until there is no more change between parses - } while (xt.String != new_xt.String); - - Expanding = false; - std::swap(cpp.MacroList, iMacros); - - return xt; - } - - void CPreprocessor::Error(int iLine, const char *iError, const Token *iToken) - { - String msg; - if (iToken) - msg = StringUtil::format("line %d: %s: `%.*s'\n", iLine, iError, int(iToken->Length), iToken->String); - else - msg = StringUtil::format("line %d: %s\n", iLine, iError); - LogManager::getSingleton().logMessage(msg, LML_CRITICAL); - } - - CPreprocessor::CPreprocessor (const Token &iToken, int iLine) - { - Source = iToken.String; - SourceEnd = iToken.String + iToken.Length; - EnableOutput = 1; - EnableElif = 0; - Line = iLine; - BOL = true; - SupplimentaryExpand = false; - } - - CPreprocessor::CPreprocessor() - { - Source = 0; - SourceEnd = 0; - EnableOutput = 1; - Line = 0; - BOL = true; - SupplimentaryExpand = false; - } - - CPreprocessor::~CPreprocessor() {} - - CPreprocessor::Token CPreprocessor::GetToken (bool iExpand) - { - if (Source >= SourceEnd) - return Token (Token::TK_EOS); - - const char *begin = Source; - char c = *Source++; - - - if (c == '\n' || (c == '\r' && *Source == '\n')) - { - Line++; - BOL = true; - if (c == '\r') - Source++; - return Token (Token::TK_NEWLINE, begin, Source - begin); - } - else if (isspace (c)) - { - while (Source < SourceEnd && - *Source != '\r' && - *Source != '\n' && - isspace (*Source)) - Source++; - - return Token (Token::TK_WHITESPACE, begin, Source - begin); - } - else if (isdigit (c)) - { - BOL = false; - if (c == '0' && Source < SourceEnd && Source [0] == 'x') // hex numbers - { - Source++; - while (Source < SourceEnd && isxdigit (*Source)) - Source++; - } - else - while (Source < SourceEnd && isdigit (*Source)) - Source++; - return Token (Token::TK_NUMBER, begin, Source - begin); - } - else if (c == '_' || isalnum (c)) - { - BOL = false; - while (Source < SourceEnd && (*Source == '_' || isalnum (*Source))) - Source++; - Token t (Token::TK_KEYWORD, begin, Source - begin); - if (iExpand) - t = ExpandMacro (t); - return t; - } - else if (c == '"' || c == '\'') - { - BOL = false; - while (Source < SourceEnd && *Source != c) - { - if (*Source == '\\') - { - Source++; - if (Source >= SourceEnd) - break; - } - if (*Source == '\n') - Line++; - Source++; - } - if (Source < SourceEnd) - Source++; - return Token (Token::TK_STRING, begin, Source - begin); - } - else if (c == '/' && *Source == '/') - { - BOL = false; - Source++; - while (Source < SourceEnd && *Source != '\r' && *Source != '\n') - Source++; - return Token (Token::TK_LINECOMMENT, begin, Source - begin); - } - else if (c == '/' && *Source == '*') - { - BOL = false; - Source++; - while (Source < SourceEnd && (Source [0] != '*' || Source [1] != '/')) - { - if (*Source == '\n') - Line++; - Source++; - } - if (Source < SourceEnd && *Source == '*') - Source++; - if (Source < SourceEnd && *Source == '/') - Source++; - return Token (Token::TK_COMMENT, begin, Source - begin); - } - else if (c == '#' && BOL) - { - // Skip all whitespaces after '#' - while (Source < SourceEnd && isspace (*Source)) - Source++; - while (Source < SourceEnd && !isspace (*Source)) - Source++; - return Token (Token::TK_DIRECTIVE, begin, Source - begin); - } - else if (c == '\\' && Source < SourceEnd && (*Source == '\r' || *Source == '\n')) - { - // Treat backslash-newline as a whole token - if (*Source == '\r') - Source++; - if (*Source == '\n') - Source++; - Line++; - BOL = true; - return Token (Token::TK_LINECONT, begin, Source - begin); - } - else - { - BOL = false; - // Handle double-char operators here - if (c == '>' && (*Source == '>' || *Source == '=')) - Source++; - else if (c == '<' && (*Source == '<' || *Source == '=')) - Source++; - else if (c == '!' && *Source == '=') - Source++; - else if (c == '=' && *Source == '=') - Source++; - else if ((c == '|' || c == '&' || c == '^') && *Source == c) - Source++; - return Token (Token::TK_PUNCTUATION, begin, Source - begin); - } - } - - - CPreprocessor::Macro *CPreprocessor::IsDefined (const Token &iToken) - { - for (Macro& cur : MacroList) - if (cur.Name == iToken) - return &cur; - - return NULL; - } - - - CPreprocessor::Token CPreprocessor::ExpandMacro (const Token &iToken) - { - Macro *cur = IsDefined (iToken); - if (cur && !cur->Expanding) - { - std::vector args; - int old_line = Line; - - if (!cur->Args.empty()) - { - Token t = GetArguments (args, cur->ExpandFunc ? false : true, false); - if (t.Type == Token::TK_ERROR) - { - return t; - } - - // Put the token back into the source pool; we'll handle it later - if (t.String) - { - // Returned token should never be allocated on heap - assert (t.Allocated == 0); - Source = t.String; - Line -= t.CountNL (); - } - // If a macro is defined with arguments but gets not "called" it should behave like normal text - if (args.size() == 0 && (t.Type != Token::TK_PUNCTUATION || t.String [0] != '(')) - { - return iToken; - } - } - - if (args.size() > cur->Args.size()) - { - char tmp [60]; - snprintf (tmp, sizeof (tmp), "Macro `%.*s' passed %zu arguments, but takes just %zu", - int (cur->Name.Length), cur->Name.String, - args.size(), cur->Args.size()); - Error (old_line, tmp); - return Token (Token::TK_ERROR); - } - - Token t = cur->ExpandFunc ? - cur->ExpandFunc (this, args) : - cur->Expand (args, MacroList); - t.AppendNL (Line - old_line); - - return t; - } - - return iToken; - } - - - /** - * Operator priority: - * 0: Whole expression - * 1: '(' ')' - * 2: || - * 3: && - * 4: | - * 5: ^ - * 6: & - * 7: '==' '!=' - * 8: '<' '<=' '>' '>=' - * 9: '<<' '>>' - * 10: '+' '-' - * 11: '*' '/' '%' - * 12: unary '+' '-' '!' '~' - */ - CPreprocessor::Token CPreprocessor::GetExpression ( - Token &oResult, int iLine, int iOpPriority) - { - char tmp [40]; - - do - { - oResult = GetToken (true); - } while (oResult.Type == Token::TK_WHITESPACE || - oResult.Type == Token::TK_NEWLINE || - oResult.Type == Token::TK_COMMENT || - oResult.Type == Token::TK_LINECOMMENT || - oResult.Type == Token::TK_LINECONT); - - Token op (Token::TK_WHITESPACE, "", 0); - - // Handle unary operators here - if (oResult.Type == Token::TK_PUNCTUATION && oResult.Length == 1) - { - if (strchr ("+-!~", oResult.String [0])) - { - char uop = oResult.String [0]; - op = GetExpression (oResult, iLine, 12); - long val; - if (!GetValue (oResult, val, iLine)) - { - snprintf (tmp, sizeof (tmp), "Unary '%c' not applicable", uop); - Error (iLine, tmp, &oResult); - return Token (Token::TK_ERROR); - } - - if (uop == '-') - oResult.SetValue (-val); - else if (uop == '!') - oResult.SetValue (!val); - else if (uop == '~') - oResult.SetValue (~val); - } - else if (oResult.String [0] == '(') - { - op = GetExpression (oResult, iLine, 1); - if (op.Type == Token::TK_ERROR) - return op; - if (op.Type == Token::TK_EOS) - { - Error (iLine, "Unclosed parenthesis in #if expression"); - return Token (Token::TK_ERROR); - } - - assert (op.Type == Token::TK_PUNCTUATION && - op.Length == 1 && - op.String [0] == ')'); - op = GetToken (true); - } - } - - while (op.Type == Token::TK_WHITESPACE || - op.Type == Token::TK_NEWLINE || - op.Type == Token::TK_COMMENT || - op.Type == Token::TK_LINECOMMENT || - op.Type == Token::TK_LINECONT) - op = GetToken (true); - - while (true) - { - if (op.Type != Token::TK_PUNCTUATION) - return op; - - int prio = 0; - if (op.Length == 1) - switch (op.String [0]) - { - case ')': return op; - case '|': prio = 4; break; - case '^': prio = 5; break; - case '&': prio = 6; break; - case '<': - case '>': prio = 8; break; - case '+': - case '-': prio = 10; break; - case '*': - case '/': - case '%': prio = 11; break; - } - else if (op.Length == 2) - switch (op.String [0]) - { - case '|': if (op.String [1] == '|') prio = 2; break; - case '&': if (op.String [1] == '&') prio = 3; break; - case '=': if (op.String [1] == '=') prio = 7; break; - case '!': if (op.String [1] == '=') prio = 7; break; - case '<': - if (op.String [1] == '=') - prio = 8; - else if (op.String [1] == '<') - prio = 9; - break; - case '>': - if (op.String [1] == '=') - prio = 8; - else if (op.String [1] == '>') - prio = 9; - break; - } - - if (!prio) - { - Error (iLine, "Expecting operator, got", &op); - return Token (Token::TK_ERROR); - } - - if (iOpPriority >= prio) - return op; - - Token rop; - Token nextop = GetExpression (rop, iLine, prio); - long vlop, vrop; - if (!GetValue (oResult, vlop, iLine)) - { - snprintf (tmp, sizeof (tmp), "Left operand of '%.*s' is not a number", - int (op.Length), op.String); - Error (iLine, tmp, &oResult); - return Token (Token::TK_ERROR); - } - if (!GetValue (rop, vrop, iLine)) - { - snprintf (tmp, sizeof (tmp), "Right operand of '%.*s' is not a number", - int (op.Length), op.String); - Error (iLine, tmp, &rop); - return Token (Token::TK_ERROR); - } - - switch (op.String [0]) - { - case '|': - if (prio == 2) - oResult.SetValue (vlop || vrop); - else - oResult.SetValue (vlop | vrop); - break; - case '&': - if (prio == 3) - oResult.SetValue (vlop && vrop); - else - oResult.SetValue (vlop & vrop); - break; - case '<': - if (op.Length == 1) - oResult.SetValue (vlop < vrop); - else if (prio == 8) - oResult.SetValue (vlop <= vrop); - else if (prio == 9) - oResult.SetValue (vlop << vrop); - break; - case '>': - if (op.Length == 1) - oResult.SetValue (vlop > vrop); - else if (prio == 8) - oResult.SetValue (vlop >= vrop); - else if (prio == 9) - oResult.SetValue (vlop >> vrop); - break; - case '^': oResult.SetValue (vlop ^ vrop); break; - case '!': oResult.SetValue (vlop != vrop); break; - case '=': oResult.SetValue (vlop == vrop); break; - case '+': oResult.SetValue (vlop + vrop); break; - case '-': oResult.SetValue (vlop - vrop); break; - case '*': oResult.SetValue (vlop * vrop); break; - case '/': - case '%': - if (vrop == 0) - { - Error (iLine, "Division by zero"); - return Token (Token::TK_ERROR); - } - if (op.String [0] == '/') - oResult.SetValue (vlop / vrop); - else - oResult.SetValue (vlop % vrop); - break; - } - - op = nextop; - } - } - - - bool CPreprocessor::GetValue (const Token &iToken, long &oValue, int iLine) - { - Token r; - const Token *vt = &iToken; - - if ((vt->Type == Token::TK_KEYWORD || - vt->Type == Token::TK_TEXT || - vt->Type == Token::TK_NUMBER) && - !vt->String) - { - Error (iLine, "Trying to evaluate an empty expression"); - return false; - } - - if (vt->Type == Token::TK_TEXT) - { - CPreprocessor cpp (iToken, iLine); - std::swap(cpp.MacroList, MacroList); - - Token t; - t = cpp.GetExpression (r, iLine); - - std::swap(cpp.MacroList, MacroList); - - if (t.Type == Token::TK_ERROR) - return false; - - if (t.Type != Token::TK_EOS) - { - Error (iLine, "Garbage after expression", &t); - return false; - } - - vt = &r; - } - - Macro *m; - switch (vt->Type) - { - case Token::TK_EOS: - case Token::TK_ERROR: - return false; - - case Token::TK_KEYWORD: - // Try to expand the macro - if ((m = IsDefined (*vt)) && !m->Expanding) - { - Token x = ExpandMacro (*vt); - m->Expanding = true; - bool rc = GetValue (x, oValue, iLine); - m->Expanding = false; - return rc; - } - - // Undefined macro, "expand" to 0 (mimic cpp behaviour) - oValue = 0; - break; - - case Token::TK_TEXT: - case Token::TK_NUMBER: - if (!vt->GetValue (oValue)) - { - Error (iLine, "Not a numeric expression", vt); - return false; - } - break; - - default: - Error (iLine, "Unexpected token", vt); - return false; - } - - return true; - } - - - CPreprocessor::Token CPreprocessor::GetArgument (Token &oArg, bool iExpand, - bool shouldAppendArg) - { - do - { - oArg = GetToken (iExpand); - } while (oArg.Type == Token::TK_WHITESPACE || - oArg.Type == Token::TK_NEWLINE || - oArg.Type == Token::TK_COMMENT || - oArg.Type == Token::TK_LINECOMMENT || - oArg.Type == Token::TK_LINECONT); - - if (!iExpand) - { - if (oArg.Type == Token::TK_EOS) - return oArg; - else if (oArg.Type == Token::TK_PUNCTUATION && - (oArg.String [0] == ',' || - oArg.String [0] == ')')) - { - Token t = oArg; - oArg = Token (Token::TK_TEXT, "", 0); - return t; - } - else if (oArg.Type != Token::TK_KEYWORD) - { - Error (Line, "Unexpected token", &oArg); - return Token (Token::TK_ERROR); - } - } - - size_t braceCount = 0; - - if( oArg.Type == Token::TK_PUNCTUATION && oArg.String[0] == '(' ) - ++braceCount; - - size_t len = oArg.Length; - while (true) - { - Token t = GetToken (iExpand); - switch (t.Type) - { - case Token::TK_EOS: - Error (Line, "Unfinished list of arguments"); - OGRE_FALLTHROUGH; - case Token::TK_ERROR: - return Token (Token::TK_ERROR); - case Token::TK_PUNCTUATION: - if( t.String [0] == '(' ) - { - ++braceCount; - } - else if( !braceCount ) - { - if (t.String [0] == ',' || - t.String [0] == ')') - { - // Trim whitespaces at the end - oArg.Length = len; - - //Append "__arg_" to all macro arguments, otherwise if user does: - // #define mad( a, b, c ) fma( a, b, c ) - // mad( x.s, y, a ); - //It will be translated to: - // fma( x.s, y, x.s ); - //instead of: - // fma( x.s, y, a ); - //This does not fix the problem by the root, but - //typing "__arg_" by the user is extremely rare. - if( shouldAppendArg ) - oArg.Append( "__arg_", 6 ); - return t; - } - } - else - { - if( t.String [0] == ')' ) - --braceCount; - } - break; - case Token::TK_LINECONT: - case Token::TK_COMMENT: - case Token::TK_LINECOMMENT: - case Token::TK_NEWLINE: - // ignore these tokens - continue; - default: - break; - } - - if (!iExpand && t.Type != Token::TK_WHITESPACE) - { - Error (Line, "Unexpected token", &oArg); - return Token (Token::TK_ERROR); - } - - oArg.Append (t); - - if (t.Type != Token::TK_WHITESPACE) - len = oArg.Length; - } - } - - - CPreprocessor::Token CPreprocessor::GetArguments (std::vector& oArgs, - bool iExpand, bool shouldAppendArg) - { - Token args [MAX_MACRO_ARGS]; - int nargs = 0; - - // Suppose we'll leave by the wrong path - oArgs.clear(); - - bool isFirstTokenParsed = false; - bool isFirstTokenNotAnOpenBrace = false; - - Token t; - do - { - t = GetToken (iExpand); - - if( !isFirstTokenParsed && - (t.Type != Token::TK_PUNCTUATION || t.String [0] != '(') ) - { - isFirstTokenNotAnOpenBrace = true; - } - isFirstTokenParsed = true; - } while (t.Type == Token::TK_WHITESPACE || - t.Type == Token::TK_COMMENT || - t.Type == Token::TK_LINECOMMENT); - - if( isFirstTokenNotAnOpenBrace ) - { - oArgs.clear(); - return t; - } - - while (true) - { - if (nargs == MAX_MACRO_ARGS) - { - Error (Line, "Too many arguments to macro"); - return Token (Token::TK_ERROR); - } - - t = GetArgument (args [nargs++], iExpand, shouldAppendArg); - - switch (t.Type) - { - case Token::TK_EOS: - Error (Line, "Unfinished list of arguments"); - OGRE_FALLTHROUGH; - case Token::TK_ERROR: - return Token (Token::TK_ERROR); - - case Token::TK_PUNCTUATION: - if (t.String [0] == ')') - { - t = GetToken (iExpand); - goto Done; - } // otherwise we've got a ',' - break; - - default: - Error (Line, "Unexpected token", &t); - break; - } - } - - Done: - oArgs.insert(oArgs.begin(), args, args + nargs); - return t; - } - - - bool CPreprocessor::HandleDefine (Token &iBody, int iLine) - { - // Create an additional preprocessor to process macro body - CPreprocessor cpp (iBody, iLine); - - Token t = cpp.GetToken (false); - if (t.Type != Token::TK_KEYWORD) - { - Error (iLine, "Macro name expected after #define"); - return false; - } - - Macro m(t); - m.Body = iBody; - t = cpp.GetArguments (m.Args, false, true); - while (t.Type == Token::TK_WHITESPACE) - t = cpp.GetToken (false); - - switch (t.Type) - { - case Token::TK_NEWLINE: - case Token::TK_EOS: - // Assign "" to token - t = Token (Token::TK_TEXT, "", 0); - break; - - case Token::TK_ERROR: - return false; - - default: - t.Type = Token::TK_TEXT; - assert (t.String + t.Length == cpp.Source); - t.Length = cpp.SourceEnd - t.String; - break; - } - - if( !m.Args.empty() ) - { - CPreprocessor cpp2; - - //We need to convert: - // #define mad( a__arg_, b__arg_, c__arg_ ) fma( a, b, c ) - //into: - // #define mad( a__arg_, b__arg_, c__arg_ ) fma( a__arg_, b__arg_, c__arg_ ) - for (const Token& arg : m.Args) - { - cpp2.Define(arg.String, arg.Length - 6, arg.String, arg.Length); - } - - // Now run the macro expansion through the supplimentary preprocessor - Token xt = cpp2.Parse( t ); - t = xt; - } - - m.Value = t; - MacroList.push_front(std::move(m)); - return true; - } - - - bool CPreprocessor::HandleUnDef (Token &iBody, int iLine) - { - CPreprocessor cpp (iBody, iLine); - - Token t = cpp.GetToken (false); - - if (t.Type != Token::TK_KEYWORD) - { - Error (iLine, "Expecting a macro name after #undef, got", &t); - return false; - } - - // Don't barf if macro does not exist - standard C behaviour - Undef (t.String, t.Length); - - do - { - t = cpp.GetToken (false); - } while (t.Type == Token::TK_WHITESPACE || - t.Type == Token::TK_COMMENT || - t.Type == Token::TK_LINECOMMENT); - - if (t.Type != Token::TK_EOS) - Error (iLine, "Warning: Ignoring garbage after directive", &t); - - return true; - } - - bool CPreprocessor::HandleIf(bool val, int iLine) - { - if (EnableOutput & (1 << 31)) - { - Error (iLine, "Too many embedded #if directives"); - return false; - } - - EnableElif <<= 1; - EnableOutput <<= 1; - if (val) - EnableOutput |= 1; - else - EnableElif |= 1; - - return true; - } - - bool CPreprocessor::HandleIfDef (Token &iBody, int iLine) - { - CPreprocessor cpp (iBody, iLine); - - Token t = cpp.GetToken (false); - - if (t.Type != Token::TK_KEYWORD) - { - Error (iLine, "Expecting a macro name after #ifdef, got", &t); - return false; - } - - if (!HandleIf(IsDefined(t), iLine)) - return false; - - do - { - t = cpp.GetToken (false); - } while (t.Type == Token::TK_WHITESPACE || - t.Type == Token::TK_COMMENT || - t.Type == Token::TK_LINECOMMENT); - - if (t.Type != Token::TK_EOS) - Error (iLine, "Warning: Ignoring garbage after directive", &t); - - return true; - } - - - CPreprocessor::Token CPreprocessor::ExpandDefined (CPreprocessor *iParent, const std::vector& iArgs) - { - if (iArgs.size() != 1) - { - iParent->Error (iParent->Line, "The defined() function takes exactly one argument"); - return Token (Token::TK_ERROR); - } - - const char *v = iParent->IsDefined (iArgs [0]) ? "1" : "0"; - return Token (Token::TK_NUMBER, v, 1); - } - - bool CPreprocessor::GetValueDef(const Token &iToken, long &oValue, int iLine) - { - // Temporary add the defined() function to the macro list - MacroList.emplace_front(Token(Token::TK_KEYWORD, "defined", 7)); - MacroList.front().ExpandFunc = ExpandDefined; - MacroList.front().Args.resize(1); - - bool rc = GetValue (iToken, oValue, iLine); - - // Restore the macro list - MacroList.pop_front(); - - return rc; - } - - bool CPreprocessor::HandleIf (Token &iBody, int iLine) - { - long val; - return GetValueDef(iBody, val, iLine) && HandleIf(val, iLine); - } - - bool CPreprocessor::HandleElif (Token &iBody, int iLine) - { - if (EnableOutput == 1) - { - Error (iLine, "#elif without #if"); - return false; - } - - long val; - if (!GetValueDef(iBody, val, iLine)) - return false; - - if (val && (EnableElif & 1)) - { - EnableOutput |= 1; - EnableElif &= ~1; - } - else - EnableOutput &= ~1; - - return true; - } - - - bool CPreprocessor::HandleElse (Token &iBody, int iLine) - { - if (EnableOutput == 1) - { - Error (iLine, "#else without #if"); - return false; - } - - // Negate the result of last #if - if ((EnableElif & 1) || (EnableOutput & 1)) - EnableOutput ^= 1; - - if (iBody.Length) - Error (iLine, "Warning: Ignoring garbage after #else", &iBody); - - return true; - } - - - bool CPreprocessor::HandleEndIf (Token &iBody, int iLine) - { - EnableElif >>= 1; - EnableOutput >>= 1; - if (EnableOutput == 0) - { - Error (iLine, "#endif without #if"); - return false; - } - - if (iBody.Length) - Error (iLine, "Warning: Ignoring garbage after #endif", &iBody); - - return true; - } - - - CPreprocessor::Token CPreprocessor::HandleDirective (Token &iToken, int iLine) - { - // Analyze preprocessor directive - const char *directive = iToken.String + 1; - size_t dirlen = iToken.Length - 1; - while (dirlen && isspace (*directive)) - dirlen--, directive++; - - int old_line = Line; - - // Collect the remaining part of the directive until EOL - Token t, last; - do - { - t = GetToken (false); - if (t.Type == Token::TK_NEWLINE) - { - // No directive arguments - last = t; - t.Length = 0; - goto Done; - } - } while (t.Type == Token::TK_WHITESPACE || - t.Type == Token::TK_LINECONT || - t.Type == Token::TK_COMMENT || - t.Type == Token::TK_LINECOMMENT); - - for (;;) - { - last = GetToken (false); - switch (last.Type) - { - case Token::TK_EOS: - // Can happen and is not an error - goto Done; - - case Token::TK_LINECOMMENT: - case Token::TK_COMMENT: - // Skip comments in macros - continue; - - case Token::TK_ERROR: - return last; - - case Token::TK_LINECONT: - continue; - - case Token::TK_NEWLINE: - goto Done; - - default: - break; - } - - t.Append (last); - t.Type = Token::TK_TEXT; - } - Done: - -#define IS_DIRECTIVE(s) \ - (dirlen == strlen(s) && (strncmp (directive, s, dirlen) == 0)) - - bool outputEnabled = ((EnableOutput & (EnableOutput + 1)) == 0); - bool rc; - - if (IS_DIRECTIVE ("define") && outputEnabled) - rc = HandleDefine (t, iLine); - else if (IS_DIRECTIVE ("undef") && outputEnabled) - rc = HandleUnDef (t, iLine); - else if (IS_DIRECTIVE ("ifdef")) - rc = HandleIfDef (t, iLine); - else if (IS_DIRECTIVE ("ifndef")) - { - rc = HandleIfDef (t, iLine); - if (rc) - { - EnableOutput ^= 1; - EnableElif ^= 1; - } - } - else if (IS_DIRECTIVE ("if")) - rc = HandleIf (t, iLine); - else if (IS_DIRECTIVE ("elif")) - rc = HandleElif (t, iLine); - - else if (IS_DIRECTIVE ("else")) - rc = HandleElse (t, iLine); - else if (IS_DIRECTIVE ("endif")) - rc = HandleEndIf (t, iLine); - else - { - //Error (iLine, "Unknown preprocessor directive", &iToken); - //return Token (Token::TK_ERROR); - - // Unknown preprocessor directive, roll back and pass through - Line = old_line; - Source = iToken.String + iToken.Length; - iToken.Type = Token::TK_TEXT; - return iToken; - } - -#undef IS_DIRECTIVE - - if (!rc) - return Token (Token::TK_ERROR); - return last; - } - - - void CPreprocessor::Define (const char *iMacroName, size_t iMacroNameLen, - const char *iMacroValue, size_t iMacroValueLen) - { - MacroList.emplace_front(Token(Token::TK_KEYWORD, iMacroName, iMacroNameLen)); - MacroList.front().Value = Token(Token::TK_TEXT, iMacroValue, iMacroValueLen); - } - - - void CPreprocessor::Define (const char *iMacroName, size_t iMacroNameLen) - { - MacroList.emplace_front(Token(Token::TK_KEYWORD, iMacroName, iMacroNameLen)); - } - - - bool CPreprocessor::Undef (const char *iMacroName, size_t iMacroNameLen) - { - Token name (Token::TK_KEYWORD, iMacroName, iMacroNameLen); - - for (auto it = MacroList.before_begin();; ++it) - { - auto itpp = std::next(it); - if(itpp == MacroList.end()) break; - - if (itpp->Name == name) - { - MacroList.erase_after(it); - return true; - } - } - - return false; - } - - - CPreprocessor::Token CPreprocessor::Parse (const Token &iSource) - { - Source = iSource.String; - SourceEnd = Source + iSource.Length; - Line = 1; - BOL = true; - EnableOutput = 1; - EnableElif = 0; - - // Accumulate output into this token - Token output (Token::TK_TEXT); - int empty_lines = 0; - - // Enable output only if all embedded #if's were true - bool old_output_enabled = true; - bool output_enabled = true; - int output_disabled_line = 0; - - while (Source < SourceEnd) - { - int old_line = Line; - Token t = GetToken (true); - - NextToken: - switch (t.Type) - { - case Token::TK_ERROR: - return t; - - case Token::TK_EOS: - return output; // Force termination - - case Token::TK_COMMENT: - // C comments are replaced with single spaces. - if (output_enabled) - { - output.Append (" ", 1); - output.AppendNL (Line - old_line); - } - break; - - case Token::TK_LINECOMMENT: - // C++ comments are ignored - continue; - - case Token::TK_DIRECTIVE: - // Handle preprocessor directives - t = HandleDirective (t, old_line); - - output_enabled = ((EnableOutput & (EnableOutput + 1)) == 0); - if (output_enabled != old_output_enabled) - { - if (output_enabled) - output.AppendNL (old_line - output_disabled_line); - else - output_disabled_line = old_line; - old_output_enabled = output_enabled; - } - - if (output_enabled) - output.AppendNL (Line - old_line - t.CountNL ()); - goto NextToken; - - case Token::TK_LINECONT: - // Backslash-Newline sequences are deleted, no matter where. - empty_lines++; - break; - - case Token::TK_PUNCTUATION: - if (output_enabled && (!SupplimentaryExpand || t.String[0] != '#')) - output.Append (t); - break; - - case Token::TK_NEWLINE: - if (empty_lines) - { - // Compensate for the backslash-newline combinations - // we have encountered, otherwise line numeration is broken - if (output_enabled) - output.AppendNL (empty_lines); - empty_lines = 0; - } - OGRE_FALLTHROUGH; // to default - case Token::TK_WHITESPACE: - // Fallthrough to default - default: - // Passthrough all other tokens - if (output_enabled) - output.Append (t); - break; - } - } - - if (EnableOutput != 1) - { - Error (Line, "Unclosed #if at end of source"); - return Token (Token::TK_ERROR); - } - - return output; - } - - - char *CPreprocessor::Parse (const char *iSource, size_t iLength, size_t &oLength) - { - Token retval = Parse (Token (Token::TK_TEXT, iSource, iLength)); - if (retval.Type == Token::TK_ERROR) - return NULL; - - oLength = retval.Length; - retval.Allocated = 0; - return retval.Buffer; - } - -} // namespace Ogre diff --git a/RenderSystems/GLSupport/src/GLSL/OgreGLSLProgramCommon.cpp b/RenderSystems/GLSupport/src/GLSL/OgreGLSLProgramCommon.cpp deleted file mode 100644 index 5cec9f21e0d..00000000000 --- a/RenderSystems/GLSupport/src/GLSL/OgreGLSLProgramCommon.cpp +++ /dev/null @@ -1,152 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#include "OgreGLSLProgramCommon.h" -#include "OgreStringConverter.h" - -#include - -namespace Ogre -{ -GLSLProgramCommon::GLSLProgramCommon(const GLShaderList& shaders) - : mShaders(shaders), - mUniformRefsBuilt(false), - mGLProgramHandle(0), - mLinked(false) -{ - // compute shader presence means no other shaders are allowed - if(shaders[GPT_COMPUTE_PROGRAM]) - { - mShaders.fill(NULL); - mShaders[GPT_COMPUTE_PROGRAM] = shaders[GPT_COMPUTE_PROGRAM]; - } -} - -// Switching attribute bindings requires re-creating VAOs. So avoid! -// Fixed builtins (from ARB_vertex_program Table X.2) are: - -// a builtin custom attrib name -// ---------------------------------------------- -// 0 gl_Vertex vertex/ position -// 1 n/a blendWeights -// 2 gl_Normal normal -// 3 gl_Color colour -// 4 gl_SecondaryColor secondary_colour -// 5 gl_FogCoord n/a -// 6 n/a n/a -// 7 n/a blendIndices -// 8 gl_MultiTexCoord0 uv0 -// 9 gl_MultiTexCoord1 uv1 -// 10 gl_MultiTexCoord2 uv2 -// 11 gl_MultiTexCoord3 uv3 -// 12 gl_MultiTexCoord4 uv4 -// 13 gl_MultiTexCoord5 uv5 -// 14 gl_MultiTexCoord6 uv6, tangent -// 15 gl_MultiTexCoord7 uv7, binormal -GLSLProgramCommon::CustomAttribute GLSLProgramCommon::msCustomAttributes[17] = { - {"vertex", getFixedAttributeIndex(VES_POSITION, 0), VES_POSITION}, - {"position", getFixedAttributeIndex(VES_POSITION, 0), VES_POSITION}, // allow alias for "vertex" - {"blendWeights", getFixedAttributeIndex(VES_BLEND_WEIGHTS, 0), VES_BLEND_WEIGHTS}, - {"normal", getFixedAttributeIndex(VES_NORMAL, 0), VES_NORMAL}, - {"colour", getFixedAttributeIndex(VES_DIFFUSE, 0), VES_DIFFUSE}, - {"secondary_colour", getFixedAttributeIndex(VES_SPECULAR, 0), VES_SPECULAR}, - {"blendIndices", getFixedAttributeIndex(VES_BLEND_INDICES, 0), VES_BLEND_INDICES}, - {"uv0", getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 0), VES_TEXTURE_COORDINATES}, - {"uv1", getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 1), VES_TEXTURE_COORDINATES}, - {"uv2", getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 2), VES_TEXTURE_COORDINATES}, - {"uv3", getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 3), VES_TEXTURE_COORDINATES}, - {"uv4", getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 4), VES_TEXTURE_COORDINATES}, - {"uv5", getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 5), VES_TEXTURE_COORDINATES}, - {"uv6", getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 6), VES_TEXTURE_COORDINATES}, - {"uv7", getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 7), VES_TEXTURE_COORDINATES}, - {"tangent", getFixedAttributeIndex(VES_TANGENT, 0), VES_TANGENT}, - {"binormal", getFixedAttributeIndex(VES_BINORMAL, 0), VES_BINORMAL}, -}; - -static int32 attributeIndex[VES_COUNT + 1] = { - -1,// n/a - 0, // VES_POSITION - 1, // VES_BLEND_WEIGHTS - 7, // VES_BLEND_INDICES - 2, // VES_NORMAL - 3, // VES_DIFFUSE - 4, // VES_SPECULAR - 8, // VES_TEXTURE_COORDINATES - 15,// VES_BINORMAL - 14 // VES_TANGENT -}; - -void GLSLProgramCommon::useTightAttributeLayout() { - // a builtin custom attrib name - // ---------------------------------------------- - // 0 gl_Vertex vertex/ position - // 1 gl_Normal normal - // 2 gl_Color colour - // 3 gl_MultiTexCoord0 uv0 - // 4 gl_MultiTexCoord1 uv1, blendWeights - // 5 gl_MultiTexCoord2 uv2, blendIndices - // 6 gl_MultiTexCoord3 uv3, tangent - // 7 gl_MultiTexCoord4 uv4, binormal - - size_t numAttribs = sizeof(msCustomAttributes)/sizeof(CustomAttribute); - for (size_t i = 0; i < numAttribs; ++i) - { - CustomAttribute& a = msCustomAttributes[i]; - a.attrib -= attributeIndex[a.semantic]; // only keep index (for uvXY) - } - - attributeIndex[VES_NORMAL] = 1; - attributeIndex[VES_DIFFUSE] = 2; - attributeIndex[VES_TEXTURE_COORDINATES] = 3; - attributeIndex[VES_BLEND_WEIGHTS] = 4; - attributeIndex[VES_BLEND_INDICES] = 5; - attributeIndex[VES_TANGENT] = 6; - attributeIndex[VES_BINORMAL] = 7; - - for (size_t i = 0; i < numAttribs; ++i) - { - CustomAttribute& a = msCustomAttributes[i]; - a.attrib += attributeIndex[a.semantic]; - } -} - -int32 GLSLProgramCommon::getFixedAttributeIndex(VertexElementSemantic semantic, uint index) -{ - OgreAssertDbg(semantic > 0 && semantic <= VES_COUNT, "Missing attribute!"); - - if(semantic == VES_TEXTURE_COORDINATES) - return attributeIndex[semantic] + index; - - return attributeIndex[semantic]; -} - -String GLSLProgramCommon::getCombinedName() -{ - StringStream ss; - - for(auto s : mShaders) - { - if (s) - { - ss << s->getName() << "\n"; - } - } - - return ss.str(); -} - -uint32 GLSLProgramCommon::getCombinedHash() -{ - uint32 hash = 0; - - for (auto p : mShaders) - { - if(!p) continue; - hash = p->_getHash(hash); - } - return hash; -} - -} /* namespace Ogre */ diff --git a/RenderSystems/GLSupport/src/GLSL/OgreGLSLProgramManagerCommon.cpp b/RenderSystems/GLSupport/src/GLSL/OgreGLSLProgramManagerCommon.cpp deleted file mode 100644 index 8bc3f61f7f8..00000000000 --- a/RenderSystems/GLSupport/src/GLSL/OgreGLSLProgramManagerCommon.cpp +++ /dev/null @@ -1,494 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGLSLProgramManagerCommon.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreGLSLProgramCommon.h" - -namespace Ogre { - - GLSLProgramManagerCommon::GLSLProgramManagerCommon() : mActiveProgram(NULL) - { - mActiveShader.fill(NULL); - - // Fill in the relationship between type names and enums - mTypeEnumMap.emplace("float", GCT_FLOAT1); - mTypeEnumMap.emplace("vec2", GCT_FLOAT2); - mTypeEnumMap.emplace("vec3", GCT_FLOAT3); - mTypeEnumMap.emplace("vec4", GCT_FLOAT4); - mTypeEnumMap.emplace("sampler1D", GCT_SAMPLER1D); - mTypeEnumMap.emplace("sampler2D", GCT_SAMPLER2D); - mTypeEnumMap.emplace("sampler3D", GCT_SAMPLER3D); - mTypeEnumMap.emplace("samplerCube", GCT_SAMPLERCUBE); - mTypeEnumMap.emplace("sampler1DShadow", GCT_SAMPLER1DSHADOW); - mTypeEnumMap.emplace("sampler2DShadow", GCT_SAMPLER2DSHADOW); - mTypeEnumMap.emplace("int", GCT_INT1); - mTypeEnumMap.emplace("ivec2", GCT_INT2); - mTypeEnumMap.emplace("ivec3", GCT_INT3); - mTypeEnumMap.emplace("ivec4", GCT_INT4); - mTypeEnumMap.emplace("bool", GCT_BOOL1); - mTypeEnumMap.emplace("bvec2", GCT_BOOL2); - mTypeEnumMap.emplace("bvec3", GCT_BOOL3); - mTypeEnumMap.emplace("bvec4", GCT_BOOL4); - mTypeEnumMap.emplace("mat2", GCT_MATRIX_2X2); - mTypeEnumMap.emplace("mat3", GCT_MATRIX_3X3); - mTypeEnumMap.emplace("mat4", GCT_MATRIX_4X4); - - // GLES2 ext - mTypeEnumMap.emplace("samplerExternalOES", GCT_SAMPLER_EXTERNAL_OES); - - // GL 2.1 - mTypeEnumMap.emplace("mat2x2", GCT_MATRIX_2X2); - mTypeEnumMap.emplace("mat3x3", GCT_MATRIX_3X3); - mTypeEnumMap.emplace("mat4x4", GCT_MATRIX_4X4); - mTypeEnumMap.emplace("mat2x3", GCT_MATRIX_2X3); - mTypeEnumMap.emplace("mat3x2", GCT_MATRIX_3X2); - mTypeEnumMap.emplace("mat3x4", GCT_MATRIX_3X4); - mTypeEnumMap.emplace("mat4x3", GCT_MATRIX_4X3); - mTypeEnumMap.emplace("mat2x4", GCT_MATRIX_2X4); - mTypeEnumMap.emplace("mat4x2", GCT_MATRIX_4X2); - - // GL 3.0 - mTypeEnumMap.emplace("uint", GCT_UINT1); - mTypeEnumMap.emplace("uvec2", GCT_UINT2); - mTypeEnumMap.emplace("uvec3", GCT_UINT3); - mTypeEnumMap.emplace("uvec4", GCT_UINT4); - mTypeEnumMap.emplace("samplerCubeShadow", GCT_SAMPLERCUBE); - mTypeEnumMap.emplace("sampler1DArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("sampler2DArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("sampler1DArrayShadow", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("sampler2DArrayShadow", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("isampler1D", GCT_SAMPLER1D); - mTypeEnumMap.emplace("isampler2D", GCT_SAMPLER2D); - mTypeEnumMap.emplace("isampler3D", GCT_SAMPLER3D); - mTypeEnumMap.emplace("isamplerCube", GCT_SAMPLERCUBE); - mTypeEnumMap.emplace("isampler1DArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("isampler2DArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("usampler1D", GCT_SAMPLER1D); - mTypeEnumMap.emplace("usampler2D", GCT_SAMPLER2D); - mTypeEnumMap.emplace("usampler3D", GCT_SAMPLER3D); - mTypeEnumMap.emplace("usamplerCube", GCT_SAMPLERCUBE); - mTypeEnumMap.emplace("usampler1DArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("usampler2DArray", GCT_SAMPLER2DARRAY); - - // GL 3.1 - mTypeEnumMap.emplace("sampler2DRect", GCT_SAMPLER2D); - mTypeEnumMap.emplace("sampler2DRectShadow", GCT_SAMPLER2D); - mTypeEnumMap.emplace("isampler2DRect", GCT_SAMPLER2D); - mTypeEnumMap.emplace("usampler2DRect", GCT_SAMPLER2D); - mTypeEnumMap.emplace("samplerBuffer", GCT_SAMPLER1D); - mTypeEnumMap.emplace("isamplerBuffer", GCT_SAMPLER1D); - mTypeEnumMap.emplace("usamplerBuffer", GCT_SAMPLER1D); - - // GL 3.2 - mTypeEnumMap.emplace("sampler2DMS", GCT_SAMPLER2D); - mTypeEnumMap.emplace("isampler2DMS", GCT_SAMPLER2D); - mTypeEnumMap.emplace("usampler2DMS", GCT_SAMPLER2D); - mTypeEnumMap.emplace("sampler2DMSArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("isampler2DMSArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("usampler2DMSArray", GCT_SAMPLER2DARRAY); - - // GL 4.0 - mTypeEnumMap.emplace("double", GCT_DOUBLE1); - mTypeEnumMap.emplace("dmat2", GCT_MATRIX_DOUBLE_2X2); - mTypeEnumMap.emplace("dmat3", GCT_MATRIX_DOUBLE_3X3); - mTypeEnumMap.emplace("dmat4", GCT_MATRIX_DOUBLE_4X4); - mTypeEnumMap.emplace("dmat2x2", GCT_MATRIX_DOUBLE_2X2); - mTypeEnumMap.emplace("dmat3x3", GCT_MATRIX_DOUBLE_3X3); - mTypeEnumMap.emplace("dmat4x4", GCT_MATRIX_DOUBLE_4X4); - mTypeEnumMap.emplace("dmat2x3", GCT_MATRIX_DOUBLE_2X3); - mTypeEnumMap.emplace("dmat3x2", GCT_MATRIX_DOUBLE_3X2); - mTypeEnumMap.emplace("dmat3x4", GCT_MATRIX_DOUBLE_3X4); - mTypeEnumMap.emplace("dmat4x3", GCT_MATRIX_DOUBLE_4X3); - mTypeEnumMap.emplace("dmat2x4", GCT_MATRIX_DOUBLE_2X4); - mTypeEnumMap.emplace("dmat4x2", GCT_MATRIX_DOUBLE_4X2); - mTypeEnumMap.emplace("dvec2", GCT_DOUBLE2); - mTypeEnumMap.emplace("dvec3", GCT_DOUBLE3); - mTypeEnumMap.emplace("dvec4", GCT_DOUBLE4); - mTypeEnumMap.emplace("samplerCubeArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("samplerCubeArrayShadow", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("isamplerCubeArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("usamplerCubeArray", GCT_SAMPLER2DARRAY); - - //TODO should image be its own type? - mTypeEnumMap.emplace("image1D", GCT_SAMPLER1D); - mTypeEnumMap.emplace("iimage1D", GCT_SAMPLER1D); - mTypeEnumMap.emplace("uimage1D", GCT_SAMPLER1D); - mTypeEnumMap.emplace("image2D", GCT_SAMPLER2D); - mTypeEnumMap.emplace("iimage2D", GCT_SAMPLER2D); - mTypeEnumMap.emplace("uimage2D", GCT_SAMPLER2D); - mTypeEnumMap.emplace("image3D", GCT_SAMPLER3D); - mTypeEnumMap.emplace("iimage3D", GCT_SAMPLER3D); - mTypeEnumMap.emplace("uimage3D", GCT_SAMPLER3D); - mTypeEnumMap.emplace("image2DRect", GCT_SAMPLER2D); - mTypeEnumMap.emplace("iimage2DRect", GCT_SAMPLER2D); - mTypeEnumMap.emplace("uimage2DRect", GCT_SAMPLER2D); - mTypeEnumMap.emplace("imageCube", GCT_SAMPLERCUBE); - mTypeEnumMap.emplace("iimageCube", GCT_SAMPLERCUBE); - mTypeEnumMap.emplace("uimageCube", GCT_SAMPLERCUBE); - mTypeEnumMap.emplace("imageBuffer", GCT_SAMPLER1D); - mTypeEnumMap.emplace("iimageBuffer", GCT_SAMPLER1D); - mTypeEnumMap.emplace("uimageBuffer", GCT_SAMPLER1D); - mTypeEnumMap.emplace("image1DArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("iimage1DArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("uimage1DArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("image2DArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("iimage2DArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("uimage2DArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("imageCubeArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("iimageCubeArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("uimageCubeArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("image2DMS", GCT_SAMPLER2D); - mTypeEnumMap.emplace("iimage2DMS", GCT_SAMPLER2D); - mTypeEnumMap.emplace("uimage2DMS", GCT_SAMPLER2D); - mTypeEnumMap.emplace("image2DMSArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("iimage2DMSArray", GCT_SAMPLER2DARRAY); - mTypeEnumMap.emplace("uimage2DMSArray", GCT_SAMPLER2DARRAY); - - // GL 4.2 - mTypeEnumMap.emplace("atomic_uint", GCT_UINT1); //TODO should be its own type? - } - - GLSLProgramManagerCommon::~GLSLProgramManagerCommon() - { - // iterate through map container and delete link programs - for (auto & p : mPrograms) - { - delete p.second; - } - } - - void GLSLProgramManagerCommon::destroyAllByShader(GLSLShaderCommon* shader) - { - std::vector keysToErase; - for (auto & p : mPrograms) - { - GLSLProgramCommon* prgm = p.second; - if(prgm->isUsingShader(shader)) - { - OGRE_DELETE prgm; - keysToErase.push_back(p.first); - } - } - - for(unsigned int & i : keysToErase) - { - mPrograms.erase(mPrograms.find(i)); - } - } - - void GLSLProgramManagerCommon::setActiveShader(GpuProgramType type, GLSLShaderCommon* shader) - { - if (mActiveShader[type] != shader) - { - mActiveShader[type] = shader; - // ActiveMonolithicProgram is no longer valid - mActiveProgram = NULL; - } - } - - void GLSLProgramManagerCommon::parseGLSLUniform(String line, GpuNamedConstants& defs, - const String& filename) - { - GpuConstantDefinition def; - String paramName = ""; - - // Remove spaces before opening square braces, otherwise - // the following split() can split the line at inappropriate - // places (e.g. "vec3 something [3]" won't work). - //FIXME What are valid ways of including spaces in GLSL - // variable declarations? May need regex. - for (String::size_type sqp = line.find (" ["); sqp != String::npos; - sqp = line.find (" [")) - line.erase (sqp, 1); - // Split into tokens - StringVector parts = StringUtil::split(line, ", \t\r\n"); - - for (auto & part : parts) - { - // Is this a type? - StringToEnumMap::iterator typei = mTypeEnumMap.find(part); - if (typei != mTypeEnumMap.end()) - { - def.constType = typei->second; - // GL doesn't pad - def.elementSize = GpuConstantDefinition::getElementSize(def.constType, false); - } - else - { - // if this is not a type, and not empty, it should be a name - StringUtil::trim(part); - if (part.empty()) continue; - - // Skip over precision keywords - if(StringUtil::match(part, "lowp") || - StringUtil::match(part, "mediump") || - StringUtil::match(part, "highp")) - continue; - - String::size_type arrayStart = part.find("[", 0); - if (arrayStart != String::npos) - { - // potential name (if butted up to array) - String name = part.substr(0, arrayStart); - StringUtil::trim(name); - if (!name.empty()) - paramName = name; - - def.arraySize = 1; - - // N-dimensional arrays - while (arrayStart != String::npos) { - String::size_type arrayEnd = part.find("]", arrayStart); - String arrayDimTerm = part.substr(arrayStart + 1, arrayEnd - arrayStart - 1); - StringUtil::trim(arrayDimTerm); - //TODO - // the array term might be a simple number or it might be - // an expression (e.g. 24*3) or refer to a constant expression - // we'd have to evaluate the expression which could get nasty - def.arraySize *= StringConverter::parseInt(arrayDimTerm); - arrayStart = part.find("[", arrayEnd); - } - } - else - { - paramName = part; - def.arraySize = 1; - } - - // Name should be after the type, so complete def and add - // We do this now so that comma-separated params will do - // this part once for each name mentioned - if (def.constType == GCT_UNKNOWN) - { - LogManager::getSingleton().logMessage("Problem parsing the following GLSL Uniform: '" - + line + "' in file " + filename, LML_CRITICAL); - // next uniform - break; - } - - // Complete def and add - // increment physical buffer location - def.logicalIndex = 0; // not valid in GLSL - if (def.isFloat() || def.isDouble() || def.isInt() || def.isUnsignedInt() || def.isBool()) - { - def.physicalIndex = defs.bufferSize * 4; - defs.bufferSize += def.arraySize * def.elementSize; - } - else if(def.isSampler()) - { - def.physicalIndex = defs.registerCount; - defs.registerCount += def.arraySize * def.elementSize; - } - else - { - LogManager::getSingleton().logMessage("Could not parse type of GLSL Uniform: '" - + line + "' in file " + filename); - } - defs.map.emplace(paramName, def); - - // warn if there is a default value, that we would overwrite - if (line.find('=') != String::npos) - { - LogManager::getSingleton().logWarning("Default value of uniform '" + paramName + - "' is ignored in " + filename); - break; - } - } - } - } - - //--------------------------------------------------------------------- - static bool findUniformDataSource(const String& paramName, const GpuConstantDefinitionMap* (&constantDefs)[6], - GLUniformReference& refToUpdate) - { - for (int i = 0; i < 6; i++) - { - if (constantDefs[i]) - { - auto parami = constantDefs[i]->find(paramName); - if (parami != constantDefs[i]->end()) - { - refToUpdate.mSourceProgType = static_cast(i); - refToUpdate.mConstantDef = &(parami->second); - return true; - } - } - } - return false; - } - - bool GLSLProgramManagerCommon::validateParam(String paramName, uint32 numActiveArrayElements, - const GpuConstantDefinitionMap* (&constantDefs)[6], - GLUniformReference& refToUpdate) - { - // Don't add built in uniforms, atomic counters, or uniform block parameters. - if (refToUpdate.mLocation < 0) - return false; - - // ATI drivers (Catalyst 7.2 and earlier) and - // older NVidia drivers will include all array - // elements as uniforms but we only want the root - // array name and location. Also note that ATI Catalyst - // 6.8 to 7.2 there is a bug with glUniform that does - // not allow you to update a uniform array past the - // first uniform array element ie you can't start - // updating an array starting at element 1, must - // always be element 0. - - // If the uniform name ends with "]" then its an array element uniform - if (paramName.back() == ']') - { - // if not the first array element then skip it and continue to the next uniform - if (paramName.compare(paramName.size() - 3, 3, "[0]") != 0) - return false; - paramName.resize(paramName.size() - 3); - } - - // Find out which params object this comes from - bool foundSource = findUniformDataSource(paramName, constantDefs, refToUpdate); - - if(!foundSource) - return false; - - // Note that numActiveArrayElements comes from glGetActiveUniformARB() - // which returns the index of the highest active array element (that is - // an element actually used by the shader) plus one. That is, if some array - // elements are not used by the shader (possibly optimized away), then - // numActiveArrayElements can well be less than - // newGLUniformReference.mConstantDef->arraySize. - // Keep in mind that glUniform*v() faimily of functions does allow specifying - // a number of elements to update greater than the number of active - // elements in the shader. - OgreAssertDbg(numActiveArrayElements <= refToUpdate.mConstantDef->arraySize, - "We provide less array elements than what shader actually uses"); - - // Only add this parameter if we found the source - return true; - } - - void GLSLProgramManagerCommon::extractUniformsFromGLSL(const String& src, - GpuNamedConstants& defs, const String& filename) - { - // Parse the output string and collect all uniforms - // NOTE this relies on the source already having been preprocessed - // which is done in GLSLESProgram::loadFromSource - String line; - String::size_type currPos = src.find("uniform"); - while (currPos != String::npos) - { - // Now check for using the word 'uniform' in a larger string & ignore - bool inLargerString = false; - if (currPos != 0) - { - char prev = src.at(currPos - 1); - if (prev != ' ' && prev != '\t' && prev != '\r' && prev != '\n' - && prev != ';') - inLargerString = true; - } - if (!inLargerString && currPos + 7 < src.size()) - { - char next = src.at(currPos + 7); - if (next != ' ' && next != '\t' && next != '\r' && next != '\n') - inLargerString = true; - } - - // skip 'uniform' - currPos += 7; - - if (!inLargerString) - { - String::size_type endPos; - String typeString; - - // Check for a type. If there is one, then the semicolon is missing - // otherwise treat as if it is a uniform block - String::size_type lineEndPos = src.find_first_of("\n\r", currPos); - line = src.substr(currPos, lineEndPos - currPos); - StringVector parts = StringUtil::split(line, " \t"); - - // Skip over precision keywords - if(StringUtil::match((parts.front()), "lowp") || - StringUtil::match((parts.front()), "mediump") || - StringUtil::match((parts.front()), "highp")) - typeString = parts[1]; - else - typeString = parts[0]; - - StringToEnumMap::iterator typei = mTypeEnumMap.find(typeString); - if (typei == mTypeEnumMap.end()) - { - // Gobble up the external name - String externalName = parts.front(); - - // Now there should be an opening brace - String::size_type openBracePos = src.find('{', currPos); - if (openBracePos != String::npos) - { - currPos = openBracePos + 1; - } - else - { - LogManager::getSingleton().logMessage("Missing opening brace in GLSL Uniform Block in file " - + filename); - break; - } - - // First we need to find the internal name for the uniform block - String::size_type endBracePos = src.find('}', currPos); - - // Find terminating semicolon - currPos = endBracePos + 1; - endPos = src.find(';', currPos); - if (endPos == String::npos) - { - // problem, missing semicolon, abort - break; - } - } - else - { - // find terminating semicolon - endPos = src.find(';', currPos); - if (endPos == String::npos) - { - // problem, missing semicolon, abort - break; - } - - parseGLSLUniform(src.substr(currPos, endPos - currPos), defs, filename); - } - line = src.substr(currPos, endPos - currPos); - } // not commented or a larger symbol - - // Find next one - currPos = src.find("uniform", currPos); - } - } -} diff --git a/RenderSystems/GLSupport/src/GLSL/OgreGLSLShaderCommon.cpp b/RenderSystems/GLSupport/src/GLSL/OgreGLSLShaderCommon.cpp deleted file mode 100644 index e4988cfe781..00000000000 --- a/RenderSystems/GLSupport/src/GLSL/OgreGLSLShaderCommon.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreGpuProgram.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" -#include "OgreRenderSystemCapabilities.h" -#include "OgreStringConverter.h" -#include "OgreGpuProgramManager.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreLogManager.h" - -#include "OgreGLSLShaderCommon.h" -#include "OgreGLSLPreprocessor.h" - -namespace Ogre { - //----------------------------------------------------------------------- - uint GLSLShaderCommon::mShaderCount = 0; - - GLSLShaderCommon::CmdAttach GLSLShaderCommon::msCmdAttach; - GLSLShaderCommon::CmdColumnMajorMatrices GLSLShaderCommon::msCmdColumnMajorMatrices; - - String GLSLShaderCommon::getResourceLogName() const - { - if(mLoadFromFile) - return "'" + mFilename + "'"; - return "'"+mName+"'"; - } - - //----------------------------------------------------------------------- - void GLSLShaderCommon::prepareImpl() - { - HighLevelGpuProgram::prepareImpl(); // loads source - - if(mSource.empty()) - return; // nothing to do - - // Preprocess the GLSL shader in order to get a clean source - CPreprocessor cpp; - - // Define "predefined" macros. - if(getLanguage() == "glsles") - cpp.Define("GL_ES", 5, "1", 1); - - size_t versionPos = mSource.find("#version"); - if(versionPos != String::npos) - { - mShaderVersion = StringConverter::parseInt(mSource.substr(versionPos+9, 3)); - } - String verStr = std::to_string(mShaderVersion); - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE - auto rsc = Root::getSingleton().getRenderSystem()->getCapabilities(); - // OSX driver only supports glsl150+ in core profile, GL3+ will auto-upgrade code - if(mShaderVersion < 150 && getLanguage() == "glsl" && rsc->isShaderProfileSupported("glsl150")) - verStr = "150"; -#endif - - cpp.Define("__VERSION__", 11, verStr.c_str(), verStr.size()); - - String defines = appendBuiltinDefines(mPreprocessorDefines); - - for(const auto& def : parseDefines(defines)) - { - cpp.Define(def.first, strlen(def.first), def.second, strlen(def.second)); - } - - // deal with includes - mSource = _resolveIncludes(mSource, this, mFilename); - - size_t out_size = 0; - const char *src = mSource.c_str (); - size_t src_len = mSource.size (); - char *out = cpp.Parse (src, src_len, out_size); - if (!out || !out_size) - // Failed to preprocess, break out - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to preprocess shader " + mName); - - mSource = String (out, out_size); - if (out < src || out > src + src_len) - free (out); - } - //----------------------------------------------------------------------- - GLSLShaderCommon::GLSLShaderCommon(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - : HighLevelGpuProgram(creator, name, handle, group, isManual, loader) - , mColumnMajorMatrices(true) - , mLinked(0) - , mShaderID(++mShaderCount) // Increase shader counter and use as ID - , mGLShaderHandle(0) - , mGLProgramHandle(0) - , mShaderVersion(100) - { - } - //----------------------------------------------------------------------- - String GLSLShaderCommon::CmdAttach::doGet(const void *target) const - { - return (static_cast(target))->getAttachedShaderNames(); - } - //----------------------------------------------------------------------- - void GLSLShaderCommon::CmdAttach::doSet(void *target, const String& shaderNames) - { - //get all the shader program names: there could be more than one - StringVector vecShaderNames = StringUtil::split(shaderNames, " \t", 0); - - size_t programNameCount = vecShaderNames.size(); - for ( size_t i = 0; i < programNameCount; ++i ) - { - static_cast(target)->attachChildShader(vecShaderNames[i]); - } - } - //----------------------------------------------------------------------- - void GLSLShaderCommon::attachChildShader(const String& name) - { - // is the name valid and already loaded? - // check with the high level program manager to see if it was loaded - HighLevelGpuProgramPtr hlProgram = HighLevelGpuProgramManager::getSingleton().getByName( - name, ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME); - if (hlProgram && hlProgram->getSyntaxCode() == "glsl") - { - // make sure attached program source gets loaded and compiled - // don't need a low level implementation for attached shader objects - // loadHighLevel will only load the source and compile once - // so don't worry about calling it several times - GLSLShaderCommon* childShader = static_cast(hlProgram.get()); - // load the source and attach the child shader only if supported - if (isSupported()) - { - childShader->safePrepare(); - childShader->loadHighLevel(); - // add to the container - mAttachedGLSLPrograms.push_back( childShader ); - mAttachedShaderNames += name + " "; - } - } - } - //----------------------------------------------------------------------- - String GLSLShaderCommon::CmdColumnMajorMatrices::doGet(const void *target) const - { - return StringConverter::toString(static_cast(target)->getColumnMajorMatrices()); - } - void GLSLShaderCommon::CmdColumnMajorMatrices::doSet(void *target, const String& val) - { - static_cast(target)->setColumnMajorMatrices(StringConverter::parseBool(val)); - } -} diff --git a/RenderSystems/GLSupport/src/GLX/OgreGLXContext.cpp b/RenderSystems/GLSupport/src/GLX/OgreGLXContext.cpp deleted file mode 100644 index 9ff22c6afa4..00000000000 --- a/RenderSystems/GLSupport/src/GLX/OgreGLXContext.cpp +++ /dev/null @@ -1,88 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGLRenderSystemCommon.h" -#include "OgreRoot.h" -#include "OgreGLXContext.h" -#include "OgreGLXGLSupport.h" - -namespace Ogre -{ - GLXContext::GLXContext(GLXGLSupport* glsupport, ::GLXFBConfig fbconfig, ::GLXDrawable drawable, ::GLXContext context) : - mDrawable(drawable), mContext(0), mFBConfig(fbconfig), mGLSupport(glsupport), mExternalContext(false) - { - GLRenderSystemCommon *renderSystem = static_cast(Root::getSingleton().getRenderSystem()); - GLXContext* mainContext = static_cast(renderSystem->_getMainContext()); - ::GLXContext shareContext = 0; - - if (mainContext) - { - shareContext = mainContext->mContext; - } - - if (context) - { - mContext = context; - mExternalContext = true; - } - else - { - mContext = mGLSupport->createNewContext(mFBConfig, GLX_RGBA_TYPE, shareContext, GL_TRUE); - } - - if (! mContext) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to create a suitable GLXContext", "GLXContext::GLXContext"); - } - } - - GLXContext::~GLXContext() - { - GLRenderSystemCommon *rs = static_cast(Root::getSingleton().getRenderSystem()); - - if (!mExternalContext) - glXDestroyContext(mGLSupport->getGLDisplay(), mContext); - - rs->_unregisterContext(this); - } - - void GLXContext::setCurrent() - { - glXMakeCurrent(mGLSupport->getGLDisplay(), mDrawable, mContext); - } - - void GLXContext::endCurrent() - { - glXMakeCurrent(mGLSupport->getGLDisplay(), None, None); - } - - GLContext* GLXContext::clone() const - { - return new GLXContext(mGLSupport, mFBConfig, mDrawable); - } -} diff --git a/RenderSystems/GLSupport/src/GLX/OgreGLXGLSupport.cpp b/RenderSystems/GLSupport/src/GLX/OgreGLXGLSupport.cpp deleted file mode 100644 index 7b056f0f78f..00000000000 --- a/RenderSystems/GLSupport/src/GLX/OgreGLXGLSupport.cpp +++ /dev/null @@ -1,655 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" - -#include "OgreGLXGLSupport.h" -#include "OgreGLXWindow.h" -#include "OgreGLXRenderTexture.h" - -#include "OgreGLUtil.h" - -#include "OgreX11.h" - -#include - -static bool ctxErrorOccurred = false; -static Ogre::String ctxErrorMessage; -static int ctxErrorHandler( Display *dpy, XErrorEvent *ev ) -{ - char buffer[512] = {0}; - ctxErrorOccurred = true; - - XGetErrorText(dpy, ev->error_code, buffer, 512); - ctxErrorMessage = Ogre::String(buffer); - return 0; -} - -namespace Ogre -{ - struct GLXVideoMode - { - typedef std::pair ScreenSize; - typedef short Rate; - ScreenSize first; - Rate second; - - GLXVideoMode() {} - GLXVideoMode(const VideoMode& m) : first(m.width, m.height), second(m.refreshRate) {} - - bool operator!=(const GLXVideoMode& o) const - { - return first != o.first || second != o.second; - } - }; - typedef std::vector GLXVideoModes; - - GLNativeSupport* getGLSupport(int profile) - { - return new GLXGLSupport(profile); - } - - //-------------------------------------------------------------------------------------------------// - GLXGLSupport::GLXGLSupport(int profile) : GLNativeSupport(profile), mGLDisplay(0), mXDisplay(0) - { - // A connection that might be shared with the application for GL rendering: - mGLDisplay = getGLDisplay(); - - // A connection that is NOT shared to enable independent event processing: - mXDisplay = getXDisplay(); - - getXVideoModes(mXDisplay, mCurrentMode, mVideoModes); - - if(mVideoModes.empty()) - { - mCurrentMode.width = DisplayWidth(mXDisplay, DefaultScreen(mXDisplay)); - mCurrentMode.height = DisplayHeight(mXDisplay, DefaultScreen(mXDisplay)); - mCurrentMode.refreshRate = 0; - - mVideoModes.push_back(mCurrentMode); - } - - mOriginalMode = mCurrentMode; - - GLXFBConfig *fbConfigs; - int config, nConfigs = 0; - - fbConfigs = chooseFBConfig(NULL, &nConfigs); - - for (config = 0; config < nConfigs; config++) - { - int caveat, samples; - - getFBConfigAttrib (fbConfigs[config], GLX_CONFIG_CAVEAT, &caveat); - - if (caveat != GLX_SLOW_CONFIG) - { - getFBConfigAttrib (fbConfigs[config], GLX_SAMPLES, &samples); - mFSAALevels.push_back(samples); - } - } - - XFree (fbConfigs); - } - - //-------------------------------------------------------------------------------------------------// - GLXGLSupport::~GLXGLSupport() - { - if (mXDisplay) - XCloseDisplay(mXDisplay); - - if (! mIsExternalDisplay && mGLDisplay) - XCloseDisplay(mGLDisplay); - } - - //-------------------------------------------------------------------------------------------------// - RenderWindow* GLXGLSupport::newWindow(const String &name, unsigned int width, unsigned int height, bool fullScreen, const NameValuePairList *miscParams) - { - GLXWindow* window = new GLXWindow(this); - - window->create(name, width, height, fullScreen, miscParams); - - return window; - } - - //-------------------------------------------------------------------------------------------------// - GLPBuffer *GLXGLSupport::createPBuffer(PixelComponentType format, size_t width, size_t height) - { - return new GLXPBuffer(this, format, width, height); - } - - //-------------------------------------------------------------------------------------------------// - void GLXGLSupport::start() - { - LogManager::getSingleton().logMessage( - "******************************\n" - "*** Starting GLX Subsystem ***\n" - "******************************"); - initialiseExtensions(); - } - - //-------------------------------------------------------------------------------------------------// - void GLXGLSupport::stop() - { - LogManager::getSingleton().logMessage( - "******************************\n" - "*** Stopping GLX Subsystem ***\n" - "******************************"); - } - - //-------------------------------------------------------------------------------------------------// - void* GLXGLSupport::getProcAddress(const char* procname) const { - return (void*)glXGetProcAddressARB((const GLubyte*)procname); - } - - //-------------------------------------------------------------------------------------------------// - void GLXGLSupport::initialiseExtensions() - { - assert (mGLDisplay); - - mGLXVerMajor = mGLXVerMinor = 0; - glXQueryVersion(mGLDisplay, &mGLXVerMajor, &mGLXVerMinor); - - const char* verStr = glXGetClientString(mGLDisplay, GLX_VERSION); - LogManager::getSingleton().stream() << "GLX_VERSION = " << verStr; - - const char* extensionsString; - - // This is more realistic than using glXGetClientString: - extensionsString = glXGetClientString(mGLDisplay, GLX_EXTENSIONS); - - LogManager::getSingleton().stream() << "GLX_EXTENSIONS = " << extensionsString; - - StringStream ext; - String instr; - - ext << extensionsString; - - while(ext >> instr) - { - extensionList.insert(instr); - } - } - - //-------------------------------------------------------------------------------------------------// - // Returns the FBConfig behind a GLXContext - - GLXFBConfig GLXGLSupport::getFBConfigFromContext(::GLXContext context) - { - GLXFBConfig fbConfig = 0; - - int fbConfigAttrib[] = { - GLX_FBCONFIG_ID, 0, - None - }; - GLXFBConfig *fbConfigs; - int nElements = 0; - - glXQueryContext(mGLDisplay, context, GLX_FBCONFIG_ID, &fbConfigAttrib[1]); - fbConfigs = glXChooseFBConfig(mGLDisplay, DefaultScreen(mGLDisplay), fbConfigAttrib, &nElements); - - if (nElements) - { - fbConfig = fbConfigs[0]; - XFree(fbConfigs); - } - - return fbConfig; - } - - //-------------------------------------------------------------------------------------------------// - // Returns the FBConfig behind a GLXDrawable, or returns 0 when - // missing GLX_SGIX_fbconfig and drawable is Window (unlikely), OR - // missing GLX_VERSION_1_3 and drawable is a GLXPixmap (possible). - - GLXFBConfig GLXGLSupport::getFBConfigFromDrawable(GLXDrawable drawable, unsigned int *width, unsigned int *height) - { - GLXFBConfig fbConfig = 0; - - int fbConfigAttrib[] = { - GLX_FBCONFIG_ID, 0, - None - }; - GLXFBConfig *fbConfigs; - int nElements = 0; - - glXQueryDrawable (mGLDisplay, drawable, GLX_FBCONFIG_ID, (unsigned int*)&fbConfigAttrib[1]); - - fbConfigs = glXChooseFBConfig(mGLDisplay, DefaultScreen(mGLDisplay), fbConfigAttrib, &nElements); - - if (nElements) - { - fbConfig = fbConfigs[0]; - XFree (fbConfigs); - - glXQueryDrawable(mGLDisplay, drawable, GLX_WIDTH, width); - glXQueryDrawable(mGLDisplay, drawable, GLX_HEIGHT, height); - } - - if (! fbConfig) - { - XWindowAttributes windowAttrib; - - if (XGetWindowAttributes(mGLDisplay, drawable, &windowAttrib)) - { - VisualID visualid = XVisualIDFromVisual(windowAttrib.visual); - - fbConfig = getFBConfigFromVisualID(visualid); - - *width = windowAttrib.width; - *height = windowAttrib.height; - } - } - - return fbConfig; - } - - //-------------------------------------------------------------------------------------------------// - // Finds a GLXFBConfig compatible with a given VisualID. - - GLXFBConfig GLXGLSupport::getFBConfigFromVisualID(VisualID visualid) - { - PFNGLXGETFBCONFIGFROMVISUALSGIXPROC glXGetFBConfigFromVisualSGIX = - (PFNGLXGETFBCONFIGFROMVISUALSGIXPROC)getProcAddress("glXGetFBConfigFromVisualSGIX"); - - GLXFBConfig fbConfig = 0; - - XVisualInfo visualInfo; - - visualInfo.screen = DefaultScreen(mGLDisplay); - visualInfo.depth = DefaultDepth(mGLDisplay, DefaultScreen(mGLDisplay)); - visualInfo.visualid = visualid; - - fbConfig = glXGetFBConfigFromVisualSGIX(mGLDisplay, &visualInfo); - - if (! fbConfig) - { - int minAttribs[] = { - GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, - GLX_RENDER_TYPE, GLX_RGBA_BIT, - GLX_RED_SIZE, 1, - GLX_BLUE_SIZE, 1, - GLX_GREEN_SIZE, 1, - None - }; - int nConfigs = 0; - - GLXFBConfig *fbConfigs = chooseFBConfig(minAttribs, &nConfigs); - - for (int i = 0; i < nConfigs && ! fbConfig; i++) - { - XVisualInfo *vInfo = getVisualFromFBConfig(fbConfigs[i]); - - if (vInfo ->visualid == visualid) - fbConfig = fbConfigs[i]; - - XFree(vInfo ); - } - - XFree(fbConfigs); - } - - return fbConfig; - } - - //-------------------------------------------------------------------------------------------------// - // A helper class for the implementation of selectFBConfig - - class FBConfigAttribs - { - public: - FBConfigAttribs(const int* attribs) - { - fields[GLX_CONFIG_CAVEAT] = GLX_NONE; - - for (int i = 0; attribs[2*i]; i++) - { - fields[attribs[2*i]] = attribs[2*i+1]; - } - } - - void load(GLXGLSupport* const glSupport, GLXFBConfig fbConfig) - { - std::map::iterator it; - - for (it = fields.begin(); it != fields.end(); it++) - { - it->second = 0; - - glSupport->getFBConfigAttrib(fbConfig, it->first, &it->second); - } - } - - bool operator>(FBConfigAttribs& alternative) - { - // Caveats are best avoided, but might be needed for anti-aliasing - - if (fields[GLX_CONFIG_CAVEAT] != alternative.fields[GLX_CONFIG_CAVEAT]) - { - if (fields[GLX_CONFIG_CAVEAT] == GLX_SLOW_CONFIG) - return false; - - if (fields.find(GLX_SAMPLES) != fields.end() && - fields[GLX_SAMPLES] < alternative.fields[GLX_SAMPLES]) - return false; - } - - std::map::iterator it; - - for (it = fields.begin(); it != fields.end(); it++) - { - if (it->first != GLX_CONFIG_CAVEAT && fields[it->first] > alternative.fields[it->first]) - return true; - } - - return false; - } - - std::map fields; - }; - - //-------------------------------------------------------------------------------------------------// - // Finds an FBConfig that possesses each of minAttribs and gets as close - // as possible to each of the maxAttribs without exceeding them. - // Resembles glXChooseFBConfig, but is forgiving to platforms - // that do not support the attributes listed in the maxAttribs. - - GLXFBConfig GLXGLSupport::selectFBConfig (const int* minAttribs, const int *maxAttribs) - { - GLXFBConfig *fbConfigs; - GLXFBConfig fbConfig = 0; - int config, nConfigs = 0; - - fbConfigs = chooseFBConfig(minAttribs, &nConfigs); - - // this is a fix for cases where chooseFBConfig is not supported. - // On the 10/2010 chooseFBConfig was not supported on VirtualBox - // http://www.virtualbox.org/ticket/7195 - if (!nConfigs) - { - fbConfigs = glXGetFBConfigs(mGLDisplay, DefaultScreen(mGLDisplay), &nConfigs); - } - - if (! nConfigs) - return 0; - - fbConfig = fbConfigs[0]; - - if (maxAttribs) - { - FBConfigAttribs maximum(maxAttribs); - FBConfigAttribs best(maxAttribs); - FBConfigAttribs candidate(maxAttribs); - - best.load(this, fbConfig); - - for (config = 1; config < nConfigs; config++) - { - candidate.load(this, fbConfigs[config]); - - if (candidate > maximum) - continue; - - if (candidate > best) - { - fbConfig = fbConfigs[config]; - - best.load(this, fbConfig); - } - } - } - - XFree (fbConfigs); - return fbConfig; - } - - //-------------------------------------------------------------------------------------------------// - Display* GLXGLSupport::getGLDisplay(void) - { - if (! mGLDisplay) - { - // glXGetCurrentDisplay = (PFNGLXGETCURRENTDISPLAYPROC)getProcAddress("glXGetCurrentDisplay"); - - mGLDisplay = glXGetCurrentDisplay(); - mIsExternalDisplay = true; - - if (! mGLDisplay) - { - mGLDisplay = XOpenDisplay(0); - mIsExternalDisplay = false; - } - - if(! mGLDisplay) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn`t open X display " + String((const char*)XDisplayName (0)), "GLXGLSupport::getGLDisplay"); - } - } - - return mGLDisplay; - } - - //-------------------------------------------------------------------------------------------------// - Display* GLXGLSupport::getXDisplay(void) - { - if (! mXDisplay) - { - char* displayString = mGLDisplay ? DisplayString(mGLDisplay) : 0; - - mXDisplay = XOpenDisplay(displayString); - - if (! mXDisplay) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn`t open X display " + String((const char*)displayString), "GLXGLSupport::getXDisplay"); - } - - mAtomDeleteWindow = XInternAtom(mXDisplay, "WM_DELETE_WINDOW", True); - mAtomFullScreen = XInternAtom(mXDisplay, "_NET_WM_STATE_FULLSCREEN", True); - mAtomState = XInternAtom(mXDisplay, "_NET_WM_STATE", True); - } - - return mXDisplay; - } - - //-------------------------------------------------------------------------------------------------// - GLXFBConfig* GLXGLSupport::chooseFBConfig(const GLint *attribList, GLint *nElements) - { - GLXFBConfig *fbConfigs; - - fbConfigs = glXChooseFBConfig(mGLDisplay, DefaultScreen(mGLDisplay), attribList, nElements); - - return fbConfigs; - } - - //-------------------------------------------------------------------------------------------------// - ::GLXContext GLXGLSupport::createNewContext(GLXFBConfig fbConfig, GLint renderType, ::GLXContext shareList, GLboolean direct) const - { - ::GLXContext glxContext = NULL; - - int profile; - int majorVersion; - int minorVersion = 0; - - switch(mContextProfile) { - case CONTEXT_COMPATIBILITY: - profile = GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; - majorVersion = 1; - break; - case CONTEXT_ES: - profile = GLX_CONTEXT_ES2_PROFILE_BIT_EXT; - majorVersion = 2; - break; - default: - profile = GLX_CONTEXT_CORE_PROFILE_BIT_ARB; - majorVersion = 3; - minorVersion = 3; // 3.1 would be sufficient per spec, but we need 3.3 anyway.. - break; - } - - int context_attribs[] = { - GLX_CONTEXT_MAJOR_VERSION_ARB, majorVersion, - GLX_CONTEXT_MINOR_VERSION_ARB, minorVersion, - GLX_CONTEXT_PROFILE_MASK_ARB, profile, - None - }; - - ctxErrorOccurred = false; - int (*oldHandler)(Display*, XErrorEvent*) = - XSetErrorHandler(&ctxErrorHandler); - - PFNGLXCREATECONTEXTATTRIBSARBPROC _glXCreateContextAttribsARB; - _glXCreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC)getProcAddress("glXCreateContextAttribsARB"); - - if(_glXCreateContextAttribsARB) - { - // find maximal supported context version - context_attribs[1] = 4; - context_attribs[3] = 6; - while(!glxContext && - ((context_attribs[1] > majorVersion) || - (context_attribs[1] == majorVersion && context_attribs[3] >= minorVersion))) - { - ctxErrorOccurred = false; - glxContext = _glXCreateContextAttribsARB(mGLDisplay, fbConfig, shareList, direct, context_attribs); - context_attribs[1] -= context_attribs[3] == 0; // only decrement if minor == 0 - context_attribs[3] = (context_attribs[3] - 1 + 7) % 7; // decrement: -1 -> 6 - } - } - else - { - // try old style context creation as a last resort - // Needed at least by MESA 8.0.4 on Ubuntu 12.04. - if (mContextProfile != CONTEXT_COMPATIBILITY) { - ctxErrorMessage = "Can not set a context profile"; - } else { - glxContext = - glXCreateNewContext(mGLDisplay, fbConfig, renderType, shareList, direct); - } - } - - // Sync to ensure any errors generated are processed. - XSync( mGLDisplay, False ); - - // Restore the original error handler - XSetErrorHandler( oldHandler ); - - if (ctxErrorOccurred || !glxContext) - { - LogManager::getSingleton().logError("Failed to create an OpenGL context - " + ctxErrorMessage); - } - - return glxContext; - } - - //-------------------------------------------------------------------------------------------------// - GLint GLXGLSupport::getFBConfigAttrib(GLXFBConfig fbConfig, GLint attribute, GLint *value) - { - GLint status; - - status = glXGetFBConfigAttrib(mGLDisplay, fbConfig, attribute, value); - - return status; - } - - //-------------------------------------------------------------------------------------------------// - XVisualInfo* GLXGLSupport::getVisualFromFBConfig(GLXFBConfig fbConfig) - { - XVisualInfo *visualInfo; - - visualInfo = glXGetVisualFromFBConfig(mGLDisplay, fbConfig); - - return visualInfo; - } - - //-------------------------------------------------------------------------------------------------// - void GLXGLSupport::switchMode(uint& width, uint& height, short& frequency) - { - int size = 0; - int newSize = -1; - - GLXVideoModes glxVideoModes(mVideoModes.begin(), mVideoModes.end()); - - GLXVideoModes::iterator mode; - GLXVideoModes::iterator end = glxVideoModes.end(); - GLXVideoMode *newMode = 0; - - for(mode = glxVideoModes.begin(); mode != end; size++) - { - if (mode->first.first >= width && - mode->first.second >= height) - { - if (! newMode || - mode->first.first < newMode->first.first || - mode->first.second < newMode->first.second) - { - newSize = size; - newMode = &(*mode); - } - } - - GLXVideoMode *lastMode = &(*mode); - - while (++mode != end && mode->first == lastMode->first) - { - if (lastMode == newMode && mode->second == frequency) - { - newMode = &(*mode); - } - } - } - - if (newMode && *newMode != mCurrentMode) - { - XRRScreenConfiguration *screenConfig = XRRGetScreenInfo (mXDisplay, DefaultRootWindow(mXDisplay)); - - if (screenConfig) - { - Rotation currentRotation; - - XRRConfigCurrentConfiguration (screenConfig, ¤tRotation); - - XRRSetScreenConfigAndRate(mXDisplay, screenConfig, DefaultRootWindow(mXDisplay), newSize, currentRotation, newMode->second, CurrentTime); - - XRRFreeScreenConfigInfo(screenConfig); - - mCurrentMode = {newMode->first.first, newMode->first.second, newMode->second}; - - LogManager::getSingleton().logMessage("Entered video mode " + mCurrentMode.getDescription() + " @ " + StringConverter::toString(mCurrentMode.refreshRate) + "Hz"); - } - } - } - - //-------------------------------------------------------------------------------------------------// - void GLXGLSupport::switchMode(void) - { - return switchMode(mOriginalMode.width, mOriginalMode.height, mOriginalMode.refreshRate); - } -} diff --git a/RenderSystems/GLSupport/src/GLX/OgreGLXRenderTexture.cpp b/RenderSystems/GLSupport/src/GLX/OgreGLXRenderTexture.cpp deleted file mode 100644 index e4dc8a1c868..00000000000 --- a/RenderSystems/GLSupport/src/GLX/OgreGLXRenderTexture.cpp +++ /dev/null @@ -1,167 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreRoot.h" -#include "OgreStringConverter.h" - -#include "OgreGLXRenderTexture.h" -#include "OgreGLXContext.h" -#include "OgreGLXGLSupport.h" - -#include - -#define GLX_RGBA_FLOAT_ATI_BIT 0x00000100 -#define GLX_RGBA_FLOAT_BIT 0x00000004 - -namespace Ogre -{ - //-------------------------------------------------------------------------------------------------// - GLXPBuffer::GLXPBuffer(GLXGLSupport* glsupport, PixelComponentType format, size_t width, size_t height): - GLPBuffer(format, width, height), mContext(0), mGLSupport(glsupport) - { - Display *glDisplay = mGLSupport->getGLDisplay(); - ::GLXDrawable glxDrawable = 0; - ::GLXFBConfig fbConfig = 0; - - int bits = 0; - - switch (mFormat) - { - case PCT_BYTE: - bits = 8; - break; - - case PCT_SHORT: - bits = 16; - break; - - case PCT_FLOAT16: - bits = 16; - break; - - case PCT_FLOAT32: - bits = 32; - break; - - default: - break; - } - - int renderAttrib = GLX_RENDER_TYPE; - int renderValue = GLX_RGBA_BIT; - - if (mFormat == PCT_FLOAT16 || mFormat == PCT_FLOAT32) - { - if (glsupport->checkExtension("GLX_NV_float_buffer")) - { - renderAttrib = GLX_FLOAT_COMPONENTS_NV; - renderValue = GL_TRUE; - } - - if (glsupport->checkExtension("GLX_ATI_pixel_format_float")) - { - renderAttrib = GLX_RENDER_TYPE; - renderValue = GLX_RGBA_FLOAT_ATI_BIT; - } - - if (glsupport->checkExtension("GLX_ARB_fbconfig_float")) - { - renderAttrib = GLX_RENDER_TYPE; - renderValue = GLX_RGBA_FLOAT_BIT; - } - - if (renderAttrib == GLX_RENDER_TYPE && renderValue == GLX_RGBA_BIT) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "No support for Floating point PBuffers", "GLRenderTexture::createPBuffer"); - } - } - - int minAttribs[] = { - GLX_DRAWABLE_TYPE, GLX_PBUFFER, - renderAttrib, renderValue, - GLX_DOUBLEBUFFER, 0, - None - }; - - int maxAttribs[] = { - GLX_RED_SIZE, bits, - GLX_GREEN_SIZE, bits, - GLX_BLUE_SIZE, bits, - GLX_ALPHA_SIZE, bits, - GLX_STENCIL_SIZE, INT_MAX, - None - }; - - int pBufferAttribs[] = { - GLX_PBUFFER_WIDTH, (int)mWidth, - GLX_PBUFFER_HEIGHT, (int)mHeight, - GLX_PRESERVED_CONTENTS, GL_TRUE, - None - }; - - fbConfig = mGLSupport->selectFBConfig(minAttribs, maxAttribs); - - glxDrawable = glXCreatePbuffer(glDisplay, fbConfig, pBufferAttribs); - - if (! fbConfig || ! glxDrawable) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to create Pbuffer", "GLXPBuffer::GLXPBuffer"); - } - - GLint fbConfigID; - GLuint iWidth, iHeight; - - glXGetFBConfigAttrib(glDisplay, fbConfig, GLX_FBCONFIG_ID, &fbConfigID); - glXQueryDrawable(glDisplay, glxDrawable, GLX_WIDTH, &iWidth); - glXQueryDrawable(glDisplay, glxDrawable, GLX_HEIGHT, &iHeight); - - mWidth = iWidth; - mHeight = iHeight; - LogManager::getSingleton().logMessage(LML_NORMAL, "GLXPBuffer::create used final dimensions " + StringConverter::toString(mWidth) + " x " + StringConverter::toString(mHeight)); - LogManager::getSingleton().logMessage("GLXPBuffer::create used FBConfigID " + StringConverter::toString(fbConfigID)); - - mContext = new GLXContext(mGLSupport, fbConfig, glxDrawable); - } - - //-------------------------------------------------------------------------------------------------// - GLXPBuffer::~GLXPBuffer() - { - glXDestroyPbuffer(mGLSupport->getGLDisplay(), mContext->mDrawable); - - delete mContext; - - LogManager::getSingleton().logMessage(LML_NORMAL, "GLXPBuffer::PBuffer destroyed"); - } - - //-------------------------------------------------------------------------------------------------// - GLContext *GLXPBuffer::getContext() const - { - return mContext; - } -} diff --git a/RenderSystems/GLSupport/src/GLX/OgreGLXWindow.cpp b/RenderSystems/GLSupport/src/GLX/OgreGLXWindow.cpp deleted file mode 100644 index 14a10b3f760..00000000000 --- a/RenderSystems/GLSupport/src/GLX/OgreGLXWindow.cpp +++ /dev/null @@ -1,556 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGLXWindow.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" -#include "OgreImageCodec.h" -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreViewport.h" - -#include "OgreGLXContext.h" -#include "OgreGLXGLSupport.h" -#include "OgreX11.h" - -#include - -namespace Ogre -{ - //-------------------------------------------------------------------------------------------------// - GLXWindow::GLXWindow(GLXGLSupport *glsupport) : GLWindow(), - mGLSupport(glsupport) - { - mWindow = 0; - } - - //-------------------------------------------------------------------------------------------------// - GLXWindow::~GLXWindow() - { - Display* xDisplay = mGLSupport->getXDisplay(); - - destroy(); - - if (mWindow && mIsTopLevel) - { - destroyXWindow(xDisplay, mWindow); - } - - if (mContext) - { - delete mContext; - } - - mContext = 0; - mWindow = 0; - } - - //-------------------------------------------------------------------------------------------------// - void GLXWindow::create(const String& name, uint width, uint height, - bool fullScreen, const NameValuePairList *miscParams) - { - Display *xDisplay = mGLSupport->getXDisplay(); - String title = name; - uint samples = 0; - short frequency = 0; - bool vsync = false; - bool hidden = false; - unsigned int vsyncInterval = 1; - bool gamma = false; - ::GLXContext glxContext = 0; - ::GLXDrawable glxDrawable = 0; - Window parentWindow = DefaultRootWindow(xDisplay); - int left = DisplayWidth(xDisplay, DefaultScreen(xDisplay))/2 - width/2; - int top = DisplayHeight(xDisplay, DefaultScreen(xDisplay))/2 - height/2; - - int minBufferSize = 16; - - mIsFullScreen = fullScreen; - - if(miscParams) - { - NameValuePairList::const_iterator opt; - NameValuePairList::const_iterator end = miscParams->end(); - - // NB: Do not try to implement the externalGLContext option. - // - // Accepting a non-current context would expose us to the - // risk of segfaults when we made it current. Since the - // application programmers would be responsible for these - // segfaults, they are better discovering them in their code. - - if ((opt = miscParams->find("currentGLContext")) != end && - StringConverter::parseBool(opt->second)) - { - glxContext = glXGetCurrentContext(); - - if (!glxContext) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "currentGLContext was specified with no current GL context", "GLXWindow::create"); - } - - glxDrawable = glXGetCurrentDrawable(); - } - - // Note: Some platforms support AA inside ordinary windows - if((opt = miscParams->find("FSAA")) != end) - samples = StringConverter::parseUnsignedInt(opt->second); - - if( (opt = miscParams->find("displayFrequency")) != end && opt->second != "N/A" ) - frequency = (short)StringConverter::parseInt(opt->second); - - if((opt = miscParams->find("vsync")) != end) - vsync = StringConverter::parseBool(opt->second); - - if((opt = miscParams->find("hidden")) != end) - hidden = StringConverter::parseBool(opt->second); - - if((opt = miscParams->find("vsyncInterval")) != end) - vsyncInterval = StringConverter::parseUnsignedInt(opt->second); - - if ((opt = miscParams->find("gamma")) != end) - gamma = StringConverter::parseBool(opt->second); - - if((opt = miscParams->find("left")) != end) - left = StringConverter::parseInt(opt->second); - - if((opt = miscParams->find("top")) != end) - top = StringConverter::parseInt(opt->second); - - if((opt = miscParams->find("title")) != end) - title = opt->second; - - if((opt = miscParams->find("minColourBufferSize")) != end) - minBufferSize = StringConverter::parseInt(opt->second); - - if ((opt = miscParams->find("externalGLControl")) != end) - mIsExternalGLControl = StringConverter::parseBool(opt->second); - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - if ((opt = miscParams->find("stereoMode")) != end) - { - mStereoEnabled = StringConverter::parseBool(opt->second); - } -#endif - - if ((opt = miscParams->find("parentWindowHandle")) != end || - (opt = miscParams->find("externalWindowHandle")) != end) - { - std::vector tokens = StringUtil::split(opt->second, " :"); - - if (tokens.size() >= 3) - { - // deprecated display:screen:xid:visualinfo format - StringConverter::parse(tokens[2], parentWindow); - } - else - { - // xid format - StringConverter::parse(tokens[0], parentWindow); - } - - // reset drawable in case currentGLContext was used - // it should be queried from the parentWindow - glxDrawable = 0; - } - } - - validateParentWindow(xDisplay, parentWindow); - - // Derive fbConfig - ::GLXFBConfig fbConfig = 0; - - if (glxDrawable) - { - fbConfig = mGLSupport->getFBConfigFromDrawable (glxDrawable, &width, &height); - } - - if (! fbConfig && glxContext) - { - fbConfig = mGLSupport->getFBConfigFromContext (glxContext); - } - - mIsExternal = (glxDrawable != 0); - - if (! fbConfig) - { - int minComponentSize = minBufferSize; - int maxComponentSize = 8; - - bool fourComponents = (minBufferSize % 3) != 0; - minComponentSize /= fourComponents ? 4 : 3; - - if(minComponentSize > maxComponentSize) - maxComponentSize = minComponentSize; - - int minAttribs[] = { - GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, - GLX_RENDER_TYPE, GLX_RGBA_BIT, - GLX_RED_SIZE, minComponentSize, - GLX_BLUE_SIZE, minComponentSize, - GLX_GREEN_SIZE, minComponentSize, - GLX_ALPHA_SIZE, fourComponents ? minComponentSize : 0, -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - GLX_STEREO, mStereoEnabled ? True : False, -#endif - GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT, gamma, - None - }; - - int maxAttribs[] = { - GLX_SAMPLES, static_cast(samples), - GLX_RED_SIZE, maxComponentSize, - GLX_BLUE_SIZE, maxComponentSize, - GLX_GREEN_SIZE, maxComponentSize, - GLX_ALPHA_SIZE, fourComponents ? maxComponentSize : 0, - GLX_DOUBLEBUFFER, 1, - GLX_STENCIL_SIZE, INT_MAX, - GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT, 1, - None - }; - - fbConfig = mGLSupport->selectFBConfig(minAttribs, maxAttribs); - } - - // This should never happen. - if(!fbConfig) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unexpected failure to determine a GLXFBConfig"); - - - // Now check the actual fsaa and gamma value - - GLint fsaa; - mGLSupport->getFBConfigAttrib(fbConfig, GLX_SAMPLES, &fsaa); - mFSAA = fsaa; - - if (gamma) - { - int val = 0; - gamma = mGLSupport->getFBConfigAttrib(fbConfig, GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT, &val) == 0; - gamma = gamma && val; // can an supported extension return 0? lets rather be safe.. - } - mHwGamma = gamma; - - int bufferSize = 0; - for(int i = GLX_RED_SIZE; i < GLX_ALPHA_SIZE + 1; i++) - { - int val = 0; - mGLSupport->getFBConfigAttrib(fbConfig, i, &val); - bufferSize += val; - } - - LogManager::getSingleton().logMessage(StringUtil::format( - "GLXWindow::create colourBufferSize=%d gamma=%d FSAA=%d", bufferSize, mHwGamma, fsaa)); - - mIsTopLevel = (! mIsExternal && parentWindow == DefaultRootWindow(xDisplay)); - - if (! mIsTopLevel) - { - mIsFullScreen = false; - left = top = 0; - } - - if (mIsFullScreen) - { - mGLSupport->switchMode (width, height, frequency); - } - - if (! mIsExternal) - { - XVisualInfo *visualInfo = mGLSupport->getVisualFromFBConfig (fbConfig); - - // Create window on server - mWindow = createXWindow(xDisplay, parentWindow, visualInfo, left, top, width, height, mGLSupport->mAtomFullScreen, mIsFullScreen); - - if (mIsTopLevel) - { - finaliseTopLevel(xDisplay, mWindow, left, top, width, height, title, mGLSupport->mAtomDeleteWindow); - } - - glxDrawable = mWindow; - - // setHidden takes care of mapping or unmapping the window - // and also calls setFullScreen if appropriate. - setHidden(hidden); - XFlush(xDisplay); - } - - mContext = new GLXContext(mGLSupport, fbConfig, glxDrawable, glxContext); - - // apply vsync settings. call setVSyncInterval first to avoid - // setting vsync more than once. - setVSyncInterval(vsyncInterval); - setVSyncEnabled(vsync); - - int fbConfigID; - - mGLSupport->getFBConfigAttrib(fbConfig, GLX_FBCONFIG_ID, &fbConfigID); - - LogManager::getSingleton().logMessage("GLXWindow::create used FBConfigID = " + StringConverter::toString(fbConfigID)); - - mName = name; - mWidth = width; - mHeight = height; - mLeft = left; - mTop = top; - mActive = true; - mClosed = false; - mVisible = true; - } - - //-------------------------------------------------------------------------------------------------// - void GLXWindow::destroy(void) - { - if (mClosed) - return; - - mClosed = true; - mActive = false; - - if (mIsFullScreen) - { - mGLSupport->switchMode(); - switchFullScreen(false); - } - } - - //-------------------------------------------------------------------------------------------------// - void GLXWindow::setFullscreen(bool fullscreen, uint width, uint height) - { - short frequency = 0; - - if (mClosed || ! mIsTopLevel) - return; - - if (fullscreen == mIsFullScreen && width == mWidth && height == mHeight) - return; - - if (mIsFullScreen != fullscreen && mGLSupport->mAtomFullScreen == None) - { - // Without WM support it is best to give up. - LogManager::getSingleton().logMessage("GLXWindow::switchFullScreen: Your WM has no fullscreen support"); - return; - } - else if (fullscreen) - { - mGLSupport->switchMode(width, height, frequency); - } - else - { - mGLSupport->switchMode(); - } - - if (mIsFullScreen != fullscreen) - { - switchFullScreen(fullscreen); - } - - if (! mIsFullScreen) - { - resize(width, height); - reposition(mLeft, mTop); - } - } - - //-------------------------------------------------------------------------------------------------// - void GLXWindow::setHidden(bool hidden) - { - mHidden = hidden; - // ignore for external windows as these should handle - // this externally - if (mIsExternal) - return; - - if (hidden) - { - XUnmapWindow(mGLSupport->getXDisplay(), mWindow); - } - else - { - XMapWindow(mGLSupport->getXDisplay(), mWindow); - if (mIsFullScreen) - { - switchFullScreen(true); - } - } - } - - //-------------------------------------------------------------------------------------------------// - void GLXWindow::setVSyncEnabled(bool vsync) - { - mVSync = vsync; - // we need to make our context current to set vsync - // store previous context to restore when finished. - ::GLXDrawable oldDrawable = glXGetCurrentDrawable(); - ::GLXContext oldContext = glXGetCurrentContext(); - - mContext->setCurrent(); - - PFNGLXSWAPINTERVALEXTPROC _glXSwapIntervalEXT; - _glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC)mGLSupport->getProcAddress("glXSwapIntervalEXT"); - PFNGLXSWAPINTERVALMESAPROC _glXSwapIntervalMESA; - _glXSwapIntervalMESA = (PFNGLXSWAPINTERVALMESAPROC)mGLSupport->getProcAddress("glXSwapIntervalMESA"); - PFNGLXSWAPINTERVALSGIPROC _glXSwapIntervalSGI; - _glXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC)mGLSupport->getProcAddress("glXSwapIntervalSGI"); - - if (! mIsExternalGLControl ) - { - if( _glXSwapIntervalEXT ) - { - _glXSwapIntervalEXT( mGLSupport->getGLDisplay(), static_cast(mContext)->mDrawable, - vsync ? mVSyncInterval : 0 ); - } - else if( _glXSwapIntervalMESA ) - _glXSwapIntervalMESA( vsync ? mVSyncInterval : 0 ); - else { - OgreAssert(_glXSwapIntervalSGI, "no glx swap interval function found"); - _glXSwapIntervalSGI( vsync ? mVSyncInterval : 0 ); - } - } - - mContext->endCurrent(); - - glXMakeCurrent (mGLSupport->getGLDisplay(), oldDrawable, oldContext); - } - - //-------------------------------------------------------------------------------------------------// - void GLXWindow::reposition(int left, int top) - { - if (mClosed || ! mIsTopLevel) - return; - - XMoveWindow(mGLSupport->getXDisplay(), mWindow, left, top); - } - - //-------------------------------------------------------------------------------------------------// - void GLXWindow::resize(uint width, uint height) - { - if (mClosed) - return; - - if(mWidth == width && mHeight == height) - return; - - if(width != 0 && height != 0) - { - if (!mIsTopLevel) - { - XResizeWindow(mGLSupport->getXDisplay(), mWindow, width, height); - XFlush(mGLSupport->getXDisplay()); - } - - mWidth = width; - mHeight = height; - - for (ViewportList::iterator it = mViewportList.begin(); it != mViewportList.end(); ++it) - (*it).second->_updateDimensions(); - } - } - - //-------------------------------------------------------------------------------------------------// - void GLXWindow::windowMovedOrResized() - { - if (mClosed || !mWindow) - return; - - Display* xDisplay = mGLSupport->getXDisplay(); - uint width, height; - queryRect(xDisplay, mWindow, mLeft, mTop, width, height, mIsTopLevel && !mIsFullScreen); - resize(width, height); - } - - //-------------------------------------------------------------------------------------------------// - void GLXWindow::swapBuffers() - { - if (mClosed || mIsExternalGLControl) - return; - - glXSwapBuffers(mGLSupport->getGLDisplay(), static_cast(mContext)->mDrawable); - } - - //-------------------------------------------------------------------------------------------------// - void GLXWindow::getCustomAttribute( const String& name, void* pData ) - { - if( name == "DISPLAY" ) - { - *static_cast(pData) = mGLSupport->getGLDisplay(); - return; - } - else if( name == "GLCONTEXT" ) - { - *static_cast(pData) = mContext; - return; - } - else if( name == "XDISPLAY" ) - { - *static_cast(pData) = mGLSupport->getXDisplay(); - return; - } - else if( name == "ATOM" ) - { - *static_cast< ::Atom* >(pData) = mGLSupport->mAtomDeleteWindow; - return; - } - else if( name == "WINDOW" ) - { - *static_cast(pData) = mWindow; - return; - } - } - - //-------------------------------------------------------------------------------------------------// - PixelFormat GLXWindow::suggestPixelFormat() const - { - return mGLSupport->getContextProfile() == GLNativeSupport::CONTEXT_ES ? PF_BYTE_RGBA : PF_BYTE_RGB; - } - - //-------------------------------------------------------------------------------------------------// - void GLXWindow::switchFullScreen(bool fullscreen) - { - if (mGLSupport->mAtomFullScreen != None) - { - Display* xDisplay = mGLSupport->getXDisplay(); - XClientMessageEvent xMessage; - - xMessage.type = ClientMessage; - xMessage.serial = 0; - xMessage.send_event = True; - xMessage.window = mWindow; - xMessage.message_type = mGLSupport->mAtomState; - xMessage.format = 32; - xMessage.data.l[0] = (fullscreen ? 1 : 0); - xMessage.data.l[1] = mGLSupport->mAtomFullScreen; - xMessage.data.l[2] = 0; - - XSendEvent(xDisplay, DefaultRootWindow(xDisplay), False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*)&xMessage); - - mIsFullScreen = fullscreen; - } - } -} diff --git a/RenderSystems/GLSupport/src/OSX/OgreOSXCocoaContext.mm b/RenderSystems/GLSupport/src/OSX/OgreOSXCocoaContext.mm deleted file mode 100644 index 53b1512fdc5..00000000000 --- a/RenderSystems/GLSupport/src/OSX/OgreOSXCocoaContext.mm +++ /dev/null @@ -1,78 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#import "OgreOSXCocoaContext.h" -#include "OgreGLRenderSystemCommon.h" -#include "OgreRoot.h" - -namespace Ogre -{ - - CocoaContext::CocoaContext(NSOpenGLContext *context, NSOpenGLPixelFormat *pixelFormat) - : mNSGLContext(context), mNSGLPixelFormat(pixelFormat) - { - if(mNSGLPixelFormat) - [mNSGLPixelFormat retain]; - } - - CocoaContext::~CocoaContext() - { - GLRenderSystemCommon *rs = static_cast(Root::getSingleton().getRenderSystem()); - rs->_unregisterContext(this); - - if(mNSGLPixelFormat) - [mNSGLPixelFormat release]; - } - - void CocoaContext::setCurrent() - { - [mNSGLContext makeCurrentContext]; - } - - void CocoaContext::endCurrent() - { - [NSOpenGLContext clearCurrentContext]; - } - - GLContext* CocoaContext::clone() const - { - NSOpenGLContext *cloneCtx = [[NSOpenGLContext alloc] initWithFormat:mNSGLPixelFormat shareContext:mNSGLContext]; - [cloneCtx copyAttributesFromContext:mNSGLContext withMask:0]; - return OGRE_NEW CocoaContext(cloneCtx, mNSGLPixelFormat); - } - - NSOpenGLContext* CocoaContext::getContext() - { - return mNSGLContext; - } - - NSOpenGLPixelFormat* CocoaContext::getPixelFormat() - { - return mNSGLPixelFormat; - } -} diff --git a/RenderSystems/GLSupport/src/OSX/OgreOSXCocoaView.mm b/RenderSystems/GLSupport/src/OSX/OgreOSXCocoaView.mm deleted file mode 100644 index 8250caff89e..00000000000 --- a/RenderSystems/GLSupport/src/OSX/OgreOSXCocoaView.mm +++ /dev/null @@ -1,87 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#import "OgreOSXCocoaView.h" -#import - -@implementation OgreGLView - -- (id)initWithFrame:(NSRect)f -{ - if((self = [super initWithFrame:f])) - { - NSApplicationLoad(); - - window = 0; - } - return self; -} - -- (id)initWithGLOSXWindow:(Ogre::RenderWindow*)w -{ - if((self = [super initWithFrame:NSMakeRect(0, 0, w->getWidth(), w->getHeight())])) - { - window = w; - } - return self; -} - -- (void)setOgreWindow:(Ogre::RenderWindow*)w -{ - window = w; -} - -- (Ogre::RenderWindow*)ogreWindow -{ - return window; -} - -- (void)setFrameSize:(NSSize)s -{ - [super setFrameSize:s]; - if (window) - window->windowMovedOrResized(); -} - -- (void)drawRect:(NSRect)r -{ - if(window) - window->update(); -} - -- (BOOL)acceptsFirstResponder -{ - return NO; -} - -- (BOOL)canBecomeKeyView -{ - return NO; -} - -@end diff --git a/RenderSystems/GLSupport/src/OSX/OgreOSXCocoaWindow.mm b/RenderSystems/GLSupport/src/OSX/OgreOSXCocoaWindow.mm deleted file mode 100644 index 85d62c04e2c..00000000000 --- a/RenderSystems/GLSupport/src/OSX/OgreOSXCocoaWindow.mm +++ /dev/null @@ -1,789 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#import "OgreOSXCocoaWindow.h" -#import "OgreRoot.h" -#import "OgreLogManager.h" -#import "OgreStringConverter.h" - -#import "OgreGLRenderSystemCommon.h" -#import "OgreGLNativeSupport.h" -#import -#import -#import -#import -#import "OgreViewport.h" -#import - -@implementation OgreGLWindow - -- (BOOL)canBecomeKeyWindow -{ - return YES; -} - -- (BOOL)acceptsFirstMouse:(NSEvent *)theEvent -{ - return YES; -} - -- (BOOL)acceptsFirstResponder -{ - return YES; -} - -@end - -namespace Ogre { - - struct NSOpenGLContextGuard - { - NSOpenGLContextGuard(NSOpenGLContext* ctx) : mPrevContext([NSOpenGLContext currentContext]) { if(ctx != mPrevContext) [ctx makeCurrentContext]; } - ~NSOpenGLContextGuard() { [mPrevContext makeCurrentContext]; } - private: - NSOpenGLContext *mPrevContext; - }; - - - CocoaWindow::CocoaWindow() : GLWindow(), mWindow(nil), mView(nil), mGLContext(nil), mGLPixelFormat(nil), mWindowOriginPt(NSZeroPoint), - mHasResized(false), mWindowTitle(""), - mUseOgreGLView(true), mContentScalingFactor(1.0), mStyleMask(NSResizableWindowMask|NSTitledWindowMask) - { - // Set vsync by default to save battery and reduce tearing - } - - CocoaWindow::~CocoaWindow() - { - [mGLContext clearDrawable]; - - destroy(); - - if(mView && mUseOgreGLView) - { - [(OgreGLView*)mView setOgreWindow:NULL]; - } - - if(mWindow && !mIsExternal) - { - [mWindow release]; - mWindow = nil; - } - } - - void CocoaWindow::create(const String& name, unsigned int widthPt, unsigned int heightPt, - bool fullScreen, const NameValuePairList *miscParams) - { - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - NSApplicationLoad(); - - /* - ***Key: "title" Description: The title of the window that will appear in the title bar - Values: string Default: RenderTarget name - - ***Key: "colourDepth" Description: Colour depth of the resulting rendering window; - only applies if fullScreen is set. Values: 16 or 32 Default: desktop depth Notes: [W32 specific] - - ***Key: "left" Description: screen x coordinate from left Values: positive integers - Default: 'center window on screen' Notes: Ignored in case of full screen - - ***Key: "top" Description: screen y coordinate from top Values: positive integers - Default: 'center window on screen' Notes: Ignored in case of full screen - - ***Key: "depthBuffer" [DX9 specific] Description: Use depth buffer Values: false or true Default: true - - ***Key: "externalWindowHandle" [API specific] Description: External window handle, for embedding the - OGRE context Values: positive integer for W32 (HWND handle) poslong:posint:poslong (display*:screen:windowHandle) - or poslong:posint:poslong:poslong (display*:screen:windowHandle:XVisualInfo*) for GLX Default: 0 (None) - - ***Key: "FSAA" Description: Full screen antialiasing factor Values: 0,2,4,6,... Default: 0 - - ***Key: "displayFrequency" Description: Display frequency rate, for fullscreen mode Values: 60...? - Default: Desktop vsync rate - - ***Key: "vsync" Description: Synchronize buffer swaps to vsync Values: true, false Default: 0 - - ***Key: "currentGLContext" Description: use an externally created OpenGL context (must be current) - Values: true, false Default: false - */ - - BOOL hasDepthBuffer = YES; - int fsaa_samples = 0; - bool hidden = false; - NSString *windowTitle = [NSString stringWithCString:name.c_str() encoding:NSUTF8StringEncoding]; - int winxPt = 0, winyPt = 0; - int colourDepth = 32; - int surfaceOrder = 1; - int contextProfile = GLNativeSupport::CONTEXT_COMPATIBILITY; - bool currentGLContext = false; - NSOpenGLContext *externalGLContext = nil; - NSObject* externalWindowHandle = nil; // NSOpenGLView, NSView or NSWindow - NameValuePairList::const_iterator opt; - - mIsFullScreen = fullScreen; - - if(miscParams) - { - opt = miscParams->find("title"); - if(opt != miscParams->end()) - windowTitle = [NSString stringWithCString:opt->second.c_str() encoding:NSUTF8StringEncoding]; - - opt = miscParams->find("left"); - if(opt != miscParams->end()) - winxPt = StringConverter::parseUnsignedInt(opt->second); - - opt = miscParams->find("top"); - if(opt != miscParams->end()) - winyPt = (int)NSHeight([[NSScreen mainScreen] frame]) - StringConverter::parseUnsignedInt(opt->second) - heightPt; - - opt = miscParams->find("hidden"); - if (opt != miscParams->end()) - hidden = StringConverter::parseBool(opt->second); - - opt = miscParams->find("depthBuffer"); - if(opt != miscParams->end()) - hasDepthBuffer = StringConverter::parseBool(opt->second); - - opt = miscParams->find("FSAA"); - if(opt != miscParams->end()) - fsaa_samples = StringConverter::parseUnsignedInt(opt->second); - - opt = miscParams->find("gamma"); - if(opt != miscParams->end()) - mHwGamma = StringConverter::parseBool(opt->second); - - opt = miscParams->find("vsync"); - if(opt != miscParams->end()) - mVSync = StringConverter::parseBool(opt->second); - - opt = miscParams->find("colourDepth"); - if(opt != miscParams->end()) - colourDepth = StringConverter::parseUnsignedInt(opt->second); - - opt = miscParams->find("Full Screen"); - if(opt != miscParams->end()) - fullScreen = StringConverter::parseBool(opt->second); - - opt = miscParams->find("contentScalingFactor"); - if(opt != miscParams->end()) - mContentScalingFactor = StringConverter::parseReal(opt->second); - - opt = miscParams->find("contextProfile"); - if(opt != miscParams->end()) - contextProfile = StringConverter::parseInt(opt->second); - - opt = miscParams->find("currentGLContext"); - if (opt != miscParams->end()) - currentGLContext = StringConverter::parseBool(opt->second); - - opt = miscParams->find("externalGLControl"); - if (opt != miscParams->end()) - mIsExternalGLControl = StringConverter::parseBool(opt->second); - - opt = miscParams->find("externalGLContext"); - if(opt != miscParams->end()) - externalGLContext = (NSOpenGLContext*)StringConverter::parseSizeT(opt->second); - - opt = miscParams->find("externalWindowHandle"); - if(opt != miscParams->end()) - externalWindowHandle = (NSObject*)StringConverter::parseSizeT(opt->second); - - opt = miscParams->find("border"); - if(opt != miscParams->end()) - { - String border = opt->second; - if (border == "none") - { - mStyleMask = NSBorderlessWindowMask; - } - else if (border == "fixed") - { - mStyleMask = NSTitledWindowMask; - } - // Default case set in initializer. - } - - opt = miscParams->find("NSOpenGLCPSurfaceOrder"); - if(opt != miscParams->end()) - surfaceOrder = StringConverter::parseInt(opt->second); - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - opt = miscParams->find("stereoMode"); - if (opt != miscParams->end()) - { - mStereoEnabled = StringConverter::parseBool(opt->second); - } -#endif - } - - if(externalGLContext) - { - mGLContext = [externalGLContext retain]; - mGLPixelFormat = [externalGLContext.pixelFormat retain]; - } - else if(currentGLContext) - { - mGLContext = [[NSOpenGLContext currentContext] retain]; - mGLPixelFormat = [mGLContext.pixelFormat retain]; - } - else if(!mIsExternalGLControl) - { - NSOpenGLPixelFormatAttribute attribs[30]; - int i = 0; - - // Specify the display ID to associate the GL context with (main display for now) - // Useful if there is ambiguity - attribs[i++] = NSOpenGLPFAScreenMask; - attribs[i++] = (NSOpenGLPixelFormatAttribute)CGDisplayIDToOpenGLDisplayMask(CGMainDisplayID()); - - // Specify that we want to use the OpenGL 3.2 Core profile - attribs[i++] = NSOpenGLPFAOpenGLProfile; - attribs[i++] = contextProfile == GLNativeSupport::CONTEXT_CORE ? NSOpenGLProfileVersion3_2Core : NSOpenGLProfileVersionLegacy; - - // Specifying "NoRecovery" gives us a context that cannot fall back to the software renderer. - // This makes the View-based context a compatible with the fullscreen context, enabling us to use - // the "shareContext" feature to share textures, display lists, and other OpenGL objects between the two. - attribs[i++] = NSOpenGLPFANoRecovery; - - attribs[i++] = NSOpenGLPFAAccelerated; - attribs[i++] = NSOpenGLPFADoubleBuffer; - - attribs[i++] = NSOpenGLPFAColorSize; - attribs[i++] = (NSOpenGLPixelFormatAttribute) colourDepth; - - attribs[i++] = NSOpenGLPFAAlphaSize; - attribs[i++] = (NSOpenGLPixelFormatAttribute) 8; - - attribs[i++] = NSOpenGLPFAStencilSize; - attribs[i++] = (NSOpenGLPixelFormatAttribute) 8; - - attribs[i++] = NSOpenGLPFADepthSize; - attribs[i++] = (NSOpenGLPixelFormatAttribute) (hasDepthBuffer? 16 : 0); - - if(fsaa_samples > 0) - { - attribs[i++] = NSOpenGLPFAMultisample; - attribs[i++] = NSOpenGLPFASampleBuffers; - attribs[i++] = (NSOpenGLPixelFormatAttribute) 1; - - attribs[i++] = NSOpenGLPFASamples; - attribs[i++] = (NSOpenGLPixelFormatAttribute) fsaa_samples; - } - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - if (mStereoEnabled) - attribs[i++] = NSOpenGLPFAStereo; -#endif - - attribs[i++] = (NSOpenGLPixelFormatAttribute) 0; - - mGLPixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs]; - - GLRenderSystemCommon *rs = static_cast(Root::getSingleton().getRenderSystem()); - CocoaContext *mainContext = (CocoaContext*)rs->_getMainContext(); - NSOpenGLContext *shareContext = mainContext == 0 ? nil : mainContext->getContext(); - mGLContext = [[NSOpenGLContext alloc] initWithFormat:mGLPixelFormat shareContext:shareContext]; - } - - if(!mIsExternalGLControl) - { - // Set vsync - GLint swapInterval = (GLint)mVSync; - [mGLContext setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval]; - GLint order = (GLint)surfaceOrder; - [mGLContext setValues:&order forParameter:NSOpenGLCPSurfaceOrder]; - } - - // Make active - setHidden(hidden); - mActive = true; - mVisible = true; - mClosed = false; - mName = [windowTitle cStringUsingEncoding:NSUTF8StringEncoding]; - mWidth = _getPixelFromPoint(widthPt); - mHeight = _getPixelFromPoint(heightPt); - mFSAA = fsaa_samples; - - if(!externalWindowHandle) - { - createNewWindow(widthPt, heightPt, [windowTitle cStringUsingEncoding:NSUTF8StringEncoding]); - } - else - { - if([externalWindowHandle isKindOfClass:[NSWindow class]]) - { - mView = [(NSWindow*)externalWindowHandle contentView]; - mUseOgreGLView = [mView isKindOfClass:[OgreGLView class]]; - LogManager::getSingleton().logMessage(mUseOgreGLView ? - "Mac Cocoa Window: Rendering on an external NSWindow with nested OgreGLView" : - "Mac Cocoa Window: Rendering on an external NSWindow with nested NSView"); - } - else - { - assert([externalWindowHandle isKindOfClass:[NSView class]]); - mView = (NSView*)externalWindowHandle; - mUseOgreGLView = [mView isKindOfClass:[OgreGLView class]]; - LogManager::getSingleton().logMessage(mUseOgreGLView ? - "Mac Cocoa Window: Rendering on an external OgreGLView" : - "Mac Cocoa Window: Rendering on an external NSView"); - } - - if(mUseOgreGLView) - { - [(OgreGLView*)mView setOgreWindow:this]; - } - - NSRect b = [mView bounds]; - mWidth = _getPixelFromPoint((int)b.size.width); - mHeight = _getPixelFromPoint((int)b.size.height); - - mWindow = [mView window]; - mIsExternal = true; - } - - // Create register the context with the rendersystem and associate it with this window - mContext = OGRE_NEW CocoaContext(mGLContext, mGLPixelFormat); - - if(mContentScalingFactor > 1.0) - [mView setWantsBestResolutionOpenGLSurface:YES]; - - CGLLockContext((CGLContextObj)[mGLContext CGLContextObj]); - - [mView setNeedsDisplay:YES]; - - if([mGLContext view] != mView) - [mGLContext setView:mView]; - [mGLContext makeCurrentContext]; - -#if OGRE_DEBUG_MODE - // Crash on functions that have been removed from the API - CGLEnable((CGLContextObj)[mGLContext CGLContextObj], kCGLCECrashOnRemovedFunctions); -#endif - - // Enable GL multithreading - CGLEnable((CGLContextObj)[mGLContext CGLContextObj], kCGLCEMPEngine); - - [mGLContext update]; - -// rs->clearFrameBuffer(FBT_COLOUR); - - [mGLContext flushBuffer]; - CGLUnlockContext((CGLContextObj)[mGLContext CGLContextObj]); - - [pool drain]; - - StringStream ss; - ss << "Cocoa: Window created " << widthPt << " x " << heightPt - << " with backing store size " << mWidth << " x " << mHeight - << " using content scaling factor " << std::fixed << std::setprecision(1) << getViewPointToPixelScale(); - LogManager::getSingleton().logMessage(ss.str()); - } - - unsigned int CocoaWindow::getWidth() const - { - // keep mWidth in sync with reality - OgreAssertDbg(mView == nil || int(mWidth) == _getPixelFromPoint([mView frame].size.width), - "Window dimension mismatch. Did you call windowMovedOrResized?"); - - return mWidth; - } - - unsigned int CocoaWindow::getHeight() const - { - // keep mHeight in sync with reality - OgreAssertDbg(mView == nil || int(mHeight) == _getPixelFromPoint([mView frame].size.height), - "Window dimension mismatch. Did you call windowMovedOrResized?"); - - return mHeight; - } - - void CocoaWindow::destroy(void) - { - if(!mIsFullScreen) - { - // Unregister and destroy OGRE GLContext - OGRE_DELETE mContext; - - if(mWindow && !mIsExternal) - { - [mWindow performClose:nil]; - } - } - - if(mGLContext) - { - [mGLContext release]; - mGLContext = nil; - } - - if(mGLPixelFormat) - { - [mGLPixelFormat release]; - mGLPixelFormat = nil; - } - - mActive = false; - mClosed = true; - } - - void CocoaWindow::setHidden(bool hidden) - { - mHidden = hidden; - if (!mIsExternal) - { - if (hidden) - [mWindow orderOut:nil]; - else - [mWindow makeKeyAndOrderFront:nil]; - } - } - - void CocoaWindow::setVSyncEnabled(bool vsync) - { - mVSync = vsync; - mContext->setCurrent(); - - GLint vsyncInterval = mVSync ? 1 : 0; - [mGLContext setValues:&vsyncInterval forParameter:NSOpenGLCPSwapInterval]; - - mContext->endCurrent(); - - if(mGLContext != [NSOpenGLContext currentContext]) - [mGLContext makeCurrentContext]; - } - - float CocoaWindow::getViewPointToPixelScale() - { - return mContentScalingFactor > 1.0f ? mContentScalingFactor : 1.0f; - } - - int CocoaWindow::_getPixelFromPoint(int viewPt) const - { - return mContentScalingFactor > 1.0 ? viewPt * mContentScalingFactor : viewPt; - } - - void CocoaWindow::reposition(int leftPt, int topPt) - { - if(!mWindow) - return; - - if(mIsFullScreen) - return; - - NSRect frame = mIsExternal ? [[mView window] frame] : [mWindow frame]; - NSRect screenFrame = [[NSScreen mainScreen] visibleFrame]; - frame.origin.x = leftPt; - frame.origin.y = screenFrame.size.height - frame.size.height - topPt; - mWindowOriginPt = frame.origin; - - if(mIsExternal) - [[mView window] setFrame:frame display:YES]; - else - [mWindow setFrame:frame display:YES]; - - // Keep our size up to date - NSRect b = [mView bounds]; - mWidth = _getPixelFromPoint((int)b.size.width); - mHeight = _getPixelFromPoint((int)b.size.height); - } - - void CocoaWindow::resize(unsigned int widthPt, unsigned int heightPt) - { - if(!mWindow) - return; - - if(mIsFullScreen) - return; - - unsigned widthPx = _getPixelFromPoint(widthPt); - unsigned heightPx = _getPixelFromPoint(heightPt); - - // Check if the window size really changed - if(mWidth == widthPx && mHeight == heightPx) - return; - - mWidth = widthPx; - mHeight = heightPx; - - if(mIsExternal) - { - NSRect viewFrame = [mView frame]; - viewFrame.size.width = widthPt; - viewFrame.size.height = heightPt; - - NSRect windowFrame = [[mView window] frame]; - - CGFloat leftPt = viewFrame.origin.x; - CGFloat topPt = windowFrame.size.height - (viewFrame.origin.y + viewFrame.size.height); - mLeft = _getPixelFromPoint((int)leftPt); - mTop = _getPixelFromPoint((int)topPt); - mWindowOriginPt = NSMakePoint(leftPt, topPt); - - GLint bufferRect[4]; - bufferRect[0] = mLeft; // 0 = left edge - bufferRect[1] = mTop; // 0 = bottom edge - bufferRect[2] = mWidth; // width of buffer rect - bufferRect[3] = mHeight; // height of buffer rect - CGLContextObj ctx = (CGLContextObj)[mGLContext CGLContextObj]; - CGLSetParameter(ctx, kCGLCPSwapRectangle, bufferRect); - } - else - { - mWindowOriginPt = [mWindow frame].origin; - [mWindow setContentSize:NSMakeSize(widthPt, heightPt)]; - } - //make sure the context is current - NSOpenGLContextGuard ctx_guard(mGLContext); - for (ViewportList::iterator it = mViewportList.begin(); it != mViewportList.end(); ++it) - { - (*it).second->_updateDimensions(); - } - [mGLContext update]; - } - - void CocoaWindow::windowHasResized() - { - // Ensure the context is current - [mGLContext flushBuffer]; - } - - void CocoaWindow::windowMovedOrResized() - { - mContentScalingFactor = - ([mView respondsToSelector:@selector(wantsBestResolutionOpenGLSurface)] && [(id)mView wantsBestResolutionOpenGLSurface]) ? - (mView.window.screen ?: [NSScreen mainScreen]).backingScaleFactor : 1.0f; - - NSRect winFrame = mIsExternal ? [[mView window] frame] : [mWindow frame]; - NSRect viewFrame = [mView frame]; - NSRect screenFrame = [[NSScreen mainScreen] visibleFrame]; - CGFloat leftPt = winFrame.origin.x; - CGFloat topPt = screenFrame.size.height - winFrame.size.height; - mWidth = _getPixelFromPoint((unsigned int)viewFrame.size.width); - mHeight = _getPixelFromPoint((unsigned int)viewFrame.size.height); - mLeft = _getPixelFromPoint((int)leftPt); - mTop = _getPixelFromPoint((int)topPt); - - mWindowOriginPt = NSMakePoint(leftPt, topPt); - - //make sure the context is current - NSOpenGLContextGuard ctx_guard(mGLContext); - - for (ViewportList::iterator it = mViewportList.begin(); it != mViewportList.end(); ++it) - { - (*it).second->_updateDimensions(); - } - [mGLContext update]; - } - - void CocoaWindow::swapBuffers() - { - if(!mIsExternalGLControl) - { - CGLLockContext((CGLContextObj)[mGLContext CGLContextObj]); - [mGLContext makeCurrentContext]; - - if([mGLContext view] != mView) - [mGLContext setView:mView]; - - [mGLContext flushBuffer]; - CGLUnlockContext((CGLContextObj)[mGLContext CGLContextObj]); - } - } - - //-------------------------------------------------------------------------------------------------// - void CocoaWindow::getCustomAttribute( const String& name, void* pData ) - { - if( name == "GLCONTEXT" ) - { - *static_cast(pData) = mContext; - return; - } - else if( name == "WINDOW" ) - { - *(void**)(pData) = mWindow; - return; - } - else if( name == "VIEW" ) - { - *(void**)(pData) = mView; - return; - } - else if( name == "NSOPENGLCONTEXT" ) - { - *(void**)(pData) = mGLContext; - return; - } - else if( name == "NSOPENGLPIXELFORMAT" ) - { - *(void**)(pData) = mGLPixelFormat; - return; - } - - } - - void CocoaWindow::createNewWindow(unsigned int widthPt, unsigned int heightPt, String title) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Builtin Window creation broken. Use an external Window (e.g SDL2) or fix this"); - - // Get the dimensions of the display. We will use it for the window size but not context resolution - NSRect windowRect = NSZeroRect; - if(mIsFullScreen) - { - NSRect mainDisplayRect = [[NSScreen mainScreen] visibleFrame]; - windowRect = NSMakeRect(0.0, 0.0, mainDisplayRect.size.width, mainDisplayRect.size.height); - } - else - windowRect = NSMakeRect(0.0, 0.0, widthPt, heightPt); - - mWindow = [[OgreGLWindow alloc] initWithContentRect:windowRect - styleMask:mIsFullScreen ? NSBorderlessWindowMask : mStyleMask - backing:NSBackingStoreBuffered - defer:YES]; - [mWindow setTitle:[NSString stringWithCString:title.c_str() encoding:NSUTF8StringEncoding]]; - mWindowTitle = title; - - mView = [[OgreGLView alloc] initWithGLOSXWindow:this]; - - _setWindowParameters(widthPt, heightPt); - -// GL3PlusRenderSystem *rs = static_cast(Root::getSingleton().getRenderSystem()); -// rs->clearFrameBuffer(FBT_COLOUR); - - // Show window - setHidden(mHidden); - } - - void CocoaWindow::createWindowFromExternal(NSView *viewRef) - { - LogManager::getSingleton().logMessage("Creating external window"); - - NSRect viewBounds = [mView convertRectToBacking:[mView bounds]]; - - mWindow = [viewRef window]; - - mView = viewRef; - - GLint bufferRect[4]; - bufferRect[0] = viewBounds.origin.x; // 0 = left edge - bufferRect[1] = viewBounds.origin.y; // 0 = bottom edge - bufferRect[2] = viewBounds.size.width; // width of buffer rect - bufferRect[3] = viewBounds.size.height; // height of buffer rect - CGLContextObj ctx = (CGLContextObj)[mGLContext CGLContextObj]; - CGLSetParameter(ctx, kCGLCPSwapRectangle, bufferRect); - - mIsExternal = true; - } - - void CocoaWindow::_setWindowParameters(unsigned int widthPt, unsigned int heightPt) - { - if(mWindow) - { - if(mIsFullScreen) - { - // Set the backing store size to the viewport dimensions - // This ensures that it will scale to the full screen size - NSRect mainDisplayRect = [[NSScreen mainScreen] frame]; - NSRect backingRect = NSZeroRect; - if(mContentScalingFactor > 1.0) - backingRect = [[NSScreen mainScreen] convertRectToBacking:mainDisplayRect]; - else - backingRect = mainDisplayRect; - - GLint backingStoreDimensions[2] = { static_cast(backingRect.size.width), static_cast(backingRect.size.height) }; - CGLSetParameter((CGLContextObj)[mGLContext CGLContextObj], kCGLCPSurfaceBackingSize, backingStoreDimensions); - CGLEnable((CGLContextObj)[mGLContext CGLContextObj], kCGLCESurfaceBackingSize); - - NSRect windowRect = NSMakeRect(0.0, 0.0, mainDisplayRect.size.width, mainDisplayRect.size.height); - [mWindow setFrame:windowRect display:YES]; - [mView setFrame:windowRect]; - - // Set window properties for full screen and save the origin in case the window has been moved - [mWindow setStyleMask:NSBorderlessWindowMask]; - [mWindow setOpaque:YES]; - [mWindow setHidesOnDeactivate:YES]; - [mWindow setContentView:mView]; - [mWindow setFrameOrigin:NSZeroPoint]; - [mWindow setLevel:NSMainMenuWindowLevel+1]; - - mWindowOriginPt = mWindow.frame.origin; - mLeft = mTop = 0; - } - else - { - // Reset and disable the backing store in windowed mode - GLint backingStoreDimensions[2] = { 0, 0 }; - CGLSetParameter((CGLContextObj)[mGLContext CGLContextObj], kCGLCPSurfaceBackingSize, backingStoreDimensions); - CGLDisable((CGLContextObj)[mGLContext CGLContextObj], kCGLCESurfaceBackingSize); - - NSRect viewRect = NSMakeRect(mWindowOriginPt.x, mWindowOriginPt.y, widthPt, heightPt); - [mWindow setFrame:viewRect display:YES]; - [mView setFrame:viewRect]; - [mWindow setStyleMask:mStyleMask]; - [mWindow setOpaque:YES]; - [mWindow setHidesOnDeactivate:NO]; - [mWindow setContentView:mView]; - [mWindow setLevel:NSNormalWindowLevel]; - [mWindow center]; - - // Set the drawable, and current context - // If you do this last, there is a moment before the rendering window pops-up - [mGLContext makeCurrentContext]; - } - - [mGLContext update]; - - // Even though OgreCocoaView doesn't accept first responder, it will get passed onto the next in the chain - [mWindow makeFirstResponder:mView]; - [NSApp activateIgnoringOtherApps:YES]; - } - } - - void CocoaWindow::setFullscreen(bool fullScreen, unsigned int widthPt, unsigned int heightPt) - { - unsigned widthPx = _getPixelFromPoint(widthPt); - unsigned heightPx = _getPixelFromPoint(heightPt); - if (mIsFullScreen != fullScreen || widthPx != mWidth || heightPx != mHeight) - { - // Set the full screen flag - mIsFullScreen = fullScreen; - - // Create a window if we haven't already, existence check is done within the functions - if(!mWindow) - { - if(mIsExternal) - createWindowFromExternal(mView); - else - createNewWindow(widthPt, heightPt, mWindowTitle); - } - - _setWindowParameters(widthPt, heightPt); - - mWidth = widthPx; - mHeight = heightPx; - } - } -} diff --git a/RenderSystems/GLSupport/src/OSX/OgreOSXGL3PlusSupport.mm b/RenderSystems/GLSupport/src/OSX/OgreOSXGL3PlusSupport.mm deleted file mode 100644 index 20c84387ccc..00000000000 --- a/RenderSystems/GLSupport/src/OSX/OgreOSXGL3PlusSupport.mm +++ /dev/null @@ -1,257 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#import "OgreException.h" -#import "OgreLogManager.h" -#import "OgreStringConverter.h" -#import "OgreRoot.h" - -#import "OgreGLNativeSupport.h" -#import "OgreOSXGLSupport.h" -#import "OgreOSXCocoaWindow.h" -#import "OgreGLUtil.h" - -#import - -#import -#import - -namespace Ogre { - -GLNativeSupport* getGLSupport(int profile) -{ - return new OSXGLSupport(profile); -} - -ConfigOptionMap OSXGLSupport::getConfigOptions() -{ - ConfigOptionMap mOptions; - ConfigOption optBitDepth; - ConfigOption optContentScalingFactor; - - optBitDepth.name = "Colour Depth"; - optBitDepth.currentValue = "32"; - optBitDepth.immutable = false; - - optContentScalingFactor.name = "Content Scaling Factor"; - optContentScalingFactor.possibleValues.push_back( "1.0" ); - optContentScalingFactor.possibleValues.push_back( "2.0" ); - optContentScalingFactor.currentValue = StringConverter::toString((float)[NSScreen mainScreen].backingScaleFactor); - optContentScalingFactor.immutable = false; - - mOptions[ optBitDepth.name ] = optBitDepth; - mOptions[ optContentScalingFactor.name ] = optContentScalingFactor; - - CGLRendererInfoObj rend; - GLint nrend = 0, maxSamples = 0; - - CGLQueryRendererInfo(CGDisplayIDToOpenGLDisplayMask(kCGDirectMainDisplay), &rend, &nrend); - CGLDescribeRenderer(rend, 0, kCGLRPMaxSamples, &maxSamples); - CGLDestroyRendererInfo(rend); - - // FSAA possibilities - for(int i = 0; i <= maxSamples; i += 2) - mFSAALevels.push_back( i ); - - // Video mode possibilities - CFArrayRef displayModes = CGDisplayCopyAllDisplayModes(CGMainDisplayID(), NULL); - CFIndex numModes = CFArrayGetCount(displayModes); - CFMutableArrayRef goodModes = NULL; - goodModes = CFArrayCreateMutable(kCFAllocatorDefault, numModes, NULL); - - // Grab all the available display modes, then weed out duplicates... - for(int i = 0; i < numModes; ++i) - { - CGDisplayModeRef modeInfo = (CGDisplayModeRef)CFArrayGetValueAtIndex(displayModes, i); - - // Get IOKit flags for the display mode - uint32_t ioFlags = CGDisplayModeGetIOFlags(modeInfo); - - bool safeForHardware = ioFlags & kDisplayModeSafetyFlags ? true : false; - bool stretched = ioFlags & kDisplayModeStretchedFlag ? true : false; - bool skipped = false; - - if((safeForHardware) || (!stretched)) - { - size_t width = CGDisplayModeGetWidth(modeInfo); - size_t height = CGDisplayModeGetHeight(modeInfo); - - for(CFIndex j = 0; j < CFArrayGetCount(goodModes); ++j) - { - CGDisplayModeRef otherMode = (CGDisplayModeRef)CFArrayGetValueAtIndex(goodModes, j); - - size_t otherWidth = CGDisplayModeGetWidth(otherMode); - size_t otherHeight = CGDisplayModeGetHeight(otherMode); - - // If we find a duplicate then skip this mode - if((otherWidth == width) && (otherHeight == height)) - skipped = true; - } - - // This is a new mode, so add it to our goodModes array - if(!skipped) - CFArrayAppendValue(goodModes, modeInfo); - } - } - - // Release memory - CFRelease(displayModes); - - // Sort the modes... - CFArraySortValues(goodModes, CFRangeMake(0, CFArrayGetCount(goodModes)), - (CFComparatorFunction)_compareModes, NULL); - - // Now pull the modes out and put them into optVideoModes - for(int i = 0; i < CFArrayGetCount(goodModes); ++i) - { - CGDisplayModeRef resolution = (CGDisplayModeRef)CFArrayGetValueAtIndex(goodModes, i); - - size_t fWidth = CGDisplayModeGetWidth(resolution); - size_t fHeight = CGDisplayModeGetHeight(resolution); - // allow 16 and 32 bpp - mVideoModes.push_back({uint32(fWidth), uint32(fHeight),0, 16}); - mVideoModes.push_back({uint32(fWidth), uint32(fHeight),0, 32}); - } - - // Release memory - CFRelease(goodModes); - - return mOptions; -} - -RenderWindow* OSXGLSupport::newWindow( const String &name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams ) -{ - NameValuePairList params; - if(miscParams) - params = *miscParams; - params["contextProfile"] = StringConverter::toString(int(mContextProfile)); - - // Create the window, if Cocoa return a Cocoa window - LogManager::getSingleton().logMessage("Creating a Cocoa Compatible Render System"); - CocoaWindow *window = OGRE_NEW CocoaWindow(); - window->create(name, width, height, fullScreen, ¶ms); - - return window; -} - -void OSXGLSupport::start() -{ - LogManager::getSingleton().logMessage( - "********************************************\n" - "*** Starting Mac OS X OpenGL Subsystem ***\n" - "********************************************"); -} - -void OSXGLSupport::stop() -{ - LogManager::getSingleton().logMessage( - "********************************************\n" - "*** Stopping Mac OS X OpenGL Subsystem ***\n" - "********************************************"); -} - -void* OSXGLSupport::getProcAddress( const char* name ) const -{ - return dlsym (RTLD_DEFAULT, name); -} - -CFComparisonResult OSXGLSupport::_compareModes (const void *val1, const void *val2, void *context) -{ - // These are the values we will be interested in... - /* - CGDisplayModeGetWidth - CGDisplayModeGetHeight - CGDisplayModeGetRefreshRate - _getDictionaryLong((mode), kCGDisplayBitsPerPixel) - CGDisplayModeGetIOFlags((mode), kDisplayModeStretchedFlag) - CGDisplayModeGetIOFlags((mode), kDisplayModeSafetyFlags) - */ - - // CFArray comparison callback for sorting display modes. - #pragma unused(context) - CGDisplayModeRef thisMode = (CGDisplayModeRef)val1; - CGDisplayModeRef otherMode = (CGDisplayModeRef)val2; - - size_t width = CGDisplayModeGetWidth(thisMode); - size_t otherWidth = CGDisplayModeGetWidth(otherMode); - - size_t height = CGDisplayModeGetHeight(thisMode); - size_t otherHeight = CGDisplayModeGetHeight(otherMode); - - // Sort modes in screen size order - if (width * height < otherWidth * otherHeight) - { - return kCFCompareLessThan; - } - else if (width * height > otherWidth * otherHeight) - { - return kCFCompareGreaterThan; - } - - // Sort modes by refresh rate. - double refreshRate = CGDisplayModeGetRefreshRate(thisMode); - double otherRefreshRate = CGDisplayModeGetRefreshRate(otherMode); - - if (refreshRate < otherRefreshRate) - { - return kCFCompareLessThan; - } - else if (refreshRate > otherRefreshRate) - { - return kCFCompareGreaterThan; - } - - return kCFCompareEqualTo; -} - -Boolean OSXGLSupport::_getDictionaryBoolean(CFDictionaryRef dict, const void* key) -{ - Boolean value = false; - CFBooleanRef boolRef; - boolRef = (CFBooleanRef)CFDictionaryGetValue(dict, key); - - if (boolRef != NULL) - value = CFBooleanGetValue(boolRef); - - return value; -} - -long OSXGLSupport::_getDictionaryLong(CFDictionaryRef dict, const void* key) -{ - long value = 0; - CFNumberRef numRef; - numRef = (CFNumberRef)CFDictionaryGetValue(dict, key); - - if (numRef != NULL) - CFNumberGetValue(numRef, kCFNumberLongType, &value); - - return value; -} - -} diff --git a/RenderSystems/GLSupport/src/OSX/OgreOSXRenderTexture.cpp b/RenderSystems/GLSupport/src/OSX/OgreOSXRenderTexture.cpp deleted file mode 100644 index 776c7d38b4c..00000000000 --- a/RenderSystems/GLSupport/src/OSX/OgreOSXRenderTexture.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreRoot.h" -#include "OgreStringConverter.h" - -#include "OgreGLRenderSystem.h" - -#include "OgreOSXRenderTexture.h" -#include "OgreOSXCarbonContext.h" - -#include -#define GL_EXT_texture_env_combine 1 -#include -#include - -namespace Ogre -{ - OSXPBuffer::OSXPBuffer( PixelComponentType format, uint32 width, uint32 height ) : GLPBuffer( format, width, height ), mContext( NULL ) - { - LogManager::getSingleton().logMessage( "OSXPBuffer::OSXPBuffer()" ); - createPBuffer(); - // Create context - //mContext = OGRE_NEW OSXCarbonContext(mAGLContext); - } - - OSXPBuffer::~OSXPBuffer() - { - LogManager::getSingleton().logMessage( "OSXPBuffer::~OSXPBuffer()" ); - OGRE_DELETE mContext; - destroyPBuffer(); - } - - GLContext* OSXPBuffer::getContext() const - { - LogManager::getSingleton().logMessage( "OSXPBuffer::getContext()" ); - return mContext; - } - - void OSXPBuffer::createPBuffer() - { - LogManager::getSingleton().logMessage( "OSXPBuffer::createPBuffer()" ); - - GLint attrib[] = { AGL_NO_RECOVERY, GL_TRUE, AGL_ACCELERATED, GL_TRUE, AGL_RGBA, AGL_NONE }; - AGLPixelFormat pixelFormat = aglChoosePixelFormat(NULL, 0, attrib); - mAGLContext = aglCreateContext(pixelFormat, NULL); - - //mAGLContext = aglGetCurrentContext(); - aglCreatePBuffer( mWidth, mHeight, GL_TEXTURE_2D, GL_RGBA, 0, &mPBuffer ); - - GLint vs = aglGetVirtualScreen( mAGLContext ); - aglSetPBuffer( mAGLContext, mPBuffer, 0, 0, vs ); - mContext = OGRE_NEW OSXCocoaContext(mAGLContext, pixelFormat); - } - - void OSXPBuffer::destroyPBuffer() - { - LogManager::getSingleton().logMessage( "OSXPBuffer::destroyPBuffer()" ); - aglDestroyPBuffer( mPBuffer ); - } -} - diff --git a/RenderSystems/GLSupport/src/OgreGLDepthBufferCommon.cpp b/RenderSystems/GLSupport/src/OgreGLDepthBufferCommon.cpp deleted file mode 100644 index 6f9cb5e67c8..00000000000 --- a/RenderSystems/GLSupport/src/OgreGLDepthBufferCommon.cpp +++ /dev/null @@ -1,97 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. - -#include "OgreGLDepthBufferCommon.h" -#include "OgreGLHardwarePixelBufferCommon.h" -#include "OgreGLRenderSystemCommon.h" -#include "OgreGLRenderTexture.h" - -namespace Ogre -{ -GLDepthBufferCommon::GLDepthBufferCommon(uint16 poolId, GLRenderSystemCommon* renderSystem, - GLContext* creatorContext, GLHardwarePixelBufferCommon* depth, - GLHardwarePixelBufferCommon* stencil, const RenderTarget* target, - bool manual) - : DepthBuffer(poolId, target->getWidth(), target->getHeight(), target->getFSAA(), manual), - mCreatorContext(creatorContext), mDepthBuffer(depth), mStencilBuffer(stencil), - mRenderSystem(renderSystem) -{ -} - -GLDepthBufferCommon::~GLDepthBufferCommon() -{ - if (mStencilBuffer && mStencilBuffer != mDepthBuffer) - { - delete mStencilBuffer; - mStencilBuffer = 0; - } - - if (mDepthBuffer) - { - delete mDepthBuffer; - mDepthBuffer = 0; - } -} - -bool GLDepthBufferCommon::isCompatible(RenderTarget* renderTarget) const -{ - bool retVal = false; - - // Check standard stuff first. - if (mRenderSystem->getCapabilities()->hasCapability(RSC_RTT_DEPTHBUFFER_RESOLUTION_LESSEQUAL)) - { - if (!DepthBuffer::isCompatible(renderTarget)) - return false; - } - else - { - if (this->getWidth() != renderTarget->getWidth() || - this->getHeight() != renderTarget->getHeight() || this->getFSAA() != renderTarget->getFSAA()) - return false; - } - - // Now check this is the appropriate format - auto fbo = dynamic_cast(renderTarget)->getFBO(); - - if (!fbo) - { - GLContext* windowContext = dynamic_cast(renderTarget)->getContext(); - - // Non-FBO targets and FBO depth surfaces don't play along, only dummies which match the same - // context - if (!mDepthBuffer && !mStencilBuffer && (!windowContext || mCreatorContext == windowContext)) - retVal = true; - } - else - { - // Check this isn't a dummy non-FBO depth buffer with an FBO target, don't mix them. - // If you don't want depth buffer, use a Null Depth Buffer, not a dummy one. - if (mDepthBuffer || mStencilBuffer) - { - PixelFormat internalFormat = fbo->getFormat(); - uint32 depthFormat, stencilFormat; - mRenderSystem->_getDepthStencilFormatFor(internalFormat, &depthFormat, &stencilFormat); - - bool bSameDepth = false; - - if (mDepthBuffer) - bSameDepth |= mDepthBuffer->getGLFormat() == depthFormat; - - bool bSameStencil = false; - - if (!mStencilBuffer || mStencilBuffer == mDepthBuffer) - bSameStencil = stencilFormat == 0; // GL_NONE - else - { - if (mStencilBuffer) - bSameStencil = stencilFormat == mStencilBuffer->getGLFormat(); - } - - retVal = PixelUtil::isDepth(internalFormat) ? bSameDepth : (bSameDepth && bSameStencil); - } - } - - return retVal; -} -} // namespace Ogre diff --git a/RenderSystems/GLSupport/src/OgreGLHardwarePixelBufferCommon.cpp b/RenderSystems/GLSupport/src/OgreGLHardwarePixelBufferCommon.cpp deleted file mode 100644 index 1763641393c..00000000000 --- a/RenderSystems/GLSupport/src/OgreGLHardwarePixelBufferCommon.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreGLHardwarePixelBufferCommon.h" - -namespace Ogre -{ -GLHardwarePixelBufferCommon::GLHardwarePixelBufferCommon(uint32 inWidth, uint32 inHeight, - uint32 inDepth, PixelFormat inFormat, - HardwareBuffer::Usage usage) - : HardwarePixelBuffer(inWidth, inHeight, inDepth, inFormat, usage, false), - mBuffer(inWidth, inHeight, inDepth, inFormat), - mGLInternalFormat(0) -{ -} - -GLHardwarePixelBufferCommon::~GLHardwarePixelBufferCommon() -{ - // Force free buffer - delete[] mBuffer.data; -} - -void GLHardwarePixelBufferCommon::allocateBuffer() -{ - if (mBuffer.data) - // Already allocated - return; - - mBuffer.data = new uint8[mSizeInBytes]; -} - -void GLHardwarePixelBufferCommon::freeBuffer() -{ - // Free buffer if we're STATIC to save memory - if (mUsage & HBU_STATIC) - { - delete[] mBuffer.data; - mBuffer.data = 0; - } -} - -PixelBox GLHardwarePixelBufferCommon::lockImpl(const Box& lockBox, LockOptions options) -{ - allocateBuffer(); - if (!((mUsage & HBU_DETAIL_WRITE_ONLY) || (options == HBL_DISCARD) || (options == HBL_WRITE_ONLY))) - { - // Download the old contents of the texture - download(mBuffer); - } - return mBuffer.getSubVolume(lockBox); -} - -void GLHardwarePixelBufferCommon::unlockImpl(void) -{ - if (mCurrentLockOptions != HBL_READ_ONLY) - { - // From buffer to card, only upload if was locked for writing. - upload(mCurrentLock, mLockedBox); - } - freeBuffer(); -} - -void GLHardwarePixelBufferCommon::upload(const PixelBox &data, const Box &dest) -{ - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Upload not possible for this pixelbuffer type", - "GLHardwarePixelBufferCommon::upload"); -} - -void GLHardwarePixelBufferCommon::download(const PixelBox &data) -{ - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Download not possible for this pixelbuffer type", - "GLHardwarePixelBufferCommon::download"); -} - -void GLHardwarePixelBufferCommon::bindToFramebuffer(uint32 attachment, uint32 zoffset) -{ - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Framebuffer bind not possible for this pixelbuffer type", - "GLHardwarePixelBufferCommon::bindToFramebuffer"); -} - -} /* namespace Ogre */ diff --git a/RenderSystems/GLSupport/src/OgreGLRenderSystemCommon.cpp b/RenderSystems/GLSupport/src/OgreGLRenderSystemCommon.cpp deleted file mode 100644 index 599dbb7325e..00000000000 --- a/RenderSystems/GLSupport/src/OgreGLRenderSystemCommon.cpp +++ /dev/null @@ -1,266 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreGLRenderSystemCommon.h" -#include "OgreGLContext.h" -#include "OgreGLNativeSupport.h" -#include "OgreGLRenderTexture.h" - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN -#include "OgreEGLWindow.h" -#endif - -namespace Ogre { - static void removeDuplicates(std::vector& c) - { - std::sort(c.begin(), c.end()); - auto p = std::unique(c.begin(), c.end()); - c.erase(p, c.end()); - } - - String VideoMode::getDescription() const - { - return StringUtil::format("%4d x %4d", width, height); - } - - void GLRenderSystemCommon::initConfigOptions() - { - mOptions = mGLSupport->getConfigOptions(); - - RenderSystem::initConfigOptions(); - - ConfigOption optDisplayFrequency; - optDisplayFrequency.name = "Display Frequency"; - optDisplayFrequency.immutable = false; - mOptions[optDisplayFrequency.name] = optDisplayFrequency; - - ConfigOption optVideoMode; - optVideoMode.name = "Video Mode"; - optVideoMode.immutable = false; - for (const auto& mode : mGLSupport->getVideoModes()) - { - optVideoMode.possibleValues.push_back(mode.getDescription()); - } - removeDuplicates(optVideoMode.possibleValues); // also sorts - - if(!optVideoMode.possibleValues.empty()) // otherwise keep dummy defaults - { - optVideoMode.currentValue = optVideoMode.possibleValues[0]; - mOptions[optVideoMode.name] = optVideoMode; - } - - ConfigOption optFSAA; - optFSAA.name = "FSAA"; - optFSAA.immutable = false; - for (int sampleLevel : mGLSupport->getFSAALevels()) - { - optFSAA.possibleValues.push_back(StringConverter::toString(sampleLevel)); - } - if (!optFSAA.possibleValues.empty()) - { - removeDuplicates(optFSAA.possibleValues); - optFSAA.currentValue = optFSAA.possibleValues[0]; - } - mOptions[optFSAA.name] = optFSAA; - - refreshConfig(); - } - - void GLRenderSystemCommon::refreshConfig() - { - // set bpp and refresh rate as appropriate - ConfigOptionMap::iterator optVideoMode = mOptions.find("Video Mode"); - ConfigOptionMap::iterator optDisplayFrequency = mOptions.find("Display Frequency"); - ConfigOptionMap::iterator optFullScreen = mOptions.find("Full Screen"); - ConfigOptionMap::iterator optColourDepth = mOptions.find("Colour Depth"); - - // coulour depth is optional - if (optColourDepth != mOptions.end()) - { - for (const auto& mode : mGLSupport->getVideoModes()) - { - if (mode.getDescription() == optVideoMode->second.currentValue) - { - optColourDepth->second.possibleValues.push_back( - StringConverter::toString((unsigned int)mode.bpp)); - } - } - - removeDuplicates(optColourDepth->second.possibleValues); - } - - // we can only set refresh rate in full screen mode - bool isFullscreen = false; - if( optFullScreen != mOptions.end()) - isFullscreen = optFullScreen->second.currentValue == "Yes"; - - if (optVideoMode == mOptions.end() || optDisplayFrequency == mOptions.end()) - return; - - optDisplayFrequency->second.possibleValues.clear(); - if (isFullscreen) - { - for (const auto& mode : mGLSupport->getVideoModes()) - { - if (mode.getDescription() == optVideoMode->second.currentValue) - { - String frequency = StringConverter::toString(mode.refreshRate) + " Hz"; - optDisplayFrequency->second.possibleValues.push_back(frequency); - - if(optColourDepth != mOptions.end()) - optColourDepth->second.possibleValues.push_back( - StringConverter::toString((unsigned int)mode.bpp)); - } - } - - removeDuplicates(optDisplayFrequency->second.possibleValues); - } - - if (optDisplayFrequency->second.possibleValues.empty()) - { - optDisplayFrequency->second.possibleValues.push_back("N/A"); - optDisplayFrequency->second.immutable = true; - } - - optDisplayFrequency->second.currentValue = optDisplayFrequency->second.possibleValues.front(); - } - - //-------------------------------------------------------------------------------------------------// - void GLRenderSystemCommon::setConfigOption(const String &name, const String &value) - { - ConfigOptionMap::iterator option = mOptions.find(name); - if (option == mOptions.end()) { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Option named '" + name + "' does not exist."); - } - option->second.currentValue = value; - - if( name == "Video Mode" || name == "Full Screen" ) - refreshConfig(); - } - - bool GLRenderSystemCommon::checkExtension(const String& ext) const - { - return mExtensionList.find(ext) != mExtensionList.end() || mGLSupport->checkExtension(ext); - } - - bool GLRenderSystemCommon::hasMinGLVersion(int major, int minor) const - { - if (mDriverVersion.major == major) { - return mDriverVersion.minor >= minor; - } - return mDriverVersion.major > major; - } - - void GLRenderSystemCommon::_completeDeferredVaoFboDestruction() - { - if(GLContext* ctx = mCurrentContext) - { - std::vector& vaos = ctx->_getVaoDeferredForDestruction(); - while(!vaos.empty()) - { - _destroyVao(ctx, vaos.back()); - vaos.pop_back(); - } - - std::vector& fbos = ctx->_getFboDeferredForDestruction(); - while(!fbos.empty()) - { - _destroyFbo(ctx, fbos.back()); - fbos.pop_back(); - } - - } - } - - void GLRenderSystemCommon::_convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest, bool) - { - // no conversion required for OpenGL - dest = matrix; - - if (mIsReverseDepthBufferEnabled) - { - // Convert depth range from [-1,+1] to [1,0] - dest[2][0] = (dest[2][0] - dest[3][0]) * -0.5f; - dest[2][1] = (dest[2][1] - dest[3][1]) * -0.5f; - dest[2][2] = (dest[2][2] - dest[3][2]) * -0.5f; - dest[2][3] = (dest[2][3] - dest[3][3]) * -0.5f; - } - } - - void GLRenderSystemCommon::_getDepthStencilFormatFor(PixelFormat internalColourFormat, - uint32* depthFormat, uint32* stencilFormat) - { - mRTTManager->getBestDepthStencil( internalColourFormat, depthFormat, stencilFormat ); - } - - void GLRenderSystemCommon::registerThread() - { - OGRE_LOCK_MUTEX(mThreadInitMutex); - // This is only valid once we've created the main context - if (!mMainContext) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Cannot register a background thread before the main context has been created"); - } - - // Create a new context for this thread. Cloning from the main context - // will ensure that resources are shared with the main context - // We want a separate context so that we can safely create GL - // objects in parallel with the main thread - GLContext* newContext = mMainContext->clone(); - mBackgroundContextList.push_back(newContext); - - // Bind this new context to this thread. - newContext->setCurrent(); - - _oneTimeContextInitialization(); - newContext->setInitialized(); - } - - void GLRenderSystemCommon::unregisterThread() - { - // nothing to do here? - // Don't need to worry about active context, just make sure we delete - // on shutdown. - } - - void GLRenderSystemCommon::preExtraThreadsStarted() - { - OGRE_LOCK_MUTEX(mThreadInitMutex); - // free context, we'll need this to share lists - if (mCurrentContext) - mCurrentContext->endCurrent(); - } - - void GLRenderSystemCommon::postExtraThreadsStarted() - { - OGRE_LOCK_MUTEX(mThreadInitMutex); - // reacquire context - if (mCurrentContext) - mCurrentContext->setCurrent(); - } -} diff --git a/RenderSystems/GLSupport/src/OgreGLRenderTexture.cpp b/RenderSystems/GLSupport/src/OgreGLRenderTexture.cpp deleted file mode 100644 index 3e1079a15af..00000000000 --- a/RenderSystems/GLSupport/src/OgreGLRenderTexture.cpp +++ /dev/null @@ -1,187 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGLRenderTexture.h" -#include "OgreGLHardwarePixelBufferCommon.h" -#include "OgreGLRenderSystemCommon.h" -#include "OgreRoot.h" - -namespace Ogre { - - const String GLRenderTexture::CustomAttributeString_FBO = "FBO"; - const String GLRenderTexture::CustomAttributeString_TARGET = "TARGET"; - const String GLRenderTexture::CustomAttributeString_GLCONTEXT = "GLCONTEXT"; - - template<> GLRTTManager* Singleton::msSingleton = NULL; - - GLFrameBufferObjectCommon::GLFrameBufferObjectCommon(int32 fsaa) - : mFB(0), mMultisampleFB(0), mNumSamples(fsaa) - { - auto* rs = static_cast( - Root::getSingleton().getRenderSystem()); - mContext = rs->_getCurrentContext(); - - // Initialise state - mDepth.buffer = 0; - mStencil.buffer = 0; - for(auto & x : mColour) - { - x.buffer=0; - } - } - - void GLFrameBufferObjectCommon::bindSurface(size_t attachment, const GLSurfaceDesc &target) - { - assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS); - mColour[attachment] = target; - // Re-initialise - if(mColour[0].buffer) - initialise(); - } - - void GLFrameBufferObjectCommon::unbindSurface(size_t attachment) - { - assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS); - mColour[attachment].buffer = 0; - // Re-initialise if buffer 0 still bound - if(mColour[0].buffer) - initialise(); - } - - uint32 GLFrameBufferObjectCommon::getWidth() const - { - assert(mColour[0].buffer); - return mColour[0].buffer->getWidth(); - } - uint32 GLFrameBufferObjectCommon::getHeight() const - { - assert(mColour[0].buffer); - return mColour[0].buffer->getHeight(); - } - PixelFormat GLFrameBufferObjectCommon::getFormat() const - { - assert(mColour[0].buffer); - return mColour[0].buffer->getFormat(); - } - - GLRTTManager* GLRTTManager::getSingletonPtr(void) - { - return msSingleton; - } - GLRTTManager& GLRTTManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - - GLRTTManager::GLRTTManager() {} - // need to implement in cpp due to how Ogre::Singleton works - GLRTTManager::~GLRTTManager() {} - - PixelFormat GLRTTManager::getSupportedAlternative(PixelFormat format) - { - if (checkFormat(format)) - { - return format; - } - - if(PixelUtil::isDepth(format)) - { - switch (format) - { - default: - case PF_DEPTH16: - format = PF_FLOAT16_R; - break; - case PF_DEPTH24_STENCIL8: - case PF_DEPTH32F: - case PF_DEPTH32: - format = PF_FLOAT32_R; - break; - } - } - else - { - /// Find first alternative - switch (PixelUtil::getComponentType(format)) - { - case PCT_BYTE: - format = PF_BYTE_RGBA; // native endian - break; - case PCT_SHORT: - format = PF_SHORT_RGBA; - break; - case PCT_FLOAT16: - format = PF_FLOAT16_RGBA; - break; - case PCT_FLOAT32: - format = PF_FLOAT32_RGBA; - break; - default: - break; - } - } - - if (checkFormat(format)) - return format; - - /// If none at all, return to default - return PF_BYTE_RGBA; // native endian - } - - void GLRTTManager::releaseRenderBuffer(const GLSurfaceDesc &surface) - { - if(surface.buffer == 0) - return; - RBFormat key(surface.buffer->getGLFormat(), surface.buffer->getWidth(), surface.buffer->getHeight(), surface.numSamples); - RenderBufferMap::iterator it = mRenderBufferMap.find(key); - if(it != mRenderBufferMap.end()) - { - // Decrease refcount - --it->second.refcount; - if(it->second.refcount==0) - { - // If refcount reaches zero, delete buffer and remove from map - delete it->second.buffer; - mRenderBufferMap.erase(it); - // std::cerr << "Destroyed renderbuffer of format " << std::hex << key.format << std::dec - // << " of " << key.width << "x" << key.height << std::endl; - } - } - } - - GLRenderTexture::GLRenderTexture(const String &name, - const GLSurfaceDesc &target, - bool writeGamma, - uint fsaa) - : RenderTexture(target.buffer, target.zoffset) - { - mName = name; - mHwGamma = writeGamma; - mFSAA = fsaa; - } -} diff --git a/RenderSystems/GLSupport/src/OgreGLRenderToVertexBufferCommon.cpp b/RenderSystems/GLSupport/src/OgreGLRenderToVertexBufferCommon.cpp deleted file mode 100644 index da9fbdad59f..00000000000 --- a/RenderSystems/GLSupport/src/OgreGLRenderToVertexBufferCommon.cpp +++ /dev/null @@ -1,59 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#include "OgreGLRenderToVertexBufferCommon.h" - -#include "OgreHardwareBufferManager.h" - -namespace Ogre -{ - -void GLRenderToVertexBufferCommon::reallocateBuffer(uint8 index) -{ - assert(index < 2); - - // Transform feedback buffer must be at least as large as the - // number of output primitives. - mVertexBuffers[index] = HardwareBufferManager::getSingleton().createVertexBuffer( - mVertexData->vertexDeclaration->getVertexSize(0), mMaxVertexCount, HBU_GPU_ONLY); -} - -String GLRenderToVertexBufferCommon::getSemanticVaryingName(VertexElementSemantic semantic, - unsigned short index) -{ - switch (semantic) - { - case VES_POSITION: - return "xfb_position"; - case VES_NORMAL: - return "xfb_normal"; - case VES_TEXTURE_COORDINATES: - return StringUtil::format("xfb_uv%d", index); - case VES_DIFFUSE: - return "xfb_colour"; - case VES_SPECULAR: - return "xfb_colour2"; - default: - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unsupported VertexElementSemantic"); - } -} - -uint32 GLRenderToVertexBufferCommon::getVertexCountPerPrimitive(RenderOperation::OperationType operationType) -{ - // We can only get points, lines or triangles since they are the only - // legal R2VB output primitive types. - switch (operationType) - { - case RenderOperation::OT_POINT_LIST: - return 1; - case RenderOperation::OT_LINE_LIST: - return 2; - default: - case RenderOperation::OT_TRIANGLE_LIST: - return 3; - } -} - -} /* namespace Ogre */ diff --git a/RenderSystems/GLSupport/src/OgreGLTextureCommon.cpp b/RenderSystems/GLSupport/src/OgreGLTextureCommon.cpp deleted file mode 100644 index d90caa1e463..00000000000 --- a/RenderSystems/GLSupport/src/OgreGLTextureCommon.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreGLTextureCommon.h" -#include "OgreResourceGroupManager.h" -#include "OgreRoot.h" -#include "OgreBitwise.h" - -namespace Ogre -{ -void GLTextureCommon::getCustomAttribute(const String& name, void* pData) -{ - if (name == "GLID") - *static_cast(pData) = mTextureID; -} - -} /* namespace Ogre */ diff --git a/RenderSystems/GLSupport/src/OgreGLUniformCache.cpp b/RenderSystems/GLSupport/src/OgreGLUniformCache.cpp deleted file mode 100644 index d2fd9284583..00000000000 --- a/RenderSystems/GLSupport/src/OgreGLUniformCache.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2012 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ - -#include "OgreGLUniformCache.h" -#include "OgreCommon.h" - -namespace Ogre { - - void GLUniformCache::clearCache() - { -#ifdef OGRE_ENABLE_STATE_CACHE - mUniformValueMap.clear(); -#endif - } - - bool GLUniformCache::updateUniform(int location, const void *value, int length) - { -#ifdef OGRE_ENABLE_STATE_CACHE - uint32 current = mUniformValueMap[location]; - uint32 hash = Ogre::FastHash((const char *)value, length); - // First check if the uniform name is in the map. If not, this is new so insert it into the map. - if (!current || (current != hash)) - { - // Haven't cached this state yet or the value has changed - mUniformValueMap[location] = hash; - return true; - } - - return false; -#else - return true; -#endif - } -} diff --git a/RenderSystems/GLSupport/src/OgreGLVertexArrayObject.cpp b/RenderSystems/GLSupport/src/OgreGLVertexArrayObject.cpp deleted file mode 100644 index d4088fbe68d..00000000000 --- a/RenderSystems/GLSupport/src/OgreGLVertexArrayObject.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#include "OgreGLVertexArrayObject.h" -#include "OgreRoot.h" -#include "OgreLogManager.h" -#include "OgreGLSLProgramCommon.h" -#include "OgreGLRenderSystemCommon.h" - -namespace Ogre { - GLVertexArrayObject::GLVertexArrayObject() : mCreatorContext(0), mVAO(0), mNeedsUpdate(true), mVertexStart(0) { - } - - GLVertexArrayObject::~GLVertexArrayObject() - { - if(mVAO != 0) - { - GLRenderSystemCommon* rs = static_cast(Root::getSingleton().getRenderSystem()); - rs->_destroyVao(mCreatorContext, mVAO); - } - } - - void GLVertexArrayObject::bind(GLRenderSystemCommon* rs) - { - if(mCreatorContext && mCreatorContext != rs->_getCurrentContext()) // VAO is unusable with current context, destroy it - { - if(mVAO != 0) - rs->_destroyVao(mCreatorContext, mVAO); - mCreatorContext = 0; - mVAO = 0; - mNeedsUpdate = true; - } - if(!mCreatorContext && rs->getCapabilities()->hasCapability(RSC_VAO)) // create VAO lazy or recreate after destruction - { - mCreatorContext = rs->_getCurrentContext(); - mVAO = rs->_createVao(); - mNeedsUpdate = true; - } - rs->_bindVao(mCreatorContext, mVAO); - } - - bool GLVertexArrayObject::needsUpdate(VertexBufferBinding* vertexBufferBinding, - size_t vertexStart) - { - if(mNeedsUpdate) - return true; - - for (const auto& elem : mElementList) - { - uint16 source = elem.getSource(); - - if (!vertexBufferBinding->isBufferBound(source)) - continue; // Skip unbound elements - - VertexElementSemantic sem = elem.getSemantic(); - unsigned short elemIndex = elem.getIndex(); - - uint32 attrib = (uint32)GLSLProgramCommon::getFixedAttributeIndex(sem, elemIndex); - - const HardwareVertexBufferSharedPtr& vertexBuffer = vertexBufferBinding->getBuffer(source); - if (std::find(mAttribsBound.begin(), mAttribsBound.end(), - std::make_pair(attrib, vertexBuffer.get())) == mAttribsBound.end()) - return true; - - if (vertexBuffer->isInstanceData() && - std::find(mInstanceAttribsBound.begin(), mInstanceAttribsBound.end(), attrib) == - mInstanceAttribsBound.end()) - return true; - } - - if(vertexStart != mVertexStart) { - return true; - } - - return false; - } - - void GLVertexArrayObject::bindToGpu(GLRenderSystemCommon* rs, - VertexBufferBinding* vertexBufferBinding, - size_t vertexStart) - { - mAttribsBound.clear(); - mInstanceAttribsBound.clear(); - - for (const auto& elem : mElementList) - { - uint16 source = elem.getSource(); - - if (!vertexBufferBinding->isBufferBound(source)) - continue; // Skip unbound elements - - VertexElementSemantic sem = elem.getSemantic(); - unsigned short elemIndex = elem.getIndex(); - - uint32 attrib = (uint32)GLSLProgramCommon::getFixedAttributeIndex(sem, elemIndex); - - const HardwareVertexBufferSharedPtr& vertexBuffer = vertexBufferBinding->getBuffer(source); - - mAttribsBound.push_back(std::make_pair(attrib, vertexBuffer.get())); - - rs->bindVertexElementToGpu(elem, vertexBuffer, vertexStart); - - if (vertexBuffer->isInstanceData()) - mInstanceAttribsBound.push_back(attrib); - } - - mVertexStart = vertexStart; - mNeedsUpdate = false; - } -} diff --git a/RenderSystems/GLSupport/src/OgreGLWindow.cpp b/RenderSystems/GLSupport/src/OgreGLWindow.cpp deleted file mode 100644 index 14bea75beab..00000000000 --- a/RenderSystems/GLSupport/src/OgreGLWindow.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreGLWindow.h" -#include "OgreException.h" -#include "OgreGLRenderSystemCommon.h" -#include "OgreRoot.h" - -namespace Ogre -{ -GLWindow::GLWindow() : mContext(0) -{ - mIsTopLevel = false; - mIsFullScreen = false; - mIsExternal = false; - mIsExternalGLControl = false; - mActive = false; - mHidden = false; - mVisible = false; - mVSync = false; -} - -//-------------------------------------------------------------------------------------------------// -void GLWindow::setVSyncInterval(unsigned int interval) -{ - mVSyncInterval = interval; - if (mVSync) - setVSyncEnabled(true); -} - -void GLWindow::copyContentsToMemory(const Box& src, const PixelBox& dst, FrameBuffer buffer) -{ - if (mClosed) - return; - - if (src.right > mWidth || src.bottom > mHeight || src.front != 0 || src.back != 1 || - dst.getWidth() != src.getWidth() || dst.getHeight() != src.getHeight() || dst.getDepth() != 1) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Invalid box"); - } - - if (buffer == FB_AUTO) - { - buffer = mIsFullScreen ? FB_FRONT : FB_BACK; - } - - static_cast(Root::getSingleton().getRenderSystem()) - ->_copyContentsToMemory(getViewport(0), src, dst, buffer); -} -} // namespace Ogre diff --git a/RenderSystems/GLSupport/src/X11/OgreX11.cpp b/RenderSystems/GLSupport/src/X11/OgreX11.cpp deleted file mode 100644 index e21ec71e212..00000000000 --- a/RenderSystems/GLSupport/src/X11/OgreX11.cpp +++ /dev/null @@ -1,205 +0,0 @@ -#include -#include - -#include - -namespace { - int safeXErrorHandler (Display *display, XErrorEvent *event) - { - // Ignore all XErrorEvents - return 0; - } - int (*oldXErrorHandler)(Display *, XErrorEvent*); -} - -namespace Ogre -{ -Display* getXDisplay(Display* glDisplay, Atom& deleteWindow, Atom& fullScreen, Atom& state) -{ - char* displayString = glDisplay ? DisplayString(glDisplay) : NULL; - - auto xDisplay = XOpenDisplay(displayString); - - if (!xDisplay) - return xDisplay; - - deleteWindow = XInternAtom(xDisplay, "WM_DELETE_WINDOW", True); - fullScreen = XInternAtom(xDisplay, "_NET_WM_STATE_FULLSCREEN", True); - state = XInternAtom(xDisplay, "_NET_WM_STATE", True); - return xDisplay; -} - -void validateParentWindow(Display* display, Window parentWindow) -{ - // Ignore fatal XErrorEvents during parameter validation: - oldXErrorHandler = XSetErrorHandler(safeXErrorHandler); - - // Validate parentWindowHandle - if (parentWindow != DefaultRootWindow(display)) - { - XWindowAttributes windowAttrib; - - if (!XGetWindowAttributes(display, parentWindow, &windowAttrib) || - windowAttrib.root != DefaultRootWindow(display)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Invalid parentWindowHandle (wrong server or screen)"); - } - } - - XSetErrorHandler(oldXErrorHandler); -} - -Window createXWindow(Display* display, Window parent, XVisualInfo* visualInfo, int& left, int& top, uint& width, - uint& height, Atom wmFullScreen, bool fullScreen) -{ - XSetWindowAttributes attr; - attr.background_pixel = 0; - attr.border_pixel = 0; - attr.colormap = XCreateColormap(display, DefaultRootWindow(display), visualInfo->visual, AllocNone); - attr.event_mask = StructureNotifyMask | VisibilityChangeMask | FocusChangeMask; - - ulong mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask; - - if (fullScreen && wmFullScreen == None) - { - LogManager::getSingleton().logWarning("createXWindow: Your WM has no fullscreen support"); - - // A second best approach for outdated window managers - attr.backing_store = NotUseful; - attr.save_under = False; - attr.override_redirect = True; - mask |= CWSaveUnder | CWBackingStore | CWOverrideRedirect; - left = top = 0; - } - - auto window = XCreateWindow(display, parent, left, top, width, height, 0, visualInfo->depth, InputOutput, - visualInfo->visual, mask, &attr); - XFree(visualInfo); - - if (!window) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unable to create an X Window"); - } - - return window; -} - -void destroyXWindow(Display* display, Window window) -{ - // Ignore fatal XErrorEvents from stale handles. - oldXErrorHandler = XSetErrorHandler(safeXErrorHandler); - XDestroyWindow(display, window); - XSetErrorHandler(oldXErrorHandler); -} - -void queryRect(Display* display, Window window, int& left, int& top, uint& width, uint& height, bool queryOffset) -{ - XWindowAttributes windowAttrib; - - Window parent, root, *children; - uint nChildren; - - XQueryTree(display, window, &root, &parent, &children, &nChildren); - - if (children) - XFree(children); - - XGetWindowAttributes(display, parent, &windowAttrib); - - if (queryOffset) - { - // offset from window decorations - left = windowAttrib.x; - top = windowAttrib.y; - // w/ h of the actual renderwindow - XGetWindowAttributes(display, window, &windowAttrib); - } - - width = windowAttrib.width; - height = windowAttrib.height; -} - -void finaliseTopLevel(Display* display, Window window, int& left, int& top, uint& width, uint& height, String& title, Atom wmDelete) -{ - XWMHints* wmHints; - XSizeHints* sizeHints; - - // Is this really necessary ? Which broken WM might need it? - if ((wmHints = XAllocWMHints()) != NULL) - { - wmHints->initial_state = NormalState; - wmHints->input = True; - wmHints->flags = StateHint | InputHint; - } - - // Is this really necessary ? Which broken WM might need it? - if ((sizeHints = XAllocSizeHints()) != NULL) - { - sizeHints->flags = USPosition; - } - - XTextProperty titleprop; - char* lst = const_cast(title.c_str()); - XStringListToTextProperty(&lst, 1, &titleprop); - XSetWMProperties(display, window, &titleprop, NULL, NULL, 0, sizeHints, wmHints, NULL); - - XFree(titleprop.value); - XFree(wmHints); - XFree(sizeHints); - - XSetWMProtocols(display, window, &wmDelete, 1); - - XWindowAttributes windowAttrib; - - XGetWindowAttributes(display, window, &windowAttrib); - - left = windowAttrib.x; - top = windowAttrib.y; - width = windowAttrib.width; - height = windowAttrib.height; -} - -bool getXVideoModes(Display* display, VideoMode& currentMode, VideoModes& videoModes) -{ - int dummy; - if (!XQueryExtension(display, "RANDR", &dummy, &dummy, &dummy)) - return false; - - auto screenConfig = XRRGetScreenInfo(display, DefaultRootWindow(display)); - if (!screenConfig) - return false; - - XRRScreenSize* screenSizes; - int nSizes = 0; - Rotation currentRotation; - int currentSizeID = XRRConfigCurrentConfiguration(screenConfig, ¤tRotation); - - screenSizes = XRRConfigSizes(screenConfig, &nSizes); - - currentMode.width = screenSizes[currentSizeID].width; - currentMode.height = screenSizes[currentSizeID].height; - currentMode.refreshRate = XRRConfigCurrentRate(screenConfig); - - for (int sizeID = 0; sizeID < nSizes; sizeID++) - { - short* rates; - int nRates = 0; - - rates = XRRConfigRates(screenConfig, sizeID, &nRates); - - for (int rate = 0; rate < nRates; rate++) - { - VideoMode mode = {}; - - mode.width = screenSizes[sizeID].width; - mode.height = screenSizes[sizeID].height; - mode.refreshRate = rates[rate]; - - videoModes.push_back(mode); - } - } - XRRFreeScreenConfigInfo(screenConfig); - - return true; -} -} // namespace Ogre \ No newline at end of file diff --git a/RenderSystems/GLSupport/src/X11/OgreX11.h b/RenderSystems/GLSupport/src/X11/OgreX11.h deleted file mode 100644 index 2e4c7bee204..00000000000 --- a/RenderSystems/GLSupport/src/X11/OgreX11.h +++ /dev/null @@ -1,38 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#ifndef OGRE_X11_H__ -#define OGRE_X11_H__ - -#include -#include - -#ifndef Status -#define Status int -#endif - -#include -#include - -namespace Ogre -{ -Display* getXDisplay(Display* glDisplay, Atom& deleteWindow, Atom& fullScreen, Atom& state); - -void validateParentWindow(Display* display, Window parentWindow); - -Window createXWindow(Display* display, Window parent, XVisualInfo* visualInfo, int& left, int& top, uint& width, - uint& height, Atom wmFullScreen, bool fullScreen); - -void destroyXWindow(Display* display, Window window); - -void queryRect(Display* display, Window window, int& left, int& top, uint& width, uint& height, bool queryOffset); - -void finaliseTopLevel(Display* display, Window window, int& left, int& top, uint& width, uint& height, String& title, - Atom wmDelete); - -bool getXVideoModes(Display* display, VideoMode& currentMode, VideoModes& videoModes); -} // namespace Ogre - -#endif \ No newline at end of file diff --git a/RenderSystems/GLSupport/src/win32/OgreWin32Context.cpp b/RenderSystems/GLSupport/src/win32/OgreWin32Context.cpp deleted file mode 100644 index 55c8daadb40..00000000000 --- a/RenderSystems/GLSupport/src/win32/OgreWin32Context.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef _WIN32_WINNT -#define _WIN32_WINNT 0x0502 -#endif -#include "OgreWin32Context.h" -#include "OgreException.h" -#include "OgreGLRenderSystemCommon.h" -#include "OgreRoot.h" -#include "OgreWin32GLSupport.h" - -namespace Ogre { - - Win32Context::Win32Context(HDC HDC, HGLRC Glrc, Win32GLSupport &glsupport): - mHDC(HDC), - mGlrc(Glrc), - mGLSupport(glsupport) - { - } - - Win32Context::~Win32Context() - { - // NB have to do this is subclass to ensure any methods called back - // are on this subclass and not half-destructed superclass - GLRenderSystemCommon *rs = static_cast(Root::getSingleton().getRenderSystem()); - rs->_unregisterContext(this); - } - - void Win32Context::setCurrent() - { - wglMakeCurrent(mHDC, mGlrc); - } - void Win32Context::endCurrent() - { - wglMakeCurrent(NULL, NULL); - } - - GLContext* Win32Context::clone() const - { - HGLRC oldrc = wglGetCurrentContext(); - // Create new context based on own HDC - HGLRC newCtx = mGLSupport.createNewContext(mHDC, oldrc); - - HDC oldhdc = wglGetCurrentDC(); - - // restore old context - wglMakeCurrent(oldhdc, oldrc); - - return new Win32Context(mHDC, newCtx, mGLSupport); - } - - void Win32Context::releaseContext() - { - if (mGlrc != NULL) - { - wglDeleteContext(mGlrc); - mGlrc = NULL; - mHDC = NULL; - } - } -} diff --git a/RenderSystems/GLSupport/src/win32/OgreWin32GLSupport.cpp b/RenderSystems/GLSupport/src/win32/OgreWin32GLSupport.cpp deleted file mode 100644 index 0343ddde39c..00000000000 --- a/RenderSystems/GLSupport/src/win32/OgreWin32GLSupport.cpp +++ /dev/null @@ -1,542 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#include "OgreRoot.h" -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" - -#include - -#include "OgreWin32GLSupport.h" -#include "OgreWin32Window.h" -#include "OgreGLUtil.h" - -#include -#include - -static PFNWGLCREATECONTEXTATTRIBSARBPROC _wglCreateContextAttribsARB = 0; - -static int glMajorMax = 0; -static int glMinorMax = 0; - -namespace Ogre { - GLNativeSupport* getGLSupport(int profile) - { - return new Win32GLSupport(profile); - } - - Win32GLSupport::Win32GLSupport(int profile) - : GLNativeSupport(profile) - , mInitialWindow(0) - , mHasPixelFormatARB(false) - , mHasMultisample(false) - , mHasHardwareGamma(false) - , mWglChoosePixelFormat(0) - { - // immediately test WGL_ARB_pixel_format and FSAA support - // so we can set configuration options appropriately - initialiseWGL(); - } - - ConfigOptionMap Win32GLSupport::getConfigOptions() - { - ConfigOptionMap mOptions; - - //TODO: EnumDisplayDevices http://msdn.microsoft.com/library/en-us/gdi/devcons_2303.asp - /*vector DisplayDevices; - DISPLAY_DEVICE DisplayDevice; - DisplayDevice.cb = sizeof(DISPLAY_DEVICE); - DWORD i=0; - while (EnumDisplayDevices(NULL, i++, &DisplayDevice, 0) { - DisplayDevices.push_back(DisplayDevice.DeviceName); - }*/ - - // Video mode possibilities - DEVMODE DevMode; - DevMode.dmSize = sizeof(DEVMODE); - for (DWORD i = 0; EnumDisplaySettings(NULL, i, &DevMode); ++i) - { - if (DevMode.dmBitsPerPel < 16 || DevMode.dmPelsHeight < 480) - continue; - mVideoModes.push_back({DevMode.dmPelsWidth, DevMode.dmPelsHeight, - short(DevMode.dmDisplayFrequency), uint8(DevMode.dmBitsPerPel)}); - } - - ConfigOption optColourDepth; - optColourDepth.name = "Colour Depth"; - optColourDepth.immutable = false; - - mOptions[optColourDepth.name] = optColourDepth; - - return mOptions; - } - - BOOL CALLBACK Win32GLSupport::sCreateMonitorsInfoEnumProc( - HMONITOR hMonitor, // handle to display monitor - HDC hdcMonitor, // handle to monitor DC - LPRECT lprcMonitor, // monitor intersection rectangle - LPARAM dwData // data - ) - { - DisplayMonitorInfoList* pArrMonitorsInfo = (DisplayMonitorInfoList*)dwData; - - // Get monitor info - DisplayMonitorInfo displayMonitorInfo; - - displayMonitorInfo.hMonitor = hMonitor; - - memset(&displayMonitorInfo.monitorInfoEx, 0, sizeof(MONITORINFOEX)); - displayMonitorInfo.monitorInfoEx.cbSize = sizeof(MONITORINFOEX); - GetMonitorInfo(hMonitor, &displayMonitorInfo.monitorInfoEx); - - pArrMonitorsInfo->push_back(displayMonitorInfo); - - return TRUE; - } - - - RenderWindow* Win32GLSupport::newWindow(const String &name, unsigned int width, - unsigned int height, bool fullScreen, const NameValuePairList *miscParams) - { - Win32Window* window = OGRE_NEW Win32Window(*this); - NameValuePairList newParams; - - if (miscParams != NULL) - { - newParams = *miscParams; - miscParams = &newParams; - - NameValuePairList::const_iterator monitorIndexIt = miscParams->find("monitorIndex"); - HMONITOR hMonitor = NULL; - int monitorIndex = -1; - - // If monitor index found, try to assign the monitor handle based on it. - if (monitorIndexIt != miscParams->end()) - { - if (mMonitorInfoList.empty()) - EnumDisplayMonitors(NULL, NULL, sCreateMonitorsInfoEnumProc, (LPARAM)&mMonitorInfoList); - - monitorIndex = StringConverter::parseInt(monitorIndexIt->second); - if (monitorIndex < (int)mMonitorInfoList.size()) - { - hMonitor = mMonitorInfoList[monitorIndex].hMonitor; - } - } - // If we didn't specified the monitor index, or if it didn't find it - if (hMonitor == NULL) - { - POINT windowAnchorPoint; - - NameValuePairList::const_iterator opt; - int left = -1; - int top = -1; - - if ((opt = newParams.find("left")) != newParams.end()) - left = StringConverter::parseInt(opt->second); - - if ((opt = newParams.find("top")) != newParams.end()) - top = StringConverter::parseInt(opt->second); - - // Fill in anchor point. - windowAnchorPoint.x = left; - windowAnchorPoint.y = top; - - - // Get the nearest monitor to this window. - hMonitor = MonitorFromPoint(windowAnchorPoint, MONITOR_DEFAULTTOPRIMARY); - } - - newParams["monitorHandle"] = StringConverter::toString((size_t)hMonitor); - } - - window->create(name, width, height, fullScreen, miscParams); - - if(!mInitialWindow) { - mInitialWindow = window; - initialiseExtensions(); - } - - return window; - } - - void Win32GLSupport::start() - { - LogManager::getSingleton().logMessage("*** Starting Win32GL Subsystem ***"); - } - - void Win32GLSupport::stop() - { - LogManager::getSingleton().logMessage("*** Stopping Win32GL Subsystem ***"); - mInitialWindow = 0; // Since there is no removeWindow, although there should be... - } - - void Win32GLSupport::initialiseExtensions() - { - assert(mInitialWindow); - - // Check for W32 specific extensions probe function - PFNWGLGETEXTENSIONSSTRINGARBPROC _wglGetExtensionsStringARB = - (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB"); - if(!_wglGetExtensionsStringARB) - return; - const char *wgl_extensions = _wglGetExtensionsStringARB(mInitialWindow->getHDC()); - LogManager::getSingleton().stream() - << "Supported WGL extensions: " << wgl_extensions; - // Parse them, and add them to the main list - StringStream ext; - String instr; - ext << wgl_extensions; - while(ext >> instr) - { - extensionList.insert(instr); - } - } - - - void* Win32GLSupport::getProcAddress(const char* procname) const - { - void* res = (void*)wglGetProcAddress(procname); - - if (!res) { - static HMODULE libgl = LoadLibraryA("opengl32.dll"); - res = (void*)GetProcAddress(libgl, procname); - } - - return res; - } - void Win32GLSupport::initialiseWGL() - { - // wglGetProcAddress does not work without an active OpenGL context, - // but we need wglChoosePixelFormatARB's address before we can - // create our main window. Thank you very much, Microsoft! - // - // The solution is to create a dummy OpenGL window first, and then - // test for WGL_ARB_pixel_format support. If it is not supported, - // we make sure to never call the ARB pixel format functions. - // - // If is is supported, we call the pixel format functions at least once - // to initialise them (pointers are stored by glprocs.h). We can also - // take this opportunity to enumerate the valid FSAA modes. - - LPCSTR dummyText = "OgreWglDummy"; - - HINSTANCE hinst = NULL; - #ifdef __MINGW32__ - #ifdef OGRE_STATIC_LIB - hinst = GetModuleHandle( NULL ); - #else - #if OGRE_DEBUG_MODE == 1 - hinst = GetModuleHandle("RenderSystem_GL3Plus_d.dll"); - #else - hinst = GetModuleHandle("RenderSystem_GL3Plus.dll"); - #endif - #endif - #else - static const TCHAR staticVar; - GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, &staticVar, &hinst); - #endif - - WNDCLASS dummyClass; - memset(&dummyClass, 0, sizeof(WNDCLASS)); - dummyClass.style = CS_OWNDC; - dummyClass.hInstance = hinst; - dummyClass.lpfnWndProc = dummyWndProc; - dummyClass.lpszClassName = dummyText; - RegisterClass(&dummyClass); - - HWND hwnd = CreateWindow(dummyText, dummyText, - WS_POPUP | WS_CLIPCHILDREN, - 0, 0, 32, 32, 0, 0, hinst, 0); - - // if a simple CreateWindow fails, then boy are we in trouble... - if (hwnd == NULL) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "CreateWindow() failed", "Win32GLSupport::initializeWGL"); - - - // no chance of failure and no need to release thanks to CS_OWNDC - HDC hdc = GetDC(hwnd); - - // assign a simple OpenGL pixel format that everyone supports - PIXELFORMATDESCRIPTOR pfd; - memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); - pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); - pfd.nVersion = 1; - pfd.cColorBits = 16; - pfd.cDepthBits = 15; - pfd.dwFlags = PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER; - pfd.iPixelType = PFD_TYPE_RGBA; - - // if these fail, wglCreateContext will also quietly fail - int format; - if ((format = ChoosePixelFormat(hdc, &pfd)) != 0) - SetPixelFormat(hdc, format, &pfd); - - HGLRC hrc = wglCreateContext(hdc); - if (hrc) - { - HGLRC oldrc = wglGetCurrentContext(); - HDC oldhdc = wglGetCurrentDC(); - // if wglMakeCurrent fails, wglGetProcAddress will return null - wglMakeCurrent(hdc, hrc); - - // the default context is created with maximum version - // use GL3 query type, as it is the only consumer - glGetIntegerv(0x821B, &glMajorMax); - glGetIntegerv(0x821C, &glMinorMax); - - _wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC) - wglGetProcAddress("wglCreateContextAttribsARB"); - - PFNWGLGETEXTENSIONSSTRINGARBPROC _wglGetExtensionsStringARB = - (PFNWGLGETEXTENSIONSSTRINGARBPROC) - wglGetProcAddress("wglGetExtensionsStringARB"); - - // check for pixel format and multisampling support - if (_wglGetExtensionsStringARB) - { - std::istringstream wglexts(_wglGetExtensionsStringARB(hdc)); - std::string ext; - while (wglexts >> ext) - { - if (ext == "WGL_ARB_pixel_format") - mHasPixelFormatARB = true; - else if (ext == "WGL_ARB_multisample") - mHasMultisample = true; - else if (ext == "WGL_EXT_framebuffer_sRGB") - mHasHardwareGamma = true; - } - } - - if (mHasPixelFormatARB && mHasMultisample) - { - // enumerate all formats w/ multisampling - static const int iattr[] = { - WGL_DRAW_TO_WINDOW_ARB, true, - WGL_SUPPORT_OPENGL_ARB, true, - WGL_DOUBLE_BUFFER_ARB, true, - WGL_SAMPLE_BUFFERS_ARB, true, - WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, - /* We are no matter about the colour, depth and stencil buffers here - WGL_COLOR_BITS_ARB, 24, - WGL_ALPHA_BITS_ARB, 8, - WGL_DEPTH_BITS_ARB, 24, - WGL_STENCIL_BITS_ARB, 8, - */ - WGL_SAMPLES_ARB, 2, - 0 - }; - int formats[256] = {0}; - unsigned int count = 0; - // cheating here. wglChoosePixelFormatARB procc address needed later on - // when a valid GL context does not exist and glew is not initialized yet. - PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribiv = (PFNWGLGETPIXELFORMATATTRIBIVARBPROC)wglGetProcAddress("wglGetPixelFormatAttribivARB"); - - mWglChoosePixelFormat = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); - - - if (mWglChoosePixelFormat(hdc, iattr, 0, 256, formats, &count)) - { - // determine what multisampling levels are offered - int query = WGL_SAMPLES_ARB, samples; - for (unsigned int i = 0; i < count; ++i) - { - if (wglGetPixelFormatAttribiv(hdc, formats[i], 0, 1, &query, &samples)) - { - mFSAALevels.push_back(samples); - } - } - mFSAALevels.push_back(0); - } - } - - wglMakeCurrent(oldhdc, oldrc); - wglDeleteContext(hrc); - } - - // clean up our dummy window and class - DestroyWindow(hwnd); - UnregisterClass(dummyText, hinst); - } - - LRESULT Win32GLSupport::dummyWndProc(HWND hwnd, UINT umsg, WPARAM wp, LPARAM lp) - { - return DefWindowProc(hwnd, umsg, wp, lp); - } - - bool Win32GLSupport::selectPixelFormat(HDC hdc, int colourDepth, int multisample, bool hwGamma, bool stereo) - { - PIXELFORMATDESCRIPTOR pfd; - memset(&pfd, 0, sizeof(pfd)); - pfd.nSize = sizeof(pfd); - pfd.nVersion = 1; - pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; - pfd.iPixelType = PFD_TYPE_RGBA; - pfd.cColorBits = (colourDepth > 16)? 24 : colourDepth; - pfd.cAlphaBits = (colourDepth > 16)? 8 : 0; - pfd.cDepthBits = 24; - pfd.cStencilBits = 8; - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - if (stereo) - pfd.dwFlags |= PFD_STEREO; -#endif - - int format = 0; - - int useHwGamma = hwGamma; - - if (multisample && (!mHasMultisample || !mHasPixelFormatARB)) - return false; - - if (hwGamma && !mHasHardwareGamma) - return false; - - if ((multisample || hwGamma) && mWglChoosePixelFormat) - { - - // Use WGL to test extended caps (multisample, sRGB) - std::vector attribList; - attribList.push_back(WGL_DRAW_TO_WINDOW_ARB); attribList.push_back(true); - attribList.push_back(WGL_SUPPORT_OPENGL_ARB); attribList.push_back(true); - attribList.push_back(WGL_DOUBLE_BUFFER_ARB); attribList.push_back(true); - attribList.push_back(WGL_SAMPLE_BUFFERS_ARB); attribList.push_back(true); - attribList.push_back(WGL_ACCELERATION_ARB); attribList.push_back(WGL_FULL_ACCELERATION_ARB); - attribList.push_back(WGL_COLOR_BITS_ARB); attribList.push_back(pfd.cColorBits); - attribList.push_back(WGL_ALPHA_BITS_ARB); attribList.push_back(pfd.cAlphaBits); - attribList.push_back(WGL_DEPTH_BITS_ARB); attribList.push_back(24); - attribList.push_back(WGL_STENCIL_BITS_ARB); attribList.push_back(8); - attribList.push_back(WGL_SAMPLES_ARB); attribList.push_back(multisample); - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - if (stereo) - attribList.push_back(WGL_STEREO_ARB); attribList.push_back(true); -#endif - - if (useHwGamma && mHasHardwareGamma) - { - attribList.push_back(WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT); attribList.push_back(true); - } - // terminator - attribList.push_back(0); - - - UINT nformats; - // ChoosePixelFormatARB proc address was obtained when setting up a dummy GL context in initialiseWGL() - // since glew hasn't been initialized yet, we have to cheat and use the previously obtained address - if (!mWglChoosePixelFormat(hdc, &(attribList[0]), NULL, 1, &format, &nformats) || nformats <= 0) - return false; - } - else - { - format = ChoosePixelFormat(hdc, &pfd); - } - - - return (format && SetPixelFormat(hdc, format, &pfd)); - } - - HGLRC Win32GLSupport::createNewContext(HDC hdc, HGLRC shareList) - { - HGLRC glrc = NULL; - - int profile; - int majorVersion; - int minorVersion = 0; - - switch(mContextProfile) { - case CONTEXT_COMPATIBILITY: - profile = WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; - majorVersion = 1; - break; - case CONTEXT_ES: - profile = WGL_CONTEXT_ES2_PROFILE_BIT_EXT; - majorVersion = 2; - break; - default: - profile = WGL_CONTEXT_CORE_PROFILE_BIT_ARB; - if (glMajorMax > 3) - { - majorVersion = glMajorMax; - minorVersion = glMinorMax; - } - else - { - majorVersion = 3; - minorVersion = 3; // 3.1 would be sufficient per spec, but we need 3.3 anyway.. - } - break; - } - - int context_attribs[] = { - WGL_CONTEXT_MAJOR_VERSION_ARB, majorVersion, - WGL_CONTEXT_MINOR_VERSION_ARB, minorVersion, - WGL_CONTEXT_PROFILE_MASK_ARB, profile, - 0 - }; - - glrc = _wglCreateContextAttribsARB ? _wglCreateContextAttribsARB(hdc, shareList, context_attribs) : wglCreateContext(hdc); - - if (!glrc) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglCreateContext failed: " + translateWGLError()); - - if(!_wglCreateContextAttribsARB && shareList && shareList != glrc) - { - // Share lists with old context - if (!wglShareLists(shareList, glrc)) - { - wglDeleteContext(glrc); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglShareLists() failed: "+ translateWGLError()); - } - } - - return glrc; - } - - String translateWGLError() - { - int winError = GetLastError(); - char* errDesc; - int i; - - errDesc = new char[255]; - // Try windows errors first - i = FormatMessage( - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - winError, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language - (LPTSTR) errDesc, - 255, - NULL - ); - - return String(errDesc); - } - -} diff --git a/RenderSystems/GLSupport/src/win32/OgreWin32RenderTexture.cpp b/RenderSystems/GLSupport/src/win32/OgreWin32RenderTexture.cpp deleted file mode 100644 index eb0bbc78caf..00000000000 --- a/RenderSystems/GLSupport/src/win32/OgreWin32RenderTexture.cpp +++ /dev/null @@ -1,230 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreRoot.h" -#include "OgreLogManager.h" -#include "OgreRenderSystem.h" -#include "OgreImageCodec.h" -#include "OgreException.h" -#include "OgreStringConverter.h" -#include "OgreWin32RenderTexture.h" -#include "OgreWin32GLSupport.h" -#include "OgreWin32Context.h" - -namespace Ogre { - - Win32PBuffer::Win32PBuffer(PixelComponentType format, size_t width, size_t height, Win32GLSupport &glsupport): - GLPBuffer(format, width, height), - mContext(0) - { - createPBuffer(); - - // Create context - mContext = new Win32Context(mHDC, mGlrc, glsupport); -#if 0 - if(mUseBind) - { - // Bind texture - glBindTextureEXT(GL_TEXTURE_2D, static_cast(mTexture.get())->getGLID()); - wglBindTexImageARB(mPBuffer, WGL_FRONT_LEFT_ARB); - } -#endif - } - Win32PBuffer::~Win32PBuffer() - { -#if 0 - if(mUseBind) - { - // Unbind texture - glBindTextureEXT(GL_TEXTURE_2D, - static_cast(mTexture.get())->getGLID()); - glBindTextureEXT(GL_TEXTURE_2D, - static_cast(mTexture.get())->getGLID()); - wglReleaseTexImageARB(mPBuffer, WGL_FRONT_LEFT_ARB); - } -#endif - // Unregister and destroy mContext - delete mContext; - - // Destroy pbuffer - destroyPBuffer(); - } - - void Win32PBuffer::createPBuffer() - { - - // Process format - int bits=0; - bool isFloat=false; -#if 0 - bool hasAlpha=true; -#endif - switch(mFormat) - { - case PCT_BYTE: - bits=8; isFloat=false; - break; - case PCT_SHORT: - bits=16; isFloat=false; - break; - case PCT_FLOAT16: - bits=16; isFloat=true; - break; - case PCT_FLOAT32: - bits=32; isFloat=true; - break; - default: break; - }; - LogManager::getSingleton().logMessage( - " Win32PBuffer::Creating PBuffer of format bits="+ - StringConverter::toString(bits)+ - " float="+StringConverter::toString(isFloat) - ); - - - HDC old_hdc = wglGetCurrentDC(); - HGLRC old_context = wglGetCurrentContext(); - - // Bind to RGB or RGBA texture - int bttype = 0; -#if 0 - if(mUseBind) - { - // Only provide bind type when actually binding - bttype = PixelUtil::hasAlpha(mInternalFormat)? - WGL_BIND_TO_TEXTURE_RGBA_ARB : WGL_BIND_TO_TEXTURE_RGB_ARB; - } - int texformat = hasAlpha? - WGL_TEXTURE_RGBA_ARB : WGL_TEXTURE_RGB_ARB; -#endif - // Make a float buffer? - int pixeltype = isFloat? - WGL_TYPE_RGBA_FLOAT_ARB: WGL_TYPE_RGBA_ARB; - - int attrib[] = { - WGL_RED_BITS_ARB,bits, - WGL_GREEN_BITS_ARB,bits, - WGL_BLUE_BITS_ARB,bits, - WGL_ALPHA_BITS_ARB,bits, - WGL_STENCIL_BITS_ARB,1, - WGL_DEPTH_BITS_ARB,15, - WGL_DRAW_TO_PBUFFER_ARB,true, - WGL_SUPPORT_OPENGL_ARB,true, - WGL_PIXEL_TYPE_ARB,pixeltype, - //WGL_DOUBLE_BUFFER_ARB,true, - //WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB, // Make sure it is accelerated - bttype,true, // must be last, as bttype can be zero - 0 - }; - int pattrib_default[] = { - 0 - }; -#if 0 - int pattrib_bind[] = { - WGL_TEXTURE_FORMAT_ARB, texformat, - WGL_TEXTURE_TARGET_ARB, WGL_TEXTURE_2D_ARB, - WGL_PBUFFER_LARGEST_ARB, true, - 0 - }; -#endif - int format; - unsigned int count; - - PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); - - // Choose suitable pixel format - wglChoosePixelFormatARB(old_hdc,attrib,NULL,1,&format,&count); - if(count == 0) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglChoosePixelFormatARB() failed", " Win32PBuffer::createPBuffer"); - - // Analyse pixel format - const int piAttributes[]={ - WGL_RED_BITS_ARB,WGL_GREEN_BITS_ARB,WGL_BLUE_BITS_ARB,WGL_ALPHA_BITS_ARB, - WGL_DEPTH_BITS_ARB,WGL_STENCIL_BITS_ARB - }; - int piValues[sizeof(piAttributes)/sizeof(const int)]; - - PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribiv = (PFNWGLGETPIXELFORMATATTRIBIVARBPROC)wglGetProcAddress("wglGetPixelFormatAttribivARB"); - wglGetPixelFormatAttribiv(old_hdc,format,0,sizeof(piAttributes)/sizeof(const int),piAttributes,piValues); - - LogManager::getSingleton().stream() - << " Win32PBuffer::PBuffer -- Chosen pixel format rgba=" - << piValues[0] << "," - << piValues[1] << "," - << piValues[2] << "," - << piValues[3] - << " depth=" << piValues[4] - << " stencil=" << piValues[5]; - // FIXME lookup procaddress - mPBuffer = 0;//wglCreatePbufferARB(old_hdc,format,mWidth,mHeight,pattrib_default); - if(!mPBuffer) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglCreatePbufferARB() failed", " Win32PBuffer::createPBuffer"); -#if 0 - mHDC = wglGetPbufferDCARB(mPBuffer); - if(!mHDC) { - wglDestroyPbufferARB(mPBuffer); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglGetPbufferDCARB() failed", " Win32PBuffer::createPBuffer"); - } - - mGlrc = wglCreateContext(mHDC); - if(!mGlrc) { - wglReleasePbufferDCARB(mPBuffer,mHDC); - wglDestroyPbufferARB(mPBuffer); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglCreateContext() failed", " Win32PBuffer::createPBuffer"); - } - - if(!wglShareLists(old_context,mGlrc)) { - wglDeleteContext(mGlrc); - wglReleasePbufferDCARB(mPBuffer,mHDC); - wglDestroyPbufferARB(mPBuffer); - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglShareLists() failed", " Win32PBuffer::createPBuffer"); - } - - // Query real width and height - int iWidth, iHeight; - wglQueryPbufferARB(mPBuffer, WGL_PBUFFER_WIDTH_ARB, &iWidth); - wglQueryPbufferARB(mPBuffer, WGL_PBUFFER_HEIGHT_ARB, &iHeight); - mWidth = iWidth; - mHeight = iHeight; - LogManager::getSingleton().stream() - << "Win32RenderTexture::PBuffer created -- Real dimensions " - << mWidth << "x" << mHeight; -#endif - } - void Win32PBuffer::destroyPBuffer() - { - wglDeleteContext(mGlrc); - // FIXME lookup procaddress -#if 0 - wglReleasePbufferDCARB(mPBuffer,mHDC); - wglDestroyPbufferARB(mPBuffer); -#endif - } - - -} diff --git a/RenderSystems/GLSupport/src/win32/OgreWin32Window.cpp b/RenderSystems/GLSupport/src/win32/OgreWin32Window.cpp deleted file mode 100644 index f543825661d..00000000000 --- a/RenderSystems/GLSupport/src/win32/OgreWin32Window.cpp +++ /dev/null @@ -1,820 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef _WIN32_WINNT -#define _WIN32_WINNT 0x0502 -#endif -#include "OgreWin32Window.h" -#include "OgreRoot.h" -#include "OgreViewport.h" -#include "OgreLogManager.h" -#include "OgreRenderSystem.h" -#include "OgreImageCodec.h" -#include "OgreStringConverter.h" -#include "OgreException.h" -#include "OgreWin32GLSupport.h" -#include "OgreWin32Context.h" - -#include "OgreDepthBuffer.h" - -#include "OgreGLRenderSystemCommon.h" - -namespace Ogre { - - #define _MAX_CLASS_NAME_ 128 - - Win32Window::Win32Window(Win32GLSupport &glsupport): GLWindow(), - mGLSupport(glsupport) - { - mHWnd = 0; - mGlrc = 0; - mOwnsGLContext = true; - mSizing = false; - mDisplayFrequency = 0; - mDeviceName = NULL; - mWindowedWinStyle = 0; - mFullscreenWinStyle = 0; - } - - Win32Window::~Win32Window() - { - destroy(); - } - - void Win32Window::create(const String& name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams) - { - // destroy current window, if any - if (mHWnd) - destroy(); - - HINSTANCE hInst = NULL; - #ifdef __MINGW32__ - #ifdef OGRE_STATIC_LIB - hInst = GetModuleHandle( NULL ); - #else - #if OGRE_DEBUG_MODE == 1 - hInst = GetModuleHandle("GLSupport_d.dll"); - #else - hInst = GetModuleHandle("GLSupport.dll"); - #endif - #endif - #else - static const TCHAR staticVar; - GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, &staticVar, &hInst); - #endif - - mHWnd = 0; - mName = name; - mIsFullScreen = fullScreen; - mClosed = false; - mDisplayFrequency = 0; - mDepthBufferPoolId = DepthBuffer::POOL_DEFAULT; - mColourDepth = mIsFullScreen? 32 : GetDeviceCaps(GetDC(0), BITSPIXEL); - int left = -1; // Defaults to screen center - int top = -1; // Defaults to screen center - WNDPROC windowProc = DefWindowProc; - String title = name; - bool hidden = false; - String border; - bool outerSize = false; - bool hwGamma = false; - bool enableDoubleClick = false; - int monitorIndex = -1; - HMONITOR hMonitor = NULL; - - if(miscParams) - { - // Get variable-length params - NameValuePairList::const_iterator opt; - NameValuePairList::const_iterator end = miscParams->end(); - - if ((opt = miscParams->find("title")) != end) - title = opt->second; - - if ((opt = miscParams->find("left")) != end) - left = StringConverter::parseInt(opt->second); - - if ((opt = miscParams->find("top")) != end) - top = StringConverter::parseInt(opt->second); - - if ((opt = miscParams->find("depthBuffer")) != end) - { - mDepthBufferPoolId = StringConverter::parseBool(opt->second) ? - DepthBuffer::POOL_DEFAULT : DepthBuffer::POOL_NO_DEPTH; - } - - if ((opt = miscParams->find("vsync")) != end) - mVSync = StringConverter::parseBool(opt->second); - - if ((opt = miscParams->find("hidden")) != end) - hidden = StringConverter::parseBool(opt->second); - - if ((opt = miscParams->find("vsyncInterval")) != end) - mVSyncInterval = StringConverter::parseUnsignedInt(opt->second); - - if ((opt = miscParams->find("FSAA")) != end) - mFSAA = StringConverter::parseUnsignedInt(opt->second); - - if ((opt = miscParams->find("FSAAHint")) != end) - mFSAAHint = opt->second; - - if ((opt = miscParams->find("gamma")) != end) - hwGamma = StringConverter::parseBool(opt->second); - -#if OGRE_NO_QUAD_BUFFER_STEREO == 0 - if ((opt = miscParams->find("stereoMode")) != end) - { - mStereoEnabled = StringConverter::parseBool(opt->second); - } -#endif - - - - if ((opt = miscParams->find("parentWindowHandle")) != end || - (opt = miscParams->find("externalWindowHandle")) != end) - { - mHWnd = (HWND)StringConverter::parseSizeT(opt->second); - if (mHWnd) - { - mIsExternal = true; - mIsFullScreen = false; - } - - if ((opt = miscParams->find("externalGLControl")) != end) { - mIsExternalGLControl = StringConverter::parseBool(opt->second); - } - } - - if ((opt = miscParams->find("currentGLContext")) != end ) - { - if( StringConverter::parseBool(opt->second) ) - { - mGlrc = wglGetCurrentContext(); - - if ( mGlrc ) - { - mOwnsGLContext = false; - } - else - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "currentGLContext was specified with no current GL context", "Win32Window::create"); - } - } - } - if ((opt = miscParams->find("externalGLContext")) != end) - { - mGlrc = (HGLRC)StringConverter::parseSizeT(opt->second); - - if( mGlrc ) - { - mOwnsGLContext = false; - } - else - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "parsing the value of 'externalGLContext' failed: " + translateWGLError(), "Win32Window::create"); - } - } - - // window border style - opt = miscParams->find("border"); - if(opt != miscParams->end()) - border = opt->second; - // set outer dimensions? - opt = miscParams->find("outerDimensions"); - if(opt != miscParams->end()) - outerSize = StringConverter::parseBool(opt->second); - - // only available with fullscreen - if ((opt = miscParams->find("displayFrequency")) != end) - mDisplayFrequency = StringConverter::parseUnsignedInt(opt->second); - if ((opt = miscParams->find("colourDepth")) != end) - { - mColourDepth = StringConverter::parseUnsignedInt(opt->second); - if (!mIsFullScreen) - { - // make sure we don't exceed desktop colour depth - if ((int)mColourDepth > GetDeviceCaps(GetDC(0), BITSPIXEL)) - mColourDepth = GetDeviceCaps(GetDC(0), BITSPIXEL); - } - } - - if ((opt = miscParams->find("windowProc")) != end) - windowProc = reinterpret_cast(StringConverter::parseSizeT(opt->second)); - - // monitor index - if ((opt = miscParams->find("monitorIndex")) != end) - monitorIndex = StringConverter::parseInt(opt->second); - - // monitor handle - if ((opt = miscParams->find("monitorHandle")) != end) - hMonitor = (HMONITOR)StringConverter::parseSizeT(opt->second); - - // enable double click messages - if ((opt = miscParams->find("enableDoubleClick")) != end) - enableDoubleClick = StringConverter::parseBool(opt->second); - - } - - if (!mIsExternal) - { - DWORD dwStyleEx = 0; - MONITORINFOEX monitorInfoEx; - RECT rc; - - // If we didn't specified the adapter index, or if it didn't find it - if (hMonitor == NULL) - { - POINT windowAnchorPoint; - - // Fill in anchor point. - windowAnchorPoint.x = left; - windowAnchorPoint.y = top; - - - // Get the nearest monitor to this window. - hMonitor = MonitorFromPoint(windowAnchorPoint, MONITOR_DEFAULTTOPRIMARY); - } - - // Get the target monitor info - memset(&monitorInfoEx, 0, sizeof(MONITORINFOEX)); - monitorInfoEx.cbSize = sizeof(MONITORINFOEX); - GetMonitorInfo(hMonitor, &monitorInfoEx); - - size_t devNameLen = strlen(monitorInfoEx.szDevice); - mDeviceName = new char[devNameLen + 1]; - - strcpy(mDeviceName, monitorInfoEx.szDevice); - - // Update window style flags. - mFullscreenWinStyle = (hidden ? 0 : WS_VISIBLE) | WS_CLIPCHILDREN | WS_POPUP; - mWindowedWinStyle = (hidden ? 0 : WS_VISIBLE) | WS_CLIPCHILDREN; - - if (border == "none") - mWindowedWinStyle |= WS_POPUP; - else if (border == "fixed") - mWindowedWinStyle |= WS_OVERLAPPED | WS_BORDER | WS_CAPTION | - WS_SYSMENU | WS_MINIMIZEBOX; - else - mWindowedWinStyle |= WS_OVERLAPPEDWINDOW; - - // No specified top left -> Center the window in the middle of the monitor - if (left == -1 || top == -1) - { - uint screenw = monitorInfoEx.rcWork.right - monitorInfoEx.rcWork.left; - uint screenh = monitorInfoEx.rcWork.bottom - monitorInfoEx.rcWork.top; - - unsigned int winWidth, winHeight; - adjustWindow(width, height, &winWidth, &winHeight); - - // clamp window dimensions to screen size - int outerw = (winWidth < screenw)? winWidth : screenw; - int outerh = (winHeight < screenh)? winHeight : screenh; - - if (left == -1) - left = monitorInfoEx.rcWork.left + (screenw - outerw) / 2; - else if (monitorIndex != -1) - left += monitorInfoEx.rcWork.left; - - if (top == -1) - top = monitorInfoEx.rcWork.top + (screenh - outerh) / 2; - else if (monitorIndex != -1) - top += monitorInfoEx.rcWork.top; - } - else if (monitorIndex != -1) - { - left += monitorInfoEx.rcWork.left; - top += monitorInfoEx.rcWork.top; - } - - mWidth = width; - mHeight = height; - mTop = top; - mLeft = left; - - if (mIsFullScreen) - { - dwStyleEx |= WS_EX_TOPMOST; - mTop = monitorInfoEx.rcMonitor.top; - mLeft = monitorInfoEx.rcMonitor.left; - } - else - { - int screenw = GetSystemMetrics(SM_CXSCREEN); - int screenh = GetSystemMetrics(SM_CYSCREEN); - - if (!outerSize) - { - // Calculate window dimensions required - // to get the requested client area - SetRect(&rc, 0, 0, mWidth, mHeight); - AdjustWindowRect(&rc, getWindowStyle(fullScreen), false); - mWidth = rc.right - rc.left; - mHeight = rc.bottom - rc.top; - - // Clamp window rect to the nearest display monitor. - if (mLeft < monitorInfoEx.rcWork.left) - mLeft = monitorInfoEx.rcWork.left; - - if (mTop < monitorInfoEx.rcWork.top) - mTop = monitorInfoEx.rcWork.top; - - if ((int)mWidth > monitorInfoEx.rcWork.right - mLeft) - mWidth = monitorInfoEx.rcWork.right - mLeft; - - if ((int)mHeight > monitorInfoEx.rcWork.bottom - mTop) - mHeight = monitorInfoEx.rcWork.bottom - mTop; - } - } - - UINT classStyle = CS_OWNDC; - if (enableDoubleClick) - classStyle |= CS_DBLCLKS; - - // register class and create window - WNDCLASS wc = { classStyle, windowProc, 0, 0, hInst, - LoadIcon(NULL, IDI_APPLICATION), LoadCursor(NULL, IDC_ARROW), - (HBRUSH)GetStockObject(BLACK_BRUSH), NULL, "OgreGLWindow" }; - RegisterClass(&wc); - - if (mIsFullScreen) - { - switchMode(mWidth, mHeight, mDisplayFrequency); - } - - // Pass pointer to self as WM_CREATE parameter - mHWnd = CreateWindowEx(dwStyleEx, "OgreGLWindow", title.c_str(), - getWindowStyle(fullScreen), mLeft, mTop, mWidth, mHeight, 0, 0, hInst, this); - - LogManager::getSingleton().stream() - << "Created Win32Window '" - << mName << "' : " << mWidth << "x" << mHeight - << ", " << mColourDepth << "bpp"; - - } - - HDC old_hdc = wglGetCurrentDC(); - HGLRC old_context = wglGetCurrentContext(); - - RECT rc; - // top and left represent outer window position - GetWindowRect(mHWnd, &rc); - mTop = rc.top; - mLeft = rc.left; - // width and height represent drawable area only - GetClientRect(mHWnd, &rc); - mWidth = rc.right; - mHeight = rc.bottom; - - mHDC = GetDC(mHWnd); - - if (!mIsExternalGLControl) - { - int testFsaa = mFSAA; - bool testHwGamma = hwGamma; - bool formatOk = mGLSupport.selectPixelFormat(mHDC, mColourDepth, testFsaa, testHwGamma, mStereoEnabled); - if (!formatOk) - { - if (mFSAA > 0) - { - // try without FSAA - testFsaa = 0; - formatOk = mGLSupport.selectPixelFormat(mHDC, mColourDepth, testFsaa, testHwGamma, mStereoEnabled); - } - - if (!formatOk && hwGamma) - { - // try without sRGB - testHwGamma = false; - testFsaa = mFSAA; - formatOk = mGLSupport.selectPixelFormat(mHDC, mColourDepth, testFsaa, testHwGamma, mStereoEnabled); - } - - if (!formatOk && hwGamma && (mFSAA > 0)) - { - // try without both - testHwGamma = false; - testFsaa = 0; - formatOk = mGLSupport.selectPixelFormat(mHDC, mColourDepth, testFsaa, testHwGamma, mStereoEnabled); - } - - if (!formatOk) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "selectPixelFormat failed", "Win32Window::create"); - - } - // record what gamma option we used in the end - // this will control enabling of sRGB state flags when used - mHwGamma = testHwGamma; - mFSAA = testFsaa; - } - if (mOwnsGLContext) - { - // New context is shared with previous one - mGlrc = mGLSupport.createNewContext(mHDC, old_context); - } - - if (!wglMakeCurrent(mHDC, mGlrc)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglMakeCurrent", "Win32Window::create"); - - // Do not change vsync if the external window has the OpenGL control - if (!mIsExternalGLControl) { - // Don't use wglew as if this is the first window, we won't have initialised yet - PFNWGLSWAPINTERVALEXTPROC _wglSwapIntervalEXT = - (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT"); - if (_wglSwapIntervalEXT) - _wglSwapIntervalEXT(mVSync? mVSyncInterval : 0); - } - - if (old_context && old_context != mGlrc) - { - // Restore old context - if (!wglMakeCurrent(old_hdc, old_context)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglMakeCurrent() failed", "Win32Window::create"); - } - - // Create RenderSystem context - mContext = new Win32Context(mHDC, mGlrc, mGLSupport); - - mActive = true; - setHidden(hidden); - } - - void Win32Window::adjustWindow(unsigned int clientWidth, unsigned int clientHeight, - unsigned int* winWidth, unsigned int* winHeight) - { - // NB only call this for non full screen - RECT rc; - SetRect(&rc, 0, 0, clientWidth, clientHeight); - AdjustWindowRect(&rc, getWindowStyle(mIsFullScreen), false); - *winWidth = rc.right - rc.left; - *winHeight = rc.bottom - rc.top; - - // adjust to monitor - HMONITOR hMonitor = MonitorFromWindow(mHWnd, MONITOR_DEFAULTTONEAREST); - - // Get monitor info - MONITORINFO monitorInfo; - - memset(&monitorInfo, 0, sizeof(MONITORINFO)); - monitorInfo.cbSize = sizeof(MONITORINFO); - GetMonitorInfo(hMonitor, &monitorInfo); - - LONG maxW = monitorInfo.rcWork.right - monitorInfo.rcWork.left; - LONG maxH = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top; - - if (*winWidth > (unsigned int)maxW) - *winWidth = maxW; - if (*winHeight > (unsigned int)maxH) - *winHeight = maxH; - - } - - void Win32Window::switchMode(uint width, uint height, uint frequency) - { - DEVMODE displayDeviceMode = {}; - - displayDeviceMode.dmSize = sizeof(DEVMODE); - displayDeviceMode.dmBitsPerPel = mColourDepth; - displayDeviceMode.dmPelsWidth = width; - displayDeviceMode.dmPelsHeight = height; - displayDeviceMode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; - - if (frequency) - { - displayDeviceMode.dmDisplayFrequency = frequency; - displayDeviceMode.dmFields |= DM_DISPLAYFREQUENCY; - if (ChangeDisplaySettingsEx(mDeviceName, &displayDeviceMode, NULL, CDS_FULLSCREEN | CDS_TEST, NULL) != DISP_CHANGE_SUCCESSFUL) - { - LogManager::getSingleton().logWarning("ChangeDisplaySettings with user display frequency failed"); - displayDeviceMode.dmFields ^= DM_DISPLAYFREQUENCY; - } - } - if (ChangeDisplaySettingsEx(mDeviceName, &displayDeviceMode, NULL, CDS_FULLSCREEN, NULL) != DISP_CHANGE_SUCCESSFUL) - LogManager::getSingleton().logError("ChangeDisplaySettings failed"); - } - - void Win32Window::setFullscreen(bool fullScreen, unsigned int width, unsigned int height) - { - if(mIsExternal) - return; - - if (mIsFullScreen != fullScreen || width != mWidth || height != mHeight) - { - mIsFullScreen = fullScreen; - - if (mIsFullScreen) - { - switchMode(width, height, mDisplayFrequency); - - // Get the nearest monitor to this window. - HMONITOR hMonitor = MonitorFromWindow(mHWnd, MONITOR_DEFAULTTONEAREST); - - // Get monitor info - MONITORINFO monitorInfo; - - memset(&monitorInfo, 0, sizeof(MONITORINFO)); - monitorInfo.cbSize = sizeof(MONITORINFO); - GetMonitorInfo(hMonitor, &monitorInfo); - - mTop = monitorInfo.rcMonitor.top; - mLeft = monitorInfo.rcMonitor.left; - - SetWindowLong(mHWnd, GWL_STYLE, getWindowStyle(mIsFullScreen)); - SetWindowPos(mHWnd, HWND_TOPMOST, mLeft, mTop, width, height, - SWP_NOACTIVATE); - mWidth = width; - mHeight = height; - - - } - else - { - // drop out of fullscreen - ChangeDisplaySettingsEx(mDeviceName, NULL, NULL, 0, NULL); - - // calculate overall dimensions for requested client area - unsigned int winWidth, winHeight; - adjustWindow(width, height, &winWidth, &winHeight); - - // deal with centering when switching down to smaller resolution - - HMONITOR hMonitor = MonitorFromWindow(mHWnd, MONITOR_DEFAULTTONEAREST); - MONITORINFO monitorInfo; - memset(&monitorInfo, 0, sizeof(MONITORINFO)); - monitorInfo.cbSize = sizeof(MONITORINFO); - GetMonitorInfo(hMonitor, &monitorInfo); - - uint screenw = monitorInfo.rcWork.right - monitorInfo.rcWork.left; - uint screenh = monitorInfo.rcWork.bottom - monitorInfo.rcWork.top; - - - int left = screenw > winWidth ? ((screenw - winWidth) / 2) : 0; - int top = screenh > winHeight ? ((screenh - winHeight) / 2) : 0; - - SetWindowLong(mHWnd, GWL_STYLE, getWindowStyle(mIsFullScreen)); - SetWindowPos(mHWnd, HWND_NOTOPMOST, left, top, winWidth, winHeight, - SWP_DRAWFRAME | SWP_FRAMECHANGED | SWP_NOACTIVATE); - mWidth = width; - mHeight = height; - - windowMovedOrResized(); - - } - - } - } - - void Win32Window::destroy(void) - { - if (!mHWnd) - return; - - // Unregister and destroy OGRE GLContext - delete mContext; - mContext = 0; - - if (mOwnsGLContext) - { - wglDeleteContext(mGlrc); - mGlrc = 0; - } - if (!mIsExternal) - { - if (mIsFullScreen) - ChangeDisplaySettingsEx(mDeviceName, NULL, NULL, 0, NULL); - DestroyWindow(mHWnd); - } - else - { - // just release the DC - ReleaseDC(mHWnd, mHDC); - } - - mActive = false; - mClosed = true; - mHDC = 0; // no release thanks to CS_OWNDC wndclass style - mHWnd = 0; - - if (mDeviceName != NULL) - { - delete[] mDeviceName; - mDeviceName = NULL; - } - - } - - - bool Win32Window::isActive(void) const - { - if (isFullScreen()) - return isVisible(); - - return mActive && isVisible(); - } - - bool Win32Window::isVisible() const - { - return (mHWnd && !IsIconic(mHWnd)); - } - - void Win32Window::setHidden(bool hidden) - { - mHidden = hidden; - if (!mIsExternal) - { - if (hidden) - ShowWindow(mHWnd, SW_HIDE); - else - ShowWindow(mHWnd, SW_SHOWNORMAL); - } - } - - void Win32Window::setVSyncEnabled(bool vsync) - { - mVSync = vsync; - HDC old_hdc = wglGetCurrentDC(); - HGLRC old_context = wglGetCurrentContext(); - if (!wglMakeCurrent(mHDC, mGlrc)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglMakeCurrent", "Win32Window::setVSyncEnabled"); - - // Do not change vsync if the external window has the OpenGL control - if (!mIsExternalGLControl) { - // Don't use wglew as if this is the first window, we won't have initialised yet - PFNWGLSWAPINTERVALEXTPROC _wglSwapIntervalEXT = - (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT"); - if (_wglSwapIntervalEXT) - _wglSwapIntervalEXT(mVSync? mVSyncInterval : 0); - } - - if (old_context && old_context != mGlrc) - { - // Restore old context - if (!wglMakeCurrent(old_hdc, old_context)) - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglMakeCurrent() failed", "Win32Window::setVSyncEnabled"); - } - } - - void Win32Window::reposition(int left, int top) - { - if (mHWnd && !mIsFullScreen) - { - SetWindowPos(mHWnd, 0, left, top, 0, 0, - SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); - } - } - - void Win32Window::resize(unsigned int width, unsigned int height) - { - if (!isVisible()) - return; - - if (!mIsExternal && !mIsFullScreen && width > 0 && height > 0) - { - RECT rc = { 0, 0, int(width), int(height) }; - AdjustWindowRect(&rc, getWindowStyle(mIsFullScreen), false); - width = rc.right - rc.left; - height = rc.bottom - rc.top; - SetWindowPos(mHWnd, 0, 0, 0, width, height, - SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE); - return; - } - - updateWindowRect(); - } - - void Win32Window::windowMovedOrResized() - { - if (!isVisible()) - return; - - updateWindowRect(); - } - - - void Win32Window::updateWindowRect() - { - RECT rc; - BOOL result; - - // Update top left parameters - result = GetWindowRect(mHWnd, &rc); - if (result == FALSE) - { - mTop = 0; - mLeft = 0; - mWidth = 0; - mHeight = 0; - return; - } - - mTop = rc.top; - mLeft = rc.left; - - // width and height represent drawable area only - result = GetClientRect(mHWnd, &rc); - if (result == FALSE) - { - mTop = 0; - mLeft = 0; - mWidth = 0; - mHeight = 0; - return; - } - unsigned int width = rc.right - rc.left; - unsigned int height = rc.bottom - rc.top; - - // Case window resized. - if (width != mWidth || height != mHeight) - { - mWidth = rc.right - rc.left; - mHeight = rc.bottom - rc.top; - - // Notify viewports of resize - ViewportList::iterator it = mViewportList.begin(); - while( it != mViewportList.end() ) - (*it++).second->_updateDimensions(); - } - } - - - void Win32Window::swapBuffers() - { - if (!mIsExternalGLControl) { - SwapBuffers(mHDC); - } - } - - void Win32Window::getCustomAttribute( const String& name, void* pData ) - { - if( name == "GLCONTEXT" ) { - *static_cast(pData) = mContext; - return; - } else if( name == "WINDOW" ) - { - HWND *pHwnd = (HWND*)pData; - *pHwnd = getWindowHandle(); - return; - } - } - - void Win32Window::setActive( bool state ) - { - if (mDeviceName != NULL && state == false) - { - HWND hActiveWindow = GetActiveWindow(); - char classNameSrc[_MAX_CLASS_NAME_ + 1]; - char classNameDst[_MAX_CLASS_NAME_ + 1]; - - GetClassName(mHWnd, classNameSrc, _MAX_CLASS_NAME_); - GetClassName(hActiveWindow, classNameDst, _MAX_CLASS_NAME_); - - if (strcmp(classNameDst, classNameSrc) == 0) - { - state = true; - } - } - - mActive = state; - - if( mIsFullScreen ) - { - if( state == false ) - { //Restore Desktop - ChangeDisplaySettingsEx(mDeviceName, NULL, NULL, 0, NULL); - ShowWindow(mHWnd, SW_SHOWMINNOACTIVE); - } - else - { - switchMode(mWidth, mHeight, mDisplayFrequency); - } - } - } -} diff --git a/RenderSystems/Metal/CMakeLists.txt b/RenderSystems/Metal/CMakeLists.txt deleted file mode 100644 index c595f6579ee..00000000000 --- a/RenderSystems/Metal/CMakeLists.txt +++ /dev/null @@ -1,47 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure Metal RenderSystem build - -if (APPLE_IOS) -set(OS "iOS") -else() -set(OS "OSX") -endif() - -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h" "${CMAKE_CURRENT_SOURCE_DIR}/include/Windowing/${OS}/*.h") -file(GLOB SOURCE_FILES - "${CMAKE_CURRENT_SOURCE_DIR}/src/*.mm" - "${CMAKE_CURRENT_SOURCE_DIR}/src/Windowing/${OS}/*.mm") - -include_directories( - BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/include/Windowing/${OS} -) - -add_definitions(${OGRE_VISIBILITY_FLAGS}) -add_library(RenderSystem_Metal ${OGRE_LIB_TYPE} ${HEADER_FILES} ${SOURCE_FILES}) -if (APPLE_IOS) -target_link_libraries(RenderSystem_Metal OgreMain "-framework Metal" "-framework QuartzCore") -else() -target_link_libraries(RenderSystem_Metal OgreMain "-framework Metal" "-framework AppKit" "-framework QuartzCore") -endif() - -target_compile_options(RenderSystem_Metal PRIVATE "-fobjc-arc") -set_target_properties(RenderSystem_Metal PROPERTIES LINK_FLAGS "-fobjc-arc") - -if (OGRE_CONFIG_THREADS) - target_link_libraries(RenderSystem_Metal ${OGRE_THREAD_LIBRARIES}) -endif () - -ogre_config_framework(RenderSystem_Metal) - -ogre_config_plugin(RenderSystem_Metal) -install(FILES ${HEADER_FILES} DESTINATION include/OGRE/RenderSystems/Metal) -install(FILES ${PLATFORM_HEADERS} DESTINATION include/OGRE/RenderSystems/Metal/${PLATFORM_HEADER_INSTALL}) -install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include DESTINATION include/OGRE/RenderSystems/Metal) diff --git a/RenderSystems/Metal/include/OgreMetalDepthBuffer.h b/RenderSystems/Metal/include/OgreMetalDepthBuffer.h deleted file mode 100644 index 0586fa851fc..00000000000 --- a/RenderSystems/Metal/include/OgreMetalDepthBuffer.h +++ /dev/null @@ -1,66 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2016 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _OgreMetalDepthBuffer_H_ -#define _OgreMetalDepthBuffer_H_ - -#include "OgreMetalPrerequisites.h" -#include "OgreDepthBuffer.h" -#include - -namespace Ogre -{ - class _OgreMetalExport MetalDepthBuffer : public DepthBuffer - { - public: - MTLRenderPassDepthAttachmentDescriptor *mDepthAttachmentDesc; - MTLRenderPassStencilAttachmentDescriptor *mStencilAttachmentDesc; - - protected: - MetalDevice *mDevice; - MTLPixelFormat mFormat; - - public: - MetalDepthBuffer( uint16 poolId, MetalRenderSystem *renderSystem, - uint32 width, uint32 height, uint32 fsaa, - MTLPixelFormat pixelFormat, bool _isManual, - id depthTexture, id stencilTexture, - MetalDevice *device ); - virtual ~MetalDepthBuffer(); - - /// @copydoc DepthBuffer::isCompatible - virtual bool isCompatible( RenderTarget *renderTarget) const; - - MetalDevice* getOwnerDevice(void) const { return mDevice; } - - MTLPixelFormat getFormat() const { return mFormat; } - - protected: - virtual bool copyToImpl( DepthBuffer *destination ); - }; -} -#endif diff --git a/RenderSystems/Metal/include/OgreMetalDevice.h b/RenderSystems/Metal/include/OgreMetalDevice.h deleted file mode 100644 index 447a1ddc754..00000000000 --- a/RenderSystems/Metal/include/OgreMetalDevice.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2016 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#ifndef _OgreMetalDevice_H_ -#define _OgreMetalDevice_H_ - -#include "OgreMetalPrerequisites.h" - -#import - -namespace Ogre -{ - struct _OgreMetalExport MetalDevice - { - /// Once a frame is aborted, MTLRenderCommandEncoder are no longer created (ignored). - bool mFrameAborted; - id mDevice; - id mMainCommandQueue; - id mCurrentCommandBuffer; - id mBlitEncoder; - idmComputeEncoder; - id mRenderEncoder; - MetalRenderSystem *mRenderSystem; - dispatch_semaphore_t mStallSemaphore; - - MetalDevice( MetalRenderSystem *renderSystem ); - ~MetalDevice(); - - void init(void); - - void endBlitEncoder(void); - void endRenderEncoder(void); - void endComputeEncoder(void); - - void endAllEncoders(void); - - //Ends all encoders, calls commit and grabs a new mMainCommandBuffer - void commitAndNextCommandBuffer(void); - - /** Gets current blit encoder. If none is current, ends all other - encoders and creates a new blit encoder. - - Use __unsafe_unretained to avoid unnecessary ARC overhead; unless - you really need to hold on to the returned variable. - i.e. - __unsafe_unretained id blitEncoder = mDevice->getBlitEncoder(); - */ - id getBlitEncoder(void); - - /// See getBlitEncoder. - id getComputeEncoder(void); - - /// Waits for the GPU to finish all pending commands. - void stall(void); - }; -} - -#endif diff --git a/RenderSystems/Metal/include/OgreMetalHardwareBufferCommon.h b/RenderSystems/Metal/include/OgreMetalHardwareBufferCommon.h deleted file mode 100644 index dc5e04317e7..00000000000 --- a/RenderSystems/Metal/include/OgreMetalHardwareBufferCommon.h +++ /dev/null @@ -1,82 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef _OgreMetalHardwareBufferCommon_H_ -#define _OgreMetalHardwareBufferCommon_H_ - -#include "OgreMetalPrerequisites.h" -#include "OgreHardwareBuffer.h" - -namespace Ogre -{ - /// Common buffer operations for most v1 buffer interfaces used in Metal - /// This implementation treats: - /// Ignores STATIC and DYNAMIC bit in buffers - /// Lack of WRITE_ONLY and DISCARDABLE buffer puts it in slowest path. - /// Puts WRITE_ONLY in device memory and uses staging buffers to avoid blocking. - /// Use WRITE_ONLY when possible. - class _OgreMetalExport MetalHardwareBufferCommon : public HardwareBuffer - { - private: - id mBuffer; - MetalDevice *mDevice; - public: - MetalHardwareBufferCommon(size_t sizeBytes, Usage usage, bool useShadowBuffer, uint16 alignment, - MetalDevice* device); - virtual ~MetalHardwareBufferCommon(); - - void _notifyDeviceStalled() {} - - /** Returns the actual API buffer, but first sets mLastFrameUsed as we - assume you're calling this function to use the buffer in the GPU. - @param outOffset - Out. Guaranteed to be written. Used by HBU_DISCARDABLE buffers which - need an offset to the internal ring buffer we've allocated. - @return - The MTLBuffer in question. - */ - id getBufferName( size_t &outOffset ); - - void* lockImpl(size_t offset, size_t length, LockOptions options) override; - void unlockImpl() override; - - void readData( size_t offset, size_t length, void* pDest ) override; - - void writeData( size_t offset, size_t length, - const void* pSource, bool discardWholeBuffer = false ) override; - - void writeDataImpl(size_t offset, size_t length, const void* pSource, bool discardWholeBuffer); - - void copyData( HardwareBuffer& srcBuffer, size_t srcOffset, - size_t dstOffset, size_t length, bool discardWholeBuffer = false ) override; - - void _updateFromShadow(void) override; - }; -} - -#endif diff --git a/RenderSystems/Metal/include/OgreMetalHardwareBufferManager.h b/RenderSystems/Metal/include/OgreMetalHardwareBufferManager.h deleted file mode 100644 index 420f6e5deff..00000000000 --- a/RenderSystems/Metal/include/OgreMetalHardwareBufferManager.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#ifndef _OgreMetalHardwareBufferManager_H_ -#define _OgreMetalHardwareBufferManager_H_ - -#include "OgreMetalPrerequisites.h" -#include "OgreHardwareBufferManager.h" - -namespace Ogre { - /// Implementation of HardwareBufferManager for Metal. - class _OgreMetalExport MetalHardwareBufferManager : public HardwareBufferManager - { - protected: - MetalDevice *mDevice; - OGRE_MUTEX(mIndexBuffersMutex); - IndexBufferList mIndexBuffers; - public: - MetalHardwareBufferManager( MetalDevice *device); - virtual ~MetalHardwareBufferManager(); - - void _notifyDeviceStalled(void); - - /// Creates a vertex buffer - virtual HardwareVertexBufferSharedPtr createVertexBuffer( size_t vertexSize, size_t numVerts, - HardwareBuffer::Usage usage, - bool useShadowBuffer = false ); - /// Create an index buffer - virtual HardwareIndexBufferSharedPtr createIndexBuffer( - HardwareIndexBuffer::IndexType itype, size_t numIndexes, - HardwareBuffer::Usage usage, bool useShadowBuffer = false ); - }; -} - -#endif diff --git a/RenderSystems/Metal/include/OgreMetalHardwarePixelBuffer.h b/RenderSystems/Metal/include/OgreMetalHardwarePixelBuffer.h deleted file mode 100644 index 33527faf0c4..00000000000 --- a/RenderSystems/Metal/include/OgreMetalHardwarePixelBuffer.h +++ /dev/null @@ -1,131 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2016 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef _OgreMetalHardwarePixelBuffer_H_ -#define _OgreMetalHardwarePixelBuffer_H_ - -#include "OgreMetalPrerequisites.h" -#include "OgreHardwarePixelBuffer.h" - -#import - -namespace Ogre { - class _OgreMetalExport MetalHardwarePixelBuffer : public HardwarePixelBuffer - { - protected: - /// Lock a box - PixelBox lockImpl(const Box &lockBox, LockOptions options); - - /// Unlock a box - void unlockImpl(void); - - // Internal buffer; either on-card or in system memory, freed/allocated on demand - // depending on buffer usage - PixelBox mBuffer; - - bool mHwGamma; - - // Buffer allocation/freeage - void allocateBuffer(); - - void freeBuffer(); - - // Upload a box of pixels to this buffer on the card - virtual void upload(const PixelBox &data, const Box &dest); - - // Download a box of pixels from the card - virtual void download(const PixelBox &data); - - public: - /// Should be called by HardwareBufferManager - MetalHardwarePixelBuffer( uint32 width, uint32 height, uint32 depth, - PixelFormat format, bool hwGamma, - HardwareBuffer::Usage usage ); - - /// @copydoc HardwarePixelBuffer::blitFromMemory - void blitFromMemory(const PixelBox &src, const Box &dstBox); - - /// @copydoc HardwarePixelBuffer::blitToMemory - void blitToMemory(const Box &srcBox, const PixelBox &dst); - - virtual ~MetalHardwarePixelBuffer(); - - /** Bind surface to frame buffer. Needs FBO extension. - */ - virtual void bindToFramebuffer(uint32 attachment, size_t zoffset); - }; - - /// Texture surface. - class _OgreMetalExport MetalTextureBuffer : public MetalHardwarePixelBuffer - { - public: - /** Texture constructor */ - MetalTextureBuffer( __unsafe_unretained id renderTexture, - __unsafe_unretained id resolveTexture, - MetalDevice *device, - const String &baseName, MTLTextureType target, - int width, int height, int depth, PixelFormat format, - int face, int level, Usage usage, - bool writeGamma, uint fsaa ); - virtual ~MetalTextureBuffer(); - - virtual void bindToFramebuffer(uint32 attachment, size_t zoffset); - - /// Upload a box of pixels to this buffer on the card - virtual void upload(const PixelBox &data, const Box &dest); - - /// Download a box of pixels from the card - virtual void download(const PixelBox &data); - - /// Hardware implementation of blitFromMemory - virtual void blitFromMemory(const PixelBox &src_orig, const Box &dstBox); - - /// Lock a box -// PixelBox lockImpl(const Box &lockBox, LockOptions options) { return PixelBox(); } - - // Copy from framebuffer - void copyFromFramebuffer(size_t zoffset); - - /// @copydoc HardwarePixelBuffer::blit - void blit( const HardwarePixelBufferSharedPtr &src, - const Box &srcBox, const Box &dstBox ); - // Blitting implementation - void blitFromTexture( MetalTextureBuffer *src, const Box &srcBox, - const Box &dstBox ); - - protected: - __unsafe_unretained id mTexture; - // In case this is a texture level - MTLTextureType mTarget; - uint32 mBufferId; - int mFace; - int mLevel; - }; -} - -#endif diff --git a/RenderSystems/Metal/include/OgreMetalMappings.h b/RenderSystems/Metal/include/OgreMetalMappings.h deleted file mode 100644 index c96c3ad2f3e..00000000000 --- a/RenderSystems/Metal/include/OgreMetalMappings.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2016 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#ifndef _OgreMetalMappings_H_ -#define _OgreMetalMappings_H_ - -#include "OgreMetalPrerequisites.h" - -#include "OgrePixelFormat.h" -#include "OgreBlendMode.h" -#include "OgreGpuProgramParams.h" -#include "OgreRenderSystem.h" - -#import -#import -#import -#import -#import - -namespace Ogre -{ - class _OgreMetalExport MetalMappings - { - public: - static MTLPixelFormat getPixelFormat( PixelFormat pf, bool isGamma ); - /// Can throw if PixelFormat is not depth. - static void getDepthStencilFormat( MetalDevice *device, PixelFormat pf, - MTLPixelFormat &outDepth, MTLPixelFormat &outStencil ); - static MTLBlendFactor get( SceneBlendFactor op ); - static MTLBlendOperation get( SceneBlendOperation op ); - - static MTLStencilOperation get( StencilOperation op ); - - static MTLCompareFunction get( CompareFunction cmp ); - - static MTLVertexFormat get( VertexElementType vertexElemType ); - - static MTLSamplerMinMagFilter get( FilterOptions filter ); - static MTLSamplerMipFilter getMipFilter( FilterOptions filter ); - static MTLSamplerAddressMode get( TextureAddressingMode mode ); - - static MTLVertexFormat dataTypeToVertexFormat( MTLDataType dataType ); - - static GpuConstantType get( MTLDataType dataType ); - }; -} - -#endif diff --git a/RenderSystems/Metal/include/OgreMetalMultiRenderTarget.h b/RenderSystems/Metal/include/OgreMetalMultiRenderTarget.h deleted file mode 100644 index a3cd746ce14..00000000000 --- a/RenderSystems/Metal/include/OgreMetalMultiRenderTarget.h +++ /dev/null @@ -1,57 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2017 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _OgreMetalMultiRenderTarget_H_ -#define _OgreMetalMultiRenderTarget_H_ - -#include "OgreMetalPrerequisites.h" -#include "OgreRenderTexture.h" - -#include "OgreMetalRenderTargetCommon.h" - -namespace Ogre -{ - class _OgreMetalExport MetalMultiRenderTarget : public MultiRenderTarget - { - MetalRenderTargetCommon *mMetalRenderTargetCommon[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; - uint8 mNumMRTs; - - public: - MetalMultiRenderTarget( const String &name ); - virtual ~MetalMultiRenderTarget(); - - // MultiRenderTarget overloads. - virtual void bindSurfaceImpl( size_t attachment, RenderTexture *target ); - virtual void unbindSurfaceImpl( size_t attachment ); - - // RenderTarget overloads. - virtual bool requiresTextureFlipping() const { return false; } - virtual void getCustomAttribute( const String& name, void *pData ); - }; -} - -#endif diff --git a/RenderSystems/Metal/include/OgreMetalPlugin.h b/RenderSystems/Metal/include/OgreMetalPlugin.h deleted file mode 100644 index f59509b77be..00000000000 --- a/RenderSystems/Metal/include/OgreMetalPlugin.h +++ /dev/null @@ -1,63 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2016 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _OgreMetalPlugin_H_ -#define _OgreMetalPlugin_H_ - -#include "OgrePlugin.h" - -namespace Ogre -{ - class MetalRenderSystem; - - /** Plugin instance for Metal Manager */ - class MetalPlugin : public Plugin - { - public: - MetalPlugin(); - - - /// @copydoc Plugin::getName - const String& getName() const; - - /// @copydoc Plugin::install - void install(); - - /// @copydoc Plugin::initialise - void initialise(); - - /// @copydoc Plugin::shutdown - void shutdown(); - - /// @copydoc Plugin::uninstall - void uninstall(); - protected: - MetalRenderSystem* mRenderSystem; - }; -} - -#endif diff --git a/RenderSystems/Metal/include/OgreMetalPrerequisites.h b/RenderSystems/Metal/include/OgreMetalPrerequisites.h deleted file mode 100644 index ad4342c8b19..00000000000 --- a/RenderSystems/Metal/include/OgreMetalPrerequisites.h +++ /dev/null @@ -1,95 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2016 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _OgreMetalPrerequisites_H_ -#define _OgreMetalPrerequisites_H_ - -#include "OgrePrerequisites.h" -#include "OgreLogManager.h" - -#include "OgreHardwareVertexBuffer.h" -#include "OgreRenderOperation.h" -#include "OgrePixelFormat.h" - -#ifdef __OBJC__ - @protocol MTLBlitCommandEncoder; - @protocol MTLBuffer; - @protocol MTLCommandBuffer; - @protocol MTLCommandQueue; - @protocol MTLComputeCommandEncoder; - @protocol MTLComputePipelineState; - @protocol MTLDepthStencilState; - @protocol MTLDevice; - @protocol MTLRenderCommandEncoder; - @protocol MTLTexture; - - @class MTLRenderPassColorAttachmentDescriptor; - @class MTLRenderPassDepthAttachmentDescriptor; - @class MTLRenderPassStencilAttachmentDescriptor; -#endif - -#define RESTRICT_ALIAS __restrict__ -#define RESTRICT_ALIAS_RETURN - -namespace Ogre -{ - // Forward declarations - class MetalDepthBuffer; - struct MetalDevice; - class MetalProgram; - class MetalProgramFactory; - class MetalRenderSystem; - class MetalRenderTargetCommon; - - // forward compatibility defines - class MetalHardwareBufferCommon; - - /// Aligns the input 'offset' to the next multiple of 'alignment'. - /// Alignment can be any value except 0. Some examples: - /// - /// alignToNextMultiple( 0, 4 ) = 0; - /// alignToNextMultiple( 1, 4 ) = 4; - /// alignToNextMultiple( 2, 4 ) = 4; - /// alignToNextMultiple( 3, 4 ) = 4; - /// alignToNextMultiple( 4, 4 ) = 4; - /// alignToNextMultiple( 5, 4 ) = 8; - /// - /// alignToNextMultiple( 0, 3 ) = 0; - /// alignToNextMultiple( 1, 3 ) = 3; - inline size_t alignToNextMultiple( size_t offset, size_t alignment ) - { - return ( (offset + alignment - 1u) / alignment ) * alignment; - } -} - -#if defined ( OGRE_GCC_VISIBILITY ) -# define _OgreMetalExport __attribute__ ((visibility("default"))) -#else -# define _OgreMetalExport -#endif - -#endif //#ifndef _OgreMetalPrerequisites_H_ diff --git a/RenderSystems/Metal/include/OgreMetalProgram.h b/RenderSystems/Metal/include/OgreMetalProgram.h deleted file mode 100644 index e53450a528a..00000000000 --- a/RenderSystems/Metal/include/OgreMetalProgram.h +++ /dev/null @@ -1,136 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2016 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _OgreMetalProgram_H_ -#define _OgreMetalProgram_H_ - -#include "OgreMetalPrerequisites.h" -#include "OgreHighLevelGpuProgram.h" -#include "OgreHardwareVertexBuffer.h" -#import -#import -#import - -@class MTLArgument; - -namespace Ogre -{ - /** Specialisation of HighLevelGpuProgram to provide support for Metal - Shader Language. - - Metal has no target assembler or entry point specification like DirectX 9 HLSL. - Vertex and Fragment shaders only have one entry point called "main". - When a shader is compiled, microcode is generated but can not be accessed by - the application. - Metal also does not provide assembler low level output after compiling. The Metal Render - system assumes that the Gpu program is a Metal Gpu program so MetalProgram will create a - MetalGpuProgram that is subclassed from MetalGpuProgram for the low level implementation. - The MetalProgram class will create a shader object and compile the source but will - not create a program object. It's up to MetalGpuProgram class to request a program object - to link the shader object to. - */ - class _OgreMetalExport MetalProgram : public HighLevelGpuProgram - { - public: - /// Command object for setting vertex shader pair - class CmdShaderReflectionPairHint : public ParamCommand - { - public: - String doGet(const void* target) const; - void doSet(void* target, const String& val); - }; - - MetalProgram( ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - MetalDevice *device ); - virtual ~MetalProgram(); - - /** Sets the entry point for this program ie the first method called. */ - void setEntryPoint(const String& entryPoint) { mEntryPoint = entryPoint; } - /** Gets the entry point defined for this program. */ - const String& getEntryPoint(void) const { return mEntryPoint; } - - /// If this shader is a pixel shader, sets a vertex shader that can be paired with us - /// for properly getting reflection data for GPU program parameters. - void setShaderReflectionPairHint(const String& shaderName) - { mShaderReflectionPairHint = shaderName; } - /// Gets the paired shader. See setShaderReflectionPairHint. - const String& getShaderReflectionPairHint(void) const { return mShaderReflectionPairHint; } - - /// Overridden from GpuProgram - const String& getLanguage(void) const; - /// Overridden from GpuProgram - GpuProgramParametersSharedPtr createParameters(void); - - /// Retrieve the Metal function object - id getMetalFunction(void) const { return mFunction; } - - /// Compile source into shader object - bool compile(const bool checkErrors = false); - void analyzeComputeParameters(void); - void analyzeRenderParameters(void); - static void autoFillDummyVertexAttributesForShader( id inVertexFunction, - MTLRenderPipelineDescriptor *outPsd ); - void analyzeParameterBuffer( MTLArgument *arg ); - - static uint32 getAttributeIndex(VertexElementSemantic semantic); - - // first 15 slots are reserved for the vertex attribute buffers - constexpr static int UNIFORM_INDEX_START = 16; - protected: - static CmdShaderReflectionPairHint msCmdShaderReflectionPairHint; - - /** Internal load implementation, must be implemented by subclasses. - */ - void loadFromSource(void); - /// noop - void createLowLevelImpl(void) {} - /// shortcut as we there is no low-level separation here - GpuProgram* _getBindingDelegate(void) { return this; } - /// Internal unload implementation, must be implemented by subclasses - void unloadHighLevelImpl(void); - - /// Populate the passed parameters with name->index map, must be overridden - void buildConstantDefinitions(void) override; - - void parsePreprocessorDefinitions( NSMutableDictionary *inOutMacros ); - - private: - id mLibrary; - id mFunction; - - MetalDevice *mDevice; - - /// Flag indicating if shader object successfully compiled - bool mCompiled; - /// Preprocessor options - String mTargetBufferName; - String mShaderReflectionPairHint; - }; -} - -#endif // __MetalProgram_H__ diff --git a/RenderSystems/Metal/include/OgreMetalProgramFactory.h b/RenderSystems/Metal/include/OgreMetalProgramFactory.h deleted file mode 100644 index 6c41732e434..00000000000 --- a/RenderSystems/Metal/include/OgreMetalProgramFactory.h +++ /dev/null @@ -1,59 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2016 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - - -#ifndef _OgreMetalProgramFactory_H_ -#define _OgreMetalProgramFactory_H_ - -#import "OgreMetalPrerequisites.h" -#import "OgreHighLevelGpuProgramManager.h" - -@protocol MTLFunction; - -namespace Ogre -{ - /** Factory class for Metal programs. */ - class _OgreMetalExport MetalProgramFactory : public HighLevelGpuProgramFactory - { - protected: - static String sLanguageName; - MetalDevice *mDevice; - - public: - MetalProgramFactory( MetalDevice *device ); - virtual ~MetalProgramFactory(void); - /// Get the name of the language this factory creates programs for - const String& getLanguage(void) const; - /// Create an instance of MetalProgram - GpuProgram* create(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader); - }; -} - -#endif // __MetalProgramFactory_H__ diff --git a/RenderSystems/Metal/include/OgreMetalRenderSystem.h b/RenderSystems/Metal/include/OgreMetalRenderSystem.h deleted file mode 100644 index e244c148553..00000000000 --- a/RenderSystems/Metal/include/OgreMetalRenderSystem.h +++ /dev/null @@ -1,181 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2016 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#ifndef _OgreMetalRenderSystem_H_ -#define _OgreMetalRenderSystem_H_ - -#include "OgreMetalPrerequisites.h" - -#include "OgreRenderSystem.h" -#include "OgreMetalDevice.h" - -#import -#import - -namespace Ogre -{ - class HardwareBufferManager; - - /** \addtogroup RenderSystems RenderSystems - * @{ - */ - /** \defgroup Metal Metal - * Implementation of Metal as a rendering system. - * @{ - */ - class _OgreMetalExport MetalRenderSystem : public RenderSystem - { - MTLRenderPipelineDescriptor *psd; - MTLDepthStencilDescriptor* mDepthStencilDesc; - id mDepthStencilState; - bool mDepthStencilDescChanged; - - bool mInitialized; - HardwareBufferManager *mHardwareBufferManager; - MetalProgramFactory *mMetalProgramFactory; - - bool mStencilEnabled; - uint32_t mStencilRefValue; - - //For v1 rendering. - IndexData *mCurrentIndexBuffer; - VertexData *mCurrentVertexBuffer; - MTLPrimitiveType mCurrentPrimType; - - uint8 mNumMRTs; - MetalRenderTargetCommon *mCurrentColourRTs[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; - MetalDepthBuffer *mCurrentDepthBuffer; - MetalDevice *mActiveDevice; - __unsafe_unretained id mActiveRenderEncoder; - - MetalDevice mDevice; - dispatch_semaphore_t mMainGpuSyncSemaphore; - bool mMainSemaphoreAlreadyWaited; - bool mBeginFrameOnceStarted; - - void setActiveDevice( MetalDevice *device ); - void createRenderEncoder(void); - - std::map> mPSOCache; - id getPipelineState(); - - GpuProgram* mDefaultVP; - GpuProgram* mDefaultFP; - - std::unique_ptr mAutoParamsBuffer; - public: - const GpuProgramParametersPtr& getFixedFunctionParams(TrackVertexColourType tracking, - FogMode fog); - void applyFixedFunctionParams(const GpuProgramParametersPtr& params, uint16 mask); - - MetalRenderSystem(); - virtual ~MetalRenderSystem(); - - virtual void shutdown(void); - - virtual const String& getName(void) const; - virtual void setConfigOption(const String &name, const String &value) {} - - virtual HardwareOcclusionQuery* createHardwareOcclusionQuery(void); - - virtual RenderSystemCapabilities* createRenderSystemCapabilities(void) const; - - virtual RenderWindow* _createRenderWindow( const String &name, - unsigned int width, unsigned int height, - bool fullScreen, - const NameValuePairList *miscParams = 0); - - virtual MultiRenderTarget* createMultiRenderTarget(const String & name); - - virtual void _setTexture(size_t unit, bool enabled, const TexturePtr& texPtr); - - virtual DepthBuffer* _createDepthBufferFor( RenderTarget *renderTarget); - - void setStencilState(const StencilState& state) override; - - /// See VaoManager::waitForTailFrameToFinish - virtual void _waitForTailFrameToFinish(void); - virtual bool _willTailFrameStall(void); - - virtual void _beginFrame(void); - virtual void _endFrame(void); - - void setScissorTest(bool enabled, const Rect& rect); - - virtual void _setViewport(Viewport *vp); - - void setColourBlendState(const ColourBlendState& state); - - void _setSampler( size_t texUnit, Sampler& s); - void _setDepthClamp(bool enable); - void _setDepthBufferParams(bool depthTest = true, bool depthWrite = true, CompareFunction depthFunction = CMPF_LESS_EQUAL); - - void _setCullingMode(CullingMode mode); - void _setDepthBias(float constantBias, float slopeScaleBias = 0.0f); - - virtual void _convertProjectionMatrix( const Matrix4& matrix, Matrix4& dest, - bool forGpuProgram = false); - void _setPolygonMode(PolygonMode level); - void _setAlphaRejectSettings(CompareFunction func, unsigned char value, bool alphaToCoverage); - virtual void _render( const RenderOperation &op ); - - void bindGpuProgram(GpuProgram* prg); - virtual void bindGpuProgramParameters(GpuProgramType gptype, - const GpuProgramParametersPtr& params, uint16 variabilityMask); - virtual void clearFrameBuffer(unsigned int buffers, - const ColourValue& colour = ColourValue::Black, - float depth = 1.0f, unsigned short stencil = 0); - - virtual Real getMinimumDepthInputValue(void); - virtual Real getMaximumDepthInputValue(void); - - virtual void _setRenderTarget(RenderTarget *target); - - virtual void beginProfileEvent( const String &eventName ); - virtual void endProfileEvent( void ); - virtual void markProfileEvent( const String &event ); - - virtual void initGPUProfiling(void); - virtual void deinitGPUProfiling(void); - virtual void beginGPUSampleProfile( const String &name, uint32 *hashCache ); - virtual void endGPUSampleProfile( const String &name ); - - virtual void initialiseFromRenderSystemCapabilities( RenderSystemCapabilities* caps, - RenderTarget* primary ); - - MetalDevice* getActiveDevice(void) { return mActiveDevice; } - - void _notifyActiveEncoderEnded(void); - void _notifyActiveComputeEnded(void); - void _notifyDeviceStalled(void); - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/RenderSystems/Metal/include/OgreMetalRenderTargetCommon.h b/RenderSystems/Metal/include/OgreMetalRenderTargetCommon.h deleted file mode 100644 index aa62518460e..00000000000 --- a/RenderSystems/Metal/include/OgreMetalRenderTargetCommon.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2016 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#ifndef _OgreMetalRenderTargetCommon_H_ -#define _OgreMetalRenderTargetCommon_H_ - -#include "OgreMetalPrerequisites.h" - -namespace Ogre -{ - class _OgreMetalExport MetalRenderTargetCommon - { - protected: - MetalDevice *mOwnerDevice; - PixelFormat mFormat; - public: - MTLRenderPassColorAttachmentDescriptor *mColourAttachmentDesc; - - public: - MetalRenderTargetCommon( MetalDevice *ownerDevice ); - ~MetalRenderTargetCommon(); - - void init( id texture, id resolveTexture ); - void destroy(void); - - /// Returns true on success. False on failure. - virtual bool nextDrawable(void) { return true; } - - MetalDevice* getOwnerDevice(void) const { return mOwnerDevice; } - }; -} - -#endif diff --git a/RenderSystems/Metal/include/OgreMetalRenderTexture.h b/RenderSystems/Metal/include/OgreMetalRenderTexture.h deleted file mode 100644 index 5ccbee78edb..00000000000 --- a/RenderSystems/Metal/include/OgreMetalRenderTexture.h +++ /dev/null @@ -1,59 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2016 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _OgreMetalRenderTexture_H_ -#define _OgreMetalRenderTexture_H_ - -#include "OgreMetalPrerequisites.h" -#include "OgreRenderTexture.h" - -#include "OgreMetalRenderTargetCommon.h" - -namespace Ogre -{ - class MetalRenderTexture : public RenderTexture, public MetalRenderTargetCommon - { - //MetalRenderSystem *mRenderSystem; - - public: - MetalRenderTexture( MetalDevice *ownerDevice, const String &name, - HardwarePixelBuffer *buffer, - __unsafe_unretained id renderTexture, - __unsafe_unretained id resolveTexture, - PixelFormat format, uint32 depthPlane, uint32 slice, - uint32 fsaa, uint32 mip, bool hwGamma ); - virtual ~MetalRenderTexture(); - - virtual void swapBuffers(void); - - // RenderTarget overloads. - virtual bool requiresTextureFlipping() const { return false; } - virtual void getCustomAttribute( const String& name, void* pData ); - }; -} - -#endif diff --git a/RenderSystems/Metal/include/OgreMetalRenderWindow.h b/RenderSystems/Metal/include/OgreMetalRenderWindow.h deleted file mode 100644 index 03f6a3a9d09..00000000000 --- a/RenderSystems/Metal/include/OgreMetalRenderWindow.h +++ /dev/null @@ -1,84 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2016 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _OgreMetalRenderWindow_H_ -#define _OgreMetalRenderWindow_H_ - -#include "OgreMetalPrerequisites.h" -#include "OgreRenderWindow.h" - -#include "OgreMetalRenderTargetCommon.h" - -#include "OgreMetalView.h" - -#import - -namespace Ogre -{ - class MetalRenderWindow : public RenderWindow, public MetalRenderTargetCommon - { - CAMetalLayer *mMetalLayer; - id mCurrentDrawable; - id mMsaaTex; - OgreMetalView *mMetalView; -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - NSWindow *mWindow; - id mResizeObserver; -#endif - - float mContentScalingFactor; - - inline void checkLayerSizeChanges(void); - public: - MetalRenderWindow( MetalDevice *ownerDevice, MetalRenderSystem *renderSystem ); - virtual ~MetalRenderWindow(); - - virtual void swapBuffers(void); - virtual void windowMovedOrResized(void); - - virtual bool nextDrawable(void); - - virtual void create( const String& name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams ); - virtual void destroy(void); - - virtual void resize( unsigned int width, unsigned int height ); - virtual void reposition( int left, int top ); - - // RenderTarget overloads. - virtual void copyContentsToMemory(const Box& src, const PixelBox &dst, FrameBuffer buffer) {} - virtual bool requiresTextureFlipping() const { return false; } - - virtual void getCustomAttribute( const String& name, void* pData ); - - PixelFormat suggestPixelFormat() const override { return mFormat; } - - float getViewPointToPixelScale() override { return mContentScalingFactor; } - }; -} - -#endif diff --git a/RenderSystems/Metal/include/OgreMetalTexture.h b/RenderSystems/Metal/include/OgreMetalTexture.h deleted file mode 100644 index c91250cd569..00000000000 --- a/RenderSystems/Metal/include/OgreMetalTexture.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2016 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#ifndef _OgreMetalTexture_H_ -#define _OgreMetalTexture_H_ - -#include "OgreMetalPrerequisites.h" -#include "OgreMetalHardwarePixelBuffer.h" -#include "OgreTexture.h" -#include "OgreRenderTexture.h" -#include "OgreImage.h" -#include "OgreException.h" -#include "OgreHardwarePixelBuffer.h" - -#import - -namespace Ogre -{ - class MetalTexture : public Texture - { - protected: - id mTexture; - id mMsaaTexture; - MetalDevice *mDevice; - - MTLTextureType getMetalTextureTarget(void) const; - void createMetalTexResource(void); - void createSurfaceList(void); - - virtual void createInternalResourcesImpl(void); - virtual void freeInternalResourcesImpl(void); - - public: - MetalTexture( ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - MetalDevice *device ); - virtual ~MetalTexture(); - - void _autogenerateMipmaps(void); - - id getTextureForSampling( MetalRenderSystem *renderSystem ); - - MetalDevice* getOwnerDevice(void) const { return mDevice; } - }; -} - -#endif diff --git a/RenderSystems/Metal/include/OgreMetalTextureManager.h b/RenderSystems/Metal/include/OgreMetalTextureManager.h deleted file mode 100644 index 3bc858e35e1..00000000000 --- a/RenderSystems/Metal/include/OgreMetalTextureManager.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2016 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ -#ifndef _OgreMetalTextureManager_H_ -#define _OgreMetalTextureManager_H_ - -#include "OgreMetalPrerequisites.h" -#include "OgreTextureManager.h" - -#import - -namespace Ogre -{ - class MetalSampler : public Sampler - { - public: - MetalSampler(MetalDevice *device) : mDevice(device) {} - id getState(); - private: - id mSampler; - MetalDevice *mDevice; - }; - - class MetalTextureManager : public TextureManager - { - protected: - MetalDevice *mDevice; - - /// @copydoc ResourceManager::createImpl - virtual Resource* createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams); - - SamplerPtr _createSamplerImpl(); - public: - MetalTextureManager( MetalDevice *device ); - virtual ~MetalTextureManager(); - - /// @copydoc TextureManager::getNativeFormat - virtual PixelFormat getNativeFormat(TextureType ttype, PixelFormat format, int usage); - }; -} - -#endif diff --git a/RenderSystems/Metal/include/Windowing/OSX/OgreMetalView.h b/RenderSystems/Metal/include/Windowing/OSX/OgreMetalView.h deleted file mode 100644 index 37211dcd59a..00000000000 --- a/RenderSystems/Metal/include/Windowing/OSX/OgreMetalView.h +++ /dev/null @@ -1,67 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2016 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#import -#import -#import - -@interface OgreMetalView : NSView - -// view has a handle to the metal device when created -@property (nonatomic, readonly) id device; - -@property (nonatomic, readwrite) BOOL layerSizeDidUpdate; - -/// When true (default), we will try to set the contentScaleFactor to the native's. -/// You can use 'nativeScaleFactor' for further control. -/// Note: Changing contentScaleFactor directly will force this value to false. -@property (nonatomic) bool scaleToNative; - -/// When scaleToNative = true, instead of setting self.contentScaleFactor, you -/// should change this setting. It's expressed in fractions of the nativeScale. -/// -/// For example on an iPad Mini 3 the native factor is 2.0; thus if you set -/// nativeScaleFactor = 1; then contentScaleFactor = 2.0 -/// If you set nativeScaleFactor = 0.5; we'll set contentScaleFactor = 1.0 -@property (nonatomic) CGFloat nativeScaleFactor; - -@property(nonatomic) CGFloat contentScaleFactor; - -/// The value of presentationTime will be passed to -/// MTLCommandBuffer::presentDrawable atTime:presentationTime -/// When negative, it means to present immediately (Ogre will call presentDrawable overload) -/// This value is very important if you want to render at e.g. 30 fps: -/// Calling CADisplayLink.frameInterval = 2 is not enough; as the CPU timer will be fired -/// once every two VSync intervals, but if the GPU completes its job too soon, it will -/// present immediately (i.e. in the next 16ms instead of waiting 33ms). -/// In that case you'll want to set presentationTime = displayLink.timestamp+(1.0/fps) -/// See -/// https://developer.apple.com/library/prerelease/content/documentation/3DDrawing/Conceptual/MTLBestPracticesGuide/FrameRate.html -@property (nonatomic) CFTimeInterval presentationTime; - -@end diff --git a/RenderSystems/Metal/include/Windowing/iOS/OgreMetalView.h b/RenderSystems/Metal/include/Windowing/iOS/OgreMetalView.h deleted file mode 100644 index 4687fd2e360..00000000000 --- a/RenderSystems/Metal/include/Windowing/iOS/OgreMetalView.h +++ /dev/null @@ -1,62 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2016 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#import -#import -#import - -@interface OgreMetalView : UIView - -@property (readwrite, nonatomic) BOOL layerSizeDidUpdate; - -/// When true (default), we will try to set the contentScaleFactor to the native's. -/// You can use 'nativeScaleFactor' for further control. -/// Note: Changing contentScaleFactor directly will force this value to false. -@property (nonatomic) bool scaleToNative; - -/// When scaleToNative = true, instead of setting self.contentScaleFactor, you -/// should change this setting. It's expressed in fractions of the nativeScale. -/// -/// For example on an iPad Mini 3 the native factor is 2.0; thus if you set -/// nativeScaleFactor = 1; then contentScaleFactor = 2.0 -/// If you set nativeScaleFactor = 0.5; we'll set contentScaleFactor = 1.0 -@property (nonatomic) CGFloat nativeScaleFactor; - -/// The value of presentationTime will be passed to -/// MTLCommandBuffer::presentDrawable atTime:presentationTime -/// When negative, it means to present immediately (Ogre will call presentDrawable overload) -/// This value is very important if you want to render at e.g. 30 fps: -/// Calling CADisplayLink.frameInterval = 2 is not enough; as the CPU timer will be fired -/// once every two VSync intervals, but if the GPU completes its job too soon, it will -/// present immediately (i.e. in the next 16ms instead of waiting 33ms). -/// In that case you'll want to set presentationTime = displayLink.timestamp+(1.0/fps) -/// See -/// https://developer.apple.com/library/prerelease/content/documentation/3DDrawing/Conceptual/MTLBestPracticesGuide/FrameRate.html -@property (nonatomic) CFTimeInterval presentationTime; - -@end diff --git a/RenderSystems/Metal/src/OgreMetalDepthBuffer.mm b/RenderSystems/Metal/src/OgreMetalDepthBuffer.mm deleted file mode 100644 index 350b48b93a7..00000000000 --- a/RenderSystems/Metal/src/OgreMetalDepthBuffer.mm +++ /dev/null @@ -1,108 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2016 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreMetalDepthBuffer.h" -#include "OgreMetalRenderSystem.h" -#include "OgreRenderTarget.h" -#include "OgreMetalRenderTargetCommon.h" - -#import -#import - -namespace Ogre -{ - MetalDepthBuffer::MetalDepthBuffer( uint16 poolId, MetalRenderSystem *renderSystem, - uint32 width, uint32 height, uint32 fsaa, - MTLPixelFormat pixelFormat, bool _isManual, - id depthTexture, id stencilTexture, - MetalDevice *device ) : - DepthBuffer( poolId, width, height, fsaa, - _isManual ), - mDepthAttachmentDesc( 0 ), - mStencilAttachmentDesc( 0 ), - mDevice( device ) - { - mFormat = pixelFormat; - if( depthTexture ) - { - mDepthAttachmentDesc = [MTLRenderPassDepthAttachmentDescriptor new]; - mDepthAttachmentDesc.loadAction = MTLLoadActionDontCare; - mDepthAttachmentDesc.storeAction = MTLStoreActionStore; - mDepthAttachmentDesc.texture = depthTexture; - } - - if( stencilTexture ) - { - mStencilAttachmentDesc = [MTLRenderPassStencilAttachmentDescriptor new]; - mStencilAttachmentDesc.loadAction = MTLLoadActionDontCare; - mStencilAttachmentDesc.storeAction = MTLStoreActionStore; - mStencilAttachmentDesc.texture = stencilTexture; - } - } - //----------------------------------------------------------------------------------- - MetalDepthBuffer::~MetalDepthBuffer() - { - mDepthAttachmentDesc = 0; - mStencilAttachmentDesc = 0; - } - //----------------------------------------------------------------------------------- - bool MetalDepthBuffer::isCompatible( RenderTarget *renderTarget) const - { - //First check they belong to the same GPU device. - auto device = dynamic_cast(renderTarget)->getOwnerDevice(); - if( device == mDevice && renderTarget->suggestPixelFormat() != PF_UNKNOWN && - this->getWidth() == renderTarget->getWidth() && - this->getHeight() == renderTarget->getHeight() && - this->getFSAA() == renderTarget->getFSAA()// && - // mDepthTexture == renderTarget->prefersDepthTexture() && - // mFormat == renderTarget->getDesiredDepthBufferFormat() - ) - { - return true; - } - - return false; - } - //----------------------------------------------------------------------------------- - bool MetalDepthBuffer::copyToImpl( DepthBuffer *destination ) - { - MetalDepthBuffer *dstDepthBuffer = static_cast( destination ); - - __unsafe_unretained id blitEncoder = mDevice->getBlitEncoder(); - [blitEncoder copyFromTexture:mDepthAttachmentDesc.texture - sourceSlice:0 - sourceLevel:0 - sourceOrigin:MTLOriginMake( 0, 0, 0 ) - sourceSize:MTLSizeMake( mWidth, mHeight, 1u ) - toTexture:dstDepthBuffer->mDepthAttachmentDesc.texture - destinationSlice:0 - destinationLevel:0 - destinationOrigin:MTLOriginMake( 0, 0, 0 )]; - - return true; - } -} diff --git a/RenderSystems/Metal/src/OgreMetalDevice.mm b/RenderSystems/Metal/src/OgreMetalDevice.mm deleted file mode 100644 index 50437096e62..00000000000 --- a/RenderSystems/Metal/src/OgreMetalDevice.mm +++ /dev/null @@ -1,183 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2016 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreMetalDevice.h" -#include "OgreMetalRenderSystem.h" -#include "OgreProfiler.h" - -#import -#import -#import - -namespace Ogre -{ - MetalDevice::MetalDevice( MetalRenderSystem *renderSystem ) : - mFrameAborted( false ), - mDevice( 0 ), - mMainCommandQueue( 0 ), - mCurrentCommandBuffer( 0 ), - mBlitEncoder( 0 ), - mComputeEncoder( 0 ), - mRenderEncoder( 0 ), - mRenderSystem( renderSystem ), - mStallSemaphore( 0 ) - { - mStallSemaphore = dispatch_semaphore_create( 0 ); - } - //------------------------------------------------------------------------- - MetalDevice::~MetalDevice() - { - mDevice = 0; - mMainCommandQueue = 0; - mCurrentCommandBuffer = 0; - mBlitEncoder = 0; - mComputeEncoder = 0; - mRenderEncoder = 0; - } - //------------------------------------------------------------------------- - void MetalDevice::init(void) - { - @autoreleasepool - { - mDevice = MTLCreateSystemDefaultDevice(); - OgreAssert(mDevice, "Could not create Metal Device"); - - mMainCommandQueue = [mDevice newCommandQueue]; - mCurrentCommandBuffer = [mMainCommandQueue commandBuffer]; - mBlitEncoder = 0; - mComputeEncoder = 0; - mRenderEncoder = 0; - } - } - //------------------------------------------------------------------------- - void MetalDevice::endBlitEncoder(void) - { - if( mBlitEncoder ) - { - [mBlitEncoder endEncoding]; - mBlitEncoder = 0; - } - } - //------------------------------------------------------------------------- - void MetalDevice::endRenderEncoder(void) - { - if( mRenderEncoder ) - { - [mRenderEncoder endEncoding]; - mRenderEncoder = 0; - - if( mRenderSystem->getActiveDevice() == this ) - mRenderSystem->_notifyActiveEncoderEnded(); - } - } - //------------------------------------------------------------------------- - void MetalDevice::endComputeEncoder(void) - { - if( mComputeEncoder ) - { - [mComputeEncoder endEncoding]; - mComputeEncoder = 0; - - if( mRenderSystem->getActiveDevice() == this ) - mRenderSystem->_notifyActiveComputeEnded(); - } - } - //------------------------------------------------------------------------- - void MetalDevice::endAllEncoders(void) - { - endBlitEncoder(); - endRenderEncoder(); - endComputeEncoder(); - } - //------------------------------------------------------------------------- - void MetalDevice::commitAndNextCommandBuffer(void) - { - endAllEncoders(); - //Push the command buffer to the GPU - [mCurrentCommandBuffer commit]; - @autoreleasepool - { - mCurrentCommandBuffer = [mMainCommandQueue commandBuffer]; -#if OGRE_PROFILING - _rmt_BindMetal( mCurrentCommandBuffer ); -#endif - } - } - //------------------------------------------------------------------------- - id MetalDevice::getBlitEncoder(void) - { - if( !mBlitEncoder ) - { - endRenderEncoder(); - endComputeEncoder(); - - @autoreleasepool - { - mBlitEncoder = [mCurrentCommandBuffer blitCommandEncoder]; - } - } - - return mBlitEncoder; - } - //------------------------------------------------------------------------- - id MetalDevice::getComputeEncoder(void) - { - if( !mComputeEncoder ) - { - endRenderEncoder(); - endBlitEncoder(); - - mComputeEncoder = [mCurrentCommandBuffer computeCommandEncoder]; - } - - return mComputeEncoder; - } - //------------------------------------------------------------------------- - void MetalDevice::stall(void) - { - __block dispatch_semaphore_t blockSemaphore = mStallSemaphore; - [mCurrentCommandBuffer addCompletedHandler:^(id buffer) - { - dispatch_semaphore_signal( blockSemaphore ); - }]; - commitAndNextCommandBuffer(); - - const long result = dispatch_semaphore_wait( mStallSemaphore, DISPATCH_TIME_FOREVER ); - - if( result != 0 ) - { - OGRE_EXCEPT( Exception::ERR_RENDERINGAPI_ERROR, - "Failure while waiting for a MetalFence. Could be out of GPU memory. " - "Update your video card drivers. If that doesn't help, " - "contact the developers. Error code: " + StringConverter::toString( result ), - "MetalDevice::stall" ); - } - - mRenderSystem->_notifyDeviceStalled(); - } -} diff --git a/RenderSystems/Metal/src/OgreMetalEngineDll.mm b/RenderSystems/Metal/src/OgreMetalEngineDll.mm deleted file mode 100644 index b1fc3580b2c..00000000000 --- a/RenderSystems/Metal/src/OgreMetalEngineDll.mm +++ /dev/null @@ -1,52 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2016 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreRoot.h" -#include "OgreMetalPlugin.h" -#include "OgreMetalPrerequisites.h" - -#ifndef OGRE_STATIC_LIB - -namespace Ogre -{ - static MetalPlugin* plugin; - - extern "C" void _OgreMetalExport dllStartPlugin(void) throw() - { - plugin = OGRE_NEW MetalPlugin(); - Root::getSingleton().installPlugin(plugin); - } - - extern "C" void _OgreMetalExport dllStopPlugin(void) - { - Root::getSingleton().uninstallPlugin(plugin); - OGRE_DELETE plugin; - } -} - -#endif diff --git a/RenderSystems/Metal/src/OgreMetalHardwareBufferCommon.mm b/RenderSystems/Metal/src/OgreMetalHardwareBufferCommon.mm deleted file mode 100644 index a63362b93c1..00000000000 --- a/RenderSystems/Metal/src/OgreMetalHardwareBufferCommon.mm +++ /dev/null @@ -1,177 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreMetalHardwareBufferCommon.h" -#include "OgreMetalDevice.h" -#include "OgreDefaultHardwareBufferManager.h" - -#import -#import - -namespace Ogre -{ - MetalHardwareBufferCommon::MetalHardwareBufferCommon( size_t sizeBytes, Usage usage, bool useShadowBuffer, - uint16 alignment, - MetalDevice *device ) : - HardwareBuffer(usage, false), - mBuffer( 0 ), - mDevice( device ) - { - mSizeInBytes = sizeBytes; - - MTLResourceOptions resourceOptions = 0; - - // FIXME always using shared storage for now - if( usage & HBU_DETAIL_WRITE_ONLY & 0) - { - resourceOptions |= MTLResourceStorageModePrivate; - resourceOptions |= MTLResourceCPUCacheModeWriteCombined; - } - else - { - resourceOptions |= MTLResourceStorageModeShared; - } - - mBuffer = [mDevice->mDevice newBufferWithLength:alignToNextMultiple( sizeBytes, 4u ) - options:resourceOptions]; - - if (useShadowBuffer) - { - mShadowBuffer.reset(new DefaultHardwareBuffer(mSizeInBytes)); - } - } - //----------------------------------------------------------------------------------- - MetalHardwareBufferCommon::~MetalHardwareBufferCommon() - { - mBuffer = 0; - } - //----------------------------------------------------------------------------------- - id MetalHardwareBufferCommon::getBufferName( size_t &outOffset ) - { - outOffset = 0; - return mBuffer; - } - //----------------------------------------------------------------------------------- - void* MetalHardwareBufferCommon::lockImpl( size_t offset, size_t length, LockOptions options) - { - if ((options == HBL_READ_ONLY || options == HBL_NORMAL) && mBuffer.storageMode == MTLStorageModePrivate) - { - LogManager::getSingleton().logWarning("HardwareBuffer - UNIMPLEMENTED implicit GPU to HOST copy (slow)"); - } - - void *retPtr = mBuffer.contents; - return static_cast( retPtr ) + offset; - } - //----------------------------------------------------------------------------------- - void MetalHardwareBufferCommon::unlockImpl() - { - } - //----------------------------------------------------------------------------------- - void MetalHardwareBufferCommon::readData( size_t offset, size_t length, void* pDest ) - { - // just use memcpy - HardwareBufferLockGuard thisLock(this, offset, length, HBL_READ_ONLY); - memcpy(pDest, thisLock.pData, length); - } - //----------------------------------------------------------------------------------- - void MetalHardwareBufferCommon::writeData(size_t offset, size_t length, const void* pSource, - bool discardWholeBuffer) - { - discardWholeBuffer = discardWholeBuffer || (offset == 0 && length == mSizeInBytes); - if (mShadowBuffer) - { - mShadowBuffer->writeData(offset, length, pSource, discardWholeBuffer); - } - - writeDataImpl(offset, length, pSource, discardWholeBuffer); - } - void MetalHardwareBufferCommon::writeDataImpl(size_t offset, size_t length, const void* pSource, - bool discardWholeBuffer) - { - // FIXME - if(true || mBuffer.storageMode == MTLStorageModePrivate) - { - void *dstData = lockImpl( offset, length, HBL_DISCARD); - memcpy( dstData, pSource, length ); - unlockImpl(); - } - } - //----------------------------------------------------------------------------------- - void MetalHardwareBufferCommon::copyData( HardwareBuffer& _srcBuffer, size_t srcOffset, - size_t dstOffset, size_t length, bool discardWholeBuffer ) - { - if (mShadowBuffer) - { - mShadowBuffer->copyData(_srcBuffer, srcOffset, dstOffset, length, discardWholeBuffer); - } - - auto srcBuffer = static_cast(&_srcBuffer); - discardWholeBuffer = discardWholeBuffer || (dstOffset == 0 && length == mSizeInBytes); - - if( srcBuffer->mBuffer.storageMode == MTLStorageModePrivate ) - { - size_t srcOffsetStart = 0; - __unsafe_unretained id srcBuf = srcBuffer->getBufferName( srcOffsetStart ); - __unsafe_unretained id dstBuf = mBuffer; - - __unsafe_unretained id blitEncoder = mDevice->getBlitEncoder(); - [blitEncoder copyFromBuffer:srcBuf - sourceOffset:srcOffset + srcOffsetStart - toBuffer:dstBuf - destinationOffset:dstOffset - size:length]; - } - else - { - HardwareBuffer::LockOptions dstOption; - if( discardWholeBuffer ) - dstOption = HardwareBuffer::HBL_DISCARD; - else - dstOption = HardwareBuffer::HBL_WRITE_ONLY; - - const void *srcData = srcBuffer->lockImpl( srcOffset, length, HBL_READ_ONLY); - void *dstData = this->lockImpl( dstOffset, length, dstOption ); - - memcpy( dstData, srcData, length ); - - this->unlockImpl(); - srcBuffer->unlockImpl(); - } - } - - //----------------------------------------------------------------------------------- - void MetalHardwareBufferCommon::_updateFromShadow(void) - { - if( mShadowBuffer && mShadowUpdated && !mSuppressHardwareUpdate ) - { - HardwareBufferLockGuard shadowLock(mShadowBuffer.get(), mLockStart, mLockSize, HBL_READ_ONLY); - writeDataImpl(mLockStart, mLockSize, shadowLock.pData, false); - mShadowUpdated = false; - } - } -} diff --git a/RenderSystems/Metal/src/OgreMetalHardwareBufferManager.mm b/RenderSystems/Metal/src/OgreMetalHardwareBufferManager.mm deleted file mode 100644 index d41087e0ce2..00000000000 --- a/RenderSystems/Metal/src/OgreMetalHardwareBufferManager.mm +++ /dev/null @@ -1,103 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreMetalHardwareBufferManager.h" -#include "OgreMetalHardwareBufferCommon.h" - -namespace Ogre { - MetalHardwareBufferManager::MetalHardwareBufferManager( MetalDevice *device) : mDevice(device) - { - } - //----------------------------------------------------------------------------------- - MetalHardwareBufferManager::~MetalHardwareBufferManager() - { - destroyAllDeclarations(); - destroyAllBindings(); - } - //----------------------------------------------------------------------------------- - void MetalHardwareBufferManager::_notifyDeviceStalled(void) - { - { - OGRE_LOCK_MUTEX(mVertexBuffersMutex); - VertexBufferList::const_iterator itor = mVertexBuffers.begin(); - VertexBufferList::const_iterator end = mVertexBuffers.end(); - - while( itor != end ) - { - auto hwBuffer = (*itor)->_getImpl(); - hwBuffer->_notifyDeviceStalled(); - ++itor; - } - } - { - OGRE_LOCK_MUTEX(mIndexBuffersMutex); - IndexBufferList::const_iterator itor = mIndexBuffers.begin(); - IndexBufferList::const_iterator end = mIndexBuffers.end(); - - while( itor != end ) - { - auto hwBuffer = (*itor)->_getImpl(); - hwBuffer->_notifyDeviceStalled(); - ++itor; - } - } - } - //----------------------------------------------------------------------------------- - HardwareVertexBufferSharedPtr - MetalHardwareBufferManager::createVertexBuffer( size_t vertexSize, size_t numVerts, - HardwareBuffer::Usage usage, - bool useShadowBuffer ) - { - auto impl = new MetalHardwareBufferCommon(vertexSize * numVerts, usage, useShadowBuffer, 4, - mDevice); - auto buf = std::make_shared(this, vertexSize, numVerts, impl); - { - OGRE_LOCK_MUTEX(mVertexBuffersMutex); - mVertexBuffers.insert(buf.get()); - } - return buf; - } - //----------------------------------------------------------------------------------- - HardwareIndexBufferSharedPtr - MetalHardwareBufferManager::createIndexBuffer( HardwareIndexBuffer::IndexType itype, - size_t numIndexes, - HardwareBuffer::Usage usage, - bool useShadowBuffer ) - { - auto indexSize = HardwareIndexBuffer::indexSize(itype); - auto impl = new MetalHardwareBufferCommon(indexSize * numIndexes, usage, useShadowBuffer, 4, - mDevice); - - auto buf = std::make_shared(this, itype, numIndexes, impl); - { - OGRE_LOCK_MUTEX(mIndexBuffersMutex); - mIndexBuffers.insert(buf.get()); - } - return buf; - } -} diff --git a/RenderSystems/Metal/src/OgreMetalHardwarePixelBuffer.mm b/RenderSystems/Metal/src/OgreMetalHardwarePixelBuffer.mm deleted file mode 100644 index 68719200a49..00000000000 --- a/RenderSystems/Metal/src/OgreMetalHardwarePixelBuffer.mm +++ /dev/null @@ -1,565 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2016 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreMetalHardwarePixelBuffer.h" -#include "OgreMetalRenderTexture.h" -#include "OgreMetalRenderSystem.h" -#include "OgreRoot.h" - -#include "OgreMetalMappings.h" - -#import - -namespace Ogre { - MetalHardwarePixelBuffer::MetalHardwarePixelBuffer( uint32 width, uint32 height, - uint32 depth, PixelFormat format, - bool hwGamma, HardwareBuffer::Usage usage ) - : HardwarePixelBuffer(width, height, depth, format, usage, false), - mBuffer(width, height, depth, format) - { - } - - MetalHardwarePixelBuffer::~MetalHardwarePixelBuffer() - { - // Force free buffer - delete [] (uint8*)mBuffer.data; - } - - void MetalHardwarePixelBuffer::allocateBuffer() - { - if (mBuffer.data) - // Already allocated - return; - - mBuffer.data = new uint8[mSizeInBytes]; - } - - void MetalHardwarePixelBuffer::freeBuffer() - { - // Free buffer if we're STATIC to save memory - if (mUsage & HBU_STATIC) - { - delete [] (uint8*)mBuffer.data; - mBuffer.data = 0; - } - } - - PixelBox MetalHardwarePixelBuffer::lockImpl(const Box &lockBox, LockOptions options) - { - allocateBuffer(); - if (options != HardwareBuffer::HBL_DISCARD) - { - // Download the old contents of the texture - download(mBuffer); - } - return mBuffer.getSubVolume(lockBox); - } - - void MetalHardwarePixelBuffer::unlockImpl(void) - { - if (mCurrentLockOptions != HardwareBuffer::HBL_READ_ONLY) - { - // From buffer to card, only upload if was locked for writing - upload(mCurrentLock, mLockedBox); - } - freeBuffer(); - } - - void MetalHardwarePixelBuffer::blitFromMemory(const PixelBox &src, const Box &dstBox) - { - if (!mBuffer.contains(dstBox)) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Destination box out of range", - "MetalHardwarePixelBuffer::blitFromMemory"); - } - - bool freeScaledBuffer = false; - PixelBox scaled; - - if (src.getWidth() != dstBox.getWidth() || - src.getHeight() != dstBox.getHeight() || - src.getDepth() != dstBox.getDepth()) - { - // Scale to destination size. - // This also does pixel format conversion if needed - allocateBuffer(); - scaled = mBuffer.getSubVolume(dstBox); - Image::scale(src, scaled, Image::FILTER_BILINEAR); - } - else - { - allocateBuffer(); - - // No scaling or conversion needed - scaled = PixelBox(src.getWidth(), src.getHeight(), src.getDepth(), src.format, src.data); - - if (src.format == PF_R8G8B8 || src.format == PF_B8G8R8) - { - const PixelFormat newFormat = src.format == PF_R8G8B8 ? PF_X8R8G8B8 : PF_X8B8G8R8; - freeScaledBuffer = true; - size_t scaledSize = PixelUtil::getMemorySize( src.getWidth(), src.getHeight(), - src.getDepth(), newFormat ); - scaled.format = newFormat; - scaled.data = new uint8[scaledSize]; - scaled.setConsecutive(); - PixelUtil::bulkPixelConversion(src, scaled); - } - else if (src.format == PF_BYTE_LA) - { - freeScaledBuffer = true; - size_t scaledSize = PixelUtil::getMemorySize( src.getWidth(), src.getHeight(), - src.getDepth(), PF_A8R8G8B8 ); - scaled.format = PF_A8R8G8B8; - scaled.data = new uint8[scaledSize]; - scaled.setConsecutive(); - PixelUtil::bulkPixelConversion(src, scaled); - } - } - - upload(scaled, dstBox); - freeBuffer(); - - if (freeScaledBuffer) - { - delete[] (uint8*)scaled.data; - } - } - - void MetalHardwarePixelBuffer::blitToMemory(const Box &srcBox, const PixelBox &dst) - { - if (!mBuffer.contains(srcBox)) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "source box out of range", - "MetalHardwarePixelBuffer::blitToMemory"); - } - - if( srcBox.left == 0 && srcBox.right == getWidth() && - srcBox.top == 0 && srcBox.bottom == getHeight() && - srcBox.front == 0 && srcBox.back == getDepth() && - dst.getWidth() == getWidth() && - dst.getHeight() == getHeight() && - dst.getDepth() == getDepth() ) - { - // The direct case: the user wants the entire texture in a format supported by Metal - // so we don't need an intermediate buffer - download(dst); - } - else - { - // Use buffer for intermediate copy - allocateBuffer(); - // Download entire buffer - download(mBuffer); - if(srcBox.getWidth() != dst.getWidth() || - srcBox.getHeight() != dst.getHeight() || - srcBox.getDepth() != dst.getDepth()) - { - // We need scaling - Image::scale(mBuffer.getSubVolume(srcBox), dst, Image::FILTER_BILINEAR); - } - else - { - // Just copy the bit that we need - PixelUtil::bulkPixelConversion(mBuffer.getSubVolume(srcBox), dst); - } - freeBuffer(); - } - } - - void MetalHardwarePixelBuffer::upload(const PixelBox &data, const Box &dest) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Upload not possible for this pixelbuffer type", - "MetalHardwarePixelBuffer::upload"); - } - - void MetalHardwarePixelBuffer::download(const PixelBox &data) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Download not possible for this pixelbuffer type", - "MetalHardwarePixelBuffer::download"); - } - - void MetalHardwarePixelBuffer::bindToFramebuffer(uint32 attachment, size_t zoffset) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, - "Framebuffer bind not possible for this pixelbuffer type", - "MetalHardwarePixelBuffer::bindToFramebuffer"); - } - - // TextureBuffer - MetalTextureBuffer::MetalTextureBuffer( __unsafe_unretained id renderTexture, - __unsafe_unretained id resolveTexture, - MetalDevice *device, - const String &baseName, MTLTextureType target, - int width, int height, int depth, PixelFormat format, - int face, int level, Usage usage, - bool writeGamma, uint fsaa ) : - MetalHardwarePixelBuffer(0, 0, 0, format, writeGamma, usage), - mTexture( renderTexture ? renderTexture : resolveTexture ), - mTarget( target ), - mBufferId( 0 ), - mFace( face ), - mLevel( level ) - { - // Calculate the width and height of the texture at this mip level - mWidth = mLevel == 0 ? width : width / static_cast(pow(2.0f, level)); - mHeight = mLevel == 0 ? height : height / static_cast(pow(2.0f, level)); - if(mWidth < 1) - mWidth = 1; - if(mHeight < 1) - mHeight = 1; - - if(target != MTLTextureType3D && target != MTLTextureType2DArray) - mDepth = 1; // Depth always 1 for non-3D textures - else - mDepth = depth; - -#if OGRE_DEBUG_MODE - // Log a message - std::stringstream str; - str << "MetalHardwarePixelBuffer constructed for texture " << baseName - << " face " << mFace << " level " << mLevel << ":" - << " width=" << mWidth << " height="<< mHeight << " depth=" << mDepth - << " format=" << PixelUtil::getFormatName(mFormat) - << " MTLformat=" << format - << " rowPitch=" << mRowPitch; - LogManager::getSingleton().logMessage(LML_NORMAL, str.str()); -#endif - - // Set up a pixel box - mBuffer = PixelBox(mWidth, mHeight, mDepth, mFormat); - - if (mWidth == 0 || mHeight == 0 || mDepth == 0) - // We are invalid, do not allocate a buffer - return; - - // Is this a render target? - if (mUsage & TU_RENDERTARGET) - { - // Create render target for each slice - mSliceTRT.reserve(mDepth); - for(uint32 zoffset=0; zoffsetattachRenderTarget(*mSliceTRT[zoffset]); - } - } - } - - MetalTextureBuffer::~MetalTextureBuffer() - { - } - - void MetalTextureBuffer::upload(const PixelBox &data, const Box &dest) - { - if(PixelUtil::isCompressed(data.format) && (NSUInteger)mLevel == mTexture.mipmapLevelCount) - return; - - // Calculate size for all mip levels of the texture - size_t bytesPerImage = PixelUtil::getMemorySize( dest.getWidth(), dest.getHeight(), - 1, data.format ); - - if (!PixelUtil::isCompressed(data.format)) - { - if (data.getWidth() != data.rowPitch) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Unsupported texture format", - "MetalTextureBuffer::upload"); - } - - if (data.getHeight() * data.getWidth() != data.slicePitch) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "Unsupported texture format", - "MetalTextureBuffer::upload"); - } - } - - NSUInteger rowPitch = PixelUtil::getMemorySize(data.getWidth(), 1, 1, data.format); - - // PVR textures should have 0 row size and data size - if( data.format == PF_PVRTC2_2BPP || - data.format == PF_PVRTC2_4BPP || - data.format == PF_PVRTC_RGB2 || - data.format == PF_PVRTC_RGB4 || - data.format == PF_PVRTC_RGBA2 || - data.format == PF_PVRTC_RGBA4 ) - { - rowPitch = 0; - bytesPerImage = 0; - } - - switch(mTarget) - { - case MTLTextureType1D: - [mTexture replaceRegion:MTLRegionMake1D( dest.left, dest.getWidth() ) - mipmapLevel:mLevel - withBytes:data.data - bytesPerRow:0]; - break; - case MTLTextureType1DArray: - [mTexture replaceRegion:MTLRegionMake1D( dest.left, dest.getWidth() ) - mipmapLevel:mLevel - withBytes:data.data - bytesPerRow:rowPitch]; - break; - case MTLTextureType2D: - [mTexture replaceRegion:MTLRegionMake2D( dest.left, dest.top, - dest.getWidth(), dest.getHeight() ) - mipmapLevel:mLevel - withBytes:data.data - bytesPerRow:rowPitch]; - break; - case MTLTextureType2DArray: - [mTexture replaceRegion:MTLRegionMake2D( dest.left, dest.top, - dest.getWidth(), dest.getHeight() ) - mipmapLevel:mLevel - slice:dest.front - withBytes:data.data - bytesPerRow:rowPitch - bytesPerImage:bytesPerImage]; - break; - case MTLTextureType2DMultisample: - [mTexture replaceRegion:MTLRegionMake2D( dest.left, dest.top, - dest.getWidth(), dest.getHeight() ) - mipmapLevel:mLevel - withBytes:data.data - bytesPerRow:rowPitch]; - break; - case MTLTextureTypeCube: - [mTexture replaceRegion:MTLRegionMake2D( dest.left, dest.top, - dest.getWidth(), dest.getHeight() ) - mipmapLevel:mLevel - slice:mFace - withBytes:data.data - bytesPerRow:rowPitch - bytesPerImage:bytesPerImage]; - break; -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - case MTLTextureTypeCubeArray: - [mTexture replaceRegion:MTLRegionMake3D( dest.left, dest.top, dest.front, - dest.getWidth(), - dest.getHeight(), - dest.getDepth() ) - mipmapLevel:mLevel - slice:dest.front - withBytes:data.data - bytesPerRow:rowPitch - bytesPerImage:bytesPerImage]; -#endif - case MTLTextureType3D: - [mTexture replaceRegion:MTLRegionMake3D( dest.left, dest.top, dest.front, - dest.getWidth(), - dest.getHeight(), - dest.getDepth() ) - mipmapLevel:mLevel - slice:0 - withBytes:data.data - bytesPerRow:rowPitch - bytesPerImage:bytesPerImage]; - break; - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "unhandled case"); - } - -#if OGRE_DEBUG_MODE - std::stringstream str; - str << "MetalTextureBuffer::upload: " - << " pixel buffer: " << mBufferId - << " bytes: " << mSizeInBytes - << " dest depth: " << dest.getDepth() - << " dest front: " << dest.front - << " bytesPerImage: " << bytesPerImage - << " face: " << mFace << " level: " << mLevel - << " width: " << mWidth << " height: "<< mHeight << " depth: " << mDepth - << " format: " << PixelUtil::getFormatName(mFormat) - << " data format: " << PixelUtil::getFormatName(data.format); - LogManager::getSingleton().logMessage(LML_NORMAL, str.str()); -#endif - } - - //----------------------------------------------------------------------------------- - void MetalTextureBuffer::download(const PixelBox &data) - { - if(data.getWidth() != getWidth() || - data.getHeight() != getHeight() || - data.getDepth() != getDepth()) - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "only download of entire buffer is supported by Metal", - "MetalTextureBuffer::download" ); - - // Sleep for 0.01s to allow render operations to finish - struct timespec tim, tim2; - tim.tv_sec = 0; - tim.tv_nsec = 10000000L; - - nanosleep(&tim, &tim2); - - NSUInteger bytesPerPixel = PixelUtil::getNumElemBytes(data.format); - - // Construct a temp PixelBox - size_t sizeInBytes = PixelUtil::getMemorySize( data.getWidth(), data.getHeight(), - data.getDepth(), mFormat ); - - PixelBox tempBox = PixelBox( data.getWidth(), data.getHeight(), data.getDepth(), mFormat ); - tempBox.data = new uint8[sizeInBytes]; - - if( mTexture.storageMode == MTLStorageModePrivate ) - { - MetalRenderSystem *renderSystem = - static_cast( Root::getSingleton().getRenderSystem() ); - MetalDevice *device = renderSystem->getActiveDevice(); - - MTLResourceOptions resourceOptions = MTLResourceCPUCacheModeDefaultCache| - MTLResourceStorageModeShared; - id tmpBuffer = [device->mDevice newBufferWithLength:sizeInBytes - options:resourceOptions]; - __unsafe_unretained id blitEncoder = device->getBlitEncoder(); - - [blitEncoder copyFromTexture:mTexture - sourceSlice:0 - sourceLevel:0 - sourceOrigin:MTLOriginMake( data.left, data.top, data.front ) - sourceSize:MTLSizeMake( data.getWidth(), data.getHeight(), - data.getDepth() ) - toBuffer:tmpBuffer - destinationOffset:0 - destinationBytesPerRow:bytesPerPixel * data.getWidth() - destinationBytesPerImage:bytesPerPixel * data.getWidth() * data.getHeight()]; - - device->stall(); - - memcpy( tempBox.data, [tmpBuffer contents], sizeInBytes ); - } - else - { - [mTexture getBytes:tempBox.data - bytesPerRow:bytesPerPixel * data.getWidth() - fromRegion:MTLRegionMake2D(data.left, data.top, data.getWidth(), data.getHeight()) - mipmapLevel:0]; - } - - // Convert to the target pixel format and vertically flip - PixelUtil::bulkPixelConversion(tempBox, data); - - delete[] (uint8*) tempBox.data; - tempBox.data = 0; - } - //----------------------------------------------------------------------------------- - void MetalTextureBuffer::bindToFramebuffer(uint32 attachment, size_t zoffset) - { - assert(zoffset < mDepth); - } - //----------------------------------------------------------------------------------- - void MetalTextureBuffer::copyFromFramebuffer(size_t zoffset) - { - } - //----------------------------------------------------------------------------------- - void MetalTextureBuffer::blit( const HardwarePixelBufferSharedPtr &src, - const Box &srcBox, const Box &dstBox ) - { - MetalTextureBuffer *srct = static_cast(src.get()); - // Destination texture must be 2D or Cube - // Source texture must be 2D - if(((src->getUsage() & TU_RENDERTARGET) == 0 && (srct->mTarget == MTLTextureType2D)) - || ((srct->mTarget == MTLTextureType3D) && (mTarget != MTLTextureType2DArray))) - { - blitFromTexture(srct, srcBox, dstBox); - } - else - { - MetalHardwarePixelBuffer::blit(src, srcBox, dstBox); - } - } - - //----------------------------------------------------------------------------------- - // Very fast texture-to-texture blitter and hardware bi/trilinear scaling implementation using FBO - // Destination texture must be 1D, 2D, 3D, or Cube - // Source texture must be 1D, 2D or 3D - // Supports compressed formats as both source and destination format, it will use the hardware DXT compressor - // if available. - // @author W.J. van der Laan - void MetalTextureBuffer::blitFromTexture(MetalTextureBuffer *src, const Box &srcBox, const Box &dstBox) - { - // Implement? - } - //----------------------------------------------------------------------------------- - // blitFromMemory doing hardware trilinear scaling - void MetalTextureBuffer::blitFromMemory(const PixelBox &src_orig, const Box &dstBox) - { - // Fall back to normal MetalHardwarePixelBuffer::blitFromMemory in case - // - Either source or target is luminance due doesn't looks like supported by hardware - // - the source dimensions match the destination ones, in which case no scaling is needed - if(PixelUtil::isLuminance(src_orig.format) || - PixelUtil::isLuminance(mFormat) || - (src_orig.getWidth() == dstBox.getWidth() && - src_orig.getHeight() == dstBox.getHeight() && - src_orig.getDepth() == dstBox.getDepth())) - { - MetalHardwarePixelBuffer::blitFromMemory(src_orig, dstBox); - return; - } - if(!mBuffer.contains(dstBox)) - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Destination box out of range", - "MetalTextureBuffer::blitFromMemory"); - // For scoped deletion of conversion buffer - MemoryDataStreamPtr buf; - PixelBox src; - - // Create temporary texture to store source data - MTLTextureType target = (src.getDepth() != 1) ? MTLTextureType3D : MTLTextureType2D; - - int width = src.getWidth(); - int height = src.getHeight(); - int depth = src.getDepth(); - - // Metal texture buffer - MetalTextureBuffer tex( mTexture, 0, 0, BLANKSTRING, target, width, height, depth, - src.format, - 0, 0, (Usage)(TU_AUTOMIPMAP|HBU_STATIC_WRITE_ONLY), - src.format == mFormat ? mHwGamma : false, 0 ); - - // Upload data to 0,0,0 in temporary texture - Box tempTarget(0, 0, 0, src.getWidth(), src.getHeight(), src.getDepth()); - tex.upload(src, tempTarget); - - // Blit - blitFromTexture(&tex, tempTarget, dstBox); - } -} diff --git a/RenderSystems/Metal/src/OgreMetalMappings.mm b/RenderSystems/Metal/src/OgreMetalMappings.mm deleted file mode 100644 index 3c040258fd2..00000000000 --- a/RenderSystems/Metal/src/OgreMetalMappings.mm +++ /dev/null @@ -1,552 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2016 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreMetalMappings.h" -#include "OgreMetalDevice.h" - -namespace Ogre -{ - MTLPixelFormat MetalMappings::getPixelFormat( PixelFormat pf, bool isGamma ) - { - switch( pf ) - { - case PF_L8: return MTLPixelFormatR8Unorm; - case PF_L16: return MTLPixelFormatR16Unorm; - case PF_A8: return MTLPixelFormatA8Unorm; - case PF_BYTE_LA: return MTLPixelFormatInvalid; -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - case PF_R5G6B5: return MTLPixelFormatB5G6R5Unorm; - case PF_B5G6R5: return MTLPixelFormatB5G6R5Unorm; -#endif - case PF_R3G3B2: return MTLPixelFormatInvalid; -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - case PF_A4R4G4B4: return MTLPixelFormatABGR4Unorm; - case PF_A1R5G5B5: return MTLPixelFormatBGR5A1Unorm; -#endif - - case PF_X8R8G8B8: - case PF_A8R8G8B8: - case PF_B8G8R8A8: - return !isGamma ? MTLPixelFormatBGRA8Unorm : MTLPixelFormatBGRA8Unorm_sRGB; - - case PF_R8G8B8: - case PF_B8G8R8: - case PF_X8B8G8R8: - case PF_A8B8G8R8: - case PF_R8G8B8A8: - return !isGamma ? MTLPixelFormatRGBA8Unorm : MTLPixelFormatRGBA8Unorm_sRGB; - - case PF_A2R10G10B10: return MTLPixelFormatRGB10A2Unorm; - case PF_A2B10G10R10: return MTLPixelFormatRGB10A2Unorm; -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - case PF_DXT1: return !isGamma ? MTLPixelFormatBC1_RGBA : MTLPixelFormatBC1_RGBA_sRGB; - case PF_DXT2: return !isGamma ? MTLPixelFormatBC2_RGBA : MTLPixelFormatBC2_RGBA_sRGB; - case PF_DXT3: return !isGamma ? MTLPixelFormatBC2_RGBA : MTLPixelFormatBC2_RGBA_sRGB; - case PF_DXT4: return !isGamma ? MTLPixelFormatBC3_RGBA : MTLPixelFormatBC3_RGBA_sRGB; - case PF_DXT5: return !isGamma ? MTLPixelFormatBC3_RGBA : MTLPixelFormatBC3_RGBA_sRGB; -#endif - case PF_FLOAT16_R: return MTLPixelFormatR16Float; - case PF_FLOAT16_RGB: return MTLPixelFormatRGBA16Float; - case PF_FLOAT16_RGBA: return MTLPixelFormatRGBA16Float; - case PF_FLOAT32_R: return MTLPixelFormatR32Float; - case PF_FLOAT32_RGB: return MTLPixelFormatRGBA32Float; - case PF_FLOAT32_RGBA: return MTLPixelFormatRGBA32Float; - case PF_FLOAT16_GR: return MTLPixelFormatRG16Float; - case PF_FLOAT32_GR: return MTLPixelFormatRG32Float; - case PF_SHORT_RGBA: return MTLPixelFormatRGBA16Snorm; - case PF_SHORT_GR: return MTLPixelFormatRG16Snorm; - case PF_SHORT_RGB: return MTLPixelFormatRGBA16Snorm; -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - case PF_PVRTC_RGB2: return !isGamma ? MTLPixelFormatPVRTC_RGB_2BPP : MTLPixelFormatPVRTC_RGB_2BPP_sRGB; - case PF_PVRTC_RGBA2: return !isGamma ? MTLPixelFormatPVRTC_RGBA_2BPP : MTLPixelFormatPVRTC_RGBA_2BPP_sRGB; - case PF_PVRTC_RGB4: return !isGamma ? MTLPixelFormatPVRTC_RGB_4BPP : MTLPixelFormatPVRTC_RGB_4BPP_sRGB; - case PF_PVRTC_RGBA4: return !isGamma ? MTLPixelFormatPVRTC_RGBA_4BPP : MTLPixelFormatPVRTC_RGBA_4BPP_sRGB; -#endif - case PF_PVRTC2_2BPP: return MTLPixelFormatInvalid; - case PF_PVRTC2_4BPP: return MTLPixelFormatInvalid; - case PF_R11G11B10_FLOAT: return MTLPixelFormatRG11B10Float; - case PF_R8_UINT: return MTLPixelFormatR8Uint; - case PF_R8G8_UINT: return MTLPixelFormatRG8Uint; - case PF_R8G8B8_UINT: return MTLPixelFormatRGBA8Uint; - case PF_R8G8B8A8_UINT: return MTLPixelFormatRGBA8Uint; - case PF_R16_UINT: return MTLPixelFormatR16Uint; - case PF_R16G16_UINT: return MTLPixelFormatRG16Uint; - case PF_R16G16B16_UINT: return MTLPixelFormatRGBA16Uint; - case PF_R16G16B16A16_UINT: return MTLPixelFormatRGBA16Uint; - case PF_R32_UINT: return MTLPixelFormatR32Uint; - case PF_R32G32_UINT: return MTLPixelFormatRG32Uint; - case PF_R32G32B32_UINT: return MTLPixelFormatRGBA32Uint; - case PF_R32G32B32A32_UINT: return MTLPixelFormatRGBA32Uint; - case PF_R8_SINT: return MTLPixelFormatR8Sint; - case PF_R8G8_SINT: return MTLPixelFormatRG8Sint; - case PF_R8G8B8_SINT: return MTLPixelFormatRGBA8Sint; - case PF_R8G8B8A8_SINT: return MTLPixelFormatRGBA8Sint; - case PF_R16_SINT: return MTLPixelFormatR16Sint; - case PF_R16G16_SINT: return MTLPixelFormatRG16Sint; - case PF_R16G16B16_SINT: return MTLPixelFormatRGBA16Sint; - case PF_R16G16B16A16_SINT: return MTLPixelFormatRGBA16Sint; - case PF_R32_SINT: return MTLPixelFormatR32Sint; - case PF_R32G32_SINT: return MTLPixelFormatRG32Sint; - case PF_R32G32B32_SINT: return MTLPixelFormatRGBA32Sint; - case PF_R32G32B32A32_SINT: return MTLPixelFormatRGBA32Sint; - case PF_R9G9B9E5_SHAREDEXP: return MTLPixelFormatRGB9E5Float; -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - case PF_BC4_UNORM: return MTLPixelFormatBC4_RUnorm; - case PF_BC4_SNORM: return MTLPixelFormatBC4_RSnorm; - case PF_BC5_UNORM: return MTLPixelFormatBC5_RGUnorm; - case PF_BC5_SNORM: return MTLPixelFormatBC5_RGSnorm; - case PF_BC6H_UF16: return MTLPixelFormatBC6H_RGBUfloat; - case PF_BC6H_SF16: return MTLPixelFormatBC6H_RGBFloat; - case PF_BC7_UNORM: return MTLPixelFormatBC7_RGBAUnorm; -#endif -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - case PF_R8: return !isGamma ? MTLPixelFormatR8Unorm : MTLPixelFormatR8Unorm_sRGB; - case PF_RG8: return !isGamma ? MTLPixelFormatRG8Unorm : MTLPixelFormatRG8Unorm_sRGB; -#else - case PF_R8: return MTLPixelFormatR8Unorm; - case PF_RG8: return MTLPixelFormatRG8Unorm; -#endif - case PF_R8_SNORM: return MTLPixelFormatR8Snorm; - case PF_R8G8_SNORM: return MTLPixelFormatRG8Snorm; - case PF_R8G8B8_SNORM: return MTLPixelFormatRGBA8Snorm; - case PF_R8G8B8A8_SNORM: return MTLPixelFormatRGBA8Snorm; - case PF_R16_SNORM: return MTLPixelFormatR16Snorm; - case PF_R16G16_SNORM: return MTLPixelFormatRG16Snorm; - case PF_R16G16B16_SNORM: return MTLPixelFormatRGBA16Snorm; - case PF_R16G16B16A16_SNORM: return MTLPixelFormatRGBA16Snorm; -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - case PF_ETC1_RGB8: return !isGamma ? MTLPixelFormatETC2_RGB8 : MTLPixelFormatETC2_RGB8_sRGB; - case PF_ETC2_RGB8: return !isGamma ? MTLPixelFormatETC2_RGB8 : MTLPixelFormatETC2_RGB8_sRGB; - case PF_ETC2_RGBA8: return !isGamma ? MTLPixelFormatEAC_RGBA8 : MTLPixelFormatEAC_RGBA8_sRGB; - case PF_ETC2_RGB8A1: return !isGamma ? MTLPixelFormatETC2_RGB8A1 : MTLPixelFormatETC2_RGB8A1_sRGB; -#endif - case PF_ATC_RGB: return MTLPixelFormatInvalid; - case PF_ATC_RGBA_EXPLICIT_ALPHA: return MTLPixelFormatInvalid; - case PF_ATC_RGBA_INTERPOLATED_ALPHA: return MTLPixelFormatInvalid; - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - case PF_ASTC_RGBA_4X4_LDR: return MTLPixelFormatASTC_4x4_LDR; - case PF_ASTC_RGBA_5X4_LDR: return MTLPixelFormatASTC_5x4_LDR; - case PF_ASTC_RGBA_5X5_LDR: return MTLPixelFormatASTC_5x5_LDR; - case PF_ASTC_RGBA_6X5_LDR: return MTLPixelFormatASTC_6x5_LDR; - case PF_ASTC_RGBA_6X6_LDR: return MTLPixelFormatASTC_6x6_LDR; - case PF_ASTC_RGBA_8X5_LDR: return MTLPixelFormatASTC_8x5_LDR; - case PF_ASTC_RGBA_8X6_LDR: return MTLPixelFormatASTC_8x6_LDR; - case PF_ASTC_RGBA_8X8_LDR: return MTLPixelFormatASTC_8x8_LDR; - case PF_ASTC_RGBA_10X5_LDR: return MTLPixelFormatASTC_10x5_LDR; - case PF_ASTC_RGBA_10X6_LDR: return MTLPixelFormatASTC_10x6_LDR; - case PF_ASTC_RGBA_10X8_LDR: return MTLPixelFormatASTC_10x8_LDR; - case PF_ASTC_RGBA_10X10_LDR: return MTLPixelFormatASTC_10x10_LDR; - case PF_ASTC_RGBA_12X10_LDR: return MTLPixelFormatASTC_12x10_LDR; - case PF_ASTC_RGBA_12X12_LDR: return MTLPixelFormatASTC_12x12_LDR; -#endif - -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - case PF_DEPTH24_STENCIL8: return MTLPixelFormatDepth24Unorm_Stencil8; -#else - case PF_DEPTH24_STENCIL8: return MTLPixelFormatDepth32Float_Stencil8; -#endif -#if 0 - case PF_X24_S8_UINT: return MTLPixelFormatStencil8; -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - case PF_D24_UNORM: return MTLPixelFormatDepth24Unorm_Stencil8; -#else - case PF_D24_UNORM: return MTLPixelFormatDepth32Float; -#endif - case PF_D32_FLOAT_X24_S8_UINT: return MTLPixelFormatDepth32Float_Stencil8; - case PF_D32_FLOAT_X24_X8: return MTLPixelFormatDepth32Float_Stencil8; - case PF_X32_X24_S8_UINT: return MTLPixelFormatStencil8; -#endif - - case PF_DEPTH16: return MTLPixelFormatDepth32Float; - case PF_DEPTH32: return MTLPixelFormatDepth32Float; - case PF_DEPTH32F: return MTLPixelFormatDepth32Float; - - default: - case PF_COUNT: return MTLPixelFormatInvalid; - } - } - //----------------------------------------------------------------------------------- - void MetalMappings::getDepthStencilFormat( MetalDevice *device, PixelFormat pf, - MTLPixelFormat &outDepth, MTLPixelFormat &outStencil ) - { - MTLPixelFormat depthFormat = MTLPixelFormatInvalid; - MTLPixelFormat stencilFormat = MTLPixelFormatInvalid; - - switch( pf ) - { - case PF_DEPTH24_STENCIL8: -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - depthFormat = MTLPixelFormatDepth32Float; - stencilFormat = MTLPixelFormatStencil8; -#else - if( device->mDevice.depth24Stencil8PixelFormatSupported ) - { - depthFormat = MTLPixelFormatDepth24Unorm_Stencil8; - stencilFormat = MTLPixelFormatDepth24Unorm_Stencil8; - } - else - { - depthFormat = MTLPixelFormatDepth32Float_Stencil8; - stencilFormat = MTLPixelFormatDepth32Float_Stencil8; - } -#endif - // keep stencil off for now - stencilFormat = MTLPixelFormatInvalid; - break; -#if 0 - case PF_D32_FLOAT: - case PF_D32_FLOAT_X24_X8: - depthFormat = MTLPixelFormatDepth32Float; - break; - case PF_D32_FLOAT_X24_S8_UINT: -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - depthFormat = MTLPixelFormatDepth32Float; - stencilFormat = MTLPixelFormatStencil8; -#else - depthFormat = MTLPixelFormatDepth32Float_Stencil8; - stencilFormat = MTLPixelFormatDepth32Float_Stencil8; -#endif - break; - case PF_X32_X24_S8_UINT: - stencilFormat = MTLPixelFormatStencil8; - break; -#endif - case PF_DEPTH16: - case PF_DEPTH32: - case PF_DEPTH32F: - depthFormat = MTLPixelFormatDepth32Float; - break; - default: - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "PixelFormat '" + PixelUtil::getFormatName( pf ) + - "' is not a valid depth buffer format", - "MetalRenderSystem::_createDepthBufferFor" ); - } - - outDepth = depthFormat; - outStencil = stencilFormat; - } - //----------------------------------------------------------------------------------- - MTLBlendFactor MetalMappings::get( SceneBlendFactor op ) - { - switch( op ) - { - case SBF_ONE: return MTLBlendFactorOne; - case SBF_ZERO: return MTLBlendFactorZero; - case SBF_DEST_COLOUR: return MTLBlendFactorDestinationColor; - case SBF_SOURCE_COLOUR: return MTLBlendFactorSourceColor; - case SBF_ONE_MINUS_DEST_COLOUR: return MTLBlendFactorOneMinusDestinationColor; - case SBF_ONE_MINUS_SOURCE_COLOUR:return MTLBlendFactorOneMinusSourceColor; - case SBF_DEST_ALPHA: return MTLBlendFactorDestinationAlpha; - case SBF_SOURCE_ALPHA: return MTLBlendFactorSourceAlpha; - case SBF_ONE_MINUS_DEST_ALPHA: return MTLBlendFactorOneMinusDestinationAlpha; - case SBF_ONE_MINUS_SOURCE_ALPHA:return MTLBlendFactorOneMinusSourceAlpha; - } - } - //----------------------------------------------------------------------------------- - MTLBlendOperation MetalMappings::get( SceneBlendOperation op ) - { - switch( op ) - { - case SBO_ADD: return MTLBlendOperationAdd; - case SBO_SUBTRACT: return MTLBlendOperationSubtract; - case SBO_REVERSE_SUBTRACT: return MTLBlendOperationReverseSubtract; - case SBO_MIN: return MTLBlendOperationMin; - case SBO_MAX: return MTLBlendOperationMax; - } - } - //----------------------------------------------------------------------------------- - MTLStencilOperation MetalMappings::get( StencilOperation op ) - { - switch( op ) - { - case SOP_KEEP: return MTLStencilOperationKeep; - case SOP_ZERO: return MTLStencilOperationZero; - case SOP_REPLACE: return MTLStencilOperationReplace; - case SOP_INCREMENT: return MTLStencilOperationIncrementClamp; - case SOP_DECREMENT: return MTLStencilOperationDecrementClamp; - case SOP_INCREMENT_WRAP: return MTLStencilOperationIncrementWrap; - case SOP_DECREMENT_WRAP: return MTLStencilOperationDecrementWrap; - case SOP_INVERT: return MTLStencilOperationInvert; - } - } - //----------------------------------------------------------------------------------- - MTLCompareFunction MetalMappings::get( CompareFunction cmp ) - { - switch( cmp ) - { - case CMPF_ALWAYS_FAIL: return MTLCompareFunctionNever; - case CMPF_ALWAYS_PASS: return MTLCompareFunctionAlways; - case CMPF_LESS: return MTLCompareFunctionLess; - case CMPF_LESS_EQUAL: return MTLCompareFunctionLessEqual; - case CMPF_EQUAL: return MTLCompareFunctionEqual; - case CMPF_NOT_EQUAL: return MTLCompareFunctionNotEqual; - case CMPF_GREATER_EQUAL: return MTLCompareFunctionGreaterEqual; - case CMPF_GREATER: return MTLCompareFunctionGreater; - } - } - //----------------------------------------------------------------------------------- - MTLVertexFormat MetalMappings::get( VertexElementType vertexElemType ) - { - switch( vertexElemType ) - { - case VET_FLOAT1: return MTLVertexFormatFloat; - case VET_FLOAT2: return MTLVertexFormatFloat2; - case VET_FLOAT3: return MTLVertexFormatFloat3; - case VET_FLOAT4: return MTLVertexFormatFloat4; - case VET_SHORT2: return MTLVertexFormatShort2; - case VET_SHORT4: return MTLVertexFormatShort4; - case VET_UBYTE4: return MTLVertexFormatUChar4; - case VET_USHORT2: return MTLVertexFormatUShort2; - case VET_USHORT4: return MTLVertexFormatUShort4; - case VET_INT1: return MTLVertexFormatInt; - case VET_INT2: return MTLVertexFormatInt2; - case VET_INT3: return MTLVertexFormatInt3; - case VET_INT4: return MTLVertexFormatInt4; - case VET_UINT1: return MTLVertexFormatUInt; - case VET_UINT2: return MTLVertexFormatUInt2; - case VET_UINT3: return MTLVertexFormatUInt3; - case VET_UINT4: return MTLVertexFormatUInt4; - case VET_BYTE4: return MTLVertexFormatChar4; - //case VET_BYTE4_SNORM: return MTLVertexFormatChar4Normalized; - case VET_UBYTE4_NORM: return MTLVertexFormatUChar4Normalized; - //case VET_SHORT2_SNORM: return MTLVertexFormatShort2Normalized; - //case VET_SHORT4_SNORM: return MTLVertexFormatShort4Normalized; - case VET_USHORT2_NORM: return MTLVertexFormatUShort2Normalized; - case VET_USHORT4_NORM: return MTLVertexFormatUShort4Normalized; - //case VET_HALF2: return MTLVertexFormatHalf2; - //case VET_HALF4: return MTLVertexFormatHalf4; - case VET_INT_10_10_10_2_NORM: return MTLVertexFormatInt1010102Normalized; - - case VET_DOUBLE1: - case VET_DOUBLE2: - case VET_DOUBLE3: - case VET_DOUBLE4: - case VET_USHORT1: - case VET_USHORT3: - default: - return MTLVertexFormatInvalid; - } - } - //----------------------------------------------------------------------------------- - MTLSamplerMinMagFilter MetalMappings::get( FilterOptions filter ) - { - switch( filter ) - { - case FO_NONE: return MTLSamplerMinMagFilterNearest; - case FO_POINT: return MTLSamplerMinMagFilterNearest; - case FO_LINEAR: return MTLSamplerMinMagFilterLinear; - case FO_ANISOTROPIC: return MTLSamplerMinMagFilterLinear; - } - } - //----------------------------------------------------------------------------------- - MTLSamplerMipFilter MetalMappings::getMipFilter( FilterOptions filter ) - { - switch( filter ) - { - case FO_NONE: return MTLSamplerMipFilterNotMipmapped; - case FO_POINT: return MTLSamplerMipFilterNearest; - case FO_LINEAR: return MTLSamplerMipFilterLinear; - case FO_ANISOTROPIC: return MTLSamplerMipFilterLinear; - } - } - //----------------------------------------------------------------------------------- - MTLSamplerAddressMode MetalMappings::get( TextureAddressingMode mode ) - { - switch( mode ) - { - case TAM_WRAP: return MTLSamplerAddressModeRepeat; - case TAM_MIRROR: return MTLSamplerAddressModeMirrorRepeat; - case TAM_CLAMP: return MTLSamplerAddressModeClampToEdge; - //Not supported. Get the best next thing. - case TAM_BORDER: return MTLSamplerAddressModeClampToEdge; - default: return MTLSamplerAddressModeClampToEdge; - } - } - //----------------------------------------------------------------------------------- - MTLVertexFormat MetalMappings::dataTypeToVertexFormat( MTLDataType dataType ) - { - switch( dataType ) - { - case MTLDataTypeNone: return MTLVertexFormatInvalid; - case MTLDataTypeStruct: return MTLVertexFormatInvalid; - case MTLDataTypeArray: return MTLVertexFormatInvalid; - - case MTLDataTypeFloat: return MTLVertexFormatFloat; - case MTLDataTypeFloat2: return MTLVertexFormatFloat2; - case MTLDataTypeFloat3: return MTLVertexFormatFloat3; - case MTLDataTypeFloat4: return MTLVertexFormatFloat4; - - case MTLDataTypeFloat2x2: return MTLVertexFormatInvalid; - case MTLDataTypeFloat2x3: return MTLVertexFormatInvalid; - case MTLDataTypeFloat2x4: return MTLVertexFormatInvalid; - - case MTLDataTypeFloat3x2: return MTLVertexFormatInvalid; - case MTLDataTypeFloat3x3: return MTLVertexFormatInvalid; - case MTLDataTypeFloat3x4: return MTLVertexFormatInvalid; - - case MTLDataTypeFloat4x2: return MTLVertexFormatInvalid; - case MTLDataTypeFloat4x3: return MTLVertexFormatInvalid; - case MTLDataTypeFloat4x4: return MTLVertexFormatInvalid; - - case MTLDataTypeHalf: return MTLVertexFormatHalf2; - case MTLDataTypeHalf2: return MTLVertexFormatHalf2; - case MTLDataTypeHalf3: return MTLVertexFormatHalf3; - case MTLDataTypeHalf4: return MTLVertexFormatHalf4; - - case MTLDataTypeHalf2x2: return MTLVertexFormatInvalid; - case MTLDataTypeHalf2x3: return MTLVertexFormatInvalid; - case MTLDataTypeHalf2x4: return MTLVertexFormatInvalid; - - case MTLDataTypeHalf3x2: return MTLVertexFormatInvalid; - case MTLDataTypeHalf3x3: return MTLVertexFormatInvalid; - case MTLDataTypeHalf3x4: return MTLVertexFormatInvalid; - - case MTLDataTypeHalf4x2: return MTLVertexFormatInvalid; - case MTLDataTypeHalf4x3: return MTLVertexFormatInvalid; - case MTLDataTypeHalf4x4: return MTLVertexFormatInvalid; - - case MTLDataTypeInt: return MTLVertexFormatInt; - case MTLDataTypeInt2: return MTLVertexFormatInt2; - case MTLDataTypeInt3: return MTLVertexFormatInt3; - case MTLDataTypeInt4: return MTLVertexFormatInt4; - - case MTLDataTypeUInt: return MTLVertexFormatUInt; - case MTLDataTypeUInt2: return MTLVertexFormatUInt2; - case MTLDataTypeUInt3: return MTLVertexFormatUInt3; - case MTLDataTypeUInt4: return MTLVertexFormatUInt4; - - case MTLDataTypeShort: return MTLVertexFormatShort2; - case MTLDataTypeShort2: return MTLVertexFormatShort2; - case MTLDataTypeShort3: return MTLVertexFormatShort3; - case MTLDataTypeShort4: return MTLVertexFormatShort4; - - case MTLDataTypeUShort: return MTLVertexFormatUShort2; - case MTLDataTypeUShort2: return MTLVertexFormatUShort2; - case MTLDataTypeUShort3: return MTLVertexFormatUShort3; - case MTLDataTypeUShort4: return MTLVertexFormatUShort4; - - case MTLDataTypeChar: return MTLVertexFormatChar2; - case MTLDataTypeChar2: return MTLVertexFormatChar2; - case MTLDataTypeChar3: return MTLVertexFormatChar3; - case MTLDataTypeChar4: return MTLVertexFormatChar4; - - case MTLDataTypeUChar: return MTLVertexFormatUChar2; - case MTLDataTypeUChar2: return MTLVertexFormatUChar2; - case MTLDataTypeUChar3: return MTLVertexFormatUChar3; - case MTLDataTypeUChar4: return MTLVertexFormatUChar4; - - case MTLDataTypeBool: return MTLVertexFormatFloat; - case MTLDataTypeBool2: return MTLVertexFormatFloat2; - case MTLDataTypeBool3: return MTLVertexFormatFloat3; - case MTLDataTypeBool4: return MTLVertexFormatFloat4; - default: OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "unhandled case"); - } - } - //----------------------------------------------------------------------------------- - GpuConstantType MetalMappings::get( MTLDataType dataType ) - { - switch( dataType ) - { - case MTLDataTypeNone: return GCT_UNKNOWN; - case MTLDataTypeStruct: return GCT_UNKNOWN; - case MTLDataTypeArray: return GCT_UNKNOWN; - - case MTLDataTypeFloat: return GCT_FLOAT1; - case MTLDataTypeFloat2: return GCT_FLOAT2; - case MTLDataTypeFloat3: return GCT_FLOAT3; - case MTLDataTypeFloat4: return GCT_FLOAT4; - - case MTLDataTypeFloat2x2: return GCT_MATRIX_2X2; - case MTLDataTypeFloat2x3: return GCT_MATRIX_2X3; - case MTLDataTypeFloat2x4: return GCT_MATRIX_2X4; - - case MTLDataTypeFloat3x2: return GCT_MATRIX_3X2; - case MTLDataTypeFloat3x3: return GCT_MATRIX_3X3; - case MTLDataTypeFloat3x4: return GCT_MATRIX_3X4; - - case MTLDataTypeFloat4x2: return GCT_MATRIX_4X2; - case MTLDataTypeFloat4x3: return GCT_MATRIX_4X3; - case MTLDataTypeFloat4x4: return GCT_MATRIX_4X4; - - case MTLDataTypeHalf: return GCT_UNKNOWN; - case MTLDataTypeHalf2: return GCT_UNKNOWN; - case MTLDataTypeHalf3: return GCT_UNKNOWN; - case MTLDataTypeHalf4: return GCT_UNKNOWN; - - case MTLDataTypeHalf2x2: return GCT_UNKNOWN; - case MTLDataTypeHalf2x3: return GCT_UNKNOWN; - case MTLDataTypeHalf2x4: return GCT_UNKNOWN; - - case MTLDataTypeHalf3x2: return GCT_UNKNOWN; - case MTLDataTypeHalf3x3: return GCT_UNKNOWN; - case MTLDataTypeHalf3x4: return GCT_UNKNOWN; - - case MTLDataTypeHalf4x2: return GCT_UNKNOWN; - case MTLDataTypeHalf4x3: return GCT_UNKNOWN; - case MTLDataTypeHalf4x4: return GCT_UNKNOWN; - - case MTLDataTypeInt: return GCT_INT1; - case MTLDataTypeInt2: return GCT_INT2; - case MTLDataTypeInt3: return GCT_INT3; - case MTLDataTypeInt4: return GCT_INT4; - - case MTLDataTypeUInt: return GCT_UINT1; - case MTLDataTypeUInt2: return GCT_UINT2; - case MTLDataTypeUInt3: return GCT_UINT3; - case MTLDataTypeUInt4: return GCT_UINT4; - - case MTLDataTypeShort: return GCT_UNKNOWN; - case MTLDataTypeShort2: return GCT_UNKNOWN; - case MTLDataTypeShort3: return GCT_UNKNOWN; - case MTLDataTypeShort4: return GCT_UNKNOWN; - - case MTLDataTypeUShort: return GCT_UNKNOWN; - case MTLDataTypeUShort2: return GCT_UNKNOWN; - case MTLDataTypeUShort3: return GCT_UNKNOWN; - case MTLDataTypeUShort4: return GCT_UNKNOWN; - - case MTLDataTypeChar: return GCT_UNKNOWN; - case MTLDataTypeChar2: return GCT_UNKNOWN; - case MTLDataTypeChar3: return GCT_UNKNOWN; - case MTLDataTypeChar4: return GCT_UNKNOWN; - - case MTLDataTypeUChar: return GCT_UNKNOWN; - case MTLDataTypeUChar2: return GCT_UNKNOWN; - case MTLDataTypeUChar3: return GCT_UNKNOWN; - case MTLDataTypeUChar4: return GCT_UNKNOWN; - - case MTLDataTypeBool: return GCT_BOOL1; - case MTLDataTypeBool2: return GCT_BOOL2; - case MTLDataTypeBool3: return GCT_BOOL3; - case MTLDataTypeBool4: return GCT_BOOL4; - default: OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "unhandled case"); - } - } -} diff --git a/RenderSystems/Metal/src/OgreMetalMultiRenderTarget.mm b/RenderSystems/Metal/src/OgreMetalMultiRenderTarget.mm deleted file mode 100644 index bd2e677ea20..00000000000 --- a/RenderSystems/Metal/src/OgreMetalMultiRenderTarget.mm +++ /dev/null @@ -1,112 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2017 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreMetalMultiRenderTarget.h" -#include "OgreMetalRenderTexture.h" - -#include "OgreException.h" - -namespace Ogre -{ - MetalMultiRenderTarget::MetalMultiRenderTarget( const String &name ) : - MultiRenderTarget( name ), - mNumMRTs( 0 ) - { - memset( mMetalRenderTargetCommon, 0, sizeof(mMetalRenderTargetCommon) ); - - mWidth = 0; - mHeight = 0; - mFSAA = 1u; - } - //----------------------------------------------------------------------------------- - MetalMultiRenderTarget::~MetalMultiRenderTarget() - { - } - //----------------------------------------------------------------------------------- - void MetalMultiRenderTarget::bindSurfaceImpl( size_t attachment, RenderTexture *target ) - { - assert( attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS ); - assert( mNumMRTs < OGRE_MAX_MULTIPLE_RENDER_TARGETS && - "Reached max number of attachments!" ); - assert( !mMetalRenderTargetCommon[attachment] && - "RTT already attached at this slot! " - "You must call MultiRenderTarget::unbindSurface first!" ); - - if( mWidth ) - { - if( mWidth != target->getWidth() && mHeight != target->getHeight() && - mFSAA != target->getFSAA() ) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "MultiRenderTarget surfaces are not of same size", - "MetalMultiRenderTarget::bindSurface" ); - } - } - - mWidth = target->getWidth(); - mHeight = target->getHeight(); - mFSAA = target->getFSAA(); - - assert( dynamic_cast( target ) ); - MetalRenderTexture *metalRtt = static_cast( target ); - - mMetalRenderTargetCommon[attachment] = metalRtt; - ++mNumMRTs; - } - //----------------------------------------------------------------------------------- - void MetalMultiRenderTarget::unbindSurfaceImpl( size_t attachment ) - { - assert( attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS ); - - if( mMetalRenderTargetCommon[attachment] ) - { - mMetalRenderTargetCommon[attachment] = 0; - --mNumMRTs; - - if( !mNumMRTs ) - { - mWidth = 0; - mHeight = 0; - mFSAA = 1u; - } - } - } - //----------------------------------------------------------------------------------- - void MetalMultiRenderTarget::getCustomAttribute( const String& name, void *pData ) - { - if( name == "mNumMRTs" ) - { - *static_cast(pData) = mNumMRTs; - } - else - { - MultiRenderTarget::getCustomAttribute( name, pData ); - } - } - //----------------------------------------------------------------------------------- -} diff --git a/RenderSystems/Metal/src/OgreMetalPlugin.mm b/RenderSystems/Metal/src/OgreMetalPlugin.mm deleted file mode 100644 index b69244a5849..00000000000 --- a/RenderSystems/Metal/src/OgreMetalPlugin.mm +++ /dev/null @@ -1,73 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2016 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreMetalPlugin.h" -#include "OgreMetalRenderSystem.h" -#include "OgreRoot.h" - -#if !__has_feature( objc_arc ) - #error "ARC is off!!!" -#endif - -namespace Ogre -{ - const String sPluginName = "Metal RenderSystem"; - //--------------------------------------------------------------------- - MetalPlugin::MetalPlugin() - : mRenderSystem(0) - { - } - //--------------------------------------------------------------------- - const String& MetalPlugin::getName() const - { - return sPluginName; - } - //--------------------------------------------------------------------- - void MetalPlugin::install() - { - mRenderSystem = OGRE_NEW MetalRenderSystem(); - - Root::getSingleton().addRenderSystem(mRenderSystem); - } - //--------------------------------------------------------------------- - void MetalPlugin::initialise() - { - // nothing to do - } - //--------------------------------------------------------------------- - void MetalPlugin::shutdown() - { - // nothing to do - } - //--------------------------------------------------------------------- - void MetalPlugin::uninstall() - { - OGRE_DELETE mRenderSystem; - mRenderSystem = 0; - } -} diff --git a/RenderSystems/Metal/src/OgreMetalProgram.mm b/RenderSystems/Metal/src/OgreMetalProgram.mm deleted file mode 100644 index 727f3e1c1df..00000000000 --- a/RenderSystems/Metal/src/OgreMetalProgram.mm +++ /dev/null @@ -1,471 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2016 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreMetalProgram.h" -#include "OgreLogManager.h" -#include "OgreMetalDevice.h" -#include "OgreMetalMappings.h" -#include "OgreGpuProgramManager.h" - -#import -#import -#import - -namespace Ogre { - static const uint32 VERTEX_ATTRIBUTE_INDEX[VES_COUNT] = - { - 0, // VES_POSITION - 1 - 1, // VES_BLEND_WEIGHTS - 1 - 7, // VES_BLEND_INDICES - 1 - 2, // VES_NORMAL - 1 - 3, // VES_DIFFUSE - 1 - 4, // VES_SPECULAR - 1 - 8, // VES_TEXTURE_COORDINATES - 1 - //There are up to 8 VES_TEXTURE_COORDINATES. Occupy range [8; 16) - //Range [14; 16) overlaps with VES_TANGENT & VES_BINORMAL - //(slot 16 is where const buffers start) - 15,// VES_BINORMAL - 1 - 14, // VES_TANGENT - 1 - }; - - uint32 MetalProgram::getAttributeIndex(VertexElementSemantic semantic) - { - return VERTEX_ATTRIBUTE_INDEX[semantic - 1]; - } - - //----------------------------------------------------------------------- - MetalProgram::CmdShaderReflectionPairHint MetalProgram::msCmdShaderReflectionPairHint; - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - MetalProgram::MetalProgram( ResourceManager* creator, const String& name, - ResourceHandle handle, const String& group, - bool isManual, ManualResourceLoader* loader, - MetalDevice *device ) : - HighLevelGpuProgram(creator, name, handle, group, isManual, loader), - mLibrary( nil ), - mFunction( nil ), - mDevice( device ), - mCompiled( false ) - { - if (createParamDictionary("MetalProgram")) - { - setupBaseParamDictionary(); - ParamDictionary* dict = getParamDictionary(); - - dict->addParameter(ParameterDef("shader_reflection_pair_hint", - "Metal requires Pixel Shaders to be paired with a valid " - "vertex shader to obtain reflection data (i.e. program " - "parameters). Pixel Shaders without parameters don't need " - "this. Pass the name of an already defined vertex shader.", - PT_STRING),&msCmdShaderReflectionPairHint); - } - mTargetBufferName = ""; - mEntryPoint = "mainfunc"; // 1.4.4: A Metal function cannot be called main. - } - //--------------------------------------------------------------------------- - MetalProgram::~MetalProgram() - { - mLibrary = nil; - mFunction = nil; - - // Have to call this here reather than in Resource destructor - // since calling virtual methods in base destructors causes crash - if (isLoaded()) - { - unload(); - } - else - { - unloadHighLevel(); - } - } - //----------------------------------------------------------------------- - void MetalProgram::loadFromSource(void) - { - compile( true ); - } - //----------------------------------------------------------------------- - void MetalProgram::parsePreprocessorDefinitions( NSMutableDictionary *inOutMacros ) - { - String defines = appendBuiltinDefines(mPreprocessorDefines); - for(auto def : parseDefines(defines)) - { - NSString *key = [NSString stringWithUTF8String:def.first]; - NSString *value = [NSString stringWithUTF8String:def.second]; - inOutMacros[key] = value; - } - } - //----------------------------------------------------------------------- - bool MetalProgram::compile(const bool checkErrors) - { - mCompileError = true; //Set to true until we've confirmed otherwise. - - //Send fixed vertex attributes as macros/definitions. - MTLCompileOptions *options = [[MTLCompileOptions alloc] init]; - NSMutableDictionary *preprocessorMacros = - [NSMutableDictionary dictionary]; - - parsePreprocessorDefinitions( preprocessorMacros ); - - options.preprocessorMacros = preprocessorMacros; - - // metal does not support runtime #includes. Also we want to use our Resource system - mSource = _resolveIncludes(mSource, this, mFilename, true); - - NSError *error; - mLibrary = [mDevice->mDevice newLibraryWithSource:[NSString stringWithUTF8String:mSource.c_str()] - options:options - error:&error]; - - if( !mLibrary && checkErrors ) - { - String errorDesc; - if( error ) - errorDesc = [error localizedDescription].UTF8String; - - LogManager::getSingleton().logError( - "Metal Compiler in " + mName + ":\n" + errorDesc ); - } - else - { - mCompiled = true; - - if( error ) - { - String errorDesc; - if( error ) - errorDesc = [error localizedDescription].UTF8String; - LogManager::getSingleton().logWarning( - "Metal SL Compiler in " + mName + ":\n" + errorDesc ); - } - } - - mLibrary.label = [NSString stringWithUTF8String:mName.c_str()]; - - mFunction = [mLibrary newFunctionWithName:[NSString stringWithUTF8String:mEntryPoint.c_str()]]; - if( !mFunction ) - { - mCompiled = false; - LogManager::getSingleton().logError( - "retriving entry point '" + mEntryPoint + "' in shader " + mName ); - } - - // Log a message that the shader compiled successfully. - if( mCompiled && checkErrors ) - LogManager::getSingleton().logMessage( "Shader " + mName + " compiled successfully." ); - - mCompileError = !mCompiled; - - if( !mCompiled ) - { - OGRE_EXCEPT( Exception::ERR_RENDERINGAPI_ERROR, - ((mType == GPT_VERTEX_PROGRAM) ? "Vertex Program " : "Fragment Program ") + - mName + " failed to compile. See compile log above for details.", - "MetalProgram::compile" ); - } - - return mCompiled; - } - - //----------------------------------------------------------------------- - void MetalProgram::autoFillDummyVertexAttributesForShader( id vertexFunction, - MTLRenderPipelineDescriptor *psd ) - { - if( [vertexFunction.vertexAttributes count] ) - { - size_t maxSize = 0; - MTLVertexDescriptor *vertexDescriptor = [MTLVertexDescriptor vertexDescriptor]; - - for( MTLVertexAttribute *vertexAttribute in vertexFunction.vertexAttributes ) - { - const size_t elementIdx = vertexAttribute.attributeIndex; - vertexDescriptor.attributes[elementIdx].format = - MetalMappings::dataTypeToVertexFormat( vertexAttribute.attributeType ); - vertexDescriptor.attributes[elementIdx].bufferIndex = 0; - vertexDescriptor.attributes[elementIdx].offset = elementIdx * 16u; - - maxSize = std::max( maxSize, elementIdx * 16u ); - } - - vertexDescriptor.layouts[0].stride = maxSize + 16u; - vertexDescriptor.layouts[0].stepFunction = MTLVertexStepFunctionPerVertex; - - [psd setVertexDescriptor:vertexDescriptor]; - } - } - //----------------------------------------------------------------------- - void MetalProgram::analyzeComputeParameters(void) - { - MTLAutoreleasedComputePipelineReflection reflection = 0; - NSError* error = 0; - id metalFunction = this->getMetalFunction(); - id pso = - [mDevice->mDevice newComputePipelineStateWithFunction:metalFunction - options:MTLPipelineOptionBufferTypeInfo - reflection:&reflection - error:&error]; - if( !pso || error ) - { - String errorDesc; - if( error ) - errorDesc = [error localizedDescription].UTF8String; - - OGRE_EXCEPT( Exception::ERR_RENDERINGAPI_ERROR, - "Failed to create pipeline state for reflection, error " + - errorDesc, "MetalProgram::analyzeComputeParameters" ); - } - else - { - createParameterMappingStructures( true ); - NSArray *arguments = reflection.arguments; - - for( MTLArgument *arg in arguments ) - { - if( arg.type == MTLArgumentTypeBuffer && arg.index >= UNIFORM_INDEX_START ) - analyzeParameterBuffer( arg ); - } - } - } - //----------------------------------------------------------------------- - void MetalProgram::analyzeRenderParameters(void) - { - MTLRenderPipelineDescriptor *psd = [[MTLRenderPipelineDescriptor alloc] init]; - //[psd setSampleCount: 1]; - - switch( mType ) - { - case GPT_VERTEX_PROGRAM: - { - id metalFunction = this->getMetalFunction(); - [psd setVertexFunction:metalFunction]; - autoFillDummyVertexAttributesForShader( metalFunction, psd ); - break; - } - case GPT_FRAGMENT_PROGRAM: - { - GpuProgramPtr shader = GpuProgramManager::getSingleton(). - getByName( mShaderReflectionPairHint ); - if( !shader ) - { - OGRE_EXCEPT( Exception::ERR_ITEM_NOT_FOUND, - "Shader reflection hint '" + mShaderReflectionPairHint + - "' not found for pixel shader '" + mName + "'", - "MetalProgram::analyzeRenderParameters" ); - } - if( shader->getType() != GPT_VERTEX_PROGRAM ) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "Shader reflection hint '" + mShaderReflectionPairHint + - "' for pixel shader '" + mName + "' must be a vertex shader.", - "MetalProgram::analyzeRenderParameters" ); - } - shader->load(); - - if(shader->hasCompileError()) - return; - - assert( dynamic_cast( shader->_getBindingDelegate() ) ); - MetalProgram *vertexShader = static_cast( shader->_getBindingDelegate() ); - autoFillDummyVertexAttributesForShader( vertexShader->getMetalFunction(), psd ); - [psd setVertexFunction:vertexShader->getMetalFunction()]; - [psd setFragmentFunction:this->getMetalFunction()]; - break; - } - default: - OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, "", "MetalProgram::analyzeRenderParameters" ); - } - - psd.depthAttachmentPixelFormat = MTLPixelFormatDepth32Float; - - MTLAutoreleasedRenderPipelineReflection reflection = 0; - NSError* error = 0; - id pso = - [mDevice->mDevice newRenderPipelineStateWithDescriptor:psd - options:MTLPipelineOptionBufferTypeInfo reflection:&reflection error:&error]; - - if( !pso || error ) - { - String errorDesc; - if( error ) - errorDesc = [error localizedDescription].UTF8String; - - OGRE_EXCEPT( Exception::ERR_RENDERINGAPI_ERROR, - "Failed to create pipeline state for reflection, error " + - errorDesc, "MetalProgram::analyzeRenderParameters" ); - } - else - { - createParameterMappingStructures( true ); - NSArray *arguments = - mType == GPT_VERTEX_PROGRAM ? reflection.vertexArguments : - reflection.fragmentArguments; - - for( MTLArgument *arg in arguments ) - { - if( arg.type == MTLArgumentTypeBuffer && arg.index >= UNIFORM_INDEX_START ) - analyzeParameterBuffer( arg ); - } - } - } - //----------------------------------------------------------------------- - void MetalProgram::analyzeParameterBuffer( MTLArgument *arg ) - { - if( arg.bufferDataSize == 0 ) - return; - - { - //Check if not a struct (i.e. a pointer to a basic type, like a float4x4*) - GpuConstantType ogreType = MetalMappings::get( arg.bufferDataType ); - if( ogreType != GCT_UNKNOWN ) - { - GpuConstantDefinition def; - def.constType = ogreType; - def.logicalIndex = 0; - def.physicalIndex = 0; - def.elementSize = GpuConstantDefinition::getElementSize(def.constType, false); - def.arraySize = 1; - def.variability = GPV_GLOBAL; - - def.physicalIndex = mLogicalToPhysical->bufferSize*4; - OGRE_LOCK_MUTEX(mLogicalToPhysical->mutex); - mLogicalToPhysical->map.insert( - GpuLogicalIndexUseMap::value_type(def.logicalIndex, - GpuLogicalIndexUse(def.physicalIndex, - def.arraySize * def.elementSize, GPV_GLOBAL, BCT_UNKNOWN))); - mLogicalToPhysical->bufferSize += def.arraySize * def.elementSize; - mConstantDefs->bufferSize = mLogicalToPhysical->bufferSize; - - String varName = arg.name.UTF8String; - - mConstantDefs->map.insert( GpuConstantDefinitionMap::value_type( varName, def ) ); - } - } - - for( MTLStructMember *member in arg.bufferStructType.members ) - { - GpuConstantType ogreType; - - if( member.dataType == MTLDataTypeArray ) - ogreType = MetalMappings::get( member.arrayType.elementType ); - else - ogreType = MetalMappings::get( member.dataType ); - - if( ogreType != GCT_UNKNOWN ) - { - GpuConstantDefinition def; - def.constType = ogreType; - def.logicalIndex = member.offset; - def.physicalIndex = member.offset; - if( member.dataType == MTLDataTypeArray ) - { - def.elementSize = member.arrayType.stride / sizeof(float); - def.arraySize = member.arrayType.arrayLength; - } - else - { - def.elementSize = GpuConstantDefinition::getElementSize(def.constType, false); - def.arraySize = 1; - } - def.variability = GPV_GLOBAL; - - OGRE_LOCK_MUTEX(mLogicalToPhysical->mutex); - mLogicalToPhysical->map.insert( - GpuLogicalIndexUseMap::value_type(def.logicalIndex, - GpuLogicalIndexUse(def.physicalIndex, - def.arraySize * def.elementSize, GPV_GLOBAL, BCT_UNKNOWN))); - mLogicalToPhysical->bufferSize += def.arraySize * def.elementSize; - mConstantDefs->bufferSize = mLogicalToPhysical->bufferSize; - - String varName = member.name.UTF8String; - - mConstantDefs->map.insert( GpuConstantDefinitionMap::value_type( varName, def ) ); - } - } - } - //----------------------------------------------------------------------- - void MetalProgram::unloadHighLevelImpl(void) - { - // Release everything - mLibrary = nil; - mFunction = nil; - mCompiled = false; - } - //----------------------------------------------------------------------- - void MetalProgram::buildConstantDefinitions(void) - { - if( mType == GPT_FRAGMENT_PROGRAM && mShaderReflectionPairHint.empty() ) - { - LogManager::getSingleton().logMessage( - "WARNING: Pixel Shader '" + mName + "' without shader_reflection_pair_hint. " - "If this is intentional, use build_parameters_from_reflection false to hide " - "this warning."); - return; - } - - if( mCompileError ) - return; - - if( !mLibrary ) - return; - - if( mType != GPT_COMPUTE_PROGRAM ) - { - analyzeRenderParameters(); - } - else - { - analyzeComputeParameters(); - } - - mLogicalToPhysical.reset(); // disallow access by index for now - } - //----------------------------------------------------------------------- - String MetalProgram::CmdShaderReflectionPairHint::doGet(const void *target) const - { - return static_cast(target)->getShaderReflectionPairHint(); - } - //----------------------------------------------------------------------- - void MetalProgram::CmdShaderReflectionPairHint::doSet(void *target, const String& val) - { - static_cast(target)->setShaderReflectionPairHint(val); - } - //----------------------------------------------------------------------- - const String& MetalProgram::getLanguage(void) const - { - static const String language = "metal"; - - return language; - } - //----------------------------------------------------------------------- - GpuProgramParametersSharedPtr MetalProgram::createParameters( void ) - { - GpuProgramParametersSharedPtr params = HighLevelGpuProgram::createParameters(); - params->setTransposeMatrices(true); - return params; - } -} diff --git a/RenderSystems/Metal/src/OgreMetalProgramFactory.mm b/RenderSystems/Metal/src/OgreMetalProgramFactory.mm deleted file mode 100644 index 075484f5b99..00000000000 --- a/RenderSystems/Metal/src/OgreMetalProgramFactory.mm +++ /dev/null @@ -1,59 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2016 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreMetalProgramFactory.h" -#include "OgreMetalProgram.h" -#include "OgreRoot.h" -#include "OgreHighLevelGpuProgram.h" -#include "OgreMetalDevice.h" - -namespace Ogre { - //----------------------------------------------------------------------- - String MetalProgramFactory::sLanguageName = "metal"; - //----------------------------------------------------------------------- - MetalProgramFactory::MetalProgramFactory( MetalDevice *device ) : - mDevice( device ) - { - } - //----------------------------------------------------------------------- - MetalProgramFactory::~MetalProgramFactory(void) - { - } - //----------------------------------------------------------------------- - const String& MetalProgramFactory::getLanguage(void) const - { - return sLanguageName; - } - //----------------------------------------------------------------------- - GpuProgram* MetalProgramFactory::create(ResourceManager* creator, - const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) - { - return OGRE_NEW MetalProgram(creator, name, handle, group, isManual, loader, mDevice); - } -} diff --git a/RenderSystems/Metal/src/OgreMetalRenderSystem.mm b/RenderSystems/Metal/src/OgreMetalRenderSystem.mm deleted file mode 100644 index 063aa3ab086..00000000000 --- a/RenderSystems/Metal/src/OgreMetalRenderSystem.mm +++ /dev/null @@ -1,1182 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2016 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreMetalRenderSystem.h" -#include "OgreMetalRenderWindow.h" -#include "OgreMetalTextureManager.h" -#include "OgreMetalRenderTargetCommon.h" -#include "OgreMetalDepthBuffer.h" -#include "OgreMetalDevice.h" -#include "OgreGpuProgramManager.h" -#include "OgreMetalProgram.h" -#include "OgreMetalProgramFactory.h" -#include "OgreMetalTexture.h" -#include "OgreMetalMultiRenderTarget.h" - -#include "OgreMetalHardwareBufferManager.h" -#include "OgreMetalHardwareBufferCommon.h" - -#include "OgreViewport.h" - -#include "OgreMetalMappings.h" - -#import -#import - - -namespace Ogre -{ - //------------------------------------------------------------------------- - MetalRenderSystem::MetalRenderSystem() : - RenderSystem(), - mInitialized( false ), - mHardwareBufferManager( 0 ), - mMetalProgramFactory( 0 ), - mCurrentIndexBuffer( 0 ), - mCurrentVertexBuffer( 0 ), - mCurrentPrimType( MTLPrimitiveTypePoint ), - mNumMRTs( 0 ), - mCurrentDepthBuffer( 0 ), - mActiveDevice( 0 ), - mActiveRenderEncoder( 0 ), - mDevice( this ), - mMainGpuSyncSemaphore( 0 ), - mMainSemaphoreAlreadyWaited( false ), - mBeginFrameOnceStarted( false ) - { - for( size_t i=0; isecond; - mRenderTargets.clear(); - } - //------------------------------------------------------------------------- - void MetalRenderSystem::shutdown(void) - { - RenderSystem::shutdown(); - - OGRE_DELETE mHardwareBufferManager; - mHardwareBufferManager = 0; - - if( mMetalProgramFactory ) - { - // Remove from manager safely - if( HighLevelGpuProgramManager::getSingletonPtr() ) - HighLevelGpuProgramManager::getSingleton().removeFactory( mMetalProgramFactory ); - OGRE_DELETE mMetalProgramFactory; - mMetalProgramFactory = 0; - } - - OGRE_DELETE mTextureManager; - mTextureManager = 0; - } - //------------------------------------------------------------------------- - const String& MetalRenderSystem::getName(void) const - { - static String strName("Metal Rendering Subsystem"); - return strName; - } - //------------------------------------------------------------------------- - HardwareOcclusionQuery* MetalRenderSystem::createHardwareOcclusionQuery(void) - { - return 0; //TODO - } - //------------------------------------------------------------------------- - RenderSystemCapabilities* MetalRenderSystem::createRenderSystemCapabilities(void) const - { - RenderSystemCapabilities* rsc = new RenderSystemCapabilities(); - rsc->setRenderSystemName(getName()); - - rsc->setDeviceName(mActiveDevice->mDevice.name.UTF8String); - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS || OGRE_CPU == OGRE_CPU_ARM - rsc->setVendor( GPU_APPLE ); -#endif - - rsc->setCapability(RSC_HWSTENCIL); - rsc->setNumTextureUnits(16); - rsc->setNumVertexTextureUnits(16); - rsc->setCapability(RSC_ANISOTROPY); - rsc->setCapability(RSC_TEXTURE_COMPRESSION); -#if TARGET_OS_TV - rsc->setCapability(RSC_TEXTURE_COMPRESSION_ASTC); -#endif -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - // If the device is running macOS older than 11, - // then they are all x86 systems which all support BCn - bool supportsBCTextureCompression = true; - if( @available( macOS 11, * ) ) - { - supportsBCTextureCompression = mActiveDevice->mDevice.supportsBCTextureCompression; - } - - if( supportsBCTextureCompression ) - { - rsc->setCapability( RSC_TEXTURE_COMPRESSION_DXT ); - rsc->setCapability( RSC_TEXTURE_COMPRESSION_BC4_BC5 ); - // rsc->setCapability(RSC_TEXTURE_COMPRESSION_BC6H_BC7); - } -#else - //Actually the limit is not the count but rather how many bytes are in the - //GPU's internal TBDR cache (16 bytes for Family 1, 32 bytes for the rest) - //Consult Metal's manual for more info. - if( [mActiveDevice->mDevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily2_v1] ) - { - rsc->setCapability(RSC_TEXTURE_COMPRESSION_ASTC); - } -#endif - rsc->setCapability(RSC_32BIT_INDEX); - rsc->setCapability(RSC_TWO_SIDED_STENCIL); - rsc->setCapability(RSC_STENCIL_WRAP); - rsc->setCapability(RSC_USER_CLIP_PLANES); -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - if( [mActiveDevice->mDevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily4_v1] ) -#endif - { - rsc->setCapability(RSC_DEPTH_CLAMP); - } - - rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES); - rsc->setNonPOW2TexturesLimited(false); - rsc->setCapability(RSC_HWRENDER_TO_TEXTURE); - rsc->setCapability(RSC_TEXTURE_FLOAT); - rsc->setCapability(RSC_POINT_SPRITES); - rsc->setCapability(RSC_TEXTURE_1D); - rsc->setCapability(RSC_TEXTURE_3D); - // rsc->setCapability(RSC_TEXTURE_SIGNED_INT); - rsc->setCapability(RSC_VERTEX_PROGRAM); - rsc->setCapability(RSC_VERTEX_BUFFER_INSTANCE_DATA); - rsc->setCapability(RSC_VERTEX_FORMAT_INT_10_10_10_2); - rsc->setCapability(RSC_MIPMAP_LOD_BIAS); - rsc->setCapability(RSC_ALPHA_TO_COVERAGE); - rsc->setMaxPointSize(256); - - rsc->setCapability(RSC_COMPUTE_PROGRAM); - rsc->setCapability(RSC_HW_GAMMA); - // rsc->setCapability(RSC_TEXTURE_GATHER); - rsc->setCapability(RSC_TEXTURE_2D_ARRAY); - // rsc->setCapability(RSC_CONST_BUFFER_SLOTS_IN_SHADER); - - //These don't make sense on Metal, so just use flexible defaults. - rsc->setVertexProgramConstantFloatCount( 16384 ); - rsc->setFragmentProgramConstantFloatCount( 16384 ); - rsc->setComputeProgramConstantFloatCount( 16384 ); - -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - uint8 mrtCount = 8u; -#else - //Actually the limit is not the count but rather how many bytes are in the - //GPU's internal TBDR cache (16 bytes for Family 1, 32 bytes for the rest) - //Consult Metal's manual for more info. - uint8 mrtCount = 4u; - if( [mActiveDevice->mDevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily2_v1] || - [mActiveDevice->mDevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily2_v2] || - [mActiveDevice->mDevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily3_v1] ) - { - mrtCount = 8u; - } -#endif - rsc->setNumMultiRenderTargets( std::min(mrtCount, OGRE_MAX_MULTIPLE_RENDER_TARGETS) ); - -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - //uint16 max2DResolution = 16384; -#else - uint16 max2DResolution = 4096; - if( [mActiveDevice->mDevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily1_v2] || - [mActiveDevice->mDevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily2_v2] ) - { - max2DResolution = 8192; - } - if( [mActiveDevice->mDevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily3_v1] ) - { - max2DResolution = 16384; - } -#endif - // rsc->setMaximumResolutions( max2DResolution, 2048, max2DResolution ); - - //TODO: UAVs - //rsc->setCapability(RSC_UAV); - //rsc->setCapability(RSC_ATOMIC_COUNTERS); - - rsc->addShaderProfile( "metal" ); - - rsc->setCapability(RSC_FIXED_FUNCTION); // FIXME: hack to get past RTSS - - DriverVersion driverVersion; - - struct FeatureSets - { - MTLFeatureSet featureSet; - const char* name; - int major; - int minor; - }; - - FeatureSets featureSets[] = - { -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - { MTLFeatureSet_iOS_GPUFamily1_v1, "iOS_GPUFamily1_v1", 1, 1 }, - { MTLFeatureSet_iOS_GPUFamily2_v1, "iOS_GPUFamily2_v1", 2, 1 }, - - { MTLFeatureSet_iOS_GPUFamily1_v2, "iOS_GPUFamily1_v2", 1, 2 }, - { MTLFeatureSet_iOS_GPUFamily2_v2, "iOS_GPUFamily2_v2", 2, 2 }, - { MTLFeatureSet_iOS_GPUFamily3_v1, "iOS_GPUFamily3_v2", 3, 2 }, -#else - { MTLFeatureSet_OSX_GPUFamily1_v1, "OSX_GPUFamily1_v1", 1, 1 }, -#endif - }; - - for( size_t i=0; imDevice supportsFeatureSet:featureSets[i].featureSet] ) - { - LogManager::getSingleton().logMessage( "Supports: " + String(featureSets[i].name) ); - driverVersion.major = featureSets[i].major; - driverVersion.minor = featureSets[i].minor; - } - } - - rsc->setDriverVersion( driverVersion ); - - return rsc; - } - //------------------------------------------------------------------------- - RenderWindow* MetalRenderSystem::_createRenderWindow( const String &name, - unsigned int width, unsigned int height, - bool fullScreen, - const NameValuePairList *miscParams ) - { - RenderSystem::_createRenderWindow(name, width, height, fullScreen, miscParams); - if( !mInitialized ) - { - // enable debug layer - setenv("METAL_DEVICE_WRAPPER_TYPE", "1", 0); - - mDevice.init(); - setActiveDevice(&mDevice); - - const long c_inFlightCommandBuffers = 3; - mMainGpuSyncSemaphore = dispatch_semaphore_create(c_inFlightCommandBuffers); - mMainSemaphoreAlreadyWaited = false; - mBeginFrameOnceStarted = false; - mRealCapabilities = createRenderSystemCapabilities(); - mDriverVersion = mRealCapabilities->getDriverVersion(); - - if (!mUseCustomCapabilities) - mCurrentCapabilities = mRealCapabilities; - - fireEvent("RenderSystemCapabilitiesCreated"); - - initialiseFromRenderSystemCapabilities( mCurrentCapabilities, 0 ); - - mTextureManager = new MetalTextureManager( &mDevice ); - mHardwareBufferManager = new MetalHardwareBufferManager( &mDevice ); - - psd = [MTLRenderPipelineDescriptor new]; - MTLVertexDescriptor *vertexDescriptor = [MTLVertexDescriptor vertexDescriptor]; - [psd setVertexDescriptor:vertexDescriptor]; - mDepthStencilDesc = [MTLDepthStencilDescriptor new]; - - mInitialized = true; - - mDefaultVP = GpuProgramManager::getSingleton().createProgram("MetalDefaultVP", RGN_INTERNAL, "metal", GPT_VERTEX_PROGRAM).get(); - mDefaultFP = GpuProgramManager::getSingleton().createProgram("MetalDefaultFP", RGN_INTERNAL, "metal", GPT_FRAGMENT_PROGRAM).get(); - mDefaultVP->setSourceFile("DefaultShaders.metal"); - mDefaultVP->setParameter("entry_point", "default_vp"); - mDefaultFP->setSourceFile("DefaultShaders.metal"); - mDefaultFP->setParameter("entry_point", "default_fp"); - mDefaultFP->setParameter("shader_reflection_pair_hint", "MetalDefaultVP"); - } - - RenderWindow *win = OGRE_NEW MetalRenderWindow( &mDevice, this ); - win->create( name, width, height, fullScreen, miscParams ); - attachRenderTarget(*win); - return win; - } - - const GpuProgramParametersPtr& MetalRenderSystem::getFixedFunctionParams(TrackVertexColourType tracking, - FogMode fog) - { - mDefaultVP->load(); - mDefaultFP->load(); - - if(!mAutoParamsBuffer) - { - mDefaultFP->getDefaultParameters(); // also analyse FP params for testing - - auto vpParams = mDefaultVP->getDefaultParameters(); - vpParams->setNamedAutoConstant("texMtx", GpuProgramParameters::ACT_TEXTURE_MATRIX); - vpParams->setNamedAutoConstant("mvpMtx", GpuProgramParameters::ACT_WORLDVIEWPROJ_MATRIX); - - // create const buffer to back VP (currently unused) - if(auto sz = vpParams->getConstantList().size()) - { - mAutoParamsBuffer.reset(new MetalHardwareBufferCommon(sz, HBU_CPU_TO_GPU, - false, 4, &mDevice)); - } - } - - bindGpuProgram(mDefaultVP); - bindGpuProgram(mDefaultFP); - - return mDefaultVP->getDefaultParameters(); - } - - void MetalRenderSystem::applyFixedFunctionParams(const GpuProgramParametersPtr& params, uint16 mask) - { - bindGpuProgramParameters(GPT_VERTEX_PROGRAM, params, mask); - } - - //------------------------------------------------------------------------- - MultiRenderTarget* MetalRenderSystem::createMultiRenderTarget( const String & name ) - { - MetalMultiRenderTarget *retVal = OGRE_NEW MetalMultiRenderTarget( name ); - attachRenderTarget( *retVal ); - return retVal; - } - //------------------------------------------------------------------------- - void MetalRenderSystem::_setTexture(size_t unit, bool enabled, const TexturePtr& texPtr) - { - __unsafe_unretained id metalTexture = 0; - - if( texPtr && enabled ) - { - MetalTexture *metalTex = static_cast( texPtr.get() ); - metalTexture = metalTex->getTextureForSampling( this ); - } - - [mActiveRenderEncoder setVertexTexture:metalTexture atIndex:unit]; - [mActiveRenderEncoder setFragmentTexture:metalTexture atIndex:unit]; - } - //------------------------------------------------------------------------- - DepthBuffer* MetalRenderSystem::_createDepthBufferFor( RenderTarget *renderTarget ) - { - MTLTextureDescriptor *desc = [MTLTextureDescriptor new]; - desc.sampleCount = renderTarget->getFSAA(); - desc.textureType = renderTarget->getFSAA() > 1u ? MTLTextureType2DMultisample : - MTLTextureType2D; - desc.width = (NSUInteger)renderTarget->getWidth(); - desc.height = (NSUInteger)renderTarget->getHeight(); - desc.depth = (NSUInteger)1u; - desc.arrayLength = 1u; - desc.mipmapLevelCount = 1u; - - desc.usage = MTLTextureUsageRenderTarget; - //if( renderTarget->prefersDepthTexture() ) - // desc.usage |= MTLTextureUsageShaderRead; - -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - desc.storageMode = MTLStorageModePrivate; -#endif - - PixelFormat desiredDepthBufferFormat = PF_DEPTH24_STENCIL8;//renderTarget->getDesiredDepthBufferFormat(); - - MTLPixelFormat depthFormat = MTLPixelFormatInvalid; - MTLPixelFormat stencilFormat = MTLPixelFormatInvalid; - MetalMappings::getDepthStencilFormat( mActiveDevice, desiredDepthBufferFormat, - depthFormat, stencilFormat ); - - id depthTexture = 0; - id stencilTexture = 0; - - if( depthFormat != MTLPixelFormatInvalid ) - { - desc.pixelFormat = depthFormat; - depthTexture = [mActiveDevice->mDevice newTextureWithDescriptor: desc]; - } - - if( stencilFormat != MTLPixelFormatInvalid ) - { - if( stencilFormat != MTLPixelFormatDepth32Float_Stencil8 - #if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - && stencilFormat != MTLPixelFormatDepth24Unorm_Stencil8 - #endif - ) - { - //Separate Stencil & Depth - desc.pixelFormat = stencilFormat; - stencilTexture = [mActiveDevice->mDevice newTextureWithDescriptor: desc]; - } - else - { - //Combined Stencil & Depth - stencilTexture = depthTexture; - } - } - - DepthBuffer *retVal = new MetalDepthBuffer( 0, this, renderTarget->getWidth(), - renderTarget->getHeight(), - renderTarget->getFSAA(), - depthFormat, false, - depthTexture, stencilTexture, - mActiveDevice ); - - return retVal; - } - //------------------------------------------------------------------------- - void MetalRenderSystem::_waitForTailFrameToFinish(void) - { - if( !mMainSemaphoreAlreadyWaited ) - { - dispatch_semaphore_wait( mMainGpuSyncSemaphore, DISPATCH_TIME_FOREVER ); - mMainSemaphoreAlreadyWaited = true; - } - } - //------------------------------------------------------------------------- - bool MetalRenderSystem::_willTailFrameStall(void) - { - bool retVal = mMainSemaphoreAlreadyWaited; - - if( !mMainSemaphoreAlreadyWaited ) - { - const long result = dispatch_semaphore_wait( mMainGpuSyncSemaphore, DISPATCH_TIME_NOW ); - if( result == 0 ) - { - retVal = true; - //Semaphore was just grabbed, so ensure we don't grab it twice. - mMainSemaphoreAlreadyWaited = true; - } - } - - return retVal; - } - //------------------------------------------------------------------------- - void MetalRenderSystem::_beginFrame(void) - { - RenderSystem::_beginFrame(); - - assert( !mBeginFrameOnceStarted && - "Calling MetalRenderSystem::_beginFrameOnce more than once " - "without matching call to _endFrameOnce!!!" ); - - //Allow the renderer to preflight 3 frames on the CPU (using a semapore as a guard) and - //commit them to the GPU. This semaphore will get signaled once the GPU completes a - //frame's work via addCompletedHandler callback below, signifying the CPU can go ahead - //and prepare another frame. - _waitForTailFrameToFinish(); - - mBeginFrameOnceStarted = true; - } - //------------------------------------------------------------------------- - void MetalRenderSystem::_endFrame(void) - { - //TODO: We shouldn't tidy up JUST the active device. But all of them. - - __block dispatch_semaphore_t blockSemaphore = mMainGpuSyncSemaphore; - [mActiveDevice->mCurrentCommandBuffer addCompletedHandler:^(id buffer) - { - // GPU has completed rendering the frame and is done using the contents of any buffers - // previously encoded on the CPU for that frame. Signal the semaphore and allow the CPU - // to proceed and construct the next frame. - dispatch_semaphore_signal( blockSemaphore ); - }]; - - mActiveDevice->commitAndNextCommandBuffer(); - - mActiveRenderTarget = 0; - mActiveDevice->mFrameAborted = false; - mMainSemaphoreAlreadyWaited = false; - mBeginFrameOnceStarted = false; - } - //------------------------------------------------------------------------- - void MetalRenderSystem::setScissorTest(bool enabled, const Rect& rect) - { - if(!enabled) - return; - - MTLScissorRect scissorRect; - scissorRect.x = rect.left; - scissorRect.y = rect.top; - scissorRect.width = rect.width(); - scissorRect.height = rect.height(); - [mActiveRenderEncoder setScissorRect:scissorRect]; - } - void MetalRenderSystem::_setViewport(Viewport *vp) - { - if( mActiveViewport != vp ) - { - mActiveViewport = vp; - - if( vp ) - { - //const bool activeHasColourWrites = mNumMRTs != 0; - - if( vp->getTarget() != mActiveRenderTarget ) - { - _setRenderTarget( vp->getTarget() ); - } - -#if 0 - if( mActiveRenderEncoder || ( !mActiveRenderEncoder /*&& - (!vp->coversEntireTarget() || - !vp->scissorsMatchViewport())*/ ) ) -#endif - { - if( !mActiveRenderEncoder ) - createRenderEncoder(); - - //if( !vp->coversEntireTarget() ) - { - MTLViewport mtlVp; - mtlVp.originX = vp->getActualLeft(); - mtlVp.originY = vp->getActualTop(); - mtlVp.width = vp->getActualWidth(); - mtlVp.height = vp->getActualHeight(); - mtlVp.znear = 0; - mtlVp.zfar = 1; - [mActiveRenderEncoder setViewport:mtlVp]; - } - } - } - } - - //if( mActiveRenderEncoder && mUavsDirty ) - // flushUAVs(); - } - //------------------------------------------------------------------------- - void MetalRenderSystem::setActiveDevice( MetalDevice *device ) - { - if( mActiveDevice != device ) - { - mActiveDevice = device; - mActiveRenderEncoder = device ? device->mRenderEncoder : 0; - } - } - //------------------------------------------------------------------------- - void MetalRenderSystem::createRenderEncoder(void) - { - assert( mActiveDevice ); - - //We assume the RenderWindow is at MRT#0 (in fact it - //would be very odd to use the RenderWindow as MRT) - if( mNumMRTs > 0 ) - mActiveDevice->mFrameAborted |= !mCurrentColourRTs[0]->nextDrawable(); - - if( mActiveDevice->mFrameAborted ) - { - mActiveDevice->endAllEncoders(); - mActiveRenderEncoder = 0; - return; - } - - const bool hadActiveRenderEncoder = mActiveRenderEncoder; - Viewport *prevViewport = 0; - RenderTarget *prevRenderTarget = 0; - if( hadActiveRenderEncoder ) - { - //Ending all encoders will clear those, so we'll have to restore them. - prevViewport = mActiveViewport; - prevRenderTarget = mActiveRenderTarget; - } - - mActiveDevice->endAllEncoders(); - mActiveRenderEncoder = 0; - - if( hadActiveRenderEncoder ) - { - if( prevViewport /*&& (!prevViewport->coversEntireTarget() || - !prevViewport->scissorsMatchViewport())*/ ) - { - _setViewport( prevViewport ); - } - else - { - mActiveViewport = prevViewport; - mActiveRenderTarget = prevRenderTarget; - } - } - - //TODO: With a couple modifications, Compositor should be able to tell us - //if we can use MTLStoreActionDontCare. - - MTLRenderPassDescriptor *passDesc = [MTLRenderPassDescriptor renderPassDescriptor]; - for( uint8 i=0; imColourAttachmentDesc copy]; - mCurrentColourRTs[i]->mColourAttachmentDesc.loadAction = MTLLoadActionLoad; - - assert( passDesc.colorAttachments[i].texture ); - } - - if( mCurrentDepthBuffer ) - { - MTLRenderPassDepthAttachmentDescriptor *descDepth = - mCurrentDepthBuffer->mDepthAttachmentDesc; - if( descDepth ) - { - passDesc.depthAttachment = [descDepth copy]; - descDepth.loadAction = MTLLoadActionLoad; - } - - MTLRenderPassStencilAttachmentDescriptor *descStencil = - mCurrentDepthBuffer->mStencilAttachmentDesc; - if( descStencil ) - { - passDesc.stencilAttachment = [descStencil copy]; - descStencil.loadAction = MTLLoadActionLoad; - } - } - - mActiveDevice->mRenderEncoder = - [mActiveDevice->mCurrentCommandBuffer renderCommandEncoderWithDescriptor:passDesc]; - mActiveRenderEncoder = mActiveDevice->mRenderEncoder; - - // static_cast( mVaoManager )->bindDrawId(); - [mActiveRenderEncoder setFrontFacingWinding:MTLWindingCounterClockwise]; - // flushUAVs(); - - if (mStencilEnabled) - { - [mActiveRenderEncoder setStencilReferenceValue:mStencilRefValue]; - } - } - //------------------------------------------------------------------------- - void MetalRenderSystem::_notifyActiveEncoderEnded(void) - { - mActiveViewport = 0; - mActiveRenderTarget = 0; - mActiveRenderEncoder = 0; - } - //------------------------------------------------------------------------- - void MetalRenderSystem::_notifyActiveComputeEnded(void) - { - //mComputePso = 0; - } - //------------------------------------------------------------------------- - void MetalRenderSystem::_notifyDeviceStalled(void) - { - MetalHardwareBufferManager *hwBufferMgr = static_cast( - mHardwareBufferManager ); - hwBufferMgr->_notifyDeviceStalled(); - } - void MetalRenderSystem::setColourBlendState(const ColourBlendState& state) - { - mCurrentBlend = state; - - uint8 mrtCount = 1; - /*for( int i=0; ipass.colourFormat[i] != PF_NULL ) - mrtCount = i + 1u; - }*/ - - for( int i=0; i sampler = static_cast(s).getState(); - [mActiveRenderEncoder setVertexSamplerState:sampler atIndex: texUnit]; - [mActiveRenderEncoder setFragmentSamplerState:sampler atIndex: texUnit]; - } - - void MetalRenderSystem::_setDepthClamp(bool enable) - { - [mActiveRenderEncoder setDepthClipMode:enable ? MTLDepthClipModeClamp : MTLDepthClipModeClip]; - } - - void MetalRenderSystem::_setDepthBufferParams( bool depthTest, bool depthWrite, CompareFunction depthFunction ) - { - mDepthStencilDescChanged = true; - if(!depthTest) - { - mDepthStencilDesc.depthCompareFunction = MTLCompareFunctionAlways; - mDepthStencilDesc.depthWriteEnabled = false; - return; - } - - mDepthStencilDesc.depthCompareFunction = MetalMappings::get( depthFunction ); - mDepthStencilDesc.depthWriteEnabled = depthWrite; - } - void MetalRenderSystem::_setCullingMode(CullingMode mode) - { - MTLCullMode cullMode = MTLCullModeNone; - - switch( mode ) - { - case CULL_NONE: cullMode = MTLCullModeNone; break; - case CULL_CLOCKWISE: cullMode = MTLCullModeBack; break; - case CULL_ANTICLOCKWISE: cullMode = MTLCullModeFront; break; - } - - [mActiveRenderEncoder setCullMode:cullMode]; - } - void MetalRenderSystem::_setDepthBias(float constantBias, float slopeScaleBias) - { - [mActiveRenderEncoder setDepthBias:constantBias - slopeScale:slopeScaleBias - clamp:0.0f]; - } - - void MetalRenderSystem::_setPolygonMode(PolygonMode level) - { - MTLTriangleFillMode fillMode = - level == PM_SOLID ? MTLTriangleFillModeFill : MTLTriangleFillModeLines; - [mActiveRenderEncoder setTriangleFillMode:fillMode]; - } - - void MetalRenderSystem::_setAlphaRejectSettings(CompareFunction func, unsigned char value, bool alphaToCoverage) - { - psd.alphaToCoverageEnabled = (func != CMPF_ALWAYS_PASS) && alphaToCoverage; - } - - //------------------------------------------------------------------------- - void MetalRenderSystem::_convertProjectionMatrix( const Matrix4& matrix, Matrix4& dest, - bool forGpuProgram ) - { - dest = matrix; - - // Convert depth range from [-1,+1] to [0,1] - dest[2][0] = (dest[2][0] + dest[3][0]) / 2; - dest[2][1] = (dest[2][1] + dest[3][1]) / 2; - dest[2][2] = (dest[2][2] + dest[3][2]) / 2; - dest[2][3] = (dest[2][3] + dest[3][3]) / 2; - } - //------------------------------------------------------------------------- - id MetalRenderSystem::getPipelineState() - { - NSUInteger psdHash = [psd hash]; - auto it = mPSOCache.find(psdHash); - if(it != mPSOCache.end()) - return it->second; - - NSError* error = NULL; - id pso = - [mActiveDevice->mDevice newRenderPipelineStateWithDescriptor:psd error:&error]; - - if( !pso || error ) - { - String errorDesc; - if( error ) - errorDesc = [error localizedDescription].UTF8String; - - OGRE_EXCEPT( Exception::ERR_RENDERINGAPI_ERROR, - "Failed to created pipeline state for rendering: " + errorDesc); - } - - mPSOCache.emplace(psdHash, pso); - - return pso; - } - - void MetalRenderSystem::_render( const RenderOperation &op ) - { - if(!mActiveRenderTarget) return; - - // Call super class. - RenderSystem::_render(op); - - mCurrentIndexBuffer = op.indexData; - mCurrentVertexBuffer= op.vertexData; - mCurrentPrimType = std::min( MTLPrimitiveTypeTriangleStrip, - static_cast( op.operationType - 1u ) ); - - psd.colorAttachments[0].pixelFormat = MetalMappings::getPixelFormat( - mActiveRenderTarget->suggestPixelFormat(), mActiveRenderTarget->isHardwareGammaEnabled() ); - psd.depthAttachmentPixelFormat = static_cast(mActiveRenderTarget->getDepthBuffer())->getFormat(); - - MTLVertexDescriptor *vertexDescriptor = [psd vertexDescriptor]; - [vertexDescriptor reset]; - - size_t unused; - for (auto elem : mCurrentVertexBuffer->vertexDeclaration->getElements()) - { - auto bufferIdx = elem.getSource(); - if (!mCurrentVertexBuffer->vertexBufferBinding->isBufferBound(bufferIdx)) - continue; // skip unbound elements - auto elementIdx = MetalProgram::getAttributeIndex(elem.getSemantic()); - - auto hwbuf = mCurrentVertexBuffer->vertexBufferBinding->getBuffer(bufferIdx).get(); - - vertexDescriptor.attributes[elementIdx].format = MetalMappings::get( elem.getType() ); - vertexDescriptor.attributes[elementIdx].bufferIndex = bufferIdx; - vertexDescriptor.attributes[elementIdx].offset = elem.getOffset(); - - vertexDescriptor.layouts[bufferIdx].stride = hwbuf->getVertexSize(); - vertexDescriptor.layouts[bufferIdx].stepFunction = MTLVertexStepFunctionPerVertex; - - auto mtlbuf = hwbuf->_getImpl(); - [mActiveRenderEncoder setVertexBuffer:mtlbuf->getBufferName(unused) offset:0 atIndex:bufferIdx]; - } - - if(mDepthStencilDescChanged) - { - mDepthStencilState = - [mActiveDevice->mDevice newDepthStencilStateWithDescriptor:mDepthStencilDesc]; - mDepthStencilDescChanged = false; - } - - [mActiveRenderEncoder setDepthStencilState:mDepthStencilState]; - - [mActiveRenderEncoder setRenderPipelineState:getPipelineState()]; - - const size_t numberOfInstances = op.numberOfInstances; - - // Render to screen! - if( op.useIndexes ) - { - do - { - const MTLIndexType indexType = static_cast( - mCurrentIndexBuffer->indexBuffer->getType() ); - - //Get index buffer stuff which is the same for all draws in this cmd - const size_t bytesPerIndexElement = mCurrentIndexBuffer->indexBuffer->getIndexSize(); - - size_t offsetStart; - auto metalBuffer = mCurrentIndexBuffer->indexBuffer->_getImpl(); - __unsafe_unretained id indexBuffer = metalBuffer->getBufferName( offsetStart ); - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - OgreAssertDbg( ((mCurrentIndexBuffer->indexStart * bytesPerIndexElement) & 0x03) == 0 - ,"Index Buffer must be aligned to 4 bytes. If you're messing with " - "IndexBuffer::indexStart, you've entered an invalid " - "indexStart; not supported by the Metal API." ); - - [mActiveRenderEncoder drawIndexedPrimitives:mCurrentPrimType - indexCount:mCurrentIndexBuffer->indexCount - indexType:indexType - indexBuffer:indexBuffer - indexBufferOffset:mCurrentIndexBuffer->indexStart * bytesPerIndexElement + offsetStart - instanceCount:numberOfInstances]; -#else - [mActiveRenderEncoder drawIndexedPrimitives:mCurrentPrimType - indexCount:mCurrentIndexBuffer->indexCount - indexType:indexType - indexBuffer:indexBuffer - indexBufferOffset:mCurrentIndexBuffer->indexStart * bytesPerIndexElement + offsetStart - instanceCount:numberOfInstances - baseVertex:mCurrentVertexBuffer->vertexStart - baseInstance:0]; -#endif - } while (updatePassIterationRenderState()); - } - else - { - do - { - // Update derived depth bias. - if (mDerivedDepthBias && mCurrentPassIterationNum > 0) - { - [mActiveRenderEncoder setDepthBias:mDerivedDepthBiasBase + - mDerivedDepthBiasMultiplier * - mCurrentPassIterationNum - slopeScale:mDerivedDepthBiasSlopeScale - clamp:0.0f]; - } - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - const uint32 vertexStart = 0; -#else - const uint32 vertexStart = static_cast( mCurrentVertexBuffer->vertexStart ); -#endif - - if (numberOfInstances > 1) - { - [mActiveRenderEncoder drawPrimitives:mCurrentPrimType - vertexStart:vertexStart - vertexCount:mCurrentVertexBuffer->vertexCount - instanceCount:numberOfInstances]; - } - else - { - [mActiveRenderEncoder drawPrimitives:mCurrentPrimType - vertexStart:vertexStart - vertexCount:mCurrentVertexBuffer->vertexCount]; - } - } while (updatePassIterationRenderState()); - } - } - //------------------------------------------------------------------------- - void MetalRenderSystem::bindGpuProgram(GpuProgram* prg) - { - auto shader = static_cast( prg->_getBindingDelegate() ); - if(prg->getType() == GPT_VERTEX_PROGRAM) - [psd setVertexFunction:shader->getMetalFunction()]; - else - [psd setFragmentFunction:shader->getMetalFunction()]; - } - - void MetalRenderSystem::bindGpuProgramParameters( GpuProgramType gptype, - const GpuProgramParametersPtr& params, - uint16 variabilityMask ) - { - mActiveParameters[gptype] = params; - - switch (gptype) - { - case GPT_GEOMETRY_PROGRAM: - OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, - "Geometry Shaders are not supported in Metal."); - break; - case GPT_HULL_PROGRAM: - OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, - "Tesselation is different in Metal."); - break; - case GPT_DOMAIN_PROGRAM: - OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED, - "Tesselation is different in Metal."); - break; - default: - break; - } - - // update const buffer - #if 1 - [mActiveRenderEncoder setVertexBytes:params->getFloatPointer(0) - length:params->getConstantList().size() atIndex:MetalProgram::UNIFORM_INDEX_START]; - #else - // TODO rather use this, but buffer seems to be never updated - size_t unused; - mAutoParamsBuffer->writeData(0, params->getConstantList().size(), params->getFloatPointer(0)); - [mActiveRenderEncoder setVertexBuffer:mAutoParamsBuffer->getBufferName(unused) offset:0 atIndex:MetalProgram::UNIFORM_INDEX_START]; - #endif - } - //------------------------------------------------------------------------- - void MetalRenderSystem::clearFrameBuffer( unsigned int buffers, const ColourValue& colour, - float depth, unsigned short stencil ) - { - if( buffers & FBT_COLOUR ) - { - for( size_t i=0; imColourAttachmentDesc.loadAction = MTLLoadActionClear; - mCurrentColourRTs[i]->mColourAttachmentDesc.clearColor = - MTLClearColorMake( colour.r, colour.g, colour.b, colour.a ); - } - } - } - - if( mCurrentDepthBuffer ) - { - if( buffers & FBT_DEPTH && mCurrentDepthBuffer->mDepthAttachmentDesc ) - { - mCurrentDepthBuffer->mDepthAttachmentDesc.loadAction = MTLLoadActionClear; - mCurrentDepthBuffer->mDepthAttachmentDesc.clearDepth = depth; - } - - if( buffers & FBT_STENCIL && mCurrentDepthBuffer->mStencilAttachmentDesc ) - { - mCurrentDepthBuffer->mStencilAttachmentDesc.loadAction = MTLLoadActionClear; - mCurrentDepthBuffer->mStencilAttachmentDesc.clearStencil = stencil; - } - } - } - //------------------------------------------------------------------------- - Real MetalRenderSystem::getMinimumDepthInputValue(void) - { - return 0.0f; - } - //------------------------------------------------------------------------- - Real MetalRenderSystem::getMaximumDepthInputValue(void) - { - return 1.0f; - } - //------------------------------------------------------------------------- - void MetalRenderSystem::_setRenderTarget(RenderTarget *target) - { - #if 0 - uint8 viewportRenderTargetFlags = 0; - { - const bool activeHasColourWrites = mNumMRTs != 0; - if( mActiveRenderTarget == target && - activeHasColourWrites == (viewportRenderTargetFlags & VP_RTT_COLOUR_WRITE) ) - { - if( mActiveRenderEncoder && mUavsDirty ) - flushUAVs(); - return; - } - } - #endif - - if( mActiveDevice ) - mActiveDevice->endRenderEncoder(); - - mActiveRenderTarget = target; - - if( auto metalTarget = dynamic_cast(target) ) - { - //if( target->getForceDisableColourWrites() ) - // viewportRenderTargetFlags &= ~VP_RTT_COLOUR_WRITE; - - mCurrentColourRTs[0] = metalTarget; - //We need to set mCurrentColourRTs[0] to grab the active device, - //even if we won't be drawing to colour target. - target->getCustomAttribute( "mNumMRTs", &mNumMRTs ); - - MetalDevice *ownerDevice = 0; - - //if( viewportRenderTargetFlags & VP_RTT_COLOUR_WRITE ) - { - for( size_t i=0; imColourAttachmentDesc; - - //TODO. This information is stored in Texture. Metal needs it now. - const bool explicitResolve = false; - - //TODO: Compositor should be able to tell us whether to use - //MTLStoreActionDontCare with some future enhancements. - if( target->getFSAA() > 1 && !explicitResolve ) - { - desc.storeAction = MTLStoreActionMultisampleResolve; - } - else - { - desc.storeAction = MTLStoreActionStore; - } - - ownerDevice = mCurrentColourRTs[i]->getOwnerDevice(); - } - } - if(0) //else - { - mNumMRTs = 0; - } - - MetalDepthBuffer *depthBuffer = static_cast( target->getDepthBuffer() ); - - if( target->getDepthBufferPool() != DepthBuffer::POOL_NO_DEPTH && !depthBuffer ) - { - // Depth is automatically managed and there is no depth buffer attached to this RT - setDepthBufferFor( target ); - } - - depthBuffer = static_cast( target->getDepthBuffer() ); - mCurrentDepthBuffer = depthBuffer; - if( depthBuffer ) - { - if( depthBuffer->mDepthAttachmentDesc ) - depthBuffer->mDepthAttachmentDesc.storeAction = MTLStoreActionStore; - if( depthBuffer->mStencilAttachmentDesc ) - depthBuffer->mStencilAttachmentDesc.storeAction = MTLStoreActionStore; - - ownerDevice = depthBuffer->getOwnerDevice(); - } - - setActiveDevice( ownerDevice ); - } - else - { - mNumMRTs = 0; - mCurrentDepthBuffer = 0; - } - } - //------------------------------------------------------------------------- - void MetalRenderSystem::initGPUProfiling(void) - { -#if OGRE_PROFILING -// _rmt_BindMetal( mActiveDevice->mCurrentCommandBuffer ); -#endif - } - //------------------------------------------------------------------------- - void MetalRenderSystem::deinitGPUProfiling(void) - { -#if OGRE_PROFILING - _rmt_UnbindMetal(); -#endif - } - //------------------------------------------------------------------------- - void MetalRenderSystem::beginGPUSampleProfile( const String &name, uint32 *hashCache ) - { -#if OGRE_PROFILING - _rmt_BeginMetalSample( name.c_str(), hashCache ); -#endif - } - //------------------------------------------------------------------------- - void MetalRenderSystem::endGPUSampleProfile( const String &name ) - { -#if OGRE_PROFILING - _rmt_EndMetalSample(); -#endif - } - //------------------------------------------------------------------------- - void MetalRenderSystem::beginProfileEvent( const String &eventName ) - { - } - //------------------------------------------------------------------------- - void MetalRenderSystem::endProfileEvent( void ) - { - } - //------------------------------------------------------------------------- - void MetalRenderSystem::markProfileEvent( const String &event ) - { - } - //------------------------------------------------------------------------- - void MetalRenderSystem::initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary) - { - //DepthBuffer::DefaultDepthBufferFormat = PF_D32_FLOAT_X24_S8_UINT; - mMetalProgramFactory = new MetalProgramFactory( &mDevice ); - HighLevelGpuProgramManager::getSingleton().addFactory( mMetalProgramFactory ); - } - //------------------------------------------------------------------------- - void MetalRenderSystem::setStencilState(const StencilState& state) - { - mStencilEnabled = state.enabled; - // There are two main cases: - // 1. The active render encoder is valid and will be subsequently used for drawing. - // We need to set the stencil reference value on this encoder. We do this below. - // 2. The active render is invalid or is about to go away. - // In this case, we need to set the stencil reference value on the new encoder when it is created - // (see createRenderEncoder). (In this case, the setStencilReferenceValue below in this wasted, but it is inexpensive). - - if (mStencilEnabled) - { - mStencilRefValue = state.referenceValue; - - if( mActiveRenderEncoder ) - [mActiveRenderEncoder setStencilReferenceValue:mStencilRefValue]; - } - } - } diff --git a/RenderSystems/Metal/src/OgreMetalRenderTargetCommon.mm b/RenderSystems/Metal/src/OgreMetalRenderTargetCommon.mm deleted file mode 100644 index 8e749a73d46..00000000000 --- a/RenderSystems/Metal/src/OgreMetalRenderTargetCommon.mm +++ /dev/null @@ -1,59 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2016 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreMetalRenderTargetCommon.h" - -#import - -namespace Ogre -{ - MetalRenderTargetCommon::MetalRenderTargetCommon( MetalDevice *ownerDevice ) : - mOwnerDevice( ownerDevice ), - mColourAttachmentDesc( 0 ) - { - } - //----------------------------------------------------------------------------------- - MetalRenderTargetCommon::~MetalRenderTargetCommon() - { - destroy(); - } - //----------------------------------------------------------------------------------- - void MetalRenderTargetCommon::init( id texture, id resolveTexture ) - { - mColourAttachmentDesc = [MTLRenderPassColorAttachmentDescriptor alloc]; - mColourAttachmentDesc.loadAction = MTLLoadActionDontCare; - mColourAttachmentDesc.storeAction = MTLStoreActionStore; - mColourAttachmentDesc.texture = texture; - mColourAttachmentDesc.resolveTexture = resolveTexture; - } - //----------------------------------------------------------------------------------- - void MetalRenderTargetCommon::destroy(void) - { - mColourAttachmentDesc = 0; - } -} diff --git a/RenderSystems/Metal/src/OgreMetalRenderTexture.mm b/RenderSystems/Metal/src/OgreMetalRenderTexture.mm deleted file mode 100644 index 6117ab219ae..00000000000 --- a/RenderSystems/Metal/src/OgreMetalRenderTexture.mm +++ /dev/null @@ -1,87 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2016 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreMetalRenderTexture.h" - -#import -#import - -namespace Ogre -{ - MetalRenderTexture::MetalRenderTexture( MetalDevice *ownerDevice, const String &name, - HardwarePixelBuffer *buffer, - __unsafe_unretained id renderTexture, - __unsafe_unretained id resolveTexture, - PixelFormat format, uint32 depthPlane, uint32 slice, - uint32 fsaa, uint32 mip, bool hwGamma ) : - RenderTexture( buffer, depthPlane != 1 ? depthPlane : slice ), - MetalRenderTargetCommon( ownerDevice ) - { - mActive = false; - mHwGamma = hwGamma; - - mName = name; - mFormat = format; - mWidth = static_cast( renderTexture.width ); - mHeight = static_cast( renderTexture.height ); - mFSAA = fsaa; - - this->init( renderTexture, resolveTexture ); - - mColourAttachmentDesc.depthPlane = depthPlane; - mColourAttachmentDesc.slice = slice; - mColourAttachmentDesc.level = mip; - mColourAttachmentDesc.resolveTexture = resolveTexture; - mColourAttachmentDesc.texture = renderTexture; - mColourAttachmentDesc.resolveLevel = mip; - mColourAttachmentDesc.resolveDepthPlane = depthPlane; - mColourAttachmentDesc.resolveSlice = slice; - } - //------------------------------------------------------------------------- - MetalRenderTexture::~MetalRenderTexture() - { - mActive = false; - } - //------------------------------------------------------------------------- - void MetalRenderTexture::swapBuffers(void) - { - RenderTexture::swapBuffers(); - } - //------------------------------------------------------------------------- - void MetalRenderTexture::getCustomAttribute( const String& name, void* pData ) - { - if( name == "mNumMRTs" ) - { - *static_cast(pData) = 1u; - } - else - { - RenderTarget::getCustomAttribute( name, pData ); - } - } -} diff --git a/RenderSystems/Metal/src/OgreMetalRenderWindow.mm b/RenderSystems/Metal/src/OgreMetalRenderWindow.mm deleted file mode 100644 index a10f519935e..00000000000 --- a/RenderSystems/Metal/src/OgreMetalRenderWindow.mm +++ /dev/null @@ -1,319 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2016 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreMetalRenderWindow.h" -#include "OgreMetalMappings.h" -#include "OgreMetalRenderSystem.h" -#include "OgreViewport.h" - -namespace Ogre -{ - MetalRenderWindow::MetalRenderWindow( MetalDevice *ownerDevice, MetalRenderSystem *renderSystem ) : - RenderWindow(), - MetalRenderTargetCommon( ownerDevice ), - mMetalLayer( 0 ), - mCurrentDrawable( 0 ), - mMsaaTex( 0 ), - mContentScalingFactor(1) - { - mIsFullScreen = false; - mActive = false; - mFSAA = 1; - } - //------------------------------------------------------------------------- - MetalRenderWindow::~MetalRenderWindow() - { - destroy(); - } - //------------------------------------------------------------------------- - inline void MetalRenderWindow::checkLayerSizeChanges(void) - { - // Handle display changes here - if( mMetalView.layerSizeDidUpdate ) - { - // set the metal layer to the drawable size in case orientation or size changes - CGSize drawableSize = CGSizeMake(mMetalView.bounds.size.width, mMetalView.bounds.size.height); -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - drawableSize.width *= mMetalView.layer.contentsScale; - drawableSize.height *= mMetalView.layer.contentsScale; -#else - NSScreen* screen = mMetalView.window.screen ?: [NSScreen mainScreen]; - drawableSize.width *= screen.backingScaleFactor; - drawableSize.height *= screen.backingScaleFactor; -#endif - mMetalLayer.drawableSize = drawableSize; - - // Resize anything if needed - this->windowMovedOrResized(); - - mMetalView.layerSizeDidUpdate = NO; - } - } - //------------------------------------------------------------------------- - void MetalRenderWindow::swapBuffers(void) - { - /*assert( (mOwnerDevice->mFrameAborted || - mColourAttachmentDesc.loadAction != MTLLoadActionClear) && - "A clear has been asked but no rendering command was " - "issued and Ogre didn't catch it." );*/ - - RenderWindow::swapBuffers(); - - // Do not retain current drawable's texture beyond the frame. - if( mFSAA > 1 ) - mColourAttachmentDesc.resolveTexture = 0; - else - mColourAttachmentDesc.texture = 0; - - if( !mOwnerDevice->mFrameAborted ) - { - // Schedule a present once rendering to the framebuffer is complete - const CFTimeInterval presentationTime = mMetalView.presentationTime; - - if( presentationTime < 0 ) - { - [mOwnerDevice->mCurrentCommandBuffer presentDrawable:mCurrentDrawable]; - } - else - { - [mOwnerDevice->mCurrentCommandBuffer presentDrawable:mCurrentDrawable - atTime:presentationTime]; - } - } - mCurrentDrawable = 0; - } - //------------------------------------------------------------------------- - void MetalRenderWindow::windowMovedOrResized(void) - { - if( mWidth != mMetalLayer.drawableSize.width || - mHeight != mMetalLayer.drawableSize.height ) - { - mWidth = mMetalLayer.drawableSize.width; - mHeight = mMetalLayer.drawableSize.height; - - if( mFSAA > 1 && mWidth > 0 && mHeight > 0 ) - { - mMsaaTex = 0; - mColourAttachmentDesc.texture = 0; - MTLTextureDescriptor* desc = [MTLTextureDescriptor - texture2DDescriptorWithPixelFormat: - MetalMappings::getPixelFormat( mFormat, mHwGamma ) - width: mWidth height: mHeight mipmapped: NO]; - desc.textureType = MTLTextureType2DMultisample; - desc.sampleCount = mFSAA; - desc.usage = MTLTextureUsageRenderTarget; - - mMsaaTex = [mOwnerDevice->mDevice newTextureWithDescriptor: desc]; - mColourAttachmentDesc.texture = mMsaaTex; - } - - detachDepthBuffer(); - - ViewportList::iterator itor = mViewportList.begin(); - ViewportList::iterator end = mViewportList.end(); - while( itor != end ) - { - (*itor).second->_updateDimensions(); - ++itor; - } - } - } - - bool MetalRenderWindow::nextDrawable(void) - { - bool isSuccess = true; - - @autoreleasepool - { - if( !mCurrentDrawable ) - { - if( mMetalView.layerSizeDidUpdate ) - checkLayerSizeChanges(); - - // do not retain current drawable beyond the frame. - // There should be no strong references to this object outside of this view class - mCurrentDrawable = [mMetalLayer nextDrawable]; - if( !mCurrentDrawable ) - { - LogManager::getSingleton().logMessage( "Metal ERROR: Failed to get a drawable!", - LML_CRITICAL ); - //We're unable to render. Skip frame. - //dispatch_semaphore_signal( _inflight_semaphore ); - - isSuccess = false; - } - else - { - if( mFSAA > 1 ) - mColourAttachmentDesc.resolveTexture = mCurrentDrawable.texture; - else - mColourAttachmentDesc.texture = mCurrentDrawable.texture; - } - } - } - - return isSuccess; - } - //------------------------------------------------------------------------- - void MetalRenderWindow::create( const String& name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams ) - { - mWidth = width; - mHeight = height; - - mName = name; - mIsFullScreen = fullScreen; - - mActive = true; - mClosed = false; - - mFormat = PF_B8G8R8A8; - mHwGamma = true; - - if( miscParams ) - { - NameValuePairList::const_iterator opt; - NameValuePairList::const_iterator end = miscParams->end(); - - opt = miscParams->find("FSAA"); - if( opt != end ) - mFSAA = std::max( 1u, StringConverter::parseUnsignedInt( opt->second ) ); - - opt = miscParams->find("gamma"); - if( opt != end ) - mHwGamma = StringConverter::parseBool( opt->second ); - -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - opt = miscParams->find("externalWindowHandle"); - if( opt != end ) - { - LogManager::getSingleton().logMessage("Mac Cocoa Window: Rendering on an external NSWindow*"); - mWindow = (__bridge NSWindow*)reinterpret_cast(StringConverter::parseSizeT(opt->second)); - assert( mWindow && - "Unable to get a pointer to the parent NSWindow." - "Was the 'externalWindowHandle' parameter set correctly in the call to createRenderWindow()?"); - } -#endif - } - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - CGRect frame; -#else - NSRect frame; -#endif - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - frame.origin.x = 0; - frame.origin.y = 0; - frame.size.width = mWidth; - frame.size.height = mHeight; -#else - frame = [mWindow.contentView bounds]; - mContentScalingFactor = mWindow.backingScaleFactor; -#endif - mMetalView = [[OgreMetalView alloc] initWithFrame:frame]; - -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - NSView *view = mWindow.contentView; - [view addSubview:mMetalView]; - mResizeObserver = [[NSNotificationCenter defaultCenter] addObserverForName:NSWindowDidResizeNotification object:mWindow queue:nil usingBlock:^(NSNotification *){ - mMetalView.frame = [mWindow.contentView bounds]; - }]; -#endif - - mMetalLayer = (CAMetalLayer*)mMetalView.layer; - mMetalLayer.device = mOwnerDevice->mDevice; - mMetalLayer.pixelFormat = MetalMappings::getPixelFormat( mFormat, mHwGamma ); - - //This is the default but if we wanted to perform compute - //on the final rendering layer we could set this to no - mMetalLayer.framebufferOnly = YES; - - this->init( nil, nil ); - -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - checkLayerSizeChanges(); -#endif - windowMovedOrResized(); - } - //------------------------------------------------------------------------- - void MetalRenderWindow::destroy() - { -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - [[NSNotificationCenter defaultCenter] removeObserver:mResizeObserver]; -#endif - mActive = false; - mClosed = true; - - mMetalLayer = 0; - mCurrentDrawable = 0; - mMsaaTex = 0; - mMetalView = 0; - } - //------------------------------------------------------------------------- - void MetalRenderWindow::resize( unsigned int width, unsigned int height ) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - CGRect frame = mMetalView.frame; - frame.size.width = width; - frame.size.height = height; - mMetalView.frame = frame; -#else - mMetalView.frame = [mWindow.contentView bounds]; -#endif - detachDepthBuffer(); - } - //------------------------------------------------------------------------- - void MetalRenderWindow::reposition( int left, int top ) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - CGRect frame = mMetalView.frame; - frame.origin.x = left; - frame.origin.y = top; - mMetalView.frame = frame; -#else - mMetalView.frame = [mWindow.contentView bounds]; -#endif - } - //------------------------------------------------------------------------- - void MetalRenderWindow::getCustomAttribute( const String& name, void* pData ) - { - if( name == "mNumMRTs" ) - { - *static_cast(pData) = 1u; - } - else if( name == "UIView" ) - { - *static_cast(pData) = const_cast((const void*)CFBridgingRetain( mMetalView )); - } - else - { - RenderTarget::getCustomAttribute( name, pData ); - } - } -} diff --git a/RenderSystems/Metal/src/OgreMetalTexture.mm b/RenderSystems/Metal/src/OgreMetalTexture.mm deleted file mode 100644 index 69b307b0704..00000000000 --- a/RenderSystems/Metal/src/OgreMetalTexture.mm +++ /dev/null @@ -1,252 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreMetalTexture.h" -#include "OgreMetalRenderTexture.h" -#include "OgreMetalMappings.h" -#include "OgreMetalDevice.h" -#include "OgreMetalRenderSystem.h" -#include "OgreTextureManager.h" -#include "OgreStringConverter.h" -#include "OgreMetalDepthBuffer.h" -#include "OgreBitwise.h" - -#import "Metal/MTLBlitCommandEncoder.h" - -namespace Ogre -{ - MetalTexture::MetalTexture( ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - MetalDevice *device ) : - Texture(creator, name, handle, group, isManual, loader), - mTexture( 0 ), - mDevice( device ) - { - mMipmapsHardwareGenerated = true; - } - //----------------------------------------------------------------------------------- - MetalTexture::~MetalTexture() - { - // have to call this here rather than in Resource destructor - // since calling virtual methods in base destructors causes crash - unload(); - } - //----------------------------------------------------------------------------------- - MTLTextureType MetalTexture::getMetalTextureTarget(void) const - { - switch( mTextureType ) - { - case TEX_TYPE_1D: - return MTLTextureType1D; - case TEX_TYPE_2D: - return MTLTextureType2D; - case TEX_TYPE_CUBE_MAP: - return MTLTextureTypeCube; - case TEX_TYPE_3D: - return MTLTextureType3D; - case TEX_TYPE_2D_ARRAY: - return MTLTextureType2DArray; - default: - return (MTLTextureType)999; - }; - } - //----------------------------------------------------------------------------------- - void MetalTexture::createMetalTexResource(void) - { - // Adjust format if required - mFormat = TextureManager::getSingleton().getNativeFormat( mTextureType, mFormat, mUsage ); - const MTLTextureType texTarget = getMetalTextureTarget(); - - if(mTextureType == TEX_TYPE_1D ) - mNumMipmaps = mNumRequestedMipmaps = 0; - - // If we can do automip generation and the user desires this, do so - mMipmapsHardwareGenerated = !PixelUtil::isCompressed( mFormat ); - - MTLTextureDescriptor *desc = [MTLTextureDescriptor new]; - desc.mipmapLevelCount = mNumMipmaps + 1u; - desc.textureType = texTarget; - desc.width = mWidth; - desc.height = mHeight; - if( mTextureType != TEX_TYPE_CUBE_MAP ) - { - desc.depth = mTextureType == TEX_TYPE_2D_ARRAY ? 1u : mDepth; - desc.arrayLength= mTextureType == TEX_TYPE_2D_ARRAY ? mDepth : 1u; - } - else - { - desc.depth = 1u; - desc.arrayLength= 1u; - } - desc.pixelFormat = MetalMappings::getPixelFormat( mFormat, mHwGamma ); - desc.sampleCount = 1u; - - desc.usage = MTLTextureUsageShaderRead; - if( mUsage & TU_RENDERTARGET ) - desc.usage |= MTLTextureUsageRenderTarget; - if( mUsage & TU_UNORDERED_ACCESS ) - desc.usage |= MTLTextureUsageShaderWrite; - - if( mUsage & (TU_UNORDERED_ACCESS|TU_NOT_SRV|TU_RENDERTARGET) ) - desc.storageMode = MTLStorageModePrivate; - - mTexture = [mDevice->mDevice newTextureWithDescriptor:desc]; - mTexture.label = [NSString stringWithUTF8String:mName.c_str()]; - - if( mFSAA > 1u ) - { - desc.textureType = MTLTextureType2DMultisample; - desc.depth = 1u; - desc.arrayLength = 1u; - desc.sampleCount = mFSAA; - mMsaaTexture = [mDevice->mDevice newTextureWithDescriptor:desc]; - mMsaaTexture.label = [NSString stringWithUTF8String:(mName + "_MSAA").c_str()]; - } - } - //----------------------------------------------------------------------------------- - // Creation / loading methods - void MetalTexture::createInternalResourcesImpl(void) - { - if( mFSAA < 1u ) - mFSAA = 1u; - - createMetalTexResource(); - createSurfaceList(); - - if( (mUsage & TU_AUTOMIPMAP) && - mNumMipmaps && mMipmapsHardwareGenerated ) - { - __unsafe_unretained id blitEncoder = mDevice->getBlitEncoder(); - [blitEncoder generateMipmapsForTexture:mTexture]; - } - } - void MetalTexture::freeInternalResourcesImpl(void) - { - mTexture = 0; - } - //----------------------------------------------------------------------------------- - void MetalTexture::createSurfaceList(void) - { - mSurfaceList.clear(); - - __unsafe_unretained id renderTexture = mTexture; - __unsafe_unretained id resolveTexture = 0; - - if( mMsaaTexture ) - { - renderTexture = mMsaaTexture; - resolveTexture = mTexture; - } - - for (size_t face = 0; face < getNumFaces(); face++) - { - uint32 width = mWidth; - uint32 height = mHeight; - uint32 depth = mDepth; - - for (uint8 mip = 0; mip <= getNumMipmaps(); mip++) - { - MetalHardwarePixelBuffer *buf = OGRE_NEW MetalTextureBuffer( - renderTexture, resolveTexture, mDevice, mName, - getMetalTextureTarget(), width, height, depth, mFormat, - static_cast(face), mip, - static_cast(mUsage), - mHwGamma, mFSAA ); - - mSurfaceList.push_back( HardwarePixelBufferSharedPtr(buf) ); - } - } - } - //----------------------------------------------------------------------------------- - void MetalTexture::_autogenerateMipmaps(void) - { - __unsafe_unretained id blitEncoder = mDevice->getBlitEncoder(); - [blitEncoder generateMipmapsForTexture: mTexture]; - - // mSurfaceList[0]->getRenderTarget()->_setMipmapsUpdated(); - } - //----------------------------------------------------------------------------------- - id MetalTexture::getTextureForSampling( MetalRenderSystem *renderSystem ) - { - __unsafe_unretained id retVal = mTexture; - - if( mUsage & TU_RENDERTARGET ) - { - #if OGRE_DEBUG_MODE - RenderTarget *renderTarget = mSurfaceList[0]->getRenderTarget(); - assert( dynamic_cast( renderTarget ) ); - if( PixelUtil::isDepth( renderTarget->suggestPixelFormat() ) ) - { - MetalDepthBuffer *depthBuffer = static_cast( - renderTarget->getDepthBuffer() ); - assert( depthBuffer->mDepthAttachmentDesc.loadAction != MTLLoadActionClear ); - } - else - { - MetalRenderTexture *renderTexture = static_cast( renderTarget ); - assert( renderTexture->mColourAttachmentDesc.loadAction != MTLLoadActionClear ); - } - #endif - - if( mFSAA > 1u ) - { - //RenderTarget *renderTarget = mSurfaceList[0]->getRenderTarget(); - //In metal, implicitly resolved textures are immediately resolved - //via MTLStoreActionMultisampleResolve, so we don't need to do - //anything for implicit resolves (it's already resolved and the - //contents of the msaa texture are left undefined). -// if( !mFsaaExplicitResolve ) -// { -// for( size_t face=0; facegetRenderTarget(); -// if( renderTarget->isFsaaResolveDirty() ) -// renderTarget->swapBuffers(); -// } -// } -// else if( renderTarget->isFsaaResolveDirty() ) - //if( !mFsaaExplicitResolve && renderTarget->isFsaaResolveDirty() ) - { - //Explicit resolves. Only use the - //Fsaa texture before it has been resolved - retVal = mMsaaTexture; - } - } - - if( (mUsage & (TU_AUTOMIPMAP|TU_RENDERTARGET)) == - (TU_AUTOMIPMAP|TU_RENDERTARGET) ) - { - // RenderTarget *renderTarget = mSurfaceList[0]->getRenderTarget(); - // if( renderTarget->isMipmapsDirty() ) - this->_autogenerateMipmaps(); - } - } - - return retVal; - } -} diff --git a/RenderSystems/Metal/src/OgreMetalTextureManager.mm b/RenderSystems/Metal/src/OgreMetalTextureManager.mm deleted file mode 100644 index 9c9ed17df27..00000000000 --- a/RenderSystems/Metal/src/OgreMetalTextureManager.mm +++ /dev/null @@ -1,109 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2016 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreMetalTextureManager.h" -#include "OgreMetalTexture.h" -#include "OgreMetalMappings.h" -#include "OgreMetalDevice.h" - -namespace Ogre -{ - id MetalSampler::getState() - { - if(!mDirty) - return mSampler; - - MTLSamplerDescriptor *samplerDescriptor = [MTLSamplerDescriptor new]; - samplerDescriptor.minFilter = MetalMappings::get( mMinFilter ); - samplerDescriptor.magFilter = MetalMappings::get( mMagFilter ); - samplerDescriptor.mipFilter = MetalMappings::getMipFilter( mMipFilter ); - samplerDescriptor.maxAnisotropy = mMaxAniso; - samplerDescriptor.sAddressMode = MetalMappings::get( mAddressMode.u ); - samplerDescriptor.tAddressMode = MetalMappings::get( mAddressMode.v ); - samplerDescriptor.rAddressMode = MetalMappings::get( mAddressMode.w ); - samplerDescriptor.normalizedCoordinates = YES; - //samplerDescriptor.lodMinClamp = newBlock->mMinLod; - //samplerDescriptor.lodMaxClamp = newBlock->mMaxLod; - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - const bool supportsCompareFunction = - [mDevice->mDevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily3_v1]; -#else - const bool supportsCompareFunction = true; -#endif - - if( supportsCompareFunction && mCompareEnabled ) - { - samplerDescriptor.compareFunction = MetalMappings::get( mCompareFunc ); - } - - mSampler = [mDevice->mDevice newSamplerStateWithDescriptor:samplerDescriptor]; - - mDirty = false; - - return mSampler; - } - - MetalTextureManager::MetalTextureManager( MetalDevice *device ) : - TextureManager(), - mDevice( device ) - { - ResourceGroupManager::getSingleton()._registerResourceManager(mResourceType, this); - } - - MetalTextureManager::~MetalTextureManager() - { - // unregister with group manager - ResourceGroupManager::getSingleton()._unregisterResourceManager(mResourceType); - } - - Resource* MetalTextureManager::createImpl(const String& name, - ResourceHandle handle, const String& group, bool isManual, - ManualResourceLoader* loader, const NameValuePairList* createParams) - { - return new MetalTexture( this, name, handle, group, isManual, loader, mDevice ); - } - - SamplerPtr MetalTextureManager::_createSamplerImpl() - { - return std::make_shared(mDevice); - } - - PixelFormat MetalTextureManager::getNativeFormat(TextureType ttype, PixelFormat format, int usage) - { - if( format == PF_R8G8B8 ) - return PF_X8R8G8B8; - if( format == PF_B8G8R8 ) - return PF_X8B8G8R8; - - if(MetalMappings::getPixelFormat( format, false ) != MTLPixelFormatInvalid) - return format; - - return PF_BYTE_RGBA; - } -} diff --git a/RenderSystems/Metal/src/Windowing/OSX/OgreMetalView.mm b/RenderSystems/Metal/src/Windowing/OSX/OgreMetalView.mm deleted file mode 100644 index 5e17180078d..00000000000 --- a/RenderSystems/Metal/src/Windowing/OSX/OgreMetalView.mm +++ /dev/null @@ -1,119 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2016 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#import "OgreMetalView.h" - -#import -#import - -@implementation OgreMetalView -{ -} - -+ (Class)layerClass -{ - return [CAMetalLayer class]; -} - -- (void)initCommon -{ - self.layer = [CAMetalLayer layer]; - self.wantsLayer = YES; - - _layerSizeDidUpdate = YES; -} - -- (void)viewDidMoveToWindow -{ - //if(self.scaleToNative) - // [setContentScaleFactor:self.window.screen.backingScaleFactor * self.nativeScaleFactor]; - _layerSizeDidUpdate = YES; -} - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS -- (id)initWithFrame:(CGRect)frame -#else -- (id)initWithFrame:(NSRect)frame -#endif -{ - self = [super initWithFrame:frame]; - - if( self ) - { - [self initCommon]; - } - - return self; -} - -- (instancetype)initWithCoder:(NSCoder *)coder -{ - self = [super initWithCoder:coder]; - - if( self ) - { - [self initCommon]; - } - return self; -} - -- (BOOL)acceptsFirstMouse:(NSEvent *)theEvent -{ - if(self.superview == nil) { - return NO; - } else { - return [self.superview acceptsFirstMouse:theEvent]; - } -} - -- (void)setContentScaleFactor:(CGFloat)contentScaleFactor -{ - self.scaleToNative = false; - //[super setContentScaleFactor:contentScaleFactor]; - _layerSizeDidUpdate = YES; -} - -- (void)setFrameSize:(NSSize)newSize -{ - [super setFrameSize:newSize]; - _layerSizeDidUpdate = YES; -} - -- (void)setBoundsSize:(NSSize)newSize -{ - [super setBoundsSize:newSize]; - _layerSizeDidUpdate = YES; -} - -- (void)viewDidChangeBackingProperties -{ - [super viewDidChangeBackingProperties]; - _layerSizeDidUpdate = YES; -} - -@end diff --git a/RenderSystems/Metal/src/Windowing/iOS/OgreMetalView.mm b/RenderSystems/Metal/src/Windowing/iOS/OgreMetalView.mm deleted file mode 100644 index 9eda96ebc26..00000000000 --- a/RenderSystems/Metal/src/Windowing/iOS/OgreMetalView.mm +++ /dev/null @@ -1,111 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2016 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#import "OgreMetalView.h" - -#import - -@implementation OgreMetalView -{ -} - -+ (Class)layerClass -{ - return [CAMetalLayer class]; -} - -- (void)initCommon -{ - self.opaque = YES; - self.backgroundColor = nil; - self.scaleToNative = true; - self.nativeScaleFactor = 1.0; - self.presentationTime = -1.0; -} - -- (void)didMoveToWindow -{ - if( self.scaleToNative ) - [super setContentScaleFactor:self.window.screen.nativeScale * self.nativeScaleFactor]; - _layerSizeDidUpdate = YES; -} - -- (id)initWithFrame:(CGRect)frame -{ - self = [super initWithFrame:frame]; - - if( self ) - { - [self initCommon]; - } - - return self; -} - -- (instancetype)initWithCoder:(NSCoder *)coder -{ - self = [super initWithCoder:coder]; - - if( self ) - { - [self initCommon]; - } - return self; -} - -- (void)setContentScaleFactor:(CGFloat)contentScaleFactor -{ - self.scaleToNative = false; - [super setContentScaleFactor:contentScaleFactor]; - _layerSizeDidUpdate = YES; -} - -- (void)layoutSubviews -{ - [super layoutSubviews]; - - _layerSizeDidUpdate = YES; -} - -//- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event -//{ -//} - -//- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event -//{ -//} - -//- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event -//{ -//} - -//- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event -//{ -//} - -@end diff --git a/RenderSystems/Tiny/CMakeLists.txt b/RenderSystems/Tiny/CMakeLists.txt deleted file mode 100644 index b91d50a9550..00000000000 --- a/RenderSystems/Tiny/CMakeLists.txt +++ /dev/null @@ -1,36 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES ${PROJECT_BINARY_DIR}/include/OgreTinyExports.h) -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp") - -add_definitions(${OGRE_VISIBILITY_FLAGS}) - -add_library(RenderSystem_Tiny ${OGRE_LIB_TYPE} ${HEADER_FILES} ${SOURCE_FILES}) -target_link_libraries(RenderSystem_Tiny PUBLIC OgreMain PRIVATE) -target_include_directories(RenderSystem_Tiny PUBLIC - "$" - $) - -find_package(OpenMP QUIET) -if(OpenMP_CXX_FOUND) - target_link_libraries(RenderSystem_Tiny PUBLIC OpenMP::OpenMP_CXX) -endif() - -if(SDL2_FOUND) - target_link_libraries(RenderSystem_Tiny PRIVATE SDL2::SDL2) -endif() - -generate_export_header(RenderSystem_Tiny - EXPORT_MACRO_NAME _OgreTinyExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreTinyExports.h) - -ogre_config_framework(RenderSystem_Tiny) -ogre_config_plugin(RenderSystem_Tiny) diff --git a/RenderSystems/Tiny/include/OgreTinyDepthBuffer.h b/RenderSystems/Tiny/include/OgreTinyDepthBuffer.h deleted file mode 100644 index d104372cf06..00000000000 --- a/RenderSystems/Tiny/include/OgreTinyDepthBuffer.h +++ /dev/null @@ -1,26 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT -#ifndef __TinyDepthBuffer_H__ -#define __TinyDepthBuffer_H__ - -#include "OgreDepthBuffer.h" -#include "OgreImage.h" - -namespace Ogre -{ - class TinyDepthBuffer : public DepthBuffer - { - Ogre::Image mBuffer; - public: - TinyDepthBuffer(uint16 poolId, uint32 width, uint32 height, uint32 fsaa, bool manual) - : DepthBuffer(poolId, width, height, fsaa, manual) - { - mBuffer.create(PF_FLOAT32_R, width, height); - } - - Image* getImage() { return &mBuffer; } - }; -} -#endif diff --git a/RenderSystems/Tiny/include/OgreTinyHardwarePixelBuffer.h b/RenderSystems/Tiny/include/OgreTinyHardwarePixelBuffer.h deleted file mode 100644 index c29417ccf4c..00000000000 --- a/RenderSystems/Tiny/include/OgreTinyHardwarePixelBuffer.h +++ /dev/null @@ -1,32 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT -#ifndef __TinyHardwarePixelBuffer_H__ -#define __TinyHardwarePixelBuffer_H__ - -#include "OgreHardwarePixelBuffer.h" - -namespace Ogre { - class TinyHardwarePixelBuffer: public HardwarePixelBuffer - { - PixelBox mBuffer; - public: - /// Should be called by HardwareBufferManager - TinyHardwarePixelBuffer(const PixelBox& data, Usage usage); - - /// Lock a box - PixelBox lockImpl(const Box &lockBox, LockOptions options) override { return mBuffer.getSubVolume(lockBox); } - - /// Unlock a box - void unlockImpl(void) override {} - - /// @copydoc HardwarePixelBuffer::blitFromMemory - void blitFromMemory(const PixelBox &src, const Box &dstBox) override; - - /// @copydoc HardwarePixelBuffer::blitToMemory - void blitToMemory(const Box &srcBox, const PixelBox &dst) override; - }; -} - -#endif diff --git a/RenderSystems/Tiny/include/OgreTinyPlugin.h b/RenderSystems/Tiny/include/OgreTinyPlugin.h deleted file mode 100644 index a3c35528777..00000000000 --- a/RenderSystems/Tiny/include/OgreTinyPlugin.h +++ /dev/null @@ -1,31 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT -#ifndef __TinyPlugin_H__ -#define __TinyPlugin_H__ - -#include "OgrePlugin.h" -#include "OgreTinyExports.h" - -namespace Ogre -{ -/** Plugin instance for Tiny Manager */ -class _OgreTinyExport TinyPlugin : public Plugin -{ -public: - TinyPlugin(); - - const String& getName() const override; - - void install() override; - void initialise() override; - void shutdown() override; - void uninstall() override; - -protected: - RenderSystem* mRenderSystem; -}; -} // namespace Ogre - -#endif diff --git a/RenderSystems/Tiny/include/OgreTinyRenderSystem.h b/RenderSystems/Tiny/include/OgreTinyRenderSystem.h deleted file mode 100644 index ee37a3eb11a..00000000000 --- a/RenderSystems/Tiny/include/OgreTinyRenderSystem.h +++ /dev/null @@ -1,173 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#ifndef __TinyRenderSystem_H__ -#define __TinyRenderSystem_H__ - -#include "OgreRenderWindow.h" -#include "OgreRenderSystem.h" - -namespace Ogre { - /** \addtogroup RenderSystems RenderSystems - * @{ - */ - /** \defgroup Tiny Tiny - * Software rasterizer Implementation as a rendering system. - * @{ - */ - class HardwareBufferManager; - - struct IShader { - // typedefs to make Ogre types more GLSLy - typedef Vector<2, float> vec2; - typedef Vector<3, float> vec3; - typedef Vector<4, float> vec4; - typedef Vector<3, uchar> vec3b; - typedef Vector<4, uchar> vec4b; - - typedef Matrix3 mat3; - typedef Matrix4 mat4; - - static int mod(int a, int b) { - return (b + (a % b)) % b; - } - - static const vec4b& sample2D(const Image& img, const vec2& uv) - { - Vector2i uvi(uv.x * (img.getWidth() - 1), uv.y * (img.getHeight() - 1)); - return *img.getData(mod(uvi[0], img.getWidth()), mod(uvi[1], img.getHeight())); - } - - virtual bool fragment(const vec3& bar, ColourValue& gl_FragColor) = 0; - }; - - /** - Software rasterizer Implementation as a rendering system. - */ - class TinyRenderSystem : public RenderSystem - { - Matrix4 mVP; // viewport transform - - Image* mActiveColourBuffer; - Image* mActiveDepthBuffer; - - struct DefaultShader : public IShader - { - mat4 uniform_MVP; - mat4 uniform_Tex; - mat4 uniform_MVIT; - vec3 uniform_lightDir; - ColourValue uniform_ambientCol; - - bool uniform_doLighting; - - const Image* image; - - vec2 var_uv[3]; - vec3 var_normal[3]; - - void vertex(const vec4& vertex, const vec2* uv, const vec3* normal, int gl_VertexID, - vec4& gl_Position); - bool fragment(const vec3& bar, ColourValue& gl_FragColor) override; - } mDefaultShader; - - bool mDepthTest; - bool mDepthWrite; - bool mBlendAdd; - - HardwareBufferManager* mHardwareBufferManager; - - /// Check if the GL system has already been initialised - bool mGLInitialised; - public: - // Default constructor / destructor - TinyRenderSystem(); - ~TinyRenderSystem(); - - Real getMinimumDepthInputValue(void) override { return -1.0f; } // Range [-1.0f, 1.0f] - Real getMaximumDepthInputValue(void) override { return 1.0f; } // Range [-1.0f, 1.0f] - void _convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest, bool) override { dest = matrix; } - - void setConfigOption(const String &name, const String &value) override {} - - // ---------------------------------- - // Overridden RenderSystem functions - // ---------------------------------- - - const String& getName(void) const override; - - RenderSystemCapabilities* createRenderSystemCapabilities() const override; - - void initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary) override; - - void shutdown(void) override; - - /// @copydoc RenderSystem::_createRenderWindow - RenderWindow* _createRenderWindow(const String &name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams = 0) override; - - /// @copydoc RenderSystem::_createDepthBufferFor - DepthBuffer* _createDepthBufferFor( RenderTarget *renderTarget ) override; - - /// @copydoc RenderSystem::createMultiRenderTarget - MultiRenderTarget * createMultiRenderTarget(const String & name) override; - - // ----------------------------- - // Low-level overridden members - // ----------------------------- - void _setTexture(size_t unit, bool enabled, const TexturePtr &tex) override; - - void _setSampler(size_t unit, Sampler& sampler) override; - - - void setLightingEnabled(bool enabled) override { mDefaultShader.uniform_doLighting = enabled; } - - void _setViewport(Viewport *vp) override; - - void _endFrame(void) override; - - void _setCullingMode(CullingMode mode) override; - - void _setDepthBufferParams(bool depthTest = true, bool depthWrite = true, CompareFunction depthFunction = CMPF_LESS_EQUAL) override; - - void _setDepthBias(float constantBias, float slopeScaleBias) override; - - void setColourBlendState(const ColourBlendState& state) override; - - void _setPolygonMode(PolygonMode level) override; - - void setStencilState(const StencilState& state) override {} - - void applyFixedFunctionParams(const GpuProgramParametersPtr& params, uint16 variabilityMask) override; - - void _render(const RenderOperation& op) override; - - void setScissorTest(bool enabled, const Rect& rect = Rect()) override; - - void clearFrameBuffer(unsigned int buffers, - const ColourValue& colour = ColourValue::Black, - float depth = 1.0f, unsigned short stencil = 0) override; - HardwareOcclusionQuery* createHardwareOcclusionQuery(void) override; - - /** - * Set current render target to target, enabling its GL context if needed - */ - void _setRenderTarget(RenderTarget *target) override; - - void bindGpuProgramParameters(GpuProgramType gptype, - const GpuProgramParametersPtr& params, uint16 variabilityMask) override {} - - /// @copydoc RenderSystem::_setAlphaRejectSettings - void _setAlphaRejectSettings( CompareFunction func, unsigned char value, bool alphaToCoverage ) override; - - void beginProfileEvent( const String &eventName ) override {} - void endProfileEvent( void ) override {} - void markProfileEvent( const String &eventName ) override {} - }; - /** @} */ - /** @} */ -} - -#endif diff --git a/RenderSystems/Tiny/include/OgreTinyTexture.h b/RenderSystems/Tiny/include/OgreTinyTexture.h deleted file mode 100644 index 33b399d37c9..00000000000 --- a/RenderSystems/Tiny/include/OgreTinyTexture.h +++ /dev/null @@ -1,29 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT -#ifndef __TinyTexture_H__ -#define __TinyTexture_H__ - -#include "OgreTexture.h" - -namespace Ogre { - class TinyTexture : public Texture - { - public: - // Constructor - TinyTexture(ResourceManager* creator, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader); - - Image* getImage() { return &mBuffer; } - - virtual ~TinyTexture(); - - protected: - Image mBuffer; - void createInternalResourcesImpl(void) override; - void freeInternalResourcesImpl(void) override {} - }; -} - -#endif diff --git a/RenderSystems/Tiny/include/OgreTinyTextureManager.h b/RenderSystems/Tiny/include/OgreTinyTextureManager.h deleted file mode 100644 index dd67932891c..00000000000 --- a/RenderSystems/Tiny/include/OgreTinyTextureManager.h +++ /dev/null @@ -1,29 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT -#ifndef __TinyTextureManager_H__ -#define __TinyTextureManager_H__ - -#include "OgreTextureManager.h" -#include "OgreTexture.h" - -namespace Ogre { - class TinyTextureManager : public TextureManager - { - public: - TinyTextureManager(); - virtual ~TinyTextureManager(); - - /// @copydoc TextureManager::getNativeFormat - PixelFormat getNativeFormat(TextureType ttype, PixelFormat format, int usage) override; - - protected: - /// @copydoc ResourceManager::createImpl - Resource* createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams) override; - }; -} - -#endif diff --git a/RenderSystems/Tiny/include/OgreTinyWindow.h b/RenderSystems/Tiny/include/OgreTinyWindow.h deleted file mode 100644 index b145830d119..00000000000 --- a/RenderSystems/Tiny/include/OgreTinyWindow.h +++ /dev/null @@ -1,41 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#ifndef __GLWindow_H__ -#define __GLWindow_H__ - -#include "OgreRenderWindow.h" -#include "OgreImage.h" - -struct SDL_Window; - -namespace Ogre -{ - class _OgrePrivate TinyWindow : public RenderWindow - { - public: - TinyWindow(); - - void create(const String& name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams) override; - - void destroy(void) override {} - - void resize(unsigned int width, unsigned int height) override; - - void copyContentsToMemory(const Box& src, const PixelBox &dst, FrameBuffer buffer) override; - bool requiresTextureFlipping() const override { return true; } - - Image* getImage() { return &mBuffer; } - - void swapBuffers() override; - - protected: - Image mBuffer; - SDL_Window* mParentWindow; - }; -} - -#endif diff --git a/RenderSystems/Tiny/src/OgreTinyHardwarePixelBuffer.cpp b/RenderSystems/Tiny/src/OgreTinyHardwarePixelBuffer.cpp deleted file mode 100644 index da4cfa274ff..00000000000 --- a/RenderSystems/Tiny/src/OgreTinyHardwarePixelBuffer.cpp +++ /dev/null @@ -1,54 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT -#include "OgreTinyHardwarePixelBuffer.h" - -namespace Ogre { - - TinyHardwarePixelBuffer::TinyHardwarePixelBuffer(const PixelBox& data, Usage usage) - : HardwarePixelBuffer(data.getWidth(), data.getHeight(), data.getDepth(), data.format, usage, false), mBuffer(data) - { - } - - void TinyHardwarePixelBuffer::blitFromMemory(const PixelBox &src, const Box &dstBox) - { - if (!mBuffer.contains(dstBox)) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Destination box out of range"); - } - - PixelBox scaled; - if (src.getSize() != dstBox.getSize()) - { - // Scale to destination size. - // This also does pixel format conversion if needed. - scaled = mBuffer.getSubVolume(dstBox); - Image::scale(src, scaled, Image::FILTER_BILINEAR); - } - else - { - scaled = mBuffer.getSubVolume(dstBox); - PixelUtil::bulkPixelConversion(src, scaled); - } - } - - void TinyHardwarePixelBuffer::blitToMemory(const Box &srcBox, const PixelBox &dst) - { - if (!mBuffer.contains(srcBox)) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "source box out of range"); - } - - if(srcBox.getSize() != dst.getSize()) - { - // We need scaling - Image::scale(mBuffer.getSubVolume(srcBox), dst, Image::FILTER_BILINEAR); - } - else - { - // Just copy the bit that we need - PixelUtil::bulkPixelConversion(mBuffer.getSubVolume(srcBox), dst); - } - } -} diff --git a/RenderSystems/Tiny/src/OgreTinyPlugin.cpp b/RenderSystems/Tiny/src/OgreTinyPlugin.cpp deleted file mode 100644 index 55bce3995bb..00000000000 --- a/RenderSystems/Tiny/src/OgreTinyPlugin.cpp +++ /dev/null @@ -1,63 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#include "OgreTinyPlugin.h" -#include "OgreRoot.h" -#include "OgreTinyRenderSystem.h" -#include "OgreTinyExports.h" - -namespace Ogre -{ -const String sPluginName = "Tiny RenderSystem"; - -TinyPlugin::TinyPlugin() : mRenderSystem(0) {} - -const String& TinyPlugin::getName() const -{ - return sPluginName; -} - -void TinyPlugin::install() -{ - mRenderSystem = OGRE_NEW TinyRenderSystem(); - - Root::getSingleton().addRenderSystem(mRenderSystem); -} - -void TinyPlugin::initialise() -{ - // nothing to do -} - -void TinyPlugin::shutdown() -{ - // nothing to do -} - -void TinyPlugin::uninstall() -{ - OGRE_DELETE mRenderSystem; - mRenderSystem = 0; -} - -#ifndef OGRE_STATIC_LIB -static TinyPlugin* plugin; - -extern "C" void _OgreTinyExport dllStartPlugin(void); -extern "C" void _OgreTinyExport dllStopPlugin(void); - -extern "C" void _OgreTinyExport dllStartPlugin(void) -{ - plugin = OGRE_NEW TinyPlugin(); - Root::getSingleton().installPlugin(plugin); -} - -extern "C" void _OgreTinyExport dllStopPlugin(void) -{ - Root::getSingleton().uninstallPlugin(plugin); - OGRE_DELETE plugin; -} -#endif -} // namespace Ogre diff --git a/RenderSystems/Tiny/src/OgreTinyRenderSystem.cpp b/RenderSystems/Tiny/src/OgreTinyRenderSystem.cpp deleted file mode 100644 index 8ca302e331c..00000000000 --- a/RenderSystems/Tiny/src/OgreTinyRenderSystem.cpp +++ /dev/null @@ -1,465 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#include "OgreTinyRenderSystem.h" - -#include "OgreRenderSystem.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "OgreTinyTextureManager.h" -#include "OgreHardwareBuffer.h" -#include "OgreGpuProgramManager.h" -#include "OgreException.h" -#include "OgreTinyDepthBuffer.h" -#include "OgreTinyHardwarePixelBuffer.h" -#include "OgreDefaultHardwareBufferManager.h" -#include "OgreRoot.h" -#include "OgreConfig.h" -#include "OgreViewport.h" -#include "OgreTinyWindow.h" -#include "OgreTinyTexture.h" - -#include "tinyrenderer.h" - -namespace Ogre { - TinyRenderSystem::TinyRenderSystem() - : mHardwareBufferManager(0) - { - LogManager::getSingleton().logMessage(getName() + " created."); - - initConfigOptions(); - - // create params - GpuLogicalBufferStructPtr logicalBufferStruct(new GpuLogicalBufferStruct()); - mFixedFunctionParams.reset(new GpuProgramParameters); - mFixedFunctionParams->_setLogicalIndexes(logicalBufferStruct); - mFixedFunctionParams->setAutoConstant(0, GpuProgramParameters::ACT_WORLDVIEWPROJ_MATRIX); - mFixedFunctionParams->setAutoConstant(4, GpuProgramParameters::ACT_TEXTURE_MATRIX); - mFixedFunctionParams->setAutoConstant(8, GpuProgramParameters::ACT_DERIVED_AMBIENT_LIGHT_COLOUR); - mFixedFunctionParams->setAutoConstant(9, GpuProgramParameters::ACT_LIGHT_POSITION); - mFixedFunctionParams->setAutoConstant(10, GpuProgramParameters::ACT_INVERSE_TRANSPOSE_WORLDVIEW_MATRIX); - - mActiveRenderTarget = 0; - mGLInitialised = false; - } - - - void TinyRenderSystem::applyFixedFunctionParams(const GpuProgramParametersPtr& params, uint16 mask) - { - // Autoconstant index is not a physical index - for (const auto& ac : params->getAutoConstants()) - { - // Only update needed slots - if (ac.variability & mask) - { - const float* ptr = params->getFloatPointer(ac.physicalIndex); - switch(ac.paramType) - { - case GpuProgramParameters::ACT_WORLDVIEWPROJ_MATRIX: - mDefaultShader.uniform_MVP = Matrix4(ptr); - break; - case GpuProgramParameters::ACT_TEXTURE_MATRIX: - mDefaultShader.uniform_Tex = Matrix4(ptr); - break; - case GpuProgramParameters::ACT_DERIVED_AMBIENT_LIGHT_COLOUR: - memcpy(mDefaultShader.uniform_ambientCol.ptr(), ptr, sizeof(float)*4); - break; - case GpuProgramParameters::ACT_LIGHT_POSITION: - // ptr[3] ? LIGHT_POINT : LIGHT_DIRECTIONAL; - mDefaultShader.uniform_lightDir = ptr[3] ? Vector3(ptr).normalisedCopy() : -Vector3(ptr); - break; - case GpuProgramParameters::ACT_INVERSE_TRANSPOSE_WORLDVIEW_MATRIX: - mDefaultShader.uniform_MVIT = Matrix4(ptr); - break; - default: - // ignore - break; - } - } - } - } - - TinyRenderSystem::~TinyRenderSystem() - { - shutdown(); - } - - const String& TinyRenderSystem::getName(void) const - { - static String strName("Tiny Rendering Subsystem"); - return strName; - } - RenderSystemCapabilities* TinyRenderSystem::createRenderSystemCapabilities() const - { - RenderSystemCapabilities* rsc = OGRE_NEW RenderSystemCapabilities(); - - rsc->setDriverVersion(mDriverVersion); - - rsc->setRenderSystemName(getName()); - rsc->setNumTextureUnits(1); - - rsc->setCapability(RSC_FIXED_FUNCTION); - - // Vertex Buffer Objects are always supported - rsc->setCapability(RSC_MAPBUFFER); - - // Check for non-power-of-2 texture support - rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES); - - // As are user clipping planes - rsc->setCapability(RSC_USER_CLIP_PLANES); - - // So are 1D & 3D textures - rsc->setCapability(RSC_TEXTURE_1D); - rsc->setCapability(RSC_TEXTURE_3D); - rsc->setCapability(RSC_TEXTURE_2D_ARRAY); - - rsc->setCapability(RSC_32BIT_INDEX); - - rsc->setCapability(RSC_DEPTH_CLAMP); - - rsc->setCapability(RSC_VERTEX_BUFFER_INSTANCE_DATA); - - // Check for Float textures - rsc->setCapability(RSC_TEXTURE_FLOAT); - - rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH); - - return rsc; - } - - void TinyRenderSystem::initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary) - { - // Use VBO's by default - mHardwareBufferManager = new DefaultHardwareBufferManager(); - - // Create the texture manager - mTextureManager = new TinyTextureManager(); - - mGLInitialised = true; - } - - void TinyRenderSystem::shutdown(void) - { - RenderSystem::shutdown(); - - OGRE_DELETE mHardwareBufferManager; - mHardwareBufferManager = 0; - - OGRE_DELETE mTextureManager; - mTextureManager = 0; - - mGLInitialised = 0; - } - - RenderWindow* TinyRenderSystem::_createRenderWindow(const String &name, unsigned int width, unsigned int height, - bool fullScreen, const NameValuePairList *miscParams) - { - RenderSystem::_createRenderWindow(name, width, height, fullScreen, miscParams); - - // Create the window - RenderWindow* win = new TinyWindow(); - win->create(name, width, height, fullScreen, miscParams); - attachRenderTarget(*win); - - if (!mGLInitialised) - { - LogManager::getSingleton().logMessage("**************************************"); - LogManager::getSingleton().logMessage("*** Tiny Renderer Started ***"); - LogManager::getSingleton().logMessage("**************************************"); - - // Initialise GL after the first window has been created - // TODO: fire this from emulation options, and don't duplicate Real and Current capabilities - mRealCapabilities = createRenderSystemCapabilities(); - - // use real capabilities if custom capabilities are not available - if (!mUseCustomCapabilities) - mCurrentCapabilities = mRealCapabilities; - - fireEvent("RenderSystemCapabilitiesCreated"); - - initialiseFromRenderSystemCapabilities(mCurrentCapabilities, (RenderTarget *) win); - } - - if ( win->getDepthBufferPool() != DepthBuffer::POOL_NO_DEPTH ) - { - // Unlike D3D9, OGL doesn't allow sharing the main depth buffer, so keep them separate. - // Only Copy does, but Copy means only one depth buffer... - auto *depthBuffer = new TinyDepthBuffer( DepthBuffer::POOL_DEFAULT, - win->getWidth(), win->getHeight(), - win->getFSAA(), true ); - - mDepthBufferPool[depthBuffer->getPoolId()].push_back( depthBuffer ); - - win->attachDepthBuffer( depthBuffer ); - } - - return win; - } - - - DepthBuffer* TinyRenderSystem::_createDepthBufferFor( RenderTarget *rt ) - { - // No "custom-quality" multisample for now in GL - return new TinyDepthBuffer(0, rt->getWidth(), rt->getHeight(), rt->getFSAA(), false); - } - - MultiRenderTarget* TinyRenderSystem::createMultiRenderTarget(const String & name) - { - return NULL; - } - - void TinyRenderSystem::_setTexture(size_t stage, bool enabled, const TexturePtr &texPtr) - { - if(stage > 0) - return; - - if(!enabled || !texPtr) - { - mDefaultShader.image = NULL; - return; - } - - mDefaultShader.image = static_cast(texPtr.get())->getImage(); - } - - void TinyRenderSystem::_setSampler(size_t unit, Sampler& sampler) - { - } - - void TinyRenderSystem::_setAlphaRejectSettings(CompareFunction func, unsigned char value, bool alphaToCoverage) - { - } - - void TinyRenderSystem::_setViewport(Viewport *vp) - { - // Check if viewport is different - if (!vp) - { - mActiveViewport = NULL; - _setRenderTarget(NULL); - } - - else if (vp != mActiveViewport || vp->_isUpdated()) - { - RenderTarget* target; - - target = vp->getTarget(); - _setRenderTarget(target); - mActiveViewport = vp; - - // Calculate the "lower-left" corner of the viewport - Rect vpRect = vp->getActualDimensions(); - if (!target->requiresTextureFlipping()) - { - // Convert "upper-left" corner to "lower-left" - std::swap(vpRect.top, vpRect.bottom); - vpRect.top = target->getHeight() - vpRect.top; - vpRect.bottom = target->getHeight() - vpRect.bottom; - } - - mVP.makeTransform({vpRect.left + vpRect.width() / 2.f, vpRect.top + vpRect.height() / 2.f, 0.5}, - {vpRect.width() / 2.f, vpRect.height() / 2.f, 0.5}, Ogre::Quaternion::IDENTITY); - - vp->_clearUpdatedFlag(); - } - } - - void TinyRenderSystem::_endFrame(void) - { - } - - void TinyRenderSystem::_setCullingMode(CullingMode mode) - { - mCullingMode = mode; - } - - void TinyRenderSystem::_setDepthBufferParams(bool depthTest, bool depthWrite, CompareFunction depthFunction) - { - mDepthTest = depthTest; - mDepthWrite = depthWrite; - } - - void TinyRenderSystem::_setDepthBias(float constantBias, float slopeScaleBias) - { - - } - - void TinyRenderSystem::setColourBlendState(const ColourBlendState& state) - { - mBlendAdd = state.destFactor == SBF_ONE; - } - - HardwareOcclusionQuery* TinyRenderSystem::createHardwareOcclusionQuery(void) - { - return NULL; - } - - void TinyRenderSystem::_setPolygonMode(PolygonMode level) - { - - } - - void TinyRenderSystem::DefaultShader::vertex(const vec4& vertex, const vec2* uv, const vec3* normal, - int gl_VertexID, vec4& gl_Position) - { - gl_Position = uniform_MVP * vertex; - - if(uv) - var_uv[gl_VertexID] = (uniform_Tex*vec4(uv->x, uv->y, 0, 1)).xy(); - - if(normal) - var_normal[gl_VertexID] = uniform_MVIT.linear() * *normal; - } - bool TinyRenderSystem::DefaultShader::fragment(const vec3& bar, ColourValue& gl_FragColor) - { - if(image) - { - vec2 uv = var_uv[0]*bar.x + var_uv[1]*bar.y + var_uv[2]*bar.z; - - const vec4b& tex = sample2D(*image, uv); - - if(tex[3] < 1) - return true; - - gl_FragColor = ColourValue(tex.ptr()); - } - - if(uniform_doLighting) - { - vec3 n = var_normal[0]*bar.x + var_normal[1]*bar.y + var_normal[2]*bar.z; - float diffuse = std::max(0.f, n.dotProduct(uniform_lightDir)); - gl_FragColor *= diffuse; - gl_FragColor += uniform_ambientCol; - } - - return false; - } - - static uchar* getData(const RenderOperation& op, VertexElementSemantic sem, size_t& step) - { - auto element = op.vertexData->vertexDeclaration->findElementBySemantic(sem); - if(!element) - return NULL; - - step = op.vertexData->vertexDeclaration->getVertexSize(element->getSource()); - - auto buf = op.vertexData->vertexBufferBinding->getBuffer(element->getSource()); - uchar* ret = (uchar*)buf->lock(HardwareBuffer::HBL_NORMAL); - buf->unlock(); // no real locking performed - return ret + element->getOffset() + op.vertexData->vertexStart * step; - } - - void TinyRenderSystem::_render(const RenderOperation& op) - { - // Call super class. - RenderSystem::_render(op); - - bool isStrip = op.operationType == RenderOperation::OT_TRIANGLE_STRIP; - - if(!isStrip && op.operationType != RenderOperation::OT_TRIANGLE_LIST) // only triangle list/ strip supported - return; - - size_t posStep; - auto posData = getData(op, VES_POSITION, posStep); - OgreAssert(posData, "VES_POSITION required"); - - size_t uvStep = 0; - auto uvData = getData(op, VES_TEXTURE_COORDINATES, uvStep); - - size_t normStep = 0; - uchar* normData = getData(op, VES_NORMAL, normStep);; - - mDefaultShader.uniform_doLighting &= bool(normData); - - int16* idx16Data = NULL; - int32* idx32Data = NULL; - size_t drawCount = op.vertexData->vertexCount; - if (op.useIndexes) - { - if(op.indexData->indexBuffer->getIndexSize() == 2) - { - idx16Data = (int16*)op.indexData->indexBuffer->lock(HardwareBuffer::HBL_NORMAL); - idx16Data += op.indexData->indexStart; - } - else - { - idx32Data = (int32*)op.indexData->indexBuffer->lock(HardwareBuffer::HBL_NORMAL); - idx32Data += op.indexData->indexStart; - } - op.indexData->indexBuffer->unlock(); - drawCount = op.indexData->indexCount; - } - - Vector3f* v = NULL; - Vector2* uv = NULL; - Vector3f* n = NULL; - vec4 clip_vert[3]; // triangle coordinates (clip coordinates), written by VS, read by FS - do - { - for(size_t i = 0; i < drawCount; i += 3) - { - if (i && isStrip) - i -= 2; - for(int j= 0; j < 3; j++) - { - int idx = i + j; - idx = idx16Data ? idx16Data[idx] : (idx32Data ? idx32Data[idx] : idx); - v = (Vector3f*)(posData + posStep*idx); - uv = (Vector2*)(uvData + uvStep*idx); - n = (Vector3f*)(normData + normStep*idx); - mDefaultShader.vertex(vec4(*v), uv, n, j, clip_vert[j]); - } - triangle(mVP, clip_vert, mDefaultShader, *mActiveColourBuffer, *mActiveDepthBuffer, - mDepthTest, mDepthWrite, mBlendAdd, !isStrip); - } - - } while (updatePassIterationRenderState()); - } - - void TinyRenderSystem::setScissorTest(bool enabled, const Rect& rect) - { - - } - - void TinyRenderSystem::clearFrameBuffer(unsigned int buffers, - const ColourValue& colour, - float depth, unsigned short stencil) - { - if (buffers & FBT_COLOUR) - { - mActiveColourBuffer->setTo(colour); - } - if (buffers & FBT_DEPTH) - { - mActiveDepthBuffer->setTo(ColourValue(depth)); - } - } - - void TinyRenderSystem::_setRenderTarget(RenderTarget *target) - { - mActiveRenderTarget = target; - - if (!target) - return; - - if(auto win = dynamic_cast(target)) - { - mActiveColourBuffer = win->getImage(); - mActiveDepthBuffer = dynamic_cast(win->getDepthBuffer())->getImage(); - } - - // Check the depth buffer status - auto *depthBuffer = target->getDepthBuffer(); - - if ( target->getDepthBufferPool() != DepthBuffer::POOL_NO_DEPTH && - (!depthBuffer) ) - { - // Depth is automatically managed and there is no depth buffer attached to this RT - // or the Current context doesn't match the one this Depth buffer was created with - setDepthBufferFor( target ); - } - } -} diff --git a/RenderSystems/Tiny/src/OgreTinyTexture.cpp b/RenderSystems/Tiny/src/OgreTinyTexture.cpp deleted file mode 100644 index fcbf375f22c..00000000000 --- a/RenderSystems/Tiny/src/OgreTinyTexture.cpp +++ /dev/null @@ -1,62 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#include "OgreTinyTexture.h" -#include "OgreTinyRenderSystem.h" -#include "OgreHardwareBufferManager.h" -#include "OgreTinyHardwarePixelBuffer.h" -#include "OgreBitwise.h" -#include "OgreTextureManager.h" - -namespace Ogre { - TinyTexture::TinyTexture(ResourceManager* creator, const String& name, - ResourceHandle handle, const String& group, bool isManual, - ManualResourceLoader* loader) - : Texture(creator, name, handle, group, isManual, loader) - { - mMipmapsHardwareGenerated = false; - } - - TinyTexture::~TinyTexture() - { - // have to call this here rather than in Resource destructor - // since calling virtual methods in base destructors causes crash - unload(); - } - - // Creation / loading methods - void TinyTexture::createInternalResourcesImpl(void) - { - // set HardwareBuffer::Usage for TU_RENDERTARGET if nothing else specified - if((mUsage & TU_RENDERTARGET) && (mUsage & ~TU_RENDERTARGET) == 0) - mUsage |= HardwareBuffer::HBU_DYNAMIC; - - // Adjust format if required. - mFormat = TextureManager::getSingleton().getNativeFormat(mTextureType, mFormat, mUsage); - - mNumMipmaps = mNumRequestedMipmaps = 0; - - mBuffer.create(mFormat, mWidth, mHeight, mDepth, getNumFaces(), mNumMipmaps); - - mSurfaceList.clear(); - - for (uint8 face = 0; face < getNumFaces(); face++) - { - for (uint32 mip = 0; mip <= getNumMipmaps(); mip++) - { - TinyHardwarePixelBuffer* buf = - new TinyHardwarePixelBuffer(mBuffer.getPixelBox(face, mip), mUsage); - mSurfaceList.push_back(HardwarePixelBufferSharedPtr(buf)); - } - } - - // Generate mipmaps after all texture levels have been loaded - // This is required for compressed formats such as DXT - if (mUsage & TU_AUTOMIPMAP) - { - - } - } -} diff --git a/RenderSystems/Tiny/src/OgreTinyTextureManager.cpp b/RenderSystems/Tiny/src/OgreTinyTextureManager.cpp deleted file mode 100644 index af5a6c9fbfb..00000000000 --- a/RenderSystems/Tiny/src/OgreTinyTextureManager.cpp +++ /dev/null @@ -1,38 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#include "OgreTinyTextureManager.h" -#include "OgreRenderSystem.h" -#include "OgreRenderTexture.h" -#include "OgreTinyTexture.h" -#include "OgreRoot.h" - -namespace Ogre -{ -TinyTextureManager::TinyTextureManager() -{ - // Register with group manager - ResourceGroupManager::getSingleton()._registerResourceManager(mResourceType, this); -} - -TinyTextureManager::~TinyTextureManager() -{ - // Unregister with group manager - ResourceGroupManager::getSingleton()._unregisterResourceManager(mResourceType); -} - -Resource* TinyTextureManager::createImpl(const String& name, ResourceHandle handle, const String& group, - bool isManual, ManualResourceLoader* loader, - const NameValuePairList* createParams) -{ - return new TinyTexture(this, name, handle, group, isManual, loader); -} - -PixelFormat TinyTextureManager::getNativeFormat(TextureType ttype, PixelFormat format, int usage) -{ - // only byte formats supported - return PF_BYTE_RGBA; -} -} // namespace Ogre diff --git a/RenderSystems/Tiny/src/OgreTinyWindow.cpp b/RenderSystems/Tiny/src/OgreTinyWindow.cpp deleted file mode 100644 index 5744535afcf..00000000000 --- a/RenderSystems/Tiny/src/OgreTinyWindow.cpp +++ /dev/null @@ -1,82 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#include "OgreTinyWindow.h" -#include "OgreException.h" -#include "OgreStringConverter.h" - -#include "OgreComponents.h" -#if OGRE_BITES_HAVE_SDL -#include -#endif - -namespace Ogre -{ -TinyWindow::TinyWindow() : mParentWindow(NULL) -{ - mIsFullScreen = false; - mActive = true; -} - -void TinyWindow::create(const String& name, uint width, uint height, - bool fullScreen, const NameValuePairList *miscParams) -{ - mName = name; - - if(miscParams) - { - auto it = miscParams->find("sdlwin"); - if(it != miscParams->end()) - mParentWindow = (SDL_Window*)StringConverter::parseSizeT(it->second); - } - - resize(width, height); -} - -void TinyWindow::resize(uint width, uint height) -{ - mWidth = width; - mHeight = height; - mBuffer.create(PF_BYTE_RGB, width, height); -} - -void TinyWindow::swapBuffers() -{ -#if OGRE_BITES_HAVE_SDL - if(!mParentWindow) - return; - - SDL_Surface* surface = SDL_GetWindowSurface(mParentWindow); - - SDL_LockSurface(surface); - - auto format = surface->format->BytesPerPixel == 4 ? PF_BYTE_BGRA : PF_BYTE_BGR; - - PixelBox dst(surface->w, surface->h, 1, format, surface->pixels); - dst.rowPitch = surface->pitch/surface->format->BytesPerPixel; - dst.data = (uchar*)surface->pixels; - - copyContentsToMemory(dst, dst, FB_BACK); - - SDL_UnlockSurface(surface); - - SDL_UpdateWindowSurface(mParentWindow); -#endif -} - -void TinyWindow::copyContentsToMemory(const Box& src, const PixelBox& dst, FrameBuffer buffer) -{ - if (mClosed) - return; - - if (src.right > mWidth || src.bottom > mHeight || src.front != 0 || src.back != 1 || - dst.getWidth() != src.getWidth() || dst.getHeight() != src.getHeight() || dst.getDepth() != 1) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Invalid box"); - } - - PixelUtil::bulkPixelConversion(mBuffer.getPixelBox().getSubVolume(src), dst); -} -} // namespace Ogre diff --git a/RenderSystems/Tiny/src/tinyrenderer.h b/RenderSystems/Tiny/src/tinyrenderer.h deleted file mode 100644 index eb517e8fd51..00000000000 --- a/RenderSystems/Tiny/src/tinyrenderer.h +++ /dev/null @@ -1,97 +0,0 @@ -/** -Tiny Renderer, https://github.com/ssloy/tinyrenderer -Copyright Dmitry V. Sokolov - -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. -*/ -#include -#include - -namespace Ogre { -typedef Vector<2, float> vec2; -typedef Vector<3, float> vec3; -typedef Vector<4, float> vec4; -typedef Vector<3, uchar> vec3b; -typedef Vector<4, uchar> vec4b; - -typedef Matrix3 mat3; -typedef Matrix4 mat4; - - -static vec3 barycentric(const vec2 tri[3], const vec2& P) { - mat3 ABC(tri[0].x, tri[1].x, tri[2].x, - tri[0].y, tri[1].y, tri[2].y, - 1, 1, 1); - //if (ABC.determinant()<1e-6) return vec3(-1,1,1); // for a degenerate triangle generate negative coordinates, it will be thrown away by the rasterizator - return ABC.inverse() * vec3(P.x, P.y, 1); -} - -static float cross(const vec2 &v1, const vec2 &v2) { - return v1.x * v2.y - v1.y * v2.x; -} - -/// triangle screen coordinates before persp. division -static void triangle(const mat4& Viewport, const vec4 clip_verts[3], IShader& shader, Image& image, - Image& zbuffer, bool depthCheck, bool depthWrite, bool blendAdd, bool doCull) -{ - vec4 pts[3] = { Viewport*clip_verts[0], Viewport*clip_verts[1], Viewport*clip_verts[2] }; // triangle screen coordinates before persp. division - for (int i = 0; i < 3; i++) - { - float w = pts[i][3]; - pts[i] /= w; - pts[i][3] = 1 / w; - } - - vec2 pts2[3] = { pts[0].xy(), pts[1].xy(), pts[2].xy() }; // triangle screen coordinates after perps. division - - if(doCull && cross(pts2[2] - pts2[0], pts2[2] - pts2[1]) > 0) - return; // culled - - vec2 bboxmin( std::numeric_limits::max(), std::numeric_limits::max()); - vec2 bboxmax(-std::numeric_limits::max(), -std::numeric_limits::max()); - vec2 clamp(image.getWidth()-1, image.getHeight()-1); - for (int i=0; i<3; i++) - for (int j=0; j<2; j++) { - bboxmin[j] = std::max(0.f, std::min(bboxmin[j], pts2[i][j])); - bboxmax[j] = std::min(clamp[j], std::max(bboxmax[j], pts2[i][j])); - } - -#pragma omp parallel for - for (int x=(int)bboxmin.x; x<=(int)bboxmax.x; x++) { - for (int y=(int)bboxmin.y; y<=(int)bboxmax.y; y++) { - vec3 bc_screen = barycentric(pts2, vec2(x, y)); - vec3 bc_clip = vec3(bc_screen.x*pts[0][3], bc_screen.y*pts[1][3], bc_screen.z*pts[2][3]); - bc_clip = bc_clip/(bc_clip.x+bc_clip.y+bc_clip.z); // check https://github.com/ssloy/tinyrenderer/wiki/Technical-difficulties-linear-interpolation-with-perspective-deformations - float frag_depth = vec3(pts[0][2], pts[1][2], pts[2][2]).dotProduct(bc_clip); - if (bc_screen.x<0 || bc_screen.y<0 || bc_screen.z<0) continue; - - if (frag_depth < 0.0) - continue; - - if(depthCheck && frag_depth > *zbuffer.getData(x, y)) - continue; - - ColourValue fragColour; - bool discard = shader.fragment(bc_clip, fragColour); - if (discard) continue; - auto& dst = *image.getData(x, y); - if(blendAdd) - fragColour += ColourValue(vec4b(dst[0], dst[1], dst[2], 0).ptr()); - fragColour.saturate(); - fragColour *= 255; - - dst = vec3b(fragColour.ptr()); - if (depthWrite) - *zbuffer.getData(x, y) = frag_depth; - } - } -} -} \ No newline at end of file diff --git a/RenderSystems/Vulkan/CMakeLists.txt b/RenderSystems/Vulkan/CMakeLists.txt deleted file mode 100755 index 630e6dae0db..00000000000 --- a/RenderSystems/Vulkan/CMakeLists.txt +++ /dev/null @@ -1,59 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure Vulkan RenderSystem build - -file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/*.h") -list(APPEND HEADER_FILES ${PROJECT_BINARY_DIR}/include/OgreVulkanExports.h) -file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/src/volk.c") - -set( HEADER_FILES ${HEADER_FILES}) -set( SOURCE_FILES ${SOURCE_FILES}) - -add_library(RenderSystem_Vulkan ${OGRE_LIB_TYPE} ${HEADER_FILES} ${SOURCE_FILES}) - -if(WIN32) - target_include_directories(RenderSystem_Vulkan PRIVATE $ENV{VULKAN_SDK}/Include) - target_link_directories(RenderSystem_Vulkan PRIVATE $ENV{VULKAN_SDK}/Lib) - - set_source_files_properties("${CMAKE_CURRENT_SOURCE_DIR}/src/volk.c" - PROPERTIES COMPILE_DEFINITIONS VK_USE_PLATFORM_WIN32_KHR) -elseif(ANDROID) - set_source_files_properties("${CMAKE_CURRENT_SOURCE_DIR}/src/volk.c" - PROPERTIES COMPILE_DEFINITIONS VK_USE_PLATFORM_ANDROID_KHR) -else() - set_source_files_properties("${CMAKE_CURRENT_SOURCE_DIR}/src/volk.c" - PROPERTIES COMPILE_DEFINITIONS VK_USE_PLATFORM_XLIB_KHR) - target_link_libraries(RenderSystem_Vulkan PRIVATE ${X11_LIBRARIES}) -endif() - -if(UNIX) - set_source_files_properties(src/vma.cpp - PROPERTIES COMPILE_FLAGS "-Wno-implicit-fallthrough -Wno-unused-variable -Wno-parentheses -Wno-unused-function") -endif() - -#target_compile_features(RenderSystem_Vulkan PRIVATE cxx_std_17) -target_link_libraries(RenderSystem_Vulkan PUBLIC OgreMain PRIVATE ${CMAKE_DL_LIBS}) - -target_include_directories(RenderSystem_Vulkan PUBLIC - "$" - "$" - $) - - -generate_export_header(RenderSystem_Vulkan - EXPORT_MACRO_NAME _OgreVulkanExport - EXPORT_FILE_NAME ${PROJECT_BINARY_DIR}/include/OgreVulkanExports.h) - -ogre_config_framework(RenderSystem_Vulkan) - -ogre_config_plugin(RenderSystem_Vulkan) -install(FILES ${HEADER_FILES} DESTINATION include/OGRE/RenderSystems/Vulkan) -install(FILES ${PLATFORM_HEADERS} DESTINATION include/OGRE/RenderSystems/Vulkan/${PLATFORM_HEADER_INSTALL}) -install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include DESTINATION include/OGRE/RenderSystems/Vulkan) diff --git a/RenderSystems/Vulkan/include/OgreVulkanDescriptorPool.h b/RenderSystems/Vulkan/include/OgreVulkanDescriptorPool.h deleted file mode 100644 index 32dbdfc1aad..00000000000 --- a/RenderSystems/Vulkan/include/OgreVulkanDescriptorPool.h +++ /dev/null @@ -1,60 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-present Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _OgreVulkanDescriptorPool_H_ -#define _OgreVulkanDescriptorPool_H_ - -#include "OgreVulkanPrerequisites.h" - -namespace Ogre -{ - /** - @brief The VulkanDescriptorPool class - A VulkanDescriptorPool manages the pool of a single set (i.e. one VkDescriptorSetLayout) - */ - class VulkanDescriptorPool - { - std::vector mPools; - std::vector mDescriptorsUsedPerPool; - std::vector mPoolSizes; - VkDescriptorSetLayout mLayout; - - size_t mCurrentPoolIdx; - - VulkanDevice *mDevice; - - void createNewPool(); - public: - VulkanDescriptorPool(const std::vector& poolSizes, VkDescriptorSetLayout layout, - VulkanDevice* device); - ~VulkanDescriptorPool(); - - VkDescriptorSet allocate(); - }; -} // namespace Ogre - -#endif diff --git a/RenderSystems/Vulkan/include/OgreVulkanDevice.h b/RenderSystems/Vulkan/include/OgreVulkanDevice.h deleted file mode 100644 index 6449c6bc556..00000000000 --- a/RenderSystems/Vulkan/include/OgreVulkanDevice.h +++ /dev/null @@ -1,114 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-present Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef _OgreVulkanDevice_H_ -#define _OgreVulkanDevice_H_ - -#include "OgreVulkanPrerequisites.h" - -#include "OgreVulkanQueue.h" - -#include "OgreHeaderPrefix.h" - -#include "vk_mem_alloc.h" - -namespace Ogre -{ - struct _OgreVulkanExport VulkanDevice - { - struct SelectedQueue - { - VulkanQueue::QueueFamily usage; - uint32 familyIdx; - uint32 queueIdx; - SelectedQueue(); - }; - - // clang-format off - VkInstance mInstance; - VkPhysicalDevice mPhysicalDevice; - VkDevice mDevice; - - VmaAllocator mVmaAllocator; - - VkQueue mPresentQueue; - /// Graphics queue is *guaranteed by spec* to also be able to run compute and transfer - /// A GPU may not have a graphics queue though (Ogre can't run there) - VulkanQueue mGraphicsQueue; - /// Additional compute queues to run async compute (besides the main graphics one) - FastArray mComputeQueues; - /// Additional transfer queues to run async transfers (besides the main graphics one) - FastArray mTransferQueues; - // clang-format on - - VkPhysicalDeviceProperties mDeviceProperties; - VkPhysicalDeviceMemoryProperties mDeviceMemoryProperties; - VkPhysicalDeviceFeatures mDeviceFeatures; - FastArray mQueueProps; - - VulkanRenderSystem *mRenderSystem; - - uint32 mSupportedStages; - - static void destroyQueues( FastArray &queueArray ); - - void findGraphicsQueue( FastArray &inOutUsedQueueCount ); - void findComputeQueue( FastArray &inOutUsedQueueCount, uint32 maxNumQueues ); - void findTransferQueue( FastArray &inOutUsedQueueCount, uint32 maxNumQueues ); - - void fillQueueCreationInfo( uint32 maxComputeQueues, uint32 maxTransferQueues, - FastArray &outQueueCiArray ); - - public: - VulkanDevice( VkInstance instance, uint32 deviceIdx, VulkanRenderSystem *renderSystem ); - ~VulkanDevice(); - - static VkInstance createInstance( FastArray &extensions, - FastArray &layers, - PFN_vkDebugReportCallbackEXT debugCallback ); - - void createPhysicalDevice( uint32 deviceIdx ); - - void createDevice( FastArray &extensions, uint32 maxComputeQueues, - uint32 maxTransferQueues ); - - void initQueues( void ); - - void commitAndNextCommandBuffer( - SubmissionType::SubmissionType submissionType = SubmissionType::FlushOnly ); - - /// Waits for the GPU to finish all pending commands. - void stall( void ); - - VmaAllocator getAllocator() const { return mVmaAllocator; } - }; -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/RenderSystems/Vulkan/include/OgreVulkanHardwareBuffer.h b/RenderSystems/Vulkan/include/OgreVulkanHardwareBuffer.h deleted file mode 100644 index c26d008cbad..00000000000 --- a/RenderSystems/Vulkan/include/OgreVulkanHardwareBuffer.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#ifndef _OgreVulkanHardwareBufferCommon_H_ -#define _OgreVulkanHardwareBufferCommon_H_ - -#include "OgreVulkanPrerequisites.h" - -#include "OgreHardwareBuffer.h" - -#include "vk_mem_alloc.h" - -namespace Ogre -{ - class VulkanHardwareBuffer : public HardwareBuffer - { - private: - VkBuffer mBuffer; - VmaAllocation mAllocation; - VulkanDevice *mDevice; - uint32 mTarget; - void *mMappedPtr; - - void discard(); - public: - VulkanHardwareBuffer(uint32 target, size_t sizeBytes, Usage usage, bool useShadowBuffer, VulkanDevice* device); - virtual ~VulkanHardwareBuffer(); - - void _notifyDeviceStalled(void) {} - - VkBuffer getVkBuffer() const { return mBuffer; } - - void* lockImpl(size_t offset, size_t length, LockOptions options) override; - void unlockImpl() override; - - void readData( size_t offset, size_t length, void *pDest ) override; - - void writeData( size_t offset, size_t length, const void *pSource, - bool discardWholeBuffer = false ) override; - - void copyData( HardwareBuffer& srcBuffer, size_t srcOffset, size_t dstOffset, - size_t length, bool discardWholeBuffer = false ) override; - - void _updateFromShadow() override; - }; -} - -#endif diff --git a/RenderSystems/Vulkan/include/OgreVulkanHardwareBufferManager.h b/RenderSystems/Vulkan/include/OgreVulkanHardwareBufferManager.h deleted file mode 100644 index e289b576fb4..00000000000 --- a/RenderSystems/Vulkan/include/OgreVulkanHardwareBufferManager.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#ifndef _OgreVulkanHardwareBufferManager_H_ -#define _OgreVulkanHardwareBufferManager_H_ - -#include "OgreVulkanPrerequisites.h" -#include "OgreHardwareBufferManager.h" - -namespace Ogre -{ - class _OgreVulkanExport VulkanHardwareBufferManager : public HardwareBufferManager - { - VulkanDevice *mDevice;; - OGRE_MUTEX(mIndexBuffersMutex); - IndexBufferList mIndexBuffers; - public: - VulkanHardwareBufferManager( VulkanDevice *device ); - virtual ~VulkanHardwareBufferManager(); - - void _notifyDeviceStalled( void ); - - HardwareVertexBufferSharedPtr createVertexBuffer( size_t vertexSize, size_t numVerts, - HardwareBuffer::Usage usage, bool useShadowBuffer ) override; - HardwareIndexBufferSharedPtr createIndexBuffer( HardwareIndexBuffer::IndexType itype, - size_t numIndexes, HardwareBuffer::Usage usage, bool useShadowBuffer ) override; - HardwareBufferPtr createUniformBuffer(size_t sizeBytes, - HardwareBufferUsage usage = HBU_CPU_TO_GPU, - bool useShadowBuffer = false) override; - }; -} - -#endif \ No newline at end of file diff --git a/RenderSystems/Vulkan/include/OgreVulkanMappings.h b/RenderSystems/Vulkan/include/OgreVulkanMappings.h deleted file mode 100644 index 464c205b657..00000000000 --- a/RenderSystems/Vulkan/include/OgreVulkanMappings.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-present Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#ifndef _OgreVulkanMappings_H_ -#define _OgreVulkanMappings_H_ - -#include "OgreVulkanPrerequisites.h" - -#include "OgreBlendMode.h" -#include "OgrePixelFormat.h" -#include "OgreTexture.h" -#include "OgreRenderOperation.h" -#include "OgreRenderSystem.h" - -namespace Ogre -{ - class _OgreVulkanExport VulkanMappings - { - public: - static VkPrimitiveTopology get( RenderOperation::OperationType opType ); - static VkPolygonMode get( PolygonMode polygonMode ); - static VkCullModeFlags get( CullingMode cullMode ); - static VkCompareOp get( CompareFunction compareFunc ); - static VkStencilOp get( StencilOperation stencilOp ); - - static VkBlendFactor get( SceneBlendFactor blendFactor ); - static VkBlendOp get( SceneBlendOperation blendOp ); - - static VkFormat get( VertexElementType vertexElemType ); - - static VkFilter get( FilterOptions filter ); - static VkSamplerMipmapMode getMipFilter( FilterOptions filter ); - static VkSamplerAddressMode get( TextureAddressingMode mode ); - - static VkImageViewType get( TextureType textureType ); - static VkFormat get( PixelFormat pf, bool hwGamma = false); - static VkImageAspectFlags getImageAspect( PixelFormatGpu pf, - const bool bPreferDepthOverStencil = false ); - - static VkAccessFlags get( const TextureGpu *texture ); - }; -} // namespace Ogre - -#endif diff --git a/RenderSystems/Vulkan/include/OgreVulkanPlugin.h b/RenderSystems/Vulkan/include/OgreVulkanPlugin.h deleted file mode 100644 index bfccb391e64..00000000000 --- a/RenderSystems/Vulkan/include/OgreVulkanPlugin.h +++ /dev/null @@ -1,64 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __VulkanPlugin_H__ -#define __VulkanPlugin_H__ - -#include "OgrePlugin.h" -#include "OgreVulkanExports.h" - -namespace Ogre -{ - class VulkanRenderSystem; - - /** Plugin instance for Vulkan Manager */ - class _OgreVulkanExport VulkanPlugin : public Plugin - { - public: - VulkanPlugin(); - - /// @copydoc Plugin::getName - const String &getName() const override; - - /// @copydoc Plugin::install - void install() override; - - /// @copydoc Plugin::initialise - void initialise() override; - - /// @copydoc Plugin::shutdown - void shutdown() override; - - /// @copydoc Plugin::uninstall - void uninstall() override; - - protected: - VulkanRenderSystem *mRenderSystem; - }; -} // namespace Ogre - -#endif diff --git a/RenderSystems/Vulkan/include/OgreVulkanPrerequisites.h b/RenderSystems/Vulkan/include/OgreVulkanPrerequisites.h deleted file mode 100644 index 65868dbbe3b..00000000000 --- a/RenderSystems/Vulkan/include/OgreVulkanPrerequisites.h +++ /dev/null @@ -1,130 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-present Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _OgreVulkanPrerequisites_H_ -#define _OgreVulkanPrerequisites_H_ - -#include "OgrePrerequisites.h" - -#include "OgreLogManager.h" -#include "OgrePixelFormat.h" - -#include "OgreVulkanExports.h" -#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX -#define VK_USE_PLATFORM_XLIB_KHR -#elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32 -#define VK_USE_PLATFORM_WIN32_KHR -#elif OGRE_PLATFORM == OGRE_PLATFORM_ANDROID -#define VK_USE_PLATFORM_ANDROID_KHR -#endif - -#include - -#define VMA_NULLABLE -#define VMA_NOT_NULL -#define VMA_STATIC_VULKAN_FUNCTIONS 0 - -namespace Ogre -{ - // Forward declarations - class VulkanDescriptorPool; - struct VulkanDevice; - class VulkanGpuProgramManager; - class VulkanProgram; - class VulkanProgramFactory; - class VulkanQueue; - class VulkanRenderSystem; - class VulkanTextureGpu; - class VulkanTextureGpuManager; - class VulkanWindow; - - template - using FastArray = std::vector; - - /// Aligns the input 'offset' to the next multiple of 'alignment'. - /// Alignment can be any value except 0. Some examples: - /// - /// alignToNextMultiple( 0, 4 ) = 0; - /// alignToNextMultiple( 1, 4 ) = 4; - /// alignToNextMultiple( 2, 4 ) = 4; - /// alignToNextMultiple( 3, 4 ) = 4; - /// alignToNextMultiple( 4, 4 ) = 4; - /// alignToNextMultiple( 5, 4 ) = 8; - /// - /// alignToNextMultiple( 0, 3 ) = 0; - /// alignToNextMultiple( 1, 3 ) = 3; - inline size_t alignToNextMultiple( size_t offset, size_t alignment ) - { - return ( (offset + alignment - 1u) / alignment ) * alignment; - } - - class VulkanHardwareBuffer; - - typedef Texture TextureGpu; - typedef PixelFormat PixelFormatGpu; - - namespace SubmissionType - { - enum SubmissionType - { - /// Send the work we have so far to the GPU, but there may be more under way - /// - /// A fence won't be generated automatically to protect this work, but - /// there may be one if getCurrentFence or acquireCurrentFence - /// was called - FlushOnly, - /// Same as FlushOnly + fences the data so that - /// VaoManager::mDynamicBufferCurrentFrame can be incremented and - /// waitForTailFrameToFinish works without stalling. - /// - /// It's like forcing the end of a frame without swapping windows, e.g. - /// when waiting for textures to finish streaming. - NewFrameIdx, - /// Same as NewFrameIdx + swaps windows (presents). - /// This is the real end of the frame. - EndFrameAndSwap - }; - } - -} // namespace Ogre - -#define OGRE_ASSERT_HIGH(x) OgreAssert((x), "high") -#define OGRE_ASSERT_MEDIUM(x) OgreAssert((x), "medium") -#define OGRE_ASSERT_LOW(x) OgreAssert((x), "low") - -#define OGRE_VK_CHECK(vkcall) \ -{ \ - VkResult result = vkcall; \ - if (result != VK_SUCCESS) \ - { \ - String vkfunc = #vkcall; \ - vkfunc = vkfunc.substr(0, vkfunc.find('(')); \ - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, vkfunc + " failed with " + vkResultToString(result)); \ - } \ -} - -#endif //#ifndef _OgreVulkanPrerequisites_H_ diff --git a/RenderSystems/Vulkan/include/OgreVulkanProgram.h b/RenderSystems/Vulkan/include/OgreVulkanProgram.h deleted file mode 100644 index e298b55f997..00000000000 --- a/RenderSystems/Vulkan/include/OgreVulkanProgram.h +++ /dev/null @@ -1,84 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-present Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _OgreVulkanProgram_H_ -#define _OgreVulkanProgram_H_ - -#include "OgreVulkanPrerequisites.h" - -#include "OgreGpuProgramManager.h" - -struct VkVertexInputBindingDescription; -struct VkVertexInputAttributeDescription; - -namespace Ogre -{ - /** Specialisation of GpuProgram to provide support for SPIRV - */ - class VulkanProgram : public GpuProgram - { - public: - VulkanProgram( ResourceManager *creator, const String &name, ResourceHandle handle, - const String &group, bool isManual, ManualResourceLoader *loader, - VulkanDevice *device ); - virtual ~VulkanProgram(); - - const String &getLanguage( void ) const override; - GpuProgramParametersSharedPtr createParameters( void ) override; - - VkPipelineShaderStageCreateInfo getPipelineShaderStageCi() const; - - uint32 getDrawIdLocation() const { return mDrawIdLocation; } - - private: - void loadFromSource() override; - void unloadImpl() override; - - VulkanDevice *mDevice; - VkShaderModule mShaderModule; - uint32 mDrawIdLocation; - }; - - /** Factory class for Vulkan programs. */ - class VulkanProgramFactory : public GpuProgramFactory - { - protected: - String mLanguageName; - VulkanDevice *mDevice; - - public: - VulkanProgramFactory( VulkanDevice *device); - virtual ~VulkanProgramFactory( void ); - /// Get the name of the language this factory creates programs for - const String &getLanguage( void ) const override; - /// Create an instance of VulkanProgram - GpuProgram *create( ResourceManager *creator, const String &name, ResourceHandle handle, - const String &group, bool isManual, ManualResourceLoader *loader ) override; - }; -} // namespace Ogre - -#endif // __VulkanProgram_H__ diff --git a/RenderSystems/Vulkan/include/OgreVulkanQueue.h b/RenderSystems/Vulkan/include/OgreVulkanQueue.h deleted file mode 100644 index 0b19b6bd0df..00000000000 --- a/RenderSystems/Vulkan/include/OgreVulkanQueue.h +++ /dev/null @@ -1,250 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-present Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef _OgreVulkanQueue_H_ -#define _OgreVulkanQueue_H_ - -#include "OgreVulkanPrerequisites.h" - -#include "OgreHeaderPrefix.h" - -#include "vk_mem_alloc.h" - -namespace Ogre -{ - typedef std::vector VkSemaphoreArray; - typedef std::vector VkFenceArray; - struct BufferPacked; - - class _OgreVulkanExport VulkanQueue - { - public: - enum QueueFamily - { - Graphics, - Compute, - Transfer, - NumQueueFamilies - }; - - struct PerFrameData - { - VkCommandPool mCommandPool; - VkCommandBuffer mCommandBuffer; - VkFence mProtectingFence; - - std::vector> mBufferGraveyard; - std::vector> mDescriptorPoolGraveyard; - }; - - enum EncoderState - { - EncoderGraphicsOpen, - EncoderComputeOpen, - EncoderCopyOpen, - EncoderClosed - }; - - VkDevice mDevice; - QueueFamily mFamily; - - uint32 mFamilyIdx; - - uint32 getFamilyIdx() const { return mFamilyIdx; } - - uint32 mQueueIdx; - - VkQueue mQueue; - VkCommandBuffer mCurrentCmdBuffer; - - VulkanDevice *mOwnerDevice; - - uint8 mNumFramesInFlight; - uint8 mCurrentFrameIdx; - protected: - - // clang-format off - // One per buffered frame - FastArray mPerFrameData; - - /// Collection of semaphore we need to wait on before our queue executes - /// pending commands when commitAndNextCommandBuffer is called - VkSemaphoreArray mGpuWaitSemaphForCurrCmdBuff; - FastArray mGpuWaitFlags; - /// Collection of semaphore we will signal when our queue - /// submitted in commitAndNextCommandBuffer is done - VkSemaphoreArray mGpuSignalSemaphForCurrCmdBuff; - // clang-format on - - public: - FastArray mWindowsPendingSwap; - - protected: - VulkanRenderSystem *mRenderSystem; - - VkFence mCurrentFence; - - typedef std::map BufferPackedDownloadMap; - typedef std::map TextureGpuDownloadMap; - - EncoderState mEncoderState; - VkAccessFlags mCopyEndReadSrcBufferFlags; - VkAccessFlags mCopyEndReadDstBufferFlags; - VkAccessFlags mCopyEndReadDstTextureFlags; - VkAccessFlags mCopyStartWriteSrcBufferFlags; - FastArray mImageMemBarriers; - FastArray mImageMemBarrierPtrs; - /// When mCopyDownloadTextures[buffer] = true, this buffer has been last downloaded - /// When mCopyDownloadTextures[buffer] = false, this buffer has been last uploaded - /// When mCopyDownloadTextures[buffer] = not_found, this buffer hasn't been downloaded/uploaded - TextureGpuDownloadMap mCopyDownloadTextures; - /// When mCopyDownloadBuffers[buffer] = true, this buffer has been last downloaded - /// When mCopyDownloadBuffers[buffer] = false, this buffer has been last uploaded - /// When mCopyDownloadBuffers[buffer] = not_found, this buffer hasn't been downloaded/uploaded - BufferPackedDownloadMap mCopyDownloadBuffers; - - static VkPipelineStageFlags deriveStageFromBufferAccessFlags( VkAccessFlags accessFlags ); - static VkPipelineStageFlags deriveStageFromTextureAccessFlags( VkAccessFlags accessFlags ); - - /// Schedules a barrier to be issued in endCopyEncoder - /// This is to RESTORE the texture's layout and force future rendering cmds to wait - /// for our transfer to finish. - void insertRestoreBarrier( VulkanTextureGpu *vkTexture, const VkImageLayout newTransferLayout ); - - /** There will be two barriers that prepareForUpload will generate: - - 1. We must wait until previous commands are done reading from/writing to dst - before we can proceed with a copy command what writes to dst.
- That includes previous copy commands, but we don't because we assume two - consecutive uploads to the same buffer (or textures) are always done to - non-overlapping regions. - 2. At endCopyEncoder: we must ensure future GPU commands wait for our copy - command to end writing to dst before they can start. - - prepareForUpload tries its best to generate no more than 2 barriers (except for - texture layout transitions) between getCopyEncoder and endCopyEncoder, but sometimes - more than 2 barriers may end up being issued - @param buffer - @param texture - */ - void prepareForUpload( const BufferPacked *buffer, TextureGpu *texture ); - - /** There between zero to two barriers that prepareForDownload will generate: - - 1. We must wait until previous commands are done writing to src before we can - proceed with a copy command that reads from src. Some buffers/textures are - guaranteed to be read-only, in this case we can avoid this barrier. - Textures may still need to transition their layout though. - 2. At endCopyEncoder: we must ensure future commands don't write to src before - we're done reading from src. Again, buffers/textures which are guaranteed to - be read-only don't need this. - Textures may still need to transition their layout though - - prepareForDownload tries its best to generate no more than 2 barriers (except for - texture layout transitions) between getCopyEncoder and endCopyEncoder, but sometimes - more than 2 barriers may end up being issued - @param buffer - @param texture - */ - void prepareForDownload( const BufferPacked *buffer, VulkanTextureGpu *texture ); - - public: - VulkanQueue(); - ~VulkanQueue(); - - void setQueueData( VulkanDevice *owner, QueueFamily family, uint32 familyIdx, uint32 queueIdx ); - - void init( VkDevice device, VkQueue queue, VulkanRenderSystem *renderSystem ); - void destroy( void ); - - void queueForDeletion(VkBuffer buffer, VmaAllocation allocation); - void queueForDeletion(const std::shared_ptr& descriptorPool); - protected: - void newCommandBuffer( void ); - void endCommandBuffer( void ); - - public: - EncoderState getEncoderState( void ) const { return mEncoderState; } - - void getGraphicsEncoder( void ); - void getComputeEncoder( void ); - /** Call this function when you need to start copy/transfer operations - - buffer and texture pointers cannot be both nullptr at the same time - - You don't have to pair every getCopyEncoder call with an endCopyEncoder call. In - fact this is discouraged. - - Keep calling getCopyEncoder until you're done with all transfer operations - - @see VulkanQueue::prepareForUpload - @see VulkanQueue::prepareForDownload - @param buffer - The buffer we're copying from/to. Can be nullptr - @param texture - The texture we're copying from/to. Can be nullptr - - If uploading, the texture will be transitioned to VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL - If downloading, the texture will be transitioned to VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL - @param bDownload - True if we plan to do CPU -> GPU transfers - False if we plan to do GPU -> CPU transfers - - If you want to perform GPU -> GPU transfers, then you need to call: - @code - queue->getCopyEncoder( src, src, true ); - queue->getCopyEncoder( dst, dst, false ); - @endcode - */ - void getCopyEncoder( const BufferPacked *buffer, VulkanTextureGpu *texture, const bool bDownload ); - void getCopyEncoderV1Buffer( const bool bDownload ); - - void endCopyEncoder( void ); - void endRenderEncoder( const bool endRenderPassDesc = true ); - void endComputeEncoder( void ); - - void endAllEncoders( bool endRenderPassDesc = true ); - - void notifyTextureDestroyed( VulkanTextureGpu *texture ); - - /// When we'll call commitAndNextCommandBuffer, we'll have to wait for - /// this semaphore on to execute STAGE_COLOR_ATTACHMENT_OUTPUT_BIT - void addWindowToWaitFor( VkSemaphore imageAcquisitionSemaph ); - - void _waitOnFrame( uint8 frameIdx ); - bool _isFrameFinished( uint8 frameIdx ); - - void commitAndNextCommandBuffer( - SubmissionType::SubmissionType submissionType = SubmissionType::FlushOnly ); - }; - -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/RenderSystems/Vulkan/include/OgreVulkanRenderPassDescriptor.h b/RenderSystems/Vulkan/include/OgreVulkanRenderPassDescriptor.h deleted file mode 100644 index bccf8fb77ec..00000000000 --- a/RenderSystems/Vulkan/include/OgreVulkanRenderPassDescriptor.h +++ /dev/null @@ -1,144 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-present Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef _OgreVulkanRenderPassDescriptor_H_ -#define _OgreVulkanRenderPassDescriptor_H_ - -#include "OgreVulkanPrerequisites.h" - -#include "OgreCommon.h" -#include "OgrePixelFormat.h" - -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - // forward compatibility defines - class VulkanRenderPassDescriptor; - typedef VulkanRenderPassDescriptor RenderPassDescriptor; - - struct VulkanFrameBufferDescValue - { - uint16 refCount; - - uint32 mNumImageViews; - VkImageView mImageViews[OGRE_MAX_MULTIPLE_RENDER_TARGETS * 2u + 2u]; - FastArray mWindowImageViews; // Only used by windows - // We normally need just one, but Windows are a special case - // because we need to have one per swapchain image, hence FastArray - // - // A single VkFramebuffer contains the VkRenderPass + the actual imageviews + resolution - FastArray mFramebuffers; - - /// Contains baked info of load/store/clear - /// Doesn't reference ImageViews, however it mentions them by attachmentIdx - /// which makes VkRenderPass difficult to actually share - /// - /// Thus we generate VkRenderPass and FBOs together - VkRenderPass mRenderPass; - - VulkanFrameBufferDescValue(); - }; - - typedef std::unordered_map VulkanFrameBufferDescMap; - - class _OgreVulkanExport VulkanRenderPassDescriptor - { - public: - VulkanTextureGpu* mColour[1]; - VulkanTextureGpu* mDepth; - uint8 mNumColourEntries = 0; - uint8 mSlice = 0; - private: - // 1 per MRT - // 1 per MRT MSAA resolve - // 1 for Depth buffer - // 1 for Stencil buffer - VkClearValue mClearValues[OGRE_MAX_MULTIPLE_RENDER_TARGETS * 2u + 2u]; - - VulkanFrameBufferDescMap::iterator mSharedFboItor; - - /// This value MUST be set to the resolution of any of the textures. - /// If it's changed arbitrarily then FrameBufferDescKey will not take - /// this into account (two RenderPassDescriptors will share the same - /// FBO when they should not) - uint32 mTargetWidth; - uint32 mTargetHeight; - - VulkanQueue *mQueue; - VulkanRenderSystem *mRenderSystem; - - void calculateSharedKey( void ); - - static VkClearColorValue getClearColour( const ColourValue &clearColour, - PixelFormatGpu pixelFormat ); - void setupColourAttachment( const size_t idx, VulkanFrameBufferDescValue &fboDesc, - VkAttachmentDescription *attachments, uint32 &currAttachmIdx, - VkAttachmentReference *colourAttachRefs, - VkAttachmentReference *resolveAttachRefs, const size_t vkIdx, - const bool bResolveTex ); - VkImageView setupDepthAttachment( VkAttachmentDescription &attachment ); - - void setupFbo( VulkanFrameBufferDescValue &fboDesc ); - static void destroyFbo( VulkanQueue *queue, VulkanFrameBufferDescValue &fboDesc ); - public: - VulkanRenderPassDescriptor( VulkanQueue *graphicsQueue, VulkanRenderSystem *renderSystem ); - virtual ~VulkanRenderPassDescriptor(); - - void releaseFbo( void ); - - virtual void entriesModified( bool createFbo ); - - virtual void setClearColour( uint8 idx, const ColourValue &clearColour ); - virtual void setClearDepth( float clearDepth ); - virtual void setClearStencil( uint32 clearStencil ); - - /// Sets the clear colour to all entries. In some APIs may be faster - /// than calling setClearColour( idx, clearColour ) for each entry - /// individually. - virtual void setClearColour( const ColourValue &clearColour ); - - VkRenderPass getRenderPass() const; - - void performLoadActions(); - void performStoreActions(); - }; - - /** @} */ - /** @} */ -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/RenderSystems/Vulkan/include/OgreVulkanRenderSystem.h b/RenderSystems/Vulkan/include/OgreVulkanRenderSystem.h deleted file mode 100644 index c4b232eb881..00000000000 --- a/RenderSystems/Vulkan/include/OgreVulkanRenderSystem.h +++ /dev/null @@ -1,225 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-present Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef _OgreVulkanRenderSystem_H_ -#define _OgreVulkanRenderSystem_H_ - -#include "OgreVulkanPrerequisites.h" - -#include "OgreRenderSystem.h" -#include "OgreVulkanProgram.h" - -#include "OgreVulkanRenderPassDescriptor.h" - -namespace Ogre -{ - class VulkanHardwareBufferManager; - - /** \addtogroup RenderSystems RenderSystems - * @{ - */ - /** \defgroup Vulkan Vulkan - * Implementation of Vulkan as a rendering system. - * @{ - */ - class _OgreVulkanExport VulkanRenderSystem : public RenderSystem - { - friend class VulkanSampler; - bool mInitialized; - VulkanHardwareBufferManager *mHardwareBufferManager; - - VkBuffer mIndirectBuffer; - unsigned char *mSwIndirectBufferPtr; - - VulkanProgramFactory *mSPIRVProgramFactory; - - VkInstance mVkInstance; - - std::vector mDevices; - - HardwareBufferPtr mAutoParamsBuffer; - uint32 mAutoParamsBufferPos; - std::vector mAutoParamsBufferUsage; - - void resizeAutoParamsBuffer(size_t size); - - VulkanDevice *mActiveDevice; - - VulkanDevice *mDevice; - - VulkanRenderPassDescriptor *mCurrentRenderPassDescriptor; - - VulkanFrameBufferDescMap mFrameBufferDescMap; - - bool mHasValidationLayers; - - PFN_vkCreateDebugReportCallbackEXT CreateDebugReportCallback; - PFN_vkDestroyDebugReportCallbackEXT DestroyDebugReportCallback; - VkDebugReportCallbackEXT mDebugReportCallback; - - /// Declared here to avoid constant reallocations - FastArray mImageBarriers; - - void addInstanceDebugCallback( void ); - - void flushRootLayout( void ); - - // Pipeline State Infos - VkGraphicsPipelineCreateInfo pipelineCi; - VkPipelineLayoutCreateInfo pipelineLayoutCi; - VkPipelineVertexInputStateCreateInfo vertexFormatCi; - VkPipelineInputAssemblyStateCreateInfo inputAssemblyCi; - VkPipelineMultisampleStateCreateInfo mssCi; - VkPipelineRasterizationStateCreateInfo rasterState; - VkPipelineColorBlendStateCreateInfo blendStateCi; - std::array shaderStages; - std::array mBoundGpuPrograms; - - // descriptor set layout - std::vector mDescriptorSetBindings; - std::vector mDescriptorPoolSizes; - std::vector mDescriptorWrites; - std::array mUBOInfo; - std::array mUBODynOffsets; - std::array mImageInfos; - VkDescriptorSetLayout mDescriptorSetLayout; - - VkPipelineLayout mLayout; - - std::array blendStates; - - VkPipelineDepthStencilStateCreateInfo depthStencilStateCi; - VkViewport mVkViewport; - VkRect2D mScissorRect; - VkPipelineViewportStateCreateInfo viewportStateCi; - - std::unordered_map mDescriptorSetCache; - std::unordered_map mRenderPassCache; - std::unordered_map mPipelineCache; - - std::shared_ptr mDescriptorPool; - - // clears the pipeline cache - void clearPipelineCache(); - - void initializeVkInstance( void ); - void enumerateDevices(); - uint32 getSelectedDeviceIdx() const; - - VkDescriptorSet getDescriptorSet(); - VkPipeline getPipeline(); - public: - VulkanRenderSystem(); - ~VulkanRenderSystem(); - - void shutdown( void ) override; - - const String &getName( void ) const override; - void refreshConfig(); - void initConfigOptions() override; - void setConfigOption( const String &name, const String &value ) override; - - HardwareOcclusionQuery *createHardwareOcclusionQuery( void ) override; - - RenderSystemCapabilities *createRenderSystemCapabilities( void ) const override; - - void resetAllBindings( void ); - - VkInstance getVkInstance( void ) const { return mVkInstance; } - - RenderWindow *_createRenderWindow( const String &name, uint32 width, uint32 height, - bool fullScreen, const NameValuePairList *miscParams = 0 ) override; - - void flushUAVs( void ); - - void _setTexture( size_t unit, bool enabled, const TexturePtr& texPtr ) override; - - virtual VulkanFrameBufferDescMap &_getFrameBufferDescMap( void ) { return mFrameBufferDescMap; } - - void _beginFrame( void ) override; - void _endFrame( void ) override; - - void _render( const RenderOperation &op ) override; - - void bindGpuProgram(GpuProgram* prg) override; - void bindGpuProgramParameters( GpuProgramType gptype, - const GpuProgramParametersPtr& params, - uint16 variabilityMask ) override; - - Real getHorizontalTexelOffset( void ) override; - Real getVerticalTexelOffset( void ) override; - Real getMinimumDepthInputValue( void ) override; - Real getMaximumDepthInputValue( void ) override; - - void beginProfileEvent( const String &eventName ) override; - void endProfileEvent( void ) override; - void markProfileEvent( const String &event ) override; - - virtual void initGPUProfiling( void ); - virtual void deinitGPUProfiling( void ); - virtual void beginGPUSampleProfile( const String &name, uint32 *hashCache ); - virtual void endGPUSampleProfile( const String &name ); - - void initialiseFromRenderSystemCapabilities( RenderSystemCapabilities *caps, - RenderTarget *primary ) override; - - void executeRenderPassDescriptorDelayedActions( bool officialCall = true ); - void endRenderPassDescriptor(); - - DepthBuffer *_createDepthBufferFor( RenderTarget* renderTarget) override; - - void notifySwapchainDestroyed(); - - VulkanDevice *getVulkanDevice() const { return mDevice; } - void _notifyDeviceStalled(); - - void _notifyActiveEncoderEnded(); - void _notifyActiveComputeEnded( void ); - - void _setViewport(Viewport *vp) override; - void _setRenderTarget(RenderTarget *target) override; - void clearFrameBuffer(unsigned int buffers, const ColourValue& colour = ColourValue::Black, - float depth = 1.0f, unsigned short stencil = 0) override; - void setScissorTest(bool enabled, const Rect& rect = Rect()) override; - void setStencilState(const StencilState& state) override; - void _setPolygonMode(PolygonMode level) override; - void _convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest, bool) override; - void _setDepthBias(float constantBias, float slopeScaleBias = 0.0f) override; - void _setDepthBufferParams(bool depthTest, bool depthWrite, CompareFunction depthFunction) override; - void _setDepthClamp(bool enable) override; - void _setCullingMode(CullingMode mode) override; - void _setAlphaRejectSettings(CompareFunction func, unsigned char value, bool alphaToCoverage) override; - void setColourBlendState(const ColourBlendState& state) override; - void _setSampler(size_t texUnit, Sampler& s) override; - MultiRenderTarget * createMultiRenderTarget(const String & name) override { return NULL; } - }; - /** @} */ - /** @} */ -} // namespace Ogre - -#endif diff --git a/RenderSystems/Vulkan/include/OgreVulkanTextureGpu.h b/RenderSystems/Vulkan/include/OgreVulkanTextureGpu.h deleted file mode 100644 index a18cdd0bdc2..00000000000 --- a/RenderSystems/Vulkan/include/OgreVulkanTextureGpu.h +++ /dev/null @@ -1,190 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2017 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef _OgreVulkanTextureGpu_H_ -#define _OgreVulkanTextureGpu_H_ - -#include "OgreVulkanPrerequisites.h" - -#include "OgreTexture.h" - -#include "OgreHardwarePixelBuffer.h" -#include "OgreVulkanHardwareBuffer.h" -#include "OgreRenderTexture.h" - -#include "vk_mem_alloc.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - - class VulkanRenderPassDescriptor; - - namespace ResourceAccess - { - /// Enum identifying the texture access privilege - enum ResourceAccess - { - Undefined = 0x00, - Read = 0x01, - Write = 0x02, - ReadWrite = Read | Write - }; - } - - class VulkanHardwarePixelBuffer : public HardwarePixelBuffer - { - VulkanTextureGpu* mParent; - uint8 mFace; - uint32 mLevel; - std::unique_ptr mStagingBuffer; - PixelBox lockImpl(const Box &lockBox, LockOptions options) override; - void unlockImpl(void) override; - public: - VulkanHardwarePixelBuffer(VulkanTextureGpu* tex, uint32 width, uint32 height, uint32 depth, uint8 face, uint32 mip); - void blitFromMemory(const PixelBox& src, const Box& dstBox) override; - void blitToMemory(const Box& srcBox, const PixelBox& dst) override; - }; - - class _OgreVulkanExport VulkanTextureGpu : public Texture - { - protected: - /// The general case is that the whole D3D11 texture will be accessed through the SRV. - /// That means: createSrv( this->getPixelFormat(), false ); - /// To avoid creating multiple unnecessary copies of the SRV, we keep a cache of that - /// default SRV with us; and calling createSrv with default params will return - /// this cache instead. - VkImageView mDefaultDisplaySrv; - - /// This will not be owned by us if hasAutomaticBatching is true. - /// It will also not be owned by us if we're not in GpuResidency::Resident - /// This will always point to: - /// * A GL texture owned by us. - /// * A 4x4 dummy texture (now owned by us). - /// * A 64x64 mipmapped texture of us (but now owned by us). - /// * A GL texture not owned by us, but contains the final information. - VkImage mDisplayTextureName; - - /// When we're transitioning to GpuResidency::Resident but we're not there yet, - /// we will be either displaying a 4x4 dummy texture or a 64x64 one. However - /// we reserve a spot to a final place will already be there for us once the - /// texture data is fully uploaded. This variable contains that texture. - /// Async upload operations should stack to this variable. - /// May contain: - /// 1. 0, if not resident or resident but not yet reached main thread. - /// 2. The texture - /// 3. An msaa texture (hasMsaaExplicitResolves == true) - /// 4. The msaa resolved texture (hasMsaaExplicitResolves==false) - /// This value may be a renderbuffer instead of a texture if isRenderbuffer() returns true. - VkImage mFinalTextureName; - VmaAllocation mAllocation; - - /// Only used when hasMsaaExplicitResolves() == false - VkImage mMsaaTextureName; - VmaAllocation mMsaaAllocation; - public: - /// The current layout we're in. Including any internal stuff. - VkImageLayout mCurrLayout; - /// The layout we're expected to be when rendering or doing compute, rather than when doing - /// internal stuff (e.g. this variable won't contain VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, - /// because that origins from C++ operations and are not expected by the compositor) - /// - /// When mCurrLayout != mNextLayout, it means that there is already a layout transition - /// that will be happening to achieve mCurrLayout = mNextLayout - VkImageLayout mNextLayout; - - protected: - void createInternalResourcesImpl( void ) override; - void freeInternalResourcesImpl( void ) override; - - virtual void createMsaaSurface( void ); - virtual void destroyMsaaSurface( void ); - public: - uint32 getNumLayers() const { return mTextureType == TEX_TYPE_2D_ARRAY ? mDepth : getNumFaces(); } - bool hasMsaaExplicitResolves() const { return false; } - bool isUav() const { return false; } - bool isMultisample() const { return mFSAA > 1; } - virtual bool isRenderWindowSpecific() const { return false; } - - VulkanTextureGpu(TextureManager* textureManager, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader); - virtual ~VulkanTextureGpu(); - - VkImageLayout getCurrentLayout( void ) const { return mCurrLayout; } - - virtual void copyTo( TextureGpu *dst, const PixelBox &dstBox, uint8 dstMipLevel, - const PixelBox &srcBox, uint8 srcMipLevel, - bool keepResolvedTexSynced = true, - ResourceAccess::ResourceAccess issueBarriers = ResourceAccess::ReadWrite ); - - void _autogenerateMipmaps( bool bUseBarrierSolver = false ); - - VkImageType getVulkanTextureType( void ) const; - - VkImageViewType getInternalVulkanTextureViewType( void ) const; - - VkImageView _createView(uint8 mipLevel, uint8 numMipmaps, uint16 arraySlice, uint32 numSlices = 0u, - VkImage imageOverride = 0) const; - - VkImageView createView( void ) const; - VkImageView getDefaultDisplaySrv( void ) const { return mDefaultDisplaySrv; } - - void destroyView( VkImageView imageView ); - - /// Returns a fresh VkImageMemoryBarrier filled with common data. - /// srcAccessMask, dstAccessMask, oldLayout and newLayout must be filled by caller - VkImageMemoryBarrier getImageMemoryBarrier( void ) const; - - VkImage getDisplayTextureName( void ) const { return mDisplayTextureName; } - VkImage getFinalTextureName( void ) const { return mFinalTextureName; } - VkImage getMsaaTextureName( void ) const { return mMsaaTextureName; } - }; - - class VulkanRenderTexture : public RenderTexture - { - std::unique_ptr mDepthTexture; - std::unique_ptr mRenderPassDescriptor; - public: - VulkanRenderTexture(const String& name, HardwarePixelBuffer* buffer, uint32 zoffset, VulkanTextureGpu* target, - uint32 face); - - bool requiresTextureFlipping() const override { return true; } - - VulkanRenderPassDescriptor* getRenderPassDescriptor() const { return mRenderPassDescriptor.get(); } - }; - - /** @} */ - /** @} */ -} // namespace Ogre - -#endif diff --git a/RenderSystems/Vulkan/include/OgreVulkanTextureGpuManager.h b/RenderSystems/Vulkan/include/OgreVulkanTextureGpuManager.h deleted file mode 100644 index 1661d8c6fc6..00000000000 --- a/RenderSystems/Vulkan/include/OgreVulkanTextureGpuManager.h +++ /dev/null @@ -1,96 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2017 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef _OgreVulkanTextureGpuManager_H_ -#define _OgreVulkanTextureGpuManager_H_ - -#include "OgreVulkanPrerequisites.h" - -#include "OgreTextureManager.h" - -#include "OgreVulkanDevice.h" -#include "OgreVulkanRenderSystem.h" - -#include "OgreVulkanTextureGpu.h" - -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - /** \addtogroup Core - * @{ - */ - /** \addtogroup Resources - * @{ - */ - - struct StagingTexture; - struct AsyncTextureTicket; - - class VulkanSampler : public Sampler - { - public: - VulkanSampler(VkDevice device); - ~VulkanSampler(); - VkSampler bind(); - private: - VkDevice mDevice; - VkSampler mVkSampler; - }; - - class VulkanTextureGpuManager : public TextureManager - { - protected: - VulkanDevice *mDevice; - - bool mCanRestrictImageViewUsage; - - SamplerPtr _createSamplerImpl() override; - - Resource* createImpl(const String& name, ResourceHandle handle, const String& group, bool isManual, - ManualResourceLoader* loader, const NameValuePairList* createParams) override; - - PixelFormat getNativeFormat(TextureType ttype, PixelFormat format, int usage) override; - public: - VulkanTextureGpuManager(RenderSystem* renderSystem, VulkanDevice* device, bool bCanRestrictImageViewUsage); - virtual ~VulkanTextureGpuManager(); - - VulkanDevice *getDevice() const { return mDevice; } - - bool canRestrictImageViewUsage( void ) const { return mCanRestrictImageViewUsage; } - - virtual bool checkSupport( PixelFormatGpu format, uint32 textureFlags ) const; - }; - - /** @} */ - /** @} */ -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/RenderSystems/Vulkan/include/OgreVulkanTextureGpuWindow.h b/RenderSystems/Vulkan/include/OgreVulkanTextureGpuWindow.h deleted file mode 100644 index f11330913dd..00000000000 --- a/RenderSystems/Vulkan/include/OgreVulkanTextureGpuWindow.h +++ /dev/null @@ -1,67 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-present Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef _OgreVulkanTextureGpuWindow_H_ -#define _OgreVulkanTextureGpuWindow_H_ - -#include "OgreVulkanTextureGpu.h" - -#include "OgreHeaderPrefix.h" - -namespace Ogre -{ - class _OgreVulkanExport VulkanTextureGpuWindow : public VulkanTextureGpu - { - VulkanWindow *mWindow; - uint32 mCurrentImageIdx; - - void createInternalResourcesImpl( void ) override; - void freeInternalResourcesImpl( void ) override; - - public: - VulkanTextureGpuWindow(const String& name, TextureType initialType, TextureManager* textureManager, - VulkanWindow* window); - virtual ~VulkanTextureGpuWindow(); - - bool isRenderWindowSpecific() const override { return true; } - - /// @copydoc VulkanWindow::getImageAcquiredSemaphore - VkSemaphore getImageAcquiredSemaphore( void ); - - void _setCurrentImage( VkImage image, uint32 imageIdx ); - uint32 getCurrentImageIdx( void ) const { return mCurrentImageIdx; } - - VulkanWindow* getWindow() const { return mWindow; } - - void getCustomAttribute( const String& name, void *pData ) override; - }; -} // namespace Ogre - -#include "OgreHeaderSuffix.h" - -#endif diff --git a/RenderSystems/Vulkan/include/OgreVulkanUtils.h b/RenderSystems/Vulkan/include/OgreVulkanUtils.h deleted file mode 100644 index abdd1c6accf..00000000000 --- a/RenderSystems/Vulkan/include/OgreVulkanUtils.h +++ /dev/null @@ -1,43 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-present Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _OgreVulkanUtils_H_ -#define _OgreVulkanUtils_H_ - -#include "OgreVulkanPrerequisites.h" - -#include "OgreString.h" - -namespace Ogre -{ - String vkResultToString( VkResult result ); - - void setObjectName( VkDevice device, uint64_t object, VkDebugReportObjectTypeEXT objectType, - const char *name ); -} // namespace Ogre - -#endif //#ifndef _OgreVulkanPrerequisites_H_ diff --git a/RenderSystems/Vulkan/include/OgreVulkanWindow.h b/RenderSystems/Vulkan/include/OgreVulkanWindow.h deleted file mode 100644 index ee7edaea673..00000000000 --- a/RenderSystems/Vulkan/include/OgreVulkanWindow.h +++ /dev/null @@ -1,169 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _OgreVulkanWindow_H_ -#define _OgreVulkanWindow_H_ - -#include "OgreVulkanPrerequisites.h" - -#include "OgreRenderWindow.h" -#include "OgreVulkanTextureGpuWindow.h" - -namespace Ogre -{ - class VulkanRenderPassDescriptor; - class VulkanWindow : public RenderWindow - { - public: - enum SwapchainStatus - { - /// We already called VulkanWindow::acquireNextImage. - /// - /// Can only go into this state if we're coming from SwapchainReleased - SwapchainAcquired, - /// We already called VulkanWindow::getImageAcquiredSemaphore. - /// Further calls to getImageAcquiredSemaphore will return null. - /// Ogre is rendering or intends to into this swapchain. - /// - /// Can only go into this state if we're coming from SwapchainAcquired - SwapchainUsedInRendering, - /// We've come from SwapchainUsedInRendering and are waiting for - /// VulkanDevice::commitAndNextCommandBuffer to present us - SwapchainPendingSwap, - /// We don't own a swapchain. Ogre cannot render to this window. - /// - /// This status should not last long unless we're not initialized yet. - SwapchainReleased - }; - - bool mLowestLatencyVSync; - bool mHwGamma; - - bool mVisible; - bool mHidden; - - bool mVSync; - int mVSyncInterval; - size_t mWindowHandle = 0; - - VulkanDevice *mDevice; - VulkanTextureGpuWindow* mTexture; - VulkanTextureGpu* mDepthTexture; - - VkSurfaceKHR mSurfaceKHR; - VkSwapchainKHR mSwapchain; - std::vector mSwapchainImages; - std::vector mSwapchainImageViews; - - /// Makes Queue execution wait until the acquired image is done presenting - std::vector mImageReadySemaphores; - std::vector mRenderFinishedSemaphores; - std::vector mImageFences; - int mCurrentSemaphoreIndex; - SwapchainStatus mSwapchainStatus; - - VkSurfaceTransformFlagBitsKHR mSurfaceTransform; - - PixelFormat chooseSurfaceFormat( bool hwGamma ); - void createSwapchain( void ); - void destroySwapchain( void ); - - void createSurface(size_t windowHandle); - - std::unique_ptr mRenderPassDescriptor; - - public: - void acquireNextImage( void ); - - public: - VulkanWindow( const String &title, uint32 width, uint32 height, bool fullscreenMode ); - virtual ~VulkanWindow(); - - static const char *getRequiredExtensionName(); - - VulkanRenderPassDescriptor* getRenderPassDescriptor() const { return mRenderPassDescriptor.get(); } - - VulkanTextureGpu* getTexture() { return mTexture; } - VulkanTextureGpu* getDepthTexture() { return mDepthTexture; } - - VkSurfaceTransformFlagBitsKHR getSurfaceTransform() const { return mSurfaceTransform; } - - void destroy( void ) override; - - void reposition( int32 leftPt, int32 topPt ) override {} - - void setVisible( bool visible ) override { mVisible = visible; } - bool isVisible( void ) const override { return mVisible; } - void setHidden( bool hidden ) override { mHidden = hidden; } - bool isHidden( void ) const override { return mHidden; } - - PixelFormat suggestPixelFormat() const override { return mTexture->getFormat(); } - void copyContentsToMemory(const Box& src, const PixelBox &dst, FrameBuffer buffer = FB_AUTO) override; - - /// Vulkan clip space has inverted Y axis compared to OpenGL - bool requiresTextureFlipping() const override { return true; } - - void resize(unsigned int widthPt, unsigned int heightPt) override; - - void windowMovedOrResized() override; - - void _setDevice( VulkanDevice *device ); - - void create(const String& name, unsigned int widthPt, unsigned int heightPt, bool fullScreen, - const NameValuePairList* miscParams) override; - - /// Returns null if getImageAcquiredSemaphore has already been called during this frame - VkSemaphore getImageAcquiredSemaphore( void ); - - VkSemaphore getRenderFinishedSemaphore() const; - - void setImageFence(VkFence fence) { mImageFences[mCurrentSemaphoreIndex] = fence; } - - const std::vector& getSwapchainImageViews() const { return mSwapchainImageViews; } - - virtual void setVSync( bool vSync, uint32 vSyncInterval ); - - /// Tells our VulkanDevice that the next commitAndNextCommandBuffer call should present us - /// Calling swapBuffers during the command buffer that is rendering to us is key for - /// good performance; otherwise Ogre may split the commands that render to this window - /// and the command that presents this window into two queue submissions. - void swapBuffers( void ) override; - - /** Actually performs present. Called by VulkanDevice::commitAndNextCommandBuffer - @param queueFinishSemaphore - Makes our present request wait until the Queue is done executing before we can present - */ - void _swapBuffers(); - -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - void _notifySurfaceDestroyed() override {} - void _notifySurfaceCreated(void* window, void* config) override {} -#endif - }; -} // namespace Ogre - -#endif diff --git a/RenderSystems/Vulkan/src/OgreVulkanDescriptorPool.cpp b/RenderSystems/Vulkan/src/OgreVulkanDescriptorPool.cpp deleted file mode 100644 index 190bc3399e4..00000000000 --- a/RenderSystems/Vulkan/src/OgreVulkanDescriptorPool.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-present Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreVulkanDescriptorPool.h" - -#include "OgreVulkanDevice.h" -#include "OgreVulkanUtils.h" -#include "OgreException.h" - -namespace Ogre -{ - static const int MAX_POOL_CAPACITY = 50; - //------------------------------------------------------------------------- - VulkanDescriptorPool::VulkanDescriptorPool(const std::vector& poolSizes, - VkDescriptorSetLayout layout, VulkanDevice* device) - : mLayout(layout), mCurrentPoolIdx(0u), mDevice(device) - { - mPoolSizes = poolSizes; - - for(auto& p : mPoolSizes) - p.descriptorCount *= MAX_POOL_CAPACITY; - - createNewPool(); - } - //------------------------------------------------------------------------- - VulkanDescriptorPool::~VulkanDescriptorPool() - { - for(auto p : mPools) - { - vkDestroyDescriptorPool(mDevice->mDevice, p, 0); - } - mPools.clear(); - } - //------------------------------------------------------------------------- - void VulkanDescriptorPool::createNewPool() - { - VkDescriptorPoolCreateInfo poolCi = {VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; - poolCi.flags = 0; - poolCi.poolSizeCount = mPoolSizes.size(); - poolCi.pPoolSizes = mPoolSizes.data(); - poolCi.maxSets = MAX_POOL_CAPACITY; - - mCurrentPoolIdx = mPools.size(); - - // Create the Vulkan descriptor pool - VkDescriptorPool pool; - OGRE_VK_CHECK(vkCreateDescriptorPool( mDevice->mDevice, &poolCi, 0, &pool )); - mPools.push_back(pool); - mDescriptorsUsedPerPool.push_back(0); - } - //------------------------------------------------------------------------- - VkDescriptorSet VulkanDescriptorPool::allocate() - { - if(mDescriptorsUsedPerPool[mCurrentPoolIdx] == MAX_POOL_CAPACITY) - createNewPool(); - - VkDescriptorSetAllocateInfo allocInfo = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; - allocInfo.descriptorPool = mPools[mCurrentPoolIdx]; - allocInfo.descriptorSetCount = 1u; - allocInfo.pSetLayouts = &mLayout; - - VkDescriptorSet handle = VK_NULL_HANDLE; - - // Allocate a new descriptor set from the current pool - VkResult result = vkAllocateDescriptorSets( mDevice->mDevice, &allocInfo, &handle ); - if( result != VK_SUCCESS ) - { - LogManager::getSingleton().logError("vkAllocateDescriptorSets failed! Out of Memory?"); - return VK_NULL_HANDLE; - } - - mDescriptorsUsedPerPool[mCurrentPoolIdx]++; - return handle; - } -} // namespace Ogre diff --git a/RenderSystems/Vulkan/src/OgreVulkanDevice.cpp b/RenderSystems/Vulkan/src/OgreVulkanDevice.cpp deleted file mode 100644 index 303a30f52d6..00000000000 --- a/RenderSystems/Vulkan/src/OgreVulkanDevice.cpp +++ /dev/null @@ -1,346 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-present Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreVulkanDevice.h" - -#include "OgreVulkanRenderSystem.h" -#include "OgreVulkanWindow.h" - -#include "OgreException.h" -#include "OgreStringConverter.h" - -#include "OgreVulkanUtils.h" - -#define TODO_findRealPresentQueue - -namespace Ogre -{ - VulkanDevice::VulkanDevice( VkInstance instance, uint32 deviceIdx, - VulkanRenderSystem *renderSystem ) : - mInstance( instance ), - mPhysicalDevice( 0 ), - mDevice( 0 ), - mPresentQueue( 0 ), - mRenderSystem( renderSystem ), - mSupportedStages( 0xFFFFFFFF ) - { - memset( &mDeviceMemoryProperties, 0, sizeof( mDeviceMemoryProperties ) ); - createPhysicalDevice( deviceIdx ); - } - //------------------------------------------------------------------------- - VulkanDevice::~VulkanDevice() - { - if( mDevice ) - { - vkDeviceWaitIdle( mDevice ); - - mGraphicsQueue.destroy(); - destroyQueues( mComputeQueues ); - destroyQueues( mTransferQueues ); - - vmaDestroyAllocator(mVmaAllocator); - - vkDestroyDevice( mDevice, 0 ); - mDevice = 0; - mPhysicalDevice = 0; - } - } - //------------------------------------------------------------------------- - void VulkanDevice::destroyQueues( FastArray &queueArray ) - { - for (auto& q : queueArray) - q.destroy(); - queueArray.clear(); - } - //------------------------------------------------------------------------- - VkInstance VulkanDevice::createInstance( FastArray &extensions, - FastArray &layers, - PFN_vkDebugReportCallbackEXT debugCallback) - { - VkInstanceCreateInfo createInfo = {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; - VkApplicationInfo appInfo = {VK_STRUCTURE_TYPE_APPLICATION_INFO}; - - appInfo.pEngineName = "Ogre3D Vulkan Engine"; - appInfo.engineVersion = OGRE_VERSION; - appInfo.apiVersion = VK_API_VERSION_1_0; - - createInfo.pApplicationInfo = &appInfo; - createInfo.enabledLayerCount = layers.size(); - createInfo.ppEnabledLayerNames = layers.data(); - - createInfo.enabledExtensionCount = extensions.size(); - createInfo.ppEnabledExtensionNames = extensions.data(); - -#if 1 //OGRE_DEBUG_MODE - VkDebugReportCallbackCreateInfoEXT debugCb = {VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT}; - debugCb.pfnCallback = debugCallback; - debugCb.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT; - createInfo.pNext = &debugCb; -#endif - - VkInstance instance; - OGRE_VK_CHECK(vkCreateInstance(&createInfo, 0, &instance)); - return instance; - } - //------------------------------------------------------------------------- - void VulkanDevice::createPhysicalDevice( uint32 deviceIdx ) - { - uint32 numDevices = 0u; - OGRE_VK_CHECK(vkEnumeratePhysicalDevices(mInstance, &numDevices, NULL)); - - if( numDevices == 0u ) - { - OGRE_EXCEPT( Exception::ERR_RENDERINGAPI_ERROR, "No Vulkan devices found.", - "VulkanDevice::createPhysicalDevice" ); - } - - const String numDevicesStr = StringConverter::toString( numDevices ); - String deviceIdsStr = StringConverter::toString( deviceIdx ); - - if( deviceIdx >= numDevices ) - { - LogManager::getSingleton().logWarning( "[Vulkan] Requested device index " + deviceIdsStr + - " but there's only " + - StringConverter::toString( numDevices ) + "devices" ); - deviceIdx = 0u; - deviceIdsStr = "0"; - } - - LogManager::getSingleton().logMessage( "[Vulkan] Selecting device #" + deviceIdsStr ); - - FastArray pd(numDevices); - OGRE_VK_CHECK(vkEnumeratePhysicalDevices(mInstance, &numDevices, pd.data())); - mPhysicalDevice = pd[deviceIdx]; - - vkGetPhysicalDeviceMemoryProperties( mPhysicalDevice, &mDeviceMemoryProperties ); - vkGetPhysicalDeviceFeatures( mPhysicalDevice, &mDeviceFeatures ); - - mSupportedStages = 0xFFFFFFFF; - if( !mDeviceFeatures.geometryShader ) - mSupportedStages ^= VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT; - if( !mDeviceFeatures.tessellationShader ) - { - mSupportedStages ^= VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | - VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT; - } - } - //------------------------------------------------------------------------- - void VulkanDevice::findGraphicsQueue( FastArray &inOutUsedQueueCount ) - { - const size_t numQueues = mQueueProps.size(); - for( size_t i = 0u; i < numQueues; ++i ) - { - if( mQueueProps[i].queueFlags & VK_QUEUE_GRAPHICS_BIT && - inOutUsedQueueCount[i] < mQueueProps[i].queueCount ) - { - mGraphicsQueue.setQueueData( this, VulkanQueue::Graphics, static_cast( i ), - inOutUsedQueueCount[i] ); - ++inOutUsedQueueCount[i]; - return; - } - } - - OGRE_EXCEPT( Exception::ERR_RENDERINGAPI_ERROR, - "GPU does not expose Graphics queue. Cannot be used for rendering", - "VulkanQueue::findGraphicsQueue" ); - } - //------------------------------------------------------------------------- - void VulkanDevice::findComputeQueue( FastArray &inOutUsedQueueCount, uint32 maxNumQueues ) - { - const size_t numQueues = mQueueProps.size(); - for( size_t i = 0u; i < numQueues && mComputeQueues.size() < maxNumQueues; ++i ) - { - if( mQueueProps[i].queueFlags & VK_QUEUE_COMPUTE_BIT && - inOutUsedQueueCount[i] < mQueueProps[i].queueCount ) - { - mComputeQueues.push_back( VulkanQueue() ); - mComputeQueues.back().setQueueData( this, VulkanQueue::Compute, static_cast( i ), - inOutUsedQueueCount[i] ); - ++inOutUsedQueueCount[i]; - } - } - } - //------------------------------------------------------------------------- - void VulkanDevice::findTransferQueue( FastArray &inOutUsedQueueCount, uint32 maxNumQueues ) - { - const size_t numQueues = mQueueProps.size(); - for( size_t i = 0u; i < numQueues && mTransferQueues.size() < maxNumQueues; ++i ) - { - if( mQueueProps[i].queueFlags & VK_QUEUE_TRANSFER_BIT && - !( mQueueProps[i].queueFlags & ( VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT ) ) && - inOutUsedQueueCount[i] < mQueueProps[i].queueCount ) - { - mTransferQueues.push_back( VulkanQueue() ); - mTransferQueues.back().setQueueData( this, VulkanQueue::Transfer, - static_cast( i ), inOutUsedQueueCount[i] ); - ++inOutUsedQueueCount[i]; - } - } - } - //------------------------------------------------------------------------- - void VulkanDevice::fillQueueCreationInfo( uint32 maxComputeQueues, uint32 maxTransferQueues, - FastArray &outQueueCiArray ) - { - const size_t numQueueFamilies = mQueueProps.size(); - - FastArray usedQueueCount; - usedQueueCount.resize( numQueueFamilies, 0u ); - - findGraphicsQueue( usedQueueCount ); - findComputeQueue( usedQueueCount, maxComputeQueues ); - findTransferQueue( usedQueueCount, maxTransferQueues ); - - VkDeviceQueueCreateInfo queueCi = {VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; - for( size_t i = 0u; i < numQueueFamilies; ++i ) - { - queueCi.queueFamilyIndex = static_cast( i ); - queueCi.queueCount = usedQueueCount[i]; - if( queueCi.queueCount > 0u ) - outQueueCiArray.push_back( queueCi ); - } - } - //------------------------------------------------------------------------- - void VulkanDevice::createDevice( FastArray &extensions, uint32 maxComputeQueues, - uint32 maxTransferQueues ) - { - uint32 numQueues; - vkGetPhysicalDeviceQueueFamilyProperties( mPhysicalDevice, &numQueues, NULL ); - OgreAssert( numQueues > 0u, "No queues found" ); - mQueueProps.resize( numQueues ); - vkGetPhysicalDeviceQueueFamilyProperties( mPhysicalDevice, &numQueues, &mQueueProps[0] ); - - // Setup queue creation - FastArray queueCreateInfo; - fillQueueCreationInfo( maxComputeQueues, maxTransferQueues, queueCreateInfo ); - - FastArray > queuePriorities; - queuePriorities.resize( queueCreateInfo.size() ); - - for( size_t i = 0u; i < queueCreateInfo.size(); ++i ) - { - queuePriorities[i].resize( queueCreateInfo[i].queueCount, 1.0f ); - queueCreateInfo[i].pQueuePriorities = queuePriorities[i].data(); - } - - extensions.push_back( VK_KHR_SWAPCHAIN_EXTENSION_NAME ); - - VkDeviceCreateInfo createInfo = {VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; - - createInfo.enabledExtensionCount = static_cast( extensions.size() ); - createInfo.ppEnabledExtensionNames = extensions.data(); - - createInfo.queueCreateInfoCount = static_cast( queueCreateInfo.size() ); - createInfo.pQueueCreateInfos = &queueCreateInfo[0]; - - createInfo.pEnabledFeatures = &mDeviceFeatures; - - OGRE_VK_CHECK(vkCreateDevice(mPhysicalDevice, &createInfo, NULL, &mDevice)); - - volkLoadDevice(mDevice); - - VmaVulkanFunctions fns; - fns.vkGetInstanceProcAddr = vkGetInstanceProcAddr; - fns.vkGetDeviceProcAddr = vkGetDeviceProcAddr; - fns.vkGetPhysicalDeviceProperties = vkGetPhysicalDeviceProperties; - fns.vkGetPhysicalDeviceMemoryProperties = vkGetPhysicalDeviceMemoryProperties; - fns.vkAllocateMemory = vkAllocateMemory; - fns.vkFreeMemory = vkFreeMemory; - fns.vkMapMemory = vkMapMemory; - fns.vkUnmapMemory = vkUnmapMemory; - fns.vkFlushMappedMemoryRanges = vkFlushMappedMemoryRanges; - fns.vkInvalidateMappedMemoryRanges = vkInvalidateMappedMemoryRanges; - fns.vkBindBufferMemory = vkBindBufferMemory; - fns.vkBindImageMemory = vkBindImageMemory; - fns.vkGetBufferMemoryRequirements = vkGetBufferMemoryRequirements; - fns.vkGetImageMemoryRequirements = vkGetImageMemoryRequirements; - fns.vkCreateBuffer = vkCreateBuffer; - fns.vkDestroyBuffer = vkDestroyBuffer; - fns.vkCreateImage = vkCreateImage; - fns.vkDestroyImage = vkDestroyImage; - fns.vkCmdCopyBuffer = vkCmdCopyBuffer; - - VmaAllocatorCreateInfo allocatorCreateInfo = {}; - allocatorCreateInfo.instance = mInstance; - allocatorCreateInfo.device = mDevice; - allocatorCreateInfo.physicalDevice = mPhysicalDevice; - allocatorCreateInfo.pVulkanFunctions = &fns; - vmaCreateAllocator(&allocatorCreateInfo, &mVmaAllocator); - } - //------------------------------------------------------------------------- - void VulkanDevice::initQueues( void ) - { - VkQueue queue = 0; - vkGetDeviceQueue( mDevice, mGraphicsQueue.mFamilyIdx, mGraphicsQueue.mQueueIdx, &queue ); - mGraphicsQueue.init( mDevice, queue, mRenderSystem ); - - for (auto& q : mComputeQueues) - { - vkGetDeviceQueue( mDevice, q.mFamilyIdx, q.mQueueIdx, &queue); - q.init(mDevice, queue, mRenderSystem); - } - - for (auto& q : mTransferQueues) - { - vkGetDeviceQueue(mDevice, q.mFamilyIdx, q.mQueueIdx, &queue); - q.init(mDevice, queue, mRenderSystem); - } - - TODO_findRealPresentQueue; - mPresentQueue = mGraphicsQueue.mQueue; - } - //------------------------------------------------------------------------- - void VulkanDevice::commitAndNextCommandBuffer( SubmissionType::SubmissionType submissionType ) - { - mGraphicsQueue.endAllEncoders(); - mGraphicsQueue.commitAndNextCommandBuffer( submissionType ); - } - //------------------------------------------------------------------------- - void VulkanDevice::stall( void ) - { - // We must flush the cmd buffer and our bindings because we take the - // moment to delete all delayed buffers and API handles after a stall. - // - // We can't have potentially dangling API handles in a cmd buffer. - // We must submit our current pending work so far and wait until that's done. - commitAndNextCommandBuffer( SubmissionType::FlushOnly ); - mRenderSystem->resetAllBindings(); - - vkDeviceWaitIdle( mDevice ); - - mRenderSystem->_notifyDeviceStalled(); - } - //------------------------------------------------------------------------- - //------------------------------------------------------------------------- - //------------------------------------------------------------------------- - VulkanDevice::SelectedQueue::SelectedQueue() : - usage( VulkanQueue::NumQueueFamilies ), - familyIdx( std::numeric_limits::max() ), - queueIdx( 0 ) - { - } -} // namespace Ogre diff --git a/RenderSystems/Vulkan/src/OgreVulkanHardwareBuffer.cpp b/RenderSystems/Vulkan/src/OgreVulkanHardwareBuffer.cpp deleted file mode 100644 index a3f02319faa..00000000000 --- a/RenderSystems/Vulkan/src/OgreVulkanHardwareBuffer.cpp +++ /dev/null @@ -1,179 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreVulkanHardwareBuffer.h" - -#include - -#include "OgreVulkanDevice.h" -#include "OgreVulkanUtils.h" - -namespace Ogre -{ - VulkanHardwareBuffer::VulkanHardwareBuffer(uint32 target, - size_t sizeBytes, Usage usage, bool useShadowBuffer, VulkanDevice *device ) : - HardwareBuffer(usage, useShadowBuffer), - mBuffer(VK_NULL_HANDLE), - mDevice( device ), - mTarget( target ), - mMappedPtr( nullptr ) - { - mSizeInBytes = sizeBytes; - - discard(); - - if(mUsage == HBU_GPU_ONLY) - { - mShadowBuffer = std::make_unique(VK_BUFFER_USAGE_TRANSFER_SRC_BIT, sizeBytes, HBU_CPU_ONLY, false, mDevice); - } - } - - static VmaMemoryUsage getVmaUsage(HardwareBuffer::Usage usage) - { - switch(usage) - { - case HBU_CPU_TO_GPU: - return VMA_MEMORY_USAGE_CPU_TO_GPU; - case HBU_GPU_TO_CPU: - return VMA_MEMORY_USAGE_GPU_TO_CPU; - case HBU_CPU_ONLY: - return VMA_MEMORY_USAGE_CPU_ONLY; - default: - case HBU_GPU_ONLY: - return VMA_MEMORY_USAGE_GPU_ONLY; - } - } - - void VulkanHardwareBuffer::discard() - { - if(mBuffer) - { - if(mMappedPtr) - vmaUnmapMemory( mDevice->getAllocator(), mAllocation ); - mDevice->mGraphicsQueue.queueForDeletion(mBuffer, mAllocation); - } - - VkBufferCreateInfo bufferCi = {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; - bufferCi.size = mSizeInBytes; - bufferCi.usage = mTarget; - - if((mUsage & HBU_CPU_ONLY) == 0) - bufferCi.usage |= VK_BUFFER_USAGE_TRANSFER_DST_BIT; - - VmaAllocationCreateInfo allocInfo = {}; - allocInfo.usage = getVmaUsage(mUsage); - OGRE_VK_CHECK(vmaCreateBuffer(mDevice->getAllocator(), &bufferCi, &allocInfo, &mBuffer, &mAllocation, 0)); - - if (mUsage == HBU_CPU_TO_GPU) - { - OGRE_VK_CHECK(vmaMapMemory(mDevice->getAllocator(), mAllocation, &mMappedPtr)); - } - } - - VulkanHardwareBuffer::~VulkanHardwareBuffer() - { - if(mMappedPtr) - vmaUnmapMemory( mDevice->getAllocator(), mAllocation ); - // delay until we are sure this buffer is no longer in use - mDevice->mGraphicsQueue.queueForDeletion(mBuffer, mAllocation); - } - - void* VulkanHardwareBuffer::lockImpl(size_t offset, size_t length, LockOptions options) - { - if(mShadowBuffer) - return mShadowBuffer->lock(offset, length, options); - - if (options == HBL_DISCARD && mUsage == HBU_CPU_TO_GPU) - discard(); - - if ((options == HBL_READ_ONLY || options == HBL_NORMAL) && mUsage == HBU_GPU_ONLY) - { - LogManager::getSingleton().logWarning("HardwareBuffer - UNIMPLEMENTED implicit GPU to HOST copy (slow)"); - } - - if (mMappedPtr) // persistent mapping - return static_cast(mMappedPtr) + offset; - - void *retPtr = 0; - OGRE_VK_CHECK(vmaMapMemory(mDevice->getAllocator(), mAllocation, &retPtr)); - return static_cast(retPtr) + offset; - } - - void VulkanHardwareBuffer::unlockImpl() - { - OgreAssert(!mShadowBuffer, "should be handled by _updateFromShadow"); - if(mMappedPtr) // persistent mapping - return; - vmaUnmapMemory( mDevice->getAllocator(), mAllocation ); - } - - void VulkanHardwareBuffer::readData( size_t offset, size_t length, void *pDest ) - { - // just use memcpy - HardwareBufferLockGuard thisLock(this, offset, length, HBL_READ_ONLY); - memcpy(pDest, thisLock.pData, length); - } - - void VulkanHardwareBuffer::writeData(size_t offset, size_t length, const void* pSource, - bool discardWholeBuffer) - { - // just use memcpy - HardwareBufferLockGuard thisLock(this, offset, length, discardWholeBuffer ? HBL_DISCARD : HBL_NORMAL); - memcpy(thisLock.pData, pSource, length); - } - - void VulkanHardwareBuffer::_updateFromShadow() - { - if(mShadowBuffer && mShadowUpdated && !mSuppressHardwareUpdate) - { - bool discardWholeBuffer = mLockStart == 0 && mLockSize == mSizeInBytes; - copyData(*mShadowBuffer, mLockStart, mLockStart, mLockSize, discardWholeBuffer); - mShadowUpdated = false; - } - } - - void VulkanHardwareBuffer::copyData( HardwareBuffer& _srcBuffer, size_t srcOffset, - size_t dstOffset, size_t length, bool discardWholeBuffer ) - { - auto srcBuffer = dynamic_cast( &_srcBuffer ); - if( srcBuffer && (mUsage & HBU_CPU_ONLY) == 0) - { - mDevice->mGraphicsQueue.getCopyEncoderV1Buffer( false ); - - VkBuffer srcBuf = srcBuffer->getVkBuffer(); - VkBufferCopy region = {srcOffset, dstOffset, length}; - vkCmdCopyBuffer( mDevice->mGraphicsQueue.mCurrentCmdBuffer, srcBuf, mBuffer, 1u, ®ion ); - } - else - { - const void* srcData = _srcBuffer.lock(srcOffset, length, HBL_READ_ONLY); - writeData(dstOffset, length, srcData, discardWholeBuffer); - _srcBuffer.unlock(); - } - } -} diff --git a/RenderSystems/Vulkan/src/OgreVulkanHardwareBufferManager.cpp b/RenderSystems/Vulkan/src/OgreVulkanHardwareBufferManager.cpp deleted file mode 100644 index a70ca165cc5..00000000000 --- a/RenderSystems/Vulkan/src/OgreVulkanHardwareBufferManager.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreVulkanHardwareBufferManager.h" -#include "OgreVulkanHardwareBuffer.h" - -namespace Ogre -{ - VulkanHardwareBufferManager::VulkanHardwareBufferManager( VulkanDevice *device) : - mDevice( device ) - { - } - //----------------------------------------------------------------------------------- - VulkanHardwareBufferManager::~VulkanHardwareBufferManager() - { - destroyAllDeclarations(); - destroyAllBindings(); - } - //----------------------------------------------------------------------------------- - void VulkanHardwareBufferManager::_notifyDeviceStalled( void ) - { - { - OGRE_LOCK_MUTEX( mVertexBuffersMutex ); - for (auto& b : mVertexBuffers) - { - auto hwBuffer = b->_getImpl(); - hwBuffer->_notifyDeviceStalled(); - } - } - { - OGRE_LOCK_MUTEX( mIndexBuffersMutex ); - for (auto& i : mIndexBuffers) - { - auto hwBuffer = i->_getImpl(); - hwBuffer->_notifyDeviceStalled(); - } - } - } - //----------------------------------------------------------------------------------- - HardwareVertexBufferSharedPtr VulkanHardwareBufferManager::createVertexBuffer( - size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer ) - { - auto impl = new VulkanHardwareBuffer(VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, vertexSize * numVerts, usage, - useShadowBuffer, mDevice); - auto buf = std::make_shared(this, vertexSize, numVerts, impl); - { - OGRE_LOCK_MUTEX(mVertexBuffersMutex); - mVertexBuffers.insert(buf.get()); - } - return buf; - } - //----------------------------------------------------------------------------------- - HardwareIndexBufferSharedPtr VulkanHardwareBufferManager::createIndexBuffer( - HardwareIndexBuffer::IndexType itype, size_t numIndexes, HardwareBuffer::Usage usage, - bool useShadowBuffer ) - { - auto indexSize = HardwareIndexBuffer::indexSize(itype); - auto impl = new VulkanHardwareBuffer(VK_BUFFER_USAGE_INDEX_BUFFER_BIT, indexSize * numIndexes, usage, - useShadowBuffer, mDevice); - - auto buf = std::make_shared(this, itype, numIndexes, impl); - { - OGRE_LOCK_MUTEX(mIndexBuffersMutex); - //mIndexBuffers.insert(buf.get()); // TODO never deleted yet - } - return buf; - } - //----------------------------------------------------------------------------------- - HardwareBufferPtr VulkanHardwareBufferManager::createUniformBuffer(size_t sizeBytes, HardwareBufferUsage usage, - bool useShadowBuffer) - { - return std::make_shared(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, sizeBytes, usage, false, - mDevice); - } -} // namespace Ogre diff --git a/RenderSystems/Vulkan/src/OgreVulkanMappings.cpp b/RenderSystems/Vulkan/src/OgreVulkanMappings.cpp deleted file mode 100644 index c0d3902697b..00000000000 --- a/RenderSystems/Vulkan/src/OgreVulkanMappings.cpp +++ /dev/null @@ -1,453 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-present Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreVulkanMappings.h" - -#include "OgrePixelFormat.h" - -namespace Ogre -{ - //----------------------------------------------------------------------------------- - VkPrimitiveTopology VulkanMappings::get( RenderOperation::OperationType opType ) - { - switch( opType ) - { - // clang-format off - case RenderOperation::OT_POINT_LIST: return VK_PRIMITIVE_TOPOLOGY_POINT_LIST; - case RenderOperation::OT_LINE_LIST: return VK_PRIMITIVE_TOPOLOGY_LINE_LIST; - case RenderOperation::OT_LINE_STRIP: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP; - case RenderOperation::OT_TRIANGLE_LIST: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; - case RenderOperation::OT_TRIANGLE_STRIP: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; - case RenderOperation::OT_TRIANGLE_FAN: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN; - default: - return VK_PRIMITIVE_TOPOLOGY_PATCH_LIST; - // clang-format on - } - } - //----------------------------------------------------------------------------------- - VkPolygonMode VulkanMappings::get( PolygonMode polygonMode ) - { - switch( polygonMode ) - { - // clang-format off - case PM_POINTS: return VK_POLYGON_MODE_POINT; - case PM_WIREFRAME: return VK_POLYGON_MODE_LINE; - case PM_SOLID: return VK_POLYGON_MODE_FILL; - // clang-format on - } - return VK_POLYGON_MODE_FILL; - } - //----------------------------------------------------------------------------------- - VkCullModeFlags VulkanMappings::get( CullingMode cullMode ) - { - switch( cullMode ) - { - // clang-format off - case CULL_NONE: return VK_CULL_MODE_NONE; - case CULL_CLOCKWISE: return VK_CULL_MODE_BACK_BIT; - case CULL_ANTICLOCKWISE: return VK_CULL_MODE_FRONT_BIT; - // clang-format on - } - return VK_CULL_MODE_BACK_BIT; - } - //----------------------------------------------------------------------------------- - VkCompareOp VulkanMappings::get( CompareFunction compareFunc ) - { - switch( compareFunc ) - { - // clang-format off - case CMPF_ALWAYS_FAIL: return VK_COMPARE_OP_NEVER; - case CMPF_ALWAYS_PASS: return VK_COMPARE_OP_ALWAYS; - case CMPF_LESS: return VK_COMPARE_OP_LESS; - case CMPF_LESS_EQUAL: return VK_COMPARE_OP_LESS_OR_EQUAL; - case CMPF_EQUAL: return VK_COMPARE_OP_EQUAL; - case CMPF_NOT_EQUAL: return VK_COMPARE_OP_NOT_EQUAL; - case CMPF_GREATER_EQUAL: return VK_COMPARE_OP_GREATER_OR_EQUAL; - case CMPF_GREATER: return VK_COMPARE_OP_GREATER; - // clang-format on - } - return VK_COMPARE_OP_NEVER; - } - //----------------------------------------------------------------------------------- - VkStencilOp VulkanMappings::get( StencilOperation stencilOp ) - { - switch( stencilOp ) - { - // clang-format off - case SOP_KEEP: return VK_STENCIL_OP_KEEP; - case SOP_ZERO: return VK_STENCIL_OP_ZERO; - case SOP_REPLACE: return VK_STENCIL_OP_REPLACE; - case SOP_INCREMENT: return VK_STENCIL_OP_INCREMENT_AND_CLAMP; - case SOP_DECREMENT: return VK_STENCIL_OP_DECREMENT_AND_CLAMP; - case SOP_INCREMENT_WRAP: return VK_STENCIL_OP_INCREMENT_AND_WRAP; - case SOP_DECREMENT_WRAP: return VK_STENCIL_OP_DECREMENT_AND_WRAP; - case SOP_INVERT: return VK_STENCIL_OP_INVERT; - // clang-format on - } - return VK_STENCIL_OP_KEEP; - } - //----------------------------------------------------------------------------------- - VkBlendFactor VulkanMappings::get( SceneBlendFactor blendFactor ) - { - switch( blendFactor ) - { - // clang-format off - case SBF_ONE: return VK_BLEND_FACTOR_ONE; - case SBF_ZERO: return VK_BLEND_FACTOR_ZERO; - case SBF_DEST_COLOUR: return VK_BLEND_FACTOR_DST_COLOR; - case SBF_SOURCE_COLOUR: return VK_BLEND_FACTOR_SRC_COLOR; - case SBF_ONE_MINUS_DEST_COLOUR: return VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR; - case SBF_ONE_MINUS_SOURCE_COLOUR: return VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR; - case SBF_DEST_ALPHA: return VK_BLEND_FACTOR_DST_ALPHA; - case SBF_SOURCE_ALPHA: return VK_BLEND_FACTOR_SRC_ALPHA; - case SBF_ONE_MINUS_DEST_ALPHA: return VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA; - case SBF_ONE_MINUS_SOURCE_ALPHA: return VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; - // clang-format on - } - return VK_BLEND_FACTOR_ONE; - } - //----------------------------------------------------------------------------------- - VkBlendOp VulkanMappings::get( SceneBlendOperation blendOp ) - { - switch( blendOp ) - { - // clang-format off - case SBO_ADD: return VK_BLEND_OP_ADD; - case SBO_SUBTRACT: return VK_BLEND_OP_SUBTRACT; - case SBO_REVERSE_SUBTRACT: return VK_BLEND_OP_REVERSE_SUBTRACT; - case SBO_MIN: return VK_BLEND_OP_MIN; - case SBO_MAX: return VK_BLEND_OP_MAX; - // clang-format on - } - return VK_BLEND_OP_ADD; - } - //----------------------------------------------------------------------------------- - VkFormat VulkanMappings::get( VertexElementType vertexElemType ) - { - switch( vertexElemType ) - { - case VET_FLOAT1: - return VK_FORMAT_R32_SFLOAT; - case VET_FLOAT2: - return VK_FORMAT_R32G32_SFLOAT; - case VET_FLOAT3: - return VK_FORMAT_R32G32B32_SFLOAT; - case VET_FLOAT4: - return VK_FORMAT_R32G32B32A32_SFLOAT; - case VET_SHORT2: - return VK_FORMAT_R16G16_SINT; - case VET_SHORT4: - return VK_FORMAT_R16G16B16A16_SINT; - case VET_UBYTE4: - return VK_FORMAT_R8G8B8A8_UINT; - case VET_USHORT2: - return VK_FORMAT_R16G16_UINT; - case VET_USHORT4: - return VK_FORMAT_R16G16B16A16_UINT; - case VET_INT1: - return VK_FORMAT_R32_SINT; - case VET_INT2: - return VK_FORMAT_R32G32_SINT; - case VET_INT3: - return VK_FORMAT_R32G32B32_SINT; - case VET_INT4: - return VK_FORMAT_R32G32B32A32_SINT; - case VET_UINT1: - return VK_FORMAT_R32_UINT; - case VET_UINT2: - return VK_FORMAT_R32G32_UINT; - case VET_UINT3: - return VK_FORMAT_R32G32B32_UINT; - case VET_UINT4: - return VK_FORMAT_R32G32B32A32_SINT; - case VET_BYTE4: - return VK_FORMAT_R8G8B8A8_SINT; - //case VET_BYTE4_SNORM: - // return VK_FORMAT_R8G8B8A8_SNORM; - case VET_UBYTE4_NORM: - return VK_FORMAT_R8G8B8A8_UNORM; - //case VET_SHORT2_SNORM: - // return VK_FORMAT_R16G16_SNORM; - //case VET_SHORT4_SNORM: - // return VK_FORMAT_R16G16B16A16_SNORM; - case VET_USHORT2_NORM: - return VK_FORMAT_R16G16_UNORM; - case VET_USHORT4_NORM: - return VK_FORMAT_R16G16B16A16_UNORM; - //case VET_HALF2: - // return VK_FORMAT_R16G16_SFLOAT; - //case VET_HALF4: - // return VK_FORMAT_R16G16B16A16_SFLOAT; - case VET_INT_10_10_10_2_NORM: - return VK_FORMAT_A2B10G10R10_SNORM_PACK32; - default: - case VET_DOUBLE1: - case VET_DOUBLE2: - case VET_DOUBLE3: - case VET_DOUBLE4: - case VET_USHORT1: - case VET_USHORT3: - return VK_FORMAT_UNDEFINED; - } - - return VK_FORMAT_UNDEFINED; - } - //----------------------------------------------------------------------------------- - VkFilter VulkanMappings::get( FilterOptions filter ) - { - switch( filter ) - { - // clang-format off - case FO_NONE: return VK_FILTER_NEAREST; - case FO_POINT: return VK_FILTER_NEAREST; - case FO_LINEAR: return VK_FILTER_LINEAR; - case FO_ANISOTROPIC: return VK_FILTER_LINEAR; - // clang-format on - } - - return VK_FILTER_NEAREST; - } - //----------------------------------------------------------------------------------- - VkSamplerMipmapMode VulkanMappings::getMipFilter( FilterOptions filter ) - { - switch( filter ) - { - // clang-format off - case FO_NONE: return VK_SAMPLER_MIPMAP_MODE_NEAREST; - case FO_POINT: return VK_SAMPLER_MIPMAP_MODE_NEAREST; - case FO_LINEAR: return VK_SAMPLER_MIPMAP_MODE_LINEAR; - case FO_ANISOTROPIC: return VK_SAMPLER_MIPMAP_MODE_LINEAR; - // clang-format on - } - - return VK_SAMPLER_MIPMAP_MODE_NEAREST; - } - //----------------------------------------------------------------------------------- - VkSamplerAddressMode VulkanMappings::get( TextureAddressingMode mode ) - { - switch( mode ) - { - case TAM_WRAP: - return VK_SAMPLER_ADDRESS_MODE_REPEAT; - case TAM_MIRROR: - return VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; - case TAM_CLAMP: - return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - case TAM_BORDER: - return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; - } - - return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; - } - //----------------------------------------------------------------------------------- - VkImageViewType VulkanMappings::get( TextureType textureType ) - { - switch( textureType ) - { - // clang-format off - case TEX_TYPE_1D: return VK_IMAGE_VIEW_TYPE_1D; - //case TextureTypes::Type1DArray: return VK_IMAGE_VIEW_TYPE_1D_ARRAY; - case TEX_TYPE_2D: return VK_IMAGE_VIEW_TYPE_2D; - case TEX_TYPE_2D_ARRAY: return VK_IMAGE_VIEW_TYPE_2D_ARRAY; - case TEX_TYPE_CUBE_MAP: return VK_IMAGE_VIEW_TYPE_CUBE; - //case TextureTypes::TypeCubeArray: return VK_IMAGE_VIEW_TYPE_CUBE_ARRAY; - case TEX_TYPE_3D: return VK_IMAGE_VIEW_TYPE_3D; - // clang-format on - case TEX_TYPE_EXTERNAL_OES: - break; - } - return VK_IMAGE_VIEW_TYPE_2D; - } - //----------------------------------------------------------------------------------- - VkFormat VulkanMappings::get( PixelFormat pf, bool hwGamma ) - { - // clang-format off - switch( pf ) - { - case PF_FLOAT32_RGBA: return VK_FORMAT_R32G32B32A32_SFLOAT; - case PF_R32G32B32A32_UINT: return VK_FORMAT_R32G32B32A32_UINT; - case PF_R32G32B32A32_SINT: return VK_FORMAT_R32G32B32A32_SINT; - case PF_FLOAT32_RGB: return VK_FORMAT_R32G32B32_SFLOAT; - case PF_R32G32B32_UINT: return VK_FORMAT_R32G32B32_UINT; - case PF_R32G32B32_SINT: return VK_FORMAT_R32G32B32_SINT; - case PF_FLOAT16_RGBA: return VK_FORMAT_R16G16B16A16_SFLOAT; - //case PF_R16G16B16A16_UNORM: return VK_FORMAT_R16G16B16A16_UNORM; - case PF_R16G16B16A16_UINT: return VK_FORMAT_R16G16B16A16_UINT; - case PF_R16G16B16A16_SNORM: return VK_FORMAT_R16G16B16A16_SNORM; - case PF_R16G16B16A16_SINT: return VK_FORMAT_R16G16B16A16_SINT; - //case PF_FLOAT32_RG: return VK_FORMAT_R32G32_SFLOAT; - case PF_R32G32_UINT: return VK_FORMAT_R32G32_UINT; - case PF_R32G32_SINT: return VK_FORMAT_R32G32_SINT; - //case PF_D32_FLOAT_S8X24_UINT: return VK_FORMAT_D32_SFLOAT_S8_UINT; - case PF_A2B10G10R10: return VK_FORMAT_A2B10G10R10_UNORM_PACK32; - //case PF_R10G10B10A2_UINT: return VK_FORMAT_A2B10G10R10_UINT_PACK32; - case PF_R11G11B10_FLOAT: return VK_FORMAT_B10G11R11_UFLOAT_PACK32; - case PF_X8B8G8R8: - case PF_A8B8G8R8: return hwGamma ? VK_FORMAT_R8G8B8A8_SRGB : VK_FORMAT_R8G8B8A8_UNORM; - //case PF_A8B8G8R8_UINT: return VK_FORMAT_R8G8B8A8_UINT; - //case PF_A8B8G8R8_SNORM: return VK_FORMAT_R8G8B8A8_SNORM; - //case PF_A8B8G8R8_SINT: return VK_FORMAT_R8G8B8A8_SINT; - case PF_FLOAT16_GR: return VK_FORMAT_R16G16_SFLOAT; - //case PF_R16G16_UNORM: return VK_FORMAT_R16G16_UNORM; - case PF_R16G16_UINT: return VK_FORMAT_R16G16_UINT; - case PF_R16G16_SNORM: return VK_FORMAT_R16G16_SNORM; - case PF_R16G16_SINT: return VK_FORMAT_R16G16_SINT; - case PF_DEPTH32: - case PF_DEPTH32F: return VK_FORMAT_D32_SFLOAT; - case PF_FLOAT32_R: return VK_FORMAT_R32_SFLOAT; - case PF_R32_UINT: return VK_FORMAT_R32_UINT; - case PF_R32_SINT: return VK_FORMAT_R32_SINT; - //case PF_D24_UNORM: return VK_FORMAT_X8_D24_UNORM_PACK32; - case PF_DEPTH24_STENCIL8: return VK_FORMAT_D32_SFLOAT_S8_UINT; // VK_FORMAT_D24_UNORM_S8_UINT not supported on AMD - case PF_BYTE_LA: - case PF_RG8: return VK_FORMAT_R8G8_UNORM; - case PF_R8G8_UINT: return VK_FORMAT_R8G8_UINT; - case PF_R8G8_SNORM: return VK_FORMAT_R8G8_SNORM; - case PF_R8G8_SINT: return VK_FORMAT_R8G8_SINT; - case PF_FLOAT16_R: return VK_FORMAT_R16_SFLOAT; - case PF_DEPTH16: return VK_FORMAT_D16_UNORM; - //case PF_R16_UNORM: return VK_FORMAT_R16_UNORM; - case PF_R16_UINT: return VK_FORMAT_R16_UINT; - case PF_R16_SNORM: return VK_FORMAT_R16_SNORM; - case PF_R16_SINT: return VK_FORMAT_R16_SINT; - case PF_A8: - case PF_L8: - case PF_R8: return VK_FORMAT_R8_UNORM; - case PF_R8_UINT: return VK_FORMAT_R8_UINT; - case PF_R8_SNORM: return VK_FORMAT_R8_SNORM; - case PF_R8_SINT: return VK_FORMAT_R8_SINT; - case PF_R9G9B9E5_SHAREDEXP: return VK_FORMAT_E5B9G9R9_UFLOAT_PACK32; - case PF_DXT1: return hwGamma ? VK_FORMAT_BC1_RGBA_SRGB_BLOCK : VK_FORMAT_BC1_RGBA_UNORM_BLOCK; - case PF_DXT2: return hwGamma ? VK_FORMAT_BC1_RGBA_SRGB_BLOCK : VK_FORMAT_BC1_RGBA_UNORM_BLOCK; - case PF_DXT3: return hwGamma ? VK_FORMAT_BC2_SRGB_BLOCK : VK_FORMAT_BC2_UNORM_BLOCK; - case PF_DXT4: return hwGamma ? VK_FORMAT_BC2_SRGB_BLOCK : VK_FORMAT_BC2_UNORM_BLOCK; - case PF_DXT5: return hwGamma ? VK_FORMAT_BC3_SRGB_BLOCK : VK_FORMAT_BC3_UNORM_BLOCK; -#if 0 - case PF_R8G8_B8G8_UNORM: return VK_FORMAT_B8G8R8G8_422_UNORM; - case PF_G8R8_G8B8_UNORM: return VK_FORMAT_G8B8G8R8_422_UNORM; -#endif - case PF_BC4_UNORM: return VK_FORMAT_BC4_UNORM_BLOCK; - case PF_BC4_SNORM: return VK_FORMAT_BC4_SNORM_BLOCK; - case PF_BC5_UNORM: return VK_FORMAT_BC5_UNORM_BLOCK; - case PF_BC5_SNORM: return VK_FORMAT_BC5_SNORM_BLOCK; - case PF_R5G6B5: return VK_FORMAT_R5G6B5_UNORM_PACK16; - case PF_B5G6R5: return VK_FORMAT_B5G6R5_UNORM_PACK16; - case PF_A1R5G5B5: return VK_FORMAT_B5G5R5A1_UNORM_PACK16; - case PF_A8R8G8B8: return hwGamma ? VK_FORMAT_B8G8R8A8_SRGB : VK_FORMAT_B8G8R8A8_UNORM; - case PF_X8R8G8B8: return hwGamma ? VK_FORMAT_B8G8R8A8_SRGB : VK_FORMAT_B8G8R8A8_UNORM; - //case PF_R10G10B10_XR_BIAS_A2_UNORM:return VK_FORMAT_A2R10G10B10_USCALED_PACK32; - case PF_BC6H_UF16: return VK_FORMAT_BC6H_UFLOAT_BLOCK; - case PF_BC6H_SF16: return VK_FORMAT_BC6H_SFLOAT_BLOCK; - case PF_BC7_UNORM: return VK_FORMAT_BC7_UNORM_BLOCK; - case PF_A4R4G4B4: return VK_FORMAT_B4G4R4A4_UNORM_PACK16; - case PF_ETC1_RGB8: return VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK; - case PF_ETC2_RGB8: return VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK; - case PF_ETC2_RGBA8: return VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK; - case PF_ETC2_RGB8A1: return VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK; -#if 0 - case PF_EAC_R11_UNORM: return VK_FORMAT_EAC_R11_UNORM_BLOCK; - case PF_EAC_R11_SNORM: return VK_FORMAT_EAC_R11_SNORM_BLOCK; - case PF_EAC_R11G11_UNORM: return VK_FORMAT_EAC_R11G11_UNORM_BLOCK; - case PF_EAC_R11G11_SNORM: return VK_FORMAT_EAC_R11G11_SNORM_BLOCK; -#endif - - case PF_ASTC_RGBA_4X4_LDR: return VK_FORMAT_ASTC_4x4_UNORM_BLOCK; - case PF_ASTC_RGBA_5X4_LDR: return VK_FORMAT_ASTC_5x4_UNORM_BLOCK; - case PF_ASTC_RGBA_5X5_LDR: return VK_FORMAT_ASTC_5x5_UNORM_BLOCK; - case PF_ASTC_RGBA_6X5_LDR: return VK_FORMAT_ASTC_6x5_UNORM_BLOCK; - case PF_ASTC_RGBA_6X6_LDR: return VK_FORMAT_ASTC_6x6_UNORM_BLOCK; - case PF_ASTC_RGBA_8X5_LDR: return VK_FORMAT_ASTC_8x5_UNORM_BLOCK; - case PF_ASTC_RGBA_8X6_LDR: return VK_FORMAT_ASTC_8x6_UNORM_BLOCK; - case PF_ASTC_RGBA_8X8_LDR: return VK_FORMAT_ASTC_8x8_UNORM_BLOCK; - case PF_ASTC_RGBA_10X5_LDR: return VK_FORMAT_ASTC_10x5_UNORM_BLOCK; - case PF_ASTC_RGBA_10X6_LDR: return VK_FORMAT_ASTC_10x6_UNORM_BLOCK; - case PF_ASTC_RGBA_10X8_LDR: return VK_FORMAT_ASTC_10x8_UNORM_BLOCK; - case PF_ASTC_RGBA_10X10_LDR: return VK_FORMAT_ASTC_10x10_UNORM_BLOCK; - case PF_ASTC_RGBA_12X10_LDR: return VK_FORMAT_ASTC_12x10_UNORM_BLOCK; - case PF_ASTC_RGBA_12X12_LDR: return VK_FORMAT_ASTC_12x12_UNORM_BLOCK; - case PF_ATC_RGB: - case PF_ATC_RGBA_EXPLICIT_ALPHA: - case PF_ATC_RGBA_INTERPOLATED_ALPHA: - // PVRTC requires asking for extension VK_IMG_format_pvrtc before using - // VK_FORMAT_PVRTC* family of enums. - // - // However: - // 1. This extension is deprecated. - // 2. We have no way of testing the extension/functionality works and won't crash if Ogre - // ever runs on PVRTC-enabled drivers. The oldest / most popular PVRTC GPU we can get is - // the PowerVR GE8320 and it doesn't expose this extension. - // - // PVRTC on Vulkan is dead. - case PF_PVRTC_RGB2: - case PF_PVRTC_RGBA2: - case PF_PVRTC_RGB4: - case PF_PVRTC_RGBA4: - case PF_PVRTC2_2BPP: - case PF_PVRTC2_4BPP: - default: - return VK_FORMAT_UNDEFINED; - } - // clang-format on - } - //----------------------------------------------------------------------------------- - VkImageAspectFlags VulkanMappings::getImageAspect(PixelFormat pf, const bool bPreferDepthOverStencil) - { - int ret = PixelUtil::isDepth(pf) ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT; - if (pf == PF_DEPTH24_STENCIL8) - ret |= VK_IMAGE_ASPECT_STENCIL_BIT; - return ret; - } - //----------------------------------------------------------------------------------- - VkAccessFlags VulkanMappings::get( const Texture *texture ) - { - VkAccessFlags texAccessFlags = 0; - - if( texture->getUsage() & TU_UNORDERED_ACCESS ) - { - texAccessFlags |= VK_ACCESS_SHADER_READ_BIT; - if( texture->getUsage() & TU_UNORDERED_ACCESS ) - texAccessFlags |= VK_ACCESS_SHADER_WRITE_BIT; - } - if( texture->getUsage() & TU_RENDERTARGET ) - { - // texAccessFlags |= VK_ACCESS_INPUT_ATTACHMENT_READ_BIT; - if( !PixelUtil::isDepth( texture->getFormat() ) ) - { - texAccessFlags |= - VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - } - else - { - texAccessFlags |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; - } - } - - return texAccessFlags; - } -} // namespace Ogre diff --git a/RenderSystems/Vulkan/src/OgreVulkanPlugin.cpp b/RenderSystems/Vulkan/src/OgreVulkanPlugin.cpp deleted file mode 100644 index 2607dc54e40..00000000000 --- a/RenderSystems/Vulkan/src/OgreVulkanPlugin.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "OgreVulkanPlugin.h" -#include "OgreRoot.h" -#include "OgreVulkanRenderSystem.h" - -namespace Ogre -{ - const String sPluginName = "Vulkan RenderSystem"; - //--------------------------------------------------------------------- - VulkanPlugin::VulkanPlugin() : mRenderSystem( 0 ) {} - //--------------------------------------------------------------------- - const String &VulkanPlugin::getName() const { return sPluginName; } - //--------------------------------------------------------------------- - void VulkanPlugin::install() - { - mRenderSystem = OGRE_NEW VulkanRenderSystem(); - - Root::getSingleton().addRenderSystem( mRenderSystem ); - } - //--------------------------------------------------------------------- - void VulkanPlugin::initialise() - { - // nothing to do - } - //--------------------------------------------------------------------- - void VulkanPlugin::shutdown() - { - // nothing to do - } - //--------------------------------------------------------------------- - void VulkanPlugin::uninstall() - { - OGRE_DELETE mRenderSystem; - mRenderSystem = 0; - } - -#ifndef OGRE_STATIC_LIB - static VulkanPlugin *plugin; - - extern "C" void _OgreVulkanExport dllStartPlugin(void); - extern "C" void _OgreVulkanExport dllStopPlugin(void); - - extern "C" void _OgreVulkanExport dllStartPlugin( void ) - { - plugin = OGRE_NEW VulkanPlugin(); - Root::getSingleton().installPlugin( plugin ); - } - - extern "C" void _OgreVulkanExport dllStopPlugin( void ) - { - Root::getSingleton().uninstallPlugin( plugin ); - OGRE_DELETE plugin; - } -#endif -} // namespace Ogre diff --git a/RenderSystems/Vulkan/src/OgreVulkanProgram.cpp b/RenderSystems/Vulkan/src/OgreVulkanProgram.cpp deleted file mode 100644 index f67db90d7fd..00000000000 --- a/RenderSystems/Vulkan/src/OgreVulkanProgram.cpp +++ /dev/null @@ -1,145 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-present Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreVulkanProgram.h" - -#include "OgreLogManager.h" -#include "OgreProfiler.h" -#include "OgreVulkanDevice.h" -#include "OgreVulkanMappings.h" - -#include "OgreStringConverter.h" -#include "OgreVulkanUtils.h" - -#include "OgreRenderSystemCapabilities.h" -#include "OgreRoot.h" - -#define OgreProfileExhaustive OgreProfile - -namespace Ogre -{ - //----------------------------------------------------------------------- - VulkanProgram::VulkanProgram( ResourceManager *creator, const String &name, ResourceHandle handle, - const String &group, bool isManual, ManualResourceLoader *loader, - VulkanDevice *device ) : - GpuProgram( creator, name, handle, group, isManual, loader ), - mDevice( device ), - mShaderModule( VK_NULL_HANDLE ) - { - if( createParamDictionary( "VulkanProgram" ) ) - { - setupBaseParamDictionary(); - } - - mDrawIdLocation = /*( mShaderSyntax == GLSL ) */ true ? 15 : 0; - } - //--------------------------------------------------------------------------- - VulkanProgram::~VulkanProgram() - { - // Have to call this here reather than in Resource destructor - // since calling virtual methods in base destructors causes crash - unload(); - } - //----------------------------------------------------------------------- - void VulkanProgram::loadFromSource() - { - mCompileError = false; - - VkShaderModuleCreateInfo moduleCi = {VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; - moduleCi.codeSize = mSource.size(); - moduleCi.pCode = (const uint32*)mSource.data(); - OGRE_VK_CHECK(vkCreateShaderModule(mDevice->mDevice, &moduleCi, 0, &mShaderModule)); - - setObjectName(mDevice->mDevice, (uint64_t)mShaderModule, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT, - mName.c_str()); - } - //--------------------------------------------------------------------------- - void VulkanProgram::unloadImpl() - { - vkDestroyShaderModule( mDevice->mDevice, mShaderModule, 0 ); - mShaderModule = VK_NULL_HANDLE; - } - //----------------------------------------------------------------------- - static VkShaderStageFlagBits get( GpuProgramType programType ) - { - switch( programType ) - { - // clang-format off - case GPT_VERTEX_PROGRAM: return VK_SHADER_STAGE_VERTEX_BIT; - case GPT_FRAGMENT_PROGRAM: return VK_SHADER_STAGE_FRAGMENT_BIT; - case GPT_GEOMETRY_PROGRAM: return VK_SHADER_STAGE_GEOMETRY_BIT; - case GPT_HULL_PROGRAM: return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT; - case GPT_DOMAIN_PROGRAM: return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT; - case GPT_COMPUTE_PROGRAM: return VK_SHADER_STAGE_COMPUTE_BIT; - // clang-format on - } - return VK_SHADER_STAGE_FRAGMENT_BIT; - } - VkPipelineShaderStageCreateInfo VulkanProgram::getPipelineShaderStageCi() const - { - VkPipelineShaderStageCreateInfo ret = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; - ret.stage = get( mType ); - ret.module = mShaderModule; - ret.pName = "main"; - return ret; - } - //----------------------------------------------------------------------- - const String &VulkanProgram::getLanguage( void ) const - { - static const String language = "spirv"; - return language; - } - //----------------------------------------------------------------------- - GpuProgramParametersSharedPtr VulkanProgram::createParameters( void ) - { - GpuProgramParametersSharedPtr params = GpuProgram::createParameters(); - params->setTransposeMatrices( true ); - return params; - } - //----------------------------------------------------------------------- - VulkanProgramFactory::VulkanProgramFactory( VulkanDevice *device ) : - mDevice( device ) - { - } - //----------------------------------------------------------------------- - VulkanProgramFactory::~VulkanProgramFactory( void ) - { - } - //----------------------------------------------------------------------- - const String& VulkanProgramFactory::getLanguage(void) const - { - static String language = "spirv"; - return language; - } - //----------------------------------------------------------------------- - GpuProgram *VulkanProgramFactory::create( ResourceManager *creator, const String &name, - ResourceHandle handle, const String &group, - bool isManual, ManualResourceLoader *loader ) - { - return OGRE_NEW VulkanProgram(creator, name, handle, group, isManual, loader, mDevice); - } -} // namespace Ogre diff --git a/RenderSystems/Vulkan/src/OgreVulkanQueue.cpp b/RenderSystems/Vulkan/src/OgreVulkanQueue.cpp deleted file mode 100644 index 8ea91c58d08..00000000000 --- a/RenderSystems/Vulkan/src/OgreVulkanQueue.cpp +++ /dev/null @@ -1,928 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-present Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreVulkanQueue.h" - -#include "OgreVulkanDevice.h" -#include "OgreVulkanMappings.h" -#include "OgreVulkanRenderSystem.h" -#include "OgreVulkanTextureGpu.h" -#include "OgreVulkanWindow.h" - -#include "OgreException.h" -#include "OgrePixelFormat.h" -#include "OgreStringConverter.h" - -#include "OgreVulkanUtils.h" -#include "OgreVulkanDescriptorPool.h" - -#define TODO_findRealPresentQueue -#define TODO_we_assume_has_stencil - -namespace Ogre -{ - // Mask away read flags from srcAccessMask - static const uint32 c_srcValidAccessFlags = - 0xFFFFFFFF ^ - ( VK_ACCESS_INDIRECT_COMMAND_READ_BIT | VK_ACCESS_INDEX_READ_BIT | - VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_UNIFORM_READ_BIT | - VK_ACCESS_INPUT_ATTACHMENT_READ_BIT | VK_ACCESS_SHADER_READ_BIT | - VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | - VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_HOST_READ_BIT | VK_ACCESS_MEMORY_READ_BIT ); - - VulkanQueue::VulkanQueue() : - mDevice( 0 ), - mFamily( NumQueueFamilies ), - mFamilyIdx( 0u ), - mQueueIdx( 0u ), - mQueue( 0 ), - mCurrentCmdBuffer( 0 ), - mOwnerDevice( 0 ), - mNumFramesInFlight( 3 ), - mCurrentFrameIdx( 0 ), - mRenderSystem( 0 ), - mCurrentFence( 0 ), - mEncoderState( EncoderClosed ), - mCopyEndReadSrcBufferFlags( 0 ), - mCopyEndReadDstBufferFlags( 0 ), - mCopyEndReadDstTextureFlags( 0 ), - mCopyStartWriteSrcBufferFlags( 0 ) - { - } - //------------------------------------------------------------------------- - VulkanQueue::~VulkanQueue() { destroy(); } - //------------------------------------------------------------------------- - void VulkanQueue::setQueueData( VulkanDevice *owner, QueueFamily family, uint32 familyIdx, - uint32 queueIdx ) - { - mOwnerDevice = owner; - mFamily = family; - mFamilyIdx = familyIdx; - mQueueIdx = queueIdx; - } - //------------------------------------------------------------------------- - void VulkanQueue::init( VkDevice device, VkQueue queue, VulkanRenderSystem *renderSystem ) - { - mDevice = device; - mQueue = queue; - mRenderSystem = renderSystem; - - mPerFrameData.resize( mNumFramesInFlight ); - - VkCommandPoolCreateInfo cmdPoolCreateInfo = {VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; - cmdPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT; - cmdPoolCreateInfo.queueFamilyIndex = mFamilyIdx; - - VkCommandBufferAllocateInfo allocateInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; - allocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - allocateInfo.commandBufferCount = 1u; - - VkFenceCreateInfo fenceCi = {VK_STRUCTURE_TYPE_FENCE_CREATE_INFO}; - fenceCi.flags = VK_FENCE_CREATE_SIGNALED_BIT; - - for (auto& fd : mPerFrameData) - { - OGRE_VK_CHECK(vkCreateCommandPool(mDevice, &cmdPoolCreateInfo, 0, &fd.mCommandPool)); - allocateInfo.commandPool = fd.mCommandPool; - OGRE_VK_CHECK(vkAllocateCommandBuffers( mDevice, &allocateInfo, &fd.mCommandBuffer )); - OGRE_VK_CHECK(vkCreateFence(mDevice, &fenceCi, 0, &fd.mProtectingFence)); - } - - newCommandBuffer(); - } - - void VulkanQueue::destroy() - { - if( mDevice ) - { - vkDeviceWaitIdle( mDevice ); - - for(size_t i = 0; i < mPerFrameData.size(); ++i) - { - _waitOnFrame(i); - } - - for(auto& fd : mPerFrameData) - { - vkDestroyFence( mDevice, fd.mProtectingFence, 0 ); - vkDestroyCommandPool( mDevice, fd.mCommandPool, 0 ); - } - - mDevice = 0; - } - } - - //------------------------------------------------------------------------- - void VulkanQueue::newCommandBuffer( void ) - { - _waitOnFrame(mCurrentFrameIdx); - - vkResetCommandPool(mDevice, mPerFrameData[mCurrentFrameIdx].mCommandPool, 0); - mCurrentCmdBuffer = mPerFrameData[mCurrentFrameIdx].mCommandBuffer; - mCurrentFence = mPerFrameData[mCurrentFrameIdx].mProtectingFence; - - VkCommandBufferBeginInfo beginInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - vkBeginCommandBuffer( mCurrentCmdBuffer, &beginInfo ); - } - //------------------------------------------------------------------------- - void VulkanQueue::endCommandBuffer( void ) - { - if( mCurrentCmdBuffer ) - { - endAllEncoders(); - - OGRE_VK_CHECK(vkEndCommandBuffer( mCurrentCmdBuffer )); - } - } - //------------------------------------------------------------------------- - void VulkanQueue::getGraphicsEncoder( void ) - { - if( mEncoderState != EncoderGraphicsOpen ) - { - endCopyEncoder(); - endComputeEncoder(); - - mEncoderState = EncoderGraphicsOpen; - } - } - //------------------------------------------------------------------------- - void VulkanQueue::getComputeEncoder( void ) - { - if( mEncoderState != EncoderComputeOpen ) - { - endRenderEncoder(); - endCopyEncoder(); - - mEncoderState = EncoderComputeOpen; - } - } - //------------------------------------------------------------------------- - VkPipelineStageFlags VulkanQueue::deriveStageFromBufferAccessFlags( VkAccessFlags accessFlags ) - { - VkPipelineStageFlags stage = 0; - if( accessFlags & VK_ACCESS_INDIRECT_COMMAND_READ_BIT ) - stage |= VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT; - if( accessFlags & ( VK_ACCESS_INDEX_READ_BIT | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT ) ) - { - stage |= VK_PIPELINE_STAGE_VERTEX_INPUT_BIT; - } - if( accessFlags & - ( VK_ACCESS_UNIFORM_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT ) ) - { - stage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | - VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | - VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | - VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - } - if( accessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) ) - { - stage |= VK_PIPELINE_STAGE_TRANSFER_BIT; - } - - return stage; - } - //------------------------------------------------------------------------- - VkPipelineStageFlags VulkanQueue::deriveStageFromTextureAccessFlags( VkAccessFlags accessFlags ) - { - VkPipelineStageFlags stage = 0; - if( accessFlags & ( VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | - VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT ) ) - { - stage |= - VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; - } - if( accessFlags & - ( VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT ) ) - { - stage |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - } - if( accessFlags & ( VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT ) ) - { - stage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | - VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | - VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | - VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - } - if( accessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) ) - { - stage |= VK_PIPELINE_STAGE_TRANSFER_BIT; - } - if( accessFlags & VK_ACCESS_INPUT_ATTACHMENT_READ_BIT ) - stage |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - - return stage; - } - //------------------------------------------------------------------------- - void VulkanQueue::insertRestoreBarrier( VulkanTextureGpu *vkTexture, - const VkImageLayout newTransferLayout ) - { - const VkImageLayout oldLayout = vkTexture->mCurrLayout; - - const VkImageLayout otherTransferLayout = - newTransferLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL - ? VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL - : VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - - const VkAccessFlags accessFlags = newTransferLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL - ? VK_ACCESS_TRANSFER_READ_BIT - : VK_ACCESS_TRANSFER_WRITE_BIT; - - if( oldLayout == newTransferLayout ) - { - // Nothing to do. A restore barrier has already been inserted - // If the assert fails, then the texture transitioned - // to this layout without us knowing - OGRE_ASSERT_HIGH( std::find( mImageMemBarrierPtrs.begin(), mImageMemBarrierPtrs.end(), - vkTexture ) != mImageMemBarrierPtrs.end() && - "Only this class should set VK_IMAGE_LAYOUT_TRANSFER_*_OPTIMAL" ); - } - else if( oldLayout == otherTransferLayout ) - { - // A restore barrier has already been inserted, but it needs modification - FastArray::iterator itor = - std::find( mImageMemBarrierPtrs.begin(), mImageMemBarrierPtrs.end(), vkTexture ); - - // If the assert fails, then the texture transitioned - // to this layout without us knowing - OGRE_ASSERT_LOW( itor != mImageMemBarrierPtrs.end() && - "Only this class should set VK_IMAGE_LAYOUT_TRANSFER_*_OPTIMAL" ); - - const size_t idx = ( size_t )( itor - mImageMemBarrierPtrs.begin() ); - VkImageMemoryBarrier &imageMemBarrier = *( mImageMemBarriers.begin() + idx ); - imageMemBarrier.srcAccessMask = accessFlags & c_srcValidAccessFlags; - imageMemBarrier.oldLayout = newTransferLayout; - } - else - { - // First time we see this texture - VkImageMemoryBarrier imageMemBarrier = vkTexture->getImageMemoryBarrier(); - imageMemBarrier.srcAccessMask = accessFlags & c_srcValidAccessFlags; - imageMemBarrier.dstAccessMask = VulkanMappings::get( vkTexture ); - if( newTransferLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ) - { - // We need to block subsequent stages from writing to this texture - // until we're done copying from it (but they can read) - imageMemBarrier.dstAccessMask &= (VkAccessFlags)~VK_ACCESS_SHADER_READ_BIT; - mCopyEndReadDstTextureFlags |= imageMemBarrier.dstAccessMask; - } - - imageMemBarrier.oldLayout = newTransferLayout; - imageMemBarrier.newLayout = vkTexture->mNextLayout; - mImageMemBarriers.push_back( imageMemBarrier ); - mImageMemBarrierPtrs.push_back( vkTexture ); - } - } - //------------------------------------------------------------------------- - void VulkanQueue::prepareForUpload( const BufferPacked *buffer, TextureGpu *texture ) - { - VkAccessFlags bufferAccessFlags = 0; - - if( buffer ) - { - BufferPackedDownloadMap::iterator it = mCopyDownloadBuffers.find( buffer ); - - if( it == mCopyDownloadBuffers.end() ) - ;//bufferAccessFlags = VulkanMappings::get( buffer->getBufferPackedType() ); - else - { - if( !it->second ) - { - // bufferAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT; - // We assume consecutive writes means we're writing to non-overlapping areas - // Do not wait for previous transfers. - bufferAccessFlags = 0; - } - else - bufferAccessFlags = VK_ACCESS_TRANSFER_READ_BIT; - } - - mCopyDownloadBuffers[buffer] = false; - - mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_WRITE_BIT; - } - - OGRE_ASSERT_HIGH( !texture || dynamic_cast( texture ) ); - VulkanTextureGpu *vkTexture = static_cast( texture ); - - VkAccessFlags texAccessFlags = 0; - - if( texture ) - { - TextureGpuDownloadMap::iterator it = mCopyDownloadTextures.find( vkTexture ); - - if( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_UNDEFINED ) - { - // This texture must just have been created - texAccessFlags = 0; - } - else if( it == mCopyDownloadTextures.end() ) - { - if( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL || - vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ) - { - OGRE_EXCEPT( Exception::ERR_INVALID_STATE, - "Texture " + vkTexture->getName() + - " is already in CopySrc or CopyDst layout, externally set. Perhaps " - "you need to call RenderSystem::flushTextureCopyOperations", - "VulkanQueue::prepareForUpload" ); - } - - texAccessFlags = VulkanMappings::get( texture ); - } - else - { - if( !it->second ) - { - OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ); - // texAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT; - // We assume consecutive writes means we're writing to non-overlapping areas - // Do not wait for previous transfers. - texAccessFlags = 0; - } - else - { - OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ); - texAccessFlags = VK_ACCESS_TRANSFER_READ_BIT; - } - } - - // We need to block subsequent stages from accessing this texture at all - // until we're done copying into it - mCopyEndReadDstTextureFlags |= VulkanMappings::get( texture ); - mCopyDownloadTextures[vkTexture] = false; - } - - // One buffer barrier is enough for all buffers. - // Unless we already issued a transfer to this same buffer - const bool bNeedsBufferBarrier = - ( bufferAccessFlags && - ( mCopyEndReadDstBufferFlags & bufferAccessFlags ) != bufferAccessFlags ) || - ( bufferAccessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) ); - - const bool bNeedsTexTransition = - vkTexture && vkTexture->mCurrLayout != VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - - mCopyEndReadDstBufferFlags |= bufferAccessFlags; - - // Trigger the barrier if we actually have to wait. - // And only if we haven't issued this barrier already - if( bNeedsBufferBarrier || bNeedsTexTransition ) - { - VkPipelineStageFlags srcStage = 0; - - uint32 numMemBarriers = 0u; - VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - if( bNeedsBufferBarrier ) - { - // GPU must stop using this buffer before we can write into it - memBarrier.srcAccessMask = bufferAccessFlags & c_srcValidAccessFlags; - memBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - - srcStage |= deriveStageFromBufferAccessFlags( bufferAccessFlags ); - numMemBarriers = 1u; - } - - uint32 numImageMemBarriers = 0u; - VkImageMemoryBarrier imageMemBarrier; - if( bNeedsTexTransition ) - { - // GPU must stop using this texture before we can write into it - // Also we need to do a transition - imageMemBarrier = vkTexture->getImageMemoryBarrier(); - imageMemBarrier.srcAccessMask = texAccessFlags & c_srcValidAccessFlags; - imageMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - imageMemBarrier.oldLayout = vkTexture->mCurrLayout; - imageMemBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - - if( texAccessFlags == 0u ) - { - if( bufferAccessFlags == 0u ) - { - // Wait for nothing. We're only issuing a barrier - // because of the texture transition - srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - } - } - else - { - srcStage |= deriveStageFromTextureAccessFlags( texAccessFlags ); - } - - insertRestoreBarrier( vkTexture, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ); - - vkTexture->mCurrLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - numImageMemBarriers = 1u; - } - - // Wait until earlier render, compute and transfers are done so we can copy what - // they wrote (unless we're only here for a texture transition) - vkCmdPipelineBarrier( mCurrentCmdBuffer, srcStage & mOwnerDevice->mSupportedStages, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, numMemBarriers, &memBarrier, 0u, 0, - numImageMemBarriers, &imageMemBarrier ); - } - } - //------------------------------------------------------------------------- - void VulkanQueue::prepareForDownload( const BufferPacked *buffer, VulkanTextureGpu *texture ) - { - VkAccessFlags bufferAccessFlags = 0; - VkPipelineStageFlags srcStage = 0; - - // Evaluate the stages which blocks us before we can begin our transfer - if( buffer ) - { - BufferPackedDownloadMap::iterator it = mCopyDownloadBuffers.find( buffer ); - - if( it == mCopyDownloadBuffers.end() ) - { - if( /*buffer->getBufferPackedType() == BP_TYPE_UAV*/ 0 ) - { - bufferAccessFlags = VK_ACCESS_SHADER_WRITE_BIT; - srcStage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | - VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | - VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | - VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | - VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - } - // else - //{ - // If the buffer is not BT_TYPE_UAV, the GPU won't modify these buffers, - // we can start downloading right away without waiting - //} - } - else - { - if( !it->second ) - { - bufferAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT; - srcStage |= VK_PIPELINE_STAGE_TRANSFER_BIT; - } - else - bufferAccessFlags = 0; // Consecutive reads don't require waiting - } - - mCopyDownloadBuffers[buffer] = true; - - mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_READ_BIT; - } - - OGRE_ASSERT_HIGH( !texture || dynamic_cast( texture ) ); - VulkanTextureGpu *vkTexture = static_cast( texture ); - - VkAccessFlags texAccessFlags = 0; - - if( texture ) - { - TextureGpuDownloadMap::iterator it = mCopyDownloadTextures.find( vkTexture ); - - if( it == mCopyDownloadTextures.end() ) - { - if( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL || - vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ) - { - OGRE_EXCEPT( Exception::ERR_INVALID_STATE, - "Texture " + vkTexture->getName() + - " is already in CopySrc or CopyDst layout, externally set. Perhaps " - "you need to call RenderSystem::flushTextureCopyOperations", - "VulkanQueue::prepareForDownload" ); - } - - if( texture->isUav() ) - { - texAccessFlags |= VK_ACCESS_SHADER_WRITE_BIT; - srcStage |= VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | - VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | - VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | - VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | - VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; - } - - if( texture->getUsage() & TU_RENDERTARGET ) - { - if( !PixelUtil::isDepth( texture->getFormat() ) ) - { - texAccessFlags |= VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; - srcStage |= VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - } - else - { - texAccessFlags |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; - srcStage |= VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | - VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; - } - } - } - else - { - if( !it->second ) - { - OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ); - texAccessFlags = VK_ACCESS_TRANSFER_WRITE_BIT; - srcStage |= VK_PIPELINE_STAGE_TRANSFER_BIT; - } - else - { - OGRE_ASSERT_MEDIUM( vkTexture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ); - texAccessFlags = 0; // Consecutive reads don't require waiting - } - } - - mCopyDownloadTextures[vkTexture] = true; - } - - // One buffer barrier is enough for all buffers. - // Unless we already issued a transfer to this same buffer - const bool bNeedsBufferBarrier = - ( bufferAccessFlags && - ( mCopyStartWriteSrcBufferFlags & bufferAccessFlags ) != bufferAccessFlags ) || - ( bufferAccessFlags & ( VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT ) ); - - mCopyStartWriteSrcBufferFlags |= bufferAccessFlags; - - const bool bNeedsTexTransition = - vkTexture && vkTexture->mCurrLayout != VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - - // Trigger the barrier if we actually have to wait. - // And only if we haven't issued this barrier already - if( bNeedsBufferBarrier || bNeedsTexTransition ) - { - uint32 numMemBarriers = 0u; - VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - if( bNeedsBufferBarrier ) - { - memBarrier.srcAccessMask = bufferAccessFlags & c_srcValidAccessFlags; - memBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - numMemBarriers = 1u; - } - - uint32 numImageMemBarriers = 0u; - VkImageMemoryBarrier imageMemBarrier; - if( bNeedsTexTransition ) - { - imageMemBarrier = vkTexture->getImageMemoryBarrier(); - imageMemBarrier.srcAccessMask = texAccessFlags & c_srcValidAccessFlags; - imageMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - imageMemBarrier.oldLayout = vkTexture->mCurrLayout; - imageMemBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - - insertRestoreBarrier( vkTexture, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ); - - vkTexture->mCurrLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - numImageMemBarriers = 1u; - - if( !srcStage ) - { - // If we're here the texture is read-only and we only - // need the barrier to perform a layout transition - srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - } - } - - // Wait until earlier render, compute and transfers are done so we can copy what - // they wrote (unless we're only here for a texture transition) - vkCmdPipelineBarrier( mCurrentCmdBuffer, srcStage & mOwnerDevice->mSupportedStages, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, numMemBarriers, &memBarrier, 0u, 0, - numImageMemBarriers, &imageMemBarrier ); - } - } - //------------------------------------------------------------------------- - void VulkanQueue::getCopyEncoder( const BufferPacked *buffer, VulkanTextureGpu *texture, - const bool bDownload ) - { - OgreAssert(mEncoderState != EncoderGraphicsOpen, "interrupting RenderPass not supported"); - if( mEncoderState != EncoderCopyOpen ) - { - endRenderEncoder(); - endComputeEncoder(); - - mEncoderState = EncoderCopyOpen; - - // Submission guarantees the host write being complete, as per - // khronos.org/registry/vulkan/specs/1.0/html/vkspec.html#synchronization-submission-host-writes - // So no need for a barrier before the transfer - // - // The only exception is when writing from CPU to GPU when a command that uses that region - // has already been submitted via vkQueueSubmit (and you're using vkCmdWaitEvents to wait - // for the CPU to write the data and give ok to the GPU). - // Which Ogre does not do (too complex to get right). - } - - if( bDownload ) - prepareForDownload( buffer, texture ); - else - prepareForUpload( buffer, texture ); - } - //------------------------------------------------------------------------- - void VulkanQueue::getCopyEncoderV1Buffer( const bool bDownload ) - { - OgreAssert(mEncoderState != EncoderGraphicsOpen, "interrupting RenderPass not supported"); - if( mEncoderState != EncoderCopyOpen ) - { - endRenderEncoder(); - endComputeEncoder(); - - mEncoderState = EncoderCopyOpen; - } - - if( !bDownload ) - { - // V1 buffers are only used for vertex and index buffers - // We assume v1 buffers don't try to write then read (or read then write) in a row - const VkAccessFlags bufferAccessFlags = - VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_INDEX_READ_BIT; - - if( ( mCopyEndReadDstBufferFlags & bufferAccessFlags ) != bufferAccessFlags ) - { - uint32 numMemBarriers = 0u; - VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - memBarrier.srcAccessMask = bufferAccessFlags & c_srcValidAccessFlags; - memBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - numMemBarriers = 1u; - - // GPU must stop using this buffer before we can write into it - vkCmdPipelineBarrier( mCurrentCmdBuffer, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, numMemBarriers, &memBarrier, 0u, - 0, 0u, 0 ); - } - - mCopyEndReadDstBufferFlags |= bufferAccessFlags; - mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_WRITE_BIT; - } - else - { - mCopyEndReadSrcBufferFlags |= VK_ACCESS_TRANSFER_READ_BIT; - } - } - //------------------------------------------------------------------------- - void VulkanQueue::endCopyEncoder( void ) - { - if( mEncoderState != EncoderCopyOpen ) - return; - - if( mCopyEndReadDstBufferFlags || !mImageMemBarrierPtrs.empty() ) - { - VkPipelineStageFlags dstStage = 0; - - uint32 numMemBarriers = 0u; - VkMemoryBarrier memBarrier = {VK_STRUCTURE_TYPE_MEMORY_BARRIER}; - if( mCopyEndReadDstBufferFlags ) - { - memBarrier.srcAccessMask = mCopyEndReadSrcBufferFlags & c_srcValidAccessFlags; - memBarrier.dstAccessMask = mCopyEndReadDstBufferFlags; - - // Evaluate the stages we can unblock when our transfers are done - dstStage |= deriveStageFromBufferAccessFlags( memBarrier.dstAccessMask ); - numMemBarriers = 1u; - } - - dstStage |= deriveStageFromTextureAccessFlags( mCopyEndReadDstTextureFlags ); - - if( dstStage == 0u ) - { - // Nothing needs to wait for us. Can happen if all we're - // doing is copying from read-only textures (rare) - dstStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; - -#if OGRE_DEBUG_MODE - FastArray::const_iterator itor = mImageMemBarrierPtrs.begin(); - FastArray::const_iterator endt = mImageMemBarrierPtrs.end(); - - while( itor != endt ) - { - OgreAssert( (( *itor )->getUsage() & TU_RENDERTARGET) == 0/*&& !( *itor )->isUav()*/, - "endCopyEncoder says nothing will wait on this texture(s) but " - "we don't know if a subsequent stage will write to it" ); - ++itor; - } -#endif - } - - // Wait until earlier render, compute and transfers are done - // Block render, compute and transfers until we're done - vkCmdPipelineBarrier( mCurrentCmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, - dstStage & mOwnerDevice->mSupportedStages, 0, numMemBarriers, - &memBarrier, 0u, 0, static_cast( mImageMemBarriers.size() ), - mImageMemBarriers.data() ); - - mImageMemBarriers.clear(); - mImageMemBarrierPtrs.clear(); - - TextureGpuDownloadMap::const_iterator itor = mCopyDownloadTextures.begin(); - TextureGpuDownloadMap::const_iterator endt = mCopyDownloadTextures.end(); - - while( itor != endt ) - { - itor->first->mCurrLayout = itor->first->mNextLayout; - ++itor; - } - } - - mCopyEndReadSrcBufferFlags = 0; - mCopyEndReadDstBufferFlags = 0; - mCopyEndReadDstTextureFlags = 0; - mCopyStartWriteSrcBufferFlags = 0; - - mCopyDownloadTextures.clear(); - mCopyDownloadBuffers.clear(); - - mEncoderState = EncoderClosed; - } - //------------------------------------------------------------------------- - void VulkanQueue::endRenderEncoder( const bool endRenderPassDesc ) - { - if( mEncoderState != EncoderGraphicsOpen ) - return; - mRenderSystem->_notifyActiveEncoderEnded(); - if( endRenderPassDesc ) - mRenderSystem->endRenderPassDescriptor(); - mEncoderState = EncoderClosed; - } - //------------------------------------------------------------------------- - void VulkanQueue::endComputeEncoder( void ) - { - if( mEncoderState != EncoderComputeOpen ) - return; - - mEncoderState = EncoderClosed; - mRenderSystem->_notifyActiveComputeEnded(); - } - //------------------------------------------------------------------------- - void VulkanQueue::endAllEncoders( const bool endRenderPassDesc ) - { - endCopyEncoder(); - endRenderEncoder( endRenderPassDesc ); - endComputeEncoder(); - } - //------------------------------------------------------------------------- - void VulkanQueue::notifyTextureDestroyed( VulkanTextureGpu *texture ) - { - if( mEncoderState == EncoderCopyOpen ) - { - bool needsToFlush = false; - TextureGpuDownloadMap::const_iterator itor = mCopyDownloadTextures.find( texture ); - - if( itor != mCopyDownloadTextures.end() ) - needsToFlush = true; - else - { - FastArray::const_iterator it2 = - std::find( mImageMemBarrierPtrs.begin(), mImageMemBarrierPtrs.end(), texture ); - if( it2 != mImageMemBarrierPtrs.end() ) - needsToFlush = true; - } - - if( needsToFlush ) - { - // If this asserts triggers, then the texture is probably being referenced - // by something else doing anything on the texture and was interrupted - // midway (since Ogre must ensure the texture ends in TRANSFER_SRC/DST_OPTIMAL - // if the copy encoder is holding a reference. - OGRE_ASSERT_LOW( texture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL || - texture->mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ); - endCopyEncoder(); - } - } - } - //------------------------------------------------------------------------- - void VulkanQueue::addWindowToWaitFor( VkSemaphore imageAcquisitionSemaph ) - { - OGRE_ASSERT_MEDIUM( mFamily == Graphics ); - mGpuWaitFlags.push_back( VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT ); - mGpuWaitSemaphForCurrCmdBuff.push_back( imageAcquisitionSemaph ); - } - //------------------------------------------------------------------------- - void VulkanQueue::queueForDeletion(VkBuffer buffer, VmaAllocation allocation) - { - mPerFrameData[mCurrentFrameIdx].mBufferGraveyard.push_back({buffer, allocation}); - } - void VulkanQueue::queueForDeletion(const std::shared_ptr& descriptorPool) - { - mPerFrameData[mCurrentFrameIdx].mDescriptorPoolGraveyard.push_back(descriptorPool); - } - void VulkanQueue::_waitOnFrame( uint8 frameIdx ) - { - VkFence fence = mPerFrameData[frameIdx].mProtectingFence; - vkWaitForFences( mDevice, 1, &fence, VK_TRUE, UINT64_MAX ); - - // it is safe to free staging buffers now - for(auto bm : mPerFrameData[frameIdx].mBufferGraveyard) - { - vmaDestroyBuffer(mOwnerDevice->getAllocator(), bm.first, bm.second); - } - mPerFrameData[frameIdx].mBufferGraveyard.clear(); - mPerFrameData[frameIdx].mDescriptorPoolGraveyard.clear(); - } - //------------------------------------------------------------------------- - bool VulkanQueue::_isFrameFinished( uint8 frameIdx ) - { - VkFence fence = mPerFrameData[frameIdx].mProtectingFence; - VkResult ret = vkWaitForFences( mDevice, 1, &fence, VK_TRUE, 0u ); - if( ret != VK_TIMEOUT ) - { - OGRE_VK_CHECK(ret); - //recycleFences( fences ); - return true; - } - - return false; - } - //------------------------------------------------------------------------- - void VulkanQueue::commitAndNextCommandBuffer( SubmissionType::SubmissionType submissionType ) - { - endCommandBuffer(); - - VkSubmitInfo submitInfo = {VK_STRUCTURE_TYPE_SUBMIT_INFO}; - submitInfo.commandBufferCount = 1; - submitInfo.pCommandBuffers = &mCurrentCmdBuffer; - - if( !mGpuWaitSemaphForCurrCmdBuff.empty() ) - { - // We need to wait on these semaphores so that rendering can - // only happen start the swapchain is done presenting - submitInfo.waitSemaphoreCount = mGpuWaitSemaphForCurrCmdBuff.size(); - submitInfo.pWaitSemaphores = mGpuWaitSemaphForCurrCmdBuff.data(); - submitInfo.pWaitDstStageMask = mGpuWaitFlags.data(); - } - - if( submissionType >= SubmissionType::NewFrameIdx ) - { - if( submissionType >= SubmissionType::EndFrameAndSwap ) - { - // Get semaphores so that presentation can wait for this job to finish rendering - // (one for each window that will be swapped) - for (auto w : mWindowsPendingSwap) - { - mGpuSignalSemaphForCurrCmdBuff.push_back(w->getRenderFinishedSemaphore()); - w->setImageFence(mCurrentFence); - } - } - - if( !mGpuSignalSemaphForCurrCmdBuff.empty() ) - { - // We need to signal these semaphores so that presentation - // can only happen after we're done rendering (presentation may not be the - // only thing waiting for us though; thus we must set this with NewFrameIdx - // and not just with EndFrameAndSwap) - submitInfo.signalSemaphoreCount = mGpuSignalSemaphForCurrCmdBuff.size(); - submitInfo.pSignalSemaphores = mGpuSignalSemaphForCurrCmdBuff.data(); - } - } - - OGRE_VK_CHECK(vkResetFences(mDevice, 1, &mCurrentFence) ); - vkQueueSubmit( mQueue, 1u, &submitInfo, mCurrentFence ); - mGpuWaitSemaphForCurrCmdBuff.clear(); - mCurrentCmdBuffer = VK_NULL_HANDLE; - - if( submissionType >= SubmissionType::EndFrameAndSwap ) - { - for (auto w : mWindowsPendingSwap) - w->_swapBuffers(); - } - - if( submissionType >= SubmissionType::NewFrameIdx ) - { - mCurrentFrameIdx = (mCurrentFrameIdx + 1) % mPerFrameData.size(); - } - - newCommandBuffer(); - - if( submissionType >= SubmissionType::EndFrameAndSwap ) - { - // acquireNextImage must be called after newCommandBuffer() - for (auto w : mWindowsPendingSwap) - w->acquireNextImage(); - mWindowsPendingSwap.clear(); - - mGpuSignalSemaphForCurrCmdBuff.clear(); - } - } -} // namespace Ogre diff --git a/RenderSystems/Vulkan/src/OgreVulkanRenderPassDescriptor.cpp b/RenderSystems/Vulkan/src/OgreVulkanRenderPassDescriptor.cpp deleted file mode 100644 index a4b8614b71a..00000000000 --- a/RenderSystems/Vulkan/src/OgreVulkanRenderPassDescriptor.cpp +++ /dev/null @@ -1,559 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-present Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreVulkanRenderPassDescriptor.h" - -#include "OgreVulkanDevice.h" -#include "OgreVulkanRenderSystem.h" -#include "OgreVulkanTextureGpu.h" -#include "OgreVulkanTextureGpuWindow.h" -#include "OgreVulkanWindow.h" - -#include "OgreVulkanMappings.h" -#include "OgreVulkanUtils.h" - -namespace Ogre -{ - VulkanRenderPassDescriptor::VulkanRenderPassDescriptor( VulkanQueue *graphicsQueue, - VulkanRenderSystem *renderSystem ) : - mSharedFboItor( renderSystem->_getFrameBufferDescMap().end() ), - mTargetWidth( 0u ), - mTargetHeight( 0u ), - mQueue( graphicsQueue ), - mRenderSystem( renderSystem ) - { - } - //----------------------------------------------------------------------------------- - VulkanRenderPassDescriptor::~VulkanRenderPassDescriptor() { releaseFbo(); } - //----------------------------------------------------------------------------------- - void VulkanRenderPassDescriptor::calculateSharedKey( void ) - { - uint32 hash = FastHash((const char*)mColour, mNumColourEntries * sizeof(mColour[0])); - hash = HashCombine(hash, mDepth); - - VulkanFrameBufferDescMap &frameBufferDescMap = mRenderSystem->_getFrameBufferDescMap(); - VulkanFrameBufferDescMap::iterator newItor = frameBufferDescMap.find( hash ); - - if( newItor == frameBufferDescMap.end() ) - { - VulkanFrameBufferDescValue value; - value.refCount = 0; - frameBufferDescMap[hash] = value; - newItor = frameBufferDescMap.find(hash); - } - - ++newItor->second.refCount; - - releaseFbo(); - - mSharedFboItor = newItor; - } - //----------------------------------------------------------------------------------- - VkClearColorValue VulkanRenderPassDescriptor::getClearColour( const ColourValue &clearColour, - PixelFormatGpu pixelFormat ) - { - const bool isInteger = PixelUtil::isInteger( pixelFormat ); - const bool isSigned = false;//PixelUtil::isSigned( pixelFormat ); - VkClearColorValue retVal; - if( !isInteger ) - { - for( size_t i = 0u; i < 4u; ++i ) - retVal.float32[i] = static_cast( clearColour[i] ); - } - else - { - if( !isSigned ) - { - for( size_t i = 0u; i < 4u; ++i ) - retVal.uint32[i] = static_cast( clearColour[i] ); - } - else - { - for( size_t i = 0u; i < 4u; ++i ) - retVal.int32[i] = static_cast( clearColour[i] ); - } - } - return retVal; - } - //----------------------------------------------------------------------------------- - /** - @brief VulkanRenderPassDescriptor::setupColourAttachment - This will setup: - attachments[currAttachmIdx] - colourAttachRefs[vkIdx] - resolveAttachRefs[vkIdx] - fboDesc.mImageViews[currAttachmIdx] - fboDesc.mWindowImageViews - - Except mWindowImageViews, all the other variables are *always* written to. - @param idx [in] - idx to mColour[idx] - @param fboDesc [in/out] - @param attachments [out] - A pointer to setup VkAttachmentDescription - @param currAttachmIdx [in/out] - A value to index attachments[currAttachmIdx] - @param colourAttachRefs [out] - A pointer to setup VkAttachmentReference - @param resolveAttachRefs [out] - A pointer to setup VkAttachmentReference - @param vkIdx [in] - A value to index both colourAttachRefs[vkIdx] & resolveAttachRefs[vkIdx] - Very often idx == vkIdx except when we skip a colour entry due to being PFG_NULL - @param resolveTex - False if we're setting up the main target - True if we're setting up the resolve target - */ - void VulkanRenderPassDescriptor::setupColourAttachment( - const size_t idx, VulkanFrameBufferDescValue &fboDesc, VkAttachmentDescription *attachments, - uint32 &currAttachmIdx, VkAttachmentReference *colourAttachRefs, - VkAttachmentReference *resolveAttachRefs, const size_t vkIdx, const bool bResolveTex ) - { - VulkanTextureGpu* colour = mColour[idx]; - - if (!colour->getMsaaTextureName() && bResolveTex) - { - // There's no resolve texture to setup - resolveAttachRefs[vkIdx].attachment = VK_ATTACHMENT_UNUSED; - resolveAttachRefs[vkIdx].layout = VK_IMAGE_LAYOUT_UNDEFINED; - return; - } - - VkImage texName = 0; - VulkanTextureGpu *texture = colour; - - if( !bResolveTex && texture->getMsaaTextureName()) - { - texName = texture->getMsaaTextureName(); - } - else - { - texName = texture->getFinalTextureName(); - } - - VkAttachmentDescription &attachment = attachments[currAttachmIdx]; - attachment.format = VulkanMappings::get( texture->getFormat(), texture->isHardwareGammaEnabled() ); - attachment.samples = bResolveTex ? VK_SAMPLE_COUNT_1_BIT : VkSampleCountFlagBits(colour->getFSAA()); - attachment.loadOp = bResolveTex ? VK_ATTACHMENT_LOAD_OP_DONT_CARE : VK_ATTACHMENT_LOAD_OP_CLEAR;// TODO colour.loadAction ); - attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; // TODO colour.storeAction - attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; - attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - if( !bResolveTex ) - { - attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; // TODO VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - if (texture->isRenderWindowSpecific() && !texture->isMultisample()) - { - attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; - } - else if(!texture->isMultisample()) - { - attachment.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - } - else - { - attachment.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - } - } - else - { - attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - if (texture->isRenderWindowSpecific()) - attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; - else - attachment.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - } - - const uint8 mipLevel = 0;//bResolveTex ? colour.resolveMipLevel : colour.mipLevel; - //mSlice = bResolveTex ? colour.resolveSlice : colour.slice; - - if( !texture->isRenderWindowSpecific() || ( texture->isMultisample() && !bResolveTex ) ) - { - fboDesc.mImageViews[currAttachmIdx] = texture->_createView(mipLevel, 1, mSlice, 1u, texName); - } - else - { - fboDesc.mImageViews[currAttachmIdx] = 0; // Set to null (will be set later, 1 for each FBO) - auto textureVulkan = dynamic_cast(texture); - - OGRE_ASSERT_LOW(fboDesc.mWindowImageViews.empty() && "Only one window can be used as target"); - fboDesc.mWindowImageViews = textureVulkan->getWindow()->getSwapchainImageViews(); - } - - if( bResolveTex ) - { - resolveAttachRefs[vkIdx].attachment = currAttachmIdx; - resolveAttachRefs[vkIdx].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - ++currAttachmIdx; - } - else - { - colourAttachRefs[vkIdx].attachment = currAttachmIdx; - colourAttachRefs[vkIdx].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - ++currAttachmIdx; - - // Now repeat with the resolve texture (if applies) - setupColourAttachment( idx, fboDesc, attachments, currAttachmIdx, colourAttachRefs, - resolveAttachRefs, vkIdx, true ); - } - } - //----------------------------------------------------------------------------------- - VkImageView VulkanRenderPassDescriptor::setupDepthAttachment( VkAttachmentDescription &attachment ) - { - attachment.format = VulkanMappings::get( mDepth->getFormat() ); - attachment.samples = VkSampleCountFlagBits(std::max(mDepth->getFSAA(), 1u)); - attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; - attachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - if( 0 ) - { - attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; - attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - } - else - { - attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; - attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; - } - - attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - if(mNumColourEntries == 0) - { - // assume depth will be read - attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; - attachment.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - } - else - { - attachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; - } - - VulkanTextureGpu *texture = mDepth; - VkImage texName = - texture->getMsaaTextureName() ? texture->getMsaaTextureName() : texture->getFinalTextureName(); - return texture->_createView(0, 1, 0, 1u, texName); - } - //----------------------------------------------------------------------------------- - void VulkanRenderPassDescriptor::setupFbo( VulkanFrameBufferDescValue &fboDesc ) - { - if( fboDesc.mRenderPass ) - return; // Already initialized - - bool hasRenderWindow = false; - - uint32 attachmentIdx = 0u; - uint32 numColourAttachments = 0u; - uint32 windowAttachmentIdx = std::numeric_limits::max(); - bool usesResolveAttachments = false; - - // 1 per MRT - // 1 per MRT MSAA resolve - // 1 for Depth buffer - // 1 for Stencil buffer - VkAttachmentDescription attachments[OGRE_MAX_MULTIPLE_RENDER_TARGETS * 2u + 2u] = {}; - - VkAttachmentReference colourAttachRefs[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; - VkAttachmentReference resolveAttachRefs[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; - VkAttachmentReference depthAttachRef; - - for( size_t i = 0; i < mNumColourEntries; ++i ) - { - hasRenderWindow |= mColour[i]->isRenderWindowSpecific(); - - if( mColour[i]->getFormat() == PF_UNKNOWN ) - continue; - - OGRE_ASSERT_HIGH( dynamic_cast( mColour[i] ) ); - VulkanTextureGpu *textureVulkan = static_cast( mColour[i] ); - - if( textureVulkan->isRenderWindowSpecific() ) - { - windowAttachmentIdx = attachmentIdx; - // use the resolve texture idx - if (textureVulkan->getMsaaTextureName()) - windowAttachmentIdx++; - } - - setupColourAttachment( i, fboDesc, attachments, attachmentIdx, colourAttachRefs, - resolveAttachRefs, numColourAttachments, false ); - if( resolveAttachRefs[numColourAttachments].attachment != VK_ATTACHMENT_UNUSED ) - usesResolveAttachments = true; - ++numColourAttachments; - } - - if( mDepth ) - { - fboDesc.mImageViews[attachmentIdx] = setupDepthAttachment( attachments[attachmentIdx] ); - depthAttachRef.attachment = attachmentIdx; - if(0)// mDepth.readOnly ) - depthAttachRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL; - else - depthAttachRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; - ++attachmentIdx; - } - - VkSubpassDescription subpass = {VK_PIPELINE_BIND_POINT_GRAPHICS}; - subpass.inputAttachmentCount = 0u; - subpass.colorAttachmentCount = numColourAttachments; - subpass.pColorAttachments = colourAttachRefs; - subpass.pResolveAttachments = usesResolveAttachments ? resolveAttachRefs : 0; - subpass.pDepthStencilAttachment = mDepth ? &depthAttachRef : 0; - - fboDesc.mNumImageViews = attachmentIdx; - - // Use subpass dependencies for layout transitions for RenderTextures - auto accessMask = - mNumColourEntries ? VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT : VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; - std::array dependencies; - dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; - dependencies[0].dstSubpass = 0; - dependencies[0].srcStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - dependencies[0].srcAccessMask = VK_ACCESS_SHADER_READ_BIT; - dependencies[0].dstAccessMask = accessMask; - dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; - - dependencies[1].srcSubpass = 0; - dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; - dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - dependencies[1].dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; - dependencies[1].srcAccessMask = accessMask; - dependencies[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; - dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; - - VkRenderPassCreateInfo renderPassCreateInfo = {VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO}; - renderPassCreateInfo.attachmentCount = attachmentIdx; - renderPassCreateInfo.pAttachments = attachments; - renderPassCreateInfo.subpassCount = 1u; - renderPassCreateInfo.pSubpasses = &subpass; - - if(!hasRenderWindow) - { - renderPassCreateInfo.dependencyCount = dependencies.size(); - renderPassCreateInfo.pDependencies = dependencies.data(); - } - - OGRE_VK_CHECK(vkCreateRenderPass( mQueue->mDevice, &renderPassCreateInfo, 0, &fboDesc.mRenderPass )); - - VkFramebufferCreateInfo fbCreateInfo = {VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; - fbCreateInfo.renderPass = fboDesc.mRenderPass; - fbCreateInfo.attachmentCount = attachmentIdx; - fbCreateInfo.pAttachments = fboDesc.mImageViews; - fbCreateInfo.width = mTargetWidth; - fbCreateInfo.height = mTargetHeight; - fbCreateInfo.layers = 1u; - - const size_t numFramebuffers = std::max( fboDesc.mWindowImageViews.size(), 1u ); - fboDesc.mFramebuffers.resize( numFramebuffers ); - for( size_t i = 0u; i < numFramebuffers; ++i ) - { - if( !fboDesc.mWindowImageViews.empty() ) - fboDesc.mImageViews[windowAttachmentIdx] = fboDesc.mWindowImageViews[i]; - OGRE_VK_CHECK(vkCreateFramebuffer(mQueue->mDevice, &fbCreateInfo, 0, &fboDesc.mFramebuffers[i])); - if( !fboDesc.mWindowImageViews.empty() ) - fboDesc.mImageViews[windowAttachmentIdx] = 0; - } - } - //----------------------------------------------------------------------------------- - void VulkanRenderPassDescriptor::releaseFbo( void ) - { - VulkanFrameBufferDescMap &frameBufferDescMap = mRenderSystem->_getFrameBufferDescMap(); - if( mSharedFboItor != frameBufferDescMap.end() ) - { - --mSharedFboItor->second.refCount; - if( !mSharedFboItor->second.refCount ) - { - destroyFbo( mQueue, mSharedFboItor->second ); - frameBufferDescMap.erase( mSharedFboItor ); - } - mSharedFboItor = frameBufferDescMap.end(); - } - } - //----------------------------------------------------------------------------------- - void VulkanRenderPassDescriptor::destroyFbo( VulkanQueue *queue, - VulkanFrameBufferDescValue &fboDesc ) - { - //VaoManager *vaoManager = queue->getVaoManager(); - - { - FastArray::const_iterator itor = fboDesc.mFramebuffers.begin(); - FastArray::const_iterator endt = fboDesc.mFramebuffers.end(); - while( itor != endt ) - vkDestroyFramebuffer( queue->mDevice, *itor++, 0 ); - fboDesc.mFramebuffers.clear(); - } - - for( size_t i = 0u; i < fboDesc.mNumImageViews; ++i ) - { - if( fboDesc.mImageViews[i] ) - { - vkDestroyImageView( queue->mDevice, fboDesc.mImageViews[i], 0 ); - fboDesc.mImageViews[i] = 0; - } - } - fboDesc.mNumImageViews = 0u; - - vkDestroyRenderPass( queue->mDevice, fboDesc.mRenderPass, 0 ); - fboDesc.mRenderPass = 0; - } - //----------------------------------------------------------------------------------- - void VulkanRenderPassDescriptor::entriesModified( bool createFbo ) - { - calculateSharedKey(); - - TextureGpu *anyTargetTexture = 0; - const uint8 numColourEntries = mNumColourEntries; - for( int i = 0; i < numColourEntries && !anyTargetTexture; ++i ) - anyTargetTexture = mColour[i]; - if( !anyTargetTexture ) - anyTargetTexture = mDepth; - - mTargetWidth = 0u; - mTargetHeight = 0u; - if( anyTargetTexture ) - { - mTargetWidth = anyTargetTexture->getWidth(); - mTargetHeight = anyTargetTexture->getHeight(); - } - - if( createFbo ) - setupFbo( mSharedFboItor->second ); - } - //----------------------------------------------------------------------------------- - void VulkanRenderPassDescriptor::setClearColour( uint8 idx, const ColourValue &clearColour ) - { - //RenderPassDescriptor::setClearColour( idx, clearColour ); - - size_t attachmentIdx = 0u; - for( size_t i = 0u; i < idx; ++i ) - { - ++attachmentIdx; - if (mColour[i]->getMsaaTextureName()) - ++attachmentIdx; - } - - mClearValues[attachmentIdx].color = - getClearColour( clearColour, mColour[idx]->getFormat() ); - } - //----------------------------------------------------------------------------------- - void VulkanRenderPassDescriptor::setClearDepth( float clearDepth ) - { - //RenderPassDescriptor::setClearDepth( clearDepth ); - if( mDepth && mSharedFboItor != mRenderSystem->_getFrameBufferDescMap().end() ) - { - size_t attachmentIdx = mSharedFboItor->second.mNumImageViews - 1u; - if( !mRenderSystem->isReverseDepthBufferEnabled() ) - mClearValues[attachmentIdx].depthStencil.depth = clearDepth; - else - { - mClearValues[attachmentIdx].depthStencil.depth = 1.0f - clearDepth; - } - } - } - //----------------------------------------------------------------------------------- - void VulkanRenderPassDescriptor::setClearStencil( uint32 clearStencil ) - { - //RenderPassDescriptor::setClearStencil( clearStencil ); - if (mDepth && mSharedFboItor != mRenderSystem->_getFrameBufferDescMap().end()) - { - size_t attachmentIdx = mSharedFboItor->second.mNumImageViews - 1u; - mClearValues[attachmentIdx].depthStencil.stencil = clearStencil; - } - } - //----------------------------------------------------------------------------------- - void VulkanRenderPassDescriptor::setClearColour( const ColourValue &clearColour ) - { - const size_t numColourEntries = mNumColourEntries; - size_t attachmentIdx = 0u; - for( size_t i = 0u; i < numColourEntries; ++i ) - { - mClearValues[attachmentIdx].color = getClearColour(clearColour, mColour[i]->getFormat()); - ++attachmentIdx; - if (mColour[i]->getMsaaTextureName()) - ++attachmentIdx; - } - } - VkRenderPass VulkanRenderPassDescriptor::getRenderPass() const - { - return mSharedFboItor->second.mRenderPass; - } - //----------------------------------------------------------------------------------- - void VulkanRenderPassDescriptor::performLoadActions() - { - VkCommandBuffer cmdBuffer = mQueue->mCurrentCmdBuffer; - - const VulkanFrameBufferDescValue &fboDesc = mSharedFboItor->second; - - size_t fboIdx = 0u; - if( !fboDesc.mWindowImageViews.empty() ) - { - VulkanTextureGpuWindow* textureVulkan = static_cast(mColour[0]); - fboIdx = textureVulkan->getCurrentImageIdx(); - - VkSemaphore semaphore = textureVulkan->getImageAcquiredSemaphore(); - if( semaphore ) - { - // We cannot start executing color attachment commands until the semaphore says so - mQueue->addWindowToWaitFor( semaphore ); - } - } - - VkRenderPassBeginInfo passBeginInfo = {VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; - passBeginInfo.renderPass = fboDesc.mRenderPass; - passBeginInfo.framebuffer = fboDesc.mFramebuffers[fboIdx]; - passBeginInfo.renderArea.offset.x = 0; - passBeginInfo.renderArea.offset.y = 0; - passBeginInfo.renderArea.extent.width = mTargetWidth; - passBeginInfo.renderArea.extent.height = mTargetHeight; - passBeginInfo.clearValueCount = sizeof( mClearValues ) / sizeof( mClearValues[0] ); - passBeginInfo.pClearValues = mClearValues; - - vkCmdBeginRenderPass( cmdBuffer, &passBeginInfo, VK_SUBPASS_CONTENTS_INLINE ); - } - //----------------------------------------------------------------------------------- - void VulkanRenderPassDescriptor::performStoreActions() - { - if( mQueue->getEncoderState() != VulkanQueue::EncoderGraphicsOpen ) - return; - - vkCmdEndRenderPass( mQueue->mCurrentCmdBuffer ); - - // End (if exists) the render command encoder tied to this RenderPassDesc. - // Another encoder will have to be created, and don't let ours linger - // since mCurrentRenderPassDescriptor probably doesn't even point to 'this' - mQueue->endAllEncoders( false ); - } - //----------------------------------------------------------------------------------- - //----------------------------------------------------------------------------------- - //----------------------------------------------------------------------------------- - VulkanFrameBufferDescValue::VulkanFrameBufferDescValue() : - refCount( 0u ), - mNumImageViews( 0u ), - mRenderPass( 0 ) - { - memset( mImageViews, 0, sizeof( mImageViews ) ); - } -} // namespace Ogre diff --git a/RenderSystems/Vulkan/src/OgreVulkanRenderSystem.cpp b/RenderSystems/Vulkan/src/OgreVulkanRenderSystem.cpp deleted file mode 100644 index 70fedbbcfc1..00000000000 --- a/RenderSystems/Vulkan/src/OgreVulkanRenderSystem.cpp +++ /dev/null @@ -1,1382 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-present Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreVulkanRenderSystem.h" - -#include - -#include "OgreGpuProgramManager.h" -#include "OgreViewport.h" - -#include "OgreVulkanRenderPassDescriptor.h" -#include "OgreVulkanDevice.h" -#include "OgreVulkanMappings.h" -#include "OgreVulkanProgram.h" -#include "OgreVulkanRenderPassDescriptor.h" -#include "OgreVulkanTextureGpuManager.h" -#include "OgreVulkanUtils.h" -#include "OgreVulkanWindow.h" -#include "OgreVulkanHardwareBuffer.h" -#include "OgreVulkanHardwareBufferManager.h" -#include "OgreVulkanTextureGpu.h" -#include "OgreVulkanDescriptorPool.h" - -#include "OgreDepthBuffer.h" -#include "OgreRoot.h" - -#include "OgreVulkanWindow.h" -#include "OgrePixelFormat.h" - -#define USE_VALIDATION_LAYERS 0 - -namespace Ogre -{ - static const uint32 VERTEX_ATTRIBUTE_INDEX[VES_COUNT] = - { - 0, // VES_POSITION - 1 - 1, // VES_BLEND_WEIGHTS - 1 - 7, // VES_BLEND_INDICES - 1 - 2, // VES_NORMAL - 1 - 3, // VES_DIFFUSE - 1 - 4, // VES_SPECULAR - 1 - 8, // VES_TEXTURE_COORDINATES - 1 - //There are up to 8 VES_TEXTURE_COORDINATES. Occupy range [8; 16) - //Range [14; 16) overlaps with VES_TANGENT & VES_BINORMAL - //(slot 16 is where const buffers start) - 15,// VES_BINORMAL - 1 - 14, // VES_TANGENT - 1 - }; - - static VKAPI_ATTR VkBool32 dbgFunc( VkFlags msgFlags, VkDebugReportObjectTypeEXT objType, - uint64_t srcObject, size_t location, int32_t msgCode, - const char *pLayerPrefix, const char *pMsg, void *pUserData ) - { - const char* messageType = "INFORMATION"; - - if (msgFlags & VK_DEBUG_REPORT_WARNING_BIT_EXT) - messageType = "WARNING"; - else if (msgFlags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) - messageType = "PERFORMANCE WARNING"; - else if (msgFlags & VK_DEBUG_REPORT_ERROR_BIT_EXT) - messageType = "ERROR"; - else if (msgFlags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) - messageType = "DEBUG"; - - LogManager::getSingleton().logMessage( - StringUtil::format("%s: [%s] Code %d : %s", messageType, pLayerPrefix, msgCode, pMsg)); - - /* - * false indicates that layer should not bail-out of an - * API call that had validation failures. This may mean that the - * app dies inside the driver due to invalid parameter(s). - * That's what would happen without validation layers, so we'll - * keep that behavior here. - */ - return false; - } - - //------------------------------------------------------------------------- - VulkanRenderSystem::VulkanRenderSystem() : - RenderSystem(), - mInitialized( false ), - mHardwareBufferManager( 0 ), - mIndirectBuffer( 0 ), - mSPIRVProgramFactory( 0 ), - mVkInstance( 0 ), - mActiveDevice( 0 ), - mDevice( 0 ), - mCurrentRenderPassDescriptor( 0 ), - mHasValidationLayers( false ), - CreateDebugReportCallback( 0 ), - DestroyDebugReportCallback( 0 ), - mDebugReportCallback( 0 ), - pipelineCi{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO}, - pipelineLayoutCi{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}, - vertexFormatCi{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}, - inputAssemblyCi{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}, - mssCi{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}, - rasterState{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}, - blendStateCi{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}, - mUBOInfo{}, - mUBODynOffsets{}, - mImageInfos{}, - depthStencilStateCi{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO}, - mVkViewport{}, - mScissorRect{}, - viewportStateCi{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO} - { - mAutoParamsBufferPos = 0; - - pipelineCi.pVertexInputState = &vertexFormatCi; - pipelineCi.pInputAssemblyState = &inputAssemblyCi; - pipelineCi.pRasterizationState = &rasterState; - pipelineCi.pMultisampleState = &mssCi; - pipelineCi.pDepthStencilState = &depthStencilStateCi; - pipelineCi.pColorBlendState = &blendStateCi; - pipelineCi.pViewportState = &viewportStateCi; - pipelineCi.pStages = shaderStages.data(); - pipelineCi.stageCount = 2; // vertex+fragment - - inputAssemblyCi.primitiveRestartEnable = false; - - mssCi.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; - - rasterState.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; - rasterState.lineWidth = 1.0f; - - blendStateCi.attachmentCount = 1; - blendStateCi.pAttachments = blendStates.data(); - - depthStencilStateCi.minDepthBounds = 0.0f; - depthStencilStateCi.maxDepthBounds = 1.0f; - mVkViewport.minDepth = 0.0f; - mVkViewport.maxDepth = 1.0f; - - viewportStateCi.pViewports = &mVkViewport; - viewportStateCi.viewportCount = 1u; - viewportStateCi.scissorCount = 1u; - - // use a single descriptor set for all shaders - mDescriptorSetBindings.push_back({0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1, VK_SHADER_STAGE_ALL_GRAPHICS}); - mDescriptorSetBindings.push_back({1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1, VK_SHADER_STAGE_ALL_GRAPHICS}); - for(uint32 i = 0; i < OGRE_MAX_TEXTURE_COORD_SETS; ++i) - mDescriptorSetBindings.push_back({2 + i, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_ALL_GRAPHICS}); - - // one descriptor will have at most OGRE_MAX_TEXTURE_LAYERS and one UBO per shader type (for now) - mDescriptorPoolSizes.push_back({VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, GPT_COUNT}); - mDescriptorPoolSizes.push_back({VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, OGRE_MAX_TEXTURE_COORD_SETS}); - - // silence validation layer, when unused - mUBOInfo[0].range = 1; - mUBOInfo[1].range = 1; - - mDescriptorWrites.resize(OGRE_MAX_TEXTURE_COORD_SETS + 2, {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET}); - mDescriptorWrites[0].dstBinding = 0; - mDescriptorWrites[0].descriptorCount = 1; - mDescriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; - mDescriptorWrites[0].pBufferInfo = mUBOInfo.data(); - - mDescriptorWrites[1].dstBinding = 1; - mDescriptorWrites[1].descriptorCount = 1; - mDescriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC; - mDescriptorWrites[1].pBufferInfo = mUBOInfo.data() + 1; - - for(int i = 0; i < OGRE_MAX_TEXTURE_COORD_SETS; i++) - { - mDescriptorWrites[i + 2].dstBinding = 2 + i; - mDescriptorWrites[i + 2].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; - mDescriptorWrites[i + 2].pImageInfo = mImageInfos.data() + i; - mDescriptorWrites[i + 2].descriptorCount = 1; - } - - if(volkInitialize() != VK_SUCCESS) - { - LogManager::getSingleton().logWarning("Vulkan unavailable - loader not found"); - return; - } - - try { - initializeVkInstance(); - } catch(const std::exception& e) { - LogManager::getSingleton().logWarning(e.what()); - return; - } - enumerateDevices(); - initConfigOptions(); - } - void VulkanRenderSystem::enumerateDevices() - { - mDevices.clear(); - - VkInstance instance = getVkInstance(); - - uint32 numDevices = 0u; - OGRE_VK_CHECK(vkEnumeratePhysicalDevices(instance, &numDevices, NULL)); - - if( numDevices == 0u ) - { - LogManager::getSingleton().logError( "[Vulkan] No Vulkan devices found." ); - return; - } - - FastArray pd(numDevices); - OGRE_VK_CHECK(vkEnumeratePhysicalDevices(instance, &numDevices, pd.data())); - - LogManager::getSingleton().logMessage( "[Vulkan] Found devices:" ); - - mDevices.reserve( numDevices ); - for( uint32 i = 0u; i < numDevices; ++i ) - { - VkPhysicalDeviceProperties deviceProps; - vkGetPhysicalDeviceProperties( pd[i], &deviceProps ); - - mDevices.push_back( deviceProps.deviceName ); - - LogManager::getSingleton().stream() << " #" << i << " " << deviceProps.deviceName; - } - } - uint32 VulkanRenderSystem::getSelectedDeviceIdx() const - { - uint32 deviceIdx = 0u; - auto itDevice = std::find(mDevices.begin(), mDevices.end(), mOptions.at("Device").currentValue); - if( itDevice != mDevices.end() ) - deviceIdx = itDevice - mDevices.begin(); - - return deviceIdx; - } - //------------------------------------------------------------------------- - VulkanRenderSystem::~VulkanRenderSystem() - { - shutdown(); - - if( mDebugReportCallback ) - { - DestroyDebugReportCallback( mVkInstance, mDebugReportCallback, 0 ); - mDebugReportCallback = 0; - } - - if( mVkInstance ) - { - vkDestroyInstance( mVkInstance, 0 ); - mVkInstance = 0; - } - } - //------------------------------------------------------------------------- - void VulkanRenderSystem::shutdown( void ) - { - if( !mDevice ) - return; - - mDevice->stall(); -#if 0 - { - // Remove all windows. - // (destroy primary window last since others may depend on it) - RenderWindow *primary = 0; - WindowSet::const_iterator itor = mWindows.begin(); - WindowSet::const_iterator endt = mWindows.end(); - - while( itor != endt ) - { - if( !primary && ( *itor )->isPrimary() ) - primary = *itor; - else - OGRE_DELETE *itor; - - ++itor; - } - - OGRE_DELETE primary; - mWindows.clear(); - } -#endif - _cleanupDepthBuffers(); - - mAutoParamsBuffer.reset(); - - OGRE_DELETE mHardwareBufferManager; - mHardwareBufferManager = 0; - - OGRE_DELETE mTextureManager; - mTextureManager = 0; - - OGRE_DELETE mSPIRVProgramFactory; - mSPIRVProgramFactory = 0; - - vkDestroyPipelineLayout(mDevice->mDevice, mLayout, 0); - vkDestroyDescriptorSetLayout(mDevice->mDevice, mDescriptorSetLayout, 0); - - for(auto it : mRenderPassCache) - { - vkDestroyRenderPass(mDevice->mDevice, it.second, 0); - } - - mDescriptorPool.reset(); - - clearPipelineCache(); - - delete mDevice; - mDevice = 0; - } - void VulkanRenderSystem::clearPipelineCache() - { - for(auto it : mPipelineCache) - { - vkDestroyPipeline(mDevice->mDevice, it.second, 0); - } - - mPipelineCache.clear(); - } - //------------------------------------------------------------------------- - const String &VulkanRenderSystem::getName( void ) const - { - static String strName( "Vulkan Rendering Subsystem" ); - return strName; - } - void VulkanRenderSystem::initConfigOptions( void ) - { - RenderSystem::initConfigOptions(); - - ConfigOption optFSAA; - optFSAA.name = "FSAA"; - optFSAA.immutable = false; - optFSAA.possibleValues.push_back( "1" ); - optFSAA.possibleValues.push_back( "2" ); - optFSAA.possibleValues.push_back( "4" ); - optFSAA.possibleValues.push_back( "8" ); - optFSAA.possibleValues.push_back( "16" ); - optFSAA.currentValue = optFSAA.possibleValues.front(); - - ConfigOption optDevices; - optDevices.name = "Device"; - - for(const auto& d : mDevices) - optDevices.possibleValues.push_back( d); - - optDevices.currentValue = mDevices.front(); - optDevices.immutable = false; - - mOptions[optDevices.name] = optDevices; - mOptions[optFSAA.name] = optFSAA; - - ConfigOption opt; - opt.name = "Reversed Z-Buffer"; - opt.possibleValues = {"No", "Yes"}; - opt.currentValue = opt.possibleValues[0]; - opt.immutable = false; - - mOptions[opt.name] = opt; - } - //------------------------------------------------------------------------- - void VulkanRenderSystem::setConfigOption( const String &name, const String &value ) - { - ConfigOptionMap::iterator it = mOptions.find( name ); - - if( it == mOptions.end() ) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Option named " + name + " does not exist.", - "VulkanSupport::setConfigOption" ); - } - - it->second.currentValue = value; - - if(name == "Reversed Z-Buffer") - mIsReverseDepthBufferEnabled = StringConverter::parseBool(value); - } - //------------------------------------------------------------------------- - void VulkanRenderSystem::addInstanceDebugCallback( void ) - { - CreateDebugReportCallback = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr( - mVkInstance, "vkCreateDebugReportCallbackEXT" ); - DestroyDebugReportCallback = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr( - mVkInstance, "vkDestroyDebugReportCallbackEXT" ); - if( !CreateDebugReportCallback ) - { - LogManager::getSingleton().logMessage( - "[Vulkan] GetProcAddr: Unable to find vkCreateDebugReportCallbackEXT. " - "Debug reporting won't be available" ); - return; - } - if( !DestroyDebugReportCallback ) - { - LogManager::getSingleton().logMessage( - "[Vulkan] GetProcAddr: Unable to find vkDestroyDebugReportCallbackEXT. " - "Debug reporting won't be available" ); - return; - } - // DebugReportMessage = - // (PFN_vkDebugReportMessageEXT)vkGetInstanceProcAddr( mVkInstance, "vkDebugReportMessageEXT" - // ); - // if( !DebugReportMessage ) - //{ - // LogManager::getSingleton().logMessage( - // "[Vulkan] GetProcAddr: Unable to find DebugReportMessage. " - // "Debug reporting won't be available" ); - //} - - VkDebugReportCallbackCreateInfoEXT dbgCreateInfo = {VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT}; - PFN_vkDebugReportCallbackEXT callback; - callback = dbgFunc; - dbgCreateInfo.pfnCallback = callback; - dbgCreateInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | - VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT; - OGRE_VK_CHECK( - CreateDebugReportCallback( mVkInstance, &dbgCreateInfo, 0, &mDebugReportCallback )); - } - //------------------------------------------------------------------------- - HardwareOcclusionQuery *VulkanRenderSystem::createHardwareOcclusionQuery( void ) - { - return 0; // TODO - } - //------------------------------------------------------------------------- - RenderSystemCapabilities *VulkanRenderSystem::createRenderSystemCapabilities( void ) const - { - RenderSystemCapabilities *rsc = new RenderSystemCapabilities(); - rsc->setRenderSystemName( getName() ); - - // We would like to save the device properties for the device capabilities limits. - // These limits are needed for buffers' binding alignments. - VkPhysicalDeviceProperties *vkProperties = - const_cast( &mActiveDevice->mDeviceProperties ); - vkGetPhysicalDeviceProperties( mActiveDevice->mPhysicalDevice, vkProperties ); - - VkPhysicalDeviceProperties &properties = mActiveDevice->mDeviceProperties; - - LogManager::getSingleton().logMessage( - StringUtil::format("[Vulkan] API Version: %d.%d.%d", VK_VERSION_MAJOR(properties.apiVersion), - VK_VERSION_MINOR(properties.apiVersion), VK_VERSION_PATCH(properties.apiVersion))); - LogManager::getSingleton().logMessage(StringUtil::format("[Vulkan] Vendor ID: %#x", properties.vendorID)); - LogManager::getSingleton().logMessage(StringUtil::format("[Vulkan] Device ID: %#x", properties.deviceID)); - - rsc->setDeviceName( properties.deviceName ); - - switch( properties.vendorID ) - { - case 0x10DE: - { - rsc->setVendor( GPU_NVIDIA ); - // 10 bits = major version (up to r1023) - // 8 bits = minor version (up to 255) - // 8 bits = secondary branch version/build version (up to 255) - // 6 bits = tertiary branch/build version (up to 63) - - DriverVersion driverVersion; - driverVersion.major = ( properties.driverVersion >> 22u ) & 0x3ff; - driverVersion.minor = ( properties.driverVersion >> 14u ) & 0x0ff; - driverVersion.release = ( properties.driverVersion >> 6u ) & 0x0ff; - driverVersion.build = ( properties.driverVersion ) & 0x003f; - rsc->setDriverVersion( driverVersion ); - } - break; - case 0x1002: - rsc->setVendor( GPU_AMD ); - break; - case 0x8086: - rsc->setVendor( GPU_INTEL ); - break; - case 0x13B5: - rsc->setVendor( GPU_ARM ); // Mali - break; - case 0x5143: - rsc->setVendor( GPU_QUALCOMM ); - break; - case 0x1010: - rsc->setVendor( GPU_IMAGINATION_TECHNOLOGIES ); // PowerVR - break; - } - - if( rsc->getVendor() != GPU_NVIDIA ) - { - // Generic version routine that matches SaschaWillems's VulkanCapsViewer - DriverVersion driverVersion; - driverVersion.major = ( properties.driverVersion >> 22u ) & 0x3ff; - driverVersion.minor = ( properties.driverVersion >> 12u ) & 0x3ff; - driverVersion.release = ( properties.driverVersion ) & 0xfff; - driverVersion.build = 0; - rsc->setDriverVersion( driverVersion ); - } - - //if( mActiveDevice->mDeviceFeatures.imageCubeArray ) - // rsc->setCapability( RSC_TEXTURE_CUBE_MAP_ARRAY ); - - if( mActiveDevice->mDeviceFeatures.depthClamp ) - rsc->setCapability( RSC_DEPTH_CLAMP ); - - { - VkFormatProperties props; - - vkGetPhysicalDeviceFormatProperties( mDevice->mPhysicalDevice, - VulkanMappings::get( PF_DXT1 ), &props ); - if( props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT ) - rsc->setCapability( RSC_TEXTURE_COMPRESSION_DXT ); - - vkGetPhysicalDeviceFormatProperties( mDevice->mPhysicalDevice, - VulkanMappings::get( PF_BC4_UNORM ), &props ); - if( props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT ) - rsc->setCapability( RSC_TEXTURE_COMPRESSION_BC4_BC5 ); - - vkGetPhysicalDeviceFormatProperties( mDevice->mPhysicalDevice, - VulkanMappings::get( PF_BC6H_UF16 ), &props ); - if( props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT ) - rsc->setCapability( RSC_TEXTURE_COMPRESSION_BC6H_BC7 ); - - // Vulkan doesn't allow supporting ETC1 without ETC2 - vkGetPhysicalDeviceFormatProperties( mDevice->mPhysicalDevice, - VulkanMappings::get( PF_ETC2_RGB8 ), &props ); - if( props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT ) - { - rsc->setCapability( RSC_TEXTURE_COMPRESSION_ETC1 ); - rsc->setCapability( RSC_TEXTURE_COMPRESSION_ETC2 ); - } - - vkGetPhysicalDeviceFormatProperties( - mDevice->mPhysicalDevice, VulkanMappings::get( PF_ASTC_RGBA_4X4_LDR ), &props ); - if( props.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT ) - rsc->setCapability( RSC_TEXTURE_COMPRESSION_ASTC ); - } - - const VkPhysicalDeviceLimits &deviceLimits = mDevice->mDeviceProperties.limits; - //rsc->setMaximumResolutions( deviceLimits.maxImageDimension2D, deviceLimits.maxImageDimension3D, - // deviceLimits.maxImageDimensionCube ); - //rsc->setMaxThreadsPerThreadgroupAxis( deviceLimits.maxComputeWorkGroupSize ); - //rsc->setMaxThreadsPerThreadgroup( deviceLimits.maxComputeWorkGroupInvocations ); - - if( mActiveDevice->mDeviceFeatures.samplerAnisotropy && deviceLimits.maxSamplerAnisotropy > 1u ) - { - rsc->setCapability( RSC_ANISOTROPY ); - rsc->setMaxSupportedAnisotropy( deviceLimits.maxSamplerAnisotropy ); - } - - //rsc->setCapability( RSC_STORE_AND_MULTISAMPLE_RESOLVE ); - //rsc->setCapability( RSC_TEXTURE_GATHER ); - - rsc->setCapability( RSC_COMPUTE_PROGRAM ); - //rsc->setCapability( RSC_UAV ); - //rsc->setCapability( RSC_TYPED_UAV_LOADS ); - //rsc->setCapability( RSC_EXPLICIT_FSAA_RESOLVE ); - rsc->setCapability( RSC_TEXTURE_1D ); - - //rsc->setCapability( RSC_HWSTENCIL ); - rsc->setNumTextureUnits( OGRE_MAX_TEXTURE_COORD_SETS ); - rsc->setCapability( RSC_TEXTURE_COMPRESSION ); - rsc->setCapability( RSC_32BIT_INDEX ); - rsc->setCapability( RSC_TWO_SIDED_STENCIL ); - rsc->setCapability( RSC_STENCIL_WRAP ); - if( mActiveDevice->mDeviceFeatures.shaderClipDistance ) - rsc->setCapability( RSC_USER_CLIP_PLANES ); - rsc->setCapability( RSC_TEXTURE_3D ); - rsc->setCapability( RSC_NON_POWER_OF_2_TEXTURES ); - rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH); - rsc->setNonPOW2TexturesLimited( false ); - rsc->setCapability( RSC_HWRENDER_TO_TEXTURE ); - rsc->setCapability( RSC_TEXTURE_FLOAT ); - if( mActiveDevice->mDeviceFeatures.largePoints ) - { - rsc->setCapability( RSC_POINT_SPRITES ); - } - rsc->setCapability( RSC_TEXTURE_2D_ARRAY ); - rsc->setCapability( RSC_ALPHA_TO_COVERAGE ); - rsc->setCapability( RSC_HW_GAMMA ); - rsc->setCapability( RSC_VERTEX_BUFFER_INSTANCE_DATA ); - rsc->setCapability(RSC_VERTEX_FORMAT_INT_10_10_10_2); - rsc->setMaxPointSize( deviceLimits.pointSizeRange[1] ); - - //rsc->setMaximumResolutions( 16384, 4096, 16384 ); - auto maxFloatVectors = deviceLimits.maxUniformBufferRange / (4 * sizeof(float)); - rsc->setVertexProgramConstantFloatCount(maxFloatVectors); - rsc->setGeometryProgramConstantFloatCount(maxFloatVectors); - rsc->setFragmentProgramConstantFloatCount(maxFloatVectors); - rsc->setTessellationHullProgramConstantFloatCount(maxFloatVectors); - rsc->setTessellationDomainProgramConstantFloatCount(maxFloatVectors); - rsc->setComputeProgramConstantFloatCount(maxFloatVectors); - - rsc->addShaderProfile( "spirv" ); - - if( rsc->getVendor() == GPU_QUALCOMM ) - { -#ifdef OGRE_VK_WORKAROUND_ADRENO_D32_FLOAT - Workarounds::mAdrenoD32FloatBug = false; - if( !rsc->getDriverVersion().hasMinVersion( 512, 415 ) ) - Workarounds::mAdrenoD32FloatBug = true; -#endif -#ifdef OGRE_VK_WORKAROUND_ADRENO_5XX_6XX_MINCAPS - Workarounds::mAdreno5xx6xxMinCaps = false; - - const uint32 c_adreno5xx6xxDeviceIds[] = { - 0x5000400, // 504 - 0x5000500, // 505 - 0x5000600, // 506 - 0x5000800, // 508 - 0x5000900, // 509 - 0x5010000, // 510 - 0x5010200, // 512 - 0x5030002, // 530 - 0x5040001, // 540 - - 0x6010000, // 610 - 0x6010200, // 612 - 0x6010501, // 615 - 0x6010600, // 616 - 0x6010800, // 618 - 0x6020001, // 620 - 0x6030001, // 630 - 0x6040001, // 640 - 0x6050002, // 650 - }; - - const size_t numDevIds = - sizeof( c_adreno5xx6xxDeviceIds ) / sizeof( c_adreno5xx6xxDeviceIds[0] ); - for( size_t i = 0u; i < numDevIds; ++i ) - { - if( properties.deviceID == c_adreno5xx6xxDeviceIds[i] ) - { - Workarounds::mAdreno5xx6xxMinCaps = true; - break; - } - } -#endif - } - - return rsc; - } - //------------------------------------------------------------------------- - void VulkanRenderSystem::resetAllBindings( void ) - { - - } - //------------------------------------------------------------------------- - void VulkanRenderSystem::initializeVkInstance( void ) - { - if( mVkInstance ) - return; - - LogManager::getSingleton().logMessage( "[Vulkan] Initializing VkInstance" ); - - uint32 numExtensions = 0u; - OGRE_VK_CHECK(vkEnumerateInstanceExtensionProperties(0, &numExtensions, 0)); - - std::vector availableExtensions(numExtensions); - OGRE_VK_CHECK(vkEnumerateInstanceExtensionProperties(0, &numExtensions, availableExtensions.data())); - - bool debugEnabled = USE_VALIDATION_LAYERS; - //StringConverter::parse(mOptions.at("Debug Layer").currentValue, debugEnabled); - - // Check supported extensions we may want - std::vector reqInstanceExtensions; - for( size_t i = 0u; i < numExtensions; ++i ) - { - const String extensionName = availableExtensions[i].extensionName; - LogManager::getSingleton().logMessage( "Found instance extension: " + extensionName ); - - if (extensionName == VulkanWindow::getRequiredExtensionName()) - { - reqInstanceExtensions.push_back(VulkanWindow::getRequiredExtensionName()); - } - - if (debugEnabled && extensionName == "VK_EXT_debug_report") - reqInstanceExtensions.push_back("VK_EXT_debug_report"); - } - - reqInstanceExtensions.push_back("VK_KHR_surface"); // required for window surface - - // Check supported layers we may want - uint32 numInstanceLayers = 0u; - OGRE_VK_CHECK(vkEnumerateInstanceLayerProperties(&numInstanceLayers, 0)); - - FastArray instanceLayerProps(numInstanceLayers); - OGRE_VK_CHECK(vkEnumerateInstanceLayerProperties(&numInstanceLayers, instanceLayerProps.data())); - - FastArray instanceLayers; - for( size_t i = 0u; i < numInstanceLayers; ++i ) - { - const String layerName = instanceLayerProps[i].layerName; - LogManager::getSingleton().logMessage( "Found instance layer: " + layerName ); - if( debugEnabled && layerName == "VK_LAYER_KHRONOS_validation" ) - { - mHasValidationLayers = true; - instanceLayers.push_back( "VK_LAYER_KHRONOS_validation" ); - } - } - - if (debugEnabled && !mHasValidationLayers) - { - LogManager::getSingleton().logWarning( - "Debug Layer requested, but VK_LAYER_KHRONOS_validation layer not present"); - } - - mVkInstance = VulkanDevice::createInstance(reqInstanceExtensions, instanceLayers, dbgFunc); - volkLoadInstanceOnly(mVkInstance); - - if(mHasValidationLayers) - addInstanceDebugCallback(); - } - //------------------------------------------------------------------------- - RenderWindow *VulkanRenderSystem::_createRenderWindow( const String &name, uint32 width, uint32 height, - bool fullScreen, - const NameValuePairList *miscParams ) - { - RenderSystem::_createRenderWindow(name, width, height, fullScreen, miscParams); - - VulkanWindow *win = OGRE_NEW VulkanWindow( name, width, height, fullScreen ); - attachRenderTarget((Ogre::RenderTarget&) *win); - - if( !mInitialized ) - { - initializeVkInstance(); - - mDevice = new VulkanDevice( mVkInstance, getSelectedDeviceIdx(), this ); - mActiveDevice = mDevice; - - mRealCapabilities = createRenderSystemCapabilities(); - mCurrentCapabilities = mRealCapabilities; - - initialiseFromRenderSystemCapabilities( mCurrentCapabilities, 0 ); - - mNativeShadingLanguageVersion = 100; - - bool bCanRestrictImageViewUsage = false; - - FastArray deviceExtensions; - { - uint32 numExtensions = 0; - vkEnumerateDeviceExtensionProperties( mDevice->mPhysicalDevice, 0, &numExtensions, 0 ); - - std::vector availableExtensions(numExtensions); - vkEnumerateDeviceExtensionProperties( mDevice->mPhysicalDevice, 0, &numExtensions, - availableExtensions.data() ); - for( size_t i = 0u; i < numExtensions; ++i ) - { - const String extensionName = availableExtensions[i].extensionName; - LogManager::getSingleton().logMessage( "Found device extension: " + extensionName ); - - if( extensionName == VK_KHR_MAINTENANCE2_EXTENSION_NAME ) - { - deviceExtensions.push_back( VK_KHR_MAINTENANCE2_EXTENSION_NAME ); - bCanRestrictImageViewUsage = true; - } - else if( extensionName == VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME ) - deviceExtensions.push_back( VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME ); - } - } - - if( !bCanRestrictImageViewUsage ) - { - LogManager::getSingleton().logMessage( - "WARNING: " VK_KHR_MAINTENANCE2_EXTENSION_NAME - " not present. We may have to force the driver to do UAV + SRGB operations " - "the GPU should support, but it's not guaranteed to work" ); - } - - if( mHasValidationLayers ) - deviceExtensions.push_back( VK_EXT_DEBUG_MARKER_EXTENSION_NAME ); - - mDevice->createDevice( deviceExtensions, 0u, 0u ); - - mHardwareBufferManager = OGRE_NEW VulkanHardwareBufferManager( mDevice ); - - mActiveDevice->initQueues(); - //vaoManager->initDrawIdVertexBuffer(); - - mTextureManager = new VulkanTextureGpuManager(this, mDevice, bCanRestrictImageViewUsage); - mTextureManager->_getWarningTexture(); // preload warning texture, so does not interrupt render pass - - VkDescriptorSetLayoutCreateInfo descriptorSetLayoutCi = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; - descriptorSetLayoutCi.bindingCount = mDescriptorSetBindings.size(); - descriptorSetLayoutCi.pBindings = mDescriptorSetBindings.data(); - OGRE_VK_CHECK(vkCreateDescriptorSetLayout(mActiveDevice->mDevice, &descriptorSetLayoutCi, nullptr, - &mDescriptorSetLayout)); - - pipelineLayoutCi.pSetLayouts = &mDescriptorSetLayout; - pipelineLayoutCi.setLayoutCount = 1; - OGRE_VK_CHECK(vkCreatePipelineLayout(mActiveDevice->mDevice, &pipelineLayoutCi, 0, &mLayout)); - - // allocate 1.5MB buffer. Holds e.g. 1024 batches of 512 bytes for 3 frames-in-flight - resizeAutoParamsBuffer(1024 * 512 * 3); - mAutoParamsBufferUsage.resize(mActiveDevice->mGraphicsQueue.mNumFramesInFlight); - - resetAllBindings(); - - String workaroundsStr; - //Workarounds::dump( (void *)&workaroundsStr ); - if( !workaroundsStr.empty() ) - { - workaroundsStr = "Workarounds applied:" + workaroundsStr; - LogManager::getSingleton().logMessage( workaroundsStr ); - } - - mInitialized = true; - } - - win->_setDevice( mActiveDevice ); - win->create( name, width, height, fullScreen, miscParams ); - - return win; - } - - void VulkanRenderSystem::resizeAutoParamsBuffer(size_t size) - { - size = alignToNextMultiple(size, mDevice->mDeviceProperties.limits.minUniformBufferOffsetAlignment); - mAutoParamsBuffer = mHardwareBufferManager->createUniformBuffer(size); - mAutoParamsBufferPos = 0; - - mUBOInfo[0].buffer = static_cast(mAutoParamsBuffer.get())->getVkBuffer(); - mUBOInfo[1].buffer = mUBOInfo[0].buffer; - - // descriptors referring to old buffer are invalidated - mDescriptorSetCache.clear(); - mActiveDevice->mGraphicsQueue.queueForDeletion(mDescriptorPool); - mDescriptorPool.reset( new VulkanDescriptorPool(mDescriptorPoolSizes, mDescriptorSetLayout, mDevice)); - } - - //------------------------------------------------------------------------- - void VulkanRenderSystem::_notifyDeviceStalled() - { - VulkanHardwareBufferManager *hwBufferMgr = - static_cast( mHardwareBufferManager ); - - hwBufferMgr->_notifyDeviceStalled(); - } - //------------------------------------------------------------------------- - void VulkanRenderSystem::_setTexture( size_t unit, bool enabled, const TexturePtr& texPtr ) - { - if( texPtr && enabled) - { - VulkanTextureGpu *tex = static_cast( texPtr.get() ); - mImageInfos[unit].imageView = tex->getDefaultDisplaySrv(); - mImageInfos[unit].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - } - else - { - mImageInfos[unit].imageView = NULL; - } - } - //------------------------------------------------------------------------- - void VulkanRenderSystem::_beginFrame( void ) {} - //------------------------------------------------------------------------- - void VulkanRenderSystem::_notifyActiveEncoderEnded() - { - } - //------------------------------------------------------------------------- - void VulkanRenderSystem::_notifyActiveComputeEnded( void ) - { - - } - //------------------------------------------------------------------------- - void VulkanRenderSystem::_endFrame( void ) - { - endRenderPassDescriptor(); - //mActiveDevice->commitAndNextCommandBuffer( SubmissionType::EndFrameAndSwap ); - } - //------------------------------------------------------------------------- - void VulkanRenderSystem::flushRootLayout( void ) - { - //VulkanRootLayout *rootLayout = reinterpret_cast( mPso->rsData )->rootLayout; - //rootLayout->bind( mDevice, vaoManager, mGlobalTable ); - } - - VkDescriptorSet VulkanRenderSystem::getDescriptorSet() - { - uint32 hash = HashCombine(0, mUBOInfo); - - int numTextures = 0; - for (; numTextures < OGRE_MAX_TEXTURE_COORD_SETS; numTextures++) - { - if (!mImageInfos[numTextures].imageView) - break; - hash = HashCombine(hash, mImageInfos[numTextures]); - } - - VkDescriptorSet retVal = mDescriptorSetCache[hash]; - - if(retVal != VK_NULL_HANDLE) - return retVal; - - retVal = mDescriptorPool->allocate(); - - mDescriptorWrites[0].dstSet = retVal; - mDescriptorWrites[1].dstSet = retVal; - for(int i = 0; i < numTextures; i++) - { - mDescriptorWrites[i + 2].dstSet = retVal; - } - - int bindCount = numTextures + 2; - vkUpdateDescriptorSets(mActiveDevice->mDevice, bindCount, mDescriptorWrites.data(), 0, nullptr); - - mDescriptorSetCache[hash] = retVal; - - return retVal; - } - - VkPipeline VulkanRenderSystem::getPipeline() - { - pipelineCi.renderPass = mCurrentRenderPassDescriptor->getRenderPass(); - pipelineCi.layout = mLayout; - mssCi.rasterizationSamples = VkSampleCountFlagBits(std::max(mActiveRenderTarget->getFSAA(), 1u)); - - auto hash = HashCombine(0, pipelineCi.renderPass); - hash = HashCombine(hash, blendStates[0]); - hash = HashCombine(hash, rasterState); - hash = HashCombine(hash, inputAssemblyCi); - hash = HashCombine(hash, mssCi); - - for(uint32 i = 0; i mDevice, 0, 1, &pipelineCi, 0, &retVal)); - - mPipelineCache[hash] = retVal; - - return retVal; - } - - void VulkanRenderSystem::_render( const RenderOperation &op ) - { - if ((op.useIndexes && op.indexData->indexCount == 0) || op.vertexData->vertexCount == 0) - return; - - // Call super class. - RenderSystem::_render( op ); - - if(mActiveDevice->mGraphicsQueue.getEncoderState() != VulkanQueue::EncoderGraphicsOpen) - { - // ensure scissor is set - vkCmdSetScissor(mActiveDevice->mGraphicsQueue.mCurrentCmdBuffer, 0u, 1, &mScissorRect); - mAutoParamsBufferUsage[mActiveDevice->mGraphicsQueue.mCurrentFrameIdx] = 0; - executeRenderPassDescriptorDelayedActions(); - } - - std::vector vertexInputs; - uint32 uvCount = 0; - for (auto elem : op.vertexData->vertexDeclaration->getElements()) - { - VkVertexInputAttributeDescription inputDesc; - inputDesc.location = VERTEX_ATTRIBUTE_INDEX[elem.getSemantic() - 1]; - if (elem.getSemantic() == VES_TEXTURE_COORDINATES) - inputDesc.location += uvCount++; - - inputDesc.format = VulkanMappings::get( elem.getType() ); - inputDesc.binding = elem.getSource(); - inputDesc.offset = elem.getOffset(); - if (!op.vertexData->vertexBufferBinding->isBufferBound(inputDesc.binding)) - continue; // skip unbound elements - vertexInputs.push_back(inputDesc); - } - - OgreAssert(!op.vertexData->vertexBufferBinding->hasGaps(), "no gaps allowed"); - - std::vector vertexBuffers; - std::vector bufferBindings; - for(const auto& it : op.vertexData->vertexBufferBinding->getBindings()) - { - auto inputRate = it.second->isInstanceData() ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX; - bufferBindings.push_back({it.first, uint32(it.second->getVertexSize()), inputRate}); - auto b = it.second->_getImpl()->getVkBuffer(); - vertexBuffers.push_back(b); - } - - VkDeviceSize offsets[15] = {}; - - vertexFormatCi.pVertexAttributeDescriptions = vertexInputs.data(); - vertexFormatCi.vertexAttributeDescriptionCount = vertexInputs.size(); - vertexFormatCi.pVertexBindingDescriptions = bufferBindings.data(); - vertexFormatCi.vertexBindingDescriptionCount = bufferBindings.size(); - - inputAssemblyCi.topology = VulkanMappings::get( op.operationType ); - - VkCommandBuffer cmdBuffer = mActiveDevice->mGraphicsQueue.mCurrentCmdBuffer; - - if(!vertexBuffers.empty()) - vkCmdBindVertexBuffers(cmdBuffer, 0, vertexBuffers.size(), vertexBuffers.data(), offsets); - - if(op.indexData) - { - auto itype = VkIndexType(op.indexData->indexBuffer->getType()); - auto b = op.indexData->indexBuffer->_getImpl()->getVkBuffer(); - vkCmdBindIndexBuffer(cmdBuffer, b, 0, itype); - } - - auto pipeline = getPipeline(); - auto descriptorSet = getDescriptorSet(); - vkCmdBindDescriptorSets(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineCi.layout, 0, 1, &descriptorSet, 2, - mUBODynOffsets.data()); - - vkCmdBindPipeline( cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline ); - - // Render to screen! - if( op.useIndexes ) - { - do - { - // Update derived depth bias. - if( mDerivedDepthBias && mCurrentPassIterationNum > 0 ) - { - const float biasSign = mIsReverseDepthBufferEnabled ? 1.0f : -1.0f; - vkCmdSetDepthBias( cmdBuffer, - ( mDerivedDepthBiasBase + - mDerivedDepthBiasMultiplier * mCurrentPassIterationNum ) * - biasSign, - 0.f, mDerivedDepthBiasSlopeScale * biasSign ); - } - - vkCmdDrawIndexed(cmdBuffer, (uint32)op.indexData->indexCount, op.numberOfInstances, - (uint32)op.indexData->indexStart, (int32)op.vertexData->vertexStart, 0u); - } while( updatePassIterationRenderState() ); - } - else - { - do - { - // Update derived depth bias. - if( mDerivedDepthBias && mCurrentPassIterationNum > 0 ) - { - const float biasSign = mIsReverseDepthBufferEnabled ? 1.0f : -1.0f; - vkCmdSetDepthBias( cmdBuffer, - ( mDerivedDepthBiasBase + - mDerivedDepthBiasMultiplier * mCurrentPassIterationNum ) * - biasSign, - 0.0f, mDerivedDepthBiasSlopeScale * biasSign ); - } - const uint32 vertexStart = static_cast( op.vertexData->vertexStart ); - vkCmdDraw(cmdBuffer, (uint32)op.vertexData->vertexCount, op.numberOfInstances, vertexStart, 0u); - } while( updatePassIterationRenderState() ); - } - } - //------------------------------------------------------------------------- - void VulkanRenderSystem::bindGpuProgram(GpuProgram* prg) - { - auto shader = static_cast(prg); - shaderStages[prg->getType()] = shader->getPipelineShaderStageCi(); - mBoundGpuPrograms[prg->getType()] = prg->_getHash(); - } - void VulkanRenderSystem::bindGpuProgramParameters( GpuProgramType gptype, - const GpuProgramParametersPtr& params, - uint16 variabilityMask ) - { - mActiveParameters[gptype] = params; - - auto sizeBytes = params->getConstantList().size(); - if(sizeBytes && gptype <= GPT_FRAGMENT_PROGRAM) - { - auto step = - alignToNextMultiple(sizeBytes, mDevice->mDeviceProperties.limits.minUniformBufferOffsetAlignment); - mUBOInfo[gptype].range = sizeBytes; - - if (std::accumulate(mAutoParamsBufferUsage.begin(), mAutoParamsBufferUsage.end(), 0) + step >= - mAutoParamsBuffer->getSizeInBytes()) - { - // ran out of UBO memory, allocate a bigger buffer - resizeAutoParamsBuffer(mAutoParamsBuffer->getSizeInBytes() * 2); - } - - if((mAutoParamsBufferPos + sizeBytes) >= mAutoParamsBuffer->getSizeInBytes()) - mAutoParamsBufferPos = 0; - - mUBODynOffsets[gptype] = mAutoParamsBufferPos; - - mAutoParamsBuffer->writeData(mAutoParamsBufferPos, sizeBytes, params->getConstantList().data()); - mAutoParamsBufferPos += step; - mAutoParamsBufferUsage[mActiveDevice->mGraphicsQueue.mCurrentFrameIdx] += step; - - if(mAutoParamsBufferPos >= mAutoParamsBuffer->getSizeInBytes()) - mAutoParamsBufferPos = 0; - } - } - //------------------------------------------------------------------------- - Real VulkanRenderSystem::getHorizontalTexelOffset( void ) { return 0.0f; } - //------------------------------------------------------------------------- - Real VulkanRenderSystem::getVerticalTexelOffset( void ) { return 0.0f; } - //------------------------------------------------------------------------- - Real VulkanRenderSystem::getMinimumDepthInputValue( void ) { return 0.0f; } - //------------------------------------------------------------------------- - Real VulkanRenderSystem::getMaximumDepthInputValue( void ) { return 1.0f; } - //------------------------------------------------------------------------- - void VulkanRenderSystem::beginProfileEvent(const String& eventName) - { - if(vkCmdDebugMarkerBeginEXT) - { - VkDebugMarkerMarkerInfoEXT markerInfo = {VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT}; - markerInfo.pMarkerName = eventName.c_str(); - vkCmdDebugMarkerBeginEXT(mActiveDevice->mGraphicsQueue.mCurrentCmdBuffer, &markerInfo); - } - } - //------------------------------------------------------------------------- - void VulkanRenderSystem::endProfileEvent(void) { - if(vkCmdDebugMarkerEndEXT) - { - vkCmdDebugMarkerEndEXT(mActiveDevice->mGraphicsQueue.mCurrentCmdBuffer); - } - } - //------------------------------------------------------------------------- - void VulkanRenderSystem::markProfileEvent(const String& event) {} - //------------------------------------------------------------------------- - void VulkanRenderSystem::initGPUProfiling( void ) {} - //------------------------------------------------------------------------- - void VulkanRenderSystem::deinitGPUProfiling( void ) {} - //------------------------------------------------------------------------- - void VulkanRenderSystem::beginGPUSampleProfile( const String &name, uint32 *hashCache ) {} - //------------------------------------------------------------------------- - void VulkanRenderSystem::endGPUSampleProfile( const String &name ) {} - //------------------------------------------------------------------------- - void VulkanRenderSystem::initialiseFromRenderSystemCapabilities( RenderSystemCapabilities *caps, - RenderTarget *primary ) - { - mSPIRVProgramFactory = OGRE_NEW VulkanProgramFactory( mActiveDevice ); - GpuProgramManager::getSingleton().addFactory( mSPIRVProgramFactory ); - } - //------------------------------------------------------------------------- - void VulkanRenderSystem::executeRenderPassDescriptorDelayedActions( bool officialCall ) - { - mActiveDevice->mGraphicsQueue.endAllEncoders( false ); - mCurrentRenderPassDescriptor->performLoadActions(); - mActiveDevice->mGraphicsQueue.getGraphicsEncoder(); - } - //------------------------------------------------------------------------- - void VulkanRenderSystem::endRenderPassDescriptor() - { - if( mCurrentRenderPassDescriptor ) - { - mCurrentRenderPassDescriptor->performStoreActions(); - } - } - //------------------------------------------------------------------------- - - DepthBuffer *VulkanRenderSystem::_createDepthBufferFor( RenderTarget* ) - { - return NULL; - } - - //------------------------------------------------------------------------- - void VulkanRenderSystem::notifySwapchainDestroyed() - { - clearPipelineCache(); - } - //------------------------------------------------------------------------- - void VulkanRenderSystem::setColourBlendState(const ColourBlendState& state) - { - blendStates[0].blendEnable = state.blendingEnabled(); - blendStates[0].srcColorBlendFactor = VulkanMappings::get(state.sourceFactor); - blendStates[0].dstColorBlendFactor = VulkanMappings::get(state.destFactor); - blendStates[0].colorBlendOp = VulkanMappings::get(state.operation); - blendStates[0].srcAlphaBlendFactor = VulkanMappings::get(state.sourceFactorAlpha); - blendStates[0].dstAlphaBlendFactor = VulkanMappings::get(state.destFactorAlpha); - blendStates[0].alphaBlendOp = VulkanMappings::get(state.alphaOperation); - blendStates[0].colorWriteMask = state.writeA << 3 | state.writeB << 2 | state.writeG << 1 | int(state.writeR); - - for( uint i = 1; i < blendStateCi.attachmentCount; ++i ) - blendStates[i] = blendStates[0]; - } - - void VulkanRenderSystem::_setSampler(size_t texUnit, Sampler& sampler) - { - mImageInfos[texUnit].sampler = static_cast(sampler).bind(); - } - - void VulkanRenderSystem::_setPolygonMode(PolygonMode level) - { - rasterState.polygonMode = VulkanMappings::get(level); - } - - void VulkanRenderSystem::_convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest, bool) - { - dest = matrix; - - if (auto win = dynamic_cast(mActiveRenderTarget)) - { - int transform = win->getSurfaceTransform(); - if (transform != VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) - { - auto angle = Degree(90) * (transform - 1); - dest = Matrix4(Quaternion(angle, Vector3::UNIT_Z)) * dest; - } - } - - if (mIsReverseDepthBufferEnabled) - { - // Convert depth range from [-1,+1] to [1,0] - dest[2][0] = (dest[2][0] - dest[3][0]) * -0.5f; - dest[2][1] = (dest[2][1] - dest[3][1]) * -0.5f; - dest[2][2] = (dest[2][2] - dest[3][2]) * -0.5f; - dest[2][3] = (dest[2][3] - dest[3][3]) * -0.5f; - } - else - { - // Convert depth range from [-1,+1] to [0,1] - dest[2][0] = (dest[2][0] + dest[3][0]) / 2; - dest[2][1] = (dest[2][1] + dest[3][1]) / 2; - dest[2][2] = (dest[2][2] + dest[3][2]) / 2; - dest[2][3] = (dest[2][3] + dest[3][3]) / 2; - } - } - - void VulkanRenderSystem::_setCullingMode(CullingMode mode) - { - rasterState.cullMode = VulkanMappings::get(mode); - // flipFrontFace result is inverted due to inverted clip space Y - rasterState.frontFace = !flipFrontFace() ? VK_FRONT_FACE_CLOCKWISE : VK_FRONT_FACE_COUNTER_CLOCKWISE; - } - - void VulkanRenderSystem::_setDepthBias(float constantBias, float slopeScaleBias) - { - rasterState.depthBiasEnable = (std::abs(constantBias) + std::abs(slopeScaleBias)) != 0.0f; - rasterState.depthBiasConstantFactor = -constantBias; - rasterState.depthBiasSlopeFactor = -slopeScaleBias; - - if(mIsReverseDepthBufferEnabled) - { - rasterState.depthBiasConstantFactor *= -1; - rasterState.depthBiasSlopeFactor *= -1; - } - } - - void VulkanRenderSystem::_setDepthClamp(bool enable) - { - rasterState.depthClampEnable = enable; - } - - void VulkanRenderSystem::_setAlphaRejectSettings(CompareFunction func, unsigned char value, bool alphaToCoverage) - { - mssCi.alphaToCoverageEnable = (func != CMPF_ALWAYS_PASS) && alphaToCoverage; - } - - void VulkanRenderSystem::_setDepthBufferParams(bool depthTest, bool depthWrite, CompareFunction func) - { - depthStencilStateCi.depthTestEnable = depthTest; - depthStencilStateCi.depthWriteEnable = depthWrite; - - if (isReverseDepthBufferEnabled()) - func = reverseCompareFunction(func); - - depthStencilStateCi.depthCompareOp = VulkanMappings::get(func); - } - - void VulkanRenderSystem::setScissorTest(bool enabled, const Rect& rect) - { - if (!enabled) - { - mScissorRect = {{int32(mVkViewport.x), int32(mVkViewport.y)}, - {uint32(mVkViewport.width), uint32(mVkViewport.height)}}; - } - else - { - mScissorRect = {{int32(rect.left), int32(rect.top)}, {uint32(rect.width()), uint32(rect.height())}}; - } - - vkCmdSetScissor(mActiveDevice->mGraphicsQueue.mCurrentCmdBuffer, 0u, 1, &mScissorRect); - } - - void VulkanRenderSystem::setStencilState(const StencilState& state) - { - depthStencilStateCi.stencilTestEnable = state.enabled; - depthStencilStateCi.front.failOp = VulkanMappings::get(state.stencilFailOp); - depthStencilStateCi.front.passOp = VulkanMappings::get(state.depthStencilPassOp); - depthStencilStateCi.front.depthFailOp = VulkanMappings::get(state.depthFailOp); - depthStencilStateCi.front.compareOp = VulkanMappings::get(state.compareOp); - depthStencilStateCi.front.compareMask = state.compareMask; - depthStencilStateCi.front.writeMask = state.writeMask; - depthStencilStateCi.front.reference = state.referenceValue; - - depthStencilStateCi.back.failOp = VulkanMappings::get(state.stencilFailOp); - depthStencilStateCi.back.passOp = VulkanMappings::get(state.depthStencilPassOp); - depthStencilStateCi.back.depthFailOp = VulkanMappings::get(state.depthFailOp); - depthStencilStateCi.back.compareOp = VulkanMappings::get(state.compareOp); - depthStencilStateCi.back.compareMask = state.compareMask; - depthStencilStateCi.back.writeMask = state.writeMask; - depthStencilStateCi.back.reference = state.referenceValue; - } - - void VulkanRenderSystem::_setViewport(Viewport *vp) - { - if (!vp) - { - mActiveViewport = NULL; - _setRenderTarget(NULL); - } - else if (vp != mActiveViewport || vp->_isUpdated()) - { - auto target = vp->getTarget(); - _setRenderTarget(target); - mActiveViewport = vp; - - // Calculate the "lower-left" corner of the viewport - Rect vpRect = vp->getActualDimensions(); - if (!target->requiresTextureFlipping()) - { - // Convert "upper-left" corner to "lower-left" - std::swap(vpRect.top, vpRect.bottom); - vpRect.top = target->getHeight() - vpRect.top; - vpRect.bottom = target->getHeight() - vpRect.bottom; - } - - if (auto win = dynamic_cast(mActiveRenderTarget)) - { - if (win->getSurfaceTransform() & - (VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR | VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR)) - { - std::swap(vpRect.bottom, vpRect.right); - std::swap(vpRect.top, vpRect.left); - } - } - - mVkViewport.x = vpRect.left; - mVkViewport.y = vpRect.top; - mVkViewport.width = vpRect.width(); - mVkViewport.height = vpRect.height(); - - setScissorTest(false); // reset scissor - - vp->_clearUpdatedFlag(); - } - } - void VulkanRenderSystem::_setRenderTarget(RenderTarget *target) - { - mActiveRenderTarget = target; - - if (!target) - return; - - if(auto win = dynamic_cast(target)) - { - mCurrentRenderPassDescriptor = win->getRenderPassDescriptor(); - } - if(auto rtt = dynamic_cast(target)) - { - mCurrentRenderPassDescriptor = rtt->getRenderPassDescriptor(); - } - } - void VulkanRenderSystem::clearFrameBuffer(unsigned int buffers, const ColourValue& colour, float depth, - unsigned short stencil) - { - mCurrentRenderPassDescriptor->setClearColour(colour); - mCurrentRenderPassDescriptor->setClearDepth(depth); - } -} // namespace Ogre diff --git a/RenderSystems/Vulkan/src/OgreVulkanTextureGpu.cpp b/RenderSystems/Vulkan/src/OgreVulkanTextureGpu.cpp deleted file mode 100644 index ddcce10df06..00000000000 --- a/RenderSystems/Vulkan/src/OgreVulkanTextureGpu.cpp +++ /dev/null @@ -1,760 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2017 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreVulkanTextureGpu.h" - -#include - -#include "OgreException.h" -#include "OgreVector.h" -#include "OgreVulkanMappings.h" -#include "OgreVulkanTextureGpuManager.h" -#include "OgreVulkanUtils.h" -#include "OgreVulkanHardwareBuffer.h" -#include "OgreBitwise.h" -#include "OgreRoot.h" -#include "OgreVulkanTextureGpuWindow.h" - -#define TODO_add_resource_transitions - -namespace Ogre -{ - VulkanHardwarePixelBuffer::VulkanHardwarePixelBuffer(VulkanTextureGpu* tex, uint32 width, uint32 height, uint32 depth, - uint8 face, uint32 mip) - : HardwarePixelBuffer(width, height, depth, tex->getFormat(), tex->getUsage(), false), mParent(tex), - mFace(face), mLevel(mip) - { - if(mParent->getUsage() & TU_RENDERTARGET) - { - // Create render target for each slice - mSliceTRT.reserve(mDepth); - for(size_t zoffset=0; zoffsetgetName(); - - RenderTexture *trt = new VulkanRenderTexture(name, this, zoffset, mParent, mFace); - mSliceTRT.push_back(trt); - Root::getSingleton().getRenderSystem()->attachRenderTarget(*trt); - } - } - } - - PixelBox VulkanHardwarePixelBuffer::lockImpl(const Box &lockBox, LockOptions options) - { - PixelBox ret(lockBox, mParent->getFormat()); - - auto textureManager = static_cast(mParent->getCreator()); - VulkanDevice* device = textureManager->getDevice(); - - uint32 target = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; - if(options != HBL_DISCARD && options != HBL_WRITE_ONLY) - target |= VK_BUFFER_USAGE_TRANSFER_DST_BIT; - - mStagingBuffer = std::make_unique(target, ret.getConsecutiveSize(), HBU_CPU_ONLY, false, device); - - if (options != HBL_DISCARD && options != HBL_WRITE_ONLY) - { - device->mGraphicsQueue.getCopyEncoder(0, mParent, true); - - VkBuffer dstBuffer = mStagingBuffer->getVkBuffer(); - - VkBufferImageCopy region; - region.bufferOffset = 0; - region.bufferRowLength = 0; - region.bufferImageHeight = 0; - - region.imageSubresource.aspectMask = VulkanMappings::getImageAspect(mFormat);; - region.imageSubresource.mipLevel = mLevel; - region.imageSubresource.baseArrayLayer = mFace; - region.imageSubresource.layerCount = 1; - - region.imageOffset.x = lockBox.left; - region.imageOffset.y = lockBox.top; - region.imageOffset.z = lockBox.front; - region.imageExtent.width = lockBox.getWidth(); - region.imageExtent.height = lockBox.getHeight(); - region.imageExtent.depth = lockBox.getDepth(); - - vkCmdCopyImageToBuffer(device->mGraphicsQueue.mCurrentCmdBuffer, mParent->getFinalTextureName(), - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dstBuffer, 1u, ®ion); - device->mGraphicsQueue.commitAndNextCommandBuffer(); - } - - return PixelBox(lockBox, mParent->getFormat(), mStagingBuffer->lock(options)); - } - - void VulkanHardwarePixelBuffer::unlockImpl() - { - mStagingBuffer->unlock(); - VkBufferImageCopy region; - if (mCurrentLockOptions != HBL_READ_ONLY) - { - auto textureManager = static_cast(mParent->getCreator()); - VulkanDevice* device = textureManager->getDevice(); - device->mGraphicsQueue.getCopyEncoder(0, mParent, false); - - VkBuffer srcBuffer = mStagingBuffer->getVkBuffer(); - - region.bufferOffset = 0; - region.bufferRowLength = 0; - region.bufferImageHeight = 0; - - region.imageSubresource.aspectMask = VulkanMappings::getImageAspect(mFormat); - region.imageSubresource.mipLevel = mLevel; - region.imageSubresource.baseArrayLayer = mFace; - region.imageSubresource.layerCount = 1; - - region.imageOffset.x = mCurrentLock.left; - region.imageOffset.y = mCurrentLock.top; - region.imageOffset.z = mCurrentLock.front; - region.imageExtent.width = mCurrentLock.getWidth(); - region.imageExtent.height = mCurrentLock.getHeight(); - region.imageExtent.depth = mCurrentLock.getDepth(); - - if (mParent->getTextureType() == TEX_TYPE_2D_ARRAY) - { - region.imageSubresource.baseArrayLayer = mCurrentLock.front; - region.imageOffset.z = 0; - } - - vkCmdCopyBufferToImage(device->mGraphicsQueue.mCurrentCmdBuffer, srcBuffer, mParent->getFinalTextureName(), - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1u, ®ion); - } - - bool finalSlice = region.imageSubresource.baseArrayLayer == mParent->getNumLayers() - 1; - if((mParent->getUsage() & TU_AUTOMIPMAP) && finalSlice) - mParent->_autogenerateMipmaps(); - mStagingBuffer.reset(); - } - - void VulkanHardwarePixelBuffer::blitFromMemory(const PixelBox& src, const Box& dstBox) - { - OgreAssert(src.getSize() == dstBox.getSize(), "scaling currently not supported"); - // convert to image native format if necessary - if(src.format != mFormat) - { - std::vector buffer; - buffer.resize(PixelUtil::getMemorySize(src.getWidth(), src.getHeight(), src.getDepth(), mFormat)); - PixelBox converted = PixelBox(src.getWidth(), src.getHeight(), src.getDepth(), mFormat, buffer.data()); - PixelUtil::bulkPixelConversion(src, converted); - blitFromMemory(converted, dstBox); // recursive call - return; - } - - auto ptr = lock(dstBox, HBL_WRITE_ONLY).data; - - memcpy(ptr, src.data, src.getConsecutiveSize()); - - unlock(); - } - void VulkanHardwarePixelBuffer::blitToMemory(const Box& srcBox, const PixelBox& dst) - { - OgreAssert(srcBox.getSize() == dst.getSize(), "scaling currently not supported"); - auto src = lock(srcBox, HBL_READ_ONLY); - PixelUtil::bulkPixelConversion(src, dst); - unlock(); - } - - VulkanTextureGpu::VulkanTextureGpu(TextureManager* textureManager, const String& name, ResourceHandle handle, - const String& group, bool isManual, ManualResourceLoader* loader) : - Texture(textureManager, name, handle, group, isManual, loader ), - mDefaultDisplaySrv( 0 ), - mDisplayTextureName( 0 ), - mFinalTextureName( 0 ), - mAllocation(VK_NULL_HANDLE), - mMsaaTextureName( 0 ), - mMsaaAllocation(VK_NULL_HANDLE), - mCurrLayout( VK_IMAGE_LAYOUT_UNDEFINED ), - mNextLayout( VK_IMAGE_LAYOUT_UNDEFINED ) - { - - } - //----------------------------------------------------------------------------------- - VulkanTextureGpu::~VulkanTextureGpu() { unload(); } - //----------------------------------------------------------------------------------- - void VulkanTextureGpu::createInternalResourcesImpl( void ) - { - if( mFormat == PF_UNKNOWN ) - return; // Nothing to do - - // Adjust format if required. - mFormat = TextureManager::getSingleton().getNativeFormat(mTextureType, mFormat, mUsage); - - VkImageCreateInfo imageInfo = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - imageInfo.imageType = getVulkanTextureType(); - imageInfo.extent.width = getWidth(); - imageInfo.extent.height = getHeight(); - imageInfo.extent.depth = getDepth(); - imageInfo.mipLevels = mNumMipmaps + 1; - imageInfo.arrayLayers = getNumFaces(); - imageInfo.flags = 0; - imageInfo.format = VulkanMappings::get( mFormat, mHwGamma ); - imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL; - imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - imageInfo.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; - imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - - if(mTextureType == TEX_TYPE_2D_ARRAY) - std::swap(imageInfo.extent.depth, imageInfo.arrayLayers); - - if( hasMsaaExplicitResolves() ) - { - imageInfo.samples = VkSampleCountFlagBits(std::max(mFSAA, 1u)); - } - else - imageInfo.samples = VK_SAMPLE_COUNT_1_BIT; - - if( mTextureType == TEX_TYPE_CUBE_MAP /*|| mTextureType == TextureTypes::TypeCubeArray*/ ) - imageInfo.flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; - - imageInfo.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; - - if (PixelUtil::isDepth(mFormat)) - imageInfo.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; - else if(mUsage & TU_RENDERTARGET) - imageInfo.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - - if( isUav() ) - imageInfo.usage |= VK_IMAGE_USAGE_STORAGE_BIT; - - VulkanDevice* device = static_cast(mCreator)->getDevice(); - - VmaAllocationCreateInfo allocInfo = {}; - allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; - OGRE_VK_CHECK(vmaCreateImage(device->getAllocator(), &imageInfo, &allocInfo, &mFinalTextureName, &mAllocation, 0)); - - String textureName = getName(); - setObjectName( device->mDevice, (uint64_t)mFinalTextureName, - VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, textureName.c_str() ); - - OgreAssert(device->mGraphicsQueue.getEncoderState() != VulkanQueue::EncoderGraphicsOpen, - "interrupting RenderPass not supported"); - device->mGraphicsQueue.endAllEncoders(); - - // Pool owners transition all its slices to read_only_optimal to avoid the validation layers - // from complaining the unused (and untouched) slices are in the wrong layout. - // We wait for no stage, and no stage waits for us. No caches are flushed. - // - // Later our TextureGpus using individual slices will perform an - // undefined -> read_only_optimal transition on the individual slices & mips - // to fill the data; and those transitions will be the ones who take care of blocking - // previous/later stages in their respective barriers - VkImageMemoryBarrier imageBarrier = this->getImageMemoryBarrier(); - imageBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - imageBarrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - - if( PixelUtil::isDepth( mFormat ) ) - imageBarrier.newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; - - vkCmdPipelineBarrier( device->mGraphicsQueue.mCurrentCmdBuffer, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - 0, 0u, 0, 0u, 0, 1u, &imageBarrier ); - - mCurrLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - mNextLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; - - // create - uint32 depth = mDepth; - for (uint8 face = 0; face < getNumFaces(); face++) - { - uint32 width = mWidth; - uint32 height = mHeight; - - for (uint32 mip = 0; mip <= getNumMipmaps(); mip++) - { - auto buf = std::make_shared(this, width, height, depth, face, mip); - mSurfaceList.push_back(buf); - if (width > 1) - width = width / 2; - if (height > 1) - height = height / 2; - if (depth > 1 && mTextureType != TEX_TYPE_2D_ARRAY) - depth = depth / 2; - } - } - - mDefaultDisplaySrv = _createView(0, 0, 0, getNumLayers()); - - if( mFSAA > 1 && !hasMsaaExplicitResolves() ) - createMsaaSurface(); - } - //----------------------------------------------------------------------------------- - void VulkanTextureGpu::freeInternalResourcesImpl( void ) - { - // If 'this' is being destroyed: We must call notifyTextureDestroyed - // - // If 'this' is only being transitioned to OnStorage: - // Our VkImage is being destroyed; and there may be pending image operations on it. - // This wouldn't be a problem because the vkDestroyImage call is delayed. - // However if the texture is later transitioned again to Resident, mCurrLayout & mNextLayout - // will get out of sync when endCopyEncoder gets called. - // - // e.g. if a texture performs: - // OnStorage -> Resident -> -> OnStorage -> Resident -> - // endCopyEncoder -> -> endCopyEncoder - // - // then the 1st endCopyEncoder will set mCurrLayout to SHADER_READ_ONLY_OPTIMAL because - // it thinks it changed the layout of the current mFinalTextureName, but it actually - // changed the layout of the previous mFinalTextureName which is scheduled to be destroyed - auto textureManager = static_cast(mCreator); - VulkanDevice *device = textureManager->getDevice(); - device->mGraphicsQueue.notifyTextureDestroyed( this ); - - vkDestroyImageView(device->mDevice, mDefaultDisplaySrv, 0); - mDefaultDisplaySrv = 0; - - vmaDestroyImage(device->getAllocator(), mFinalTextureName, mAllocation); - - destroyMsaaSurface(); - - mCurrLayout = VK_IMAGE_LAYOUT_UNDEFINED; - mNextLayout = VK_IMAGE_LAYOUT_UNDEFINED; - } - //----------------------------------------------------------------------------------- - void VulkanTextureGpu::copyTo( TextureGpu *dst, const PixelBox &dstBox, uint8 dstMipLevel, - const PixelBox &srcBox, uint8 srcMipLevel, - bool keepResolvedTexSynced, - ResourceAccess::ResourceAccess issueBarriers ) - { - //TextureGpu::copyTo( dst, dstBox, dstMipLevel, srcBox, srcMipLevel, issueBarriers ); - - OGRE_ASSERT_HIGH( dynamic_cast( dst ) ); - - VulkanTextureGpu *dstTexture = static_cast( dst ); - VulkanTextureGpuManager *textureManager = - static_cast( mCreator ); - VulkanDevice *device = textureManager->getDevice(); - - if( issueBarriers & ResourceAccess::Read ) - device->mGraphicsQueue.getCopyEncoder( 0, this, true ); - else - { - // This won't generate barriers, but it will close all other encoders - // and open the copy one - device->mGraphicsQueue.getCopyEncoder( 0, 0, true ); - } - - if( issueBarriers & ResourceAccess::Write ) - device->mGraphicsQueue.getCopyEncoder( 0, dstTexture, false ); - - VkImageCopy region; - - const uint32 sourceSlice = srcBox.front;// + getInternalSliceStart(); - const uint32 destinationSlice = dstBox.front;// + dstTexture->getInternalSliceStart(); - const uint32 numSlices = dstBox.getDepth() != 0 ? dstBox.getDepth() : dstTexture->getDepth(); - - region.srcSubresource.aspectMask = VulkanMappings::getImageAspect( this->getFormat() ); - region.srcSubresource.mipLevel = srcMipLevel; - region.srcSubresource.baseArrayLayer = sourceSlice; - region.srcSubresource.layerCount = numSlices; - - region.srcOffset.x = static_cast( srcBox.left ); - region.srcOffset.y = static_cast( srcBox.top ); - region.srcOffset.z = static_cast( srcBox.front ); - - region.dstSubresource.aspectMask = VulkanMappings::getImageAspect( dst->getFormat() ); - region.dstSubresource.mipLevel = dstMipLevel; - region.dstSubresource.baseArrayLayer = destinationSlice; - region.dstSubresource.layerCount = numSlices; - - region.dstOffset.x = dstBox.left; - region.dstOffset.y = dstBox.top; - region.dstOffset.z = dstBox.front; - - region.extent.width = srcBox.getWidth(); - region.extent.height = srcBox.getHeight(); - region.extent.depth = srcBox.getDepth(); - - VkImage srcTextureName = this->mFinalTextureName; - VkImage dstTextureName = dstTexture->mFinalTextureName; - - if( this->isMultisample() && !this->hasMsaaExplicitResolves() ) - srcTextureName = this->mMsaaTextureName; - if( dstTexture->isMultisample() && !dstTexture->hasMsaaExplicitResolves() ) - dstTextureName = dstTexture->mMsaaTextureName; - - vkCmdCopyImage( device->mGraphicsQueue.mCurrentCmdBuffer, srcTextureName, mCurrLayout, - dstTextureName, dstTexture->mCurrLayout, 1u, ®ion ); - - if( dstTexture->isMultisample() && !dstTexture->hasMsaaExplicitResolves() && - keepResolvedTexSynced ) - { - TODO_add_resource_transitions; // We must add res. transitions and then restore them - - // Must keep the resolved texture up to date. - VkImageResolve resolve = {}; - resolve.srcSubresource = region.dstSubresource; - resolve.dstSubresource = region.dstSubresource; - resolve.extent.width = getWidth(); - resolve.extent.height = getHeight(); - resolve.extent.depth = getDepth(); - - vkCmdResolveImage( device->mGraphicsQueue.mCurrentCmdBuffer, - dstTexture->mMsaaTextureName, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - dstTexture->mFinalTextureName, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1u, - &resolve ); - } - - // Do not perform the sync if notifyDataIsReady hasn't been called yet (i.e. we're - // still building the HW mipmaps, and the texture will never be ready) - /*if( dst->_isDataReadyImpl() && - dst->getGpuPageOutStrategy() == GpuPageOutStrategy::AlwaysKeepSystemRamCopy ) - { - dst->_syncGpuResidentToSystemRam(); - }*/ - } - //----------------------------------------------------------------------------------- - void VulkanTextureGpu::_autogenerateMipmaps( bool bUseBarrierSolver ) - { - // TODO: Integrate FidelityFX Single Pass Downsampler - SPD - // - // https://gpuopen.com/fidelityfx-spd/ - // https://github.com/GPUOpen-Effects/FidelityFX-SPD - VulkanTextureGpuManager *textureManager = - static_cast( mCreator ); - VulkanDevice *device = textureManager->getDevice(); - - const bool callerIsCompositor = mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - - if( callerIsCompositor ) - device->mGraphicsQueue.getCopyEncoder( 0, 0, true ); - else - { - // We must transition to VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL - // By the time we exit _autogenerateMipmaps, the texture will - // still be in VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, thus - // endCopyEncoder will perform as expected - device->mGraphicsQueue.getCopyEncoder( 0, this, true ); - } - - const uint32 numSlices = getNumLayers(); - - VkImageMemoryBarrier imageBarrier = getImageMemoryBarrier(); - - imageBarrier.subresourceRange.levelCount = 1u; - - const uint32 internalWidth = getWidth(); - const uint32 internalHeight = getHeight(); - - for( size_t i = 1u; i <= mNumMipmaps; ++i ) - { - // Convert the dst mipmap 'i' to TRANSFER_DST_OPTIMAL. Does not have to wait - // on anything because previous barriers (compositor or getCopyEncoder) - // have already waited - imageBarrier.subresourceRange.baseMipLevel = static_cast( i ); - imageBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - imageBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - imageBarrier.srcAccessMask = 0; - imageBarrier.dstAccessMask = 0; - vkCmdPipelineBarrier( device->mGraphicsQueue.mCurrentCmdBuffer, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - 0, 0u, 0, 0u, 0, 1u, &imageBarrier ); - - VkImageBlit region; - - region.srcSubresource.aspectMask = VulkanMappings::getImageAspect( this->getFormat() ); - region.srcSubresource.mipLevel = static_cast( i - 1u ); - region.srcSubresource.baseArrayLayer = 0u; - region.srcSubresource.layerCount = numSlices; - - region.srcOffsets[0].x = 0; - region.srcOffsets[0].y = 0; - region.srcOffsets[0].z = 0; - - region.srcOffsets[1].x = static_cast( std::max( internalWidth >> ( i - 1u ), 1u ) ); - region.srcOffsets[1].y = - static_cast( std::max( internalHeight >> ( i - 1u ), 1u ) ); - region.srcOffsets[1].z = static_cast( std::max( getDepth() >> ( i - 1u ), 1u ) ); - - region.dstSubresource.aspectMask = region.srcSubresource.aspectMask; - region.dstSubresource.mipLevel = static_cast( i ); - region.dstSubresource.baseArrayLayer = 0u; - region.dstSubresource.layerCount = numSlices; - - region.dstOffsets[0].x = 0; - region.dstOffsets[0].y = 0; - region.dstOffsets[0].z = 0; - - region.dstOffsets[1].x = static_cast( std::max( internalWidth >> i, 1u ) ); - region.dstOffsets[1].y = static_cast( std::max( internalHeight >> i, 1u ) ); - region.dstOffsets[1].z = static_cast( std::max( getDepth() >> i, 1u ) ); - - if(mTextureType == TEX_TYPE_2D_ARRAY) - { - region.srcOffsets[1].z = 1; - region.dstOffsets[1].z = 1; - } - - vkCmdBlitImage( device->mGraphicsQueue.mCurrentCmdBuffer, mFinalTextureName, mCurrLayout, - mFinalTextureName, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1u, ®ion, - VK_FILTER_LINEAR ); - - // Wait for vkCmdBlitImage on mip i to finish before advancing to mip i+1 - // Also transition src mip 'i' to TRANSFER_SRC_OPTIMAL - imageBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; - imageBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; - imageBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; - imageBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; - vkCmdPipelineBarrier( device->mGraphicsQueue.mCurrentCmdBuffer, - VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0u, - 0, 0u, 0, 1u, &imageBarrier ); - } - } - //----------------------------------------------------------------------------------- - VkImageType VulkanTextureGpu::getVulkanTextureType( void ) const - { - // clang-format off - switch( mTextureType ) - { - case TEX_TYPE_1D: return VK_IMAGE_TYPE_1D; - case TEX_TYPE_2D: return VK_IMAGE_TYPE_2D; - case TEX_TYPE_2D_ARRAY: return VK_IMAGE_TYPE_2D; - case TEX_TYPE_CUBE_MAP: return VK_IMAGE_TYPE_2D; - case TEX_TYPE_3D: return VK_IMAGE_TYPE_3D; - case TEX_TYPE_EXTERNAL_OES: break; - } - // clang-format on - - return VK_IMAGE_TYPE_2D; - } - //----------------------------------------------------------------------------------- - VkImageViewType VulkanTextureGpu::getInternalVulkanTextureViewType( void ) const - { - // clang-format off - switch( getTextureType() ) - { - case TEX_TYPE_1D: return VK_IMAGE_VIEW_TYPE_1D; - case TEX_TYPE_2D: return VK_IMAGE_VIEW_TYPE_2D; - case TEX_TYPE_2D_ARRAY: return VK_IMAGE_VIEW_TYPE_2D_ARRAY; - case TEX_TYPE_CUBE_MAP: return VK_IMAGE_VIEW_TYPE_CUBE; - case TEX_TYPE_3D: return VK_IMAGE_VIEW_TYPE_3D; - case TEX_TYPE_EXTERNAL_OES: break; - } - // clang-format on - - return VK_IMAGE_VIEW_TYPE_2D; - } - //----------------------------------------------------------------------------------- - VkImageView VulkanTextureGpu::_createView( uint8 mipLevel, - uint8 numMipmaps, uint16 arraySlice, - uint32 numSlices, - VkImage imageOverride ) const - { - VkImageViewType texType = this->getInternalVulkanTextureViewType(); - - if (numSlices == 1u && mTextureType == TEX_TYPE_CUBE_MAP) - { - texType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; - } - - if( !numMipmaps ) - numMipmaps = mNumMipmaps - mipLevel + 1; - - OGRE_ASSERT_LOW( numMipmaps <= (mNumMipmaps - mipLevel + 1) && - "Asking for more mipmaps than the texture has!" ); - - auto textureManager = static_cast(TextureManager::getSingletonPtr()); - VulkanDevice *device = textureManager->getDevice(); - - VkImageViewCreateInfo imageViewCi = {VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; - imageViewCi.image = imageOverride ? imageOverride : mFinalTextureName; - imageViewCi.viewType = texType; - imageViewCi.format = VulkanMappings::get( mFormat, mHwGamma ); - - if (PixelUtil::isLuminance(mFormat) && !PixelUtil::isDepth(mFormat)) - { - if (PixelUtil::getComponentCount(mFormat) == 2) - { - imageViewCi.components = {VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, - VK_COMPONENT_SWIZZLE_G}; - } - else - { - imageViewCi.components = {VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, - VK_COMPONENT_SWIZZLE_ONE}; - } - } - else if (mFormat == PF_A8) - { - imageViewCi.components = {VK_COMPONENT_SWIZZLE_ONE, VK_COMPONENT_SWIZZLE_ONE, VK_COMPONENT_SWIZZLE_ONE, - VK_COMPONENT_SWIZZLE_R}; - } - - // Using both depth & stencil aspects in an image view for texture sampling is illegal - // Thus prefer depth over stencil. We only use both flags for FBOs - imageViewCi.subresourceRange.aspectMask = VulkanMappings::getImageAspect(mFormat, imageOverride == 0); - imageViewCi.subresourceRange.baseMipLevel = mipLevel; - imageViewCi.subresourceRange.levelCount = numMipmaps; - imageViewCi.subresourceRange.baseArrayLayer = arraySlice; - if( numSlices == 0u ) - imageViewCi.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; - else - imageViewCi.subresourceRange.layerCount = numSlices; - - VkImageViewUsageCreateInfo flagRestriction = {VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; - if( textureManager->canRestrictImageViewUsage() && isUav() ) - { - // Some formats (e.g. *_SRGB formats) do not support USAGE_STORAGE_BIT at all - // Thus we need to mark when this view won't be using that bit. - // - // If VK_KHR_maintenance2 is not available then we cross our fingers - // and hope the driver doesn't stop us from doing it (it should work) - // - // The validation layers will complain though. This was a major Vulkan oversight. - imageViewCi.pNext = &flagRestriction; - flagRestriction.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; - flagRestriction.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; - if (mUsage & TU_RENDERTARGET) - { - flagRestriction.usage |= PixelUtil::isDepth(mFormat) ? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT - : VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - } - } - - VkImageView imageView; - OGRE_VK_CHECK(vkCreateImageView( device->mDevice, &imageViewCi, 0, &imageView )); - return imageView; - } - //----------------------------------------------------------------------------------- - void VulkanTextureGpu::destroyView( VkImageView imageView ) - { - //VulkanTextureGpuManager *textureManager = - // static_cast( mCreator ); - //VulkanDevice *device = textureManager->getDevice(); - - //delayed_vkDestroyImageView( textureManager->getVaoManager(), device->mDevice, imageView, 0 ); - } - //----------------------------------------------------------------------------------- - VkImageView VulkanTextureGpu::createView( void ) const - { - OGRE_ASSERT_MEDIUM( mDefaultDisplaySrv && - "Either the texture wasn't properly loaded or _setToDisplayDummyTexture " - "wasn't called when it should have been" ); - return mDefaultDisplaySrv; - } - //----------------------------------------------------------------------------------- - VkImageMemoryBarrier VulkanTextureGpu::getImageMemoryBarrier( void ) const - { - VkImageMemoryBarrier imageMemBarrier = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; - imageMemBarrier.image = mFinalTextureName; - imageMemBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - imageMemBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; - imageMemBarrier.subresourceRange.aspectMask = VulkanMappings::getImageAspect(mFormat); - imageMemBarrier.subresourceRange.baseMipLevel = 0u; - imageMemBarrier.subresourceRange.levelCount = mNumMipmaps + 1; - imageMemBarrier.subresourceRange.baseArrayLayer = 0; - imageMemBarrier.subresourceRange.layerCount = getNumLayers(); - return imageMemBarrier; - } - //----------------------------------------------------------------------------------- - void VulkanTextureGpu::createMsaaSurface( void ) - { - VkImageCreateInfo imageInfo = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; - imageInfo.imageType = getVulkanTextureType(); - imageInfo.extent.width = getWidth(); - imageInfo.extent.height = getHeight(); - imageInfo.extent.depth = getDepth(); - imageInfo.mipLevels = 1u; - imageInfo.arrayLayers = 1u; - imageInfo.format = VulkanMappings::get( mFormat ); - imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL; - imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - imageInfo.usage = VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT; - imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; - imageInfo.samples = VkSampleCountFlagBits( mFSAA ); - imageInfo.flags = 0; - imageInfo.usage |= PixelUtil::isDepth( mFormat ) - ? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT - : VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; - - VulkanDevice* device = static_cast(mCreator)->getDevice(); - - VmaAllocationCreateInfo allocInfo = {}; - allocInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; - OGRE_VK_CHECK( - vmaCreateImage(device->getAllocator(), &imageInfo, &allocInfo, &mMsaaTextureName, &mMsaaAllocation, 0)); - - String textureName = getName() + "/MsaaImplicit"; - setObjectName(device->mDevice, (uint64_t)mMsaaTextureName, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, - textureName.c_str()); - - // Immediately transition to its only state - VkImageMemoryBarrier imageBarrier = this->getImageMemoryBarrier(); - imageBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - imageBarrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - - if( PixelUtil::isDepth( mFormat ) ) - imageBarrier.newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; - - imageBarrier.image = mMsaaTextureName; - vkCmdPipelineBarrier( device->mGraphicsQueue.mCurrentCmdBuffer, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, - 0u, 0, 0u, 0, 1u, &imageBarrier ); - } - //----------------------------------------------------------------------------------- - void VulkanTextureGpu::destroyMsaaSurface( void ) - { - if(!mMsaaTextureName) - return; - - VulkanDevice *device = static_cast(mCreator)->getDevice(); - vmaDestroyImage(device->getAllocator(), mMsaaTextureName, mMsaaAllocation); - } - - VulkanRenderTexture::VulkanRenderTexture(const String& name, HardwarePixelBuffer* buffer, uint32 zoffset, - VulkanTextureGpu* target, uint32 face) - : RenderTexture(buffer, zoffset) - { - mName = name; - - auto texMgr = TextureManager::getSingletonPtr(); - VulkanDevice* device = static_cast(texMgr)->getDevice(); - - target->setFSAA(1, ""); - - bool depthTarget = PixelUtil::isDepth(target->getFormat()); - - if(!depthTarget) - { - mDepthTexture = std::make_unique(texMgr, mName+"/Depth", 0, "", true, nullptr); - mDepthTexture->setWidth(target->getWidth()); - mDepthTexture->setHeight(target->getHeight()); - mDepthTexture->setFormat(PF_DEPTH32); - mDepthTexture->createInternalResources(); - mDepthTexture->setFSAA(1, ""); - } - - mRenderPassDescriptor = std::make_unique(&device->mGraphicsQueue, device->mRenderSystem); - mRenderPassDescriptor->mColour[0] = depthTarget ? 0 : target; - mRenderPassDescriptor->mSlice = face; - mRenderPassDescriptor->mDepth = depthTarget ? target : mDepthTexture.get(); - mRenderPassDescriptor->mNumColourEntries = int(depthTarget == 0); - mRenderPassDescriptor->entriesModified(true); - } -} // namespace Ogre diff --git a/RenderSystems/Vulkan/src/OgreVulkanTextureGpuManager.cpp b/RenderSystems/Vulkan/src/OgreVulkanTextureGpuManager.cpp deleted file mode 100644 index f6c6b502c74..00000000000 --- a/RenderSystems/Vulkan/src/OgreVulkanTextureGpuManager.cpp +++ /dev/null @@ -1,205 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2017 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreVulkanTextureGpuManager.h" - -#include "OgreVulkanMappings.h" -#include "OgreVulkanTextureGpu.h" -#include "OgreVulkanTextureGpuWindow.h" -#include "OgreVulkanUtils.h" - -#include "OgrePixelFormat.h" -#include "OgreVector.h" -#include "OgreRoot.h" - -#include "OgreException.h" - -namespace Ogre -{ - VulkanSampler::VulkanSampler(VkDevice device) : mDevice(device), mVkSampler(VK_NULL_HANDLE) {} - VulkanSampler::~VulkanSampler() { vkDestroySampler(mDevice, mVkSampler, nullptr); } - VkSampler VulkanSampler::bind() - { - if(!mDirty) - return mVkSampler; - - vkDestroySampler(mDevice, mVkSampler, nullptr); - - VkSamplerCreateInfo samplerCi = {VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; - samplerCi.minFilter = VulkanMappings::get(mMinFilter); - samplerCi.magFilter = VulkanMappings::get(mMagFilter); - samplerCi.mipmapMode = VulkanMappings::getMipFilter(mMipFilter); - samplerCi.mipLodBias = mMipmapBias; - - auto caps = Root::getSingleton().getRenderSystem()->getCapabilities(); - if (caps->hasCapability(RSC_ANISOTROPY)) - { - samplerCi.anisotropyEnable = VK_TRUE; - samplerCi.maxAnisotropy = std::min(caps->getMaxSupportedAnisotropy(), mMaxAniso); - } - - samplerCi.addressModeU = VulkanMappings::get(mAddressMode.u); - samplerCi.addressModeV = VulkanMappings::get(mAddressMode.v); - samplerCi.addressModeW = VulkanMappings::get(mAddressMode.w); - samplerCi.unnormalizedCoordinates = VK_FALSE; - samplerCi.maxLod = mMipFilter == FO_NONE ? 0 : VK_LOD_CLAMP_NONE; - - bool reversedZ = Root::getSingleton().getRenderSystem()->isReverseDepthBufferEnabled(); - - auto borderBlack = VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK; - auto borderWhite = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; - - if(reversedZ) - std::swap(borderBlack, borderWhite); - - samplerCi.borderColor = mBorderColour.getAsRGBA() == 0x0000FF ? borderBlack : borderWhite; - - if (mCompareEnabled) - { - auto cmpFunc = mCompareFunc; - if(reversedZ) - cmpFunc = VulkanRenderSystem::reverseCompareFunction(cmpFunc); - samplerCi.compareEnable = VK_TRUE; - samplerCi.compareOp = VulkanMappings::get(cmpFunc); - } - - OGRE_VK_CHECK(vkCreateSampler(mDevice, &samplerCi, 0, &mVkSampler)); - mDirty = false; - return mVkSampler; - } - - VulkanTextureGpuManager::VulkanTextureGpuManager(RenderSystem *renderSystem, VulkanDevice *device, - bool bCanRestrictImageViewUsage ) : - mDevice( device ), - mCanRestrictImageViewUsage( bCanRestrictImageViewUsage ) - { - } - //----------------------------------------------------------------------------------- - VulkanTextureGpuManager::~VulkanTextureGpuManager() - { - removeAll(); - } - SamplerPtr VulkanTextureGpuManager::_createSamplerImpl() - { - return std::make_shared(mDevice->mDevice); - } - //----------------------------------------------------------------------------------- - Resource* VulkanTextureGpuManager::createImpl(const String& name, ResourceHandle handle, - const String& group, bool isManual, - ManualResourceLoader* loader, - const NameValuePairList* createParams) - { - return OGRE_NEW VulkanTextureGpu(this, name, handle, group, isManual, loader); - } - PixelFormat VulkanTextureGpuManager::getNativeFormat(TextureType ttype, PixelFormat format, int usage) - { - if( format == PF_R8G8B8 ) - return PF_X8R8G8B8; - if( format == PF_B8G8R8 ) - return PF_X8B8G8R8; - -#ifdef OGRE_VK_WORKAROUND_ADRENO_D32_FLOAT - if( Workarounds::mAdrenoD32FloatBug && isRenderToTexture() ) - { - if( pixelFormat == PF_DEPTH32F ) - return PFG_D24_UNORM; - else if( pixelFormat == PFG_D32_FLOAT_S8X24_UINT ) - return PFG_D24_UNORM_S8_UINT; - } -#endif - - if (VulkanMappings::get(format)) - return format; - - return PF_BYTE_RGBA; - } - //----------------------------------------------------------------------------------- - bool VulkanTextureGpuManager::checkSupport( PixelFormatGpu format, uint32 textureFlags ) const - { - OGRE_ASSERT_LOW( - textureFlags != TU_NOT_SRV && - "Invalid textureFlags combination. Asking to check if format is supported to do nothing" ); - - const VkFormat vkFormat = VulkanMappings::get( format ); - - VkFormatProperties props; - vkGetPhysicalDeviceFormatProperties( mDevice->mPhysicalDevice, vkFormat, &props ); - - uint32 features = 0; - - if( !( textureFlags & TU_NOT_SRV ) ) - features |= VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT; - - if( textureFlags & TU_UNORDERED_ACCESS ) - features |= VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT; - - if( textureFlags & TU_RENDERTARGET ) - { - if( PixelUtil::isDepth( format ) ) - { - features |= VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT; - } - else - { - features |= VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT | - VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT; - } - } - - if( textureFlags & TU_AUTOMIPMAP ) - { - features |= VK_FORMAT_FEATURE_BLIT_SRC_BIT | VK_FORMAT_FEATURE_BLIT_DST_BIT; - //if( !PixelUtil::supportsHwMipmaps( format ) ) - return false; - } - - if( ( props.optimalTilingFeatures & features ) == features ) - return true; - -#ifdef OGRE_VK_WORKAROUND_ADRENO_5XX_6XX_MINCAPS - if( Workarounds::mAdreno5xx6xxMinCaps && - ( textureFlags & ( TextureFlags::Uav | TextureFlags::AllowAutomipmaps ) ) == 0u ) - { - switch( format ) - { - case PFG_R16_UNORM: - case PFG_R16_SNORM: - case PFG_RG16_UNORM: - case PFG_RG16_SNORM: - case PFG_RGBA16_UNORM: - case PFG_RGBA16_SNORM: - return true; - default: - break; - } - } -#endif - - return false; - } -} // namespace Ogre diff --git a/RenderSystems/Vulkan/src/OgreVulkanTextureGpuWindow.cpp b/RenderSystems/Vulkan/src/OgreVulkanTextureGpuWindow.cpp deleted file mode 100644 index df6885404be..00000000000 --- a/RenderSystems/Vulkan/src/OgreVulkanTextureGpuWindow.cpp +++ /dev/null @@ -1,88 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-present Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreVulkanTextureGpuWindow.h" - -#include "OgreVulkanTextureGpuManager.h" -#include "OgreVulkanWindow.h" -#include "OgreVector.h" - -#include "OgreException.h" - -namespace Ogre -{ - extern const String CustomAttributeIdString_GLCONTEXT; - - VulkanTextureGpuWindow::VulkanTextureGpuWindow(const String& name, - TextureType initialType, TextureManager *textureManager, - VulkanWindow *window ) : - VulkanTextureGpu( textureManager, name, 0, "", true, 0), - mWindow( window ), - mCurrentImageIdx( 0u ) - { - mTextureType = TEX_TYPE_2D; - mNumMipmaps = 0; - } - //----------------------------------------------------------------------------------- - VulkanTextureGpuWindow::~VulkanTextureGpuWindow() { unload(); } - //----------------------------------------------------------------------------------- - VkSemaphore VulkanTextureGpuWindow::getImageAcquiredSemaphore( void ) - { - return mWindow->getImageAcquiredSemaphore(); - } - //----------------------------------------------------------------------------------- - void VulkanTextureGpuWindow::_setCurrentImage( VkImage image, uint32 imageIdx ) - { - mFinalTextureName = image; - mCurrentImageIdx = imageIdx; - } - //----------------------------------------------------------------------------------- - void VulkanTextureGpuWindow::createInternalResourcesImpl( void ) - { - if( mFSAA > 1 ) - createMsaaSurface(); - - // create surface to handle download - auto buf = std::make_shared(this, mWidth, mHeight, mDepth, 0, 0); - mSurfaceList.push_back(buf); - mCurrLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; - mNextLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; - } - //----------------------------------------------------------------------------------- - void VulkanTextureGpuWindow::freeInternalResourcesImpl( void ) - { - mFinalTextureName = 0; - destroyMsaaSurface(); - } - //----------------------------------------------------------------------------------- - void VulkanTextureGpuWindow::getCustomAttribute( const String& name, void *pData ) - { - //if( name == "Window" ) - // *static_cast( pData ) = mWindow; - } -} // namespace Ogre diff --git a/RenderSystems/Vulkan/src/OgreVulkanUtils.cpp b/RenderSystems/Vulkan/src/OgreVulkanUtils.cpp deleted file mode 100644 index 5e227c53d27..00000000000 --- a/RenderSystems/Vulkan/src/OgreVulkanUtils.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-present Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreVulkanUtils.h" - -#include "OgreStringConverter.h" -#include "OgreVulkanDevice.h" -#include "OgreVulkanMappings.h" - -namespace Ogre -{ - String vkResultToString( VkResult result ) - { - // clang-format off - switch( result ) - { - case VK_SUCCESS: return "VK_SUCCESS"; - case VK_NOT_READY: return "VK_NOT_READY"; - case VK_TIMEOUT: return "VK_TIMEOUT"; - case VK_EVENT_SET: return "VK_EVENT_SET"; - case VK_EVENT_RESET: return "VK_EVENT_RESET"; - case VK_INCOMPLETE: return "VK_INCOMPLETE"; - case VK_ERROR_OUT_OF_HOST_MEMORY: return "VK_ERROR_OUT_OF_HOST_MEMORY"; - case VK_ERROR_OUT_OF_DEVICE_MEMORY: return "VK_ERROR_OUT_OF_DEVICE_MEMORY"; - case VK_ERROR_INITIALIZATION_FAILED: return "VK_ERROR_INITIALIZATION_FAILED"; - case VK_ERROR_DEVICE_LOST: return "VK_ERROR_DEVICE_LOST"; - case VK_ERROR_MEMORY_MAP_FAILED: return "VK_ERROR_MEMORY_MAP_FAILED"; - case VK_ERROR_LAYER_NOT_PRESENT: return "VK_ERROR_LAYER_NOT_PRESENT"; - case VK_ERROR_EXTENSION_NOT_PRESENT: return "VK_ERROR_EXTENSION_NOT_PRESENT"; - case VK_ERROR_FEATURE_NOT_PRESENT: return "VK_ERROR_FEATURE_NOT_PRESENT"; - case VK_ERROR_INCOMPATIBLE_DRIVER: return "VK_ERROR_INCOMPATIBLE_DRIVER"; - case VK_ERROR_TOO_MANY_OBJECTS: return "VK_ERROR_TOO_MANY_OBJECTS"; - case VK_ERROR_FORMAT_NOT_SUPPORTED: return "VK_ERROR_FORMAT_NOT_SUPPORTED"; - case VK_ERROR_FRAGMENTED_POOL: return "VK_ERROR_FRAGMENTED_POOL"; - case VK_ERROR_OUT_OF_POOL_MEMORY: return "VK_ERROR_OUT_OF_POOL_MEMORY"; - case VK_ERROR_INVALID_EXTERNAL_HANDLE: return "VK_ERROR_INVALID_EXTERNAL_HANDLE"; - case VK_ERROR_SURFACE_LOST_KHR: return "VK_ERROR_SURFACE_LOST_KHR"; - case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR: return "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR"; - case VK_SUBOPTIMAL_KHR: return "VK_SUBOPTIMAL_KHR"; - case VK_ERROR_OUT_OF_DATE_KHR: return "VK_ERROR_OUT_OF_DATE_KHR"; - case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR: return "VK_ERROR_INCOMPATIBLE_DISPLAY_KHR"; - case VK_ERROR_VALIDATION_FAILED_EXT: return "VK_ERROR_VALIDATION_FAILED_EXT"; - case VK_ERROR_INVALID_SHADER_NV: return "VK_ERROR_INVALID_SHADER_NV"; - case VK_ERROR_NOT_PERMITTED_EXT: return "VK_ERROR_NOT_PERMITTED_EXT"; - default: - return StringConverter::toString( result ); - } - // clang-format on - } - - void setObjectName( VkDevice device, uint64_t object, VkDebugReportObjectTypeEXT objectType, - const char *name ) - { - // Check for a valid function pointer - if( vkDebugMarkerSetObjectNameEXT ) - { - VkDebugMarkerObjectNameInfoEXT nameInfo = {}; - nameInfo.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT; - nameInfo.objectType = objectType; - nameInfo.object = object; - nameInfo.pObjectName = name; - vkDebugMarkerSetObjectNameEXT( device, &nameInfo ); - } - } -} // namespace Ogre diff --git a/RenderSystems/Vulkan/src/OgreVulkanWindow.cpp b/RenderSystems/Vulkan/src/OgreVulkanWindow.cpp deleted file mode 100644 index d5a399afd4c..00000000000 --- a/RenderSystems/Vulkan/src/OgreVulkanWindow.cpp +++ /dev/null @@ -1,576 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreVulkanWindow.h" - -#include "OgreVulkanDevice.h" -#include "OgreVulkanMappings.h" -#include "OgreVulkanRenderSystem.h" -#include "OgreVulkanTextureGpuWindow.h" -#include "OgreVulkanUtils.h" - -#include "OgreException.h" -#include "OgrePixelFormat.h" -#include "OgreVulkanTextureGpuManager.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreViewport.h" -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID -#include -#elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32 -#define WIN32_LEAN_AND_MEAN -#include -#endif -#include "OgreDepthBuffer.h" - -#define TODO_handleSeparatePresentQueue - -namespace Ogre -{ - VulkanWindow::VulkanWindow( const String &title, uint32 width, uint32 height, bool fullscreenMode ) : - mLowestLatencyVSync( false ), - mHwGamma( false ), - mDevice( 0 ), - mTexture( 0 ), - mDepthTexture( 0 ), - mSurfaceKHR( 0 ), - mSwapchain( 0 ), - mCurrentSemaphoreIndex( 0 ), - mSwapchainStatus( SwapchainReleased ), - mSurfaceTransform( VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR ) - { - mActive = true; - mName = title; - } - //------------------------------------------------------------------------- - VulkanWindow::~VulkanWindow() - { - destroy(); - } - //------------------------------------------------------------------------- - PixelFormat VulkanWindow::chooseSurfaceFormat( bool hwGamma ) - { - uint32 numFormats = 0u; - OGRE_VK_CHECK(vkGetPhysicalDeviceSurfaceFormatsKHR(mDevice->mPhysicalDevice, mSurfaceKHR, &numFormats, 0)); - OgreAssert(numFormats > 0, "No surface formats found"); - - FastArray formats(numFormats); - OGRE_VK_CHECK( - vkGetPhysicalDeviceSurfaceFormatsKHR(mDevice->mPhysicalDevice, mSurfaceKHR, &numFormats, formats.data())); - - PixelFormatGpu pixelFormat = PF_UNKNOWN; - for( size_t i = 0; i < numFormats && pixelFormat == PF_UNKNOWN; ++i ) - { - switch( formats[i].format ) - { - case VK_FORMAT_R8G8B8A8_SRGB: - if( hwGamma ) - pixelFormat = PF_A8B8G8R8;//_SRGB; - break; - case VK_FORMAT_B8G8R8A8_SRGB: - if( hwGamma ) - pixelFormat = PF_A8R8G8B8;//_SRGB; - break; - case VK_FORMAT_R8G8B8A8_UNORM: - if( !hwGamma ) - pixelFormat = PF_A8B8G8R8; - break; - case VK_FORMAT_B8G8R8A8_UNORM: - if( !hwGamma ) - pixelFormat = PF_A8R8G8B8; - break; - default: - continue; - } - } - - OgreAssert(pixelFormat != PF_UNKNOWN, "No suitable surface format found"); - return pixelFormat; - } - //------------------------------------------------------------------------- - void VulkanWindow::createSwapchain( void ) - { - mTexture->setWidth(mWidth); - mTexture->setHeight(mHeight); - mTexture->createInternalResources(); - - mDepthTexture->setWidth(mWidth); - mDepthTexture->setHeight(mHeight); - mDepthTexture->setNumMipmaps(0); - mDepthTexture->createInternalResources(); - - VkSurfaceCapabilitiesKHR surfaceCaps; - OGRE_VK_CHECK(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(mDevice->mPhysicalDevice, mSurfaceKHR, &surfaceCaps)); - - // Swapchain may be smaller/bigger than requested - mWidth = Math::Clamp(mWidth, surfaceCaps.minImageExtent.width, surfaceCaps.maxImageExtent.width); - mHeight = - Math::Clamp(mHeight, surfaceCaps.minImageExtent.height, surfaceCaps.maxImageExtent.height); - - VkBool32 supported; - OGRE_VK_CHECK(vkGetPhysicalDeviceSurfaceSupportKHR(mDevice->mPhysicalDevice, mDevice->mGraphicsQueue.mFamilyIdx, - mSurfaceKHR, &supported)); - OgreAssert(supported, "KHR Surface is unsupported"); - - uint32 numPresentModes = 0u; - vkGetPhysicalDeviceSurfacePresentModesKHR(mDevice->mPhysicalDevice, mSurfaceKHR, &numPresentModes, 0); - std::vector presentModes(numPresentModes); - vkGetPhysicalDeviceSurfacePresentModesKHR(mDevice->mPhysicalDevice, mSurfaceKHR, &numPresentModes, - presentModes.data()); - - // FIFO is guaranteed to be present - VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_KHR; - - if (!mVSync && - std::find(presentModes.begin(), presentModes.end(), VK_PRESENT_MODE_IMMEDIATE_KHR) != presentModes.end()) - { - presentMode = VK_PRESENT_MODE_IMMEDIATE_KHR; - } - - const char* c_presentModeStrs[] = {"IMMEDIATE_KHR", - "MAILBOX_KHR", - "FIFO_KHR", - "FIFO_RELAXED_KHR", - "SHARED_DEMAND_REFRESH_KHR", - "SHARED_CONTINUOUS_REFRESH_KHR"}; - - LogManager::getSingleton().stream() << "[VulkanWindow] presentMode = " << c_presentModeStrs[presentMode]; - - //----------------------------- - // Create swapchain - //----------------------------- - - // try to get triple buffering by default - // https://github.com/KhronosGroup/Vulkan-Samples/blob/master/samples/performance/swapchain_images/swapchain_images_tutorial.md - auto minImageCount = surfaceCaps.minImageCount + 1; - if (surfaceCaps.maxImageCount != 0u) - minImageCount = std::min(minImageCount, surfaceCaps.maxImageCount); - - VkSwapchainCreateInfoKHR swapchainCreateInfo = {VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR}; - swapchainCreateInfo.surface = mSurfaceKHR; - swapchainCreateInfo.minImageCount = minImageCount; - swapchainCreateInfo.imageFormat = VulkanMappings::get(mTexture->getFormat()); - swapchainCreateInfo.imageColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR; - swapchainCreateInfo.imageExtent.width = getWidth(); - swapchainCreateInfo.imageExtent.height = getHeight(); - swapchainCreateInfo.imageArrayLayers = 1u; - swapchainCreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; - swapchainCreateInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; - swapchainCreateInfo.queueFamilyIndexCount = 0u; - swapchainCreateInfo.pQueueFamilyIndices = 0; - // Find a supported composite alpha mode - one of these is guaranteed to be set - swapchainCreateInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; - VkCompositeAlphaFlagBitsKHR compositeAlphaFlags[4] = { - VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, - VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR, - VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR, - VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR, - }; - for (auto flag : compositeAlphaFlags) - { - if (surfaceCaps.supportedCompositeAlpha & flag) - { - swapchainCreateInfo.compositeAlpha = flag; - break; - } - } - -#if 0 - // https://developer.android.com/games/optimize/vulkan-prerotation - mSurfaceTransform = surfaceCaps.currentTransform; - if (mSurfaceTransform & (VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR | VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR)) - { - std::swap(swapchainCreateInfo.imageExtent.width, swapchainCreateInfo.imageExtent.height); - std::swap(mWidth, mHeight); - } - swapchainCreateInfo.preTransform = mSurfaceTransform; - LogManager::getSingleton().stream() << "[VulkanWindow] SurfaceTransform = " << mSurfaceTransform; -#endif - swapchainCreateInfo.preTransform = mSurfaceTransform; - swapchainCreateInfo.presentMode = presentMode; - - //----------------------------- - // Create swapchain images - //----------------------------- - OGRE_VK_CHECK(vkCreateSwapchainKHR(mDevice->mDevice, &swapchainCreateInfo, 0, &mSwapchain)); - - uint32 numSwapchainImages = 0u; - OGRE_VK_CHECK(vkGetSwapchainImagesKHR(mDevice->mDevice, mSwapchain, &numSwapchainImages, NULL)); - - OGRE_ASSERT_LOW( numSwapchainImages > 0u ); - - mSwapchainImages.resize( numSwapchainImages ); - OGRE_VK_CHECK( - vkGetSwapchainImagesKHR(mDevice->mDevice, mSwapchain, &numSwapchainImages, mSwapchainImages.data())); - - mSwapchainImageViews.resize(numSwapchainImages); - mImageReadySemaphores.resize(numSwapchainImages); - mRenderFinishedSemaphores.resize(numSwapchainImages); - mImageFences.resize(numSwapchainImages); - - VkSemaphoreCreateInfo semaphoreCreateInfo = {VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO}; - for (uint32 i = 0; i < numSwapchainImages; i++) - { - mSwapchainImageViews[i] = mTexture->_createView(0, 1, 0, 1u, mSwapchainImages[i]); - OGRE_VK_CHECK(vkCreateSemaphore(mDevice->mDevice, &semaphoreCreateInfo, 0, &mImageReadySemaphores[i])); - OGRE_VK_CHECK(vkCreateSemaphore(mDevice->mDevice, &semaphoreCreateInfo, 0, &mRenderFinishedSemaphores[i])); - } - - acquireNextImage(); - - mRenderPassDescriptor->mColour[0] = mTexture; - mRenderPassDescriptor->mDepth = mDepthTexture; - mRenderPassDescriptor->mNumColourEntries = 1; - mRenderPassDescriptor->entriesModified(true); - } - //------------------------------------------------------------------------- - void VulkanWindow::destroySwapchain( void ) - { - for(auto imf : mImageFences) - { - if(imf == VK_NULL_HANDLE) - continue; - OGRE_VK_CHECK(vkWaitForFences(mDevice->mDevice, 1, &imf, VK_TRUE, UINT64_MAX)); - } - - mTexture->unload(); - mDepthTexture->unload(); - mRenderPassDescriptor->releaseFbo(); - mDevice->mRenderSystem->notifySwapchainDestroyed(); - - for(auto iv : mSwapchainImageViews) - { - vkDestroyImageView(mDevice->mDevice, iv, 0); - } - - for(auto s : mImageReadySemaphores) - { - vkDestroySemaphore( mDevice->mDevice, s, 0 ); - } - - for(auto s : mRenderFinishedSemaphores) - { - vkDestroySemaphore( mDevice->mDevice, s, 0 ); - } - - vkDestroySwapchainKHR(mDevice->mDevice, mSwapchain, 0); - mSwapchain = 0; - - mSwapchainStatus = SwapchainReleased; - } - //------------------------------------------------------------------------- - void VulkanWindow::acquireNextImage( void ) - { - OGRE_ASSERT_LOW( mSwapchainStatus == SwapchainReleased ); - - mCurrentSemaphoreIndex = (mCurrentSemaphoreIndex + 1) % mImageReadySemaphores.size(); - auto semaphore = mImageReadySemaphores[mCurrentSemaphoreIndex]; - - uint32 imageIdx = 0u; - auto res = - vkAcquireNextImageKHR(mDevice->mDevice, mSwapchain, UINT64_MAX, semaphore, VK_NULL_HANDLE, &imageIdx); - if (res != VK_ERROR_OUT_OF_DATE_KHR && res != VK_SUBOPTIMAL_KHR && res != VK_SUCCESS) - { - LogManager::getSingleton().logError("vkAcquireNextImageKHR failed with" + vkResultToString(res)); - return; - } - - if(mImageFences[imageIdx]) - OGRE_VK_CHECK(vkWaitForFences(mDevice->mDevice, 1, &mImageFences[imageIdx], VK_TRUE, UINT64_MAX)); - - mSwapchainStatus = SwapchainAcquired; - mTexture->_setCurrentImage( mSwapchainImages[imageIdx], imageIdx ); - } - - void VulkanWindow::resize(uint width, uint height) - { - if (mClosed) - return; - - if (mWidth == width && mHeight == height) - return; - - if (width != 0 && height != 0) - { - mWidth = width; - mHeight = height; - - // recreate swapchain - mDevice->stall(); - destroySwapchain(); - createSwapchain(); - - for (auto it : mViewportList) - it.second->_updateDimensions(); - } - } - - void VulkanWindow::windowMovedOrResized() - { -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - // read size from handle - auto width = ANativeWindow_getWidth((ANativeWindow*)mWindowHandle); - auto height = ANativeWindow_getHeight((ANativeWindow*)mWindowHandle); - resize(width, height); -#endif - } - - void VulkanWindow::copyContentsToMemory(const Box& src, const PixelBox &dst, FrameBuffer buffer) - { - mTexture->getBuffer()->blitToMemory(src, dst); - } - - //------------------------------------------------------------------------- - void VulkanWindow::destroy( void ) - { - destroySwapchain(); - delete mTexture; - delete mDepthTexture; - if( mSurfaceKHR ) - { - vkDestroySurfaceKHR( mDevice->mInstance, mSurfaceKHR, 0 ); - mSurfaceKHR = 0; - } - } - //------------------------------------------------------------------------- - void VulkanWindow::_setDevice( VulkanDevice *device ) - { - OGRE_ASSERT_LOW( !mDevice ); - mDevice = device; - } - //------------------------------------------------------------------------- - void VulkanWindow::createSurface(size_t windowHandle) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX - Display *dpy = XOpenDisplay(NULL); - - VkXlibSurfaceCreateInfoKHR surfCreateInfo = {VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR}; - surfCreateInfo.dpy = dpy; - surfCreateInfo.window = (Window)windowHandle;; - - int scr = DefaultScreen( dpy ); - if (!vkGetPhysicalDeviceXlibPresentationSupportKHR(mDevice->mPhysicalDevice, mDevice->mGraphicsQueue.mFamilyIdx, - dpy, DefaultVisual(dpy, scr)->visualid)) - { - OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Vulkan not supported on given X11 window"); - } - - OGRE_VK_CHECK(vkCreateXlibSurfaceKHR(mDevice->mInstance, &surfCreateInfo, 0, &mSurfaceKHR)); -#elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - HINSTANCE hInst = NULL; - static TCHAR staticVar; - GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, &staticVar, &hInst); - - VkWin32SurfaceCreateInfoKHR surfCreateInfo = {VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; - surfCreateInfo.hinstance = hInst; - surfCreateInfo.hwnd = (HWND)windowHandle; - - OGRE_VK_CHECK(vkCreateWin32SurfaceKHR(mDevice->mInstance, &surfCreateInfo, 0, &mSurfaceKHR)); -#elif OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - VkAndroidSurfaceCreateInfoKHR surfCreateInfo = {VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR}; - surfCreateInfo.window = (ANativeWindow*)windowHandle; - - OGRE_VK_CHECK(vkCreateAndroidSurfaceKHR(mDevice->mInstance, &surfCreateInfo, 0, &mSurfaceKHR)); -#endif - } - - const char *VulkanWindow::getRequiredExtensionName() - { -#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX - return VK_KHR_XLIB_SURFACE_EXTENSION_NAME; -#elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - return VK_KHR_WIN32_SURFACE_EXTENSION_NAME; -#elif OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - return VK_KHR_ANDROID_SURFACE_EXTENSION_NAME; -#endif - } - - void VulkanWindow::create(const String& name, unsigned int width, unsigned int height, bool fullScreen, - const NameValuePairList* miscParams) - { - mActive = true; - mVisible = true; - mClosed = false; - mHwGamma = false; - mWidth = width; - mHeight = height; - mFSAA = 1; - - if( miscParams ) - { - NameValuePairList::const_iterator end = miscParams->end(); - - auto opt = miscParams->find( "externalWindowHandle" ); - if( opt != end ) - mWindowHandle = StringConverter::parseSizeT( opt->second ); - - opt = miscParams->find( "vsync" ); - if( opt != end ) - mVSync = StringConverter::parseBool( opt->second ); - opt = miscParams->find( "vsyncInterval" ); - if( opt != end ) - mVSyncInterval = StringConverter::parseUnsignedInt( opt->second ); - opt = miscParams->find( "FSAA" ); - if( opt != end ) - mFSAA = StringConverter::parseUnsignedInt(opt->second); - opt = miscParams->find( "gamma" ); - if( opt != end ) - mHwGamma = StringConverter::parseBool( opt->second ); - } - - OgreAssert( mWindowHandle, "externalWindowHandle required" ); - createSurface(mWindowHandle); - - auto texMgr = TextureManager::getSingletonPtr(); - mTexture = new VulkanTextureGpuWindow("RenderWindow", TEX_TYPE_2D, texMgr, this);; - mTexture->setFormat(chooseSurfaceFormat(mHwGamma)); - mTexture->setHardwareGammaEnabled(mHwGamma); - mTexture->setFSAA(mFSAA, ""); - - mDepthTexture = new VulkanTextureGpu(texMgr, "RenderWindow DepthBuffer", 0, "", true, 0); - mDepthTexture->setFormat(PF_DEPTH32); - mDepthTexture->setFSAA(mFSAA, ""); -#if 0 - mStencilBuffer = 0; - if( PixelFormatGpuUtils::isStencil( mDepthBuffer->getPixelFormat() ) ) - mStencilBuffer = mDepthBuffer; -#endif - - mRenderPassDescriptor.reset(new VulkanRenderPassDescriptor(&mDevice->mGraphicsQueue, mDevice->mRenderSystem)); - createSwapchain(); - } - //------------------------------------------------------------------------- - VkSemaphore VulkanWindow::getImageAcquiredSemaphore( void ) - { - OGRE_ASSERT_LOW( mSwapchainStatus != SwapchainReleased ); - // It's weird that mSwapchainStatus would be in SwapchainPendingSwap here, - // however it's not invalid and won't result in race conditions (e.g. swapBuffers was called, - // then more work was added, but commitAndNextCommandBuffer hasn't yet been called). - // - // We assert because it may signify that something weird is going on: if user called - // swapBuffers(), then he may expect to present everything that has been rendered - // up until now, without including what came after the swapBuffers call. - // TODO OGRE_ASSERT_MEDIUM( mSwapchainStatus != SwapchainPendingSwap ); - - VkSemaphore retVal = 0; - if( mSwapchainStatus == SwapchainAcquired ) - { - mSwapchainStatus = SwapchainUsedInRendering; - retVal = mImageReadySemaphores[mCurrentSemaphoreIndex]; - } - return retVal; - } - - VkSemaphore VulkanWindow::getRenderFinishedSemaphore() const - { - return mRenderFinishedSemaphores[mCurrentSemaphoreIndex]; - } - - //------------------------------------------------------------------------- - void VulkanWindow::setVSync( bool vSync, uint32 vSyncInterval ) - { - // mVSyncInterval is ignored at least for now - // (we'd need VK_GOOGLE_display_timing or VK_MESA_present_period) - mVSyncInterval = vSyncInterval & 0x7FFFFFFFu; - mLowestLatencyVSync = vSyncInterval & 0x80000000u; - - if( mVSync == vSync ) - return; - - mVSync = vSync; - - destroySwapchain(); - createSwapchain(); - } - //------------------------------------------------------------------------- - void VulkanWindow::swapBuffers( void ) - { - mSwapchainStatus = SwapchainUsedInRendering; - if( mSwapchainStatus == SwapchainAcquired || mSwapchainStatus == SwapchainPendingSwap ) - { - // Ogre never rendered to this window. There's nothing to present. - // Pass the currently acquired swapchain onto the next frame. - // Or alternatively, swapBuffers was called twice in a row - return; - } - - OGRE_ASSERT_LOW( mSwapchainStatus == SwapchainUsedInRendering ); - - mDevice->mGraphicsQueue.mWindowsPendingSwap.push_back( this ); - mSwapchainStatus = SwapchainPendingSwap; - - //endRenderPassDescriptor(); - mDevice->commitAndNextCommandBuffer( SubmissionType::EndFrameAndSwap ); - } - //------------------------------------------------------------------------- - void VulkanWindow::_swapBuffers() - { - OGRE_ASSERT_LOW( mSwapchainStatus == SwapchainPendingSwap ); - - auto queueFinishSemaphore = getRenderFinishedSemaphore(); - const uint32 currentImageIdx = mTexture->getCurrentImageIdx(); - - TODO_handleSeparatePresentQueue; - /* - if (demo->separate_present_queue) { - // If we are using separate queues, change image ownership to the - // present queue before presenting, waiting for the draw complete - // semaphore and signalling the ownership released semaphore when finished - VkFence nullFence = VK_NULL_HANDLE; - pipe_stage_flags = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; - submit_info.waitSemaphoreCount = 1; - submit_info.pWaitSemaphores = &demo->draw_complete_semaphores[demo->frame_index]; - submit_info.commandBufferCount = 1; - submit_info.pCommandBuffers = - &demo->swapchain_image_resources[demo->current_buffer].graphics_to_present_cmd; - submit_info.signalSemaphoreCount = 1; - submit_info.pSignalSemaphores = &demo->image_ownership_semaphores[demo->frame_index]; - err = vkQueueSubmit(demo->present_queue, 1, &submit_info, nullFence); - assert(!err); - }*/ - - VkPresentInfoKHR present = {VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; - present.swapchainCount = 1u; - present.pSwapchains = &mSwapchain; - present.pImageIndices = ¤tImageIdx; - present.waitSemaphoreCount = 1u; - present.pWaitSemaphores = &queueFinishSemaphore; - - VkResult result = vkQueuePresentKHR( mDevice->mPresentQueue, &present ); - - if( result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR && result != VK_ERROR_OUT_OF_DATE_KHR ) - { - LogManager::getSingleton().logMessage( - "[VulkanWindow::swapBuffers] vkQueuePresentKHR: error presenting VkResult = " + - vkResultToString( result ) ); - } - - if( result == VK_SUBOPTIMAL_KHR || result == VK_ERROR_OUT_OF_DATE_KHR ) - LogManager::getSingleton().logMessage("[VulkanWindow::swapBuffers] swapchain suboptimal or out fo date"); - - mSwapchainStatus = SwapchainReleased; - } -} // namespace Ogre diff --git a/RenderSystems/Vulkan/src/vk_mem_alloc.h b/RenderSystems/Vulkan/src/vk_mem_alloc.h deleted file mode 100644 index b0b319d17ac..00000000000 --- a/RenderSystems/Vulkan/src/vk_mem_alloc.h +++ /dev/null @@ -1,19670 +0,0 @@ -// -// Copyright (c) 2017-2022 Advanced Micro Devices, Inc. All rights reserved. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -#ifndef AMD_VULKAN_MEMORY_ALLOCATOR_H -#define AMD_VULKAN_MEMORY_ALLOCATOR_H - -/** \mainpage Vulkan Memory Allocator - -Version 3.1.0-development - -Copyright (c) 2017-2022 Advanced Micro Devices, Inc. All rights reserved. \n -License: MIT - -API documentation divided into groups: [Modules](modules.html) - -\section main_table_of_contents Table of contents - -- User guide - - \subpage quick_start - - [Project setup](@ref quick_start_project_setup) - - [Initialization](@ref quick_start_initialization) - - [Resource allocation](@ref quick_start_resource_allocation) - - \subpage choosing_memory_type - - [Usage](@ref choosing_memory_type_usage) - - [Required and preferred flags](@ref choosing_memory_type_required_preferred_flags) - - [Explicit memory types](@ref choosing_memory_type_explicit_memory_types) - - [Custom memory pools](@ref choosing_memory_type_custom_memory_pools) - - [Dedicated allocations](@ref choosing_memory_type_dedicated_allocations) - - \subpage memory_mapping - - [Mapping functions](@ref memory_mapping_mapping_functions) - - [Persistently mapped memory](@ref memory_mapping_persistently_mapped_memory) - - [Cache flush and invalidate](@ref memory_mapping_cache_control) - - \subpage staying_within_budget - - [Querying for budget](@ref staying_within_budget_querying_for_budget) - - [Controlling memory usage](@ref staying_within_budget_controlling_memory_usage) - - \subpage resource_aliasing - - \subpage custom_memory_pools - - [Choosing memory type index](@ref custom_memory_pools_MemTypeIndex) - - [Linear allocation algorithm](@ref linear_algorithm) - - [Free-at-once](@ref linear_algorithm_free_at_once) - - [Stack](@ref linear_algorithm_stack) - - [Double stack](@ref linear_algorithm_double_stack) - - [Ring buffer](@ref linear_algorithm_ring_buffer) - - \subpage defragmentation - - \subpage statistics - - [Numeric statistics](@ref statistics_numeric_statistics) - - [JSON dump](@ref statistics_json_dump) - - \subpage allocation_annotation - - [Allocation user data](@ref allocation_user_data) - - [Allocation names](@ref allocation_names) - - \subpage virtual_allocator - - \subpage debugging_memory_usage - - [Memory initialization](@ref debugging_memory_usage_initialization) - - [Margins](@ref debugging_memory_usage_margins) - - [Corruption detection](@ref debugging_memory_usage_corruption_detection) - - \subpage opengl_interop -- \subpage usage_patterns - - [GPU-only resource](@ref usage_patterns_gpu_only) - - [Staging copy for upload](@ref usage_patterns_staging_copy_upload) - - [Readback](@ref usage_patterns_readback) - - [Advanced data uploading](@ref usage_patterns_advanced_data_uploading) - - [Other use cases](@ref usage_patterns_other_use_cases) -- \subpage configuration - - [Pointers to Vulkan functions](@ref config_Vulkan_functions) - - [Custom host memory allocator](@ref custom_memory_allocator) - - [Device memory allocation callbacks](@ref allocation_callbacks) - - [Device heap memory limit](@ref heap_memory_limit) -- Extension support - - \subpage vk_khr_dedicated_allocation - - \subpage enabling_buffer_device_address - - \subpage vk_ext_memory_priority - - \subpage vk_amd_device_coherent_memory -- \subpage general_considerations - - [Thread safety](@ref general_considerations_thread_safety) - - [Versioning and compatibility](@ref general_considerations_versioning_and_compatibility) - - [Validation layer warnings](@ref general_considerations_validation_layer_warnings) - - [Allocation algorithm](@ref general_considerations_allocation_algorithm) - - [Features not supported](@ref general_considerations_features_not_supported) - -\section main_see_also See also - -- [**Product page on GPUOpen**](https://gpuopen.com/gaming-product/vulkan-memory-allocator/) -- [**Source repository on GitHub**](https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator) - -\defgroup group_init Library initialization - -\brief API elements related to the initialization and management of the entire library, especially #VmaAllocator object. - -\defgroup group_alloc Memory allocation - -\brief API elements related to the allocation, deallocation, and management of Vulkan memory, buffers, images. -Most basic ones being: vmaCreateBuffer(), vmaCreateImage(). - -\defgroup group_virtual Virtual allocator - -\brief API elements related to the mechanism of \ref virtual_allocator - using the core allocation algorithm -for user-defined purpose without allocating any real GPU memory. - -\defgroup group_stats Statistics - -\brief API elements that query current status of the allocator, from memory usage, budget, to full dump of the internal state in JSON format. -See documentation chapter: \ref statistics. -*/ - - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef VULKAN_H_ - #include -#endif - -#if !defined(VMA_VULKAN_VERSION) - #if defined(VK_VERSION_1_3) - #define VMA_VULKAN_VERSION 1003000 - #elif defined(VK_VERSION_1_2) - #define VMA_VULKAN_VERSION 1002000 - #elif defined(VK_VERSION_1_1) - #define VMA_VULKAN_VERSION 1001000 - #else - #define VMA_VULKAN_VERSION 1000000 - #endif -#endif - -#if defined(__ANDROID__) && defined(VK_NO_PROTOTYPES) && VMA_STATIC_VULKAN_FUNCTIONS - extern PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr; - extern PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr; - extern PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties; - extern PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties; - extern PFN_vkAllocateMemory vkAllocateMemory; - extern PFN_vkFreeMemory vkFreeMemory; - extern PFN_vkMapMemory vkMapMemory; - extern PFN_vkUnmapMemory vkUnmapMemory; - extern PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges; - extern PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges; - extern PFN_vkBindBufferMemory vkBindBufferMemory; - extern PFN_vkBindImageMemory vkBindImageMemory; - extern PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements; - extern PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements; - extern PFN_vkCreateBuffer vkCreateBuffer; - extern PFN_vkDestroyBuffer vkDestroyBuffer; - extern PFN_vkCreateImage vkCreateImage; - extern PFN_vkDestroyImage vkDestroyImage; - extern PFN_vkCmdCopyBuffer vkCmdCopyBuffer; - #if VMA_VULKAN_VERSION >= 1001000 - extern PFN_vkGetBufferMemoryRequirements2 vkGetBufferMemoryRequirements2; - extern PFN_vkGetImageMemoryRequirements2 vkGetImageMemoryRequirements2; - extern PFN_vkBindBufferMemory2 vkBindBufferMemory2; - extern PFN_vkBindImageMemory2 vkBindImageMemory2; - extern PFN_vkGetPhysicalDeviceMemoryProperties2 vkGetPhysicalDeviceMemoryProperties2; - #endif // #if VMA_VULKAN_VERSION >= 1001000 -#endif // #if defined(__ANDROID__) && VMA_STATIC_VULKAN_FUNCTIONS && VK_NO_PROTOTYPES - -#if !defined(VMA_DEDICATED_ALLOCATION) - #if VK_KHR_get_memory_requirements2 && VK_KHR_dedicated_allocation - #define VMA_DEDICATED_ALLOCATION 1 - #else - #define VMA_DEDICATED_ALLOCATION 0 - #endif -#endif - -#if !defined(VMA_BIND_MEMORY2) - #if VK_KHR_bind_memory2 - #define VMA_BIND_MEMORY2 1 - #else - #define VMA_BIND_MEMORY2 0 - #endif -#endif - -#if !defined(VMA_MEMORY_BUDGET) - #if VK_EXT_memory_budget && (VK_KHR_get_physical_device_properties2 || VMA_VULKAN_VERSION >= 1001000) - #define VMA_MEMORY_BUDGET 1 - #else - #define VMA_MEMORY_BUDGET 0 - #endif -#endif - -// Defined to 1 when VK_KHR_buffer_device_address device extension or equivalent core Vulkan 1.2 feature is defined in its headers. -#if !defined(VMA_BUFFER_DEVICE_ADDRESS) - #if VK_KHR_buffer_device_address || VMA_VULKAN_VERSION >= 1002000 - #define VMA_BUFFER_DEVICE_ADDRESS 1 - #else - #define VMA_BUFFER_DEVICE_ADDRESS 0 - #endif -#endif - -// Defined to 1 when VK_EXT_memory_priority device extension is defined in Vulkan headers. -#if !defined(VMA_MEMORY_PRIORITY) - #if VK_EXT_memory_priority - #define VMA_MEMORY_PRIORITY 1 - #else - #define VMA_MEMORY_PRIORITY 0 - #endif -#endif - -// Defined to 1 when VK_KHR_external_memory device extension is defined in Vulkan headers. -#if !defined(VMA_EXTERNAL_MEMORY) - #if VK_KHR_external_memory - #define VMA_EXTERNAL_MEMORY 1 - #else - #define VMA_EXTERNAL_MEMORY 0 - #endif -#endif - -// Define these macros to decorate all public functions with additional code, -// before and after returned type, appropriately. This may be useful for -// exporting the functions when compiling VMA as a separate library. Example: -// #define VMA_CALL_PRE __declspec(dllexport) -// #define VMA_CALL_POST __cdecl -#ifndef VMA_CALL_PRE - #define VMA_CALL_PRE -#endif -#ifndef VMA_CALL_POST - #define VMA_CALL_POST -#endif - -// Define this macro to decorate pointers with an attribute specifying the -// length of the array they point to if they are not null. -// -// The length may be one of -// - The name of another parameter in the argument list where the pointer is declared -// - The name of another member in the struct where the pointer is declared -// - The name of a member of a struct type, meaning the value of that member in -// the context of the call. For example -// VMA_LEN_IF_NOT_NULL("VkPhysicalDeviceMemoryProperties::memoryHeapCount"), -// this means the number of memory heaps available in the device associated -// with the VmaAllocator being dealt with. -#ifndef VMA_LEN_IF_NOT_NULL - #define VMA_LEN_IF_NOT_NULL(len) -#endif - -// The VMA_NULLABLE macro is defined to be _Nullable when compiling with Clang. -// see: https://clang.llvm.org/docs/AttributeReference.html#nullable -#ifndef VMA_NULLABLE - #ifdef __clang__ - #define VMA_NULLABLE _Nullable - #else - #define VMA_NULLABLE - #endif -#endif - -// The VMA_NOT_NULL macro is defined to be _Nonnull when compiling with Clang. -// see: https://clang.llvm.org/docs/AttributeReference.html#nonnull -#ifndef VMA_NOT_NULL - #ifdef __clang__ - #define VMA_NOT_NULL _Nonnull - #else - #define VMA_NOT_NULL - #endif -#endif - -// If non-dispatchable handles are represented as pointers then we can give -// then nullability annotations -#ifndef VMA_NOT_NULL_NON_DISPATCHABLE - #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__) ) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__) - #define VMA_NOT_NULL_NON_DISPATCHABLE VMA_NOT_NULL - #else - #define VMA_NOT_NULL_NON_DISPATCHABLE - #endif -#endif - -#ifndef VMA_NULLABLE_NON_DISPATCHABLE - #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__) ) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__) - #define VMA_NULLABLE_NON_DISPATCHABLE VMA_NULLABLE - #else - #define VMA_NULLABLE_NON_DISPATCHABLE - #endif -#endif - -#ifndef VMA_STATS_STRING_ENABLED - #define VMA_STATS_STRING_ENABLED 1 -#endif - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -// -// INTERFACE -// -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -// Sections for managing code placement in file, only for development purposes e.g. for convenient folding inside an IDE. -#ifndef _VMA_ENUM_DECLARATIONS - -/** -\addtogroup group_init -@{ -*/ - -/// Flags for created #VmaAllocator. -typedef enum VmaAllocatorCreateFlagBits -{ - /** \brief Allocator and all objects created from it will not be synchronized internally, so you must guarantee they are used from only one thread at a time or synchronized externally by you. - - Using this flag may increase performance because internal mutexes are not used. - */ - VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT = 0x00000001, - /** \brief Enables usage of VK_KHR_dedicated_allocation extension. - - The flag works only if VmaAllocatorCreateInfo::vulkanApiVersion `== VK_API_VERSION_1_0`. - When it is `VK_API_VERSION_1_1`, the flag is ignored because the extension has been promoted to Vulkan 1.1. - - Using this extension will automatically allocate dedicated blocks of memory for - some buffers and images instead of suballocating place for them out of bigger - memory blocks (as if you explicitly used #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT - flag) when it is recommended by the driver. It may improve performance on some - GPUs. - - You may set this flag only if you found out that following device extensions are - supported, you enabled them while creating Vulkan device passed as - VmaAllocatorCreateInfo::device, and you want them to be used internally by this - library: - - - VK_KHR_get_memory_requirements2 (device extension) - - VK_KHR_dedicated_allocation (device extension) - - When this flag is set, you can experience following warnings reported by Vulkan - validation layer. You can ignore them. - - > vkBindBufferMemory(): Binding memory to buffer 0x2d but vkGetBufferMemoryRequirements() has not been called on that buffer. - */ - VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT = 0x00000002, - /** - Enables usage of VK_KHR_bind_memory2 extension. - - The flag works only if VmaAllocatorCreateInfo::vulkanApiVersion `== VK_API_VERSION_1_0`. - When it is `VK_API_VERSION_1_1`, the flag is ignored because the extension has been promoted to Vulkan 1.1. - - You may set this flag only if you found out that this device extension is supported, - you enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device, - and you want it to be used internally by this library. - - The extension provides functions `vkBindBufferMemory2KHR` and `vkBindImageMemory2KHR`, - which allow to pass a chain of `pNext` structures while binding. - This flag is required if you use `pNext` parameter in vmaBindBufferMemory2() or vmaBindImageMemory2(). - */ - VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT = 0x00000004, - /** - Enables usage of VK_EXT_memory_budget extension. - - You may set this flag only if you found out that this device extension is supported, - you enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device, - and you want it to be used internally by this library, along with another instance extension - VK_KHR_get_physical_device_properties2, which is required by it (or Vulkan 1.1, where this extension is promoted). - - The extension provides query for current memory usage and budget, which will probably - be more accurate than an estimation used by the library otherwise. - */ - VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT = 0x00000008, - /** - Enables usage of VK_AMD_device_coherent_memory extension. - - You may set this flag only if you: - - - found out that this device extension is supported and enabled it while creating Vulkan device passed as VmaAllocatorCreateInfo::device, - - checked that `VkPhysicalDeviceCoherentMemoryFeaturesAMD::deviceCoherentMemory` is true and set it while creating the Vulkan device, - - want it to be used internally by this library. - - The extension and accompanying device feature provide access to memory types with - `VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD` and `VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD` flags. - They are useful mostly for writing breadcrumb markers - a common method for debugging GPU crash/hang/TDR. - - When the extension is not enabled, such memory types are still enumerated, but their usage is illegal. - To protect from this error, if you don't create the allocator with this flag, it will refuse to allocate any memory or create a custom pool in such memory type, - returning `VK_ERROR_FEATURE_NOT_PRESENT`. - */ - VMA_ALLOCATOR_CREATE_AMD_DEVICE_COHERENT_MEMORY_BIT = 0x00000010, - /** - Enables usage of "buffer device address" feature, which allows you to use function - `vkGetBufferDeviceAddress*` to get raw GPU pointer to a buffer and pass it for usage inside a shader. - - You may set this flag only if you: - - 1. (For Vulkan version < 1.2) Found as available and enabled device extension - VK_KHR_buffer_device_address. - This extension is promoted to core Vulkan 1.2. - 2. Found as available and enabled device feature `VkPhysicalDeviceBufferDeviceAddressFeatures::bufferDeviceAddress`. - - When this flag is set, you can create buffers with `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT` using VMA. - The library automatically adds `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT` to - allocated memory blocks wherever it might be needed. - - For more information, see documentation chapter \ref enabling_buffer_device_address. - */ - VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT = 0x00000020, - /** - Enables usage of VK_EXT_memory_priority extension in the library. - - You may set this flag only if you found available and enabled this device extension, - along with `VkPhysicalDeviceMemoryPriorityFeaturesEXT::memoryPriority == VK_TRUE`, - while creating Vulkan device passed as VmaAllocatorCreateInfo::device. - - When this flag is used, VmaAllocationCreateInfo::priority and VmaPoolCreateInfo::priority - are used to set priorities of allocated Vulkan memory. Without it, these variables are ignored. - - A priority must be a floating-point value between 0 and 1, indicating the priority of the allocation relative to other memory allocations. - Larger values are higher priority. The granularity of the priorities is implementation-dependent. - It is automatically passed to every call to `vkAllocateMemory` done by the library using structure `VkMemoryPriorityAllocateInfoEXT`. - The value to be used for default priority is 0.5. - For more details, see the documentation of the VK_EXT_memory_priority extension. - */ - VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT = 0x00000040, - - VMA_ALLOCATOR_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VmaAllocatorCreateFlagBits; -/// See #VmaAllocatorCreateFlagBits. -typedef VkFlags VmaAllocatorCreateFlags; - -/** @} */ - -/** -\addtogroup group_alloc -@{ -*/ - -/// \brief Intended usage of the allocated memory. -typedef enum VmaMemoryUsage -{ - /** No intended memory usage specified. - Use other members of VmaAllocationCreateInfo to specify your requirements. - */ - VMA_MEMORY_USAGE_UNKNOWN = 0, - /** - \deprecated Obsolete, preserved for backward compatibility. - Prefers `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`. - */ - VMA_MEMORY_USAGE_GPU_ONLY = 1, - /** - \deprecated Obsolete, preserved for backward compatibility. - Guarantees `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` and `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT`. - */ - VMA_MEMORY_USAGE_CPU_ONLY = 2, - /** - \deprecated Obsolete, preserved for backward compatibility. - Guarantees `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT`, prefers `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`. - */ - VMA_MEMORY_USAGE_CPU_TO_GPU = 3, - /** - \deprecated Obsolete, preserved for backward compatibility. - Guarantees `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT`, prefers `VK_MEMORY_PROPERTY_HOST_CACHED_BIT`. - */ - VMA_MEMORY_USAGE_GPU_TO_CPU = 4, - /** - \deprecated Obsolete, preserved for backward compatibility. - Prefers not `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`. - */ - VMA_MEMORY_USAGE_CPU_COPY = 5, - /** - Lazily allocated GPU memory having `VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT`. - Exists mostly on mobile platforms. Using it on desktop PC or other GPUs with no such memory type present will fail the allocation. - - Usage: Memory for transient attachment images (color attachments, depth attachments etc.), created with `VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT`. - - Allocations with this usage are always created as dedicated - it implies #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT. - */ - VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED = 6, - /** - Selects best memory type automatically. - This flag is recommended for most common use cases. - - When using this flag, if you want to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT), - you must pass one of the flags: #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT - in VmaAllocationCreateInfo::flags. - - It can be used only with functions that let the library know `VkBufferCreateInfo` or `VkImageCreateInfo`, e.g. - vmaCreateBuffer(), vmaCreateImage(), vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo() - and not with generic memory allocation functions. - */ - VMA_MEMORY_USAGE_AUTO = 7, - /** - Selects best memory type automatically with preference for GPU (device) memory. - - When using this flag, if you want to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT), - you must pass one of the flags: #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT - in VmaAllocationCreateInfo::flags. - - It can be used only with functions that let the library know `VkBufferCreateInfo` or `VkImageCreateInfo`, e.g. - vmaCreateBuffer(), vmaCreateImage(), vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo() - and not with generic memory allocation functions. - */ - VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE = 8, - /** - Selects best memory type automatically with preference for CPU (host) memory. - - When using this flag, if you want to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT), - you must pass one of the flags: #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT - in VmaAllocationCreateInfo::flags. - - It can be used only with functions that let the library know `VkBufferCreateInfo` or `VkImageCreateInfo`, e.g. - vmaCreateBuffer(), vmaCreateImage(), vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo() - and not with generic memory allocation functions. - */ - VMA_MEMORY_USAGE_AUTO_PREFER_HOST = 9, - - VMA_MEMORY_USAGE_MAX_ENUM = 0x7FFFFFFF -} VmaMemoryUsage; - -/// Flags to be passed as VmaAllocationCreateInfo::flags. -typedef enum VmaAllocationCreateFlagBits -{ - /** \brief Set this flag if the allocation should have its own memory block. - - Use it for special, big resources, like fullscreen images used as attachments. - */ - VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT = 0x00000001, - - /** \brief Set this flag to only try to allocate from existing `VkDeviceMemory` blocks and never create new such block. - - If new allocation cannot be placed in any of the existing blocks, allocation - fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY` error. - - You should not use #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT and - #VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT at the same time. It makes no sense. - */ - VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT = 0x00000002, - /** \brief Set this flag to use a memory that will be persistently mapped and retrieve pointer to it. - - Pointer to mapped memory will be returned through VmaAllocationInfo::pMappedData. - - It is valid to use this flag for allocation made from memory type that is not - `HOST_VISIBLE`. This flag is then ignored and memory is not mapped. This is - useful if you need an allocation that is efficient to use on GPU - (`DEVICE_LOCAL`) and still want to map it directly if possible on platforms that - support it (e.g. Intel GPU). - */ - VMA_ALLOCATION_CREATE_MAPPED_BIT = 0x00000004, - /** \deprecated Preserved for backward compatibility. Consider using vmaSetAllocationName() instead. - - Set this flag to treat VmaAllocationCreateInfo::pUserData as pointer to a - null-terminated string. Instead of copying pointer value, a local copy of the - string is made and stored in allocation's `pName`. The string is automatically - freed together with the allocation. It is also used in vmaBuildStatsString(). - */ - VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT = 0x00000020, - /** Allocation will be created from upper stack in a double stack pool. - - This flag is only allowed for custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT flag. - */ - VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT = 0x00000040, - /** Create both buffer/image and allocation, but don't bind them together. - It is useful when you want to bind yourself to do some more advanced binding, e.g. using some extensions. - The flag is meaningful only with functions that bind by default: vmaCreateBuffer(), vmaCreateImage(). - Otherwise it is ignored. - - If you want to make sure the new buffer/image is not tied to the new memory allocation - through `VkMemoryDedicatedAllocateInfoKHR` structure in case the allocation ends up in its own memory block, - use also flag #VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT. - */ - VMA_ALLOCATION_CREATE_DONT_BIND_BIT = 0x00000080, - /** Create allocation only if additional device memory required for it, if any, won't exceed - memory budget. Otherwise return `VK_ERROR_OUT_OF_DEVICE_MEMORY`. - */ - VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT = 0x00000100, - /** \brief Set this flag if the allocated memory will have aliasing resources. - - Usage of this flag prevents supplying `VkMemoryDedicatedAllocateInfoKHR` when #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT is specified. - Otherwise created dedicated memory will not be suitable for aliasing resources, resulting in Vulkan Validation Layer errors. - */ - VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT = 0x00000200, - /** - Requests possibility to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT). - - - If you use #VMA_MEMORY_USAGE_AUTO or other `VMA_MEMORY_USAGE_AUTO*` value, - you must use this flag to be able to map the allocation. Otherwise, mapping is incorrect. - - If you use other value of #VmaMemoryUsage, this flag is ignored and mapping is always possible in memory types that are `HOST_VISIBLE`. - This includes allocations created in \ref custom_memory_pools. - - Declares that mapped memory will only be written sequentially, e.g. using `memcpy()` or a loop writing number-by-number, - never read or accessed randomly, so a memory type can be selected that is uncached and write-combined. - - \warning Violating this declaration may work correctly, but will likely be very slow. - Watch out for implicit reads introduced by doing e.g. `pMappedData[i] += x;` - Better prepare your data in a local variable and `memcpy()` it to the mapped pointer all at once. - */ - VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT = 0x00000400, - /** - Requests possibility to map the allocation (using vmaMapMemory() or #VMA_ALLOCATION_CREATE_MAPPED_BIT). - - - If you use #VMA_MEMORY_USAGE_AUTO or other `VMA_MEMORY_USAGE_AUTO*` value, - you must use this flag to be able to map the allocation. Otherwise, mapping is incorrect. - - If you use other value of #VmaMemoryUsage, this flag is ignored and mapping is always possible in memory types that are `HOST_VISIBLE`. - This includes allocations created in \ref custom_memory_pools. - - Declares that mapped memory can be read, written, and accessed in random order, - so a `HOST_CACHED` memory type is required. - */ - VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT = 0x00000800, - /** - Together with #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT, - it says that despite request for host access, a not-`HOST_VISIBLE` memory type can be selected - if it may improve performance. - - By using this flag, you declare that you will check if the allocation ended up in a `HOST_VISIBLE` memory type - (e.g. using vmaGetAllocationMemoryProperties()) and if not, you will create some "staging" buffer and - issue an explicit transfer to write/read your data. - To prepare for this possibility, don't forget to add appropriate flags like - `VK_BUFFER_USAGE_TRANSFER_DST_BIT`, `VK_BUFFER_USAGE_TRANSFER_SRC_BIT` to the parameters of created buffer or image. - */ - VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT = 0x00001000, - /** Allocation strategy that chooses smallest possible free range for the allocation - to minimize memory usage and fragmentation, possibly at the expense of allocation time. - */ - VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT = 0x00010000, - /** Allocation strategy that chooses first suitable free range for the allocation - - not necessarily in terms of the smallest offset but the one that is easiest and fastest to find - to minimize allocation time, possibly at the expense of allocation quality. - */ - VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT = 0x00020000, - /** Allocation strategy that chooses always the lowest offset in available space. - This is not the most efficient strategy but achieves highly packed data. - Used internally by defragmentation, not recommended in typical usage. - */ - VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT = 0x00040000, - /** Alias to #VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT. - */ - VMA_ALLOCATION_CREATE_STRATEGY_BEST_FIT_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT, - /** Alias to #VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT. - */ - VMA_ALLOCATION_CREATE_STRATEGY_FIRST_FIT_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT, - /** A bit mask to extract only `STRATEGY` bits from entire set of flags. - */ - VMA_ALLOCATION_CREATE_STRATEGY_MASK = - VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT | - VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT | - VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT, - - VMA_ALLOCATION_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VmaAllocationCreateFlagBits; -/// See #VmaAllocationCreateFlagBits. -typedef VkFlags VmaAllocationCreateFlags; - -/// Flags to be passed as VmaPoolCreateInfo::flags. -typedef enum VmaPoolCreateFlagBits -{ - /** \brief Use this flag if you always allocate only buffers and linear images or only optimal images out of this pool and so Buffer-Image Granularity can be ignored. - - This is an optional optimization flag. - - If you always allocate using vmaCreateBuffer(), vmaCreateImage(), - vmaAllocateMemoryForBuffer(), then you don't need to use it because allocator - knows exact type of your allocations so it can handle Buffer-Image Granularity - in the optimal way. - - If you also allocate using vmaAllocateMemoryForImage() or vmaAllocateMemory(), - exact type of such allocations is not known, so allocator must be conservative - in handling Buffer-Image Granularity, which can lead to suboptimal allocation - (wasted memory). In that case, if you can make sure you always allocate only - buffers and linear images or only optimal images out of this pool, use this flag - to make allocator disregard Buffer-Image Granularity and so make allocations - faster and more optimal. - */ - VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT = 0x00000002, - - /** \brief Enables alternative, linear allocation algorithm in this pool. - - Specify this flag to enable linear allocation algorithm, which always creates - new allocations after last one and doesn't reuse space from allocations freed in - between. It trades memory consumption for simplified algorithm and data - structure, which has better performance and uses less memory for metadata. - - By using this flag, you can achieve behavior of free-at-once, stack, - ring buffer, and double stack. - For details, see documentation chapter \ref linear_algorithm. - */ - VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT = 0x00000004, - - /** Bit mask to extract only `ALGORITHM` bits from entire set of flags. - */ - VMA_POOL_CREATE_ALGORITHM_MASK = - VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT, - - VMA_POOL_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VmaPoolCreateFlagBits; -/// Flags to be passed as VmaPoolCreateInfo::flags. See #VmaPoolCreateFlagBits. -typedef VkFlags VmaPoolCreateFlags; - -/// Flags to be passed as VmaDefragmentationInfo::flags. -typedef enum VmaDefragmentationFlagBits -{ - /* \brief Use simple but fast algorithm for defragmentation. - May not achieve best results but will require least time to compute and least allocations to copy. - */ - VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FAST_BIT = 0x1, - /* \brief Default defragmentation algorithm, applied also when no `ALGORITHM` flag is specified. - Offers a balance between defragmentation quality and the amount of allocations and bytes that need to be moved. - */ - VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT = 0x2, - /* \brief Perform full defragmentation of memory. - Can result in notably more time to compute and allocations to copy, but will achieve best memory packing. - */ - VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FULL_BIT = 0x4, - /** \brief Use the most roboust algorithm at the cost of time to compute and number of copies to make. - Only available when bufferImageGranularity is greater than 1, since it aims to reduce - alignment issues between different types of resources. - Otherwise falls back to same behavior as #VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FULL_BIT. - */ - VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT = 0x8, - - /// A bit mask to extract only `ALGORITHM` bits from entire set of flags. - VMA_DEFRAGMENTATION_FLAG_ALGORITHM_MASK = - VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FAST_BIT | - VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT | - VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FULL_BIT | - VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT, - - VMA_DEFRAGMENTATION_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VmaDefragmentationFlagBits; -/// See #VmaDefragmentationFlagBits. -typedef VkFlags VmaDefragmentationFlags; - -/// Operation performed on single defragmentation move. See structure #VmaDefragmentationMove. -typedef enum VmaDefragmentationMoveOperation -{ - /// Buffer/image has been recreated at `dstTmpAllocation`, data has been copied, old buffer/image has been destroyed. `srcAllocation` should be changed to point to the new place. This is the default value set by vmaBeginDefragmentationPass(). - VMA_DEFRAGMENTATION_MOVE_OPERATION_COPY = 0, - /// Set this value if you cannot move the allocation. New place reserved at `dstTmpAllocation` will be freed. `srcAllocation` will remain unchanged. - VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE = 1, - /// Set this value if you decide to abandon the allocation and you destroyed the buffer/image. New place reserved at `dstTmpAllocation` will be freed, along with `srcAllocation`, which will be destroyed. - VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY = 2, -} VmaDefragmentationMoveOperation; - -/** @} */ - -/** -\addtogroup group_virtual -@{ -*/ - -/// Flags to be passed as VmaVirtualBlockCreateInfo::flags. -typedef enum VmaVirtualBlockCreateFlagBits -{ - /** \brief Enables alternative, linear allocation algorithm in this virtual block. - - Specify this flag to enable linear allocation algorithm, which always creates - new allocations after last one and doesn't reuse space from allocations freed in - between. It trades memory consumption for simplified algorithm and data - structure, which has better performance and uses less memory for metadata. - - By using this flag, you can achieve behavior of free-at-once, stack, - ring buffer, and double stack. - For details, see documentation chapter \ref linear_algorithm. - */ - VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT = 0x00000001, - - /** \brief Bit mask to extract only `ALGORITHM` bits from entire set of flags. - */ - VMA_VIRTUAL_BLOCK_CREATE_ALGORITHM_MASK = - VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT, - - VMA_VIRTUAL_BLOCK_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VmaVirtualBlockCreateFlagBits; -/// Flags to be passed as VmaVirtualBlockCreateInfo::flags. See #VmaVirtualBlockCreateFlagBits. -typedef VkFlags VmaVirtualBlockCreateFlags; - -/// Flags to be passed as VmaVirtualAllocationCreateInfo::flags. -typedef enum VmaVirtualAllocationCreateFlagBits -{ - /** \brief Allocation will be created from upper stack in a double stack pool. - - This flag is only allowed for virtual blocks created with #VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT flag. - */ - VMA_VIRTUAL_ALLOCATION_CREATE_UPPER_ADDRESS_BIT = VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT, - /** \brief Allocation strategy that tries to minimize memory usage. - */ - VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT, - /** \brief Allocation strategy that tries to minimize allocation time. - */ - VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT, - /** Allocation strategy that chooses always the lowest offset in available space. - This is not the most efficient strategy but achieves highly packed data. - */ - VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT = VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT, - /** \brief A bit mask to extract only `STRATEGY` bits from entire set of flags. - - These strategy flags are binary compatible with equivalent flags in #VmaAllocationCreateFlagBits. - */ - VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MASK = VMA_ALLOCATION_CREATE_STRATEGY_MASK, - - VMA_VIRTUAL_ALLOCATION_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF -} VmaVirtualAllocationCreateFlagBits; -/// Flags to be passed as VmaVirtualAllocationCreateInfo::flags. See #VmaVirtualAllocationCreateFlagBits. -typedef VkFlags VmaVirtualAllocationCreateFlags; - -/** @} */ - -#endif // _VMA_ENUM_DECLARATIONS - -#ifndef _VMA_DATA_TYPES_DECLARATIONS - -/** -\addtogroup group_init -@{ */ - -/** \struct VmaAllocator -\brief Represents main object of this library initialized. - -Fill structure #VmaAllocatorCreateInfo and call function vmaCreateAllocator() to create it. -Call function vmaDestroyAllocator() to destroy it. - -It is recommended to create just one object of this type per `VkDevice` object, -right after Vulkan is initialized and keep it alive until before Vulkan device is destroyed. -*/ -VK_DEFINE_HANDLE(VmaAllocator) - -/** @} */ - -/** -\addtogroup group_alloc -@{ -*/ - -/** \struct VmaPool -\brief Represents custom memory pool - -Fill structure VmaPoolCreateInfo and call function vmaCreatePool() to create it. -Call function vmaDestroyPool() to destroy it. - -For more information see [Custom memory pools](@ref choosing_memory_type_custom_memory_pools). -*/ -VK_DEFINE_HANDLE(VmaPool) - -/** \struct VmaAllocation -\brief Represents single memory allocation. - -It may be either dedicated block of `VkDeviceMemory` or a specific region of a bigger block of this type -plus unique offset. - -There are multiple ways to create such object. -You need to fill structure VmaAllocationCreateInfo. -For more information see [Choosing memory type](@ref choosing_memory_type). - -Although the library provides convenience functions that create Vulkan buffer or image, -allocate memory for it and bind them together, -binding of the allocation to a buffer or an image is out of scope of the allocation itself. -Allocation object can exist without buffer/image bound, -binding can be done manually by the user, and destruction of it can be done -independently of destruction of the allocation. - -The object also remembers its size and some other information. -To retrieve this information, use function vmaGetAllocationInfo() and inspect -returned structure VmaAllocationInfo. -*/ -VK_DEFINE_HANDLE(VmaAllocation) - -/** \struct VmaDefragmentationContext -\brief An opaque object that represents started defragmentation process. - -Fill structure #VmaDefragmentationInfo and call function vmaBeginDefragmentation() to create it. -Call function vmaEndDefragmentation() to destroy it. -*/ -VK_DEFINE_HANDLE(VmaDefragmentationContext) - -/** @} */ - -/** -\addtogroup group_virtual -@{ -*/ - -/** \struct VmaVirtualAllocation -\brief Represents single memory allocation done inside VmaVirtualBlock. - -Use it as a unique identifier to virtual allocation within the single block. - -Use value `VK_NULL_HANDLE` to represent a null/invalid allocation. -*/ -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VmaVirtualAllocation); - -/** @} */ - -/** -\addtogroup group_virtual -@{ -*/ - -/** \struct VmaVirtualBlock -\brief Handle to a virtual block object that allows to use core allocation algorithm without allocating any real GPU memory. - -Fill in #VmaVirtualBlockCreateInfo structure and use vmaCreateVirtualBlock() to create it. Use vmaDestroyVirtualBlock() to destroy it. -For more information, see documentation chapter \ref virtual_allocator. - -This object is not thread-safe - should not be used from multiple threads simultaneously, must be synchronized externally. -*/ -VK_DEFINE_HANDLE(VmaVirtualBlock) - -/** @} */ - -/** -\addtogroup group_init -@{ -*/ - -/// Callback function called after successful vkAllocateMemory. -typedef void (VKAPI_PTR* PFN_vmaAllocateDeviceMemoryFunction)( - VmaAllocator VMA_NOT_NULL allocator, - uint32_t memoryType, - VkDeviceMemory VMA_NOT_NULL_NON_DISPATCHABLE memory, - VkDeviceSize size, - void* VMA_NULLABLE pUserData); - -/// Callback function called before vkFreeMemory. -typedef void (VKAPI_PTR* PFN_vmaFreeDeviceMemoryFunction)( - VmaAllocator VMA_NOT_NULL allocator, - uint32_t memoryType, - VkDeviceMemory VMA_NOT_NULL_NON_DISPATCHABLE memory, - VkDeviceSize size, - void* VMA_NULLABLE pUserData); - -/** \brief Set of callbacks that the library will call for `vkAllocateMemory` and `vkFreeMemory`. - -Provided for informative purpose, e.g. to gather statistics about number of -allocations or total amount of memory allocated in Vulkan. - -Used in VmaAllocatorCreateInfo::pDeviceMemoryCallbacks. -*/ -typedef struct VmaDeviceMemoryCallbacks -{ - /// Optional, can be null. - PFN_vmaAllocateDeviceMemoryFunction VMA_NULLABLE pfnAllocate; - /// Optional, can be null. - PFN_vmaFreeDeviceMemoryFunction VMA_NULLABLE pfnFree; - /// Optional, can be null. - void* VMA_NULLABLE pUserData; -} VmaDeviceMemoryCallbacks; - -/** \brief Pointers to some Vulkan functions - a subset used by the library. - -Used in VmaAllocatorCreateInfo::pVulkanFunctions. -*/ -typedef struct VmaVulkanFunctions -{ - /// Required when using VMA_DYNAMIC_VULKAN_FUNCTIONS. - PFN_vkGetInstanceProcAddr VMA_NULLABLE vkGetInstanceProcAddr; - /// Required when using VMA_DYNAMIC_VULKAN_FUNCTIONS. - PFN_vkGetDeviceProcAddr VMA_NULLABLE vkGetDeviceProcAddr; - PFN_vkGetPhysicalDeviceProperties VMA_NULLABLE vkGetPhysicalDeviceProperties; - PFN_vkGetPhysicalDeviceMemoryProperties VMA_NULLABLE vkGetPhysicalDeviceMemoryProperties; - PFN_vkAllocateMemory VMA_NULLABLE vkAllocateMemory; - PFN_vkFreeMemory VMA_NULLABLE vkFreeMemory; - PFN_vkMapMemory VMA_NULLABLE vkMapMemory; - PFN_vkUnmapMemory VMA_NULLABLE vkUnmapMemory; - PFN_vkFlushMappedMemoryRanges VMA_NULLABLE vkFlushMappedMemoryRanges; - PFN_vkInvalidateMappedMemoryRanges VMA_NULLABLE vkInvalidateMappedMemoryRanges; - PFN_vkBindBufferMemory VMA_NULLABLE vkBindBufferMemory; - PFN_vkBindImageMemory VMA_NULLABLE vkBindImageMemory; - PFN_vkGetBufferMemoryRequirements VMA_NULLABLE vkGetBufferMemoryRequirements; - PFN_vkGetImageMemoryRequirements VMA_NULLABLE vkGetImageMemoryRequirements; - PFN_vkCreateBuffer VMA_NULLABLE vkCreateBuffer; - PFN_vkDestroyBuffer VMA_NULLABLE vkDestroyBuffer; - PFN_vkCreateImage VMA_NULLABLE vkCreateImage; - PFN_vkDestroyImage VMA_NULLABLE vkDestroyImage; - PFN_vkCmdCopyBuffer VMA_NULLABLE vkCmdCopyBuffer; -#if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 - /// Fetch "vkGetBufferMemoryRequirements2" on Vulkan >= 1.1, fetch "vkGetBufferMemoryRequirements2KHR" when using VK_KHR_dedicated_allocation extension. - PFN_vkGetBufferMemoryRequirements2KHR VMA_NULLABLE vkGetBufferMemoryRequirements2KHR; - /// Fetch "vkGetImageMemoryRequirements2" on Vulkan >= 1.1, fetch "vkGetImageMemoryRequirements2KHR" when using VK_KHR_dedicated_allocation extension. - PFN_vkGetImageMemoryRequirements2KHR VMA_NULLABLE vkGetImageMemoryRequirements2KHR; -#endif -#if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000 - /// Fetch "vkBindBufferMemory2" on Vulkan >= 1.1, fetch "vkBindBufferMemory2KHR" when using VK_KHR_bind_memory2 extension. - PFN_vkBindBufferMemory2KHR VMA_NULLABLE vkBindBufferMemory2KHR; - /// Fetch "vkBindImageMemory2" on Vulkan >= 1.1, fetch "vkBindImageMemory2KHR" when using VK_KHR_bind_memory2 extension. - PFN_vkBindImageMemory2KHR VMA_NULLABLE vkBindImageMemory2KHR; -#endif -#if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000 - PFN_vkGetPhysicalDeviceMemoryProperties2KHR VMA_NULLABLE vkGetPhysicalDeviceMemoryProperties2KHR; -#endif -#if VMA_VULKAN_VERSION >= 1003000 - /// Fetch from "vkGetDeviceBufferMemoryRequirements" on Vulkan >= 1.3, but you can also fetch it from "vkGetDeviceBufferMemoryRequirementsKHR" if you enabled extension VK_KHR_maintenance4. - PFN_vkGetDeviceBufferMemoryRequirements VMA_NULLABLE vkGetDeviceBufferMemoryRequirements; - /// Fetch from "vkGetDeviceImageMemoryRequirements" on Vulkan >= 1.3, but you can also fetch it from "vkGetDeviceImageMemoryRequirementsKHR" if you enabled extension VK_KHR_maintenance4. - PFN_vkGetDeviceImageMemoryRequirements VMA_NULLABLE vkGetDeviceImageMemoryRequirements; -#endif -} VmaVulkanFunctions; - -/// Description of a Allocator to be created. -typedef struct VmaAllocatorCreateInfo -{ - /// Flags for created allocator. Use #VmaAllocatorCreateFlagBits enum. - VmaAllocatorCreateFlags flags; - /// Vulkan physical device. - /** It must be valid throughout whole lifetime of created allocator. */ - VkPhysicalDevice VMA_NOT_NULL physicalDevice; - /// Vulkan device. - /** It must be valid throughout whole lifetime of created allocator. */ - VkDevice VMA_NOT_NULL device; - /// Preferred size of a single `VkDeviceMemory` block to be allocated from large heaps > 1 GiB. Optional. - /** Set to 0 to use default, which is currently 256 MiB. */ - VkDeviceSize preferredLargeHeapBlockSize; - /// Custom CPU memory allocation callbacks. Optional. - /** Optional, can be null. When specified, will also be used for all CPU-side memory allocations. */ - const VkAllocationCallbacks* VMA_NULLABLE pAllocationCallbacks; - /// Informative callbacks for `vkAllocateMemory`, `vkFreeMemory`. Optional. - /** Optional, can be null. */ - const VmaDeviceMemoryCallbacks* VMA_NULLABLE pDeviceMemoryCallbacks; - /** \brief Either null or a pointer to an array of limits on maximum number of bytes that can be allocated out of particular Vulkan memory heap. - - If not NULL, it must be a pointer to an array of - `VkPhysicalDeviceMemoryProperties::memoryHeapCount` elements, defining limit on - maximum number of bytes that can be allocated out of particular Vulkan memory - heap. - - Any of the elements may be equal to `VK_WHOLE_SIZE`, which means no limit on that - heap. This is also the default in case of `pHeapSizeLimit` = NULL. - - If there is a limit defined for a heap: - - - If user tries to allocate more memory from that heap using this allocator, - the allocation fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY`. - - If the limit is smaller than heap size reported in `VkMemoryHeap::size`, the - value of this limit will be reported instead when using vmaGetMemoryProperties(). - - Warning! Using this feature may not be equivalent to installing a GPU with - smaller amount of memory, because graphics driver doesn't necessary fail new - allocations with `VK_ERROR_OUT_OF_DEVICE_MEMORY` result when memory capacity is - exceeded. It may return success and just silently migrate some device memory - blocks to system RAM. This driver behavior can also be controlled using - VK_AMD_memory_overallocation_behavior extension. - */ - const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL("VkPhysicalDeviceMemoryProperties::memoryHeapCount") pHeapSizeLimit; - - /** \brief Pointers to Vulkan functions. Can be null. - - For details see [Pointers to Vulkan functions](@ref config_Vulkan_functions). - */ - const VmaVulkanFunctions* VMA_NULLABLE pVulkanFunctions; - /** \brief Handle to Vulkan instance object. - - Starting from version 3.0.0 this member is no longer optional, it must be set! - */ - VkInstance VMA_NOT_NULL instance; - /** \brief Optional. The highest version of Vulkan that the application is designed to use. - - It must be a value in the format as created by macro `VK_MAKE_VERSION` or a constant like: `VK_API_VERSION_1_1`, `VK_API_VERSION_1_0`. - The patch version number specified is ignored. Only the major and minor versions are considered. - It must be less or equal (preferably equal) to value as passed to `vkCreateInstance` as `VkApplicationInfo::apiVersion`. - Only versions 1.0, 1.1, 1.2, 1.3 are supported by the current implementation. - Leaving it initialized to zero is equivalent to `VK_API_VERSION_1_0`. - */ - uint32_t vulkanApiVersion; -#if VMA_EXTERNAL_MEMORY - /** \brief Either null or a pointer to an array of external memory handle types for each Vulkan memory type. - - If not NULL, it must be a pointer to an array of `VkPhysicalDeviceMemoryProperties::memoryTypeCount` - elements, defining external memory handle types of particular Vulkan memory type, - to be passed using `VkExportMemoryAllocateInfoKHR`. - - Any of the elements may be equal to 0, which means not to use `VkExportMemoryAllocateInfoKHR` on this memory type. - This is also the default in case of `pTypeExternalMemoryHandleTypes` = NULL. - */ - const VkExternalMemoryHandleTypeFlagsKHR* VMA_NULLABLE VMA_LEN_IF_NOT_NULL("VkPhysicalDeviceMemoryProperties::memoryTypeCount") pTypeExternalMemoryHandleTypes; -#endif // #if VMA_EXTERNAL_MEMORY -} VmaAllocatorCreateInfo; - -/// Information about existing #VmaAllocator object. -typedef struct VmaAllocatorInfo -{ - /** \brief Handle to Vulkan instance object. - - This is the same value as has been passed through VmaAllocatorCreateInfo::instance. - */ - VkInstance VMA_NOT_NULL instance; - /** \brief Handle to Vulkan physical device object. - - This is the same value as has been passed through VmaAllocatorCreateInfo::physicalDevice. - */ - VkPhysicalDevice VMA_NOT_NULL physicalDevice; - /** \brief Handle to Vulkan device object. - - This is the same value as has been passed through VmaAllocatorCreateInfo::device. - */ - VkDevice VMA_NOT_NULL device; -} VmaAllocatorInfo; - -/** @} */ - -/** -\addtogroup group_stats -@{ -*/ - -/** \brief Calculated statistics of memory usage e.g. in a specific memory type, heap, custom pool, or total. - -These are fast to calculate. -See functions: vmaGetHeapBudgets(), vmaGetPoolStatistics(). -*/ -typedef struct VmaStatistics -{ - /** \brief Number of `VkDeviceMemory` objects - Vulkan memory blocks allocated. - */ - uint32_t blockCount; - /** \brief Number of #VmaAllocation objects allocated. - - Dedicated allocations have their own blocks, so each one adds 1 to `allocationCount` as well as `blockCount`. - */ - uint32_t allocationCount; - /** \brief Number of bytes allocated in `VkDeviceMemory` blocks. - - \note To avoid confusion, please be aware that what Vulkan calls an "allocation" - a whole `VkDeviceMemory` object - (e.g. as in `VkPhysicalDeviceLimits::maxMemoryAllocationCount`) is called a "block" in VMA, while VMA calls - "allocation" a #VmaAllocation object that represents a memory region sub-allocated from such block, usually for a single buffer or image. - */ - VkDeviceSize blockBytes; - /** \brief Total number of bytes occupied by all #VmaAllocation objects. - - Always less or equal than `blockBytes`. - Difference `(blockBytes - allocationBytes)` is the amount of memory allocated from Vulkan - but unused by any #VmaAllocation. - */ - VkDeviceSize allocationBytes; -} VmaStatistics; - -/** \brief More detailed statistics than #VmaStatistics. - -These are slower to calculate. Use for debugging purposes. -See functions: vmaCalculateStatistics(), vmaCalculatePoolStatistics(). - -Previous version of the statistics API provided averages, but they have been removed -because they can be easily calculated as: - -\code -VkDeviceSize allocationSizeAvg = detailedStats.statistics.allocationBytes / detailedStats.statistics.allocationCount; -VkDeviceSize unusedBytes = detailedStats.statistics.blockBytes - detailedStats.statistics.allocationBytes; -VkDeviceSize unusedRangeSizeAvg = unusedBytes / detailedStats.unusedRangeCount; -\endcode -*/ -typedef struct VmaDetailedStatistics -{ - /// Basic statistics. - VmaStatistics statistics; - /// Number of free ranges of memory between allocations. - uint32_t unusedRangeCount; - /// Smallest allocation size. `VK_WHOLE_SIZE` if there are 0 allocations. - VkDeviceSize allocationSizeMin; - /// Largest allocation size. 0 if there are 0 allocations. - VkDeviceSize allocationSizeMax; - /// Smallest empty range size. `VK_WHOLE_SIZE` if there are 0 empty ranges. - VkDeviceSize unusedRangeSizeMin; - /// Largest empty range size. 0 if there are 0 empty ranges. - VkDeviceSize unusedRangeSizeMax; -} VmaDetailedStatistics; - -/** \brief General statistics from current state of the Allocator - -total memory usage across all memory heaps and types. - -These are slower to calculate. Use for debugging purposes. -See function vmaCalculateStatistics(). -*/ -typedef struct VmaTotalStatistics -{ - VmaDetailedStatistics memoryType[VK_MAX_MEMORY_TYPES]; - VmaDetailedStatistics memoryHeap[VK_MAX_MEMORY_HEAPS]; - VmaDetailedStatistics total; -} VmaTotalStatistics; - -/** \brief Statistics of current memory usage and available budget for a specific memory heap. - -These are fast to calculate. -See function vmaGetHeapBudgets(). -*/ -typedef struct VmaBudget -{ - /** \brief Statistics fetched from the library. - */ - VmaStatistics statistics; - /** \brief Estimated current memory usage of the program, in bytes. - - Fetched from system using VK_EXT_memory_budget extension if enabled. - - It might be different than `statistics.blockBytes` (usually higher) due to additional implicit objects - also occupying the memory, like swapchain, pipelines, descriptor heaps, command buffers, or - `VkDeviceMemory` blocks allocated outside of this library, if any. - */ - VkDeviceSize usage; - /** \brief Estimated amount of memory available to the program, in bytes. - - Fetched from system using VK_EXT_memory_budget extension if enabled. - - It might be different (most probably smaller) than `VkMemoryHeap::size[heapIndex]` due to factors - external to the program, decided by the operating system. - Difference `budget - usage` is the amount of additional memory that can probably - be allocated without problems. Exceeding the budget may result in various problems. - */ - VkDeviceSize budget; -} VmaBudget; - -/** @} */ - -/** -\addtogroup group_alloc -@{ -*/ - -/** \brief Parameters of new #VmaAllocation. - -To be used with functions like vmaCreateBuffer(), vmaCreateImage(), and many others. -*/ -typedef struct VmaAllocationCreateInfo -{ - /// Use #VmaAllocationCreateFlagBits enum. - VmaAllocationCreateFlags flags; - /** \brief Intended usage of memory. - - You can leave #VMA_MEMORY_USAGE_UNKNOWN if you specify memory requirements in other way. \n - If `pool` is not null, this member is ignored. - */ - VmaMemoryUsage usage; - /** \brief Flags that must be set in a Memory Type chosen for an allocation. - - Leave 0 if you specify memory requirements in other way. \n - If `pool` is not null, this member is ignored.*/ - VkMemoryPropertyFlags requiredFlags; - /** \brief Flags that preferably should be set in a memory type chosen for an allocation. - - Set to 0 if no additional flags are preferred. \n - If `pool` is not null, this member is ignored. */ - VkMemoryPropertyFlags preferredFlags; - /** \brief Bitmask containing one bit set for every memory type acceptable for this allocation. - - Value 0 is equivalent to `UINT32_MAX` - it means any memory type is accepted if - it meets other requirements specified by this structure, with no further - restrictions on memory type index. \n - If `pool` is not null, this member is ignored. - */ - uint32_t memoryTypeBits; - /** \brief Pool that this allocation should be created in. - - Leave `VK_NULL_HANDLE` to allocate from default pool. If not null, members: - `usage`, `requiredFlags`, `preferredFlags`, `memoryTypeBits` are ignored. - */ - VmaPool VMA_NULLABLE pool; - /** \brief Custom general-purpose pointer that will be stored in #VmaAllocation, can be read as VmaAllocationInfo::pUserData and changed using vmaSetAllocationUserData(). - - If #VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT is used, it must be either - null or pointer to a null-terminated string. The string will be then copied to - internal buffer, so it doesn't need to be valid after allocation call. - */ - void* VMA_NULLABLE pUserData; - /** \brief A floating-point value between 0 and 1, indicating the priority of the allocation relative to other memory allocations. - - It is used only when #VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT flag was used during creation of the #VmaAllocator object - and this allocation ends up as dedicated or is explicitly forced as dedicated using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT. - Otherwise, it has the priority of a memory block where it is placed and this variable is ignored. - */ - float priority; -} VmaAllocationCreateInfo; - -/// Describes parameter of created #VmaPool. -typedef struct VmaPoolCreateInfo -{ - /** \brief Vulkan memory type index to allocate this pool from. - */ - uint32_t memoryTypeIndex; - /** \brief Use combination of #VmaPoolCreateFlagBits. - */ - VmaPoolCreateFlags flags; - /** \brief Size of a single `VkDeviceMemory` block to be allocated as part of this pool, in bytes. Optional. - - Specify nonzero to set explicit, constant size of memory blocks used by this - pool. - - Leave 0 to use default and let the library manage block sizes automatically. - Sizes of particular blocks may vary. - In this case, the pool will also support dedicated allocations. - */ - VkDeviceSize blockSize; - /** \brief Minimum number of blocks to be always allocated in this pool, even if they stay empty. - - Set to 0 to have no preallocated blocks and allow the pool be completely empty. - */ - size_t minBlockCount; - /** \brief Maximum number of blocks that can be allocated in this pool. Optional. - - Set to 0 to use default, which is `SIZE_MAX`, which means no limit. - - Set to same value as VmaPoolCreateInfo::minBlockCount to have fixed amount of memory allocated - throughout whole lifetime of this pool. - */ - size_t maxBlockCount; - /** \brief A floating-point value between 0 and 1, indicating the priority of the allocations in this pool relative to other memory allocations. - - It is used only when #VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT flag was used during creation of the #VmaAllocator object. - Otherwise, this variable is ignored. - */ - float priority; - /** \brief Additional minimum alignment to be used for all allocations created from this pool. Can be 0. - - Leave 0 (default) not to impose any additional alignment. If not 0, it must be a power of two. - It can be useful in cases where alignment returned by Vulkan by functions like `vkGetBufferMemoryRequirements` is not enough, - e.g. when doing interop with OpenGL. - */ - VkDeviceSize minAllocationAlignment; - /** \brief Additional `pNext` chain to be attached to `VkMemoryAllocateInfo` used for every allocation made by this pool. Optional. - - Optional, can be null. If not null, it must point to a `pNext` chain of structures that can be attached to `VkMemoryAllocateInfo`. - It can be useful for special needs such as adding `VkExportMemoryAllocateInfoKHR`. - Structures pointed by this member must remain alive and unchanged for the whole lifetime of the custom pool. - - Please note that some structures, e.g. `VkMemoryPriorityAllocateInfoEXT`, `VkMemoryDedicatedAllocateInfoKHR`, - can be attached automatically by this library when using other, more convenient of its features. - */ - void* VMA_NULLABLE pMemoryAllocateNext; -} VmaPoolCreateInfo; - -/** @} */ - -/** -\addtogroup group_alloc -@{ -*/ - -/// Parameters of #VmaAllocation objects, that can be retrieved using function vmaGetAllocationInfo(). -typedef struct VmaAllocationInfo -{ - /** \brief Memory type index that this allocation was allocated from. - - It never changes. - */ - uint32_t memoryType; - /** \brief Handle to Vulkan memory object. - - Same memory object can be shared by multiple allocations. - - It can change after the allocation is moved during \ref defragmentation. - */ - VkDeviceMemory VMA_NULLABLE_NON_DISPATCHABLE deviceMemory; - /** \brief Offset in `VkDeviceMemory` object to the beginning of this allocation, in bytes. `(deviceMemory, offset)` pair is unique to this allocation. - - You usually don't need to use this offset. If you create a buffer or an image together with the allocation using e.g. function - vmaCreateBuffer(), vmaCreateImage(), functions that operate on these resources refer to the beginning of the buffer or image, - not entire device memory block. Functions like vmaMapMemory(), vmaBindBufferMemory() also refer to the beginning of the allocation - and apply this offset automatically. - - It can change after the allocation is moved during \ref defragmentation. - */ - VkDeviceSize offset; - /** \brief Size of this allocation, in bytes. - - It never changes. - - \note Allocation size returned in this variable may be greater than the size - requested for the resource e.g. as `VkBufferCreateInfo::size`. Whole size of the - allocation is accessible for operations on memory e.g. using a pointer after - mapping with vmaMapMemory(), but operations on the resource e.g. using - `vkCmdCopyBuffer` must be limited to the size of the resource. - */ - VkDeviceSize size; - /** \brief Pointer to the beginning of this allocation as mapped data. - - If the allocation hasn't been mapped using vmaMapMemory() and hasn't been - created with #VMA_ALLOCATION_CREATE_MAPPED_BIT flag, this value is null. - - It can change after call to vmaMapMemory(), vmaUnmapMemory(). - It can also change after the allocation is moved during \ref defragmentation. - */ - void* VMA_NULLABLE pMappedData; - /** \brief Custom general-purpose pointer that was passed as VmaAllocationCreateInfo::pUserData or set using vmaSetAllocationUserData(). - - It can change after call to vmaSetAllocationUserData() for this allocation. - */ - void* VMA_NULLABLE pUserData; - /** \brief Custom allocation name that was set with vmaSetAllocationName(). - - It can change after call to vmaSetAllocationName() for this allocation. - - Another way to set custom name is to pass it in VmaAllocationCreateInfo::pUserData with - additional flag #VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT set [DEPRECATED]. - */ - const char* VMA_NULLABLE pName; -} VmaAllocationInfo; - -/** \brief Parameters for defragmentation. - -To be used with function vmaBeginDefragmentation(). -*/ -typedef struct VmaDefragmentationInfo -{ - /// \brief Use combination of #VmaDefragmentationFlagBits. - VmaDefragmentationFlags flags; - /** \brief Custom pool to be defragmented. - - If null then default pools will undergo defragmentation process. - */ - VmaPool VMA_NULLABLE pool; - /** \brief Maximum numbers of bytes that can be copied during single pass, while moving allocations to different places. - - `0` means no limit. - */ - VkDeviceSize maxBytesPerPass; - /** \brief Maximum number of allocations that can be moved during single pass to a different place. - - `0` means no limit. - */ - uint32_t maxAllocationsPerPass; -} VmaDefragmentationInfo; - -/// Single move of an allocation to be done for defragmentation. -typedef struct VmaDefragmentationMove -{ - /// Operation to be performed on the allocation by vmaEndDefragmentationPass(). Default value is #VMA_DEFRAGMENTATION_MOVE_OPERATION_COPY. You can modify it. - VmaDefragmentationMoveOperation operation; - /// Allocation that should be moved. - VmaAllocation VMA_NOT_NULL srcAllocation; - /** \brief Temporary allocation pointing to destination memory that will replace `srcAllocation`. - - \warning Do not store this allocation in your data structures! It exists only temporarily, for the duration of the defragmentation pass, - to be used for binding new buffer/image to the destination memory using e.g. vmaBindBufferMemory(). - vmaEndDefragmentationPass() will destroy it and make `srcAllocation` point to this memory. - */ - VmaAllocation VMA_NOT_NULL dstTmpAllocation; -} VmaDefragmentationMove; - -/** \brief Parameters for incremental defragmentation steps. - -To be used with function vmaBeginDefragmentationPass(). -*/ -typedef struct VmaDefragmentationPassMoveInfo -{ - /// Number of elements in the `pMoves` array. - uint32_t moveCount; - /** \brief Array of moves to be performed by the user in the current defragmentation pass. - - Pointer to an array of `moveCount` elements, owned by VMA, created in vmaBeginDefragmentationPass(), destroyed in vmaEndDefragmentationPass(). - - For each element, you should: - - 1. Create a new buffer/image in the place pointed by VmaDefragmentationMove::dstMemory + VmaDefragmentationMove::dstOffset. - 2. Copy data from the VmaDefragmentationMove::srcAllocation e.g. using `vkCmdCopyBuffer`, `vkCmdCopyImage`. - 3. Make sure these commands finished executing on the GPU. - 4. Destroy the old buffer/image. - - Only then you can finish defragmentation pass by calling vmaEndDefragmentationPass(). - After this call, the allocation will point to the new place in memory. - - Alternatively, if you cannot move specific allocation, you can set VmaDefragmentationMove::operation to #VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE. - - Alternatively, if you decide you want to completely remove the allocation: - - 1. Destroy its buffer/image. - 2. Set VmaDefragmentationMove::operation to #VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY. - - Then, after vmaEndDefragmentationPass() the allocation will be freed. - */ - VmaDefragmentationMove* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(moveCount) pMoves; -} VmaDefragmentationPassMoveInfo; - -/// Statistics returned for defragmentation process in function vmaEndDefragmentation(). -typedef struct VmaDefragmentationStats -{ - /// Total number of bytes that have been copied while moving allocations to different places. - VkDeviceSize bytesMoved; - /// Total number of bytes that have been released to the system by freeing empty `VkDeviceMemory` objects. - VkDeviceSize bytesFreed; - /// Number of allocations that have been moved to different places. - uint32_t allocationsMoved; - /// Number of empty `VkDeviceMemory` objects that have been released to the system. - uint32_t deviceMemoryBlocksFreed; -} VmaDefragmentationStats; - -/** @} */ - -/** -\addtogroup group_virtual -@{ -*/ - -/// Parameters of created #VmaVirtualBlock object to be passed to vmaCreateVirtualBlock(). -typedef struct VmaVirtualBlockCreateInfo -{ - /** \brief Total size of the virtual block. - - Sizes can be expressed in bytes or any units you want as long as you are consistent in using them. - For example, if you allocate from some array of structures, 1 can mean single instance of entire structure. - */ - VkDeviceSize size; - - /** \brief Use combination of #VmaVirtualBlockCreateFlagBits. - */ - VmaVirtualBlockCreateFlags flags; - - /** \brief Custom CPU memory allocation callbacks. Optional. - - Optional, can be null. When specified, they will be used for all CPU-side memory allocations. - */ - const VkAllocationCallbacks* VMA_NULLABLE pAllocationCallbacks; -} VmaVirtualBlockCreateInfo; - -/// Parameters of created virtual allocation to be passed to vmaVirtualAllocate(). -typedef struct VmaVirtualAllocationCreateInfo -{ - /** \brief Size of the allocation. - - Cannot be zero. - */ - VkDeviceSize size; - /** \brief Required alignment of the allocation. Optional. - - Must be power of two. Special value 0 has the same meaning as 1 - means no special alignment is required, so allocation can start at any offset. - */ - VkDeviceSize alignment; - /** \brief Use combination of #VmaVirtualAllocationCreateFlagBits. - */ - VmaVirtualAllocationCreateFlags flags; - /** \brief Custom pointer to be associated with the allocation. Optional. - - It can be any value and can be used for user-defined purposes. It can be fetched or changed later. - */ - void* VMA_NULLABLE pUserData; -} VmaVirtualAllocationCreateInfo; - -/// Parameters of an existing virtual allocation, returned by vmaGetVirtualAllocationInfo(). -typedef struct VmaVirtualAllocationInfo -{ - /** \brief Offset of the allocation. - - Offset at which the allocation was made. - */ - VkDeviceSize offset; - /** \brief Size of the allocation. - - Same value as passed in VmaVirtualAllocationCreateInfo::size. - */ - VkDeviceSize size; - /** \brief Custom pointer associated with the allocation. - - Same value as passed in VmaVirtualAllocationCreateInfo::pUserData or to vmaSetVirtualAllocationUserData(). - */ - void* VMA_NULLABLE pUserData; -} VmaVirtualAllocationInfo; - -/** @} */ - -#endif // _VMA_DATA_TYPES_DECLARATIONS - -#ifndef _VMA_FUNCTION_HEADERS - -/** -\addtogroup group_init -@{ -*/ - -/// Creates #VmaAllocator object. -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAllocator( - const VmaAllocatorCreateInfo* VMA_NOT_NULL pCreateInfo, - VmaAllocator VMA_NULLABLE* VMA_NOT_NULL pAllocator); - -/// Destroys allocator object. -VMA_CALL_PRE void VMA_CALL_POST vmaDestroyAllocator( - VmaAllocator VMA_NULLABLE allocator); - -/** \brief Returns information about existing #VmaAllocator object - handle to Vulkan device etc. - -It might be useful if you want to keep just the #VmaAllocator handle and fetch other required handles to -`VkPhysicalDevice`, `VkDevice` etc. every time using this function. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocatorInfo( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocatorInfo* VMA_NOT_NULL pAllocatorInfo); - -/** -PhysicalDeviceProperties are fetched from physicalDevice by the allocator. -You can access it here, without fetching it again on your own. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaGetPhysicalDeviceProperties( - VmaAllocator VMA_NOT_NULL allocator, - const VkPhysicalDeviceProperties* VMA_NULLABLE* VMA_NOT_NULL ppPhysicalDeviceProperties); - -/** -PhysicalDeviceMemoryProperties are fetched from physicalDevice by the allocator. -You can access it here, without fetching it again on your own. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryProperties( - VmaAllocator VMA_NOT_NULL allocator, - const VkPhysicalDeviceMemoryProperties* VMA_NULLABLE* VMA_NOT_NULL ppPhysicalDeviceMemoryProperties); - -/** -\brief Given Memory Type Index, returns Property Flags of this memory type. - -This is just a convenience function. Same information can be obtained using -vmaGetMemoryProperties(). -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryTypeProperties( - VmaAllocator VMA_NOT_NULL allocator, - uint32_t memoryTypeIndex, - VkMemoryPropertyFlags* VMA_NOT_NULL pFlags); - -/** \brief Sets index of the current frame. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaSetCurrentFrameIndex( - VmaAllocator VMA_NOT_NULL allocator, - uint32_t frameIndex); - -/** @} */ - -/** -\addtogroup group_stats -@{ -*/ - -/** \brief Retrieves statistics from current state of the Allocator. - -This function is called "calculate" not "get" because it has to traverse all -internal data structures, so it may be quite slow. Use it for debugging purposes. -For faster but more brief statistics suitable to be called every frame or every allocation, -use vmaGetHeapBudgets(). - -Note that when using allocator from multiple threads, returned information may immediately -become outdated. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaCalculateStatistics( - VmaAllocator VMA_NOT_NULL allocator, - VmaTotalStatistics* VMA_NOT_NULL pStats); - -/** \brief Retrieves information about current memory usage and budget for all memory heaps. - -\param allocator -\param[out] pBudgets Must point to array with number of elements at least equal to number of memory heaps in physical device used. - -This function is called "get" not "calculate" because it is very fast, suitable to be called -every frame or every allocation. For more detailed statistics use vmaCalculateStatistics(). - -Note that when using allocator from multiple threads, returned information may immediately -become outdated. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaGetHeapBudgets( - VmaAllocator VMA_NOT_NULL allocator, - VmaBudget* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL("VkPhysicalDeviceMemoryProperties::memoryHeapCount") pBudgets); - -/** @} */ - -/** -\addtogroup group_alloc -@{ -*/ - -/** -\brief Helps to find memoryTypeIndex, given memoryTypeBits and VmaAllocationCreateInfo. - -This algorithm tries to find a memory type that: - -- Is allowed by memoryTypeBits. -- Contains all the flags from pAllocationCreateInfo->requiredFlags. -- Matches intended usage. -- Has as many flags from pAllocationCreateInfo->preferredFlags as possible. - -\return Returns VK_ERROR_FEATURE_NOT_PRESENT if not found. Receiving such result -from this function or any other allocating function probably means that your -device doesn't support any memory type with requested features for the specific -type of resource you want to use it for. Please check parameters of your -resource, like image layout (OPTIMAL versus LINEAR) or mip level count. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndex( - VmaAllocator VMA_NOT_NULL allocator, - uint32_t memoryTypeBits, - const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo, - uint32_t* VMA_NOT_NULL pMemoryTypeIndex); - -/** -\brief Helps to find memoryTypeIndex, given VkBufferCreateInfo and VmaAllocationCreateInfo. - -It can be useful e.g. to determine value to be used as VmaPoolCreateInfo::memoryTypeIndex. -It internally creates a temporary, dummy buffer that never has memory bound. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForBufferInfo( - VmaAllocator VMA_NOT_NULL allocator, - const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo, - const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo, - uint32_t* VMA_NOT_NULL pMemoryTypeIndex); - -/** -\brief Helps to find memoryTypeIndex, given VkImageCreateInfo and VmaAllocationCreateInfo. - -It can be useful e.g. to determine value to be used as VmaPoolCreateInfo::memoryTypeIndex. -It internally creates a temporary, dummy image that never has memory bound. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForImageInfo( - VmaAllocator VMA_NOT_NULL allocator, - const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo, - const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo, - uint32_t* VMA_NOT_NULL pMemoryTypeIndex); - -/** \brief Allocates Vulkan device memory and creates #VmaPool object. - -\param allocator Allocator object. -\param pCreateInfo Parameters of pool to create. -\param[out] pPool Handle to created pool. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreatePool( - VmaAllocator VMA_NOT_NULL allocator, - const VmaPoolCreateInfo* VMA_NOT_NULL pCreateInfo, - VmaPool VMA_NULLABLE* VMA_NOT_NULL pPool); - -/** \brief Destroys #VmaPool object and frees Vulkan device memory. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaDestroyPool( - VmaAllocator VMA_NOT_NULL allocator, - VmaPool VMA_NULLABLE pool); - -/** @} */ - -/** -\addtogroup group_stats -@{ -*/ - -/** \brief Retrieves statistics of existing #VmaPool object. - -\param allocator Allocator object. -\param pool Pool object. -\param[out] pPoolStats Statistics of specified pool. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolStatistics( - VmaAllocator VMA_NOT_NULL allocator, - VmaPool VMA_NOT_NULL pool, - VmaStatistics* VMA_NOT_NULL pPoolStats); - -/** \brief Retrieves detailed statistics of existing #VmaPool object. - -\param allocator Allocator object. -\param pool Pool object. -\param[out] pPoolStats Statistics of specified pool. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaCalculatePoolStatistics( - VmaAllocator VMA_NOT_NULL allocator, - VmaPool VMA_NOT_NULL pool, - VmaDetailedStatistics* VMA_NOT_NULL pPoolStats); - -/** @} */ - -/** -\addtogroup group_alloc -@{ -*/ - -/** \brief Checks magic number in margins around all allocations in given memory pool in search for corruptions. - -Corruption detection is enabled only when `VMA_DEBUG_DETECT_CORRUPTION` macro is defined to nonzero, -`VMA_DEBUG_MARGIN` is defined to nonzero and the pool is created in memory type that is -`HOST_VISIBLE` and `HOST_COHERENT`. For more information, see [Corruption detection](@ref debugging_memory_usage_corruption_detection). - -Possible return values: - -- `VK_ERROR_FEATURE_NOT_PRESENT` - corruption detection is not enabled for specified pool. -- `VK_SUCCESS` - corruption detection has been performed and succeeded. -- `VK_ERROR_UNKNOWN` - corruption detection has been performed and found memory corruptions around one of the allocations. - `VMA_ASSERT` is also fired in that case. -- Other value: Error returned by Vulkan, e.g. memory mapping failure. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckPoolCorruption( - VmaAllocator VMA_NOT_NULL allocator, - VmaPool VMA_NOT_NULL pool); - -/** \brief Retrieves name of a custom pool. - -After the call `ppName` is either null or points to an internally-owned null-terminated string -containing name of the pool that was previously set. The pointer becomes invalid when the pool is -destroyed or its name is changed using vmaSetPoolName(). -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolName( - VmaAllocator VMA_NOT_NULL allocator, - VmaPool VMA_NOT_NULL pool, - const char* VMA_NULLABLE* VMA_NOT_NULL ppName); - -/** \brief Sets name of a custom pool. - -`pName` can be either null or pointer to a null-terminated string with new name for the pool. -Function makes internal copy of the string, so it can be changed or freed immediately after this call. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaSetPoolName( - VmaAllocator VMA_NOT_NULL allocator, - VmaPool VMA_NOT_NULL pool, - const char* VMA_NULLABLE pName); - -/** \brief General purpose memory allocation. - -\param allocator -\param pVkMemoryRequirements -\param pCreateInfo -\param[out] pAllocation Handle to allocated memory. -\param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo(). - -You should free the memory using vmaFreeMemory() or vmaFreeMemoryPages(). - -It is recommended to use vmaAllocateMemoryForBuffer(), vmaAllocateMemoryForImage(), -vmaCreateBuffer(), vmaCreateImage() instead whenever possible. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemory( - VmaAllocator VMA_NOT_NULL allocator, - const VkMemoryRequirements* VMA_NOT_NULL pVkMemoryRequirements, - const VmaAllocationCreateInfo* VMA_NOT_NULL pCreateInfo, - VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation, - VmaAllocationInfo* VMA_NULLABLE pAllocationInfo); - -/** \brief General purpose memory allocation for multiple allocation objects at once. - -\param allocator Allocator object. -\param pVkMemoryRequirements Memory requirements for each allocation. -\param pCreateInfo Creation parameters for each allocation. -\param allocationCount Number of allocations to make. -\param[out] pAllocations Pointer to array that will be filled with handles to created allocations. -\param[out] pAllocationInfo Optional. Pointer to array that will be filled with parameters of created allocations. - -You should free the memory using vmaFreeMemory() or vmaFreeMemoryPages(). - -Word "pages" is just a suggestion to use this function to allocate pieces of memory needed for sparse binding. -It is just a general purpose allocation function able to make multiple allocations at once. -It may be internally optimized to be more efficient than calling vmaAllocateMemory() `allocationCount` times. - -All allocations are made using same parameters. All of them are created out of the same memory pool and type. -If any allocation fails, all allocations already made within this function call are also freed, so that when -returned result is not `VK_SUCCESS`, `pAllocation` array is always entirely filled with `VK_NULL_HANDLE`. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryPages( - VmaAllocator VMA_NOT_NULL allocator, - const VkMemoryRequirements* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pVkMemoryRequirements, - const VmaAllocationCreateInfo* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pCreateInfo, - size_t allocationCount, - VmaAllocation VMA_NULLABLE* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pAllocations, - VmaAllocationInfo* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) pAllocationInfo); - -/** \brief Allocates memory suitable for given `VkBuffer`. - -\param allocator -\param buffer -\param pCreateInfo -\param[out] pAllocation Handle to allocated memory. -\param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo(). - -It only creates #VmaAllocation. To bind the memory to the buffer, use vmaBindBufferMemory(). - -This is a special-purpose function. In most cases you should use vmaCreateBuffer(). - -You must free the allocation using vmaFreeMemory() when no longer needed. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForBuffer( - VmaAllocator VMA_NOT_NULL allocator, - VkBuffer VMA_NOT_NULL_NON_DISPATCHABLE buffer, - const VmaAllocationCreateInfo* VMA_NOT_NULL pCreateInfo, - VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation, - VmaAllocationInfo* VMA_NULLABLE pAllocationInfo); - -/** \brief Allocates memory suitable for given `VkImage`. - -\param allocator -\param image -\param pCreateInfo -\param[out] pAllocation Handle to allocated memory. -\param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo(). - -It only creates #VmaAllocation. To bind the memory to the buffer, use vmaBindImageMemory(). - -This is a special-purpose function. In most cases you should use vmaCreateImage(). - -You must free the allocation using vmaFreeMemory() when no longer needed. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForImage( - VmaAllocator VMA_NOT_NULL allocator, - VkImage VMA_NOT_NULL_NON_DISPATCHABLE image, - const VmaAllocationCreateInfo* VMA_NOT_NULL pCreateInfo, - VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation, - VmaAllocationInfo* VMA_NULLABLE pAllocationInfo); - -/** \brief Frees memory previously allocated using vmaAllocateMemory(), vmaAllocateMemoryForBuffer(), or vmaAllocateMemoryForImage(). - -Passing `VK_NULL_HANDLE` as `allocation` is valid. Such function call is just skipped. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemory( - VmaAllocator VMA_NOT_NULL allocator, - const VmaAllocation VMA_NULLABLE allocation); - -/** \brief Frees memory and destroys multiple allocations. - -Word "pages" is just a suggestion to use this function to free pieces of memory used for sparse binding. -It is just a general purpose function to free memory and destroy allocations made using e.g. vmaAllocateMemory(), -vmaAllocateMemoryPages() and other functions. -It may be internally optimized to be more efficient than calling vmaFreeMemory() `allocationCount` times. - -Allocations in `pAllocations` array can come from any memory pools and types. -Passing `VK_NULL_HANDLE` as elements of `pAllocations` array is valid. Such entries are just skipped. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemoryPages( - VmaAllocator VMA_NOT_NULL allocator, - size_t allocationCount, - const VmaAllocation VMA_NULLABLE* VMA_NOT_NULL VMA_LEN_IF_NOT_NULL(allocationCount) pAllocations); - -/** \brief Returns current information about specified allocation. - -Current parameters of given allocation are returned in `pAllocationInfo`. - -Although this function doesn't lock any mutex, so it should be quite efficient, -you should avoid calling it too often. -You can retrieve same VmaAllocationInfo structure while creating your resource, from function -vmaCreateBuffer(), vmaCreateImage(). You can remember it if you are sure parameters don't change -(e.g. due to defragmentation). -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationInfo( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - VmaAllocationInfo* VMA_NOT_NULL pAllocationInfo); - -/** \brief Sets pUserData in given allocation to new value. - -The value of pointer `pUserData` is copied to allocation's `pUserData`. -It is opaque, so you can use it however you want - e.g. -as a pointer, ordinal number or some handle to you own data. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationUserData( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - void* VMA_NULLABLE pUserData); - -/** \brief Sets pName in given allocation to new value. - -`pName` must be either null, or pointer to a null-terminated string. The function -makes local copy of the string and sets it as allocation's `pName`. String -passed as pName doesn't need to be valid for whole lifetime of the allocation - -you can free it after this call. String previously pointed by allocation's -`pName` is freed from memory. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationName( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - const char* VMA_NULLABLE pName); - -/** -\brief Given an allocation, returns Property Flags of its memory type. - -This is just a convenience function. Same information can be obtained using -vmaGetAllocationInfo() + vmaGetMemoryProperties(). -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationMemoryProperties( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - VkMemoryPropertyFlags* VMA_NOT_NULL pFlags); - -/** \brief Maps memory represented by given allocation and returns pointer to it. - -Maps memory represented by given allocation to make it accessible to CPU code. -When succeeded, `*ppData` contains pointer to first byte of this memory. - -\warning -If the allocation is part of a bigger `VkDeviceMemory` block, returned pointer is -correctly offsetted to the beginning of region assigned to this particular allocation. -Unlike the result of `vkMapMemory`, it points to the allocation, not to the beginning of the whole block. -You should not add VmaAllocationInfo::offset to it! - -Mapping is internally reference-counted and synchronized, so despite raw Vulkan -function `vkMapMemory()` cannot be used to map same block of `VkDeviceMemory` -multiple times simultaneously, it is safe to call this function on allocations -assigned to the same memory block. Actual Vulkan memory will be mapped on first -mapping and unmapped on last unmapping. - -If the function succeeded, you must call vmaUnmapMemory() to unmap the -allocation when mapping is no longer needed or before freeing the allocation, at -the latest. - -It also safe to call this function multiple times on the same allocation. You -must call vmaUnmapMemory() same number of times as you called vmaMapMemory(). - -It is also safe to call this function on allocation created with -#VMA_ALLOCATION_CREATE_MAPPED_BIT flag. Its memory stays mapped all the time. -You must still call vmaUnmapMemory() same number of times as you called -vmaMapMemory(). You must not call vmaUnmapMemory() additional time to free the -"0-th" mapping made automatically due to #VMA_ALLOCATION_CREATE_MAPPED_BIT flag. - -This function fails when used on allocation made in memory type that is not -`HOST_VISIBLE`. - -This function doesn't automatically flush or invalidate caches. -If the allocation is made from a memory types that is not `HOST_COHERENT`, -you also need to use vmaInvalidateAllocation() / vmaFlushAllocation(), as required by Vulkan specification. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaMapMemory( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - void* VMA_NULLABLE* VMA_NOT_NULL ppData); - -/** \brief Unmaps memory represented by given allocation, mapped previously using vmaMapMemory(). - -For details, see description of vmaMapMemory(). - -This function doesn't automatically flush or invalidate caches. -If the allocation is made from a memory types that is not `HOST_COHERENT`, -you also need to use vmaInvalidateAllocation() / vmaFlushAllocation(), as required by Vulkan specification. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaUnmapMemory( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation); - -/** \brief Flushes memory of given allocation. - -Calls `vkFlushMappedMemoryRanges()` for memory associated with given range of given allocation. -It needs to be called after writing to a mapped memory for memory types that are not `HOST_COHERENT`. -Unmap operation doesn't do that automatically. - -- `offset` must be relative to the beginning of allocation. -- `size` can be `VK_WHOLE_SIZE`. It means all memory from `offset` the the end of given allocation. -- `offset` and `size` don't have to be aligned. - They are internally rounded down/up to multiply of `nonCoherentAtomSize`. -- If `size` is 0, this call is ignored. -- If memory type that the `allocation` belongs to is not `HOST_VISIBLE` or it is `HOST_COHERENT`, - this call is ignored. - -Warning! `offset` and `size` are relative to the contents of given `allocation`. -If you mean whole allocation, you can pass 0 and `VK_WHOLE_SIZE`, respectively. -Do not pass allocation's offset as `offset`!!! - -This function returns the `VkResult` from `vkFlushMappedMemoryRanges` if it is -called, otherwise `VK_SUCCESS`. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocation( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - VkDeviceSize offset, - VkDeviceSize size); - -/** \brief Invalidates memory of given allocation. - -Calls `vkInvalidateMappedMemoryRanges()` for memory associated with given range of given allocation. -It needs to be called before reading from a mapped memory for memory types that are not `HOST_COHERENT`. -Map operation doesn't do that automatically. - -- `offset` must be relative to the beginning of allocation. -- `size` can be `VK_WHOLE_SIZE`. It means all memory from `offset` the the end of given allocation. -- `offset` and `size` don't have to be aligned. - They are internally rounded down/up to multiply of `nonCoherentAtomSize`. -- If `size` is 0, this call is ignored. -- If memory type that the `allocation` belongs to is not `HOST_VISIBLE` or it is `HOST_COHERENT`, - this call is ignored. - -Warning! `offset` and `size` are relative to the contents of given `allocation`. -If you mean whole allocation, you can pass 0 and `VK_WHOLE_SIZE`, respectively. -Do not pass allocation's offset as `offset`!!! - -This function returns the `VkResult` from `vkInvalidateMappedMemoryRanges` if -it is called, otherwise `VK_SUCCESS`. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocation( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - VkDeviceSize offset, - VkDeviceSize size); - -/** \brief Flushes memory of given set of allocations. - -Calls `vkFlushMappedMemoryRanges()` for memory associated with given ranges of given allocations. -For more information, see documentation of vmaFlushAllocation(). - -\param allocator -\param allocationCount -\param allocations -\param offsets If not null, it must point to an array of offsets of regions to flush, relative to the beginning of respective allocations. Null means all ofsets are zero. -\param sizes If not null, it must point to an array of sizes of regions to flush in respective allocations. Null means `VK_WHOLE_SIZE` for all allocations. - -This function returns the `VkResult` from `vkFlushMappedMemoryRanges` if it is -called, otherwise `VK_SUCCESS`. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocations( - VmaAllocator VMA_NOT_NULL allocator, - uint32_t allocationCount, - const VmaAllocation VMA_NOT_NULL* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) allocations, - const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) offsets, - const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) sizes); - -/** \brief Invalidates memory of given set of allocations. - -Calls `vkInvalidateMappedMemoryRanges()` for memory associated with given ranges of given allocations. -For more information, see documentation of vmaInvalidateAllocation(). - -\param allocator -\param allocationCount -\param allocations -\param offsets If not null, it must point to an array of offsets of regions to flush, relative to the beginning of respective allocations. Null means all ofsets are zero. -\param sizes If not null, it must point to an array of sizes of regions to flush in respective allocations. Null means `VK_WHOLE_SIZE` for all allocations. - -This function returns the `VkResult` from `vkInvalidateMappedMemoryRanges` if it is -called, otherwise `VK_SUCCESS`. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocations( - VmaAllocator VMA_NOT_NULL allocator, - uint32_t allocationCount, - const VmaAllocation VMA_NOT_NULL* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) allocations, - const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) offsets, - const VkDeviceSize* VMA_NULLABLE VMA_LEN_IF_NOT_NULL(allocationCount) sizes); - -/** \brief Checks magic number in margins around all allocations in given memory types (in both default and custom pools) in search for corruptions. - -\param allocator -\param memoryTypeBits Bit mask, where each bit set means that a memory type with that index should be checked. - -Corruption detection is enabled only when `VMA_DEBUG_DETECT_CORRUPTION` macro is defined to nonzero, -`VMA_DEBUG_MARGIN` is defined to nonzero and only for memory types that are -`HOST_VISIBLE` and `HOST_COHERENT`. For more information, see [Corruption detection](@ref debugging_memory_usage_corruption_detection). - -Possible return values: - -- `VK_ERROR_FEATURE_NOT_PRESENT` - corruption detection is not enabled for any of specified memory types. -- `VK_SUCCESS` - corruption detection has been performed and succeeded. -- `VK_ERROR_UNKNOWN` - corruption detection has been performed and found memory corruptions around one of the allocations. - `VMA_ASSERT` is also fired in that case. -- Other value: Error returned by Vulkan, e.g. memory mapping failure. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckCorruption( - VmaAllocator VMA_NOT_NULL allocator, - uint32_t memoryTypeBits); - -/** \brief Begins defragmentation process. - -\param allocator Allocator object. -\param pInfo Structure filled with parameters of defragmentation. -\param[out] pContext Context object that must be passed to vmaEndDefragmentation() to finish defragmentation. -\returns -- `VK_SUCCESS` if defragmentation can begin. -- `VK_ERROR_FEATURE_NOT_PRESENT` if defragmentation is not supported. - -For more information about defragmentation, see documentation chapter: -[Defragmentation](@ref defragmentation). -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentation( - VmaAllocator VMA_NOT_NULL allocator, - const VmaDefragmentationInfo* VMA_NOT_NULL pInfo, - VmaDefragmentationContext VMA_NULLABLE* VMA_NOT_NULL pContext); - -/** \brief Ends defragmentation process. - -\param allocator Allocator object. -\param context Context object that has been created by vmaBeginDefragmentation(). -\param[out] pStats Optional stats for the defragmentation. Can be null. - -Use this function to finish defragmentation started by vmaBeginDefragmentation(). -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaEndDefragmentation( - VmaAllocator VMA_NOT_NULL allocator, - VmaDefragmentationContext VMA_NOT_NULL context, - VmaDefragmentationStats* VMA_NULLABLE pStats); - -/** \brief Starts single defragmentation pass. - -\param allocator Allocator object. -\param context Context object that has been created by vmaBeginDefragmentation(). -\param[out] pPassInfo Computed information for current pass. -\returns -- `VK_SUCCESS` if no more moves are possible. Then you can omit call to vmaEndDefragmentationPass() and simply end whole defragmentation. -- `VK_INCOMPLETE` if there are pending moves returned in `pPassInfo`. You need to perform them, call vmaEndDefragmentationPass(), - and then preferably try another pass with vmaBeginDefragmentationPass(). -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentationPass( - VmaAllocator VMA_NOT_NULL allocator, - VmaDefragmentationContext VMA_NOT_NULL context, - VmaDefragmentationPassMoveInfo* VMA_NOT_NULL pPassInfo); - -/** \brief Ends single defragmentation pass. - -\param allocator Allocator object. -\param context Context object that has been created by vmaBeginDefragmentation(). -\param pPassInfo Computed information for current pass filled by vmaBeginDefragmentationPass() and possibly modified by you. - -Returns `VK_SUCCESS` if no more moves are possible or `VK_INCOMPLETE` if more defragmentations are possible. - -Ends incremental defragmentation pass and commits all defragmentation moves from `pPassInfo`. -After this call: - -- Allocations at `pPassInfo[i].srcAllocation` that had `pPassInfo[i].operation ==` #VMA_DEFRAGMENTATION_MOVE_OPERATION_COPY - (which is the default) will be pointing to the new destination place. -- Allocation at `pPassInfo[i].srcAllocation` that had `pPassInfo[i].operation ==` #VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY - will be freed. - -If no more moves are possible you can end whole defragmentation. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaEndDefragmentationPass( - VmaAllocator VMA_NOT_NULL allocator, - VmaDefragmentationContext VMA_NOT_NULL context, - VmaDefragmentationPassMoveInfo* VMA_NOT_NULL pPassInfo); - -/** \brief Binds buffer to allocation. - -Binds specified buffer to region of memory represented by specified allocation. -Gets `VkDeviceMemory` handle and offset from the allocation. -If you want to create a buffer, allocate memory for it and bind them together separately, -you should use this function for binding instead of standard `vkBindBufferMemory()`, -because it ensures proper synchronization so that when a `VkDeviceMemory` object is used by multiple -allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from multiple threads simultaneously -(which is illegal in Vulkan). - -It is recommended to use function vmaCreateBuffer() instead of this one. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - VkBuffer VMA_NOT_NULL_NON_DISPATCHABLE buffer); - -/** \brief Binds buffer to allocation with additional parameters. - -\param allocator -\param allocation -\param allocationLocalOffset Additional offset to be added while binding, relative to the beginning of the `allocation`. Normally it should be 0. -\param buffer -\param pNext A chain of structures to be attached to `VkBindBufferMemoryInfoKHR` structure used internally. Normally it should be null. - -This function is similar to vmaBindBufferMemory(), but it provides additional parameters. - -If `pNext` is not null, #VmaAllocator object must have been created with #VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT flag -or with VmaAllocatorCreateInfo::vulkanApiVersion `>= VK_API_VERSION_1_1`. Otherwise the call fails. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory2( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - VkDeviceSize allocationLocalOffset, - VkBuffer VMA_NOT_NULL_NON_DISPATCHABLE buffer, - const void* VMA_NULLABLE pNext); - -/** \brief Binds image to allocation. - -Binds specified image to region of memory represented by specified allocation. -Gets `VkDeviceMemory` handle and offset from the allocation. -If you want to create an image, allocate memory for it and bind them together separately, -you should use this function for binding instead of standard `vkBindImageMemory()`, -because it ensures proper synchronization so that when a `VkDeviceMemory` object is used by multiple -allocations, calls to `vkBind*Memory()` or `vkMapMemory()` won't happen from multiple threads simultaneously -(which is illegal in Vulkan). - -It is recommended to use function vmaCreateImage() instead of this one. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - VkImage VMA_NOT_NULL_NON_DISPATCHABLE image); - -/** \brief Binds image to allocation with additional parameters. - -\param allocator -\param allocation -\param allocationLocalOffset Additional offset to be added while binding, relative to the beginning of the `allocation`. Normally it should be 0. -\param image -\param pNext A chain of structures to be attached to `VkBindImageMemoryInfoKHR` structure used internally. Normally it should be null. - -This function is similar to vmaBindImageMemory(), but it provides additional parameters. - -If `pNext` is not null, #VmaAllocator object must have been created with #VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT flag -or with VmaAllocatorCreateInfo::vulkanApiVersion `>= VK_API_VERSION_1_1`. Otherwise the call fails. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory2( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - VkDeviceSize allocationLocalOffset, - VkImage VMA_NOT_NULL_NON_DISPATCHABLE image, - const void* VMA_NULLABLE pNext); - -/** \brief Creates a new `VkBuffer`, allocates and binds memory for it. - -\param allocator -\param pBufferCreateInfo -\param pAllocationCreateInfo -\param[out] pBuffer Buffer that was created. -\param[out] pAllocation Allocation that was created. -\param[out] pAllocationInfo Optional. Information about allocated memory. It can be later fetched using function vmaGetAllocationInfo(). - -This function automatically: - --# Creates buffer. --# Allocates appropriate memory for it. --# Binds the buffer with the memory. - -If any of these operations fail, buffer and allocation are not created, -returned value is negative error code, `*pBuffer` and `*pAllocation` are null. - -If the function succeeded, you must destroy both buffer and allocation when you -no longer need them using either convenience function vmaDestroyBuffer() or -separately, using `vkDestroyBuffer()` and vmaFreeMemory(). - -If #VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT flag was used, -VK_KHR_dedicated_allocation extension is used internally to query driver whether -it requires or prefers the new buffer to have dedicated allocation. If yes, -and if dedicated allocation is possible -(#VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT is not used), it creates dedicated -allocation for this buffer, just like when using -#VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT. - -\note This function creates a new `VkBuffer`. Sub-allocation of parts of one large buffer, -although recommended as a good practice, is out of scope of this library and could be implemented -by the user as a higher-level logic on top of VMA. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBuffer( - VmaAllocator VMA_NOT_NULL allocator, - const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo, - const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo, - VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer, - VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation, - VmaAllocationInfo* VMA_NULLABLE pAllocationInfo); - -/** \brief Creates a buffer with additional minimum alignment. - -Similar to vmaCreateBuffer() but provides additional parameter `minAlignment` which allows to specify custom, -minimum alignment to be used when placing the buffer inside a larger memory block, which may be needed e.g. -for interop with OpenGL. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBufferWithAlignment( - VmaAllocator VMA_NOT_NULL allocator, - const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo, - const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo, - VkDeviceSize minAlignment, - VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer, - VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation, - VmaAllocationInfo* VMA_NULLABLE pAllocationInfo); - -/** \brief Creates a new `VkBuffer`, binds already created memory for it. - -\param allocator -\param allocation Allocation that provides memory to be used for binding new buffer to it. -\param pBufferCreateInfo -\param[out] pBuffer Buffer that was created. - -This function automatically: - --# Creates buffer. --# Binds the buffer with the supplied memory. - -If any of these operations fail, buffer is not created, -returned value is negative error code and `*pBuffer` is null. - -If the function succeeded, you must destroy the buffer when you -no longer need it using `vkDestroyBuffer()`. If you want to also destroy the corresponding -allocation you can use convenience function vmaDestroyBuffer(). - -\note There is a new version of this function augmented with parameter `allocationLocalOffset` - see vmaCreateAliasingBuffer2(). -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingBuffer( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo, - VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer); - -/** \brief Creates a new `VkBuffer`, binds already created memory for it. - -\param allocator -\param allocation Allocation that provides memory to be used for binding new buffer to it. -\param allocationLocalOffset Additional offset to be added while binding, relative to the beginning of the allocation. Normally it should be 0. -\param pBufferCreateInfo -\param[out] pBuffer Buffer that was created. - -This function automatically: - --# Creates buffer. --# Binds the buffer with the supplied memory. - -If any of these operations fail, buffer is not created, -returned value is negative error code and `*pBuffer` is null. - -If the function succeeded, you must destroy the buffer when you -no longer need it using `vkDestroyBuffer()`. If you want to also destroy the corresponding -allocation you can use convenience function vmaDestroyBuffer(). - -\note This is a new version of the function augmented with parameter `allocationLocalOffset`. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingBuffer2( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - VkDeviceSize allocationLocalOffset, - const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo, - VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer); - -/** \brief Destroys Vulkan buffer and frees allocated memory. - -This is just a convenience function equivalent to: - -\code -vkDestroyBuffer(device, buffer, allocationCallbacks); -vmaFreeMemory(allocator, allocation); -\endcode - -It is safe to pass null as buffer and/or allocation. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaDestroyBuffer( - VmaAllocator VMA_NOT_NULL allocator, - VkBuffer VMA_NULLABLE_NON_DISPATCHABLE buffer, - VmaAllocation VMA_NULLABLE allocation); - -/// Function similar to vmaCreateBuffer(). -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateImage( - VmaAllocator VMA_NOT_NULL allocator, - const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo, - const VmaAllocationCreateInfo* VMA_NOT_NULL pAllocationCreateInfo, - VkImage VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pImage, - VmaAllocation VMA_NULLABLE* VMA_NOT_NULL pAllocation, - VmaAllocationInfo* VMA_NULLABLE pAllocationInfo); - -/// Function similar to vmaCreateAliasingBuffer() but for images. -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingImage( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo, - VkImage VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pImage); - -/// Function similar to vmaCreateAliasingBuffer2() but for images. -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingImage2( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - VkDeviceSize allocationLocalOffset, - const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo, - VkImage VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pImage); - -/** \brief Destroys Vulkan image and frees allocated memory. - -This is just a convenience function equivalent to: - -\code -vkDestroyImage(device, image, allocationCallbacks); -vmaFreeMemory(allocator, allocation); -\endcode - -It is safe to pass null as image and/or allocation. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaDestroyImage( - VmaAllocator VMA_NOT_NULL allocator, - VkImage VMA_NULLABLE_NON_DISPATCHABLE image, - VmaAllocation VMA_NULLABLE allocation); - -/** @} */ - -/** -\addtogroup group_virtual -@{ -*/ - -/** \brief Creates new #VmaVirtualBlock object. - -\param pCreateInfo Parameters for creation. -\param[out] pVirtualBlock Returned virtual block object or `VMA_NULL` if creation failed. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateVirtualBlock( - const VmaVirtualBlockCreateInfo* VMA_NOT_NULL pCreateInfo, - VmaVirtualBlock VMA_NULLABLE* VMA_NOT_NULL pVirtualBlock); - -/** \brief Destroys #VmaVirtualBlock object. - -Please note that you should consciously handle virtual allocations that could remain unfreed in the block. -You should either free them individually using vmaVirtualFree() or call vmaClearVirtualBlock() -if you are sure this is what you want. If you do neither, an assert is called. - -If you keep pointers to some additional metadata associated with your virtual allocations in their `pUserData`, -don't forget to free them. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaDestroyVirtualBlock( - VmaVirtualBlock VMA_NULLABLE virtualBlock); - -/** \brief Returns true of the #VmaVirtualBlock is empty - contains 0 virtual allocations and has all its space available for new allocations. -*/ -VMA_CALL_PRE VkBool32 VMA_CALL_POST vmaIsVirtualBlockEmpty( - VmaVirtualBlock VMA_NOT_NULL virtualBlock); - -/** \brief Returns information about a specific virtual allocation within a virtual block, like its size and `pUserData` pointer. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaGetVirtualAllocationInfo( - VmaVirtualBlock VMA_NOT_NULL virtualBlock, - VmaVirtualAllocation VMA_NOT_NULL_NON_DISPATCHABLE allocation, VmaVirtualAllocationInfo* VMA_NOT_NULL pVirtualAllocInfo); - -/** \brief Allocates new virtual allocation inside given #VmaVirtualBlock. - -If the allocation fails due to not enough free space available, `VK_ERROR_OUT_OF_DEVICE_MEMORY` is returned -(despite the function doesn't ever allocate actual GPU memory). -`pAllocation` is then set to `VK_NULL_HANDLE` and `pOffset`, if not null, it set to `UINT64_MAX`. - -\param virtualBlock Virtual block -\param pCreateInfo Parameters for the allocation -\param[out] pAllocation Returned handle of the new allocation -\param[out] pOffset Returned offset of the new allocation. Optional, can be null. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaVirtualAllocate( - VmaVirtualBlock VMA_NOT_NULL virtualBlock, - const VmaVirtualAllocationCreateInfo* VMA_NOT_NULL pCreateInfo, - VmaVirtualAllocation VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pAllocation, - VkDeviceSize* VMA_NULLABLE pOffset); - -/** \brief Frees virtual allocation inside given #VmaVirtualBlock. - -It is correct to call this function with `allocation == VK_NULL_HANDLE` - it does nothing. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaVirtualFree( - VmaVirtualBlock VMA_NOT_NULL virtualBlock, - VmaVirtualAllocation VMA_NULLABLE_NON_DISPATCHABLE allocation); - -/** \brief Frees all virtual allocations inside given #VmaVirtualBlock. - -You must either call this function or free each virtual allocation individually with vmaVirtualFree() -before destroying a virtual block. Otherwise, an assert is called. - -If you keep pointer to some additional metadata associated with your virtual allocation in its `pUserData`, -don't forget to free it as well. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaClearVirtualBlock( - VmaVirtualBlock VMA_NOT_NULL virtualBlock); - -/** \brief Changes custom pointer associated with given virtual allocation. -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaSetVirtualAllocationUserData( - VmaVirtualBlock VMA_NOT_NULL virtualBlock, - VmaVirtualAllocation VMA_NOT_NULL_NON_DISPATCHABLE allocation, - void* VMA_NULLABLE pUserData); - -/** \brief Calculates and returns statistics about virtual allocations and memory usage in given #VmaVirtualBlock. - -This function is fast to call. For more detailed statistics, see vmaCalculateVirtualBlockStatistics(). -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaGetVirtualBlockStatistics( - VmaVirtualBlock VMA_NOT_NULL virtualBlock, - VmaStatistics* VMA_NOT_NULL pStats); - -/** \brief Calculates and returns detailed statistics about virtual allocations and memory usage in given #VmaVirtualBlock. - -This function is slow to call. Use for debugging purposes. -For less detailed statistics, see vmaGetVirtualBlockStatistics(). -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaCalculateVirtualBlockStatistics( - VmaVirtualBlock VMA_NOT_NULL virtualBlock, - VmaDetailedStatistics* VMA_NOT_NULL pStats); - -/** @} */ - -#if VMA_STATS_STRING_ENABLED -/** -\addtogroup group_stats -@{ -*/ - -/** \brief Builds and returns a null-terminated string in JSON format with information about given #VmaVirtualBlock. -\param virtualBlock Virtual block. -\param[out] ppStatsString Returned string. -\param detailedMap Pass `VK_FALSE` to only obtain statistics as returned by vmaCalculateVirtualBlockStatistics(). Pass `VK_TRUE` to also obtain full list of allocations and free spaces. - -Returned string must be freed using vmaFreeVirtualBlockStatsString(). -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaBuildVirtualBlockStatsString( - VmaVirtualBlock VMA_NOT_NULL virtualBlock, - char* VMA_NULLABLE* VMA_NOT_NULL ppStatsString, - VkBool32 detailedMap); - -/// Frees a string returned by vmaBuildVirtualBlockStatsString(). -VMA_CALL_PRE void VMA_CALL_POST vmaFreeVirtualBlockStatsString( - VmaVirtualBlock VMA_NOT_NULL virtualBlock, - char* VMA_NULLABLE pStatsString); - -/** \brief Builds and returns statistics as a null-terminated string in JSON format. -\param allocator -\param[out] ppStatsString Must be freed using vmaFreeStatsString() function. -\param detailedMap -*/ -VMA_CALL_PRE void VMA_CALL_POST vmaBuildStatsString( - VmaAllocator VMA_NOT_NULL allocator, - char* VMA_NULLABLE* VMA_NOT_NULL ppStatsString, - VkBool32 detailedMap); - -VMA_CALL_PRE void VMA_CALL_POST vmaFreeStatsString( - VmaAllocator VMA_NOT_NULL allocator, - char* VMA_NULLABLE pStatsString); - -/** @} */ - -#endif // VMA_STATS_STRING_ENABLED - -#endif // _VMA_FUNCTION_HEADERS - -#ifdef __cplusplus -} -#endif - -#endif // AMD_VULKAN_MEMORY_ALLOCATOR_H - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -// -// IMPLEMENTATION -// -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -// For Visual Studio IntelliSense. -#if defined(__cplusplus) && defined(__INTELLISENSE__) -#define VMA_IMPLEMENTATION -#endif - -#ifdef VMA_IMPLEMENTATION -#undef VMA_IMPLEMENTATION - -#include -#include -#include -#include -#include - -#ifdef _MSC_VER - #include // For functions like __popcnt, _BitScanForward etc. -#endif -#if __cplusplus >= 202002L || _MSVC_LANG >= 202002L // C++20 - #include // For std::popcount -#endif - -/******************************************************************************* -CONFIGURATION SECTION - -Define some of these macros before each #include of this header or change them -here if you need other then default behavior depending on your environment. -*/ -#ifndef _VMA_CONFIGURATION - -/* -Define this macro to 1 to make the library fetch pointers to Vulkan functions -internally, like: - - vulkanFunctions.vkAllocateMemory = &vkAllocateMemory; -*/ -#if !defined(VMA_STATIC_VULKAN_FUNCTIONS) && !defined(VK_NO_PROTOTYPES) - #define VMA_STATIC_VULKAN_FUNCTIONS 1 -#endif - -/* -Define this macro to 1 to make the library fetch pointers to Vulkan functions -internally, like: - - vulkanFunctions.vkAllocateMemory = (PFN_vkAllocateMemory)vkGetDeviceProcAddr(device, "vkAllocateMemory"); - -To use this feature in new versions of VMA you now have to pass -VmaVulkanFunctions::vkGetInstanceProcAddr and vkGetDeviceProcAddr as -VmaAllocatorCreateInfo::pVulkanFunctions. Other members can be null. -*/ -#if !defined(VMA_DYNAMIC_VULKAN_FUNCTIONS) - #define VMA_DYNAMIC_VULKAN_FUNCTIONS 1 -#endif - -#ifndef VMA_USE_STL_SHARED_MUTEX - // Compiler conforms to C++17. - #if __cplusplus >= 201703L - #define VMA_USE_STL_SHARED_MUTEX 1 - // Visual studio defines __cplusplus properly only when passed additional parameter: /Zc:__cplusplus - // Otherwise it is always 199711L, despite shared_mutex works since Visual Studio 2015 Update 2. - #elif defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 190023918 && __cplusplus == 199711L && _MSVC_LANG >= 201703L - #define VMA_USE_STL_SHARED_MUTEX 1 - #else - #define VMA_USE_STL_SHARED_MUTEX 0 - #endif -#endif - -/* -Define this macro to include custom header files without having to edit this file directly, e.g.: - - // Inside of "my_vma_configuration_user_includes.h": - - #include "my_custom_assert.h" // for MY_CUSTOM_ASSERT - #include "my_custom_min.h" // for my_custom_min - #include - #include - - // Inside a different file, which includes "vk_mem_alloc.h": - - #define VMA_CONFIGURATION_USER_INCLUDES_H "my_vma_configuration_user_includes.h" - #define VMA_ASSERT(expr) MY_CUSTOM_ASSERT(expr) - #define VMA_MIN(v1, v2) (my_custom_min(v1, v2)) - #include "vk_mem_alloc.h" - ... - -The following headers are used in this CONFIGURATION section only, so feel free to -remove them if not needed. -*/ -#if !defined(VMA_CONFIGURATION_USER_INCLUDES_H) - #include // for assert - #include // for min, max - #include -#else - #include VMA_CONFIGURATION_USER_INCLUDES_H -#endif - -#ifndef VMA_NULL - // Value used as null pointer. Define it to e.g.: nullptr, NULL, 0, (void*)0. - #define VMA_NULL nullptr -#endif - -// Normal assert to check for programmer's errors, especially in Debug configuration. -#ifndef VMA_ASSERT - #ifdef NDEBUG - #define VMA_ASSERT(expr) - #else - #define VMA_ASSERT(expr) assert(expr) - #endif -#endif - -// Assert that will be called very often, like inside data structures e.g. operator[]. -// Making it non-empty can make program slow. -#ifndef VMA_HEAVY_ASSERT - #ifdef NDEBUG - #define VMA_HEAVY_ASSERT(expr) - #else - #define VMA_HEAVY_ASSERT(expr) //VMA_ASSERT(expr) - #endif -#endif - -// If your compiler is not compatible with C++17 and definition of -// aligned_alloc() function is missing, uncommenting following line may help: - -//#include - -#if defined(__ANDROID_API__) && (__ANDROID_API__ < 16) -#include -static void* vma_aligned_alloc(size_t alignment, size_t size) -{ - // alignment must be >= sizeof(void*) - if(alignment < sizeof(void*)) - { - alignment = sizeof(void*); - } - - return memalign(alignment, size); -} -#elif defined(__APPLE__) || defined(__ANDROID__) || (defined(__linux__) && defined(__GLIBCXX__) && !defined(_GLIBCXX_HAVE_ALIGNED_ALLOC)) -#include - -#if defined(__APPLE__) -#include -#endif - -static void* vma_aligned_alloc(size_t alignment, size_t size) -{ - // Unfortunately, aligned_alloc causes VMA to crash due to it returning null pointers. (At least under 11.4) - // Therefore, for now disable this specific exception until a proper solution is found. - //#if defined(__APPLE__) && (defined(MAC_OS_X_VERSION_10_16) || defined(__IPHONE_14_0)) - //#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_16 || __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_14_0 - // // For C++14, usr/include/malloc/_malloc.h declares aligned_alloc()) only - // // with the MacOSX11.0 SDK in Xcode 12 (which is what adds - // // MAC_OS_X_VERSION_10_16), even though the function is marked - // // available for 10.15. That is why the preprocessor checks for 10.16 but - // // the __builtin_available checks for 10.15. - // // People who use C++17 could call aligned_alloc with the 10.15 SDK already. - // if (__builtin_available(macOS 10.15, iOS 13, *)) - // return aligned_alloc(alignment, size); - //#endif - //#endif - - // alignment must be >= sizeof(void*) - if(alignment < sizeof(void*)) - { - alignment = sizeof(void*); - } - - void *pointer; - if(posix_memalign(&pointer, alignment, size) == 0) - return pointer; - return VMA_NULL; -} -#elif defined(_WIN32) -static void* vma_aligned_alloc(size_t alignment, size_t size) -{ - return _aligned_malloc(size, alignment); -} -#elif __cplusplus >= 201703L // Compiler conforms to C++17. -static void* vma_aligned_alloc(size_t alignment, size_t size) -{ - return aligned_alloc(alignment, size); -} -#else -static void* vma_aligned_alloc(size_t alignment, size_t size) -{ - VMA_ASSERT(0 && "Could not implement aligned_alloc automatically. Please enable C++17 or later in your compiler or provide custom implementation of macro VMA_SYSTEM_ALIGNED_MALLOC (and VMA_SYSTEM_ALIGNED_FREE if needed) using the API of your system."); - return VMA_NULL; -} -#endif - -#if defined(_WIN32) -static void vma_aligned_free(void* ptr) -{ - _aligned_free(ptr); -} -#else -static void vma_aligned_free(void* VMA_NULLABLE ptr) -{ - free(ptr); -} -#endif - -#ifndef VMA_ALIGN_OF - #define VMA_ALIGN_OF(type) (__alignof(type)) -#endif - -#ifndef VMA_SYSTEM_ALIGNED_MALLOC - #define VMA_SYSTEM_ALIGNED_MALLOC(size, alignment) vma_aligned_alloc((alignment), (size)) -#endif - -#ifndef VMA_SYSTEM_ALIGNED_FREE - // VMA_SYSTEM_FREE is the old name, but might have been defined by the user - #if defined(VMA_SYSTEM_FREE) - #define VMA_SYSTEM_ALIGNED_FREE(ptr) VMA_SYSTEM_FREE(ptr) - #else - #define VMA_SYSTEM_ALIGNED_FREE(ptr) vma_aligned_free(ptr) - #endif -#endif - -#ifndef VMA_COUNT_BITS_SET - // Returns number of bits set to 1 in (v) - #define VMA_COUNT_BITS_SET(v) VmaCountBitsSet(v) -#endif - -#ifndef VMA_BITSCAN_LSB - // Scans integer for index of first nonzero value from the Least Significant Bit (LSB). If mask is 0 then returns UINT8_MAX - #define VMA_BITSCAN_LSB(mask) VmaBitScanLSB(mask) -#endif - -#ifndef VMA_BITSCAN_MSB - // Scans integer for index of first nonzero value from the Most Significant Bit (MSB). If mask is 0 then returns UINT8_MAX - #define VMA_BITSCAN_MSB(mask) VmaBitScanMSB(mask) -#endif - -#ifndef VMA_MIN - #define VMA_MIN(v1, v2) ((std::min)((v1), (v2))) -#endif - -#ifndef VMA_MAX - #define VMA_MAX(v1, v2) ((std::max)((v1), (v2))) -#endif - -#ifndef VMA_SWAP - #define VMA_SWAP(v1, v2) std::swap((v1), (v2)) -#endif - -#ifndef VMA_SORT - #define VMA_SORT(beg, end, cmp) std::sort(beg, end, cmp) -#endif - -#ifndef VMA_DEBUG_LOG - #define VMA_DEBUG_LOG(format, ...) - /* - #define VMA_DEBUG_LOG(format, ...) do { \ - printf(format, __VA_ARGS__); \ - printf("\n"); \ - } while(false) - */ -#endif - -// Define this macro to 1 to enable functions: vmaBuildStatsString, vmaFreeStatsString. -#if VMA_STATS_STRING_ENABLED - static inline void VmaUint32ToStr(char* VMA_NOT_NULL outStr, size_t strLen, uint32_t num) - { - snprintf(outStr, strLen, "%u", static_cast(num)); - } - static inline void VmaUint64ToStr(char* VMA_NOT_NULL outStr, size_t strLen, uint64_t num) - { - snprintf(outStr, strLen, "%llu", static_cast(num)); - } - static inline void VmaPtrToStr(char* VMA_NOT_NULL outStr, size_t strLen, const void* ptr) - { - snprintf(outStr, strLen, "%p", ptr); - } -#endif - -#ifndef VMA_MUTEX - class VmaMutex - { - public: - void Lock() { m_Mutex.lock(); } - void Unlock() { m_Mutex.unlock(); } - bool TryLock() { return m_Mutex.try_lock(); } - private: - std::mutex m_Mutex; - }; - #define VMA_MUTEX VmaMutex -#endif - -// Read-write mutex, where "read" is shared access, "write" is exclusive access. -#ifndef VMA_RW_MUTEX - #if VMA_USE_STL_SHARED_MUTEX - // Use std::shared_mutex from C++17. - #include - class VmaRWMutex - { - public: - void LockRead() { m_Mutex.lock_shared(); } - void UnlockRead() { m_Mutex.unlock_shared(); } - bool TryLockRead() { return m_Mutex.try_lock_shared(); } - void LockWrite() { m_Mutex.lock(); } - void UnlockWrite() { m_Mutex.unlock(); } - bool TryLockWrite() { return m_Mutex.try_lock(); } - private: - std::shared_mutex m_Mutex; - }; - #define VMA_RW_MUTEX VmaRWMutex - #elif defined(_WIN32) && defined(WINVER) && WINVER >= 0x0600 - // Use SRWLOCK from WinAPI. - // Minimum supported client = Windows Vista, server = Windows Server 2008. - class VmaRWMutex - { - public: - VmaRWMutex() { InitializeSRWLock(&m_Lock); } - void LockRead() { AcquireSRWLockShared(&m_Lock); } - void UnlockRead() { ReleaseSRWLockShared(&m_Lock); } - bool TryLockRead() { return TryAcquireSRWLockShared(&m_Lock) != FALSE; } - void LockWrite() { AcquireSRWLockExclusive(&m_Lock); } - void UnlockWrite() { ReleaseSRWLockExclusive(&m_Lock); } - bool TryLockWrite() { return TryAcquireSRWLockExclusive(&m_Lock) != FALSE; } - private: - SRWLOCK m_Lock; - }; - #define VMA_RW_MUTEX VmaRWMutex - #else - // Less efficient fallback: Use normal mutex. - class VmaRWMutex - { - public: - void LockRead() { m_Mutex.Lock(); } - void UnlockRead() { m_Mutex.Unlock(); } - bool TryLockRead() { return m_Mutex.TryLock(); } - void LockWrite() { m_Mutex.Lock(); } - void UnlockWrite() { m_Mutex.Unlock(); } - bool TryLockWrite() { return m_Mutex.TryLock(); } - private: - VMA_MUTEX m_Mutex; - }; - #define VMA_RW_MUTEX VmaRWMutex - #endif // #if VMA_USE_STL_SHARED_MUTEX -#endif // #ifndef VMA_RW_MUTEX - -/* -If providing your own implementation, you need to implement a subset of std::atomic. -*/ -#ifndef VMA_ATOMIC_UINT32 - #include - #define VMA_ATOMIC_UINT32 std::atomic -#endif - -#ifndef VMA_ATOMIC_UINT64 - #include - #define VMA_ATOMIC_UINT64 std::atomic -#endif - -#ifndef VMA_DEBUG_ALWAYS_DEDICATED_MEMORY - /** - Every allocation will have its own memory block. - Define to 1 for debugging purposes only. - */ - #define VMA_DEBUG_ALWAYS_DEDICATED_MEMORY (0) -#endif - -#ifndef VMA_MIN_ALIGNMENT - /** - Minimum alignment of all allocations, in bytes. - Set to more than 1 for debugging purposes. Must be power of two. - */ - #ifdef VMA_DEBUG_ALIGNMENT // Old name - #define VMA_MIN_ALIGNMENT VMA_DEBUG_ALIGNMENT - #else - #define VMA_MIN_ALIGNMENT (1) - #endif -#endif - -#ifndef VMA_DEBUG_MARGIN - /** - Minimum margin after every allocation, in bytes. - Set nonzero for debugging purposes only. - */ - #define VMA_DEBUG_MARGIN (0) -#endif - -#ifndef VMA_DEBUG_INITIALIZE_ALLOCATIONS - /** - Define this macro to 1 to automatically fill new allocations and destroyed - allocations with some bit pattern. - */ - #define VMA_DEBUG_INITIALIZE_ALLOCATIONS (0) -#endif - -#ifndef VMA_DEBUG_DETECT_CORRUPTION - /** - Define this macro to 1 together with non-zero value of VMA_DEBUG_MARGIN to - enable writing magic value to the margin after every allocation and - validating it, so that memory corruptions (out-of-bounds writes) are detected. - */ - #define VMA_DEBUG_DETECT_CORRUPTION (0) -#endif - -#ifndef VMA_DEBUG_GLOBAL_MUTEX - /** - Set this to 1 for debugging purposes only, to enable single mutex protecting all - entry calls to the library. Can be useful for debugging multithreading issues. - */ - #define VMA_DEBUG_GLOBAL_MUTEX (0) -#endif - -#ifndef VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY - /** - Minimum value for VkPhysicalDeviceLimits::bufferImageGranularity. - Set to more than 1 for debugging purposes only. Must be power of two. - */ - #define VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY (1) -#endif - -#ifndef VMA_DEBUG_DONT_EXCEED_MAX_MEMORY_ALLOCATION_COUNT - /* - Set this to 1 to make VMA never exceed VkPhysicalDeviceLimits::maxMemoryAllocationCount - and return error instead of leaving up to Vulkan implementation what to do in such cases. - */ - #define VMA_DEBUG_DONT_EXCEED_MAX_MEMORY_ALLOCATION_COUNT (0) -#endif - -#ifndef VMA_SMALL_HEAP_MAX_SIZE - /// Maximum size of a memory heap in Vulkan to consider it "small". - #define VMA_SMALL_HEAP_MAX_SIZE (1024ull * 1024 * 1024) -#endif - -#ifndef VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE - /// Default size of a block allocated as single VkDeviceMemory from a "large" heap. - #define VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE (256ull * 1024 * 1024) -#endif - -/* -Mapping hysteresis is a logic that launches when vmaMapMemory/vmaUnmapMemory is called -or a persistently mapped allocation is created and destroyed several times in a row. -It keeps additional +1 mapping of a device memory block to prevent calling actual -vkMapMemory/vkUnmapMemory too many times, which may improve performance and help -tools like RenderDoc. -*/ -#ifndef VMA_MAPPING_HYSTERESIS_ENABLED - #define VMA_MAPPING_HYSTERESIS_ENABLED 1 -#endif - -#ifndef VMA_CLASS_NO_COPY - #define VMA_CLASS_NO_COPY(className) \ - private: \ - className(const className&) = delete; \ - className& operator=(const className&) = delete; -#endif - -#define VMA_VALIDATE(cond) do { if(!(cond)) { \ - VMA_ASSERT(0 && "Validation failed: " #cond); \ - return false; \ - } } while(false) - -/******************************************************************************* -END OF CONFIGURATION -*/ -#endif // _VMA_CONFIGURATION - - -static const uint8_t VMA_ALLOCATION_FILL_PATTERN_CREATED = 0xDC; -static const uint8_t VMA_ALLOCATION_FILL_PATTERN_DESTROYED = 0xEF; -// Decimal 2139416166, float NaN, little-endian binary 66 E6 84 7F. -static const uint32_t VMA_CORRUPTION_DETECTION_MAGIC_VALUE = 0x7F84E666; - -// Copy of some Vulkan definitions so we don't need to check their existence just to handle few constants. -static const uint32_t VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY = 0x00000040; -static const uint32_t VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY = 0x00000080; -static const uint32_t VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY = 0x00020000; -static const uint32_t VK_IMAGE_CREATE_DISJOINT_BIT_COPY = 0x00000200; -static const int32_t VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT_COPY = 1000158000; -static const uint32_t VMA_ALLOCATION_INTERNAL_STRATEGY_MIN_OFFSET = 0x10000000u; -static const uint32_t VMA_ALLOCATION_TRY_COUNT = 32; -static const uint32_t VMA_VENDOR_ID_AMD = 4098; - -// This one is tricky. Vulkan specification defines this code as available since -// Vulkan 1.0, but doesn't actually define it in Vulkan SDK earlier than 1.2.131. -// See pull request #207. -#define VK_ERROR_UNKNOWN_COPY ((VkResult)-13) - - -#if VMA_STATS_STRING_ENABLED -// Correspond to values of enum VmaSuballocationType. -static const char* VMA_SUBALLOCATION_TYPE_NAMES[] = -{ - "FREE", - "UNKNOWN", - "BUFFER", - "IMAGE_UNKNOWN", - "IMAGE_LINEAR", - "IMAGE_OPTIMAL", -}; -#endif - -static VkAllocationCallbacks VmaEmptyAllocationCallbacks = - { VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL, VMA_NULL }; - - -#ifndef _VMA_ENUM_DECLARATIONS - -enum VmaSuballocationType -{ - VMA_SUBALLOCATION_TYPE_FREE = 0, - VMA_SUBALLOCATION_TYPE_UNKNOWN = 1, - VMA_SUBALLOCATION_TYPE_BUFFER = 2, - VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN = 3, - VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR = 4, - VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL = 5, - VMA_SUBALLOCATION_TYPE_MAX_ENUM = 0x7FFFFFFF -}; - -enum VMA_CACHE_OPERATION -{ - VMA_CACHE_FLUSH, - VMA_CACHE_INVALIDATE -}; - -enum class VmaAllocationRequestType -{ - Normal, - TLSF, - // Used by "Linear" algorithm. - UpperAddress, - EndOf1st, - EndOf2nd, -}; - -#endif // _VMA_ENUM_DECLARATIONS - -#ifndef _VMA_FORWARD_DECLARATIONS -// Opaque handle used by allocation algorithms to identify single allocation in any conforming way. -VK_DEFINE_NON_DISPATCHABLE_HANDLE(VmaAllocHandle); - -struct VmaMutexLock; -struct VmaMutexLockRead; -struct VmaMutexLockWrite; - -template -struct AtomicTransactionalIncrement; - -template -struct VmaStlAllocator; - -template -class VmaVector; - -template -class VmaSmallVector; - -template -class VmaPoolAllocator; - -template -struct VmaListItem; - -template -class VmaRawList; - -template -class VmaList; - -template -class VmaIntrusiveLinkedList; - -// Unused in this version -#if 0 -template -struct VmaPair; -template -struct VmaPairFirstLess; - -template -class VmaMap; -#endif - -#if VMA_STATS_STRING_ENABLED -class VmaStringBuilder; -class VmaJsonWriter; -#endif - -class VmaDeviceMemoryBlock; - -struct VmaDedicatedAllocationListItemTraits; -class VmaDedicatedAllocationList; - -struct VmaSuballocation; -struct VmaSuballocationOffsetLess; -struct VmaSuballocationOffsetGreater; -struct VmaSuballocationItemSizeLess; - -typedef VmaList> VmaSuballocationList; - -struct VmaAllocationRequest; - -class VmaBlockMetadata; -class VmaBlockMetadata_Linear; -class VmaBlockMetadata_TLSF; - -class VmaBlockVector; - -struct VmaPoolListItemTraits; - -struct VmaCurrentBudgetData; - -class VmaAllocationObjectAllocator; - -#endif // _VMA_FORWARD_DECLARATIONS - - -#ifndef _VMA_FUNCTIONS - -/* -Returns number of bits set to 1 in (v). - -On specific platforms and compilers you can use instrinsics like: - -Visual Studio: - return __popcnt(v); -GCC, Clang: - return static_cast(__builtin_popcount(v)); - -Define macro VMA_COUNT_BITS_SET to provide your optimized implementation. -But you need to check in runtime whether user's CPU supports these, as some old processors don't. -*/ -static inline uint32_t VmaCountBitsSet(uint32_t v) -{ -#if __cplusplus >= 202002L || _MSVC_LANG >= 202002L // C++20 - return std::popcount(v); -#else - uint32_t c = v - ((v >> 1) & 0x55555555); - c = ((c >> 2) & 0x33333333) + (c & 0x33333333); - c = ((c >> 4) + c) & 0x0F0F0F0F; - c = ((c >> 8) + c) & 0x00FF00FF; - c = ((c >> 16) + c) & 0x0000FFFF; - return c; -#endif -} - -static inline uint8_t VmaBitScanLSB(uint64_t mask) -{ -#if defined(_MSC_VER) && defined(_WIN64) - unsigned long pos; - if (_BitScanForward64(&pos, mask)) - return static_cast(pos); - return UINT8_MAX; -#elif defined __GNUC__ || defined __clang__ - return static_cast(__builtin_ffsll(mask)) - 1U; -#else - uint8_t pos = 0; - uint64_t bit = 1; - do - { - if (mask & bit) - return pos; - bit <<= 1; - } while (pos++ < 63); - return UINT8_MAX; -#endif -} - -static inline uint8_t VmaBitScanLSB(uint32_t mask) -{ -#ifdef _MSC_VER - unsigned long pos; - if (_BitScanForward(&pos, mask)) - return static_cast(pos); - return UINT8_MAX; -#elif defined __GNUC__ || defined __clang__ - return static_cast(__builtin_ffs(mask)) - 1U; -#else - uint8_t pos = 0; - uint32_t bit = 1; - do - { - if (mask & bit) - return pos; - bit <<= 1; - } while (pos++ < 31); - return UINT8_MAX; -#endif -} - -static inline uint8_t VmaBitScanMSB(uint64_t mask) -{ -#if defined(_MSC_VER) && defined(_WIN64) - unsigned long pos; - if (_BitScanReverse64(&pos, mask)) - return static_cast(pos); -#elif defined __GNUC__ || defined __clang__ - if (mask) - return 63 - static_cast(__builtin_clzll(mask)); -#else - uint8_t pos = 63; - uint64_t bit = 1ULL << 63; - do - { - if (mask & bit) - return pos; - bit >>= 1; - } while (pos-- > 0); -#endif - return UINT8_MAX; -} - -static inline uint8_t VmaBitScanMSB(uint32_t mask) -{ -#ifdef _MSC_VER - unsigned long pos; - if (_BitScanReverse(&pos, mask)) - return static_cast(pos); -#elif defined __GNUC__ || defined __clang__ - if (mask) - return 31 - static_cast(__builtin_clz(mask)); -#else - uint8_t pos = 31; - uint32_t bit = 1UL << 31; - do - { - if (mask & bit) - return pos; - bit >>= 1; - } while (pos-- > 0); -#endif - return UINT8_MAX; -} - -/* -Returns true if given number is a power of two. -T must be unsigned integer number or signed integer but always nonnegative. -For 0 returns true. -*/ -template -inline bool VmaIsPow2(T x) -{ - return (x & (x - 1)) == 0; -} - -// Aligns given value up to nearest multiply of align value. For example: VmaAlignUp(11, 8) = 16. -// Use types like uint32_t, uint64_t as T. -template -static inline T VmaAlignUp(T val, T alignment) -{ - VMA_HEAVY_ASSERT(VmaIsPow2(alignment)); - return (val + alignment - 1) & ~(alignment - 1); -} - -// Aligns given value down to nearest multiply of align value. For example: VmaAlignUp(11, 8) = 8. -// Use types like uint32_t, uint64_t as T. -template -static inline T VmaAlignDown(T val, T alignment) -{ - VMA_HEAVY_ASSERT(VmaIsPow2(alignment)); - return val & ~(alignment - 1); -} - -// Division with mathematical rounding to nearest number. -template -static inline T VmaRoundDiv(T x, T y) -{ - return (x + (y / (T)2)) / y; -} - -// Divide by 'y' and round up to nearest integer. -template -static inline T VmaDivideRoundingUp(T x, T y) -{ - return (x + y - (T)1) / y; -} - -// Returns smallest power of 2 greater or equal to v. -static inline uint32_t VmaNextPow2(uint32_t v) -{ - v--; - v |= v >> 1; - v |= v >> 2; - v |= v >> 4; - v |= v >> 8; - v |= v >> 16; - v++; - return v; -} - -static inline uint64_t VmaNextPow2(uint64_t v) -{ - v--; - v |= v >> 1; - v |= v >> 2; - v |= v >> 4; - v |= v >> 8; - v |= v >> 16; - v |= v >> 32; - v++; - return v; -} - -// Returns largest power of 2 less or equal to v. -static inline uint32_t VmaPrevPow2(uint32_t v) -{ - v |= v >> 1; - v |= v >> 2; - v |= v >> 4; - v |= v >> 8; - v |= v >> 16; - v = v ^ (v >> 1); - return v; -} - -static inline uint64_t VmaPrevPow2(uint64_t v) -{ - v |= v >> 1; - v |= v >> 2; - v |= v >> 4; - v |= v >> 8; - v |= v >> 16; - v |= v >> 32; - v = v ^ (v >> 1); - return v; -} - -static inline bool VmaStrIsEmpty(const char* pStr) -{ - return pStr == VMA_NULL || *pStr == '\0'; -} - -/* -Returns true if two memory blocks occupy overlapping pages. -ResourceA must be in less memory offset than ResourceB. - -Algorithm is based on "Vulkan 1.0.39 - A Specification (with all registered Vulkan extensions)" -chapter 11.6 "Resource Memory Association", paragraph "Buffer-Image Granularity". -*/ -static inline bool VmaBlocksOnSamePage( - VkDeviceSize resourceAOffset, - VkDeviceSize resourceASize, - VkDeviceSize resourceBOffset, - VkDeviceSize pageSize) -{ - VMA_ASSERT(resourceAOffset + resourceASize <= resourceBOffset && resourceASize > 0 && pageSize > 0); - VkDeviceSize resourceAEnd = resourceAOffset + resourceASize - 1; - VkDeviceSize resourceAEndPage = resourceAEnd & ~(pageSize - 1); - VkDeviceSize resourceBStart = resourceBOffset; - VkDeviceSize resourceBStartPage = resourceBStart & ~(pageSize - 1); - return resourceAEndPage == resourceBStartPage; -} - -/* -Returns true if given suballocation types could conflict and must respect -VkPhysicalDeviceLimits::bufferImageGranularity. They conflict if one is buffer -or linear image and another one is optimal image. If type is unknown, behave -conservatively. -*/ -static inline bool VmaIsBufferImageGranularityConflict( - VmaSuballocationType suballocType1, - VmaSuballocationType suballocType2) -{ - if (suballocType1 > suballocType2) - { - VMA_SWAP(suballocType1, suballocType2); - } - - switch (suballocType1) - { - case VMA_SUBALLOCATION_TYPE_FREE: - return false; - case VMA_SUBALLOCATION_TYPE_UNKNOWN: - return true; - case VMA_SUBALLOCATION_TYPE_BUFFER: - return - suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN || - suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL; - case VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN: - return - suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN || - suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR || - suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL; - case VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR: - return - suballocType2 == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL; - case VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL: - return false; - default: - VMA_ASSERT(0); - return true; - } -} - -static void VmaWriteMagicValue(void* pData, VkDeviceSize offset) -{ -#if VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_DETECT_CORRUPTION - uint32_t* pDst = (uint32_t*)((char*)pData + offset); - const size_t numberCount = VMA_DEBUG_MARGIN / sizeof(uint32_t); - for (size_t i = 0; i < numberCount; ++i, ++pDst) - { - *pDst = VMA_CORRUPTION_DETECTION_MAGIC_VALUE; - } -#else - // no-op -#endif -} - -static bool VmaValidateMagicValue(const void* pData, VkDeviceSize offset) -{ -#if VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_DETECT_CORRUPTION - const uint32_t* pSrc = (const uint32_t*)((const char*)pData + offset); - const size_t numberCount = VMA_DEBUG_MARGIN / sizeof(uint32_t); - for (size_t i = 0; i < numberCount; ++i, ++pSrc) - { - if (*pSrc != VMA_CORRUPTION_DETECTION_MAGIC_VALUE) - { - return false; - } - } -#endif - return true; -} - -/* -Fills structure with parameters of an example buffer to be used for transfers -during GPU memory defragmentation. -*/ -static void VmaFillGpuDefragmentationBufferCreateInfo(VkBufferCreateInfo& outBufCreateInfo) -{ - memset(&outBufCreateInfo, 0, sizeof(outBufCreateInfo)); - outBufCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; - outBufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - outBufCreateInfo.size = (VkDeviceSize)VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE; // Example size. -} - - -/* -Performs binary search and returns iterator to first element that is greater or -equal to (key), according to comparison (cmp). - -Cmp should return true if first argument is less than second argument. - -Returned value is the found element, if present in the collection or place where -new element with value (key) should be inserted. -*/ -template -static IterT VmaBinaryFindFirstNotLess(IterT beg, IterT end, const KeyT& key, const CmpLess& cmp) -{ - size_t down = 0, up = (end - beg); - while (down < up) - { - const size_t mid = down + (up - down) / 2; // Overflow-safe midpoint calculation - if (cmp(*(beg + mid), key)) - { - down = mid + 1; - } - else - { - up = mid; - } - } - return beg + down; -} - -template -IterT VmaBinaryFindSorted(const IterT& beg, const IterT& end, const KeyT& value, const CmpLess& cmp) -{ - IterT it = VmaBinaryFindFirstNotLess( - beg, end, value, cmp); - if (it == end || - (!cmp(*it, value) && !cmp(value, *it))) - { - return it; - } - return end; -} - -/* -Returns true if all pointers in the array are not-null and unique. -Warning! O(n^2) complexity. Use only inside VMA_HEAVY_ASSERT. -T must be pointer type, e.g. VmaAllocation, VmaPool. -*/ -template -static bool VmaValidatePointerArray(uint32_t count, const T* arr) -{ - for (uint32_t i = 0; i < count; ++i) - { - const T iPtr = arr[i]; - if (iPtr == VMA_NULL) - { - return false; - } - for (uint32_t j = i + 1; j < count; ++j) - { - if (iPtr == arr[j]) - { - return false; - } - } - } - return true; -} - -template -static inline void VmaPnextChainPushFront(MainT* mainStruct, NewT* newStruct) -{ - newStruct->pNext = mainStruct->pNext; - mainStruct->pNext = newStruct; -} - -// This is the main algorithm that guides the selection of a memory type best for an allocation - -// converts usage to required/preferred/not preferred flags. -static bool FindMemoryPreferences( - bool isIntegratedGPU, - const VmaAllocationCreateInfo& allocCreateInfo, - VkFlags bufImgUsage, // VkBufferCreateInfo::usage or VkImageCreateInfo::usage. UINT32_MAX if unknown. - VkMemoryPropertyFlags& outRequiredFlags, - VkMemoryPropertyFlags& outPreferredFlags, - VkMemoryPropertyFlags& outNotPreferredFlags) -{ - outRequiredFlags = allocCreateInfo.requiredFlags; - outPreferredFlags = allocCreateInfo.preferredFlags; - outNotPreferredFlags = 0; - - switch(allocCreateInfo.usage) - { - case VMA_MEMORY_USAGE_UNKNOWN: - break; - case VMA_MEMORY_USAGE_GPU_ONLY: - if(!isIntegratedGPU || (outPreferredFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0) - { - outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; - } - break; - case VMA_MEMORY_USAGE_CPU_ONLY: - outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; - break; - case VMA_MEMORY_USAGE_CPU_TO_GPU: - outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; - if(!isIntegratedGPU || (outPreferredFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0) - { - outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; - } - break; - case VMA_MEMORY_USAGE_GPU_TO_CPU: - outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; - outPreferredFlags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT; - break; - case VMA_MEMORY_USAGE_CPU_COPY: - outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; - break; - case VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED: - outRequiredFlags |= VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT; - break; - case VMA_MEMORY_USAGE_AUTO: - case VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE: - case VMA_MEMORY_USAGE_AUTO_PREFER_HOST: - { - if(bufImgUsage == UINT32_MAX) - { - VMA_ASSERT(0 && "VMA_MEMORY_USAGE_AUTO* values can only be used with functions like vmaCreateBuffer, vmaCreateImage so that the details of the created resource are known."); - return false; - } - // This relies on values of VK_IMAGE_USAGE_TRANSFER* being the same VK_BUFFER_IMAGE_TRANSFER*. - const bool deviceAccess = (bufImgUsage & ~(VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT)) != 0; - const bool hostAccessSequentialWrite = (allocCreateInfo.flags & VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT) != 0; - const bool hostAccessRandom = (allocCreateInfo.flags & VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT) != 0; - const bool hostAccessAllowTransferInstead = (allocCreateInfo.flags & VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT) != 0; - const bool preferDevice = allocCreateInfo.usage == VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE; - const bool preferHost = allocCreateInfo.usage == VMA_MEMORY_USAGE_AUTO_PREFER_HOST; - - // CPU random access - e.g. a buffer written to or transferred from GPU to read back on CPU. - if(hostAccessRandom) - { - if(!isIntegratedGPU && deviceAccess && hostAccessAllowTransferInstead && !preferHost) - { - // Nice if it will end up in HOST_VISIBLE, but more importantly prefer DEVICE_LOCAL. - // Omitting HOST_VISIBLE here is intentional. - // In case there is DEVICE_LOCAL | HOST_VISIBLE | HOST_CACHED, it will pick that one. - // Otherwise, this will give same weight to DEVICE_LOCAL as HOST_VISIBLE | HOST_CACHED and select the former if occurs first on the list. - outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT; - } - else - { - // Always CPU memory, cached. - outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT; - } - } - // CPU sequential write - may be CPU or host-visible GPU memory, uncached and write-combined. - else if(hostAccessSequentialWrite) - { - // Want uncached and write-combined. - outNotPreferredFlags |= VK_MEMORY_PROPERTY_HOST_CACHED_BIT; - - if(!isIntegratedGPU && deviceAccess && hostAccessAllowTransferInstead && !preferHost) - { - outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; - } - else - { - outRequiredFlags |= VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; - // Direct GPU access, CPU sequential write (e.g. a dynamic uniform buffer updated every frame) - if(deviceAccess) - { - // Could go to CPU memory or GPU BAR/unified. Up to the user to decide. If no preference, choose GPU memory. - if(preferHost) - outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; - else - outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; - } - // GPU no direct access, CPU sequential write (e.g. an upload buffer to be transferred to the GPU) - else - { - // Could go to CPU memory or GPU BAR/unified. Up to the user to decide. If no preference, choose CPU memory. - if(preferDevice) - outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; - else - outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; - } - } - } - // No CPU access - else - { - // GPU access, no CPU access (e.g. a color attachment image) - prefer GPU memory - if(deviceAccess) - { - // ...unless there is a clear preference from the user not to do so. - if(preferHost) - outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; - else - outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; - } - // No direct GPU access, no CPU access, just transfers. - // It may be staging copy intended for e.g. preserving image for next frame (then better GPU memory) or - // a "swap file" copy to free some GPU memory (then better CPU memory). - // Up to the user to decide. If no preferece, assume the former and choose GPU memory. - if(preferHost) - outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; - else - outPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; - } - break; - } - default: - VMA_ASSERT(0); - } - - // Avoid DEVICE_COHERENT unless explicitly requested. - if(((allocCreateInfo.requiredFlags | allocCreateInfo.preferredFlags) & - (VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY | VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY)) == 0) - { - outNotPreferredFlags |= VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY; - } - - return true; -} - -//////////////////////////////////////////////////////////////////////////////// -// Memory allocation - -static void* VmaMalloc(const VkAllocationCallbacks* pAllocationCallbacks, size_t size, size_t alignment) -{ - void* result = VMA_NULL; - if ((pAllocationCallbacks != VMA_NULL) && - (pAllocationCallbacks->pfnAllocation != VMA_NULL)) - { - result = (*pAllocationCallbacks->pfnAllocation)( - pAllocationCallbacks->pUserData, - size, - alignment, - VK_SYSTEM_ALLOCATION_SCOPE_OBJECT); - } - else - { - result = VMA_SYSTEM_ALIGNED_MALLOC(size, alignment); - } - VMA_ASSERT(result != VMA_NULL && "CPU memory allocation failed."); - return result; -} - -static void VmaFree(const VkAllocationCallbacks* pAllocationCallbacks, void* ptr) -{ - if ((pAllocationCallbacks != VMA_NULL) && - (pAllocationCallbacks->pfnFree != VMA_NULL)) - { - (*pAllocationCallbacks->pfnFree)(pAllocationCallbacks->pUserData, ptr); - } - else - { - VMA_SYSTEM_ALIGNED_FREE(ptr); - } -} - -template -static T* VmaAllocate(const VkAllocationCallbacks* pAllocationCallbacks) -{ - return (T*)VmaMalloc(pAllocationCallbacks, sizeof(T), VMA_ALIGN_OF(T)); -} - -template -static T* VmaAllocateArray(const VkAllocationCallbacks* pAllocationCallbacks, size_t count) -{ - return (T*)VmaMalloc(pAllocationCallbacks, sizeof(T) * count, VMA_ALIGN_OF(T)); -} - -#define vma_new(allocator, type) new(VmaAllocate(allocator))(type) - -#define vma_new_array(allocator, type, count) new(VmaAllocateArray((allocator), (count)))(type) - -template -static void vma_delete(const VkAllocationCallbacks* pAllocationCallbacks, T* ptr) -{ - ptr->~T(); - VmaFree(pAllocationCallbacks, ptr); -} - -template -static void vma_delete_array(const VkAllocationCallbacks* pAllocationCallbacks, T* ptr, size_t count) -{ - if (ptr != VMA_NULL) - { - for (size_t i = count; i--; ) - { - ptr[i].~T(); - } - VmaFree(pAllocationCallbacks, ptr); - } -} - -static char* VmaCreateStringCopy(const VkAllocationCallbacks* allocs, const char* srcStr) -{ - if (srcStr != VMA_NULL) - { - const size_t len = strlen(srcStr); - char* const result = vma_new_array(allocs, char, len + 1); - memcpy(result, srcStr, len + 1); - return result; - } - return VMA_NULL; -} - -#if VMA_STATS_STRING_ENABLED -static char* VmaCreateStringCopy(const VkAllocationCallbacks* allocs, const char* srcStr, size_t strLen) -{ - if (srcStr != VMA_NULL) - { - char* const result = vma_new_array(allocs, char, strLen + 1); - memcpy(result, srcStr, strLen); - result[strLen] = '\0'; - return result; - } - return VMA_NULL; -} -#endif // VMA_STATS_STRING_ENABLED - -static void VmaFreeString(const VkAllocationCallbacks* allocs, char* str) -{ - if (str != VMA_NULL) - { - const size_t len = strlen(str); - vma_delete_array(allocs, str, len + 1); - } -} - -template -size_t VmaVectorInsertSorted(VectorT& vector, const typename VectorT::value_type& value) -{ - const size_t indexToInsert = VmaBinaryFindFirstNotLess( - vector.data(), - vector.data() + vector.size(), - value, - CmpLess()) - vector.data(); - VmaVectorInsert(vector, indexToInsert, value); - return indexToInsert; -} - -template -bool VmaVectorRemoveSorted(VectorT& vector, const typename VectorT::value_type& value) -{ - CmpLess comparator; - typename VectorT::iterator it = VmaBinaryFindFirstNotLess( - vector.begin(), - vector.end(), - value, - comparator); - if ((it != vector.end()) && !comparator(*it, value) && !comparator(value, *it)) - { - size_t indexToRemove = it - vector.begin(); - VmaVectorRemove(vector, indexToRemove); - return true; - } - return false; -} -#endif // _VMA_FUNCTIONS - -#ifndef _VMA_STATISTICS_FUNCTIONS - -static void VmaClearStatistics(VmaStatistics& outStats) -{ - outStats.blockCount = 0; - outStats.allocationCount = 0; - outStats.blockBytes = 0; - outStats.allocationBytes = 0; -} - -static void VmaAddStatistics(VmaStatistics& inoutStats, const VmaStatistics& src) -{ - inoutStats.blockCount += src.blockCount; - inoutStats.allocationCount += src.allocationCount; - inoutStats.blockBytes += src.blockBytes; - inoutStats.allocationBytes += src.allocationBytes; -} - -static void VmaClearDetailedStatistics(VmaDetailedStatistics& outStats) -{ - VmaClearStatistics(outStats.statistics); - outStats.unusedRangeCount = 0; - outStats.allocationSizeMin = VK_WHOLE_SIZE; - outStats.allocationSizeMax = 0; - outStats.unusedRangeSizeMin = VK_WHOLE_SIZE; - outStats.unusedRangeSizeMax = 0; -} - -static void VmaAddDetailedStatisticsAllocation(VmaDetailedStatistics& inoutStats, VkDeviceSize size) -{ - inoutStats.statistics.allocationCount++; - inoutStats.statistics.allocationBytes += size; - inoutStats.allocationSizeMin = VMA_MIN(inoutStats.allocationSizeMin, size); - inoutStats.allocationSizeMax = VMA_MAX(inoutStats.allocationSizeMax, size); -} - -static void VmaAddDetailedStatisticsUnusedRange(VmaDetailedStatistics& inoutStats, VkDeviceSize size) -{ - inoutStats.unusedRangeCount++; - inoutStats.unusedRangeSizeMin = VMA_MIN(inoutStats.unusedRangeSizeMin, size); - inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, size); -} - -static void VmaAddDetailedStatistics(VmaDetailedStatistics& inoutStats, const VmaDetailedStatistics& src) -{ - VmaAddStatistics(inoutStats.statistics, src.statistics); - inoutStats.unusedRangeCount += src.unusedRangeCount; - inoutStats.allocationSizeMin = VMA_MIN(inoutStats.allocationSizeMin, src.allocationSizeMin); - inoutStats.allocationSizeMax = VMA_MAX(inoutStats.allocationSizeMax, src.allocationSizeMax); - inoutStats.unusedRangeSizeMin = VMA_MIN(inoutStats.unusedRangeSizeMin, src.unusedRangeSizeMin); - inoutStats.unusedRangeSizeMax = VMA_MAX(inoutStats.unusedRangeSizeMax, src.unusedRangeSizeMax); -} - -#endif // _VMA_STATISTICS_FUNCTIONS - -#ifndef _VMA_MUTEX_LOCK -// Helper RAII class to lock a mutex in constructor and unlock it in destructor (at the end of scope). -struct VmaMutexLock -{ - VMA_CLASS_NO_COPY(VmaMutexLock) -public: - VmaMutexLock(VMA_MUTEX& mutex, bool useMutex = true) : - m_pMutex(useMutex ? &mutex : VMA_NULL) - { - if (m_pMutex) { m_pMutex->Lock(); } - } - ~VmaMutexLock() { if (m_pMutex) { m_pMutex->Unlock(); } } - -private: - VMA_MUTEX* m_pMutex; -}; - -// Helper RAII class to lock a RW mutex in constructor and unlock it in destructor (at the end of scope), for reading. -struct VmaMutexLockRead -{ - VMA_CLASS_NO_COPY(VmaMutexLockRead) -public: - VmaMutexLockRead(VMA_RW_MUTEX& mutex, bool useMutex) : - m_pMutex(useMutex ? &mutex : VMA_NULL) - { - if (m_pMutex) { m_pMutex->LockRead(); } - } - ~VmaMutexLockRead() { if (m_pMutex) { m_pMutex->UnlockRead(); } } - -private: - VMA_RW_MUTEX* m_pMutex; -}; - -// Helper RAII class to lock a RW mutex in constructor and unlock it in destructor (at the end of scope), for writing. -struct VmaMutexLockWrite -{ - VMA_CLASS_NO_COPY(VmaMutexLockWrite) -public: - VmaMutexLockWrite(VMA_RW_MUTEX& mutex, bool useMutex) - : m_pMutex(useMutex ? &mutex : VMA_NULL) - { - if (m_pMutex) { m_pMutex->LockWrite(); } - } - ~VmaMutexLockWrite() { if (m_pMutex) { m_pMutex->UnlockWrite(); } } - -private: - VMA_RW_MUTEX* m_pMutex; -}; - -#if VMA_DEBUG_GLOBAL_MUTEX - static VMA_MUTEX gDebugGlobalMutex; - #define VMA_DEBUG_GLOBAL_MUTEX_LOCK VmaMutexLock debugGlobalMutexLock(gDebugGlobalMutex, true); -#else - #define VMA_DEBUG_GLOBAL_MUTEX_LOCK -#endif -#endif // _VMA_MUTEX_LOCK - -#ifndef _VMA_ATOMIC_TRANSACTIONAL_INCREMENT -// An object that increments given atomic but decrements it back in the destructor unless Commit() is called. -template -struct AtomicTransactionalIncrement -{ -public: - typedef std::atomic AtomicT; - - ~AtomicTransactionalIncrement() - { - if(m_Atomic) - --(*m_Atomic); - } - - void Commit() { m_Atomic = nullptr; } - T Increment(AtomicT* atomic) - { - m_Atomic = atomic; - return m_Atomic->fetch_add(1); - } - -private: - AtomicT* m_Atomic = nullptr; -}; -#endif // _VMA_ATOMIC_TRANSACTIONAL_INCREMENT - -#ifndef _VMA_STL_ALLOCATOR -// STL-compatible allocator. -template -struct VmaStlAllocator -{ - const VkAllocationCallbacks* const m_pCallbacks; - typedef T value_type; - - VmaStlAllocator(const VkAllocationCallbacks* pCallbacks) : m_pCallbacks(pCallbacks) {} - template - VmaStlAllocator(const VmaStlAllocator& src) : m_pCallbacks(src.m_pCallbacks) {} - VmaStlAllocator(const VmaStlAllocator&) = default; - VmaStlAllocator& operator=(const VmaStlAllocator&) = delete; - - T* allocate(size_t n) { return VmaAllocateArray(m_pCallbacks, n); } - void deallocate(T* p, size_t n) { VmaFree(m_pCallbacks, p); } - - template - bool operator==(const VmaStlAllocator& rhs) const - { - return m_pCallbacks == rhs.m_pCallbacks; - } - template - bool operator!=(const VmaStlAllocator& rhs) const - { - return m_pCallbacks != rhs.m_pCallbacks; - } -}; -#endif // _VMA_STL_ALLOCATOR - -#ifndef _VMA_VECTOR -/* Class with interface compatible with subset of std::vector. -T must be POD because constructors and destructors are not called and memcpy is -used for these objects. */ -template -class VmaVector -{ -public: - typedef T value_type; - typedef T* iterator; - typedef const T* const_iterator; - - VmaVector(const AllocatorT& allocator); - VmaVector(size_t count, const AllocatorT& allocator); - // This version of the constructor is here for compatibility with pre-C++14 std::vector. - // value is unused. - VmaVector(size_t count, const T& value, const AllocatorT& allocator) : VmaVector(count, allocator) {} - VmaVector(const VmaVector& src); - VmaVector& operator=(const VmaVector& rhs); - ~VmaVector() { VmaFree(m_Allocator.m_pCallbacks, m_pArray); } - - bool empty() const { return m_Count == 0; } - size_t size() const { return m_Count; } - T* data() { return m_pArray; } - T& front() { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[0]; } - T& back() { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[m_Count - 1]; } - const T* data() const { return m_pArray; } - const T& front() const { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[0]; } - const T& back() const { VMA_HEAVY_ASSERT(m_Count > 0); return m_pArray[m_Count - 1]; } - - iterator begin() { return m_pArray; } - iterator end() { return m_pArray + m_Count; } - const_iterator cbegin() const { return m_pArray; } - const_iterator cend() const { return m_pArray + m_Count; } - const_iterator begin() const { return cbegin(); } - const_iterator end() const { return cend(); } - - void pop_front() { VMA_HEAVY_ASSERT(m_Count > 0); remove(0); } - void pop_back() { VMA_HEAVY_ASSERT(m_Count > 0); resize(size() - 1); } - void push_front(const T& src) { insert(0, src); } - - void push_back(const T& src); - void reserve(size_t newCapacity, bool freeMemory = false); - void resize(size_t newCount); - void clear() { resize(0); } - void shrink_to_fit(); - void insert(size_t index, const T& src); - void remove(size_t index); - - T& operator[](size_t index) { VMA_HEAVY_ASSERT(index < m_Count); return m_pArray[index]; } - const T& operator[](size_t index) const { VMA_HEAVY_ASSERT(index < m_Count); return m_pArray[index]; } - -private: - AllocatorT m_Allocator; - T* m_pArray; - size_t m_Count; - size_t m_Capacity; -}; - -#ifndef _VMA_VECTOR_FUNCTIONS -template -VmaVector::VmaVector(const AllocatorT& allocator) - : m_Allocator(allocator), - m_pArray(VMA_NULL), - m_Count(0), - m_Capacity(0) {} - -template -VmaVector::VmaVector(size_t count, const AllocatorT& allocator) - : m_Allocator(allocator), - m_pArray(count ? (T*)VmaAllocateArray(allocator.m_pCallbacks, count) : VMA_NULL), - m_Count(count), - m_Capacity(count) {} - -template -VmaVector::VmaVector(const VmaVector& src) - : m_Allocator(src.m_Allocator), - m_pArray(src.m_Count ? (T*)VmaAllocateArray(src.m_Allocator.m_pCallbacks, src.m_Count) : VMA_NULL), - m_Count(src.m_Count), - m_Capacity(src.m_Count) -{ - if (m_Count != 0) - { - memcpy(m_pArray, src.m_pArray, m_Count * sizeof(T)); - } -} - -template -VmaVector& VmaVector::operator=(const VmaVector& rhs) -{ - if (&rhs != this) - { - resize(rhs.m_Count); - if (m_Count != 0) - { - memcpy(m_pArray, rhs.m_pArray, m_Count * sizeof(T)); - } - } - return *this; -} - -template -void VmaVector::push_back(const T& src) -{ - const size_t newIndex = size(); - resize(newIndex + 1); - m_pArray[newIndex] = src; -} - -template -void VmaVector::reserve(size_t newCapacity, bool freeMemory) -{ - newCapacity = VMA_MAX(newCapacity, m_Count); - - if ((newCapacity < m_Capacity) && !freeMemory) - { - newCapacity = m_Capacity; - } - - if (newCapacity != m_Capacity) - { - T* const newArray = newCapacity ? VmaAllocateArray(m_Allocator, newCapacity) : VMA_NULL; - if (m_Count != 0) - { - memcpy(newArray, m_pArray, m_Count * sizeof(T)); - } - VmaFree(m_Allocator.m_pCallbacks, m_pArray); - m_Capacity = newCapacity; - m_pArray = newArray; - } -} - -template -void VmaVector::resize(size_t newCount) -{ - size_t newCapacity = m_Capacity; - if (newCount > m_Capacity) - { - newCapacity = VMA_MAX(newCount, VMA_MAX(m_Capacity * 3 / 2, (size_t)8)); - } - - if (newCapacity != m_Capacity) - { - T* const newArray = newCapacity ? VmaAllocateArray(m_Allocator.m_pCallbacks, newCapacity) : VMA_NULL; - const size_t elementsToCopy = VMA_MIN(m_Count, newCount); - if (elementsToCopy != 0) - { - memcpy(newArray, m_pArray, elementsToCopy * sizeof(T)); - } - VmaFree(m_Allocator.m_pCallbacks, m_pArray); - m_Capacity = newCapacity; - m_pArray = newArray; - } - - m_Count = newCount; -} - -template -void VmaVector::shrink_to_fit() -{ - if (m_Capacity > m_Count) - { - T* newArray = VMA_NULL; - if (m_Count > 0) - { - newArray = VmaAllocateArray(m_Allocator.m_pCallbacks, m_Count); - memcpy(newArray, m_pArray, m_Count * sizeof(T)); - } - VmaFree(m_Allocator.m_pCallbacks, m_pArray); - m_Capacity = m_Count; - m_pArray = newArray; - } -} - -template -void VmaVector::insert(size_t index, const T& src) -{ - VMA_HEAVY_ASSERT(index <= m_Count); - const size_t oldCount = size(); - resize(oldCount + 1); - if (index < oldCount) - { - memmove(m_pArray + (index + 1), m_pArray + index, (oldCount - index) * sizeof(T)); - } - m_pArray[index] = src; -} - -template -void VmaVector::remove(size_t index) -{ - VMA_HEAVY_ASSERT(index < m_Count); - const size_t oldCount = size(); - if (index < oldCount - 1) - { - memmove(m_pArray + index, m_pArray + (index + 1), (oldCount - index - 1) * sizeof(T)); - } - resize(oldCount - 1); -} -#endif // _VMA_VECTOR_FUNCTIONS - -template -static void VmaVectorInsert(VmaVector& vec, size_t index, const T& item) -{ - vec.insert(index, item); -} - -template -static void VmaVectorRemove(VmaVector& vec, size_t index) -{ - vec.remove(index); -} -#endif // _VMA_VECTOR - -#ifndef _VMA_SMALL_VECTOR -/* -This is a vector (a variable-sized array), optimized for the case when the array is small. - -It contains some number of elements in-place, which allows it to avoid heap allocation -when the actual number of elements is below that threshold. This allows normal "small" -cases to be fast without losing generality for large inputs. -*/ -template -class VmaSmallVector -{ -public: - typedef T value_type; - typedef T* iterator; - - VmaSmallVector(const AllocatorT& allocator); - VmaSmallVector(size_t count, const AllocatorT& allocator); - template - VmaSmallVector(const VmaSmallVector&) = delete; - template - VmaSmallVector& operator=(const VmaSmallVector&) = delete; - ~VmaSmallVector() = default; - - bool empty() const { return m_Count == 0; } - size_t size() const { return m_Count; } - T* data() { return m_Count > N ? m_DynamicArray.data() : m_StaticArray; } - T& front() { VMA_HEAVY_ASSERT(m_Count > 0); return data()[0]; } - T& back() { VMA_HEAVY_ASSERT(m_Count > 0); return data()[m_Count - 1]; } - const T* data() const { return m_Count > N ? m_DynamicArray.data() : m_StaticArray; } - const T& front() const { VMA_HEAVY_ASSERT(m_Count > 0); return data()[0]; } - const T& back() const { VMA_HEAVY_ASSERT(m_Count > 0); return data()[m_Count - 1]; } - - iterator begin() { return data(); } - iterator end() { return data() + m_Count; } - - void pop_front() { VMA_HEAVY_ASSERT(m_Count > 0); remove(0); } - void pop_back() { VMA_HEAVY_ASSERT(m_Count > 0); resize(size() - 1); } - void push_front(const T& src) { insert(0, src); } - - void push_back(const T& src); - void resize(size_t newCount, bool freeMemory = false); - void clear(bool freeMemory = false); - void insert(size_t index, const T& src); - void remove(size_t index); - - T& operator[](size_t index) { VMA_HEAVY_ASSERT(index < m_Count); return data()[index]; } - const T& operator[](size_t index) const { VMA_HEAVY_ASSERT(index < m_Count); return data()[index]; } - -private: - size_t m_Count; - T m_StaticArray[N]; // Used when m_Size <= N - VmaVector m_DynamicArray; // Used when m_Size > N -}; - -#ifndef _VMA_SMALL_VECTOR_FUNCTIONS -template -VmaSmallVector::VmaSmallVector(const AllocatorT& allocator) - : m_Count(0), - m_DynamicArray(allocator) {} - -template -VmaSmallVector::VmaSmallVector(size_t count, const AllocatorT& allocator) - : m_Count(count), - m_DynamicArray(count > N ? count : 0, allocator) {} - -template -void VmaSmallVector::push_back(const T& src) -{ - const size_t newIndex = size(); - resize(newIndex + 1); - data()[newIndex] = src; -} - -template -void VmaSmallVector::resize(size_t newCount, bool freeMemory) -{ - if (newCount > N && m_Count > N) - { - // Any direction, staying in m_DynamicArray - m_DynamicArray.resize(newCount); - if (freeMemory) - { - m_DynamicArray.shrink_to_fit(); - } - } - else if (newCount > N && m_Count <= N) - { - // Growing, moving from m_StaticArray to m_DynamicArray - m_DynamicArray.resize(newCount); - if (m_Count > 0) - { - memcpy(m_DynamicArray.data(), m_StaticArray, m_Count * sizeof(T)); - } - } - else if (newCount <= N && m_Count > N) - { - // Shrinking, moving from m_DynamicArray to m_StaticArray - if (newCount > 0) - { - memcpy(m_StaticArray, m_DynamicArray.data(), newCount * sizeof(T)); - } - m_DynamicArray.resize(0); - if (freeMemory) - { - m_DynamicArray.shrink_to_fit(); - } - } - else - { - // Any direction, staying in m_StaticArray - nothing to do here - } - m_Count = newCount; -} - -template -void VmaSmallVector::clear(bool freeMemory) -{ - m_DynamicArray.clear(); - if (freeMemory) - { - m_DynamicArray.shrink_to_fit(); - } - m_Count = 0; -} - -template -void VmaSmallVector::insert(size_t index, const T& src) -{ - VMA_HEAVY_ASSERT(index <= m_Count); - const size_t oldCount = size(); - resize(oldCount + 1); - T* const dataPtr = data(); - if (index < oldCount) - { - // I know, this could be more optimal for case where memmove can be memcpy directly from m_StaticArray to m_DynamicArray. - memmove(dataPtr + (index + 1), dataPtr + index, (oldCount - index) * sizeof(T)); - } - dataPtr[index] = src; -} - -template -void VmaSmallVector::remove(size_t index) -{ - VMA_HEAVY_ASSERT(index < m_Count); - const size_t oldCount = size(); - if (index < oldCount - 1) - { - // I know, this could be more optimal for case where memmove can be memcpy directly from m_DynamicArray to m_StaticArray. - T* const dataPtr = data(); - memmove(dataPtr + index, dataPtr + (index + 1), (oldCount - index - 1) * sizeof(T)); - } - resize(oldCount - 1); -} -#endif // _VMA_SMALL_VECTOR_FUNCTIONS -#endif // _VMA_SMALL_VECTOR - -#ifndef _VMA_POOL_ALLOCATOR -/* -Allocator for objects of type T using a list of arrays (pools) to speed up -allocation. Number of elements that can be allocated is not bounded because -allocator can create multiple blocks. -*/ -template -class VmaPoolAllocator -{ - VMA_CLASS_NO_COPY(VmaPoolAllocator) -public: - VmaPoolAllocator(const VkAllocationCallbacks* pAllocationCallbacks, uint32_t firstBlockCapacity); - ~VmaPoolAllocator(); - template T* Alloc(Types&&... args); - void Free(T* ptr); - -private: - union Item - { - uint32_t NextFreeIndex; - alignas(T) char Value[sizeof(T)]; - }; - struct ItemBlock - { - Item* pItems; - uint32_t Capacity; - uint32_t FirstFreeIndex; - }; - - const VkAllocationCallbacks* m_pAllocationCallbacks; - const uint32_t m_FirstBlockCapacity; - VmaVector> m_ItemBlocks; - - ItemBlock& CreateNewBlock(); -}; - -#ifndef _VMA_POOL_ALLOCATOR_FUNCTIONS -template -VmaPoolAllocator::VmaPoolAllocator(const VkAllocationCallbacks* pAllocationCallbacks, uint32_t firstBlockCapacity) - : m_pAllocationCallbacks(pAllocationCallbacks), - m_FirstBlockCapacity(firstBlockCapacity), - m_ItemBlocks(VmaStlAllocator(pAllocationCallbacks)) -{ - VMA_ASSERT(m_FirstBlockCapacity > 1); -} - -template -VmaPoolAllocator::~VmaPoolAllocator() -{ - for (size_t i = m_ItemBlocks.size(); i--;) - vma_delete_array(m_pAllocationCallbacks, m_ItemBlocks[i].pItems, m_ItemBlocks[i].Capacity); - m_ItemBlocks.clear(); -} - -template -template T* VmaPoolAllocator::Alloc(Types&&... args) -{ - for (size_t i = m_ItemBlocks.size(); i--; ) - { - ItemBlock& block = m_ItemBlocks[i]; - // This block has some free items: Use first one. - if (block.FirstFreeIndex != UINT32_MAX) - { - Item* const pItem = &block.pItems[block.FirstFreeIndex]; - block.FirstFreeIndex = pItem->NextFreeIndex; - T* result = (T*)&pItem->Value; - new(result)T(std::forward(args)...); // Explicit constructor call. - return result; - } - } - - // No block has free item: Create new one and use it. - ItemBlock& newBlock = CreateNewBlock(); - Item* const pItem = &newBlock.pItems[0]; - newBlock.FirstFreeIndex = pItem->NextFreeIndex; - T* result = (T*)&pItem->Value; - new(result) T(std::forward(args)...); // Explicit constructor call. - return result; -} - -template -void VmaPoolAllocator::Free(T* ptr) -{ - // Search all memory blocks to find ptr. - for (size_t i = m_ItemBlocks.size(); i--; ) - { - ItemBlock& block = m_ItemBlocks[i]; - - // Casting to union. - Item* pItemPtr; - memcpy(&pItemPtr, &ptr, sizeof(pItemPtr)); - - // Check if pItemPtr is in address range of this block. - if ((pItemPtr >= block.pItems) && (pItemPtr < block.pItems + block.Capacity)) - { - ptr->~T(); // Explicit destructor call. - const uint32_t index = static_cast(pItemPtr - block.pItems); - pItemPtr->NextFreeIndex = block.FirstFreeIndex; - block.FirstFreeIndex = index; - return; - } - } - VMA_ASSERT(0 && "Pointer doesn't belong to this memory pool."); -} - -template -typename VmaPoolAllocator::ItemBlock& VmaPoolAllocator::CreateNewBlock() -{ - const uint32_t newBlockCapacity = m_ItemBlocks.empty() ? - m_FirstBlockCapacity : m_ItemBlocks.back().Capacity * 3 / 2; - - const ItemBlock newBlock = - { - vma_new_array(m_pAllocationCallbacks, Item, newBlockCapacity), - newBlockCapacity, - 0 - }; - - m_ItemBlocks.push_back(newBlock); - - // Setup singly-linked list of all free items in this block. - for (uint32_t i = 0; i < newBlockCapacity - 1; ++i) - newBlock.pItems[i].NextFreeIndex = i + 1; - newBlock.pItems[newBlockCapacity - 1].NextFreeIndex = UINT32_MAX; - return m_ItemBlocks.back(); -} -#endif // _VMA_POOL_ALLOCATOR_FUNCTIONS -#endif // _VMA_POOL_ALLOCATOR - -#ifndef _VMA_RAW_LIST -template -struct VmaListItem -{ - VmaListItem* pPrev; - VmaListItem* pNext; - T Value; -}; - -// Doubly linked list. -template -class VmaRawList -{ - VMA_CLASS_NO_COPY(VmaRawList) -public: - typedef VmaListItem ItemType; - - VmaRawList(const VkAllocationCallbacks* pAllocationCallbacks); - // Intentionally not calling Clear, because that would be unnecessary - // computations to return all items to m_ItemAllocator as free. - ~VmaRawList() = default; - - size_t GetCount() const { return m_Count; } - bool IsEmpty() const { return m_Count == 0; } - - ItemType* Front() { return m_pFront; } - ItemType* Back() { return m_pBack; } - const ItemType* Front() const { return m_pFront; } - const ItemType* Back() const { return m_pBack; } - - ItemType* PushFront(); - ItemType* PushBack(); - ItemType* PushFront(const T& value); - ItemType* PushBack(const T& value); - void PopFront(); - void PopBack(); - - // Item can be null - it means PushBack. - ItemType* InsertBefore(ItemType* pItem); - // Item can be null - it means PushFront. - ItemType* InsertAfter(ItemType* pItem); - ItemType* InsertBefore(ItemType* pItem, const T& value); - ItemType* InsertAfter(ItemType* pItem, const T& value); - - void Clear(); - void Remove(ItemType* pItem); - -private: - const VkAllocationCallbacks* const m_pAllocationCallbacks; - VmaPoolAllocator m_ItemAllocator; - ItemType* m_pFront; - ItemType* m_pBack; - size_t m_Count; -}; - -#ifndef _VMA_RAW_LIST_FUNCTIONS -template -VmaRawList::VmaRawList(const VkAllocationCallbacks* pAllocationCallbacks) - : m_pAllocationCallbacks(pAllocationCallbacks), - m_ItemAllocator(pAllocationCallbacks, 128), - m_pFront(VMA_NULL), - m_pBack(VMA_NULL), - m_Count(0) {} - -template -VmaListItem* VmaRawList::PushFront() -{ - ItemType* const pNewItem = m_ItemAllocator.Alloc(); - pNewItem->pPrev = VMA_NULL; - if (IsEmpty()) - { - pNewItem->pNext = VMA_NULL; - m_pFront = pNewItem; - m_pBack = pNewItem; - m_Count = 1; - } - else - { - pNewItem->pNext = m_pFront; - m_pFront->pPrev = pNewItem; - m_pFront = pNewItem; - ++m_Count; - } - return pNewItem; -} - -template -VmaListItem* VmaRawList::PushBack() -{ - ItemType* const pNewItem = m_ItemAllocator.Alloc(); - pNewItem->pNext = VMA_NULL; - if(IsEmpty()) - { - pNewItem->pPrev = VMA_NULL; - m_pFront = pNewItem; - m_pBack = pNewItem; - m_Count = 1; - } - else - { - pNewItem->pPrev = m_pBack; - m_pBack->pNext = pNewItem; - m_pBack = pNewItem; - ++m_Count; - } - return pNewItem; -} - -template -VmaListItem* VmaRawList::PushFront(const T& value) -{ - ItemType* const pNewItem = PushFront(); - pNewItem->Value = value; - return pNewItem; -} - -template -VmaListItem* VmaRawList::PushBack(const T& value) -{ - ItemType* const pNewItem = PushBack(); - pNewItem->Value = value; - return pNewItem; -} - -template -void VmaRawList::PopFront() -{ - VMA_HEAVY_ASSERT(m_Count > 0); - ItemType* const pFrontItem = m_pFront; - ItemType* const pNextItem = pFrontItem->pNext; - if (pNextItem != VMA_NULL) - { - pNextItem->pPrev = VMA_NULL; - } - m_pFront = pNextItem; - m_ItemAllocator.Free(pFrontItem); - --m_Count; -} - -template -void VmaRawList::PopBack() -{ - VMA_HEAVY_ASSERT(m_Count > 0); - ItemType* const pBackItem = m_pBack; - ItemType* const pPrevItem = pBackItem->pPrev; - if(pPrevItem != VMA_NULL) - { - pPrevItem->pNext = VMA_NULL; - } - m_pBack = pPrevItem; - m_ItemAllocator.Free(pBackItem); - --m_Count; -} - -template -void VmaRawList::Clear() -{ - if (IsEmpty() == false) - { - ItemType* pItem = m_pBack; - while (pItem != VMA_NULL) - { - ItemType* const pPrevItem = pItem->pPrev; - m_ItemAllocator.Free(pItem); - pItem = pPrevItem; - } - m_pFront = VMA_NULL; - m_pBack = VMA_NULL; - m_Count = 0; - } -} - -template -void VmaRawList::Remove(ItemType* pItem) -{ - VMA_HEAVY_ASSERT(pItem != VMA_NULL); - VMA_HEAVY_ASSERT(m_Count > 0); - - if(pItem->pPrev != VMA_NULL) - { - pItem->pPrev->pNext = pItem->pNext; - } - else - { - VMA_HEAVY_ASSERT(m_pFront == pItem); - m_pFront = pItem->pNext; - } - - if(pItem->pNext != VMA_NULL) - { - pItem->pNext->pPrev = pItem->pPrev; - } - else - { - VMA_HEAVY_ASSERT(m_pBack == pItem); - m_pBack = pItem->pPrev; - } - - m_ItemAllocator.Free(pItem); - --m_Count; -} - -template -VmaListItem* VmaRawList::InsertBefore(ItemType* pItem) -{ - if(pItem != VMA_NULL) - { - ItemType* const prevItem = pItem->pPrev; - ItemType* const newItem = m_ItemAllocator.Alloc(); - newItem->pPrev = prevItem; - newItem->pNext = pItem; - pItem->pPrev = newItem; - if(prevItem != VMA_NULL) - { - prevItem->pNext = newItem; - } - else - { - VMA_HEAVY_ASSERT(m_pFront == pItem); - m_pFront = newItem; - } - ++m_Count; - return newItem; - } - else - return PushBack(); -} - -template -VmaListItem* VmaRawList::InsertAfter(ItemType* pItem) -{ - if(pItem != VMA_NULL) - { - ItemType* const nextItem = pItem->pNext; - ItemType* const newItem = m_ItemAllocator.Alloc(); - newItem->pNext = nextItem; - newItem->pPrev = pItem; - pItem->pNext = newItem; - if(nextItem != VMA_NULL) - { - nextItem->pPrev = newItem; - } - else - { - VMA_HEAVY_ASSERT(m_pBack == pItem); - m_pBack = newItem; - } - ++m_Count; - return newItem; - } - else - return PushFront(); -} - -template -VmaListItem* VmaRawList::InsertBefore(ItemType* pItem, const T& value) -{ - ItemType* const newItem = InsertBefore(pItem); - newItem->Value = value; - return newItem; -} - -template -VmaListItem* VmaRawList::InsertAfter(ItemType* pItem, const T& value) -{ - ItemType* const newItem = InsertAfter(pItem); - newItem->Value = value; - return newItem; -} -#endif // _VMA_RAW_LIST_FUNCTIONS -#endif // _VMA_RAW_LIST - -#ifndef _VMA_LIST -template -class VmaList -{ - VMA_CLASS_NO_COPY(VmaList) -public: - class reverse_iterator; - class const_iterator; - class const_reverse_iterator; - - class iterator - { - friend class const_iterator; - friend class VmaList; - public: - iterator() : m_pList(VMA_NULL), m_pItem(VMA_NULL) {} - iterator(const reverse_iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {} - - T& operator*() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return m_pItem->Value; } - T* operator->() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return &m_pItem->Value; } - - bool operator==(const iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem == rhs.m_pItem; } - bool operator!=(const iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem != rhs.m_pItem; } - - iterator operator++(int) { iterator result = *this; ++*this; return result; } - iterator operator--(int) { iterator result = *this; --*this; return result; } - - iterator& operator++() { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); m_pItem = m_pItem->pNext; return *this; } - iterator& operator--(); - - private: - VmaRawList* m_pList; - VmaListItem* m_pItem; - - iterator(VmaRawList* pList, VmaListItem* pItem) : m_pList(pList), m_pItem(pItem) {} - }; - class reverse_iterator - { - friend class const_reverse_iterator; - friend class VmaList; - public: - reverse_iterator() : m_pList(VMA_NULL), m_pItem(VMA_NULL) {} - reverse_iterator(const iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {} - - T& operator*() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return m_pItem->Value; } - T* operator->() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return &m_pItem->Value; } - - bool operator==(const reverse_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem == rhs.m_pItem; } - bool operator!=(const reverse_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem != rhs.m_pItem; } - - reverse_iterator operator++(int) { reverse_iterator result = *this; ++* this; return result; } - reverse_iterator operator--(int) { reverse_iterator result = *this; --* this; return result; } - - reverse_iterator& operator++() { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); m_pItem = m_pItem->pPrev; return *this; } - reverse_iterator& operator--(); - - private: - VmaRawList* m_pList; - VmaListItem* m_pItem; - - reverse_iterator(VmaRawList* pList, VmaListItem* pItem) : m_pList(pList), m_pItem(pItem) {} - }; - class const_iterator - { - friend class VmaList; - public: - const_iterator() : m_pList(VMA_NULL), m_pItem(VMA_NULL) {} - const_iterator(const iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {} - const_iterator(const reverse_iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {} - - iterator drop_const() { return { const_cast*>(m_pList), const_cast*>(m_pItem) }; } - - const T& operator*() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return m_pItem->Value; } - const T* operator->() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return &m_pItem->Value; } - - bool operator==(const const_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem == rhs.m_pItem; } - bool operator!=(const const_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem != rhs.m_pItem; } - - const_iterator operator++(int) { const_iterator result = *this; ++* this; return result; } - const_iterator operator--(int) { const_iterator result = *this; --* this; return result; } - - const_iterator& operator++() { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); m_pItem = m_pItem->pNext; return *this; } - const_iterator& operator--(); - - private: - const VmaRawList* m_pList; - const VmaListItem* m_pItem; - - const_iterator(const VmaRawList* pList, const VmaListItem* pItem) : m_pList(pList), m_pItem(pItem) {} - }; - class const_reverse_iterator - { - friend class VmaList; - public: - const_reverse_iterator() : m_pList(VMA_NULL), m_pItem(VMA_NULL) {} - const_reverse_iterator(const reverse_iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {} - const_reverse_iterator(const iterator& src) : m_pList(src.m_pList), m_pItem(src.m_pItem) {} - - reverse_iterator drop_const() { return { const_cast*>(m_pList), const_cast*>(m_pItem) }; } - - const T& operator*() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return m_pItem->Value; } - const T* operator->() const { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); return &m_pItem->Value; } - - bool operator==(const const_reverse_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem == rhs.m_pItem; } - bool operator!=(const const_reverse_iterator& rhs) const { VMA_HEAVY_ASSERT(m_pList == rhs.m_pList); return m_pItem != rhs.m_pItem; } - - const_reverse_iterator operator++(int) { const_reverse_iterator result = *this; ++* this; return result; } - const_reverse_iterator operator--(int) { const_reverse_iterator result = *this; --* this; return result; } - - const_reverse_iterator& operator++() { VMA_HEAVY_ASSERT(m_pItem != VMA_NULL); m_pItem = m_pItem->pPrev; return *this; } - const_reverse_iterator& operator--(); - - private: - const VmaRawList* m_pList; - const VmaListItem* m_pItem; - - const_reverse_iterator(const VmaRawList* pList, const VmaListItem* pItem) : m_pList(pList), m_pItem(pItem) {} - }; - - VmaList(const AllocatorT& allocator) : m_RawList(allocator.m_pCallbacks) {} - - bool empty() const { return m_RawList.IsEmpty(); } - size_t size() const { return m_RawList.GetCount(); } - - iterator begin() { return iterator(&m_RawList, m_RawList.Front()); } - iterator end() { return iterator(&m_RawList, VMA_NULL); } - - const_iterator cbegin() const { return const_iterator(&m_RawList, m_RawList.Front()); } - const_iterator cend() const { return const_iterator(&m_RawList, VMA_NULL); } - - const_iterator begin() const { return cbegin(); } - const_iterator end() const { return cend(); } - - reverse_iterator rbegin() { return reverse_iterator(&m_RawList, m_RawList.Back()); } - reverse_iterator rend() { return reverse_iterator(&m_RawList, VMA_NULL); } - - const_reverse_iterator crbegin() const { return const_reverse_iterator(&m_RawList, m_RawList.Back()); } - const_reverse_iterator crend() const { return const_reverse_iterator(&m_RawList, VMA_NULL); } - - const_reverse_iterator rbegin() const { return crbegin(); } - const_reverse_iterator rend() const { return crend(); } - - void push_back(const T& value) { m_RawList.PushBack(value); } - iterator insert(iterator it, const T& value) { return iterator(&m_RawList, m_RawList.InsertBefore(it.m_pItem, value)); } - - void clear() { m_RawList.Clear(); } - void erase(iterator it) { m_RawList.Remove(it.m_pItem); } - -private: - VmaRawList m_RawList; -}; - -#ifndef _VMA_LIST_FUNCTIONS -template -typename VmaList::iterator& VmaList::iterator::operator--() -{ - if (m_pItem != VMA_NULL) - { - m_pItem = m_pItem->pPrev; - } - else - { - VMA_HEAVY_ASSERT(!m_pList->IsEmpty()); - m_pItem = m_pList->Back(); - } - return *this; -} - -template -typename VmaList::reverse_iterator& VmaList::reverse_iterator::operator--() -{ - if (m_pItem != VMA_NULL) - { - m_pItem = m_pItem->pNext; - } - else - { - VMA_HEAVY_ASSERT(!m_pList->IsEmpty()); - m_pItem = m_pList->Front(); - } - return *this; -} - -template -typename VmaList::const_iterator& VmaList::const_iterator::operator--() -{ - if (m_pItem != VMA_NULL) - { - m_pItem = m_pItem->pPrev; - } - else - { - VMA_HEAVY_ASSERT(!m_pList->IsEmpty()); - m_pItem = m_pList->Back(); - } - return *this; -} - -template -typename VmaList::const_reverse_iterator& VmaList::const_reverse_iterator::operator--() -{ - if (m_pItem != VMA_NULL) - { - m_pItem = m_pItem->pNext; - } - else - { - VMA_HEAVY_ASSERT(!m_pList->IsEmpty()); - m_pItem = m_pList->Back(); - } - return *this; -} -#endif // _VMA_LIST_FUNCTIONS -#endif // _VMA_LIST - -#ifndef _VMA_INTRUSIVE_LINKED_LIST -/* -Expected interface of ItemTypeTraits: -struct MyItemTypeTraits -{ - typedef MyItem ItemType; - static ItemType* GetPrev(const ItemType* item) { return item->myPrevPtr; } - static ItemType* GetNext(const ItemType* item) { return item->myNextPtr; } - static ItemType*& AccessPrev(ItemType* item) { return item->myPrevPtr; } - static ItemType*& AccessNext(ItemType* item) { return item->myNextPtr; } -}; -*/ -template -class VmaIntrusiveLinkedList -{ -public: - typedef typename ItemTypeTraits::ItemType ItemType; - static ItemType* GetPrev(const ItemType* item) { return ItemTypeTraits::GetPrev(item); } - static ItemType* GetNext(const ItemType* item) { return ItemTypeTraits::GetNext(item); } - - // Movable, not copyable. - VmaIntrusiveLinkedList() = default; - VmaIntrusiveLinkedList(VmaIntrusiveLinkedList && src); - VmaIntrusiveLinkedList(const VmaIntrusiveLinkedList&) = delete; - VmaIntrusiveLinkedList& operator=(VmaIntrusiveLinkedList&& src); - VmaIntrusiveLinkedList& operator=(const VmaIntrusiveLinkedList&) = delete; - ~VmaIntrusiveLinkedList() { VMA_HEAVY_ASSERT(IsEmpty()); } - - size_t GetCount() const { return m_Count; } - bool IsEmpty() const { return m_Count == 0; } - ItemType* Front() { return m_Front; } - ItemType* Back() { return m_Back; } - const ItemType* Front() const { return m_Front; } - const ItemType* Back() const { return m_Back; } - - void PushBack(ItemType* item); - void PushFront(ItemType* item); - ItemType* PopBack(); - ItemType* PopFront(); - - // MyItem can be null - it means PushBack. - void InsertBefore(ItemType* existingItem, ItemType* newItem); - // MyItem can be null - it means PushFront. - void InsertAfter(ItemType* existingItem, ItemType* newItem); - void Remove(ItemType* item); - void RemoveAll(); - -private: - ItemType* m_Front = VMA_NULL; - ItemType* m_Back = VMA_NULL; - size_t m_Count = 0; -}; - -#ifndef _VMA_INTRUSIVE_LINKED_LIST_FUNCTIONS -template -VmaIntrusiveLinkedList::VmaIntrusiveLinkedList(VmaIntrusiveLinkedList&& src) - : m_Front(src.m_Front), m_Back(src.m_Back), m_Count(src.m_Count) -{ - src.m_Front = src.m_Back = VMA_NULL; - src.m_Count = 0; -} - -template -VmaIntrusiveLinkedList& VmaIntrusiveLinkedList::operator=(VmaIntrusiveLinkedList&& src) -{ - if (&src != this) - { - VMA_HEAVY_ASSERT(IsEmpty()); - m_Front = src.m_Front; - m_Back = src.m_Back; - m_Count = src.m_Count; - src.m_Front = src.m_Back = VMA_NULL; - src.m_Count = 0; - } - return *this; -} - -template -void VmaIntrusiveLinkedList::PushBack(ItemType* item) -{ - VMA_HEAVY_ASSERT(ItemTypeTraits::GetPrev(item) == VMA_NULL && ItemTypeTraits::GetNext(item) == VMA_NULL); - if (IsEmpty()) - { - m_Front = item; - m_Back = item; - m_Count = 1; - } - else - { - ItemTypeTraits::AccessPrev(item) = m_Back; - ItemTypeTraits::AccessNext(m_Back) = item; - m_Back = item; - ++m_Count; - } -} - -template -void VmaIntrusiveLinkedList::PushFront(ItemType* item) -{ - VMA_HEAVY_ASSERT(ItemTypeTraits::GetPrev(item) == VMA_NULL && ItemTypeTraits::GetNext(item) == VMA_NULL); - if (IsEmpty()) - { - m_Front = item; - m_Back = item; - m_Count = 1; - } - else - { - ItemTypeTraits::AccessNext(item) = m_Front; - ItemTypeTraits::AccessPrev(m_Front) = item; - m_Front = item; - ++m_Count; - } -} - -template -typename VmaIntrusiveLinkedList::ItemType* VmaIntrusiveLinkedList::PopBack() -{ - VMA_HEAVY_ASSERT(m_Count > 0); - ItemType* const backItem = m_Back; - ItemType* const prevItem = ItemTypeTraits::GetPrev(backItem); - if (prevItem != VMA_NULL) - { - ItemTypeTraits::AccessNext(prevItem) = VMA_NULL; - } - m_Back = prevItem; - --m_Count; - ItemTypeTraits::AccessPrev(backItem) = VMA_NULL; - ItemTypeTraits::AccessNext(backItem) = VMA_NULL; - return backItem; -} - -template -typename VmaIntrusiveLinkedList::ItemType* VmaIntrusiveLinkedList::PopFront() -{ - VMA_HEAVY_ASSERT(m_Count > 0); - ItemType* const frontItem = m_Front; - ItemType* const nextItem = ItemTypeTraits::GetNext(frontItem); - if (nextItem != VMA_NULL) - { - ItemTypeTraits::AccessPrev(nextItem) = VMA_NULL; - } - m_Front = nextItem; - --m_Count; - ItemTypeTraits::AccessPrev(frontItem) = VMA_NULL; - ItemTypeTraits::AccessNext(frontItem) = VMA_NULL; - return frontItem; -} - -template -void VmaIntrusiveLinkedList::InsertBefore(ItemType* existingItem, ItemType* newItem) -{ - VMA_HEAVY_ASSERT(newItem != VMA_NULL && ItemTypeTraits::GetPrev(newItem) == VMA_NULL && ItemTypeTraits::GetNext(newItem) == VMA_NULL); - if (existingItem != VMA_NULL) - { - ItemType* const prevItem = ItemTypeTraits::GetPrev(existingItem); - ItemTypeTraits::AccessPrev(newItem) = prevItem; - ItemTypeTraits::AccessNext(newItem) = existingItem; - ItemTypeTraits::AccessPrev(existingItem) = newItem; - if (prevItem != VMA_NULL) - { - ItemTypeTraits::AccessNext(prevItem) = newItem; - } - else - { - VMA_HEAVY_ASSERT(m_Front == existingItem); - m_Front = newItem; - } - ++m_Count; - } - else - PushBack(newItem); -} - -template -void VmaIntrusiveLinkedList::InsertAfter(ItemType* existingItem, ItemType* newItem) -{ - VMA_HEAVY_ASSERT(newItem != VMA_NULL && ItemTypeTraits::GetPrev(newItem) == VMA_NULL && ItemTypeTraits::GetNext(newItem) == VMA_NULL); - if (existingItem != VMA_NULL) - { - ItemType* const nextItem = ItemTypeTraits::GetNext(existingItem); - ItemTypeTraits::AccessNext(newItem) = nextItem; - ItemTypeTraits::AccessPrev(newItem) = existingItem; - ItemTypeTraits::AccessNext(existingItem) = newItem; - if (nextItem != VMA_NULL) - { - ItemTypeTraits::AccessPrev(nextItem) = newItem; - } - else - { - VMA_HEAVY_ASSERT(m_Back == existingItem); - m_Back = newItem; - } - ++m_Count; - } - else - return PushFront(newItem); -} - -template -void VmaIntrusiveLinkedList::Remove(ItemType* item) -{ - VMA_HEAVY_ASSERT(item != VMA_NULL && m_Count > 0); - if (ItemTypeTraits::GetPrev(item) != VMA_NULL) - { - ItemTypeTraits::AccessNext(ItemTypeTraits::AccessPrev(item)) = ItemTypeTraits::GetNext(item); - } - else - { - VMA_HEAVY_ASSERT(m_Front == item); - m_Front = ItemTypeTraits::GetNext(item); - } - - if (ItemTypeTraits::GetNext(item) != VMA_NULL) - { - ItemTypeTraits::AccessPrev(ItemTypeTraits::AccessNext(item)) = ItemTypeTraits::GetPrev(item); - } - else - { - VMA_HEAVY_ASSERT(m_Back == item); - m_Back = ItemTypeTraits::GetPrev(item); - } - ItemTypeTraits::AccessPrev(item) = VMA_NULL; - ItemTypeTraits::AccessNext(item) = VMA_NULL; - --m_Count; -} - -template -void VmaIntrusiveLinkedList::RemoveAll() -{ - if (!IsEmpty()) - { - ItemType* item = m_Back; - while (item != VMA_NULL) - { - ItemType* const prevItem = ItemTypeTraits::AccessPrev(item); - ItemTypeTraits::AccessPrev(item) = VMA_NULL; - ItemTypeTraits::AccessNext(item) = VMA_NULL; - item = prevItem; - } - m_Front = VMA_NULL; - m_Back = VMA_NULL; - m_Count = 0; - } -} -#endif // _VMA_INTRUSIVE_LINKED_LIST_FUNCTIONS -#endif // _VMA_INTRUSIVE_LINKED_LIST - -// Unused in this version. -#if 0 - -#ifndef _VMA_PAIR -template -struct VmaPair -{ - T1 first; - T2 second; - - VmaPair() : first(), second() {} - VmaPair(const T1& firstSrc, const T2& secondSrc) : first(firstSrc), second(secondSrc) {} -}; - -template -struct VmaPairFirstLess -{ - bool operator()(const VmaPair& lhs, const VmaPair& rhs) const - { - return lhs.first < rhs.first; - } - bool operator()(const VmaPair& lhs, const FirstT& rhsFirst) const - { - return lhs.first < rhsFirst; - } -}; -#endif // _VMA_PAIR - -#ifndef _VMA_MAP -/* Class compatible with subset of interface of std::unordered_map. -KeyT, ValueT must be POD because they will be stored in VmaVector. -*/ -template -class VmaMap -{ -public: - typedef VmaPair PairType; - typedef PairType* iterator; - - VmaMap(const VmaStlAllocator& allocator) : m_Vector(allocator) {} - - iterator begin() { return m_Vector.begin(); } - iterator end() { return m_Vector.end(); } - size_t size() { return m_Vector.size(); } - - void insert(const PairType& pair); - iterator find(const KeyT& key); - void erase(iterator it); - -private: - VmaVector< PairType, VmaStlAllocator> m_Vector; -}; - -#ifndef _VMA_MAP_FUNCTIONS -template -void VmaMap::insert(const PairType& pair) -{ - const size_t indexToInsert = VmaBinaryFindFirstNotLess( - m_Vector.data(), - m_Vector.data() + m_Vector.size(), - pair, - VmaPairFirstLess()) - m_Vector.data(); - VmaVectorInsert(m_Vector, indexToInsert, pair); -} - -template -VmaPair* VmaMap::find(const KeyT& key) -{ - PairType* it = VmaBinaryFindFirstNotLess( - m_Vector.data(), - m_Vector.data() + m_Vector.size(), - key, - VmaPairFirstLess()); - if ((it != m_Vector.end()) && (it->first == key)) - { - return it; - } - else - { - return m_Vector.end(); - } -} - -template -void VmaMap::erase(iterator it) -{ - VmaVectorRemove(m_Vector, it - m_Vector.begin()); -} -#endif // _VMA_MAP_FUNCTIONS -#endif // _VMA_MAP - -#endif // #if 0 - -#if !defined(_VMA_STRING_BUILDER) && VMA_STATS_STRING_ENABLED -class VmaStringBuilder -{ -public: - VmaStringBuilder(const VkAllocationCallbacks* allocationCallbacks) : m_Data(VmaStlAllocator(allocationCallbacks)) {} - ~VmaStringBuilder() = default; - - size_t GetLength() const { return m_Data.size(); } - const char* GetData() const { return m_Data.data(); } - void AddNewLine() { Add('\n'); } - void Add(char ch) { m_Data.push_back(ch); } - - void Add(const char* pStr); - void AddNumber(uint32_t num); - void AddNumber(uint64_t num); - void AddPointer(const void* ptr); - -private: - VmaVector> m_Data; -}; - -#ifndef _VMA_STRING_BUILDER_FUNCTIONS -void VmaStringBuilder::Add(const char* pStr) -{ - const size_t strLen = strlen(pStr); - if (strLen > 0) - { - const size_t oldCount = m_Data.size(); - m_Data.resize(oldCount + strLen); - memcpy(m_Data.data() + oldCount, pStr, strLen); - } -} - -void VmaStringBuilder::AddNumber(uint32_t num) -{ - char buf[11]; - buf[10] = '\0'; - char* p = &buf[10]; - do - { - *--p = '0' + (num % 10); - num /= 10; - } while (num); - Add(p); -} - -void VmaStringBuilder::AddNumber(uint64_t num) -{ - char buf[21]; - buf[20] = '\0'; - char* p = &buf[20]; - do - { - *--p = '0' + (num % 10); - num /= 10; - } while (num); - Add(p); -} - -void VmaStringBuilder::AddPointer(const void* ptr) -{ - char buf[21]; - VmaPtrToStr(buf, sizeof(buf), ptr); - Add(buf); -} -#endif //_VMA_STRING_BUILDER_FUNCTIONS -#endif // _VMA_STRING_BUILDER - -#if !defined(_VMA_JSON_WRITER) && VMA_STATS_STRING_ENABLED -/* -Allows to conveniently build a correct JSON document to be written to the -VmaStringBuilder passed to the constructor. -*/ -class VmaJsonWriter -{ - VMA_CLASS_NO_COPY(VmaJsonWriter) -public: - // sb - string builder to write the document to. Must remain alive for the whole lifetime of this object. - VmaJsonWriter(const VkAllocationCallbacks* pAllocationCallbacks, VmaStringBuilder& sb); - ~VmaJsonWriter(); - - // Begins object by writing "{". - // Inside an object, you must call pairs of WriteString and a value, e.g.: - // j.BeginObject(true); j.WriteString("A"); j.WriteNumber(1); j.WriteString("B"); j.WriteNumber(2); j.EndObject(); - // Will write: { "A": 1, "B": 2 } - void BeginObject(bool singleLine = false); - // Ends object by writing "}". - void EndObject(); - - // Begins array by writing "[". - // Inside an array, you can write a sequence of any values. - void BeginArray(bool singleLine = false); - // Ends array by writing "[". - void EndArray(); - - // Writes a string value inside "". - // pStr can contain any ANSI characters, including '"', new line etc. - they will be properly escaped. - void WriteString(const char* pStr); - - // Begins writing a string value. - // Call BeginString, ContinueString, ContinueString, ..., EndString instead of - // WriteString to conveniently build the string content incrementally, made of - // parts including numbers. - void BeginString(const char* pStr = VMA_NULL); - // Posts next part of an open string. - void ContinueString(const char* pStr); - // Posts next part of an open string. The number is converted to decimal characters. - void ContinueString(uint32_t n); - void ContinueString(uint64_t n); - void ContinueString_Size(size_t n); - // Posts next part of an open string. Pointer value is converted to characters - // using "%p" formatting - shown as hexadecimal number, e.g.: 000000081276Ad00 - void ContinueString_Pointer(const void* ptr); - // Ends writing a string value by writing '"'. - void EndString(const char* pStr = VMA_NULL); - - // Writes a number value. - void WriteNumber(uint32_t n); - void WriteNumber(uint64_t n); - void WriteSize(size_t n); - // Writes a boolean value - false or true. - void WriteBool(bool b); - // Writes a null value. - void WriteNull(); - -private: - enum COLLECTION_TYPE - { - COLLECTION_TYPE_OBJECT, - COLLECTION_TYPE_ARRAY, - }; - struct StackItem - { - COLLECTION_TYPE type; - uint32_t valueCount; - bool singleLineMode; - }; - - static const char* const INDENT; - - VmaStringBuilder& m_SB; - VmaVector< StackItem, VmaStlAllocator > m_Stack; - bool m_InsideString; - - // Write size_t for less than 64bits - void WriteSize(size_t n, std::integral_constant) { m_SB.AddNumber(static_cast(n)); } - // Write size_t for 64bits - void WriteSize(size_t n, std::integral_constant) { m_SB.AddNumber(static_cast(n)); } - - void BeginValue(bool isString); - void WriteIndent(bool oneLess = false); -}; -const char* const VmaJsonWriter::INDENT = " "; - -#ifndef _VMA_JSON_WRITER_FUNCTIONS -VmaJsonWriter::VmaJsonWriter(const VkAllocationCallbacks* pAllocationCallbacks, VmaStringBuilder& sb) - : m_SB(sb), - m_Stack(VmaStlAllocator(pAllocationCallbacks)), - m_InsideString(false) {} - -VmaJsonWriter::~VmaJsonWriter() -{ - VMA_ASSERT(!m_InsideString); - VMA_ASSERT(m_Stack.empty()); -} - -void VmaJsonWriter::BeginObject(bool singleLine) -{ - VMA_ASSERT(!m_InsideString); - - BeginValue(false); - m_SB.Add('{'); - - StackItem item; - item.type = COLLECTION_TYPE_OBJECT; - item.valueCount = 0; - item.singleLineMode = singleLine; - m_Stack.push_back(item); -} - -void VmaJsonWriter::EndObject() -{ - VMA_ASSERT(!m_InsideString); - - WriteIndent(true); - m_SB.Add('}'); - - VMA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_OBJECT); - m_Stack.pop_back(); -} - -void VmaJsonWriter::BeginArray(bool singleLine) -{ - VMA_ASSERT(!m_InsideString); - - BeginValue(false); - m_SB.Add('['); - - StackItem item; - item.type = COLLECTION_TYPE_ARRAY; - item.valueCount = 0; - item.singleLineMode = singleLine; - m_Stack.push_back(item); -} - -void VmaJsonWriter::EndArray() -{ - VMA_ASSERT(!m_InsideString); - - WriteIndent(true); - m_SB.Add(']'); - - VMA_ASSERT(!m_Stack.empty() && m_Stack.back().type == COLLECTION_TYPE_ARRAY); - m_Stack.pop_back(); -} - -void VmaJsonWriter::WriteString(const char* pStr) -{ - BeginString(pStr); - EndString(); -} - -void VmaJsonWriter::BeginString(const char* pStr) -{ - VMA_ASSERT(!m_InsideString); - - BeginValue(true); - m_SB.Add('"'); - m_InsideString = true; - if (pStr != VMA_NULL && pStr[0] != '\0') - { - ContinueString(pStr); - } -} - -void VmaJsonWriter::ContinueString(const char* pStr) -{ - VMA_ASSERT(m_InsideString); - - const size_t strLen = strlen(pStr); - for (size_t i = 0; i < strLen; ++i) - { - char ch = pStr[i]; - if (ch == '\\') - { - m_SB.Add("\\\\"); - } - else if (ch == '"') - { - m_SB.Add("\\\""); - } - else if (ch >= 32) - { - m_SB.Add(ch); - } - else switch (ch) - { - case '\b': - m_SB.Add("\\b"); - break; - case '\f': - m_SB.Add("\\f"); - break; - case '\n': - m_SB.Add("\\n"); - break; - case '\r': - m_SB.Add("\\r"); - break; - case '\t': - m_SB.Add("\\t"); - break; - default: - VMA_ASSERT(0 && "Character not currently supported."); - break; - } - } -} - -void VmaJsonWriter::ContinueString(uint32_t n) -{ - VMA_ASSERT(m_InsideString); - m_SB.AddNumber(n); -} - -void VmaJsonWriter::ContinueString(uint64_t n) -{ - VMA_ASSERT(m_InsideString); - m_SB.AddNumber(n); -} - -void VmaJsonWriter::ContinueString_Size(size_t n) -{ - VMA_ASSERT(m_InsideString); - // Fix for AppleClang incorrect type casting - // TODO: Change to if constexpr when C++17 used as minimal standard - WriteSize(n, std::is_same{}); -} - -void VmaJsonWriter::ContinueString_Pointer(const void* ptr) -{ - VMA_ASSERT(m_InsideString); - m_SB.AddPointer(ptr); -} - -void VmaJsonWriter::EndString(const char* pStr) -{ - VMA_ASSERT(m_InsideString); - if (pStr != VMA_NULL && pStr[0] != '\0') - { - ContinueString(pStr); - } - m_SB.Add('"'); - m_InsideString = false; -} - -void VmaJsonWriter::WriteNumber(uint32_t n) -{ - VMA_ASSERT(!m_InsideString); - BeginValue(false); - m_SB.AddNumber(n); -} - -void VmaJsonWriter::WriteNumber(uint64_t n) -{ - VMA_ASSERT(!m_InsideString); - BeginValue(false); - m_SB.AddNumber(n); -} - -void VmaJsonWriter::WriteSize(size_t n) -{ - VMA_ASSERT(!m_InsideString); - BeginValue(false); - // Fix for AppleClang incorrect type casting - // TODO: Change to if constexpr when C++17 used as minimal standard - WriteSize(n, std::is_same{}); -} - -void VmaJsonWriter::WriteBool(bool b) -{ - VMA_ASSERT(!m_InsideString); - BeginValue(false); - m_SB.Add(b ? "true" : "false"); -} - -void VmaJsonWriter::WriteNull() -{ - VMA_ASSERT(!m_InsideString); - BeginValue(false); - m_SB.Add("null"); -} - -void VmaJsonWriter::BeginValue(bool isString) -{ - if (!m_Stack.empty()) - { - StackItem& currItem = m_Stack.back(); - if (currItem.type == COLLECTION_TYPE_OBJECT && - currItem.valueCount % 2 == 0) - { - VMA_ASSERT(isString); - } - - if (currItem.type == COLLECTION_TYPE_OBJECT && - currItem.valueCount % 2 != 0) - { - m_SB.Add(": "); - } - else if (currItem.valueCount > 0) - { - m_SB.Add(", "); - WriteIndent(); - } - else - { - WriteIndent(); - } - ++currItem.valueCount; - } -} - -void VmaJsonWriter::WriteIndent(bool oneLess) -{ - if (!m_Stack.empty() && !m_Stack.back().singleLineMode) - { - m_SB.AddNewLine(); - - size_t count = m_Stack.size(); - if (count > 0 && oneLess) - { - --count; - } - for (size_t i = 0; i < count; ++i) - { - m_SB.Add(INDENT); - } - } -} -#endif // _VMA_JSON_WRITER_FUNCTIONS - -static void VmaPrintDetailedStatistics(VmaJsonWriter& json, const VmaDetailedStatistics& stat) -{ - json.BeginObject(); - - json.WriteString("BlockCount"); - json.WriteNumber(stat.statistics.blockCount); - json.WriteString("BlockBytes"); - json.WriteNumber(stat.statistics.blockBytes); - json.WriteString("AllocationCount"); - json.WriteNumber(stat.statistics.allocationCount); - json.WriteString("AllocationBytes"); - json.WriteNumber(stat.statistics.allocationBytes); - json.WriteString("UnusedRangeCount"); - json.WriteNumber(stat.unusedRangeCount); - - if (stat.statistics.allocationCount > 1) - { - json.WriteString("AllocationSizeMin"); - json.WriteNumber(stat.allocationSizeMin); - json.WriteString("AllocationSizeMax"); - json.WriteNumber(stat.allocationSizeMax); - } - if (stat.unusedRangeCount > 1) - { - json.WriteString("UnusedRangeSizeMin"); - json.WriteNumber(stat.unusedRangeSizeMin); - json.WriteString("UnusedRangeSizeMax"); - json.WriteNumber(stat.unusedRangeSizeMax); - } - json.EndObject(); -} -#endif // _VMA_JSON_WRITER - -#ifndef _VMA_MAPPING_HYSTERESIS - -class VmaMappingHysteresis -{ - VMA_CLASS_NO_COPY(VmaMappingHysteresis) -public: - VmaMappingHysteresis() = default; - - uint32_t GetExtraMapping() const { return m_ExtraMapping; } - - // Call when Map was called. - // Returns true if switched to extra +1 mapping reference count. - bool PostMap() - { -#if VMA_MAPPING_HYSTERESIS_ENABLED - if(m_ExtraMapping == 0) - { - ++m_MajorCounter; - if(m_MajorCounter >= COUNTER_MIN_EXTRA_MAPPING) - { - m_ExtraMapping = 1; - m_MajorCounter = 0; - m_MinorCounter = 0; - return true; - } - } - else // m_ExtraMapping == 1 - PostMinorCounter(); -#endif // #if VMA_MAPPING_HYSTERESIS_ENABLED - return false; - } - - // Call when Unmap was called. - void PostUnmap() - { -#if VMA_MAPPING_HYSTERESIS_ENABLED - if(m_ExtraMapping == 0) - ++m_MajorCounter; - else // m_ExtraMapping == 1 - PostMinorCounter(); -#endif // #if VMA_MAPPING_HYSTERESIS_ENABLED - } - - // Call when allocation was made from the memory block. - void PostAlloc() - { -#if VMA_MAPPING_HYSTERESIS_ENABLED - if(m_ExtraMapping == 1) - ++m_MajorCounter; - else // m_ExtraMapping == 0 - PostMinorCounter(); -#endif // #if VMA_MAPPING_HYSTERESIS_ENABLED - } - - // Call when allocation was freed from the memory block. - // Returns true if switched to extra -1 mapping reference count. - bool PostFree() - { -#if VMA_MAPPING_HYSTERESIS_ENABLED - if(m_ExtraMapping == 1) - { - ++m_MajorCounter; - if(m_MajorCounter >= COUNTER_MIN_EXTRA_MAPPING && - m_MajorCounter > m_MinorCounter + 1) - { - m_ExtraMapping = 0; - m_MajorCounter = 0; - m_MinorCounter = 0; - return true; - } - } - else // m_ExtraMapping == 0 - PostMinorCounter(); -#endif // #if VMA_MAPPING_HYSTERESIS_ENABLED - return false; - } - -private: - static const int32_t COUNTER_MIN_EXTRA_MAPPING = 7; - - uint32_t m_MinorCounter = 0; - uint32_t m_MajorCounter = 0; - uint32_t m_ExtraMapping = 0; // 0 or 1. - - void PostMinorCounter() - { - if(m_MinorCounter < m_MajorCounter) - { - ++m_MinorCounter; - } - else if(m_MajorCounter > 0) - { - --m_MajorCounter; - --m_MinorCounter; - } - } -}; - -#endif // _VMA_MAPPING_HYSTERESIS - -#ifndef _VMA_DEVICE_MEMORY_BLOCK -/* -Represents a single block of device memory (`VkDeviceMemory`) with all the -data about its regions (aka suballocations, #VmaAllocation), assigned and free. - -Thread-safety: -- Access to m_pMetadata must be externally synchronized. -- Map, Unmap, Bind* are synchronized internally. -*/ -class VmaDeviceMemoryBlock -{ - VMA_CLASS_NO_COPY(VmaDeviceMemoryBlock) -public: - VmaBlockMetadata* m_pMetadata; - - VmaDeviceMemoryBlock(VmaAllocator hAllocator); - ~VmaDeviceMemoryBlock(); - - // Always call after construction. - void Init( - VmaAllocator hAllocator, - VmaPool hParentPool, - uint32_t newMemoryTypeIndex, - VkDeviceMemory newMemory, - VkDeviceSize newSize, - uint32_t id, - uint32_t algorithm, - VkDeviceSize bufferImageGranularity); - // Always call before destruction. - void Destroy(VmaAllocator allocator); - - VmaPool GetParentPool() const { return m_hParentPool; } - VkDeviceMemory GetDeviceMemory() const { return m_hMemory; } - uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; } - uint32_t GetId() const { return m_Id; } - void* GetMappedData() const { return m_pMappedData; } - uint32_t GetMapRefCount() const { return m_MapCount; } - - // Call when allocation/free was made from m_pMetadata. - // Used for m_MappingHysteresis. - void PostAlloc(VmaAllocator hAllocator); - void PostFree(VmaAllocator hAllocator); - - // Validates all data structures inside this object. If not valid, returns false. - bool Validate() const; - VkResult CheckCorruption(VmaAllocator hAllocator); - - // ppData can be null. - VkResult Map(VmaAllocator hAllocator, uint32_t count, void** ppData); - void Unmap(VmaAllocator hAllocator, uint32_t count); - - VkResult WriteMagicValueAfterAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize); - VkResult ValidateMagicValueAfterAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize); - - VkResult BindBufferMemory( - const VmaAllocator hAllocator, - const VmaAllocation hAllocation, - VkDeviceSize allocationLocalOffset, - VkBuffer hBuffer, - const void* pNext); - VkResult BindImageMemory( - const VmaAllocator hAllocator, - const VmaAllocation hAllocation, - VkDeviceSize allocationLocalOffset, - VkImage hImage, - const void* pNext); - -private: - VmaPool m_hParentPool; // VK_NULL_HANDLE if not belongs to custom pool. - uint32_t m_MemoryTypeIndex; - uint32_t m_Id; - VkDeviceMemory m_hMemory; - - /* - Protects access to m_hMemory so it is not used by multiple threads simultaneously, e.g. vkMapMemory, vkBindBufferMemory. - Also protects m_MapCount, m_pMappedData. - Allocations, deallocations, any change in m_pMetadata is protected by parent's VmaBlockVector::m_Mutex. - */ - VMA_MUTEX m_MapAndBindMutex; - VmaMappingHysteresis m_MappingHysteresis; - uint32_t m_MapCount; - void* m_pMappedData; -}; -#endif // _VMA_DEVICE_MEMORY_BLOCK - -#ifndef _VMA_ALLOCATION_T -struct VmaAllocation_T -{ - friend struct VmaDedicatedAllocationListItemTraits; - - enum FLAGS - { - FLAG_PERSISTENT_MAP = 0x01, - FLAG_MAPPING_ALLOWED = 0x02, - }; - -public: - enum ALLOCATION_TYPE - { - ALLOCATION_TYPE_NONE, - ALLOCATION_TYPE_BLOCK, - ALLOCATION_TYPE_DEDICATED, - }; - - // This struct is allocated using VmaPoolAllocator. - VmaAllocation_T(bool mappingAllowed); - ~VmaAllocation_T(); - - void InitBlockAllocation( - VmaDeviceMemoryBlock* block, - VmaAllocHandle allocHandle, - VkDeviceSize alignment, - VkDeviceSize size, - uint32_t memoryTypeIndex, - VmaSuballocationType suballocationType, - bool mapped); - // pMappedData not null means allocation is created with MAPPED flag. - void InitDedicatedAllocation( - VmaPool hParentPool, - uint32_t memoryTypeIndex, - VkDeviceMemory hMemory, - VmaSuballocationType suballocationType, - void* pMappedData, - VkDeviceSize size); - - ALLOCATION_TYPE GetType() const { return (ALLOCATION_TYPE)m_Type; } - VkDeviceSize GetAlignment() const { return m_Alignment; } - VkDeviceSize GetSize() const { return m_Size; } - void* GetUserData() const { return m_pUserData; } - const char* GetName() const { return m_pName; } - VmaSuballocationType GetSuballocationType() const { return (VmaSuballocationType)m_SuballocationType; } - - VmaDeviceMemoryBlock* GetBlock() const { VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK); return m_BlockAllocation.m_Block; } - uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; } - bool IsPersistentMap() const { return (m_Flags & FLAG_PERSISTENT_MAP) != 0; } - bool IsMappingAllowed() const { return (m_Flags & FLAG_MAPPING_ALLOWED) != 0; } - - void SetUserData(VmaAllocator hAllocator, void* pUserData) { m_pUserData = pUserData; } - void SetName(VmaAllocator hAllocator, const char* pName); - void FreeName(VmaAllocator hAllocator); - uint8_t SwapBlockAllocation(VmaAllocator hAllocator, VmaAllocation allocation); - VmaAllocHandle GetAllocHandle() const; - VkDeviceSize GetOffset() const; - VmaPool GetParentPool() const; - VkDeviceMemory GetMemory() const; - void* GetMappedData() const; - - void BlockAllocMap(); - void BlockAllocUnmap(); - VkResult DedicatedAllocMap(VmaAllocator hAllocator, void** ppData); - void DedicatedAllocUnmap(VmaAllocator hAllocator); - -#if VMA_STATS_STRING_ENABLED - uint32_t GetBufferImageUsage() const { return m_BufferImageUsage; } - - void InitBufferImageUsage(uint32_t bufferImageUsage); - void PrintParameters(class VmaJsonWriter& json) const; -#endif - -private: - // Allocation out of VmaDeviceMemoryBlock. - struct BlockAllocation - { - VmaDeviceMemoryBlock* m_Block; - VmaAllocHandle m_AllocHandle; - }; - // Allocation for an object that has its own private VkDeviceMemory. - struct DedicatedAllocation - { - VmaPool m_hParentPool; // VK_NULL_HANDLE if not belongs to custom pool. - VkDeviceMemory m_hMemory; - void* m_pMappedData; // Not null means memory is mapped. - VmaAllocation_T* m_Prev; - VmaAllocation_T* m_Next; - }; - union - { - // Allocation out of VmaDeviceMemoryBlock. - BlockAllocation m_BlockAllocation; - // Allocation for an object that has its own private VkDeviceMemory. - DedicatedAllocation m_DedicatedAllocation; - }; - - VkDeviceSize m_Alignment; - VkDeviceSize m_Size; - void* m_pUserData; - char* m_pName; - uint32_t m_MemoryTypeIndex; - uint8_t m_Type; // ALLOCATION_TYPE - uint8_t m_SuballocationType; // VmaSuballocationType - // Reference counter for vmaMapMemory()/vmaUnmapMemory(). - uint8_t m_MapCount; - uint8_t m_Flags; // enum FLAGS -#if VMA_STATS_STRING_ENABLED - uint32_t m_BufferImageUsage; // 0 if unknown. -#endif -}; -#endif // _VMA_ALLOCATION_T - -#ifndef _VMA_DEDICATED_ALLOCATION_LIST_ITEM_TRAITS -struct VmaDedicatedAllocationListItemTraits -{ - typedef VmaAllocation_T ItemType; - - static ItemType* GetPrev(const ItemType* item) - { - VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED); - return item->m_DedicatedAllocation.m_Prev; - } - static ItemType* GetNext(const ItemType* item) - { - VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED); - return item->m_DedicatedAllocation.m_Next; - } - static ItemType*& AccessPrev(ItemType* item) - { - VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED); - return item->m_DedicatedAllocation.m_Prev; - } - static ItemType*& AccessNext(ItemType* item) - { - VMA_HEAVY_ASSERT(item->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED); - return item->m_DedicatedAllocation.m_Next; - } -}; -#endif // _VMA_DEDICATED_ALLOCATION_LIST_ITEM_TRAITS - -#ifndef _VMA_DEDICATED_ALLOCATION_LIST -/* -Stores linked list of VmaAllocation_T objects. -Thread-safe, synchronized internally. -*/ -class VmaDedicatedAllocationList -{ -public: - VmaDedicatedAllocationList() {} - ~VmaDedicatedAllocationList(); - - void Init(bool useMutex) { m_UseMutex = useMutex; } - bool Validate(); - - void AddDetailedStatistics(VmaDetailedStatistics& inoutStats); - void AddStatistics(VmaStatistics& inoutStats); -#if VMA_STATS_STRING_ENABLED - // Writes JSON array with the list of allocations. - void BuildStatsString(VmaJsonWriter& json); -#endif - - bool IsEmpty(); - void Register(VmaAllocation alloc); - void Unregister(VmaAllocation alloc); - -private: - typedef VmaIntrusiveLinkedList DedicatedAllocationLinkedList; - - bool m_UseMutex = true; - VMA_RW_MUTEX m_Mutex; - DedicatedAllocationLinkedList m_AllocationList; -}; - -#ifndef _VMA_DEDICATED_ALLOCATION_LIST_FUNCTIONS - -VmaDedicatedAllocationList::~VmaDedicatedAllocationList() -{ - VMA_HEAVY_ASSERT(Validate()); - - if (!m_AllocationList.IsEmpty()) - { - VMA_ASSERT(false && "Unfreed dedicated allocations found!"); - } -} - -bool VmaDedicatedAllocationList::Validate() -{ - const size_t declaredCount = m_AllocationList.GetCount(); - size_t actualCount = 0; - VmaMutexLockRead lock(m_Mutex, m_UseMutex); - for (VmaAllocation alloc = m_AllocationList.Front(); - alloc != VMA_NULL; alloc = m_AllocationList.GetNext(alloc)) - { - ++actualCount; - } - VMA_VALIDATE(actualCount == declaredCount); - - return true; -} - -void VmaDedicatedAllocationList::AddDetailedStatistics(VmaDetailedStatistics& inoutStats) -{ - for(auto* item = m_AllocationList.Front(); item != nullptr; item = DedicatedAllocationLinkedList::GetNext(item)) - { - const VkDeviceSize size = item->GetSize(); - inoutStats.statistics.blockCount++; - inoutStats.statistics.blockBytes += size; - VmaAddDetailedStatisticsAllocation(inoutStats, item->GetSize()); - } -} - -void VmaDedicatedAllocationList::AddStatistics(VmaStatistics& inoutStats) -{ - VmaMutexLockRead lock(m_Mutex, m_UseMutex); - - const uint32_t allocCount = (uint32_t)m_AllocationList.GetCount(); - inoutStats.blockCount += allocCount; - inoutStats.allocationCount += allocCount; - - for(auto* item = m_AllocationList.Front(); item != nullptr; item = DedicatedAllocationLinkedList::GetNext(item)) - { - const VkDeviceSize size = item->GetSize(); - inoutStats.blockBytes += size; - inoutStats.allocationBytes += size; - } -} - -#if VMA_STATS_STRING_ENABLED -void VmaDedicatedAllocationList::BuildStatsString(VmaJsonWriter& json) -{ - VmaMutexLockRead lock(m_Mutex, m_UseMutex); - json.BeginArray(); - for (VmaAllocation alloc = m_AllocationList.Front(); - alloc != VMA_NULL; alloc = m_AllocationList.GetNext(alloc)) - { - json.BeginObject(true); - alloc->PrintParameters(json); - json.EndObject(); - } - json.EndArray(); -} -#endif // VMA_STATS_STRING_ENABLED - -bool VmaDedicatedAllocationList::IsEmpty() -{ - VmaMutexLockRead lock(m_Mutex, m_UseMutex); - return m_AllocationList.IsEmpty(); -} - -void VmaDedicatedAllocationList::Register(VmaAllocation alloc) -{ - VmaMutexLockWrite lock(m_Mutex, m_UseMutex); - m_AllocationList.PushBack(alloc); -} - -void VmaDedicatedAllocationList::Unregister(VmaAllocation alloc) -{ - VmaMutexLockWrite lock(m_Mutex, m_UseMutex); - m_AllocationList.Remove(alloc); -} -#endif // _VMA_DEDICATED_ALLOCATION_LIST_FUNCTIONS -#endif // _VMA_DEDICATED_ALLOCATION_LIST - -#ifndef _VMA_SUBALLOCATION -/* -Represents a region of VmaDeviceMemoryBlock that is either assigned and returned as -allocated memory block or free. -*/ -struct VmaSuballocation -{ - VkDeviceSize offset; - VkDeviceSize size; - void* userData; - VmaSuballocationType type; -}; - -// Comparator for offsets. -struct VmaSuballocationOffsetLess -{ - bool operator()(const VmaSuballocation& lhs, const VmaSuballocation& rhs) const - { - return lhs.offset < rhs.offset; - } -}; - -struct VmaSuballocationOffsetGreater -{ - bool operator()(const VmaSuballocation& lhs, const VmaSuballocation& rhs) const - { - return lhs.offset > rhs.offset; - } -}; - -struct VmaSuballocationItemSizeLess -{ - bool operator()(const VmaSuballocationList::iterator lhs, - const VmaSuballocationList::iterator rhs) const - { - return lhs->size < rhs->size; - } - - bool operator()(const VmaSuballocationList::iterator lhs, - VkDeviceSize rhsSize) const - { - return lhs->size < rhsSize; - } -}; -#endif // _VMA_SUBALLOCATION - -#ifndef _VMA_ALLOCATION_REQUEST -/* -Parameters of planned allocation inside a VmaDeviceMemoryBlock. -item points to a FREE suballocation. -*/ -struct VmaAllocationRequest -{ - VmaAllocHandle allocHandle; - VkDeviceSize size; - VmaSuballocationList::iterator item; - void* customData; - uint64_t algorithmData; - VmaAllocationRequestType type; -}; -#endif // _VMA_ALLOCATION_REQUEST - -#ifndef _VMA_BLOCK_METADATA -/* -Data structure used for bookkeeping of allocations and unused ranges of memory -in a single VkDeviceMemory block. -*/ -class VmaBlockMetadata -{ -public: - // pAllocationCallbacks, if not null, must be owned externally - alive and unchanged for the whole lifetime of this object. - VmaBlockMetadata(const VkAllocationCallbacks* pAllocationCallbacks, - VkDeviceSize bufferImageGranularity, bool isVirtual); - virtual ~VmaBlockMetadata() = default; - - virtual void Init(VkDeviceSize size) { m_Size = size; } - bool IsVirtual() const { return m_IsVirtual; } - VkDeviceSize GetSize() const { return m_Size; } - - // Validates all data structures inside this object. If not valid, returns false. - virtual bool Validate() const = 0; - virtual size_t GetAllocationCount() const = 0; - virtual size_t GetFreeRegionsCount() const = 0; - virtual VkDeviceSize GetSumFreeSize() const = 0; - // Returns true if this block is empty - contains only single free suballocation. - virtual bool IsEmpty() const = 0; - virtual void GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) = 0; - virtual VkDeviceSize GetAllocationOffset(VmaAllocHandle allocHandle) const = 0; - virtual void* GetAllocationUserData(VmaAllocHandle allocHandle) const = 0; - - virtual VmaAllocHandle GetAllocationListBegin() const = 0; - virtual VmaAllocHandle GetNextAllocation(VmaAllocHandle prevAlloc) const = 0; - virtual VkDeviceSize GetNextFreeRegionSize(VmaAllocHandle alloc) const = 0; - - // Shouldn't modify blockCount. - virtual void AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const = 0; - virtual void AddStatistics(VmaStatistics& inoutStats) const = 0; - -#if VMA_STATS_STRING_ENABLED - virtual void PrintDetailedMap(class VmaJsonWriter& json) const = 0; -#endif - - // Tries to find a place for suballocation with given parameters inside this block. - // If succeeded, fills pAllocationRequest and returns true. - // If failed, returns false. - virtual bool CreateAllocationRequest( - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - bool upperAddress, - VmaSuballocationType allocType, - // Always one of VMA_ALLOCATION_CREATE_STRATEGY_* or VMA_ALLOCATION_INTERNAL_STRATEGY_* flags. - uint32_t strategy, - VmaAllocationRequest* pAllocationRequest) = 0; - - virtual VkResult CheckCorruption(const void* pBlockData) = 0; - - // Makes actual allocation based on request. Request must already be checked and valid. - virtual void Alloc( - const VmaAllocationRequest& request, - VmaSuballocationType type, - void* userData) = 0; - - // Frees suballocation assigned to given memory region. - virtual void Free(VmaAllocHandle allocHandle) = 0; - - // Frees all allocations. - // Careful! Don't call it if there are VmaAllocation objects owned by userData of cleared allocations! - virtual void Clear() = 0; - - virtual void SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) = 0; - virtual void DebugLogAllAllocations() const = 0; - -protected: - const VkAllocationCallbacks* GetAllocationCallbacks() const { return m_pAllocationCallbacks; } - VkDeviceSize GetBufferImageGranularity() const { return m_BufferImageGranularity; } - VkDeviceSize GetDebugMargin() const { return IsVirtual() ? 0 : VMA_DEBUG_MARGIN; } - - void DebugLogAllocation(VkDeviceSize offset, VkDeviceSize size, void* userData) const; -#if VMA_STATS_STRING_ENABLED - // mapRefCount == UINT32_MAX means unspecified. - void PrintDetailedMap_Begin(class VmaJsonWriter& json, - VkDeviceSize unusedBytes, - size_t allocationCount, - size_t unusedRangeCount) const; - void PrintDetailedMap_Allocation(class VmaJsonWriter& json, - VkDeviceSize offset, VkDeviceSize size, void* userData) const; - void PrintDetailedMap_UnusedRange(class VmaJsonWriter& json, - VkDeviceSize offset, - VkDeviceSize size) const; - void PrintDetailedMap_End(class VmaJsonWriter& json) const; -#endif - -private: - VkDeviceSize m_Size; - const VkAllocationCallbacks* m_pAllocationCallbacks; - const VkDeviceSize m_BufferImageGranularity; - const bool m_IsVirtual; -}; - -#ifndef _VMA_BLOCK_METADATA_FUNCTIONS -VmaBlockMetadata::VmaBlockMetadata(const VkAllocationCallbacks* pAllocationCallbacks, - VkDeviceSize bufferImageGranularity, bool isVirtual) - : m_Size(0), - m_pAllocationCallbacks(pAllocationCallbacks), - m_BufferImageGranularity(bufferImageGranularity), - m_IsVirtual(isVirtual) {} - -void VmaBlockMetadata::DebugLogAllocation(VkDeviceSize offset, VkDeviceSize size, void* userData) const -{ - if (IsVirtual()) - { - VMA_DEBUG_LOG("UNFREED VIRTUAL ALLOCATION; Offset: %llu; Size: %llu; UserData: %p", offset, size, userData); - } - else - { - VMA_ASSERT(userData != VMA_NULL); - VmaAllocation allocation = reinterpret_cast(userData); - - userData = allocation->GetUserData(); - const char* name = allocation->GetName(); - -#if VMA_STATS_STRING_ENABLED - VMA_DEBUG_LOG("UNFREED ALLOCATION; Offset: %llu; Size: %llu; UserData: %p; Name: %s; Type: %s; Usage: %u", - offset, size, userData, name ? name : "vma_empty", - VMA_SUBALLOCATION_TYPE_NAMES[allocation->GetSuballocationType()], - allocation->GetBufferImageUsage()); -#else - VMA_DEBUG_LOG("UNFREED ALLOCATION; Offset: %llu; Size: %llu; UserData: %p; Name: %s; Type: %u", - offset, size, userData, name ? name : "vma_empty", - (uint32_t)allocation->GetSuballocationType()); -#endif // VMA_STATS_STRING_ENABLED - } - -} - -#if VMA_STATS_STRING_ENABLED -void VmaBlockMetadata::PrintDetailedMap_Begin(class VmaJsonWriter& json, - VkDeviceSize unusedBytes, size_t allocationCount, size_t unusedRangeCount) const -{ - json.WriteString("TotalBytes"); - json.WriteNumber(GetSize()); - - json.WriteString("UnusedBytes"); - json.WriteSize(unusedBytes); - - json.WriteString("Allocations"); - json.WriteSize(allocationCount); - - json.WriteString("UnusedRanges"); - json.WriteSize(unusedRangeCount); - - json.WriteString("Suballocations"); - json.BeginArray(); -} - -void VmaBlockMetadata::PrintDetailedMap_Allocation(class VmaJsonWriter& json, - VkDeviceSize offset, VkDeviceSize size, void* userData) const -{ - json.BeginObject(true); - - json.WriteString("Offset"); - json.WriteNumber(offset); - - if (IsVirtual()) - { - json.WriteString("Size"); - json.WriteNumber(size); - if (userData) - { - json.WriteString("CustomData"); - json.BeginString(); - json.ContinueString_Pointer(userData); - json.EndString(); - } - } - else - { - ((VmaAllocation)userData)->PrintParameters(json); - } - - json.EndObject(); -} - -void VmaBlockMetadata::PrintDetailedMap_UnusedRange(class VmaJsonWriter& json, - VkDeviceSize offset, VkDeviceSize size) const -{ - json.BeginObject(true); - - json.WriteString("Offset"); - json.WriteNumber(offset); - - json.WriteString("Type"); - json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[VMA_SUBALLOCATION_TYPE_FREE]); - - json.WriteString("Size"); - json.WriteNumber(size); - - json.EndObject(); -} - -void VmaBlockMetadata::PrintDetailedMap_End(class VmaJsonWriter& json) const -{ - json.EndArray(); -} -#endif // VMA_STATS_STRING_ENABLED -#endif // _VMA_BLOCK_METADATA_FUNCTIONS -#endif // _VMA_BLOCK_METADATA - -#ifndef _VMA_BLOCK_BUFFER_IMAGE_GRANULARITY -// Before deleting object of this class remember to call 'Destroy()' -class VmaBlockBufferImageGranularity final -{ -public: - struct ValidationContext - { - const VkAllocationCallbacks* allocCallbacks; - uint16_t* pageAllocs; - }; - - VmaBlockBufferImageGranularity(VkDeviceSize bufferImageGranularity); - ~VmaBlockBufferImageGranularity(); - - bool IsEnabled() const { return m_BufferImageGranularity > MAX_LOW_BUFFER_IMAGE_GRANULARITY; } - - void Init(const VkAllocationCallbacks* pAllocationCallbacks, VkDeviceSize size); - // Before destroying object you must call free it's memory - void Destroy(const VkAllocationCallbacks* pAllocationCallbacks); - - void RoundupAllocRequest(VmaSuballocationType allocType, - VkDeviceSize& inOutAllocSize, - VkDeviceSize& inOutAllocAlignment) const; - - bool CheckConflictAndAlignUp(VkDeviceSize& inOutAllocOffset, - VkDeviceSize allocSize, - VkDeviceSize blockOffset, - VkDeviceSize blockSize, - VmaSuballocationType allocType) const; - - void AllocPages(uint8_t allocType, VkDeviceSize offset, VkDeviceSize size); - void FreePages(VkDeviceSize offset, VkDeviceSize size); - void Clear(); - - ValidationContext StartValidation(const VkAllocationCallbacks* pAllocationCallbacks, - bool isVirutal) const; - bool Validate(ValidationContext& ctx, VkDeviceSize offset, VkDeviceSize size) const; - bool FinishValidation(ValidationContext& ctx) const; - -private: - static const uint16_t MAX_LOW_BUFFER_IMAGE_GRANULARITY = 256; - - struct RegionInfo - { - uint8_t allocType; - uint16_t allocCount; - }; - - VkDeviceSize m_BufferImageGranularity; - uint32_t m_RegionCount; - RegionInfo* m_RegionInfo; - - uint32_t GetStartPage(VkDeviceSize offset) const { return OffsetToPageIndex(offset & ~(m_BufferImageGranularity - 1)); } - uint32_t GetEndPage(VkDeviceSize offset, VkDeviceSize size) const { return OffsetToPageIndex((offset + size - 1) & ~(m_BufferImageGranularity - 1)); } - - uint32_t OffsetToPageIndex(VkDeviceSize offset) const; - void AllocPage(RegionInfo& page, uint8_t allocType); -}; - -#ifndef _VMA_BLOCK_BUFFER_IMAGE_GRANULARITY_FUNCTIONS -VmaBlockBufferImageGranularity::VmaBlockBufferImageGranularity(VkDeviceSize bufferImageGranularity) - : m_BufferImageGranularity(bufferImageGranularity), - m_RegionCount(0), - m_RegionInfo(VMA_NULL) {} - -VmaBlockBufferImageGranularity::~VmaBlockBufferImageGranularity() -{ - VMA_ASSERT(m_RegionInfo == VMA_NULL && "Free not called before destroying object!"); -} - -void VmaBlockBufferImageGranularity::Init(const VkAllocationCallbacks* pAllocationCallbacks, VkDeviceSize size) -{ - if (IsEnabled()) - { - m_RegionCount = static_cast(VmaDivideRoundingUp(size, m_BufferImageGranularity)); - m_RegionInfo = vma_new_array(pAllocationCallbacks, RegionInfo, m_RegionCount); - memset(m_RegionInfo, 0, m_RegionCount * sizeof(RegionInfo)); - } -} - -void VmaBlockBufferImageGranularity::Destroy(const VkAllocationCallbacks* pAllocationCallbacks) -{ - if (m_RegionInfo) - { - vma_delete_array(pAllocationCallbacks, m_RegionInfo, m_RegionCount); - m_RegionInfo = VMA_NULL; - } -} - -void VmaBlockBufferImageGranularity::RoundupAllocRequest(VmaSuballocationType allocType, - VkDeviceSize& inOutAllocSize, - VkDeviceSize& inOutAllocAlignment) const -{ - if (m_BufferImageGranularity > 1 && - m_BufferImageGranularity <= MAX_LOW_BUFFER_IMAGE_GRANULARITY) - { - if (allocType == VMA_SUBALLOCATION_TYPE_UNKNOWN || - allocType == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN || - allocType == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL) - { - inOutAllocAlignment = VMA_MAX(inOutAllocAlignment, m_BufferImageGranularity); - inOutAllocSize = VmaAlignUp(inOutAllocSize, m_BufferImageGranularity); - } - } -} - -bool VmaBlockBufferImageGranularity::CheckConflictAndAlignUp(VkDeviceSize& inOutAllocOffset, - VkDeviceSize allocSize, - VkDeviceSize blockOffset, - VkDeviceSize blockSize, - VmaSuballocationType allocType) const -{ - if (IsEnabled()) - { - uint32_t startPage = GetStartPage(inOutAllocOffset); - if (m_RegionInfo[startPage].allocCount > 0 && - VmaIsBufferImageGranularityConflict(static_cast(m_RegionInfo[startPage].allocType), allocType)) - { - inOutAllocOffset = VmaAlignUp(inOutAllocOffset, m_BufferImageGranularity); - if (blockSize < allocSize + inOutAllocOffset - blockOffset) - return true; - ++startPage; - } - uint32_t endPage = GetEndPage(inOutAllocOffset, allocSize); - if (endPage != startPage && - m_RegionInfo[endPage].allocCount > 0 && - VmaIsBufferImageGranularityConflict(static_cast(m_RegionInfo[endPage].allocType), allocType)) - { - return true; - } - } - return false; -} - -void VmaBlockBufferImageGranularity::AllocPages(uint8_t allocType, VkDeviceSize offset, VkDeviceSize size) -{ - if (IsEnabled()) - { - uint32_t startPage = GetStartPage(offset); - AllocPage(m_RegionInfo[startPage], allocType); - - uint32_t endPage = GetEndPage(offset, size); - if (startPage != endPage) - AllocPage(m_RegionInfo[endPage], allocType); - } -} - -void VmaBlockBufferImageGranularity::FreePages(VkDeviceSize offset, VkDeviceSize size) -{ - if (IsEnabled()) - { - uint32_t startPage = GetStartPage(offset); - --m_RegionInfo[startPage].allocCount; - if (m_RegionInfo[startPage].allocCount == 0) - m_RegionInfo[startPage].allocType = VMA_SUBALLOCATION_TYPE_FREE; - uint32_t endPage = GetEndPage(offset, size); - if (startPage != endPage) - { - --m_RegionInfo[endPage].allocCount; - if (m_RegionInfo[endPage].allocCount == 0) - m_RegionInfo[endPage].allocType = VMA_SUBALLOCATION_TYPE_FREE; - } - } -} - -void VmaBlockBufferImageGranularity::Clear() -{ - if (m_RegionInfo) - memset(m_RegionInfo, 0, m_RegionCount * sizeof(RegionInfo)); -} - -VmaBlockBufferImageGranularity::ValidationContext VmaBlockBufferImageGranularity::StartValidation( - const VkAllocationCallbacks* pAllocationCallbacks, bool isVirutal) const -{ - ValidationContext ctx{ pAllocationCallbacks, VMA_NULL }; - if (!isVirutal && IsEnabled()) - { - ctx.pageAllocs = vma_new_array(pAllocationCallbacks, uint16_t, m_RegionCount); - memset(ctx.pageAllocs, 0, m_RegionCount * sizeof(uint16_t)); - } - return ctx; -} - -bool VmaBlockBufferImageGranularity::Validate(ValidationContext& ctx, - VkDeviceSize offset, VkDeviceSize size) const -{ - if (IsEnabled()) - { - uint32_t start = GetStartPage(offset); - ++ctx.pageAllocs[start]; - VMA_VALIDATE(m_RegionInfo[start].allocCount > 0); - - uint32_t end = GetEndPage(offset, size); - if (start != end) - { - ++ctx.pageAllocs[end]; - VMA_VALIDATE(m_RegionInfo[end].allocCount > 0); - } - } - return true; -} - -bool VmaBlockBufferImageGranularity::FinishValidation(ValidationContext& ctx) const -{ - // Check proper page structure - if (IsEnabled()) - { - VMA_ASSERT(ctx.pageAllocs != VMA_NULL && "Validation context not initialized!"); - - for (uint32_t page = 0; page < m_RegionCount; ++page) - { - VMA_VALIDATE(ctx.pageAllocs[page] == m_RegionInfo[page].allocCount); - } - vma_delete_array(ctx.allocCallbacks, ctx.pageAllocs, m_RegionCount); - ctx.pageAllocs = VMA_NULL; - } - return true; -} - -uint32_t VmaBlockBufferImageGranularity::OffsetToPageIndex(VkDeviceSize offset) const -{ - return static_cast(offset >> VMA_BITSCAN_MSB(m_BufferImageGranularity)); -} - -void VmaBlockBufferImageGranularity::AllocPage(RegionInfo& page, uint8_t allocType) -{ - // When current alloc type is free then it can be overridden by new type - if (page.allocCount == 0 || (page.allocCount > 0 && page.allocType == VMA_SUBALLOCATION_TYPE_FREE)) - page.allocType = allocType; - - ++page.allocCount; -} -#endif // _VMA_BLOCK_BUFFER_IMAGE_GRANULARITY_FUNCTIONS -#endif // _VMA_BLOCK_BUFFER_IMAGE_GRANULARITY - -#if 0 -#ifndef _VMA_BLOCK_METADATA_GENERIC -class VmaBlockMetadata_Generic : public VmaBlockMetadata -{ - friend class VmaDefragmentationAlgorithm_Generic; - friend class VmaDefragmentationAlgorithm_Fast; - VMA_CLASS_NO_COPY(VmaBlockMetadata_Generic) -public: - VmaBlockMetadata_Generic(const VkAllocationCallbacks* pAllocationCallbacks, - VkDeviceSize bufferImageGranularity, bool isVirtual); - virtual ~VmaBlockMetadata_Generic() = default; - - size_t GetAllocationCount() const override { return m_Suballocations.size() - m_FreeCount; } - VkDeviceSize GetSumFreeSize() const override { return m_SumFreeSize; } - bool IsEmpty() const override { return (m_Suballocations.size() == 1) && (m_FreeCount == 1); } - void Free(VmaAllocHandle allocHandle) override { FreeSuballocation(FindAtOffset((VkDeviceSize)allocHandle - 1)); } - VkDeviceSize GetAllocationOffset(VmaAllocHandle allocHandle) const override { return (VkDeviceSize)allocHandle - 1; }; - - void Init(VkDeviceSize size) override; - bool Validate() const override; - - void AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const override; - void AddStatistics(VmaStatistics& inoutStats) const override; - -#if VMA_STATS_STRING_ENABLED - void PrintDetailedMap(class VmaJsonWriter& json, uint32_t mapRefCount) const override; -#endif - - bool CreateAllocationRequest( - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - bool upperAddress, - VmaSuballocationType allocType, - uint32_t strategy, - VmaAllocationRequest* pAllocationRequest) override; - - VkResult CheckCorruption(const void* pBlockData) override; - - void Alloc( - const VmaAllocationRequest& request, - VmaSuballocationType type, - void* userData) override; - - void GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) override; - void* GetAllocationUserData(VmaAllocHandle allocHandle) const override; - VmaAllocHandle GetAllocationListBegin() const override; - VmaAllocHandle GetNextAllocation(VmaAllocHandle prevAlloc) const override; - void Clear() override; - void SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) override; - void DebugLogAllAllocations() const override; - -private: - uint32_t m_FreeCount; - VkDeviceSize m_SumFreeSize; - VmaSuballocationList m_Suballocations; - // Suballocations that are free. Sorted by size, ascending. - VmaVector> m_FreeSuballocationsBySize; - - VkDeviceSize AlignAllocationSize(VkDeviceSize size) const { return IsVirtual() ? size : VmaAlignUp(size, (VkDeviceSize)16); } - - VmaSuballocationList::iterator FindAtOffset(VkDeviceSize offset) const; - bool ValidateFreeSuballocationList() const; - - // Checks if requested suballocation with given parameters can be placed in given pFreeSuballocItem. - // If yes, fills pOffset and returns true. If no, returns false. - bool CheckAllocation( - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - VmaSuballocationType allocType, - VmaSuballocationList::const_iterator suballocItem, - VmaAllocHandle* pAllocHandle) const; - - // Given free suballocation, it merges it with following one, which must also be free. - void MergeFreeWithNext(VmaSuballocationList::iterator item); - // Releases given suballocation, making it free. - // Merges it with adjacent free suballocations if applicable. - // Returns iterator to new free suballocation at this place. - VmaSuballocationList::iterator FreeSuballocation(VmaSuballocationList::iterator suballocItem); - // Given free suballocation, it inserts it into sorted list of - // m_FreeSuballocationsBySize if it is suitable. - void RegisterFreeSuballocation(VmaSuballocationList::iterator item); - // Given free suballocation, it removes it from sorted list of - // m_FreeSuballocationsBySize if it is suitable. - void UnregisterFreeSuballocation(VmaSuballocationList::iterator item); -}; - -#ifndef _VMA_BLOCK_METADATA_GENERIC_FUNCTIONS -VmaBlockMetadata_Generic::VmaBlockMetadata_Generic(const VkAllocationCallbacks* pAllocationCallbacks, - VkDeviceSize bufferImageGranularity, bool isVirtual) - : VmaBlockMetadata(pAllocationCallbacks, bufferImageGranularity, isVirtual), - m_FreeCount(0), - m_SumFreeSize(0), - m_Suballocations(VmaStlAllocator(pAllocationCallbacks)), - m_FreeSuballocationsBySize(VmaStlAllocator(pAllocationCallbacks)) {} - -void VmaBlockMetadata_Generic::Init(VkDeviceSize size) -{ - VmaBlockMetadata::Init(size); - - m_FreeCount = 1; - m_SumFreeSize = size; - - VmaSuballocation suballoc = {}; - suballoc.offset = 0; - suballoc.size = size; - suballoc.type = VMA_SUBALLOCATION_TYPE_FREE; - - m_Suballocations.push_back(suballoc); - m_FreeSuballocationsBySize.push_back(m_Suballocations.begin()); -} - -bool VmaBlockMetadata_Generic::Validate() const -{ - VMA_VALIDATE(!m_Suballocations.empty()); - - // Expected offset of new suballocation as calculated from previous ones. - VkDeviceSize calculatedOffset = 0; - // Expected number of free suballocations as calculated from traversing their list. - uint32_t calculatedFreeCount = 0; - // Expected sum size of free suballocations as calculated from traversing their list. - VkDeviceSize calculatedSumFreeSize = 0; - // Expected number of free suballocations that should be registered in - // m_FreeSuballocationsBySize calculated from traversing their list. - size_t freeSuballocationsToRegister = 0; - // True if previous visited suballocation was free. - bool prevFree = false; - - const VkDeviceSize debugMargin = GetDebugMargin(); - - for (const auto& subAlloc : m_Suballocations) - { - // Actual offset of this suballocation doesn't match expected one. - VMA_VALIDATE(subAlloc.offset == calculatedOffset); - - const bool currFree = (subAlloc.type == VMA_SUBALLOCATION_TYPE_FREE); - // Two adjacent free suballocations are invalid. They should be merged. - VMA_VALIDATE(!prevFree || !currFree); - - VmaAllocation alloc = (VmaAllocation)subAlloc.userData; - if (!IsVirtual()) - { - VMA_VALIDATE(currFree == (alloc == VK_NULL_HANDLE)); - } - - if (currFree) - { - calculatedSumFreeSize += subAlloc.size; - ++calculatedFreeCount; - ++freeSuballocationsToRegister; - - // Margin required between allocations - every free space must be at least that large. - VMA_VALIDATE(subAlloc.size >= debugMargin); - } - else - { - if (!IsVirtual()) - { - VMA_VALIDATE((VkDeviceSize)alloc->GetAllocHandle() == subAlloc.offset + 1); - VMA_VALIDATE(alloc->GetSize() == subAlloc.size); - } - - // Margin required between allocations - previous allocation must be free. - VMA_VALIDATE(debugMargin == 0 || prevFree); - } - - calculatedOffset += subAlloc.size; - prevFree = currFree; - } - - // Number of free suballocations registered in m_FreeSuballocationsBySize doesn't - // match expected one. - VMA_VALIDATE(m_FreeSuballocationsBySize.size() == freeSuballocationsToRegister); - - VkDeviceSize lastSize = 0; - for (size_t i = 0; i < m_FreeSuballocationsBySize.size(); ++i) - { - VmaSuballocationList::iterator suballocItem = m_FreeSuballocationsBySize[i]; - - // Only free suballocations can be registered in m_FreeSuballocationsBySize. - VMA_VALIDATE(suballocItem->type == VMA_SUBALLOCATION_TYPE_FREE); - // They must be sorted by size ascending. - VMA_VALIDATE(suballocItem->size >= lastSize); - - lastSize = suballocItem->size; - } - - // Check if totals match calculated values. - VMA_VALIDATE(ValidateFreeSuballocationList()); - VMA_VALIDATE(calculatedOffset == GetSize()); - VMA_VALIDATE(calculatedSumFreeSize == m_SumFreeSize); - VMA_VALIDATE(calculatedFreeCount == m_FreeCount); - - return true; -} - -void VmaBlockMetadata_Generic::AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const -{ - const uint32_t rangeCount = (uint32_t)m_Suballocations.size(); - inoutStats.statistics.blockCount++; - inoutStats.statistics.blockBytes += GetSize(); - - for (const auto& suballoc : m_Suballocations) - { - if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE) - VmaAddDetailedStatisticsAllocation(inoutStats, suballoc.size); - else - VmaAddDetailedStatisticsUnusedRange(inoutStats, suballoc.size); - } -} - -void VmaBlockMetadata_Generic::AddStatistics(VmaStatistics& inoutStats) const -{ - inoutStats.blockCount++; - inoutStats.allocationCount += (uint32_t)m_Suballocations.size() - m_FreeCount; - inoutStats.blockBytes += GetSize(); - inoutStats.allocationBytes += GetSize() - m_SumFreeSize; -} - -#if VMA_STATS_STRING_ENABLED -void VmaBlockMetadata_Generic::PrintDetailedMap(class VmaJsonWriter& json, uint32_t mapRefCount) const -{ - PrintDetailedMap_Begin(json, - m_SumFreeSize, // unusedBytes - m_Suballocations.size() - (size_t)m_FreeCount, // allocationCount - m_FreeCount, // unusedRangeCount - mapRefCount); - - for (const auto& suballoc : m_Suballocations) - { - if (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE) - { - PrintDetailedMap_UnusedRange(json, suballoc.offset, suballoc.size); - } - else - { - PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.size, suballoc.userData); - } - } - - PrintDetailedMap_End(json); -} -#endif // VMA_STATS_STRING_ENABLED - -bool VmaBlockMetadata_Generic::CreateAllocationRequest( - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - bool upperAddress, - VmaSuballocationType allocType, - uint32_t strategy, - VmaAllocationRequest* pAllocationRequest) -{ - VMA_ASSERT(allocSize > 0); - VMA_ASSERT(!upperAddress); - VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE); - VMA_ASSERT(pAllocationRequest != VMA_NULL); - VMA_HEAVY_ASSERT(Validate()); - - allocSize = AlignAllocationSize(allocSize); - - pAllocationRequest->type = VmaAllocationRequestType::Normal; - pAllocationRequest->size = allocSize; - - const VkDeviceSize debugMargin = GetDebugMargin(); - - // There is not enough total free space in this block to fulfill the request: Early return. - if (m_SumFreeSize < allocSize + debugMargin) - { - return false; - } - - // New algorithm, efficiently searching freeSuballocationsBySize. - const size_t freeSuballocCount = m_FreeSuballocationsBySize.size(); - if (freeSuballocCount > 0) - { - if (strategy == 0 || - strategy == VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT) - { - // Find first free suballocation with size not less than allocSize + debugMargin. - VmaSuballocationList::iterator* const it = VmaBinaryFindFirstNotLess( - m_FreeSuballocationsBySize.data(), - m_FreeSuballocationsBySize.data() + freeSuballocCount, - allocSize + debugMargin, - VmaSuballocationItemSizeLess()); - size_t index = it - m_FreeSuballocationsBySize.data(); - for (; index < freeSuballocCount; ++index) - { - if (CheckAllocation( - allocSize, - allocAlignment, - allocType, - m_FreeSuballocationsBySize[index], - &pAllocationRequest->allocHandle)) - { - pAllocationRequest->item = m_FreeSuballocationsBySize[index]; - return true; - } - } - } - else if (strategy == VMA_ALLOCATION_INTERNAL_STRATEGY_MIN_OFFSET) - { - for (VmaSuballocationList::iterator it = m_Suballocations.begin(); - it != m_Suballocations.end(); - ++it) - { - if (it->type == VMA_SUBALLOCATION_TYPE_FREE && CheckAllocation( - allocSize, - allocAlignment, - allocType, - it, - &pAllocationRequest->allocHandle)) - { - pAllocationRequest->item = it; - return true; - } - } - } - else - { - VMA_ASSERT(strategy & (VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT | VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT )); - // Search staring from biggest suballocations. - for (size_t index = freeSuballocCount; index--; ) - { - if (CheckAllocation( - allocSize, - allocAlignment, - allocType, - m_FreeSuballocationsBySize[index], - &pAllocationRequest->allocHandle)) - { - pAllocationRequest->item = m_FreeSuballocationsBySize[index]; - return true; - } - } - } - } - - return false; -} - -VkResult VmaBlockMetadata_Generic::CheckCorruption(const void* pBlockData) -{ - for (auto& suballoc : m_Suballocations) - { - if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE) - { - if (!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size)) - { - VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!"); - return VK_ERROR_UNKNOWN_COPY; - } - } - } - - return VK_SUCCESS; -} - -void VmaBlockMetadata_Generic::Alloc( - const VmaAllocationRequest& request, - VmaSuballocationType type, - void* userData) -{ - VMA_ASSERT(request.type == VmaAllocationRequestType::Normal); - VMA_ASSERT(request.item != m_Suballocations.end()); - VmaSuballocation& suballoc = *request.item; - // Given suballocation is a free block. - VMA_ASSERT(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE); - - // Given offset is inside this suballocation. - VMA_ASSERT((VkDeviceSize)request.allocHandle - 1 >= suballoc.offset); - const VkDeviceSize paddingBegin = (VkDeviceSize)request.allocHandle - suballoc.offset - 1; - VMA_ASSERT(suballoc.size >= paddingBegin + request.size); - const VkDeviceSize paddingEnd = suballoc.size - paddingBegin - request.size; - - // Unregister this free suballocation from m_FreeSuballocationsBySize and update - // it to become used. - UnregisterFreeSuballocation(request.item); - - suballoc.offset = (VkDeviceSize)request.allocHandle - 1; - suballoc.size = request.size; - suballoc.type = type; - suballoc.userData = userData; - - // If there are any free bytes remaining at the end, insert new free suballocation after current one. - if (paddingEnd) - { - VmaSuballocation paddingSuballoc = {}; - paddingSuballoc.offset = suballoc.offset + suballoc.size; - paddingSuballoc.size = paddingEnd; - paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE; - VmaSuballocationList::iterator next = request.item; - ++next; - const VmaSuballocationList::iterator paddingEndItem = - m_Suballocations.insert(next, paddingSuballoc); - RegisterFreeSuballocation(paddingEndItem); - } - - // If there are any free bytes remaining at the beginning, insert new free suballocation before current one. - if (paddingBegin) - { - VmaSuballocation paddingSuballoc = {}; - paddingSuballoc.offset = suballoc.offset - paddingBegin; - paddingSuballoc.size = paddingBegin; - paddingSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE; - const VmaSuballocationList::iterator paddingBeginItem = - m_Suballocations.insert(request.item, paddingSuballoc); - RegisterFreeSuballocation(paddingBeginItem); - } - - // Update totals. - m_FreeCount = m_FreeCount - 1; - if (paddingBegin > 0) - { - ++m_FreeCount; - } - if (paddingEnd > 0) - { - ++m_FreeCount; - } - m_SumFreeSize -= request.size; -} - -void VmaBlockMetadata_Generic::GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) -{ - outInfo.offset = (VkDeviceSize)allocHandle - 1; - const VmaSuballocation& suballoc = *FindAtOffset(outInfo.offset); - outInfo.size = suballoc.size; - outInfo.pUserData = suballoc.userData; -} - -void* VmaBlockMetadata_Generic::GetAllocationUserData(VmaAllocHandle allocHandle) const -{ - return FindAtOffset((VkDeviceSize)allocHandle - 1)->userData; -} - -VmaAllocHandle VmaBlockMetadata_Generic::GetAllocationListBegin() const -{ - if (IsEmpty()) - return VK_NULL_HANDLE; - - for (const auto& suballoc : m_Suballocations) - { - if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE) - return (VmaAllocHandle)(suballoc.offset + 1); - } - VMA_ASSERT(false && "Should contain at least 1 allocation!"); - return VK_NULL_HANDLE; -} - -VmaAllocHandle VmaBlockMetadata_Generic::GetNextAllocation(VmaAllocHandle prevAlloc) const -{ - VmaSuballocationList::const_iterator prev = FindAtOffset((VkDeviceSize)prevAlloc - 1); - - for (VmaSuballocationList::const_iterator it = ++prev; it != m_Suballocations.end(); ++it) - { - if (it->type != VMA_SUBALLOCATION_TYPE_FREE) - return (VmaAllocHandle)(it->offset + 1); - } - return VK_NULL_HANDLE; -} - -void VmaBlockMetadata_Generic::Clear() -{ - const VkDeviceSize size = GetSize(); - - VMA_ASSERT(IsVirtual()); - m_FreeCount = 1; - m_SumFreeSize = size; - m_Suballocations.clear(); - m_FreeSuballocationsBySize.clear(); - - VmaSuballocation suballoc = {}; - suballoc.offset = 0; - suballoc.size = size; - suballoc.type = VMA_SUBALLOCATION_TYPE_FREE; - m_Suballocations.push_back(suballoc); - - m_FreeSuballocationsBySize.push_back(m_Suballocations.begin()); -} - -void VmaBlockMetadata_Generic::SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) -{ - VmaSuballocation& suballoc = *FindAtOffset((VkDeviceSize)allocHandle - 1); - suballoc.userData = userData; -} - -void VmaBlockMetadata_Generic::DebugLogAllAllocations() const -{ - for (const auto& suballoc : m_Suballocations) - { - if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE) - DebugLogAllocation(suballoc.offset, suballoc.size, suballoc.userData); - } -} - -VmaSuballocationList::iterator VmaBlockMetadata_Generic::FindAtOffset(VkDeviceSize offset) const -{ - VMA_HEAVY_ASSERT(!m_Suballocations.empty()); - const VkDeviceSize last = m_Suballocations.rbegin()->offset; - if (last == offset) - return m_Suballocations.rbegin().drop_const(); - const VkDeviceSize first = m_Suballocations.begin()->offset; - if (first == offset) - return m_Suballocations.begin().drop_const(); - - const size_t suballocCount = m_Suballocations.size(); - const VkDeviceSize step = (last - first + m_Suballocations.begin()->size) / suballocCount; - auto findSuballocation = [&](auto begin, auto end) -> VmaSuballocationList::iterator - { - for (auto suballocItem = begin; - suballocItem != end; - ++suballocItem) - { - if (suballocItem->offset == offset) - return suballocItem.drop_const(); - } - VMA_ASSERT(false && "Not found!"); - return m_Suballocations.end().drop_const(); - }; - // If requested offset is closer to the end of range, search from the end - if (offset - first > suballocCount * step / 2) - { - return findSuballocation(m_Suballocations.rbegin(), m_Suballocations.rend()); - } - return findSuballocation(m_Suballocations.begin(), m_Suballocations.end()); -} - -bool VmaBlockMetadata_Generic::ValidateFreeSuballocationList() const -{ - VkDeviceSize lastSize = 0; - for (size_t i = 0, count = m_FreeSuballocationsBySize.size(); i < count; ++i) - { - const VmaSuballocationList::iterator it = m_FreeSuballocationsBySize[i]; - - VMA_VALIDATE(it->type == VMA_SUBALLOCATION_TYPE_FREE); - VMA_VALIDATE(it->size >= lastSize); - lastSize = it->size; - } - return true; -} - -bool VmaBlockMetadata_Generic::CheckAllocation( - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - VmaSuballocationType allocType, - VmaSuballocationList::const_iterator suballocItem, - VmaAllocHandle* pAllocHandle) const -{ - VMA_ASSERT(allocSize > 0); - VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE); - VMA_ASSERT(suballocItem != m_Suballocations.cend()); - VMA_ASSERT(pAllocHandle != VMA_NULL); - - const VkDeviceSize debugMargin = GetDebugMargin(); - const VkDeviceSize bufferImageGranularity = GetBufferImageGranularity(); - - const VmaSuballocation& suballoc = *suballocItem; - VMA_ASSERT(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE); - - // Size of this suballocation is too small for this request: Early return. - if (suballoc.size < allocSize) - { - return false; - } - - // Start from offset equal to beginning of this suballocation. - VkDeviceSize offset = suballoc.offset + (suballocItem == m_Suballocations.cbegin() ? 0 : GetDebugMargin()); - - // Apply debugMargin from the end of previous alloc. - if (debugMargin > 0) - { - offset += debugMargin; - } - - // Apply alignment. - offset = VmaAlignUp(offset, allocAlignment); - - // Check previous suballocations for BufferImageGranularity conflicts. - // Make bigger alignment if necessary. - if (bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment) - { - bool bufferImageGranularityConflict = false; - VmaSuballocationList::const_iterator prevSuballocItem = suballocItem; - while (prevSuballocItem != m_Suballocations.cbegin()) - { - --prevSuballocItem; - const VmaSuballocation& prevSuballoc = *prevSuballocItem; - if (VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, offset, bufferImageGranularity)) - { - if (VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType)) - { - bufferImageGranularityConflict = true; - break; - } - } - else - // Already on previous page. - break; - } - if (bufferImageGranularityConflict) - { - offset = VmaAlignUp(offset, bufferImageGranularity); - } - } - - // Calculate padding at the beginning based on current offset. - const VkDeviceSize paddingBegin = offset - suballoc.offset; - - // Fail if requested size plus margin after is bigger than size of this suballocation. - if (paddingBegin + allocSize + debugMargin > suballoc.size) - { - return false; - } - - // Check next suballocations for BufferImageGranularity conflicts. - // If conflict exists, allocation cannot be made here. - if (allocSize % bufferImageGranularity || offset % bufferImageGranularity) - { - VmaSuballocationList::const_iterator nextSuballocItem = suballocItem; - ++nextSuballocItem; - while (nextSuballocItem != m_Suballocations.cend()) - { - const VmaSuballocation& nextSuballoc = *nextSuballocItem; - if (VmaBlocksOnSamePage(offset, allocSize, nextSuballoc.offset, bufferImageGranularity)) - { - if (VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type)) - { - return false; - } - } - else - { - // Already on next page. - break; - } - ++nextSuballocItem; - } - } - - *pAllocHandle = (VmaAllocHandle)(offset + 1); - // All tests passed: Success. pAllocHandle is already filled. - return true; -} - -void VmaBlockMetadata_Generic::MergeFreeWithNext(VmaSuballocationList::iterator item) -{ - VMA_ASSERT(item != m_Suballocations.end()); - VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE); - - VmaSuballocationList::iterator nextItem = item; - ++nextItem; - VMA_ASSERT(nextItem != m_Suballocations.end()); - VMA_ASSERT(nextItem->type == VMA_SUBALLOCATION_TYPE_FREE); - - item->size += nextItem->size; - --m_FreeCount; - m_Suballocations.erase(nextItem); -} - -VmaSuballocationList::iterator VmaBlockMetadata_Generic::FreeSuballocation(VmaSuballocationList::iterator suballocItem) -{ - // Change this suballocation to be marked as free. - VmaSuballocation& suballoc = *suballocItem; - suballoc.type = VMA_SUBALLOCATION_TYPE_FREE; - suballoc.userData = VMA_NULL; - - // Update totals. - ++m_FreeCount; - m_SumFreeSize += suballoc.size; - - // Merge with previous and/or next suballocation if it's also free. - bool mergeWithNext = false; - bool mergeWithPrev = false; - - VmaSuballocationList::iterator nextItem = suballocItem; - ++nextItem; - if ((nextItem != m_Suballocations.end()) && (nextItem->type == VMA_SUBALLOCATION_TYPE_FREE)) - { - mergeWithNext = true; - } - - VmaSuballocationList::iterator prevItem = suballocItem; - if (suballocItem != m_Suballocations.begin()) - { - --prevItem; - if (prevItem->type == VMA_SUBALLOCATION_TYPE_FREE) - { - mergeWithPrev = true; - } - } - - if (mergeWithNext) - { - UnregisterFreeSuballocation(nextItem); - MergeFreeWithNext(suballocItem); - } - - if (mergeWithPrev) - { - UnregisterFreeSuballocation(prevItem); - MergeFreeWithNext(prevItem); - RegisterFreeSuballocation(prevItem); - return prevItem; - } - else - { - RegisterFreeSuballocation(suballocItem); - return suballocItem; - } -} - -void VmaBlockMetadata_Generic::RegisterFreeSuballocation(VmaSuballocationList::iterator item) -{ - VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE); - VMA_ASSERT(item->size > 0); - - // You may want to enable this validation at the beginning or at the end of - // this function, depending on what do you want to check. - VMA_HEAVY_ASSERT(ValidateFreeSuballocationList()); - - if (m_FreeSuballocationsBySize.empty()) - { - m_FreeSuballocationsBySize.push_back(item); - } - else - { - VmaVectorInsertSorted(m_FreeSuballocationsBySize, item); - } - - //VMA_HEAVY_ASSERT(ValidateFreeSuballocationList()); -} - -void VmaBlockMetadata_Generic::UnregisterFreeSuballocation(VmaSuballocationList::iterator item) -{ - VMA_ASSERT(item->type == VMA_SUBALLOCATION_TYPE_FREE); - VMA_ASSERT(item->size > 0); - - // You may want to enable this validation at the beginning or at the end of - // this function, depending on what do you want to check. - VMA_HEAVY_ASSERT(ValidateFreeSuballocationList()); - - VmaSuballocationList::iterator* const it = VmaBinaryFindFirstNotLess( - m_FreeSuballocationsBySize.data(), - m_FreeSuballocationsBySize.data() + m_FreeSuballocationsBySize.size(), - item, - VmaSuballocationItemSizeLess()); - for (size_t index = it - m_FreeSuballocationsBySize.data(); - index < m_FreeSuballocationsBySize.size(); - ++index) - { - if (m_FreeSuballocationsBySize[index] == item) - { - VmaVectorRemove(m_FreeSuballocationsBySize, index); - return; - } - VMA_ASSERT((m_FreeSuballocationsBySize[index]->size == item->size) && "Not found."); - } - VMA_ASSERT(0 && "Not found."); - - //VMA_HEAVY_ASSERT(ValidateFreeSuballocationList()); -} -#endif // _VMA_BLOCK_METADATA_GENERIC_FUNCTIONS -#endif // _VMA_BLOCK_METADATA_GENERIC -#endif // #if 0 - -#ifndef _VMA_BLOCK_METADATA_LINEAR -/* -Allocations and their references in internal data structure look like this: - -if(m_2ndVectorMode == SECOND_VECTOR_EMPTY): - - 0 +-------+ - | | - | | - | | - +-------+ - | Alloc | 1st[m_1stNullItemsBeginCount] - +-------+ - | Alloc | 1st[m_1stNullItemsBeginCount + 1] - +-------+ - | ... | - +-------+ - | Alloc | 1st[1st.size() - 1] - +-------+ - | | - | | - | | -GetSize() +-------+ - -if(m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER): - - 0 +-------+ - | Alloc | 2nd[0] - +-------+ - | Alloc | 2nd[1] - +-------+ - | ... | - +-------+ - | Alloc | 2nd[2nd.size() - 1] - +-------+ - | | - | | - | | - +-------+ - | Alloc | 1st[m_1stNullItemsBeginCount] - +-------+ - | Alloc | 1st[m_1stNullItemsBeginCount + 1] - +-------+ - | ... | - +-------+ - | Alloc | 1st[1st.size() - 1] - +-------+ - | | -GetSize() +-------+ - -if(m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK): - - 0 +-------+ - | | - | | - | | - +-------+ - | Alloc | 1st[m_1stNullItemsBeginCount] - +-------+ - | Alloc | 1st[m_1stNullItemsBeginCount + 1] - +-------+ - | ... | - +-------+ - | Alloc | 1st[1st.size() - 1] - +-------+ - | | - | | - | | - +-------+ - | Alloc | 2nd[2nd.size() - 1] - +-------+ - | ... | - +-------+ - | Alloc | 2nd[1] - +-------+ - | Alloc | 2nd[0] -GetSize() +-------+ - -*/ -class VmaBlockMetadata_Linear : public VmaBlockMetadata -{ - VMA_CLASS_NO_COPY(VmaBlockMetadata_Linear) -public: - VmaBlockMetadata_Linear(const VkAllocationCallbacks* pAllocationCallbacks, - VkDeviceSize bufferImageGranularity, bool isVirtual); - virtual ~VmaBlockMetadata_Linear() = default; - - VkDeviceSize GetSumFreeSize() const override { return m_SumFreeSize; } - bool IsEmpty() const override { return GetAllocationCount() == 0; } - VkDeviceSize GetAllocationOffset(VmaAllocHandle allocHandle) const override { return (VkDeviceSize)allocHandle - 1; }; - - void Init(VkDeviceSize size) override; - bool Validate() const override; - size_t GetAllocationCount() const override; - size_t GetFreeRegionsCount() const override; - - void AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const override; - void AddStatistics(VmaStatistics& inoutStats) const override; - -#if VMA_STATS_STRING_ENABLED - void PrintDetailedMap(class VmaJsonWriter& json) const override; -#endif - - bool CreateAllocationRequest( - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - bool upperAddress, - VmaSuballocationType allocType, - uint32_t strategy, - VmaAllocationRequest* pAllocationRequest) override; - - VkResult CheckCorruption(const void* pBlockData) override; - - void Alloc( - const VmaAllocationRequest& request, - VmaSuballocationType type, - void* userData) override; - - void Free(VmaAllocHandle allocHandle) override; - void GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) override; - void* GetAllocationUserData(VmaAllocHandle allocHandle) const override; - VmaAllocHandle GetAllocationListBegin() const override; - VmaAllocHandle GetNextAllocation(VmaAllocHandle prevAlloc) const override; - VkDeviceSize GetNextFreeRegionSize(VmaAllocHandle alloc) const override; - void Clear() override; - void SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) override; - void DebugLogAllAllocations() const override; - -private: - /* - There are two suballocation vectors, used in ping-pong way. - The one with index m_1stVectorIndex is called 1st. - The one with index (m_1stVectorIndex ^ 1) is called 2nd. - 2nd can be non-empty only when 1st is not empty. - When 2nd is not empty, m_2ndVectorMode indicates its mode of operation. - */ - typedef VmaVector> SuballocationVectorType; - - enum SECOND_VECTOR_MODE - { - SECOND_VECTOR_EMPTY, - /* - Suballocations in 2nd vector are created later than the ones in 1st, but they - all have smaller offset. - */ - SECOND_VECTOR_RING_BUFFER, - /* - Suballocations in 2nd vector are upper side of double stack. - They all have offsets higher than those in 1st vector. - Top of this stack means smaller offsets, but higher indices in this vector. - */ - SECOND_VECTOR_DOUBLE_STACK, - }; - - VkDeviceSize m_SumFreeSize; - SuballocationVectorType m_Suballocations0, m_Suballocations1; - uint32_t m_1stVectorIndex; - SECOND_VECTOR_MODE m_2ndVectorMode; - // Number of items in 1st vector with hAllocation = null at the beginning. - size_t m_1stNullItemsBeginCount; - // Number of other items in 1st vector with hAllocation = null somewhere in the middle. - size_t m_1stNullItemsMiddleCount; - // Number of items in 2nd vector with hAllocation = null. - size_t m_2ndNullItemsCount; - - SuballocationVectorType& AccessSuballocations1st() { return m_1stVectorIndex ? m_Suballocations1 : m_Suballocations0; } - SuballocationVectorType& AccessSuballocations2nd() { return m_1stVectorIndex ? m_Suballocations0 : m_Suballocations1; } - const SuballocationVectorType& AccessSuballocations1st() const { return m_1stVectorIndex ? m_Suballocations1 : m_Suballocations0; } - const SuballocationVectorType& AccessSuballocations2nd() const { return m_1stVectorIndex ? m_Suballocations0 : m_Suballocations1; } - - VmaSuballocation& FindSuballocation(VkDeviceSize offset) const; - bool ShouldCompact1st() const; - void CleanupAfterFree(); - - bool CreateAllocationRequest_LowerAddress( - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - VmaSuballocationType allocType, - uint32_t strategy, - VmaAllocationRequest* pAllocationRequest); - bool CreateAllocationRequest_UpperAddress( - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - VmaSuballocationType allocType, - uint32_t strategy, - VmaAllocationRequest* pAllocationRequest); -}; - -#ifndef _VMA_BLOCK_METADATA_LINEAR_FUNCTIONS -VmaBlockMetadata_Linear::VmaBlockMetadata_Linear(const VkAllocationCallbacks* pAllocationCallbacks, - VkDeviceSize bufferImageGranularity, bool isVirtual) - : VmaBlockMetadata(pAllocationCallbacks, bufferImageGranularity, isVirtual), - m_SumFreeSize(0), - m_Suballocations0(VmaStlAllocator(pAllocationCallbacks)), - m_Suballocations1(VmaStlAllocator(pAllocationCallbacks)), - m_1stVectorIndex(0), - m_2ndVectorMode(SECOND_VECTOR_EMPTY), - m_1stNullItemsBeginCount(0), - m_1stNullItemsMiddleCount(0), - m_2ndNullItemsCount(0) {} - -void VmaBlockMetadata_Linear::Init(VkDeviceSize size) -{ - VmaBlockMetadata::Init(size); - m_SumFreeSize = size; -} - -bool VmaBlockMetadata_Linear::Validate() const -{ - const SuballocationVectorType& suballocations1st = AccessSuballocations1st(); - const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); - - VMA_VALIDATE(suballocations2nd.empty() == (m_2ndVectorMode == SECOND_VECTOR_EMPTY)); - VMA_VALIDATE(!suballocations1st.empty() || - suballocations2nd.empty() || - m_2ndVectorMode != SECOND_VECTOR_RING_BUFFER); - - if (!suballocations1st.empty()) - { - // Null item at the beginning should be accounted into m_1stNullItemsBeginCount. - VMA_VALIDATE(suballocations1st[m_1stNullItemsBeginCount].type != VMA_SUBALLOCATION_TYPE_FREE); - // Null item at the end should be just pop_back(). - VMA_VALIDATE(suballocations1st.back().type != VMA_SUBALLOCATION_TYPE_FREE); - } - if (!suballocations2nd.empty()) - { - // Null item at the end should be just pop_back(). - VMA_VALIDATE(suballocations2nd.back().type != VMA_SUBALLOCATION_TYPE_FREE); - } - - VMA_VALIDATE(m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount <= suballocations1st.size()); - VMA_VALIDATE(m_2ndNullItemsCount <= suballocations2nd.size()); - - VkDeviceSize sumUsedSize = 0; - const size_t suballoc1stCount = suballocations1st.size(); - const VkDeviceSize debugMargin = GetDebugMargin(); - VkDeviceSize offset = 0; - - if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) - { - const size_t suballoc2ndCount = suballocations2nd.size(); - size_t nullItem2ndCount = 0; - for (size_t i = 0; i < suballoc2ndCount; ++i) - { - const VmaSuballocation& suballoc = suballocations2nd[i]; - const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE); - - VmaAllocation const alloc = (VmaAllocation)suballoc.userData; - if (!IsVirtual()) - { - VMA_VALIDATE(currFree == (alloc == VK_NULL_HANDLE)); - } - VMA_VALIDATE(suballoc.offset >= offset); - - if (!currFree) - { - if (!IsVirtual()) - { - VMA_VALIDATE((VkDeviceSize)alloc->GetAllocHandle() == suballoc.offset + 1); - VMA_VALIDATE(alloc->GetSize() == suballoc.size); - } - sumUsedSize += suballoc.size; - } - else - { - ++nullItem2ndCount; - } - - offset = suballoc.offset + suballoc.size + debugMargin; - } - - VMA_VALIDATE(nullItem2ndCount == m_2ndNullItemsCount); - } - - for (size_t i = 0; i < m_1stNullItemsBeginCount; ++i) - { - const VmaSuballocation& suballoc = suballocations1st[i]; - VMA_VALIDATE(suballoc.type == VMA_SUBALLOCATION_TYPE_FREE && - suballoc.userData == VMA_NULL); - } - - size_t nullItem1stCount = m_1stNullItemsBeginCount; - - for (size_t i = m_1stNullItemsBeginCount; i < suballoc1stCount; ++i) - { - const VmaSuballocation& suballoc = suballocations1st[i]; - const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE); - - VmaAllocation const alloc = (VmaAllocation)suballoc.userData; - if (!IsVirtual()) - { - VMA_VALIDATE(currFree == (alloc == VK_NULL_HANDLE)); - } - VMA_VALIDATE(suballoc.offset >= offset); - VMA_VALIDATE(i >= m_1stNullItemsBeginCount || currFree); - - if (!currFree) - { - if (!IsVirtual()) - { - VMA_VALIDATE((VkDeviceSize)alloc->GetAllocHandle() == suballoc.offset + 1); - VMA_VALIDATE(alloc->GetSize() == suballoc.size); - } - sumUsedSize += suballoc.size; - } - else - { - ++nullItem1stCount; - } - - offset = suballoc.offset + suballoc.size + debugMargin; - } - VMA_VALIDATE(nullItem1stCount == m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount); - - if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) - { - const size_t suballoc2ndCount = suballocations2nd.size(); - size_t nullItem2ndCount = 0; - for (size_t i = suballoc2ndCount; i--; ) - { - const VmaSuballocation& suballoc = suballocations2nd[i]; - const bool currFree = (suballoc.type == VMA_SUBALLOCATION_TYPE_FREE); - - VmaAllocation const alloc = (VmaAllocation)suballoc.userData; - if (!IsVirtual()) - { - VMA_VALIDATE(currFree == (alloc == VK_NULL_HANDLE)); - } - VMA_VALIDATE(suballoc.offset >= offset); - - if (!currFree) - { - if (!IsVirtual()) - { - VMA_VALIDATE((VkDeviceSize)alloc->GetAllocHandle() == suballoc.offset + 1); - VMA_VALIDATE(alloc->GetSize() == suballoc.size); - } - sumUsedSize += suballoc.size; - } - else - { - ++nullItem2ndCount; - } - - offset = suballoc.offset + suballoc.size + debugMargin; - } - - VMA_VALIDATE(nullItem2ndCount == m_2ndNullItemsCount); - } - - VMA_VALIDATE(offset <= GetSize()); - VMA_VALIDATE(m_SumFreeSize == GetSize() - sumUsedSize); - - return true; -} - -size_t VmaBlockMetadata_Linear::GetAllocationCount() const -{ - return AccessSuballocations1st().size() - m_1stNullItemsBeginCount - m_1stNullItemsMiddleCount + - AccessSuballocations2nd().size() - m_2ndNullItemsCount; -} - -size_t VmaBlockMetadata_Linear::GetFreeRegionsCount() const -{ - // Function only used for defragmentation, which is disabled for this algorithm - VMA_ASSERT(0); - return SIZE_MAX; -} - -void VmaBlockMetadata_Linear::AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const -{ - const VkDeviceSize size = GetSize(); - const SuballocationVectorType& suballocations1st = AccessSuballocations1st(); - const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); - const size_t suballoc1stCount = suballocations1st.size(); - const size_t suballoc2ndCount = suballocations2nd.size(); - - inoutStats.statistics.blockCount++; - inoutStats.statistics.blockBytes += size; - - VkDeviceSize lastOffset = 0; - - if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) - { - const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset; - size_t nextAlloc2ndIndex = 0; - while (lastOffset < freeSpace2ndTo1stEnd) - { - // Find next non-null allocation or move nextAllocIndex to the end. - while (nextAlloc2ndIndex < suballoc2ndCount && - suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL) - { - ++nextAlloc2ndIndex; - } - - // Found non-null allocation. - if (nextAlloc2ndIndex < suballoc2ndCount) - { - const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; - - // 1. Process free space before this allocation. - if (lastOffset < suballoc.offset) - { - // There is free space from lastOffset to suballoc.offset. - const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; - VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize); - } - - // 2. Process this allocation. - // There is allocation with suballoc.offset, suballoc.size. - VmaAddDetailedStatisticsAllocation(inoutStats, suballoc.size); - - // 3. Prepare for next iteration. - lastOffset = suballoc.offset + suballoc.size; - ++nextAlloc2ndIndex; - } - // We are at the end. - else - { - // There is free space from lastOffset to freeSpace2ndTo1stEnd. - if (lastOffset < freeSpace2ndTo1stEnd) - { - const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset; - VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize); - } - - // End of loop. - lastOffset = freeSpace2ndTo1stEnd; - } - } - } - - size_t nextAlloc1stIndex = m_1stNullItemsBeginCount; - const VkDeviceSize freeSpace1stTo2ndEnd = - m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size; - while (lastOffset < freeSpace1stTo2ndEnd) - { - // Find next non-null allocation or move nextAllocIndex to the end. - while (nextAlloc1stIndex < suballoc1stCount && - suballocations1st[nextAlloc1stIndex].userData == VMA_NULL) - { - ++nextAlloc1stIndex; - } - - // Found non-null allocation. - if (nextAlloc1stIndex < suballoc1stCount) - { - const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex]; - - // 1. Process free space before this allocation. - if (lastOffset < suballoc.offset) - { - // There is free space from lastOffset to suballoc.offset. - const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; - VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize); - } - - // 2. Process this allocation. - // There is allocation with suballoc.offset, suballoc.size. - VmaAddDetailedStatisticsAllocation(inoutStats, suballoc.size); - - // 3. Prepare for next iteration. - lastOffset = suballoc.offset + suballoc.size; - ++nextAlloc1stIndex; - } - // We are at the end. - else - { - // There is free space from lastOffset to freeSpace1stTo2ndEnd. - if (lastOffset < freeSpace1stTo2ndEnd) - { - const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset; - VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize); - } - - // End of loop. - lastOffset = freeSpace1stTo2ndEnd; - } - } - - if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) - { - size_t nextAlloc2ndIndex = suballocations2nd.size() - 1; - while (lastOffset < size) - { - // Find next non-null allocation or move nextAllocIndex to the end. - while (nextAlloc2ndIndex != SIZE_MAX && - suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL) - { - --nextAlloc2ndIndex; - } - - // Found non-null allocation. - if (nextAlloc2ndIndex != SIZE_MAX) - { - const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; - - // 1. Process free space before this allocation. - if (lastOffset < suballoc.offset) - { - // There is free space from lastOffset to suballoc.offset. - const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; - VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize); - } - - // 2. Process this allocation. - // There is allocation with suballoc.offset, suballoc.size. - VmaAddDetailedStatisticsAllocation(inoutStats, suballoc.size); - - // 3. Prepare for next iteration. - lastOffset = suballoc.offset + suballoc.size; - --nextAlloc2ndIndex; - } - // We are at the end. - else - { - // There is free space from lastOffset to size. - if (lastOffset < size) - { - const VkDeviceSize unusedRangeSize = size - lastOffset; - VmaAddDetailedStatisticsUnusedRange(inoutStats, unusedRangeSize); - } - - // End of loop. - lastOffset = size; - } - } - } -} - -void VmaBlockMetadata_Linear::AddStatistics(VmaStatistics& inoutStats) const -{ - const SuballocationVectorType& suballocations1st = AccessSuballocations1st(); - const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); - const VkDeviceSize size = GetSize(); - const size_t suballoc1stCount = suballocations1st.size(); - const size_t suballoc2ndCount = suballocations2nd.size(); - - inoutStats.blockCount++; - inoutStats.blockBytes += size; - inoutStats.allocationBytes += size - m_SumFreeSize; - - VkDeviceSize lastOffset = 0; - - if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) - { - const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset; - size_t nextAlloc2ndIndex = m_1stNullItemsBeginCount; - while (lastOffset < freeSpace2ndTo1stEnd) - { - // Find next non-null allocation or move nextAlloc2ndIndex to the end. - while (nextAlloc2ndIndex < suballoc2ndCount && - suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL) - { - ++nextAlloc2ndIndex; - } - - // Found non-null allocation. - if (nextAlloc2ndIndex < suballoc2ndCount) - { - const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; - - // 1. Process free space before this allocation. - if (lastOffset < suballoc.offset) - { - // There is free space from lastOffset to suballoc.offset. - const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; - } - - // 2. Process this allocation. - // There is allocation with suballoc.offset, suballoc.size. - ++inoutStats.allocationCount; - - // 3. Prepare for next iteration. - lastOffset = suballoc.offset + suballoc.size; - ++nextAlloc2ndIndex; - } - // We are at the end. - else - { - if (lastOffset < freeSpace2ndTo1stEnd) - { - // There is free space from lastOffset to freeSpace2ndTo1stEnd. - const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset; - } - - // End of loop. - lastOffset = freeSpace2ndTo1stEnd; - } - } - } - - size_t nextAlloc1stIndex = m_1stNullItemsBeginCount; - const VkDeviceSize freeSpace1stTo2ndEnd = - m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size; - while (lastOffset < freeSpace1stTo2ndEnd) - { - // Find next non-null allocation or move nextAllocIndex to the end. - while (nextAlloc1stIndex < suballoc1stCount && - suballocations1st[nextAlloc1stIndex].userData == VMA_NULL) - { - ++nextAlloc1stIndex; - } - - // Found non-null allocation. - if (nextAlloc1stIndex < suballoc1stCount) - { - const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex]; - - // 1. Process free space before this allocation. - if (lastOffset < suballoc.offset) - { - // There is free space from lastOffset to suballoc.offset. - const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; - } - - // 2. Process this allocation. - // There is allocation with suballoc.offset, suballoc.size. - ++inoutStats.allocationCount; - - // 3. Prepare for next iteration. - lastOffset = suballoc.offset + suballoc.size; - ++nextAlloc1stIndex; - } - // We are at the end. - else - { - if (lastOffset < freeSpace1stTo2ndEnd) - { - // There is free space from lastOffset to freeSpace1stTo2ndEnd. - const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset; - } - - // End of loop. - lastOffset = freeSpace1stTo2ndEnd; - } - } - - if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) - { - size_t nextAlloc2ndIndex = suballocations2nd.size() - 1; - while (lastOffset < size) - { - // Find next non-null allocation or move nextAlloc2ndIndex to the end. - while (nextAlloc2ndIndex != SIZE_MAX && - suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL) - { - --nextAlloc2ndIndex; - } - - // Found non-null allocation. - if (nextAlloc2ndIndex != SIZE_MAX) - { - const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; - - // 1. Process free space before this allocation. - if (lastOffset < suballoc.offset) - { - // There is free space from lastOffset to suballoc.offset. - const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; - } - - // 2. Process this allocation. - // There is allocation with suballoc.offset, suballoc.size. - ++inoutStats.allocationCount; - - // 3. Prepare for next iteration. - lastOffset = suballoc.offset + suballoc.size; - --nextAlloc2ndIndex; - } - // We are at the end. - else - { - if (lastOffset < size) - { - // There is free space from lastOffset to size. - const VkDeviceSize unusedRangeSize = size - lastOffset; - } - - // End of loop. - lastOffset = size; - } - } - } -} - -#if VMA_STATS_STRING_ENABLED -void VmaBlockMetadata_Linear::PrintDetailedMap(class VmaJsonWriter& json) const -{ - const VkDeviceSize size = GetSize(); - const SuballocationVectorType& suballocations1st = AccessSuballocations1st(); - const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); - const size_t suballoc1stCount = suballocations1st.size(); - const size_t suballoc2ndCount = suballocations2nd.size(); - - // FIRST PASS - - size_t unusedRangeCount = 0; - VkDeviceSize usedBytes = 0; - - VkDeviceSize lastOffset = 0; - - size_t alloc2ndCount = 0; - if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) - { - const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset; - size_t nextAlloc2ndIndex = 0; - while (lastOffset < freeSpace2ndTo1stEnd) - { - // Find next non-null allocation or move nextAlloc2ndIndex to the end. - while (nextAlloc2ndIndex < suballoc2ndCount && - suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL) - { - ++nextAlloc2ndIndex; - } - - // Found non-null allocation. - if (nextAlloc2ndIndex < suballoc2ndCount) - { - const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; - - // 1. Process free space before this allocation. - if (lastOffset < suballoc.offset) - { - // There is free space from lastOffset to suballoc.offset. - ++unusedRangeCount; - } - - // 2. Process this allocation. - // There is allocation with suballoc.offset, suballoc.size. - ++alloc2ndCount; - usedBytes += suballoc.size; - - // 3. Prepare for next iteration. - lastOffset = suballoc.offset + suballoc.size; - ++nextAlloc2ndIndex; - } - // We are at the end. - else - { - if (lastOffset < freeSpace2ndTo1stEnd) - { - // There is free space from lastOffset to freeSpace2ndTo1stEnd. - ++unusedRangeCount; - } - - // End of loop. - lastOffset = freeSpace2ndTo1stEnd; - } - } - } - - size_t nextAlloc1stIndex = m_1stNullItemsBeginCount; - size_t alloc1stCount = 0; - const VkDeviceSize freeSpace1stTo2ndEnd = - m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? suballocations2nd.back().offset : size; - while (lastOffset < freeSpace1stTo2ndEnd) - { - // Find next non-null allocation or move nextAllocIndex to the end. - while (nextAlloc1stIndex < suballoc1stCount && - suballocations1st[nextAlloc1stIndex].userData == VMA_NULL) - { - ++nextAlloc1stIndex; - } - - // Found non-null allocation. - if (nextAlloc1stIndex < suballoc1stCount) - { - const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex]; - - // 1. Process free space before this allocation. - if (lastOffset < suballoc.offset) - { - // There is free space from lastOffset to suballoc.offset. - ++unusedRangeCount; - } - - // 2. Process this allocation. - // There is allocation with suballoc.offset, suballoc.size. - ++alloc1stCount; - usedBytes += suballoc.size; - - // 3. Prepare for next iteration. - lastOffset = suballoc.offset + suballoc.size; - ++nextAlloc1stIndex; - } - // We are at the end. - else - { - if (lastOffset < size) - { - // There is free space from lastOffset to freeSpace1stTo2ndEnd. - ++unusedRangeCount; - } - - // End of loop. - lastOffset = freeSpace1stTo2ndEnd; - } - } - - if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) - { - size_t nextAlloc2ndIndex = suballocations2nd.size() - 1; - while (lastOffset < size) - { - // Find next non-null allocation or move nextAlloc2ndIndex to the end. - while (nextAlloc2ndIndex != SIZE_MAX && - suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL) - { - --nextAlloc2ndIndex; - } - - // Found non-null allocation. - if (nextAlloc2ndIndex != SIZE_MAX) - { - const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; - - // 1. Process free space before this allocation. - if (lastOffset < suballoc.offset) - { - // There is free space from lastOffset to suballoc.offset. - ++unusedRangeCount; - } - - // 2. Process this allocation. - // There is allocation with suballoc.offset, suballoc.size. - ++alloc2ndCount; - usedBytes += suballoc.size; - - // 3. Prepare for next iteration. - lastOffset = suballoc.offset + suballoc.size; - --nextAlloc2ndIndex; - } - // We are at the end. - else - { - if (lastOffset < size) - { - // There is free space from lastOffset to size. - ++unusedRangeCount; - } - - // End of loop. - lastOffset = size; - } - } - } - - const VkDeviceSize unusedBytes = size - usedBytes; - PrintDetailedMap_Begin(json, unusedBytes, alloc1stCount + alloc2ndCount, unusedRangeCount); - - // SECOND PASS - lastOffset = 0; - - if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) - { - const VkDeviceSize freeSpace2ndTo1stEnd = suballocations1st[m_1stNullItemsBeginCount].offset; - size_t nextAlloc2ndIndex = 0; - while (lastOffset < freeSpace2ndTo1stEnd) - { - // Find next non-null allocation or move nextAlloc2ndIndex to the end. - while (nextAlloc2ndIndex < suballoc2ndCount && - suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL) - { - ++nextAlloc2ndIndex; - } - - // Found non-null allocation. - if (nextAlloc2ndIndex < suballoc2ndCount) - { - const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; - - // 1. Process free space before this allocation. - if (lastOffset < suballoc.offset) - { - // There is free space from lastOffset to suballoc.offset. - const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; - PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize); - } - - // 2. Process this allocation. - // There is allocation with suballoc.offset, suballoc.size. - PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.size, suballoc.userData); - - // 3. Prepare for next iteration. - lastOffset = suballoc.offset + suballoc.size; - ++nextAlloc2ndIndex; - } - // We are at the end. - else - { - if (lastOffset < freeSpace2ndTo1stEnd) - { - // There is free space from lastOffset to freeSpace2ndTo1stEnd. - const VkDeviceSize unusedRangeSize = freeSpace2ndTo1stEnd - lastOffset; - PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize); - } - - // End of loop. - lastOffset = freeSpace2ndTo1stEnd; - } - } - } - - nextAlloc1stIndex = m_1stNullItemsBeginCount; - while (lastOffset < freeSpace1stTo2ndEnd) - { - // Find next non-null allocation or move nextAllocIndex to the end. - while (nextAlloc1stIndex < suballoc1stCount && - suballocations1st[nextAlloc1stIndex].userData == VMA_NULL) - { - ++nextAlloc1stIndex; - } - - // Found non-null allocation. - if (nextAlloc1stIndex < suballoc1stCount) - { - const VmaSuballocation& suballoc = suballocations1st[nextAlloc1stIndex]; - - // 1. Process free space before this allocation. - if (lastOffset < suballoc.offset) - { - // There is free space from lastOffset to suballoc.offset. - const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; - PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize); - } - - // 2. Process this allocation. - // There is allocation with suballoc.offset, suballoc.size. - PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.size, suballoc.userData); - - // 3. Prepare for next iteration. - lastOffset = suballoc.offset + suballoc.size; - ++nextAlloc1stIndex; - } - // We are at the end. - else - { - if (lastOffset < freeSpace1stTo2ndEnd) - { - // There is free space from lastOffset to freeSpace1stTo2ndEnd. - const VkDeviceSize unusedRangeSize = freeSpace1stTo2ndEnd - lastOffset; - PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize); - } - - // End of loop. - lastOffset = freeSpace1stTo2ndEnd; - } - } - - if (m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) - { - size_t nextAlloc2ndIndex = suballocations2nd.size() - 1; - while (lastOffset < size) - { - // Find next non-null allocation or move nextAlloc2ndIndex to the end. - while (nextAlloc2ndIndex != SIZE_MAX && - suballocations2nd[nextAlloc2ndIndex].userData == VMA_NULL) - { - --nextAlloc2ndIndex; - } - - // Found non-null allocation. - if (nextAlloc2ndIndex != SIZE_MAX) - { - const VmaSuballocation& suballoc = suballocations2nd[nextAlloc2ndIndex]; - - // 1. Process free space before this allocation. - if (lastOffset < suballoc.offset) - { - // There is free space from lastOffset to suballoc.offset. - const VkDeviceSize unusedRangeSize = suballoc.offset - lastOffset; - PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize); - } - - // 2. Process this allocation. - // There is allocation with suballoc.offset, suballoc.size. - PrintDetailedMap_Allocation(json, suballoc.offset, suballoc.size, suballoc.userData); - - // 3. Prepare for next iteration. - lastOffset = suballoc.offset + suballoc.size; - --nextAlloc2ndIndex; - } - // We are at the end. - else - { - if (lastOffset < size) - { - // There is free space from lastOffset to size. - const VkDeviceSize unusedRangeSize = size - lastOffset; - PrintDetailedMap_UnusedRange(json, lastOffset, unusedRangeSize); - } - - // End of loop. - lastOffset = size; - } - } - } - - PrintDetailedMap_End(json); -} -#endif // VMA_STATS_STRING_ENABLED - -bool VmaBlockMetadata_Linear::CreateAllocationRequest( - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - bool upperAddress, - VmaSuballocationType allocType, - uint32_t strategy, - VmaAllocationRequest* pAllocationRequest) -{ - VMA_ASSERT(allocSize > 0); - VMA_ASSERT(allocType != VMA_SUBALLOCATION_TYPE_FREE); - VMA_ASSERT(pAllocationRequest != VMA_NULL); - VMA_HEAVY_ASSERT(Validate()); - pAllocationRequest->size = allocSize; - return upperAddress ? - CreateAllocationRequest_UpperAddress( - allocSize, allocAlignment, allocType, strategy, pAllocationRequest) : - CreateAllocationRequest_LowerAddress( - allocSize, allocAlignment, allocType, strategy, pAllocationRequest); -} - -VkResult VmaBlockMetadata_Linear::CheckCorruption(const void* pBlockData) -{ - VMA_ASSERT(!IsVirtual()); - SuballocationVectorType& suballocations1st = AccessSuballocations1st(); - for (size_t i = m_1stNullItemsBeginCount, count = suballocations1st.size(); i < count; ++i) - { - const VmaSuballocation& suballoc = suballocations1st[i]; - if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE) - { - if (!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size)) - { - VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!"); - return VK_ERROR_UNKNOWN_COPY; - } - } - } - - SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); - for (size_t i = 0, count = suballocations2nd.size(); i < count; ++i) - { - const VmaSuballocation& suballoc = suballocations2nd[i]; - if (suballoc.type != VMA_SUBALLOCATION_TYPE_FREE) - { - if (!VmaValidateMagicValue(pBlockData, suballoc.offset + suballoc.size)) - { - VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!"); - return VK_ERROR_UNKNOWN_COPY; - } - } - } - - return VK_SUCCESS; -} - -void VmaBlockMetadata_Linear::Alloc( - const VmaAllocationRequest& request, - VmaSuballocationType type, - void* userData) -{ - const VkDeviceSize offset = (VkDeviceSize)request.allocHandle - 1; - const VmaSuballocation newSuballoc = { offset, request.size, userData, type }; - - switch (request.type) - { - case VmaAllocationRequestType::UpperAddress: - { - VMA_ASSERT(m_2ndVectorMode != SECOND_VECTOR_RING_BUFFER && - "CRITICAL ERROR: Trying to use linear allocator as double stack while it was already used as ring buffer."); - SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); - suballocations2nd.push_back(newSuballoc); - m_2ndVectorMode = SECOND_VECTOR_DOUBLE_STACK; - } - break; - case VmaAllocationRequestType::EndOf1st: - { - SuballocationVectorType& suballocations1st = AccessSuballocations1st(); - - VMA_ASSERT(suballocations1st.empty() || - offset >= suballocations1st.back().offset + suballocations1st.back().size); - // Check if it fits before the end of the block. - VMA_ASSERT(offset + request.size <= GetSize()); - - suballocations1st.push_back(newSuballoc); - } - break; - case VmaAllocationRequestType::EndOf2nd: - { - SuballocationVectorType& suballocations1st = AccessSuballocations1st(); - // New allocation at the end of 2-part ring buffer, so before first allocation from 1st vector. - VMA_ASSERT(!suballocations1st.empty() && - offset + request.size <= suballocations1st[m_1stNullItemsBeginCount].offset); - SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); - - switch (m_2ndVectorMode) - { - case SECOND_VECTOR_EMPTY: - // First allocation from second part ring buffer. - VMA_ASSERT(suballocations2nd.empty()); - m_2ndVectorMode = SECOND_VECTOR_RING_BUFFER; - break; - case SECOND_VECTOR_RING_BUFFER: - // 2-part ring buffer is already started. - VMA_ASSERT(!suballocations2nd.empty()); - break; - case SECOND_VECTOR_DOUBLE_STACK: - VMA_ASSERT(0 && "CRITICAL ERROR: Trying to use linear allocator as ring buffer while it was already used as double stack."); - break; - default: - VMA_ASSERT(0); - } - - suballocations2nd.push_back(newSuballoc); - } - break; - default: - VMA_ASSERT(0 && "CRITICAL INTERNAL ERROR."); - } - - m_SumFreeSize -= newSuballoc.size; -} - -void VmaBlockMetadata_Linear::Free(VmaAllocHandle allocHandle) -{ - SuballocationVectorType& suballocations1st = AccessSuballocations1st(); - SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); - VkDeviceSize offset = (VkDeviceSize)allocHandle - 1; - - if (!suballocations1st.empty()) - { - // First allocation: Mark it as next empty at the beginning. - VmaSuballocation& firstSuballoc = suballocations1st[m_1stNullItemsBeginCount]; - if (firstSuballoc.offset == offset) - { - firstSuballoc.type = VMA_SUBALLOCATION_TYPE_FREE; - firstSuballoc.userData = VMA_NULL; - m_SumFreeSize += firstSuballoc.size; - ++m_1stNullItemsBeginCount; - CleanupAfterFree(); - return; - } - } - - // Last allocation in 2-part ring buffer or top of upper stack (same logic). - if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER || - m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) - { - VmaSuballocation& lastSuballoc = suballocations2nd.back(); - if (lastSuballoc.offset == offset) - { - m_SumFreeSize += lastSuballoc.size; - suballocations2nd.pop_back(); - CleanupAfterFree(); - return; - } - } - // Last allocation in 1st vector. - else if (m_2ndVectorMode == SECOND_VECTOR_EMPTY) - { - VmaSuballocation& lastSuballoc = suballocations1st.back(); - if (lastSuballoc.offset == offset) - { - m_SumFreeSize += lastSuballoc.size; - suballocations1st.pop_back(); - CleanupAfterFree(); - return; - } - } - - VmaSuballocation refSuballoc; - refSuballoc.offset = offset; - // Rest of members stays uninitialized intentionally for better performance. - - // Item from the middle of 1st vector. - { - const SuballocationVectorType::iterator it = VmaBinaryFindSorted( - suballocations1st.begin() + m_1stNullItemsBeginCount, - suballocations1st.end(), - refSuballoc, - VmaSuballocationOffsetLess()); - if (it != suballocations1st.end()) - { - it->type = VMA_SUBALLOCATION_TYPE_FREE; - it->userData = VMA_NULL; - ++m_1stNullItemsMiddleCount; - m_SumFreeSize += it->size; - CleanupAfterFree(); - return; - } - } - - if (m_2ndVectorMode != SECOND_VECTOR_EMPTY) - { - // Item from the middle of 2nd vector. - const SuballocationVectorType::iterator it = m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER ? - VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetLess()) : - VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetGreater()); - if (it != suballocations2nd.end()) - { - it->type = VMA_SUBALLOCATION_TYPE_FREE; - it->userData = VMA_NULL; - ++m_2ndNullItemsCount; - m_SumFreeSize += it->size; - CleanupAfterFree(); - return; - } - } - - VMA_ASSERT(0 && "Allocation to free not found in linear allocator!"); -} - -void VmaBlockMetadata_Linear::GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) -{ - outInfo.offset = (VkDeviceSize)allocHandle - 1; - VmaSuballocation& suballoc = FindSuballocation(outInfo.offset); - outInfo.size = suballoc.size; - outInfo.pUserData = suballoc.userData; -} - -void* VmaBlockMetadata_Linear::GetAllocationUserData(VmaAllocHandle allocHandle) const -{ - return FindSuballocation((VkDeviceSize)allocHandle - 1).userData; -} - -VmaAllocHandle VmaBlockMetadata_Linear::GetAllocationListBegin() const -{ - // Function only used for defragmentation, which is disabled for this algorithm - VMA_ASSERT(0); - return VK_NULL_HANDLE; -} - -VmaAllocHandle VmaBlockMetadata_Linear::GetNextAllocation(VmaAllocHandle prevAlloc) const -{ - // Function only used for defragmentation, which is disabled for this algorithm - VMA_ASSERT(0); - return VK_NULL_HANDLE; -} - -VkDeviceSize VmaBlockMetadata_Linear::GetNextFreeRegionSize(VmaAllocHandle alloc) const -{ - // Function only used for defragmentation, which is disabled for this algorithm - VMA_ASSERT(0); - return 0; -} - -void VmaBlockMetadata_Linear::Clear() -{ - m_SumFreeSize = GetSize(); - m_Suballocations0.clear(); - m_Suballocations1.clear(); - // Leaving m_1stVectorIndex unchanged - it doesn't matter. - m_2ndVectorMode = SECOND_VECTOR_EMPTY; - m_1stNullItemsBeginCount = 0; - m_1stNullItemsMiddleCount = 0; - m_2ndNullItemsCount = 0; -} - -void VmaBlockMetadata_Linear::SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) -{ - VmaSuballocation& suballoc = FindSuballocation((VkDeviceSize)allocHandle - 1); - suballoc.userData = userData; -} - -void VmaBlockMetadata_Linear::DebugLogAllAllocations() const -{ - const SuballocationVectorType& suballocations1st = AccessSuballocations1st(); - for (auto it = suballocations1st.begin() + m_1stNullItemsBeginCount; it != suballocations1st.end(); ++it) - if (it->type != VMA_SUBALLOCATION_TYPE_FREE) - DebugLogAllocation(it->offset, it->size, it->userData); - - const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); - for (auto it = suballocations2nd.begin(); it != suballocations2nd.end(); ++it) - if (it->type != VMA_SUBALLOCATION_TYPE_FREE) - DebugLogAllocation(it->offset, it->size, it->userData); -} - -VmaSuballocation& VmaBlockMetadata_Linear::FindSuballocation(VkDeviceSize offset) const -{ - const SuballocationVectorType& suballocations1st = AccessSuballocations1st(); - const SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); - - VmaSuballocation refSuballoc; - refSuballoc.offset = offset; - // Rest of members stays uninitialized intentionally for better performance. - - // Item from the 1st vector. - { - SuballocationVectorType::const_iterator it = VmaBinaryFindSorted( - suballocations1st.begin() + m_1stNullItemsBeginCount, - suballocations1st.end(), - refSuballoc, - VmaSuballocationOffsetLess()); - if (it != suballocations1st.end()) - { - return const_cast(*it); - } - } - - if (m_2ndVectorMode != SECOND_VECTOR_EMPTY) - { - // Rest of members stays uninitialized intentionally for better performance. - SuballocationVectorType::const_iterator it = m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER ? - VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetLess()) : - VmaBinaryFindSorted(suballocations2nd.begin(), suballocations2nd.end(), refSuballoc, VmaSuballocationOffsetGreater()); - if (it != suballocations2nd.end()) - { - return const_cast(*it); - } - } - - VMA_ASSERT(0 && "Allocation not found in linear allocator!"); - return const_cast(suballocations1st.back()); // Should never occur. -} - -bool VmaBlockMetadata_Linear::ShouldCompact1st() const -{ - const size_t nullItemCount = m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount; - const size_t suballocCount = AccessSuballocations1st().size(); - return suballocCount > 32 && nullItemCount * 2 >= (suballocCount - nullItemCount) * 3; -} - -void VmaBlockMetadata_Linear::CleanupAfterFree() -{ - SuballocationVectorType& suballocations1st = AccessSuballocations1st(); - SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); - - if (IsEmpty()) - { - suballocations1st.clear(); - suballocations2nd.clear(); - m_1stNullItemsBeginCount = 0; - m_1stNullItemsMiddleCount = 0; - m_2ndNullItemsCount = 0; - m_2ndVectorMode = SECOND_VECTOR_EMPTY; - } - else - { - const size_t suballoc1stCount = suballocations1st.size(); - const size_t nullItem1stCount = m_1stNullItemsBeginCount + m_1stNullItemsMiddleCount; - VMA_ASSERT(nullItem1stCount <= suballoc1stCount); - - // Find more null items at the beginning of 1st vector. - while (m_1stNullItemsBeginCount < suballoc1stCount && - suballocations1st[m_1stNullItemsBeginCount].type == VMA_SUBALLOCATION_TYPE_FREE) - { - ++m_1stNullItemsBeginCount; - --m_1stNullItemsMiddleCount; - } - - // Find more null items at the end of 1st vector. - while (m_1stNullItemsMiddleCount > 0 && - suballocations1st.back().type == VMA_SUBALLOCATION_TYPE_FREE) - { - --m_1stNullItemsMiddleCount; - suballocations1st.pop_back(); - } - - // Find more null items at the end of 2nd vector. - while (m_2ndNullItemsCount > 0 && - suballocations2nd.back().type == VMA_SUBALLOCATION_TYPE_FREE) - { - --m_2ndNullItemsCount; - suballocations2nd.pop_back(); - } - - // Find more null items at the beginning of 2nd vector. - while (m_2ndNullItemsCount > 0 && - suballocations2nd[0].type == VMA_SUBALLOCATION_TYPE_FREE) - { - --m_2ndNullItemsCount; - VmaVectorRemove(suballocations2nd, 0); - } - - if (ShouldCompact1st()) - { - const size_t nonNullItemCount = suballoc1stCount - nullItem1stCount; - size_t srcIndex = m_1stNullItemsBeginCount; - for (size_t dstIndex = 0; dstIndex < nonNullItemCount; ++dstIndex) - { - while (suballocations1st[srcIndex].type == VMA_SUBALLOCATION_TYPE_FREE) - { - ++srcIndex; - } - if (dstIndex != srcIndex) - { - suballocations1st[dstIndex] = suballocations1st[srcIndex]; - } - ++srcIndex; - } - suballocations1st.resize(nonNullItemCount); - m_1stNullItemsBeginCount = 0; - m_1stNullItemsMiddleCount = 0; - } - - // 2nd vector became empty. - if (suballocations2nd.empty()) - { - m_2ndVectorMode = SECOND_VECTOR_EMPTY; - } - - // 1st vector became empty. - if (suballocations1st.size() - m_1stNullItemsBeginCount == 0) - { - suballocations1st.clear(); - m_1stNullItemsBeginCount = 0; - - if (!suballocations2nd.empty() && m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) - { - // Swap 1st with 2nd. Now 2nd is empty. - m_2ndVectorMode = SECOND_VECTOR_EMPTY; - m_1stNullItemsMiddleCount = m_2ndNullItemsCount; - while (m_1stNullItemsBeginCount < suballocations2nd.size() && - suballocations2nd[m_1stNullItemsBeginCount].type == VMA_SUBALLOCATION_TYPE_FREE) - { - ++m_1stNullItemsBeginCount; - --m_1stNullItemsMiddleCount; - } - m_2ndNullItemsCount = 0; - m_1stVectorIndex ^= 1; - } - } - } - - VMA_HEAVY_ASSERT(Validate()); -} - -bool VmaBlockMetadata_Linear::CreateAllocationRequest_LowerAddress( - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - VmaSuballocationType allocType, - uint32_t strategy, - VmaAllocationRequest* pAllocationRequest) -{ - const VkDeviceSize blockSize = GetSize(); - const VkDeviceSize debugMargin = GetDebugMargin(); - const VkDeviceSize bufferImageGranularity = GetBufferImageGranularity(); - SuballocationVectorType& suballocations1st = AccessSuballocations1st(); - SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); - - if (m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) - { - // Try to allocate at the end of 1st vector. - - VkDeviceSize resultBaseOffset = 0; - if (!suballocations1st.empty()) - { - const VmaSuballocation& lastSuballoc = suballocations1st.back(); - resultBaseOffset = lastSuballoc.offset + lastSuballoc.size + debugMargin; - } - - // Start from offset equal to beginning of free space. - VkDeviceSize resultOffset = resultBaseOffset; - - // Apply alignment. - resultOffset = VmaAlignUp(resultOffset, allocAlignment); - - // Check previous suballocations for BufferImageGranularity conflicts. - // Make bigger alignment if necessary. - if (bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment && !suballocations1st.empty()) - { - bool bufferImageGranularityConflict = false; - for (size_t prevSuballocIndex = suballocations1st.size(); prevSuballocIndex--; ) - { - const VmaSuballocation& prevSuballoc = suballocations1st[prevSuballocIndex]; - if (VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity)) - { - if (VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType)) - { - bufferImageGranularityConflict = true; - break; - } - } - else - // Already on previous page. - break; - } - if (bufferImageGranularityConflict) - { - resultOffset = VmaAlignUp(resultOffset, bufferImageGranularity); - } - } - - const VkDeviceSize freeSpaceEnd = m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK ? - suballocations2nd.back().offset : blockSize; - - // There is enough free space at the end after alignment. - if (resultOffset + allocSize + debugMargin <= freeSpaceEnd) - { - // Check next suballocations for BufferImageGranularity conflicts. - // If conflict exists, allocation cannot be made here. - if ((allocSize % bufferImageGranularity || resultOffset % bufferImageGranularity) && m_2ndVectorMode == SECOND_VECTOR_DOUBLE_STACK) - { - for (size_t nextSuballocIndex = suballocations2nd.size(); nextSuballocIndex--; ) - { - const VmaSuballocation& nextSuballoc = suballocations2nd[nextSuballocIndex]; - if (VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity)) - { - if (VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type)) - { - return false; - } - } - else - { - // Already on previous page. - break; - } - } - } - - // All tests passed: Success. - pAllocationRequest->allocHandle = (VmaAllocHandle)(resultOffset + 1); - // pAllocationRequest->item, customData unused. - pAllocationRequest->type = VmaAllocationRequestType::EndOf1st; - return true; - } - } - - // Wrap-around to end of 2nd vector. Try to allocate there, watching for the - // beginning of 1st vector as the end of free space. - if (m_2ndVectorMode == SECOND_VECTOR_EMPTY || m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) - { - VMA_ASSERT(!suballocations1st.empty()); - - VkDeviceSize resultBaseOffset = 0; - if (!suballocations2nd.empty()) - { - const VmaSuballocation& lastSuballoc = suballocations2nd.back(); - resultBaseOffset = lastSuballoc.offset + lastSuballoc.size + debugMargin; - } - - // Start from offset equal to beginning of free space. - VkDeviceSize resultOffset = resultBaseOffset; - - // Apply alignment. - resultOffset = VmaAlignUp(resultOffset, allocAlignment); - - // Check previous suballocations for BufferImageGranularity conflicts. - // Make bigger alignment if necessary. - if (bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment && !suballocations2nd.empty()) - { - bool bufferImageGranularityConflict = false; - for (size_t prevSuballocIndex = suballocations2nd.size(); prevSuballocIndex--; ) - { - const VmaSuballocation& prevSuballoc = suballocations2nd[prevSuballocIndex]; - if (VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity)) - { - if (VmaIsBufferImageGranularityConflict(prevSuballoc.type, allocType)) - { - bufferImageGranularityConflict = true; - break; - } - } - else - // Already on previous page. - break; - } - if (bufferImageGranularityConflict) - { - resultOffset = VmaAlignUp(resultOffset, bufferImageGranularity); - } - } - - size_t index1st = m_1stNullItemsBeginCount; - - // There is enough free space at the end after alignment. - if ((index1st == suballocations1st.size() && resultOffset + allocSize + debugMargin <= blockSize) || - (index1st < suballocations1st.size() && resultOffset + allocSize + debugMargin <= suballocations1st[index1st].offset)) - { - // Check next suballocations for BufferImageGranularity conflicts. - // If conflict exists, allocation cannot be made here. - if (allocSize % bufferImageGranularity || resultOffset % bufferImageGranularity) - { - for (size_t nextSuballocIndex = index1st; - nextSuballocIndex < suballocations1st.size(); - nextSuballocIndex++) - { - const VmaSuballocation& nextSuballoc = suballocations1st[nextSuballocIndex]; - if (VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity)) - { - if (VmaIsBufferImageGranularityConflict(allocType, nextSuballoc.type)) - { - return false; - } - } - else - { - // Already on next page. - break; - } - } - } - - // All tests passed: Success. - pAllocationRequest->allocHandle = (VmaAllocHandle)(resultOffset + 1); - pAllocationRequest->type = VmaAllocationRequestType::EndOf2nd; - // pAllocationRequest->item, customData unused. - return true; - } - } - - return false; -} - -bool VmaBlockMetadata_Linear::CreateAllocationRequest_UpperAddress( - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - VmaSuballocationType allocType, - uint32_t strategy, - VmaAllocationRequest* pAllocationRequest) -{ - const VkDeviceSize blockSize = GetSize(); - const VkDeviceSize bufferImageGranularity = GetBufferImageGranularity(); - SuballocationVectorType& suballocations1st = AccessSuballocations1st(); - SuballocationVectorType& suballocations2nd = AccessSuballocations2nd(); - - if (m_2ndVectorMode == SECOND_VECTOR_RING_BUFFER) - { - VMA_ASSERT(0 && "Trying to use pool with linear algorithm as double stack, while it is already being used as ring buffer."); - return false; - } - - // Try to allocate before 2nd.back(), or end of block if 2nd.empty(). - if (allocSize > blockSize) - { - return false; - } - VkDeviceSize resultBaseOffset = blockSize - allocSize; - if (!suballocations2nd.empty()) - { - const VmaSuballocation& lastSuballoc = suballocations2nd.back(); - resultBaseOffset = lastSuballoc.offset - allocSize; - if (allocSize > lastSuballoc.offset) - { - return false; - } - } - - // Start from offset equal to end of free space. - VkDeviceSize resultOffset = resultBaseOffset; - - const VkDeviceSize debugMargin = GetDebugMargin(); - - // Apply debugMargin at the end. - if (debugMargin > 0) - { - if (resultOffset < debugMargin) - { - return false; - } - resultOffset -= debugMargin; - } - - // Apply alignment. - resultOffset = VmaAlignDown(resultOffset, allocAlignment); - - // Check next suballocations from 2nd for BufferImageGranularity conflicts. - // Make bigger alignment if necessary. - if (bufferImageGranularity > 1 && bufferImageGranularity != allocAlignment && !suballocations2nd.empty()) - { - bool bufferImageGranularityConflict = false; - for (size_t nextSuballocIndex = suballocations2nd.size(); nextSuballocIndex--; ) - { - const VmaSuballocation& nextSuballoc = suballocations2nd[nextSuballocIndex]; - if (VmaBlocksOnSamePage(resultOffset, allocSize, nextSuballoc.offset, bufferImageGranularity)) - { - if (VmaIsBufferImageGranularityConflict(nextSuballoc.type, allocType)) - { - bufferImageGranularityConflict = true; - break; - } - } - else - // Already on previous page. - break; - } - if (bufferImageGranularityConflict) - { - resultOffset = VmaAlignDown(resultOffset, bufferImageGranularity); - } - } - - // There is enough free space. - const VkDeviceSize endOf1st = !suballocations1st.empty() ? - suballocations1st.back().offset + suballocations1st.back().size : - 0; - if (endOf1st + debugMargin <= resultOffset) - { - // Check previous suballocations for BufferImageGranularity conflicts. - // If conflict exists, allocation cannot be made here. - if (bufferImageGranularity > 1) - { - for (size_t prevSuballocIndex = suballocations1st.size(); prevSuballocIndex--; ) - { - const VmaSuballocation& prevSuballoc = suballocations1st[prevSuballocIndex]; - if (VmaBlocksOnSamePage(prevSuballoc.offset, prevSuballoc.size, resultOffset, bufferImageGranularity)) - { - if (VmaIsBufferImageGranularityConflict(allocType, prevSuballoc.type)) - { - return false; - } - } - else - { - // Already on next page. - break; - } - } - } - - // All tests passed: Success. - pAllocationRequest->allocHandle = (VmaAllocHandle)(resultOffset + 1); - // pAllocationRequest->item unused. - pAllocationRequest->type = VmaAllocationRequestType::UpperAddress; - return true; - } - - return false; -} -#endif // _VMA_BLOCK_METADATA_LINEAR_FUNCTIONS -#endif // _VMA_BLOCK_METADATA_LINEAR - -#if 0 -#ifndef _VMA_BLOCK_METADATA_BUDDY -/* -- GetSize() is the original size of allocated memory block. -- m_UsableSize is this size aligned down to a power of two. - All allocations and calculations happen relative to m_UsableSize. -- GetUnusableSize() is the difference between them. - It is reported as separate, unused range, not available for allocations. - -Node at level 0 has size = m_UsableSize. -Each next level contains nodes with size 2 times smaller than current level. -m_LevelCount is the maximum number of levels to use in the current object. -*/ -class VmaBlockMetadata_Buddy : public VmaBlockMetadata -{ - VMA_CLASS_NO_COPY(VmaBlockMetadata_Buddy) -public: - VmaBlockMetadata_Buddy(const VkAllocationCallbacks* pAllocationCallbacks, - VkDeviceSize bufferImageGranularity, bool isVirtual); - virtual ~VmaBlockMetadata_Buddy(); - - size_t GetAllocationCount() const override { return m_AllocationCount; } - VkDeviceSize GetSumFreeSize() const override { return m_SumFreeSize + GetUnusableSize(); } - bool IsEmpty() const override { return m_Root->type == Node::TYPE_FREE; } - VkResult CheckCorruption(const void* pBlockData) override { return VK_ERROR_FEATURE_NOT_PRESENT; } - VkDeviceSize GetAllocationOffset(VmaAllocHandle allocHandle) const override { return (VkDeviceSize)allocHandle - 1; }; - void DebugLogAllAllocations() const override { DebugLogAllAllocationNode(m_Root, 0); } - - void Init(VkDeviceSize size) override; - bool Validate() const override; - - void AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const override; - void AddStatistics(VmaStatistics& inoutStats) const override; - -#if VMA_STATS_STRING_ENABLED - void PrintDetailedMap(class VmaJsonWriter& json, uint32_t mapRefCount) const override; -#endif - - bool CreateAllocationRequest( - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - bool upperAddress, - VmaSuballocationType allocType, - uint32_t strategy, - VmaAllocationRequest* pAllocationRequest) override; - - void Alloc( - const VmaAllocationRequest& request, - VmaSuballocationType type, - void* userData) override; - - void Free(VmaAllocHandle allocHandle) override; - void GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) override; - void* GetAllocationUserData(VmaAllocHandle allocHandle) const override; - VmaAllocHandle GetAllocationListBegin() const override; - VmaAllocHandle GetNextAllocation(VmaAllocHandle prevAlloc) const override; - void Clear() override; - void SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) override; - -private: - static const size_t MAX_LEVELS = 48; - - struct ValidationContext - { - size_t calculatedAllocationCount = 0; - size_t calculatedFreeCount = 0; - VkDeviceSize calculatedSumFreeSize = 0; - }; - struct Node - { - VkDeviceSize offset; - enum TYPE - { - TYPE_FREE, - TYPE_ALLOCATION, - TYPE_SPLIT, - TYPE_COUNT - } type; - Node* parent; - Node* buddy; - - union - { - struct - { - Node* prev; - Node* next; - } free; - struct - { - void* userData; - } allocation; - struct - { - Node* leftChild; - } split; - }; - }; - - // Size of the memory block aligned down to a power of two. - VkDeviceSize m_UsableSize; - uint32_t m_LevelCount; - VmaPoolAllocator m_NodeAllocator; - Node* m_Root; - struct - { - Node* front; - Node* back; - } m_FreeList[MAX_LEVELS]; - - // Number of nodes in the tree with type == TYPE_ALLOCATION. - size_t m_AllocationCount; - // Number of nodes in the tree with type == TYPE_FREE. - size_t m_FreeCount; - // Doesn't include space wasted due to internal fragmentation - allocation sizes are just aligned up to node sizes. - // Doesn't include unusable size. - VkDeviceSize m_SumFreeSize; - - VkDeviceSize GetUnusableSize() const { return GetSize() - m_UsableSize; } - VkDeviceSize LevelToNodeSize(uint32_t level) const { return m_UsableSize >> level; } - - VkDeviceSize AlignAllocationSize(VkDeviceSize size) const - { - if (!IsVirtual()) - { - size = VmaAlignUp(size, (VkDeviceSize)16); - } - return VmaNextPow2(size); - } - Node* FindAllocationNode(VkDeviceSize offset, uint32_t& outLevel) const; - void DeleteNodeChildren(Node* node); - bool ValidateNode(ValidationContext& ctx, const Node* parent, const Node* curr, uint32_t level, VkDeviceSize levelNodeSize) const; - uint32_t AllocSizeToLevel(VkDeviceSize allocSize) const; - void AddNodeToDetailedStatistics(VmaDetailedStatistics& inoutStats, const Node* node, VkDeviceSize levelNodeSize) const; - // Adds node to the front of FreeList at given level. - // node->type must be FREE. - // node->free.prev, next can be undefined. - void AddToFreeListFront(uint32_t level, Node* node); - // Removes node from FreeList at given level. - // node->type must be FREE. - // node->free.prev, next stay untouched. - void RemoveFromFreeList(uint32_t level, Node* node); - void DebugLogAllAllocationNode(Node* node, uint32_t level) const; - -#if VMA_STATS_STRING_ENABLED - void PrintDetailedMapNode(class VmaJsonWriter& json, const Node* node, VkDeviceSize levelNodeSize) const; -#endif -}; - -#ifndef _VMA_BLOCK_METADATA_BUDDY_FUNCTIONS -VmaBlockMetadata_Buddy::VmaBlockMetadata_Buddy(const VkAllocationCallbacks* pAllocationCallbacks, - VkDeviceSize bufferImageGranularity, bool isVirtual) - : VmaBlockMetadata(pAllocationCallbacks, bufferImageGranularity, isVirtual), - m_NodeAllocator(pAllocationCallbacks, 32), // firstBlockCapacity - m_Root(VMA_NULL), - m_AllocationCount(0), - m_FreeCount(1), - m_SumFreeSize(0) -{ - memset(m_FreeList, 0, sizeof(m_FreeList)); -} - -VmaBlockMetadata_Buddy::~VmaBlockMetadata_Buddy() -{ - DeleteNodeChildren(m_Root); - m_NodeAllocator.Free(m_Root); -} - -void VmaBlockMetadata_Buddy::Init(VkDeviceSize size) -{ - VmaBlockMetadata::Init(size); - - m_UsableSize = VmaPrevPow2(size); - m_SumFreeSize = m_UsableSize; - - // Calculate m_LevelCount. - const VkDeviceSize minNodeSize = IsVirtual() ? 1 : 16; - m_LevelCount = 1; - while (m_LevelCount < MAX_LEVELS && - LevelToNodeSize(m_LevelCount) >= minNodeSize) - { - ++m_LevelCount; - } - - Node* rootNode = m_NodeAllocator.Alloc(); - rootNode->offset = 0; - rootNode->type = Node::TYPE_FREE; - rootNode->parent = VMA_NULL; - rootNode->buddy = VMA_NULL; - - m_Root = rootNode; - AddToFreeListFront(0, rootNode); -} - -bool VmaBlockMetadata_Buddy::Validate() const -{ - // Validate tree. - ValidationContext ctx; - if (!ValidateNode(ctx, VMA_NULL, m_Root, 0, LevelToNodeSize(0))) - { - VMA_VALIDATE(false && "ValidateNode failed."); - } - VMA_VALIDATE(m_AllocationCount == ctx.calculatedAllocationCount); - VMA_VALIDATE(m_SumFreeSize == ctx.calculatedSumFreeSize); - - // Validate free node lists. - for (uint32_t level = 0; level < m_LevelCount; ++level) - { - VMA_VALIDATE(m_FreeList[level].front == VMA_NULL || - m_FreeList[level].front->free.prev == VMA_NULL); - - for (Node* node = m_FreeList[level].front; - node != VMA_NULL; - node = node->free.next) - { - VMA_VALIDATE(node->type == Node::TYPE_FREE); - - if (node->free.next == VMA_NULL) - { - VMA_VALIDATE(m_FreeList[level].back == node); - } - else - { - VMA_VALIDATE(node->free.next->free.prev == node); - } - } - } - - // Validate that free lists ar higher levels are empty. - for (uint32_t level = m_LevelCount; level < MAX_LEVELS; ++level) - { - VMA_VALIDATE(m_FreeList[level].front == VMA_NULL && m_FreeList[level].back == VMA_NULL); - } - - return true; -} - -void VmaBlockMetadata_Buddy::AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const -{ - inoutStats.statistics.blockCount++; - inoutStats.statistics.blockBytes += GetSize(); - - AddNodeToDetailedStatistics(inoutStats, m_Root, LevelToNodeSize(0)); - - const VkDeviceSize unusableSize = GetUnusableSize(); - if (unusableSize > 0) - VmaAddDetailedStatisticsUnusedRange(inoutStats, unusableSize); -} - -void VmaBlockMetadata_Buddy::AddStatistics(VmaStatistics& inoutStats) const -{ - inoutStats.blockCount++; - inoutStats.allocationCount += (uint32_t)m_AllocationCount; - inoutStats.blockBytes += GetSize(); - inoutStats.allocationBytes += GetSize() - m_SumFreeSize; -} - -#if VMA_STATS_STRING_ENABLED -void VmaBlockMetadata_Buddy::PrintDetailedMap(class VmaJsonWriter& json, uint32_t mapRefCount) const -{ - VmaDetailedStatistics stats; - VmaClearDetailedStatistics(stats); - AddDetailedStatistics(stats); - - PrintDetailedMap_Begin( - json, - stats.statistics.blockBytes - stats.statistics.allocationBytes, - stats.statistics.allocationCount, - stats.unusedRangeCount, - mapRefCount); - - PrintDetailedMapNode(json, m_Root, LevelToNodeSize(0)); - - const VkDeviceSize unusableSize = GetUnusableSize(); - if (unusableSize > 0) - { - PrintDetailedMap_UnusedRange(json, - m_UsableSize, // offset - unusableSize); // size - } - - PrintDetailedMap_End(json); -} -#endif // VMA_STATS_STRING_ENABLED - -bool VmaBlockMetadata_Buddy::CreateAllocationRequest( - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - bool upperAddress, - VmaSuballocationType allocType, - uint32_t strategy, - VmaAllocationRequest* pAllocationRequest) -{ - VMA_ASSERT(!upperAddress && "VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT can be used only with linear algorithm."); - - allocSize = AlignAllocationSize(allocSize); - - // Simple way to respect bufferImageGranularity. May be optimized some day. - // Whenever it might be an OPTIMAL image... - if (allocType == VMA_SUBALLOCATION_TYPE_UNKNOWN || - allocType == VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN || - allocType == VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL) - { - allocAlignment = VMA_MAX(allocAlignment, GetBufferImageGranularity()); - allocSize = VmaAlignUp(allocSize, GetBufferImageGranularity()); - } - - if (allocSize > m_UsableSize) - { - return false; - } - - const uint32_t targetLevel = AllocSizeToLevel(allocSize); - for (uint32_t level = targetLevel; level--; ) - { - for (Node* freeNode = m_FreeList[level].front; - freeNode != VMA_NULL; - freeNode = freeNode->free.next) - { - if (freeNode->offset % allocAlignment == 0) - { - pAllocationRequest->type = VmaAllocationRequestType::Normal; - pAllocationRequest->allocHandle = (VmaAllocHandle)(freeNode->offset + 1); - pAllocationRequest->size = allocSize; - pAllocationRequest->customData = (void*)(uintptr_t)level; - return true; - } - } - } - - return false; -} - -void VmaBlockMetadata_Buddy::Alloc( - const VmaAllocationRequest& request, - VmaSuballocationType type, - void* userData) -{ - VMA_ASSERT(request.type == VmaAllocationRequestType::Normal); - - const uint32_t targetLevel = AllocSizeToLevel(request.size); - uint32_t currLevel = (uint32_t)(uintptr_t)request.customData; - - Node* currNode = m_FreeList[currLevel].front; - VMA_ASSERT(currNode != VMA_NULL && currNode->type == Node::TYPE_FREE); - const VkDeviceSize offset = (VkDeviceSize)request.allocHandle - 1; - while (currNode->offset != offset) - { - currNode = currNode->free.next; - VMA_ASSERT(currNode != VMA_NULL && currNode->type == Node::TYPE_FREE); - } - - // Go down, splitting free nodes. - while (currLevel < targetLevel) - { - // currNode is already first free node at currLevel. - // Remove it from list of free nodes at this currLevel. - RemoveFromFreeList(currLevel, currNode); - - const uint32_t childrenLevel = currLevel + 1; - - // Create two free sub-nodes. - Node* leftChild = m_NodeAllocator.Alloc(); - Node* rightChild = m_NodeAllocator.Alloc(); - - leftChild->offset = currNode->offset; - leftChild->type = Node::TYPE_FREE; - leftChild->parent = currNode; - leftChild->buddy = rightChild; - - rightChild->offset = currNode->offset + LevelToNodeSize(childrenLevel); - rightChild->type = Node::TYPE_FREE; - rightChild->parent = currNode; - rightChild->buddy = leftChild; - - // Convert current currNode to split type. - currNode->type = Node::TYPE_SPLIT; - currNode->split.leftChild = leftChild; - - // Add child nodes to free list. Order is important! - AddToFreeListFront(childrenLevel, rightChild); - AddToFreeListFront(childrenLevel, leftChild); - - ++m_FreeCount; - ++currLevel; - currNode = m_FreeList[currLevel].front; - - /* - We can be sure that currNode, as left child of node previously split, - also fulfills the alignment requirement. - */ - } - - // Remove from free list. - VMA_ASSERT(currLevel == targetLevel && - currNode != VMA_NULL && - currNode->type == Node::TYPE_FREE); - RemoveFromFreeList(currLevel, currNode); - - // Convert to allocation node. - currNode->type = Node::TYPE_ALLOCATION; - currNode->allocation.userData = userData; - - ++m_AllocationCount; - --m_FreeCount; - m_SumFreeSize -= request.size; -} - -void VmaBlockMetadata_Buddy::GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) -{ - uint32_t level = 0; - outInfo.offset = (VkDeviceSize)allocHandle - 1; - const Node* const node = FindAllocationNode(outInfo.offset, level); - outInfo.size = LevelToNodeSize(level); - outInfo.pUserData = node->allocation.userData; -} - -void* VmaBlockMetadata_Buddy::GetAllocationUserData(VmaAllocHandle allocHandle) const -{ - uint32_t level = 0; - const Node* const node = FindAllocationNode((VkDeviceSize)allocHandle - 1, level); - return node->allocation.userData; -} - -VmaAllocHandle VmaBlockMetadata_Buddy::GetAllocationListBegin() const -{ - // Function only used for defragmentation, which is disabled for this algorithm - return VK_NULL_HANDLE; -} - -VmaAllocHandle VmaBlockMetadata_Buddy::GetNextAllocation(VmaAllocHandle prevAlloc) const -{ - // Function only used for defragmentation, which is disabled for this algorithm - return VK_NULL_HANDLE; -} - -void VmaBlockMetadata_Buddy::DeleteNodeChildren(Node* node) -{ - if (node->type == Node::TYPE_SPLIT) - { - DeleteNodeChildren(node->split.leftChild->buddy); - DeleteNodeChildren(node->split.leftChild); - const VkAllocationCallbacks* allocationCallbacks = GetAllocationCallbacks(); - m_NodeAllocator.Free(node->split.leftChild->buddy); - m_NodeAllocator.Free(node->split.leftChild); - } -} - -void VmaBlockMetadata_Buddy::Clear() -{ - DeleteNodeChildren(m_Root); - m_Root->type = Node::TYPE_FREE; - m_AllocationCount = 0; - m_FreeCount = 1; - m_SumFreeSize = m_UsableSize; -} - -void VmaBlockMetadata_Buddy::SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) -{ - uint32_t level = 0; - Node* const node = FindAllocationNode((VkDeviceSize)allocHandle - 1, level); - node->allocation.userData = userData; -} - -VmaBlockMetadata_Buddy::Node* VmaBlockMetadata_Buddy::FindAllocationNode(VkDeviceSize offset, uint32_t& outLevel) const -{ - Node* node = m_Root; - VkDeviceSize nodeOffset = 0; - outLevel = 0; - VkDeviceSize levelNodeSize = LevelToNodeSize(0); - while (node->type == Node::TYPE_SPLIT) - { - const VkDeviceSize nextLevelNodeSize = levelNodeSize >> 1; - if (offset < nodeOffset + nextLevelNodeSize) - { - node = node->split.leftChild; - } - else - { - node = node->split.leftChild->buddy; - nodeOffset += nextLevelNodeSize; - } - ++outLevel; - levelNodeSize = nextLevelNodeSize; - } - - VMA_ASSERT(node != VMA_NULL && node->type == Node::TYPE_ALLOCATION); - return node; -} - -bool VmaBlockMetadata_Buddy::ValidateNode(ValidationContext& ctx, const Node* parent, const Node* curr, uint32_t level, VkDeviceSize levelNodeSize) const -{ - VMA_VALIDATE(level < m_LevelCount); - VMA_VALIDATE(curr->parent == parent); - VMA_VALIDATE((curr->buddy == VMA_NULL) == (parent == VMA_NULL)); - VMA_VALIDATE(curr->buddy == VMA_NULL || curr->buddy->buddy == curr); - switch (curr->type) - { - case Node::TYPE_FREE: - // curr->free.prev, next are validated separately. - ctx.calculatedSumFreeSize += levelNodeSize; - ++ctx.calculatedFreeCount; - break; - case Node::TYPE_ALLOCATION: - ++ctx.calculatedAllocationCount; - if (!IsVirtual()) - { - VMA_VALIDATE(curr->allocation.userData != VMA_NULL); - } - break; - case Node::TYPE_SPLIT: - { - const uint32_t childrenLevel = level + 1; - const VkDeviceSize childrenLevelNodeSize = levelNodeSize >> 1; - const Node* const leftChild = curr->split.leftChild; - VMA_VALIDATE(leftChild != VMA_NULL); - VMA_VALIDATE(leftChild->offset == curr->offset); - if (!ValidateNode(ctx, curr, leftChild, childrenLevel, childrenLevelNodeSize)) - { - VMA_VALIDATE(false && "ValidateNode for left child failed."); - } - const Node* const rightChild = leftChild->buddy; - VMA_VALIDATE(rightChild->offset == curr->offset + childrenLevelNodeSize); - if (!ValidateNode(ctx, curr, rightChild, childrenLevel, childrenLevelNodeSize)) - { - VMA_VALIDATE(false && "ValidateNode for right child failed."); - } - } - break; - default: - return false; - } - - return true; -} - -uint32_t VmaBlockMetadata_Buddy::AllocSizeToLevel(VkDeviceSize allocSize) const -{ - // I know this could be optimized somehow e.g. by using std::log2p1 from C++20. - uint32_t level = 0; - VkDeviceSize currLevelNodeSize = m_UsableSize; - VkDeviceSize nextLevelNodeSize = currLevelNodeSize >> 1; - while (allocSize <= nextLevelNodeSize && level + 1 < m_LevelCount) - { - ++level; - currLevelNodeSize >>= 1; - nextLevelNodeSize >>= 1; - } - return level; -} - -void VmaBlockMetadata_Buddy::Free(VmaAllocHandle allocHandle) -{ - uint32_t level = 0; - Node* node = FindAllocationNode((VkDeviceSize)allocHandle - 1, level); - - ++m_FreeCount; - --m_AllocationCount; - m_SumFreeSize += LevelToNodeSize(level); - - node->type = Node::TYPE_FREE; - - // Join free nodes if possible. - while (level > 0 && node->buddy->type == Node::TYPE_FREE) - { - RemoveFromFreeList(level, node->buddy); - Node* const parent = node->parent; - - m_NodeAllocator.Free(node->buddy); - m_NodeAllocator.Free(node); - parent->type = Node::TYPE_FREE; - - node = parent; - --level; - --m_FreeCount; - } - - AddToFreeListFront(level, node); -} - -void VmaBlockMetadata_Buddy::AddNodeToDetailedStatistics(VmaDetailedStatistics& inoutStats, const Node* node, VkDeviceSize levelNodeSize) const -{ - switch (node->type) - { - case Node::TYPE_FREE: - VmaAddDetailedStatisticsUnusedRange(inoutStats, levelNodeSize); - break; - case Node::TYPE_ALLOCATION: - VmaAddDetailedStatisticsAllocation(inoutStats, levelNodeSize); - break; - case Node::TYPE_SPLIT: - { - const VkDeviceSize childrenNodeSize = levelNodeSize / 2; - const Node* const leftChild = node->split.leftChild; - AddNodeToDetailedStatistics(inoutStats, leftChild, childrenNodeSize); - const Node* const rightChild = leftChild->buddy; - AddNodeToDetailedStatistics(inoutStats, rightChild, childrenNodeSize); - } - break; - default: - VMA_ASSERT(0); - } -} - -void VmaBlockMetadata_Buddy::AddToFreeListFront(uint32_t level, Node* node) -{ - VMA_ASSERT(node->type == Node::TYPE_FREE); - - // List is empty. - Node* const frontNode = m_FreeList[level].front; - if (frontNode == VMA_NULL) - { - VMA_ASSERT(m_FreeList[level].back == VMA_NULL); - node->free.prev = node->free.next = VMA_NULL; - m_FreeList[level].front = m_FreeList[level].back = node; - } - else - { - VMA_ASSERT(frontNode->free.prev == VMA_NULL); - node->free.prev = VMA_NULL; - node->free.next = frontNode; - frontNode->free.prev = node; - m_FreeList[level].front = node; - } -} - -void VmaBlockMetadata_Buddy::RemoveFromFreeList(uint32_t level, Node* node) -{ - VMA_ASSERT(m_FreeList[level].front != VMA_NULL); - - // It is at the front. - if (node->free.prev == VMA_NULL) - { - VMA_ASSERT(m_FreeList[level].front == node); - m_FreeList[level].front = node->free.next; - } - else - { - Node* const prevFreeNode = node->free.prev; - VMA_ASSERT(prevFreeNode->free.next == node); - prevFreeNode->free.next = node->free.next; - } - - // It is at the back. - if (node->free.next == VMA_NULL) - { - VMA_ASSERT(m_FreeList[level].back == node); - m_FreeList[level].back = node->free.prev; - } - else - { - Node* const nextFreeNode = node->free.next; - VMA_ASSERT(nextFreeNode->free.prev == node); - nextFreeNode->free.prev = node->free.prev; - } -} - -void VmaBlockMetadata_Buddy::DebugLogAllAllocationNode(Node* node, uint32_t level) const -{ - switch (node->type) - { - case Node::TYPE_FREE: - break; - case Node::TYPE_ALLOCATION: - DebugLogAllocation(node->offset, LevelToNodeSize(level), node->allocation.userData); - break; - case Node::TYPE_SPLIT: - { - ++level; - DebugLogAllAllocationNode(node->split.leftChild, level); - DebugLogAllAllocationNode(node->split.leftChild->buddy, level); - } - break; - default: - VMA_ASSERT(0); - } -} - -#if VMA_STATS_STRING_ENABLED -void VmaBlockMetadata_Buddy::PrintDetailedMapNode(class VmaJsonWriter& json, const Node* node, VkDeviceSize levelNodeSize) const -{ - switch (node->type) - { - case Node::TYPE_FREE: - PrintDetailedMap_UnusedRange(json, node->offset, levelNodeSize); - break; - case Node::TYPE_ALLOCATION: - PrintDetailedMap_Allocation(json, node->offset, levelNodeSize, node->allocation.userData); - break; - case Node::TYPE_SPLIT: - { - const VkDeviceSize childrenNodeSize = levelNodeSize / 2; - const Node* const leftChild = node->split.leftChild; - PrintDetailedMapNode(json, leftChild, childrenNodeSize); - const Node* const rightChild = leftChild->buddy; - PrintDetailedMapNode(json, rightChild, childrenNodeSize); - } - break; - default: - VMA_ASSERT(0); - } -} -#endif // VMA_STATS_STRING_ENABLED -#endif // _VMA_BLOCK_METADATA_BUDDY_FUNCTIONS -#endif // _VMA_BLOCK_METADATA_BUDDY -#endif // #if 0 - -#ifndef _VMA_BLOCK_METADATA_TLSF -// To not search current larger region if first allocation won't succeed and skip to smaller range -// use with VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT as strategy in CreateAllocationRequest(). -// When fragmentation and reusal of previous blocks doesn't matter then use with -// VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT for fastest alloc time possible. -class VmaBlockMetadata_TLSF : public VmaBlockMetadata -{ - VMA_CLASS_NO_COPY(VmaBlockMetadata_TLSF) -public: - VmaBlockMetadata_TLSF(const VkAllocationCallbacks* pAllocationCallbacks, - VkDeviceSize bufferImageGranularity, bool isVirtual); - virtual ~VmaBlockMetadata_TLSF(); - - size_t GetAllocationCount() const override { return m_AllocCount; } - size_t GetFreeRegionsCount() const override { return m_BlocksFreeCount + 1; } - VkDeviceSize GetSumFreeSize() const override { return m_BlocksFreeSize + m_NullBlock->size; } - bool IsEmpty() const override { return m_NullBlock->offset == 0; } - VkDeviceSize GetAllocationOffset(VmaAllocHandle allocHandle) const override { return ((Block*)allocHandle)->offset; }; - - void Init(VkDeviceSize size) override; - bool Validate() const override; - - void AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const override; - void AddStatistics(VmaStatistics& inoutStats) const override; - -#if VMA_STATS_STRING_ENABLED - void PrintDetailedMap(class VmaJsonWriter& json) const override; -#endif - - bool CreateAllocationRequest( - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - bool upperAddress, - VmaSuballocationType allocType, - uint32_t strategy, - VmaAllocationRequest* pAllocationRequest) override; - - VkResult CheckCorruption(const void* pBlockData) override; - void Alloc( - const VmaAllocationRequest& request, - VmaSuballocationType type, - void* userData) override; - - void Free(VmaAllocHandle allocHandle) override; - void GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) override; - void* GetAllocationUserData(VmaAllocHandle allocHandle) const override; - VmaAllocHandle GetAllocationListBegin() const override; - VmaAllocHandle GetNextAllocation(VmaAllocHandle prevAlloc) const override; - VkDeviceSize GetNextFreeRegionSize(VmaAllocHandle alloc) const override; - void Clear() override; - void SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) override; - void DebugLogAllAllocations() const override; - -private: - // According to original paper it should be preferable 4 or 5: - // M. Masmano, I. Ripoll, A. Crespo, and J. Real "TLSF: a New Dynamic Memory Allocator for Real-Time Systems" - // http://www.gii.upv.es/tlsf/files/ecrts04_tlsf.pdf - static const uint8_t SECOND_LEVEL_INDEX = 5; - static const uint16_t SMALL_BUFFER_SIZE = 256; - static const uint32_t INITIAL_BLOCK_ALLOC_COUNT = 16; - static const uint8_t MEMORY_CLASS_SHIFT = 7; - static const uint8_t MAX_MEMORY_CLASSES = 65 - MEMORY_CLASS_SHIFT; - - class Block - { - public: - VkDeviceSize offset; - VkDeviceSize size; - Block* prevPhysical; - Block* nextPhysical; - - void MarkFree() { prevFree = VMA_NULL; } - void MarkTaken() { prevFree = this; } - bool IsFree() const { return prevFree != this; } - void*& UserData() { VMA_HEAVY_ASSERT(!IsFree()); return userData; } - Block*& PrevFree() { return prevFree; } - Block*& NextFree() { VMA_HEAVY_ASSERT(IsFree()); return nextFree; } - - private: - Block* prevFree; // Address of the same block here indicates that block is taken - union - { - Block* nextFree; - void* userData; - }; - }; - - size_t m_AllocCount; - // Total number of free blocks besides null block - size_t m_BlocksFreeCount; - // Total size of free blocks excluding null block - VkDeviceSize m_BlocksFreeSize; - uint32_t m_IsFreeBitmap; - uint8_t m_MemoryClasses; - uint32_t m_InnerIsFreeBitmap[MAX_MEMORY_CLASSES]; - uint32_t m_ListsCount; - /* - * 0: 0-3 lists for small buffers - * 1+: 0-(2^SLI-1) lists for normal buffers - */ - Block** m_FreeList; - VmaPoolAllocator m_BlockAllocator; - Block* m_NullBlock; - VmaBlockBufferImageGranularity m_GranularityHandler; - - uint8_t SizeToMemoryClass(VkDeviceSize size) const; - uint16_t SizeToSecondIndex(VkDeviceSize size, uint8_t memoryClass) const; - uint32_t GetListIndex(uint8_t memoryClass, uint16_t secondIndex) const; - uint32_t GetListIndex(VkDeviceSize size) const; - - void RemoveFreeBlock(Block* block); - void InsertFreeBlock(Block* block); - void MergeBlock(Block* block, Block* prev); - - Block* FindFreeBlock(VkDeviceSize size, uint32_t& listIndex) const; - bool CheckBlock( - Block& block, - uint32_t listIndex, - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - VmaSuballocationType allocType, - VmaAllocationRequest* pAllocationRequest); -}; - -#ifndef _VMA_BLOCK_METADATA_TLSF_FUNCTIONS -VmaBlockMetadata_TLSF::VmaBlockMetadata_TLSF(const VkAllocationCallbacks* pAllocationCallbacks, - VkDeviceSize bufferImageGranularity, bool isVirtual) - : VmaBlockMetadata(pAllocationCallbacks, bufferImageGranularity, isVirtual), - m_AllocCount(0), - m_BlocksFreeCount(0), - m_BlocksFreeSize(0), - m_IsFreeBitmap(0), - m_MemoryClasses(0), - m_ListsCount(0), - m_FreeList(VMA_NULL), - m_BlockAllocator(pAllocationCallbacks, INITIAL_BLOCK_ALLOC_COUNT), - m_NullBlock(VMA_NULL), - m_GranularityHandler(bufferImageGranularity) {} - -VmaBlockMetadata_TLSF::~VmaBlockMetadata_TLSF() -{ - if (m_FreeList) - vma_delete_array(GetAllocationCallbacks(), m_FreeList, m_ListsCount); - m_GranularityHandler.Destroy(GetAllocationCallbacks()); -} - -void VmaBlockMetadata_TLSF::Init(VkDeviceSize size) -{ - VmaBlockMetadata::Init(size); - - if (!IsVirtual()) - m_GranularityHandler.Init(GetAllocationCallbacks(), size); - - m_NullBlock = m_BlockAllocator.Alloc(); - m_NullBlock->size = size; - m_NullBlock->offset = 0; - m_NullBlock->prevPhysical = VMA_NULL; - m_NullBlock->nextPhysical = VMA_NULL; - m_NullBlock->MarkFree(); - m_NullBlock->NextFree() = VMA_NULL; - m_NullBlock->PrevFree() = VMA_NULL; - uint8_t memoryClass = SizeToMemoryClass(size); - uint16_t sli = SizeToSecondIndex(size, memoryClass); - m_ListsCount = (memoryClass == 0 ? 0 : (memoryClass - 1) * (1UL << SECOND_LEVEL_INDEX) + sli) + 1; - if (IsVirtual()) - m_ListsCount += 1UL << SECOND_LEVEL_INDEX; - else - m_ListsCount += 4; - - m_MemoryClasses = memoryClass + 2; - memset(m_InnerIsFreeBitmap, 0, MAX_MEMORY_CLASSES * sizeof(uint32_t)); - - m_FreeList = vma_new_array(GetAllocationCallbacks(), Block*, m_ListsCount); - memset(m_FreeList, 0, m_ListsCount * sizeof(Block*)); -} - -bool VmaBlockMetadata_TLSF::Validate() const -{ - VMA_VALIDATE(GetSumFreeSize() <= GetSize()); - - VkDeviceSize calculatedSize = m_NullBlock->size; - VkDeviceSize calculatedFreeSize = m_NullBlock->size; - size_t allocCount = 0; - size_t freeCount = 0; - - // Check integrity of free lists - for (uint32_t list = 0; list < m_ListsCount; ++list) - { - Block* block = m_FreeList[list]; - if (block != VMA_NULL) - { - VMA_VALIDATE(block->IsFree()); - VMA_VALIDATE(block->PrevFree() == VMA_NULL); - while (block->NextFree()) - { - VMA_VALIDATE(block->NextFree()->IsFree()); - VMA_VALIDATE(block->NextFree()->PrevFree() == block); - block = block->NextFree(); - } - } - } - - VkDeviceSize nextOffset = m_NullBlock->offset; - auto validateCtx = m_GranularityHandler.StartValidation(GetAllocationCallbacks(), IsVirtual()); - - VMA_VALIDATE(m_NullBlock->nextPhysical == VMA_NULL); - if (m_NullBlock->prevPhysical) - { - VMA_VALIDATE(m_NullBlock->prevPhysical->nextPhysical == m_NullBlock); - } - // Check all blocks - for (Block* prev = m_NullBlock->prevPhysical; prev != VMA_NULL; prev = prev->prevPhysical) - { - VMA_VALIDATE(prev->offset + prev->size == nextOffset); - nextOffset = prev->offset; - calculatedSize += prev->size; - - uint32_t listIndex = GetListIndex(prev->size); - if (prev->IsFree()) - { - ++freeCount; - // Check if free block belongs to free list - Block* freeBlock = m_FreeList[listIndex]; - VMA_VALIDATE(freeBlock != VMA_NULL); - - bool found = false; - do - { - if (freeBlock == prev) - found = true; - - freeBlock = freeBlock->NextFree(); - } while (!found && freeBlock != VMA_NULL); - - VMA_VALIDATE(found); - calculatedFreeSize += prev->size; - } - else - { - ++allocCount; - // Check if taken block is not on a free list - Block* freeBlock = m_FreeList[listIndex]; - while (freeBlock) - { - VMA_VALIDATE(freeBlock != prev); - freeBlock = freeBlock->NextFree(); - } - - if (!IsVirtual()) - { - VMA_VALIDATE(m_GranularityHandler.Validate(validateCtx, prev->offset, prev->size)); - } - } - - if (prev->prevPhysical) - { - VMA_VALIDATE(prev->prevPhysical->nextPhysical == prev); - } - } - - if (!IsVirtual()) - { - VMA_VALIDATE(m_GranularityHandler.FinishValidation(validateCtx)); - } - - VMA_VALIDATE(nextOffset == 0); - VMA_VALIDATE(calculatedSize == GetSize()); - VMA_VALIDATE(calculatedFreeSize == GetSumFreeSize()); - VMA_VALIDATE(allocCount == m_AllocCount); - VMA_VALIDATE(freeCount == m_BlocksFreeCount); - - return true; -} - -void VmaBlockMetadata_TLSF::AddDetailedStatistics(VmaDetailedStatistics& inoutStats) const -{ - inoutStats.statistics.blockCount++; - inoutStats.statistics.blockBytes += GetSize(); - if (m_NullBlock->size > 0) - VmaAddDetailedStatisticsUnusedRange(inoutStats, m_NullBlock->size); - - for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical) - { - if (block->IsFree()) - VmaAddDetailedStatisticsUnusedRange(inoutStats, block->size); - else - VmaAddDetailedStatisticsAllocation(inoutStats, block->size); - } -} - -void VmaBlockMetadata_TLSF::AddStatistics(VmaStatistics& inoutStats) const -{ - inoutStats.blockCount++; - inoutStats.allocationCount += (uint32_t)m_AllocCount; - inoutStats.blockBytes += GetSize(); - inoutStats.allocationBytes += GetSize() - GetSumFreeSize(); -} - -#if VMA_STATS_STRING_ENABLED -void VmaBlockMetadata_TLSF::PrintDetailedMap(class VmaJsonWriter& json) const -{ - size_t blockCount = m_AllocCount + m_BlocksFreeCount; - VmaStlAllocator allocator(GetAllocationCallbacks()); - VmaVector> blockList(blockCount, allocator); - - size_t i = blockCount; - for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical) - { - blockList[--i] = block; - } - VMA_ASSERT(i == 0); - - VmaDetailedStatistics stats; - VmaClearDetailedStatistics(stats); - AddDetailedStatistics(stats); - - PrintDetailedMap_Begin(json, - stats.statistics.blockBytes - stats.statistics.allocationBytes, - stats.statistics.allocationCount, - stats.unusedRangeCount); - - for (; i < blockCount; ++i) - { - Block* block = blockList[i]; - if (block->IsFree()) - PrintDetailedMap_UnusedRange(json, block->offset, block->size); - else - PrintDetailedMap_Allocation(json, block->offset, block->size, block->UserData()); - } - if (m_NullBlock->size > 0) - PrintDetailedMap_UnusedRange(json, m_NullBlock->offset, m_NullBlock->size); - - PrintDetailedMap_End(json); -} -#endif - -bool VmaBlockMetadata_TLSF::CreateAllocationRequest( - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - bool upperAddress, - VmaSuballocationType allocType, - uint32_t strategy, - VmaAllocationRequest* pAllocationRequest) -{ - VMA_ASSERT(allocSize > 0 && "Cannot allocate empty block!"); - VMA_ASSERT(!upperAddress && "VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT can be used only with linear algorithm."); - - // For small granularity round up - if (!IsVirtual()) - m_GranularityHandler.RoundupAllocRequest(allocType, allocSize, allocAlignment); - - allocSize += GetDebugMargin(); - // Quick check for too small pool - if (allocSize > GetSumFreeSize()) - return false; - - // If no free blocks in pool then check only null block - if (m_BlocksFreeCount == 0) - return CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest); - - // Round up to the next block - VkDeviceSize sizeForNextList = allocSize; - VkDeviceSize smallSizeStep = SMALL_BUFFER_SIZE / (IsVirtual() ? 1 << SECOND_LEVEL_INDEX : 4); - if (allocSize > SMALL_BUFFER_SIZE) - { - sizeForNextList += (1ULL << (VMA_BITSCAN_MSB(allocSize) - SECOND_LEVEL_INDEX)); - } - else if (allocSize > SMALL_BUFFER_SIZE - smallSizeStep) - sizeForNextList = SMALL_BUFFER_SIZE + 1; - else - sizeForNextList += smallSizeStep; - - uint32_t nextListIndex = 0; - uint32_t prevListIndex = 0; - Block* nextListBlock = VMA_NULL; - Block* prevListBlock = VMA_NULL; - - // Check blocks according to strategies - if (strategy & VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT) - { - // Quick check for larger block first - nextListBlock = FindFreeBlock(sizeForNextList, nextListIndex); - if (nextListBlock != VMA_NULL && CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest)) - return true; - - // If not fitted then null block - if (CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest)) - return true; - - // Null block failed, search larger bucket - while (nextListBlock) - { - if (CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest)) - return true; - nextListBlock = nextListBlock->NextFree(); - } - - // Failed again, check best fit bucket - prevListBlock = FindFreeBlock(allocSize, prevListIndex); - while (prevListBlock) - { - if (CheckBlock(*prevListBlock, prevListIndex, allocSize, allocAlignment, allocType, pAllocationRequest)) - return true; - prevListBlock = prevListBlock->NextFree(); - } - } - else if (strategy & VMA_ALLOCATION_CREATE_STRATEGY_MIN_MEMORY_BIT) - { - // Check best fit bucket - prevListBlock = FindFreeBlock(allocSize, prevListIndex); - while (prevListBlock) - { - if (CheckBlock(*prevListBlock, prevListIndex, allocSize, allocAlignment, allocType, pAllocationRequest)) - return true; - prevListBlock = prevListBlock->NextFree(); - } - - // If failed check null block - if (CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest)) - return true; - - // Check larger bucket - nextListBlock = FindFreeBlock(sizeForNextList, nextListIndex); - while (nextListBlock) - { - if (CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest)) - return true; - nextListBlock = nextListBlock->NextFree(); - } - } - else if (strategy & VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT ) - { - // Perform search from the start - VmaStlAllocator allocator(GetAllocationCallbacks()); - VmaVector> blockList(m_BlocksFreeCount, allocator); - - size_t i = m_BlocksFreeCount; - for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical) - { - if (block->IsFree() && block->size >= allocSize) - blockList[--i] = block; - } - - for (; i < m_BlocksFreeCount; ++i) - { - Block& block = *blockList[i]; - if (CheckBlock(block, GetListIndex(block.size), allocSize, allocAlignment, allocType, pAllocationRequest)) - return true; - } - - // If failed check null block - if (CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest)) - return true; - - // Whole range searched, no more memory - return false; - } - else - { - // Check larger bucket - nextListBlock = FindFreeBlock(sizeForNextList, nextListIndex); - while (nextListBlock) - { - if (CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest)) - return true; - nextListBlock = nextListBlock->NextFree(); - } - - // If failed check null block - if (CheckBlock(*m_NullBlock, m_ListsCount, allocSize, allocAlignment, allocType, pAllocationRequest)) - return true; - - // Check best fit bucket - prevListBlock = FindFreeBlock(allocSize, prevListIndex); - while (prevListBlock) - { - if (CheckBlock(*prevListBlock, prevListIndex, allocSize, allocAlignment, allocType, pAllocationRequest)) - return true; - prevListBlock = prevListBlock->NextFree(); - } - } - - // Worst case, full search has to be done - while (++nextListIndex < m_ListsCount) - { - nextListBlock = m_FreeList[nextListIndex]; - while (nextListBlock) - { - if (CheckBlock(*nextListBlock, nextListIndex, allocSize, allocAlignment, allocType, pAllocationRequest)) - return true; - nextListBlock = nextListBlock->NextFree(); - } - } - - // No more memory sadly - return false; -} - -VkResult VmaBlockMetadata_TLSF::CheckCorruption(const void* pBlockData) -{ - for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical) - { - if (!block->IsFree()) - { - if (!VmaValidateMagicValue(pBlockData, block->offset + block->size)) - { - VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER VALIDATED ALLOCATION!"); - return VK_ERROR_UNKNOWN_COPY; - } - } - } - - return VK_SUCCESS; -} - -void VmaBlockMetadata_TLSF::Alloc( - const VmaAllocationRequest& request, - VmaSuballocationType type, - void* userData) -{ - VMA_ASSERT(request.type == VmaAllocationRequestType::TLSF); - - // Get block and pop it from the free list - Block* currentBlock = (Block*)request.allocHandle; - VkDeviceSize offset = request.algorithmData; - VMA_ASSERT(currentBlock != VMA_NULL); - VMA_ASSERT(currentBlock->offset <= offset); - - if (currentBlock != m_NullBlock) - RemoveFreeBlock(currentBlock); - - VkDeviceSize debugMargin = GetDebugMargin(); - VkDeviceSize misssingAlignment = offset - currentBlock->offset; - - // Append missing alignment to prev block or create new one - if (misssingAlignment) - { - Block* prevBlock = currentBlock->prevPhysical; - VMA_ASSERT(prevBlock != VMA_NULL && "There should be no missing alignment at offset 0!"); - - if (prevBlock->IsFree() && prevBlock->size != debugMargin) - { - uint32_t oldList = GetListIndex(prevBlock->size); - prevBlock->size += misssingAlignment; - // Check if new size crosses list bucket - if (oldList != GetListIndex(prevBlock->size)) - { - prevBlock->size -= misssingAlignment; - RemoveFreeBlock(prevBlock); - prevBlock->size += misssingAlignment; - InsertFreeBlock(prevBlock); - } - else - m_BlocksFreeSize += misssingAlignment; - } - else - { - Block* newBlock = m_BlockAllocator.Alloc(); - currentBlock->prevPhysical = newBlock; - prevBlock->nextPhysical = newBlock; - newBlock->prevPhysical = prevBlock; - newBlock->nextPhysical = currentBlock; - newBlock->size = misssingAlignment; - newBlock->offset = currentBlock->offset; - newBlock->MarkTaken(); - - InsertFreeBlock(newBlock); - } - - currentBlock->size -= misssingAlignment; - currentBlock->offset += misssingAlignment; - } - - VkDeviceSize size = request.size + debugMargin; - if (currentBlock->size == size) - { - if (currentBlock == m_NullBlock) - { - // Setup new null block - m_NullBlock = m_BlockAllocator.Alloc(); - m_NullBlock->size = 0; - m_NullBlock->offset = currentBlock->offset + size; - m_NullBlock->prevPhysical = currentBlock; - m_NullBlock->nextPhysical = VMA_NULL; - m_NullBlock->MarkFree(); - m_NullBlock->PrevFree() = VMA_NULL; - m_NullBlock->NextFree() = VMA_NULL; - currentBlock->nextPhysical = m_NullBlock; - currentBlock->MarkTaken(); - } - } - else - { - VMA_ASSERT(currentBlock->size > size && "Proper block already found, shouldn't find smaller one!"); - - // Create new free block - Block* newBlock = m_BlockAllocator.Alloc(); - newBlock->size = currentBlock->size - size; - newBlock->offset = currentBlock->offset + size; - newBlock->prevPhysical = currentBlock; - newBlock->nextPhysical = currentBlock->nextPhysical; - currentBlock->nextPhysical = newBlock; - currentBlock->size = size; - - if (currentBlock == m_NullBlock) - { - m_NullBlock = newBlock; - m_NullBlock->MarkFree(); - m_NullBlock->NextFree() = VMA_NULL; - m_NullBlock->PrevFree() = VMA_NULL; - currentBlock->MarkTaken(); - } - else - { - newBlock->nextPhysical->prevPhysical = newBlock; - newBlock->MarkTaken(); - InsertFreeBlock(newBlock); - } - } - currentBlock->UserData() = userData; - - if (debugMargin > 0) - { - currentBlock->size -= debugMargin; - Block* newBlock = m_BlockAllocator.Alloc(); - newBlock->size = debugMargin; - newBlock->offset = currentBlock->offset + currentBlock->size; - newBlock->prevPhysical = currentBlock; - newBlock->nextPhysical = currentBlock->nextPhysical; - newBlock->MarkTaken(); - currentBlock->nextPhysical->prevPhysical = newBlock; - currentBlock->nextPhysical = newBlock; - InsertFreeBlock(newBlock); - } - - if (!IsVirtual()) - m_GranularityHandler.AllocPages((uint8_t)(uintptr_t)request.customData, - currentBlock->offset, currentBlock->size); - ++m_AllocCount; -} - -void VmaBlockMetadata_TLSF::Free(VmaAllocHandle allocHandle) -{ - Block* block = (Block*)allocHandle; - Block* next = block->nextPhysical; - VMA_ASSERT(!block->IsFree() && "Block is already free!"); - - if (!IsVirtual()) - m_GranularityHandler.FreePages(block->offset, block->size); - --m_AllocCount; - - VkDeviceSize debugMargin = GetDebugMargin(); - if (debugMargin > 0) - { - RemoveFreeBlock(next); - MergeBlock(next, block); - block = next; - next = next->nextPhysical; - } - - // Try merging - Block* prev = block->prevPhysical; - if (prev != VMA_NULL && prev->IsFree() && prev->size != debugMargin) - { - RemoveFreeBlock(prev); - MergeBlock(block, prev); - } - - if (!next->IsFree()) - InsertFreeBlock(block); - else if (next == m_NullBlock) - MergeBlock(m_NullBlock, block); - else - { - RemoveFreeBlock(next); - MergeBlock(next, block); - InsertFreeBlock(next); - } -} - -void VmaBlockMetadata_TLSF::GetAllocationInfo(VmaAllocHandle allocHandle, VmaVirtualAllocationInfo& outInfo) -{ - Block* block = (Block*)allocHandle; - VMA_ASSERT(!block->IsFree() && "Cannot get allocation info for free block!"); - outInfo.offset = block->offset; - outInfo.size = block->size; - outInfo.pUserData = block->UserData(); -} - -void* VmaBlockMetadata_TLSF::GetAllocationUserData(VmaAllocHandle allocHandle) const -{ - Block* block = (Block*)allocHandle; - VMA_ASSERT(!block->IsFree() && "Cannot get user data for free block!"); - return block->UserData(); -} - -VmaAllocHandle VmaBlockMetadata_TLSF::GetAllocationListBegin() const -{ - if (m_AllocCount == 0) - return VK_NULL_HANDLE; - - for (Block* block = m_NullBlock->prevPhysical; block; block = block->prevPhysical) - { - if (!block->IsFree()) - return (VmaAllocHandle)block; - } - VMA_ASSERT(false && "If m_AllocCount > 0 then should find any allocation!"); - return VK_NULL_HANDLE; -} - -VmaAllocHandle VmaBlockMetadata_TLSF::GetNextAllocation(VmaAllocHandle prevAlloc) const -{ - Block* startBlock = (Block*)prevAlloc; - VMA_ASSERT(!startBlock->IsFree() && "Incorrect block!"); - - for (Block* block = startBlock->prevPhysical; block; block = block->prevPhysical) - { - if (!block->IsFree()) - return (VmaAllocHandle)block; - } - return VK_NULL_HANDLE; -} - -VkDeviceSize VmaBlockMetadata_TLSF::GetNextFreeRegionSize(VmaAllocHandle alloc) const -{ - Block* block = (Block*)alloc; - VMA_ASSERT(!block->IsFree() && "Incorrect block!"); - - if (block->prevPhysical) - return block->prevPhysical->IsFree() ? block->prevPhysical->size : 0; - return 0; -} - -void VmaBlockMetadata_TLSF::Clear() -{ - m_AllocCount = 0; - m_BlocksFreeCount = 0; - m_BlocksFreeSize = 0; - m_IsFreeBitmap = 0; - m_NullBlock->offset = 0; - m_NullBlock->size = GetSize(); - Block* block = m_NullBlock->prevPhysical; - m_NullBlock->prevPhysical = VMA_NULL; - while (block) - { - Block* prev = block->prevPhysical; - m_BlockAllocator.Free(block); - block = prev; - } - memset(m_FreeList, 0, m_ListsCount * sizeof(Block*)); - memset(m_InnerIsFreeBitmap, 0, m_MemoryClasses * sizeof(uint32_t)); - m_GranularityHandler.Clear(); -} - -void VmaBlockMetadata_TLSF::SetAllocationUserData(VmaAllocHandle allocHandle, void* userData) -{ - Block* block = (Block*)allocHandle; - VMA_ASSERT(!block->IsFree() && "Trying to set user data for not allocated block!"); - block->UserData() = userData; -} - -void VmaBlockMetadata_TLSF::DebugLogAllAllocations() const -{ - for (Block* block = m_NullBlock->prevPhysical; block != VMA_NULL; block = block->prevPhysical) - if (!block->IsFree()) - DebugLogAllocation(block->offset, block->size, block->UserData()); -} - -uint8_t VmaBlockMetadata_TLSF::SizeToMemoryClass(VkDeviceSize size) const -{ - if (size > SMALL_BUFFER_SIZE) - return VMA_BITSCAN_MSB(size) - MEMORY_CLASS_SHIFT; - return 0; -} - -uint16_t VmaBlockMetadata_TLSF::SizeToSecondIndex(VkDeviceSize size, uint8_t memoryClass) const -{ - if (memoryClass == 0) - { - if (IsVirtual()) - return static_cast((size - 1) / 8); - else - return static_cast((size - 1) / 64); - } - return static_cast((size >> (memoryClass + MEMORY_CLASS_SHIFT - SECOND_LEVEL_INDEX)) ^ (1U << SECOND_LEVEL_INDEX)); -} - -uint32_t VmaBlockMetadata_TLSF::GetListIndex(uint8_t memoryClass, uint16_t secondIndex) const -{ - if (memoryClass == 0) - return secondIndex; - - const uint32_t index = static_cast(memoryClass - 1) * (1 << SECOND_LEVEL_INDEX) + secondIndex; - if (IsVirtual()) - return index + (1 << SECOND_LEVEL_INDEX); - else - return index + 4; -} - -uint32_t VmaBlockMetadata_TLSF::GetListIndex(VkDeviceSize size) const -{ - uint8_t memoryClass = SizeToMemoryClass(size); - return GetListIndex(memoryClass, SizeToSecondIndex(size, memoryClass)); -} - -void VmaBlockMetadata_TLSF::RemoveFreeBlock(Block* block) -{ - VMA_ASSERT(block != m_NullBlock); - VMA_ASSERT(block->IsFree()); - - if (block->NextFree() != VMA_NULL) - block->NextFree()->PrevFree() = block->PrevFree(); - if (block->PrevFree() != VMA_NULL) - block->PrevFree()->NextFree() = block->NextFree(); - else - { - uint8_t memClass = SizeToMemoryClass(block->size); - uint16_t secondIndex = SizeToSecondIndex(block->size, memClass); - uint32_t index = GetListIndex(memClass, secondIndex); - VMA_ASSERT(m_FreeList[index] == block); - m_FreeList[index] = block->NextFree(); - if (block->NextFree() == VMA_NULL) - { - m_InnerIsFreeBitmap[memClass] &= ~(1U << secondIndex); - if (m_InnerIsFreeBitmap[memClass] == 0) - m_IsFreeBitmap &= ~(1UL << memClass); - } - } - block->MarkTaken(); - block->UserData() = VMA_NULL; - --m_BlocksFreeCount; - m_BlocksFreeSize -= block->size; -} - -void VmaBlockMetadata_TLSF::InsertFreeBlock(Block* block) -{ - VMA_ASSERT(block != m_NullBlock); - VMA_ASSERT(!block->IsFree() && "Cannot insert block twice!"); - - uint8_t memClass = SizeToMemoryClass(block->size); - uint16_t secondIndex = SizeToSecondIndex(block->size, memClass); - uint32_t index = GetListIndex(memClass, secondIndex); - VMA_ASSERT(index < m_ListsCount); - block->PrevFree() = VMA_NULL; - block->NextFree() = m_FreeList[index]; - m_FreeList[index] = block; - if (block->NextFree() != VMA_NULL) - block->NextFree()->PrevFree() = block; - else - { - m_InnerIsFreeBitmap[memClass] |= 1U << secondIndex; - m_IsFreeBitmap |= 1UL << memClass; - } - ++m_BlocksFreeCount; - m_BlocksFreeSize += block->size; -} - -void VmaBlockMetadata_TLSF::MergeBlock(Block* block, Block* prev) -{ - VMA_ASSERT(block->prevPhysical == prev && "Cannot merge separate physical regions!"); - VMA_ASSERT(!prev->IsFree() && "Cannot merge block that belongs to free list!"); - - block->offset = prev->offset; - block->size += prev->size; - block->prevPhysical = prev->prevPhysical; - if (block->prevPhysical) - block->prevPhysical->nextPhysical = block; - m_BlockAllocator.Free(prev); -} - -VmaBlockMetadata_TLSF::Block* VmaBlockMetadata_TLSF::FindFreeBlock(VkDeviceSize size, uint32_t& listIndex) const -{ - uint8_t memoryClass = SizeToMemoryClass(size); - uint32_t innerFreeMap = m_InnerIsFreeBitmap[memoryClass] & (~0U << SizeToSecondIndex(size, memoryClass)); - if (!innerFreeMap) - { - // Check higher levels for available blocks - uint32_t freeMap = m_IsFreeBitmap & (~0UL << (memoryClass + 1)); - if (!freeMap) - return VMA_NULL; // No more memory available - - // Find lowest free region - memoryClass = VMA_BITSCAN_LSB(freeMap); - innerFreeMap = m_InnerIsFreeBitmap[memoryClass]; - VMA_ASSERT(innerFreeMap != 0); - } - // Find lowest free subregion - listIndex = GetListIndex(memoryClass, VMA_BITSCAN_LSB(innerFreeMap)); - VMA_ASSERT(m_FreeList[listIndex]); - return m_FreeList[listIndex]; -} - -bool VmaBlockMetadata_TLSF::CheckBlock( - Block& block, - uint32_t listIndex, - VkDeviceSize allocSize, - VkDeviceSize allocAlignment, - VmaSuballocationType allocType, - VmaAllocationRequest* pAllocationRequest) -{ - VMA_ASSERT(block.IsFree() && "Block is already taken!"); - - VkDeviceSize alignedOffset = VmaAlignUp(block.offset, allocAlignment); - if (block.size < allocSize + alignedOffset - block.offset) - return false; - - // Check for granularity conflicts - if (!IsVirtual() && - m_GranularityHandler.CheckConflictAndAlignUp(alignedOffset, allocSize, block.offset, block.size, allocType)) - return false; - - // Alloc successful - pAllocationRequest->type = VmaAllocationRequestType::TLSF; - pAllocationRequest->allocHandle = (VmaAllocHandle)█ - pAllocationRequest->size = allocSize - GetDebugMargin(); - pAllocationRequest->customData = (void*)allocType; - pAllocationRequest->algorithmData = alignedOffset; - - // Place block at the start of list if it's normal block - if (listIndex != m_ListsCount && block.PrevFree()) - { - block.PrevFree()->NextFree() = block.NextFree(); - if (block.NextFree()) - block.NextFree()->PrevFree() = block.PrevFree(); - block.PrevFree() = VMA_NULL; - block.NextFree() = m_FreeList[listIndex]; - m_FreeList[listIndex] = █ - if (block.NextFree()) - block.NextFree()->PrevFree() = █ - } - - return true; -} -#endif // _VMA_BLOCK_METADATA_TLSF_FUNCTIONS -#endif // _VMA_BLOCK_METADATA_TLSF - -#ifndef _VMA_BLOCK_VECTOR -/* -Sequence of VmaDeviceMemoryBlock. Represents memory blocks allocated for a specific -Vulkan memory type. - -Synchronized internally with a mutex. -*/ -class VmaBlockVector -{ - friend struct VmaDefragmentationContext_T; - VMA_CLASS_NO_COPY(VmaBlockVector) -public: - VmaBlockVector( - VmaAllocator hAllocator, - VmaPool hParentPool, - uint32_t memoryTypeIndex, - VkDeviceSize preferredBlockSize, - size_t minBlockCount, - size_t maxBlockCount, - VkDeviceSize bufferImageGranularity, - bool explicitBlockSize, - uint32_t algorithm, - float priority, - VkDeviceSize minAllocationAlignment, - void* pMemoryAllocateNext); - ~VmaBlockVector(); - - VmaAllocator GetAllocator() const { return m_hAllocator; } - VmaPool GetParentPool() const { return m_hParentPool; } - bool IsCustomPool() const { return m_hParentPool != VMA_NULL; } - uint32_t GetMemoryTypeIndex() const { return m_MemoryTypeIndex; } - VkDeviceSize GetPreferredBlockSize() const { return m_PreferredBlockSize; } - VkDeviceSize GetBufferImageGranularity() const { return m_BufferImageGranularity; } - uint32_t GetAlgorithm() const { return m_Algorithm; } - bool HasExplicitBlockSize() const { return m_ExplicitBlockSize; } - float GetPriority() const { return m_Priority; } - const void* GetAllocationNextPtr() const { return m_pMemoryAllocateNext; } - // To be used only while the m_Mutex is locked. Used during defragmentation. - size_t GetBlockCount() const { return m_Blocks.size(); } - // To be used only while the m_Mutex is locked. Used during defragmentation. - VmaDeviceMemoryBlock* GetBlock(size_t index) const { return m_Blocks[index]; } - VMA_RW_MUTEX &GetMutex() { return m_Mutex; } - - VkResult CreateMinBlocks(); - void AddStatistics(VmaStatistics& inoutStats); - void AddDetailedStatistics(VmaDetailedStatistics& inoutStats); - bool IsEmpty(); - bool IsCorruptionDetectionEnabled() const; - - VkResult Allocate( - VkDeviceSize size, - VkDeviceSize alignment, - const VmaAllocationCreateInfo& createInfo, - VmaSuballocationType suballocType, - size_t allocationCount, - VmaAllocation* pAllocations); - - void Free(const VmaAllocation hAllocation); - -#if VMA_STATS_STRING_ENABLED - void PrintDetailedMap(class VmaJsonWriter& json); -#endif - - VkResult CheckCorruption(); - -private: - const VmaAllocator m_hAllocator; - const VmaPool m_hParentPool; - const uint32_t m_MemoryTypeIndex; - const VkDeviceSize m_PreferredBlockSize; - const size_t m_MinBlockCount; - const size_t m_MaxBlockCount; - const VkDeviceSize m_BufferImageGranularity; - const bool m_ExplicitBlockSize; - const uint32_t m_Algorithm; - const float m_Priority; - const VkDeviceSize m_MinAllocationAlignment; - - void* const m_pMemoryAllocateNext; - VMA_RW_MUTEX m_Mutex; - // Incrementally sorted by sumFreeSize, ascending. - VmaVector> m_Blocks; - uint32_t m_NextBlockId; - bool m_IncrementalSort = true; - - void SetIncrementalSort(bool val) { m_IncrementalSort = val; } - - VkDeviceSize CalcMaxBlockSize() const; - // Finds and removes given block from vector. - void Remove(VmaDeviceMemoryBlock* pBlock); - // Performs single step in sorting m_Blocks. They may not be fully sorted - // after this call. - void IncrementallySortBlocks(); - void SortByFreeSize(); - - VkResult AllocatePage( - VkDeviceSize size, - VkDeviceSize alignment, - const VmaAllocationCreateInfo& createInfo, - VmaSuballocationType suballocType, - VmaAllocation* pAllocation); - - VkResult AllocateFromBlock( - VmaDeviceMemoryBlock* pBlock, - VkDeviceSize size, - VkDeviceSize alignment, - VmaAllocationCreateFlags allocFlags, - void* pUserData, - VmaSuballocationType suballocType, - uint32_t strategy, - VmaAllocation* pAllocation); - - VkResult CommitAllocationRequest( - VmaAllocationRequest& allocRequest, - VmaDeviceMemoryBlock* pBlock, - VkDeviceSize alignment, - VmaAllocationCreateFlags allocFlags, - void* pUserData, - VmaSuballocationType suballocType, - VmaAllocation* pAllocation); - - VkResult CreateBlock(VkDeviceSize blockSize, size_t* pNewBlockIndex); - bool HasEmptyBlock(); -}; -#endif // _VMA_BLOCK_VECTOR - -#ifndef _VMA_DEFRAGMENTATION_CONTEXT -struct VmaDefragmentationContext_T -{ - VMA_CLASS_NO_COPY(VmaDefragmentationContext_T) -public: - VmaDefragmentationContext_T( - VmaAllocator hAllocator, - const VmaDefragmentationInfo& info); - ~VmaDefragmentationContext_T(); - - void GetStats(VmaDefragmentationStats& outStats) { outStats = m_GlobalStats; } - - VkResult DefragmentPassBegin(VmaDefragmentationPassMoveInfo& moveInfo); - VkResult DefragmentPassEnd(VmaDefragmentationPassMoveInfo& moveInfo); - -private: - // Max number of allocations to ignore due to size constraints before ending single pass - static const uint8_t MAX_ALLOCS_TO_IGNORE = 16; - enum class CounterStatus { Pass, Ignore, End }; - - struct FragmentedBlock - { - uint32_t data; - VmaDeviceMemoryBlock* block; - }; - struct StateBalanced - { - VkDeviceSize avgFreeSize = 0; - VkDeviceSize avgAllocSize = UINT64_MAX; - }; - struct StateExtensive - { - enum class Operation : uint8_t - { - FindFreeBlockBuffer, FindFreeBlockTexture, FindFreeBlockAll, - MoveBuffers, MoveTextures, MoveAll, - Cleanup, Done - }; - - Operation operation = Operation::FindFreeBlockTexture; - size_t firstFreeBlock = SIZE_MAX; - }; - struct MoveAllocationData - { - VkDeviceSize size; - VkDeviceSize alignment; - VmaSuballocationType type; - VmaAllocationCreateFlags flags; - VmaDefragmentationMove move = {}; - }; - - const VkDeviceSize m_MaxPassBytes; - const uint32_t m_MaxPassAllocations; - - VmaStlAllocator m_MoveAllocator; - VmaVector> m_Moves; - - uint8_t m_IgnoredAllocs = 0; - uint32_t m_Algorithm; - uint32_t m_BlockVectorCount; - VmaBlockVector* m_PoolBlockVector; - VmaBlockVector** m_pBlockVectors; - size_t m_ImmovableBlockCount = 0; - VmaDefragmentationStats m_GlobalStats = { 0 }; - VmaDefragmentationStats m_PassStats = { 0 }; - void* m_AlgorithmState = VMA_NULL; - - static MoveAllocationData GetMoveData(VmaAllocHandle handle, VmaBlockMetadata* metadata); - CounterStatus CheckCounters(VkDeviceSize bytes); - bool IncrementCounters(VkDeviceSize bytes); - bool ReallocWithinBlock(VmaBlockVector& vector, VmaDeviceMemoryBlock* block); - bool AllocInOtherBlock(size_t start, size_t end, MoveAllocationData& data, VmaBlockVector& vector); - - bool ComputeDefragmentation(VmaBlockVector& vector, size_t index); - bool ComputeDefragmentation_Fast(VmaBlockVector& vector); - bool ComputeDefragmentation_Balanced(VmaBlockVector& vector, size_t index, bool update); - bool ComputeDefragmentation_Full(VmaBlockVector& vector); - bool ComputeDefragmentation_Extensive(VmaBlockVector& vector, size_t index); - - void UpdateVectorStatistics(VmaBlockVector& vector, StateBalanced& state); - bool MoveDataToFreeBlocks(VmaSuballocationType currentType, - VmaBlockVector& vector, size_t firstFreeBlock, - bool& texturePresent, bool& bufferPresent, bool& otherPresent); -}; -#endif // _VMA_DEFRAGMENTATION_CONTEXT - -#ifndef _VMA_POOL_T -struct VmaPool_T -{ - friend struct VmaPoolListItemTraits; - VMA_CLASS_NO_COPY(VmaPool_T) -public: - VmaBlockVector m_BlockVector; - VmaDedicatedAllocationList m_DedicatedAllocations; - - VmaPool_T( - VmaAllocator hAllocator, - const VmaPoolCreateInfo& createInfo, - VkDeviceSize preferredBlockSize); - ~VmaPool_T(); - - uint32_t GetId() const { return m_Id; } - void SetId(uint32_t id) { VMA_ASSERT(m_Id == 0); m_Id = id; } - - const char* GetName() const { return m_Name; } - void SetName(const char* pName); - -#if VMA_STATS_STRING_ENABLED - //void PrintDetailedMap(class VmaStringBuilder& sb); -#endif - -private: - uint32_t m_Id; - char* m_Name; - VmaPool_T* m_PrevPool = VMA_NULL; - VmaPool_T* m_NextPool = VMA_NULL; -}; - -struct VmaPoolListItemTraits -{ - typedef VmaPool_T ItemType; - - static ItemType* GetPrev(const ItemType* item) { return item->m_PrevPool; } - static ItemType* GetNext(const ItemType* item) { return item->m_NextPool; } - static ItemType*& AccessPrev(ItemType* item) { return item->m_PrevPool; } - static ItemType*& AccessNext(ItemType* item) { return item->m_NextPool; } -}; -#endif // _VMA_POOL_T - -#ifndef _VMA_CURRENT_BUDGET_DATA -struct VmaCurrentBudgetData -{ - VMA_ATOMIC_UINT32 m_BlockCount[VK_MAX_MEMORY_HEAPS]; - VMA_ATOMIC_UINT32 m_AllocationCount[VK_MAX_MEMORY_HEAPS]; - VMA_ATOMIC_UINT64 m_BlockBytes[VK_MAX_MEMORY_HEAPS]; - VMA_ATOMIC_UINT64 m_AllocationBytes[VK_MAX_MEMORY_HEAPS]; - -#if VMA_MEMORY_BUDGET - VMA_ATOMIC_UINT32 m_OperationsSinceBudgetFetch; - VMA_RW_MUTEX m_BudgetMutex; - uint64_t m_VulkanUsage[VK_MAX_MEMORY_HEAPS]; - uint64_t m_VulkanBudget[VK_MAX_MEMORY_HEAPS]; - uint64_t m_BlockBytesAtBudgetFetch[VK_MAX_MEMORY_HEAPS]; -#endif // VMA_MEMORY_BUDGET - - VmaCurrentBudgetData(); - - void AddAllocation(uint32_t heapIndex, VkDeviceSize allocationSize); - void RemoveAllocation(uint32_t heapIndex, VkDeviceSize allocationSize); -}; - -#ifndef _VMA_CURRENT_BUDGET_DATA_FUNCTIONS -VmaCurrentBudgetData::VmaCurrentBudgetData() -{ - for (uint32_t heapIndex = 0; heapIndex < VK_MAX_MEMORY_HEAPS; ++heapIndex) - { - m_BlockCount[heapIndex] = 0; - m_AllocationCount[heapIndex] = 0; - m_BlockBytes[heapIndex] = 0; - m_AllocationBytes[heapIndex] = 0; -#if VMA_MEMORY_BUDGET - m_VulkanUsage[heapIndex] = 0; - m_VulkanBudget[heapIndex] = 0; - m_BlockBytesAtBudgetFetch[heapIndex] = 0; -#endif - } - -#if VMA_MEMORY_BUDGET - m_OperationsSinceBudgetFetch = 0; -#endif -} - -void VmaCurrentBudgetData::AddAllocation(uint32_t heapIndex, VkDeviceSize allocationSize) -{ - m_AllocationBytes[heapIndex] += allocationSize; - ++m_AllocationCount[heapIndex]; -#if VMA_MEMORY_BUDGET - ++m_OperationsSinceBudgetFetch; -#endif -} - -void VmaCurrentBudgetData::RemoveAllocation(uint32_t heapIndex, VkDeviceSize allocationSize) -{ - VMA_ASSERT(m_AllocationBytes[heapIndex] >= allocationSize); - m_AllocationBytes[heapIndex] -= allocationSize; - VMA_ASSERT(m_AllocationCount[heapIndex] > 0); - --m_AllocationCount[heapIndex]; -#if VMA_MEMORY_BUDGET - ++m_OperationsSinceBudgetFetch; -#endif -} -#endif // _VMA_CURRENT_BUDGET_DATA_FUNCTIONS -#endif // _VMA_CURRENT_BUDGET_DATA - -#ifndef _VMA_ALLOCATION_OBJECT_ALLOCATOR -/* -Thread-safe wrapper over VmaPoolAllocator free list, for allocation of VmaAllocation_T objects. -*/ -class VmaAllocationObjectAllocator -{ - VMA_CLASS_NO_COPY(VmaAllocationObjectAllocator) -public: - VmaAllocationObjectAllocator(const VkAllocationCallbacks* pAllocationCallbacks) - : m_Allocator(pAllocationCallbacks, 1024) {} - - template VmaAllocation Allocate(Types&&... args); - void Free(VmaAllocation hAlloc); - -private: - VMA_MUTEX m_Mutex; - VmaPoolAllocator m_Allocator; -}; - -template -VmaAllocation VmaAllocationObjectAllocator::Allocate(Types&&... args) -{ - VmaMutexLock mutexLock(m_Mutex); - return m_Allocator.Alloc(std::forward(args)...); -} - -void VmaAllocationObjectAllocator::Free(VmaAllocation hAlloc) -{ - VmaMutexLock mutexLock(m_Mutex); - m_Allocator.Free(hAlloc); -} -#endif // _VMA_ALLOCATION_OBJECT_ALLOCATOR - -#ifndef _VMA_VIRTUAL_BLOCK_T -struct VmaVirtualBlock_T -{ - VMA_CLASS_NO_COPY(VmaVirtualBlock_T) -public: - const bool m_AllocationCallbacksSpecified; - const VkAllocationCallbacks m_AllocationCallbacks; - - VmaVirtualBlock_T(const VmaVirtualBlockCreateInfo& createInfo); - ~VmaVirtualBlock_T(); - - VkResult Init() { return VK_SUCCESS; } - bool IsEmpty() const { return m_Metadata->IsEmpty(); } - void Free(VmaVirtualAllocation allocation) { m_Metadata->Free((VmaAllocHandle)allocation); } - void SetAllocationUserData(VmaVirtualAllocation allocation, void* userData) { m_Metadata->SetAllocationUserData((VmaAllocHandle)allocation, userData); } - void Clear() { m_Metadata->Clear(); } - - const VkAllocationCallbacks* GetAllocationCallbacks() const; - void GetAllocationInfo(VmaVirtualAllocation allocation, VmaVirtualAllocationInfo& outInfo); - VkResult Allocate(const VmaVirtualAllocationCreateInfo& createInfo, VmaVirtualAllocation& outAllocation, - VkDeviceSize* outOffset); - void GetStatistics(VmaStatistics& outStats) const; - void CalculateDetailedStatistics(VmaDetailedStatistics& outStats) const; -#if VMA_STATS_STRING_ENABLED - void BuildStatsString(bool detailedMap, VmaStringBuilder& sb) const; -#endif - -private: - VmaBlockMetadata* m_Metadata; -}; - -#ifndef _VMA_VIRTUAL_BLOCK_T_FUNCTIONS -VmaVirtualBlock_T::VmaVirtualBlock_T(const VmaVirtualBlockCreateInfo& createInfo) - : m_AllocationCallbacksSpecified(createInfo.pAllocationCallbacks != VMA_NULL), - m_AllocationCallbacks(createInfo.pAllocationCallbacks != VMA_NULL ? *createInfo.pAllocationCallbacks : VmaEmptyAllocationCallbacks) -{ - const uint32_t algorithm = createInfo.flags & VMA_VIRTUAL_BLOCK_CREATE_ALGORITHM_MASK; - switch (algorithm) - { - default: - VMA_ASSERT(0); - case 0: - m_Metadata = vma_new(GetAllocationCallbacks(), VmaBlockMetadata_TLSF)(VK_NULL_HANDLE, 1, true); - break; - case VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT: - m_Metadata = vma_new(GetAllocationCallbacks(), VmaBlockMetadata_Linear)(VK_NULL_HANDLE, 1, true); - break; - } - - m_Metadata->Init(createInfo.size); -} - -VmaVirtualBlock_T::~VmaVirtualBlock_T() -{ - // Define macro VMA_DEBUG_LOG to receive the list of the unfreed allocations - if (!m_Metadata->IsEmpty()) - m_Metadata->DebugLogAllAllocations(); - // This is the most important assert in the entire library. - // Hitting it means you have some memory leak - unreleased virtual allocations. - VMA_ASSERT(m_Metadata->IsEmpty() && "Some virtual allocations were not freed before destruction of this virtual block!"); - - vma_delete(GetAllocationCallbacks(), m_Metadata); -} - -const VkAllocationCallbacks* VmaVirtualBlock_T::GetAllocationCallbacks() const -{ - return m_AllocationCallbacksSpecified ? &m_AllocationCallbacks : VMA_NULL; -} - -void VmaVirtualBlock_T::GetAllocationInfo(VmaVirtualAllocation allocation, VmaVirtualAllocationInfo& outInfo) -{ - m_Metadata->GetAllocationInfo((VmaAllocHandle)allocation, outInfo); -} - -VkResult VmaVirtualBlock_T::Allocate(const VmaVirtualAllocationCreateInfo& createInfo, VmaVirtualAllocation& outAllocation, - VkDeviceSize* outOffset) -{ - VmaAllocationRequest request = {}; - if (m_Metadata->CreateAllocationRequest( - createInfo.size, // allocSize - VMA_MAX(createInfo.alignment, (VkDeviceSize)1), // allocAlignment - (createInfo.flags & VMA_VIRTUAL_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0, // upperAddress - VMA_SUBALLOCATION_TYPE_UNKNOWN, // allocType - unimportant - createInfo.flags & VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MASK, // strategy - &request)) - { - m_Metadata->Alloc(request, - VMA_SUBALLOCATION_TYPE_UNKNOWN, // type - unimportant - createInfo.pUserData); - outAllocation = (VmaVirtualAllocation)request.allocHandle; - if(outOffset) - *outOffset = m_Metadata->GetAllocationOffset(request.allocHandle); - return VK_SUCCESS; - } - outAllocation = (VmaVirtualAllocation)VK_NULL_HANDLE; - if (outOffset) - *outOffset = UINT64_MAX; - return VK_ERROR_OUT_OF_DEVICE_MEMORY; -} - -void VmaVirtualBlock_T::GetStatistics(VmaStatistics& outStats) const -{ - VmaClearStatistics(outStats); - m_Metadata->AddStatistics(outStats); -} - -void VmaVirtualBlock_T::CalculateDetailedStatistics(VmaDetailedStatistics& outStats) const -{ - VmaClearDetailedStatistics(outStats); - m_Metadata->AddDetailedStatistics(outStats); -} - -#if VMA_STATS_STRING_ENABLED -void VmaVirtualBlock_T::BuildStatsString(bool detailedMap, VmaStringBuilder& sb) const -{ - VmaJsonWriter json(GetAllocationCallbacks(), sb); - json.BeginObject(); - - VmaDetailedStatistics stats; - CalculateDetailedStatistics(stats); - - json.WriteString("Stats"); - VmaPrintDetailedStatistics(json, stats); - - if (detailedMap) - { - json.WriteString("Details"); - json.BeginObject(); - m_Metadata->PrintDetailedMap(json); - json.EndObject(); - } - - json.EndObject(); -} -#endif // VMA_STATS_STRING_ENABLED -#endif // _VMA_VIRTUAL_BLOCK_T_FUNCTIONS -#endif // _VMA_VIRTUAL_BLOCK_T - - -// Main allocator object. -struct VmaAllocator_T -{ - VMA_CLASS_NO_COPY(VmaAllocator_T) -public: - bool m_UseMutex; - uint32_t m_VulkanApiVersion; - bool m_UseKhrDedicatedAllocation; // Can be set only if m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0). - bool m_UseKhrBindMemory2; // Can be set only if m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0). - bool m_UseExtMemoryBudget; - bool m_UseAmdDeviceCoherentMemory; - bool m_UseKhrBufferDeviceAddress; - bool m_UseExtMemoryPriority; - VkDevice m_hDevice; - VkInstance m_hInstance; - bool m_AllocationCallbacksSpecified; - VkAllocationCallbacks m_AllocationCallbacks; - VmaDeviceMemoryCallbacks m_DeviceMemoryCallbacks; - VmaAllocationObjectAllocator m_AllocationObjectAllocator; - - // Each bit (1 << i) is set if HeapSizeLimit is enabled for that heap, so cannot allocate more than the heap size. - uint32_t m_HeapSizeLimitMask; - - VkPhysicalDeviceProperties m_PhysicalDeviceProperties; - VkPhysicalDeviceMemoryProperties m_MemProps; - - // Default pools. - VmaBlockVector* m_pBlockVectors[VK_MAX_MEMORY_TYPES]; - VmaDedicatedAllocationList m_DedicatedAllocations[VK_MAX_MEMORY_TYPES]; - - VmaCurrentBudgetData m_Budget; - VMA_ATOMIC_UINT32 m_DeviceMemoryCount; // Total number of VkDeviceMemory objects. - - VmaAllocator_T(const VmaAllocatorCreateInfo* pCreateInfo); - VkResult Init(const VmaAllocatorCreateInfo* pCreateInfo); - ~VmaAllocator_T(); - - const VkAllocationCallbacks* GetAllocationCallbacks() const - { - return m_AllocationCallbacksSpecified ? &m_AllocationCallbacks : VMA_NULL; - } - const VmaVulkanFunctions& GetVulkanFunctions() const - { - return m_VulkanFunctions; - } - - VkPhysicalDevice GetPhysicalDevice() const { return m_PhysicalDevice; } - - VkDeviceSize GetBufferImageGranularity() const - { - return VMA_MAX( - static_cast(VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY), - m_PhysicalDeviceProperties.limits.bufferImageGranularity); - } - - uint32_t GetMemoryHeapCount() const { return m_MemProps.memoryHeapCount; } - uint32_t GetMemoryTypeCount() const { return m_MemProps.memoryTypeCount; } - - uint32_t MemoryTypeIndexToHeapIndex(uint32_t memTypeIndex) const - { - VMA_ASSERT(memTypeIndex < m_MemProps.memoryTypeCount); - return m_MemProps.memoryTypes[memTypeIndex].heapIndex; - } - // True when specific memory type is HOST_VISIBLE but not HOST_COHERENT. - bool IsMemoryTypeNonCoherent(uint32_t memTypeIndex) const - { - return (m_MemProps.memoryTypes[memTypeIndex].propertyFlags & (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) == - VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; - } - // Minimum alignment for all allocations in specific memory type. - VkDeviceSize GetMemoryTypeMinAlignment(uint32_t memTypeIndex) const - { - return IsMemoryTypeNonCoherent(memTypeIndex) ? - VMA_MAX((VkDeviceSize)VMA_MIN_ALIGNMENT, m_PhysicalDeviceProperties.limits.nonCoherentAtomSize) : - (VkDeviceSize)VMA_MIN_ALIGNMENT; - } - - bool IsIntegratedGpu() const - { - return m_PhysicalDeviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU; - } - - uint32_t GetGlobalMemoryTypeBits() const { return m_GlobalMemoryTypeBits; } - - void GetBufferMemoryRequirements( - VkBuffer hBuffer, - VkMemoryRequirements& memReq, - bool& requiresDedicatedAllocation, - bool& prefersDedicatedAllocation) const; - void GetImageMemoryRequirements( - VkImage hImage, - VkMemoryRequirements& memReq, - bool& requiresDedicatedAllocation, - bool& prefersDedicatedAllocation) const; - VkResult FindMemoryTypeIndex( - uint32_t memoryTypeBits, - const VmaAllocationCreateInfo* pAllocationCreateInfo, - VkFlags bufImgUsage, // VkBufferCreateInfo::usage or VkImageCreateInfo::usage. UINT32_MAX if unknown. - uint32_t* pMemoryTypeIndex) const; - - // Main allocation function. - VkResult AllocateMemory( - const VkMemoryRequirements& vkMemReq, - bool requiresDedicatedAllocation, - bool prefersDedicatedAllocation, - VkBuffer dedicatedBuffer, - VkImage dedicatedImage, - VkFlags dedicatedBufferImageUsage, // UINT32_MAX if unknown. - const VmaAllocationCreateInfo& createInfo, - VmaSuballocationType suballocType, - size_t allocationCount, - VmaAllocation* pAllocations); - - // Main deallocation function. - void FreeMemory( - size_t allocationCount, - const VmaAllocation* pAllocations); - - void CalculateStatistics(VmaTotalStatistics* pStats); - - void GetHeapBudgets( - VmaBudget* outBudgets, uint32_t firstHeap, uint32_t heapCount); - -#if VMA_STATS_STRING_ENABLED - void PrintDetailedMap(class VmaJsonWriter& json); -#endif - - void GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationInfo* pAllocationInfo); - - VkResult CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool); - void DestroyPool(VmaPool pool); - void GetPoolStatistics(VmaPool pool, VmaStatistics* pPoolStats); - void CalculatePoolStatistics(VmaPool pool, VmaDetailedStatistics* pPoolStats); - - void SetCurrentFrameIndex(uint32_t frameIndex); - uint32_t GetCurrentFrameIndex() const { return m_CurrentFrameIndex.load(); } - - VkResult CheckPoolCorruption(VmaPool hPool); - VkResult CheckCorruption(uint32_t memoryTypeBits); - - // Call to Vulkan function vkAllocateMemory with accompanying bookkeeping. - VkResult AllocateVulkanMemory(const VkMemoryAllocateInfo* pAllocateInfo, VkDeviceMemory* pMemory); - // Call to Vulkan function vkFreeMemory with accompanying bookkeeping. - void FreeVulkanMemory(uint32_t memoryType, VkDeviceSize size, VkDeviceMemory hMemory); - // Call to Vulkan function vkBindBufferMemory or vkBindBufferMemory2KHR. - VkResult BindVulkanBuffer( - VkDeviceMemory memory, - VkDeviceSize memoryOffset, - VkBuffer buffer, - const void* pNext); - // Call to Vulkan function vkBindImageMemory or vkBindImageMemory2KHR. - VkResult BindVulkanImage( - VkDeviceMemory memory, - VkDeviceSize memoryOffset, - VkImage image, - const void* pNext); - - VkResult Map(VmaAllocation hAllocation, void** ppData); - void Unmap(VmaAllocation hAllocation); - - VkResult BindBufferMemory( - VmaAllocation hAllocation, - VkDeviceSize allocationLocalOffset, - VkBuffer hBuffer, - const void* pNext); - VkResult BindImageMemory( - VmaAllocation hAllocation, - VkDeviceSize allocationLocalOffset, - VkImage hImage, - const void* pNext); - - VkResult FlushOrInvalidateAllocation( - VmaAllocation hAllocation, - VkDeviceSize offset, VkDeviceSize size, - VMA_CACHE_OPERATION op); - VkResult FlushOrInvalidateAllocations( - uint32_t allocationCount, - const VmaAllocation* allocations, - const VkDeviceSize* offsets, const VkDeviceSize* sizes, - VMA_CACHE_OPERATION op); - - void FillAllocation(const VmaAllocation hAllocation, uint8_t pattern); - - /* - Returns bit mask of memory types that can support defragmentation on GPU as - they support creation of required buffer for copy operations. - */ - uint32_t GetGpuDefragmentationMemoryTypeBits(); - -#if VMA_EXTERNAL_MEMORY - VkExternalMemoryHandleTypeFlagsKHR GetExternalMemoryHandleTypeFlags(uint32_t memTypeIndex) const - { - return m_TypeExternalMemoryHandleTypes[memTypeIndex]; - } -#endif // #if VMA_EXTERNAL_MEMORY - -private: - VkDeviceSize m_PreferredLargeHeapBlockSize; - - VkPhysicalDevice m_PhysicalDevice; - VMA_ATOMIC_UINT32 m_CurrentFrameIndex; - VMA_ATOMIC_UINT32 m_GpuDefragmentationMemoryTypeBits; // UINT32_MAX means uninitialized. -#if VMA_EXTERNAL_MEMORY - VkExternalMemoryHandleTypeFlagsKHR m_TypeExternalMemoryHandleTypes[VK_MAX_MEMORY_TYPES]; -#endif // #if VMA_EXTERNAL_MEMORY - - VMA_RW_MUTEX m_PoolsMutex; - typedef VmaIntrusiveLinkedList PoolList; - // Protected by m_PoolsMutex. - PoolList m_Pools; - uint32_t m_NextPoolId; - - VmaVulkanFunctions m_VulkanFunctions; - - // Global bit mask AND-ed with any memoryTypeBits to disallow certain memory types. - uint32_t m_GlobalMemoryTypeBits; - - void ImportVulkanFunctions(const VmaVulkanFunctions* pVulkanFunctions); - -#if VMA_STATIC_VULKAN_FUNCTIONS == 1 - void ImportVulkanFunctions_Static(); -#endif - - void ImportVulkanFunctions_Custom(const VmaVulkanFunctions* pVulkanFunctions); - -#if VMA_DYNAMIC_VULKAN_FUNCTIONS == 1 - void ImportVulkanFunctions_Dynamic(); -#endif - - void ValidateVulkanFunctions(); - - VkDeviceSize CalcPreferredBlockSize(uint32_t memTypeIndex); - - VkResult AllocateMemoryOfType( - VmaPool pool, - VkDeviceSize size, - VkDeviceSize alignment, - bool dedicatedPreferred, - VkBuffer dedicatedBuffer, - VkImage dedicatedImage, - VkFlags dedicatedBufferImageUsage, - const VmaAllocationCreateInfo& createInfo, - uint32_t memTypeIndex, - VmaSuballocationType suballocType, - VmaDedicatedAllocationList& dedicatedAllocations, - VmaBlockVector& blockVector, - size_t allocationCount, - VmaAllocation* pAllocations); - - // Helper function only to be used inside AllocateDedicatedMemory. - VkResult AllocateDedicatedMemoryPage( - VmaPool pool, - VkDeviceSize size, - VmaSuballocationType suballocType, - uint32_t memTypeIndex, - const VkMemoryAllocateInfo& allocInfo, - bool map, - bool isUserDataString, - bool isMappingAllowed, - void* pUserData, - VmaAllocation* pAllocation); - - // Allocates and registers new VkDeviceMemory specifically for dedicated allocations. - VkResult AllocateDedicatedMemory( - VmaPool pool, - VkDeviceSize size, - VmaSuballocationType suballocType, - VmaDedicatedAllocationList& dedicatedAllocations, - uint32_t memTypeIndex, - bool map, - bool isUserDataString, - bool isMappingAllowed, - bool canAliasMemory, - void* pUserData, - float priority, - VkBuffer dedicatedBuffer, - VkImage dedicatedImage, - VkFlags dedicatedBufferImageUsage, - size_t allocationCount, - VmaAllocation* pAllocations, - const void* pNextChain = nullptr); - - void FreeDedicatedMemory(const VmaAllocation allocation); - - VkResult CalcMemTypeParams( - VmaAllocationCreateInfo& outCreateInfo, - uint32_t memTypeIndex, - VkDeviceSize size, - size_t allocationCount); - VkResult CalcAllocationParams( - VmaAllocationCreateInfo& outCreateInfo, - bool dedicatedRequired, - bool dedicatedPreferred); - - /* - Calculates and returns bit mask of memory types that can support defragmentation - on GPU as they support creation of required buffer for copy operations. - */ - uint32_t CalculateGpuDefragmentationMemoryTypeBits() const; - uint32_t CalculateGlobalMemoryTypeBits() const; - - bool GetFlushOrInvalidateRange( - VmaAllocation allocation, - VkDeviceSize offset, VkDeviceSize size, - VkMappedMemoryRange& outRange) const; - -#if VMA_MEMORY_BUDGET - void UpdateVulkanBudget(); -#endif // #if VMA_MEMORY_BUDGET -}; - - -#ifndef _VMA_MEMORY_FUNCTIONS -static void* VmaMalloc(VmaAllocator hAllocator, size_t size, size_t alignment) -{ - return VmaMalloc(&hAllocator->m_AllocationCallbacks, size, alignment); -} - -static void VmaFree(VmaAllocator hAllocator, void* ptr) -{ - VmaFree(&hAllocator->m_AllocationCallbacks, ptr); -} - -template -static T* VmaAllocate(VmaAllocator hAllocator) -{ - return (T*)VmaMalloc(hAllocator, sizeof(T), VMA_ALIGN_OF(T)); -} - -template -static T* VmaAllocateArray(VmaAllocator hAllocator, size_t count) -{ - return (T*)VmaMalloc(hAllocator, sizeof(T) * count, VMA_ALIGN_OF(T)); -} - -template -static void vma_delete(VmaAllocator hAllocator, T* ptr) -{ - if(ptr != VMA_NULL) - { - ptr->~T(); - VmaFree(hAllocator, ptr); - } -} - -template -static void vma_delete_array(VmaAllocator hAllocator, T* ptr, size_t count) -{ - if(ptr != VMA_NULL) - { - for(size_t i = count; i--; ) - ptr[i].~T(); - VmaFree(hAllocator, ptr); - } -} -#endif // _VMA_MEMORY_FUNCTIONS - -#ifndef _VMA_DEVICE_MEMORY_BLOCK_FUNCTIONS -VmaDeviceMemoryBlock::VmaDeviceMemoryBlock(VmaAllocator hAllocator) - : m_pMetadata(VMA_NULL), - m_MemoryTypeIndex(UINT32_MAX), - m_Id(0), - m_hMemory(VK_NULL_HANDLE), - m_MapCount(0), - m_pMappedData(VMA_NULL) {} - -VmaDeviceMemoryBlock::~VmaDeviceMemoryBlock() -{ - VMA_ASSERT(m_MapCount == 0 && "VkDeviceMemory block is being destroyed while it is still mapped."); - VMA_ASSERT(m_hMemory == VK_NULL_HANDLE); -} - -void VmaDeviceMemoryBlock::Init( - VmaAllocator hAllocator, - VmaPool hParentPool, - uint32_t newMemoryTypeIndex, - VkDeviceMemory newMemory, - VkDeviceSize newSize, - uint32_t id, - uint32_t algorithm, - VkDeviceSize bufferImageGranularity) -{ - VMA_ASSERT(m_hMemory == VK_NULL_HANDLE); - - m_hParentPool = hParentPool; - m_MemoryTypeIndex = newMemoryTypeIndex; - m_Id = id; - m_hMemory = newMemory; - - switch (algorithm) - { - case VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT: - m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_Linear)(hAllocator->GetAllocationCallbacks(), - bufferImageGranularity, false); // isVirtual - break; - default: - VMA_ASSERT(0); - // Fall-through. - case 0: - m_pMetadata = vma_new(hAllocator, VmaBlockMetadata_TLSF)(hAllocator->GetAllocationCallbacks(), - bufferImageGranularity, false); // isVirtual - } - m_pMetadata->Init(newSize); -} - -void VmaDeviceMemoryBlock::Destroy(VmaAllocator allocator) -{ - // Define macro VMA_DEBUG_LOG to receive the list of the unfreed allocations - if (!m_pMetadata->IsEmpty()) - m_pMetadata->DebugLogAllAllocations(); - // This is the most important assert in the entire library. - // Hitting it means you have some memory leak - unreleased VmaAllocation objects. - VMA_ASSERT(m_pMetadata->IsEmpty() && "Some allocations were not freed before destruction of this memory block!"); - - VMA_ASSERT(m_hMemory != VK_NULL_HANDLE); - allocator->FreeVulkanMemory(m_MemoryTypeIndex, m_pMetadata->GetSize(), m_hMemory); - m_hMemory = VK_NULL_HANDLE; - - vma_delete(allocator, m_pMetadata); - m_pMetadata = VMA_NULL; -} - -void VmaDeviceMemoryBlock::PostAlloc(VmaAllocator hAllocator) -{ - VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex); - m_MappingHysteresis.PostAlloc(); -} - -void VmaDeviceMemoryBlock::PostFree(VmaAllocator hAllocator) -{ - VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex); - if(m_MappingHysteresis.PostFree()) - { - VMA_ASSERT(m_MappingHysteresis.GetExtraMapping() == 0); - if (m_MapCount == 0) - { - m_pMappedData = VMA_NULL; - (*hAllocator->GetVulkanFunctions().vkUnmapMemory)(hAllocator->m_hDevice, m_hMemory); - } - } -} - -bool VmaDeviceMemoryBlock::Validate() const -{ - VMA_VALIDATE((m_hMemory != VK_NULL_HANDLE) && - (m_pMetadata->GetSize() != 0)); - - return m_pMetadata->Validate(); -} - -VkResult VmaDeviceMemoryBlock::CheckCorruption(VmaAllocator hAllocator) -{ - void* pData = nullptr; - VkResult res = Map(hAllocator, 1, &pData); - if (res != VK_SUCCESS) - { - return res; - } - - res = m_pMetadata->CheckCorruption(pData); - - Unmap(hAllocator, 1); - - return res; -} - -VkResult VmaDeviceMemoryBlock::Map(VmaAllocator hAllocator, uint32_t count, void** ppData) -{ - if (count == 0) - { - return VK_SUCCESS; - } - - VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex); - const uint32_t oldTotalMapCount = m_MapCount + m_MappingHysteresis.GetExtraMapping(); - m_MappingHysteresis.PostMap(); - if (oldTotalMapCount != 0) - { - m_MapCount += count; - VMA_ASSERT(m_pMappedData != VMA_NULL); - if (ppData != VMA_NULL) - { - *ppData = m_pMappedData; - } - return VK_SUCCESS; - } - else - { - VkResult result = (*hAllocator->GetVulkanFunctions().vkMapMemory)( - hAllocator->m_hDevice, - m_hMemory, - 0, // offset - VK_WHOLE_SIZE, - 0, // flags - &m_pMappedData); - if (result == VK_SUCCESS) - { - if (ppData != VMA_NULL) - { - *ppData = m_pMappedData; - } - m_MapCount = count; - } - return result; - } -} - -void VmaDeviceMemoryBlock::Unmap(VmaAllocator hAllocator, uint32_t count) -{ - if (count == 0) - { - return; - } - - VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex); - if (m_MapCount >= count) - { - m_MapCount -= count; - const uint32_t totalMapCount = m_MapCount + m_MappingHysteresis.GetExtraMapping(); - if (totalMapCount == 0) - { - m_pMappedData = VMA_NULL; - (*hAllocator->GetVulkanFunctions().vkUnmapMemory)(hAllocator->m_hDevice, m_hMemory); - } - m_MappingHysteresis.PostUnmap(); - } - else - { - VMA_ASSERT(0 && "VkDeviceMemory block is being unmapped while it was not previously mapped."); - } -} - -VkResult VmaDeviceMemoryBlock::WriteMagicValueAfterAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize) -{ - VMA_ASSERT(VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_MARGIN % 4 == 0 && VMA_DEBUG_DETECT_CORRUPTION); - - void* pData; - VkResult res = Map(hAllocator, 1, &pData); - if (res != VK_SUCCESS) - { - return res; - } - - VmaWriteMagicValue(pData, allocOffset + allocSize); - - Unmap(hAllocator, 1); - return VK_SUCCESS; -} - -VkResult VmaDeviceMemoryBlock::ValidateMagicValueAfterAllocation(VmaAllocator hAllocator, VkDeviceSize allocOffset, VkDeviceSize allocSize) -{ - VMA_ASSERT(VMA_DEBUG_MARGIN > 0 && VMA_DEBUG_MARGIN % 4 == 0 && VMA_DEBUG_DETECT_CORRUPTION); - - void* pData; - VkResult res = Map(hAllocator, 1, &pData); - if (res != VK_SUCCESS) - { - return res; - } - - if (!VmaValidateMagicValue(pData, allocOffset + allocSize)) - { - VMA_ASSERT(0 && "MEMORY CORRUPTION DETECTED AFTER FREED ALLOCATION!"); - } - - Unmap(hAllocator, 1); - return VK_SUCCESS; -} - -VkResult VmaDeviceMemoryBlock::BindBufferMemory( - const VmaAllocator hAllocator, - const VmaAllocation hAllocation, - VkDeviceSize allocationLocalOffset, - VkBuffer hBuffer, - const void* pNext) -{ - VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK && - hAllocation->GetBlock() == this); - VMA_ASSERT(allocationLocalOffset < hAllocation->GetSize() && - "Invalid allocationLocalOffset. Did you forget that this offset is relative to the beginning of the allocation, not the whole memory block?"); - const VkDeviceSize memoryOffset = hAllocation->GetOffset() + allocationLocalOffset; - // This lock is important so that we don't call vkBind... and/or vkMap... simultaneously on the same VkDeviceMemory from multiple threads. - VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex); - return hAllocator->BindVulkanBuffer(m_hMemory, memoryOffset, hBuffer, pNext); -} - -VkResult VmaDeviceMemoryBlock::BindImageMemory( - const VmaAllocator hAllocator, - const VmaAllocation hAllocation, - VkDeviceSize allocationLocalOffset, - VkImage hImage, - const void* pNext) -{ - VMA_ASSERT(hAllocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_BLOCK && - hAllocation->GetBlock() == this); - VMA_ASSERT(allocationLocalOffset < hAllocation->GetSize() && - "Invalid allocationLocalOffset. Did you forget that this offset is relative to the beginning of the allocation, not the whole memory block?"); - const VkDeviceSize memoryOffset = hAllocation->GetOffset() + allocationLocalOffset; - // This lock is important so that we don't call vkBind... and/or vkMap... simultaneously on the same VkDeviceMemory from multiple threads. - VmaMutexLock lock(m_MapAndBindMutex, hAllocator->m_UseMutex); - return hAllocator->BindVulkanImage(m_hMemory, memoryOffset, hImage, pNext); -} -#endif // _VMA_DEVICE_MEMORY_BLOCK_FUNCTIONS - -#ifndef _VMA_ALLOCATION_T_FUNCTIONS -VmaAllocation_T::VmaAllocation_T(bool mappingAllowed) - : m_Alignment{ 1 }, - m_Size{ 0 }, - m_pUserData{ VMA_NULL }, - m_pName{ VMA_NULL }, - m_MemoryTypeIndex{ 0 }, - m_Type{ (uint8_t)ALLOCATION_TYPE_NONE }, - m_SuballocationType{ (uint8_t)VMA_SUBALLOCATION_TYPE_UNKNOWN }, - m_MapCount{ 0 }, - m_Flags{ 0 } -{ - if(mappingAllowed) - m_Flags |= (uint8_t)FLAG_MAPPING_ALLOWED; - -#if VMA_STATS_STRING_ENABLED - m_BufferImageUsage = 0; -#endif -} - -VmaAllocation_T::~VmaAllocation_T() -{ - VMA_ASSERT(m_MapCount == 0 && "Allocation was not unmapped before destruction."); - - // Check if owned string was freed. - VMA_ASSERT(m_pName == VMA_NULL); -} - -void VmaAllocation_T::InitBlockAllocation( - VmaDeviceMemoryBlock* block, - VmaAllocHandle allocHandle, - VkDeviceSize alignment, - VkDeviceSize size, - uint32_t memoryTypeIndex, - VmaSuballocationType suballocationType, - bool mapped) -{ - VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE); - VMA_ASSERT(block != VMA_NULL); - m_Type = (uint8_t)ALLOCATION_TYPE_BLOCK; - m_Alignment = alignment; - m_Size = size; - m_MemoryTypeIndex = memoryTypeIndex; - if(mapped) - { - VMA_ASSERT(IsMappingAllowed() && "Mapping is not allowed on this allocation! Please use one of the new VMA_ALLOCATION_CREATE_HOST_ACCESS_* flags when creating it."); - m_Flags |= (uint8_t)FLAG_PERSISTENT_MAP; - } - m_SuballocationType = (uint8_t)suballocationType; - m_BlockAllocation.m_Block = block; - m_BlockAllocation.m_AllocHandle = allocHandle; -} - -void VmaAllocation_T::InitDedicatedAllocation( - VmaPool hParentPool, - uint32_t memoryTypeIndex, - VkDeviceMemory hMemory, - VmaSuballocationType suballocationType, - void* pMappedData, - VkDeviceSize size) -{ - VMA_ASSERT(m_Type == ALLOCATION_TYPE_NONE); - VMA_ASSERT(hMemory != VK_NULL_HANDLE); - m_Type = (uint8_t)ALLOCATION_TYPE_DEDICATED; - m_Alignment = 0; - m_Size = size; - m_MemoryTypeIndex = memoryTypeIndex; - m_SuballocationType = (uint8_t)suballocationType; - if(pMappedData != VMA_NULL) - { - VMA_ASSERT(IsMappingAllowed() && "Mapping is not allowed on this allocation! Please use one of the new VMA_ALLOCATION_CREATE_HOST_ACCESS_* flags when creating it."); - m_Flags |= (uint8_t)FLAG_PERSISTENT_MAP; - } - m_DedicatedAllocation.m_hParentPool = hParentPool; - m_DedicatedAllocation.m_hMemory = hMemory; - m_DedicatedAllocation.m_pMappedData = pMappedData; - m_DedicatedAllocation.m_Prev = VMA_NULL; - m_DedicatedAllocation.m_Next = VMA_NULL; -} - -void VmaAllocation_T::SetName(VmaAllocator hAllocator, const char* pName) -{ - VMA_ASSERT(pName == VMA_NULL || pName != m_pName); - - FreeName(hAllocator); - - if (pName != VMA_NULL) - m_pName = VmaCreateStringCopy(hAllocator->GetAllocationCallbacks(), pName); -} - -uint8_t VmaAllocation_T::SwapBlockAllocation(VmaAllocator hAllocator, VmaAllocation allocation) -{ - VMA_ASSERT(allocation != VMA_NULL); - VMA_ASSERT(m_Type == ALLOCATION_TYPE_BLOCK); - VMA_ASSERT(allocation->m_Type == ALLOCATION_TYPE_BLOCK); - - if (m_MapCount != 0) - m_BlockAllocation.m_Block->Unmap(hAllocator, m_MapCount); - - m_BlockAllocation.m_Block->m_pMetadata->SetAllocationUserData(m_BlockAllocation.m_AllocHandle, allocation); - VMA_SWAP(m_BlockAllocation, allocation->m_BlockAllocation); - m_BlockAllocation.m_Block->m_pMetadata->SetAllocationUserData(m_BlockAllocation.m_AllocHandle, this); - -#if VMA_STATS_STRING_ENABLED - VMA_SWAP(m_BufferImageUsage, allocation->m_BufferImageUsage); -#endif - return m_MapCount; -} - -VmaAllocHandle VmaAllocation_T::GetAllocHandle() const -{ - switch (m_Type) - { - case ALLOCATION_TYPE_BLOCK: - return m_BlockAllocation.m_AllocHandle; - case ALLOCATION_TYPE_DEDICATED: - return VK_NULL_HANDLE; - default: - VMA_ASSERT(0); - return VK_NULL_HANDLE; - } -} - -VkDeviceSize VmaAllocation_T::GetOffset() const -{ - switch (m_Type) - { - case ALLOCATION_TYPE_BLOCK: - return m_BlockAllocation.m_Block->m_pMetadata->GetAllocationOffset(m_BlockAllocation.m_AllocHandle); - case ALLOCATION_TYPE_DEDICATED: - return 0; - default: - VMA_ASSERT(0); - return 0; - } -} - -VmaPool VmaAllocation_T::GetParentPool() const -{ - switch (m_Type) - { - case ALLOCATION_TYPE_BLOCK: - return m_BlockAllocation.m_Block->GetParentPool(); - case ALLOCATION_TYPE_DEDICATED: - return m_DedicatedAllocation.m_hParentPool; - default: - VMA_ASSERT(0); - return VK_NULL_HANDLE; - } -} - -VkDeviceMemory VmaAllocation_T::GetMemory() const -{ - switch (m_Type) - { - case ALLOCATION_TYPE_BLOCK: - return m_BlockAllocation.m_Block->GetDeviceMemory(); - case ALLOCATION_TYPE_DEDICATED: - return m_DedicatedAllocation.m_hMemory; - default: - VMA_ASSERT(0); - return VK_NULL_HANDLE; - } -} - -void* VmaAllocation_T::GetMappedData() const -{ - switch (m_Type) - { - case ALLOCATION_TYPE_BLOCK: - if (m_MapCount != 0 || IsPersistentMap()) - { - void* pBlockData = m_BlockAllocation.m_Block->GetMappedData(); - VMA_ASSERT(pBlockData != VMA_NULL); - return (char*)pBlockData + GetOffset(); - } - else - { - return VMA_NULL; - } - break; - case ALLOCATION_TYPE_DEDICATED: - VMA_ASSERT((m_DedicatedAllocation.m_pMappedData != VMA_NULL) == (m_MapCount != 0 || IsPersistentMap())); - return m_DedicatedAllocation.m_pMappedData; - default: - VMA_ASSERT(0); - return VMA_NULL; - } -} - -void VmaAllocation_T::BlockAllocMap() -{ - VMA_ASSERT(GetType() == ALLOCATION_TYPE_BLOCK); - VMA_ASSERT(IsMappingAllowed() && "Mapping is not allowed on this allocation! Please use one of the new VMA_ALLOCATION_CREATE_HOST_ACCESS_* flags when creating it."); - - if (m_MapCount < 0xFF) - { - ++m_MapCount; - } - else - { - VMA_ASSERT(0 && "Allocation mapped too many times simultaneously."); - } -} - -void VmaAllocation_T::BlockAllocUnmap() -{ - VMA_ASSERT(GetType() == ALLOCATION_TYPE_BLOCK); - - if (m_MapCount > 0) - { - --m_MapCount; - } - else - { - VMA_ASSERT(0 && "Unmapping allocation not previously mapped."); - } -} - -VkResult VmaAllocation_T::DedicatedAllocMap(VmaAllocator hAllocator, void** ppData) -{ - VMA_ASSERT(GetType() == ALLOCATION_TYPE_DEDICATED); - VMA_ASSERT(IsMappingAllowed() && "Mapping is not allowed on this allocation! Please use one of the new VMA_ALLOCATION_CREATE_HOST_ACCESS_* flags when creating it."); - - if (m_MapCount != 0 || IsPersistentMap()) - { - if (m_MapCount < 0xFF) - { - VMA_ASSERT(m_DedicatedAllocation.m_pMappedData != VMA_NULL); - *ppData = m_DedicatedAllocation.m_pMappedData; - ++m_MapCount; - return VK_SUCCESS; - } - else - { - VMA_ASSERT(0 && "Dedicated allocation mapped too many times simultaneously."); - return VK_ERROR_MEMORY_MAP_FAILED; - } - } - else - { - VkResult result = (*hAllocator->GetVulkanFunctions().vkMapMemory)( - hAllocator->m_hDevice, - m_DedicatedAllocation.m_hMemory, - 0, // offset - VK_WHOLE_SIZE, - 0, // flags - ppData); - if (result == VK_SUCCESS) - { - m_DedicatedAllocation.m_pMappedData = *ppData; - m_MapCount = 1; - } - return result; - } -} - -void VmaAllocation_T::DedicatedAllocUnmap(VmaAllocator hAllocator) -{ - VMA_ASSERT(GetType() == ALLOCATION_TYPE_DEDICATED); - - if (m_MapCount > 0) - { - --m_MapCount; - if (m_MapCount == 0 && !IsPersistentMap()) - { - m_DedicatedAllocation.m_pMappedData = VMA_NULL; - (*hAllocator->GetVulkanFunctions().vkUnmapMemory)( - hAllocator->m_hDevice, - m_DedicatedAllocation.m_hMemory); - } - } - else - { - VMA_ASSERT(0 && "Unmapping dedicated allocation not previously mapped."); - } -} - -#if VMA_STATS_STRING_ENABLED -void VmaAllocation_T::InitBufferImageUsage(uint32_t bufferImageUsage) -{ - VMA_ASSERT(m_BufferImageUsage == 0); - m_BufferImageUsage = bufferImageUsage; -} - -void VmaAllocation_T::PrintParameters(class VmaJsonWriter& json) const -{ - json.WriteString("Type"); - json.WriteString(VMA_SUBALLOCATION_TYPE_NAMES[m_SuballocationType]); - - json.WriteString("Size"); - json.WriteNumber(m_Size); - json.WriteString("Usage"); - json.WriteNumber(m_BufferImageUsage); - - if (m_pUserData != VMA_NULL) - { - json.WriteString("CustomData"); - json.BeginString(); - json.ContinueString_Pointer(m_pUserData); - json.EndString(); - } - if (m_pName != VMA_NULL) - { - json.WriteString("Name"); - json.WriteString(m_pName); - } -} -#endif // VMA_STATS_STRING_ENABLED - -void VmaAllocation_T::FreeName(VmaAllocator hAllocator) -{ - if(m_pName) - { - VmaFreeString(hAllocator->GetAllocationCallbacks(), m_pName); - m_pName = VMA_NULL; - } -} -#endif // _VMA_ALLOCATION_T_FUNCTIONS - -#ifndef _VMA_BLOCK_VECTOR_FUNCTIONS -VmaBlockVector::VmaBlockVector( - VmaAllocator hAllocator, - VmaPool hParentPool, - uint32_t memoryTypeIndex, - VkDeviceSize preferredBlockSize, - size_t minBlockCount, - size_t maxBlockCount, - VkDeviceSize bufferImageGranularity, - bool explicitBlockSize, - uint32_t algorithm, - float priority, - VkDeviceSize minAllocationAlignment, - void* pMemoryAllocateNext) - : m_hAllocator(hAllocator), - m_hParentPool(hParentPool), - m_MemoryTypeIndex(memoryTypeIndex), - m_PreferredBlockSize(preferredBlockSize), - m_MinBlockCount(minBlockCount), - m_MaxBlockCount(maxBlockCount), - m_BufferImageGranularity(bufferImageGranularity), - m_ExplicitBlockSize(explicitBlockSize), - m_Algorithm(algorithm), - m_Priority(priority), - m_MinAllocationAlignment(minAllocationAlignment), - m_pMemoryAllocateNext(pMemoryAllocateNext), - m_Blocks(VmaStlAllocator(hAllocator->GetAllocationCallbacks())), - m_NextBlockId(0) {} - -VmaBlockVector::~VmaBlockVector() -{ - for (size_t i = m_Blocks.size(); i--; ) - { - m_Blocks[i]->Destroy(m_hAllocator); - vma_delete(m_hAllocator, m_Blocks[i]); - } -} - -VkResult VmaBlockVector::CreateMinBlocks() -{ - for (size_t i = 0; i < m_MinBlockCount; ++i) - { - VkResult res = CreateBlock(m_PreferredBlockSize, VMA_NULL); - if (res != VK_SUCCESS) - { - return res; - } - } - return VK_SUCCESS; -} - -void VmaBlockVector::AddStatistics(VmaStatistics& inoutStats) -{ - VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex); - - const size_t blockCount = m_Blocks.size(); - for (uint32_t blockIndex = 0; blockIndex < blockCount; ++blockIndex) - { - const VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex]; - VMA_ASSERT(pBlock); - VMA_HEAVY_ASSERT(pBlock->Validate()); - pBlock->m_pMetadata->AddStatistics(inoutStats); - } -} - -void VmaBlockVector::AddDetailedStatistics(VmaDetailedStatistics& inoutStats) -{ - VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex); - - const size_t blockCount = m_Blocks.size(); - for (uint32_t blockIndex = 0; blockIndex < blockCount; ++blockIndex) - { - const VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex]; - VMA_ASSERT(pBlock); - VMA_HEAVY_ASSERT(pBlock->Validate()); - pBlock->m_pMetadata->AddDetailedStatistics(inoutStats); - } -} - -bool VmaBlockVector::IsEmpty() -{ - VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex); - return m_Blocks.empty(); -} - -bool VmaBlockVector::IsCorruptionDetectionEnabled() const -{ - const uint32_t requiredMemFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; - return (VMA_DEBUG_DETECT_CORRUPTION != 0) && - (VMA_DEBUG_MARGIN > 0) && - (m_Algorithm == 0 || m_Algorithm == VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT) && - (m_hAllocator->m_MemProps.memoryTypes[m_MemoryTypeIndex].propertyFlags & requiredMemFlags) == requiredMemFlags; -} - -VkResult VmaBlockVector::Allocate( - VkDeviceSize size, - VkDeviceSize alignment, - const VmaAllocationCreateInfo& createInfo, - VmaSuballocationType suballocType, - size_t allocationCount, - VmaAllocation* pAllocations) -{ - size_t allocIndex; - VkResult res = VK_SUCCESS; - - alignment = VMA_MAX(alignment, m_MinAllocationAlignment); - - if (IsCorruptionDetectionEnabled()) - { - size = VmaAlignUp(size, sizeof(VMA_CORRUPTION_DETECTION_MAGIC_VALUE)); - alignment = VmaAlignUp(alignment, sizeof(VMA_CORRUPTION_DETECTION_MAGIC_VALUE)); - } - - { - VmaMutexLockWrite lock(m_Mutex, m_hAllocator->m_UseMutex); - for (allocIndex = 0; allocIndex < allocationCount; ++allocIndex) - { - res = AllocatePage( - size, - alignment, - createInfo, - suballocType, - pAllocations + allocIndex); - if (res != VK_SUCCESS) - { - break; - } - } - } - - if (res != VK_SUCCESS) - { - // Free all already created allocations. - while (allocIndex--) - Free(pAllocations[allocIndex]); - memset(pAllocations, 0, sizeof(VmaAllocation) * allocationCount); - } - - return res; -} - -VkResult VmaBlockVector::AllocatePage( - VkDeviceSize size, - VkDeviceSize alignment, - const VmaAllocationCreateInfo& createInfo, - VmaSuballocationType suballocType, - VmaAllocation* pAllocation) -{ - const bool isUpperAddress = (createInfo.flags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0; - - VkDeviceSize freeMemory; - { - const uint32_t heapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex); - VmaBudget heapBudget = {}; - m_hAllocator->GetHeapBudgets(&heapBudget, heapIndex, 1); - freeMemory = (heapBudget.usage < heapBudget.budget) ? (heapBudget.budget - heapBudget.usage) : 0; - } - - const bool canFallbackToDedicated = !HasExplicitBlockSize() && - (createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0; - const bool canCreateNewBlock = - ((createInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0) && - (m_Blocks.size() < m_MaxBlockCount) && - (freeMemory >= size || !canFallbackToDedicated); - uint32_t strategy = createInfo.flags & VMA_ALLOCATION_CREATE_STRATEGY_MASK; - - // Upper address can only be used with linear allocator and within single memory block. - if (isUpperAddress && - (m_Algorithm != VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT || m_MaxBlockCount > 1)) - { - return VK_ERROR_FEATURE_NOT_PRESENT; - } - - // Early reject: requested allocation size is larger that maximum block size for this block vector. - if (size + VMA_DEBUG_MARGIN > m_PreferredBlockSize) - { - return VK_ERROR_OUT_OF_DEVICE_MEMORY; - } - - // 1. Search existing allocations. Try to allocate. - if (m_Algorithm == VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT) - { - // Use only last block. - if (!m_Blocks.empty()) - { - VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks.back(); - VMA_ASSERT(pCurrBlock); - VkResult res = AllocateFromBlock( - pCurrBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation); - if (res == VK_SUCCESS) - { - VMA_DEBUG_LOG(" Returned from last block #%u", pCurrBlock->GetId()); - IncrementallySortBlocks(); - return VK_SUCCESS; - } - } - } - else - { - if (strategy != VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT) // MIN_MEMORY or default - { - const bool isHostVisible = - (m_hAllocator->m_MemProps.memoryTypes[m_MemoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0; - if(isHostVisible) - { - const bool isMappingAllowed = (createInfo.flags & - (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0; - /* - For non-mappable allocations, check blocks that are not mapped first. - For mappable allocations, check blocks that are already mapped first. - This way, having many blocks, we will separate mappable and non-mappable allocations, - hopefully limiting the number of blocks that are mapped, which will help tools like RenderDoc. - */ - for(size_t mappingI = 0; mappingI < 2; ++mappingI) - { - // Forward order in m_Blocks - prefer blocks with smallest amount of free space. - for (size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex) - { - VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex]; - VMA_ASSERT(pCurrBlock); - const bool isBlockMapped = pCurrBlock->GetMappedData() != VMA_NULL; - if((mappingI == 0) == (isMappingAllowed == isBlockMapped)) - { - VkResult res = AllocateFromBlock( - pCurrBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation); - if (res == VK_SUCCESS) - { - VMA_DEBUG_LOG(" Returned from existing block #%u", pCurrBlock->GetId()); - IncrementallySortBlocks(); - return VK_SUCCESS; - } - } - } - } - } - else - { - // Forward order in m_Blocks - prefer blocks with smallest amount of free space. - for (size_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex) - { - VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex]; - VMA_ASSERT(pCurrBlock); - VkResult res = AllocateFromBlock( - pCurrBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation); - if (res == VK_SUCCESS) - { - VMA_DEBUG_LOG(" Returned from existing block #%u", pCurrBlock->GetId()); - IncrementallySortBlocks(); - return VK_SUCCESS; - } - } - } - } - else // VMA_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT - { - // Backward order in m_Blocks - prefer blocks with largest amount of free space. - for (size_t blockIndex = m_Blocks.size(); blockIndex--; ) - { - VmaDeviceMemoryBlock* const pCurrBlock = m_Blocks[blockIndex]; - VMA_ASSERT(pCurrBlock); - VkResult res = AllocateFromBlock(pCurrBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation); - if (res == VK_SUCCESS) - { - VMA_DEBUG_LOG(" Returned from existing block #%u", pCurrBlock->GetId()); - IncrementallySortBlocks(); - return VK_SUCCESS; - } - } - } - } - - // 2. Try to create new block. - if (canCreateNewBlock) - { - // Calculate optimal size for new block. - VkDeviceSize newBlockSize = m_PreferredBlockSize; - uint32_t newBlockSizeShift = 0; - const uint32_t NEW_BLOCK_SIZE_SHIFT_MAX = 3; - - if (!m_ExplicitBlockSize) - { - // Allocate 1/8, 1/4, 1/2 as first blocks. - const VkDeviceSize maxExistingBlockSize = CalcMaxBlockSize(); - for (uint32_t i = 0; i < NEW_BLOCK_SIZE_SHIFT_MAX; ++i) - { - const VkDeviceSize smallerNewBlockSize = newBlockSize / 2; - if (smallerNewBlockSize > maxExistingBlockSize && smallerNewBlockSize >= size * 2) - { - newBlockSize = smallerNewBlockSize; - ++newBlockSizeShift; - } - else - { - break; - } - } - } - - size_t newBlockIndex = 0; - VkResult res = (newBlockSize <= freeMemory || !canFallbackToDedicated) ? - CreateBlock(newBlockSize, &newBlockIndex) : VK_ERROR_OUT_OF_DEVICE_MEMORY; - // Allocation of this size failed? Try 1/2, 1/4, 1/8 of m_PreferredBlockSize. - if (!m_ExplicitBlockSize) - { - while (res < 0 && newBlockSizeShift < NEW_BLOCK_SIZE_SHIFT_MAX) - { - const VkDeviceSize smallerNewBlockSize = newBlockSize / 2; - if (smallerNewBlockSize >= size) - { - newBlockSize = smallerNewBlockSize; - ++newBlockSizeShift; - res = (newBlockSize <= freeMemory || !canFallbackToDedicated) ? - CreateBlock(newBlockSize, &newBlockIndex) : VK_ERROR_OUT_OF_DEVICE_MEMORY; - } - else - { - break; - } - } - } - - if (res == VK_SUCCESS) - { - VmaDeviceMemoryBlock* const pBlock = m_Blocks[newBlockIndex]; - VMA_ASSERT(pBlock->m_pMetadata->GetSize() >= size); - - res = AllocateFromBlock( - pBlock, size, alignment, createInfo.flags, createInfo.pUserData, suballocType, strategy, pAllocation); - if (res == VK_SUCCESS) - { - VMA_DEBUG_LOG(" Created new block #%u Size=%llu", pBlock->GetId(), newBlockSize); - IncrementallySortBlocks(); - return VK_SUCCESS; - } - else - { - // Allocation from new block failed, possibly due to VMA_DEBUG_MARGIN or alignment. - return VK_ERROR_OUT_OF_DEVICE_MEMORY; - } - } - } - - return VK_ERROR_OUT_OF_DEVICE_MEMORY; -} - -void VmaBlockVector::Free(const VmaAllocation hAllocation) -{ - VmaDeviceMemoryBlock* pBlockToDelete = VMA_NULL; - - bool budgetExceeded = false; - { - const uint32_t heapIndex = m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex); - VmaBudget heapBudget = {}; - m_hAllocator->GetHeapBudgets(&heapBudget, heapIndex, 1); - budgetExceeded = heapBudget.usage >= heapBudget.budget; - } - - // Scope for lock. - { - VmaMutexLockWrite lock(m_Mutex, m_hAllocator->m_UseMutex); - - VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock(); - - if (IsCorruptionDetectionEnabled()) - { - VkResult res = pBlock->ValidateMagicValueAfterAllocation(m_hAllocator, hAllocation->GetOffset(), hAllocation->GetSize()); - VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to validate magic value."); - } - - if (hAllocation->IsPersistentMap()) - { - pBlock->Unmap(m_hAllocator, 1); - } - - const bool hadEmptyBlockBeforeFree = HasEmptyBlock(); - pBlock->m_pMetadata->Free(hAllocation->GetAllocHandle()); - pBlock->PostFree(m_hAllocator); - VMA_HEAVY_ASSERT(pBlock->Validate()); - - VMA_DEBUG_LOG(" Freed from MemoryTypeIndex=%u", m_MemoryTypeIndex); - - const bool canDeleteBlock = m_Blocks.size() > m_MinBlockCount; - // pBlock became empty after this deallocation. - if (pBlock->m_pMetadata->IsEmpty()) - { - // Already had empty block. We don't want to have two, so delete this one. - if ((hadEmptyBlockBeforeFree || budgetExceeded) && canDeleteBlock) - { - pBlockToDelete = pBlock; - Remove(pBlock); - } - // else: We now have one empty block - leave it. A hysteresis to avoid allocating whole block back and forth. - } - // pBlock didn't become empty, but we have another empty block - find and free that one. - // (This is optional, heuristics.) - else if (hadEmptyBlockBeforeFree && canDeleteBlock) - { - VmaDeviceMemoryBlock* pLastBlock = m_Blocks.back(); - if (pLastBlock->m_pMetadata->IsEmpty()) - { - pBlockToDelete = pLastBlock; - m_Blocks.pop_back(); - } - } - - IncrementallySortBlocks(); - } - - // Destruction of a free block. Deferred until this point, outside of mutex - // lock, for performance reason. - if (pBlockToDelete != VMA_NULL) - { - VMA_DEBUG_LOG(" Deleted empty block #%u", pBlockToDelete->GetId()); - pBlockToDelete->Destroy(m_hAllocator); - vma_delete(m_hAllocator, pBlockToDelete); - } - - m_hAllocator->m_Budget.RemoveAllocation(m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex), hAllocation->GetSize()); - m_hAllocator->m_AllocationObjectAllocator.Free(hAllocation); -} - -VkDeviceSize VmaBlockVector::CalcMaxBlockSize() const -{ - VkDeviceSize result = 0; - for (size_t i = m_Blocks.size(); i--; ) - { - result = VMA_MAX(result, m_Blocks[i]->m_pMetadata->GetSize()); - if (result >= m_PreferredBlockSize) - { - break; - } - } - return result; -} - -void VmaBlockVector::Remove(VmaDeviceMemoryBlock* pBlock) -{ - for (uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex) - { - if (m_Blocks[blockIndex] == pBlock) - { - VmaVectorRemove(m_Blocks, blockIndex); - return; - } - } - VMA_ASSERT(0); -} - -void VmaBlockVector::IncrementallySortBlocks() -{ - if (!m_IncrementalSort) - return; - if (m_Algorithm != VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT) - { - // Bubble sort only until first swap. - for (size_t i = 1; i < m_Blocks.size(); ++i) - { - if (m_Blocks[i - 1]->m_pMetadata->GetSumFreeSize() > m_Blocks[i]->m_pMetadata->GetSumFreeSize()) - { - VMA_SWAP(m_Blocks[i - 1], m_Blocks[i]); - return; - } - } - } -} - -void VmaBlockVector::SortByFreeSize() -{ - VMA_SORT(m_Blocks.begin(), m_Blocks.end(), - [](VmaDeviceMemoryBlock* b1, VmaDeviceMemoryBlock* b2) -> bool - { - return b1->m_pMetadata->GetSumFreeSize() < b2->m_pMetadata->GetSumFreeSize(); - }); -} - -VkResult VmaBlockVector::AllocateFromBlock( - VmaDeviceMemoryBlock* pBlock, - VkDeviceSize size, - VkDeviceSize alignment, - VmaAllocationCreateFlags allocFlags, - void* pUserData, - VmaSuballocationType suballocType, - uint32_t strategy, - VmaAllocation* pAllocation) -{ - const bool isUpperAddress = (allocFlags & VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT) != 0; - - VmaAllocationRequest currRequest = {}; - if (pBlock->m_pMetadata->CreateAllocationRequest( - size, - alignment, - isUpperAddress, - suballocType, - strategy, - &currRequest)) - { - return CommitAllocationRequest(currRequest, pBlock, alignment, allocFlags, pUserData, suballocType, pAllocation); - } - return VK_ERROR_OUT_OF_DEVICE_MEMORY; -} - -VkResult VmaBlockVector::CommitAllocationRequest( - VmaAllocationRequest& allocRequest, - VmaDeviceMemoryBlock* pBlock, - VkDeviceSize alignment, - VmaAllocationCreateFlags allocFlags, - void* pUserData, - VmaSuballocationType suballocType, - VmaAllocation* pAllocation) -{ - const bool mapped = (allocFlags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0; - const bool isUserDataString = (allocFlags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0; - const bool isMappingAllowed = (allocFlags & - (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0; - - pBlock->PostAlloc(m_hAllocator); - // Allocate from pCurrBlock. - if (mapped) - { - VkResult res = pBlock->Map(m_hAllocator, 1, VMA_NULL); - if (res != VK_SUCCESS) - { - return res; - } - } - - *pAllocation = m_hAllocator->m_AllocationObjectAllocator.Allocate(isMappingAllowed); - pBlock->m_pMetadata->Alloc(allocRequest, suballocType, *pAllocation); - (*pAllocation)->InitBlockAllocation( - pBlock, - allocRequest.allocHandle, - alignment, - allocRequest.size, // Not size, as actual allocation size may be larger than requested! - m_MemoryTypeIndex, - suballocType, - mapped); - VMA_HEAVY_ASSERT(pBlock->Validate()); - if (isUserDataString) - (*pAllocation)->SetName(m_hAllocator, (const char*)pUserData); - else - (*pAllocation)->SetUserData(m_hAllocator, pUserData); - m_hAllocator->m_Budget.AddAllocation(m_hAllocator->MemoryTypeIndexToHeapIndex(m_MemoryTypeIndex), allocRequest.size); - if (VMA_DEBUG_INITIALIZE_ALLOCATIONS) - { - m_hAllocator->FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED); - } - if (IsCorruptionDetectionEnabled()) - { - VkResult res = pBlock->WriteMagicValueAfterAllocation(m_hAllocator, (*pAllocation)->GetOffset(), allocRequest.size); - VMA_ASSERT(res == VK_SUCCESS && "Couldn't map block memory to write magic value."); - } - return VK_SUCCESS; -} - -VkResult VmaBlockVector::CreateBlock(VkDeviceSize blockSize, size_t* pNewBlockIndex) -{ - VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO }; - allocInfo.pNext = m_pMemoryAllocateNext; - allocInfo.memoryTypeIndex = m_MemoryTypeIndex; - allocInfo.allocationSize = blockSize; - -#if VMA_BUFFER_DEVICE_ADDRESS - // Every standalone block can potentially contain a buffer with VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT - always enable the feature. - VkMemoryAllocateFlagsInfoKHR allocFlagsInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO_KHR }; - if (m_hAllocator->m_UseKhrBufferDeviceAddress) - { - allocFlagsInfo.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR; - VmaPnextChainPushFront(&allocInfo, &allocFlagsInfo); - } -#endif // VMA_BUFFER_DEVICE_ADDRESS - -#if VMA_MEMORY_PRIORITY - VkMemoryPriorityAllocateInfoEXT priorityInfo = { VK_STRUCTURE_TYPE_MEMORY_PRIORITY_ALLOCATE_INFO_EXT }; - if (m_hAllocator->m_UseExtMemoryPriority) - { - VMA_ASSERT(m_Priority >= 0.f && m_Priority <= 1.f); - priorityInfo.priority = m_Priority; - VmaPnextChainPushFront(&allocInfo, &priorityInfo); - } -#endif // VMA_MEMORY_PRIORITY - -#if VMA_EXTERNAL_MEMORY - // Attach VkExportMemoryAllocateInfoKHR if necessary. - VkExportMemoryAllocateInfoKHR exportMemoryAllocInfo = { VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR }; - exportMemoryAllocInfo.handleTypes = m_hAllocator->GetExternalMemoryHandleTypeFlags(m_MemoryTypeIndex); - if (exportMemoryAllocInfo.handleTypes != 0) - { - VmaPnextChainPushFront(&allocInfo, &exportMemoryAllocInfo); - } -#endif // VMA_EXTERNAL_MEMORY - - VkDeviceMemory mem = VK_NULL_HANDLE; - VkResult res = m_hAllocator->AllocateVulkanMemory(&allocInfo, &mem); - if (res < 0) - { - return res; - } - - // New VkDeviceMemory successfully created. - - // Create new Allocation for it. - VmaDeviceMemoryBlock* const pBlock = vma_new(m_hAllocator, VmaDeviceMemoryBlock)(m_hAllocator); - pBlock->Init( - m_hAllocator, - m_hParentPool, - m_MemoryTypeIndex, - mem, - allocInfo.allocationSize, - m_NextBlockId++, - m_Algorithm, - m_BufferImageGranularity); - - m_Blocks.push_back(pBlock); - if (pNewBlockIndex != VMA_NULL) - { - *pNewBlockIndex = m_Blocks.size() - 1; - } - - return VK_SUCCESS; -} - -bool VmaBlockVector::HasEmptyBlock() -{ - for (size_t index = 0, count = m_Blocks.size(); index < count; ++index) - { - VmaDeviceMemoryBlock* const pBlock = m_Blocks[index]; - if (pBlock->m_pMetadata->IsEmpty()) - { - return true; - } - } - return false; -} - -#if VMA_STATS_STRING_ENABLED -void VmaBlockVector::PrintDetailedMap(class VmaJsonWriter& json) -{ - VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex); - - - json.BeginObject(); - for (size_t i = 0; i < m_Blocks.size(); ++i) - { - json.BeginString(); - json.ContinueString(m_Blocks[i]->GetId()); - json.EndString(); - - json.BeginObject(); - json.WriteString("MapRefCount"); - json.WriteNumber(m_Blocks[i]->GetMapRefCount()); - - m_Blocks[i]->m_pMetadata->PrintDetailedMap(json); - json.EndObject(); - } - json.EndObject(); -} -#endif // VMA_STATS_STRING_ENABLED - -VkResult VmaBlockVector::CheckCorruption() -{ - if (!IsCorruptionDetectionEnabled()) - { - return VK_ERROR_FEATURE_NOT_PRESENT; - } - - VmaMutexLockRead lock(m_Mutex, m_hAllocator->m_UseMutex); - for (uint32_t blockIndex = 0; blockIndex < m_Blocks.size(); ++blockIndex) - { - VmaDeviceMemoryBlock* const pBlock = m_Blocks[blockIndex]; - VMA_ASSERT(pBlock); - VkResult res = pBlock->CheckCorruption(m_hAllocator); - if (res != VK_SUCCESS) - { - return res; - } - } - return VK_SUCCESS; -} - -#endif // _VMA_BLOCK_VECTOR_FUNCTIONS - -#ifndef _VMA_DEFRAGMENTATION_CONTEXT_FUNCTIONS -VmaDefragmentationContext_T::VmaDefragmentationContext_T( - VmaAllocator hAllocator, - const VmaDefragmentationInfo& info) - : m_MaxPassBytes(info.maxBytesPerPass == 0 ? VK_WHOLE_SIZE : info.maxBytesPerPass), - m_MaxPassAllocations(info.maxAllocationsPerPass == 0 ? UINT32_MAX : info.maxAllocationsPerPass), - m_MoveAllocator(hAllocator->GetAllocationCallbacks()), - m_Moves(m_MoveAllocator) -{ - m_Algorithm = info.flags & VMA_DEFRAGMENTATION_FLAG_ALGORITHM_MASK; - - if (info.pool != VMA_NULL) - { - m_BlockVectorCount = 1; - m_PoolBlockVector = &info.pool->m_BlockVector; - m_pBlockVectors = &m_PoolBlockVector; - m_PoolBlockVector->SetIncrementalSort(false); - m_PoolBlockVector->SortByFreeSize(); - } - else - { - m_BlockVectorCount = hAllocator->GetMemoryTypeCount(); - m_PoolBlockVector = VMA_NULL; - m_pBlockVectors = hAllocator->m_pBlockVectors; - for (uint32_t i = 0; i < m_BlockVectorCount; ++i) - { - VmaBlockVector* vector = m_pBlockVectors[i]; - if (vector != VMA_NULL) - { - vector->SetIncrementalSort(false); - vector->SortByFreeSize(); - } - } - } - - switch (m_Algorithm) - { - case 0: // Default algorithm - m_Algorithm = VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT; - case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT: - { - m_AlgorithmState = vma_new_array(hAllocator, StateBalanced, m_BlockVectorCount); - break; - } - case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT: - { - if (hAllocator->GetBufferImageGranularity() > 1) - { - m_AlgorithmState = vma_new_array(hAllocator, StateExtensive, m_BlockVectorCount); - } - break; - } - } -} - -VmaDefragmentationContext_T::~VmaDefragmentationContext_T() -{ - if (m_PoolBlockVector != VMA_NULL) - { - m_PoolBlockVector->SetIncrementalSort(true); - } - else - { - for (uint32_t i = 0; i < m_BlockVectorCount; ++i) - { - VmaBlockVector* vector = m_pBlockVectors[i]; - if (vector != VMA_NULL) - vector->SetIncrementalSort(true); - } - } - - if (m_AlgorithmState) - { - switch (m_Algorithm) - { - case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT: - vma_delete_array(m_MoveAllocator.m_pCallbacks, reinterpret_cast(m_AlgorithmState), m_BlockVectorCount); - break; - case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT: - vma_delete_array(m_MoveAllocator.m_pCallbacks, reinterpret_cast(m_AlgorithmState), m_BlockVectorCount); - break; - default: - VMA_ASSERT(0); - } - } -} - -VkResult VmaDefragmentationContext_T::DefragmentPassBegin(VmaDefragmentationPassMoveInfo& moveInfo) -{ - if (m_PoolBlockVector != VMA_NULL) - { - VmaMutexLockWrite lock(m_PoolBlockVector->GetMutex(), m_PoolBlockVector->GetAllocator()->m_UseMutex); - - if (m_PoolBlockVector->GetBlockCount() > 1) - ComputeDefragmentation(*m_PoolBlockVector, 0); - else if (m_PoolBlockVector->GetBlockCount() == 1) - ReallocWithinBlock(*m_PoolBlockVector, m_PoolBlockVector->GetBlock(0)); - } - else - { - for (uint32_t i = 0; i < m_BlockVectorCount; ++i) - { - if (m_pBlockVectors[i] != VMA_NULL) - { - VmaMutexLockWrite lock(m_pBlockVectors[i]->GetMutex(), m_pBlockVectors[i]->GetAllocator()->m_UseMutex); - - if (m_pBlockVectors[i]->GetBlockCount() > 1) - { - if (ComputeDefragmentation(*m_pBlockVectors[i], i)) - break; - } - else if (m_pBlockVectors[i]->GetBlockCount() == 1) - { - if (ReallocWithinBlock(*m_pBlockVectors[i], m_pBlockVectors[i]->GetBlock(0))) - break; - } - } - } - } - - moveInfo.moveCount = static_cast(m_Moves.size()); - if (moveInfo.moveCount > 0) - { - moveInfo.pMoves = m_Moves.data(); - return VK_INCOMPLETE; - } - - moveInfo.pMoves = VMA_NULL; - return VK_SUCCESS; -} - -VkResult VmaDefragmentationContext_T::DefragmentPassEnd(VmaDefragmentationPassMoveInfo& moveInfo) -{ - VMA_ASSERT(moveInfo.moveCount > 0 ? moveInfo.pMoves != VMA_NULL : true); - - VkResult result = VK_SUCCESS; - VmaStlAllocator blockAllocator(m_MoveAllocator.m_pCallbacks); - VmaVector> immovableBlocks(blockAllocator); - VmaVector> mappedBlocks(blockAllocator); - - VmaAllocator allocator = VMA_NULL; - for (uint32_t i = 0; i < moveInfo.moveCount; ++i) - { - VmaDefragmentationMove& move = moveInfo.pMoves[i]; - size_t prevCount = 0, currentCount = 0; - VkDeviceSize freedBlockSize = 0; - - uint32_t vectorIndex; - VmaBlockVector* vector; - if (m_PoolBlockVector != VMA_NULL) - { - vectorIndex = 0; - vector = m_PoolBlockVector; - } - else - { - vectorIndex = move.srcAllocation->GetMemoryTypeIndex(); - vector = m_pBlockVectors[vectorIndex]; - VMA_ASSERT(vector != VMA_NULL); - } - - switch (move.operation) - { - case VMA_DEFRAGMENTATION_MOVE_OPERATION_COPY: - { - uint8_t mapCount = move.srcAllocation->SwapBlockAllocation(vector->m_hAllocator, move.dstTmpAllocation); - if (mapCount > 0) - { - allocator = vector->m_hAllocator; - VmaDeviceMemoryBlock* newMapBlock = move.srcAllocation->GetBlock(); - bool notPresent = true; - for (FragmentedBlock& block : mappedBlocks) - { - if (block.block == newMapBlock) - { - notPresent = false; - block.data += mapCount; - break; - } - } - if (notPresent) - mappedBlocks.push_back({ mapCount, newMapBlock }); - } - - // Scope for locks, Free have it's own lock - { - VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex); - prevCount = vector->GetBlockCount(); - freedBlockSize = move.dstTmpAllocation->GetBlock()->m_pMetadata->GetSize(); - } - vector->Free(move.dstTmpAllocation); - { - VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex); - currentCount = vector->GetBlockCount(); - } - - result = VK_INCOMPLETE; - break; - } - case VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE: - { - m_PassStats.bytesMoved -= move.srcAllocation->GetSize(); - --m_PassStats.allocationsMoved; - vector->Free(move.dstTmpAllocation); - - VmaDeviceMemoryBlock* newBlock = move.srcAllocation->GetBlock(); - bool notPresent = true; - for (const FragmentedBlock& block : immovableBlocks) - { - if (block.block == newBlock) - { - notPresent = false; - break; - } - } - if (notPresent) - immovableBlocks.push_back({ vectorIndex, newBlock }); - break; - } - case VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY: - { - m_PassStats.bytesMoved -= move.srcAllocation->GetSize(); - --m_PassStats.allocationsMoved; - // Scope for locks, Free have it's own lock - { - VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex); - prevCount = vector->GetBlockCount(); - freedBlockSize = move.srcAllocation->GetBlock()->m_pMetadata->GetSize(); - } - vector->Free(move.srcAllocation); - { - VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex); - currentCount = vector->GetBlockCount(); - } - freedBlockSize *= prevCount - currentCount; - - VkDeviceSize dstBlockSize; - { - VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex); - dstBlockSize = move.dstTmpAllocation->GetBlock()->m_pMetadata->GetSize(); - } - vector->Free(move.dstTmpAllocation); - { - VmaMutexLockRead lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex); - freedBlockSize += dstBlockSize * (currentCount - vector->GetBlockCount()); - currentCount = vector->GetBlockCount(); - } - - result = VK_INCOMPLETE; - break; - } - default: - VMA_ASSERT(0); - } - - if (prevCount > currentCount) - { - size_t freedBlocks = prevCount - currentCount; - m_PassStats.deviceMemoryBlocksFreed += static_cast(freedBlocks); - m_PassStats.bytesFreed += freedBlockSize; - } - - switch (m_Algorithm) - { - case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT: - { - if (m_AlgorithmState != VMA_NULL) - { - // Avoid unnecessary tries to allocate when new free block is available - StateExtensive& state = reinterpret_cast(m_AlgorithmState)[vectorIndex]; - if (state.firstFreeBlock != SIZE_MAX) - { - const size_t diff = prevCount - currentCount; - if (state.firstFreeBlock >= diff) - { - state.firstFreeBlock -= diff; - if (state.firstFreeBlock != 0) - state.firstFreeBlock -= vector->GetBlock(state.firstFreeBlock - 1)->m_pMetadata->IsEmpty(); - } - else - state.firstFreeBlock = 0; - } - } - } - } - } - moveInfo.moveCount = 0; - moveInfo.pMoves = VMA_NULL; - m_Moves.clear(); - - // Update stats - m_GlobalStats.allocationsMoved += m_PassStats.allocationsMoved; - m_GlobalStats.bytesFreed += m_PassStats.bytesFreed; - m_GlobalStats.bytesMoved += m_PassStats.bytesMoved; - m_GlobalStats.deviceMemoryBlocksFreed += m_PassStats.deviceMemoryBlocksFreed; - m_PassStats = { 0 }; - - // Move blocks with immovable allocations according to algorithm - if (immovableBlocks.size() > 0) - { - switch (m_Algorithm) - { - case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT: - { - if (m_AlgorithmState != VMA_NULL) - { - bool swapped = false; - // Move to the start of free blocks range - for (const FragmentedBlock& block : immovableBlocks) - { - StateExtensive& state = reinterpret_cast(m_AlgorithmState)[block.data]; - if (state.operation != StateExtensive::Operation::Cleanup) - { - VmaBlockVector* vector = m_pBlockVectors[block.data]; - VmaMutexLockWrite lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex); - - for (size_t i = 0, count = vector->GetBlockCount() - m_ImmovableBlockCount; i < count; ++i) - { - if (vector->GetBlock(i) == block.block) - { - VMA_SWAP(vector->m_Blocks[i], vector->m_Blocks[vector->GetBlockCount() - ++m_ImmovableBlockCount]); - if (state.firstFreeBlock != SIZE_MAX) - { - if (i + 1 < state.firstFreeBlock) - { - if (state.firstFreeBlock > 1) - VMA_SWAP(vector->m_Blocks[i], vector->m_Blocks[--state.firstFreeBlock]); - else - --state.firstFreeBlock; - } - } - swapped = true; - break; - } - } - } - } - if (swapped) - result = VK_INCOMPLETE; - break; - } - } - default: - { - // Move to the beginning - for (const FragmentedBlock& block : immovableBlocks) - { - VmaBlockVector* vector = m_pBlockVectors[block.data]; - VmaMutexLockWrite lock(vector->GetMutex(), vector->GetAllocator()->m_UseMutex); - - for (size_t i = m_ImmovableBlockCount; i < vector->GetBlockCount(); ++i) - { - if (vector->GetBlock(i) == block.block) - { - VMA_SWAP(vector->m_Blocks[i], vector->m_Blocks[m_ImmovableBlockCount++]); - break; - } - } - } - break; - } - } - } - - // Bulk-map destination blocks - for (const FragmentedBlock& block : mappedBlocks) - { - VkResult res = block.block->Map(allocator, block.data, VMA_NULL); - VMA_ASSERT(res == VK_SUCCESS); - } - return result; -} - -bool VmaDefragmentationContext_T::ComputeDefragmentation(VmaBlockVector& vector, size_t index) -{ - switch (m_Algorithm) - { - case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FAST_BIT: - return ComputeDefragmentation_Fast(vector); - default: - VMA_ASSERT(0); - case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_BALANCED_BIT: - return ComputeDefragmentation_Balanced(vector, index, true); - case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FULL_BIT: - return ComputeDefragmentation_Full(vector); - case VMA_DEFRAGMENTATION_FLAG_ALGORITHM_EXTENSIVE_BIT: - return ComputeDefragmentation_Extensive(vector, index); - } -} - -VmaDefragmentationContext_T::MoveAllocationData VmaDefragmentationContext_T::GetMoveData( - VmaAllocHandle handle, VmaBlockMetadata* metadata) -{ - MoveAllocationData moveData; - moveData.move.srcAllocation = (VmaAllocation)metadata->GetAllocationUserData(handle); - moveData.size = moveData.move.srcAllocation->GetSize(); - moveData.alignment = moveData.move.srcAllocation->GetAlignment(); - moveData.type = moveData.move.srcAllocation->GetSuballocationType(); - moveData.flags = 0; - - if (moveData.move.srcAllocation->IsPersistentMap()) - moveData.flags |= VMA_ALLOCATION_CREATE_MAPPED_BIT; - if (moveData.move.srcAllocation->IsMappingAllowed()) - moveData.flags |= VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT; - - return moveData; -} - -VmaDefragmentationContext_T::CounterStatus VmaDefragmentationContext_T::CheckCounters(VkDeviceSize bytes) -{ - // Ignore allocation if will exceed max size for copy - if (m_PassStats.bytesMoved + bytes > m_MaxPassBytes) - { - if (++m_IgnoredAllocs < MAX_ALLOCS_TO_IGNORE) - return CounterStatus::Ignore; - else - return CounterStatus::End; - } - return CounterStatus::Pass; -} - -bool VmaDefragmentationContext_T::IncrementCounters(VkDeviceSize bytes) -{ - m_PassStats.bytesMoved += bytes; - // Early return when max found - if (++m_PassStats.allocationsMoved >= m_MaxPassAllocations || m_PassStats.bytesMoved >= m_MaxPassBytes) - { - VMA_ASSERT(m_PassStats.allocationsMoved == m_MaxPassAllocations || - m_PassStats.bytesMoved == m_MaxPassBytes && "Exceeded maximal pass threshold!"); - return true; - } - return false; -} - -bool VmaDefragmentationContext_T::ReallocWithinBlock(VmaBlockVector& vector, VmaDeviceMemoryBlock* block) -{ - VmaBlockMetadata* metadata = block->m_pMetadata; - - for (VmaAllocHandle handle = metadata->GetAllocationListBegin(); - handle != VK_NULL_HANDLE; - handle = metadata->GetNextAllocation(handle)) - { - MoveAllocationData moveData = GetMoveData(handle, metadata); - // Ignore newly created allocations by defragmentation algorithm - if (moveData.move.srcAllocation->GetUserData() == this) - continue; - switch (CheckCounters(moveData.move.srcAllocation->GetSize())) - { - case CounterStatus::Ignore: - continue; - case CounterStatus::End: - return true; - default: - VMA_ASSERT(0); - case CounterStatus::Pass: - break; - } - - VkDeviceSize offset = moveData.move.srcAllocation->GetOffset(); - if (offset != 0 && metadata->GetSumFreeSize() >= moveData.size) - { - VmaAllocationRequest request = {}; - if (metadata->CreateAllocationRequest( - moveData.size, - moveData.alignment, - false, - moveData.type, - VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT, - &request)) - { - if (metadata->GetAllocationOffset(request.allocHandle) < offset) - { - if (vector.CommitAllocationRequest( - request, - block, - moveData.alignment, - moveData.flags, - this, - moveData.type, - &moveData.move.dstTmpAllocation) == VK_SUCCESS) - { - m_Moves.push_back(moveData.move); - if (IncrementCounters(moveData.size)) - return true; - } - } - } - } - } - return false; -} - -bool VmaDefragmentationContext_T::AllocInOtherBlock(size_t start, size_t end, MoveAllocationData& data, VmaBlockVector& vector) -{ - for (; start < end; ++start) - { - VmaDeviceMemoryBlock* dstBlock = vector.GetBlock(start); - if (dstBlock->m_pMetadata->GetSumFreeSize() >= data.size) - { - if (vector.AllocateFromBlock(dstBlock, - data.size, - data.alignment, - data.flags, - this, - data.type, - 0, - &data.move.dstTmpAllocation) == VK_SUCCESS) - { - m_Moves.push_back(data.move); - if (IncrementCounters(data.size)) - return true; - break; - } - } - } - return false; -} - -bool VmaDefragmentationContext_T::ComputeDefragmentation_Fast(VmaBlockVector& vector) -{ - // Move only between blocks - - // Go through allocations in last blocks and try to fit them inside first ones - for (size_t i = vector.GetBlockCount() - 1; i > m_ImmovableBlockCount; --i) - { - VmaBlockMetadata* metadata = vector.GetBlock(i)->m_pMetadata; - - for (VmaAllocHandle handle = metadata->GetAllocationListBegin(); - handle != VK_NULL_HANDLE; - handle = metadata->GetNextAllocation(handle)) - { - MoveAllocationData moveData = GetMoveData(handle, metadata); - // Ignore newly created allocations by defragmentation algorithm - if (moveData.move.srcAllocation->GetUserData() == this) - continue; - switch (CheckCounters(moveData.move.srcAllocation->GetSize())) - { - case CounterStatus::Ignore: - continue; - case CounterStatus::End: - return true; - default: - VMA_ASSERT(0); - case CounterStatus::Pass: - break; - } - - // Check all previous blocks for free space - if (AllocInOtherBlock(0, i, moveData, vector)) - return true; - } - } - return false; -} - -bool VmaDefragmentationContext_T::ComputeDefragmentation_Balanced(VmaBlockVector& vector, size_t index, bool update) -{ - // Go over every allocation and try to fit it in previous blocks at lowest offsets, - // if not possible: realloc within single block to minimize offset (exclude offset == 0), - // but only if there are noticeable gaps between them (some heuristic, ex. average size of allocation in block) - VMA_ASSERT(m_AlgorithmState != VMA_NULL); - - StateBalanced& vectorState = reinterpret_cast(m_AlgorithmState)[index]; - if (update && vectorState.avgAllocSize == UINT64_MAX) - UpdateVectorStatistics(vector, vectorState); - - const size_t startMoveCount = m_Moves.size(); - VkDeviceSize minimalFreeRegion = vectorState.avgFreeSize / 2; - for (size_t i = vector.GetBlockCount() - 1; i > m_ImmovableBlockCount; --i) - { - VmaDeviceMemoryBlock* block = vector.GetBlock(i); - VmaBlockMetadata* metadata = block->m_pMetadata; - VkDeviceSize prevFreeRegionSize = 0; - - for (VmaAllocHandle handle = metadata->GetAllocationListBegin(); - handle != VK_NULL_HANDLE; - handle = metadata->GetNextAllocation(handle)) - { - MoveAllocationData moveData = GetMoveData(handle, metadata); - // Ignore newly created allocations by defragmentation algorithm - if (moveData.move.srcAllocation->GetUserData() == this) - continue; - switch (CheckCounters(moveData.move.srcAllocation->GetSize())) - { - case CounterStatus::Ignore: - continue; - case CounterStatus::End: - return true; - default: - VMA_ASSERT(0); - case CounterStatus::Pass: - break; - } - - // Check all previous blocks for free space - const size_t prevMoveCount = m_Moves.size(); - if (AllocInOtherBlock(0, i, moveData, vector)) - return true; - - VkDeviceSize nextFreeRegionSize = metadata->GetNextFreeRegionSize(handle); - // If no room found then realloc within block for lower offset - VkDeviceSize offset = moveData.move.srcAllocation->GetOffset(); - if (prevMoveCount == m_Moves.size() && offset != 0 && metadata->GetSumFreeSize() >= moveData.size) - { - // Check if realloc will make sense - if (prevFreeRegionSize >= minimalFreeRegion || - nextFreeRegionSize >= minimalFreeRegion || - moveData.size <= vectorState.avgFreeSize || - moveData.size <= vectorState.avgAllocSize) - { - VmaAllocationRequest request = {}; - if (metadata->CreateAllocationRequest( - moveData.size, - moveData.alignment, - false, - moveData.type, - VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT, - &request)) - { - if (metadata->GetAllocationOffset(request.allocHandle) < offset) - { - if (vector.CommitAllocationRequest( - request, - block, - moveData.alignment, - moveData.flags, - this, - moveData.type, - &moveData.move.dstTmpAllocation) == VK_SUCCESS) - { - m_Moves.push_back(moveData.move); - if (IncrementCounters(moveData.size)) - return true; - } - } - } - } - } - prevFreeRegionSize = nextFreeRegionSize; - } - } - - // No moves performed, update statistics to current vector state - if (startMoveCount == m_Moves.size() && !update) - { - vectorState.avgAllocSize = UINT64_MAX; - return ComputeDefragmentation_Balanced(vector, index, false); - } - return false; -} - -bool VmaDefragmentationContext_T::ComputeDefragmentation_Full(VmaBlockVector& vector) -{ - // Go over every allocation and try to fit it in previous blocks at lowest offsets, - // if not possible: realloc within single block to minimize offset (exclude offset == 0) - - for (size_t i = vector.GetBlockCount() - 1; i > m_ImmovableBlockCount; --i) - { - VmaDeviceMemoryBlock* block = vector.GetBlock(i); - VmaBlockMetadata* metadata = block->m_pMetadata; - - for (VmaAllocHandle handle = metadata->GetAllocationListBegin(); - handle != VK_NULL_HANDLE; - handle = metadata->GetNextAllocation(handle)) - { - MoveAllocationData moveData = GetMoveData(handle, metadata); - // Ignore newly created allocations by defragmentation algorithm - if (moveData.move.srcAllocation->GetUserData() == this) - continue; - switch (CheckCounters(moveData.move.srcAllocation->GetSize())) - { - case CounterStatus::Ignore: - continue; - case CounterStatus::End: - return true; - default: - VMA_ASSERT(0); - case CounterStatus::Pass: - break; - } - - // Check all previous blocks for free space - const size_t prevMoveCount = m_Moves.size(); - if (AllocInOtherBlock(0, i, moveData, vector)) - return true; - - // If no room found then realloc within block for lower offset - VkDeviceSize offset = moveData.move.srcAllocation->GetOffset(); - if (prevMoveCount == m_Moves.size() && offset != 0 && metadata->GetSumFreeSize() >= moveData.size) - { - VmaAllocationRequest request = {}; - if (metadata->CreateAllocationRequest( - moveData.size, - moveData.alignment, - false, - moveData.type, - VMA_ALLOCATION_CREATE_STRATEGY_MIN_OFFSET_BIT, - &request)) - { - if (metadata->GetAllocationOffset(request.allocHandle) < offset) - { - if (vector.CommitAllocationRequest( - request, - block, - moveData.alignment, - moveData.flags, - this, - moveData.type, - &moveData.move.dstTmpAllocation) == VK_SUCCESS) - { - m_Moves.push_back(moveData.move); - if (IncrementCounters(moveData.size)) - return true; - } - } - } - } - } - } - return false; -} - -bool VmaDefragmentationContext_T::ComputeDefragmentation_Extensive(VmaBlockVector& vector, size_t index) -{ - // First free single block, then populate it to the brim, then free another block, and so on - - // Fallback to previous algorithm since without granularity conflicts it can achieve max packing - if (vector.m_BufferImageGranularity == 1) - return ComputeDefragmentation_Full(vector); - - VMA_ASSERT(m_AlgorithmState != VMA_NULL); - - StateExtensive& vectorState = reinterpret_cast(m_AlgorithmState)[index]; - - bool texturePresent = false, bufferPresent = false, otherPresent = false; - switch (vectorState.operation) - { - case StateExtensive::Operation::Done: // Vector defragmented - return false; - case StateExtensive::Operation::FindFreeBlockBuffer: - case StateExtensive::Operation::FindFreeBlockTexture: - case StateExtensive::Operation::FindFreeBlockAll: - { - // No more blocks to free, just perform fast realloc and move to cleanup - if (vectorState.firstFreeBlock == 0) - { - vectorState.operation = StateExtensive::Operation::Cleanup; - return ComputeDefragmentation_Fast(vector); - } - - // No free blocks, have to clear last one - size_t last = (vectorState.firstFreeBlock == SIZE_MAX ? vector.GetBlockCount() : vectorState.firstFreeBlock) - 1; - VmaBlockMetadata* freeMetadata = vector.GetBlock(last)->m_pMetadata; - - const size_t prevMoveCount = m_Moves.size(); - for (VmaAllocHandle handle = freeMetadata->GetAllocationListBegin(); - handle != VK_NULL_HANDLE; - handle = freeMetadata->GetNextAllocation(handle)) - { - MoveAllocationData moveData = GetMoveData(handle, freeMetadata); - switch (CheckCounters(moveData.move.srcAllocation->GetSize())) - { - case CounterStatus::Ignore: - continue; - case CounterStatus::End: - return true; - default: - VMA_ASSERT(0); - case CounterStatus::Pass: - break; - } - - // Check all previous blocks for free space - if (AllocInOtherBlock(0, last, moveData, vector)) - { - // Full clear performed already - if (prevMoveCount != m_Moves.size() && freeMetadata->GetNextAllocation(handle) == VK_NULL_HANDLE) - reinterpret_cast(m_AlgorithmState)[index] = last; - return true; - } - } - - if (prevMoveCount == m_Moves.size()) - { - // Cannot perform full clear, have to move data in other blocks around - if (last != 0) - { - for (size_t i = last - 1; i; --i) - { - if (ReallocWithinBlock(vector, vector.GetBlock(i))) - return true; - } - } - - if (prevMoveCount == m_Moves.size()) - { - // No possible reallocs within blocks, try to move them around fast - return ComputeDefragmentation_Fast(vector); - } - } - else - { - switch (vectorState.operation) - { - case StateExtensive::Operation::FindFreeBlockBuffer: - vectorState.operation = StateExtensive::Operation::MoveBuffers; - break; - default: - VMA_ASSERT(0); - case StateExtensive::Operation::FindFreeBlockTexture: - vectorState.operation = StateExtensive::Operation::MoveTextures; - break; - case StateExtensive::Operation::FindFreeBlockAll: - vectorState.operation = StateExtensive::Operation::MoveAll; - break; - } - vectorState.firstFreeBlock = last; - // Nothing done, block found without reallocations, can perform another reallocs in same pass - return ComputeDefragmentation_Extensive(vector, index); - } - break; - } - case StateExtensive::Operation::MoveTextures: - { - if (MoveDataToFreeBlocks(VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL, vector, - vectorState.firstFreeBlock, texturePresent, bufferPresent, otherPresent)) - { - if (texturePresent) - { - vectorState.operation = StateExtensive::Operation::FindFreeBlockTexture; - return ComputeDefragmentation_Extensive(vector, index); - } - - if (!bufferPresent && !otherPresent) - { - vectorState.operation = StateExtensive::Operation::Cleanup; - break; - } - - // No more textures to move, check buffers - vectorState.operation = StateExtensive::Operation::MoveBuffers; - bufferPresent = false; - otherPresent = false; - } - else - break; - } - case StateExtensive::Operation::MoveBuffers: - { - if (MoveDataToFreeBlocks(VMA_SUBALLOCATION_TYPE_BUFFER, vector, - vectorState.firstFreeBlock, texturePresent, bufferPresent, otherPresent)) - { - if (bufferPresent) - { - vectorState.operation = StateExtensive::Operation::FindFreeBlockBuffer; - return ComputeDefragmentation_Extensive(vector, index); - } - - if (!otherPresent) - { - vectorState.operation = StateExtensive::Operation::Cleanup; - break; - } - - // No more buffers to move, check all others - vectorState.operation = StateExtensive::Operation::MoveAll; - otherPresent = false; - } - else - break; - } - case StateExtensive::Operation::MoveAll: - { - if (MoveDataToFreeBlocks(VMA_SUBALLOCATION_TYPE_FREE, vector, - vectorState.firstFreeBlock, texturePresent, bufferPresent, otherPresent)) - { - if (otherPresent) - { - vectorState.operation = StateExtensive::Operation::FindFreeBlockBuffer; - return ComputeDefragmentation_Extensive(vector, index); - } - // Everything moved - vectorState.operation = StateExtensive::Operation::Cleanup; - } - break; - } - case StateExtensive::Operation::Cleanup: - // Cleanup is handled below so that other operations may reuse the cleanup code. This case is here to prevent the unhandled enum value warning (C4062). - break; - } - - if (vectorState.operation == StateExtensive::Operation::Cleanup) - { - // All other work done, pack data in blocks even tighter if possible - const size_t prevMoveCount = m_Moves.size(); - for (size_t i = 0; i < vector.GetBlockCount(); ++i) - { - if (ReallocWithinBlock(vector, vector.GetBlock(i))) - return true; - } - - if (prevMoveCount == m_Moves.size()) - vectorState.operation = StateExtensive::Operation::Done; - } - return false; -} - -void VmaDefragmentationContext_T::UpdateVectorStatistics(VmaBlockVector& vector, StateBalanced& state) -{ - size_t allocCount = 0; - size_t freeCount = 0; - state.avgFreeSize = 0; - state.avgAllocSize = 0; - - for (size_t i = 0; i < vector.GetBlockCount(); ++i) - { - VmaBlockMetadata* metadata = vector.GetBlock(i)->m_pMetadata; - - allocCount += metadata->GetAllocationCount(); - freeCount += metadata->GetFreeRegionsCount(); - state.avgFreeSize += metadata->GetSumFreeSize(); - state.avgAllocSize += metadata->GetSize(); - } - - state.avgAllocSize = (state.avgAllocSize - state.avgFreeSize) / allocCount; - state.avgFreeSize /= freeCount; -} - -bool VmaDefragmentationContext_T::MoveDataToFreeBlocks(VmaSuballocationType currentType, - VmaBlockVector& vector, size_t firstFreeBlock, - bool& texturePresent, bool& bufferPresent, bool& otherPresent) -{ - const size_t prevMoveCount = m_Moves.size(); - for (size_t i = firstFreeBlock ; i;) - { - VmaDeviceMemoryBlock* block = vector.GetBlock(--i); - VmaBlockMetadata* metadata = block->m_pMetadata; - - for (VmaAllocHandle handle = metadata->GetAllocationListBegin(); - handle != VK_NULL_HANDLE; - handle = metadata->GetNextAllocation(handle)) - { - MoveAllocationData moveData = GetMoveData(handle, metadata); - // Ignore newly created allocations by defragmentation algorithm - if (moveData.move.srcAllocation->GetUserData() == this) - continue; - switch (CheckCounters(moveData.move.srcAllocation->GetSize())) - { - case CounterStatus::Ignore: - continue; - case CounterStatus::End: - return true; - default: - VMA_ASSERT(0); - case CounterStatus::Pass: - break; - } - - // Move only single type of resources at once - if (!VmaIsBufferImageGranularityConflict(moveData.type, currentType)) - { - // Try to fit allocation into free blocks - if (AllocInOtherBlock(firstFreeBlock, vector.GetBlockCount(), moveData, vector)) - return false; - } - - if (!VmaIsBufferImageGranularityConflict(moveData.type, VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL)) - texturePresent = true; - else if (!VmaIsBufferImageGranularityConflict(moveData.type, VMA_SUBALLOCATION_TYPE_BUFFER)) - bufferPresent = true; - else - otherPresent = true; - } - } - return prevMoveCount == m_Moves.size(); -} -#endif // _VMA_DEFRAGMENTATION_CONTEXT_FUNCTIONS - -#ifndef _VMA_POOL_T_FUNCTIONS -VmaPool_T::VmaPool_T( - VmaAllocator hAllocator, - const VmaPoolCreateInfo& createInfo, - VkDeviceSize preferredBlockSize) - : m_BlockVector( - hAllocator, - this, // hParentPool - createInfo.memoryTypeIndex, - createInfo.blockSize != 0 ? createInfo.blockSize : preferredBlockSize, - createInfo.minBlockCount, - createInfo.maxBlockCount, - (createInfo.flags& VMA_POOL_CREATE_IGNORE_BUFFER_IMAGE_GRANULARITY_BIT) != 0 ? 1 : hAllocator->GetBufferImageGranularity(), - createInfo.blockSize != 0, // explicitBlockSize - createInfo.flags & VMA_POOL_CREATE_ALGORITHM_MASK, // algorithm - createInfo.priority, - VMA_MAX(hAllocator->GetMemoryTypeMinAlignment(createInfo.memoryTypeIndex), createInfo.minAllocationAlignment), - createInfo.pMemoryAllocateNext), - m_Id(0), - m_Name(VMA_NULL) {} - -VmaPool_T::~VmaPool_T() -{ - VMA_ASSERT(m_PrevPool == VMA_NULL && m_NextPool == VMA_NULL); -} - -void VmaPool_T::SetName(const char* pName) -{ - const VkAllocationCallbacks* allocs = m_BlockVector.GetAllocator()->GetAllocationCallbacks(); - VmaFreeString(allocs, m_Name); - - if (pName != VMA_NULL) - { - m_Name = VmaCreateStringCopy(allocs, pName); - } - else - { - m_Name = VMA_NULL; - } -} -#endif // _VMA_POOL_T_FUNCTIONS - -#ifndef _VMA_ALLOCATOR_T_FUNCTIONS -VmaAllocator_T::VmaAllocator_T(const VmaAllocatorCreateInfo* pCreateInfo) : - m_UseMutex((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT) == 0), - m_VulkanApiVersion(pCreateInfo->vulkanApiVersion != 0 ? pCreateInfo->vulkanApiVersion : VK_API_VERSION_1_0), - m_UseKhrDedicatedAllocation((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT) != 0), - m_UseKhrBindMemory2((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT) != 0), - m_UseExtMemoryBudget((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT) != 0), - m_UseAmdDeviceCoherentMemory((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_AMD_DEVICE_COHERENT_MEMORY_BIT) != 0), - m_UseKhrBufferDeviceAddress((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT) != 0), - m_UseExtMemoryPriority((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT) != 0), - m_hDevice(pCreateInfo->device), - m_hInstance(pCreateInfo->instance), - m_AllocationCallbacksSpecified(pCreateInfo->pAllocationCallbacks != VMA_NULL), - m_AllocationCallbacks(pCreateInfo->pAllocationCallbacks ? - *pCreateInfo->pAllocationCallbacks : VmaEmptyAllocationCallbacks), - m_AllocationObjectAllocator(&m_AllocationCallbacks), - m_HeapSizeLimitMask(0), - m_DeviceMemoryCount(0), - m_PreferredLargeHeapBlockSize(0), - m_PhysicalDevice(pCreateInfo->physicalDevice), - m_GpuDefragmentationMemoryTypeBits(UINT32_MAX), - m_NextPoolId(0), - m_GlobalMemoryTypeBits(UINT32_MAX) -{ - if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) - { - m_UseKhrDedicatedAllocation = false; - m_UseKhrBindMemory2 = false; - } - - if(VMA_DEBUG_DETECT_CORRUPTION) - { - // Needs to be multiply of uint32_t size because we are going to write VMA_CORRUPTION_DETECTION_MAGIC_VALUE to it. - VMA_ASSERT(VMA_DEBUG_MARGIN % sizeof(uint32_t) == 0); - } - - VMA_ASSERT(pCreateInfo->physicalDevice && pCreateInfo->device && pCreateInfo->instance); - - if(m_VulkanApiVersion < VK_MAKE_VERSION(1, 1, 0)) - { -#if !(VMA_DEDICATED_ALLOCATION) - if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT) != 0) - { - VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT set but required extensions are disabled by preprocessor macros."); - } -#endif -#if !(VMA_BIND_MEMORY2) - if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT) != 0) - { - VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_KHR_BIND_MEMORY2_BIT set but required extension is disabled by preprocessor macros."); - } -#endif - } -#if !(VMA_MEMORY_BUDGET) - if((pCreateInfo->flags & VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT) != 0) - { - VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT set but required extension is disabled by preprocessor macros."); - } -#endif -#if !(VMA_BUFFER_DEVICE_ADDRESS) - if(m_UseKhrBufferDeviceAddress) - { - VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT is set but required extension or Vulkan 1.2 is not available in your Vulkan header or its support in VMA has been disabled by a preprocessor macro."); - } -#endif -#if VMA_VULKAN_VERSION < 1003000 - if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 3, 0)) - { - VMA_ASSERT(0 && "vulkanApiVersion >= VK_API_VERSION_1_3 but required Vulkan version is disabled by preprocessor macros."); - } -#endif -#if VMA_VULKAN_VERSION < 1002000 - if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 2, 0)) - { - VMA_ASSERT(0 && "vulkanApiVersion >= VK_API_VERSION_1_2 but required Vulkan version is disabled by preprocessor macros."); - } -#endif -#if VMA_VULKAN_VERSION < 1001000 - if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) - { - VMA_ASSERT(0 && "vulkanApiVersion >= VK_API_VERSION_1_1 but required Vulkan version is disabled by preprocessor macros."); - } -#endif -#if !(VMA_MEMORY_PRIORITY) - if(m_UseExtMemoryPriority) - { - VMA_ASSERT(0 && "VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT is set but required extension is not available in your Vulkan header or its support in VMA has been disabled by a preprocessor macro."); - } -#endif - - memset(&m_DeviceMemoryCallbacks, 0 ,sizeof(m_DeviceMemoryCallbacks)); - memset(&m_PhysicalDeviceProperties, 0, sizeof(m_PhysicalDeviceProperties)); - memset(&m_MemProps, 0, sizeof(m_MemProps)); - - memset(&m_pBlockVectors, 0, sizeof(m_pBlockVectors)); - memset(&m_VulkanFunctions, 0, sizeof(m_VulkanFunctions)); - -#if VMA_EXTERNAL_MEMORY - memset(&m_TypeExternalMemoryHandleTypes, 0, sizeof(m_TypeExternalMemoryHandleTypes)); -#endif // #if VMA_EXTERNAL_MEMORY - - if(pCreateInfo->pDeviceMemoryCallbacks != VMA_NULL) - { - m_DeviceMemoryCallbacks.pUserData = pCreateInfo->pDeviceMemoryCallbacks->pUserData; - m_DeviceMemoryCallbacks.pfnAllocate = pCreateInfo->pDeviceMemoryCallbacks->pfnAllocate; - m_DeviceMemoryCallbacks.pfnFree = pCreateInfo->pDeviceMemoryCallbacks->pfnFree; - } - - ImportVulkanFunctions(pCreateInfo->pVulkanFunctions); - - (*m_VulkanFunctions.vkGetPhysicalDeviceProperties)(m_PhysicalDevice, &m_PhysicalDeviceProperties); - (*m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties)(m_PhysicalDevice, &m_MemProps); - - VMA_ASSERT(VmaIsPow2(VMA_MIN_ALIGNMENT)); - VMA_ASSERT(VmaIsPow2(VMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY)); - VMA_ASSERT(VmaIsPow2(m_PhysicalDeviceProperties.limits.bufferImageGranularity)); - VMA_ASSERT(VmaIsPow2(m_PhysicalDeviceProperties.limits.nonCoherentAtomSize)); - - m_PreferredLargeHeapBlockSize = (pCreateInfo->preferredLargeHeapBlockSize != 0) ? - pCreateInfo->preferredLargeHeapBlockSize : static_cast(VMA_DEFAULT_LARGE_HEAP_BLOCK_SIZE); - - m_GlobalMemoryTypeBits = CalculateGlobalMemoryTypeBits(); - -#if VMA_EXTERNAL_MEMORY - if(pCreateInfo->pTypeExternalMemoryHandleTypes != VMA_NULL) - { - memcpy(m_TypeExternalMemoryHandleTypes, pCreateInfo->pTypeExternalMemoryHandleTypes, - sizeof(VkExternalMemoryHandleTypeFlagsKHR) * GetMemoryTypeCount()); - } -#endif // #if VMA_EXTERNAL_MEMORY - - if(pCreateInfo->pHeapSizeLimit != VMA_NULL) - { - for(uint32_t heapIndex = 0; heapIndex < GetMemoryHeapCount(); ++heapIndex) - { - const VkDeviceSize limit = pCreateInfo->pHeapSizeLimit[heapIndex]; - if(limit != VK_WHOLE_SIZE) - { - m_HeapSizeLimitMask |= 1u << heapIndex; - if(limit < m_MemProps.memoryHeaps[heapIndex].size) - { - m_MemProps.memoryHeaps[heapIndex].size = limit; - } - } - } - } - - for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) - { - // Create only supported types - if((m_GlobalMemoryTypeBits & (1u << memTypeIndex)) != 0) - { - const VkDeviceSize preferredBlockSize = CalcPreferredBlockSize(memTypeIndex); - m_pBlockVectors[memTypeIndex] = vma_new(this, VmaBlockVector)( - this, - VK_NULL_HANDLE, // hParentPool - memTypeIndex, - preferredBlockSize, - 0, - SIZE_MAX, - GetBufferImageGranularity(), - false, // explicitBlockSize - 0, // algorithm - 0.5f, // priority (0.5 is the default per Vulkan spec) - GetMemoryTypeMinAlignment(memTypeIndex), // minAllocationAlignment - VMA_NULL); // // pMemoryAllocateNext - // No need to call m_pBlockVectors[memTypeIndex][blockVectorTypeIndex]->CreateMinBlocks here, - // becase minBlockCount is 0. - } - } -} - -VkResult VmaAllocator_T::Init(const VmaAllocatorCreateInfo* pCreateInfo) -{ - VkResult res = VK_SUCCESS; - -#if VMA_MEMORY_BUDGET - if(m_UseExtMemoryBudget) - { - UpdateVulkanBudget(); - } -#endif // #if VMA_MEMORY_BUDGET - - return res; -} - -VmaAllocator_T::~VmaAllocator_T() -{ - VMA_ASSERT(m_Pools.IsEmpty()); - - for(size_t memTypeIndex = GetMemoryTypeCount(); memTypeIndex--; ) - { - vma_delete(this, m_pBlockVectors[memTypeIndex]); - } -} - -void VmaAllocator_T::ImportVulkanFunctions(const VmaVulkanFunctions* pVulkanFunctions) -{ -#if VMA_STATIC_VULKAN_FUNCTIONS == 1 - ImportVulkanFunctions_Static(); -#endif - - if(pVulkanFunctions != VMA_NULL) - { - ImportVulkanFunctions_Custom(pVulkanFunctions); - } - -#if VMA_DYNAMIC_VULKAN_FUNCTIONS == 1 - ImportVulkanFunctions_Dynamic(); -#endif - - ValidateVulkanFunctions(); -} - -#if VMA_STATIC_VULKAN_FUNCTIONS == 1 - -void VmaAllocator_T::ImportVulkanFunctions_Static() -{ - // Vulkan 1.0 - m_VulkanFunctions.vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)vkGetInstanceProcAddr; - m_VulkanFunctions.vkGetDeviceProcAddr = (PFN_vkGetDeviceProcAddr)vkGetDeviceProcAddr; - m_VulkanFunctions.vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)vkGetPhysicalDeviceProperties; - m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties)vkGetPhysicalDeviceMemoryProperties; - m_VulkanFunctions.vkAllocateMemory = (PFN_vkAllocateMemory)vkAllocateMemory; - m_VulkanFunctions.vkFreeMemory = (PFN_vkFreeMemory)vkFreeMemory; - m_VulkanFunctions.vkMapMemory = (PFN_vkMapMemory)vkMapMemory; - m_VulkanFunctions.vkUnmapMemory = (PFN_vkUnmapMemory)vkUnmapMemory; - m_VulkanFunctions.vkFlushMappedMemoryRanges = (PFN_vkFlushMappedMemoryRanges)vkFlushMappedMemoryRanges; - m_VulkanFunctions.vkInvalidateMappedMemoryRanges = (PFN_vkInvalidateMappedMemoryRanges)vkInvalidateMappedMemoryRanges; - m_VulkanFunctions.vkBindBufferMemory = (PFN_vkBindBufferMemory)vkBindBufferMemory; - m_VulkanFunctions.vkBindImageMemory = (PFN_vkBindImageMemory)vkBindImageMemory; - m_VulkanFunctions.vkGetBufferMemoryRequirements = (PFN_vkGetBufferMemoryRequirements)vkGetBufferMemoryRequirements; - m_VulkanFunctions.vkGetImageMemoryRequirements = (PFN_vkGetImageMemoryRequirements)vkGetImageMemoryRequirements; - m_VulkanFunctions.vkCreateBuffer = (PFN_vkCreateBuffer)vkCreateBuffer; - m_VulkanFunctions.vkDestroyBuffer = (PFN_vkDestroyBuffer)vkDestroyBuffer; - m_VulkanFunctions.vkCreateImage = (PFN_vkCreateImage)vkCreateImage; - m_VulkanFunctions.vkDestroyImage = (PFN_vkDestroyImage)vkDestroyImage; - m_VulkanFunctions.vkCmdCopyBuffer = (PFN_vkCmdCopyBuffer)vkCmdCopyBuffer; - - // Vulkan 1.1 -#if VMA_VULKAN_VERSION >= 1001000 - if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) - { - m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR = (PFN_vkGetBufferMemoryRequirements2)vkGetBufferMemoryRequirements2; - m_VulkanFunctions.vkGetImageMemoryRequirements2KHR = (PFN_vkGetImageMemoryRequirements2)vkGetImageMemoryRequirements2; - m_VulkanFunctions.vkBindBufferMemory2KHR = (PFN_vkBindBufferMemory2)vkBindBufferMemory2; - m_VulkanFunctions.vkBindImageMemory2KHR = (PFN_vkBindImageMemory2)vkBindImageMemory2; - m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties2KHR = (PFN_vkGetPhysicalDeviceMemoryProperties2)vkGetPhysicalDeviceMemoryProperties2; - } -#endif - -#if VMA_VULKAN_VERSION >= 1003000 - if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 3, 0)) - { - m_VulkanFunctions.vkGetDeviceBufferMemoryRequirements = (PFN_vkGetDeviceBufferMemoryRequirements)vkGetDeviceBufferMemoryRequirements; - m_VulkanFunctions.vkGetDeviceImageMemoryRequirements = (PFN_vkGetDeviceImageMemoryRequirements)vkGetDeviceImageMemoryRequirements; - } -#endif -} - -#endif // VMA_STATIC_VULKAN_FUNCTIONS == 1 - -void VmaAllocator_T::ImportVulkanFunctions_Custom(const VmaVulkanFunctions* pVulkanFunctions) -{ - VMA_ASSERT(pVulkanFunctions != VMA_NULL); - -#define VMA_COPY_IF_NOT_NULL(funcName) \ - if(pVulkanFunctions->funcName != VMA_NULL) m_VulkanFunctions.funcName = pVulkanFunctions->funcName; - - VMA_COPY_IF_NOT_NULL(vkGetInstanceProcAddr); - VMA_COPY_IF_NOT_NULL(vkGetDeviceProcAddr); - VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceProperties); - VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceMemoryProperties); - VMA_COPY_IF_NOT_NULL(vkAllocateMemory); - VMA_COPY_IF_NOT_NULL(vkFreeMemory); - VMA_COPY_IF_NOT_NULL(vkMapMemory); - VMA_COPY_IF_NOT_NULL(vkUnmapMemory); - VMA_COPY_IF_NOT_NULL(vkFlushMappedMemoryRanges); - VMA_COPY_IF_NOT_NULL(vkInvalidateMappedMemoryRanges); - VMA_COPY_IF_NOT_NULL(vkBindBufferMemory); - VMA_COPY_IF_NOT_NULL(vkBindImageMemory); - VMA_COPY_IF_NOT_NULL(vkGetBufferMemoryRequirements); - VMA_COPY_IF_NOT_NULL(vkGetImageMemoryRequirements); - VMA_COPY_IF_NOT_NULL(vkCreateBuffer); - VMA_COPY_IF_NOT_NULL(vkDestroyBuffer); - VMA_COPY_IF_NOT_NULL(vkCreateImage); - VMA_COPY_IF_NOT_NULL(vkDestroyImage); - VMA_COPY_IF_NOT_NULL(vkCmdCopyBuffer); - -#if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 - VMA_COPY_IF_NOT_NULL(vkGetBufferMemoryRequirements2KHR); - VMA_COPY_IF_NOT_NULL(vkGetImageMemoryRequirements2KHR); -#endif - -#if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000 - VMA_COPY_IF_NOT_NULL(vkBindBufferMemory2KHR); - VMA_COPY_IF_NOT_NULL(vkBindImageMemory2KHR); -#endif - -#if VMA_MEMORY_BUDGET - VMA_COPY_IF_NOT_NULL(vkGetPhysicalDeviceMemoryProperties2KHR); -#endif - -#if VMA_VULKAN_VERSION >= 1003000 - VMA_COPY_IF_NOT_NULL(vkGetDeviceBufferMemoryRequirements); - VMA_COPY_IF_NOT_NULL(vkGetDeviceImageMemoryRequirements); -#endif - -#undef VMA_COPY_IF_NOT_NULL -} - -#if VMA_DYNAMIC_VULKAN_FUNCTIONS == 1 - -void VmaAllocator_T::ImportVulkanFunctions_Dynamic() -{ - VMA_ASSERT(m_VulkanFunctions.vkGetInstanceProcAddr && m_VulkanFunctions.vkGetDeviceProcAddr && - "To use VMA_DYNAMIC_VULKAN_FUNCTIONS in new versions of VMA you now have to pass " - "VmaVulkanFunctions::vkGetInstanceProcAddr and vkGetDeviceProcAddr as VmaAllocatorCreateInfo::pVulkanFunctions. " - "Other members can be null."); - -#define VMA_FETCH_INSTANCE_FUNC(memberName, functionPointerType, functionNameString) \ - if(m_VulkanFunctions.memberName == VMA_NULL) \ - m_VulkanFunctions.memberName = \ - (functionPointerType)m_VulkanFunctions.vkGetInstanceProcAddr(m_hInstance, functionNameString); -#define VMA_FETCH_DEVICE_FUNC(memberName, functionPointerType, functionNameString) \ - if(m_VulkanFunctions.memberName == VMA_NULL) \ - m_VulkanFunctions.memberName = \ - (functionPointerType)m_VulkanFunctions.vkGetDeviceProcAddr(m_hDevice, functionNameString); - - VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceProperties, PFN_vkGetPhysicalDeviceProperties, "vkGetPhysicalDeviceProperties"); - VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceMemoryProperties, PFN_vkGetPhysicalDeviceMemoryProperties, "vkGetPhysicalDeviceMemoryProperties"); - VMA_FETCH_DEVICE_FUNC(vkAllocateMemory, PFN_vkAllocateMemory, "vkAllocateMemory"); - VMA_FETCH_DEVICE_FUNC(vkFreeMemory, PFN_vkFreeMemory, "vkFreeMemory"); - VMA_FETCH_DEVICE_FUNC(vkMapMemory, PFN_vkMapMemory, "vkMapMemory"); - VMA_FETCH_DEVICE_FUNC(vkUnmapMemory, PFN_vkUnmapMemory, "vkUnmapMemory"); - VMA_FETCH_DEVICE_FUNC(vkFlushMappedMemoryRanges, PFN_vkFlushMappedMemoryRanges, "vkFlushMappedMemoryRanges"); - VMA_FETCH_DEVICE_FUNC(vkInvalidateMappedMemoryRanges, PFN_vkInvalidateMappedMemoryRanges, "vkInvalidateMappedMemoryRanges"); - VMA_FETCH_DEVICE_FUNC(vkBindBufferMemory, PFN_vkBindBufferMemory, "vkBindBufferMemory"); - VMA_FETCH_DEVICE_FUNC(vkBindImageMemory, PFN_vkBindImageMemory, "vkBindImageMemory"); - VMA_FETCH_DEVICE_FUNC(vkGetBufferMemoryRequirements, PFN_vkGetBufferMemoryRequirements, "vkGetBufferMemoryRequirements"); - VMA_FETCH_DEVICE_FUNC(vkGetImageMemoryRequirements, PFN_vkGetImageMemoryRequirements, "vkGetImageMemoryRequirements"); - VMA_FETCH_DEVICE_FUNC(vkCreateBuffer, PFN_vkCreateBuffer, "vkCreateBuffer"); - VMA_FETCH_DEVICE_FUNC(vkDestroyBuffer, PFN_vkDestroyBuffer, "vkDestroyBuffer"); - VMA_FETCH_DEVICE_FUNC(vkCreateImage, PFN_vkCreateImage, "vkCreateImage"); - VMA_FETCH_DEVICE_FUNC(vkDestroyImage, PFN_vkDestroyImage, "vkDestroyImage"); - VMA_FETCH_DEVICE_FUNC(vkCmdCopyBuffer, PFN_vkCmdCopyBuffer, "vkCmdCopyBuffer"); - -#if VMA_VULKAN_VERSION >= 1001000 - if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) - { - VMA_FETCH_DEVICE_FUNC(vkGetBufferMemoryRequirements2KHR, PFN_vkGetBufferMemoryRequirements2, "vkGetBufferMemoryRequirements2"); - VMA_FETCH_DEVICE_FUNC(vkGetImageMemoryRequirements2KHR, PFN_vkGetImageMemoryRequirements2, "vkGetImageMemoryRequirements2"); - VMA_FETCH_DEVICE_FUNC(vkBindBufferMemory2KHR, PFN_vkBindBufferMemory2, "vkBindBufferMemory2"); - VMA_FETCH_DEVICE_FUNC(vkBindImageMemory2KHR, PFN_vkBindImageMemory2, "vkBindImageMemory2"); - VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceMemoryProperties2KHR, PFN_vkGetPhysicalDeviceMemoryProperties2, "vkGetPhysicalDeviceMemoryProperties2"); - } -#endif - -#if VMA_DEDICATED_ALLOCATION - if(m_UseKhrDedicatedAllocation) - { - VMA_FETCH_DEVICE_FUNC(vkGetBufferMemoryRequirements2KHR, PFN_vkGetBufferMemoryRequirements2KHR, "vkGetBufferMemoryRequirements2KHR"); - VMA_FETCH_DEVICE_FUNC(vkGetImageMemoryRequirements2KHR, PFN_vkGetImageMemoryRequirements2KHR, "vkGetImageMemoryRequirements2KHR"); - } -#endif - -#if VMA_BIND_MEMORY2 - if(m_UseKhrBindMemory2) - { - VMA_FETCH_DEVICE_FUNC(vkBindBufferMemory2KHR, PFN_vkBindBufferMemory2KHR, "vkBindBufferMemory2KHR"); - VMA_FETCH_DEVICE_FUNC(vkBindImageMemory2KHR, PFN_vkBindImageMemory2KHR, "vkBindImageMemory2KHR"); - } -#endif // #if VMA_BIND_MEMORY2 - -#if VMA_MEMORY_BUDGET - if(m_UseExtMemoryBudget) - { - VMA_FETCH_INSTANCE_FUNC(vkGetPhysicalDeviceMemoryProperties2KHR, PFN_vkGetPhysicalDeviceMemoryProperties2KHR, "vkGetPhysicalDeviceMemoryProperties2KHR"); - } -#endif // #if VMA_MEMORY_BUDGET - -#if VMA_VULKAN_VERSION >= 1003000 - if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 3, 0)) - { - VMA_FETCH_DEVICE_FUNC(vkGetDeviceBufferMemoryRequirements, PFN_vkGetDeviceBufferMemoryRequirements, "vkGetDeviceBufferMemoryRequirements"); - VMA_FETCH_DEVICE_FUNC(vkGetDeviceImageMemoryRequirements, PFN_vkGetDeviceImageMemoryRequirements, "vkGetDeviceImageMemoryRequirements"); - } -#endif - -#undef VMA_FETCH_DEVICE_FUNC -#undef VMA_FETCH_INSTANCE_FUNC -} - -#endif // VMA_DYNAMIC_VULKAN_FUNCTIONS == 1 - -void VmaAllocator_T::ValidateVulkanFunctions() -{ - VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceProperties != VMA_NULL); - VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties != VMA_NULL); - VMA_ASSERT(m_VulkanFunctions.vkAllocateMemory != VMA_NULL); - VMA_ASSERT(m_VulkanFunctions.vkFreeMemory != VMA_NULL); - VMA_ASSERT(m_VulkanFunctions.vkMapMemory != VMA_NULL); - VMA_ASSERT(m_VulkanFunctions.vkUnmapMemory != VMA_NULL); - VMA_ASSERT(m_VulkanFunctions.vkFlushMappedMemoryRanges != VMA_NULL); - VMA_ASSERT(m_VulkanFunctions.vkInvalidateMappedMemoryRanges != VMA_NULL); - VMA_ASSERT(m_VulkanFunctions.vkBindBufferMemory != VMA_NULL); - VMA_ASSERT(m_VulkanFunctions.vkBindImageMemory != VMA_NULL); - VMA_ASSERT(m_VulkanFunctions.vkGetBufferMemoryRequirements != VMA_NULL); - VMA_ASSERT(m_VulkanFunctions.vkGetImageMemoryRequirements != VMA_NULL); - VMA_ASSERT(m_VulkanFunctions.vkCreateBuffer != VMA_NULL); - VMA_ASSERT(m_VulkanFunctions.vkDestroyBuffer != VMA_NULL); - VMA_ASSERT(m_VulkanFunctions.vkCreateImage != VMA_NULL); - VMA_ASSERT(m_VulkanFunctions.vkDestroyImage != VMA_NULL); - VMA_ASSERT(m_VulkanFunctions.vkCmdCopyBuffer != VMA_NULL); - -#if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 - if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0) || m_UseKhrDedicatedAllocation) - { - VMA_ASSERT(m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR != VMA_NULL); - VMA_ASSERT(m_VulkanFunctions.vkGetImageMemoryRequirements2KHR != VMA_NULL); - } -#endif - -#if VMA_BIND_MEMORY2 || VMA_VULKAN_VERSION >= 1001000 - if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0) || m_UseKhrBindMemory2) - { - VMA_ASSERT(m_VulkanFunctions.vkBindBufferMemory2KHR != VMA_NULL); - VMA_ASSERT(m_VulkanFunctions.vkBindImageMemory2KHR != VMA_NULL); - } -#endif - -#if VMA_MEMORY_BUDGET || VMA_VULKAN_VERSION >= 1001000 - if(m_UseExtMemoryBudget || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) - { - VMA_ASSERT(m_VulkanFunctions.vkGetPhysicalDeviceMemoryProperties2KHR != VMA_NULL); - } -#endif - -#if VMA_VULKAN_VERSION >= 1003000 - if(m_VulkanApiVersion >= VK_MAKE_VERSION(1, 3, 0)) - { - VMA_ASSERT(m_VulkanFunctions.vkGetDeviceBufferMemoryRequirements != VMA_NULL); - VMA_ASSERT(m_VulkanFunctions.vkGetDeviceImageMemoryRequirements != VMA_NULL); - } -#endif -} - -VkDeviceSize VmaAllocator_T::CalcPreferredBlockSize(uint32_t memTypeIndex) -{ - const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex); - const VkDeviceSize heapSize = m_MemProps.memoryHeaps[heapIndex].size; - const bool isSmallHeap = heapSize <= VMA_SMALL_HEAP_MAX_SIZE; - return VmaAlignUp(isSmallHeap ? (heapSize / 8) : m_PreferredLargeHeapBlockSize, (VkDeviceSize)32); -} - -VkResult VmaAllocator_T::AllocateMemoryOfType( - VmaPool pool, - VkDeviceSize size, - VkDeviceSize alignment, - bool dedicatedPreferred, - VkBuffer dedicatedBuffer, - VkImage dedicatedImage, - VkFlags dedicatedBufferImageUsage, - const VmaAllocationCreateInfo& createInfo, - uint32_t memTypeIndex, - VmaSuballocationType suballocType, - VmaDedicatedAllocationList& dedicatedAllocations, - VmaBlockVector& blockVector, - size_t allocationCount, - VmaAllocation* pAllocations) -{ - VMA_ASSERT(pAllocations != VMA_NULL); - VMA_DEBUG_LOG(" AllocateMemory: MemoryTypeIndex=%u, AllocationCount=%zu, Size=%llu", memTypeIndex, allocationCount, size); - - VmaAllocationCreateInfo finalCreateInfo = createInfo; - VkResult res = CalcMemTypeParams( - finalCreateInfo, - memTypeIndex, - size, - allocationCount); - if(res != VK_SUCCESS) - return res; - - if((finalCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0) - { - return AllocateDedicatedMemory( - pool, - size, - suballocType, - dedicatedAllocations, - memTypeIndex, - (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0, - (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0, - (finalCreateInfo.flags & - (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0, - (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT) != 0, - finalCreateInfo.pUserData, - finalCreateInfo.priority, - dedicatedBuffer, - dedicatedImage, - dedicatedBufferImageUsage, - allocationCount, - pAllocations, - blockVector.GetAllocationNextPtr()); - } - else - { - const bool canAllocateDedicated = - (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) == 0 && - (pool == VK_NULL_HANDLE || !blockVector.HasExplicitBlockSize()); - - if(canAllocateDedicated) - { - // Heuristics: Allocate dedicated memory if requested size if greater than half of preferred block size. - if(size > blockVector.GetPreferredBlockSize() / 2) - { - dedicatedPreferred = true; - } - // Protection against creating each allocation as dedicated when we reach or exceed heap size/budget, - // which can quickly deplete maxMemoryAllocationCount: Don't prefer dedicated allocations when above - // 3/4 of the maximum allocation count. - if(m_DeviceMemoryCount.load() > m_PhysicalDeviceProperties.limits.maxMemoryAllocationCount * 3 / 4) - { - dedicatedPreferred = false; - } - - if(dedicatedPreferred) - { - res = AllocateDedicatedMemory( - pool, - size, - suballocType, - dedicatedAllocations, - memTypeIndex, - (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0, - (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0, - (finalCreateInfo.flags & - (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0, - (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT) != 0, - finalCreateInfo.pUserData, - finalCreateInfo.priority, - dedicatedBuffer, - dedicatedImage, - dedicatedBufferImageUsage, - allocationCount, - pAllocations, - blockVector.GetAllocationNextPtr()); - if(res == VK_SUCCESS) - { - // Succeeded: AllocateDedicatedMemory function already filled pMemory, nothing more to do here. - VMA_DEBUG_LOG(" Allocated as DedicatedMemory"); - return VK_SUCCESS; - } - } - } - - res = blockVector.Allocate( - size, - alignment, - finalCreateInfo, - suballocType, - allocationCount, - pAllocations); - if(res == VK_SUCCESS) - return VK_SUCCESS; - - // Try dedicated memory. - if(canAllocateDedicated && !dedicatedPreferred) - { - res = AllocateDedicatedMemory( - pool, - size, - suballocType, - dedicatedAllocations, - memTypeIndex, - (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0, - (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_USER_DATA_COPY_STRING_BIT) != 0, - (finalCreateInfo.flags & - (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0, - (finalCreateInfo.flags & VMA_ALLOCATION_CREATE_CAN_ALIAS_BIT) != 0, - finalCreateInfo.pUserData, - finalCreateInfo.priority, - dedicatedBuffer, - dedicatedImage, - dedicatedBufferImageUsage, - allocationCount, - pAllocations, - blockVector.GetAllocationNextPtr()); - if(res == VK_SUCCESS) - { - // Succeeded: AllocateDedicatedMemory function already filled pMemory, nothing more to do here. - VMA_DEBUG_LOG(" Allocated as DedicatedMemory"); - return VK_SUCCESS; - } - } - // Everything failed: Return error code. - VMA_DEBUG_LOG(" vkAllocateMemory FAILED"); - return res; - } -} - -VkResult VmaAllocator_T::AllocateDedicatedMemory( - VmaPool pool, - VkDeviceSize size, - VmaSuballocationType suballocType, - VmaDedicatedAllocationList& dedicatedAllocations, - uint32_t memTypeIndex, - bool map, - bool isUserDataString, - bool isMappingAllowed, - bool canAliasMemory, - void* pUserData, - float priority, - VkBuffer dedicatedBuffer, - VkImage dedicatedImage, - VkFlags dedicatedBufferImageUsage, - size_t allocationCount, - VmaAllocation* pAllocations, - const void* pNextChain) -{ - VMA_ASSERT(allocationCount > 0 && pAllocations); - - VkMemoryAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO }; - allocInfo.memoryTypeIndex = memTypeIndex; - allocInfo.allocationSize = size; - allocInfo.pNext = pNextChain; - -#if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 - VkMemoryDedicatedAllocateInfoKHR dedicatedAllocInfo = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR }; - if(!canAliasMemory) - { - if(m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) - { - if(dedicatedBuffer != VK_NULL_HANDLE) - { - VMA_ASSERT(dedicatedImage == VK_NULL_HANDLE); - dedicatedAllocInfo.buffer = dedicatedBuffer; - VmaPnextChainPushFront(&allocInfo, &dedicatedAllocInfo); - } - else if(dedicatedImage != VK_NULL_HANDLE) - { - dedicatedAllocInfo.image = dedicatedImage; - VmaPnextChainPushFront(&allocInfo, &dedicatedAllocInfo); - } - } - } -#endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 - -#if VMA_BUFFER_DEVICE_ADDRESS - VkMemoryAllocateFlagsInfoKHR allocFlagsInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO_KHR }; - if(m_UseKhrBufferDeviceAddress) - { - bool canContainBufferWithDeviceAddress = true; - if(dedicatedBuffer != VK_NULL_HANDLE) - { - canContainBufferWithDeviceAddress = dedicatedBufferImageUsage == UINT32_MAX || // Usage flags unknown - (dedicatedBufferImageUsage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_EXT) != 0; - } - else if(dedicatedImage != VK_NULL_HANDLE) - { - canContainBufferWithDeviceAddress = false; - } - if(canContainBufferWithDeviceAddress) - { - allocFlagsInfo.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR; - VmaPnextChainPushFront(&allocInfo, &allocFlagsInfo); - } - } -#endif // #if VMA_BUFFER_DEVICE_ADDRESS - -#if VMA_MEMORY_PRIORITY - VkMemoryPriorityAllocateInfoEXT priorityInfo = { VK_STRUCTURE_TYPE_MEMORY_PRIORITY_ALLOCATE_INFO_EXT }; - if(m_UseExtMemoryPriority) - { - VMA_ASSERT(priority >= 0.f && priority <= 1.f); - priorityInfo.priority = priority; - VmaPnextChainPushFront(&allocInfo, &priorityInfo); - } -#endif // #if VMA_MEMORY_PRIORITY - -#if VMA_EXTERNAL_MEMORY - // Attach VkExportMemoryAllocateInfoKHR if necessary. - VkExportMemoryAllocateInfoKHR exportMemoryAllocInfo = { VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR }; - exportMemoryAllocInfo.handleTypes = GetExternalMemoryHandleTypeFlags(memTypeIndex); - if(exportMemoryAllocInfo.handleTypes != 0) - { - VmaPnextChainPushFront(&allocInfo, &exportMemoryAllocInfo); - } -#endif // #if VMA_EXTERNAL_MEMORY - - size_t allocIndex; - VkResult res = VK_SUCCESS; - for(allocIndex = 0; allocIndex < allocationCount; ++allocIndex) - { - res = AllocateDedicatedMemoryPage( - pool, - size, - suballocType, - memTypeIndex, - allocInfo, - map, - isUserDataString, - isMappingAllowed, - pUserData, - pAllocations + allocIndex); - if(res != VK_SUCCESS) - { - break; - } - } - - if(res == VK_SUCCESS) - { - for (allocIndex = 0; allocIndex < allocationCount; ++allocIndex) - { - dedicatedAllocations.Register(pAllocations[allocIndex]); - } - VMA_DEBUG_LOG(" Allocated DedicatedMemory Count=%zu, MemoryTypeIndex=#%u", allocationCount, memTypeIndex); - } - else - { - // Free all already created allocations. - while(allocIndex--) - { - VmaAllocation currAlloc = pAllocations[allocIndex]; - VkDeviceMemory hMemory = currAlloc->GetMemory(); - - /* - There is no need to call this, because Vulkan spec allows to skip vkUnmapMemory - before vkFreeMemory. - - if(currAlloc->GetMappedData() != VMA_NULL) - { - (*m_VulkanFunctions.vkUnmapMemory)(m_hDevice, hMemory); - } - */ - - FreeVulkanMemory(memTypeIndex, currAlloc->GetSize(), hMemory); - m_Budget.RemoveAllocation(MemoryTypeIndexToHeapIndex(memTypeIndex), currAlloc->GetSize()); - m_AllocationObjectAllocator.Free(currAlloc); - } - - memset(pAllocations, 0, sizeof(VmaAllocation) * allocationCount); - } - - return res; -} - -VkResult VmaAllocator_T::AllocateDedicatedMemoryPage( - VmaPool pool, - VkDeviceSize size, - VmaSuballocationType suballocType, - uint32_t memTypeIndex, - const VkMemoryAllocateInfo& allocInfo, - bool map, - bool isUserDataString, - bool isMappingAllowed, - void* pUserData, - VmaAllocation* pAllocation) -{ - VkDeviceMemory hMemory = VK_NULL_HANDLE; - VkResult res = AllocateVulkanMemory(&allocInfo, &hMemory); - if(res < 0) - { - VMA_DEBUG_LOG(" vkAllocateMemory FAILED"); - return res; - } - - void* pMappedData = VMA_NULL; - if(map) - { - res = (*m_VulkanFunctions.vkMapMemory)( - m_hDevice, - hMemory, - 0, - VK_WHOLE_SIZE, - 0, - &pMappedData); - if(res < 0) - { - VMA_DEBUG_LOG(" vkMapMemory FAILED"); - FreeVulkanMemory(memTypeIndex, size, hMemory); - return res; - } - } - - *pAllocation = m_AllocationObjectAllocator.Allocate(isMappingAllowed); - (*pAllocation)->InitDedicatedAllocation(pool, memTypeIndex, hMemory, suballocType, pMappedData, size); - if (isUserDataString) - (*pAllocation)->SetName(this, (const char*)pUserData); - else - (*pAllocation)->SetUserData(this, pUserData); - m_Budget.AddAllocation(MemoryTypeIndexToHeapIndex(memTypeIndex), size); - if(VMA_DEBUG_INITIALIZE_ALLOCATIONS) - { - FillAllocation(*pAllocation, VMA_ALLOCATION_FILL_PATTERN_CREATED); - } - - return VK_SUCCESS; -} - -void VmaAllocator_T::GetBufferMemoryRequirements( - VkBuffer hBuffer, - VkMemoryRequirements& memReq, - bool& requiresDedicatedAllocation, - bool& prefersDedicatedAllocation) const -{ -#if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 - if(m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) - { - VkBufferMemoryRequirementsInfo2KHR memReqInfo = { VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR }; - memReqInfo.buffer = hBuffer; - - VkMemoryDedicatedRequirementsKHR memDedicatedReq = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR }; - - VkMemoryRequirements2KHR memReq2 = { VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR }; - VmaPnextChainPushFront(&memReq2, &memDedicatedReq); - - (*m_VulkanFunctions.vkGetBufferMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2); - - memReq = memReq2.memoryRequirements; - requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE); - prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE); - } - else -#endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 - { - (*m_VulkanFunctions.vkGetBufferMemoryRequirements)(m_hDevice, hBuffer, &memReq); - requiresDedicatedAllocation = false; - prefersDedicatedAllocation = false; - } -} - -void VmaAllocator_T::GetImageMemoryRequirements( - VkImage hImage, - VkMemoryRequirements& memReq, - bool& requiresDedicatedAllocation, - bool& prefersDedicatedAllocation) const -{ -#if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 - if(m_UseKhrDedicatedAllocation || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) - { - VkImageMemoryRequirementsInfo2KHR memReqInfo = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2_KHR }; - memReqInfo.image = hImage; - - VkMemoryDedicatedRequirementsKHR memDedicatedReq = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR }; - - VkMemoryRequirements2KHR memReq2 = { VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR }; - VmaPnextChainPushFront(&memReq2, &memDedicatedReq); - - (*m_VulkanFunctions.vkGetImageMemoryRequirements2KHR)(m_hDevice, &memReqInfo, &memReq2); - - memReq = memReq2.memoryRequirements; - requiresDedicatedAllocation = (memDedicatedReq.requiresDedicatedAllocation != VK_FALSE); - prefersDedicatedAllocation = (memDedicatedReq.prefersDedicatedAllocation != VK_FALSE); - } - else -#endif // #if VMA_DEDICATED_ALLOCATION || VMA_VULKAN_VERSION >= 1001000 - { - (*m_VulkanFunctions.vkGetImageMemoryRequirements)(m_hDevice, hImage, &memReq); - requiresDedicatedAllocation = false; - prefersDedicatedAllocation = false; - } -} - -VkResult VmaAllocator_T::FindMemoryTypeIndex( - uint32_t memoryTypeBits, - const VmaAllocationCreateInfo* pAllocationCreateInfo, - VkFlags bufImgUsage, - uint32_t* pMemoryTypeIndex) const -{ - memoryTypeBits &= GetGlobalMemoryTypeBits(); - - if(pAllocationCreateInfo->memoryTypeBits != 0) - { - memoryTypeBits &= pAllocationCreateInfo->memoryTypeBits; - } - - VkMemoryPropertyFlags requiredFlags = 0, preferredFlags = 0, notPreferredFlags = 0; - if(!FindMemoryPreferences( - IsIntegratedGpu(), - *pAllocationCreateInfo, - bufImgUsage, - requiredFlags, preferredFlags, notPreferredFlags)) - { - return VK_ERROR_FEATURE_NOT_PRESENT; - } - - *pMemoryTypeIndex = UINT32_MAX; - uint32_t minCost = UINT32_MAX; - for(uint32_t memTypeIndex = 0, memTypeBit = 1; - memTypeIndex < GetMemoryTypeCount(); - ++memTypeIndex, memTypeBit <<= 1) - { - // This memory type is acceptable according to memoryTypeBits bitmask. - if((memTypeBit & memoryTypeBits) != 0) - { - const VkMemoryPropertyFlags currFlags = - m_MemProps.memoryTypes[memTypeIndex].propertyFlags; - // This memory type contains requiredFlags. - if((requiredFlags & ~currFlags) == 0) - { - // Calculate cost as number of bits from preferredFlags not present in this memory type. - uint32_t currCost = VMA_COUNT_BITS_SET(preferredFlags & ~currFlags) + - VMA_COUNT_BITS_SET(currFlags & notPreferredFlags); - // Remember memory type with lowest cost. - if(currCost < minCost) - { - *pMemoryTypeIndex = memTypeIndex; - if(currCost == 0) - { - return VK_SUCCESS; - } - minCost = currCost; - } - } - } - } - return (*pMemoryTypeIndex != UINT32_MAX) ? VK_SUCCESS : VK_ERROR_FEATURE_NOT_PRESENT; -} - -VkResult VmaAllocator_T::CalcMemTypeParams( - VmaAllocationCreateInfo& inoutCreateInfo, - uint32_t memTypeIndex, - VkDeviceSize size, - size_t allocationCount) -{ - // If memory type is not HOST_VISIBLE, disable MAPPED. - if((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0 && - (m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0) - { - inoutCreateInfo.flags &= ~VMA_ALLOCATION_CREATE_MAPPED_BIT; - } - - if((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0 && - (inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT) != 0) - { - const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memTypeIndex); - VmaBudget heapBudget = {}; - GetHeapBudgets(&heapBudget, heapIndex, 1); - if(heapBudget.usage + size * allocationCount > heapBudget.budget) - { - return VK_ERROR_OUT_OF_DEVICE_MEMORY; - } - } - return VK_SUCCESS; -} - -VkResult VmaAllocator_T::CalcAllocationParams( - VmaAllocationCreateInfo& inoutCreateInfo, - bool dedicatedRequired, - bool dedicatedPreferred) -{ - VMA_ASSERT((inoutCreateInfo.flags & - (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != - (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT) && - "Specifying both flags VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT and VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT is incorrect."); - VMA_ASSERT((((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT) == 0 || - (inoutCreateInfo.flags & (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0)) && - "Specifying VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT requires also VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT."); - if(inoutCreateInfo.usage == VMA_MEMORY_USAGE_AUTO || inoutCreateInfo.usage == VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE || inoutCreateInfo.usage == VMA_MEMORY_USAGE_AUTO_PREFER_HOST) - { - if((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0) - { - VMA_ASSERT((inoutCreateInfo.flags & (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) != 0 && - "When using VMA_ALLOCATION_CREATE_MAPPED_BIT and usage = VMA_MEMORY_USAGE_AUTO*, you must also specify VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT."); - } - } - - // If memory is lazily allocated, it should be always dedicated. - if(dedicatedRequired || - inoutCreateInfo.usage == VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED) - { - inoutCreateInfo.flags |= VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT; - } - - if(inoutCreateInfo.pool != VK_NULL_HANDLE) - { - if(inoutCreateInfo.pool->m_BlockVector.HasExplicitBlockSize() && - (inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0) - { - VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT while current custom pool doesn't support dedicated allocations."); - return VK_ERROR_FEATURE_NOT_PRESENT; - } - inoutCreateInfo.priority = inoutCreateInfo.pool->m_BlockVector.GetPriority(); - } - - if((inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT) != 0 && - (inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0) - { - VMA_ASSERT(0 && "Specifying VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT together with VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT makes no sense."); - return VK_ERROR_FEATURE_NOT_PRESENT; - } - - if(VMA_DEBUG_ALWAYS_DEDICATED_MEMORY && - (inoutCreateInfo.flags & VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT) != 0) - { - inoutCreateInfo.flags |= VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT; - } - - // Non-auto USAGE values imply HOST_ACCESS flags. - // And so does VMA_MEMORY_USAGE_UNKNOWN because it is used with custom pools. - // Which specific flag is used doesn't matter. They change things only when used with VMA_MEMORY_USAGE_AUTO*. - // Otherwise they just protect from assert on mapping. - if(inoutCreateInfo.usage != VMA_MEMORY_USAGE_AUTO && - inoutCreateInfo.usage != VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE && - inoutCreateInfo.usage != VMA_MEMORY_USAGE_AUTO_PREFER_HOST) - { - if((inoutCreateInfo.flags & (VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT)) == 0) - { - inoutCreateInfo.flags |= VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT; - } - } - - return VK_SUCCESS; -} - -VkResult VmaAllocator_T::AllocateMemory( - const VkMemoryRequirements& vkMemReq, - bool requiresDedicatedAllocation, - bool prefersDedicatedAllocation, - VkBuffer dedicatedBuffer, - VkImage dedicatedImage, - VkFlags dedicatedBufferImageUsage, - const VmaAllocationCreateInfo& createInfo, - VmaSuballocationType suballocType, - size_t allocationCount, - VmaAllocation* pAllocations) -{ - memset(pAllocations, 0, sizeof(VmaAllocation) * allocationCount); - - VMA_ASSERT(VmaIsPow2(vkMemReq.alignment)); - - if(vkMemReq.size == 0) - { - return VK_ERROR_INITIALIZATION_FAILED; - } - - VmaAllocationCreateInfo createInfoFinal = createInfo; - VkResult res = CalcAllocationParams(createInfoFinal, requiresDedicatedAllocation, prefersDedicatedAllocation); - if(res != VK_SUCCESS) - return res; - - if(createInfoFinal.pool != VK_NULL_HANDLE) - { - VmaBlockVector& blockVector = createInfoFinal.pool->m_BlockVector; - return AllocateMemoryOfType( - createInfoFinal.pool, - vkMemReq.size, - vkMemReq.alignment, - prefersDedicatedAllocation, - dedicatedBuffer, - dedicatedImage, - dedicatedBufferImageUsage, - createInfoFinal, - blockVector.GetMemoryTypeIndex(), - suballocType, - createInfoFinal.pool->m_DedicatedAllocations, - blockVector, - allocationCount, - pAllocations); - } - else - { - // Bit mask of memory Vulkan types acceptable for this allocation. - uint32_t memoryTypeBits = vkMemReq.memoryTypeBits; - uint32_t memTypeIndex = UINT32_MAX; - res = FindMemoryTypeIndex(memoryTypeBits, &createInfoFinal, dedicatedBufferImageUsage, &memTypeIndex); - // Can't find any single memory type matching requirements. res is VK_ERROR_FEATURE_NOT_PRESENT. - if(res != VK_SUCCESS) - return res; - do - { - VmaBlockVector* blockVector = m_pBlockVectors[memTypeIndex]; - VMA_ASSERT(blockVector && "Trying to use unsupported memory type!"); - res = AllocateMemoryOfType( - VK_NULL_HANDLE, - vkMemReq.size, - vkMemReq.alignment, - requiresDedicatedAllocation || prefersDedicatedAllocation, - dedicatedBuffer, - dedicatedImage, - dedicatedBufferImageUsage, - createInfoFinal, - memTypeIndex, - suballocType, - m_DedicatedAllocations[memTypeIndex], - *blockVector, - allocationCount, - pAllocations); - // Allocation succeeded - if(res == VK_SUCCESS) - return VK_SUCCESS; - - // Remove old memTypeIndex from list of possibilities. - memoryTypeBits &= ~(1u << memTypeIndex); - // Find alternative memTypeIndex. - res = FindMemoryTypeIndex(memoryTypeBits, &createInfoFinal, dedicatedBufferImageUsage, &memTypeIndex); - } while(res == VK_SUCCESS); - - // No other matching memory type index could be found. - // Not returning res, which is VK_ERROR_FEATURE_NOT_PRESENT, because we already failed to allocate once. - return VK_ERROR_OUT_OF_DEVICE_MEMORY; - } -} - -void VmaAllocator_T::FreeMemory( - size_t allocationCount, - const VmaAllocation* pAllocations) -{ - VMA_ASSERT(pAllocations); - - for(size_t allocIndex = allocationCount; allocIndex--; ) - { - VmaAllocation allocation = pAllocations[allocIndex]; - - if(allocation != VK_NULL_HANDLE) - { - if(VMA_DEBUG_INITIALIZE_ALLOCATIONS) - { - FillAllocation(allocation, VMA_ALLOCATION_FILL_PATTERN_DESTROYED); - } - - allocation->FreeName(this); - - switch(allocation->GetType()) - { - case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: - { - VmaBlockVector* pBlockVector = VMA_NULL; - VmaPool hPool = allocation->GetParentPool(); - if(hPool != VK_NULL_HANDLE) - { - pBlockVector = &hPool->m_BlockVector; - } - else - { - const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex(); - pBlockVector = m_pBlockVectors[memTypeIndex]; - VMA_ASSERT(pBlockVector && "Trying to free memory of unsupported type!"); - } - pBlockVector->Free(allocation); - } - break; - case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: - FreeDedicatedMemory(allocation); - break; - default: - VMA_ASSERT(0); - } - } - } -} - -void VmaAllocator_T::CalculateStatistics(VmaTotalStatistics* pStats) -{ - // Initialize. - VmaClearDetailedStatistics(pStats->total); - for(uint32_t i = 0; i < VK_MAX_MEMORY_TYPES; ++i) - VmaClearDetailedStatistics(pStats->memoryType[i]); - for(uint32_t i = 0; i < VK_MAX_MEMORY_HEAPS; ++i) - VmaClearDetailedStatistics(pStats->memoryHeap[i]); - - // Process default pools. - for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) - { - VmaBlockVector* const pBlockVector = m_pBlockVectors[memTypeIndex]; - if (pBlockVector != VMA_NULL) - pBlockVector->AddDetailedStatistics(pStats->memoryType[memTypeIndex]); - } - - // Process custom pools. - { - VmaMutexLockRead lock(m_PoolsMutex, m_UseMutex); - for(VmaPool pool = m_Pools.Front(); pool != VMA_NULL; pool = m_Pools.GetNext(pool)) - { - VmaBlockVector& blockVector = pool->m_BlockVector; - const uint32_t memTypeIndex = blockVector.GetMemoryTypeIndex(); - blockVector.AddDetailedStatistics(pStats->memoryType[memTypeIndex]); - pool->m_DedicatedAllocations.AddDetailedStatistics(pStats->memoryType[memTypeIndex]); - } - } - - // Process dedicated allocations. - for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) - { - m_DedicatedAllocations[memTypeIndex].AddDetailedStatistics(pStats->memoryType[memTypeIndex]); - } - - // Sum from memory types to memory heaps. - for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) - { - const uint32_t memHeapIndex = m_MemProps.memoryTypes[memTypeIndex].heapIndex; - VmaAddDetailedStatistics(pStats->memoryHeap[memHeapIndex], pStats->memoryType[memTypeIndex]); - } - - // Sum from memory heaps to total. - for(uint32_t memHeapIndex = 0; memHeapIndex < GetMemoryHeapCount(); ++memHeapIndex) - VmaAddDetailedStatistics(pStats->total, pStats->memoryHeap[memHeapIndex]); - - VMA_ASSERT(pStats->total.statistics.allocationCount == 0 || - pStats->total.allocationSizeMax >= pStats->total.allocationSizeMin); - VMA_ASSERT(pStats->total.unusedRangeCount == 0 || - pStats->total.unusedRangeSizeMax >= pStats->total.unusedRangeSizeMin); -} - -void VmaAllocator_T::GetHeapBudgets(VmaBudget* outBudgets, uint32_t firstHeap, uint32_t heapCount) -{ -#if VMA_MEMORY_BUDGET - if(m_UseExtMemoryBudget) - { - if(m_Budget.m_OperationsSinceBudgetFetch < 30) - { - VmaMutexLockRead lockRead(m_Budget.m_BudgetMutex, m_UseMutex); - for(uint32_t i = 0; i < heapCount; ++i, ++outBudgets) - { - const uint32_t heapIndex = firstHeap + i; - - outBudgets->statistics.blockCount = m_Budget.m_BlockCount[heapIndex]; - outBudgets->statistics.allocationCount = m_Budget.m_AllocationCount[heapIndex]; - outBudgets->statistics.blockBytes = m_Budget.m_BlockBytes[heapIndex]; - outBudgets->statistics.allocationBytes = m_Budget.m_AllocationBytes[heapIndex]; - - if(m_Budget.m_VulkanUsage[heapIndex] + outBudgets->statistics.blockBytes > m_Budget.m_BlockBytesAtBudgetFetch[heapIndex]) - { - outBudgets->usage = m_Budget.m_VulkanUsage[heapIndex] + - outBudgets->statistics.blockBytes - m_Budget.m_BlockBytesAtBudgetFetch[heapIndex]; - } - else - { - outBudgets->usage = 0; - } - - // Have to take MIN with heap size because explicit HeapSizeLimit is included in it. - outBudgets->budget = VMA_MIN( - m_Budget.m_VulkanBudget[heapIndex], m_MemProps.memoryHeaps[heapIndex].size); - } - } - else - { - UpdateVulkanBudget(); // Outside of mutex lock - GetHeapBudgets(outBudgets, firstHeap, heapCount); // Recursion - } - } - else -#endif - { - for(uint32_t i = 0; i < heapCount; ++i, ++outBudgets) - { - const uint32_t heapIndex = firstHeap + i; - - outBudgets->statistics.blockCount = m_Budget.m_BlockCount[heapIndex]; - outBudgets->statistics.allocationCount = m_Budget.m_AllocationCount[heapIndex]; - outBudgets->statistics.blockBytes = m_Budget.m_BlockBytes[heapIndex]; - outBudgets->statistics.allocationBytes = m_Budget.m_AllocationBytes[heapIndex]; - - outBudgets->usage = outBudgets->statistics.blockBytes; - outBudgets->budget = m_MemProps.memoryHeaps[heapIndex].size * 8 / 10; // 80% heuristics. - } - } -} - -void VmaAllocator_T::GetAllocationInfo(VmaAllocation hAllocation, VmaAllocationInfo* pAllocationInfo) -{ - pAllocationInfo->memoryType = hAllocation->GetMemoryTypeIndex(); - pAllocationInfo->deviceMemory = hAllocation->GetMemory(); - pAllocationInfo->offset = hAllocation->GetOffset(); - pAllocationInfo->size = hAllocation->GetSize(); - pAllocationInfo->pMappedData = hAllocation->GetMappedData(); - pAllocationInfo->pUserData = hAllocation->GetUserData(); - pAllocationInfo->pName = hAllocation->GetName(); -} - -VkResult VmaAllocator_T::CreatePool(const VmaPoolCreateInfo* pCreateInfo, VmaPool* pPool) -{ - VMA_DEBUG_LOG(" CreatePool: MemoryTypeIndex=%u, flags=%u", pCreateInfo->memoryTypeIndex, pCreateInfo->flags); - - VmaPoolCreateInfo newCreateInfo = *pCreateInfo; - - // Protection against uninitialized new structure member. If garbage data are left there, this pointer dereference would crash. - if(pCreateInfo->pMemoryAllocateNext) - { - VMA_ASSERT(((const VkBaseInStructure*)pCreateInfo->pMemoryAllocateNext)->sType != 0); - } - - if(newCreateInfo.maxBlockCount == 0) - { - newCreateInfo.maxBlockCount = SIZE_MAX; - } - if(newCreateInfo.minBlockCount > newCreateInfo.maxBlockCount) - { - return VK_ERROR_INITIALIZATION_FAILED; - } - // Memory type index out of range or forbidden. - if(pCreateInfo->memoryTypeIndex >= GetMemoryTypeCount() || - ((1u << pCreateInfo->memoryTypeIndex) & m_GlobalMemoryTypeBits) == 0) - { - return VK_ERROR_FEATURE_NOT_PRESENT; - } - if(newCreateInfo.minAllocationAlignment > 0) - { - VMA_ASSERT(VmaIsPow2(newCreateInfo.minAllocationAlignment)); - } - - const VkDeviceSize preferredBlockSize = CalcPreferredBlockSize(newCreateInfo.memoryTypeIndex); - - *pPool = vma_new(this, VmaPool_T)(this, newCreateInfo, preferredBlockSize); - - VkResult res = (*pPool)->m_BlockVector.CreateMinBlocks(); - if(res != VK_SUCCESS) - { - vma_delete(this, *pPool); - *pPool = VMA_NULL; - return res; - } - - // Add to m_Pools. - { - VmaMutexLockWrite lock(m_PoolsMutex, m_UseMutex); - (*pPool)->SetId(m_NextPoolId++); - m_Pools.PushBack(*pPool); - } - - return VK_SUCCESS; -} - -void VmaAllocator_T::DestroyPool(VmaPool pool) -{ - // Remove from m_Pools. - { - VmaMutexLockWrite lock(m_PoolsMutex, m_UseMutex); - m_Pools.Remove(pool); - } - - vma_delete(this, pool); -} - -void VmaAllocator_T::GetPoolStatistics(VmaPool pool, VmaStatistics* pPoolStats) -{ - VmaClearStatistics(*pPoolStats); - pool->m_BlockVector.AddStatistics(*pPoolStats); - pool->m_DedicatedAllocations.AddStatistics(*pPoolStats); -} - -void VmaAllocator_T::CalculatePoolStatistics(VmaPool pool, VmaDetailedStatistics* pPoolStats) -{ - VmaClearDetailedStatistics(*pPoolStats); - pool->m_BlockVector.AddDetailedStatistics(*pPoolStats); - pool->m_DedicatedAllocations.AddDetailedStatistics(*pPoolStats); -} - -void VmaAllocator_T::SetCurrentFrameIndex(uint32_t frameIndex) -{ - m_CurrentFrameIndex.store(frameIndex); - -#if VMA_MEMORY_BUDGET - if(m_UseExtMemoryBudget) - { - UpdateVulkanBudget(); - } -#endif // #if VMA_MEMORY_BUDGET -} - -VkResult VmaAllocator_T::CheckPoolCorruption(VmaPool hPool) -{ - return hPool->m_BlockVector.CheckCorruption(); -} - -VkResult VmaAllocator_T::CheckCorruption(uint32_t memoryTypeBits) -{ - VkResult finalRes = VK_ERROR_FEATURE_NOT_PRESENT; - - // Process default pools. - for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) - { - VmaBlockVector* const pBlockVector = m_pBlockVectors[memTypeIndex]; - if(pBlockVector != VMA_NULL) - { - VkResult localRes = pBlockVector->CheckCorruption(); - switch(localRes) - { - case VK_ERROR_FEATURE_NOT_PRESENT: - break; - case VK_SUCCESS: - finalRes = VK_SUCCESS; - break; - default: - return localRes; - } - } - } - - // Process custom pools. - { - VmaMutexLockRead lock(m_PoolsMutex, m_UseMutex); - for(VmaPool pool = m_Pools.Front(); pool != VMA_NULL; pool = m_Pools.GetNext(pool)) - { - if(((1u << pool->m_BlockVector.GetMemoryTypeIndex()) & memoryTypeBits) != 0) - { - VkResult localRes = pool->m_BlockVector.CheckCorruption(); - switch(localRes) - { - case VK_ERROR_FEATURE_NOT_PRESENT: - break; - case VK_SUCCESS: - finalRes = VK_SUCCESS; - break; - default: - return localRes; - } - } - } - } - - return finalRes; -} - -VkResult VmaAllocator_T::AllocateVulkanMemory(const VkMemoryAllocateInfo* pAllocateInfo, VkDeviceMemory* pMemory) -{ - AtomicTransactionalIncrement deviceMemoryCountIncrement; - const uint64_t prevDeviceMemoryCount = deviceMemoryCountIncrement.Increment(&m_DeviceMemoryCount); -#if VMA_DEBUG_DONT_EXCEED_MAX_MEMORY_ALLOCATION_COUNT - if(prevDeviceMemoryCount >= m_PhysicalDeviceProperties.limits.maxMemoryAllocationCount) - { - return VK_ERROR_TOO_MANY_OBJECTS; - } -#endif - - const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(pAllocateInfo->memoryTypeIndex); - - // HeapSizeLimit is in effect for this heap. - if((m_HeapSizeLimitMask & (1u << heapIndex)) != 0) - { - const VkDeviceSize heapSize = m_MemProps.memoryHeaps[heapIndex].size; - VkDeviceSize blockBytes = m_Budget.m_BlockBytes[heapIndex]; - for(;;) - { - const VkDeviceSize blockBytesAfterAllocation = blockBytes + pAllocateInfo->allocationSize; - if(blockBytesAfterAllocation > heapSize) - { - return VK_ERROR_OUT_OF_DEVICE_MEMORY; - } - if(m_Budget.m_BlockBytes[heapIndex].compare_exchange_strong(blockBytes, blockBytesAfterAllocation)) - { - break; - } - } - } - else - { - m_Budget.m_BlockBytes[heapIndex] += pAllocateInfo->allocationSize; - } - ++m_Budget.m_BlockCount[heapIndex]; - - // VULKAN CALL vkAllocateMemory. - VkResult res = (*m_VulkanFunctions.vkAllocateMemory)(m_hDevice, pAllocateInfo, GetAllocationCallbacks(), pMemory); - - if(res == VK_SUCCESS) - { -#if VMA_MEMORY_BUDGET - ++m_Budget.m_OperationsSinceBudgetFetch; -#endif - - // Informative callback. - if(m_DeviceMemoryCallbacks.pfnAllocate != VMA_NULL) - { - (*m_DeviceMemoryCallbacks.pfnAllocate)(this, pAllocateInfo->memoryTypeIndex, *pMemory, pAllocateInfo->allocationSize, m_DeviceMemoryCallbacks.pUserData); - } - - deviceMemoryCountIncrement.Commit(); - } - else - { - --m_Budget.m_BlockCount[heapIndex]; - m_Budget.m_BlockBytes[heapIndex] -= pAllocateInfo->allocationSize; - } - - return res; -} - -void VmaAllocator_T::FreeVulkanMemory(uint32_t memoryType, VkDeviceSize size, VkDeviceMemory hMemory) -{ - // Informative callback. - if(m_DeviceMemoryCallbacks.pfnFree != VMA_NULL) - { - (*m_DeviceMemoryCallbacks.pfnFree)(this, memoryType, hMemory, size, m_DeviceMemoryCallbacks.pUserData); - } - - // VULKAN CALL vkFreeMemory. - (*m_VulkanFunctions.vkFreeMemory)(m_hDevice, hMemory, GetAllocationCallbacks()); - - const uint32_t heapIndex = MemoryTypeIndexToHeapIndex(memoryType); - --m_Budget.m_BlockCount[heapIndex]; - m_Budget.m_BlockBytes[heapIndex] -= size; - - --m_DeviceMemoryCount; -} - -VkResult VmaAllocator_T::BindVulkanBuffer( - VkDeviceMemory memory, - VkDeviceSize memoryOffset, - VkBuffer buffer, - const void* pNext) -{ - if(pNext != VMA_NULL) - { -#if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2 - if((m_UseKhrBindMemory2 || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) && - m_VulkanFunctions.vkBindBufferMemory2KHR != VMA_NULL) - { - VkBindBufferMemoryInfoKHR bindBufferMemoryInfo = { VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHR }; - bindBufferMemoryInfo.pNext = pNext; - bindBufferMemoryInfo.buffer = buffer; - bindBufferMemoryInfo.memory = memory; - bindBufferMemoryInfo.memoryOffset = memoryOffset; - return (*m_VulkanFunctions.vkBindBufferMemory2KHR)(m_hDevice, 1, &bindBufferMemoryInfo); - } - else -#endif // #if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2 - { - return VK_ERROR_EXTENSION_NOT_PRESENT; - } - } - else - { - return (*m_VulkanFunctions.vkBindBufferMemory)(m_hDevice, buffer, memory, memoryOffset); - } -} - -VkResult VmaAllocator_T::BindVulkanImage( - VkDeviceMemory memory, - VkDeviceSize memoryOffset, - VkImage image, - const void* pNext) -{ - if(pNext != VMA_NULL) - { -#if VMA_VULKAN_VERSION >= 1001000 || VMA_BIND_MEMORY2 - if((m_UseKhrBindMemory2 || m_VulkanApiVersion >= VK_MAKE_VERSION(1, 1, 0)) && - m_VulkanFunctions.vkBindImageMemory2KHR != VMA_NULL) - { - VkBindImageMemoryInfoKHR bindBufferMemoryInfo = { VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO_KHR }; - bindBufferMemoryInfo.pNext = pNext; - bindBufferMemoryInfo.image = image; - bindBufferMemoryInfo.memory = memory; - bindBufferMemoryInfo.memoryOffset = memoryOffset; - return (*m_VulkanFunctions.vkBindImageMemory2KHR)(m_hDevice, 1, &bindBufferMemoryInfo); - } - else -#endif // #if VMA_BIND_MEMORY2 - { - return VK_ERROR_EXTENSION_NOT_PRESENT; - } - } - else - { - return (*m_VulkanFunctions.vkBindImageMemory)(m_hDevice, image, memory, memoryOffset); - } -} - -VkResult VmaAllocator_T::Map(VmaAllocation hAllocation, void** ppData) -{ - switch(hAllocation->GetType()) - { - case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: - { - VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock(); - char *pBytes = VMA_NULL; - VkResult res = pBlock->Map(this, 1, (void**)&pBytes); - if(res == VK_SUCCESS) - { - *ppData = pBytes + (ptrdiff_t)hAllocation->GetOffset(); - hAllocation->BlockAllocMap(); - } - return res; - } - case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: - return hAllocation->DedicatedAllocMap(this, ppData); - default: - VMA_ASSERT(0); - return VK_ERROR_MEMORY_MAP_FAILED; - } -} - -void VmaAllocator_T::Unmap(VmaAllocation hAllocation) -{ - switch(hAllocation->GetType()) - { - case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: - { - VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock(); - hAllocation->BlockAllocUnmap(); - pBlock->Unmap(this, 1); - } - break; - case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: - hAllocation->DedicatedAllocUnmap(this); - break; - default: - VMA_ASSERT(0); - } -} - -VkResult VmaAllocator_T::BindBufferMemory( - VmaAllocation hAllocation, - VkDeviceSize allocationLocalOffset, - VkBuffer hBuffer, - const void* pNext) -{ - VkResult res = VK_SUCCESS; - switch(hAllocation->GetType()) - { - case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: - res = BindVulkanBuffer(hAllocation->GetMemory(), allocationLocalOffset, hBuffer, pNext); - break; - case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: - { - VmaDeviceMemoryBlock* const pBlock = hAllocation->GetBlock(); - VMA_ASSERT(pBlock && "Binding buffer to allocation that doesn't belong to any block."); - res = pBlock->BindBufferMemory(this, hAllocation, allocationLocalOffset, hBuffer, pNext); - break; - } - default: - VMA_ASSERT(0); - } - return res; -} - -VkResult VmaAllocator_T::BindImageMemory( - VmaAllocation hAllocation, - VkDeviceSize allocationLocalOffset, - VkImage hImage, - const void* pNext) -{ - VkResult res = VK_SUCCESS; - switch(hAllocation->GetType()) - { - case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: - res = BindVulkanImage(hAllocation->GetMemory(), allocationLocalOffset, hImage, pNext); - break; - case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: - { - VmaDeviceMemoryBlock* pBlock = hAllocation->GetBlock(); - VMA_ASSERT(pBlock && "Binding image to allocation that doesn't belong to any block."); - res = pBlock->BindImageMemory(this, hAllocation, allocationLocalOffset, hImage, pNext); - break; - } - default: - VMA_ASSERT(0); - } - return res; -} - -VkResult VmaAllocator_T::FlushOrInvalidateAllocation( - VmaAllocation hAllocation, - VkDeviceSize offset, VkDeviceSize size, - VMA_CACHE_OPERATION op) -{ - VkResult res = VK_SUCCESS; - - VkMappedMemoryRange memRange = {}; - if(GetFlushOrInvalidateRange(hAllocation, offset, size, memRange)) - { - switch(op) - { - case VMA_CACHE_FLUSH: - res = (*GetVulkanFunctions().vkFlushMappedMemoryRanges)(m_hDevice, 1, &memRange); - break; - case VMA_CACHE_INVALIDATE: - res = (*GetVulkanFunctions().vkInvalidateMappedMemoryRanges)(m_hDevice, 1, &memRange); - break; - default: - VMA_ASSERT(0); - } - } - // else: Just ignore this call. - return res; -} - -VkResult VmaAllocator_T::FlushOrInvalidateAllocations( - uint32_t allocationCount, - const VmaAllocation* allocations, - const VkDeviceSize* offsets, const VkDeviceSize* sizes, - VMA_CACHE_OPERATION op) -{ - typedef VmaStlAllocator RangeAllocator; - typedef VmaSmallVector RangeVector; - RangeVector ranges = RangeVector(RangeAllocator(GetAllocationCallbacks())); - - for(uint32_t allocIndex = 0; allocIndex < allocationCount; ++allocIndex) - { - const VmaAllocation alloc = allocations[allocIndex]; - const VkDeviceSize offset = offsets != VMA_NULL ? offsets[allocIndex] : 0; - const VkDeviceSize size = sizes != VMA_NULL ? sizes[allocIndex] : VK_WHOLE_SIZE; - VkMappedMemoryRange newRange; - if(GetFlushOrInvalidateRange(alloc, offset, size, newRange)) - { - ranges.push_back(newRange); - } - } - - VkResult res = VK_SUCCESS; - if(!ranges.empty()) - { - switch(op) - { - case VMA_CACHE_FLUSH: - res = (*GetVulkanFunctions().vkFlushMappedMemoryRanges)(m_hDevice, (uint32_t)ranges.size(), ranges.data()); - break; - case VMA_CACHE_INVALIDATE: - res = (*GetVulkanFunctions().vkInvalidateMappedMemoryRanges)(m_hDevice, (uint32_t)ranges.size(), ranges.data()); - break; - default: - VMA_ASSERT(0); - } - } - // else: Just ignore this call. - return res; -} - -void VmaAllocator_T::FreeDedicatedMemory(const VmaAllocation allocation) -{ - VMA_ASSERT(allocation && allocation->GetType() == VmaAllocation_T::ALLOCATION_TYPE_DEDICATED); - - const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex(); - VmaPool parentPool = allocation->GetParentPool(); - if(parentPool == VK_NULL_HANDLE) - { - // Default pool - m_DedicatedAllocations[memTypeIndex].Unregister(allocation); - } - else - { - // Custom pool - parentPool->m_DedicatedAllocations.Unregister(allocation); - } - - VkDeviceMemory hMemory = allocation->GetMemory(); - - /* - There is no need to call this, because Vulkan spec allows to skip vkUnmapMemory - before vkFreeMemory. - - if(allocation->GetMappedData() != VMA_NULL) - { - (*m_VulkanFunctions.vkUnmapMemory)(m_hDevice, hMemory); - } - */ - - FreeVulkanMemory(memTypeIndex, allocation->GetSize(), hMemory); - - m_Budget.RemoveAllocation(MemoryTypeIndexToHeapIndex(allocation->GetMemoryTypeIndex()), allocation->GetSize()); - m_AllocationObjectAllocator.Free(allocation); - - VMA_DEBUG_LOG(" Freed DedicatedMemory MemoryTypeIndex=%u", memTypeIndex); -} - -uint32_t VmaAllocator_T::CalculateGpuDefragmentationMemoryTypeBits() const -{ - VkBufferCreateInfo dummyBufCreateInfo; - VmaFillGpuDefragmentationBufferCreateInfo(dummyBufCreateInfo); - - uint32_t memoryTypeBits = 0; - - // Create buffer. - VkBuffer buf = VK_NULL_HANDLE; - VkResult res = (*GetVulkanFunctions().vkCreateBuffer)( - m_hDevice, &dummyBufCreateInfo, GetAllocationCallbacks(), &buf); - if(res == VK_SUCCESS) - { - // Query for supported memory types. - VkMemoryRequirements memReq; - (*GetVulkanFunctions().vkGetBufferMemoryRequirements)(m_hDevice, buf, &memReq); - memoryTypeBits = memReq.memoryTypeBits; - - // Destroy buffer. - (*GetVulkanFunctions().vkDestroyBuffer)(m_hDevice, buf, GetAllocationCallbacks()); - } - - return memoryTypeBits; -} - -uint32_t VmaAllocator_T::CalculateGlobalMemoryTypeBits() const -{ - // Make sure memory information is already fetched. - VMA_ASSERT(GetMemoryTypeCount() > 0); - - uint32_t memoryTypeBits = UINT32_MAX; - - if(!m_UseAmdDeviceCoherentMemory) - { - // Exclude memory types that have VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD. - for(uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) - { - if((m_MemProps.memoryTypes[memTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY) != 0) - { - memoryTypeBits &= ~(1u << memTypeIndex); - } - } - } - - return memoryTypeBits; -} - -bool VmaAllocator_T::GetFlushOrInvalidateRange( - VmaAllocation allocation, - VkDeviceSize offset, VkDeviceSize size, - VkMappedMemoryRange& outRange) const -{ - const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex(); - if(size > 0 && IsMemoryTypeNonCoherent(memTypeIndex)) - { - const VkDeviceSize nonCoherentAtomSize = m_PhysicalDeviceProperties.limits.nonCoherentAtomSize; - const VkDeviceSize allocationSize = allocation->GetSize(); - VMA_ASSERT(offset <= allocationSize); - - outRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; - outRange.pNext = VMA_NULL; - outRange.memory = allocation->GetMemory(); - - switch(allocation->GetType()) - { - case VmaAllocation_T::ALLOCATION_TYPE_DEDICATED: - outRange.offset = VmaAlignDown(offset, nonCoherentAtomSize); - if(size == VK_WHOLE_SIZE) - { - outRange.size = allocationSize - outRange.offset; - } - else - { - VMA_ASSERT(offset + size <= allocationSize); - outRange.size = VMA_MIN( - VmaAlignUp(size + (offset - outRange.offset), nonCoherentAtomSize), - allocationSize - outRange.offset); - } - break; - case VmaAllocation_T::ALLOCATION_TYPE_BLOCK: - { - // 1. Still within this allocation. - outRange.offset = VmaAlignDown(offset, nonCoherentAtomSize); - if(size == VK_WHOLE_SIZE) - { - size = allocationSize - offset; - } - else - { - VMA_ASSERT(offset + size <= allocationSize); - } - outRange.size = VmaAlignUp(size + (offset - outRange.offset), nonCoherentAtomSize); - - // 2. Adjust to whole block. - const VkDeviceSize allocationOffset = allocation->GetOffset(); - VMA_ASSERT(allocationOffset % nonCoherentAtomSize == 0); - const VkDeviceSize blockSize = allocation->GetBlock()->m_pMetadata->GetSize(); - outRange.offset += allocationOffset; - outRange.size = VMA_MIN(outRange.size, blockSize - outRange.offset); - - break; - } - default: - VMA_ASSERT(0); - } - return true; - } - return false; -} - -#if VMA_MEMORY_BUDGET -void VmaAllocator_T::UpdateVulkanBudget() -{ - VMA_ASSERT(m_UseExtMemoryBudget); - - VkPhysicalDeviceMemoryProperties2KHR memProps = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2_KHR }; - - VkPhysicalDeviceMemoryBudgetPropertiesEXT budgetProps = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT }; - VmaPnextChainPushFront(&memProps, &budgetProps); - - GetVulkanFunctions().vkGetPhysicalDeviceMemoryProperties2KHR(m_PhysicalDevice, &memProps); - - { - VmaMutexLockWrite lockWrite(m_Budget.m_BudgetMutex, m_UseMutex); - - for(uint32_t heapIndex = 0; heapIndex < GetMemoryHeapCount(); ++heapIndex) - { - m_Budget.m_VulkanUsage[heapIndex] = budgetProps.heapUsage[heapIndex]; - m_Budget.m_VulkanBudget[heapIndex] = budgetProps.heapBudget[heapIndex]; - m_Budget.m_BlockBytesAtBudgetFetch[heapIndex] = m_Budget.m_BlockBytes[heapIndex].load(); - - // Some bugged drivers return the budget incorrectly, e.g. 0 or much bigger than heap size. - if(m_Budget.m_VulkanBudget[heapIndex] == 0) - { - m_Budget.m_VulkanBudget[heapIndex] = m_MemProps.memoryHeaps[heapIndex].size * 8 / 10; // 80% heuristics. - } - else if(m_Budget.m_VulkanBudget[heapIndex] > m_MemProps.memoryHeaps[heapIndex].size) - { - m_Budget.m_VulkanBudget[heapIndex] = m_MemProps.memoryHeaps[heapIndex].size; - } - if(m_Budget.m_VulkanUsage[heapIndex] == 0 && m_Budget.m_BlockBytesAtBudgetFetch[heapIndex] > 0) - { - m_Budget.m_VulkanUsage[heapIndex] = m_Budget.m_BlockBytesAtBudgetFetch[heapIndex]; - } - } - m_Budget.m_OperationsSinceBudgetFetch = 0; - } -} -#endif // VMA_MEMORY_BUDGET - -void VmaAllocator_T::FillAllocation(const VmaAllocation hAllocation, uint8_t pattern) -{ - if(VMA_DEBUG_INITIALIZE_ALLOCATIONS && - hAllocation->IsMappingAllowed() && - (m_MemProps.memoryTypes[hAllocation->GetMemoryTypeIndex()].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0) - { - void* pData = VMA_NULL; - VkResult res = Map(hAllocation, &pData); - if(res == VK_SUCCESS) - { - memset(pData, (int)pattern, (size_t)hAllocation->GetSize()); - FlushOrInvalidateAllocation(hAllocation, 0, VK_WHOLE_SIZE, VMA_CACHE_FLUSH); - Unmap(hAllocation); - } - else - { - VMA_ASSERT(0 && "VMA_DEBUG_INITIALIZE_ALLOCATIONS is enabled, but couldn't map memory to fill allocation."); - } - } -} - -uint32_t VmaAllocator_T::GetGpuDefragmentationMemoryTypeBits() -{ - uint32_t memoryTypeBits = m_GpuDefragmentationMemoryTypeBits.load(); - if(memoryTypeBits == UINT32_MAX) - { - memoryTypeBits = CalculateGpuDefragmentationMemoryTypeBits(); - m_GpuDefragmentationMemoryTypeBits.store(memoryTypeBits); - } - return memoryTypeBits; -} - -#if VMA_STATS_STRING_ENABLED -void VmaAllocator_T::PrintDetailedMap(VmaJsonWriter& json) -{ - json.WriteString("DefaultPools"); - json.BeginObject(); - { - for (uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) - { - VmaBlockVector* pBlockVector = m_pBlockVectors[memTypeIndex]; - VmaDedicatedAllocationList& dedicatedAllocList = m_DedicatedAllocations[memTypeIndex]; - if (pBlockVector != VMA_NULL) - { - json.BeginString("Type "); - json.ContinueString(memTypeIndex); - json.EndString(); - json.BeginObject(); - { - json.WriteString("PreferredBlockSize"); - json.WriteNumber(pBlockVector->GetPreferredBlockSize()); - - json.WriteString("Blocks"); - pBlockVector->PrintDetailedMap(json); - - json.WriteString("DedicatedAllocations"); - dedicatedAllocList.BuildStatsString(json); - } - json.EndObject(); - } - } - } - json.EndObject(); - - json.WriteString("CustomPools"); - json.BeginObject(); - { - VmaMutexLockRead lock(m_PoolsMutex, m_UseMutex); - if (!m_Pools.IsEmpty()) - { - for (uint32_t memTypeIndex = 0; memTypeIndex < GetMemoryTypeCount(); ++memTypeIndex) - { - bool displayType = true; - size_t index = 0; - for (VmaPool pool = m_Pools.Front(); pool != VMA_NULL; pool = m_Pools.GetNext(pool)) - { - VmaBlockVector& blockVector = pool->m_BlockVector; - if (blockVector.GetMemoryTypeIndex() == memTypeIndex) - { - if (displayType) - { - json.BeginString("Type "); - json.ContinueString(memTypeIndex); - json.EndString(); - json.BeginArray(); - displayType = false; - } - - json.BeginObject(); - { - json.WriteString("Name"); - json.BeginString(); - json.ContinueString_Size(index++); - if (pool->GetName()) - { - json.ContinueString(" - "); - json.ContinueString(pool->GetName()); - } - json.EndString(); - - json.WriteString("PreferredBlockSize"); - json.WriteNumber(blockVector.GetPreferredBlockSize()); - - json.WriteString("Blocks"); - blockVector.PrintDetailedMap(json); - - json.WriteString("DedicatedAllocations"); - pool->m_DedicatedAllocations.BuildStatsString(json); - } - json.EndObject(); - } - } - - if (!displayType) - json.EndArray(); - } - } - } - json.EndObject(); -} -#endif // VMA_STATS_STRING_ENABLED -#endif // _VMA_ALLOCATOR_T_FUNCTIONS - - -#ifndef _VMA_PUBLIC_INTERFACE -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAllocator( - const VmaAllocatorCreateInfo* pCreateInfo, - VmaAllocator* pAllocator) -{ - VMA_ASSERT(pCreateInfo && pAllocator); - VMA_ASSERT(pCreateInfo->vulkanApiVersion == 0 || - (VK_VERSION_MAJOR(pCreateInfo->vulkanApiVersion) == 1 && VK_VERSION_MINOR(pCreateInfo->vulkanApiVersion) <= 3)); - VMA_DEBUG_LOG("vmaCreateAllocator"); - *pAllocator = vma_new(pCreateInfo->pAllocationCallbacks, VmaAllocator_T)(pCreateInfo); - VkResult result = (*pAllocator)->Init(pCreateInfo); - if(result < 0) - { - vma_delete(pCreateInfo->pAllocationCallbacks, *pAllocator); - *pAllocator = VK_NULL_HANDLE; - } - return result; -} - -VMA_CALL_PRE void VMA_CALL_POST vmaDestroyAllocator( - VmaAllocator allocator) -{ - if(allocator != VK_NULL_HANDLE) - { - VMA_DEBUG_LOG("vmaDestroyAllocator"); - VkAllocationCallbacks allocationCallbacks = allocator->m_AllocationCallbacks; // Have to copy the callbacks when destroying. - vma_delete(&allocationCallbacks, allocator); - } -} - -VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocatorInfo(VmaAllocator allocator, VmaAllocatorInfo* pAllocatorInfo) -{ - VMA_ASSERT(allocator && pAllocatorInfo); - pAllocatorInfo->instance = allocator->m_hInstance; - pAllocatorInfo->physicalDevice = allocator->GetPhysicalDevice(); - pAllocatorInfo->device = allocator->m_hDevice; -} - -VMA_CALL_PRE void VMA_CALL_POST vmaGetPhysicalDeviceProperties( - VmaAllocator allocator, - const VkPhysicalDeviceProperties **ppPhysicalDeviceProperties) -{ - VMA_ASSERT(allocator && ppPhysicalDeviceProperties); - *ppPhysicalDeviceProperties = &allocator->m_PhysicalDeviceProperties; -} - -VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryProperties( - VmaAllocator allocator, - const VkPhysicalDeviceMemoryProperties** ppPhysicalDeviceMemoryProperties) -{ - VMA_ASSERT(allocator && ppPhysicalDeviceMemoryProperties); - *ppPhysicalDeviceMemoryProperties = &allocator->m_MemProps; -} - -VMA_CALL_PRE void VMA_CALL_POST vmaGetMemoryTypeProperties( - VmaAllocator allocator, - uint32_t memoryTypeIndex, - VkMemoryPropertyFlags* pFlags) -{ - VMA_ASSERT(allocator && pFlags); - VMA_ASSERT(memoryTypeIndex < allocator->GetMemoryTypeCount()); - *pFlags = allocator->m_MemProps.memoryTypes[memoryTypeIndex].propertyFlags; -} - -VMA_CALL_PRE void VMA_CALL_POST vmaSetCurrentFrameIndex( - VmaAllocator allocator, - uint32_t frameIndex) -{ - VMA_ASSERT(allocator); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - allocator->SetCurrentFrameIndex(frameIndex); -} - -VMA_CALL_PRE void VMA_CALL_POST vmaCalculateStatistics( - VmaAllocator allocator, - VmaTotalStatistics* pStats) -{ - VMA_ASSERT(allocator && pStats); - VMA_DEBUG_GLOBAL_MUTEX_LOCK - allocator->CalculateStatistics(pStats); -} - -VMA_CALL_PRE void VMA_CALL_POST vmaGetHeapBudgets( - VmaAllocator allocator, - VmaBudget* pBudgets) -{ - VMA_ASSERT(allocator && pBudgets); - VMA_DEBUG_GLOBAL_MUTEX_LOCK - allocator->GetHeapBudgets(pBudgets, 0, allocator->GetMemoryHeapCount()); -} - -#if VMA_STATS_STRING_ENABLED - -VMA_CALL_PRE void VMA_CALL_POST vmaBuildStatsString( - VmaAllocator allocator, - char** ppStatsString, - VkBool32 detailedMap) -{ - VMA_ASSERT(allocator && ppStatsString); - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - VmaStringBuilder sb(allocator->GetAllocationCallbacks()); - { - VmaBudget budgets[VK_MAX_MEMORY_HEAPS]; - allocator->GetHeapBudgets(budgets, 0, allocator->GetMemoryHeapCount()); - - VmaTotalStatistics stats; - allocator->CalculateStatistics(&stats); - - VmaJsonWriter json(allocator->GetAllocationCallbacks(), sb); - json.BeginObject(); - { - json.WriteString("General"); - json.BeginObject(); - { - const VkPhysicalDeviceProperties& deviceProperties = allocator->m_PhysicalDeviceProperties; - const VkPhysicalDeviceMemoryProperties& memoryProperties = allocator->m_MemProps; - - json.WriteString("API"); - json.WriteString("Vulkan"); - - json.WriteString("apiVersion"); - json.BeginString(); - json.ContinueString(VK_VERSION_MAJOR(deviceProperties.apiVersion)); - json.ContinueString("."); - json.ContinueString(VK_VERSION_MINOR(deviceProperties.apiVersion)); - json.ContinueString("."); - json.ContinueString(VK_VERSION_PATCH(deviceProperties.apiVersion)); - json.EndString(); - - json.WriteString("GPU"); - json.WriteString(deviceProperties.deviceName); - json.WriteString("deviceType"); - json.WriteNumber(static_cast(deviceProperties.deviceType)); - - json.WriteString("maxMemoryAllocationCount"); - json.WriteNumber(deviceProperties.limits.maxMemoryAllocationCount); - json.WriteString("bufferImageGranularity"); - json.WriteNumber(deviceProperties.limits.bufferImageGranularity); - json.WriteString("nonCoherentAtomSize"); - json.WriteNumber(deviceProperties.limits.nonCoherentAtomSize); - - json.WriteString("memoryHeapCount"); - json.WriteNumber(memoryProperties.memoryHeapCount); - json.WriteString("memoryTypeCount"); - json.WriteNumber(memoryProperties.memoryTypeCount); - } - json.EndObject(); - } - { - json.WriteString("Total"); - VmaPrintDetailedStatistics(json, stats.total); - } - { - json.WriteString("MemoryInfo"); - json.BeginObject(); - { - for (uint32_t heapIndex = 0; heapIndex < allocator->GetMemoryHeapCount(); ++heapIndex) - { - json.BeginString("Heap "); - json.ContinueString(heapIndex); - json.EndString(); - json.BeginObject(); - { - const VkMemoryHeap& heapInfo = allocator->m_MemProps.memoryHeaps[heapIndex]; - json.WriteString("Flags"); - json.BeginArray(true); - { - if (heapInfo.flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) - json.WriteString("DEVICE_LOCAL"); - #if VMA_VULKAN_VERSION >= 1001000 - if (heapInfo.flags & VK_MEMORY_HEAP_MULTI_INSTANCE_BIT) - json.WriteString("MULTI_INSTANCE"); - #endif - - VkMemoryHeapFlags flags = heapInfo.flags & - ~(VK_MEMORY_HEAP_DEVICE_LOCAL_BIT - #if VMA_VULKAN_VERSION >= 1001000 - | VK_MEMORY_HEAP_MULTI_INSTANCE_BIT - #endif - ); - if (flags != 0) - json.WriteNumber(flags); - } - json.EndArray(); - - json.WriteString("Size"); - json.WriteNumber(heapInfo.size); - - json.WriteString("Budget"); - json.BeginObject(); - { - json.WriteString("BudgetBytes"); - json.WriteNumber(budgets[heapIndex].budget); - json.WriteString("UsageBytes"); - json.WriteNumber(budgets[heapIndex].usage); - } - json.EndObject(); - - json.WriteString("Stats"); - VmaPrintDetailedStatistics(json, stats.memoryHeap[heapIndex]); - - json.WriteString("MemoryPools"); - json.BeginObject(); - { - for (uint32_t typeIndex = 0; typeIndex < allocator->GetMemoryTypeCount(); ++typeIndex) - { - if (allocator->MemoryTypeIndexToHeapIndex(typeIndex) == heapIndex) - { - json.BeginString("Type "); - json.ContinueString(typeIndex); - json.EndString(); - json.BeginObject(); - { - json.WriteString("Flags"); - json.BeginArray(true); - { - VkMemoryPropertyFlags flags = allocator->m_MemProps.memoryTypes[typeIndex].propertyFlags; - if (flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) - json.WriteString("DEVICE_LOCAL"); - if (flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) - json.WriteString("HOST_VISIBLE"); - if (flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) - json.WriteString("HOST_COHERENT"); - if (flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) - json.WriteString("HOST_CACHED"); - if (flags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) - json.WriteString("LAZILY_ALLOCATED"); - #if VMA_VULKAN_VERSION >= 1001000 - if (flags & VK_MEMORY_PROPERTY_PROTECTED_BIT) - json.WriteString("PROTECTED"); - #endif - #if VK_AMD_device_coherent_memory - if (flags & VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY) - json.WriteString("DEVICE_COHERENT_AMD"); - if (flags & VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY) - json.WriteString("DEVICE_UNCACHED_AMD"); - #endif - - flags &= ~(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT - #if VMA_VULKAN_VERSION >= 1001000 - | VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT - #endif - #if VK_AMD_device_coherent_memory - | VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD_COPY - | VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD_COPY - #endif - | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT - | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT - | VK_MEMORY_PROPERTY_HOST_CACHED_BIT); - if (flags != 0) - json.WriteNumber(flags); - } - json.EndArray(); - - json.WriteString("Stats"); - VmaPrintDetailedStatistics(json, stats.memoryType[typeIndex]); - } - json.EndObject(); - } - } - - } - json.EndObject(); - } - json.EndObject(); - } - } - json.EndObject(); - } - - if (detailedMap == VK_TRUE) - allocator->PrintDetailedMap(json); - - json.EndObject(); - } - - *ppStatsString = VmaCreateStringCopy(allocator->GetAllocationCallbacks(), sb.GetData(), sb.GetLength()); -} - -VMA_CALL_PRE void VMA_CALL_POST vmaFreeStatsString( - VmaAllocator allocator, - char* pStatsString) -{ - if(pStatsString != VMA_NULL) - { - VMA_ASSERT(allocator); - VmaFreeString(allocator->GetAllocationCallbacks(), pStatsString); - } -} - -#endif // VMA_STATS_STRING_ENABLED - -/* -This function is not protected by any mutex because it just reads immutable data. -*/ -VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndex( - VmaAllocator allocator, - uint32_t memoryTypeBits, - const VmaAllocationCreateInfo* pAllocationCreateInfo, - uint32_t* pMemoryTypeIndex) -{ - VMA_ASSERT(allocator != VK_NULL_HANDLE); - VMA_ASSERT(pAllocationCreateInfo != VMA_NULL); - VMA_ASSERT(pMemoryTypeIndex != VMA_NULL); - - return allocator->FindMemoryTypeIndex(memoryTypeBits, pAllocationCreateInfo, UINT32_MAX, pMemoryTypeIndex); -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForBufferInfo( - VmaAllocator allocator, - const VkBufferCreateInfo* pBufferCreateInfo, - const VmaAllocationCreateInfo* pAllocationCreateInfo, - uint32_t* pMemoryTypeIndex) -{ - VMA_ASSERT(allocator != VK_NULL_HANDLE); - VMA_ASSERT(pBufferCreateInfo != VMA_NULL); - VMA_ASSERT(pAllocationCreateInfo != VMA_NULL); - VMA_ASSERT(pMemoryTypeIndex != VMA_NULL); - - const VkDevice hDev = allocator->m_hDevice; - const VmaVulkanFunctions* funcs = &allocator->GetVulkanFunctions(); - VkResult res; - -#if VMA_VULKAN_VERSION >= 1003000 - if(funcs->vkGetDeviceBufferMemoryRequirements) - { - // Can query straight from VkBufferCreateInfo :) - VkDeviceBufferMemoryRequirements devBufMemReq = {VK_STRUCTURE_TYPE_DEVICE_BUFFER_MEMORY_REQUIREMENTS}; - devBufMemReq.pCreateInfo = pBufferCreateInfo; - - VkMemoryRequirements2 memReq = {VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2}; - (*funcs->vkGetDeviceBufferMemoryRequirements)(hDev, &devBufMemReq, &memReq); - - res = allocator->FindMemoryTypeIndex( - memReq.memoryRequirements.memoryTypeBits, pAllocationCreateInfo, pBufferCreateInfo->usage, pMemoryTypeIndex); - } - else -#endif // #if VMA_VULKAN_VERSION >= 1003000 - { - // Must create a dummy buffer to query :( - VkBuffer hBuffer = VK_NULL_HANDLE; - res = funcs->vkCreateBuffer( - hDev, pBufferCreateInfo, allocator->GetAllocationCallbacks(), &hBuffer); - if(res == VK_SUCCESS) - { - VkMemoryRequirements memReq = {}; - funcs->vkGetBufferMemoryRequirements(hDev, hBuffer, &memReq); - - res = allocator->FindMemoryTypeIndex( - memReq.memoryTypeBits, pAllocationCreateInfo, pBufferCreateInfo->usage, pMemoryTypeIndex); - - funcs->vkDestroyBuffer( - hDev, hBuffer, allocator->GetAllocationCallbacks()); - } - } - return res; -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaFindMemoryTypeIndexForImageInfo( - VmaAllocator allocator, - const VkImageCreateInfo* pImageCreateInfo, - const VmaAllocationCreateInfo* pAllocationCreateInfo, - uint32_t* pMemoryTypeIndex) -{ - VMA_ASSERT(allocator != VK_NULL_HANDLE); - VMA_ASSERT(pImageCreateInfo != VMA_NULL); - VMA_ASSERT(pAllocationCreateInfo != VMA_NULL); - VMA_ASSERT(pMemoryTypeIndex != VMA_NULL); - - const VkDevice hDev = allocator->m_hDevice; - const VmaVulkanFunctions* funcs = &allocator->GetVulkanFunctions(); - VkResult res; - -#if VMA_VULKAN_VERSION >= 1003000 - if(funcs->vkGetDeviceImageMemoryRequirements) - { - // Can query straight from VkImageCreateInfo :) - VkDeviceImageMemoryRequirements devImgMemReq = {VK_STRUCTURE_TYPE_DEVICE_IMAGE_MEMORY_REQUIREMENTS}; - devImgMemReq.pCreateInfo = pImageCreateInfo; - VMA_ASSERT(pImageCreateInfo->tiling != VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT_COPY && (pImageCreateInfo->flags & VK_IMAGE_CREATE_DISJOINT_BIT_COPY) == 0 && - "Cannot use this VkImageCreateInfo with vmaFindMemoryTypeIndexForImageInfo as I don't know what to pass as VkDeviceImageMemoryRequirements::planeAspect."); - - VkMemoryRequirements2 memReq = {VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2}; - (*funcs->vkGetDeviceImageMemoryRequirements)(hDev, &devImgMemReq, &memReq); - - res = allocator->FindMemoryTypeIndex( - memReq.memoryRequirements.memoryTypeBits, pAllocationCreateInfo, pImageCreateInfo->usage, pMemoryTypeIndex); - } - else -#endif // #if VMA_VULKAN_VERSION >= 1003000 - { - // Must create a dummy image to query :( - VkImage hImage = VK_NULL_HANDLE; - res = funcs->vkCreateImage( - hDev, pImageCreateInfo, allocator->GetAllocationCallbacks(), &hImage); - if(res == VK_SUCCESS) - { - VkMemoryRequirements memReq = {}; - funcs->vkGetImageMemoryRequirements(hDev, hImage, &memReq); - - res = allocator->FindMemoryTypeIndex( - memReq.memoryTypeBits, pAllocationCreateInfo, pImageCreateInfo->usage, pMemoryTypeIndex); - - funcs->vkDestroyImage( - hDev, hImage, allocator->GetAllocationCallbacks()); - } - } - return res; -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreatePool( - VmaAllocator allocator, - const VmaPoolCreateInfo* pCreateInfo, - VmaPool* pPool) -{ - VMA_ASSERT(allocator && pCreateInfo && pPool); - - VMA_DEBUG_LOG("vmaCreatePool"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - return allocator->CreatePool(pCreateInfo, pPool); -} - -VMA_CALL_PRE void VMA_CALL_POST vmaDestroyPool( - VmaAllocator allocator, - VmaPool pool) -{ - VMA_ASSERT(allocator); - - if(pool == VK_NULL_HANDLE) - { - return; - } - - VMA_DEBUG_LOG("vmaDestroyPool"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - allocator->DestroyPool(pool); -} - -VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolStatistics( - VmaAllocator allocator, - VmaPool pool, - VmaStatistics* pPoolStats) -{ - VMA_ASSERT(allocator && pool && pPoolStats); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - allocator->GetPoolStatistics(pool, pPoolStats); -} - -VMA_CALL_PRE void VMA_CALL_POST vmaCalculatePoolStatistics( - VmaAllocator allocator, - VmaPool pool, - VmaDetailedStatistics* pPoolStats) -{ - VMA_ASSERT(allocator && pool && pPoolStats); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - allocator->CalculatePoolStatistics(pool, pPoolStats); -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckPoolCorruption(VmaAllocator allocator, VmaPool pool) -{ - VMA_ASSERT(allocator && pool); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - VMA_DEBUG_LOG("vmaCheckPoolCorruption"); - - return allocator->CheckPoolCorruption(pool); -} - -VMA_CALL_PRE void VMA_CALL_POST vmaGetPoolName( - VmaAllocator allocator, - VmaPool pool, - const char** ppName) -{ - VMA_ASSERT(allocator && pool && ppName); - - VMA_DEBUG_LOG("vmaGetPoolName"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - *ppName = pool->GetName(); -} - -VMA_CALL_PRE void VMA_CALL_POST vmaSetPoolName( - VmaAllocator allocator, - VmaPool pool, - const char* pName) -{ - VMA_ASSERT(allocator && pool); - - VMA_DEBUG_LOG("vmaSetPoolName"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - pool->SetName(pName); -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemory( - VmaAllocator allocator, - const VkMemoryRequirements* pVkMemoryRequirements, - const VmaAllocationCreateInfo* pCreateInfo, - VmaAllocation* pAllocation, - VmaAllocationInfo* pAllocationInfo) -{ - VMA_ASSERT(allocator && pVkMemoryRequirements && pCreateInfo && pAllocation); - - VMA_DEBUG_LOG("vmaAllocateMemory"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - VkResult result = allocator->AllocateMemory( - *pVkMemoryRequirements, - false, // requiresDedicatedAllocation - false, // prefersDedicatedAllocation - VK_NULL_HANDLE, // dedicatedBuffer - VK_NULL_HANDLE, // dedicatedImage - UINT32_MAX, // dedicatedBufferImageUsage - *pCreateInfo, - VMA_SUBALLOCATION_TYPE_UNKNOWN, - 1, // allocationCount - pAllocation); - - if(pAllocationInfo != VMA_NULL && result == VK_SUCCESS) - { - allocator->GetAllocationInfo(*pAllocation, pAllocationInfo); - } - - return result; -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryPages( - VmaAllocator allocator, - const VkMemoryRequirements* pVkMemoryRequirements, - const VmaAllocationCreateInfo* pCreateInfo, - size_t allocationCount, - VmaAllocation* pAllocations, - VmaAllocationInfo* pAllocationInfo) -{ - if(allocationCount == 0) - { - return VK_SUCCESS; - } - - VMA_ASSERT(allocator && pVkMemoryRequirements && pCreateInfo && pAllocations); - - VMA_DEBUG_LOG("vmaAllocateMemoryPages"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - VkResult result = allocator->AllocateMemory( - *pVkMemoryRequirements, - false, // requiresDedicatedAllocation - false, // prefersDedicatedAllocation - VK_NULL_HANDLE, // dedicatedBuffer - VK_NULL_HANDLE, // dedicatedImage - UINT32_MAX, // dedicatedBufferImageUsage - *pCreateInfo, - VMA_SUBALLOCATION_TYPE_UNKNOWN, - allocationCount, - pAllocations); - - if(pAllocationInfo != VMA_NULL && result == VK_SUCCESS) - { - for(size_t i = 0; i < allocationCount; ++i) - { - allocator->GetAllocationInfo(pAllocations[i], pAllocationInfo + i); - } - } - - return result; -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForBuffer( - VmaAllocator allocator, - VkBuffer buffer, - const VmaAllocationCreateInfo* pCreateInfo, - VmaAllocation* pAllocation, - VmaAllocationInfo* pAllocationInfo) -{ - VMA_ASSERT(allocator && buffer != VK_NULL_HANDLE && pCreateInfo && pAllocation); - - VMA_DEBUG_LOG("vmaAllocateMemoryForBuffer"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - VkMemoryRequirements vkMemReq = {}; - bool requiresDedicatedAllocation = false; - bool prefersDedicatedAllocation = false; - allocator->GetBufferMemoryRequirements(buffer, vkMemReq, - requiresDedicatedAllocation, - prefersDedicatedAllocation); - - VkResult result = allocator->AllocateMemory( - vkMemReq, - requiresDedicatedAllocation, - prefersDedicatedAllocation, - buffer, // dedicatedBuffer - VK_NULL_HANDLE, // dedicatedImage - UINT32_MAX, // dedicatedBufferImageUsage - *pCreateInfo, - VMA_SUBALLOCATION_TYPE_BUFFER, - 1, // allocationCount - pAllocation); - - if(pAllocationInfo && result == VK_SUCCESS) - { - allocator->GetAllocationInfo(*pAllocation, pAllocationInfo); - } - - return result; -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaAllocateMemoryForImage( - VmaAllocator allocator, - VkImage image, - const VmaAllocationCreateInfo* pCreateInfo, - VmaAllocation* pAllocation, - VmaAllocationInfo* pAllocationInfo) -{ - VMA_ASSERT(allocator && image != VK_NULL_HANDLE && pCreateInfo && pAllocation); - - VMA_DEBUG_LOG("vmaAllocateMemoryForImage"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - VkMemoryRequirements vkMemReq = {}; - bool requiresDedicatedAllocation = false; - bool prefersDedicatedAllocation = false; - allocator->GetImageMemoryRequirements(image, vkMemReq, - requiresDedicatedAllocation, prefersDedicatedAllocation); - - VkResult result = allocator->AllocateMemory( - vkMemReq, - requiresDedicatedAllocation, - prefersDedicatedAllocation, - VK_NULL_HANDLE, // dedicatedBuffer - image, // dedicatedImage - UINT32_MAX, // dedicatedBufferImageUsage - *pCreateInfo, - VMA_SUBALLOCATION_TYPE_IMAGE_UNKNOWN, - 1, // allocationCount - pAllocation); - - if(pAllocationInfo && result == VK_SUCCESS) - { - allocator->GetAllocationInfo(*pAllocation, pAllocationInfo); - } - - return result; -} - -VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemory( - VmaAllocator allocator, - VmaAllocation allocation) -{ - VMA_ASSERT(allocator); - - if(allocation == VK_NULL_HANDLE) - { - return; - } - - VMA_DEBUG_LOG("vmaFreeMemory"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - allocator->FreeMemory( - 1, // allocationCount - &allocation); -} - -VMA_CALL_PRE void VMA_CALL_POST vmaFreeMemoryPages( - VmaAllocator allocator, - size_t allocationCount, - const VmaAllocation* pAllocations) -{ - if(allocationCount == 0) - { - return; - } - - VMA_ASSERT(allocator); - - VMA_DEBUG_LOG("vmaFreeMemoryPages"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - allocator->FreeMemory(allocationCount, pAllocations); -} - -VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationInfo( - VmaAllocator allocator, - VmaAllocation allocation, - VmaAllocationInfo* pAllocationInfo) -{ - VMA_ASSERT(allocator && allocation && pAllocationInfo); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - allocator->GetAllocationInfo(allocation, pAllocationInfo); -} - -VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationUserData( - VmaAllocator allocator, - VmaAllocation allocation, - void* pUserData) -{ - VMA_ASSERT(allocator && allocation); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - allocation->SetUserData(allocator, pUserData); -} - -VMA_CALL_PRE void VMA_CALL_POST vmaSetAllocationName( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - const char* VMA_NULLABLE pName) -{ - allocation->SetName(allocator, pName); -} - -VMA_CALL_PRE void VMA_CALL_POST vmaGetAllocationMemoryProperties( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - VkMemoryPropertyFlags* VMA_NOT_NULL pFlags) -{ - VMA_ASSERT(allocator && allocation && pFlags); - const uint32_t memTypeIndex = allocation->GetMemoryTypeIndex(); - *pFlags = allocator->m_MemProps.memoryTypes[memTypeIndex].propertyFlags; -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaMapMemory( - VmaAllocator allocator, - VmaAllocation allocation, - void** ppData) -{ - VMA_ASSERT(allocator && allocation && ppData); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - return allocator->Map(allocation, ppData); -} - -VMA_CALL_PRE void VMA_CALL_POST vmaUnmapMemory( - VmaAllocator allocator, - VmaAllocation allocation) -{ - VMA_ASSERT(allocator && allocation); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - allocator->Unmap(allocation); -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocation( - VmaAllocator allocator, - VmaAllocation allocation, - VkDeviceSize offset, - VkDeviceSize size) -{ - VMA_ASSERT(allocator && allocation); - - VMA_DEBUG_LOG("vmaFlushAllocation"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - const VkResult res = allocator->FlushOrInvalidateAllocation(allocation, offset, size, VMA_CACHE_FLUSH); - - return res; -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocation( - VmaAllocator allocator, - VmaAllocation allocation, - VkDeviceSize offset, - VkDeviceSize size) -{ - VMA_ASSERT(allocator && allocation); - - VMA_DEBUG_LOG("vmaInvalidateAllocation"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - const VkResult res = allocator->FlushOrInvalidateAllocation(allocation, offset, size, VMA_CACHE_INVALIDATE); - - return res; -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaFlushAllocations( - VmaAllocator allocator, - uint32_t allocationCount, - const VmaAllocation* allocations, - const VkDeviceSize* offsets, - const VkDeviceSize* sizes) -{ - VMA_ASSERT(allocator); - - if(allocationCount == 0) - { - return VK_SUCCESS; - } - - VMA_ASSERT(allocations); - - VMA_DEBUG_LOG("vmaFlushAllocations"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - const VkResult res = allocator->FlushOrInvalidateAllocations(allocationCount, allocations, offsets, sizes, VMA_CACHE_FLUSH); - - return res; -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaInvalidateAllocations( - VmaAllocator allocator, - uint32_t allocationCount, - const VmaAllocation* allocations, - const VkDeviceSize* offsets, - const VkDeviceSize* sizes) -{ - VMA_ASSERT(allocator); - - if(allocationCount == 0) - { - return VK_SUCCESS; - } - - VMA_ASSERT(allocations); - - VMA_DEBUG_LOG("vmaInvalidateAllocations"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - const VkResult res = allocator->FlushOrInvalidateAllocations(allocationCount, allocations, offsets, sizes, VMA_CACHE_INVALIDATE); - - return res; -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCheckCorruption( - VmaAllocator allocator, - uint32_t memoryTypeBits) -{ - VMA_ASSERT(allocator); - - VMA_DEBUG_LOG("vmaCheckCorruption"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - return allocator->CheckCorruption(memoryTypeBits); -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentation( - VmaAllocator allocator, - const VmaDefragmentationInfo* pInfo, - VmaDefragmentationContext* pContext) -{ - VMA_ASSERT(allocator && pInfo && pContext); - - VMA_DEBUG_LOG("vmaBeginDefragmentation"); - - if (pInfo->pool != VMA_NULL) - { - // Check if run on supported algorithms - if (pInfo->pool->m_BlockVector.GetAlgorithm() & VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT) - return VK_ERROR_FEATURE_NOT_PRESENT; - } - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - *pContext = vma_new(allocator, VmaDefragmentationContext_T)(allocator, *pInfo); - return VK_SUCCESS; -} - -VMA_CALL_PRE void VMA_CALL_POST vmaEndDefragmentation( - VmaAllocator allocator, - VmaDefragmentationContext context, - VmaDefragmentationStats* pStats) -{ - VMA_ASSERT(allocator && context); - - VMA_DEBUG_LOG("vmaEndDefragmentation"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - if (pStats) - context->GetStats(*pStats); - vma_delete(allocator, context); -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaBeginDefragmentationPass( - VmaAllocator VMA_NOT_NULL allocator, - VmaDefragmentationContext VMA_NOT_NULL context, - VmaDefragmentationPassMoveInfo* VMA_NOT_NULL pPassInfo) -{ - VMA_ASSERT(context && pPassInfo); - - VMA_DEBUG_LOG("vmaBeginDefragmentationPass"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - return context->DefragmentPassBegin(*pPassInfo); -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaEndDefragmentationPass( - VmaAllocator VMA_NOT_NULL allocator, - VmaDefragmentationContext VMA_NOT_NULL context, - VmaDefragmentationPassMoveInfo* VMA_NOT_NULL pPassInfo) -{ - VMA_ASSERT(context && pPassInfo); - - VMA_DEBUG_LOG("vmaEndDefragmentationPass"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - return context->DefragmentPassEnd(*pPassInfo); -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory( - VmaAllocator allocator, - VmaAllocation allocation, - VkBuffer buffer) -{ - VMA_ASSERT(allocator && allocation && buffer); - - VMA_DEBUG_LOG("vmaBindBufferMemory"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - return allocator->BindBufferMemory(allocation, 0, buffer, VMA_NULL); -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindBufferMemory2( - VmaAllocator allocator, - VmaAllocation allocation, - VkDeviceSize allocationLocalOffset, - VkBuffer buffer, - const void* pNext) -{ - VMA_ASSERT(allocator && allocation && buffer); - - VMA_DEBUG_LOG("vmaBindBufferMemory2"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - return allocator->BindBufferMemory(allocation, allocationLocalOffset, buffer, pNext); -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory( - VmaAllocator allocator, - VmaAllocation allocation, - VkImage image) -{ - VMA_ASSERT(allocator && allocation && image); - - VMA_DEBUG_LOG("vmaBindImageMemory"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - return allocator->BindImageMemory(allocation, 0, image, VMA_NULL); -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaBindImageMemory2( - VmaAllocator allocator, - VmaAllocation allocation, - VkDeviceSize allocationLocalOffset, - VkImage image, - const void* pNext) -{ - VMA_ASSERT(allocator && allocation && image); - - VMA_DEBUG_LOG("vmaBindImageMemory2"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - return allocator->BindImageMemory(allocation, allocationLocalOffset, image, pNext); -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBuffer( - VmaAllocator allocator, - const VkBufferCreateInfo* pBufferCreateInfo, - const VmaAllocationCreateInfo* pAllocationCreateInfo, - VkBuffer* pBuffer, - VmaAllocation* pAllocation, - VmaAllocationInfo* pAllocationInfo) -{ - VMA_ASSERT(allocator && pBufferCreateInfo && pAllocationCreateInfo && pBuffer && pAllocation); - - if(pBufferCreateInfo->size == 0) - { - return VK_ERROR_INITIALIZATION_FAILED; - } - if((pBufferCreateInfo->usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY) != 0 && - !allocator->m_UseKhrBufferDeviceAddress) - { - VMA_ASSERT(0 && "Creating a buffer with VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT is not valid if VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT was not used."); - return VK_ERROR_INITIALIZATION_FAILED; - } - - VMA_DEBUG_LOG("vmaCreateBuffer"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - *pBuffer = VK_NULL_HANDLE; - *pAllocation = VK_NULL_HANDLE; - - // 1. Create VkBuffer. - VkResult res = (*allocator->GetVulkanFunctions().vkCreateBuffer)( - allocator->m_hDevice, - pBufferCreateInfo, - allocator->GetAllocationCallbacks(), - pBuffer); - if(res >= 0) - { - // 2. vkGetBufferMemoryRequirements. - VkMemoryRequirements vkMemReq = {}; - bool requiresDedicatedAllocation = false; - bool prefersDedicatedAllocation = false; - allocator->GetBufferMemoryRequirements(*pBuffer, vkMemReq, - requiresDedicatedAllocation, prefersDedicatedAllocation); - - // 3. Allocate memory using allocator. - res = allocator->AllocateMemory( - vkMemReq, - requiresDedicatedAllocation, - prefersDedicatedAllocation, - *pBuffer, // dedicatedBuffer - VK_NULL_HANDLE, // dedicatedImage - pBufferCreateInfo->usage, // dedicatedBufferImageUsage - *pAllocationCreateInfo, - VMA_SUBALLOCATION_TYPE_BUFFER, - 1, // allocationCount - pAllocation); - - if(res >= 0) - { - // 3. Bind buffer with memory. - if((pAllocationCreateInfo->flags & VMA_ALLOCATION_CREATE_DONT_BIND_BIT) == 0) - { - res = allocator->BindBufferMemory(*pAllocation, 0, *pBuffer, VMA_NULL); - } - if(res >= 0) - { - // All steps succeeded. - #if VMA_STATS_STRING_ENABLED - (*pAllocation)->InitBufferImageUsage(pBufferCreateInfo->usage); - #endif - if(pAllocationInfo != VMA_NULL) - { - allocator->GetAllocationInfo(*pAllocation, pAllocationInfo); - } - - return VK_SUCCESS; - } - allocator->FreeMemory( - 1, // allocationCount - pAllocation); - *pAllocation = VK_NULL_HANDLE; - (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks()); - *pBuffer = VK_NULL_HANDLE; - return res; - } - (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks()); - *pBuffer = VK_NULL_HANDLE; - return res; - } - return res; -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateBufferWithAlignment( - VmaAllocator allocator, - const VkBufferCreateInfo* pBufferCreateInfo, - const VmaAllocationCreateInfo* pAllocationCreateInfo, - VkDeviceSize minAlignment, - VkBuffer* pBuffer, - VmaAllocation* pAllocation, - VmaAllocationInfo* pAllocationInfo) -{ - VMA_ASSERT(allocator && pBufferCreateInfo && pAllocationCreateInfo && VmaIsPow2(minAlignment) && pBuffer && pAllocation); - - if(pBufferCreateInfo->size == 0) - { - return VK_ERROR_INITIALIZATION_FAILED; - } - if((pBufferCreateInfo->usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY) != 0 && - !allocator->m_UseKhrBufferDeviceAddress) - { - VMA_ASSERT(0 && "Creating a buffer with VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT is not valid if VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT was not used."); - return VK_ERROR_INITIALIZATION_FAILED; - } - - VMA_DEBUG_LOG("vmaCreateBufferWithAlignment"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - *pBuffer = VK_NULL_HANDLE; - *pAllocation = VK_NULL_HANDLE; - - // 1. Create VkBuffer. - VkResult res = (*allocator->GetVulkanFunctions().vkCreateBuffer)( - allocator->m_hDevice, - pBufferCreateInfo, - allocator->GetAllocationCallbacks(), - pBuffer); - if(res >= 0) - { - // 2. vkGetBufferMemoryRequirements. - VkMemoryRequirements vkMemReq = {}; - bool requiresDedicatedAllocation = false; - bool prefersDedicatedAllocation = false; - allocator->GetBufferMemoryRequirements(*pBuffer, vkMemReq, - requiresDedicatedAllocation, prefersDedicatedAllocation); - - // 2a. Include minAlignment - vkMemReq.alignment = VMA_MAX(vkMemReq.alignment, minAlignment); - - // 3. Allocate memory using allocator. - res = allocator->AllocateMemory( - vkMemReq, - requiresDedicatedAllocation, - prefersDedicatedAllocation, - *pBuffer, // dedicatedBuffer - VK_NULL_HANDLE, // dedicatedImage - pBufferCreateInfo->usage, // dedicatedBufferImageUsage - *pAllocationCreateInfo, - VMA_SUBALLOCATION_TYPE_BUFFER, - 1, // allocationCount - pAllocation); - - if(res >= 0) - { - // 3. Bind buffer with memory. - if((pAllocationCreateInfo->flags & VMA_ALLOCATION_CREATE_DONT_BIND_BIT) == 0) - { - res = allocator->BindBufferMemory(*pAllocation, 0, *pBuffer, VMA_NULL); - } - if(res >= 0) - { - // All steps succeeded. - #if VMA_STATS_STRING_ENABLED - (*pAllocation)->InitBufferImageUsage(pBufferCreateInfo->usage); - #endif - if(pAllocationInfo != VMA_NULL) - { - allocator->GetAllocationInfo(*pAllocation, pAllocationInfo); - } - - return VK_SUCCESS; - } - allocator->FreeMemory( - 1, // allocationCount - pAllocation); - *pAllocation = VK_NULL_HANDLE; - (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks()); - *pBuffer = VK_NULL_HANDLE; - return res; - } - (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks()); - *pBuffer = VK_NULL_HANDLE; - return res; - } - return res; -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingBuffer( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo, - VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer) -{ - return vmaCreateAliasingBuffer2(allocator, allocation, 0, pBufferCreateInfo, pBuffer); -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingBuffer2( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - VkDeviceSize allocationLocalOffset, - const VkBufferCreateInfo* VMA_NOT_NULL pBufferCreateInfo, - VkBuffer VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pBuffer) -{ - VMA_ASSERT(allocator && pBufferCreateInfo && pBuffer && allocation); - VMA_ASSERT(allocationLocalOffset + pBufferCreateInfo->size <= allocation->GetSize()); - - VMA_DEBUG_LOG("vmaCreateAliasingBuffer2"); - - *pBuffer = VK_NULL_HANDLE; - - if (pBufferCreateInfo->size == 0) - { - return VK_ERROR_INITIALIZATION_FAILED; - } - if ((pBufferCreateInfo->usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_COPY) != 0 && - !allocator->m_UseKhrBufferDeviceAddress) - { - VMA_ASSERT(0 && "Creating a buffer with VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT is not valid if VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT was not used."); - return VK_ERROR_INITIALIZATION_FAILED; - } - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - // 1. Create VkBuffer. - VkResult res = (*allocator->GetVulkanFunctions().vkCreateBuffer)( - allocator->m_hDevice, - pBufferCreateInfo, - allocator->GetAllocationCallbacks(), - pBuffer); - if (res >= 0) - { - // 2. Bind buffer with memory. - res = allocator->BindBufferMemory(allocation, allocationLocalOffset, *pBuffer, VMA_NULL); - if (res >= 0) - { - return VK_SUCCESS; - } - (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, *pBuffer, allocator->GetAllocationCallbacks()); - } - return res; -} - -VMA_CALL_PRE void VMA_CALL_POST vmaDestroyBuffer( - VmaAllocator allocator, - VkBuffer buffer, - VmaAllocation allocation) -{ - VMA_ASSERT(allocator); - - if(buffer == VK_NULL_HANDLE && allocation == VK_NULL_HANDLE) - { - return; - } - - VMA_DEBUG_LOG("vmaDestroyBuffer"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - if(buffer != VK_NULL_HANDLE) - { - (*allocator->GetVulkanFunctions().vkDestroyBuffer)(allocator->m_hDevice, buffer, allocator->GetAllocationCallbacks()); - } - - if(allocation != VK_NULL_HANDLE) - { - allocator->FreeMemory( - 1, // allocationCount - &allocation); - } -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateImage( - VmaAllocator allocator, - const VkImageCreateInfo* pImageCreateInfo, - const VmaAllocationCreateInfo* pAllocationCreateInfo, - VkImage* pImage, - VmaAllocation* pAllocation, - VmaAllocationInfo* pAllocationInfo) -{ - VMA_ASSERT(allocator && pImageCreateInfo && pAllocationCreateInfo && pImage && pAllocation); - - if(pImageCreateInfo->extent.width == 0 || - pImageCreateInfo->extent.height == 0 || - pImageCreateInfo->extent.depth == 0 || - pImageCreateInfo->mipLevels == 0 || - pImageCreateInfo->arrayLayers == 0) - { - return VK_ERROR_INITIALIZATION_FAILED; - } - - VMA_DEBUG_LOG("vmaCreateImage"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - *pImage = VK_NULL_HANDLE; - *pAllocation = VK_NULL_HANDLE; - - // 1. Create VkImage. - VkResult res = (*allocator->GetVulkanFunctions().vkCreateImage)( - allocator->m_hDevice, - pImageCreateInfo, - allocator->GetAllocationCallbacks(), - pImage); - if(res >= 0) - { - VmaSuballocationType suballocType = pImageCreateInfo->tiling == VK_IMAGE_TILING_OPTIMAL ? - VMA_SUBALLOCATION_TYPE_IMAGE_OPTIMAL : - VMA_SUBALLOCATION_TYPE_IMAGE_LINEAR; - - // 2. Allocate memory using allocator. - VkMemoryRequirements vkMemReq = {}; - bool requiresDedicatedAllocation = false; - bool prefersDedicatedAllocation = false; - allocator->GetImageMemoryRequirements(*pImage, vkMemReq, - requiresDedicatedAllocation, prefersDedicatedAllocation); - - res = allocator->AllocateMemory( - vkMemReq, - requiresDedicatedAllocation, - prefersDedicatedAllocation, - VK_NULL_HANDLE, // dedicatedBuffer - *pImage, // dedicatedImage - pImageCreateInfo->usage, // dedicatedBufferImageUsage - *pAllocationCreateInfo, - suballocType, - 1, // allocationCount - pAllocation); - - if(res >= 0) - { - // 3. Bind image with memory. - if((pAllocationCreateInfo->flags & VMA_ALLOCATION_CREATE_DONT_BIND_BIT) == 0) - { - res = allocator->BindImageMemory(*pAllocation, 0, *pImage, VMA_NULL); - } - if(res >= 0) - { - // All steps succeeded. - #if VMA_STATS_STRING_ENABLED - (*pAllocation)->InitBufferImageUsage(pImageCreateInfo->usage); - #endif - if(pAllocationInfo != VMA_NULL) - { - allocator->GetAllocationInfo(*pAllocation, pAllocationInfo); - } - - return VK_SUCCESS; - } - allocator->FreeMemory( - 1, // allocationCount - pAllocation); - *pAllocation = VK_NULL_HANDLE; - (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks()); - *pImage = VK_NULL_HANDLE; - return res; - } - (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks()); - *pImage = VK_NULL_HANDLE; - return res; - } - return res; -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingImage( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo, - VkImage VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pImage) -{ - return vmaCreateAliasingImage2(allocator, allocation, 0, pImageCreateInfo, pImage); -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateAliasingImage2( - VmaAllocator VMA_NOT_NULL allocator, - VmaAllocation VMA_NOT_NULL allocation, - VkDeviceSize allocationLocalOffset, - const VkImageCreateInfo* VMA_NOT_NULL pImageCreateInfo, - VkImage VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pImage) -{ - VMA_ASSERT(allocator && pImageCreateInfo && pImage && allocation); - - *pImage = VK_NULL_HANDLE; - - VMA_DEBUG_LOG("vmaCreateImage2"); - - if (pImageCreateInfo->extent.width == 0 || - pImageCreateInfo->extent.height == 0 || - pImageCreateInfo->extent.depth == 0 || - pImageCreateInfo->mipLevels == 0 || - pImageCreateInfo->arrayLayers == 0) - { - return VK_ERROR_INITIALIZATION_FAILED; - } - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - // 1. Create VkImage. - VkResult res = (*allocator->GetVulkanFunctions().vkCreateImage)( - allocator->m_hDevice, - pImageCreateInfo, - allocator->GetAllocationCallbacks(), - pImage); - if (res >= 0) - { - // 2. Bind image with memory. - res = allocator->BindImageMemory(allocation, allocationLocalOffset, *pImage, VMA_NULL); - if (res >= 0) - { - return VK_SUCCESS; - } - (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, *pImage, allocator->GetAllocationCallbacks()); - } - return res; -} - -VMA_CALL_PRE void VMA_CALL_POST vmaDestroyImage( - VmaAllocator VMA_NOT_NULL allocator, - VkImage VMA_NULLABLE_NON_DISPATCHABLE image, - VmaAllocation VMA_NULLABLE allocation) -{ - VMA_ASSERT(allocator); - - if(image == VK_NULL_HANDLE && allocation == VK_NULL_HANDLE) - { - return; - } - - VMA_DEBUG_LOG("vmaDestroyImage"); - - VMA_DEBUG_GLOBAL_MUTEX_LOCK - - if(image != VK_NULL_HANDLE) - { - (*allocator->GetVulkanFunctions().vkDestroyImage)(allocator->m_hDevice, image, allocator->GetAllocationCallbacks()); - } - if(allocation != VK_NULL_HANDLE) - { - allocator->FreeMemory( - 1, // allocationCount - &allocation); - } -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaCreateVirtualBlock( - const VmaVirtualBlockCreateInfo* VMA_NOT_NULL pCreateInfo, - VmaVirtualBlock VMA_NULLABLE * VMA_NOT_NULL pVirtualBlock) -{ - VMA_ASSERT(pCreateInfo && pVirtualBlock); - VMA_ASSERT(pCreateInfo->size > 0); - VMA_DEBUG_LOG("vmaCreateVirtualBlock"); - VMA_DEBUG_GLOBAL_MUTEX_LOCK; - *pVirtualBlock = vma_new(pCreateInfo->pAllocationCallbacks, VmaVirtualBlock_T)(*pCreateInfo); - VkResult res = (*pVirtualBlock)->Init(); - if(res < 0) - { - vma_delete(pCreateInfo->pAllocationCallbacks, *pVirtualBlock); - *pVirtualBlock = VK_NULL_HANDLE; - } - return res; -} - -VMA_CALL_PRE void VMA_CALL_POST vmaDestroyVirtualBlock(VmaVirtualBlock VMA_NULLABLE virtualBlock) -{ - if(virtualBlock != VK_NULL_HANDLE) - { - VMA_DEBUG_LOG("vmaDestroyVirtualBlock"); - VMA_DEBUG_GLOBAL_MUTEX_LOCK; - VkAllocationCallbacks allocationCallbacks = virtualBlock->m_AllocationCallbacks; // Have to copy the callbacks when destroying. - vma_delete(&allocationCallbacks, virtualBlock); - } -} - -VMA_CALL_PRE VkBool32 VMA_CALL_POST vmaIsVirtualBlockEmpty(VmaVirtualBlock VMA_NOT_NULL virtualBlock) -{ - VMA_ASSERT(virtualBlock != VK_NULL_HANDLE); - VMA_DEBUG_LOG("vmaIsVirtualBlockEmpty"); - VMA_DEBUG_GLOBAL_MUTEX_LOCK; - return virtualBlock->IsEmpty() ? VK_TRUE : VK_FALSE; -} - -VMA_CALL_PRE void VMA_CALL_POST vmaGetVirtualAllocationInfo(VmaVirtualBlock VMA_NOT_NULL virtualBlock, - VmaVirtualAllocation VMA_NOT_NULL_NON_DISPATCHABLE allocation, VmaVirtualAllocationInfo* VMA_NOT_NULL pVirtualAllocInfo) -{ - VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && pVirtualAllocInfo != VMA_NULL); - VMA_DEBUG_LOG("vmaGetVirtualAllocationInfo"); - VMA_DEBUG_GLOBAL_MUTEX_LOCK; - virtualBlock->GetAllocationInfo(allocation, *pVirtualAllocInfo); -} - -VMA_CALL_PRE VkResult VMA_CALL_POST vmaVirtualAllocate(VmaVirtualBlock VMA_NOT_NULL virtualBlock, - const VmaVirtualAllocationCreateInfo* VMA_NOT_NULL pCreateInfo, VmaVirtualAllocation VMA_NULLABLE_NON_DISPATCHABLE* VMA_NOT_NULL pAllocation, - VkDeviceSize* VMA_NULLABLE pOffset) -{ - VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && pCreateInfo != VMA_NULL && pAllocation != VMA_NULL); - VMA_DEBUG_LOG("vmaVirtualAllocate"); - VMA_DEBUG_GLOBAL_MUTEX_LOCK; - return virtualBlock->Allocate(*pCreateInfo, *pAllocation, pOffset); -} - -VMA_CALL_PRE void VMA_CALL_POST vmaVirtualFree(VmaVirtualBlock VMA_NOT_NULL virtualBlock, VmaVirtualAllocation VMA_NULLABLE_NON_DISPATCHABLE allocation) -{ - if(allocation != VK_NULL_HANDLE) - { - VMA_ASSERT(virtualBlock != VK_NULL_HANDLE); - VMA_DEBUG_LOG("vmaVirtualFree"); - VMA_DEBUG_GLOBAL_MUTEX_LOCK; - virtualBlock->Free(allocation); - } -} - -VMA_CALL_PRE void VMA_CALL_POST vmaClearVirtualBlock(VmaVirtualBlock VMA_NOT_NULL virtualBlock) -{ - VMA_ASSERT(virtualBlock != VK_NULL_HANDLE); - VMA_DEBUG_LOG("vmaClearVirtualBlock"); - VMA_DEBUG_GLOBAL_MUTEX_LOCK; - virtualBlock->Clear(); -} - -VMA_CALL_PRE void VMA_CALL_POST vmaSetVirtualAllocationUserData(VmaVirtualBlock VMA_NOT_NULL virtualBlock, - VmaVirtualAllocation VMA_NOT_NULL_NON_DISPATCHABLE allocation, void* VMA_NULLABLE pUserData) -{ - VMA_ASSERT(virtualBlock != VK_NULL_HANDLE); - VMA_DEBUG_LOG("vmaSetVirtualAllocationUserData"); - VMA_DEBUG_GLOBAL_MUTEX_LOCK; - virtualBlock->SetAllocationUserData(allocation, pUserData); -} - -VMA_CALL_PRE void VMA_CALL_POST vmaGetVirtualBlockStatistics(VmaVirtualBlock VMA_NOT_NULL virtualBlock, - VmaStatistics* VMA_NOT_NULL pStats) -{ - VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && pStats != VMA_NULL); - VMA_DEBUG_LOG("vmaGetVirtualBlockStatistics"); - VMA_DEBUG_GLOBAL_MUTEX_LOCK; - virtualBlock->GetStatistics(*pStats); -} - -VMA_CALL_PRE void VMA_CALL_POST vmaCalculateVirtualBlockStatistics(VmaVirtualBlock VMA_NOT_NULL virtualBlock, - VmaDetailedStatistics* VMA_NOT_NULL pStats) -{ - VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && pStats != VMA_NULL); - VMA_DEBUG_LOG("vmaCalculateVirtualBlockStatistics"); - VMA_DEBUG_GLOBAL_MUTEX_LOCK; - virtualBlock->CalculateDetailedStatistics(*pStats); -} - -#if VMA_STATS_STRING_ENABLED - -VMA_CALL_PRE void VMA_CALL_POST vmaBuildVirtualBlockStatsString(VmaVirtualBlock VMA_NOT_NULL virtualBlock, - char* VMA_NULLABLE * VMA_NOT_NULL ppStatsString, VkBool32 detailedMap) -{ - VMA_ASSERT(virtualBlock != VK_NULL_HANDLE && ppStatsString != VMA_NULL); - VMA_DEBUG_GLOBAL_MUTEX_LOCK; - const VkAllocationCallbacks* allocationCallbacks = virtualBlock->GetAllocationCallbacks(); - VmaStringBuilder sb(allocationCallbacks); - virtualBlock->BuildStatsString(detailedMap != VK_FALSE, sb); - *ppStatsString = VmaCreateStringCopy(allocationCallbacks, sb.GetData(), sb.GetLength()); -} - -VMA_CALL_PRE void VMA_CALL_POST vmaFreeVirtualBlockStatsString(VmaVirtualBlock VMA_NOT_NULL virtualBlock, - char* VMA_NULLABLE pStatsString) -{ - if(pStatsString != VMA_NULL) - { - VMA_ASSERT(virtualBlock != VK_NULL_HANDLE); - VMA_DEBUG_GLOBAL_MUTEX_LOCK; - VmaFreeString(virtualBlock->GetAllocationCallbacks(), pStatsString); - } -} -#endif // VMA_STATS_STRING_ENABLED -#endif // _VMA_PUBLIC_INTERFACE -#endif // VMA_IMPLEMENTATION - -/** -\page quick_start Quick start - -\section quick_start_project_setup Project setup - -Vulkan Memory Allocator comes in form of a "stb-style" single header file. -You don't need to build it as a separate library project. -You can add this file directly to your project and submit it to code repository next to your other source files. - -"Single header" doesn't mean that everything is contained in C/C++ declarations, -like it tends to be in case of inline functions or C++ templates. -It means that implementation is bundled with interface in a single file and needs to be extracted using preprocessor macro. -If you don't do it properly, you will get linker errors. - -To do it properly: - --# Include "vk_mem_alloc.h" file in each CPP file where you want to use the library. - This includes declarations of all members of the library. --# In exactly one CPP file define following macro before this include. - It enables also internal definitions. - -\code -#define VMA_IMPLEMENTATION -#include "vk_mem_alloc.h" -\endcode - -It may be a good idea to create dedicated CPP file just for this purpose. - -This library includes header ``, which in turn -includes `` on Windows. If you need some specific macros defined -before including these headers (like `WIN32_LEAN_AND_MEAN` or -`WINVER` for Windows, `VK_USE_PLATFORM_WIN32_KHR` for Vulkan), you must define -them before every `#include` of this library. - -This library is written in C++, but has C-compatible interface. -Thus you can include and use vk_mem_alloc.h in C or C++ code, but full -implementation with `VMA_IMPLEMENTATION` macro must be compiled as C++, NOT as C. -Some features of C++14 are used. STL containers, RTTI, or C++ exceptions are not used. - - -\section quick_start_initialization Initialization - -At program startup: - --# Initialize Vulkan to have `VkPhysicalDevice`, `VkDevice` and `VkInstance` object. --# Fill VmaAllocatorCreateInfo structure and create #VmaAllocator object by - calling vmaCreateAllocator(). - -Only members `physicalDevice`, `device`, `instance` are required. -However, you should inform the library which Vulkan version do you use by setting -VmaAllocatorCreateInfo::vulkanApiVersion and which extensions did you enable -by setting VmaAllocatorCreateInfo::flags (like #VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT for VK_KHR_buffer_device_address). -Otherwise, VMA would use only features of Vulkan 1.0 core with no extensions. - -\subsection quick_start_initialization_selecting_vulkan_version Selecting Vulkan version - -VMA supports Vulkan version down to 1.0, for backward compatibility. -If you want to use higher version, you need to inform the library about it. -This is a two-step process. - -Step 1: Compile time. By default, VMA compiles with code supporting the highest -Vulkan version found in the included `` that is also supported by the library. -If this is OK, you don't need to do anything. -However, if you want to compile VMA as if only some lower Vulkan version was available, -define macro `VMA_VULKAN_VERSION` before every `#include "vk_mem_alloc.h"`. -It should have decimal numeric value in form of ABBBCCC, where A = major, BBB = minor, CCC = patch Vulkan version. -For example, to compile against Vulkan 1.2: - -\code -#define VMA_VULKAN_VERSION 1002000 // Vulkan 1.2 -#include "vk_mem_alloc.h" -\endcode - -Step 2: Runtime. Even when compiled with higher Vulkan version available, -VMA can use only features of a lower version, which is configurable during creation of the #VmaAllocator object. -By default, only Vulkan 1.0 is used. -To initialize the allocator with support for higher Vulkan version, you need to set member -VmaAllocatorCreateInfo::vulkanApiVersion to an appropriate value, e.g. using constants like `VK_API_VERSION_1_2`. -See code sample below. - -\subsection quick_start_initialization_importing_vulkan_functions Importing Vulkan functions - -You may need to configure importing Vulkan functions. There are 3 ways to do this: - --# **If you link with Vulkan static library** (e.g. "vulkan-1.lib" on Windows): - - You don't need to do anything. - - VMA will use these, as macro `VMA_STATIC_VULKAN_FUNCTIONS` is defined to 1 by default. --# **If you want VMA to fetch pointers to Vulkan functions dynamically** using `vkGetInstanceProcAddr`, - `vkGetDeviceProcAddr` (this is the option presented in the example below): - - Define `VMA_STATIC_VULKAN_FUNCTIONS` to 0, `VMA_DYNAMIC_VULKAN_FUNCTIONS` to 1. - - Provide pointers to these two functions via VmaVulkanFunctions::vkGetInstanceProcAddr, - VmaVulkanFunctions::vkGetDeviceProcAddr. - - The library will fetch pointers to all other functions it needs internally. --# **If you fetch pointers to all Vulkan functions in a custom way**, e.g. using some loader like - [Volk](https://github.com/zeux/volk): - - Define `VMA_STATIC_VULKAN_FUNCTIONS` and `VMA_DYNAMIC_VULKAN_FUNCTIONS` to 0. - - Pass these pointers via structure #VmaVulkanFunctions. - -Example for case 2: - -\code -#define VMA_STATIC_VULKAN_FUNCTIONS 0 -#define VMA_DYNAMIC_VULKAN_FUNCTIONS 1 -#include "vk_mem_alloc.h" - -... - -VmaVulkanFunctions vulkanFunctions = {}; -vulkanFunctions.vkGetInstanceProcAddr = &vkGetInstanceProcAddr; -vulkanFunctions.vkGetDeviceProcAddr = &vkGetDeviceProcAddr; - -VmaAllocatorCreateInfo allocatorCreateInfo = {}; -allocatorCreateInfo.vulkanApiVersion = VK_API_VERSION_1_2; -allocatorCreateInfo.physicalDevice = physicalDevice; -allocatorCreateInfo.device = device; -allocatorCreateInfo.instance = instance; -allocatorCreateInfo.pVulkanFunctions = &vulkanFunctions; - -VmaAllocator allocator; -vmaCreateAllocator(&allocatorCreateInfo, &allocator); -\endcode - - -\section quick_start_resource_allocation Resource allocation - -When you want to create a buffer or image: - --# Fill `VkBufferCreateInfo` / `VkImageCreateInfo` structure. --# Fill VmaAllocationCreateInfo structure. --# Call vmaCreateBuffer() / vmaCreateImage() to get `VkBuffer`/`VkImage` with memory - already allocated and bound to it, plus #VmaAllocation objects that represents its underlying memory. - -\code -VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; -bufferInfo.size = 65536; -bufferInfo.usage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - -VmaAllocationCreateInfo allocInfo = {}; -allocInfo.usage = VMA_MEMORY_USAGE_AUTO; - -VkBuffer buffer; -VmaAllocation allocation; -vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr); -\endcode - -Don't forget to destroy your objects when no longer needed: - -\code -vmaDestroyBuffer(allocator, buffer, allocation); -vmaDestroyAllocator(allocator); -\endcode - - -\page choosing_memory_type Choosing memory type - -Physical devices in Vulkan support various combinations of memory heaps and -types. Help with choosing correct and optimal memory type for your specific -resource is one of the key features of this library. You can use it by filling -appropriate members of VmaAllocationCreateInfo structure, as described below. -You can also combine multiple methods. - --# If you just want to find memory type index that meets your requirements, you - can use function: vmaFindMemoryTypeIndexForBufferInfo(), - vmaFindMemoryTypeIndexForImageInfo(), vmaFindMemoryTypeIndex(). --# If you want to allocate a region of device memory without association with any - specific image or buffer, you can use function vmaAllocateMemory(). Usage of - this function is not recommended and usually not needed. - vmaAllocateMemoryPages() function is also provided for creating multiple allocations at once, - which may be useful for sparse binding. --# If you already have a buffer or an image created, you want to allocate memory - for it and then you will bind it yourself, you can use function - vmaAllocateMemoryForBuffer(), vmaAllocateMemoryForImage(). - For binding you should use functions: vmaBindBufferMemory(), vmaBindImageMemory() - or their extended versions: vmaBindBufferMemory2(), vmaBindImageMemory2(). --# **This is the easiest and recommended way to use this library:** - If you want to create a buffer or an image, allocate memory for it and bind - them together, all in one call, you can use function vmaCreateBuffer(), - vmaCreateImage(). - -When using 3. or 4., the library internally queries Vulkan for memory types -supported for that buffer or image (function `vkGetBufferMemoryRequirements()`) -and uses only one of these types. - -If no memory type can be found that meets all the requirements, these functions -return `VK_ERROR_FEATURE_NOT_PRESENT`. - -You can leave VmaAllocationCreateInfo structure completely filled with zeros. -It means no requirements are specified for memory type. -It is valid, although not very useful. - -\section choosing_memory_type_usage Usage - -The easiest way to specify memory requirements is to fill member -VmaAllocationCreateInfo::usage using one of the values of enum #VmaMemoryUsage. -It defines high level, common usage types. -Since version 3 of the library, it is recommended to use #VMA_MEMORY_USAGE_AUTO to let it select best memory type for your resource automatically. - -For example, if you want to create a uniform buffer that will be filled using -transfer only once or infrequently and then used for rendering every frame as a uniform buffer, you can -do it using following code. The buffer will most likely end up in a memory type with -`VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT` to be fast to access by the GPU device. - -\code -VkBufferCreateInfo bufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; -bufferInfo.size = 65536; -bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - -VmaAllocationCreateInfo allocInfo = {}; -allocInfo.usage = VMA_MEMORY_USAGE_AUTO; - -VkBuffer buffer; -VmaAllocation allocation; -vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr); -\endcode - -If you have a preference for putting the resource in GPU (device) memory or CPU (host) memory -on systems with discrete graphics card that have the memories separate, you can use -#VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE or #VMA_MEMORY_USAGE_AUTO_PREFER_HOST. - -When using `VMA_MEMORY_USAGE_AUTO*` while you want to map the allocated memory, -you also need to specify one of the host access flags: -#VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT. -This will help the library decide about preferred memory type to ensure it has `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` -so you can map it. - -For example, a staging buffer that will be filled via mapped pointer and then -used as a source of transfer to the buffer described previously can be created like this. -It will likely end up in a memory type that is `HOST_VISIBLE` and `HOST_COHERENT` -but not `HOST_CACHED` (meaning uncached, write-combined) and not `DEVICE_LOCAL` (meaning system RAM). - -\code -VkBufferCreateInfo stagingBufferInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; -stagingBufferInfo.size = 65536; -stagingBufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; - -VmaAllocationCreateInfo stagingAllocInfo = {}; -stagingAllocInfo.usage = VMA_MEMORY_USAGE_AUTO; -stagingAllocInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT; - -VkBuffer stagingBuffer; -VmaAllocation stagingAllocation; -vmaCreateBuffer(allocator, &stagingBufferInfo, &stagingAllocInfo, &stagingBuffer, &stagingAllocation, nullptr); -\endcode - -For more examples of creating different kinds of resources, see chapter \ref usage_patterns. - -Usage values `VMA_MEMORY_USAGE_AUTO*` are legal to use only when the library knows -about the resource being created by having `VkBufferCreateInfo` / `VkImageCreateInfo` passed, -so they work with functions like: vmaCreateBuffer(), vmaCreateImage(), vmaFindMemoryTypeIndexForBufferInfo() etc. -If you allocate raw memory using function vmaAllocateMemory(), you have to use other means of selecting -memory type, as described below. - -\note -Old usage values (`VMA_MEMORY_USAGE_GPU_ONLY`, `VMA_MEMORY_USAGE_CPU_ONLY`, -`VMA_MEMORY_USAGE_CPU_TO_GPU`, `VMA_MEMORY_USAGE_GPU_TO_CPU`, `VMA_MEMORY_USAGE_CPU_COPY`) -are still available and work same way as in previous versions of the library -for backward compatibility, but they are not recommended. - -\section choosing_memory_type_required_preferred_flags Required and preferred flags - -You can specify more detailed requirements by filling members -VmaAllocationCreateInfo::requiredFlags and VmaAllocationCreateInfo::preferredFlags -with a combination of bits from enum `VkMemoryPropertyFlags`. For example, -if you want to create a buffer that will be persistently mapped on host (so it -must be `HOST_VISIBLE`) and preferably will also be `HOST_COHERENT` and `HOST_CACHED`, -use following code: - -\code -VmaAllocationCreateInfo allocInfo = {}; -allocInfo.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; -allocInfo.preferredFlags = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT; -allocInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT; - -VkBuffer buffer; -VmaAllocation allocation; -vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr); -\endcode - -A memory type is chosen that has all the required flags and as many preferred -flags set as possible. - -Value passed in VmaAllocationCreateInfo::usage is internally converted to a set of required and preferred flags, -plus some extra "magic" (heuristics). - -\section choosing_memory_type_explicit_memory_types Explicit memory types - -If you inspected memory types available on the physical device and you have -a preference for memory types that you want to use, you can fill member -VmaAllocationCreateInfo::memoryTypeBits. It is a bit mask, where each bit set -means that a memory type with that index is allowed to be used for the -allocation. Special value 0, just like `UINT32_MAX`, means there are no -restrictions to memory type index. - -Please note that this member is NOT just a memory type index. -Still you can use it to choose just one, specific memory type. -For example, if you already determined that your buffer should be created in -memory type 2, use following code: - -\code -uint32_t memoryTypeIndex = 2; - -VmaAllocationCreateInfo allocInfo = {}; -allocInfo.memoryTypeBits = 1u << memoryTypeIndex; - -VkBuffer buffer; -VmaAllocation allocation; -vmaCreateBuffer(allocator, &bufferInfo, &allocInfo, &buffer, &allocation, nullptr); -\endcode - - -\section choosing_memory_type_custom_memory_pools Custom memory pools - -If you allocate from custom memory pool, all the ways of specifying memory -requirements described above are not applicable and the aforementioned members -of VmaAllocationCreateInfo structure are ignored. Memory type is selected -explicitly when creating the pool and then used to make all the allocations from -that pool. For further details, see \ref custom_memory_pools. - -\section choosing_memory_type_dedicated_allocations Dedicated allocations - -Memory for allocations is reserved out of larger block of `VkDeviceMemory` -allocated from Vulkan internally. That is the main feature of this whole library. -You can still request a separate memory block to be created for an allocation, -just like you would do in a trivial solution without using any allocator. -In that case, a buffer or image is always bound to that memory at offset 0. -This is called a "dedicated allocation". -You can explicitly request it by using flag #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT. -The library can also internally decide to use dedicated allocation in some cases, e.g.: - -- When the size of the allocation is large. -- When [VK_KHR_dedicated_allocation](@ref vk_khr_dedicated_allocation) extension is enabled - and it reports that dedicated allocation is required or recommended for the resource. -- When allocation of next big memory block fails due to not enough device memory, - but allocation with the exact requested size succeeds. - - -\page memory_mapping Memory mapping - -To "map memory" in Vulkan means to obtain a CPU pointer to `VkDeviceMemory`, -to be able to read from it or write to it in CPU code. -Mapping is possible only of memory allocated from a memory type that has -`VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` flag. -Functions `vkMapMemory()`, `vkUnmapMemory()` are designed for this purpose. -You can use them directly with memory allocated by this library, -but it is not recommended because of following issue: -Mapping the same `VkDeviceMemory` block multiple times is illegal - only one mapping at a time is allowed. -This includes mapping disjoint regions. Mapping is not reference-counted internally by Vulkan. -Because of this, Vulkan Memory Allocator provides following facilities: - -\note If you want to be able to map an allocation, you need to specify one of the flags -#VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT -in VmaAllocationCreateInfo::flags. These flags are required for an allocation to be mappable -when using #VMA_MEMORY_USAGE_AUTO or other `VMA_MEMORY_USAGE_AUTO*` enum values. -For other usage values they are ignored and every such allocation made in `HOST_VISIBLE` memory type is mappable, -but they can still be used for consistency. - -\section memory_mapping_mapping_functions Mapping functions - -The library provides following functions for mapping of a specific #VmaAllocation: vmaMapMemory(), vmaUnmapMemory(). -They are safer and more convenient to use than standard Vulkan functions. -You can map an allocation multiple times simultaneously - mapping is reference-counted internally. -You can also map different allocations simultaneously regardless of whether they use the same `VkDeviceMemory` block. -The way it is implemented is that the library always maps entire memory block, not just region of the allocation. -For further details, see description of vmaMapMemory() function. -Example: - -\code -// Having these objects initialized: -struct ConstantBuffer -{ - ... -}; -ConstantBuffer constantBufferData = ... - -VmaAllocator allocator = ... -VkBuffer constantBuffer = ... -VmaAllocation constantBufferAllocation = ... - -// You can map and fill your buffer using following code: - -void* mappedData; -vmaMapMemory(allocator, constantBufferAllocation, &mappedData); -memcpy(mappedData, &constantBufferData, sizeof(constantBufferData)); -vmaUnmapMemory(allocator, constantBufferAllocation); -\endcode - -When mapping, you may see a warning from Vulkan validation layer similar to this one: - -Mapping an image with layout VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL can result in undefined behavior if this memory is used by the device. Only GENERAL or PREINITIALIZED should be used. - -It happens because the library maps entire `VkDeviceMemory` block, where different -types of images and buffers may end up together, especially on GPUs with unified memory like Intel. -You can safely ignore it if you are sure you access only memory of the intended -object that you wanted to map. - - -\section memory_mapping_persistently_mapped_memory Persistently mapped memory - -Keeping your memory persistently mapped is generally OK in Vulkan. -You don't need to unmap it before using its data on the GPU. -The library provides a special feature designed for that: -Allocations made with #VMA_ALLOCATION_CREATE_MAPPED_BIT flag set in -VmaAllocationCreateInfo::flags stay mapped all the time, -so you can just access CPU pointer to it any time -without a need to call any "map" or "unmap" function. -Example: - -\code -VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; -bufCreateInfo.size = sizeof(ConstantBuffer); -bufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; - -VmaAllocationCreateInfo allocCreateInfo = {}; -allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; -allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | - VMA_ALLOCATION_CREATE_MAPPED_BIT; - -VkBuffer buf; -VmaAllocation alloc; -VmaAllocationInfo allocInfo; -vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo); - -// Buffer is already mapped. You can access its memory. -memcpy(allocInfo.pMappedData, &constantBufferData, sizeof(constantBufferData)); -\endcode - -\note #VMA_ALLOCATION_CREATE_MAPPED_BIT by itself doesn't guarantee that the allocation will end up -in a mappable memory type. -For this, you need to also specify #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT or -#VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT. -#VMA_ALLOCATION_CREATE_MAPPED_BIT only guarantees that if the memory is `HOST_VISIBLE`, the allocation will be mapped on creation. -For an example of how to make use of this fact, see section \ref usage_patterns_advanced_data_uploading. - -\section memory_mapping_cache_control Cache flush and invalidate - -Memory in Vulkan doesn't need to be unmapped before using it on GPU, -but unless a memory types has `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT` flag set, -you need to manually **invalidate** cache before reading of mapped pointer -and **flush** cache after writing to mapped pointer. -Map/unmap operations don't do that automatically. -Vulkan provides following functions for this purpose `vkFlushMappedMemoryRanges()`, -`vkInvalidateMappedMemoryRanges()`, but this library provides more convenient -functions that refer to given allocation object: vmaFlushAllocation(), -vmaInvalidateAllocation(), -or multiple objects at once: vmaFlushAllocations(), vmaInvalidateAllocations(). - -Regions of memory specified for flush/invalidate must be aligned to -`VkPhysicalDeviceLimits::nonCoherentAtomSize`. This is automatically ensured by the library. -In any memory type that is `HOST_VISIBLE` but not `HOST_COHERENT`, all allocations -within blocks are aligned to this value, so their offsets are always multiply of -`nonCoherentAtomSize` and two different allocations never share same "line" of this size. - -Also, Windows drivers from all 3 PC GPU vendors (AMD, Intel, NVIDIA) -currently provide `HOST_COHERENT` flag on all memory types that are -`HOST_VISIBLE`, so on PC you may not need to bother. - - -\page staying_within_budget Staying within budget - -When developing a graphics-intensive game or program, it is important to avoid allocating -more GPU memory than it is physically available. When the memory is over-committed, -various bad things can happen, depending on the specific GPU, graphics driver, and -operating system: - -- It may just work without any problems. -- The application may slow down because some memory blocks are moved to system RAM - and the GPU has to access them through PCI Express bus. -- A new allocation may take very long time to complete, even few seconds, and possibly - freeze entire system. -- The new allocation may fail with `VK_ERROR_OUT_OF_DEVICE_MEMORY`. -- It may even result in GPU crash (TDR), observed as `VK_ERROR_DEVICE_LOST` - returned somewhere later. - -\section staying_within_budget_querying_for_budget Querying for budget - -To query for current memory usage and available budget, use function vmaGetHeapBudgets(). -Returned structure #VmaBudget contains quantities expressed in bytes, per Vulkan memory heap. - -Please note that this function returns different information and works faster than -vmaCalculateStatistics(). vmaGetHeapBudgets() can be called every frame or even before every -allocation, while vmaCalculateStatistics() is intended to be used rarely, -only to obtain statistical information, e.g. for debugging purposes. - -It is recommended to use VK_EXT_memory_budget device extension to obtain information -about the budget from Vulkan device. VMA is able to use this extension automatically. -When not enabled, the allocator behaves same way, but then it estimates current usage -and available budget based on its internal information and Vulkan memory heap sizes, -which may be less precise. In order to use this extension: - -1. Make sure extensions VK_EXT_memory_budget and VK_KHR_get_physical_device_properties2 - required by it are available and enable them. Please note that the first is a device - extension and the second is instance extension! -2. Use flag #VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT when creating #VmaAllocator object. -3. Make sure to call vmaSetCurrentFrameIndex() every frame. Budget is queried from - Vulkan inside of it to avoid overhead of querying it with every allocation. - -\section staying_within_budget_controlling_memory_usage Controlling memory usage - -There are many ways in which you can try to stay within the budget. - -First, when making new allocation requires allocating a new memory block, the library -tries not to exceed the budget automatically. If a block with default recommended size -(e.g. 256 MB) would go over budget, a smaller block is allocated, possibly even -dedicated memory for just this resource. - -If the size of the requested resource plus current memory usage is more than the -budget, by default the library still tries to create it, leaving it to the Vulkan -implementation whether the allocation succeeds or fails. You can change this behavior -by using #VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT flag. With it, the allocation is -not made if it would exceed the budget or if the budget is already exceeded. -VMA then tries to make the allocation from the next eligible Vulkan memory type. -The all of them fail, the call then fails with `VK_ERROR_OUT_OF_DEVICE_MEMORY`. -Example usage pattern may be to pass the #VMA_ALLOCATION_CREATE_WITHIN_BUDGET_BIT flag -when creating resources that are not essential for the application (e.g. the texture -of a specific object) and not to pass it when creating critically important resources -(e.g. render targets). - -On AMD graphics cards there is a custom vendor extension available: VK_AMD_memory_overallocation_behavior -that allows to control the behavior of the Vulkan implementation in out-of-memory cases - -whether it should fail with an error code or still allow the allocation. -Usage of this extension involves only passing extra structure on Vulkan device creation, -so it is out of scope of this library. - -Finally, you can also use #VMA_ALLOCATION_CREATE_NEVER_ALLOCATE_BIT flag to make sure -a new allocation is created only when it fits inside one of the existing memory blocks. -If it would require to allocate a new block, if fails instead with `VK_ERROR_OUT_OF_DEVICE_MEMORY`. -This also ensures that the function call is very fast because it never goes to Vulkan -to obtain a new block. - -\note Creating \ref custom_memory_pools with VmaPoolCreateInfo::minBlockCount -set to more than 0 will currently try to allocate memory blocks without checking whether they -fit within budget. - - -\page resource_aliasing Resource aliasing (overlap) - -New explicit graphics APIs (Vulkan and Direct3D 12), thanks to manual memory -management, give an opportunity to alias (overlap) multiple resources in the -same region of memory - a feature not available in the old APIs (Direct3D 11, OpenGL). -It can be useful to save video memory, but it must be used with caution. - -For example, if you know the flow of your whole render frame in advance, you -are going to use some intermediate textures or buffers only during a small range of render passes, -and you know these ranges don't overlap in time, you can bind these resources to -the same place in memory, even if they have completely different parameters (width, height, format etc.). - -![Resource aliasing (overlap)](../gfx/Aliasing.png) - -Such scenario is possible using VMA, but you need to create your images manually. -Then you need to calculate parameters of an allocation to be made using formula: - -- allocation size = max(size of each image) -- allocation alignment = max(alignment of each image) -- allocation memoryTypeBits = bitwise AND(memoryTypeBits of each image) - -Following example shows two different images bound to the same place in memory, -allocated to fit largest of them. - -\code -// A 512x512 texture to be sampled. -VkImageCreateInfo img1CreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO }; -img1CreateInfo.imageType = VK_IMAGE_TYPE_2D; -img1CreateInfo.extent.width = 512; -img1CreateInfo.extent.height = 512; -img1CreateInfo.extent.depth = 1; -img1CreateInfo.mipLevels = 10; -img1CreateInfo.arrayLayers = 1; -img1CreateInfo.format = VK_FORMAT_R8G8B8A8_SRGB; -img1CreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL; -img1CreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; -img1CreateInfo.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; -img1CreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; - -// A full screen texture to be used as color attachment. -VkImageCreateInfo img2CreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO }; -img2CreateInfo.imageType = VK_IMAGE_TYPE_2D; -img2CreateInfo.extent.width = 1920; -img2CreateInfo.extent.height = 1080; -img2CreateInfo.extent.depth = 1; -img2CreateInfo.mipLevels = 1; -img2CreateInfo.arrayLayers = 1; -img2CreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM; -img2CreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL; -img2CreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; -img2CreateInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; -img2CreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; - -VkImage img1; -res = vkCreateImage(device, &img1CreateInfo, nullptr, &img1); -VkImage img2; -res = vkCreateImage(device, &img2CreateInfo, nullptr, &img2); - -VkMemoryRequirements img1MemReq; -vkGetImageMemoryRequirements(device, img1, &img1MemReq); -VkMemoryRequirements img2MemReq; -vkGetImageMemoryRequirements(device, img2, &img2MemReq); - -VkMemoryRequirements finalMemReq = {}; -finalMemReq.size = std::max(img1MemReq.size, img2MemReq.size); -finalMemReq.alignment = std::max(img1MemReq.alignment, img2MemReq.alignment); -finalMemReq.memoryTypeBits = img1MemReq.memoryTypeBits & img2MemReq.memoryTypeBits; -// Validate if(finalMemReq.memoryTypeBits != 0) - -VmaAllocationCreateInfo allocCreateInfo = {}; -allocCreateInfo.preferredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; - -VmaAllocation alloc; -res = vmaAllocateMemory(allocator, &finalMemReq, &allocCreateInfo, &alloc, nullptr); - -res = vmaBindImageMemory(allocator, alloc, img1); -res = vmaBindImageMemory(allocator, alloc, img2); - -// You can use img1, img2 here, but not at the same time! - -vmaFreeMemory(allocator, alloc); -vkDestroyImage(allocator, img2, nullptr); -vkDestroyImage(allocator, img1, nullptr); -\endcode - -Remember that using resources that alias in memory requires proper synchronization. -You need to issue a memory barrier to make sure commands that use `img1` and `img2` -don't overlap on GPU timeline. -You also need to treat a resource after aliasing as uninitialized - containing garbage data. -For example, if you use `img1` and then want to use `img2`, you need to issue -an image memory barrier for `img2` with `oldLayout` = `VK_IMAGE_LAYOUT_UNDEFINED`. - -Additional considerations: - -- Vulkan also allows to interpret contents of memory between aliasing resources consistently in some cases. -See chapter 11.8. "Memory Aliasing" of Vulkan specification or `VK_IMAGE_CREATE_ALIAS_BIT` flag. -- You can create more complex layout where different images and buffers are bound -at different offsets inside one large allocation. For example, one can imagine -a big texture used in some render passes, aliasing with a set of many small buffers -used between in some further passes. To bind a resource at non-zero offset in an allocation, -use vmaBindBufferMemory2() / vmaBindImageMemory2(). -- Before allocating memory for the resources you want to alias, check `memoryTypeBits` -returned in memory requirements of each resource to make sure the bits overlap. -Some GPUs may expose multiple memory types suitable e.g. only for buffers or -images with `COLOR_ATTACHMENT` usage, so the sets of memory types supported by your -resources may be disjoint. Aliasing them is not possible in that case. - - -\page custom_memory_pools Custom memory pools - -A memory pool contains a number of `VkDeviceMemory` blocks. -The library automatically creates and manages default pool for each memory type available on the device. -Default memory pool automatically grows in size. -Size of allocated blocks is also variable and managed automatically. - -You can create custom pool and allocate memory out of it. -It can be useful if you want to: - -- Keep certain kind of allocations separate from others. -- Enforce particular, fixed size of Vulkan memory blocks. -- Limit maximum amount of Vulkan memory allocated for that pool. -- Reserve minimum or fixed amount of Vulkan memory always preallocated for that pool. -- Use extra parameters for a set of your allocations that are available in #VmaPoolCreateInfo but not in - #VmaAllocationCreateInfo - e.g., custom minimum alignment, custom `pNext` chain. -- Perform defragmentation on a specific subset of your allocations. - -To use custom memory pools: - --# Fill VmaPoolCreateInfo structure. --# Call vmaCreatePool() to obtain #VmaPool handle. --# When making an allocation, set VmaAllocationCreateInfo::pool to this handle. - You don't need to specify any other parameters of this structure, like `usage`. - -Example: - -\code -// Find memoryTypeIndex for the pool. -VkBufferCreateInfo sampleBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; -sampleBufCreateInfo.size = 0x10000; // Doesn't matter. -sampleBufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - -VmaAllocationCreateInfo sampleAllocCreateInfo = {}; -sampleAllocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; - -uint32_t memTypeIndex; -VkResult res = vmaFindMemoryTypeIndexForBufferInfo(allocator, - &sampleBufCreateInfo, &sampleAllocCreateInfo, &memTypeIndex); -// Check res... - -// Create a pool that can have at most 2 blocks, 128 MiB each. -VmaPoolCreateInfo poolCreateInfo = {}; -poolCreateInfo.memoryTypeIndex = memTypeIndex; -poolCreateInfo.blockSize = 128ull * 1024 * 1024; -poolCreateInfo.maxBlockCount = 2; - -VmaPool pool; -res = vmaCreatePool(allocator, &poolCreateInfo, &pool); -// Check res... - -// Allocate a buffer out of it. -VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; -bufCreateInfo.size = 1024; -bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - -VmaAllocationCreateInfo allocCreateInfo = {}; -allocCreateInfo.pool = pool; - -VkBuffer buf; -VmaAllocation alloc; -res = vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, nullptr); -// Check res... -\endcode - -You have to free all allocations made from this pool before destroying it. - -\code -vmaDestroyBuffer(allocator, buf, alloc); -vmaDestroyPool(allocator, pool); -\endcode - -New versions of this library support creating dedicated allocations in custom pools. -It is supported only when VmaPoolCreateInfo::blockSize = 0. -To use this feature, set VmaAllocationCreateInfo::pool to the pointer to your custom pool and -VmaAllocationCreateInfo::flags to #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT. - -\note Excessive use of custom pools is a common mistake when using this library. -Custom pools may be useful for special purposes - when you want to -keep certain type of resources separate e.g. to reserve minimum amount of memory -for them or limit maximum amount of memory they can occupy. For most -resources this is not needed and so it is not recommended to create #VmaPool -objects and allocations out of them. Allocating from the default pool is sufficient. - - -\section custom_memory_pools_MemTypeIndex Choosing memory type index - -When creating a pool, you must explicitly specify memory type index. -To find the one suitable for your buffers or images, you can use helper functions -vmaFindMemoryTypeIndexForBufferInfo(), vmaFindMemoryTypeIndexForImageInfo(). -You need to provide structures with example parameters of buffers or images -that you are going to create in that pool. - -\code -VkBufferCreateInfo exampleBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; -exampleBufCreateInfo.size = 1024; // Doesn't matter -exampleBufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - -VmaAllocationCreateInfo allocCreateInfo = {}; -allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; - -uint32_t memTypeIndex; -vmaFindMemoryTypeIndexForBufferInfo(allocator, &exampleBufCreateInfo, &allocCreateInfo, &memTypeIndex); - -VmaPoolCreateInfo poolCreateInfo = {}; -poolCreateInfo.memoryTypeIndex = memTypeIndex; -// ... -\endcode - -When creating buffers/images allocated in that pool, provide following parameters: - -- `VkBufferCreateInfo`: Prefer to pass same parameters as above. - Otherwise you risk creating resources in a memory type that is not suitable for them, which may result in undefined behavior. - Using different `VK_BUFFER_USAGE_` flags may work, but you shouldn't create images in a pool intended for buffers - or the other way around. -- VmaAllocationCreateInfo: You don't need to pass same parameters. Fill only `pool` member. - Other members are ignored anyway. - -\section linear_algorithm Linear allocation algorithm - -Each Vulkan memory block managed by this library has accompanying metadata that -keeps track of used and unused regions. By default, the metadata structure and -algorithm tries to find best place for new allocations among free regions to -optimize memory usage. This way you can allocate and free objects in any order. - -![Default allocation algorithm](../gfx/Linear_allocator_1_algo_default.png) - -Sometimes there is a need to use simpler, linear allocation algorithm. You can -create custom pool that uses such algorithm by adding flag -#VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT to VmaPoolCreateInfo::flags while creating -#VmaPool object. Then an alternative metadata management is used. It always -creates new allocations after last one and doesn't reuse free regions after -allocations freed in the middle. It results in better allocation performance and -less memory consumed by metadata. - -![Linear allocation algorithm](../gfx/Linear_allocator_2_algo_linear.png) - -With this one flag, you can create a custom pool that can be used in many ways: -free-at-once, stack, double stack, and ring buffer. See below for details. -You don't need to specify explicitly which of these options you are going to use - it is detected automatically. - -\subsection linear_algorithm_free_at_once Free-at-once - -In a pool that uses linear algorithm, you still need to free all the allocations -individually, e.g. by using vmaFreeMemory() or vmaDestroyBuffer(). You can free -them in any order. New allocations are always made after last one - free space -in the middle is not reused. However, when you release all the allocation and -the pool becomes empty, allocation starts from the beginning again. This way you -can use linear algorithm to speed up creation of allocations that you are going -to release all at once. - -![Free-at-once](../gfx/Linear_allocator_3_free_at_once.png) - -This mode is also available for pools created with VmaPoolCreateInfo::maxBlockCount -value that allows multiple memory blocks. - -\subsection linear_algorithm_stack Stack - -When you free an allocation that was created last, its space can be reused. -Thanks to this, if you always release allocations in the order opposite to their -creation (LIFO - Last In First Out), you can achieve behavior of a stack. - -![Stack](../gfx/Linear_allocator_4_stack.png) - -This mode is also available for pools created with VmaPoolCreateInfo::maxBlockCount -value that allows multiple memory blocks. - -\subsection linear_algorithm_double_stack Double stack - -The space reserved by a custom pool with linear algorithm may be used by two -stacks: - -- First, default one, growing up from offset 0. -- Second, "upper" one, growing down from the end towards lower offsets. - -To make allocation from the upper stack, add flag #VMA_ALLOCATION_CREATE_UPPER_ADDRESS_BIT -to VmaAllocationCreateInfo::flags. - -![Double stack](../gfx/Linear_allocator_7_double_stack.png) - -Double stack is available only in pools with one memory block - -VmaPoolCreateInfo::maxBlockCount must be 1. Otherwise behavior is undefined. - -When the two stacks' ends meet so there is not enough space between them for a -new allocation, such allocation fails with usual -`VK_ERROR_OUT_OF_DEVICE_MEMORY` error. - -\subsection linear_algorithm_ring_buffer Ring buffer - -When you free some allocations from the beginning and there is not enough free space -for a new one at the end of a pool, allocator's "cursor" wraps around to the -beginning and starts allocation there. Thanks to this, if you always release -allocations in the same order as you created them (FIFO - First In First Out), -you can achieve behavior of a ring buffer / queue. - -![Ring buffer](../gfx/Linear_allocator_5_ring_buffer.png) - -Ring buffer is available only in pools with one memory block - -VmaPoolCreateInfo::maxBlockCount must be 1. Otherwise behavior is undefined. - -\note \ref defragmentation is not supported in custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT. - - -\page defragmentation Defragmentation - -Interleaved allocations and deallocations of many objects of varying size can -cause fragmentation over time, which can lead to a situation where the library is unable -to find a continuous range of free memory for a new allocation despite there is -enough free space, just scattered across many small free ranges between existing -allocations. - -To mitigate this problem, you can use defragmentation feature. -It doesn't happen automatically though and needs your cooperation, -because VMA is a low level library that only allocates memory. -It cannot recreate buffers and images in a new place as it doesn't remember the contents of `VkBufferCreateInfo` / `VkImageCreateInfo` structures. -It cannot copy their contents as it doesn't record any commands to a command buffer. - -Example: - -\code -VmaDefragmentationInfo defragInfo = {}; -defragInfo.pool = myPool; -defragInfo.flags = VMA_DEFRAGMENTATION_FLAG_ALGORITHM_FAST_BIT; - -VmaDefragmentationContext defragCtx; -VkResult res = vmaBeginDefragmentation(allocator, &defragInfo, &defragCtx); -// Check res... - -for(;;) -{ - VmaDefragmentationPassMoveInfo pass; - res = vmaBeginDefragmentationPass(allocator, defragCtx, &pass); - if(res == VK_SUCCESS) - break; - else if(res != VK_INCOMPLETE) - // Handle error... - - for(uint32_t i = 0; i < pass.moveCount; ++i) - { - // Inspect pass.pMoves[i].srcAllocation, identify what buffer/image it represents. - VmaAllocationInfo allocInfo; - vmaGetAllocationInfo(allocator, pMoves[i].srcAllocation, &allocInfo); - MyEngineResourceData* resData = (MyEngineResourceData*)allocInfo.pUserData; - - // Recreate and bind this buffer/image at: pass.pMoves[i].dstMemory, pass.pMoves[i].dstOffset. - VkImageCreateInfo imgCreateInfo = ... - VkImage newImg; - res = vkCreateImage(device, &imgCreateInfo, nullptr, &newImg); - // Check res... - res = vmaBindImageMemory(allocator, pMoves[i].dstTmpAllocation, newImg); - // Check res... - - // Issue a vkCmdCopyBuffer/vkCmdCopyImage to copy its content to the new place. - vkCmdCopyImage(cmdBuf, resData->img, ..., newImg, ...); - } - - // Make sure the copy commands finished executing. - vkWaitForFences(...); - - // Destroy old buffers/images bound with pass.pMoves[i].srcAllocation. - for(uint32_t i = 0; i < pass.moveCount; ++i) - { - // ... - vkDestroyImage(device, resData->img, nullptr); - } - - // Update appropriate descriptors to point to the new places... - - res = vmaEndDefragmentationPass(allocator, defragCtx, &pass); - if(res == VK_SUCCESS) - break; - else if(res != VK_INCOMPLETE) - // Handle error... -} - -vmaEndDefragmentation(allocator, defragCtx, nullptr); -\endcode - -Although functions like vmaCreateBuffer(), vmaCreateImage(), vmaDestroyBuffer(), vmaDestroyImage() -create/destroy an allocation and a buffer/image at once, these are just a shortcut for -creating the resource, allocating memory, and binding them together. -Defragmentation works on memory allocations only. You must handle the rest manually. -Defragmentation is an iterative process that should repreat "passes" as long as related functions -return `VK_INCOMPLETE` not `VK_SUCCESS`. -In each pass: - -1. vmaBeginDefragmentationPass() function call: - - Calculates and returns the list of allocations to be moved in this pass. - Note this can be a time-consuming process. - - Reserves destination memory for them by creating temporary destination allocations - that you can query for their `VkDeviceMemory` + offset using vmaGetAllocationInfo(). -2. Inside the pass, **you should**: - - Inspect the returned list of allocations to be moved. - - Create new buffers/images and bind them at the returned destination temporary allocations. - - Copy data from source to destination resources if necessary. - - Destroy the source buffers/images, but NOT their allocations. -3. vmaEndDefragmentationPass() function call: - - Frees the source memory reserved for the allocations that are moved. - - Modifies source #VmaAllocation objects that are moved to point to the destination reserved memory. - - Frees `VkDeviceMemory` blocks that became empty. - -Unlike in previous iterations of the defragmentation API, there is no list of "movable" allocations passed as a parameter. -Defragmentation algorithm tries to move all suitable allocations. -You can, however, refuse to move some of them inside a defragmentation pass, by setting -`pass.pMoves[i].operation` to #VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE. -This is not recommended and may result in suboptimal packing of the allocations after defragmentation. -If you cannot ensure any allocation can be moved, it is better to keep movable allocations separate in a custom pool. - -Inside a pass, for each allocation that should be moved: - -- You should copy its data from the source to the destination place by calling e.g. `vkCmdCopyBuffer()`, `vkCmdCopyImage()`. - - You need to make sure these commands finished executing before destroying the source buffers/images and before calling vmaEndDefragmentationPass(). -- If a resource doesn't contain any meaningful data, e.g. it is a transient color attachment image to be cleared, - filled, and used temporarily in each rendering frame, you can just recreate this image - without copying its data. -- If the resource is in `HOST_VISIBLE` and `HOST_CACHED` memory, you can copy its data on the CPU - using `memcpy()`. -- If you cannot move the allocation, you can set `pass.pMoves[i].operation` to #VMA_DEFRAGMENTATION_MOVE_OPERATION_IGNORE. - This will cancel the move. - - vmaEndDefragmentationPass() will then free the destination memory - not the source memory of the allocation, leaving it unchanged. -- If you decide the allocation is unimportant and can be destroyed instead of moved (e.g. it wasn't used for long time), - you can set `pass.pMoves[i].operation` to #VMA_DEFRAGMENTATION_MOVE_OPERATION_DESTROY. - - vmaEndDefragmentationPass() will then free both source and destination memory, and will destroy the source #VmaAllocation object. - -You can defragment a specific custom pool by setting VmaDefragmentationInfo::pool -(like in the example above) or all the default pools by setting this member to null. - -Defragmentation is always performed in each pool separately. -Allocations are never moved between different Vulkan memory types. -The size of the destination memory reserved for a moved allocation is the same as the original one. -Alignment of an allocation as it was determined using `vkGetBufferMemoryRequirements()` etc. is also respected after defragmentation. -Buffers/images should be recreated with the same `VkBufferCreateInfo` / `VkImageCreateInfo` parameters as the original ones. - -You can perform the defragmentation incrementally to limit the number of allocations and bytes to be moved -in each pass, e.g. to call it in sync with render frames and not to experience too big hitches. -See members: VmaDefragmentationInfo::maxBytesPerPass, VmaDefragmentationInfo::maxAllocationsPerPass. - -It is also safe to perform the defragmentation asynchronously to render frames and other Vulkan and VMA -usage, possibly from multiple threads, with the exception that allocations -returned in VmaDefragmentationPassMoveInfo::pMoves shouldn't be destroyed until the defragmentation pass is ended. - -Mapping is preserved on allocations that are moved during defragmentation. -Whether through #VMA_ALLOCATION_CREATE_MAPPED_BIT or vmaMapMemory(), the allocations -are mapped at their new place. Of course, pointer to the mapped data changes, so it needs to be queried -using VmaAllocationInfo::pMappedData. - -\note Defragmentation is not supported in custom pools created with #VMA_POOL_CREATE_LINEAR_ALGORITHM_BIT. - - -\page statistics Statistics - -This library contains several functions that return information about its internal state, -especially the amount of memory allocated from Vulkan. - -\section statistics_numeric_statistics Numeric statistics - -If you need to obtain basic statistics about memory usage per heap, together with current budget, -you can call function vmaGetHeapBudgets() and inspect structure #VmaBudget. -This is useful to keep track of memory usage and stay within budget -(see also \ref staying_within_budget). -Example: - -\code -uint32_t heapIndex = ... - -VmaBudget budgets[VK_MAX_MEMORY_HEAPS]; -vmaGetHeapBudgets(allocator, budgets); - -printf("My heap currently has %u allocations taking %llu B,\n", - budgets[heapIndex].statistics.allocationCount, - budgets[heapIndex].statistics.allocationBytes); -printf("allocated out of %u Vulkan device memory blocks taking %llu B,\n", - budgets[heapIndex].statistics.blockCount, - budgets[heapIndex].statistics.blockBytes); -printf("Vulkan reports total usage %llu B with budget %llu B.\n", - budgets[heapIndex].usage, - budgets[heapIndex].budget); -\endcode - -You can query for more detailed statistics per memory heap, type, and totals, -including minimum and maximum allocation size and unused range size, -by calling function vmaCalculateStatistics() and inspecting structure #VmaTotalStatistics. -This function is slower though, as it has to traverse all the internal data structures, -so it should be used only for debugging purposes. - -You can query for statistics of a custom pool using function vmaGetPoolStatistics() -or vmaCalculatePoolStatistics(). - -You can query for information about a specific allocation using function vmaGetAllocationInfo(). -It fill structure #VmaAllocationInfo. - -\section statistics_json_dump JSON dump - -You can dump internal state of the allocator to a string in JSON format using function vmaBuildStatsString(). -The result is guaranteed to be correct JSON. -It uses ANSI encoding. -Any strings provided by user (see [Allocation names](@ref allocation_names)) -are copied as-is and properly escaped for JSON, so if they use UTF-8, ISO-8859-2 or any other encoding, -this JSON string can be treated as using this encoding. -It must be freed using function vmaFreeStatsString(). - -The format of this JSON string is not part of official documentation of the library, -but it will not change in backward-incompatible way without increasing library major version number -and appropriate mention in changelog. - -The JSON string contains all the data that can be obtained using vmaCalculateStatistics(). -It can also contain detailed map of allocated memory blocks and their regions - -free and occupied by allocations. -This allows e.g. to visualize the memory or assess fragmentation. - - -\page allocation_annotation Allocation names and user data - -\section allocation_user_data Allocation user data - -You can annotate allocations with your own information, e.g. for debugging purposes. -To do that, fill VmaAllocationCreateInfo::pUserData field when creating -an allocation. It is an opaque `void*` pointer. You can use it e.g. as a pointer, -some handle, index, key, ordinal number or any other value that would associate -the allocation with your custom metadata. -It is useful to identify appropriate data structures in your engine given #VmaAllocation, -e.g. when doing \ref defragmentation. - -\code -VkBufferCreateInfo bufCreateInfo = ... - -MyBufferMetadata* pMetadata = CreateBufferMetadata(); - -VmaAllocationCreateInfo allocCreateInfo = {}; -allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; -allocCreateInfo.pUserData = pMetadata; - -VkBuffer buffer; -VmaAllocation allocation; -vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buffer, &allocation, nullptr); -\endcode - -The pointer may be later retrieved as VmaAllocationInfo::pUserData: - -\code -VmaAllocationInfo allocInfo; -vmaGetAllocationInfo(allocator, allocation, &allocInfo); -MyBufferMetadata* pMetadata = (MyBufferMetadata*)allocInfo.pUserData; -\endcode - -It can also be changed using function vmaSetAllocationUserData(). - -Values of (non-zero) allocations' `pUserData` are printed in JSON report created by -vmaBuildStatsString() in hexadecimal form. - -\section allocation_names Allocation names - -An allocation can also carry a null-terminated string, giving a name to the allocation. -To set it, call vmaSetAllocationName(). -The library creates internal copy of the string, so the pointer you pass doesn't need -to be valid for whole lifetime of the allocation. You can free it after the call. - -\code -std::string imageName = "Texture: "; -imageName += fileName; -vmaSetAllocationName(allocator, allocation, imageName.c_str()); -\endcode - -The string can be later retrieved by inspecting VmaAllocationInfo::pName. -It is also printed in JSON report created by vmaBuildStatsString(). - -\note Setting string name to VMA allocation doesn't automatically set it to the Vulkan buffer or image created with it. -You must do it manually using an extension like VK_EXT_debug_utils, which is independent of this library. - - -\page virtual_allocator Virtual allocator - -As an extra feature, the core allocation algorithm of the library is exposed through a simple and convenient API of "virtual allocator". -It doesn't allocate any real GPU memory. It just keeps track of used and free regions of a "virtual block". -You can use it to allocate your own memory or other objects, even completely unrelated to Vulkan. -A common use case is sub-allocation of pieces of one large GPU buffer. - -\section virtual_allocator_creating_virtual_block Creating virtual block - -To use this functionality, there is no main "allocator" object. -You don't need to have #VmaAllocator object created. -All you need to do is to create a separate #VmaVirtualBlock object for each block of memory you want to be managed by the allocator: - --# Fill in #VmaVirtualBlockCreateInfo structure. --# Call vmaCreateVirtualBlock(). Get new #VmaVirtualBlock object. - -Example: - -\code -VmaVirtualBlockCreateInfo blockCreateInfo = {}; -blockCreateInfo.size = 1048576; // 1 MB - -VmaVirtualBlock block; -VkResult res = vmaCreateVirtualBlock(&blockCreateInfo, &block); -\endcode - -\section virtual_allocator_making_virtual_allocations Making virtual allocations - -#VmaVirtualBlock object contains internal data structure that keeps track of free and occupied regions -using the same code as the main Vulkan memory allocator. -Similarly to #VmaAllocation for standard GPU allocations, there is #VmaVirtualAllocation type -that represents an opaque handle to an allocation within the virtual block. - -In order to make such allocation: - --# Fill in #VmaVirtualAllocationCreateInfo structure. --# Call vmaVirtualAllocate(). Get new #VmaVirtualAllocation object that represents the allocation. - You can also receive `VkDeviceSize offset` that was assigned to the allocation. - -Example: - -\code -VmaVirtualAllocationCreateInfo allocCreateInfo = {}; -allocCreateInfo.size = 4096; // 4 KB - -VmaVirtualAllocation alloc; -VkDeviceSize offset; -res = vmaVirtualAllocate(block, &allocCreateInfo, &alloc, &offset); -if(res == VK_SUCCESS) -{ - // Use the 4 KB of your memory starting at offset. -} -else -{ - // Allocation failed - no space for it could be found. Handle this error! -} -\endcode - -\section virtual_allocator_deallocation Deallocation - -When no longer needed, an allocation can be freed by calling vmaVirtualFree(). -You can only pass to this function an allocation that was previously returned by vmaVirtualAllocate() -called for the same #VmaVirtualBlock. - -When whole block is no longer needed, the block object can be released by calling vmaDestroyVirtualBlock(). -All allocations must be freed before the block is destroyed, which is checked internally by an assert. -However, if you don't want to call vmaVirtualFree() for each allocation, you can use vmaClearVirtualBlock() to free them all at once - -a feature not available in normal Vulkan memory allocator. Example: - -\code -vmaVirtualFree(block, alloc); -vmaDestroyVirtualBlock(block); -\endcode - -\section virtual_allocator_allocation_parameters Allocation parameters - -You can attach a custom pointer to each allocation by using vmaSetVirtualAllocationUserData(). -Its default value is null. -It can be used to store any data that needs to be associated with that allocation - e.g. an index, a handle, or a pointer to some -larger data structure containing more information. Example: - -\code -struct CustomAllocData -{ - std::string m_AllocName; -}; -CustomAllocData* allocData = new CustomAllocData(); -allocData->m_AllocName = "My allocation 1"; -vmaSetVirtualAllocationUserData(block, alloc, allocData); -\endcode - -The pointer can later be fetched, along with allocation offset and size, by passing the allocation handle to function -vmaGetVirtualAllocationInfo() and inspecting returned structure #VmaVirtualAllocationInfo. -If you allocated a new object to be used as the custom pointer, don't forget to delete that object before freeing the allocation! -Example: - -\code -VmaVirtualAllocationInfo allocInfo; -vmaGetVirtualAllocationInfo(block, alloc, &allocInfo); -delete (CustomAllocData*)allocInfo.pUserData; - -vmaVirtualFree(block, alloc); -\endcode - -\section virtual_allocator_alignment_and_units Alignment and units - -It feels natural to express sizes and offsets in bytes. -If an offset of an allocation needs to be aligned to a multiply of some number (e.g. 4 bytes), you can fill optional member -VmaVirtualAllocationCreateInfo::alignment to request it. Example: - -\code -VmaVirtualAllocationCreateInfo allocCreateInfo = {}; -allocCreateInfo.size = 4096; // 4 KB -allocCreateInfo.alignment = 4; // Returned offset must be a multiply of 4 B - -VmaVirtualAllocation alloc; -res = vmaVirtualAllocate(block, &allocCreateInfo, &alloc, nullptr); -\endcode - -Alignments of different allocations made from one block may vary. -However, if all alignments and sizes are always multiply of some size e.g. 4 B or `sizeof(MyDataStruct)`, -you can express all sizes, alignments, and offsets in multiples of that size instead of individual bytes. -It might be more convenient, but you need to make sure to use this new unit consistently in all the places: - -- VmaVirtualBlockCreateInfo::size -- VmaVirtualAllocationCreateInfo::size and VmaVirtualAllocationCreateInfo::alignment -- Using offset returned by vmaVirtualAllocate() or in VmaVirtualAllocationInfo::offset - -\section virtual_allocator_statistics Statistics - -You can obtain statistics of a virtual block using vmaGetVirtualBlockStatistics() -(to get brief statistics that are fast to calculate) -or vmaCalculateVirtualBlockStatistics() (to get more detailed statistics, slower to calculate). -The functions fill structures #VmaStatistics, #VmaDetailedStatistics respectively - same as used by the normal Vulkan memory allocator. -Example: - -\code -VmaStatistics stats; -vmaGetVirtualBlockStatistics(block, &stats); -printf("My virtual block has %llu bytes used by %u virtual allocations\n", - stats.allocationBytes, stats.allocationCount); -\endcode - -You can also request a full list of allocations and free regions as a string in JSON format by calling -vmaBuildVirtualBlockStatsString(). -Returned string must be later freed using vmaFreeVirtualBlockStatsString(). -The format of this string differs from the one returned by the main Vulkan allocator, but it is similar. - -\section virtual_allocator_additional_considerations Additional considerations - -The "virtual allocator" functionality is implemented on a level of individual memory blocks. -Keeping track of a whole collection of blocks, allocating new ones when out of free space, -deleting empty ones, and deciding which one to try first for a new allocation must be implemented by the user. - -Alternative allocation algorithms are supported, just like in custom pools of the real GPU memory. -See enum #VmaVirtualBlockCreateFlagBits to learn how to specify them (e.g. #VMA_VIRTUAL_BLOCK_CREATE_LINEAR_ALGORITHM_BIT). -You can find their description in chapter \ref custom_memory_pools. -Allocation strategies are also supported. -See enum #VmaVirtualAllocationCreateFlagBits to learn how to specify them (e.g. #VMA_VIRTUAL_ALLOCATION_CREATE_STRATEGY_MIN_TIME_BIT). - -Following features are supported only by the allocator of the real GPU memory and not by virtual allocations: -buffer-image granularity, `VMA_DEBUG_MARGIN`, `VMA_MIN_ALIGNMENT`. - - -\page debugging_memory_usage Debugging incorrect memory usage - -If you suspect a bug with memory usage, like usage of uninitialized memory or -memory being overwritten out of bounds of an allocation, -you can use debug features of this library to verify this. - -\section debugging_memory_usage_initialization Memory initialization - -If you experience a bug with incorrect and nondeterministic data in your program and you suspect uninitialized memory to be used, -you can enable automatic memory initialization to verify this. -To do it, define macro `VMA_DEBUG_INITIALIZE_ALLOCATIONS` to 1. - -\code -#define VMA_DEBUG_INITIALIZE_ALLOCATIONS 1 -#include "vk_mem_alloc.h" -\endcode - -It makes memory of new allocations initialized to bit pattern `0xDCDCDCDC`. -Before an allocation is destroyed, its memory is filled with bit pattern `0xEFEFEFEF`. -Memory is automatically mapped and unmapped if necessary. - -If you find these values while debugging your program, good chances are that you incorrectly -read Vulkan memory that is allocated but not initialized, or already freed, respectively. - -Memory initialization works only with memory types that are `HOST_VISIBLE` and with allocations that can be mapped. -It works also with dedicated allocations. - -\section debugging_memory_usage_margins Margins - -By default, allocations are laid out in memory blocks next to each other if possible -(considering required alignment, `bufferImageGranularity`, and `nonCoherentAtomSize`). - -![Allocations without margin](../gfx/Margins_1.png) - -Define macro `VMA_DEBUG_MARGIN` to some non-zero value (e.g. 16) to enforce specified -number of bytes as a margin after every allocation. - -\code -#define VMA_DEBUG_MARGIN 16 -#include "vk_mem_alloc.h" -\endcode - -![Allocations with margin](../gfx/Margins_2.png) - -If your bug goes away after enabling margins, it means it may be caused by memory -being overwritten outside of allocation boundaries. It is not 100% certain though. -Change in application behavior may also be caused by different order and distribution -of allocations across memory blocks after margins are applied. - -Margins work with all types of memory. - -Margin is applied only to allocations made out of memory blocks and not to dedicated -allocations, which have their own memory block of specific size. -It is thus not applied to allocations made using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT flag -or those automatically decided to put into dedicated allocations, e.g. due to its -large size or recommended by VK_KHR_dedicated_allocation extension. - -Margins appear in [JSON dump](@ref statistics_json_dump) as part of free space. - -Note that enabling margins increases memory usage and fragmentation. - -Margins do not apply to \ref virtual_allocator. - -\section debugging_memory_usage_corruption_detection Corruption detection - -You can additionally define macro `VMA_DEBUG_DETECT_CORRUPTION` to 1 to enable validation -of contents of the margins. - -\code -#define VMA_DEBUG_MARGIN 16 -#define VMA_DEBUG_DETECT_CORRUPTION 1 -#include "vk_mem_alloc.h" -\endcode - -When this feature is enabled, number of bytes specified as `VMA_DEBUG_MARGIN` -(it must be multiply of 4) after every allocation is filled with a magic number. -This idea is also know as "canary". -Memory is automatically mapped and unmapped if necessary. - -This number is validated automatically when the allocation is destroyed. -If it is not equal to the expected value, `VMA_ASSERT()` is executed. -It clearly means that either CPU or GPU overwritten the memory outside of boundaries of the allocation, -which indicates a serious bug. - -You can also explicitly request checking margins of all allocations in all memory blocks -that belong to specified memory types by using function vmaCheckCorruption(), -or in memory blocks that belong to specified custom pool, by using function -vmaCheckPoolCorruption(). - -Margin validation (corruption detection) works only for memory types that are -`HOST_VISIBLE` and `HOST_COHERENT`. - - -\page opengl_interop OpenGL Interop - -VMA provides some features that help with interoperability with OpenGL. - -\section opengl_interop_exporting_memory Exporting memory - -If you want to attach `VkExportMemoryAllocateInfoKHR` structure to `pNext` chain of memory allocations made by the library: - -It is recommended to create \ref custom_memory_pools for such allocations. -Define and fill in your `VkExportMemoryAllocateInfoKHR` structure and attach it to VmaPoolCreateInfo::pMemoryAllocateNext -while creating the custom pool. -Please note that the structure must remain alive and unchanged for the whole lifetime of the #VmaPool, -not only while creating it, as no copy of the structure is made, -but its original pointer is used for each allocation instead. - -If you want to export all memory allocated by the library from certain memory types, -also dedicated allocations or other allocations made from default pools, -an alternative solution is to fill in VmaAllocatorCreateInfo::pTypeExternalMemoryHandleTypes. -It should point to an array with `VkExternalMemoryHandleTypeFlagsKHR` to be automatically passed by the library -through `VkExportMemoryAllocateInfoKHR` on each allocation made from a specific memory type. -Please note that new versions of the library also support dedicated allocations created in custom pools. - -You should not mix these two methods in a way that allows to apply both to the same memory type. -Otherwise, `VkExportMemoryAllocateInfoKHR` structure would be attached twice to the `pNext` chain of `VkMemoryAllocateInfo`. - - -\section opengl_interop_custom_alignment Custom alignment - -Buffers or images exported to a different API like OpenGL may require a different alignment, -higher than the one used by the library automatically, queried from functions like `vkGetBufferMemoryRequirements`. -To impose such alignment: - -It is recommended to create \ref custom_memory_pools for such allocations. -Set VmaPoolCreateInfo::minAllocationAlignment member to the minimum alignment required for each allocation -to be made out of this pool. -The alignment actually used will be the maximum of this member and the alignment returned for the specific buffer or image -from a function like `vkGetBufferMemoryRequirements`, which is called by VMA automatically. - -If you want to create a buffer with a specific minimum alignment out of default pools, -use special function vmaCreateBufferWithAlignment(), which takes additional parameter `minAlignment`. - -Note the problem of alignment affects only resources placed inside bigger `VkDeviceMemory` blocks and not dedicated -allocations, as these, by definition, always have alignment = 0 because the resource is bound to the beginning of its dedicated block. -Contrary to Direct3D 12, Vulkan doesn't have a concept of alignment of the entire memory block passed on its allocation. - - -\page usage_patterns Recommended usage patterns - -Vulkan gives great flexibility in memory allocation. -This chapter shows the most common patterns. - -See also slides from talk: -[Sawicki, Adam. Advanced Graphics Techniques Tutorial: Memory management in Vulkan and DX12. Game Developers Conference, 2018](https://www.gdcvault.com/play/1025458/Advanced-Graphics-Techniques-Tutorial-New) - - -\section usage_patterns_gpu_only GPU-only resource - -When: -Any resources that you frequently write and read on GPU, -e.g. images used as color attachments (aka "render targets"), depth-stencil attachments, -images/buffers used as storage image/buffer (aka "Unordered Access View (UAV)"). - -What to do: -Let the library select the optimal memory type, which will likely have `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT`. - -\code -VkImageCreateInfo imgCreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO }; -imgCreateInfo.imageType = VK_IMAGE_TYPE_2D; -imgCreateInfo.extent.width = 3840; -imgCreateInfo.extent.height = 2160; -imgCreateInfo.extent.depth = 1; -imgCreateInfo.mipLevels = 1; -imgCreateInfo.arrayLayers = 1; -imgCreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM; -imgCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL; -imgCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; -imgCreateInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; -imgCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; - -VmaAllocationCreateInfo allocCreateInfo = {}; -allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; -allocCreateInfo.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT; -allocCreateInfo.priority = 1.0f; - -VkImage img; -VmaAllocation alloc; -vmaCreateImage(allocator, &imgCreateInfo, &allocCreateInfo, &img, &alloc, nullptr); -\endcode - -Also consider: -Consider creating them as dedicated allocations using #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT, -especially if they are large or if you plan to destroy and recreate them with different sizes -e.g. when display resolution changes. -Prefer to create such resources first and all other GPU resources (like textures and vertex buffers) later. -When VK_EXT_memory_priority extension is enabled, it is also worth setting high priority to such allocation -to decrease chances to be evicted to system memory by the operating system. - -\section usage_patterns_staging_copy_upload Staging copy for upload - -When: -A "staging" buffer than you want to map and fill from CPU code, then use as a source of transfer -to some GPU resource. - -What to do: -Use flag #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT. -Let the library select the optimal memory type, which will always have `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT`. - -\code -VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; -bufCreateInfo.size = 65536; -bufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; - -VmaAllocationCreateInfo allocCreateInfo = {}; -allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; -allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | - VMA_ALLOCATION_CREATE_MAPPED_BIT; - -VkBuffer buf; -VmaAllocation alloc; -VmaAllocationInfo allocInfo; -vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo); - -... - -memcpy(allocInfo.pMappedData, myData, myDataSize); -\endcode - -Also consider: -You can map the allocation using vmaMapMemory() or you can create it as persistenly mapped -using #VMA_ALLOCATION_CREATE_MAPPED_BIT, as in the example above. - - -\section usage_patterns_readback Readback - -When: -Buffers for data written by or transferred from the GPU that you want to read back on the CPU, -e.g. results of some computations. - -What to do: -Use flag #VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT. -Let the library select the optimal memory type, which will always have `VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT` -and `VK_MEMORY_PROPERTY_HOST_CACHED_BIT`. - -\code -VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; -bufCreateInfo.size = 65536; -bufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; - -VmaAllocationCreateInfo allocCreateInfo = {}; -allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; -allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | - VMA_ALLOCATION_CREATE_MAPPED_BIT; - -VkBuffer buf; -VmaAllocation alloc; -VmaAllocationInfo allocInfo; -vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo); - -... - -const float* downloadedData = (const float*)allocInfo.pMappedData; -\endcode - - -\section usage_patterns_advanced_data_uploading Advanced data uploading - -For resources that you frequently write on CPU via mapped pointer and -frequently read on GPU e.g. as a uniform buffer (also called "dynamic"), multiple options are possible: - --# Easiest solution is to have one copy of the resource in `HOST_VISIBLE` memory, - even if it means system RAM (not `DEVICE_LOCAL`) on systems with a discrete graphics card, - and make the device reach out to that resource directly. - - Reads performed by the device will then go through PCI Express bus. - The performance of this access may be limited, but it may be fine depending on the size - of this resource (whether it is small enough to quickly end up in GPU cache) and the sparsity - of access. --# On systems with unified memory (e.g. AMD APU or Intel integrated graphics, mobile chips), - a memory type may be available that is both `HOST_VISIBLE` (available for mapping) and `DEVICE_LOCAL` - (fast to access from the GPU). Then, it is likely the best choice for such type of resource. --# Systems with a discrete graphics card and separate video memory may or may not expose - a memory type that is both `HOST_VISIBLE` and `DEVICE_LOCAL`, also known as Base Address Register (BAR). - If they do, it represents a piece of VRAM (or entire VRAM, if ReBAR is enabled in the motherboard BIOS) - that is available to CPU for mapping. - - Writes performed by the host to that memory go through PCI Express bus. - The performance of these writes may be limited, but it may be fine, especially on PCIe 4.0, - as long as rules of using uncached and write-combined memory are followed - only sequential writes and no reads. --# Finally, you may need or prefer to create a separate copy of the resource in `DEVICE_LOCAL` memory, - a separate "staging" copy in `HOST_VISIBLE` memory and perform an explicit transfer command between them. - -Thankfully, VMA offers an aid to create and use such resources in the the way optimal -for the current Vulkan device. To help the library make the best choice, -use flag #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT together with -#VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT. -It will then prefer a memory type that is both `DEVICE_LOCAL` and `HOST_VISIBLE` (integrated memory or BAR), -but if no such memory type is available or allocation from it fails -(PC graphics cards have only 256 MB of BAR by default, unless ReBAR is supported and enabled in BIOS), -it will fall back to `DEVICE_LOCAL` memory for fast GPU access. -It is then up to you to detect that the allocation ended up in a memory type that is not `HOST_VISIBLE`, -so you need to create another "staging" allocation and perform explicit transfers. - -\code -VkBufferCreateInfo bufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; -bufCreateInfo.size = 65536; -bufCreateInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; - -VmaAllocationCreateInfo allocCreateInfo = {}; -allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; -allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | - VMA_ALLOCATION_CREATE_HOST_ACCESS_ALLOW_TRANSFER_INSTEAD_BIT | - VMA_ALLOCATION_CREATE_MAPPED_BIT; - -VkBuffer buf; -VmaAllocation alloc; -VmaAllocationInfo allocInfo; -vmaCreateBuffer(allocator, &bufCreateInfo, &allocCreateInfo, &buf, &alloc, &allocInfo); - -VkMemoryPropertyFlags memPropFlags; -vmaGetAllocationMemoryProperties(allocator, alloc, &memPropFlags); - -if(memPropFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) -{ - // Allocation ended up in a mappable memory and is already mapped - write to it directly. - - // [Executed in runtime]: - memcpy(allocInfo.pMappedData, myData, myDataSize); -} -else -{ - // Allocation ended up in a non-mappable memory - need to transfer. - VkBufferCreateInfo stagingBufCreateInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; - stagingBufCreateInfo.size = 65536; - stagingBufCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; - - VmaAllocationCreateInfo stagingAllocCreateInfo = {}; - stagingAllocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; - stagingAllocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | - VMA_ALLOCATION_CREATE_MAPPED_BIT; - - VkBuffer stagingBuf; - VmaAllocation stagingAlloc; - VmaAllocationInfo stagingAllocInfo; - vmaCreateBuffer(allocator, &stagingBufCreateInfo, &stagingAllocCreateInfo, - &stagingBuf, &stagingAlloc, stagingAllocInfo); - - // [Executed in runtime]: - memcpy(stagingAllocInfo.pMappedData, myData, myDataSize); - //vkCmdPipelineBarrier: VK_ACCESS_HOST_WRITE_BIT --> VK_ACCESS_TRANSFER_READ_BIT - VkBufferCopy bufCopy = { - 0, // srcOffset - 0, // dstOffset, - myDataSize); // size - vkCmdCopyBuffer(cmdBuf, stagingBuf, buf, 1, &bufCopy); -} -\endcode - -\section usage_patterns_other_use_cases Other use cases - -Here are some other, less obvious use cases and their recommended settings: - -- An image that is used only as transfer source and destination, but it should stay on the device, - as it is used to temporarily store a copy of some texture, e.g. from the current to the next frame, - for temporal antialiasing or other temporal effects. - - Use `VkImageCreateInfo::usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT` - - Use VmaAllocationCreateInfo::usage = #VMA_MEMORY_USAGE_AUTO -- An image that is used only as transfer source and destination, but it should be placed - in the system RAM despite it doesn't need to be mapped, because it serves as a "swap" copy to evict - least recently used textures from VRAM. - - Use `VkImageCreateInfo::usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT` - - Use VmaAllocationCreateInfo::usage = #VMA_MEMORY_USAGE_AUTO_PREFER_HOST, - as VMA needs a hint here to differentiate from the previous case. -- A buffer that you want to map and write from the CPU, directly read from the GPU - (e.g. as a uniform or vertex buffer), but you have a clear preference to place it in device or - host memory due to its large size. - - Use `VkBufferCreateInfo::usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT` - - Use VmaAllocationCreateInfo::usage = #VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE or #VMA_MEMORY_USAGE_AUTO_PREFER_HOST - - Use VmaAllocationCreateInfo::flags = #VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT - - -\page configuration Configuration - -Please check "CONFIGURATION SECTION" in the code to find macros that you can define -before each include of this file or change directly in this file to provide -your own implementation of basic facilities like assert, `min()` and `max()` functions, -mutex, atomic etc. -The library uses its own implementation of containers by default, but you can switch to using -STL containers instead. - -For example, define `VMA_ASSERT(expr)` before including the library to provide -custom implementation of the assertion, compatible with your project. -By default it is defined to standard C `assert(expr)` in `_DEBUG` configuration -and empty otherwise. - -\section config_Vulkan_functions Pointers to Vulkan functions - -There are multiple ways to import pointers to Vulkan functions in the library. -In the simplest case you don't need to do anything. -If the compilation or linking of your program or the initialization of the #VmaAllocator -doesn't work for you, you can try to reconfigure it. - -First, the allocator tries to fetch pointers to Vulkan functions linked statically, -like this: - -\code -m_VulkanFunctions.vkAllocateMemory = (PFN_vkAllocateMemory)vkAllocateMemory; -\endcode - -If you want to disable this feature, set configuration macro: `#define VMA_STATIC_VULKAN_FUNCTIONS 0`. - -Second, you can provide the pointers yourself by setting member VmaAllocatorCreateInfo::pVulkanFunctions. -You can fetch them e.g. using functions `vkGetInstanceProcAddr` and `vkGetDeviceProcAddr` or -by using a helper library like [volk](https://github.com/zeux/volk). - -Third, VMA tries to fetch remaining pointers that are still null by calling -`vkGetInstanceProcAddr` and `vkGetDeviceProcAddr` on its own. -You need to only fill in VmaVulkanFunctions::vkGetInstanceProcAddr and VmaVulkanFunctions::vkGetDeviceProcAddr. -Other pointers will be fetched automatically. -If you want to disable this feature, set configuration macro: `#define VMA_DYNAMIC_VULKAN_FUNCTIONS 0`. - -Finally, all the function pointers required by the library (considering selected -Vulkan version and enabled extensions) are checked with `VMA_ASSERT` if they are not null. - - -\section custom_memory_allocator Custom host memory allocator - -If you use custom allocator for CPU memory rather than default operator `new` -and `delete` from C++, you can make this library using your allocator as well -by filling optional member VmaAllocatorCreateInfo::pAllocationCallbacks. These -functions will be passed to Vulkan, as well as used by the library itself to -make any CPU-side allocations. - -\section allocation_callbacks Device memory allocation callbacks - -The library makes calls to `vkAllocateMemory()` and `vkFreeMemory()` internally. -You can setup callbacks to be informed about these calls, e.g. for the purpose -of gathering some statistics. To do it, fill optional member -VmaAllocatorCreateInfo::pDeviceMemoryCallbacks. - -\section heap_memory_limit Device heap memory limit - -When device memory of certain heap runs out of free space, new allocations may -fail (returning error code) or they may succeed, silently pushing some existing_ -memory blocks from GPU VRAM to system RAM (which degrades performance). This -behavior is implementation-dependent - it depends on GPU vendor and graphics -driver. - -On AMD cards it can be controlled while creating Vulkan device object by using -VK_AMD_memory_overallocation_behavior extension, if available. - -Alternatively, if you want to test how your program behaves with limited amount of Vulkan device -memory available without switching your graphics card to one that really has -smaller VRAM, you can use a feature of this library intended for this purpose. -To do it, fill optional member VmaAllocatorCreateInfo::pHeapSizeLimit. - - - -\page vk_khr_dedicated_allocation VK_KHR_dedicated_allocation - -VK_KHR_dedicated_allocation is a Vulkan extension which can be used to improve -performance on some GPUs. It augments Vulkan API with possibility to query -driver whether it prefers particular buffer or image to have its own, dedicated -allocation (separate `VkDeviceMemory` block) for better efficiency - to be able -to do some internal optimizations. The extension is supported by this library. -It will be used automatically when enabled. - -It has been promoted to core Vulkan 1.1, so if you use eligible Vulkan version -and inform VMA about it by setting VmaAllocatorCreateInfo::vulkanApiVersion, -you are all set. - -Otherwise, if you want to use it as an extension: - -1 . When creating Vulkan device, check if following 2 device extensions are -supported (call `vkEnumerateDeviceExtensionProperties()`). -If yes, enable them (fill `VkDeviceCreateInfo::ppEnabledExtensionNames`). - -- VK_KHR_get_memory_requirements2 -- VK_KHR_dedicated_allocation - -If you enabled these extensions: - -2 . Use #VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT flag when creating -your #VmaAllocator to inform the library that you enabled required extensions -and you want the library to use them. - -\code -allocatorInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT; - -vmaCreateAllocator(&allocatorInfo, &allocator); -\endcode - -That is all. The extension will be automatically used whenever you create a -buffer using vmaCreateBuffer() or image using vmaCreateImage(). - -When using the extension together with Vulkan Validation Layer, you will receive -warnings like this: - -_vkBindBufferMemory(): Binding memory to buffer 0x33 but vkGetBufferMemoryRequirements() has not been called on that buffer._ - -It is OK, you should just ignore it. It happens because you use function -`vkGetBufferMemoryRequirements2KHR()` instead of standard -`vkGetBufferMemoryRequirements()`, while the validation layer seems to be -unaware of it. - -To learn more about this extension, see: - -- [VK_KHR_dedicated_allocation in Vulkan specification](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/chap50.html#VK_KHR_dedicated_allocation) -- [VK_KHR_dedicated_allocation unofficial manual](http://asawicki.info/articles/VK_KHR_dedicated_allocation.php5) - - - -\page vk_ext_memory_priority VK_EXT_memory_priority - -VK_EXT_memory_priority is a device extension that allows to pass additional "priority" -value to Vulkan memory allocations that the implementation may use prefer certain -buffers and images that are critical for performance to stay in device-local memory -in cases when the memory is over-subscribed, while some others may be moved to the system memory. - -VMA offers convenient usage of this extension. -If you enable it, you can pass "priority" parameter when creating allocations or custom pools -and the library automatically passes the value to Vulkan using this extension. - -If you want to use this extension in connection with VMA, follow these steps: - -\section vk_ext_memory_priority_initialization Initialization - -1) Call `vkEnumerateDeviceExtensionProperties` for the physical device. -Check if the extension is supported - if returned array of `VkExtensionProperties` contains "VK_EXT_memory_priority". - -2) Call `vkGetPhysicalDeviceFeatures2` for the physical device instead of old `vkGetPhysicalDeviceFeatures`. -Attach additional structure `VkPhysicalDeviceMemoryPriorityFeaturesEXT` to `VkPhysicalDeviceFeatures2::pNext` to be returned. -Check if the device feature is really supported - check if `VkPhysicalDeviceMemoryPriorityFeaturesEXT::memoryPriority` is true. - -3) While creating device with `vkCreateDevice`, enable this extension - add "VK_EXT_memory_priority" -to the list passed as `VkDeviceCreateInfo::ppEnabledExtensionNames`. - -4) While creating the device, also don't set `VkDeviceCreateInfo::pEnabledFeatures`. -Fill in `VkPhysicalDeviceFeatures2` structure instead and pass it as `VkDeviceCreateInfo::pNext`. -Enable this device feature - attach additional structure `VkPhysicalDeviceMemoryPriorityFeaturesEXT` to -`VkPhysicalDeviceFeatures2::pNext` chain and set its member `memoryPriority` to `VK_TRUE`. - -5) While creating #VmaAllocator with vmaCreateAllocator() inform VMA that you -have enabled this extension and feature - add #VMA_ALLOCATOR_CREATE_EXT_MEMORY_PRIORITY_BIT -to VmaAllocatorCreateInfo::flags. - -\section vk_ext_memory_priority_usage Usage - -When using this extension, you should initialize following member: - -- VmaAllocationCreateInfo::priority when creating a dedicated allocation with #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT. -- VmaPoolCreateInfo::priority when creating a custom pool. - -It should be a floating-point value between `0.0f` and `1.0f`, where recommended default is `0.5f`. -Memory allocated with higher value can be treated by the Vulkan implementation as higher priority -and so it can have lower chances of being pushed out to system memory, experiencing degraded performance. - -It might be a good idea to create performance-critical resources like color-attachment or depth-stencil images -as dedicated and set high priority to them. For example: - -\code -VkImageCreateInfo imgCreateInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO }; -imgCreateInfo.imageType = VK_IMAGE_TYPE_2D; -imgCreateInfo.extent.width = 3840; -imgCreateInfo.extent.height = 2160; -imgCreateInfo.extent.depth = 1; -imgCreateInfo.mipLevels = 1; -imgCreateInfo.arrayLayers = 1; -imgCreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM; -imgCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL; -imgCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; -imgCreateInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; -imgCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; - -VmaAllocationCreateInfo allocCreateInfo = {}; -allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO; -allocCreateInfo.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT; -allocCreateInfo.priority = 1.0f; - -VkImage img; -VmaAllocation alloc; -vmaCreateImage(allocator, &imgCreateInfo, &allocCreateInfo, &img, &alloc, nullptr); -\endcode - -`priority` member is ignored in the following situations: - -- Allocations created in custom pools: They inherit the priority, along with all other allocation parameters - from the parametrs passed in #VmaPoolCreateInfo when the pool was created. -- Allocations created in default pools: They inherit the priority from the parameters - VMA used when creating default pools, which means `priority == 0.5f`. - - -\page vk_amd_device_coherent_memory VK_AMD_device_coherent_memory - -VK_AMD_device_coherent_memory is a device extension that enables access to -additional memory types with `VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD` and -`VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD` flag. It is useful mostly for -allocation of buffers intended for writing "breadcrumb markers" in between passes -or draw calls, which in turn are useful for debugging GPU crash/hang/TDR cases. - -When the extension is available but has not been enabled, Vulkan physical device -still exposes those memory types, but their usage is forbidden. VMA automatically -takes care of that - it returns `VK_ERROR_FEATURE_NOT_PRESENT` when an attempt -to allocate memory of such type is made. - -If you want to use this extension in connection with VMA, follow these steps: - -\section vk_amd_device_coherent_memory_initialization Initialization - -1) Call `vkEnumerateDeviceExtensionProperties` for the physical device. -Check if the extension is supported - if returned array of `VkExtensionProperties` contains "VK_AMD_device_coherent_memory". - -2) Call `vkGetPhysicalDeviceFeatures2` for the physical device instead of old `vkGetPhysicalDeviceFeatures`. -Attach additional structure `VkPhysicalDeviceCoherentMemoryFeaturesAMD` to `VkPhysicalDeviceFeatures2::pNext` to be returned. -Check if the device feature is really supported - check if `VkPhysicalDeviceCoherentMemoryFeaturesAMD::deviceCoherentMemory` is true. - -3) While creating device with `vkCreateDevice`, enable this extension - add "VK_AMD_device_coherent_memory" -to the list passed as `VkDeviceCreateInfo::ppEnabledExtensionNames`. - -4) While creating the device, also don't set `VkDeviceCreateInfo::pEnabledFeatures`. -Fill in `VkPhysicalDeviceFeatures2` structure instead and pass it as `VkDeviceCreateInfo::pNext`. -Enable this device feature - attach additional structure `VkPhysicalDeviceCoherentMemoryFeaturesAMD` to -`VkPhysicalDeviceFeatures2::pNext` and set its member `deviceCoherentMemory` to `VK_TRUE`. - -5) While creating #VmaAllocator with vmaCreateAllocator() inform VMA that you -have enabled this extension and feature - add #VMA_ALLOCATOR_CREATE_AMD_DEVICE_COHERENT_MEMORY_BIT -to VmaAllocatorCreateInfo::flags. - -\section vk_amd_device_coherent_memory_usage Usage - -After following steps described above, you can create VMA allocations and custom pools -out of the special `DEVICE_COHERENT` and `DEVICE_UNCACHED` memory types on eligible -devices. There are multiple ways to do it, for example: - -- You can request or prefer to allocate out of such memory types by adding - `VK_MEMORY_PROPERTY_DEVICE_UNCACHED_BIT_AMD` to VmaAllocationCreateInfo::requiredFlags - or VmaAllocationCreateInfo::preferredFlags. Those flags can be freely mixed with - other ways of \ref choosing_memory_type, like setting VmaAllocationCreateInfo::usage. -- If you manually found memory type index to use for this purpose, force allocation - from this specific index by setting VmaAllocationCreateInfo::memoryTypeBits `= 1u << index`. - -\section vk_amd_device_coherent_memory_more_information More information - -To learn more about this extension, see [VK_AMD_device_coherent_memory in Vulkan specification](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VK_AMD_device_coherent_memory.html) - -Example use of this extension can be found in the code of the sample and test suite -accompanying this library. - - -\page enabling_buffer_device_address Enabling buffer device address - -Device extension VK_KHR_buffer_device_address -allow to fetch raw GPU pointer to a buffer and pass it for usage in a shader code. -It has been promoted to core Vulkan 1.2. - -If you want to use this feature in connection with VMA, follow these steps: - -\section enabling_buffer_device_address_initialization Initialization - -1) (For Vulkan version < 1.2) Call `vkEnumerateDeviceExtensionProperties` for the physical device. -Check if the extension is supported - if returned array of `VkExtensionProperties` contains -"VK_KHR_buffer_device_address". - -2) Call `vkGetPhysicalDeviceFeatures2` for the physical device instead of old `vkGetPhysicalDeviceFeatures`. -Attach additional structure `VkPhysicalDeviceBufferDeviceAddressFeatures*` to `VkPhysicalDeviceFeatures2::pNext` to be returned. -Check if the device feature is really supported - check if `VkPhysicalDeviceBufferDeviceAddressFeatures::bufferDeviceAddress` is true. - -3) (For Vulkan version < 1.2) While creating device with `vkCreateDevice`, enable this extension - add -"VK_KHR_buffer_device_address" to the list passed as `VkDeviceCreateInfo::ppEnabledExtensionNames`. - -4) While creating the device, also don't set `VkDeviceCreateInfo::pEnabledFeatures`. -Fill in `VkPhysicalDeviceFeatures2` structure instead and pass it as `VkDeviceCreateInfo::pNext`. -Enable this device feature - attach additional structure `VkPhysicalDeviceBufferDeviceAddressFeatures*` to -`VkPhysicalDeviceFeatures2::pNext` and set its member `bufferDeviceAddress` to `VK_TRUE`. - -5) While creating #VmaAllocator with vmaCreateAllocator() inform VMA that you -have enabled this feature - add #VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT -to VmaAllocatorCreateInfo::flags. - -\section enabling_buffer_device_address_usage Usage - -After following steps described above, you can create buffers with `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT*` using VMA. -The library automatically adds `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT*` to -allocated memory blocks wherever it might be needed. - -Please note that the library supports only `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT*`. -The second part of this functionality related to "capture and replay" is not supported, -as it is intended for usage in debugging tools like RenderDoc, not in everyday Vulkan usage. - -\section enabling_buffer_device_address_more_information More information - -To learn more about this extension, see [VK_KHR_buffer_device_address in Vulkan specification](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/chap46.html#VK_KHR_buffer_device_address) - -Example use of this extension can be found in the code of the sample and test suite -accompanying this library. - -\page general_considerations General considerations - -\section general_considerations_thread_safety Thread safety - -- The library has no global state, so separate #VmaAllocator objects can be used - independently. - There should be no need to create multiple such objects though - one per `VkDevice` is enough. -- By default, all calls to functions that take #VmaAllocator as first parameter - are safe to call from multiple threads simultaneously because they are - synchronized internally when needed. - This includes allocation and deallocation from default memory pool, as well as custom #VmaPool. -- When the allocator is created with #VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT - flag, calls to functions that take such #VmaAllocator object must be - synchronized externally. -- Access to a #VmaAllocation object must be externally synchronized. For example, - you must not call vmaGetAllocationInfo() and vmaMapMemory() from different - threads at the same time if you pass the same #VmaAllocation object to these - functions. -- #VmaVirtualBlock is not safe to be used from multiple threads simultaneously. - -\section general_considerations_versioning_and_compatibility Versioning and compatibility - -The library uses [**Semantic Versioning**](https://semver.org/), -which means version numbers follow convention: Major.Minor.Patch (e.g. 2.3.0), where: - -- Incremented Patch version means a release is backward- and forward-compatible, - introducing only some internal improvements, bug fixes, optimizations etc. - or changes that are out of scope of the official API described in this documentation. -- Incremented Minor version means a release is backward-compatible, - so existing code that uses the library should continue to work, while some new - symbols could have been added: new structures, functions, new values in existing - enums and bit flags, new structure members, but not new function parameters. -- Incrementing Major version means a release could break some backward compatibility. - -All changes between official releases are documented in file "CHANGELOG.md". - -\warning Backward compatibility is considered on the level of C++ source code, not binary linkage. -Adding new members to existing structures is treated as backward compatible if initializing -the new members to binary zero results in the old behavior. -You should always fully initialize all library structures to zeros and not rely on their -exact binary size. - -\section general_considerations_validation_layer_warnings Validation layer warnings - -When using this library, you can meet following types of warnings issued by -Vulkan validation layer. They don't necessarily indicate a bug, so you may need -to just ignore them. - -- *vkBindBufferMemory(): Binding memory to buffer 0xeb8e4 but vkGetBufferMemoryRequirements() has not been called on that buffer.* - - It happens when VK_KHR_dedicated_allocation extension is enabled. - `vkGetBufferMemoryRequirements2KHR` function is used instead, while validation layer seems to be unaware of it. -- *Mapping an image with layout VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL can result in undefined behavior if this memory is used by the device. Only GENERAL or PREINITIALIZED should be used.* - - It happens when you map a buffer or image, because the library maps entire - `VkDeviceMemory` block, where different types of images and buffers may end - up together, especially on GPUs with unified memory like Intel. -- *Non-linear image 0xebc91 is aliased with linear buffer 0xeb8e4 which may indicate a bug.* - - It may happen when you use [defragmentation](@ref defragmentation). - -\section general_considerations_allocation_algorithm Allocation algorithm - -The library uses following algorithm for allocation, in order: - --# Try to find free range of memory in existing blocks. --# If failed, try to create a new block of `VkDeviceMemory`, with preferred block size. --# If failed, try to create such block with size / 2, size / 4, size / 8. --# If failed, try to allocate separate `VkDeviceMemory` for this allocation, - just like when you use #VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT. --# If failed, choose other memory type that meets the requirements specified in - VmaAllocationCreateInfo and go to point 1. --# If failed, return `VK_ERROR_OUT_OF_DEVICE_MEMORY`. - -\section general_considerations_features_not_supported Features not supported - -Features deliberately excluded from the scope of this library: - --# **Data transfer.** Uploading (streaming) and downloading data of buffers and images - between CPU and GPU memory and related synchronization is responsibility of the user. - Defining some "texture" object that would automatically stream its data from a - staging copy in CPU memory to GPU memory would rather be a feature of another, - higher-level library implemented on top of VMA. - VMA doesn't record any commands to a `VkCommandBuffer`. It just allocates memory. --# **Recreation of buffers and images.** Although the library has functions for - buffer and image creation: vmaCreateBuffer(), vmaCreateImage(), you need to - recreate these objects yourself after defragmentation. That is because the big - structures `VkBufferCreateInfo`, `VkImageCreateInfo` are not stored in - #VmaAllocation object. --# **Handling CPU memory allocation failures.** When dynamically creating small C++ - objects in CPU memory (not Vulkan memory), allocation failures are not checked - and handled gracefully, because that would complicate code significantly and - is usually not needed in desktop PC applications anyway. - Success of an allocation is just checked with an assert. --# **Code free of any compiler warnings.** Maintaining the library to compile and - work correctly on so many different platforms is hard enough. Being free of - any warnings, on any version of any compiler, is simply not feasible. - There are many preprocessor macros that make some variables unused, function parameters unreferenced, - or conditional expressions constant in some configurations. - The code of this library should not be bigger or more complicated just to silence these warnings. - It is recommended to disable such warnings instead. --# This is a C++ library with C interface. **Bindings or ports to any other programming languages** are welcome as external projects but - are not going to be included into this repository. -*/ diff --git a/RenderSystems/Vulkan/src/vma.cpp b/RenderSystems/Vulkan/src/vma.cpp deleted file mode 100644 index 0860faed741..00000000000 --- a/RenderSystems/Vulkan/src/vma.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include "OgreVulkanPrerequisites.h" - -#define VMA_IMPLEMENTATION -#define VMA_DYNAMIC_VULKAN_FUNCTIONS 0 - -#ifndef _MSVC_LANG -#define _MSVC_LANG 0 -#endif - -#define VMA_SYSTEM_ALIGNED_MALLOC Ogre::AlignedMemory::allocate -#define VMA_SYSTEM_ALIGNED_FREE Ogre::AlignedMemory::deallocate - -// #define VMA_ASSERT(expr) OgreAssert(expr, "") -#include "vk_mem_alloc.h" \ No newline at end of file diff --git a/RenderSystems/Vulkan/src/volk.c b/RenderSystems/Vulkan/src/volk.c deleted file mode 100644 index eb6684a82de..00000000000 --- a/RenderSystems/Vulkan/src/volk.c +++ /dev/null @@ -1,2278 +0,0 @@ -/* This file is part of volk library; see volk.h for version/license details */ -/* clang-format off */ -#include "volk.h" - -#ifdef _WIN32 - typedef const char* LPCSTR; - typedef struct HINSTANCE__* HINSTANCE; - typedef HINSTANCE HMODULE; - #ifdef _WIN64 - typedef __int64 (__stdcall* FARPROC)(void); - #else - typedef int (__stdcall* FARPROC)(void); - #endif -#else -# include -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef _WIN32 -__declspec(dllimport) HMODULE __stdcall LoadLibraryA(LPCSTR); -__declspec(dllimport) FARPROC __stdcall GetProcAddress(HMODULE, LPCSTR); -#endif - -static VkInstance loadedInstance = VK_NULL_HANDLE; -static VkDevice loadedDevice = VK_NULL_HANDLE; - -static void volkGenLoadLoader(void* context, PFN_vkVoidFunction (*load)(void*, const char*)); -static void volkGenLoadInstance(void* context, PFN_vkVoidFunction (*load)(void*, const char*)); -static void volkGenLoadDevice(void* context, PFN_vkVoidFunction (*load)(void*, const char*)); -static void volkGenLoadDeviceTable(struct VolkDeviceTable* table, void* context, PFN_vkVoidFunction (*load)(void*, const char*)); - -static PFN_vkVoidFunction vkGetInstanceProcAddrStub(void* context, const char* name) -{ - return vkGetInstanceProcAddr((VkInstance)context, name); -} - -static PFN_vkVoidFunction vkGetDeviceProcAddrStub(void* context, const char* name) -{ - return vkGetDeviceProcAddr((VkDevice)context, name); -} - -VkResult volkInitialize(void) -{ -#if defined(_WIN32) - HMODULE module = LoadLibraryA("vulkan-1.dll"); - if (!module) - return VK_ERROR_INITIALIZATION_FAILED; - - // note: function pointer is cast through void function pointer to silence cast-function-type warning on gcc8 - vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)(void(*)(void))GetProcAddress(module, "vkGetInstanceProcAddr"); -#elif defined(__APPLE__) - void* module = dlopen("libvulkan.dylib", RTLD_NOW | RTLD_LOCAL); - if (!module) - module = dlopen("libvulkan.1.dylib", RTLD_NOW | RTLD_LOCAL); - if (!module) - module = dlopen("libMoltenVK.dylib", RTLD_NOW | RTLD_LOCAL); - if (!module) - return VK_ERROR_INITIALIZATION_FAILED; - - vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)dlsym(module, "vkGetInstanceProcAddr"); -#else - void* module = dlopen("libvulkan.so.1", RTLD_NOW | RTLD_LOCAL); - if (!module) - module = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL); - if (!module) - return VK_ERROR_INITIALIZATION_FAILED; - - vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)dlsym(module, "vkGetInstanceProcAddr"); -#endif - - volkGenLoadLoader(NULL, vkGetInstanceProcAddrStub); - - return VK_SUCCESS; -} - -void volkInitializeCustom(PFN_vkGetInstanceProcAddr handler) -{ - vkGetInstanceProcAddr = handler; - - volkGenLoadLoader(NULL, vkGetInstanceProcAddrStub); -} - -uint32_t volkGetInstanceVersion(void) -{ -#if defined(VK_VERSION_1_1) - uint32_t apiVersion = 0; - if (vkEnumerateInstanceVersion && vkEnumerateInstanceVersion(&apiVersion) == VK_SUCCESS) - return apiVersion; -#endif - - if (vkCreateInstance) - return VK_API_VERSION_1_0; - - return 0; -} - -void volkLoadInstance(VkInstance instance) -{ - loadedInstance = instance; - volkGenLoadInstance(instance, vkGetInstanceProcAddrStub); - volkGenLoadDevice(instance, vkGetInstanceProcAddrStub); -} - -void volkLoadInstanceOnly(VkInstance instance) -{ - loadedInstance = instance; - volkGenLoadInstance(instance, vkGetInstanceProcAddrStub); -} - -VkInstance volkGetLoadedInstance() -{ - return loadedInstance; -} - -void volkLoadDevice(VkDevice device) -{ - loadedDevice = device; - volkGenLoadDevice(device, vkGetDeviceProcAddrStub); -} - -VkDevice volkGetLoadedDevice() -{ - return loadedDevice; -} - -void volkLoadDeviceTable(struct VolkDeviceTable* table, VkDevice device) -{ - volkGenLoadDeviceTable(table, device, vkGetDeviceProcAddrStub); -} - -static void volkGenLoadLoader(void* context, PFN_vkVoidFunction (*load)(void*, const char*)) -{ - /* VOLK_GENERATE_LOAD_LOADER */ -#if defined(VK_VERSION_1_0) - vkCreateInstance = (PFN_vkCreateInstance)load(context, "vkCreateInstance"); - vkEnumerateInstanceExtensionProperties = (PFN_vkEnumerateInstanceExtensionProperties)load(context, "vkEnumerateInstanceExtensionProperties"); - vkEnumerateInstanceLayerProperties = (PFN_vkEnumerateInstanceLayerProperties)load(context, "vkEnumerateInstanceLayerProperties"); -#endif /* defined(VK_VERSION_1_0) */ -#if defined(VK_VERSION_1_1) - vkEnumerateInstanceVersion = (PFN_vkEnumerateInstanceVersion)load(context, "vkEnumerateInstanceVersion"); -#endif /* defined(VK_VERSION_1_1) */ - /* VOLK_GENERATE_LOAD_LOADER */ -} - -static void volkGenLoadInstance(void* context, PFN_vkVoidFunction (*load)(void*, const char*)) -{ - /* VOLK_GENERATE_LOAD_INSTANCE */ -#if defined(VK_VERSION_1_0) - vkCreateDevice = (PFN_vkCreateDevice)load(context, "vkCreateDevice"); - vkDestroyInstance = (PFN_vkDestroyInstance)load(context, "vkDestroyInstance"); - vkEnumerateDeviceExtensionProperties = (PFN_vkEnumerateDeviceExtensionProperties)load(context, "vkEnumerateDeviceExtensionProperties"); - vkEnumerateDeviceLayerProperties = (PFN_vkEnumerateDeviceLayerProperties)load(context, "vkEnumerateDeviceLayerProperties"); - vkEnumeratePhysicalDevices = (PFN_vkEnumeratePhysicalDevices)load(context, "vkEnumeratePhysicalDevices"); - vkGetDeviceProcAddr = (PFN_vkGetDeviceProcAddr)load(context, "vkGetDeviceProcAddr"); - vkGetPhysicalDeviceFeatures = (PFN_vkGetPhysicalDeviceFeatures)load(context, "vkGetPhysicalDeviceFeatures"); - vkGetPhysicalDeviceFormatProperties = (PFN_vkGetPhysicalDeviceFormatProperties)load(context, "vkGetPhysicalDeviceFormatProperties"); - vkGetPhysicalDeviceImageFormatProperties = (PFN_vkGetPhysicalDeviceImageFormatProperties)load(context, "vkGetPhysicalDeviceImageFormatProperties"); - vkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties)load(context, "vkGetPhysicalDeviceMemoryProperties"); - vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties)load(context, "vkGetPhysicalDeviceProperties"); - vkGetPhysicalDeviceQueueFamilyProperties = (PFN_vkGetPhysicalDeviceQueueFamilyProperties)load(context, "vkGetPhysicalDeviceQueueFamilyProperties"); - vkGetPhysicalDeviceSparseImageFormatProperties = (PFN_vkGetPhysicalDeviceSparseImageFormatProperties)load(context, "vkGetPhysicalDeviceSparseImageFormatProperties"); -#endif /* defined(VK_VERSION_1_0) */ -#if defined(VK_VERSION_1_1) - vkEnumeratePhysicalDeviceGroups = (PFN_vkEnumeratePhysicalDeviceGroups)load(context, "vkEnumeratePhysicalDeviceGroups"); - vkGetPhysicalDeviceExternalBufferProperties = (PFN_vkGetPhysicalDeviceExternalBufferProperties)load(context, "vkGetPhysicalDeviceExternalBufferProperties"); - vkGetPhysicalDeviceExternalFenceProperties = (PFN_vkGetPhysicalDeviceExternalFenceProperties)load(context, "vkGetPhysicalDeviceExternalFenceProperties"); - vkGetPhysicalDeviceExternalSemaphoreProperties = (PFN_vkGetPhysicalDeviceExternalSemaphoreProperties)load(context, "vkGetPhysicalDeviceExternalSemaphoreProperties"); - vkGetPhysicalDeviceFeatures2 = (PFN_vkGetPhysicalDeviceFeatures2)load(context, "vkGetPhysicalDeviceFeatures2"); - vkGetPhysicalDeviceFormatProperties2 = (PFN_vkGetPhysicalDeviceFormatProperties2)load(context, "vkGetPhysicalDeviceFormatProperties2"); - vkGetPhysicalDeviceImageFormatProperties2 = (PFN_vkGetPhysicalDeviceImageFormatProperties2)load(context, "vkGetPhysicalDeviceImageFormatProperties2"); - vkGetPhysicalDeviceMemoryProperties2 = (PFN_vkGetPhysicalDeviceMemoryProperties2)load(context, "vkGetPhysicalDeviceMemoryProperties2"); - vkGetPhysicalDeviceProperties2 = (PFN_vkGetPhysicalDeviceProperties2)load(context, "vkGetPhysicalDeviceProperties2"); - vkGetPhysicalDeviceQueueFamilyProperties2 = (PFN_vkGetPhysicalDeviceQueueFamilyProperties2)load(context, "vkGetPhysicalDeviceQueueFamilyProperties2"); - vkGetPhysicalDeviceSparseImageFormatProperties2 = (PFN_vkGetPhysicalDeviceSparseImageFormatProperties2)load(context, "vkGetPhysicalDeviceSparseImageFormatProperties2"); -#endif /* defined(VK_VERSION_1_1) */ -#if defined(VK_EXT_acquire_drm_display) - vkAcquireDrmDisplayEXT = (PFN_vkAcquireDrmDisplayEXT)load(context, "vkAcquireDrmDisplayEXT"); - vkGetDrmDisplayEXT = (PFN_vkGetDrmDisplayEXT)load(context, "vkGetDrmDisplayEXT"); -#endif /* defined(VK_EXT_acquire_drm_display) */ -#if defined(VK_EXT_acquire_xlib_display) - vkAcquireXlibDisplayEXT = (PFN_vkAcquireXlibDisplayEXT)load(context, "vkAcquireXlibDisplayEXT"); - vkGetRandROutputDisplayEXT = (PFN_vkGetRandROutputDisplayEXT)load(context, "vkGetRandROutputDisplayEXT"); -#endif /* defined(VK_EXT_acquire_xlib_display) */ -#if defined(VK_EXT_calibrated_timestamps) - vkGetPhysicalDeviceCalibrateableTimeDomainsEXT = (PFN_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT)load(context, "vkGetPhysicalDeviceCalibrateableTimeDomainsEXT"); -#endif /* defined(VK_EXT_calibrated_timestamps) */ -#if defined(VK_EXT_debug_report) - vkCreateDebugReportCallbackEXT = (PFN_vkCreateDebugReportCallbackEXT)load(context, "vkCreateDebugReportCallbackEXT"); - vkDebugReportMessageEXT = (PFN_vkDebugReportMessageEXT)load(context, "vkDebugReportMessageEXT"); - vkDestroyDebugReportCallbackEXT = (PFN_vkDestroyDebugReportCallbackEXT)load(context, "vkDestroyDebugReportCallbackEXT"); -#endif /* defined(VK_EXT_debug_report) */ -#if defined(VK_EXT_debug_utils) - vkCmdBeginDebugUtilsLabelEXT = (PFN_vkCmdBeginDebugUtilsLabelEXT)load(context, "vkCmdBeginDebugUtilsLabelEXT"); - vkCmdEndDebugUtilsLabelEXT = (PFN_vkCmdEndDebugUtilsLabelEXT)load(context, "vkCmdEndDebugUtilsLabelEXT"); - vkCmdInsertDebugUtilsLabelEXT = (PFN_vkCmdInsertDebugUtilsLabelEXT)load(context, "vkCmdInsertDebugUtilsLabelEXT"); - vkCreateDebugUtilsMessengerEXT = (PFN_vkCreateDebugUtilsMessengerEXT)load(context, "vkCreateDebugUtilsMessengerEXT"); - vkDestroyDebugUtilsMessengerEXT = (PFN_vkDestroyDebugUtilsMessengerEXT)load(context, "vkDestroyDebugUtilsMessengerEXT"); - vkQueueBeginDebugUtilsLabelEXT = (PFN_vkQueueBeginDebugUtilsLabelEXT)load(context, "vkQueueBeginDebugUtilsLabelEXT"); - vkQueueEndDebugUtilsLabelEXT = (PFN_vkQueueEndDebugUtilsLabelEXT)load(context, "vkQueueEndDebugUtilsLabelEXT"); - vkQueueInsertDebugUtilsLabelEXT = (PFN_vkQueueInsertDebugUtilsLabelEXT)load(context, "vkQueueInsertDebugUtilsLabelEXT"); - vkSetDebugUtilsObjectNameEXT = (PFN_vkSetDebugUtilsObjectNameEXT)load(context, "vkSetDebugUtilsObjectNameEXT"); - vkSetDebugUtilsObjectTagEXT = (PFN_vkSetDebugUtilsObjectTagEXT)load(context, "vkSetDebugUtilsObjectTagEXT"); - vkSubmitDebugUtilsMessageEXT = (PFN_vkSubmitDebugUtilsMessageEXT)load(context, "vkSubmitDebugUtilsMessageEXT"); -#endif /* defined(VK_EXT_debug_utils) */ -#if defined(VK_EXT_direct_mode_display) - vkReleaseDisplayEXT = (PFN_vkReleaseDisplayEXT)load(context, "vkReleaseDisplayEXT"); -#endif /* defined(VK_EXT_direct_mode_display) */ -#if defined(VK_EXT_directfb_surface) - vkCreateDirectFBSurfaceEXT = (PFN_vkCreateDirectFBSurfaceEXT)load(context, "vkCreateDirectFBSurfaceEXT"); - vkGetPhysicalDeviceDirectFBPresentationSupportEXT = (PFN_vkGetPhysicalDeviceDirectFBPresentationSupportEXT)load(context, "vkGetPhysicalDeviceDirectFBPresentationSupportEXT"); -#endif /* defined(VK_EXT_directfb_surface) */ -#if defined(VK_EXT_display_surface_counter) - vkGetPhysicalDeviceSurfaceCapabilities2EXT = (PFN_vkGetPhysicalDeviceSurfaceCapabilities2EXT)load(context, "vkGetPhysicalDeviceSurfaceCapabilities2EXT"); -#endif /* defined(VK_EXT_display_surface_counter) */ -#if defined(VK_EXT_full_screen_exclusive) - vkGetPhysicalDeviceSurfacePresentModes2EXT = (PFN_vkGetPhysicalDeviceSurfacePresentModes2EXT)load(context, "vkGetPhysicalDeviceSurfacePresentModes2EXT"); -#endif /* defined(VK_EXT_full_screen_exclusive) */ -#if defined(VK_EXT_headless_surface) - vkCreateHeadlessSurfaceEXT = (PFN_vkCreateHeadlessSurfaceEXT)load(context, "vkCreateHeadlessSurfaceEXT"); -#endif /* defined(VK_EXT_headless_surface) */ -#if defined(VK_EXT_metal_surface) - vkCreateMetalSurfaceEXT = (PFN_vkCreateMetalSurfaceEXT)load(context, "vkCreateMetalSurfaceEXT"); -#endif /* defined(VK_EXT_metal_surface) */ -#if defined(VK_EXT_sample_locations) - vkGetPhysicalDeviceMultisamplePropertiesEXT = (PFN_vkGetPhysicalDeviceMultisamplePropertiesEXT)load(context, "vkGetPhysicalDeviceMultisamplePropertiesEXT"); -#endif /* defined(VK_EXT_sample_locations) */ -#if defined(VK_EXT_tooling_info) - vkGetPhysicalDeviceToolPropertiesEXT = (PFN_vkGetPhysicalDeviceToolPropertiesEXT)load(context, "vkGetPhysicalDeviceToolPropertiesEXT"); -#endif /* defined(VK_EXT_tooling_info) */ -#if defined(VK_FUCHSIA_imagepipe_surface) - vkCreateImagePipeSurfaceFUCHSIA = (PFN_vkCreateImagePipeSurfaceFUCHSIA)load(context, "vkCreateImagePipeSurfaceFUCHSIA"); -#endif /* defined(VK_FUCHSIA_imagepipe_surface) */ -#if defined(VK_GGP_stream_descriptor_surface) - vkCreateStreamDescriptorSurfaceGGP = (PFN_vkCreateStreamDescriptorSurfaceGGP)load(context, "vkCreateStreamDescriptorSurfaceGGP"); -#endif /* defined(VK_GGP_stream_descriptor_surface) */ -#if defined(VK_KHR_android_surface) - vkCreateAndroidSurfaceKHR = (PFN_vkCreateAndroidSurfaceKHR)load(context, "vkCreateAndroidSurfaceKHR"); -#endif /* defined(VK_KHR_android_surface) */ -#if defined(VK_KHR_device_group_creation) - vkEnumeratePhysicalDeviceGroupsKHR = (PFN_vkEnumeratePhysicalDeviceGroupsKHR)load(context, "vkEnumeratePhysicalDeviceGroupsKHR"); -#endif /* defined(VK_KHR_device_group_creation) */ -#if defined(VK_KHR_display) - vkCreateDisplayModeKHR = (PFN_vkCreateDisplayModeKHR)load(context, "vkCreateDisplayModeKHR"); - vkCreateDisplayPlaneSurfaceKHR = (PFN_vkCreateDisplayPlaneSurfaceKHR)load(context, "vkCreateDisplayPlaneSurfaceKHR"); - vkGetDisplayModePropertiesKHR = (PFN_vkGetDisplayModePropertiesKHR)load(context, "vkGetDisplayModePropertiesKHR"); - vkGetDisplayPlaneCapabilitiesKHR = (PFN_vkGetDisplayPlaneCapabilitiesKHR)load(context, "vkGetDisplayPlaneCapabilitiesKHR"); - vkGetDisplayPlaneSupportedDisplaysKHR = (PFN_vkGetDisplayPlaneSupportedDisplaysKHR)load(context, "vkGetDisplayPlaneSupportedDisplaysKHR"); - vkGetPhysicalDeviceDisplayPlanePropertiesKHR = (PFN_vkGetPhysicalDeviceDisplayPlanePropertiesKHR)load(context, "vkGetPhysicalDeviceDisplayPlanePropertiesKHR"); - vkGetPhysicalDeviceDisplayPropertiesKHR = (PFN_vkGetPhysicalDeviceDisplayPropertiesKHR)load(context, "vkGetPhysicalDeviceDisplayPropertiesKHR"); -#endif /* defined(VK_KHR_display) */ -#if defined(VK_KHR_external_fence_capabilities) - vkGetPhysicalDeviceExternalFencePropertiesKHR = (PFN_vkGetPhysicalDeviceExternalFencePropertiesKHR)load(context, "vkGetPhysicalDeviceExternalFencePropertiesKHR"); -#endif /* defined(VK_KHR_external_fence_capabilities) */ -#if defined(VK_KHR_external_memory_capabilities) - vkGetPhysicalDeviceExternalBufferPropertiesKHR = (PFN_vkGetPhysicalDeviceExternalBufferPropertiesKHR)load(context, "vkGetPhysicalDeviceExternalBufferPropertiesKHR"); -#endif /* defined(VK_KHR_external_memory_capabilities) */ -#if defined(VK_KHR_external_semaphore_capabilities) - vkGetPhysicalDeviceExternalSemaphorePropertiesKHR = (PFN_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR)load(context, "vkGetPhysicalDeviceExternalSemaphorePropertiesKHR"); -#endif /* defined(VK_KHR_external_semaphore_capabilities) */ -#if defined(VK_KHR_fragment_shading_rate) - vkGetPhysicalDeviceFragmentShadingRatesKHR = (PFN_vkGetPhysicalDeviceFragmentShadingRatesKHR)load(context, "vkGetPhysicalDeviceFragmentShadingRatesKHR"); -#endif /* defined(VK_KHR_fragment_shading_rate) */ -#if defined(VK_KHR_get_display_properties2) - vkGetDisplayModeProperties2KHR = (PFN_vkGetDisplayModeProperties2KHR)load(context, "vkGetDisplayModeProperties2KHR"); - vkGetDisplayPlaneCapabilities2KHR = (PFN_vkGetDisplayPlaneCapabilities2KHR)load(context, "vkGetDisplayPlaneCapabilities2KHR"); - vkGetPhysicalDeviceDisplayPlaneProperties2KHR = (PFN_vkGetPhysicalDeviceDisplayPlaneProperties2KHR)load(context, "vkGetPhysicalDeviceDisplayPlaneProperties2KHR"); - vkGetPhysicalDeviceDisplayProperties2KHR = (PFN_vkGetPhysicalDeviceDisplayProperties2KHR)load(context, "vkGetPhysicalDeviceDisplayProperties2KHR"); -#endif /* defined(VK_KHR_get_display_properties2) */ -#if defined(VK_KHR_get_physical_device_properties2) - vkGetPhysicalDeviceFeatures2KHR = (PFN_vkGetPhysicalDeviceFeatures2KHR)load(context, "vkGetPhysicalDeviceFeatures2KHR"); - vkGetPhysicalDeviceFormatProperties2KHR = (PFN_vkGetPhysicalDeviceFormatProperties2KHR)load(context, "vkGetPhysicalDeviceFormatProperties2KHR"); - vkGetPhysicalDeviceImageFormatProperties2KHR = (PFN_vkGetPhysicalDeviceImageFormatProperties2KHR)load(context, "vkGetPhysicalDeviceImageFormatProperties2KHR"); - vkGetPhysicalDeviceMemoryProperties2KHR = (PFN_vkGetPhysicalDeviceMemoryProperties2KHR)load(context, "vkGetPhysicalDeviceMemoryProperties2KHR"); - vkGetPhysicalDeviceProperties2KHR = (PFN_vkGetPhysicalDeviceProperties2KHR)load(context, "vkGetPhysicalDeviceProperties2KHR"); - vkGetPhysicalDeviceQueueFamilyProperties2KHR = (PFN_vkGetPhysicalDeviceQueueFamilyProperties2KHR)load(context, "vkGetPhysicalDeviceQueueFamilyProperties2KHR"); - vkGetPhysicalDeviceSparseImageFormatProperties2KHR = (PFN_vkGetPhysicalDeviceSparseImageFormatProperties2KHR)load(context, "vkGetPhysicalDeviceSparseImageFormatProperties2KHR"); -#endif /* defined(VK_KHR_get_physical_device_properties2) */ -#if defined(VK_KHR_get_surface_capabilities2) - vkGetPhysicalDeviceSurfaceCapabilities2KHR = (PFN_vkGetPhysicalDeviceSurfaceCapabilities2KHR)load(context, "vkGetPhysicalDeviceSurfaceCapabilities2KHR"); - vkGetPhysicalDeviceSurfaceFormats2KHR = (PFN_vkGetPhysicalDeviceSurfaceFormats2KHR)load(context, "vkGetPhysicalDeviceSurfaceFormats2KHR"); -#endif /* defined(VK_KHR_get_surface_capabilities2) */ -#if defined(VK_KHR_performance_query) - vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR = (PFN_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR)load(context, "vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR"); - vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR = (PFN_vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR)load(context, "vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR"); -#endif /* defined(VK_KHR_performance_query) */ -#if defined(VK_KHR_surface) - vkDestroySurfaceKHR = (PFN_vkDestroySurfaceKHR)load(context, "vkDestroySurfaceKHR"); - vkGetPhysicalDeviceSurfaceCapabilitiesKHR = (PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR)load(context, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR"); - vkGetPhysicalDeviceSurfaceFormatsKHR = (PFN_vkGetPhysicalDeviceSurfaceFormatsKHR)load(context, "vkGetPhysicalDeviceSurfaceFormatsKHR"); - vkGetPhysicalDeviceSurfacePresentModesKHR = (PFN_vkGetPhysicalDeviceSurfacePresentModesKHR)load(context, "vkGetPhysicalDeviceSurfacePresentModesKHR"); - vkGetPhysicalDeviceSurfaceSupportKHR = (PFN_vkGetPhysicalDeviceSurfaceSupportKHR)load(context, "vkGetPhysicalDeviceSurfaceSupportKHR"); -#endif /* defined(VK_KHR_surface) */ -#if defined(VK_KHR_video_queue) - vkGetPhysicalDeviceVideoCapabilitiesKHR = (PFN_vkGetPhysicalDeviceVideoCapabilitiesKHR)load(context, "vkGetPhysicalDeviceVideoCapabilitiesKHR"); - vkGetPhysicalDeviceVideoFormatPropertiesKHR = (PFN_vkGetPhysicalDeviceVideoFormatPropertiesKHR)load(context, "vkGetPhysicalDeviceVideoFormatPropertiesKHR"); -#endif /* defined(VK_KHR_video_queue) */ -#if defined(VK_KHR_wayland_surface) - vkCreateWaylandSurfaceKHR = (PFN_vkCreateWaylandSurfaceKHR)load(context, "vkCreateWaylandSurfaceKHR"); - vkGetPhysicalDeviceWaylandPresentationSupportKHR = (PFN_vkGetPhysicalDeviceWaylandPresentationSupportKHR)load(context, "vkGetPhysicalDeviceWaylandPresentationSupportKHR"); -#endif /* defined(VK_KHR_wayland_surface) */ -#if defined(VK_KHR_win32_surface) - vkCreateWin32SurfaceKHR = (PFN_vkCreateWin32SurfaceKHR)load(context, "vkCreateWin32SurfaceKHR"); - vkGetPhysicalDeviceWin32PresentationSupportKHR = (PFN_vkGetPhysicalDeviceWin32PresentationSupportKHR)load(context, "vkGetPhysicalDeviceWin32PresentationSupportKHR"); -#endif /* defined(VK_KHR_win32_surface) */ -#if defined(VK_KHR_xcb_surface) - vkCreateXcbSurfaceKHR = (PFN_vkCreateXcbSurfaceKHR)load(context, "vkCreateXcbSurfaceKHR"); - vkGetPhysicalDeviceXcbPresentationSupportKHR = (PFN_vkGetPhysicalDeviceXcbPresentationSupportKHR)load(context, "vkGetPhysicalDeviceXcbPresentationSupportKHR"); -#endif /* defined(VK_KHR_xcb_surface) */ -#if defined(VK_KHR_xlib_surface) - vkCreateXlibSurfaceKHR = (PFN_vkCreateXlibSurfaceKHR)load(context, "vkCreateXlibSurfaceKHR"); - vkGetPhysicalDeviceXlibPresentationSupportKHR = (PFN_vkGetPhysicalDeviceXlibPresentationSupportKHR)load(context, "vkGetPhysicalDeviceXlibPresentationSupportKHR"); -#endif /* defined(VK_KHR_xlib_surface) */ -#if defined(VK_MVK_ios_surface) - vkCreateIOSSurfaceMVK = (PFN_vkCreateIOSSurfaceMVK)load(context, "vkCreateIOSSurfaceMVK"); -#endif /* defined(VK_MVK_ios_surface) */ -#if defined(VK_MVK_macos_surface) - vkCreateMacOSSurfaceMVK = (PFN_vkCreateMacOSSurfaceMVK)load(context, "vkCreateMacOSSurfaceMVK"); -#endif /* defined(VK_MVK_macos_surface) */ -#if defined(VK_NN_vi_surface) - vkCreateViSurfaceNN = (PFN_vkCreateViSurfaceNN)load(context, "vkCreateViSurfaceNN"); -#endif /* defined(VK_NN_vi_surface) */ -#if defined(VK_NV_acquire_winrt_display) - vkAcquireWinrtDisplayNV = (PFN_vkAcquireWinrtDisplayNV)load(context, "vkAcquireWinrtDisplayNV"); - vkGetWinrtDisplayNV = (PFN_vkGetWinrtDisplayNV)load(context, "vkGetWinrtDisplayNV"); -#endif /* defined(VK_NV_acquire_winrt_display) */ -#if defined(VK_NV_cooperative_matrix) - vkGetPhysicalDeviceCooperativeMatrixPropertiesNV = (PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesNV)load(context, "vkGetPhysicalDeviceCooperativeMatrixPropertiesNV"); -#endif /* defined(VK_NV_cooperative_matrix) */ -#if defined(VK_NV_coverage_reduction_mode) - vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV = (PFN_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV)load(context, "vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV"); -#endif /* defined(VK_NV_coverage_reduction_mode) */ -#if defined(VK_NV_external_memory_capabilities) - vkGetPhysicalDeviceExternalImageFormatPropertiesNV = (PFN_vkGetPhysicalDeviceExternalImageFormatPropertiesNV)load(context, "vkGetPhysicalDeviceExternalImageFormatPropertiesNV"); -#endif /* defined(VK_NV_external_memory_capabilities) */ -#if defined(VK_QNX_screen_surface) - vkCreateScreenSurfaceQNX = (PFN_vkCreateScreenSurfaceQNX)load(context, "vkCreateScreenSurfaceQNX"); - vkGetPhysicalDeviceScreenPresentationSupportQNX = (PFN_vkGetPhysicalDeviceScreenPresentationSupportQNX)load(context, "vkGetPhysicalDeviceScreenPresentationSupportQNX"); -#endif /* defined(VK_QNX_screen_surface) */ -#if (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) - vkGetPhysicalDevicePresentRectanglesKHR = (PFN_vkGetPhysicalDevicePresentRectanglesKHR)load(context, "vkGetPhysicalDevicePresentRectanglesKHR"); -#endif /* (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) */ - /* VOLK_GENERATE_LOAD_INSTANCE */ -} - -static void volkGenLoadDevice(void* context, PFN_vkVoidFunction (*load)(void*, const char*)) -{ - /* VOLK_GENERATE_LOAD_DEVICE */ -#if defined(VK_VERSION_1_0) - vkAllocateCommandBuffers = (PFN_vkAllocateCommandBuffers)load(context, "vkAllocateCommandBuffers"); - vkAllocateDescriptorSets = (PFN_vkAllocateDescriptorSets)load(context, "vkAllocateDescriptorSets"); - vkAllocateMemory = (PFN_vkAllocateMemory)load(context, "vkAllocateMemory"); - vkBeginCommandBuffer = (PFN_vkBeginCommandBuffer)load(context, "vkBeginCommandBuffer"); - vkBindBufferMemory = (PFN_vkBindBufferMemory)load(context, "vkBindBufferMemory"); - vkBindImageMemory = (PFN_vkBindImageMemory)load(context, "vkBindImageMemory"); - vkCmdBeginQuery = (PFN_vkCmdBeginQuery)load(context, "vkCmdBeginQuery"); - vkCmdBeginRenderPass = (PFN_vkCmdBeginRenderPass)load(context, "vkCmdBeginRenderPass"); - vkCmdBindDescriptorSets = (PFN_vkCmdBindDescriptorSets)load(context, "vkCmdBindDescriptorSets"); - vkCmdBindIndexBuffer = (PFN_vkCmdBindIndexBuffer)load(context, "vkCmdBindIndexBuffer"); - vkCmdBindPipeline = (PFN_vkCmdBindPipeline)load(context, "vkCmdBindPipeline"); - vkCmdBindVertexBuffers = (PFN_vkCmdBindVertexBuffers)load(context, "vkCmdBindVertexBuffers"); - vkCmdBlitImage = (PFN_vkCmdBlitImage)load(context, "vkCmdBlitImage"); - vkCmdClearAttachments = (PFN_vkCmdClearAttachments)load(context, "vkCmdClearAttachments"); - vkCmdClearColorImage = (PFN_vkCmdClearColorImage)load(context, "vkCmdClearColorImage"); - vkCmdClearDepthStencilImage = (PFN_vkCmdClearDepthStencilImage)load(context, "vkCmdClearDepthStencilImage"); - vkCmdCopyBuffer = (PFN_vkCmdCopyBuffer)load(context, "vkCmdCopyBuffer"); - vkCmdCopyBufferToImage = (PFN_vkCmdCopyBufferToImage)load(context, "vkCmdCopyBufferToImage"); - vkCmdCopyImage = (PFN_vkCmdCopyImage)load(context, "vkCmdCopyImage"); - vkCmdCopyImageToBuffer = (PFN_vkCmdCopyImageToBuffer)load(context, "vkCmdCopyImageToBuffer"); - vkCmdCopyQueryPoolResults = (PFN_vkCmdCopyQueryPoolResults)load(context, "vkCmdCopyQueryPoolResults"); - vkCmdDispatch = (PFN_vkCmdDispatch)load(context, "vkCmdDispatch"); - vkCmdDispatchIndirect = (PFN_vkCmdDispatchIndirect)load(context, "vkCmdDispatchIndirect"); - vkCmdDraw = (PFN_vkCmdDraw)load(context, "vkCmdDraw"); - vkCmdDrawIndexed = (PFN_vkCmdDrawIndexed)load(context, "vkCmdDrawIndexed"); - vkCmdDrawIndexedIndirect = (PFN_vkCmdDrawIndexedIndirect)load(context, "vkCmdDrawIndexedIndirect"); - vkCmdDrawIndirect = (PFN_vkCmdDrawIndirect)load(context, "vkCmdDrawIndirect"); - vkCmdEndQuery = (PFN_vkCmdEndQuery)load(context, "vkCmdEndQuery"); - vkCmdEndRenderPass = (PFN_vkCmdEndRenderPass)load(context, "vkCmdEndRenderPass"); - vkCmdExecuteCommands = (PFN_vkCmdExecuteCommands)load(context, "vkCmdExecuteCommands"); - vkCmdFillBuffer = (PFN_vkCmdFillBuffer)load(context, "vkCmdFillBuffer"); - vkCmdNextSubpass = (PFN_vkCmdNextSubpass)load(context, "vkCmdNextSubpass"); - vkCmdPipelineBarrier = (PFN_vkCmdPipelineBarrier)load(context, "vkCmdPipelineBarrier"); - vkCmdPushConstants = (PFN_vkCmdPushConstants)load(context, "vkCmdPushConstants"); - vkCmdResetEvent = (PFN_vkCmdResetEvent)load(context, "vkCmdResetEvent"); - vkCmdResetQueryPool = (PFN_vkCmdResetQueryPool)load(context, "vkCmdResetQueryPool"); - vkCmdResolveImage = (PFN_vkCmdResolveImage)load(context, "vkCmdResolveImage"); - vkCmdSetBlendConstants = (PFN_vkCmdSetBlendConstants)load(context, "vkCmdSetBlendConstants"); - vkCmdSetDepthBias = (PFN_vkCmdSetDepthBias)load(context, "vkCmdSetDepthBias"); - vkCmdSetDepthBounds = (PFN_vkCmdSetDepthBounds)load(context, "vkCmdSetDepthBounds"); - vkCmdSetEvent = (PFN_vkCmdSetEvent)load(context, "vkCmdSetEvent"); - vkCmdSetLineWidth = (PFN_vkCmdSetLineWidth)load(context, "vkCmdSetLineWidth"); - vkCmdSetScissor = (PFN_vkCmdSetScissor)load(context, "vkCmdSetScissor"); - vkCmdSetStencilCompareMask = (PFN_vkCmdSetStencilCompareMask)load(context, "vkCmdSetStencilCompareMask"); - vkCmdSetStencilReference = (PFN_vkCmdSetStencilReference)load(context, "vkCmdSetStencilReference"); - vkCmdSetStencilWriteMask = (PFN_vkCmdSetStencilWriteMask)load(context, "vkCmdSetStencilWriteMask"); - vkCmdSetViewport = (PFN_vkCmdSetViewport)load(context, "vkCmdSetViewport"); - vkCmdUpdateBuffer = (PFN_vkCmdUpdateBuffer)load(context, "vkCmdUpdateBuffer"); - vkCmdWaitEvents = (PFN_vkCmdWaitEvents)load(context, "vkCmdWaitEvents"); - vkCmdWriteTimestamp = (PFN_vkCmdWriteTimestamp)load(context, "vkCmdWriteTimestamp"); - vkCreateBuffer = (PFN_vkCreateBuffer)load(context, "vkCreateBuffer"); - vkCreateBufferView = (PFN_vkCreateBufferView)load(context, "vkCreateBufferView"); - vkCreateCommandPool = (PFN_vkCreateCommandPool)load(context, "vkCreateCommandPool"); - vkCreateComputePipelines = (PFN_vkCreateComputePipelines)load(context, "vkCreateComputePipelines"); - vkCreateDescriptorPool = (PFN_vkCreateDescriptorPool)load(context, "vkCreateDescriptorPool"); - vkCreateDescriptorSetLayout = (PFN_vkCreateDescriptorSetLayout)load(context, "vkCreateDescriptorSetLayout"); - vkCreateEvent = (PFN_vkCreateEvent)load(context, "vkCreateEvent"); - vkCreateFence = (PFN_vkCreateFence)load(context, "vkCreateFence"); - vkCreateFramebuffer = (PFN_vkCreateFramebuffer)load(context, "vkCreateFramebuffer"); - vkCreateGraphicsPipelines = (PFN_vkCreateGraphicsPipelines)load(context, "vkCreateGraphicsPipelines"); - vkCreateImage = (PFN_vkCreateImage)load(context, "vkCreateImage"); - vkCreateImageView = (PFN_vkCreateImageView)load(context, "vkCreateImageView"); - vkCreatePipelineCache = (PFN_vkCreatePipelineCache)load(context, "vkCreatePipelineCache"); - vkCreatePipelineLayout = (PFN_vkCreatePipelineLayout)load(context, "vkCreatePipelineLayout"); - vkCreateQueryPool = (PFN_vkCreateQueryPool)load(context, "vkCreateQueryPool"); - vkCreateRenderPass = (PFN_vkCreateRenderPass)load(context, "vkCreateRenderPass"); - vkCreateSampler = (PFN_vkCreateSampler)load(context, "vkCreateSampler"); - vkCreateSemaphore = (PFN_vkCreateSemaphore)load(context, "vkCreateSemaphore"); - vkCreateShaderModule = (PFN_vkCreateShaderModule)load(context, "vkCreateShaderModule"); - vkDestroyBuffer = (PFN_vkDestroyBuffer)load(context, "vkDestroyBuffer"); - vkDestroyBufferView = (PFN_vkDestroyBufferView)load(context, "vkDestroyBufferView"); - vkDestroyCommandPool = (PFN_vkDestroyCommandPool)load(context, "vkDestroyCommandPool"); - vkDestroyDescriptorPool = (PFN_vkDestroyDescriptorPool)load(context, "vkDestroyDescriptorPool"); - vkDestroyDescriptorSetLayout = (PFN_vkDestroyDescriptorSetLayout)load(context, "vkDestroyDescriptorSetLayout"); - vkDestroyDevice = (PFN_vkDestroyDevice)load(context, "vkDestroyDevice"); - vkDestroyEvent = (PFN_vkDestroyEvent)load(context, "vkDestroyEvent"); - vkDestroyFence = (PFN_vkDestroyFence)load(context, "vkDestroyFence"); - vkDestroyFramebuffer = (PFN_vkDestroyFramebuffer)load(context, "vkDestroyFramebuffer"); - vkDestroyImage = (PFN_vkDestroyImage)load(context, "vkDestroyImage"); - vkDestroyImageView = (PFN_vkDestroyImageView)load(context, "vkDestroyImageView"); - vkDestroyPipeline = (PFN_vkDestroyPipeline)load(context, "vkDestroyPipeline"); - vkDestroyPipelineCache = (PFN_vkDestroyPipelineCache)load(context, "vkDestroyPipelineCache"); - vkDestroyPipelineLayout = (PFN_vkDestroyPipelineLayout)load(context, "vkDestroyPipelineLayout"); - vkDestroyQueryPool = (PFN_vkDestroyQueryPool)load(context, "vkDestroyQueryPool"); - vkDestroyRenderPass = (PFN_vkDestroyRenderPass)load(context, "vkDestroyRenderPass"); - vkDestroySampler = (PFN_vkDestroySampler)load(context, "vkDestroySampler"); - vkDestroySemaphore = (PFN_vkDestroySemaphore)load(context, "vkDestroySemaphore"); - vkDestroyShaderModule = (PFN_vkDestroyShaderModule)load(context, "vkDestroyShaderModule"); - vkDeviceWaitIdle = (PFN_vkDeviceWaitIdle)load(context, "vkDeviceWaitIdle"); - vkEndCommandBuffer = (PFN_vkEndCommandBuffer)load(context, "vkEndCommandBuffer"); - vkFlushMappedMemoryRanges = (PFN_vkFlushMappedMemoryRanges)load(context, "vkFlushMappedMemoryRanges"); - vkFreeCommandBuffers = (PFN_vkFreeCommandBuffers)load(context, "vkFreeCommandBuffers"); - vkFreeDescriptorSets = (PFN_vkFreeDescriptorSets)load(context, "vkFreeDescriptorSets"); - vkFreeMemory = (PFN_vkFreeMemory)load(context, "vkFreeMemory"); - vkGetBufferMemoryRequirements = (PFN_vkGetBufferMemoryRequirements)load(context, "vkGetBufferMemoryRequirements"); - vkGetDeviceMemoryCommitment = (PFN_vkGetDeviceMemoryCommitment)load(context, "vkGetDeviceMemoryCommitment"); - vkGetDeviceQueue = (PFN_vkGetDeviceQueue)load(context, "vkGetDeviceQueue"); - vkGetEventStatus = (PFN_vkGetEventStatus)load(context, "vkGetEventStatus"); - vkGetFenceStatus = (PFN_vkGetFenceStatus)load(context, "vkGetFenceStatus"); - vkGetImageMemoryRequirements = (PFN_vkGetImageMemoryRequirements)load(context, "vkGetImageMemoryRequirements"); - vkGetImageSparseMemoryRequirements = (PFN_vkGetImageSparseMemoryRequirements)load(context, "vkGetImageSparseMemoryRequirements"); - vkGetImageSubresourceLayout = (PFN_vkGetImageSubresourceLayout)load(context, "vkGetImageSubresourceLayout"); - vkGetPipelineCacheData = (PFN_vkGetPipelineCacheData)load(context, "vkGetPipelineCacheData"); - vkGetQueryPoolResults = (PFN_vkGetQueryPoolResults)load(context, "vkGetQueryPoolResults"); - vkGetRenderAreaGranularity = (PFN_vkGetRenderAreaGranularity)load(context, "vkGetRenderAreaGranularity"); - vkInvalidateMappedMemoryRanges = (PFN_vkInvalidateMappedMemoryRanges)load(context, "vkInvalidateMappedMemoryRanges"); - vkMapMemory = (PFN_vkMapMemory)load(context, "vkMapMemory"); - vkMergePipelineCaches = (PFN_vkMergePipelineCaches)load(context, "vkMergePipelineCaches"); - vkQueueBindSparse = (PFN_vkQueueBindSparse)load(context, "vkQueueBindSparse"); - vkQueueSubmit = (PFN_vkQueueSubmit)load(context, "vkQueueSubmit"); - vkQueueWaitIdle = (PFN_vkQueueWaitIdle)load(context, "vkQueueWaitIdle"); - vkResetCommandBuffer = (PFN_vkResetCommandBuffer)load(context, "vkResetCommandBuffer"); - vkResetCommandPool = (PFN_vkResetCommandPool)load(context, "vkResetCommandPool"); - vkResetDescriptorPool = (PFN_vkResetDescriptorPool)load(context, "vkResetDescriptorPool"); - vkResetEvent = (PFN_vkResetEvent)load(context, "vkResetEvent"); - vkResetFences = (PFN_vkResetFences)load(context, "vkResetFences"); - vkSetEvent = (PFN_vkSetEvent)load(context, "vkSetEvent"); - vkUnmapMemory = (PFN_vkUnmapMemory)load(context, "vkUnmapMemory"); - vkUpdateDescriptorSets = (PFN_vkUpdateDescriptorSets)load(context, "vkUpdateDescriptorSets"); - vkWaitForFences = (PFN_vkWaitForFences)load(context, "vkWaitForFences"); -#endif /* defined(VK_VERSION_1_0) */ -#if defined(VK_VERSION_1_1) - vkBindBufferMemory2 = (PFN_vkBindBufferMemory2)load(context, "vkBindBufferMemory2"); - vkBindImageMemory2 = (PFN_vkBindImageMemory2)load(context, "vkBindImageMemory2"); - vkCmdDispatchBase = (PFN_vkCmdDispatchBase)load(context, "vkCmdDispatchBase"); - vkCmdSetDeviceMask = (PFN_vkCmdSetDeviceMask)load(context, "vkCmdSetDeviceMask"); - vkCreateDescriptorUpdateTemplate = (PFN_vkCreateDescriptorUpdateTemplate)load(context, "vkCreateDescriptorUpdateTemplate"); - vkCreateSamplerYcbcrConversion = (PFN_vkCreateSamplerYcbcrConversion)load(context, "vkCreateSamplerYcbcrConversion"); - vkDestroyDescriptorUpdateTemplate = (PFN_vkDestroyDescriptorUpdateTemplate)load(context, "vkDestroyDescriptorUpdateTemplate"); - vkDestroySamplerYcbcrConversion = (PFN_vkDestroySamplerYcbcrConversion)load(context, "vkDestroySamplerYcbcrConversion"); - vkGetBufferMemoryRequirements2 = (PFN_vkGetBufferMemoryRequirements2)load(context, "vkGetBufferMemoryRequirements2"); - vkGetDescriptorSetLayoutSupport = (PFN_vkGetDescriptorSetLayoutSupport)load(context, "vkGetDescriptorSetLayoutSupport"); - vkGetDeviceGroupPeerMemoryFeatures = (PFN_vkGetDeviceGroupPeerMemoryFeatures)load(context, "vkGetDeviceGroupPeerMemoryFeatures"); - vkGetDeviceQueue2 = (PFN_vkGetDeviceQueue2)load(context, "vkGetDeviceQueue2"); - vkGetImageMemoryRequirements2 = (PFN_vkGetImageMemoryRequirements2)load(context, "vkGetImageMemoryRequirements2"); - vkGetImageSparseMemoryRequirements2 = (PFN_vkGetImageSparseMemoryRequirements2)load(context, "vkGetImageSparseMemoryRequirements2"); - vkTrimCommandPool = (PFN_vkTrimCommandPool)load(context, "vkTrimCommandPool"); - vkUpdateDescriptorSetWithTemplate = (PFN_vkUpdateDescriptorSetWithTemplate)load(context, "vkUpdateDescriptorSetWithTemplate"); -#endif /* defined(VK_VERSION_1_1) */ -#if defined(VK_VERSION_1_2) - vkCmdBeginRenderPass2 = (PFN_vkCmdBeginRenderPass2)load(context, "vkCmdBeginRenderPass2"); - vkCmdDrawIndexedIndirectCount = (PFN_vkCmdDrawIndexedIndirectCount)load(context, "vkCmdDrawIndexedIndirectCount"); - vkCmdDrawIndirectCount = (PFN_vkCmdDrawIndirectCount)load(context, "vkCmdDrawIndirectCount"); - vkCmdEndRenderPass2 = (PFN_vkCmdEndRenderPass2)load(context, "vkCmdEndRenderPass2"); - vkCmdNextSubpass2 = (PFN_vkCmdNextSubpass2)load(context, "vkCmdNextSubpass2"); - vkCreateRenderPass2 = (PFN_vkCreateRenderPass2)load(context, "vkCreateRenderPass2"); - vkGetBufferDeviceAddress = (PFN_vkGetBufferDeviceAddress)load(context, "vkGetBufferDeviceAddress"); - vkGetBufferOpaqueCaptureAddress = (PFN_vkGetBufferOpaqueCaptureAddress)load(context, "vkGetBufferOpaqueCaptureAddress"); - vkGetDeviceMemoryOpaqueCaptureAddress = (PFN_vkGetDeviceMemoryOpaqueCaptureAddress)load(context, "vkGetDeviceMemoryOpaqueCaptureAddress"); - vkGetSemaphoreCounterValue = (PFN_vkGetSemaphoreCounterValue)load(context, "vkGetSemaphoreCounterValue"); - vkResetQueryPool = (PFN_vkResetQueryPool)load(context, "vkResetQueryPool"); - vkSignalSemaphore = (PFN_vkSignalSemaphore)load(context, "vkSignalSemaphore"); - vkWaitSemaphores = (PFN_vkWaitSemaphores)load(context, "vkWaitSemaphores"); -#endif /* defined(VK_VERSION_1_2) */ -#if defined(VK_AMD_buffer_marker) - vkCmdWriteBufferMarkerAMD = (PFN_vkCmdWriteBufferMarkerAMD)load(context, "vkCmdWriteBufferMarkerAMD"); -#endif /* defined(VK_AMD_buffer_marker) */ -#if defined(VK_AMD_display_native_hdr) - vkSetLocalDimmingAMD = (PFN_vkSetLocalDimmingAMD)load(context, "vkSetLocalDimmingAMD"); -#endif /* defined(VK_AMD_display_native_hdr) */ -#if defined(VK_AMD_draw_indirect_count) - vkCmdDrawIndexedIndirectCountAMD = (PFN_vkCmdDrawIndexedIndirectCountAMD)load(context, "vkCmdDrawIndexedIndirectCountAMD"); - vkCmdDrawIndirectCountAMD = (PFN_vkCmdDrawIndirectCountAMD)load(context, "vkCmdDrawIndirectCountAMD"); -#endif /* defined(VK_AMD_draw_indirect_count) */ -#if defined(VK_AMD_shader_info) - vkGetShaderInfoAMD = (PFN_vkGetShaderInfoAMD)load(context, "vkGetShaderInfoAMD"); -#endif /* defined(VK_AMD_shader_info) */ -#if defined(VK_ANDROID_external_memory_android_hardware_buffer) - vkGetAndroidHardwareBufferPropertiesANDROID = (PFN_vkGetAndroidHardwareBufferPropertiesANDROID)load(context, "vkGetAndroidHardwareBufferPropertiesANDROID"); - vkGetMemoryAndroidHardwareBufferANDROID = (PFN_vkGetMemoryAndroidHardwareBufferANDROID)load(context, "vkGetMemoryAndroidHardwareBufferANDROID"); -#endif /* defined(VK_ANDROID_external_memory_android_hardware_buffer) */ -#if defined(VK_EXT_buffer_device_address) - vkGetBufferDeviceAddressEXT = (PFN_vkGetBufferDeviceAddressEXT)load(context, "vkGetBufferDeviceAddressEXT"); -#endif /* defined(VK_EXT_buffer_device_address) */ -#if defined(VK_EXT_calibrated_timestamps) - vkGetCalibratedTimestampsEXT = (PFN_vkGetCalibratedTimestampsEXT)load(context, "vkGetCalibratedTimestampsEXT"); -#endif /* defined(VK_EXT_calibrated_timestamps) */ -#if defined(VK_EXT_color_write_enable) - vkCmdSetColorWriteEnableEXT = (PFN_vkCmdSetColorWriteEnableEXT)load(context, "vkCmdSetColorWriteEnableEXT"); -#endif /* defined(VK_EXT_color_write_enable) */ -#if defined(VK_EXT_conditional_rendering) - vkCmdBeginConditionalRenderingEXT = (PFN_vkCmdBeginConditionalRenderingEXT)load(context, "vkCmdBeginConditionalRenderingEXT"); - vkCmdEndConditionalRenderingEXT = (PFN_vkCmdEndConditionalRenderingEXT)load(context, "vkCmdEndConditionalRenderingEXT"); -#endif /* defined(VK_EXT_conditional_rendering) */ -#if defined(VK_EXT_debug_marker) - vkCmdDebugMarkerBeginEXT = (PFN_vkCmdDebugMarkerBeginEXT)load(context, "vkCmdDebugMarkerBeginEXT"); - vkCmdDebugMarkerEndEXT = (PFN_vkCmdDebugMarkerEndEXT)load(context, "vkCmdDebugMarkerEndEXT"); - vkCmdDebugMarkerInsertEXT = (PFN_vkCmdDebugMarkerInsertEXT)load(context, "vkCmdDebugMarkerInsertEXT"); - vkDebugMarkerSetObjectNameEXT = (PFN_vkDebugMarkerSetObjectNameEXT)load(context, "vkDebugMarkerSetObjectNameEXT"); - vkDebugMarkerSetObjectTagEXT = (PFN_vkDebugMarkerSetObjectTagEXT)load(context, "vkDebugMarkerSetObjectTagEXT"); -#endif /* defined(VK_EXT_debug_marker) */ -#if defined(VK_EXT_discard_rectangles) - vkCmdSetDiscardRectangleEXT = (PFN_vkCmdSetDiscardRectangleEXT)load(context, "vkCmdSetDiscardRectangleEXT"); -#endif /* defined(VK_EXT_discard_rectangles) */ -#if defined(VK_EXT_display_control) - vkDisplayPowerControlEXT = (PFN_vkDisplayPowerControlEXT)load(context, "vkDisplayPowerControlEXT"); - vkGetSwapchainCounterEXT = (PFN_vkGetSwapchainCounterEXT)load(context, "vkGetSwapchainCounterEXT"); - vkRegisterDeviceEventEXT = (PFN_vkRegisterDeviceEventEXT)load(context, "vkRegisterDeviceEventEXT"); - vkRegisterDisplayEventEXT = (PFN_vkRegisterDisplayEventEXT)load(context, "vkRegisterDisplayEventEXT"); -#endif /* defined(VK_EXT_display_control) */ -#if defined(VK_EXT_extended_dynamic_state) - vkCmdBindVertexBuffers2EXT = (PFN_vkCmdBindVertexBuffers2EXT)load(context, "vkCmdBindVertexBuffers2EXT"); - vkCmdSetCullModeEXT = (PFN_vkCmdSetCullModeEXT)load(context, "vkCmdSetCullModeEXT"); - vkCmdSetDepthBoundsTestEnableEXT = (PFN_vkCmdSetDepthBoundsTestEnableEXT)load(context, "vkCmdSetDepthBoundsTestEnableEXT"); - vkCmdSetDepthCompareOpEXT = (PFN_vkCmdSetDepthCompareOpEXT)load(context, "vkCmdSetDepthCompareOpEXT"); - vkCmdSetDepthTestEnableEXT = (PFN_vkCmdSetDepthTestEnableEXT)load(context, "vkCmdSetDepthTestEnableEXT"); - vkCmdSetDepthWriteEnableEXT = (PFN_vkCmdSetDepthWriteEnableEXT)load(context, "vkCmdSetDepthWriteEnableEXT"); - vkCmdSetFrontFaceEXT = (PFN_vkCmdSetFrontFaceEXT)load(context, "vkCmdSetFrontFaceEXT"); - vkCmdSetPrimitiveTopologyEXT = (PFN_vkCmdSetPrimitiveTopologyEXT)load(context, "vkCmdSetPrimitiveTopologyEXT"); - vkCmdSetScissorWithCountEXT = (PFN_vkCmdSetScissorWithCountEXT)load(context, "vkCmdSetScissorWithCountEXT"); - vkCmdSetStencilOpEXT = (PFN_vkCmdSetStencilOpEXT)load(context, "vkCmdSetStencilOpEXT"); - vkCmdSetStencilTestEnableEXT = (PFN_vkCmdSetStencilTestEnableEXT)load(context, "vkCmdSetStencilTestEnableEXT"); - vkCmdSetViewportWithCountEXT = (PFN_vkCmdSetViewportWithCountEXT)load(context, "vkCmdSetViewportWithCountEXT"); -#endif /* defined(VK_EXT_extended_dynamic_state) */ -#if defined(VK_EXT_extended_dynamic_state2) - vkCmdSetDepthBiasEnableEXT = (PFN_vkCmdSetDepthBiasEnableEXT)load(context, "vkCmdSetDepthBiasEnableEXT"); - vkCmdSetLogicOpEXT = (PFN_vkCmdSetLogicOpEXT)load(context, "vkCmdSetLogicOpEXT"); - vkCmdSetPatchControlPointsEXT = (PFN_vkCmdSetPatchControlPointsEXT)load(context, "vkCmdSetPatchControlPointsEXT"); - vkCmdSetPrimitiveRestartEnableEXT = (PFN_vkCmdSetPrimitiveRestartEnableEXT)load(context, "vkCmdSetPrimitiveRestartEnableEXT"); - vkCmdSetRasterizerDiscardEnableEXT = (PFN_vkCmdSetRasterizerDiscardEnableEXT)load(context, "vkCmdSetRasterizerDiscardEnableEXT"); -#endif /* defined(VK_EXT_extended_dynamic_state2) */ -#if defined(VK_EXT_external_memory_host) - vkGetMemoryHostPointerPropertiesEXT = (PFN_vkGetMemoryHostPointerPropertiesEXT)load(context, "vkGetMemoryHostPointerPropertiesEXT"); -#endif /* defined(VK_EXT_external_memory_host) */ -#if defined(VK_EXT_full_screen_exclusive) - vkAcquireFullScreenExclusiveModeEXT = (PFN_vkAcquireFullScreenExclusiveModeEXT)load(context, "vkAcquireFullScreenExclusiveModeEXT"); - vkReleaseFullScreenExclusiveModeEXT = (PFN_vkReleaseFullScreenExclusiveModeEXT)load(context, "vkReleaseFullScreenExclusiveModeEXT"); -#endif /* defined(VK_EXT_full_screen_exclusive) */ -#if defined(VK_EXT_hdr_metadata) - vkSetHdrMetadataEXT = (PFN_vkSetHdrMetadataEXT)load(context, "vkSetHdrMetadataEXT"); -#endif /* defined(VK_EXT_hdr_metadata) */ -#if defined(VK_EXT_host_query_reset) - vkResetQueryPoolEXT = (PFN_vkResetQueryPoolEXT)load(context, "vkResetQueryPoolEXT"); -#endif /* defined(VK_EXT_host_query_reset) */ -#if defined(VK_EXT_image_drm_format_modifier) - vkGetImageDrmFormatModifierPropertiesEXT = (PFN_vkGetImageDrmFormatModifierPropertiesEXT)load(context, "vkGetImageDrmFormatModifierPropertiesEXT"); -#endif /* defined(VK_EXT_image_drm_format_modifier) */ -#if defined(VK_EXT_line_rasterization) - vkCmdSetLineStippleEXT = (PFN_vkCmdSetLineStippleEXT)load(context, "vkCmdSetLineStippleEXT"); -#endif /* defined(VK_EXT_line_rasterization) */ -#if defined(VK_EXT_multi_draw) - vkCmdDrawMultiEXT = (PFN_vkCmdDrawMultiEXT)load(context, "vkCmdDrawMultiEXT"); - vkCmdDrawMultiIndexedEXT = (PFN_vkCmdDrawMultiIndexedEXT)load(context, "vkCmdDrawMultiIndexedEXT"); -#endif /* defined(VK_EXT_multi_draw) */ -#if defined(VK_EXT_pageable_device_local_memory) - vkSetDeviceMemoryPriorityEXT = (PFN_vkSetDeviceMemoryPriorityEXT)load(context, "vkSetDeviceMemoryPriorityEXT"); -#endif /* defined(VK_EXT_pageable_device_local_memory) */ -#if defined(VK_EXT_private_data) - vkCreatePrivateDataSlotEXT = (PFN_vkCreatePrivateDataSlotEXT)load(context, "vkCreatePrivateDataSlotEXT"); - vkDestroyPrivateDataSlotEXT = (PFN_vkDestroyPrivateDataSlotEXT)load(context, "vkDestroyPrivateDataSlotEXT"); - vkGetPrivateDataEXT = (PFN_vkGetPrivateDataEXT)load(context, "vkGetPrivateDataEXT"); - vkSetPrivateDataEXT = (PFN_vkSetPrivateDataEXT)load(context, "vkSetPrivateDataEXT"); -#endif /* defined(VK_EXT_private_data) */ -#if defined(VK_EXT_sample_locations) - vkCmdSetSampleLocationsEXT = (PFN_vkCmdSetSampleLocationsEXT)load(context, "vkCmdSetSampleLocationsEXT"); -#endif /* defined(VK_EXT_sample_locations) */ -#if defined(VK_EXT_transform_feedback) - vkCmdBeginQueryIndexedEXT = (PFN_vkCmdBeginQueryIndexedEXT)load(context, "vkCmdBeginQueryIndexedEXT"); - vkCmdBeginTransformFeedbackEXT = (PFN_vkCmdBeginTransformFeedbackEXT)load(context, "vkCmdBeginTransformFeedbackEXT"); - vkCmdBindTransformFeedbackBuffersEXT = (PFN_vkCmdBindTransformFeedbackBuffersEXT)load(context, "vkCmdBindTransformFeedbackBuffersEXT"); - vkCmdDrawIndirectByteCountEXT = (PFN_vkCmdDrawIndirectByteCountEXT)load(context, "vkCmdDrawIndirectByteCountEXT"); - vkCmdEndQueryIndexedEXT = (PFN_vkCmdEndQueryIndexedEXT)load(context, "vkCmdEndQueryIndexedEXT"); - vkCmdEndTransformFeedbackEXT = (PFN_vkCmdEndTransformFeedbackEXT)load(context, "vkCmdEndTransformFeedbackEXT"); -#endif /* defined(VK_EXT_transform_feedback) */ -#if defined(VK_EXT_validation_cache) - vkCreateValidationCacheEXT = (PFN_vkCreateValidationCacheEXT)load(context, "vkCreateValidationCacheEXT"); - vkDestroyValidationCacheEXT = (PFN_vkDestroyValidationCacheEXT)load(context, "vkDestroyValidationCacheEXT"); - vkGetValidationCacheDataEXT = (PFN_vkGetValidationCacheDataEXT)load(context, "vkGetValidationCacheDataEXT"); - vkMergeValidationCachesEXT = (PFN_vkMergeValidationCachesEXT)load(context, "vkMergeValidationCachesEXT"); -#endif /* defined(VK_EXT_validation_cache) */ -#if defined(VK_EXT_vertex_input_dynamic_state) - vkCmdSetVertexInputEXT = (PFN_vkCmdSetVertexInputEXT)load(context, "vkCmdSetVertexInputEXT"); -#endif /* defined(VK_EXT_vertex_input_dynamic_state) */ -#if defined(VK_FUCHSIA_buffer_collection) - vkCreateBufferCollectionFUCHSIA = (PFN_vkCreateBufferCollectionFUCHSIA)load(context, "vkCreateBufferCollectionFUCHSIA"); - vkDestroyBufferCollectionFUCHSIA = (PFN_vkDestroyBufferCollectionFUCHSIA)load(context, "vkDestroyBufferCollectionFUCHSIA"); - vkGetBufferCollectionPropertiesFUCHSIA = (PFN_vkGetBufferCollectionPropertiesFUCHSIA)load(context, "vkGetBufferCollectionPropertiesFUCHSIA"); - vkSetBufferCollectionBufferConstraintsFUCHSIA = (PFN_vkSetBufferCollectionBufferConstraintsFUCHSIA)load(context, "vkSetBufferCollectionBufferConstraintsFUCHSIA"); - vkSetBufferCollectionImageConstraintsFUCHSIA = (PFN_vkSetBufferCollectionImageConstraintsFUCHSIA)load(context, "vkSetBufferCollectionImageConstraintsFUCHSIA"); -#endif /* defined(VK_FUCHSIA_buffer_collection) */ -#if defined(VK_FUCHSIA_external_memory) - vkGetMemoryZirconHandleFUCHSIA = (PFN_vkGetMemoryZirconHandleFUCHSIA)load(context, "vkGetMemoryZirconHandleFUCHSIA"); - vkGetMemoryZirconHandlePropertiesFUCHSIA = (PFN_vkGetMemoryZirconHandlePropertiesFUCHSIA)load(context, "vkGetMemoryZirconHandlePropertiesFUCHSIA"); -#endif /* defined(VK_FUCHSIA_external_memory) */ -#if defined(VK_FUCHSIA_external_semaphore) - vkGetSemaphoreZirconHandleFUCHSIA = (PFN_vkGetSemaphoreZirconHandleFUCHSIA)load(context, "vkGetSemaphoreZirconHandleFUCHSIA"); - vkImportSemaphoreZirconHandleFUCHSIA = (PFN_vkImportSemaphoreZirconHandleFUCHSIA)load(context, "vkImportSemaphoreZirconHandleFUCHSIA"); -#endif /* defined(VK_FUCHSIA_external_semaphore) */ -#if defined(VK_GOOGLE_display_timing) - vkGetPastPresentationTimingGOOGLE = (PFN_vkGetPastPresentationTimingGOOGLE)load(context, "vkGetPastPresentationTimingGOOGLE"); - vkGetRefreshCycleDurationGOOGLE = (PFN_vkGetRefreshCycleDurationGOOGLE)load(context, "vkGetRefreshCycleDurationGOOGLE"); -#endif /* defined(VK_GOOGLE_display_timing) */ -#if defined(VK_HUAWEI_invocation_mask) - vkCmdBindInvocationMaskHUAWEI = (PFN_vkCmdBindInvocationMaskHUAWEI)load(context, "vkCmdBindInvocationMaskHUAWEI"); -#endif /* defined(VK_HUAWEI_invocation_mask) */ -#if defined(VK_HUAWEI_subpass_shading) - vkCmdSubpassShadingHUAWEI = (PFN_vkCmdSubpassShadingHUAWEI)load(context, "vkCmdSubpassShadingHUAWEI"); - vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI = (PFN_vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI)load(context, "vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI"); -#endif /* defined(VK_HUAWEI_subpass_shading) */ -#if defined(VK_INTEL_performance_query) - vkAcquirePerformanceConfigurationINTEL = (PFN_vkAcquirePerformanceConfigurationINTEL)load(context, "vkAcquirePerformanceConfigurationINTEL"); - vkCmdSetPerformanceMarkerINTEL = (PFN_vkCmdSetPerformanceMarkerINTEL)load(context, "vkCmdSetPerformanceMarkerINTEL"); - vkCmdSetPerformanceOverrideINTEL = (PFN_vkCmdSetPerformanceOverrideINTEL)load(context, "vkCmdSetPerformanceOverrideINTEL"); - vkCmdSetPerformanceStreamMarkerINTEL = (PFN_vkCmdSetPerformanceStreamMarkerINTEL)load(context, "vkCmdSetPerformanceStreamMarkerINTEL"); - vkGetPerformanceParameterINTEL = (PFN_vkGetPerformanceParameterINTEL)load(context, "vkGetPerformanceParameterINTEL"); - vkInitializePerformanceApiINTEL = (PFN_vkInitializePerformanceApiINTEL)load(context, "vkInitializePerformanceApiINTEL"); - vkQueueSetPerformanceConfigurationINTEL = (PFN_vkQueueSetPerformanceConfigurationINTEL)load(context, "vkQueueSetPerformanceConfigurationINTEL"); - vkReleasePerformanceConfigurationINTEL = (PFN_vkReleasePerformanceConfigurationINTEL)load(context, "vkReleasePerformanceConfigurationINTEL"); - vkUninitializePerformanceApiINTEL = (PFN_vkUninitializePerformanceApiINTEL)load(context, "vkUninitializePerformanceApiINTEL"); -#endif /* defined(VK_INTEL_performance_query) */ -#if defined(VK_KHR_acceleration_structure) - vkBuildAccelerationStructuresKHR = (PFN_vkBuildAccelerationStructuresKHR)load(context, "vkBuildAccelerationStructuresKHR"); - vkCmdBuildAccelerationStructuresIndirectKHR = (PFN_vkCmdBuildAccelerationStructuresIndirectKHR)load(context, "vkCmdBuildAccelerationStructuresIndirectKHR"); - vkCmdBuildAccelerationStructuresKHR = (PFN_vkCmdBuildAccelerationStructuresKHR)load(context, "vkCmdBuildAccelerationStructuresKHR"); - vkCmdCopyAccelerationStructureKHR = (PFN_vkCmdCopyAccelerationStructureKHR)load(context, "vkCmdCopyAccelerationStructureKHR"); - vkCmdCopyAccelerationStructureToMemoryKHR = (PFN_vkCmdCopyAccelerationStructureToMemoryKHR)load(context, "vkCmdCopyAccelerationStructureToMemoryKHR"); - vkCmdCopyMemoryToAccelerationStructureKHR = (PFN_vkCmdCopyMemoryToAccelerationStructureKHR)load(context, "vkCmdCopyMemoryToAccelerationStructureKHR"); - vkCmdWriteAccelerationStructuresPropertiesKHR = (PFN_vkCmdWriteAccelerationStructuresPropertiesKHR)load(context, "vkCmdWriteAccelerationStructuresPropertiesKHR"); - vkCopyAccelerationStructureKHR = (PFN_vkCopyAccelerationStructureKHR)load(context, "vkCopyAccelerationStructureKHR"); - vkCopyAccelerationStructureToMemoryKHR = (PFN_vkCopyAccelerationStructureToMemoryKHR)load(context, "vkCopyAccelerationStructureToMemoryKHR"); - vkCopyMemoryToAccelerationStructureKHR = (PFN_vkCopyMemoryToAccelerationStructureKHR)load(context, "vkCopyMemoryToAccelerationStructureKHR"); - vkCreateAccelerationStructureKHR = (PFN_vkCreateAccelerationStructureKHR)load(context, "vkCreateAccelerationStructureKHR"); - vkDestroyAccelerationStructureKHR = (PFN_vkDestroyAccelerationStructureKHR)load(context, "vkDestroyAccelerationStructureKHR"); - vkGetAccelerationStructureBuildSizesKHR = (PFN_vkGetAccelerationStructureBuildSizesKHR)load(context, "vkGetAccelerationStructureBuildSizesKHR"); - vkGetAccelerationStructureDeviceAddressKHR = (PFN_vkGetAccelerationStructureDeviceAddressKHR)load(context, "vkGetAccelerationStructureDeviceAddressKHR"); - vkGetDeviceAccelerationStructureCompatibilityKHR = (PFN_vkGetDeviceAccelerationStructureCompatibilityKHR)load(context, "vkGetDeviceAccelerationStructureCompatibilityKHR"); - vkWriteAccelerationStructuresPropertiesKHR = (PFN_vkWriteAccelerationStructuresPropertiesKHR)load(context, "vkWriteAccelerationStructuresPropertiesKHR"); -#endif /* defined(VK_KHR_acceleration_structure) */ -#if defined(VK_KHR_bind_memory2) - vkBindBufferMemory2KHR = (PFN_vkBindBufferMemory2KHR)load(context, "vkBindBufferMemory2KHR"); - vkBindImageMemory2KHR = (PFN_vkBindImageMemory2KHR)load(context, "vkBindImageMemory2KHR"); -#endif /* defined(VK_KHR_bind_memory2) */ -#if defined(VK_KHR_buffer_device_address) - vkGetBufferDeviceAddressKHR = (PFN_vkGetBufferDeviceAddressKHR)load(context, "vkGetBufferDeviceAddressKHR"); - vkGetBufferOpaqueCaptureAddressKHR = (PFN_vkGetBufferOpaqueCaptureAddressKHR)load(context, "vkGetBufferOpaqueCaptureAddressKHR"); - vkGetDeviceMemoryOpaqueCaptureAddressKHR = (PFN_vkGetDeviceMemoryOpaqueCaptureAddressKHR)load(context, "vkGetDeviceMemoryOpaqueCaptureAddressKHR"); -#endif /* defined(VK_KHR_buffer_device_address) */ -#if defined(VK_KHR_copy_commands2) - vkCmdBlitImage2KHR = (PFN_vkCmdBlitImage2KHR)load(context, "vkCmdBlitImage2KHR"); - vkCmdCopyBuffer2KHR = (PFN_vkCmdCopyBuffer2KHR)load(context, "vkCmdCopyBuffer2KHR"); - vkCmdCopyBufferToImage2KHR = (PFN_vkCmdCopyBufferToImage2KHR)load(context, "vkCmdCopyBufferToImage2KHR"); - vkCmdCopyImage2KHR = (PFN_vkCmdCopyImage2KHR)load(context, "vkCmdCopyImage2KHR"); - vkCmdCopyImageToBuffer2KHR = (PFN_vkCmdCopyImageToBuffer2KHR)load(context, "vkCmdCopyImageToBuffer2KHR"); - vkCmdResolveImage2KHR = (PFN_vkCmdResolveImage2KHR)load(context, "vkCmdResolveImage2KHR"); -#endif /* defined(VK_KHR_copy_commands2) */ -#if defined(VK_KHR_create_renderpass2) - vkCmdBeginRenderPass2KHR = (PFN_vkCmdBeginRenderPass2KHR)load(context, "vkCmdBeginRenderPass2KHR"); - vkCmdEndRenderPass2KHR = (PFN_vkCmdEndRenderPass2KHR)load(context, "vkCmdEndRenderPass2KHR"); - vkCmdNextSubpass2KHR = (PFN_vkCmdNextSubpass2KHR)load(context, "vkCmdNextSubpass2KHR"); - vkCreateRenderPass2KHR = (PFN_vkCreateRenderPass2KHR)load(context, "vkCreateRenderPass2KHR"); -#endif /* defined(VK_KHR_create_renderpass2) */ -#if defined(VK_KHR_deferred_host_operations) - vkCreateDeferredOperationKHR = (PFN_vkCreateDeferredOperationKHR)load(context, "vkCreateDeferredOperationKHR"); - vkDeferredOperationJoinKHR = (PFN_vkDeferredOperationJoinKHR)load(context, "vkDeferredOperationJoinKHR"); - vkDestroyDeferredOperationKHR = (PFN_vkDestroyDeferredOperationKHR)load(context, "vkDestroyDeferredOperationKHR"); - vkGetDeferredOperationMaxConcurrencyKHR = (PFN_vkGetDeferredOperationMaxConcurrencyKHR)load(context, "vkGetDeferredOperationMaxConcurrencyKHR"); - vkGetDeferredOperationResultKHR = (PFN_vkGetDeferredOperationResultKHR)load(context, "vkGetDeferredOperationResultKHR"); -#endif /* defined(VK_KHR_deferred_host_operations) */ -#if defined(VK_KHR_descriptor_update_template) - vkCreateDescriptorUpdateTemplateKHR = (PFN_vkCreateDescriptorUpdateTemplateKHR)load(context, "vkCreateDescriptorUpdateTemplateKHR"); - vkDestroyDescriptorUpdateTemplateKHR = (PFN_vkDestroyDescriptorUpdateTemplateKHR)load(context, "vkDestroyDescriptorUpdateTemplateKHR"); - vkUpdateDescriptorSetWithTemplateKHR = (PFN_vkUpdateDescriptorSetWithTemplateKHR)load(context, "vkUpdateDescriptorSetWithTemplateKHR"); -#endif /* defined(VK_KHR_descriptor_update_template) */ -#if defined(VK_KHR_device_group) - vkCmdDispatchBaseKHR = (PFN_vkCmdDispatchBaseKHR)load(context, "vkCmdDispatchBaseKHR"); - vkCmdSetDeviceMaskKHR = (PFN_vkCmdSetDeviceMaskKHR)load(context, "vkCmdSetDeviceMaskKHR"); - vkGetDeviceGroupPeerMemoryFeaturesKHR = (PFN_vkGetDeviceGroupPeerMemoryFeaturesKHR)load(context, "vkGetDeviceGroupPeerMemoryFeaturesKHR"); -#endif /* defined(VK_KHR_device_group) */ -#if defined(VK_KHR_display_swapchain) - vkCreateSharedSwapchainsKHR = (PFN_vkCreateSharedSwapchainsKHR)load(context, "vkCreateSharedSwapchainsKHR"); -#endif /* defined(VK_KHR_display_swapchain) */ -#if defined(VK_KHR_draw_indirect_count) - vkCmdDrawIndexedIndirectCountKHR = (PFN_vkCmdDrawIndexedIndirectCountKHR)load(context, "vkCmdDrawIndexedIndirectCountKHR"); - vkCmdDrawIndirectCountKHR = (PFN_vkCmdDrawIndirectCountKHR)load(context, "vkCmdDrawIndirectCountKHR"); -#endif /* defined(VK_KHR_draw_indirect_count) */ -#if defined(VK_KHR_dynamic_rendering) - vkCmdBeginRenderingKHR = (PFN_vkCmdBeginRenderingKHR)load(context, "vkCmdBeginRenderingKHR"); - vkCmdEndRenderingKHR = (PFN_vkCmdEndRenderingKHR)load(context, "vkCmdEndRenderingKHR"); -#endif /* defined(VK_KHR_dynamic_rendering) */ -#if defined(VK_KHR_external_fence_fd) - vkGetFenceFdKHR = (PFN_vkGetFenceFdKHR)load(context, "vkGetFenceFdKHR"); - vkImportFenceFdKHR = (PFN_vkImportFenceFdKHR)load(context, "vkImportFenceFdKHR"); -#endif /* defined(VK_KHR_external_fence_fd) */ -#if defined(VK_KHR_external_fence_win32) - vkGetFenceWin32HandleKHR = (PFN_vkGetFenceWin32HandleKHR)load(context, "vkGetFenceWin32HandleKHR"); - vkImportFenceWin32HandleKHR = (PFN_vkImportFenceWin32HandleKHR)load(context, "vkImportFenceWin32HandleKHR"); -#endif /* defined(VK_KHR_external_fence_win32) */ -#if defined(VK_KHR_external_memory_fd) - vkGetMemoryFdKHR = (PFN_vkGetMemoryFdKHR)load(context, "vkGetMemoryFdKHR"); - vkGetMemoryFdPropertiesKHR = (PFN_vkGetMemoryFdPropertiesKHR)load(context, "vkGetMemoryFdPropertiesKHR"); -#endif /* defined(VK_KHR_external_memory_fd) */ -#if defined(VK_KHR_external_memory_win32) - vkGetMemoryWin32HandleKHR = (PFN_vkGetMemoryWin32HandleKHR)load(context, "vkGetMemoryWin32HandleKHR"); - vkGetMemoryWin32HandlePropertiesKHR = (PFN_vkGetMemoryWin32HandlePropertiesKHR)load(context, "vkGetMemoryWin32HandlePropertiesKHR"); -#endif /* defined(VK_KHR_external_memory_win32) */ -#if defined(VK_KHR_external_semaphore_fd) - vkGetSemaphoreFdKHR = (PFN_vkGetSemaphoreFdKHR)load(context, "vkGetSemaphoreFdKHR"); - vkImportSemaphoreFdKHR = (PFN_vkImportSemaphoreFdKHR)load(context, "vkImportSemaphoreFdKHR"); -#endif /* defined(VK_KHR_external_semaphore_fd) */ -#if defined(VK_KHR_external_semaphore_win32) - vkGetSemaphoreWin32HandleKHR = (PFN_vkGetSemaphoreWin32HandleKHR)load(context, "vkGetSemaphoreWin32HandleKHR"); - vkImportSemaphoreWin32HandleKHR = (PFN_vkImportSemaphoreWin32HandleKHR)load(context, "vkImportSemaphoreWin32HandleKHR"); -#endif /* defined(VK_KHR_external_semaphore_win32) */ -#if defined(VK_KHR_fragment_shading_rate) - vkCmdSetFragmentShadingRateKHR = (PFN_vkCmdSetFragmentShadingRateKHR)load(context, "vkCmdSetFragmentShadingRateKHR"); -#endif /* defined(VK_KHR_fragment_shading_rate) */ -#if defined(VK_KHR_get_memory_requirements2) - vkGetBufferMemoryRequirements2KHR = (PFN_vkGetBufferMemoryRequirements2KHR)load(context, "vkGetBufferMemoryRequirements2KHR"); - vkGetImageMemoryRequirements2KHR = (PFN_vkGetImageMemoryRequirements2KHR)load(context, "vkGetImageMemoryRequirements2KHR"); - vkGetImageSparseMemoryRequirements2KHR = (PFN_vkGetImageSparseMemoryRequirements2KHR)load(context, "vkGetImageSparseMemoryRequirements2KHR"); -#endif /* defined(VK_KHR_get_memory_requirements2) */ -#if defined(VK_KHR_maintenance1) - vkTrimCommandPoolKHR = (PFN_vkTrimCommandPoolKHR)load(context, "vkTrimCommandPoolKHR"); -#endif /* defined(VK_KHR_maintenance1) */ -#if defined(VK_KHR_maintenance3) - vkGetDescriptorSetLayoutSupportKHR = (PFN_vkGetDescriptorSetLayoutSupportKHR)load(context, "vkGetDescriptorSetLayoutSupportKHR"); -#endif /* defined(VK_KHR_maintenance3) */ -#if defined(VK_KHR_maintenance4) - vkGetDeviceBufferMemoryRequirementsKHR = (PFN_vkGetDeviceBufferMemoryRequirementsKHR)load(context, "vkGetDeviceBufferMemoryRequirementsKHR"); - vkGetDeviceImageMemoryRequirementsKHR = (PFN_vkGetDeviceImageMemoryRequirementsKHR)load(context, "vkGetDeviceImageMemoryRequirementsKHR"); - vkGetDeviceImageSparseMemoryRequirementsKHR = (PFN_vkGetDeviceImageSparseMemoryRequirementsKHR)load(context, "vkGetDeviceImageSparseMemoryRequirementsKHR"); -#endif /* defined(VK_KHR_maintenance4) */ -#if defined(VK_KHR_performance_query) - vkAcquireProfilingLockKHR = (PFN_vkAcquireProfilingLockKHR)load(context, "vkAcquireProfilingLockKHR"); - vkReleaseProfilingLockKHR = (PFN_vkReleaseProfilingLockKHR)load(context, "vkReleaseProfilingLockKHR"); -#endif /* defined(VK_KHR_performance_query) */ -#if defined(VK_KHR_pipeline_executable_properties) - vkGetPipelineExecutableInternalRepresentationsKHR = (PFN_vkGetPipelineExecutableInternalRepresentationsKHR)load(context, "vkGetPipelineExecutableInternalRepresentationsKHR"); - vkGetPipelineExecutablePropertiesKHR = (PFN_vkGetPipelineExecutablePropertiesKHR)load(context, "vkGetPipelineExecutablePropertiesKHR"); - vkGetPipelineExecutableStatisticsKHR = (PFN_vkGetPipelineExecutableStatisticsKHR)load(context, "vkGetPipelineExecutableStatisticsKHR"); -#endif /* defined(VK_KHR_pipeline_executable_properties) */ -#if defined(VK_KHR_present_wait) - vkWaitForPresentKHR = (PFN_vkWaitForPresentKHR)load(context, "vkWaitForPresentKHR"); -#endif /* defined(VK_KHR_present_wait) */ -#if defined(VK_KHR_push_descriptor) - vkCmdPushDescriptorSetKHR = (PFN_vkCmdPushDescriptorSetKHR)load(context, "vkCmdPushDescriptorSetKHR"); -#endif /* defined(VK_KHR_push_descriptor) */ -#if defined(VK_KHR_ray_tracing_pipeline) - vkCmdSetRayTracingPipelineStackSizeKHR = (PFN_vkCmdSetRayTracingPipelineStackSizeKHR)load(context, "vkCmdSetRayTracingPipelineStackSizeKHR"); - vkCmdTraceRaysIndirectKHR = (PFN_vkCmdTraceRaysIndirectKHR)load(context, "vkCmdTraceRaysIndirectKHR"); - vkCmdTraceRaysKHR = (PFN_vkCmdTraceRaysKHR)load(context, "vkCmdTraceRaysKHR"); - vkCreateRayTracingPipelinesKHR = (PFN_vkCreateRayTracingPipelinesKHR)load(context, "vkCreateRayTracingPipelinesKHR"); - vkGetRayTracingCaptureReplayShaderGroupHandlesKHR = (PFN_vkGetRayTracingCaptureReplayShaderGroupHandlesKHR)load(context, "vkGetRayTracingCaptureReplayShaderGroupHandlesKHR"); - vkGetRayTracingShaderGroupHandlesKHR = (PFN_vkGetRayTracingShaderGroupHandlesKHR)load(context, "vkGetRayTracingShaderGroupHandlesKHR"); - vkGetRayTracingShaderGroupStackSizeKHR = (PFN_vkGetRayTracingShaderGroupStackSizeKHR)load(context, "vkGetRayTracingShaderGroupStackSizeKHR"); -#endif /* defined(VK_KHR_ray_tracing_pipeline) */ -#if defined(VK_KHR_sampler_ycbcr_conversion) - vkCreateSamplerYcbcrConversionKHR = (PFN_vkCreateSamplerYcbcrConversionKHR)load(context, "vkCreateSamplerYcbcrConversionKHR"); - vkDestroySamplerYcbcrConversionKHR = (PFN_vkDestroySamplerYcbcrConversionKHR)load(context, "vkDestroySamplerYcbcrConversionKHR"); -#endif /* defined(VK_KHR_sampler_ycbcr_conversion) */ -#if defined(VK_KHR_shared_presentable_image) - vkGetSwapchainStatusKHR = (PFN_vkGetSwapchainStatusKHR)load(context, "vkGetSwapchainStatusKHR"); -#endif /* defined(VK_KHR_shared_presentable_image) */ -#if defined(VK_KHR_swapchain) - vkAcquireNextImageKHR = (PFN_vkAcquireNextImageKHR)load(context, "vkAcquireNextImageKHR"); - vkCreateSwapchainKHR = (PFN_vkCreateSwapchainKHR)load(context, "vkCreateSwapchainKHR"); - vkDestroySwapchainKHR = (PFN_vkDestroySwapchainKHR)load(context, "vkDestroySwapchainKHR"); - vkGetSwapchainImagesKHR = (PFN_vkGetSwapchainImagesKHR)load(context, "vkGetSwapchainImagesKHR"); - vkQueuePresentKHR = (PFN_vkQueuePresentKHR)load(context, "vkQueuePresentKHR"); -#endif /* defined(VK_KHR_swapchain) */ -#if defined(VK_KHR_synchronization2) - vkCmdPipelineBarrier2KHR = (PFN_vkCmdPipelineBarrier2KHR)load(context, "vkCmdPipelineBarrier2KHR"); - vkCmdResetEvent2KHR = (PFN_vkCmdResetEvent2KHR)load(context, "vkCmdResetEvent2KHR"); - vkCmdSetEvent2KHR = (PFN_vkCmdSetEvent2KHR)load(context, "vkCmdSetEvent2KHR"); - vkCmdWaitEvents2KHR = (PFN_vkCmdWaitEvents2KHR)load(context, "vkCmdWaitEvents2KHR"); - vkCmdWriteTimestamp2KHR = (PFN_vkCmdWriteTimestamp2KHR)load(context, "vkCmdWriteTimestamp2KHR"); - vkQueueSubmit2KHR = (PFN_vkQueueSubmit2KHR)load(context, "vkQueueSubmit2KHR"); -#endif /* defined(VK_KHR_synchronization2) */ -#if defined(VK_KHR_synchronization2) && defined(VK_AMD_buffer_marker) - vkCmdWriteBufferMarker2AMD = (PFN_vkCmdWriteBufferMarker2AMD)load(context, "vkCmdWriteBufferMarker2AMD"); -#endif /* defined(VK_KHR_synchronization2) && defined(VK_AMD_buffer_marker) */ -#if defined(VK_KHR_synchronization2) && defined(VK_NV_device_diagnostic_checkpoints) - vkGetQueueCheckpointData2NV = (PFN_vkGetQueueCheckpointData2NV)load(context, "vkGetQueueCheckpointData2NV"); -#endif /* defined(VK_KHR_synchronization2) && defined(VK_NV_device_diagnostic_checkpoints) */ -#if defined(VK_KHR_timeline_semaphore) - vkGetSemaphoreCounterValueKHR = (PFN_vkGetSemaphoreCounterValueKHR)load(context, "vkGetSemaphoreCounterValueKHR"); - vkSignalSemaphoreKHR = (PFN_vkSignalSemaphoreKHR)load(context, "vkSignalSemaphoreKHR"); - vkWaitSemaphoresKHR = (PFN_vkWaitSemaphoresKHR)load(context, "vkWaitSemaphoresKHR"); -#endif /* defined(VK_KHR_timeline_semaphore) */ -#if defined(VK_KHR_video_decode_queue) - vkCmdDecodeVideoKHR = (PFN_vkCmdDecodeVideoKHR)load(context, "vkCmdDecodeVideoKHR"); -#endif /* defined(VK_KHR_video_decode_queue) */ -#if defined(VK_KHR_video_encode_queue) - vkCmdEncodeVideoKHR = (PFN_vkCmdEncodeVideoKHR)load(context, "vkCmdEncodeVideoKHR"); -#endif /* defined(VK_KHR_video_encode_queue) */ -#if defined(VK_KHR_video_queue) - vkBindVideoSessionMemoryKHR = (PFN_vkBindVideoSessionMemoryKHR)load(context, "vkBindVideoSessionMemoryKHR"); - vkCmdBeginVideoCodingKHR = (PFN_vkCmdBeginVideoCodingKHR)load(context, "vkCmdBeginVideoCodingKHR"); - vkCmdControlVideoCodingKHR = (PFN_vkCmdControlVideoCodingKHR)load(context, "vkCmdControlVideoCodingKHR"); - vkCmdEndVideoCodingKHR = (PFN_vkCmdEndVideoCodingKHR)load(context, "vkCmdEndVideoCodingKHR"); - vkCreateVideoSessionKHR = (PFN_vkCreateVideoSessionKHR)load(context, "vkCreateVideoSessionKHR"); - vkCreateVideoSessionParametersKHR = (PFN_vkCreateVideoSessionParametersKHR)load(context, "vkCreateVideoSessionParametersKHR"); - vkDestroyVideoSessionKHR = (PFN_vkDestroyVideoSessionKHR)load(context, "vkDestroyVideoSessionKHR"); - vkDestroyVideoSessionParametersKHR = (PFN_vkDestroyVideoSessionParametersKHR)load(context, "vkDestroyVideoSessionParametersKHR"); - vkGetVideoSessionMemoryRequirementsKHR = (PFN_vkGetVideoSessionMemoryRequirementsKHR)load(context, "vkGetVideoSessionMemoryRequirementsKHR"); - vkUpdateVideoSessionParametersKHR = (PFN_vkUpdateVideoSessionParametersKHR)load(context, "vkUpdateVideoSessionParametersKHR"); -#endif /* defined(VK_KHR_video_queue) */ -#if defined(VK_NVX_binary_import) - vkCmdCuLaunchKernelNVX = (PFN_vkCmdCuLaunchKernelNVX)load(context, "vkCmdCuLaunchKernelNVX"); - vkCreateCuFunctionNVX = (PFN_vkCreateCuFunctionNVX)load(context, "vkCreateCuFunctionNVX"); - vkCreateCuModuleNVX = (PFN_vkCreateCuModuleNVX)load(context, "vkCreateCuModuleNVX"); - vkDestroyCuFunctionNVX = (PFN_vkDestroyCuFunctionNVX)load(context, "vkDestroyCuFunctionNVX"); - vkDestroyCuModuleNVX = (PFN_vkDestroyCuModuleNVX)load(context, "vkDestroyCuModuleNVX"); -#endif /* defined(VK_NVX_binary_import) */ -#if defined(VK_NVX_image_view_handle) - vkGetImageViewAddressNVX = (PFN_vkGetImageViewAddressNVX)load(context, "vkGetImageViewAddressNVX"); - vkGetImageViewHandleNVX = (PFN_vkGetImageViewHandleNVX)load(context, "vkGetImageViewHandleNVX"); -#endif /* defined(VK_NVX_image_view_handle) */ -#if defined(VK_NV_clip_space_w_scaling) - vkCmdSetViewportWScalingNV = (PFN_vkCmdSetViewportWScalingNV)load(context, "vkCmdSetViewportWScalingNV"); -#endif /* defined(VK_NV_clip_space_w_scaling) */ -#if defined(VK_NV_device_diagnostic_checkpoints) - vkCmdSetCheckpointNV = (PFN_vkCmdSetCheckpointNV)load(context, "vkCmdSetCheckpointNV"); - vkGetQueueCheckpointDataNV = (PFN_vkGetQueueCheckpointDataNV)load(context, "vkGetQueueCheckpointDataNV"); -#endif /* defined(VK_NV_device_diagnostic_checkpoints) */ -#if defined(VK_NV_device_generated_commands) - vkCmdBindPipelineShaderGroupNV = (PFN_vkCmdBindPipelineShaderGroupNV)load(context, "vkCmdBindPipelineShaderGroupNV"); - vkCmdExecuteGeneratedCommandsNV = (PFN_vkCmdExecuteGeneratedCommandsNV)load(context, "vkCmdExecuteGeneratedCommandsNV"); - vkCmdPreprocessGeneratedCommandsNV = (PFN_vkCmdPreprocessGeneratedCommandsNV)load(context, "vkCmdPreprocessGeneratedCommandsNV"); - vkCreateIndirectCommandsLayoutNV = (PFN_vkCreateIndirectCommandsLayoutNV)load(context, "vkCreateIndirectCommandsLayoutNV"); - vkDestroyIndirectCommandsLayoutNV = (PFN_vkDestroyIndirectCommandsLayoutNV)load(context, "vkDestroyIndirectCommandsLayoutNV"); - vkGetGeneratedCommandsMemoryRequirementsNV = (PFN_vkGetGeneratedCommandsMemoryRequirementsNV)load(context, "vkGetGeneratedCommandsMemoryRequirementsNV"); -#endif /* defined(VK_NV_device_generated_commands) */ -#if defined(VK_NV_external_memory_rdma) - vkGetMemoryRemoteAddressNV = (PFN_vkGetMemoryRemoteAddressNV)load(context, "vkGetMemoryRemoteAddressNV"); -#endif /* defined(VK_NV_external_memory_rdma) */ -#if defined(VK_NV_external_memory_win32) - vkGetMemoryWin32HandleNV = (PFN_vkGetMemoryWin32HandleNV)load(context, "vkGetMemoryWin32HandleNV"); -#endif /* defined(VK_NV_external_memory_win32) */ -#if defined(VK_NV_fragment_shading_rate_enums) - vkCmdSetFragmentShadingRateEnumNV = (PFN_vkCmdSetFragmentShadingRateEnumNV)load(context, "vkCmdSetFragmentShadingRateEnumNV"); -#endif /* defined(VK_NV_fragment_shading_rate_enums) */ -#if defined(VK_NV_mesh_shader) - vkCmdDrawMeshTasksIndirectCountNV = (PFN_vkCmdDrawMeshTasksIndirectCountNV)load(context, "vkCmdDrawMeshTasksIndirectCountNV"); - vkCmdDrawMeshTasksIndirectNV = (PFN_vkCmdDrawMeshTasksIndirectNV)load(context, "vkCmdDrawMeshTasksIndirectNV"); - vkCmdDrawMeshTasksNV = (PFN_vkCmdDrawMeshTasksNV)load(context, "vkCmdDrawMeshTasksNV"); -#endif /* defined(VK_NV_mesh_shader) */ -#if defined(VK_NV_ray_tracing) - vkBindAccelerationStructureMemoryNV = (PFN_vkBindAccelerationStructureMemoryNV)load(context, "vkBindAccelerationStructureMemoryNV"); - vkCmdBuildAccelerationStructureNV = (PFN_vkCmdBuildAccelerationStructureNV)load(context, "vkCmdBuildAccelerationStructureNV"); - vkCmdCopyAccelerationStructureNV = (PFN_vkCmdCopyAccelerationStructureNV)load(context, "vkCmdCopyAccelerationStructureNV"); - vkCmdTraceRaysNV = (PFN_vkCmdTraceRaysNV)load(context, "vkCmdTraceRaysNV"); - vkCmdWriteAccelerationStructuresPropertiesNV = (PFN_vkCmdWriteAccelerationStructuresPropertiesNV)load(context, "vkCmdWriteAccelerationStructuresPropertiesNV"); - vkCompileDeferredNV = (PFN_vkCompileDeferredNV)load(context, "vkCompileDeferredNV"); - vkCreateAccelerationStructureNV = (PFN_vkCreateAccelerationStructureNV)load(context, "vkCreateAccelerationStructureNV"); - vkCreateRayTracingPipelinesNV = (PFN_vkCreateRayTracingPipelinesNV)load(context, "vkCreateRayTracingPipelinesNV"); - vkDestroyAccelerationStructureNV = (PFN_vkDestroyAccelerationStructureNV)load(context, "vkDestroyAccelerationStructureNV"); - vkGetAccelerationStructureHandleNV = (PFN_vkGetAccelerationStructureHandleNV)load(context, "vkGetAccelerationStructureHandleNV"); - vkGetAccelerationStructureMemoryRequirementsNV = (PFN_vkGetAccelerationStructureMemoryRequirementsNV)load(context, "vkGetAccelerationStructureMemoryRequirementsNV"); - vkGetRayTracingShaderGroupHandlesNV = (PFN_vkGetRayTracingShaderGroupHandlesNV)load(context, "vkGetRayTracingShaderGroupHandlesNV"); -#endif /* defined(VK_NV_ray_tracing) */ -#if defined(VK_NV_scissor_exclusive) - vkCmdSetExclusiveScissorNV = (PFN_vkCmdSetExclusiveScissorNV)load(context, "vkCmdSetExclusiveScissorNV"); -#endif /* defined(VK_NV_scissor_exclusive) */ -#if defined(VK_NV_shading_rate_image) - vkCmdBindShadingRateImageNV = (PFN_vkCmdBindShadingRateImageNV)load(context, "vkCmdBindShadingRateImageNV"); - vkCmdSetCoarseSampleOrderNV = (PFN_vkCmdSetCoarseSampleOrderNV)load(context, "vkCmdSetCoarseSampleOrderNV"); - vkCmdSetViewportShadingRatePaletteNV = (PFN_vkCmdSetViewportShadingRatePaletteNV)load(context, "vkCmdSetViewportShadingRatePaletteNV"); -#endif /* defined(VK_NV_shading_rate_image) */ -#if (defined(VK_EXT_full_screen_exclusive) && defined(VK_KHR_device_group)) || (defined(VK_EXT_full_screen_exclusive) && defined(VK_VERSION_1_1)) - vkGetDeviceGroupSurfacePresentModes2EXT = (PFN_vkGetDeviceGroupSurfacePresentModes2EXT)load(context, "vkGetDeviceGroupSurfacePresentModes2EXT"); -#endif /* (defined(VK_EXT_full_screen_exclusive) && defined(VK_KHR_device_group)) || (defined(VK_EXT_full_screen_exclusive) && defined(VK_VERSION_1_1)) */ -#if (defined(VK_KHR_descriptor_update_template) && defined(VK_KHR_push_descriptor)) || (defined(VK_KHR_push_descriptor) && defined(VK_VERSION_1_1)) || (defined(VK_KHR_push_descriptor) && defined(VK_KHR_descriptor_update_template)) - vkCmdPushDescriptorSetWithTemplateKHR = (PFN_vkCmdPushDescriptorSetWithTemplateKHR)load(context, "vkCmdPushDescriptorSetWithTemplateKHR"); -#endif /* (defined(VK_KHR_descriptor_update_template) && defined(VK_KHR_push_descriptor)) || (defined(VK_KHR_push_descriptor) && defined(VK_VERSION_1_1)) || (defined(VK_KHR_push_descriptor) && defined(VK_KHR_descriptor_update_template)) */ -#if (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) - vkGetDeviceGroupPresentCapabilitiesKHR = (PFN_vkGetDeviceGroupPresentCapabilitiesKHR)load(context, "vkGetDeviceGroupPresentCapabilitiesKHR"); - vkGetDeviceGroupSurfacePresentModesKHR = (PFN_vkGetDeviceGroupSurfacePresentModesKHR)load(context, "vkGetDeviceGroupSurfacePresentModesKHR"); -#endif /* (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) */ -#if (defined(VK_KHR_device_group) && defined(VK_KHR_swapchain)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) - vkAcquireNextImage2KHR = (PFN_vkAcquireNextImage2KHR)load(context, "vkAcquireNextImage2KHR"); -#endif /* (defined(VK_KHR_device_group) && defined(VK_KHR_swapchain)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) */ - /* VOLK_GENERATE_LOAD_DEVICE */ -} - -static void volkGenLoadDeviceTable(struct VolkDeviceTable* table, void* context, PFN_vkVoidFunction (*load)(void*, const char*)) -{ - /* VOLK_GENERATE_LOAD_DEVICE_TABLE */ -#if defined(VK_VERSION_1_0) - table->vkAllocateCommandBuffers = (PFN_vkAllocateCommandBuffers)load(context, "vkAllocateCommandBuffers"); - table->vkAllocateDescriptorSets = (PFN_vkAllocateDescriptorSets)load(context, "vkAllocateDescriptorSets"); - table->vkAllocateMemory = (PFN_vkAllocateMemory)load(context, "vkAllocateMemory"); - table->vkBeginCommandBuffer = (PFN_vkBeginCommandBuffer)load(context, "vkBeginCommandBuffer"); - table->vkBindBufferMemory = (PFN_vkBindBufferMemory)load(context, "vkBindBufferMemory"); - table->vkBindImageMemory = (PFN_vkBindImageMemory)load(context, "vkBindImageMemory"); - table->vkCmdBeginQuery = (PFN_vkCmdBeginQuery)load(context, "vkCmdBeginQuery"); - table->vkCmdBeginRenderPass = (PFN_vkCmdBeginRenderPass)load(context, "vkCmdBeginRenderPass"); - table->vkCmdBindDescriptorSets = (PFN_vkCmdBindDescriptorSets)load(context, "vkCmdBindDescriptorSets"); - table->vkCmdBindIndexBuffer = (PFN_vkCmdBindIndexBuffer)load(context, "vkCmdBindIndexBuffer"); - table->vkCmdBindPipeline = (PFN_vkCmdBindPipeline)load(context, "vkCmdBindPipeline"); - table->vkCmdBindVertexBuffers = (PFN_vkCmdBindVertexBuffers)load(context, "vkCmdBindVertexBuffers"); - table->vkCmdBlitImage = (PFN_vkCmdBlitImage)load(context, "vkCmdBlitImage"); - table->vkCmdClearAttachments = (PFN_vkCmdClearAttachments)load(context, "vkCmdClearAttachments"); - table->vkCmdClearColorImage = (PFN_vkCmdClearColorImage)load(context, "vkCmdClearColorImage"); - table->vkCmdClearDepthStencilImage = (PFN_vkCmdClearDepthStencilImage)load(context, "vkCmdClearDepthStencilImage"); - table->vkCmdCopyBuffer = (PFN_vkCmdCopyBuffer)load(context, "vkCmdCopyBuffer"); - table->vkCmdCopyBufferToImage = (PFN_vkCmdCopyBufferToImage)load(context, "vkCmdCopyBufferToImage"); - table->vkCmdCopyImage = (PFN_vkCmdCopyImage)load(context, "vkCmdCopyImage"); - table->vkCmdCopyImageToBuffer = (PFN_vkCmdCopyImageToBuffer)load(context, "vkCmdCopyImageToBuffer"); - table->vkCmdCopyQueryPoolResults = (PFN_vkCmdCopyQueryPoolResults)load(context, "vkCmdCopyQueryPoolResults"); - table->vkCmdDispatch = (PFN_vkCmdDispatch)load(context, "vkCmdDispatch"); - table->vkCmdDispatchIndirect = (PFN_vkCmdDispatchIndirect)load(context, "vkCmdDispatchIndirect"); - table->vkCmdDraw = (PFN_vkCmdDraw)load(context, "vkCmdDraw"); - table->vkCmdDrawIndexed = (PFN_vkCmdDrawIndexed)load(context, "vkCmdDrawIndexed"); - table->vkCmdDrawIndexedIndirect = (PFN_vkCmdDrawIndexedIndirect)load(context, "vkCmdDrawIndexedIndirect"); - table->vkCmdDrawIndirect = (PFN_vkCmdDrawIndirect)load(context, "vkCmdDrawIndirect"); - table->vkCmdEndQuery = (PFN_vkCmdEndQuery)load(context, "vkCmdEndQuery"); - table->vkCmdEndRenderPass = (PFN_vkCmdEndRenderPass)load(context, "vkCmdEndRenderPass"); - table->vkCmdExecuteCommands = (PFN_vkCmdExecuteCommands)load(context, "vkCmdExecuteCommands"); - table->vkCmdFillBuffer = (PFN_vkCmdFillBuffer)load(context, "vkCmdFillBuffer"); - table->vkCmdNextSubpass = (PFN_vkCmdNextSubpass)load(context, "vkCmdNextSubpass"); - table->vkCmdPipelineBarrier = (PFN_vkCmdPipelineBarrier)load(context, "vkCmdPipelineBarrier"); - table->vkCmdPushConstants = (PFN_vkCmdPushConstants)load(context, "vkCmdPushConstants"); - table->vkCmdResetEvent = (PFN_vkCmdResetEvent)load(context, "vkCmdResetEvent"); - table->vkCmdResetQueryPool = (PFN_vkCmdResetQueryPool)load(context, "vkCmdResetQueryPool"); - table->vkCmdResolveImage = (PFN_vkCmdResolveImage)load(context, "vkCmdResolveImage"); - table->vkCmdSetBlendConstants = (PFN_vkCmdSetBlendConstants)load(context, "vkCmdSetBlendConstants"); - table->vkCmdSetDepthBias = (PFN_vkCmdSetDepthBias)load(context, "vkCmdSetDepthBias"); - table->vkCmdSetDepthBounds = (PFN_vkCmdSetDepthBounds)load(context, "vkCmdSetDepthBounds"); - table->vkCmdSetEvent = (PFN_vkCmdSetEvent)load(context, "vkCmdSetEvent"); - table->vkCmdSetLineWidth = (PFN_vkCmdSetLineWidth)load(context, "vkCmdSetLineWidth"); - table->vkCmdSetScissor = (PFN_vkCmdSetScissor)load(context, "vkCmdSetScissor"); - table->vkCmdSetStencilCompareMask = (PFN_vkCmdSetStencilCompareMask)load(context, "vkCmdSetStencilCompareMask"); - table->vkCmdSetStencilReference = (PFN_vkCmdSetStencilReference)load(context, "vkCmdSetStencilReference"); - table->vkCmdSetStencilWriteMask = (PFN_vkCmdSetStencilWriteMask)load(context, "vkCmdSetStencilWriteMask"); - table->vkCmdSetViewport = (PFN_vkCmdSetViewport)load(context, "vkCmdSetViewport"); - table->vkCmdUpdateBuffer = (PFN_vkCmdUpdateBuffer)load(context, "vkCmdUpdateBuffer"); - table->vkCmdWaitEvents = (PFN_vkCmdWaitEvents)load(context, "vkCmdWaitEvents"); - table->vkCmdWriteTimestamp = (PFN_vkCmdWriteTimestamp)load(context, "vkCmdWriteTimestamp"); - table->vkCreateBuffer = (PFN_vkCreateBuffer)load(context, "vkCreateBuffer"); - table->vkCreateBufferView = (PFN_vkCreateBufferView)load(context, "vkCreateBufferView"); - table->vkCreateCommandPool = (PFN_vkCreateCommandPool)load(context, "vkCreateCommandPool"); - table->vkCreateComputePipelines = (PFN_vkCreateComputePipelines)load(context, "vkCreateComputePipelines"); - table->vkCreateDescriptorPool = (PFN_vkCreateDescriptorPool)load(context, "vkCreateDescriptorPool"); - table->vkCreateDescriptorSetLayout = (PFN_vkCreateDescriptorSetLayout)load(context, "vkCreateDescriptorSetLayout"); - table->vkCreateEvent = (PFN_vkCreateEvent)load(context, "vkCreateEvent"); - table->vkCreateFence = (PFN_vkCreateFence)load(context, "vkCreateFence"); - table->vkCreateFramebuffer = (PFN_vkCreateFramebuffer)load(context, "vkCreateFramebuffer"); - table->vkCreateGraphicsPipelines = (PFN_vkCreateGraphicsPipelines)load(context, "vkCreateGraphicsPipelines"); - table->vkCreateImage = (PFN_vkCreateImage)load(context, "vkCreateImage"); - table->vkCreateImageView = (PFN_vkCreateImageView)load(context, "vkCreateImageView"); - table->vkCreatePipelineCache = (PFN_vkCreatePipelineCache)load(context, "vkCreatePipelineCache"); - table->vkCreatePipelineLayout = (PFN_vkCreatePipelineLayout)load(context, "vkCreatePipelineLayout"); - table->vkCreateQueryPool = (PFN_vkCreateQueryPool)load(context, "vkCreateQueryPool"); - table->vkCreateRenderPass = (PFN_vkCreateRenderPass)load(context, "vkCreateRenderPass"); - table->vkCreateSampler = (PFN_vkCreateSampler)load(context, "vkCreateSampler"); - table->vkCreateSemaphore = (PFN_vkCreateSemaphore)load(context, "vkCreateSemaphore"); - table->vkCreateShaderModule = (PFN_vkCreateShaderModule)load(context, "vkCreateShaderModule"); - table->vkDestroyBuffer = (PFN_vkDestroyBuffer)load(context, "vkDestroyBuffer"); - table->vkDestroyBufferView = (PFN_vkDestroyBufferView)load(context, "vkDestroyBufferView"); - table->vkDestroyCommandPool = (PFN_vkDestroyCommandPool)load(context, "vkDestroyCommandPool"); - table->vkDestroyDescriptorPool = (PFN_vkDestroyDescriptorPool)load(context, "vkDestroyDescriptorPool"); - table->vkDestroyDescriptorSetLayout = (PFN_vkDestroyDescriptorSetLayout)load(context, "vkDestroyDescriptorSetLayout"); - table->vkDestroyDevice = (PFN_vkDestroyDevice)load(context, "vkDestroyDevice"); - table->vkDestroyEvent = (PFN_vkDestroyEvent)load(context, "vkDestroyEvent"); - table->vkDestroyFence = (PFN_vkDestroyFence)load(context, "vkDestroyFence"); - table->vkDestroyFramebuffer = (PFN_vkDestroyFramebuffer)load(context, "vkDestroyFramebuffer"); - table->vkDestroyImage = (PFN_vkDestroyImage)load(context, "vkDestroyImage"); - table->vkDestroyImageView = (PFN_vkDestroyImageView)load(context, "vkDestroyImageView"); - table->vkDestroyPipeline = (PFN_vkDestroyPipeline)load(context, "vkDestroyPipeline"); - table->vkDestroyPipelineCache = (PFN_vkDestroyPipelineCache)load(context, "vkDestroyPipelineCache"); - table->vkDestroyPipelineLayout = (PFN_vkDestroyPipelineLayout)load(context, "vkDestroyPipelineLayout"); - table->vkDestroyQueryPool = (PFN_vkDestroyQueryPool)load(context, "vkDestroyQueryPool"); - table->vkDestroyRenderPass = (PFN_vkDestroyRenderPass)load(context, "vkDestroyRenderPass"); - table->vkDestroySampler = (PFN_vkDestroySampler)load(context, "vkDestroySampler"); - table->vkDestroySemaphore = (PFN_vkDestroySemaphore)load(context, "vkDestroySemaphore"); - table->vkDestroyShaderModule = (PFN_vkDestroyShaderModule)load(context, "vkDestroyShaderModule"); - table->vkDeviceWaitIdle = (PFN_vkDeviceWaitIdle)load(context, "vkDeviceWaitIdle"); - table->vkEndCommandBuffer = (PFN_vkEndCommandBuffer)load(context, "vkEndCommandBuffer"); - table->vkFlushMappedMemoryRanges = (PFN_vkFlushMappedMemoryRanges)load(context, "vkFlushMappedMemoryRanges"); - table->vkFreeCommandBuffers = (PFN_vkFreeCommandBuffers)load(context, "vkFreeCommandBuffers"); - table->vkFreeDescriptorSets = (PFN_vkFreeDescriptorSets)load(context, "vkFreeDescriptorSets"); - table->vkFreeMemory = (PFN_vkFreeMemory)load(context, "vkFreeMemory"); - table->vkGetBufferMemoryRequirements = (PFN_vkGetBufferMemoryRequirements)load(context, "vkGetBufferMemoryRequirements"); - table->vkGetDeviceMemoryCommitment = (PFN_vkGetDeviceMemoryCommitment)load(context, "vkGetDeviceMemoryCommitment"); - table->vkGetDeviceQueue = (PFN_vkGetDeviceQueue)load(context, "vkGetDeviceQueue"); - table->vkGetEventStatus = (PFN_vkGetEventStatus)load(context, "vkGetEventStatus"); - table->vkGetFenceStatus = (PFN_vkGetFenceStatus)load(context, "vkGetFenceStatus"); - table->vkGetImageMemoryRequirements = (PFN_vkGetImageMemoryRequirements)load(context, "vkGetImageMemoryRequirements"); - table->vkGetImageSparseMemoryRequirements = (PFN_vkGetImageSparseMemoryRequirements)load(context, "vkGetImageSparseMemoryRequirements"); - table->vkGetImageSubresourceLayout = (PFN_vkGetImageSubresourceLayout)load(context, "vkGetImageSubresourceLayout"); - table->vkGetPipelineCacheData = (PFN_vkGetPipelineCacheData)load(context, "vkGetPipelineCacheData"); - table->vkGetQueryPoolResults = (PFN_vkGetQueryPoolResults)load(context, "vkGetQueryPoolResults"); - table->vkGetRenderAreaGranularity = (PFN_vkGetRenderAreaGranularity)load(context, "vkGetRenderAreaGranularity"); - table->vkInvalidateMappedMemoryRanges = (PFN_vkInvalidateMappedMemoryRanges)load(context, "vkInvalidateMappedMemoryRanges"); - table->vkMapMemory = (PFN_vkMapMemory)load(context, "vkMapMemory"); - table->vkMergePipelineCaches = (PFN_vkMergePipelineCaches)load(context, "vkMergePipelineCaches"); - table->vkQueueBindSparse = (PFN_vkQueueBindSparse)load(context, "vkQueueBindSparse"); - table->vkQueueSubmit = (PFN_vkQueueSubmit)load(context, "vkQueueSubmit"); - table->vkQueueWaitIdle = (PFN_vkQueueWaitIdle)load(context, "vkQueueWaitIdle"); - table->vkResetCommandBuffer = (PFN_vkResetCommandBuffer)load(context, "vkResetCommandBuffer"); - table->vkResetCommandPool = (PFN_vkResetCommandPool)load(context, "vkResetCommandPool"); - table->vkResetDescriptorPool = (PFN_vkResetDescriptorPool)load(context, "vkResetDescriptorPool"); - table->vkResetEvent = (PFN_vkResetEvent)load(context, "vkResetEvent"); - table->vkResetFences = (PFN_vkResetFences)load(context, "vkResetFences"); - table->vkSetEvent = (PFN_vkSetEvent)load(context, "vkSetEvent"); - table->vkUnmapMemory = (PFN_vkUnmapMemory)load(context, "vkUnmapMemory"); - table->vkUpdateDescriptorSets = (PFN_vkUpdateDescriptorSets)load(context, "vkUpdateDescriptorSets"); - table->vkWaitForFences = (PFN_vkWaitForFences)load(context, "vkWaitForFences"); -#endif /* defined(VK_VERSION_1_0) */ -#if defined(VK_VERSION_1_1) - table->vkBindBufferMemory2 = (PFN_vkBindBufferMemory2)load(context, "vkBindBufferMemory2"); - table->vkBindImageMemory2 = (PFN_vkBindImageMemory2)load(context, "vkBindImageMemory2"); - table->vkCmdDispatchBase = (PFN_vkCmdDispatchBase)load(context, "vkCmdDispatchBase"); - table->vkCmdSetDeviceMask = (PFN_vkCmdSetDeviceMask)load(context, "vkCmdSetDeviceMask"); - table->vkCreateDescriptorUpdateTemplate = (PFN_vkCreateDescriptorUpdateTemplate)load(context, "vkCreateDescriptorUpdateTemplate"); - table->vkCreateSamplerYcbcrConversion = (PFN_vkCreateSamplerYcbcrConversion)load(context, "vkCreateSamplerYcbcrConversion"); - table->vkDestroyDescriptorUpdateTemplate = (PFN_vkDestroyDescriptorUpdateTemplate)load(context, "vkDestroyDescriptorUpdateTemplate"); - table->vkDestroySamplerYcbcrConversion = (PFN_vkDestroySamplerYcbcrConversion)load(context, "vkDestroySamplerYcbcrConversion"); - table->vkGetBufferMemoryRequirements2 = (PFN_vkGetBufferMemoryRequirements2)load(context, "vkGetBufferMemoryRequirements2"); - table->vkGetDescriptorSetLayoutSupport = (PFN_vkGetDescriptorSetLayoutSupport)load(context, "vkGetDescriptorSetLayoutSupport"); - table->vkGetDeviceGroupPeerMemoryFeatures = (PFN_vkGetDeviceGroupPeerMemoryFeatures)load(context, "vkGetDeviceGroupPeerMemoryFeatures"); - table->vkGetDeviceQueue2 = (PFN_vkGetDeviceQueue2)load(context, "vkGetDeviceQueue2"); - table->vkGetImageMemoryRequirements2 = (PFN_vkGetImageMemoryRequirements2)load(context, "vkGetImageMemoryRequirements2"); - table->vkGetImageSparseMemoryRequirements2 = (PFN_vkGetImageSparseMemoryRequirements2)load(context, "vkGetImageSparseMemoryRequirements2"); - table->vkTrimCommandPool = (PFN_vkTrimCommandPool)load(context, "vkTrimCommandPool"); - table->vkUpdateDescriptorSetWithTemplate = (PFN_vkUpdateDescriptorSetWithTemplate)load(context, "vkUpdateDescriptorSetWithTemplate"); -#endif /* defined(VK_VERSION_1_1) */ -#if defined(VK_VERSION_1_2) - table->vkCmdBeginRenderPass2 = (PFN_vkCmdBeginRenderPass2)load(context, "vkCmdBeginRenderPass2"); - table->vkCmdDrawIndexedIndirectCount = (PFN_vkCmdDrawIndexedIndirectCount)load(context, "vkCmdDrawIndexedIndirectCount"); - table->vkCmdDrawIndirectCount = (PFN_vkCmdDrawIndirectCount)load(context, "vkCmdDrawIndirectCount"); - table->vkCmdEndRenderPass2 = (PFN_vkCmdEndRenderPass2)load(context, "vkCmdEndRenderPass2"); - table->vkCmdNextSubpass2 = (PFN_vkCmdNextSubpass2)load(context, "vkCmdNextSubpass2"); - table->vkCreateRenderPass2 = (PFN_vkCreateRenderPass2)load(context, "vkCreateRenderPass2"); - table->vkGetBufferDeviceAddress = (PFN_vkGetBufferDeviceAddress)load(context, "vkGetBufferDeviceAddress"); - table->vkGetBufferOpaqueCaptureAddress = (PFN_vkGetBufferOpaqueCaptureAddress)load(context, "vkGetBufferOpaqueCaptureAddress"); - table->vkGetDeviceMemoryOpaqueCaptureAddress = (PFN_vkGetDeviceMemoryOpaqueCaptureAddress)load(context, "vkGetDeviceMemoryOpaqueCaptureAddress"); - table->vkGetSemaphoreCounterValue = (PFN_vkGetSemaphoreCounterValue)load(context, "vkGetSemaphoreCounterValue"); - table->vkResetQueryPool = (PFN_vkResetQueryPool)load(context, "vkResetQueryPool"); - table->vkSignalSemaphore = (PFN_vkSignalSemaphore)load(context, "vkSignalSemaphore"); - table->vkWaitSemaphores = (PFN_vkWaitSemaphores)load(context, "vkWaitSemaphores"); -#endif /* defined(VK_VERSION_1_2) */ -#if defined(VK_AMD_buffer_marker) - table->vkCmdWriteBufferMarkerAMD = (PFN_vkCmdWriteBufferMarkerAMD)load(context, "vkCmdWriteBufferMarkerAMD"); -#endif /* defined(VK_AMD_buffer_marker) */ -#if defined(VK_AMD_display_native_hdr) - table->vkSetLocalDimmingAMD = (PFN_vkSetLocalDimmingAMD)load(context, "vkSetLocalDimmingAMD"); -#endif /* defined(VK_AMD_display_native_hdr) */ -#if defined(VK_AMD_draw_indirect_count) - table->vkCmdDrawIndexedIndirectCountAMD = (PFN_vkCmdDrawIndexedIndirectCountAMD)load(context, "vkCmdDrawIndexedIndirectCountAMD"); - table->vkCmdDrawIndirectCountAMD = (PFN_vkCmdDrawIndirectCountAMD)load(context, "vkCmdDrawIndirectCountAMD"); -#endif /* defined(VK_AMD_draw_indirect_count) */ -#if defined(VK_AMD_shader_info) - table->vkGetShaderInfoAMD = (PFN_vkGetShaderInfoAMD)load(context, "vkGetShaderInfoAMD"); -#endif /* defined(VK_AMD_shader_info) */ -#if defined(VK_ANDROID_external_memory_android_hardware_buffer) - table->vkGetAndroidHardwareBufferPropertiesANDROID = (PFN_vkGetAndroidHardwareBufferPropertiesANDROID)load(context, "vkGetAndroidHardwareBufferPropertiesANDROID"); - table->vkGetMemoryAndroidHardwareBufferANDROID = (PFN_vkGetMemoryAndroidHardwareBufferANDROID)load(context, "vkGetMemoryAndroidHardwareBufferANDROID"); -#endif /* defined(VK_ANDROID_external_memory_android_hardware_buffer) */ -#if defined(VK_EXT_buffer_device_address) - table->vkGetBufferDeviceAddressEXT = (PFN_vkGetBufferDeviceAddressEXT)load(context, "vkGetBufferDeviceAddressEXT"); -#endif /* defined(VK_EXT_buffer_device_address) */ -#if defined(VK_EXT_calibrated_timestamps) - table->vkGetCalibratedTimestampsEXT = (PFN_vkGetCalibratedTimestampsEXT)load(context, "vkGetCalibratedTimestampsEXT"); -#endif /* defined(VK_EXT_calibrated_timestamps) */ -#if defined(VK_EXT_color_write_enable) - table->vkCmdSetColorWriteEnableEXT = (PFN_vkCmdSetColorWriteEnableEXT)load(context, "vkCmdSetColorWriteEnableEXT"); -#endif /* defined(VK_EXT_color_write_enable) */ -#if defined(VK_EXT_conditional_rendering) - table->vkCmdBeginConditionalRenderingEXT = (PFN_vkCmdBeginConditionalRenderingEXT)load(context, "vkCmdBeginConditionalRenderingEXT"); - table->vkCmdEndConditionalRenderingEXT = (PFN_vkCmdEndConditionalRenderingEXT)load(context, "vkCmdEndConditionalRenderingEXT"); -#endif /* defined(VK_EXT_conditional_rendering) */ -#if defined(VK_EXT_debug_marker) - table->vkCmdDebugMarkerBeginEXT = (PFN_vkCmdDebugMarkerBeginEXT)load(context, "vkCmdDebugMarkerBeginEXT"); - table->vkCmdDebugMarkerEndEXT = (PFN_vkCmdDebugMarkerEndEXT)load(context, "vkCmdDebugMarkerEndEXT"); - table->vkCmdDebugMarkerInsertEXT = (PFN_vkCmdDebugMarkerInsertEXT)load(context, "vkCmdDebugMarkerInsertEXT"); - table->vkDebugMarkerSetObjectNameEXT = (PFN_vkDebugMarkerSetObjectNameEXT)load(context, "vkDebugMarkerSetObjectNameEXT"); - table->vkDebugMarkerSetObjectTagEXT = (PFN_vkDebugMarkerSetObjectTagEXT)load(context, "vkDebugMarkerSetObjectTagEXT"); -#endif /* defined(VK_EXT_debug_marker) */ -#if defined(VK_EXT_discard_rectangles) - table->vkCmdSetDiscardRectangleEXT = (PFN_vkCmdSetDiscardRectangleEXT)load(context, "vkCmdSetDiscardRectangleEXT"); -#endif /* defined(VK_EXT_discard_rectangles) */ -#if defined(VK_EXT_display_control) - table->vkDisplayPowerControlEXT = (PFN_vkDisplayPowerControlEXT)load(context, "vkDisplayPowerControlEXT"); - table->vkGetSwapchainCounterEXT = (PFN_vkGetSwapchainCounterEXT)load(context, "vkGetSwapchainCounterEXT"); - table->vkRegisterDeviceEventEXT = (PFN_vkRegisterDeviceEventEXT)load(context, "vkRegisterDeviceEventEXT"); - table->vkRegisterDisplayEventEXT = (PFN_vkRegisterDisplayEventEXT)load(context, "vkRegisterDisplayEventEXT"); -#endif /* defined(VK_EXT_display_control) */ -#if defined(VK_EXT_extended_dynamic_state) - table->vkCmdBindVertexBuffers2EXT = (PFN_vkCmdBindVertexBuffers2EXT)load(context, "vkCmdBindVertexBuffers2EXT"); - table->vkCmdSetCullModeEXT = (PFN_vkCmdSetCullModeEXT)load(context, "vkCmdSetCullModeEXT"); - table->vkCmdSetDepthBoundsTestEnableEXT = (PFN_vkCmdSetDepthBoundsTestEnableEXT)load(context, "vkCmdSetDepthBoundsTestEnableEXT"); - table->vkCmdSetDepthCompareOpEXT = (PFN_vkCmdSetDepthCompareOpEXT)load(context, "vkCmdSetDepthCompareOpEXT"); - table->vkCmdSetDepthTestEnableEXT = (PFN_vkCmdSetDepthTestEnableEXT)load(context, "vkCmdSetDepthTestEnableEXT"); - table->vkCmdSetDepthWriteEnableEXT = (PFN_vkCmdSetDepthWriteEnableEXT)load(context, "vkCmdSetDepthWriteEnableEXT"); - table->vkCmdSetFrontFaceEXT = (PFN_vkCmdSetFrontFaceEXT)load(context, "vkCmdSetFrontFaceEXT"); - table->vkCmdSetPrimitiveTopologyEXT = (PFN_vkCmdSetPrimitiveTopologyEXT)load(context, "vkCmdSetPrimitiveTopologyEXT"); - table->vkCmdSetScissorWithCountEXT = (PFN_vkCmdSetScissorWithCountEXT)load(context, "vkCmdSetScissorWithCountEXT"); - table->vkCmdSetStencilOpEXT = (PFN_vkCmdSetStencilOpEXT)load(context, "vkCmdSetStencilOpEXT"); - table->vkCmdSetStencilTestEnableEXT = (PFN_vkCmdSetStencilTestEnableEXT)load(context, "vkCmdSetStencilTestEnableEXT"); - table->vkCmdSetViewportWithCountEXT = (PFN_vkCmdSetViewportWithCountEXT)load(context, "vkCmdSetViewportWithCountEXT"); -#endif /* defined(VK_EXT_extended_dynamic_state) */ -#if defined(VK_EXT_extended_dynamic_state2) - table->vkCmdSetDepthBiasEnableEXT = (PFN_vkCmdSetDepthBiasEnableEXT)load(context, "vkCmdSetDepthBiasEnableEXT"); - table->vkCmdSetLogicOpEXT = (PFN_vkCmdSetLogicOpEXT)load(context, "vkCmdSetLogicOpEXT"); - table->vkCmdSetPatchControlPointsEXT = (PFN_vkCmdSetPatchControlPointsEXT)load(context, "vkCmdSetPatchControlPointsEXT"); - table->vkCmdSetPrimitiveRestartEnableEXT = (PFN_vkCmdSetPrimitiveRestartEnableEXT)load(context, "vkCmdSetPrimitiveRestartEnableEXT"); - table->vkCmdSetRasterizerDiscardEnableEXT = (PFN_vkCmdSetRasterizerDiscardEnableEXT)load(context, "vkCmdSetRasterizerDiscardEnableEXT"); -#endif /* defined(VK_EXT_extended_dynamic_state2) */ -#if defined(VK_EXT_external_memory_host) - table->vkGetMemoryHostPointerPropertiesEXT = (PFN_vkGetMemoryHostPointerPropertiesEXT)load(context, "vkGetMemoryHostPointerPropertiesEXT"); -#endif /* defined(VK_EXT_external_memory_host) */ -#if defined(VK_EXT_full_screen_exclusive) - table->vkAcquireFullScreenExclusiveModeEXT = (PFN_vkAcquireFullScreenExclusiveModeEXT)load(context, "vkAcquireFullScreenExclusiveModeEXT"); - table->vkReleaseFullScreenExclusiveModeEXT = (PFN_vkReleaseFullScreenExclusiveModeEXT)load(context, "vkReleaseFullScreenExclusiveModeEXT"); -#endif /* defined(VK_EXT_full_screen_exclusive) */ -#if defined(VK_EXT_hdr_metadata) - table->vkSetHdrMetadataEXT = (PFN_vkSetHdrMetadataEXT)load(context, "vkSetHdrMetadataEXT"); -#endif /* defined(VK_EXT_hdr_metadata) */ -#if defined(VK_EXT_host_query_reset) - table->vkResetQueryPoolEXT = (PFN_vkResetQueryPoolEXT)load(context, "vkResetQueryPoolEXT"); -#endif /* defined(VK_EXT_host_query_reset) */ -#if defined(VK_EXT_image_drm_format_modifier) - table->vkGetImageDrmFormatModifierPropertiesEXT = (PFN_vkGetImageDrmFormatModifierPropertiesEXT)load(context, "vkGetImageDrmFormatModifierPropertiesEXT"); -#endif /* defined(VK_EXT_image_drm_format_modifier) */ -#if defined(VK_EXT_line_rasterization) - table->vkCmdSetLineStippleEXT = (PFN_vkCmdSetLineStippleEXT)load(context, "vkCmdSetLineStippleEXT"); -#endif /* defined(VK_EXT_line_rasterization) */ -#if defined(VK_EXT_multi_draw) - table->vkCmdDrawMultiEXT = (PFN_vkCmdDrawMultiEXT)load(context, "vkCmdDrawMultiEXT"); - table->vkCmdDrawMultiIndexedEXT = (PFN_vkCmdDrawMultiIndexedEXT)load(context, "vkCmdDrawMultiIndexedEXT"); -#endif /* defined(VK_EXT_multi_draw) */ -#if defined(VK_EXT_pageable_device_local_memory) - table->vkSetDeviceMemoryPriorityEXT = (PFN_vkSetDeviceMemoryPriorityEXT)load(context, "vkSetDeviceMemoryPriorityEXT"); -#endif /* defined(VK_EXT_pageable_device_local_memory) */ -#if defined(VK_EXT_private_data) - table->vkCreatePrivateDataSlotEXT = (PFN_vkCreatePrivateDataSlotEXT)load(context, "vkCreatePrivateDataSlotEXT"); - table->vkDestroyPrivateDataSlotEXT = (PFN_vkDestroyPrivateDataSlotEXT)load(context, "vkDestroyPrivateDataSlotEXT"); - table->vkGetPrivateDataEXT = (PFN_vkGetPrivateDataEXT)load(context, "vkGetPrivateDataEXT"); - table->vkSetPrivateDataEXT = (PFN_vkSetPrivateDataEXT)load(context, "vkSetPrivateDataEXT"); -#endif /* defined(VK_EXT_private_data) */ -#if defined(VK_EXT_sample_locations) - table->vkCmdSetSampleLocationsEXT = (PFN_vkCmdSetSampleLocationsEXT)load(context, "vkCmdSetSampleLocationsEXT"); -#endif /* defined(VK_EXT_sample_locations) */ -#if defined(VK_EXT_transform_feedback) - table->vkCmdBeginQueryIndexedEXT = (PFN_vkCmdBeginQueryIndexedEXT)load(context, "vkCmdBeginQueryIndexedEXT"); - table->vkCmdBeginTransformFeedbackEXT = (PFN_vkCmdBeginTransformFeedbackEXT)load(context, "vkCmdBeginTransformFeedbackEXT"); - table->vkCmdBindTransformFeedbackBuffersEXT = (PFN_vkCmdBindTransformFeedbackBuffersEXT)load(context, "vkCmdBindTransformFeedbackBuffersEXT"); - table->vkCmdDrawIndirectByteCountEXT = (PFN_vkCmdDrawIndirectByteCountEXT)load(context, "vkCmdDrawIndirectByteCountEXT"); - table->vkCmdEndQueryIndexedEXT = (PFN_vkCmdEndQueryIndexedEXT)load(context, "vkCmdEndQueryIndexedEXT"); - table->vkCmdEndTransformFeedbackEXT = (PFN_vkCmdEndTransformFeedbackEXT)load(context, "vkCmdEndTransformFeedbackEXT"); -#endif /* defined(VK_EXT_transform_feedback) */ -#if defined(VK_EXT_validation_cache) - table->vkCreateValidationCacheEXT = (PFN_vkCreateValidationCacheEXT)load(context, "vkCreateValidationCacheEXT"); - table->vkDestroyValidationCacheEXT = (PFN_vkDestroyValidationCacheEXT)load(context, "vkDestroyValidationCacheEXT"); - table->vkGetValidationCacheDataEXT = (PFN_vkGetValidationCacheDataEXT)load(context, "vkGetValidationCacheDataEXT"); - table->vkMergeValidationCachesEXT = (PFN_vkMergeValidationCachesEXT)load(context, "vkMergeValidationCachesEXT"); -#endif /* defined(VK_EXT_validation_cache) */ -#if defined(VK_EXT_vertex_input_dynamic_state) - table->vkCmdSetVertexInputEXT = (PFN_vkCmdSetVertexInputEXT)load(context, "vkCmdSetVertexInputEXT"); -#endif /* defined(VK_EXT_vertex_input_dynamic_state) */ -#if defined(VK_FUCHSIA_buffer_collection) - table->vkCreateBufferCollectionFUCHSIA = (PFN_vkCreateBufferCollectionFUCHSIA)load(context, "vkCreateBufferCollectionFUCHSIA"); - table->vkDestroyBufferCollectionFUCHSIA = (PFN_vkDestroyBufferCollectionFUCHSIA)load(context, "vkDestroyBufferCollectionFUCHSIA"); - table->vkGetBufferCollectionPropertiesFUCHSIA = (PFN_vkGetBufferCollectionPropertiesFUCHSIA)load(context, "vkGetBufferCollectionPropertiesFUCHSIA"); - table->vkSetBufferCollectionBufferConstraintsFUCHSIA = (PFN_vkSetBufferCollectionBufferConstraintsFUCHSIA)load(context, "vkSetBufferCollectionBufferConstraintsFUCHSIA"); - table->vkSetBufferCollectionImageConstraintsFUCHSIA = (PFN_vkSetBufferCollectionImageConstraintsFUCHSIA)load(context, "vkSetBufferCollectionImageConstraintsFUCHSIA"); -#endif /* defined(VK_FUCHSIA_buffer_collection) */ -#if defined(VK_FUCHSIA_external_memory) - table->vkGetMemoryZirconHandleFUCHSIA = (PFN_vkGetMemoryZirconHandleFUCHSIA)load(context, "vkGetMemoryZirconHandleFUCHSIA"); - table->vkGetMemoryZirconHandlePropertiesFUCHSIA = (PFN_vkGetMemoryZirconHandlePropertiesFUCHSIA)load(context, "vkGetMemoryZirconHandlePropertiesFUCHSIA"); -#endif /* defined(VK_FUCHSIA_external_memory) */ -#if defined(VK_FUCHSIA_external_semaphore) - table->vkGetSemaphoreZirconHandleFUCHSIA = (PFN_vkGetSemaphoreZirconHandleFUCHSIA)load(context, "vkGetSemaphoreZirconHandleFUCHSIA"); - table->vkImportSemaphoreZirconHandleFUCHSIA = (PFN_vkImportSemaphoreZirconHandleFUCHSIA)load(context, "vkImportSemaphoreZirconHandleFUCHSIA"); -#endif /* defined(VK_FUCHSIA_external_semaphore) */ -#if defined(VK_GOOGLE_display_timing) - table->vkGetPastPresentationTimingGOOGLE = (PFN_vkGetPastPresentationTimingGOOGLE)load(context, "vkGetPastPresentationTimingGOOGLE"); - table->vkGetRefreshCycleDurationGOOGLE = (PFN_vkGetRefreshCycleDurationGOOGLE)load(context, "vkGetRefreshCycleDurationGOOGLE"); -#endif /* defined(VK_GOOGLE_display_timing) */ -#if defined(VK_HUAWEI_invocation_mask) - table->vkCmdBindInvocationMaskHUAWEI = (PFN_vkCmdBindInvocationMaskHUAWEI)load(context, "vkCmdBindInvocationMaskHUAWEI"); -#endif /* defined(VK_HUAWEI_invocation_mask) */ -#if defined(VK_HUAWEI_subpass_shading) - table->vkCmdSubpassShadingHUAWEI = (PFN_vkCmdSubpassShadingHUAWEI)load(context, "vkCmdSubpassShadingHUAWEI"); - table->vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI = (PFN_vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI)load(context, "vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI"); -#endif /* defined(VK_HUAWEI_subpass_shading) */ -#if defined(VK_INTEL_performance_query) - table->vkAcquirePerformanceConfigurationINTEL = (PFN_vkAcquirePerformanceConfigurationINTEL)load(context, "vkAcquirePerformanceConfigurationINTEL"); - table->vkCmdSetPerformanceMarkerINTEL = (PFN_vkCmdSetPerformanceMarkerINTEL)load(context, "vkCmdSetPerformanceMarkerINTEL"); - table->vkCmdSetPerformanceOverrideINTEL = (PFN_vkCmdSetPerformanceOverrideINTEL)load(context, "vkCmdSetPerformanceOverrideINTEL"); - table->vkCmdSetPerformanceStreamMarkerINTEL = (PFN_vkCmdSetPerformanceStreamMarkerINTEL)load(context, "vkCmdSetPerformanceStreamMarkerINTEL"); - table->vkGetPerformanceParameterINTEL = (PFN_vkGetPerformanceParameterINTEL)load(context, "vkGetPerformanceParameterINTEL"); - table->vkInitializePerformanceApiINTEL = (PFN_vkInitializePerformanceApiINTEL)load(context, "vkInitializePerformanceApiINTEL"); - table->vkQueueSetPerformanceConfigurationINTEL = (PFN_vkQueueSetPerformanceConfigurationINTEL)load(context, "vkQueueSetPerformanceConfigurationINTEL"); - table->vkReleasePerformanceConfigurationINTEL = (PFN_vkReleasePerformanceConfigurationINTEL)load(context, "vkReleasePerformanceConfigurationINTEL"); - table->vkUninitializePerformanceApiINTEL = (PFN_vkUninitializePerformanceApiINTEL)load(context, "vkUninitializePerformanceApiINTEL"); -#endif /* defined(VK_INTEL_performance_query) */ -#if defined(VK_KHR_acceleration_structure) - table->vkBuildAccelerationStructuresKHR = (PFN_vkBuildAccelerationStructuresKHR)load(context, "vkBuildAccelerationStructuresKHR"); - table->vkCmdBuildAccelerationStructuresIndirectKHR = (PFN_vkCmdBuildAccelerationStructuresIndirectKHR)load(context, "vkCmdBuildAccelerationStructuresIndirectKHR"); - table->vkCmdBuildAccelerationStructuresKHR = (PFN_vkCmdBuildAccelerationStructuresKHR)load(context, "vkCmdBuildAccelerationStructuresKHR"); - table->vkCmdCopyAccelerationStructureKHR = (PFN_vkCmdCopyAccelerationStructureKHR)load(context, "vkCmdCopyAccelerationStructureKHR"); - table->vkCmdCopyAccelerationStructureToMemoryKHR = (PFN_vkCmdCopyAccelerationStructureToMemoryKHR)load(context, "vkCmdCopyAccelerationStructureToMemoryKHR"); - table->vkCmdCopyMemoryToAccelerationStructureKHR = (PFN_vkCmdCopyMemoryToAccelerationStructureKHR)load(context, "vkCmdCopyMemoryToAccelerationStructureKHR"); - table->vkCmdWriteAccelerationStructuresPropertiesKHR = (PFN_vkCmdWriteAccelerationStructuresPropertiesKHR)load(context, "vkCmdWriteAccelerationStructuresPropertiesKHR"); - table->vkCopyAccelerationStructureKHR = (PFN_vkCopyAccelerationStructureKHR)load(context, "vkCopyAccelerationStructureKHR"); - table->vkCopyAccelerationStructureToMemoryKHR = (PFN_vkCopyAccelerationStructureToMemoryKHR)load(context, "vkCopyAccelerationStructureToMemoryKHR"); - table->vkCopyMemoryToAccelerationStructureKHR = (PFN_vkCopyMemoryToAccelerationStructureKHR)load(context, "vkCopyMemoryToAccelerationStructureKHR"); - table->vkCreateAccelerationStructureKHR = (PFN_vkCreateAccelerationStructureKHR)load(context, "vkCreateAccelerationStructureKHR"); - table->vkDestroyAccelerationStructureKHR = (PFN_vkDestroyAccelerationStructureKHR)load(context, "vkDestroyAccelerationStructureKHR"); - table->vkGetAccelerationStructureBuildSizesKHR = (PFN_vkGetAccelerationStructureBuildSizesKHR)load(context, "vkGetAccelerationStructureBuildSizesKHR"); - table->vkGetAccelerationStructureDeviceAddressKHR = (PFN_vkGetAccelerationStructureDeviceAddressKHR)load(context, "vkGetAccelerationStructureDeviceAddressKHR"); - table->vkGetDeviceAccelerationStructureCompatibilityKHR = (PFN_vkGetDeviceAccelerationStructureCompatibilityKHR)load(context, "vkGetDeviceAccelerationStructureCompatibilityKHR"); - table->vkWriteAccelerationStructuresPropertiesKHR = (PFN_vkWriteAccelerationStructuresPropertiesKHR)load(context, "vkWriteAccelerationStructuresPropertiesKHR"); -#endif /* defined(VK_KHR_acceleration_structure) */ -#if defined(VK_KHR_bind_memory2) - table->vkBindBufferMemory2KHR = (PFN_vkBindBufferMemory2KHR)load(context, "vkBindBufferMemory2KHR"); - table->vkBindImageMemory2KHR = (PFN_vkBindImageMemory2KHR)load(context, "vkBindImageMemory2KHR"); -#endif /* defined(VK_KHR_bind_memory2) */ -#if defined(VK_KHR_buffer_device_address) - table->vkGetBufferDeviceAddressKHR = (PFN_vkGetBufferDeviceAddressKHR)load(context, "vkGetBufferDeviceAddressKHR"); - table->vkGetBufferOpaqueCaptureAddressKHR = (PFN_vkGetBufferOpaqueCaptureAddressKHR)load(context, "vkGetBufferOpaqueCaptureAddressKHR"); - table->vkGetDeviceMemoryOpaqueCaptureAddressKHR = (PFN_vkGetDeviceMemoryOpaqueCaptureAddressKHR)load(context, "vkGetDeviceMemoryOpaqueCaptureAddressKHR"); -#endif /* defined(VK_KHR_buffer_device_address) */ -#if defined(VK_KHR_copy_commands2) - table->vkCmdBlitImage2KHR = (PFN_vkCmdBlitImage2KHR)load(context, "vkCmdBlitImage2KHR"); - table->vkCmdCopyBuffer2KHR = (PFN_vkCmdCopyBuffer2KHR)load(context, "vkCmdCopyBuffer2KHR"); - table->vkCmdCopyBufferToImage2KHR = (PFN_vkCmdCopyBufferToImage2KHR)load(context, "vkCmdCopyBufferToImage2KHR"); - table->vkCmdCopyImage2KHR = (PFN_vkCmdCopyImage2KHR)load(context, "vkCmdCopyImage2KHR"); - table->vkCmdCopyImageToBuffer2KHR = (PFN_vkCmdCopyImageToBuffer2KHR)load(context, "vkCmdCopyImageToBuffer2KHR"); - table->vkCmdResolveImage2KHR = (PFN_vkCmdResolveImage2KHR)load(context, "vkCmdResolveImage2KHR"); -#endif /* defined(VK_KHR_copy_commands2) */ -#if defined(VK_KHR_create_renderpass2) - table->vkCmdBeginRenderPass2KHR = (PFN_vkCmdBeginRenderPass2KHR)load(context, "vkCmdBeginRenderPass2KHR"); - table->vkCmdEndRenderPass2KHR = (PFN_vkCmdEndRenderPass2KHR)load(context, "vkCmdEndRenderPass2KHR"); - table->vkCmdNextSubpass2KHR = (PFN_vkCmdNextSubpass2KHR)load(context, "vkCmdNextSubpass2KHR"); - table->vkCreateRenderPass2KHR = (PFN_vkCreateRenderPass2KHR)load(context, "vkCreateRenderPass2KHR"); -#endif /* defined(VK_KHR_create_renderpass2) */ -#if defined(VK_KHR_deferred_host_operations) - table->vkCreateDeferredOperationKHR = (PFN_vkCreateDeferredOperationKHR)load(context, "vkCreateDeferredOperationKHR"); - table->vkDeferredOperationJoinKHR = (PFN_vkDeferredOperationJoinKHR)load(context, "vkDeferredOperationJoinKHR"); - table->vkDestroyDeferredOperationKHR = (PFN_vkDestroyDeferredOperationKHR)load(context, "vkDestroyDeferredOperationKHR"); - table->vkGetDeferredOperationMaxConcurrencyKHR = (PFN_vkGetDeferredOperationMaxConcurrencyKHR)load(context, "vkGetDeferredOperationMaxConcurrencyKHR"); - table->vkGetDeferredOperationResultKHR = (PFN_vkGetDeferredOperationResultKHR)load(context, "vkGetDeferredOperationResultKHR"); -#endif /* defined(VK_KHR_deferred_host_operations) */ -#if defined(VK_KHR_descriptor_update_template) - table->vkCreateDescriptorUpdateTemplateKHR = (PFN_vkCreateDescriptorUpdateTemplateKHR)load(context, "vkCreateDescriptorUpdateTemplateKHR"); - table->vkDestroyDescriptorUpdateTemplateKHR = (PFN_vkDestroyDescriptorUpdateTemplateKHR)load(context, "vkDestroyDescriptorUpdateTemplateKHR"); - table->vkUpdateDescriptorSetWithTemplateKHR = (PFN_vkUpdateDescriptorSetWithTemplateKHR)load(context, "vkUpdateDescriptorSetWithTemplateKHR"); -#endif /* defined(VK_KHR_descriptor_update_template) */ -#if defined(VK_KHR_device_group) - table->vkCmdDispatchBaseKHR = (PFN_vkCmdDispatchBaseKHR)load(context, "vkCmdDispatchBaseKHR"); - table->vkCmdSetDeviceMaskKHR = (PFN_vkCmdSetDeviceMaskKHR)load(context, "vkCmdSetDeviceMaskKHR"); - table->vkGetDeviceGroupPeerMemoryFeaturesKHR = (PFN_vkGetDeviceGroupPeerMemoryFeaturesKHR)load(context, "vkGetDeviceGroupPeerMemoryFeaturesKHR"); -#endif /* defined(VK_KHR_device_group) */ -#if defined(VK_KHR_display_swapchain) - table->vkCreateSharedSwapchainsKHR = (PFN_vkCreateSharedSwapchainsKHR)load(context, "vkCreateSharedSwapchainsKHR"); -#endif /* defined(VK_KHR_display_swapchain) */ -#if defined(VK_KHR_draw_indirect_count) - table->vkCmdDrawIndexedIndirectCountKHR = (PFN_vkCmdDrawIndexedIndirectCountKHR)load(context, "vkCmdDrawIndexedIndirectCountKHR"); - table->vkCmdDrawIndirectCountKHR = (PFN_vkCmdDrawIndirectCountKHR)load(context, "vkCmdDrawIndirectCountKHR"); -#endif /* defined(VK_KHR_draw_indirect_count) */ -#if defined(VK_KHR_dynamic_rendering) - table->vkCmdBeginRenderingKHR = (PFN_vkCmdBeginRenderingKHR)load(context, "vkCmdBeginRenderingKHR"); - table->vkCmdEndRenderingKHR = (PFN_vkCmdEndRenderingKHR)load(context, "vkCmdEndRenderingKHR"); -#endif /* defined(VK_KHR_dynamic_rendering) */ -#if defined(VK_KHR_external_fence_fd) - table->vkGetFenceFdKHR = (PFN_vkGetFenceFdKHR)load(context, "vkGetFenceFdKHR"); - table->vkImportFenceFdKHR = (PFN_vkImportFenceFdKHR)load(context, "vkImportFenceFdKHR"); -#endif /* defined(VK_KHR_external_fence_fd) */ -#if defined(VK_KHR_external_fence_win32) - table->vkGetFenceWin32HandleKHR = (PFN_vkGetFenceWin32HandleKHR)load(context, "vkGetFenceWin32HandleKHR"); - table->vkImportFenceWin32HandleKHR = (PFN_vkImportFenceWin32HandleKHR)load(context, "vkImportFenceWin32HandleKHR"); -#endif /* defined(VK_KHR_external_fence_win32) */ -#if defined(VK_KHR_external_memory_fd) - table->vkGetMemoryFdKHR = (PFN_vkGetMemoryFdKHR)load(context, "vkGetMemoryFdKHR"); - table->vkGetMemoryFdPropertiesKHR = (PFN_vkGetMemoryFdPropertiesKHR)load(context, "vkGetMemoryFdPropertiesKHR"); -#endif /* defined(VK_KHR_external_memory_fd) */ -#if defined(VK_KHR_external_memory_win32) - table->vkGetMemoryWin32HandleKHR = (PFN_vkGetMemoryWin32HandleKHR)load(context, "vkGetMemoryWin32HandleKHR"); - table->vkGetMemoryWin32HandlePropertiesKHR = (PFN_vkGetMemoryWin32HandlePropertiesKHR)load(context, "vkGetMemoryWin32HandlePropertiesKHR"); -#endif /* defined(VK_KHR_external_memory_win32) */ -#if defined(VK_KHR_external_semaphore_fd) - table->vkGetSemaphoreFdKHR = (PFN_vkGetSemaphoreFdKHR)load(context, "vkGetSemaphoreFdKHR"); - table->vkImportSemaphoreFdKHR = (PFN_vkImportSemaphoreFdKHR)load(context, "vkImportSemaphoreFdKHR"); -#endif /* defined(VK_KHR_external_semaphore_fd) */ -#if defined(VK_KHR_external_semaphore_win32) - table->vkGetSemaphoreWin32HandleKHR = (PFN_vkGetSemaphoreWin32HandleKHR)load(context, "vkGetSemaphoreWin32HandleKHR"); - table->vkImportSemaphoreWin32HandleKHR = (PFN_vkImportSemaphoreWin32HandleKHR)load(context, "vkImportSemaphoreWin32HandleKHR"); -#endif /* defined(VK_KHR_external_semaphore_win32) */ -#if defined(VK_KHR_fragment_shading_rate) - table->vkCmdSetFragmentShadingRateKHR = (PFN_vkCmdSetFragmentShadingRateKHR)load(context, "vkCmdSetFragmentShadingRateKHR"); -#endif /* defined(VK_KHR_fragment_shading_rate) */ -#if defined(VK_KHR_get_memory_requirements2) - table->vkGetBufferMemoryRequirements2KHR = (PFN_vkGetBufferMemoryRequirements2KHR)load(context, "vkGetBufferMemoryRequirements2KHR"); - table->vkGetImageMemoryRequirements2KHR = (PFN_vkGetImageMemoryRequirements2KHR)load(context, "vkGetImageMemoryRequirements2KHR"); - table->vkGetImageSparseMemoryRequirements2KHR = (PFN_vkGetImageSparseMemoryRequirements2KHR)load(context, "vkGetImageSparseMemoryRequirements2KHR"); -#endif /* defined(VK_KHR_get_memory_requirements2) */ -#if defined(VK_KHR_maintenance1) - table->vkTrimCommandPoolKHR = (PFN_vkTrimCommandPoolKHR)load(context, "vkTrimCommandPoolKHR"); -#endif /* defined(VK_KHR_maintenance1) */ -#if defined(VK_KHR_maintenance3) - table->vkGetDescriptorSetLayoutSupportKHR = (PFN_vkGetDescriptorSetLayoutSupportKHR)load(context, "vkGetDescriptorSetLayoutSupportKHR"); -#endif /* defined(VK_KHR_maintenance3) */ -#if defined(VK_KHR_maintenance4) - table->vkGetDeviceBufferMemoryRequirementsKHR = (PFN_vkGetDeviceBufferMemoryRequirementsKHR)load(context, "vkGetDeviceBufferMemoryRequirementsKHR"); - table->vkGetDeviceImageMemoryRequirementsKHR = (PFN_vkGetDeviceImageMemoryRequirementsKHR)load(context, "vkGetDeviceImageMemoryRequirementsKHR"); - table->vkGetDeviceImageSparseMemoryRequirementsKHR = (PFN_vkGetDeviceImageSparseMemoryRequirementsKHR)load(context, "vkGetDeviceImageSparseMemoryRequirementsKHR"); -#endif /* defined(VK_KHR_maintenance4) */ -#if defined(VK_KHR_performance_query) - table->vkAcquireProfilingLockKHR = (PFN_vkAcquireProfilingLockKHR)load(context, "vkAcquireProfilingLockKHR"); - table->vkReleaseProfilingLockKHR = (PFN_vkReleaseProfilingLockKHR)load(context, "vkReleaseProfilingLockKHR"); -#endif /* defined(VK_KHR_performance_query) */ -#if defined(VK_KHR_pipeline_executable_properties) - table->vkGetPipelineExecutableInternalRepresentationsKHR = (PFN_vkGetPipelineExecutableInternalRepresentationsKHR)load(context, "vkGetPipelineExecutableInternalRepresentationsKHR"); - table->vkGetPipelineExecutablePropertiesKHR = (PFN_vkGetPipelineExecutablePropertiesKHR)load(context, "vkGetPipelineExecutablePropertiesKHR"); - table->vkGetPipelineExecutableStatisticsKHR = (PFN_vkGetPipelineExecutableStatisticsKHR)load(context, "vkGetPipelineExecutableStatisticsKHR"); -#endif /* defined(VK_KHR_pipeline_executable_properties) */ -#if defined(VK_KHR_present_wait) - table->vkWaitForPresentKHR = (PFN_vkWaitForPresentKHR)load(context, "vkWaitForPresentKHR"); -#endif /* defined(VK_KHR_present_wait) */ -#if defined(VK_KHR_push_descriptor) - table->vkCmdPushDescriptorSetKHR = (PFN_vkCmdPushDescriptorSetKHR)load(context, "vkCmdPushDescriptorSetKHR"); -#endif /* defined(VK_KHR_push_descriptor) */ -#if defined(VK_KHR_ray_tracing_pipeline) - table->vkCmdSetRayTracingPipelineStackSizeKHR = (PFN_vkCmdSetRayTracingPipelineStackSizeKHR)load(context, "vkCmdSetRayTracingPipelineStackSizeKHR"); - table->vkCmdTraceRaysIndirectKHR = (PFN_vkCmdTraceRaysIndirectKHR)load(context, "vkCmdTraceRaysIndirectKHR"); - table->vkCmdTraceRaysKHR = (PFN_vkCmdTraceRaysKHR)load(context, "vkCmdTraceRaysKHR"); - table->vkCreateRayTracingPipelinesKHR = (PFN_vkCreateRayTracingPipelinesKHR)load(context, "vkCreateRayTracingPipelinesKHR"); - table->vkGetRayTracingCaptureReplayShaderGroupHandlesKHR = (PFN_vkGetRayTracingCaptureReplayShaderGroupHandlesKHR)load(context, "vkGetRayTracingCaptureReplayShaderGroupHandlesKHR"); - table->vkGetRayTracingShaderGroupHandlesKHR = (PFN_vkGetRayTracingShaderGroupHandlesKHR)load(context, "vkGetRayTracingShaderGroupHandlesKHR"); - table->vkGetRayTracingShaderGroupStackSizeKHR = (PFN_vkGetRayTracingShaderGroupStackSizeKHR)load(context, "vkGetRayTracingShaderGroupStackSizeKHR"); -#endif /* defined(VK_KHR_ray_tracing_pipeline) */ -#if defined(VK_KHR_sampler_ycbcr_conversion) - table->vkCreateSamplerYcbcrConversionKHR = (PFN_vkCreateSamplerYcbcrConversionKHR)load(context, "vkCreateSamplerYcbcrConversionKHR"); - table->vkDestroySamplerYcbcrConversionKHR = (PFN_vkDestroySamplerYcbcrConversionKHR)load(context, "vkDestroySamplerYcbcrConversionKHR"); -#endif /* defined(VK_KHR_sampler_ycbcr_conversion) */ -#if defined(VK_KHR_shared_presentable_image) - table->vkGetSwapchainStatusKHR = (PFN_vkGetSwapchainStatusKHR)load(context, "vkGetSwapchainStatusKHR"); -#endif /* defined(VK_KHR_shared_presentable_image) */ -#if defined(VK_KHR_swapchain) - table->vkAcquireNextImageKHR = (PFN_vkAcquireNextImageKHR)load(context, "vkAcquireNextImageKHR"); - table->vkCreateSwapchainKHR = (PFN_vkCreateSwapchainKHR)load(context, "vkCreateSwapchainKHR"); - table->vkDestroySwapchainKHR = (PFN_vkDestroySwapchainKHR)load(context, "vkDestroySwapchainKHR"); - table->vkGetSwapchainImagesKHR = (PFN_vkGetSwapchainImagesKHR)load(context, "vkGetSwapchainImagesKHR"); - table->vkQueuePresentKHR = (PFN_vkQueuePresentKHR)load(context, "vkQueuePresentKHR"); -#endif /* defined(VK_KHR_swapchain) */ -#if defined(VK_KHR_synchronization2) - table->vkCmdPipelineBarrier2KHR = (PFN_vkCmdPipelineBarrier2KHR)load(context, "vkCmdPipelineBarrier2KHR"); - table->vkCmdResetEvent2KHR = (PFN_vkCmdResetEvent2KHR)load(context, "vkCmdResetEvent2KHR"); - table->vkCmdSetEvent2KHR = (PFN_vkCmdSetEvent2KHR)load(context, "vkCmdSetEvent2KHR"); - table->vkCmdWaitEvents2KHR = (PFN_vkCmdWaitEvents2KHR)load(context, "vkCmdWaitEvents2KHR"); - table->vkCmdWriteTimestamp2KHR = (PFN_vkCmdWriteTimestamp2KHR)load(context, "vkCmdWriteTimestamp2KHR"); - table->vkQueueSubmit2KHR = (PFN_vkQueueSubmit2KHR)load(context, "vkQueueSubmit2KHR"); -#endif /* defined(VK_KHR_synchronization2) */ -#if defined(VK_KHR_synchronization2) && defined(VK_AMD_buffer_marker) - table->vkCmdWriteBufferMarker2AMD = (PFN_vkCmdWriteBufferMarker2AMD)load(context, "vkCmdWriteBufferMarker2AMD"); -#endif /* defined(VK_KHR_synchronization2) && defined(VK_AMD_buffer_marker) */ -#if defined(VK_KHR_synchronization2) && defined(VK_NV_device_diagnostic_checkpoints) - table->vkGetQueueCheckpointData2NV = (PFN_vkGetQueueCheckpointData2NV)load(context, "vkGetQueueCheckpointData2NV"); -#endif /* defined(VK_KHR_synchronization2) && defined(VK_NV_device_diagnostic_checkpoints) */ -#if defined(VK_KHR_timeline_semaphore) - table->vkGetSemaphoreCounterValueKHR = (PFN_vkGetSemaphoreCounterValueKHR)load(context, "vkGetSemaphoreCounterValueKHR"); - table->vkSignalSemaphoreKHR = (PFN_vkSignalSemaphoreKHR)load(context, "vkSignalSemaphoreKHR"); - table->vkWaitSemaphoresKHR = (PFN_vkWaitSemaphoresKHR)load(context, "vkWaitSemaphoresKHR"); -#endif /* defined(VK_KHR_timeline_semaphore) */ -#if defined(VK_KHR_video_decode_queue) - table->vkCmdDecodeVideoKHR = (PFN_vkCmdDecodeVideoKHR)load(context, "vkCmdDecodeVideoKHR"); -#endif /* defined(VK_KHR_video_decode_queue) */ -#if defined(VK_KHR_video_encode_queue) - table->vkCmdEncodeVideoKHR = (PFN_vkCmdEncodeVideoKHR)load(context, "vkCmdEncodeVideoKHR"); -#endif /* defined(VK_KHR_video_encode_queue) */ -#if defined(VK_KHR_video_queue) - table->vkBindVideoSessionMemoryKHR = (PFN_vkBindVideoSessionMemoryKHR)load(context, "vkBindVideoSessionMemoryKHR"); - table->vkCmdBeginVideoCodingKHR = (PFN_vkCmdBeginVideoCodingKHR)load(context, "vkCmdBeginVideoCodingKHR"); - table->vkCmdControlVideoCodingKHR = (PFN_vkCmdControlVideoCodingKHR)load(context, "vkCmdControlVideoCodingKHR"); - table->vkCmdEndVideoCodingKHR = (PFN_vkCmdEndVideoCodingKHR)load(context, "vkCmdEndVideoCodingKHR"); - table->vkCreateVideoSessionKHR = (PFN_vkCreateVideoSessionKHR)load(context, "vkCreateVideoSessionKHR"); - table->vkCreateVideoSessionParametersKHR = (PFN_vkCreateVideoSessionParametersKHR)load(context, "vkCreateVideoSessionParametersKHR"); - table->vkDestroyVideoSessionKHR = (PFN_vkDestroyVideoSessionKHR)load(context, "vkDestroyVideoSessionKHR"); - table->vkDestroyVideoSessionParametersKHR = (PFN_vkDestroyVideoSessionParametersKHR)load(context, "vkDestroyVideoSessionParametersKHR"); - table->vkGetVideoSessionMemoryRequirementsKHR = (PFN_vkGetVideoSessionMemoryRequirementsKHR)load(context, "vkGetVideoSessionMemoryRequirementsKHR"); - table->vkUpdateVideoSessionParametersKHR = (PFN_vkUpdateVideoSessionParametersKHR)load(context, "vkUpdateVideoSessionParametersKHR"); -#endif /* defined(VK_KHR_video_queue) */ -#if defined(VK_NVX_binary_import) - table->vkCmdCuLaunchKernelNVX = (PFN_vkCmdCuLaunchKernelNVX)load(context, "vkCmdCuLaunchKernelNVX"); - table->vkCreateCuFunctionNVX = (PFN_vkCreateCuFunctionNVX)load(context, "vkCreateCuFunctionNVX"); - table->vkCreateCuModuleNVX = (PFN_vkCreateCuModuleNVX)load(context, "vkCreateCuModuleNVX"); - table->vkDestroyCuFunctionNVX = (PFN_vkDestroyCuFunctionNVX)load(context, "vkDestroyCuFunctionNVX"); - table->vkDestroyCuModuleNVX = (PFN_vkDestroyCuModuleNVX)load(context, "vkDestroyCuModuleNVX"); -#endif /* defined(VK_NVX_binary_import) */ -#if defined(VK_NVX_image_view_handle) - table->vkGetImageViewAddressNVX = (PFN_vkGetImageViewAddressNVX)load(context, "vkGetImageViewAddressNVX"); - table->vkGetImageViewHandleNVX = (PFN_vkGetImageViewHandleNVX)load(context, "vkGetImageViewHandleNVX"); -#endif /* defined(VK_NVX_image_view_handle) */ -#if defined(VK_NV_clip_space_w_scaling) - table->vkCmdSetViewportWScalingNV = (PFN_vkCmdSetViewportWScalingNV)load(context, "vkCmdSetViewportWScalingNV"); -#endif /* defined(VK_NV_clip_space_w_scaling) */ -#if defined(VK_NV_device_diagnostic_checkpoints) - table->vkCmdSetCheckpointNV = (PFN_vkCmdSetCheckpointNV)load(context, "vkCmdSetCheckpointNV"); - table->vkGetQueueCheckpointDataNV = (PFN_vkGetQueueCheckpointDataNV)load(context, "vkGetQueueCheckpointDataNV"); -#endif /* defined(VK_NV_device_diagnostic_checkpoints) */ -#if defined(VK_NV_device_generated_commands) - table->vkCmdBindPipelineShaderGroupNV = (PFN_vkCmdBindPipelineShaderGroupNV)load(context, "vkCmdBindPipelineShaderGroupNV"); - table->vkCmdExecuteGeneratedCommandsNV = (PFN_vkCmdExecuteGeneratedCommandsNV)load(context, "vkCmdExecuteGeneratedCommandsNV"); - table->vkCmdPreprocessGeneratedCommandsNV = (PFN_vkCmdPreprocessGeneratedCommandsNV)load(context, "vkCmdPreprocessGeneratedCommandsNV"); - table->vkCreateIndirectCommandsLayoutNV = (PFN_vkCreateIndirectCommandsLayoutNV)load(context, "vkCreateIndirectCommandsLayoutNV"); - table->vkDestroyIndirectCommandsLayoutNV = (PFN_vkDestroyIndirectCommandsLayoutNV)load(context, "vkDestroyIndirectCommandsLayoutNV"); - table->vkGetGeneratedCommandsMemoryRequirementsNV = (PFN_vkGetGeneratedCommandsMemoryRequirementsNV)load(context, "vkGetGeneratedCommandsMemoryRequirementsNV"); -#endif /* defined(VK_NV_device_generated_commands) */ -#if defined(VK_NV_external_memory_rdma) - table->vkGetMemoryRemoteAddressNV = (PFN_vkGetMemoryRemoteAddressNV)load(context, "vkGetMemoryRemoteAddressNV"); -#endif /* defined(VK_NV_external_memory_rdma) */ -#if defined(VK_NV_external_memory_win32) - table->vkGetMemoryWin32HandleNV = (PFN_vkGetMemoryWin32HandleNV)load(context, "vkGetMemoryWin32HandleNV"); -#endif /* defined(VK_NV_external_memory_win32) */ -#if defined(VK_NV_fragment_shading_rate_enums) - table->vkCmdSetFragmentShadingRateEnumNV = (PFN_vkCmdSetFragmentShadingRateEnumNV)load(context, "vkCmdSetFragmentShadingRateEnumNV"); -#endif /* defined(VK_NV_fragment_shading_rate_enums) */ -#if defined(VK_NV_mesh_shader) - table->vkCmdDrawMeshTasksIndirectCountNV = (PFN_vkCmdDrawMeshTasksIndirectCountNV)load(context, "vkCmdDrawMeshTasksIndirectCountNV"); - table->vkCmdDrawMeshTasksIndirectNV = (PFN_vkCmdDrawMeshTasksIndirectNV)load(context, "vkCmdDrawMeshTasksIndirectNV"); - table->vkCmdDrawMeshTasksNV = (PFN_vkCmdDrawMeshTasksNV)load(context, "vkCmdDrawMeshTasksNV"); -#endif /* defined(VK_NV_mesh_shader) */ -#if defined(VK_NV_ray_tracing) - table->vkBindAccelerationStructureMemoryNV = (PFN_vkBindAccelerationStructureMemoryNV)load(context, "vkBindAccelerationStructureMemoryNV"); - table->vkCmdBuildAccelerationStructureNV = (PFN_vkCmdBuildAccelerationStructureNV)load(context, "vkCmdBuildAccelerationStructureNV"); - table->vkCmdCopyAccelerationStructureNV = (PFN_vkCmdCopyAccelerationStructureNV)load(context, "vkCmdCopyAccelerationStructureNV"); - table->vkCmdTraceRaysNV = (PFN_vkCmdTraceRaysNV)load(context, "vkCmdTraceRaysNV"); - table->vkCmdWriteAccelerationStructuresPropertiesNV = (PFN_vkCmdWriteAccelerationStructuresPropertiesNV)load(context, "vkCmdWriteAccelerationStructuresPropertiesNV"); - table->vkCompileDeferredNV = (PFN_vkCompileDeferredNV)load(context, "vkCompileDeferredNV"); - table->vkCreateAccelerationStructureNV = (PFN_vkCreateAccelerationStructureNV)load(context, "vkCreateAccelerationStructureNV"); - table->vkCreateRayTracingPipelinesNV = (PFN_vkCreateRayTracingPipelinesNV)load(context, "vkCreateRayTracingPipelinesNV"); - table->vkDestroyAccelerationStructureNV = (PFN_vkDestroyAccelerationStructureNV)load(context, "vkDestroyAccelerationStructureNV"); - table->vkGetAccelerationStructureHandleNV = (PFN_vkGetAccelerationStructureHandleNV)load(context, "vkGetAccelerationStructureHandleNV"); - table->vkGetAccelerationStructureMemoryRequirementsNV = (PFN_vkGetAccelerationStructureMemoryRequirementsNV)load(context, "vkGetAccelerationStructureMemoryRequirementsNV"); - table->vkGetRayTracingShaderGroupHandlesNV = (PFN_vkGetRayTracingShaderGroupHandlesNV)load(context, "vkGetRayTracingShaderGroupHandlesNV"); -#endif /* defined(VK_NV_ray_tracing) */ -#if defined(VK_NV_scissor_exclusive) - table->vkCmdSetExclusiveScissorNV = (PFN_vkCmdSetExclusiveScissorNV)load(context, "vkCmdSetExclusiveScissorNV"); -#endif /* defined(VK_NV_scissor_exclusive) */ -#if defined(VK_NV_shading_rate_image) - table->vkCmdBindShadingRateImageNV = (PFN_vkCmdBindShadingRateImageNV)load(context, "vkCmdBindShadingRateImageNV"); - table->vkCmdSetCoarseSampleOrderNV = (PFN_vkCmdSetCoarseSampleOrderNV)load(context, "vkCmdSetCoarseSampleOrderNV"); - table->vkCmdSetViewportShadingRatePaletteNV = (PFN_vkCmdSetViewportShadingRatePaletteNV)load(context, "vkCmdSetViewportShadingRatePaletteNV"); -#endif /* defined(VK_NV_shading_rate_image) */ -#if (defined(VK_EXT_full_screen_exclusive) && defined(VK_KHR_device_group)) || (defined(VK_EXT_full_screen_exclusive) && defined(VK_VERSION_1_1)) - table->vkGetDeviceGroupSurfacePresentModes2EXT = (PFN_vkGetDeviceGroupSurfacePresentModes2EXT)load(context, "vkGetDeviceGroupSurfacePresentModes2EXT"); -#endif /* (defined(VK_EXT_full_screen_exclusive) && defined(VK_KHR_device_group)) || (defined(VK_EXT_full_screen_exclusive) && defined(VK_VERSION_1_1)) */ -#if (defined(VK_KHR_descriptor_update_template) && defined(VK_KHR_push_descriptor)) || (defined(VK_KHR_push_descriptor) && defined(VK_VERSION_1_1)) || (defined(VK_KHR_push_descriptor) && defined(VK_KHR_descriptor_update_template)) - table->vkCmdPushDescriptorSetWithTemplateKHR = (PFN_vkCmdPushDescriptorSetWithTemplateKHR)load(context, "vkCmdPushDescriptorSetWithTemplateKHR"); -#endif /* (defined(VK_KHR_descriptor_update_template) && defined(VK_KHR_push_descriptor)) || (defined(VK_KHR_push_descriptor) && defined(VK_VERSION_1_1)) || (defined(VK_KHR_push_descriptor) && defined(VK_KHR_descriptor_update_template)) */ -#if (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) - table->vkGetDeviceGroupPresentCapabilitiesKHR = (PFN_vkGetDeviceGroupPresentCapabilitiesKHR)load(context, "vkGetDeviceGroupPresentCapabilitiesKHR"); - table->vkGetDeviceGroupSurfacePresentModesKHR = (PFN_vkGetDeviceGroupSurfacePresentModesKHR)load(context, "vkGetDeviceGroupSurfacePresentModesKHR"); -#endif /* (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) */ -#if (defined(VK_KHR_device_group) && defined(VK_KHR_swapchain)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) - table->vkAcquireNextImage2KHR = (PFN_vkAcquireNextImage2KHR)load(context, "vkAcquireNextImage2KHR"); -#endif /* (defined(VK_KHR_device_group) && defined(VK_KHR_swapchain)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) */ - /* VOLK_GENERATE_LOAD_DEVICE_TABLE */ -} - -#ifdef __GNUC__ -#ifdef VOLK_DEFAULT_VISIBILITY -# pragma GCC visibility push(default) -#else -# pragma GCC visibility push(hidden) -#endif -#endif - -/* VOLK_GENERATE_PROTOTYPES_C */ -#if defined(VK_VERSION_1_0) -PFN_vkAllocateCommandBuffers vkAllocateCommandBuffers; -PFN_vkAllocateDescriptorSets vkAllocateDescriptorSets; -PFN_vkAllocateMemory vkAllocateMemory; -PFN_vkBeginCommandBuffer vkBeginCommandBuffer; -PFN_vkBindBufferMemory vkBindBufferMemory; -PFN_vkBindImageMemory vkBindImageMemory; -PFN_vkCmdBeginQuery vkCmdBeginQuery; -PFN_vkCmdBeginRenderPass vkCmdBeginRenderPass; -PFN_vkCmdBindDescriptorSets vkCmdBindDescriptorSets; -PFN_vkCmdBindIndexBuffer vkCmdBindIndexBuffer; -PFN_vkCmdBindPipeline vkCmdBindPipeline; -PFN_vkCmdBindVertexBuffers vkCmdBindVertexBuffers; -PFN_vkCmdBlitImage vkCmdBlitImage; -PFN_vkCmdClearAttachments vkCmdClearAttachments; -PFN_vkCmdClearColorImage vkCmdClearColorImage; -PFN_vkCmdClearDepthStencilImage vkCmdClearDepthStencilImage; -PFN_vkCmdCopyBuffer vkCmdCopyBuffer; -PFN_vkCmdCopyBufferToImage vkCmdCopyBufferToImage; -PFN_vkCmdCopyImage vkCmdCopyImage; -PFN_vkCmdCopyImageToBuffer vkCmdCopyImageToBuffer; -PFN_vkCmdCopyQueryPoolResults vkCmdCopyQueryPoolResults; -PFN_vkCmdDispatch vkCmdDispatch; -PFN_vkCmdDispatchIndirect vkCmdDispatchIndirect; -PFN_vkCmdDraw vkCmdDraw; -PFN_vkCmdDrawIndexed vkCmdDrawIndexed; -PFN_vkCmdDrawIndexedIndirect vkCmdDrawIndexedIndirect; -PFN_vkCmdDrawIndirect vkCmdDrawIndirect; -PFN_vkCmdEndQuery vkCmdEndQuery; -PFN_vkCmdEndRenderPass vkCmdEndRenderPass; -PFN_vkCmdExecuteCommands vkCmdExecuteCommands; -PFN_vkCmdFillBuffer vkCmdFillBuffer; -PFN_vkCmdNextSubpass vkCmdNextSubpass; -PFN_vkCmdPipelineBarrier vkCmdPipelineBarrier; -PFN_vkCmdPushConstants vkCmdPushConstants; -PFN_vkCmdResetEvent vkCmdResetEvent; -PFN_vkCmdResetQueryPool vkCmdResetQueryPool; -PFN_vkCmdResolveImage vkCmdResolveImage; -PFN_vkCmdSetBlendConstants vkCmdSetBlendConstants; -PFN_vkCmdSetDepthBias vkCmdSetDepthBias; -PFN_vkCmdSetDepthBounds vkCmdSetDepthBounds; -PFN_vkCmdSetEvent vkCmdSetEvent; -PFN_vkCmdSetLineWidth vkCmdSetLineWidth; -PFN_vkCmdSetScissor vkCmdSetScissor; -PFN_vkCmdSetStencilCompareMask vkCmdSetStencilCompareMask; -PFN_vkCmdSetStencilReference vkCmdSetStencilReference; -PFN_vkCmdSetStencilWriteMask vkCmdSetStencilWriteMask; -PFN_vkCmdSetViewport vkCmdSetViewport; -PFN_vkCmdUpdateBuffer vkCmdUpdateBuffer; -PFN_vkCmdWaitEvents vkCmdWaitEvents; -PFN_vkCmdWriteTimestamp vkCmdWriteTimestamp; -PFN_vkCreateBuffer vkCreateBuffer; -PFN_vkCreateBufferView vkCreateBufferView; -PFN_vkCreateCommandPool vkCreateCommandPool; -PFN_vkCreateComputePipelines vkCreateComputePipelines; -PFN_vkCreateDescriptorPool vkCreateDescriptorPool; -PFN_vkCreateDescriptorSetLayout vkCreateDescriptorSetLayout; -PFN_vkCreateDevice vkCreateDevice; -PFN_vkCreateEvent vkCreateEvent; -PFN_vkCreateFence vkCreateFence; -PFN_vkCreateFramebuffer vkCreateFramebuffer; -PFN_vkCreateGraphicsPipelines vkCreateGraphicsPipelines; -PFN_vkCreateImage vkCreateImage; -PFN_vkCreateImageView vkCreateImageView; -PFN_vkCreateInstance vkCreateInstance; -PFN_vkCreatePipelineCache vkCreatePipelineCache; -PFN_vkCreatePipelineLayout vkCreatePipelineLayout; -PFN_vkCreateQueryPool vkCreateQueryPool; -PFN_vkCreateRenderPass vkCreateRenderPass; -PFN_vkCreateSampler vkCreateSampler; -PFN_vkCreateSemaphore vkCreateSemaphore; -PFN_vkCreateShaderModule vkCreateShaderModule; -PFN_vkDestroyBuffer vkDestroyBuffer; -PFN_vkDestroyBufferView vkDestroyBufferView; -PFN_vkDestroyCommandPool vkDestroyCommandPool; -PFN_vkDestroyDescriptorPool vkDestroyDescriptorPool; -PFN_vkDestroyDescriptorSetLayout vkDestroyDescriptorSetLayout; -PFN_vkDestroyDevice vkDestroyDevice; -PFN_vkDestroyEvent vkDestroyEvent; -PFN_vkDestroyFence vkDestroyFence; -PFN_vkDestroyFramebuffer vkDestroyFramebuffer; -PFN_vkDestroyImage vkDestroyImage; -PFN_vkDestroyImageView vkDestroyImageView; -PFN_vkDestroyInstance vkDestroyInstance; -PFN_vkDestroyPipeline vkDestroyPipeline; -PFN_vkDestroyPipelineCache vkDestroyPipelineCache; -PFN_vkDestroyPipelineLayout vkDestroyPipelineLayout; -PFN_vkDestroyQueryPool vkDestroyQueryPool; -PFN_vkDestroyRenderPass vkDestroyRenderPass; -PFN_vkDestroySampler vkDestroySampler; -PFN_vkDestroySemaphore vkDestroySemaphore; -PFN_vkDestroyShaderModule vkDestroyShaderModule; -PFN_vkDeviceWaitIdle vkDeviceWaitIdle; -PFN_vkEndCommandBuffer vkEndCommandBuffer; -PFN_vkEnumerateDeviceExtensionProperties vkEnumerateDeviceExtensionProperties; -PFN_vkEnumerateDeviceLayerProperties vkEnumerateDeviceLayerProperties; -PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties; -PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties; -PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices; -PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges; -PFN_vkFreeCommandBuffers vkFreeCommandBuffers; -PFN_vkFreeDescriptorSets vkFreeDescriptorSets; -PFN_vkFreeMemory vkFreeMemory; -PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements; -PFN_vkGetDeviceMemoryCommitment vkGetDeviceMemoryCommitment; -PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr; -PFN_vkGetDeviceQueue vkGetDeviceQueue; -PFN_vkGetEventStatus vkGetEventStatus; -PFN_vkGetFenceStatus vkGetFenceStatus; -PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements; -PFN_vkGetImageSparseMemoryRequirements vkGetImageSparseMemoryRequirements; -PFN_vkGetImageSubresourceLayout vkGetImageSubresourceLayout; -PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr; -PFN_vkGetPhysicalDeviceFeatures vkGetPhysicalDeviceFeatures; -PFN_vkGetPhysicalDeviceFormatProperties vkGetPhysicalDeviceFormatProperties; -PFN_vkGetPhysicalDeviceImageFormatProperties vkGetPhysicalDeviceImageFormatProperties; -PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties; -PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties; -PFN_vkGetPhysicalDeviceQueueFamilyProperties vkGetPhysicalDeviceQueueFamilyProperties; -PFN_vkGetPhysicalDeviceSparseImageFormatProperties vkGetPhysicalDeviceSparseImageFormatProperties; -PFN_vkGetPipelineCacheData vkGetPipelineCacheData; -PFN_vkGetQueryPoolResults vkGetQueryPoolResults; -PFN_vkGetRenderAreaGranularity vkGetRenderAreaGranularity; -PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges; -PFN_vkMapMemory vkMapMemory; -PFN_vkMergePipelineCaches vkMergePipelineCaches; -PFN_vkQueueBindSparse vkQueueBindSparse; -PFN_vkQueueSubmit vkQueueSubmit; -PFN_vkQueueWaitIdle vkQueueWaitIdle; -PFN_vkResetCommandBuffer vkResetCommandBuffer; -PFN_vkResetCommandPool vkResetCommandPool; -PFN_vkResetDescriptorPool vkResetDescriptorPool; -PFN_vkResetEvent vkResetEvent; -PFN_vkResetFences vkResetFences; -PFN_vkSetEvent vkSetEvent; -PFN_vkUnmapMemory vkUnmapMemory; -PFN_vkUpdateDescriptorSets vkUpdateDescriptorSets; -PFN_vkWaitForFences vkWaitForFences; -#endif /* defined(VK_VERSION_1_0) */ -#if defined(VK_VERSION_1_1) -PFN_vkBindBufferMemory2 vkBindBufferMemory2; -PFN_vkBindImageMemory2 vkBindImageMemory2; -PFN_vkCmdDispatchBase vkCmdDispatchBase; -PFN_vkCmdSetDeviceMask vkCmdSetDeviceMask; -PFN_vkCreateDescriptorUpdateTemplate vkCreateDescriptorUpdateTemplate; -PFN_vkCreateSamplerYcbcrConversion vkCreateSamplerYcbcrConversion; -PFN_vkDestroyDescriptorUpdateTemplate vkDestroyDescriptorUpdateTemplate; -PFN_vkDestroySamplerYcbcrConversion vkDestroySamplerYcbcrConversion; -PFN_vkEnumerateInstanceVersion vkEnumerateInstanceVersion; -PFN_vkEnumeratePhysicalDeviceGroups vkEnumeratePhysicalDeviceGroups; -PFN_vkGetBufferMemoryRequirements2 vkGetBufferMemoryRequirements2; -PFN_vkGetDescriptorSetLayoutSupport vkGetDescriptorSetLayoutSupport; -PFN_vkGetDeviceGroupPeerMemoryFeatures vkGetDeviceGroupPeerMemoryFeatures; -PFN_vkGetDeviceQueue2 vkGetDeviceQueue2; -PFN_vkGetImageMemoryRequirements2 vkGetImageMemoryRequirements2; -PFN_vkGetImageSparseMemoryRequirements2 vkGetImageSparseMemoryRequirements2; -PFN_vkGetPhysicalDeviceExternalBufferProperties vkGetPhysicalDeviceExternalBufferProperties; -PFN_vkGetPhysicalDeviceExternalFenceProperties vkGetPhysicalDeviceExternalFenceProperties; -PFN_vkGetPhysicalDeviceExternalSemaphoreProperties vkGetPhysicalDeviceExternalSemaphoreProperties; -PFN_vkGetPhysicalDeviceFeatures2 vkGetPhysicalDeviceFeatures2; -PFN_vkGetPhysicalDeviceFormatProperties2 vkGetPhysicalDeviceFormatProperties2; -PFN_vkGetPhysicalDeviceImageFormatProperties2 vkGetPhysicalDeviceImageFormatProperties2; -PFN_vkGetPhysicalDeviceMemoryProperties2 vkGetPhysicalDeviceMemoryProperties2; -PFN_vkGetPhysicalDeviceProperties2 vkGetPhysicalDeviceProperties2; -PFN_vkGetPhysicalDeviceQueueFamilyProperties2 vkGetPhysicalDeviceQueueFamilyProperties2; -PFN_vkGetPhysicalDeviceSparseImageFormatProperties2 vkGetPhysicalDeviceSparseImageFormatProperties2; -PFN_vkTrimCommandPool vkTrimCommandPool; -PFN_vkUpdateDescriptorSetWithTemplate vkUpdateDescriptorSetWithTemplate; -#endif /* defined(VK_VERSION_1_1) */ -#if defined(VK_VERSION_1_2) -PFN_vkCmdBeginRenderPass2 vkCmdBeginRenderPass2; -PFN_vkCmdDrawIndexedIndirectCount vkCmdDrawIndexedIndirectCount; -PFN_vkCmdDrawIndirectCount vkCmdDrawIndirectCount; -PFN_vkCmdEndRenderPass2 vkCmdEndRenderPass2; -PFN_vkCmdNextSubpass2 vkCmdNextSubpass2; -PFN_vkCreateRenderPass2 vkCreateRenderPass2; -PFN_vkGetBufferDeviceAddress vkGetBufferDeviceAddress; -PFN_vkGetBufferOpaqueCaptureAddress vkGetBufferOpaqueCaptureAddress; -PFN_vkGetDeviceMemoryOpaqueCaptureAddress vkGetDeviceMemoryOpaqueCaptureAddress; -PFN_vkGetSemaphoreCounterValue vkGetSemaphoreCounterValue; -PFN_vkResetQueryPool vkResetQueryPool; -PFN_vkSignalSemaphore vkSignalSemaphore; -PFN_vkWaitSemaphores vkWaitSemaphores; -#endif /* defined(VK_VERSION_1_2) */ -#if defined(VK_AMD_buffer_marker) -PFN_vkCmdWriteBufferMarkerAMD vkCmdWriteBufferMarkerAMD; -#endif /* defined(VK_AMD_buffer_marker) */ -#if defined(VK_AMD_display_native_hdr) -PFN_vkSetLocalDimmingAMD vkSetLocalDimmingAMD; -#endif /* defined(VK_AMD_display_native_hdr) */ -#if defined(VK_AMD_draw_indirect_count) -PFN_vkCmdDrawIndexedIndirectCountAMD vkCmdDrawIndexedIndirectCountAMD; -PFN_vkCmdDrawIndirectCountAMD vkCmdDrawIndirectCountAMD; -#endif /* defined(VK_AMD_draw_indirect_count) */ -#if defined(VK_AMD_shader_info) -PFN_vkGetShaderInfoAMD vkGetShaderInfoAMD; -#endif /* defined(VK_AMD_shader_info) */ -#if defined(VK_ANDROID_external_memory_android_hardware_buffer) -PFN_vkGetAndroidHardwareBufferPropertiesANDROID vkGetAndroidHardwareBufferPropertiesANDROID; -PFN_vkGetMemoryAndroidHardwareBufferANDROID vkGetMemoryAndroidHardwareBufferANDROID; -#endif /* defined(VK_ANDROID_external_memory_android_hardware_buffer) */ -#if defined(VK_EXT_acquire_drm_display) -PFN_vkAcquireDrmDisplayEXT vkAcquireDrmDisplayEXT; -PFN_vkGetDrmDisplayEXT vkGetDrmDisplayEXT; -#endif /* defined(VK_EXT_acquire_drm_display) */ -#if defined(VK_EXT_acquire_xlib_display) -PFN_vkAcquireXlibDisplayEXT vkAcquireXlibDisplayEXT; -PFN_vkGetRandROutputDisplayEXT vkGetRandROutputDisplayEXT; -#endif /* defined(VK_EXT_acquire_xlib_display) */ -#if defined(VK_EXT_buffer_device_address) -PFN_vkGetBufferDeviceAddressEXT vkGetBufferDeviceAddressEXT; -#endif /* defined(VK_EXT_buffer_device_address) */ -#if defined(VK_EXT_calibrated_timestamps) -PFN_vkGetCalibratedTimestampsEXT vkGetCalibratedTimestampsEXT; -PFN_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT vkGetPhysicalDeviceCalibrateableTimeDomainsEXT; -#endif /* defined(VK_EXT_calibrated_timestamps) */ -#if defined(VK_EXT_color_write_enable) -PFN_vkCmdSetColorWriteEnableEXT vkCmdSetColorWriteEnableEXT; -#endif /* defined(VK_EXT_color_write_enable) */ -#if defined(VK_EXT_conditional_rendering) -PFN_vkCmdBeginConditionalRenderingEXT vkCmdBeginConditionalRenderingEXT; -PFN_vkCmdEndConditionalRenderingEXT vkCmdEndConditionalRenderingEXT; -#endif /* defined(VK_EXT_conditional_rendering) */ -#if defined(VK_EXT_debug_marker) -PFN_vkCmdDebugMarkerBeginEXT vkCmdDebugMarkerBeginEXT; -PFN_vkCmdDebugMarkerEndEXT vkCmdDebugMarkerEndEXT; -PFN_vkCmdDebugMarkerInsertEXT vkCmdDebugMarkerInsertEXT; -PFN_vkDebugMarkerSetObjectNameEXT vkDebugMarkerSetObjectNameEXT; -PFN_vkDebugMarkerSetObjectTagEXT vkDebugMarkerSetObjectTagEXT; -#endif /* defined(VK_EXT_debug_marker) */ -#if defined(VK_EXT_debug_report) -PFN_vkCreateDebugReportCallbackEXT vkCreateDebugReportCallbackEXT; -PFN_vkDebugReportMessageEXT vkDebugReportMessageEXT; -PFN_vkDestroyDebugReportCallbackEXT vkDestroyDebugReportCallbackEXT; -#endif /* defined(VK_EXT_debug_report) */ -#if defined(VK_EXT_debug_utils) -PFN_vkCmdBeginDebugUtilsLabelEXT vkCmdBeginDebugUtilsLabelEXT; -PFN_vkCmdEndDebugUtilsLabelEXT vkCmdEndDebugUtilsLabelEXT; -PFN_vkCmdInsertDebugUtilsLabelEXT vkCmdInsertDebugUtilsLabelEXT; -PFN_vkCreateDebugUtilsMessengerEXT vkCreateDebugUtilsMessengerEXT; -PFN_vkDestroyDebugUtilsMessengerEXT vkDestroyDebugUtilsMessengerEXT; -PFN_vkQueueBeginDebugUtilsLabelEXT vkQueueBeginDebugUtilsLabelEXT; -PFN_vkQueueEndDebugUtilsLabelEXT vkQueueEndDebugUtilsLabelEXT; -PFN_vkQueueInsertDebugUtilsLabelEXT vkQueueInsertDebugUtilsLabelEXT; -PFN_vkSetDebugUtilsObjectNameEXT vkSetDebugUtilsObjectNameEXT; -PFN_vkSetDebugUtilsObjectTagEXT vkSetDebugUtilsObjectTagEXT; -PFN_vkSubmitDebugUtilsMessageEXT vkSubmitDebugUtilsMessageEXT; -#endif /* defined(VK_EXT_debug_utils) */ -#if defined(VK_EXT_direct_mode_display) -PFN_vkReleaseDisplayEXT vkReleaseDisplayEXT; -#endif /* defined(VK_EXT_direct_mode_display) */ -#if defined(VK_EXT_directfb_surface) -PFN_vkCreateDirectFBSurfaceEXT vkCreateDirectFBSurfaceEXT; -PFN_vkGetPhysicalDeviceDirectFBPresentationSupportEXT vkGetPhysicalDeviceDirectFBPresentationSupportEXT; -#endif /* defined(VK_EXT_directfb_surface) */ -#if defined(VK_EXT_discard_rectangles) -PFN_vkCmdSetDiscardRectangleEXT vkCmdSetDiscardRectangleEXT; -#endif /* defined(VK_EXT_discard_rectangles) */ -#if defined(VK_EXT_display_control) -PFN_vkDisplayPowerControlEXT vkDisplayPowerControlEXT; -PFN_vkGetSwapchainCounterEXT vkGetSwapchainCounterEXT; -PFN_vkRegisterDeviceEventEXT vkRegisterDeviceEventEXT; -PFN_vkRegisterDisplayEventEXT vkRegisterDisplayEventEXT; -#endif /* defined(VK_EXT_display_control) */ -#if defined(VK_EXT_display_surface_counter) -PFN_vkGetPhysicalDeviceSurfaceCapabilities2EXT vkGetPhysicalDeviceSurfaceCapabilities2EXT; -#endif /* defined(VK_EXT_display_surface_counter) */ -#if defined(VK_EXT_extended_dynamic_state) -PFN_vkCmdBindVertexBuffers2EXT vkCmdBindVertexBuffers2EXT; -PFN_vkCmdSetCullModeEXT vkCmdSetCullModeEXT; -PFN_vkCmdSetDepthBoundsTestEnableEXT vkCmdSetDepthBoundsTestEnableEXT; -PFN_vkCmdSetDepthCompareOpEXT vkCmdSetDepthCompareOpEXT; -PFN_vkCmdSetDepthTestEnableEXT vkCmdSetDepthTestEnableEXT; -PFN_vkCmdSetDepthWriteEnableEXT vkCmdSetDepthWriteEnableEXT; -PFN_vkCmdSetFrontFaceEXT vkCmdSetFrontFaceEXT; -PFN_vkCmdSetPrimitiveTopologyEXT vkCmdSetPrimitiveTopologyEXT; -PFN_vkCmdSetScissorWithCountEXT vkCmdSetScissorWithCountEXT; -PFN_vkCmdSetStencilOpEXT vkCmdSetStencilOpEXT; -PFN_vkCmdSetStencilTestEnableEXT vkCmdSetStencilTestEnableEXT; -PFN_vkCmdSetViewportWithCountEXT vkCmdSetViewportWithCountEXT; -#endif /* defined(VK_EXT_extended_dynamic_state) */ -#if defined(VK_EXT_extended_dynamic_state2) -PFN_vkCmdSetDepthBiasEnableEXT vkCmdSetDepthBiasEnableEXT; -PFN_vkCmdSetLogicOpEXT vkCmdSetLogicOpEXT; -PFN_vkCmdSetPatchControlPointsEXT vkCmdSetPatchControlPointsEXT; -PFN_vkCmdSetPrimitiveRestartEnableEXT vkCmdSetPrimitiveRestartEnableEXT; -PFN_vkCmdSetRasterizerDiscardEnableEXT vkCmdSetRasterizerDiscardEnableEXT; -#endif /* defined(VK_EXT_extended_dynamic_state2) */ -#if defined(VK_EXT_external_memory_host) -PFN_vkGetMemoryHostPointerPropertiesEXT vkGetMemoryHostPointerPropertiesEXT; -#endif /* defined(VK_EXT_external_memory_host) */ -#if defined(VK_EXT_full_screen_exclusive) -PFN_vkAcquireFullScreenExclusiveModeEXT vkAcquireFullScreenExclusiveModeEXT; -PFN_vkGetPhysicalDeviceSurfacePresentModes2EXT vkGetPhysicalDeviceSurfacePresentModes2EXT; -PFN_vkReleaseFullScreenExclusiveModeEXT vkReleaseFullScreenExclusiveModeEXT; -#endif /* defined(VK_EXT_full_screen_exclusive) */ -#if defined(VK_EXT_hdr_metadata) -PFN_vkSetHdrMetadataEXT vkSetHdrMetadataEXT; -#endif /* defined(VK_EXT_hdr_metadata) */ -#if defined(VK_EXT_headless_surface) -PFN_vkCreateHeadlessSurfaceEXT vkCreateHeadlessSurfaceEXT; -#endif /* defined(VK_EXT_headless_surface) */ -#if defined(VK_EXT_host_query_reset) -PFN_vkResetQueryPoolEXT vkResetQueryPoolEXT; -#endif /* defined(VK_EXT_host_query_reset) */ -#if defined(VK_EXT_image_drm_format_modifier) -PFN_vkGetImageDrmFormatModifierPropertiesEXT vkGetImageDrmFormatModifierPropertiesEXT; -#endif /* defined(VK_EXT_image_drm_format_modifier) */ -#if defined(VK_EXT_line_rasterization) -PFN_vkCmdSetLineStippleEXT vkCmdSetLineStippleEXT; -#endif /* defined(VK_EXT_line_rasterization) */ -#if defined(VK_EXT_metal_surface) -PFN_vkCreateMetalSurfaceEXT vkCreateMetalSurfaceEXT; -#endif /* defined(VK_EXT_metal_surface) */ -#if defined(VK_EXT_multi_draw) -PFN_vkCmdDrawMultiEXT vkCmdDrawMultiEXT; -PFN_vkCmdDrawMultiIndexedEXT vkCmdDrawMultiIndexedEXT; -#endif /* defined(VK_EXT_multi_draw) */ -#if defined(VK_EXT_pageable_device_local_memory) -PFN_vkSetDeviceMemoryPriorityEXT vkSetDeviceMemoryPriorityEXT; -#endif /* defined(VK_EXT_pageable_device_local_memory) */ -#if defined(VK_EXT_private_data) -PFN_vkCreatePrivateDataSlotEXT vkCreatePrivateDataSlotEXT; -PFN_vkDestroyPrivateDataSlotEXT vkDestroyPrivateDataSlotEXT; -PFN_vkGetPrivateDataEXT vkGetPrivateDataEXT; -PFN_vkSetPrivateDataEXT vkSetPrivateDataEXT; -#endif /* defined(VK_EXT_private_data) */ -#if defined(VK_EXT_sample_locations) -PFN_vkCmdSetSampleLocationsEXT vkCmdSetSampleLocationsEXT; -PFN_vkGetPhysicalDeviceMultisamplePropertiesEXT vkGetPhysicalDeviceMultisamplePropertiesEXT; -#endif /* defined(VK_EXT_sample_locations) */ -#if defined(VK_EXT_tooling_info) -PFN_vkGetPhysicalDeviceToolPropertiesEXT vkGetPhysicalDeviceToolPropertiesEXT; -#endif /* defined(VK_EXT_tooling_info) */ -#if defined(VK_EXT_transform_feedback) -PFN_vkCmdBeginQueryIndexedEXT vkCmdBeginQueryIndexedEXT; -PFN_vkCmdBeginTransformFeedbackEXT vkCmdBeginTransformFeedbackEXT; -PFN_vkCmdBindTransformFeedbackBuffersEXT vkCmdBindTransformFeedbackBuffersEXT; -PFN_vkCmdDrawIndirectByteCountEXT vkCmdDrawIndirectByteCountEXT; -PFN_vkCmdEndQueryIndexedEXT vkCmdEndQueryIndexedEXT; -PFN_vkCmdEndTransformFeedbackEXT vkCmdEndTransformFeedbackEXT; -#endif /* defined(VK_EXT_transform_feedback) */ -#if defined(VK_EXT_validation_cache) -PFN_vkCreateValidationCacheEXT vkCreateValidationCacheEXT; -PFN_vkDestroyValidationCacheEXT vkDestroyValidationCacheEXT; -PFN_vkGetValidationCacheDataEXT vkGetValidationCacheDataEXT; -PFN_vkMergeValidationCachesEXT vkMergeValidationCachesEXT; -#endif /* defined(VK_EXT_validation_cache) */ -#if defined(VK_EXT_vertex_input_dynamic_state) -PFN_vkCmdSetVertexInputEXT vkCmdSetVertexInputEXT; -#endif /* defined(VK_EXT_vertex_input_dynamic_state) */ -#if defined(VK_FUCHSIA_buffer_collection) -PFN_vkCreateBufferCollectionFUCHSIA vkCreateBufferCollectionFUCHSIA; -PFN_vkDestroyBufferCollectionFUCHSIA vkDestroyBufferCollectionFUCHSIA; -PFN_vkGetBufferCollectionPropertiesFUCHSIA vkGetBufferCollectionPropertiesFUCHSIA; -PFN_vkSetBufferCollectionBufferConstraintsFUCHSIA vkSetBufferCollectionBufferConstraintsFUCHSIA; -PFN_vkSetBufferCollectionImageConstraintsFUCHSIA vkSetBufferCollectionImageConstraintsFUCHSIA; -#endif /* defined(VK_FUCHSIA_buffer_collection) */ -#if defined(VK_FUCHSIA_external_memory) -PFN_vkGetMemoryZirconHandleFUCHSIA vkGetMemoryZirconHandleFUCHSIA; -PFN_vkGetMemoryZirconHandlePropertiesFUCHSIA vkGetMemoryZirconHandlePropertiesFUCHSIA; -#endif /* defined(VK_FUCHSIA_external_memory) */ -#if defined(VK_FUCHSIA_external_semaphore) -PFN_vkGetSemaphoreZirconHandleFUCHSIA vkGetSemaphoreZirconHandleFUCHSIA; -PFN_vkImportSemaphoreZirconHandleFUCHSIA vkImportSemaphoreZirconHandleFUCHSIA; -#endif /* defined(VK_FUCHSIA_external_semaphore) */ -#if defined(VK_FUCHSIA_imagepipe_surface) -PFN_vkCreateImagePipeSurfaceFUCHSIA vkCreateImagePipeSurfaceFUCHSIA; -#endif /* defined(VK_FUCHSIA_imagepipe_surface) */ -#if defined(VK_GGP_stream_descriptor_surface) -PFN_vkCreateStreamDescriptorSurfaceGGP vkCreateStreamDescriptorSurfaceGGP; -#endif /* defined(VK_GGP_stream_descriptor_surface) */ -#if defined(VK_GOOGLE_display_timing) -PFN_vkGetPastPresentationTimingGOOGLE vkGetPastPresentationTimingGOOGLE; -PFN_vkGetRefreshCycleDurationGOOGLE vkGetRefreshCycleDurationGOOGLE; -#endif /* defined(VK_GOOGLE_display_timing) */ -#if defined(VK_HUAWEI_invocation_mask) -PFN_vkCmdBindInvocationMaskHUAWEI vkCmdBindInvocationMaskHUAWEI; -#endif /* defined(VK_HUAWEI_invocation_mask) */ -#if defined(VK_HUAWEI_subpass_shading) -PFN_vkCmdSubpassShadingHUAWEI vkCmdSubpassShadingHUAWEI; -PFN_vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI; -#endif /* defined(VK_HUAWEI_subpass_shading) */ -#if defined(VK_INTEL_performance_query) -PFN_vkAcquirePerformanceConfigurationINTEL vkAcquirePerformanceConfigurationINTEL; -PFN_vkCmdSetPerformanceMarkerINTEL vkCmdSetPerformanceMarkerINTEL; -PFN_vkCmdSetPerformanceOverrideINTEL vkCmdSetPerformanceOverrideINTEL; -PFN_vkCmdSetPerformanceStreamMarkerINTEL vkCmdSetPerformanceStreamMarkerINTEL; -PFN_vkGetPerformanceParameterINTEL vkGetPerformanceParameterINTEL; -PFN_vkInitializePerformanceApiINTEL vkInitializePerformanceApiINTEL; -PFN_vkQueueSetPerformanceConfigurationINTEL vkQueueSetPerformanceConfigurationINTEL; -PFN_vkReleasePerformanceConfigurationINTEL vkReleasePerformanceConfigurationINTEL; -PFN_vkUninitializePerformanceApiINTEL vkUninitializePerformanceApiINTEL; -#endif /* defined(VK_INTEL_performance_query) */ -#if defined(VK_KHR_acceleration_structure) -PFN_vkBuildAccelerationStructuresKHR vkBuildAccelerationStructuresKHR; -PFN_vkCmdBuildAccelerationStructuresIndirectKHR vkCmdBuildAccelerationStructuresIndirectKHR; -PFN_vkCmdBuildAccelerationStructuresKHR vkCmdBuildAccelerationStructuresKHR; -PFN_vkCmdCopyAccelerationStructureKHR vkCmdCopyAccelerationStructureKHR; -PFN_vkCmdCopyAccelerationStructureToMemoryKHR vkCmdCopyAccelerationStructureToMemoryKHR; -PFN_vkCmdCopyMemoryToAccelerationStructureKHR vkCmdCopyMemoryToAccelerationStructureKHR; -PFN_vkCmdWriteAccelerationStructuresPropertiesKHR vkCmdWriteAccelerationStructuresPropertiesKHR; -PFN_vkCopyAccelerationStructureKHR vkCopyAccelerationStructureKHR; -PFN_vkCopyAccelerationStructureToMemoryKHR vkCopyAccelerationStructureToMemoryKHR; -PFN_vkCopyMemoryToAccelerationStructureKHR vkCopyMemoryToAccelerationStructureKHR; -PFN_vkCreateAccelerationStructureKHR vkCreateAccelerationStructureKHR; -PFN_vkDestroyAccelerationStructureKHR vkDestroyAccelerationStructureKHR; -PFN_vkGetAccelerationStructureBuildSizesKHR vkGetAccelerationStructureBuildSizesKHR; -PFN_vkGetAccelerationStructureDeviceAddressKHR vkGetAccelerationStructureDeviceAddressKHR; -PFN_vkGetDeviceAccelerationStructureCompatibilityKHR vkGetDeviceAccelerationStructureCompatibilityKHR; -PFN_vkWriteAccelerationStructuresPropertiesKHR vkWriteAccelerationStructuresPropertiesKHR; -#endif /* defined(VK_KHR_acceleration_structure) */ -#if defined(VK_KHR_android_surface) -PFN_vkCreateAndroidSurfaceKHR vkCreateAndroidSurfaceKHR; -#endif /* defined(VK_KHR_android_surface) */ -#if defined(VK_KHR_bind_memory2) -PFN_vkBindBufferMemory2KHR vkBindBufferMemory2KHR; -PFN_vkBindImageMemory2KHR vkBindImageMemory2KHR; -#endif /* defined(VK_KHR_bind_memory2) */ -#if defined(VK_KHR_buffer_device_address) -PFN_vkGetBufferDeviceAddressKHR vkGetBufferDeviceAddressKHR; -PFN_vkGetBufferOpaqueCaptureAddressKHR vkGetBufferOpaqueCaptureAddressKHR; -PFN_vkGetDeviceMemoryOpaqueCaptureAddressKHR vkGetDeviceMemoryOpaqueCaptureAddressKHR; -#endif /* defined(VK_KHR_buffer_device_address) */ -#if defined(VK_KHR_copy_commands2) -PFN_vkCmdBlitImage2KHR vkCmdBlitImage2KHR; -PFN_vkCmdCopyBuffer2KHR vkCmdCopyBuffer2KHR; -PFN_vkCmdCopyBufferToImage2KHR vkCmdCopyBufferToImage2KHR; -PFN_vkCmdCopyImage2KHR vkCmdCopyImage2KHR; -PFN_vkCmdCopyImageToBuffer2KHR vkCmdCopyImageToBuffer2KHR; -PFN_vkCmdResolveImage2KHR vkCmdResolveImage2KHR; -#endif /* defined(VK_KHR_copy_commands2) */ -#if defined(VK_KHR_create_renderpass2) -PFN_vkCmdBeginRenderPass2KHR vkCmdBeginRenderPass2KHR; -PFN_vkCmdEndRenderPass2KHR vkCmdEndRenderPass2KHR; -PFN_vkCmdNextSubpass2KHR vkCmdNextSubpass2KHR; -PFN_vkCreateRenderPass2KHR vkCreateRenderPass2KHR; -#endif /* defined(VK_KHR_create_renderpass2) */ -#if defined(VK_KHR_deferred_host_operations) -PFN_vkCreateDeferredOperationKHR vkCreateDeferredOperationKHR; -PFN_vkDeferredOperationJoinKHR vkDeferredOperationJoinKHR; -PFN_vkDestroyDeferredOperationKHR vkDestroyDeferredOperationKHR; -PFN_vkGetDeferredOperationMaxConcurrencyKHR vkGetDeferredOperationMaxConcurrencyKHR; -PFN_vkGetDeferredOperationResultKHR vkGetDeferredOperationResultKHR; -#endif /* defined(VK_KHR_deferred_host_operations) */ -#if defined(VK_KHR_descriptor_update_template) -PFN_vkCreateDescriptorUpdateTemplateKHR vkCreateDescriptorUpdateTemplateKHR; -PFN_vkDestroyDescriptorUpdateTemplateKHR vkDestroyDescriptorUpdateTemplateKHR; -PFN_vkUpdateDescriptorSetWithTemplateKHR vkUpdateDescriptorSetWithTemplateKHR; -#endif /* defined(VK_KHR_descriptor_update_template) */ -#if defined(VK_KHR_device_group) -PFN_vkCmdDispatchBaseKHR vkCmdDispatchBaseKHR; -PFN_vkCmdSetDeviceMaskKHR vkCmdSetDeviceMaskKHR; -PFN_vkGetDeviceGroupPeerMemoryFeaturesKHR vkGetDeviceGroupPeerMemoryFeaturesKHR; -#endif /* defined(VK_KHR_device_group) */ -#if defined(VK_KHR_device_group_creation) -PFN_vkEnumeratePhysicalDeviceGroupsKHR vkEnumeratePhysicalDeviceGroupsKHR; -#endif /* defined(VK_KHR_device_group_creation) */ -#if defined(VK_KHR_display) -PFN_vkCreateDisplayModeKHR vkCreateDisplayModeKHR; -PFN_vkCreateDisplayPlaneSurfaceKHR vkCreateDisplayPlaneSurfaceKHR; -PFN_vkGetDisplayModePropertiesKHR vkGetDisplayModePropertiesKHR; -PFN_vkGetDisplayPlaneCapabilitiesKHR vkGetDisplayPlaneCapabilitiesKHR; -PFN_vkGetDisplayPlaneSupportedDisplaysKHR vkGetDisplayPlaneSupportedDisplaysKHR; -PFN_vkGetPhysicalDeviceDisplayPlanePropertiesKHR vkGetPhysicalDeviceDisplayPlanePropertiesKHR; -PFN_vkGetPhysicalDeviceDisplayPropertiesKHR vkGetPhysicalDeviceDisplayPropertiesKHR; -#endif /* defined(VK_KHR_display) */ -#if defined(VK_KHR_display_swapchain) -PFN_vkCreateSharedSwapchainsKHR vkCreateSharedSwapchainsKHR; -#endif /* defined(VK_KHR_display_swapchain) */ -#if defined(VK_KHR_draw_indirect_count) -PFN_vkCmdDrawIndexedIndirectCountKHR vkCmdDrawIndexedIndirectCountKHR; -PFN_vkCmdDrawIndirectCountKHR vkCmdDrawIndirectCountKHR; -#endif /* defined(VK_KHR_draw_indirect_count) */ -#if defined(VK_KHR_dynamic_rendering) -PFN_vkCmdBeginRenderingKHR vkCmdBeginRenderingKHR; -PFN_vkCmdEndRenderingKHR vkCmdEndRenderingKHR; -#endif /* defined(VK_KHR_dynamic_rendering) */ -#if defined(VK_KHR_external_fence_capabilities) -PFN_vkGetPhysicalDeviceExternalFencePropertiesKHR vkGetPhysicalDeviceExternalFencePropertiesKHR; -#endif /* defined(VK_KHR_external_fence_capabilities) */ -#if defined(VK_KHR_external_fence_fd) -PFN_vkGetFenceFdKHR vkGetFenceFdKHR; -PFN_vkImportFenceFdKHR vkImportFenceFdKHR; -#endif /* defined(VK_KHR_external_fence_fd) */ -#if defined(VK_KHR_external_fence_win32) -PFN_vkGetFenceWin32HandleKHR vkGetFenceWin32HandleKHR; -PFN_vkImportFenceWin32HandleKHR vkImportFenceWin32HandleKHR; -#endif /* defined(VK_KHR_external_fence_win32) */ -#if defined(VK_KHR_external_memory_capabilities) -PFN_vkGetPhysicalDeviceExternalBufferPropertiesKHR vkGetPhysicalDeviceExternalBufferPropertiesKHR; -#endif /* defined(VK_KHR_external_memory_capabilities) */ -#if defined(VK_KHR_external_memory_fd) -PFN_vkGetMemoryFdKHR vkGetMemoryFdKHR; -PFN_vkGetMemoryFdPropertiesKHR vkGetMemoryFdPropertiesKHR; -#endif /* defined(VK_KHR_external_memory_fd) */ -#if defined(VK_KHR_external_memory_win32) -PFN_vkGetMemoryWin32HandleKHR vkGetMemoryWin32HandleKHR; -PFN_vkGetMemoryWin32HandlePropertiesKHR vkGetMemoryWin32HandlePropertiesKHR; -#endif /* defined(VK_KHR_external_memory_win32) */ -#if defined(VK_KHR_external_semaphore_capabilities) -PFN_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR vkGetPhysicalDeviceExternalSemaphorePropertiesKHR; -#endif /* defined(VK_KHR_external_semaphore_capabilities) */ -#if defined(VK_KHR_external_semaphore_fd) -PFN_vkGetSemaphoreFdKHR vkGetSemaphoreFdKHR; -PFN_vkImportSemaphoreFdKHR vkImportSemaphoreFdKHR; -#endif /* defined(VK_KHR_external_semaphore_fd) */ -#if defined(VK_KHR_external_semaphore_win32) -PFN_vkGetSemaphoreWin32HandleKHR vkGetSemaphoreWin32HandleKHR; -PFN_vkImportSemaphoreWin32HandleKHR vkImportSemaphoreWin32HandleKHR; -#endif /* defined(VK_KHR_external_semaphore_win32) */ -#if defined(VK_KHR_fragment_shading_rate) -PFN_vkCmdSetFragmentShadingRateKHR vkCmdSetFragmentShadingRateKHR; -PFN_vkGetPhysicalDeviceFragmentShadingRatesKHR vkGetPhysicalDeviceFragmentShadingRatesKHR; -#endif /* defined(VK_KHR_fragment_shading_rate) */ -#if defined(VK_KHR_get_display_properties2) -PFN_vkGetDisplayModeProperties2KHR vkGetDisplayModeProperties2KHR; -PFN_vkGetDisplayPlaneCapabilities2KHR vkGetDisplayPlaneCapabilities2KHR; -PFN_vkGetPhysicalDeviceDisplayPlaneProperties2KHR vkGetPhysicalDeviceDisplayPlaneProperties2KHR; -PFN_vkGetPhysicalDeviceDisplayProperties2KHR vkGetPhysicalDeviceDisplayProperties2KHR; -#endif /* defined(VK_KHR_get_display_properties2) */ -#if defined(VK_KHR_get_memory_requirements2) -PFN_vkGetBufferMemoryRequirements2KHR vkGetBufferMemoryRequirements2KHR; -PFN_vkGetImageMemoryRequirements2KHR vkGetImageMemoryRequirements2KHR; -PFN_vkGetImageSparseMemoryRequirements2KHR vkGetImageSparseMemoryRequirements2KHR; -#endif /* defined(VK_KHR_get_memory_requirements2) */ -#if defined(VK_KHR_get_physical_device_properties2) -PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR; -PFN_vkGetPhysicalDeviceFormatProperties2KHR vkGetPhysicalDeviceFormatProperties2KHR; -PFN_vkGetPhysicalDeviceImageFormatProperties2KHR vkGetPhysicalDeviceImageFormatProperties2KHR; -PFN_vkGetPhysicalDeviceMemoryProperties2KHR vkGetPhysicalDeviceMemoryProperties2KHR; -PFN_vkGetPhysicalDeviceProperties2KHR vkGetPhysicalDeviceProperties2KHR; -PFN_vkGetPhysicalDeviceQueueFamilyProperties2KHR vkGetPhysicalDeviceQueueFamilyProperties2KHR; -PFN_vkGetPhysicalDeviceSparseImageFormatProperties2KHR vkGetPhysicalDeviceSparseImageFormatProperties2KHR; -#endif /* defined(VK_KHR_get_physical_device_properties2) */ -#if defined(VK_KHR_get_surface_capabilities2) -PFN_vkGetPhysicalDeviceSurfaceCapabilities2KHR vkGetPhysicalDeviceSurfaceCapabilities2KHR; -PFN_vkGetPhysicalDeviceSurfaceFormats2KHR vkGetPhysicalDeviceSurfaceFormats2KHR; -#endif /* defined(VK_KHR_get_surface_capabilities2) */ -#if defined(VK_KHR_maintenance1) -PFN_vkTrimCommandPoolKHR vkTrimCommandPoolKHR; -#endif /* defined(VK_KHR_maintenance1) */ -#if defined(VK_KHR_maintenance3) -PFN_vkGetDescriptorSetLayoutSupportKHR vkGetDescriptorSetLayoutSupportKHR; -#endif /* defined(VK_KHR_maintenance3) */ -#if defined(VK_KHR_maintenance4) -PFN_vkGetDeviceBufferMemoryRequirementsKHR vkGetDeviceBufferMemoryRequirementsKHR; -PFN_vkGetDeviceImageMemoryRequirementsKHR vkGetDeviceImageMemoryRequirementsKHR; -PFN_vkGetDeviceImageSparseMemoryRequirementsKHR vkGetDeviceImageSparseMemoryRequirementsKHR; -#endif /* defined(VK_KHR_maintenance4) */ -#if defined(VK_KHR_performance_query) -PFN_vkAcquireProfilingLockKHR vkAcquireProfilingLockKHR; -PFN_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR; -PFN_vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR; -PFN_vkReleaseProfilingLockKHR vkReleaseProfilingLockKHR; -#endif /* defined(VK_KHR_performance_query) */ -#if defined(VK_KHR_pipeline_executable_properties) -PFN_vkGetPipelineExecutableInternalRepresentationsKHR vkGetPipelineExecutableInternalRepresentationsKHR; -PFN_vkGetPipelineExecutablePropertiesKHR vkGetPipelineExecutablePropertiesKHR; -PFN_vkGetPipelineExecutableStatisticsKHR vkGetPipelineExecutableStatisticsKHR; -#endif /* defined(VK_KHR_pipeline_executable_properties) */ -#if defined(VK_KHR_present_wait) -PFN_vkWaitForPresentKHR vkWaitForPresentKHR; -#endif /* defined(VK_KHR_present_wait) */ -#if defined(VK_KHR_push_descriptor) -PFN_vkCmdPushDescriptorSetKHR vkCmdPushDescriptorSetKHR; -#endif /* defined(VK_KHR_push_descriptor) */ -#if defined(VK_KHR_ray_tracing_pipeline) -PFN_vkCmdSetRayTracingPipelineStackSizeKHR vkCmdSetRayTracingPipelineStackSizeKHR; -PFN_vkCmdTraceRaysIndirectKHR vkCmdTraceRaysIndirectKHR; -PFN_vkCmdTraceRaysKHR vkCmdTraceRaysKHR; -PFN_vkCreateRayTracingPipelinesKHR vkCreateRayTracingPipelinesKHR; -PFN_vkGetRayTracingCaptureReplayShaderGroupHandlesKHR vkGetRayTracingCaptureReplayShaderGroupHandlesKHR; -PFN_vkGetRayTracingShaderGroupHandlesKHR vkGetRayTracingShaderGroupHandlesKHR; -PFN_vkGetRayTracingShaderGroupStackSizeKHR vkGetRayTracingShaderGroupStackSizeKHR; -#endif /* defined(VK_KHR_ray_tracing_pipeline) */ -#if defined(VK_KHR_sampler_ycbcr_conversion) -PFN_vkCreateSamplerYcbcrConversionKHR vkCreateSamplerYcbcrConversionKHR; -PFN_vkDestroySamplerYcbcrConversionKHR vkDestroySamplerYcbcrConversionKHR; -#endif /* defined(VK_KHR_sampler_ycbcr_conversion) */ -#if defined(VK_KHR_shared_presentable_image) -PFN_vkGetSwapchainStatusKHR vkGetSwapchainStatusKHR; -#endif /* defined(VK_KHR_shared_presentable_image) */ -#if defined(VK_KHR_surface) -PFN_vkDestroySurfaceKHR vkDestroySurfaceKHR; -PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR; -PFN_vkGetPhysicalDeviceSurfaceFormatsKHR vkGetPhysicalDeviceSurfaceFormatsKHR; -PFN_vkGetPhysicalDeviceSurfacePresentModesKHR vkGetPhysicalDeviceSurfacePresentModesKHR; -PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR; -#endif /* defined(VK_KHR_surface) */ -#if defined(VK_KHR_swapchain) -PFN_vkAcquireNextImageKHR vkAcquireNextImageKHR; -PFN_vkCreateSwapchainKHR vkCreateSwapchainKHR; -PFN_vkDestroySwapchainKHR vkDestroySwapchainKHR; -PFN_vkGetSwapchainImagesKHR vkGetSwapchainImagesKHR; -PFN_vkQueuePresentKHR vkQueuePresentKHR; -#endif /* defined(VK_KHR_swapchain) */ -#if defined(VK_KHR_synchronization2) -PFN_vkCmdPipelineBarrier2KHR vkCmdPipelineBarrier2KHR; -PFN_vkCmdResetEvent2KHR vkCmdResetEvent2KHR; -PFN_vkCmdSetEvent2KHR vkCmdSetEvent2KHR; -PFN_vkCmdWaitEvents2KHR vkCmdWaitEvents2KHR; -PFN_vkCmdWriteTimestamp2KHR vkCmdWriteTimestamp2KHR; -PFN_vkQueueSubmit2KHR vkQueueSubmit2KHR; -#endif /* defined(VK_KHR_synchronization2) */ -#if defined(VK_KHR_synchronization2) && defined(VK_AMD_buffer_marker) -PFN_vkCmdWriteBufferMarker2AMD vkCmdWriteBufferMarker2AMD; -#endif /* defined(VK_KHR_synchronization2) && defined(VK_AMD_buffer_marker) */ -#if defined(VK_KHR_synchronization2) && defined(VK_NV_device_diagnostic_checkpoints) -PFN_vkGetQueueCheckpointData2NV vkGetQueueCheckpointData2NV; -#endif /* defined(VK_KHR_synchronization2) && defined(VK_NV_device_diagnostic_checkpoints) */ -#if defined(VK_KHR_timeline_semaphore) -PFN_vkGetSemaphoreCounterValueKHR vkGetSemaphoreCounterValueKHR; -PFN_vkSignalSemaphoreKHR vkSignalSemaphoreKHR; -PFN_vkWaitSemaphoresKHR vkWaitSemaphoresKHR; -#endif /* defined(VK_KHR_timeline_semaphore) */ -#if defined(VK_KHR_video_decode_queue) -PFN_vkCmdDecodeVideoKHR vkCmdDecodeVideoKHR; -#endif /* defined(VK_KHR_video_decode_queue) */ -#if defined(VK_KHR_video_encode_queue) -PFN_vkCmdEncodeVideoKHR vkCmdEncodeVideoKHR; -#endif /* defined(VK_KHR_video_encode_queue) */ -#if defined(VK_KHR_video_queue) -PFN_vkBindVideoSessionMemoryKHR vkBindVideoSessionMemoryKHR; -PFN_vkCmdBeginVideoCodingKHR vkCmdBeginVideoCodingKHR; -PFN_vkCmdControlVideoCodingKHR vkCmdControlVideoCodingKHR; -PFN_vkCmdEndVideoCodingKHR vkCmdEndVideoCodingKHR; -PFN_vkCreateVideoSessionKHR vkCreateVideoSessionKHR; -PFN_vkCreateVideoSessionParametersKHR vkCreateVideoSessionParametersKHR; -PFN_vkDestroyVideoSessionKHR vkDestroyVideoSessionKHR; -PFN_vkDestroyVideoSessionParametersKHR vkDestroyVideoSessionParametersKHR; -PFN_vkGetPhysicalDeviceVideoCapabilitiesKHR vkGetPhysicalDeviceVideoCapabilitiesKHR; -PFN_vkGetPhysicalDeviceVideoFormatPropertiesKHR vkGetPhysicalDeviceVideoFormatPropertiesKHR; -PFN_vkGetVideoSessionMemoryRequirementsKHR vkGetVideoSessionMemoryRequirementsKHR; -PFN_vkUpdateVideoSessionParametersKHR vkUpdateVideoSessionParametersKHR; -#endif /* defined(VK_KHR_video_queue) */ -#if defined(VK_KHR_wayland_surface) -PFN_vkCreateWaylandSurfaceKHR vkCreateWaylandSurfaceKHR; -PFN_vkGetPhysicalDeviceWaylandPresentationSupportKHR vkGetPhysicalDeviceWaylandPresentationSupportKHR; -#endif /* defined(VK_KHR_wayland_surface) */ -#if defined(VK_KHR_win32_surface) -PFN_vkCreateWin32SurfaceKHR vkCreateWin32SurfaceKHR; -PFN_vkGetPhysicalDeviceWin32PresentationSupportKHR vkGetPhysicalDeviceWin32PresentationSupportKHR; -#endif /* defined(VK_KHR_win32_surface) */ -#if defined(VK_KHR_xcb_surface) -PFN_vkCreateXcbSurfaceKHR vkCreateXcbSurfaceKHR; -PFN_vkGetPhysicalDeviceXcbPresentationSupportKHR vkGetPhysicalDeviceXcbPresentationSupportKHR; -#endif /* defined(VK_KHR_xcb_surface) */ -#if defined(VK_KHR_xlib_surface) -PFN_vkCreateXlibSurfaceKHR vkCreateXlibSurfaceKHR; -PFN_vkGetPhysicalDeviceXlibPresentationSupportKHR vkGetPhysicalDeviceXlibPresentationSupportKHR; -#endif /* defined(VK_KHR_xlib_surface) */ -#if defined(VK_MVK_ios_surface) -PFN_vkCreateIOSSurfaceMVK vkCreateIOSSurfaceMVK; -#endif /* defined(VK_MVK_ios_surface) */ -#if defined(VK_MVK_macos_surface) -PFN_vkCreateMacOSSurfaceMVK vkCreateMacOSSurfaceMVK; -#endif /* defined(VK_MVK_macos_surface) */ -#if defined(VK_NN_vi_surface) -PFN_vkCreateViSurfaceNN vkCreateViSurfaceNN; -#endif /* defined(VK_NN_vi_surface) */ -#if defined(VK_NVX_binary_import) -PFN_vkCmdCuLaunchKernelNVX vkCmdCuLaunchKernelNVX; -PFN_vkCreateCuFunctionNVX vkCreateCuFunctionNVX; -PFN_vkCreateCuModuleNVX vkCreateCuModuleNVX; -PFN_vkDestroyCuFunctionNVX vkDestroyCuFunctionNVX; -PFN_vkDestroyCuModuleNVX vkDestroyCuModuleNVX; -#endif /* defined(VK_NVX_binary_import) */ -#if defined(VK_NVX_image_view_handle) -PFN_vkGetImageViewAddressNVX vkGetImageViewAddressNVX; -PFN_vkGetImageViewHandleNVX vkGetImageViewHandleNVX; -#endif /* defined(VK_NVX_image_view_handle) */ -#if defined(VK_NV_acquire_winrt_display) -PFN_vkAcquireWinrtDisplayNV vkAcquireWinrtDisplayNV; -PFN_vkGetWinrtDisplayNV vkGetWinrtDisplayNV; -#endif /* defined(VK_NV_acquire_winrt_display) */ -#if defined(VK_NV_clip_space_w_scaling) -PFN_vkCmdSetViewportWScalingNV vkCmdSetViewportWScalingNV; -#endif /* defined(VK_NV_clip_space_w_scaling) */ -#if defined(VK_NV_cooperative_matrix) -PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesNV vkGetPhysicalDeviceCooperativeMatrixPropertiesNV; -#endif /* defined(VK_NV_cooperative_matrix) */ -#if defined(VK_NV_coverage_reduction_mode) -PFN_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV; -#endif /* defined(VK_NV_coverage_reduction_mode) */ -#if defined(VK_NV_device_diagnostic_checkpoints) -PFN_vkCmdSetCheckpointNV vkCmdSetCheckpointNV; -PFN_vkGetQueueCheckpointDataNV vkGetQueueCheckpointDataNV; -#endif /* defined(VK_NV_device_diagnostic_checkpoints) */ -#if defined(VK_NV_device_generated_commands) -PFN_vkCmdBindPipelineShaderGroupNV vkCmdBindPipelineShaderGroupNV; -PFN_vkCmdExecuteGeneratedCommandsNV vkCmdExecuteGeneratedCommandsNV; -PFN_vkCmdPreprocessGeneratedCommandsNV vkCmdPreprocessGeneratedCommandsNV; -PFN_vkCreateIndirectCommandsLayoutNV vkCreateIndirectCommandsLayoutNV; -PFN_vkDestroyIndirectCommandsLayoutNV vkDestroyIndirectCommandsLayoutNV; -PFN_vkGetGeneratedCommandsMemoryRequirementsNV vkGetGeneratedCommandsMemoryRequirementsNV; -#endif /* defined(VK_NV_device_generated_commands) */ -#if defined(VK_NV_external_memory_capabilities) -PFN_vkGetPhysicalDeviceExternalImageFormatPropertiesNV vkGetPhysicalDeviceExternalImageFormatPropertiesNV; -#endif /* defined(VK_NV_external_memory_capabilities) */ -#if defined(VK_NV_external_memory_rdma) -PFN_vkGetMemoryRemoteAddressNV vkGetMemoryRemoteAddressNV; -#endif /* defined(VK_NV_external_memory_rdma) */ -#if defined(VK_NV_external_memory_win32) -PFN_vkGetMemoryWin32HandleNV vkGetMemoryWin32HandleNV; -#endif /* defined(VK_NV_external_memory_win32) */ -#if defined(VK_NV_fragment_shading_rate_enums) -PFN_vkCmdSetFragmentShadingRateEnumNV vkCmdSetFragmentShadingRateEnumNV; -#endif /* defined(VK_NV_fragment_shading_rate_enums) */ -#if defined(VK_NV_mesh_shader) -PFN_vkCmdDrawMeshTasksIndirectCountNV vkCmdDrawMeshTasksIndirectCountNV; -PFN_vkCmdDrawMeshTasksIndirectNV vkCmdDrawMeshTasksIndirectNV; -PFN_vkCmdDrawMeshTasksNV vkCmdDrawMeshTasksNV; -#endif /* defined(VK_NV_mesh_shader) */ -#if defined(VK_NV_ray_tracing) -PFN_vkBindAccelerationStructureMemoryNV vkBindAccelerationStructureMemoryNV; -PFN_vkCmdBuildAccelerationStructureNV vkCmdBuildAccelerationStructureNV; -PFN_vkCmdCopyAccelerationStructureNV vkCmdCopyAccelerationStructureNV; -PFN_vkCmdTraceRaysNV vkCmdTraceRaysNV; -PFN_vkCmdWriteAccelerationStructuresPropertiesNV vkCmdWriteAccelerationStructuresPropertiesNV; -PFN_vkCompileDeferredNV vkCompileDeferredNV; -PFN_vkCreateAccelerationStructureNV vkCreateAccelerationStructureNV; -PFN_vkCreateRayTracingPipelinesNV vkCreateRayTracingPipelinesNV; -PFN_vkDestroyAccelerationStructureNV vkDestroyAccelerationStructureNV; -PFN_vkGetAccelerationStructureHandleNV vkGetAccelerationStructureHandleNV; -PFN_vkGetAccelerationStructureMemoryRequirementsNV vkGetAccelerationStructureMemoryRequirementsNV; -PFN_vkGetRayTracingShaderGroupHandlesNV vkGetRayTracingShaderGroupHandlesNV; -#endif /* defined(VK_NV_ray_tracing) */ -#if defined(VK_NV_scissor_exclusive) -PFN_vkCmdSetExclusiveScissorNV vkCmdSetExclusiveScissorNV; -#endif /* defined(VK_NV_scissor_exclusive) */ -#if defined(VK_NV_shading_rate_image) -PFN_vkCmdBindShadingRateImageNV vkCmdBindShadingRateImageNV; -PFN_vkCmdSetCoarseSampleOrderNV vkCmdSetCoarseSampleOrderNV; -PFN_vkCmdSetViewportShadingRatePaletteNV vkCmdSetViewportShadingRatePaletteNV; -#endif /* defined(VK_NV_shading_rate_image) */ -#if defined(VK_QNX_screen_surface) -PFN_vkCreateScreenSurfaceQNX vkCreateScreenSurfaceQNX; -PFN_vkGetPhysicalDeviceScreenPresentationSupportQNX vkGetPhysicalDeviceScreenPresentationSupportQNX; -#endif /* defined(VK_QNX_screen_surface) */ -#if (defined(VK_EXT_full_screen_exclusive) && defined(VK_KHR_device_group)) || (defined(VK_EXT_full_screen_exclusive) && defined(VK_VERSION_1_1)) -PFN_vkGetDeviceGroupSurfacePresentModes2EXT vkGetDeviceGroupSurfacePresentModes2EXT; -#endif /* (defined(VK_EXT_full_screen_exclusive) && defined(VK_KHR_device_group)) || (defined(VK_EXT_full_screen_exclusive) && defined(VK_VERSION_1_1)) */ -#if (defined(VK_KHR_descriptor_update_template) && defined(VK_KHR_push_descriptor)) || (defined(VK_KHR_push_descriptor) && defined(VK_VERSION_1_1)) || (defined(VK_KHR_push_descriptor) && defined(VK_KHR_descriptor_update_template)) -PFN_vkCmdPushDescriptorSetWithTemplateKHR vkCmdPushDescriptorSetWithTemplateKHR; -#endif /* (defined(VK_KHR_descriptor_update_template) && defined(VK_KHR_push_descriptor)) || (defined(VK_KHR_push_descriptor) && defined(VK_VERSION_1_1)) || (defined(VK_KHR_push_descriptor) && defined(VK_KHR_descriptor_update_template)) */ -#if (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) -PFN_vkGetDeviceGroupPresentCapabilitiesKHR vkGetDeviceGroupPresentCapabilitiesKHR; -PFN_vkGetDeviceGroupSurfacePresentModesKHR vkGetDeviceGroupSurfacePresentModesKHR; -PFN_vkGetPhysicalDevicePresentRectanglesKHR vkGetPhysicalDevicePresentRectanglesKHR; -#endif /* (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) */ -#if (defined(VK_KHR_device_group) && defined(VK_KHR_swapchain)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) -PFN_vkAcquireNextImage2KHR vkAcquireNextImage2KHR; -#endif /* (defined(VK_KHR_device_group) && defined(VK_KHR_swapchain)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) */ -/* VOLK_GENERATE_PROTOTYPES_C */ - -#ifdef __GNUC__ -# pragma GCC visibility pop -#endif - -#ifdef __cplusplus -} -#endif -/* clang-format on */ diff --git a/RenderSystems/Vulkan/src/volk.h b/RenderSystems/Vulkan/src/volk.h deleted file mode 100644 index 80a87ddfe93..00000000000 --- a/RenderSystems/Vulkan/src/volk.h +++ /dev/null @@ -1,1501 +0,0 @@ -/** - * volk - * - * Copyright (C) 2018-2019, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com) - * Report bugs and download new versions at https://github.com/zeux/volk - * - * This library is distributed under the MIT License. See notice at the end of this file. - */ -/* clang-format off */ -#ifndef VOLK_H_ -#define VOLK_H_ - -#if defined(VULKAN_H_) && !defined(VK_NO_PROTOTYPES) -# error To use volk, you need to define VK_NO_PROTOTYPES before including vulkan.h -#endif - -/* VOLK_GENERATE_VERSION_DEFINE */ -#define VOLK_HEADER_VERSION 198 -/* VOLK_GENERATE_VERSION_DEFINE */ - -#ifndef VK_NO_PROTOTYPES -# define VK_NO_PROTOTYPES -#endif - -#ifndef VULKAN_H_ -# ifdef VOLK_VULKAN_H_PATH -# include VOLK_VULKAN_H_PATH -# elif defined(VK_USE_PLATFORM_WIN32_KHR) -# include -# include - - /* When VK_USE_PLATFORM_WIN32_KHR is defined, instead of including vulkan.h directly, we include individual parts of the SDK - * This is necessary to avoid including which is very heavy - it takes 200ms to parse without WIN32_LEAN_AND_MEAN - * and 100ms to parse with it. vulkan_win32.h only needs a few symbols that are easy to redefine ourselves. - */ - typedef unsigned long DWORD; - typedef const wchar_t* LPCWSTR; - typedef void* HANDLE; - typedef struct HINSTANCE__* HINSTANCE; - typedef struct HWND__* HWND; - typedef struct HMONITOR__* HMONITOR; - typedef struct _SECURITY_ATTRIBUTES SECURITY_ATTRIBUTES; - -# include - -# ifdef VK_ENABLE_BETA_EXTENSIONS -# include -# endif -# else -# include -# endif -#endif - -/* Disable several extensions on earlier SDKs because later SDKs introduce a backwards incompatible change to function signatures */ -#if VK_HEADER_VERSION < 140 -# undef VK_NVX_image_view_handle -#endif -#if VK_HEADER_VERSION < 184 -# undef VK_HUAWEI_subpass_shading -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -struct VolkDeviceTable; - -/** - * Initialize library by loading Vulkan loader; call this function before creating the Vulkan instance. - * - * Returns VK_SUCCESS on success and VK_ERROR_INITIALIZATION_FAILED otherwise. - */ -VkResult volkInitialize(void); - -/** - * Initialize library by providing a custom handler to load global symbols. - * - * This function can be used instead of volkInitialize. - * The handler function pointer will be asked to load global Vulkan symbols which require no instance - * (such as vkCreateInstance, vkEnumerateInstance* and vkEnumerateInstanceVersion if available). - */ -void volkInitializeCustom(PFN_vkGetInstanceProcAddr handler); - -/** - * Get Vulkan instance version supported by the Vulkan loader, or 0 if Vulkan isn't supported - * - * Returns 0 if volkInitialize wasn't called or failed. - */ -uint32_t volkGetInstanceVersion(void); - -/** - * Load global function pointers using application-created VkInstance; call this function after creating the Vulkan instance. - */ -void volkLoadInstance(VkInstance instance); - -/** - * Load global function pointers using application-created VkInstance; call this function after creating the Vulkan instance. - * Skips loading device-based function pointers, requires usage of volkLoadDevice afterwards. - */ -void volkLoadInstanceOnly(VkInstance instance); - -/** - * Load global function pointers using application-created VkDevice; call this function after creating the Vulkan device. - * - * Note: this is not suitable for applications that want to use multiple VkDevice objects concurrently. - */ -void volkLoadDevice(VkDevice device); - -/** - * Return last VkInstance for which global function pointers have been loaded via volkLoadInstance(), - * or VK_NULL_HANDLE if volkLoadInstance() has not been called. - */ -VkInstance volkGetLoadedInstance(void); - -/** - * Return last VkDevice for which global function pointers have been loaded via volkLoadDevice(), - * or VK_NULL_HANDLE if volkLoadDevice() has not been called. - */ -VkDevice volkGetLoadedDevice(void); - -/** - * Load function pointers using application-created VkDevice into a table. - * Application should use function pointers from that table instead of using global function pointers. - */ -void volkLoadDeviceTable(struct VolkDeviceTable* table, VkDevice device); - -/** - * Device-specific function pointer table - */ -struct VolkDeviceTable -{ - /* VOLK_GENERATE_DEVICE_TABLE */ -#if defined(VK_VERSION_1_0) - PFN_vkAllocateCommandBuffers vkAllocateCommandBuffers; - PFN_vkAllocateDescriptorSets vkAllocateDescriptorSets; - PFN_vkAllocateMemory vkAllocateMemory; - PFN_vkBeginCommandBuffer vkBeginCommandBuffer; - PFN_vkBindBufferMemory vkBindBufferMemory; - PFN_vkBindImageMemory vkBindImageMemory; - PFN_vkCmdBeginQuery vkCmdBeginQuery; - PFN_vkCmdBeginRenderPass vkCmdBeginRenderPass; - PFN_vkCmdBindDescriptorSets vkCmdBindDescriptorSets; - PFN_vkCmdBindIndexBuffer vkCmdBindIndexBuffer; - PFN_vkCmdBindPipeline vkCmdBindPipeline; - PFN_vkCmdBindVertexBuffers vkCmdBindVertexBuffers; - PFN_vkCmdBlitImage vkCmdBlitImage; - PFN_vkCmdClearAttachments vkCmdClearAttachments; - PFN_vkCmdClearColorImage vkCmdClearColorImage; - PFN_vkCmdClearDepthStencilImage vkCmdClearDepthStencilImage; - PFN_vkCmdCopyBuffer vkCmdCopyBuffer; - PFN_vkCmdCopyBufferToImage vkCmdCopyBufferToImage; - PFN_vkCmdCopyImage vkCmdCopyImage; - PFN_vkCmdCopyImageToBuffer vkCmdCopyImageToBuffer; - PFN_vkCmdCopyQueryPoolResults vkCmdCopyQueryPoolResults; - PFN_vkCmdDispatch vkCmdDispatch; - PFN_vkCmdDispatchIndirect vkCmdDispatchIndirect; - PFN_vkCmdDraw vkCmdDraw; - PFN_vkCmdDrawIndexed vkCmdDrawIndexed; - PFN_vkCmdDrawIndexedIndirect vkCmdDrawIndexedIndirect; - PFN_vkCmdDrawIndirect vkCmdDrawIndirect; - PFN_vkCmdEndQuery vkCmdEndQuery; - PFN_vkCmdEndRenderPass vkCmdEndRenderPass; - PFN_vkCmdExecuteCommands vkCmdExecuteCommands; - PFN_vkCmdFillBuffer vkCmdFillBuffer; - PFN_vkCmdNextSubpass vkCmdNextSubpass; - PFN_vkCmdPipelineBarrier vkCmdPipelineBarrier; - PFN_vkCmdPushConstants vkCmdPushConstants; - PFN_vkCmdResetEvent vkCmdResetEvent; - PFN_vkCmdResetQueryPool vkCmdResetQueryPool; - PFN_vkCmdResolveImage vkCmdResolveImage; - PFN_vkCmdSetBlendConstants vkCmdSetBlendConstants; - PFN_vkCmdSetDepthBias vkCmdSetDepthBias; - PFN_vkCmdSetDepthBounds vkCmdSetDepthBounds; - PFN_vkCmdSetEvent vkCmdSetEvent; - PFN_vkCmdSetLineWidth vkCmdSetLineWidth; - PFN_vkCmdSetScissor vkCmdSetScissor; - PFN_vkCmdSetStencilCompareMask vkCmdSetStencilCompareMask; - PFN_vkCmdSetStencilReference vkCmdSetStencilReference; - PFN_vkCmdSetStencilWriteMask vkCmdSetStencilWriteMask; - PFN_vkCmdSetViewport vkCmdSetViewport; - PFN_vkCmdUpdateBuffer vkCmdUpdateBuffer; - PFN_vkCmdWaitEvents vkCmdWaitEvents; - PFN_vkCmdWriteTimestamp vkCmdWriteTimestamp; - PFN_vkCreateBuffer vkCreateBuffer; - PFN_vkCreateBufferView vkCreateBufferView; - PFN_vkCreateCommandPool vkCreateCommandPool; - PFN_vkCreateComputePipelines vkCreateComputePipelines; - PFN_vkCreateDescriptorPool vkCreateDescriptorPool; - PFN_vkCreateDescriptorSetLayout vkCreateDescriptorSetLayout; - PFN_vkCreateEvent vkCreateEvent; - PFN_vkCreateFence vkCreateFence; - PFN_vkCreateFramebuffer vkCreateFramebuffer; - PFN_vkCreateGraphicsPipelines vkCreateGraphicsPipelines; - PFN_vkCreateImage vkCreateImage; - PFN_vkCreateImageView vkCreateImageView; - PFN_vkCreatePipelineCache vkCreatePipelineCache; - PFN_vkCreatePipelineLayout vkCreatePipelineLayout; - PFN_vkCreateQueryPool vkCreateQueryPool; - PFN_vkCreateRenderPass vkCreateRenderPass; - PFN_vkCreateSampler vkCreateSampler; - PFN_vkCreateSemaphore vkCreateSemaphore; - PFN_vkCreateShaderModule vkCreateShaderModule; - PFN_vkDestroyBuffer vkDestroyBuffer; - PFN_vkDestroyBufferView vkDestroyBufferView; - PFN_vkDestroyCommandPool vkDestroyCommandPool; - PFN_vkDestroyDescriptorPool vkDestroyDescriptorPool; - PFN_vkDestroyDescriptorSetLayout vkDestroyDescriptorSetLayout; - PFN_vkDestroyDevice vkDestroyDevice; - PFN_vkDestroyEvent vkDestroyEvent; - PFN_vkDestroyFence vkDestroyFence; - PFN_vkDestroyFramebuffer vkDestroyFramebuffer; - PFN_vkDestroyImage vkDestroyImage; - PFN_vkDestroyImageView vkDestroyImageView; - PFN_vkDestroyPipeline vkDestroyPipeline; - PFN_vkDestroyPipelineCache vkDestroyPipelineCache; - PFN_vkDestroyPipelineLayout vkDestroyPipelineLayout; - PFN_vkDestroyQueryPool vkDestroyQueryPool; - PFN_vkDestroyRenderPass vkDestroyRenderPass; - PFN_vkDestroySampler vkDestroySampler; - PFN_vkDestroySemaphore vkDestroySemaphore; - PFN_vkDestroyShaderModule vkDestroyShaderModule; - PFN_vkDeviceWaitIdle vkDeviceWaitIdle; - PFN_vkEndCommandBuffer vkEndCommandBuffer; - PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges; - PFN_vkFreeCommandBuffers vkFreeCommandBuffers; - PFN_vkFreeDescriptorSets vkFreeDescriptorSets; - PFN_vkFreeMemory vkFreeMemory; - PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements; - PFN_vkGetDeviceMemoryCommitment vkGetDeviceMemoryCommitment; - PFN_vkGetDeviceQueue vkGetDeviceQueue; - PFN_vkGetEventStatus vkGetEventStatus; - PFN_vkGetFenceStatus vkGetFenceStatus; - PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements; - PFN_vkGetImageSparseMemoryRequirements vkGetImageSparseMemoryRequirements; - PFN_vkGetImageSubresourceLayout vkGetImageSubresourceLayout; - PFN_vkGetPipelineCacheData vkGetPipelineCacheData; - PFN_vkGetQueryPoolResults vkGetQueryPoolResults; - PFN_vkGetRenderAreaGranularity vkGetRenderAreaGranularity; - PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges; - PFN_vkMapMemory vkMapMemory; - PFN_vkMergePipelineCaches vkMergePipelineCaches; - PFN_vkQueueBindSparse vkQueueBindSparse; - PFN_vkQueueSubmit vkQueueSubmit; - PFN_vkQueueWaitIdle vkQueueWaitIdle; - PFN_vkResetCommandBuffer vkResetCommandBuffer; - PFN_vkResetCommandPool vkResetCommandPool; - PFN_vkResetDescriptorPool vkResetDescriptorPool; - PFN_vkResetEvent vkResetEvent; - PFN_vkResetFences vkResetFences; - PFN_vkSetEvent vkSetEvent; - PFN_vkUnmapMemory vkUnmapMemory; - PFN_vkUpdateDescriptorSets vkUpdateDescriptorSets; - PFN_vkWaitForFences vkWaitForFences; -#endif /* defined(VK_VERSION_1_0) */ -#if defined(VK_VERSION_1_1) - PFN_vkBindBufferMemory2 vkBindBufferMemory2; - PFN_vkBindImageMemory2 vkBindImageMemory2; - PFN_vkCmdDispatchBase vkCmdDispatchBase; - PFN_vkCmdSetDeviceMask vkCmdSetDeviceMask; - PFN_vkCreateDescriptorUpdateTemplate vkCreateDescriptorUpdateTemplate; - PFN_vkCreateSamplerYcbcrConversion vkCreateSamplerYcbcrConversion; - PFN_vkDestroyDescriptorUpdateTemplate vkDestroyDescriptorUpdateTemplate; - PFN_vkDestroySamplerYcbcrConversion vkDestroySamplerYcbcrConversion; - PFN_vkGetBufferMemoryRequirements2 vkGetBufferMemoryRequirements2; - PFN_vkGetDescriptorSetLayoutSupport vkGetDescriptorSetLayoutSupport; - PFN_vkGetDeviceGroupPeerMemoryFeatures vkGetDeviceGroupPeerMemoryFeatures; - PFN_vkGetDeviceQueue2 vkGetDeviceQueue2; - PFN_vkGetImageMemoryRequirements2 vkGetImageMemoryRequirements2; - PFN_vkGetImageSparseMemoryRequirements2 vkGetImageSparseMemoryRequirements2; - PFN_vkTrimCommandPool vkTrimCommandPool; - PFN_vkUpdateDescriptorSetWithTemplate vkUpdateDescriptorSetWithTemplate; -#endif /* defined(VK_VERSION_1_1) */ -#if defined(VK_VERSION_1_2) - PFN_vkCmdBeginRenderPass2 vkCmdBeginRenderPass2; - PFN_vkCmdDrawIndexedIndirectCount vkCmdDrawIndexedIndirectCount; - PFN_vkCmdDrawIndirectCount vkCmdDrawIndirectCount; - PFN_vkCmdEndRenderPass2 vkCmdEndRenderPass2; - PFN_vkCmdNextSubpass2 vkCmdNextSubpass2; - PFN_vkCreateRenderPass2 vkCreateRenderPass2; - PFN_vkGetBufferDeviceAddress vkGetBufferDeviceAddress; - PFN_vkGetBufferOpaqueCaptureAddress vkGetBufferOpaqueCaptureAddress; - PFN_vkGetDeviceMemoryOpaqueCaptureAddress vkGetDeviceMemoryOpaqueCaptureAddress; - PFN_vkGetSemaphoreCounterValue vkGetSemaphoreCounterValue; - PFN_vkResetQueryPool vkResetQueryPool; - PFN_vkSignalSemaphore vkSignalSemaphore; - PFN_vkWaitSemaphores vkWaitSemaphores; -#endif /* defined(VK_VERSION_1_2) */ -#if defined(VK_AMD_buffer_marker) - PFN_vkCmdWriteBufferMarkerAMD vkCmdWriteBufferMarkerAMD; -#endif /* defined(VK_AMD_buffer_marker) */ -#if defined(VK_AMD_display_native_hdr) - PFN_vkSetLocalDimmingAMD vkSetLocalDimmingAMD; -#endif /* defined(VK_AMD_display_native_hdr) */ -#if defined(VK_AMD_draw_indirect_count) - PFN_vkCmdDrawIndexedIndirectCountAMD vkCmdDrawIndexedIndirectCountAMD; - PFN_vkCmdDrawIndirectCountAMD vkCmdDrawIndirectCountAMD; -#endif /* defined(VK_AMD_draw_indirect_count) */ -#if defined(VK_AMD_shader_info) - PFN_vkGetShaderInfoAMD vkGetShaderInfoAMD; -#endif /* defined(VK_AMD_shader_info) */ -#if defined(VK_ANDROID_external_memory_android_hardware_buffer) - PFN_vkGetAndroidHardwareBufferPropertiesANDROID vkGetAndroidHardwareBufferPropertiesANDROID; - PFN_vkGetMemoryAndroidHardwareBufferANDROID vkGetMemoryAndroidHardwareBufferANDROID; -#endif /* defined(VK_ANDROID_external_memory_android_hardware_buffer) */ -#if defined(VK_EXT_buffer_device_address) - PFN_vkGetBufferDeviceAddressEXT vkGetBufferDeviceAddressEXT; -#endif /* defined(VK_EXT_buffer_device_address) */ -#if defined(VK_EXT_calibrated_timestamps) - PFN_vkGetCalibratedTimestampsEXT vkGetCalibratedTimestampsEXT; -#endif /* defined(VK_EXT_calibrated_timestamps) */ -#if defined(VK_EXT_color_write_enable) - PFN_vkCmdSetColorWriteEnableEXT vkCmdSetColorWriteEnableEXT; -#endif /* defined(VK_EXT_color_write_enable) */ -#if defined(VK_EXT_conditional_rendering) - PFN_vkCmdBeginConditionalRenderingEXT vkCmdBeginConditionalRenderingEXT; - PFN_vkCmdEndConditionalRenderingEXT vkCmdEndConditionalRenderingEXT; -#endif /* defined(VK_EXT_conditional_rendering) */ -#if defined(VK_EXT_debug_marker) - PFN_vkCmdDebugMarkerBeginEXT vkCmdDebugMarkerBeginEXT; - PFN_vkCmdDebugMarkerEndEXT vkCmdDebugMarkerEndEXT; - PFN_vkCmdDebugMarkerInsertEXT vkCmdDebugMarkerInsertEXT; - PFN_vkDebugMarkerSetObjectNameEXT vkDebugMarkerSetObjectNameEXT; - PFN_vkDebugMarkerSetObjectTagEXT vkDebugMarkerSetObjectTagEXT; -#endif /* defined(VK_EXT_debug_marker) */ -#if defined(VK_EXT_discard_rectangles) - PFN_vkCmdSetDiscardRectangleEXT vkCmdSetDiscardRectangleEXT; -#endif /* defined(VK_EXT_discard_rectangles) */ -#if defined(VK_EXT_display_control) - PFN_vkDisplayPowerControlEXT vkDisplayPowerControlEXT; - PFN_vkGetSwapchainCounterEXT vkGetSwapchainCounterEXT; - PFN_vkRegisterDeviceEventEXT vkRegisterDeviceEventEXT; - PFN_vkRegisterDisplayEventEXT vkRegisterDisplayEventEXT; -#endif /* defined(VK_EXT_display_control) */ -#if defined(VK_EXT_extended_dynamic_state) - PFN_vkCmdBindVertexBuffers2EXT vkCmdBindVertexBuffers2EXT; - PFN_vkCmdSetCullModeEXT vkCmdSetCullModeEXT; - PFN_vkCmdSetDepthBoundsTestEnableEXT vkCmdSetDepthBoundsTestEnableEXT; - PFN_vkCmdSetDepthCompareOpEXT vkCmdSetDepthCompareOpEXT; - PFN_vkCmdSetDepthTestEnableEXT vkCmdSetDepthTestEnableEXT; - PFN_vkCmdSetDepthWriteEnableEXT vkCmdSetDepthWriteEnableEXT; - PFN_vkCmdSetFrontFaceEXT vkCmdSetFrontFaceEXT; - PFN_vkCmdSetPrimitiveTopologyEXT vkCmdSetPrimitiveTopologyEXT; - PFN_vkCmdSetScissorWithCountEXT vkCmdSetScissorWithCountEXT; - PFN_vkCmdSetStencilOpEXT vkCmdSetStencilOpEXT; - PFN_vkCmdSetStencilTestEnableEXT vkCmdSetStencilTestEnableEXT; - PFN_vkCmdSetViewportWithCountEXT vkCmdSetViewportWithCountEXT; -#endif /* defined(VK_EXT_extended_dynamic_state) */ -#if defined(VK_EXT_extended_dynamic_state2) - PFN_vkCmdSetDepthBiasEnableEXT vkCmdSetDepthBiasEnableEXT; - PFN_vkCmdSetLogicOpEXT vkCmdSetLogicOpEXT; - PFN_vkCmdSetPatchControlPointsEXT vkCmdSetPatchControlPointsEXT; - PFN_vkCmdSetPrimitiveRestartEnableEXT vkCmdSetPrimitiveRestartEnableEXT; - PFN_vkCmdSetRasterizerDiscardEnableEXT vkCmdSetRasterizerDiscardEnableEXT; -#endif /* defined(VK_EXT_extended_dynamic_state2) */ -#if defined(VK_EXT_external_memory_host) - PFN_vkGetMemoryHostPointerPropertiesEXT vkGetMemoryHostPointerPropertiesEXT; -#endif /* defined(VK_EXT_external_memory_host) */ -#if defined(VK_EXT_full_screen_exclusive) - PFN_vkAcquireFullScreenExclusiveModeEXT vkAcquireFullScreenExclusiveModeEXT; - PFN_vkReleaseFullScreenExclusiveModeEXT vkReleaseFullScreenExclusiveModeEXT; -#endif /* defined(VK_EXT_full_screen_exclusive) */ -#if defined(VK_EXT_hdr_metadata) - PFN_vkSetHdrMetadataEXT vkSetHdrMetadataEXT; -#endif /* defined(VK_EXT_hdr_metadata) */ -#if defined(VK_EXT_host_query_reset) - PFN_vkResetQueryPoolEXT vkResetQueryPoolEXT; -#endif /* defined(VK_EXT_host_query_reset) */ -#if defined(VK_EXT_image_drm_format_modifier) - PFN_vkGetImageDrmFormatModifierPropertiesEXT vkGetImageDrmFormatModifierPropertiesEXT; -#endif /* defined(VK_EXT_image_drm_format_modifier) */ -#if defined(VK_EXT_line_rasterization) - PFN_vkCmdSetLineStippleEXT vkCmdSetLineStippleEXT; -#endif /* defined(VK_EXT_line_rasterization) */ -#if defined(VK_EXT_multi_draw) - PFN_vkCmdDrawMultiEXT vkCmdDrawMultiEXT; - PFN_vkCmdDrawMultiIndexedEXT vkCmdDrawMultiIndexedEXT; -#endif /* defined(VK_EXT_multi_draw) */ -#if defined(VK_EXT_pageable_device_local_memory) - PFN_vkSetDeviceMemoryPriorityEXT vkSetDeviceMemoryPriorityEXT; -#endif /* defined(VK_EXT_pageable_device_local_memory) */ -#if defined(VK_EXT_private_data) - PFN_vkCreatePrivateDataSlotEXT vkCreatePrivateDataSlotEXT; - PFN_vkDestroyPrivateDataSlotEXT vkDestroyPrivateDataSlotEXT; - PFN_vkGetPrivateDataEXT vkGetPrivateDataEXT; - PFN_vkSetPrivateDataEXT vkSetPrivateDataEXT; -#endif /* defined(VK_EXT_private_data) */ -#if defined(VK_EXT_sample_locations) - PFN_vkCmdSetSampleLocationsEXT vkCmdSetSampleLocationsEXT; -#endif /* defined(VK_EXT_sample_locations) */ -#if defined(VK_EXT_transform_feedback) - PFN_vkCmdBeginQueryIndexedEXT vkCmdBeginQueryIndexedEXT; - PFN_vkCmdBeginTransformFeedbackEXT vkCmdBeginTransformFeedbackEXT; - PFN_vkCmdBindTransformFeedbackBuffersEXT vkCmdBindTransformFeedbackBuffersEXT; - PFN_vkCmdDrawIndirectByteCountEXT vkCmdDrawIndirectByteCountEXT; - PFN_vkCmdEndQueryIndexedEXT vkCmdEndQueryIndexedEXT; - PFN_vkCmdEndTransformFeedbackEXT vkCmdEndTransformFeedbackEXT; -#endif /* defined(VK_EXT_transform_feedback) */ -#if defined(VK_EXT_validation_cache) - PFN_vkCreateValidationCacheEXT vkCreateValidationCacheEXT; - PFN_vkDestroyValidationCacheEXT vkDestroyValidationCacheEXT; - PFN_vkGetValidationCacheDataEXT vkGetValidationCacheDataEXT; - PFN_vkMergeValidationCachesEXT vkMergeValidationCachesEXT; -#endif /* defined(VK_EXT_validation_cache) */ -#if defined(VK_EXT_vertex_input_dynamic_state) - PFN_vkCmdSetVertexInputEXT vkCmdSetVertexInputEXT; -#endif /* defined(VK_EXT_vertex_input_dynamic_state) */ -#if defined(VK_FUCHSIA_buffer_collection) - PFN_vkCreateBufferCollectionFUCHSIA vkCreateBufferCollectionFUCHSIA; - PFN_vkDestroyBufferCollectionFUCHSIA vkDestroyBufferCollectionFUCHSIA; - PFN_vkGetBufferCollectionPropertiesFUCHSIA vkGetBufferCollectionPropertiesFUCHSIA; - PFN_vkSetBufferCollectionBufferConstraintsFUCHSIA vkSetBufferCollectionBufferConstraintsFUCHSIA; - PFN_vkSetBufferCollectionImageConstraintsFUCHSIA vkSetBufferCollectionImageConstraintsFUCHSIA; -#endif /* defined(VK_FUCHSIA_buffer_collection) */ -#if defined(VK_FUCHSIA_external_memory) - PFN_vkGetMemoryZirconHandleFUCHSIA vkGetMemoryZirconHandleFUCHSIA; - PFN_vkGetMemoryZirconHandlePropertiesFUCHSIA vkGetMemoryZirconHandlePropertiesFUCHSIA; -#endif /* defined(VK_FUCHSIA_external_memory) */ -#if defined(VK_FUCHSIA_external_semaphore) - PFN_vkGetSemaphoreZirconHandleFUCHSIA vkGetSemaphoreZirconHandleFUCHSIA; - PFN_vkImportSemaphoreZirconHandleFUCHSIA vkImportSemaphoreZirconHandleFUCHSIA; -#endif /* defined(VK_FUCHSIA_external_semaphore) */ -#if defined(VK_GOOGLE_display_timing) - PFN_vkGetPastPresentationTimingGOOGLE vkGetPastPresentationTimingGOOGLE; - PFN_vkGetRefreshCycleDurationGOOGLE vkGetRefreshCycleDurationGOOGLE; -#endif /* defined(VK_GOOGLE_display_timing) */ -#if defined(VK_HUAWEI_invocation_mask) - PFN_vkCmdBindInvocationMaskHUAWEI vkCmdBindInvocationMaskHUAWEI; -#endif /* defined(VK_HUAWEI_invocation_mask) */ -#if defined(VK_HUAWEI_subpass_shading) - PFN_vkCmdSubpassShadingHUAWEI vkCmdSubpassShadingHUAWEI; - PFN_vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI; -#endif /* defined(VK_HUAWEI_subpass_shading) */ -#if defined(VK_INTEL_performance_query) - PFN_vkAcquirePerformanceConfigurationINTEL vkAcquirePerformanceConfigurationINTEL; - PFN_vkCmdSetPerformanceMarkerINTEL vkCmdSetPerformanceMarkerINTEL; - PFN_vkCmdSetPerformanceOverrideINTEL vkCmdSetPerformanceOverrideINTEL; - PFN_vkCmdSetPerformanceStreamMarkerINTEL vkCmdSetPerformanceStreamMarkerINTEL; - PFN_vkGetPerformanceParameterINTEL vkGetPerformanceParameterINTEL; - PFN_vkInitializePerformanceApiINTEL vkInitializePerformanceApiINTEL; - PFN_vkQueueSetPerformanceConfigurationINTEL vkQueueSetPerformanceConfigurationINTEL; - PFN_vkReleasePerformanceConfigurationINTEL vkReleasePerformanceConfigurationINTEL; - PFN_vkUninitializePerformanceApiINTEL vkUninitializePerformanceApiINTEL; -#endif /* defined(VK_INTEL_performance_query) */ -#if defined(VK_KHR_acceleration_structure) - PFN_vkBuildAccelerationStructuresKHR vkBuildAccelerationStructuresKHR; - PFN_vkCmdBuildAccelerationStructuresIndirectKHR vkCmdBuildAccelerationStructuresIndirectKHR; - PFN_vkCmdBuildAccelerationStructuresKHR vkCmdBuildAccelerationStructuresKHR; - PFN_vkCmdCopyAccelerationStructureKHR vkCmdCopyAccelerationStructureKHR; - PFN_vkCmdCopyAccelerationStructureToMemoryKHR vkCmdCopyAccelerationStructureToMemoryKHR; - PFN_vkCmdCopyMemoryToAccelerationStructureKHR vkCmdCopyMemoryToAccelerationStructureKHR; - PFN_vkCmdWriteAccelerationStructuresPropertiesKHR vkCmdWriteAccelerationStructuresPropertiesKHR; - PFN_vkCopyAccelerationStructureKHR vkCopyAccelerationStructureKHR; - PFN_vkCopyAccelerationStructureToMemoryKHR vkCopyAccelerationStructureToMemoryKHR; - PFN_vkCopyMemoryToAccelerationStructureKHR vkCopyMemoryToAccelerationStructureKHR; - PFN_vkCreateAccelerationStructureKHR vkCreateAccelerationStructureKHR; - PFN_vkDestroyAccelerationStructureKHR vkDestroyAccelerationStructureKHR; - PFN_vkGetAccelerationStructureBuildSizesKHR vkGetAccelerationStructureBuildSizesKHR; - PFN_vkGetAccelerationStructureDeviceAddressKHR vkGetAccelerationStructureDeviceAddressKHR; - PFN_vkGetDeviceAccelerationStructureCompatibilityKHR vkGetDeviceAccelerationStructureCompatibilityKHR; - PFN_vkWriteAccelerationStructuresPropertiesKHR vkWriteAccelerationStructuresPropertiesKHR; -#endif /* defined(VK_KHR_acceleration_structure) */ -#if defined(VK_KHR_bind_memory2) - PFN_vkBindBufferMemory2KHR vkBindBufferMemory2KHR; - PFN_vkBindImageMemory2KHR vkBindImageMemory2KHR; -#endif /* defined(VK_KHR_bind_memory2) */ -#if defined(VK_KHR_buffer_device_address) - PFN_vkGetBufferDeviceAddressKHR vkGetBufferDeviceAddressKHR; - PFN_vkGetBufferOpaqueCaptureAddressKHR vkGetBufferOpaqueCaptureAddressKHR; - PFN_vkGetDeviceMemoryOpaqueCaptureAddressKHR vkGetDeviceMemoryOpaqueCaptureAddressKHR; -#endif /* defined(VK_KHR_buffer_device_address) */ -#if defined(VK_KHR_copy_commands2) - PFN_vkCmdBlitImage2KHR vkCmdBlitImage2KHR; - PFN_vkCmdCopyBuffer2KHR vkCmdCopyBuffer2KHR; - PFN_vkCmdCopyBufferToImage2KHR vkCmdCopyBufferToImage2KHR; - PFN_vkCmdCopyImage2KHR vkCmdCopyImage2KHR; - PFN_vkCmdCopyImageToBuffer2KHR vkCmdCopyImageToBuffer2KHR; - PFN_vkCmdResolveImage2KHR vkCmdResolveImage2KHR; -#endif /* defined(VK_KHR_copy_commands2) */ -#if defined(VK_KHR_create_renderpass2) - PFN_vkCmdBeginRenderPass2KHR vkCmdBeginRenderPass2KHR; - PFN_vkCmdEndRenderPass2KHR vkCmdEndRenderPass2KHR; - PFN_vkCmdNextSubpass2KHR vkCmdNextSubpass2KHR; - PFN_vkCreateRenderPass2KHR vkCreateRenderPass2KHR; -#endif /* defined(VK_KHR_create_renderpass2) */ -#if defined(VK_KHR_deferred_host_operations) - PFN_vkCreateDeferredOperationKHR vkCreateDeferredOperationKHR; - PFN_vkDeferredOperationJoinKHR vkDeferredOperationJoinKHR; - PFN_vkDestroyDeferredOperationKHR vkDestroyDeferredOperationKHR; - PFN_vkGetDeferredOperationMaxConcurrencyKHR vkGetDeferredOperationMaxConcurrencyKHR; - PFN_vkGetDeferredOperationResultKHR vkGetDeferredOperationResultKHR; -#endif /* defined(VK_KHR_deferred_host_operations) */ -#if defined(VK_KHR_descriptor_update_template) - PFN_vkCreateDescriptorUpdateTemplateKHR vkCreateDescriptorUpdateTemplateKHR; - PFN_vkDestroyDescriptorUpdateTemplateKHR vkDestroyDescriptorUpdateTemplateKHR; - PFN_vkUpdateDescriptorSetWithTemplateKHR vkUpdateDescriptorSetWithTemplateKHR; -#endif /* defined(VK_KHR_descriptor_update_template) */ -#if defined(VK_KHR_device_group) - PFN_vkCmdDispatchBaseKHR vkCmdDispatchBaseKHR; - PFN_vkCmdSetDeviceMaskKHR vkCmdSetDeviceMaskKHR; - PFN_vkGetDeviceGroupPeerMemoryFeaturesKHR vkGetDeviceGroupPeerMemoryFeaturesKHR; -#endif /* defined(VK_KHR_device_group) */ -#if defined(VK_KHR_display_swapchain) - PFN_vkCreateSharedSwapchainsKHR vkCreateSharedSwapchainsKHR; -#endif /* defined(VK_KHR_display_swapchain) */ -#if defined(VK_KHR_draw_indirect_count) - PFN_vkCmdDrawIndexedIndirectCountKHR vkCmdDrawIndexedIndirectCountKHR; - PFN_vkCmdDrawIndirectCountKHR vkCmdDrawIndirectCountKHR; -#endif /* defined(VK_KHR_draw_indirect_count) */ -#if defined(VK_KHR_dynamic_rendering) - PFN_vkCmdBeginRenderingKHR vkCmdBeginRenderingKHR; - PFN_vkCmdEndRenderingKHR vkCmdEndRenderingKHR; -#endif /* defined(VK_KHR_dynamic_rendering) */ -#if defined(VK_KHR_external_fence_fd) - PFN_vkGetFenceFdKHR vkGetFenceFdKHR; - PFN_vkImportFenceFdKHR vkImportFenceFdKHR; -#endif /* defined(VK_KHR_external_fence_fd) */ -#if defined(VK_KHR_external_fence_win32) - PFN_vkGetFenceWin32HandleKHR vkGetFenceWin32HandleKHR; - PFN_vkImportFenceWin32HandleKHR vkImportFenceWin32HandleKHR; -#endif /* defined(VK_KHR_external_fence_win32) */ -#if defined(VK_KHR_external_memory_fd) - PFN_vkGetMemoryFdKHR vkGetMemoryFdKHR; - PFN_vkGetMemoryFdPropertiesKHR vkGetMemoryFdPropertiesKHR; -#endif /* defined(VK_KHR_external_memory_fd) */ -#if defined(VK_KHR_external_memory_win32) - PFN_vkGetMemoryWin32HandleKHR vkGetMemoryWin32HandleKHR; - PFN_vkGetMemoryWin32HandlePropertiesKHR vkGetMemoryWin32HandlePropertiesKHR; -#endif /* defined(VK_KHR_external_memory_win32) */ -#if defined(VK_KHR_external_semaphore_fd) - PFN_vkGetSemaphoreFdKHR vkGetSemaphoreFdKHR; - PFN_vkImportSemaphoreFdKHR vkImportSemaphoreFdKHR; -#endif /* defined(VK_KHR_external_semaphore_fd) */ -#if defined(VK_KHR_external_semaphore_win32) - PFN_vkGetSemaphoreWin32HandleKHR vkGetSemaphoreWin32HandleKHR; - PFN_vkImportSemaphoreWin32HandleKHR vkImportSemaphoreWin32HandleKHR; -#endif /* defined(VK_KHR_external_semaphore_win32) */ -#if defined(VK_KHR_fragment_shading_rate) - PFN_vkCmdSetFragmentShadingRateKHR vkCmdSetFragmentShadingRateKHR; -#endif /* defined(VK_KHR_fragment_shading_rate) */ -#if defined(VK_KHR_get_memory_requirements2) - PFN_vkGetBufferMemoryRequirements2KHR vkGetBufferMemoryRequirements2KHR; - PFN_vkGetImageMemoryRequirements2KHR vkGetImageMemoryRequirements2KHR; - PFN_vkGetImageSparseMemoryRequirements2KHR vkGetImageSparseMemoryRequirements2KHR; -#endif /* defined(VK_KHR_get_memory_requirements2) */ -#if defined(VK_KHR_maintenance1) - PFN_vkTrimCommandPoolKHR vkTrimCommandPoolKHR; -#endif /* defined(VK_KHR_maintenance1) */ -#if defined(VK_KHR_maintenance3) - PFN_vkGetDescriptorSetLayoutSupportKHR vkGetDescriptorSetLayoutSupportKHR; -#endif /* defined(VK_KHR_maintenance3) */ -#if defined(VK_KHR_maintenance4) - PFN_vkGetDeviceBufferMemoryRequirementsKHR vkGetDeviceBufferMemoryRequirementsKHR; - PFN_vkGetDeviceImageMemoryRequirementsKHR vkGetDeviceImageMemoryRequirementsKHR; - PFN_vkGetDeviceImageSparseMemoryRequirementsKHR vkGetDeviceImageSparseMemoryRequirementsKHR; -#endif /* defined(VK_KHR_maintenance4) */ -#if defined(VK_KHR_performance_query) - PFN_vkAcquireProfilingLockKHR vkAcquireProfilingLockKHR; - PFN_vkReleaseProfilingLockKHR vkReleaseProfilingLockKHR; -#endif /* defined(VK_KHR_performance_query) */ -#if defined(VK_KHR_pipeline_executable_properties) - PFN_vkGetPipelineExecutableInternalRepresentationsKHR vkGetPipelineExecutableInternalRepresentationsKHR; - PFN_vkGetPipelineExecutablePropertiesKHR vkGetPipelineExecutablePropertiesKHR; - PFN_vkGetPipelineExecutableStatisticsKHR vkGetPipelineExecutableStatisticsKHR; -#endif /* defined(VK_KHR_pipeline_executable_properties) */ -#if defined(VK_KHR_present_wait) - PFN_vkWaitForPresentKHR vkWaitForPresentKHR; -#endif /* defined(VK_KHR_present_wait) */ -#if defined(VK_KHR_push_descriptor) - PFN_vkCmdPushDescriptorSetKHR vkCmdPushDescriptorSetKHR; -#endif /* defined(VK_KHR_push_descriptor) */ -#if defined(VK_KHR_ray_tracing_pipeline) - PFN_vkCmdSetRayTracingPipelineStackSizeKHR vkCmdSetRayTracingPipelineStackSizeKHR; - PFN_vkCmdTraceRaysIndirectKHR vkCmdTraceRaysIndirectKHR; - PFN_vkCmdTraceRaysKHR vkCmdTraceRaysKHR; - PFN_vkCreateRayTracingPipelinesKHR vkCreateRayTracingPipelinesKHR; - PFN_vkGetRayTracingCaptureReplayShaderGroupHandlesKHR vkGetRayTracingCaptureReplayShaderGroupHandlesKHR; - PFN_vkGetRayTracingShaderGroupHandlesKHR vkGetRayTracingShaderGroupHandlesKHR; - PFN_vkGetRayTracingShaderGroupStackSizeKHR vkGetRayTracingShaderGroupStackSizeKHR; -#endif /* defined(VK_KHR_ray_tracing_pipeline) */ -#if defined(VK_KHR_sampler_ycbcr_conversion) - PFN_vkCreateSamplerYcbcrConversionKHR vkCreateSamplerYcbcrConversionKHR; - PFN_vkDestroySamplerYcbcrConversionKHR vkDestroySamplerYcbcrConversionKHR; -#endif /* defined(VK_KHR_sampler_ycbcr_conversion) */ -#if defined(VK_KHR_shared_presentable_image) - PFN_vkGetSwapchainStatusKHR vkGetSwapchainStatusKHR; -#endif /* defined(VK_KHR_shared_presentable_image) */ -#if defined(VK_KHR_swapchain) - PFN_vkAcquireNextImageKHR vkAcquireNextImageKHR; - PFN_vkCreateSwapchainKHR vkCreateSwapchainKHR; - PFN_vkDestroySwapchainKHR vkDestroySwapchainKHR; - PFN_vkGetSwapchainImagesKHR vkGetSwapchainImagesKHR; - PFN_vkQueuePresentKHR vkQueuePresentKHR; -#endif /* defined(VK_KHR_swapchain) */ -#if defined(VK_KHR_synchronization2) - PFN_vkCmdPipelineBarrier2KHR vkCmdPipelineBarrier2KHR; - PFN_vkCmdResetEvent2KHR vkCmdResetEvent2KHR; - PFN_vkCmdSetEvent2KHR vkCmdSetEvent2KHR; - PFN_vkCmdWaitEvents2KHR vkCmdWaitEvents2KHR; - PFN_vkCmdWriteTimestamp2KHR vkCmdWriteTimestamp2KHR; - PFN_vkQueueSubmit2KHR vkQueueSubmit2KHR; -#endif /* defined(VK_KHR_synchronization2) */ -#if defined(VK_KHR_synchronization2) && defined(VK_AMD_buffer_marker) - PFN_vkCmdWriteBufferMarker2AMD vkCmdWriteBufferMarker2AMD; -#endif /* defined(VK_KHR_synchronization2) && defined(VK_AMD_buffer_marker) */ -#if defined(VK_KHR_synchronization2) && defined(VK_NV_device_diagnostic_checkpoints) - PFN_vkGetQueueCheckpointData2NV vkGetQueueCheckpointData2NV; -#endif /* defined(VK_KHR_synchronization2) && defined(VK_NV_device_diagnostic_checkpoints) */ -#if defined(VK_KHR_timeline_semaphore) - PFN_vkGetSemaphoreCounterValueKHR vkGetSemaphoreCounterValueKHR; - PFN_vkSignalSemaphoreKHR vkSignalSemaphoreKHR; - PFN_vkWaitSemaphoresKHR vkWaitSemaphoresKHR; -#endif /* defined(VK_KHR_timeline_semaphore) */ -#if defined(VK_KHR_video_decode_queue) - PFN_vkCmdDecodeVideoKHR vkCmdDecodeVideoKHR; -#endif /* defined(VK_KHR_video_decode_queue) */ -#if defined(VK_KHR_video_encode_queue) - PFN_vkCmdEncodeVideoKHR vkCmdEncodeVideoKHR; -#endif /* defined(VK_KHR_video_encode_queue) */ -#if defined(VK_KHR_video_queue) - PFN_vkBindVideoSessionMemoryKHR vkBindVideoSessionMemoryKHR; - PFN_vkCmdBeginVideoCodingKHR vkCmdBeginVideoCodingKHR; - PFN_vkCmdControlVideoCodingKHR vkCmdControlVideoCodingKHR; - PFN_vkCmdEndVideoCodingKHR vkCmdEndVideoCodingKHR; - PFN_vkCreateVideoSessionKHR vkCreateVideoSessionKHR; - PFN_vkCreateVideoSessionParametersKHR vkCreateVideoSessionParametersKHR; - PFN_vkDestroyVideoSessionKHR vkDestroyVideoSessionKHR; - PFN_vkDestroyVideoSessionParametersKHR vkDestroyVideoSessionParametersKHR; - PFN_vkGetVideoSessionMemoryRequirementsKHR vkGetVideoSessionMemoryRequirementsKHR; - PFN_vkUpdateVideoSessionParametersKHR vkUpdateVideoSessionParametersKHR; -#endif /* defined(VK_KHR_video_queue) */ -#if defined(VK_NVX_binary_import) - PFN_vkCmdCuLaunchKernelNVX vkCmdCuLaunchKernelNVX; - PFN_vkCreateCuFunctionNVX vkCreateCuFunctionNVX; - PFN_vkCreateCuModuleNVX vkCreateCuModuleNVX; - PFN_vkDestroyCuFunctionNVX vkDestroyCuFunctionNVX; - PFN_vkDestroyCuModuleNVX vkDestroyCuModuleNVX; -#endif /* defined(VK_NVX_binary_import) */ -#if defined(VK_NVX_image_view_handle) - PFN_vkGetImageViewAddressNVX vkGetImageViewAddressNVX; - PFN_vkGetImageViewHandleNVX vkGetImageViewHandleNVX; -#endif /* defined(VK_NVX_image_view_handle) */ -#if defined(VK_NV_clip_space_w_scaling) - PFN_vkCmdSetViewportWScalingNV vkCmdSetViewportWScalingNV; -#endif /* defined(VK_NV_clip_space_w_scaling) */ -#if defined(VK_NV_device_diagnostic_checkpoints) - PFN_vkCmdSetCheckpointNV vkCmdSetCheckpointNV; - PFN_vkGetQueueCheckpointDataNV vkGetQueueCheckpointDataNV; -#endif /* defined(VK_NV_device_diagnostic_checkpoints) */ -#if defined(VK_NV_device_generated_commands) - PFN_vkCmdBindPipelineShaderGroupNV vkCmdBindPipelineShaderGroupNV; - PFN_vkCmdExecuteGeneratedCommandsNV vkCmdExecuteGeneratedCommandsNV; - PFN_vkCmdPreprocessGeneratedCommandsNV vkCmdPreprocessGeneratedCommandsNV; - PFN_vkCreateIndirectCommandsLayoutNV vkCreateIndirectCommandsLayoutNV; - PFN_vkDestroyIndirectCommandsLayoutNV vkDestroyIndirectCommandsLayoutNV; - PFN_vkGetGeneratedCommandsMemoryRequirementsNV vkGetGeneratedCommandsMemoryRequirementsNV; -#endif /* defined(VK_NV_device_generated_commands) */ -#if defined(VK_NV_external_memory_rdma) - PFN_vkGetMemoryRemoteAddressNV vkGetMemoryRemoteAddressNV; -#endif /* defined(VK_NV_external_memory_rdma) */ -#if defined(VK_NV_external_memory_win32) - PFN_vkGetMemoryWin32HandleNV vkGetMemoryWin32HandleNV; -#endif /* defined(VK_NV_external_memory_win32) */ -#if defined(VK_NV_fragment_shading_rate_enums) - PFN_vkCmdSetFragmentShadingRateEnumNV vkCmdSetFragmentShadingRateEnumNV; -#endif /* defined(VK_NV_fragment_shading_rate_enums) */ -#if defined(VK_NV_mesh_shader) - PFN_vkCmdDrawMeshTasksIndirectCountNV vkCmdDrawMeshTasksIndirectCountNV; - PFN_vkCmdDrawMeshTasksIndirectNV vkCmdDrawMeshTasksIndirectNV; - PFN_vkCmdDrawMeshTasksNV vkCmdDrawMeshTasksNV; -#endif /* defined(VK_NV_mesh_shader) */ -#if defined(VK_NV_ray_tracing) - PFN_vkBindAccelerationStructureMemoryNV vkBindAccelerationStructureMemoryNV; - PFN_vkCmdBuildAccelerationStructureNV vkCmdBuildAccelerationStructureNV; - PFN_vkCmdCopyAccelerationStructureNV vkCmdCopyAccelerationStructureNV; - PFN_vkCmdTraceRaysNV vkCmdTraceRaysNV; - PFN_vkCmdWriteAccelerationStructuresPropertiesNV vkCmdWriteAccelerationStructuresPropertiesNV; - PFN_vkCompileDeferredNV vkCompileDeferredNV; - PFN_vkCreateAccelerationStructureNV vkCreateAccelerationStructureNV; - PFN_vkCreateRayTracingPipelinesNV vkCreateRayTracingPipelinesNV; - PFN_vkDestroyAccelerationStructureNV vkDestroyAccelerationStructureNV; - PFN_vkGetAccelerationStructureHandleNV vkGetAccelerationStructureHandleNV; - PFN_vkGetAccelerationStructureMemoryRequirementsNV vkGetAccelerationStructureMemoryRequirementsNV; - PFN_vkGetRayTracingShaderGroupHandlesNV vkGetRayTracingShaderGroupHandlesNV; -#endif /* defined(VK_NV_ray_tracing) */ -#if defined(VK_NV_scissor_exclusive) - PFN_vkCmdSetExclusiveScissorNV vkCmdSetExclusiveScissorNV; -#endif /* defined(VK_NV_scissor_exclusive) */ -#if defined(VK_NV_shading_rate_image) - PFN_vkCmdBindShadingRateImageNV vkCmdBindShadingRateImageNV; - PFN_vkCmdSetCoarseSampleOrderNV vkCmdSetCoarseSampleOrderNV; - PFN_vkCmdSetViewportShadingRatePaletteNV vkCmdSetViewportShadingRatePaletteNV; -#endif /* defined(VK_NV_shading_rate_image) */ -#if (defined(VK_EXT_full_screen_exclusive) && defined(VK_KHR_device_group)) || (defined(VK_EXT_full_screen_exclusive) && defined(VK_VERSION_1_1)) - PFN_vkGetDeviceGroupSurfacePresentModes2EXT vkGetDeviceGroupSurfacePresentModes2EXT; -#endif /* (defined(VK_EXT_full_screen_exclusive) && defined(VK_KHR_device_group)) || (defined(VK_EXT_full_screen_exclusive) && defined(VK_VERSION_1_1)) */ -#if (defined(VK_KHR_descriptor_update_template) && defined(VK_KHR_push_descriptor)) || (defined(VK_KHR_push_descriptor) && defined(VK_VERSION_1_1)) || (defined(VK_KHR_push_descriptor) && defined(VK_KHR_descriptor_update_template)) - PFN_vkCmdPushDescriptorSetWithTemplateKHR vkCmdPushDescriptorSetWithTemplateKHR; -#endif /* (defined(VK_KHR_descriptor_update_template) && defined(VK_KHR_push_descriptor)) || (defined(VK_KHR_push_descriptor) && defined(VK_VERSION_1_1)) || (defined(VK_KHR_push_descriptor) && defined(VK_KHR_descriptor_update_template)) */ -#if (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) - PFN_vkGetDeviceGroupPresentCapabilitiesKHR vkGetDeviceGroupPresentCapabilitiesKHR; - PFN_vkGetDeviceGroupSurfacePresentModesKHR vkGetDeviceGroupSurfacePresentModesKHR; -#endif /* (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) */ -#if (defined(VK_KHR_device_group) && defined(VK_KHR_swapchain)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) - PFN_vkAcquireNextImage2KHR vkAcquireNextImage2KHR; -#endif /* (defined(VK_KHR_device_group) && defined(VK_KHR_swapchain)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) */ - /* VOLK_GENERATE_DEVICE_TABLE */ -}; - -/* VOLK_GENERATE_PROTOTYPES_H */ -#if defined(VK_VERSION_1_0) -extern PFN_vkAllocateCommandBuffers vkAllocateCommandBuffers; -extern PFN_vkAllocateDescriptorSets vkAllocateDescriptorSets; -extern PFN_vkAllocateMemory vkAllocateMemory; -extern PFN_vkBeginCommandBuffer vkBeginCommandBuffer; -extern PFN_vkBindBufferMemory vkBindBufferMemory; -extern PFN_vkBindImageMemory vkBindImageMemory; -extern PFN_vkCmdBeginQuery vkCmdBeginQuery; -extern PFN_vkCmdBeginRenderPass vkCmdBeginRenderPass; -extern PFN_vkCmdBindDescriptorSets vkCmdBindDescriptorSets; -extern PFN_vkCmdBindIndexBuffer vkCmdBindIndexBuffer; -extern PFN_vkCmdBindPipeline vkCmdBindPipeline; -extern PFN_vkCmdBindVertexBuffers vkCmdBindVertexBuffers; -extern PFN_vkCmdBlitImage vkCmdBlitImage; -extern PFN_vkCmdClearAttachments vkCmdClearAttachments; -extern PFN_vkCmdClearColorImage vkCmdClearColorImage; -extern PFN_vkCmdClearDepthStencilImage vkCmdClearDepthStencilImage; -extern PFN_vkCmdCopyBuffer vkCmdCopyBuffer; -extern PFN_vkCmdCopyBufferToImage vkCmdCopyBufferToImage; -extern PFN_vkCmdCopyImage vkCmdCopyImage; -extern PFN_vkCmdCopyImageToBuffer vkCmdCopyImageToBuffer; -extern PFN_vkCmdCopyQueryPoolResults vkCmdCopyQueryPoolResults; -extern PFN_vkCmdDispatch vkCmdDispatch; -extern PFN_vkCmdDispatchIndirect vkCmdDispatchIndirect; -extern PFN_vkCmdDraw vkCmdDraw; -extern PFN_vkCmdDrawIndexed vkCmdDrawIndexed; -extern PFN_vkCmdDrawIndexedIndirect vkCmdDrawIndexedIndirect; -extern PFN_vkCmdDrawIndirect vkCmdDrawIndirect; -extern PFN_vkCmdEndQuery vkCmdEndQuery; -extern PFN_vkCmdEndRenderPass vkCmdEndRenderPass; -extern PFN_vkCmdExecuteCommands vkCmdExecuteCommands; -extern PFN_vkCmdFillBuffer vkCmdFillBuffer; -extern PFN_vkCmdNextSubpass vkCmdNextSubpass; -extern PFN_vkCmdPipelineBarrier vkCmdPipelineBarrier; -extern PFN_vkCmdPushConstants vkCmdPushConstants; -extern PFN_vkCmdResetEvent vkCmdResetEvent; -extern PFN_vkCmdResetQueryPool vkCmdResetQueryPool; -extern PFN_vkCmdResolveImage vkCmdResolveImage; -extern PFN_vkCmdSetBlendConstants vkCmdSetBlendConstants; -extern PFN_vkCmdSetDepthBias vkCmdSetDepthBias; -extern PFN_vkCmdSetDepthBounds vkCmdSetDepthBounds; -extern PFN_vkCmdSetEvent vkCmdSetEvent; -extern PFN_vkCmdSetLineWidth vkCmdSetLineWidth; -extern PFN_vkCmdSetScissor vkCmdSetScissor; -extern PFN_vkCmdSetStencilCompareMask vkCmdSetStencilCompareMask; -extern PFN_vkCmdSetStencilReference vkCmdSetStencilReference; -extern PFN_vkCmdSetStencilWriteMask vkCmdSetStencilWriteMask; -extern PFN_vkCmdSetViewport vkCmdSetViewport; -extern PFN_vkCmdUpdateBuffer vkCmdUpdateBuffer; -extern PFN_vkCmdWaitEvents vkCmdWaitEvents; -extern PFN_vkCmdWriteTimestamp vkCmdWriteTimestamp; -extern PFN_vkCreateBuffer vkCreateBuffer; -extern PFN_vkCreateBufferView vkCreateBufferView; -extern PFN_vkCreateCommandPool vkCreateCommandPool; -extern PFN_vkCreateComputePipelines vkCreateComputePipelines; -extern PFN_vkCreateDescriptorPool vkCreateDescriptorPool; -extern PFN_vkCreateDescriptorSetLayout vkCreateDescriptorSetLayout; -extern PFN_vkCreateDevice vkCreateDevice; -extern PFN_vkCreateEvent vkCreateEvent; -extern PFN_vkCreateFence vkCreateFence; -extern PFN_vkCreateFramebuffer vkCreateFramebuffer; -extern PFN_vkCreateGraphicsPipelines vkCreateGraphicsPipelines; -extern PFN_vkCreateImage vkCreateImage; -extern PFN_vkCreateImageView vkCreateImageView; -extern PFN_vkCreateInstance vkCreateInstance; -extern PFN_vkCreatePipelineCache vkCreatePipelineCache; -extern PFN_vkCreatePipelineLayout vkCreatePipelineLayout; -extern PFN_vkCreateQueryPool vkCreateQueryPool; -extern PFN_vkCreateRenderPass vkCreateRenderPass; -extern PFN_vkCreateSampler vkCreateSampler; -extern PFN_vkCreateSemaphore vkCreateSemaphore; -extern PFN_vkCreateShaderModule vkCreateShaderModule; -extern PFN_vkDestroyBuffer vkDestroyBuffer; -extern PFN_vkDestroyBufferView vkDestroyBufferView; -extern PFN_vkDestroyCommandPool vkDestroyCommandPool; -extern PFN_vkDestroyDescriptorPool vkDestroyDescriptorPool; -extern PFN_vkDestroyDescriptorSetLayout vkDestroyDescriptorSetLayout; -extern PFN_vkDestroyDevice vkDestroyDevice; -extern PFN_vkDestroyEvent vkDestroyEvent; -extern PFN_vkDestroyFence vkDestroyFence; -extern PFN_vkDestroyFramebuffer vkDestroyFramebuffer; -extern PFN_vkDestroyImage vkDestroyImage; -extern PFN_vkDestroyImageView vkDestroyImageView; -extern PFN_vkDestroyInstance vkDestroyInstance; -extern PFN_vkDestroyPipeline vkDestroyPipeline; -extern PFN_vkDestroyPipelineCache vkDestroyPipelineCache; -extern PFN_vkDestroyPipelineLayout vkDestroyPipelineLayout; -extern PFN_vkDestroyQueryPool vkDestroyQueryPool; -extern PFN_vkDestroyRenderPass vkDestroyRenderPass; -extern PFN_vkDestroySampler vkDestroySampler; -extern PFN_vkDestroySemaphore vkDestroySemaphore; -extern PFN_vkDestroyShaderModule vkDestroyShaderModule; -extern PFN_vkDeviceWaitIdle vkDeviceWaitIdle; -extern PFN_vkEndCommandBuffer vkEndCommandBuffer; -extern PFN_vkEnumerateDeviceExtensionProperties vkEnumerateDeviceExtensionProperties; -extern PFN_vkEnumerateDeviceLayerProperties vkEnumerateDeviceLayerProperties; -extern PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties; -extern PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties; -extern PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices; -extern PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges; -extern PFN_vkFreeCommandBuffers vkFreeCommandBuffers; -extern PFN_vkFreeDescriptorSets vkFreeDescriptorSets; -extern PFN_vkFreeMemory vkFreeMemory; -extern PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements; -extern PFN_vkGetDeviceMemoryCommitment vkGetDeviceMemoryCommitment; -extern PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr; -extern PFN_vkGetDeviceQueue vkGetDeviceQueue; -extern PFN_vkGetEventStatus vkGetEventStatus; -extern PFN_vkGetFenceStatus vkGetFenceStatus; -extern PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements; -extern PFN_vkGetImageSparseMemoryRequirements vkGetImageSparseMemoryRequirements; -extern PFN_vkGetImageSubresourceLayout vkGetImageSubresourceLayout; -extern PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr; -extern PFN_vkGetPhysicalDeviceFeatures vkGetPhysicalDeviceFeatures; -extern PFN_vkGetPhysicalDeviceFormatProperties vkGetPhysicalDeviceFormatProperties; -extern PFN_vkGetPhysicalDeviceImageFormatProperties vkGetPhysicalDeviceImageFormatProperties; -extern PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties; -extern PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties; -extern PFN_vkGetPhysicalDeviceQueueFamilyProperties vkGetPhysicalDeviceQueueFamilyProperties; -extern PFN_vkGetPhysicalDeviceSparseImageFormatProperties vkGetPhysicalDeviceSparseImageFormatProperties; -extern PFN_vkGetPipelineCacheData vkGetPipelineCacheData; -extern PFN_vkGetQueryPoolResults vkGetQueryPoolResults; -extern PFN_vkGetRenderAreaGranularity vkGetRenderAreaGranularity; -extern PFN_vkInvalidateMappedMemoryRanges vkInvalidateMappedMemoryRanges; -extern PFN_vkMapMemory vkMapMemory; -extern PFN_vkMergePipelineCaches vkMergePipelineCaches; -extern PFN_vkQueueBindSparse vkQueueBindSparse; -extern PFN_vkQueueSubmit vkQueueSubmit; -extern PFN_vkQueueWaitIdle vkQueueWaitIdle; -extern PFN_vkResetCommandBuffer vkResetCommandBuffer; -extern PFN_vkResetCommandPool vkResetCommandPool; -extern PFN_vkResetDescriptorPool vkResetDescriptorPool; -extern PFN_vkResetEvent vkResetEvent; -extern PFN_vkResetFences vkResetFences; -extern PFN_vkSetEvent vkSetEvent; -extern PFN_vkUnmapMemory vkUnmapMemory; -extern PFN_vkUpdateDescriptorSets vkUpdateDescriptorSets; -extern PFN_vkWaitForFences vkWaitForFences; -#endif /* defined(VK_VERSION_1_0) */ -#if defined(VK_VERSION_1_1) -extern PFN_vkBindBufferMemory2 vkBindBufferMemory2; -extern PFN_vkBindImageMemory2 vkBindImageMemory2; -extern PFN_vkCmdDispatchBase vkCmdDispatchBase; -extern PFN_vkCmdSetDeviceMask vkCmdSetDeviceMask; -extern PFN_vkCreateDescriptorUpdateTemplate vkCreateDescriptorUpdateTemplate; -extern PFN_vkCreateSamplerYcbcrConversion vkCreateSamplerYcbcrConversion; -extern PFN_vkDestroyDescriptorUpdateTemplate vkDestroyDescriptorUpdateTemplate; -extern PFN_vkDestroySamplerYcbcrConversion vkDestroySamplerYcbcrConversion; -extern PFN_vkEnumerateInstanceVersion vkEnumerateInstanceVersion; -extern PFN_vkEnumeratePhysicalDeviceGroups vkEnumeratePhysicalDeviceGroups; -extern PFN_vkGetBufferMemoryRequirements2 vkGetBufferMemoryRequirements2; -extern PFN_vkGetDescriptorSetLayoutSupport vkGetDescriptorSetLayoutSupport; -extern PFN_vkGetDeviceGroupPeerMemoryFeatures vkGetDeviceGroupPeerMemoryFeatures; -extern PFN_vkGetDeviceQueue2 vkGetDeviceQueue2; -extern PFN_vkGetImageMemoryRequirements2 vkGetImageMemoryRequirements2; -extern PFN_vkGetImageSparseMemoryRequirements2 vkGetImageSparseMemoryRequirements2; -extern PFN_vkGetPhysicalDeviceExternalBufferProperties vkGetPhysicalDeviceExternalBufferProperties; -extern PFN_vkGetPhysicalDeviceExternalFenceProperties vkGetPhysicalDeviceExternalFenceProperties; -extern PFN_vkGetPhysicalDeviceExternalSemaphoreProperties vkGetPhysicalDeviceExternalSemaphoreProperties; -extern PFN_vkGetPhysicalDeviceFeatures2 vkGetPhysicalDeviceFeatures2; -extern PFN_vkGetPhysicalDeviceFormatProperties2 vkGetPhysicalDeviceFormatProperties2; -extern PFN_vkGetPhysicalDeviceImageFormatProperties2 vkGetPhysicalDeviceImageFormatProperties2; -extern PFN_vkGetPhysicalDeviceMemoryProperties2 vkGetPhysicalDeviceMemoryProperties2; -extern PFN_vkGetPhysicalDeviceProperties2 vkGetPhysicalDeviceProperties2; -extern PFN_vkGetPhysicalDeviceQueueFamilyProperties2 vkGetPhysicalDeviceQueueFamilyProperties2; -extern PFN_vkGetPhysicalDeviceSparseImageFormatProperties2 vkGetPhysicalDeviceSparseImageFormatProperties2; -extern PFN_vkTrimCommandPool vkTrimCommandPool; -extern PFN_vkUpdateDescriptorSetWithTemplate vkUpdateDescriptorSetWithTemplate; -#endif /* defined(VK_VERSION_1_1) */ -#if defined(VK_VERSION_1_2) -extern PFN_vkCmdBeginRenderPass2 vkCmdBeginRenderPass2; -extern PFN_vkCmdDrawIndexedIndirectCount vkCmdDrawIndexedIndirectCount; -extern PFN_vkCmdDrawIndirectCount vkCmdDrawIndirectCount; -extern PFN_vkCmdEndRenderPass2 vkCmdEndRenderPass2; -extern PFN_vkCmdNextSubpass2 vkCmdNextSubpass2; -extern PFN_vkCreateRenderPass2 vkCreateRenderPass2; -extern PFN_vkGetBufferDeviceAddress vkGetBufferDeviceAddress; -extern PFN_vkGetBufferOpaqueCaptureAddress vkGetBufferOpaqueCaptureAddress; -extern PFN_vkGetDeviceMemoryOpaqueCaptureAddress vkGetDeviceMemoryOpaqueCaptureAddress; -extern PFN_vkGetSemaphoreCounterValue vkGetSemaphoreCounterValue; -extern PFN_vkResetQueryPool vkResetQueryPool; -extern PFN_vkSignalSemaphore vkSignalSemaphore; -extern PFN_vkWaitSemaphores vkWaitSemaphores; -#endif /* defined(VK_VERSION_1_2) */ -#if defined(VK_AMD_buffer_marker) -extern PFN_vkCmdWriteBufferMarkerAMD vkCmdWriteBufferMarkerAMD; -#endif /* defined(VK_AMD_buffer_marker) */ -#if defined(VK_AMD_display_native_hdr) -extern PFN_vkSetLocalDimmingAMD vkSetLocalDimmingAMD; -#endif /* defined(VK_AMD_display_native_hdr) */ -#if defined(VK_AMD_draw_indirect_count) -extern PFN_vkCmdDrawIndexedIndirectCountAMD vkCmdDrawIndexedIndirectCountAMD; -extern PFN_vkCmdDrawIndirectCountAMD vkCmdDrawIndirectCountAMD; -#endif /* defined(VK_AMD_draw_indirect_count) */ -#if defined(VK_AMD_shader_info) -extern PFN_vkGetShaderInfoAMD vkGetShaderInfoAMD; -#endif /* defined(VK_AMD_shader_info) */ -#if defined(VK_ANDROID_external_memory_android_hardware_buffer) -extern PFN_vkGetAndroidHardwareBufferPropertiesANDROID vkGetAndroidHardwareBufferPropertiesANDROID; -extern PFN_vkGetMemoryAndroidHardwareBufferANDROID vkGetMemoryAndroidHardwareBufferANDROID; -#endif /* defined(VK_ANDROID_external_memory_android_hardware_buffer) */ -#if defined(VK_EXT_acquire_drm_display) -extern PFN_vkAcquireDrmDisplayEXT vkAcquireDrmDisplayEXT; -extern PFN_vkGetDrmDisplayEXT vkGetDrmDisplayEXT; -#endif /* defined(VK_EXT_acquire_drm_display) */ -#if defined(VK_EXT_acquire_xlib_display) -extern PFN_vkAcquireXlibDisplayEXT vkAcquireXlibDisplayEXT; -extern PFN_vkGetRandROutputDisplayEXT vkGetRandROutputDisplayEXT; -#endif /* defined(VK_EXT_acquire_xlib_display) */ -#if defined(VK_EXT_buffer_device_address) -extern PFN_vkGetBufferDeviceAddressEXT vkGetBufferDeviceAddressEXT; -#endif /* defined(VK_EXT_buffer_device_address) */ -#if defined(VK_EXT_calibrated_timestamps) -extern PFN_vkGetCalibratedTimestampsEXT vkGetCalibratedTimestampsEXT; -extern PFN_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT vkGetPhysicalDeviceCalibrateableTimeDomainsEXT; -#endif /* defined(VK_EXT_calibrated_timestamps) */ -#if defined(VK_EXT_color_write_enable) -extern PFN_vkCmdSetColorWriteEnableEXT vkCmdSetColorWriteEnableEXT; -#endif /* defined(VK_EXT_color_write_enable) */ -#if defined(VK_EXT_conditional_rendering) -extern PFN_vkCmdBeginConditionalRenderingEXT vkCmdBeginConditionalRenderingEXT; -extern PFN_vkCmdEndConditionalRenderingEXT vkCmdEndConditionalRenderingEXT; -#endif /* defined(VK_EXT_conditional_rendering) */ -#if defined(VK_EXT_debug_marker) -extern PFN_vkCmdDebugMarkerBeginEXT vkCmdDebugMarkerBeginEXT; -extern PFN_vkCmdDebugMarkerEndEXT vkCmdDebugMarkerEndEXT; -extern PFN_vkCmdDebugMarkerInsertEXT vkCmdDebugMarkerInsertEXT; -extern PFN_vkDebugMarkerSetObjectNameEXT vkDebugMarkerSetObjectNameEXT; -extern PFN_vkDebugMarkerSetObjectTagEXT vkDebugMarkerSetObjectTagEXT; -#endif /* defined(VK_EXT_debug_marker) */ -#if defined(VK_EXT_debug_report) -extern PFN_vkCreateDebugReportCallbackEXT vkCreateDebugReportCallbackEXT; -extern PFN_vkDebugReportMessageEXT vkDebugReportMessageEXT; -extern PFN_vkDestroyDebugReportCallbackEXT vkDestroyDebugReportCallbackEXT; -#endif /* defined(VK_EXT_debug_report) */ -#if defined(VK_EXT_debug_utils) -extern PFN_vkCmdBeginDebugUtilsLabelEXT vkCmdBeginDebugUtilsLabelEXT; -extern PFN_vkCmdEndDebugUtilsLabelEXT vkCmdEndDebugUtilsLabelEXT; -extern PFN_vkCmdInsertDebugUtilsLabelEXT vkCmdInsertDebugUtilsLabelEXT; -extern PFN_vkCreateDebugUtilsMessengerEXT vkCreateDebugUtilsMessengerEXT; -extern PFN_vkDestroyDebugUtilsMessengerEXT vkDestroyDebugUtilsMessengerEXT; -extern PFN_vkQueueBeginDebugUtilsLabelEXT vkQueueBeginDebugUtilsLabelEXT; -extern PFN_vkQueueEndDebugUtilsLabelEXT vkQueueEndDebugUtilsLabelEXT; -extern PFN_vkQueueInsertDebugUtilsLabelEXT vkQueueInsertDebugUtilsLabelEXT; -extern PFN_vkSetDebugUtilsObjectNameEXT vkSetDebugUtilsObjectNameEXT; -extern PFN_vkSetDebugUtilsObjectTagEXT vkSetDebugUtilsObjectTagEXT; -extern PFN_vkSubmitDebugUtilsMessageEXT vkSubmitDebugUtilsMessageEXT; -#endif /* defined(VK_EXT_debug_utils) */ -#if defined(VK_EXT_direct_mode_display) -extern PFN_vkReleaseDisplayEXT vkReleaseDisplayEXT; -#endif /* defined(VK_EXT_direct_mode_display) */ -#if defined(VK_EXT_directfb_surface) -extern PFN_vkCreateDirectFBSurfaceEXT vkCreateDirectFBSurfaceEXT; -extern PFN_vkGetPhysicalDeviceDirectFBPresentationSupportEXT vkGetPhysicalDeviceDirectFBPresentationSupportEXT; -#endif /* defined(VK_EXT_directfb_surface) */ -#if defined(VK_EXT_discard_rectangles) -extern PFN_vkCmdSetDiscardRectangleEXT vkCmdSetDiscardRectangleEXT; -#endif /* defined(VK_EXT_discard_rectangles) */ -#if defined(VK_EXT_display_control) -extern PFN_vkDisplayPowerControlEXT vkDisplayPowerControlEXT; -extern PFN_vkGetSwapchainCounterEXT vkGetSwapchainCounterEXT; -extern PFN_vkRegisterDeviceEventEXT vkRegisterDeviceEventEXT; -extern PFN_vkRegisterDisplayEventEXT vkRegisterDisplayEventEXT; -#endif /* defined(VK_EXT_display_control) */ -#if defined(VK_EXT_display_surface_counter) -extern PFN_vkGetPhysicalDeviceSurfaceCapabilities2EXT vkGetPhysicalDeviceSurfaceCapabilities2EXT; -#endif /* defined(VK_EXT_display_surface_counter) */ -#if defined(VK_EXT_extended_dynamic_state) -extern PFN_vkCmdBindVertexBuffers2EXT vkCmdBindVertexBuffers2EXT; -extern PFN_vkCmdSetCullModeEXT vkCmdSetCullModeEXT; -extern PFN_vkCmdSetDepthBoundsTestEnableEXT vkCmdSetDepthBoundsTestEnableEXT; -extern PFN_vkCmdSetDepthCompareOpEXT vkCmdSetDepthCompareOpEXT; -extern PFN_vkCmdSetDepthTestEnableEXT vkCmdSetDepthTestEnableEXT; -extern PFN_vkCmdSetDepthWriteEnableEXT vkCmdSetDepthWriteEnableEXT; -extern PFN_vkCmdSetFrontFaceEXT vkCmdSetFrontFaceEXT; -extern PFN_vkCmdSetPrimitiveTopologyEXT vkCmdSetPrimitiveTopologyEXT; -extern PFN_vkCmdSetScissorWithCountEXT vkCmdSetScissorWithCountEXT; -extern PFN_vkCmdSetStencilOpEXT vkCmdSetStencilOpEXT; -extern PFN_vkCmdSetStencilTestEnableEXT vkCmdSetStencilTestEnableEXT; -extern PFN_vkCmdSetViewportWithCountEXT vkCmdSetViewportWithCountEXT; -#endif /* defined(VK_EXT_extended_dynamic_state) */ -#if defined(VK_EXT_extended_dynamic_state2) -extern PFN_vkCmdSetDepthBiasEnableEXT vkCmdSetDepthBiasEnableEXT; -extern PFN_vkCmdSetLogicOpEXT vkCmdSetLogicOpEXT; -extern PFN_vkCmdSetPatchControlPointsEXT vkCmdSetPatchControlPointsEXT; -extern PFN_vkCmdSetPrimitiveRestartEnableEXT vkCmdSetPrimitiveRestartEnableEXT; -extern PFN_vkCmdSetRasterizerDiscardEnableEXT vkCmdSetRasterizerDiscardEnableEXT; -#endif /* defined(VK_EXT_extended_dynamic_state2) */ -#if defined(VK_EXT_external_memory_host) -extern PFN_vkGetMemoryHostPointerPropertiesEXT vkGetMemoryHostPointerPropertiesEXT; -#endif /* defined(VK_EXT_external_memory_host) */ -#if defined(VK_EXT_full_screen_exclusive) -extern PFN_vkAcquireFullScreenExclusiveModeEXT vkAcquireFullScreenExclusiveModeEXT; -extern PFN_vkGetPhysicalDeviceSurfacePresentModes2EXT vkGetPhysicalDeviceSurfacePresentModes2EXT; -extern PFN_vkReleaseFullScreenExclusiveModeEXT vkReleaseFullScreenExclusiveModeEXT; -#endif /* defined(VK_EXT_full_screen_exclusive) */ -#if defined(VK_EXT_hdr_metadata) -extern PFN_vkSetHdrMetadataEXT vkSetHdrMetadataEXT; -#endif /* defined(VK_EXT_hdr_metadata) */ -#if defined(VK_EXT_headless_surface) -extern PFN_vkCreateHeadlessSurfaceEXT vkCreateHeadlessSurfaceEXT; -#endif /* defined(VK_EXT_headless_surface) */ -#if defined(VK_EXT_host_query_reset) -extern PFN_vkResetQueryPoolEXT vkResetQueryPoolEXT; -#endif /* defined(VK_EXT_host_query_reset) */ -#if defined(VK_EXT_image_drm_format_modifier) -extern PFN_vkGetImageDrmFormatModifierPropertiesEXT vkGetImageDrmFormatModifierPropertiesEXT; -#endif /* defined(VK_EXT_image_drm_format_modifier) */ -#if defined(VK_EXT_line_rasterization) -extern PFN_vkCmdSetLineStippleEXT vkCmdSetLineStippleEXT; -#endif /* defined(VK_EXT_line_rasterization) */ -#if defined(VK_EXT_metal_surface) -extern PFN_vkCreateMetalSurfaceEXT vkCreateMetalSurfaceEXT; -#endif /* defined(VK_EXT_metal_surface) */ -#if defined(VK_EXT_multi_draw) -extern PFN_vkCmdDrawMultiEXT vkCmdDrawMultiEXT; -extern PFN_vkCmdDrawMultiIndexedEXT vkCmdDrawMultiIndexedEXT; -#endif /* defined(VK_EXT_multi_draw) */ -#if defined(VK_EXT_pageable_device_local_memory) -extern PFN_vkSetDeviceMemoryPriorityEXT vkSetDeviceMemoryPriorityEXT; -#endif /* defined(VK_EXT_pageable_device_local_memory) */ -#if defined(VK_EXT_private_data) -extern PFN_vkCreatePrivateDataSlotEXT vkCreatePrivateDataSlotEXT; -extern PFN_vkDestroyPrivateDataSlotEXT vkDestroyPrivateDataSlotEXT; -extern PFN_vkGetPrivateDataEXT vkGetPrivateDataEXT; -extern PFN_vkSetPrivateDataEXT vkSetPrivateDataEXT; -#endif /* defined(VK_EXT_private_data) */ -#if defined(VK_EXT_sample_locations) -extern PFN_vkCmdSetSampleLocationsEXT vkCmdSetSampleLocationsEXT; -extern PFN_vkGetPhysicalDeviceMultisamplePropertiesEXT vkGetPhysicalDeviceMultisamplePropertiesEXT; -#endif /* defined(VK_EXT_sample_locations) */ -#if defined(VK_EXT_tooling_info) -extern PFN_vkGetPhysicalDeviceToolPropertiesEXT vkGetPhysicalDeviceToolPropertiesEXT; -#endif /* defined(VK_EXT_tooling_info) */ -#if defined(VK_EXT_transform_feedback) -extern PFN_vkCmdBeginQueryIndexedEXT vkCmdBeginQueryIndexedEXT; -extern PFN_vkCmdBeginTransformFeedbackEXT vkCmdBeginTransformFeedbackEXT; -extern PFN_vkCmdBindTransformFeedbackBuffersEXT vkCmdBindTransformFeedbackBuffersEXT; -extern PFN_vkCmdDrawIndirectByteCountEXT vkCmdDrawIndirectByteCountEXT; -extern PFN_vkCmdEndQueryIndexedEXT vkCmdEndQueryIndexedEXT; -extern PFN_vkCmdEndTransformFeedbackEXT vkCmdEndTransformFeedbackEXT; -#endif /* defined(VK_EXT_transform_feedback) */ -#if defined(VK_EXT_validation_cache) -extern PFN_vkCreateValidationCacheEXT vkCreateValidationCacheEXT; -extern PFN_vkDestroyValidationCacheEXT vkDestroyValidationCacheEXT; -extern PFN_vkGetValidationCacheDataEXT vkGetValidationCacheDataEXT; -extern PFN_vkMergeValidationCachesEXT vkMergeValidationCachesEXT; -#endif /* defined(VK_EXT_validation_cache) */ -#if defined(VK_EXT_vertex_input_dynamic_state) -extern PFN_vkCmdSetVertexInputEXT vkCmdSetVertexInputEXT; -#endif /* defined(VK_EXT_vertex_input_dynamic_state) */ -#if defined(VK_FUCHSIA_buffer_collection) -extern PFN_vkCreateBufferCollectionFUCHSIA vkCreateBufferCollectionFUCHSIA; -extern PFN_vkDestroyBufferCollectionFUCHSIA vkDestroyBufferCollectionFUCHSIA; -extern PFN_vkGetBufferCollectionPropertiesFUCHSIA vkGetBufferCollectionPropertiesFUCHSIA; -extern PFN_vkSetBufferCollectionBufferConstraintsFUCHSIA vkSetBufferCollectionBufferConstraintsFUCHSIA; -extern PFN_vkSetBufferCollectionImageConstraintsFUCHSIA vkSetBufferCollectionImageConstraintsFUCHSIA; -#endif /* defined(VK_FUCHSIA_buffer_collection) */ -#if defined(VK_FUCHSIA_external_memory) -extern PFN_vkGetMemoryZirconHandleFUCHSIA vkGetMemoryZirconHandleFUCHSIA; -extern PFN_vkGetMemoryZirconHandlePropertiesFUCHSIA vkGetMemoryZirconHandlePropertiesFUCHSIA; -#endif /* defined(VK_FUCHSIA_external_memory) */ -#if defined(VK_FUCHSIA_external_semaphore) -extern PFN_vkGetSemaphoreZirconHandleFUCHSIA vkGetSemaphoreZirconHandleFUCHSIA; -extern PFN_vkImportSemaphoreZirconHandleFUCHSIA vkImportSemaphoreZirconHandleFUCHSIA; -#endif /* defined(VK_FUCHSIA_external_semaphore) */ -#if defined(VK_FUCHSIA_imagepipe_surface) -extern PFN_vkCreateImagePipeSurfaceFUCHSIA vkCreateImagePipeSurfaceFUCHSIA; -#endif /* defined(VK_FUCHSIA_imagepipe_surface) */ -#if defined(VK_GGP_stream_descriptor_surface) -extern PFN_vkCreateStreamDescriptorSurfaceGGP vkCreateStreamDescriptorSurfaceGGP; -#endif /* defined(VK_GGP_stream_descriptor_surface) */ -#if defined(VK_GOOGLE_display_timing) -extern PFN_vkGetPastPresentationTimingGOOGLE vkGetPastPresentationTimingGOOGLE; -extern PFN_vkGetRefreshCycleDurationGOOGLE vkGetRefreshCycleDurationGOOGLE; -#endif /* defined(VK_GOOGLE_display_timing) */ -#if defined(VK_HUAWEI_invocation_mask) -extern PFN_vkCmdBindInvocationMaskHUAWEI vkCmdBindInvocationMaskHUAWEI; -#endif /* defined(VK_HUAWEI_invocation_mask) */ -#if defined(VK_HUAWEI_subpass_shading) -extern PFN_vkCmdSubpassShadingHUAWEI vkCmdSubpassShadingHUAWEI; -extern PFN_vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI vkGetDeviceSubpassShadingMaxWorkgroupSizeHUAWEI; -#endif /* defined(VK_HUAWEI_subpass_shading) */ -#if defined(VK_INTEL_performance_query) -extern PFN_vkAcquirePerformanceConfigurationINTEL vkAcquirePerformanceConfigurationINTEL; -extern PFN_vkCmdSetPerformanceMarkerINTEL vkCmdSetPerformanceMarkerINTEL; -extern PFN_vkCmdSetPerformanceOverrideINTEL vkCmdSetPerformanceOverrideINTEL; -extern PFN_vkCmdSetPerformanceStreamMarkerINTEL vkCmdSetPerformanceStreamMarkerINTEL; -extern PFN_vkGetPerformanceParameterINTEL vkGetPerformanceParameterINTEL; -extern PFN_vkInitializePerformanceApiINTEL vkInitializePerformanceApiINTEL; -extern PFN_vkQueueSetPerformanceConfigurationINTEL vkQueueSetPerformanceConfigurationINTEL; -extern PFN_vkReleasePerformanceConfigurationINTEL vkReleasePerformanceConfigurationINTEL; -extern PFN_vkUninitializePerformanceApiINTEL vkUninitializePerformanceApiINTEL; -#endif /* defined(VK_INTEL_performance_query) */ -#if defined(VK_KHR_acceleration_structure) -extern PFN_vkBuildAccelerationStructuresKHR vkBuildAccelerationStructuresKHR; -extern PFN_vkCmdBuildAccelerationStructuresIndirectKHR vkCmdBuildAccelerationStructuresIndirectKHR; -extern PFN_vkCmdBuildAccelerationStructuresKHR vkCmdBuildAccelerationStructuresKHR; -extern PFN_vkCmdCopyAccelerationStructureKHR vkCmdCopyAccelerationStructureKHR; -extern PFN_vkCmdCopyAccelerationStructureToMemoryKHR vkCmdCopyAccelerationStructureToMemoryKHR; -extern PFN_vkCmdCopyMemoryToAccelerationStructureKHR vkCmdCopyMemoryToAccelerationStructureKHR; -extern PFN_vkCmdWriteAccelerationStructuresPropertiesKHR vkCmdWriteAccelerationStructuresPropertiesKHR; -extern PFN_vkCopyAccelerationStructureKHR vkCopyAccelerationStructureKHR; -extern PFN_vkCopyAccelerationStructureToMemoryKHR vkCopyAccelerationStructureToMemoryKHR; -extern PFN_vkCopyMemoryToAccelerationStructureKHR vkCopyMemoryToAccelerationStructureKHR; -extern PFN_vkCreateAccelerationStructureKHR vkCreateAccelerationStructureKHR; -extern PFN_vkDestroyAccelerationStructureKHR vkDestroyAccelerationStructureKHR; -extern PFN_vkGetAccelerationStructureBuildSizesKHR vkGetAccelerationStructureBuildSizesKHR; -extern PFN_vkGetAccelerationStructureDeviceAddressKHR vkGetAccelerationStructureDeviceAddressKHR; -extern PFN_vkGetDeviceAccelerationStructureCompatibilityKHR vkGetDeviceAccelerationStructureCompatibilityKHR; -extern PFN_vkWriteAccelerationStructuresPropertiesKHR vkWriteAccelerationStructuresPropertiesKHR; -#endif /* defined(VK_KHR_acceleration_structure) */ -#if defined(VK_KHR_android_surface) -extern PFN_vkCreateAndroidSurfaceKHR vkCreateAndroidSurfaceKHR; -#endif /* defined(VK_KHR_android_surface) */ -#if defined(VK_KHR_bind_memory2) -extern PFN_vkBindBufferMemory2KHR vkBindBufferMemory2KHR; -extern PFN_vkBindImageMemory2KHR vkBindImageMemory2KHR; -#endif /* defined(VK_KHR_bind_memory2) */ -#if defined(VK_KHR_buffer_device_address) -extern PFN_vkGetBufferDeviceAddressKHR vkGetBufferDeviceAddressKHR; -extern PFN_vkGetBufferOpaqueCaptureAddressKHR vkGetBufferOpaqueCaptureAddressKHR; -extern PFN_vkGetDeviceMemoryOpaqueCaptureAddressKHR vkGetDeviceMemoryOpaqueCaptureAddressKHR; -#endif /* defined(VK_KHR_buffer_device_address) */ -#if defined(VK_KHR_copy_commands2) -extern PFN_vkCmdBlitImage2KHR vkCmdBlitImage2KHR; -extern PFN_vkCmdCopyBuffer2KHR vkCmdCopyBuffer2KHR; -extern PFN_vkCmdCopyBufferToImage2KHR vkCmdCopyBufferToImage2KHR; -extern PFN_vkCmdCopyImage2KHR vkCmdCopyImage2KHR; -extern PFN_vkCmdCopyImageToBuffer2KHR vkCmdCopyImageToBuffer2KHR; -extern PFN_vkCmdResolveImage2KHR vkCmdResolveImage2KHR; -#endif /* defined(VK_KHR_copy_commands2) */ -#if defined(VK_KHR_create_renderpass2) -extern PFN_vkCmdBeginRenderPass2KHR vkCmdBeginRenderPass2KHR; -extern PFN_vkCmdEndRenderPass2KHR vkCmdEndRenderPass2KHR; -extern PFN_vkCmdNextSubpass2KHR vkCmdNextSubpass2KHR; -extern PFN_vkCreateRenderPass2KHR vkCreateRenderPass2KHR; -#endif /* defined(VK_KHR_create_renderpass2) */ -#if defined(VK_KHR_deferred_host_operations) -extern PFN_vkCreateDeferredOperationKHR vkCreateDeferredOperationKHR; -extern PFN_vkDeferredOperationJoinKHR vkDeferredOperationJoinKHR; -extern PFN_vkDestroyDeferredOperationKHR vkDestroyDeferredOperationKHR; -extern PFN_vkGetDeferredOperationMaxConcurrencyKHR vkGetDeferredOperationMaxConcurrencyKHR; -extern PFN_vkGetDeferredOperationResultKHR vkGetDeferredOperationResultKHR; -#endif /* defined(VK_KHR_deferred_host_operations) */ -#if defined(VK_KHR_descriptor_update_template) -extern PFN_vkCreateDescriptorUpdateTemplateKHR vkCreateDescriptorUpdateTemplateKHR; -extern PFN_vkDestroyDescriptorUpdateTemplateKHR vkDestroyDescriptorUpdateTemplateKHR; -extern PFN_vkUpdateDescriptorSetWithTemplateKHR vkUpdateDescriptorSetWithTemplateKHR; -#endif /* defined(VK_KHR_descriptor_update_template) */ -#if defined(VK_KHR_device_group) -extern PFN_vkCmdDispatchBaseKHR vkCmdDispatchBaseKHR; -extern PFN_vkCmdSetDeviceMaskKHR vkCmdSetDeviceMaskKHR; -extern PFN_vkGetDeviceGroupPeerMemoryFeaturesKHR vkGetDeviceGroupPeerMemoryFeaturesKHR; -#endif /* defined(VK_KHR_device_group) */ -#if defined(VK_KHR_device_group_creation) -extern PFN_vkEnumeratePhysicalDeviceGroupsKHR vkEnumeratePhysicalDeviceGroupsKHR; -#endif /* defined(VK_KHR_device_group_creation) */ -#if defined(VK_KHR_display) -extern PFN_vkCreateDisplayModeKHR vkCreateDisplayModeKHR; -extern PFN_vkCreateDisplayPlaneSurfaceKHR vkCreateDisplayPlaneSurfaceKHR; -extern PFN_vkGetDisplayModePropertiesKHR vkGetDisplayModePropertiesKHR; -extern PFN_vkGetDisplayPlaneCapabilitiesKHR vkGetDisplayPlaneCapabilitiesKHR; -extern PFN_vkGetDisplayPlaneSupportedDisplaysKHR vkGetDisplayPlaneSupportedDisplaysKHR; -extern PFN_vkGetPhysicalDeviceDisplayPlanePropertiesKHR vkGetPhysicalDeviceDisplayPlanePropertiesKHR; -extern PFN_vkGetPhysicalDeviceDisplayPropertiesKHR vkGetPhysicalDeviceDisplayPropertiesKHR; -#endif /* defined(VK_KHR_display) */ -#if defined(VK_KHR_display_swapchain) -extern PFN_vkCreateSharedSwapchainsKHR vkCreateSharedSwapchainsKHR; -#endif /* defined(VK_KHR_display_swapchain) */ -#if defined(VK_KHR_draw_indirect_count) -extern PFN_vkCmdDrawIndexedIndirectCountKHR vkCmdDrawIndexedIndirectCountKHR; -extern PFN_vkCmdDrawIndirectCountKHR vkCmdDrawIndirectCountKHR; -#endif /* defined(VK_KHR_draw_indirect_count) */ -#if defined(VK_KHR_dynamic_rendering) -extern PFN_vkCmdBeginRenderingKHR vkCmdBeginRenderingKHR; -extern PFN_vkCmdEndRenderingKHR vkCmdEndRenderingKHR; -#endif /* defined(VK_KHR_dynamic_rendering) */ -#if defined(VK_KHR_external_fence_capabilities) -extern PFN_vkGetPhysicalDeviceExternalFencePropertiesKHR vkGetPhysicalDeviceExternalFencePropertiesKHR; -#endif /* defined(VK_KHR_external_fence_capabilities) */ -#if defined(VK_KHR_external_fence_fd) -extern PFN_vkGetFenceFdKHR vkGetFenceFdKHR; -extern PFN_vkImportFenceFdKHR vkImportFenceFdKHR; -#endif /* defined(VK_KHR_external_fence_fd) */ -#if defined(VK_KHR_external_fence_win32) -extern PFN_vkGetFenceWin32HandleKHR vkGetFenceWin32HandleKHR; -extern PFN_vkImportFenceWin32HandleKHR vkImportFenceWin32HandleKHR; -#endif /* defined(VK_KHR_external_fence_win32) */ -#if defined(VK_KHR_external_memory_capabilities) -extern PFN_vkGetPhysicalDeviceExternalBufferPropertiesKHR vkGetPhysicalDeviceExternalBufferPropertiesKHR; -#endif /* defined(VK_KHR_external_memory_capabilities) */ -#if defined(VK_KHR_external_memory_fd) -extern PFN_vkGetMemoryFdKHR vkGetMemoryFdKHR; -extern PFN_vkGetMemoryFdPropertiesKHR vkGetMemoryFdPropertiesKHR; -#endif /* defined(VK_KHR_external_memory_fd) */ -#if defined(VK_KHR_external_memory_win32) -extern PFN_vkGetMemoryWin32HandleKHR vkGetMemoryWin32HandleKHR; -extern PFN_vkGetMemoryWin32HandlePropertiesKHR vkGetMemoryWin32HandlePropertiesKHR; -#endif /* defined(VK_KHR_external_memory_win32) */ -#if defined(VK_KHR_external_semaphore_capabilities) -extern PFN_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR vkGetPhysicalDeviceExternalSemaphorePropertiesKHR; -#endif /* defined(VK_KHR_external_semaphore_capabilities) */ -#if defined(VK_KHR_external_semaphore_fd) -extern PFN_vkGetSemaphoreFdKHR vkGetSemaphoreFdKHR; -extern PFN_vkImportSemaphoreFdKHR vkImportSemaphoreFdKHR; -#endif /* defined(VK_KHR_external_semaphore_fd) */ -#if defined(VK_KHR_external_semaphore_win32) -extern PFN_vkGetSemaphoreWin32HandleKHR vkGetSemaphoreWin32HandleKHR; -extern PFN_vkImportSemaphoreWin32HandleKHR vkImportSemaphoreWin32HandleKHR; -#endif /* defined(VK_KHR_external_semaphore_win32) */ -#if defined(VK_KHR_fragment_shading_rate) -extern PFN_vkCmdSetFragmentShadingRateKHR vkCmdSetFragmentShadingRateKHR; -extern PFN_vkGetPhysicalDeviceFragmentShadingRatesKHR vkGetPhysicalDeviceFragmentShadingRatesKHR; -#endif /* defined(VK_KHR_fragment_shading_rate) */ -#if defined(VK_KHR_get_display_properties2) -extern PFN_vkGetDisplayModeProperties2KHR vkGetDisplayModeProperties2KHR; -extern PFN_vkGetDisplayPlaneCapabilities2KHR vkGetDisplayPlaneCapabilities2KHR; -extern PFN_vkGetPhysicalDeviceDisplayPlaneProperties2KHR vkGetPhysicalDeviceDisplayPlaneProperties2KHR; -extern PFN_vkGetPhysicalDeviceDisplayProperties2KHR vkGetPhysicalDeviceDisplayProperties2KHR; -#endif /* defined(VK_KHR_get_display_properties2) */ -#if defined(VK_KHR_get_memory_requirements2) -extern PFN_vkGetBufferMemoryRequirements2KHR vkGetBufferMemoryRequirements2KHR; -extern PFN_vkGetImageMemoryRequirements2KHR vkGetImageMemoryRequirements2KHR; -extern PFN_vkGetImageSparseMemoryRequirements2KHR vkGetImageSparseMemoryRequirements2KHR; -#endif /* defined(VK_KHR_get_memory_requirements2) */ -#if defined(VK_KHR_get_physical_device_properties2) -extern PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR; -extern PFN_vkGetPhysicalDeviceFormatProperties2KHR vkGetPhysicalDeviceFormatProperties2KHR; -extern PFN_vkGetPhysicalDeviceImageFormatProperties2KHR vkGetPhysicalDeviceImageFormatProperties2KHR; -extern PFN_vkGetPhysicalDeviceMemoryProperties2KHR vkGetPhysicalDeviceMemoryProperties2KHR; -extern PFN_vkGetPhysicalDeviceProperties2KHR vkGetPhysicalDeviceProperties2KHR; -extern PFN_vkGetPhysicalDeviceQueueFamilyProperties2KHR vkGetPhysicalDeviceQueueFamilyProperties2KHR; -extern PFN_vkGetPhysicalDeviceSparseImageFormatProperties2KHR vkGetPhysicalDeviceSparseImageFormatProperties2KHR; -#endif /* defined(VK_KHR_get_physical_device_properties2) */ -#if defined(VK_KHR_get_surface_capabilities2) -extern PFN_vkGetPhysicalDeviceSurfaceCapabilities2KHR vkGetPhysicalDeviceSurfaceCapabilities2KHR; -extern PFN_vkGetPhysicalDeviceSurfaceFormats2KHR vkGetPhysicalDeviceSurfaceFormats2KHR; -#endif /* defined(VK_KHR_get_surface_capabilities2) */ -#if defined(VK_KHR_maintenance1) -extern PFN_vkTrimCommandPoolKHR vkTrimCommandPoolKHR; -#endif /* defined(VK_KHR_maintenance1) */ -#if defined(VK_KHR_maintenance3) -extern PFN_vkGetDescriptorSetLayoutSupportKHR vkGetDescriptorSetLayoutSupportKHR; -#endif /* defined(VK_KHR_maintenance3) */ -#if defined(VK_KHR_maintenance4) -extern PFN_vkGetDeviceBufferMemoryRequirementsKHR vkGetDeviceBufferMemoryRequirementsKHR; -extern PFN_vkGetDeviceImageMemoryRequirementsKHR vkGetDeviceImageMemoryRequirementsKHR; -extern PFN_vkGetDeviceImageSparseMemoryRequirementsKHR vkGetDeviceImageSparseMemoryRequirementsKHR; -#endif /* defined(VK_KHR_maintenance4) */ -#if defined(VK_KHR_performance_query) -extern PFN_vkAcquireProfilingLockKHR vkAcquireProfilingLockKHR; -extern PFN_vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR vkEnumeratePhysicalDeviceQueueFamilyPerformanceQueryCountersKHR; -extern PFN_vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR vkGetPhysicalDeviceQueueFamilyPerformanceQueryPassesKHR; -extern PFN_vkReleaseProfilingLockKHR vkReleaseProfilingLockKHR; -#endif /* defined(VK_KHR_performance_query) */ -#if defined(VK_KHR_pipeline_executable_properties) -extern PFN_vkGetPipelineExecutableInternalRepresentationsKHR vkGetPipelineExecutableInternalRepresentationsKHR; -extern PFN_vkGetPipelineExecutablePropertiesKHR vkGetPipelineExecutablePropertiesKHR; -extern PFN_vkGetPipelineExecutableStatisticsKHR vkGetPipelineExecutableStatisticsKHR; -#endif /* defined(VK_KHR_pipeline_executable_properties) */ -#if defined(VK_KHR_present_wait) -extern PFN_vkWaitForPresentKHR vkWaitForPresentKHR; -#endif /* defined(VK_KHR_present_wait) */ -#if defined(VK_KHR_push_descriptor) -extern PFN_vkCmdPushDescriptorSetKHR vkCmdPushDescriptorSetKHR; -#endif /* defined(VK_KHR_push_descriptor) */ -#if defined(VK_KHR_ray_tracing_pipeline) -extern PFN_vkCmdSetRayTracingPipelineStackSizeKHR vkCmdSetRayTracingPipelineStackSizeKHR; -extern PFN_vkCmdTraceRaysIndirectKHR vkCmdTraceRaysIndirectKHR; -extern PFN_vkCmdTraceRaysKHR vkCmdTraceRaysKHR; -extern PFN_vkCreateRayTracingPipelinesKHR vkCreateRayTracingPipelinesKHR; -extern PFN_vkGetRayTracingCaptureReplayShaderGroupHandlesKHR vkGetRayTracingCaptureReplayShaderGroupHandlesKHR; -extern PFN_vkGetRayTracingShaderGroupHandlesKHR vkGetRayTracingShaderGroupHandlesKHR; -extern PFN_vkGetRayTracingShaderGroupStackSizeKHR vkGetRayTracingShaderGroupStackSizeKHR; -#endif /* defined(VK_KHR_ray_tracing_pipeline) */ -#if defined(VK_KHR_sampler_ycbcr_conversion) -extern PFN_vkCreateSamplerYcbcrConversionKHR vkCreateSamplerYcbcrConversionKHR; -extern PFN_vkDestroySamplerYcbcrConversionKHR vkDestroySamplerYcbcrConversionKHR; -#endif /* defined(VK_KHR_sampler_ycbcr_conversion) */ -#if defined(VK_KHR_shared_presentable_image) -extern PFN_vkGetSwapchainStatusKHR vkGetSwapchainStatusKHR; -#endif /* defined(VK_KHR_shared_presentable_image) */ -#if defined(VK_KHR_surface) -extern PFN_vkDestroySurfaceKHR vkDestroySurfaceKHR; -extern PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR; -extern PFN_vkGetPhysicalDeviceSurfaceFormatsKHR vkGetPhysicalDeviceSurfaceFormatsKHR; -extern PFN_vkGetPhysicalDeviceSurfacePresentModesKHR vkGetPhysicalDeviceSurfacePresentModesKHR; -extern PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR; -#endif /* defined(VK_KHR_surface) */ -#if defined(VK_KHR_swapchain) -extern PFN_vkAcquireNextImageKHR vkAcquireNextImageKHR; -extern PFN_vkCreateSwapchainKHR vkCreateSwapchainKHR; -extern PFN_vkDestroySwapchainKHR vkDestroySwapchainKHR; -extern PFN_vkGetSwapchainImagesKHR vkGetSwapchainImagesKHR; -extern PFN_vkQueuePresentKHR vkQueuePresentKHR; -#endif /* defined(VK_KHR_swapchain) */ -#if defined(VK_KHR_synchronization2) -extern PFN_vkCmdPipelineBarrier2KHR vkCmdPipelineBarrier2KHR; -extern PFN_vkCmdResetEvent2KHR vkCmdResetEvent2KHR; -extern PFN_vkCmdSetEvent2KHR vkCmdSetEvent2KHR; -extern PFN_vkCmdWaitEvents2KHR vkCmdWaitEvents2KHR; -extern PFN_vkCmdWriteTimestamp2KHR vkCmdWriteTimestamp2KHR; -extern PFN_vkQueueSubmit2KHR vkQueueSubmit2KHR; -#endif /* defined(VK_KHR_synchronization2) */ -#if defined(VK_KHR_synchronization2) && defined(VK_AMD_buffer_marker) -extern PFN_vkCmdWriteBufferMarker2AMD vkCmdWriteBufferMarker2AMD; -#endif /* defined(VK_KHR_synchronization2) && defined(VK_AMD_buffer_marker) */ -#if defined(VK_KHR_synchronization2) && defined(VK_NV_device_diagnostic_checkpoints) -extern PFN_vkGetQueueCheckpointData2NV vkGetQueueCheckpointData2NV; -#endif /* defined(VK_KHR_synchronization2) && defined(VK_NV_device_diagnostic_checkpoints) */ -#if defined(VK_KHR_timeline_semaphore) -extern PFN_vkGetSemaphoreCounterValueKHR vkGetSemaphoreCounterValueKHR; -extern PFN_vkSignalSemaphoreKHR vkSignalSemaphoreKHR; -extern PFN_vkWaitSemaphoresKHR vkWaitSemaphoresKHR; -#endif /* defined(VK_KHR_timeline_semaphore) */ -#if defined(VK_KHR_video_decode_queue) -extern PFN_vkCmdDecodeVideoKHR vkCmdDecodeVideoKHR; -#endif /* defined(VK_KHR_video_decode_queue) */ -#if defined(VK_KHR_video_encode_queue) -extern PFN_vkCmdEncodeVideoKHR vkCmdEncodeVideoKHR; -#endif /* defined(VK_KHR_video_encode_queue) */ -#if defined(VK_KHR_video_queue) -extern PFN_vkBindVideoSessionMemoryKHR vkBindVideoSessionMemoryKHR; -extern PFN_vkCmdBeginVideoCodingKHR vkCmdBeginVideoCodingKHR; -extern PFN_vkCmdControlVideoCodingKHR vkCmdControlVideoCodingKHR; -extern PFN_vkCmdEndVideoCodingKHR vkCmdEndVideoCodingKHR; -extern PFN_vkCreateVideoSessionKHR vkCreateVideoSessionKHR; -extern PFN_vkCreateVideoSessionParametersKHR vkCreateVideoSessionParametersKHR; -extern PFN_vkDestroyVideoSessionKHR vkDestroyVideoSessionKHR; -extern PFN_vkDestroyVideoSessionParametersKHR vkDestroyVideoSessionParametersKHR; -extern PFN_vkGetPhysicalDeviceVideoCapabilitiesKHR vkGetPhysicalDeviceVideoCapabilitiesKHR; -extern PFN_vkGetPhysicalDeviceVideoFormatPropertiesKHR vkGetPhysicalDeviceVideoFormatPropertiesKHR; -extern PFN_vkGetVideoSessionMemoryRequirementsKHR vkGetVideoSessionMemoryRequirementsKHR; -extern PFN_vkUpdateVideoSessionParametersKHR vkUpdateVideoSessionParametersKHR; -#endif /* defined(VK_KHR_video_queue) */ -#if defined(VK_KHR_wayland_surface) -extern PFN_vkCreateWaylandSurfaceKHR vkCreateWaylandSurfaceKHR; -extern PFN_vkGetPhysicalDeviceWaylandPresentationSupportKHR vkGetPhysicalDeviceWaylandPresentationSupportKHR; -#endif /* defined(VK_KHR_wayland_surface) */ -#if defined(VK_KHR_win32_surface) -extern PFN_vkCreateWin32SurfaceKHR vkCreateWin32SurfaceKHR; -extern PFN_vkGetPhysicalDeviceWin32PresentationSupportKHR vkGetPhysicalDeviceWin32PresentationSupportKHR; -#endif /* defined(VK_KHR_win32_surface) */ -#if defined(VK_KHR_xcb_surface) -extern PFN_vkCreateXcbSurfaceKHR vkCreateXcbSurfaceKHR; -extern PFN_vkGetPhysicalDeviceXcbPresentationSupportKHR vkGetPhysicalDeviceXcbPresentationSupportKHR; -#endif /* defined(VK_KHR_xcb_surface) */ -#if defined(VK_KHR_xlib_surface) -extern PFN_vkCreateXlibSurfaceKHR vkCreateXlibSurfaceKHR; -extern PFN_vkGetPhysicalDeviceXlibPresentationSupportKHR vkGetPhysicalDeviceXlibPresentationSupportKHR; -#endif /* defined(VK_KHR_xlib_surface) */ -#if defined(VK_MVK_ios_surface) -extern PFN_vkCreateIOSSurfaceMVK vkCreateIOSSurfaceMVK; -#endif /* defined(VK_MVK_ios_surface) */ -#if defined(VK_MVK_macos_surface) -extern PFN_vkCreateMacOSSurfaceMVK vkCreateMacOSSurfaceMVK; -#endif /* defined(VK_MVK_macos_surface) */ -#if defined(VK_NN_vi_surface) -extern PFN_vkCreateViSurfaceNN vkCreateViSurfaceNN; -#endif /* defined(VK_NN_vi_surface) */ -#if defined(VK_NVX_binary_import) -extern PFN_vkCmdCuLaunchKernelNVX vkCmdCuLaunchKernelNVX; -extern PFN_vkCreateCuFunctionNVX vkCreateCuFunctionNVX; -extern PFN_vkCreateCuModuleNVX vkCreateCuModuleNVX; -extern PFN_vkDestroyCuFunctionNVX vkDestroyCuFunctionNVX; -extern PFN_vkDestroyCuModuleNVX vkDestroyCuModuleNVX; -#endif /* defined(VK_NVX_binary_import) */ -#if defined(VK_NVX_image_view_handle) -extern PFN_vkGetImageViewAddressNVX vkGetImageViewAddressNVX; -extern PFN_vkGetImageViewHandleNVX vkGetImageViewHandleNVX; -#endif /* defined(VK_NVX_image_view_handle) */ -#if defined(VK_NV_acquire_winrt_display) -extern PFN_vkAcquireWinrtDisplayNV vkAcquireWinrtDisplayNV; -extern PFN_vkGetWinrtDisplayNV vkGetWinrtDisplayNV; -#endif /* defined(VK_NV_acquire_winrt_display) */ -#if defined(VK_NV_clip_space_w_scaling) -extern PFN_vkCmdSetViewportWScalingNV vkCmdSetViewportWScalingNV; -#endif /* defined(VK_NV_clip_space_w_scaling) */ -#if defined(VK_NV_cooperative_matrix) -extern PFN_vkGetPhysicalDeviceCooperativeMatrixPropertiesNV vkGetPhysicalDeviceCooperativeMatrixPropertiesNV; -#endif /* defined(VK_NV_cooperative_matrix) */ -#if defined(VK_NV_coverage_reduction_mode) -extern PFN_vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV; -#endif /* defined(VK_NV_coverage_reduction_mode) */ -#if defined(VK_NV_device_diagnostic_checkpoints) -extern PFN_vkCmdSetCheckpointNV vkCmdSetCheckpointNV; -extern PFN_vkGetQueueCheckpointDataNV vkGetQueueCheckpointDataNV; -#endif /* defined(VK_NV_device_diagnostic_checkpoints) */ -#if defined(VK_NV_device_generated_commands) -extern PFN_vkCmdBindPipelineShaderGroupNV vkCmdBindPipelineShaderGroupNV; -extern PFN_vkCmdExecuteGeneratedCommandsNV vkCmdExecuteGeneratedCommandsNV; -extern PFN_vkCmdPreprocessGeneratedCommandsNV vkCmdPreprocessGeneratedCommandsNV; -extern PFN_vkCreateIndirectCommandsLayoutNV vkCreateIndirectCommandsLayoutNV; -extern PFN_vkDestroyIndirectCommandsLayoutNV vkDestroyIndirectCommandsLayoutNV; -extern PFN_vkGetGeneratedCommandsMemoryRequirementsNV vkGetGeneratedCommandsMemoryRequirementsNV; -#endif /* defined(VK_NV_device_generated_commands) */ -#if defined(VK_NV_external_memory_capabilities) -extern PFN_vkGetPhysicalDeviceExternalImageFormatPropertiesNV vkGetPhysicalDeviceExternalImageFormatPropertiesNV; -#endif /* defined(VK_NV_external_memory_capabilities) */ -#if defined(VK_NV_external_memory_rdma) -extern PFN_vkGetMemoryRemoteAddressNV vkGetMemoryRemoteAddressNV; -#endif /* defined(VK_NV_external_memory_rdma) */ -#if defined(VK_NV_external_memory_win32) -extern PFN_vkGetMemoryWin32HandleNV vkGetMemoryWin32HandleNV; -#endif /* defined(VK_NV_external_memory_win32) */ -#if defined(VK_NV_fragment_shading_rate_enums) -extern PFN_vkCmdSetFragmentShadingRateEnumNV vkCmdSetFragmentShadingRateEnumNV; -#endif /* defined(VK_NV_fragment_shading_rate_enums) */ -#if defined(VK_NV_mesh_shader) -extern PFN_vkCmdDrawMeshTasksIndirectCountNV vkCmdDrawMeshTasksIndirectCountNV; -extern PFN_vkCmdDrawMeshTasksIndirectNV vkCmdDrawMeshTasksIndirectNV; -extern PFN_vkCmdDrawMeshTasksNV vkCmdDrawMeshTasksNV; -#endif /* defined(VK_NV_mesh_shader) */ -#if defined(VK_NV_ray_tracing) -extern PFN_vkBindAccelerationStructureMemoryNV vkBindAccelerationStructureMemoryNV; -extern PFN_vkCmdBuildAccelerationStructureNV vkCmdBuildAccelerationStructureNV; -extern PFN_vkCmdCopyAccelerationStructureNV vkCmdCopyAccelerationStructureNV; -extern PFN_vkCmdTraceRaysNV vkCmdTraceRaysNV; -extern PFN_vkCmdWriteAccelerationStructuresPropertiesNV vkCmdWriteAccelerationStructuresPropertiesNV; -extern PFN_vkCompileDeferredNV vkCompileDeferredNV; -extern PFN_vkCreateAccelerationStructureNV vkCreateAccelerationStructureNV; -extern PFN_vkCreateRayTracingPipelinesNV vkCreateRayTracingPipelinesNV; -extern PFN_vkDestroyAccelerationStructureNV vkDestroyAccelerationStructureNV; -extern PFN_vkGetAccelerationStructureHandleNV vkGetAccelerationStructureHandleNV; -extern PFN_vkGetAccelerationStructureMemoryRequirementsNV vkGetAccelerationStructureMemoryRequirementsNV; -extern PFN_vkGetRayTracingShaderGroupHandlesNV vkGetRayTracingShaderGroupHandlesNV; -#endif /* defined(VK_NV_ray_tracing) */ -#if defined(VK_NV_scissor_exclusive) -extern PFN_vkCmdSetExclusiveScissorNV vkCmdSetExclusiveScissorNV; -#endif /* defined(VK_NV_scissor_exclusive) */ -#if defined(VK_NV_shading_rate_image) -extern PFN_vkCmdBindShadingRateImageNV vkCmdBindShadingRateImageNV; -extern PFN_vkCmdSetCoarseSampleOrderNV vkCmdSetCoarseSampleOrderNV; -extern PFN_vkCmdSetViewportShadingRatePaletteNV vkCmdSetViewportShadingRatePaletteNV; -#endif /* defined(VK_NV_shading_rate_image) */ -#if defined(VK_QNX_screen_surface) -extern PFN_vkCreateScreenSurfaceQNX vkCreateScreenSurfaceQNX; -extern PFN_vkGetPhysicalDeviceScreenPresentationSupportQNX vkGetPhysicalDeviceScreenPresentationSupportQNX; -#endif /* defined(VK_QNX_screen_surface) */ -#if (defined(VK_EXT_full_screen_exclusive) && defined(VK_KHR_device_group)) || (defined(VK_EXT_full_screen_exclusive) && defined(VK_VERSION_1_1)) -extern PFN_vkGetDeviceGroupSurfacePresentModes2EXT vkGetDeviceGroupSurfacePresentModes2EXT; -#endif /* (defined(VK_EXT_full_screen_exclusive) && defined(VK_KHR_device_group)) || (defined(VK_EXT_full_screen_exclusive) && defined(VK_VERSION_1_1)) */ -#if (defined(VK_KHR_descriptor_update_template) && defined(VK_KHR_push_descriptor)) || (defined(VK_KHR_push_descriptor) && defined(VK_VERSION_1_1)) || (defined(VK_KHR_push_descriptor) && defined(VK_KHR_descriptor_update_template)) -extern PFN_vkCmdPushDescriptorSetWithTemplateKHR vkCmdPushDescriptorSetWithTemplateKHR; -#endif /* (defined(VK_KHR_descriptor_update_template) && defined(VK_KHR_push_descriptor)) || (defined(VK_KHR_push_descriptor) && defined(VK_VERSION_1_1)) || (defined(VK_KHR_push_descriptor) && defined(VK_KHR_descriptor_update_template)) */ -#if (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) -extern PFN_vkGetDeviceGroupPresentCapabilitiesKHR vkGetDeviceGroupPresentCapabilitiesKHR; -extern PFN_vkGetDeviceGroupSurfacePresentModesKHR vkGetDeviceGroupSurfacePresentModesKHR; -extern PFN_vkGetPhysicalDevicePresentRectanglesKHR vkGetPhysicalDevicePresentRectanglesKHR; -#endif /* (defined(VK_KHR_device_group) && defined(VK_KHR_surface)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) */ -#if (defined(VK_KHR_device_group) && defined(VK_KHR_swapchain)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) -extern PFN_vkAcquireNextImage2KHR vkAcquireNextImage2KHR; -#endif /* (defined(VK_KHR_device_group) && defined(VK_KHR_swapchain)) || (defined(VK_KHR_swapchain) && defined(VK_VERSION_1_1)) */ -/* VOLK_GENERATE_PROTOTYPES_H */ - -#ifdef __cplusplus -} -#endif - -#endif - -#ifdef VOLK_IMPLEMENTATION -#undef VOLK_IMPLEMENTATION -// Prevent tools like dependency checkers that don't evaluate -// macros from detecting a cyclic dependency. -#define VOLK_SOURCE "volk.c" -#include VOLK_SOURCE -#endif - -/** - * Copyright (c) 2018-2019 Arseny Kapoulkine - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. -*/ -/* clang-format on */ diff --git a/SDK/Android/drawable-hdpi/ic_launcher.png b/SDK/Android/drawable-hdpi/ic_launcher.png deleted file mode 100644 index fd5b6dd9529..00000000000 Binary files a/SDK/Android/drawable-hdpi/ic_launcher.png and /dev/null differ diff --git a/SDK/Android/drawable-ldpi/ic_launcher.png b/SDK/Android/drawable-ldpi/ic_launcher.png deleted file mode 100644 index 42a5f40bcf4..00000000000 Binary files a/SDK/Android/drawable-ldpi/ic_launcher.png and /dev/null differ diff --git a/SDK/Android/drawable-mdpi/ic_launcher.png b/SDK/Android/drawable-mdpi/ic_launcher.png deleted file mode 100644 index a849a7c0f0b..00000000000 Binary files a/SDK/Android/drawable-mdpi/ic_launcher.png and /dev/null differ diff --git a/SDK/Android/drawable-xhdpi/ic_launcher.png b/SDK/Android/drawable-xhdpi/ic_launcher.png deleted file mode 100644 index 85b240e3490..00000000000 Binary files a/SDK/Android/drawable-xhdpi/ic_launcher.png and /dev/null differ diff --git a/SDK/Dockerfile b/SDK/Dockerfile deleted file mode 100644 index 06b8e4b17dc..00000000000 --- a/SDK/Dockerfile +++ /dev/null @@ -1,7 +0,0 @@ -FROM quay.io/pypa/manylinux2014_x86_64:latest -RUN yum install -y zlib-devel libXrandr-devel mesa-libEGL-devel vulkan-devel -WORKDIR / -RUN curl -LO https://sdk.lunarg.com/sdk/download/1.3.224.1/linux/vulkansdk-linux-x86_64-1.3.224.1.tar.gz && tar xvf vulkansdk-linux-x86_64-1.3.224.1.tar.gz -ENV VULKAN_SDK=/1.3.224.1/x86_64/ -WORKDIR /workspace -CMD PATH="/opt/python/$PYVER/bin/:$PATH" pip wheel . --verbose \ No newline at end of file diff --git a/Samples/AndroidJNI/AndroidTextureOES.java b/Samples/AndroidJNI/AndroidTextureOES.java deleted file mode 100644 index 190582eca61..00000000000 --- a/Samples/AndroidJNI/AndroidTextureOES.java +++ /dev/null @@ -1,193 +0,0 @@ -package org.ogre.example; - -import android.content.pm.ActivityInfo; - -import android.Manifest; -import android.content.pm.PackageManager; -import androidx.core.app.ActivityCompat; -import androidx.core.content.ContextCompat; - -import android.graphics.SurfaceTexture; -import android.app.Activity; -import android.os.Bundle; -import android.os.Handler; -import android.view.Surface; -import android.view.SurfaceHolder; -import android.view.SurfaceView; - -import org.ogre.*; - -public class AndroidTextureOES extends Activity { - - static { - System.loadLibrary("OgreJNI"); - } - - private Handler handler = new Handler(); - private ApplicationContext ogre = new ApplicationContext(); - private SurfaceTexture cameraTexture; - - private Surface lastSurface; - private SurfaceView surfaceView; - private Rectangle2D rect; - - private boolean windowCreated = false; - private boolean renderSessionPaused = true; - private boolean sceneCreated = false; - - private long textureId = -1L; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - surfaceView = new SurfaceView(this); - setContentView(surfaceView); - setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); - - surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() { - - @Override - public void surfaceCreated(SurfaceHolder holder) { - if (holder.getSurface() != null && holder.getSurface().isValid()) { - lastSurface = holder.getSurface(); - handler.post(renderer); - } - } - - @Override - public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { - } - - @Override - public void surfaceDestroyed(SurfaceHolder holder) { - windowCreated = false; - ogre.getRenderWindow()._notifySurfaceDestroyed(); - } - }); - } - - @Override - protected void onResume() { - super.onResume(); - renderSessionPaused = false; - handler.post(renderer); - } - - @Override - protected void onPause() { - renderSessionPaused = true; - super.onPause(); - } - - private void initializeScene() { - sceneCreated = true; - - final SceneManager scnMgr = ogre.getRoot().createSceneManager(); - ShaderGenerator.getSingleton().addSceneManager(scnMgr); - - final Light light = scnMgr.createLight("MainLight"); - - final SceneNode lightNode = scnMgr.getRootSceneNode().createChildSceneNode(); - lightNode.setPosition(0f, 10f, 15f); - lightNode.attachObject(light); - - final Camera camera = scnMgr.createCamera("Camera"); - camera.setNearClipDistance(5f); - camera.setAutoAspectRatio(true); - - final SceneNode cameraNode = scnMgr.getRootSceneNode().createChildSceneNode(); - cameraNode.attachObject(camera); - cameraNode.setPosition(0f, 0f, 15f); - - final MaterialPtr material = MaterialManager.getSingleton().create("PlaneMat", Ogre.getRGN_DEFAULT()); - - final Pass pass = material.getTechniques().get(0).getPass(0); - pass.setDepthCheckEnabled(false); - pass.setDepthWriteEnabled(false); - pass.setLightingEnabled(false); - - final TexturePtr texturePtr = TextureManager.getSingleton().createManual( - "SomeTexture", Ogre.getRGN_DEFAULT(), - TextureType.TEX_TYPE_EXTERNAL_OES, - 1080, - 1920, - 1, - 0, - PixelFormat.PF_UNKNOWN - ); - - textureId = texturePtr.getCustomAttribute("GLID"); - - pass.createTextureUnitState().setTexture(texturePtr); - - final AxisAlignedBox bb = new AxisAlignedBox(); - bb.setInfinite(); - - rect = scnMgr.createScreenSpaceRect(true); - // 90 deg rotate: - rect.setUVs(new Vector2(0, 1), new Vector2(1, 1), new Vector2(0, 0), new Vector2(1, 0)); - rect.setMaterial(material); - rect.setRenderQueueGroup((short)RenderQueueGroupID.RENDER_QUEUE_BACKGROUND.swigValue()); - rect.setBoundingBox(bb); - - final SceneNode rectNode = scnMgr.getRootSceneNode().createChildSceneNode(); - rectNode.attachObject(rect); - - final Entity ogreEntity = scnMgr.createEntity("Sinbad.mesh"); - final SceneNode ogreNode = scnMgr.getRootSceneNode().createChildSceneNode(); - ogreNode.attachObject(ogreEntity); - ogreNode.setPosition(new Vector3(0f, 0f, 0f)); - ogreNode.scale(0.5f, 0.5f, 0.5f); - - ogre.getRenderWindow().addViewport(camera); - } - - private Runnable renderer = new Runnable() { - @Override - public void run() { - if (renderSessionPaused) { - return; - } - - if (!windowCreated && lastSurface != null) { - windowCreated = true; - - if (!sceneCreated) { - ogre.initAppForAndroid(getAssets(), lastSurface); - initializeScene(); - - if (ContextCompat.checkSelfPermission(AndroidTextureOES.this, Manifest.permission.CAMERA) - == PackageManager.PERMISSION_DENIED) - { - ActivityCompat.requestPermissions(AndroidTextureOES.this, new String[] {Manifest.permission.CAMERA}, 100); - } - - final android.hardware.Camera camera = android.hardware.Camera.open(); - try { - cameraTexture = new SurfaceTexture((int) textureId); - camera.setPreviewTexture(cameraTexture); - final android.hardware.Camera.Parameters params = camera.getParameters(); - final android.hardware.Camera.Size size = params.getSupportedPreviewSizes().get(0); - params.setPreviewSize(size.width, size.height); - camera.setParameters(params); - camera.startPreview(); - } catch (Exception e) { - throw new RuntimeException("An error occurred during camera preview initialization"); - } - } else { - ogre.getRenderWindow()._notifySurfaceCreated(lastSurface); - } - - handler.post(this); - return; - } - - if (windowCreated) { - cameraTexture.updateTexImage(); - ogre.getRoot().renderOneFrame(); - } - - handler.post(this); - } - }; -} diff --git a/Samples/AndroidJNI/BasicSample.java b/Samples/AndroidJNI/BasicSample.java deleted file mode 100644 index 6ebfa57443c..00000000000 --- a/Samples/AndroidJNI/BasicSample.java +++ /dev/null @@ -1,225 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -package org.ogre.example; - -import org.ogre.*; - -import android.app.Activity; -import android.os.Bundle; -import android.os.Handler; -import android.view.MotionEvent; -import android.view.Surface; -import android.view.SurfaceHolder; -import android.view.SurfaceHolder.Callback; -import android.view.SurfaceView; -import android.content.res.AssetManager; - -public class BasicSample extends Activity { - protected Handler handler = null; - protected SurfaceView surfaceView = null; - protected Surface lastSurface = null; - - private Runnable renderer = null; - private boolean paused = false; - private boolean initOGRE = false; - private AssetManager assetMgr = null; - - ApplicationContext ogreApp = null; - CameraMan camman = null; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - handler = new Handler(); - sysInit(); - } - - @Override - protected void onPause() { - super.onPause(); - handler.removeCallbacks(renderer); - paused = true; - } - - @Override - protected void onResume() { - super.onResume(); - paused = false; - handler.post(renderer); - } - - @Override - protected void onDestroy() { - super.onDestroy(); - - Runnable destroyer = new Runnable() { - public void run() { - ogreApp.shutdown(); - } - }; - handler.post(destroyer); - } - - private void sysInit() { - final Runnable initRunnable = new Runnable() { - public void run() { - if (!initOGRE) { - initOGRE = true; - - if(assetMgr == null) { - assetMgr = getResources().getAssets(); - } - - renderer = new Runnable() { - public void run() { - - if (paused) - return; - - if (!wndCreate && lastSurface != null) { - wndCreate = true; - - if(ogreApp == null) { - ogreApp = new ApplicationContext(); - ogreApp.initAppForAndroid(assetMgr, lastSurface); - - SceneManager scnMgr = ogreApp.getRoot().createSceneManager(); - ShaderGenerator.getSingleton().addSceneManager(scnMgr); - - Light light = scnMgr.createLight("MainLight"); - SceneNode lightnode = scnMgr.getRootSceneNode().createChildSceneNode(); - lightnode.setPosition(0, 10, 15); - lightnode.attachObject(light); - - Camera cam = scnMgr.createCamera("myCam"); - cam.setNearClipDistance(5); - cam.setAutoAspectRatio(true); - - SceneNode camnode = scnMgr.getRootSceneNode().createChildSceneNode(); - camnode.attachObject(cam); - camnode.setPosition(0, 0, 15); - - camman = new CameraMan(camnode); - ogreApp.addInputListener(camman); - - Entity ent = scnMgr.createEntity("Sinbad.mesh"); - SceneNode node = scnMgr.getRootSceneNode().createChildSceneNode(); - node.attachObject(ent); - - Viewport vp = ogreApp.getRenderWindow().addViewport(cam); - vp.setBackgroundColour(new ColourValue(0.3f, 0.3f, 0.3f)); - } else { - ogreApp.getRenderWindow()._notifySurfaceCreated(lastSurface); - } - - handler.post(this); - return; - } - - if (initOGRE && wndCreate) { - ogreApp.getRoot().renderOneFrame(); - } - - handler.post(this); - } - }; - - handler.post(renderer); - } - } - - }; - - SurfaceView view = new SurfaceView(this); - SurfaceHolder holder = view.getHolder(); - surfaceView = view; - - holder.addCallback(new Callback() { - public void surfaceCreated(SurfaceHolder holder) { - if (holder.getSurface() != null - && holder.getSurface().isValid()) { - lastSurface = holder.getSurface(); - handler.post(initRunnable); - } - } - - public void surfaceDestroyed(SurfaceHolder holder) { - if (initOGRE && wndCreate) { - wndCreate = false; - lastSurface = null; - handler.post(new Runnable() { - public void run() { - ogreApp.getRenderWindow()._notifySurfaceDestroyed(); - } - }); - } - } - - public void surfaceChanged(SurfaceHolder holder, int format, - int width, int height) { - - } - }); - setContentView(surfaceView); - } - - boolean wndCreate = false; - - private int previousX = -1; - private int previousY = -1; - - @Override - public boolean onTouchEvent(MotionEvent e) { - if(ogreApp == null) - return true; - - if(e.getAction() == MotionEvent.ACTION_MOVE) - { - // Convert to Ogre Event types, so we can use C++ Listeners like CameraMan - // you could also just modify camnode here yourself - MouseMotionEvent mme = new MouseMotionEvent(); - mme.setXrel((int) e.getX() - previousX); - mme.setYrel((int) e.getY() - previousY); - mme.setType(EventType.MOUSEMOTION.swigValue()); - - Event ogreEvt = new Event(); - ogreEvt.setMotion(mme); - ogreApp._fireInputEvent(ogreEvt, 0); - } - - previousX = (int)e.getX(); - previousY = (int)e.getY(); - - return true; - } - - static { - System.loadLibrary("OgreJNI"); - } -} diff --git a/Samples/AndroidJNI/CMakeLists.txt b/Samples/AndroidJNI/CMakeLists.txt deleted file mode 100644 index 4a7f500ac14..00000000000 --- a/Samples/AndroidJNI/CMakeLists.txt +++ /dev/null @@ -1,50 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Include the CreateAndroidProj macro to create a basic android setup -# and add_static_libs macro to define additional target static libs -include(AndroidMacros) - -if(ANDROID AND OGRE_BUILD_COMPONENT_JAVA) - # Setup create_android_proj macro requirements - SET(ANDROID_MOD_NAME "OgreJNI") - SET(JNI_PATH ".") - #SET(JNI_SRC_FILES "OgreActivityJNI.cpp") - - SET(NDKOUT "${CMAKE_BINARY_DIR}/${ANDROID_MOD_NAME}") - - SET(PKG_NAME "org.ogre.jni") - - # Set this variable to false if no java code will be present (google android:hasCode for more info) - SET(HAS_CODE "true") - - SET(MAIN_ACTIVITY "org.ogre.example.BasicSample") - SET(EXTRA_ACTIVITIES "org.ogre.example.AndroidTextureOES") - SET(ANDROID_ADDITIONAL_PERMISSION "") - SET(HEADERS "") - SET(SAMPLE_LDLIBS "") - - # Copy and create resource files - file(COPY "${JNI_PATH}/BasicSample.java" DESTINATION "${NDKOUT}/app/src/main/java/org/ogre/example") - file(COPY "${JNI_PATH}/AndroidTextureOES.java" DESTINATION "${NDKOUT}/app/src/main/java/org/ogre/example") - - copy_assets_to_android_proj() - - # Create CMake target - file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/dummyJNI.cpp "int x = 23;") - ADD_LIBRARY(OgreJNIDummy SHARED ${CMAKE_CURRENT_BINARY_DIR}/dummyJNI.cpp) - add_dependencies(OgreJNIDummy OgreJNI) - - # copy the SDK - add_custom_command(TARGET OgreJNIDummy PRE_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_directory "${PROJECT_BINARY_DIR}/java" "${NDKOUT}") - - # set(JNI_PATH "${NDKOUT}/jni") - create_android_proj(OgreJNIDummy) -endif() diff --git a/Samples/Browser/CMakeLists.txt b/Samples/Browser/CMakeLists.txt deleted file mode 100644 index 6e7bd4a1ca9..00000000000 --- a/Samples/Browser/CMakeLists.txt +++ /dev/null @@ -1,299 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure Browser demo build - -set (HEADER_FILES - ${PROJECT_SOURCE_DIR}/Samples/Browser/include/SampleBrowser.h - ${PROJECT_SOURCE_DIR}/Samples/Common/include/Sample.h - ${PROJECT_SOURCE_DIR}/Samples/Common/include/SampleContext.h - ${PROJECT_SOURCE_DIR}/Samples/Common/include/SamplePlugin.h - ${PROJECT_SOURCE_DIR}/Samples/Common/include/SdkSample.h -) - -# Get the list of configured samples -get_property(OGRE_SAMPLES_LIST GLOBAL PROPERTY "OGRE_SAMPLES_LIST") - -if (APPLE AND APPLE_IOS) - set(HEADER_FILES ${HEADER_FILES} - ${PROJECT_SOURCE_DIR}/Samples/Browser/include/SampleBrowser_iOS.h - ) -elseif (APPLE) - set(HEADER_FILES ${HEADER_FILES} - ${PROJECT_SOURCE_DIR}/Samples/Common/misc/SampleBrowser_OSX.icns - ) -endif () - -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) - -if (WINDOWS_STORE OR WINDOWS_PHONE) - - # Inspired by http://cmakems.codeplex.com/SourceControl/latest#Tests/VSWinStorePhone/CMakeLists.txt - - # Generate manifest. - set(EXE_NAME SampleBrowser) - set(SHORT_NAME ${EXE_NAME}) - set(PACKAGE_GUID "ef31484f-4f23-4b9f-8748-af5482696ae5") - set(APP_MANIFEST_NAME Package.appxmanifest) - configure_file( - ${OGRE_TEMPLATES_DIR}/Package_vc1900.WindowsStore.appxmanifest.in - ${CMAKE_CURRENT_BINARY_DIR}/${APP_MANIFEST_NAME} - @ONLY) - - # Make symlink to Media folder - if( NOT EXISTS "${CMAKE_CURRENT_BINARY_DIR}/Media") - # Get OS dependent path to use in `execute_process` - file(TO_NATIVE_PATH "${CMAKE_CURRENT_BINARY_DIR}/Media" link) - file(TO_NATIVE_PATH "${PROJECT_SOURCE_DIR}/Samples/Media" target) - execute_process( COMMAND cmd.exe /c mklink /J ${link} ${target}) - endif() - - # Copy other resources - file(COPY - ${SDL2_BINARY} - - ${PROJECT_BINARY_DIR}/inst/bin/resources.cfg - ${PROJECT_BINARY_DIR}/inst/bin/plugins.cfg - ${PROJECT_BINARY_DIR}/inst/bin/samples.cfg - - ${PROJECT_SOURCE_DIR}/Samples/Common/misc.winrt/Logo.png - ${PROJECT_SOURCE_DIR}/Samples/Common/misc.winrt/SmallLogo.png - ${PROJECT_SOURCE_DIR}/Samples/Common/misc.winrt/StoreLogo.png - ${PROJECT_SOURCE_DIR}/Samples/Common/misc.winrt/SplashScreen.png - - DESTINATION ${CMAKE_CURRENT_BINARY_DIR} - ) - - # Mark resources as deployment content, so that it would be packaged - set(CONTENT_FILES ${CONTENT_FILES} - ${CMAKE_CURRENT_BINARY_DIR}/${APP_MANIFEST_NAME} - ${CMAKE_CURRENT_BINARY_DIR}/SDL2.dll - ${CMAKE_CURRENT_BINARY_DIR}/Media - ${CMAKE_CURRENT_BINARY_DIR}/Logo.png - ${CMAKE_CURRENT_BINARY_DIR}/SmallLogo.png - ${CMAKE_CURRENT_BINARY_DIR}/StoreLogo.png - ${CMAKE_CURRENT_BINARY_DIR}/SplashScreen.png - ${CMAKE_CURRENT_BINARY_DIR}/resources.cfg - ${CMAKE_CURRENT_BINARY_DIR}/plugins.cfg - ${CMAKE_CURRENT_BINARY_DIR}/samples.cfg - ) - set_property(SOURCE ${CONTENT_FILES} PROPERTY VS_DEPLOYMENT_CONTENT 1) - - set(RESOURCE_FILES ${CONTENT_FILES}) - source_group("Resource Files" FILES ${RESOURCE_FILES}) - -endif() - -if (OGRE_BUILD_TESTS) - add_definitions(-DSAMPLES_INCLUDE_PLAYPEN) - include_directories(${PROJECT_SOURCE_DIR}/Tests/PlayPen/include - ${PROJECT_SOURCE_DIR}/Tests/VisualTests/PlayPen/include) -endif() - -# Fix for static build with MinGW -if (OGRE_BUILD_RENDERSYSTEM_D3D9 AND OGRE_STATIC) - link_directories(${DirectX9_LIBRARY_DIR}) -endif() - -if (ANDROID) - include(AndroidMacros) - - add_ndk_cpufeatures_library() - add_ndk_native_app_glue_library() - - include_directories(${PROJECT_SOURCE_DIR}/RenderSystems/GLSupport/include) - set(SOURCE_FILES - ${PROJECT_SOURCE_DIR}/Samples/Browser/src/gestureDetector.cpp - ${PROJECT_SOURCE_DIR}/Samples/Browser/src/android_main.cpp) - - add_library(SampleBrowser SHARED ${HEADER_FILES} ${SOURCE_FILES} ${RESOURCE_FILES}) -else() - set(SOURCE_FILES ${PROJECT_SOURCE_DIR}/Samples/Browser/src/main.cpp) - add_executable(SampleBrowser WIN32 ${HEADER_FILES} ${SOURCE_FILES} ${RESOURCE_FILES}) -endif() - -# Fix for static build with MinGW -if (OGRE_BUILD_RENDERSYSTEM_D3D9 AND OGRE_STATIC) - target_link_libraries(SampleBrowser ${DirectX9_LIBRARIES}) -endif() - -target_link_libraries(SampleBrowser OgreMain ${OGRE_PLUGIN_LIBRARIES} ${SAMPLE_LIBRARIES} OgreBites) - -if(ANDROID) - target_link_libraries(SampleBrowser native_app_glue cpufeatures android c m dl z log EGL GLESv2 "-u ANativeActivity_onCreate") - set_target_properties(SampleBrowser PROPERTIES LINK_FLAGS -s) # strip symbols -endif() - -# Add samples as dependencies -add_dependencies(SampleBrowser ${OGRE_SAMPLES_LIST}) - -if (OGRE_STATIC) - # Link to samples too - target_link_libraries(SampleBrowser ${OGRE_SAMPLES_LIST}) -endif() - -if (SAMPLE_DEPENDENCIES) - add_dependencies(SampleBrowser ${SAMPLE_DEPENDENCIES}) -endif () - - -# configure SampleBrowser build - -ogre_config_common(SampleBrowser) - -# append _d for debug builds -if (WIN32 AND NOT (WINDOWS_STORE OR WINDOWS_PHONE)) - set_property(TARGET SampleBrowser APPEND PROPERTY DEBUG_POSTFIX "_d") -endif () - -if (WINDOWS_STORE OR WINDOWS_PHONE) - set_target_properties(SampleBrowser PROPERTIES VS_WINRT_COMPONENT "true") -endif() - -if (APPLE) - set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/src/main.cpp PROPERTIES COMPILE_FLAGS "-x objective-c++") - - # On OS X, create .app bundle - set_property(TARGET SampleBrowser PROPERTY MACOSX_BUNDLE TRUE) - set_property(TARGET SampleBrowser PROPERTY MACOSX_BUNDLE_ICON_FILE SampleBrowser_OSX.icns) - set_property(TARGET SampleBrowser PROPERTY MACOSX_BUNDLE_INFO_PLIST ${PROJECT_SOURCE_DIR}/Samples/Common/misc/Info.plist) - set(MACOSX_BUNDLE_GUI_IDENTIFIER "org.ogre3d.\${PRODUCT_NAME:rfc1034identifier}") - set_target_properties(SampleBrowser PROPERTIES XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH "NO") - - if (APPLE_IOS) - set_target_properties(SampleBrowser PROPERTIES XCODE_ATTRIBUTE_TARGETED_DEVICE_FAMILY "1,2") - set(OGRE_SAMPLE_CONTENTS_PATH ${PROJECT_BINARY_DIR}/bin/$(CONFIGURATION)/SampleBrowser.app) - add_custom_command(TARGET SampleBrowser POST_BUILD - COMMAND ditto ${PROJECT_SOURCE_DIR}/Samples/Common/misc/*.png ${OGRE_SAMPLE_CONTENTS_PATH}/ - COMMAND ditto ${PROJECT_BINARY_DIR}/bin/*.cfg ${OGRE_SAMPLE_CONTENTS_PATH}/ - ) - add_custom_command(TARGET SampleBrowser POST_BUILD - COMMAND mkdir ARGS -p ${PROJECT_BINARY_DIR}/lib/$(CONFIGURATION)/ - COMMAND ditto ${PROJECT_SOURCE_DIR}/Media ${OGRE_SAMPLE_CONTENTS_PATH}/Media - COMMAND ditto ${PROJECT_SOURCE_DIR}/Samples/Media ${OGRE_SAMPLE_CONTENTS_PATH}/Media - ) - else() - - set_target_properties(SampleBrowser - PROPERTIES BUILD_WITH_INSTALL_RPATH 1 - INSTALL_RPATH "@executable_path/../Frameworks;${OGREDEPS_PATH}/lib" - ) - - target_link_libraries(SampleBrowser ${OPENGL_gl_LIBRARY} ${CoreVideo_LIBRARIES}) - # also, symlink frameworks so .app is standalone - # NOTE: $(CONFIGURATION) is not resolvable at CMake run time, it's only - # valid at build time (hence parenthesis rather than braces) - # PLATFORM_NAME is set by us in ConfigTargets - - set(OGRE_OSX_BUILD_CONFIGURATION "${PLATFORM_NAME}/$(CONFIGURATION)") - set (OGRE_SAMPLE_CONTENTS_PATH - ${PROJECT_BINARY_DIR}/bin/$(CONFIGURATION)/SampleBrowser.app/Contents) - add_custom_command(TARGET SampleBrowser POST_BUILD - COMMAND mkdir ARGS -p ${OGRE_SAMPLE_CONTENTS_PATH}/Frameworks - COMMAND ln ARGS -s -f ${PROJECT_BINARY_DIR}/lib/${OGRE_OSX_BUILD_CONFIGURATION}/Ogre.framework ${OGRE_SAMPLE_CONTENTS_PATH}/Frameworks/ - COMMAND ln ARGS -s -f ${Cg_LIBRARY_REL} ${OGRE_SAMPLE_CONTENTS_PATH}/Frameworks/ - ) - # now cfg files - add_custom_command(TARGET SampleBrowser POST_BUILD - COMMAND mkdir ARGS -p ${OGRE_SAMPLE_CONTENTS_PATH}/Resources - COMMAND ln ARGS -s -f ${PROJECT_BINARY_DIR}/bin/plugins.cfg ${OGRE_SAMPLE_CONTENTS_PATH}/Resources/ - COMMAND ln ARGS -s -f ${PROJECT_BINARY_DIR}/bin/resources.cfg ${OGRE_SAMPLE_CONTENTS_PATH}/Resources/ - COMMAND ln ARGS -s -f ${PROJECT_BINARY_DIR}/bin/samples.cfg ${OGRE_SAMPLE_CONTENTS_PATH}/Resources/ - COMMAND ln ARGS -s -f ${PROJECT_SOURCE_DIR}/Samples/Media ${OGRE_SAMPLE_CONTENTS_PATH}/Resources/ - COMMAND ditto ${PROJECT_SOURCE_DIR}/Samples/Common/misc/SampleBrowser_OSX.icns ${OGRE_SAMPLE_CONTENTS_PATH}/Resources - ) - - # now plugins - add_custom_command(TARGET SampleBrowser POST_BUILD - COMMAND mkdir ARGS -p ${OGRE_SAMPLE_CONTENTS_PATH}/Frameworks - COMMAND mkdir ARGS -p ${OGRE_SAMPLE_CONTENTS_PATH}/Plugins) - - set(FRAMEWORKS OgreOverlay - OgreBites - OgreBullet - OgrePaging - OgreProperty - OgreRTShaderSystem - OgreTerrain - OgreVolume - OgreMeshLodGenerator - Plugin_BSPSceneManager - Plugin_CgProgramManager - Plugin_OctreeSceneManager - Plugin_OctreeZone - Plugin_ParticleFX - Plugin_PCZSceneManager - Plugin_DotScene - Codec_STBI - Codec_FreeImage - RenderSystem_GL - RenderSystem_GL3Plus - RenderSystem_Metal - ) - - foreach(FWK ${FRAMEWORKS}) - if(TARGET ${FWK}) - add_custom_command(TARGET SampleBrowser POST_BUILD - COMMAND ln -s -f - ${PROJECT_BINARY_DIR}/lib/${OGRE_OSX_BUILD_CONFIGURATION}/${FWK}.framework - ${OGRE_SAMPLE_CONTENTS_PATH}/Frameworks/${FWK}.framework) - endif() - endforeach(FWK) - - # Add links for the sample plugins - foreach(SAMPLE_PLUGIN ${OGRE_SAMPLES_LIST}) - add_custom_command(TARGET SampleBrowser POST_BUILD - COMMAND ln ARGS -s -f ${PROJECT_BINARY_DIR}/lib/${OGRE_OSX_BUILD_CONFIGURATION}/${SAMPLE_PLUGIN}.dylib - ${OGRE_SAMPLE_CONTENTS_PATH}/Plugins/ - ) - endforeach(SAMPLE_PLUGIN) - - if (OGRE_BUILD_TESTS) - add_custom_command(TARGET SampleBrowser POST_BUILD - COMMAND ln ARGS -s -f ${PROJECT_BINARY_DIR}/lib/${OGRE_OSX_BUILD_CONFIGURATION}/PlayPen.dylib - ${OGRE_SAMPLE_CONTENTS_PATH}/Plugins/ - ) - endif() - endif() - -endif (APPLE) - -if (ANDROID) - SET(ANDROID_MOD_NAME "OgreSampleBrowser") - SET(NDKOUT "${CMAKE_BINARY_DIR}/SampleBrowserNDK") - SET(PKG_NAME "org.ogre.browser") - SET(HAS_CODE "false") - SET(MAIN_ACTIVITY "android.app.NativeActivity") - SET(HEADERS "") - SET(SAMPLE_LDLIBS "") - - copy_assets_to_android_proj() - - file(MAKE_DIRECTORY "${NDKOUT}/app/src/main/jniLibs/${ANDROID_NDK_ABI_NAME}") - set_target_properties(SampleBrowser PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${NDKOUT}/app/src/main/jniLibs/${ANDROID_NDK_ABI_NAME}") - set_target_properties(SampleBrowser PROPERTIES OUTPUT_NAME "OgreSampleBrowser") - - create_android_proj(SampleBrowser) - # this whole part should be simplified more -endif(ANDROID) - -if (OGRE_INSTALL_SAMPLES) - ogre_install_target(SampleBrowser "" FALSE) - install(FILES ${PROJECT_BINARY_DIR}/inst/bin/samples.cfg DESTINATION "${OGRE_CFG_INSTALL_PATH}") - - if (OGRE_INSTALL_PDB) - # install debug pdb files - install(FILES $ - DESTINATION bin${OGRE_DEBUG_PATH} CONFIGURATIONS Debug - ) - install(FILES $ - DESTINATION bin${OGRE_RELWDBG_PATH} CONFIGURATIONS RelWithDebInfo - ) - endif () -endif () diff --git a/Samples/Browser/include/SampleBrowser.h b/Samples/Browser/include/SampleBrowser.h deleted file mode 100644 index 8de3bd7c586..00000000000 --- a/Samples/Browser/include/SampleBrowser.h +++ /dev/null @@ -1,1197 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#ifndef __SampleBrowser_H__ -#define __SampleBrowser_H__ - -#include "SampleContext.h" -#include "SamplePlugin.h" -#include "OgreTrays.h" -#include "OgreConfigFile.h" -#include "OgreTechnique.h" -#include "OgreArchiveManager.h" -#include "SdkSample.h" - -#define ENABLE_SHADERS_CACHE 1 - -#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT -# include -# if defined(_WIN32_WINNT) && _WIN32_WINNT == _WIN32_WINNT_WIN8 -// For WinRT 8.0 we only support running from the cache file. -# undef ENABLE_SHADERS_CACHE -# define ENABLE_SHADERS_CACHE 1 -# endif -#endif - -#ifndef __OGRE_WINRT_PHONE -#define __OGRE_WINRT_PHONE 0 -#endif - -#ifdef OGRE_STATIC_LIB -#include "DefaultSamplesPlugin.h" -# ifdef SAMPLES_INCLUDE_PLAYPEN -# include "PlayPenTestPlugin.h" -# endif -#endif - -#define CAROUSEL_REDRAW_EPS 0.001 - -namespace OgreBites -{ - /*============================================================================= - | The OGRE Sample Browser. Features a menu accessible from all samples, - | dynamic configuration, resource reloading, node labeling, and more. - =============================================================================*/ - class SampleBrowser : public SampleContext, public TrayListener - { -#ifdef OGRE_STATIC_LIB - typedef std::map PluginMap; - PluginMap mPluginNameMap; // A structure to map plugin names to class types -#endif - public: - - SampleBrowser(bool nograb = false, int startSampleIndex = -1) - : SampleContext("OGRE Sample Browser"), mGrabInput(!nograb) - { - mIsShuttingDown = false; - mTrayMgr = 0; - mLastViewCategory = 0; - mLastViewTitle = 0; - mLastSampleIndex = -1; - mStartSampleIndex = startSampleIndex; - mCategoryMenu = 0; - mSampleMenu = 0; - mSampleSlider = 0; - mTitleLabel = 0; - mDescBox = 0; - mRendererMenu = 0; - mCarouselPlace = 0.0f; - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - mGestureView = 0; -#endif - } - - void loadStartUpSample() override - { - if (mStartSampleIndex != -1) - { - runSampleByIndex(mStartSampleIndex); - mStartSampleIndex = -1; - } - } - - virtual void runSampleByIndex(int idx) - { - runSample(Ogre::any_cast(mThumbs[idx]->getUserObjectBindings().getUserAny())); - } - - /*----------------------------------------------------------------------------- - | Extends runSample to handle creation and destruction of dummy scene. - -----------------------------------------------------------------------------*/ - void runSample(Sample* s) override - { - if (mCurrentSample) // sample quitting - { - mCurrentSample->_shutdown(); - mCurrentSample = 0; - mSamplePaused = false; // don't pause next sample - - // create dummy scene and modify controls - createDummyScene(); - mTrayMgr->showBackdrop("SdkTrays/Bands"); - mTrayMgr->showAll(); - ((Button*)mTrayMgr->getWidget("StartStop"))->setCaption("Start Sample"); - } - - if (s) // sample starting - { - // destroy dummy scene and modify controls - ((Button*)mTrayMgr->getWidget("StartStop"))->setCaption("Stop Sample"); - mTrayMgr->showBackdrop("SdkTrays/Shade"); - mTrayMgr->hideAll(); - destroyDummyScene(); - - try - { - if(dynamic_cast(s)) - s->_setupTrays(mWindow); - SampleContext::runSample(s); - } - catch (Ogre::Exception& e) // if failed to start, show error and fall back to menu - { - destroyDummyScene(); - - s->_shutdown(); - - createDummyScene(); - mTrayMgr->showBackdrop("SdkTrays/Bands"); - mTrayMgr->showAll(); - ((Button*)mTrayMgr->getWidget("StartStop"))->setCaption("Start Sample"); - - mTrayMgr->showOkDialog("Error!", e.getDescription() + "\nSource: " + e.getSource()); - } - } - } - - /// catch any exceptions that might drop out of event handlers implemented by Samples - bool frameStarted(const Ogre::FrameEvent& evt) override - { - try - { - return SampleContext::frameStarted(evt); - } - catch (Ogre::Exception& e) // show error and fall back to menu - { - runSample(0); - mTrayMgr->showOkDialog("Error!", e.getDescription() + "\nSource: " + e.getSource()); - } - - return true; - } - - /*----------------------------------------------------------------------------- - | Extends frameRenderingQueued to update tray manager and carousel. - -----------------------------------------------------------------------------*/ - bool frameRenderingQueued(const Ogre::FrameEvent& evt) override - { - // don't do all these calculations when sample's running or when in configuration screen or when no samples loaded - if (!mLoadedSamples.empty() && mTitleLabel->getTrayLocation() != TL_NONE && (!mCurrentSample || mSamplePaused)) - { - // makes the carousel spin smoothly toward its right position - float carouselOffset = mSampleMenu->getSelectionIndex() - mCarouselPlace; - if (std::abs(carouselOffset) <= CAROUSEL_REDRAW_EPS) mCarouselPlace = mSampleMenu->getSelectionIndex(); - else mCarouselPlace += carouselOffset * Ogre::Math::Clamp(evt.timeSinceLastFrame * 15.0, -1.0, 1.0); - - // update the thumbnail positions based on carousel state - for (int i = 0; i < (int)mThumbs.size(); i++) - { - if(carouselOffset == 0) break; - - Ogre::Real thumbOffset = mCarouselPlace - i; - Ogre::Real phase = (thumbOffset / 2.0) - 2.8; - - if (thumbOffset < -5 || thumbOffset > 4) // prevent thumbnails from wrapping around in a circle - { - mThumbs[i]->hide(); - continue; - } - else mThumbs[i]->show(); - - Ogre::Real left = Ogre::Math::Cos(phase) * 200.0; - Ogre::Real top = Ogre::Math::Sin(phase) * 200.0; - Ogre::Real scale = 1.0 / Ogre::Math::Pow((Ogre::Math::Abs(thumbOffset) + 1.0), 0.75); - - auto frame = - dynamic_cast(mThumbs[i]->getChildren().begin()->second); - - mThumbs[i]->setDimensions(128.0 * scale, 96.0 * scale); - frame->setDimensions(mThumbs[i]->getWidth() + 16.0, mThumbs[i]->getHeight() + 16.0); - mThumbs[i]->setPosition((int)(left - 80.0 - (mThumbs[i]->getWidth() / 2.0)), - (int)(top - 5.0 - (mThumbs[i]->getHeight() / 2.0))); - frame->setMaterial(nullptr); // dont draw inner region - if (i == mSampleMenu->getSelectionIndex()) frame->setBorderMaterialName("SdkTrays/Frame/Over"); - else frame->setBorderMaterialName("SdkTrays/Frame"); - } - } - - mTrayMgr->frameRendered(evt); - - return SampleContext::frameRenderingQueued(evt); - } - - /*----------------------------------------------------------------------------- - | Handles confirmation dialog responses. - -----------------------------------------------------------------------------*/ - void yesNoDialogClosed(const Ogre::DisplayString& question, bool yesHit) override - { - if (question.substr(0, 14) == "This will stop" && yesHit) // confirm unloading of samples - { - runSample(0); - buttonHit((Button*)mTrayMgr->getWidget("UnloadReload")); - } - } - - /*----------------------------------------------------------------------------- - | Handles button widget events. - -----------------------------------------------------------------------------*/ - void buttonHit(Button* b) override - { - if (b->getName() == "StartStop") // start or stop sample - { - if (b->getCaption() == "Start Sample") - { - if (mLoadedSamples.empty()) { - mTrayMgr->showOkDialog("Error!", "No sample selected!"); - } else { - // use the sample pointer we stored inside the thumbnail - Ogre::Renderable* r = mThumbs[mSampleMenu->getSelectionIndex()]; - runSample(Ogre::any_cast(r->getUserObjectBindings().getUserAny())); - } - } else - runSample(0); - } - else if (b->getName() == "UnloadReload") // unload or reload sample plugins and update controls - { - if (b->getCaption() == "Unload Samples") - { - if (mCurrentSample) mTrayMgr->showYesNoDialog("Warning!", "This will stop the current sample. Unload anyway?"); - else - { - // save off current view and try to restore it on the next reload - mLastViewTitle = mSampleMenu->getSelectionIndex(); - mLastViewCategory = mCategoryMenu->getSelectionIndex(); - - unloadSamples(); - populateSampleMenus(); - b->setCaption("Reload Samples"); - } - } - else - { - loadSamples(); - populateSampleMenus(); - if (!mLoadedSamples.empty()) b->setCaption("Unload Samples"); - - try // attempt to restore the last view before unloading samples - { - mCategoryMenu->selectItem(mLastViewCategory); - mSampleMenu->selectItem(mLastViewTitle); - } - catch (Ogre::Exception&) {} - } - } - else if (b->getName() == "Configure") // enter configuration screen - { - mTrayMgr->removeWidgetFromTray("StartStop"); - mTrayMgr->removeWidgetFromTray("Configure"); -#if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID - mTrayMgr->removeWidgetFromTray("UnloadReload"); - mTrayMgr->removeWidgetFromTray("Quit"); - mTrayMgr->moveWidgetToTray("Apply", TL_RIGHT); -#endif - mTrayMgr->moveWidgetToTray("Back", TL_RIGHT); - - for (unsigned int i = 0; i < mThumbs.size(); i++) - { - mThumbs[i]->hide(); - } - - while (mTrayMgr->getTrayContainer(TL_CENTER)->isVisible()) - { - mTrayMgr->removeWidgetFromTray(TL_CENTER, 0); - } - - while (mTrayMgr->getTrayContainer(TL_LEFT)->isVisible()) - { - mTrayMgr->removeWidgetFromTray(TL_LEFT, 0); - } - - mTrayMgr->moveWidgetToTray("ConfigLabel", TL_LEFT); - mTrayMgr->moveWidgetToTray(mRendererMenu, TL_LEFT); - mTrayMgr->moveWidgetToTray("ConfigSeparator", TL_LEFT); - - mRendererMenu->selectItem(mRoot->getRenderSystem()->getName()); - - windowResized(mWindow); - } - else if (b->getName() == "Back") // leave configuration screen - { - while (mTrayMgr->getWidgets(mRendererMenu->getTrayLocation()).size() > 3) - { - mTrayMgr->destroyWidget(mRendererMenu->getTrayLocation(), 3); - } - - while (!mTrayMgr->getWidgets(TL_NONE).empty()) - { - mTrayMgr->moveWidgetToTray(TL_NONE, 0, TL_LEFT); - } - - mTrayMgr->removeWidgetFromTray("Apply"); - mTrayMgr->removeWidgetFromTray("Back"); - mTrayMgr->removeWidgetFromTray("ConfigLabel"); - mTrayMgr->removeWidgetFromTray(mRendererMenu); - mTrayMgr->removeWidgetFromTray("ConfigSeparator"); - - mTrayMgr->moveWidgetToTray("StartStop", TL_RIGHT); -#if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID - mTrayMgr->moveWidgetToTray("UnloadReload", TL_RIGHT); -#endif - mTrayMgr->moveWidgetToTray("Configure", TL_RIGHT); -#if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID - mTrayMgr->moveWidgetToTray("Quit", TL_RIGHT); -#endif - - mCarouselPlace += CAROUSEL_REDRAW_EPS; // force redraw - windowResized(mWindow); - } - else if (b->getName() == "Apply") // apply any changes made in the configuration screen - { - bool reset = false; - - auto options = - mRoot->getRenderSystemByName(mRendererMenu->getSelectedItem())->getConfigOptions(); - - Ogre::NameValuePairList newOptions; - - // collect new settings and decide if a reset is needed - - if (mRendererMenu->getSelectedItem() != mRoot->getRenderSystem()->getName()) { - reset = true; - } - - for (unsigned int i = 3; i < mTrayMgr->getWidgets(mRendererMenu->getTrayLocation()).size(); i++) - { - SelectMenu* menu = (SelectMenu*)mTrayMgr->getWidgets(mRendererMenu->getTrayLocation())[i]; - if (menu->getSelectedItem() != options[menu->getCaption()].currentValue) reset = true; - newOptions[menu->getCaption()] = menu->getSelectedItem(); - } - - // reset with new settings if necessary - if (reset) reconfigure(mRendererMenu->getSelectedItem(), newOptions); - } - else - { - mRoot->queueEndRendering(); // exit browser - } - } - - /*----------------------------------------------------------------------------- - | Handles menu item selection changes. - -----------------------------------------------------------------------------*/ - void itemSelected(SelectMenu* menu) override - { - if (menu == mCategoryMenu) // category changed, so update the sample menu, carousel, and slider - { - for (unsigned int i = 0; i < mThumbs.size(); i++) // destroy all thumbnails in carousel - { - Ogre::MaterialManager::getSingleton().remove(mThumbs[i]->getName(), "Essential"); - Widget::nukeOverlayElement(mThumbs[i]); - } - mThumbs.clear(); - - Ogre::OverlayManager& om = Ogre::OverlayManager::getSingleton(); - Ogre::String selectedCategory; - - if (menu->getSelectionIndex() != -1) selectedCategory = menu->getSelectedItem(); - else - { - mTitleLabel->setCaption(""); - mDescBox->setText(""); - } - - bool all = selectedCategory == "All"; - Ogre::StringVector sampleTitles; - Ogre::MaterialPtr templateMat = Ogre::MaterialManager::getSingleton().getByName("SdkTrays/SampleThumbnail"); - - // populate the sample menu and carousel with filtered samples - for (SampleSet::iterator i = mLoadedSamples.begin(); i != mLoadedSamples.end(); i++) - { - Ogre::NameValuePairList& info = (*i)->getInfo(); - - if (all || info["Category"] == selectedCategory) - { - Ogre::String name = "SdkTrays/SampleThumb" + Ogre::StringConverter::toString(sampleTitles.size() + 1); - - // clone a new material for sample thumbnail - Ogre::MaterialPtr newMat = templateMat->clone(name); - - Ogre::TextureUnitState* tus = newMat->getTechnique(0)->getPass(0)->getTextureUnitState(0); - tus->setTextureName(info["Thumbnail"]); - - // create sample thumbnail overlay - auto bp = dynamic_cast( - om.createOverlayElementFromTemplate("SdkTrays/Picture", "", name)); - bp->setHorizontalAlignment(Ogre::GHA_RIGHT); - bp->setVerticalAlignment(Ogre::GVA_CENTER); - bp->setMaterialName(name); - bp->getUserObjectBindings().setUserAny(*i); - mTrayMgr->getTraysLayer()->add2D(bp); - - // add sample thumbnail and title - mThumbs.push_back(bp); - sampleTitles.push_back((*i)->getInfo()["Title"]); - } - } - - mCarouselPlace = CAROUSEL_REDRAW_EPS; // reset carousel - - mSampleMenu->setItems(sampleTitles); - if (mSampleMenu->getNumItems() != 0) itemSelected(mSampleMenu); - - mSampleSlider->setRange(1, static_cast(sampleTitles.size()), static_cast(sampleTitles.size())); - } - else if (menu == mSampleMenu) // sample changed, so update slider, label and description - { - if (mSampleSlider->getValue() != menu->getSelectionIndex() + 1) - mSampleSlider->setValue(menu->getSelectionIndex() + 1); - - Ogre::Renderable* r = mThumbs[mSampleMenu->getSelectionIndex()]; - Sample* s = Ogre::any_cast(r->getUserObjectBindings().getUserAny()); - mTitleLabel->setCaption(menu->getSelectedItem()); - mDescBox->setText("Category: " + s->getInfo()["Category"] + "\nDescription: " + s->getInfo()["Description"]); - - if (mCurrentSample != s) ((Button*)mTrayMgr->getWidget("StartStop"))->setCaption("Start Sample"); - else ((Button*)mTrayMgr->getWidget("StartStop"))->setCaption("Stop Sample"); - } - else if (menu == mRendererMenu) // renderer selected, so update all settings - { - while (mTrayMgr->getWidgets(mRendererMenu->getTrayLocation()).size() > 3) - { - mTrayMgr->destroyWidget(mRendererMenu->getTrayLocation(), 3); - } - - auto options = mRoot->getRenderSystemByName(menu->getSelectedItem())->getConfigOptions(); - - unsigned int i = 0; - - // create all the config option select menus - for (Ogre::ConfigOptionMap::iterator it = options.begin(); it != options.end(); it++) - { - i++; - SelectMenu* optionMenu = mTrayMgr->createLongSelectMenu - (TL_LEFT, "ConfigOption" + Ogre::StringConverter::toString(i), it->first, 450, 240, 10); - optionMenu->setItems(it->second.possibleValues); - - // if the current config value is not in the menu, add it - if(optionMenu->containsItem(it->second.currentValue) == false) - { - optionMenu->addItem(it->second.currentValue); - } - - optionMenu->selectItem(it->second.currentValue); - } - - windowResized(mWindow); - } - } - - /*----------------------------------------------------------------------------- - | Handles sample slider changes. - -----------------------------------------------------------------------------*/ - void sliderMoved(Slider* slider) override - { - // format the caption to be fraction style - Ogre::String denom = "/" + Ogre::StringConverter::toString(mSampleMenu->getNumItems()); - slider->setValueCaption(slider->getValueCaption() + denom); - - // tell the sample menu to change if it hasn't already - if (mSampleMenu->getSelectionIndex() != -1 && mSampleMenu->getSelectionIndex() != slider->getValue() - 1) - mSampleMenu->selectItem(slider->getValue() - 1); - } - - /*----------------------------------------------------------------------------- - | Handles keypresses. - -----------------------------------------------------------------------------*/ - bool keyPressed(const KeyboardEvent& evt) override - { - if (mTrayMgr->isDialogVisible()) return true; // ignore keypresses when dialog is showing - - Keycode key = evt.keysym.sym; - - if (key == SDLK_ESCAPE) - { -#if __OGRE_WINRT_PHONE - // If there is a quit button, assume that we intended to press it via 'ESC'. - if (mTrayMgr->areTraysVisible()) - { - Widget *pWidget = mTrayMgr->getWidget("Quit"); - if (pWidget) - { - buttonHit((Button*)pWidget); // on phone, quit entirely. - return false; // now act as if we didn't handle the button to get AppModel to exit. - } - } -#endif // __OGRE_WINRT_PHONE - if (mTitleLabel->getTrayLocation() != TL_NONE) - { - // if we're in the main screen and a sample's running, toggle sample pause state - if (mCurrentSample) - { - if (mSamplePaused) - { - mTrayMgr->hideAll(); - unpauseCurrentSample(); - } - else - { - pauseCurrentSample(); - mTrayMgr->showAll(); - } - } - } - else buttonHit((Button*)mTrayMgr->getWidget("Back")); // if we're in config, just go back - } - else if ((key == SDLK_UP || key == SDLK_DOWN) && mTitleLabel->getTrayLocation() != TL_NONE) - { - // if we're in the main screen, use the up and down arrow keys to cycle through samples - int newIndex = mSampleMenu->getSelectionIndex() + (key == SDLK_UP ? -1 : 1); - mSampleMenu->selectItem(Ogre::Math::Clamp(newIndex, 0, mSampleMenu->getNumItems() - 1)); - } - else if (key == SDLK_RETURN) // start or stop sample - { - if (!mLoadedSamples.empty() && (mSamplePaused || mCurrentSample == 0)) - { - Ogre::Renderable* r = mThumbs[mSampleMenu->getSelectionIndex()]; - Sample* newSample = Ogre::any_cast(r->getUserObjectBindings().getUserAny()); - runSample(newSample == mCurrentSample ? 0 : newSample); - } - } - else if(key == SDLK_F9) // toggle full screen - { - // Make sure we use the window size as originally requested, NOT the - // current window size (which may have altered to fit desktop) - auto desc = mRoot->getRenderSystem()->getRenderWindowDescription(); - mWindow->setFullscreen(!mWindow->isFullScreen(), desc.width, desc.height); - } - else if(key == SDLK_F11 || key == SDLK_F12) // Decrease and increase FSAA level on the fly - { - // current FSAA 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 - unsigned decreasedFSAA[17] = { 0, 0, 1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8 }; - unsigned increasedFSAA[17] = { 2, 2, 4, 4, 8, 8, 8, 8,16,16,16,16,16,16,16,16, 0, }; - unsigned FSAA = std::min(mWindow->getFSAA(), 16U); - unsigned newFSAA = (key == SDLK_F12) ? increasedFSAA[FSAA] : decreasedFSAA[FSAA]; - if(newFSAA != 0) - mWindow->setFSAA(newFSAA, mWindow->getFSAAHint()); - } - - return SampleContext::keyPressed(evt); - } - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - void motionBegan( void ) - { - } - - void motionEnded( void ) - { - if (mTrayMgr->isDialogVisible()) return; // ignore keypresses when dialog is showing - - if (mTitleLabel->getTrayLocation() != TL_NONE) - { - // if we're in the main screen and a sample's running, toggle sample pause state - if (mCurrentSample) - { - if (mSamplePaused) - { - mTrayMgr->hideAll(); - unpauseCurrentSample(); - } - else - { - pauseCurrentSample(); - mTrayMgr->showAll(); - } - } - } - else buttonHit((Button*)mTrayMgr->getWidget("Back")); // if we're in config, just go back - - } - - void motionCancelled( void ) - { - } -#endif - - /*----------------------------------------------------------------------------- - | Extends pointerPressed to inject mouse press into tray manager, and to check - | for thumbnail clicks, just because we can. - -----------------------------------------------------------------------------*/ - bool mousePressed(const MouseButtonEvent& evt) override - { - if (mTitleLabel->getTrayLocation() != TL_NONE) - { - for (unsigned int i = 0; i < mThumbs.size(); i++) - { - if (mThumbs[i]->isVisible() && Widget::isCursorOver(mThumbs[i], - Ogre::Vector2(mTrayMgr->getCursorContainer()->getLeft(), mTrayMgr->getCursorContainer()->getTop()), 0)) - { - mSampleMenu->selectItem(i); - return true; - } - } - } - - if (isCurrentSamplePaused()) return mTrayMgr->mousePressed(evt); - - return SampleContext::mousePressed(evt); - } - - // convert and redirect - bool touchPressed(const TouchFingerEvent& evt) override { - MouseButtonEvent e; - e.button = BUTTON_LEFT; - return mousePressed(e); - } - - bool buttonPressed(const ButtonEvent& evt) override - { - KeyboardEvent e; - e.keysym.sym = 0; - switch (evt.button) - { - case 0: - e.keysym.sym = SDLK_RETURN; - break; - case 1: - e.keysym.sym = SDLK_ESCAPE; - break; - case 11: - e.keysym.sym = SDLK_UP; - break; - case 12: - e.keysym.sym = SDLK_DOWN; - break; - } - return keyPressed(e); - } - - /*----------------------------------------------------------------------------- - | Extends pointerReleased to inject mouse release into tray manager. - -----------------------------------------------------------------------------*/ - bool mouseReleased(const MouseButtonEvent& evt) override - { - if (isCurrentSamplePaused()) return mTrayMgr->mouseReleased(evt); - - return SampleContext::mouseReleased(evt); - } - - // convert and redirect - bool touchReleased(const TouchFingerEvent& evt) override { - MouseButtonEvent e; - e.button = BUTTON_LEFT; - return mouseReleased(e); - } - - /*----------------------------------------------------------------------------- - | Extends pointerMoved to inject mouse position into tray manager, and checks - | for mouse wheel movements to slide the carousel, because we can. - -----------------------------------------------------------------------------*/ - bool mouseMoved(const MouseMotionEvent& evt) override - { - if (isCurrentSamplePaused()) return mTrayMgr->mouseMoved(evt); - - return SampleContext::mouseMoved(evt); - } - - // convert and redirect - bool touchMoved(const TouchFingerEvent& evt) override { - MouseMotionEvent e; - e.x = evt.x * mWindow->getWidth(); - e.y = evt.y * mWindow->getHeight(); - e.xrel = evt.dx * mWindow->getWidth(); - e.yrel = evt.dy * mWindow->getHeight(); - return mouseMoved(e); - } - - //TODO: Handle iOS and Android. - /** Mouse wheel scrolls the sample list. - */ - bool mouseWheelRolled(const MouseWheelEvent& evt) override - { - if(mTrayMgr->mouseWheelRolled(evt)) - return true; - - if (isCurrentSamplePaused() && mTitleLabel->getTrayLocation() != TL_NONE && - mSampleMenu->getNumItems() != 0) - { - int newIndex = mSampleMenu->getSelectionIndex() - evt.y / Ogre::Math::Abs(evt.y); - mSampleMenu->selectItem(Ogre::Math::Clamp(newIndex, 0, mSampleMenu->getNumItems() - 1)); - } - - return SampleContext::mouseWheelRolled(evt); - } - - /*----------------------------------------------------------------------------- - | Extends windowResized to best fit menus on screen. We basically move the - | menu tray to the left for higher resolutions and move it to the center - | for lower resolutions. - -----------------------------------------------------------------------------*/ - void windowResized(Ogre::RenderWindow* rw) override - { - if (!mTrayMgr) return; - - Ogre::OverlayContainer* center = mTrayMgr->getTrayContainer(TL_CENTER); - Ogre::OverlayContainer* left = mTrayMgr->getTrayContainer(TL_LEFT); - - if (center->isVisible() && rw->getWidth() < 1280 - center->getWidth()) - { - while (center->isVisible()) - { - mTrayMgr->moveWidgetToTray(mTrayMgr->getWidgets(TL_CENTER)[0], TL_LEFT); - } - } - else if (left->isVisible() && rw->getWidth() >= 1280 - left->getWidth()) - { - while (left->isVisible()) - { - mTrayMgr->moveWidgetToTray(mTrayMgr->getWidgets(TL_LEFT)[0], TL_CENTER); - } - } - - SampleContext::windowResized(rw); - } - - /*----------------------------------------------------------------------------- - | Extends setup to create dummy scene and tray interface. - -----------------------------------------------------------------------------*/ - void setup() override - { - ApplicationContext::setup(); - mWindow = getRenderWindow(); - addInputListener(this); - if(mGrabInput) setWindowGrab(); - else mTrayMgr->hideCursor(); -#ifdef OGRE_STATIC_LIB - mPluginNameMap["DefaultSamples"] = new DefaultSamplesPlugin(); -# ifdef SAMPLES_INCLUDE_PLAYPEN - mPluginNameMap["PlaypenTests"] = new PlaypenTestPlugin(); -# endif -#endif - - Sample* startupSample = loadSamples(); - - // create template material for sample thumbnails - Ogre::MaterialPtr thumbMat = Ogre::MaterialManager::getSingleton().create("SdkTrays/SampleThumbnail", "Essential"); - thumbMat->setLightingEnabled(false); - thumbMat->setDepthCheckEnabled(false); - thumbMat->getTechnique(0)->getPass(0)->createTextureUnitState(); - - setupWidgets(); - windowResized(mWindow); // adjust menus for resolution - - // if this is our first time running, and there's a startup sample, run it - if (startupSample && mFirstRun){ - runSample(startupSample); - } - } - - protected: - /*----------------------------------------------------------------------------- - | Overrides the default window title. - -----------------------------------------------------------------------------*/ - NativeWindowPair createWindow(const Ogre::String& name, uint32_t w, uint32_t h, Ogre::NameValuePairList miscParams) override - { -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - // Make sure Trays are not tiny - we cannot easily scale the UI, therefore just reduce resolution - float contentScaling = AConfiguration_getDensity(mAConfig)/float(ACONFIGURATION_DENSITY_HIGH); - if(contentScaling > 1.0) - { - miscParams["contentScalingFactor"] = std::to_string(contentScaling); - miscParams["FSAA"] = "2"; - } -#endif - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - mGestureView = [[SampleBrowserGestureView alloc] init]; - mGestureView.mBrowser = this; - - [[[UIApplication sharedApplication] keyWindow] addSubview:mGestureView]; -#endif - - return ApplicationContext::createWindow(name, w, h, miscParams); - } - - /*----------------------------------------------------------------------------- - | Initialises only the browser's resources and those most commonly used - | by samples. This way, additional special content can be initialised by - | the samples that use them, so startup time is unaffected. - -----------------------------------------------------------------------------*/ - void loadResources() override - { -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE - Ogre::OverlayManager::getSingleton().setPixelRatio(getDisplayDPI()/96); -#endif - - Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Essential"); - mTrayMgr = new TrayManager("BrowserControls", getRenderWindow(), this); - mTrayMgr->showBackdrop("SdkTrays/Bands"); - mTrayMgr->getTrayContainer(TL_NONE)->hide(); - -#if ENABLE_SHADERS_CACHE == 1 - enableShaderCache(); -#endif - // Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5); - - createDummyScene(); - - mTrayMgr->showLoadingBar(1, 0); - Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); - mTrayMgr->hideLoadingBar(); - } - - /*----------------------------------------------------------------------------- - | Loads sample plugins from a configuration file. - -----------------------------------------------------------------------------*/ - virtual Sample* loadSamples() - { - Sample* startupSample = 0; - Ogre::StringVector unloadedSamplePlugins; - - Ogre::String startupSampleTitle; - Ogre::StringVector sampleList; -#ifdef OGRE_STATIC_LIB - for(auto it = mPluginNameMap.begin(); it != mPluginNameMap.end(); ++it) - { - sampleList.push_back(it->first); - } -#else - Ogre::ConfigFile cfg; -# if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - Ogre::Archive* apk = Ogre::ArchiveManager::getSingleton().load("", "APKFileSystem", true); - cfg.load(apk->open(mFSLayer->getConfigFilePath("samples.cfg"))); -# else - cfg.load(mFSLayer->getConfigFilePath("samples.cfg")); -# endif - - Ogre::String sampleDir = cfg.getSetting("SampleFolder"); // Mac OS X just uses Resources/ directory - sampleList = cfg.getMultiSetting("SamplePlugin"); - startupSampleTitle = cfg.getSetting("StartupSample"); - - sampleDir = Ogre::FileSystemLayer::resolveBundlePath(sampleDir); - -# if OGRE_PLATFORM != OGRE_PLATFORM_APPLE && OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - if (sampleDir.empty()) sampleDir = "."; // user didn't specify plugins folder, try current one -# endif - - // add slash or backslash based on platform - char lastChar = sampleDir[sampleDir.length() - 1]; - if (lastChar != '/' && lastChar != '\\') - { -# if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || (OGRE_PLATFORM == OGRE_PLATFORM_WINRT) - sampleDir += "\\"; -# else - sampleDir += "/"; -# endif - } -#endif - - SampleSet newSamples; - - // loop through all sample plugins... - for (Ogre::StringVector::iterator i = sampleList.begin(); i != sampleList.end(); i++) - { -#ifndef OGRE_STATIC_LIB - try // try to load the plugin - { - mRoot->loadPlugin(sampleDir + *i); - } - catch (Ogre::Exception& e) // plugin couldn't be loaded - { - Ogre::LogManager::getSingleton().logError(e.what()); - unloadedSamplePlugins.push_back(sampleDir + *i); - continue; - } - - Ogre::Plugin* p = mRoot->getInstalledPlugins().back(); // acquire plugin instance - SamplePlugin* sp = dynamic_cast(p); - - if (!sp) // this is not a SamplePlugin, so unload it - { - unloadedSamplePlugins.push_back(sampleDir + *i); - mRoot->unloadPlugin(sampleDir + *i); - continue; - } - - mLoadedSamplePlugins.push_back(sampleDir + *i); // add to records -#else - SamplePlugin* sp = mPluginNameMap[*i]; -#endif - - // go through every sample in the plugin... - newSamples = sp->getSamples(); - for (SampleSet::iterator j = newSamples.begin(); j != newSamples.end(); j++) - { - Ogre::NameValuePairList& info = (*j)->getInfo(); // acquire custom sample info - - mLoadedSamples.insert(*j); // add sample only after ensuring title for sorting - mSampleCategories.insert(info["Category"]); // add sample category - - if (info["Title"] == startupSampleTitle) startupSample = *j; // we found the startup sample - } - } - - if (!mLoadedSamples.empty()) mSampleCategories.insert("All"); // insert a category for all samples - - if (!unloadedSamplePlugins.empty()) // show error message summarising missing or invalid plugins - { - Ogre::String message = "These requested sample plugins were either missing, corrupt or invalid:"; - - for (unsigned int i = 0; i < unloadedSamplePlugins.size(); i++) - { - message += "\n- " + unloadedSamplePlugins[i]; - } - - mTrayMgr->showOkDialog("Error!", message); - } - - return startupSample; - } - - /*----------------------------------------------------------------------------- - | Unloads any loaded sample plugins. - -----------------------------------------------------------------------------*/ - virtual void unloadSamples() - { -#ifndef OGRE_STATIC_LIB - for (unsigned int i = 0; i < mLoadedSamplePlugins.size(); i++) - { - mRoot->unloadPlugin(mLoadedSamplePlugins[i]); - } -#endif - - mLoadedSamples.clear(); - mLoadedSamplePlugins.clear(); - mSampleCategories.clear(); - } - - /*----------------------------------------------------------------------------- - | Sets up main page for browsing samples. - -----------------------------------------------------------------------------*/ - virtual void setupWidgets() - { - mTrayMgr->destroyAllWidgets(); - - // create main navigation tray - mTrayMgr->showLogo(TL_RIGHT); - mTrayMgr->createSeparator(TL_RIGHT, "LogoSep"); - mTrayMgr->createButton(TL_RIGHT, "StartStop", "Start Sample", 120); - -#if (OGRE_PLATFORM != OGRE_PLATFORM_WINRT) && (OGRE_PLATFORM != OGRE_PLATFORM_ANDROID) - mTrayMgr->createButton(TL_RIGHT, "UnloadReload", mLoadedSamples.empty() ? "Reload Samples" : "Unload Samples"); -#endif -#if (OGRE_PLATFORM != OGRE_PLATFORM_WINRT) - mTrayMgr->createButton(TL_RIGHT, "Configure", "Configure"); -#endif -#if (OGRE_PLATFORM != OGRE_PLATFORM_ANDROID) - mTrayMgr->createButton(TL_RIGHT, "Quit", "Quit"); -#endif - - // create sample viewing controls - float infoWidth = 250; -#if (OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS) || (OGRE_PLATFORM == OGRE_PLATFORM_ANDROID) - infoWidth *= 0.9; -#endif - mTitleLabel = mTrayMgr->createLabel(TL_LEFT, "SampleTitle", ""); - mDescBox = mTrayMgr->createTextBox(TL_LEFT, "SampleInfo", "Sample Info", infoWidth, 208); - mCategoryMenu = mTrayMgr->createThickSelectMenu(TL_LEFT, "CategoryMenu", "Select Category", infoWidth, 10); - mSampleMenu = mTrayMgr->createThickSelectMenu(TL_LEFT, "SampleMenu", "Select Sample", infoWidth, 10); - mSampleSlider = mTrayMgr->createThickSlider(TL_LEFT, "SampleSlider", "Slide Samples", infoWidth, 80, 0, 0, 0); - - /* Sliders do not notify their listeners on creation, so we manually call the callback here - to format the slider value correctly. */ - sliderMoved(mSampleSlider); - - // create configuration screen button tray - mTrayMgr->createButton(TL_NONE, "Apply", "Apply Changes"); - mTrayMgr->createButton(TL_NONE, "Back", "Go Back"); - - // create configuration screen label and renderer menu - mTrayMgr->createLabel(TL_NONE, "ConfigLabel", "Configuration"); - mRendererMenu = mTrayMgr->createLongSelectMenu(TL_NONE, "RendererMenu", "Render System", 450, 240, 10); - mTrayMgr->createSeparator(TL_NONE, "ConfigSeparator"); - - // populate render system names - Ogre::StringVector rsNames; - Ogre::RenderSystemList rsList = mRoot->getAvailableRenderers(); - for (unsigned int i = 0; i < rsList.size(); i++) - { - rsNames.push_back(rsList[i]->getName()); - } - mRendererMenu->setItems(rsNames); - - populateSampleMenus(); - } - - /*----------------------------------------------------------------------------- - | Populates home menus with loaded samples. - -----------------------------------------------------------------------------*/ - virtual void populateSampleMenus() - { - Ogre::StringVector categories; - for (std::set::iterator i = mSampleCategories.begin(); i != mSampleCategories.end(); i++) - categories.push_back(*i); - - mCategoryMenu->setItems(categories); - if (mCategoryMenu->getNumItems() != 0) - mCategoryMenu->selectItem(0); - else - itemSelected(mCategoryMenu); // if there are no items, we can't select one, so manually invoke callback - - mCarouselPlace = CAROUSEL_REDRAW_EPS; // force redraw - } - - /*----------------------------------------------------------------------------- - | Overrides to recover by last sample's index instead. - -----------------------------------------------------------------------------*/ - void recoverLastSample() override - { - // restore the view while we're at it too - mCategoryMenu->selectItem(mLastViewCategory); - mSampleMenu->selectItem(mLastViewTitle); - - if (mLastSampleIndex != -1) - { - int index = -1; - for (SampleSet::iterator i = mLoadedSamples.begin(); i != mLoadedSamples.end(); i++) - { - index++; - if (index == mLastSampleIndex) - { - runSample(*i); - (*i)->restoreState(mLastSampleState); - mLastSample = 0; - mLastSampleIndex = -1; - mLastSampleState.clear(); - } - } - - pauseCurrentSample(); - mTrayMgr->showAll(); - } - - buttonHit((Button*)mTrayMgr->getWidget("Configure")); - } - - /*----------------------------------------------------------------------------- - | Extends reconfigure to save the view and the index of last sample run. - -----------------------------------------------------------------------------*/ - void reconfigure(const Ogre::String& renderer, Ogre::NameValuePairList& options) override - { - mLastViewCategory = mCategoryMenu->getSelectionIndex(); - mLastViewTitle = mSampleMenu->getSelectionIndex(); - - mLastSampleIndex = -1; - unsigned int index = -1; - for (SampleSet::iterator i = mLoadedSamples.begin(); i != mLoadedSamples.end(); i++) - { - index++; - if (*i == mCurrentSample) - { - mLastSampleIndex = index; - break; - } - } - - SampleContext::reconfigure(renderer, options); - } - public: - /*----------------------------------------------------------------------------- - | Extends shutdown to destroy dummy scene and tray interface. - -----------------------------------------------------------------------------*/ - void shutdown() override - { -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - [mGestureView release]; -#endif - if (mTrayMgr) - { - delete mTrayMgr; - mTrayMgr = 0; - } - - if (!mCurrentSample && mRoot->getRenderSystem() != NULL) destroyDummyScene(); - - SampleContext::shutdown(); - - mCategoryMenu = 0; - mSampleMenu = 0; - mSampleSlider = 0; - mTitleLabel = 0; - mDescBox = 0; - mRendererMenu = 0; - mHiddenOverlays.clear(); - mThumbs.clear(); - mCarouselPlace = 0; - mWindow = 0; - - unloadSamples(); - } - protected: - /*----------------------------------------------------------------------------- - | Extend to temporarily hide a sample's overlays while in the pause menu. - -----------------------------------------------------------------------------*/ - void pauseCurrentSample() override - { - SampleContext::pauseCurrentSample(); - - Ogre::OverlayManager::OverlayMapIterator it = Ogre::OverlayManager::getSingleton().getOverlayIterator(); - mHiddenOverlays.clear(); - - while (it.hasMoreElements()) - { - Ogre::Overlay* o = it.getNext(); - if (o->isVisible()) // later, we don't want to unhide the initially hidden overlays - { - mHiddenOverlays.push_back(o); // save off hidden overlays so we can unhide them later - o->hide(); - } - } - } - - /*----------------------------------------------------------------------------- - | Extend to unhide all of sample's temporarily hidden overlays. - -----------------------------------------------------------------------------*/ - void unpauseCurrentSample() override - { - SampleContext::unpauseCurrentSample(); - - for (std::vector::iterator i = mHiddenOverlays.begin(); i != mHiddenOverlays.end(); i++) - { - (*i)->show(); - } - - mHiddenOverlays.clear(); - } - - TrayManager* mTrayMgr; // SDK tray interface - Ogre::StringVector mLoadedSamplePlugins; // loaded sample plugins - std::set mSampleCategories; // sample categories - SampleSet mLoadedSamples; // loaded samples - SelectMenu* mCategoryMenu; // sample category select menu - SelectMenu* mSampleMenu; // sample select menu - Slider* mSampleSlider; // sample slider bar - Label* mTitleLabel; // sample title label - TextBox* mDescBox; // sample description box - SelectMenu* mRendererMenu; // render system selection menu - std::vector mHiddenOverlays; // sample overlays hidden for pausing - std::vector mThumbs; // sample thumbnails - Ogre::Real mCarouselPlace; // current state of carousel - int mLastViewTitle; // last sample title viewed - int mLastViewCategory; // last sample category viewed - int mLastSampleIndex; // index of last sample running - int mStartSampleIndex; // directly starts the sample with the given index - public: -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - SampleBrowserGestureView *mGestureView; -#endif - bool mIsShuttingDown; - bool mGrabInput; - }; -} - -#endif diff --git a/Samples/Browser/include/SampleBrowser_iOS.h b/Samples/Browser/include/SampleBrowser_iOS.h deleted file mode 100644 index e19261a5640..00000000000 --- a/Samples/Browser/include/SampleBrowser_iOS.h +++ /dev/null @@ -1,213 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ - -#ifndef __SampleBrowser_iOS_H__ -#define __SampleBrowser_iOS_H__ - -#include "OgrePlatform.h" - -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS -#error This header is for use with iOS only -#endif - -#import -#import - -// Defaulting to 2 means that we run at 30 frames per second. For 60 frames, use a value of 1. -// 30 FPS is usually sufficient and results in lower power consumption. -#define DISPLAYLINK_FRAME_INTERVAL 2 - -#ifdef __OBJC__ - -namespace OgreBites -{ - class SampleBrowser; -} - -@interface SampleBrowserGestureView : UIView -{ - OgreBites::SampleBrowser *mBrowser; -} -@property (assign) OgreBites::SampleBrowser *mBrowser; - -@end - -#import "SampleBrowser.h" - -@interface AppDelegate : NSObject -{ - OgreBites::SampleBrowser sb; - - CADisplayLink *mDisplayLink; - NSDate* mDate; - NSTimeInterval mLastFrameTime; -} - -- (void)go; -- (void)renderOneFrame:(id)sender; - -@property (nonatomic) NSTimeInterval mLastFrameTime; - -@end - -@implementation AppDelegate - -@dynamic mLastFrameTime; - -- (NSTimeInterval)mLastFrameTime -{ - return mLastFrameTime; -} - -- (void)setLastFrameTime:(NSTimeInterval)frameInterval -{ - // Frame interval defines how many display frames must pass between each time the - // display link fires. The display link will only fire 30 times a second when the - // frame internal is two on a display that refreshes 60 times a second. The default - // frame interval setting of one will fire 60 times a second when the display refreshes - // at 60 times a second. A frame interval setting of less than one results in undefined - // behavior. - if (frameInterval >= 1) - { - mLastFrameTime = frameInterval; - } -} - -- (void)go { - - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - - try { - sb.go(); - } catch( Ogre::Exception& e ) { - std::cerr << "An exception has occurred: " << - e.getFullDescription().c_str() << std::endl; - } - - [pool release]; -} - -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions -{ - mLastFrameTime = DISPLAYLINK_FRAME_INTERVAL; - mDisplayLink = nil; - - [self go]; - - return YES; -} - -- (void)applicationWillTerminate:(UIApplication *)application -{ - sb.shutdown(); -} - -- (void)applicationDidBecomeActive:(UIApplication *)application -{ - // Reset event times and reallocate the date and displaylink objects - Ogre::Root::getSingleton().clearEventTimes(); - mDate = [[NSDate alloc] init]; - mLastFrameTime = DISPLAYLINK_FRAME_INTERVAL; // Reset the timer - - mDisplayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(renderOneFrame:)]; - [mDisplayLink setFrameInterval:mLastFrameTime]; - [mDisplayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; -} - -- (void)applicationWillResignActive:(UIApplication *)application -{ - Ogre::Root::getSingleton().saveConfig(); - - [mDate release]; - mDate = nil; - - [mDisplayLink invalidate]; - mDisplayLink = nil; -} - -- (void)renderOneFrame:(id)sender -{ - [sb.mGestureView becomeFirstResponder]; - - // NSTimeInterval is a simple typedef for double - NSTimeInterval currentFrameTime = -[mDate timeIntervalSinceNow]; - NSTimeInterval differenceInSeconds = currentFrameTime - mLastFrameTime; - mLastFrameTime = currentFrameTime; - - dispatch_async(dispatch_get_main_queue(), ^(void) - { - Ogre::Root::getSingleton().renderOneFrame((Ogre::Real)differenceInSeconds); - }); -} - -@end - -@implementation SampleBrowserGestureView - -@synthesize mBrowser; - -- (BOOL)canBecomeFirstResponder -{ - return YES; -} - -- (void)dealloc { - [super dealloc]; -} - -- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event { - if(mBrowser && event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake) - mBrowser->motionBegan(); - - if ([super respondsToSelector:@selector(motionBegan:withEvent:)]) { - [super motionBegan:motion withEvent:event]; - } -} - -- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { - if(mBrowser && event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake) - mBrowser->motionEnded(); - - if ([super respondsToSelector:@selector(motionEnded:withEvent:)]) { - [super motionEnded:motion withEvent:event]; - } -} - -- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event { - if(mBrowser && event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake) - mBrowser->motionCancelled(); - - if ([super respondsToSelector:@selector(motionCancelled:withEvent:)]) { - [super motionCancelled:motion withEvent:event]; - } -} -@end - -#endif - -#endif diff --git a/Samples/Browser/include/gestureDetector.h b/Samples/Browser/include/gestureDetector.h deleted file mode 100644 index 9c4aaae6afe..00000000000 --- a/Samples/Browser/include/gestureDetector.h +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright 2013 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -//-------------------------------------------------------------------------------- -// gestureDetector.h -//-------------------------------------------------------------------------------- -#ifndef GESTUREDETECTOR_H_ -#define GESTUREDETECTOR_H_ - -#include - -#include -#include -#include -#include - -// adapt to OGRE -#include "OgreVector.h" -#include -#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "Ogre", __VA_ARGS__)) -#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "Ogre", __VA_ARGS__)) - -namespace ndk_helper -{ -typedef Ogre::Vector2 Vec2; - -//-------------------------------------------------------------------------------- -// Constants -//-------------------------------------------------------------------------------- -const int32_t DOUBLE_TAP_TIMEOUT = 300 * 1000000; -const int32_t TAP_TIMEOUT = 180 * 1000000; -const int32_t DOUBLE_TAP_SLOP = 100; -const int32_t TOUCH_SLOP = 8; - -enum -{ - GESTURE_STATE_NONE = 0, - GESTURE_STATE_START = 1, - GESTURE_STATE_MOVE = 2, - GESTURE_STATE_END = 4, - GESTURE_STATE_ACTION = (GESTURE_STATE_START | GESTURE_STATE_END), -}; -typedef int32_t GESTURE_STATE; - -/****************************************************************** - * Base class of Gesture Detectors - * GestureDetectors handles input events and detect gestures - * Note that different detectors may detect gestures with an event at - * same time. The caller needs to manage gesture priority accordingly - * - */ -class GestureDetector -{ -protected: - float dp_factor_; -public: - GestureDetector(); - virtual ~GestureDetector() - { - } - virtual void SetConfiguration( AConfiguration* config ); - - virtual GESTURE_STATE Detect( const AInputEvent* motion_event ) = 0; -}; - -/****************************************************************** - * Tap gesture detector - * Returns GESTURE_STATE_ACTION when a tap gesture is detected - * - */ -class TapDetector: public GestureDetector -{ -private: - int32_t down_pointer_id_; - float down_x_; - float down_y_; -public: - TapDetector() - { - } - virtual ~TapDetector() - { - } - GESTURE_STATE Detect( const AInputEvent* motion_event ) override; -}; - -/****************************************************************** - * Pinch gesture detector - * Returns GESTURE_STATE_ACTION when a double-tap gesture is detected - * - */ -class DoubletapDetector: public GestureDetector -{ -private: - TapDetector tap_detector_; - int64_t last_tap_time_; - float last_tap_x_; - float last_tap_y_; - -public: - DoubletapDetector() - { - } - virtual ~DoubletapDetector() - { - } - GESTURE_STATE Detect( const AInputEvent* motion_event ) override; - void SetConfiguration( AConfiguration* config ) override; -}; - -/****************************************************************** - * Double gesture detector - * Returns pinch gesture state when a pinch gesture is detected - * The class handles multiple touches more than 2 - * When the finger 1,2,3 are tapped and then finger 1 is released, - * the detector start new pinch gesture with finger 2 & 3. - */ -class PinchDetector: public GestureDetector -{ -private: - int32_t FindIndex( const AInputEvent* event, int32_t id ); - const AInputEvent* event_; - std::vector vec_pointers_; - -public: - PinchDetector() - { - } - virtual ~PinchDetector() - { - } - GESTURE_STATE Detect( const AInputEvent* event ) override; - bool GetPointers( Vec2& v1, Vec2& v2 ); -}; - -/****************************************************************** - * Drag gesture detector - * Returns drag gesture state when a drag-tap gesture is detected - * - */ -class DragDetector: public GestureDetector -{ -private: - int32_t FindIndex( const AInputEvent* event, int32_t id ); - const AInputEvent* event_; - std::vector vec_pointers_; -public: - DragDetector() - { - } - virtual ~DragDetector() - { - } - GESTURE_STATE Detect( const AInputEvent* event ) override; - bool GetPointer( Vec2& v ); -}; - -} //namespace ndkHelper -#endif /* GESTUREDETECTOR_H_ */ diff --git a/Samples/Browser/src/android_main.cpp b/Samples/Browser/src/android_main.cpp deleted file mode 100644 index 3f0999b4f6c..00000000000 --- a/Samples/Browser/src/android_main.cpp +++ /dev/null @@ -1,157 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ - -#include - -#include "SampleBrowser.h" -#include "gestureDetector.h" - -/*============================================================================= - | Ogre Android bridge - =============================================================================*/ -struct OgreAndroidBridge -{ - static void shutdown() - { - if(!mBrowser.getRoot()) - return; - - mBrowser.closeApp(); - } - - static int32_t handleInput(struct android_app* app, AInputEvent* event) - { - if (!mBrowser.getRenderWindow()) - return 0; - - static float len = 0; - - int wheel = 0; // overrides other events if mPinchGesture triggers - - if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) - { - - ndk_helper::GESTURE_STATE s = mPinchGesture.Detect(event); - - if(s & ndk_helper::GESTURE_STATE_START) { - ndk_helper::Vec2 p1, p2; - mPinchGesture.GetPointers(p1, p2); - len = (p1 - p2).length(); - } else if (s & ndk_helper::GESTURE_STATE_MOVE) { - ndk_helper::Vec2 p1, p2; - mPinchGesture.GetPointers(p1, p2); - float curr = (p1 - p2).length(); - - if(fabs(curr - len)/mBrowser.getRenderWindow()->getWidth() > 0.01) { - wheel = (curr - len) > 0 ? 1 : -1; - len = curr; - } - } - } - - mBrowser._fireInputEventAndroid(event, wheel); - - return 1; - } - - static void handleCmd(struct android_app* app, int32_t cmd) - { - switch (cmd) - { - case APP_CMD_SAVE_STATE: - break; - case APP_CMD_INIT_WINDOW: - if (app->window) - { - if (!mBrowser.getRenderWindow()) - { - mBrowser.initAppForAndroid(app->activity->assetManager, app->window); - } - else - { - AConfiguration* config = AConfiguration_new(); - AConfiguration_fromAssetManager(config, app->activity->assetManager); - mBrowser.getRenderWindow()->_notifySurfaceCreated(app->window, config); - AConfiguration_delete(config); - } - } - break; - case APP_CMD_TERM_WINDOW: - if(mBrowser.getRenderWindow()) - mBrowser.getRenderWindow()->_notifySurfaceDestroyed(); - break; - case APP_CMD_RESUME: - if(mBrowser.getRenderWindow()) - mBrowser.getRenderWindow()->setVisible(true); - break; - case APP_CMD_PAUSE: - if(mBrowser.getRenderWindow()) - mBrowser.getRenderWindow()->setVisible(false); - break; - case APP_CMD_CONFIG_CHANGED: - break; - } - } - - static void go(struct android_app* state) - { - int ident, events; - struct android_poll_source* source; - - while (true) - { - while ((ident = ALooper_pollAll(0, NULL, &events, (void**)&source)) >= 0) - { - if (source != NULL) - source->process(state, source); - - if (state->destroyRequested != 0) - return; - } - - if(mBrowser.getRenderWindow() && mBrowser.getRenderWindow()->isActive()) - { - mBrowser.getRoot()->renderOneFrame(); - } - } - } - -private: - static OgreBites::SampleBrowser mBrowser; - static ndk_helper::PinchDetector mPinchGesture; -}; - -OgreBites::SampleBrowser OgreAndroidBridge::mBrowser; -ndk_helper::PinchDetector OgreAndroidBridge::mPinchGesture; - -void android_main(struct android_app* state) -{ - state->onAppCmd = &OgreAndroidBridge::handleCmd; - state->onInputEvent = &OgreAndroidBridge::handleInput; - OgreAndroidBridge::go(state); -} diff --git a/Samples/Browser/src/gestureDetector.cpp b/Samples/Browser/src/gestureDetector.cpp deleted file mode 100644 index 1160a116f72..00000000000 --- a/Samples/Browser/src/gestureDetector.cpp +++ /dev/null @@ -1,350 +0,0 @@ -/* - * Copyright 2013 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "gestureDetector.h" - -//-------------------------------------------------------------------------------- -// gestureDetector.cpp -//-------------------------------------------------------------------------------- -namespace ndk_helper -{ - -//-------------------------------------------------------------------------------- -// includes -//-------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------- -// GestureDetector -//-------------------------------------------------------------------------------- -GestureDetector::GestureDetector() -{ - dp_factor_ = 1.f; -} - -void GestureDetector::SetConfiguration( AConfiguration* config ) -{ - dp_factor_ = 160.f / AConfiguration_getDensity( config ); -} - -//-------------------------------------------------------------------------------- -// TapDetector -//-------------------------------------------------------------------------------- -GESTURE_STATE TapDetector::Detect( const AInputEvent* motion_event ) -{ - if( AMotionEvent_getPointerCount( motion_event ) > 1 ) - { - //Only support single touch - return false; - } - - int32_t action = AMotionEvent_getAction( motion_event ); - unsigned int flags = action & AMOTION_EVENT_ACTION_MASK; - switch( flags ) - { - case AMOTION_EVENT_ACTION_DOWN: - down_pointer_id_ = AMotionEvent_getPointerId( motion_event, 0 ); - down_x_ = AMotionEvent_getX( motion_event, 0 ); - down_y_ = AMotionEvent_getY( motion_event, 0 ); - break; - case AMOTION_EVENT_ACTION_UP: - { - int64_t eventTime = AMotionEvent_getEventTime( motion_event ); - int64_t downTime = AMotionEvent_getDownTime( motion_event ); - if( eventTime - downTime <= TAP_TIMEOUT ) - { - if( down_pointer_id_ == AMotionEvent_getPointerId( motion_event, 0 ) ) - { - float x = AMotionEvent_getX( motion_event, 0 ) - down_x_; - float y = AMotionEvent_getY( motion_event, 0 ) - down_y_; - if( x * x + y * y < TOUCH_SLOP * TOUCH_SLOP * dp_factor_ ) - { - LOGI( "TapDetector: Tap detected" ); - return GESTURE_STATE_ACTION; - } - } - } - break; - } - } - return GESTURE_STATE_NONE; -} - -//-------------------------------------------------------------------------------- -// DoubletapDetector -//-------------------------------------------------------------------------------- -GESTURE_STATE DoubletapDetector::Detect( const AInputEvent* motion_event ) -{ - if( AMotionEvent_getPointerCount( motion_event ) > 1 ) - { - //Only support single double tap - return false; - } - - bool tap_detected = tap_detector_.Detect( motion_event ); - - int32_t action = AMotionEvent_getAction( motion_event ); - unsigned int flags = action & AMOTION_EVENT_ACTION_MASK; - switch( flags ) - { - case AMOTION_EVENT_ACTION_DOWN: - { - int64_t eventTime = AMotionEvent_getEventTime( motion_event ); - if( eventTime - last_tap_time_ <= DOUBLE_TAP_TIMEOUT ) - { - float x = AMotionEvent_getX( motion_event, 0 ) - last_tap_x_; - float y = AMotionEvent_getY( motion_event, 0 ) - last_tap_y_; - if( x * x + y * y < DOUBLE_TAP_SLOP * DOUBLE_TAP_SLOP * dp_factor_ ) - { - LOGI( "DoubletapDetector: Doubletap detected" ); - return GESTURE_STATE_ACTION; - } - } - break; - } - case AMOTION_EVENT_ACTION_UP: - if( tap_detected ) - { - last_tap_time_ = AMotionEvent_getEventTime( motion_event ); - last_tap_x_ = AMotionEvent_getX( motion_event, 0 ); - last_tap_y_ = AMotionEvent_getY( motion_event, 0 ); - } - break; - } - return GESTURE_STATE_NONE; -} - -void DoubletapDetector::SetConfiguration( AConfiguration* config ) -{ - dp_factor_ = 160.f / AConfiguration_getDensity( config ); - tap_detector_.SetConfiguration( config ); -} - -//-------------------------------------------------------------------------------- -// PinchDetector -//-------------------------------------------------------------------------------- - -int32_t PinchDetector::FindIndex( const AInputEvent* event, int32_t id ) -{ - int32_t count = AMotionEvent_getPointerCount( event ); - for( int32_t i = 0; i < count; ++i ) - { - if( id == AMotionEvent_getPointerId( event, i ) ) - return i; - } - return -1; -} - -GESTURE_STATE PinchDetector::Detect( const AInputEvent* event ) -{ - GESTURE_STATE ret = GESTURE_STATE_NONE; - int32_t action = AMotionEvent_getAction( event ); - uint32_t flags = action & AMOTION_EVENT_ACTION_MASK; - event_ = event; - - int32_t count = AMotionEvent_getPointerCount( event ); - switch( flags ) - { - case AMOTION_EVENT_ACTION_DOWN: - vec_pointers_.push_back( AMotionEvent_getPointerId( event, 0 ) ); - break; - case AMOTION_EVENT_ACTION_POINTER_DOWN: - { - int32_t iIndex = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) - >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; - vec_pointers_.push_back( AMotionEvent_getPointerId( event, iIndex ) ); - if( count == 2 ) - { - //Start new pinch - ret = GESTURE_STATE_START; - } - } - break; - case AMOTION_EVENT_ACTION_UP: - vec_pointers_.pop_back(); - break; - case AMOTION_EVENT_ACTION_POINTER_UP: - { - int32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) - >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; - int32_t released_pointer_id = AMotionEvent_getPointerId( event, index ); - - std::vector::iterator it = vec_pointers_.begin(); - std::vector::iterator it_end = vec_pointers_.end(); - int32_t i = 0; - for( ; it != it_end; ++it, ++i ) - { - if( *it == released_pointer_id ) - { - vec_pointers_.erase( it ); - break; - } - } - - if( i <= 1 ) - { - //Reset pinch or drag - if( count != 2 ) - { - //Start new pinch - ret = GESTURE_STATE_START | GESTURE_STATE_END; - } - } - } - break; - case AMOTION_EVENT_ACTION_MOVE: - switch( count ) - { - case 1: - break; - default: - //Multi touch - ret = GESTURE_STATE_MOVE; - break; - } - break; - case AMOTION_EVENT_ACTION_CANCEL: - break; - } - - return ret; -} - -bool PinchDetector::GetPointers( Vec2& v1, Vec2& v2 ) -{ - if( vec_pointers_.size() < 2 ) - return false; - - int32_t index = FindIndex( event_, vec_pointers_[0] ); - if( index == -1 ) - return false; - - float x = AMotionEvent_getX( event_, index ); - float y = AMotionEvent_getY( event_, index ); - - index = FindIndex( event_, vec_pointers_[1] ); - if( index == -1 ) - return false; - - float x2 = AMotionEvent_getX( event_, index ); - float y2 = AMotionEvent_getY( event_, index ); - - v1 = Vec2( x, y ); - v2 = Vec2( x2, y2 ); - - return true; -} - -//-------------------------------------------------------------------------------- -// DragDetector -//-------------------------------------------------------------------------------- - -int32_t DragDetector::FindIndex( const AInputEvent* event, int32_t id ) -{ - int32_t count = AMotionEvent_getPointerCount( event ); - for( int32_t i = 0; i < count; ++i ) - { - if( id == AMotionEvent_getPointerId( event, i ) ) - return i; - } - return -1; -} - -GESTURE_STATE DragDetector::Detect( const AInputEvent* event ) -{ - GESTURE_STATE ret = GESTURE_STATE_NONE; - int32_t action = AMotionEvent_getAction( event ); - int32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) - >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; - uint32_t flags = action & AMOTION_EVENT_ACTION_MASK; - event_ = event; - - int32_t count = AMotionEvent_getPointerCount( event ); - switch( flags ) - { - case AMOTION_EVENT_ACTION_DOWN: - vec_pointers_.push_back( AMotionEvent_getPointerId( event, 0 ) ); - ret = GESTURE_STATE_START; - break; - case AMOTION_EVENT_ACTION_POINTER_DOWN: - vec_pointers_.push_back( AMotionEvent_getPointerId( event, index ) ); - break; - case AMOTION_EVENT_ACTION_UP: - vec_pointers_.pop_back(); - ret = GESTURE_STATE_END; - break; - case AMOTION_EVENT_ACTION_POINTER_UP: - { - int32_t released_pointer_id = AMotionEvent_getPointerId( event, index ); - - std::vector::iterator it = vec_pointers_.begin(); - std::vector::iterator it_end = vec_pointers_.end(); - int32_t i = 0; - for( ; it != it_end; ++it, ++i ) - { - if( *it == released_pointer_id ) - { - vec_pointers_.erase( it ); - break; - } - } - - if( i <= 1 ) - { - //Reset pinch or drag - if( count == 2 ) - { - ret = GESTURE_STATE_START; - } - } - break; - } - case AMOTION_EVENT_ACTION_MOVE: - switch( count ) - { - case 1: - //Drag - ret = GESTURE_STATE_MOVE; - break; - default: - break; - } - break; - case AMOTION_EVENT_ACTION_CANCEL: - break; - } - - return ret; -} - -bool DragDetector::GetPointer( Vec2& v ) -{ - if( vec_pointers_.size() < 1 ) - return false; - - int32_t iIndex = FindIndex( event_, vec_pointers_[0] ); - if( iIndex == -1 ) - return false; - - float x = AMotionEvent_getX( event_, iIndex ); - float y = AMotionEvent_getY( event_, iIndex ); - - v = Vec2( x, y ); - - return true; -} - -} //namespace ndkHelper - diff --git a/Samples/Browser/src/main.cpp b/Samples/Browser/src/main.cpp deleted file mode 100644 index ef8b64657bd..00000000000 --- a/Samples/Browser/src/main.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#include -#include "OgrePlatform.h" -#include - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 -#define WIN32_LEAN_AND_MEAN -#include "windows.h" -#include "OgreString.h" -#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS -#include "SampleBrowser_iOS.h" -#endif - -#include "SampleBrowser.h" - -#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT -// short version of SDL_winrt_main_NonXAML.cpp -#include -#pragma warning(disable:4447) -#pragma comment(lib, "runtimeobject.lib") -INT WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, INT) -{ - if(FAILED(Windows::Foundation::Initialize(RO_INIT_MULTITHREADED))) { - return 1; - } - SDL_WinRTRunApp(main, NULL); - return 0; -} -#endif - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 -INT WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR cmdLine, INT) { - int argc = __argc; - char** argv = __argv; -#else -int main(int argc, char *argv[]) { -#endif -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - int retVal = UIApplicationMain(argc, argv, @"UIApplication", @"AppDelegate"); - [pool release]; - return retVal; -#else - - try - { - bool nograb = false; - if (argc >= 2 && Ogre::String(argv[1]) == "nograb") - nograb = true; - - int startUpSampleIdx = -1; - if (argc >= 3) - { - startUpSampleIdx = Ogre::StringConverter::parseInt(Ogre::String(argv[2]), -1); - } - else if (argc >= 2) - { - // first parameter can be either nograb or index. in the former case, we'll just - // get -1, which is fine. - startUpSampleIdx = Ogre::StringConverter::parseInt(Ogre::String(argv[1]), -1); - } - OgreBites::SampleBrowser brows (nograb, startUpSampleIdx); - brows.go(); - } - catch (Ogre::Exception& e) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - MessageBoxA(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_ICONERROR | MB_TASKMODAL); -#else - std::cerr << "An exception has occurred: " << e.getFullDescription().c_str() << std::endl; -#endif - } - return 0; -#endif -} diff --git a/Samples/CMakeLists.txt b/Samples/CMakeLists.txt deleted file mode 100644 index fe0a979a426..00000000000 --- a/Samples/CMakeLists.txt +++ /dev/null @@ -1,111 +0,0 @@ -# Configure Samples build - -# Add android JNI binding example -if(OGRE_BUILD_ANDROID_JNI_SAMPLE) - add_subdirectory(AndroidJNI) -endif() - -if (OGRE_BUILD_SAMPLES) - include_directories(${CMAKE_CURRENT_SOURCE_DIR}/Common/include) - - if (OGRE_BUILD_COMPONENT_RTSHADERSYSTEM) - add_definitions(-DINCLUDE_RTSHADER_SYSTEM) - set(SAMPLE_DEPENDENCIES ${SAMPLE_DEPENDENCIES} OgreRTShaderSystem) - endif () - - if (OGRE_BUILD_COMPONENT_BULLET) - set(SAMPLE_DEPENDENCIES ${SAMPLE_DEPENDENCIES} OgreBullet) - endif () - - if (OGRE_BUILD_COMPONENT_OVERLAY) - set(SAMPLE_DEPENDENCIES ${SAMPLE_DEPENDENCIES} OgreOverlay) - endif () - - if (OGRE_BUILD_COMPONENT_TERRAIN) - set(SAMPLE_DEPENDENCIES ${SAMPLE_DEPENDENCIES} OgreTerrain) - endif () - - if (OGRE_BUILD_COMPONENT_VOLUME) - set(SAMPLE_DEPENDENCIES ${SAMPLE_DEPENDENCIES} OgreVolume) - endif () - - if (OGRE_BUILD_COMPONENT_MESHLODGENERATOR AND OGRE_CONFIG_ENABLE_MESHLOD) - set(SAMPLE_DEPENDENCIES ${SAMPLE_DEPENDENCIES} OgreMeshLodGenerator) - endif () - - if(EMSCRIPTEN) - add_subdirectory(Emscripten) - return() - endif() - - ## Default Samples Plugin - file (GLOB SAMPLES_HEADERS ${PROJECT_SOURCE_DIR}/Samples/*/include) - include_directories(${SAMPLES_HEADERS}) - - file(GLOB SAMPLES_SOURCES ${PROJECT_SOURCE_DIR}/Samples/*/src/*.cpp) - - set(BLACKLIST Browser TerrainTessellation) - if(NOT OGRE_BUILD_PLUGIN_PCZ) - list(APPEND BLACKLIST PCZTestApp) - endif() - if(NOT OGRE_BUILD_COMPONENT_TERRAIN) - list(APPEND BLACKLIST EndlessWorld) - endif() - - foreach(FILTER_SAMPLE ${BLACKLIST}) - file(GLOB BLACKLIST_CPP ${PROJECT_SOURCE_DIR}/Samples/${FILTER_SAMPLE}/src/*.cpp) - list(REMOVE_ITEM SAMPLES_SOURCES ${BLACKLIST_CPP}) - endforeach() - - add_definitions(${OGRE_VISIBILITY_FLAGS}) - add_library(DefaultSamples ${OGRE_LIB_TYPE} - ${CMAKE_CURRENT_SOURCE_DIR}/Common/src/DefaultSamplesPlugin.cpp - ${SAMPLES_SOURCES} ${SAMPLES_HEADERS}) - target_link_libraries(DefaultSamples OgreMain ${SAMPLE_DEPENDENCIES} OgreBites) - - if(OGRE_BUILD_PLUGIN_PCZ) - target_link_libraries(DefaultSamples Plugin_PCZSceneManager) - target_compile_definitions(DefaultSamples PRIVATE -DHAVE_PCZ_PLUGIN) - endif() - - if(OGRE_BUILD_COMPONENT_OVERLAY_IMGUI) - target_compile_definitions(DefaultSamples PRIVATE -DHAVE_IMGUI) - endif() - - ogre_config_sample_lib(DefaultSamples) - - if (APPLE AND NOT APPLE_IOS) - # Set the INSTALL_PATH so that Samples can be installed in the application package - set_target_properties(DefaultSamples - PROPERTIES BUILD_WITH_INSTALL_RPATH 1 - INSTALL_NAME_DIR "@executable_path/../Plugins" - ) - endif() - - ## Add browser last - add_subdirectory(Browser) -endif () - -if (MSVC AND OGRE_BUILD_SAMPLES) - find_package(Wix) - if (Wix_FOUND) - # Create WiX setup for demo build - configure_file(${OGRE_TEMPLATES_DIR}/demos.wxs.in ${CMAKE_CURRENT_BINARY_DIR}/demos.wxs @ONLY) - configure_file(${OGRE_TEMPLATES_DIR}/demomedia.wxi.in ${CMAKE_CURRENT_BINARY_DIR}/demomedia.wxi @ONLY) - configure_file(${OGRE_TEMPLATES_DIR}/DemoLicense.rtf ${CMAKE_CURRENT_BINARY_DIR}/DemoLicense.rtf COPYONLY) - # Configure files, set media dir temporarily - set(OGRE_MEDIA_DIR_TMP ${OGRE_MEDIA_DIR_REL}) - set(OGRE_MEDIA_DIR_REL "Media") - configure_file(${OGRE_TEMPLATES_DIR}/resources.cfg.in ${CMAKE_CURRENT_BINARY_DIR}/resources.cfg @ONLY) - # restore - set(OGRE_MEDIA_DIR_REL ${OGRE_MEDIA_DIR_TMP}) - add_custom_target(demo_installer - COMMAND ${Wix_BINARY_DIR}/candle demos.wxs - COMMAND ${Wix_BINARY_DIR}/light -ext WixUIExtension -cultures:en-us -out OgreDemos_v${OGRE_VERSION_DASH_SEPARATED}.msi demos.wixobj - WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} - COMMENT "Building demo installer" VERBATIM - ) - # Make sure we build samples first - add_dependencies(demo_installer SampleBrowser) - endif() -endif() diff --git a/Samples/CSMShadows/include/CSMGpuConstants.h b/Samples/CSMShadows/include/CSMGpuConstants.h deleted file mode 100644 index 87c893ac060..00000000000 --- a/Samples/CSMShadows/include/CSMGpuConstants.h +++ /dev/null @@ -1,30 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -/* Copyright 2010-2012 Matthew Paul Reid - */ -#ifndef CSM_GPU_CONSTANTS_H -#define CSM_GPU_CONSTANTS_H - -#include "Ogre.h" - -namespace Ogre -{ - -class CSMGpuConstants : public ShadowTextureListener -{ -public: - CSMGpuConstants(size_t cascadeCount); - void shadowTextureCasterPreViewProj(Light* light, Camera* camera, size_t iteration) override; - -private: - Ogre::GpuSharedParametersPtr mParamsScaleBias; - - Ogre::Matrix4 mFirstCascadeViewMatrix; - Ogre::Real mFirstCascadeCamWidth; - Ogre::Real mViewRange; -}; - -} // namespace Ogre - -#endif // CSM_GPU_CONSTANTS_H diff --git a/Samples/CSMShadows/include/CSMShadows.h b/Samples/CSMShadows/include/CSMShadows.h deleted file mode 100644 index f57c9431a48..00000000000 --- a/Samples/CSMShadows/include/CSMShadows.h +++ /dev/null @@ -1,158 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -/* Copyright 2010-2012 Matthew Paul Reid - */ - -#include "SdkSample.h" - -#include "CSMGpuConstants.h" -#include "ShadowCameraSetupStableCSM.h" - -using namespace Ogre; -using namespace OgreBites; - -class CSMShadows : public SdkSample -{ -public: - CSMShadows() : mGpuConstants(0) - { - mInfo["Title"] = "CSM Shadows"; - mInfo["Description"] = "A demonstration of a custom shadow camera implementation"; - mInfo["Thumbnail"] = "thumb_csm.png"; - mInfo["Category"] = "Lighting"; - } - - void cleanupContent() override - { - mSceneMgr->removeShadowTextureListener(mGpuConstants); - delete mGpuConstants; - } - - enum { - NUM_CASCADES = 4 - }; - - void testCapabilities(const Ogre::RenderSystemCapabilities* caps) override - { - requireMaterial("CSMShadows/Rockwall"); - } - - void setupContent() override - { - mCameraMan->setStyle(CS_ORBIT); - - setupGeometry(); - setupLights(); - setupShadows(); - - mTrayMgr->showCursor(); - } - -private: - void setupGeometry() - { - float scale = 0.5f; - Vector3 scaleVec(scale, scale, scale); - { - SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - Entity* athene = mSceneMgr->createEntity("athene", "athene.mesh"); - athene->setMaterialName("CSMShadows/Athene"); - node->attachObject(athene); - node->translate(0, -27 * scale, 0); - node->yaw(Degree(90)); - node->setScale(scaleVec); - } - - { - SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - Entity* athene = mSceneMgr->createEntity("athene2", "athene.mesh"); - athene->setMaterialName("CSMShadows/Athene"); - node->attachObject(athene); - node->translate(30, -27 * scale, 22); - node->yaw(Degree(-45)); - node->setScale(scaleVec); - } - - Entity* pEnt; - // Columns - for (int x = -4; x <= 4; ++x) - { - for (int z = -4; z <= 4; ++z) - { - if (x != 0 || z != 0) - { - SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - pEnt = mSceneMgr->createEntity(StringUtil::format("col%d_%d", x, z), "column.mesh"); - pEnt->setMaterialName("CSMShadows/Rockwall"); - node->attachObject(pEnt); - node->translate(x * 500, 0, z * 500); - node->setScale(scale * 2, scale, scale * 2); - } - } - } - - // Skybox - mSceneMgr->setSkyBox(true, "Examples/StormySkyBox"); - - // Floor plane (use POSM plane def) - Plane* plane = new MovablePlane("*mPlane"); - plane->normal = Vector3::UNIT_Y; - plane->d = 107 * scale; - MeshManager::getSingleton().createPlane( - "MyPlane", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, *plane, 6000, 6000, 50, 50, true, - 1, 25.0f / scale, 25.0f / scale, Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity("plane", "MyPlane"); - pPlaneEnt->setMaterialName("CSMShadows/Rockwall"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - } - - void setupLights() - { - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); - Light* light = mSceneMgr->createLight(Light::LT_DIRECTIONAL); - Vector3 direction(1, -1, 0.4); - light->setCastShadows(true); - light->setShadowFarClipDistance(12000); - - auto node = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - node->attachObject(light); - node->setDirection(direction.normalisedCopy()); - } - - void setupShadows() - { - // Scene manager shadow settings - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE_INTEGRATED); - mSceneMgr->setShadowCasterRenderBackFaces(false); - - mSceneMgr->setShadowTextureCount(NUM_CASCADES); - mSceneMgr->setShadowTextureCountPerLightType(Light::LT_DIRECTIONAL, NUM_CASCADES); - - mGpuConstants = new CSMGpuConstants(NUM_CASCADES); - mSceneMgr->addShadowTextureListener(mGpuConstants); - - for (int i = 0; i < NUM_CASCADES; i++) - mSceneMgr->setShadowTextureConfig(i, 1024, 1024, PF_FLOAT32_R); - - float farClip = 5000.0f; - - // Create the CSM shadow setup - StableCSMShadowCameraSetup* shadowSetup = new StableCSMShadowCameraSetup(); - - float lambda = 0.93f; // lower lamdba means more uniform, higher lambda means more logarithmic - float firstSplitDist = 50.0f; - - shadowSetup->calculateSplitPoints(NUM_CASCADES, firstSplitDist, farClip, lambda); - StableCSMShadowCameraSetup::SplitPointList points = shadowSetup->getSplitPoints(); - - // Apply settings - shadowSetup->setSplitPoints(points); - float splitPadding = 1.0f; - shadowSetup->setSplitPadding(splitPadding); - mSceneMgr->setShadowCameraSetup(ShadowCameraSetupPtr(shadowSetup)); - } - - CSMGpuConstants* mGpuConstants; -}; diff --git a/Samples/CSMShadows/include/ShadowCameraSetupStableCSM.h b/Samples/CSMShadows/include/ShadowCameraSetupStableCSM.h deleted file mode 100644 index 13499e3f724..00000000000 --- a/Samples/CSMShadows/include/ShadowCameraSetupStableCSM.h +++ /dev/null @@ -1,69 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -/* Copyright 2010-2012 Matthew Paul Reid - */ -#ifndef SHADOW_CAMERA_SETUP_STABLE_CSM_H -#define SHADOW_CAMERA_SETUP_STABLE_CSM_H - -#include "Ogre.h" - -namespace Ogre -{ - -class StableCSMShadowCameraSetup : public Ogre::DefaultShadowCameraSetup -{ -public: - typedef std::vector SplitPointList; - -public: - StableCSMShadowCameraSetup(); - ~StableCSMShadowCameraSetup(); - - /** Calculate a new splitting scheme. - @param cascadeCount The number of cascades to use - @param firstSplitDist distance of the first split - @param farDist The far plane to use for the last split - @param lambda Value between 0 (linear splits) and 1 (logarithmic splits) - */ - void calculateSplitPoints(size_t cascadeCount, Ogre::Real firstSplitDist, Ogre::Real farDist, - Ogre::Real lambda = 0.95); - - /** Manually configure a new splitting scheme. - @param newSplitPoints A list which is cascadeCount + 1 entries long, containing the - split points. The first value is the near point, the last value is the - far point, and each value in between is both a far point of the previous - split, and a near point for the next one. - */ - void setSplitPoints(const SplitPointList& newSplitPoints); - - void setSplitPadding(Ogre::Real pad) { mSplitPadding = pad; } - - /** Get the padding factor to apply to the near & far distances when matching up - splits to one another, to avoid 'cracks'. - */ - Ogre::Real getSplitPadding() const { return mSplitPadding; } - /// Get the number of splits. - size_t getCascadeCount() const { return mCascadeCount; } - - /// Returns a stable CSM shadow camera for the given iteration - void getShadowCamera(const Ogre::SceneManager* sm, const Ogre::Camera* cam, - const Ogre::Viewport* vp, const Ogre::Light* light, Ogre::Camera* texCam, - size_t iteration) const override; - - /// Returns the calculated split points. - const SplitPointList& getSplitPoints() const { return mSplitPoints; } - -private: - void getShadowCameraForCascade(const Ogre::SceneManager* sm, const Ogre::Camera* cam, - const Ogre::Viewport* vp, const Ogre::Light* light, Ogre::Camera* texCam, - size_t iteration, Ogre::Real nearSplit, Ogre::Real farSplit) const; - - size_t mCascadeCount; - SplitPointList mSplitPoints; - Ogre::Real mSplitPadding; -}; - -} // namespace Ogre - -#endif // SHADOW_CAMERA_SETUP_STABLE_CSM_H diff --git a/Samples/CSMShadows/src/CSMGpuConstants.cpp b/Samples/CSMShadows/src/CSMGpuConstants.cpp deleted file mode 100644 index bc1a191ed93..00000000000 --- a/Samples/CSMShadows/src/CSMGpuConstants.cpp +++ /dev/null @@ -1,58 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -/* Copyright 2010-2012 Matthew Paul Reid -*/ -#include "CSMGpuConstants.h" - -namespace Ogre -{ - -CSMGpuConstants::CSMGpuConstants(size_t cascadeCount) -{ - mParamsScaleBias = - GpuProgramManager::getSingleton().getSharedParameters("params_shadowMatrixScaleBias"); - for (size_t i = 1; i < cascadeCount; i++) - { - mParamsScaleBias->addConstantDefinition("texMatrixScaleBias" + StringConverter::toString(i), - GCT_FLOAT4); - } -} - -void CSMGpuConstants::shadowTextureCasterPreViewProj(Light* light, Camera* texCam, size_t index) -{ - if (index == 0) - { - mFirstCascadeViewMatrix = texCam->getViewMatrix(); - mFirstCascadeCamWidth = texCam->getOrthoWindowWidth(); - mViewRange = texCam->getFarClipDistance() - texCam->getNearClipDistance(); - } - else - { - Matrix4 mat0 = mFirstCascadeViewMatrix; - Matrix4 mat1 = texCam->getViewMatrix(); - - Real offsetX = mat1[0][3] - mat0[0][3]; - Real offsetY = mat1[1][3] - mat0[1][3]; - Real offsetZ = mat1[2][3] - mat0[2][3]; - - Real width0 = mFirstCascadeCamWidth; - Real width1 = texCam->getOrthoWindowWidth(); - - Real oneOnWidth = 1.0f / width0; - Real offCenter = width1 / (2.0f * width0) - 0.5; - - RenderSystem* rs = Root::getSingletonPtr()->getRenderSystem(); - float depthRange = Math::Abs(rs->getMinimumDepthInputValue() - rs->getMaximumDepthInputValue()); - - Vector4 result; - result.x = offsetX * oneOnWidth + offCenter; - result.y = -offsetY * oneOnWidth + offCenter; - result.z = -depthRange * offsetZ / mViewRange; - result.w = width0 / width1; - - mParamsScaleBias->setNamedConstant("texMatrixScaleBias" + StringConverter::toString(index), result); - } -} - -} // namespace Ogre diff --git a/Samples/CSMShadows/src/ShadowCameraSetupStableCSM.cpp b/Samples/CSMShadows/src/ShadowCameraSetupStableCSM.cpp deleted file mode 100644 index 84522e01696..00000000000 --- a/Samples/CSMShadows/src/ShadowCameraSetupStableCSM.cpp +++ /dev/null @@ -1,173 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -/* Copyright 2010-2012 Matthew Paul Reid -*/ -#include "ShadowCameraSetupStableCSM.h" -#include "CSMGpuConstants.h" - -namespace Ogre { - -StableCSMShadowCameraSetup::StableCSMShadowCameraSetup() : - mSplitPadding(1.0f) -{ - calculateSplitPoints(3, 100, 100000); -} -//--------------------------------------------------------------------- -StableCSMShadowCameraSetup::~StableCSMShadowCameraSetup() -{ -} -//--------------------------------------------------------------------- -void StableCSMShadowCameraSetup::calculateSplitPoints(size_t cascadeCount, Real firstSplitDist, Real farDist, Real lambda) -{ - OgreAssert(cascadeCount >= 2, "Cannot specify less than 2 cascades"); - - mSplitPoints.resize(cascadeCount + 1); - mCascadeCount = cascadeCount; - - mSplitPoints[0] = 0; - firstSplitDist = std::max((Real)0.001, firstSplitDist); - - for (size_t i = 1; i <= mCascadeCount; i++) - { - Real fraction = (Real)(i-1) / (mCascadeCount-1); - Real logDist = firstSplitDist * Math::Pow(farDist / firstSplitDist, fraction); - Real linDist = firstSplitDist + fraction * (farDist - firstSplitDist); - Real splitPoint = linDist + lambda * (logDist - linDist); - - mSplitPoints[i] = splitPoint; - } -} -//--------------------------------------------------------------------- -void StableCSMShadowCameraSetup::setSplitPoints(const SplitPointList& newSplitPoints) -{ - OgreAssert(newSplitPoints.size() >= 3, "Cannot specify less than 2 splits"); // 3, not 2 since splits + 1 points - mCascadeCount = newSplitPoints.size() - 1; - mSplitPoints = newSplitPoints; -} - -//--------------------------------------------------------------------- -void StableCSMShadowCameraSetup::getShadowCamera(const Ogre::SceneManager *sm, const Ogre::Camera *cam, - const Ogre::Viewport *vp, const Ogre::Light *light, Ogre::Camera *texCam, size_t iteration) const -{ - texCam->setLodBias(0.25); - - // apply the right clip distance. - Real nearDist = mSplitPoints[iteration]; - Real farDist = mSplitPoints[iteration + 1]; - - // Add a padding factor to internal distances so that the connecting split point will not have bad artifacts. - if (iteration > 0) - { - nearDist -= mSplitPadding; - } - if (iteration < mCascadeCount - 1) - { - farDist += mSplitPadding; - } - - getShadowCameraForCascade(sm, cam, vp, light, texCam, iteration, nearDist, farDist); -} - - - -void StableCSMShadowCameraSetup::getShadowCameraForCascade (const SceneManager *sm, const Camera *cam, - const Viewport *vp, const Light *light, Camera *texCam, size_t iteration, - Ogre::Real nearSplit, Ogre::Real farSplit) const -{ - OgreAssert(light->getType() == Light::LT_DIRECTIONAL, "only directional lights supported"); - - Vector3 pos, dir; - Matrix3 rot; - - // reset custom view / projection matrix in case already set - texCam->setCustomViewMatrix(false); - texCam->setCustomProjectionMatrix(false); - - // set up the shadow texture - // Set ortho projection - texCam->setProjectionType(PT_ORTHOGRAPHIC); - // set easy FOV and near dist so that texture covers far dist - texCam->setFOVy(Degree(90)); - - float nearClip = light->_deriveShadowNearClipDistance(cam); - float farClip = light->_deriveShadowFarClipDistance(); - - texCam->setNearClipDistance(nearClip); - texCam->setFarClipDistance(farClip); - - // need an actual farClip, so make one up - if (farClip == 0) - farClip = nearClip * 3000; - - // Calculate texCam direction, which same as directional light direction - dir = - light->getDerivedDirection(); // backwards since point down -z - dir.normalise(); - - - //get light orientation - - Vector3 up = Vector3::UNIT_Y; - // Check it's not coincident with dir - if (Math::Abs(up.dotProduct(dir)) >= 1.0f) - { - // Use camera up - up = Vector3::UNIT_Z; - } - rot = Math::lookRotation(dir, up); - - // Find minimum enclosing sphere for view frustum - // We do this in local space so that we don't have slight precision variation between frames - float vertical = Math::Tan(cam->getFOVy()*0.5f); - float horizontal = Math::Tan(cam->getFOVy()*0.5f * cam->getAspectRatio()); - - Vector3 topLeftFar; - topLeftFar.x = horizontal * farSplit; - topLeftFar.y = vertical * farSplit; - topLeftFar.z = farSplit; - - Vector3 bottomRightNear; - bottomRightNear.z = nearSplit; - bottomRightNear.x = horizontal * bottomRightNear.z; - bottomRightNear.y = vertical * bottomRightNear.z; - - float dist = (topLeftFar.squaredLength() - bottomRightNear.squaredLength()) / (2 * (topLeftFar.z - bottomRightNear.z)); - - if (dist > farSplit) - { - dist = farSplit; - } - - Vector3 localPos(0, 0, -dist); // we have now found the point along frustum center which is equi-distant to the opposing corner positions - - Real diameter = 2.0f * topLeftFar.distance(-localPos); - pos = cam->getDerivedPosition() + cam->getDerivedOrientation() * localPos; - - diameter *= (Real)1.01; // allow some boundary pixels for filtering etc. TODO - make this a user constant - pos += dir * 0.5 * (farClip - nearClip); // pull light back so we can see the scene - - - //calculate window size - texCam->setOrthoWindowWidth(diameter); - - - // Round local x/y position based on a world-space texel; this helps to reduce - // jittering caused by the projection moving with the camera - Real worldTexelSize = (texCam->getOrthoWindowWidth()) / texCam->getViewport()->getActualWidth(); - - //convert world space camera position into light space - Vector3 lightSpacePos = rot.transpose() * pos; - - //snap to nearest texel - lightSpacePos.x -= fmod(lightSpacePos.x, worldTexelSize); - lightSpacePos.y -= fmod(lightSpacePos.y, worldTexelSize); - - //convert back to world space - pos = rot * lightSpacePos; - - // Finally set position - texCam->getParentNode()->setPosition(pos); - texCam->getParentNode()->setOrientation(rot); -} - -} diff --git a/Samples/Character/include/CharacterSample.h b/Samples/Character/include/CharacterSample.h deleted file mode 100644 index cdcf9715b5d..00000000000 --- a/Samples/Character/include/CharacterSample.h +++ /dev/null @@ -1,150 +0,0 @@ -#ifndef __Character_H__ -#define __Character_H__ - -#include "SdkSample.h" -#include "SinbadCharacterController.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_Character : public SdkSample -{ -public: - - Sample_Character() - { - mInfo["Title"] = "Character"; - mInfo["Description"] = "A demo showing 3rd-person character control and use of TagPoints."; - mInfo["Thumbnail"] = "thumb_char.png"; - mInfo["Category"] = "Animation"; - mInfo["Help"] = "Use the WASD keys to move Sinbad, and the space bar to jump. " - "Use mouse to look around and mouse wheel to zoom. Press Q to take out or put back " - "Sinbad's swords. With the swords equipped, you can left click to slice vertically or " - "right click to slice horizontally. When the swords are not equipped, press E to " - "start/stop a silly dance routine."; - } - - bool frameRenderingQueued(const FrameEvent& evt) override - { - // let character update animations and camera - mChara->addTime(evt.timeSinceLastFrame); - return SdkSample::frameRenderingQueued(evt); - } - - bool keyPressed(const KeyboardEvent& evt) override - { - // relay input events to character controller - if (!mTrayMgr->isDialogVisible()) mChara->injectKeyDown(evt); - return SdkSample::keyPressed(evt); - } - - bool keyReleased(const KeyboardEvent& evt) override - { - // relay input events to character controller - if (!mTrayMgr->isDialogVisible()) mChara->injectKeyUp(evt); - return SdkSample::keyReleased(evt); - } - - bool mouseMoved(const MouseMotionEvent& evt) override - { - // Relay input events to character controller. - if (!mTrayMgr->isDialogVisible()) mChara->injectMouseMove(evt); - return SdkSample::mouseMoved(evt); - } - - bool mouseWheelRolled(const MouseWheelEvent& evt) override { - // Relay input events to character controller. - if (!mTrayMgr->isDialogVisible()) mChara->injectMouseWheel(evt); - return SdkSample::mouseWheelRolled(evt); - } - - bool mousePressed(const MouseButtonEvent& evt) override - { - // Relay input events to character controller. - if (!mTrayMgr->isDialogVisible()) mChara->injectMouseDown(evt); - return SdkSample::mousePressed(evt); - } - -protected: - - void setupContent() override - { -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - // add integrated depth shadows - auto& rtShaderGen = RTShader::ShaderGenerator::getSingleton(); - auto schemRenderState = rtShaderGen.getRenderState(MSN_SHADERGEN); - schemRenderState->addTemplateSubRenderState(rtShaderGen.createSubRenderState(RTShader::SRS_SHADOW_MAPPING)); - - // Make this viewport work with shader generator scheme. - mViewport->setMaterialScheme(MSN_SHADERGEN); - // update scheme for FFP supporting rendersystems - MaterialManager::getSingleton().setActiveScheme(mViewport->getMaterialScheme()); -#endif - // set background and some fog - mViewport->setBackgroundColour(ColourValue(1.0f, 1.0f, 0.8f)); - mSceneMgr->setFog(Ogre::FOG_LINEAR, ColourValue(1.0f, 1.0f, 0.8f), 0, 15, 100); - - // set shadow properties - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE_INTEGRATED); - mSceneMgr->setShadowTexturePixelFormat(PF_DEPTH16); - mSceneMgr->setShadowColour(ColourValue(0.5, 0.5, 0.5)); - mSceneMgr->setShadowTextureSize(1024); - mSceneMgr->setShadowTextureCount(1); - mSceneMgr->setShadowDirLightTextureOffset(0); - mSceneMgr->setShadowFarDistance(50); - mSceneMgr->setShadowCameraSetup(LiSPSMShadowCameraSetup::create()); - - // disable default camera control so the character can do its own - mCameraMan->setStyle(CS_MANUAL); - - // use a small amount of ambient lighting - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); - - // add a bright light above the scene - Light* light = mSceneMgr->createLight(Light::LT_POINT); - mSceneMgr->getRootSceneNode() - ->createChildSceneNode(Vector3(-10, 40, 20)) - ->attachObject(light); - light->setSpecularColour(ColourValue::White); - - // create a floor mesh resource - MeshManager::getSingleton().createPlane("floor", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - Plane(Vector3::UNIT_Y, 0), 100, 100, 10, 10, true, 1, 10, 10, Vector3::UNIT_Z); - - // create a floor entity, give it a material, and place it at the origin - Entity* floor = mSceneMgr->createEntity("Floor", "floor"); - floor->setMaterialName("Examples/Rockwall"); - floor->setCastShadows(false); - mSceneMgr->getRootSceneNode()->attachObject(floor); - -// LogManager::getSingleton().logMessage("creating sinbad"); - // create our character controller - mChara = new SinbadCharacterController(mCamera); - -// LogManager::getSingleton().logMessage("toggling stats"); - mTrayMgr->toggleAdvancedFrameStats(); - -// LogManager::getSingleton().logMessage("creating panel"); - StringVector items; - items.push_back("Help"); - ParamsPanel* help = mTrayMgr->createParamsPanel(TL_TOPLEFT, "HelpMessage", 100, items); - help->setParamValue("Help", "H / F1"); - -// LogManager::getSingleton().logMessage("all done"); - } - - void cleanupContent() override - { - // clean up character controller and the floor mesh - if (mChara) - { - delete mChara; - mChara = 0; - } - MeshManager::getSingleton().remove("floor", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - } - - SinbadCharacterController* mChara; -}; - -#endif diff --git a/Samples/Character/include/SinbadCharacterController.h b/Samples/Character/include/SinbadCharacterController.h deleted file mode 100644 index 5f75b517177..00000000000 --- a/Samples/Character/include/SinbadCharacterController.h +++ /dev/null @@ -1,516 +0,0 @@ -#ifndef __Sinbad_H__ -#define __Sinbad_H__ - -#include "Ogre.h" -#include "OgreInput.h" - -using namespace Ogre; -using namespace OgreBites; - -#define CHAR_HEIGHT 5 // height of character's center of mass above ground -#define CAM_HEIGHT 2 // height of camera above character's center of mass -#define RUN_SPEED 17 // character running speed in units per second -#define TURN_SPEED 500.0f // character turning in degrees per second -#define ANIM_FADE_SPEED 7.5f // animation crossfade speed in % of full weight per second -#define JUMP_ACCEL 30.0f // character jump acceleration in upward units per squared second -#define GRAVITY 90.0f // gravity in downward units per squared second - -class SinbadCharacterController -{ -private: - - // all the animations our character has, and a null ID - // some of these affect separate body parts and will be blended together - enum AnimID - { - ANIM_IDLE_BASE, - ANIM_IDLE_TOP, - ANIM_RUN_BASE, - ANIM_RUN_TOP, - ANIM_HANDS_CLOSED, - ANIM_HANDS_RELAXED, - ANIM_DRAW_SWORDS, - ANIM_SLICE_VERTICAL, - ANIM_SLICE_HORIZONTAL, - ANIM_DANCE, - ANIM_JUMP_START, - ANIM_JUMP_LOOP, - ANIM_JUMP_END, - NUM_ANIMS, - ANIM_NONE = NUM_ANIMS - }; - -public: - - SinbadCharacterController(Camera* cam) : mBaseAnimID(ANIM_NONE), mTopAnimID(ANIM_NONE) - { - setupBody(cam->getSceneManager()); - setupCamera(cam); - setupAnimations(); - } - - void addTime(Real deltaTime) - { - updateBody(deltaTime); - updateAnimations(deltaTime); - updateCamera(deltaTime); - } - - void injectKeyDown(const KeyboardEvent& evt) - { - Keycode key = evt.keysym.sym; - if (key == 'q' && (mTopAnimID == ANIM_IDLE_TOP || mTopAnimID == ANIM_RUN_TOP)) - { - // take swords out (or put them back, since it's the same animation but reversed) - setTopAnimation(ANIM_DRAW_SWORDS, true); - mTimer = 0; - } - else if (key == 'e' && !mSwordsDrawn) - { - if (mTopAnimID == ANIM_IDLE_TOP || mTopAnimID == ANIM_RUN_TOP) - { - // start dancing - setBaseAnimation(ANIM_DANCE, true); - setTopAnimation(ANIM_NONE); - // disable hand animation because the dance controls hands - mAnims[ANIM_HANDS_RELAXED]->setEnabled(false); - } - else if (mBaseAnimID == ANIM_DANCE) - { - // stop dancing - setBaseAnimation(ANIM_IDLE_BASE); - setTopAnimation(ANIM_IDLE_TOP); - // re-enable hand animation - mAnims[ANIM_HANDS_RELAXED]->setEnabled(true); - } - } - - // keep track of the player's intended direction - else if (key == 'w') mKeyDirection.z = -1; - else if (key == 'a') mKeyDirection.x = -1; - else if (key == 's') mKeyDirection.z = 1; - else if (key == 'd') mKeyDirection.x = 1; - - else if (key == SDLK_SPACE && (mTopAnimID == ANIM_IDLE_TOP || mTopAnimID == ANIM_RUN_TOP)) - { - // jump if on ground - setBaseAnimation(ANIM_JUMP_START, true); - setTopAnimation(ANIM_NONE); - mTimer = 0; - } - - if (!mKeyDirection.isZeroLength() && mBaseAnimID == ANIM_IDLE_BASE) - { - // start running if not already moving and the player wants to move - setBaseAnimation(ANIM_RUN_BASE, true); - if (mTopAnimID == ANIM_IDLE_TOP) setTopAnimation(ANIM_RUN_TOP, true); - } - } - - void injectKeyUp(const KeyboardEvent& evt) - { - Keycode key = evt.keysym.sym; - // keep track of the player's intended direction - if (key == 'w' && mKeyDirection.z == -1) mKeyDirection.z = 0; - else if (key == 'a' && mKeyDirection.x == -1) mKeyDirection.x = 0; - else if (key == 's' && mKeyDirection.z == 1) mKeyDirection.z = 0; - else if (key == 'd' && mKeyDirection.x == 1) mKeyDirection.x = 0; - - if (mKeyDirection.isZeroLength() && mBaseAnimID == ANIM_RUN_BASE) - { - // stop running if already moving and the player doesn't want to move - setBaseAnimation(ANIM_IDLE_BASE); - if (mTopAnimID == ANIM_RUN_TOP) setTopAnimation(ANIM_IDLE_TOP); - } - } - - void injectMouseMove(const MouseMotionEvent& evt) - { - // update camera goal based on mouse movement - updateCameraGoal(-0.05f * evt.xrel, -0.05f * evt.yrel, 0); - } - - void injectMouseWheel(const MouseWheelEvent& evt) - { - // update camera goal based on mouse movement - updateCameraGoal(0, 0, -0.05f * evt.y); - } - - void injectMouseDown(const MouseButtonEvent& evt) - { - if (mSwordsDrawn && (mTopAnimID == ANIM_IDLE_TOP || mTopAnimID == ANIM_RUN_TOP)) - { - // if swords are out, and character's not doing something weird, then SLICE! - if (evt.button == BUTTON_LEFT) setTopAnimation(ANIM_SLICE_VERTICAL, true); - else if (evt.button == BUTTON_RIGHT) setTopAnimation(ANIM_SLICE_HORIZONTAL, true); - mTimer = 0; - } - } - -private: - - void setupBody(SceneManager* sceneMgr) - { - // create main model - mBodyNode = sceneMgr->getRootSceneNode()->createChildSceneNode(Vector3::UNIT_Y * CHAR_HEIGHT); - mBodyEnt = sceneMgr->createEntity("SinbadBody", "Sinbad.mesh"); - mBodyNode->attachObject(mBodyEnt); - - // create swords and attach to sheath - LogManager::getSingleton().logMessage("Creating swords"); - mSword1 = sceneMgr->createEntity("SinbadSword1", "Sword.mesh"); - mSword2 = sceneMgr->createEntity("SinbadSword2", "Sword.mesh"); - mBodyEnt->attachObjectToBone("Sheath.L", mSword1); - mBodyEnt->attachObjectToBone("Sheath.R", mSword2); - - LogManager::getSingleton().logMessage("Creating the chains"); - // create a couple of ribbon trails for the swords, just for fun - NameValuePairList params; - params["numberOfChains"] = "2"; - params["maxElements"] = "80"; - mSwordTrail = (RibbonTrail*)sceneMgr->createMovableObject("RibbonTrail", ¶ms); - mSwordTrail->setMaterialName("Examples/LightRibbonTrail"); - mSwordTrail->setTrailLength(20); - mSwordTrail->setVisible(false); - sceneMgr->getRootSceneNode()->attachObject(mSwordTrail); - - - for (int i = 0; i < 2; i++) - { - mSwordTrail->setInitialColour(i, 1, 0.8, 0); - mSwordTrail->setColourChange(i, 0.75, 1.25, 1.25, 1.25); - mSwordTrail->setWidthChange(i, 1); - mSwordTrail->setInitialWidth(i, 0.5); - } - - mKeyDirection = Vector3::ZERO; - mVerticalVelocity = 0; - } - - void setupAnimations() - { - // this is very important due to the nature of the exported animations - mBodyEnt->getSkeleton()->setBlendMode(ANIMBLEND_CUMULATIVE); - - String animNames[NUM_ANIMS] = - {"IdleBase", "IdleTop", "RunBase", "RunTop", "HandsClosed", "HandsRelaxed", "DrawSwords", - "SliceVertical", "SliceHorizontal", "Dance", "JumpStart", "JumpLoop", "JumpEnd"}; - - // populate our animation list - for (int i = 0; i < NUM_ANIMS; i++) - { - mAnims[i] = mBodyEnt->getAnimationState(animNames[i]); - mAnims[i]->setLoop(true); - mFadingIn[i] = false; - mFadingOut[i] = false; - } - - // start off in the idle state (top and bottom together) - setBaseAnimation(ANIM_IDLE_BASE); - setTopAnimation(ANIM_IDLE_TOP); - - // relax the hands since we're not holding anything - mAnims[ANIM_HANDS_RELAXED]->setEnabled(true); - - mSwordsDrawn = false; - } - - void setupCamera(Camera* cam) - { - // create a pivot at roughly the character's shoulder - mCameraPivot = cam->getSceneManager()->getRootSceneNode()->createChildSceneNode(); - // this is where the camera should be soon, and it spins around the pivot - mCameraGoal = mCameraPivot->createChildSceneNode(Vector3(0, 0, 15)); - // this is where the camera actually is - mCameraNode = cam->getParentSceneNode(); - mCameraNode->setPosition(mCameraPivot->getPosition() + mCameraGoal->getPosition()); - - mCameraPivot->setFixedYawAxis(true); - mCameraGoal->setFixedYawAxis(true); - mCameraNode->setFixedYawAxis(true); - - // our model is quite small, so reduce the clipping planes - cam->setNearClipDistance(1); - cam->setFarClipDistance(100); - - mPivotPitch = 0; - } - - void updateBody(Real deltaTime) - { - mGoalDirection = Vector3::ZERO; // we will calculate this - - if (mKeyDirection != Vector3::ZERO && mBaseAnimID != ANIM_DANCE) - { - // calculate actually goal direction in world based on player's key directions - mGoalDirection += mKeyDirection.z * mCameraNode->getOrientation().zAxis(); - mGoalDirection += mKeyDirection.x * mCameraNode->getOrientation().xAxis(); - mGoalDirection.y = 0; - mGoalDirection.normalise(); - - Quaternion toGoal = mBodyNode->getOrientation().zAxis().getRotationTo(mGoalDirection); - - // calculate how much the character has to turn to face goal direction - Real yawToGoal = toGoal.getYaw().valueDegrees(); - // this is how much the character CAN turn this frame - Real yawAtSpeed = yawToGoal / Math::Abs(yawToGoal) * deltaTime * TURN_SPEED; - // reduce "turnability" if we're in midair - if (mBaseAnimID == ANIM_JUMP_LOOP) yawAtSpeed *= 0.2f; - - // turn as much as we can, but not more than we need to - if (yawToGoal < 0) yawToGoal = std::min(0, std::max(yawToGoal, yawAtSpeed)); //yawToGoal = Math::Clamp(yawToGoal, yawAtSpeed, 0); - else if (yawToGoal > 0) yawToGoal = std::max(0, std::min(yawToGoal, yawAtSpeed)); //yawToGoal = Math::Clamp(yawToGoal, 0, yawAtSpeed); - - mBodyNode->yaw(Degree(yawToGoal)); - - // move in current body direction (not the goal direction) - mBodyNode->translate(0, 0, deltaTime * RUN_SPEED * mAnims[mBaseAnimID]->getWeight(), - Node::TS_LOCAL); - } - - if (mBaseAnimID == ANIM_JUMP_LOOP) - { - // if we're jumping, add a vertical offset too, and apply gravity - mBodyNode->translate(0, mVerticalVelocity * deltaTime, 0, Node::TS_LOCAL); - mVerticalVelocity -= GRAVITY * deltaTime; - - Vector3 pos = mBodyNode->getPosition(); - if (pos.y <= CHAR_HEIGHT) - { - // if we've hit the ground, change to landing state - pos.y = CHAR_HEIGHT; - mBodyNode->setPosition(pos); - setBaseAnimation(ANIM_JUMP_END, true); - mTimer = 0; - } - } - } - - void updateAnimations(Real deltaTime) - { - Real baseAnimSpeed = 1; - Real topAnimSpeed = 1; - - mTimer += deltaTime; - - if (mTopAnimID == ANIM_DRAW_SWORDS) - { - // flip the draw swords animation if we need to put it back - topAnimSpeed = mSwordsDrawn ? -1 : 1; - - // half-way through the animation is when the hand grasps the handles... - if (mTimer >= mAnims[mTopAnimID]->getLength() / 2 && - mTimer - deltaTime < mAnims[mTopAnimID]->getLength() / 2) - { - // so transfer the swords from the sheaths to the hands - mBodyEnt->detachAllObjectsFromBone(); - mBodyEnt->attachObjectToBone(mSwordsDrawn ? "Sheath.L" : "Handle.L", mSword1); - mBodyEnt->attachObjectToBone(mSwordsDrawn ? "Sheath.R" : "Handle.R", mSword2); - // change the hand state to grab or let go - mAnims[ANIM_HANDS_CLOSED]->setEnabled(!mSwordsDrawn); - mAnims[ANIM_HANDS_RELAXED]->setEnabled(mSwordsDrawn); - - // toggle sword trails - if (mSwordsDrawn) - { - mSwordTrail->setVisible(false); - mSwordTrail->removeNode(mSword1->getParentNode()); - mSwordTrail->removeNode(mSword2->getParentNode()); - } - else - { - mSwordTrail->setVisible(true); - mSwordTrail->addNode(mSword1->getParentNode()); - mSwordTrail->addNode(mSword2->getParentNode()); - } - } - - if (mTimer >= mAnims[mTopAnimID]->getLength()) - { - // animation is finished, so return to what we were doing before - if (mBaseAnimID == ANIM_IDLE_BASE) setTopAnimation(ANIM_IDLE_TOP); - else - { - setTopAnimation(ANIM_RUN_TOP); - mAnims[ANIM_RUN_TOP]->setTimePosition(mAnims[ANIM_RUN_BASE]->getTimePosition()); - } - mSwordsDrawn = !mSwordsDrawn; - } - } - else if (mTopAnimID == ANIM_SLICE_VERTICAL || mTopAnimID == ANIM_SLICE_HORIZONTAL) - { - if (mTimer >= mAnims[mTopAnimID]->getLength()) - { - // animation is finished, so return to what we were doing before - if (mBaseAnimID == ANIM_IDLE_BASE) setTopAnimation(ANIM_IDLE_TOP); - else - { - setTopAnimation(ANIM_RUN_TOP); - mAnims[ANIM_RUN_TOP]->setTimePosition(mAnims[ANIM_RUN_BASE]->getTimePosition()); - } - } - - // don't sway hips from side to side when slicing. that's just embarrassing. - if (mBaseAnimID == ANIM_IDLE_BASE) baseAnimSpeed = 0; - } - else if (mBaseAnimID == ANIM_JUMP_START) - { - if (mTimer >= mAnims[mBaseAnimID]->getLength()) - { - // takeoff animation finished, so time to leave the ground! - setBaseAnimation(ANIM_JUMP_LOOP, true); - // apply a jump acceleration to the character - mVerticalVelocity = JUMP_ACCEL; - } - } - else if (mBaseAnimID == ANIM_JUMP_END) - { - if (mTimer >= mAnims[mBaseAnimID]->getLength()) - { - // safely landed, so go back to running or idling - if (mKeyDirection == Vector3::ZERO) - { - setBaseAnimation(ANIM_IDLE_BASE); - setTopAnimation(ANIM_IDLE_TOP); - } - else - { - setBaseAnimation(ANIM_RUN_BASE, true); - setTopAnimation(ANIM_RUN_TOP, true); - } - } - } - - // increment the current base and top animation times - if (mBaseAnimID != ANIM_NONE) mAnims[mBaseAnimID]->addTime(deltaTime * baseAnimSpeed); - if (mTopAnimID != ANIM_NONE) mAnims[mTopAnimID]->addTime(deltaTime * topAnimSpeed); - - // apply smooth transitioning between our animations - fadeAnimations(deltaTime); - } - - void fadeAnimations(Real deltaTime) - { - for (int i = 0; i < NUM_ANIMS; i++) - { - if (mFadingIn[i]) - { - // slowly fade this animation in until it has full weight - Real newWeight = mAnims[i]->getWeight() + deltaTime * ANIM_FADE_SPEED; - mAnims[i]->setWeight(Math::Clamp(newWeight, 0, 1)); - if (newWeight >= 1) mFadingIn[i] = false; - } - else if (mFadingOut[i]) - { - // slowly fade this animation out until it has no weight, and then disable it - Real newWeight = mAnims[i]->getWeight() - deltaTime * ANIM_FADE_SPEED; - mAnims[i]->setWeight(Math::Clamp(newWeight, 0, 1)); - if (newWeight <= 0) - { - mAnims[i]->setEnabled(false); - mFadingOut[i] = false; - } - } - } - } - - void updateCamera(Real deltaTime) - { - // place the camera pivot roughly at the character's shoulder - mCameraPivot->setPosition(mBodyNode->getPosition() + Vector3::UNIT_Y * CAM_HEIGHT); - // move the camera smoothly to the goal - Vector3 goalOffset = mCameraGoal->_getDerivedPosition() - mCameraNode->getPosition(); - mCameraNode->translate(goalOffset * deltaTime * 9.0f); - // always look at the pivot - mCameraNode->lookAt(mCameraPivot->_getDerivedPosition(), Node::TS_PARENT); - } - - void updateCameraGoal(Real deltaYaw, Real deltaPitch, Real deltaZoom) - { - mCameraPivot->yaw(Degree(deltaYaw), Node::TS_PARENT); - - // bound the pitch - if (!(mPivotPitch + deltaPitch > 25 && deltaPitch > 0) && - !(mPivotPitch + deltaPitch < -60 && deltaPitch < 0)) - { - mCameraPivot->pitch(Degree(deltaPitch), Node::TS_LOCAL); - mPivotPitch += deltaPitch; - } - - Real dist = mCameraGoal->_getDerivedPosition().distance(mCameraPivot->_getDerivedPosition()); - Real distChange = deltaZoom * dist; - - // bound the zoom - if (!(dist + distChange < 8 && distChange < 0) && - !(dist + distChange > 25 && distChange > 0)) - { - mCameraGoal->translate(0, 0, distChange, Node::TS_LOCAL); - } - } - - void setBaseAnimation(AnimID id, bool reset = false) - { - if (mBaseAnimID != ANIM_NONE) - { - // if we have an old animation, fade it out - mFadingIn[mBaseAnimID] = false; - mFadingOut[mBaseAnimID] = true; - } - - mBaseAnimID = id; - - if (id != ANIM_NONE) - { - // if we have a new animation, enable it and fade it in - mAnims[id]->setEnabled(true); - mAnims[id]->setWeight(0); - mFadingOut[id] = false; - mFadingIn[id] = true; - if (reset) mAnims[id]->setTimePosition(0); - } - } - - void setTopAnimation(AnimID id, bool reset = false) - { - if (mTopAnimID != ANIM_NONE) - { - // if we have an old animation, fade it out - mFadingIn[mTopAnimID] = false; - mFadingOut[mTopAnimID] = true; - } - - mTopAnimID = id; - - if (id != ANIM_NONE) - { - // if we have a new animation, enable it and fade it in - mAnims[id]->setEnabled(true); - mAnims[id]->setWeight(0); - mFadingOut[id] = false; - mFadingIn[id] = true; - if (reset) mAnims[id]->setTimePosition(0); - } - } - - SceneNode* mBodyNode; - SceneNode* mCameraPivot; - SceneNode* mCameraGoal; - SceneNode* mCameraNode; - Real mPivotPitch; - Entity* mBodyEnt; - Entity* mSword1; - Entity* mSword2; - RibbonTrail* mSwordTrail; - AnimationState* mAnims[NUM_ANIMS]; // master animation list - AnimID mBaseAnimID; // current base (full- or lower-body) animation - AnimID mTopAnimID; // current top (upper-body) animation - bool mFadingIn[NUM_ANIMS]; // which animations are fading in - bool mFadingOut[NUM_ANIMS]; // which animations are fading out - bool mSwordsDrawn; - Vector3 mKeyDirection; // player's local intended direction based on WASD keys - Vector3 mGoalDirection; // actual intended direction in world-space - Real mVerticalVelocity; // for jumping - Real mTimer; // general timer to see how long animations have been playing -}; - -#endif diff --git a/Samples/Common/include/DefaultSamplesPlugin.h b/Samples/Common/include/DefaultSamplesPlugin.h deleted file mode 100644 index 3abfaffcb57..00000000000 --- a/Samples/Common/include/DefaultSamplesPlugin.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#ifndef __DefaultSamplesPlugin_H__ -#define __DefaultSamplesPlugin_H__ - -#include "SamplePlugin.h" - -namespace OgreBites -{ - class _OgreSampleClassExport DefaultSamplesPlugin : public SamplePlugin - { - public: - DefaultSamplesPlugin(); - ~DefaultSamplesPlugin(); - }; -} - -#endif diff --git a/Samples/Common/include/ListenerFactoryLogic.h b/Samples/Common/include/ListenerFactoryLogic.h deleted file mode 100644 index ed48876e124..00000000000 --- a/Samples/Common/include/ListenerFactoryLogic.h +++ /dev/null @@ -1,50 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -conditions of the standard open source license. ------------------------------------------------------------------------------ -*/ - -#ifndef _LISTENER_FACTORY_LOGIC_H -#define _LISTENER_FACTORY_LOGIC_H - -#include "OgreCompositorInstance.h" -#include "OgreCompositorLogic.h" -#include - -//The simple types of compositor logics will all do the same thing - -//Attach a listener to the created compositor -class ListenerFactoryLogic : public Ogre::CompositorLogic -{ -public: - void compositorInstanceCreated(Ogre::CompositorInstance* newInstance) override - { - Ogre::CompositorInstance::Listener* listener = createListener(newInstance); - newInstance->addListener(listener); - mListeners[newInstance] = listener; - } - - void compositorInstanceDestroyed(Ogre::CompositorInstance* destroyedInstance) override - { - destroyedInstance->removeListener(mListeners[destroyedInstance]); - delete mListeners[destroyedInstance]; - mListeners.erase(destroyedInstance); - } - -protected: - //This is the method that implementers will need to create - virtual Ogre::CompositorInstance::Listener* createListener(Ogre::CompositorInstance* instance) = 0; -private: - typedef std::map ListenerMap; - ListenerMap mListeners; - -}; - -#endif diff --git a/Samples/Common/include/Sample.h b/Samples/Common/include/Sample.h deleted file mode 100644 index 7f2e681fce6..00000000000 --- a/Samples/Common/include/Sample.h +++ /dev/null @@ -1,351 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#ifndef __Sample_H__ -#define __Sample_H__ - -#include "OgreRoot.h" -#include "OgreOverlaySystem.h" -#include "OgreResourceManager.h" -#include "OgreComponents.h" - -#include "OgreFileSystemLayer.h" - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM -# include "OgreRTShaderSystem.h" -#endif //INCLUDE_RTSHADER_SYSTEM - -#include "OgreInput.h" -#include "OgreTrays.h" -#include "OgreCameraMan.h" -#include "OgreMaterialManager.h" - -namespace OgreBites -{ - - - /*============================================================================= - | Base class responsible for everything specific to one sample. - | Designed to be subclassed for each sample. - =============================================================================*/ - class Sample : public InputListener, public TrayListener, public Ogre::GeneralAllocatedObject - { - public: - /*============================================================================= - | Utility comparison structure for sorting samples using SampleSet. - =============================================================================*/ - struct Comparer - { - bool operator()(const Sample* a, const Sample* b) const - { - return a->getInfo().at("Title") < b->getInfo().at("Title"); - } - }; - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - Sample() : mShaderGenerator(0) -#else - Sample() -#endif - { - mRoot = Ogre::Root::getSingletonPtr(); - mWindow = 0; - mSceneMgr = 0; - mDone = true; - mResourcesLoaded = false; - mContentSetup = false; - - mCamera = 0; - mCameraNode = 0; - mViewport = 0; - - mFSLayer = 0; - mOverlaySystem = 0; - - // so we don't have to worry about checking if these keys exist later - mInfo["Title"] = "Untitled"; - mInfo["Description"] = ""; - mInfo["Category"] = "Unsorted"; - mInfo["Thumbnail"] = "thumb_error.png"; - mInfo["Help"] = ""; - } - - virtual ~Sample() {} - - /*----------------------------------------------------------------------------- - | Retrieves custom sample info. - -----------------------------------------------------------------------------*/ - const Ogre::NameValuePairList& getInfo() const { return mInfo; } - Ogre::NameValuePairList& getInfo() { return mInfo; } - - /*----------------------------------------------------------------------------- - | Tests to see if target machine meets any special requirements of - | this sample. Signal a failure by throwing an exception. - -----------------------------------------------------------------------------*/ - virtual void testCapabilities(const Ogre::RenderSystemCapabilities* caps) {} - - void requireMaterial(const Ogre::String& name) - { - Ogre::StringStream err; - err << "Material: " << name << " "; - auto mat = Ogre::MaterialManager::getSingleton().getByName(name); - if(!mat) - { - err << "not found"; - OGRE_EXCEPT(Ogre::Exception::ERR_NOT_IMPLEMENTED, err.str()); - } - mat->load(); - if (mat->getSupportedTechniques().empty()) - { - err << mat->getUnsupportedTechniquesExplanation(); - OGRE_EXCEPT(Ogre::Exception::ERR_NOT_IMPLEMENTED, err.str()); - } - } - - /*----------------------------------------------------------------------------- - | If this sample requires specific plugins to run, this method will be - | used to return their names. - -----------------------------------------------------------------------------*/ - virtual Ogre::StringVector getRequiredPlugins() { return Ogre::StringVector(); } - - Ogre::SceneManager* getSceneManager() { return mSceneMgr; } - bool isDone() { return mDone; } - - /** Adds a screenshot frame to the list - this should - * be done during setup of the test. */ - void addScreenshotFrame(int frame) - { - mScreenshotFrames.insert(frame); - } - - /** Returns whether or not a screenshot should be taken at the given frame */ - virtual bool isScreenshotFrame(int frame) - { - if (mScreenshotFrames.empty()) - { - mDone = true; - } - else if (frame == *(mScreenshotFrames.begin())) - { - mScreenshotFrames.erase(mScreenshotFrames.begin()); - if (mScreenshotFrames.empty()) - mDone = true; - return true; - } - return false; - } - - // enable trays GUI for this sample - void _setupTrays(Ogre::RenderWindow* window) - { - mTrayMgr.reset(new TrayManager("SampleControls", window, this)); // create a tray interface - // show stats and logo and hide the cursor - mTrayMgr->showFrameStats(TL_BOTTOMLEFT); - mTrayMgr->showLogo(TL_BOTTOMRIGHT); - mTrayMgr->hideCursor(); - } - - /*----------------------------------------------------------------------------- - | Sets up a sample. Used by the SampleContext class. Do not call directly. - -----------------------------------------------------------------------------*/ - virtual void _setup(Ogre::RenderWindow* window, Ogre::FileSystemLayer* fsLayer, Ogre::OverlaySystem* overlaySys) - { - mOverlaySystem = overlaySys; - mWindow = window; - - mFSLayer = fsLayer; - - locateResources(); - createSceneManager(); - setupView(); - - mCameraMan.reset(new CameraMan(mCameraNode)); // create a default camera controller - - loadResources(); - mResourcesLoaded = true; - setupContent(); - mContentSetup = true; - - mDone = false; - } - - /*----------------------------------------------------------------------------- - | Shuts down a sample. Used by the SampleContext class. Do not call directly. - -----------------------------------------------------------------------------*/ - virtual void _shutdown() - { - Ogre::ControllerManager::getSingleton().clearControllers(); - - if (mContentSetup) - cleanupContent(); - if (mSceneMgr) - mSceneMgr->clearScene(); - mContentSetup = false; - - if (mResourcesLoaded) - unloadResources(); - mResourcesLoaded = false; - if (mSceneMgr) - { -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - mShaderGenerator->removeSceneManager(mSceneMgr); -#endif - mSceneMgr->removeRenderQueueListener(mOverlaySystem); - mRoot->destroySceneManager(mSceneMgr); - } - mSceneMgr = 0; - - mDone = true; - } - - /*----------------------------------------------------------------------------- - | Actions to perform when the context stops sending frame listener events - | and input device events to this sample. - -----------------------------------------------------------------------------*/ - virtual void paused() {} - - /*----------------------------------------------------------------------------- - | Actions to perform when the context continues sending frame listener - | events and input device events to this sample. - -----------------------------------------------------------------------------*/ - virtual void unpaused() {} - - /*----------------------------------------------------------------------------- - | Saves the sample state. Optional. Used during reconfiguration. - -----------------------------------------------------------------------------*/ - virtual void saveState(Ogre::NameValuePairList& state) {} - - /*----------------------------------------------------------------------------- - | Restores the sample state. Optional. Used during reconfiguration. - -----------------------------------------------------------------------------*/ - virtual void restoreState(Ogre::NameValuePairList& state) {} - - // callback interface copied from various listeners to be used by SampleContext - - virtual bool frameStarted(const Ogre::FrameEvent& evt) { return true; } - virtual bool frameRenderingQueued(const Ogre::FrameEvent& evt) { return true; } - virtual bool frameEnded(const Ogre::FrameEvent& evt) { return true; } - virtual void windowMoved(Ogre::RenderWindow* rw) {} - virtual void windowResized(Ogre::RenderWindow* rw) {} - virtual bool windowClosing(Ogre::RenderWindow* rw) { return true; } - virtual void windowClosed(Ogre::RenderWindow* rw) {} - virtual void windowFocusChange(Ogre::RenderWindow* rw) {} - protected: - - /*----------------------------------------------------------------------------- - | Finds sample-specific resources. No such effort is made for most samples, - | but this is useful for special samples with large, exclusive resources. - -----------------------------------------------------------------------------*/ - virtual void locateResources() {} - - /*----------------------------------------------------------------------------- - | Loads sample-specific resources. No such effort is made for most samples, - | but this is useful for special samples with large, exclusive resources. - -----------------------------------------------------------------------------*/ - virtual void loadResources() {} - - /*----------------------------------------------------------------------------- - | Creates a scene manager for the sample. A generic one is the default, - | but many samples require a special kind of scene manager. - -----------------------------------------------------------------------------*/ - virtual void createSceneManager() - { - mSceneMgr = Ogre::Root::getSingleton().createSceneManager(); -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - mShaderGenerator->addSceneManager(mSceneMgr); - auto mainRenderState = mShaderGenerator->getRenderState(Ogre::MSN_SHADERGEN); - // reset global light state - mainRenderState->setLightCount(0); - mainRenderState->setLightCountAutoUpdate(true); - mainRenderState->resetToBuiltinSubRenderStates(); -#endif - if(mOverlaySystem) - mSceneMgr->addRenderQueueListener(mOverlaySystem); - } - - /*----------------------------------------------------------------------------- - | Sets up viewport layout and camera. - -----------------------------------------------------------------------------*/ - virtual void setupView() {} - - /*----------------------------------------------------------------------------- - | Sets up the scene (and anything else you want for the sample). - -----------------------------------------------------------------------------*/ - virtual void setupContent() {} - - /*----------------------------------------------------------------------------- - | Cleans up the scene (and anything else you used). - -----------------------------------------------------------------------------*/ - virtual void cleanupContent() {} - - /*----------------------------------------------------------------------------- - | Unloads sample-specific resources. My method here is simple and good - | enough for most small samples, but your needs may vary. - -----------------------------------------------------------------------------*/ - virtual void unloadResources() - { - for (auto& it : Ogre::ResourceGroupManager::getSingleton().getResourceManagers()) - { - it.second->unloadUnreferencedResources(); - } - } - - Ogre::Root* mRoot; // OGRE root object - Ogre::OverlaySystem* mOverlaySystem; // OverlaySystem - Ogre::RenderWindow* mWindow; // context render window - Ogre::FileSystemLayer* mFSLayer; // file system abstraction layer - Ogre::SceneManager* mSceneMgr; // scene manager for this sample - Ogre::NameValuePairList mInfo; // custom sample info - - Ogre::Viewport* mViewport; // main viewport - Ogre::Camera* mCamera; // main camera - Ogre::SceneNode* mCameraNode; // camera node - - // SdkSample fields - std::unique_ptr mTrayMgr; // tray interface manager - std::unique_ptr mCameraMan; // basic camera controller - - bool mDone; // flag to mark the end of the sample - bool mResourcesLoaded; // whether or not resources have been loaded - bool mContentSetup; // whether or not scene was created -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - Ogre::RTShader::ShaderGenerator* mShaderGenerator; // The Shader generator instance. - public: - void setShaderGenerator(Ogre::RTShader::ShaderGenerator* shaderGenerator) - { - mShaderGenerator = shaderGenerator; - } -#endif - private: - // VisualTest fields - std::set mScreenshotFrames; - }; - - typedef std::set SampleSet; -} - -#endif diff --git a/Samples/Common/include/SampleContext.h b/Samples/Common/include/SampleContext.h deleted file mode 100644 index 01058a55aaf..00000000000 --- a/Samples/Common/include/SampleContext.h +++ /dev/null @@ -1,374 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#ifndef __SampleContext_H__ -#define __SampleContext_H__ - -#include "OgreApplicationContext.h" - -#include "Sample.h" -#include "OgreRenderWindow.h" - -namespace OgreBites -{ - /*============================================================================= - | Base class responsible for setting up a common context for samples. - | May be subclassed for specific sample types (not specific samples). - | Allows one sample to run at a time, while maintaining a sample queue. - =============================================================================*/ - class SampleContext : public ApplicationContext, public InputListener - { - public: - Ogre::RenderWindow* mWindow; - - SampleContext(const Ogre::String& appName = OGRE_VERSION_NAME) - : ApplicationContext(appName), mWindow(NULL) - { - mCurrentSample = 0; - mSamplePaused = false; - mLastRun = false; - mLastSample = 0; - } - - virtual Sample* getCurrentSample() - { - return mCurrentSample; - } - - /*----------------------------------------------------------------------------- - | Quits the current sample and starts a new one. - -----------------------------------------------------------------------------*/ - virtual void runSample(Sample* s) - { - Ogre::Profiler* prof = Ogre::Profiler::getSingletonPtr(); - if (prof) - prof->setEnabled(false); - - if (mCurrentSample) - { - mCurrentSample->_shutdown(); // quit current sample - mSamplePaused = false; // don't pause the next sample - } - - mWindow->removeAllViewports(); // wipe viewports - mWindow->resetStatistics(); - - if (s) - { - // retrieve sample's required plugins and currently installed plugins - Ogre::Root::PluginInstanceList ip = mRoot->getInstalledPlugins(); - Ogre::StringVector rp = s->getRequiredPlugins(); - - for (Ogre::StringVector::iterator j = rp.begin(); j != rp.end(); j++) - { - bool found = false; - // try to find the required plugin in the current installed plugins - for (Ogre::Root::PluginInstanceList::iterator k = ip.begin(); k != ip.end(); k++) - { - if ((*k)->getName() == *j) - { - found = true; - break; - } - } - if (!found) // throw an exception if a plugin is not found - { - OGRE_EXCEPT(Ogre::Exception::ERR_NOT_IMPLEMENTED, "Sample requires plugin: " + *j); - } - } - - // test system capabilities against sample requirements - s->testCapabilities(mRoot->getRenderSystem()->getCapabilities()); -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - s->setShaderGenerator(mShaderGenerator); -#endif - s->_setup(mWindow, mFSLayer, mOverlaySystem); // start new sample - } - - if (prof) - prof->setEnabled(true); - - mCurrentSample = s; - } - - /*----------------------------------------------------------------------------- - | This function encapsulates the entire lifetime of the context. - -----------------------------------------------------------------------------*/ - virtual void go(Sample* initialSample = 0) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - mLastRun = true; // assume this is our last run - - initApp(); - loadStartUpSample(); -#else - while (!mLastRun) - { - mLastRun = true; // assume this is our last run - - initApp(); - -#if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID - // restore the last sample if there was one or, if not, start initial sample - if (!mFirstRun) recoverLastSample(); - else if (initialSample) runSample(initialSample); -#endif - - loadStartUpSample(); - - if (mRoot->getRenderSystem() != NULL) - { - mRoot->startRendering(); // start the render loop - } - - closeApp(); - - mFirstRun = false; - } -#endif - } - - virtual void loadStartUpSample() {} - - bool isCurrentSamplePaused() - { - return !mCurrentSample || mSamplePaused; - } - - virtual void pauseCurrentSample() - { - if (!isCurrentSamplePaused()) - { - mSamplePaused = true; - mCurrentSample->paused(); - } - } - - virtual void unpauseCurrentSample() - { - if (mCurrentSample && mSamplePaused) - { - mSamplePaused = false; - mCurrentSample->unpaused(); - } - } - - /*----------------------------------------------------------------------------- - | Processes frame started events. - -----------------------------------------------------------------------------*/ - bool frameStarted(const Ogre::FrameEvent& evt) override - { - pollEvents(); - - // manually call sample callback to ensure correct order - return !isCurrentSamplePaused() ? mCurrentSample->frameStarted(evt) : true; - } - - /*----------------------------------------------------------------------------- - | Processes rendering queued events. - -----------------------------------------------------------------------------*/ - bool frameRenderingQueued(const Ogre::FrameEvent& evt) override - { - // manually call sample callback to ensure correct order - return !isCurrentSamplePaused() ? mCurrentSample->frameRenderingQueued(evt) : true; - } - - /*----------------------------------------------------------------------------- - | Processes frame ended events. - -----------------------------------------------------------------------------*/ - bool frameEnded(const Ogre::FrameEvent& evt) override - { - // manually call sample callback to ensure correct order - if (mCurrentSample && !mSamplePaused && !mCurrentSample->frameEnded(evt)) return false; - // quit if window was closed - if (mWindow->isClosed()) return false; - // go into idle mode if current sample has ended - if (mCurrentSample && mCurrentSample->isDone()) runSample(0); - - return true; - } - - /*----------------------------------------------------------------------------- - | Processes window size change event. Adjusts mouse's region to match that - | of the window. You could also override this method to prevent resizing. - -----------------------------------------------------------------------------*/ - void windowResized(Ogre::RenderWindow* rw) override - { - // manually call sample callback to ensure correct order - if (!isCurrentSamplePaused()) mCurrentSample->windowResized(rw); - } - - // window event callbacks which manually call their respective sample callbacks to ensure correct order - - void windowMoved(Ogre::RenderWindow* rw) override - { - if (!isCurrentSamplePaused()) mCurrentSample->windowMoved(rw); - } - - bool windowClosing(Ogre::RenderWindow* rw) override - { - if (!isCurrentSamplePaused()) return mCurrentSample->windowClosing(rw); - return true; - } - - void windowClosed(Ogre::RenderWindow* rw) override - { - if (!isCurrentSamplePaused()) mCurrentSample->windowClosed(rw); - } - - void windowFocusChange(Ogre::RenderWindow* rw) override - { - if (!isCurrentSamplePaused()) mCurrentSample->windowFocusChange(rw); - } - - // keyboard and mouse callbacks which manually call their respective sample callbacks to ensure correct order - - bool keyPressed(const KeyboardEvent& evt) override - { - // Ignore repeated signals from key being held down. - if (evt.repeat) return true; - - if (!isCurrentSamplePaused()) return mCurrentSample->keyPressed(evt); - return true; - } - - bool keyReleased(const KeyboardEvent& evt) override - { - if (!isCurrentSamplePaused()) return mCurrentSample->keyReleased(evt); - return true; - } - - bool touchMoved(const TouchFingerEvent& evt) override - { - if (!isCurrentSamplePaused()) - return mCurrentSample->touchMoved(evt); - return true; - } - - bool mouseMoved(const MouseMotionEvent& evt) override - { - if (!isCurrentSamplePaused()) - return mCurrentSample->mouseMoved(evt); - return true; - } - - bool touchPressed(const TouchFingerEvent& evt) override - { - if (!isCurrentSamplePaused()) - return mCurrentSample->touchPressed(evt); - return true; - } - - bool mousePressed(const MouseButtonEvent& evt) override - { - if (!isCurrentSamplePaused()) - return mCurrentSample->mousePressed(evt); - return true; - } - - bool touchReleased(const TouchFingerEvent& evt) override - { - if (!isCurrentSamplePaused()) - return mCurrentSample->touchReleased(evt); - return true; - } - - bool mouseReleased(const MouseButtonEvent& evt) override - { - if (!isCurrentSamplePaused()) - return mCurrentSample->mouseReleased(evt); - return true; - } - - bool mouseWheelRolled(const MouseWheelEvent& evt) override - { - if (!isCurrentSamplePaused()) - return mCurrentSample->mouseWheelRolled(evt); - return true; - } - - bool textInput (const TextInputEvent& evt) override - { - if (!isCurrentSamplePaused ()) - return mCurrentSample->textInput (evt); - return true; - } - - bool isFirstRun() { return mFirstRun; } - void setFirstRun(bool flag) { mFirstRun = flag; } - bool isLastRun() { return mLastRun; } - void setLastRun(bool flag) { mLastRun = flag; } - protected: - /*----------------------------------------------------------------------------- - | Reconfigures the context. Attempts to preserve the current sample state. - -----------------------------------------------------------------------------*/ - void reconfigure(const Ogre::String& renderer, Ogre::NameValuePairList& options) override - { - // save current sample state - mLastSample = mCurrentSample; - if (mCurrentSample) mCurrentSample->saveState(mLastSampleState); - - mLastRun = false; // we want to go again with the new settings - ApplicationContext::reconfigure(renderer, options); - } - - /*----------------------------------------------------------------------------- - | Recovers the last sample after a reset. You can override in the case that - | the last sample is destroyed in the process of resetting, and you have to - | recover it through another means. - -----------------------------------------------------------------------------*/ - virtual void recoverLastSample() - { - runSample(mLastSample); - mLastSample->restoreState(mLastSampleState); - mLastSample = 0; - mLastSampleState.clear(); - } - - /*----------------------------------------------------------------------------- - | Cleans up and shuts down the context. - -----------------------------------------------------------------------------*/ - void shutdown() override - { - if (mCurrentSample) - { - mCurrentSample->_shutdown(); - mCurrentSample = 0; - } - - ApplicationContext::shutdown(); - } - - Sample* mCurrentSample; // The active sample (0 if none is active) - bool mSamplePaused; // whether current sample is paused - bool mLastRun; // whether or not this is the final run - Sample* mLastSample; // last sample run before reconfiguration - Ogre::NameValuePairList mLastSampleState; // state of last sample - }; -} - -#endif diff --git a/Samples/Common/include/SamplePlugin.h b/Samples/Common/include/SamplePlugin.h deleted file mode 100644 index 69b916b0e6b..00000000000 --- a/Samples/Common/include/SamplePlugin.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#ifndef __SamplePlugin_H__ -#define __SamplePlugin_H__ - -#include "OgrePlugin.h" -#include "Sample.h" - -// Export macro to export the sample's main dll functions. -#if defined( OGRE_STATIC_LIB ) -# define _OgreSampleExport -#else -# if (OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT) && !defined(__MINGW32__) -# define _OgreSampleExport __declspec(dllexport) -# elif defined ( OGRE_GCC_VISIBILITY ) -# define _OgreSampleExport __attribute__ ((visibility("default"))) -# else -# define _OgreSampleExport -# endif -#endif - -#define _OgreSampleClassExport - -namespace OgreBites -{ - /*============================================================================= - | Utility class used to hold a set of samples in an OGRE plugin. - =============================================================================*/ - class _OgreSampleExport SamplePlugin : public Ogre::Plugin - { - public: - - SamplePlugin(const Ogre::String& name) - : mName(name) - { - } - - const Ogre::String& getName() const override - { - return mName; - } - - void install() override {} - void uninstall() override {} - void initialise() override {} - void shutdown() override {} - - /*----------------------------------------------------------------------------- - | Adds a sample to the queue. - -----------------------------------------------------------------------------*/ - void addSample(Sample* s) - { - mSamples.insert(s); - } - - /*----------------------------------------------------------------------------- - | Retrieves the queue of samples. - -----------------------------------------------------------------------------*/ - const SampleSet& getSamples() - { - return mSamples; - } - - protected: - - Ogre::String mName; - SampleSet mSamples; - }; -} - -#endif diff --git a/Samples/Common/include/SdkSample.h b/Samples/Common/include/SdkSample.h deleted file mode 100644 index 91cdbb2e47f..00000000000 --- a/Samples/Common/include/SdkSample.h +++ /dev/null @@ -1,291 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#ifndef __SdkSample_H__ -#define __SdkSample_H__ - -#include "Sample.h" -#include "Ogre.h" -#include "OgreAdvancedRenderControls.h" - -namespace OgreBites -{ - /*============================================================================= - // Base SDK sample class. Includes default player camera and SDK trays. - =============================================================================*/ - class SdkSample : public Sample - { - public: - SdkSample() - { - mCameraMan = 0; - mCursorWasVisible = false; - mDragLook = false; - } - - /*----------------------------------------------------------------------------- - | Manually update the cursor position after being unpaused. - -----------------------------------------------------------------------------*/ - void unpaused() override - { - mTrayMgr->refreshCursor(); - } - - /*----------------------------------------------------------------------------- - | Automatically saves position and orientation for free-look cameras. - -----------------------------------------------------------------------------*/ - void saveState(Ogre::NameValuePairList& state) override - { - if (mCameraMan->getStyle() == CS_FREELOOK) - { - state["CameraPosition"] = Ogre::StringConverter::toString(mCameraNode->getPosition()); - state["CameraOrientation"] = Ogre::StringConverter::toString(mCameraNode->getOrientation()); - } - } - - /*----------------------------------------------------------------------------- - | Automatically restores position and orientation for free-look cameras. - -----------------------------------------------------------------------------*/ - void restoreState(Ogre::NameValuePairList& state) override - { - if (state.find("CameraPosition") != state.end() && state.find("CameraOrientation") != state.end()) - { - mCameraMan->setStyle(CS_FREELOOK); - mCameraNode->setPosition(Ogre::StringConverter::parseVector3(state["CameraPosition"])); - mCameraNode->setOrientation(Ogre::StringConverter::parseQuaternion(state["CameraOrientation"])); - } - } - - bool frameRenderingQueued(const Ogre::FrameEvent& evt) override - { - if(!mTrayMgr) return true; - - mTrayMgr->frameRendered(evt); - mControls->frameRendered(evt); - - if (!mTrayMgr->isDialogVisible()) - { - mCameraMan->frameRendered(evt); // if dialog isn't up, then update the camera - } - - return true; - } - - bool keyPressed(const KeyboardEvent& evt) override - { - int key = evt.keysym.sym; - - if (key == 'h' || key == SDLK_F1) // toggle visibility of help dialog - { - if (!mTrayMgr->isDialogVisible() && mInfo["Help"] != "") mTrayMgr->showOkDialog("Help", mInfo["Help"]); - else mTrayMgr->closeDialog(); - } - - if (mTrayMgr->isDialogVisible()) return true; // don't process any more keys if dialog is up - - mControls->keyPressed(evt); - mCameraMan->keyPressed(evt); - return true; - } - - bool keyReleased(const KeyboardEvent& evt) override - { - mCameraMan->keyReleased(evt); - - return true; - } - - /* IMPORTANT: When overriding these following handlers, remember to allow the tray manager - to filter out any interface-related mouse events before processing them in your scene. - If the tray manager handler returns true, the event was meant for the trays, not you. */ - bool mouseMoved(const MouseMotionEvent& evt) override - { - if (mTrayMgr->mouseMoved(evt)) return true; - - mCameraMan->mouseMoved(evt); - return true; - } - - // convert and redirect - bool touchMoved(const TouchFingerEvent& evt) override { - MouseMotionEvent e; - e.xrel = evt.dx * mWindow->getWidth(); - e.yrel = evt.dy * mWindow->getHeight(); - return mouseMoved(e); - } - - bool mousePressed(const MouseButtonEvent& evt) override - { - if (mTrayMgr->mousePressed(evt)) return true; - - if (mDragLook && evt.button == BUTTON_LEFT) - { - mCameraMan->setStyle(CS_FREELOOK); - mTrayMgr->hideCursor(); - } - - mCameraMan->mousePressed(evt); - return true; - } - - // convert and redirect - bool touchPressed(const TouchFingerEvent& evt) override { - MouseButtonEvent e; - e.button = BUTTON_LEFT; - return mousePressed(e); - } - - bool mouseReleased(const MouseButtonEvent& evt) override - { - if (mTrayMgr->mouseReleased(evt)) return true; - - if (mDragLook && evt.button == BUTTON_LEFT) - { - mCameraMan->setStyle(CS_MANUAL); - mTrayMgr->showCursor(); - } - - mCameraMan->mouseReleased(evt); - return true; - } - - // convert and redirect - bool touchReleased(const TouchFingerEvent& evt) override { - MouseButtonEvent e; - e.button = BUTTON_LEFT; - return mouseReleased(e); - } - - bool mouseWheelRolled(const MouseWheelEvent& evt) override { - if(mTrayMgr->mouseWheelRolled(evt)) - return true; - mCameraMan->mouseWheelRolled(evt); - return true; - } - - /*----------------------------------------------------------------------------- - | Extended to setup a default tray interface and camera controller. - -----------------------------------------------------------------------------*/ - void _setup(Ogre::RenderWindow* window, Ogre::FileSystemLayer* fsLayer, Ogre::OverlaySystem* overlaySys) override - { - Sample::_setup(window, fsLayer, overlaySys); - - if(mTrayMgr) - mControls.reset(new AdvancedRenderControls(mTrayMgr.get(), mCamera)); - } - - void _shutdown() override - { - Sample::_shutdown(); - - mControls.reset(); - mCameraMan.reset(); - mTrayMgr.reset(); - - // restore settings we may have changed, so as not to affect other samples - Ogre::MaterialManager::getSingleton().setDefaultTextureFiltering(Ogre::TFO_BILINEAR); - Ogre::MaterialManager::getSingleton().setDefaultAnisotropy(1); - } - - protected: - - void setupView() override - { - // setup default viewport layout and camera - mCamera = mSceneMgr->createCamera("MainCamera"); - mCameraNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mCameraNode->attachObject(mCamera); - mCameraNode->setFixedYawAxis(true); - mViewport = mWindow->addViewport(mCamera); - mCamera->setAspectRatio((Ogre::Real)mViewport->getActualWidth() / (Ogre::Real)mViewport->getActualHeight()); - mCamera->setAutoAspectRatio(true); - mCamera->setNearClipDistance(5); - } - - virtual void setDragLook(bool enabled) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - return; -#endif - if (enabled) - { - mCameraMan->setStyle(CS_MANUAL); - mTrayMgr->showCursor(); - mDragLook = true; - } - else - { - mCameraMan->setStyle(CS_FREELOOK); - mTrayMgr->hideCursor(); - mDragLook = false; - } - } - - void addTextureDebugOverlay(TrayLocation loc, const Ogre::TexturePtr& tex, size_t i) - { - using namespace Ogre; - // Create material - String matName = "Ogre/DebugTexture" + StringConverter::toString(i); - MaterialPtr debugMat = MaterialManager::getSingleton().getByName( - matName, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - if (!debugMat) - { - debugMat = MaterialManager::getSingleton().create(matName, - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - } - Pass* p = debugMat->getTechnique(0)->getPass(0); - p->removeAllTextureUnitStates(); - p->setLightingEnabled(false); - TextureUnitState *t = p->createTextureUnitState(tex->getName()); - t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); - - // create template - if (!OverlayManager::getSingleton().hasOverlayElement("Ogre/DebugTexOverlay", true)) - { - OverlayElement* e = OverlayManager::getSingleton().createOverlayElement("Panel", "Ogre/DebugTexOverlay", true); - e->setMetricsMode(GMM_PIXELS); - e->setWidth(128); - e->setHeight(128); - } - - // add widget - String widgetName = "DebugTex"+ StringConverter::toString(i); - Widget* w = mTrayMgr->getWidget(widgetName); - if (!w) - { - w = mTrayMgr->createDecorWidget(loc, widgetName, "Ogre/DebugTexOverlay"); - } - w->getOverlayElement()->setMaterial(debugMat); - } - - std::unique_ptr mControls; // sample details panel - bool mCursorWasVisible; // was cursor visible before dialog appeared - bool mDragLook; // click and drag to free-look - }; -} - -#endif diff --git a/Samples/Common/misc.winrt/Logo.png b/Samples/Common/misc.winrt/Logo.png deleted file mode 100644 index 4b74ea6357b..00000000000 Binary files a/Samples/Common/misc.winrt/Logo.png and /dev/null differ diff --git a/Samples/Common/misc.winrt/SmallLogo.png b/Samples/Common/misc.winrt/SmallLogo.png deleted file mode 100644 index 314d8617666..00000000000 Binary files a/Samples/Common/misc.winrt/SmallLogo.png and /dev/null differ diff --git a/Samples/Common/misc.winrt/SplashScreen.png b/Samples/Common/misc.winrt/SplashScreen.png deleted file mode 100644 index 7d5e190d7c6..00000000000 Binary files a/Samples/Common/misc.winrt/SplashScreen.png and /dev/null differ diff --git a/Samples/Common/misc.winrt/StoreLogo.png b/Samples/Common/misc.winrt/StoreLogo.png deleted file mode 100644 index a400c597c9c..00000000000 Binary files a/Samples/Common/misc.winrt/StoreLogo.png and /dev/null differ diff --git a/Samples/Common/misc/.keepme b/Samples/Common/misc/.keepme deleted file mode 100644 index e0808fa1636..00000000000 --- a/Samples/Common/misc/.keepme +++ /dev/null @@ -1 +0,0 @@ -keep me diff --git a/Samples/Common/misc/Default-568h@2x.png b/Samples/Common/misc/Default-568h@2x.png deleted file mode 100644 index e572c909e8e..00000000000 Binary files a/Samples/Common/misc/Default-568h@2x.png and /dev/null differ diff --git a/Samples/Common/misc/Default-Landscape@2x~ipad.png b/Samples/Common/misc/Default-Landscape@2x~ipad.png deleted file mode 100644 index 2c177d212d4..00000000000 Binary files a/Samples/Common/misc/Default-Landscape@2x~ipad.png and /dev/null differ diff --git a/Samples/Common/misc/Default-Landscape~ipad.png b/Samples/Common/misc/Default-Landscape~ipad.png deleted file mode 100644 index cc2539362ed..00000000000 Binary files a/Samples/Common/misc/Default-Landscape~ipad.png and /dev/null differ diff --git a/Samples/Common/misc/Default-Portrait@2x~ipad.png b/Samples/Common/misc/Default-Portrait@2x~ipad.png deleted file mode 100644 index fe023b14cb4..00000000000 Binary files a/Samples/Common/misc/Default-Portrait@2x~ipad.png and /dev/null differ diff --git a/Samples/Common/misc/Default-Portrait~ipad.png b/Samples/Common/misc/Default-Portrait~ipad.png deleted file mode 100644 index 37c206fe896..00000000000 Binary files a/Samples/Common/misc/Default-Portrait~ipad.png and /dev/null differ diff --git a/Samples/Common/misc/Default.png b/Samples/Common/misc/Default.png deleted file mode 100644 index 5913e244514..00000000000 Binary files a/Samples/Common/misc/Default.png and /dev/null differ diff --git a/Samples/Common/misc/Default@2x.png b/Samples/Common/misc/Default@2x.png deleted file mode 100644 index 59dd24e009c..00000000000 Binary files a/Samples/Common/misc/Default@2x.png and /dev/null differ diff --git a/Samples/Common/misc/Icon-72.png b/Samples/Common/misc/Icon-72.png deleted file mode 100644 index 98f16c65c5c..00000000000 Binary files a/Samples/Common/misc/Icon-72.png and /dev/null differ diff --git a/Samples/Common/misc/Icon.png b/Samples/Common/misc/Icon.png deleted file mode 100644 index 94395e95dcf..00000000000 Binary files a/Samples/Common/misc/Icon.png and /dev/null differ diff --git a/Samples/Common/misc/Icon@2x-72.png b/Samples/Common/misc/Icon@2x-72.png deleted file mode 100644 index ba9a756af80..00000000000 Binary files a/Samples/Common/misc/Icon@2x-72.png and /dev/null differ diff --git a/Samples/Common/misc/Icon@2x.png b/Samples/Common/misc/Icon@2x.png deleted file mode 100644 index c84a44e9c53..00000000000 Binary files a/Samples/Common/misc/Icon@2x.png and /dev/null differ diff --git a/Samples/Common/misc/Info.plist b/Samples/Common/misc/Info.plist deleted file mode 100644 index c09c6d35759..00000000000 --- a/Samples/Common/misc/Info.plist +++ /dev/null @@ -1,48 +0,0 @@ - - - - - CFBundleDevelopmentRegion - English - CFBundleExecutable - SampleBrowser - CFBundleGetInfoString - ${MACOSX_BUNDLE_INFO_STRING} - CFBundleIconFile - ${MACOSX_BUNDLE_ICON_FILE} - CFBundleIdentifier - ${MACOSX_BUNDLE_GUI_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleLongVersionString - 1.0 - CFBundleName - ${MACOSX_BUNDLE_BUNDLE_NAME} - CFBundlePackageType - APPL - CFBundleShortVersionString - 1.0 - CFBundleSignature - ???? - CFBundleVersion - 1.0 - CSResourcesFileMapped - - LSRequiresCarbon - - NSHumanReadableCopyright - ${MACOSX_BUNDLE_COPYRIGHT} - UIStatusBarHidden - - UIViewControllerBasedStatusBarAppearance - - NSPrincipalClass - NSApplication - UISupportedInterfaceOrientations - - UIInterfaceOrientationPortrait - UIInterfaceOrientationLandscapeRight - UIInterfaceOrientationLandscapeLeft - - - diff --git a/Samples/Common/misc/SampleBrowser_OSX.icns b/Samples/Common/misc/SampleBrowser_OSX.icns deleted file mode 100644 index 35b7cd46b13..00000000000 Binary files a/Samples/Common/misc/SampleBrowser_OSX.icns and /dev/null differ diff --git a/Samples/Common/src/DefaultSamplesPlugin.cpp b/Samples/Common/src/DefaultSamplesPlugin.cpp deleted file mode 100644 index 5b2288f153b..00000000000 --- a/Samples/Common/src/DefaultSamplesPlugin.cpp +++ /dev/null @@ -1,202 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ -#include "DefaultSamplesPlugin.h" - -#include "OgreComponents.h" - -#include "AtomicCounters.h" -#include "BezierPatch.h" -#include "BSP.h" -#ifdef OGRE_BUILD_COMPONENT_BULLET -#include "Bullet.h" -#endif -#include "CameraTrack.h" -#include "CelShading.h" -#include "CharacterSample.h" -#include "Compositor.h" -#include "Compute.h" -#include "CubeMapping.h" -#include "CSMShadows.h" -#include "DeferredShadingDemo.h" -#include "Dot3Bump.h" -#include "DualQuaternion.h" -#include "DynTex.h" -#ifdef OGRE_BUILD_COMPONENT_TERRAIN -# include "EndlessWorld.h" -# include "Terrain.h" -#endif -#include "FacialAnimation.h" -#include "Fresnel.h" -#include "Grass.h" -#ifdef HAVE_IMGUI -#include "ImGuiDemo.h" -#endif -#include "Isosurf.h" -#include "Lighting.h" -#include "LightShafts.h" -#ifdef OGRE_BUILD_COMPONENT_MESHLODGENERATOR -# include "MeshLod.h" -#endif -#include "NewInstancing.h" -#include "OceanDemo.h" -#include "ParticleFX.h" -#include "ParticleGS.h" -#ifdef HAVE_PCZ_PLUGIN - #include "PCZTestApp.h" -#endif -#include "PBR.h" -#include "RectLight.h" -#include "PNTrianglesTessellation.h" -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM -# include "ShaderSystem.h" -# include "ShaderSystemTexturedFog.h" -# include "ShaderSystemMultiLight.h" -#endif -#include "Shadows.h" -#include "SkeletalAnimation.h" -#include "SkyBox.h" -#include "SkyDome.h" -#include "SkyPlane.h" -#include "Smoke.h" -#include "SphereMapping.h" -#include "SSAO.h" -#include "Tessellation.h" -#include "TextureArray.h" -#include "TextureFX.h" -#include "Transparency.h" -#ifdef OGRE_BUILD_COMPONENT_VOLUME -# include "VolumeCSG.h" -# include "VolumeTerrain.h" -#endif -#include "VolumeTex.h" -#include "Water.h" - -using namespace Ogre; -using namespace OgreBites; - -DefaultSamplesPlugin::DefaultSamplesPlugin() : SamplePlugin("DefaultSamplesPlugin") -{ - addSample(new Sample_AtomicCounters); - addSample(new Sample_BezierPatch); -#ifdef OGRE_BUILD_COMPONENT_BULLET - addSample(new Sample_Bullet); -#endif - addSample(new Sample_CameraTrack); - addSample(new Sample_Character); - addSample(new CSMShadows); -#if OGRE_PLATFORM != OGRE_PLATFORM_WINRT - addSample(new Sample_DynTex); - addSample(new Sample_FacialAnimation); - addSample(new Sample_Grass); - addSample(new Sample_DualQuaternion); - addSample(new Sample_Isosurf); -#ifdef HAVE_IMGUI - addSample(new Sample_ImGui); -#endif - addSample(new Sample_NewInstancing); - addSample(new Sample_TextureArray); - addSample(new Sample_Tessellation); - addSample(new Sample_PNTriangles); -# ifdef OGRE_BUILD_COMPONENT_VOLUME - addSample(new Sample_VolumeCSG); - addSample(new Sample_VolumeTerrain); -# endif - addSample(new Sample_VolumeTex); - addSample(new Sample_Shadows); - addSample(new Sample_Lighting); - addSample(new Sample_LightShafts); -#ifdef OGRE_BUILD_COMPONENT_MESHLODGENERATOR - addSample(new Sample_MeshLod); -#endif - addSample(new Sample_ParticleFX); -#ifdef HAVE_PCZ_PLUGIN - addSample(new Sample_PCZTest); -#endif - addSample(new Sample_ParticleGS); - addSample(new Sample_Smoke); -#endif // OGRE_PLATFORM_WINRT - addSample(new Sample_SkeletalAnimation); - addSample(new Sample_SkyBox); - addSample(new Sample_SkyDome); - addSample(new Sample_SkyPlane); - addSample(new Sample_SphereMapping); - addSample(new Sample_TextureFX); - addSample(new Sample_Transparency); - - // the samples below require shaders - addSample(new Sample_Tessellation); - addSample(new Sample_PBR); - addSample(new Sample_RectLight); -#if defined(OGRE_BUILD_COMPONENT_RTSHADERSYSTEM) && OGRE_PLATFORM != OGRE_PLATFORM_WINRT - addSample(new Sample_ShaderSystem); - addSample(new Sample_ShaderSystemTexturedFog); - addSample(new Sample_ShaderSystemMultiLight); -#endif - addSample(new Sample_BSP); - addSample(new Sample_CelShading); - addSample(new Sample_Compositor); - addSample(new Sample_Compute); - addSample(new Sample_CubeMapping); - addSample(new Sample_DeferredShading); - addSample(new Sample_SSAO); - addSample(new Sample_Ocean); - addSample(new Sample_Water); - addSample(new Sample_Dot3Bump); - addSample(new Sample_Fresnel); -#ifdef OGRE_BUILD_COMPONENT_TERRAIN - addSample(new Sample_Terrain); - addSample(new Sample_EndlessWorld); -#endif -} - -DefaultSamplesPlugin::~DefaultSamplesPlugin() -{ - for (auto s : mSamples) - { - delete s; - } -} - -#ifndef OGRE_STATIC_LIB -static SamplePlugin* sp; - -extern "C" void _OgreSampleExport dllStartPlugin(void); -extern "C" void _OgreSampleExport dllStopPlugin(void); - -extern "C" _OgreSampleExport void dllStartPlugin() -{ - sp = new DefaultSamplesPlugin(); - Root::getSingleton().installPlugin(sp); -} - -extern "C" _OgreSampleExport void dllStopPlugin() -{ - Root::getSingleton().uninstallPlugin(sp); - delete sp; -} -#endif diff --git a/Samples/Compositor/include/Compositor.h b/Samples/Compositor/include/Compositor.h deleted file mode 100644 index 9a50c0560ea..00000000000 --- a/Samples/Compositor/include/Compositor.h +++ /dev/null @@ -1,666 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - - You may use this sample code for anything you like, it is not covered by the - same license as the rest of the engine. - ----------------------------------------------------------------------------- -*/ - -#ifndef __CompositorDemo_H__ -#define __CompositorDemo_H__ - -#include "OgreConfigFile.h" -#include "OgreStringConverter.h" -#include "OgreException.h" - -#include "SdkSample.h" -#include "SamplePlugin.h" - -using namespace Ogre; -using namespace OgreBites; - -#define COMPOSITORS_PER_PAGE 8 - -class _OgreSampleClassExport Sample_Compositor : public SdkSample -{ - public: - Sample_Compositor(); - - void setupContent(void) override; - void cleanupContent(void) override; - - bool frameRenderingQueued(const FrameEvent& evt) override; - - void checkBoxToggled(OgreBites::CheckBox * box) override; - void buttonHit(OgreBites::Button* button) override; - void itemSelected(OgreBites::SelectMenu* menu) override; - - protected: - - void setupView(void) override; - void setupControls(void); - void setupScene(void); - void createEffects(void); - void createTextures(void); - - void registerCompositors(); - void changePage(size_t pageNum); - - SceneNode * mSpinny; - StringVector mCompositorNames; - size_t mActiveCompositorPage; - size_t mNumCompositorPages; - - //Used to unregister compositor logics and free memory - typedef std::map CompositorLogicMap; - CompositorLogicMap mCompositorLogics; - - String mDebugCompositorName; - SelectMenu* mDebugTextureSelectMenu; - TextureUnitState* mDebugTextureTUS; - -}; - -/** - @file - Compositor.cpp - @brief - Shows OGRE's Compositor feature - @author - W.J. :wumpus: van der Laan - Ogre compositor framework - Manuel Bua - Postfilter ideas and original out-of-core implementation - Jeff (nfz) Doyle - added gui framework to demo -*/ - -#include "HelperLogics.h" - -/************************************************************************* - Sample_Compositor Methods -*************************************************************************/ -Sample_Compositor::Sample_Compositor() -{ - mInfo["Title"] = "Compositor"; - mInfo["Description"] = "A demo of Ogre's post-processing framework."; - mInfo["Thumbnail"] = "thumb_comp.png"; - mInfo["Category"] = "Effects"; -} - - -void Sample_Compositor::setupView() -{ - SdkSample::setupView(); - mCameraNode->setPosition(Ogre::Vector3(0,0,0)); - mCameraNode->lookAt(Ogre::Vector3(0,0,-300), Ogre::Node::TS_PARENT); - mCamera->setNearClipDistance(1); -} - - -void Sample_Compositor::setupContent(void) -{ - // Register the compositor logics - // See comment in beginning of HelperLogics.h for explanation - Ogre::CompositorManager& compMgr = Ogre::CompositorManager::getSingleton(); - mCompositorLogics["GaussianBlur"] = new GaussianBlurLogic; - mCompositorLogics["HDR"] = new HDRLogic; - mCompositorLogics["HeatVision"] = new HeatVisionLogic; - compMgr.registerCompositorLogic("GaussianBlur", mCompositorLogics["GaussianBlur"]); - compMgr.registerCompositorLogic("HDR", mCompositorLogics["HDR"]); - compMgr.registerCompositorLogic("HeatVision", mCompositorLogics["HeatVision"]); - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - mShaderGenerator->createScheme("HDR"); // make sure HDR viewport is handled -#endif - - createTextures(); - /// Create a couple of hard coded postfilter effects as an example of how to do it - /// but the preferred method is to use compositor scripts. - createEffects(); - - setupScene(); - - registerCompositors(); - - setupControls(); - setDragLook(true); -} - -static bool blacklisted(const String& name) -{ - const char* blacklist[] = {"Ogre/Scene/", "DeferredShading", "SSAO", "TestMRT", "Compute", "Fresnel", "CubeMap"}; - - for(auto it : blacklist) - { - if(name.find(it) == 0) - return true; - } - - return false; -} - -void Sample_Compositor::registerCompositors(void) -{ - Ogre::Viewport *vp = mViewport; - - //iterate through Compositor Managers resources and add name keys to menu - Ogre::CompositorManager::ResourceMapIterator resourceIterator = - Ogre::CompositorManager::getSingleton().getResourceIterator(); - - // add all compositor resources to the view container - while (resourceIterator.hasMoreElements()) - { - Ogre::ResourcePtr resource = resourceIterator.getNext(); - const Ogre::String& compositorName = resource->getName(); - - // Don't add blacklisted compositor to view - if (blacklisted(compositorName)) - continue; - - mCompositorNames.push_back(compositorName); - int addPosition = -1; - if (compositorName == "HDR") - { - // HDR must be first in the chain - addPosition = 0; - } - try - { - Ogre::CompositorManager::getSingleton().addCompositor(vp, compositorName, addPosition); - Ogre::CompositorManager::getSingleton().setCompositorEnabled(vp, compositorName, false); - } catch (Ogre::Exception& e) { - /// Warn user - LogManager::getSingleton().logMessage(e.getDescription(), LML_CRITICAL); - } - } - - mNumCompositorPages = (mCompositorNames.size() / COMPOSITORS_PER_PAGE) + - ((mCompositorNames.size() % COMPOSITORS_PER_PAGE == 0) ? 0 : 1); -} - - -void Sample_Compositor::changePage(size_t pageNum) -{ - assert(pageNum < mNumCompositorPages); - - mActiveCompositorPage = pageNum; - size_t maxCompositorsInPage = mCompositorNames.size() - (pageNum * COMPOSITORS_PER_PAGE); - for (size_t i=0; i < COMPOSITORS_PER_PAGE; i++) - { - String checkBoxName = "Compositor_" + Ogre::StringConverter::toString(i); - CheckBox* cb = static_cast(mTrayMgr->getWidget(TL_TOPLEFT, checkBoxName)); - if (i < maxCompositorsInPage) - { - String compositorName = mCompositorNames[pageNum * COMPOSITORS_PER_PAGE + i]; - CompositorInstance *tmpCompo = CompositorManager::getSingleton().getCompositorChain(mViewport) - ->getCompositor(compositorName); - - cb->setCaption(compositorName); - - if( tmpCompo ) - { - cb->setChecked( tmpCompo->getEnabled(), false ); - cb->show(); - } - else - { - cb->setChecked( false, false ); - cb->hide(); - } - - } - else - { - cb->hide(); - } - } - - OgreBites::Button* pageButton = static_cast(mTrayMgr->getWidget(TL_TOPLEFT, "PageButton")); - Ogre::StringStream ss; - ss << "Compositors " << pageNum + 1 << "/" << mNumCompositorPages; - pageButton->setCaption(ss.str()); -} - - -void Sample_Compositor::cleanupContent(void) -{ - mDebugTextureTUS->setContentType(TextureUnitState::CONTENT_NAMED); - CompositorManager::getSingleton().removeCompositorChain(mViewport); - mCompositorNames.clear(); - - TextureManager::getSingleton().remove("DitherTex", "General"); - TextureManager::getSingleton().remove("HalftoneVolume", "General"); - - Ogre::CompositorManager& compMgr = Ogre::CompositorManager::getSingleton(); - CompositorLogicMap::const_iterator itor = mCompositorLogics.begin(); - CompositorLogicMap::const_iterator end = mCompositorLogics.end(); - while( itor != end ) - { - compMgr.unregisterCompositorLogic( itor->first ); - delete itor->second; - ++itor; - } - mCompositorLogics.clear(); - MeshManager::getSingleton().remove("Myplane", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); -} - - -void Sample_Compositor::setupControls(void) -{ - mTrayMgr->createButton(TL_TOPLEFT, "PageButton", "Compositors", 175); - - for (size_t i=0; i < COMPOSITORS_PER_PAGE; i++) - { - String checkBoxName = "Compositor_" + Ogre::StringConverter::toString(i); - CheckBox* cb = mTrayMgr->createCheckBox(TL_TOPLEFT, checkBoxName, "Compositor", 175); - cb->hide(); - } - - changePage(0); - - mDebugTextureSelectMenu = mTrayMgr->createThickSelectMenu(TL_TOPRIGHT, "DebugRTTSelectMenu", "Debug RTT", 180, 5); - mDebugTextureSelectMenu->addItem("None"); - - mTrayMgr->createSeparator(TL_TOPRIGHT, "DebugRTTSep1"); // this is a hack to give the debug RTT a bit more room - - DecorWidget* debugRTTPanel = mTrayMgr->createDecorWidget(TL_NONE, "DebugRTTPanel", "SdkTrays/Picture"); - OverlayContainer* debugRTTContainer = (OverlayContainer*)debugRTTPanel->getOverlayElement(); - mDebugTextureTUS = debugRTTContainer->getMaterial()->getBestTechnique()->getPass(0)->getTextureUnitState(0); - //mDebugTextureTUS->setTextureName("CompositorDemo/DebugView"); - debugRTTContainer->setDimensions(128, 128); - debugRTTContainer->getChild("DebugRTTPanel/PictureFrame")->setDimensions(144, 144); - debugRTTPanel->hide(); - - mTrayMgr->createSeparator(TL_TOPRIGHT, "DebugRTTSep2"); // this is a hack to give the debug RTT a bit more room - - mTrayMgr->showCursor(); - mTrayMgr->showLogo(TL_BOTTOMLEFT); - mTrayMgr->toggleAdvancedFrameStats(); -} - - -void Sample_Compositor::checkBoxToggled(OgreBites::CheckBox * box) -{ - if (Ogre::StringUtil::startsWith(box->getName(), "Compositor_", false)) - { - String compositorName = box->getCaption(); - - String activeTex = mDebugTextureSelectMenu->getSelectedItem(); - - if (!box->isChecked()) - { - //Remove the items from the debug menu and remove debug texture if from disabled compositor - bool debuggingRemovedTex = StringUtil::startsWith(activeTex, compositorName, false); - if (debuggingRemovedTex) - { - mDebugTextureTUS->setContentType(TextureUnitState::CONTENT_NAMED); - mDebugTextureSelectMenu->selectItem(0, true); - } - for (unsigned int i = 1; i < mDebugTextureSelectMenu->getNumItems(); i++) - { - if (StringUtil::startsWith(mDebugTextureSelectMenu->getItems()[i], compositorName, false)) - { - mDebugTextureSelectMenu->removeItem(i); - i--; - } - } - if (!debuggingRemovedTex) - { - //Selection clears itself when removing items. Restore. - mDebugTextureSelectMenu->selectItem(activeTex, false); - } - } - - CompositorManager::getSingleton().setCompositorEnabled(mViewport, compositorName, box->isChecked()); - - - if (box->isChecked()) - { - //Add the items to the selectable texture menu - CompositorInstance* instance = CompositorManager::getSingleton().getCompositorChain(mViewport)->getCompositor(compositorName); - if (instance) - { - const CompositionTechnique::TextureDefinitions& defs = - instance->getTechnique()->getTextureDefinitions(); - CompositionTechnique::TextureDefinitions::const_iterator defIter; - for (defIter = defs.begin(); defIter != defs.end(); ++defIter) - { - CompositionTechnique::TextureDefinition* texDef = *defIter; - size_t numTextures = texDef->formatList.size(); - if (numTextures > 1) - { - for (size_t i=0; iaddItem(compositorName + ";" + texDef->name + ";" + - Ogre::StringConverter::toString((Ogre::uint32)i)); - } - } - else - { - mDebugTextureSelectMenu->addItem(compositorName + ";" + texDef->name); - } - } - mDebugTextureSelectMenu->selectItem(activeTex, false); - } - } - } -} - - -void Sample_Compositor::buttonHit(OgreBites::Button* button) -{ - size_t nextPage = (mActiveCompositorPage + 1) % mNumCompositorPages; - changePage(nextPage); -} - - -void Sample_Compositor::itemSelected(OgreBites::SelectMenu* menu) -{ - if (menu->getSelectionIndex() == 0) - { - mDebugTextureTUS->setContentType(TextureUnitState::CONTENT_NAMED); - mTrayMgr->getWidget("DebugRTTPanel")->hide(); - mTrayMgr->removeWidgetFromTray("DebugRTTPanel"); - return; - } - - mTrayMgr->getWidget("DebugRTTPanel")->show(); - mTrayMgr->moveWidgetToTray("DebugRTTPanel", TL_TOPRIGHT, mTrayMgr->getWidgets(TL_TOPRIGHT).size() - 1); - StringVector parts = StringUtil::split(menu->getSelectedItem(), ";"); - mDebugTextureTUS->setContentType(TextureUnitState::CONTENT_COMPOSITOR); - - if (parts.size() == 2) - { - mDebugTextureTUS->setCompositorReference(parts[0], parts[1]); - } - else - { - mDebugTextureTUS->setCompositorReference(parts[0], parts[1], - StringConverter::parseUnsignedInt(parts[2])); - } -} - - -void Sample_Compositor::setupScene(void) -{ - mSceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_TEXTURE_MODULATIVE); - mSceneMgr->setShadowFarDistance(1000); - - Ogre::MovableObject::setDefaultVisibilityFlags(0x00000001); - - // Set ambient light - mSceneMgr->setAmbientLight(Ogre::ColourValue(0.3, 0.3, 0.2)); - - Ogre::Light* l = mSceneMgr->createLight(Light::LT_DIRECTIONAL); - l->setDiffuseColour(1, 1, 0.8); - l->setSpecularColour(1, 1, 1); - - auto ln = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - ln->setDirection(Vector3(-1,-1,0).normalisedCopy()); - ln->attachObject(l); - - - Ogre::Entity* pEnt; - - // House - pEnt = mSceneMgr->createEntity( "1", "tudorhouse.mesh" ); - Ogre::SceneNode* n1 = mSceneMgr->getRootSceneNode()->createChildSceneNode(Ogre::Vector3(350, 450, -200)); - n1->attachObject( pEnt ); - - pEnt = mSceneMgr->createEntity( "2", "tudorhouse.mesh" ); - Ogre::SceneNode* n2 = mSceneMgr->getRootSceneNode()->createChildSceneNode(Ogre::Vector3(-350, 450, -200)); - n2->attachObject( pEnt ); - - pEnt = mSceneMgr->createEntity( "3", "knot.mesh" ); - mSpinny = mSceneMgr->getRootSceneNode()->createChildSceneNode(Ogre::Vector3(0, 0, 300)); - mSpinny->attachObject( pEnt ); - pEnt->setMaterialName("Examples/MorningCubeMap"); - - mSceneMgr->setSkyBox(true, "Examples/MorningSkyBox"); - - - Ogre::Plane plane; - plane.normal = Ogre::Vector3::UNIT_Y; - plane.d = 100; - Ogre::MeshManager::getSingleton().createPlane("Myplane", - Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane, - 1500, 1500, 10, 10, true, 1, 5, 5, Ogre::Vector3::UNIT_Z); - Ogre::Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("Examples/Rockwall"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - mCameraNode->setPosition(-400, 50, 900); - mCameraNode->lookAt(Ogre::Vector3(0,80,0), Ogre::Node::TS_PARENT); -} - - -bool Sample_Compositor::frameRenderingQueued(const FrameEvent& evt) -{ - mSpinny->yaw(Ogre::Degree(10 * evt.timeSinceLastFrame)); - return SdkSample::frameRenderingQueued(evt); -} - - -/// Create the hard coded postfilter effects -void Sample_Compositor::createEffects(void) -{ - /// Motion blur effect - Ogre::CompositorPtr comp3 = Ogre::CompositorManager::getSingleton().create( - "Motion Blur", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME - ); - { - Ogre::CompositionTechnique *t = comp3->createTechnique(); - { - Ogre::CompositionTechnique::TextureDefinition *def = t->createTextureDefinition("scene"); - def->width = 0; - def->height = 0; - def->formatList.push_back(Ogre::PF_R8G8B8); - } - { - Ogre::CompositionTechnique::TextureDefinition *def = t->createTextureDefinition("sum"); - def->width = 0; - def->height = 0; - def->formatList.push_back(Ogre::PF_R8G8B8); - } - { - Ogre::CompositionTechnique::TextureDefinition *def = t->createTextureDefinition("temp"); - def->width = 0; - def->height = 0; - def->formatList.push_back(Ogre::PF_R8G8B8); - } - /// Render scene - { - Ogre::CompositionTargetPass *tp = t->createTargetPass(); - tp->setInputMode(Ogre::CompositionTargetPass::IM_PREVIOUS); - tp->setOutputName("scene"); - } - /// Initialisation pass for sum texture - { - Ogre::CompositionTargetPass *tp = t->createTargetPass(); - tp->setInputMode(Ogre::CompositionTargetPass::IM_PREVIOUS); - tp->setOutputName("sum"); - tp->setOnlyInitial(true); - } - /// Do the motion blur - { - Ogre::CompositionTargetPass *tp = t->createTargetPass(); - tp->setInputMode(Ogre::CompositionTargetPass::IM_NONE); - tp->setOutputName("temp"); - { Ogre::CompositionPass *pass = tp->createPass(Ogre::CompositionPass::PT_RENDERQUAD); - pass->setMaterialName("Ogre/Compositor/Combine"); - pass->setInput(0, "scene"); - pass->setInput(1, "sum"); - } - } - /// Copy back sum texture - { - Ogre::CompositionTargetPass *tp = t->createTargetPass(); - tp->setInputMode(Ogre::CompositionTargetPass::IM_NONE); - tp->setOutputName("sum"); - { Ogre::CompositionPass *pass = tp->createPass(Ogre::CompositionPass::PT_RENDERQUAD); - pass->setMaterialName("Ogre/Compositor/Copyback"); - pass->setInput(0, "temp"); - } - } - /// Display result - { - Ogre::CompositionTargetPass *tp = t->getOutputTargetPass(); - tp->setInputMode(Ogre::CompositionTargetPass::IM_NONE); - { Ogre::CompositionPass *pass = tp->createPass(Ogre::CompositionPass::PT_RENDERQUAD); - pass->setMaterialName("Ogre/Compositor/MotionBlur"); - pass->setInput(0, "sum"); - } - } - } - /// Heat vision effect - Ogre::CompositorPtr comp4 = Ogre::CompositorManager::getSingleton().create( - "Heat Vision", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME - ); - { - Ogre::CompositionTechnique *t = comp4->createTechnique(); - t->setCompositorLogicName("HeatVision"); - { - Ogre::CompositionTechnique::TextureDefinition *def = t->createTextureDefinition("scene"); - def->width = 256; - def->height = 256; - def->formatList.push_back(Ogre::PF_R8G8B8); - } - { - Ogre::CompositionTechnique::TextureDefinition *def = t->createTextureDefinition("temp"); - def->width = 256; - def->height = 256; - def->formatList.push_back(Ogre::PF_R8G8B8); - } - /// Render scene - { - Ogre::CompositionTargetPass *tp = t->createTargetPass(); - tp->setInputMode(Ogre::CompositionTargetPass::IM_PREVIOUS); - tp->setOutputName("scene"); - } - /// Light to heat pass - { - Ogre::CompositionTargetPass *tp = t->createTargetPass(); - tp->setInputMode(Ogre::CompositionTargetPass::IM_NONE); - tp->setOutputName("temp"); - { - Ogre::CompositionPass *pass = tp->createPass(Ogre::CompositionPass::PT_RENDERQUAD); - pass->setIdentifier(0xDEADBABE); /// Identify pass for use in listener - pass->setMaterialName("Fury/HeatVision/LightToHeat"); - pass->setInput(0, "scene"); - } - } - /// Display result - { - Ogre::CompositionTargetPass *tp = t->getOutputTargetPass(); - tp->setInputMode(Ogre::CompositionTargetPass::IM_NONE); - { - Ogre::CompositionPass *pass = tp->createPass(Ogre::CompositionPass::PT_RENDERQUAD); - pass->setMaterialName("Fury/HeatVision/Blur"); - pass->setInput(0, "temp"); - } - } - } -} - - -void Sample_Compositor::createTextures(void) -{ - using namespace Ogre; - - TexturePtr tex = TextureManager::getSingleton().createManual( - "HalftoneVolume", - "General", - TEX_TYPE_3D, - 64,64,64, - 0, - PF_L8, - TU_DYNAMIC_WRITE_ONLY - ); - - MaterialManager::getSingleton() - .getByName("Ogre/Compositor/Halftone", "General") - ->getTechnique(0) - ->getPass(0) - ->getTextureUnitState("noise") - ->setTexture(tex); - - if(tex) - { - HardwarePixelBufferSharedPtr ptr = tex->getBuffer(0,0); - ptr->lock(HardwareBuffer::HBL_DISCARD); - const PixelBox &pb = ptr->getCurrentLock(); - Ogre::uint8 *data = pb.data; - - size_t height = pb.getHeight(); - size_t width = pb.getWidth(); - size_t depth = pb.getDepth(); - size_t rowPitch = pb.rowPitch; - size_t slicePitch = pb.slicePitch; - - for (size_t z = 0; z < depth; ++z) - { - for (size_t y = 0; y < height; ++y) - { - for(size_t x = 0; x < width; ++x) - { - float fx = 32-(float)x+0.5f; - float fy = 32-(float)y+0.5f; - float fz = 32-((float)z)/3+0.5f; - float distanceSquare = fx*fx+fy*fy+fz*fz; - data[slicePitch*z + rowPitch*y + x] = 0x00; - if (distanceSquare < 1024.0f) - data[slicePitch*z + rowPitch*y + x] += 0xFF; - } - } - } - ptr->unlock(); - } - Ogre::Viewport *vp = mWindow->getViewport(0); - - TexturePtr tex2 = TextureManager::getSingleton().createManual( - "DitherTex", - "General", - TEX_TYPE_2D, - vp->getActualWidth(),vp->getActualHeight(),1, - 0, - PF_L8, - TU_DYNAMIC_WRITE_ONLY - ); - - MaterialManager::getSingleton() - .getByName("Ogre/Compositor/Dither", "General") - ->getTechnique(0) - ->getPass(0) - ->getTextureUnitState("noise") - ->setTexture(tex2); - - HardwarePixelBufferSharedPtr ptr2 = tex2->getBuffer(0,0); - ptr2->lock(HardwareBuffer::HBL_DISCARD); - const PixelBox &pb2 = ptr2->getCurrentLock(); - Ogre::uint8 *data2 = pb2.data; - - size_t height2 = pb2.getHeight(); - size_t width2 = pb2.getWidth(); - size_t rowPitch2 = pb2.rowPitch; - - for (size_t y = 0; y < height2; ++y) - { - for(size_t x = 0; x < width2; ++x) - { - data2[rowPitch2*y + x] = Ogre::Math::RangeRandom(64.0,192); - } - } - - ptr2->unlock(); -} - -#endif // end _CompositorDemo_H_ diff --git a/Samples/Compositor/include/HelperLogics.h b/Samples/Compositor/include/HelperLogics.h deleted file mode 100644 index 5c2e626e3a8..00000000000 --- a/Samples/Compositor/include/HelperLogics.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - - You may use this sample code for anything you like, it is not covered by the - conditions of the standard open source license. - ----------------------------------------------------------------------------- -*/ - -#ifndef __HelperLogics_H__ -#define __HelperLogics_H__ - -#include "OgrePrerequisites.h" -#include "OgreCompositorLogic.h" -#include "OgreCompositorInstance.h" - -/** - The simple types of compositor logics will all do the same thing. - Attach a listener to the created compositor. - - Demo note: - This file contains three compositor logics for the HDR, Heat Vision - and Gaussian Blur compositors. If you wish to use these - compositors in your application, make sure to add this code as - well. This code fits the plugin architecture pretty well, but was - not exported to a plugin for simplification of the SDK package. - @see CompositorDemo::loadResources -*/ -#include "ListenerFactoryLogic.h" - -/// The compositor logic for the heat vision compositor. -class HeatVisionLogic : public ListenerFactoryLogic -{ - protected: - /** @copydoc ListenerFactoryLogic::createListener */ - Ogre::CompositorInstance::Listener* createListener(Ogre::CompositorInstance* instance) override; -}; - -/// The compositor logic for the HDR compositor. -class HDRLogic : public ListenerFactoryLogic -{ - protected: - /** @copydoc ListenerFactoryLogic::createListener */ - Ogre::CompositorInstance::Listener* createListener(Ogre::CompositorInstance* instance) override; -}; - -/// The compositor logic for the gaussian blur compositor. -class GaussianBlurLogic : public ListenerFactoryLogic -{ - protected: - /** @copydoc ListenerFactoryLogic::createListener */ - Ogre::CompositorInstance::Listener* createListener(Ogre::CompositorInstance* instance) override; -}; - -#endif diff --git a/Samples/Compositor/src/HelperLogics.cpp b/Samples/Compositor/src/HelperLogics.cpp deleted file mode 100644 index 1294bdd5558..00000000000 --- a/Samples/Compositor/src/HelperLogics.cpp +++ /dev/null @@ -1,344 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#include "HelperLogics.h" - -#include - -#include "Ogre.h" -#include "OgreTimer.h" - -//--------------------------------------------------------------------------- -class HeatVisionListener: public Ogre::CompositorInstance::Listener -{ -public: - HeatVisionListener(); - virtual ~HeatVisionListener(); - void notifyMaterialSetup(Ogre::uint32 pass_id, Ogre::MaterialPtr &mat) override; - void notifyMaterialRender(Ogre::uint32 pass_id, Ogre::MaterialPtr &mat) override; -protected: - Ogre::GpuProgramParametersSharedPtr fpParams; - float start, end, curr; - Ogre::Timer *timer; -}; -//--------------------------------------------------------------------------- -class HDRListener: public Ogre::CompositorInstance::Listener -{ -protected: - int mVpWidth, mVpHeight; - int mBloomSize; - // Array params - have to pack in groups of 4 since this is how Cg generates them - // also prevents dependent texture read problems if ops don't require swizzle - float mBloomTexWeights[15][4]; - float mBloomTexOffsetsHorz[15][4]; - float mBloomTexOffsetsVert[15][4]; -public: - HDRListener(); - virtual ~HDRListener(); - void notifyViewportSize(int width, int height); - void notifyCompositor(Ogre::CompositorInstance* instance); - void notifyMaterialSetup(Ogre::uint32 pass_id, Ogre::MaterialPtr &mat) override; - void notifyMaterialRender(Ogre::uint32 pass_id, Ogre::MaterialPtr &mat) override; -}; -//--------------------------------------------------------------------------- -class GaussianListener : public Ogre::CompositorInstance::Listener -{ -protected: - int mVpWidth, mVpHeight; - // Array params - have to pack in groups of 4 since this is how Cg generates them - // also prevents dependent texture read problems if ops don't require swizzle - float mBloomTexWeights[15][4]; - float mBloomTexOffsetsHorz[15][4]; - float mBloomTexOffsetsVert[15][4]; -public: - GaussianListener(); - virtual ~GaussianListener(); - void notifyViewportSize(int width, int height); - void notifyMaterialSetup(Ogre::uint32 pass_id, Ogre::MaterialPtr &mat) override; - void notifyMaterialRender(Ogre::uint32 pass_id, Ogre::MaterialPtr &mat) override; -}; -//--------------------------------------------------------------------------- -Ogre::CompositorInstance::Listener* HDRLogic::createListener(Ogre::CompositorInstance* instance) -{ - HDRListener* listener = new HDRListener; - Ogre::Viewport* vp = instance->getChain()->getViewport(); - listener->notifyViewportSize(vp->getActualWidth(), vp->getActualHeight()); - listener->notifyCompositor(instance); - return listener; -} -//--------------------------------------------------------------------------- -Ogre::CompositorInstance::Listener* HeatVisionLogic::createListener(Ogre::CompositorInstance* instance) -{ - return new HeatVisionListener; -} -//--------------------------------------------------------------------------- -Ogre::CompositorInstance::Listener* GaussianBlurLogic::createListener(Ogre::CompositorInstance* instance) -{ - GaussianListener* listener = new GaussianListener; - Ogre::Viewport* vp = instance->getChain()->getViewport(); - listener->notifyViewportSize(vp->getActualWidth(), vp->getActualHeight()); - return listener; -} -/************************************************************************* - HeatVisionListener Methods -*************************************************************************/ -//--------------------------------------------------------------------------- -HeatVisionListener::HeatVisionListener() -{ - timer = new Ogre::Timer(); - start = end = curr = 0.0f; -} -//--------------------------------------------------------------------------- -HeatVisionListener::~HeatVisionListener() -{ - delete timer; -} -//--------------------------------------------------------------------------- -void HeatVisionListener::notifyMaterialSetup(Ogre::uint32 pass_id, Ogre::MaterialPtr &mat) -{ - if(pass_id == 0xDEADBABE) - { - timer->reset(); - fpParams = - mat->getTechnique(0)->getPass(0)->getFragmentProgramParameters(); - } -} -//--------------------------------------------------------------------------- -void HeatVisionListener::notifyMaterialRender(Ogre::uint32 pass_id, Ogre::MaterialPtr &mat) -{ - if(pass_id == 0xDEADBABE) - { - // "random_fractions" parameter - fpParams->setNamedConstant("random_fractions", Ogre::Vector4(Ogre::Math::RangeRandom(0.0, 1.0), Ogre::Math::RangeRandom(0, 1.0), 0, 0)); - - // "depth_modulator" parameter - float inc = ((float)timer->getMilliseconds())/1000.0f; - if ( (std::fabs(curr-end) <= 0.001) ) { - // take a new value to reach - end = Ogre::Math::RangeRandom(0.95, 1.0); - start = curr; - } else { - if (curr > end) curr -= inc; - else curr += inc; - } - timer->reset(); - - fpParams->setNamedConstant("depth_modulator", Ogre::Vector4(curr, 0, 0, 0)); - } -} -//--------------------------------------------------------------------------- - -/************************************************************************* -HDRListener Methods -*************************************************************************/ -//--------------------------------------------------------------------------- -HDRListener::HDRListener() -{ -} -//--------------------------------------------------------------------------- -HDRListener::~HDRListener() -{ -} -//--------------------------------------------------------------------------- -void HDRListener::notifyViewportSize(int width, int height) -{ - mVpWidth = width; - mVpHeight = height; -} -//--------------------------------------------------------------------------- -void HDRListener::notifyCompositor(Ogre::CompositorInstance* instance) -{ - // Get some RTT dimensions for later calculations - const Ogre::CompositionTechnique::TextureDefinitions& defs = - instance->getTechnique()->getTextureDefinitions(); - Ogre::CompositionTechnique::TextureDefinitions::const_iterator defIter; - for (defIter = defs.begin(); defIter != defs.end(); ++defIter) - { - Ogre::CompositionTechnique::TextureDefinition* def = *defIter; - if(def->name == "rt_bloom0") - { - mBloomSize = (int)def->width; // should be square - // Calculate gaussian texture offsets & weights - float deviation = 3.0f; - float texelSize = 1.0f / (float)mBloomSize; - - // central sample, no offset - mBloomTexOffsetsHorz[0][0] = 0.0f; - mBloomTexOffsetsHorz[0][1] = 0.0f; - mBloomTexOffsetsVert[0][0] = 0.0f; - mBloomTexOffsetsVert[0][1] = 0.0f; - mBloomTexWeights[0][0] = mBloomTexWeights[0][1] = - mBloomTexWeights[0][2] = Ogre::Math::gaussianDistribution(0, 0, deviation); - mBloomTexWeights[0][3] = 1.0f; - - // 'pre' samples - for(int i = 1; i < 8; ++i) - { - mBloomTexWeights[i][0] = mBloomTexWeights[i][1] = - mBloomTexWeights[i][2] = 1.25f * Ogre::Math::gaussianDistribution((Ogre::Real)i, 0, deviation); - mBloomTexWeights[i][3] = 1.0f; - mBloomTexOffsetsHorz[i][0] = i * texelSize; - mBloomTexOffsetsHorz[i][1] = 0.0f; - mBloomTexOffsetsVert[i][0] = 0.0f; - mBloomTexOffsetsVert[i][1] = i * texelSize; - } - // 'post' samples - for(int i = 8; i < 15; ++i) - { - mBloomTexWeights[i][0] = mBloomTexWeights[i][1] = - mBloomTexWeights[i][2] = mBloomTexWeights[i - 7][0]; - mBloomTexWeights[i][3] = 1.0f; - - mBloomTexOffsetsHorz[i][0] = -mBloomTexOffsetsHorz[i - 7][0]; - mBloomTexOffsetsHorz[i][1] = 0.0f; - mBloomTexOffsetsVert[i][0] = 0.0f; - mBloomTexOffsetsVert[i][1] = -mBloomTexOffsetsVert[i - 7][1]; - } - - } - } -} -//--------------------------------------------------------------------------- -void HDRListener::notifyMaterialSetup(Ogre::uint32 pass_id, Ogre::MaterialPtr &mat) -{ - // Prepare the fragment params offsets - switch(pass_id) - { - //case 994: // rt_lum4 - case 993: // rt_lum3 - case 992: // rt_lum2 - case 991: // rt_lum1 - case 990: // rt_lum0 - break; - case 800: // rt_brightpass - break; - case 701: // rt_bloom1 - { - // horizontal bloom - mat->load(); - Ogre::GpuProgramParametersSharedPtr fparams = - mat->getBestTechnique()->getPass(0)->getFragmentProgramParameters(); - fparams->setNamedConstant("sampleOffsets", mBloomTexOffsetsHorz[0], 15); - fparams->setNamedConstant("sampleWeights", mBloomTexWeights[0], 15); - - break; - } - case 700: // rt_bloom0 - { - // vertical bloom - mat->load(); - Ogre::GpuProgramParametersSharedPtr fparams = - mat->getTechnique(0)->getPass(0)->getFragmentProgramParameters(); - fparams->setNamedConstant("sampleOffsets", mBloomTexOffsetsVert[0], 15); - fparams->setNamedConstant("sampleWeights", mBloomTexWeights[0], 15); - - break; - } - } -} -//--------------------------------------------------------------------------- -void HDRListener::notifyMaterialRender(Ogre::uint32 pass_id, Ogre::MaterialPtr &mat) -{ -} -//--------------------------------------------------------------------------- - - -/************************************************************************* -GaussianListener Methods -*************************************************************************/ -//--------------------------------------------------------------------------- -GaussianListener::GaussianListener() -{ -} -//--------------------------------------------------------------------------- -GaussianListener::~GaussianListener() -{ -} -//--------------------------------------------------------------------------- -void GaussianListener::notifyViewportSize(int width, int height) -{ - mVpWidth = width; - mVpHeight = height; - // Calculate gaussian texture offsets & weights - float deviation = 3.0f; - float texelSize = 1.0f / (float)std::min(mVpWidth, mVpHeight); - - // central sample, no offset - mBloomTexOffsetsHorz[0][0] = 0.0f; - mBloomTexOffsetsHorz[0][1] = 0.0f; - mBloomTexOffsetsVert[0][0] = 0.0f; - mBloomTexOffsetsVert[0][1] = 0.0f; - mBloomTexWeights[0][0] = mBloomTexWeights[0][1] = - mBloomTexWeights[0][2] = Ogre::Math::gaussianDistribution(0, 0, deviation); - mBloomTexWeights[0][3] = 1.0f; - - // 'pre' samples - for(int i = 1; i < 8; ++i) - { - mBloomTexWeights[i][0] = mBloomTexWeights[i][1] = - mBloomTexWeights[i][2] = Ogre::Math::gaussianDistribution((Ogre::Real)i, 0, deviation); - mBloomTexWeights[i][3] = 1.0f; - mBloomTexOffsetsHorz[i][0] = i * texelSize; - mBloomTexOffsetsHorz[i][1] = 0.0f; - mBloomTexOffsetsVert[i][0] = 0.0f; - mBloomTexOffsetsVert[i][1] = i * texelSize; - } - // 'post' samples - for(int i = 8; i < 15; ++i) - { - mBloomTexWeights[i][0] = mBloomTexWeights[i][1] = - mBloomTexWeights[i][2] = mBloomTexWeights[i - 7][0]; - mBloomTexWeights[i][3] = 1.0f; - - mBloomTexOffsetsHorz[i][0] = -mBloomTexOffsetsHorz[i - 7][0]; - mBloomTexOffsetsHorz[i][1] = 0.0f; - mBloomTexOffsetsVert[i][0] = 0.0f; - mBloomTexOffsetsVert[i][1] = -mBloomTexOffsetsVert[i - 7][1]; - } -} -//--------------------------------------------------------------------------- -void GaussianListener::notifyMaterialSetup(Ogre::uint32 pass_id, Ogre::MaterialPtr &mat) -{ - // Prepare the fragment params offsets - switch(pass_id) - { - case 701: // blur horz - { - // horizontal bloom - mat->load(); - Ogre::GpuProgramParametersSharedPtr fparams = - mat->getBestTechnique()->getPass(0)->getFragmentProgramParameters(); - fparams->setNamedConstant("sampleOffsets", mBloomTexOffsetsHorz[0], 15); - fparams->setNamedConstant("sampleWeights", mBloomTexWeights[0], 15); - - break; - } - case 700: // blur vert - { - // vertical bloom - mat->load(); - Ogre::GpuProgramParametersSharedPtr fparams = - mat->getTechnique(0)->getPass(0)->getFragmentProgramParameters(); - fparams->setNamedConstant("sampleOffsets", mBloomTexOffsetsVert[0], 15); - fparams->setNamedConstant("sampleWeights", mBloomTexWeights[0], 15); - - break; - } - } -} -//--------------------------------------------------------------------------- -void GaussianListener::notifyMaterialRender(Ogre::uint32 pass_id, Ogre::MaterialPtr &mat) -{ -} -//--------------------------------------------------------------------------- diff --git a/Samples/Csharp/README.md b/Samples/Csharp/README.md deleted file mode 100644 index 415ea4fbedd..00000000000 --- a/Samples/Csharp/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# Build instructions - -1. copy the contents of `lib/cli/ogre-sharp-x.y.z/` to the `bin/` directory -2. copy `example.cs` to the `bin/` directory -3. compile the sample as - ``` - C:/Windows/Microsoft.NET/Framework64/x.y.z/csc.exe example.cs -r:Ogre.dll - ``` - On Linux, you can the `mcs` mono compiler instead. -4. Run the sample by double clicking `example.exe` or on linux, running: - ``` - mono example.exe - ``` \ No newline at end of file diff --git a/Samples/Csharp/example.cs b/Samples/Csharp/example.cs deleted file mode 100644 index 6619128fd6e..00000000000 --- a/Samples/Csharp/example.cs +++ /dev/null @@ -1,73 +0,0 @@ -using org.ogre; - -public class KeyListener : InputListener -{ - ApplicationContext ctx; - - public KeyListener(ApplicationContext ctx) - { - this.ctx = ctx; - } - - public override bool keyPressed(KeyboardEvent evt) - { - if (evt.keysym.sym == 27) - ctx.getRoot().queueEndRendering(); - return true; - } -} - -public class Example : ApplicationContext -{ - InputListener listener; - - public Example() - { - listener = new KeyListener(this); - } - - public override void setup() - { - base.setup(); - addInputListener(listener); - - var root = getRoot(); - var scnMgr = root.createSceneManager(); - - var shadergen = ShaderGenerator.getSingleton(); - shadergen.addSceneManager(scnMgr); // must be done before we do anything with the scene - - scnMgr.setAmbientLight(new ColourValue(.1f, .1f, .1f)); - - var light = scnMgr.createLight("MainLight"); - var lightnode = scnMgr.getRootSceneNode().createChildSceneNode(); - lightnode.setPosition(0f, 10f, 15f); - lightnode.attachObject(light); - - var cam = scnMgr.createCamera("myCam"); - cam.setAutoAspectRatio(true); - cam.setNearClipDistance(5); - var camnode = scnMgr.getRootSceneNode().createChildSceneNode(); - camnode.attachObject(cam); - - var camman = new CameraMan(camnode); - camman.setStyle(CameraStyle.CS_ORBIT); - camman.setYawPitchDist(new Radian(0), new Radian(0.3f), 15f); - addInputListener(camman); - - var vp = getRenderWindow().addViewport(cam); - vp.setBackgroundColour(new ColourValue(.3f, .3f, .3f)); - - var ent = scnMgr.createEntity("Sinbad.mesh"); - var node = scnMgr.getRootSceneNode().createChildSceneNode(); - node.attachObject(ent); - } - - static void Main() - { - var app = new Example(); - app.initApp(); - app.getRoot().startRendering(); - app.closeApp(); - } -} \ No newline at end of file diff --git a/Samples/Csharp/winforms.cs b/Samples/Csharp/winforms.cs deleted file mode 100644 index b2d8aafb34f..00000000000 --- a/Samples/Csharp/winforms.cs +++ /dev/null @@ -1,103 +0,0 @@ -using org.ogre; -using System.Windows.Forms; -using System.Runtime.InteropServices; - -public class Example : ApplicationContextBase -{ - private Form form; - - public Example() - { - form = new Form(); - form.Resize += Resize; - form.KeyDown += KeyDown; - form.Closing += Closing; - // TODO: prevent drawing of Form, since Ogre draws over anyway - - form.Show(); - } - - private void Resize(object sender, System.EventArgs e) - { - var win = getRenderWindow(); - win.windowMovedOrResized(); - windowResized(win); - } - - private void KeyDown(object sender, KeyEventArgs e) - { - if(e.KeyValue == 27) - getRoot().queueEndRendering(); - } - - private void Closing(object sender, System.ComponentModel.CancelEventArgs e) - { - getRoot().queueEndRendering(); - } - - public override NativeWindowPair createWindow(string title, uint w, uint h, NameValuePairList miscParams) - { - miscParams["externalWindowHandle"] = form.Handle.ToString(); - - var ret = base.createWindow(title, w, h, miscParams); - - w = ret.render.getWidth(); - h = ret.render.getHeight(); - - // update Form - form.Text = title; - form.Width = (int)w; - form.Height = (int)h; - - return ret; - } - - public override void setup() - { - base.setup(); - - var root = getRoot(); - var scnMgr = root.createSceneManager(); - - var shadergen = ShaderGenerator.getSingleton(); - shadergen.addSceneManager(scnMgr); // must be done before we do anything with the scene - - scnMgr.setAmbientLight(new ColourValue(.1f, .1f, .1f)); - - var light = scnMgr.createLight("MainLight"); - var lightnode = scnMgr.getRootSceneNode().createChildSceneNode(); - lightnode.setPosition(0f, 10f, 15f); - lightnode.attachObject(light); - - var cam = scnMgr.createCamera("myCam"); - cam.setAutoAspectRatio(true); - cam.setNearClipDistance(5); - var camnode = scnMgr.getRootSceneNode().createChildSceneNode(); - camnode.attachObject(cam); - - var camman = new CameraMan(camnode); - camman.setStyle(CameraStyle.CS_ORBIT); - camman.setYawPitchDist(new Radian(0), new Radian(0.3f), 15f); - - var vp = getRenderWindow().addViewport(cam); - vp.setBackgroundColour(new ColourValue(.3f, .3f, .3f)); - - var ent = scnMgr.createEntity("Sinbad.mesh"); - var node = scnMgr.getRootSceneNode().createChildSceneNode(); - node.attachObject(ent); - } - - static void Main() - { - var app = new Example(); - app.initApp(); - - while(!app.getRoot().endRenderingQueued()) - { - Application.DoEvents(); - app.getRoot().renderOneFrame(); - } - - app.closeApp(); - } -} \ No newline at end of file diff --git a/Samples/DeferredShading/include/AmbientLight.h b/Samples/DeferredShading/include/AmbientLight.h deleted file mode 100644 index 17ab14c59e1..00000000000 --- a/Samples/DeferredShading/include/AmbientLight.h +++ /dev/null @@ -1,53 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#ifndef _AMBIENTLIGHT_H -#define _AMBIENTLIGHT_H - -#include "OgreSimpleRenderable.h" - -// Renderable for rendering Ambient component and also to -// establish the depths - -// Just instantiation is sufficient -// Note that instantiation is necessary to at least establish the depths -// even if the current ambient colour is 0 - -// its ambient colour is same as the scene's ambient colour - -// XXX Could make this a singleton/make it private to the DeferredShadingSystem e.g. - -class AmbientLight : public Ogre::SimpleRenderable - -{ -public: - AmbientLight(); - ~AmbientLight(); - - /** @copydoc MovableObject::getBoundingRadius */ - Ogre::Real getBoundingRadius(void) const override; - /** @copydoc Renderable::getSquaredViewDepth */ - Ogre::Real getSquaredViewDepth(const Ogre::Camera*) const override; - /** @copydoc Renderable::getMaterial */ - const Ogre::MaterialPtr& getMaterial(void) const override; - - void getWorldTransforms(Ogre::Matrix4* xform) const override; - - void updateFromCamera(Ogre::Camera* camera); -protected: - Ogre::Real mRadius; - Ogre::MaterialPtr mMatPtr; -}; - -#endif diff --git a/Samples/DeferredShading/include/DLight.h b/Samples/DeferredShading/include/DLight.h deleted file mode 100644 index e522bf51669..00000000000 --- a/Samples/DeferredShading/include/DLight.h +++ /dev/null @@ -1,93 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#ifndef H_WJ_DLight -#define H_WJ_DLight - -#include "OgreSimpleRenderable.h" -#include "MaterialGenerator.h" - -/** Deferred light geometry. Each instance matches a normal light. - Should not be created by the user. - XXX support other types of light other than point lights. - */ -class DLight: public Ogre::SimpleRenderable -{ -public: - DLight(MaterialGenerator *gen, Ogre::Light* parentLight); - ~DLight(); - - /** Update the information from the light that matches this one - */ - void updateFromParent(); - - /** Update the information that is related to the camera - */ - void updateFromCamera(Ogre::Camera* camera); - - /** Does this light cast shadows? - */ - virtual bool getCastChadows() const; - - /** @copydoc MovableObject::getBoundingRadius */ - Ogre::Real getBoundingRadius(void) const override; - /** @copydoc Renderable::getSquaredViewDepth */ - Ogre::Real getSquaredViewDepth(const Ogre::Camera*) const override; - /** @copydoc Renderable::getMaterial */ - const Ogre::MaterialPtr& getMaterial(void) const override; - /** @copydoc Renderable::getBoundingRadius */ - void getWorldTransforms(Ogre::Matrix4* xform) const override; -protected: - - /** Check if the camera is inside a light - */ - bool isCameraInsideLight(Ogre::Camera* camera); - - /** Create geometry for this light. - */ - void rebuildGeometry(float radius); - - /** Create a sphere geometry. - */ - void createSphere(float radius, int nRings, int nSegments); - - /** Create a rectangle. - */ - void createRectangle2D(); - - /** Create a cone. - */ - void createCone(float radius, float height, int nVerticesInBase); - - /** Set constant, linear, quadratic Attenuation terms - */ - void setAttenuation(float c, float b, float a); - - /** Set the specular colour - */ - void setSpecularColour(const Ogre::ColourValue &col); - - /// The light that this DLight renders - Ogre::Light* mParentLight; - /// Mode to ignore world orientation/position - bool bIgnoreWorld; - /// Bounding sphere radius - float mRadius; - /// Deferred shading system this minilight is part of - MaterialGenerator *mGenerator; - /// Material permutation - Ogre::uint32 mPermutation; -}; - -#endif diff --git a/Samples/DeferredShading/include/DeferredLightCP.h b/Samples/DeferredShading/include/DeferredLightCP.h deleted file mode 100644 index f9f2ded7180..00000000000 --- a/Samples/DeferredShading/include/DeferredLightCP.h +++ /dev/null @@ -1,78 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#ifndef _DEFERRED_LIGHT_CP_H -#define _DEFERRED_LIGHT_CP_H - -#include "OgreCompositorInstance.h" -#include "OgreCustomCompositionPass.h" - -#include "DLight.h" -#include "MaterialGenerator.h" -#include "AmbientLight.h" - -//The render operation that will be called each frame in the custom composition pass -//This is the class that will send the actual render calls of the spheres (point lights), -//cones (spotlights) and quads (directional lights) after the GBuffer has been constructed -class DeferredLightRenderOperation : public Ogre::CompositorInstance::RenderSystemOperation -{ -public: - DeferredLightRenderOperation(Ogre::CompositorInstance* instance, const Ogre::CompositionPass* pass); - - /** @copydoc CompositorInstance::RenderSystemOperation::execute */ - void execute(Ogre::SceneManager *sm, Ogre::RenderSystem *rs) override; - - virtual ~DeferredLightRenderOperation(); -private: - - /** Create a new deferred light - */ - DLight *createDLight(Ogre::Light* light); - - //The texture names of the GBuffer components - Ogre::String mTexName0; - Ogre::String mTexName1; - - //The material generator for the light geometry - MaterialGenerator* mLightMaterialGenerator; - - //The map of deferred light geometries already constructed - typedef std::map LightsMap; - LightsMap mLights; - - //The ambient light used to render the scene - AmbientLight* mAmbientLight; - - //The viewport that we are rendering to - Ogre::Viewport* mViewport; -}; - -//The custom composition pass that is used for rendering the light geometry -//This class needs to be registered with the CompositorManager -class DeferredLightCompositionPass : public Ogre::CustomCompositionPass -{ -public: - - /** @copydoc CustomCompositionPass::createOperation */ - Ogre::CompositorInstance::RenderSystemOperation* createOperation( - Ogre::CompositorInstance* instance, const Ogre::CompositionPass* pass) override - { - return OGRE_NEW DeferredLightRenderOperation(instance, pass); - } - -protected: - virtual ~DeferredLightCompositionPass() {} -}; - -#endif diff --git a/Samples/DeferredShading/include/DeferredShading.h b/Samples/DeferredShading/include/DeferredShading.h deleted file mode 100755 index 1b51bf2fb60..00000000000 --- a/Samples/DeferredShading/include/DeferredShading.h +++ /dev/null @@ -1,111 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -/** -Implementation of a Deferred Shading engine in OGRE, using Multiple Render Targets and -CG high level language shaders. - // W.J. :wumpus: van der Laan 2005 / Noam Gat 2009 // - -Deferred shading renders the scene to a 'fat' texture format, using a shader that outputs colour, -normal, depth, and possible other attributes per fragment. Multi Render Target is required as we -are dealing with many outputs which get written into multiple render textures in the same pass. - -After rendering the scene in this format, the shading (lighting) can be done as a post process. -This means that lighting is done in screen space, using light-representing geometry (sphere for -point light, cone for spot light and quad for directional) to render their contribution. - -The wiki article explaining this demo can be found here : - http://www.ogre3d.org/wiki/index.php/Deferred_Shading -*/ - -#ifndef H_DeferredShadingSystem -#define H_DeferredShadingSystem - -#include "SdkSample.h" - -#include "OgreCompositorInstance.h" -#include "OgreSceneManager.h" -#include "OgreSceneNode.h" -#include "OgreMaterial.h" -#include "OgreRenderTargetListener.h" -#include "GeomUtils.h" - -using namespace Ogre; -using namespace OgreBites; - -/** System to manage Deferred Shading for a camera/render target. - * @note With the changes to the compositor framework, this class just - * selects which compositors to enable. - */ -class DeferredShadingSystem : public Ogre::RenderTargetListener -{ -public: - DeferredShadingSystem(Ogre::Viewport *vp, Ogre::SceneManager *sm, Ogre::Camera *cam); - ~DeferredShadingSystem(); - - enum DSMode - { - DSM_SHOWLIT = 0, // The deferred shading mode - DSM_SHOWCOLOUR = 1, // Show diffuse (for debugging) - DSM_SHOWNORMALS = 2, // Show normals (for debugging) - DSM_SHOWDSP = 3, // Show depth and specular channel (for debugging) - DSM_COUNT = 4 - }; - - //The first render queue that does not get rendered into the GBuffer - //place transparent (or other non gbuffer) objects after this one - static const Ogre::uint8 POST_GBUFFER_RENDER_QUEUE; - - void initialize(); - - /** Set rendering mode (one of DSMode) - */ - void setMode(DSMode mode); - - DSMode getMode(void) const; - - /** Set screen space ambient occlusion mode - */ - void setSSAO(bool ssao); - - bool getSSAO() const; - - /** Activate or deactivate system - */ - void setActive(bool active); - -protected: - Ogre::Viewport *mViewport; - Ogre::SceneManager *mSceneMgr; - Ogre::Camera *mCamera; - - Ogre::CompositorInstance *mGBufferInstance; - // Filters - Ogre::CompositorInstance *mInstance[DSM_COUNT]; - Ogre::CompositorInstance* mSSAOInstance; - // Active/inactive - bool mActive; - DSMode mCurrentMode; - bool mSSAO; - - //Used to unregister compositor logics and free memory - typedef std::map CompositorLogicMap; - CompositorLogicMap mCompositorLogics; - - void createResources(); - - void logCurrentMode(void); -}; - -#endif diff --git a/Samples/DeferredShading/include/DeferredShadingDemo.h b/Samples/DeferredShading/include/DeferredShadingDemo.h deleted file mode 100644 index d40102dde6a..00000000000 --- a/Samples/DeferredShading/include/DeferredShadingDemo.h +++ /dev/null @@ -1,438 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -/** -Implementation of a Deferred Shading engine in OGRE, using Multiple Render Targets and -CG high level language shaders. - // W.J. :wumpus: van der Laan 2005 / Noam Gat 2009 // - -Deferred shading renders the scene to a 'fat' texture format, using a shader that outputs colour, -normal, depth, and possible other attributes per fragment. Multi Render Target is required as we -are dealing with many outputs which get written into multiple render textures in the same pass. - -After rendering the scene in this format, the shading (lighting) can be done as a post process. -This means that lighting is done in screen space, using light-representing geometry (sphere for -point light, cone for spot light and quad for directional) to render their contribution. - -The wiki article explaining this demo can be found here : - http://www.ogre3d.org/wiki/index.php/Deferred_Shading -*/ - -#ifndef H_DeferredShadingDemo -#define H_DeferredShadingDemo - -#include "SdkSample.h" - -#include "DeferredShading.h" -#include "OgreCompositorInstance.h" -#include "OgreSceneManager.h" -#include "OgreSceneNode.h" -#include "OgreMaterial.h" -#include "OgreRenderTargetListener.h" -#include "GeomUtils.h" - -using namespace Ogre; -using namespace OgreBites; - -const ColourValue SAMPLE_COLORS[] = -{ ColourValue::Red, ColourValue::Green, ColourValue::Blue, - ColourValue::White, ColourValue(1,1,0,1), ColourValue(1,0,1,1) -}; - -class _OgreSampleClassExport Sample_DeferredShading : public SdkSample, public RenderTargetListener -{ -protected: - Light* mMainLight; - DeferredShadingSystem *mSystem; - SelectMenu* mDisplayModeMenu; - -public: - Sample_DeferredShading() - { - mInfo["Title"] = "Deferred Shading"; - mInfo["Description"] = "A sample implementation of a deferred renderer using the compositor framework."; - mInfo["Thumbnail"] = "thumb_deferred.png"; - mInfo["Category"] = "Lighting"; - mInfo["Help"] = "See http://www.ogre3d.org/wiki/index.php/Deferred_Shading for more info"; - } - -protected: - - void cleanupContent(void) override - { - delete mSystem; - } - - void setupControls() - { - mTrayMgr->showCursor(); - - // create checkboxs to toggle ssao and shadows - mTrayMgr->createCheckBox(TL_TOPLEFT, "DeferredShading", "Deferred Shading", 220)->setChecked(true, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "SSAO", "Ambient Occlusion", 220)->setChecked(false, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "GlobalLight", "Global Light", 220)->setChecked(true, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "Shadows", "Shadows", 220)->setChecked(true, false); - - // create a menu to choose the model displayed - mDisplayModeMenu = mTrayMgr->createThickSelectMenu(TL_TOPLEFT, "DisplayMode", "Display Mode", 220, 4); - mDisplayModeMenu->addItem("Regular view"); - mDisplayModeMenu->addItem("Debug colours"); - mDisplayModeMenu->addItem("Debug normals"); - mDisplayModeMenu->addItem("Debug depth / specular"); - } - - void itemSelected(SelectMenu* menu) override - { - //Options are aligned with the mode enum - mSystem->setMode((DeferredShadingSystem::DSMode)menu->getSelectionIndex()); - } - - void checkBoxToggled(CheckBox* box) override - { - if (box->getName() == "SSAO") - { - mSystem->setSSAO(box->isChecked()); - } - else if (box->getName() == "GlobalLight") - { - mMainLight->setVisible(box->isChecked()); - } - else if (box->getName() == "Shadows") - { - mSceneMgr->setShadowTechnique(box->isChecked() ? - SHADOWTYPE_TEXTURE_ADDITIVE : - SHADOWTYPE_NONE); - } - else if (box->getName() == "DeferredShading") - { - mSystem->setActive(box->isChecked()); - } - } - - //Utility function to help set scene up - void setEntityHeight(Entity* ent, Real newHeight) - { - Real curHeight = ent->getMesh()->getBounds().getSize().y; - Real scaleFactor = newHeight / curHeight; - - SceneNode* parentNode = ent->getParentSceneNode(); - parentNode->setScale(scaleFactor, scaleFactor, scaleFactor); - } - - void createAtheneScene(SceneNode* rootNode) - { - // Prepare athene mesh for normalmapping - MeshPtr pAthene = MeshManager::getSingleton().load("athene.mesh", RGN_DEFAULT); - pAthene->buildTangentVectors(); - - //Create an athena statue - Entity* athena = mSceneMgr->createEntity("Athena", "athene.mesh"); - athena->setMaterialName("DeferredDemo/DeferredAthena"); - SceneNode *aNode = rootNode->createChildSceneNode(); - aNode->attachObject( athena ); - aNode->setPosition(-8.5, 4.5, 0); - setEntityHeight(athena, 4.0); - aNode->yaw(Ogre::Degree(90)); - // Create some happy little lights to decorate the athena statue - createSampleLights(); - } - - void createKnotScene(SceneNode* rootNode) - { - // Prepare knot mesh for normal mapping - MeshPtr pKnot = MeshManager::getSingleton().load("knot.mesh", RGN_DEFAULT); - pKnot->buildTangentVectors(); - - // Create a bunch of knots with spotlights hanging from above - Entity* knotEnt = mSceneMgr->createEntity("Knot", "knot.mesh"); - knotEnt->setMaterialName("DeferredDemo/RockWall"); - //knotEnt->setMeshLodBias(0.25f); - Vector3 knotStartPos(25.5, 2, 5.5); - Vector3 knotDiff(-3.7, 0, 0); - for (int i=0; i < 5; i++) - { - Entity* cloneKnot = knotEnt->clone(StringUtil::format("Knot%d", i)); - Vector3 clonePos = knotStartPos + knotDiff*i; - SceneNode* cloneNode = rootNode->createChildSceneNode(clonePos); - cloneNode->attachObject(cloneKnot); - setEntityHeight(cloneKnot, 3); - cloneNode->yaw(Degree(i*17)); - cloneNode->roll(Degree(i*31)); - - Light* knotLight = mSceneMgr->createLight(StringUtil::format("KnotLight%d", i)); - SceneNode* ln = rootNode->createChildSceneNode(clonePos + Vector3(0,3,0)); - ln->setDirection(Vector3::NEGATIVE_UNIT_Y); - ln->attachObject(knotLight); - knotLight->setType(Light::LT_SPOTLIGHT); - knotLight->setDiffuseColour(SAMPLE_COLORS[i]); - knotLight->setSpecularColour(ColourValue::White); - knotLight->setSpotlightRange(Degree(25), Degree(45), 1); - knotLight->setAttenuation(6, 1, 0.2, 0); - } - } - - void createObjects(SceneNode* rootNode) - { - // Create ogre heads to decorate the wall - Entity* ogreHead = mSceneMgr->createEntity("Head", "ogrehead.mesh"); - //rootNode->createChildSceneNode( "Head" )->attachObject( ogreHead ); - Vector3 headStartPos[2] = { Vector3(25.25,11,3), Vector3(25.25,11,-3) }; - Vector3 headDiff(-3.7,0,0); - for (int i=0; i < 12; i++) - { - Entity* cloneHead = ogreHead->clone(StringUtil::format("OgreHead%d", i)); - Vector3 clonePos = headStartPos[i%2] + headDiff*(i/2); - if ((i/2) >= 4) clonePos.x -= 0.75; - SceneNode* cloneNode = rootNode->createChildSceneNode(clonePos); - cloneNode->attachObject(cloneHead); - setEntityHeight(cloneHead, 1.5); - if (i % 2 == 0) - { - cloneNode->yaw(Degree(180)); - } - } - - // Create a pile of wood pallets - Entity* woodPallet = mSceneMgr->createEntity("Pallet", "WoodPallet.mesh"); - Vector3 woodStartPos(10, 0.5, -5.5); - Vector3 woodDiff(0, 0.3, 0); - for (int i=0; i < 5; i++) - { - Entity* clonePallet = woodPallet->clone(StringUtil::format("WoodPallet%d", i)); - Vector3 clonePos = woodStartPos + woodDiff*i; - SceneNode* cloneNode = rootNode->createChildSceneNode(clonePos); - cloneNode->attachObject(clonePallet); - setEntityHeight(clonePallet, 0.3); - cloneNode->yaw(Degree(i*20)); - } - - } - - void testCapabilities(const RenderSystemCapabilities* caps) override - { - if (caps->getNumMultiRenderTargets()<2) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Your card does not support at least two simultaneous render targets, so cannot " - "run this demo. Sorry!", - "DeferredShading::testCapabilities"); - } - - requireMaterial("DeferredShading/AmbientLight"); - } - - // Just override the mandatory create scene method - void setupContent(void) override - { - mCameraMan->setTopSpeed(20.0); - mSystem = 0; - - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.15, 0.00, 0.00)); - // Skybox - mSceneMgr->setSkyBox(true, "DeferredDemo/SkyBox", 500); - // Create main, static light - Light* l1 = mSceneMgr->createLight(); - l1->setType(Light::LT_DIRECTIONAL); - l1->setDiffuseColour(0.5f, 0.45f, 0.1f); - l1->setShadowFarClipDistance(250); - l1->setShadowFarDistance(75); - //Turn this on to have the directional light cast shadows - l1->setCastShadows(false); - - auto ln = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - ln->setDirection(Vector3(1, -0.5, -0.2)); - ln->attachObject(l1); - - mCameraNode->setPosition(25, 5, 0); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - mCamera->setFarClipDistance(1000.0); - mCamera->setNearClipDistance(0.5); - setDragLook(true); - - mSystem = new DeferredShadingSystem(mWindow->getViewport(0), mSceneMgr, mCamera); - mSystem->initialize(); - - mMainLight = l1; - - //Create the scene - // Create "root" node - SceneNode* rootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - // Create the cathedral - this will be the static scene - Entity* cathedralEnt = mSceneMgr->createEntity("Cathedral", "sibenik.mesh"); - SceneNode* cathedralNode = rootNode->createChildSceneNode(); - cathedralNode->attachObject(cathedralEnt); - - createAtheneScene(rootNode); - createKnotScene(rootNode); - createObjects(rootNode); - - setupControls(); - } - - void createSampleLights() - { - // Create some lights - std::vector lights; - SceneNode *parentNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("LightsParent"); - // Create light nodes - std::vector nodes; - - Vector4 attParams = Vector4(4,1,0,7); - Real lightRadius = 25; - - Light *a = mSceneMgr->createLight(); - SceneNode *an = parentNode->createChildSceneNode(); - an->attachObject(a); - a->setAttenuation(attParams.x, attParams.y, attParams.z, attParams.w); - //a->setAttenuation(1.0f, 0.000f, 0.000f); - an->setPosition(0,0,lightRadius); - a->setDiffuseColour(1,0,0); - //a->setSpecularColour(0.5,0,0); - lights.push_back(a); - nodes.push_back(an); - - Light *b = mSceneMgr->createLight(); - SceneNode *bn = parentNode->createChildSceneNode(); - bn->attachObject(b); - b->setAttenuation(attParams.x, attParams.y, attParams.z, attParams.w); - bn->setPosition(lightRadius,0,0); - b->setDiffuseColour(1,1,0); - //b->setSpecularColour(0.5,0.5,0); - lights.push_back(b); - nodes.push_back(bn); - - Light *c = mSceneMgr->createLight(); - SceneNode *cn = parentNode->createChildSceneNode(); - cn->attachObject(c); - c->setAttenuation(attParams.x, attParams.y, attParams.z, attParams.w); - cn->setPosition(0,0,-lightRadius); - c->setDiffuseColour(0,1,1); - c->setSpecularColour(0.25,1.0,1.0); // Cyan light has specular component - lights.push_back(c); - nodes.push_back(cn); - - Light *d = mSceneMgr->createLight(); - SceneNode *dn = parentNode->createChildSceneNode(); - dn->attachObject(d); - d->setAttenuation(attParams.x, attParams.y, attParams.z, attParams.w); - dn->setPosition(-lightRadius,0,0); - d->setDiffuseColour(1,0,1); - d->setSpecularColour(0.0,0,0.0); - lights.push_back(d); - nodes.push_back(dn); - - Light *e = mSceneMgr->createLight(); - SceneNode *en = parentNode->createChildSceneNode(); - en->attachObject(e); - e->setAttenuation(attParams.x, attParams.y, attParams.z, attParams.w); - en->setPosition(lightRadius,0,lightRadius); - e->setDiffuseColour(0,0,1); - e->setSpecularColour(0,0,0); - lights.push_back(e); - nodes.push_back(en); - - Light *f = mSceneMgr->createLight(); - SceneNode *fn = parentNode->createChildSceneNode(); - fn->attachObject(f); - f->setAttenuation(attParams.x, attParams.y, attParams.z, attParams.w); - fn->setPosition(-lightRadius,0,-lightRadius); - f->setDiffuseColour(0,1,0); - f->setSpecularColour(0,0.0,0.0); - lights.push_back(f); - nodes.push_back(fn); - - // Create marker meshes to show user where the lights are - Entity *ent; - GeomUtils::createSphere("PointLightMesh", 0.05f, 5, 5, true, true); - for(std::vector::iterator i=lights.begin(); i!=lights.end(); ++i) - { - Light* light = *i; - ent = mSceneMgr->createEntity(light->getName()+"v", "PointLightMesh"); - String matname = light->getName()+"m"; - // Create coloured material - MaterialPtr mat = MaterialManager::getSingleton().create(matname, - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - Pass* pass = mat->getTechnique(0)->getPass(0); - pass->setDiffuse(0.0f,0.0f,0.0f,1.0f); - pass->setAmbient(0.0f,0.0f,0.0f); - pass->setSelfIllumination(light->getDiffuseColour()); - - ent->setMaterialName(matname); - //ent->setRenderQueueGroup(light->getRenderQueueGroup()); - ent->setRenderQueueGroup(DeferredShadingSystem::POST_GBUFFER_RENDER_QUEUE); - static_cast(light->getParentNode())->attachObject(ent); - ent->setVisible(true); - } - - // Do some animation for node a-f - // Generate helix structure - float seconds_per_station = 1.0f; - float r = 1.0; - //Vector3 base(0,-30,0); - Vector3 base(-8.75, 3.5, 0); - - float h=3; - const size_t s_to_top = 16; - const size_t stations = s_to_top*2-1; - float ascend = h/((float)s_to_top); - float stations_per_revolution = 3.5f; - size_t skip = 2; // stations between lights - Vector3 station_pos[stations]; - for(size_t x=0; xcreateAnimation("LightSwarmTrack", stations*seconds_per_station); - // Spline it for nice curves - anim->setInterpolationMode(Animation::IM_SPLINE); - for(unsigned int x=0; xcreateNodeTrack(x, nodes[x]); - for(size_t y=0; y<=stations; ++y) - { - // Setup keyframes - TransformKeyFrame* key = track->createNodeKeyFrame(y*seconds_per_station); // A start position - key->setTranslate(station_pos[(x*skip+y)%stations]); - // Make sure size of light doesn't change - key->setScale(nodes[x]->getScale()); - } - } - // Create a new animation state to track this - auto animState = mSceneMgr->createAnimationState("LightSwarmTrack"); - animState->setEnabled(true); - - auto& controllerMgr = ControllerManager::getSingleton(); - controllerMgr.createFrameTimePassthroughController(AnimationStateControllerValue::create(animState, true)); - - /*Light* spotLight = mSceneMgr->createLight("Spotlight1"); - spotLight->setType(Light::LT_SPOTLIGHT); - spotLight->setAttenuation(200, 1.0f, 0, 0); - spotLight->setSpotlightRange(Degree(30.0), Degree(45.0), 0.8); - spotLight->setPosition(0,120,0); - spotLight->setDirection(0, -1, 0); - spotLight->setDiffuseColour(1,1,1); - spotLight->setSpecularColour(1,1,1);*/ - } -}; - -#endif diff --git a/Samples/DeferredShading/include/GBufferSchemeHandler.h b/Samples/DeferredShading/include/GBufferSchemeHandler.h deleted file mode 100644 index f927cd17230..00000000000 --- a/Samples/DeferredShading/include/GBufferSchemeHandler.h +++ /dev/null @@ -1,36 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - - -#ifndef _GBUFFERSCHEMEHANDLER_H -#define _GBUFFERSCHEMEHANDLER_H - -#include "OgreMaterialManager.h" - -/** Class for handling materials who did not specify techniques for rendering - * themselves into the GBuffer. This class allows deferred shading to be used, - * without having to specify new techniques for all the objects in the scene. - * @note This does not support all the possible rendering techniques out there. - * in order to support more, either expand this class or specify the techniques - * in the materials. - */ -class GBufferSchemeHandler : public Ogre::MaterialManager::Listener -{ -public: - Ogre::Technique* handleSchemeNotFound(unsigned short schemeIndex, - const Ogre::String& schemeName, Ogre::Material* originalMaterial, unsigned short lodIndex, - const Ogre::Renderable* rend) override; -}; - -#endif diff --git a/Samples/DeferredShading/include/GeomUtils.h b/Samples/DeferredShading/include/GeomUtils.h deleted file mode 100644 index 3516741466c..00000000000 --- a/Samples/DeferredShading/include/GeomUtils.h +++ /dev/null @@ -1,61 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#ifndef _GEOMUTILS_H -#define _GEOMUTILS_H - -#include "OgreString.h" -#include "OgreVertexIndexData.h" - -class GeomUtils -{ -public: - // Create a sphere Mesh with a given name, radius, number of rings and number of segments - static void createSphere(const Ogre::String& strName - , float radius - , int nRings, int nSegments - , bool bNormals - , bool bTexCoords - ); - - - // Fill up a fresh copy of VertexData and IndexData with a sphere's coords given the number of rings and the number of segments - static void createSphere(Ogre::VertexData*& vertexData, Ogre::IndexData*& indexData - , float radius - , int nRings, int nSegments - , bool bNormals - , bool bTexCoords); - - // Create a cone Mesh with a given name, radius and number of vertices in base - // Created cone will have its head at 0,0,0, and will 'expand to' positive y - static void createCone(const Ogre::String& strName - , float radius - , float height - , int nVerticesInBase); - - // Fill up a fresh copy of VertexData and IndexData with a cone's coords given the radius and number of vertices in base - static void createCone(Ogre::VertexData*& vertexData, Ogre::IndexData*& indexData - , float radius - , float height - , int nVerticesInBase); - - - // Fill up a fresh copy of VertexData with a normalized quad - static void createQuad(Ogre::VertexData*& vertexData); - - -}; - - -#endif diff --git a/Samples/DeferredShading/include/LightMaterialGenerator.h b/Samples/DeferredShading/include/LightMaterialGenerator.h deleted file mode 100755 index 28dc32ff0df..00000000000 --- a/Samples/DeferredShading/include/LightMaterialGenerator.h +++ /dev/null @@ -1,40 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#ifndef H_WJ_LightMaterialGenerator -#define H_WJ_LightMaterialGenerator - -#include "MaterialGenerator.h" - -class LightMaterialGenerator: public MaterialGenerator -{ -public: - /** Permutation of light materials - */ - enum MaterialID - { - MI_POINT = 0x01, // Is a point light - MI_SPOTLIGHT = 0x02, // Is a spot light - MI_DIRECTIONAL = 0x04, // Is a directional light - - MI_ATTENUATED = 0x08, // Rendered attenuated - MI_SPECULAR = 0x10, // Specular component is calculated - MI_SHADOW_CASTER = 0x20 // Will cast shadows - }; - - LightMaterialGenerator(); - virtual ~LightMaterialGenerator(); -}; - -#endif diff --git a/Samples/DeferredShading/include/MaterialGenerator.h b/Samples/DeferredShading/include/MaterialGenerator.h deleted file mode 100755 index 89604e8540e..00000000000 --- a/Samples/DeferredShading/include/MaterialGenerator.h +++ /dev/null @@ -1,82 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#ifndef H_WJ_MaterialGenerator -#define H_WJ_MaterialGenerator - -#include "OgreMaterial.h" -#include "OgreStringVector.h" - -/** Caching, on-the-fly material generator. This is a class that automatically - generates and stores different permutations of a material, and its shaders. - It can be used if you have a material that has lots of slightly different - variations, like whether to use a specular light, skinning, normal mapping - and other options. Writing all these out is a tedious job. Of course it is - possible to always use the material with all features, but that might result - in large, slow shader programs. This class provides an efficient solution - to that. - */ -class MaterialGenerator -{ -public: - /** Bitfield used to signify a material permutations */ - typedef Ogre::uint32 Perm; - virtual ~MaterialGenerator(); - - const Ogre::MaterialPtr &getMaterial(Perm permutation); - - /** Implementation class that takes care of actual generation or lookup - of the various constituent parts (template material, fragment shader - and vertex shader). These methods are only called once for every permutation, - after which the result is stored and re-used. - */ - class Impl - { - public: - virtual ~Impl(); - virtual Ogre::GpuProgramPtr generateVertexShader(Perm permutation) = 0; - virtual Ogre::GpuProgramPtr generateFragmentShader(Perm permutation) = 0; - virtual Ogre::MaterialPtr generateTemplateMaterial(Perm permutation) = 0; - }; -protected: - /** The constructor is protected as this base class should never be constructed - as-is. It is meant to be subclassed so that values can be assigned to - the various fields controlling material generator, and most importantly, the - mImpl field. - */ - MaterialGenerator(); - - const Ogre::GpuProgramPtr &getVertexShader(Perm permutation); - const Ogre::GpuProgramPtr &getFragmentShader(Perm permutation); - const Ogre::MaterialPtr &getTemplateMaterial(Perm permutation); - - /// Base name of materials generated by this - Ogre::String materialBaseName; - /// Mask of permutation bits that influence vertex shader choice - Perm vsMask; - /// Mask of permutation bits that influence fragment shader choice - Perm fsMask; - /// Mask of permutation bits that influence template material choice - Perm matMask; - /// Generator - Impl *mImpl; - - typedef std::map ProgramMap; - typedef std::map MaterialMap; - - ProgramMap mVs, mFs; - MaterialMap mTemplateMat, mMaterials; -}; - -#endif diff --git a/Samples/DeferredShading/include/SSAOLogic.h b/Samples/DeferredShading/include/SSAOLogic.h deleted file mode 100644 index dc00d81721f..00000000000 --- a/Samples/DeferredShading/include/SSAOLogic.h +++ /dev/null @@ -1,27 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#ifndef _SSAOLOGIC_H -#define _SSAOLOGIC_H - -#include "ListenerFactoryLogic.h" - -class SSAOLogic : public ListenerFactoryLogic -{ -protected: - /** @copydoc ListenerFactoryLogic::createListener */ - Ogre::CompositorInstance::Listener* createListener(Ogre::CompositorInstance* instance) override; -}; - -#endif diff --git a/Samples/DeferredShading/src/AmbientLight.cpp b/Samples/DeferredShading/src/AmbientLight.cpp deleted file mode 100644 index f4c34b5f0c2..00000000000 --- a/Samples/DeferredShading/src/AmbientLight.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - - -#include "AmbientLight.h" -#include "GeomUtils.h" -#include "OgreMaterialManager.h" -#include "OgreCamera.h" -#include "OgreRoot.h" -#include "OgreRenderSystem.h" -#include "OgreTechnique.h" - -using namespace Ogre; - -AmbientLight::AmbientLight() -{ - setRenderQueueGroup(RENDER_QUEUE_2); - - mRenderOp.vertexData = new VertexData(); - mRenderOp.indexData = 0; - - GeomUtils::createQuad(mRenderOp.vertexData); - - mRenderOp.operationType = RenderOperation::OT_TRIANGLE_STRIP; - mRenderOp.useIndexes = false; - - // Set bounding - setBoundingBox(AxisAlignedBox(-10000,-10000,-10000,10000,10000,10000)); - mRadius = 15000; - - mMatPtr = MaterialManager::getSingleton().getByName("DeferredShading/AmbientLight"); - assert(mMatPtr); - mMatPtr->load(); -} - -AmbientLight::~AmbientLight() -{ - // need to release IndexData and vertexData created for renderable - delete mRenderOp.indexData; - delete mRenderOp.vertexData; -} - -/** @copydoc MovableObject::getBoundingRadius */ -Real AmbientLight::getBoundingRadius(void) const -{ - return mRadius; - -} -/** @copydoc Renderable::getSquaredViewDepth */ -Real AmbientLight::getSquaredViewDepth(const Camera*) const -{ - return 0.0; -} - -const MaterialPtr& AmbientLight::getMaterial(void) const -{ - return mMatPtr; -} - -void AmbientLight::getWorldTransforms(Ogre::Matrix4* xform) const -{ - *xform = Matrix4::IDENTITY; -} -void AmbientLight::updateFromCamera(Ogre::Camera* camera) -{ - Ogre::Technique* tech = getMaterial()->getBestTechnique(); - Ogre::Vector3 farCorner = camera->getViewMatrix(true) * camera->getWorldSpaceCorners()[4]; - - for (unsigned short i=0; igetNumPasses(); i++) - { - Ogre::Pass* pass = tech->getPass(i); - // get the vertex shader parameters - Ogre::GpuProgramParametersSharedPtr params = pass->getVertexProgramParameters(); - // set the camera's far-top-right corner - if (params->_findNamedConstantDefinition("farCorner")) - params->setNamedConstant("farCorner", farCorner); - - params = pass->getFragmentProgramParameters(); - if (params->_findNamedConstantDefinition("farCorner")) - params->setNamedConstant("farCorner", farCorner); - } -} diff --git a/Samples/DeferredShading/src/DLight.cpp b/Samples/DeferredShading/src/DLight.cpp deleted file mode 100644 index 026516d7390..00000000000 --- a/Samples/DeferredShading/src/DLight.cpp +++ /dev/null @@ -1,357 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#include "DLight.h" - -#include - -#include "OgreHardwareBufferManager.h" -#include "OgreCamera.h" -#include "OgreSceneNode.h" -#include "OgreLight.h" -#include "GeomUtils.h" -#include "LightMaterialGenerator.h" -#include "OgreTechnique.h" -#include "OgreSceneManager.h" -#include "OgreShadowCameraSetup.h" - -#define ENABLE_BIT(mask, flag) (mask) |= (flag) -#define DISABLE_BIT(mask, flag) (mask) &= ~(flag) - -using namespace Ogre; -//----------------------------------------------------------------------- -DLight::DLight(MaterialGenerator *sys, Ogre::Light* parentLight): - mParentLight(parentLight), bIgnoreWorld(false), mGenerator(sys), mPermutation(0) -{ - // Set up geometry - // Allocate render operation - mRenderOp.operationType = RenderOperation::OT_TRIANGLE_LIST; - mRenderOp.indexData = 0; - mRenderOp.vertexData = 0; - mRenderOp.useIndexes = true; - - updateFromParent(); -} -//----------------------------------------------------------------------- -DLight::~DLight() -{ - // need to release IndexData and vertexData created for renderable - delete mRenderOp.indexData; - delete mRenderOp.vertexData; -} -//----------------------------------------------------------------------- -void DLight::setAttenuation(float c, float b, float a) -{ - // Set Attenuation parameter to shader - //setCustomParameter(3, Vector4(c, b, a, 0)); - float outerRadius = mParentLight->getAttenuationRange(); - /// There is attenuation? Set material accordingly - if(c != 1.0f || b != 0.0f || a != 0.0f) - { - ENABLE_BIT(mPermutation, LightMaterialGenerator::MI_ATTENUATED); - if (mParentLight->getType() == Light::LT_POINT) - { - //// Calculate radius from Attenuation - int threshold_level = 10;// difference of 10-15 levels deemed unnoticeable - float threshold = 1.0f/((float)threshold_level/256.0f); - - //// Use quadratic formula to determine outer radius - c = c-threshold; - float d=std::sqrt(b*b-4*a*c); - outerRadius = (-2*c)/(b+d); - outerRadius *= 1.2; - } - } - else - { - DISABLE_BIT(mPermutation,LightMaterialGenerator::MI_ATTENUATED); - } - - rebuildGeometry(outerRadius); -} -//----------------------------------------------------------------------- -void DLight::setSpecularColour(const ColourValue &col) -{ - //setCustomParameter(2, Vector4(col.r, col.g, col.b, col.a)); - /// There is a specular component? Set material accordingly - - if(col.r != 0.0f || col.g != 0.0f || col.b != 0.0f) - ENABLE_BIT(mPermutation,LightMaterialGenerator::MI_SPECULAR); - else - DISABLE_BIT(mPermutation,LightMaterialGenerator::MI_SPECULAR); - -} -//----------------------------------------------------------------------- -void DLight::rebuildGeometry(float radius) -{ - //Disable all 3 bits - DISABLE_BIT(mPermutation, LightMaterialGenerator::MI_POINT); - DISABLE_BIT(mPermutation, LightMaterialGenerator::MI_SPOTLIGHT); - DISABLE_BIT(mPermutation, LightMaterialGenerator::MI_DIRECTIONAL); - - switch (mParentLight->getType()) - { - case Light::LT_DIRECTIONAL: - createRectangle2D(); - ENABLE_BIT(mPermutation,LightMaterialGenerator::MI_DIRECTIONAL); - break; - case Light::LT_POINT: - /// XXX some more intelligent expression for rings and segments - createSphere(radius, 10, 10); - ENABLE_BIT(mPermutation,LightMaterialGenerator::MI_POINT); - break; - case Light::LT_RECTLIGHT: - case Light::LT_SPOTLIGHT: - Real height = mParentLight->getAttenuationRange(); - Radian coneRadiusAngle = mParentLight->getSpotlightOuterAngle() / 2; - Real rad = Math::Tan(coneRadiusAngle) * height; - createCone(rad, height, 20); - ENABLE_BIT(mPermutation,LightMaterialGenerator::MI_SPOTLIGHT); - break; - } -} -//----------------------------------------------------------------------- -void DLight::createRectangle2D() -{ - /// XXX this RenderOp should really be re-used between DLight objects, - /// not generated every time - delete mRenderOp.vertexData; - delete mRenderOp.indexData; - - mRenderOp.vertexData = new VertexData(); - mRenderOp.indexData = 0; - - GeomUtils::createQuad(mRenderOp.vertexData); - - mRenderOp.operationType = RenderOperation::OT_TRIANGLE_STRIP; - mRenderOp.useIndexes = false; - - // Set bounding - setBoundingBox(AxisAlignedBox(-10000,-10000,-10000,10000,10000,10000)); - mRadius = 15000; - bIgnoreWorld = true; -} -//----------------------------------------------------------------------- -void DLight::createSphere(float radius, int nRings, int nSegments) -{ - delete mRenderOp.vertexData; - delete mRenderOp.indexData; - mRenderOp.operationType = RenderOperation::OT_TRIANGLE_LIST; - mRenderOp.indexData = new IndexData(); - mRenderOp.vertexData = new VertexData(); - mRenderOp.useIndexes = true; - - GeomUtils::createSphere(mRenderOp.vertexData, mRenderOp.indexData - , radius - , nRings, nSegments - , false // no normals - , false // no texture coordinates - ); - - // Set bounding box and sphere - setBoundingBox( AxisAlignedBox( Vector3(-radius, -radius, -radius), Vector3(radius, radius, radius) ) ); - mRadius = radius; - bIgnoreWorld = false; -} -//----------------------------------------------------------------------- -void DLight::createCone(float radius, float height, int nVerticesInBase) -{ - delete mRenderOp.vertexData; - delete mRenderOp.indexData; - mRenderOp.operationType = RenderOperation::OT_TRIANGLE_LIST; - mRenderOp.indexData = new IndexData(); - mRenderOp.vertexData = new VertexData(); - mRenderOp.useIndexes = true; - - GeomUtils::createCone(mRenderOp.vertexData, mRenderOp.indexData - , radius - , height, nVerticesInBase); - - // Set bounding box and sphere - setBoundingBox( AxisAlignedBox( - Vector3(-radius, 0, -radius), - Vector3(radius, height, radius) ) ); - - mRadius = radius; - bIgnoreWorld = false; -} -//----------------------------------------------------------------------- -Real DLight::getBoundingRadius(void) const -{ - return mRadius; -} -//----------------------------------------------------------------------- -Real DLight::getSquaredViewDepth(const Camera* cam) const -{ - if(bIgnoreWorld) - { - return 0.0f; - } - else - { - Vector3 dist = cam->getDerivedPosition() - getParentSceneNode()->_getDerivedPosition(); - return dist.squaredLength(); - } -} -//----------------------------------------------------------------------- -const MaterialPtr& DLight::getMaterial(void) const -{ - return mGenerator->getMaterial(mPermutation); -} -//----------------------------------------------------------------------- -void DLight::getWorldTransforms(Matrix4* xform) const -{ - if (mParentLight->getType() == Light::LT_SPOTLIGHT) - { - Quaternion quat = Vector3::UNIT_Y.getRotationTo(mParentLight->getDerivedDirection()); - xform->makeTransform(mParentLight->getDerivedPosition(), - Vector3::UNIT_SCALE, quat); - } - else - { - xform->makeTransform(mParentLight->getDerivedPosition(), - Vector3::UNIT_SCALE, Quaternion::IDENTITY); - } - -} -//----------------------------------------------------------------------- -void DLight::updateFromParent() -{ - //TODO : Don't do this unless something changed - setAttenuation(mParentLight->getAttenuationConstant(), - mParentLight->getAttenuationLinear(), mParentLight->getAttenuationQuadric()); - setSpecularColour(mParentLight->getSpecularColour()); - - if (getCastChadows()) - { - ENABLE_BIT(mPermutation,LightMaterialGenerator::MI_SHADOW_CASTER); - } - else - { - DISABLE_BIT(mPermutation, LightMaterialGenerator::MI_SHADOW_CASTER); - } -} -//----------------------------------------------------------------------- -bool DLight::isCameraInsideLight(Ogre::Camera* camera) -{ - switch (mParentLight->getType()) - { - case Ogre::Light::LT_DIRECTIONAL: - return false; - case Ogre::Light::LT_POINT: - { - Ogre::Real distanceFromLight = camera->getDerivedPosition() - .distance(mParentLight->getDerivedPosition()); - //Small epsilon fix to account for the fact that we aren't a true sphere. - return distanceFromLight <= mRadius + camera->getNearClipDistance() + 0.1; - } - case Ogre::Light::LT_SPOTLIGHT: - { - Ogre::Vector3 lightPos = mParentLight->getDerivedPosition(); - Ogre::Vector3 lightDir = mParentLight->getDerivedDirection(); - Ogre::Radian attAngle = mParentLight->getSpotlightOuterAngle(); - - //Extend the analytic cone's radius by the near clip range by moving its tip accordingly. - //Some trigonometry needed here. - Ogre::Vector3 clipRangeFix = -lightDir * (camera->getNearClipDistance() / Ogre::Math::Tan(attAngle/2)); - lightPos = lightPos + clipRangeFix; - - Ogre::Vector3 lightToCamDir = camera->getDerivedPosition() - lightPos; - Ogre::Real distanceFromLight = lightToCamDir.normalise(); - - Ogre::Real cosAngle = lightToCamDir.dotProduct(lightDir); - Ogre::Radian angle = Ogre::Math::ACos(cosAngle); - //Check whether we will see the cone from our current POV. - return (distanceFromLight <= (mParentLight->getAttenuationRange() / cosAngle + clipRangeFix.length())) - && (angle <= attAngle); - } - default: - //Please the compiler - return false; - } -} -//----------------------------------------------------------------------- -bool DLight::getCastChadows() const -{ - return - mParentLight->_getManager()->isShadowTechniqueInUse() && - mParentLight->getCastShadows() && - (mParentLight->getType() == Light::LT_DIRECTIONAL || mParentLight->getType() == Light::LT_SPOTLIGHT); -} -//----------------------------------------------------------------------- -void DLight::updateFromCamera(Ogre::Camera* camera) -{ - //Set shader params - const Ogre::MaterialPtr& mat = getMaterial(); - if (!mat->isLoaded()) - { - mat->load(); - } - Ogre::Technique* tech = mat->getBestTechnique(); - Ogre::Vector3 farCorner = camera->getViewMatrix(true) * camera->getWorldSpaceCorners()[4]; - - for (unsigned short i=0; igetNumPasses(); i++) - { - Ogre::Pass* pass = tech->getPass(i); - // get the vertex shader parameters - Ogre::GpuProgramParametersSharedPtr params = pass->getVertexProgramParameters(); - // set the camera's far-top-right corner - if (params->_findNamedConstantDefinition("farCorner")) - params->setNamedConstant("farCorner", farCorner); - - params = pass->getFragmentProgramParameters(); - if (params->_findNamedConstantDefinition("farCorner")) - params->setNamedConstant("farCorner", farCorner); - - //If inside light geometry, render back faces with CMPF_GREATER, otherwise normally - if (mParentLight->getType() == Ogre::Light::LT_DIRECTIONAL) - { - pass->setCullingMode(Ogre::CULL_CLOCKWISE); - pass->setDepthCheckEnabled(false); - } - else - { - pass->setDepthCheckEnabled(true); - if (isCameraInsideLight(camera)) - { - pass->setCullingMode(Ogre::CULL_ANTICLOCKWISE); - pass->setDepthFunction(Ogre::CMPF_GREATER_EQUAL); - } - else - { - pass->setCullingMode(Ogre::CULL_CLOCKWISE); - pass->setDepthFunction(Ogre::CMPF_LESS_EQUAL); - } - } - - SceneNode dummyNode(NULL); - Camera shadowCam("ShadowCameraSetupCam", 0); - dummyNode.attachObject(&shadowCam); - shadowCam._notifyViewport(camera->getViewport()); - SceneManager* sm = mParentLight->_getManager(); - sm->getShadowCameraSetup()->getShadowCamera(sm, - camera, camera->getViewport(), mParentLight, &shadowCam, 0); - - //Get the shadow camera position - if (params->_findNamedConstantDefinition("shadowCamPos")) - { - params->setNamedConstant("shadowCamPos", shadowCam.getDerivedPosition()); - } - if (params->_findNamedConstantDefinition("shadowFarClip")) - { - params->setNamedConstant("shadowFarClip", shadowCam.getFarClipDistance()); - } - - } -} diff --git a/Samples/DeferredShading/src/DeferredLightCP.cpp b/Samples/DeferredShading/src/DeferredLightCP.cpp deleted file mode 100644 index 56ab56ea95d..00000000000 --- a/Samples/DeferredShading/src/DeferredLightCP.cpp +++ /dev/null @@ -1,135 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#include "DeferredLightCP.h" - -#include "Ogre.h" -using namespace Ogre; - -#include "LightMaterialGenerator.h" - -//----------------------------------------------------------------------- -DeferredLightRenderOperation::DeferredLightRenderOperation( - CompositorInstance* instance, const CompositionPass* pass) -{ - mViewport = instance->getChain()->getViewport(); - - //Get the names of the GBuffer textures - const CompositionPass::InputTex& input0 = pass->getInput(0); - mTexName0 = instance->getTextureInstanceName(input0.name, input0.mrtIndex); - const CompositionPass::InputTex& input1 = pass->getInput(1); - mTexName1 = instance->getTextureInstanceName(input1.name, input1.mrtIndex); - - // Create lights material generator - mLightMaterialGenerator = new LightMaterialGenerator(); - - // Create the ambient light - mAmbientLight = new AmbientLight(); - const MaterialPtr& mat = mAmbientLight->getMaterial(); - mat->load(); -} -//----------------------------------------------------------------------- -DLight* DeferredLightRenderOperation::createDLight(Ogre::Light* light) -{ - DLight *rv = new DLight(mLightMaterialGenerator,light); - mLights[light] = rv; - return rv; -} -//----------------------------------------------------------------------- -static void injectTechnique(SceneManager* sm, Technique* tech, Renderable* rend, const Ogre::LightList* lightList) -{ - for(unsigned short i=0; igetNumPasses(); ++i) - { - Ogre::Pass* pass = tech->getPass(i); - if (lightList != 0) - { - sm->_injectRenderWithPass(pass, rend, false, false, lightList); - } - else - { - sm->_injectRenderWithPass(pass, rend, false); - } - - } -} -//! [execute] -void DeferredLightRenderOperation::execute(SceneManager *sm, RenderSystem *rs) -{ - Ogre::Camera* cam = mViewport->getCamera(); - - mAmbientLight->updateFromCamera(cam); - Technique* tech = mAmbientLight->getMaterial()->getBestTechnique(); - injectTechnique(sm, tech, mAmbientLight, 0); - - const LightList& lightList = sm->_getLightsAffectingFrustum(); - for (LightList::const_iterator it = lightList.begin(); it != lightList.end(); it++) - { - Light* light = *it; - Ogre::LightList ll; - ll.push_back(light); - - //if (++i != 2) continue; - //if (light->getType() != Light::LT_DIRECTIONAL) continue; - //if (light->getDiffuseColour() != ColourValue::Red) continue; - - LightsMap::iterator dLightIt = mLights.find(light); - DLight* dLight = 0; - if (dLightIt == mLights.end()) - { - dLight = createDLight(light); - } - else - { - dLight = dLightIt->second; - dLight->updateFromParent(); - } - dLight->updateFromCamera(cam); - tech = dLight->getMaterial()->getBestTechnique(); - - //Update shadow texture - if (dLight->getCastChadows()) - { - SceneManager::RenderContext* context = sm->_pauseRendering(); - - sm->prepareShadowTextures(cam, mViewport, &ll); - sm->_resumeRendering(context); - - Pass* pass = tech->getPass(0); - TextureUnitState* tus = pass->getTextureUnitState("ShadowMap"); - assert(tus); - const TexturePtr& shadowTex = sm->getShadowTexture(0); - if (tus->_getTexturePtr() != shadowTex) - { - tus->_setTexturePtr(shadowTex); - } - - } - - injectTechnique(sm, tech, dLight, &ll); - } -} -//! [execute] -//----------------------------------------------------------------------- -DeferredLightRenderOperation::~DeferredLightRenderOperation() -{ - for (LightsMap::iterator it = mLights.begin(); it != mLights.end(); ++it) - { - delete it->second; - } - mLights.clear(); - - delete mAmbientLight; - delete mLightMaterialGenerator; -} -//----------------------------------------------------------------------- diff --git a/Samples/DeferredShading/src/DeferredShading.cpp b/Samples/DeferredShading/src/DeferredShading.cpp deleted file mode 100644 index 97dabef4702..00000000000 --- a/Samples/DeferredShading/src/DeferredShading.cpp +++ /dev/null @@ -1,215 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#include "DeferredShading.h" - -#include "OgreConfigFile.h" -#include "OgreStringConverter.h" -#include "OgreException.h" - -#include "OgreRoot.h" -#include "OgreRenderSystem.h" - -#include "OgreEntity.h" -#include "OgreSubEntity.h" -#include "OgreRoot.h" - -#include "OgreCompositor.h" -#include "OgreCompositorManager.h" -#include "OgreCompositorChain.h" -#include "OgreCompositorInstance.h" - -#include "OgreLogManager.h" - -#include "DeferredLightCP.h" -#include "SSAOLogic.h" -#include "GBufferSchemeHandler.h" - -using namespace Ogre; - -const Ogre::uint8 DeferredShadingSystem::POST_GBUFFER_RENDER_QUEUE = Ogre::RENDER_QUEUE_TRANSPARENTS; - -DeferredShadingSystem::DeferredShadingSystem( - Viewport *vp, SceneManager *sm, Camera *cam - ): - mViewport(vp), mSceneMgr(sm), mCamera(cam) -{ - sm->setShadowTechnique(SHADOWTYPE_TEXTURE_ADDITIVE); - sm->setShadowTextureCasterMaterial( - MaterialManager::getSingleton().getByName("DeferredShading/Shadows/Caster", "General")); - mSceneMgr->setShadowTextureCount(1); - mSceneMgr->setShadowFarDistance(150); - //Use a value of "2" to use a different depth buffer pool and avoid sharing this with the Backbuffer's - mSceneMgr->setShadowTextureConfig( 0, 512, 512, PF_FLOAT16_R, 0, 2 ); - mSceneMgr->setShadowDirectionalLightExtrusionDistance(75); -} - -void DeferredShadingSystem::initialize() -{ - for(auto & i : mInstance) - i=0; - - createResources(); - - mActive = false; - - mSSAO = false; - mCurrentMode = DSM_SHOWLIT; - setActive(true); -} - -DeferredShadingSystem::~DeferredShadingSystem() -{ - CompositorChain *chain = CompositorManager::getSingleton().getCompositorChain(mViewport); - for(auto & i : mInstance) - chain->_removeInstance(i); - CompositorManager::getSingleton().removeCompositorChain(mViewport); - - Ogre::CompositorManager& compMgr = Ogre::CompositorManager::getSingleton(); - CompositorLogicMap::const_iterator itor = mCompositorLogics.begin(); - CompositorLogicMap::const_iterator end = mCompositorLogics.end(); - while( itor != end ) - { - compMgr.unregisterCompositorLogic( itor->first ); - delete itor->second; - ++itor; - } - mCompositorLogics.clear(); -} - -void DeferredShadingSystem::setMode(DSMode mode) -{ - assert( 0 <= mode && mode < DSM_COUNT); - - // prevent duplicate setups - if (mCurrentMode == mode && mInstance[mode]->getEnabled()==mActive) - return; - - for(int i=0; isetEnabled(mActive); - } - else - { - mInstance[i]->setEnabled(false); - } - } - - mCurrentMode = mode; - - mSSAOInstance->setEnabled(mActive && mSSAO && mCurrentMode == DSM_SHOWLIT); -} - -void DeferredShadingSystem::setSSAO(bool ssao) -{ - if (ssao != mSSAO) - { - mSSAO = ssao; - if (mActive && mCurrentMode == DSM_SHOWLIT) - { - mSSAOInstance->setEnabled(ssao); - } - } -} - -bool DeferredShadingSystem::getSSAO() const -{ - return mSSAO; -} -void DeferredShadingSystem::setActive(bool active) -{ - if (mActive != active) - { - mActive = active; - mGBufferInstance->setEnabled(active); - - RTShader::ShaderGenerator& rtShaderGen = RTShader::ShaderGenerator::getSingleton(); - // we do lights ourselves if active - rtShaderGen.getRenderState(MSN_SHADERGEN)->setLightCountAutoUpdate(!mActive); - - // mCurrentMode could have changed with a prior call to setMode, so iterate all - setMode(mCurrentMode); - } -} - -DeferredShadingSystem::DSMode DeferredShadingSystem::getMode(void) const -{ - return mCurrentMode; -} - -void DeferredShadingSystem::createResources(void) -{ - CompositorManager &compMan = CompositorManager::getSingleton(); - - RTShader::ShaderGenerator& rtShaderGen = RTShader::ShaderGenerator::getSingleton(); - - //Hook up the compositor logic and scheme handlers. - //This can theoretically happen in a loaded plugin, but in this case the demo contains the code. - static bool firstTime = true; - if (firstTime) - { - MaterialManager::getSingleton().addListener(new GBufferSchemeHandler, "GBuffer"); - - compMan.registerCustomCompositionPass("DeferredLight", new DeferredLightCompositionPass); - - rtShaderGen.createScheme("GBuffer"); - - firstTime = false; - } - - - RTShader::RenderState* schemRenderState = rtShaderGen.getRenderState("GBuffer"); - schemRenderState->setLightCountAutoUpdate(false); // does not use lights - auto subRenderState = rtShaderGen.createSubRenderState(RTShader::SRS_GBUFFER); - subRenderState->setParameter("target_buffers", StringVector{"diffuse_specular", "normal_viewdepth"}); - schemRenderState->addTemplateSubRenderState(subRenderState); - - mCompositorLogics["SSAOLogic"] = new SSAOLogic; - compMan.registerCompositorLogic("SSAOLogic", mCompositorLogics["SSAOLogic"]); - - // Create the main GBuffer compositor - mGBufferInstance = compMan.addCompositor(mViewport, "DeferredShading/GBuffer"); - - if(!GpuProgramManager::getSingleton().isSyntaxSupported("hlsl")) - { - // need to clear depth to 1.0 for GL - mGBufferInstance->getTechnique()->getTargetPass(0)->getPass(0)->setClearColour(ColourValue(0.0, 0.0, 0.0, 1.0)); - } - - // Create filters - mInstance[DSM_SHOWLIT] = compMan.addCompositor(mViewport, "DeferredShading/ShowLit"); - mInstance[DSM_SHOWNORMALS] = compMan.addCompositor(mViewport, "DeferredShading/ShowNormals"); - mInstance[DSM_SHOWDSP] = compMan.addCompositor(mViewport, "DeferredShading/ShowDepthSpecular"); - mInstance[DSM_SHOWCOLOUR] = compMan.addCompositor(mViewport, "DeferredShading/ShowColour"); - - mSSAOInstance = compMan.addCompositor(mViewport, "DeferredShading/SSAO"); -} - - -void DeferredShadingSystem::logCurrentMode(void) -{ - if (mActive==false) - { - LogManager::getSingleton().logMessage("No Compositor Enabled!"); - return; - } - - CompositorInstance* ci = mInstance[mCurrentMode]; - assert(ci->getEnabled()==true); - - LogManager::getSingleton().logMessage("Current Mode: "); - LogManager::getSingleton().logMessage(ci->getCompositor()->getName()); -} diff --git a/Samples/DeferredShading/src/GBufferSchemeHandler.cpp b/Samples/DeferredShading/src/GBufferSchemeHandler.cpp deleted file mode 100644 index e4c433e5209..00000000000 --- a/Samples/DeferredShading/src/GBufferSchemeHandler.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#include "GBufferSchemeHandler.h" - -#include "OgreMaterialManager.h" -#include "OgreTechnique.h" -#include "OgreRTShaderSystem.h" - -using namespace Ogre; - -//! [schemenotfound] -Technique* GBufferSchemeHandler::handleSchemeNotFound(unsigned short schemeIndex, - const String& schemeName, Material* originalMaterial, unsigned short lodIndex, - const Renderable* rend) -{ - Ogre::MaterialManager& matMgr = Ogre::MaterialManager::getSingleton(); - String curSchemeName = matMgr.getActiveScheme(); - matMgr.setActiveScheme(MSN_DEFAULT); - Technique* originalTechnique = originalMaterial->getBestTechnique(lodIndex, rend); - matMgr.setActiveScheme(curSchemeName); - - RTShader::ShaderGenerator& rtShaderGen = RTShader::ShaderGenerator::getSingleton(); - rtShaderGen.createShaderBasedTechnique(originalTechnique, "GBuffer"); - - for (unsigned short i=0; igetNumPasses(); i++) - { - rtShaderGen.validateMaterial("GBuffer", *originalMaterial); - // Grab the generated technique. - for(Technique* curTech : originalMaterial->getTechniques()) - { - if (curTech->getSchemeName() == schemeName) - { - return curTech; - } - } - } - - return NULL; -} -//! [schemenotfound] \ No newline at end of file diff --git a/Samples/DeferredShading/src/GeomUtils.cpp b/Samples/DeferredShading/src/GeomUtils.cpp deleted file mode 100644 index 692074101fa..00000000000 --- a/Samples/DeferredShading/src/GeomUtils.cpp +++ /dev/null @@ -1,251 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - - -#include "GeomUtils.h" - -#include "OgreMeshManager.h" -#include "OgreSubMesh.h" -#include "OgreHardwareBufferManager.h" -#include "OgreMesh.h" - -using namespace Ogre; - -void GeomUtils::createSphere( const String& strName - , float radius - , int nRings, int nSegments - , bool bNormals - , bool bTexCoords) -{ - MeshPtr pSphere = MeshManager::getSingleton().createManual(strName, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - SubMesh *pSphereVertex = pSphere->createSubMesh(); - pSphere->createVertexData(); - - createSphere(pSphere->sharedVertexData, pSphereVertex->indexData - , radius - , nRings, nSegments - , bNormals // need normals - , bTexCoords // need texture co-ordinates - ); - - // Generate face list - pSphereVertex->useSharedVertices = true; - - // the original code was missing this line: - pSphere->_setBounds( AxisAlignedBox( Vector3(-radius, -radius, -radius), Vector3(radius, radius, radius) ), false ); - pSphere->_setBoundingSphereRadius(radius); - // this line makes clear the mesh is loaded (avoids memory leaks) - pSphere->load(); -} - -void GeomUtils::createSphere(VertexData*& vertexData, IndexData*& indexData - , float radius - , int nRings, int nSegments - , bool bNormals - , bool bTexCoords) -{ - assert(vertexData && indexData); - - // define the vertex format - VertexDeclaration* vertexDecl = vertexData->vertexDeclaration; - size_t currOffset = 0; - // positions - currOffset += vertexDecl->addElement(0, currOffset, VET_FLOAT3, VES_POSITION).getSize(); - - if (bNormals) - { - // normals - currOffset += vertexDecl->addElement(0, currOffset, VET_FLOAT3, VES_NORMAL).getSize(); - } - // two dimensional texture coordinates - if (bTexCoords) - { - vertexDecl->addElement(0, currOffset, VET_FLOAT2, VES_TEXTURE_COORDINATES, 0); - } - - // allocate the vertex buffer - vertexData->vertexCount = (nRings + 1) * (nSegments+1); - HardwareVertexBufferSharedPtr vBuf = HardwareBufferManager::getSingleton().createVertexBuffer(vertexDecl->getVertexSize(0), vertexData->vertexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY, false); - VertexBufferBinding* binding = vertexData->vertexBufferBinding; - binding->setBinding(0, vBuf); - float* pVertex = static_cast(vBuf->lock(HardwareBuffer::HBL_DISCARD)); - - // allocate index buffer - indexData->indexCount = 6 * nRings * (nSegments + 1); - indexData->indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer(HardwareIndexBuffer::IT_16BIT, indexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY, false); - HardwareIndexBufferSharedPtr iBuf = indexData->indexBuffer; - unsigned short* pIndices = static_cast(iBuf->lock(HardwareBuffer::HBL_DISCARD)); - - float fDeltaRingAngle = (Math::PI / nRings); - float fDeltaSegAngle = (2 * Math::PI / nSegments); - unsigned short wVerticeIndex = 0 ; - - // Generate the group of rings for the sphere - for( int ring = 0; ring <= nRings; ring++ ) { - float r0 = radius * sinf (ring * fDeltaRingAngle); - float y0 = radius * cosf (ring * fDeltaRingAngle); - - // Generate the group of segments for the current ring - for(int seg = 0; seg <= nSegments; seg++) { - float x0 = r0 * sinf(seg * fDeltaSegAngle); - float z0 = r0 * cosf(seg * fDeltaSegAngle); - - // Add one vertex to the strip which makes up the sphere - *pVertex++ = x0; - *pVertex++ = y0; - *pVertex++ = z0; - - if (bNormals) - { - Vector3 vNormal = Vector3(x0, y0, z0).normalisedCopy(); - *pVertex++ = vNormal.x; - *pVertex++ = vNormal.y; - *pVertex++ = vNormal.z; - } - if (bTexCoords) - { - *pVertex++ = (float) seg / (float) nSegments; - *pVertex++ = (float) ring / (float) nRings; - } - - if (ring != nRings) - { - // each vertex (except the last) has six indices pointing to it - *pIndices++ = wVerticeIndex + nSegments + 1; - *pIndices++ = wVerticeIndex; - *pIndices++ = wVerticeIndex + nSegments; - *pIndices++ = wVerticeIndex + nSegments + 1; - *pIndices++ = wVerticeIndex + 1; - *pIndices++ = wVerticeIndex; - wVerticeIndex ++; - } - }; // end for seg - } // end for ring - - // Unlock - vBuf->unlock(); - iBuf->unlock(); -} - -void GeomUtils::createQuad(VertexData*& vertexData) -{ - assert(vertexData); - - vertexData->vertexCount = 4; - vertexData->vertexStart = 0; - - VertexDeclaration* vertexDecl = vertexData->vertexDeclaration; - VertexBufferBinding* bind = vertexData->vertexBufferBinding; - - vertexDecl->addElement(0, 0, VET_FLOAT3, VES_POSITION); - - HardwareVertexBufferSharedPtr vbuf = - HardwareBufferManager::getSingleton().createVertexBuffer( - vertexDecl->getVertexSize(0), - vertexData->vertexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - // Bind buffer - bind->setBinding(0, vbuf); - // Upload data - float data[]={ - -1,1,-1, // corner 1 - -1,-1,-1, // corner 2 - 1,1,-1, // corner 3 - 1,-1,-1}; // corner 4 - vbuf->writeData(0, sizeof(data), data, true); -} - -void GeomUtils::createCone(const Ogre::String& strName , float radius , float height, int nVerticesInBase) -{ - MeshPtr pCone = MeshManager::getSingleton().createManual(strName, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - SubMesh *pConeVertex = pCone->createSubMesh(); - pCone->createVertexData(); - - createCone(pCone->sharedVertexData, pConeVertex->indexData - , radius - , height - , nVerticesInBase); - - // Generate face list - pConeVertex->useSharedVertices = true; - - // the original code was missing this line: - pCone->_setBounds( AxisAlignedBox( - Vector3(-radius, 0, -radius), - Vector3(radius, height, radius) ), false ); - - pCone->_setBoundingSphereRadius(Math::Sqrt(height*height + radius*radius)); - // this line makes clear the mesh is loaded (avoids memory leaks) - pCone->load(); -} - - -void GeomUtils::createCone(Ogre::VertexData*& vertexData, Ogre::IndexData*& indexData, - float radius , float height, int nVerticesInBase) -{ - assert(vertexData && indexData); - - // define the vertex format - VertexDeclaration* vertexDecl = vertexData->vertexDeclaration; - // positions - vertexDecl->addElement(0, 0, VET_FLOAT3, VES_POSITION); - - // allocate the vertex buffer - vertexData->vertexCount = nVerticesInBase + 1; - HardwareVertexBufferSharedPtr vBuf = HardwareBufferManager::getSingleton().createVertexBuffer(vertexDecl->getVertexSize(0), vertexData->vertexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY, false); - VertexBufferBinding* binding = vertexData->vertexBufferBinding; - binding->setBinding(0, vBuf); - float* pVertex = static_cast(vBuf->lock(HardwareBuffer::HBL_DISCARD)); - - // allocate index buffer - cone and base - indexData->indexCount = (3 * nVerticesInBase) + (3 * (nVerticesInBase - 2)); - indexData->indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer(HardwareIndexBuffer::IT_16BIT, indexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY, false); - HardwareIndexBufferSharedPtr iBuf = indexData->indexBuffer; - unsigned short* pIndices = static_cast(iBuf->lock(HardwareBuffer::HBL_DISCARD)); - - //Positions : cone head and base - for (int i=0; i<3; i++) - *pVertex++ = 0.0f; - - //Base : - float fDeltaBaseAngle = (2 * Math::PI) / nVerticesInBase; - for (int i=0; iunlock(); - iBuf->unlock(); -} diff --git a/Samples/DeferredShading/src/LightMaterialGenerator.cpp b/Samples/DeferredShading/src/LightMaterialGenerator.cpp deleted file mode 100644 index 87be7ea36fe..00000000000 --- a/Samples/DeferredShading/src/LightMaterialGenerator.cpp +++ /dev/null @@ -1,404 +0,0 @@ -/****************************************************************************** -Copyright (c) W.J. van der Laan - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the -Software, and to permit persons to whom the Software is furnished to do so, subject -to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies -or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ - -#include "LightMaterialGenerator.h" - -#include "OgreStringConverter.h" -#include "OgreException.h" -#include "OgreMaterialManager.h" - -#include "OgrePass.h" -#include "OgreTechnique.h" - -#include "OgreGpuProgramManager.h" -#include "OgreHighLevelGpuProgram.h" -#include "OgreHighLevelGpuProgramManager.h" - -#include "DLight.h" - -using namespace Ogre; - -//CG -class LightMaterialGeneratorCG : public MaterialGenerator::Impl -{ -public: - typedef MaterialGenerator::Perm Perm; - LightMaterialGeneratorCG(const String &baseName): - mBaseName(baseName) - { - - } - virtual ~LightMaterialGeneratorCG() - { - - } - - GpuProgramPtr generateVertexShader(Perm permutation) override - { - String programName = "DeferredShading/post/"; - - if (permutation & LightMaterialGenerator::MI_DIRECTIONAL) - { - programName += "vs"; - } - else - { - programName += "LightMaterial_vs"; - } - - GpuProgramPtr ptr = HighLevelGpuProgramManager::getSingleton().getByName( - programName, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - OgreAssert(ptr, "vertex shader is NULL"); - return ptr; - } - - GpuProgramPtr generateFragmentShader(Perm permutation) override - { - /// Create shader - if (mMasterSource.empty()) - { - DataStreamPtr ptrMasterSource = ResourceGroupManager::getSingleton().openResource( - "LightMaterial_ps.cg" - , ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - assert(ptrMasterSource); - mMasterSource = ptrMasterSource->getAsString(); - } - - assert(mMasterSource.empty()==false); - - // Create name - String name = mBaseName+StringConverter::toString(permutation)+"_ps"; - - // Create shader object - HighLevelGpuProgramPtr ptrProgram = HighLevelGpuProgramManager::getSingleton().createProgram( - name, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - "hlsl", GPT_FRAGMENT_PROGRAM); - ptrProgram->setSource(mMasterSource); - ptrProgram->setParameter("entry_point","main"); - ptrProgram->setParameter("target","ps_2_a"); - // set up the preprocessor defines - // Important to do this before any call to get parameters, i.e. before the program gets loaded - ptrProgram->setParameter("preprocessor_defines", getPPDefines(permutation)); - - setUpBaseParameters(ptrProgram->getDefaultParameters()); - - return GpuProgramPtr(ptrProgram); - } - - MaterialPtr generateTemplateMaterial(Perm permutation) override - { - String materialName = mBaseName; - - if(permutation & LightMaterialGenerator::MI_DIRECTIONAL) - { - materialName += "Quad"; - } - else - { - materialName += "Geometry"; - } - - if(permutation & LightMaterialGenerator::MI_SHADOW_CASTER) - { - materialName += "Shadow"; - } - return MaterialManager::getSingleton().getByName(materialName); - } - - protected: - String mBaseName; - String mMasterSource; - // Utility method - String getPPDefines(Perm permutation) - { - String strPPD; - - //Get the type of light - String lightType; - if (permutation & LightMaterialGenerator::MI_POINT) - { - lightType = "POINT"; - } - else if (permutation & LightMaterialGenerator::MI_SPOTLIGHT) - { - lightType = "SPOT"; - } - else if (permutation & LightMaterialGenerator::MI_DIRECTIONAL) - { - lightType = "DIRECTIONAL"; - } - else - { - assert(false && "Permutation must have a light type"); - } - strPPD += "LIGHT_TYPE=LIGHT_" + lightType; - - //Optional parameters - if (permutation & LightMaterialGenerator::MI_SPECULAR) - { - strPPD += ",IS_SPECULAR=1"; - } - if (permutation & LightMaterialGenerator::MI_ATTENUATED) - { - strPPD += ",IS_ATTENUATED=1"; - } - if (permutation & LightMaterialGenerator::MI_SHADOW_CASTER) - { - strPPD += ",IS_SHADOW_CASTER=1"; - } - return strPPD; - } - - void setUpBaseParameters(const GpuProgramParametersSharedPtr& params) - { - assert(params); - - struct AutoParamPair { String name; GpuProgramParameters::AutoConstantType type; }; - - //A list of auto params that might be present in the shaders generated - static const AutoParamPair AUTO_PARAMS[] = { - { "vpWidth", GpuProgramParameters::ACT_VIEWPORT_WIDTH }, - { "vpHeight", GpuProgramParameters::ACT_VIEWPORT_HEIGHT }, - { "worldView", GpuProgramParameters::ACT_WORLDVIEW_MATRIX }, - { "invProj", GpuProgramParameters::ACT_INVERSE_PROJECTION_MATRIX }, - { "invView", GpuProgramParameters::ACT_INVERSE_VIEW_MATRIX }, - { "flip", GpuProgramParameters::ACT_RENDER_TARGET_FLIPPING }, - { "lightDiffuseColor", GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR }, - { "lightSpecularColor", GpuProgramParameters::ACT_LIGHT_SPECULAR_COLOUR }, - { "lightFalloff", GpuProgramParameters::ACT_LIGHT_ATTENUATION }, - { "lightPos", GpuProgramParameters::ACT_LIGHT_POSITION_VIEW_SPACE }, - { "lightDir", GpuProgramParameters::ACT_LIGHT_DIRECTION_VIEW_SPACE }, - { "spotParams", GpuProgramParameters::ACT_SPOTLIGHT_PARAMS }, - { "farClipDistance", GpuProgramParameters::ACT_FAR_CLIP_DISTANCE }, - { "shadowViewProjMat", GpuProgramParameters::ACT_TEXTURE_VIEWPROJ_MATRIX } - }; - int numParams = sizeof(AUTO_PARAMS) / sizeof(AutoParamPair); - - for (int i=0; i_findNamedConstantDefinition(AUTO_PARAMS[i].name)) - { - params->setNamedAutoConstant(AUTO_PARAMS[i].name, AUTO_PARAMS[i].type); - } - } - } -}; - -//GLSL -class LightMaterialGeneratorGLSL : public MaterialGenerator::Impl -{ -public: - typedef MaterialGenerator::Perm Perm; - LightMaterialGeneratorGLSL(const String &baseName): - mBaseName(baseName) - { - - } - virtual ~LightMaterialGeneratorGLSL() - { - - } - - GpuProgramPtr generateVertexShader(Perm permutation) override - { - String programName = "DeferredShading/post/"; - - if (permutation & LightMaterialGenerator::MI_DIRECTIONAL) - { - programName += "vs"; - } - else - { - programName += "LightMaterial_vs"; - } - - GpuProgramPtr ptr = HighLevelGpuProgramManager::getSingleton().getByName( - programName, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - OgreAssert(ptr, "vertex shader is NULL"); - return ptr; - } - - GpuProgramPtr generateFragmentShader(Perm permutation) override - { - /// Create shader - if (mMasterSource.empty()) - { - DataStreamPtr ptrMasterSource = - ResourceGroupManager::getSingleton().openResource("LightMaterial_ps.glsl", RGN_DEFAULT); - - OgreAssert(ptrMasterSource, "could not find 'LightMaterial_ps'"); - mMasterSource = ptrMasterSource->getAsString(); - } - - OgreAssert(!mMasterSource.empty(), "no source code"); - - // Create name - String name = mBaseName+StringConverter::toString(permutation)+"_ps"; - - // Create shader object - HighLevelGpuProgramPtr ptrProgram; - if(GpuProgramManager::getSingleton().isSyntaxSupported("glsles")) - { - ptrProgram = HighLevelGpuProgramManager::getSingleton().createProgram(name, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - "glsles", GPT_FRAGMENT_PROGRAM); - } - else - { - ptrProgram = HighLevelGpuProgramManager::getSingleton().createProgram(name, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - "glsl", GPT_FRAGMENT_PROGRAM); - } - ptrProgram->setSource(mMasterSource); - // set up the preprocessor defines - // Important to do this before any call to get parameters, i.e. before the program gets loaded - ptrProgram->setParameter("preprocessor_defines", getPPDefines(permutation)); - - setUpBaseParameters(ptrProgram->getDefaultParameters()); - - // Bind samplers - GpuProgramParametersSharedPtr params = ptrProgram->getDefaultParameters(); - int numSamplers = 0; - params->setNamedConstant("Tex0", (int)numSamplers++); - params->setNamedConstant("Tex1", (int)numSamplers++); - - if(permutation & LightMaterialGenerator::MI_SHADOW_CASTER) - params->setNamedConstant("ShadowTex", (int)numSamplers++); - - return GpuProgramPtr(ptrProgram); - } - - MaterialPtr generateTemplateMaterial(Perm permutation) override - { - String materialName = mBaseName; - - if(permutation & LightMaterialGenerator::MI_DIRECTIONAL) - { - materialName += "Quad"; - } - else - { - materialName += "Geometry"; - } - - if(permutation & LightMaterialGenerator::MI_SHADOW_CASTER) - { - materialName += "Shadow"; - } - return MaterialManager::getSingleton().getByName(materialName); - } - -protected: - String mBaseName; - String mMasterSource; - // Utility method - String getPPDefines(Perm permutation) - { - String strPPD; - - //Get the type of light - Ogre::uint lightType = 0; - if (permutation & LightMaterialGenerator::MI_POINT) - { - lightType = 1; - } - else if (permutation & LightMaterialGenerator::MI_SPOTLIGHT) - { - lightType = 2; - } - else if (permutation & LightMaterialGenerator::MI_DIRECTIONAL) - { - lightType = 3; - } - else - { - assert(false && "Permutation must have a light type"); - } - strPPD += "LIGHT_TYPE=" + StringConverter::toString(lightType); - - //Optional parameters - if (permutation & LightMaterialGenerator::MI_SPECULAR) - { - strPPD += ",IS_SPECULAR=1"; - } - if (permutation & LightMaterialGenerator::MI_ATTENUATED) - { - strPPD += ",IS_ATTENUATED=1"; - } - if (permutation & LightMaterialGenerator::MI_SHADOW_CASTER) - { - strPPD += ",IS_SHADOW_CASTER=1"; - } - return strPPD; - } - - void setUpBaseParameters(const GpuProgramParametersSharedPtr& params) - { - assert(params); - - struct AutoParamPair { String name; GpuProgramParameters::AutoConstantType type; }; - - //A list of auto params that might be present in the shaders generated - static const AutoParamPair AUTO_PARAMS[] = { - { "vpWidth", GpuProgramParameters::ACT_VIEWPORT_WIDTH }, - { "vpHeight", GpuProgramParameters::ACT_VIEWPORT_HEIGHT }, - { "worldView", GpuProgramParameters::ACT_WORLDVIEW_MATRIX }, - { "invProj", GpuProgramParameters::ACT_INVERSE_PROJECTION_MATRIX }, - { "invView", GpuProgramParameters::ACT_INVERSE_VIEW_MATRIX }, - { "flip", GpuProgramParameters::ACT_RENDER_TARGET_FLIPPING }, - { "lightDiffuseColor", GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR }, - { "lightSpecularColor", GpuProgramParameters::ACT_LIGHT_SPECULAR_COLOUR }, - { "lightFalloff", GpuProgramParameters::ACT_LIGHT_ATTENUATION }, - { "lightPos", GpuProgramParameters::ACT_LIGHT_POSITION_VIEW_SPACE }, - { "lightDir", GpuProgramParameters::ACT_LIGHT_DIRECTION_VIEW_SPACE }, - { "spotParams", GpuProgramParameters::ACT_SPOTLIGHT_PARAMS }, - { "farClipDistance", GpuProgramParameters::ACT_FAR_CLIP_DISTANCE }, - { "shadowViewProjMat", GpuProgramParameters::ACT_TEXTURE_VIEWPROJ_MATRIX } - }; - int numParams = sizeof(AUTO_PARAMS) / sizeof(AutoParamPair); - - for (int i=0; i_findNamedConstantDefinition(AUTO_PARAMS[i].name)) - { - params->setNamedAutoConstant(AUTO_PARAMS[i].name, AUTO_PARAMS[i].type); - } - } - } -}; - -LightMaterialGenerator::LightMaterialGenerator() -{ - vsMask = 0x00000004; - fsMask = 0x0000003F; - matMask = LightMaterialGenerator::MI_DIRECTIONAL | - LightMaterialGenerator::MI_SHADOW_CASTER; - - materialBaseName = "DeferredShading/LightMaterial/"; - if ((GpuProgramManager::getSingleton().isSyntaxSupported("glsl") || GpuProgramManager::getSingleton().isSyntaxSupported("glsles")) && - !(GpuProgramManager::getSingleton().isSyntaxSupported("ps_2_x") ||GpuProgramManager::getSingleton().isSyntaxSupported("arbfp1"))) - mImpl = new LightMaterialGeneratorGLSL("DeferredShading/LightMaterial/"); - else - mImpl = new LightMaterialGeneratorCG("DeferredShading/LightMaterial/"); -} - -LightMaterialGenerator::~LightMaterialGenerator() -{ - -} diff --git a/Samples/DeferredShading/src/MaterialGenerator.cpp b/Samples/DeferredShading/src/MaterialGenerator.cpp deleted file mode 100755 index 63e8edaaf12..00000000000 --- a/Samples/DeferredShading/src/MaterialGenerator.cpp +++ /dev/null @@ -1,129 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#include "MaterialGenerator.h" - -#include "OgreStringConverter.h" -#include "OgreException.h" - -#include "OgrePass.h" -#include "OgreTechnique.h" - -#include "OgreHighLevelGpuProgram.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreMaterialManager.h" - -#include - -using namespace Ogre; - -MaterialGenerator::MaterialGenerator(): - vsMask(0), fsMask(0), matMask(0), mImpl(0) -{ -} -MaterialGenerator::~MaterialGenerator() -{ - // we have generated fragment shaders and materials - // so delete them - for(ProgramMap::iterator it = mFs.begin(); it != mFs.end(); ++it) { - HighLevelGpuProgramManager::getSingleton().remove(it->second); - } - for(MaterialMap::iterator it = mMaterials.begin(); it != mMaterials.end(); ++it) { - MaterialManager::getSingleton().remove(it->second); - } - - delete mImpl; -} - -const MaterialPtr &MaterialGenerator::getMaterial(Perm permutation) -{ - /// Check if material/shader permutation already was generated - MaterialMap::iterator i = mMaterials.find(permutation); - if(i != mMaterials.end()) - { - return i->second; - } - else - { - /// Create it - MaterialPtr templ = getTemplateMaterial(permutation & matMask); - GpuProgramPtr vs = getVertexShader(permutation & vsMask); - GpuProgramPtr fs = getFragmentShader(permutation & fsMask); - - /// Create material name - String name = materialBaseName + StringConverter::toString(permutation); - - std::cerr << name << " " << vs->getName() << " " << fs->getName() << std::endl; - /// Create material from template, and set shaders - MaterialPtr mat = templ->clone(name); - Technique *tech = mat->getTechnique(0); - Pass *pass = tech->getPass(0); - pass->setFragmentProgram(fs->getName()); - pass->setVertexProgram(vs->getName()); - - /// And store it - mMaterials[permutation] = mat; - return mMaterials[permutation]; - } -} - -const GpuProgramPtr &MaterialGenerator::getVertexShader(Perm permutation) -{ - ProgramMap::iterator i = mVs.find(permutation); - if(i != mVs.end()) - { - return i->second; - } - else - { - /// Create it - mVs[permutation] = mImpl->generateVertexShader(permutation); - return mVs[permutation]; - } -} - -const GpuProgramPtr &MaterialGenerator::getFragmentShader(Perm permutation) -{ - ProgramMap::iterator i = mFs.find(permutation); - if(i != mFs.end()) - { - return i->second; - } - else - { - /// Create it - mFs[permutation] = mImpl->generateFragmentShader(permutation); - return mFs[permutation]; - } -} - -const MaterialPtr &MaterialGenerator::getTemplateMaterial(Perm permutation) -{ - MaterialMap::iterator i = mTemplateMat.find(permutation); - if(i != mTemplateMat.end()) - { - return i->second; - } - else - { - /// Create it - mTemplateMat[permutation] = mImpl->generateTemplateMaterial(permutation); - return mTemplateMat[permutation]; - } -} - -MaterialGenerator::Impl::~Impl() -{ -} - diff --git a/Samples/DeferredShading/src/SSAOLogic.cpp b/Samples/DeferredShading/src/SSAOLogic.cpp deleted file mode 100644 index 9a99e9b45f4..00000000000 --- a/Samples/DeferredShading/src/SSAOLogic.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#include "SSAOLogic.h" - -#include "Ogre.h" -using namespace Ogre; - -class ssaoListener: public Ogre::CompositorInstance::Listener -{ -public: - - ssaoListener(Ogre::CompositorInstance* instance) : mInstance(instance) {} - - // this callback we will use to modify SSAO parameters - void notifyMaterialRender(Ogre::uint32 pass_id, Ogre::MaterialPtr &mat) override - { - if (pass_id != 42) // not SSAO, return - return; - - // this is the camera you're using - Ogre::Camera *cam = mInstance->getChain()->getViewport()->getCamera(); - - // get the pass - Ogre::Pass *pass = mat->getBestTechnique()->getPass(0); - - // get the fragment shader parameters - auto params = pass->getFragmentProgramParameters(); - // set the projection matrix we need - params->setNamedConstant("ptMat", Matrix4::CLIPSPACE2DTOIMAGESPACE * cam->getProjectionMatrixWithRSDepth()); - } -private: - Ogre::CompositorInstance* mInstance; -}; - -Ogre::CompositorInstance::Listener* SSAOLogic::createListener(Ogre::CompositorInstance* instance) -{ - return new ssaoListener(instance); -} diff --git a/Samples/Emscripten/CMakeLists.txt b/Samples/Emscripten/CMakeLists.txt deleted file mode 100644 index f03925be9fe..00000000000 --- a/Samples/Emscripten/CMakeLists.txt +++ /dev/null @@ -1,33 +0,0 @@ -set(MEDIA_DIR ${CMAKE_BINARY_DIR}/bin/media/) - -set(CMAKE_EXECUTABLE_SUFFIX ".html") -set(CMAKE_EXE_LINKER_FLAGS "--preload-file ${MEDIA_DIR}/@. -s EXPORTED_FUNCTIONS=\"[ '_passAssetAsArrayBuffer', '_clearScene', '_main']\" -s USE_SDL=2 -s MAX_WEBGL_VERSION=2") - -add_definitions(-s USE_SDL=2) - -if(TRUE) - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -s ASSERTIONS=1 -s DISABLE_EXCEPTION_CATCHING=0") -endif() - -include_directories(${PROJECT_SOURCE_DIR}/Samples/Character/include) -add_executable(EmscriptenSample Main.cpp Context.cpp) -target_link_libraries(EmscriptenSample OgreBites ${OGRE_LIBRARIES}) - -file(COPY - "${CMAKE_SOURCE_DIR}/Samples/Emscripten/media" - DESTINATION "${CMAKE_BINARY_DIR}/bin/") - -file(COPY - "${CMAKE_SOURCE_DIR}/Samples/Media/materials/textures/ribbonband.png" - "${CMAKE_SOURCE_DIR}/Samples/Media/materials/textures/rockwall.tga" - "${CMAKE_SOURCE_DIR}/Media/packs/SdkTrays.zip" - "${CMAKE_SOURCE_DIR}/Samples/Media/packs/Sinbad.zip" - DESTINATION ${MEDIA_DIR}) - -file(COPY - "${CMAKE_SOURCE_DIR}/Media/RTShaderLib" - DESTINATION "${MEDIA_DIR}/") - -file(COPY - "${CMAKE_SOURCE_DIR}/Media/Main" - DESTINATION "${MEDIA_DIR}/") diff --git a/Samples/Emscripten/Context.cpp b/Samples/Emscripten/Context.cpp deleted file mode 100755 index 7b5a3c76f2c..00000000000 --- a/Samples/Emscripten/Context.cpp +++ /dev/null @@ -1,229 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ - -#include "OgreZip.h" - -#include "SamplePlugin.h" -#include "CharacterSample.h" - -#include -#include "Context.h" - -Context::Context() - : OgreBites::SampleContext("OGRE Emscripten Sample"), mBuffer(NULL), mNode(NULL) -{ -} - -bool Context::mouseWheelRolled(const OgreBites::MouseWheelEvent& evt) { - OgreBites::MouseWheelEvent _evt = evt; - // chrome reports values of 53 here - _evt.y = std::min(3, std::max(-3, evt.y)); - return OgreBites::SampleContext::mouseWheelRolled(evt); -} - -void Context::_mainLoop(void* target) -{ - Context* thizz = static_cast(target); - if (thizz->mRoot->endRenderingQueued()) - { - emscripten_cancel_main_loop(); - } - else - { - try - { - if (!thizz->mRoot->renderOneFrame()) - { - emscripten_cancel_main_loop(); - } - } - catch (Ogre::Exception& e) - { - size_t length = emscripten_get_callstack(EM_LOG_C_STACK | EM_LOG_DEMANGLE | EM_LOG_NO_PATHS | EM_LOG_FUNC_PARAMS,0,0) + 50; - std::vector buffer(length); - emscripten_get_callstack(EM_LOG_C_STACK | EM_LOG_DEMANGLE | EM_LOG_NO_PATHS | EM_LOG_FUNC_PARAMS, buffer.data(), length); - Ogre::LogManager::getSingleton().logMessage(buffer.data()); - - emscripten_pause_main_loop(); - } - } -} - - -void Context::unloadResource(Ogre::ResourceManager* resMgr, const Ogre::String& resourceName) -{ - Ogre::ResourcePtr rPtr = resMgr->getResourceByName(resourceName, "General"); - if (!rPtr) - return; - - rPtr->unload(); - resMgr->remove(resourceName, "General"); -} - -void Context::destroyMaterials( const Ogre::String& resourceGroupID ) -{ - - try - { - Ogre::MaterialManager* materialManager = Ogre::MaterialManager::getSingletonPtr(); - Ogre::ResourceManager::ResourceMapIterator resourceIterator = materialManager->getResourceIterator(); - - std::vector< std::string > materialNamesToRemove; - - while( resourceIterator.hasMoreElements() ) - { - Ogre::ResourcePtr material = resourceIterator.getNext(); - std::string matName = material->getName(); - - if( resourceGroupID == material->getGroup()) - { - mShaderGenerator->removeAllShaderBasedTechniques( matName, material->getGroup() ); - material->unload(); - material.reset(); - materialNamesToRemove.push_back( matName ); - } - } - - for( size_t i = 0; i < materialNamesToRemove.size(); ++i ) - { - materialManager->remove( materialNamesToRemove[i], resourceGroupID ); - } - materialManager->removeUnreferencedResources(); - } - catch( ... ) - { - Ogre::LogManager::getSingleton().logMessage("An Error occurred trying to destroy Materials in " + resourceGroupID); - } - -} - -void Context::destroyTextures( const Ogre::String& resourceGroupID ) -{ - try - { - Ogre::TextureManager* textureManager = Ogre::TextureManager::getSingletonPtr(); - Ogre::ResourceManager::ResourceMapIterator resourceIterator = textureManager->getResourceIterator(); - - std::vector< std::string > textureNamesToRemove; - - while( resourceIterator.hasMoreElements() ) - { - Ogre::ResourcePtr texture = resourceIterator.getNext(); - Ogre::String resourceName = texture->getName(); - if( resourceGroupID == texture->getGroup()) - { - texture->unload(); - texture.reset(); - textureNamesToRemove.push_back( resourceName ); - } - } - - for( size_t i = 0; i < textureNamesToRemove.size(); ++i ) - { - textureManager->remove( textureNamesToRemove[i], resourceGroupID ); - } - } - catch( ... ) - { - Ogre::LogManager::getSingleton().logMessage("An Error occurred trying to destroy Textures in " + resourceGroupID); - } - -} - -void Context::clearScene() -{ - if (mBuffer != NULL) - { - //for (auto mo : mNode->getAttachedObjects()) - // mSceneMgr->destroyMovableObject(mo); - mNode->detachAllObjects(); - - Ogre::MaterialManager* matMgr = Ogre::MaterialManager::getSingletonPtr(); - matMgr->removeUnreferencedResources(); - - Ogre::MeshManager* meshMgr = Ogre::MeshManager::getSingletonPtr(); - meshMgr->unloadUnreferencedResources(); - - Ogre::TextureManager* texMgr = Ogre::TextureManager::getSingletonPtr(); - texMgr->removeUnreferencedResources(); - - if( Ogre::ResourceGroupManager::getSingleton().resourceGroupExists("Download") && Ogre::ResourceGroupManager::getSingleton().isResourceGroupInitialised("Download") ) - { - destroyMaterials( "Download" ); - destroyTextures( "Download" ); - - Ogre::ResourceGroupManager::getSingleton().removeResourceLocation( "download.zip" ); - Ogre::ResourceGroupManager::getSingleton().destroyResourceGroup( "Download" ); - } - - Ogre::EmbeddedZipArchiveFactory::removeEmbbeddedFile("download.zip"); - - mShaderGenerator->removeAllShaderBasedTechniques(); - mShaderGenerator->flushShaderCache(); - - //free(mBuffer); - mBuffer = NULL; - } -} - -void Context::passAssetAsArrayBuffer(unsigned char* arr, int length) { - - try { - - clearScene(); - Ogre::ResourceGroupManager::getSingleton().createResourceGroup("Download"); - mBuffer = arr; - - Ogre::EmbeddedZipArchiveFactory::addEmbbeddedFile("download.zip", mBuffer, length, NULL); - Ogre::ResourceGroupManager::getSingleton().addResourceLocation("download.zip","EmbeddedZip","Download"); - Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Download"); - - Ogre::StringVectorPtr meshes = Ogre::ArchiveManager::getSingleton().load("download.zip","EmbeddedZip",true)->find("*.mesh"); - for (auto i : *meshes) - { - //mNode->attachObject(mSceneMgr->createEntity(i)); - } - - } catch (Ogre::Exception& ex) { - Ogre::LogManager::getSingleton().logMessage(ex.what()); - - } - - -} - -void Context::setup() { - OgreBites::ApplicationContext::setup(); - mWindow = getRenderWindow(); - addInputListener(this); - - mCurrentSample = new Sample_Character(); - mCurrentSample->setShaderGenerator(mShaderGenerator); - mCurrentSample->_setupTrays(mWindow); - mCurrentSample->_setup(mWindow, mFSLayer, mOverlaySystem); -} diff --git a/Samples/Emscripten/Context.h b/Samples/Emscripten/Context.h deleted file mode 100755 index c699e0a1506..00000000000 --- a/Samples/Emscripten/Context.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ - -#ifndef __SAMPLE_H__ -#define __SAMPLE_H__ - -#include "Ogre.h" -#include "OgreTrays.h" -#include "OgreCameraMan.h" -#include "OgreApplicationContext.h" - -#include "SampleContext.h" - -class Context : public OgreBites::SampleContext -{ -public: - Context(); - - void passAssetAsArrayBuffer(unsigned char*, int length); - void clearScene(); - - static void _mainLoop(void* target); -private: - unsigned char* mBuffer; - Ogre::SceneNode* mNode; - - void destroyMaterials( const Ogre::String& resourceGroupID ); - void destroyTextures( const Ogre::String& resourceGroupID ); - void unloadResource(Ogre::ResourceManager* resMgr, const Ogre::String& resourceName); - - void setup(); - - bool mouseWheelRolled(const OgreBites::MouseWheelEvent& evt); -}; -#endif diff --git a/Samples/Emscripten/Main.cpp b/Samples/Emscripten/Main.cpp deleted file mode 100755 index 177b9521d33..00000000000 --- a/Samples/Emscripten/Main.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- - */ - -#include "Context.h" - -static Context* sampleInst = NULL; - -int main( int argc, const char* argv[] ) { - try - { - sampleInst = new Context(); - sampleInst->initApp(); - emscripten_set_main_loop_arg(Context::_mainLoop, sampleInst, 0, 1); - sampleInst->closeApp(); - delete sampleInst; - sampleInst = NULL; - } - catch ( std::exception& e ) - { - Ogre::LogManager::getSingleton().logMessage(e.what()); - } - return 0; -} - -extern "C" -{ - int passAssetAsArrayBuffer(unsigned char* buf, int length) { - sampleInst->passAssetAsArrayBuffer(buf, length); - return 0; - } - - int clearScene() { - sampleInst->clearScene(); - return 0; - } -} diff --git a/Samples/Emscripten/media/ogre.cfg b/Samples/Emscripten/media/ogre.cfg deleted file mode 100644 index f0097fcfbd5..00000000000 --- a/Samples/Emscripten/media/ogre.cfg +++ /dev/null @@ -1,7 +0,0 @@ -Render System=OpenGL ES 2.x Rendering Subsystem - -[OpenGL ES 2.x Rendering Subsystem] -FSAA=2 -VSync=Yes -Video Mode=800 x 600 -sRGB Gamma Conversion=No diff --git a/Samples/Emscripten/media/resources.cfg b/Samples/Emscripten/media/resources.cfg deleted file mode 100644 index 814c89a4538..00000000000 --- a/Samples/Emscripten/media/resources.cfg +++ /dev/null @@ -1,11 +0,0 @@ -# Ogre Core Resources -[OgreInternal] -FileSystem=/RTShaderLib -FileSystem=/Main - -[Essential] -Zip=/SdkTrays.zip - -[General] -FileSystem= -Zip=/Sinbad.zip \ No newline at end of file diff --git a/Samples/Emscripten/media/sample.material b/Samples/Emscripten/media/sample.material deleted file mode 100644 index ab318477f26..00000000000 --- a/Samples/Emscripten/media/sample.material +++ /dev/null @@ -1,52 +0,0 @@ -material Examples/LightRibbonTrail -{ - technique - { - pass - { - lighting off - scene_blend add - depth_write off - diffuse vertexcolour - - texture_unit - { - texture ribbonband.png 1d - tex_address_mode clamp - filtering none - } - } - } -} - -material Examples/Rockwall -{ - technique - { - pass - { - texture_unit - { - texture rockwall.tga - } - } - } -} - -material PSSM/shadow_caster -{ - technique - { - // all this will do is write depth - pass - { - fog_override true none - depth_bias -1 -1 - - rtshader_system - { - lighting_stage gbuffer depth - } - } - } -} diff --git a/Samples/EndlessWorld/include/EndlessWorld.h b/Samples/EndlessWorld/include/EndlessWorld.h deleted file mode 100644 index 35f9d8af9be..00000000000 --- a/Samples/EndlessWorld/include/EndlessWorld.h +++ /dev/null @@ -1,449 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ -#ifndef __EndlessWorld_H__ -#define __EndlessWorld_H__ - -#define ENDLESS_PAGING - -// max range for a int16 -#define ENDLESS_PAGE_MIN_X (-0x7FFF) -#define ENDLESS_PAGE_MIN_Y (-0x7FFF) -#define ENDLESS_PAGE_MAX_X 0x7FFF -#define ENDLESS_PAGE_MAX_Y 0x7FFF - -#include "SdkSample.h" -#include "OgreTerrain.h" -#include "OgreTerrainGroup.h" -#include "OgreTerrainQuadTreeNode.h" -#include "OgreTerrainMaterialGeneratorA.h" -#include "OgreTerrainPagedWorldSection.h" -#include "OgreTerrainAutoUpdateLod.h" -#include "OgreTerrainPaging.h" -#include "OgrePageManager.h" -#include "PerlinNoiseTerrainGenerator.h" - -#define ENDLESS_TERRAIN_FILE_PREFIX String("EndlessWorldTerrain") -#define ENDLESS_TERRAIN_FILE_SUFFIX String("dat") -#define TERRAIN_WORLD_SIZE 12000.0f -#define TERRAIN_SIZE 513 -#define HOLD_LOD_DISTANCE 3000.0 -#define USE_PERLIN_DEFINER 1 - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_EndlessWorld : public SdkSample -{ -public: - - Sample_EndlessWorld() - : mTerrainGlobals(0) - , mTerrainGroup(0) - , mTerrainPaging(0) - , mPageManager(0) - , mPagedWorld(0) - , mTerrainPagedWorldSection(0) - , mPerlinNoiseTerrainGenerator(0) - , mLodStatus(false) - , mFly(true) - , mFallVelocity(0) - , mTerrainPos(0,0,0) - , mLodInfoOverlay(0) - , mLodInfoOverlayContainer(0) - - { - mInfo["Title"] = "Endless World"; - mInfo["Description"] = "Demonstrates use of the terrain plugin with paging option."; - mInfo["Thumbnail"] = "thumb_terrain.png"; - mInfo["Category"] = "Environment"; - mInfo["Help"] = "Left click and drag anywhere in the scene to look around. Let go again to show " - "cursor and access widgets. Use WASD keys to move. You can increase/decrease terrains' LOD level using Page Up/Page Down." - "Use C to generate another random terrain"; - } - - bool frameRenderingQueued(const FrameEvent& evt) override - { - if (!mFly) - { - // clamp to terrain - Vector3 camPos = mCameraNode->getPosition(); - Ray ray; - ray.setOrigin(Vector3(camPos.x, mTerrainPos.y + 10000, camPos.z)); - ray.setDirection(Vector3::NEGATIVE_UNIT_Y); - - TerrainGroup::RayResult rayResult = mTerrainGroup->rayIntersects(ray); - const Real distanceAboveTerrain = 50; - if (rayResult.hit) - mCameraNode->setPosition(camPos.x, rayResult.position.y + distanceAboveTerrain, camPos.z); - } - - if (mTerrainGroup->isDerivedDataUpdateInProgress()) - { - mTrayMgr->moveWidgetToTray(mInfoLabel, TL_TOP, 0); - mInfoLabel->show(); - mInfoLabel->setCaption("Building terrain..."); - } - else - { - mTrayMgr->removeWidgetFromTray(mInfoLabel); - mInfoLabel->hide(); - } - - if (mLodStatus) - { - for(LabelList::iterator li = mLodStatusLabelList.begin(); li != mLodStatusLabelList.end(); li++) - { - mLodInfoOverlayContainer->_removeChild(*li); - OverlayManager::getSingleton().destroyOverlayElement(*li); - } - mLodStatusLabelList.clear(); - - for (const auto& ti : mTerrainGroup->getTerrainSlots()) - { - Terrain* t = ti.second->instance; - if (!t) - continue; - - Vector3 pt = mCamera->getProjectionMatrix() * (mCamera->getViewMatrix() * t->getPosition()); - Real x = (pt.x / 2) + 0.5f; - Real y = 1 - ((pt.y / 2) + 0.5f); - - String lName = StringConverter::toString(size_t(t))+"/"+"LodInfoLabel"; - - OverlayElement *l = OverlayManager::getSingleton().createOverlayElement("TextArea", lName); - l->setCaption("Target="+StringConverter::toString(t->getTargetLodLevel())+"\nHighest="+ - StringConverter::toString(t->getHighestLodLoaded())+"\nPrepared="+ - StringConverter::toString(t->getHighestLodPrepared()) - ); - l->setPosition(x, y); - l->setDimensions(0.1, 0.1); // center text in label and its position - l->setParameter("font_name", "SdkTrays/Value"); - l->setParameter("char_height", "0.02f"); - l->setColour(ColourValue(1.0,0.0,0.0)); - - mLodInfoOverlayContainer->addChild(l); - mLodStatusLabelList.push_back(l); - } - } - - mTerrainGroup->autoUpdateLodAll(false, Real(HOLD_LOD_DISTANCE)); - return SdkSample::frameRenderingQueued(evt); // don't forget the parent updates! - } - - bool keyPressed (const KeyboardEvent &e) override - { -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - switch (e.keysym.sym) - { - case SDLK_PAGEUP: - { - mAutoBox->setChecked(false); - for (const auto& ti : mTerrainGroup->getTerrainSlots()) - { - if(Terrain* t = ti.second->instance) - t->increaseLodLevel(); - } - } - break; - case SDLK_PAGEDOWN: - { - mAutoBox->setChecked(false); - for (const auto& ti : mTerrainGroup->getTerrainSlots()) - { - if(Terrain* t = ti.second->instance) - t->decreaseLodLevel(); - } - } - break; - // generate new random offset, to make terrains different - case 'c': - if(mPerlinNoiseTerrainGenerator) - { - // random a new origin point - mPerlinNoiseTerrainGenerator->randomize(); - - // reload all terrains - for (const auto& ti : mTerrainGroup->getTerrainSlots()) - { - mTerrainPagedWorldSection->unloadPage(ti.first); - mTerrainPagedWorldSection->loadPage(ti.first); - } - } - break; - default: - return SdkSample::keyPressed(e); - } -#endif - - return true; - } - - void checkBoxToggled(CheckBox* box) override - { - if (box == mFlyBox) - { - mFly = mFlyBox->isChecked(); - } - else if (box == mLodStatusBox) - { - mLodStatus = mLodStatusBox->isChecked(); - if (!mLodStatus) - { - for(LabelList::iterator li = mLodStatusLabelList.begin(); li != mLodStatusLabelList.end(); li++) - { - mLodInfoOverlayContainer->_removeChild(*li); - OverlayManager::getSingleton().destroyOverlayElement(*li); - } - mLodStatusLabelList.clear(); - } - } - else if (box == mAutoBox) - { - if(mTerrainGroup) - { - auto strategy = mAutoBox->isChecked() ? BY_DISTANCE : NONE; - mTerrainGroup->setAutoUpdateLod(TerrainAutoUpdateLodFactory::getAutoUpdateLod(strategy)); - } - } - } - -protected: - - TerrainGlobalOptions* mTerrainGlobals; - TerrainGroup* mTerrainGroup; - TerrainPaging* mTerrainPaging; - PageManager* mPageManager; - PagedWorld* mPagedWorld; - TerrainPagedWorldSection* mTerrainPagedWorldSection; - PerlinNoiseTerrainGenerator* mPerlinNoiseTerrainGenerator; - bool mLodStatus; - - /// This class just pretends to provide procedural page content to avoid page loading - class DummyPageProvider : public PageProvider - { - public: - bool prepareProceduralPage(Page* page, PagedWorldSection* section) override { return true; } - bool loadProceduralPage(Page* page, PagedWorldSection* section) override { return true; } - bool unloadProceduralPage(Page* page, PagedWorldSection* section) override { return true; } - bool unprepareProceduralPage(Page* page, PagedWorldSection* section) override { return true; } - }; - DummyPageProvider mDummyPageProvider; - - bool mFly; - Real mFallVelocity; - Vector3 mTerrainPos; - CheckBox* mFlyBox; - OgreBites::Label* mInfoLabel; - - typedef std::list LabelList; - LabelList mLodStatusLabelList; - - Overlay *mLodInfoOverlay; - OverlayContainer *mLodInfoOverlayContainer; - - CheckBox *mLodStatusBox; - CheckBox *mAutoBox; - - void configureTerrainDefaults(Light* l) - { - // Configure global - mTerrainGlobals->setMaxPixelError(8); - // testing composite map - mTerrainGlobals->setCompositeMapDistance(3000); - //mTerrainGlobals->setUseRayBoxDistanceCalculation(true); - mTerrainGlobals->getDefaultMaterialGenerator()->setLightmapEnabled(false); - - mTerrainGlobals->setCompositeMapAmbient(mSceneMgr->getAmbientLight()); - mTerrainGlobals->setCompositeMapDiffuse(l->getDiffuseColour()); - mTerrainGlobals->setLightMapDirection(l->getDerivedDirection()); - - // Configure default import settings for if we use imported image - Terrain::ImportData& defaultimp = mTerrainGroup->getDefaultImportSettings(); - defaultimp.terrainSize = TERRAIN_SIZE; - defaultimp.worldSize = TERRAIN_WORLD_SIZE; - defaultimp.inputScale = 600; - defaultimp.minBatchSize = 33; - defaultimp.maxBatchSize = 65; - // textures - defaultimp.layerList.resize(1); - defaultimp.layerList[0].worldSize = 200; - defaultimp.layerList[0].textureNames.push_back("Ground37_diffspec.dds"); - defaultimp.layerList[0].textureNames.push_back("Ground37_normheight.dds"); - } - - /*----------------------------------------------------------------------------- - | Extends setupView to change some initial camera settings for this sample. - -----------------------------------------------------------------------------*/ - void setupView() override - { - SdkSample::setupView(); - // put camera at world center, so that it's difficult to reach the edge - Vector3 worldCenter( - (ENDLESS_PAGE_MAX_X+ENDLESS_PAGE_MIN_X) / 2 * TERRAIN_WORLD_SIZE, - 0, - -(ENDLESS_PAGE_MAX_Y+ENDLESS_PAGE_MIN_Y) / 2 * TERRAIN_WORLD_SIZE - ); - mCameraNode->setPosition(mTerrainPos+worldCenter); - mCameraNode->lookAt(mTerrainPos, Node::TS_PARENT); - mCamera->setNearClipDistance(5); - mCamera->setFarClipDistance(0); // enable infinite far clip distance - } - - void setupControls() - { - mTrayMgr->showCursor(); - - // make room for the controls - mTrayMgr->showLogo(TL_TOPRIGHT); - mTrayMgr->showFrameStats(TL_TOPRIGHT); - mTrayMgr->toggleAdvancedFrameStats(); - - mInfoLabel = mTrayMgr->createLabel(TL_TOP, "TInfo", "", 350); - - mFlyBox = mTrayMgr->createCheckBox(TL_BOTTOM, "Fly", "Fly"); - mFlyBox->setChecked(false, true); - - mLodStatusBox = mTrayMgr->createCheckBox(TL_BOTTOM, "LODStatus", "LOD Status"); - mLodStatusBox->setChecked(false, true); - - mAutoBox = mTrayMgr->createCheckBox(TL_BOTTOM, "LODAuto", "Auto LOD"); - mAutoBox->setChecked(true, true); - - // a friendly reminder - StringVector names; - names.push_back("Help"); - mTrayMgr->createParamsPanel(TL_TOPLEFT, "Help", 100, names)->setParamValue(0, "H/F1"); - } - - class SimpleTerrainDefiner : public TerrainPagedWorldSection::TerrainDefiner - { - public: - void define(TerrainGroup* terrainGroup, long x, long y) override - { - Image img; - img.load("terrain.png", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - if (x % 2) - img.flipAroundY(); - if (y % 2) - img.flipAroundX(); - terrainGroup->defineTerrain(x, y, &img); - } - }; - - void setupContent() override - { - mTerrainGlobals = OGRE_NEW TerrainGlobalOptions(); - - mCameraMan->setTopSpeed(100); - - setDragLook(true); - -#if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID - MaterialManager::getSingleton().setDefaultTextureFiltering(TFO_ANISOTROPIC); - MaterialManager::getSingleton().setDefaultAnisotropy(8); -#endif - - mSceneMgr->setFog(FOG_LINEAR, ColourValue(0.7, 0.7, 0.8), 0, 4000, 10000); - - LogManager::getSingleton().setMinLogLevel(LML_TRIVIAL); - - Light* l = mSceneMgr->createLight("tstLight"); - l->setType(Light::LT_DIRECTIONAL); - l->setDiffuseColour(ColourValue::White); - l->setSpecularColour(ColourValue(0.4, 0.4, 0.4)); - - auto ln = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - ln->setDirection(Vector3(0.55, -0.3, 0.75).normalisedCopy()); - ln->attachObject(l); - - mSceneMgr->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); - - mTerrainGroup = OGRE_NEW TerrainGroup(mSceneMgr, Terrain::ALIGN_X_Z, TERRAIN_SIZE, TERRAIN_WORLD_SIZE); - mTerrainGroup->setFilenameConvention(ENDLESS_TERRAIN_FILE_PREFIX, ENDLESS_TERRAIN_FILE_SUFFIX); - mTerrainGroup->setOrigin(mTerrainPos); - mTerrainGroup->setAutoUpdateLod(TerrainAutoUpdateLodFactory::getAutoUpdateLod(BY_DISTANCE)); - - configureTerrainDefaults(l); - - // Paging setup - mPageManager = OGRE_NEW PageManager(); - // Since we're not loading any pages from .page files, we need a way just - // to say we've loaded them without them actually being loaded - mPageManager->setPageProvider(&mDummyPageProvider); - mPageManager->addCamera(mCamera); - mPageManager->setDebugDisplayLevel(0); - mTerrainPaging = OGRE_NEW TerrainPaging(mPageManager); - mPagedWorld = mPageManager->createWorld(); - mTerrainPagedWorldSection = mTerrainPaging->createWorldSection(mPagedWorld, mTerrainGroup, 400, 500, - ENDLESS_PAGE_MIN_X, ENDLESS_PAGE_MIN_Y, - ENDLESS_PAGE_MAX_X, ENDLESS_PAGE_MAX_Y); - -#if USE_PERLIN_DEFINER == 1 - mPerlinNoiseTerrainGenerator = OGRE_NEW PerlinNoiseTerrainGenerator; - mTerrainPagedWorldSection->setDefiner(mPerlinNoiseTerrainGenerator); -#else - mTerrainPagedWorldSection->setDefiner(OGRE_NEW SimpleTerrainDefiner); -#endif - - mTerrainGroup->freeTemporaryResources(); - - mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); - - // setup LOD info overlay - mLodInfoOverlay = OverlayManager::getSingleton().create("LODInfoOverlay"); - - mLodInfoOverlay->setZOrder(10); - mLodInfoOverlayContainer = (OverlayContainer*)OverlayManager::getSingleton().createOverlayElement("Panel", "LODInfoOverlayPanel"); - mLodInfoOverlayContainer->setDimensions(1.0, 1.0); - mLodInfoOverlayContainer->setPosition(0.0, 0.0); - - mLodInfoOverlay->add2D(mLodInfoOverlayContainer); - mLodInfoOverlay->show(); - - setupControls(); - } - - void _shutdown() override - { - if(mTerrainPaging) - { - OGRE_DELETE mTerrainPaging; - mPageManager->removeCamera(mCamera); - mPageManager->destroyWorld( mPagedWorld ); - OGRE_DELETE mPageManager; - } - - if(mTerrainGlobals) - OGRE_DELETE mTerrainGlobals; - - if(mLodInfoOverlay) - OverlayManager::getSingleton().destroy(mLodInfoOverlay); - - if(mLodInfoOverlayContainer) - { - for(LabelList::iterator li = mLodStatusLabelList.begin(); li != mLodStatusLabelList.end(); li++) - { - mLodInfoOverlayContainer->_removeChild(*li); - OverlayManager::getSingleton().destroyOverlayElement(*li); - } - mLodStatusLabelList.clear(); - - OverlayManager::getSingleton().destroyOverlayElement(mLodInfoOverlayContainer); - } - - SdkSample::_shutdown(); - } -}; - -#endif diff --git a/Samples/EndlessWorld/include/PerlinNoiseTerrainGenerator.h b/Samples/EndlessWorld/include/PerlinNoiseTerrainGenerator.h deleted file mode 100644 index 1300b7f4403..00000000000 --- a/Samples/EndlessWorld/include/PerlinNoiseTerrainGenerator.h +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once - -#include "OgreTerrainPagedWorldSection.h" - -#define B 0x100 -using namespace Ogre; - -///Use PerlinNoise algorithm to generate terrain height map -class PerlinNoiseTerrainGenerator : public TerrainPagedWorldSection::TerrainDefiner -{ -public: - /** Constructor of PerlinNoiseTerrainGenerator - @param alpha The weight when the sum is formed - @param beta The harmonic scaling/spacing - @param iterationNum The iterations num to produce a point. - @param cycle The terrain size maps to one cycle of perlin curve - @param heightScale The height maps to curve amplitude - */ - PerlinNoiseTerrainGenerator(const Real& alpha = 3.3, const Real& beta = 2.2, int iterationNum = 10, const Real& cycle = 128, const Real& heightScale = 4); - - /// Define terrain - void define( Ogre::TerrainGroup* terrainGroup, long x, long y ) override; - /// Random terrain origin point to make it looks different - void randomize(); -private: - /** Produce a noise according to PerlinNoise algorithm - Generate multiple values by calling noise(): - v0=noise(x,y), - v1=noise(x*beta,y*beta), - v2=noise(x*beta*beta,y*beta*beta) - ... - Accumulate them: - result = v0/alpha + v1/(alpha*alpha) + v1/(alpha*alpha*alpha) + ... - */ - Real produceSingleHeight(const Vector2& vec2); - - /// Generate a 2D noise - Real noise(const Vector2& vec2); - - inline Real sCurve(const Real& t) const { return t * t * (3 - 2 * t); } - inline Real lerp(const Real& t, const Real& a, const Real& b) const { return a + t*(b - a); } - void setup( const Real& target, int& b0, int& b1, Real& r0, Real& r1); - - Real mAlpha; - Real mBeta; - int mIterationNum; - Real mCycle; - Real mHeightScale; - Vector2 mOriginPoint; - - int p[B + B + 2]; - Vector3 g3[B + B + 2]; - Vector2 g2[B + B + 2]; - Real g1[B + B + 2]; -}; diff --git a/Samples/EndlessWorld/src/PerlinNoiseTerrainGenerator.cpp b/Samples/EndlessWorld/src/PerlinNoiseTerrainGenerator.cpp deleted file mode 100644 index 674e91c9518..00000000000 --- a/Samples/EndlessWorld/src/PerlinNoiseTerrainGenerator.cpp +++ /dev/null @@ -1,125 +0,0 @@ -#include -#include -#include "OgreMath.h" -#include "PerlinNoiseTerrainGenerator.h" - -using namespace Ogre; - -#define BM 0xff -#define N 0x1000 -#define NP 12 /* 2^N */ -#define NM 0xfff - -PerlinNoiseTerrainGenerator::PerlinNoiseTerrainGenerator(const Real& alpha, const Real& beta, int iterationNum, const Real& cycle, const Real& heightScale) - : mAlpha(alpha) - , mBeta(beta) - , mIterationNum(iterationNum) - , mCycle(cycle) - , mHeightScale(heightScale) - , mOriginPoint(0.f) -{ - for (int i = 0 ; i < B ; i++) { - p[i] = i; - g1[i] = Math::SymmetricRandom(); - - g2[i] = Vector2(Math::SymmetricRandom(), Math::SymmetricRandom()); - g2[i].normalise(); - - g3[i] = Vector3(Math::SymmetricRandom(), Math::SymmetricRandom(), Math::SymmetricRandom()); - g3[i].normalise(); - } - - for (int i = 0 ; i < B ; i++) { - int j = (int) Math::RangeRandom (0,B); - - int k = p[i]; - p[i] = p[j]; - p[j] = k; - } - - for (int i = 0 ; i < B + 2 ; i++) { - p[B + i] = p[i]; - g1[B + i] = g1[i]; - g2[B + i] = g2[i]; - g3[B + i] = g3[i]; - } -} - -void PerlinNoiseTerrainGenerator::define( TerrainGroup* terrainGroup, long x, long y ) -{ - uint16 terrainSize = terrainGroup->getTerrainSize(); - float* heightMap = OGRE_ALLOC_T(float, terrainSize*terrainSize, MEMCATEGORY_GEOMETRY); - - Vector2 worldOffset( Real(x*(terrainSize-1)), Real(y*(terrainSize-1)) ); - worldOffset += mOriginPoint; - - Vector2 revisedValuePoint; - for( uint16 i=0; idefineTerrain(x,y,heightMap); - OGRE_FREE(heightMap, MEMCATEGORY_GEOMETRY); -} - -Real PerlinNoiseTerrainGenerator::produceSingleHeight(const Vector2& vec2) -{ - Vector2 tempVec(vec2); - Real sum = 0; - Real scale = 1; - - for (int i=0;isetPosition(0, 0, -40); - mCameraNode->lookAt(Vector3(0,0,0), Node::TS_PARENT); - mCamera->setNearClipDistance(0.1); - mCamera->setFarClipDistance(100); - - mTetrahedraMesh = ProceduralTools::generateTetrahedra(); - // Create tetrahedra and add it to the root scene node - tetrahedra = mSceneMgr->createEntity("TetrahedraEntity", mTetrahedraMesh); - //tetrahedra->setDebugDisplayEnabled(true); - Ogre::SceneNode* parentNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - parentNode->attachObject(tetrahedra); - parentNode->setScale(10,10,10); - } - - void Sample_Isosurf::cleanupContent() - { - MeshManager::getSingleton().remove(mTetrahedraMesh); - } - - bool Sample_Isosurf::frameRenderingQueued(const FrameEvent& evt) - { - Real seconds = (Real)(Root::getSingleton().getTimer()->getMilliseconds()) / 1000.0; - Ogre::Pass* renderPass = tetrahedra->getSubEntity(0)->getMaterial()->getTechnique(0)->getPass(0); - if (renderPass->hasVertexProgram()) - { - Ogre::Vector4 constParam = Ogre::Vector4(-0.5, 0.0, 0.0, 0.2); - renderPass->getVertexProgramParameters()->setNamedConstant("Metaballs[0]", constParam); - - Ogre::Vector4 timeParam = Ogre::Vector4( - 0.1 + Ogre::Math::Sin(seconds)*0.5, Ogre::Math::Cos(seconds)*0.5, 0.0, 0.1); - renderPass->getVertexProgramParameters()->setNamedConstant("Metaballs[1]", timeParam); - } - - return SdkSample::frameRenderingQueued(evt); - } -}; diff --git a/Samples/Isosurf/src/ProceduralTools.cpp b/Samples/Isosurf/src/ProceduralTools.cpp deleted file mode 100644 index 3449f267289..00000000000 --- a/Samples/Isosurf/src/ProceduralTools.cpp +++ /dev/null @@ -1,174 +0,0 @@ -#include "ProceduralTools.h" - -#include "Ogre.h" - -using namespace Ogre; - -//Constants (copied as is from sample) - -// Grid sizes (in vertices) -#define X_SIZE_LOG2 6 -#define Y_SIZE_LOG2 6 -#define Z_SIZE_LOG2 6 -#define TOTAL_POINTS (1<<(X_SIZE_LOG2 + Y_SIZE_LOG2 + Z_SIZE_LOG2)) -#define CELLS_COUNT (((1<>= 1; - pPos[1] = index & 1; - index >>= 1; - pPos[2] = index & 1; - index >>= 1; - - // Treat the rest of the index like a row, column, depth array - // Each dimension needs to grab sizeLog2 - 1 bits - // This will make the blocks traverse the grid in a raster style order - index <<= 1; - pPos[0] = pPos[0] | (index & ( (1 << sizeLog2[0]) - 2)); - index >>= sizeLog2[0] - 1; - pPos[1] = pPos[1] | ( index & ( (1 << sizeLog2[1]) - 2)); - index >>= sizeLog2[1] - 1; - pPos[2] = pPos[2] | ( index & ( (1 << sizeLog2[2]) - 2)); -} - - -MeshPtr ProceduralTools::generateTetrahedra() -{ - MeshPtr tetrahedraMesh = Ogre::MeshManager::getSingleton().createManual - ("TetrahedraMesh", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - SubMesh* tetrahedraSubMesh = tetrahedraMesh->createSubMesh(); - tetrahedraSubMesh->operationType = RenderOperation::OT_LINE_LIST_ADJ; - //tetrahedraSubMesh->operationType = RenderOperation::OT_TRIANGLE_STRIP; - tetrahedraSubMesh->setMaterialName("Ogre/Isosurf/TessellateTetrahedra"); - //tetrahedraSubMesh->setMaterialName("BaseWhiteNoLighting"); - - Ogre::uint sizeLog2[3] = { X_SIZE_LOG2, Y_SIZE_LOG2, Z_SIZE_LOG2 }; - Ogre::uint nTotalBits = sizeLog2[0] + sizeLog2[1] + sizeLog2[2]; - Ogre::uint nPointsTotal = 1 << nTotalBits; - - tetrahedraSubMesh->createVertexData(); - - tetrahedraSubMesh->vertexData->vertexDeclaration->addElement(0, 0, - VET_FLOAT4, VES_POSITION); - - HardwareVertexBufferSharedPtr vertexBuffer = HardwareBufferManager::getSingleton().createVertexBuffer( - tetrahedraSubMesh->vertexData->vertexDeclaration->getVertexSize(0), - nPointsTotal, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - HardwareIndexBufferSharedPtr indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_32BIT, - CELLS_COUNT * sizeof(Ogre::uint) * 24, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - tetrahedraSubMesh->vertexData->vertexBufferBinding->setBinding(0, vertexBuffer); - tetrahedraSubMesh->vertexData->vertexCount = nPointsTotal; - tetrahedraSubMesh->vertexData->vertexStart = 0; - - tetrahedraSubMesh->indexData->indexBuffer = indexBuffer; - - float* positions = static_cast(vertexBuffer->lock(HardwareBuffer::HBL_DISCARD)); - - //Generate positions - for (Ogre::uint i = 0; i < nPointsTotal; i++) - { - Ogre::uint pos[3]; - pos[0] = i & ((1<> X_SIZE_LOG2) & ((1<> (X_SIZE_LOG2+Y_SIZE_LOG2)) & ((1<unlock(); - - Ogre::uint numIndices = 0; - - // Generate indices - Ogre::uint32* indices = static_cast(indexBuffer->lock(HardwareBuffer::HBL_DISCARD)); - - for (Ogre::uint i = 0; i < nPointsTotal; i++) - { - Ogre::uint pos[3]; -#if SWIZZLE - UnSwizzle(i, sizeLog2, pos); // un-swizzle current index to get x, y, z for the current sampling point -#else - pos[0] = i & ((1<> X_SIZE_LOG2) & ((1<> (X_SIZE_LOG2+Y_SIZE_LOG2)) & ((1<unlock(); - - tetrahedraSubMesh->indexData->indexCount = numIndices; - tetrahedraSubMesh->indexData->indexStart = 0; - - AxisAlignedBox meshBounds; - meshBounds.setMinimum(-1,-1,-1); - meshBounds.setMaximum(1,1,1); - tetrahedraMesh->_setBounds(meshBounds); - tetrahedraMesh->_setBoundingSphereRadius(2); - - return tetrahedraMesh; -} diff --git a/Samples/Java/Example.java b/Samples/Java/Example.java deleted file mode 100644 index bd075a3e159..00000000000 --- a/Samples/Java/Example.java +++ /dev/null @@ -1,55 +0,0 @@ -import org.ogre.*; - -public class Example { - static { - System.loadLibrary("OgreJNI"); - } - - public static void main(String[] args) { - final ApplicationContext ctx = new ApplicationContext(); - ctx.initApp(); - - ctx.addInputListener(new InputListener() { - public boolean keyPressed(KeyboardEvent evt) - { - if (evt.getKeysym().getSym() == BitesConstants.SDLK_ESCAPE) - ctx.getRoot().queueEndRendering(); - return true; - } - }); - - Root root = ctx.getRoot(); - SceneManager scnMgr = root.createSceneManager(); - ShaderGenerator.getSingleton().addSceneManager(scnMgr); - - scnMgr.setAmbientLight(new ColourValue(.1f, .1f, .1f)); - - Light light = scnMgr.createLight("MainLight"); - SceneNode lightnode = scnMgr.getRootSceneNode().createChildSceneNode(); - lightnode.setPosition(0, 10, 15); - lightnode.attachObject(light); - - Camera cam = scnMgr.createCamera("myCam"); - SceneNode camnode = scnMgr.getRootSceneNode().createChildSceneNode(); - camnode.attachObject(cam); - camnode.setPosition(0, 0, 15); - - cam.setNearClipDistance(5); - cam.setAutoAspectRatio(true); - - CameraMan camman = new CameraMan(camnode); - camman.setStyle(CameraStyle.CS_ORBIT); - camman.setYawPitchDist(new Radian(0f), new Radian(0.3f), 15); - ctx.addInputListener(camman); - - Viewport vp = ctx.getRenderWindow().addViewport(cam); - vp.setBackgroundColour(new ColourValue(.3f, .3f, .3f)); - - Entity ent = scnMgr.createEntity("Sinbad.mesh"); - SceneNode node = scnMgr.getRootSceneNode().createChildSceneNode(); - node.attachObject(ent); - - ctx.getRoot().startRendering(); - ctx.closeApp(); - } -} diff --git a/Samples/Java/README.md b/Samples/Java/README.md deleted file mode 100644 index 349cc5dbc59..00000000000 --- a/Samples/Java/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Build instructions - -1. copy `lib/OgreJNI.dll` and the contents of `share/java/` to the `bin/` directory -2. copy `Example.java` to the `bin/` directory -3. compile the sample as - ``` - javac Example.java -classpath Ogre-*.jar - ``` -4. Run the sample as - ``` - java -classpath .:Ogre-1.12.12.jar -Djava.library.path=. Example - ``` \ No newline at end of file diff --git a/Samples/Media/CSMShadows/BasicShadowMapReceiver.h b/Samples/Media/CSMShadows/BasicShadowMapReceiver.h deleted file mode 100644 index 197c96602dd..00000000000 --- a/Samples/Media/CSMShadows/BasicShadowMapReceiver.h +++ /dev/null @@ -1,29 +0,0 @@ -/* Copyright 2010-2012 Matthew Paul Reid - This file is subject to the terms and conditions defined in - file 'License.txt', which is part of this source code package. -*/ - -half getShadowFactor -( - uniform sampler2D shadowMapUnit, - float4 lightSpacePos, - uniform float shadowmapSize, - uniform float inverseShadowmapSize, - uniform float fixedDepthBias, - uniform float gradientScaleBias, - half shadowLightDotLN -) -{ - // point on shadowmap - float depthAdjust = fixedDepthBias + (1.0f - abs(shadowLightDotLN)) * gradientScaleBias; - lightSpacePos.z -= depthAdjust; // lightSpacePos.z contains lightspace position of current object - - // Sample each of them checking whether the pixel under test is shadowed or not - float lightMask = (lightSpacePos.z < tex2D_inBranch( shadowMapUnit, lightSpacePos.xy).r); - - // Hack to prevent these getting optimized out, thereby preventing OGRE errors - lightMask += 0.001 * (0.001*shadowmapSize + inverseShadowmapSize); - - // Get the average - return lightMask; -} diff --git a/Samples/Media/CSMShadows/CSMShadows.material b/Samples/Media/CSMShadows/CSMShadows.material deleted file mode 100644 index 74626d74501..00000000000 --- a/Samples/Media/CSMShadows/CSMShadows.material +++ /dev/null @@ -1,156 +0,0 @@ -// CASTER pass -vertex_program ShadowCasterVP cg -{ - source pssm.cg - entry_point shadow_caster_vs - profiles vs_3_0 arbvp1 - - default_params - { - param_named_auto worldViewProjMatrix worldviewproj_matrix - } -} - -fragment_program ShadowCasterFP cg -{ - source pssm.cg - entry_point shadow_caster_ps - profiles ps_3_0 arbfp1 -} - -material CSMShadows/Caster -{ - technique - { - pass - { - vertex_program_ref ShadowCasterVP - { - } - - fragment_program_ref ShadowCasterFP - { - } - } - } -} - -// RECEIVER pass -vertex_program ShadowReceiverVP cg -{ - source ShadowReceiver.cg - entry_point main_vp - profiles vs_3_0 arbvp1 - - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto worldMat world_matrix - param_named_auto texMatrix0 texture_viewproj_matrix 0 - } -} - -shared_params params_shadowMatrixScaleBias -{ - // filled by code -} - -fragment_program ShadowReceiverFP cg -{ - source ShadowReceiver.cg - entry_point main_fp - profiles ps_3_0 arbfp1 - - default_params - { - param_named_auto lightDirection light_direction 0 - param_named_auto ambientColor ambient_light_colour - param_named_auto shadowMapSize packed_texture_size 1 - - shared_params_ref params_shadowMatrixScaleBias - - param_named fixedDepthBias float4 0.0005, 0.001, 0.001, 0.003; - param_named gradientScaleBias float4 0.0005, 0.001, 0.001, 0.003; - param_named shadowFadeDist float 500; - param_named shadowMaxDist float 6000; - } -} - -material CSMShadows/Receiver -{ - technique - { - shadow_caster_material CSMShadows/Caster - pass - { - - vertex_program_ref ShadowReceiverVP - { - } - - fragment_program_ref ShadowReceiverFP - { - } - - texture_unit Diffuse - { - - } - - texture_unit - { - content_type shadow - tex_address_mode clamp - } - texture_unit - { - content_type shadow - tex_address_mode clamp - } - texture_unit - { - content_type shadow - tex_address_mode clamp - } - texture_unit - { - content_type shadow - tex_address_mode clamp - } - - texture_unit - { - texture KernelRotation.png - filtering none - } - } - } -} - -material CSMShadows/Rockwall : CSMShadows/Receiver -{ - technique - { - pass - { - texture_unit Diffuse - { - texture rockwall.tga - } - } - } -} - -material CSMShadows/Athene : CSMShadows/Receiver -{ - technique - { - pass - { - texture_unit Diffuse - { - texture egyptrockyfull.jpg - } - } - } -} diff --git a/Samples/Media/CSMShadows/CsmShadows.h b/Samples/Media/CSMShadows/CsmShadows.h deleted file mode 100644 index 347dc818f5a..00000000000 --- a/Samples/Media/CSMShadows/CsmShadows.h +++ /dev/null @@ -1,113 +0,0 @@ -/* Copyright 2010-2012 Matthew Paul Reid - This file is subject to the terms and conditions defined in - file 'License.txt', which is part of this source code package. -*/ - -uniform float4 fixedDepthBias; -uniform float4 gradientScaleBias; -uniform float4 shadowMapSize; - - - -#define BLENDING // enables blending between cascades - -#ifdef DEBUG_CSM - static half3 cascadeColor = float3(1,1,1); -#endif - -half getCsmShadowFactor -( - uniform sampler2D shadowTexture0, - uniform sampler2D shadowTexture1, - uniform sampler2D shadowTexture2, - uniform sampler2D shadowTexture3, - float4 lightSpacePos0, - float4 lightSpacePos1, - float4 lightSpacePos2, - float4 lightSpacePos3, - half shadowLightDotLN -) -{ - half factor = 1; - - if (lightSpacePos0.x > 0.01 && lightSpacePos0.y > 0.01 && lightSpacePos0.x < 0.99 && lightSpacePos0.y < 0.99) - { - factor = getShadowFactor(shadowTexture0, lightSpacePos0, shadowMapSize.x, shadowMapSize.z, - fixedDepthBias.x, gradientScaleBias.x, shadowLightDotLN); - - #ifdef DEBUG_CSM - cascadeColor = float3(1,0,0); - #endif - - #ifdef BLENDING - half blend = getShadowFactor(shadowTexture1, lightSpacePos1, shadowMapSize.x, shadowMapSize.z, - fixedDepthBias.y, gradientScaleBias.y, shadowLightDotLN); - - half weight = saturate((max( abs(lightSpacePos0.x-0.5), abs(lightSpacePos0.y-0.5)) -0.375) * 8); - factor = lerp (factor, blend, weight); - - #ifdef DEBUG_CSM - cascadeColor = lerp(cascadeColor, float3(0,1,0), weight); - #endif - - #endif - - } - else if (lightSpacePos1.x > 0.01 && lightSpacePos1.y > 0.01 && lightSpacePos1.x < 0.99 && lightSpacePos1.y < 0.99) - { - factor = getShadowFactor(shadowTexture1, lightSpacePos1, shadowMapSize.x, shadowMapSize.z, - fixedDepthBias.y, gradientScaleBias.y, shadowLightDotLN); - - #ifdef DEBUG_CSM - cascadeColor = float3(0,1,0); - #endif - - #ifdef BLENDING - half blend = getShadowFactor(shadowTexture2, lightSpacePos2, shadowMapSize.x, shadowMapSize.z, - fixedDepthBias.z, gradientScaleBias.z, shadowLightDotLN); - half weight = saturate((max( abs(lightSpacePos1.x-0.5), abs(lightSpacePos1.y-0.5) ) -0.4375) * 16); - factor = lerp (factor, blend, weight); - - #ifdef DEBUG_CSM - cascadeColor = lerp(cascadeColor, float3(0,0,1), weight); - #endif - - #endif - } - else if (lightSpacePos2.x > 0.01 && lightSpacePos2.y > 0.01 && lightSpacePos2.x < 0.99 && lightSpacePos2.y < 0.99) - { - factor = getShadowFactor(shadowTexture2, lightSpacePos2, shadowMapSize.x, shadowMapSize.z, - fixedDepthBias.z, gradientScaleBias.z, shadowLightDotLN); - - #ifdef DEBUG_CSM - cascadeColor = float3(0,0,1); - #endif - - #ifdef BLENDING - half blend = getShadowFactor(shadowTexture3, lightSpacePos3, shadowMapSize.x, shadowMapSize.z, - fixedDepthBias.w, gradientScaleBias.w, shadowLightDotLN); - - half weight = saturate((max( abs(lightSpacePos2.x-0.5), abs(lightSpacePos2.y-0.5)) -0.375) * 8); - factor = lerp (factor, blend, weight); - - #ifdef DEBUG_CSM - cascadeColor = lerp(cascadeColor, float3(1,1,0), weight); - #endif - #endif - } - else - { - factor = getShadowFactor(shadowTexture3, lightSpacePos3, shadowMapSize.x, shadowMapSize.z, - fixedDepthBias.w, gradientScaleBias.w, shadowLightDotLN); - - // Fade out to edges - half weight = saturate((max( abs(lightSpacePos3.x-0.5), abs(lightSpacePos3.y-0.5)) -0.375) * 8); - factor = lerp (factor, 1, weight); - - #ifdef DEBUG_CSM - cascadeColor = float3(1,1,weight); - #endif - } - - return factor; -} diff --git a/Samples/Media/CSMShadows/DepthShadowMapReceiverJitter.h b/Samples/Media/CSMShadows/DepthShadowMapReceiverJitter.h deleted file mode 100644 index d31761dbe48..00000000000 --- a/Samples/Media/CSMShadows/DepthShadowMapReceiverJitter.h +++ /dev/null @@ -1,62 +0,0 @@ -/* Copyright 2010-2012 Matthew Paul Reid - This file is subject to the terms and conditions defined in - file 'License.txt', which is part of this source code package. -*/ - -float2 offsetSample(float2 uv, float2 offset, float invMapSize) -{ - return float2(uv.xy + offset * invMapSize); -} - -float2 offsetRotateSample(float2 uv, float2 offset, float2x2 rotMat, float invMapSize) -{ - offset = mul(rotMat, offset); - return float2(uv.xy + offset * invMapSize); -} - - -half getShadowFactor -( - uniform sampler2D shadowMapUnit, - float4 lightSpacePos, - uniform float shadowmapSize, - uniform float inverseShadowmapSize, - uniform float fixedDepthBias, - uniform float gradientScaleBias, - half shadowLightDotLN -) -{ - // point on shadowmap - float depthAdjust = fixedDepthBias + (1.0f - abs(shadowLightDotLN)) * gradientScaleBias; - lightSpacePos.z -= depthAdjust; // lightSpacePos.z contains lightspace position of current object - - const float radius = 3.0f; - const float4 offsets[4] = { float4(-0.3464376f, -0.7120676f, 0.4692491f, -0.7939163f) * radius, - float4(0.1561844f, -0.04416115f, -0.9133415f, -0.3314315f) * radius, - float4(-0.4210564f, 0.4838058f, 0.5794852f, 0.474482f) * radius, - float4(0.7723071f, -0.2627881f, 0.07587272f, 0.926478f) * radius}; - - - - float2 rotations = tex2D_inBranch( jitterMapUnit, lightSpacePos.xy * shadowmapSize) * 2 - 1; - float2x2 rotMat = float2x2(rotations.x, -rotations.y, rotations.y, rotations.x); - - half4 shadows; - shadows.r = tex2D_inBranch( shadowMapUnit, offsetRotateSample( lightSpacePos.xy, offsets[0].xy, rotMat, inverseShadowmapSize)); - shadows.g = tex2D_inBranch( shadowMapUnit, offsetRotateSample( lightSpacePos.xy, offsets[0].zw, rotMat, inverseShadowmapSize)); - shadows.b = tex2D_inBranch( shadowMapUnit, offsetRotateSample( lightSpacePos.xy, offsets[1].xy, rotMat, inverseShadowmapSize)); - shadows.a = tex2D_inBranch( shadowMapUnit, offsetRotateSample( lightSpacePos.xy, offsets[1].zw, rotMat, inverseShadowmapSize)); - - half4 inLight = (lightSpacePos.zzzz < shadows); - half shadow = dot( inLight, half4(0.125, 0.125, 0.125, 0.125) ); - - shadows.r = tex2D_inBranch( shadowMapUnit, offsetRotateSample( lightSpacePos.xy, offsets[2].xy, rotMat, inverseShadowmapSize)); - shadows.g = tex2D_inBranch( shadowMapUnit, offsetRotateSample( lightSpacePos.xy, offsets[2].zw, rotMat, inverseShadowmapSize)); - shadows.b = tex2D_inBranch( shadowMapUnit, offsetRotateSample( lightSpacePos.xy, offsets[3].xy, rotMat, inverseShadowmapSize)); - shadows.a = tex2D_inBranch( shadowMapUnit, offsetRotateSample( lightSpacePos.xy, offsets[3].zw, rotMat, inverseShadowmapSize)); - - inLight = (lightSpacePos.zzzz < shadows); - shadow += dot( inLight, half4(0.125, 0.125, 0.125, 0.125) ); - //shadow = 0.001 * shadow + rotations.x; - return shadow; -} diff --git a/Samples/Media/CSMShadows/KernelRotation.png b/Samples/Media/CSMShadows/KernelRotation.png deleted file mode 100644 index 9f5f20baedf..00000000000 Binary files a/Samples/Media/CSMShadows/KernelRotation.png and /dev/null differ diff --git a/Samples/Media/CSMShadows/ShadowReceiver.cg b/Samples/Media/CSMShadows/ShadowReceiver.cg deleted file mode 100644 index 4ff59a163c6..00000000000 --- a/Samples/Media/CSMShadows/ShadowReceiver.cg +++ /dev/null @@ -1,118 +0,0 @@ -/* Copyright 2010-2012 Matthew Paul Reid - This file is subject to the terms and conditions defined in - file 'License.txt', which is part of this source code package. -*/ - -uniform sampler2D diffuseTexture : register(s0); -uniform sampler2D shadowTexture0 : register(s1); -uniform sampler2D shadowTexture1 : register(s2); -uniform sampler2D shadowTexture2 : register(s3); -uniform sampler2D shadowTexture3 : register(s4); -uniform sampler2D jitterMapUnit : register(s5); - - -//#define DEBUG_CSM // enables cascade debug visualisation -#define JITTER_SHADOWS // enables poisson disk jitter filtering - -arbfp1 float4 tex2D_inBranch(uniform sampler2D sampler, float2 texCoords) -{ - return tex2D(sampler, texCoords); -} - -ps_3_0 float4 tex2D_inBranch(uniform sampler2D sampler, float2 texCoords) -{ - return tex2D(sampler, texCoords, 0, 0); -} - -#ifdef JITTER_SHADOWS -#include "DepthShadowMapReceiverJitter.h" -#else -#include "BasicShadowMapReceiver.h" -#endif -#include "CsmShadows.h" - -#define PACKED_VIEWMATRIX -#ifdef PACKED_VIEWMATRIX -uniform float4 texMatrixScaleBias1; -uniform float4 texMatrixScaleBias2; -uniform float4 texMatrixScaleBias3; -#endif - -void main_vp -( - float4 iPosition : POSITION, - float3 iNormal : NORMAL, - float4 iTexCoord0 : TEXCOORD0, - float4 iColor : COLOR0, - - out float4 oPosition : POSITION, - out float4 oTexCoord0 : TEXCOORD0, - out float3 oNormal : TEXCOORD1, - out float4 oShadowLightspacePos0 : TEXCOORD2, - - uniform float4x4 worldViewProj, - uniform float4x4 worldMat, - uniform float4x4 texMatrix0 -) -{ - oPosition = mul(worldViewProj, iPosition); - oTexCoord0 = iTexCoord0; - oNormal = normalize(mul(float3x3(worldMat), iNormal)); - - // Calculate vertex position in light space - float4 worldPos = mul(worldMat, iPosition); - oShadowLightspacePos0 = mul(texMatrix0, worldPos); - - // Store vertex distance from camera for use in shadows - oTexCoord0.z = oPosition.z; -} - -void main_fp -( - float4 iTexCoord0 : TEXCOORD0, - float3 iNormal : TEXCOORD1, - float4 iShadowLightspacePos0 : TEXCOORD2, - out float4 oColor : COLOR0, - - uniform float4 lightDirection, - uniform float4 ambientColor, - uniform float shadowFadeDist, - uniform float shadowMaxDist -) -{ - float lDotN = dot(iNormal.xyz, -lightDirection.xyz); - half3 lambert = saturate(lDotN); - - float4 iShadowLightspacePos1; - iShadowLightspacePos1.xyz = iShadowLightspacePos0.xyz + texMatrixScaleBias1.xyz; - iShadowLightspacePos1.xy *= texMatrixScaleBias1.w; - - float4 iShadowLightspacePos2; - iShadowLightspacePos2.xyz = iShadowLightspacePos0.xyz + texMatrixScaleBias2.xyz; - iShadowLightspacePos2.xy *= texMatrixScaleBias2.w; - - float4 iShadowLightspacePos3; - iShadowLightspacePos3.xyz = iShadowLightspacePos0.xyz + texMatrixScaleBias3.xyz; - iShadowLightspacePos3.xy *= texMatrixScaleBias3.w; - - half shadow = getCsmShadowFactor(shadowTexture0, shadowTexture1, shadowTexture2, shadowTexture3, - iShadowLightspacePos0, iShadowLightspacePos1, iShadowLightspacePos2, iShadowLightspacePos3, lDotN); - - // Fade out shadows near max distance - half weight = saturate(((iTexCoord0.z + shadowFadeDist) - shadowMaxDist) / shadowFadeDist); - shadow = lerp(shadow, 1, weight); - - // Mask lambert by shadow - lambert *= shadow; - - // Calculate total pixel brightness - float4 brightness = float4(ambientColor.rgb + lambert, 1); - - // - oColor = tex2D(diffuseTexture, iTexCoord0.xy) * brightness; - oColor.a = 1; - -#ifdef DEBUG_CSM - oColor.rgb *= cascadeColor; -#endif -} diff --git a/Samples/Media/DeferredShadingMedia/COPYING b/Samples/Media/DeferredShadingMedia/COPYING deleted file mode 100755 index f26726f9775..00000000000 --- a/Samples/Media/DeferredShadingMedia/COPYING +++ /dev/null @@ -1,18 +0,0 @@ -Copyright (c) W.J. van der Laan - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the -Software, and to permit persons to whom the Software is furnished to do so, subject -to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies -or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Samples/Media/DeferredShadingMedia/DeferredShading/post/Ambient_ps.cg b/Samples/Media/DeferredShadingMedia/DeferredShading/post/Ambient_ps.cg deleted file mode 100644 index c77cbcae329..00000000000 --- a/Samples/Media/DeferredShadingMedia/DeferredShading/post/Ambient_ps.cg +++ /dev/null @@ -1,66 +0,0 @@ -/****************************************************************************** -Copyright (c) W.J. van der Laan - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the -Software, and to permit persons to whom the Software is furnished to do so, subject -to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies -or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ -/** Deferred shading framework - // W.J. :wumpus: van der Laan 2005 // - - Post shader: Multipass, ambient (base) pass -*/ - - -#include "HLSL_SM4Support.hlsl" - -SAMPLER2D(Tex0, 0); -SAMPLER2D(Tex1, 1); - -float finalDepth(float4 p) -{ - // normally it's in [-1..1] - return p.z / p.w; -} - -void main( - float4 oPos: POSITION, - float2 texCoord: TEXCOORD0, - float3 ray : TEXCOORD1, - - out float4 oColour : COLOR, - out float oDepth : DEPTH, - - uniform float4x4 proj, - uniform float4 ambientColor, - uniform float3 farCorner, - uniform float farClipDistance - ) -{ - float4 a0 = tex2D(Tex0, texCoord); // Attribute 0: Diffuse color+shininess - float4 a1 = tex2D(Tex1, texCoord); // Attribute 1: Normal+depth - - // Clip fragment if depth is too close, so the skybox can be rendered on the background - clip(a1.w-0.0001); - - // Calculate ambient colour of fragment - oColour = float4( ambientColor*float4(a0.rgb ,0)); - - // Calculate depth of fragment; - float3 viewPos = normalize(ray) * farClipDistance * a1.w; - float4 projPos = mul( proj, float4(viewPos, 1) ); - oDepth = finalDepth(projPos); -} diff --git a/Samples/Media/DeferredShadingMedia/DeferredShading/post/Ambient_ps.glsl b/Samples/Media/DeferredShadingMedia/DeferredShading/post/Ambient_ps.glsl deleted file mode 100644 index 39bef64272d..00000000000 --- a/Samples/Media/DeferredShadingMedia/DeferredShading/post/Ambient_ps.glsl +++ /dev/null @@ -1,65 +0,0 @@ -/****************************************************************************** -Copyright (c) W.J. van der Laan - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the -Software, and to permit persons to whom the Software is furnished to do so, subject -to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies -or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ -/** Deferred shading framework - // W.J. :wumpus: van der Laan 2005 // - - Post shader: Multipass, ambient (base) pass -*/ -#ifdef GL_ES -#version 300 es -#else -#version 150 -#endif - -in vec2 oUv0; -in vec3 oRay; - -out vec4 oColour; - -uniform sampler2D Tex0; -uniform sampler2D Tex1; -uniform mat4 proj; -uniform vec4 ambientColor; -uniform float farClipDistance; - -float finalDepth(vec4 p) -{ - // GL needs it in [0..1] - return (p.z / p.w) * 0.5 + 0.5; -} - -void main() -{ - vec4 a0 = texture(Tex0, oUv0); // Attribute 0: Diffuse color+shininess - vec4 a1 = texture(Tex1, oUv0); // Attribute 1: Normal+depth - - // Clip fragment if depth is too close, so the skybox can be rendered on the background - if(a1.w > 0.95) - discard; - - // Calculate ambient colour of fragment - oColour = vec4(ambientColor * vec4(a0.rgb,0)); - - // Calculate depth of fragment; - vec3 viewPos = normalize(oRay) * farClipDistance * a1.w; - vec4 projPos = proj * vec4(viewPos, 1); - gl_FragDepth = finalDepth(projPos); -} diff --git a/Samples/Media/DeferredShadingMedia/DeferredShading/post/LightMaterial_ps.cg b/Samples/Media/DeferredShadingMedia/DeferredShading/post/LightMaterial_ps.cg deleted file mode 100644 index 569eb6e4753..00000000000 --- a/Samples/Media/DeferredShadingMedia/DeferredShading/post/LightMaterial_ps.cg +++ /dev/null @@ -1,182 +0,0 @@ -/****************************************************************************** -Copyright (c) W.J. van der Laan - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the -Software, and to permit persons to whom the Software is furnished to do so, subject -to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies -or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ -/** Deferred shading framework - // W.J. :wumpus: van der Laan 2005 // - - Post shader: Light geometry material -*/ - -#define LIGHT_POINT 1 -#define LIGHT_SPOT 2 -#define LIGHT_DIRECTIONAL 3 - -////////////////////////////////////////////////////////////////////////////// -// Helper function section -////////////////////////////////////////////////////////////////////////////// - -//DirectX needs this to compensate for jitter -float2 fixUV(float2 texCoord, float2 texSize) -{ - return texCoord - (float2(0.5,0.5)/texSize); -} - - -void checkShadow( - sampler2D shadowMap, - float3 viewPos, - float4x4 invView, - float4x4 shadowViewProj, - float shadowFarClip, -#if LIGHT_TYPE == LIGHT_DIRECTIONAL - float3 shadowCamPos -#else - float distanceFromLight -#endif - ) -{ - float3 worldPos = mul(invView, float4(viewPos, 1)).xyz; -#if LIGHT_TYPE == LIGHT_DIRECTIONAL - float distanceFromLight = length(shadowCamPos-worldPos); -#endif - float4 shadowProjPos = mul(shadowViewProj, float4(worldPos,1)); - shadowProjPos /= shadowProjPos.w; - float2 shadowSampleTexCoord = shadowProjPos.xy; - float shadowDepth = tex2D(shadowMap, shadowSampleTexCoord).r; - float shadowDistance = shadowDepth * shadowFarClip; - clip(shadowDistance - distanceFromLight + 0.1); -} - -////////////////////////////////////////////////////////////////////////////// -// Main shader section -////////////////////////////////////////////////////////////////////////////// - -float4 main( - float4 oPos: POSITION, -#if LIGHT_TYPE == LIGHT_DIRECTIONAL - float2 texCoord : TEXCOORD0, - float3 ray : TEXCOORD1, -#else - float4 projPos : TEXCOORD0, -#endif - - uniform sampler Tex0: register(s0), - uniform sampler Tex1: register(s1), - -#if LIGHT_TYPE != LIGHT_POINT - uniform float3 lightDir, -#endif - -#if LIGHT_TYPE == LIGHT_SPOT - uniform float4 spotParams, -#endif - -#if LIGHT_TYPE != LIGHT_DIRECTIONAL - uniform float vpWidth, - uniform float vpHeight, - uniform float3 farCorner, - uniform float flip, -#endif - -#ifdef IS_SHADOW_CASTER - uniform float4x4 invView, - uniform float4x4 shadowViewProjMat, - uniform sampler ShadowTex : register(s2), - uniform float3 shadowCamPos, - uniform float shadowFarClip, -#endif - - uniform float farClipDistance, - // Attributes of light - uniform float4 lightDiffuseColor, - uniform float4 lightSpecularColor, - uniform float4 lightFalloff, - uniform float3 lightPos - ) : COLOR -{ - - //None directional lights have some calculations to do in the beginning of the pixel shader -#if LIGHT_TYPE != LIGHT_DIRECTIONAL - projPos /= projPos.w; - // -1 is because generally +Y is down for textures but up for the screen - float2 texCoord = float2(projPos.x, projPos.y * -1 * flip) * 0.5 + 0.5; - // Texture coordinate magic, this compensates for jitter - texCoord = fixUV(texCoord, float2(vpWidth, vpHeight)); - float3 ray = float3(projPos.x, projPos.y * flip, 1) * farCorner; -#endif - - float4 a0 = tex2D(Tex0, texCoord); // Attribute 0: Diffuse color+shininess - float4 a1 = tex2D(Tex1, texCoord); // Attribute 1: Normal+depth - - // Attributes - float3 colour = a0.rgb; - float specularity = a0.a; - float distance = a1.w; // Distance from viewer (w) - float3 normal = a1.xyz; - - // Calculate position of texel in view space - float3 viewPos = normalize(ray)*distance*farClipDistance; - - // Calculate light direction and distance -#if LIGHT_TYPE == LIGHT_DIRECTIONAL - float3 objToLightDir = -lightDir.xyz; -#else - float3 objToLightVec = lightPos - viewPos; - float len_sq = dot(objToLightVec, objToLightVec); - float len = sqrt(len_sq); - float3 objToLightDir = objToLightVec/len; -#endif - -#ifdef IS_SHADOW_CASTER - #if LIGHT_TYPE == LIGHT_DIRECTIONAL - checkShadow(ShadowTex, viewPos, invView, shadowViewProjMat, shadowFarClip, shadowCamPos); - #else - checkShadow(ShadowTex, viewPos, invView, shadowViewProjMat, shadowFarClip, len); - #endif -#endif - - // Calculate diffuse colour - float3 total_light_contrib; - total_light_contrib = max(0.0,dot(objToLightDir, normal)) * lightDiffuseColor.rgb; - -#if IS_SPECULAR - // Calculate specular component - float3 viewDir = -normalize(viewPos); - float3 h = normalize(viewDir + objToLightDir); - float3 light_specular = pow(dot(normal, h),32.0) * lightSpecularColor.rgb; - - total_light_contrib += specularity * light_specular; -#endif - -#if IS_ATTENUATED - clip(lightFalloff.x - len); - // Calculate attenuation - float attenuation = dot(lightFalloff.yzw, float3(1.0, len, len_sq)); - total_light_contrib /= attenuation; -#endif - -#if LIGHT_TYPE == LIGHT_SPOT - float spotlightAngle = saturate(dot(lightDir.xyz, -objToLightDir)); - float spotFalloff = saturate((spotlightAngle - spotParams.x) / (spotParams.y - spotParams.x)); - total_light_contrib *= (1-spotFalloff); -#endif - - return float4(total_light_contrib*colour, 0.0); -} diff --git a/Samples/Media/DeferredShadingMedia/DeferredShading/post/LightMaterial_ps.glsl b/Samples/Media/DeferredShadingMedia/DeferredShading/post/LightMaterial_ps.glsl deleted file mode 100644 index 711f6949f46..00000000000 --- a/Samples/Media/DeferredShadingMedia/DeferredShading/post/LightMaterial_ps.glsl +++ /dev/null @@ -1,180 +0,0 @@ -/****************************************************************************** -Copyright (c) W.J. van der Laan - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the -Software, and to permit persons to whom the Software is furnished to do so, subject -to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies -or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ -/** Deferred shading framework - // W.J. :wumpus: van der Laan 2005 // - - Post shader: Light geometry material -*/ - -#define LIGHT_POINT 1 -#define LIGHT_SPOT 2 -#define LIGHT_DIRECTIONAL 3 - -////////////////////////////////////////////////////////////////////////////// -// Helper function section -////////////////////////////////////////////////////////////////////////////// -#ifdef GL_ES -#version 300 es -#else -#version 150 -#endif - -void checkShadow( - sampler2D shadowMap, - vec3 viewPos, - mat4 invView, - mat4 shadowViewProj, - float shadowFarClip, -#if LIGHT_TYPE == LIGHT_DIRECTIONAL - vec3 shadowCamPos -#else - float distanceFromLight -#endif - ) -{ - vec3 worldPos = (invView * vec4(viewPos, 1)).xyz; -#if LIGHT_TYPE == LIGHT_DIRECTIONAL - float distanceFromLight = length(shadowCamPos-worldPos); -#endif - vec4 shadowProjPos = shadowViewProj * vec4(worldPos,1); - shadowProjPos /= shadowProjPos.w; - vec2 shadowSampleTexCoord = shadowProjPos.xy; - float shadowDepth = texture(shadowMap, shadowSampleTexCoord).r; - float shadowDistance = shadowDepth * shadowFarClip; - if((shadowDistance - distanceFromLight + 0.1) < 0.0) - discard; -} - -////////////////////////////////////////////////////////////////////////////// -// Main shader section -////////////////////////////////////////////////////////////////////////////// - -#if LIGHT_TYPE == LIGHT_DIRECTIONAL -in vec2 oUv0; -in vec3 oRay; -#else -in vec4 oPos; -#endif - -uniform sampler2D Tex0; -uniform sampler2D Tex1; - -#if LIGHT_TYPE != LIGHT_POINT -uniform vec3 lightDir; -#endif - -#if LIGHT_TYPE == LIGHT_SPOT -uniform vec4 spotParams; -#endif - -#if LIGHT_TYPE != LIGHT_DIRECTIONAL -uniform float vpWidth; -uniform float vpHeight; -uniform vec3 farCorner; -uniform float flip; -#endif - -#ifdef IS_SHADOW_CASTER -uniform mat4 invView; -uniform mat4 shadowViewProjMat; -uniform sampler2D ShadowTex; -uniform vec3 shadowCamPos; -uniform float shadowFarClip; -#endif - -uniform float farClipDistance; -// Attributes of light -uniform vec4 lightDiffuseColor; -uniform vec4 lightSpecularColor; -uniform vec4 lightFalloff; -uniform vec3 lightPos; - -out vec4 fragColour; - -void main() -{ - // None directional lights have some calculations to do in the beginning of the pixel shader -#if LIGHT_TYPE != LIGHT_DIRECTIONAL - vec4 normProjPos = oPos / oPos.w; - // -1 is because generally +Y is down for textures but up for the screen - vec2 oUv0 = vec2(normProjPos.x, normProjPos.y * -1.0 * flip) * 0.5 + 0.5; - vec3 oRay = vec3(normProjPos.x, normProjPos.y * flip, 1.0) * farCorner; -#endif - - vec4 a0 = texture(Tex0, oUv0); // Attribute 0: Diffuse color+shininess - vec4 a1 = texture(Tex1, oUv0); // Attribute 1: Normal+depth - - // Attributes - vec3 colour = a0.rgb; - float specularity = a0.a; - float distance = a1.w; // Distance from viewer (w) - vec3 normal = a1.xyz; - - // Calculate position of texel in view space - vec3 viewPos = normalize(oRay)*distance*farClipDistance; - - // Calculate light direction and distance -#if LIGHT_TYPE == LIGHT_DIRECTIONAL - vec3 objToLightDir = -lightDir.xyz; -#else - vec3 objToLightVec = lightPos - viewPos; - float len_sq = dot(objToLightVec, objToLightVec); - float len = sqrt(len_sq); - vec3 objToLightDir = objToLightVec/len; -#endif - -#ifdef IS_SHADOW_CASTER - #if LIGHT_TYPE == LIGHT_DIRECTIONAL - checkShadow(ShadowTex, viewPos, invView, shadowViewProjMat, shadowFarClip, shadowCamPos); - #else - checkShadow(ShadowTex, viewPos, invView, shadowViewProjMat, shadowFarClip, len); - #endif -#endif - - // Calculate diffuse colour - vec3 total_light_contrib; - total_light_contrib = max(0.0,dot(objToLightDir, normal)) * lightDiffuseColor.rgb; - -#if IS_SPECULAR - // Calculate specular component - vec3 viewDir = -normalize(viewPos); - vec3 h = normalize(viewDir + objToLightDir); - vec3 light_specular = pow(dot(normal, h),32.0) * lightSpecularColor.rgb; - - total_light_contrib += specularity * light_specular; -#endif - -#if IS_ATTENUATED - if(lightFalloff.x - len < 0.0) - discard; - // Calculate attenuation - float attenuation = dot(lightFalloff.yzw, vec3(1.0, len, len_sq)); - total_light_contrib /= attenuation; -#endif - -#if LIGHT_TYPE == LIGHT_SPOT - float spotlightAngle = clamp(dot(lightDir.xyz, -objToLightDir), 0.0, 1.0); - float spotFalloff = clamp((spotlightAngle - spotParams.x) / (spotParams.y - spotParams.x), 0.0, 1.0); - total_light_contrib *= (1.0-spotFalloff); -#endif - - fragColour = vec4(total_light_contrib*colour, 0.0); -} diff --git a/Samples/Media/DeferredShadingMedia/DeferredShading/post/LightMaterial_vs.cg b/Samples/Media/DeferredShadingMedia/DeferredShading/post/LightMaterial_vs.cg deleted file mode 100644 index a9b3bf4c1d8..00000000000 --- a/Samples/Media/DeferredShadingMedia/DeferredShading/post/LightMaterial_vs.cg +++ /dev/null @@ -1,53 +0,0 @@ -/****************************************************************************** -Copyright (c) W.J. van der Laan - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the -Software, and to permit persons to whom the Software is furnished to do so, subject -to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies -or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ -/** Deferred shading framework - // W.J. :wumpus: van der Laan 2005 // - - Post shader: Light geometry material -*/ - -void main( - float4 Pos: POSITION, - - out float4 oPos: POSITION, - out float4 oTexCoord : TEXCOORD0, - - uniform float4x4 worldViewProj - ) -{ - float4 projPos = mul(worldViewProj, Pos); - oTexCoord = projPos; - - oPos = projPos; - - // projPos is now in nonhomogeneous 2d space -- this makes sure no perspective interpolation is - // done that could mess with our concept. - //projPos = projPos/projPos.w; - //oRay = float3(projPos.x, projPos.y * flip, 1) * farCorner; - - - // -1 is because generally +Y is down for textures but up for the screen - //float2 uv = float2(projPos.x, projPos.y * -1) * 0.5 + 0.5; - - // Texture coordinate magic, this compensates for jitter - //float2 texCoord = float2(projPos[0]/2+0.5, -projPos[1]/2+0.5); - //oTexCoord = fixUV(uv, float2(vpWidth, vpHeight)); -} diff --git a/Samples/Media/DeferredShadingMedia/DeferredShading/post/LightMaterial_vs.glsl b/Samples/Media/DeferredShadingMedia/DeferredShading/post/LightMaterial_vs.glsl deleted file mode 100644 index 8c22a35fbbe..00000000000 --- a/Samples/Media/DeferredShadingMedia/DeferredShading/post/LightMaterial_vs.glsl +++ /dev/null @@ -1,44 +0,0 @@ -/****************************************************************************** -Copyright (c) W.J. van der Laan - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the -Software, and to permit persons to whom the Software is furnished to do so, subject -to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies -or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ -/** Deferred shading framework - // W.J. :wumpus: van der Laan 2005 // - - Post shader: Light geometry material -*/ -#ifdef GL_ES -#version 300 es -#else -#version 150 -#endif - -in vec4 vertex; - -out vec4 oPos; -out vec2 oUv0; - -uniform mat4 worldViewProj; - -void main() -{ - gl_Position = worldViewProj * vertex; - oPos = gl_Position; - oUv0 = gl_Position.xy; -} diff --git a/Samples/Media/DeferredShadingMedia/DeferredShading/post/ShowColour_ps.cg b/Samples/Media/DeferredShadingMedia/DeferredShading/post/ShowColour_ps.cg deleted file mode 100644 index dc94b560862..00000000000 --- a/Samples/Media/DeferredShadingMedia/DeferredShading/post/ShowColour_ps.cg +++ /dev/null @@ -1,42 +0,0 @@ -/****************************************************************************** -Copyright (c) W.J. van der Laan - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the -Software, and to permit persons to whom the Software is furnished to do so, subject -to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies -or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ -/** Deferred shading framework - // W.J. :wumpus: van der Laan 2005 // - - Post shader: Debug, show colour channel -*/ - - -float4 main( - float4 oPos: POSITION, - float2 texCoord: TEXCOORD0, - float2 projCoord: TEXCOORD1, - - uniform sampler Tex0: register(s0), - uniform sampler Tex1: register(s1) - ) : COLOR -{ - float4 a0 = tex2D(Tex0, texCoord); // Attribute 0: Diffuse color+shininess - float4 a1 = tex2D(Tex1, texCoord); // Attribute 1: Normal+depth - - return float4(a0.xyz, 0); -} - diff --git a/Samples/Media/DeferredShadingMedia/DeferredShading/post/ShowColour_ps.glsl b/Samples/Media/DeferredShadingMedia/DeferredShading/post/ShowColour_ps.glsl deleted file mode 100644 index 5590885aee3..00000000000 --- a/Samples/Media/DeferredShadingMedia/DeferredShading/post/ShowColour_ps.glsl +++ /dev/null @@ -1,35 +0,0 @@ -/****************************************************************************** -Copyright (c) W.J. van der Laan - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the -Software, and to permit persons to whom the Software is furnished to do so, subject -to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies -or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ -/** Deferred shading framework - // W.J. :wumpus: van der Laan 2005 // - - Post shader: Debug, show colour channel -*/ -uniform sampler2D Tex0; - -varying vec2 oUv0; - -void main() -{ - vec4 a0 = texture2D(Tex0, oUv0); // Attribute 0: Diffuse color+shininess - - gl_FragColor = vec4(a0.xyz, 0); -} diff --git a/Samples/Media/DeferredShadingMedia/DeferredShading/post/ShowDS_ps.cg b/Samples/Media/DeferredShadingMedia/DeferredShading/post/ShowDS_ps.cg deleted file mode 100644 index 6fb8df99178..00000000000 --- a/Samples/Media/DeferredShadingMedia/DeferredShading/post/ShowDS_ps.cg +++ /dev/null @@ -1,41 +0,0 @@ -/****************************************************************************** -Copyright (c) W.J. van der Laan - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the -Software, and to permit persons to whom the Software is furnished to do so, subject -to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies -or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ -/** Deferred shading framework - // W.J. :wumpus: van der Laan 2005 // - - Post shader: Debug, show depth and specularity channel -*/ -float4 main( - float4 oPos: POSITION, - float2 texCoord: TEXCOORD0, - float2 projCoord: TEXCOORD1, - - uniform sampler Tex0: register(s0), - uniform sampler Tex1: register(s1) - ) : COLOR -{ - float4 a0 = tex2D(Tex0, texCoord); // Attribute 0: Diffuse color+shininess - float4 a1 = tex2D(Tex1, texCoord); // Attribute 1: Normal+depth - - //Get the 3rd root of the depth to show up-close differences - return float4(pow(a1.w,0.33), 0, a0.w, 0); -} - diff --git a/Samples/Media/DeferredShadingMedia/DeferredShading/post/ShowDS_ps.glsl b/Samples/Media/DeferredShadingMedia/DeferredShading/post/ShowDS_ps.glsl deleted file mode 100644 index 57ab9035c78..00000000000 --- a/Samples/Media/DeferredShadingMedia/DeferredShading/post/ShowDS_ps.glsl +++ /dev/null @@ -1,38 +0,0 @@ -/****************************************************************************** -Copyright (c) W.J. van der Laan - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the -Software, and to permit persons to whom the Software is furnished to do so, subject -to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies -or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ -/** Deferred shading framework - // W.J. :wumpus: van der Laan 2005 // - - Post shader: Debug, show depth and specularity channel -*/ -uniform sampler2D Tex0; -uniform sampler2D Tex1; - -varying vec2 oUv0; - -void main() -{ - vec4 a0 = texture2D(Tex0, oUv0); // Attribute 0: Diffuse color+shininess - vec4 a1 = texture2D(Tex1, oUv0); // Attribute 1: Normal+depth - - //Get the 3rd root of the depth to show up-close differences - gl_FragColor = vec4(pow(a1.w,0.33), 0, a0.w, 0); -} diff --git a/Samples/Media/DeferredShadingMedia/DeferredShading/post/ShowNormal_ps.cg b/Samples/Media/DeferredShadingMedia/DeferredShading/post/ShowNormal_ps.cg deleted file mode 100644 index e50ff8c57da..00000000000 --- a/Samples/Media/DeferredShadingMedia/DeferredShading/post/ShowNormal_ps.cg +++ /dev/null @@ -1,43 +0,0 @@ -/****************************************************************************** -Copyright (c) W.J. van der Laan - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the -Software, and to permit persons to whom the Software is furnished to do so, subject -to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies -or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ -/** Deferred shading framework - // W.J. :wumpus: van der Laan 2005 // - - Post shader: Debug, show normal channel -*/ - -#include "HLSL_SM4Support.hlsl" - -SAMPLER2D(Tex0, 0); -SAMPLER2D(Tex1, 1); - -float4 main( - float4 oPos: POSITION, - float2 texCoord: TEXCOORD0, - float2 projCoord: TEXCOORD1 - ) : COLOR -{ - float4 a0 = tex2D(Tex0, texCoord); // Attribute 0: Diffuse color+shininess - float4 a1 = tex2D(Tex1, texCoord); // Attribute 1: Normal+depth - - return float4((a1.xyz+1)*0.5,0); -} - diff --git a/Samples/Media/DeferredShadingMedia/DeferredShading/post/ShowNormal_ps.glsl b/Samples/Media/DeferredShadingMedia/DeferredShading/post/ShowNormal_ps.glsl deleted file mode 100644 index 9127e6d83cb..00000000000 --- a/Samples/Media/DeferredShadingMedia/DeferredShading/post/ShowNormal_ps.glsl +++ /dev/null @@ -1,35 +0,0 @@ -/****************************************************************************** -Copyright (c) W.J. van der Laan - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the -Software, and to permit persons to whom the Software is furnished to do so, subject -to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies -or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ -/** Deferred shading framework - // W.J. :wumpus: van der Laan 2005 // - - Post shader: Debug, show normal channel -*/ -uniform sampler2D Tex1; - -varying vec2 oUv0; - -void main() -{ - vec4 a1 = texture2D(Tex1, oUv0); // Attribute 1: Normal+depth - - gl_FragColor = vec4((a1.xyz+1.0)*0.5,0.0); -} diff --git a/Samples/Media/DeferredShadingMedia/DeferredShading/post/vs.cg b/Samples/Media/DeferredShadingMedia/DeferredShading/post/vs.cg deleted file mode 100644 index 8746e72c926..00000000000 --- a/Samples/Media/DeferredShadingMedia/DeferredShading/post/vs.cg +++ /dev/null @@ -1,54 +0,0 @@ -/****************************************************************************** -Copyright (c) W.J. van der Laan - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the -Software, and to permit persons to whom the Software is furnished to do so, subject -to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies -or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ -/** Deferred shading framework - // W.J. :wumpus: van der Laan 2005 // - - Post shader: Generic fullscreen quad -*/ -void main( - float4 Pos: POSITION, - - out float4 oPos: POSITION, - out float2 oTexCoord: TEXCOORD0, - - out float3 oRay : TEXCOORD1, - - uniform float3 farCorner, - uniform float flip - ) -{ - // Clean up inaccuracies - Pos.xy = sign(Pos.xy); - - oPos = float4(Pos.xy, 0, 1); - oPos.y *= flip; - - // Image-space - oTexCoord.x = 0.5 * (1 + Pos.x); - oTexCoord.y = 0.5 * (1 - Pos.y); - - // This ray will be interpolated and will be the ray from the camera - // to the far clip plane, per pixel - oRay = farCorner * float3(Pos.xy, 1); -} - - - diff --git a/Samples/Media/DeferredShadingMedia/DeferredShading/post/vs.glsl b/Samples/Media/DeferredShadingMedia/DeferredShading/post/vs.glsl deleted file mode 100644 index d55e51a942d..00000000000 --- a/Samples/Media/DeferredShadingMedia/DeferredShading/post/vs.glsl +++ /dev/null @@ -1,54 +0,0 @@ -/****************************************************************************** -Copyright (c) W.J. van der Laan - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the -Software, and to permit persons to whom the Software is furnished to do so, subject -to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies -or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, -INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -******************************************************************************/ -/** Deferred shading framework - // W.J. :wumpus: van der Laan 2005 // - - Post shader: Generic fullscreen quad -*/ -#ifdef GL_ES -#version 300 es -#else -#version 150 -#endif - -in vec4 vertex; - -out vec2 oUv0; -out vec3 oRay; - -uniform vec3 farCorner; -uniform float flip; - -void main() -{ - // Clean up inaccuracies - vec2 Pos = sign(vertex.xy); - - // Image-space - oUv0 = (vec2(Pos.x, -Pos.y) + 1.0) * 0.5; - - // This ray will be interpolated and will be the ray from the camera - // to the far clip plane, per pixel - oRay = farCorner * vec3(Pos, 1); - - gl_Position = vec4(Pos, 0, 1); - gl_Position.y *= flip; -} diff --git a/Samples/Media/DeferredShadingMedia/ShadowCaster.cg b/Samples/Media/DeferredShadingMedia/ShadowCaster.cg deleted file mode 100644 index 2117d655793..00000000000 --- a/Samples/Media/DeferredShadingMedia/ShadowCaster.cg +++ /dev/null @@ -1,26 +0,0 @@ -void ShadowCasterVP( - float4 iPosition : POSITION, - - out float4 oPosition : POSITION, - out float3 oViewPos : TEXCOORD0, - - uniform float4x4 cWorldViewProj, - uniform float4x4 cWorldView - ) -{ - oPosition = mul(cWorldViewProj, iPosition); - oViewPos = mul(cWorldView, iPosition).xyz; -} - -void ShadowCasterFP( - float4 oPosition : POSITION, - float3 iViewPos : TEXCOORD0, - - out float4 oColor : COLOR0, - - uniform float cFarDistance - ) -{ - float depth = length(iViewPos) / cFarDistance; - oColor.rgba = float4(depth, depth, depth, 1); -} diff --git a/Samples/Media/DeferredShadingMedia/ShadowCaster.material b/Samples/Media/DeferredShadingMedia/ShadowCaster.material deleted file mode 100644 index 7ea57e9557f..00000000000 --- a/Samples/Media/DeferredShadingMedia/ShadowCaster.material +++ /dev/null @@ -1,15 +0,0 @@ -material DeferredShading/Shadows/Caster -{ - technique - { - pass - { - vertex_program_ref DeferredShading/Shadows/CasterVP - { - } - fragment_program_ref DeferredShading/Shadows/CasterFP - { - } - } - } -} diff --git a/Samples/Media/DeferredShadingMedia/ShadowCaster.program b/Samples/Media/DeferredShadingMedia/ShadowCaster.program deleted file mode 100644 index d47fb1f708b..00000000000 --- a/Samples/Media/DeferredShadingMedia/ShadowCaster.program +++ /dev/null @@ -1,75 +0,0 @@ -// Auxiliary lights -vertex_program DeferredShading/Shadows/CasterVP unified -{ - delegate DeferredShading/Shadows/CasterVP_pCg - delegate DeferredShading/Shadows/CasterVP_pGLSL - delegate DeferredShading/Shadows/CasterVP_pGLSLES -} -vertex_program DeferredShading/Shadows/CasterVP_pCg hlsl -{ - source ShadowCaster.cg - target vs_2_0 - entry_point ShadowCasterVP - default_params - { - param_named_auto cWorldViewProj worldviewproj_matrix - param_named_auto cWorldView worldview_matrix - } -} -vertex_program DeferredShading/Shadows/CasterVP_pGLSL glsl -{ - source ShadowCaster_vp.glsl - default_params - { - param_named_auto cWorldViewProj worldviewproj_matrix - param_named_auto cWorldView worldview_matrix - } -} - -vertex_program DeferredShading/Shadows/CasterVP_pGLSLES glsles -{ - source ShadowCaster_vp.glsl - syntax glsles - default_params - { - param_named_auto cWorldViewProj worldviewproj_matrix - param_named_auto cWorldView worldview_matrix - } -} - -fragment_program DeferredShading/Shadows/CasterFP unified -{ - delegate DeferredShading/Shadows/CasterFP_pCg - delegate DeferredShading/Shadows/CasterFP_pGLSL - delegate DeferredShading/Shadows/CasterFP_pGLSLES -} -fragment_program DeferredShading/Shadows/CasterFP_pCg hlsl -{ - source ShadowCaster.cg - target ps_2_0 - entry_point ShadowCasterFP - - default_params - { - param_named_auto cFarDistance far_clip_distance - } -} -fragment_program DeferredShading/Shadows/CasterFP_pGLSL glsl -{ - source ShadowCaster_fp.glsl - default_params - { - param_named_auto cFarDistance far_clip_distance - } -} - -fragment_program DeferredShading/Shadows/CasterFP_pGLSLES glsles -{ - source ShadowCaster_fp.glsl - syntax glsles - - default_params - { - param_named_auto cFarDistance far_clip_distance - } -} diff --git a/Samples/Media/DeferredShadingMedia/ShadowCaster_fp.glsl b/Samples/Media/DeferredShadingMedia/ShadowCaster_fp.glsl deleted file mode 100644 index de4bb2194bb..00000000000 --- a/Samples/Media/DeferredShadingMedia/ShadowCaster_fp.glsl +++ /dev/null @@ -1,8 +0,0 @@ -varying vec3 oViewPos; -uniform float cFarDistance; - -void main() -{ - float depth = length(oViewPos) / cFarDistance; - gl_FragColor = vec4(depth, depth, depth, 1.0); -} diff --git a/Samples/Media/DeferredShadingMedia/ShadowCaster_vp.glsl b/Samples/Media/DeferredShadingMedia/ShadowCaster_vp.glsl deleted file mode 100644 index efa091a3674..00000000000 --- a/Samples/Media/DeferredShadingMedia/ShadowCaster_vp.glsl +++ /dev/null @@ -1,12 +0,0 @@ -attribute vec4 vertex; - -varying vec3 oViewPos; - -uniform mat4 cWorldViewProj; -uniform mat4 cWorldView; - -void main() -{ - gl_Position = cWorldViewProj * vertex; - oViewPos = (cWorldView * vertex).xyz; -} diff --git a/Samples/Media/DeferredShadingMedia/deferred.compositor b/Samples/Media/DeferredShadingMedia/deferred.compositor deleted file mode 100644 index f9a32dcd648..00000000000 --- a/Samples/Media/DeferredShadingMedia/deferred.compositor +++ /dev/null @@ -1,142 +0,0 @@ -//Postfilter generating the GBuffer -//! [gbuffer] -compositor DeferredShading/GBuffer -{ - technique - { - // GBuffer textures - // PF_BYTE_RGBA would be sufficient for color, but D3D9 requires same bitdepth for all MRTs - texture mrt_output target_width target_height PF_FLOAT16_RGBA PF_FLOAT16_RGBA chain_scope - - target mrt_output - { - input none - pass clear - { - } - - shadows off - material_scheme GBuffer - - // everything but the lights and their meshes - // could do this with something like a visibility mask too - pass render_scene - { - first_render_queue 10 - last_render_queue 80 - } - } - } -} -//! [gbuffer] - -//Postfilter lighting the scene using the GBuffer -//! [showlit] -compositor DeferredShading/ShowLit -{ - - technique - { - //Reference the main Gbuffer texture - texture_ref mrt_output DeferredShading/GBuffer mrt_output - - target_output - { - input none - //We will dispatch the shadow texture rendering ourselves - shadows off - - pass clear - { - - } - - // render skies and other pre-gbuffer objects - pass render_scene - { - first_render_queue 1 - last_render_queue 9 - } - - //Render the lights and their meshes - pass render_custom DeferredLight - { - input 0 mrt_output 0 - input 1 mrt_output 1 - } - - //Render transparents and other post-GBuffer render queue objects - pass render_scene - { - first_render_queue 90 - } - } - } -} -//! [showlit] - -// Postfilter that shows the colour channel -compositor DeferredShading/ShowColour -{ - technique - { - //Reference the main Gbuffer texture - texture_ref mrt_output DeferredShading/GBuffer mrt_output - - target_output - { - input none - - pass render_quad - { - material DeferredShading/Post/ShowColour - input 0 mrt_output 0 - input 1 mrt_output 1 - } - } - } -} - -// Postfilter that shows the normal channel -compositor DeferredShading/ShowNormals -{ - technique - { - //Reference the main Gbuffer texture - texture_ref mrt_output DeferredShading/GBuffer mrt_output - - target_output - { - input none - - pass render_quad - { - material DeferredShading/Post/ShowNormal - input 0 mrt_output 0 - input 1 mrt_output 1 - } - } - } -} - -// Postfilter that shows the depth and specular channel -compositor DeferredShading/ShowDepthSpecular -{ - technique - { - //Reference the main Gbuffer texture - texture_ref mrt_output DeferredShading/GBuffer mrt_output - - target_output - { - input none - - pass render_quad - { - material DeferredShading/Post/ShowDS - input 0 mrt_output 0 - input 1 mrt_output 1 - } - } - } -} diff --git a/Samples/Media/DeferredShadingMedia/deferred_post.material b/Samples/Media/DeferredShadingMedia/deferred_post.material deleted file mode 100644 index b2f3590acde..00000000000 --- a/Samples/Media/DeferredShadingMedia/deferred_post.material +++ /dev/null @@ -1,144 +0,0 @@ -// Post processors - -//Ambient light -material DeferredShading/AmbientLight -{ - technique - { - pass - { - lighting off - - depth_write on - depth_check on - - vertex_program_ref DeferredShading/post/vs - { - - } - fragment_program_ref DeferredShading/post/Ambient_ps - { - - } - - texture_unit - { - content_type compositor DeferredShading/GBuffer mrt_output 0 - tex_address_mode clamp - filtering none - } - texture_unit - { - content_type compositor DeferredShading/GBuffer mrt_output 1 - tex_address_mode clamp - filtering none - } - } - } -} - -//These materials don't need content_type compositor, as they get their textures from the compositor that uses them -//In a full screen quad -material DeferredShading/Post/ShowNormal -{ - technique - { - pass - { - cull_hardware none - depth_func always_pass - fragment_program_ref DeferredShading/post/ShowNormal_ps - { - } - vertex_program_ref Ogre/Compositor/StdQuad_vp - { - } - texture_unit - { - tex_address_mode clamp - filtering none - } - texture_unit - { - tex_coord_set 1 - tex_address_mode clamp - filtering none - } - } - } -} -material DeferredShading/Post/ShowDS -{ - technique - { - pass - { - cull_hardware none - depth_func always_pass - fragment_program_ref DeferredShading/post/ShowDS_ps - { - } - vertex_program_ref Ogre/Compositor/StdQuad_vp - { - } - texture_unit - { - tex_address_mode clamp - filtering none - } - texture_unit - { - tex_coord_set 1 - tex_address_mode clamp - filtering none - } - } - } - -} -material DeferredShading/Post/ShowColour -{ - technique - { - pass - { - cull_hardware none - depth_func always_pass - fragment_program_ref DeferredShading/post/ShowColour_ps - { - } - vertex_program_ref Ogre/Compositor/StdQuad_vp - { - } - texture_unit - { - tex_address_mode clamp - filtering none - } - texture_unit - { - tex_coord_set 1 - tex_address_mode clamp - filtering none - } - } - } -} - -material DeferredShading/Post/SimpleQuad -{ - technique - { - pass - { - lighting off - depth_write off - depth_check off - - texture_unit - { - filtering none - } - } - } -} diff --git a/Samples/Media/DeferredShadingMedia/deferred_post.program b/Samples/Media/DeferredShadingMedia/deferred_post.program deleted file mode 100644 index 13c229fc8b9..00000000000 --- a/Samples/Media/DeferredShadingMedia/deferred_post.program +++ /dev/null @@ -1,185 +0,0 @@ -// Ambient_ps -fragment_program DeferredShading/post/Ambient_ps unified -{ - delegate DeferredShading/post/Ambient_ps_pCg - delegate DeferredShading/post/Ambient_ps_pGLSL - delegate DeferredShading/post/Ambient_ps_pGLSLES -} -fragment_program DeferredShading/post/Ambient_ps_pCg hlsl -{ - source Ambient_ps.cg - target ps_2_0 - - default_params - { - param_named_auto ambientColor ambient_light_colour - param_named_auto proj projection_matrix - param_named_auto farClipDistance far_clip_distance - } -} -fragment_program DeferredShading/post/Ambient_ps_pGLSL glsl -{ - source Ambient_ps.glsl - syntax glsl150 - - default_params - { - param_named_auto ambientColor ambient_light_colour - param_named_auto proj projection_matrix - param_named_auto farClipDistance far_clip_distance - param_named Tex0 int 0 - param_named Tex1 int 1 - } -} -fragment_program DeferredShading/post/Ambient_ps_pGLSLES glsles -{ - source Ambient_ps.glsl - syntax glsl300es - - default_params - { - param_named_auto ambientColor ambient_light_colour - param_named_auto proj projection_matrix - param_named_auto farClipDistance far_clip_distance - param_named Tex0 int 0 - param_named Tex1 int 1 - } -} - -// ShowNormal_ps -fragment_program DeferredShading/post/ShowNormal_ps unified -{ - delegate DeferredShading/post/ShowNormal_ps_pGLSL - delegate DeferredShading/post/ShowNormal_ps_pCg -} -fragment_program DeferredShading/post/ShowNormal_ps_pCg hlsl -{ - source ShowNormal_ps.cg - target ps_2_0 -} -fragment_program DeferredShading/post/ShowNormal_ps_pGLSL glsl glsles -{ - source ShowNormal_ps.glsl - default_params - { - param_named Tex1 int 1 - } -} - -// ShowDS_ps -fragment_program DeferredShading/post/ShowDS_ps unified -{ - delegate DeferredShading/post/ShowDS_ps_pGLSL - delegate DeferredShading/post/ShowDS_ps_pCg -} -fragment_program DeferredShading/post/ShowDS_ps_pCg hlsl -{ - source ShowDS_ps.cg - target ps_2_0 -} -fragment_program DeferredShading/post/ShowDS_ps_pGLSL glsl glsles -{ - source ShowDS_ps.glsl - default_params - { - param_named Tex0 int 0 - param_named Tex1 int 1 - } -} - -// ShowColour_ps -fragment_program DeferredShading/post/ShowColour_ps unified -{ - delegate DeferredShading/post/ShowColour_ps_pGLSL - delegate DeferredShading/post/ShowColour_ps_pCg -} -fragment_program DeferredShading/post/ShowColour_ps_pCg hlsl -{ - source ShowColour_ps.cg - target ps_2_0 -} -fragment_program DeferredShading/post/ShowColour_ps_pGLSL glsl glsles -{ - source ShowColour_ps.glsl - default_params - { - param_named Tex0 int 0 - } -} -// Auxiliary lights -// cg -vertex_program DeferredShading/post/LightMaterial_vs unified -{ - delegate DeferredShading/post/LightMaterial_vs_pCg - delegate DeferredShading/post/LightMaterial_vs_pGLSL - delegate DeferredShading/post/LightMaterial_vs_pGLSLES -} -vertex_program DeferredShading/post/LightMaterial_vs_pCg hlsl -{ - source LightMaterial_vs.cg - target vs_2_0 - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - //param_named_auto invProj inverse_projection_matrix - //param_named_auto vpWidth viewport_width - //param_named_auto vpHeight viewport_height - } -} -vertex_program DeferredShading/post/LightMaterial_vs_pGLSL glsl -{ - source LightMaterial_vs.glsl - syntax glsl150 - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} -vertex_program DeferredShading/post/LightMaterial_vs_pGLSLES glsles -{ - source LightMaterial_vs.glsl - syntax glsles - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -// Post processors -vertex_program DeferredShading/post/vs unified -{ - delegate DeferredShading/post/vs_pCg - delegate DeferredShading/post/vs_pGLSL - delegate DeferredShading/post/vs_pGLSLES -} -vertex_program DeferredShading/post/vs_pCg hlsl -{ - source vs.cg - target vs_2_0 - default_params - { - //param_named_auto invProj inverse_projection_matrix - param_named_auto flip render_target_flipping - param_named farCorner float3 1 1 1 - } -} -vertex_program DeferredShading/post/vs_pGLSL glsl -{ - source vs.glsl - syntax glsl150 - default_params - { - param_named_auto flip render_target_flipping - param_named farCorner float3 1 1 1 - } -} -vertex_program DeferredShading/post/vs_pGLSLES glsles -{ - source vs.glsl - syntax glsles - default_params - { - param_named_auto flip render_target_flipping - param_named farCorner float3 1 1 1 - } -} diff --git a/Samples/Media/DeferredShadingMedia/deferred_post_minilight.material b/Samples/Media/DeferredShadingMedia/deferred_post_minilight.material deleted file mode 100755 index 99d22300026..00000000000 --- a/Samples/Media/DeferredShadingMedia/deferred_post_minilight.material +++ /dev/null @@ -1,71 +0,0 @@ -// Auxiliary lights - -// Reference material [geometry] -material DeferredShading/LightMaterial/Geometry -{ - technique DeferredTechnique - { - pass DeferredPass - { - // Don't disable depth test, because the light doesn't have to be rendered - // if the bounding geometry is obscured. - scene_blend add - depth_write off - depth_check on - lighting off - - texture_unit GBuffer1 - { - content_type compositor DeferredShading/GBuffer mrt_output 0 - tex_address_mode clamp - filtering none - } - texture_unit GBuffer2 - { - content_type compositor DeferredShading/GBuffer mrt_output 1 - tex_address_mode clamp - filtering none - } - } - } -} - -// Reference material [geometry w/shadows] -material DeferredShading/LightMaterial/GeometryShadow : DeferredShading/LightMaterial/Geometry -{ - technique DeferredTechnique - { - pass DeferredPass - { - texture_unit ShadowMap - { - content_type shadow - } - } - } -} - -// Reference material [quad] -material DeferredShading/LightMaterial/Quad : DeferredShading/LightMaterial/Geometry -{ - technique DeferredTechnique - { - pass DeferredPass - { - depth_check off - } - } -} - - -// Reference material [quad w/shadows] -material DeferredShading/LightMaterial/QuadShadow : DeferredShading/LightMaterial/GeometryShadow -{ - technique DeferredTechnique - { - pass DeferredPass - { - depth_check off - } - } -} diff --git a/Samples/Media/DeferredShadingMedia/deferreddemo.material b/Samples/Media/DeferredShadingMedia/deferreddemo.material deleted file mode 100755 index e781983137c..00000000000 --- a/Samples/Media/DeferredShadingMedia/deferreddemo.material +++ /dev/null @@ -1,81 +0,0 @@ -// Materials for deferred shading test -// Sky box -material DeferredDemo/SkyBox -{ - technique - { - pass - { - depth_write off - lighting off - texture_unit - { - texture evening.jpg cubic - tex_address_mode clamp - } - } - } -} -// Ground plane -material DeferredDemo/Ground -{ - technique - { - pass main - { - texture_unit - { - texture grass_1024.jpg - } - } - } -} -// Rock wall texture [bumpmapped] -material DeferredDemo/RockWall -{ - technique - { - pass main - { - specular 0 0 0 1 0.6 - texture_unit - { - texture rockwall.tga - } - - // include normalmap in normal GBuffer - rtshader_system GBuffer - { - lighting_stage normal_map rockwall_NH.tga - } - - rtshader_system - { - lighting_stage normal_map rockwall_NH.tga - } - } - } -} - -// Athena texture [bumpmapped, untextured] -material DeferredDemo/DeferredAthena -{ - technique - { - pass main - { - diffuse 0.7 0.7 0.7 - specular 1.0 1.0 1.0 1.0 0.5 - - rtshader_system GBuffer - { - lighting_stage normal_map atheneNormalMap.png - } - - rtshader_system - { - lighting_stage normal_map atheneNormalMap.png - } - } - } -} diff --git a/Samples/Media/DeferredShadingMedia/ssao.cg b/Samples/Media/DeferredShadingMedia/ssao.cg deleted file mode 100644 index 0c64fec9263..00000000000 --- a/Samples/Media/DeferredShadingMedia/ssao.cg +++ /dev/null @@ -1,173 +0,0 @@ -struct VIn -{ - float4 p : POSITION; - float3 n : NORMAL; - float2 uv : TEXCOORD0; -}; - -struct VOut -{ - float4 p : POSITION; - float2 uv : TEXCOORD0; - float3 ray : TEXCOORD1; -}; - -struct PIn -{ - float2 uv : TEXCOORD0; - float3 ray : TEXCOORD1; -}; - -VOut ssao_vs(VIn IN, uniform float4x4 wvp, uniform float3 farCorner) -{ - VOut OUT; - OUT.p = mul(wvp, IN.p); - // clean up inaccuracies for the UV coords - float2 uv = sign(IN.p); - // convert to image space - uv = (float2(uv.x, -uv.y) + 1.0) * 0.5; - OUT.uv = uv; - // ray towards frustum far corners - OUT.ray = IN.n; - return OUT; -} - -float3 computeZ(float2 xy) -{ - return float3(xy, sqrt(1.0 - dot(xy, xy))); -} - -// for ps_3_0, we want to use tex2Dlod because it's faster -float4 TEX2DLOD(sampler2D map, float2 uv) -{ - return tex2Dlod(map, float4(uv.xy, 0, 0)); -} - -float4 ssao_ps( - PIn IN, - uniform float4x4 ptMat, - uniform float far, - uniform sampler2D geomMap : TEXUNIT0, - uniform sampler2D randMap : TEXUNIT1): COLOR0 -{ - #define MAX_RAND_SAMPLES 14 - - const float3 RAND_SAMPLES[MAX_RAND_SAMPLES] = - { - float3(1, 0, 0), - float3( -1, 0, 0), - float3(0, 1, 0), - float3(0, -1, 0), - float3(0, 0, 1), - float3(0, 0, -1), - normalize(float3(1, 1, 1)), - normalize(float3(-1, 1, 1)), - normalize(float3(1, -1, 1)), - normalize(float3(1, 1, -1)), - normalize(float3(-1, -1, 1)), - normalize(float3(-1, 1, -1)), - normalize(float3(1, -1, -1)), - normalize(float3(-1, -1, -1)) - }; - - // constant expressin != const int :( - #define NUM_BASE_SAMPLES 6 - - // random normal lookup from a texture and expand to [-1..1] - float3 randN = TEX2DLOD(randMap, IN.uv * 24).xyz * 2.0 - 1.0; - float4 geom = TEX2DLOD(geomMap, IN.uv); - float depth = geom.w; - - // IN.ray will be distorted slightly due to interpolation - // it should be normalized here - float3 viewPos = IN.ray * depth; - - // by computing Z manually, we lose some accuracy under extreme angles - // considering this is just for bias, this loss is acceptable - float3 viewNorm = geom.xyz;//computeZ(geom.yz); - - // accumulated occlusion factor - float occ = 0; - for (int i = 0; i < NUM_BASE_SAMPLES; ++i) - { - // reflected direction to move in for the sphere - // (based on random samples and a random texture sample) - // bias the random direction away from the normal - // this tends to minimize self occlusion - float3 randomDir = reflect(RAND_SAMPLES[i], randN) + viewNorm; - - // move new view-space position back into texture space - #define RADIUS 0.2125 - float4 nuv = mul(ptMat, float4(viewPos.xyz + randomDir * RADIUS, 1)); - nuv.xy /= nuv.w; - - // compute occlusion based on the (scaled) Z difference - float zd = saturate(far * (depth - TEX2DLOD(geomMap, nuv.xy).w)); - // this is a sample occlusion function, you can always play with - // other ones, like 1.0 / (1.0 + zd * zd) and stuff - occ += saturate(pow(1.0 - zd, 11) + zd); - } - occ /= NUM_BASE_SAMPLES; - - return float4(occ, occ, occ, 1); -} - -#define NUM_BLUR_SAMPLES 8 - -float4 ssaoBlurX_ps(float2 uv : TEXCOORD0, - uniform float4 invTexSize, - uniform sampler2D map : TEXUNIT0, uniform sampler2D geomMap : TEXUNIT1): COLOR0 -{ -// return TEX2DLOD(ssaoMap, uv); - float2 o = float2(invTexSize.x, 0); - float4 sum = TEX2DLOD(map, uv) * (NUM_BLUR_SAMPLES + 1); - float denom = NUM_BLUR_SAMPLES + 1; - float4 geom = TEX2DLOD(geomMap, uv); - for (int i = 1; i <= NUM_BLUR_SAMPLES; ++i) - { - float2 nuv = uv + o * i; - float4 nGeom = TEX2DLOD(geomMap, nuv); - float coef = (NUM_BLUR_SAMPLES + 1 - i) * (dot(geom.xyz, nGeom.xyz) > 0.9); - sum += TEX2DLOD(map, nuv) * coef; - denom += coef; - } - for (int i = 1; i <= 4; ++i) - { - float2 nuv = uv + o * -i; - float4 nGeom = TEX2DLOD(geomMap, nuv); - float coef = (NUM_BLUR_SAMPLES + 1 - i) * (dot(geom.xyz, nGeom.xyz) > 0.9); - sum += TEX2DLOD(map, nuv) * coef; - denom += coef; - } - return sum / denom; -} - -float4 ssaoBlurY_ps(float2 uv : TEXCOORD0, - uniform float4 invTexSize, - uniform sampler2D map : TEXUNIT0, uniform sampler2D geomMap : TEXUNIT1): COLOR0 -{ -// return TEX2DLOD(map, uv); - float2 o = float2(0, invTexSize.y); - float4 sum = TEX2DLOD(map, uv) * (NUM_BLUR_SAMPLES + 1); - float denom = NUM_BLUR_SAMPLES + 1; - float4 geom = TEX2DLOD(geomMap, uv); - for (int i = 1; i <= NUM_BLUR_SAMPLES; ++i) - { - float2 nuv = uv + o * i; - float4 nGeom = TEX2DLOD(geomMap, nuv); - float coef = (NUM_BLUR_SAMPLES + 1 - i) * (dot(geom.xyz, nGeom.xyz) > 0.9); - sum += TEX2DLOD(map, nuv) * coef; - denom += coef; - } - for (int i = 1; i <= 4; ++i) - { - float2 nuv = uv + o * -i; - float4 nGeom = TEX2DLOD(geomMap, nuv); - float coef = (NUM_BLUR_SAMPLES + 1 - i) * (dot(geom.xyz, nGeom.xyz) > 0.9); - sum += TEX2DLOD(map, nuv) * coef; - denom += coef; - } - return sum / denom; -} - - diff --git a/Samples/Media/DeferredShadingMedia/ssao.compositor b/Samples/Media/DeferredShadingMedia/ssao.compositor deleted file mode 100644 index 5ee19648971..00000000000 --- a/Samples/Media/DeferredShadingMedia/ssao.compositor +++ /dev/null @@ -1,95 +0,0 @@ -compositor DeferredShading/SSAO -{ - technique - { - compositor_logic SSAOLogic - - texture_ref geom DeferredShading/GBuffer mrt_output - texture scene target_width target_height PF_BYTE_RGBA - texture ssao target_width_scaled 0.5 target_height_scaled 0.5 PF_BYTE_RGB - texture ssaoBlurX target_width target_height PF_BYTE_RGB - texture ssaoBlurY target_width target_height PF_BYTE_RGB - - // the scene we want to modulate - target scene - { - input previous - } - - - - target ssao - { - input none - - pass clear - { - } - - pass render_quad - { - // our SSAO listener number - identifier 42 - - quad_normals camera_far_corners_view_space - - material ssao - // pass in the "geometry map" - input 0 geom 1 - } - } - - target ssaoBlurX - { - input none - - pass clear - { - } - - pass render_quad - { - identifier 43 - - material ssaoBlurX - input 0 ssao - input 1 geom 1 - } - } - - target ssaoBlurY - { - input none - - pass clear - { - } - - pass render_quad - { - identifier 43 - - material ssaoBlurY - input 0 ssaoBlurX - input 1 geom 1 - } - } - - - - target_output - { - input none - - pass render_quad - { - // just output something, for example, use a modulate - // material to just multiply the scene by the ssao - material modulate - input 0 scene - input 1 ssaoBlurY - //input 1 ssao - } - } - } -} diff --git a/Samples/Media/DeferredShadingMedia/ssao.material b/Samples/Media/DeferredShadingMedia/ssao.material deleted file mode 100644 index f8882f4ffed..00000000000 --- a/Samples/Media/DeferredShadingMedia/ssao.material +++ /dev/null @@ -1,262 +0,0 @@ - -// full screen quad with camera-to-pixel ray calculations - -vertex_program ssao_vs unified -{ - delegate ssao_vs_pCg - delegate ssao_vs_pGLSL - delegate ssao_vs_pGLSLES -} -vertex_program ssao_vs_pCg hlsl -{ - source ssao.cg - target vs_2_0 - entry_point ssao_vs - default_params - { - param_named_auto wvp worldviewproj_matrix - } -} -vertex_program ssao_vs_pGLSL glsl -{ - source ssao_vs.glsl - syntax glsl150 - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} -vertex_program ssao_vs_pGLSLES glsles -{ - source ssao_vs.glsl - syntax glsles - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} -fragment_program ssao_ps unified -{ - delegate ssao_ps_pCg - delegate ssao_ps_pGLSL - delegate ssao_ps_pGLSLES -} -fragment_program ssao_ps_pCg hlsl -{ - source ssao.cg - entry_point ssao_ps - // will run on anything with pixel shader 2.b and up - target ps_3_0 - default_params - { - } -} -fragment_program ssao_ps_pGLSL glsl -{ - source ssao_ps.glsl - // will run on anything with GLSL 1.50 and up - syntax glsl150 - default_params - { - param_named geomMap int 0 - param_named randMap int 1 - } -} -fragment_program ssao_ps_pGLSLES glsles -{ - source ssao_ps.glsl - // will run on anything with GLSL 1.50 and up - syntax glsl300es - default_params - { - param_named geomMap int 0 - param_named randMap int 1 - } -} -fragment_program ssaoBlurX_ps unified -{ - delegate ssaoBlurX_ps_pCg - delegate ssaoBlurX_ps_pGLSL - delegate ssaoBlurX_ps_pGLSLES -} -fragment_program ssaoBlurX_ps_pCg hlsl -{ - source ssao.cg - entry_point ssaoBlurX_ps - target ps_3_0 - default_params - { - param_named_auto invTexSize inverse_texture_size 0 - } -} -fragment_program ssaoBlurX_ps_pGLSL glsl -{ - source ssao_blurx_ps.glsl - syntax glsl150 - default_params - { - param_named_auto invTexSize inverse_texture_size 0 - param_named map int 0 - param_named geomMap int 1 - } -} -fragment_program ssaoBlurX_ps_pGLSLES glsles -{ - source ssao_blurx_ps.glsl - syntax glsl300es - default_params - { - param_named_auto invTexSize inverse_texture_size 0 - param_named map int 0 - param_named geomMap int 1 - } -} - -fragment_program ssaoBlurY_ps unified -{ - delegate ssaoBlurY_ps_pCg - delegate ssaoBlurY_ps_pGLSL - delegate ssaoBlurY_ps_pGLSLES -} -fragment_program ssaoBlurY_ps_pCg hlsl -{ - source ssao.cg - entry_point ssaoBlurY_ps - target ps_3_0 - default_params - { - param_named_auto invTexSize inverse_texture_size 0 - } -} -fragment_program ssaoBlurY_ps_pGLSL glsl -{ - source ssao_blury_ps.glsl - syntax glsl150 - default_params - { - param_named_auto invTexSize inverse_texture_size 0 - param_named map int 0 - param_named geomMap int 1 - } -} -fragment_program ssaoBlurY_ps_pGLSLES glsles -{ - source ssao_blury_ps.glsl - syntax glsl300es - default_params - { - param_named_auto invTexSize inverse_texture_size 0 - param_named map int 0 - param_named geomMap int 1 - } -} - -material ssao -{ - technique - { - pass - { - vertex_program_ref ssao_vs - { - } - - fragment_program_ref ssao_ps - { - param_named_auto far far_clip_distance - } - - texture_unit geomMap - { - tex_address_mode clamp - filtering bilinear - } - - texture_unit randMap - { - texture random.png - filtering none - } - } - } -} - -material ssaoBlurX -{ - technique - { - pass - { - - vertex_program_ref Ogre/BasicVertexPrograms/AmbientOneTextureWithUV - { - } - - fragment_program_ref ssaoBlurX_ps - { - } - - texture_unit map - { - tex_address_mode clamp - filtering bilinear - } - - texture_unit geomMap - { - tex_address_mode clamp - filtering bilinear - } - } - } -} - -material ssaoBlurY -{ - technique - { - pass - { - vertex_program_ref Ogre/BasicVertexPrograms/AmbientOneTextureWithUV - { - } - - fragment_program_ref ssaoBlurY_ps - { - } - - texture_unit map - { - tex_address_mode clamp - filtering bilinear - } - - texture_unit geomMap - { - tex_address_mode clamp - filtering bilinear - } - } - } -} - -material modulate -{ - technique - { - pass - { - lighting off - - texture_unit - { - filtering none - } - - texture_unit - { - filtering none - } - } - } -} diff --git a/Samples/Media/DeferredShadingMedia/ssao_blurx_ps.glsl b/Samples/Media/DeferredShadingMedia/ssao_blurx_ps.glsl deleted file mode 100644 index 154a7287ee5..00000000000 --- a/Samples/Media/DeferredShadingMedia/ssao_blurx_ps.glsl +++ /dev/null @@ -1,41 +0,0 @@ -#ifdef GL_ES -#version 300 es -#else -#version 150 -#endif - -in vec4 ambientUV; -in vec3 ray; - -out vec4 fragColour; - -uniform vec4 invTexSize; -uniform sampler2D map; -uniform sampler2D geomMap; - -#define NUM_BLUR_SAMPLES 8 - -void main() -{ - vec2 o = vec2(invTexSize.x, 0.0); - vec4 sum = textureLod(map, ambientUV.xy, ambientUV.w) * float(NUM_BLUR_SAMPLES + 1); - float denom = float(NUM_BLUR_SAMPLES + 1); - vec4 geom = textureLod(geomMap, ambientUV.xy, ambientUV.w); - for (int i = 1; i <= NUM_BLUR_SAMPLES; ++i) - { - vec2 nuv = ambientUV.xy + o * float(i); - vec4 nGeom = textureLod(geomMap, nuv, 0.0); - float coef = float(NUM_BLUR_SAMPLES + 1 - i) * step(0.9, (dot(geom.xyz, nGeom.xyz))); - sum += textureLod(map, nuv, 0.0) * coef; - denom += coef; - } - for (int i = 1; i <= 4; ++i) - { - vec2 nuv = ambientUV.xy + o * float(-i); - vec4 nGeom = textureLod(geomMap, nuv, 0.0); - float coef = float(NUM_BLUR_SAMPLES + 1 - i) * step(0.9, (dot(geom.xyz, nGeom.xyz))); - sum += textureLod(map, nuv, 0.0) * coef; - denom += coef; - } - fragColour = sum / denom; -} diff --git a/Samples/Media/DeferredShadingMedia/ssao_blury_ps.glsl b/Samples/Media/DeferredShadingMedia/ssao_blury_ps.glsl deleted file mode 100644 index a2c3a9c9666..00000000000 --- a/Samples/Media/DeferredShadingMedia/ssao_blury_ps.glsl +++ /dev/null @@ -1,41 +0,0 @@ -#ifdef GL_ES -#version 300 es -#else -#version 150 -#endif - -in vec4 ambientUV; -in vec3 ray; - -out vec4 fragColour; - -uniform vec4 invTexSize; -uniform sampler2D map; -uniform sampler2D geomMap; - -#define NUM_BLUR_SAMPLES 8 - -void main() -{ - vec2 o = vec2(0.0, invTexSize.y); - vec4 sum = textureLod(map, ambientUV.xy, ambientUV.w) * float(NUM_BLUR_SAMPLES + 1); - float denom = float(NUM_BLUR_SAMPLES + 1); - vec4 geom = textureLod(geomMap, ambientUV.xy, ambientUV.w); - for (int i = 1; i <= NUM_BLUR_SAMPLES; ++i) - { - vec2 nuv = ambientUV.xy + o * float(i); - vec4 nGeom = textureLod(geomMap, nuv, 0.0); - float coef = float(NUM_BLUR_SAMPLES + 1 - i) * step(0.9, (dot(geom.xyz, nGeom.xyz))); - sum += textureLod(map, nuv, 0.0) * coef; - denom += coef; - } - for (int i = 1; i <= 4; ++i) - { - vec2 nuv = ambientUV.xy + o * float(-i); - vec4 nGeom = textureLod(geomMap, nuv, 0.0); - float coef = float(NUM_BLUR_SAMPLES + 1 - i) * step(0.9, (dot(geom.xyz, nGeom.xyz))); - sum += textureLod(map, nuv, 0.0) * coef; - denom += coef; - } - fragColour = sum / denom; -} diff --git a/Samples/Media/DeferredShadingMedia/ssao_ps.glsl b/Samples/Media/DeferredShadingMedia/ssao_ps.glsl deleted file mode 100644 index 2ab72ccfa31..00000000000 --- a/Samples/Media/DeferredShadingMedia/ssao_ps.glsl +++ /dev/null @@ -1,77 +0,0 @@ -#ifdef GL_ES -#version 300 es -#else -#version 150 -#endif - -uniform mat4 ptMat; -uniform float far; -uniform sampler2D geomMap; -uniform sampler2D randMap; - -out vec4 fragColour; -in vec2 oUv0; -in vec3 ray; - -void main() -{ - #define MAX_RAND_SAMPLES 14 - - const vec3 RAND_SAMPLES[MAX_RAND_SAMPLES] = - vec3[]( - vec3(1, 0, 0), - vec3(-1, 0, 0), - vec3(0, 1, 0), - vec3(0, -1, 0), - vec3(0, 0, 1), - vec3(0, 0, -1), - normalize(vec3(1, 1, 1)), - normalize(vec3(-1, 1, 1)), - normalize(vec3(1, -1, 1)), - normalize(vec3(1, 1, -1)), - normalize(vec3(-1, -1, 1)), - normalize(vec3(-1, 1, -1)), - normalize(vec3(1, -1, -1)), - normalize(vec3(-1, -1, -1))); - - // constant expression != const int :( - #define NUM_BASE_SAMPLES 6 - - // random normal lookup from a texture and expand to [-1..1] - vec3 randN = textureLod(randMap, oUv0 * 24.0, 0.0).xyz * 2.0 - 1.0; - vec4 geom = textureLod(geomMap, oUv0, 0.0); - float depth = geom.w; - - // IN.ray will be distorted slightly due to interpolation - // it should be normalized here - vec3 viewPos = ray * depth; - - // By computing Z manually, we lose some accuracy under extreme angles - // considering this is just for bias, this loss is acceptable - vec3 viewNorm = geom.xyz; - - // Accumulated occlusion factor - float occ = 0.0; - for (int i = 0; i < NUM_BASE_SAMPLES; ++i) - { - // Reflected direction to move in for the sphere - // (based on random samples and a random texture sample) - // bias the random direction away from the normal - // this tends to minimize self occlusion - vec3 randomDir = reflect(RAND_SAMPLES[i], randN) + viewNorm; - - // Move new view-space position back into texture space - #define RADIUS 0.2125 - vec4 nuv = ptMat * vec4(viewPos.xyz + randomDir * RADIUS, 1.0); - nuv.xy /= nuv.w; - - // Compute occlusion based on the (scaled) Z difference - float zd = clamp(far * (depth - textureLod(geomMap, nuv.xy, nuv.w).w), 0.0, 1.0); - // This is a sample occlusion function, you can always play with - // other ones, like 1.0 / (1.0 + zd * zd) and stuff - occ += clamp(pow(1.0 - zd, 11.0) + zd, 0.0, 1.0); - } - occ /= float(NUM_BASE_SAMPLES); - - fragColour = vec4(occ, occ, occ, 1.0); -} diff --git a/Samples/Media/DeferredShadingMedia/ssao_vs.glsl b/Samples/Media/DeferredShadingMedia/ssao_vs.glsl deleted file mode 100644 index a81d17cd47d..00000000000 --- a/Samples/Media/DeferredShadingMedia/ssao_vs.glsl +++ /dev/null @@ -1,24 +0,0 @@ -#ifdef GL_ES -#version 300 es -#else -#version 150 -#endif - -uniform mat4 worldViewProj; -in vec4 vertex; -in vec3 normal; -out vec2 oUv0; -out vec3 ray; - -void main() -{ - gl_Position = worldViewProj * vertex; - - // Clean up inaccuracies for the UV coords - vec2 uv = sign(vertex).xy; - // Convert to image space - uv = (vec2(uv.x, -uv.y) + 1.0) * 0.5; - oUv0 = uv; - // ray towards frustum far corners - ray = normal; -} diff --git a/Samples/Media/PBR/black.png b/Samples/Media/PBR/black.png deleted file mode 100644 index 3cf27f47d2f..00000000000 Binary files a/Samples/Media/PBR/black.png and /dev/null differ diff --git a/Samples/Media/PBR/brdfLUT.png b/Samples/Media/PBR/brdfLUT.png deleted file mode 100644 index 5f6541b326e..00000000000 Binary files a/Samples/Media/PBR/brdfLUT.png and /dev/null differ diff --git a/Samples/Media/PBR/filament/filament.material b/Samples/Media/PBR/filament/filament.material deleted file mode 100644 index 6b3e8f46678..00000000000 --- a/Samples/Media/PBR/filament/filament.material +++ /dev/null @@ -1,106 +0,0 @@ -sampler PBRSampler -{ - filtering anisotropic - max_anisotropy 8 -} - -sampler PBRLUTSampler -{ - filtering none - tex_address_mode clamp -} - -sampler PBRIBLSampler -{ - tex_address_mode clamp - filtering trilinear -} - -sampler PBRSSAOSampler -{ - tex_address_mode clamp - filtering none -} - -abstract material Filament -{ - set $Albedo white.png - set $AmbientOcclusion white.png - set $Normal normal_disabled.png - set $Emissive black.png - set $MetalRoughness white.png - set $BRDFLUT "dfgLUTmultiscatter.dds 2d 0" - set $IBL_SPECULAR black.png - - technique - { - pass - { - // These are safe to override. - texture_unit Albedo - { - texture $Albedo - sampler_ref PBRSampler - } - texture_unit AmbientOcclusion - { - texture $AmbientOcclusion - tex_coord_set 1 - sampler_ref PBRSampler - } - texture_unit Normal - { - texture $Normal - sampler_ref PBRSampler - } - texture_unit Emissive - { - texture $Emissive - sampler_ref PBRSampler - } - texture_unit MetalRoughness - { - texture $MetalRoughness - sampler_ref PBRSampler - } - // You should not override these. - texture_unit BRDFLUT - { - texture $BRDFLUT - sampler_ref PBRLUTSampler - } - texture_unit IBL_SPECULAR - { - texture $IBL_SPECULAR cubic gamma - sampler_ref PBRIBLSampler - } - texture_unit SSAO - { - texture $AmbientOcclusion - tex_coord_set 1 - sampler_ref PBRSampler - } - /* - texture_unit SSAO - { - content_type compositor SSAO/GBuffer blurred_occlusion 0 - sampler_ref PBRSSAOSampler - } - */ - - vertex_program_ref PBR_filament_vs - { - } - - fragment_program_ref PBR_filament_fs - { - // PBR parameters - param_named u_BaseColorFactor float4 1 1 1 1 - param_named u_NormalScale float 1 - param_named u_EmissiveFactor float3 1 1 1 - param_named u_MetallicRoughnessValues float2 1 1 - param_named u_OcclusionStrength float 1 - } - } - } -} diff --git a/Samples/Media/PBR/filament/pbr_filament.frag.glsl b/Samples/Media/PBR/filament/pbr_filament.frag.glsl deleted file mode 100644 index 9d5ff596f86..00000000000 --- a/Samples/Media/PBR/filament/pbr_filament.frag.glsl +++ /dev/null @@ -1,229 +0,0 @@ -#version 330 - -// Apparently needed by layout(location = ) syntax -#extension GL_ARB_separate_shader_objects : enable - -// #include "common_types.fs" - -uniform vec4 u_lightPositionFalloff[LIGHT_COUNT]; // Light position world space -uniform vec4 u_lightColorIntensity[LIGHT_COUNT]; // Light color, .w = attenuation multiplier -uniform vec4 u_lightDirection[LIGHT_COUNT]; // Light direction -uniform vec4 u_lightSpotlightParams[LIGHT_COUNT]; // Spotlight parameters, Vector4(innerFactor, outerFactor, falloff, isSpot) innerFactor and outerFactor are cos(angle/2) The isSpot parameter is 0.0f for non-spotlights, 1.0f for spotlights. - -#ifdef HAS_BASECOLORMAP -uniform sampler2D u_BaseColorSampler; -#endif -#ifdef MATERIAL_HAS_NORMAL -uniform sampler2D u_NormalSampler; -uniform float u_NormalScale; -#endif -#ifdef MATERIAL_HAS_EMISSIVE -uniform sampler2D u_EmissiveSampler; -uniform vec3 u_EmissiveFactor; -#endif -#ifdef HAS_METALROUGHNESSMAP -uniform sampler2D u_MetallicRoughnessSampler; -#endif -#ifdef HAS_OCCLUSIONMAP -uniform sampler2D u_OcclusionSampler; -uniform float u_OcclusionStrength; -#endif - -uniform vec2 u_MetallicRoughnessValues; -uniform vec4 u_BaseColorFactor; -#ifdef MATERIAL_HAS_CLEAR_COAT -uniform vec2 u_clearCoatRoughnessValues; -#endif -#ifdef MATERIAL_HAS_ANISOTROPY -uniform float u_anisotropy; -#endif - -uniform sampler2D light_iblDFG; -uniform samplerCube light_iblSpecular; -#ifdef HAS_SSAO -uniform sampler2D light_ssao; -#endif - -#include "pbr_filament_frameuniforms.glsl" -#include "pbr_filament_lightuniforms.glsl" - -in highp vec3 vertex_worldPosition; -#if defined(HAS_ATTRIBUTE_TANGENTS) -in mediump vec3 vertex_worldNormal; -#if defined(MATERIAL_HAS_ANISOTROPY) || defined(MATERIAL_HAS_NORMAL) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL) -in mediump vec3 vertex_worldTangent; -in mediump vec3 vertex_worldBitangent; -#endif -#endif - -#if defined(HAS_ATTRIBUTE_COLOR) -in mediump vec4 vertex_color; -#endif - -#if defined(HAS_ATTRIBUTE_UV0) && !defined(HAS_ATTRIBUTE_UV1) -in highp vec2 vertex_uv01; -#elif defined(HAS_ATTRIBUTE_UV1) -in highp vec4 vertex_uv01; -#endif - -#if defined(HAS_SHADOWING) && defined(HAS_DIRECTIONAL_LIGHTING) -in highp vec4 vertex_lightSpacePosition; -#endif - -out vec4 fragColor; - -// This exposes "global" variables, some of which will be -// initialized by the prepareMaterial() -#include "common_shading.fs" -#include "common_math.fs" -#include "common_material.fs" -#include "common_graphics.fs" -#include "common_lighting.fs" - -#include "tone_mapping.fs" -#include "conversion_functions.fs" - -#include "material_inputs.fs" - -#include "getters.fs" - -#include "shading_parameters.fs" - -#include "ambient_occlusion.fs" - -#include "brdf.fs" - -#ifdef SHADING_MODEL_CLOTH -#include "shading_model_cloth.fs" -#else -#include "shading_model_standard.fs" -#endif - -#include "light_indirect.fs" -#include "light_punctual.fs" - -// Contains the root evaluateMaterial() function that calls everything else. -#include "shading_lit.fs" - -float sRGB_OECF(const float sRGB) { - // IEC 61966-2-1:1999 - float linearLow = sRGB / 12.92; - float linearHigh = pow((sRGB + 0.055) / 1.055, 2.4); - return sRGB <= 0.04045 ? linearLow : linearHigh; -} - -/** - * Reverse opto-electronic conversion function to the one that filament - * provides. Filament version has LDR RGB linear color -> LDR RGB non-linear - * color in sRGB space. This function will thus provide LDR RGB non-linear - * color in sRGB space -> LDR RGB linear color conversion. - */ -vec3 sRGB_OECF(const vec3 sRGB) -{ - return vec3(sRGB_OECF(sRGB.r), sRGB_OECF(sRGB.g), sRGB_OECF(sRGB.b)); -} - -void material(inout MaterialInputs material) -{ -#ifdef HAS_BASECOLORMAP - vec4 baseColor = texture(u_BaseColorSampler, vertex_uv01.xy); - baseColor *= u_BaseColorFactor; - baseColor.rgb = sRGB_OECF(baseColor.rgb); -#else - vec4 baseColor = u_BaseColorFactor; -#endif - material.baseColor = baseColor; - - // Metallic and Roughness material properties are packed together - // In glTF, these factors can be specified by fixed scalar values - // or from a metallic-roughness map - float perceptualRoughness = u_MetallicRoughnessValues.y; - float metallic = u_MetallicRoughnessValues.x; -#ifdef HAS_METALROUGHNESSMAP - // Roughness is stored in the 'g' channel, metallic is stored in the 'b' channel. - // This layout intentionally reserves the 'r' channel for (optional) occlusion map data - vec4 mrSample = texture(u_MetallicRoughnessSampler, vertex_uv01.xy); - perceptualRoughness = mrSample.g * perceptualRoughness; - metallic = mrSample.b * metallic; -#endif -#ifndef SHADING_MODEL_CLOTH - material.roughness = perceptualRoughness; - material.metallic = metallic; -#endif - - // TODO Add reflectance. - // material.reflectance -#ifdef HAS_OCCLUSIONMAP - material.ambientOcclusion = texture(u_OcclusionSampler, vertex_uv01.zw).r * u_OcclusionStrength; -#endif -#ifdef MATERIAL_HAS_EMISSIVE - material.emissive = texture(u_EmissiveSampler, vertex_uv01.xy); - material.emissive.rgb *= u_EmissiveFactor; - material.emissive.rgb = sRGB_OECF(material.emissive.rgb); -#endif -#ifdef MATERIAL_HAS_NORMAL - material.normal = texture2D(u_NormalSampler, vertex_uv01.xy).xyz; - // Z is assumed to be always positive from range 0 to 1 like defaulted by the NVIDIA Normal Map Filter. - material.normal.xy = (2.0 * material.normal.xy - 1.0) * vec2(u_NormalScale); -#endif -#ifdef MATERIAL_HAS_CLEAR_COAT - float clearCoat = u_clearCoatRoughnessValues.x; - float clearCoatRoughness = u_clearCoatRoughnessValues.y; -#ifndef HAS_METALROUGHNESSMAP - vec4 mrSample = texture(u_MetallicRoughnessSampler, vertex_uv01.xy); -#endif - clearCoat = mrSample.a * clearCoat; - clearCoatRoughness = mrSample.r * clearCoatRoughness; - material.clearCoat = clearCoat; - material.clearCoatRoughness = clearCoatRoughness; -#endif -#ifdef MATERIAL_HAS_ANISOTROPY - material.anisotropy = u_anisotropy; - material.anisotropyDirection = normalize(vertex_worldNormal); -#endif - - // Must be invoked after setting material.normal. - prepareMaterial(material); - shading_reflected.z *= -1.0; -} - -// Mainly from main.fs - -#if defined(MATERIAL_HAS_POST_LIGHTING_COLOR) -void blendPostLightingColor(const MaterialInputs material, inout vec4 color) { -#if defined(POST_LIGHTING_BLEND_MODE_OPAQUE) - color = material.postLightingColor; -#elif defined(POST_LIGHTING_BLEND_MODE_TRANSPARENT) - color = material.postLightingColor + color * (1.0 - material.postLightingColor.a); -#elif defined(POST_LIGHTING_BLEND_MODE_ADD) - color += material.postLightingColor; -#elif defined(POST_LIGHTING_BLEND_MODE_MULTIPLY) - color *= material.postLightingColor; -#elif defined(POST_LIGHTING_BLEND_MODE_SCREEN) - color += material.postLightingColor * (1.0 - color); -#endif -} -#endif - -void main() -{ - // See shading_parameters.fs - // Computes global variables we need to evaluate material and lighting - computeShadingParams(); - - // Initialize the inputs to sensible default values, see material_inputs.fs - MaterialInputs inputs; - initMaterial(inputs); - - // Invoke user code - material(inputs); - - fragColor = evaluateMaterial(inputs); - -#if defined(MATERIAL_HAS_POST_LIGHTING_COLOR) - blendPostLightingColor(inputs, fragColor); -#endif - - // Convert from linear HDR pre-exposed to linear LDR. - fragColor.rgb = OECF(tonemap(fragColor.rgb)); -} diff --git a/Samples/Media/PBR/filament/pbr_filament.program b/Samples/Media/PBR/filament/pbr_filament.program deleted file mode 100644 index dc3a770483e..00000000000 --- a/Samples/Media/PBR/filament/pbr_filament.program +++ /dev/null @@ -1,197 +0,0 @@ -shared_params SphericalHarmonicsSky -{ - shared_param_named frameUniforms.iblSH float3 [9] 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 -} - -shared_params SphericalHarmonicsEnvironment -{ - shared_param_named frameUniforms.iblSH float3 [9] 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 65504.0 -} - -vertex_program PBR_filament_vs_glsl glsl -{ - syntax glsl330 - source pbr_filament.vert.glsl - // HAS_DYNAMIC_LIGHTING will also handle HAS_DIRECTIONAL_LIGHTING - preprocessor_defines HAS_ATTRIBUTE_TANGENTS,HAS_ATTRIBUTE_COLOR,HAS_ATTRIBUTE_UV0,HAS_ATTRIBUTE_UV1,MATERIAL_HAS_NORMAL,HAS_DYNAMIC_LIGHTING,VERTEX_DOMAIN_OBJECT - - default_params - { - // Only used when HAS_ATTRIBUTE_TANGENTS - param_named_auto objectUniforms.worldFromModelMatrix world_matrix - // param_named_auto objectUniforms.worldFromModelNormalMatrix normal_matrix - // If HAS_SKINNING_OR_MORPHING enabled then we need these - // param_named_auto objectUniforms.morphWeights animation_parametric - // param_named objectUniforms.morphingEnabled int 0 - // param_named objectUniforms.skinningEnabled int 0 - // Defined but not needed by the compiled code - // param_named_auto frameUniforms.viewFromWorldMatrix view_matrix - // param_named_auto frameUniforms.clipFromViewMatrix projection_matrix - // param_named_auto frameUniforms.worldFromViewMatrix inverse_view_matrix - // param_named_auto frameUniforms.viewFromClipMatrix inverse_projection_matrix - param_named_auto frameUniforms.clipFromWorldMatrix viewproj_matrix - // param_named_auto frameUniforms.worldFromClipMatrix inverse_viewproj_matrix - } -} - -abstract fragment_program PBR_filament_base_fs_glsl glsl -{ - syntax glsl330 - source pbr_filament.frag.glsl - // HAS_DYNAMIC_LIGHTING will also handle HAS_DIRECTIONAL_LIGHTING - // preprocessor_defines HAS_ATTRIBUTE_TANGENTS,HAS_ATTRIBUTE_COLOR,HAS_ATTRIBUTE_UV0,HAS_ATTRIBUTE_UV1,HAS_BASECOLORMAP,MATERIAL_HAS_NORMAL,HAS_METALROUGHNESSMAP,HAS_OCCLUSIONMAP,HAS_DYNAMIC_LIGHTING,LIGHT_COUNT=8u,MATERIAL_HAS_EMISSIVE,VERTEX_DOMAIN_OBJECT,MATERIAL_CAN_SKIP_LIGHTING - - default_params - { - // lighting parameters - param_named_auto u_lightSpotlightParams spotlight_params_array 8 - param_named_auto u_lightPositionFalloff light_position_array 8 - param_named_auto u_lightDirection light_direction_array 8 - param_named_auto u_lightColorIntensity light_diffuse_colour_array 8 - - // GL sampler settings - param_named u_BaseColorSampler int 0 - param_named u_OcclusionSampler int 1 - // Only used when HAS_ATTRIBUTE_TANGENTS - param_named u_NormalSampler int 2 - param_named u_EmissiveSampler int 3 - param_named u_MetallicRoughnessSampler int 4 - param_named light_iblDFG int 5 - param_named light_iblSpecular int 6 - - // Filament spherical harmonics, not used but needed by the shader. - // param_named frameUniforms.iblSH float27 65504.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 - // x = IBL max mip level (= numMipMaps - 1) - // y = IBL resolution - param_named frameUniforms.iblMaxMipLevel float2 4.0 256.0 - param_named frameUniforms.iblLuminance float 1.0 - // Only needed when HAS_REFRACTION - // param_named_auto frameUniforms.clipFromWorldMatrix viewproj_matrix - // exposure = 1.0 / (pow(2.0, ev100) * 1.2) - param_named frameUniforms.exposure float 0.0000260416666666666666666 - // This is only needed when using emissive! i.e. MATERIAL_HAS_EMISSIVE defined. - // Computes the camera's EV100 from exposure settings - // aperture in f-stops - // shutterSpeed in seconds - // sensitivity in ISO - // ev100 = log2((aperture * aperture) / shutterSpeed * 100.0 / sensitivity); - // Aperture: f/16 - // Shutter speed: 1/125s - // ISO: 100 - param_named frameUniforms.ev100 float 14.965784284662087043610958288468 - // param_named u_anisotropy float 0.1 - param_named_auto frameUniforms.cameraPosition camera_position - shared_params_ref SphericalHarmonicsEnvironment - } -} - - -abstract fragment_program PBR_filament_base_ssao_fs_glsl glsl : PBR_filament_base_fs_glsl -{ - // preprocessor_defines += HAS_SSAO,MULTI_BOUNCE_AMBIENT_OCCLUSION=1,SPECULAR_AMBIENT_OCCLUSION=1 - default_params - { - param_named light_ssao int 7 - param_named_auto frameUniforms.viewportWidth inverse_viewport_width - param_named_auto frameUniforms.viewportHeight inverse_viewport_height - } -} - -fragment_program PBR_filament_fs_glsl glsl : PBR_filament_base_ssao_fs_glsl -{ - preprocessor_defines MULTI_BOUNCE_AMBIENT_OCCLUSION=1,SPECULAR_AMBIENT_OCCLUSION=1,HAS_ATTRIBUTE_TANGENTS,HAS_ATTRIBUTE_COLOR,HAS_ATTRIBUTE_UV0,HAS_ATTRIBUTE_UV1,HAS_BASECOLORMAP,MATERIAL_HAS_NORMAL,HAS_METALROUGHNESSMAP,HAS_OCCLUSIONMAP,HAS_DYNAMIC_LIGHTING,LIGHT_COUNT=8u,MATERIAL_HAS_EMISSIVE,VERTEX_DOMAIN_OBJECT,MATERIAL_CAN_SKIP_LIGHTING -} - -fragment_program PBR_NO_SSAO_filament_fs_glsl glsl : PBR_filament_base_fs_glsl -{ - preprocessor_defines MULTI_BOUNCE_AMBIENT_OCCLUSION=1,SPECULAR_AMBIENT_OCCLUSION=1,HAS_ATTRIBUTE_TANGENTS,HAS_ATTRIBUTE_COLOR,HAS_ATTRIBUTE_UV0,HAS_ATTRIBUTE_UV1,HAS_BASECOLORMAP,MATERIAL_HAS_NORMAL,HAS_METALROUGHNESSMAP,HAS_OCCLUSIONMAP,HAS_DYNAMIC_LIGHTING,LIGHT_COUNT=8u,MATERIAL_HAS_EMISSIVE,VERTEX_DOMAIN_OBJECT,MATERIAL_CAN_SKIP_LIGHTING -} - -fragment_program PBR_filament_clear_coat_fs_glsl glsl : PBR_filament_base_ssao_fs_glsl -{ - preprocessor_defines MATERIAL_HAS_CLEAR_COAT,HAS_SSAO,MULTI_BOUNCE_AMBIENT_OCCLUSION=1,SPECULAR_AMBIENT_OCCLUSION=1,HAS_ATTRIBUTE_TANGENTS,HAS_ATTRIBUTE_COLOR,HAS_ATTRIBUTE_UV0,HAS_ATTRIBUTE_UV1,HAS_BASECOLORMAP,MATERIAL_HAS_NORMAL,HAS_METALROUGHNESSMAP,HAS_OCCLUSIONMAP,HAS_DYNAMIC_LIGHTING,LIGHT_COUNT=8u,MATERIAL_HAS_EMISSIVE,VERTEX_DOMAIN_OBJECT,MATERIAL_CAN_SKIP_LIGHTING -} - -fragment_program PBR_filament_clear_coat_ior_change_fs_glsl glsl : PBR_filament_base_ssao_fs_glsl -{ - preprocessor_defines CLEAR_COAT_IOR_CHANGE,MATERIAL_HAS_CLEAR_COAT,HAS_SSAO,MULTI_BOUNCE_AMBIENT_OCCLUSION=1,SPECULAR_AMBIENT_OCCLUSION=1,HAS_ATTRIBUTE_TANGENTS,HAS_ATTRIBUTE_COLOR,HAS_ATTRIBUTE_UV0,HAS_ATTRIBUTE_UV1,HAS_BASECOLORMAP,MATERIAL_HAS_NORMAL,HAS_METALROUGHNESSMAP,HAS_OCCLUSIONMAP,HAS_DYNAMIC_LIGHTING,LIGHT_COUNT=8u,MATERIAL_HAS_EMISSIVE,VERTEX_DOMAIN_OBJECT,MATERIAL_CAN_SKIP_LIGHTING -} - -fragment_program PBR_filament_cloth_fs_glsl glsl -{ - syntax glsl330 - source pbr_filament.frag.glsl - // HAS_DYNAMIC_LIGHTING will also handle HAS_DIRECTIONAL_LIGHTING - preprocessor_defines HAS_ATTRIBUTE_TANGENTS,HAS_ATTRIBUTE_COLOR,HAS_ATTRIBUTE_UV0,HAS_ATTRIBUTE_UV1,HAS_BASECOLORMAP,MATERIAL_HAS_NORMAL,HAS_OCCLUSIONMAP,HAS_DYNAMIC_LIGHTING,LIGHT_COUNT=8u,MATERIAL_HAS_EMISSIVE,VERTEX_DOMAIN_OBJECT,SHADING_MODEL_CLOTH,MATERIAL_CAN_SKIP_LIGHTING - - default_params - { - // lighting parameters - param_named_auto u_lightSpotlightParams spotlight_params_array 8 - param_named_auto u_lightPositionFalloff light_position_array 8 - param_named_auto u_lightDirection light_direction_array 8 - param_named_auto u_lightColorIntensity light_diffuse_colour_array 8 - - // GL sampler settings - param_named u_BaseColorSampler int 0 - param_named u_OcclusionSampler int 1 - // Only used when HAS_ATTRIBUTE_TANGENTS - param_named u_NormalSampler int 2 - param_named u_EmissiveSampler int 3 - param_named light_iblDFG int 4 - param_named light_iblSpecular int 5 - - // Filament spherical harmonics, not used but needed by the shader. - // param_named frameUniforms.iblSH float27 65504.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 - // x = IBL max mip level - // y = IBL resolution - param_named frameUniforms.iblMaxMipLevel float2 10.0 1024.0 - param_named frameUniforms.iblLuminance float 1.0 - // Only needed when HAS_REFRACTION - // param_named_auto frameUniforms.clipFromWorldMatrix viewproj_matrix - // exposure = 1.0 / (pow(2.0, ev100) * 1.2) - param_named frameUniforms.exposure float 0.0000260416666666666666666 - // This is only needed when using emissive! i.e. MATERIAL_HAS_EMISSIVE defined. - // Computes the camera's EV100 from exposure settings - // aperture in f-stops - // shutterSpeed in seconds - // sensitivity in ISO - // ev100 = log2((aperture * aperture) / shutterSpeed * 100.0 / sensitivity); - // Aperture: f/16 - // Shutter speed: 1/125s - // ISO: 100 - param_named frameUniforms.ev100 float 14.965784284662087043610958288468 - param_named_auto frameUniforms.cameraPosition camera_position - shared_params_ref SphericalHarmonicsEnvironment - } -} - -vertex_program PBR_filament_vs unified -{ - delegate PBR_filament_vs_glsl -} - -fragment_program PBR_filament_fs unified -{ - delegate PBR_filament_fs_glsl -} - -fragment_program PBR_NO_SSAO_filament_fs unified -{ - delegate PBR_NO_SSAO_filament_fs_glsl -} - -fragment_program PBR_filament_clear_coat_fs unified -{ - delegate PBR_filament_clear_coat_fs_glsl -} - -fragment_program PBR_filament_clear_coat_ior_change_fs unified -{ - delegate PBR_filament_clear_coat_ior_change_fs_glsl -} - -fragment_program PBR_filament_cloth_fs unified -{ - delegate PBR_filament_fs_cloth_glsl -} diff --git a/Samples/Media/PBR/filament/pbr_filament.vert.glsl b/Samples/Media/PBR/filament/pbr_filament.vert.glsl deleted file mode 100644 index 63d58c42585..00000000000 --- a/Samples/Media/PBR/filament/pbr_filament.vert.glsl +++ /dev/null @@ -1,189 +0,0 @@ -#version 330 - -// Apparently needed by layout(location = ) syntax -#extension GL_ARB_separate_shader_objects : enable - -in vec4 position; - -#if defined(HAS_ATTRIBUTE_TANGENTS) -in vec4 normal; -in vec4 tangent; -#endif - -#if defined(HAS_ATTRIBUTE_COLOR) -in vec4 colour; -#endif - -#if defined(HAS_ATTRIBUTE_UV0) -in vec2 uv0; -#endif - -#if defined(HAS_ATTRIBUTE_UV1) -in vec2 uv1; -#endif - -out highp vec3 vertex_worldPosition; -#if defined(HAS_ATTRIBUTE_TANGENTS) -out mediump vec3 vertex_worldNormal; -#if defined(MATERIAL_HAS_ANISOTROPY) || defined(MATERIAL_HAS_NORMAL) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL) -out mediump vec3 vertex_worldTangent; -out mediump vec3 vertex_worldBitangent; -#endif -#endif - -#if defined(HAS_ATTRIBUTE_COLOR) -out mediump vec4 vertex_color; -#endif - -#if defined(HAS_ATTRIBUTE_UV0) && !defined(HAS_ATTRIBUTE_UV1) -out highp vec2 vertex_uv01; -#elif defined(HAS_ATTRIBUTE_UV1) -out highp vec4 vertex_uv01; -#endif - -#if defined(HAS_SHADOWING) && defined(HAS_DIRECTIONAL_LIGHTING) -out highp vec4 vertex_lightSpacePosition; -#endif - -#include "pbr_filament_objectuniforms.glsl" -#include "pbr_filament_frameuniforms.glsl" - -#include "common_getters.fs" -#include "common_math.fs" -#include "getters.vs" -#include "material_inputs.vs" - -// This is mainly from main.vs - -void main() -{ - // Initialize the inputs to sensible default values, see material_inputs.vs - MaterialVertexInputs material; - initMaterialVertex(material); - -#if defined(HAS_ATTRIBUTE_TANGENTS) - // If the material defines a value for the "normal" property, we need to output - // the full orthonormal basis to apply normal mapping - #if defined(MATERIAL_HAS_ANISOTROPY) || defined(MATERIAL_HAS_NORMAL) || defined(MATERIAL_HAS_CLEAR_COAT_NORMAL) - // Extract the normal and tangent in world space from the input quaternion - // We encode the orthonormal basis as a quaternion to save space in the attributes - // toTangentFrame(mesh_tangents, material.worldNormal, vertex_worldTangent); - // Ogre does not provide "orthonormal basis quaternion" but tangents/normals/binormals directly. - material.worldNormal = normal.xyz; - vertex_worldTangent = tangent.xyz; - - #if defined(HAS_SKINNING_OR_MORPHING) - - if (objectUniforms.morphingEnabled == 1) { - vec3 normal0, normal1, normal2, normal3; - toTangentFrame(mesh_custom4, normal0); - toTangentFrame(mesh_custom5, normal1); - toTangentFrame(mesh_custom6, normal2); - toTangentFrame(mesh_custom7, normal3); - material.worldNormal += objectUniforms.morphWeights.x * normal0; - material.worldNormal += objectUniforms.morphWeights.y * normal1; - material.worldNormal += objectUniforms.morphWeights.z * normal2; - material.worldNormal += objectUniforms.morphWeights.w * normal3; - material.worldNormal = normalize(material.worldNormal); - } - - if (objectUniforms.skinningEnabled == 1) { - skinNormal(material.worldNormal, mesh_bone_indices, mesh_bone_weights); - skinNormal(vertex_worldTangent, mesh_bone_indices, mesh_bone_weights); - } - - #endif - - // We don't need to normalize here, even if there's a scale in the matrix - // because we ensure the worldFromModelNormalMatrix pre-scales the normal such that - // all its components are < 1.0. This precents the bitangent to exceed the range of fp16 - // in the fragment shader, where we renormalize after interpolation - // vertex_worldTangent = objectUniforms.worldFromModelNormalMatrix * vertex_worldTangent; - // material.worldNormal = objectUniforms.worldFromModelNormalMatrix * material.worldNormal; - mat3 worldFromModelNormalMatrix = mat3(objectUniforms.worldFromModelMatrix); - worldFromModelNormalMatrix = mat3( - normalize(worldFromModelNormalMatrix[0]), - normalize(worldFromModelNormalMatrix[1]), - normalize(worldFromModelNormalMatrix[2]) - ); - - vertex_worldTangent = worldFromModelNormalMatrix * tangent.xyz; - material.worldNormal = worldFromModelNormalMatrix * normal.xyz; - - vertex_worldTangent = normalize(vertex_worldTangent - dot(normalize(material.worldNormal), vertex_worldTangent) * normalize(material.worldNormal)); - - // Reconstruct the bitangent from the normal and tangent. We don't bother with - // normalization here since we'll do it after interpolation in the fragment stage - // vertex_worldBitangent = - // cross(material.worldNormal, vertex_worldTangent) * sign(tangent.w); - vertex_worldBitangent = cross(material.worldNormal, vertex_worldTangent) * sign(tangent.w); - #else // MATERIAL_HAS_ANISOTROPY || MATERIAL_HAS_NORMAL - // Without anisotropy or normal mapping we only need the normal vector - // toTangentFrame(mesh_tangents, material.worldNormal); - - #if defined(HAS_SKINNING_OR_MORPHING) - if (objectUniforms.skinningEnabled == 1) { - skinNormal(material.worldNormal, mesh_bone_indices, mesh_bone_weights); - } - #endif - - // material.worldNormal = objectUniforms.worldFromModelNormalMatrix * material.worldNormal; - - #endif // MATERIAL_HAS_ANISOTROPY || MATERIAL_HAS_NORMAL -#endif // HAS_ATTRIBUTE_TANGENTS - - // Invoke user code - // materialVertex(material); - - // Handle built-in interpolated attributes -#if defined(HAS_ATTRIBUTE_COLOR) - vertex_color = material.color; -#endif -#if defined(HAS_ATTRIBUTE_UV0) - vertex_uv01.xy = material.uv0; -#endif -#if defined(HAS_ATTRIBUTE_UV1) - vertex_uv01.zw = material.uv1; -#endif - - // Handle user-defined interpolated attributes -#if defined(VARIABLE_CUSTOM0) - VARIABLE_CUSTOM_AT0 = material.VARIABLE_CUSTOM0; -#endif -#if defined(VARIABLE_CUSTOM1) - VARIABLE_CUSTOM_AT1 = material.VARIABLE_CUSTOM1; -#endif -#if defined(VARIABLE_CUSTOM2) - VARIABLE_CUSTOM_AT2 = material.VARIABLE_CUSTOM2; -#endif -#if defined(VARIABLE_CUSTOM3) - VARIABLE_CUSTOM_AT3 = material.VARIABLE_CUSTOM3; -#endif - - // The world position can be changed by the user in materialVertex() - vertex_worldPosition = material.worldPosition.xyz; -#ifdef HAS_ATTRIBUTE_TANGENTS - vertex_worldNormal = material.worldNormal; -#endif - -#if defined(HAS_SHADOWING) && defined(HAS_DIRECTIONAL_LIGHTING) - vertex_lightSpacePosition = getLightSpacePosition(vertex_worldPosition, vertex_worldNormal); -#endif - -#if defined(VERTEX_DOMAIN_DEVICE) - // The other vertex domains are handled in initMaterialVertex()->computeWorldPosition() - gl_Position = getPosition(); -#else - gl_Position = getClipFromWorldMatrix() * getWorldPosition(material); -#endif - -#ifdef MATERIAL_HAS_CLIP_SPACE_TRANSFORM - gl_Position = getClipSpaceTransform(material) * gl_Position; -#endif - -#if defined(TARGET_VULKAN_ENVIRONMENT) - // In Vulkan, clip-space Z is [0,w] rather than [-w,+w] and Y is flipped. - gl_Position.y = -gl_Position.y; - gl_Position.z = (gl_Position.z + gl_Position.w) * 0.5; -#endif -} diff --git a/Samples/Media/PBR/filament/pbr_filament_frameuniforms.glsl b/Samples/Media/PBR/filament/pbr_filament_frameuniforms.glsl deleted file mode 100644 index 32619773287..00000000000 --- a/Samples/Media/PBR/filament/pbr_filament_frameuniforms.glsl +++ /dev/null @@ -1,51 +0,0 @@ - -struct FrameUniform -{ - mat4 viewFromWorldMatrix; // View matrix - mat4 clipFromViewMatrix; // Projection matrix - mat4 worldFromViewMatrix; // Inverse view matrix - mat4 viewFromClipMatrix; // Inverse projection matrix - mat4 clipFromWorldMatrix; // View and projection matrix concatenated - mat4 worldFromClipMatrix; // Inverse of concatenated view and projection matrices - mat4 lightFromWorldMatrix; - vec2 iblMaxMipLevel; // x = max mip, y = image resolution - // when reading from the cubemap, we are not pre-exposed so we apply iblLuminance - // which is not the case when we'll read from the screen-space buffer - float iblLuminance; - // light_punctual :: getPointLight/getSpotLight :: computePreExposedIntensity - // shading_lit :: addEmissive - float exposure; - // shading_parameters :: computeShadingParams - vec3 cameraPosition; - // Computes the camera's EV100 from exposure settings - // aperture in f-stops - // shutterSpeed in seconds - // sensitivity in ISO - // log2((aperture * aperture) / shutterSpeed * 100.0 / sensitivity); - // Only used when MATERIAL_HAS_EMISSIVE defined. - float ev100; - // Never actually used but defined in common_getters.fs - vec3 worldOffset; - // Used by dithering.fs (so not in use atm) - float time; - // Never actually used but defined in common_getters.fs - vec4 userTime; - // Used by SSAO (zw might be as view bounds) and dithering.fs - // post_process.vs uses the .xy components and light_punctual.fs uses .y when using froxels. - // So we never actually use this. - vec4 resolution; - float viewportWidth; - float viewportHeight; - // froxel specific values that we don't use - vec2 origin; - float oneOverFroxelDimension; - float oneOverFroxelDimensionY; - vec4 zParams; - // getFroxelIndex - uint fParamsX; - uvec2 fParams; - - vec3 iblSH[9]; // Spherical harmonics -}; - -uniform FrameUniform frameUniforms; diff --git a/Samples/Media/PBR/filament/pbr_filament_lightuniforms.glsl b/Samples/Media/PBR/filament/pbr_filament_lightuniforms.glsl deleted file mode 100644 index d7f7b406e5e..00000000000 --- a/Samples/Media/PBR/filament/pbr_filament_lightuniforms.glsl +++ /dev/null @@ -1,9 +0,0 @@ -struct LightUniform -{ - mat4 lights[LIGHT_COUNT]; -}; - -uniform LightUniform lightsUniforms; - -uniform usampler2D light_froxels; -uniform usampler2D light_records; \ No newline at end of file diff --git a/Samples/Media/PBR/filament/pbr_filament_objectuniforms.glsl b/Samples/Media/PBR/filament/pbr_filament_objectuniforms.glsl deleted file mode 100644 index 60d9603de05..00000000000 --- a/Samples/Media/PBR/filament/pbr_filament_objectuniforms.glsl +++ /dev/null @@ -1,12 +0,0 @@ -struct ObjectUniform -{ - mat4 worldFromModelMatrix; // World matrix - mat3 worldFromModelNormalMatrix; // This would be inverse transpose world matrix with only upper left 3x3 but Ogre doesn't provide one so we use the one above. -#if defined(HAS_SKINNING_OR_MORPHING) - vec4 morphWeights; // Parametric animation value - int morphingEnabled; - int skinningEnabled; -#endif -}; - -uniform ObjectUniform objectUniforms; diff --git a/Samples/Media/PBR/glTF2_PBR.material b/Samples/Media/PBR/glTF2_PBR.material deleted file mode 100644 index d541f1022a9..00000000000 --- a/Samples/Media/PBR/glTF2_PBR.material +++ /dev/null @@ -1,85 +0,0 @@ -material glTF2/PBR -{ - set $Albedo white.png - set $Normal normal_disabled.png - set $Emissive black.png - set $MetalRoughness white.png - set $AmbientOcclusion white.png - set $IBL_Diffuse black.png - set $IBL_Specular black.png - - technique - { - pass - { - texture_unit Albedo - { - texture $Albedo - } - texture_unit Normal - { - texture $Normal - } - texture_unit Emissive - { - texture $Emissive - } - texture_unit MetalRoughness - { - texture $MetalRoughness - } - texture_unit AmbientOcclusion - { - texture $AmbientOcclusion - } - texture_unit IBL_Diffuse - { - texture $IBL_Diffuse cubic gamma - } - texture_unit IBL_Specular - { - texture $IBL_Specular cubic gamma - } - texture_unit IBL_LUT - { - texture brdfLUT.png - } - - vertex_program_ref glTF2/PBR_vs - { - param_named_auto u_MVPMatrix worldviewproj_matrix - param_named_auto u_ModelMatrix world_matrix - } - fragment_program_ref glTF2/PBR_fs - { - // standard parameters - param_named_auto u_LightDirection light_position 0 - param_named_auto u_LightColor light_diffuse_colour 0 - param_named_auto u_Camera camera_position - - // PBR parameters - param_named u_BaseColorFactor float4 1 1 1 1 - param_named u_NormalScale float 1 - param_named u_EmissiveFactor float3 1 1 1 - param_named u_MetallicRoughnessValues float2 1 1 - param_named u_OcclusionStrength float 1 - - // GL sampler settings - param_named u_BaseColorSampler int 0 - param_named u_NormalSampler int 1 - param_named u_EmissiveSampler int 2 - param_named u_MetallicRoughnessSampler int 3 - param_named u_OcclusionSampler int 4 - param_named u_DiffuseEnvSampler int 5 - param_named u_SpecularEnvSampler int 6 - param_named u_brdfLUT int 7 - - // This section is used to override final color for reference app visualization - // of various parameters in the lighting equation. - param_named u_ScaleFGDSpec float4 0 0 0 0 - param_named u_ScaleDiffBaseMR float4 0 0 0 0 - param_named u_ScaleIBLAmbient float4 1 1 1 1 - } - } - } -} diff --git a/Samples/Media/PBR/normal_disabled.png b/Samples/Media/PBR/normal_disabled.png deleted file mode 100644 index 7d35507377b..00000000000 Binary files a/Samples/Media/PBR/normal_disabled.png and /dev/null differ diff --git a/Samples/Media/PBR/pbr-frag.glsl b/Samples/Media/PBR/pbr-frag.glsl deleted file mode 100644 index e7421020898..00000000000 --- a/Samples/Media/PBR/pbr-frag.glsl +++ /dev/null @@ -1,326 +0,0 @@ -#ifndef OGRE_HLSL -#ifndef GL_ES -#if defined(USE_TEX_LOD) && __VERSION__ < 150 -#extension GL_ARB_shader_texture_lod : require -#endif -#else -#extension GL_OES_standard_derivatives : enable -#extension GL_EXT_shader_texture_lod: enable -#define textureCubeLod textureLodEXT -precision highp float; -#endif -#endif - -#include - -// The MIT License -// Copyright (c) 2016-2017 Mohamad Moneimne and Contributors -// -// This fragment shader defines a reference implementation for Physically Based Shading of -// a microfacet surface material defined by a glTF model. -// -// References: -// [1] Real Shading in Unreal Engine 4 -// http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf -// [2] Physically Based Shading at Disney -// http://blog.selfshadow.com/publications/s2012-shading-course/burley/s2012_pbs_disney_brdf_notes_v3.pdf -// [3] README.md - Environment Maps -// https://github.com/KhronosGroup/glTF-WebGL-PBR/#environment-maps -// [4] "An Inexpensive BRDF Model for Physically based Rendering" by Christophe Schlick -// https://www.cs.virginia.edu/~jdl/bib/appearance/analytic%20models/schlick94b.pdf - -#ifdef USE_IBL -SAMPLERCUBE(u_DiffuseEnvSampler, 5); -SAMPLERCUBE(u_SpecularEnvSampler, 6); -SAMPLER2D(u_brdfLUT, 7); -#endif - -#ifdef HAS_BASECOLORMAP -SAMPLER2D(u_BaseColorSampler, 0); -#endif -#ifdef HAS_METALROUGHNESSMAP -SAMPLER2D(u_MetallicRoughnessSampler, 3); -#endif -#ifdef HAS_NORMALMAP -SAMPLER2D(u_NormalSampler, 1); -#endif -#ifdef HAS_EMISSIVEMAP -SAMPLER2D(u_EmissiveSampler, 2); -#endif -#ifdef HAS_OCCLUSIONMAP -SAMPLER2D(u_OcclusionSampler, 4); -#endif - -OGRE_UNIFORMS_BEGIN -uniform vec3 u_LightDirection; -uniform vec3 u_LightColor; - -#ifdef HAS_NORMALMAP -uniform float u_NormalScale; -#endif -#ifdef HAS_EMISSIVEMAP -uniform vec3 u_EmissiveFactor; -#endif -#ifdef HAS_OCCLUSIONMAP -uniform float u_OcclusionStrength; -#endif - -uniform vec2 u_MetallicRoughnessValues; -uniform vec4 u_BaseColorFactor; - -uniform vec3 u_Camera; - -// debugging flags used for shader output of intermediate PBR variables -uniform vec4 u_ScaleDiffBaseMR; -uniform vec4 u_ScaleFGDSpec; -uniform vec4 u_ScaleIBLAmbient; -OGRE_UNIFORMS_END - -// Encapsulate the various inputs used by the various functions in the shading equation -// We store values in this struct to simplify the integration of alternative implementations -// of the shading terms, outlined in the Readme.MD Appendix. -struct PBRInfo -{ - float NdotL; // cos angle between normal and light direction - float NdotV; // cos angle between normal and view direction - float NdotH; // cos angle between normal and half vector - float LdotH; // cos angle between light direction and half vector - float VdotH; // cos angle between view direction and half vector - float perceptualRoughness; // roughness value, as authored by the model creator (input to shader) - float metalness; // metallic value at the surface - vec3 reflectance0; // full reflectance color (normal incidence angle) - vec3 reflectance90; // reflectance color at grazing angle - float alphaRoughness; // roughness mapped to a more linear change in the roughness (proposed by [2]) - vec3 diffuseColor; // color contribution from diffuse lighting - vec3 specularColor; // color contribution from specular lighting -}; - -STATIC const float M_PI = 3.141592653589793; -STATIC const float c_MinRoughness = 0.04; - -vec4 SRGBtoLINEAR(vec4 srgbIn) -{ - #ifdef MANUAL_SRGB - #ifdef SRGB_FAST_APPROXIMATION - vec3 linOut = pow(srgbIn.xyz,vec3(2.2, 2.2, 2.2)); - #else //SRGB_FAST_APPROXIMATION - vec3 bLess = step(vec3(0.04045),srgbIn.xyz); - vec3 linOut = mix( srgbIn.xyz/vec3(12.92), pow((srgbIn.xyz+vec3(0.055))/vec3(1.055),vec3(2.4)), bLess ); - #endif //SRGB_FAST_APPROXIMATION - return vec4(linOut,srgbIn.w);; - #else //MANUAL_SRGB - return srgbIn; - #endif //MANUAL_SRGB -} - -// Find the normal for this fragment, pulling either from a predefined normal map -// or from the interpolated mesh normal and tangent attributes. -vec3 getNormal(mat3 tbn, vec2 v_UV) -{ - // Retrieve the tangent space matrix -#ifndef HAS_TANGENTS - vec3 pos_dx = dFdx(v_Position); - vec3 pos_dy = dFdy(v_Position); - vec3 tex_dx = dFdx(vec3(v_UV, 0.0)); - vec3 tex_dy = dFdy(vec3(v_UV, 0.0)); - vec3 t = (tex_dy.t * pos_dx - tex_dx.t * pos_dy) / (tex_dx.s * tex_dy.t - tex_dy.s * tex_dx.t); - -#ifdef HAS_NORMALS - vec3 ng = normalize(v_Normal); -#else - vec3 ng = cross(pos_dx, pos_dy); -#endif - - t = normalize(t - ng * dot(ng, t)); - vec3 b = normalize(cross(ng, t)); - tbn = mtxFromCols(t, b, ng); -#endif - -#ifdef HAS_NORMALMAP - vec3 n = texture2D(u_NormalSampler, v_UV).rgb; - n = normalize(mul(tbn, ((2.0 * n - 1.0) * vec3(u_NormalScale, u_NormalScale, 1.0)))); -#else - vec3 n = tbn[2].xyz; -#endif - - return n; -} - -#ifdef USE_IBL -// Calculation of the lighting contribution from an optional Image Based Light source. -// Precomputed Environment Maps are required uniform inputs and are computed as outlined in [1]. -// See our README.md on Environment Maps [3] for additional discussion. -vec3 getIBLContribution(PBRInfo pbrInputs, vec3 n, vec3 reflection) -{ - float mipCount = 9.0; // resolution of 512x512 - float lod = (pbrInputs.perceptualRoughness * mipCount); - // retrieve a scale and bias to F0. See [1], Figure 3 - vec3 brdf = SRGBtoLINEAR(texture2D(u_brdfLUT, vec2(pbrInputs.NdotV, 1.0 - pbrInputs.perceptualRoughness))).rgb; - vec3 diffuseLight = textureCube(u_DiffuseEnvSampler, n).rgb; - -#ifdef USE_TEX_LOD - vec3 specularLight = textureCubeLod(u_SpecularEnvSampler, reflection, lod).rgb; -#else - vec3 specularLight = textureCube(u_SpecularEnvSampler, reflection).rgb; -#endif - - vec3 diffuse = diffuseLight * pbrInputs.diffuseColor; - vec3 specular = specularLight * (pbrInputs.specularColor * brdf.x + brdf.y); - - // For presentation, this allows us to disable IBL terms - diffuse *= u_ScaleIBLAmbient.x; - specular *= u_ScaleIBLAmbient.y; - - return diffuse + specular; -} -#endif - -// Basic Lambertian diffuse -// Implementation from Lambert's Photometria https://archive.org/details/lambertsphotome00lambgoog -// See also [1], Equation 1 -vec3 diffuse(PBRInfo pbrInputs) -{ - return pbrInputs.diffuseColor / M_PI; -} - -// The following equation models the Fresnel reflectance term of the spec equation (aka F()) -// Implementation of fresnel from [4], Equation 15 -vec3 specularReflection(PBRInfo pbrInputs) -{ - return pbrInputs.reflectance0 + (pbrInputs.reflectance90 - pbrInputs.reflectance0) * pow(clamp(1.0 - pbrInputs.VdotH, 0.0, 1.0), 5.0); -} - -// This calculates the specular geometric attenuation (aka G()), -// where rougher material will reflect less light back to the viewer. -// This implementation is based on [1] Equation 4, and we adopt their modifications to -// alphaRoughness as input as originally proposed in [2]. -float geometricOcclusion(PBRInfo pbrInputs) -{ - float NdotL = pbrInputs.NdotL; - float NdotV = pbrInputs.NdotV; - float r = pbrInputs.alphaRoughness; - - float attenuationL = 2.0 * NdotL / (NdotL + sqrt(r * r + (1.0 - r * r) * (NdotL * NdotL))); - float attenuationV = 2.0 * NdotV / (NdotV + sqrt(r * r + (1.0 - r * r) * (NdotV * NdotV))); - return attenuationL * attenuationV; -} - -// The following equation(s) model the distribution of microfacet normals across the area being drawn (aka D()) -// Implementation from "Average Irregularity Representation of a Roughened Surface for Ray Reflection" by T. S. Trowbridge, and K. P. Reitz -// Follows the distribution function recommended in the SIGGRAPH 2013 course notes from EPIC Games [1], Equation 3. -float microfacetDistribution(PBRInfo pbrInputs) -{ - float roughnessSq = pbrInputs.alphaRoughness * pbrInputs.alphaRoughness; - float f = (pbrInputs.NdotH * roughnessSq - pbrInputs.NdotH) * pbrInputs.NdotH + 1.0; - return roughnessSq / (M_PI * f * f); -} - -MAIN_PARAMETERS - -IN(vec3 v_Position, TEXCOORD0) -IN(vec2 v_UV, TEXCOORD1) - -#ifdef HAS_NORMALS -#ifdef HAS_TANGENTS -IN(mat3 v_TBN, TEXCOORD2) -#else -IN(vec3 v_Normal, TEXCOORD2) -#endif -#endif - -MAIN_DECLARATION -{ - // Metallic and Roughness material properties are packed together - // In glTF, these factors can be specified by fixed scalar values - // or from a metallic-roughness map - float perceptualRoughness = u_MetallicRoughnessValues.y; - float metallic = u_MetallicRoughnessValues.x; -#ifdef HAS_METALROUGHNESSMAP - // Roughness is stored in the 'g' channel, metallic is stored in the 'b' channel. - // This layout intentionally reserves the 'r' channel for (optional) occlusion map data - vec4 mrSample = texture2D(u_MetallicRoughnessSampler, v_UV); - perceptualRoughness = mrSample.g * perceptualRoughness; - metallic = mrSample.b * metallic; -#endif - perceptualRoughness = clamp(perceptualRoughness, c_MinRoughness, 1.0); - metallic = clamp(metallic, 0.0, 1.0); - - PBRInfo pbrInputs; - - // Roughness is authored as perceptual roughness; as is convention, - // convert to material roughness by squaring the perceptual roughness [2]. - pbrInputs.alphaRoughness = perceptualRoughness * perceptualRoughness; - - // The albedo may be defined from a base texture or a flat color -#ifdef HAS_BASECOLORMAP - vec4 baseColor = SRGBtoLINEAR(texture2D(u_BaseColorSampler, v_UV)) * u_BaseColorFactor; -#else - vec4 baseColor = u_BaseColorFactor; -#endif - - vec3 f0 = vec3(0.04, 0.04, 0.04); - vec3 diffuseColor = baseColor.rgb * (vec3(1.0, 1.0, 1.0) - f0); - diffuseColor *= 1.0 - metallic; - vec3 specularColor = mix(f0, baseColor.rgb, metallic); - - // Compute reflectance. - float reflectance = max(max(specularColor.r, specularColor.g), specularColor.b); - - // For typical incident reflectance range (between 4% to 100%) set the grazing reflectance to 100% for typical fresnel effect. - // For very low reflectance range on highly diffuse objects (below 4%), incrementally reduce grazing reflecance to 0%. - float reflectance90 = clamp(reflectance * 25.0, 0.0, 1.0); - - pbrInputs.reflectance0 = specularColor.rgb; - pbrInputs.reflectance90 = vec3(1.0, 1.0, 1.0) * reflectance90; - - pbrInputs.perceptualRoughness = perceptualRoughness; - pbrInputs.metalness = metallic; - pbrInputs.diffuseColor = diffuseColor; - pbrInputs.specularColor = specularColor; - -#ifndef HAS_TANGENTS - mat3 tbn; - vec3 n = getNormal(tbn, v_UV); // normal at surface point -#else - vec3 n = getNormal(v_TBN, v_UV); -#endif - vec3 v = normalize(u_Camera - v_Position); // Vector from surface point to camera - vec3 l = normalize(u_LightDirection); // Vector from surface point to light - vec3 h = normalize(l+v); // Half vector between both l and v - vec3 reflection = -normalize(reflect(v, n)); - reflection.z *= -1.0; - - pbrInputs.NdotL = clamp(dot(n, l), 0.001, 1.0); - pbrInputs.NdotV = abs(dot(n, v)) + 0.001; - pbrInputs.NdotH = clamp(dot(n, h), 0.0, 1.0); - pbrInputs.LdotH = clamp(dot(l, h), 0.0, 1.0); - pbrInputs.VdotH = clamp(dot(v, h), 0.0, 1.0); - - // Calculate the shading terms for the microfacet specular shading model - vec3 F = specularReflection(pbrInputs); - float G = geometricOcclusion(pbrInputs); - float D = microfacetDistribution(pbrInputs); - - // Calculation of analytical lighting contribution - vec3 diffuseContrib = (1.0 - F) * diffuse(pbrInputs); - vec3 specContrib = F * G * D / (4.0 * pbrInputs.NdotL * pbrInputs.NdotV); - vec3 color = pbrInputs.NdotL * u_LightColor * (diffuseContrib + specContrib); - - // Calculate lighting contribution from image based lighting source (IBL) -#ifdef USE_IBL - color += getIBLContribution(pbrInputs, n, reflection); -#endif - - // Apply optional PBR terms for additional (optional) shading -#ifdef HAS_OCCLUSIONMAP - float ao = texture2D(u_OcclusionSampler, v_UV).r; - color = mix(color, color * ao, u_OcclusionStrength); -#endif - -#ifdef HAS_EMISSIVEMAP - vec3 emissive = SRGBtoLINEAR(texture2D(u_EmissiveSampler, v_UV)).rgb * u_EmissiveFactor; - color += emissive; -#endif - - gl_FragColor = vec4(pow(color,vec3(1.0/2.2, 1.0/2.2, 1.0/2.2)), baseColor.a); -} diff --git a/Samples/Media/PBR/pbr-vert.glsl b/Samples/Media/PBR/pbr-vert.glsl deleted file mode 100644 index b45d0de0f20..00000000000 --- a/Samples/Media/PBR/pbr-vert.glsl +++ /dev/null @@ -1,61 +0,0 @@ -#include - -// The MIT License -// Copyright (c) 2016-2017 Mohamad Moneimne and Contributors - -OGRE_UNIFORMS( -uniform mat4 u_MVPMatrix; -uniform mat4 u_ModelMatrix; -) - -MAIN_PARAMETERS - -IN(vec4 position, POSITION) -#ifdef HAS_NORMALS -IN(vec4 normal, NORMAL) -#endif -#ifdef HAS_TANGENTS -IN(vec4 tangent, TANGENT) -#endif -#ifdef HAS_UV -IN(vec2 uv0, TEXCOORD0) -#endif - -OUT(vec3 v_Position, TEXCOORD0) -OUT(vec2 v_UV, TEXCOORD1) - -#ifdef HAS_NORMALS -#ifdef HAS_TANGENTS -OUT(mat3 v_TBN, TEXCOORD2) -#else -OUT(vec3 v_Normal, TEXCOORD2) -#endif -#endif - - -MAIN_DECLARATION -{ - vec4 pos = mul(u_ModelMatrix, position); - v_Position = vec3(pos.xyz) / pos.w; - - #ifdef HAS_NORMALS - #ifdef HAS_TANGENTS - vec3 normalW = normalize(mul(u_ModelMatrix, vec4(normal.xyz, 0.0)).xyz); - vec3 tangentW = normalize(mul(u_ModelMatrix, vec4(tangent.xyz, 0.0)).xyz); - vec3 bitangentW = cross(normalW, tangentW) * tangent.w; - v_TBN = mtxFromCols(tangentW, bitangentW, normalW); - #else // HAS_TANGENTS != 1 - v_Normal = normalize(vec3(mul(u_ModelMatrix, vec4(normal.xyz, 0.0)))); - #endif - #endif - - #ifdef HAS_UV - v_UV = uv0; - #else - v_UV = vec2(0.,0.); - #endif - - gl_Position = mul(u_MVPMatrix, position); // needs w for proper perspective correction -} - - diff --git a/Samples/Media/PBR/pbr.program b/Samples/Media/PBR/pbr.program deleted file mode 100644 index 67116ed6b9b..00000000000 --- a/Samples/Media/PBR/pbr.program +++ /dev/null @@ -1,24 +0,0 @@ -vertex_program glTF2/PBR_vs hlsl glsl glsles glslang -{ - source pbr-vert.glsl - preprocessor_defines HAS_NORMALS,HAS_TANGENTS,HAS_UV -} - -fragment_program glTF2/PBR_fs_glsl glsl glslang -{ - source pbr-frag.glsl - preprocessor_defines MANUAL_SRGB,SRGB_FAST_APPROXIMATION,HAS_NORMALS,HAS_TANGENTS,HAS_BASECOLORMAP,HAS_NORMALMAP,HAS_EMISSIVEMAP,HAS_METALROUGHNESSMAP,HAS_OCCLUSIONMAP,USE_IBL,USE_TEX_LOD -} - -fragment_program glTF2/PBR_fs_hlsl hlsl glsles -{ - source pbr-frag.glsl - target ps_2_a - preprocessor_defines MANUAL_SRGB,SRGB_FAST_APPROXIMATION,HAS_NORMALS,HAS_TANGENTS,HAS_BASECOLORMAP,HAS_NORMALMAP,HAS_EMISSIVEMAP,HAS_METALROUGHNESSMAP,HAS_OCCLUSIONMAP,USE_IBL -} - -fragment_program glTF2/PBR_fs unified -{ - delegate glTF2/PBR_fs_glsl - delegate glTF2/PBR_fs_hlsl -} \ No newline at end of file diff --git a/Samples/Media/PBR/studio_garden_diffuse_nx.png b/Samples/Media/PBR/studio_garden_diffuse_nx.png deleted file mode 100644 index d8ee66a232b..00000000000 Binary files a/Samples/Media/PBR/studio_garden_diffuse_nx.png and /dev/null differ diff --git a/Samples/Media/PBR/studio_garden_diffuse_ny.png b/Samples/Media/PBR/studio_garden_diffuse_ny.png deleted file mode 100644 index d46552e17a1..00000000000 Binary files a/Samples/Media/PBR/studio_garden_diffuse_ny.png and /dev/null differ diff --git a/Samples/Media/PBR/studio_garden_diffuse_nz.png b/Samples/Media/PBR/studio_garden_diffuse_nz.png deleted file mode 100644 index 63475e6f51e..00000000000 Binary files a/Samples/Media/PBR/studio_garden_diffuse_nz.png and /dev/null differ diff --git a/Samples/Media/PBR/studio_garden_diffuse_px.png b/Samples/Media/PBR/studio_garden_diffuse_px.png deleted file mode 100644 index b69193e45b4..00000000000 Binary files a/Samples/Media/PBR/studio_garden_diffuse_px.png and /dev/null differ diff --git a/Samples/Media/PBR/studio_garden_diffuse_py.png b/Samples/Media/PBR/studio_garden_diffuse_py.png deleted file mode 100644 index 002755092e1..00000000000 Binary files a/Samples/Media/PBR/studio_garden_diffuse_py.png and /dev/null differ diff --git a/Samples/Media/PBR/studio_garden_diffuse_pz.png b/Samples/Media/PBR/studio_garden_diffuse_pz.png deleted file mode 100644 index ea8ee395bc8..00000000000 Binary files a/Samples/Media/PBR/studio_garden_diffuse_pz.png and /dev/null differ diff --git a/Samples/Media/PBR/white.png b/Samples/Media/PBR/white.png deleted file mode 100644 index 818c71d03f4..00000000000 Binary files a/Samples/Media/PBR/white.png and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/Carpet_Diamond_Olive.jpg b/Samples/Media/PCZAppMedia/Carpet_Diamond_Olive.jpg deleted file mode 100644 index c94e0471544..00000000000 Binary files a/Samples/Media/PCZAppMedia/Carpet_Diamond_Olive.jpg and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/Metal_Brass_Ceiling.jpg b/Samples/Media/PCZAppMedia/Metal_Brass_Ceiling.jpg deleted file mode 100644 index c1123dbb38f..00000000000 Binary files a/Samples/Media/PCZAppMedia/Metal_Brass_Ceiling.jpg and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/Metal_Embossed.jpg b/Samples/Media/PCZAppMedia/Metal_Embossed.jpg deleted file mode 100644 index 6902ca8ab46..00000000000 Binary files a/Samples/Media/PCZAppMedia/Metal_Embossed.jpg and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/Metal_Rusted.jpg b/Samples/Media/PCZAppMedia/Metal_Rusted.jpg deleted file mode 100644 index a98a19a9f21..00000000000 Binary files a/Samples/Media/PCZAppMedia/Metal_Rusted.jpg and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/Metal_Rusted1.jpg b/Samples/Media/PCZAppMedia/Metal_Rusted1.jpg deleted file mode 100644 index a98a19a9f21..00000000000 Binary files a/Samples/Media/PCZAppMedia/Metal_Rusted1.jpg and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/Metal_Steel_Textured.jpg b/Samples/Media/PCZAppMedia/Metal_Steel_Textured.jpg deleted file mode 100644 index 957a0ade481..00000000000 Binary files a/Samples/Media/PCZAppMedia/Metal_Steel_Textured.jpg and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/Metal_Steel_Textured_White.jpg b/Samples/Media/PCZAppMedia/Metal_Steel_Textured_White.jpg deleted file mode 100644 index 53e8b3859fa..00000000000 Binary files a/Samples/Media/PCZAppMedia/Metal_Steel_Textured_White.jpg and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/ROOM.material b/Samples/Media/PCZAppMedia/ROOM.material deleted file mode 100644 index c668661c164..00000000000 --- a/Samples/Media/PCZAppMedia/ROOM.material +++ /dev/null @@ -1,149 +0,0 @@ -material SketchupDefault -{ - technique - { - pass - { - diffuse 0.882352941176471 0.882352941176471 0.784313725490196 - } - } -} -material Metal_Brass_Ceiling -{ - technique - { - pass - { - diffuse 1 1 1 1.0 - texture_unit - { - texture Metal_Brass_Ceiling.jpg - } - } - } -} -material Metal_Embossed -{ - technique - { - pass - { - diffuse 1 1 1 1.0 - texture_unit - { - texture Metal_Embossed.jpg - } - } - } -} -material Metal_Steel_Textured_White -{ - technique - { - pass - { - diffuse 1 1 1 1.0 - texture_unit - { - texture Metal_Steel_Textured_White.jpg - } - } - } -} -material Metal_Steel_Textured -{ - technique - { - pass - { - diffuse 1 1 1 1.0 - texture_unit - { - texture Metal_Steel_Textured.jpg - } - } - } -} -material Metal_Rusted -{ - technique - { - pass - { - diffuse 1 1 1 1.0 - texture_unit - { - texture Metal_Rusted.jpg - } - } - } -} -material Material1 -{ - technique - { - pass - { - diffuse 0.250980392156863 0.250980392156863 0.250980392156863 1.0 - } - } -} -material [Metal_Rusted]1 -{ - technique - { - pass - { - diffuse 1 1 1 1.0 - texture_unit - { - texture Metal_Rusted.jpg - } - } - } -} -material Carpet_Diamond_Olive -{ - technique - { - pass - { - diffuse 1 1 1 1.0 - texture_unit - { - texture Carpet_Diamond_Olive.jpg - } - } - } -} -material Roofing_Tile_Spanish -{ - technique - { - pass - { - diffuse 1 1 1 1.0 - texture_unit - { - texture Roofing_Tile_Spanish.jpg - } - } - } -} -material TransparentGlassTinted -{ - technique - { - pass - { - scene_blend add - depth_write off - cull_hardware none - - texture_unit - { - texture Translucent_Glass_Tinted.jpg - } - } - } -} diff --git a/Samples/Media/PCZAppMedia/ROOM_NX.mesh b/Samples/Media/PCZAppMedia/ROOM_NX.mesh deleted file mode 100644 index a41935ce21b..00000000000 Binary files a/Samples/Media/PCZAppMedia/ROOM_NX.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/ROOM_NY.mesh b/Samples/Media/PCZAppMedia/ROOM_NY.mesh deleted file mode 100644 index 02d5533423e..00000000000 Binary files a/Samples/Media/PCZAppMedia/ROOM_NY.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/ROOM_NZ.mesh b/Samples/Media/PCZAppMedia/ROOM_NZ.mesh deleted file mode 100644 index b2f8144a262..00000000000 Binary files a/Samples/Media/PCZAppMedia/ROOM_NZ.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/ROOM_PX.mesh b/Samples/Media/PCZAppMedia/ROOM_PX.mesh deleted file mode 100644 index 8d7b92eec27..00000000000 Binary files a/Samples/Media/PCZAppMedia/ROOM_PX.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/ROOM_PY.mesh b/Samples/Media/PCZAppMedia/ROOM_PY.mesh deleted file mode 100644 index ec26eecc9bf..00000000000 Binary files a/Samples/Media/PCZAppMedia/ROOM_PY.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/ROOM_PZ.mesh b/Samples/Media/PCZAppMedia/ROOM_PZ.mesh deleted file mode 100644 index a05e2a33ea8..00000000000 Binary files a/Samples/Media/PCZAppMedia/ROOM_PZ.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/Roofing_Tile_Spanish.jpg b/Samples/Media/PCZAppMedia/Roofing_Tile_Spanish.jpg deleted file mode 100644 index 78910327489..00000000000 Binary files a/Samples/Media/PCZAppMedia/Roofing_Tile_Spanish.jpg and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/Translucent_Glass_Tinted.jpg b/Samples/Media/PCZAppMedia/Translucent_Glass_Tinted.jpg deleted file mode 100644 index 7409a5921d3..00000000000 Binary files a/Samples/Media/PCZAppMedia/Translucent_Glass_Tinted.jpg and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/Translucent_Glass_Tinted1.jpg b/Samples/Media/PCZAppMedia/Translucent_Glass_Tinted1.jpg deleted file mode 100644 index 7409a5921d3..00000000000 Binary files a/Samples/Media/PCZAppMedia/Translucent_Glass_Tinted1.jpg and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/Wood_Floor.jpg b/Samples/Media/PCZAppMedia/Wood_Floor.jpg deleted file mode 100644 index 97b7a286168..00000000000 Binary files a/Samples/Media/PCZAppMedia/Wood_Floor.jpg and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/building_exterior.mesh b/Samples/Media/PCZAppMedia/building_exterior.mesh deleted file mode 100644 index 22cfba050b6..00000000000 Binary files a/Samples/Media/PCZAppMedia/building_exterior.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/room_nxnynz.mesh b/Samples/Media/PCZAppMedia/room_nxnynz.mesh deleted file mode 100644 index ae554c85d2a..00000000000 Binary files a/Samples/Media/PCZAppMedia/room_nxnynz.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/room_nxpx.mesh b/Samples/Media/PCZAppMedia/room_nxpx.mesh deleted file mode 100644 index 4a289820354..00000000000 Binary files a/Samples/Media/PCZAppMedia/room_nxpx.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/room_nxpxnypynzpz.mesh b/Samples/Media/PCZAppMedia/room_nxpxnypynzpz.mesh deleted file mode 100644 index 9c46aa478f7..00000000000 Binary files a/Samples/Media/PCZAppMedia/room_nxpxnypynzpz.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/room_nxpxnz.mesh b/Samples/Media/PCZAppMedia/room_nxpxnz.mesh deleted file mode 100644 index 4746045ef9b..00000000000 Binary files a/Samples/Media/PCZAppMedia/room_nxpxnz.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/room_nxpxnzpz.mesh b/Samples/Media/PCZAppMedia/room_nxpxnzpz.mesh deleted file mode 100644 index d8a8b1de6bd..00000000000 Binary files a/Samples/Media/PCZAppMedia/room_nxpxnzpz.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/room_nxpxpz.mesh b/Samples/Media/PCZAppMedia/room_nxpxpz.mesh deleted file mode 100644 index 8a37c34ce9b..00000000000 Binary files a/Samples/Media/PCZAppMedia/room_nxpxpz.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/room_nxpynz.mesh b/Samples/Media/PCZAppMedia/room_nxpynz.mesh deleted file mode 100644 index 8b41888293a..00000000000 Binary files a/Samples/Media/PCZAppMedia/room_nxpynz.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/room_nxpz.mesh b/Samples/Media/PCZAppMedia/room_nxpz.mesh deleted file mode 100644 index afac2d77796..00000000000 Binary files a/Samples/Media/PCZAppMedia/room_nxpz.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/room_nypy.mesh b/Samples/Media/PCZAppMedia/room_nypy.mesh deleted file mode 100644 index 564b5c589f5..00000000000 Binary files a/Samples/Media/PCZAppMedia/room_nypy.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/room_nypy_4y.mesh b/Samples/Media/PCZAppMedia/room_nypy_4y.mesh deleted file mode 100644 index 76c0f0edbea..00000000000 Binary files a/Samples/Media/PCZAppMedia/room_nypy_4y.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/room_nzpz.mesh b/Samples/Media/PCZAppMedia/room_nzpz.mesh deleted file mode 100644 index 293700835b2..00000000000 Binary files a/Samples/Media/PCZAppMedia/room_nzpz.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/room_pxnynz.mesh b/Samples/Media/PCZAppMedia/room_pxnynz.mesh deleted file mode 100644 index c70792995f1..00000000000 Binary files a/Samples/Media/PCZAppMedia/room_pxnynz.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/room_pxpynz.mesh b/Samples/Media/PCZAppMedia/room_pxpynz.mesh deleted file mode 100644 index 43f37c0a85a..00000000000 Binary files a/Samples/Media/PCZAppMedia/room_pxpynz.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/room_pxpz.mesh b/Samples/Media/PCZAppMedia/room_pxpz.mesh deleted file mode 100644 index b08c9ddde47..00000000000 Binary files a/Samples/Media/PCZAppMedia/room_pxpz.mesh and /dev/null differ diff --git a/Samples/Media/PCZAppMedia/terrain2.cfg b/Samples/Media/PCZAppMedia/terrain2.cfg deleted file mode 100644 index b3b7a939d3c..00000000000 --- a/Samples/Media/PCZAppMedia/terrain2.cfg +++ /dev/null @@ -1,71 +0,0 @@ -# The main world texture (if you wish the terrain manager to create a material for you) -WorldTexture=terrain_texture.jpg - -# The detail texture (if you wish the terrain manager to create a material for you) -DetailTexture=terrain_detail.jpg - -#number of times the detail texture will tile in a terrain tile -DetailTile=3 - -# Heightmap source -PageSource=Heightmap - -# Heightmap-source specific settings -Heightmap.image=terrain2.png - -# If you use RAW, fill in the below too -# RAW-specific setting - size (horizontal/vertical) -#Heightmap.raw.size=513 -# RAW-specific setting - bytes per pixel (1 = 8bit, 2=16bit) -#Heightmap.raw.bpp=2 - -# How large is a page of tiles (in vertices)? Must be (2^n)+1 -PageSize=513 - -# How large is each tile? Must be (2^n)+1 and be smaller than PageSize -TileSize=65 - -# The maximum error allowed when determining which LOD to use -MaxPixelError=3 - -# The size of a terrain page, in world units -PageWorldX=1500 -PageWorldZ=1500 -# Maximum height of the terrain -MaxHeight=250 - -# Upper LOD limit -MaxMipMapLevel=5 - -#VertexNormals=yes -#VertexColors=yes -#UseTriStrips=yes - -# Use vertex program to morph LODs, if available -VertexProgramMorph=yes - -# The proportional distance range at which the LOD morph starts to take effect -# This is as a proportion of the distance between the current LODs effective range, -# and the effective range of the next lower LOD -LODMorphStart=0.2 - -# This following section is for if you want to provide your own terrain shading routine -# Note that since you define your textures within the material this makes the -# WorldTexture and DetailTexture settings redundant - -# The name of the vertex program parameter you wish to bind the morph LOD factor to -# this is 0 when there is no adjustment (highest) to 1 when the morph takes it completely -# to the same position as the next lower LOD -# USE THIS IF YOU USE HIGH-LEVEL VERTEX PROGRAMS WITH LOD MORPHING -#MorphLODFactorParamName=morphFactor - -# The index of the vertex program parameter you wish to bind the morph LOD factor to -# this is 0 when there is no adjustment (highest) to 1 when the morph takes it completely -# to the same position as the next lower LOD -# USE THIS IF YOU USE ASSEMBLER VERTEX PROGRAMS WITH LOD MORPHING -#MorphLODFactorParamIndex=4 - -# The name of the material you will define to shade the terrain -#CustomMaterialName=TestTerrainMaterial - - diff --git a/Samples/Media/PCZAppMedia/terrain2.png b/Samples/Media/PCZAppMedia/terrain2.png deleted file mode 100644 index 18b620b2dfe..00000000000 Binary files a/Samples/Media/PCZAppMedia/terrain2.png and /dev/null differ diff --git a/Samples/Media/materials/programs/Cg/Example_Projection.cg b/Samples/Media/materials/programs/Cg/Example_Projection.cg deleted file mode 100644 index c43f59041bd..00000000000 --- a/Samples/Media/materials/programs/Cg/Example_Projection.cg +++ /dev/null @@ -1,28 +0,0 @@ - -void generalPurposeProjection_vp( - float4 pos : POSITION, - - out float4 oPos : POSITION, - out float4 texCoord : TEXCOORD0, - - uniform float4x4 worldViewProjMatrix, - uniform float4x4 worldMatrix, - uniform float4x4 texViewProjMatrix) -{ - oPos = mul(worldViewProjMatrix, pos); - // multiply position by world matrix, then by projective view/proj - float4 newpos = mul(worldMatrix, pos); - texCoord = mul(texViewProjMatrix, newpos); - -} - -void generalPurposeProjection_fp( - float4 texCoord : TEXCOORD0, - out float4 col : COLOR, - uniform sampler2D texMap) -{ - col = tex2Dproj(texMap, texCoord); - -} - - diff --git a/Samples/Media/materials/programs/Cg/HeatVision.cg b/Samples/Media/materials/programs/Cg/HeatVision.cg deleted file mode 100644 index e99598303d6..00000000000 --- a/Samples/Media/materials/programs/Cg/HeatVision.cg +++ /dev/null @@ -1,195 +0,0 @@ -////////////////////////////////////////////// -// CASTER PASS // -// HEAT // -////////////////////////////////////////////// - -// vs_1_1 -void HeatCaster_vp( - // in - float4 vPos: POSITION, - float4 vNormal: NORMAL, - - // out - out float4 oPos: POSITION, - out float2 oNDotV: TEXCOORD0, - - // parameters - uniform float4x4 worldViewProj, - uniform float3 eyePosition // object space - ) -{ - float4 eyeDir = float4(eyePosition - vPos.xyz, 0); - eyeDir = normalize(eyeDir); - oPos = mul( worldViewProj, vPos ); - oNDotV = clamp( dot( vNormal, eyeDir ), 0, 1 ); -} - -// ps_2_0 -float4 HeatCaster_fp( - // input from vp - float2 iNDotV: TEXCOORD0 - ) : COLOR0 -{ - return iNDotV.x; -} - - -////////////////////////////////////////////// -// CASTER PASS // -// COLD // -////////////////////////////////////////////// - -// vs_1_1 -void ColdCaster_vp( - // in - float4 vPos: POSITION, - float4 vNormal: NORMAL, - - // out - out float4 oPos: POSITION, - out float2 oNDotV: TEXCOORD0, - - // parameters - uniform float4x4 worldViewProj, - uniform float3 eyePosition // object space - ) -{ - float4 eyeDir = float4(eyePosition - vPos.xyz, 0); - eyeDir = normalize(eyeDir); - oPos = mul( worldViewProj, vPos ); - oNDotV = clamp( dot( vNormal, eyeDir ), 0, 1 ); -} - -// ps_2_0 -float4 ColdCaster_fp( - // input from vp - float2 iNDotV: TEXCOORD0 - ) : COLOR0 -{ - return iNDotV.x / 2; -} - - -////////////////////////////////////////////// -// PASS 1 - Light to heat conversion // -////////////////////////////////////////////// - -// ps_2_0 -void LightToHeat_fp( - // input from vp - float4 inDiffuse: COLOR0, - float2 inUV0: TEXCOORD0, - - // out - out float4 outColor: COLOR0, - - // params - uniform float4 random_fractions, - uniform float4 heatBiasScale, - uniform float4 depth_modulator, - - uniform sampler2D Input, // output of HeatVisionCaster_fp (NdotV) - uniform sampler2D NoiseMap, - uniform sampler2D HeatLookup - ) -{ - float depth, heat, interference; - - // Output constant color: - depth = tex2D( Input, inUV0 ); - depth *= (depth * depth_modulator); - - heat = (depth * heatBiasScale.y); - -// if (depth > 0) - { - interference = -0.5 + tex2D( NoiseMap, inUV0 + float2( random_fractions.x, random_fractions.y ) ); - interference *= interference; - interference *= 1 - heat; - heat += interference;//+ heatBiasScale.x; - } - -/* - heatBias isn't used for now - if (heat > 0) - heat += heatBiasScale.x; -*/ - - // Clamp UVs - heat = max( 0.005, min( 0.995, heat ) ); - outColor = tex2D( HeatLookup, float2( heat, 0.f ) ); -} - - -////////////////////////////////////////////// -// PASS 2 - add simple blur (final pass) // -////////////////////////////////////////////// - -// ps_2_0 -void Blur_fp( - // input from vp - float4 inDiffuse: COLOR0, - float2 inUV0: TEXCOORD0, - - // out - out float4 outColor: COLOR0, - - // parameters - uniform sampler2D Input, // output of HeatVision_fp1 (HeatRenderTexture) - uniform float4 blurAmount - ) -{ - int i; - float4 tmpOutColor; - float diffuseGlowFactor; - const float2 offsets[4] = - { -/* - // hazy blur - -1.8, -1.8, - -1.8, 1.8, - 1.8, -1.8, - 1.8, 1.8 -*/ -/* - // less-hazy blur - -1.0, 2.0, - -1.0, -1.0, - 1.0, -1.0, - 1.0, 1.0 -*/ -/* - -0.326212, -0.405805, - -0.840144, -0.073580, - -0.695914, 0.457137, - -0.203345, 0.620716 -*/ - - -0.3, 0.4, - -0.3, -0.4, - 0.3, -0.4, - 0.3, 0.4 - - }; - - tmpOutColor = tex2D( Input, inUV0 ); // UV coords are in image space - - // calculate glow amount - diffuseGlowFactor = 0.0113f * (2.0 - max( tmpOutColor.r, tmpOutColor.g )); - - // basic blur filter - for (i = 0; i < 4; i++) { - tmpOutColor += tex2D( Input, inUV0 + blurAmount.x * diffuseGlowFactor * offsets[i] ); - } - - tmpOutColor *= 0.25; - - // TIPS (old-skool strikes again!) - // Pay attention here! If you use the "out float4 outColor" directly - // in your steps while creating the output color (like you remove - // the "tmpOutColor" var and just use the "outColor" directly) - // your pixel-color output IS CHANGING EACH TIME YOU DO AN ASSIGNMENT TOO! - // A temporary variable, instead, acts like a per-pixel double buffer, and - // best of all, lead to better performance. - outColor = tmpOutColor; -} diff --git a/Samples/Media/materials/programs/Cg/NightVisionFP.cg b/Samples/Media/materials/programs/Cg/NightVisionFP.cg deleted file mode 100644 index 5bbd831835b..00000000000 --- a/Samples/Media/materials/programs/Cg/NightVisionFP.cg +++ /dev/null @@ -1,27 +0,0 @@ -sampler2D RT : register(s0); -sampler3D noiseVol : register(s1); - -float4 NightVision_ps( float4 pos : POSITION, - float2 TexCoord : TEXCOORD0, - uniform float4 lum, - uniform float time) : COLOR -{ - float4 oC; - oC = tex2D(RT, TexCoord); - - //obtain luminence value - oC = dot(oC,lum); - - //add some random noise - oC += 0.2 *(tex3D(noiseVol, float3(TexCoord*5,time)))- 0.05; - - //add lens circle effect - //(could be optimised by using texture) - float dist = distance(TexCoord, float2(0.5,0.5)); - oC *= smoothstep(0.5,0.45,dist); - - //add rb to the brightest pixels - oC.rb = max (oC.r - 0.75, 0)*4; - - return oC ; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/Cg/OldTV.cg b/Samples/Media/materials/programs/Cg/OldTV.cg deleted file mode 100644 index 0fbb815d095..00000000000 --- a/Samples/Media/materials/programs/Cg/OldTV.cg +++ /dev/null @@ -1,44 +0,0 @@ -sampler2D Image: register(s0); -sampler3D Rand: register(s1); -sampler3D Noise: register(s2); - -float4 OldTV_ps(float4 posIn: POSITION, float2 img: TEXCOORD0, - uniform float distortionFreq: register(c3), - uniform float distortionScale: register(c4), - uniform float distortionRoll: register(c5), - uniform float interference: register(c7), - uniform float frameLimit: register(c8), - uniform float frameShape: register(c0), - uniform float frameSharpness: register(c1), - uniform float time_0_X: register(c2), - uniform float sin_time_0_X: register(c6) - -) : COLOR { - - // Define a frame shape - float2 pos = abs((img - 0.5) * 2.0); - float f = (1 - pos.x * pos.x) * (1 - pos.y * pos.y); - float frame = saturate(frameSharpness * (pow(f, frameShape) - frameLimit)); - - // Interference ... just a texture filled with rand() - float4 rand = tex3D(Rand, float3(1.5 * pos, time_0_X)) - 0.2; - rand -= float4(0.2,0.2,0.2,0.2); - - // Some signed noise for the distortion effect - float4 noisy = tex3D(Noise, float3(0, 0.5 * pos.y, 0.1 * time_0_X)) - 0.5; - noisy -= float4(0.5,0.5,0.5,0.5); - - // Repeat a 1 - x^2 (0 < x < 1) curve and roll it with sinus. - float dst = frac(pos.y * distortionFreq + distortionRoll * sin_time_0_X); - dst *= (1 - dst); - // Make sure distortion is highest in the center of the image - dst /= 1 + distortionScale * abs(pos.y); - - // ... and finally distort - img.x += distortionScale * noisy.x * dst; - float4 image = tex2D(Image, img); - - // Combine frame, distorted image and interference - return frame * (interference * rand.x + image); -} - diff --git a/Samples/Media/materials/programs/Cg/ParticleGS.cg b/Samples/Media/materials/programs/Cg/ParticleGS.cg deleted file mode 100644 index 3a830e8fb25..00000000000 --- a/Samples/Media/materials/programs/Cg/ParticleGS.cg +++ /dev/null @@ -1,324 +0,0 @@ -// -// Explanation of different particle types -// -#define PT_LAUNCHER 0 //Firework Launcher - launches a PT_SHELL every so many seconds -#define PT_SHELL 1 //Unexploded shell - flies from the origin and explodes into many PT_EMBERXs -#define PT_EMBER1 2 //basic particle - after it's emitted from the shell, it dies -#define PT_EMBER2 3 //after it's emitted, it explodes again into many PT_EMBER1s -#define PT_EMBER3 4 //just a differently colored ember1 -#define P_SHELLLIFE 3.0 -#define P_EMBER1LIFE 2.5 -#define P_EMBER2LIFE 1.5 -#define P_EMBER3LIFE 2.0 - -//These two were originally shader params, but they caused runtime errors -#define NUM_EMBER_1S 30 -#define NUM_EMBER_2S 15 -#define NUM_EMBER_3S 10 -//This one was originally a variant, but this also causes runtime errors -//#define MAX_EMBER_2S 15.0 - -// -// Generic particle motion handler -// - -void GSGenericHandler( float3 Pos, float3 Vel, float Timer, float Type, - float elapsedTime, - float3 frameGravity) -{ - Pos += Vel * elapsedTime; - Vel += frameGravity; - Timer -= elapsedTime; - if (Pos.y > -100) - { - emitVertex( Pos : POSITION, Vel : TEXCOORD2, Timer : TEXCOORD0, Type : TEXCOORD1); - } -} - -// -// Sample a random direction from our random texture -// -float3 RandomDir(float fOffset, float globalTime, sampler1D randomTex) -{ - float tCoord = (globalTime + fOffset) / 300.0; - return tex1D(randomTex, tCoord).rgb; -} - -// -// Launcher type particle handler -// -void GSLauncherHandler( float3 Pos, float3 Vel, float Timer, float Type, - float elapsedTime, - float globalTime, - sampler1D randomTex, - float secondsPerFirework) -{ - if(Timer <= 0) - { - float3 vRandom = normalize( RandomDir( Type, globalTime, randomTex) ); - //Give it more of an up bias - vRandom = normalize(vRandom + float3(0,2.5,0)); - - //time to emit a new SHELL - float3 outputPos = Pos + Vel*elapsedTime; - float3 outputVel = Vel + vRandom*35.0; - float outputTimer = P_SHELLLIFE + vRandom.y*0.5; - float outputType = PT_SHELL; - emitVertex(outputPos : POSITION, outputVel : TEXCOORD2, outputTimer : TEXCOORD0, outputType : TEXCOORD1); - - //reset our timer - Timer = secondsPerFirework + vRandom.x*0.4; - } - else - { - Timer -= elapsedTime; - } - - //emit ourselves to keep us alive - emitVertex( Pos : POSITION, Vel : TEXCOORD2, Timer : TEXCOORD0, Type : TEXCOORD1); -} - -// -// Shell type particle handler -// -void GSShellHandler( float3 Pos, float3 Vel, float Timer, float Type, - float elapsedTime, - float globalTime, - sampler1D randomTex, - float3 frameGravity) -{ - if(Timer <= 0) - { - float3 outputPos; - float3 outputVel; - float outputTimer; - float outputType; - - float3 vRandom = float3(0,0,0); - - //time to emit a series of new Ember1s - for(int i=0; i 0) - { - GSGenericHandler(Pos, Vel, Timer, Type, elapsedTime, frameGravity ); - } -} - -// -// Ember2 type particle handler -// -void GSEmber2Handler( float3 Pos, float3 Vel, float Timer, float Type, - float elapsedTime, - float globalTime, - sampler1D randomTex, - float3 frameGravity) -{ - if(Timer <= 0) - { - float3 outputPos; - float3 outputVel; - float outputTimer; - float outputType; - - //time to emit a series of new Ember3s - for(int i=0; i Pos : POSITION, - AttribArray Timer : TEXCOORD0, - AttribArray Type : TEXCOORD1, - AttribArray Vel : TEXCOORD2, - - uniform sampler1D randomTex : TEXUNIT0, - uniform float3 gravity, - uniform float globalTime, - uniform float elapsedTime, - uniform float secondsPerFirework - ) -{ - vec3 frameGravity = gravity * elapsedTime; - if( Type[0] == PT_LAUNCHER ) - GSLauncherHandler( Pos[0], Vel[0], Timer[0], Type[0], - elapsedTime, globalTime, randomTex, secondsPerFirework); - else if ( Type[0] == PT_SHELL ) - GSShellHandler( Pos[0], Vel[0], Timer[0], Type[0], - elapsedTime, globalTime, randomTex, frameGravity); - else if ( Type[0] == PT_EMBER1 || - Type[0] == PT_EMBER3 ) - GSEmber1Handler( Pos[0], Vel[0], Timer[0], Type[0], - elapsedTime, frameGravity); - else if( Type[0] == PT_EMBER2 ) - GSEmber2Handler( Pos[0], Vel[0], Timer[0], Type[0], - elapsedTime, globalTime, randomTex, frameGravity); -} - -struct ColoredFirework -{ - float4 pos : POSITION; - float4 color : COLOR; - float2 radius : TEXCOORD0; -}; - -//The vertex shader that prepares the fireworks for display -ColoredFirework DisplayParticles_VS -( - in float3 inPos : POSITION, - in float inTimer : TEXCOORD0, - in float inType : TEXCOORD1, - in float3 inVelocity : TEXCOORD2, - - - uniform float4x4 worldView, - uniform float4x4 proj -) -{ - ColoredFirework output; - // - // Pass the point through - // - output.pos = mul(worldView, float4(inPos,1)); - output.radius = float2(1.5); - - // - // calculate the color - // - if( inType == PT_LAUNCHER ) - { - output.color = float4(1,0.1,0.1,1); - output.radius = float2(1.0); - } - else if( inType == PT_SHELL ) - { - output.color = float4(0.1,1,1,1); - output.radius = float2(1.0); - } - else if( inType == PT_EMBER1 ) - { - output.color = float4(1,1,0.1,1); - output.color *= (inTimer / P_EMBER1LIFE ); - } - else if( inType == PT_EMBER2 ) - { - output.color = float4(1,0.1,1,1); - } - else if( inType == PT_EMBER3 ) - { - output.color = float4(1,0.1,0.1,1); - output.color *= (inTimer / P_EMBER3LIFE ); - } - - float4 tmp = mul(proj, float4(output.radius, output.pos.z, 1)); - output.radius = tmp.xy; // no w divison here, no viewport normalization in GS - output.pos = mul(proj, output.pos); - - return output; -} - -//The geometry shader that prepares the fireworks for display -POINT -TRIANGLE_OUT -void DisplayParticles_GS( AttribArray Pos : POSITION, - AttribArray Color : COLOR, - AttribArray Radius : TEXCOORD0) -{ - //float3 g_positions[4] = { float3( -1, 1, 0 ), float3( 1, 1, 0 ), float3( -1, -1, 0 ), float3( 1, -1, 0 ) }; - float2 g_positions[4] = { float2( -1, 1 ), float2( -1, -1 ), float2( 1, 1 ), float2( 1, -1 ) }; - float2 g_texcoords[4] = { float2(0,1), float2(1,1), float2(0,0), float2(1,0) }; - - - // - // Emit two new triangles - // - for(int i=0; i<4; i++) - { - float4 position = Pos[0] - float4(g_positions[i]*Radius[0], 0, 0); - emitVertex(position : POSITION, Color[0] : COLOR0, g_texcoords[i] : TEXCOORD0); - } - restartStrip(); -} - -//The pixels shaders that colors the fireworks -float4 DisplayParticles_PS( float2 iTexCoord : TEXCOORD0, - float4 iColor : COLOR0, - uniform sampler diffuseTex : register(s0)) : COLOR -{ - return tex2D(diffuseTex, iTexCoord) * iColor; - //return float4(iTexCoord.x, iTexCoord.y, 0, 1) + iColor * 0.01; - //return float4(iTexCoord.xy, 0, 1) * 0.3 + tex2D(diffuseTex, iTexCoord) * 0.7 + iColor * 0.01; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/Cg/PassthroughFP.cg b/Samples/Media/materials/programs/Cg/PassthroughFP.cg deleted file mode 100644 index 3da7ca5d897..00000000000 --- a/Samples/Media/materials/programs/Cg/PassthroughFP.cg +++ /dev/null @@ -1,14 +0,0 @@ -float4 main (float4 pos : POSITION, uniform float4 colour) : COLOR -{ - return colour; -} - -float4 mainCg (float4 colour0 : COLOR) : COLOR -{ - return colour0; -} - -float4 mainForAmbientOneTexture (float4 pos : POSITION, float2 oUv : TEXCOORD0, float4 colour0 : COLOR, uniform float4 colour) : COLOR -{ - return colour; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/Cg/PassthroughFP_sm4.cg b/Samples/Media/materials/programs/Cg/PassthroughFP_sm4.cg deleted file mode 100644 index 69aa2b87c75..00000000000 --- a/Samples/Media/materials/programs/Cg/PassthroughFP_sm4.cg +++ /dev/null @@ -1,16 +0,0 @@ -float4 main (float4 pos : SV_POSITION, - float2 oUv : TEXCOORD0, - float4 colour : COLOR) : COLOR -{ - return colour; -} - -float4 mainCg (float4 pos : SV_POSITION, float4 colour0 : COLOR) : COLOR -{ - return colour0; -} - -float4 mainForAmbientOneTexture (float4 pos : SV_POSITION, float2 oUv : TEXCOORD0, float4 colour0 : COLOR, uniform float4 colour) : COLOR -{ - return colour; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/Cg/Swizzle.gp b/Samples/Media/materials/programs/Cg/Swizzle.gp deleted file mode 100644 index 929c4e616ed..00000000000 --- a/Samples/Media/materials/programs/Cg/Swizzle.gp +++ /dev/null @@ -1,39 +0,0 @@ -!!NVgp4.0 -PRIMITIVE_IN TRIANGLES; -PRIMITIVE_OUT TRIANGLE_STRIP; -VERTICES_OUT 6; -# cgc version 2.0.0015, build date May 15 2008 -# command line args: -profile gpu_gp -# source file: gs_simple.cg -#vendor NVIDIA Corporation -#version 2.0.0.15 -#profile gpu_gp -#program geometry_swizzle -#semantic geometry_swizzle.position : POSITION -#var float4 position.__data[0] : $vin.VERTEX[0].POSITION : HPOS[0][32] : 0 : 1 -#var float4 position.__data[1] : $vin.VERTEX[1].POSITION : HPOS[1][32] : 0 : 1 -#var float4 position.__data[2] : $vin.VERTEX[2].POSITION : HPOS[2][32] : 0 : 1 -ATTRIB vertex_position = vertex.position; -TEMP RC, HC; -MOV.F result.position, vertex[0].position; -MOV.F result.color, {1, 0}.xyyx; -EMIT; -MOV.F result.position, vertex[1].position; -MOV.F result.color, {1, 0}.xyyx; -EMIT; -MOV.F result.position, vertex[2].position; -MOV.F result.color, {1, 0}.xyyx; -EMIT; -ENDPRIM; -MOV.F result.position, vertex[0].position.yxzw; -MOV.F result.color, {0, 1}.xxyy; -EMIT; -MOV.F result.position, vertex[1].position.yxzw; -MOV.F result.color, {0, 1}.xxyy; -EMIT; -MOV.F result.position, vertex[2].position.yxzw; -MOV.F result.color, {0, 1}.xxyy; -EMIT; -ENDPRIM; -END -# 20 instructions, 0 R-regs \ No newline at end of file diff --git a/Samples/Media/materials/programs/Cg/SwizzleGP.cg b/Samples/Media/materials/programs/Cg/SwizzleGP.cg deleted file mode 100644 index 7532c80a552..00000000000 --- a/Samples/Media/materials/programs/Cg/SwizzleGP.cg +++ /dev/null @@ -1,14 +0,0 @@ -// Geometry pass-through program for colored triangles -TRIANGLE void gs_swizzle(AttribArray position : POSITION) -{ - for (int i=0; i Field0.x)) - { - if (t > 0 && t < 1) - { - float4 Pos = lerp(Pos0, Pos1, t); - float3 N = lerp(N0, N1, t); - emitVertex(Pos : POSITION, N : TEXCOORD0); - } - } -} - -// Geometry shader -// input: line with adjacency (tetrahedron) -// outputs: zero, one or two triangles depending if isosurface intersects tetrahedron -LINE_ADJ -TRIANGLE_OUT -void mainGS( - AttribArray Pos : POSITION, - AttribArray N : TEXCOORD0, - AttribArray Field : TEXCOORD1 - ) -{ - // construct index for this tetrahedron - unsigned int index = (int(Field[0].y) << 3) | - (int(Field[1].y) << 2) | - (int(Field[2].y) << 1) | - int(Field[3].y); - - // don't bother if all vertices out or all vertices inside isosurface - if (index > 0 && index < 15) - { - //Uber-compressed version of the edge table. - unsigned int edgeListHex[] = - {0x0001cde0, 0x98b08c9d, 0x674046ce, 0x487bc480, - 0x21301d2e, 0x139bd910, 0x26376e20, 0x3b700000}; - - unsigned int edgeValFull = edgeListHex[index/2]; - unsigned int edgeVal = (index % 2 == 1) ? (edgeValFull & 0xFFFF) : ((edgeValFull >> 16) & 0xFFFF); - int4 e0 = int4((edgeVal >> 14) & 0x3, (edgeVal >> 12) & 0x3, (edgeVal >> 10) & 0x3, (edgeVal >> 8) & 0x3); - int4 e1 = int4((edgeVal >> 6) & 0x3, (edgeVal >> 4) & 0x3, (edgeVal >> 2) & 0x3, (edgeVal >> 0) & 0x3); - - CalcIntersection(Pos[e0.x], N[e0.x], Field[e0.x], Pos[e0.y], N[e0.y], Field[e0.y]); - CalcIntersection(Pos[e0.z], N[e0.z], Field[e0.z], Pos[e0.w], N[e0.w], Field[e0.w]); - CalcIntersection(Pos[e1.x], N[e1.x], Field[e1.x], Pos[e1.y], N[e1.y], Field[e1.y]); - - // Emit additional triangle, if necessary - if (e1.z != -1) { - CalcIntersection(Pos[e1.z], N[e1.z], Field[e1.z], Pos[e1.w], N[e1.w], Field[e1.w]); - } - } -} diff --git a/Samples/Media/materials/programs/Cg/varianceshadowcasterfp.cg b/Samples/Media/materials/programs/Cg/varianceshadowcasterfp.cg deleted file mode 100644 index f39e8a054b2..00000000000 --- a/Samples/Media/materials/programs/Cg/varianceshadowcasterfp.cg +++ /dev/null @@ -1,65 +0,0 @@ -///////////////////////////////////////////////////////////////////////////////// -// -// shadowcasterfp.cg -// -// Hamilton Chong -// (c) 2006 -// -// This is an example fragment shader for shadow caster objects. -// -///////////////////////////////////////////////////////////////////////////////// - - -// Define outputs from vertex shader. -struct VertexOut -{ - float4 position : POSITION; // can't rely on access to this - float4 pos : TEXCOORD0; // position of fragment (in homogeneous coordinates) - float4 normal : TEXCOORD1; // un-normalized normal in object space - float4 modelPos : TEXCOORD2; // coordinates of model in object space at this point -}; - -struct FragmentOut -{ - float4 color : COLOR0; -}; - -FragmentOut main( VertexOut In, // fragment to process - uniform float uDepthOffset, // offset amount (constant in eye space) - uniform float4x4 uProjection // projection matrix - ) -{ - FragmentOut Out; - - // compute the "normalized device coordinates" (no viewport applied yet) - float4 postproj = In.pos / In.pos.w; - - // get the normalized normal of the geometry seen at this point - float4 normal = normalize(In.normal); - - - // -- Computing Depth Bias Quantities ----------------------------- - - // We now compute the change in z that would signify a push in the z direction - // by 1 unit in eye space. Note that eye space z is related in a nonlinear way to - // screen space z, so this is not just a constant. - // ddepth below is how much screen space z at this point would change for that push. - // NOTE: computation of ddepth likely differs from OpenGL's glPolygonOffset "unit" - // computation, which is allowed to be vendor specific. - float4 dpwdz = mul(uProjection, float4(0.0, 0.0, 1.0, 0.0)); - float4 dpdz = (dpwdz - (postproj * dpwdz.w)) / In.pos.w; - float ddepth = abs(dpdz.z); - - // -- End depth bias helper section -------------------------------- - - // We now compute the depth of the fragment. This is the actual depth value plus - // our depth bias. The depth bias depends on how uncertain we are about the z value - // plus some constant push in the z direction. The exact coefficients to use are - // up to you, but at least it should be somewhat intuitive now what the tradeoffs are. - float depthval = postproj.z /* + (0.5 * dzlen)*/ + (uDepthOffset * ddepth); - depthval = (0.5 * depthval) + 0.5; // put into [0,1] range instead of [-1,1] - - - Out.color = float4(depthval, depthval * depthval, depthval, 0.0); - return Out; -} diff --git a/Samples/Media/materials/programs/Cg/varianceshadowcastervp.cg b/Samples/Media/materials/programs/Cg/varianceshadowcastervp.cg deleted file mode 100644 index 60d6de3a551..00000000000 --- a/Samples/Media/materials/programs/Cg/varianceshadowcastervp.cg +++ /dev/null @@ -1,44 +0,0 @@ -///////////////////////////////////////////////////////////////////////////////// -// -// shadowcastervp.cg -// -// Hamilton Chong -// (c) 2006 -// -// This is an example vertex shader for shadow caster objects. -// -///////////////////////////////////////////////////////////////////////////////// - - -// Define inputs from application. -struct VertexIn -{ - float4 position : POSITION; // vertex position in object space - float4 normal : NORMAL; // vertex normal in object space -}; - -// Define outputs from vertex shader. -struct VertexOut -{ - float4 position : POSITION; // post projection position coordinates - float4 pos : TEXCOORD0; // ditto. Not all hardware allows access values bound to POSITION in fp. - float4 normal : TEXCOORD1; // normal in object space (to be interpolated) - float4 modelPos : TEXCOORD2; // position in object space (to be interpolated) -}; - -VertexOut main( VertexIn In, // vertex to process - uniform float4x4 uModelViewProjection // model-view-projection matrix - ) -{ - VertexOut Out; // output data - - // Transform vertex position into post projective (homogenous screen) space. - Out.position = mul(uModelViewProjection, In.position); - Out.pos = mul(uModelViewProjection, In.position); - - // copy over data to interpolate using perspective correct interpolation - Out.normal = float4(In.normal.x, In.normal.y, In.normal.z, 0.0); - Out.modelPos = In.position; - - return Out; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/Cg/varianceshadowreceiverfp.cg b/Samples/Media/materials/programs/Cg/varianceshadowreceiverfp.cg deleted file mode 100644 index 28a9aacfbfc..00000000000 --- a/Samples/Media/materials/programs/Cg/varianceshadowreceiverfp.cg +++ /dev/null @@ -1,107 +0,0 @@ -///////////////////////////////////////////////////////////////////////////////// -// -// shadowreceiverfp.cg -// -// Hamilton Chong -// (c) 2006 -// -// This is an example fragment shader for shadow receiver objects. -// -///////////////////////////////////////////////////////////////////////////////// - - -sampler2D ShadowMap : TEXUNIT0; - -// Define outputs from vertex shader. -struct Vertex -{ - float4 position : POSITION; // fragment position in post projective space - float4 shadowCoord : TEXCOORD0; // fragment position in shadow map coordinates - float diffuse : TEXCOORD1; // diffuse shading value -}; - -struct Fragment -{ - float4 color : COLOR0; -}; - -Fragment main(Vertex In, - uniform float uSTexWidth, - uniform float uSTexHeight) -{ - Fragment Out; - - // compute the shadow coordinates for texture lookup - // NOTE: texture_viewproj_matrix maps z into [0,1] range, not [-1,1], so - // have to make sure shadow caster stores depth values with same convention. - float4 scoord = In.shadowCoord / In.shadowCoord.w; - - - // -- Bilinear Filtering of Sample -------------------------------------------- - - // One could use scoord.xy to look up the shadow map for depth testing, but - // we'll be implementing a simple "percentage closest filtering" algorithm instead. - // This mimics the behavior of turning on bilinear filtering on NVIDIA hardware - // when also performing shadow comparisons. This causes bilinear filtering of - // depth tests. Note that this is NOT the same as bilinear filtering the depth - // values and then doing the depth comparison. The two operations are not - // commutative. PCF is explicitly about filtering the test values since - // testing filtered z values is often meaningless. - - // Real percentage closest filtering should sample from the entire footprint - // on the shadow map, not just seek the closest four sample points. Such - // an improvement is for future work. - - - // NOTE: Assuming OpenGL convention for texture lookups with integers in centers. - // DX convention is to have integers mark sample corners - float2 tcoord; - tcoord.x = (scoord.x * uSTexWidth) - 0.5; - tcoord.y = (scoord.y * uSTexHeight) - 0.5; - float x0 = floor(tcoord.x); - float x1 = ceil(tcoord.x); - float fracx = frac(tcoord.x); - float y0 = floor(tcoord.y); - float y1 = ceil(tcoord.y); - float fracy = frac(tcoord.y); - - // sample coordinates in [0,1]^2 domain - float2 t00, t01, t10, t11; - float invWidth = 1.0 / uSTexWidth; - float invHeight = 1.0 / uSTexHeight; - t00 = float2((x0+0.5) * invWidth, (y0+0.5) * invHeight); - t10 = float2((x1+0.5) * invWidth, (y0+0.5) * invHeight); - t01 = float2((x0+0.5) * invWidth, (y1+0.5) * invHeight); - t11 = float2((x1+0.5) * invWidth, (y1+0.5) * invHeight); - - // grab the samples - float2 z00 = tex2D(ShadowMap, t00).xy; - float2 z01 = tex2D(ShadowMap, t01).xy; - float2 z10 = tex2D(ShadowMap, t10).xy; - float2 z11 = tex2D(ShadowMap, t11).xy; - - // bilinear filter the sample data - float2 d0 = ((1.0 - fracx) * z00) + (fracx * z10); - float2 d1 = ((1.0 - fracx) * z01) + (fracx * z11); - float2 datum = ((1.0 - fracy) * d0) + (fracy * d1); - - // -- Variance Shadow Mapping --------------------------------------------------- - - float zVariance = datum.y - (datum.x * datum.x); - float zDeviation = scoord.z - datum.x; - zDeviation = (zDeviation < 0.0) ? 0.0 : zDeviation; - float visibility = zVariance / (zVariance + (zDeviation * zDeviation)); - float ztest = (scoord.z < datum.x) ? 1.0:0.0; // filtering depth ok, because used only for small variance - visibility = (zVariance > 0.0) ? visibility : ztest; // if variance too small, we get garbage - //0.0000001 - - // determine that all geometry within pixel border of shadow map (and outside) is lit - float filterBorder = max(invWidth, invHeight); - visibility = (all(abs(scoord.xy-0.5)<=0.5-filterBorder)) ? visibility : 1.0; - - // ------------------------------------------------------------------------------ - - visibility *= In.diffuse; - Out.color = float4(visibility, visibility, visibility, 0.0); - return Out; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/Cg/varianceshadowreceivervp.cg b/Samples/Media/materials/programs/Cg/varianceshadowreceivervp.cg deleted file mode 100644 index ff950405ca3..00000000000 --- a/Samples/Media/materials/programs/Cg/varianceshadowreceivervp.cg +++ /dev/null @@ -1,47 +0,0 @@ -///////////////////////////////////////////////////////////////////////////////// -// -// shadowreceivervp.cg -// -// Hamilton Chong -// (c) 2006 -// -// This is an example vertex shader for shadow receiver objects. -// -///////////////////////////////////////////////////////////////////////////////// - -// Define inputs from application. -struct VertexIn -{ - float4 position : POSITION; // vertex position in object space - float4 normal : NORMAL; // vertex normal in object space -}; - -// Define outputs from vertex shader. -struct Vertex -{ - float4 position : POSITION; // vertex position in post projective space - float4 shadowCoord : TEXCOORD0; // vertex position in shadow map coordinates - float diffuse : TEXCOORD1; // diffuse shading value -}; - -Vertex main(VertexIn In, - uniform float4x4 uModelViewProjection, // model-view-projection matrix - uniform float4 uLightPosition, // light position in object space - uniform float4x4 uModel, // model matrix - uniform float4x4 uTextureViewProjection // shadow map's view projection matrix - ) -{ - Vertex Out; - - // compute diffuse shading - float3 lightDirection = normalize(uLightPosition.xyz - In.position.xyz); - Out.diffuse = dot(In.normal.xyz, lightDirection); - - // compute shadow map lookup coordinates - Out.shadowCoord = mul(uTextureViewProjection, mul(uModel, In.position)); - - // compute vertex's homogenous screen-space coordinates - Out.position = mul(uModelViewProjection, In.position); - - return Out; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/GLSL/AmbientOneTexture.glsl b/Samples/Media/materials/programs/GLSL/AmbientOneTexture.glsl deleted file mode 100644 index 1ec6d43a9fa..00000000000 --- a/Samples/Media/materials/programs/GLSL/AmbientOneTexture.glsl +++ /dev/null @@ -1,15 +0,0 @@ -uniform vec4 ambient; -uniform mat4 worldViewProj; - -attribute vec4 position; - -varying vec4 colour; - -/* - Basic ambient lighting vertex program for GLSL -*/ -void main() -{ - gl_Position = worldViewProj * position; - colour = ambient; -} diff --git a/Samples/Media/materials/programs/GLSL/AmbientOneTextureWithUV.glsl b/Samples/Media/materials/programs/GLSL/AmbientOneTextureWithUV.glsl deleted file mode 100644 index 7a54f348df9..00000000000 --- a/Samples/Media/materials/programs/GLSL/AmbientOneTextureWithUV.glsl +++ /dev/null @@ -1,18 +0,0 @@ -uniform vec4 ambient; -uniform mat4 worldViewProj; - -attribute vec4 position; -attribute vec4 uv0; - -varying vec4 colour; -varying vec4 ambientUV; - -/* - Basic ambient lighting vertex program for GLSL -*/ -void main() -{ - gl_Position = worldViewProj * position; - colour = ambient; - ambientUV = uv0; -} diff --git a/Samples/Media/materials/programs/GLSL/Bloom2_ps20.glsl b/Samples/Media/materials/programs/GLSL/Bloom2_ps20.glsl deleted file mode 100644 index f473fee441a..00000000000 --- a/Samples/Media/materials/programs/GLSL/Bloom2_ps20.glsl +++ /dev/null @@ -1,26 +0,0 @@ -//------------------------------- -//Bloom_ps20.glsl -// Blends using weights the blurred image with the sharp one -// Params: -// OriginalImageWeight -// BlurWeight -//------------------------------- - -uniform sampler2D RT; -uniform sampler2D Blur1; - -uniform float OriginalImageWeight; -uniform float BlurWeight; -varying vec2 texCoord; - -void main() -{ - vec4 sharp; - vec4 blur; - - sharp = texture2D( RT, texCoord); - blur = texture2D( Blur1, texCoord); - - gl_FragColor = ( (blur * BlurWeight) + (sharp * OriginalImageWeight) ); - //gl_FragColor = vec4(0); -} diff --git a/Samples/Media/materials/programs/GLSL/BlurH_ps20.glsl b/Samples/Media/materials/programs/GLSL/BlurH_ps20.glsl deleted file mode 100644 index 2b1d09ba76d..00000000000 --- a/Samples/Media/materials/programs/GLSL/BlurH_ps20.glsl +++ /dev/null @@ -1,54 +0,0 @@ -//------------------------------- -//BlurH_ps20.glsl -// Horizontal Gaussian-Blur pass -//------------------------------- - -uniform sampler2D Blur0; -varying vec2 texCoord; - -vec2 pos[11]; -//We use the Normal-gauss distribution formula -//f(x) being the formula, we used f(0.5)-f(-0.5); f(1.5)-f(0.5)... -float samples[11]; - -void main() -{ - pos[0] = vec2(-5.0, 0.0); - pos[1] = vec2(-4.0, 0.0); - pos[2] = vec2(-3.0, 0.0); - pos[3] = vec2(-2.0, 0.0); - pos[4] = vec2(-1.0, 0.0); - pos[5] = vec2(0.0, 0.0); - pos[6] = vec2(1.0, 0.0); - pos[7] = vec2(2.0, 0.0); - pos[8] = vec2(3.0, 0.0); - pos[9] = vec2(4.0, 0.0); - pos[10] = vec2(5.0, 0.0); - - //We use the Normal-gauss distribution formula - //f(x) being the formula, we used f(0.5)-f(-0.5); f(1.5)-f(0.5)... - //stddev=2.0 - samples[0] = 0.01222447; - samples[1] = 0.02783468; - samples[2] = 0.06559061; - samples[3] = 0.12097757; - samples[4] = 0.17466632; - samples[5] = 0.19741265; - samples[6] = 0.17466632; - samples[7] = 0.12097757; - samples[8] = 0.06559061; - samples[9] = 0.02783468; - samples[10] = 0.01222447; - - vec4 retVal; - vec4 sum; - int i = 0; - - sum = vec4( 0 ); - for( i=0;i < 11; i++ ) - { - sum += texture2D( Blur0, texCoord + (pos[i] * 0.0100000) ) * samples[i]; - } - - gl_FragColor = sum; -} diff --git a/Samples/Media/materials/programs/GLSL/BlurV_ps20.glsl b/Samples/Media/materials/programs/GLSL/BlurV_ps20.glsl deleted file mode 100644 index a21740390fa..00000000000 --- a/Samples/Media/materials/programs/GLSL/BlurV_ps20.glsl +++ /dev/null @@ -1,59 +0,0 @@ -// Note, this won't work on ATI which is why it's not used -// the issue is with the array initializers -// no card supports GL_3DL_array_objects but it does work on nvidia, not on ATI -//#extension GL_3DL_array_objects : enable - -//------------------------------- -//BlurV_ps20.glsl -// Vertical Gaussian-Blur pass -//------------------------------- - -uniform sampler2D Blur0; -varying vec2 texCoord; - -vec2 pos[11]; -//We use the Normal-gauss distribution formula -//f(x) being the formula, we used f(0.5)-f(-0.5); f(1.5)-f(0.5)... -float samples[11]; - -void main() -{ - pos[0] = vec2(0.0, -5.0); - pos[1] = vec2(0.0, -4.0); - pos[2] = vec2(0.0, -3.0); - pos[3] = vec2(0.0, -2.0); - pos[4] = vec2(0.0, -1.0); - pos[5] = vec2(0.0, 0.0); - pos[6] = vec2(0.0, 1.0); - pos[7] = vec2(0.0, 2.0); - pos[8] = vec2(0.0, 3.0); - pos[9] = vec2(0.0, 4.0); - pos[10] = vec2(0.0, 5.0); - - //We use the Normal-gauss distribution formula - //f(x) being the formula, we used f(0.5)-f(-0.5); f(1.5)-f(0.5)... - //stddev=2.0 - samples[0] = 0.01222447; - samples[1] = 0.02783468; - samples[2] = 0.06559061; - samples[3] = 0.12097757; - samples[4] = 0.17466632; - samples[5] = 0.19741265; - samples[6] = 0.17466632; - samples[7] = 0.12097757; - samples[8] = 0.06559061; - samples[9] = 0.02783468; - samples[10] = 0.01222447; - - vec4 retVal; - vec4 sum; - int i = 0; - - sum = vec4( 0 ); - for( ;i < 11; i++ ) - { - sum += texture2D( Blur0, texCoord + (pos[i] * 0.0100000) ) * samples[i]; - } - - gl_FragColor = sum; -} diff --git a/Samples/Media/materials/programs/GLSL/Blur_vs.glsl b/Samples/Media/materials/programs/GLSL/Blur_vs.glsl deleted file mode 100644 index b0f7e0195c1..00000000000 --- a/Samples/Media/materials/programs/GLSL/Blur_vs.glsl +++ /dev/null @@ -1,11 +0,0 @@ -varying vec2 texCoord; -uniform mat4 worldViewProj; - -attribute vec4 vertex; -attribute vec2 uv0; - -void main() -{ - gl_Position = worldViewProj * vertex; - texCoord = uv0; -} diff --git a/Samples/Media/materials/programs/GLSL/BrightBloom2_ps20.glsl b/Samples/Media/materials/programs/GLSL/BrightBloom2_ps20.glsl deleted file mode 100644 index 26df20d6452..00000000000 --- a/Samples/Media/materials/programs/GLSL/BrightBloom2_ps20.glsl +++ /dev/null @@ -1,28 +0,0 @@ -//------------------------------- -//BrightBloom_ps20.glsl -// High-pass filter for obtaining lumminance -// We use an aproximation formula that is pretty fast: -// f(x) = ( -3 * ( x - 1 )^2 + 1 ) * 2 -// Color += Grayscale( f(Color) ) + 0.6 -// -// Special thanks to ATI for their great HLSL2GLSL utility -// http://sourceforge.net/projects/hlsl2glsl -//------------------------------- - -uniform sampler2D RT; -varying vec2 oUv0; - -void main() -{ - vec4 tex; - vec4 bright4; - float bright; - - tex = texture2D(RT, oUv0); - tex -= 1.00000; - bright4 = -6.00000 * tex * tex + 2.00000; - bright = dot( bright4, vec4( 0.333333, 0.333333, 0.333333, 0.000000) ); - tex += (bright + 0.600000); - - gl_FragColor = tex; -} diff --git a/Samples/Media/materials/programs/GLSL/ColdCasterFp.glsl b/Samples/Media/materials/programs/GLSL/ColdCasterFp.glsl deleted file mode 100644 index f7bd9fea136..00000000000 --- a/Samples/Media/materials/programs/GLSL/ColdCasterFp.glsl +++ /dev/null @@ -1,6 +0,0 @@ -varying vec2 NDotV; - -void main() -{ - gl_FragColor = vec4(NDotV.x / 2.0); -} diff --git a/Samples/Media/materials/programs/GLSL/ColdCasterVp.glsl b/Samples/Media/materials/programs/GLSL/ColdCasterVp.glsl deleted file mode 100644 index 372349a7fa4..00000000000 --- a/Samples/Media/materials/programs/GLSL/ColdCasterVp.glsl +++ /dev/null @@ -1,13 +0,0 @@ -uniform mat4 worldViewProj; -uniform vec3 eyePosition; -attribute vec4 position; -attribute vec4 normal; -varying vec2 NDotV; - -void main() -{ - vec4 eyeDir = vec4(eyePosition - position.xyz, 0.0); - eyeDir = normalize(eyeDir); - gl_Position = worldViewProj * position; - NDotV = vec2(clamp( dot( normal, eyeDir ), 0.0, 1.0 )); -} diff --git a/Samples/Media/materials/programs/GLSL/Combine_fp.glsl b/Samples/Media/materials/programs/GLSL/Combine_fp.glsl deleted file mode 100644 index 4cf88764619..00000000000 --- a/Samples/Media/materials/programs/GLSL/Combine_fp.glsl +++ /dev/null @@ -1,13 +0,0 @@ -uniform sampler2D RT; -uniform sampler2D Sum; -uniform float blur; - -varying vec2 oUv0; - -void main() -{ - vec4 render = texture2D(RT, oUv0); - vec4 sum = texture2D(Sum, oUv0); - - gl_FragColor = mix(render, sum, blur); -} diff --git a/Samples/Media/materials/programs/GLSL/DepthShadowmapReceiverFp.glsl b/Samples/Media/materials/programs/GLSL/DepthShadowmapReceiverFp.glsl deleted file mode 100644 index 5037124459d..00000000000 --- a/Samples/Media/materials/programs/GLSL/DepthShadowmapReceiverFp.glsl +++ /dev/null @@ -1,46 +0,0 @@ -#define PCF - -#ifdef PCF -uniform float inverseShadowmapSize; -#endif -uniform sampler2D shadowMap; - -varying vec4 oUv; -varying vec4 outColor; - -void main() -{ - vec4 shadowUV = oUv; - // point on shadowmap - shadowUV = shadowUV / shadowUV.w; - float centerdepth = texture2D(shadowMap, shadowUV.xy).x; - -#ifndef OGRE_REVERSED_Z - shadowUV.z = shadowUV.z * 0.5 + 0.5; // convert -1..1 to 0..1 -#endif - - // shadowUV.z contains lightspace position of current object -#ifdef PCF - float pixeloffset = inverseShadowmapSize; - vec4 depths = vec4( - texture2D(shadowMap, shadowUV.xy + vec2(-pixeloffset, 0.0)).x, - texture2D(shadowMap, shadowUV.xy + vec2(+pixeloffset, 0.0)).x, - texture2D(shadowMap, shadowUV.xy + vec2(0.0, -pixeloffset)).x, - texture2D(shadowMap, shadowUV.xy + vec2(0.0, +pixeloffset)).x); - - // use depths from prev, calculate diff - float final = (centerdepth > shadowUV.z) ? 1.0 : 0.0; - final += (depths.x > shadowUV.z) ? 1.0 : 0.0; - final += (depths.y > shadowUV.z) ? 1.0 : 0.0; - final += (depths.z > shadowUV.z) ? 1.0 : 0.0; - final += (depths.w > shadowUV.z) ? 1.0 : 0.0; - - final *= 0.2; - - gl_FragColor = vec4(outColor.xyz * final, 1.0); - -#else - gl_FragColor = (centerdepth > shadowUV.z) ? vec4(outColor.xyz,1) : vec4(0,0,0,1); -#endif -} - diff --git a/Samples/Media/materials/programs/GLSL/DepthShadowmapReceiverVp.glsl b/Samples/Media/materials/programs/GLSL/DepthShadowmapReceiverVp.glsl deleted file mode 100644 index e34635ba5de..00000000000 --- a/Samples/Media/materials/programs/GLSL/DepthShadowmapReceiverVp.glsl +++ /dev/null @@ -1,31 +0,0 @@ -uniform mat4 world; -uniform mat4 worldIT; -uniform mat4 worldViewProj; -uniform mat4 texViewProj; -uniform vec4 lightPosition; -uniform vec4 lightColour; - -attribute vec4 vertex; -attribute vec3 normal; - -varying vec4 oUv; -varying vec4 outColor; - -void main() -{ - gl_Position = worldViewProj * vertex; - - vec4 worldPos = world * vertex; - - vec3 worldNorm = (worldIT * vec4(normal, 1.0)).xyz; - - // calculate lighting (simple vertex lighting) - vec3 lightDir = normalize( - lightPosition.xyz - (worldPos.xyz * lightPosition.w)); - - outColor = lightColour * max(dot(lightDir, worldNorm), 0.0); - - // calculate shadow map coords - oUv = texViewProj * worldPos; -} - diff --git a/Samples/Media/materials/programs/GLSL/DiffuseOneTexture.glsl b/Samples/Media/materials/programs/GLSL/DiffuseOneTexture.glsl deleted file mode 100644 index cb2aafd92ca..00000000000 --- a/Samples/Media/materials/programs/GLSL/DiffuseOneTexture.glsl +++ /dev/null @@ -1,12 +0,0 @@ -uniform sampler2D texMap; - -varying vec4 colour; -varying vec4 uv; - -/* - Basic fragment program using texture and diffuse colour. -*/ -void main() -{ - gl_FragColor = texture2D(texMap, uv.xy) * colour; -} diff --git a/Samples/Media/materials/programs/GLSL/DitherFP.glsl b/Samples/Media/materials/programs/GLSL/DitherFP.glsl deleted file mode 100644 index ef834998a9b..00000000000 --- a/Samples/Media/materials/programs/GLSL/DitherFP.glsl +++ /dev/null @@ -1,19 +0,0 @@ -uniform sampler2D RT; -uniform sampler2D noise; -varying vec2 oUv0; - -void main() -{ - float c = dot(texture2D(RT, oUv0), vec4(0.30, 0.11, 0.59, 0.00)); - float n = texture2D(noise, oUv0).r*2.0 - 1.0; - c += n; - if (c > 0.5) - { - c = 0.0; - } - else - { - c = 1.0; - } - gl_FragColor = vec4(c,c,c,1.0); -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/GLSL/DoF_Blend.frag b/Samples/Media/materials/programs/GLSL/DoF_Blend.frag deleted file mode 100644 index c78bf7f3f3f..00000000000 --- a/Samples/Media/materials/programs/GLSL/DoF_Blend.frag +++ /dev/null @@ -1,89 +0,0 @@ -// "Depth of Field" demo for Ogre -// Copyright (C) 2006 Christian Lindequist Larsen -// -// This code is in the public domain. You may do whatever you want with it. - -// based on "Advanced Depth of Field" by "Thorsten Scheuermann" -#include - -#define NUM_TAPS 12 // number of taps the shader will use - -uniform vec4 pixelSizeScene; // pixel size of full resolution image - -SAMPLER2D(scene, 0); // full resolution image -SAMPLER2D(depth, 1); // full resolution image with depth values -SAMPLER2D(blur, 2); // downsampled and blurred image - -// dofParams coefficients: -// x = near blur depth; y = focal plane depth; z = far blur depth -// w = blurriness cutoff constant -STATIC f32vec4 dofParams = vec4(0.9991, 0.9985, 0.9975, 1); - -float getBlurAmount(float depth) -{ - float f; - - if (depth > dofParams.y) - { - // scale depth value between near blur distance and focal distance - f = (dofParams.x - depth) / (dofParams.x - dofParams.y); - } - else - { - // scale depth value between focal distance and far blur distance - f = (depth - dofParams.z) / (dofParams.y - dofParams.z); - } - - return 1.0 - clamp(f, 0.0, dofParams.w); -} - -MAIN_PARAMETERS -IN(vec2 oUv0, TEXCOORD0) -MAIN_DECLARATION -{ - vec2 CoC = vec2(5.0, 1.0); // max and min circle of confusion (CoC) radius - vec2 pixelSizeBlur = pixelSizeScene.zw*4.0; // pixel size of downsampled and blurred image - - vec2 poisson[NUM_TAPS]; // contains poisson-distributed positions on the unit circle - poisson[ 0] = vec2( 0.00, 0.00); - poisson[ 1] = vec2( 0.07, -0.45); - poisson[ 2] = vec2(-0.15, -0.33); - poisson[ 3] = vec2( 0.35, -0.32); - poisson[ 4] = vec2(-0.39, -0.26); - poisson[ 5] = vec2( 0.10, -0.23); - poisson[ 6] = vec2( 0.36, -0.12); - poisson[ 7] = vec2(-0.31, -0.01); - poisson[ 8] = vec2(-0.38, 0.22); - poisson[ 9] = vec2( 0.36, 0.23); - poisson[10] = vec2(-0.13, 0.29); - poisson[11] = vec2( 0.14, 0.41); - - // Get depth of center tap and convert it into blur radius in pixels - float centerDepth = texture2D(depth, oUv0).r; - float centerBlur = getBlurAmount(centerDepth); - float discRadius = max(0.0, centerBlur * CoC.x - CoC.y); - - vec4 sum = vec4_splat(0.0); - - for (int i = 0; i < NUM_TAPS; ++i) - { - // compute texture coordinates - vec2 coordScene = oUv0 + (pixelSizeScene.zw * poisson[i] * discRadius); - vec2 coordBlur = oUv0 + (pixelSizeBlur * poisson[i] * discRadius); - - // fetch taps and depth - vec4 tapScene = texture2D(scene, coordScene); - float tapDepth = texture2D(depth, coordScene).r; - vec4 tapBlur = texture2D(blur, coordBlur); - - // mix low and high res. taps based on tap blurriness - float blurAmount = getBlurAmount(tapDepth); // put blurriness into [0, 1] - vec4 tap = mix(tapScene, tapBlur, blurAmount); - - // accumulate - sum.rgb += tap.rgb * blurAmount; - sum.a += blurAmount; - } - - gl_FragColor = (sum / sum.a); -} diff --git a/Samples/Media/materials/programs/GLSL/DoF_Gaussian3x3.frag b/Samples/Media/materials/programs/GLSL/DoF_Gaussian3x3.frag deleted file mode 100644 index a7ec699f71e..00000000000 --- a/Samples/Media/materials/programs/GLSL/DoF_Gaussian3x3.frag +++ /dev/null @@ -1,41 +0,0 @@ -// "Depth of Field" demo for Ogre -// Copyright (C) 2006 Christian Lindequist Larsen -// -// This code is in the public domain. You may do whatever you want with it. - -#include - -uniform vec4 vpSize; -SAMPLER2D(source, 0); - -#define KERNEL_SIZE 9 - -MAIN_PARAMETERS -IN(vec2 oUv0, TEXCOORD0) -MAIN_DECLARATION -{ - vec2 pixelSize = vpSize.zw; - - float weights[KERNEL_SIZE]; - weights[0] = 1.0/16.0; weights[1] = 2.0/16.0; weights[2] = 1.0/16.0; - weights[3] = 2.0/16.0; weights[4] = 4.0/16.0; weights[5] = 2.0/16.0; - weights[6] = 1.0/16.0; weights[7] = 2.0/16.0; weights[8] = 1.0/16.0; - - vec2 offsets[KERNEL_SIZE]; - offsets[0] = vec2(-pixelSize.x, -pixelSize.y); - offsets[1] = vec2(0, -pixelSize.y); - offsets[2] = vec2(pixelSize.x, -pixelSize.y); - offsets[3] = vec2(-pixelSize.x, 0); - offsets[4] = vec2(0, 0); - offsets[5] = vec2(pixelSize.x, 0); - offsets[6] = vec2(-pixelSize.x, pixelSize.y); - offsets[7] = vec2(0, pixelSize.y); - offsets[8] = vec2(pixelSize.x, pixelSize.y); - - vec4 sum = vec4_splat(0.0); - - for (int i = 0; i < KERNEL_SIZE; ++i) - sum += weights[i] * texture2D(source, oUv0 + offsets[i]); - - gl_FragColor = sum; -} diff --git a/Samples/Media/materials/programs/GLSL/EmbossedFp.glsl b/Samples/Media/materials/programs/GLSL/EmbossedFp.glsl deleted file mode 100644 index be3671b63cd..00000000000 --- a/Samples/Media/materials/programs/GLSL/EmbossedFp.glsl +++ /dev/null @@ -1,13 +0,0 @@ -uniform sampler2D RT; -varying vec2 oUv0; - -void main() -{ - vec4 Color; - Color.a = 1.0; - Color.rgb = vec3(0.5); - Color -= texture2D( RT, oUv0 - 0.001)*2.0; - Color += texture2D( RT, oUv0 + 0.001)*2.0; - Color.rgb = vec3((Color.r+Color.g+Color.b)/3.0); - gl_FragColor = Color; -} diff --git a/Samples/Media/materials/programs/GLSL/Example_BumpMappingFp.glsl b/Samples/Media/materials/programs/GLSL/Example_BumpMappingFp.glsl deleted file mode 100644 index 8dbc11f608f..00000000000 --- a/Samples/Media/materials/programs/GLSL/Example_BumpMappingFp.glsl +++ /dev/null @@ -1,25 +0,0 @@ -uniform vec4 lightDiffuse; -uniform sampler2D normalMap; - -varying vec2 oUv0; -varying vec3 oTSLightDir; - -// General functions - -// Expand a range-compressed vector -vec3 expand(vec3 v) -{ - return (v - 0.5) * 2.0; -} - -void main() -{ - // Retrieve normalised light vector, expand from range-compressed - vec3 lightVec = normalize(oTSLightDir).xyz; - - // Get bump map vector, again expand from range-compressed - vec3 bumpVec = expand(texture2D(normalMap, oUv0).xyz); - - // Calculate dot product - gl_FragColor = lightDiffuse * dot(bumpVec, lightVec); -} diff --git a/Samples/Media/materials/programs/GLSL/Example_BumpMappingShadowRcvFp.glsl b/Samples/Media/materials/programs/GLSL/Example_BumpMappingShadowRcvFp.glsl deleted file mode 100644 index 8df167abb8c..00000000000 --- a/Samples/Media/materials/programs/GLSL/Example_BumpMappingShadowRcvFp.glsl +++ /dev/null @@ -1,30 +0,0 @@ -// General functions - -// Expand a range-compressed vector -vec3 expand(vec3 v) -{ - return (v - 0.5) * 2.0; -} - -uniform sampler2D shadowMap; -uniform sampler2D normalMap; -uniform vec4 lightDiffuse; - -varying vec4 uvproj; -varying vec4 oUv0; -varying vec3 oTSLightDir; - -void main() -{ - // retrieve normalised light vector, expand from range-compressed - vec3 lightVec = expand(normalize(oTSLightDir).xyz); - - // get bump map vector, again expand from range-compressed - vec3 bumpVec = expand(texture2D(normalMap, oUv0.xy).xyz); - - // get shadow value - vec3 shadow = texture2DProj(shadowMap, uvproj).xyz; - - // Calculate dot product - gl_FragColor = vec4(shadow * lightDiffuse.xyz * dot(bumpVec, lightVec), 1.0); -} diff --git a/Samples/Media/materials/programs/GLSL/Example_BumpMappingShadowRcvVp.glsl b/Samples/Media/materials/programs/GLSL/Example_BumpMappingShadowRcvVp.glsl deleted file mode 100644 index 5e84d9d16b9..00000000000 --- a/Samples/Media/materials/programs/GLSL/Example_BumpMappingShadowRcvVp.glsl +++ /dev/null @@ -1,50 +0,0 @@ -/* Bump mapping vertex program for shadow receiving - In this program, we want to calculate the tangent space light vector - on a per-vertex level which will get passed to the fragment program, - or to the fixed function dot3 operation, to produce the per-pixel - lighting effect. -*/ - -// parameters -uniform vec4 lightPosition; // object space -uniform mat4 worldViewProj; -uniform mat4 worldMatrix; -uniform mat4 texViewProj; - -attribute vec4 vertex; -attribute vec3 normal; -attribute vec3 tangent; -attribute vec4 uv0; - -varying vec4 uvproj; -varying vec4 oUv0; -varying vec3 oTSLightDir; - -void main() -{ - // Calculate output position - gl_Position = worldViewProj * vertex; - - // Pass the main uvs straight through unchanged - oUv0 = uv0; - - // Calculate tangent space light vector - // Get object space light direction - // Non-normalised since we'll do that in the fragment program anyway - vec3 lightDir = lightPosition.xyz - (vertex * lightPosition.w).xyz; - - // Calculate the binormal (NB we assume both normal and tangent are - // already normalised) - vec3 binormal = cross(normal, tangent); - - // Form a rotation matrix out of the vectors, column major for glsl es - mat3 rotation = mat3(vec3(tangent[0], binormal[0], normal[0]), - vec3(tangent[1], binormal[1], normal[1]), - vec3(tangent[2], binormal[2], normal[2])); - - // Transform the light vector according to this matrix - oTSLightDir = rotation * lightDir; - - // Projection - uvproj = texViewProj * (worldMatrix * vertex); -} diff --git a/Samples/Media/materials/programs/GLSL/Example_BumpMappingVp.glsl b/Samples/Media/materials/programs/GLSL/Example_BumpMappingVp.glsl deleted file mode 100644 index 1e7e9e006d0..00000000000 --- a/Samples/Media/materials/programs/GLSL/Example_BumpMappingVp.glsl +++ /dev/null @@ -1,45 +0,0 @@ -/* Bump mapping vertex program - In this program, we want to calculate the tangent space light vector - on a per-vertex level which will get passed to the fragment program, - or to the fixed function dot3 operation, to produce the per-pixel - lighting effect. -*/ -// parameters -uniform vec4 lightPosition; // object space -uniform mat4 worldViewProj; - -attribute vec4 vertex; -attribute vec3 normal; -attribute vec3 tangent; -attribute vec2 uv0; - -varying vec2 oUv0; -varying vec3 oTSLightDir; - -void main() -{ - // Calculate output position - gl_Position = worldViewProj * vertex; - - // Pass the main uvs straight through unchanged - oUv0 = uv0; - - // Calculate tangent space light vector - // Get object space light direction - // Non-normalised since we'll do that in the fragment program anyway - vec3 lightDir = lightPosition.xyz - (vertex * lightPosition.w).xyz; - - // Calculate the binormal (NB we assume both normal and tangent are - // already normalised) - - // Fixed handedness - vec3 binormal = cross(normal, tangent); - - // Form a rotation matrix out of the vectors, column major for glsl es - mat3 rotation = mat3(vec3(tangent[0], binormal[0], normal[0]), - vec3(tangent[1], binormal[1], normal[1]), - vec3(tangent[2], binormal[2], normal[2])); - - // Transform the light vector according to this matrix - oTSLightDir = rotation * lightDir; -} diff --git a/Samples/Media/materials/programs/GLSL/Example_FresnelFp.glsl b/Samples/Media/materials/programs/GLSL/Example_FresnelFp.glsl deleted file mode 100644 index 9a3d430ee32..00000000000 --- a/Samples/Media/materials/programs/GLSL/Example_FresnelFp.glsl +++ /dev/null @@ -1,39 +0,0 @@ -#include - -SAMPLER2D(noiseMap, 0); -SAMPLER2D(reflectMap, 1); -SAMPLER2D(refractMap, 2); - -OGRE_UNIFORMS( -uniform vec4 tintColour; -uniform float noiseScale; -uniform float fresnelBias; -uniform float fresnelScale; -uniform float fresnelPower; -) - -MAIN_PARAMETERS -IN(vec3 noiseCoord, TEXCOORD0) -IN(vec4 projectionCoord, TEXCOORD1) -IN(vec3 eyeDir, TEXCOORD2) -IN(vec3 oNormal, TEXCOORD3) -MAIN_DECLARATION -{ - // Do the tex projection manually so we can distort _after_ - vec2 final = projectionCoord.xy / projectionCoord.w; - - // Noise - vec3 noiseNormal = (texture2D(noiseMap, (noiseCoord.xy / 5.0)).rgb - 0.5).rbg * noiseScale; - final += noiseNormal.xz; - - // Fresnel - //normal = normalize(normal + noiseNormal.xz); - float fresnel = fresnelBias + fresnelScale * pow(1.0 + dot(eyeDir, oNormal), fresnelPower); - - // Reflection / refraction - vec4 reflectionColour = texture2D(reflectMap, final); - vec4 refractionColour = texture2D(refractMap, final) + tintColour; - - // Final colour - gl_FragColor = mix(refractionColour, reflectionColour, fresnel); -} diff --git a/Samples/Media/materials/programs/GLSL/Example_FresnelVp.glsl b/Samples/Media/materials/programs/GLSL/Example_FresnelVp.glsl deleted file mode 100644 index 61cc4e71519..00000000000 --- a/Samples/Media/materials/programs/GLSL/Example_FresnelVp.glsl +++ /dev/null @@ -1,34 +0,0 @@ -#include - -OGRE_UNIFORMS( -uniform mat4 worldViewProjMatrix; -uniform mat4 textureProjMatrix; -uniform mat3 normalMatrix; -uniform vec3 eyePosition; // object space -uniform float timeVal; -uniform float scale; // the amount to scale the noise texture by -uniform float scroll; // the amount by which to scroll the noise -uniform float noise; // the noise perturb as a factor of the time -) - -MAIN_PARAMETERS -IN(vec4 position, POSITION) -IN(vec3 normal, NORMAL) -IN(vec4 uv0, TEXCOORD0) - -OUT(vec3 noiseCoord, TEXCOORD0) -OUT(vec4 projectionCoord, TEXCOORD1) -OUT(vec3 eyeDir, TEXCOORD2) -OUT(vec3 oNormal, TEXCOORD3) -MAIN_DECLARATION -{ - gl_Position = mul(worldViewProjMatrix, position); - projectionCoord = mul(textureProjMatrix, position); - - // Noise map coords - noiseCoord.xy = (uv0.xy + (timeVal * scroll)) * scale; - noiseCoord.z = noise * timeVal; - - eyeDir = normalize(position.xyz - eyePosition); - oNormal = normal; -} diff --git a/Samples/Media/materials/programs/GLSL/Example_TextureArrayVS.glsl b/Samples/Media/materials/programs/GLSL/Example_TextureArrayVS.glsl deleted file mode 100644 index 87792cad0ca..00000000000 --- a/Samples/Media/materials/programs/GLSL/Example_TextureArrayVS.glsl +++ /dev/null @@ -1,15 +0,0 @@ -#include - -OGRE_UNIFORMS( -uniform mat4 worldViewProj; -) - -MAIN_PARAMETERS -IN(vec4 vertex, POSITION) -IN(vec3 uv0, TEXCOORD0) -OUT(vec3 oUv, TEXCOORD0) -MAIN_DECLARATION -{ - gl_Position = mul(worldViewProj, vertex); - oUv = uv0; -} diff --git a/Samples/Media/materials/programs/GLSL/GlassFP.glsl b/Samples/Media/materials/programs/GLSL/GlassFP.glsl deleted file mode 100644 index f2e28ad1306..00000000000 --- a/Samples/Media/materials/programs/GLSL/GlassFP.glsl +++ /dev/null @@ -1,10 +0,0 @@ -uniform sampler2D RT; -uniform sampler2D NormalMap; -varying vec2 oUv0; - -void main() -{ - vec4 normal = 2.0 * (texture2D(NormalMap, oUv0 * 2.5) - 0.5); - - gl_FragColor = texture2D(RT, oUv0 + normal.xy * 0.05); -} diff --git a/Samples/Media/materials/programs/GLSL/GrassFp.glsl b/Samples/Media/materials/programs/GLSL/GrassFp.glsl deleted file mode 100644 index c23c4c81597..00000000000 --- a/Samples/Media/materials/programs/GLSL/GrassFp.glsl +++ /dev/null @@ -1,21 +0,0 @@ -////////////////////////////// MOVING GRASS -// Vertex program to wave some grass about -// Assumes UV texture coords of v==0 indicates the top of the grass -uniform sampler2D diffuseMap; -uniform float alphaThresh; - -varying vec4 oUv0; -varying vec4 oColour; - -void main() -{ - vec4 texColor = texture2D(diffuseMap, oUv0.xy); - - // Do manual alpha rejection because it is not built into OpenGL ES 2 - if (texColor.a < alphaThresh) - { - discard; - } - - gl_FragColor = vec4(texColor.rgb * oColour.rgb, 1.0); -} diff --git a/Samples/Media/materials/programs/GLSL/GrassVp.glsl b/Samples/Media/materials/programs/GLSL/GrassVp.glsl deleted file mode 100644 index 9ee4aa973b0..00000000000 --- a/Samples/Media/materials/programs/GLSL/GrassVp.glsl +++ /dev/null @@ -1,33 +0,0 @@ -////////////////////////////// MOVING GRASS -// Vertex program to wave some grass about -// Assumes UV texture coords of v==0 indicates the top of the grass -uniform mat4 worldViewProj; -uniform vec4 camObjPos; -uniform vec4 ambient; -uniform vec4 objSpaceLight; -uniform vec4 lightColour; -uniform vec4 offset; - -attribute vec4 position; -attribute vec4 normal; -attribute vec4 uv0; - -varying vec4 oUv0; -varying vec4 oColour; - -void main() -{ - vec4 mypos = position; - vec4 factor = vec4(1.0, 1.0, 1.0, 1.0) - uv0.yyyy; - mypos = mypos + offset * factor; - gl_Position = worldViewProj * mypos; - - oUv0 = uv0; - // Color - // get vertex light direction (support directional and point) - vec3 light = normalize(objSpaceLight.xyz - (mypos.xyz * objSpaceLight.w).xyz); - // grass is just 2D quads, so if light passes underneath we need to invert the normal - // abs() will have the same effect - float diffuseFactor = abs(dot(normal.xyz, light)); - oColour = ambient + diffuseFactor * lightColour; -} diff --git a/Samples/Media/materials/programs/GLSL/GrayScale.glsl b/Samples/Media/materials/programs/GLSL/GrayScale.glsl deleted file mode 100644 index b20808cf211..00000000000 --- a/Samples/Media/materials/programs/GLSL/GrayScale.glsl +++ /dev/null @@ -1,11 +0,0 @@ -#include - -SAMPLER2D(RT, 0); - -MAIN_PARAMETERS -IN(vec2 oUv0, TEXCOORD0) -MAIN_DECLARATION -{ - vec3 greyscale = vec3_splat(dot(texture2D(RT, oUv0).rgb, vec3(0.3, 0.59, 0.11))); - gl_FragColor = vec4(greyscale, 1.0); -} diff --git a/Samples/Media/materials/programs/GLSL/HardwareMorphAnimationVp.glsl b/Samples/Media/materials/programs/GLSL/HardwareMorphAnimationVp.glsl deleted file mode 100644 index 5c0b3fcb31c..00000000000 --- a/Samples/Media/materials/programs/GLSL/HardwareMorphAnimationVp.glsl +++ /dev/null @@ -1,21 +0,0 @@ -attribute vec4 vertex; -attribute vec4 normal; -attribute vec4 uv0; -attribute vec4 uv1; // pos2 - -varying vec2 oUv; -varying vec4 colour; - -uniform mat4 worldViewProj; -uniform vec4 anim_t; - -// hardware morph animation (no normals) -void main() -{ - // interpolate - vec4 interp = vec4(vertex.xyz + anim_t.x*(uv1.xyz - vertex.xyz), 1.0); - - gl_Position = worldViewProj * interp; - oUv = uv0.xy; - colour = vec4(1.0,0.0,0.0,1.0); -} diff --git a/Samples/Media/materials/programs/GLSL/HardwareMorphAnimationWithNormalsVp.glsl b/Samples/Media/materials/programs/GLSL/HardwareMorphAnimationWithNormalsVp.glsl deleted file mode 100644 index 60c464c6827..00000000000 --- a/Samples/Media/materials/programs/GLSL/HardwareMorphAnimationWithNormalsVp.glsl +++ /dev/null @@ -1,34 +0,0 @@ -attribute vec4 vertex; -attribute vec4 normal; -attribute vec4 uv0; -attribute vec4 uv1; // pos2 -attribute vec4 uv2; // normal2 - -varying vec2 oUv; -varying vec4 colour; - -uniform mat4 worldViewProj; -uniform vec4 anim_t; -uniform vec4 objSpaceLightPos; -uniform vec4 ambient; - -// hardware morph animation (with normals) -void main() -{ - // interpolate position - vec4 posinterp = vec4(vertex.xyz + anim_t.x*(uv1.xyz - vertex.xyz), 1.0); - - // nlerp normal - vec3 ninterp = normal.xyz + anim_t.x*(uv2.xyz - normal.xyz); - ninterp = normalize(ninterp); - - gl_Position = worldViewProj * posinterp; - oUv = uv0.xy; - - vec3 lightDir = normalize( - objSpaceLightPos.xyz - (posinterp.xyz * objSpaceLightPos.w)); - - // Colour it red to make it easy to identify - float lit = clamp(dot(lightDir, ninterp), 0.0, 1.0); - colour = vec4((ambient.rgb + vec3(lit,lit,lit)) * vec3(1.0,0.0,0.0), 1.0); -} diff --git a/Samples/Media/materials/programs/GLSL/HardwarePoseAnimationVp.glsl b/Samples/Media/materials/programs/GLSL/HardwarePoseAnimationVp.glsl deleted file mode 100644 index f54571defe7..00000000000 --- a/Samples/Media/materials/programs/GLSL/HardwarePoseAnimationVp.glsl +++ /dev/null @@ -1,23 +0,0 @@ -attribute vec4 vertex; -attribute vec4 normal; -attribute vec4 uv0; -attribute vec4 uv1; // pose1 -attribute vec4 uv2; // pose2 - -varying vec2 oUv; -varying vec4 colour; - -uniform mat4 worldViewProj; -uniform vec4 anim_t; - -// hardware pose animation (no normals) -void main() -{ - // interpolate - vec4 interp = vec4(vertex.xyz + anim_t.x*uv1.xyz + anim_t.y*uv2.xyz, 1.0); - - gl_Position = worldViewProj * interp; - oUv = uv0.xy; - colour = vec4(1.0,0.0,0.0,1.0); -} - diff --git a/Samples/Media/materials/programs/GLSL/HardwarePoseAnimationWithNormalsVp.glsl b/Samples/Media/materials/programs/GLSL/HardwarePoseAnimationWithNormalsVp.glsl deleted file mode 100644 index 9b631147bb8..00000000000 --- a/Samples/Media/materials/programs/GLSL/HardwarePoseAnimationWithNormalsVp.glsl +++ /dev/null @@ -1,44 +0,0 @@ -attribute vec4 vertex; -attribute vec4 normal; -attribute vec4 uv0; -attribute vec4 uv1; // pose1pos -attribute vec4 uv2; // pose1norm -attribute vec4 uv3; // pose2pos -attribute vec4 uv4; // pose2norm - -varying vec2 oUv; -varying vec4 colour; - -uniform mat4 worldViewProj; -uniform vec4 anim_t; -uniform vec4 objSpaceLightPos; -uniform vec4 ambient; - -// hardware pose animation (with normals) -void main() -{ - // interpolate position - vec4 posinterp = vec4(vertex.xyz + anim_t.x*uv1.xyz + anim_t.y*uv3.xyz, 1.0); - - // nlerp normal - // nlerp normal - // First apply the pose normals (these are actual normals, not offsets) - vec3 ninterp = anim_t.x*uv2.xyz + anim_t.y*uv4.xyz; - - // Now add back any influence of the original normal - // This depends on what the cumulative weighting left the normal at, if it's lacking or cancelled out - //float remainder = 1.0 - min(anim_t.x + anim_t.y, 1.0); - float remainder = 1.0 - min(length(ninterp), 1.0); - ninterp = ninterp + (normal.xyz * remainder); - ninterp = normalize(ninterp); - - gl_Position = worldViewProj * posinterp; - oUv = uv0.xy; - - vec3 lightDir = normalize( - objSpaceLightPos.xyz - (posinterp.xyz * objSpaceLightPos.w)); - - // Colour it red to make it easy to identify - float lit = clamp(dot(lightDir, ninterp), 0.0, 1.0); - colour = vec4((ambient.rgb + vec3(lit,lit,lit)) * vec3(1.0,0.0,0.0), 1.0); -} diff --git a/Samples/Media/materials/programs/GLSL/HeatBlurFp.glsl b/Samples/Media/materials/programs/GLSL/HeatBlurFp.glsl deleted file mode 100644 index 9cefc23d91f..00000000000 --- a/Samples/Media/materials/programs/GLSL/HeatBlurFp.glsl +++ /dev/null @@ -1,58 +0,0 @@ -uniform sampler2D Input; -uniform vec4 blurAmount; - -varying vec2 oUv0; - -void main() -{ - int i; - vec4 tmpOutColor; - float diffuseGlowFactor; - vec2 offsets[4]; -/* - // hazy blur - -1.8, -1.8, - -1.8, 1.8, - 1.8, -1.8, - 1.8, 1.8 -*/ -/* - // less-hazy blur - -1.0, 2.0, - -1.0, -1.0, - 1.0, -1.0, - 1.0, 1.0 -*/ -/* - -0.326212, -0.405805, - -0.840144, -0.073580, - -0.695914, 0.457137, - -0.203345, 0.620716 -*/ - - offsets[0] = vec2(-0.3, 0.4); - offsets[1] = vec2(-0.3, -0.4); - offsets[2] = vec2(0.3, -0.4); - offsets[3] = vec2(0.3, 0.4); - - tmpOutColor = texture2D( Input, oUv0 ); // UV coords are in image space - - // calculate glow amount - diffuseGlowFactor = 0.0113 * (2.0 - max( tmpOutColor.r, tmpOutColor.g )); - - // basic blur filter - for (i = 0; i < 4; i++) { - tmpOutColor += texture2D( Input, oUv0 + blurAmount.x * diffuseGlowFactor * offsets[i] ); - } - - tmpOutColor *= 0.25; - - // TIPS (old-skool strikes again!) - // Pay attention here! If you use the "out float4 outColor" directly - // in your steps while creating the output color (like you remove - // the "tmpOutColor" var and just use the "outColor" directly) - // your pixel-color output IS CHANGING EACH TIME YOU DO AN ASSIGNMENT TOO! - // A temporary variable, instead, acts like a per-pixel double buffer, and - // best of all, lead to better performance. - gl_FragColor = tmpOutColor; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/GLSL/HeatCasterFp.glsl b/Samples/Media/materials/programs/GLSL/HeatCasterFp.glsl deleted file mode 100644 index 45eadbffe0f..00000000000 --- a/Samples/Media/materials/programs/GLSL/HeatCasterFp.glsl +++ /dev/null @@ -1,6 +0,0 @@ -varying vec2 NDotV; - -void main() -{ - gl_FragColor = vec4(NDotV.x); -} diff --git a/Samples/Media/materials/programs/GLSL/HeatCasterVp.glsl b/Samples/Media/materials/programs/GLSL/HeatCasterVp.glsl deleted file mode 100644 index 372349a7fa4..00000000000 --- a/Samples/Media/materials/programs/GLSL/HeatCasterVp.glsl +++ /dev/null @@ -1,13 +0,0 @@ -uniform mat4 worldViewProj; -uniform vec3 eyePosition; -attribute vec4 position; -attribute vec4 normal; -varying vec2 NDotV; - -void main() -{ - vec4 eyeDir = vec4(eyePosition - position.xyz, 0.0); - eyeDir = normalize(eyeDir); - gl_Position = worldViewProj * position; - NDotV = vec2(clamp( dot( normal, eyeDir ), 0.0, 1.0 )); -} diff --git a/Samples/Media/materials/programs/GLSL/InvertFP.glsl b/Samples/Media/materials/programs/GLSL/InvertFP.glsl deleted file mode 100644 index f7ebef73815..00000000000 --- a/Samples/Media/materials/programs/GLSL/InvertFP.glsl +++ /dev/null @@ -1,7 +0,0 @@ -uniform sampler2D RT; -varying vec2 oUv0; - -void main() -{ - gl_FragColor = 1.0 - texture2D(RT, oUv0); -} diff --git a/Samples/Media/materials/programs/GLSL/IsosurfFS.glsl b/Samples/Media/materials/programs/GLSL/IsosurfFS.glsl deleted file mode 100644 index 4a38544f9d5..00000000000 --- a/Samples/Media/materials/programs/GLSL/IsosurfFS.glsl +++ /dev/null @@ -1,33 +0,0 @@ -#ifdef OGRE_GLSL -#version 120 -#endif - -// Ogre port of Nvidia's IsoSurf.cg file -// Modified code follows. See http://developer.download.nvidia.com/SDK/10/opengl/samples.html for original -// -// Cg port of Yury Uralsky's metaball FX shader -// -// Authors: Simon Green and Yury Urlasky -// Email: sdkfeedback@nvidia.com -// -// Copyright (c) NVIDIA Corporation. All rights reserved. -//////////////////////////////////////////////////////////////////////////////////////////////////// - -#include - -// Pixel shader -MAIN_PARAMETERS -IN(vec3 oNormal, TEXCOORD0) -MAIN_DECLARATION -{ - // Sanitize input - vec3 N = normalize(oNormal); - vec3 L = vec3(0, 0, 1); - float nDotL = dot(N, L); - - vec3 materials[2]; - materials[0] = vec3(1, 1, 1); - materials[1] = vec3(0, 0, 0.5); - - gl_FragColor = vec4(abs(nDotL) * materials[int(nDotL < 0.0)], 0.1); -} diff --git a/Samples/Media/materials/programs/GLSL/IsosurfVS.glsl b/Samples/Media/materials/programs/GLSL/IsosurfVS.glsl deleted file mode 100644 index 467cf628bdc..00000000000 --- a/Samples/Media/materials/programs/GLSL/IsosurfVS.glsl +++ /dev/null @@ -1,73 +0,0 @@ -#ifdef OGRE_GLSL -#version 120 -#endif - -// Ogre port of Nvidia's IsoSurf.cg file -// Modified code follows. See http://developer.download.nvidia.com/SDK/10/opengl/samples.html for original -// -// Cg port of Yury Uralsky's metaball FX shader -// -// Authors: Simon Green and Yury Urlasky -// Email: sdkfeedback@nvidia.com -// -// Copyright (c) NVIDIA Corporation. All rights reserved. -//////////////////////////////////////////////////////////////////////////////////////////////////// - -#include - -uniform float IsoValue; -uniform mat4 WorldViewProj; -uniform mat4 origWorldViewIT; -uniform vec4 Metaballs[2]; - -// Size of the sampling grid -const ivec3 SizeMask = ivec3( 63, 63, 63 ); -const ivec3 SizeShift = ivec3( 0, 6, 12 ); - -// Metaball function -// Returns metaball function value in .w and its gradient in .xyz -vec4 Metaball(vec3 Pos, vec3 Center, float RadiusSq) -{ - const float epsilon = 0.001; - - vec3 Dist = Pos - Center; - float InvDistSq = 1 / (dot(Dist, Dist) + epsilon); - - vec4 o; - o.xyz = -2 * RadiusSq * InvDistSq * InvDistSq * Dist; - o.w = RadiusSq * InvDistSq; - return o; -} - -MAIN_PARAMETERS -IN(vec4 vertex, POSITION) -OUT(vec3 N, TEXCOORD0) -OUT(vec2 oField, TEXCOORD1) -MAIN_DECLARATION -{ - vec4 Pos; - - // Generate sampling point position based on its index - // Pos.x = float((gl_VertexID >> SizeShift.x) & SizeMask.x) / (SizeMask.x + 1); - // Pos.y = float((gl_VertexID >> SizeShift.y) & SizeMask.y) / (SizeMask.y + 1); - // Pos.z = float((gl_VertexID >> SizeShift.z) & SizeMask.z) / (SizeMask.z + 1); - // Pos = Pos*2 - 1; - Pos = vertex; - - // Sum up contributions from all metaballs - vec4 Field = vec4(0,0,0,0); - for (int i = 0; i < 2; i++) - Field += Metaball(Pos.xyz, Metaballs[i].xyz, Metaballs[i].w); - - mat3 WorldViewIT = mat3(origWorldViewIT[0].xyz, origWorldViewIT[1].xyz, origWorldViewIT[2].xyz); - - // Transform position and normals - gl_Position = mul(WorldViewProj, vec4(Pos.xyz, 1)); - N = mul(WorldViewIT, Field.xyz); // we want normals in world space - oField.x = Field.w; - - // Generate in-out flags - oField.y = (Field.w < IsoValue) ? 1 : 0; - - // Color = (Field*0.5+0.5) * (Field.w / 10.0); -} diff --git a/Samples/Media/materials/programs/GLSL/LaplaceFP.glsl b/Samples/Media/materials/programs/GLSL/LaplaceFP.glsl deleted file mode 100644 index 1e7a4b91e04..00000000000 --- a/Samples/Media/materials/programs/GLSL/LaplaceFP.glsl +++ /dev/null @@ -1,35 +0,0 @@ -uniform sampler2D Image; -uniform float scale; -uniform float pixelSize; -varying vec2 oUv0; - -// The Laplace filter approximates the second order derivate, -// that is, the rate of change of slope in the image. It can be -// used for edge detection. The Laplace filter gives negative -// response on the higher side of the edge and positive response -// on the lower side. - -// This is the filter kernel: -// 0 1 0 -// 1 -4 1 -// 0 1 0 - -void main() -{ - vec2 samples[4]; - samples[0] = vec2(0, -1); - samples[1] = vec2(-1, 0); - samples[2] = vec2(1, 0); - samples[3] = vec2(0, 1); - - vec4 tc = texture2D(Image, oUv0); - vec4 laplace = -4.0 * tc; - - // Sample the neighbor pixels - for (int i = 0; i < 4; i++){ - laplace += texture2D(Image, oUv0 + pixelSize * samples[i]); - } - - gl_FragColor = (0.5 + scale * laplace); -} - diff --git a/Samples/Media/materials/programs/GLSL/LightShafts.frag b/Samples/Media/materials/programs/GLSL/LightShafts.frag deleted file mode 100644 index d84c3a72c58..00000000000 --- a/Samples/Media/materials/programs/GLSL/LightShafts.frag +++ /dev/null @@ -1,49 +0,0 @@ -// --------------------------------------------------------------------------------------- -// Light shafts shaders with shadows and noise support -// Inpirated on the ATI paper https://developer.amd.com/wordpress/media/2012/10/Mitchell_LightShafts.pdf -// Ogre3D implementation by Xavier Verguín González (xavyiy [at] gmail [dot] com) [Xavyiy] -// --------------------------------------------------------------------------------------- - -#include - -SAMPLER2D(uDepthMap, 0); -SAMPLER2D(uCookieMap, 1); -SAMPLER2D(uNoiseMap, 2); - -// UNIFORM -OGRE_UNIFORMS( -uniform vec4 uAttenuation; -uniform vec3 uLightPosition; -uniform float Time; -) - -MAIN_PARAMETERS -IN(vec3 vPosition, TEXCOORD0) -IN(vec4 oUV , TEXCOORD1) -MAIN_DECLARATION -{ - vec4 iUV = oUV / oUV.w; - - float Depth = texture2D(uDepthMap, iUV.xy).r; - -#if !defined(OGRE_HLSL) && !defined(OGRE_REVERSED_Z) && !defined(VULKAN) - iUV.z = iUV.z * 0.5 + 0.5; -#endif - - if (Depth < iUV.z) - { - gl_FragColor = vec4(0,0,0,1); - } - else - { - vec4 Cookie = texture2D(uCookieMap, iUV.xy); - vec2 Noise = vec2(texture2D(uNoiseMap, iUV.xy - Time).r, - texture2D(uNoiseMap, iUV.xy + Time).g); - - float noise = Noise.x * Noise.y; - float length_ = length(uLightPosition - vPosition); - float atten = 1.0 / (uAttenuation.y + uAttenuation.z*length_ + 20.0*uAttenuation.w*length_*length_); - - gl_FragColor = vec4(Cookie.rgb * atten * noise , 1); - } -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/GLSL/LightShafts.vert b/Samples/Media/materials/programs/GLSL/LightShafts.vert deleted file mode 100644 index a9cb7250fab..00000000000 --- a/Samples/Media/materials/programs/GLSL/LightShafts.vert +++ /dev/null @@ -1,24 +0,0 @@ -// --------------------------------------------------------------------------------------- -// Light shafts shaders with shadows and noise support -// Inpirated on the ATI paper https://developer.amd.com/wordpress/media/2012/10/Mitchell_LightShafts.pdf -// Ogre3D implementation by Xavier Verguín González (xavyiy [at] gmail [dot] com) [Xavyiy] -// --------------------------------------------------------------------------------------- - -#include - -OGRE_UNIFORMS( -uniform mat4 uWorldView; -uniform mat4 uWorldViewProj; -uniform mat4 uTexWorldViewProj; -) - -MAIN_PARAMETERS -IN(vec4 vertex , POSITION) -OUT(vec3 vPosition, TEXCOORD0) -OUT(vec4 oUV , TEXCOORD1) -MAIN_DECLARATION -{ - gl_Position = mul(uWorldViewProj, vertex); - vPosition = mul(uWorldView, vertex).xyz; - oUV = mul(uTexWorldViewProj, vertex); -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/GLSL/LightToHeatFp.glsl b/Samples/Media/materials/programs/GLSL/LightToHeatFp.glsl deleted file mode 100644 index b8d3dd8e84f..00000000000 --- a/Samples/Media/materials/programs/GLSL/LightToHeatFp.glsl +++ /dev/null @@ -1,33 +0,0 @@ -uniform vec4 random_fractions; -uniform vec4 heatBiasScale; -uniform vec4 depth_modulator; - -uniform sampler2D Input; // output of HeatVisionCaster_fp (NdotV) -uniform sampler2D NoiseMap; -uniform sampler2D HeatLookup; - -varying vec2 oUv0; - -void main() -{ - float depth, heat, interference; - - // Output constant color: - depth = texture2D( Input, oUv0 ).x; - depth *= (depth * depth_modulator).x; - - heat = (depth * heatBiasScale.y); - -// if (depth > 0) - { - interference = -0.5 + texture2D( NoiseMap, oUv0 + vec2( random_fractions.x, random_fractions.y ) ).x; - interference *= interference; - interference *= 1.0 - heat; - heat += interference;//+ heatBiasScale.x; - } - - // Clamp UVs - heat = max( 0.005, min( 0.995, heat ) ); - gl_FragColor = texture2D( HeatLookup, vec2( heat, 0.0 ) ); -} - diff --git a/Samples/Media/materials/programs/GLSL/Ocean2GLSL.frag b/Samples/Media/materials/programs/GLSL/Ocean2GLSL.frag deleted file mode 100644 index 024b68eb37e..00000000000 --- a/Samples/Media/materials/programs/GLSL/Ocean2GLSL.frag +++ /dev/null @@ -1,71 +0,0 @@ -/*********************************************************************NVMH3**** -Copyright NVIDIA Corporation 2003 -TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED -*AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS -BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES -WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, -BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) -ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS -BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - - -Comments: - Simple ocean shader with animated bump map and geometric waves - Based partly on "Effective Water Simulation From Physical Models", GPU Gems - -11 Aug 05: converted from HLSL to GLSL by Jeff Doyle (nfz) to work in Ogre - -******************************************************************************/ - - -uniform sampler2D NormalMap; -uniform samplerCube EnvironmentMap; -uniform vec4 deepColor; -uniform vec4 shallowColor; -uniform vec4 reflectionColor; -uniform float reflectionAmount; -uniform float reflectionBlur; -uniform float waterAmount; -uniform float fresnelPower; -uniform float fresnelBias; -uniform float hdrMultiplier; - -varying mat3 rotMatrix; // first row of the 3x3 transform from tangent to cube space -varying vec2 bumpCoord0; -varying vec2 bumpCoord1; -varying vec2 bumpCoord2; -varying vec3 eyeVector; - - -void main(void) -{ - // sum normal maps - // sample from 3 different points so no texture repetition is noticeable - vec4 t0 = texture2D(NormalMap, bumpCoord0) * 2.0 - 1.0; - vec4 t1 = texture2D(NormalMap, bumpCoord1) * 2.0 - 1.0; - vec4 t2 = texture2D(NormalMap, bumpCoord2) * 2.0 - 1.0; - vec3 N = t0.xyz + t1.xyz + t2.xyz; - - N = normalize(rotMatrix * N); - - // reflection - vec3 E = normalize(eyeVector); - vec3 R = reflect(E, N); - // Ogre conversion for cube map lookup - R.z = -R.z; - - vec4 reflection = textureCube(EnvironmentMap, R, reflectionBlur); - // cheap hdr effect - reflection.rgb *= (reflection.r + reflection.g + reflection.b) * hdrMultiplier; - - // fresnel - float facing = 1.0 - dot(-E, N); - float fresnel = clamp(fresnelBias + pow(facing, fresnelPower), 0.0, 1.0); - - vec4 waterColor = mix(shallowColor, deepColor, facing) * waterAmount; - - reflection = mix(waterColor, reflection * reflectionColor, fresnel) * reflectionAmount; - gl_FragColor = waterColor + reflection; -} diff --git a/Samples/Media/materials/programs/GLSL/Ocean2GLSL.vert b/Samples/Media/materials/programs/GLSL/Ocean2GLSL.vert deleted file mode 100644 index a88a46d3f00..00000000000 --- a/Samples/Media/materials/programs/GLSL/Ocean2GLSL.vert +++ /dev/null @@ -1,92 +0,0 @@ -/*********************************************************************NVMH3**** -Copyright NVIDIA Corporation 2003 -TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED -*AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS -BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES -WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, -BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) -ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS -BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - - -Comments: - Simple ocean shader with animated bump map and geometric waves - Based partly on "Effective Water Simulation From Physical Models", GPU Gems - -11 Aug 05: converted from HLSL to GLSL by Jeff Doyle (nfz) to work in Ogre - -******************************************************************************/ - -uniform vec3 eyePosition; -uniform float BumpScale; -uniform vec2 textureScale; -uniform vec2 bumpSpeed; -uniform float time; -uniform float waveFreq; -uniform float waveAmp; -uniform mat4 worldViewProj; - -attribute vec4 vertex; -attribute vec4 uv0; - -varying mat3 rotMatrix; // transform from tangent to obj space -varying vec2 bumpCoord0; -varying vec2 bumpCoord1; -varying vec2 bumpCoord2; -varying vec3 eyeVector; - -// wave functions -struct Wave { - float freq; // 2*PI / wavelength - float amp; // amplitude - float phase; // speed * 2*PI / wavelength - vec2 dir; -}; - - -void main(void) -{ - #define NWAVES 2 - - Wave wave[NWAVES]; - - wave[0] = Wave( waveFreq, waveAmp, 0.5, vec2(-1.0, 0.0) ); - wave[1] = Wave( 3.0 * waveFreq, 0.33 * waveAmp, 1.7, vec2(-0.7, 0.7) ); - - vec4 P = vertex; - - // sum waves - float ddx = 0.0, ddy = 0.0; - float deriv; - float angle; - - // wave synthesis using two sine waves at different frequencies and phase shift - for(int i = 0; i= 0.5) - { -#ifdef OGRE_FRAGMENT_SHADER - discard; -#endif - } -} diff --git a/Samples/Media/materials/programs/GLSL/SegmentedPerPixelLighting.glsl b/Samples/Media/materials/programs/GLSL/SegmentedPerPixelLighting.glsl deleted file mode 100644 index a81d7462237..00000000000 --- a/Samples/Media/materials/programs/GLSL/SegmentedPerPixelLighting.glsl +++ /dev/null @@ -1,167 +0,0 @@ -//----------------------------------------------------------------------------- -// Program Name: SL_Lighting -// Program Desc: Per pixel lighting functions. -// Program Type: Vertex/Pixel shader -// Language: GLSL -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -void SL_TransformNormal(in mat4 m, - in vec3 v, - out vec3 vOut) -{ - vOut = mat3(m) * v; -} - -//----------------------------------------------------------------------------- -void SL_TransformPosition(in mat4 mWorldView, - in vec4 vPos, - out vec3 vOut) -{ - vOut = (mWorldView * vPos).xyz; -} - -//----------------------------------------------------------------------------- -void SL_Light_Directional_Diffuse( - in vec3 vNormal, - in vec3 vNegLightDirView, - in vec3 vDiffuseColour, - in vec3 vBaseColour, - out vec3 vOut) -{ - vec3 vNormalView = normalize(vNormal); - float nDotL = dot(vNormalView, vNegLightDirView); - - vOut = vBaseColour + vDiffuseColour * min(max(nDotL, 0.0), 1.0); -} - -//----------------------------------------------------------------------------- -void SL_Light_Directional_DiffuseSpecular( - in vec3 vNormal, - in vec3 vViewPos, - in vec3 vNegLightDirView, - in vec3 vDiffuseColour, - in vec3 vSpecularColour, - in float fSpecularPower, - in vec3 vBaseDiffuseColour, - in vec3 vBaseSpecularColour, - out vec3 vOutDiffuse, - out vec3 vOutSpecular) -{ - vOutDiffuse = vBaseDiffuseColour; - vOutSpecular = vBaseSpecularColour; - - vec3 vNormalView = normalize(vNormal); - float nDotL = dot(vNormalView, vNegLightDirView); - vec3 vView = -normalize(vViewPos); - vec3 vHalfWay = normalize(vView + vNegLightDirView); - float nDotH = dot(vNormalView, vHalfWay); - - nDotL = max(nDotL, 0); - vOutDiffuse += vDiffuseColour * nDotL; - vOutSpecular += vSpecularColour * pow(clamp(nDotH, 0.0, 1.0), fSpecularPower); -} - -//----------------------------------------------------------------------------- -void SL_Light_Ambient_Diffuse_Inner( - in vec3 vNormal, - in vec3 vLightView, - in float fLightDist, - in vec3 vNegLightDirView, - in vec3 vSpotParams, - in vec3 vDiffuseColour, - inout vec3 vColorOut) -{ - float fLightDistInv = 1.0 / fLightDist; - float nDotL = dot(vNormal, vLightView) * fLightDistInv; - - float fAtten = (1.0 - (fLightDist * vSpotParams.x)); - fAtten = fAtten * fAtten; - - float rho = dot(vNegLightDirView, vLightView) * fLightDistInv; - float fSpotT = min(max((rho - vSpotParams.y) * vSpotParams.z, 0.0), 1.0); - - nDotL = (nDotL < 0.0 ? 0.0 : 1.0) * (0.7 + (0.3 * nDotL)); - vColorOut += vDiffuseColour * 2.0* nDotL * fAtten * fSpotT; -} - -//----------------------------------------------------------------------------- -void SL_Light_Ambient_Diffuse( - in vec3 vNormal, - in vec3 vViewPos, - in vec3 vLightPosView, - in vec3 vNegLightDirView, - in vec3 vSpotParams, - in vec3 vDiffuseColour, - inout vec3 vColorOut) -{ - vec3 vLightView = vLightPosView - vViewPos; - float fLightDist = length(vLightView); - if (fLightDist * vSpotParams.x < 1) - { - SL_Light_Ambient_Diffuse_Inner(vNormal, vLightView, fLightDist, - vNegLightDirView, vSpotParams, vDiffuseColour, vColorOut); - } -} - -//----------------------------------------------------------------------------- -void SL_Light_Segment_Texture_Ambient_Diffuse( - in vec3 vNormal, - in vec3 vViewPos, - in sampler2D dataTexture, - in vec2 lightIndexLimit, - in vec4 lightBounds, - in float invWidth, - in float invHeight, - inout vec3 vColorOut) -{ - float widthOffset = invWidth * 0.5; - float heightOffset = invHeight * 0.5; - - vec2 indexes = (vViewPos.xz - lightBounds.xy) * lightBounds.zw; - indexes = min(max(indexes, 0.0), 8.0); - int index = int(indexes.x) + int(indexes.y) * 9; - widthOffset += invWidth * 3.0 * float(index); - - vec4 indexBounds = textureLod(dataTexture, vec2(widthOffset,heightOffset), 0.0); - int toIndex = int(min(lightIndexLimit.y, indexBounds.x)); - for(int i = int(lightIndexLimit.x); i <= toIndex; ++i) - { - float heightCoord = heightOffset + invHeight * float(i); - vec4 dat1 = textureLod(dataTexture, vec2(widthOffset,heightCoord), 0.0); - - vec3 vLightView = dat1.xyz - vViewPos; - float fLightDist = length(vLightView); - if (fLightDist * dat1.w < 1.0) - { - vec4 dat2 = textureLod(dataTexture, vec2(widthOffset + invWidth,heightCoord),0.0); - vec4 dat3 = textureLod(dataTexture, vec2(widthOffset + invWidth * 2.0,heightCoord),0.0); - SL_Light_Ambient_Diffuse_Inner(vNormal, vLightView, fLightDist, dat2.xyz, vec3(dat1.w, dat2.w, dat3.w), dat3.xyz, vColorOut); - } - } -} - -//----------------------------------------------------------------------------- -void SL_Light_Segment_Debug( - in vec3 vNormal, - in vec3 vViewPos, - in sampler2D dataTexture, - in vec2 lightIndexLimit, - in vec4 lightBounds, - in float invWidth, - in float invHeight, - inout vec3 vColorOut) -{ - float widthOffset = invWidth * 0.5; - float heightOffset = invHeight * 0.5; - - vec2 indexes = (vViewPos.xz - lightBounds.xy) * lightBounds.zw; - indexes = min(max(indexes, 0.0), 8.0); - int index = int(indexes.x + (indexes.y * 9.0)); - vec4 indexBounds = textureLod(dataTexture, vec2(widthOffset,heightOffset),0.0); - - vec2 debugColors = vColorOut.xy * 0.5 + ((mod(floor(indexes.xy),2.0) == vec2(0)) ? 0.1 : 0.2); - vColorOut.xy = debugColors; - int toIndex = int(min(lightIndexLimit.y, indexBounds.x)); - vColorOut.z = (float(toIndex) - lightIndexLimit.x) / 32.0; -} diff --git a/Samples/Media/materials/programs/GLSL/SharpenEdgesFP.glsl b/Samples/Media/materials/programs/GLSL/SharpenEdgesFP.glsl deleted file mode 100644 index 19a07d75d63..00000000000 --- a/Samples/Media/materials/programs/GLSL/SharpenEdgesFP.glsl +++ /dev/null @@ -1,25 +0,0 @@ -uniform sampler2D RT; - -uniform vec2 vTexelSize; -varying vec2 oUv0; - -void main() -{ - vec2 usedTexelED[8]; - usedTexelED[0] = vec2(-1, -1); - usedTexelED[1] = vec2(0, -1); - usedTexelED[2] = vec2(1, -1); - usedTexelED[3] = vec2(-1, 0); - usedTexelED[4] = vec2(1, 0); - usedTexelED[5] = vec2(-1, 1); - usedTexelED[6] = vec2(0, 1); - usedTexelED[7] = vec2(1, 1); - - vec4 tc = texture2D(RT, oUv0); - vec4 cAvgColor = vec4(9.0 * tc); - - for(int t=0; t<8; t++) - cAvgColor -= texture2D(RT, oUv0 + vTexelSize * usedTexelED[t]); - - gl_FragColor = cAvgColor; -} diff --git a/Samples/Media/materials/programs/GLSL/ShowNormals.glsl b/Samples/Media/materials/programs/GLSL/ShowNormals.glsl deleted file mode 100644 index 5fcb0661d1e..00000000000 --- a/Samples/Media/materials/programs/GLSL/ShowNormals.glsl +++ /dev/null @@ -1,12 +0,0 @@ -attribute vec4 position; -attribute vec3 normal; - -varying vec4 oUv0; - -uniform mat4 worldViewProj; - -void main() -{ - gl_Position = worldViewProj * position; - oUv0 = vec4(normal, 1.0); -} diff --git a/Samples/Media/materials/programs/GLSL/ShowTangents.glsl b/Samples/Media/materials/programs/GLSL/ShowTangents.glsl deleted file mode 100644 index bad7cae37e2..00000000000 --- a/Samples/Media/materials/programs/GLSL/ShowTangents.glsl +++ /dev/null @@ -1,12 +0,0 @@ -attribute vec4 position; -attribute vec3 tangent; - -varying vec4 oUv0; - -uniform mat4 worldViewProj; - -void main() -{ - gl_Position = worldViewProj * position; - oUv0 = vec4(tangent, 1.0); -} diff --git a/Samples/Media/materials/programs/GLSL/ShowUV.glsl b/Samples/Media/materials/programs/GLSL/ShowUV.glsl deleted file mode 100644 index 0aff7d05b3a..00000000000 --- a/Samples/Media/materials/programs/GLSL/ShowUV.glsl +++ /dev/null @@ -1,8 +0,0 @@ -varying vec4 ambientUV; - -// Basic fragment program to display UV -void main() -{ - // wrap values using fract - gl_FragColor = vec4(fract(ambientUV.x), fract(ambientUV.y), 0.0, 1.0); -} diff --git a/Samples/Media/materials/programs/GLSL/ShowUVdir3D.glsl b/Samples/Media/materials/programs/GLSL/ShowUVdir3D.glsl deleted file mode 100644 index 38c6d85074f..00000000000 --- a/Samples/Media/materials/programs/GLSL/ShowUVdir3D.glsl +++ /dev/null @@ -1,8 +0,0 @@ -varying vec4 oUv0; - -// Basic fragment program to display 3d uv -void main() -{ - vec3 n = normalize(oUv0.xyz); - gl_FragColor = vec4(n.x, n.y, n.z, 1.0); -} diff --git a/Samples/Media/materials/programs/GLSL/StdQuad_Tex2_vp.glsl b/Samples/Media/materials/programs/GLSL/StdQuad_Tex2_vp.glsl deleted file mode 100644 index 9349a59fe81..00000000000 --- a/Samples/Media/materials/programs/GLSL/StdQuad_Tex2_vp.glsl +++ /dev/null @@ -1,16 +0,0 @@ -#include - -OGRE_UNIFORMS( -uniform mat4 worldViewProj; -) - -MAIN_PARAMETERS -IN(vec4 vertex, POSITION) -IN(vec2 uv0, TEXCOORD0) -OUT(vec2 oUv0, TEXCOORD0) -MAIN_DECLARATION -{ - // Use standardise transform, so work accord with render system specific (RS depth, requires texture flipping, etc) - gl_Position = mul(worldViewProj, vertex); - oUv0 = uv0; -} diff --git a/Samples/Media/materials/programs/GLSL/StdQuad_Tex2a_vp.glsl b/Samples/Media/materials/programs/GLSL/StdQuad_Tex2a_vp.glsl deleted file mode 100644 index 87f6acea03c..00000000000 --- a/Samples/Media/materials/programs/GLSL/StdQuad_Tex2a_vp.glsl +++ /dev/null @@ -1,16 +0,0 @@ -uniform mat4 worldViewProj; -attribute vec4 vertex; -attribute vec2 uv0; -varying vec2 oUv0; -varying vec2 oUv1; -varying vec4 pos; - -void main() -{ - // Use standardise transform, so work accord with render system specific (RS depth, requires texture flipping, etc) - gl_Position = worldViewProj * vertex; - - oUv0 = uv0; - oUv1 = -vertex.xy; - pos = gl_Position; -} diff --git a/Samples/Media/materials/programs/GLSL/StdQuad_Tex3_vp.glsl b/Samples/Media/materials/programs/GLSL/StdQuad_Tex3_vp.glsl deleted file mode 100644 index ad4f85ec09e..00000000000 --- a/Samples/Media/materials/programs/GLSL/StdQuad_Tex3_vp.glsl +++ /dev/null @@ -1,19 +0,0 @@ -uniform mat4 worldViewProj; -attribute vec4 vertex; -attribute vec2 uv0; -varying vec2 oUv0; -varying vec2 oUv1; -varying vec2 oUv2; -varying vec4 pos; - -void main() -{ - // Use standardise transform, so work accord with render system specific (RS depth, requires texture flipping, etc) - gl_Position = worldViewProj * vertex; - - // Convert to image-space - oUv0 = uv0; - oUv1 = oUv0; - oUv2 = oUv0; - pos = gl_Position; -} diff --git a/Samples/Media/materials/programs/GLSL/StdQuad_Tex4_vp.glsl b/Samples/Media/materials/programs/GLSL/StdQuad_Tex4_vp.glsl deleted file mode 100644 index 58578e45b6d..00000000000 --- a/Samples/Media/materials/programs/GLSL/StdQuad_Tex4_vp.glsl +++ /dev/null @@ -1,21 +0,0 @@ -uniform mat4 worldViewProj; -attribute vec4 vertex; -attribute vec2 uv0; -varying vec2 oUv0; -varying vec2 oUv1; -varying vec2 oUv2; -varying vec2 oUv3; -varying vec4 pos; - -void main() -{ - // Use standardise transform, so work accord with render system specific (RS depth, requires texture flipping, etc) - gl_Position = worldViewProj * vertex; - - // Convert to image-space - oUv0 = uv0; - oUv1 = oUv0; - oUv2 = oUv0; - oUv3 = oUv0; - pos = gl_Position; -} diff --git a/Samples/Media/materials/programs/GLSL/StdQuad_vp.glsl b/Samples/Media/materials/programs/GLSL/StdQuad_vp.glsl deleted file mode 100644 index 168adf58cfa..00000000000 --- a/Samples/Media/materials/programs/GLSL/StdQuad_vp.glsl +++ /dev/null @@ -1,12 +0,0 @@ -attribute vec4 vertex; -uniform mat4 worldViewProj; - -varying vec2 oUv0; - -void main() -{ - gl_Position = worldViewProj * vertex; - - vec2 inPos = sign(vertex.xy); - oUv0 = (vec2(inPos.x, -inPos.y) + 1.0) * 0.5; -} diff --git a/Samples/Media/materials/programs/GLSL/TilingFP.glsl b/Samples/Media/materials/programs/GLSL/TilingFP.glsl deleted file mode 100644 index 1a9ca76e323..00000000000 --- a/Samples/Media/materials/programs/GLSL/TilingFP.glsl +++ /dev/null @@ -1,31 +0,0 @@ -uniform sampler2D RT; -uniform float NumTiles; -uniform float Threshold; -varying vec2 oUv0; - -void main() -{ - vec3 EdgeColor = vec3(0.7, 0.7, 0.7); - - float size = 1.0/NumTiles; - vec2 Pbase = oUv0 - mod(oUv0, vec2(size)); - vec2 PCenter = vec2(Pbase + (size/2.0)); - vec2 st = (oUv0 - Pbase)/size; - vec4 c1 = vec4(0.0); - vec4 c2 = vec4(0.0); - vec4 invOff = vec4((1.0-EdgeColor),1.0); - if (st.x > st.y) { c1 = invOff; } - float threshholdB = 1.0 - Threshold; - if (st.x > threshholdB) { c2 = c1; } - if (st.y > threshholdB) { c2 = c1; } - vec4 cBottom = c2; - c1 = vec4(0.0); - c2 = vec4(0.0); - if (st.x > st.y) { c1 = invOff; } - if (st.x < Threshold) { c2 = c1; } - if (st.y < Threshold) { c2 = c1; } - vec4 cTop = c2; - vec4 tileColor = vec4(texture2D(RT, PCenter)); - vec4 result = tileColor + cTop - cBottom; - gl_FragColor = result; -} diff --git a/Samples/Media/materials/programs/GLSL/hdr_bloom.glsl b/Samples/Media/materials/programs/GLSL/hdr_bloom.glsl deleted file mode 100644 index 21a2e1dd996..00000000000 --- a/Samples/Media/materials/programs/GLSL/hdr_bloom.glsl +++ /dev/null @@ -1,22 +0,0 @@ -uniform sampler2D inRTT; - -uniform vec4 sampleOffsets[15]; -uniform vec4 sampleWeights[15]; - -varying vec2 oUv0; - -void main(void) -{ - vec4 accum = vec4(0.0, 0.0, 0.0, 1.0); - vec2 sampleUV; - - for( int i = 0; i < 15; i++ ) - { - // Sample from adjacent points, 7 each side and central - sampleUV = oUv0 + sampleOffsets[i].xy; - accum += sampleWeights[i] * texture2D(inRTT, sampleUV); - } - - gl_FragColor = accum; - -} diff --git a/Samples/Media/materials/programs/GLSL/hdr_downscale2x2luminence.glsl b/Samples/Media/materials/programs/GLSL/hdr_downscale2x2luminence.glsl deleted file mode 100644 index 971981e177a..00000000000 --- a/Samples/Media/materials/programs/GLSL/hdr_downscale2x2luminence.glsl +++ /dev/null @@ -1,24 +0,0 @@ -uniform sampler2D inRTT; -uniform vec2 texelSize; - -varying vec2 oUv0; - -void main(void) -{ - - vec4 accum = vec4(0.0, 0.0, 0.0, 0.0); - vec4 LUMINENCE_FACTOR = vec4(0.27, 0.67, 0.06, 0.0); - - // Get colour from source - accum += texture2D(inRTT, oUv0 + texelSize * vec2(-0.5, -0.5)); - accum += texture2D(inRTT, oUv0 + texelSize * vec2(-0.5, 0.5)); - accum += texture2D(inRTT, oUv0 + texelSize * vec2(0.5, 0.5)); - accum += texture2D(inRTT, oUv0 + texelSize * vec2(0.5, -0.5)); - - // Adjust the accumulated amount by lum factor - float lum = dot(accum, LUMINENCE_FACTOR); - // take average of 4 samples - lum *= 0.25; - gl_FragColor = vec4(lum, lum, lum, 1.0); - -} diff --git a/Samples/Media/materials/programs/GLSL/hdr_downscale3x3.glsl b/Samples/Media/materials/programs/GLSL/hdr_downscale3x3.glsl deleted file mode 100644 index ee8292b9863..00000000000 --- a/Samples/Media/materials/programs/GLSL/hdr_downscale3x3.glsl +++ /dev/null @@ -1,26 +0,0 @@ -uniform sampler2D inRTT; -uniform vec2 texelSize; - -varying vec2 oUv0; - -void main(void) -{ - vec4 accum = vec4(0.0, 0.0, 0.0, 0.0); - - // Get colour from source - accum += texture2D(inRTT, oUv0 + texelSize * vec2(-1.0, -1.0)); - accum += texture2D(inRTT, oUv0 + texelSize * vec2( 0.0, -1.0)); - accum += texture2D(inRTT, oUv0 + texelSize * vec2( 1.0, -1.0)); - accum += texture2D(inRTT, oUv0 + texelSize * vec2(-1.0, 0.0)); - accum += texture2D(inRTT, oUv0 + texelSize * vec2( 0.0, 0.0)); - accum += texture2D(inRTT, oUv0 + texelSize * vec2( 1.0, 0.0)); - accum += texture2D(inRTT, oUv0 + texelSize * vec2(-1.0, 1.0)); - accum += texture2D(inRTT, oUv0 + texelSize * vec2( 0.0, 1.0)); - accum += texture2D(inRTT, oUv0 + texelSize * vec2( 1.0, 1.0)); - - // take average of 9 samples - accum *= 0.1111111111111111; - - gl_FragColor = accum; - -} diff --git a/Samples/Media/materials/programs/GLSL/hdr_downscale3x3brightpass.glsl b/Samples/Media/materials/programs/GLSL/hdr_downscale3x3brightpass.glsl deleted file mode 100644 index 8ec91e7bade..00000000000 --- a/Samples/Media/materials/programs/GLSL/hdr_downscale3x3brightpass.glsl +++ /dev/null @@ -1,36 +0,0 @@ -uniform sampler2D inRTT; -uniform sampler2D inLum; -uniform vec2 texelSize; - -varying vec2 oUv0; -const vec4 BRIGHT_LIMITER = vec4(0.6, 0.6, 0.6, 0.0); - -#include "hdr_tonemap_util.glsl" - -void main(void) -{ - vec4 accum = vec4(0.0, 0.0, 0.0, 0.0); - - accum += texture2D(inRTT, oUv0 + texelSize * vec2(-1.0, -1.0)); - accum += texture2D(inRTT, oUv0 + texelSize * vec2( 0.0, -1.0)); - accum += texture2D(inRTT, oUv0 + texelSize * vec2( 1.0, -1.0)); - accum += texture2D(inRTT, oUv0 + texelSize * vec2(-1.0, 0.0)); - accum += texture2D(inRTT, oUv0 + texelSize * vec2( 0.0, 0.0)); - accum += texture2D(inRTT, oUv0 + texelSize * vec2( 1.0, 0.0)); - accum += texture2D(inRTT, oUv0 + texelSize * vec2(-1.0, 1.0)); - accum += texture2D(inRTT, oUv0 + texelSize * vec2( 0.0, 1.0)); - accum += texture2D(inRTT, oUv0 + texelSize * vec2( 1.0, 1.0)); - - // take average of 9 samples - accum *= 0.1111111111111111; - - // Reduce bright and clamp - accum = max(vec4(0.0, 0.0, 0.0, 1.0), accum - BRIGHT_LIMITER); - - // Sample the luminence texture - vec4 lum = texture2D(inLum, vec2(0.5, 0.5)); - - // Tone map result - gl_FragColor = toneMap(accum, lum.r); - -} diff --git a/Samples/Media/materials/programs/GLSL/hdr_finalToneMapping.glsl b/Samples/Media/materials/programs/GLSL/hdr_finalToneMapping.glsl deleted file mode 100644 index 48a70ce4945..00000000000 --- a/Samples/Media/materials/programs/GLSL/hdr_finalToneMapping.glsl +++ /dev/null @@ -1,27 +0,0 @@ -uniform sampler2D inRTT; -uniform sampler2D inBloom; -uniform sampler2D inLum; - -varying vec2 oUv0; - -#include "hdr_tonemap_util.glsl" - -void main(void) -{ - // Get main scene colour - vec4 sceneCol = texture2D(inRTT, oUv0); - - // Get luminence value - vec4 lum = texture2D(inLum, vec2(0.5, 0.5)); - - // tone map this - vec4 toneMappedSceneCol = toneMap(sceneCol, lum.r); - - // Get bloom colour - vec4 bloom = texture2D(inBloom, oUv0); - - // Add scene & bloom - gl_FragColor = vec4(toneMappedSceneCol.rgb + bloom.rgb, 1.0); - -} - diff --git a/Samples/Media/materials/programs/GLSL/hdr_tonemap_util.glsl b/Samples/Media/materials/programs/GLSL/hdr_tonemap_util.glsl deleted file mode 100644 index 14c58fb121d..00000000000 --- a/Samples/Media/materials/programs/GLSL/hdr_tonemap_util.glsl +++ /dev/null @@ -1,29 +0,0 @@ -const float MIDDLE_GREY = 0.72; -const float FUDGE = 0.001; -const float L_WHITE = 1.5; - -/** Tone mapping function -@note Only affects rgb, not a -@param inColour The HDR colour -@param lum The scene lumninence -@returns Tone mapped colour -*/ -vec4 toneMap(in vec4 inColour, in float lum) -{ - // From Reinhard et al - // "Photographic Tone Reproduction for Digital Images" - - // Initial luminence scaling (equation 2) - inColour.rgb *= MIDDLE_GREY / (FUDGE + lum); - - // Control white out (equation 4 nom) - inColour.rgb *= (1.0 + inColour.rgb / L_WHITE); - - // Final mapping (equation 4 denom) - inColour.rgb /= (1.0 + inColour.rgb); - - return inColour; - -} - - diff --git a/Samples/Media/materials/programs/GLSL/pssmCasterFp.glsl b/Samples/Media/materials/programs/GLSL/pssmCasterFp.glsl deleted file mode 100644 index 3d109855c10..00000000000 --- a/Samples/Media/materials/programs/GLSL/pssmCasterFp.glsl +++ /dev/null @@ -1,4 +0,0 @@ -void main() -{ - gl_FragColor = vec4(vec3(gl_FragCoord.z), 1.0); -} diff --git a/Samples/Media/materials/programs/GLSL/wboit.frag b/Samples/Media/materials/programs/GLSL/wboit.frag deleted file mode 100644 index 1848cba824d..00000000000 --- a/Samples/Media/materials/programs/GLSL/wboit.frag +++ /dev/null @@ -1,18 +0,0 @@ -#include - -SAMPLER2D(accumTexture, 0); -SAMPLER2D(revealageTexture, 1); - -#ifdef OGRE_HLSL -void main(vec4 pos : POSITION, vec2 oUv0 : TEXCOORD0, out vec4 gl_FragColor : COLOR) -#else -varying vec2 oUv0; -void main() -#endif -{ - // Weighted Blended Order-Independent Transparency, Listing 4 - vec4 accum = texture2D(accumTexture, oUv0); - float r = accum.a; - accum.a = texture2D(revealageTexture, oUv0).r; - gl_FragColor = vec4(accum.rgb / clamp(accum.a, 1e-4, 5e4), r); -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/GLSL120/Example_TextureArrayPS.glsl b/Samples/Media/materials/programs/GLSL120/Example_TextureArrayPS.glsl deleted file mode 100644 index cbce7fae05d..00000000000 --- a/Samples/Media/materials/programs/GLSL120/Example_TextureArrayPS.glsl +++ /dev/null @@ -1,21 +0,0 @@ -#ifdef OGRE_GLSL -#extension GL_EXT_texture_array : enable -#endif - -#include - -SAMPLER2DARRAY(TextureArrayTex, 0); - -MAIN_PARAMETERS -IN(vec3 oUv, TEXCOORD0) -MAIN_DECLARATION -{ - vec3 texcoord; - texcoord = oUv; - texcoord.z = floor(texcoord.z); - vec4 c0 = texture2DArray(TextureArrayTex, texcoord); - texcoord.z += 1.0; - vec4 c1 = texture2DArray(TextureArrayTex, texcoord); - - gl_FragColor = mix(c0, c1, fract(oUv.z)); -} diff --git a/Samples/Media/materials/programs/GLSL120/HW_VTFInstancing.vert b/Samples/Media/materials/programs/GLSL120/HW_VTFInstancing.vert deleted file mode 100644 index 87c9370171d..00000000000 --- a/Samples/Media/materials/programs/GLSL120/HW_VTFInstancing.vert +++ /dev/null @@ -1,128 +0,0 @@ -//--------------------------------------------------------------------------- -//These materials/shaders are part of the NEW InstanceManager implementation -//Written by Matias N. Goldberg ("dark_sylinc") -//--------------------------------------------------------------------------- -#version 120 - -//Vertex input -attribute vec4 vertex; -attribute vec3 normal; - -#ifdef BONE_TWO_WEIGHTS - attribute vec4 blendWeights; -#endif - -attribute vec4 uv0; -attribute vec4 uv1; -attribute vec4 uv2; - -#if BONE_MATRIX_LUT - attribute vec4 uv3; - attribute vec4 uv4; - attribute vec4 uv5; -#endif - -attribute vec3 tangent; - -//Parameters -uniform mat4 viewProjMatrix; -uniform sampler2D matrixTexture; - -#if (DEPTH_SHADOWCASTER || DEPTH_SHADOWRECEIVER) -uniform vec4 depthRange; -#endif - -#if DEPTH_SHADOWRECEIVER -uniform mat4 texViewProjMatrix; -#endif - -//Output -#if DEPTH_SHADOWCASTER - varying vec2 depth; -#else - varying vec2 _uv0; - varying vec3 oNormal; - varying vec3 oVPos; - #if DEPTH_SHADOWRECEIVER - varying vec4 oLightSpacePos; - #endif -#endif - -vec3 calculateBlendPosition(vec3 position, mat2x4 blendDQ) -{ - vec3 blendPosition = position + 2.0*cross(blendDQ[0].yzw, cross(blendDQ[0].yzw, position) + blendDQ[0].x*position); - vec3 trans = 2.0*(blendDQ[0].x*blendDQ[1].yzw - blendDQ[1].x*blendDQ[0].yzw + cross(blendDQ[0].yzw, blendDQ[1].yzw)); - blendPosition += trans; - - return blendPosition; -} - -vec3 calculateBlendNormal(vec3 normal, mat2x4 blendDQ) -{ - return normal + 2.0*cross(blendDQ[0].yzw, cross(blendDQ[0].yzw, normal) + blendDQ[0].x*normal); -} - -//--------------------------------------------- -//Main Vertex Shader -//--------------------------------------------- -void main(void) -{ - vec4 worldPos; - vec3 worldNorm; - -#ifdef ST_DUAL_QUATERNION - mat2x4 blendDQ; - blendDQ[0] = texture2D( matrixTexture, vec2(uv1.x, 0.0) + uv2.xy ); - blendDQ[1] = texture2D( matrixTexture, vec2(uv1.y, 0.0) + uv2.xy ); -#ifdef BONE_TWO_WEIGHTS - mat2x4 blendDQ2; - blendDQ2[0] = texture2D( matrixTexture, vec2(uv1.z, 0.0) + uv2.xy ); - blendDQ2[1] = texture2D( matrixTexture, vec2(uv1.w, 0.0) + uv2.xy ); - - //Accurate antipodality handling. For speed increase, remove the following line - if (dot(blendDQ[0], blendDQ2[0]) < 0.0) blendDQ2 *= -1.0; - - //Blend the dual quaternions based on the weights - blendDQ *= blendWeights.x; - blendDQ += blendWeights.y*blendDQ2; - //Normalize the resultant dual quaternion - blendDQ /= length(blendDQ[0]); -#endif - worldPos = vec4(calculateBlendPosition(vertex.xyz, blendDQ), 1.0); - worldNorm = calculateBlendNormal(normal, blendDQ); -#else - mat3x4 worldMatrix; - worldMatrix[0] = texture2D( matrixTexture, uv1.xw + uv2.xy ); - worldMatrix[1] = texture2D( matrixTexture, uv1.yw + uv2.xy ); - worldMatrix[2] = texture2D( matrixTexture, uv1.zw + uv2.xy ); - - worldPos = vec4(vertex * worldMatrix, 1); - worldNorm = normal * mat3(worldMatrix); -#endif - -#if BONE_MATRIX_LUT - mat4 worldCompMatrix; - worldCompMatrix[0] = uv3; - worldCompMatrix[1] = uv4; - worldCompMatrix[2] = uv5; - worldCompMatrix[3] = vec4( 0, 0, 0, 1 ); - - worldPos = worldPos * worldCompMatrix; - worldNorm = worldNorm * mat3(worldCompMatrix); -#endif - - //Transform the position - gl_Position = viewProjMatrix * worldPos; - -#if DEPTH_SHADOWCASTER - depth = gl_Position.zw; -#else - _uv0 = uv0.xy; - oNormal = worldNorm; - oVPos = worldPos.xyz; - - #if DEPTH_SHADOWRECEIVER - oLightSpacePos = texViewProjMatrix * worldPos; - #endif -#endif -} diff --git a/Samples/Media/materials/programs/GLSL120/Instancing.frag b/Samples/Media/materials/programs/GLSL120/Instancing.frag deleted file mode 100644 index 8724b8f7e30..00000000000 --- a/Samples/Media/materials/programs/GLSL120/Instancing.frag +++ /dev/null @@ -1,68 +0,0 @@ -//--------------------------------------------------------------------------- -//These materials/shaders are part of the NEW InstanceManager implementation -//Written by Matias N. Goldberg ("dark_sylinc") -//--------------------------------------------------------------------------- - -uniform sampler2D diffuseMap; - -uniform vec4 lightPosition; -uniform vec3 cameraPosition; -uniform vec3 lightAmbient; -uniform vec3 lightDiffuse; -uniform vec3 lightSpecular; -uniform vec4 lightAttenuation; -uniform float lightGloss; - -#if DEPTH_SHADOWRECEIVER -uniform sampler2D shadowMap; - -float calcDepthShadow(sampler2D shadowMap, vec4 uv) -{ - uv /= uv.w; - uv.z = uv.z * 0.5 + 0.5; // convert -1..1 to 0..1 - return texture2D(shadowMap, uv.xy).x >= uv.z ? 1.0 : 0.0; -} -#endif - -varying vec2 _uv0; -varying vec3 oNormal; -varying vec3 oVPos; -#if DEPTH_SHADOWRECEIVER - varying vec4 oLightSpacePos; -#endif - -//--------------------------------------------- -//Main Pixel Shader -//--------------------------------------------- -void main(void) -{ - vec4 color = texture2D( diffuseMap, _uv0 ); - - float fShadow = 1.0; -#if DEPTH_SHADOWRECEIVER - fShadow = calcDepthShadow( shadowMap, oLightSpacePos ); -#endif - - vec4 baseColour = texture2D( diffuseMap, _uv0 ); - - //Blinn-Phong lighting - vec3 normal = normalize( oNormal ); - vec3 lightDir = lightPosition.xyz - oVPos * lightPosition.w; - vec3 eyeDir = normalize( cameraPosition - oVPos ); - - float fLength = length( lightDir ); - lightDir = normalize( lightDir ); - - float NdotL = max( 0.0, dot( normal, lightDir ) ); - vec3 halfVector = normalize(lightDir + eyeDir); - float HdotN = max( 0.0, dot( halfVector, normal ) ); - - vec3 ambient = lightAmbient * baseColour.xyz; - vec3 diffuse = lightDiffuse * NdotL * baseColour.xyz; - vec3 specular = lightSpecular * pow( HdotN, lightGloss ); - - vec3 directLighting = (diffuse + specular) * fShadow; - - gl_FragColor = vec4( directLighting + ambient, baseColour.a ); - //gl_FragColor = baseColour; -} diff --git a/Samples/Media/materials/programs/GLSL120/SwizzleGP.glsl b/Samples/Media/materials/programs/GLSL120/SwizzleGP.glsl deleted file mode 100644 index 568aa5e0f63..00000000000 --- a/Samples/Media/materials/programs/GLSL120/SwizzleGP.glsl +++ /dev/null @@ -1,46 +0,0 @@ -#ifdef USE_LAYOUT -#version 150 -out vec4 colour; -layout(triangles) in; -layout(line_strip, max_vertices = 6) out; -#else -#version 120 -varying out vec4 colour; -#endif - -#extension GL_EXT_geometry_shader4 : enable - -uniform vec4 origColour; -uniform vec4 cloneColour; - -void main(void) -{ - ///////////////////////////////////////////////////////////// - //This example has two parts - // step a) draw the primitive pushed down the pipeline - // there are gl_Vertices # of vertices - // put the vertex value into gl_Position - // use EmitVertex => 'create' a new vertex - // use EndPrimitive to signal that you are done creating a primitive! - // step b) create a new piece of geometry (I.E. WHY WE ARE USING A GEOMETRY SHADER!) - // I just do the same loop, but swizzle the x and y values - // result => the line we want to draw, and the same line, but along the other axis - - //Pass-thru! - int i; - for (i = 0; i < gl_VerticesIn; i++) { - gl_Position = gl_PositionIn[i]; - colour = origColour; - EmitVertex(); - } - EndPrimitive(); - - //New piece of geometry! We just swizzle the x and y terms - for (i = 0; i < gl_VerticesIn; i++){ - gl_Position = gl_PositionIn[i]; - gl_Position.xy = gl_Position.yx; - colour = cloneColour; - EmitVertex(); - } - EndPrimitive(); -} diff --git a/Samples/Media/materials/programs/GLSL120/VTFInstancing.vert b/Samples/Media/materials/programs/GLSL120/VTFInstancing.vert deleted file mode 100644 index 18b75ae4994..00000000000 --- a/Samples/Media/materials/programs/GLSL120/VTFInstancing.vert +++ /dev/null @@ -1,110 +0,0 @@ -//--------------------------------------------------------------------------- -//These materials/shaders are part of the NEW InstanceManager implementation -//Written by Matias N. Goldberg ("dark_sylinc") -//--------------------------------------------------------------------------- -#version 120 - -//Vertex input -attribute vec4 vertex; -attribute vec3 normal; - -#ifdef BONE_TWO_WEIGHTS - attribute vec4 blendWeights; -#endif - -attribute vec4 uv0; -attribute vec4 uv1; -attribute vec4 uv2; -attribute vec3 tangent; - -//Parameters -uniform mat4 viewProjMatrix; -uniform sampler2D matrixTexture; - -#if (DEPTH_SHADOWCASTER || DEPTH_SHADOWRECEIVER) -uniform vec4 depthRange; -#endif - -#if DEPTH_SHADOWRECEIVER -uniform mat4 texViewProjMatrix; -#endif - -//Output -#if DEPTH_SHADOWCASTER - varying vec2 depth; -#else - varying vec2 _uv0; - varying vec3 oNormal; - varying vec3 oVPos; - #if DEPTH_SHADOWRECEIVER - varying vec4 oLightSpacePos; - #endif -#endif - -vec3 calculateBlendPosition(vec3 position, mat2x4 blendDQ) -{ - vec3 blendPosition = position + 2.0*cross(blendDQ[0].yzw, cross(blendDQ[0].yzw, position) + blendDQ[0].x*position); - vec3 trans = 2.0*(blendDQ[0].x*blendDQ[1].yzw - blendDQ[1].x*blendDQ[0].yzw + cross(blendDQ[0].yzw, blendDQ[1].yzw)); - blendPosition += trans; - - return blendPosition; -} - -vec3 calculateBlendNormal(vec3 normal, mat2x4 blendDQ) -{ - return normal + 2.0*cross(blendDQ[0].yzw, cross(blendDQ[0].yzw, normal) + blendDQ[0].x*normal); -} - -//--------------------------------------------- -//Main Vertex Shader -//--------------------------------------------- -void main(void) -{ - vec4 worldPos; - vec3 worldNorm; - -#ifdef ST_DUAL_QUATERNION - mat2x4 blendDQ; - blendDQ[0] = texture2D( matrixTexture, uv1.xy ); - blendDQ[1] = texture2D( matrixTexture, uv1.zy ); -#ifdef BONE_TWO_WEIGHTS - mat2x4 blendDQ2; - blendDQ2[0] = texture2D( matrixTexture, uv2.xy ); - blendDQ2[1] = texture2D( matrixTexture, uv2.zw ); - - //Accurate antipodality handling. For speed increase, remove the following line - if (dot(blendDQ[0], blendDQ2[0]) < 0.0) blendDQ2 *= -1.0; - - //Blend the dual quaternions based on the weights - blendDQ *= blendWeights.x; - blendDQ += blendWeights.y*blendDQ2; - //Normalize the resultant dual quaternion - blendDQ /= length(blendDQ[0]); -#endif - worldPos = vec4(calculateBlendPosition(vertex.xyz, blendDQ), 1.0); - worldNorm = calculateBlendNormal(normal, blendDQ); -#else - mat3x4 worldMatrix; - worldMatrix[0] = texture2D( matrixTexture, uv1.xy ); - worldMatrix[1] = texture2D( matrixTexture, uv1.zw ); - worldMatrix[2] = texture2D( matrixTexture, uv2.xy ); - - worldPos = vec4(vertex * worldMatrix, 1); - worldNorm = normal * mat3(worldMatrix); -#endif - - //Transform the position - gl_Position = viewProjMatrix * worldPos; - -#if DEPTH_SHADOWCASTER - depth = gl_Position.zw; -#else - _uv0 = uv0.xy; - oNormal = worldNorm; - oVPos = worldPos.xyz; - - #if DEPTH_SHADOWRECEIVER - oLightSpacePos = texViewProjMatrix * worldPos; - #endif -#endif -} diff --git a/Samples/Media/materials/programs/GLSL120/mrttestfp_quad.glsl b/Samples/Media/materials/programs/GLSL120/mrttestfp_quad.glsl deleted file mode 100644 index a14e88dc4f2..00000000000 --- a/Samples/Media/materials/programs/GLSL120/mrttestfp_quad.glsl +++ /dev/null @@ -1,17 +0,0 @@ -uniform sampler2D rt0; -uniform sampler2D rt1; -uniform sampler2D rt2; -uniform sampler2D rt3; - -varying vec2 oUv0; - -void main(void) -{ - - //gl_FragColor = texture2D(rt0, uv); - gl_FragColor = texture2D(rt1, oUv0); - //gl_FragColor = texture2D(rt2, uv); - //gl_FragColor = texture2D(rt3, uv); - -} - diff --git a/Samples/Media/materials/programs/GLSL120/mrttestfp_scene.glsl b/Samples/Media/materials/programs/GLSL120/mrttestfp_scene.glsl deleted file mode 100644 index 55e948317e4..00000000000 --- a/Samples/Media/materials/programs/GLSL120/mrttestfp_scene.glsl +++ /dev/null @@ -1,20 +0,0 @@ -// Need to enable the draw buffers extension -#extension GL_ARB_draw_buffers : enable - -uniform sampler2D tex0; - -void main() -{ - vec4 baseColour = texture2D(tex0, gl_TexCoord[0].xy); - - gl_FragData[0] = baseColour; - - gl_FragData[1] = baseColour * vec4(1, 0, 0, 1); - - float abs = (baseColour.r + baseColour.g + baseColour.b) * 0.333; - gl_FragData[2] = vec4(abs, abs, abs, 1); - - float invabs = 1.0 - abs; - gl_FragData[3] = vec4(invabs, invabs, invabs, 1); -} - diff --git a/Samples/Media/materials/programs/GLSL120/oceanGLSL.frag b/Samples/Media/materials/programs/GLSL120/oceanGLSL.frag deleted file mode 100644 index 8baa4e49bd4..00000000000 --- a/Samples/Media/materials/programs/GLSL120/oceanGLSL.frag +++ /dev/null @@ -1,45 +0,0 @@ -// oceanGLSL.frag -// fragment program for Ocean water simulation -// 05 Aug 2005 -// adapted for Ogre by nfz -// converted from HLSL to GLSL -// original shader source from Render Monkey 1.6 Reflections Refractions.rfx - -// 06 Aug 2005: moved uvw calculation from fragment program into vertex program - -uniform float fadeBias; -uniform float fadeExp; -uniform vec4 waterColor; -uniform sampler3D Noise; -uniform samplerCube skyBox; - -varying vec3 uvw; -varying vec3 oNormal; -varying vec3 vVec; - -void main(void) -{ - vec3 noisy = texture3D(Noise, uvw).xyz; - - // convert to signed noise - vec3 bump = 2.0 * noisy - 1.0; - bump.xz *= 0.15; - // Make sure the normal always points upwards - // note that Ogres y axis is vertical (RM Z axis is vertical) - bump.y = 0.8 * abs(bump.y) + 0.2; - // Offset the surface normal with the bump - bump = normalize(oNormal + bump); - - // Find the reflection vector - vec3 normView = normalize(vVec); - vec3 reflVec = reflect(normView, bump); - // Ogre has z flipped for cubemaps - reflVec.z = -reflVec.z; - vec4 refl = textureCube(skyBox, reflVec); - - // set up for fresnel calc - float lrp = 1.0 - dot(-normView, bump); - - // Interpolate between the water color and reflection for fresnel effect - gl_FragColor = mix(waterColor, refl, clamp(fadeBias + pow(lrp, fadeExp), 0.0, 1.0) ); -} diff --git a/Samples/Media/materials/programs/GLSL120/oceanGLSL.vert b/Samples/Media/materials/programs/GLSL120/oceanGLSL.vert deleted file mode 100644 index 209cccf781d..00000000000 --- a/Samples/Media/materials/programs/GLSL120/oceanGLSL.vert +++ /dev/null @@ -1,35 +0,0 @@ -// oceanGLSL.vert -// vertex program for Ocean water simulation -// 05 Aug 2005 -// adapted for Ogre by nfz -// converted from HLSL to GLSL -// original shader source from Render Monkey 1.6 Reflections Refractions.rfx - -// 06 Aug 2005: moved uvw calculation from fragment program into vertex program - -uniform vec3 scale; -uniform vec3 eyePosition; -uniform vec2 waveSpeed; -uniform float noiseSpeed; -uniform float time_0_X; -uniform mat4 worldViewProj; - -attribute vec4 vertex; -attribute vec3 normal; - -varying vec3 uvw; -varying vec3 oNormal; -varying vec3 vVec; - -void main(void) -{ - gl_Position = worldViewProj * vertex; - - // the view vector needs to be in vertex space - vVec = vertex.xyz - eyePosition; - oNormal = normal; - // uvw is the calculated uvw coordinates based on vertex position - uvw = vertex.xyz * scale.xyz; - uvw.xz += waveSpeed * time_0_X; - uvw.y += uvw.z + noiseSpeed * time_0_X; -} diff --git a/Samples/Media/materials/programs/GLSL150/ASCIIFP.glsl b/Samples/Media/materials/programs/GLSL150/ASCIIFP.glsl deleted file mode 100644 index 08ef939b040..00000000000 --- a/Samples/Media/materials/programs/GLSL150/ASCIIFP.glsl +++ /dev/null @@ -1,37 +0,0 @@ -#version 150 - -in vec4 pos; -in vec2 oUv0; -out vec4 fragColour; - -uniform sampler2D RT; -uniform sampler3D chars; -uniform vec2 numTiles; -uniform vec2 iNumTiles; -uniform vec2 iNumTiles2; -uniform vec4 lum; -uniform float charBias; - -void main() -{ - vec3 local; - - //sample RT - local.xy = mod(oUv0, iNumTiles); - vec2 middle = oUv0 - local.xy; - local.xy = local.xy * numTiles; - - //iNumTiles2 = iNumTiles / 2 - middle = middle + iNumTiles2; - vec4 c = texture(RT, middle); - - //multiply luminance by charbias , beacause not all slices of the ascii - //volume texture are used - local.z = dot(c , lum)*charBias; - - //fix to brighten the dark pixels with small characters - //c *= lerp(2.0,1.0, local.z); - - c *= texture(chars, local); - fragColour = c; -} diff --git a/Samples/Media/materials/programs/GLSL150/Blur0_vs.glsl b/Samples/Media/materials/programs/GLSL150/Blur0_vs.glsl deleted file mode 100644 index d11b7885a79..00000000000 --- a/Samples/Media/materials/programs/GLSL150/Blur0_vs.glsl +++ /dev/null @@ -1,25 +0,0 @@ -#version 150 - -in vec4 vertex; -// in vec2 uv0; -out vec2 texCoord[5]; - -// uniform mat4 worldViewProj; - -void main() -{ - // gl_Position = worldViewProj * vertex; - - // texCoord[0] = uv0; - - vec2 inPos = sign(vertex.xy); - gl_Position = vec4(inPos.xy, 0.0, 1.0); - - texCoord[0] = (vec2(inPos.x, -inPos.y) + 1.0)/2.0; - - const float size = 0.01; - texCoord[1] = texCoord[0] + vec2(1.0, 0.0) * size; - texCoord[2] = texCoord[0] + vec2(2.0, 0.0) * size; - texCoord[3] = texCoord[0] + vec2(-1.0, 0.0) * size; - texCoord[4] = texCoord[0] + vec2(-2.0, 0.0) * size; -} diff --git a/Samples/Media/materials/programs/GLSL150/Blur1_vs.glsl b/Samples/Media/materials/programs/GLSL150/Blur1_vs.glsl deleted file mode 100644 index b4347697cef..00000000000 --- a/Samples/Media/materials/programs/GLSL150/Blur1_vs.glsl +++ /dev/null @@ -1,25 +0,0 @@ -#version 150 - -in vec4 vertex; -// in vec2 uv0; -out vec2 texCoord[5]; - -// uniform mat4 worldViewProj; - -void main() -{ - // gl_Position = worldViewProj * vertex; - - // texCoord[0] = uv0; - - vec2 inPos = sign(vertex.xy); - gl_Position = vec4(inPos.xy, 0.0, 1.0); - - texCoord[0] = (vec2(inPos.x, -inPos.y) + 1.0)/2.0; - - const float size = 0.01; - texCoord[1] = texCoord[0] + vec2(0.0, 1.0) * size; - texCoord[2] = texCoord[0] + vec2(0.0, 2.0) * size; - texCoord[3] = texCoord[0] + vec2(0.0, -1.0) * size; - texCoord[4] = texCoord[0] + vec2(0.0, -2.0) * size; -} diff --git a/Samples/Media/materials/programs/GLSL150/Blur_ps.glsl b/Samples/Media/materials/programs/GLSL150/Blur_ps.glsl deleted file mode 100644 index ea2716f43e7..00000000000 --- a/Samples/Media/materials/programs/GLSL150/Blur_ps.glsl +++ /dev/null @@ -1,18 +0,0 @@ -#version 150 - -uniform sampler2D tex0; - -in vec2 texCoord[5]; - -out vec4 fragColour; - -void main() -{ - vec4 sum = texture(tex0, texCoord[0]) + - texture(tex0, texCoord[1]) + - texture(tex0, texCoord[2]) + - texture(tex0, texCoord[3]) + - texture(tex0, texCoord[4]); - fragColour = sum / 5.0; -} - diff --git a/Samples/Media/materials/programs/GLSL150/Example_CelShadingFp.glsl b/Samples/Media/materials/programs/GLSL150/Example_CelShadingFp.glsl deleted file mode 100644 index be0dcd28edc..00000000000 --- a/Samples/Media/materials/programs/GLSL150/Example_CelShadingFp.glsl +++ /dev/null @@ -1,33 +0,0 @@ -#version 150 - -/* Cel shading fragment program for single-pass rendering */ -uniform vec4 diffuse; -uniform vec4 specular; -uniform sampler1D diffuseRamp; -uniform sampler1D specularRamp; -uniform sampler1D edgeRamp; - -in float diffuseIn; -in float specularIn; -in float edge; - -out vec4 fragColour; - -/*uniform lighting -{ - vec4 diffuse; - vec4 specular; -} LightingParams;*/ - -void main() -{ - // Step functions from textures - float diffuseStep = texture(diffuseRamp, diffuseIn).x; - float specularStep = texture(specularRamp, specularIn).x; - float edgeStep = texture(edgeRamp, edge).x; - - fragColour = edgeStep * ((diffuse * diffuseStep) + - (specular * specularStep)); -// fragColour = edgeStep * ((LightingParams.diffuse * diffuseStep) + -// (LightingParams.specular * specularStep)); -} diff --git a/Samples/Media/materials/programs/GLSL150/Example_CelShadingVp.glsl b/Samples/Media/materials/programs/GLSL150/Example_CelShadingVp.glsl deleted file mode 100644 index ddbff7f6d47..00000000000 --- a/Samples/Media/materials/programs/GLSL150/Example_CelShadingVp.glsl +++ /dev/null @@ -1,50 +0,0 @@ -#version 150 - -/* Cel shading vertex program for single-pass rendering - In this program, we want to calculate the diffuse and specular - ramp components, and the edge factor (for doing simple outlining) - For the outlining to look good, we need a pretty well curved model. -*/ -// Parameters -in vec4 vertex; -in vec3 normal; - -uniform vec3 lightPosition; // object space -uniform vec3 eyePosition; // object space -uniform vec4 shininess; -uniform mat4 worldViewProj; - -//uniform transform -//{ -// vec4 shininess; -//} MaterialShininess; - -out float diffuseIn; -out float specularIn; -out float edge; - -void main() -{ - // calculate output position - gl_Position = worldViewProj * vertex; - - // calculate light vector - vec3 N = normalize(normal); - vec3 L = normalize(lightPosition - vertex.xyz); - - // Calculate diffuse component - diffuseIn = max(dot(N, L) , 0.0); - - // Mask off specular if diffuse is 0 - if (diffuseIn == 0.0) - specularIn = 0.0; - - // Calculate specular component - vec3 E = normalize(eyePosition - vertex.xyz); - vec3 H = normalize(L + E); - specularIn = pow(max(dot(N, H), 0.0), shininess.x); -// specularIn = pow(max(dot(N, H), 0.0), MaterialShininess.shininess.x); - - // Edge detection, dot eye and normal vectors - edge = max(dot(N, E), 0.0); -} diff --git a/Samples/Media/materials/programs/GLSL150/HalftoneFP.glsl b/Samples/Media/materials/programs/GLSL150/HalftoneFP.glsl deleted file mode 100644 index 63d608dcd04..00000000000 --- a/Samples/Media/materials/programs/GLSL150/HalftoneFP.glsl +++ /dev/null @@ -1,25 +0,0 @@ -#version 150 - -in vec4 pos; -in vec2 oUv0; - -uniform vec2 numTiles; -uniform vec2 iNumTiles; -uniform vec2 iNumTiles2; -uniform vec4 lum; -uniform sampler2D RT; -uniform sampler3D noise; - -out vec4 fragColour; - -void main() -{ - vec3 local; - local.xy = mod(oUv0, iNumTiles); - vec2 middle = oUv0 - local.xy; - local.xy = local.xy * numTiles; - middle += iNumTiles2; - local.z = dot(texture(RT, middle), lum); - vec4 c = vec4(texture(noise,local).r); - fragColour = c; -} diff --git a/Samples/Media/materials/programs/GLSL150/IsosurfGS.glsl b/Samples/Media/materials/programs/GLSL150/IsosurfGS.glsl deleted file mode 100644 index a2bf5f38cb2..00000000000 --- a/Samples/Media/materials/programs/GLSL150/IsosurfGS.glsl +++ /dev/null @@ -1,89 +0,0 @@ -#version 150 - -// Ogre port of Nvidia's IsoSurf.cg file -// Modified code follows. See http://developer.download.nvidia.com/SDK/10/opengl/samples.html for original -// -// Cg port of Yury Uralsky's metaball FX shader -// -// Authors: Simon Green and Yury Urlasky -// Email: sdkfeedback@nvidia.com -// -// Copyright (c) NVIDIA Corporation. All rights reserved. -//////////////////////////////////////////////////////////////////////////////////////////////////// - -// Size of the sampling grid -in VertexData -{ - vec3 N; - vec2 Field; -} VertexIn[]; - -out vec3 oNormal; - -uniform float IsoValue; - -layout(lines_adjacency) in; -layout(triangle_strip, max_vertices = 4) out; - -// Estimate where isosurface intersects grid edge with endpoints v0, v1. -void CalcIntersection(vec4 Pos0, - vec3 N0, - vec2 Field0, - vec4 Pos1, - vec3 N1, - vec2 Field1) -{ - float t = (IsoValue - Field0.x) / (Field1.x - Field0.x); - if ((Field0.x < IsoValue) && (Field1.x > Field0.x)) - { - if (t > 0 && t < 1) - { - gl_Position = mix(Pos0, Pos1, t); - oNormal = mix(N0, N1, t); - EmitVertex(); - } - } -} - -// Geometry shader -// input: line with adjacency (tetrahedron) -// outputs: zero, one or two triangles depending if isosurface intersects tetrahedron -void main() -{ - - // Construct index for this tetrahedron. - uint index = uint((uint(VertexIn[0].Field.y) << 3) | - (uint(VertexIn[1].Field.y) << 2) | - (uint(VertexIn[2].Field.y) << 1) | - uint(VertexIn[3].Field.y)); - - // Don't bother if all vertices out or all vertices inside isosurface. - if (index > uint(0) && index < uint(15)) - { - // Uber-compressed version of the edge table. - uint edgeListHex[8] = - uint[8](uint(0x0001cde0), uint(0x98b08c9d), uint(0x674046ce), uint(0x487bc480), - uint(0x21301d2e), uint(0x139bd910), uint(0x26376e20), uint(0x3b700000)); - - uint edgeValFull = edgeListHex[index/uint(2)]; - uint three = uint(0x3); - uint edgeVal = (index % uint(2) == uint(1)) ? (edgeValFull & uint(0xFFFF)) : ((edgeValFull >> 16) & uint(0xFFFF)); - ivec4 e0 = ivec4((edgeVal >> 14) & three, (edgeVal >> 12) & three, (edgeVal >> 10) & three, (edgeVal >> 8) & three); - ivec4 e1 = ivec4((edgeVal >> 6) & three, (edgeVal >> 4) & three, (edgeVal >> 2) & three, (edgeVal >> 0) & three); - - CalcIntersection(gl_in[e0.x].gl_Position, VertexIn[e0.x].N, VertexIn[e0.x].Field, - gl_in[e0.y].gl_Position, VertexIn[e0.y].N, VertexIn[e0.y].Field); - CalcIntersection(gl_in[e0.z].gl_Position, VertexIn[e0.z].N, VertexIn[e0.z].Field, - gl_in[e0.w].gl_Position, VertexIn[e0.w].N, VertexIn[e0.w].Field); - CalcIntersection(gl_in[e1.x].gl_Position, VertexIn[e1.x].N, VertexIn[e1.x].Field, - gl_in[e1.y].gl_Position, VertexIn[e1.y].N, VertexIn[e1.y].Field); - - // Emit additional triangle, if necessary. - if (e1.z != -1) { - CalcIntersection(gl_in[e1.z].gl_Position, VertexIn[e1.z].N, VertexIn[e1.z].Field, - gl_in[e1.w].gl_Position, VertexIn[e1.w].N, VertexIn[e1.w].Field); - } - - EndPrimitive(); - } -} diff --git a/Samples/Media/materials/programs/GLSL150/LightToHeatFp.glsl b/Samples/Media/materials/programs/GLSL150/LightToHeatFp.glsl deleted file mode 100644 index 3f3a59f9cd2..00000000000 --- a/Samples/Media/materials/programs/GLSL150/LightToHeatFp.glsl +++ /dev/null @@ -1,36 +0,0 @@ -#version 150 - -uniform vec4 random_fractions; -uniform vec4 heatBiasScale; -uniform vec4 depth_modulator; - -uniform sampler2D Input; // output of HeatVisionCaster_fp (NdotV) -uniform sampler2D NoiseMap; -uniform sampler2D HeatLookup; - -// in vec4 diffuse; -in vec2 uv; -out vec4 fragColour; - -void main() -{ - float depth, heat, interference; - - // Output constant color: - depth = texture( Input, uv ).x; - depth *= (depth * depth_modulator).x; - - heat = (depth * heatBiasScale.y); - - // if (depth > 0) - { - interference = -0.5 + texture( NoiseMap, uv + vec2( random_fractions.x, random_fractions.y ) ).x; - interference *= interference; - interference *= 1.0 - heat; - heat += interference;//+ heatBiasScale.x; - } - - // Clamp UVs - heat = max( 0.005, min( 0.995, heat ) ); - fragColour = texture( HeatLookup, vec2( heat, 0.0 ) ); -} diff --git a/Samples/Media/materials/programs/GLSL150/NightVisionFP.glsl b/Samples/Media/materials/programs/GLSL150/NightVisionFP.glsl deleted file mode 100644 index dce891a0fac..00000000000 --- a/Samples/Media/materials/programs/GLSL150/NightVisionFP.glsl +++ /dev/null @@ -1,32 +0,0 @@ -#version 150 - -out vec4 fragColour; - -uniform sampler2D RT; -uniform sampler3D noiseVol; - -in vec2 oUv0; -uniform vec4 lum; -uniform float time; - -void main() -{ - vec4 oC; - oC = texture(RT, oUv0); - - //obtain luminence value - oC = vec4(dot(oC,lum)); - - //add some random noise - oC += 0.2 *(texture(noiseVol, vec3(oUv0*5,time)))- 0.05; - - //add lens circle effect - //(could be optimised by using texture) - float dist = distance(oUv0, vec2(0.5,0.5)); - oC *= smoothstep(0.5,0.45,dist); - - //add rb to the brightest pixels - oC.rb = vec2(max(oC.r - 0.75, 0)*4); - - fragColour = oC; -} diff --git a/Samples/Media/materials/programs/GLSL150/OldTV.glsl b/Samples/Media/materials/programs/GLSL150/OldTV.glsl deleted file mode 100644 index 717a8341205..00000000000 --- a/Samples/Media/materials/programs/GLSL150/OldTV.glsl +++ /dev/null @@ -1,45 +0,0 @@ -#version 150 - -in vec4 pos; -in vec2 oUv0; -out vec4 fragColour; - -uniform sampler2D Image; -uniform sampler3D Rand; -uniform sampler3D Noise; -uniform float distortionFreq; -uniform float distortionScale; -uniform float distortionRoll; -uniform float interference; -uniform float frameLimit; -uniform float frameShape; -uniform float frameSharpness; -uniform float time_0_X; -uniform float sin_time_0_X; - -void main() -{ - // Define a frame shape - float f = (1 - pos.x * pos.x) * (1 - pos.y * pos.y); - float frame = clamp(frameSharpness * (pow(f, frameShape) - frameLimit), 0.0, 1.0); - - // Interference ... just a texture filled with rand() - float rand = texture(Rand, vec3(1.5 * pos.x, 1.5 * pos.y, time_0_X)).x - 0.2; - - // Some signed noise for the distortion effect - float noisy = texture(Noise, vec3(0, 0.5 * pos.y, 0.1 * time_0_X)).x - 0.5; - - // Repeat a 1 - x^2 (0 < x < 1) curve and roll it with sinus. - float dst = fract(pos.y * distortionFreq + distortionRoll * sin_time_0_X); - dst *= (1 - dst); - // Make sure distortion is highest in the center of the image - dst /= 1 + distortionScale * abs(pos.y); - - // ... and finally distort - vec2 inUv = oUv0; - inUv.x += distortionScale * noisy * dst; - vec4 image = texture(Image, inUv); - - // Combine frame, distorted image and interference - fragColour = frame * (interference * rand + image); -} diff --git a/Samples/Media/materials/programs/GLSL150/ParticleGS_DisplayFS.glsl b/Samples/Media/materials/programs/GLSL150/ParticleGS_DisplayFS.glsl deleted file mode 100644 index 4e2df6e35b3..00000000000 --- a/Samples/Media/materials/programs/GLSL150/ParticleGS_DisplayFS.glsl +++ /dev/null @@ -1,11 +0,0 @@ -#version 150 - -in vec4 colour; -out vec4 fragColour; -uniform sampler2D diffuseTex; - -// Colours the fireworks. -void main() -{ - fragColour = texture(diffuseTex, gl_PointCoord.st) * colour; -} diff --git a/Samples/Media/materials/programs/GLSL150/ParticleGS_DisplayVS.glsl b/Samples/Media/materials/programs/GLSL150/ParticleGS_DisplayVS.glsl deleted file mode 100644 index 14663e6df57..00000000000 --- a/Samples/Media/materials/programs/GLSL150/ParticleGS_DisplayVS.glsl +++ /dev/null @@ -1,81 +0,0 @@ -#version 150 - -// -// Explanation of different particle types -// -// Firework Launcher - launches a PT_SHELL every so many seconds. -#define PT_LAUNCHER 0 -// Unexploded shell - flies from the origin and explodes into many PT_EMBERX's. -#define PT_SHELL 1 -// Basic particle - after it's emitted from the shell, it dies. -#define PT_EMBER1 2 -// After it's emitted, it explodes again into many PT_EMBER1's. -#define PT_EMBER2 3 -// Just a differently colored ember1. -#define PT_EMBER3 4 -#define P_SHELLLIFE 3.0 -#define P_EMBER1LIFE 2.5 -#define P_EMBER2LIFE 1.5 -#define P_EMBER3LIFE 2.0 - -in vec4 position; -// timer -in float uv0; -// type -in float uv1; -// velocity -in vec3 uv2; - -out vec4 colour; - -uniform mat4 worldView; -uniform mat4 proj; -uniform float height; - -//The vertex shader that prepares the fireworks for display -void main() -{ - float inTimer = uv0; - float inType = uv1; - - float radius = 1.5; - - gl_Position = worldView * position; - - // - // calculate the colour - // - if (inType == PT_LAUNCHER) - { - // red - colour = vec4(1, 0.1, 0.1, 1); - radius = 1.0; - } - else if (inType == PT_SHELL) - { - // cyan - colour = vec4(0.1, 1, 1, 1); - radius = 1.0; - } - else if (inType == PT_EMBER1) - { - // yellow - colour = vec4(1, 1, 0.1, 1); - colour *= (inTimer / P_EMBER1LIFE); - } - else if (inType == PT_EMBER2) - { - // fuschia - colour = vec4(1, 0.1, 1, 1); - } - else if (inType == PT_EMBER3) - { - // red - colour = vec4(1, 0.1, 0.1, 1); - colour *= (inTimer / P_EMBER3LIFE); - } - - vec4 tmp = proj * vec4(radius*2, 0, gl_Position.z, 1); - gl_PointSize = tmp.x/tmp.w*height; - gl_Position = proj*gl_Position; -} diff --git a/Samples/Media/materials/programs/GLSL150/ParticleGS_GenerateGS.glsl b/Samples/Media/materials/programs/GLSL150/ParticleGS_GenerateGS.glsl deleted file mode 100644 index 0d8c4dc6f02..00000000000 --- a/Samples/Media/materials/programs/GLSL150/ParticleGS_GenerateGS.glsl +++ /dev/null @@ -1,240 +0,0 @@ -#version 150 - -// -// Explanation of different particle types. -// -// Firework Launcher - launches a PT_SHELL every so many seconds. -#define PT_LAUNCHER 0 -// Unexploded shell - flies from the origin and explodes into many PT_EMBERX's. -#define PT_SHELL 1 -// Basic particle - after it's emitted from the shell, it dies. -#define PT_EMBER1 2 -// After it's emitted, it explodes again into many PT_EMBER1's. -#define PT_EMBER2 3 -// Just a different colored ember1. -#define PT_EMBER3 4 -#define P_SHELLLIFE 3.0 -#define P_EMBER1LIFE 2.5 -#define P_EMBER2LIFE 1.5 -#define P_EMBER3LIFE 2.0 - -// These two were originally shader params, but they caused runtime errors. -#define NUM_EMBER_1S 30 -#define NUM_EMBER_2S 15 -#define NUM_EMBER_3S 10 -// This one was originally a variant, but also causes runtime errors. -//#define MAX_EMBER_2S 15.0 - -layout(points) in; -layout(points, max_vertices = 60) out; - -in block { - vec3 Pos; - float Timer; - float Type; - vec3 Vel; -} FireworkData[]; - -out vec3 xfb_position; -out float xfb_uv0; // Timer -out float xfb_uv1; // Type -out vec3 xfb_uv2; // Velocity - -uniform sampler1D randomTexture; -uniform vec3 gravity; -uniform float globalTime; -uniform float elapsedTime; -uniform float secondsPerFirework; - -// -// Generic particle motion handler -// -void GSGenericHandler( vec3 Pos, vec3 Vel, float Timer, float Type, - float elapsedTime, - vec3 frameGravity) -{ - Vel += frameGravity; - Timer -= elapsedTime; - - if (Pos.y > -100) - { - xfb_position = Pos + (Vel * elapsedTime); - xfb_uv0 = Timer; - xfb_uv1 = Type; - xfb_uv2 = Vel; - EmitVertex(); - } -} - -// -// Sample a random direction from our random texture -// -vec3 RandomDir(float fOffset, float globalTime, sampler1D randomTex) -{ - float tCoord = (globalTime + fOffset) / 300.0; - return texture(randomTex, tCoord).rgb; -} - -// -// Launcher type particle handler -// -void GSLauncherHandler( vec3 Pos, vec3 Vel, float Timer, float Type, - float elapsedTime, - float globalTime, - sampler1D randomTex, - float secondsPerFirework) -{ - if (Timer <= 0) - { - vec3 vRandom = normalize(RandomDir(Type, globalTime, randomTex)); - // Give it more of an up bias. - vRandom = normalize(vRandom + vec3(0, 2.5, 0)); - - // Time to emit a new SHELL. - xfb_position = Pos + Vel * elapsedTime; - xfb_uv2 = Vel + vRandom * 35.0; - xfb_uv0 = P_SHELLLIFE + vRandom.y * 0.5; - xfb_uv1 = PT_SHELL; - EmitVertex(); - - // Reset our timer. - Timer = secondsPerFirework + vRandom.x * 0.4; - } - else - { - Timer -= elapsedTime; - } - - // Emit ourselves to keep us alive. - xfb_position = Pos; - xfb_uv2 = Vel; - xfb_uv0 = Timer; - xfb_uv1 = Type; - EmitVertex(); -} - -// -// Shell type particle handler -// -void GSShellHandler( vec3 Pos, vec3 Vel, float Timer, float Type, - float elapsedTime, - float globalTime, - sampler1D randomTex, - vec3 frameGravity) -{ - if (Timer <= 0) - { - vec3 vRandom = vec3(0,0,0); - - // Time to emit a series of new Ember1s. - for (int i = 0; i < NUM_EMBER_1S; i++) - { - vRandom = normalize(RandomDir(Type + i, globalTime, randomTex)); - xfb_position = Pos + Vel * elapsedTime; - xfb_uv2 = Vel + vRandom * 15.0; - xfb_uv0 = P_EMBER1LIFE; - xfb_uv1 = PT_EMBER1; - EmitVertex(); - } - - // Find out how many Ember2s to emit. - // Not doing this because it causes a runtime error. - //int numEmber2s = abs(vRandom.x)*MAX_EMBER_2S; - for (int i = 0; i < NUM_EMBER_2S; i++) - { - vRandom = normalize(RandomDir(Type, globalTime, randomTex)); - xfb_position = Pos + Vel * elapsedTime; - xfb_uv2 = Vel + vRandom * 10.0; - xfb_uv0 = P_EMBER2LIFE + 0.4 * vRandom.x; - xfb_uv1 = PT_EMBER2; - EmitVertex(); - } - - } - else - { - GSGenericHandler(Pos, Vel, Timer, Type, elapsedTime, frameGravity); - } -} - -// -// Ember1 and Ember3 type particle handler. -// -void GSEmber1Handler( vec3 Pos, vec3 Vel, float Timer, float Type, - float elapsedTime, - vec3 frameGravity) -{ - if (Timer > 0) - { - GSGenericHandler(Pos, Vel, Timer, Type, elapsedTime, frameGravity); - } -} - -// -// Ember2 type particle handler. -// -void GSEmber2Handler( vec3 Pos, vec3 Vel, float Timer, float Type, - float elapsedTime, - float globalTime, - sampler1D randomTex, - vec3 frameGravity) -{ - if (Timer <= 0) - { - // Time to emit a series of new Ember3's. - for (int i = 0; i < NUM_EMBER_3S; i++) - { - xfb_position = Pos + Vel * elapsedTime; - xfb_uv2 = Vel + normalize(RandomDir(Type + i, globalTime, randomTex)) * 10.0; - xfb_uv0 = P_EMBER3LIFE; - xfb_uv1 = PT_EMBER3; - EmitVertex(); - } - } - else - { - GSGenericHandler(Pos, Vel, Timer, Type, elapsedTime, frameGravity); - } -} - -void main() -{ - vec3 frameGravity = gravity * elapsedTime; - if (FireworkData[0].Type == PT_LAUNCHER) - GSLauncherHandler(FireworkData[0].Pos.xyz, FireworkData[0].Vel, FireworkData[0].Timer, FireworkData[0].Type, - elapsedTime, globalTime, randomTexture, secondsPerFirework); - else if (FireworkData[0].Type == PT_SHELL) - GSShellHandler(FireworkData[0].Pos.xyz, FireworkData[0].Vel, FireworkData[0].Timer, FireworkData[0].Type, - elapsedTime, globalTime, randomTexture, frameGravity); - else if (FireworkData[0].Type == PT_EMBER1 || - FireworkData[0].Type == PT_EMBER3) - GSEmber1Handler(FireworkData[0].Pos.xyz, FireworkData[0].Vel, FireworkData[0].Timer, FireworkData[0].Type, - elapsedTime, frameGravity); - else if (FireworkData[0].Type == PT_EMBER2) - GSEmber2Handler(FireworkData[0].Pos.xyz, FireworkData[0].Vel, FireworkData[0].Timer, FireworkData[0].Type, - elapsedTime, globalTime, randomTexture, frameGravity); - EndPrimitive(); - - // // gl_Position.xyz = FireworkData[0].Pos;// + FireworkData[0].Vel * elapsedTime; - // // gl_Position.w = 1; - // gl_Position = FireworkData[0].Pos + 1;// + FireworkData[0].Vel * elapsedTime; - // // gl_Position = Pos[0];// + FireworkData[0].Vel * elapsedTime; - // //gl_Position = vec4(10, 10, 10, 1); - // // xfb_uv0 = P_SHELLLIFE + 0.5; - // xfb_uv0 = FireworkData[0].Timer; - // // xfb_uv0 = Timer[0]; - // xfb_uv1 = FireworkData[0].Type; - // // xfb_uv1 = Type[0]; - // xfb_uv2 = FireworkData[0].Vel; - // // xfb_uv2 = Vel[0]; - // //xfb_uv2 = vec3(4, 5, 35.0); - // EmitVertex(); - // EndPrimitive(); - // // // gl_Position = vec4(10, 20, 30, 1); - // gl_Position = vec3(10, 20, 30); - // xfb_uv0 = P_EMBER3LIFE; - // xfb_uv1 = PT_SHELL; - // xfb_uv2 = vec3(40, 50, 60); - // EmitVertex(); - // EndPrimitive(); -} diff --git a/Samples/Media/materials/programs/GLSL150/ParticleGS_GenerateVS.glsl b/Samples/Media/materials/programs/GLSL150/ParticleGS_GenerateVS.glsl deleted file mode 100644 index 8376a779cb4..00000000000 --- a/Samples/Media/materials/programs/GLSL150/ParticleGS_GenerateVS.glsl +++ /dev/null @@ -1,40 +0,0 @@ -#version 150 - -in vec3 vertex; -in float uv0; // Timer -in float uv1; // Type -in vec3 uv2; // Velocity -// in float inTimer; -// in float inType; -// in vec3 inVelocity; - - -out block { - vec3 Pos; - float Timer; - float Type; - vec3 Vel; -} FireworkData; - -// out vec3 Pos; -// out float Timer; -// out float Type; -// out vec3 Vel; - -//The vertex shader that prepares the fireworks for display -void main() -{ - FireworkData.Pos = vertex; - FireworkData.Timer = uv0; - FireworkData.Type = uv1; - FireworkData.Vel = uv2; - // Pos = vertex; - // Timer = uv0; - // Type = uv1; - // Vel = uv2; - - // FireworkData.Pos = vertex; - // FireworkData.Timer = 1; - // FireworkData.Type = 8; - // FireworkData.Vel = vec3(3, 3, 3); -} diff --git a/Samples/Media/materials/programs/GLSL150/PassthroughGP.glsl b/Samples/Media/materials/programs/GLSL150/PassthroughGP.glsl deleted file mode 100644 index 2656766fe9a..00000000000 --- a/Samples/Media/materials/programs/GLSL150/PassthroughGP.glsl +++ /dev/null @@ -1,18 +0,0 @@ -#version 150 - -layout(triangles) in; -layout(triangle_strip, max_vertices = 3) out; - -/* - Basic pass through geometry shader for GLSL. - Assumes triangle input and output. -*/ -void main() -{ - for (int i = 0; i < gl_in.length(); i++) - { - gl_Position = gl_in[i].gl_Position; - EmitVertex(); - } - EndPrimitive(); -} diff --git a/Samples/Media/materials/programs/GLSL400/ComputeCS.glsl b/Samples/Media/materials/programs/GLSL400/ComputeCS.glsl deleted file mode 100644 index b145d161473..00000000000 --- a/Samples/Media/materials/programs/GLSL400/ComputeCS.glsl +++ /dev/null @@ -1,17 +0,0 @@ -#version 430 - -layout(binding = 0, rgba8) writeonly uniform image2D image_data; - -uniform float roll; - -layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in; - -// source/ details: http://wili.cc/blog/opengl-cs.html -void main() -{ - ivec2 storePos = ivec2(gl_GlobalInvocationID.xy); - - float localCoef = length(vec2(ivec2(gl_LocalInvocationID.xy)-8)/8.0); - float globalCoef = sin(float(gl_WorkGroupID.x+gl_WorkGroupID.y)*0.1 + roll)*0.5; - imageStore(image_data, storePos, vec4(vec2(1.0-globalCoef*localCoef),1.0,1.0)); -} diff --git a/Samples/Media/materials/programs/GLSL400/RasterizationOrderFp.glsl b/Samples/Media/materials/programs/GLSL400/RasterizationOrderFp.glsl deleted file mode 100644 index 2d170946fb2..00000000000 --- a/Samples/Media/materials/programs/GLSL400/RasterizationOrderFp.glsl +++ /dev/null @@ -1,15 +0,0 @@ -#version 400 -#extension GL_ARB_shader_storage_buffer_object : require - -buffer CounterBuffer -{ - uint ac; -}; - -out vec4 fragColour; - -void main(void) -{ - uint counter = atomicAdd(ac, 1); - fragColour = vec4(float(counter)/(480*480),0,0,1); -} diff --git a/Samples/Media/materials/programs/GLSL400/TessellationFp.glsl b/Samples/Media/materials/programs/GLSL400/TessellationFp.glsl deleted file mode 100644 index c9ab6945ec5..00000000000 --- a/Samples/Media/materials/programs/GLSL400/TessellationFp.glsl +++ /dev/null @@ -1,9 +0,0 @@ -#version 400 core - -out vec4 fragColour; - -// Fragment shader section. -void main() -{ - fragColour = vec4(1, 1, 1, 1); -} diff --git a/Samples/Media/materials/programs/GLSL400/TessellationTd.glsl b/Samples/Media/materials/programs/GLSL400/TessellationTd.glsl deleted file mode 100644 index b618a5a283b..00000000000 --- a/Samples/Media/materials/programs/GLSL400/TessellationTd.glsl +++ /dev/null @@ -1,14 +0,0 @@ -#version 400 core - -uniform mat4 g_mWorldViewProjection; - -// GLSL tessellation evaluation shader (domain shader in HLSL). -layout(triangles, equal_spacing, cw) in; -void main() -{ - // Baricentric interpolation - vec3 finalPos = vec3(gl_TessCoord.x * gl_in[0].gl_Position + - gl_TessCoord.y * gl_in[1].gl_Position + - gl_TessCoord.z * gl_in[2].gl_Position); - gl_Position = g_mWorldViewProjection * vec4(finalPos, 1.0); -} diff --git a/Samples/Media/materials/programs/GLSL400/TessellationTh.glsl b/Samples/Media/materials/programs/GLSL400/TessellationTh.glsl deleted file mode 100644 index 8fccb0f5525..00000000000 --- a/Samples/Media/materials/programs/GLSL400/TessellationTh.glsl +++ /dev/null @@ -1,14 +0,0 @@ -#version 400 core - -uniform float g_fTessellationFactor; - -// GLSL tessellation control shader. -layout (vertices = 3) out; -void main() -{ - gl_TessLevelOuter[0] = gl_TessLevelOuter[1] = gl_TessLevelOuter[2] = g_fTessellationFactor; - gl_TessLevelInner[0] = g_fTessellationFactor; - - gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position; -} - diff --git a/Samples/Media/materials/programs/GLSL400/TessellationVp.glsl b/Samples/Media/materials/programs/GLSL400/TessellationVp.glsl deleted file mode 100644 index f5bd8ceffbf..00000000000 --- a/Samples/Media/materials/programs/GLSL400/TessellationVp.glsl +++ /dev/null @@ -1,9 +0,0 @@ -#version 400 core - -in vec4 vertex; - -// Just a pass-through vertex shader. -void main() -{ - gl_Position = vertex; -} diff --git a/Samples/Media/materials/programs/GLSLES/ASCIIFP.glsles b/Samples/Media/materials/programs/GLSLES/ASCIIFP.glsles deleted file mode 100644 index da915e2555d..00000000000 --- a/Samples/Media/materials/programs/GLSLES/ASCIIFP.glsles +++ /dev/null @@ -1,40 +0,0 @@ -#version 300 es - -precision mediump int; -precision mediump float; - -in vec4 pos; -in vec2 oUv0; -out vec4 fragColour; - -uniform sampler2D RT; -uniform lowp sampler3D chars; -uniform vec2 numTiles; -uniform vec2 iNumTiles; -uniform vec2 iNumTiles2; -uniform vec4 lum; -uniform float charBias; - -void main() -{ - vec3 local; - - //sample RT - local.xy = mod(oUv0, iNumTiles); - vec2 middle = oUv0 - local.xy; - local.xy = local.xy * numTiles; - - //iNumTiles2 = iNumTiles / 2 - middle = middle + iNumTiles2; - vec4 c = texture(RT, middle); - - //multiply luminance by charbias , beacause not all slices of the ascii - //volume texture are used - local.z = dot(c , lum)*charBias; - - //fix to brighten the dark pixels with small characters - //c *= lerp(2.0,1.0, local.z); - - c *= texture(chars, local); - fragColour = c; -} diff --git a/Samples/Media/materials/programs/GLSLES/BumpMapVPTangentParity.glsles b/Samples/Media/materials/programs/GLSLES/BumpMapVPTangentParity.glsles deleted file mode 100644 index 66ba3667563..00000000000 --- a/Samples/Media/materials/programs/GLSLES/BumpMapVPTangentParity.glsles +++ /dev/null @@ -1,49 +0,0 @@ -#version 100 -precision mediump int; -precision mediump float; - -/* Bump mapping vertex program - In this program, we want to calculate the tangent space light vector - on a per-vertex level which will get passed to the fragment program, - or to the fixed function dot3 operation, to produce the per-pixel - lighting effect. -*/ -// parameters -uniform vec4 lightPosition; // object space -uniform mat4 worldViewProj; - -attribute vec4 vertex; -attribute vec3 normal; -attribute vec4 tangent; -attribute vec2 uv0; - -varying vec2 oUv0; -varying vec3 oTSLightDir; - -void main() -{ - // Calculate output position - gl_Position = worldViewProj * vertex; - - // Pass the main uvs straight through unchanged - oUv0 = uv0; - - // Calculate tangent space light vector - // Get object space light direction - // Non-normalised since we'll do that in the fragment program anyway - vec3 lightDir = lightPosition.xyz - (vertex * lightPosition.w).xyz; - - // Calculate the binormal (NB we assume both normal and tangent are - // already normalised) - - // Fixed handedness - vec3 binormal = cross(normal, tangent.xyz) * tangent.www; - - // Form a rotation matrix out of the vectors, column major for glsl es - mat3 rotation = mat3(vec3(tangent[0], binormal[0], normal[0]), - vec3(tangent[1], binormal[1], normal[1]), - vec3(tangent[2], binormal[2], normal[2])); - - // Transform the light vector according to this matrix - oTSLightDir = rotation * lightDir; -} diff --git a/Samples/Media/materials/programs/GLSLES/Example_BumpMappingShadowRcvFp.glsles b/Samples/Media/materials/programs/GLSLES/Example_BumpMappingShadowRcvFp.glsles deleted file mode 100644 index 0b179e8b89f..00000000000 --- a/Samples/Media/materials/programs/GLSLES/Example_BumpMappingShadowRcvFp.glsles +++ /dev/null @@ -1,34 +0,0 @@ -#version 100 -precision mediump int; -precision mediump float; - -// General functions - -// Expand a range-compressed vector -vec3 expand(vec3 v) -{ - return (v - 0.5) * 2.0; -} - -uniform sampler2D shadowMap; -uniform sampler2D normalMap; -uniform vec4 lightDiffuse; - -varying vec4 uvproj; -varying vec4 oUv0; -varying vec3 oTSLightDir; - -void main() -{ - // retrieve normalised light vector, expand from range-compressed - vec3 lightVec = expand(normalize(oTSLightDir).xyz); - - // get bump map vector, again expand from range-compressed - vec3 bumpVec = expand(texture2D(normalMap, oUv0.xy).xyz); - - // get shadow value - vec3 shadow = texture2DProj(shadowMap, uvproj).xyz; - - // Calculate dot product - gl_FragColor = vec4(shadow * lightDiffuse.xyz * dot(bumpVec, lightVec), 1.0); -} diff --git a/Samples/Media/materials/programs/GLSLES/Example_BumpMappingShadowRcvVp.glsles b/Samples/Media/materials/programs/GLSLES/Example_BumpMappingShadowRcvVp.glsles deleted file mode 100644 index a190196d920..00000000000 --- a/Samples/Media/materials/programs/GLSLES/Example_BumpMappingShadowRcvVp.glsles +++ /dev/null @@ -1,54 +0,0 @@ -#version 100 -precision mediump int; -precision mediump float; - -/* Bump mapping vertex program for shadow receiving - In this program, we want to calculate the tangent space light vector - on a per-vertex level which will get passed to the fragment program, - or to the fixed function dot3 operation, to produce the per-pixel - lighting effect. -*/ - -// parameters -uniform vec4 lightPosition; // object space -uniform mat4 worldViewProj; -uniform mat4 worldMatrix; -uniform mat4 texViewProj; - -attribute vec4 vertex; -attribute vec3 normal; -attribute vec3 tangent; -attribute vec4 uv0; - -varying vec4 uvproj; -varying vec4 oUv0; -varying vec3 oTSLightDir; - -void main() -{ - // Calculate output position - gl_Position = worldViewProj * vertex; - - // Pass the main uvs straight through unchanged - oUv0 = uv0; - - // Calculate tangent space light vector - // Get object space light direction - // Non-normalised since we'll do that in the fragment program anyway - vec3 lightDir = lightPosition.xyz - (vertex * lightPosition.w).xyz; - - // Calculate the binormal (NB we assume both normal and tangent are - // already normalised) - vec3 binormal = cross(normal, tangent); - - // Form a rotation matrix out of the vectors, column major for glsl es - mat3 rotation = mat3(vec3(tangent[0], binormal[0], normal[0]), - vec3(tangent[1], binormal[1], normal[1]), - vec3(tangent[2], binormal[2], normal[2])); - - // Transform the light vector according to this matrix - oTSLightDir = rotation * lightDir; - - // Projection - uvproj = texViewProj * (worldMatrix * vertex); -} diff --git a/Samples/Media/materials/programs/GLSLES/Example_CelShadingFp.glsles b/Samples/Media/materials/programs/GLSLES/Example_CelShadingFp.glsles deleted file mode 100644 index db311e55acc..00000000000 --- a/Samples/Media/materials/programs/GLSLES/Example_CelShadingFp.glsles +++ /dev/null @@ -1,25 +0,0 @@ -#version 100 -precision mediump int; -precision mediump float; - -/* Cel shading fragment program for single-pass rendering */ -uniform vec4 diffuse; -uniform vec4 specular; -uniform sampler2D diffuseRamp; -uniform sampler2D specularRamp; -uniform sampler2D edgeRamp; - -varying float diffuseIn; -varying float specularIn; -varying float edge; - -void main() -{ - // Step functions from textures - vec4 diffuseStep = texture2D(diffuseRamp, vec2(diffuseIn)); - vec4 specularStep = texture2D(specularRamp, vec2(specularIn)); - vec4 edgeStep = texture2D(edgeRamp, vec2(edge)); - - gl_FragColor = edgeStep.x * ((diffuse * diffuseStep.x) + - (specular * specularStep.x)); -} diff --git a/Samples/Media/materials/programs/GLSLES/Example_CelShadingVp.glsles b/Samples/Media/materials/programs/GLSLES/Example_CelShadingVp.glsles deleted file mode 100644 index c37b738ec46..00000000000 --- a/Samples/Media/materials/programs/GLSLES/Example_CelShadingVp.glsles +++ /dev/null @@ -1,50 +0,0 @@ -#version 100 -precision mediump int; -precision mediump float; - -/* Cel shading vertex program for single-pass rendering - In this program, we want to calculate the diffuse and specular - ramp components, and the edge factor (for doing simple outlining) - For the outlining to look good, we need a pretty well curved model. -*/ -// Parameters -attribute vec4 vertex; -attribute vec3 normal; - -uniform vec3 lightPosition; // object space -uniform vec3 eyePosition; // object space -uniform vec4 shininess; -uniform mat4 worldViewProj; - -varying float diffuseIn; -varying float specularIn; -varying float edge; - -void main() -{ - // calculate output position - gl_Position = worldViewProj * vertex; - - // calculate light vector - vec3 N = normalize(normal); - vec3 L = normalize(lightPosition - vertex.xyz); - vec3 E = normalize(eyePosition - vertex.xyz); - - // Calculate diffuse component - diffuseIn = max(dot(N, L) , 0.0); - - // Mask off specular if diffuse is 0 - if (diffuseIn == 0.0) - { - specularIn = 0.0; - } - else - { - // Calculate specular component - vec3 H = normalize(L + E); - specularIn = pow(max(dot(N, H), 0.0), shininess.x); - } - - // Edge detection, dot eye and normal vectors - edge = max(dot(N, E), 0.0); -} diff --git a/Samples/Media/materials/programs/GLSLES/Example_ProjectionFp.glsles b/Samples/Media/materials/programs/GLSLES/Example_ProjectionFp.glsles deleted file mode 100644 index 20fd2bd22b7..00000000000 --- a/Samples/Media/materials/programs/GLSLES/Example_ProjectionFp.glsles +++ /dev/null @@ -1,56 +0,0 @@ - -void generalPurposeProjection_vp( - float4 pos : POSITION, - - out float4 oPos : POSITION, - out float4 texCoord : TEXCOORD0, - - uniform float4x4 worldViewProjMatrix, - uniform float4x4 worldMatrix, - uniform float4x4 texViewProjMatrix) -{ - oPos = mul(worldViewProjMatrix, pos); - // multiply position by world matrix, then by projective view/proj - float4 newpos = mul(worldMatrix, pos); - texCoord = mul(texViewProjMatrix, newpos); - -} - -void generalPurposeProjection_fp( - float4 texCoord : TEXCOORD0, - out float4 col : COLOR, - uniform sampler2D texMap) -{ - col = tex2Dproj(texMap, texCoord); - -} - - - -void generalPurposeProjection_vp( - float4 pos : POSITION, - - out float4 oPos : POSITION, - out float4 texCoord : TEXCOORD0, - - uniform float4x4 worldViewProjMatrix, - uniform float4x4 worldMatrix, - uniform float4x4 texViewProjMatrix) -{ - oPos = mul(worldViewProjMatrix, pos); - // multiply position by world matrix, then by projective view/proj - float4 newpos = mul(worldMatrix, pos); - texCoord = mul(texViewProjMatrix, newpos); - -} - -void generalPurposeProjection_fp( - float4 texCoord : TEXCOORD0, - out float4 col : COLOR, - uniform sampler2D texMap) -{ - col = tex2Dproj(texMap, texCoord); - -} - - diff --git a/Samples/Media/materials/programs/GLSLES/Example_ProjectionVp.glsles b/Samples/Media/materials/programs/GLSLES/Example_ProjectionVp.glsles deleted file mode 100644 index 095109475df..00000000000 --- a/Samples/Media/materials/programs/GLSLES/Example_ProjectionVp.glsles +++ /dev/null @@ -1,26 +0,0 @@ - -void generalPurposeProjection_vp( - float4 pos : POSITION, - - out float4 oPos : POSITION, - out float4 texCoord : TEXCOORD0, - - uniform float4x4 worldViewProjMatrix, - uniform float4x4 worldMatrix, - uniform float4x4 texViewProjMatrix) -{ - oPos = mul(worldViewProjMatrix, pos); - // multiply position by world matrix, then by projective view/proj - float4 newpos = mul(worldMatrix, pos); - texCoord = mul(texViewProjMatrix, newpos); -} - -void generalPurposeProjection_fp( - float4 texCoord : TEXCOORD0, - out float4 col : COLOR, - uniform sampler2D texMap) -{ - col = tex2Dproj(texMap, texCoord); -} - - diff --git a/Samples/Media/materials/programs/GLSLES/Example_TextureArrayPS.glsles b/Samples/Media/materials/programs/GLSLES/Example_TextureArrayPS.glsles deleted file mode 100644 index 4d8e06edd93..00000000000 --- a/Samples/Media/materials/programs/GLSLES/Example_TextureArrayPS.glsles +++ /dev/null @@ -1,20 +0,0 @@ -#version 300 es - -precision mediump int; -precision mediump float; - -uniform lowp sampler2DArray TextureArrayTex; -in vec4 oUv; -out vec4 fragColour; - -void main(void) -{ - vec4 texcoord; - texcoord = oUv; - texcoord.z = floor(texcoord.z); - vec4 c0 = texture(TextureArrayTex, texcoord.xyz); - texcoord.z += 1.0; - vec4 c1 = texture(TextureArrayTex, texcoord.xyz); - - fragColour = mix(c0, c1, fract(oUv.z)); -} diff --git a/Samples/Media/materials/programs/GLSLES/HW_VTFInstancing.vert b/Samples/Media/materials/programs/GLSLES/HW_VTFInstancing.vert deleted file mode 100644 index 2b0c8ab3bf0..00000000000 --- a/Samples/Media/materials/programs/GLSLES/HW_VTFInstancing.vert +++ /dev/null @@ -1,133 +0,0 @@ -//--------------------------------------------------------------------------- -//These materials/shaders are part of the NEW InstanceManager implementation -//Written by Matias N. Goldberg ("dark_sylinc") -//--------------------------------------------------------------------------- -#version 300 es -precision mediump int; -precision mediump float; - -//Vertex input -in vec4 vertex; -in vec3 normal; - -#ifdef BONE_TWO_WEIGHTS - in vec4 blendWeights; -#endif - -in vec4 uv0; -in vec4 uv1; -in vec4 uv2; - -#if BONE_MATRIX_LUT - in vec4 uv3; - in vec4 uv4; - in vec4 uv5; -#endif - -in vec3 tangent; - -//Parameters -uniform mat4 viewProjMatrix; -uniform sampler2D matrixTexture; - -#if (DEPTH_SHADOWCASTER || DEPTH_SHADOWRECEIVER) -uniform vec4 depthRange; -#endif - -#if DEPTH_SHADOWRECEIVER -uniform mat4 texViewProjMatrix; -#endif - -//Output -#if DEPTH_SHADOWCASTER - out vec2 depth; -#else - out vec2 _uv0; - out vec3 oNormal; - out vec3 oVPos; - #if DEPTH_SHADOWRECEIVER - out vec4 oLightSpacePos; - #endif -#endif - -vec3 calculateBlendPosition(vec3 position, mat2x4 blendDQ) -{ - vec3 blendPosition = position + 2.0*cross(blendDQ[0].yzw, cross(blendDQ[0].yzw, position) + blendDQ[0].x*position); - vec3 trans = 2.0*(blendDQ[0].x*blendDQ[1].yzw - blendDQ[1].x*blendDQ[0].yzw + cross(blendDQ[0].yzw, blendDQ[1].yzw)); - blendPosition += trans; - - return blendPosition; -} - -vec3 calculateBlendNormal(vec3 normal, mat2x4 blendDQ) -{ - return normal + 2.0*cross(blendDQ[0].yzw, cross(blendDQ[0].yzw, normal) + blendDQ[0].x*normal); -} - -//--------------------------------------------- -//Main Vertex Shader -//--------------------------------------------- -void main(void) -{ - vec4 worldPos; - vec3 worldNorm; - -#ifdef ST_DUAL_QUATERNION - mat2x4 blendDQ; - blendDQ[0] = texture( matrixTexture, vec2(uv1.x, 0.0) + uv2.xy ); - blendDQ[1] = texture( matrixTexture, vec2(uv1.y, 0.0) + uv2.xy ); -#ifdef BONE_TWO_WEIGHTS - mat2x4 blendDQ2; - blendDQ2[0] = texture( matrixTexture, vec2(uv1.z, 0.0) + uv2.xy ); - blendDQ2[1] = texture( matrixTexture, vec2(uv1.w, 0.0) + uv2.xy ); - - //Accurate antipodality handling. For speed increase, remove the following line - if (dot(blendDQ[0], blendDQ2[0]) < 0.0) blendDQ2 *= -1.0; - - //Blend the dual quaternions based on the weights - blendDQ *= blendWeights.x; - blendDQ += blendWeights.y*blendDQ2; - //Normalize the resultant dual quaternion - blendDQ /= length(blendDQ[0]); -#endif - worldPos = vec4(calculateBlendPosition(vertex.xyz, blendDQ), 1.0); - worldNorm = calculateBlendNormal(normal, blendDQ); -#else - mat4 worldMatrix; - worldMatrix[0] = texture( matrixTexture, uv1.xw + uv2.xy ); - worldMatrix[1] = texture( matrixTexture, uv1.yw + uv2.xy ); - worldMatrix[2] = texture( matrixTexture, uv1.zw + uv2.xy ); - worldMatrix[3] = vec4( 0, 0, 0, 1 ); - - worldPos = vertex * worldMatrix; - worldNorm = normal * mat3(worldMatrix); -#endif - -#if BONE_MATRIX_LUT - mat4 worldCompMatrix; - worldCompMatrix[0] = uv3; - worldCompMatrix[1] = uv4; - worldCompMatrix[2] = uv5; - worldCompMatrix[3] = vec4( 0, 0, 0, 1 ); - - worldPos = worldPos * worldCompMatrix; - worldNorm = worldNorm * mat3(worldCompMatrix); -#endif - - //Transform the position - gl_Position = viewProjMatrix * worldPos; - -#if DEPTH_SHADOWCASTER - depth.x = (gl_Position.z - depthRange.x) * depthRange.w; - depth.y = depthRange.w; -#else - _uv0 = uv0.xy; - oNormal = worldNorm; - oVPos = worldPos.xyz; - - #if DEPTH_SHADOWRECEIVER - oLightSpacePos = texViewProjMatrix * worldPos; - oLightSpacePos.z = (oLightSpacePos.z - depthRange.x) * depthRange.w; - #endif -#endif -} diff --git a/Samples/Media/materials/programs/GLSLES/HalftoneFP.glsles b/Samples/Media/materials/programs/GLSLES/HalftoneFP.glsles deleted file mode 100644 index 05b3392f048..00000000000 --- a/Samples/Media/materials/programs/GLSLES/HalftoneFP.glsles +++ /dev/null @@ -1,28 +0,0 @@ -#version 300 es - -precision mediump int; -precision mediump float; - -in vec4 pos; -in vec2 oUv0; - -uniform vec2 numTiles; -uniform vec2 iNumTiles; -uniform vec2 iNumTiles2; -uniform vec4 lum; -uniform sampler2D RT; -uniform lowp sampler3D noise; - -out vec4 fragColour; - -void main() -{ - vec3 local; - local.xy = mod(oUv0, iNumTiles); - vec2 middle = oUv0 - local.xy; - local.xy = local.xy * numTiles; - middle += iNumTiles2; - local.z = dot(texture(RT, middle), lum); - vec4 c = vec4(texture(noise,local).r); - fragColour = c; -} diff --git a/Samples/Media/materials/programs/GLSLES/Instancing.frag b/Samples/Media/materials/programs/GLSLES/Instancing.frag deleted file mode 100644 index c788671fd74..00000000000 --- a/Samples/Media/materials/programs/GLSLES/Instancing.frag +++ /dev/null @@ -1,72 +0,0 @@ -//--------------------------------------------------------------------------- -//These materials/shaders are part of the NEW InstanceManager implementation -//Written by Matias N. Goldberg ("dark_sylinc") -//--------------------------------------------------------------------------- - -#version 300 es - -precision mediump int; -precision mediump float; - -uniform sampler2D diffuseMap; - -uniform vec4 lightPosition; -uniform vec3 cameraPosition; -uniform vec3 lightAmbient; -uniform vec3 lightDiffuse; -uniform vec3 lightSpecular; -uniform vec4 lightAttenuation; -uniform float lightGloss; - -#if DEPTH_SHADOWRECEIVER -uniform float invShadowMapSize; -uniform lowp sampler2D shadowMap; - -#define texture2D texture -#define texture2DProj textureProj -#include "TerrainHelpers.glsl" -#endif - -in vec2 _uv0; -in vec3 oNormal; -in vec3 oVPos; -#if DEPTH_SHADOWRECEIVER - in vec4 oLightSpacePos; -#endif -out vec4 fragColour; - -//--------------------------------------------- -//Main Pixel Shader -//--------------------------------------------- -void main(void) -{ - vec4 color = texture( diffuseMap, _uv0 ); - - float fShadow = 1.0; -#if DEPTH_SHADOWRECEIVER - fShadow = calcDepthShadow( shadowMap, oLightSpacePos, invShadowMapSize ); -#endif - - vec4 baseColour = texture( diffuseMap, _uv0 ); - - //Blinn-Phong lighting - vec3 normal = normalize( oNormal ); - vec3 lightDir = lightPosition.xyz - oVPos * lightPosition.w; - vec3 eyeDir = normalize( cameraPosition - oVPos ); - - float fLength = length( lightDir ); - lightDir = normalize( lightDir ); - - float NdotL = max( 0.0, dot( normal, lightDir ) ); - vec3 halfVector = normalize(lightDir + eyeDir); - float HdotN = max( 0.0, dot( halfVector, normal ) ); - - vec3 ambient = lightAmbient * baseColour.xyz; - vec3 diffuse = lightDiffuse * NdotL * baseColour.xyz; - vec3 specular = lightSpecular * pow( HdotN, lightGloss ); - - vec3 directLighting = (diffuse + specular) * fShadow; - - fragColour = vec4( directLighting + ambient, baseColour.a ); - //fragColour = baseColour; -} diff --git a/Samples/Media/materials/programs/GLSLES/NightVisionFP.glsles b/Samples/Media/materials/programs/GLSLES/NightVisionFP.glsles deleted file mode 100644 index 99bce7bc2f9..00000000000 --- a/Samples/Media/materials/programs/GLSLES/NightVisionFP.glsles +++ /dev/null @@ -1,34 +0,0 @@ -#version 300 es -precision mediump int; -precision mediump float; - -out vec4 fragColour; - -uniform sampler2D RT; -uniform lowp sampler3D noiseVol; - -in vec2 oUv0; -uniform vec4 lum; -uniform float time; - -void main() -{ - vec4 oC; - oC = texture(RT, oUv0); - - //obtain luminence value - oC = vec4(dot(oC,lum)); - - //add some random noise - oC += 0.2 *(texture(noiseVol, vec3(oUv0*5.0,time)))- 0.05; - - //add lens circle effect - //(could be optimised by using texture) - float dist = distance(oUv0, vec2(0.5,0.5)); - oC *= smoothstep(0.5,0.45,dist); - - //add rb to the brightest pixels - oC.rb = vec2(max(oC.r - 0.75, 0.0)*4.0); - - fragColour = oC; -} diff --git a/Samples/Media/materials/programs/GLSLES/OldMovieFP.glsles b/Samples/Media/materials/programs/GLSLES/OldMovieFP.glsles deleted file mode 100644 index 8ad32346a66..00000000000 --- a/Samples/Media/materials/programs/GLSLES/OldMovieFP.glsles +++ /dev/null @@ -1,58 +0,0 @@ -#version 100 - -precision mediump int; -precision mediump float; - -varying vec2 oUv0; -//varying vec2 uv1; - -uniform sampler2D RT; -uniform sampler2D SplotchesTx; -uniform sampler2D Texture2; -uniform sampler2D SepiaTx; -uniform float time_cycle_period; -uniform float flicker; -uniform float DirtFrequency; -uniform vec3 luminance; -uniform float frameJitter; -uniform float lumiShift; - -vec2 calcSpriteAddr(vec2 texCoord, float DirtFrequency1, float period) -{ - return texCoord + texture2D(Texture2, vec2(period * DirtFrequency1, 0.0)).xy; -} - -vec4 getSplotches(vec2 spriteAddr) -{ - // get sprite address into paged texture coords space - spriteAddr = spriteAddr / 6.3; - spriteAddr = spriteAddr - (spriteAddr / 33.3); - - return texture2D(SplotchesTx, spriteAddr); -} - -void main() -{ - // get sprite address - vec2 spriteAddr = calcSpriteAddr(oUv0, DirtFrequency, time_cycle_period); - - // add some dark and light splotches to the film - vec4 splotches = getSplotches(spriteAddr); - vec4 specs = 1.0 - getSplotches(spriteAddr / 3.0); - - // convert color to base luminance - vec4 base = texture2D(RT, oUv0 + vec2(0.0, spriteAddr.y * frameJitter)); - float lumi = dot(base.rgb, luminance); - // randomly shift luminance - lumi -= spriteAddr.x * lumiShift; - // tone map luminance - base.rgb = texture2D(SepiaTx, vec2(lumi, 0.0)).rgb; - - // calc flicker speed - float darken = fract(flicker * time_cycle_period); - - // we want darken to cycle between 0.6 and 1.0 - darken = abs(darken - 0.5) * 0.4 + 0.6; - // composite dirt onto film - gl_FragColor = base * splotches * darken + specs; -} diff --git a/Samples/Media/materials/programs/GLSLES/OldTV.glsles b/Samples/Media/materials/programs/GLSLES/OldTV.glsles deleted file mode 100644 index abd782fe550..00000000000 --- a/Samples/Media/materials/programs/GLSLES/OldTV.glsles +++ /dev/null @@ -1,49 +0,0 @@ -#version 300 es - -precision mediump int; -precision mediump float; - -in vec4 pos; -in vec2 oUv0; -out vec4 fragColour; - -uniform sampler2D Image; -uniform lowp sampler3D Rand; -uniform lowp sampler3D Noise; -uniform float distortionFreq; -uniform float distortionScale; -uniform float distortionRoll; -uniform float interference; -uniform float frameLimit; -uniform float frameShape; -uniform float frameSharpness; -uniform float time_0_X; -uniform float sin_time_0_X; - -void main() -{ - // Define a frame shape - float f = (1.0 - pos.x * pos.x) * (1.0 - pos.y * pos.y); - float frame = clamp(frameSharpness * (pow(f, frameShape) - frameLimit), 0.0, 1.0); - - // Interference ... just a texture filled with rand() - float rand = texture(Rand, vec3(1.5 * pos.x, 1.5 * pos.y, time_0_X)).x - 0.2; - - // Some signed noise for the distortion effect - float noisy = texture(Noise, vec3(0, 0.5 * pos.y, 0.1 * time_0_X)).x - 0.5; - - // Repeat a 1 - x^2 (0 < x < 1) curve and roll it with sinus. - float dst = fract(pos.y * distortionFreq + distortionRoll * sin_time_0_X); - dst *= (1.0 - dst); - // Make sure distortion is highest in the center of the image - dst /= 1.0 + distortionScale * abs(pos.y); - - // ... and finally distort - vec2 inUv = oUv0; - inUv.x += distortionScale * noisy * dst; - vec4 image = texture(Image, inUv); - - // Combine frame, distorted image and interference - fragColour = frame * (interference * rand + image); -} - diff --git a/Samples/Media/materials/programs/GLSLES/SwizzleGP.glsles b/Samples/Media/materials/programs/GLSLES/SwizzleGP.glsles deleted file mode 100644 index 4dff5df2a47..00000000000 --- a/Samples/Media/materials/programs/GLSLES/SwizzleGP.glsles +++ /dev/null @@ -1,80 +0,0 @@ -#version 120 -#extension GL_EXT_geometry_shader4 : enable - -uniform vec4 origColor; -uniform vec4 cloneColor; - -void main(void) -{ - - //increment variable - int i; - - ///////////////////////////////////////////////////////////// - //This example has two parts - // step a) draw the primitive pushed down the pipeline - // there are gl_Vertices # of vertices - // put the vertex value into gl_Position - // use EmitVertex => 'create' a new vertex - // use EndPrimitive to signal that you are done creating a primitive! - // step b) create a new piece of geometry (I.E. WHY WE ARE USING A GEOMETRY SHADER!) - // I just do the same loop, but swizzle the x and y values - // result => the line we want to draw, and the same line, but along the other axis - - //Pass-thru! - for(i=0; i< gl_VerticesIn; i++){ - gl_Position = gl_PositionIn[i]; - gl_FrontColor = origColor; - EmitVertex(); - } - EndPrimitive(); - //New piece of geometry! We just swizzle the x and y terms - for(i=0; i< gl_VerticesIn; i++){ - gl_Position = gl_PositionIn[i]; - gl_Position.xy = gl_Position.yx; - gl_FrontColor = cloneColor; - EmitVertex(); - } - EndPrimitive(); - -} -#version 120 -#extension GL_EXT_geometry_shader4 : enable - -uniform vec4 origColor; -uniform vec4 cloneColor; - -void main(void) -{ - - //increment variable - int i; - - ///////////////////////////////////////////////////////////// - //This example has two parts - // step a) draw the primitive pushed down the pipeline - // there are gl_Vertices # of vertices - // put the vertex value into gl_Position - // use EmitVertex => 'create' a new vertex - // use EndPrimitive to signal that you are done creating a primitive! - // step b) create a new piece of geometry (I.E. WHY WE ARE USING A GEOMETRY SHADER!) - // I just do the same loop, but swizzle the x and y values - // result => the line we want to draw, and the same line, but along the other axis - - //Pass-thru! - for(i=0; i< gl_VerticesIn; i++){ - gl_Position = gl_PositionIn[i]; - gl_FrontColor = origColor; - EmitVertex(); - } - EndPrimitive(); - //New piece of geometry! We just swizzle the x and y terms - for(i=0; i< gl_VerticesIn; i++){ - gl_Position = gl_PositionIn[i]; - gl_Position.xy = gl_Position.yx; - gl_FrontColor = cloneColor; - EmitVertex(); - } - EndPrimitive(); - -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/GLSLES/VTFInstancing.vert b/Samples/Media/materials/programs/GLSLES/VTFInstancing.vert deleted file mode 100644 index fef11993bef..00000000000 --- a/Samples/Media/materials/programs/GLSLES/VTFInstancing.vert +++ /dev/null @@ -1,115 +0,0 @@ -//--------------------------------------------------------------------------- -//These materials/shaders are part of the NEW InstanceManager implementation -//Written by Matias N. Goldberg ("dark_sylinc") -//--------------------------------------------------------------------------- -#version 300 es -precision mediump int; -precision mediump float; - -//Vertex input -in vec4 vertex; -in vec3 normal; - -#ifdef BONE_TWO_WEIGHTS - in vec4 blendWeights; -#endif - -in vec4 uv0; -in vec4 uv1; -in vec4 uv2; -in vec3 tangent; - -//Parameters -uniform mat4 viewProjMatrix; -uniform sampler2D matrixTexture; - -#if (DEPTH_SHADOWCASTER || DEPTH_SHADOWRECEIVER) -uniform vec4 depthRange; -#endif - -#if DEPTH_SHADOWRECEIVER -uniform mat4 texViewProjMatrix; -#endif - -//Output -#if DEPTH_SHADOWCASTER - out vec2 depth; -#else - out vec2 _uv0; - out vec3 oNormal; - out vec3 oVPos; - #if DEPTH_SHADOWRECEIVER - out vec4 oLightSpacePos; - #endif -#endif - -vec3 calculateBlendPosition(vec3 position, mat2x4 blendDQ) -{ - vec3 blendPosition = position + 2.0*cross(blendDQ[0].yzw, cross(blendDQ[0].yzw, position) + blendDQ[0].x*position); - vec3 trans = 2.0*(blendDQ[0].x*blendDQ[1].yzw - blendDQ[1].x*blendDQ[0].yzw + cross(blendDQ[0].yzw, blendDQ[1].yzw)); - blendPosition += trans; - - return blendPosition; -} - -vec3 calculateBlendNormal(vec3 normal, mat2x4 blendDQ) -{ - return normal + 2.0*cross(blendDQ[0].yzw, cross(blendDQ[0].yzw, normal) + blendDQ[0].x*normal); -} - -//--------------------------------------------- -//Main Vertex Shader -//--------------------------------------------- -void main(void) -{ - vec4 worldPos; - vec3 worldNorm; - -#ifdef ST_DUAL_QUATERNION - mat2x4 blendDQ; - blendDQ[0] = texture( matrixTexture, uv1.xy ); - blendDQ[1] = texture( matrixTexture, uv1.zy ); -#ifdef BONE_TWO_WEIGHTS - mat2x4 blendDQ2; - blendDQ2[0] = texture( matrixTexture, uv2.xy ); - blendDQ2[1] = texture( matrixTexture, uv2.zw ); - - //Accurate antipodality handling. For speed increase, remove the following line - if (dot(blendDQ[0], blendDQ2[0]) < 0.0) blendDQ2 *= -1.0; - - //Blend the dual quaternions based on the weights - blendDQ *= blendWeights.x; - blendDQ += blendWeights.y*blendDQ2; - //Normalize the resultant dual quaternion - blendDQ /= length(blendDQ[0]); -#endif - worldPos = vec4(calculateBlendPosition(vertex.xyz, blendDQ), 1.0); - worldNorm = calculateBlendNormal(normal, blendDQ); -#else - mat4 worldMatrix; - worldMatrix[0] = texture( matrixTexture, uv1.xy ); - worldMatrix[1] = texture( matrixTexture, uv1.zw ); - worldMatrix[2] = texture( matrixTexture, uv2.xy ); - worldMatrix[3] = vec4( 0, 0, 0, 1 ); - - worldPos = vertex * worldMatrix; - worldNorm = normal * mat3(worldMatrix); -#endif - - //Transform the position - gl_Position = viewProjMatrix * worldPos; - -#if DEPTH_SHADOWCASTER - depth.x = (gl_Position.z - depthRange.x) * depthRange.w; - depth.y = depthRange.w; -#else - _uv0 = uv0.xy; - oNormal = worldNorm; - oVPos = worldPos.xyz; - - #if DEPTH_SHADOWRECEIVER - oLightSpacePos = texViewProjMatrix * worldPos; - oLightSpacePos.z = (oLightSpacePos.z - depthRange.x) * depthRange.w; - #endif -#endif -} diff --git a/Samples/Media/materials/programs/GLSLES/hdrFp.glsles b/Samples/Media/materials/programs/GLSLES/hdrFp.glsles deleted file mode 100644 index 854dd00442c..00000000000 --- a/Samples/Media/materials/programs/GLSLES/hdrFp.glsles +++ /dev/null @@ -1,15 +0,0 @@ -#version 100 - -precision mediump int; -precision mediump float; - -uniform sampler2D tex; -varying vec4 ambientUV; - -void main () -{ - gl_FragColor = vec4(texture2D(tex, ambientUV.xy)); - - // Blow out the light a bit - gl_FragColor *= 1.7; -} diff --git a/Samples/Media/materials/programs/GLSLES/instancingVp.glsles b/Samples/Media/materials/programs/GLSLES/instancingVp.glsles deleted file mode 100644 index bdc2f89316a..00000000000 --- a/Samples/Media/materials/programs/GLSLES/instancingVp.glsles +++ /dev/null @@ -1,44 +0,0 @@ -#version 100 - -precision highp int; -precision highp float; - -uniform mat4 worldMatrixArray[80]; -uniform mat4 viewProjectionMatrix; -uniform vec4 lightPos; -uniform vec4 ambient; -uniform vec4 lightDiffuseColour; - -attribute vec4 position; -attribute vec3 normal; -attribute vec4 uv0; -attribute float uv1; - -varying vec4 oColor_0; -#if SHADOW_CASTER -#else -varying vec2 oTexcoord2_0; -#endif - -void main() -{ - // transform by indexed matrix - vec4 transformedPos = vec4((worldMatrixArray[int(uv1)] * position).xyz, 1.0); - - // view / projection - gl_Position = viewProjectionMatrix * transformedPos; - -#if SHADOW_CASTER - - oColor_0 = ambient; -#else - oTexcoord2_0 = uv0.xy; - - vec3 norm = mat3(worldMatrixArray[int(uv1)]) * normal; - - vec3 lightDir = normalize( - lightPos.xyz - (transformedPos.xyz * lightPos.w)); - - oColor_0 = ambient + clamp(dot(lightDir, norm), 0.0, 1.0) * lightDiffuseColour; -#endif -} diff --git a/Samples/Media/materials/programs/GLSLES/mrttestfp_quad.glsles b/Samples/Media/materials/programs/GLSLES/mrttestfp_quad.glsles deleted file mode 100644 index 6b7a3de3160..00000000000 --- a/Samples/Media/materials/programs/GLSLES/mrttestfp_quad.glsles +++ /dev/null @@ -1,20 +0,0 @@ -#version 100 -precision mediump int; -precision mediump float; - -uniform sampler2D rt0; -uniform sampler2D rt1; -uniform sampler2D rt2; -uniform sampler2D rt3; - -varying vec2 uv; - -void main(void) -{ - - //gl_FragColor = texture2D(rt0, uv); - gl_FragColor = texture2D(rt1, uv); - //gl_FragColor = texture2D(rt2, uv); - //gl_FragColor = texture2D(rt3, uv); - -} diff --git a/Samples/Media/materials/programs/GLSLES/mrttestfp_scene.glsles b/Samples/Media/materials/programs/GLSLES/mrttestfp_scene.glsles deleted file mode 100644 index db55ef3cc8e..00000000000 --- a/Samples/Media/materials/programs/GLSLES/mrttestfp_scene.glsles +++ /dev/null @@ -1,21 +0,0 @@ -#version 100 -precision mediump int; -precision mediump float; - -uniform sampler2D tex0; -varying vec4 uv0; - -void main() -{ - vec4 baseColour = texture2D(tex0, uv0.xy); - - gl_FragData[0] = baseColour; - -// gl_FragData[1] = baseColour * vec4(1, 0, 0, 1); - -// float abs = (baseColour.r + baseColour.g + baseColour.b) * 0.333; -// gl_FragData[2] = vec4(abs, abs, abs, 1); - -// float invabs = 1.0 - abs; -// gl_FragData[3] = vec4(invabs, invabs, invabs, 1); -} diff --git a/Samples/Media/materials/programs/GLSLES/varianceshadowcasterfp.glsles b/Samples/Media/materials/programs/GLSLES/varianceshadowcasterfp.glsles deleted file mode 100644 index 028fd039230..00000000000 --- a/Samples/Media/materials/programs/GLSLES/varianceshadowcasterfp.glsles +++ /dev/null @@ -1,132 +0,0 @@ -///////////////////////////////////////////////////////////////////////////////// -// -// varianceshadowcasterfp.glsles -// -// Hamilton Chong -// (c) 2006 -// GLSL ES by David Rogers -// -// This is an example fragment shader for shadow caster objects. -// -///////////////////////////////////////////////////////////////////////////////// - - -// Define outputs from vertex shader. -struct VertexOut -{ - float4 position : POSITION; // can't rely on access to this - float4 pos : TEXCOORD0; // position of fragment (in homogeneous coordinates) - float4 normal : TEXCOORD1; // un-normalized normal in object space - float4 modelPos : TEXCOORD2; // coordinates of model in object space at this point -}; - -struct FragmentOut -{ - float4 color : COLOR0; -}; - -FragmentOut main( VertexOut In, // fragment to process - uniform float uDepthOffset, // offset amount (constant in eye space) - uniform float4x4 uProjection // projection matrix - ) -{ - FragmentOut Out; - - // compute the "normalized device coordinates" (no viewport applied yet) - float4 postproj = In.pos / In.pos.w; - - // get the normalized normal of the geometry seen at this point - float4 normal = normalize(In.normal); - - - // -- Computing Depth Bias Quantities ----------------------------- - - // We now compute the change in z that would signify a push in the z direction - // by 1 unit in eye space. Note that eye space z is related in a nonlinear way to - // screen space z, so this is not just a constant. - // ddepth below is how much screen space z at this point would change for that push. - // NOTE: computation of ddepth likely differs from OpenGL's glPolygonOffset "unit" - // computation, which is allowed to be vendor specific. - float4 dpwdz = mul(uProjection, float4(0.0, 0.0, 1.0, 0.0)); - float4 dpdz = (dpwdz - (postproj * dpwdz.w)) / In.pos.w; - float ddepth = abs(dpdz.z); - - // -- End depth bias helper section -------------------------------- - - // We now compute the depth of the fragment. This is the actual depth value plus - // our depth bias. The depth bias depends on how uncertain we are about the z value - // plus some constant push in the z direction. The exact coefficients to use are - // up to you, but at least it should be somewhat intuitive now what the tradeoffs are. - float depthval = postproj.z /* + (0.5 * dzlen)*/ + (uDepthOffset * ddepth); - depthval = (0.5 * depthval) + 0.5; // put into [0,1] range instead of [-1,1] - - - Out.color = float4(depthval, depthval * depthval, depthval, 0.0); - return Out; -} -///////////////////////////////////////////////////////////////////////////////// -// -// varianceshadowcasterfp.glsles -// -// Hamilton Chong -// (c) 2006 -// GLSL ES by David Rogers -// -// This is an example fragment shader for shadow caster objects. -// -///////////////////////////////////////////////////////////////////////////////// - - -// Define outputs from vertex shader. -struct VertexOut -{ - float4 position : POSITION; // can't rely on access to this - float4 pos : TEXCOORD0; // position of fragment (in homogeneous coordinates) - float4 normal : TEXCOORD1; // un-normalized normal in object space - float4 modelPos : TEXCOORD2; // coordinates of model in object space at this point -}; - -struct FragmentOut -{ - float4 color : COLOR0; -}; - -FragmentOut main( VertexOut In, // fragment to process - uniform float uDepthOffset, // offset amount (constant in eye space) - uniform float4x4 uProjection // projection matrix - ) -{ - FragmentOut Out; - - // compute the "normalized device coordinates" (no viewport applied yet) - float4 postproj = In.pos / In.pos.w; - - // get the normalized normal of the geometry seen at this point - float4 normal = normalize(In.normal); - - - // -- Computing Depth Bias Quantities ----------------------------- - - // We now compute the change in z that would signify a push in the z direction - // by 1 unit in eye space. Note that eye space z is related in a nonlinear way to - // screen space z, so this is not just a constant. - // ddepth below is how much screen space z at this point would change for that push. - // NOTE: computation of ddepth likely differs from OpenGL's glPolygonOffset "unit" - // computation, which is allowed to be vendor specific. - float4 dpwdz = mul(uProjection, float4(0.0, 0.0, 1.0, 0.0)); - float4 dpdz = (dpwdz - (postproj * dpwdz.w)) / In.pos.w; - float ddepth = abs(dpdz.z); - - // -- End depth bias helper section -------------------------------- - - // We now compute the depth of the fragment. This is the actual depth value plus - // our depth bias. The depth bias depends on how uncertain we are about the z value - // plus some constant push in the z direction. The exact coefficients to use are - // up to you, but at least it should be somewhat intuitive now what the tradeoffs are. - float depthval = postproj.z /* + (0.5 * dzlen)*/ + (uDepthOffset * ddepth); - depthval = (0.5 * depthval) + 0.5; // put into [0,1] range instead of [-1,1] - - - Out.color = float4(depthval, depthval * depthval, depthval, 0.0); - return Out; -} diff --git a/Samples/Media/materials/programs/GLSLES/varianceshadowcastervp.glsles b/Samples/Media/materials/programs/GLSLES/varianceshadowcastervp.glsles deleted file mode 100644 index 3cf3715854d..00000000000 --- a/Samples/Media/materials/programs/GLSLES/varianceshadowcastervp.glsles +++ /dev/null @@ -1,88 +0,0 @@ -///////////////////////////////////////////////////////////////////////////////// -// -// shadowcastervp.cg -// -// Hamilton Chong -// (c) 2006 -// -// This is an example vertex shader for shadow caster objects. -// -///////////////////////////////////////////////////////////////////////////////// - - -// Define inputs from application. -struct VertexIn -{ - float4 position : POSITION; // vertex position in object space - float4 normal : NORMAL; // vertex normal in object space -}; - -// Define outputs from vertex shader. -struct VertexOut -{ - float4 position : POSITION; // post projection position coordinates - float4 pos : TEXCOORD0; // ditto. Not all hardware allows access values bound to POSITION in fp. - float4 normal : TEXCOORD1; // normal in object space (to be interpolated) - float4 modelPos : TEXCOORD2; // position in object space (to be interpolated) -}; - -VertexOut main( VertexIn In, // vertex to process - uniform float4x4 uModelViewProjection // model-view-projection matrix - ) -{ - VertexOut Out; // output data - - // Transform vertex position into post projective (homogenous screen) space. - Out.position = mul(uModelViewProjection, In.position); - Out.pos = mul(uModelViewProjection, In.position); - - // copy over data to interpolate using perspective correct interpolation - Out.normal = float4(In.normal.x, In.normal.y, In.normal.z, 0.0); - Out.modelPos = In.position; - - return Out; -} -///////////////////////////////////////////////////////////////////////////////// -// -// shadowcastervp.cg -// -// Hamilton Chong -// (c) 2006 -// -// This is an example vertex shader for shadow caster objects. -// -///////////////////////////////////////////////////////////////////////////////// - - -// Define inputs from application. -struct VertexIn -{ - float4 position : POSITION; // vertex position in object space - float4 normal : NORMAL; // vertex normal in object space -}; - -// Define outputs from vertex shader. -struct VertexOut -{ - float4 position : POSITION; // post projection position coordinates - float4 pos : TEXCOORD0; // ditto. Not all hardware allows access values bound to POSITION in fp. - float4 normal : TEXCOORD1; // normal in object space (to be interpolated) - float4 modelPos : TEXCOORD2; // position in object space (to be interpolated) -}; - -VertexOut main( VertexIn In, // vertex to process - uniform float4x4 uModelViewProjection // model-view-projection matrix - ) -{ - VertexOut Out; // output data - - // Transform vertex position into post projective (homogenous screen) space. - Out.position = mul(uModelViewProjection, In.position); - Out.pos = mul(uModelViewProjection, In.position); - - // copy over data to interpolate using perspective correct interpolation - Out.normal = float4(In.normal.x, In.normal.y, In.normal.z, 0.0); - Out.modelPos = In.position; - - return Out; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/GLSLES/varianceshadowreceiverfp.glsles b/Samples/Media/materials/programs/GLSLES/varianceshadowreceiverfp.glsles deleted file mode 100644 index 120700eebfc..00000000000 --- a/Samples/Media/materials/programs/GLSLES/varianceshadowreceiverfp.glsles +++ /dev/null @@ -1,214 +0,0 @@ -///////////////////////////////////////////////////////////////////////////////// -// -// shadowreceiverfp.cg -// -// Hamilton Chong -// (c) 2006 -// -// This is an example fragment shader for shadow receiver objects. -// -///////////////////////////////////////////////////////////////////////////////// - - -sampler2D ShadowMap : TEXUNIT0; - -// Define outputs from vertex shader. -struct Vertex -{ - float4 position : POSITION; // fragment position in post projective space - float4 shadowCoord : TEXCOORD0; // fragment position in shadow map coordinates - float diffuse : TEXCOORD1; // diffuse shading value -}; - -struct Fragment -{ - float4 color : COLOR0; -}; - -Fragment main(Vertex In, - uniform float uSTexWidth, - uniform float uSTexHeight) -{ - Fragment Out; - - // compute the shadow coordinates for texture lookup - // NOTE: texture_viewproj_matrix maps z into [0,1] range, not [-1,1], so - // have to make sure shadow caster stores depth values with same convention. - float4 scoord = In.shadowCoord / In.shadowCoord.w; - - - // -- Bilinear Filtering of Sample -------------------------------------------- - - // One could use scoord.xy to look up the shadow map for depth testing, but - // we'll be implementing a simple "percentage closest filtering" algorithm instead. - // This mimics the behavior of turning on bilinear filtering on NVIDIA hardware - // when also performing shadow comparisons. This causes bilinear filtering of - // depth tests. Note that this is NOT the same as bilinear filtering the depth - // values and then doing the depth comparison. The two operations are not - // commutative. PCF is explicitly about filtering the test values since - // testing filtered z values is often meaningless. - - // Real percentage closest filtering should sample from the entire footprint - // on the shadow map, not just seek the closest four sample points. Such - // an improvement is for future work. - - - // NOTE: Assuming OpenGL convention for texture lookups with integers in centers. - // DX convention is to have integers mark sample corners - float2 tcoord; - tcoord.x = (scoord.x * uSTexWidth) - 0.5; - tcoord.y = (scoord.y * uSTexHeight) - 0.5; - float x0 = floor(tcoord.x); - float x1 = ceil(tcoord.x); - float fracx = frac(tcoord.x); - float y0 = floor(tcoord.y); - float y1 = ceil(tcoord.y); - float fracy = frac(tcoord.y); - - // sample coordinates in [0,1]^2 domain - float2 t00, t01, t10, t11; - float invWidth = 1.0 / uSTexWidth; - float invHeight = 1.0 / uSTexHeight; - t00 = float2((x0+0.5) * invWidth, (y0+0.5) * invHeight); - t10 = float2((x1+0.5) * invWidth, (y0+0.5) * invHeight); - t01 = float2((x0+0.5) * invWidth, (y1+0.5) * invHeight); - t11 = float2((x1+0.5) * invWidth, (y1+0.5) * invHeight); - - // grab the samples - float2 z00 = tex2D(ShadowMap, t00).xy; - float2 z01 = tex2D(ShadowMap, t01).xy; - float2 z10 = tex2D(ShadowMap, t10).xy; - float2 z11 = tex2D(ShadowMap, t11).xy; - - // bilinear filter the sample data - float2 d0 = ((1.0 - fracx) * z00) + (fracx * z10); - float2 d1 = ((1.0 - fracx) * z01) + (fracx * z11); - float2 datum = ((1.0 - fracy) * d0) + (fracy * d1); - - // -- Variance Shadow Mapping --------------------------------------------------- - - float zVariance = datum.y - (datum.x * datum.x); - float zDeviation = scoord.z - datum.x; - zDeviation = (zDeviation < 0.0) ? 0.0 : zDeviation; - float visibility = zVariance / (zVariance + (zDeviation * zDeviation)); - float ztest = (scoord.z < datum.x) ? 1.0:0.0; // filtering depth ok, because used only for small variance - visibility = (zVariance > 0.0) ? visibility : ztest; // if variance too small, we get garbage - //0.0000001 - - // determine that all geometry within pixel border of shadow map (and outside) is lit - float filterBorder = max(invWidth, invHeight); - visibility = (all(abs(scoord.xy-0.5)<=0.5-filterBorder)) ? visibility : 1.0; - - // ------------------------------------------------------------------------------ - - visibility *= In.diffuse; - Out.color = float4(visibility, visibility, visibility, 0.0); - return Out; -} -///////////////////////////////////////////////////////////////////////////////// -// -// shadowreceiverfp.cg -// -// Hamilton Chong -// (c) 2006 -// -// This is an example fragment shader for shadow receiver objects. -// -///////////////////////////////////////////////////////////////////////////////// - - -sampler2D ShadowMap : TEXUNIT0; - -// Define outputs from vertex shader. -struct Vertex -{ - float4 position : POSITION; // fragment position in post projective space - float4 shadowCoord : TEXCOORD0; // fragment position in shadow map coordinates - float diffuse : TEXCOORD1; // diffuse shading value -}; - -struct Fragment -{ - float4 color : COLOR0; -}; - -Fragment main(Vertex In, - uniform float uSTexWidth, - uniform float uSTexHeight) -{ - Fragment Out; - - // compute the shadow coordinates for texture lookup - // NOTE: texture_viewproj_matrix maps z into [0,1] range, not [-1,1], so - // have to make sure shadow caster stores depth values with same convention. - float4 scoord = In.shadowCoord / In.shadowCoord.w; - - - // -- Bilinear Filtering of Sample -------------------------------------------- - - // One could use scoord.xy to look up the shadow map for depth testing, but - // we'll be implementing a simple "percentage closest filtering" algorithm instead. - // This mimics the behavior of turning on bilinear filtering on NVIDIA hardware - // when also performing shadow comparisons. This causes bilinear filtering of - // depth tests. Note that this is NOT the same as bilinear filtering the depth - // values and then doing the depth comparison. The two operations are not - // commutative. PCF is explicitly about filtering the test values since - // testing filtered z values is often meaningless. - - // Real percentage closest filtering should sample from the entire footprint - // on the shadow map, not just seek the closest four sample points. Such - // an improvement is for future work. - - - // NOTE: Assuming OpenGL convention for texture lookups with integers in centers. - // DX convention is to have integers mark sample corners - float2 tcoord; - tcoord.x = (scoord.x * uSTexWidth) - 0.5; - tcoord.y = (scoord.y * uSTexHeight) - 0.5; - float x0 = floor(tcoord.x); - float x1 = ceil(tcoord.x); - float fracx = frac(tcoord.x); - float y0 = floor(tcoord.y); - float y1 = ceil(tcoord.y); - float fracy = frac(tcoord.y); - - // sample coordinates in [0,1]^2 domain - float2 t00, t01, t10, t11; - float invWidth = 1.0 / uSTexWidth; - float invHeight = 1.0 / uSTexHeight; - t00 = float2((x0+0.5) * invWidth, (y0+0.5) * invHeight); - t10 = float2((x1+0.5) * invWidth, (y0+0.5) * invHeight); - t01 = float2((x0+0.5) * invWidth, (y1+0.5) * invHeight); - t11 = float2((x1+0.5) * invWidth, (y1+0.5) * invHeight); - - // grab the samples - float2 z00 = tex2D(ShadowMap, t00).xy; - float2 z01 = tex2D(ShadowMap, t01).xy; - float2 z10 = tex2D(ShadowMap, t10).xy; - float2 z11 = tex2D(ShadowMap, t11).xy; - - // bilinear filter the sample data - float2 d0 = ((1.0 - fracx) * z00) + (fracx * z10); - float2 d1 = ((1.0 - fracx) * z01) + (fracx * z11); - float2 datum = ((1.0 - fracy) * d0) + (fracy * d1); - - // -- Variance Shadow Mapping --------------------------------------------------- - - float zVariance = datum.y - (datum.x * datum.x); - float zDeviation = scoord.z - datum.x; - zDeviation = (zDeviation < 0.0) ? 0.0 : zDeviation; - float visibility = zVariance / (zVariance + (zDeviation * zDeviation)); - float ztest = (scoord.z < datum.x) ? 1.0:0.0; // filtering depth ok, because used only for small variance - visibility = (zVariance > 0.0) ? visibility : ztest; // if variance too small, we get garbage - //0.0000001 - - // determine that all geometry within pixel border of shadow map (and outside) is lit - float filterBorder = max(invWidth, invHeight); - visibility = (all(abs(scoord.xy-0.5)<=0.5-filterBorder)) ? visibility : 1.0; - - // ------------------------------------------------------------------------------ - - visibility *= In.diffuse; - Out.color = float4(visibility, visibility, visibility, 0.0); - return Out; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/GLSLES/varianceshadowreceivervp.glsles b/Samples/Media/materials/programs/GLSLES/varianceshadowreceivervp.glsles deleted file mode 100644 index e88c0e98f6b..00000000000 --- a/Samples/Media/materials/programs/GLSLES/varianceshadowreceivervp.glsles +++ /dev/null @@ -1,94 +0,0 @@ -///////////////////////////////////////////////////////////////////////////////// -// -// shadowreceivervp.cg -// -// Hamilton Chong -// (c) 2006 -// -// This is an example vertex shader for shadow receiver objects. -// -///////////////////////////////////////////////////////////////////////////////// - -// Define inputs from application. -struct VertexIn -{ - float4 position : POSITION; // vertex position in object space - float4 normal : NORMAL; // vertex normal in object space -}; - -// Define outputs from vertex shader. -struct Vertex -{ - float4 position : POSITION; // vertex position in post projective space - float4 shadowCoord : TEXCOORD0; // vertex position in shadow map coordinates - float diffuse : TEXCOORD1; // diffuse shading value -}; - -Vertex main(VertexIn In, - uniform float4x4 uModelViewProjection, // model-view-projection matrix - uniform float4 uLightPosition, // light position in object space - uniform float4x4 uModel, // model matrix - uniform float4x4 uTextureViewProjection // shadow map's view projection matrix - ) -{ - Vertex Out; - - // compute diffuse shading - float3 lightDirection = normalize(uLightPosition.xyz - In.position.xyz); - Out.diffuse = dot(In.normal.xyz, lightDirection); - - // compute shadow map lookup coordinates - Out.shadowCoord = mul(uTextureViewProjection, mul(uModel, In.position)); - - // compute vertex's homogenous screen-space coordinates - Out.position = mul(uModelViewProjection, In.position); - - return Out; -} -///////////////////////////////////////////////////////////////////////////////// -// -// shadowreceivervp.cg -// -// Hamilton Chong -// (c) 2006 -// -// This is an example vertex shader for shadow receiver objects. -// -///////////////////////////////////////////////////////////////////////////////// - -// Define inputs from application. -struct VertexIn -{ - float4 position : POSITION; // vertex position in object space - float4 normal : NORMAL; // vertex normal in object space -}; - -// Define outputs from vertex shader. -struct Vertex -{ - float4 position : POSITION; // vertex position in post projective space - float4 shadowCoord : TEXCOORD0; // vertex position in shadow map coordinates - float diffuse : TEXCOORD1; // diffuse shading value -}; - -Vertex main(VertexIn In, - uniform float4x4 uModelViewProjection, // model-view-projection matrix - uniform float4 uLightPosition, // light position in object space - uniform float4x4 uModel, // model matrix - uniform float4x4 uTextureViewProjection // shadow map's view projection matrix - ) -{ - Vertex Out; - - // compute diffuse shading - float3 lightDirection = normalize(uLightPosition.xyz - In.position.xyz); - Out.diffuse = dot(In.normal.xyz, lightDirection); - - // compute shadow map lookup coordinates - Out.shadowCoord = mul(uTextureViewProjection, mul(uModel, In.position)); - - // compute vertex's homogenous screen-space coordinates - Out.position = mul(uModelViewProjection, In.position); - - return Out; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL/Blur0_ps20.hlsl b/Samples/Media/materials/programs/HLSL/Blur0_ps20.hlsl deleted file mode 100644 index 5790dce51d8..00000000000 --- a/Samples/Media/materials/programs/HLSL/Blur0_ps20.hlsl +++ /dev/null @@ -1,31 +0,0 @@ -sampler RT: register(s0); -// Simple blur filter - -float4 main(float2 texCoord: TEXCOORD0) : COLOR { - - float2 samples[12] = { - -0.326212, -0.405805, - -0.840144, -0.073580, - -0.695914, 0.457137, - -0.203345, 0.620716, - 0.962340, -0.194983, - 0.473434, -0.480026, - 0.519456, 0.767022, - 0.185461, -0.893124, - 0.507431, 0.064425, - 0.896420, 0.412458, - -0.321940, -0.932615, - -0.791559, -0.597705, - }; - - float4 sum = tex2D(RT, texCoord); - for (int i = 0; i < 12; i++){ - sum += tex2D(RT, texCoord + 0.025 * samples[i]); - } - return sum / 13; - -} - - - - diff --git a/Samples/Media/materials/programs/HLSL/Blur0_vs11.hlsl b/Samples/Media/materials/programs/HLSL/Blur0_vs11.hlsl deleted file mode 100644 index 3979eae9fba..00000000000 --- a/Samples/Media/materials/programs/HLSL/Blur0_vs11.hlsl +++ /dev/null @@ -1,22 +0,0 @@ -struct VS_OUTPUT { - float4 Pos: POSITION; - float2 texCoord: TEXCOORD0; -}; - -VS_OUTPUT main(float4 Pos: POSITION){ - VS_OUTPUT Out; - - // Clean up inaccuracies - Pos.xy = sign(Pos.xy); - - Out.Pos = float4(Pos.xy, 0, 1); - // Image-space - Out.texCoord.x = 0.5 * (1 + Pos.x); - Out.texCoord.y = 0.5 * (1 - Pos.y); - - return Out; -} - - - - diff --git a/Samples/Media/materials/programs/HLSL/Blur1_ps20.hlsl b/Samples/Media/materials/programs/HLSL/Blur1_ps20.hlsl deleted file mode 100644 index 95e754b24fc..00000000000 --- a/Samples/Media/materials/programs/HLSL/Blur1_ps20.hlsl +++ /dev/null @@ -1,28 +0,0 @@ -sampler Blur0: register(s0); -// Simple blur filter - -float4 main(float2 texCoord: TEXCOORD0) : COLOR { - - float2 samples[12] = { - -0.326212, -0.405805, - -0.840144, -0.073580, - -0.695914, 0.457137, - -0.203345, 0.620716, - 0.962340, -0.194983, - 0.473434, -0.480026, - 0.519456, 0.767022, - 0.185461, -0.893124, - 0.507431, 0.064425, - 0.896420, 0.412458, - -0.321940, -0.932615, - -0.791559, -0.597705, - }; - - float4 sum = tex2D(Blur0, texCoord); - for (int i = 0; i < 12; i++){ - sum += tex2D(Blur0, texCoord + 0.025 * samples[i]); - } - return sum / 13; - -} - diff --git a/Samples/Media/materials/programs/HLSL/Blur1_vs11.hlsl b/Samples/Media/materials/programs/HLSL/Blur1_vs11.hlsl deleted file mode 100644 index 49b316f169c..00000000000 --- a/Samples/Media/materials/programs/HLSL/Blur1_vs11.hlsl +++ /dev/null @@ -1,19 +0,0 @@ -struct VS_OUTPUT { - float4 Pos: POSITION; - float2 texCoord: TEXCOORD0; -}; - -VS_OUTPUT main(float4 Pos: POSITION){ - VS_OUTPUT Out; - - // Clean up inaccuracies - Pos.xy = sign(Pos.xy); - - Out.Pos = float4(Pos.xy, 0, 1); - // Image-space - Out.texCoord.x = 0.5 * (1 + Pos.x); - Out.texCoord.y = 0.5 * (1 - Pos.y); - - return Out; -} - diff --git a/Samples/Media/materials/programs/HLSL/ComputeCS.hlsl b/Samples/Media/materials/programs/HLSL/ComputeCS.hlsl deleted file mode 100644 index 5dfe397eb3f..00000000000 --- a/Samples/Media/materials/programs/HLSL/ComputeCS.hlsl +++ /dev/null @@ -1,17 +0,0 @@ -#include - -RWTexture2D tex; - -uniform float roll; - -[numthreads(16, 16, 1)] -void main( - uint3 gl_WorkGroupID : SV_GroupID, - uint3 gl_LocalInvocationID : SV_GroupThreadID, - uint3 gl_GlobalInvocationID : SV_DispatchThreadID, - uint gl_LocalInvocationIndex : SV_GroupIndex) -{ - float localCoef = length((float2(gl_LocalInvocationID.xy)-8)/8.0); - float globalCoef = sin(float(gl_WorkGroupID.x+gl_WorkGroupID.y)*0.1 + roll)*0.5; - tex[gl_GlobalInvocationID.xy] = float4(float2(1.0-globalCoef*localCoef, 1.0-globalCoef*localCoef), 1, 1); -} diff --git a/Samples/Media/materials/programs/HLSL/Hair.hlsl b/Samples/Media/materials/programs/HLSL/Hair.hlsl deleted file mode 100644 index 45e0ca764ee..00000000000 --- a/Samples/Media/materials/programs/HLSL/Hair.hlsl +++ /dev/null @@ -1,5181 +0,0 @@ -/* ----------------------------------------------------------- -Hair Tessellation sample from NVIDIA's DirectX 11 SDK: -http://developer.nvidia.com/nvidia-graphics-sdk-11-direct3d ----------------------------------------------------------- -*/ - -//#include "Hair.h" -#define NUM_MRTS 8 -#define NUM_PASSES 1 -#define ARRAY_SIZE (NUM_PASSES * NUM_MRTS) - -#define CSM_ZMAX 1.0 -#define CSM_HALF_NUM_TEX 4 - -#define MAX_IMPLICITS 10 -#define oneOverSqrt2PI 0.39894228040143267 -#define PI 3.1415926535897932384626433832795 - -#define SMALL_NUM 0.0001 -#define EPSILON 0.0001 - -// These are the values used when filling the obstacle textures -#define OBSTACLE_EXTERIOR 1.0f -#define OBSTACLE_BOUNDARY 128.0f/255.0f -#define OBSTACLE_INTERIOR 0.0f - -#define SHADOWS_VS - -// PCF -#define PCF_RADIUS 5 -#define PCF_INCREMENT 2 -#define USE_ABSORPTION - -//Deep Opacity Maps -#define SM_RADIUS 5 -#define SM_INCREMENT 2 -#define RGBA8_PRECISION_DENSITY (64.0/255.0) -#define INV_RGBA8_PRECISION_DENSITY (255.0/64.0) - -#define g_NumInterpolatedAttributesMinusOne 1023 -#define g_NumInterpolatedAttributes 1024 - -shared cbuffer constants -{ - //float g_widthMulC = 0.5;// 1;//0.5; - float g_widthMulB = 0.5;// 1;//0.5; - float g_widthMulGS = 0.95;// 0.8; - float g_widthMul = 1.0; //this is for the depth prepass - //tessellation hardware - int g_maxPatchesPerTessellatedStrand; //g_maxPatchesPerTessellatedStrand = maxStrandLength/(strandVerticesInPatch-1). note that maxStrandLength will be differernt depending on whether or not we are using this variable for a tessellated strand vs a non-tessllated strand, and will be different based on the tessellation factor. - float g_InterpolationLOD = 1.0; - float fg_textureWidth = 1024.0f; - float g_StrandWidthMultiplier = 25.0f; - float4 g_arrowColor; - - //float g_kdMesh = 1; - //float g_ksMesh = 0.1; - //float g_specPowerMesh = 10; - //float g_AmbientLightMesh = 0.3; - - float g_alpha = 1.0f; - - float g_lightBufferRes = 1.0f; - - //clumping - float g_clumpWidth = 1.0f; - float g_topWidth = 0.7; - float g_bottomWidth = 0.05; - float g_lt = 0.7; - float g_lv = 0.05; - - //float splatSize; - //int g_blurRadius; - //float3 g_blurDirection; - //float g_blurSigma; - //bool g_useGradientBasedForce; -} - -shared cbuffer cb0 -{ - float g_ScreenWidth = 1280.0; - float g_ScreenHeight = 1024.0; - - int g_bApplyAdditionalTransform; - int g_bApplyAdditionalRenderingTransform; - - float g_SSg_textureWidth; - float g_SSg_textureHeight; - - float g_ksP; - float g_ksS; - float g_kd; - float g_ka; - float g_specPowerPrimary; - float g_specPowerSecondary; - float g_specPowerPrimarySparkles; - float g_ksP_sparkles; - float4 g_baseColor; - float4 g_specColor; - - float g_fNumHairsLOD = 1; - float g_fWidthHairsLOD = 1; - - float g_maxLengthToRoot = 12; //this is the maximum length of any strand in the whole hairstyle - int g_useScalpTexture; - - int g_NumTotalWisps; - int g_NumMaxStrandsPerWisp; - - float g_blendAxis; //for coordinate frame correction - int g_doCurlyHair; - float g_angularStiffness; - int g_bApplyHorizontalForce = false; - int g_bAddGravity = false; - float g_TimeStep = 0.1; - float g_gravityStrength = 0.1f; - int g_bSimulate = false; - - //wind - float3 g_windForce = float3(-1,0,0); - - //wind fluid simulation - int fluidg_textureWidth; - int fluidg_textureHeight; - int fluidg_textureDepth; - - //body collisions - int g_NumSphereImplicits; - int g_NumCylinderImplicits; - int g_NumSphereNoMoveImplicits; - - //render the collision spheres - int g_currentCollisionSphere; - - float g_thinning = 0.5; - int g_TessellatedMasterStrandLengthMax; - - float g_densityThreshold; - // float g_interHairForces; - not used - - float g_textureHeight; - float g_textureWidth; - float g_textureDepth; - - // float g_gridZStep; - //float g_gridZMin; - //int g_gridNumRTs; - - int g_rowWidth; - int g_colWidth; - int g_textureIndex; - int g_gridZIndex; - - int g_useBlurTexture; // - not used - int g_bClearForces; - int g_useShadows; - - float g_SoftEdges; // - not used - float g_SigmaA; - - float g_ZNear, g_ZFar; -} - -#define SCALE_WIDTH_WITH_LOD - -shared cbuffer collisionmatrixes -{ - row_major float4x4 CollisionSphereTransformations[MAX_IMPLICITS]; - row_major float4x4 CollisionSphereInverseTransformations[MAX_IMPLICITS]; - row_major float4x4 CollisionCylinderTransformations[MAX_IMPLICITS]; - row_major float4x4 CollisionCylinderInverseTransformations[MAX_IMPLICITS]; - - row_major float4x4 SphereNoMoveImplicitTransform[MAX_IMPLICITS]; - row_major float4x4 SphereNoMoveImplicitInverseTransform[MAX_IMPLICITS]; - - int g_UseSphereForBarycentricInterpolant[MAX_IMPLICITS]; - int g_UseCylinderForBarycentricInterpolant[MAX_IMPLICITS]; - int g_UseSphereNoMoveForBarycentricInterpolant[MAX_IMPLICITS]; -} - -shared cbuffer matrixes -{ - matrix ViewProjection; - matrix WorldView; - matrix WorldViewProjection; - row_major float4x4 WorldToGrid; - row_major float4x4 GridToWorld; - row_major float4x4 RootTransformation; - row_major float4x4 additionalTransformation; - row_major float4x4 TotalTransformation; - row_major float4x4 HairToWorldTransform; - row_major float4x4 currentHairTransformation; - row_major float4x4 currentHairTransformationInverse; - - float3 vLightPos; - float3 LightPosition = float3(1, 1, 1); - float3 EyePosition; - float3 TransformedEyePosition; - float3 vLightDir; //TO DO SHADOWS: if world matrices (like HairToWorldTransform) are incorporated into shadows - // this vector might change to be in world space rather than hair space. - // in that case calculations using it will have to change, since they are currently - // happening in hair space - float3 vLightDirObjectSpace; - - matrix mWorldViewProj; - matrix mLightView; - matrix mLightProj; - matrix mLightViewProj; - matrix mLightViewProjI; - matrix mLightViewProjClip2Tex; -} - -//texture and buffer variables -Buffer g_Attributes : register(t0); -Buffer g_StrandSizes : register(t1); -Buffer g_StrandCircularCoordinates : register(t2); -Buffer g_StrandLengths : register(t3); -Buffer g_StrandColors : register(t4); -Buffer g_StrandCoordinates : register(t5); -Buffer g_strandDeviations : register(t6); -Buffer g_TangentJitter : register(t7); -Buffer g_curlDeviations : register(t8); -//position, tangent, index, length, coordinate frame buffers -Buffer g_TessellatedMasterStrand : register(t9); -Buffer g_MasterStrand : register(t10); -Buffer g_OriginalMasterStrand : register(t11); -Buffer g_MasterStrandRootIndices : register(t12); -Buffer g_MasterStrandRootIndicesUntessellated : register(t13); -Buffer g_MasterStrandLengths : register(t14); -Buffer g_MasterStrandLengthsUntessellated : register(t15); -Buffer g_OriginalMasterStrandRootIndices : register(t16); -Buffer g_tessellatedMasterStrandRootIndex : register(t17); -Buffer g_coordinateFrames : register(t18); -Buffer g_tessellatedCoordinateFrames : register(t19); -Buffer g_TessellatedLengthsToRoots : register(t20); -Buffer g_LengthsToRoots : register(t21); -Buffer g_TessellatedTangents : register(t22); -Buffer g_Forces : register(t23); -Buffer g_OriginalVectors : register(t24); -Buffer g_VertexNumber : register(t25); -Buffer g_Lengths : register(t26); -Buffer g_mStrandIndices : register(t27); -Buffer g_sStrandIndices : register(t28); -//precalculated positions and attributes -Buffer g_InterpolatedPositionAndWidth : register(t29); -Buffer g_InterpolatedIdAlphaTex : register(t30); -Buffer g_Interpolatedtangent : register(t31); -Buffer g_InterpolatedPositionAndWidthClump : register(t32); -Buffer g_InterpolatedIdAlphaTexClump : register(t33); -Buffer g_InterpolatedtangentClump : register(t34); -Buffer g_SStrandsPerMasterStrandCumulative : register(t35); -Buffer g_MStrandsPerWispCumulative : register(t35); - -//CSM -Texture2DArray tCSM : register(t38); -//hair rendering -Texture2D hairTexture : register(t39); -Texture2DArray hairTextureArray : register(t40); -Texture2D specularNoise : register(t41); -Texture2D densityThicknessMapClump : register(t42); -Texture2D densityThicknessMapBarycentric : register(t43); -//textures -Texture2D g_CollisionsTexture : register(t44); -Texture3D g_FluidVelocityTexture : register(t45); -Texture2D g_SupersampledSceneColor : register(t46); -Texture2D g_sceneDepth : register(t47); -//interaction variables -Texture2DArray Texture_density : register(t48); -Texture2DArray Texture_density_Demux : register(t49); -Texture2DArray Texture_density_Blur_Temp : register(t50); -Texture2DArray Texture_density_Blur : register(t51); -Texture2DArray Texure_to_blur : register(t52); -Texture2DArray Texture_Voxelized_Obstacles : register(t53); -Texture2D tShadowMap : register(t54); -Texture2D tHairDepthMap : register(t59); -Texture2DArray tShadowMapArray : register(t60); - -//Shading -Texture2D ShadingLookup1 : register(t54); -Texture2D ShadingLookup2 : register(t55); - -Texture2D meshAOMap : register(t56); - -StructuredBuffer g_MasterStrandSB : register(t57); -StructuredBuffer g_coordinateFramesSB : register(t58); - -cbuffer onblend -{ - float4 g_Zmin[NUM_MRTS]; - float4 g_Zmax[NUM_MRTS]; - float4 g_Zi[ARRAY_SIZE]; - float4 g_Dz[ARRAY_SIZE]; -} - -SamplerState samLinear -{ - Filter = MIN_MAG_MIP_LINEAR; - AddressU = Wrap; - AddressV = Wrap; -}; - -SamplerState samLinearClamp -{ - Filter = MIN_MAG_MIP_LINEAR; - AddressU = Clamp; - AddressV = Clamp; - AddressW = Clamp; -}; - -SamplerState samLinearWrap -{ - Filter = MIN_MAG_MIP_LINEAR; - AddressU = Wrap; - AddressV = Wrap; - AddressW = Wrap; -}; - -SamplerState samPointClamp -{ - Filter = MIN_MAG_MIP_POINT; - AddressU = Clamp; - AddressV = Clamp; - AddressW = Clamp; -}; - -SamplerComparisonState samShadow -{ - ComparisonFunc = GREATER_EQUAL; - Filter = COMPARISON_MIN_MAG_LINEAR_MIP_POINT; - AddressU = Clamp; - AddressV = Clamp; -}; - -SamplerState samAniso -{ - Filter = ANISOTROPIC; - AddressU = Wrap; - AddressV = Wrap; -}; - -// Hair simulation -//structs - -struct HairVertex -{ - float4 Position; -}; - -struct coordinateFrame -{ - float3 x; - float3 y; - float3 z; -}; - -struct CFVertex -{ - float4 Position; - float3 Color; -}; - -struct collisionImplicit -{ - float3 center; - float3 rotation; - float3 scale; -}; - -struct HairVertexPair -{ - float4 position : POSITION0; - float4 oldPosition : POSITION1; -}; - -struct HairVertexLength -{ - float4 Position : POSITION0; - float Length : LENGTH0; -}; - -struct HairVertexLengthStiffness -{ - float4 Position : POSITION0; - float2 LengthStiffness : LENGTH0; -}; - -struct ConstraintsHairVertex -{ - float4 Position : POSITION; - float Length : LENGTH; - uint vid : ID; -}; - -struct ConstraintsAngularHairVertex -{ - float4 Position : POSITION; - float Length : LENGTH; - float Stiffness : STIFFNESS; - uint vid : ID; -}; - -struct HairVertexVID -{ - float4 Position : POSITION; - uint vid : ID; -}; - -//helper functions -bool IsAnEnd(HairVertex vertex) -{ - return vertex.Position.w > 0; -} - -bool IsAnEnd(float4 vertex) -{ - return vertex.w > 0; -} - -bool IsFree(HairVertex particle) -{ - if(particle.Position.w >=0) - return true; - return false; -} - -bool IsFree(float4 particle) -{ - if(particle.w >=0) - return true; - return false; -} - -float2 Responsiveness(HairVertex particle0, HairVertex particle1) -{ - if (IsFree(particle0)) - { - if (IsFree(particle1)) - return float2(0.5, 0.5); - else - return float2(1, 0); - } - else - { - if (IsFree(particle1)) - return float2(0, 1); - else - return float2(0, 0); - } - -} - -//collision sphere stuff -//assuming original obstacle was a unit radius sphere centered at origin -float3 SphereConstraint(float4 position,int i) -{ - if(!IsFree(position)) - return 0; - - //inverse transform the position - float3 transformedPosition = (mul(float4(position.xyz,1),CollisionSphereInverseTransformations[i])).xyz; - - //find the force - float3 force= float3(0,0,0); - float len = length(transformedPosition); - - if(len < 1) - { - force = (1-len)*(transformedPosition/len); - - row_major float4x4 transform = CollisionSphereTransformations[i]; - //remove the translation - transform._41 = 0; - transform._42 = 0; - transform._43 = 0; - transform._44 = 1; - force = (mul(float4(force,1),transform)).xyz; - } - - return force; -} - -float3 SphereConstraint(float4 position,row_major float4x4 InverseTransform,row_major float4x4 ForwardTransform ) -{ - if(!IsFree(position)) - return 0; - - //inverse transform the position - float3 transformedPosition = (mul(float4(position.xyz,1),InverseTransform)).xyz; - - //find the force - float3 force= float3(0,0,0); - float len = length(transformedPosition); - - if(len < 1) - { - force = (1-len)*(transformedPosition/len); - - row_major float4x4 transform = ForwardTransform; - //remove the translation - transform._41 = 0; - transform._42 = 0; - transform._43 = 0; - transform._44 = 1; - force = (mul(float4(force,1),transform)).xyz; - } - - return force; -} - -//assuming original obstacle was a unit radius sphere centered at origin -bool PartitionInOutBoundarySphere(float3 position, float boundary, int i, inout float returnVal ) -{ - //inverse transform the position - float3 transformedPosition = (mul(float4(position.xyz,1),CollisionSphereInverseTransformations[i])).xyz; - - float len = length(transformedPosition); - float distanceToPush = 1 - len; - - if(distanceToPush < 0) - { - returnVal = OBSTACLE_EXTERIOR; - return false; - } - if(distanceToPush > boundary) - { - returnVal = OBSTACLE_INTERIOR; - return true; - } - returnVal = OBSTACLE_BOUNDARY; - return true; - -} - -//this assumes a circle centered at the origin with a radius of 1 -bool IsInsideSphere(float3 position, int i,float3 additionalScale) -{ - //inverse transform the position - float3 transformedPosition = mul(float4(position,1),CollisionSphereInverseTransformations[i]).xyz; - transformedPosition *= additionalScale; - float len = length(transformedPosition); - if(len<1) - return true; - return false; -} - -//this assumes a sphere centered at the origin with a radius of 1 -bool IsInsideSphere(float3 position, row_major float4x4 transform ) -{ - //inverse transform the position - float3 transformedPosition = mul(float4(position,1),transform).xyz; - float len = length(transformedPosition); - if(len<1) - return true; - return false; -} - -//collision cylinder stuff -float3 CylinderConstraint(float4 position, int i) -{ - if(!IsFree(position)) - return 0; - - //inverse transform the position - float3 transformedPosition = (mul(float4(position.xyz,1),CollisionCylinderInverseTransformations[i])).xyz; - - float3 force = float3(0,0,0); - float3 forceX = float3(0,0,0); - float3 forceY = float3(0,0,0); - - if( abs(transformedPosition.y) < 0.5 ) - { - float hmy = 0.5 - abs(transformedPosition.y); - float cpy = transformedPosition.y; - - transformedPosition.y = 0; - float l = length(transformedPosition); - if( l < 1) - { - if(cpy<0) - forceX = float3(0,-hmy,0); - else - forceX = float3(0,hmy,0); - - forceY = normalize(transformedPosition)*(1-l); - - row_major float4x4 transform = CollisionCylinderTransformations[i]; - //remove the translation - transform._41 = 0; - transform._42 = 0; - transform._43 = 0; - transform._44 = 1; - - forceX = (mul(float4(forceX,1),transform)).xyz; - forceY = (mul(float4(forceY,1),transform)).xyz; - - if(length(forceX) < length(forceY)) - force = forceX; - else - force = forceY; - } - } - - return force; -} - -//with transformed cylinders the following partitions are not exactly correct -//the boundary will favor whichever axis is longer -//check if this makes any difference in the fluid sim code and change if necessary -bool PartitionInOutBoundaryCylinder(float3 position, float boundary, int i, inout float returnVal ) -{ - //inverse transform the position - float3 transformedPosition = (mul(float4(position.xyz,1),CollisionCylinderInverseTransformations[i])).xyz; - - - if( abs(transformedPosition.y) < 0.5 ) - { - float hmy = 0.5 - abs(transformedPosition.y); - float cpy = transformedPosition.y; - - transformedPosition.y = 0; - float l = length(transformedPosition); - if( l < 1) - { - - if( hmy < 0.5 && hmy > 0 && hmy < (1-l)) - { - if(abs(hmy)>boundary) - { - returnVal = OBSTACLE_INTERIOR; - return true; - } - else - { - returnVal = OBSTACLE_BOUNDARY; - return true; - } - } - - if( (1-l) > boundary) - { - returnVal = OBSTACLE_INTERIOR; - return true; - } - else - { - returnVal = OBSTACLE_BOUNDARY; - return true; - } - } - } - - returnVal = OBSTACLE_EXTERIOR; - return false; -} - -//this assumes a height of 1 and a radius of 1 cylinder centered at the origin and aligned along the y axis -bool IsInsideCylinder(float3 position, int i) -{ - float3 transformedPosition = mul(float4(position,1),CollisionCylinderInverseTransformations[i]).xyz; - if( abs(transformedPosition.y) < 0.5 ) - { - transformedPosition.y = 0; - float l = length(transformedPosition); - if( l < 1) - return true; - } - return false; -} - -void DistanceConstraint(inout HairVertex particle0, inout HairVertex particle1, float targetDistance, float stiffness = 1.0) -{ - float3 delta = particle1.Position.xyz - particle0.Position.xyz; - float distance = max(length(delta), 1e-7); - float stretching = 1 - targetDistance / distance; - delta = stretching * delta; - float2 responsiveness = Responsiveness(particle0, particle1); - particle0.Position.xyz += responsiveness[0] * delta * stiffness; - particle1.Position.xyz -= responsiveness[1] * delta * stiffness; -} - -//this code only works with demuxed textures, not the original density texture -float Sample2DTexArray(Texture2DArray tex, float3 posInGrid) -{ - float3 texcoords = float3(posInGrid.x, posInGrid.y, posInGrid.z * g_textureDepth); - float density = abs(tex.SampleLevel(samLinearClamp,texcoords,0)).r; - return density; -} - -float3 SampleGradientTrilinear(Texture2DArray tex, float3 tc) -{ - float3 texelWidth = float3( 1.0/g_textureWidth, 1.0/g_textureHeight, 1.0/g_textureDepth ); - - #define LEFTCELL float3 (tc.x-texelWidth.x, tc.y, tc.z) - #define RIGHTCELL float3 (tc.x+texelWidth.x, tc.y, tc.z) - #define BOTTOMCELL float3 (tc.x, tc.y-texelWidth.y, tc.z) - #define TOPCELL float3 (tc.x, tc.y+texelWidth.y, tc.z) - #define DOWNCELL float3 (tc.x, tc.y, tc.z - texelWidth.z) - #define UPCELL float3 (tc.x, tc.y, tc.z + texelWidth.z) - - float texL = Sample2DTexArray( tex, LEFTCELL ); - float texR = Sample2DTexArray( tex, RIGHTCELL ); - float texB = Sample2DTexArray( tex, BOTTOMCELL ); - float texT = Sample2DTexArray( tex, TOPCELL ); - float texU = Sample2DTexArray( tex, UPCELL ); - float texD = Sample2DTexArray( tex, DOWNCELL ); - - return float3( texR - texL, texB - texT, texU - texD ); - -} - -float4 visualizeDensity(float col) -{ - if(col>g_densityThreshold) - return float4(1,0,0,1); - col /= g_densityThreshold; - return float4(col.xxx,1); -} - -//assumes x is already normalized, and x stays as it is -void GramSchmidtOrthoNormalize( float3 x, inout float3 y, inout float3 z ) -{ - y = y - dot(x,y)*x; - y = normalize(y); - - z = z - dot(x,z)*x - dot(y,z)*y; - z = normalize(z); -} - -//Vertex shaders -//add angular spring forces -HairVertexVID AddAngularForcesVS(HairVertex input , uint vertexID : SV_VertexID) -{ - HairVertexVID output; - output.Position = input.Position; - output.vid = vertexID; - return output; -} - -void addObstacleCollisionResponse(inout float4 position) -{ - int i; - - //spheres - for(i=0;i 0 ) - force *= stiffnessIncrease*6; - } - if( length(velocity)>0.5) //if velocity is very high decrease the stiffness - force *= 0.5; - - - float gravityStrength = (1-stiffness)*(1.2-0.07)+0.07; - - gravityStrength *= g_gravityStrength; - - //add wind force - if( g_bApplyHorizontalForce) - { - float4 posInGrid = mul(float4(outputPos.Position.xyz, 1), WorldToGrid ); - posInGrid.x += 0.5; - posInGrid.y += 0.5; - posInGrid.z += 0.5; - float3 texcoords = float3(posInGrid.x, 1.0-posInGrid.y, posInGrid.z); - float3 g_windForce = (g_FluidVelocityTexture.SampleLevel(samLinearClamp,texcoords,0).xyz); - g_windForce *= (1-stiffness)*(5) + 5; - force.xyz += g_windForce; - } - - //Gravity------------------------------------------------------------------------ - if( g_bAddGravity) - force.xyz += float3(0, -gravityStrength, 0); - - //original curve attractor------------------------------------------------------- - /*commenting out, this didnt work so nicely with the rest of the forces - float3 vectorToOriginal = originalPosition - particlePair.position; - float lengthToOriginal = length(vectorToOriginal); - if( lengthToOriginal>1.0) - vectorToOriginal /= lengthToOriginal; - force.xyz += vectorToOriginal*0.07; - */ - - //no move constraint-- keep the hair off the face---------------------------------- - //sphere no move constraint - //only do this to hair that are not very stiff already - - if(stiffness<0.9) - { - for(int i=0;i1.0) - vectorToOriginal /= lengthToOriginal; - - force.xyz += vectorToOriginal*0.525; - } - } - - //verlet integration - //float clampAmount = 1.0; - //velocity.xyz = clamp(velocity.xyz, float3(-clampAmount,-clampAmount,-clampAmount), float3(clampAmount,clampAmount,clampAmount) ); - outputPos.Position.xyz = particlePair.position.xyz - + velocity.xyz - + force.xyz*g_TimeStep*g_TimeStep; - - //this makes stiff hair even stiffer, and makes it go towards its base transformed pose. - //However, we only apply this force when the hair and the base transformed hair are "relatively" close. Here we have huristically decided this value to be 1.6 units - float staticky = force.w*0.0475; - if(length(outputPos.Position.xyz - transformedPos.xyz) < 1.6 ) - outputPos.Position.xyz = (1-staticky)*outputPos.Position.xyz + staticky*transformedPos.xyz; - - return outputPos; - -} - -//satisfy linear spring constraints -ConstraintsHairVertex SatisfySpringConstraintsVS(HairVertexLength input, uint vertexID : SV_VertexID) -{ - ConstraintsHairVertex output; - output.Position = input.Position; - output.vid = vertexID; - output.Length = input.Length; - return output; -} - -ConstraintsAngularHairVertex SatisfyAngularSpringConstraintsVS(HairVertexLengthStiffness input, uint vertexID : SV_VertexID) -{ - ConstraintsAngularHairVertex output; - output.Position = input.Position; - output.vid = vertexID; - output.Length = input.LengthStiffness.x; - output.Stiffness = input.LengthStiffness.y; - return output; -} - -void restoreToDefaultPositionsVS(inout HairVertex input, uint vertexID : SV_VertexID) -{ - float4 originalPosition = g_OriginalMasterStrand.Load(vertexID); - input.Position = originalPosition; -} - -//geometry shaders -float3 TransformOldVectorToNewVector( int index, float3 oldVector) -{ - float3 vM1X = g_coordinateFrames.Load(index*3).xyz; - - if(length(vM1X)<0.01) return oldVector; - - float3 vM1Y = g_coordinateFrames.Load(index*3+1).xyz; - float3 vM1Z = g_coordinateFrames.Load(index*3+2).xyz; - - float3 worldX = float3(1,0,0); - float3 worldY = float3(0,1,0); - float3 worldZ = float3(0,0,1); - - row_major float4x4 vM1ToWorld = float4x4 - ( - dot(worldX,vM1X), dot(worldY,vM1X), dot(worldZ,vM1X), 0, - dot(worldX,vM1Y), dot(worldY,vM1Y), dot(worldZ,vM1Y), 0, - dot(worldX,vM1Z), dot(worldY,vM1Z), dot(worldZ,vM1Z), 0, - 0, 0, 0, 1 - - ); - - //transform from old to new coordinate frame - float3 retVector = mul(float4(oldVector,1),vM1ToWorld).xyz; - return retVector; -} - -[MaxVertexCount(2)] -void AddAngularForcesGS(line HairVertexVID vertex[2], inout PointStream stream) -{ - HairVertex vertex0,vertex1; - vertex0.Position = vertex[0].Position; - vertex1.Position = vertex[1].Position; - - //if g_ClearForces is set, first clear the forces, and then add to them - if(g_bClearForces) - { - vertex0.Position.xyz = float3(0,0,0); - vertex1.Position.xyz = float3(0,0,0); - } - - if( vertex[0].vid == vertex[1].vid ) - { - stream.Append(vertex0); - return; - } - - float3 bPOriginal = g_OriginalVectors.Load(vertex[0].vid); - - if(length(bPOriginal)==0) //this should never happen - { - stream.Append(vertex0); - stream.Append(vertex1); - return; - } - - float4 positionV1 = g_MasterStrand.Load(vertex[0].vid); - float4 positionV2 = g_MasterStrand.Load(vertex[1].vid); - - float3 bP; - - //transform the original vector from the local coordinate frame of vertex v-1 to the world coordinate frame - bP = TransformOldVectorToNewVector(vertex[0].vid-1,bPOriginal); - //testing bP = TransformOldVectorToNewVector(vertex[0].vid,float3(1,0,0)); - - float k = vertex0.Position.w*9 + 1; //minimum stiffness is 1 and maximum is 10; empirically adjusted - - float3 b = positionV2.xyz - positionV1.xyz; - - float lengthbP = length(bP); - float lengthB = length(b); - float dotB_Bp = dot(bP,b); - float constant = k/(2*lengthbP*lengthB); - float3 bDoubleNorm = b/(lengthB*lengthB); - - vertex0.Position.xyz += constant * ( -bP + dotB_Bp*bDoubleNorm ); - vertex1.Position.xyz += constant * ( bP - dotB_Bp*bDoubleNorm ); - - - stream.Append( vertex0 ); - stream.Append( vertex1 ); -} - -[MaxVertexCount(2)] -void SatisfySpringConstraintsGS(line ConstraintsHairVertex vertex[2], inout PointStream stream) -{ - HairVertex vertex0,vertex1; - vertex0.Position = vertex[0].Position; - vertex1.Position = vertex[1].Position; - - if( vertex[0].vid == vertex[1].vid ) - { - stream.Append(vertex0); - return; - } - - DistanceConstraint(vertex0,vertex1,vertex[0].Length); - stream.Append( vertex0 ); - stream.Append( vertex1 ); -} - -[MaxVertexCount(4)] -void SatisfyAngularSpringConstraintsGS(lineadj ConstraintsAngularHairVertex vertex[4], inout PointStream stream) -{ - HairVertex vertex0,vertex1,vertex2,vertex3; - vertex0.Position = vertex[0].Position; - vertex1.Position = vertex[1].Position; - vertex2.Position = vertex[2].Position; - vertex3.Position = vertex[3].Position; - - bool firstIsReal = false; - bool secondIsReal = false; - bool thirdIsReal = false; - - if( vertex[2].vid != vertex[1].vid ) - { - secondIsReal = true; - float stiffness = vertex[0].Stiffness * g_angularStiffness; - if( stiffness>0 ) - DistanceConstraint(vertex0,vertex2, vertex[0].Length, stiffness ); - } - if( vertex[1].vid != vertex[0].vid ) - { - firstIsReal = true; - if( vertex[3].vid != vertex[2].vid ) - { - thirdIsReal = true; - float stiffness = vertex[1].Stiffness * g_angularStiffness; - if( stiffness>0 ) - DistanceConstraint(vertex1,vertex3, vertex[1].Length, stiffness ); - } - } - - stream.Append( vertex0 ); - if( firstIsReal ) - stream.Append( vertex1 ); - if( secondIsReal ) - stream.Append( vertex2 ); - if( thirdIsReal ) - stream.Append( vertex3 ); -} - -//coordinate frame update and rendering -struct coordinateFrame4 -{ - float4 xAxis : X_AXIS; - float4 yAxis : Y_AXIS; - float4 zAxis : Z_AXIS; -}; - -struct coordinateFrame4x4 -{ - coordinateFrame4 m_Arr[4]; -}; - -struct coordinateFrameAndID -{ - float3 xAxis : X_AXIS; - float3 yAxis : Y_AXIS; - float3 zAxis : Z_AXIS; - uint v : VERTEX_ID; -}; - -struct coordinateFrameRender -{ - float4 Position : SV_Position; - float3 Color : COLOR; -}; - -void rotateVector(float3 rotationAxis, float theta, float3 prevVec, inout float3 newVec) -{ - float3 axisDifference = rotationAxis - prevVec; - if( length(axisDifference) stream) -{ - coordinateFrameRender p; - - float axisScale = 0.2; - - //x-axis - p.Position = vertex; - p.Position = mul( float4(p.Position.xyz,1),ViewProjection); - p.Color = float3(1,0,0); - stream.Append(p); - - p.Position = float4(vertex.x + axisScale*cf[0].xAxis.x ,vertex.y + axisScale*cf[0].xAxis.y, vertex.z + axisScale*cf[0].xAxis.z, 1); - p.Position = mul( float4(p.Position.xyz,1),ViewProjection); - p.Color = float3(1,0,0); - stream.Append(p); - stream.RestartStrip(); - - //y-axis - p.Position = vertex; - p.Position = mul( float4(p.Position.xyz,1),ViewProjection); - p.Color = float3(0,1,0); - stream.Append(p); - - p.Position = float4(vertex.x + axisScale*cf[0].yAxis.x ,vertex.y + axisScale*cf[0].yAxis.y, vertex.z + axisScale*cf[0].yAxis.z, 1); - p.Position = mul( float4(p.Position.xyz,1),ViewProjection); - p.Color = float3(0,1,0); - stream.Append(p); - stream.RestartStrip(); - - //z-axis - p.Position = vertex; - p.Position = mul( float4(p.Position.xyz,1),ViewProjection); - p.Color = float3(0,0,1); - stream.Append(p); - p.Position = float4(vertex.x + axisScale*cf[0].zAxis.x ,vertex.y + axisScale*cf[0].zAxis.y, vertex.z + axisScale*cf[0].zAxis.z, 1); - p.Position = mul( float4(p.Position.xyz,1),ViewProjection); - p.Color = float3(0,0,1); - stream.Append(p); - stream.RestartStrip(); -} - -[MaxVertexCount(6)] -void RenderCoordinateFrameGSUnTessellated(point coordinateFrameAndID cf[1], inout LineStream stream) -{ - //load the vertex point - float4 vertex = g_MasterStrand.Load(cf[0].v); - RenderCoordinateFrameAux(cf,vertex,stream); -} - -[MaxVertexCount(6)] -void RenderCoordinateFrameGSUnTessellatedSB(point coordinateFrameAndID cf[1], inout LineStream stream) -{ - //load the vertex point - float4 vertex = g_MasterStrandSB[cf[0].v]; - RenderCoordinateFrameAux(cf,vertex,stream); -} - -[MaxVertexCount(6)] -void RenderCoordinateFrameGSTessellated(point coordinateFrameAndID cf[1], inout LineStream stream) -{ - //load the vertex point - float4 vertex = g_TessellatedMasterStrand.Load(cf[0].v); - RenderCoordinateFrameAux(cf,vertex,stream); -} - -float4 RenderCoordinateFramePS(coordinateFrameRender input) : SV_Target -{ - return float4(input.Color,1); -} - -// Hair rendering -//structs -struct HairAdjacencyVertex -{ - unsigned int controlVertexIndex : controlVertexIndex; - float u : u; -}; - -struct HairVertex2 -{ - float3 Position : Position; - float2 scalpTexcoords : SCALPTEX; - float shadow : SHADOW; - float width : Width; - float3 Tangent : Tangent; - float tex : TEXALONGLENGTH; - float dummy : MYDUMMY; // workaround for the bug in compiler (August 2009 SDK). does not compile without it - int ID : ID; -}; - -struct HairVertexPWI -{ - float3 Position : Position; - float width : Width; - int ID : ID; -}; - -struct InterpolatedSOBarycentricVertex -{ - float4 PositionAndWidth : PositionAndWidth; - float4 IdAlphaTex : IdAlphaTex; - float4 tangent : tangent; -}; -struct InterpolatedSOBarycentricVertexPosWidth -{ - float4 PositionAndWidth : PositionAndWidth; -}; -struct InterpolatedSOBarycentricVertexIDAlphaTex -{ - float4 IdAlphaTex : IdAlphaTex; -}; -struct InterpolatedSOBarycentricVertexTangent -{ - float4 tangent : tangent; -}; - -struct HairVertexPWIAT -{ - float3 Position : Position; - float width : Width; - int ID : ID; - float tex : TEXALONGLENGTH; -}; - -struct HairCollisionVertex -{ - float4 Position : SV_Position; - float3 BarycenticPosition : BPos; - float dummy : DUMMY; // added due to bug in compiler - int vertexID : VertexID; -}; - -struct HairCollisionVertexWithGS -{ - float4 Position : P; - float3 BarycenticPosition : BPos; - float dummy : DUMMY; // added due to bug in compiler - int vertexID : VertexID; -}; - -struct HairVertexCollisions -{ - float3 Position : Position; - int vertexID : vertexID; - nointerpolation float2 texcoords : TEXCOORDS; - int ID : ID; -}; - -struct HairVertex2Grid -{ - float3 Position : Position; - int ID : ID; -}; - -struct HairPoint -{ - float4 Position : SV_Position; - float3 Tangent : TANGENT; - float shadow : SHADOW; - nointerpolation float2 scalpTexcoords : SCALP_TEXCOORDS; //these texcoords stay the same over the length of the hair and are not interpolated. - float2 tex: TEXTUREACROSSSTRAND; - nointerpolation int ID : ID; -#ifndef SHADOWS_VS - float3 wPos : WorldPosition; -#endif -}; - -struct HairPoint_LINES -{ - float4 Position : SV_Position; - float3 Tangent : TANGENT; - float shadow : SHADOW; - nointerpolation float2 scalpTexcoords : SCALP_TEXCOORDS; //these texcoords stay the same over the length of the hair and are not interpolated. - nointerpolation int ID : ID; - // float3 wPos : WorldPosition; -}; - -struct HairPointDepthPrepass -{ - float4 Position : SV_Position; - float3 tex: TEXTUREACROSSSTRAND; -}; - -struct HairPointDepth -{ - float4 Position : SV_Position; - float depth : DEPTH; -}; - -struct HairPointDepthDensity -{ - float4 Position : SV_Position; - float4 posInGrid : POS_IN_GRID; -}; - -struct HairPointDepthSO -{ - float4 Position : SV_Position; - float3 wPos : WorldPosition; - float4 Positionl : Positionl; - float4 WICL : WICL; - float4 texcoords : texcoords; -}; - -struct HairPointCollisions -{ - float4 Position : SV_Position; - int vertexID : vertexID; - nointerpolation float2 texcoords : TEXCOORDS; -}; - -struct HairPointGrid -{ - float4 Position : SV_Position; - float distance : DIST; -}; - -struct simpleInPS -{ - float4 pos : SV_Position; - float3 col : COLOR0; -}; - -//vertex shaders -void Passthrough(inout HairVertex vertex) -{ -} - -//tessellation -void TessellateVSBSplinePassThrough(inout HairAdjacencyVertex input) -{ - -} - -//create coordinate frames for the tessellated hair -coordinateFrame4 TessellateVSBSplineCFs(HairAdjacencyVertex input , uint vertexID : SV_VertexID) -{ - coordinateFrame4 output; - - float4x4 basisMatrix = float4x4 - ( - -1/6.0, 3/6.0, -3/6.0, 1/6.0, - 3/6.0, -6/6.0, 3/6.0, 0, - -3/6.0, 0, 3/6.0, 0, - 1/6.0, 4/6.0, 1/6.0, 0 - ); - - float u = input.u; - coordinateFrame4x4 controlCFs; - - if(u<0) - { - u += 2; - //controlCFs.m_Arr[1].xAxis = g_coordinateFrames.Load(input.controlVertexIndex*3 ); - controlCFs.m_Arr[1].yAxis = g_coordinateFrames.Load(input.controlVertexIndex*3 + 1); - controlCFs.m_Arr[1].zAxis = g_coordinateFrames.Load(input.controlVertexIndex*3 + 2); - - //controlCFs.m_Arr[2].xAxis = g_coordinateFrames.Load((input.controlVertexIndex+1)*3 ); - controlCFs.m_Arr[2].yAxis = g_coordinateFrames.Load((input.controlVertexIndex+1)*3 + 1 ); - controlCFs.m_Arr[2].zAxis = g_coordinateFrames.Load((input.controlVertexIndex+1)*3 + 2 ); - - //controlCFs.m_Arr[3].xAxis = g_coordinateFrames.Load((input.controlVertexIndex+2)*3 ); - controlCFs.m_Arr[3].yAxis = g_coordinateFrames.Load((input.controlVertexIndex+2)*3 + 1 ); - controlCFs.m_Arr[3].zAxis = g_coordinateFrames.Load((input.controlVertexIndex+2)*3 + 2 ); - - controlCFs.m_Arr[0] = controlCFs.m_Arr[1]; - } - else if(u>1) - { - u -= 2; - //controlCFs.m_Arr[0].xAxis = g_coordinateFrames.Load((input.controlVertexIndex+1)*3); - controlCFs.m_Arr[0].yAxis = g_coordinateFrames.Load((input.controlVertexIndex+1)*3 + 1); - controlCFs.m_Arr[0].zAxis = g_coordinateFrames.Load((input.controlVertexIndex+1)*3 + 2); - - //controlCFs.m_Arr[1].xAxis = g_coordinateFrames.Load((input.controlVertexIndex+2)*3); - controlCFs.m_Arr[1].yAxis = g_coordinateFrames.Load((input.controlVertexIndex+2)*3 + 1); - controlCFs.m_Arr[1].zAxis = g_coordinateFrames.Load((input.controlVertexIndex+2)*3 + 2); - - //controlCFs.m_Arr[2].xAxis = g_coordinateFrames.Load((input.controlVertexIndex+3)*3); - controlCFs.m_Arr[2].yAxis = g_coordinateFrames.Load((input.controlVertexIndex+3)*3 + 1); - controlCFs.m_Arr[2].zAxis = g_coordinateFrames.Load((input.controlVertexIndex+3)*3 + 2); - - controlCFs.m_Arr[3] = controlCFs.m_Arr[2]; - } - else - { - //controlCFs.m_Arr[0].xAxis = g_coordinateFrames.Load((input.controlVertexIndex+0)*3); - controlCFs.m_Arr[0].yAxis = g_coordinateFrames.Load((input.controlVertexIndex+0)*3 + 1); - controlCFs.m_Arr[0].zAxis = g_coordinateFrames.Load((input.controlVertexIndex+0)*3 + 2); - - //controlCFs.m_Arr[1].xAxis = g_coordinateFrames.Load((input.controlVertexIndex+1)*3); - controlCFs.m_Arr[1].yAxis = g_coordinateFrames.Load((input.controlVertexIndex+1)*3 + 1); - controlCFs.m_Arr[1].zAxis = g_coordinateFrames.Load((input.controlVertexIndex+1)*3 + 2); - - //controlCFs.m_Arr[2].xAxis = g_coordinateFrames.Load((input.controlVertexIndex+2)*3); - controlCFs.m_Arr[2].yAxis = g_coordinateFrames.Load((input.controlVertexIndex+2)*3 + 1); - controlCFs.m_Arr[2].zAxis = g_coordinateFrames.Load((input.controlVertexIndex+2)*3 + 2); - - //controlCFs.m_Arr[3].xAxis = g_coordinateFrames.Load((input.controlVertexIndex+3)*3); - controlCFs.m_Arr[3].yAxis = g_coordinateFrames.Load((input.controlVertexIndex+3)*3 + 1); - controlCFs.m_Arr[3].zAxis = g_coordinateFrames.Load((input.controlVertexIndex+3)*3 + 2); - - } - - float4 basis = mul(float4(u * u * u, u * u, u, 1), basisMatrix); - float3 x,y,z; - - x = normalize( (g_TessellatedMasterStrand.Load(vertexID+1)).xyz - (g_TessellatedMasterStrand.Load(vertexID)).xyz); - - int c; - - y = float3(0,0,0); - y += basis[0] * controlCFs.m_Arr[0].yAxis.xyz; - y += basis[1] * controlCFs.m_Arr[1].yAxis.xyz; - y += basis[2] * controlCFs.m_Arr[2].yAxis.xyz; - y += basis[3] * controlCFs.m_Arr[3].yAxis.xyz; - - - z = float3(0,0,0); - z += basis[0] * controlCFs.m_Arr[0].zAxis.xyz; - z += basis[1] * controlCFs.m_Arr[1].zAxis.xyz; - z += basis[2] * controlCFs.m_Arr[2].zAxis.xyz; - z += basis[3] * controlCFs.m_Arr[3].zAxis.xyz; - - GramSchmidtOrthoNormalize( x, y, z ); - - output.xAxis.xyz = x; - output.yAxis.xyz = y; - output.zAxis.xyz = z; - output.xAxis.w = output.yAxis.w = output.zAxis.w = 0; - - - return output; - -} - -//create coordinate frames for the tessellated hair -coordinateFrame4 TessellateVSBSplineSBCFs(HairAdjacencyVertex input , uint vertexID : SV_VertexID) -{ - coordinateFrame4 output; - - float4x4 basisMatrix = float4x4 - ( - -1/6.0, 3/6.0, -3/6.0, 1/6.0, - 3/6.0, -6/6.0, 3/6.0, 0, - -3/6.0, 0, 3/6.0, 0, - 1/6.0, 4/6.0, 1/6.0, 0 - ); - - float u = input.u; - coordinateFrame4x4 controlCFs; - - if(u<0) - { - u += 2; - //controlCFs.m_Arr[1].xAxis = g_coordinateFramesSB[input.controlVertexIndex*3 ]; - controlCFs.m_Arr[1].yAxis = g_coordinateFramesSB[input.controlVertexIndex*3 + 1]; - controlCFs.m_Arr[1].zAxis = g_coordinateFramesSB[input.controlVertexIndex*3 + 2]; - - //controlCFs.m_Arr[2].xAxis = g_coordinateFramesSB[(input.controlVertexIndex+1)*3 ]; - controlCFs.m_Arr[2].yAxis = g_coordinateFramesSB[(input.controlVertexIndex+1)*3 + 1 ]; - controlCFs.m_Arr[2].zAxis = g_coordinateFramesSB[(input.controlVertexIndex+1)*3 + 2 ]; - - //controlCFs.m_Arr[3].xAxis = g_coordinateFramesSB[(input.controlVertexIndex+2)*3 ]; - controlCFs.m_Arr[3].yAxis = g_coordinateFramesSB[(input.controlVertexIndex+2)*3 + 1 ]; - controlCFs.m_Arr[3].zAxis = g_coordinateFramesSB[(input.controlVertexIndex+2)*3 + 2 ]; - - controlCFs.m_Arr[0] = controlCFs.m_Arr[1]; - } - else if(u>1) - { - u -= 2; - //controlCFs.m_Arr[0].xAxis = g_coordinateFramesSB[(input.controlVertexIndex+1)*3]; - controlCFs.m_Arr[0].yAxis = g_coordinateFramesSB[(input.controlVertexIndex+1)*3 + 1]; - controlCFs.m_Arr[0].zAxis = g_coordinateFramesSB[(input.controlVertexIndex+1)*3 + 2]; - - //controlCFs.m_Arr[1].xAxis = g_coordinateFramesSB[(input.controlVertexIndex+2)*3]; - controlCFs.m_Arr[1].yAxis = g_coordinateFramesSB[(input.controlVertexIndex+2)*3 + 1]; - controlCFs.m_Arr[1].zAxis = g_coordinateFramesSB[(input.controlVertexIndex+2)*3 + 2]; - - //controlCFs.m_Arr[2].xAxis = g_coordinateFramesSB[(input.controlVertexIndex+3)*3]; - controlCFs.m_Arr[2].yAxis = g_coordinateFramesSB[(input.controlVertexIndex+3)*3 + 1]; - controlCFs.m_Arr[2].zAxis = g_coordinateFramesSB[(input.controlVertexIndex+3)*3 + 2]; - - controlCFs.m_Arr[3] = controlCFs.m_Arr[2]; - } - else - { - //controlCFs.m_Arr[0].xAxis = g_coordinateFramesSB[(input.controlVertexIndex+0)*3]; - controlCFs.m_Arr[0].yAxis = g_coordinateFramesSB[(input.controlVertexIndex+0)*3 + 1]; - controlCFs.m_Arr[0].zAxis = g_coordinateFramesSB[(input.controlVertexIndex+0)*3 + 2]; - - //controlCFs.m_Arr[1].xAxis = g_coordinateFramesSB[(input.controlVertexIndex+1)*3]; - controlCFs.m_Arr[1].yAxis = g_coordinateFramesSB[(input.controlVertexIndex+1)*3 + 1]; - controlCFs.m_Arr[1].zAxis = g_coordinateFramesSB[(input.controlVertexIndex+1)*3 + 2]; - - //controlCFs.m_Arr[2].xAxis = g_coordinateFramesSB[(input.controlVertexIndex+2)*3]; - controlCFs.m_Arr[2].yAxis = g_coordinateFramesSB[(input.controlVertexIndex+2)*3 + 1]; - controlCFs.m_Arr[2].zAxis = g_coordinateFramesSB[(input.controlVertexIndex+2)*3 + 2]; - - //controlCFs.m_Arr[3].xAxis = g_coordinateFramesSB[(input.controlVertexIndex+3)*3]; - controlCFs.m_Arr[3].yAxis = g_coordinateFramesSB[(input.controlVertexIndex+3)*3 + 1]; - controlCFs.m_Arr[3].zAxis = g_coordinateFramesSB[(input.controlVertexIndex+3)*3 + 2]; - - } - - float4 basis = mul(float4(u * u * u, u * u, u, 1), basisMatrix); - float3 x,y,z; - - x = normalize( (g_TessellatedMasterStrand.Load(vertexID+1)).xyz - (g_TessellatedMasterStrand.Load(vertexID)).xyz); - - int c; - - y = float3(0,0,0); - y += basis[0] * controlCFs.m_Arr[0].yAxis.xyz; - y += basis[1] * controlCFs.m_Arr[1].yAxis.xyz; - y += basis[2] * controlCFs.m_Arr[2].yAxis.xyz; - y += basis[3] * controlCFs.m_Arr[3].yAxis.xyz; - - - z = float3(0,0,0); - z += basis[0] * controlCFs.m_Arr[0].zAxis.xyz; - z += basis[1] * controlCFs.m_Arr[1].zAxis.xyz; - z += basis[2] * controlCFs.m_Arr[2].zAxis.xyz; - z += basis[3] * controlCFs.m_Arr[3].zAxis.xyz; - - GramSchmidtOrthoNormalize( x, y, z ); - - output.xAxis.xyz = x; - output.yAxis.xyz = y; - output.zAxis.xyz = z; - output.xAxis.w = output.yAxis.w = output.zAxis.w = 0; - - return output; -} - -struct LengthVertex -{ - float Length : LENGTH; -}; - -LengthVertex TessellateVSBSplineLengths(HairAdjacencyVertex input) -{ - LengthVertex output; - output.Length = 0; - - float4x4 basisMatrix = float4x4 - ( - -1/6.0, 3/6.0, -3/6.0, 1/6.0, - 3/6.0, -6/6.0, 3/6.0, 0, - -3/6.0, 0, 3/6.0, 0, - 1/6.0, 4/6.0, 1/6.0, 0 - ); - - float u = input.u; - float4 controlVertexLengths; - - if(u<0) - { - u += 2; - controlVertexLengths[0] = controlVertexLengths[1] = g_LengthsToRoots.Load(input.controlVertexIndex); - controlVertexLengths[2] = g_LengthsToRoots.Load(input.controlVertexIndex + 1); - controlVertexLengths[3] = g_LengthsToRoots.Load(input.controlVertexIndex + 2); - } - else if(u>1) - { - u -= 2; - controlVertexLengths[0] = g_LengthsToRoots.Load(input.controlVertexIndex + 1); - controlVertexLengths[1] = g_LengthsToRoots.Load(input.controlVertexIndex + 2); - controlVertexLengths[2] = controlVertexLengths[3] = g_LengthsToRoots.Load(input.controlVertexIndex + 3); - } - else - { - controlVertexLengths[0] = g_LengthsToRoots.Load(input.controlVertexIndex ); - controlVertexLengths[1] = g_LengthsToRoots.Load(input.controlVertexIndex + 1); - controlVertexLengths[2] = g_LengthsToRoots.Load(input.controlVertexIndex + 2); - controlVertexLengths[3] = g_LengthsToRoots.Load(input.controlVertexIndex + 3); - } - - float4 basis = mul(float4(u * u * u, u * u, u, 1), basisMatrix); - [unroll] for (int c = 0; c < 4; ++c) - output.Length += basis[c] * controlVertexLengths[c]; - - return output; -} - -//interpolation -int findClosestIndex(float3 coords) -{ - int closestIndex = 0; - - if(coords.y > coords.x) - { - if(coords.z > coords.y ) - closestIndex = 2; - else - closestIndex = 1; - } - else - { - if(coords.z > coords.x ) - closestIndex = 2; - else - closestIndex = 0; - } - return closestIndex; -} - -//render the interpolated vertices into a texture to detect which of them are intersecting the collision implicits -//and what the smallest vertexID is for each strand that does intersect -//normal multistrand interpolation, no clumping -HairVertexCollisions InterpolateVSMCollisions( uint InstanceID : SV_InstanceID, uint vertexID : SV_VertexID ) -{ - HairVertexCollisions output; - - float fIndex = g_mStrandIndices.Load(InstanceID); - int index = floor(fIndex); - float3 masterStrandRoots = g_MasterStrandRootIndices.Load(index); - float4 lengths = g_MasterStrandLengths.Load( index ); - - //if we have run over hair lengths - if( (int)vertexID >= lengths.w ) - { - output.ID = -1; - return output; - } - else - output.ID = InstanceID; - - float3 coords; - coords.xy = g_StrandCoordinates.Load(output.ID & g_NumInterpolatedAttributesMinusOne); - coords.z = (1 - coords.x - coords.y); - - int3 vertexIndices; - vertexIndices[0] = floor(masterStrandRoots.x) + vertexID; - vertexIndices[1] = floor(masterStrandRoots.y) + vertexID; - vertexIndices[2] = floor(masterStrandRoots.z) + vertexID; - - float3 lengthsToRoots; - lengthsToRoots[0] = g_TessellatedLengthsToRoots.Load( vertexIndices[0] ); - lengthsToRoots[1] = g_TessellatedLengthsToRoots.Load( vertexIndices[1] ); - lengthsToRoots[2] = g_TessellatedLengthsToRoots.Load( vertexIndices[2] ); - - - //barycentric position--------------------------------------------------------------------- - float3x4 masterVertexPosition; - masterVertexPosition[0] = g_TessellatedMasterStrand.Load( vertexIndices[0] ); - masterVertexPosition[1] = g_TessellatedMasterStrand.Load( vertexIndices[1] ); - masterVertexPosition[2] = g_TessellatedMasterStrand.Load( vertexIndices[2] ); - float3 BarycenticPosition = coords.x * masterVertexPosition[0].xyz - + coords.y * masterVertexPosition[1].xyz - + coords.z * masterVertexPosition[2].xyz; - - float BarycetricLengthToRoot = coords.x * lengthsToRoots[0] - + coords.y * lengthsToRoots[1] - + coords.z * lengthsToRoots[2]; - - output.Position = BarycenticPosition; - - float fullYPixel = 1.0/g_NumTotalWisps; - float fullXPixel = 1.0/g_NumMaxStrandsPerWisp; - int interpHairNumber = frac(fIndex)*1000; //note: check that 1000 is defined in other places and checked accordingly - output.texcoords.x = interpHairNumber*fullXPixel + fullXPixel/2.0; - output.texcoords.y = 1.0 - (index*fullYPixel + fullYPixel/2.0); - - output.vertexID = vertexID; - - return output; -} - -//shadows -float4 k_v(const float k) -{ - return float4(k, k+1, k+2, k+3); -} - -float4 Ck_v(const float k) -{ - return PI * (2.0 * k_v(k) - 1.0); -} - -float Absorption(float2 texcoord, float z, int2 offset) -{ - float z0 = tShadowMap.SampleLevel(samPointClamp, texcoord, 0, offset).x; - if( z >= z0 ) - { - float d = max(z - z0, 0); - return 1 - exp(g_SigmaA * d); - //float d = clamp(g_SigmaA*(z0-z),0,1); - // return d;//1 - d; - } - return 0; -} - -float DOMContribution(float z, float2 texcoord, int2 offset) -{ - float shadow = 0; - - //read the shadow map depth - //float z0 = tHairDepthMap.SampleLevel(samPointClamp, texcoord, 0, offset); - - //read the DOM - float4 opacitySlices = tShadowMap.SampleLevel(samPointClamp, texcoord, 0, offset); - //the starting depth is embeded in the alpha channel - float z0 = opacitySlices.w; - opacitySlices *= INV_RGBA8_PRECISION_DENSITY * 2.0; - opacitySlices.w = 0; - - //compute contribution from all the layers (IMPORTANT! assuming only one texture with four slices) - float4 W = max(0, 1.0 - abs(g_Zi[0] + z0 - z) / g_Dz[0]); - shadow += dot(W, opacitySlices); - -// if(z > g_Zi[0].w + z0) shadow = opacitySlices.z; - - return min(1.0f,shadow); - -} - -float ShadowDOM(float2 texcoord, float z) -{ - float shadow = 0; - float n = 0; - [unroll]for (int dx = -SM_RADIUS; dx <= SM_RADIUS; dx+=SM_INCREMENT) - { - [unroll]for (int dy = -SM_RADIUS; dy <= SM_RADIUS; dy+=SM_INCREMENT) - { - shadow += DOMContribution(z,texcoord,int2(dx,dy)); - n++; - } - } - - shadow /= n; - //shadow = exp(-shadow*g_SigmaA); - return shadow; -} - -float ShadowPCF(float2 texcoord, float z) -{ - float shadow = 0; - float n = 0; - [unroll]for (int dx = -PCF_RADIUS; dx <= PCF_RADIUS; dx+=PCF_INCREMENT) { - [unroll]for (int dy = -PCF_RADIUS; dy <= PCF_RADIUS; dy+=PCF_INCREMENT) { - -#ifdef USE_ABSORPTION - shadow += Absorption(texcoord, z, int2(dx, dy)); -#else - shadow += tShadowMap.SampleCmpLevelZero(samShadow, texcoord, z, int2(dx, dy)); -#endif - n++; - } - } - return shadow / n; -} - -float NormalizeDepth(float z) -{ - return (z - g_ZNear) / (g_ZFar - g_ZNear) * CSM_ZMAX; -} - -float WorldToDepth(float3 wPos) -{ - float z = mul(float4(wPos, 1), mLightView).z; -#ifdef USE_CSM - return NormalizeDepth(z); -#endif - return z; - -} - -float2 WorldToLightCoord(float3 wPos) -{ - return mul(float4(wPos, 1), mLightViewProjClip2Tex).xy; -} - -//MULTISTRAND INTERPOLATION -//vertex shaders for multistrand interpolation with collision detection -//vertex shaders for rendering, depth pre-pass and shadows - -//determine position, width, ID -HairVertexPWI InterpolateVSCore0( uint InstanceID, uint vertexID, -inout int vertexIndices0_output, inout int vertexIndices1_output, inout int vertexIndices2_output, -inout float3 coords_output, inout int closestIndex_output, -inout float barycentricWeight_output, inout float clumpWeight_output, inout float2 texcoords_output, -inout float3 originalMasterStrandRoots_output, inout float lengthToRoot_output, inout float lengthsw_output) -{ - HairVertexPWI output = (HairVertexPWI)0; - - float fIndex = g_mStrandIndices.Load(InstanceID); - int index = floor(fIndex); - - float3 masterStrandRoots = g_MasterStrandRootIndices.Load(index); - float4 lengths = g_MasterStrandLengths.Load( index ); //these are the lengths in number of vertices from root - float3 originalMasterStrandRoots = g_OriginalMasterStrandRootIndices.Load(index); - - //if we have run over hair lengths - if( (int)vertexID >= lengths.w ) - { - output.ID = -1; - return output; - } - output.ID = InstanceID; - - float3 coords; - coords.xy = g_StrandCoordinates.Load(output.ID & g_NumInterpolatedAttributesMinusOne); - coords.z = (1 - coords.x - coords.y); - - //texcoords - float3x2 rootTexcoords; - rootTexcoords[0] = g_Attributes.Load( floor(originalMasterStrandRoots.x)); - rootTexcoords[1] = g_Attributes.Load( floor(originalMasterStrandRoots.y)); - rootTexcoords[2] = g_Attributes.Load( floor(originalMasterStrandRoots.z)); - float2 BaryCentricTexcoords = coords.x * rootTexcoords[0].xy - + coords.y * rootTexcoords[1].xy - + coords.z * rootTexcoords[2].xy; - - //sample the density map, and if we are over the density dont create anymore hair - float4 hairDensityThickness = densityThicknessMapBarycentric.SampleLevel(samLinear,BaryCentricTexcoords,0); - - int3 vertexIndices; - vertexIndices[0] = floor(masterStrandRoots.x) + vertexID; - vertexIndices[1] = floor(masterStrandRoots.y) + vertexID; - vertexIndices[2] = floor(masterStrandRoots.z) + vertexID; - - //length to root - //needed for clumping, tapering the ends and for texture mapping along the strand - float3 lengthsToRoots; - lengthsToRoots[0] = g_TessellatedLengthsToRoots.Load( vertexIndices[0] ); - lengthsToRoots[1] = g_TessellatedLengthsToRoots.Load( vertexIndices[1] ); - lengthsToRoots[2] = g_TessellatedLengthsToRoots.Load( vertexIndices[2] ); - - //barycentric position - float3x4 masterVertexPosition; - masterVertexPosition[0] = g_TessellatedMasterStrand.Load( vertexIndices[0] ); - masterVertexPosition[1] = g_TessellatedMasterStrand.Load( vertexIndices[1] ); - masterVertexPosition[2] = g_TessellatedMasterStrand.Load( vertexIndices[2] ); - float3 BarycenticPosition = coords.x * masterVertexPosition[0].xyz - + coords.y * masterVertexPosition[1].xyz - + coords.z * masterVertexPosition[2].xyz; - - float clumpWeight=0; - float barycentricWeight = 1.0; - - int closestIndex = findClosestIndex(coords); - - //if the hair strand below intersects an obstacle clamp to nearest guide hair - - float fullYPixel = 1.0/g_NumTotalWisps; - float fullXPixel = 1.0/g_NumMaxStrandsPerWisp; - int interpHairNumber = frac(fIndex)*100; - float2 texcoordsCollision; - texcoordsCollision.x = interpHairNumber*fullXPixel + fullXPixel/2.0; - texcoordsCollision.y = 1.0 - (index*fullYPixel + fullYPixel/2.0); - float collisions = g_CollisionsTexture.SampleLevel(samPointClamp,texcoordsCollision,0).r; - int buffer = 60; //TODO: where did this come from? - float2 texcoords; - - float BarycetricLengthToRoot = coords.x * lengthsToRoots[0] - + coords.y * lengthsToRoots[1] - + coords.z * lengthsToRoots[2]; - float lengthToRoot; - -#if 1 - if(collisions < (float)(vertexID + buffer) ) - { - float2 clumpCoordinates = g_StrandCircularCoordinates.Load(output.ID & g_NumInterpolatedAttributesMinusOne); // this is completely wrong, but it does not lead to a big visual problem. THESE COORDINATES HAVE NOTHING IN COMMON WITH THE OTHER COORDINATES THAT WE HAVE FOR MULTISTRAND. IE BOTH HAIR ARE COMPLETELT DIFFERENT - float clumpLengthToRoot = lengthsToRoots[closestIndex]; - float2 ClumpTexcoords = rootTexcoords[closestIndex]; - - //load the coordinate frames - coordinateFrame4 cf; - cf.yAxis = g_tessellatedCoordinateFrames.Load( vertexIndices[closestIndex]*3 + 1); - cf.zAxis = g_tessellatedCoordinateFrames.Load( vertexIndices[closestIndex]*3 + 2); - - //create the new position for the hair clump vertex - float radius = g_clumpWidth * (g_topWidth*(1-clumpLengthToRoot) + g_bottomWidth*clumpLengthToRoot); - float3 ClumpPosition = masterVertexPosition[closestIndex].xyz + cf.yAxis.xyz*clumpCoordinates.x*radius + cf.zAxis.xyz*clumpCoordinates.y*radius; - - clumpWeight = (vertexID - collisions + buffer)/float(buffer); - clumpWeight = clamp(clumpWeight,0,1); - clumpWeight = sin((clumpWeight-0.5)*PI)*0.5 + 0.5; - - barycentricWeight = 1.0-clumpWeight; - output.Position = BarycenticPosition*barycentricWeight + ClumpPosition*clumpWeight; - texcoords = BaryCentricTexcoords*barycentricWeight + ClumpTexcoords*clumpWeight; - lengthToRoot = BarycetricLengthToRoot*barycentricWeight + clumpLengthToRoot*clumpWeight; - } - else -#endif - { - output.Position = BarycenticPosition; - texcoords = BaryCentricTexcoords; - lengthToRoot = BarycetricLengthToRoot; - } - - if(vertexID==0) //rooting the interpolated hair - { - float3 xAxis = g_tessellatedCoordinateFrames.Load( vertexIndices[closestIndex]*3 ).xyz; - output.Position.xyz -= 0.25*xAxis; - } - - //tapering the hair--------------------------------------------------------------------------- - //modulating width by the width denoted in the densityThickness texture----------------------- - output.width = hairDensityThickness.r; - float lt = lerp( g_lt, g_lt-0.2, hairDensityThickness.r ); - if(lengthToRoot > lt) - output.width *= ( 1 + (lt*(1-g_lv)/(1-lt)) - (1-g_lv)*lengthToRoot/(1-lt) ); - - - vertexIndices0_output = vertexIndices[0]; - vertexIndices1_output = vertexIndices[1]; - vertexIndices2_output = vertexIndices[2]; - coords_output = coords; - closestIndex_output = closestIndex; - barycentricWeight_output = barycentricWeight; - clumpWeight_output = clumpWeight; - texcoords_output = texcoords; - originalMasterStrandRoots_output = originalMasterStrandRoots; - lengthToRoot_output = lengthToRoot; - lengthsw_output = lengths.w; - - return output; -} - -//determine position, width, ID, alpha and tex -HairVertexPWIAT InterpolateVSCore( uint InstanceID, uint vertexID, -inout int vertexIndices0_output, inout int vertexIndices1_output, inout int vertexIndices2_output, -inout float3 coords_output, inout int closestIndex_output, -inout float barycentricWeight_output, inout float clumpWeight_output, inout float2 texcoords_output) -{ - - //get the position, width and ID, and related values - HairVertexPWI pwi = (HairVertexPWI)0; - int3 vertexIndices; - vertexIndices[0] = vertexIndices[1] = vertexIndices[2] = 0; - float3 coords = float3(0,0,0); - int closestIndex = 0; - float barycentricWeight = 0; - float clumpWeight = 0; - float2 texcoords = float2(0,0); - float3 originalMasterStrandRoots = float3(0,0,0); - float lengthToRoot = 0; - float lengthsw = 0; - pwi = InterpolateVSCore0(InstanceID,vertexID,vertexIndices[0],vertexIndices[1],vertexIndices[2],coords,closestIndex,barycentricWeight,clumpWeight,texcoords,originalMasterStrandRoots,lengthToRoot,lengthsw); - - - HairVertexPWIAT output; - output.Position = pwi.Position; - output.width = pwi.width; - output.ID = pwi.ID; - output.tex = 0; - if(output.ID < 0 ) - return output; - - - float3 totalLengths; - totalLengths[0] = g_Lengths.Load( originalMasterStrandRoots.x ); - totalLengths[1] = g_Lengths.Load( originalMasterStrandRoots.y ); - totalLengths[2] = g_Lengths.Load( originalMasterStrandRoots.z ); - - float BarycentricTotalLength = coords.x * totalLengths[0] - + coords.y * totalLengths[1] - + coords.z * totalLengths[2]; - float clumpTotalLength = totalLengths[closestIndex]; - float totalLength = BarycentricTotalLength*barycentricWeight + clumpTotalLength*clumpWeight; - - //this texture goes from 0 to 1 for the longest hair in the hairstyle. - //lengthToRoot is the fractional distance of the current vertex from the root counted in number of vertices - //totalLength is the actual total length of the strand - //g_maxLengthToRoot is the total length of the longest strand - output.tex = lengthToRoot*totalLength/g_maxLengthToRoot; - - - //thinning the hair lengths--------------------------------------------------------------------- - float inLengthFrac = g_StrandLengths.Load(output.ID & g_NumInterpolatedAttributesMinusOne); - float maxLength = 1.0-g_thinning + g_thinning*inLengthFrac; - - if( ( int(lengthToRoot*lengthsw) > int(maxLength*lengthsw) + 1 ) || ((int)vertexID > int(lengthsw) - 1) ) - { output.ID = -1; - return output; - } - if( (lengthToRoot > maxLength) || ((int)vertexID == int(lengthsw)-1) ) - output.width = EPSILON; - - - vertexIndices0_output = vertexIndices[0]; - vertexIndices1_output = vertexIndices[1]; - vertexIndices2_output = vertexIndices[2]; - coords_output = coords; - closestIndex_output = closestIndex; - barycentricWeight_output = barycentricWeight; - clumpWeight_output = clumpWeight; - texcoords_output = texcoords; - - return output; -} - -HairVertexPWIAT InterpolateVSDepthPrepass( uint InstanceID : SV_InstanceID, uint vertexID : SV_VertexID ) -{ - int vertexIndices[3] = {0,0,0}; - float3 coords = 0; - int closestIndex = 0; - float barycentricWeight = 0, clumpWeight = 0; - float2 texcoords = 0; - return InterpolateVSCore(InstanceID,vertexID,vertexIndices[0],vertexIndices[1],vertexIndices[2],coords,closestIndex,barycentricWeight,clumpWeight,texcoords); -} - -HairVertexPWI InterpolateVSBMultiStrandDepthShadows( uint InstanceID : SV_InstanceID, uint vertexID : SV_VertexID ) -{ - int vertexIndices[3]; - float3 coords; - int closestIndex; - float barycentricWeight; - float clumpWeight; - float2 texcoords; - float3 originalMasterStrandRoots; - float lengthToRoot; - float lengthsw; - return InterpolateVSCore0(InstanceID,vertexID,vertexIndices[0],vertexIndices[1],vertexIndices[2],coords,closestIndex,barycentricWeight,clumpWeight,texcoords,originalMasterStrandRoots,lengthToRoot,lengthsw); -} - -HairVertex2 InterpolateVSBarycentricTotalCore( uint InstanceID, uint vertexID ) -{ - HairVertexPWIAT outputDepth; - int vertexIndices[3]; - vertexIndices[0] = vertexIndices[1] = vertexIndices[2] = 0; - float3 coords = float3(0,0,0); - int closestIndex = 0; - float barycentricWeight = 0; - float clumpWeight = 0; - float2 texcoords = float2(0,0); - outputDepth = InterpolateVSCore(InstanceID,vertexID,vertexIndices[0],vertexIndices[1],vertexIndices[2],coords,closestIndex,barycentricWeight,clumpWeight,texcoords); - - HairVertex2 output = (HairVertex2)0; - output.Position = outputDepth.Position; - output.width = outputDepth.width; - output.ID = outputDepth.ID; - output.tex = outputDepth.tex; - output.Tangent = float3(0,0,0); - output.scalpTexcoords = 0; - output.shadow = 0; - if(output.ID < 0 ) - return output; - - float3x4 masterVertexTangents; - masterVertexTangents[0] = g_TessellatedTangents.Load( vertexIndices[0] ); - masterVertexTangents[1] = g_TessellatedTangents.Load( vertexIndices[1] ); - masterVertexTangents[2] = g_TessellatedTangents.Load( vertexIndices[2] ); - float3 BarycentricTangent = coords.x * masterVertexTangents[0].xyz - + coords.y * masterVertexTangents[1].xyz - + coords.z * masterVertexTangents[2].xyz; - float3 ClumpTangent = masterVertexTangents[closestIndex].xyz; //NOTE: we are loading from float3x4 - why are we doing a .xyz qualification here? - output.Tangent = BarycentricTangent*barycentricWeight + ClumpTangent*clumpWeight; - output.Tangent = normalize(output.Tangent); - - output.scalpTexcoords = texcoords; - - return output; -} - -struct HS_CONTROL_POINT_OUTPUT_INTERP_B -{ - float3 tessellatedPosition : POSITION; - float4 tessellatedTangent : TANGENT; - float tessellatedLengthToRoot : LENGTHTOROOT; -}; - -struct HS_CONTROL_POINTDEPTH_OUTPUT_INTERP_B -{ - float3 tessellatedPosition : POSITION; - float tessellatedLengthToRoot : LENGTHTOROOT; -}; - -struct HS_CONTROL_POINTCOLLISIONS_OUTPUT_INTERP_B -{ - float3 tessellatedPosition : POSITION; -}; - -//this is a version of multistrand interpolation that takes all the vertex information as given, but does calculations only for a collisions, which needs only position and ID -HairCollisionVertex InterpolateVSBarycentricCollisions_withInput(HS_CONTROL_POINTCOLLISIONS_OUTPUT_INTERP_B vertex0, HS_CONTROL_POINTCOLLISIONS_OUTPUT_INTERP_B vertex1, HS_CONTROL_POINTCOLLISIONS_OUTPUT_INTERP_B vertex2, float4 lengths, float totalLengths[3], float2 rootTexcoords0, float2 rootTexcoords1, float2 rootTexcoords2, uint vertexID, uint InstanceID) -{ - HairCollisionVertex output = (HairCollisionVertex)0; - float fIndex = g_mStrandIndices.Load(InstanceID); - int index = floor(fIndex); - - //check if we are over the hair length, or if we are culled due to density-------------------------------------- - //if we have run over hair lengths, cull - if( (float)vertexID >= lengths.w || vertexID < 2) - { - output.Position = float4(0,0,-1000,1.0); - return output; - } - - int ID = InstanceID; - - float3 coords; - coords.xy = g_StrandCoordinates.Load(ID & g_NumInterpolatedAttributesMinusOne); - coords.z = (1 - coords.x - coords.y); - - //y: the wisp number - float fullYPixel = 2.0/g_NumTotalWisps; - float yPos = -1 + index*fullYPixel + fullYPixel/2.0; - - //x: the interpolated hair number - int interpHairNumber = frac(fIndex)*100; - float fullXPixel = 2.0/g_NumMaxStrandsPerWisp; - float xPos = -1 + interpHairNumber*fullXPixel + fullXPixel/2.0; - - //barycentric position--------------------------------------------------- - float3 BarycenticPosition = coords.x * vertex0.tessellatedPosition.xyz - + coords.y * vertex1.tessellatedPosition.xyz - + coords.z * vertex2.tessellatedPosition.xyz; - - output.Position = float4(xPos,yPos,0.5,1.0); - output.BarycenticPosition = BarycenticPosition; - output.vertexID = vertexID; - - return output; -} - -HairVertex2 InterpolateVSMultiStrand( uint InstanceID : SV_InstanceID, uint vertexID : SV_VertexID ) -{ - return InterpolateVSBarycentricTotalCore(InstanceID,vertexID); -} - -InterpolatedSOBarycentricVertex InterpolateVSMultiStrand_SO(uint vertexID : SV_VertexID ) -{ - HairVertex2 hairvert = InterpolateVSBarycentricTotalCore - (vertexID/g_TessellatedMasterStrandLengthMax,vertexID%g_TessellatedMasterStrandLengthMax); - - InterpolatedSOBarycentricVertex output; - output.PositionAndWidth = float4(hairvert.Position,hairvert.width); - output.IdAlphaTex = float4(asfloat(hairvert.ID),1,hairvert.tex,hairvert.scalpTexcoords.x); - output.tangent = float4(hairvert.Tangent,hairvert.scalpTexcoords.y); - return output; -} - -struct HS_CONSTANT_DATA_OUTPUT -{ - float Edges[2] : SV_TessFactor; - float2 texcoords : CCC; - float totalLength : DDD; - float hairDensity : EEE; - int nHairsBefore : HAIRS_BEFORE; - int tessellatedMasterStrandRootIndex : BBB; - int MasterStrandLength : AAA; -}; -struct BARY_HS_CONSTANT_DATA_OUTPUT -{ - float Edges[2] : SV_TessFactor; - int nHairsBefore : AAA; - float3 masterStrandRoots : BBB; - float lengthsw : DDD; - float3x2 rootTexcoords : FFF; - float3 totalLengths : GGG; -}; -struct BARYDEPTH_HS_CONSTANT_DATA_OUTPUT -{ - float Edges[2] : SV_TessFactor; - int nHairsBefore : AAA; - float3 masterStrandRoots : BBB; - float lengthsw : DDD; - float3x2 rootTexcoords : FFF; -}; -struct BARYCOLLISIONS_HS_CONSTANT_DATA_OUTPUT -{ - float Edges[2] : SV_TessFactor; - int nHairsBefore : AAA; - float3 masterStrandRoots : BBB; -}; - -static const int NHAIRS_PER_PATCH = 64; -int g_iFirstPatchHair; -// if length of hair is more than 64 verts, we are rendering it using several patches (subhairs) -int g_iSubHairFirstVert; // this is index of first subshair vertex inside hair -static const int NSEGMENTS_PER_PATCH = 64; // this is number of subhair segments - -struct DUMMY -{ - float dummy : DUMMY; -}; - -DUMMY InterpolateVS_DUMMY11() -{ - DUMMY dummy; - dummy.dummy = 0; - return dummy; -} - -HairVertex2 InterpolateVSMultiStrand_LOAD(uint index : SV_VertexID ) -{ - HairVertex2 output = (HairVertex2)0; - - float4 PositionAndWidth = g_InterpolatedPositionAndWidth.Load(index); - float4 IdAlphaTex = g_InterpolatedIdAlphaTex.Load(index); - float4 tangent = g_Interpolatedtangent.Load(index); - - - output.Position = PositionAndWidth.xyz; - if(g_bApplyAdditionalRenderingTransform) - output.Position.xyz = mul( float4(output.Position.xyz,1.0),additionalTransformation).xyz; - - output.scalpTexcoords = float2(IdAlphaTex.w,tangent.w); - - #ifdef SHADOWS_VS - if(g_useShadows) - { - float3 Pos = mul(float4(output.Position.xyz, 1), HairToWorldTransform).xyz; - float2 texcoords = WorldToLightCoord(Pos); - float z = WorldToDepth(Pos); - //TO DO SHADOWS: incorporate the HairToWorldTransform in mLightViewProjClip2Tex float2 texcoords = WorldToLightCoord(output.Position.xyz); - //TO DO SHADOWS: incorporate the HairToWorldTransform in mLightView float z = WorldToDepth(output.Position.xyz); - output.shadow = ShadowPCF(texcoords, z); - } - else - output.shadow = 0; - #endif - - output.width = PositionAndWidth.w; - output.Tangent = tangent.xyz; - output.ID = asint(IdAlphaTex.x); - output.tex = IdAlphaTex.z; - return output; -} - -HairVertexPWI InterpolateVSMultiStrandDepthShadows_LOAD(uint index : SV_VertexID) -{ - HairVertexPWI output; - - float4 PositionAndWidth = g_InterpolatedPositionAndWidth.Load(index); - float4 IdAlphaTex = g_InterpolatedIdAlphaTex.Load(index); - - output.Position = PositionAndWidth.xyz; - if(g_bApplyAdditionalRenderingTransform) - output.Position.xyz = mul( float4(output.Position.xyz,1.0),additionalTransformation).xyz; - - output.width = PositionAndWidth.w; - output.ID = asint(IdAlphaTex.x); - - return output; -} - -HairVertexPWIAT InterpolateVSDepthPrepass_LOAD(uint index : SV_VertexID ) -{ - HairVertexPWIAT output; - float4 PositionAndWidth = g_InterpolatedPositionAndWidth.Load(index); - float4 IdAlphaTex = g_InterpolatedIdAlphaTex.Load(index); - - output.Position = PositionAndWidth.xyz; - if(g_bApplyAdditionalRenderingTransform) - output.Position.xyz = mul( float4(output.Position.xyz,1.0),additionalTransformation).xyz; - output.width = PositionAndWidth.w; - output.ID = asint(IdAlphaTex.x); - output.tex = IdAlphaTex.z ; - - return output; -} - -HairPoint HairRenderInterpolatedCoreVS( uint vertexID, uint InstanceID, -Buffer InterpolatedPositionAndWidth, Buffer InterpolatedIdAlphaTex, Buffer Interpolatedtangent, float widthMult) -{ - - int index; - bool odd = false; - if((vertexID&1)==0) - { - odd = false; - index = InstanceID*g_TessellatedMasterStrandLengthMax + int(vertexID/2); - } - else - { - odd = true; - index = InstanceID*g_TessellatedMasterStrandLengthMax + int((vertexID-1)/2); - } - - float4 PositionAndWidth = InterpolatedPositionAndWidth.Load(index); - float4 IdAlphaTex = InterpolatedIdAlphaTex.Load(index); - float4 vTangent = Interpolatedtangent.Load(index); - - HairPoint hairPoint = (HairPoint)0; - hairPoint.scalpTexcoords = float2(IdAlphaTex.w,vTangent.w); - - #ifdef SHADOWS_VS - if(g_useShadows) - { - float3 Pos = mul(float4(PositionAndWidth.xyz, 1), HairToWorldTransform).xyz; - float2 texcoords = WorldToLightCoord(Pos); - float z = WorldToDepth(Pos); - //TO DO SHADOWS: incorporate the HairToWorldTransform in mLightViewProjClip2Tex float2 texcoords = WorldToLightCoord(output.Position.xyz); - //TO DO SHADOWS: incorporate the HairToWorldTransform in mLightView float z = WorldToDepth(output.Position.xyz); - hairPoint.shadow = ShadowPCF(texcoords, z); - } - else - hairPoint.shadow = 0; - #endif - - - int ID = asint(IdAlphaTex.x); - hairPoint.ID = ID; - - float strandWidth = g_StrandSizes.Load(ID & g_NumInterpolatedAttributesMinusOne) * widthMult; - float3 worldPos = PositionAndWidth.xyz; - float3 eyeVec = TransformedEyePosition - worldPos; - float3 sideVec = normalize(cross(eyeVec, vTangent.xyz)); - hairPoint.Tangent = vTangent.xyz; - - float3 pos; - if(!odd) - { - pos = worldPos - sideVec * 0.5 * strandWidth * PositionAndWidth.w; - hairPoint.tex = float2(0,IdAlphaTex.z); - } - else - { - pos = worldPos + sideVec * 0.5 * strandWidth * PositionAndWidth.w; - hairPoint.tex = float2(1,IdAlphaTex.z); - } - -#ifndef SHADOWS_VS - hairPoint.wPos = pos; -#endif - hairPoint.Position = mul( float4(pos,1.0),ViewProjection); - - - return hairPoint; - -} - -HairPointDepth HairShadowsInterpolatedCoreVS( uint vertexID, uint InstanceID, Buffer InterpolatedPositionAndWidth, -Buffer InterpolatedIdAlphaTex, Buffer Interpolatedtangent) -{ - int index; - bool odd = false; - if((vertexID&1)==0) - { - odd = false; - index = InstanceID*g_TessellatedMasterStrandLengthMax + vertexID/2; - } - else - { - odd = true; - index = InstanceID*g_TessellatedMasterStrandLengthMax + (vertexID-1)/2; - } - - float4 PositionAndWidth = InterpolatedPositionAndWidth.Load(index); - float4 vTangent = Interpolatedtangent.Load(index); - int ID = InstanceID; - - float strandWidth = g_StrandSizes.Load(ID & g_NumInterpolatedAttributesMinusOne) * g_widthMulB; - float3 worldPos = PositionAndWidth.xyz; - float3 tangent = vTangent.xyz; //using the tangent of the vertex rather than calculating v1-v0 - float3 eyeVec = TransformedEyePosition - worldPos; - float3 sideVec = normalize(cross(eyeVec, tangent)); - - float3 pos; - if(!odd) - pos = worldPos - sideVec * 0.5 * strandWidth * PositionAndWidth.w; - else - pos = worldPos + sideVec * 0.5 * strandWidth * PositionAndWidth.w; - - float3 Pos = mul(float4(pos, 1), HairToWorldTransform).xyz; - HairPointDepth hairPoint; - hairPoint.depth = mul(float4(Pos, 1), mLightView).z; - #ifdef USE_CSM - hairPoint.depth = NormalizeDepth(hairPoint.depth); - #endif - hairPoint.Position = mul(float4(Pos, 1), ViewProjection); - - return hairPoint; -} - -HairPointDepthPrepass HairDepthPrepassInterpolatedCoreVS( uint vertexID, uint InstanceID, Buffer InterpolatedPositionAndWidth, -Buffer InterpolatedIdAlphaTex, Buffer Interpolatedtangent) -{ - int index; - bool odd = false; - if((vertexID&1)==0) - { - odd = false; - index = InstanceID*g_TessellatedMasterStrandLengthMax + int(vertexID/2); - } - else - { - odd = true; - index = InstanceID*g_TessellatedMasterStrandLengthMax + int((vertexID-1)/2); - } - - float4 PositionAndWidth = InterpolatedPositionAndWidth.Load(index); - float4 IdAlphaTex = InterpolatedIdAlphaTex.Load(index); - float4 vTangent = Interpolatedtangent.Load(index); - - HairPointDepthPrepass hairPoint = (HairPointDepthPrepass)0; - int ID = asint(IdAlphaTex.x); - - float strandWidth = g_StrandSizes.Load(ID & g_NumInterpolatedAttributesMinusOne) * g_widthMul; - float3 worldPos = PositionAndWidth.xyz; - float3 tangent = vTangent.xyz; //using the tangent of the vertex rather than calculating v1-v0 - float3 eyeVec = TransformedEyePosition - worldPos; - float3 sideVec = normalize(cross(eyeVec, tangent)); - - float3 pos; - if(!odd) - { - pos = worldPos - sideVec * 0.5 * strandWidth * PositionAndWidth.w; - hairPoint.tex = float3(0,IdAlphaTex.z,ID & 3); - } - else - { - pos = worldPos + sideVec * 0.5 * strandWidth * PositionAndWidth.w; - hairPoint.tex = float3(1,IdAlphaTex.z,ID & 3); - } - - hairPoint.Position = mul( float4(pos,1.0),ViewProjection); - - return hairPoint; - -} - -HairCollisionVertex InterpolateVSMultiStrandCollisions( uint InstanceID : SV_InstanceID, uint vertexID : SV_VertexID ) -{ - HairCollisionVertex output = (HairCollisionVertex)0; - float fIndex = g_mStrandIndices.Load(InstanceID); - int index = floor(fIndex); - - - //check if we are over the hair length, or if we are culled due to density-------------------------------------- - float3 masterStrandRoots = g_MasterStrandRootIndices.Load(index); - float4 lengths = g_MasterStrandLengths.Load( index ); //these are the lengths in number of vertices from root - float3 originalMasterStrandRoots = g_OriginalMasterStrandRootIndices.Load(index); - //if we have run over hair lengths, cull - if( (float)vertexID >= lengths.w || vertexID < 2) - { - output.Position = float4(0,0,-1000,1.0); - return output; - } - int ID = InstanceID; - float3 coords; - coords.xy = g_StrandCoordinates.Load(ID & g_NumInterpolatedAttributesMinusOne); - coords.z = (1 - coords.x - coords.y); - float3x2 rootTexcoords; - rootTexcoords[0] = g_Attributes.Load( floor(originalMasterStrandRoots.x)); - rootTexcoords[1] = g_Attributes.Load( floor(originalMasterStrandRoots.y)); - rootTexcoords[2] = g_Attributes.Load( floor(originalMasterStrandRoots.z)); - float2 BaryCentricTexcoords = coords.x * rootTexcoords[0].xy - + coords.y * rootTexcoords[1].xy - + coords.z * rootTexcoords[2].xy; - //sample the density map, and if we are over the density dont create anymore hair - float4 hairDensityThickness = densityThicknessMapBarycentric.SampleLevel(samLinear,BaryCentricTexcoords,0); - - - //y: the wisp number - float fullYPixel = 2.0/g_NumTotalWisps; - float yPos = -1 + index*fullYPixel + fullYPixel/2.0; - - //x: the interpolated hair number - int interpHairNumber = frac(fIndex)*100; - float fullXPixel = 2.0/g_NumMaxStrandsPerWisp; - float xPos = -1 + interpHairNumber*fullXPixel + fullXPixel/2.0; - - //barycentric position--------------------------------------------------------------------- - int3 vertexIndices; - vertexIndices[0] = floor(masterStrandRoots.x) + min(vertexID,lengths.x); - vertexIndices[1] = floor(masterStrandRoots.y) + min(vertexID,lengths.y); - vertexIndices[2] = floor(masterStrandRoots.z) + min(vertexID,lengths.z); - float3x4 masterVertexPosition; - masterVertexPosition[0] = g_TessellatedMasterStrand.Load( vertexIndices[0] ); - masterVertexPosition[1] = g_TessellatedMasterStrand.Load( vertexIndices[1] ); - masterVertexPosition[2] = g_TessellatedMasterStrand.Load( vertexIndices[2] ); - float3 BarycenticPosition = coords.x * masterVertexPosition[0].xyz - + coords.y * masterVertexPosition[1].xyz - + coords.z * masterVertexPosition[2].xyz; - - output.Position = float4(xPos,yPos,0.5,1.0); - output.vertexID = vertexID; - output.BarycenticPosition = BarycenticPosition; - - return output; -} - -//SINGLESTRAND BASED INTERPOLATION -//vertex shaders for singlestrand based interpolation -//vertex shaders for rendering, depth pre-pass and shadows - -//calculate the position, width and ID -HairVertexPWI InterpolateVSClumpCore0( uint InstanceID, uint vertexID, inout int vertexIndexOut, -inout float2 texcoordsOut, inout int MasterStrandNumberOut, inout float lengthToRootOut, inout int MasterStrandLengthOut ) -{ - HairVertexPWI output = (HairVertexPWI)0; - float fIndex = g_sStrandIndices.Load(InstanceID); - int MasterStrandNumber = floor(fIndex); - int outputID = InstanceID; - - int tessellatedMasterStrandRootIndex; - if(MasterStrandNumber==0) - tessellatedMasterStrandRootIndex = 0; - else - tessellatedMasterStrandRootIndex = g_tessellatedMasterStrandRootIndex.Load(MasterStrandNumber-1); - int MasterStrandLength = g_tessellatedMasterStrandRootIndex.Load(MasterStrandNumber) - tessellatedMasterStrandRootIndex; - - //If the current vertexID is more than master strand length then return - if((int)vertexID > MasterStrandLength-2) - { - output.ID = -1; - return output; - } - - float2 texcoords = g_Attributes.Load(MasterStrandNumber); - - //-------------------------------------------------------------------------------------------- - //sample the density map, and if we are over the density dont create anymore hair - float4 hairDensityThickness = densityThicknessMapClump.SampleLevel(samLinear,texcoords,0); - - int vertexIndex = tessellatedMasterStrandRootIndex+vertexID; - float lengthToRoot = g_TessellatedLengthsToRoots.Load( vertexIndex ); - float2 clumpCoordinates = g_StrandCircularCoordinates.Load(outputID & g_NumInterpolatedAttributesMinusOne); - float4 masterVertexPosition = g_TessellatedMasterStrand.Load(vertexIndex); - - //jitter the position slightly - float2 jitter = g_strandDeviations.Load((outputID & g_NumInterpolatedAttributesMinusOne) * g_TessellatedMasterStrandLengthMax + vertexID); - - if(g_doCurlyHair) - jitter += g_curlDeviations.Load(MasterStrandNumber*g_TessellatedMasterStrandLengthMax + vertexID); - - clumpCoordinates += jitter; - - //modulating width by the width denoted in the densityThickness texture---------------------- - output.width = hairDensityThickness.r; - - //load the coordinate frames - coordinateFrame4 cf; - cf.yAxis = g_tessellatedCoordinateFrames.Load( vertexIndex*3 + 1); - cf.zAxis = g_tessellatedCoordinateFrames.Load( vertexIndex*3 + 2); - - output.ID = outputID; - - //create the new position for the hair clump vertex - float radius = g_clumpWidth * ( g_topWidth*(1-lengthToRoot) + g_bottomWidth*lengthToRoot ); - output.Position.xyz = masterVertexPosition.xyz + cf.yAxis.xyz*clumpCoordinates.x*radius + cf.zAxis.xyz*clumpCoordinates.y*radius; - - if(vertexID==0) - { - cf.xAxis = g_tessellatedCoordinateFrames.Load( vertexIndex*3 ); - output.Position.xyz -= 0.25*cf.xAxis.xyz; - } - - vertexIndexOut = vertexIndex; - texcoordsOut = texcoords; - MasterStrandNumberOut = MasterStrandNumber; - lengthToRootOut = lengthToRoot; - MasterStrandLengthOut = MasterStrandLength; - - return output; -} - -//calculate the position, width, ID, alpha and texture -HairVertexPWIAT InterpolateVSClumpCore(uint InstanceID, uint vertexID, inout int vertexIndexOut, inout float2 texcoordsOut) -{ - - HairVertexPWI pwi; - int vertexIndex = 0; - float2 texcoords = float2(0,0); - float lengthToRoot = 0; - int MasterStrandNumber = 0; - int MasterStrandLength = 0; - pwi = InterpolateVSClumpCore0(InstanceID,vertexID,vertexIndex,texcoords,MasterStrandNumber,lengthToRoot,MasterStrandLength); - - HairVertexPWIAT output = (HairVertexPWIAT)0; - output.Position = pwi.Position; - output.width = pwi.width; - output.ID = pwi.ID; - if(output.ID<0) - return output; - - float totalLength = g_Lengths.Load( MasterStrandNumber ); - - //thinning the hair lengths - float inLengthFrac = g_StrandLengths.Load(output.ID & g_NumInterpolatedAttributesMinusOne); - float maxLength = 1.0-g_thinning + g_thinning*inLengthFrac; - - if( ( int(lengthToRoot*MasterStrandLength) > int(maxLength*MasterStrandLength) + 1 ) || ((int)vertexID > MasterStrandLength-2) ) - { output.ID = -1; - return output; - } - if( (lengthToRoot > maxLength) || ((int)vertexID == MasterStrandLength-2) ) - output.width = EPSILON; - - - //tapering the hair - float lt = g_lt*maxLength; - if(lengthToRoot > lt) - output.width *= ( 1 + (lt*(1-g_lv)/(1-lt)) - (1-g_lv)*lengthToRoot/(1-lt) ); - - //this texture goes from 0 to 1 for the longest hair in the hairstyle. - //lengthToRoot is the fractional distance of the current vertex from the root counted in number of vertices - //totalLength is the actual total length of the strand - //g_maxLengthToRoot is the real total length of the longest strand - output.tex = lengthToRoot*totalLength/g_maxLengthToRoot; - - - vertexIndexOut = vertexIndex; - texcoordsOut = texcoords; - - return output; -} - -HairVertex2 InterpolateVSClumpTotalCore(uint InstanceID, uint vertexID) -{ - HairVertexPWIAT outputDepth; - int vertexIndex = 0; - float2 texcoords = float2(0,0); - outputDepth = InterpolateVSClumpCore(InstanceID,vertexID,vertexIndex,texcoords); - - HairVertex2 output = (HairVertex2)0; - output.Position = outputDepth.Position; - output.width = outputDepth.width; - output.ID = outputDepth.ID; - output.tex = outputDepth.tex; - output.Tangent = float3(0,0,0); - output.scalpTexcoords = 0; - output.shadow = 0; - if(output.ID<0) - return output; - - //tangent - output.Tangent.xyz = normalize((g_TessellatedTangents.Load(vertexIndex)).xyz); - - //texcoords - output.scalpTexcoords = texcoords; - - return output; -} - -// each hull shader processes strands belonging to the same master strand -BARY_HS_CONSTANT_DATA_OUTPUT InterpolateConstHSMultiStrand(uint iWisp : SV_PrimitiveID) -{ - BARY_HS_CONSTANT_DATA_OUTPUT output; - - // how many c-strands accompany this master strand? - output.nHairsBefore = g_iFirstPatchHair; - if (iWisp > 0) - { - output.nHairsBefore += g_MStrandsPerWispCumulative.Load(iWisp - 1); - } - output.Edges[0] = min(NHAIRS_PER_PATCH, g_MStrandsPerWispCumulative.Load(iWisp) - output.nHairsBefore); - float4 lengths = g_MasterStrandLengths.Load(iWisp); //these are the lengths in number of vertices from root - output.lengthsw = lengths.w; - int iSegmentsToGo = (int)lengths.w - 1 - g_iSubHairFirstVert; - output.Edges[1] = min(iSegmentsToGo, NSEGMENTS_PER_PATCH); - output.masterStrandRoots = g_MasterStrandRootIndices.Load(iWisp); - float3 originalMasterStrandRoots = g_OriginalMasterStrandRootIndices.Load(iWisp); - output.rootTexcoords[0] = g_Attributes.Load( floor(originalMasterStrandRoots.x)); - output.rootTexcoords[1] = g_Attributes.Load( floor(originalMasterStrandRoots.y)); - output.rootTexcoords[2] = g_Attributes.Load( floor(originalMasterStrandRoots.z)); - output.totalLengths[0] = g_Lengths.Load( originalMasterStrandRoots.x ); - output.totalLengths[1] = g_Lengths.Load( originalMasterStrandRoots.y ); - output.totalLengths[2] = g_Lengths.Load( originalMasterStrandRoots.z ); - - // dynamic LOD in number of hairs - output.Edges[0] = max(output.Edges[0] * g_fNumHairsLOD, 1); - - return output; -} - -[domain("isoline")] -[partitioning("integer")] -[outputtopology("line")] -[outputcontrolpoints(1)] -[patchconstantfunc("InterpolateConstHSMultiStrand")] -void InterpolateHSMultiStrand(InputPatch inputPatch) -{ -} - -// each hull shader processes c-strands belonging to the same master strand -BARYDEPTH_HS_CONSTANT_DATA_OUTPUT InterpolateConstHSMultiStrandDepth(uint iWisp : SV_PrimitiveID) -{ - BARYDEPTH_HS_CONSTANT_DATA_OUTPUT output; - - output.nHairsBefore = g_iFirstPatchHair; - if (iWisp > 0) - { - output.nHairsBefore += g_MStrandsPerWispCumulative.Load(iWisp - 1); - } - output.Edges[0] = min(NHAIRS_PER_PATCH, g_MStrandsPerWispCumulative.Load(iWisp) - output.nHairsBefore); - float4 lengths = g_MasterStrandLengths.Load(iWisp); //these are the lengths in number of vertices from root - output.lengthsw = lengths.w; - int iSegmentsToGo = (int)lengths.w - 1 - g_iSubHairFirstVert; - output.Edges[1] = min(iSegmentsToGo, NSEGMENTS_PER_PATCH); - output.masterStrandRoots = g_MasterStrandRootIndices.Load(iWisp); - float3 originalMasterStrandRoots = g_OriginalMasterStrandRootIndices.Load(iWisp); - output.rootTexcoords[0] = g_Attributes.Load( floor(originalMasterStrandRoots.x)); - output.rootTexcoords[1] = g_Attributes.Load( floor(originalMasterStrandRoots.y)); - output.rootTexcoords[2] = g_Attributes.Load( floor(originalMasterStrandRoots.z)); - - // dynamic LOD in number of hairs - output.Edges[0] = max(output.Edges[0] * g_fNumHairsLOD, 1); - - return output; -} - -[domain("isoline")] -[partitioning("integer")] -[outputtopology("line")] -[outputcontrolpoints(1)] -[patchconstantfunc("InterpolateConstHSMultiStrandDepth")] -void InterpolateHSMultiStrandDepth(InputPatch inputPatch) -{ -} - -// each hull shader processes c-strands belonging to the same master strand -BARYCOLLISIONS_HS_CONSTANT_DATA_OUTPUT InterpolateConstHSMultiStrandCollisions(uint iWisp : SV_PrimitiveID) -{ - BARYCOLLISIONS_HS_CONSTANT_DATA_OUTPUT output; - - output.nHairsBefore = g_iFirstPatchHair; - if (iWisp > 0) - { - output.nHairsBefore += g_MStrandsPerWispCumulative.Load(iWisp - 1); - } - output.Edges[0] = min(NHAIRS_PER_PATCH, g_MStrandsPerWispCumulative.Load(iWisp) - output.nHairsBefore); - float4 lengths = g_MasterStrandLengths.Load(iWisp); //these are the lengths in number of vertices from root - int iSegmentsToGo = (int)lengths.w - 1 - g_iSubHairFirstVert; - output.Edges[1] = min(iSegmentsToGo, NSEGMENTS_PER_PATCH); - output.masterStrandRoots = g_MasterStrandRootIndices.Load(iWisp); - - // dynamic LOD in number of hairs - output.Edges[0] = max(output.Edges[0] * g_fNumHairsLOD, 1); - - return output; -} - -[domain("isoline")] -[partitioning("integer")] -[outputtopology("line")] -[outputcontrolpoints(1)] -[patchconstantfunc("InterpolateConstHSMultiStrandCollisions")] -void InterpolateHSMultiStrandCollisions(InputPatch inputPatch) -{ -} - -// each hull shader processes c-strands belonging to the same master strand -HS_CONSTANT_DATA_OUTPUT InterpolateConstHSSingleStrand(uint iPatch : SV_PrimitiveID) -{ - HS_CONSTANT_DATA_OUTPUT output; - - // how many c-strands accompany this master strand? - output.nHairsBefore = g_iFirstPatchHair; - if (iPatch > 0) - { - output.nHairsBefore += g_SStrandsPerMasterStrandCumulative.Load(iPatch - 1); - } - output.Edges[0] = min(NHAIRS_PER_PATCH, g_SStrandsPerMasterStrandCumulative.Load(iPatch) - output.nHairsBefore); - output.MasterStrandLength = g_tessellatedMasterStrandRootIndex.Load(iPatch); - output.tessellatedMasterStrandRootIndex = 0; - if (iPatch > 0) - { - output.tessellatedMasterStrandRootIndex = g_tessellatedMasterStrandRootIndex.Load(iPatch - 1); - } - output.MasterStrandLength -= output.tessellatedMasterStrandRootIndex; - output.Edges[1] = min(NSEGMENTS_PER_PATCH, output.MasterStrandLength - g_iSubHairFirstVert - 2); - output.texcoords = g_Attributes.Load(iPatch); - output.totalLength = g_Lengths.Load(iPatch); - //-------------------------------------------------------------------------------------------- - //sample the density map, and if we are over the density dont create anymore hair - float4 hairDensityThickness = densityThicknessMapClump.SampleLevel(samLinear,output.texcoords,0); - output.hairDensity = hairDensityThickness.r; - - // dynamic LOD in number of hairs - output.Edges[0] = max(output.Edges[0] * g_fNumHairsLOD, 1); - - return output; -} - -[domain("isoline")] -[partitioning("integer")] -[outputtopology("line")] -[outputcontrolpoints(1)] -[patchconstantfunc("InterpolateConstHSSingleStrand")] -void InterpolateHSSingleStrand(InputPatch inputPatch) -{ -} - -[domain("isoline")] -HairVertex2 InterpolateDSMultiStrand(OutputPatch inputPatch, BARY_HS_CONSTANT_DATA_OUTPUT input, float2 uv : SV_DomainLocation, uint iWispID : SV_PrimitiveID) -{ - // how many hairs did we render before this master strand - uint iHairInsideCurMasterStrand = (int)(uv.y * input.Edges[0] + 0.5); - uint iVertexInsideCurHair = (int)(uv.x * input.Edges[1] + 0.5) + g_iSubHairFirstVert; - - uint InstanceID = iHairInsideCurMasterStrand + input.nHairsBefore; - uint vertexID = iVertexInsideCurHair; - - HairVertexPWIAT outputDepth; - - //get the position, width and ID, and related values - HairVertexPWI pwi = (HairVertexPWI)0; - - float fIndex = (float)iHairInsideCurMasterStrand / 1000.f; - int index = iWispID; - - pwi.ID = InstanceID; - - float3 coords; - coords.xy = g_StrandCoordinates.Load(pwi.ID & g_NumInterpolatedAttributesMinusOne); - coords.z = (1 - coords.x - coords.y); - - //texcoords ---------------------------------------------------------------------------------- - - float2 BaryCentricTexcoords = coords.x * input.rootTexcoords[0].xy - + coords.y * input.rootTexcoords[1].xy - + coords.z * input.rootTexcoords[2].xy; - - //-------------------------------------------------------------------------------------------- - //sample the density map, and if we are over the density dont create anymore hair - float4 hairDensityThickness = densityThicknessMapBarycentric.SampleLevel(samLinear,BaryCentricTexcoords,0); - - int3 vertexIndices; - vertexIndices[0] = floor(input.masterStrandRoots.x) + vertexID; - vertexIndices[1] = floor(input.masterStrandRoots.y) + vertexID; - vertexIndices[2] = floor(input.masterStrandRoots.z) + vertexID; - - //length to root-------------------------------------------------------------------------------- - //needed for clumping, tapering the ends and for texture mapping along the strand - float3 lengthsToRoots; - lengthsToRoots[0] = g_TessellatedLengthsToRoots.Load( vertexIndices[0] ); - lengthsToRoots[1] = g_TessellatedLengthsToRoots.Load( vertexIndices[1] ); - lengthsToRoots[2] = g_TessellatedLengthsToRoots.Load( vertexIndices[2] ); - - //barycentric position--------------------------------------------------------------------- - float3x4 masterVertexPosition; - masterVertexPosition[0] = g_TessellatedMasterStrand.Load( vertexIndices[0] ); - masterVertexPosition[1] = g_TessellatedMasterStrand.Load( vertexIndices[1] ); - masterVertexPosition[2] = g_TessellatedMasterStrand.Load( vertexIndices[2] ); - float3 BarycenticPosition = coords.x * masterVertexPosition[0].xyz - + coords.y * masterVertexPosition[1].xyz - + coords.z * masterVertexPosition[2].xyz; - - float clumpWeight=0; - float barycentricWeight = 1.0; - - int closestIndex = findClosestIndex(coords); - - //clamp------------------------------------------------------------------------------------- - //if the hair strand below intersects an obstacle clamp to nearest guide hair - - float fullYPixel = 1.0/g_NumTotalWisps; - float fullXPixel = 1.0/g_NumMaxStrandsPerWisp; - int interpHairNumber = frac(fIndex)*100; - float2 texcoordsCollision; - texcoordsCollision.x = interpHairNumber*fullXPixel + fullXPixel/2.0; - texcoordsCollision.y = 1.0 - (index*fullYPixel + fullYPixel/2.0); - float collisions = g_CollisionsTexture.SampleLevel(samPointClamp,texcoordsCollision,0).r; - int buffer = 60; - float2 texcoords; - - float BarycetricLengthToRoot = coords.x * lengthsToRoots[0] - + coords.y * lengthsToRoots[1] - + coords.z * lengthsToRoots[2]; - float lengthToRoot; - -#if 1 - if(collisions < (int)vertexID + buffer) - { - float2 clumpCoordinates = g_StrandCircularCoordinates.Load(pwi.ID & g_NumInterpolatedAttributesMinusOne); // this is completely wrong, but it does not lead to a big visual problem. THESE COORDINATES HAVE NOTHING IN COMMON WITH THE OTHER COORDINATES THAT WE HAVE FOR MULTISTRAND. IE BOTH HAIR ARE COMPLETELT DIFFERENT - float clumpLengthToRoot = lengthsToRoots[closestIndex]; - float2 ClumpTexcoords = input.rootTexcoords[closestIndex]; - - //load the coordinate frames - coordinateFrame4 cf; - cf.yAxis = g_tessellatedCoordinateFrames.Load( vertexIndices[closestIndex]*3 + 1); - cf.zAxis = g_tessellatedCoordinateFrames.Load( vertexIndices[closestIndex]*3 + 2); - - //create the new position for the hair clump vertex - float radius = g_clumpWidth * (g_topWidth*(1-clumpLengthToRoot) + g_bottomWidth*clumpLengthToRoot); - float3 ClumpPosition = masterVertexPosition[closestIndex].xyz + cf.yAxis.xyz*clumpCoordinates.x*radius + cf.zAxis.xyz*clumpCoordinates.y*radius; - - clumpWeight = (vertexID - collisions + buffer)/float(buffer); - clumpWeight = clamp(clumpWeight,0,1); - clumpWeight = sin((clumpWeight-0.5)*PI)*0.5 + 0.5; - - barycentricWeight = 1.0-clumpWeight; - pwi.Position = BarycenticPosition*barycentricWeight + ClumpPosition*clumpWeight; - texcoords = BaryCentricTexcoords*barycentricWeight + ClumpTexcoords*clumpWeight; - lengthToRoot = BarycetricLengthToRoot*barycentricWeight + clumpLengthToRoot*clumpWeight; - } - else -#endif - { - pwi.Position = BarycenticPosition; - texcoords = BaryCentricTexcoords; - lengthToRoot = BarycetricLengthToRoot; - } - - if(vertexID==0) //rooting the interpolated hair - { - float3 xAxis = g_tessellatedCoordinateFrames.Load( vertexIndices[closestIndex]*3 ).xyz; - pwi.Position.xyz -= 0.25*xAxis; - } - - //tapering the hair--------------------------------------------------------------------------- - //modulating width by the width denoted in the densityThickness texture----------------------- - pwi.width = hairDensityThickness.r; - float lt = lerp( g_lt, g_lt-0.2, hairDensityThickness.r ); - if(lengthToRoot > lt) - pwi.width *= ( 1 + (lt*(1-g_lv)/(1-lt)) - (1-g_lv)*lengthToRoot/(1-lt) ); - -#ifdef SCALE_WIDTH_WITH_LOD - //float fNumHairsLOD = max(0.1,g_fNumHairsLOD); - //pwi.width /= fNumHairsLOD; - pwi.width *= g_fWidthHairsLOD; -#endif - - outputDepth.Position = pwi.Position; - outputDepth.width = pwi.width; - outputDepth.ID = pwi.ID; - outputDepth.tex = 0; - - float BarycentricTotalLength = coords.x * input.totalLengths[0] - + coords.y * input.totalLengths[1] - + coords.z * input.totalLengths[2]; - float clumpTotalLength = input.totalLengths[closestIndex]; - float totalLength = BarycentricTotalLength*barycentricWeight + clumpTotalLength*clumpWeight; - - //this texture goes from 0 to 1 for the longest hair in the hairstyle. - //lengthToRoot is the fractional distance of the current vertex from the root counted in number of vertices - //totalLength is the actual total length of the strand - //g_maxLengthToRoot is the total length of the longest strand - outputDepth.tex = lengthToRoot*totalLength/g_maxLengthToRoot; - - //thinning the hair lengths--------------------------------------------------------------------- - float inLengthFrac = g_StrandLengths.Load(outputDepth.ID & g_NumInterpolatedAttributesMinusOne); - float maxLength = 1.0-g_thinning + g_thinning*inLengthFrac; - - if( (lengthToRoot > maxLength) || ((int)vertexID == int(input.lengthsw)-1) ) - outputDepth.width = EPSILON; - - HairVertex2 hairvert; - hairvert.Position = outputDepth.Position; - hairvert.width = outputDepth.width; - hairvert.ID = outputDepth.ID; - hairvert.tex = outputDepth.tex; - hairvert.Tangent = float3(0,0,0); - hairvert.scalpTexcoords = 0; - hairvert.shadow = 0; - - float3x4 masterVertexTangents; - masterVertexTangents[0] = g_TessellatedTangents.Load( vertexIndices[0] ); - masterVertexTangents[1] = g_TessellatedTangents.Load( vertexIndices[1] ); - masterVertexTangents[2] = g_TessellatedTangents.Load( vertexIndices[2] ); - float3 BarycentricTangent = coords.x * masterVertexTangents[0].xyz - + coords.y * masterVertexTangents[1].xyz - + coords.z * masterVertexTangents[2].xyz; - float3 ClumpTangent = masterVertexTangents[closestIndex].xyz; - hairvert.Tangent = BarycentricTangent*barycentricWeight + ClumpTangent*clumpWeight; - hairvert.Tangent = normalize(hairvert.Tangent); - - hairvert.scalpTexcoords = texcoords; - - if(g_bApplyAdditionalRenderingTransform) - hairvert.Position.xyz = mul( float4(hairvert.Position.xyz,1.0),additionalTransformation).xyz; - -#ifdef SHADOWS_VS - if(g_useShadows) - { - float3 Pos = mul(float4(hairvert.Position, 1), HairToWorldTransform).xyz; - float2 texcoords = WorldToLightCoord(Pos); - float z = WorldToDepth(Pos); - //TO DO SHADOWS: incorporate the HairToWorldTransform in mLightViewProjClip2Tex float2 texcoords = WorldToLightCoord(output.Position.xyz); - //TO DO SHADOWS: incorporate the HairToWorldTransform in mLightView float z = WorldToDepth(output.Position.xyz); - hairvert.shadow = ShadowPCF(texcoords, z); - } - else - hairvert.shadow = 0; -#endif - - return hairvert; -} - -[domain("isoline")] -HairVertexPWI InterpolateDSMultiStrandDepth(OutputPatch inputPatch, BARYDEPTH_HS_CONSTANT_DATA_OUTPUT input, float2 uv : SV_DomainLocation, uint iWispID : SV_PrimitiveID) -{ - // how many hairs did we render before this master strand - uint iHairInsideCurMasterStrand = (int)(uv.y * input.Edges[0] + 0.5); - uint iVertexInsideCurHair = (int)(uv.x * input.Edges[1] + 0.5) + g_iSubHairFirstVert; - - uint InstanceID = iHairInsideCurMasterStrand + input.nHairsBefore; - uint vertexID = iVertexInsideCurHair; - - HairVertexPWIAT outputDepth; - - float fIndex = (float)iHairInsideCurMasterStrand / 1000.f; - int index = iWispID; - - float3 coords; - coords.xy = g_StrandCoordinates.Load(InstanceID & g_NumInterpolatedAttributesMinusOne); - coords.z = (1 - coords.x - coords.y); - - //texcoords ---------------------------------------------------------------------------------- - - float2 BaryCentricTexcoords = coords.x * input.rootTexcoords[0].xy - + coords.y * input.rootTexcoords[1].xy - + coords.z * input.rootTexcoords[2].xy; - - //-------------------------------------------------------------------------------------------- - //sample the density map, and if we are over the density dont create anymore hair - float4 hairDensityThickness = densityThicknessMapBarycentric.SampleLevel(samLinear,BaryCentricTexcoords,0); - - int3 vertexIndices; - vertexIndices[0] = floor(input.masterStrandRoots.x) + vertexID; - vertexIndices[1] = floor(input.masterStrandRoots.y) + vertexID; - vertexIndices[2] = floor(input.masterStrandRoots.z) + vertexID; - - //length to root-------------------------------------------------------------------------------- - //needed for clumping, tapering the ends and for texture mapping along the strand - float3 lengthsToRoots; - lengthsToRoots[0] = g_TessellatedLengthsToRoots.Load( vertexIndices[0] ); - lengthsToRoots[1] = g_TessellatedLengthsToRoots.Load( vertexIndices[1] ); - lengthsToRoots[2] = g_TessellatedLengthsToRoots.Load( vertexIndices[2] ); - - //barycentric position--------------------------------------------------------------------- - float3x4 masterVertexPosition; - masterVertexPosition[0] = g_TessellatedMasterStrand.Load( vertexIndices[0] ); - masterVertexPosition[1] = g_TessellatedMasterStrand.Load( vertexIndices[1] ); - masterVertexPosition[2] = g_TessellatedMasterStrand.Load( vertexIndices[2] ); - float3 BarycenticPosition = coords.x * masterVertexPosition[0].xyz - + coords.y * masterVertexPosition[1].xyz - + coords.z * masterVertexPosition[2].xyz; - - float clumpWeight=0; - float barycentricWeight = 1.0; - - int closestIndex = findClosestIndex(coords); - - //clamp------------------------------------------------------------------------------------- - //if the hair strand below intersects an obstacle clamp to nearest guide hair - - float fullYPixel = 1.0/g_NumTotalWisps; - float fullXPixel = 1.0/g_NumMaxStrandsPerWisp; - int interpHairNumber = frac(fIndex)*100; - float2 texcoordsCollision; - texcoordsCollision.x = interpHairNumber*fullXPixel + fullXPixel/2.0; - texcoordsCollision.y = 1.0 - (index*fullYPixel + fullYPixel/2.0); - float collisions = g_CollisionsTexture.SampleLevel(samPointClamp,texcoordsCollision,0).r; - int buffer = 60; - float2 texcoords; - - float BarycetricLengthToRoot = coords.x * lengthsToRoots[0] - + coords.y * lengthsToRoots[1] - + coords.z * lengthsToRoots[2]; - float lengthToRoot; - - HairVertexPWI pwi; - pwi.ID = InstanceID; -#if 1 - if(collisions < (int)vertexID + buffer) - { - float2 clumpCoordinates = g_StrandCircularCoordinates.Load(InstanceID & g_NumInterpolatedAttributesMinusOne); // this is completely wrong, but it does not lead to a big visual problem. THESE COORDINATES HAVE NOTHING IN COMMON WITH THE OTHER COORDINATES THAT WE HAVE FOR MULTISTRAND. IE BOTH HAIR ARE COMPLETELT DIFFERENT - float clumpLengthToRoot = lengthsToRoots[closestIndex]; - float2 ClumpTexcoords = input.rootTexcoords[closestIndex]; - - //load the coordinate frames - coordinateFrame4 cf; - cf.yAxis = g_tessellatedCoordinateFrames.Load( vertexIndices[closestIndex]*3 + 1); - cf.zAxis = g_tessellatedCoordinateFrames.Load( vertexIndices[closestIndex]*3 + 2); - - //create the new position for the hair clump vertex - float radius = g_clumpWidth * (g_topWidth*(1-clumpLengthToRoot) + g_bottomWidth*clumpLengthToRoot); - float3 ClumpPosition = masterVertexPosition[closestIndex].xyz + cf.yAxis.xyz*clumpCoordinates.x*radius + cf.zAxis.xyz*clumpCoordinates.y*radius; - - clumpWeight = (vertexID - collisions + buffer)/float(buffer); - clumpWeight = clamp(clumpWeight,0,1); - clumpWeight = sin((clumpWeight-0.5)*PI)*0.5 + 0.5; - - barycentricWeight = 1.0-clumpWeight; - pwi.Position = BarycenticPosition*barycentricWeight + ClumpPosition*clumpWeight; - texcoords = BaryCentricTexcoords*barycentricWeight + ClumpTexcoords*clumpWeight; - lengthToRoot = BarycetricLengthToRoot*barycentricWeight + clumpLengthToRoot*clumpWeight; - } - else -#endif - { - pwi.Position = BarycenticPosition; - texcoords = BaryCentricTexcoords; - lengthToRoot = BarycetricLengthToRoot; - } - - if(vertexID==0) //rooting the interpolated hair - { - float3 xAxis = g_tessellatedCoordinateFrames.Load( vertexIndices[closestIndex]*3 ).xyz; - pwi.Position.xyz -= 0.25*xAxis; - } - - //tapering the hair--------------------------------------------------------------------------- - //modulating width by the width denoted in the densityThickness texture----------------------- - pwi.width = hairDensityThickness.r; - float lt = lerp( g_lt, g_lt-0.2, hairDensityThickness.r ); - if(lengthToRoot > lt) - pwi.width *= ( 1 + (lt*(1-g_lv)/(1-lt)) - (1-g_lv)*lengthToRoot/(1-lt) ); - -#ifdef SCALE_WIDTH_WITH_LOD -// float fNumHairsLOD = max(0.1,g_fNumHairsLOD); -// pwi.width /= fNumHairsLOD; - pwi.width *= g_fWidthHairsLOD; -#endif - - //this texture goes from 0 to 1 for the longest hair in the hairstyle. - //lengthToRoot is the fractional distance of the current vertex from the root counted in number of vertices - //totalLength is the actual total length of the strand - //g_maxLengthToRoot is the total length of the longest strand - - //thinning the hair lengths--------------------------------------------------------------------- - float inLengthFrac = g_StrandLengths.Load(InstanceID & g_NumInterpolatedAttributesMinusOne); - float maxLength = 1.0-g_thinning + g_thinning*inLengthFrac; - - if( (lengthToRoot > maxLength) || ((int)vertexID == int(input.lengthsw)-1) ) - pwi.width = EPSILON; - - if(g_bApplyAdditionalRenderingTransform) - pwi.Position.xyz = mul( float4(pwi.Position.xyz,1.0),additionalTransformation).xyz; - - return pwi; -} - -[domain("isoline")] -HairCollisionVertexWithGS InterpolateDSMultiStrandCollisionsWithGS(OutputPatch inputPatch, BARYCOLLISIONS_HS_CONSTANT_DATA_OUTPUT input, float2 uv : SV_DomainLocation, uint iWispID : SV_PrimitiveID) -{ - HairCollisionVertex output = (HairCollisionVertex)0; - - // how many hairs did we render before this master strand - uint iHairInsideCurMasterStrand = (int)(uv.y * input.Edges[0] + 0.5); - uint iVertexInsideCurHair = (int)(uv.x * input.Edges[1] + 0.5) + g_iSubHairFirstVert; - - uint InstanceID = iHairInsideCurMasterStrand + input.nHairsBefore; - uint vertexID = iVertexInsideCurHair; - - float fIndex = (float)iHairInsideCurMasterStrand / 1000.f; - int index = iWispID; - - float3 coords; - coords.xy = g_StrandCoordinates.Load(InstanceID & g_NumInterpolatedAttributesMinusOne); - coords.z = (1 - coords.x - coords.y); - - //y: the wisp number - float fullYPixel = 2.0/g_NumTotalWisps; - float yPos = -1 + index*fullYPixel + fullYPixel/2.0; - - //x: the interpolated hair number - int interpHairNumber = frac(fIndex)*100; - float fullXPixel = 2.0/g_NumMaxStrandsPerWisp; - float xPos = -1 + interpHairNumber*fullXPixel + fullXPixel/2.0; - - //barycentric position - - int3 vertexIndices; - vertexIndices[0] = floor(input.masterStrandRoots.x) + vertexID; - vertexIndices[1] = floor(input.masterStrandRoots.y) + vertexID; - vertexIndices[2] = floor(input.masterStrandRoots.z) + vertexID; - - float3x4 masterVertexPosition; - masterVertexPosition[0] = g_TessellatedMasterStrand.Load( vertexIndices[0] ); - masterVertexPosition[1] = g_TessellatedMasterStrand.Load( vertexIndices[1] ); - masterVertexPosition[2] = g_TessellatedMasterStrand.Load( vertexIndices[2] ); - float3 BarycenticPosition = coords.x * masterVertexPosition[0].xyz - + coords.y * masterVertexPosition[1].xyz - + coords.z * masterVertexPosition[2].xyz; - - - output.Position = float4(xPos,yPos,0.5,1.0); - output.BarycenticPosition = BarycenticPosition; - output.vertexID = vertexID; - - return output; -} - -[domain("isoline")] -HairVertex2 InterpolateDSSingleStrand_NORMAL(OutputPatch inputPatch, HS_CONSTANT_DATA_OUTPUT input, float2 uv : SV_DomainLocation, uint MasterStrandNumber : SV_PrimitiveID) -{ - HairVertex2 output; - - // how many hairs did we render before this master strand - uint iHairInsideCurMasterStrand = (int)(uv.y * input.Edges[0] + 0.5); - uint iVertexInsideCurHair = (int)(uv.x * input.Edges[1] + 0.5) + g_iSubHairFirstVert; - - uint InstanceID = input.nHairsBefore + iHairInsideCurMasterStrand; - uint vertexID = iVertexInsideCurHair; - - int vertexIndex = input.tessellatedMasterStrandRootIndex+vertexID; - float lengthToRoot = g_TessellatedLengthsToRoots.Load( vertexIndex ); - float2 clumpCoordinates = g_StrandCircularCoordinates.Load(InstanceID & g_NumInterpolatedAttributesMinusOne); - float4 masterVertexPosition = g_TessellatedMasterStrand.Load(vertexIndex); - - //jitter the position slightly - float2 jitter = g_strandDeviations.Load((InstanceID & g_NumInterpolatedAttributesMinusOne) * g_TessellatedMasterStrandLengthMax + vertexID); - - if(g_doCurlyHair) - jitter += g_curlDeviations.Load(MasterStrandNumber*g_TessellatedMasterStrandLengthMax + vertexID); - - clumpCoordinates += jitter; - - //load the coordinate frames - coordinateFrame4 cf; - cf.yAxis = g_tessellatedCoordinateFrames.Load( vertexIndex*3 + 1); - cf.zAxis = g_tessellatedCoordinateFrames.Load( vertexIndex*3 + 2); - - //create the new position for the hair clump vertex - float radius = g_clumpWidth * ( g_topWidth*(1-lengthToRoot) + g_bottomWidth*lengthToRoot ); - output.Position.xyz = masterVertexPosition.xyz + cf.yAxis.xyz*clumpCoordinates.x*radius + cf.zAxis.xyz*clumpCoordinates.y*radius; - - if(vertexID==0) - { - cf.xAxis = g_tessellatedCoordinateFrames.Load( vertexIndex*3 ); - output.Position.xyz -= 0.25*cf.xAxis.xyz; - } - - output.width = input.hairDensity; - - //thinning the hair lengths - float inLengthFrac = g_StrandLengths.Load(InstanceID & g_NumInterpolatedAttributesMinusOne); - float maxLength = 1.0-g_thinning + g_thinning*inLengthFrac; - - if((lengthToRoot > maxLength) || ((int)vertexID == input.MasterStrandLength-2)) - output.width = EPSILON; - - //tapering the hair - float lt = g_lt*maxLength; - if(lengthToRoot > lt) - output.width *= (1 + (lt*(1-g_lv)/(1-lt)) - (1-g_lv)*lengthToRoot/(1-lt)); - - -#ifdef SCALE_WIDTH_WITH_LOD - output.width *= g_fWidthHairsLOD; -#endif - - //this texture goes from 0 to 1 for the longest hair in the hairstyle. - //lengthToRoot is the fractional distance of the current vertex from the root counted in number of vertices - //totalLength is the actual total length of the strand - //g_maxLengthToRoot is the real total length of the longest strand - output.tex = lengthToRoot*input.totalLength/g_maxLengthToRoot; - - //tangent - output.Tangent.xyz = normalize((g_TessellatedTangents.Load(vertexIndex)).xyz); - - output.scalpTexcoords = input.texcoords; - - output.shadow = 0; - - if(g_bApplyAdditionalRenderingTransform) - output.Position.xyz = mul( float4(output.Position.xyz,1.0),additionalTransformation).xyz; - - #ifdef SHADOWS_VS - if(g_useShadows) - { - float3 Pos = mul(float4(output.Position.xyz, 1), HairToWorldTransform).xyz; - float2 texcoords = WorldToLightCoord(Pos); - float z = WorldToDepth(Pos); - //TO DO SHADOWS: incorporate the HairToWorldTransform in mLightViewProjClip2Tex float2 texcoords = WorldToLightCoord(output.Position.xyz); - //TO DO SHADOWS: incorporate the HairToWorldTransform in mLightView float z = WorldToDepth(output.Position.xyz); - output.shadow = ShadowPCF(texcoords, z); - } - else - output.shadow = 0; - #endif - - output.ID = InstanceID; - return output; -} - -[domain("isoline")] -HairVertexPWI InterpolateDSSingleStrand_DEPTH(OutputPatch inputPatch, HS_CONSTANT_DATA_OUTPUT input, float2 uv : SV_DomainLocation, uint MasterStrandNumber : SV_PrimitiveID) -{ - // how many hairs did we render before this master strand - uint iHairInsideCurMasterStrand = (int)(uv.y * input.Edges[0] + 0.5); - uint iVertexInsideCurHair = (int)(uv.x * input.Edges[1] + 0.5) + g_iSubHairFirstVert; - - HairVertex2 hairvert; - uint InstanceID = input.nHairsBefore + iHairInsideCurMasterStrand; - uint vertexID = iVertexInsideCurHair; - - HairVertexPWIAT outputDepth; - - HairVertexPWI pwi = (HairVertexPWI)0; - - int vertexIndex = input.tessellatedMasterStrandRootIndex+vertexID; - float lengthToRoot = g_TessellatedLengthsToRoots.Load( vertexIndex ); - float2 clumpCoordinates = g_StrandCircularCoordinates.Load(InstanceID & g_NumInterpolatedAttributesMinusOne); - float4 masterVertexPosition = g_TessellatedMasterStrand.Load(vertexIndex); - - //jitter the position slightly - float2 jitter = g_strandDeviations.Load((InstanceID & g_NumInterpolatedAttributesMinusOne) * g_TessellatedMasterStrandLengthMax + vertexID); - - if(g_doCurlyHair) - jitter += g_curlDeviations.Load(MasterStrandNumber*g_TessellatedMasterStrandLengthMax + vertexID); - - clumpCoordinates += jitter; - - //load the coordinate frames - coordinateFrame4 cf; - cf.yAxis = g_tessellatedCoordinateFrames.Load( vertexIndex*3 + 1); - cf.zAxis = g_tessellatedCoordinateFrames.Load( vertexIndex*3 + 2); - - //create the new position for the hair clump vertex - float radius = g_clumpWidth * ( g_topWidth*(1-lengthToRoot) + g_bottomWidth*lengthToRoot ); - pwi.Position.xyz = masterVertexPosition.xyz + cf.yAxis.xyz*clumpCoordinates.x*radius + cf.zAxis.xyz*clumpCoordinates.y*radius; - - if(vertexID==0) - { - cf.xAxis = g_tessellatedCoordinateFrames.Load( vertexIndex*3 ); - pwi.Position.xyz -= 0.25*cf.xAxis.xyz; - } - - outputDepth = (HairVertexPWIAT)0; - outputDepth.width = input.hairDensity; - - //thinning the hair lengths - float inLengthFrac = g_StrandLengths.Load(InstanceID & g_NumInterpolatedAttributesMinusOne); - float maxLength = 1.0-g_thinning + g_thinning*inLengthFrac; - - if((lengthToRoot > maxLength) || ((int)vertexID == input.MasterStrandLength-2)) - outputDepth.width = EPSILON; - - //tapering the hair - float lt = g_lt*maxLength; - if(lengthToRoot > lt) - outputDepth.width *= (1 + (lt*(1-g_lv)/(1-lt)) - (1-g_lv)*lengthToRoot/(1-lt)); - -#ifdef SCALE_WIDTH_WITH_LOD - outputDepth.width *= g_fWidthHairsLOD; -#endif - - //this texture goes from 0 to 1 for the longest hair in the hairstyle. - //lengthToRoot is the fractional distance of the current vertex from the root counted in number of vertices - //totalLength is the actual total length of the strand - //g_maxLengthToRoot is the real total length of the longest strand - outputDepth.tex = lengthToRoot*input.totalLength/g_maxLengthToRoot; - - //tangent - hairvert.Tangent.xyz = normalize((g_TessellatedTangents.Load(vertexIndex)).xyz); - - HairVertexPWI output; - output.Position = pwi.Position; - output.width = outputDepth.width; - output.ID = InstanceID; - if(g_bApplyAdditionalRenderingTransform) - output.Position.xyz = mul( float4(output.Position.xyz,1.0),additionalTransformation).xyz; - - return output; -} - -[maxvertexcount(1)] -void InterpolateGSClump_SO(point InterpolatedSOBarycentricVertex vertex[1], - inout PointStream OutputStream) -{ - OutputStream.Append(vertex[0]); -} -HairVertex2 InterpolateVSSingleStrand(uint InstanceID : SV_InstanceID, uint vertexID : SV_VertexID) -{ - return InterpolateVSClumpTotalCore(InstanceID,vertexID); -} - -HairVertexPWIAT InterpolateVSClumpDepthPrepass(uint InstanceID : SV_InstanceID, uint vertexID : SV_VertexID) -{ - int vertexIndex; - float2 texcoords; - return InterpolateVSClumpCore(InstanceID,vertexID,vertexIndex,texcoords); -} - -HairVertexPWI InterpolateVSSingleStrandDepthShadows(uint InstanceID : SV_InstanceID, uint vertexID : SV_VertexID) -{ - int vertexIndex = 0; - float2 texcoords = float2(0,0); - float lengthToRoot = 0; - int MasterStrandNumber = 0; - int MasterStrandLength = 0; - return InterpolateVSClumpCore0(InstanceID,vertexID,vertexIndex,texcoords,MasterStrandNumber,lengthToRoot,MasterStrandLength); - -} - -InterpolatedSOBarycentricVertex InterpolateVSSingleStrand_SO(uint vertexID : SV_VertexID) -{ - HairVertex2 hairvert = InterpolateVSClumpTotalCore - (vertexID/g_TessellatedMasterStrandLengthMax,vertexID%g_TessellatedMasterStrandLengthMax); - - InterpolatedSOBarycentricVertex output; - output.PositionAndWidth = float4(hairvert.Position,hairvert.width); - output.IdAlphaTex = float4(asfloat(hairvert.ID),1,hairvert.tex,hairvert.scalpTexcoords.x); - output.tangent = float4(hairvert.Tangent,hairvert.scalpTexcoords.y); - return output; -} - -HairVertex2 InterpolateVSSingleStrand_LOAD(uint index : SV_VertexID) -{ - HairVertex2 output = (HairVertex2)0; - float4 PositionAndWidth = g_InterpolatedPositionAndWidthClump.Load(index); - float4 IdAlphaTex = g_InterpolatedIdAlphaTexClump.Load(index); - float4 tangent = g_InterpolatedtangentClump.Load(index); - - output.Position = PositionAndWidth.xyz; - if(g_bApplyAdditionalRenderingTransform) - output.Position.xyz = mul( float4(output.Position.xyz,1.0),additionalTransformation).xyz; - output.scalpTexcoords = float2(IdAlphaTex.w,tangent.w); - - - #ifdef SHADOWS_VS - if(g_useShadows) - { - float3 Pos = mul(float4(output.Position.xyz, 1), HairToWorldTransform).xyz; - float2 texcoords = WorldToLightCoord(Pos); - float z = WorldToDepth(Pos); - //TO DO SHADOWS: incorporate the HairToWorldTransform in mLightViewProjClip2Tex float2 texcoords = WorldToLightCoord(output.Position.xyz); - //TO DO SHADOWS: incorporate the HairToWorldTransform in mLightView float z = WorldToDepth(output.Position.xyz); - output.shadow = ShadowPCF(texcoords, z); - } - else - output.shadow = 0; - #endif - - output.width = PositionAndWidth.w; - output.Tangent = tangent.xyz; - output.ID = asint(IdAlphaTex.x); - output.tex = IdAlphaTex.z; - - return output; -} - -HairVertexPWI InterpolateVSSingleStrandDepthShadows_LOAD(uint index : SV_VertexID ) -{ - HairVertexPWI output; - float4 PositionAndWidth = g_InterpolatedPositionAndWidthClump.Load(index); - float4 IdAlphaTex = g_InterpolatedIdAlphaTexClump.Load(index); - - output.Position = PositionAndWidth.xyz; - if(g_bApplyAdditionalRenderingTransform) - output.Position.xyz = mul( float4(output.Position.xyz,1.0),additionalTransformation).xyz; - output.width = PositionAndWidth.w; - output.ID = asint(IdAlphaTex.x); - - return output; -} - -HairVertexPWIAT InterpolateVSClumpDepthPrepass_LOAD( uint InstanceID : SV_InstanceID, uint vertexID : SV_VertexID ) -{ - HairVertexPWIAT output; - int index = InstanceID*g_TessellatedMasterStrandLengthMax + vertexID; - - float4 PositionAndWidth = g_InterpolatedPositionAndWidthClump.Load(index); - float4 IdAlphaTex = g_InterpolatedIdAlphaTexClump.Load(index); - - output.Position = PositionAndWidth.xyz; - if(g_bApplyAdditionalRenderingTransform) - output.Position.xyz = mul( float4(output.Position.xyz,1.0),additionalTransformation).xyz; - output.width = PositionAndWidth.w; - output.ID = asint(IdAlphaTex.x); - output.tex = IdAlphaTex.z ; - - return output; -} - -//rendering to grid does not do any interpolation -HairVertex2Grid InterpolateVS2Grid( uint InstanceID : SV_InstanceID, uint vertexID : SV_VertexID ) -{ - HairVertex2Grid output = (HairVertex2Grid)0; - int index = InstanceID; - float3 masterStrandRoots = g_MasterStrandRootIndicesUntessellated.Load(index); - float4 lengths = g_MasterStrandLengthsUntessellated.Load( index ); - - - //if we have run over hair lengths - if( (int)vertexID >= lengths.w ) - { - output.ID = -1; - return output; - } - else - output.ID = InstanceID; - - - float3 coords; - coords.xy = g_StrandCoordinates.Load(output.ID & g_NumInterpolatedAttributesMinusOne); - coords.z = (1 - coords.x - coords.y); - - //position - float3x4 masterVertexPosition; - masterVertexPosition[0] = g_MasterStrand.Load( floor(masterStrandRoots.x) + vertexID ); - masterVertexPosition[1] = g_MasterStrand.Load( floor(masterStrandRoots.y) + vertexID ); - masterVertexPosition[2] = g_MasterStrand.Load( floor(masterStrandRoots.z) + vertexID ); - - float3 position = coords.x * masterVertexPosition[0].xyz - + coords.y * masterVertexPosition[1].xyz - + coords.z * masterVertexPosition[2].xyz; - - output.Position = position; - return output; -} - -//geometry shaders -struct HairVertexTangent -{ - float4 Position : Position; - float4 Tangent : Tangent; -}; - -[MaxVertexCount(1)] -void TessellateGSBSpline(point HairAdjacencyVertex input[1], inout PointStream inStream ) -{ - HairVertexTangent output; - - float4x4 basisMatrix = float4x4 - ( - -1/6.0, 3/6.0, -3/6.0, 1/6.0, - 3/6.0, -6/6.0, 3/6.0, 0, - -3/6.0, 0, 3/6.0, 0, - 1/6.0, 4/6.0, 1/6.0, 0 - ); - - - float u = input[0].u; - - //positions ------------------------------------------------------------------------- - float4x4 controlVertices; - - if(u<0) - { - u += 2; - controlVertices[0] = controlVertices[1] = g_MasterStrand.Load(input[0].controlVertexIndex); - controlVertices[2] = g_MasterStrand.Load(input[0].controlVertexIndex + 1); - controlVertices[3] = g_MasterStrand.Load(input[0].controlVertexIndex + 2); - } - else if(u>1) - { - u -= 2; - controlVertices[0] = g_MasterStrand.Load(input[0].controlVertexIndex + 1); - controlVertices[1] = g_MasterStrand.Load(input[0].controlVertexIndex + 2); - controlVertices[2] = controlVertices[3] = g_MasterStrand.Load(input[0].controlVertexIndex + 3); - } - else - { - controlVertices[0] = g_MasterStrand.Load(input[0].controlVertexIndex ); - controlVertices[1] = g_MasterStrand.Load(input[0].controlVertexIndex + 1); - controlVertices[2] = g_MasterStrand.Load(input[0].controlVertexIndex + 2); - controlVertices[3] = g_MasterStrand.Load(input[0].controlVertexIndex + 3); - } - - - float4 basis = mul(float4(u * u * u, u * u, u, 1), basisMatrix); - output.Position = float4(0, 0, 0, controlVertices[0].w); - [unroll] for (int c = 0; c < 4; ++c) - output.Position += basis[c] * controlVertices[c]; - - - //tangents --------------------------------------------------------------------- - float3x3 basisMatrixQuadratic = float3x3 - ( - 0.5, -1.0, 0.5, - -1.0, 1.0, 0.0, - 0.5, 0.5, 0.0 - ); - - float3 basisTangents = mul(float3(u * u, u, 1), basisMatrixQuadratic); - - const float3 tangents[3] = - { - float3(controlVertices[1].xyz - controlVertices[0].xyz), - float3(controlVertices[2].xyz - controlVertices[1].xyz), - float3(controlVertices[3].xyz - controlVertices[2].xyz), - }; - - output.Tangent = float4(0,0,0,0); - [unroll] for (c = 0; c < 3; ++c) - output.Tangent.xyz += basisTangents[c] * tangents[c]; - - inStream.Append(output); -} - -[MaxVertexCount(1)] -void TessellateGSBSplineSB(point HairAdjacencyVertex input[1], inout PointStream inStream ) -{ - HairVertexTangent output; - - float4x4 basisMatrix = float4x4 - ( - -1/6.0, 3/6.0, -3/6.0, 1/6.0, - 3/6.0, -6/6.0, 3/6.0, 0, - -3/6.0, 0, 3/6.0, 0, - 1/6.0, 4/6.0, 1/6.0, 0 - ); - - float u = input[0].u; - - //positions - float4x4 controlVertices; - - if(u<0) - { - u += 2; - controlVertices[0] = controlVertices[1] = g_MasterStrandSB[input[0].controlVertexIndex]; - controlVertices[2] = g_MasterStrandSB[input[0].controlVertexIndex + 1]; - controlVertices[3] = g_MasterStrandSB[input[0].controlVertexIndex + 2]; - } - else if(u>1) - { - u -= 2; - controlVertices[0] = g_MasterStrandSB[input[0].controlVertexIndex + 1]; - controlVertices[1] = g_MasterStrandSB[input[0].controlVertexIndex + 2]; - controlVertices[2] = controlVertices[3] = g_MasterStrandSB[input[0].controlVertexIndex + 3]; - } - else - { - controlVertices[0] = g_MasterStrandSB[input[0].controlVertexIndex ]; - controlVertices[1] = g_MasterStrandSB[input[0].controlVertexIndex + 1]; - controlVertices[2] = g_MasterStrandSB[input[0].controlVertexIndex + 2]; - controlVertices[3] = g_MasterStrandSB[input[0].controlVertexIndex + 3]; - } - - float4 basis = mul(float4(u * u * u, u * u, u, 1), basisMatrix); - output.Position = float4(0, 0, 0, controlVertices[0].w); - [unroll] for (int c = 0; c < 4; ++c) - output.Position += basis[c] * controlVertices[c]; - - //tangents --------------------------------------------------------------------- - float3x3 basisMatrixQuadratic = float3x3 - ( - 0.5, -1.0, 0.5, - -1.0, 1.0, 0.0, - 0.5, 0.5, 0.0 - ); - - float3 basisTangents = mul(float3(u * u, u, 1), basisMatrixQuadratic); - - const float3 tangents[3] = - { - float3(controlVertices[1].xyz - controlVertices[0].xyz), - float3(controlVertices[2].xyz - controlVertices[1].xyz), - float3(controlVertices[3].xyz - controlVertices[2].xyz), - }; - - output.Tangent = float4(0,0,0,0); - [unroll] for (c = 0; c < 3; ++c) - output.Tangent.xyz += basisTangents[c] * tangents[c]; - - inStream.Append(output); -} - -[MaxVertexCount(4)] -void InterpolateGSDepthPrepass(line HairVertexPWIAT vertex[2], inout TriangleStream stream) -{ - if (vertex[0].ID < 0 || vertex[1].ID < 0) - return; - - float width = g_StrandSizes.Load(vertex[0].ID & g_NumInterpolatedAttributesMinusOne) * g_widthMulGS; - - HairPointDepthPrepass hairPoint; - float3 tangent = (vertex[1].Position - vertex[0].Position); - float height = length(tangent); - tangent = normalize(tangent); - float3 worldPos = vertex[0].Position; //note: this should be the average of the two vertices, and then the other positions also need to change. - - - float3 eyeVec = TransformedEyePosition - worldPos; - float3 sideVec = normalize(cross(eyeVec, tangent)); - - - float4x3 pos; - float3 width0 = sideVec * 0.5 * width * vertex[0].width; - float3 width1 = sideVec * 0.5 * width * vertex[1].width; - - pos[0] = vertex[0].Position - width0; - pos[1] = vertex[0].Position + width0; - pos[2] = vertex[1].Position - width1; - pos[3] = vertex[1].Position + width1; - -#ifdef INTERPOLATION_LOD_GS - float2x4 hpos; - for (int i = 0; i < 2; i++) { - hpos[i] = mul( float4(pos[i],1.0),ViewProjection); - hpos[i].xy /= hpos[i].w; - hpos[i].xy = hpos[i].xy * 0.5 + 0.5; // uv - hpos[i].xy *= float2(g_ScreenWidth, g_ScreenHeight); - } - - float w1 = length(hpos[1].xy - hpos[0].xy); - float p = w1 / g_InterpolationLOD; - if (w1 < g_InterpolationLOD) { - float rand = (float)(vertex[0].ID & g_NumInterpolatedAttributesMinusOne) / (float)g_NumInterpolatedAttributes; - if (rand >= p) return; - - float scale = 1.0/p; - width0 *= scale; - width1 *= scale; - - pos[0] = vertex[0].Position - width0; - pos[1] = vertex[0].Position + width0; - pos[2] = vertex[1].Position - width1; - pos[3] = vertex[1].Position + width1; - } -#endif - - float4x3 tex; - int textureIndex = vertex[0].ID & 3; - tex[0] = float3(0,vertex[0].tex,textureIndex); - tex[1] = float3(1,vertex[0].tex,textureIndex); - tex[2] = float3(0,vertex[1].tex,textureIndex); - tex[3] = float3(1,vertex[1].tex,textureIndex); - - - hairPoint.Position = mul( float4(pos[0],1.0),ViewProjection); - hairPoint.tex = tex[0]; - stream.Append(hairPoint); - - hairPoint.Position = mul( float4(pos[1],1.0),ViewProjection); - hairPoint.tex = tex[1]; - stream.Append(hairPoint); - - hairPoint.Position = mul( float4(pos[2],1.0),ViewProjection); - hairPoint.tex = tex[2]; - stream.Append(hairPoint); - - hairPoint.Position = mul( float4(pos[3],1.0),ViewProjection); - hairPoint.tex = tex[3]; - stream.Append(hairPoint); - - - stream.RestartStrip(); -} - -[MaxVertexCount(4)] -void InterpolateGSDepthShadows(line HairVertexPWI vertex[2], inout TriangleStream stream) -{ - if (vertex[0].ID < 0 || vertex[1].ID != vertex[0].ID) - return; - - float width = g_StrandSizes.Load(vertex[0].ID & g_NumInterpolatedAttributesMinusOne) * g_widthMulGS; - - HairPointDepth hairPoint; - float3 tangent = (vertex[1].Position - vertex[0].Position); - tangent = normalize(tangent); - float3 worldPos = vertex[0].Position; // note: this should be the average of the two vertices, and then the other positions also need to change. - - float3 eyeVec = TransformedEyePosition - worldPos; - float3 sideVec = normalize(cross(eyeVec, tangent)); - - float4x3 pos; - float3 width0 = sideVec * 0.5 * width * vertex[0].width; - float3 width1 = sideVec * 0.5 * width * vertex[1].width; - - pos[0] = vertex[0].Position - width0; - pos[1] = vertex[0].Position + width0; - pos[2] = vertex[1].Position - width1; - pos[3] = vertex[1].Position + width1; - - float3 Pos; - - Pos = mul(float4(pos[0], 1), HairToWorldTransform).xyz; - hairPoint.depth = mul(float4(Pos, 1), mLightView).z; - hairPoint.Position = mul(float4(Pos, 1), ViewProjection); - stream.Append(hairPoint); - - Pos = mul(float4(pos[1], 1), HairToWorldTransform).xyz; - hairPoint.depth = mul(float4(Pos, 1), mLightView).z; - hairPoint.Position = mul(float4(Pos, 1), ViewProjection); - stream.Append(hairPoint); - - Pos = mul(float4(pos[2], 1), HairToWorldTransform).xyz; - hairPoint.depth = mul(float4(Pos, 1), mLightView).z; - hairPoint.Position = mul(float4(Pos, 1), ViewProjection); - stream.Append(hairPoint); - - Pos = mul(float4(pos[3], 1), HairToWorldTransform).xyz; - hairPoint.depth = mul(float4(Pos, 1), mLightView).z; - hairPoint.Position = mul(float4(Pos, 1), ViewProjection); - stream.Append(hairPoint); - - stream.RestartStrip(); -} - -[MaxVertexCount(1)] -void InterpolateGSMultiStrandCollisions(line HairCollisionVertexWithGS vertex[2], inout PointStream stream) -{ - HairCollisionVertex hairPoint; - hairPoint.Position = vertex[0].Position; - hairPoint.BarycenticPosition = vertex[0].BarycenticPosition; - hairPoint.dummy = 0.0f; - hairPoint.vertexID = vertex[0].vertexID; - stream.Append(hairPoint); -} - -[maxvertexcount(4)] -void InterpolateGS(line HairVertex2 vertex[2], inout TriangleStream stream) -{ - if (vertex[0].ID < 0 || vertex[0].ID != vertex[1].ID) - return; - - float width = g_StrandSizes.Load(vertex[0].ID & g_NumInterpolatedAttributesMinusOne) * g_widthMulGS; - - HairPoint hairPoint; - float3 tangent = (vertex[1].Position - vertex[0].Position); - tangent = normalize(tangent); - float3 worldPos = vertex[0].Position; // note: this should be the average of the two vertices, and then the other positions also need to change. - - float3 eyeVec = TransformedEyePosition - worldPos; - float3 sideVec = normalize(cross(eyeVec, tangent)); - - float4x3 pos; - float3 width0 = sideVec * 0.5 * width * vertex[0].width; - float3 width1 = sideVec * 0.5 * width * vertex[1].width; - - pos[0] = vertex[0].Position - width0; - pos[1] = vertex[0].Position + width0; - pos[2] = vertex[1].Position - width1; - pos[3] = vertex[1].Position + width1; - -#ifdef INTERPOLATION_LOD_GS - float2x4 hpos; - for (int i = 0; i < 2; i++) { - hpos[i] = mul( float4(pos[i],1.0),ViewProjection); - hpos[i].xy /= hpos[i].w; - hpos[i].xy = hpos[i].xy * 0.5 + 0.5; // uv - hpos[i].xy *= float2(g_ScreenWidth, g_ScreenHeight); - } - - float w1 = length(hpos[1].xy - hpos[0].xy); - float p = w1 / g_InterpolationLOD; - if (w1 < g_InterpolationLOD) { - float rand = (float)(vertex[0].ID & g_NumInterpolatedAttributesMinusOne) / (float)g_NumInterpolatedAttributes; - if (rand >= p) return; - - float scale = 1.0/p; - width0 *= scale; - width1 *= scale; - - pos[0] = vertex[0].Position - width0; - pos[1] = vertex[0].Position + width0; - pos[2] = vertex[1].Position - width1; - pos[3] = vertex[1].Position + width1; - } -#endif - - float4x2 tex; - tex[0] = float2(0,vertex[0].tex); - tex[1] = float2(1,vertex[0].tex); - tex[2] = float2(0,vertex[1].tex); - tex[3] = float2(1,vertex[1].tex); - - float2x3 tangents; - tangents[0] = normalize(vertex[0].Tangent.xyz); - tangents[1] = normalize(vertex[1].Tangent.xyz); - hairPoint.scalpTexcoords = vertex[0].scalpTexcoords; - hairPoint.ID = vertex[0].ID; - - hairPoint.Position = mul( float4(pos[0],1.0),ViewProjection); - hairPoint.tex = tex[0]; - hairPoint.shadow = vertex[0].shadow; - hairPoint.Tangent = tangents[0]; -#ifndef SHADOWS_VS - hairPoint.wPos = pos[0]; -#endif - stream.Append(hairPoint); - - hairPoint.Position = mul( float4(pos[1],1.0),ViewProjection); - hairPoint.tex = tex[1]; - hairPoint.shadow = vertex[0].shadow; -#ifndef SHADOWS_VS - hairPoint.wPos = pos[1]; -#endif - stream.Append(hairPoint); - - hairPoint.Position = mul( float4(pos[2],1.0),ViewProjection); - hairPoint.tex = tex[2]; - hairPoint.shadow = vertex[1].shadow; - hairPoint.Tangent = tangents[1]; -#ifndef SHADOWS_VS - hairPoint.wPos = pos[2]; -#endif - stream.Append(hairPoint); - - hairPoint.Position = mul( float4(pos[3],1.0),ViewProjection); - hairPoint.tex = tex[3]; - hairPoint.shadow = vertex[1].shadow; -#ifndef SHADOWS_VS - hairPoint.wPos = pos[3]; -#endif - stream.Append(hairPoint); - - stream.RestartStrip(); -} - -[MaxVertexCount(4)] -void InterpolateGSDensity(line HairVertexPWI vertex[2], inout TriangleStream stream) -{ - if (vertex[0].ID < 0 || vertex[1].ID < 0) - return; - - float width = g_StrandSizes.Load(vertex[0].ID & g_NumInterpolatedAttributesMinusOne) * g_widthMulGS; - - HairPointDepthDensity hairPoint; - float3 tangent = (vertex[1].Position - vertex[0].Position); - float height = length(tangent); - tangent = normalize(tangent); - float3 worldPos = vertex[0].Position; // note: this should be the average of the two vertices, and then the other positions also need to change. - - float3 eyeVec = TransformedEyePosition - worldPos; - float3 sideVec = normalize(cross(eyeVec, tangent)); - - float4x3 pos; - float3 width0 = sideVec * 0.5 * width * vertex[0].width; - float3 width1 = sideVec * 0.5 * width * vertex[1].width; - - pos[0] = vertex[0].Position - width0; - pos[1] = vertex[0].Position + width0; - pos[2] = vertex[1].Position - width1; - pos[3] = vertex[1].Position + width1; - - hairPoint.posInGrid = mul(float4(pos[0], 1), WorldToGrid ); - hairPoint.Position = mul( float4(pos[0],1.0),ViewProjection); - stream.Append(hairPoint); - - hairPoint.posInGrid = mul(float4(pos[1], 1), WorldToGrid ); - hairPoint.Position = mul( float4(pos[1],1.0),ViewProjection); - stream.Append(hairPoint); - - hairPoint.posInGrid = mul(float4(pos[2], 1), WorldToGrid ); - hairPoint.Position = mul( float4(pos[2],1.0),ViewProjection); - stream.Append(hairPoint); - - hairPoint.posInGrid = mul(float4(pos[3], 1), WorldToGrid ); - hairPoint.Position = mul( float4(pos[3],1.0),ViewProjection); - stream.Append(hairPoint); - - stream.RestartStrip(); -} - -[MaxVertexCount(4)] -void InterpolateGSMCollisions(line HairVertexCollisions vertex[2], inout TriangleStream stream) -{ - if (vertex[0].ID < 0 || vertex[1].ID < 0) - return; - - float width = g_StrandSizes.Load(vertex[0].ID & g_NumInterpolatedAttributesMinusOne) * g_widthMulGS; - - HairPointCollisions hairPoint; - hairPoint.texcoords = vertex[0].texcoords; - float3 tangent = (vertex[1].Position - vertex[0].Position); - float height = length(tangent); - tangent = normalize(tangent); - float3 worldPos = vertex[0].Position; // note: this should be the average of the two vertices, and then the other positions also need to change. - - float3 eyeVec = TransformedEyePosition - worldPos; - float3 sideVec = normalize(cross(eyeVec, tangent)); - - float4x3 pos; - float3 width0 = sideVec * 0.5 * width; //note : multiply by the clump width if its anything other than 1 - float3 width1 = sideVec * 0.5 * width; //note : multiply by the clump width if its anything other than 1 - - pos[0] = vertex[0].Position - width0; - pos[1] = vertex[0].Position + width0; - pos[2] = vertex[1].Position - width1; - pos[3] = vertex[1].Position + width1; - - hairPoint.Position = mul( float4(pos[0],1.0),ViewProjection); - hairPoint.vertexID = vertex[0].vertexID; - stream.Append(hairPoint); - - hairPoint.Position = mul( float4(pos[1],1.0),ViewProjection); - hairPoint.vertexID = vertex[0].vertexID; - stream.Append(hairPoint); - - hairPoint.Position = mul( float4(pos[2],1.0),ViewProjection); - hairPoint.vertexID = vertex[1].vertexID; - stream.Append(hairPoint); - - hairPoint.Position = mul( float4(pos[3],1.0),ViewProjection); - hairPoint.vertexID = vertex[1].vertexID; - stream.Append(hairPoint); - - stream.RestartStrip(); -} - -void ExpandFacingQuad(float3 eyePos, float3 eyeVec, float3 worldPos, float3 tangent, float height,float width, inout TriangleStream stream) -{ - float3 sideVec = normalize(cross(eyeVec, tangent)); - - float4x3 pos; - pos[0] = worldPos - (sideVec * 0.5*width); - pos[1] = pos[0] + (sideVec * width); - pos[2] = pos[0] + (tangent * height); - pos[3] = pos[2] + (sideVec * width ); - - HairPointGrid hpOut; - - hpOut.Position = mul( float4(pos[0],1.0),WorldViewProjection); - hpOut.distance = hpOut.Position.z; - stream.Append(hpOut); - - hpOut.Position = mul( float4(pos[1],1.0),WorldViewProjection); - hpOut.distance = hpOut.Position.z; - stream.Append(hpOut); - - hpOut.Position = mul( float4(pos[2],1.0),WorldViewProjection); - hpOut.distance = hpOut.Position.z; - stream.Append(hpOut); - - hpOut.Position = mul( float4(pos[3],1.0),WorldViewProjection); - hpOut.distance = hpOut.Position.z; - stream.Append(hpOut); - - stream.RestartStrip(); -} - -//note! doing too many rasterizations maybe -[MaxVertexCount(8)] -void InterpolateGS2Grid(line HairVertex2Grid vertex[2], inout TriangleStream stream) -{ - if (vertex[0].ID < 0 || vertex[1].ID < 0) - return; - - float width = g_StrandSizes.Load(vertex[0].ID & g_NumInterpolatedAttributesMinusOne)*g_StrandWidthMultiplier; - - float3 tangent = (vertex[1].Position - vertex[0].Position); - float height = length(tangent); - tangent = normalize(tangent); - float3 worldPos = vertex[0].Position; // note: this should be the average of the two vertices, and then the other positions also need to change. - - float3 eyeVec; - - eyeVec = EyePosition - worldPos; - ExpandFacingQuad(EyePosition,eyeVec,worldPos,tangent,height,width,stream); - eyeVec = float3(0,0,1) - worldPos; //note: find something better! - ExpandFacingQuad(float3(0,0,1),eyeVec,worldPos,tangent,height,width,stream); -} - -//unrolled loop for efficiency, make sure the amount of implicits dosnt exceed this! -int evaluateVertexInsideImplicits(float3 Position) -{ - if(0g_densityThreshold*1.8 ) - return float4(input.vertexID,input.vertexID,input.vertexID,input.vertexID); - -/* -// reading from a pre-voxelized texture of obstacles is much faster than evaluating them here -// unrolling loop below, this was much faster than doing the implicit calculations - - if(evaluateVertexInsideImplicits(BarycenticPosition)) - return float4(input.vertexID,input.vertexID,input.vertexID,input.vertexID); -*/ - - return float4(1000,1000,1000,1000); -} - -// visualizing density -float4 RenderPSDensity(HairPoint input) : SV_Target -{ - float4 posInGrid = mul(float4(1,1,1/*input.wPos.xyz*/, 1), WorldToGrid ); - - posInGrid.x += 0.5; - posInGrid.y += 0.5; - posInGrid.z += 0.5; - - float3 texcoords = float3(posInGrid.x, 1.0 - posInGrid.y, posInGrid.z * g_textureDepth); - float density; - - //using wrap mode to show where our texture accesses are wrong - - if(g_useBlurTexture) - density = abs(Texture_density_Blur.SampleLevel(samLinearWrap,texcoords,0)).r; - else - density = abs(Texture_density_Demux.SampleLevel(samLinearWrap,texcoords,0)).r; - - return visualizeDensity(density); -} - -float4 RenderPSDensitySmall(HairPointDepthDensity input) : SV_Target -{ - float4 posInGrid = input.posInGrid; - - posInGrid.x += 0.5; - posInGrid.y += 0.5; - posInGrid.z += 0.5; - - float3 texcoords = float3(posInGrid.x, 1.0 - posInGrid.y, posInGrid.z * g_textureDepth); - float density; - - //using wrap mode to show where our texture accesses are wrong - - if(g_useBlurTexture) - density = abs(Texture_density_Blur.SampleLevel(samLinearWrap,texcoords,0)).r; - else - density = abs(Texture_density_Demux.SampleLevel(samLinearWrap,texcoords,0)).r; - - return visualizeDensity(density); -} - -float4 InterpolatePSMCollisions(HairPointCollisions input) : SV_Target -{ - - float collisions = g_CollisionsTexture.SampleLevel(samLinearWrap,input.texcoords,0).r; - if(collisions < input.vertexID) - return float4(collisions.x/10.0,0,0,1); - else - return float4(0,0,0,1); -} - -float SoftEdge(float x) -{ - float d = length(x * 2.0 - 1.0); - return exp(-g_SoftEdges * d); -} - -float4 RenderPSDepthPrepass( HairPointDepthPrepass input) : SV_Target -{ - float4 outputColor = float4(0,0,0,1); - float4 hairSpecTex = hairTextureArray.Sample( samAniso, float3(input.tex.xyz) ); - - if(hairSpecTex.x < 0.3) - return float4(0,0,0,0); - - hairSpecTex.x = hairSpecTex.x + 0.5; - - outputColor.a *= hairSpecTex.x; - - //outputColor.a = 1; - return outputColor; - -// return float4(1,0,0,0.5); -} - -//all lighting calculations here are done in object space -float4 RenderPS(HairPoint input) : SV_Target -{ - float ksP = g_ksP; - float ksS = g_ksS; - float kd = g_kd; - float specPowerPrimary = g_specPowerPrimary; - float specPowerSecondary = g_specPowerSecondary; - float ksP_sparkles = g_ksP_sparkles; - float specPowerPrimarySparkles = g_specPowerPrimarySparkles; - float ka = g_ka; - - int ID = input.ID; - - float4 outputColor; - - //input color from textures -#ifdef USE_TEXTURE_COLOR - - #ifdef USETEXTURES - float4 baseColor = (hairTexture.SampleLevel(samLinear,input.scalpTexcoords,0)); - #else - float4 baseColor = float4(g_StrandColors.Load(ID & g_NumInterpolatedAttributesMinusOne),1); - #endif - float4 specColor = (g_specColor + baseColor)*0.5; -#else - float4 baseColor = g_baseColor; - float4 specColor = g_specColor; -#endif - - float2 tangentJitter = g_TangentJitter.Load(ID & g_NumInterpolatedAttributesMinusOne); - //float2 tangentJitter = g_TangentJitter.Load(0); - - outputColor.xyz = baseColor.xyz; - - int textureArrayIndex = ID & 3; - float4 hairSpecTex = hairTextureArray.Sample( samAniso, float3(input.tex.xy,textureArrayIndex) ); - float4 specNoise = specularNoise.SampleLevel(samAniso,float2(input.tex.x,input.tex.y),0); - //float hairSpecTex = hairTextureArray.Sample( samAniso, float3(0,0,0) ); - //float specNoise = specularNoise.SampleLevel(samAniso,float2(0,0),0); - - hairSpecTex.x = hairSpecTex.x + 0.5; - - //ksP *= hairSpecTex.x; - //ksS *= hairSpecTex.x; - kd *= hairSpecTex.x; - - //make the roots darker - - //if(1) - if(input.tex.y < 0.025) - { - kd *= 0.75; - ka *= 0.75; - ksP *= 0.75; - ksS *= 0.75; - } - - // Local geometry - float3 P = float3(1,1,1); - //float3 T = float3(1,0,0); - //float3 L = normalize(float3(1, 1, 1)); //directional light - //float3 N = float3(0,1,0); - - //float3 P = input.wPos; - float3 L = vLightDirObjectSpace; - float3 V = normalize(TransformedEyePosition - P); - float3 T = input.Tangent; - //re-create the normal vector: - float3 sideVec = normalize(cross(V, T)); - float3 N = normalize(cross(T,sideVec)); - - - T += 0.2 * ( N.xyz*(hairSpecTex.x - 0.5) ); - T = normalize(T); - - float3 TPrimary = T; - TPrimary += (0.3*tangentJitter.x)*N; //jitter each hair strand tangent. primary shifted towards tip - TPrimary += 0.1*( N.xyz*(specNoise.x - 0.5) ); - TPrimary = normalize(TPrimary); - - float3 TSecondary = T; - TSecondary += (-0.3 + 0.4*tangentJitter.y)*N; //jitter each hair strand tangent. primary shifted towards tip - TSecondary += 0.1*( N.xyz*(specNoise.x - 0.5) ); - TSecondary = normalize(TSecondary); - - - - -#ifdef SHADOWS_VS - //float shadow = 0; - float shadow = input.shadow; -#else - float shadow = 0.0f; - if(g_useShadows) - { - float3 Pos = mul(float4(input.wPos, 1), HairToWorldTransform).xyz; - float2 texcoords = WorldToLightCoord(Pos); - float z = WorldToDepth(Pos); - //TO DO SHADOWS: incorporate the HairToWorldTransform in mLightViewProjClip2Tex : float2 texcoords = WorldToLightCoord(input.wPos); - //TO DO SHADOWS: incorporate the HairToWorldTransform in mLightView : float z = WorldToDepth(input.wPos); - shadow = ShadowPCF(texcoords, z); - } -#endif - - //kajiya and kay lighting - - //diffuse - float TdotL = dot( T , L); - float sinTL = sqrt( 1 - TdotL*TdotL ); - - //specular primary - float TPdotL = dot( TPrimary , L); - float sinTPL = sqrt( 1 - TPdotL*TPdotL ); - float TPdotE = dot( TPrimary , V); - float sinTPE = sqrt( 1 - TPdotE*TPdotE ); - - //specular secondary - float TSdotL = dot( TSecondary , L); - float sinTSL = sqrt( 1 - TSdotL*TSdotL ); - float TSdotE = dot( TSecondary , V); - float sinTSE = sqrt( 1 - TSdotE*TSdotE ); - - float lightDiffuse = 1-shadow; - float lightSpec = pow(lightDiffuse,2); - - float specPrimary = abs((TPdotL*TPdotE + sinTPL*sinTPE)); - - outputColor.xyz = ka*outputColor.xyz //ambient light - + lightDiffuse*(kd*sinTL*outputColor.xyz) //diffuse light - + lightSpec*(ksP*pow( specPrimary,specPowerPrimary).xxx) //primary specular light - + lightSpec*(ksS*pow( abs((TSdotL*TSdotE + sinTSL*sinTSE)),specPowerSecondary).xxx)*specColor.xyz //secondary specular light - + lightSpec*(ksP_sparkles*pow( specPrimary,specPowerPrimarySparkles).xxx) //sparkles - ; - - outputColor.a = g_alpha; - - return outputColor; -} - -struct Depth_PSOut -{ - float Z: SV_Target0; -}; - -Depth_PSOut RenderDepthPSSmall(HairPointDepth input) -{ - Depth_PSOut output; - output.Z = input.depth; - return output; -} - -void VoxelizeDensity3(inout float4 RT, float4 Zmin, float4 Zmax, float z) -{ - float A = RGBA8_PRECISION_DENSITY; - if (z >= Zmin.x) RT.x = A; - if (z >= Zmin.y) RT.y = A; - if (z >= Zmin.z) RT.z = A; - RT.w = 10000; -} - -//this version of deep shadow maps shader just does 4 layers. -//to do more layers go to the function RenderDepthPSSmall_DOM_MRT -float4 RenderDepthPSSmall_DOM(HairPointDepth input) : SV_Target -{ - float4 output = float4(0,0,0,0); - - float2 tex = float2(input.Position.x/g_lightBufferRes, input.Position.y/g_lightBufferRes); - float startDepth = tHairDepthMap.SampleLevel(samPointClamp, tex.xy, 0 ).x; - - VoxelizeDensity3(output, g_Zmin[0], g_Zmax[0], input.depth - startDepth); - output.w = startDepth; - - return output; -} - -struct Opacity_PSOut -{ - float4 RT0 : SV_Target0; - float4 RT1 : SV_Target1; - float4 RT2 : SV_Target2; - float4 RT3 : SV_Target3; -}; - -/* -void VoxelizeDensity(inout float4 RT, float4 Zmin, float4 Zmax, float z) -{ - float A = RGBA8_PRECISION_DENSITY; - - if (z >= Zmin.x) RT.x = A; - if (z >= Zmin.y) RT.y = A; - if (z >= Zmin.z) RT.z = A; - if (z >= Zmin.w) RT.w = A; - -} - -Opacity_PSOut RenderDepthPSSmall_DOM_MRT(HairPointDepth input) -{ - Opacity_PSOut OUT = (Opacity_PSOut)0.0f; - OUT.RT0.x = input.depth; - float z = input.depth; - float A = RGBA8_PRECISION_DENSITY; - - if (z >= g_Zmin[0].x && z < g_Zmax[0].x) OUT.RT0.y = A; - if (z >= g_Zmin[0].y && z < g_Zmax[0].y) OUT.RT0.z = A; - if (z >= g_Zmin[0].z && z < g_Zmax[0].z) OUT.RT0.w = A; - - VoxelizeDensity(OUT.RT1, g_Zmin[1], g_Zmax[1], z); - VoxelizeDensity(OUT.RT2, g_Zmin[2], g_Zmax[2], z); - VoxelizeDensity(OUT.RT3, g_Zmin[3], g_Zmax[3], z); - - return OUT; -}*/ - -struct PostProc_VSOut -{ - float4 pos : SV_Position; - float2 tex : TEXCOORD; -}; - -//Vertex shader that generates a full screen triangle with texcoords -//To use draw 3 vertices with primitive type triangle strip -PostProc_VSOut FullScreenTriVS( uint id : SV_VertexID ) -{ - PostProc_VSOut output = (PostProc_VSOut)0.0f; - output.tex = float2( (id << 1) & 2, id & 2 ); - output.pos = float4( output.tex * float2( 2.0f, -2.0f ) + float2( -1.0f, 1.0f), 0.0f, 1.0f ); - return output; -} - -float4 VisDepthsPS ( PostProc_VSOut IN ) : SV_TARGET -{ - float4 val = tShadowMap.SampleLevel(samPointClamp, IN.tex.xy, 0 ); - float4 output = float4(0,0,0,0); - - output.x = (val.x - g_ZNear) / (g_ZFar - g_ZNear); - - return output; -} - -float4 CopyTexturePS ( PostProc_VSOut IN ) : SV_TARGET -{ - float z0 = tHairDepthMap.SampleLevel(samPointClamp, IN.tex.xy, 0 ).x; - return float4(0,0,0,z0); -} - -struct MRT_PSOut -{ - float4 RT0 : SV_Target0; - float4 RT1 : SV_Target1; - float4 RT2 : SV_Target2; - float4 RT3 : SV_Target3; - float4 RT4 : SV_Target4; - float4 RT5 : SV_Target5; - float4 RT6 : SV_Target6; - float4 RT7 : SV_Target7; -}; - -void addDensityToMRT(inout float4 outputCol,int rgbaIndex) -{ - if(rgbaIndex == 0) - outputCol.x = 1; - else if(rgbaIndex == 1) - outputCol.y = 1; - else if(rgbaIndex == 2) - outputCol.z = 1; - else - outputCol.w = 1; -} - -MRT_PSOut RenderPSForGridMRT(HairPointGrid input) -{ - MRT_PSOut output = (MRT_PSOut)0; - - if(input.distance<0 || input.distance>1) - return output; - - int rtIndex = floor(input.distance * 8.0); - int rgbaIndex = 0x3 & int(input.distance * 32.0); - - if(rtIndex==0) - addDensityToMRT(output.RT0,rgbaIndex); - if(rtIndex==1) - addDensityToMRT(output.RT1,rgbaIndex); - if(rtIndex==2) - addDensityToMRT(output.RT2,rgbaIndex); - if(rtIndex==3) - addDensityToMRT(output.RT3,rgbaIndex); - if(rtIndex==4) - addDensityToMRT(output.RT4,rgbaIndex); - if(rtIndex==5) - addDensityToMRT(output.RT5,rgbaIndex); - if(rtIndex==6) - addDensityToMRT(output.RT6,rgbaIndex); - if(rtIndex==7) - addDensityToMRT(output.RT7,rgbaIndex); - - return output; -} - -// PCF for Mesh and floor rendering -SamplerComparisonState FILT_PCF -{ - AddressU = Clamp; - AddressV = Clamp; - Filter = COMPARISON_MIN_MAG_LINEAR_MIP_POINT; - ComparisonFunc = Less_Equal; -}; - -float BoxFilterStart( float fWidth ) //Assumes filter is odd -{ - return ( ( fWidth - 1.0f ) / 2.0f ); -} - -float DOM_FILTER( float2 tex, float fragDepth, float filterWidth ) -{ - //PreShader - This should all be optimized away by the compiler - //==================================== - float fStartOffset = BoxFilterStart( filterWidth ); - float texOffset = 1.0f / fg_textureWidth; - //==================================== - - fragDepth -= 0.3f; - tex -= fStartOffset * texOffset; - - float lit = 0.0f; - for( int i = 0; i < filterWidth; ++i ) - for( int j = 0; j < filterWidth; ++j ) - { - lit += 1.0f - DOMContribution(fragDepth, float2( tex.x + i * texOffset, tex.y + j * texOffset ), int2(0,0) );//tex, int2(i*texOffset, j*texOffset)); - } - return lit / ( filterWidth * filterWidth ); - -} - -float PCF_FILTER( float2 tex, float fragDepth, float filterWidth, Texture2D textureIn ) -{ - //PreShader - This should all be optimized away by the compiler - //==================================== - float fStartOffset = BoxFilterStart( filterWidth ); - float texOffset = 1.0f / fg_textureWidth; - //==================================== - - fragDepth -= 0.3f; - tex -= fStartOffset * texOffset; - - float lit = 0.0f; - for( int i = 0; i < filterWidth; ++i ) - for( int j = 0; j < filterWidth; ++j ) - { - lit += textureIn.SampleCmpLevelZero( FILT_PCF, float2( tex.x + i * texOffset, tex.y + j * texOffset ), fragDepth ); - } - return lit / ( filterWidth * filterWidth ); -} - - -float SHADOW_FILTER( float2 tex, float fragDepth, float filterWidth ) -{ - return PCF_FILTER( tex, fragDepth, filterWidth, tShadowMap ); -} - -// Mesh rendering -struct MeshVertexIn -{ - float3 Position : POSITION; - float3 Normal : NORMAL; - float2 TexCoord : TEXCOORD; - float3 Tangent : TANGENT; -}; - -struct MeshVertexOut -{ - float4 Position : SV_Position; - float3 Normal : Normal; - float2 TexCoord : TexCoord; - float Depth : DEPTH; - float3 wpos : WPOS; -}; - - -struct MeshVertexOutShadows -{ - float4 Position : SV_Position; - float3 Normal : Normal; - float2 TexCoord : TexCoord; - float Depth : DEPTH; - float3 wpos : WPOS; - float2 lightTexCoords : ltc; -}; - -struct PsCnDOutput -{ - float4 Color : SV_Target0; -}; - -MeshVertexOut MeshVS(MeshVertexIn vertexIn) -{ - MeshVertexOut vertex; - vertex.Position = mul(float4(vertexIn.Position.xyz, 1), ViewProjection); - vertex.Normal = normalize(vertexIn.Normal); - vertex.TexCoord = vertexIn.TexCoord; - vertex.Depth = vertex.Position.z/vertex.Position.w; - vertex.wpos = mul(float4(vertexIn.Position.xyz, 1), TotalTransformation).xyz; - return vertex; -} - -PsCnDOutput MeshPS(MeshVertexOut vertex) -{ - PsCnDOutput ret; - - float3 ambientColor = float3(1.0f,1.0f,1.0f); - if(g_useScalpTexture) - ambientColor = hairTexture.Sample(samLinear, vertex.TexCoord).xyz; - else - { - ambientColor = meshAOMap.Sample(samLinear, vertex.TexCoord).xyz; - ambientColor = clamp( ambientColor,0.6,1.0); - } - - float kd=1.0; - float ks=0.1; - float3 L = vLightDir; - float diffuseLighting = dot(-vertex.Normal, L); - diffuseLighting = 0.5f*(diffuseLighting)+0.5f; - float3 E = normalize(TransformedEyePosition - vertex.wpos); - float3 R = reflect(E,vertex.Normal); - float specularLighting = pow(max(dot(R,L),0.0),5); - - ret.Color = float4((diffuseLighting*kd + specularLighting*ks)*ambientColor,1); - - return ret; -} - -MeshVertexOutShadows MeshVSShadows(MeshVertexIn vertexIn) -{ - MeshVertexOutShadows vertex; - vertex.Position = mul(float4(vertexIn.Position, 1), ViewProjection); - vertex.Normal = normalize(vertexIn.Normal); - vertex.TexCoord = vertexIn.TexCoord; - vertex.Depth = vertex.Position.z/vertex.Position.w; - float3 wpos = mul(float4(vertexIn.Position, 1), TotalTransformation).xyz; - vertex.wpos = wpos; - vertex.lightTexCoords = mul(float4(wpos.xyz, 1), mLightViewProjClip2Tex).xy; - return vertex; -} - -PsCnDOutput MeshPSShadows(MeshVertexOutShadows vertex) -{ - PsCnDOutput ret; - - float3 ambientColor = float3(1.0f,1.0f,1.0f); - if(!g_useScalpTexture) - ambientColor = meshAOMap.Sample(samLinear, vertex.TexCoord).xyz; - ambientColor = clamp( ambientColor,0.6,1.0); - float3 ambient = ambientColor*0.15; - - float lit = 1.0f; - if(g_useShadows) - { - float fDepth = mul(float4(vertex.wpos, 1), mLightView).z; - lit = SHADOW_FILTER( vertex.lightTexCoords, fDepth, 22 ); - } - - float kd=0.85; - float ks=0.1; - float3 L = vLightDir; - float diffuseLighting = dot(-vertex.Normal, L); - diffuseLighting = 0.5f*(diffuseLighting)+0.5f; - - //and a little bit of static hero lighting for the face which never changes - float3 L2 = float3(-0.102307, -0.729127, 0.676688); - float key = 0.15*(ambient.x + saturate(dot(-vertex.Normal, L2))).x; - - - float3 E = normalize(TransformedEyePosition - vertex.wpos); - float3 R = reflect(E,vertex.Normal); - float specularLighting = pow(max(dot(R,L),0.0),5); - - ret.Color = float4((diffuseLighting*kd + specularLighting*ks)*lit*ambientColor + key,1); - - return ret; -} - -//render the plane -struct VSPlaneIn -{ - float3 pos : POSITION; - float3 norm : NORMAL; -}; - -struct PSIn -{ - float4 pos : SV_Position; - float3 wNorm : wNorm; - float3 wLight : wLight; - float fDepth : fDepth; - float2 lightTexCoords : ltc; -}; - -PSIn VSDrawPlane( VSPlaneIn input ) -{ - PSIn output = (PSIn)0.0f; - - output.pos = mul(float4(input.pos.xyz, 1), ViewProjection); - output.wNorm = input.norm; - - float3 lightVec = vLightPos.xyz - input.pos.xyz; - output.wLight = normalize( lightVec ); - output.fDepth = mul(float4(input.pos.xyz, 1), mLightView).z; - output.lightTexCoords = mul(float4(input.pos.xyz, 1), mLightViewProjClip2Tex).xy; - - return output; -} - -float4 PSDrawPlane( uniform int g_useShadows, PSIn input ) : SV_Target -{ - float4 output = (float4)0.0f; - - float lit = 1.0f; - - if(g_useShadows) - lit = SHADOW_FILTER( input.lightTexCoords, input.fDepth, 16 ); - - float3 wLight = normalize( input.wLight ); - float3 wNormal; - - wNormal = normalize( input.wNorm ); - - float diffuseLighting = 1.0f; - diffuseLighting *= dot( normalize( wNormal ), wLight ); - //diffuseLighting = clamp((diffuseLighting - 0.75)*4,0,1); - //diffuseLighting = clamp((diffuseLighting-0.5),0,1)*1.3684 + 0.3176f; - return float4( 1.0f, 1.0f, 1.0f, 1.0f ) * diffuseLighting * lit; -} - -//render collision objects----------------------------------------------- -MeshVertexOut CollisionVS(MeshVertexIn vertexIn) -{ - MeshVertexOut vertex; - float3 Pos = vertexIn.Position; - bool render = true; - if(render) - { - Pos = mul(float4(Pos,1), CollisionSphereTransformations[g_currentCollisionSphere]).xyz; - //Pos = mul(float4(Pos,1), SphereNoMoveImplicitTransform[g_currentCollisionSphere]).xyz; - //Pos = mul(float4(Pos,1), CollisionCylinderTransformations[g_currentCollisionSphere]).xyz; - Pos = mul(float4(Pos,1), HairToWorldTransform).xyz; - } - else - Pos = float3(1000,1000,1000); - vertex.Position = mul(float4(Pos, 1), ViewProjection); - vertex.Normal = normalize(vertexIn.Normal); - vertex.TexCoord = vertexIn.TexCoord; - return vertex; -} - -float4 CollisionPS(MeshVertexOut vertex) : SV_Target -{ - return float4(1,0,0,1); -} - -//note: the code for rendering skinned meshes to the shadow map is further below under RenderSkinnedMeshDepth -struct MeshDepthVertexOut -{ - float4 Position : SV_Position; - float Depth : texcoord; -}; - -MeshDepthVertexOut MeshDepthVS(MeshVertexIn vertexIn) -{ - MeshDepthVertexOut vertex; - //TO DO SHADOWS: put TotalTransformation inside the mLightViewProj matrix; then we dont need to multiply by TotalTransformation below - float3 wPos = mul(float4(vertexIn.Position, 1), TotalTransformation).xyz; - vertex.Position = mul(float4(wPos, 1), mLightViewProj); - vertex.Depth = WorldToDepth(wPos); - return vertex; -} - -Depth_PSOut MeshDepthPS(MeshDepthVertexOut vertex) -{ - Depth_PSOut output; - output.Z = vertex.Depth; - return output; -} - -float4 MeshDepthPS_DOM(MeshDepthVertexOut vertex) : SV_Target -{ - float4 output = float4(0,0,0,0); - float2 tex = float2(vertex.Position.x/g_lightBufferRes, vertex.Position.y/g_lightBufferRes); - float startDepth = tHairDepthMap.SampleLevel(samPointClamp, tex.xy, 0 ).x; - VoxelizeDensity3(output, g_Zmin[0], g_Zmax[0], vertex.Depth - startDepth); - output.w = startDepth; - return output; -} - -// arrow and cube rendering -struct VS_INPUT_ARROW -{ - float3 Position : POSITION; -}; - -struct VS_OUTPUT_ARROW -{ - float4 Position : SV_POSITION; - float Depth : DEPTH; -}; - -//vertex shader for rendering the arrow -VS_OUTPUT_ARROW VSArrow( VS_INPUT_ARROW input ) -{ - VS_OUTPUT_ARROW output = (VS_OUTPUT_ARROW)0; - output.Position = mul( float4(input.Position, 1), ViewProjection ); - output.Depth = output.Position.z/output.Position.w; - return output; -} - -//pixel shader for arrow -PsCnDOutput PSArrow(VS_OUTPUT_ARROW In) -{ - PsCnDOutput ret; - ret.Color = g_arrowColor; -// ret.Depth = In.Depth; - return ret; -} - -//inter-hair interaction and wind hair interaction -//display hair density texture------------------------------------------------------------ -struct VS_INPUT_POSITION_TEX -{ - float4 Position : POSITION; - float3 Texcoords : TEXCOORD; - -}; - -struct VS_OUTPUT_POSITION_TEX -{ - float4 Position : SV_POSITION; - float3 Texcoords : TEXCOORD0; - -}; - -struct VS_INPUT_FLUIDSIM -{ - float3 position : POSITION; // 2D slice vertex coordinates in clip space - float3 textureCoords0 : TEXCOORD; // 3D cell coordinates (x,y,z in 0-dimension range) -}; - -struct VS_OUTPUT_FLUIDSIM -{ - float4 pos : SV_Position; - float3 texcoords : TEXCOORD1; - float rtindex : rtindex; -}; - -struct GS_OUTPUT_FLUIDSIM -{ - float4 pos : SV_Position; // 2D slice vertex coordinates in homogenous clip space - float3 texcoords : TEXCOORD1; // 3D cell texcoords (x,y,z in 0-1 range) - uint RTIndex : SV_RenderTargetArrayIndex; // used to choose the destination slice -}; - -VS_OUTPUT_POSITION_TEX VS_GRID( VS_INPUT_POSITION_TEX input) -{ - VS_OUTPUT_POSITION_TEX output = (VS_OUTPUT_POSITION_TEX)0; - - output.Position = float4(input.Position.x, input.Position.y, input.Position.z, 1.0); - output.Texcoords = float3( (input.Texcoords.x)/(g_textureWidth), - (input.Texcoords.y)/(g_textureHeight), - input.Texcoords.z); - return output; -} - -VS_OUTPUT_FLUIDSIM VS_GRID_FLUIDSIM( VS_INPUT_FLUIDSIM input) -{ - VS_OUTPUT_FLUIDSIM output = (VS_OUTPUT_FLUIDSIM)0; - - output.pos = float4(input.position.x, input.position.y, input.position.z, 1.0); - output.rtindex = input.textureCoords0.z; - output.texcoords = float3( (input.textureCoords0.x)/(fluidg_textureWidth), - (input.textureCoords0.y)/(fluidg_textureHeight), - (input.textureCoords0.z)/(fluidg_textureDepth)*g_textureDepth); - return output; -} - -[maxvertexcount (3)] -void GS_ARRAY(triangle VS_OUTPUT_FLUIDSIM In[3], inout TriangleStream triStream) -{ - GS_OUTPUT_FLUIDSIM Out; - Out.RTIndex = In[0].rtindex; - - Out.pos = In[0].pos; - Out.texcoords = In[0].texcoords; - triStream.Append( Out ); - - Out.pos = In[1].pos; - Out.texcoords = In[1].texcoords; - triStream.Append( Out ); - - Out.pos = In[2].pos; - Out.texcoords = In[2].texcoords; - triStream.Append( Out ); - - triStream.RestartStrip( ); -} - -float4 PS_DEMUX_TO_3D_OBSTACLE_TEX( GS_OUTPUT_FLUIDSIM input ) : SV_Target -{ - //----------------------------------- - //find if the cell is inside an obstacle - - float returnVal; - - float4 posInWorld = mul( float4(input.texcoords.x-0.5, 0.5-input.texcoords.y,(input.texcoords.z/g_textureDepth) - 0.5,1),GridToWorld); - - for(int i=0;i0) - return obstacleDensity; - - //----------------------------------- - - int zSlice = floor(g_gridZIndex/4.0); - int rgba = 0x3 & g_gridZIndex; - - float3 texcoords = float3(input.Texcoords.xy,zSlice); - float4 density = abs(Texture_density.SampleLevel(samPointClamp,texcoords,0)); - - if(rgba == 0) - return density.r; - else if(rgba == 1) - return density.g; - else if(rgba == 2) - return density.b; - else - return density.a; - -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL/HairFluidSim.hlsl b/Samples/Media/materials/programs/HLSL/HairFluidSim.hlsl deleted file mode 100644 index bd45ea2da22..00000000000 --- a/Samples/Media/materials/programs/HLSL/HairFluidSim.hlsl +++ /dev/null @@ -1,800 +0,0 @@ -/* ----------------------------------------------------------- -Hair Tessellation sample from NVIDIA's DirectX 11 SDK: -http://developer.nvidia.com/nvidia-graphics-sdk-11-direct3d ----------------------------------------------------------- -*/ - -// These are the values used when filling the obstacle textures -#define OBSTACLE_EXTERIOR 1.0f -#define OBSTACLE_BOUNDARY 128.0f/255.0f -#define OBSTACLE_INTERIOR 0.0f - -//-------------------------------------------------------------------------------------- -// Shaders to implement a "stable fluids" style semi-Lagrangian solver for 3D smoke -//-------------------------------------------------------------------------------------- -// It assumes the velocity and pressure grids are collocated -// It handles boundary conditions for static obstacles stored as an in/out voxel volume -// MACCORMACK is supported for smoke density advection -// The diffusion step is skipped -//-------------------------------------------------------------------------------------- - -#define FT_SMOKE 0 -#define FT_FIRE 1 -#define FT_LIQUID 2 - -// Textures -Texture2D Texture_inDensity; - -Texture3D Texture_pressure; -Texture3D Texture_velocity; -Texture3D Texture_vorticity; -Texture3D Texture_divergence; - -Texture3D Texture_phi; -Texture3D Texture_phi_hat; -Texture3D Texture_phi_next; -Texture3D Texture_levelset; - -Texture3D Texture_obstacles; -Texture3D Texture_obstvelocity; - - -// Variables -shared cbuffer cb0 -{ - //int fluidType = FT_SMOKE; - int g_advectAsTemperature = 0; - int g_treatAsLiquidVelocity = 0; - int g_drawTextureNumber = 1; - float g_textureWidth; - float g_textureHeight; - float g_textureDepth; - - // NOTE: The spacing between simulation grid cells is \delta x = 1, so it is omitted everywhere - float g_timestep = 1.0f; - float g_decay = 1.0f; // this is the (1.0 - dissipation_rate). dissipation_rate >= 0 ==> g_decay <= 1 - float g_viscosity = 5e-6f;// kinematic g_viscosity - float g_vortConfinementScale = 0.0f; // this is typically a small value >= 0 - float3 g_gravity = 0; // note this is assumed to be given as pre-multiplied by the g_timestep, so it's really velocity: cells per step - float g_temperatureLoss = 0.003;// a constant amount subtracted at every step when advecting a quatnity as tempterature - - float g_radius; - float3 g_center; - float4 g_color; - - float4 g_obstBoxVelocity = float4(0, 0, 0, 0); - float3 g_obstBoxLBDcorner; - float3 g_obstBoxRTUcorner; -} - - -//parameters for attenuating velocity based on porous obstacles. -//these values are not hooked into CPP code yet, and so this option is not used currently -shared cbuffer constants -{ - bool doVelocityAttenuation = false; - float maxDensityAmount = 0.7; - float maxDensityg_decay = 0.95; - float liquidHeight = 24; - float rho = 1.2f; // rho = density of the fluid -} - -SamplerState samPointClamp -{ - Filter = MIN_MAG_MIP_POINT; - AddressU = Clamp; - AddressV = Clamp; - AddressW = Clamp; -}; - -SamplerState samLinear -{ - Filter = MIN_MAG_MIP_LINEAR; - AddressU = Clamp; - AddressV = Clamp; - AddressW = Clamp; -}; - -// Structs -struct VS_INPUT_FLUIDSIM -{ - float3 position : POSITION; // 2D slice vertex coordinates in clip space - float3 textureCoords0 : TEXCOORD; // 3D cell coordinates (x,y,z in 0-dimension range) -}; - -struct VS_OUTPUT_FLUIDSIM -{ - float4 pos : SV_Position; - float3 cell0 : TEXCOORD0; - float3 texcoords : TEXCOORD1; - float2 LR : TEXCOORD2; - float2 BT : TEXCOORD3; - float2 DU : TEXCOORD4; -}; - -struct GS_OUTPUT_FLUIDSIM -{ - float4 pos : SV_Position; // 2D slice vertex coordinates in homogenous clip space - float3 cell0 : TEXCOORD0; // 3D cell coordinates (x,y,z in 0-dimension range) - float3 texcoords : TEXCOORD1; // 3D cell texcoords (x,y,z in 0-1 range) - float2 LR : TEXCOORD2; // 3D cell texcoords for the Left and Right neighbors - float2 BT : TEXCOORD3; // 3D cell texcoords for the Bottom and Top neighbors - float2 DU : TEXCOORD4; // 3D cell texcoords for the Down and Up neighbors - uint RTIndex : SV_RenderTargetArrayIndex; // used to choose the destination slice -}; - -#define LEFTCELL float3 (input.LR.x, input.texcoords.y, input.texcoords.z) -#define RIGHTCELL float3 (input.LR.y, input.texcoords.y, input.texcoords.z) -#define BOTTOMCELL float3 (input.texcoords.x, input.BT.x, input.texcoords.z) -#define TOPCELL float3 (input.texcoords.x, input.BT.y, input.texcoords.z) -#define DOWNCELL float3 (input.texcoords.x, input.texcoords.y, input.DU.x) -#define UPCELL float3 (input.texcoords.x, input.texcoords.y, input.DU.y) - -// Vertex shaders -VS_OUTPUT_FLUIDSIM VS_GRID( VS_INPUT_FLUIDSIM input) -{ - VS_OUTPUT_FLUIDSIM output = (VS_OUTPUT_FLUIDSIM)0; - - output.pos = float4(input.position.x, input.position.y, input.position.z, 1.0); - output.cell0 = float3(input.textureCoords0.x, input.textureCoords0.y, input.textureCoords0.z); - output.texcoords = float3( (input.textureCoords0.x)/(g_textureWidth), - (input.textureCoords0.y)/(g_textureHeight), - (input.textureCoords0.z+0.5)/(g_textureDepth)); - - float x = output.texcoords.x; - float y = output.texcoords.y; - float z = output.texcoords.z; - - // compute single texel offsets in each dimension - float invW = 1.0/g_textureWidth; - float invH = 1.0/g_textureHeight; - float invD = 1.0/g_textureDepth; - - output.LR = float2(x - invW, x + invW); - output.BT = float2(y - invH, y + invH); - output.DU = float2(z - invD, z + invD); - - return output; -} - -[maxvertexcount (3)] -void GS_ARRAY(triangle VS_OUTPUT_FLUIDSIM In[3], inout TriangleStream triStream) -{ - GS_OUTPUT_FLUIDSIM Out; - // cell0.z of the first vertex in the triangle determines the destination slice index - Out.RTIndex = In[0].cell0.z; - for(int v=0; v<3; v++) - { - Out.pos = In[v].pos; - Out.cell0 = In[v].cell0; - Out.texcoords = In[v].texcoords; - Out.LR = In[v].LR; - Out.BT = In[v].BT; - Out.DU = In[v].DU; - triStream.Append( Out ); - } - triStream.RestartStrip( ); -} - -[maxvertexcount (2)] -void GS_ARRAY_LINE(line VS_OUTPUT_FLUIDSIM In[2], inout LineStream Stream) -{ - GS_OUTPUT_FLUIDSIM Out; - // cell0.z of the first vertex in the line determines the destination slice index - Out.RTIndex = In[0].cell0.z; - for(int v=0; v<2; v++) - { - Out.pos = In[v].pos; - Out.cell0 = In[v].cell0; - Out.texcoords = In[v].texcoords; - Out.LR = In[v].LR; - Out.BT = In[v].BT; - Out.DU = In[v].DU; - - Stream.Append( Out ); - } - Stream.RestartStrip( ); -} - -// Helper functions -float4 GetObstVelocity( float3 cellTexCoords ) -{ - return Texture_obstvelocity.SampleLevel(samPointClamp, cellTexCoords, 0); -} - -bool IsNonEmptyCell( float3 cellTexCoords ) -{ - return (Texture_obstacles.SampleLevel(samPointClamp, cellTexCoords, 0).r <= OBSTACLE_BOUNDARY); -} - -bool IsNonEmptyNonBoundaryCell( float3 cellTexCoords ) -{ - float obst = Texture_obstacles.SampleLevel(samPointClamp, cellTexCoords, 0).r; - return (obst < OBSTACLE_BOUNDARY); -} - -bool IsBoundaryCell( float3 cellTexCoords ) -{ - return (Texture_obstacles.SampleLevel(samPointClamp, cellTexCoords, 0).r == OBSTACLE_BOUNDARY); -} - -float3 GetAdvectedPosTexCoords(GS_OUTPUT_FLUIDSIM input) -{ - float3 pos = input.cell0; - - pos -= g_timestep * Texture_velocity.SampleLevel( samPointClamp, input.texcoords, 0 ).xyz; - - return float3(pos.x/g_textureWidth, pos.y/g_textureHeight, (pos.z+0.5)/g_textureDepth); -} - -bool IsOutsideSimulationDomain( float3 cellTexcoords ) -{ - if( g_treatAsLiquidVelocity == 1) - { - if( Texture_levelset.SampleLevel(samPointClamp, cellTexcoords, 0 ).r <= 0 ) - return false; - else - return true; - } - else - { - return false; - } -} - -#define SAMPLE_NEIGHBORS( texture3d, input ) \ - float L = texture3d.SampleLevel( samPointClamp, LEFTCELL, 0).r; \ - float R = texture3d.SampleLevel( samPointClamp, RIGHTCELL, 0).r; \ - float B = texture3d.SampleLevel( samPointClamp, BOTTOMCELL, 0).r; \ - float T = texture3d.SampleLevel( samPointClamp, TOPCELL, 0).r; \ - float D = texture3d.SampleLevel( samPointClamp, DOWNCELL, 0).r; \ - float U = texture3d.SampleLevel( samPointClamp, UPCELL, 0).r; - -float3 Gradient( Texture3D texture3d, VS_OUTPUT_FLUIDSIM input ) -{ - SAMPLE_NEIGHBORS( texture3d, input ); - return 0.5f * float3(R - L, T - B, U - D); -} - -float3 Gradient( Texture3D texture3d, GS_OUTPUT_FLUIDSIM input ) -{ - SAMPLE_NEIGHBORS( texture3d, input ); - return 0.5f * float3(R - L, T - B, U - D); -} - -float3 Gradient( Texture3D texture3d, GS_OUTPUT_FLUIDSIM input, out bool isBoundary, float minSlope, out bool highEnoughSlope ) -{ - SAMPLE_NEIGHBORS( texture3d, input ); - - float LBD = texture3d.SampleLevel( samPointClamp, float3 (input.LR.x, input.BT.x, input.DU.x), 0).r; - float LBC = texture3d.SampleLevel( samPointClamp, float3 (input.LR.x, input.BT.x, input.texcoords.z), 0).r; - float LBU = texture3d.SampleLevel( samPointClamp, float3 (input.LR.x, input.BT.x, input.DU.y), 0).r; - float LCD = texture3d.SampleLevel( samPointClamp, float3 (input.LR.x, input.texcoords.y, input.DU.x), 0).r; - //float LCC = texture3d.SampleLevel( samPointClamp, float3 (input.LR.x, input.texcoords.y, input.texcoords.z), 0).r; - float LCU = texture3d.SampleLevel( samPointClamp, float3 (input.LR.x, input.texcoords.y, input.DU.y), 0).r; - float LTD = texture3d.SampleLevel( samPointClamp, float3 (input.LR.x, input.BT.y, input.DU.x), 0).r; - float LTC = texture3d.SampleLevel( samPointClamp, float3 (input.LR.x, input.BT.y, input.texcoords.z), 0).r; - float LTU = texture3d.SampleLevel( samPointClamp, float3 (input.LR.x, input.BT.y, input.DU.y), 0).r; - - float CBD = texture3d.SampleLevel( samPointClamp, float3 (input.texcoords.x, input.BT.x, input.DU.x), 0).r; - //float CBC = texture3d.SampleLevel( samPointClamp, float3 (input.texcoords.x, input.BT.x, input.texcoords.z), 0).r; - float CBU = texture3d.SampleLevel( samPointClamp, float3 (input.texcoords.x, input.BT.x, input.DU.y), 0).r; - //float CCD = texture3d.SampleLevel( samPointClamp, float3 (input.texcoords.x, input.texcoords.y, input.DU.x), 0).r; - float CCC = texture3d.SampleLevel( samPointClamp, float3 (input.texcoords.x, input.texcoords.y, input.texcoords.z), 0).r; - //float CCU = texture3d.SampleLevel( samPointClamp, float3 (input.texcoords.x, input.texcoords.y, input.DU.y), 0).r; - float CTD = texture3d.SampleLevel( samPointClamp, float3 (input.texcoords.x, input.BT.y, input.DU.x), 0).r; - //float CTC = texture3d.SampleLevel( samPointClamp, float3 (input.texcoords.x, input.BT.y, input.texcoords.z)), 0).r; - float CTU = texture3d.SampleLevel( samPointClamp, float3 (input.texcoords.x, input.BT.y, input.DU.y), 0).r; - - float RBD = texture3d.SampleLevel( samPointClamp, float3 (input.LR.y, input.BT.x, input.DU.x), 0).r; - float RBC = texture3d.SampleLevel( samPointClamp, float3 (input.LR.y, input.BT.x, input.texcoords.z), 0).r; - float RBU = texture3d.SampleLevel( samPointClamp, float3 (input.LR.y, input.BT.x, input.DU.y), 0).r; - float RCD = texture3d.SampleLevel( samPointClamp, float3 (input.LR.y, input.texcoords.y, input.DU.x), 0).r; - //float RCC = texture3d.SampleLevel( samPointClamp, float3 (input.LR.y, input.texcoords.y, input.texcoords.z), 0).r; - float RCU = texture3d.SampleLevel( samPointClamp, float3 (input.LR.y, input.texcoords.y, input.DU.y), 0).r; - float RTD = texture3d.SampleLevel( samPointClamp, float3 (input.LR.y, input.BT.y, input.DU.x), 0).r; - float RTC = texture3d.SampleLevel( samPointClamp, float3 (input.LR.y, input.BT.y, input.texcoords.z), 0).r; - float RTU = texture3d.SampleLevel( samPointClamp, float3 (input.LR.y, input.BT.y, input.DU.y), 0).r; - - // is this cell next to the LevelSet boundary - float product = L * R * B * T * D * U; - product *= LBD * LBC * LBU * LCD * LCU * LTD * LTC * LTU - * CBD * CBU * CTD * CTU - * RBD * RBC * RBU * RCD * RCU * RTD * RTC * RTU; - isBoundary = product < 0; - - // is the slope high enough - highEnoughSlope = (abs(R - CCC) > minSlope) || (abs(L - CCC) > minSlope) || - (abs(T - CCC) > minSlope) || (abs(B - CCC) > minSlope) || - (abs(U - CCC) > minSlope) || (abs(D - CCC) > minSlope); - - return 0.5f * float3(R - L, T - B, U - D); -} - -// Pixel shaders -float4 PS_ADVECT_MACCORMACK( GS_OUTPUT_FLUIDSIM input ) : SV_Target -{ - if( IsOutsideSimulationDomain(input.texcoords.xyz ) ) - return 0; - - if( IsNonEmptyCell(input.texcoords.xyz) ) - return 0; - - // get advected new position - float3 npos = input.cell0 - g_timestep * Texture_velocity.SampleLevel( samPointClamp, input.texcoords, 0 ).xyz; - - // convert new position to texture coordinates - float3 nposTC = float3(npos.x/g_textureWidth, npos.y/g_textureHeight, (npos.z+0.5)/g_textureDepth); - - // find the texel corner closest to the semi-Lagrangian "particle" - float3 nposTexel = floor( npos + float3( 0.5f, 0.5f, 0.5f ) ); - float3 nposTexelTC = float3( nposTexel.x/g_textureWidth, nposTexel.y/g_textureHeight, nposTexel.z/g_textureDepth); - - // ht (half-texel) - float3 ht = float3(0.5f/g_textureWidth, 0.5f/g_textureHeight, 0.5f/g_textureDepth); - - // get the values of nodes that contribute to the interpolated value - // (texel centers are at half-integer locations) - float4 nodeValues[8]; - nodeValues[0] = Texture_phi.SampleLevel( samPointClamp, nposTexelTC + float3(-ht.x, -ht.y, -ht.z), 0 ); - nodeValues[1] = Texture_phi.SampleLevel( samPointClamp, nposTexelTC + float3(-ht.x, -ht.y, ht.z), 0 ); - nodeValues[2] = Texture_phi.SampleLevel( samPointClamp, nposTexelTC + float3(-ht.x, ht.y, -ht.z), 0 ); - nodeValues[3] = Texture_phi.SampleLevel( samPointClamp, nposTexelTC + float3(-ht.x, ht.y, ht.z), 0 ); - nodeValues[4] = Texture_phi.SampleLevel( samPointClamp, nposTexelTC + float3( ht.x, -ht.y, -ht.z), 0 ); - nodeValues[5] = Texture_phi.SampleLevel( samPointClamp, nposTexelTC + float3( ht.x, -ht.y, ht.z), 0 ); - nodeValues[6] = Texture_phi.SampleLevel( samPointClamp, nposTexelTC + float3( ht.x, ht.y, -ht.z), 0 ); - nodeValues[7] = Texture_phi.SampleLevel( samPointClamp, nposTexelTC + float3( ht.x, ht.y, ht.z), 0 ); - - // determine a valid range for the result - float4 phiMin = min(min(min(nodeValues[0], nodeValues [1]), nodeValues [2]), nodeValues [3]); - phiMin = min(min(min(min(phiMin, nodeValues [4]), nodeValues [5]), nodeValues [6]), nodeValues [7]); - - float4 phiMax = max(max(max(nodeValues[0], nodeValues [1]), nodeValues [2]), nodeValues [3]); - phiMax = max(max(max(max(phiMax, nodeValues [4]), nodeValues [5]), nodeValues [6]), nodeValues [7]); - - float4 ret; - // Perform final MACCORMACK advection step: - // You can use point sampling and keep Texture_phi_1_hat - // r = Texture_phi_1_hat.SampleLevel( samPointClamp, input.texcoords, 0 ) - // OR use bilerp to avoid the need to keep a separate texture for phi_n_1_hat - ret = Texture_phi.SampleLevel( samLinear, nposTC, 0) - + 0.5 * ( Texture_phi.SampleLevel( samPointClamp, input.texcoords, 0 ) - - Texture_phi_hat.SampleLevel( samPointClamp, input.texcoords, 0 ) ); - - // clamp result to the desired range - ret = max( min( ret, phiMax ), phiMin ) * g_decay; - - if(g_advectAsTemperature) - { - ret -= g_temperatureLoss * g_timestep; - ret = clamp(ret,float4(0,0,0,0),float4(5,5,5,5)); - } - - return ret; -} - -float4 PS_ADVECT( GS_OUTPUT_FLUIDSIM input ) : SV_Target -{ - if( IsOutsideSimulationDomain(input.texcoords.xyz ) ) - return 0; - - float g_decayAmount = g_decay; - - if(doVelocityAttenuation) - { - float obstacle = Texture_obstacles.SampleLevel(samPointClamp, input.texcoords.xyz, 0).r; - if( obstacle <= OBSTACLE_BOUNDARY) return 0; - g_decayAmount *= clamp((obstacle-maxDensityAmount)/(1 - maxDensityAmount),0,1)*(1-maxDensityg_decay)+maxDensityg_decay; - } - else if( IsNonEmptyCell(input.texcoords.xyz) ) - return 0; - - float3 npos = GetAdvectedPosTexCoords(input); - float4 ret = Texture_phi.SampleLevel( samLinear, npos, 0) * g_decayAmount; - - - - if(g_advectAsTemperature) - { - ret -= g_temperatureLoss * g_timestep; - ret = clamp(ret,float4(0,0,0,0),float4(5,5,5,5)); - } - - return ret; -} - -// vorticity confinement shaders -float4 PS_VORTICITY( GS_OUTPUT_FLUIDSIM input ) : SV_Target -{ - float4 L = Texture_velocity.SampleLevel( samPointClamp, LEFTCELL, 0 ); - float4 R = Texture_velocity.SampleLevel( samPointClamp, RIGHTCELL, 0 ); - float4 B = Texture_velocity.SampleLevel( samPointClamp, BOTTOMCELL, 0 ); - float4 T = Texture_velocity.SampleLevel( samPointClamp, TOPCELL, 0 ); - float4 D = Texture_velocity.SampleLevel( samPointClamp, DOWNCELL, 0 ); - float4 U = Texture_velocity.SampleLevel( samPointClamp, UPCELL, 0 ); - - float4 vorticity; - // using central differences: D0_x = (D+_x - D-_x) / 2 - vorticity.xyz = 0.5 * float3( (( T.z - B.z ) - ( U.y - D.y )) , - (( U.x - D.x ) - ( R.z - L.z )) , - (( R.y - L.y ) - ( T.x - B.x )) ); - - return vorticity; -} - -float4 PS_CONFINEMENT( GS_OUTPUT_FLUIDSIM input ) : SV_Target -{ - if( IsOutsideSimulationDomain(input.texcoords.xyz ) ) - return 0; - - if( IsNonEmptyCell(input.texcoords.xyz) ) - return 0; - - float4 omega = Texture_vorticity.SampleLevel( samPointClamp, input.texcoords, 0 ); - - // Potential optimization: don't find length multiple times - do once for the entire texture - float omegaL = length( Texture_vorticity.SampleLevel( samPointClamp, LEFTCELL, 0 ) ); - float omegaR = length( Texture_vorticity.SampleLevel( samPointClamp, RIGHTCELL, 0 ) ); - float omegaB = length( Texture_vorticity.SampleLevel( samPointClamp, BOTTOMCELL, 0 ) ); - float omegaT = length( Texture_vorticity.SampleLevel( samPointClamp, TOPCELL, 0 ) ); - float omegaD = length( Texture_vorticity.SampleLevel( samPointClamp, DOWNCELL, 0 ) ); - float omegaU = length( Texture_vorticity.SampleLevel( samPointClamp, UPCELL, 0 ) ); - - float3 eta = 0.5 * float3( omegaR - omegaL, - omegaT - omegaB, - omegaU - omegaD ); - - eta = normalize( eta + float3(0.001, 0.001, 0.001) ); - - float4 force; - force.xyz = g_timestep * g_vortConfinementScale * float3( eta.y * omega.z - eta.z * omega.y, - eta.z * omega.x - eta.x * omega.z, - eta.x * omega.y - eta.y * omega.x ); - - // Note: the result is added to the current velocity at each cell using "additive blending" - return force; -} - -//diffusion shaders -float4 PS_DIFFUSE( GS_OUTPUT_FLUIDSIM input ) : SV_Target -{ - float4 phi0C = Texture_phi.SampleLevel( samPointClamp, input.texcoords, 0 ); - - float4 phin0L = Texture_phi_next.SampleLevel( samPointClamp, LEFTCELL, 0 ); - float4 phin0R = Texture_phi_next.SampleLevel( samPointClamp, RIGHTCELL, 0 ); - float4 phin0B = Texture_phi_next.SampleLevel( samPointClamp, BOTTOMCELL, 0 ); - float4 phin0T = Texture_phi_next.SampleLevel( samPointClamp, TOPCELL, 0 ); - float4 phin0D = Texture_phi_next.SampleLevel( samPointClamp, DOWNCELL, 0 ); - float4 phin0U = Texture_phi_next.SampleLevel( samPointClamp, UPCELL, 0 ); - - float dT = g_timestep; - float v = g_viscosity; - float dX = 1; - - float4 phin1C = ( (phi0C * dX*dX) - (dT * v * ( phin0L + phin0R + phin0B + phin0T + phin0D + phin0T )) ) / ((6 * dT * v) + (dX*dX)); - - return phin1C; -} - -//pressure projection shaders -float PS_DIVERGENCE( GS_OUTPUT_FLUIDSIM input ) : SV_Target -{ - float4 fieldL = Texture_velocity.SampleLevel( samPointClamp, LEFTCELL, 0 ); - float4 fieldR = Texture_velocity.SampleLevel( samPointClamp, RIGHTCELL, 0 ); - float4 fieldB = Texture_velocity.SampleLevel( samPointClamp, BOTTOMCELL, 0 ); - float4 fieldT = Texture_velocity.SampleLevel( samPointClamp, TOPCELL, 0 ); - float4 fieldD = Texture_velocity.SampleLevel( samPointClamp, DOWNCELL, 0 ); - float4 fieldU = Texture_velocity.SampleLevel( samPointClamp, UPCELL, 0 ); - - if( IsBoundaryCell(LEFTCELL) ) fieldL = GetObstVelocity(LEFTCELL); - if( IsBoundaryCell(RIGHTCELL) ) fieldR = GetObstVelocity(RIGHTCELL); - if( IsBoundaryCell(BOTTOMCELL) )fieldB = GetObstVelocity(BOTTOMCELL); - if( IsBoundaryCell(TOPCELL) ) fieldT = GetObstVelocity(TOPCELL); - if( IsBoundaryCell(DOWNCELL) ) fieldD = GetObstVelocity(DOWNCELL); - if( IsBoundaryCell(UPCELL) ) fieldU = GetObstVelocity(UPCELL); - - float divergence = 0.5 * - ( ( fieldR.x - fieldL.x ) + ( fieldT.y - fieldB.y ) + ( fieldU.z - fieldD.z ) ); - - return divergence; -} - -float PS_SCALAR_JACOBI( GS_OUTPUT_FLUIDSIM input ) : SV_Target -{ - float pCenter = Texture_pressure.SampleLevel( samPointClamp, input.texcoords, 0 ); - float bC = Texture_divergence.SampleLevel( samPointClamp, input.texcoords, 0 ); - - float pL = Texture_pressure.SampleLevel( samPointClamp, LEFTCELL, 0 ); - float pR = Texture_pressure.SampleLevel( samPointClamp, RIGHTCELL, 0 ); - float pB = Texture_pressure.SampleLevel( samPointClamp, BOTTOMCELL, 0 ); - float pT = Texture_pressure.SampleLevel( samPointClamp, TOPCELL, 0 ); - float pD = Texture_pressure.SampleLevel( samPointClamp, DOWNCELL, 0 ); - float pU = Texture_pressure.SampleLevel( samPointClamp, UPCELL, 0 ); - - if( IsBoundaryCell(LEFTCELL) ) pL = pCenter; - if( IsBoundaryCell(RIGHTCELL) ) pR = pCenter; - if( IsBoundaryCell(BOTTOMCELL) )pB = pCenter; - if( IsBoundaryCell(TOPCELL) ) pT = pCenter; - if( IsBoundaryCell(DOWNCELL) ) pD = pCenter; - if( IsBoundaryCell(UPCELL) ) pU = pCenter; - - return( pL + pR + pB + pT + pU + pD - bC ) /6.0; -} - -float4 PS_APPLY_AIR_PRESSURE ( GS_OUTPUT_FLUIDSIM input) : SV_Target -{ - if( IsOutsideSimulationDomain( input.texcoords ) ) - return float4(0.0, 0.0, 0.0, 1.0); - - return float4(0.0, 0.0, 0.0, 0.0); -} - -float4 PS_PROJECT( GS_OUTPUT_FLUIDSIM input ): SV_Target -{ - if( IsOutsideSimulationDomain(input.texcoords.xyz ) ) - return 0; - - if( IsBoundaryCell(input.texcoords.xyz) ) - return GetObstVelocity(input.texcoords.xyz); - - float pCenter = Texture_pressure.SampleLevel( samPointClamp, input.texcoords, 0 ); - float pL = Texture_pressure.SampleLevel( samPointClamp, LEFTCELL, 0 ); - float pR = Texture_pressure.SampleLevel( samPointClamp, RIGHTCELL, 0 ); - float pB = Texture_pressure.SampleLevel( samPointClamp, BOTTOMCELL, 0 ); - float pT = Texture_pressure.SampleLevel( samPointClamp, TOPCELL, 0 ); - float pD = Texture_pressure.SampleLevel( samPointClamp, DOWNCELL, 0 ); - float pU = Texture_pressure.SampleLevel( samPointClamp, UPCELL, 0 ); - - float4 velocity; - float3 obstV = float3(0,0,0); - float3 vMask = float3(1,1,1); - float3 v; - - float3 vLeft = GetObstVelocity(LEFTCELL); - float3 vRight = GetObstVelocity(RIGHTCELL); - float3 vBottom = GetObstVelocity(BOTTOMCELL); - float3 vTop = GetObstVelocity(TOPCELL); - float3 vDown = GetObstVelocity(DOWNCELL); - float3 vUp = GetObstVelocity(UPCELL); - - if( IsBoundaryCell(LEFTCELL) ) { pL = pCenter; obstV.x = vLeft.x; vMask.x = 0; } - if( IsBoundaryCell(RIGHTCELL) ) { pR = pCenter; obstV.x = vRight.x; vMask.x = 0; } - if( IsBoundaryCell(BOTTOMCELL) ){ pB = pCenter; obstV.y = vBottom.y; vMask.y = 0; } - if( IsBoundaryCell(TOPCELL) ) { pT = pCenter; obstV.y = vTop.y; vMask.y = 0; } - if( IsBoundaryCell(DOWNCELL) ) { pD = pCenter; obstV.z = vDown.z; vMask.z = 0; } - if( IsBoundaryCell(UPCELL) ) { pU = pCenter; obstV.z = vUp.z; vMask.z = 0; } - - v = ( Texture_velocity.SampleLevel( samPointClamp, input.texcoords, 0 ).xyz - - (1.0f/rho)*(0.5*float3( pR - pL, pT - pB, pU - pD )) ); - - velocity.xyz = (vMask * v) + obstV; - - return velocity; -} - -// liquid simulation shaders -float4 PS_SIGNED_DISTANCE_TO_LIQUIDHEIGHT( GS_OUTPUT_FLUIDSIM input) : SV_Target -{ - float distance = input.cell0.z - liquidHeight; - return distance; -} - -float4 PS_INJECT_LIQUID( GS_OUTPUT_FLUIDSIM input) : SV_Target -{ - // This is a hack to prevent the liquid from "falling through the floor" when using large g_timesteps. - // The idea is to blend between the initial and "known" balanced state and the current level set state - - float d = input.cell0.z - liquidHeight; - - //float collar = 1.0; //distance *above* the liquid to reinitialize - //if( d > collar ) - // return 0; - - float amount = 0.001; - return amount * d; -} - -float4 PS_REDISTANCING( GS_OUTPUT_FLUIDSIM input ) : SV_Target -{ - const float dt = 0.1f; - - float phiC = Texture_phi_next.SampleLevel( samPointClamp, input.texcoords, 0).r; - - // avoid redistancing near boundaries, where gradients are ill-defined - if( (input.cell0.x < 3) || (input.cell0.x > (g_textureWidth-4)) || - (input.cell0.y < 3) || (input.cell0.y > (g_textureHeight-4)) || - (input.cell0.z < 3) || (input.cell0.z > (g_textureDepth-4)) ) - return phiC; - - bool isBoundary; - bool hasHighSlope; - float3 gradPhi = Gradient(Texture_phi_next, input, isBoundary, 1.01f, hasHighSlope); - float normGradPhi = length(gradPhi); - - if( isBoundary || !hasHighSlope || ( normGradPhi < 0.01f ) ) - return phiC; - - - //float signPhi = phiC > 0 ? 1 : -1; - float phiC0 = Texture_phi.SampleLevel( samPointClamp, input.texcoords, 0).r; - float signPhi = phiC0 / sqrt( (phiC0*phiC0) + 1); - //float signPhi = phiC / sqrt( (phiC*phiC) + (normGradPhi*normGradPhi)); - - float3 backwardsPos = input.cell0 - (gradPhi/normGradPhi) * signPhi * dt; - float3 npos = float3(backwardsPos.x/g_textureWidth, backwardsPos.y/g_textureHeight, (backwardsPos.z+0.5f)/g_textureDepth); - - return Texture_phi_next.SampleLevel( samLinear, npos, 0).r + (signPhi * dt); -} - -float4 PS_EXTRAPOLATE_VELOCITY( GS_OUTPUT_FLUIDSIM input ) : SV_Target -{ - const float dt = 0.25f; - // do not modify the velocity in the current location - if( !IsOutsideSimulationDomain(input.texcoords.xyz ) ) - return Texture_velocity.SampleLevel( samPointClamp, input.texcoords, 0); - - // we still keep fluid velocity as 0 in cells occupied by obstacles - if( IsNonEmptyCell(input.texcoords.xyz) ) - return 0; - - - float3 normalizedGradLS = normalize( Gradient(Texture_levelset, input) ); - float3 backwardsPos = input.cell0 - normalizedGradLS * dt; - float3 npos = float3(backwardsPos.x/g_textureWidth, backwardsPos.y/g_textureHeight, (backwardsPos.z+0.5f)/g_textureDepth); - - float4 ret = Texture_velocity.SampleLevel( samLinear, npos, 0); - - return ret; -} - -//fluid sources and external forces -float4 PS_LIQUID_STREAM( GS_OUTPUT_FLUIDSIM input, uniform bool outputColor ) : SV_Target -{ - if( IsNonEmptyCell(input.texcoords.xyz) ) - return 0; - - float dist = length(input.cell0 - g_center); - - float4 result; - - if( outputColor ) - result.rgb = g_color; - else - result.rgb = (dist - g_radius); - - if(dist < g_radius) - result.a = 1; - else - result.a = 0; - - return result; -} - -float4 PS_APPLY_GRAVITY( GS_OUTPUT_FLUIDSIM input) : SV_Target -{ - if( IsOutsideSimulationDomain(input.texcoords.xyz ) ) - return 0; - - if( IsNonEmptyCell(input.texcoords.xyz) ) - return 0; - - return float4(g_gravity, 1.0); -} - -float4 PS_GAUSSIAN( GS_OUTPUT_FLUIDSIM input ) : SV_Target -{ - if( IsNonEmptyCell(input.texcoords.xyz) ) - return 0; - - float dist = length( input.cell0 - g_center ) * g_radius; - float4 result; - result.rgb = g_color; // + sin(g_color.rgb*10.0+cell*5.0)*0.2; - result.a = exp( -dist*dist ); - - return result; -} - -float4 PS_COPY_TEXURE( GS_OUTPUT_FLUIDSIM input ) : SV_Target -{ - if( IsNonEmptyCell(input.texcoords.xyz) ) - return 0; - - float4 texCol = Texture_inDensity.SampleLevel( samLinear, input.texcoords.xy,0); - return texCol*g_color; -} - -float4 PS_ADD_DERIVATIVE_VEL( GS_OUTPUT_FLUIDSIM input ) : SV_Target -{ - if( IsNonEmptyCell(input.texcoords.xyz) ) - return 0; - - float pCenter = Texture_inDensity.SampleLevel( samLinear, input.texcoords.xy, 0 ); - float pL = Texture_inDensity.SampleLevel( samLinear, (LEFTCELL).xy, 0 ); - float pR = Texture_inDensity.SampleLevel( samLinear, (RIGHTCELL).xy, 0 ); - float pB = Texture_inDensity.SampleLevel( samLinear, (BOTTOMCELL).xy, 0 ); - float pT = Texture_inDensity.SampleLevel( samLinear, (TOPCELL).xy, 0 ); - - float4 vel = float4((pL-pR)*pCenter,(pB-pT)*pCenter,pCenter,1); - - return vel*g_color; -} - -// obstacle texture initialization -bool PointIsInsideBox(float3 p, float3 LBUcorner, float3 RTDcorner) -{ - return ((p.x > LBUcorner.x) && (p.x < RTDcorner.x) - && (p.y > LBUcorner.y) && (p.y < RTDcorner.y) - && (p.z > LBUcorner.z) && (p.z < RTDcorner.z)); -} - -struct PSDrawBoxOut -{ - float4 obstacle : SV_TARGET0; - float4 velocity : SV_TARGET1; -}; - -PSDrawBoxOut PS_DYNAMIC_OBSTACLE_BOX( GS_OUTPUT_FLUIDSIM input ) -{ - PSDrawBoxOut voxel; - float3 innerobstBoxLBDcorner = g_obstBoxLBDcorner + 1; - float3 innerobstBoxRTUcorner = g_obstBoxRTUcorner - 1; - // cells completely inside box = 0.5 - if(PointIsInsideBox(input.cell0, innerobstBoxLBDcorner, innerobstBoxRTUcorner)) - { - voxel.obstacle = OBSTACLE_INTERIOR; - voxel.velocity = 0; - return voxel; - } - - // cells in box boundary = 1.0 - if(PointIsInsideBox(input.cell0, g_obstBoxLBDcorner, g_obstBoxRTUcorner)) - { - voxel.obstacle = OBSTACLE_BOUNDARY; - voxel.velocity = float4(g_obstBoxVelocity.xyz,1); - return voxel; - } - - voxel.obstacle = OBSTACLE_EXTERIOR; - voxel.velocity = 0; - return voxel; -} - -PSDrawBoxOut PS_STATIC_OBSTACLE( GS_OUTPUT_FLUIDSIM input ) : SV_Target -{ - PSDrawBoxOut voxel; - voxel.obstacle = OBSTACLE_BOUNDARY; - voxel.velocity = 0; - return voxel; -} - -float4 PS_DRAW_TEXTURE( VS_OUTPUT_FLUIDSIM input ) : SV_Target -{ - //("Phi as density"), - if( g_drawTextureNumber == 1) - return float4(abs(Texture_phi.SampleLevel(samLinear,input.texcoords,0).r), 0.0f, 0.0f, 1.0f); - //("Phi as level set"), - else if( g_drawTextureNumber == 2) - { - float levelSet = Texture_phi.SampleLevel(samLinear,input.texcoords,0).r/(g_textureDepth); - float g_color = lerp(1.0f, 0.0f, abs(levelSet)); - if( levelSet < 0 ) - return float4(0.0f, g_color, 0.0f, 1.0f); - return float4(g_color, 0.0f, 0.0f, 1.0f); - } - //("Gradient of phi"), - else if( g_drawTextureNumber == 3) - return float4(Gradient(Texture_phi, input), 1.0f); - //("Velocity Field"), - else if( g_drawTextureNumber == 4) - return float4(abs(Texture_velocity.SampleLevel(samLinear,input.texcoords,0).xyz),1.0f); - //("Pressure Field"), - else if ( g_drawTextureNumber == 5) - return float4(abs(Texture_pressure.SampleLevel(samLinear,input.texcoords,0).xyz), 1.0f); - //("Voxelized Obstacles"), - else - { - float obstColor = (Texture_obstacles.SampleLevel(samLinear,input.texcoords,0).r - OBSTACLE_INTERIOR) / (OBSTACLE_EXTERIOR - OBSTACLE_INTERIOR); - return float4(abs(Texture_obstvelocity.SampleLevel(samLinear,input.texcoords,0).xy), obstColor, 1.0f); - } -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL/HairSimulateCS.hlsl b/Samples/Media/materials/programs/HLSL/HairSimulateCS.hlsl deleted file mode 100644 index 4847391f6b5..00000000000 --- a/Samples/Media/materials/programs/HLSL/HairSimulateCS.hlsl +++ /dev/null @@ -1,677 +0,0 @@ -/* ----------------------------------------------------------- -Hair Tessellation sample from NVIDIA's DirectX 11 SDK: -http://developer.nvidia.com/nvidia-graphics-sdk-11-direct3d ----------------------------------------------------------- -*/ - -#define MAX_IMPLICITS 10 -//constants that change frame to frame - -//ATTENTION TO THESE. SET THEM CORRECTLY. ADD COMPUTE SHADER TO THE MATERIAL> -cbuffer cbPerFrame : register( b0 ) -{ - row_major float4x4 additionalTransformation; //use this transform to transform all the vertices. We are using this to transform hair vertices back to the vicinity of the head after simulation is turned off and on again - row_major float4x4 RootTransformation; - row_major float4x4 currentHairTransformation; - row_major float4x4 WorldToGrid; - - int g_bApplyHorizontalForce; //bool - int g_bAddGravity; //bool - int g_numConstraintIterations; - int g_numCFIterations; - - float g_angularStiffness; - float g_gravityStrength; - float g_TimeStep; - int g_integrate; - - int g_bApplyAdditionalTransform; - int g_restoreToDefault; - float g_blendAxis; //for coordinate frame correction - int g_addAngularForces; -} - -//constants that are set only once -cbuffer cbOnceOnly : register( b1 ) -{ - int g_NumSphereImplicits; - int g_NumCylinderImplicits; - int g_NumSphereNoMoveImplicits; - int padding4; - - row_major float4x4 CollisionSphereTransformations[MAX_IMPLICITS]; - row_major float4x4 CollisionSphereInverseTransformations[MAX_IMPLICITS]; - row_major float4x4 CollisionCylinderTransformations[MAX_IMPLICITS]; - row_major float4x4 CollisionCylinderInverseTransformations[MAX_IMPLICITS]; - row_major float4x4 SphereNoMoveImplicitInverseTransform[MAX_IMPLICITS]; -} - -RWStructuredBuffer particlePositions : register(u0); //particle positions, for the solver -RWStructuredBuffer previousParticlePositions : register(u1); //the partice positions from the last frame -RWStructuredBuffer g_coordinateFrames : register(u2); //the coordinate frames for the particles. we have to update these as the hair moves and also use them for simulation - -Buffer g_SimulationStrandOffsets : register(t0); //note - maybe this should have been a short along with the corresponding buffer and SRV -Buffer particleDistanceConstraintLengths : register(t1); -Buffer g_stiffness : register(t2); //TODO! these are angular forces, and might be something more..have to get rid of these by the end since will be computing everything in one shader -Buffer g_OriginalMasterStrand : register(t3); -Texture3D g_FluidVelocityTexture : register(t4); -Buffer particleAngularLengthAndStiffness : register(t5); -Buffer g_OriginalVectors : register(t6); - -//data structures: -struct ConstraintsAngularHairVertex -{ - float4 Position : POSITION; - float Length : LENGTH; - float Stiffness : STIFFNESS; - uint vid : ID; -}; - -struct coordinateFrame4 -{ - float4 xAxis : X_AXIS; - float4 yAxis : Y_AXIS; - float4 zAxis : Z_AXIS; -}; - -//samplers -SamplerState samLinearClamp : register(s0) -{ - Filter = MIN_MAG_MIP_LINEAR; - AddressU = Clamp; - AddressV = Clamp; - AddressW = Clamp; -}; - -//----------------------------------------------------------------------------------------- -#define SMALL_NUM 0.0001 -void rotateVector(float3 rotationAxis, float theta, float3 prevVec, inout float3 newVec, float c, float s) -{ - float3 axisDifference = rotationAxis - prevVec; - if( length(axisDifference)=0) - return true; - return false; -} - -float2 Responsiveness(float4 particle0, float4 particle1) -{ - if (IsFree(particle0)) - { - if (IsFree(particle1)) - return float2(0.5, 0.5); - else - return float2(1, 0); - } - else - { - if (IsFree(particle1)) - return float2(0, 1); - else - return float2(0, 0); - } -} - -void DistanceConstraint(inout float4 particle0, inout float4 particle1, float targetDistance, float stiffness = 1.0) -{ - float3 delta = particle1.xyz - particle0.xyz; - float distance = max(length(delta), 1e-7); - float stretching = 1 - targetDistance / distance; - delta = stretching * delta; - float2 responsiveness = Responsiveness(particle0, particle1); - particle0.xyz += responsiveness[0] * delta * stiffness; - particle1.xyz -= responsiveness[1] * delta * stiffness; -} - -void SatisfyAngularSpringConstraints(inout ConstraintsAngularHairVertex CAvertex0, inout ConstraintsAngularHairVertex CAvertex1, inout ConstraintsAngularHairVertex CAvertex2, inout ConstraintsAngularHairVertex CAvertex3) -{ - if( CAvertex2.vid != CAvertex1.vid ) - { - float stiffness = CAvertex0.Stiffness * g_angularStiffness; - if( stiffness>0 ) - DistanceConstraint(CAvertex0.Position,CAvertex2.Position, CAvertex0.Length, stiffness ); - } - if( CAvertex1.vid != CAvertex0.vid ) - { - if( CAvertex3.vid != CAvertex2.vid ) - { - float stiffness = CAvertex1.Stiffness * g_angularStiffness; - if( stiffness>0 ) - DistanceConstraint(CAvertex1.Position,CAvertex3.Position, CAvertex1.Length, stiffness ); - } - } -} - -void SatisfyAngularSpringConstraints(inout ConstraintsAngularHairVertex CAvertex0, inout ConstraintsAngularHairVertex CAvertex1) -{ - if( CAvertex0.vid != CAvertex1.vid ) - { - float stiffness = CAvertex0.Stiffness * g_angularStiffness; - if( stiffness>0 ) - DistanceConstraint(CAvertex0.Position,CAvertex1.Position, CAvertex0.Length, stiffness ); - } -} - -float3 CylinderConstraint(float4 position, int i) -{ - if(!IsFree(position)) - return 0; - - //inverse transform the position - float3 transformedPosition = (mul(float4(position.xyz,1),CollisionCylinderInverseTransformations[i])).xyz; - - float3 force = float3(0,0,0); - float3 forceX = float3(0,0,0); - float3 forceY = float3(0,0,0); - - if( abs(transformedPosition.y) < 0.5 ) - { - float hmy = 0.5 - abs(transformedPosition.y); - float cpy = transformedPosition.y; - - transformedPosition.y = 0; - float l = length(transformedPosition); - if( l < 1) - { - if(cpy<0) - forceX = float3(0,-hmy,0); - else - forceX = float3(0,hmy,0); - - forceY = normalize(transformedPosition)*(1-l); - - row_major float4x4 transform = CollisionCylinderTransformations[i]; - //remove the translation - transform._41 = 0; - transform._42 = 0; - transform._43 = 0; - transform._44 = 1; - - forceX = (mul(float4(forceX,1),transform)).xyz; - forceY = (mul(float4(forceY,1),transform)).xyz; - - if(length(forceX) < length(forceY)) - force = forceX; - else - force = forceY; - } - } - - return force; -} - -float3 SphereConstraint(float4 position,int i) -{ - if(!IsFree(position)) - return 0; - - //inverse transform the position - float3 transformedPosition = (mul(float4(position.xyz,1),CollisionSphereInverseTransformations[i])).xyz; - - //find the force - float3 force= float3(0,0,0); - float len = length(transformedPosition); - - if(len < 1) - { - force = (1-len)*(transformedPosition/len); - - row_major float4x4 transform = CollisionSphereTransformations[i]; - //remove the translation - transform._41 = 0; - transform._42 = 0; - transform._43 = 0; - transform._44 = 1; - force = (mul(float4(force,1),transform)).xyz; - } - - return force; -} - -void addObstacleCollisionResponse(inout float4 position) -{ - int i; - - //spheres - for(i=0;i 0 ) - force *= stiffnessIncrease*6; - } - if( length(velocity)>0.5) //if velocity is very high decrease the stiffness - force *= 0.5; - - - float gravityStrength = (1-stiffness)*(1.2-0.07)+0.07; - - gravityStrength *= g_gravityStrength; - - //add wind force - if( g_bApplyHorizontalForce) - { - float4 posInGrid = mul(float4(outputPos.xyz, 1), WorldToGrid ); - posInGrid.x += 0.5; - posInGrid.y += 0.5; - posInGrid.z += 0.5; - float3 texcoords = float3(posInGrid.x, 1.0-posInGrid.y, posInGrid.z); - float3 g_windForce = (g_FluidVelocityTexture.SampleLevel(samLinearClamp,texcoords,0).xyz); - g_windForce *= (1-stiffness)*(5) + 5; - force.xyz += g_windForce; - } - - //Gravity - if( g_bAddGravity) - force.xyz += float3(0, -gravityStrength, 0); - - - //no move constraint-- keep the hair off the face - //sphere no move constraint - //only do this to hair that are not very stiff already - - { - for(int i=0;i1.0) - vectorToOriginal /= lengthToOriginal; - - force.xyz += vectorToOriginal*0.525; - } - } - - //verlet integration - //float clampAmount = 1.0; - //velocity.xyz = clamp(velocity.xyz, float3(-clampAmount,-clampAmount,-clampAmount), float3(clampAmount,clampAmount,clampAmount) ); - outputPos.xyz = position.xyz - + velocity.xyz - + force.xyz*g_TimeStep*g_TimeStep; - - //this makes stiff hair even stiffer, and makes it go towards its base transformed pose. - //However, we only apply this force when the hair and the base transformed hair are "relatively" close (and we apply this more to hair we have already designated as stiff). - //Here we have huristically decided this value to be 1.6 units - float staticky = force.w*0.0475; - if(length(outputPos.xyz - transformedPos.xyz) < 1.6 ) - outputPos.xyz = (1-staticky)*outputPos.xyz + staticky*transformedPos.xyz; - - return outputPos; - -} - -float3 TransformOldVectorToNewVector( float3 vM1X, float3 vM1Y, float3 vM1Z, float3 oldVector) -{ - if(length(vM1X)<0.01) return oldVector; - - float3 worldX = float3(1,0,0); - float3 worldY = float3(0,1,0); - float3 worldZ = float3(0,0,1); - - row_major float4x4 vM1ToWorld = float4x4 - ( - dot(worldX,vM1X), dot(worldY,vM1X), dot(worldZ,vM1X), 0, - dot(worldX,vM1Y), dot(worldY,vM1Y), dot(worldZ,vM1Y), 0, - dot(worldX,vM1Z), dot(worldY,vM1Z), dot(worldZ,vM1Z), 0, - 0, 0, 0, 1 - - ); - - //transform from old to new coordinate frame - float3 retVector = mul(float4(oldVector,1),vM1ToWorld).xyz; - return retVector; -} - -void AddAngularForces(inout float4 force0, inout float4 force1, int threadReadIndex, float4 positionV1, float4 positionV2,float3 vM1X, float3 vM1Y, float3 vM1Z) -{ - float3 bPOriginal = g_OriginalVectors.Load(threadReadIndex); - - if(length(bPOriginal)==0) //this should never happen - { - return; - } - - float3 bP; - - //transform the original vector from the local coordinate frame of vertex v-1 to the world coordinate frame - bP = TransformOldVectorToNewVector(vM1X,vM1Y,vM1Z,bPOriginal); - - float k = force0.w*9 + 1; //minimum stiffness is 1 and maximum is 10; empirically adjusted - - float3 b = positionV2.xyz - positionV1.xyz; - - float lengthbP = length(bP); - float lengthB = length(b); - float dotB_Bp = dot(bP,b); - float constant = k/(2*lengthbP*lengthB); - float3 bDoubleNorm = b/(lengthB*lengthB); - - force0.xyz += constant * ( -bP + dotB_Bp*bDoubleNorm ); - force1.xyz += constant * ( bP - dotB_Bp*bDoubleNorm ); -} - -//since the maximum length is 40 the size of the CTA is fine at 64 -//the total amount of thread local storage is limited to 32KB -#define BLOCK_SIZE 64 -groupshared float4 sharedPos[BLOCK_SIZE]; -groupshared float sharedLength[BLOCK_SIZE]; -groupshared coordinateFrame4 sharedCFs[BLOCK_SIZE]; -groupshared float sharedAngularStiffness[BLOCK_SIZE]; -groupshared float sharedAngularDistance[BLOCK_SIZE]; -groupshared float4 sharedForce[BLOCK_SIZE]; - -//we need to know what the start index is for each strand -//we need to know what the total number of vertices is for each strand -//we need to have thread local storage assigned and use it -//need to know how to sync threads - -[numthreads(64,1,1)] -void UpdateParticlesSimulate(uint threadId : SV_GroupIndex, - uint3 groupId : SV_GroupID, - uint3 globalThreadId : SV_DispatchThreadID) -{ - - int readStart = 0; //the offset into the particle attributes buffer for this particular patch - if(groupId.x > 0) readStart = g_SimulationStrandOffsets.Load( groupId - 1 ); - int n = g_SimulationStrandOffsets.Load( groupId ) - readStart; - - float4 originalPosition; - - int threadReadIndex = readStart + threadId; - - //read the attributes into shared memory - if(threadId < n) - { - originalPosition = sharedPos[threadId] = particlePositions[threadReadIndex]; - sharedLength[threadId] = particleDistanceConstraintLengths[threadReadIndex]; - float2 landS = particleAngularLengthAndStiffness[threadReadIndex]; - sharedAngularStiffness[threadId] = landS.y; - sharedAngularDistance[threadId] = landS.x; - sharedForce[threadId] = float4(0,0,0,0); - sharedForce[threadId].w = g_stiffness[threadReadIndex]; - } - - //synchronize after reading the data into shared memory - GroupMemoryBarrierWithGroupSync(); - - //read and update the coordinate frames - //note that we need these coordinate frames for calculating angular forces in addition to needing to update these for rendering - if(threadId < n) - { - sharedCFs[threadId].xAxis = g_coordinateFrames[threadReadIndex*3]; - sharedCFs[threadId].yAxis = g_coordinateFrames[threadReadIndex*3+1]; - sharedCFs[threadId].zAxis = g_coordinateFrames[threadReadIndex*3+2]; - - //update the coordinate frames - if(threadId0) - AddAngularForces(sharedForce[id1], sharedForce[id2], threadReadIndex, sharedPos[id1], sharedPos[id2], sharedCFs[id1-1].xAxis, sharedCFs[id1-1].yAxis, sharedCFs[id1-1].zAxis); - - GroupMemoryBarrierWithGroupSync(); - - //angular forces for the second subset - id1 = threadId*2+1; - id2 = threadId*2+2; - if(g_addAngularForces) - if(threadId0 ) - DistanceConstraint(sharedPos[id],sharedPos[id+2], sharedAngularDistance[id], stiffness ); - } - GroupMemoryBarrierWithGroupSync(); - - //apply the angular constraints to the second subset - if(threadId0 ) - DistanceConstraint(sharedPos[id],sharedPos[id+2], sharedAngularDistance[id], stiffness ); - } - GroupMemoryBarrierWithGroupSync(); - - //apply the collision constraints - addObstacleCollisionResponse(sharedPos[threadId]); - GroupMemoryBarrierWithGroupSync(); - } - - //and finally write back the data to the global buffer - if(threadId < n) - { - particlePositions[threadReadIndex] = sharedPos[threadId]; - - g_coordinateFrames[threadReadIndex*3] = sharedCFs[threadId].xAxis; - g_coordinateFrames[threadReadIndex*3+1] = sharedCFs[threadId].yAxis; - g_coordinateFrames[threadReadIndex*3+2] = sharedCFs[threadId].zAxis; - } -} diff --git a/Samples/Media/materials/programs/HLSL/HeatVision.hlsl b/Samples/Media/materials/programs/HLSL/HeatVision.hlsl deleted file mode 100644 index 0e4b9d0d251..00000000000 --- a/Samples/Media/materials/programs/HLSL/HeatVision.hlsl +++ /dev/null @@ -1,222 +0,0 @@ -cbuffer MatrixBuffer -{ - matrix worldViewProj; -}; - -struct v2p -{ - float4 position : SV_POSITION; - float2 texCoord : TEXCOORD0; -}; - -////////////////////////////////////////////// -// CASTER PASS // -// HEAT // -////////////////////////////////////////////// - -v2p HeatCaster_vp( - // in - float4 vPos: POSITION, - float4 vNormal: NORMAL, - uniform float3 eyePosition // object space - ) -{ - v2p output; - float4 eyeDir = float4(eyePosition - vPos.xyz, 0); - eyeDir = normalize(eyeDir); - output.position = mul( worldViewProj, vPos ); - output.texCoord = clamp( dot( vNormal, eyeDir ), 0, 1 ); - return output; -} - -float4 HeatCaster_fp( - v2p input - ) : SV_Target -{ - return float4(input.texCoord.x,input.texCoord.x,input.texCoord.x,input.texCoord.x); -} - -////////////////////////////////////////////// -// CASTER PASS // -// COLD // -////////////////////////////////////////////// - -v2p ColdCaster_vp( - // in - float4 vPos: POSITION, - float4 vNormal: NORMAL, - uniform float3 eyePosition // object space - ) -{ - v2p output; - float4 eyeDir = float4(eyePosition - vPos.xyz, 0); - eyeDir = normalize(eyeDir); - output.position = mul( worldViewProj, vPos ); - output.texCoord = clamp( dot( vNormal, eyeDir ), 0, 1 ); - return output; -} - -float4 ColdCaster_fp( - // input from vp - v2p input - ) : SV_Target -{ - return float4(input.texCoord.x / 2,input.texCoord.x / 2,input.texCoord.x / 2,input.texCoord.x / 2); -} - - -////////////////////////////////////////////// -// PASS 1 - Light to heat conversion // -////////////////////////////////////////////// - -v2p LightToHeat_vp( - // in - float4 inPos: POSITION, - uniform float flipping - ) -{ - v2p output; - output.position = float4(inPos.x, flipping * inPos.y, 0.0f, 1.0f); - inPos.xy = sign(inPos.xy); - output.texCoord = (float2(inPos.x, -inPos.y) + 1.0f)/2.0f; - return output; -} - -SamplerState g_samLinear -{ - Filter = MIN_MAG_LINEAR_MIP_POINT; - AddressU = Wrap; - AddressV = Wrap; -}; - -SamplerState g_samVolume -{ - Filter = MIN_MAG_LINEAR_MIP_POINT; - AddressU = Wrap; - AddressV = Wrap; - AddressW = Wrap; -}; - -float4 LightToHeat_fp( - // input from vp - v2p inp, - - // params - uniform float4 random_fractions, - uniform float4 heatBiasScale, - uniform float4 depth_modulator, - uniform Texture2D Input, // output of HeatVisionCaster_fp (NdotV) - uniform Texture2D NoiseMap, - uniform Texture2D HeatLookup - ) : SV_Target -{ - float depth, heat, interference; - - // Output constant color: - depth = Input.Sample(g_samLinear, inp.texCoord ).r; - depth *= (depth * depth_modulator.x); - - heat = (depth * heatBiasScale.y); - -// if (depth > 0) - { - interference = -0.5 + NoiseMap.Sample(g_samVolume, inp.texCoord.xy + float2( random_fractions.x, random_fractions.y ) ).r; - interference *= interference; - interference *= 1 - heat; - heat += interference;//+ heatBiasScale.x; - } - -/* - heatBias isn't used for now - if (heat > 0) - heat += heatBiasScale.x; -*/ - - // Clamp UVs - heat = max( 0.005, min( 0.995, heat ) ); - float4 outColor = HeatLookup.Sample(g_samLinear, float2( heat, 0.f ) ); - return outColor; -} - - -////////////////////////////////////////////// -// PASS 2 - add simple blur (final pass) // -////////////////////////////////////////////// - -v2p Blur_vp( - // in - float4 inPos: POSITION, - uniform float flipping - ) -{ - v2p output; - output.position = float4(inPos.x, flipping * inPos.y, 0.0f, 1.0f); - inPos.xy = sign(inPos.xy); - output.texCoord = (float2(inPos.x, -inPos.y) + 1.0f)/2.0f; - return output; -} - -// ps_2_0 -float4 Blur_fp( - // input from vp - v2p inp, - // parameters - uniform Texture2D Input, - uniform float4 blurAmount - ) : SV_Target -{ - int i; - float4 tmpOutColor; - float diffuseGlowFactor; - const float2 offsets[4] = - { -/* - // hazy blur - -1.8, -1.8, - -1.8, 1.8, - 1.8, -1.8, - 1.8, 1.8 -*/ -/* - // less-hazy blur - -1.0, 2.0, - -1.0, -1.0, - 1.0, -1.0, - 1.0, 1.0 -*/ -/* - -0.326212, -0.405805, - -0.840144, -0.073580, - -0.695914, 0.457137, - -0.203345, 0.620716 -*/ - - -0.3, 0.4, - -0.3, -0.4, - 0.3, -0.4, - 0.3, 0.4 - - }; - - tmpOutColor = Input.Sample(g_samLinear, inp.texCoord ); // UV coords are in image space - - // calculate glow amount - diffuseGlowFactor = 0.0113f * (2.0 - max( tmpOutColor.r, tmpOutColor.g )); - - // basic blur filter - for (i = 0; i < 4; i++) { - tmpOutColor += Input.Sample(g_samLinear, inp.texCoord.xy + blurAmount.x * diffuseGlowFactor * offsets[i] ); - } - - tmpOutColor *= 0.25; - - // TIPS (old-skool strikes again!) - // Pay attention here! If you use the "out float4 outColor" directly - // in your steps while creating the output color (like you remove - // the "tmpOutColor" var and just use the "outColor" directly) - // your pixel-color output IS CHANGING EACH TIME YOU DO AN ASSIGNMENT TOO! - // A temporary variable, instead, acts like a per-pixel double buffer, and - // best of all, lead to better performance. - float4 outColor = tmpOutColor; - return outColor; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL/Island.hlsl b/Samples/Media/materials/programs/HLSL/Island.hlsl deleted file mode 100644 index 92a35e1fdf2..00000000000 --- a/Samples/Media/materials/programs/HLSL/Island.hlsl +++ /dev/null @@ -1,733 +0,0 @@ -/* ----------------------------------------------------------- -Island Tessellation sample from NVIDIA's DirectX 11 SDK: -http://developer.nvidia.com/nvidia-graphics-sdk-11-direct3d ----------------------------------------------------------- -*/ - -#include "IslandCommon.hlsl" - -Texture2D g_HeightfieldTexture; -Texture2D g_LayerdefTexture; -Texture2D g_RockBumpTexture; -Texture2D g_RockMicroBumpTexture; -Texture2D g_RockDiffuseTexture; -Texture2D g_SandBumpTexture; -Texture2D g_SandMicroBumpTexture; -Texture2D g_SandDiffuseTexture; -Texture2D g_GrassDiffuseTexture; -Texture2D g_SlopeDiffuseTexture; -Texture2D g_WaterBumpTexture; -Texture2D g_DepthMapTexture; - -// rendertarget textures -Texture2D g_SkyTexture; -Texture2D g_ReflectionTexture; -Texture2D g_RefractionTexture; -Texture2D g_RefractionDepthTextureResolved; -Texture2D g_WaterNormalMapTexture; -Texture2D g_DepthTexture; -Texture2D g_MainTexture; -Texture2DMS g_RefractionDepthTextureMS1; -Texture2DMS g_RefractionDepthTextureMS2; -Texture2DMS g_RefractionDepthTextureMS4; - -// Shader Inputs/Outputs -struct VSIn_Diffuse -{ - float3 position : POSITION; - float2 texcoord : TEXCOORD; - float3 normal : NORMAL; -}; - -struct PSIn_Diffuse -{ - float4 position : SV_Position; - centroid float2 texcoord : TEXCOORD0; - centroid float3 normal : NORMAL; - centroid float3 positionWS : TEXCOORD1; - centroid float4 layerdef : TEXCOORD2; - centroid float4 depthmap_scaler: TEXCOORD3; -}; - -struct PSIn_Quad -{ - float4 position : SV_Position; - float2 texcoord : TEXCOORD0; -}; - -struct VSIn_Default -{ - float4 position : POSITION; - float2 texcoord : TEXCOORD; -}; - - -struct DUMMY -{ - float Dummmy : DUMMY; -}; - -struct HSIn_Heightfield -{ - float2 origin : ORIGIN; - float2 size : SIZE; -}; - - -struct PatchData -{ - float Edges[4] : SV_TessFactor; - float Inside[2] : SV_InsideTessFactor; - - float2 origin : ORIGIN; - float2 size : SIZE; -}; - -//-------------------------------------------------------------------------------------- -// Constant Buffers -//-------------------------------------------------------------------------------------- -shared cbuffer cb0 -{ - // rendering control variables - float g_RenderCaustics; - float g_UseDynamicLOD; - float g_FrustumCullInHS; - float g_DynamicTessFactor; - float g_StaticTessFactor; - float g_TerrainBeingRendered; - float g_HalfSpaceCullSign; - float g_HalfSpaceCullPosition; - float g_SkipCausticsCalculation; - int g_MSSamples; - - // view/time dependent variables - matrix g_ModelViewMatrix; - matrix g_ModelViewProjectionMatrix; - //matrix g_ModelViewProjectionMatrixInv; - matrix g_LightModelViewProjectionMatrix; - //matrix g_LightModelViewProjectionMatrixInv; - float3 g_CameraPosition; - float3 g_CameraDirection; - - - float3 g_LightPosition; - float2 g_WaterBumpTexcoordShift; - float2 g_ScreenSizeInv; - float g_MainBufferSizeMultiplier; - float g_ZNear; - float g_ZFar; - - // constants defining visual appearance - float2 g_DiffuseTexcoordScale={130.0,130.0}; - float2 g_RockBumpTexcoordScale={10.0,10.0}; - float g_RockBumpHeightScale=3.0; - float2 g_SandBumpTexcoordScale={3.5,3.5}; - float g_SandBumpHeightScale=0.5; - float g_TerrainSpecularIntensity=0.5; - float2 g_WaterMicroBumpTexcoordScale={225,225}; - float2 g_WaterBumpTexcoordScale={7,7}; - float g_WaterHeightBumpScale=1.0f; - float3 g_WaterDeepColor={0.1,0.4,0.7}; - float3 g_WaterScatterColor={0.3,0.7,0.6}; - float3 g_WaterSpecularColor={1,1,1}; - float g_WaterSpecularIntensity=350.0; - - float g_WaterSpecularPower=1000; - float2 g_WaterColorIntensity={0.1,0.2}; - float3 g_AtmosphereBrightColor={1.0,1.1,1.4}; - float3 g_AtmosphereDarkColor={0.6,0.6,0.7}; - float g_FogDensity = 1.0f/700.0f; - float2 g_HeightFieldOrigin = float2(0, 0); - float g_HeightFieldSize = 512; -}; - -// Misc functions - -// calculating tessellation factor. It is either constant or hyperbolic depending on g_UseDynamicLOD switch -float CalculateTessellationFactor(float distance) -{ - return lerp(g_StaticTessFactor,g_DynamicTessFactor*(1/(0.015*distance)),g_UseDynamicLOD); -} - -// to avoid vertex swimming while tessellation varies, one can use mipmapping for displacement maps -// it's not always the best choice, but it effificiently suppresses high frequencies at zero cost -float CalculateMIPLevelForDisplacementTextures(float distance) -{ - return log2(128/CalculateTessellationFactor(distance)); -} - -// primitive simulation of non-uniform atmospheric fog -float3 CalculateFogColor(float3 pixel_to_light_vector, float3 pixel_to_eye_vector) -{ - return lerp(g_AtmosphereDarkColor,g_AtmosphereBrightColor,0.5*dot(pixel_to_light_vector,-pixel_to_eye_vector)+0.5); -} - -// constructing the displacement amount and normal for water surface geometry -float4 CombineWaterNormal(float3 world_position) -{ - float4 water_normal=float4(0.0,4.0,0.0,0.0); - float water_miplevel; - float distance_to_camera; - float4 texvalue; - float texcoord_scale=1.0; - float height_disturbance_scale=1.0; - float normal_disturbance_scale=1.0; - float2 tc; - float2 variance={1.0,1.0}; - - // calculating MIP level for water texture fetches - distance_to_camera=length(g_CameraPosition-world_position); - water_miplevel= CalculateMIPLevelForDisplacementTextures(distance_to_camera)/2.0-2.0; - tc=(world_position.xz*g_WaterBumpTexcoordScale/g_HeightFieldSize); - - // fetching water heightmap - for(float i=0;i<5;i++) - { - texvalue=g_WaterBumpTexture.SampleLevel(SamplerLinearWrap, tc*texcoord_scale+g_WaterBumpTexcoordShift*0.03*variance,water_miplevel).rbga; - variance.x*=-1.0; - water_normal.xz+=(2*texvalue.xz-float2(1.0,1.0))*normal_disturbance_scale; - water_normal.w += (texvalue.w-0.5)*height_disturbance_scale; - texcoord_scale*=1.4; - height_disturbance_scale*=0.65; - normal_disturbance_scale*=0.65; - } - water_normal.w*=g_WaterHeightBumpScale; - return float4(normalize(water_normal.xyz),water_normal.w); -} - -// constructing water surface normal for water refraction caustics -float3 CombineSimplifiedWaterNormal(float3 world_position, float mip_level) -{ - float3 water_normal=float3(0.0,4.0,0.0); - - float water_miplevel; - float distance_to_camera; - float4 texvalue; - float texcoord_scale=1.0; - float normal_disturbance_scale=1.0; - float2 tc; - float2 variance={1.0,1.0}; - - tc=(world_position.xz*g_WaterBumpTexcoordScale/g_HeightFieldSize); - - // need more high frequensy details for caustics, so summing more "octaves" - for(float i=0;i<8;i++) - { - texvalue=g_WaterBumpTexture.SampleLevel(SamplerLinearWrap, tc*texcoord_scale+g_WaterBumpTexcoordShift*0.03*variance,mip_level/*+i*/).rbga; - variance.x*=-1.0; - water_normal.xz+=(2*texvalue.xz-float2(1,1))*normal_disturbance_scale; - texcoord_scale*=1.4; - normal_disturbance_scale*=0.85; - } - return normalize(water_normal); -} - -// calculating water refraction caustics intensity -float CalculateWaterCausticIntensity(float3 worldpos) -{ - - float distance_to_camera=length(g_CameraPosition-worldpos); - - float2 refraction_disturbance; - float3 n; - float m=0.2; - float cc=0; - float k=0.15; - float water_depth=0.5-worldpos.y; - - float3 pixel_to_light_vector=normalize(g_LightPosition-worldpos); - - worldpos.xz-=worldpos.y*pixel_to_light_vector.xz; - float3 pixel_to_water_surface_vector=pixel_to_light_vector*water_depth; - float3 refracted_pixel_to_light_vector; - - // tracing approximately refracted rays back to light - for(float i=-3; i<=3;i+=1) - for(float j=-3; j<=3;j+=1) - { - n=2.0f*g_WaterNormalMapTexture.SampleLevel(SamplerLinearWrap,(worldpos.xz-g_CameraPosition.xz-float2(200.0,200.0)+float2(i*k,j*k)*m*water_depth)/400.0,0).rgb-float3(1.0f,1.0f,1.0f); - refracted_pixel_to_light_vector=m*(pixel_to_water_surface_vector+float3(i*k,0,j*k))-0.5*float3(n.x,0,n.z); - cc+=0.05*max(0,pow(max(0,dot(normalize(refracted_pixel_to_light_vector),normalize(pixel_to_light_vector))),500.0f)); - } - return cc; -} - - -float GetRefractionDepth(float2 position) -{ - return g_RefractionDepthTextureResolved.SampleLevel(SamplerLinearClamp,position,0).r; -} - -float GetConservativeRefractionDepth(float2 position) -{ - float result = g_RefractionDepthTextureResolved.SampleLevel(SamplerPointClamp,position + 2.0*float2(g_ScreenSizeInv.x,g_ScreenSizeInv.y),0).r; - result = min(result,g_RefractionDepthTextureResolved.SampleLevel(SamplerPointClamp,position + 2.0*float2(g_ScreenSizeInv.x,-g_ScreenSizeInv.y),0).r); - result = min(result,g_RefractionDepthTextureResolved.SampleLevel(SamplerPointClamp,position + 2.0*float2(-g_ScreenSizeInv.x,g_ScreenSizeInv.y),0).r); - result = min(result,g_RefractionDepthTextureResolved.SampleLevel(SamplerPointClamp,position + 2.0*float2(-g_ScreenSizeInv.x,-g_ScreenSizeInv.y),0).r); - return result; -} - -// Heightfield shaders -HSIn_Heightfield PassThroughVS(float4 PatchParams : PATCH_PARAMETERS) -{ - HSIn_Heightfield output; - output.origin = PatchParams.xy; - output.size = PatchParams.zw; - return output; -} - -PatchData PatchConstantHS( InputPatch inputPatch ) -{ - PatchData output; - - float distance_to_camera; - float tesselation_factor; - float inside_tessellation_factor=0; - float in_frustum=0; - - output.origin = inputPatch[0].origin; - output.size = inputPatch[0].size; - - float2 texcoord0to1 = (inputPatch[0].origin + inputPatch[0].size/2.0)/g_HeightFieldSize; - texcoord0to1.y=1-texcoord0to1.y; - - // conservative frustum culling - float3 patch_center=float3(inputPatch[0].origin.x+inputPatch[0].size.x*0.5,g_TerrainBeingRendered*g_HeightfieldTexture.SampleLevel(SamplerLinearWrap, texcoord0to1,0).w,inputPatch[0].origin.y+inputPatch[0].size.y*0.5); - float3 camera_to_patch_vector = patch_center-g_CameraPosition; - float3 patch_to_camera_direction_vector = g_CameraDirection*dot(camera_to_patch_vector,g_CameraDirection)-camera_to_patch_vector; - float3 patch_center_realigned=patch_center+normalize(patch_to_camera_direction_vector)*min(2*inputPatch[0].size.x,length(patch_to_camera_direction_vector)); - float4 patch_screenspace_center = mul(float4(patch_center_realigned, 1.0), g_ModelViewProjectionMatrix); - - if(((patch_screenspace_center.x/patch_screenspace_center.w>-1.0) && (patch_screenspace_center.x/patch_screenspace_center.w<1.0) - && (patch_screenspace_center.y/patch_screenspace_center.w>-1.0) && (patch_screenspace_center.y/patch_screenspace_center.w<1.0) - && (patch_screenspace_center.w>0)) || (length(patch_center-g_CameraPosition)<2*inputPatch[0].size.x)) - { - in_frustum=1; - } - - if((in_frustum) || (g_FrustumCullInHS ==0)) - { - distance_to_camera=length(g_CameraPosition.xz-inputPatch[0].origin-float2(0,inputPatch[0].size.y*0.5)); - tesselation_factor=CalculateTessellationFactor(distance_to_camera); - output.Edges[0] = tesselation_factor; - inside_tessellation_factor+=tesselation_factor; - - - distance_to_camera=length(g_CameraPosition.xz-inputPatch[0].origin-float2(inputPatch[0].size.x*0.5,0)); - tesselation_factor=CalculateTessellationFactor(distance_to_camera); - output.Edges[1] = tesselation_factor; - inside_tessellation_factor+=tesselation_factor; - - distance_to_camera=length(g_CameraPosition.xz-inputPatch[0].origin-float2(inputPatch[0].size.x,inputPatch[0].size.y*0.5)); - tesselation_factor=CalculateTessellationFactor(distance_to_camera); - output.Edges[2] = tesselation_factor; - inside_tessellation_factor+=tesselation_factor; - - distance_to_camera=length(g_CameraPosition.xz-inputPatch[0].origin-float2(inputPatch[0].size.x*0.5,inputPatch[0].size.y)); - tesselation_factor=CalculateTessellationFactor(distance_to_camera); - output.Edges[3] = tesselation_factor; - inside_tessellation_factor+=tesselation_factor; - output.Inside[0] = output.Inside[1] = inside_tessellation_factor*0.25; - } - else - { - output.Edges[0]=-1; - output.Edges[1]=-1; - output.Edges[2]=-1; - output.Edges[3]=-1; - output.Inside[0]=-1; - output.Inside[1]=-1; - } - - return output; -} - -[domain("quad")] -[partitioning("fractional_odd")] -[outputtopology("triangle_cw")] -[outputcontrolpoints(1)] -[patchconstantfunc("PatchConstantHS")] -DUMMY PatchHS( InputPatch inputPatch ) -{ - return (DUMMY)0; -} - -[domain("quad")] -PSIn_Diffuse HeightFieldPatchDS( PatchData input, - float2 uv : SV_DomainLocation, - OutputPatch inputPatch ) -{ - PSIn_Diffuse output; - float3 vertexPosition; - float4 base_texvalue; - float2 texcoord0to1 = (input.origin + uv * input.size)/g_HeightFieldSize; - float3 base_normal; - float3 detail_normal; - float3 detail_normal_rotated; - float4 detail_texvalue; - float detail_height; - float3x3 normal_rotation_matrix; - float4 layerdef; - float distance_to_camera; - float detailmap_miplevel; - texcoord0to1.y=1-texcoord0to1.y; - - // fetching base heightmap,normal and moving vertices along y axis - base_texvalue=g_HeightfieldTexture.SampleLevel(SamplerLinearWrap, texcoord0to1,0); - base_normal=base_texvalue.xyz; - base_normal.z=-base_normal.z; - vertexPosition.xz = input.origin + uv * input.size; - vertexPosition.y = base_texvalue.w; - - // calculating MIP level for detail texture fetches - distance_to_camera=length(g_CameraPosition-vertexPosition); - detailmap_miplevel= CalculateMIPLevelForDisplacementTextures(distance_to_camera);//log2(1+distance_to_camera*3000/(g_HeightFieldSize*g_TessFactor)); - - // fetching layer definition texture - layerdef=g_LayerdefTexture.SampleLevel(SamplerLinearWrap, texcoord0to1,0); - - // default detail texture - detail_texvalue=g_SandBumpTexture.SampleLevel(SamplerLinearWrap, texcoord0to1*g_SandBumpTexcoordScale,detailmap_miplevel).rbga; - detail_normal=normalize(2*detail_texvalue.xyz-float3(1,0,1)); - detail_height=(detail_texvalue.w-0.5)*g_SandBumpHeightScale; - - // rock detail texture - detail_texvalue=g_RockBumpTexture.SampleLevel(SamplerLinearWrap, texcoord0to1*g_RockBumpTexcoordScale,detailmap_miplevel).rbga; - detail_normal=lerp(detail_normal,normalize(2*detail_texvalue.xyz-float3(1,1.4,1)),layerdef.w); - detail_height=lerp(detail_height,(detail_texvalue.w-0.5)*g_RockBumpHeightScale,layerdef.w); - - // moving vertices by detail height along base normal - vertexPosition+=base_normal*detail_height; - - //calculating base normal rotation matrix - normal_rotation_matrix[1]=base_normal; - normal_rotation_matrix[2]=normalize(cross(float3(-1.0,0.0,0.0),normal_rotation_matrix[1])); - normal_rotation_matrix[0]=normalize(cross(normal_rotation_matrix[2],normal_rotation_matrix[1])); - - //applying base rotation matrix to detail normal - detail_normal_rotated=mul(detail_normal,normal_rotation_matrix); - - //adding refraction caustics - float cc=0; - - if((g_SkipCausticsCalculation==0) && (g_RenderCaustics>0)) // doing it only for main - { - cc=CalculateWaterCausticIntensity(vertexPosition.xyz); - } - - // fading caustics out at distance - cc*=(200.0/(200.0+distance_to_camera)); - - // fading caustics out as we're getting closer to water surface - cc*=min(1,max(0,-g_WaterHeightBumpScale-vertexPosition.y)); - - - // writing output params - output.position = mul(float4(vertexPosition, 1.0), g_ModelViewProjectionMatrix); - output.texcoord = texcoord0to1*g_DiffuseTexcoordScale; - output.normal=detail_normal_rotated; - output.positionWS = vertexPosition; - output.layerdef=layerdef; - output.depthmap_scaler=float4(1.0,1.0,detail_height,cc); - - return output; -} - -float4 HeightFieldPatchPS(PSIn_Diffuse input) : SV_Target -{ - float4 color; - float3 pixel_to_light_vector = normalize(g_LightPosition-input.positionWS); - float3 pixel_to_eye_vector = normalize(g_CameraPosition-input.positionWS); - float3 microbump_normal; - - float3x3 normal_rotation_matrix; - - // culling halfspace if needed - clip(g_HalfSpaceCullSign*(input.positionWS.y-g_HalfSpaceCullPosition)); - - // fetching default microbump normal - microbump_normal = normalize(2*g_SandMicroBumpTexture.Sample(SamplerAnisotropicWrap,input.texcoord).rbg - float3 (1.0,1.0,1.0)); - microbump_normal = normalize(lerp(microbump_normal,2*g_RockMicroBumpTexture.Sample(SamplerAnisotropicWrap,input.texcoord).rbg - float3 (1.0,1.0,1.0),input.layerdef.w)); - - //calculating base normal rotation matrix - normal_rotation_matrix[1]=input.normal; - normal_rotation_matrix[2]=normalize(cross(float3(-1.0,0.0,0.0),normal_rotation_matrix[1])); - normal_rotation_matrix[0]=normalize(cross(normal_rotation_matrix[2],normal_rotation_matrix[1])); - microbump_normal=mul(microbump_normal,normal_rotation_matrix); - - // getting diffuse color - color=g_SlopeDiffuseTexture.Sample(SamplerAnisotropicWrap,input.texcoord); - color=lerp(color,g_SandDiffuseTexture.Sample(SamplerAnisotropicWrap,input.texcoord),input.layerdef.g*input.layerdef.g); - color=lerp(color,g_RockDiffuseTexture.Sample(SamplerAnisotropicWrap,input.texcoord),input.layerdef.w*input.layerdef.w); - color=lerp(color,g_GrassDiffuseTexture.Sample(SamplerAnisotropicWrap,input.texcoord),input.layerdef.b); - - // adding per-vertex lighting defined by displacement of vertex - color*=0.5+0.5*min(1.0,max(0.0,input.depthmap_scaler.b/3.0f+0.5f)); - - // calculating pixel position in light view space - float4 positionLS = mul(float4(input.positionWS,1),g_LightModelViewProjectionMatrix); - positionLS.xyz/=positionLS.w; - positionLS.x=(positionLS.x+1)*0.5; - positionLS.y=(1-positionLS.y)*0.5; - - - // fetching shadowmap and shading - float dsf=0.75f/4096.0f; - float shadow_factor=0.2*g_DepthTexture.SampleCmp(SamplerDepthAnisotropic,positionLS.xy,positionLS.z* 0.995f).r; - shadow_factor+=0.2*g_DepthTexture.SampleCmp(SamplerDepthAnisotropic,positionLS.xy+float2(dsf,dsf),positionLS.z* 0.995f).r; - shadow_factor+=0.2*g_DepthTexture.SampleCmp(SamplerDepthAnisotropic,positionLS.xy+float2(-dsf,dsf),positionLS.z* 0.995f).r; - shadow_factor+=0.2*g_DepthTexture.SampleCmp(SamplerDepthAnisotropic,positionLS.xy+float2(dsf,-dsf),positionLS.z* 0.995f).r; - shadow_factor+=0.2*g_DepthTexture.SampleCmp(SamplerDepthAnisotropic,positionLS.xy+float2(-dsf,-dsf),positionLS.z* 0.995f).r; - color.rgb*=max(0,dot(pixel_to_light_vector,microbump_normal))*shadow_factor+0.2; - - - // adding light from the sky - color.rgb+=(0.0+0.2*max(0,(dot(float3(0,1,0),microbump_normal))))*float3(0.2,0.2,0.3); - - // making all a bit brighter, simultaneously pretending the wet surface is darker than normal; - color.rgb*=0.5+0.8*max(0,min(1,input.positionWS.y*0.5+0.5)); - - - - // applying refraction caustics - color.rgb*=(1.0+max(0,0.4+0.6*dot(pixel_to_light_vector,microbump_normal))*input.depthmap_scaler.a*(0.4+0.6*shadow_factor)); - - // applying fog - color.rgb=lerp(CalculateFogColor(pixel_to_light_vector,pixel_to_eye_vector).rgb,color.rgb,min(1,exp(-length(g_CameraPosition-input.positionWS)*g_FogDensity))); - color.a=length(g_CameraPosition-input.positionWS); - return color; -} - -// Water shaders -[domain("quad")] -PSIn_Diffuse WaterPatchDS( PatchData input, - float2 uv : SV_DomainLocation, - OutputPatch inputPatch ) -{ - PSIn_Diffuse output; - float3 vertexPosition; - float2 texcoord0to1 = (input.origin + uv * input.size)/g_HeightFieldSize; - float4 water_normal; - float4 depthmap_scaler; - - // getting rough estimate of water depth from depth map texture - depthmap_scaler=g_DepthMapTexture.SampleLevel(SamplerLinearWrap, float2(texcoord0to1.x,1-texcoord0to1.y),0); - - // calculating water surface geometry position and normal - vertexPosition.xz = input.origin + uv * input.size; - vertexPosition.y = -g_WaterHeightBumpScale/2; - water_normal=CombineWaterNormal(vertexPosition.xyz); - - // fading out displacement and normal disturbance near shores by 60% - water_normal.xyz=lerp(float3(0,1,0),normalize(water_normal.xyz),0.4+0.6*depthmap_scaler.g); - vertexPosition.y+=water_normal.w*g_WaterHeightBumpScale*(0.4+0.6*depthmap_scaler.g); - vertexPosition.xz-=(water_normal.xz)*0.5*(0.4+0.6*depthmap_scaler.g); - - // writing output params - output.position = mul(float4(vertexPosition, 1.0), g_ModelViewProjectionMatrix); - output.texcoord = texcoord0to1*g_WaterMicroBumpTexcoordScale+g_WaterBumpTexcoordShift*0.07; - output.normal=normalize(water_normal.xyz); - output.depthmap_scaler=depthmap_scaler; - output.positionWS = vertexPosition; - return output; -} - -float4 WaterPatchPS(PSIn_Diffuse input) : SV_Target -{ - float4 color; - float3 pixel_to_light_vector = normalize(g_LightPosition-input.positionWS); - float3 pixel_to_eye_vector = normalize(g_CameraPosition-input.positionWS); - float3 reflected_eye_to_pixel_vector; - float3 microbump_normal; - float3x3 normal_rotation_matrix; - - float fresnel_factor; - float diffuse_factor; - float specular_factor; - float scatter_factor; - float4 refraction_color; - float4 reflection_color; - float4 disturbance_eyespace; - - float water_depth; - float4 water_color; - - // calculating pixel position in light space - float4 positionLS = mul(float4(input.positionWS,1),g_LightModelViewProjectionMatrix); - positionLS.xyz/=positionLS.w; - positionLS.x=(positionLS.x+1)*0.5; - positionLS.y=(1-positionLS.y)*0.5; - - // calculating shadow multiplier to be applied to diffuse/scatter/specular light components - float dsf=1.0f/4096.0f; - float shadow_factor=0.2*g_DepthTexture.SampleCmp(SamplerDepthAnisotropic,positionLS.xy,positionLS.z* 0.995f).r; - shadow_factor+=0.2*g_DepthTexture.SampleCmp(SamplerDepthAnisotropic,positionLS.xy+float2(dsf,dsf),positionLS.z* 0.995f).r; - shadow_factor+=0.2*g_DepthTexture.SampleCmp(SamplerDepthAnisotropic,positionLS.xy+float2(-dsf,dsf),positionLS.z* 0.995f).r; - shadow_factor+=0.2*g_DepthTexture.SampleCmp(SamplerDepthAnisotropic,positionLS.xy+float2(dsf,-dsf),positionLS.z* 0.995f).r; - shadow_factor+=0.2*g_DepthTexture.SampleCmp(SamplerDepthAnisotropic,positionLS.xy+float2(-dsf,-dsf),positionLS.z* 0.995f).r; - - // need more high frequency bumps for plausible water surface, so creating normal defined by 2 instances of same bump texture - microbump_normal = normalize(2*g_WaterBumpTexture.Sample(SamplerAnisotropicWrap,input.texcoord-g_WaterBumpTexcoordShift*0.2).gbr - float3 (1,-8,1)); - microbump_normal+= normalize(2*g_WaterBumpTexture.Sample(SamplerAnisotropicWrap,input.texcoord*0.5+g_WaterBumpTexcoordShift*0.05).gbr - float3 (1,-8,1)); - - // calculating base normal rotation matrix - normal_rotation_matrix[1]=input.normal.xyz; - normal_rotation_matrix[2]=normalize(cross(float3(0.0,0.0,-1.0),normal_rotation_matrix[1])); - normal_rotation_matrix[0]=normalize(cross(normal_rotation_matrix[2],normal_rotation_matrix[1])); - - // applying base normal rotation matrix to high frequency bump normal - microbump_normal=mul(normalize(microbump_normal),normal_rotation_matrix); - - - // simulating scattering/double refraction: light hits the side of wave, travels some distance in water, and leaves wave on the other side - // it's difficult to do it physically correct without photon mapping/ray tracing, so using simple but plausible emulation below - - // only the crests of water waves generate double refracted light - scatter_factor=2.5*max(0,input.positionWS.y*0.25+0.25); - - // the waves that lie between camera and light projection on water plane generate maximal amount of double refracted light - scatter_factor*=shadow_factor*pow(max(0.0,dot(normalize(float3(pixel_to_light_vector.x,0.0,pixel_to_light_vector.z)),-pixel_to_eye_vector)),2.0); - - // the slopes of waves that are oriented back to light generate maximal amount of double refracted light - scatter_factor*=pow(max(0.0,1.0-dot(pixel_to_light_vector,microbump_normal)),8.0); - - // water crests gather more light than lobes, so more light is scattered under the crests - scatter_factor+=shadow_factor*1.5*g_WaterColorIntensity.y*max(0,input.positionWS.y+1)* - // the scattered light is best seen if observing direction is normal to slope surface - max(0,dot(pixel_to_eye_vector,microbump_normal))* - // fading scattered light out at distance and if viewing direction is vertical to avoid unnatural look - max(0,1-pixel_to_eye_vector.y)*(300.0/(300+length(g_CameraPosition-input.positionWS))); - - // fading scatter out by 90% near shores so it looks better - scatter_factor*=0.1+0.9*input.depthmap_scaler.g; - - // calculating fresnel factor - float r=(1.2-1.0)/(1.2+1.0); - fresnel_factor = max(0.0,min(1.0,r+(1.0-r)*pow(1.0-dot(microbump_normal,pixel_to_eye_vector),4))); - - // calculating specular factor - reflected_eye_to_pixel_vector=-pixel_to_eye_vector+2*dot(pixel_to_eye_vector,microbump_normal)*microbump_normal; - specular_factor=shadow_factor*fresnel_factor*pow(max(0,dot(pixel_to_light_vector,reflected_eye_to_pixel_vector)),g_WaterSpecularPower); - - // calculating diffuse intensity of water surface itself - diffuse_factor=g_WaterColorIntensity.x+g_WaterColorIntensity.y*max(0,dot(pixel_to_light_vector,microbump_normal)); - - // calculating disturbance which has to be applied to planar reflections/refractions to give plausible results - disturbance_eyespace=mul(float4(microbump_normal.x,0,microbump_normal.z,0),g_ModelViewMatrix); - - float2 reflection_disturbance=float2(disturbance_eyespace.x,disturbance_eyespace.z)*0.03; - float2 refraction_disturbance=float2(-disturbance_eyespace.x,disturbance_eyespace.y)*0.05* - // fading out reflection disturbance at distance so reflection doesn't look noisy at distance - (20.0/(20+length(g_CameraPosition-input.positionWS))); - - // calculating correction that shifts reflection up/down according to water wave Y position - float4 projected_waveheight = mul(float4(input.positionWS.x,input.positionWS.y,input.positionWS.z,1),g_ModelViewProjectionMatrix); - float waveheight_correction=-0.5*projected_waveheight.y/projected_waveheight.w; - projected_waveheight = mul(float4(input.positionWS.x,-0.8,input.positionWS.z,1),g_ModelViewProjectionMatrix); - waveheight_correction+=0.5*projected_waveheight.y/projected_waveheight.w; - reflection_disturbance.y=max(-0.15,waveheight_correction+reflection_disturbance.y); - - // picking refraction depth at non-displaced point, need it to scale the refraction texture displacement amount according to water depth - float refraction_depth=GetRefractionDepth(input.position.xy*g_ScreenSizeInv); - refraction_depth=g_ZFar*g_ZNear/(g_ZFar-refraction_depth*(g_ZFar-g_ZNear)); - float4 vertex_in_viewspace=mul(float4(input.positionWS,1),g_ModelViewMatrix); - water_depth=refraction_depth-vertex_in_viewspace.z; - float nondisplaced_water_depth=water_depth; - - // scaling refraction texture displacement amount according to water depth, with some limit - refraction_disturbance*=min(2,water_depth); - - // picking refraction depth again, now at displaced point, need it to calculate correct water depth - refraction_depth=GetRefractionDepth(input.position.xy*g_ScreenSizeInv+refraction_disturbance); - refraction_depth=g_ZFar*g_ZNear/(g_ZFar-refraction_depth*(g_ZFar-g_ZNear)); - vertex_in_viewspace=mul(float4(input.positionWS,1),g_ModelViewMatrix); - water_depth=refraction_depth-vertex_in_viewspace.z; - - // zeroing displacement for points where displaced position points at geometry which is actually closer to the camera than the water surface - float conservative_refraction_depth=GetConservativeRefractionDepth(input.position.xy*g_ScreenSizeInv+refraction_disturbance); - conservative_refraction_depth=g_ZFar*g_ZNear/(g_ZFar-conservative_refraction_depth*(g_ZFar-g_ZNear)); - vertex_in_viewspace=mul(float4(input.positionWS,1),g_ModelViewMatrix); - float conservative_water_depth=conservative_refraction_depth-vertex_in_viewspace.z; - - if(conservative_water_depth<0) - { - refraction_disturbance=0; - water_depth=nondisplaced_water_depth; - } - water_depth=max(0,water_depth); - - // getting reflection and refraction color at disturbed texture coordinates - reflection_color=g_ReflectionTexture.SampleLevel(SamplerLinearClamp,float2(input.position.x*g_ScreenSizeInv.x,1.0-input.position.y*g_ScreenSizeInv.y)+reflection_disturbance,0); - refraction_color=g_RefractionTexture.SampleLevel(SamplerLinearClamp,input.position.xy*g_ScreenSizeInv+refraction_disturbance,0); - - // calculating water surface color and applying atmospheric fog to it - water_color=diffuse_factor*float4(g_WaterDeepColor,1); - water_color.rgb=lerp(CalculateFogColor(pixel_to_light_vector,pixel_to_eye_vector).rgb,water_color.rgb,min(1,exp(-length(g_CameraPosition-input.positionWS)*g_FogDensity))); - - // fading fresnel factor to 0 to soften water surface edges - fresnel_factor*=min(1,water_depth*5.0); - - // fading refraction color to water color according to distance that refracted ray travels in water - refraction_color=lerp(water_color,refraction_color,min(1,1.0*exp(-water_depth/8.0))); - - // combining final water color - color.rgb=lerp(refraction_color.rgb,reflection_color.rgb,fresnel_factor); - color.rgb+=g_WaterSpecularIntensity*specular_factor*g_WaterSpecularColor*fresnel_factor; - color.rgb+=g_WaterScatterColor*scatter_factor; - color.a=1; - return color; -} - -// Water normalmap combine shaders -PSIn_Quad WaterNormalmapCombineVS(uint VertexId: SV_VertexID) -{ - PSIn_Quad output; - - output.position = float4(QuadVertices[VertexId],0,1); - output.texcoord = QuadTexCoordinates[VertexId]; - - return output; -} - -float4 WaterNormalmapCombinePS(PSIn_Quad input) : SV_Target -{ - float4 color; - color.rgb = (CombineSimplifiedWaterNormal(g_CameraPosition+float3(input.texcoord.x*400.0f-200.0f,0,input.texcoord.y*400.0f-200.0f),0).rgb+float3(1.0f,1.0f,1.0f))*0.5f; - color.a=0; - return color; -} - -// Fullscreen shaders -PSIn_Quad FullScreenQuadVS(uint VertexId: SV_VertexID) -{ - PSIn_Quad output; - - output.position = float4(QuadVertices[VertexId],0,1); - output.texcoord = QuadTexCoordinates[VertexId]; - - return output; -} - -float4 MainToBackBufferPS(PSIn_Quad input) : SV_Target -{ - float4 color; - color.rgb = g_MainTexture.SampleLevel(SamplerLinearWrap,float2((input.texcoord.x-0.5)/g_MainBufferSizeMultiplier+0.5f,(input.texcoord.y-0.5)/g_MainBufferSizeMultiplier+0.5f),0).rgb; - color.a=0; - return color; -} - -float RefractionDepthManualResolvePS1(PSIn_Quad input) : SV_Target -{ - return g_RefractionDepthTextureMS1.Load(input.position.xy,0,int2(0,0)).r; -} - -float RefractionDepthManualResolvePS2(PSIn_Quad input) : SV_Target -{ - return g_RefractionDepthTextureMS2.Load(input.position.xy,0,int2(0,0)).r; -} - -float RefractionDepthManualResolvePS4(PSIn_Quad input) : SV_Target -{ - return g_RefractionDepthTextureMS4.Load(input.position.xy,0,int2(0,0)).r; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL/IslandCommon.hlsl b/Samples/Media/materials/programs/HLSL/IslandCommon.hlsl deleted file mode 100644 index f7fa5ef8dd3..00000000000 --- a/Samples/Media/materials/programs/HLSL/IslandCommon.hlsl +++ /dev/null @@ -1,102 +0,0 @@ -/* ----------------------------------------------------------- -Island Tessellation sample from NVIDIA's DirectX 11 SDK: -http://developer.nvidia.com/nvidia-graphics-sdk-11-direct3d ----------------------------------------------------------- -*/ - -cbuffer QuadObject -{ - static const float2 QuadVertices[4] = - { - {-1.0, -1.0}, - { 1.0, -1.0}, - {-1.0, 1.0}, - { 1.0, 1.0} - }; - - static const float2 QuadTexCoordinates[4] = - { - {0.0, 1.0}, - {1.0, 1.0}, - {0.0, 0.0}, - {1.0, 0.0} - }; -} - -SamplerState SamplerPointClamp -{ - Filter = MIN_MAG_MIP_POINT; - AddressU = Clamp; - AddressV = Clamp; -}; - -SamplerState SamplerLinearClamp -{ - Filter = MIN_MAG_MIP_LINEAR; - AddressU = Clamp; - AddressV = Clamp; -}; - -SamplerState SamplerLinearWrap -{ - Filter = MIN_MAG_MIP_LINEAR; - AddressU = Wrap; - AddressV = Wrap; -}; - -SamplerState SamplerAnisotropicWrap -{ - Filter = ANISOTROPIC; - AddressU = Wrap; - AddressV = Wrap; - MaxAnisotropy = 16; -}; - -SamplerState SamplerCube -{ - Filter = MIN_MAG_MIP_POINT; - AddressU = Clamp; - AddressV = Clamp; - AddressW = Clamp; -}; - -SamplerState SamplerLinearMirror -{ - Filter = MIN_MAG_MIP_LINEAR; - AddressU = Mirror; - AddressV = Mirror; -}; - -SamplerState SamplerLinearBorderBlack -{ - Filter = MIN_MAG_MIP_LINEAR; - AddressU = Border; - AddressV = Border; - AddressW = Border; - BorderColor = float4(0, 0, 0, 0); -}; - -SamplerComparisonState SamplerBackBufferDepth -{ - Filter = COMPARISON_MIN_MAG_LINEAR_MIP_POINT; - AddressU = Border; - AddressV = Border; - BorderColor = float4(1, 1, 1, 1); - ComparisonFunc = LESS_EQUAL; -}; - -SamplerComparisonState SamplerDepthAnisotropic -{ - Filter = COMPARISON_ANISOTROPIC; - AddressU = Border; - AddressV = Border; - ComparisonFunc = LESS; - BorderColor = float4(1, 1, 1, 1); - MaxAnisotropy = 16; -}; - -float4 ColorPS(uniform float4 color) : SV_Target -{ - return color; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL/NoTessellation.hlsl b/Samples/Media/materials/programs/HLSL/NoTessellation.hlsl deleted file mode 100644 index 11fa4bf3966..00000000000 --- a/Samples/Media/materials/programs/HLSL/NoTessellation.hlsl +++ /dev/null @@ -1,128 +0,0 @@ -/** -* Modified by: Juan Camilo Acosta Arango (ja0335 ) -* Date: 09-04-2014 -* Note: This shaders are based one my study over the -* Eat3D course, "Shader Production - Writing Custom Shaders with CGFX" -* http://eat3d.com/shaders_intro -**/ - -///////////// -// GLOBALS // -///////////// -Texture2D g_NormalTxt : register( t0 ); // normal -Texture2D g_DiffuseTxt : register( t1 ); // diffuse -Texture2D g_SpecularTxt : register( t2 ); // specular -SamplerState g_samLinear : register( s0 ); - -cbuffer cbVertexBuffer -{ - matrix g_WorldViewprojMatrix; - matrix g_WorldInverseTranspose; - matrix g_World; - matrix g_InverseView; -}; - -cbuffer cbPixelBuffer -{ - float4 g_AmbientLightColour; - float3 g_LightDirection; - float3 g_LightDiffuseColour; - float3 g_DiffuseColour; - float3 g_SpecularColor; - float3 g_FresnelColor; - float g_SpecularPower; - float g_FresnelPower; -}; - - -////////////// -// TYPEDEFS // -////////////// -struct ambient_a2v -{ - float4 position : POSITION; -}; - -struct ambient_v2p -{ - float4 position : SV_POSITION; -}; - -struct perlight_a2v -{ - float4 position : POSITION; - float2 texCoord : TEXCOORD0; - float4 normal : NORMAL; - float4 binormal : BINORMAL; - float4 tangent : TANGENT; -}; - -struct perlight_v2p -{ - float4 position : SV_POSITION; - float2 texCoord : TEXCOORD0; - float3 worldNormal : TEXCOORD1; - float3 worldBinormal : TEXCOORD2; - float3 worldTangent : TEXCOORD3; - float3 eyeVector : TEXCOORD4; -}; - -//=============================================================== -// AMBIENT -ambient_v2p ambient_color_vs(ambient_a2v In) -{ - ambient_v2p Out; - - Out.position = mul(g_WorldViewprojMatrix, In.position); - - return Out; -} - -float4 ambient_color_ps(ambient_v2p In) : SV_TARGET -{ - return g_AmbientLightColour; -} - -//=============================================================== -// PER-LIGHT -perlight_v2p perlight_color_vs(perlight_a2v In) -{ - perlight_v2p Out; - - Out.position = mul(g_WorldViewprojMatrix, In.position); - Out.worldNormal = mul(g_WorldInverseTranspose, In.normal).xyz; - Out.worldBinormal = mul(g_WorldInverseTranspose, In.binormal).xyz; - Out.worldTangent = mul(g_WorldInverseTranspose, In.tangent).xyz; - - float3 worldSpacePos = mul(g_World, In.position).xyz; - float3 worldCameraPos = float3(g_InverseView[0].w, g_InverseView[1].w, g_InverseView[2].w); - - Out.eyeVector = worldCameraPos - worldSpacePos; - Out.texCoord = In.texCoord; - - return Out; -} - -float4 perlight_color_ps(perlight_v2p In) : SV_TARGET -{ - float4 outColor; - float3 worldNormal = g_NormalTxt.Sample( g_samLinear, In.texCoord ).xyz * 2 - 1; - worldNormal = normalize((worldNormal.x*In.worldTangent)+(worldNormal.y*In.worldBinormal)+(worldNormal.z*In.worldNormal)); - - float3 lightDir = normalize(-g_LightDirection); - float3 eyeVector = normalize(In.eyeVector); - float3 reflectionVector = reflect(eyeVector, worldNormal)*-1; - - float4 diffuseMap = g_DiffuseTxt.Sample( g_samLinear, In.texCoord ); - float3 lambert = saturate(dot(lightDir, worldNormal)) * g_LightDiffuseColour; - - float4 specularMap = g_SpecularTxt.Sample( g_samLinear, In.texCoord ); - float3 specular = pow(saturate(dot(reflectionVector, lightDir)), g_SpecularPower) * g_SpecularColor; - float3 fresnel = pow(1- saturate(dot(eyeVector, worldNormal)), g_FresnelPower) * g_FresnelColor; - float3 totalSpec = (fresnel * specularMap.r) + (specular * specularMap.g) ; - - outColor.rgb = (lambert + g_AmbientLightColour.xyz) * (diffuseMap.rgb * g_DiffuseColour) + totalSpec; - outColor.a = 1.0f; - - return outColor; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL/OldTV.hlsl b/Samples/Media/materials/programs/HLSL/OldTV.hlsl deleted file mode 100644 index 9aa17862722..00000000000 --- a/Samples/Media/materials/programs/HLSL/OldTV.hlsl +++ /dev/null @@ -1,57 +0,0 @@ -Texture2D Image: register(s0); -Texture3D Rand: register(s1); -Texture3D Noise: register(s2); - -SamplerState g_sam3D -{ - Filter = MIN_MAG_LINEAR_MIP_POINT; - AddressU = Wrap; - AddressV = Wrap; - AddressW = Wrap; -}; - -SamplerState g_sam2D -{ - Filter = MIN_MAG_MIP_LINEAR; - AddressU = Wrap; - AddressV = Wrap; -}; - -float4 OldTV_ps(float4 posIn: SV_POSITION, float2 img: TEXCOORD0, - uniform float distortionFreq: register(c3), - uniform float distortionScale: register(c4), - uniform float distortionRoll: register(c5), - uniform float interference: register(c7), - uniform float frameLimit: register(c8), - uniform float frameShape: register(c0), - uniform float frameSharpness: register(c1), - uniform float time_0_X: register(c2), - uniform float sin_time_0_X: register(c6) - -) : SV_Target { - // Define a frame shape - float2 pos = abs((img - 0.5) * 2.0); - float f = (1 - pos.x * pos.x) * (1 - pos.y * pos.y); - float frame = saturate(frameSharpness * (pow(abs(f), frameShape) - frameLimit)); - - // Interference ... just a texture filled with rand() - float4 rand = Rand.Sample(g_sam2D, float3(1.5 * pos, time_0_X)); - rand -= float4(0.2,0.2,0.2,0.2); - - // Some signed noise for the distortion effect - float4 noisy = Noise.Sample(g_sam3D, float3(0, 0.5 * pos.y, 0.1 * time_0_X)); - noisy -= float4(0.5,0.5,0.5,0.5); - - // Repeat a 1 - x^2 (0 < x < 1) curve and roll it with sinus. - float dst = frac(pos.y * distortionFreq + distortionRoll * sin_time_0_X); - dst *= (1 - dst); - // Make sure distortion is highest in the center of the image - dst /= 1 + distortionScale * abs(pos.y); - - // ... and finally distort - img.x += distortionScale * noisy.x * dst; - float4 image = Image.Sample(g_sam2D, img); - - // Combine frame, distorted image and interference - return frame * (interference * rand.x + image); -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL/ParticleGS.hlsl b/Samples/Media/materials/programs/HLSL/ParticleGS.hlsl deleted file mode 100644 index 54cad2ff888..00000000000 --- a/Samples/Media/materials/programs/HLSL/ParticleGS.hlsl +++ /dev/null @@ -1,322 +0,0 @@ -// -// Explanation of different particle types -// -#define PT_LAUNCHER 0 //Firework Launcher - launches a PT_SHELL every so many seconds -#define PT_SHELL 1 //Unexploded shell - flies from the origin and explodes into many PT_EMBERXs -#define PT_EMBER1 2 //basic particle - after it's emitted from the shell, it dies -#define PT_EMBER2 3 //after it's emitted, it explodes again into many PT_EMBER1s -#define PT_EMBER3 4 //just a differently colored ember1 -#define P_SHELLLIFE 3.0 -#define P_EMBER1LIFE 2.5 -#define P_EMBER2LIFE 1.5 -#define P_EMBER3LIFE 2.0 - -//These two were originally shader params, but they caused runtime errors -#define NUM_EMBER_1S 30 -#define NUM_EMBER_2S 15 -#define NUM_EMBER_3S 10 -//This one was originally a variant, but this also causes runtime errors -//#define MAX_EMBER_2S 15.0 - -// -// Generic particle motion handler -// - -struct VSParticleIn -{ - float3 pos : POSITION; - float timer : TEXCOORD0; - float type : TEXCOORD1; - float3 vel : TEXCOORD2; -}; - -struct VSParticleDrawOut -{ - float4 pos : POSITION; - float4 color : COLOR0; - float2 radius : TEXCOORD0; -}; - -struct PSSceneIn -{ - float4 pos : SV_Position; - float2 tex : TEXCOORD0; - float4 color : COLOR0; -}; - -SamplerState g_samPoint -{ - Filter = MIN_MAG_MIP_POINT; - AddressU = Wrap; -}; - -SamplerState g_samLinear -{ - Filter = MIN_MAG_MIP_LINEAR; - AddressU = Clamp; - AddressV = Clamp; -}; - -void GSGenericHandler( VSParticleIn input - , float elapsedTime - , float3 frameGravity - , inout PointStream OutputStream - ) -{ - input.pos.xyz += input.vel * elapsedTime; - input.vel += frameGravity; - input.timer -= elapsedTime; - if (input.pos.y > -100) - { - OutputStream.Append(input); - } -} - -// -// Sample a random direction from our random texture -// -float3 RandomDir(float fOffset, float globalTime, Texture1D randomTex) -{ - float2 tCoord; - tCoord.x = (globalTime + fOffset) / 300.0; - tCoord.y = 0.5; - return randomTex.SampleLevel(g_samPoint, tCoord.x, 0).rgb; -} - -// -// Launcher type particle handler -// -void GSLauncherHandler( VSParticleIn input, - float elapsedTime, - float globalTime, - Texture1D randomTex, - float secondsPerFirework, - inout PointStream outputStream) -{ - if(input.timer <= 0) - { - VSParticleIn gsOutput; - float3 vRandom = normalize( RandomDir( input.type, globalTime, randomTex) ); - //Give it more of an up bias - vRandom = normalize(vRandom + float3(0,2.5,0)); - - //time to emit a new SHELL - gsOutput.pos.xyz = input.pos.xyz + input.vel*elapsedTime; - gsOutput.vel = input.vel + vRandom*35.0; - gsOutput.timer = P_SHELLLIFE + vRandom.y*0.5; - gsOutput.type = PT_SHELL; - - outputStream.Append(gsOutput); - - //reset our timer - input.timer = secondsPerFirework + vRandom.x*0.4; - } - else - { - input.timer -= elapsedTime; - } - - //emit ourselves to keep us alive - outputStream.Append(input); -} - -// -// Shell type particle handler -// -void GSShellHandler( VSParticleIn input, - float elapsedTime, - float globalTime, - Texture1D randomTex, - float3 frameGravity, - inout PointStream outputStream) -{ - if(input.timer <= 0) - { - VSParticleIn gsOutput; - - float3 vRandom = float3(0,0,0); - - //time to emit a series of new Ember1s - { - for(int i=0; i outputStream) -{ - if(input.timer > 0) - { - GSGenericHandler(input, elapsedTime, frameGravity, outputStream); - } -} - -// -// Ember2 type particle handler -// -void GSEmber2Handler(VSParticleIn input - , float elapsedTime - , float globalTime - , Texture1D randomTex - , float3 frameGravity - , inout PointStream outputStream) -{ - VSParticleIn gsOutput; - if(input.timer <= 0) - { - //time to emit a series of new Ember3s - for(int i=0; i ParticleOutputStream - , uniform Texture1D randomTex - , uniform float3 gravity - , uniform float globalTime - , uniform float elapsedTime - , uniform float secondsPerFirework - ) -{ - float3 frameGravity = gravity * elapsedTime; - if( input[0].type == PT_LAUNCHER ) - GSLauncherHandler( input[0], elapsedTime, globalTime, randomTex, secondsPerFirework, ParticleOutputStream); - else if ( input[0].type == PT_SHELL ) - GSShellHandler( input[0], elapsedTime, globalTime, randomTex, frameGravity, ParticleOutputStream); - else if ( input[0].type == PT_EMBER1 ||input[0].type == PT_EMBER3 ) - GSEmber1Handler( input[0], elapsedTime, frameGravity, ParticleOutputStream); - else if( input[0].type == PT_EMBER2 ) - GSEmber2Handler( input[0], elapsedTime, globalTime, randomTex, frameGravity, ParticleOutputStream); -} - -//The vertex shader that prepares the fireworks for display -VSParticleDrawOut DisplayParticles_VS(VSParticleIn input, - uniform float4x4 worldView, - uniform float4x4 proj) -{ - VSParticleDrawOut output; - // - // Pass the point through - // - output.pos = mul(worldView, float4(input.pos,1)); - output.radius = float2(1.5, 1.5); - - // - // calculate the color - // - if( input.type == PT_LAUNCHER ) - { - output.color = float4(1,0.1,0.1,1); - output.radius = float2(1.0, 1.0); - } - else if( input.type == PT_SHELL ) - { - output.color = float4(0.1,1,1,1); - output.radius = float2(1.0, 1.0); - } - else if( input.type == PT_EMBER1 ) - { - output.color = float4(1,1,0.1,1); - output.color *= (input.timer / P_EMBER1LIFE ); - } - else if( input.type == PT_EMBER2 ) - { - output.color = float4(1,0.1,1,1); - } - else if( input.type == PT_EMBER3 ) - { - output.color = float4(1,0.1,0.1,1); - output.color *= (input.timer / P_EMBER3LIFE ); - } - else - { - output.color = float4(0,0,0,0); - } - - float4 tmp = mul(proj, float4(output.radius, output.pos.z, 1)); - output.radius = tmp.xy; // no w divison here, no viewport normalization in GS - output.pos = mul(proj, output.pos); - - return output; -} - -//The geometry shader that prepares the fireworks for display -[maxvertexcount(4)] -void DisplayParticles_GS( point VSParticleDrawOut input[1] - , inout TriangleStream SpriteStream) -{ - float2 g_positions[4] = { float2( -1, 1 ), float2( -1, -1 ), float2( 1, 1 ), float2( 1, -1 ) }; - float2 g_texcoords[4] = { float2(0,1), float2(1,1), float2(0,0), float2(1,0) }; - - PSSceneIn output; - - // - // Emit two new triangles - // - for(int i=0; i<4; i++) - { - output.pos = input[0].pos - float4(g_positions[i]*input[0].radius, 0, 0); - output.tex = g_texcoords[i]; - output.color = input[0].color; - SpriteStream.Append(output); - } - SpriteStream.RestartStrip(); -} - -//The pixels shaders that colors the fireworks -float4 DisplayParticles_PS( PSSceneIn input - , uniform Texture2D diffuseTex) : SV_Target -{ - return diffuseTex.Sample(g_samLinear, input.tex) * input.color; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL/PassthroughFP_sm4.hlsl b/Samples/Media/materials/programs/HLSL/PassthroughFP_sm4.hlsl deleted file mode 100644 index 4b273dbc12b..00000000000 --- a/Samples/Media/materials/programs/HLSL/PassthroughFP_sm4.hlsl +++ /dev/null @@ -1,16 +0,0 @@ -float4 main (float4 pos : SV_POSITION, - float2 oUv : TEXCOORD0, - float4 colour : COLOR) : SV_Target -{ - return colour; -} - -float4 mainCg (float4 pos : SV_POSITION, float4 colour0 : COLOR) : SV_Target -{ - return colour0; -} - -float4 mainForAmbientOneTexture (float4 pos : SV_POSITION, float2 oUv : TEXCOORD0, float4 colour0 : COLOR, uniform float4 colour) : SV_Target -{ - return colour; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL/Radial_Blur_FP.hlsl b/Samples/Media/materials/programs/HLSL/Radial_Blur_FP.hlsl deleted file mode 100644 index 3e95a4d8958..00000000000 --- a/Samples/Media/materials/programs/HLSL/Radial_Blur_FP.hlsl +++ /dev/null @@ -1,58 +0,0 @@ -//------------------------------------------------------ -//Radial_Blur_FP.cg -// Implements radial blur to be used with the compositor -// It's very dependent on screen resolution -//------------------------------------------------------ - -uniform sampler2D tex: register(s0); - -static const float samples[10] = -{ --0.08, --0.05, --0.03, --0.02, --0.01, -0.01, -0.02, -0.03, -0.05, -0.08 -}; - -float4 main(float4 Pos : SV_POSITION, - float2 texCoord: TEXCOORD0, - uniform float sampleDist, - uniform float sampleStrength - ) : COLOR -{ - //Vector from pixel to the center of the screen - float2 dir = 0.5 - texCoord; - - //Distance from pixel to the center (distant pixels have stronger effect) - //float dist = distance( float2( 0.5, 0.5 ), texCoord ); - float dist = sqrt( dir.x*dir.x + dir.y*dir.y ); - - - //Now that we have dist, we can normlize vector - dir = normalize( dir ); - - //Save the color to be used later - float4 color = tex2D( tex, texCoord ); - //Average the pixels going along the vector - float4 sum = color; - for (int i = 0; i < 10; i++) - { - float4 res=tex2D( tex, texCoord + dir * samples[i] * sampleDist ); - sum += res; - } - sum /= 11; - - //Calculate amount of blur based on - //distance and a strength parameter - float t = dist * sampleStrength; - t = saturate( t );//We need 0 <= t <= 1 - - //Blend the original color with the averaged pixels - return lerp( color, sum, t ); -} diff --git a/Samples/Media/materials/programs/HLSL/Swizzle.gp b/Samples/Media/materials/programs/HLSL/Swizzle.gp deleted file mode 100644 index 929c4e616ed..00000000000 --- a/Samples/Media/materials/programs/HLSL/Swizzle.gp +++ /dev/null @@ -1,39 +0,0 @@ -!!NVgp4.0 -PRIMITIVE_IN TRIANGLES; -PRIMITIVE_OUT TRIANGLE_STRIP; -VERTICES_OUT 6; -# cgc version 2.0.0015, build date May 15 2008 -# command line args: -profile gpu_gp -# source file: gs_simple.cg -#vendor NVIDIA Corporation -#version 2.0.0.15 -#profile gpu_gp -#program geometry_swizzle -#semantic geometry_swizzle.position : POSITION -#var float4 position.__data[0] : $vin.VERTEX[0].POSITION : HPOS[0][32] : 0 : 1 -#var float4 position.__data[1] : $vin.VERTEX[1].POSITION : HPOS[1][32] : 0 : 1 -#var float4 position.__data[2] : $vin.VERTEX[2].POSITION : HPOS[2][32] : 0 : 1 -ATTRIB vertex_position = vertex.position; -TEMP RC, HC; -MOV.F result.position, vertex[0].position; -MOV.F result.color, {1, 0}.xyyx; -EMIT; -MOV.F result.position, vertex[1].position; -MOV.F result.color, {1, 0}.xyyx; -EMIT; -MOV.F result.position, vertex[2].position; -MOV.F result.color, {1, 0}.xyyx; -EMIT; -ENDPRIM; -MOV.F result.position, vertex[0].position.yxzw; -MOV.F result.color, {0, 1}.xxyy; -EMIT; -MOV.F result.position, vertex[1].position.yxzw; -MOV.F result.color, {0, 1}.xxyy; -EMIT; -MOV.F result.position, vertex[2].position.yxzw; -MOV.F result.color, {0, 1}.xxyy; -EMIT; -ENDPRIM; -END -# 20 instructions, 0 R-regs \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL/TerrainTessellation.hlsl b/Samples/Media/materials/programs/HLSL/TerrainTessellation.hlsl deleted file mode 100644 index e9a6248be5b..00000000000 --- a/Samples/Media/materials/programs/HLSL/TerrainTessellation.hlsl +++ /dev/null @@ -1,715 +0,0 @@ -/* ----------------------------------------------------------- -Terrain Tessellation sample from NVIDIA's DirectX 11 SDK: -http://developer.nvidia.com/nvidia-graphics-sdk-11-direct3d ----------------------------------------------------------- -*/ - -#include "TerrainTessellationINoise.hlsl" -#include "TerrainTessellationCommon.hlsl" - -// Work-around for an optimization rule problem in the June 2010 HLSL Compiler (9.29.952.3111). -// Without this, we get cracks in the terrain. -// see http://support.microsoft.com/kb/2448404 -// and http://blogs.msdn.com/b/chuckw/archive/2010/10/27/june-2010-hlsl-compiler-issue-with-tessellation.aspx -#if D3DX_VERSION == 0xa2b -#pragma ruledisable 0x0802405f -#endif - -Texture2D g_CoarseHeightMap; -Texture2D g_CoarseGradientMap; -Texture2D g_DetailNoiseTexture; -Texture2D g_DetailNoiseGradTexture; - -shared cbuffer UniformVariables -{ - int g_DebugShowTiles; - int g_DebugShowPatches; - float g_DetailNoiseScale; - float g_fDisplacementHeight; - float g_tileSize; - float2 g_DetailUVScale; - int3 g_FractalOctaves; - float3 g_TextureWorldOffset; -}; - -cbuffer TessellationBuffer -{ - float2 g_screenSize; //Tessellation factors: x=edge, y=inside, z=MinDistance, w=range - float g_tessellatedTriWidth; -}; - -cbuffer MatrixBuffer -{ - float fDisplacementScale; - float3 g_EyePos; // world-space eye position - float3 g_ViewDir; // world-space eye direction - // The proj matrix does not vary between the LOD and view-centre versions. Only the view matrix varies. - matrix g_WorldViewProj; - matrix g_WorldViewLOD, g_WorldViewProjLOD; - matrix g_Proj; -}; - -struct VS_CONTROL_POINT_OUTPUT -{ - float3 vPosition : POSITION; - float2 vWorldXZ : TEXCOORD1; - Adjacency adjacency : ADJACENCY_SIZES; -}; - -struct MeshVertex -{ - float4 vPosition : SV_Position; - float2 vWorldXZ : TEXCOORD1; - float3 vNormal : NORMAL; - float3 debugColour : COLOR; -}; - -// There's no vertex data. Position and UV coords are created purely from vertex and instance IDs. -void ReconstructPosition1(AppVertex input, out float3 pos, out int2 intUV) -{ - float iv = floor(input.VertexId * RECIP_CONTROL_VTX_PER_TILE_EDGE); - float iu = input.VertexId - iv * CONTROL_VTX_PER_TILE_EDGE; - float u = iu / (CONTROL_VTX_PER_TILE_EDGE - 1.0); - float v = iv / (CONTROL_VTX_PER_TILE_EDGE - 1.0); - - // Shrink tiles slightly to show gaps between them. - float size = g_tileSize; - if (g_DebugShowTiles) - size *= 0.98; - - pos = float3(u * size + input.position.x, 0, v * size + input.position.y); - intUV = int2(iu,iv); -} - -/*void ReconstructPosition(AppVertex input, out float3 pos) -{ - int2 dummy; - ReconstructPosition(input, pos, dummy); -}*/ - -// There's no vertex data. Position and UV coords are created purely from vertex and instance IDs. -void ReconstructPosition2(AppVertexTessellation input, out float3 pos, out int2 intUV) -{ - float iv = floor(input.VertexId * RECIP_CONTROL_VTX_PER_TILE_EDGE); - float iu = input.VertexId - iv * CONTROL_VTX_PER_TILE_EDGE; - float u = iu / (CONTROL_VTX_PER_TILE_EDGE - 1.0); - float v = iv / (CONTROL_VTX_PER_TILE_EDGE - 1.0); - - // Shrink tiles slightly to show gaps between them. - float size = g_tileSize; - if (g_DebugShowTiles) - size *= 0.98; - - pos = float3(u * size + input.position.x, 0, v * size + input.position.y); - intUV = int2(iu,iv); -} - -/*void ReconstructPosition(AppVertexTessellation input, out float3 pos) -{ - int2 dummy; - ReconstructPosition(input, pos, dummy); -}*/ - -// A very simple, regular procedural terrain for debugging cracks etc. -float debugSineHills(float2 uv) -{ - const float HORIZ_SCALE = 4 * 3.14159, VERT_SCALE = 1; - uv *= HORIZ_SCALE; - return VERT_SCALE * (sin(uv.x) + 1) * (sin(uv.y) + 1) - 0.5; -} - -float DetailUVScale() -{ - const float DETAIL_UV_SCALE = pow(2, g_FractalOctaves.x + g_FractalOctaves.y + g_FractalOctaves.z - 5); - return DETAIL_UV_SCALE; -} - -float2 DetailNoiseSampleCoords(float2 uv, float2 g_DetailUVScale, float3 g_TextureWorldOffset) -{ - // Texture coords have to be offset by the eye's 2D world position. - const float2 texOffset = float2(g_TextureWorldOffset.x, -g_TextureWorldOffset.z); - - const float2 detailUV = (texOffset + WORLD_UV_REPEATS * uv) * g_DetailUVScale.x; // TBD: is WORLD_UV_REPEATS spurious here? - return detailUV; -} - -float ScaleDetailNoise(float coarse, float detail, float g_DetailNoiseScale) -{ - // The 8-bit texture needs a scale + bias. - detail = 2.0 * detail - 1.0; - - // Note the detail is modulated by the height of the coarse sample, ridge octave style. - return g_DetailNoiseScale * detail * saturate(coarse); -} - -float2 ScaleDetailGrad(float2 grad, float g_DetailNoiseScale) -{ - return g_DetailNoiseScale * ((2 * grad) - 1); // 2x-1 scale and bias -} - -float SampleLevelDetailNoise(float2 uv, float coarse, float g_DetailNoiseScale, float2 g_DetailUVScale, float3 g_TextureWorldOffset) -{ - const int mip = 0; - float detail = g_DetailNoiseTexture.SampleLevel(SamplerRepeatLinear, DetailNoiseSampleCoords(uv,g_DetailUVScale,g_TextureWorldOffset), mip).r; - return ScaleDetailNoise(coarse, detail, g_DetailNoiseScale); -} - -float2 SampleDetailGradOctaves(float2 uv, float g_DetailNoiseScale, float2 g_DetailUVScale, float3 g_TextureWorldOffset) -{ - // There is a 50x scale built into the texture in order to make better use of the range. This scale - // is hardcoded by the GUI in the normal map generator. Compensate here with a 1/50. - const float TEX_SCALE = 0.02; - float2 grad = TEX_SCALE * ScaleDetailGrad(g_DetailNoiseGradTexture.Sample(SamplerRepeatMaxAniso, DetailNoiseSampleCoords(uv,g_DetailUVScale,g_TextureWorldOffset)).ra,g_DetailNoiseScale); - return grad; -} - -float2 worldXZtoHeightUV(float2 worldXZ) -{ - // [-8,8] -> [0,1] TBD: Ought to depend on world size though. - return worldXZ / 16 + 0.5; -} - -float2 heightUVToWorldXZ(float2 uv) -{ - // [0,1] -> [-8,8] TBD: Ought to depend on world size though. - return 16 * (uv - 0.5); -} - -// Wrappers for displacement map sampling allow us to substitute a 100% procedural surface. -// VS and DS sampling have to agree and use common code. -float SampleHeightForVS(Texture2D coarseTex, SamplerState coarseSampler, float2 worldXZ, int2 offset, float g_DetailNoiseScale, float2 g_DetailUVScale /*, int3 g_FractalOctaves*/, float3 g_TextureWorldOffset) -{ - const float2 uv = worldXZtoHeightUV(worldXZ); - const int mipLevel = 0; - - // You can implement purely procedural terrain here, evaluating the height fn on-the-fly. - // But for any complex function, with loads of octaves, it's faster to sample from a texture. - // return debugSineHills(uvCol); // Simple test shape. - // return 1.5 * hybridTerrain(uvCol, g_FractalOctaves); // Procedurally sampled fractal terrain. - - // Fractal terrain sampled from texture. This is a render target that is updated when the view - // point changes. There are two levels of textures here. 1) The low-res ridge noise map that is - // initialized by the deformation effect. 2) A detail texture that contains 5 octaves of - // repeating fBm. - float coarse = coarseTex.SampleLevel(coarseSampler, uv, mipLevel, offset).r; // coarse - - return VERTICAL_SCALE * (coarse + SampleLevelDetailNoise(uv, coarse, g_DetailNoiseScale, g_DetailUVScale, g_TextureWorldOffset)); // detail -} - -float SampleHeightForVS(Texture2D tex, SamplerState sam, float2 worldXZ, float g_DetailNoiseScale,float2 g_DetailUVScale/*, int3 g_FractalOctaves*/, float3 g_TextureWorldOffset) -{ - int2 offset = 0; - return SampleHeightForVS(tex, sam, worldXZ, offset, g_DetailNoiseScale, g_DetailUVScale/*, g_FractalOctaves*/, g_TextureWorldOffset); -} - -MeshVertex VTFDisplacementVS(AppVertex input) -{ - MeshVertex output = (MeshVertex) 0; - float3 displacedPos; - int2 intUV; - ReconstructPosition1(input, displacedPos, intUV); - - float z = g_fDisplacementHeight * SampleHeightForVS(g_CoarseHeightMap, SamplerClampLinear, displacedPos.xz, int2(1,1), g_DetailNoiseScale, g_DetailUVScale/*, g_FractalOctaves*/, g_TextureWorldOffset); - float z2 = g_fDisplacementHeight * SampleHeightForVS(g_CoarseHeightMap, SamplerClampLinear, displacedPos.xz, int2(2,1), g_DetailNoiseScale, g_DetailUVScale/*, g_FractalOctaves*/, g_TextureWorldOffset); - float z3 = g_fDisplacementHeight * SampleHeightForVS(g_CoarseHeightMap, SamplerClampLinear, displacedPos.xz, int2(1,2), g_DetailNoiseScale, g_DetailUVScale/*, g_FractalOctaves*/, g_TextureWorldOffset); - - float3 normal = float3(z2 - z, 1.0 / CONTROL_VTX_PER_TILE_EDGE, z3 - z); - - displacedPos.y += z; - - output.vPosition = mul( float4( displacedPos, 1.0f ), g_WorldViewProj ); - output.vWorldXZ = displacedPos.xz; - output.vNormal = normalize(normal); - output.debugColour = float3(1, 0.1, 0); - output.vNormal = float3(1,1,1); - //output.g_DebugShowPatches = g_DebugShowPatches; - //output.g_DetailNoiseScale = g_DetailNoiseScale; - //output.g_fDisplacementHeight = g_fDisplacementHeight; - //output.g_DetailUVScale = g_DetailUVScale; - /*output.g_FractalOctaves = g_FractalOctaves; */ - //output.g_TextureWorldOffset = g_TextureWorldOffset; - // For debugging, darken a chequer board pattern of tiles to highlight tile boundaries. - if (g_DebugShowPatches) - output.vNormal *= (0.5 * (((uint) intUV.x + (uint) intUV.y) % 2) + 0.5); - - return output; -} - -VS_CONTROL_POINT_OUTPUT HwTessellationPassThruVS( AppVertexTessellation input ) -{ - VS_CONTROL_POINT_OUTPUT output; - int2 intUV; - ReconstructPosition2(input, output.vPosition, intUV); - - float z = SampleHeightForVS(g_CoarseHeightMap, SamplerClampLinear, output.vPosition.xz, g_DetailNoiseScale, g_DetailUVScale/*, g_FractalOctaves*/, g_TextureWorldOffset); - output.vPosition.y += z; - output.vWorldXZ = output.vPosition.xz; - output.adjacency = input.adjacency; - //output.g_DetailNoiseScale = g_DetailNoiseScale; - //output.g_DetailUVScale = g_DetailUVScale; - /*output.g_FractalOctaves = g_FractalOctaves; */ - //output.g_TextureWorldOffset = g_TextureWorldOffset; - - return output; -} - -//-------------------------------------------------------------------------------------- -// Constant data function for the Terrain tessellation. This is executed once per patch. -//-------------------------------------------------------------------------------------- -struct HS_CONSTANT_DATA_OUTPUT -{ - float Edges[4] : SV_TessFactor; - float Inside[2] : SV_InsideTessFactor; - float2 vWorldXZ[4] : TEXCOORD4; - float3 debugColour[5] : COLOR; // 5th is centre -}; - -struct HS_OUTPUT -{ - float3 vPosition : POSITION; -}; - -// These are one colour for each tessellation level and linear graduations between. -static const float3 DEBUG_COLOURS[6] = -{ - float3(0,0,1), // 2 - blue - float3(0,1,1), // 4 - cyan - float3(0,1,0), // 8 - green - float3(1,1,0), // 16 - yellow - float3(1,0,1), // 32 - purple - float3(1,0,0), // 64 - red -}; - -float ClipToScreenSpaceTessellation(float4 clip0, float4 clip1) -{ - clip0 /= clip0.w; - clip1 /= clip1.w; - - clip0.xy *= g_screenSize; - clip1.xy *= g_screenSize; - - const float d = distance(clip0, clip1); - - // g_tessellatedTriWidth is desired pixels per tri edge - return clamp(d / g_tessellatedTriWidth, 0,64); -} - -// Project an edge into clip space and return the number of triangles that are required to fit across it -// in screenspace. -float EdgeToScreenSpaceTessellation(float3 p0, float3 p1) -{ - float4 clip0 = mul(float4(p0,1), g_WorldViewProjLOD); - float4 clip1 = mul(float4(p1,1), g_WorldViewProjLOD); - return ClipToScreenSpaceTessellation(clip0, clip1); -} - -// Project a sphere into clip space and return the number of triangles that are required to fit across the -// screenspace diameter. (For convenience of the caller, we expect two edge end points and use the mid point as centre.) -float SphereToScreenSpaceTessellation(float3 p0, float3 p1, float diameter) -{ - float3 centre = 0.5 * (p0+p1); - float4 view0 = mul(float4(centre,1), g_WorldViewLOD); - float4 view1 = view0; - view1.x += WORLD_SCALE * diameter; - - float4 clip0 = mul(view0, g_Proj); - float4 clip1 = mul(view1, g_Proj); - return ClipToScreenSpaceTessellation(clip0, clip1); -} - -// Lifted from Tim's Island demo code. -bool inFrustum(const float3 pt, const float3 eyePos, const float3 viewDir, float margin) -{ - // conservative frustum culling - float3 eyeToPt = pt - eyePos; - float3 patch_to_camera_direction_vector = viewDir * dot(eyeToPt, viewDir) - eyeToPt; - float3 patch_center_realigned = pt + normalize(patch_to_camera_direction_vector) * min(margin, length(patch_to_camera_direction_vector)); - float4 patch_screenspace_center = mul(float4(patch_center_realigned, 1.0), g_WorldViewProjLOD); - - if(((patch_screenspace_center.x/patch_screenspace_center.w > -1.0) && (patch_screenspace_center.x/patch_screenspace_center.w < 1.0) && - (patch_screenspace_center.y/patch_screenspace_center.w > -1.0) && (patch_screenspace_center.y/patch_screenspace_center.w < 1.0) && - (patch_screenspace_center.w>0)) || (length(pt-eyePos) < margin)) - { - return true; - } - - return false; -} - -// The adjacency calculations ensure that neighbours have tessellations that agree. -// However, only power of two sizes *seem* to get correctly tessellated with no cracks. -float SmallerNeighbourAdjacencyClamp(float tess) -{ - // Clamp to the nearest larger power of two. Any power of two works; larger means that we don't lose detail. - // Output is [4,64]. - float logTess = ceil(log2(tess)); - float t = pow(2, logTess); - - // Our smaller neighbour's min tessellation is pow(2,1) = 2. As we are twice its size, we can't go below 4. - return max(4, t); -} - -float LargerNeighbourAdjacencyClamp(float tess) -{ - // Clamp to the nearest larger power of two. Any power of two works; larger means that we don't lose detail. - float logTess = ceil(log2(tess)); - float t = pow(2, logTess); - - // Our larger neighbour's max tessellation is 64; as we are half its size, our tessellation must max out - // at 32, otherwise we could be over-tessellated relative to the neighbour. Output is [2,32]. - return clamp(t, 2,32); -} - -void MakeVertexHeightsAgree(inout float3 p0, inout float3 p1/*, float g_DetailNoiseScale, float g_DetailUVScale*/) -{ - // This ought to work: if the adjacency has repositioned a vertex in XZ, we need to re-acquire its height. - // However, causes an internal fxc error. Again! :-( - //float h0 = SampleHeightForVS(g_CoarseHeightMap, SamplerClampLinear, p0.xz, g_DetailNoiseScale, g_DetailUVScale); - //float h1 = SampleHeightForVS(g_CoarseHeightMap, SamplerClampLinear, p0.xz, g_DetailNoiseScale, g_DetailUVScale); - //p0.y = h0; - //p1.y = h1; - - // Instead set both vertex heights to zero. It's the only way I can think to agree with the neighbours - // when sampling is broken in fxc. - p0.y = p1.y = 0; -} - -float SmallerNeighbourAdjacencyFix(float3 p0, float3 p1, float diameter) -{ - MakeVertexHeightsAgree(p0, p1); - float t = SphereToScreenSpaceTessellation(p0, p1, diameter); - return SmallerNeighbourAdjacencyClamp(t); -} - -float LargerNeighbourAdjacencyFix(float3 p0, float3 p1, int patchIdx, float diameter) -{ - // We move one of the corner vertices in 2D (x,z) to match where the corner vertex is - // on our larger neighbour. We move p0 or p1 depending on the even/odd patch index. - // - // Larger neighbour - // +-------------------+ - // +---------+ - // p0 Us p1 ----> + Move p1 - // | 0 | 1 | patchIdx % 2 - // - // +---------+ - // + <---- p0 Us p1 Move p0 - // | 0 | 1 | patchIdx % 2 - // - if (patchIdx % 2) - p0 += (p0 - p1); - else - p1 += (p1 - p0); - - // Having moved the vertex in (x,z), its height is no longer correct. - MakeVertexHeightsAgree(p0, p1); - - // Half the tessellation because the edge is twice as long. - float t = 0.5 * SphereToScreenSpaceTessellation(p0, p1, 2*diameter); - return LargerNeighbourAdjacencyClamp(t); -} - -// This constant hull shader is executed once per patch. -HS_CONSTANT_DATA_OUTPUT TerrainScreenspaceLODConstantsHS(InputPatch ip, - uint PatchID : SV_PrimitiveID) -{ - HS_CONSTANT_DATA_OUTPUT Output = (HS_CONSTANT_DATA_OUTPUT) 0; - - const float3 centre = 0.25 * (ip[0].vPosition + ip[1].vPosition + ip[2].vPosition + ip[3].vPosition); - const float sideLen = max(abs(ip[1].vPosition.x - ip[0].vPosition.x), abs(ip[1].vPosition.x - ip[2].vPosition.x)); // assume square & uniform - const float diagLen = sqrt(2*sideLen*sideLen); - - //Output.g_DetailNoiseScale = ip[0].g_DetailNoiseScale; - //Output.g_DetailUVScale = ip[0].g_DetailUVScale; - /*Output.g_FractalOctaves = ip[0].g_FractalOctaves; */ - //Output.g_TextureWorldOffset = ip[0].g_TextureWorldOffset; - - if (!inFrustum(centre, g_EyePos / WORLD_SCALE, g_ViewDir, diagLen)) - { - Output.Inside[0] = Output.Inside[1] = -1; - Output.Edges[0] = Output.Edges[1] = Output.Edges[2] = Output.Edges[3] = -1; - } - else - { - // Alternative implementation left here for instruction purposes: - // Examining displaced patch corners completely fails for patches that are seen edge-on where the patch has - // significant interior displacement. In screenspace, two patch dimensions are ~= 0. However, once displaced - // in the DS the screenspace size is significantly > 0. I think this edge-based version simply doesn't work - // well unless you have a good estimate of the max interior displacement (needs a max displacement per patch). - //Output.Edges[0] = EdgeToScreenSpaceTessellation(ip[0].vPosition, ip[1].vPosition); - //Output.Edges[3] = EdgeToScreenSpaceTessellation(ip[1].vPosition, ip[2].vPosition); - //Output.Edges[2] = EdgeToScreenSpaceTessellation(ip[2].vPosition, ip[3].vPosition); - //Output.Edges[1] = EdgeToScreenSpaceTessellation(ip[3].vPosition, ip[0].vPosition); - - // Alternatively: project a sphere centered on the patch edge mid-point (not patch bounding sphere - that - // wouldn't work with adjacency fixes, etc). This is independent of patch orientation and doesn't suffer - // from edges getting projected to zero size. The flip side is that it over-tessellates flat, boring areas - // and uses more polygons overall. - Output.Edges[0] = SphereToScreenSpaceTessellation(ip[0].vPosition, ip[1].vPosition, sideLen); - Output.Edges[3] = SphereToScreenSpaceTessellation(ip[1].vPosition, ip[2].vPosition, sideLen); - Output.Edges[2] = SphereToScreenSpaceTessellation(ip[2].vPosition, ip[3].vPosition, sideLen); - Output.Edges[1] = SphereToScreenSpaceTessellation(ip[3].vPosition, ip[0].vPosition, sideLen); - - // Edges that need adjacency adjustment are identified by the per-instance ip[0].adjacency - // scalars, in *conjunction* with a patch ID that puts them on the edge of a tile. - int2 patchXY; - patchXY.y = PatchID / PATCHES_PER_TILE_EDGE; - patchXY.x = PatchID - patchXY.y * PATCHES_PER_TILE_EDGE; - - // Identify patch edges that are adjacent to a patch of a different size. The size difference - // is encoded in ip[n].adjacency, either 0.5, 1.0 or 2.0. - // neighbourMinusX refers to our adjacent neighbour in the direction of -ve x. The value - // is the neighbour's size relative to ours. Similarly for plus and Y, etc. You really - // need a diagram to make sense of the adjacency conditions in the if statements. :-( - // These four ifs deal with neighbours that are smaller. - if (ip[0].adjacency.neighbourMinusX < 0.55 && patchXY.x == 0) - Output.Edges[0] = SmallerNeighbourAdjacencyFix(ip[0].vPosition, ip[1].vPosition, sideLen); - if (ip[0].adjacency.neighbourMinusY < 0.55 && patchXY.y == 0) - Output.Edges[1] = SmallerNeighbourAdjacencyFix(ip[3].vPosition, ip[0].vPosition, sideLen); - if (ip[0].adjacency.neighbourPlusX < 0.55 && patchXY.x == PATCHES_PER_TILE_EDGE-1) - Output.Edges[2] = SmallerNeighbourAdjacencyFix(ip[2].vPosition, ip[3].vPosition, sideLen); - if (ip[0].adjacency.neighbourPlusY < 0.55 && patchXY.y == PATCHES_PER_TILE_EDGE-1) - Output.Edges[3] = SmallerNeighbourAdjacencyFix(ip[1].vPosition, ip[2].vPosition, sideLen); - - // Deal with neighbours that are larger than us. - if (ip[0].adjacency.neighbourMinusX > 1 && patchXY.x == 0) - Output.Edges[0] = LargerNeighbourAdjacencyFix(ip[0].vPosition, ip[1].vPosition, patchXY.y, sideLen); - if (ip[0].adjacency.neighbourMinusY > 1 && patchXY.y == 0) - Output.Edges[1] = LargerNeighbourAdjacencyFix(ip[0].vPosition, ip[3].vPosition, patchXY.x, sideLen); // NB: irregular index pattern - it's correct. - if (ip[0].adjacency.neighbourPlusX > 1 && patchXY.x == PATCHES_PER_TILE_EDGE-1) - Output.Edges[2] = LargerNeighbourAdjacencyFix(ip[3].vPosition, ip[2].vPosition, patchXY.y, sideLen); - if (ip[0].adjacency.neighbourPlusY > 1 && patchXY.y == PATCHES_PER_TILE_EDGE-1) - Output.Edges[3] = LargerNeighbourAdjacencyFix(ip[1].vPosition, ip[2].vPosition, patchXY.x, sideLen); // NB: irregular index pattern - it's correct. - - // Use average of edge points for interior - visually looks OK. - // fxc bug if we assign different complex expressions to Inside[0] and [1]. - Output.Inside[1] = 0.5 * (Output.Edges[0] + Output.Edges[2]); - Output.Inside[0] = 0.5 * (Output.Edges[1] + Output.Edges[3]); - - Output.vWorldXZ[0] = ip[0].vWorldXZ; - Output.vWorldXZ[1] = ip[1].vWorldXZ; - Output.vWorldXZ[2] = ip[2].vWorldXZ; - Output.vWorldXZ[3] = ip[3].vWorldXZ; - - Output.debugColour[0] = DEBUG_COLOURS[clamp(log2(Output.Edges[0]), 0,5)]; - Output.debugColour[1] = DEBUG_COLOURS[clamp(log2(Output.Edges[1]), 0,5)]; - Output.debugColour[2] = DEBUG_COLOURS[clamp(log2(Output.Edges[2]), 0,5)]; - Output.debugColour[3] = DEBUG_COLOURS[clamp(log2(Output.Edges[3]), 0,5)]; - Output.debugColour[4] = DEBUG_COLOURS[clamp(log2(Output.Inside[0]), 0,5)]; - } - - return Output; -} - -// The hull shader is called once per output control point, which is specified with -// outputcontrolpoints. - -// The input to the hull shader comes from the vertex shader - -// The output from the hull shader will go to the domain shader. -// The tessellation factor, topology, and partition mode will go to the fixed function -// tessellator stage to calculate the UVW and domain points. -[domain("quad")] -[partitioning("fractional_even")] -[outputtopology("triangle_cw")] -[outputcontrolpoints(4)] -[patchconstantfunc("TerrainScreenspaceLODConstantsHS")] -HS_OUTPUT TerrainScreenspaceLODHS(InputPatch p, uint i : SV_OutputControlPointID) -{ - // The VS displaces y for LOD calculations. We drop it here so as not to displace twice in the DS. - HS_OUTPUT Output; - Output.vPosition = float3(p[i].vPosition.x, 0, p[i].vPosition.z); - return Output; -} - -float3 bilerpColour(float3 c0, float3 c1, float3 c2, float3 c3, float2 UV) -{ - float3 left = lerp(c0, c1, UV.y); - float3 right = lerp(c2, c3, UV.y); - float3 result = lerp(left, right, UV.x); - return result; -} - -float3 lerpDebugColours(float3 cIn[5], float2 uv) -{ - if (uv.x < 0.5 && uv.y < 0.5) - return bilerpColour(0.5* (cIn[0] + cIn[1]), cIn[0], cIn[1], cIn[4], 2 * uv); - else if (uv.x < 0.5 && uv.y >= 0.5) - return bilerpColour(cIn[0], 0.5* (cIn[0] + cIn[3]), cIn[4], cIn[3], 2 * (uv-float2(0,0.5))); - else if (uv.x >= 0.5 && uv.y < 0.5) - return bilerpColour(cIn[1], cIn[4], 0.5* (cIn[2] + cIn[1]), cIn[2], 2 * (uv-float2(0.5,0))); - else // x >= 0.5 && y >= 0.5 - return bilerpColour(cIn[4], cIn[3], cIn[2], 0.5* (cIn[2] + cIn[3]), 2 * (uv-float2(0.5,0.5))); -} - -// Templates please!!! -float2 Bilerp(float2 v0, float2 v1, float2 v2, float2 v3, float2 i) -{ - float2 bottom = lerp(v0, v3, i.x); - float2 top = lerp(v1, v2, i.x); - float2 result = lerp(bottom, top, i.y); - return result; -} - -float3 Bilerp(float3 v0, float3 v1, float3 v2, float3 v3, float2 i) -{ - float3 bottom = lerp(v0, v3, i.x); - float3 top = lerp(v1, v2, i.x); - float3 result = lerp(bottom, top, i.y); - return result; -} - -float3 TessellatedWorldPos(HS_CONSTANT_DATA_OUTPUT input, - float2 UV : SV_DomainLocation, - const OutputPatch terrainQuad, - float g_DetailNoiseScale, - float2 g_DetailUVScale, - float g_fDisplacementHeight - /*, int3 g_FractalOctaves*/ - , float3 g_TextureWorldOffset - ) -{ - // bilerp the position - float3 worldPos = Bilerp(terrainQuad[0].vPosition, terrainQuad[1].vPosition, terrainQuad[2].vPosition, terrainQuad[3].vPosition, UV); - - const int mipLevel = 0; - - float height = SampleHeightForVS(g_CoarseHeightMap, SamplerClampLinear, worldPos.xz, g_DetailNoiseScale, g_DetailUVScale/*, g_FractalOctaves*/, g_TextureWorldOffset); - worldPos.y += g_fDisplacementHeight * height; - - return worldPos; -} - -// The domain shader is run once per vertex and calculates the final vertex's position -// and attributes. It receives the UVW from the fixed function tessellator and the -// control point outputs from the hull shader. Since we are using the DirectX 11 -// Tessellation pipeline, it is the domain shader's responsibility to calculate the -// final SV_POSITION for each vertex. - -// The input SV_DomainLocation to the domain shader comes from fixed function -// tessellator. And the OutputPatch comes from the hull shader. From these, you -// must calculate the final vertex position, color, texcoords, and other attributes. - -// The output from the domain shader will be a vertex that will go to the video card's -// rasterization pipeline and get drawn to the screen. -[domain("quad")] -MeshVertex TerrainDisplaceDS( HS_CONSTANT_DATA_OUTPUT input, - float2 UV : SV_DomainLocation, - const OutputPatch terrainQuad, - uint PatchID : SV_PrimitiveID, - uniform int g_DebugShowPatches, - uniform float g_fDisplacementHeight) -{ - MeshVertex Output = (MeshVertex) 0; - - const float3 worldPos = TessellatedWorldPos(input, UV, terrainQuad, g_DetailNoiseScale, g_DetailUVScale, g_fDisplacementHeight/*, g_FractalOctaves*/, g_TextureWorldOffset); - Output.vPosition = mul(float4(worldPos.xyz,1), g_WorldViewProj); - Output.debugColour = lerpDebugColours(input.debugColour, UV); - Output.vWorldXZ = worldPos.xz; - Output.vNormal = float3(1,1,1); - //Output.g_DebugShowPatches = g_DebugShowPatches; - //Output.g_DetailNoiseScale = input.g_DetailNoiseScale; - //Output.g_fDisplacementHeight = g_fDisplacementHeight; - //Output.g_DetailUVScale = input.g_DetailUVScale; - //Output.g_TextureWorldOffset = input.g_TextureWorldOffset; - - // For debugging, darken a chequer board pattern of tiles to highlight tile boundaries. - if (g_DebugShowPatches) - { - const uint patchY = PatchID / PATCHES_PER_TILE_EDGE; - const uint patchX = PatchID - patchY * PATCHES_PER_TILE_EDGE; - Output.vNormal *= (0.5 * ((patchX + patchY) % 2) + 0.5); - } - - return Output; -} - - -//-------------------------------------------------------------------------------------- -// Smooth shading pixel shader section -//-------------------------------------------------------------------------------------- -Texture2D g_TerrainColourTexture1; -Texture2D g_TerrainColourTexture2; - -float HighContrast(float i) -{ - //return 1.3 * (i-0.1); - //return 1.9 * (i-0.2); // higher - return i; -} - -float3 SampleDetailNormal(float2 worldXZ, float g_DetailNoiseScale, float2 g_DetailUVScale, float g_CoarseSampleSpacing) -{ - // The detail displacement is scaled by the coarse displacement's height. So we need - // to fetch the height to scale the normal. (The scale computation could perhaps be - // moved up to the DS.) - const float2 uv = worldXZtoHeightUV(worldXZ); - float coarse = g_CoarseHeightMap.Sample(SamplerClampLinear, uv).r; - - const float vScale = saturate(coarse) * WORLD_SCALE * VERTICAL_SCALE; - - // The MIP-mapping doesn't seem to work very well. Maybe I need to think more carefully about - // anti-aliasing the normal function? - float2 grad = SampleDetailGradOctaves(uv, g_DetailNoiseScale, g_DetailUVScale,g_TextureWorldOffset); - return normalize(float3(-vScale * grad.x, g_CoarseSampleSpacing * WORLD_UV_REPEATS_RECIP * g_DetailUVScale.y, vScale * grad.y)); -} - -float DebugCracksPattern(MeshVertex input) -{ - // Dark grey and black - to better show any cracks. - if (g_DebugShowPatches) - return 0.1 * (input.vNormal.x - 0.5); - else - return 0; -} - -float4 SmoothShadePS(MeshVertex input, - uniform float g_CoarseSampleSpacing) : SV_Target -{ - //return DebugCracksPattern(input); - - // Not sure about the arbitrary 2x. It looks right visually. Maybe there's a constant somewhere in - // the texture sizes that I overlooked?!? - const float ARBITRARY_FUDGE = 2; - const float2 grad = g_CoarseGradientMap.Sample(SamplerRepeatLinear, worldXZtoHeightUV(input.vWorldXZ)).rg; - const float vScale = ARBITRARY_FUDGE * g_fDisplacementHeight * WORLD_SCALE * VERTICAL_SCALE; - const float3 coarseNormal = normalize(float3(vScale * grad.x, g_CoarseSampleSpacing, -vScale * grad.y)); - const float3 detailNormal = SampleDetailNormal(input.vWorldXZ, g_DetailNoiseScale,g_DetailUVScale,g_CoarseSampleSpacing); - const float3 normal = normalize(coarseNormal + detailNormal); - - // Texture coords have to be offset by the eye's 2D world position. Why the 2x??? - const float2 texUV = input.vWorldXZ + 2 * float2(g_TextureWorldOffset.x, -g_TextureWorldOffset.z);; - - // We apply two textures at vastly different scales: macro and micro detail. - float3 macroDetail = g_TerrainColourTexture1.Sample(SamplerRepeatMaxAniso, texUV).xyz; // we know that this is grey only - float4 microDetail = g_TerrainColourTexture2.Sample(SamplerRepeatMedAniso, texUV * 50); - float gaussian = g_NoiseTexture.Sample(SamplerRepeatPoint, texUV * 50.0 / 256.0).x; - float uniformRandom = frac(gaussian * 10); - float randomizedDetail = 1; - - // Randomly choose between four versions of the micro texture in RGBA. This sort of - // blending is representative of game-engine terrain shaders (and the perf). - if (uniformRandom >= 0.75) - randomizedDetail = microDetail.x; - else if (uniformRandom >= 0.5) - randomizedDetail = microDetail.y; - else if (uniformRandom >= 0.25) - randomizedDetail = microDetail.z; - else - randomizedDetail = microDetail.w; - - // Some of the lunar reference photos have a brownish tint. IMO, it looks slightly better here. - const float3 colour = float3(0.988, 0.925, 0.847); - - // This light direction approximately matches the pre-baked direction in the NASA photos. - const float3 lightDir = normalize(float3(-0.74,0.45,-0.15)); - float lit = saturate(HighContrast(dot(lightDir, normal))); - - // Chequer pattern still comes down from the DS. - if (g_DebugShowPatches) - lit *= input.vNormal.x; - - //return lit; - return float4(colour * macroDetail * randomizedDetail * lit, 1); -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL/TerrainTessellationCommon.hlsl b/Samples/Media/materials/programs/HLSL/TerrainTessellationCommon.hlsl deleted file mode 100644 index 07f89a3ba7e..00000000000 --- a/Samples/Media/materials/programs/HLSL/TerrainTessellationCommon.hlsl +++ /dev/null @@ -1,86 +0,0 @@ -/* ----------------------------------------------------------- -Terrain Tessellation sample from NVIDIA's DirectX 11 SDK: -http://developer.nvidia.com/nvidia-graphics-sdk-11-direct3d ----------------------------------------------------------- -*/ - -#ifndef INCLUDED_COMMON_HLSL -#define INCLUDED_COMMON_HLSL - -static const int CONTROL_VTX_PER_TILE_EDGE = 9; -static const int PATCHES_PER_TILE_EDGE = 8; -static const float RECIP_CONTROL_VTX_PER_TILE_EDGE = 1.0 / 9; -static const float WORLD_SCALE = 400; -static const float VERTICAL_SCALE = 0.65; -static const float WORLD_UV_REPEATS = 8; // How many UV repeats across the world for fractal generation. -static const float WORLD_UV_REPEATS_RECIP = 1.0 / WORLD_UV_REPEATS; - -//int3 g_FractalOctaves; // ridge, fBm, uv twist -//float3 g_TextureWorldOffset; // Offset of fractal terrain in texture space. -//float g_CoarseSampleSpacing; // World space distance between samples in the coarse height map. - -struct Adjacency -{ - // These are the size of the neighbours along +/- x or y axes. For interior tiles - // this is 1. For edge tiles it is 0.5 or 2.0. - float neighbourMinusX : ADJACENCY_SIZES0; - float neighbourMinusY : ADJACENCY_SIZES1; - float neighbourPlusX : ADJACENCY_SIZES2; - float neighbourPlusY : ADJACENCY_SIZES3; -}; - -struct AppVertexTessellation -{ - float2 position : POSITION_2D; - Adjacency adjacency; - uint VertexId : SV_VertexID; - uint InstanceId : SV_InstanceID; -}; - -struct AppVertex -{ - float2 position : POSITION_2D; - Adjacency adjacency; - uint VertexId : SV_VertexID; - uint InstanceId : SV_InstanceID; -}; - -SamplerState SamplerRepeatMaxAniso -{ - Filter = ANISOTROPIC; - MaxAnisotropy = 16; - AddressU = Wrap; - AddressV = Wrap; -}; - -SamplerState SamplerRepeatMedAniso -{ - Filter = ANISOTROPIC; - MaxAnisotropy = 4; - AddressU = Wrap; - AddressV = Wrap; -}; - -SamplerState SamplerRepeatLinear -{ - Filter = MIN_MAG_MIP_LINEAR; - AddressU = Wrap; - AddressV = Wrap; -}; - -SamplerState SamplerClampLinear -{ - Filter = MIN_MAG_MIP_LINEAR; - AddressU = Clamp; - AddressV = Clamp; -}; - -SamplerState SamplerRepeatPoint -{ - Filter = MIN_MAG_MIP_POINT; - AddressU = Wrap; - AddressV = Wrap; -}; - -#endif diff --git a/Samples/Media/materials/programs/HLSL/TerrainTessellationDeformation.hlsl b/Samples/Media/materials/programs/HLSL/TerrainTessellationDeformation.hlsl deleted file mode 100644 index 265de3637e5..00000000000 --- a/Samples/Media/materials/programs/HLSL/TerrainTessellationDeformation.hlsl +++ /dev/null @@ -1,106 +0,0 @@ -/* ----------------------------------------------------------- -Terrain Tessellation sample from NVIDIA's DirectX 11 SDK: -http://developer.nvidia.com/nvidia-graphics-sdk-11-direct3d ----------------------------------------------------------- -*/ - -#include "TerrainTessellationCommon.hlsl" -#include "TerrainTessellationINoise.hlsl" - -// z in both cases is the height scale. - -// Null in that there is no associated VB set by the API. -struct NullVertex -{ - uint VertexId : SV_VertexID; - uint InstanceId : SV_InstanceID; -}; - -struct DeformVertex -{ - float4 pos : SV_Position; - float2 texCoord : TEXCOORD1; -}; - -DeformVertex InitializationVS( NullVertex input, - uniform float3 g_DeformMin, - uniform float3 g_DeformMax) -{ - DeformVertex output = (DeformVertex) 0; - - if (input.VertexId == 0) - { - output.pos = float4(g_DeformMin.x, g_DeformMin.y, 0, 1); - output.texCoord = float2(0,0); - } - else if (input.VertexId == 1) - { - output.pos = float4(g_DeformMax.x, g_DeformMin.y, 0, 1); - output.texCoord = float2(1,0); - } - else if (input.VertexId == 2) - { - output.pos = float4(g_DeformMin.x, g_DeformMax.y, 0, 1); - output.texCoord = float2(0,1); - } - else if (input.VertexId == 3) - { - output.pos = float4(g_DeformMax.x, g_DeformMax.y, 0, 1); - output.texCoord = float2(1,1); - } - - return output; -} - -float3 debugCubes(float2 uv) -{ - const float HORIZ_SCALE = 4, VERT_SCALE = 1; - uv *= HORIZ_SCALE; - return VERT_SCALE * floor(fmod(uv.x, 2.0)) * floor(fmod(uv.y, 2.0)); -} - -float3 debugXRamps(float2 uv) -{ - const float HORIZ_SCALE = 2, VERT_SCALE = 1; - uv *= HORIZ_SCALE; - return VERT_SCALE * frac(uv.x); -} - -float3 debugSineHills(float2 uv) -{ - const float HORIZ_SCALE = 2 * 3.14159, VERT_SCALE = 0.5; - uv *= HORIZ_SCALE; - //uv += 2.8; // arbitrarily not centered - test asymetric fns. - return VERT_SCALE * (sin(uv.x) + 1) * (sin(uv.y) + 1); -} - -float3 debugFlat(float2 uv) -{ - const float VERT_SCALE = 0.1; - return VERT_SCALE; -} - -float4 InitializationPS( DeformVertex input, - uniform int3 g_FractalOctaves, - uniform float3 g_TextureWorldOffset ) : SV_Target -{ - const float2 uv = g_TextureWorldOffset.xz + WORLD_UV_REPEATS * input.texCoord; - //return float4(debugXRamps(uv), 1); - //return float4(debugFlat(uv), 1); - //return float4(debugSineHills(uv), 1); - //return float4(debugCubes(uv), 1); - return hybridTerrain(uv, g_FractalOctaves); -} - -Texture2D g_InputTexture; - -float4 GradientPS( DeformVertex input ) : SV_Target -{ - input.texCoord.y = 1 - input.texCoord.y; - float x0 = g_InputTexture.Sample(SamplerClampLinear, input.texCoord, int2( 1,0)).x; - float x1 = g_InputTexture.Sample(SamplerClampLinear, input.texCoord, int2(-1,0)).x; - float y0 = g_InputTexture.Sample(SamplerClampLinear, input.texCoord, int2(0, 1)).x; - float y1 = g_InputTexture.Sample(SamplerClampLinear, input.texCoord, int2(0,-1)).x; - return float4(x0-x1, y0-y1, 0,0); -} diff --git a/Samples/Media/materials/programs/HLSL/TerrainTessellationINoise.hlsl b/Samples/Media/materials/programs/HLSL/TerrainTessellationINoise.hlsl deleted file mode 100644 index d354abcf43f..00000000000 --- a/Samples/Media/materials/programs/HLSL/TerrainTessellationINoise.hlsl +++ /dev/null @@ -1,126 +0,0 @@ -/* ----------------------------------------------------------- -Terrain Tessellation sample from NVIDIA's DirectX 11 SDK: -http://developer.nvidia.com/nvidia-graphics-sdk-11-direct3d ----------------------------------------------------------- -*/ - -#include "TerrainTessellationCommon.hlsl" - -float2 fade(float2 t) -{ - return t * t * t * (t * (t * 6 - 15) + 10); // new curve (quintic) -} - -Texture2D g_NoiseTexture; - -#define FIXED_FN_INTERPOLATION 0 -#if FIXED_FN_INTERPOLATION -// just use normal 2D texture lookup -// note - artifacts are visible at low frequencies due to interpolation precision -float inoise(float2 p) -{ - const float mipLevel = 0; - return 2 * (g_NoiseTexture.SampleLevel(SamplerRepeatLinear, p, mipLevel).x - 0.5); // [-1,1] -} - -#else - -// interpolate 2D texture -float inoise(float2 p) -{ - float2 i = floor(p*256); - float2 f = 256*p - i; - f = fade(f); - i /= 256; - - const float mipLevel = 0; - float4 n; - n.x = g_NoiseTexture.SampleLevel(SamplerRepeatPoint, i, mipLevel).x; - n.y = g_NoiseTexture.SampleLevel(SamplerRepeatPoint, i, mipLevel, int2(1,0)).x; - n.z = g_NoiseTexture.SampleLevel(SamplerRepeatPoint, i, mipLevel, int2(0,1)).x; - n.w = g_NoiseTexture.SampleLevel(SamplerRepeatPoint, i, mipLevel, int2(1,1)).x; - const float interpolated = lerp(lerp( n.x, n.y, f.x), - lerp( n.z, n.w, f.x), f.y); // [0,1] - return 2.0 * interpolated - 1.0; -} -#endif // FIXED_FN_INTERPOLATION - -// calculate gradient of noise (expensive!) -float2 inoiseGradient(float2 p, float d) -{ - float f0 = inoise(p); - float fx = inoise(p + float2(d, 0)); - float fy = inoise(p + float2(0, d)); - return float2(fx - f0, fy - f0) / d; -} - -// fractal sum -float fBm(float2 p, int octaves, float lacunarity = 2.0, float gain = 0.5) -{ - float freq = 1.0, amp = 1.0; - float sum = 0; - for(int i=0; i 0) - return h + f*saturate(h); - else - return f; -} diff --git a/Samples/Media/materials/programs/HLSL/Tessellation.hlsl b/Samples/Media/materials/programs/HLSL/Tessellation.hlsl deleted file mode 100644 index b1a9303c984..00000000000 --- a/Samples/Media/materials/programs/HLSL/Tessellation.hlsl +++ /dev/null @@ -1,119 +0,0 @@ -// Sample of DirectX11 Tessellation Tutorial from www.xtunt.com - -// This allows us to compile the shader with a #define to choose -// the different partition modes for the hull shader. - -// See the hull shader: [partitioning(BEZIER_HS_PARTITION)] -// This sample demonstrates "integer", "fractional_even", and "fractional_odd" - -#ifndef HS_PARTITION -#define HS_PARTITION "integer" -#endif - -#define INPUT_PATCH_SIZE 3 -#define OUTPUT_PATCH_SIZE 3 - -// Constant Buffers -cbuffer cbPerFrame : register( b0 ) -{ - matrix g_mViewProjection; - float g_fTessellationFactor; -}; - -// Vertex shader -struct VS_CONTROL_POINT_INPUT -{ - float3 vPosition : POSITION; -}; - -struct VS_CONTROL_POINT_OUTPUT -{ - float3 vPosition : POSITION; -}; - -//Just a pass-through shader -VS_CONTROL_POINT_OUTPUT VS( VS_CONTROL_POINT_INPUT Input ) -{ - VS_CONTROL_POINT_OUTPUT Output; - - Output.vPosition = Input.vPosition; - - return Output; -} - -// Constant data function for the HS. This is executed once per patch. -struct HS_CONSTANT_DATA_OUTPUT -{ - float Edges[3] : SV_TessFactor; - float Inside : SV_InsideTessFactor; -}; - -struct HS_OUTPUT -{ - float3 vPosition : POSITION; -}; - -HS_CONSTANT_DATA_OUTPUT ConstantHS( InputPatch ip, - uint PatchID : SV_PrimitiveID ) -{ - HS_CONSTANT_DATA_OUTPUT Output; - - Output.Edges[0] = Output.Edges[1] = Output.Edges[2] = g_fTessellationFactor; - Output.Inside = g_fTessellationFactor; - - return Output; -} - -// The input to the hull shader comes from the vertex shader - -// The output from the hull shader will go to the domain shader. -// The tessellation factor, topology, and partition mode will go to the fixed function -// tessellator stage to calculate the UVW and domain points. - -[domain("tri")] //Triangle domain for our shader -[partitioning(HS_PARTITION)] //Partitioning type according to the GUI -[outputtopology("triangle_cw")] //Where the generated triangles should face -[outputcontrolpoints(3)] //Number of times this part of the hull shader will be called for each patch -[patchconstantfunc("ConstantHS")] //The constant hull shader function -HS_OUTPUT HS( InputPatch p, - uint i : SV_OutputControlPointID, - uint PatchID : SV_PrimitiveID ) -{ - HS_OUTPUT Output; - Output.vPosition = p[i].vPosition; - return Output; -} - -// Evaluation domain shader section -struct DS_OUTPUT -{ - float4 vPosition : SV_POSITION; -}; - -//Domain Shader is invoked for each vertex created by the Tessellator -[domain("tri")] -DS_OUTPUT DS( HS_CONSTANT_DATA_OUTPUT input, - float3 UVW : SV_DomainLocation, - const OutputPatch quad ) -{ - DS_OUTPUT Output; - - //baricentric interpolation - float3 finalPos = UVW.x * quad[0].vPosition + UVW.y * quad[1].vPosition + UVW.z * quad[2].vPosition; - - Output.vPosition = mul( float4(finalPos,1), g_mViewProjection ); - - return Output; -} - -// Pixel shader section -float4 PS( DS_OUTPUT Input ) : SV_TARGET -{ - return float4(1, 0, 0, 1); -} - -// Pixel shader (used for wireframe overlay) -float4 SolidColorPS( DS_OUTPUT Input ) : SV_TARGET -{ - return float4( 1,1,1, 1 ); -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL/adaptivePNTriangles_tessellation.hlsl b/Samples/Media/materials/programs/HLSL/adaptivePNTriangles_tessellation.hlsl deleted file mode 100644 index 599e12cc9b1..00000000000 --- a/Samples/Media/materials/programs/HLSL/adaptivePNTriangles_tessellation.hlsl +++ /dev/null @@ -1,331 +0,0 @@ -///////////// -// GLOBALS // -///////////// - -cbuffer TessellationBuffer -{ - float4 tessellationAmounts; //Tessellation factors: x=edge, y=inside, z=MinDistance, w=range - float4 cameraPosition; -}; - -cbuffer MatrixBuffer -{ - matrix worldviewprojMatrix; - matrix worldMatrix; - matrix viewMatrix; - matrix projectionMatrix; - //float4 cameraPosition; - float fDisplacementScale; -}; - -////////////// -// TYPEDEFS // -////////////// -struct VertexInputType -{ - float3 position : POSITION; - float3 normal : NORMAL; - float2 texCoord : TEXCOORD0; -}; - -struct HullInputType -{ - float3 position : POSITION; - float2 texCoord : TEXCOORD0; - float3 normal : TEXCOORD1; -}; - -//The ConstantOutputType structure is what will be the output from the patch constant function. -struct ConstantOutputType -{ - float edges[3] : SV_TessFactor; - float inside : SV_InsideTessFactor; - - // Geometry cubic generated control points - float3 f3B210 : POSITION3; - float3 f3B120 : POSITION4; - float3 f3B021 : POSITION5; - float3 f3B012 : POSITION6; - float3 f3B102 : POSITION7; - float3 f3B201 : POSITION8; - float3 f3B111 : CENTER; - - // Normal quadratic generated control points - float3 f3N110 : NORMAL3; - float3 f3N011 : NORMAL4; - float3 f3N101 : NORMAL5; -}; - -//The HullOutputType structure is what will be the output from the hull shader. -struct HullOutputType -{ - float3 position : POSITION; - float2 texCoord : TEXCOORD0; - float3 normal : TEXCOORD1; -}; - -//The output of the domain shader goes to the pixel shader. This was previously in the vertex shader. -struct PixelInputType -{ - float4 position : SV_POSITION; - float2 texCoord : TEXCOORD0; - float3 normal : TEXCOORD1; -}; - -cbuffer LightBuffer -{ - float4 lightAmbientColor; - float4 lightDiffuseColor; - float4 lightSpecularColor; - float3 lightDirection; - float4 lightPosition; - float4 lightAttenuation; - float4 surfaceDiffuseColour; - float4 surfaceSpecularColour; - float surfaceShininess; -// float3 cameraPosition; -}; - -//////////////////////////////////////////////////////////////////////////////// -// Vertex Shader -//////////////////////////////////////////////////////////////////////////////// -HullInputType color_tessellation_vs(VertexInputType input) -{ - HullInputType output; - - // Pass the vertex position into the hull shader. - output.position = input.position; - output.normal = normalize( mul(input.normal, (float3x3)worldMatrix ) ); - output.texCoord = input.texCoord; - - return output; -} - -//-------------------------------------------------------------------------------------- -// Returns a distance adaptive tessellation scale factor (0.0f -> 1.0f) -//-------------------------------------------------------------------------------------- -float GetDistanceAdaptiveScaleFactor( - float3 f3Eye, // Position of the camera/eye - float3 f3EdgePosition0, // Position of the first control point of the given patch edge - float3 f3EdgePosition1, // Position of the second control point of the given patch edge - float fMinDistance, // Minimum distance that maximum tessellation factors should be applied at - float fRange // Range beyond the minimum distance where tessellation will scale down to the minimum scaling factor - ) -{ - float3 f3MidPoint = ( f3EdgePosition0 + f3EdgePosition1 ) * 0.5f; - - float fDistance = distance( f3MidPoint, f3Eye ) - fMinDistance; - - float fScale = 1.0f - saturate( fDistance / fRange ); - - return fScale; -} - -//////////////////////////////////////////////////////////////////////////////// -// Patch Constant Function -//////////////////////////////////////////////////////////////////////////////// -ConstantOutputType ColorPatchConstantFunction(InputPatch inputPatch, uint patchId : SV_PrimitiveID) -{ - ConstantOutputType output; - float adaptativeScaleFactor; - - // Set the tessellation factors for the three edges of the triangle. - /*output.edges[0] = tessellationAmounts.x; - output.edges[1] = tessellationAmounts.x; - output.edges[2] = tessellationAmounts.x;*/ - - output.edges[0] = output.edges[1] = output.edges[2] = tessellationAmounts.x; - - adaptativeScaleFactor = GetDistanceAdaptiveScaleFactor( cameraPosition.xyz, inputPatch[2].position, inputPatch[0].position, tessellationAmounts.z, tessellationAmounts.w ); - output.edges[0] = lerp( 1.0f, output.edges[0], adaptativeScaleFactor); - - adaptativeScaleFactor = GetDistanceAdaptiveScaleFactor( cameraPosition.xyz, inputPatch[0].position, inputPatch[1].position, tessellationAmounts.z, tessellationAmounts.w ); - output.edges[1] = lerp( 1.0f, output.edges[1], adaptativeScaleFactor); - - adaptativeScaleFactor = GetDistanceAdaptiveScaleFactor( cameraPosition.xyz, inputPatch[1].position, inputPatch[2].position, tessellationAmounts.z, tessellationAmounts.w ); - output.edges[2] = lerp( 1.0f, output.edges[2], adaptativeScaleFactor); - - - // Now setup the PNTriangle control points... - // Assign Positions - float3 f3B003 = inputPatch[0].position; - float3 f3B030 = inputPatch[1].position; - float3 f3B300 = inputPatch[2].position; - // And Normals - float3 f3N002 = inputPatch[0].normal; - float3 f3N020 = inputPatch[1].normal; - float3 f3N200 = inputPatch[2].normal; - - // Compute the cubic geometry control points - // Edge control points - output.f3B210 = ( ( 2.0f * f3B003 ) + f3B030 - ( dot( ( f3B030 - f3B003 ), f3N002 ) * f3N002 ) ) / 3.0f; - output.f3B120 = ( ( 2.0f * f3B030 ) + f3B003 - ( dot( ( f3B003 - f3B030 ), f3N020 ) * f3N020 ) ) / 3.0f; - output.f3B021 = ( ( 2.0f * f3B030 ) + f3B300 - ( dot( ( f3B300 - f3B030 ), f3N020 ) * f3N020 ) ) / 3.0f; - output.f3B012 = ( ( 2.0f * f3B300 ) + f3B030 - ( dot( ( f3B030 - f3B300 ), f3N200 ) * f3N200 ) ) / 3.0f; - output.f3B102 = ( ( 2.0f * f3B300 ) + f3B003 - ( dot( ( f3B003 - f3B300 ), f3N200 ) * f3N200 ) ) / 3.0f; - output.f3B201 = ( ( 2.0f * f3B003 ) + f3B300 - ( dot( ( f3B300 - f3B003 ), f3N002 ) * f3N002 ) ) / 3.0f; - - // Center control point - float3 f3E = ( output.f3B210 + output.f3B120 + output.f3B021 + output.f3B012 + output.f3B102 + output.f3B201 ) / 6.0f; - float3 f3V = ( f3B003 + f3B030 + f3B300 ) / 3.0f; - output.f3B111 = f3E + ( ( f3E - f3V ) / 2.0f ); - - // Compute the quadratic normal control points, and rotate into world space - float fV12 = 2.0f * dot( f3B030 - f3B003, f3N002 + f3N020 ) / dot( f3B030 - f3B003, f3B030 - f3B003 ); - output.f3N110 = normalize( f3N002 + f3N020 - fV12 * ( f3B030 - f3B003 ) ); - float fV23 = 2.0f * dot( f3B300 - f3B030, f3N020 + f3N200 ) / dot( f3B300 - f3B030, f3B300 - f3B030 ); - output.f3N011 = normalize( f3N020 + f3N200 - fV23 * ( f3B300 - f3B030 ) ); - float fV31 = 2.0f * dot( f3B003 - f3B300, f3N200 + f3N002 ) / dot( f3B003 - f3B300, f3B003 - f3B300 ); - output.f3N101 = normalize( f3N200 + f3N002 - fV31 * ( f3B003 - f3B300 ) ); - - // Set the tessellation factor for tessallating inside the triangle. - output.inside = (output.edges[0] + output.edges[1] + output.edges[2]) / 3.0f; - - return output; -} - -//The inputs to the domain shader are the outputs from the hull shader and constant function. -//////////////////////////////////////////////////////////////////////////////// -// Hull Shader -//////////////////////////////////////////////////////////////////////////////// -[domain("tri")] -[partitioning("integer")] -[outputtopology("triangle_cw")] -[outputcontrolpoints(3)] -[patchconstantfunc("ColorPatchConstantFunction")] -HullOutputType color_tessellation_hs(InputPatch patch, uint pointId : SV_OutputControlPointID, uint patchId : SV_PrimitiveID) -{ - HullOutputType output; - - // Set the position for this control point as the output position. - output.position = patch[pointId].position; - output.normal = patch[pointId].normal; - output.texCoord = patch[pointId].texCoord; - - return output; -} - -//The inputs to the domain shader are the outputs from the hull shader and constant function. -//////////////////////////////////////////////////////////////////////////////// -// Domain Shader -//////////////////////////////////////////////////////////////////////////////// -[domain("tri")] -PixelInputType color_tessellation_ds(ConstantOutputType input, float3 barycentricCoordinates : SV_DomainLocation, const OutputPatch patch) -{ - float3 vertexPosition; - PixelInputType output; - - // The barycentric coordinates - float fU = barycentricCoordinates.x; - float fV = barycentricCoordinates.y; - float fW = barycentricCoordinates.z; - - // Precompute squares and squares * 3 - float fUU = fU * fU; - float fVV = fV * fV; - float fWW = fW * fW; - float fUU3 = fUU * 3.0f; - float fVV3 = fVV * 3.0f; - float fWW3 = fWW * 3.0f; - - - // Compute position from cubic control points and barycentric coords - vertexPosition = patch[0].position * fWW * fW + - patch[1].position * fUU * fU + - patch[2].position * fVV * fV + - input.f3B210 * fWW3 * fU + - input.f3B120 * fW * fUU3 + - input.f3B201 * fWW3 * fV + - input.f3B021 * fUU3 * fV + - input.f3B102 * fW * fVV3 + - input.f3B012 * fU * fVV3 + - input.f3B111 * 6.0f * fW * fU * fV; - - // Compute normal from quadratic control points and barycentric coords - float3 f3Normal = patch[0].normal * fWW + - patch[1].normal * fUU + - patch[2].normal * fVV + - input.f3N110 * fW * fU + - input.f3N011 * fU * fV + - input.f3N101 * fW * fV; - - // Normalize the interpolated normal - f3Normal = normalize( f3Normal ); - - output.texCoord = patch[0].texCoord * fW + patch[1].texCoord * fU + patch[2].texCoord * fV; - - output.position = mul( worldviewprojMatrix, float4(vertexPosition, 1.0f) ); - output.normal = f3Normal; - - return output; -} - -Texture2D g_baseTexture0 : register( t0 ); -SamplerState g_samLinear0 : register( s0 ); - -Texture2D g_baseTexture1 : register( t1 ); -SamplerState g_samLinear1 : register( s1 ); - -//////////////////////////////////////////////////////////////////////////////// -// Pixel Shader -//////////////////////////////////////////////////////////////////////////////// -float4 color_tessellation_ps(PixelInputType input) : SV_TARGET -{ - float4 color; - float lightIntensity; - - float4 texColor = g_baseTexture0.Sample( g_samLinear0, input.texCoord ); - - lightIntensity = saturate(dot(input.normal, lightDirection)); - - color = saturate(surfaceDiffuseColour * lightIntensity); - color = color * texColor * lightDiffuseColor; - - return color; -} - -/* -Texture2D shaderTextures[2]; -SamplerState SampleType; - -float4 color_tessellation_ps(PixelInputType input) : SV_TARGET -{ - float4 texDiffuseColor; - float4 texBumpMap; - float3 bumpNormal; - float3 lightIntensity; - float3 diffuseContribution; - float4 color; - half lightDistance; - half iluminationLightAttenuation; - half calculatedLightAttenuation; - - texDiffuseColor = shaderTextures[0].Sample(SampleType, input.texCoord); - texBumpMap = shaderTextures[1].Sample(SampleType, input.texCoord); - - // Expand the range of the normal value from (0, +1) to (-1, +1). - texBumpMap = (texBumpMap * 2.0f) - 1.0f; - - // Calculate the normal from the data in the bump map. - bumpNormal = texBumpMap.x * input.normal + texBumpMap.y * input.normal; - - // Normalize the resulting bump normal. - bumpNormal = normalize(bumpNormal); - - // Calculate the amount of light on this pixel based on the bump map normal value. - lightIntensity = max(dot(bumpNormal, lightDirection), 0); - - //Ilumination Light Attenuation - lightDistance = length( lightPosition.xyz) / lightAttenuation.r; - iluminationLightAttenuation = lightDistance * lightDistance; // quadratic falloff - calculatedLightAttenuation = 1.0 - iluminationLightAttenuation; - - // Determine the final diffuse color based on the diffuse color and the amount of light intensity. - diffuseContribution = (lightIntensity * lightDiffuseColor.rgb * texDiffuseColor.rgb);// * surfaceDiffuseColour.rgb); - float3 lightContributtion = (diffuseContribution) * calculatedLightAttenuation; - - // Combine the final bump light color with the texture color. - color = float4(lightContributtion, texDiffuseColor.a); - - return color; -}*/ \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL/adaptive_tessellation.hlsl b/Samples/Media/materials/programs/HLSL/adaptive_tessellation.hlsl deleted file mode 100644 index fe3701c14ab..00000000000 --- a/Samples/Media/materials/programs/HLSL/adaptive_tessellation.hlsl +++ /dev/null @@ -1,257 +0,0 @@ -///////////// -// GLOBALS // -///////////// -cbuffer cbPerFrame : register( b0 ) -{ - matrix worldViewprojMatrix; -}; - -cbuffer TessellationBuffer -{ - float4 tessellationAmounts; //Tessellation factors: x=edge, y=inside, z=MinDistance, w=range - float4 cameraPosition; -}; - -////////////// -// TYPEDEFS // -////////////// -struct VertexInputType2 -{ - float3 position : POSITION; - float2 texCoord : TEXCOORD0; - float4 color : COLOR; -}; -//The HullInputType structure is the same as the output structure from the vertex shader. - -struct HullInputType -{ - float3 position : POSITION; - float2 texCoord : TEXCOORD0; - float4 color : COLOR; -}; - -//The ConstantOutputType structure is what will be the output from the patch constant function. - -struct ConstantOutputType -{ - float edges[3] : SV_TessFactor; - float inside : SV_InsideTessFactor; -}; - -//The HullOutputType structure is what will be the output from the hull shader. - -struct HullOutputType -{ - float3 position : POSITION; - float2 texCoord : TEXCOORD0; - float4 color : COLOR; -}; - -struct PixelInputType2 -{ - float4 position : SV_POSITION; - float2 texCoord : TEXCOORD0; - float4 color : COLOR; -}; - -cbuffer LightBuffer -{ - float4 lightAmbientColor; - float4 lightDiffuseColor; - float4 lightSpecularColor; - float3 lightDirection; - float4 lightPosition; - float4 lightAttenuation; - float4 surfaceDiffuseColour; - float4 surfaceSpecularColour; - float surfaceShininess; -}; - -//////////////////////////////////////////////////////////////////////////////// -// Vertex Shader -//////////////////////////////////////////////////////////////////////////////// -HullInputType color_tessellation_vs(VertexInputType2 input) -{ - HullInputType output; - - // Pass the vertex position into the hull shader. - output.position = input.position; - - output.texCoord = input.texCoord; - // Pass the input color into the hull shader. - output.color = input.color; - - return output; -} - -//-------------------------------------------------------------------------------------- -// Returns a distance adaptive tessellation scale factor (0.0f -> 1.0f) -//-------------------------------------------------------------------------------------- -float GetDistanceAdaptiveScaleFactor( - float3 f3Eye, // Position of the camera/eye - float3 f3EdgePosition0, // Position of the first control point of the given patch edge - float3 f3EdgePosition1, // Position of the second control point of the given patch edge - float fMinDistance, // Minimum distance that maximum tessellation factors should be applied at - float fRange // Range beyond the minimum distance where tessellation will scale down to the minimum scaling factor - ) -{ - float3 f3MidPoint = ( f3EdgePosition0 + f3EdgePosition1 ) * 0.5f; - - float fDistance = distance( f3MidPoint, f3Eye ) - fMinDistance; - - float fScale = 1.0f - saturate( fDistance / fRange ); - - return fScale; -} - -//////////////////////////////////////////////////////////////////////////////// -// Patch Constant Function -//////////////////////////////////////////////////////////////////////////////// -ConstantOutputType ColorPatchConstantFunction(InputPatch inputPatch, uint patchId : SV_PrimitiveID) -{ - ConstantOutputType output; - float adaptativeScaleFactor; - - // Set the tessellation factors for the three edges of the triangle. - /*output.edges[0] = tessellationAmounts.x; - output.edges[1] = tessellationAmounts.x; - output.edges[2] = tessellationAmounts.x;*/ - - output.edges[0] = output.edges[1] = output.edges[2] = tessellationAmounts.x; - - adaptativeScaleFactor = GetDistanceAdaptiveScaleFactor( cameraPosition.xyz, inputPatch[2].position, inputPatch[0].position, tessellationAmounts.z, tessellationAmounts.w ); - output.edges[0] = lerp( 1.0f, output.edges[0], adaptativeScaleFactor); - - adaptativeScaleFactor = GetDistanceAdaptiveScaleFactor( cameraPosition.xyz, inputPatch[0].position, inputPatch[1].position, tessellationAmounts.z, tessellationAmounts.w ); - output.edges[1] = lerp( 1.0f, output.edges[1], adaptativeScaleFactor); - - adaptativeScaleFactor = GetDistanceAdaptiveScaleFactor( cameraPosition.xyz, inputPatch[1].position, inputPatch[2].position, tessellationAmounts.z, tessellationAmounts.w ); - output.edges[2] = lerp( 1.0f, output.edges[2], adaptativeScaleFactor); - - // Set the tessellation factor for tessallating inside the triangle. - //output.inside = tessellationAmounts.y; - - output.inside = (output.edges[0] + output.edges[1] + output.edges[2]) / 3.0f; - - return output; -} - -//The inputs to the domain shader are the outputs from the hull shader and constant function. -//////////////////////////////////////////////////////////////////////////////// -// Hull Shader -//////////////////////////////////////////////////////////////////////////////// -[domain("tri")] -[partitioning("integer")] -[outputtopology("triangle_cw")] -[outputcontrolpoints(3)] -[patchconstantfunc("ColorPatchConstantFunction")] -HullOutputType color_tessellation_hs(InputPatch patch, uint pointId : SV_OutputControlPointID, uint patchId : SV_PrimitiveID) -{ - HullOutputType output; - - // Set the position for this control point as the output position. - output.position = patch[pointId].position; - - output.texCoord = patch[pointId].texCoord; - // Set the input color as the output color. - output.color = patch[pointId].color; - - return output; -} - -//The inputs to the domain shader are the outputs from the hull shader and constant function. -//////////////////////////////////////////////////////////////////////////////// -// Domain Shader -//////////////////////////////////////////////////////////////////////////////// -[domain("tri")] -PixelInputType2 color_tessellation_ds(ConstantOutputType input, float3 barycentricCoordinates : SV_DomainLocation, const OutputPatch patch) -{ - float3 vertexPosition; - PixelInputType2 output; - - - // Determine the position of the new vertex. - vertexPosition = barycentricCoordinates.x * patch[0].position + barycentricCoordinates.y * patch[1].position + barycentricCoordinates.z * patch[2].position; - - output.texCoord = barycentricCoordinates.x * patch[0].texCoord + - barycentricCoordinates.y * patch[1].texCoord + - barycentricCoordinates.z * patch[2].texCoord; - - // Calculate the position of the new vertex against the world, view, and projection matrices. - /*output.position = mul(float4(vertexPosition, 1.0f), worldMatrix); - output.position = mul(output.position, viewMatrix); - output.position = mul(output.position, projectionMatrix);*/ - output.position = mul( worldViewprojMatrix, float4(vertexPosition, 1.0f) ); - // Send the input color into the pixel shader. - output.color = patch[0].color; - - return output; -} - -//////////////////////////////////////////////////////////////////////////////// -// Pixel Shader -//////////////////////////////////////////////////////////////////////////////// - -Texture2D g_baseTexture0 : register( t0 ); -SamplerState g_samLinear0 : register( s0 ); - -Texture2D g_baseTexture1 : register( t1 ); -SamplerState g_samLinear1 : register( s1 ); - -float4 color_tessellation_ps(PixelInputType2 input) : SV_TARGET -{ - float4 color; - - float4 texColor = g_baseTexture0.Sample( g_samLinear0, input.texCoord ); - - color = saturate(surfaceDiffuseColour); - color = color * texColor * lightDiffuseColor; - - return color; -} - -/* -Texture2D shaderTextures[2]; -SamplerState SampleType; - -float4 color_tessellation_ps(PixelInputType input) : SV_TARGET -{ - float4 texDiffuseColor; - float4 texBumpMap; - float3 bumpNormal; - float3 lightIntensity; - float3 diffuseContribution; - float4 color; - half lightDistance; - half iluminationLightAttenuation; - half calculatedLightAttenuation; - - texDiffuseColor = shaderTextures[0].Sample(SampleType, input.texCoord); - texBumpMap = shaderTextures[1].Sample(SampleType, input.texCoord); - - // Expand the range of the normal value from (0, +1) to (-1, +1). - texBumpMap = (texBumpMap * 2.0f) - 1.0f; - - // Calculate the normal from the data in the bump map. - bumpNormal = texBumpMap.x + texBumpMap.y ; - - // Normalize the resulting bump normal. - bumpNormal = normalize(bumpNormal); - - // Calculate the amount of light on this pixel based on the bump map normal value. - lightIntensity = max(dot(bumpNormal, lightDirection), 0); - - //Ilumination Light Attenuation - lightDistance = length( lightPosition.xyz) / lightAttenuation.r; - iluminationLightAttenuation = lightDistance * lightDistance; // quadratic falloff - calculatedLightAttenuation = 1.0 - iluminationLightAttenuation; - - // Determine the final diffuse color based on the diffuse color and the amount of light intensity. - diffuseContribution = (lightIntensity * lightDiffuseColor.rgb * texDiffuseColor.rgb);// * surfaceDiffuseColour.rgb); - float3 lightContributtion = (diffuseContribution) * calculatedLightAttenuation; - - // Combine the final bump light color with the texture color. - color = float4(lightContributtion, texDiffuseColor.a); - - return color; -}*/ \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL/hdr.hlsl b/Samples/Media/materials/programs/HLSL/hdr.hlsl deleted file mode 100644 index 678633c7907..00000000000 --- a/Samples/Media/materials/programs/HLSL/hdr.hlsl +++ /dev/null @@ -1,165 +0,0 @@ -#include "hdrutils.hlsl" - -/* Downsample a 2x2 area and convert to greyscale -*/ -float4 downscale2x2Luminence( - float2 uv : TEXCOORD0, - uniform float2 texelSize, // depends on size of source texture - uniform sampler2D inRTT : register(s0) - ) : COLOR -{ - - float4 accum = float4(0.0f, 0.0f, 0.0f, 0.0f); - - float2 texOffset[4] = { - -0.5, -0.5, - -0.5, 0.5, - 0.5, -0.5, - 0.5, 0.5 }; - - for( int i = 0; i < 4; i++ ) - { - // Get colour from source - accum += tex2D(inRTT, uv + texelSize * texOffset[i]); - } - - // Adjust the accumulated amount by lum factor - // Cannot use float3's here because it generates dependent texture errors because of swizzle - float lum = dot(accum, LUMINENCE_FACTOR); - // take average of 4 samples - lum *= 0.25; - return lum; - -} - -/* Downsample a 3x3 area - * This shader is used multiple times on different source sizes, so texel size has to be configurable -*/ -float4 downscale3x3( - float2 uv : TEXCOORD0, - uniform float2 texelSize, // depends on size of source texture - uniform sampler2D inRTT : register(s0) - ) : COLOR -{ - - float4 accum = float4(0.0f, 0.0f, 0.0f, 0.0f); - - float2 texOffset[9] = { - -1.0, -1.0, - 0.0, -1.0, - 1.0, -1.0, - -1.0, 0.0, - 0.0, 0.0, - 1.0, 0.0, - -1.0, 1.0, - 0.0, 1.0, - 1.0, 1.0 - }; - - for( int i = 0; i < 9; i++ ) - { - // Get colour from source - accum += tex2D(inRTT, uv + texelSize * texOffset[i]); - } - - // take average of 9 samples - accum *= 0.1111111111111111; - return accum; - -} - -/* Downsample a 3x3 area from main RTT and perform a brightness pass -*/ -float4 downscale3x3brightpass( - float2 uv : TEXCOORD0, - uniform float2 texelSize, // depends on size of source texture - uniform sampler2D inRTT : register(s0), - uniform sampler2D inLum : register(s1) - ) : COLOR -{ - - float4 accum = float4(0.0f, 0.0f, 0.0f, 0.0f); - - float2 texOffset[9] = { - -1.0, -1.0, - 0.0, -1.0, - 1.0, -1.0, - -1.0, 0.0, - 0.0, 0.0, - 1.0, 0.0, - -1.0, 1.0, - 0.0, 1.0, - 1.0, 1.0 - }; - - for( int i = 0; i < 9; i++ ) - { - // Get colour from source - accum += tex2D(inRTT, uv + texelSize * texOffset[i]); - } - - // take average of 9 samples - accum *= 0.1111111111111111; - - // Reduce bright and clamp - accum = max(float4(0.0f, 0.0f, 0.0f, 1.0f), accum - BRIGHT_LIMITER); - - // Sample the luminence texture - float4 lum = tex2D(inLum, float2(0.5f, 0.5f)); - - // Tone map result - return toneMap(accum, lum.r); - -} - -/* Gaussian bloom, requires offsets and weights to be provided externally -*/ -float4 bloom( - float2 uv : TEXCOORD0, - uniform float2 sampleOffsets[15], - uniform float4 sampleWeights[15], - uniform sampler2D inRTT : register(s0) - ) : COLOR -{ - float4 accum = float4(0.0f, 0.0f, 0.0f, 1.0f); - float2 sampleUV; - - for( int i = 0; i < 15; i++ ) - { - // Sample from adjacent points, 7 each side and central - sampleUV = uv + sampleOffsets[i]; - accum += sampleWeights[i] * tex2D(inRTT, sampleUV); - } - - return accum; - -} - - -/* Final scene composition, with tone mapping -*/ -float4 finalToneMapping( - float2 uv : TEXCOORD0, - uniform sampler2D inRTT : register(s0), - uniform sampler2D inBloom : register(s1), - uniform sampler2D inLum : register(s2) - ) : COLOR -{ - // Get main scene colour - float4 sceneCol = tex2D(inRTT, uv); - - // Get luminence value - float4 lum = tex2D(inLum, float2(0.5f, 0.5f)); - - // tone map this - float4 toneMappedSceneCol = toneMap(sceneCol, lum.r); - - // Get bloom colour - float4 bloom = tex2D(inBloom, uv); - - // Add scene & bloom - return float4(toneMappedSceneCol.rgb + bloom.rgb, 1.0f); - -} - - diff --git a/Samples/Media/materials/programs/HLSL/hdrfp4.hlsl b/Samples/Media/materials/programs/HLSL/hdrfp4.hlsl deleted file mode 100644 index d8474d8beb7..00000000000 --- a/Samples/Media/materials/programs/HLSL/hdrfp4.hlsl +++ /dev/null @@ -1,163 +0,0 @@ -#include "hdrutils.hlsl" - -Texture2D inRTT; -Texture2D inLum; -Texture2D inBloom; -SamplerState g_samLinear -{ - Filter = MIN_MAG_MIP_LINEAR; - AddressU = Wrap; - AddressV = Wrap; -}; - -struct v2p -{ - float4 position : SV_POSITION; - float2 texCoord : TEXCOORD0; -}; - -float4 downscale2x2Luminencefp4( v2p input, - uniform float2 texelSize // depends on size of source texture - ) : SV_Target -{ - - float4 accum = float4(0.0f, 0.0f, 0.0f, 0.0f); - - float2 texOffset[4] = { - -0.5, -0.5, - -0.5, 0.5, - 0.5, -0.5, - 0.5, 0.5 }; - - for( int i = 0; i < 4; i++ ) - { - // Get colour from source - accum += inRTT.Sample(g_samLinear, input.texCoord + texelSize * texOffset[i]); - } - - // Adjust the accumulated amount by lum factor - // Cannot use float3's here because it generates dependent texture errors because of swizzle - float lum = dot(accum, LUMINENCE_FACTOR); - // take average of 4 samples - lum *= 0.25; - return lum; -} - -/* Downsample a 3x3 area - * This shader is used multiple times on different source sizes, so texel size has to be configurable -*/ -float4 downscale3x3fp4(v2p input, - uniform float2 texelSize // depends on size of source texture - ) : SV_Target -{ - - float4 accum = float4(0.0f, 0.0f, 0.0f, 0.0f); - - float2 texOffset[9] = { - -1.0, -1.0, - 0.0, -1.0, - 1.0, -1.0, - -1.0, 0.0, - 0.0, 0.0, - 1.0, 0.0, - -1.0, 1.0, - 0.0, 1.0, - 1.0, 1.0 - }; - - for( int i = 0; i < 9; i++ ) - { - // Get colour from source - accum += inRTT.Sample(g_samLinear, input.texCoord + texelSize * texOffset[i]); - } - - // take average of 9 samples - accum *= 0.1111111111111111; - return accum; - -} - -/* Downsample a 3x3 area from main RTT and perform a brightness pass -*/ -float4 downscale3x3brightpassfp4(v2p input, - uniform float2 texelSize // depends on size of source texture - ) : SV_Target -{ - - float4 accum = float4(0.0f, 0.0f, 0.0f, 0.0f); - - float2 texOffset[9] = { - -1.0, -1.0, - 0.0, -1.0, - 1.0, -1.0, - -1.0, 0.0, - 0.0, 0.0, - 1.0, 0.0, - -1.0, 1.0, - 0.0, 1.0, - 1.0, 1.0 - }; - - for( int i = 0; i < 9; i++ ) - { - // Get colour from source - accum += inRTT.Sample(g_samLinear, input.texCoord + texelSize * texOffset[i]); - } - - // take average of 9 samples - accum *= 0.1111111111111111; - - // Reduce bright and clamp - accum = max(float4(0.0f, 0.0f, 0.0f, 1.0f), accum - BRIGHT_LIMITER); - - // Sample the luminence texture - float4 lum = inLum.Sample(g_samLinear, float2(0.5f, 0.5f)); - - // Tone map result - return toneMap(accum, lum.r); - -} - -/* Gaussian bloom, requires offsets and weights to be provided externally -*/ -float4 bloomfp4(v2p input, - uniform float2 sampleOffsets[15], - uniform float4 sampleWeights[15] - ) : SV_Target -{ - float4 accum = float4(0.0f, 0.0f, 0.0f, 1.0f); - float2 sampleUV; - - for( int i = 0; i < 15; i++ ) - { - // Sample from adjacent points, 7 each side and central - sampleUV = input.texCoord + sampleOffsets[i]; - accum += sampleWeights[i] * inRTT.Sample(g_samLinear, sampleUV); - } - - return accum; - -} - - -/* Final scene composition, with tone mapping -*/ -float4 finalToneMappingfp4(v2p input - ) : SV_Target -{ - // Get main scene colour - float4 sceneCol = inRTT.Sample(g_samLinear, input.texCoord); - - // Get luminence value - float4 lum = inLum.Sample(g_samLinear, float2(0.5f, 0.5f)); - - // tone map this - float4 toneMappedSceneCol = toneMap(sceneCol, lum.r); - - // Get bloom colour - float4 bloom = inBloom.Sample(g_samLinear, input.texCoord); - - // Add scene & bloom - return float4(toneMappedSceneCol.rgb + bloom.rgb, 1.0f); - -} diff --git a/Samples/Media/materials/programs/HLSL/hdrutils.hlsl b/Samples/Media/materials/programs/HLSL/hdrutils.hlsl deleted file mode 100644 index c0611115788..00000000000 --- a/Samples/Media/materials/programs/HLSL/hdrutils.hlsl +++ /dev/null @@ -1,65 +0,0 @@ -// RGBE mode utilities -// RGB each carry a mantissa, A carries a shared exponent -// The exponent is calculated based on the largest colour channel - - -float3 decodeRGBE8(in float4 rgbe) -{ - // get exponent (-128 since it can be +ve or -ve) - float exp = rgbe.a * 255 - 128; - - // expand out the rgb value - return rgbe.rgb * exp2(exp); -} - -float4 encodeRGBE8(in float3 rgb) -{ - float4 ret; - - // What is the largest colour channel? - float highVal = max(rgb.r, max(rgb.g, rgb.b)); - - // Take the logarithm, clamp it to a whole value - float exp = ceil(log2(highVal)); - - // Divide the components by the shared exponent - ret.rgb = rgb / exp2(exp); - - // Store the shared exponent in the alpha channel - ret.a = (exp + 128) / 255; - - return ret; -} - - -static const float4 LUMINENCE_FACTOR = float4(0.27f, 0.67f, 0.06f, 0.0f); -static const float MIDDLE_GREY = 0.72f; -static const float FUDGE = 0.001f; -static const float L_WHITE = 1.5f; -static const float4 BRIGHT_LIMITER = float4(0.6f, 0.6f, 0.6f, 0.0f); - - -/** Tone mapping function -@note Only affects rgb, not a -@param inColour The HDR colour -@param lum The scene lumninence -@returns Tone mapped colour -*/ -float4 toneMap(float4 inColour, float lum) -{ - // From Reinhard et al - // "Photographic Tone Reproduction for Digital Images" - - // Initial luminence scaling (equation 2) - inColour.rgb *= MIDDLE_GREY / (FUDGE + lum); - - // Control white out (equation 4 nom) - inColour.rgb *= (1.0f + inColour.rgb / L_WHITE); - - // Final mapping (equation 4 denom) - inColour.rgb /= (1.0f + inColour.rgb); - - return inColour; - -} - diff --git a/Samples/Media/materials/programs/HLSL/isosurf.hlsl b/Samples/Media/materials/programs/HLSL/isosurf.hlsl deleted file mode 100644 index 0efe660afda..00000000000 --- a/Samples/Media/materials/programs/HLSL/isosurf.hlsl +++ /dev/null @@ -1,85 +0,0 @@ -uniform float IsoValue = 1.0; - - -struct SampleData -{ - float3 N : TEXCOORD0; - float2 Field : TEXCOORD1; - float4 Pos : SV_POSITION; -}; - -struct SurfaceVertex -{ - float3 N : TEXCOORD0; - float4 Pos : SV_POSITION; -}; - -static const int Num_Metaballs = 2; - -// Size of the sampling grid -static const int3 SizeMask = { 63, 63, 63 }; -static const int3 SizeShift = { 0, 6, 12 }; - -// Estimate where isosurface intersects grid edge with endpoints v0, v1 -void CalcIntersection(float4 Pos0, - float3 N0, - float2 Field0, - float4 Pos1, - float3 N1, - float2 Field1, - inout TriangleStream OutputStream - ) -{ - SurfaceVertex outputVertex; - float t = (IsoValue - Field0.x) / (Field1.x - Field0.x); - if ((Field0.x < IsoValue) && (Field1.x > Field0.x)) - { - if (t > 0 && t < 1) - { - float4 Pos = lerp(Pos0, Pos1, t); - float3 N = lerp(N0, N1, t); - outputVertex.Pos = Pos; - outputVertex.N = N; - OutputStream.Append(outputVertex); - } - } -} - -// Geometry shader -// input: line with adjacency (tetrahedron) -// outputs: zero, one or two triangles depending if isosurface intersects tetrahedron - - -[maxvertexcount(4)] -void mainGS(lineadj SampleData input[4], inout TriangleStream OutputStream) -{ - // construct index for this tetrahedron - unsigned int index = (int(input[0].Field.y) << 3) | - (int(input[1].Field.y) << 2) | - (int(input[2].Field.y) << 1) | - int(input[3].Field.y); - - - // don't bother if all vertices out or all vertices inside isosurface - if (index > 0 && index < 15) - { - //Uber-compressed version of the edge table. - unsigned int edgeListHex[] = - {0x0001cde0, 0x98b08c9d, 0x674046ce, 0x487bc480, - 0x21301d2e, 0x139bd910, 0x26376e20, 0x3b700000}; - - unsigned int edgeValFull = edgeListHex[index/2]; - unsigned int edgeVal = (index % 2 == 1) ? (edgeValFull & 0xFFFF) : ((edgeValFull >> 16) & 0xFFFF); - int4 e0 = int4((edgeVal >> 14) & 0x3, (edgeVal >> 12) & 0x3, (edgeVal >> 10) & 0x3, (edgeVal >> 8) & 0x3); - int4 e1 = int4((edgeVal >> 6) & 0x3, (edgeVal >> 4) & 0x3, (edgeVal >> 2) & 0x3, (edgeVal >> 0) & 0x3); - - CalcIntersection(input[e0.x].Pos, input[e0.x].N, input[e0.x].Field, input[e0.y].Pos, input[e0.y].N, input[e0.y].Field, OutputStream); - CalcIntersection(input[e0.z].Pos, input[e0.z].N, input[e0.z].Field, input[e0.w].Pos, input[e0.w].N, input[e0.w].Field, OutputStream); - CalcIntersection(input[e1.x].Pos, input[e1.x].N, input[e1.x].Field, input[e1.y].Pos, input[e1.y].N, input[e1.y].Field, OutputStream); - - // Emit additional triangle, if necessary - if (e1.z != -1) { - CalcIntersection(input[e1.z].Pos, input[e1.z].N, input[e1.z].Field, input[e1.w].Pos, input[e1.w].N, input[e1.w].Field, OutputStream); - } - } -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL/mrttestfp.hlsl b/Samples/Media/materials/programs/HLSL/mrttestfp.hlsl deleted file mode 100644 index a123a3b19ae..00000000000 --- a/Samples/Media/materials/programs/HLSL/mrttestfp.hlsl +++ /dev/null @@ -1,48 +0,0 @@ -// MRT basic test -void mainfp_scene( - float2 uv : TEXCOORD0, - uniform sampler2D tex, - - // 4 output textures - // 2 RGBA - // 2 float32_R - out float4 outcolour0 : COLOR0, - out float4 outcolour1 : COLOR1, - out float4 outcolour2 : COLOR2, - out float4 outcolour3 : COLOR3 -) -{ - float4 baseColour = tex2D(tex, uv); - - // first texture will be base - outcolour0 = baseColour; - - // extract red for the second - outcolour1 = baseColour * float4(1, 0, 0, 1); - - // greyscale positive for third - outcolour2 = (baseColour.r + baseColour.g + baseColour.b) * 0.333; - - // greyscale inverted for third - outcolour3 = 1.0 - outcolour2; -} - -void mainfp_quad( - float2 uv : TEXCOORD0, - uniform sampler2D tex0 : register(s0), - uniform sampler2D tex1 : register(s1), - uniform sampler2D tex2 : register(s2), - uniform sampler2D tex3 : register(s3), - - out float4 outcolour : COLOR0 -) -{ - //outcolour = tex2D(tex0, uv); - outcolour = tex2D(tex1, uv); - //outcolour = tex2D(tex2, uv); - //outcolour = tex2D(tex3, uv); -} - - - - diff --git a/Samples/Media/materials/programs/HLSL/simple_tessellation.hlsl b/Samples/Media/materials/programs/HLSL/simple_tessellation.hlsl deleted file mode 100644 index a2d3ad34e46..00000000000 --- a/Samples/Media/materials/programs/HLSL/simple_tessellation.hlsl +++ /dev/null @@ -1,146 +0,0 @@ -/** -* Modified by: Juan Camilo Acosta Arango (ja0335 ) -* Date: 14-04-2013 -* Note: This shaders are based one my study over the -* Eat3D course, "Shader Production - Writing Custom Shaders with CGFX" -* http://eat3d.com/shaders_intro -**/ - -///////////// -// GLOBALS // -///////////// -Texture2D g_DiffuseTxt : register( t0 ); // diffuse -SamplerState g_samLinear : register( s0 ); - -cbuffer cbVertexBuffer -{ - matrix g_WorldViewprojMatrix; - matrix g_WorldMatrix; - matrix g_ViewMatrix; - matrix g_ProjectionMatrix; -}; - -cbuffer cbTessellationBuffer -{ - float g_tessellationAmount; -}; -////////////// -// TYPEDEFS // -////////////// - -// application to vertex -struct a2v -{ - float4 position : POSITION; - float2 texCoord : TEXCOORD0; -}; - -// vertex to hull -struct v2h -{ - float4 position : POSITION; - float2 texCoord : TEXCOORD0; -}; - -// hull to domain -struct h2d -{ - float4 position : POSITION; - float2 texCoord : TEXCOORD0; -}; - -// domain to pixel -struct d2p -{ - float4 position : SV_POSITION; - float2 texCoord : TEXCOORD0; -}; - -struct v2p -{ - float4 position : SV_POSITION; - float2 texCoord : TEXCOORD0; -}; - -struct ConstantOutputType -{ - float edges[3] : SV_TessFactor; - float inside : SV_InsideTessFactor; -}; - - -//=============================================================== -// PER-LIGHT -v2h simple_tessellation_vs(a2v In) -{ - v2h Out; - //v2p Out; - - Out.position = In.position;//mul(g_WorldViewprojMatrix, In.position); - Out.texCoord = In.texCoord; - - return Out; -} - -//////////////////////////////////////////////////////////////////////////////// -// Patch Constant Function -//////////////////////////////////////////////////////////////////////////////// -ConstantOutputType ColorPatchConstantFunction(InputPatch inputPatch, uint patchId : SV_PrimitiveID) -{ - ConstantOutputType output; - // Set the tessellation factors for the three edges of the triangle. - output.edges[0] = g_tessellationAmount; - output.edges[1] = g_tessellationAmount; - output.edges[2] = g_tessellationAmount; - - // Set the tessellation factor for tessallating inside the triangle. - output.inside = g_tessellationAmount; - - return output; -} - -[domain("tri")] -[partitioning("integer")] -[outputtopology("triangle_cw")] -[outputcontrolpoints(3)] -[patchconstantfunc("ColorPatchConstantFunction")] -h2d simple_tessellation_hs(InputPatch patch, uint pointId : SV_OutputControlPointID, uint patchId : SV_PrimitiveID) -{ - h2d output; - - output.position = patch[pointId].position; - output.texCoord = patch[pointId].texCoord; - - return output; -} - -[domain("tri")] -d2p simple_tessellation_ds(ConstantOutputType input, float3 barycentricCoordinates : SV_DomainLocation, const OutputPatch patch) -{ - float3 vertexPosition; - d2p output; - - - // Determine the position of the new vertex. - vertexPosition = barycentricCoordinates.x * patch[0].position.xyz + - barycentricCoordinates.y * patch[1].position.xyz + - barycentricCoordinates.z * patch[2].position.xyz; - - - output.texCoord = barycentricCoordinates.x * patch[0].texCoord + - barycentricCoordinates.y * patch[1].texCoord + - barycentricCoordinates.z * patch[2].texCoord; - - output.position = mul(g_WorldViewprojMatrix, float4(vertexPosition, 1.0f)); - - return output; -} - -float4 simple_tessellation_ps(d2p In) : SV_TARGET -{ - float4 outColor; - outColor.rgb = g_DiffuseTxt.Sample( g_samLinear, In.texCoord ).rgb; - outColor.a = 1.0f; - - return outColor; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL_Cg/ASCIIFP.cg b/Samples/Media/materials/programs/HLSL_Cg/ASCIIFP.cg deleted file mode 100644 index 9f4357e3874..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/ASCIIFP.cg +++ /dev/null @@ -1,32 +0,0 @@ -sampler2D RT : register(s0); -sampler3D pattern : register(s1); - -float4 ASCII_ps( float4 pos : POSITION, - float2 TexCoord : TEXCOORD0, - uniform float2 numTiles, - uniform float2 iNumTiles, - uniform float2 iNumTiles2, - uniform float4 lum, - uniform float charBias) : COLOR -{ - float3 local; - - //sample RT - local.xy = fmod(TexCoord, iNumTiles); - float2 middle = TexCoord - local.xy; - local.xy = local.xy * numTiles; - - //iNumTiles2 = iNumTiles / 2 - middle = middle + iNumTiles2; - float4 c = tex2D(RT, middle ); - - //multiply luminance by charbias , beacause not all slices of the ascii - //volume texture are used - local.z = dot(c , lum)*charBias; - - //fix to brighten the dark pixels with small characters - //c *= lerp(2.0,1.0, local.z); - - c *= tex3D(pattern,local); - return c; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL_Cg/Bloom2_ps20.cg b/Samples/Media/materials/programs/HLSL_Cg/Bloom2_ps20.cg deleted file mode 100644 index 07e94271f69..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/Bloom2_ps20.cg +++ /dev/null @@ -1,59 +0,0 @@ -//--------------------------------------------- -// Bloom - - -float4 main(float4 Pos: POSITION, - float2 texCoord: TEXCOORD0, - uniform sampler RT: register(s0), - uniform sampler Blur1: register(s1), - uniform float OriginalImageWeight, - uniform float BlurWeight - ) : COLOR { - - - float4 sharp = tex2D(RT, texCoord); - float4 blur = tex2D(Blur1, texCoord); - - //return blur*0.5+sharp*0.5; - return blur*BlurWeight+sharp*OriginalImageWeight; - //return blur; - - //return ( sharp + blur * 1.8 ) / 2; - -// return (sharp*3/6 + (blur*4/6))*float4(1.5, 1.5, 1.5, 1);; - -// float4 color = lerp( sharp, blur, 0.4f ); - -// return color; - - -/* - return ( sharp + blur * 1.8 ) / 2 + - luminance(blur) * - float4( 0.5, 0.5, 0.5, 0) + - luminance(sharp) * - float4( 0.3, 0.3, 0.3, 0); -*/ -/* - return ( sharp + blur * 0.9) / 2 + - luminance(blur) * float4(0.1, 0.15, 0.7, 0); -*/ - -/* - return ( sharp + blur * 0.9) / 2 + - luminance(blur) * float4(0.1, 0.15, 0.7, 0); -*/ - -// float4 retColor = luminance( sharp ) + -// luminance( blur ) + blur / 2; -// return retColor; -} - - - - - - - - - diff --git a/Samples/Media/materials/programs/HLSL_Cg/Bloom_ps20.cg b/Samples/Media/materials/programs/HLSL_Cg/Bloom_ps20.cg deleted file mode 100644 index 4f2bd555ec1..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/Bloom_ps20.cg +++ /dev/null @@ -1,52 +0,0 @@ -sampler Blur1: register(s1); -sampler RT: register(s0); - - -float luminance(float3 c) -{ - return dot( c, float3(0.3, 0.59, 0.11) ); -} - -float4 main(float4 Pos: POSITION, float2 texCoord: TEXCOORD0) : COLOR { - float4 sharp = tex2D(RT, texCoord); - float4 blur = tex2D(Blur1, texCoord); - - - - return ( sharp + blur * 1.8 ) / 2; - -// float4 color = lerp( sharp, blur, 0.4f ); - -// return color; - - -/* - return ( sharp + blur * 1.8 ) / 2 + - luminance(blur) * - float4( 0.5, 0.5, 0.5, 0) + - luminance(sharp) * - float4( 0.3, 0.3, 0.3, 0); -*/ -/* - return ( sharp + blur * 0.9) / 2 + - luminance(blur) * float4(0.1, 0.15, 0.7, 0); -*/ - -/* - return ( sharp + blur * 0.9) / 2 + - luminance(blur) * float4(0.1, 0.15, 0.7, 0); -*/ - -// float4 retColor = luminance( sharp ) + -// luminance( blur ) + blur / 2; -// return retColor; -} - - - - - - - - - diff --git a/Samples/Media/materials/programs/HLSL_Cg/BlurH_ps20.cg b/Samples/Media/materials/programs/HLSL_Cg/BlurH_ps20.cg deleted file mode 100644 index 0ffc3cba696..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/BlurH_ps20.cg +++ /dev/null @@ -1,51 +0,0 @@ -//------------------------------- -//BlurH_ps20.hlsl -// Horizontal Gaussian-Blur pass -//------------------------------- - -sampler Blur0: register(s0); -// Simple blur filter - -//We use the Normal-gauss distribution formula -//f(x) being the formula, we used f(0.5)-f(-0.5); f(1.5)-f(0.5)... -static const float samples[11] = -{//stddev=2.0 -0.01222447, -0.02783468, -0.06559061, -0.12097757, -0.17466632, - -0.19741265, - -0.17466632, -0.12097757, -0.06559061, -0.02783468, -0.01222447 -}; - -static const float2 pos[11] = -{ --5, 0, --4, 0, --3, 0, --2, 0, --1, 0, - 0, 0, - 1, 0, - 2, 0, - 3, 0, - 4, 0, - 5, 0, -}; - -float4 main(float4 Pos: POSITION, float2 texCoord: TEXCOORD0) : COLOR -{ - float4 sum = 0; - for (int i = 0; i < 11; i++) - { - sum += tex2D(Blur0, texCoord + pos[i]*0.01) * samples[i]; - } - return sum; -} diff --git a/Samples/Media/materials/programs/HLSL_Cg/BlurV_ps20.cg b/Samples/Media/materials/programs/HLSL_Cg/BlurV_ps20.cg deleted file mode 100644 index f14e6da04b4..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/BlurV_ps20.cg +++ /dev/null @@ -1,51 +0,0 @@ -//------------------------------- -//BlurV_ps20.hlsl -// Vertical Gaussian-Blur pass -//------------------------------- - -sampler Blur0: register(s0); -// Simple blur filter - -//We use the Normal-gauss distribution formula -//f(x) being the formula, we used f(0.5)-f(-0.5); f(1.5)-f(0.5)... -static const float samples[11] = -{//stddev=2.0 -0.01222447, -0.02783468, -0.06559061, -0.12097757, -0.17466632, - -0.19741265, - -0.17466632, -0.12097757, -0.06559061, -0.02783468, -0.01222447 -}; - -static const float2 pos[11] = -{ -0, -5, -0, -4, -0, -3, -0, -2, -0, -1, -0, 0, -0, 1, -0, 2, -0, 3, -0, 4, -0, 5 -}; - -float4 main(float4 Pos: POSITION, float2 texCoord: TEXCOORD0) : COLOR -{ - float4 sum = 0; - for (int i = 0; i < 11; i++) - { - sum += tex2D(Blur0, texCoord + pos[i]*0.01) * samples[i]; - } - return sum; -} diff --git a/Samples/Media/materials/programs/HLSL_Cg/Blur_vs11.cg b/Samples/Media/materials/programs/HLSL_Cg/Blur_vs11.cg deleted file mode 100644 index 49b316f169c..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/Blur_vs11.cg +++ /dev/null @@ -1,19 +0,0 @@ -struct VS_OUTPUT { - float4 Pos: POSITION; - float2 texCoord: TEXCOORD0; -}; - -VS_OUTPUT main(float4 Pos: POSITION){ - VS_OUTPUT Out; - - // Clean up inaccuracies - Pos.xy = sign(Pos.xy); - - Out.Pos = float4(Pos.xy, 0, 1); - // Image-space - Out.texCoord.x = 0.5 * (1 + Pos.x); - Out.texCoord.y = 0.5 * (1 - Pos.y); - - return Out; -} - diff --git a/Samples/Media/materials/programs/HLSL_Cg/BrightBloom2_ps20.cg b/Samples/Media/materials/programs/HLSL_Cg/BrightBloom2_ps20.cg deleted file mode 100644 index 3fa28ac067d..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/BrightBloom2_ps20.cg +++ /dev/null @@ -1,21 +0,0 @@ -//------------------------------- -//BrightBloom_ps20.cg -// High-pass filter for obtaining lumminance -// We use an aproximation formula that is pretty fast: -// f(x) = ( -3 * ( x - 1 )^2 + 1 ) * 2 -// Color += f(Color) -//------------------------------- - -float4 main(float4 Pos: POSITION, - float2 texCoord: TEXCOORD0, - uniform sampler RT: register(s0) - ) : COLOR { - float4 tex = tex2D(RT, texCoord); - - tex -= 1; - float4 bright4= -6 * tex * tex + 2; //float4 bright4= ( -3 * tex * tex + 1 ) * 2; - float bright = dot( bright4, float4( 0.333333, 0.333333, 0.333333, 0) ); - tex += bright + 0.6; - - return tex; -} diff --git a/Samples/Media/materials/programs/HLSL_Cg/Combine_fp.cg b/Samples/Media/materials/programs/HLSL_Cg/Combine_fp.cg deleted file mode 100644 index 60673d49d95..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/Combine_fp.cg +++ /dev/null @@ -1,16 +0,0 @@ -float4 Combine_fp -( - in float4 posIn: POSITION , - in float2 texCoord: TEXCOORD0, - - uniform sampler2D RT : register(s0), - uniform sampler2D Sum : register(s1), - - uniform float blur -) : COLOR -{ - float4 render = tex2D(RT, texCoord); - float4 sum = tex2D(Sum, texCoord); - - return lerp(render, sum, blur); -} diff --git a/Samples/Media/materials/programs/HLSL_Cg/Common.cg b/Samples/Media/materials/programs/HLSL_Cg/Common.cg deleted file mode 100644 index 45a903d012c..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/Common.cg +++ /dev/null @@ -1,81 +0,0 @@ -struct outPixel -{ - float4 colour : COLOR0; -}; - -// General functions - -// Expand a range-compressed vector -half4 expand(half4 v) -{ - return v * 2 - 1; -} -half3 expand(half3 v) -{ - return v * 2 - 1; -} -half2 expand(half2 v) -{ - return v * 2 - 1; -} -half1 expand(half1 v) -{ - return v * 2 - 1; -} - -// Returns light direction from light position and vertex position -half3 getLightDirection(float4 lightPosition, float4 position) -{ - // calculate tangent space light vector - // Get object space light direction - // Non-normalised since we'll do that in the fragment program anyway - return lightPosition.xyz - (position.xyz * lightPosition.w); -} - -// Returns eye direction from eye position and vertex position -half3 getEyeDirection(float3 eyePosition, float4 position) -{ - return eyePosition - position.xyz; -} - -// Returns a Tangent Binormal Normal matrix -half3x3 getTBNMatrix(float3 tangent, float3 normal) -{ - // Calculate the binormal (NB we assume both normal and tangent are - // already normalised) - // NB looks like nvidia cross params are BACKWARDS to what you'd expect - // this equates to NxT, not TxN - float3 binormal = cross(tangent, normal); - - // Form a rotation matrix out of the vectors - return half3x3(tangent, binormal, normal); -} - -// Returns expanded normal vector from texture map -half3 getNormalMapVector(sampler2D normalMap, float2 uv) -{ - // get bump map vector, again expand from range-compressed - return expand(tex2D(normalMap, uv).xyz); -} - -// Returns displacement vector from normalmaps alpha channel -half getDisplacement(sampler2D normalMap, float2 uv, half scale, half bias) -{ - // get the height using the tex coords - half height = tex2D(normalMap, uv).a; - - // calculate displacement - return (height * scale) + bias; -} - -// Returns a specular component from normal vector, specular colour and specular power -half3 getSpecularComponent(float3 normal, float3 halfAngle, float3 specularcolour, float specularPower) -{ - return pow(saturate(dot(normal, halfAngle)), specularPower) * specularcolour; -} - -// Returns a per-pixel lighted component from normal vector, lightdir and colour -half3 getLightingComponent(float3 normal, float3 lightDir, float3 colour) -{ - return saturate(dot(normal, lightDir)) * colour; -} diff --git a/Samples/Media/materials/programs/HLSL_Cg/DitherFP.cg b/Samples/Media/materials/programs/HLSL_Cg/DitherFP.cg deleted file mode 100644 index 1d883bb4a07..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/DitherFP.cg +++ /dev/null @@ -1,18 +0,0 @@ -sampler2D RT : register(s0); -sampler2D pattern : register(s1); - -half4 Dither_ps(float4 pos : POSITION, float2 TexCoord : TEXCOORD0) : COLOR -{ - half c = dot(tex2D(RT, TexCoord),half4(0.30,0.11,0.59,0.00)); - half n = tex2D(pattern, TexCoord).r*2 - 1.0; - c += n; - if (c > 0.5) - { - c = 0.0; - } - else - { - c = 1.0; - } - return half4(c,c,c,1.0); -} diff --git a/Samples/Media/materials/programs/HLSL_Cg/DualQuaternionSkinning_Shadow.cg b/Samples/Media/materials/programs/HLSL_Cg/DualQuaternionSkinning_Shadow.cg deleted file mode 100644 index 0b7acf05135..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/DualQuaternionSkinning_Shadow.cg +++ /dev/null @@ -1,13 +0,0 @@ -float3 calculateBlendPosition(float4 position, float2x4 blendDQ) -{ - float3 blendPosition = position.xyz + 2.0*cross(blendDQ[0].yzw, cross(blendDQ[0].yzw, position.xyz) + blendDQ[0].x*position.xyz); - float3 trans = 2.0*(blendDQ[0].x*blendDQ[1].yzw - blendDQ[1].x*blendDQ[0].yzw + cross(blendDQ[0].yzw, blendDQ[1].yzw)); - blendPosition += trans; - - return blendPosition; -} - -float3 calculateBlendNormal(float3 normal, float2x4 blendDQ) -{ - return normal + 2.0*cross(blendDQ[0].yzw, cross(blendDQ[0].yzw, normal) + blendDQ[0].x*normal); -} diff --git a/Samples/Media/materials/programs/HLSL_Cg/Example_Basic.cg b/Samples/Media/materials/programs/HLSL_Cg/Example_Basic.cg deleted file mode 100644 index b9fc576501d..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/Example_Basic.cg +++ /dev/null @@ -1,186 +0,0 @@ -/* - Basic ambient lighting vertex program -*/ -void ambientOneTexture_vp(float4 position : POSITION, - float2 uv : TEXCOORD0, - - out float4 oPosition : POSITION, - out float2 oUv : TEXCOORD0, - out float4 colour : COLOR, - - uniform float4x4 worldViewProj, - uniform float4 ambient) -{ - oPosition = mul(worldViewProj, position); - oUv = uv; - colour = ambient; -} - -/* - Basic fragment program using texture and diffuse colour. -*/ -void diffuseOneTexture_fp(float4 position : POSITION, - float2 uv : TEXCOORD0, - float4 diffuse : COLOR, - out float4 colour : COLOR, - uniform sampler2D texMap : register(s0)) -{ - colour = tex2D(texMap,uv) * diffuse; -} - -// hardware morph animation (no normals) -void hardwareMorphAnimation(float3 pos1 : POSITION, - float4 normal : NORMAL, - float2 uv : TEXCOORD0, - float3 pos2 : TEXCOORD1, - - out float4 oPosition : POSITION, - out float2 oUv : TEXCOORD0, - out float4 colour : COLOR, - - uniform float4x4 worldViewProj, - uniform float4 anim_t) -{ - // interpolate - float4 interp = float4(pos1 + anim_t.x*(pos2 - pos1), 1.0f); - - oPosition = mul(worldViewProj, interp); - oUv = uv; - colour = float4(1,0,0,1); -} - -// hardware pose animation (no normals) -void hardwarePoseAnimation(float3 pos : POSITION, - float4 normal : NORMAL, - float2 uv : TEXCOORD0, - float3 pose1 : TEXCOORD1, - float3 pose2 : TEXCOORD2, - - out float4 oPosition : POSITION, - out float2 oUv : TEXCOORD0, - out float4 colour : COLOR, - - uniform float4x4 worldViewProj, - uniform float4 anim_t) -{ - // interpolate - float4 interp = float4(pos + anim_t.x*pose1 + anim_t.y*pose2, 1.0f); - - oPosition = mul(worldViewProj, interp); - oUv = uv; - colour = float4(1,0,0,1); -} - -// hardware morph animation (with normals) -void hardwareMorphAnimationWithNormals(float3 pos1 : POSITION, - float3 normal1 : NORMAL, - float2 uv : TEXCOORD0, - float3 pos2 : TEXCOORD1, - float3 normal2 : TEXCOORD2, - - out float4 oPosition : POSITION, - out float2 oUv : TEXCOORD0, - out float4 colour : COLOR, - - uniform float4x4 worldViewProj, - uniform float4 objSpaceLightPos, - uniform float4 ambient, - uniform float4 anim_t) -{ - // interpolate position - float4 posinterp = float4(pos1 + anim_t.x*(pos2 - pos1), 1.0f); - - // nlerp normal - float3 ninterp = normal1 + anim_t.x*(normal2 - normal1); - ninterp = normalize(ninterp); - - oPosition = mul(worldViewProj, posinterp); - oUv = uv; - - float3 lightDir = normalize( - objSpaceLightPos.xyz - (posinterp.xyz * objSpaceLightPos.w)); - - // Colour it red to make it easy to identify - float lit = saturate(dot(lightDir, ninterp)); - colour = float4((ambient.rgb + float3(lit,lit,lit)) * float3(1,0,0), 1); -} - -// hardware pose animation (with normals) -void hardwarePoseAnimationWithNormals(float3 pos : POSITION, - float3 normal : NORMAL, - float2 uv : TEXCOORD0, - float3 pose1pos : TEXCOORD1, - float3 pose1norm : TEXCOORD2, - float3 pose2pos : TEXCOORD3, - float3 pose2norm : TEXCOORD4, - - out float4 oPosition : POSITION, - out float2 oUv : TEXCOORD0, - out float4 colour : COLOR, - - uniform float4x4 worldViewProj, - uniform float4 objSpaceLightPos, - uniform float4 ambient, - uniform float4 anim_t) -{ - // interpolate - float4 posinterp = float4(pos + anim_t.x*pose1pos + anim_t.y*pose2pos, 1.0f); - - // nlerp normal - // First apply the pose normals (these are actual normals, not offsets) - float3 ninterp = anim_t.x*pose1norm + anim_t.y*pose2norm; - - // Now add back any influence of the original normal - // This depends on what the cumulative weighting left the normal at, if it's lacking or cancelled out - //float remainder = 1.0 - min(anim_t.x + anim_t.y, 1.0); - float remainder = 1.0 - min(length(ninterp), 1.0); - ninterp = ninterp + (normal * remainder); - ninterp = normalize(ninterp); - - oPosition = mul(worldViewProj, posinterp); - oUv = uv; - - float3 lightDir = normalize( - objSpaceLightPos.xyz - (posinterp.xyz * objSpaceLightPos.w)); - - // Colour it red to make it easy to identify - float lit = saturate(dot(lightDir, ninterp)); - colour = float4((ambient.rgb + float3(lit,lit,lit)) * float3(1,0,0), 1); -} - -void basicPassthroughTangent_v(float4 position : POSITION, - float3 tangent : TANGENT, - - out float4 oPosition : POSITION, - out float3 oTangent : TEXCOORD0, - - uniform float4x4 worldViewProj) -{ - oPosition = mul(worldViewProj, position); - oTangent = tangent; -} -void basicPassthroughNormal_v(float4 position : POSITION, - float3 normal : NORMAL, - - out float4 oPosition : POSITION, - out float3 oNormal : TEXCOORD0, - - uniform float4x4 worldViewProj) -{ - oPosition = mul(worldViewProj, position); - oNormal = normal; -} -// Basic fragment program to display UV -float4 showuv_p (float4 position : POSITION, float2 uv : TEXCOORD0) : COLOR -{ - // wrap values using frac - return float4(frac(uv.x), frac(uv.y), 0, 1); -} -// Basic fragment program to display 3d uv -float4 showuvdir3d_p (float4 position : POSITION, float3 uv : TEXCOORD0) : COLOR -{ - float3 n = normalize(uv); - return float4(n.x, n.y, n.z, 1); -} - - diff --git a/Samples/Media/materials/programs/HLSL_Cg/Example_BumpMapping.cg b/Samples/Media/materials/programs/HLSL_Cg/Example_BumpMapping.cg deleted file mode 100644 index 10a640452f9..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/Example_BumpMapping.cg +++ /dev/null @@ -1,159 +0,0 @@ -// General functions - -// Expand a range-compressed vector -float3 expand(float3 v) -{ - return (v - 0.5) * 2; -} - - -/* Bump mapping vertex program - In this program, we want to calculate the tangent space light vector - on a per-vertex level which will get passed to the fragment program, - or to the fixed function dot3 operation, to produce the per-pixel - lighting effect. -*/ -void main_vp(float4 position : POSITION, - float3 normal : NORMAL, - float2 uv : TEXCOORD0, - float4 tangent : TANGENT, - // outputs - out float4 oPosition : POSITION, - out float2 oUv : TEXCOORD0, - out float3 oTSLightDir : TEXCOORD1, - // parameters - uniform float4 lightPosition, // object space - uniform float4x4 worldViewProj) -{ - // calculate output position - oPosition = mul(worldViewProj, position); - - // pass the main uvs straight through unchanged - oUv = uv; - - // calculate tangent space light vector - // Get object space light direction - // Non-normalised since we'll do that in the fragment program anyway - float3 lightDir = lightPosition.xyz - (position * lightPosition.w); - - // Calculate the binormal (NB we assume both normal and tangent are - // already normalised) - // NB looks like nvidia cross params are BACKWARDS to what you'd expect - // this equates to NxT, not TxN - -#if TANGENTS_HAVE_PARITY - float3 binormal = cross(tangent.xyz, normal) * tangent.www; -#else - // fixed handedness - float3 binormal = cross(tangent.xyz, normal); -#endif - - // Form a rotation matrix out of the vectors - float3x3 rotation = float3x3(tangent.xyz, binormal, normal); - - // Transform the light vector according to this matrix - oTSLightDir = mul(rotation, lightDir); - - -} - -/* Bump mapping vertex program for shadow receiving - In this program, we want to calculate the tangent space light vector - on a per-vertex level which will get passed to the fragment program, - or to the fixed function dot3 operation, to produce the per-pixel - lighting effect. -*/ -void main_shadowreceiver_vp(float4 position : POSITION, - float3 normal : NORMAL, - float2 uv : TEXCOORD0, - float3 tangent : TANGENT, - - // outputs - out float4 oPosition : POSITION, - out float4 uvproj : TEXCOORD0, - out float2 oUv : TEXCOORD1, - out float3 oTSLightDir : TEXCOORD2, - - // parameters - uniform float4 lightPosition, // object space - uniform float4x4 worldViewProj, - uniform float4x4 worldMatrix, - uniform float4x4 texViewProj) -{ - // calculate output position - oPosition = mul(worldViewProj, position); - - // pass the main uvs straight through unchanged - oUv = uv; - - // calculate tangent space light vector - // Get object space light direction - // Non-normalised since we'll do that in the fragment program anyway - float3 lightDir = lightPosition.xyz - (position * lightPosition.w); - - // Calculate the binormal (NB we assume both normal and tangent are - // already normalised) - // NB looks like nvidia cross params are BACKWARDS to what you'd expect - // this equates to NxT, not TxN - float3 binormal = cross(tangent, normal); - - // Form a rotation matrix out of the vectors - float3x3 rotation = float3x3(tangent.xyz, binormal, normal); - - // Transform the light vector according to this matrix - oTSLightDir = mul(rotation, lightDir); - - // Projection - uvproj = mul(worldMatrix, position); - uvproj = mul(texViewProj, uvproj); - -} - - -void main_fp( float4 position : POSITION, - float2 uv : TEXCOORD0, - float3 TSlightDir : TEXCOORD1, - - out float4 colour : COLOR, - - uniform float4 lightDiffuse, - uniform sampler2D normalMap : register(s0)) -{ - // retrieve normalised light vector, expand from range-compressed - float3 lightVec = normalize(TSlightDir).xyz; - - // get bump map vector, again expand from range-compressed - float3 bumpVec = expand(tex2D(normalMap, uv).xyz); - - // Calculate dot product - colour = lightDiffuse * dot(bumpVec, lightVec); - -} - -void main_shadowreceiver_fp( float4 position : POSITION, - float4 uvproj : TEXCOORD0, - float2 uv : TEXCOORD1, - float3 TSlightDir : TEXCOORD2, - - out float4 colour : COLOR, - - uniform float4 lightDiffuse, - uniform sampler2D shadowMap : register(s0), - uniform sampler2D normalMap : register(s1)) -{ - - - // retrieve normalised light vector, expand from range-compressed - float3 lightVec = expand(normalize(TSlightDir).xyz); - - // get bump map vector, again expand from range-compressed - float3 bumpVec = expand(tex2D(normalMap, uv).xyz); - - // get shadow value - float3 shadow = tex2Dproj(shadowMap, uvproj).xyz; - - // Calculate dot product - colour = float4(shadow * lightDiffuse * dot(bumpVec, lightVec), 1.0f); - -} - diff --git a/Samples/Media/materials/programs/HLSL_Cg/Example_CelShading.cg b/Samples/Media/materials/programs/HLSL_Cg/Example_CelShading.cg deleted file mode 100644 index 5f69575033c..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/Example_CelShading.cg +++ /dev/null @@ -1,65 +0,0 @@ -#include "HLSL_SM4Support.hlsl" - -/* Cel shading vertex program for single-pass rendering - In this program, we want to calculate the diffuse and specular - ramp components, and the edge factor (for doing simple outlining) - For the outlining to look good, we need a pretty well curved model. -*/ -void main_vp(float4 position : POSITION, - float3 normal : NORMAL, - // outputs - out float4 oPosition : POSITION, - out float diffuse : TEXCOORD0, - out float specular : TEXCOORD1, - out float edge : TEXCOORD2, - // parameters - uniform float3 lightPosition, // object space - uniform float3 eyePosition, // object space - uniform float4 shininess, - uniform float4x4 worldViewProj) -{ - // calculate output position - oPosition = mul(worldViewProj, position); - - // calculate light vector - float3 N = normalize(normal); - float3 L = normalize(lightPosition - position.xyz); - - // Calculate diffuse component - diffuse = max(dot(N, L) , 0); - - // Calculate specular component - float3 E = normalize(eyePosition - position.xyz); - float3 H = normalize(L + E); - specular = pow(max(dot(N, H), 0), shininess); - // Mask off specular if diffuse is 0 - if (diffuse == 0) specular = 0; - - // Edge detection, dot eye and normal vectors - edge = max(dot(N, E), 0); -} - -SAMPLER1D(diffuseRamp, 0); -SAMPLER1D(specularRamp, 1); -SAMPLER1D(edgeRamp, 2); - -void main_fp( float4 position : POSITION, - float diffuseIn : TEXCOORD0, - float specularIn : TEXCOORD1, - float edge : TEXCOORD2, - - out float4 colour : COLOR, - - uniform float4 diffuse, - uniform float4 specular) -{ - // Step functions from textures - diffuseIn = tex1D(diffuseRamp, diffuseIn).x; - specularIn = tex1D(specularRamp, specularIn).x; - edge = tex1D(edgeRamp, edge).x; - - colour = edge * ((diffuse * diffuseIn) + - (specular * specularIn)); -} - - diff --git a/Samples/Media/materials/programs/HLSL_Cg/GlassFP.cg b/Samples/Media/materials/programs/HLSL_Cg/GlassFP.cg deleted file mode 100644 index a2a8f97f990..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/GlassFP.cg +++ /dev/null @@ -1,11 +0,0 @@ -#include - -SAMPLER2D(RT, 0); -SAMPLER2D(NormalMap, 1); - -float4 main_ps(float4 pos : POSITION, float2 iTexCoord : TEXCOORD0) : COLOR -{ - float4 normal = 2 * (tex2D(NormalMap, iTexCoord * 2.5) - 0.5); - - return tex2D(RT, iTexCoord + normal.xy * 0.05); -} diff --git a/Samples/Media/materials/programs/HLSL_Cg/Grass.cg b/Samples/Media/materials/programs/HLSL_Cg/Grass.cg deleted file mode 100644 index c0facc362b6..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/Grass.cg +++ /dev/null @@ -1,48 +0,0 @@ -////////////////////////////// MOVING GRASS -// Vertex program to wave some grass about -// Assumes UV texture coords of v==0 indicates the top of the grass -void grass_vp(float4 position : POSITION, - float3 normal : NORMAL, - float2 uv : TEXCOORD0, - out float4 oPosition : POSITION, - out float2 oUv : TEXCOORD0, - out float4 oColour : COLOR, - - uniform float4x4 worldViewProj, - //uniform float4 camObjPos, - uniform float4 ambient, - uniform float4 objSpaceLight, - uniform float4 lightColour, - uniform float4 offset) -{ - float4 mypos = position; - //offset = float4(0.5, 0, 0, 0); - float4 factor = float4(1,1,1,1) - uv.yyyy; - mypos = mypos + offset * factor; - oPosition = mul(worldViewProj, mypos); - - oUv = uv; - // Color - // get vertex light direction (support directional and point) - float3 light = normalize(objSpaceLight.xyz - (mypos.xyz * objSpaceLight.w)); - // grass is just 2D quads, so if light passes underneath we need to invert the normal - // abs() will have the same effect - float diffuseFactor = abs(dot(normal.xyz, light)); - oColour = ambient + diffuseFactor * lightColour; -} - -void grass_fp( float4 position : POSITION, - float2 uv : TEXCOORD0, - float4 colour : COLOR, - - out float4 oColour : COLOR, - - uniform float alphaThresh, - uniform sampler2D diffuseMap - ) -{ - float4 texColor = tex2D(diffuseMap, uv.xy); - oColour = float4(texColor.rgb * colour.rgb, texColor.a); - if(oColour.a < alphaThresh) - discard; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL_Cg/GrayScale.cg b/Samples/Media/materials/programs/HLSL_Cg/GrayScale.cg deleted file mode 100644 index 3a796b7eda5..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/GrayScale.cg +++ /dev/null @@ -1,19 +0,0 @@ -uniform sampler2D RT : register(s0); - -float4 GrayScale_ps( float4 pos : POSITION, - float2 iTexCoord : TEXCOORD0) : COLOR -{ - return dot(tex2D(RT, iTexCoord).rgb, float3(0.3, 0.59, 0.11)); -} - -float4 Embossed_ps( float4 pos : POSITION, - float2 iTexCoord : TEXCOORD0) : COLOR -{ - float4 Color; - Color.a = 1.0f; - Color.rgb = 0.5f; - Color -= tex2D( RT, iTexCoord - 0.001)*2.0f; - Color += tex2D( RT, iTexCoord + 0.001)*2.0f; - Color.rgb = (Color.r+Color.g+Color.b)/3.0f; - return Color; -} diff --git a/Samples/Media/materials/programs/HLSL_Cg/HW_VTFInstancing.cg b/Samples/Media/materials/programs/HLSL_Cg/HW_VTFInstancing.cg deleted file mode 100644 index 14161295fa2..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/HW_VTFInstancing.cg +++ /dev/null @@ -1,122 +0,0 @@ -//--------------------------------------------------------------------------- -//These materials/shaders are part of the NEW InstanceManager implementation -//Written by Matias N. Goldberg ("dark_sylinc") -//--------------------------------------------------------------------------- - -#include "HLSL_SM4Support.hlsl" - -//--------------------------------------------- -//Vertex Shader Input -//--------------------------------------------- -struct VS_INPUT -{ - float4 Position : POSITION; - float3 Normal : NORMAL; -#ifdef BONE_TWO_WEIGHTS - float4 weights : BLENDWEIGHT; -#endif - float2 uv0 : TEXCOORD0; - float4 m03 : TEXCOORD1; //m03.w is always 0 - - float2 mOffset : TEXCOORD2; - -#ifdef BONE_MATRIX_LUT - float4 worldMatrix0 : TEXCOORD3; - float4 worldMatrix1 : TEXCOORD4; - float4 worldMatrix2 : TEXCOORD5; -#endif -}; - -#include "InstancingVertexInterpolators.cg" -#ifdef ST_DUAL_QUATERNION -#include "DualQuaternionSkinning_Shadow.cg" -#endif - -#ifdef DEPTH_SHADOWCASTER - uniform SAMPLER2D(matrixTexture, 0); -#else - uniform SAMPLER2D(matrixTexture, 2); -#endif - -//--------------------------------------------- -//Main Vertex Shader -//--------------------------------------------- -VS_OUTPUT main_vs( in VS_INPUT input, - uniform float4x4 viewProjMatrix - -#if defined( DEPTH_SHADOWCASTER ) || defined( DEPTH_SHADOWRECEIVER ) - , uniform float4 depthRange -#endif -#ifdef DEPTH_SHADOWRECEIVER - , uniform float4x4 texViewProjMatrix -#endif - ) -{ - VS_OUTPUT output; - float4 worldPos; - float3 worldNorm; - - -#ifdef ST_DUAL_QUATERNION - float2x4 blendDQ; - blendDQ[0] = tex2Dlod( matrixTexture, float4(float2(input.m03.x, 0.0) + input.mOffset, 0, 0) ); - blendDQ[1] = tex2Dlod( matrixTexture, float4(float2(input.m03.y, 0.0) + input.mOffset, 0, 0) ); -#ifdef BONE_TWO_WEIGHTS - float2x4 blendDQ2; - //Use the empty parts of m03, z and w, for the second dual quaternion - blendDQ2[0] = tex2Dlod( matrixTexture, float4(float2(input.m03.z, 0.0) + input.mOffset, 0, 0) ); - blendDQ2[1] = tex2Dlod( matrixTexture, float4(float2(input.m03.w, 0.0) + input.mOffset, 0, 0) ); - - //Accurate antipodality handling. For speed increase, remove the following line - if (dot(blendDQ[0], blendDQ2[0]) < 0.0) blendDQ2 *= -1.0; - - //Blend the dual quaternions based on the weights - blendDQ *= input.weights.x; - blendDQ += input.weights.y*blendDQ2; - //Normalize the resultant dual quaternion - blendDQ /= length(blendDQ[0]); -#endif - worldPos = float4(calculateBlendPosition(input.Position, blendDQ), 1.0); - worldNorm = calculateBlendNormal(input.Normal, blendDQ); -#else - //! [world_pos] - float3x4 worldMatrix; - worldMatrix[0] = tex2Dlod( matrixTexture, float4(input.m03.xw + input.mOffset, 0, 0) ); - worldMatrix[1] = tex2Dlod( matrixTexture, float4(input.m03.yw + input.mOffset, 0, 0) ); - worldMatrix[2] = tex2Dlod( matrixTexture, float4(input.m03.zw + input.mOffset, 0, 0) ); - - worldPos = float4( mul( worldMatrix, input.Position ).xyz, 1.0f ); - //! [world_pos] - worldNorm= mul( (float3x3)(worldMatrix), input.Normal ); -#endif - -#ifdef BONE_MATRIX_LUT - float3x4 worldCompMatrix; - worldCompMatrix[0] = input.worldMatrix0; - worldCompMatrix[1] = input.worldMatrix1; - worldCompMatrix[2] = input.worldMatrix2; - - worldPos = float4( mul( worldCompMatrix, worldPos ).xyz, 1.0f ); - worldNorm = mul( (float3x3)(worldCompMatrix), worldNorm ); - -#endif - - - //Transform the position - output.ps.Position = mul( viewProjMatrix, worldPos ); - -#ifndef DEPTH_SHADOWCASTER - output.ps.uv0 = input.uv0; - - //Pass Normal and position for Blinn Phong lighting - output.ps.Normal = normalize(worldNorm); - output.ps.vPos = worldPos.xyz; - - #ifdef DEPTH_SHADOWRECEIVER - // Calculate the position of vertex in light space to do shadows - output.ps.lightSpacePos = mul( texViewProjMatrix, worldPos ); - #endif -#endif - - return output; -} diff --git a/Samples/Media/materials/programs/HLSL_Cg/HalftoneFP.cg b/Samples/Media/materials/programs/HLSL_Cg/HalftoneFP.cg deleted file mode 100644 index f13d86d5d1e..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/HalftoneFP.cg +++ /dev/null @@ -1,19 +0,0 @@ -sampler2D RT : register(s0); -sampler3D pattern : register(s1); - -float4 Halftone_ps( float4 pos : POSITION, - float2 TexCoord : TEXCOORD0, - uniform float2 numTiles, - uniform float2 iNumTiles, - uniform float2 iNumTiles2, - uniform float4 lum) : COLOR -{ - float3 local; - local.xy = fmod(TexCoord, iNumTiles); - float2 middle = TexCoord - local.xy; - local.xy = local.xy * numTiles; - middle += iNumTiles2; - local.z = dot(tex2D(RT, middle ) , lum); - float4 c = tex3D(pattern,local).r; - return c; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/HLSL_Cg/InstancingVertexInterpolators.cg b/Samples/Media/materials/programs/HLSL_Cg/InstancingVertexInterpolators.cg deleted file mode 100644 index 38d1be2befa..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/InstancingVertexInterpolators.cg +++ /dev/null @@ -1,29 +0,0 @@ -//--------------------------------------------------------------------------- -//These materials/shaders are part of the NEW InstanceManager implementation -//Written by Matias N. Goldberg ("dark_sylinc") -//--------------------------------------------------------------------------- - -//--------------------------------------------- -//Pixel Shader Input -//--------------------------------------------- -struct PS_INPUT -{ - float4 Position : POSITION; -#ifndef DEPTH_SHADOWCASTER - float2 uv0 : TEXCOORD0; - float3 Normal : TEXCOORD1; - float3 vPos : TEXCOORD2; - - #ifdef DEPTH_SHADOWRECEIVER - float4 lightSpacePos : TEXCOORD3; - #endif -#endif -}; - -//--------------------------------------------- -//Vertex Shader Output -//--------------------------------------------- -struct VS_OUTPUT -{ - PS_INPUT ps; -}; diff --git a/Samples/Media/materials/programs/HLSL_Cg/Instancing_ps.cg b/Samples/Media/materials/programs/HLSL_Cg/Instancing_ps.cg deleted file mode 100644 index a7a50cd0f39..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/Instancing_ps.cg +++ /dev/null @@ -1,59 +0,0 @@ -//--------------------------------------------------------------------------- -//These materials/shaders are part of the NEW InstanceManager implementation -//Written by Matias N. Goldberg ("dark_sylinc") -//--------------------------------------------------------------------------- -#include "HLSL_SM4Support.hlsl" -#include "InstancingVertexInterpolators.cg" - -float calcDepthShadow(sampler2D shadowMap, float4 uv) -{ - uv /= uv.w; - return tex2D(shadowMap, uv.xy).x >= uv.z ? 1.0 : 0.0; -} - -//--------------------------------------------- -//Main Pixel Shader -//--------------------------------------------- -//Textures -uniform SAMPLER2D(diffuseMap, 0); -#ifdef DEPTH_SHADOWRECEIVER - uniform SAMPLER2D(shadowMap, 1); -#endif - -half4 main_ps( PS_INPUT input , - uniform float4 lightPosition, - uniform float3 cameraPosition, - uniform half3 lightAmbient, - uniform half3 lightDiffuse, - uniform half3 lightSpecular, - uniform half4 lightAttenuation, - uniform half lightGloss - ) : COLOR0 -{ - float fShadow = 1.0f; -#ifdef DEPTH_SHADOWRECEIVER - fShadow = calcDepthShadow( shadowMap, input.lightSpacePos ); -#endif - - const half4 baseColour = tex2D( diffuseMap, input.uv0 ); - - //Blinn-Phong lighting - const half3 normal = normalize( input.Normal ); - half3 lightDir = lightPosition.xyz - input.vPos * lightPosition.w; - half3 eyeDir = normalize( cameraPosition - input.vPos ); - - const half fLength = length( lightDir ); - lightDir = normalize( lightDir ); - - const half NdotL = max( 0.0f, dot( normal, lightDir ) ); - half3 halfVector = normalize(lightDir + eyeDir); - const half HdotN = max( 0.0f, dot( halfVector, normal ) ); - - const half3 ambient = lightAmbient * baseColour.xyz; - const half3 diffuse = lightDiffuse * NdotL * baseColour.xyz; - const half3 specular = lightSpecular * pow( HdotN, lightGloss ); - - const half3 directLighting = (diffuse + specular) * fShadow; - - return half4( directLighting + ambient, baseColour.a ); -} diff --git a/Samples/Media/materials/programs/HLSL_Cg/InvertFP.cg b/Samples/Media/materials/programs/HLSL_Cg/InvertFP.cg deleted file mode 100644 index 4e34426871d..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/InvertFP.cg +++ /dev/null @@ -1,6 +0,0 @@ -sampler2D RT : register(s0); - -float4 Invert_ps (float4 pos : POSITION, float2 iTexCoord : TEXCOORD0) : COLOR -{ - return 1 - tex2D(RT, iTexCoord); -} diff --git a/Samples/Media/materials/programs/HLSL_Cg/LaplaceFP.cg b/Samples/Media/materials/programs/HLSL_Cg/LaplaceFP.cg deleted file mode 100644 index f96b5008ddf..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/LaplaceFP.cg +++ /dev/null @@ -1,37 +0,0 @@ -sampler2D Image : register(s0); - -// The Laplace filter approximates the second order derivate, -// that is, the rate of change of slope in the image. It can be -// used for edge detection. The Laplace filter gives negative -// response on the higher side of the edge and positive response -// on the lower side. - -// This is the filter kernel: -// 0 1 0 -// 1 -4 1 -// 0 1 0 - - - -float4 Laplace_ps ( float4 pos : POSITION, - float2 texCoord: TEXCOORD0, - uniform float scale, - uniform float pixelSize) : COLOR -{ - - float2 samples[4] = { - 0, -1, - -1, 0, - 1, 0, - 0, 1 - }; - float4 laplace = -4 * tex2D(Image, texCoord); - - // Sample the neighbor pixels - for (int i = 0; i < 4; i++){ - laplace += tex2D(Image, texCoord + pixelSize * samples[i]); - } - - return (0.5 + scale * laplace); -} - diff --git a/Samples/Media/materials/programs/HLSL_Cg/Ocean2HLSL_Cg.frag b/Samples/Media/materials/programs/HLSL_Cg/Ocean2HLSL_Cg.frag deleted file mode 100644 index 6b6eddab7cc..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/Ocean2HLSL_Cg.frag +++ /dev/null @@ -1,85 +0,0 @@ -/*********************************************************************NVMH3**** -Copyright NVIDIA Corporation 2003 -TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED -*AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS -BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES -WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, -BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) -ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS -BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - - -Comments: - Simple ocean shader with animated bump map and geometric waves - Based partly on "Effective Water Simulation From Physical Models", GPU Gems - -11 Aug 05: heavily modified by Jeff Doyle (nfz) for Ogre - -******************************************************************************/ - - - -struct v2f { - float4 Position : POSITION; // in clip space - float3 rotMatrix1 : TEXCOORD0; // first row of the 3x3 transform from tangent to obj space - float3 rotMatrix2 : TEXCOORD1; // second row of the 3x3 transform from tangent to obj space - float3 rotMatrix3 : TEXCOORD2; // third row of the 3x3 transform from tangent to obj space - - float2 bumpCoord0 : TEXCOORD3; - float2 bumpCoord1 : TEXCOORD4; - float2 bumpCoord2 : TEXCOORD5; - - float3 eyeVector : TEXCOORD6; -}; - - -float4 main(v2f IN, - uniform sampler2D NormalMap, - uniform samplerCUBE EnvironmentMap, - uniform float4 deepColor, - uniform float4 shallowColor, - uniform float4 reflectionColor, - uniform float reflectionAmount, - uniform float reflectionBlur, - uniform float waterAmount, - uniform float fresnelPower, - uniform float fresnelBias, - uniform float hdrMultiplier - ) : COLOR -{ - // sum normal maps - // sample from 3 different points so no texture repetition is noticeable - float4 t0 = tex2D(NormalMap, IN.bumpCoord0) * 2.0 - 1.0; - float4 t1 = tex2D(NormalMap, IN.bumpCoord1) * 2.0 - 1.0; - float4 t2 = tex2D(NormalMap, IN.bumpCoord2) * 2.0 - 1.0; - float3 N = t0.xyz + t1.xyz + t2.xyz; - - float3x3 m; // tangent to world matrix - m[0] = IN.rotMatrix1; - m[1] = IN.rotMatrix2; - m[2] = IN.rotMatrix3; - - N = normalize( mul( N, m ) ); - - // reflection - float3 E = normalize(IN.eyeVector); - float4 R; - R.xyz = reflect(E, N); - // Ogre conversion for cube map lookup - R.z = -R.z; - R.w = reflectionBlur; - float4 reflection = texCUBEbias(EnvironmentMap, R); - // cheap hdr effect - reflection.rgb *= (reflection.r + reflection.g + reflection.b) * hdrMultiplier; - - // fresnel - float facing = 1.0 - max(dot(-E, N), 0); - float fresnel = saturate(fresnelBias + pow(facing, fresnelPower)); - - float4 waterColor = lerp(shallowColor, deepColor, facing) * waterAmount; - - reflection = lerp(waterColor, reflection * reflectionColor, fresnel) * reflectionAmount; - return waterColor + reflection; -} diff --git a/Samples/Media/materials/programs/HLSL_Cg/Ocean2HLSL_Cg.vert b/Samples/Media/materials/programs/HLSL_Cg/Ocean2HLSL_Cg.vert deleted file mode 100644 index e786233390e..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/Ocean2HLSL_Cg.vert +++ /dev/null @@ -1,108 +0,0 @@ -/*********************************************************************NVMH3**** -Copyright NVIDIA Corporation 2003 -TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED -*AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS -BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES -WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, -BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) -ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS -BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - - -Comments: - Simple ocean shader with animated bump map and geometric waves - Based partly on "Effective Water Simulation From Physical Models", GPU Gems - -11 Aug 05: heavily modified by Jeff Doyle (nfz) for Ogre - -******************************************************************************/ - -struct a2v { - float4 Position : POSITION; // in object space - float2 TexCoord : TEXCOORD0; -}; - -struct v2f { - float4 Position : POSITION; // in clip space - float3 rotMatrix1 : TEXCOORD0; // first row of the 3x3 transform from tangent to obj space - float3 rotMatrix2 : TEXCOORD1; // second row of the 3x3 transform from tangent to obj space - float3 rotMatrix3 : TEXCOORD2; // third row of the 3x3 transform from tangent to obj space - - float2 bumpCoord0 : TEXCOORD3; - float2 bumpCoord1 : TEXCOORD4; - float2 bumpCoord2 : TEXCOORD5; - - float3 eyeVector : TEXCOORD6; -}; - -// wave functions - -struct Wave { - float freq; // 2*PI / wavelength - float amp; // amplitude - float phase; // speed * 2*PI / wavelength - float2 dir; -}; - -v2f main(a2v IN, - uniform float4x4 WorldViewProj, - uniform float3 eyePosition, - uniform float BumpScale, - uniform float2 textureScale, - uniform float2 bumpSpeed, - uniform float time, - uniform float waveFreq, - uniform float waveAmp - ) -{ - v2f OUT; - - #define NWAVES 2 - Wave wave[NWAVES] = { - { 1.0, 1.0, 0.5, float2(-1, 0) }, - { 2.0, 0.5, 1.7, float2(-0.7, 0.7) } - }; - - wave[0].freq = waveFreq; - wave[0].amp = waveAmp; - - wave[1].freq = waveFreq * 3.0; - wave[1].amp = waveAmp * 0.33; - - float4 P = IN.Position; - - // sum waves - float ddx = 0.0, ddy = 0.0; - float deriv; - float angle; - - // wave synthesis using two sine waves at different frequencies and phase shift - for(int i = 0; i st.y) { c1 = invOff; } - half threshholdB = 1.0 - Threshold; - if (st.x > threshholdB) { c2 = c1; } - if (st.y > threshholdB) { c2 = c1; } - half4 cBottom = c2; - c1 = (half4)0; - c2 = (half4)0; - if (st.x > st.y) { c1 = invOff; } - if (st.x < Threshold) { c2 = c1; } - if (st.y < Threshold) { c2 = c1; } - half4 cTop = c2; - half4 tileColor = tex2D(RT, PCenter); - half4 result = tileColor + cTop - cBottom; - return result; -} diff --git a/Samples/Media/materials/programs/HLSL_Cg/VTFInstancing.cg b/Samples/Media/materials/programs/HLSL_Cg/VTFInstancing.cg deleted file mode 100644 index 67db6be8240..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/VTFInstancing.cg +++ /dev/null @@ -1,105 +0,0 @@ -//--------------------------------------------------------------------------- -//These materials/shaders are part of the NEW InstanceManager implementation -//Written by Matias N. Goldberg ("dark_sylinc") -//--------------------------------------------------------------------------- - -#include "HLSL_SM4Support.hlsl" - -//--------------------------------------------- -//Vertex Shader Input -//--------------------------------------------- -struct VS_INPUT -{ - float4 Position : POSITION; - float3 Normal : NORMAL; -#ifdef BONE_TWO_WEIGHTS - float4 weights : BLENDWEIGHT; -#endif - float2 uv0 : TEXCOORD0; - - float4 m01 : TEXCOORD1; - float4 m23 : TEXCOORD2; -}; - -#include "InstancingVertexInterpolators.cg" -#ifdef ST_DUAL_QUATERNION -#include "DualQuaternionSkinning_Shadow.cg" -#endif - -#ifdef DEPTH_SHADOWCASTER - uniform SAMPLER2D(matrixTexture, 0); -#else - uniform SAMPLER2D(matrixTexture, 2); -#endif - -//--------------------------------------------- -//Main Vertex Shader -//--------------------------------------------- -VS_OUTPUT main_vs( in VS_INPUT input, - uniform float4x4 viewProjMatrix - -#if defined( DEPTH_SHADOWCASTER ) || defined( DEPTH_SHADOWRECEIVER ) - , uniform float4 depthRange -#endif -#ifdef DEPTH_SHADOWRECEIVER - , uniform float4x4 texViewProjMatrix -#endif - ) -{ - VS_OUTPUT output; - - float4 worldPos = 0; - float3 worldNorm = 0; - -#ifdef ST_DUAL_QUATERNION - float2x4 blendDQ; - blendDQ[0] = tex2Dlod( matrixTexture, float4(input.m01.xy, 0, 0) ); - blendDQ[1] = tex2Dlod( matrixTexture, float4(input.m01.zw, 0, 0) ); -#ifdef BONE_TWO_WEIGHTS - float2x4 blendDQ2; - //Use the empty parts of m03, z and w, for the second dual quaternion - blendDQ2[0] = tex2Dlod( matrixTexture, float4(input.m23.xy, 0, 0) ); - blendDQ2[1] = tex2Dlod( matrixTexture, float4(input.m23.zw, 0, 0) ); - - //Accurate antipodality handling. For speed increase, remove the following line - if (dot(blendDQ[0], blendDQ2[0]) < 0.0) blendDQ2 *= -1.0; - - //Blend the dual quaternions based on the weights - blendDQ *= input.weights.x; - blendDQ += input.weights.y*blendDQ2; - //Normalize the resultant dual quaternion - blendDQ /= length(blendDQ[0]); -#endif - //Only dealing with one weight so normalization of the dual quaternion and weighting are unnecessary - worldPos = float4(calculateBlendPosition(input.Position, blendDQ), 1.0); - worldNorm = calculateBlendNormal(input.Normal.xyz, blendDQ); -#else - //! [world_pos] - float3x4 worldMatrix; - worldMatrix[0] = tex2Dlod( matrixTexture, float4(input.m01.xy, 0, 0) ); - worldMatrix[1] = tex2Dlod( matrixTexture, float4(input.m01.zw, 0, 0) ); - worldMatrix[2] = tex2Dlod( matrixTexture, float4(input.m23.xy, 0, 0) ); - - worldPos = float4( mul( worldMatrix, input.Position ).xyz, 1.0f ); - //! [world_pos] - worldNorm= mul( (float3x3)(worldMatrix), input.Normal ); -#endif - - //Transform the position - output.ps.Position = mul( viewProjMatrix, worldPos ); - -#ifndef DEPTH_SHADOWCASTER - output.ps.uv0 = input.uv0; - - //Pass Normal and position for Blinn Phong lighting - output.ps.Normal = normalize(worldNorm); - output.ps.vPos = worldPos.xyz; - - #ifdef DEPTH_SHADOWRECEIVER - // Calculate the position of vertex in light space to do shadows - output.ps.lightSpacePos = mul( texViewProjMatrix, worldPos ); - #endif -#endif - - return output; -} diff --git a/Samples/Media/materials/programs/HLSL_Cg/oceanHLSL_Cg.frag b/Samples/Media/materials/programs/HLSL_Cg/oceanHLSL_Cg.frag deleted file mode 100644 index 6f3252496b8..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/oceanHLSL_Cg.frag +++ /dev/null @@ -1,45 +0,0 @@ -// oceanHLSL_Cg.frag -// fragment program for Ocean water simulation -// 04 Aug 2005 -// adapted for Ogre by nfz -// original shader source from Render Monkey 1.6 Reflections Refractions.rfx -// can be used in both Cg and HLSL compilers - -// 06 Aug 2005: moved uvw calculation from fragment program into vertex program - -float4 main( float4 Pos: POSITION, - float3 uvw: TEXCOORD0, float3 normal: TEXCOORD1, float3 vVec: TEXCOORD2, - uniform float fadeBias, - uniform float fadeExp, - uniform float4 waterColor, - uniform sampler3D Noise, - uniform samplerCUBE skyBox - -) : COLOR -{ - - float3 noisy = tex3D(Noise, uvw).xyz; - - // convert to Signed noise - float3 bump = 2 * noisy - 1; - bump.xz *= 0.15; - // Make sure the normal always points upwards - // note that Ogres y axis is vertical (RM Z axis is vertical) - bump.y = 0.8 * abs(bump.y) + 0.2; - // Offset the surface normal with the bump - bump = normalize(normal + bump); - - // Find the reflection vector - float3 normView = normalize(vVec); - float3 reflVec = reflect(normView, bump); - // Ogre has z flipped for cubemaps - reflVec.z = -reflVec.z; - float4 refl = texCUBE(skyBox, reflVec); - - // set up for fresnel calc - float lrp = 1 - dot(-normView, bump); - - // Interpolate between the water color and reflection for fresnel effect - return lerp(waterColor, refl, saturate(fadeBias + pow(lrp, fadeExp))); - -} diff --git a/Samples/Media/materials/programs/HLSL_Cg/oceanHLSL_Cg.vert b/Samples/Media/materials/programs/HLSL_Cg/oceanHLSL_Cg.vert deleted file mode 100644 index a3f517ea37f..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/oceanHLSL_Cg.vert +++ /dev/null @@ -1,41 +0,0 @@ -// oceanHLSL_Cg.vert -// vertex program for Ocean water simulation -// 04 Aug 2005 -// adapted for Ogre by nfz -// original shader source from Render Monkey 1.6 Reflections Refractions.rfx -// can be used in both Cg and HLSL compilers - -// 06 Aug 2005: moved uvw calculation from fragment program into vertex program - -struct VS_OUTPUT { - float4 Pos: POSITION; - float3 uvw: TEXCOORD0; - float3 normal: TEXCOORD1; - float3 vVec: TEXCOORD2; -}; - -VS_OUTPUT main(float4 Pos: POSITION, float3 normal: NORMAL, - uniform float4x4 worldViewProj_matrix, - uniform float3 scale, - uniform float2 waveSpeed, - uniform float noiseSpeed, - uniform float time_0_X, - uniform float3 eyePosition - -) -{ - VS_OUTPUT Out; - - Out.Pos = mul(worldViewProj_matrix, Pos); - - // uvw is the calculated uvw coordinates based on vertex position - Out.uvw = Pos.xyz * scale; - Out.uvw.xz += waveSpeed * time_0_X; - Out.uvw.y += Out.uvw.z + noiseSpeed * time_0_X; - - // the view vector needs to be in vertex space - Out.vVec = Pos.xyz - eyePosition; - Out.normal = normal; - - return Out; -} diff --git a/Samples/Media/materials/programs/HLSL_Cg/pssm.cg b/Samples/Media/materials/programs/HLSL_Cg/pssm.cg deleted file mode 100644 index 1d397808750..00000000000 --- a/Samples/Media/materials/programs/HLSL_Cg/pssm.cg +++ /dev/null @@ -1,25 +0,0 @@ -void shadow_caster_ps( - float4 position : POSITION, - float2 depth : TEXCOORD0, - - out float4 oColour : COLOR, - - uniform float4 pssmSplitPoints) -{ - float finalDepth = depth.x / depth.y; - oColour = float4(finalDepth, finalDepth, finalDepth, 1); -} - -void shadow_caster_vs( - float4 position : POSITION, - - out float4 oPosition : POSITION, - out float2 oDepth : TEXCOORD0, - - uniform float4x4 worldViewProjMatrix) -{ - oPosition = mul(worldViewProjMatrix, position); - - // depth info for the fragment. - oDepth = oPosition.zw; -} \ No newline at end of file diff --git a/Samples/Media/materials/programs/SPIRV/GrayScale.frag b/Samples/Media/materials/programs/SPIRV/GrayScale.frag deleted file mode 100644 index 4826354298e..00000000000 --- a/Samples/Media/materials/programs/SPIRV/GrayScale.frag +++ /dev/null @@ -1,12 +0,0 @@ -#version 430 - -layout(location = 0) uniform sampler2D RT; -layout(location = 0) in vec2 oUv0; - -layout(location = 0) out vec4 fragColor; - -void main() -{ - vec3 greyscale = vec3(dot(texture(RT, oUv0).rgb, vec3(0.3, 0.59, 0.11))); - fragColor = vec4(greyscale, 1.0); -} diff --git a/Samples/Media/materials/programs/SPIRV/README.md b/Samples/Media/materials/programs/SPIRV/README.md deleted file mode 100644 index 993f681b314..00000000000 --- a/Samples/Media/materials/programs/SPIRV/README.md +++ /dev/null @@ -1,23 +0,0 @@ -To use these shaders, enable the GLSLang Plugin and reference them in `BlackAndWhite.material` and `StdQuad_vp.program` by e.g. modifying the GLSL declaration as - -``` -fragment_program Ogre/Compositor/B&W_GLSL_FP glslang -{ - source GrayScale.frag -} - -... - -vertex_program Ogre/Compositor/StdQuad_Tex2a_GLSL_vp glslang -{ - source StdQuad_Tex2a_vp.vert - default_params - { - param_indexed_auto 0 worldviewproj_matrix - } -} -``` - -For SPIRV support, the `"Separate Shader Objects"` option (GL3+) must be enabled. This also allows mixing GLSL and SPIRV shaders in one pass. - -To manually compile these shaders install `glslangValidator` and run `compile.sh `. \ No newline at end of file diff --git a/Samples/Media/materials/programs/SPIRV/StdQuad_Tex2a_vp.vert b/Samples/Media/materials/programs/SPIRV/StdQuad_Tex2a_vp.vert deleted file mode 100644 index 5c09690fa10..00000000000 --- a/Samples/Media/materials/programs/SPIRV/StdQuad_Tex2a_vp.vert +++ /dev/null @@ -1,14 +0,0 @@ -#version 430 - -layout(location = 0) uniform mat4 worldViewProj; - -layout(location = 0) in vec4 vertex; -layout(location = 8) in vec2 uv0; - -layout(location = 0) out vec2 oUv0; - -void main() -{ - gl_Position = worldViewProj * vertex; - oUv0 = uv0; -} diff --git a/Samples/Media/materials/programs/SPIRV/compile.sh b/Samples/Media/materials/programs/SPIRV/compile.sh deleted file mode 100755 index 10f3d4ea269..00000000000 --- a/Samples/Media/materials/programs/SPIRV/compile.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh - -glslangValidator --client opengl100 $1 -o $1.spv \ No newline at end of file diff --git a/Samples/Media/materials/scripts/ASCII.material b/Samples/Media/materials/scripts/ASCII.material deleted file mode 100644 index 1af34efbbf3..00000000000 --- a/Samples/Media/materials/scripts/ASCII.material +++ /dev/null @@ -1,94 +0,0 @@ -fragment_program Ogre/Compositor/ASCIIFPCg hlsl -{ - source ASCIIFP.cg - entry_point ASCII_ps - - default_params - { - param_named iNumTiles float2 0.010 0.02 - param_named iNumTiles2 float2 0.005 0.01 - param_named numTiles float2 100 50 - param_named lum float4 0.30 0.59 0.11 0.0 - param_named charBias float 0.734375 - } -} - -fragment_program Ogre/Compositor/ASCIIFPGLSL glsl -{ - source ASCIIFP.glsl - syntax glsl150 - - default_params - { - param_named iNumTiles float2 0.010 0.02 - param_named iNumTiles2 float2 0.005 0.01 - param_named numTiles float2 100 50 - param_named lum float4 0.30 0.59 0.11 0.0 - param_named charBias float 0.734375 - param_named RT int 0 - param_named chars int 1 - } -} - -fragment_program Ogre/Compositor/ASCIIFPGLSLES glsles -{ - source ASCIIFP.glsles - syntax glsl300es - - default_params - { - param_named iNumTiles float2 0.010 0.02 - param_named iNumTiles2 float2 0.005 0.01 - param_named numTiles float2 100 50 - param_named lum float4 0.30 0.59 0.11 0.0 - param_named charBias float 0.734375 - param_named RT int 0 - param_named chars int 1 - } -} -fragment_program Ogre/Compositor/ASCIIFP unified -{ - delegate Ogre/Compositor/ASCIIFPGLSL - delegate Ogre/Compositor/ASCIIFPGLSLES - delegate Ogre/Compositor/ASCIIFPCg -} - -material Ogre/Compositor/ASCII -{ - technique - { - - pass - { - cull_hardware none - depth_func always_pass - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_Tex2a_vp - { - } - - - fragment_program_ref Ogre/Compositor/ASCIIFP - { - - } - - texture_unit RT - { - tex_coord_set 0 - tex_address_mode clamp - filtering trilinear - } - - texture_unit chars - { - texture ASCII.dds 3d - filtering none - tex_address_mode clamp - } - - } - } -} - diff --git a/Samples/Media/materials/scripts/AdaptivePNTrianglesTessellation.material b/Samples/Media/materials/scripts/AdaptivePNTrianglesTessellation.material deleted file mode 100644 index e44beff8dec..00000000000 --- a/Samples/Media/materials/scripts/AdaptivePNTrianglesTessellation.material +++ /dev/null @@ -1,351 +0,0 @@ -//=============================================================== -// AMBIENT -vertex_program Ogre/AmbientNoTessellation_vs hlsl -{ - source NoTessellation.hlsl - entry_point ambient_color_vs - target vs_5_0 - - default_params - { - param_named_auto g_WorldViewprojMatrix worldviewproj_matrix - } -} - -fragment_program Ogre/AmbientNoTessellation_ps hlsl -{ - source NoTessellation.hlsl - entry_point ambient_color_ps - target ps_5_0 - - default_params - { - param_named_auto g_AmbientLightColour ambient_light_colour - } -} -//=============================================================== -// PER-LIGHT -vertex_program Ogre/PerLightNoTessellation_vs hlsl -{ - source NoTessellation.hlsl - entry_point perlight_color_vs - target vs_5_0 - - default_params - { - param_named_auto g_WorldViewprojMatrix worldviewproj_matrix - param_named_auto g_WorldInverseTranspose inverse_transpose_world_matrix - param_named_auto g_World world_matrix - param_named_auto g_InverseView inverse_view_matrix - } -} - -fragment_program Ogre/PerLightNoTessellation_ps hlsl -{ - source NoTessellation.hlsl - entry_point perlight_color_ps - target ps_5_0 - - default_params - { - param_named_auto g_AmbientLightColour ambient_light_colour - param_named_auto g_LightDirection light_direction 0 - param_named_auto g_LightDiffuseColour light_diffuse_colour 0 - param_named_auto g_DiffuseColour surface_diffuse_colour - param_named_auto g_SpecularColor surface_specular_colour - param_named g_FresnelColor float3 0.172f, 0.172f, 0.172f - param_named g_SpecularPower float 10.0f - param_named g_FresnelPower float 10.0f - } -} - -//============================================================== -material Ogre/NoTessellation -{ - technique - { - pass ambient - { - ambient 0 0 0 - - vertex_program_ref Ogre/AmbientNoTessellation_vs - { - } - - fragment_program_ref Ogre/AmbientNoTessellation_ps - { - } - } - - pass perlight - { - diffuse 0.4 0.4 0.4 1 - specular 0.561 0.561 0.561 1 - - iteration once_per_light - scene_blend add - - vertex_program_ref Ogre/PerLightNoTessellation_vs - { - } - - fragment_program_ref Ogre/PerLightNoTessellation_ps - { - } - - texture_unit normal - { - texture Rocks_Normal.tga - } - - texture_unit diffuse - { - texture Rocks_Diffuse.tga - } - - texture_unit specular - { - texture Rocks_Spec.tga - } - } - } -} - -// Simple tessellation - new shaders - -vertex_program Ogre/PNTrianglesTessellation/simple_tessellation_vs hlsl -{ - source simple_tessellation.hlsl - entry_point simple_tessellation_vs - target vs_5_0 - - default_params - { - //param_named_auto g_WorldViewprojMatrix worldviewproj_matrix - } -} - -tessellation_hull_program Ogre/PNTrianglesTessellation/simple_tessellation_hs hlsl -{ - source simple_tessellation.hlsl - entry_point simple_tessellation_hs - target hs_5_0 - - default_params - { - param_named g_tessellationAmount float 1 - } -} - -tessellation_domain_program Ogre/PNTrianglesTessellation/simple_tessellation_ds hlsl -{ - source simple_tessellation.hlsl - entry_point simple_tessellation_ds - target ds_5_0 - - default_params - { - param_named_auto g_WorldViewprojMatrix worldviewproj_matrix - param_named_auto g_WorldMatrix world_matrix - param_named_auto g_ViewMatrix view_matrix - param_named_auto g_ProjectionMatrix projection_matrix - } -} - -fragment_program Ogre/PNTrianglesTessellation/simple_tessellation_ps hlsl -{ - source simple_tessellation.hlsl - entry_point simple_tessellation_ps - target ps_5_0 - - default_params - { - } -} - -material Ogre/SimpleTessellation -{ - technique - { - pass tessellation - { - vertex_program_ref Ogre/PNTrianglesTessellation/simple_tessellation_vs - { - } - - tessellation_hull_program_ref Ogre/PNTrianglesTessellation/simple_tessellation_hs - { - } - - tessellation_domain_program_ref Ogre/PNTrianglesTessellation/simple_tessellation_ds - { - } - - fragment_program_ref Ogre/PNTrianglesTessellation/simple_tessellation_ps - { - } - - texture_unit diffuse - { - texture Rocks_Diffuse.tga - } - } - } -} - -// Adaptive tessellation - new shaders -// just the hull shader is different from the simple tessellation - -tessellation_hull_program Ogre/PNTrianglesTessellation/adaptive_tessellation_hs hlsl -{ - source adaptive_tessellation.hlsl - entry_point color_tessellation_hs - target hs_5_0 - - default_params - { - //Tessellation factors: x=edge, y=inside, z=MinDistance, w=range - param_named tessellationAmounts float4 16 16 100 200 - param_named_auto cameraPosition camera_position - } -} - -material Ogre/AdaptiveTessellation -{ - technique - { - pass - { - iteration once_per_light - vertex_program_ref Ogre/PNTrianglesTessellation/simple_tessellation_vs - { - - } - - tessellation_hull_program_ref Ogre/PNTrianglesTessellation/adaptive_tessellation_hs - { - - } - - tessellation_domain_program_ref Ogre/PNTrianglesTessellation/simple_tessellation_ds - { - - } - - fragment_program_ref Ogre/PNTrianglesTessellation/simple_tessellation_ps - { - - } - - texture_unit - { - texture floor_diffuse.PNG - } - } - } -} - -// Adaptive PN-Triangles tessellation - new shaders - -vertex_program Ogre/PNTrianglesTessellation/adaptivePNTriangles_tessellation_vs hlsl -{ - source adaptivePNTriangles_tessellation.hlsl - entry_point color_tessellation_vs - target vs_5_0 - - default_params - { - param_named_auto worldviewprojMatrix worldviewproj_matrix - param_named_auto worldMatrix world_matrix - param_named_auto projectionMatrix projection_matrix - //param_named normal float3 1 0 0 - } -} - -tessellation_hull_program Ogre/PNTrianglesTessellation/adaptivePNTriangles_tessellation_hs hlsl -{ - source adaptivePNTriangles_tessellation.hlsl - entry_point color_tessellation_hs - target hs_5_0 - - default_params - { - //Tessellation factors: x=edge, y=inside, z=MinDistance, w=range - param_named tessellationAmounts float4 16 16 100 200 - param_named_auto cameraPosition camera_position - } -} - -tessellation_domain_program Ogre/PNTrianglesTessellation/adaptivePNTriangles_tessellation_ds hlsl -{ - source adaptivePNTriangles_tessellation.hlsl - entry_point color_tessellation_ds - target ds_5_0 - - default_params - { - param_named_auto worldviewprojMatrix worldviewproj_matrix - param_named_auto worldMatrix world_matrix - param_named_auto projectionMatrix projection_matrix - } -} - -fragment_program Ogre/PNTrianglesTessellation/adaptivePNTriangles_tessellation_ps hlsl -{ - source adaptivePNTriangles_tessellation.hlsl - entry_point color_tessellation_ps - target ps_5_0 - - default_params - { - param_named_auto lightDiffuseColor light_diffuse_colour 0 - param_named_auto lightSpecularColor light_specular_colour 0 - param_named_auto lightDirection light_direction 0 - param_named_auto lightPosition light_position 0 - param_named_auto lightAttenuation light_attenuation 0 - param_named_auto surfaceDiffuseColour surface_diffuse_colour - param_named_auto surfaceSpecularColour surface_specular_colour - param_named_auto surfaceShininess surface_shininess - //param_named_auto cameraPosition camera_position - } -} - -material Ogre/AdaptivePNTrianglesTessellation -{ - technique - { - pass - { - iteration once_per_light - vertex_program_ref Ogre/PNTrianglesTessellation/adaptivePNTriangles_tessellation_vs - { - - } - - tessellation_hull_program_ref Ogre/PNTrianglesTessellation/adaptivePNTriangles_tessellation_hs - { - - } - - tessellation_domain_program_ref Ogre/PNTrianglesTessellation/adaptivePNTriangles_tessellation_ds - { - - } - - fragment_program_ref Ogre/PNTrianglesTessellation/adaptivePNTriangles_tessellation_ps - { - - } - - texture_unit - { - texture floor_diffuse.PNG - } - - texture_unit - { - texture floor_bump.PNG - } - } - } -} \ No newline at end of file diff --git a/Samples/Media/materials/scripts/BlackAndWhite.material b/Samples/Media/materials/scripts/BlackAndWhite.material deleted file mode 100644 index 2226ec470f9..00000000000 --- a/Samples/Media/materials/scripts/BlackAndWhite.material +++ /dev/null @@ -1,38 +0,0 @@ -fragment_program Ogre/Compositor/B&W_Cg_FP hlsl -{ - source GrayScale.cg - entry_point GrayScale_ps -} - -fragment_program Ogre/Compositor/B&W_FP glsl glsles glslang hlsl -{ - source GrayScale.glsl -} - -material Ogre/Compositor/BlackAndWhite -{ - technique - { - - pass - { - depth_check off - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_Tex2_vp - { - } - - fragment_program_ref Ogre/Compositor/B&W_FP - { - } - - texture_unit - { - tex_coord_set 0 - tex_address_mode clamp - filtering linear linear linear - } - } - } -} diff --git a/Samples/Media/materials/scripts/Bloom2.material b/Samples/Media/materials/scripts/Bloom2.material deleted file mode 100644 index 443fceb68a4..00000000000 --- a/Samples/Media/materials/scripts/Bloom2.material +++ /dev/null @@ -1,239 +0,0 @@ -//--------------------------------------------------- -//Bloom2: Dark Sylinc's Bloom implementation -// Ogre/Compositor/BloomBlend is the final material applied. -// it has 2 parameters: -// OriginalImageWeight float -// BlurWeight float -// Usually they range from 0.0 to 1.0; but it can be any number -// higher numbers will result in a brighter scene. Increment BlurWeight -// to obtain increase Bloom effect. -// Works faster on my GeForce 6200 256 MB AGP 8x (Chip NV 43 Rev a1) -// than Manuel's bloom. (And at my opinion, looks nicer ;) -// Unlike Manuel's bloom, we apply a bright high-filter pass -//Copyright (C) Dark Sylinc 2007-2008 -//--------------------------------------------------- - -// NB not using GLSL versions since ATI GLSL compiler has a problem with -// BlurV_ps20 -//------------------------ -//OpenGL GLSL Definitions -//------------------------ -vertex_program Blur_vs_glsl glsl glsles -{ - source Blur_vs.glsl - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} -fragment_program BlurV_ps20_glsl glsl glsles -{ - source BlurV_ps20.glsl -} -fragment_program BlurH_ps20_glsl glsl glsles -{ - source BlurH_ps20.glsl -} -fragment_program BrightBloom2_ps20_glsl glsl glsles -{ - source BrightBloom2_ps20.glsl -} -fragment_program Bloom2_ps20_glsl glsl glsles -{ - source Bloom2_ps20.glsl - default_params - { - param_named RT int 0 - param_named Blur1 int 1 - } -} - -//------------------------ -//DirectX 9.0 HLSL Definitions -//------------------------ -//DirectX 9.0 HLSL Vertex Shader vs_1_1 -vertex_program Blur_vs11_hlsl hlsl -{ - source Blur_vs11.cg - target vs_1_1 vs_2_0 - entry_point main -} - -//DirectX 9.0 HLSL Pixel Shader ps_2_0 -fragment_program BlurV_ps20_hlsl hlsl -{ - source BlurV_ps20.cg - target ps_2_0 - entry_point main -} -fragment_program BlurH_ps20_hlsl hlsl -{ - source BlurH_ps20.cg - target ps_2_0 - entry_point main -} - -//DirectX 9.0 HLSL Pixel Shader ps_2_0 -fragment_program Bloom2_ps20_hlsl hlsl -{ - source Bloom2_ps20.cg - target ps_2_0 - entry_point main -} - -//DirectX 9.0 HLSL Pixel Shader ps_2_0 -fragment_program BrightBloom2_ps20_hlsl hlsl -{ - source BrightBloom2_ps20.cg - target ps_2_0 - entry_point main -} - -//------------------------ -//Unified Definitions -//------------------------ -vertex_program Blur_vs unified -{ - delegate Blur_vs11_hlsl - delegate Blur_vs_glsl -} - -fragment_program Bloom2_ps unified -{ - delegate Bloom2_ps20_hlsl - delegate Bloom2_ps20_glsl -} -fragment_program BlurV_ps unified -{ - delegate BlurV_ps20_hlsl - delegate BlurV_ps20_glsl -} -fragment_program BlurH_ps unified -{ - delegate BlurH_ps20_hlsl - delegate BlurH_ps20_glsl -} -fragment_program BrightBloom2_ps unified -{ - delegate BrightBloom2_ps20_hlsl - delegate BrightBloom2_ps20_glsl -} - - -//Blur: Horizontal Gaussian pass -material Ogre/Compositor/BlurH -{ - technique - { - pass - { - cull_hardware none - depth_check off - polygon_mode_overrideable false - - fragment_program_ref BlurH_ps - { - } - vertex_program_ref Blur_vs - { - } - texture_unit - { - tex_coord_set 0 - tex_address_mode clamp - filtering trilinear - } - } - } -} - -//Blur: Vertical Gaussian pass -material Ogre/Compositor/BlurV -{ - technique - { - pass - { - cull_hardware none - depth_check off - polygon_mode_overrideable false - - fragment_program_ref BlurV_ps - { - } - vertex_program_ref Blur_vs - { - } - texture_unit - { - tex_coord_set 0 - tex_address_mode clamp - filtering trilinear - } - } - } -} - -//Final Bloom pass: Blends the blurred with the sharp image -material Ogre/Compositor/BloomBlend2 -{ - technique - { - pass - { - cull_hardware none - depth_check off - polygon_mode_overrideable false - - fragment_program_ref Bloom2_ps - { - param_named OriginalImageWeight float 1.0 - param_named BlurWeight float 0.65 - } - vertex_program_ref Blur_vs - { - } - texture_unit - { - tex_coord_set 0 - tex_address_mode clamp - filtering none - } - texture_unit - { - tex_coord_set 0 - tex_address_mode clamp - filtering trilinear - } - } - } -} - -//High-pass Bright filter -//First pass -material Ogre/Compositor/BrightPass2 -{ - technique - { - pass - { - cull_hardware none - depth_check off - polygon_mode_overrideable false - - fragment_program_ref BrightBloom2_ps - { - } - - vertex_program_ref Ogre/Compositor/StdQuad_Tex2a_vp - { - } - - texture_unit - { - tex_address_mode clamp - filtering none - } - } - } -} diff --git a/Samples/Media/materials/scripts/CompositorDemo.material b/Samples/Media/materials/scripts/CompositorDemo.material deleted file mode 100644 index d62f896ebbf..00000000000 --- a/Samples/Media/materials/scripts/CompositorDemo.material +++ /dev/null @@ -1,18 +0,0 @@ -material CompositorDemo/DebugView -{ - technique - { - pass - { - lighting off - scene_blend alpha_blend - depth_check off - - texture_unit - { - //Will be filled by code, need to set specific on runtime - } - } - } - -} \ No newline at end of file diff --git a/Samples/Media/materials/scripts/Compute.material b/Samples/Media/materials/scripts/Compute.material deleted file mode 100644 index dacea703136..00000000000 --- a/Samples/Media/materials/scripts/Compute.material +++ /dev/null @@ -1,64 +0,0 @@ -////////// -// GLSL // -////////// -compute_program Compute/CS_GLSL glsl -{ - source ComputeCS.glsl - syntax glsl430 - has_sampler_binding true - - //TODO how to handle glMemoryBarrier? - // do other programs need to support this? - // should be able to handle multiple barriers via bit ops - // pre_memory_barrier texture - // post_memory_barrier texture -} - -compute_program Compute/CS_HLSL hlsl -{ - source ComputeCS.hlsl - target cs_5_0 -} - -compute_program Compute/CS unified -{ - delegate Compute/CS_GLSL - delegate Compute/CS_HLSL -} -material Compute/Compositor -{ - technique - { - pass - { - compute_program_ref Compute/CS - { - param_named_auto roll time - } - - texture_unit - { - // resolution must be 256x256. Contents will be overwritten - texture 10points.png 0 PF_BYTE_RGBA - unordered_access_mip 0 - } - } - } -} - -material Compute/Show -{ - technique - { - pass - { - lighting off - texture_unit - { - texture 10points.png 0 PF_BYTE_RGBA - filtering none - tex_address_mode clamp - } - } - } -} \ No newline at end of file diff --git a/Samples/Media/materials/scripts/DOF.material b/Samples/Media/materials/scripts/DOF.material deleted file mode 100644 index d84f1ab1916..00000000000 --- a/Samples/Media/materials/scripts/DOF.material +++ /dev/null @@ -1,67 +0,0 @@ -fragment_program DOF_Blur_ps glsl glsles hlsl -{ - source DoF_Gaussian3x3.frag - default_params - { - param_named_auto vpSize viewport_size - } -} - -fragment_program DOF_Blend_ps glsl glsles hlsl -{ - source DoF_Blend.frag - target ps_2_a - default_params - { - param_named_auto pixelSizeScene viewport_size - param_named scene int 0 - param_named depth int 1 - param_named blur int 2 - } -} - -//Effect: Depth of Field -material Ogre/Compositor/DOF_Blur -{ - technique - { - pass - { - vertex_program_ref Ogre/Compositor/StdQuad_Tex2_vp { } - fragment_program_ref DOF_Blur_ps { } - - texture_unit source - { - tex_address_mode mirror - } - } - } -} - -material Ogre/Compositor/DOF_Blend -{ - technique - { - pass - { - vertex_program_ref Ogre/Compositor/StdQuad_Tex2_vp { } - - fragment_program_ref DOF_Blend_ps { } - - texture_unit - { - tex_address_mode clamp - } - - texture_unit - { - tex_address_mode border - } - - texture_unit - { - tex_address_mode mirror - } - } - } -} diff --git a/Samples/Media/materials/scripts/DamagedHelmet.material b/Samples/Media/materials/scripts/DamagedHelmet.material deleted file mode 100644 index b0846ecce1d..00000000000 --- a/Samples/Media/materials/scripts/DamagedHelmet.material +++ /dev/null @@ -1,59 +0,0 @@ -import glTF2/PBR from glTF2_PBR.material -import Filament from filament.material - -material DamagedHelmet : glTF2/PBR -{ - set $Albedo Default_albedo.jpg - set $AmbientOcclusion Default_AO.jpg - set $Normal Default_normal.jpg - set $Emissive Default_emissive.jpg - set $MetalRoughness Default_metalRoughness.jpg - set $IBL_Diffuse studio_garden_diffuse.png - set $IBL_Specular studio_garden.jpg -} - -material DamagedHelmet_Filament : Filament -{ - set $Albedo Default_albedo.jpg - set $AmbientOcclusion Default_AO.jpg - set $Normal Default_normal.jpg - set $Emissive Default_emissive.jpg - set $MetalRoughness Default_metalRoughness.jpg - set $IBL_SPECULAR studio_garden.jpg -} - -material DamagedHelmet_RTSS { - technique - { - pass - { - // ignored - just in case you want to try the FFP look - ambient 0.8 0.8 0.8 1.0 - diffuse 0.64 0.64 0.64 1.0 - specular 0.64 0.64 0.64 256 - - // albedo - simple - texture_unit - { - texture Default_albedo.jpg - } - - // emissive - also see rtshader_system section below - texture_unit - { - texture Default_emissive.jpg - colour_op add - } - - // additional maps - requires RTSS - rtshader_system - { - lighting_stage metal_roughness texture Default_metalRoughness.jpg - lighting_stage normal_map Default_normal.jpg - texturing_stage late_add_blend // needed for emissive to work - // texture not generated by cmgen, so scale it up as a hack - image_based_lighting texture studio_garden.jpg luminance 4.0 - } - } - } -} \ No newline at end of file diff --git a/Samples/Media/materials/scripts/DepthShadowmap.material b/Samples/Media/materials/scripts/DepthShadowmap.material deleted file mode 100644 index c42c1d38ab2..00000000000 --- a/Samples/Media/materials/scripts/DepthShadowmap.material +++ /dev/null @@ -1,82 +0,0 @@ -// Specific receiver material for rockwall -material Ogre/DepthShadowmap/Receiver/RockWall -{ - technique - { - pass - { - // using integrated shadows - rtshader_system - { - shadow_mapping light_count 2 - } - - texture_unit - { - texture rockwall.tga - } - } - } -} - -// Specific receiver material for Athene -material Ogre/DepthShadowmap/Receiver/Athene -{ - technique - { - pass - { - // using integrated shadows - rtshader_system - { - shadow_mapping light_count 2 - } - - texture_unit - { - texture egyptrockyfull.jpg - } - - // Base bump map - texture_unit - { - texture atheneNormalMap.png - rtshader_system - { - normal_map tangent_space - } - } - } - } -} - -// Specialisation to use PCF -material Ogre/DepthShadowmap/Receiver/RockWall/PCF : Ogre/DepthShadowmap/Receiver/RockWall -{ - technique - { - pass - { - rtshader_system - { - shadow_mapping filter pcf16 - } - } - } -} -// Specialisation to use PCF -material Ogre/DepthShadowmap/Receiver/Athene/PCF : Ogre/DepthShadowmap/Receiver/Athene -{ - technique - { - pass - { - rtshader_system - { - shadow_mapping filter pcf16 - } - } - } -} - - diff --git a/Samples/Media/materials/scripts/Dither.material b/Samples/Media/materials/scripts/Dither.material deleted file mode 100644 index 0289495d5db..00000000000 --- a/Samples/Media/materials/scripts/Dither.material +++ /dev/null @@ -1,59 +0,0 @@ -fragment_program Ogre/Compositor/Dither_Cg_FP hlsl -{ - source DitherFP.cg - entry_point Dither_ps -} - -fragment_program Ogre/Compositor/Dither_GLSL_FP glsl glsles -{ - source DitherFP.glsl - default_params - { - param_named RT int 0 - param_named noise int 1 - } -} - -fragment_program Ogre/Compositor/DitherFP unified -{ - delegate Ogre/Compositor/Dither_GLSL_FP - delegate Ogre/Compositor/Dither_Cg_FP -} - -material Ogre/Compositor/Dither -{ - technique - { - - pass - { - cull_hardware none - depth_func always_pass - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_Tex2a_vp - { - } - - - fragment_program_ref Ogre/Compositor/DitherFP - { - - } - - texture_unit RT - { - tex_coord_set 0 - tex_address_mode clamp - filtering trilinear - } - - texture_unit noise - { - tex_address_mode wrap - tex_coord_set 1 - filtering none - } - } - } -} diff --git a/Samples/Media/materials/scripts/DualQuaternion.material b/Samples/Media/materials/scripts/DualQuaternion.material deleted file mode 100644 index 38a07be5e12..00000000000 --- a/Samples/Media/materials/scripts/DualQuaternion.material +++ /dev/null @@ -1,31 +0,0 @@ -material spine -{ - // Hardware skinning technique - no fragment program - technique - { - pass - { - diffuse 1 1 1 - texture_unit - { - texture circuit.dds - } - } - } -} - -material spineDualQuat -{ - // Hardware skinning technique - technique - { - pass - { - diffuse 1 1 1 - texture_unit - { - texture circuit.dds - } - } - } -} diff --git a/Samples/Media/materials/scripts/Embossed.material b/Samples/Media/materials/scripts/Embossed.material deleted file mode 100644 index e152f255740..00000000000 --- a/Samples/Media/materials/scripts/Embossed.material +++ /dev/null @@ -1,44 +0,0 @@ -fragment_program Ogre/Compositor/Embossed_Cg_FP hlsl -{ - source GrayScale.cg - entry_point Embossed_ps -} - -fragment_program Ogre/Compositor/Embossed_GLSL_FP glsl glsles -{ - source EmbossedFp.glsl -} - -fragment_program Ogre/Compositor/Embossed_FP unified -{ - delegate Ogre/Compositor/Embossed_GLSL_FP - delegate Ogre/Compositor/Embossed_Cg_FP -} - -material Ogre/Compositor/Embossed -{ - technique - { - - pass - { - depth_check off - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_Tex2a_vp - { - } - - fragment_program_ref Ogre/Compositor/Embossed_FP - { - } - - texture_unit RT - { - tex_coord_set 0 - tex_address_mode clamp - filtering linear linear linear - } - } - } -} diff --git a/Samples/Media/materials/scripts/Examples-Advanced.material b/Samples/Media/materials/scripts/Examples-Advanced.material deleted file mode 100644 index c36aee5f9ea..00000000000 --- a/Samples/Media/materials/scripts/Examples-Advanced.material +++ /dev/null @@ -1,669 +0,0 @@ -// ------------------------------- -// Cel Shading Section -// ------------------------------- -vertex_program Ogre/CelShadingVPCg cg -{ - source Example_CelShading.cg - entry_point main_vp - profiles vs_4_0 vs_3_0 vs_1_1 arbvp1 - - default_params - { - param_named_auto lightPosition light_position_object_space 0 - param_named_auto eyePosition camera_position_object_space - param_named_auto worldViewProj worldviewproj_matrix - param_named shininess float 10 - } -} - -fragment_program Ogre/CelShadingFPCg cg -{ - source Example_CelShading.cg - entry_point main_fp - profiles ps_4_0 ps_3_0 ps_2_0 ps_1_1 arbfp1 fp20 - -} - -vertex_program Ogre/CelShadingVPhlsl hlsl -{ - source Example_CelShading.cg - entry_point main_vp - target vs_2_0 - - default_params - { - param_named_auto lightPosition light_position_object_space 0 - param_named_auto eyePosition camera_position_object_space - param_named_auto worldViewProj worldviewproj_matrix - param_named shininess float 10 - } -} - -fragment_program Ogre/CelShadingFPhlsl hlsl -{ - source Example_CelShading.cg - entry_point main_fp - target ps_4_0 ps_2_0 -} - -vertex_program Ogre/CelShadingVPGLSLES glsles -{ - source Example_CelShadingVp.glsles - profiles glsles - - default_params - { - param_named_auto lightPosition light_position_object_space 0 - param_named_auto eyePosition camera_position_object_space - param_named_auto worldViewProj worldviewproj_matrix - param_named shininess float 10 - } -} - -fragment_program Ogre/CelShadingFPGLSLES glsles -{ - source Example_CelShadingFp.glsles - profiles glsles -} - -//! [celshading_vp] -vertex_program Ogre/CelShadingVPGLSL glsl -{ - source Example_CelShadingVp.glsl - syntax glsl150 - - default_params - { - param_named_auto lightPosition light_position_object_space 0 - param_named_auto eyePosition camera_position_object_space - param_named_auto worldViewProj worldviewproj_matrix - param_named shininess float 10 - } -} -//! [celshading_vp] - -fragment_program Ogre/CelShadingFPGLSL glsl -{ - source Example_CelShadingFp.glsl - syntax glsl150 -} - -fragment_program Ogre/CelShadingFP unified -{ - delegate Ogre/CelShadingFPhlsl - delegate Ogre/CelShadingFPGLSL - delegate Ogre/CelShadingFPGLSLES - delegate Ogre/CelShadingFPCg -} - -vertex_program Ogre/CelShadingVP unified -{ - delegate Ogre/CelShadingVPhlsl - delegate Ogre/CelShadingVPGLSL - delegate Ogre/CelShadingVPGLSLES - delegate Ogre/CelShadingVPCg -} - -//shared_params lighting -//{ -// shared_param_named diffuse float4 0 0.5 0 1 -// shared_param_named specular float4 0.3 0.5 0.3 1.0 -//} - -sampler CelShading -{ - tex_address_mode clamp - filtering none -} - -material Examples/CelShading -{ - technique - { - pass - { - vertex_program_ref Ogre/CelShadingVP - { - // map shininess from custom renderable param 1 - param_named_auto shininess custom 1 - } - fragment_program_ref Ogre/CelShadingFP - { -// shared_params_ref lighting - // map diffuse from custom renderable param 2 - param_named_auto diffuse custom 2 - // map specular from custom renderable param 3 - param_named_auto specular custom 3 - } - texture_unit - { - texture cel_shading_diffuse.png 1d - sampler_ref CelShading - } - texture_unit - { - texture cel_shading_specular.png 1d - sampler_ref CelShading - } - texture_unit - { - texture cel_shading_edge.png 1d - sampler_ref CelShading - } - } - } - -} - - - -//------------------------ -// Bump mapping section -//------------------------ - -// Bump map vertex program, support for this is required -vertex_program Examples/BumpMapVPHLSL hlsl -{ - source Example_BumpMapping.cg - entry_point main_vp - target vs_2_0 -} - -vertex_program Examples/BumpMapVPGLSL glsl glsles -{ - source Example_BumpMappingVp.glsl -} - -vertex_program Examples/BumpMapVP unified -{ - delegate Examples/BumpMapVPGLSL - delegate Examples/BumpMapVPHLSL -} - -// Bump map vertex program, with tangent parity support for this is required -vertex_program Examples/BumpMapVPTangentParityCg cg -{ - source Example_BumpMapping.cg - entry_point main_vp - profiles vs_1_1 arbvp1 - compile_arguments -DTANGENTS_HAVE_PARITY=1 -} - -// Bump map fragment program, support for this is optional -fragment_program Examples/BumpMapFPHLSL hlsl -{ - source Example_BumpMapping.cg - entry_point main_fp - target ps_2_0 -} - -fragment_program Examples/BumpMapFPGLSL glsl glsles -{ - source Example_BumpMappingFp.glsl - default_params - { - // assign samplers as required by GLSL - param_named normalMap int 0 - } -} - -fragment_program Examples/BumpMapFP unified -{ - delegate Examples/BumpMapFPGLSL - delegate Examples/BumpMapFPHLSL -} - -// Bump map vertex program shadow receiver -vertex_program Examples/BumpMapVPShadowRcvCg cg -{ - source Example_BumpMapping.cg - entry_point main_shadowreceiver_vp - profiles vs_1_1 arbvp1 -} - -// Bump map vertex program shadow receiver -vertex_program Examples/BumpMapVPShadowRcvGLSL glsl glsles -{ - source Example_BumpMappingShadowRcvVp.glsl -} - -vertex_program Examples/BumpMapVPShadowRcv unified -{ - delegate Examples/BumpMapVPShadowRcvGLSL - delegate Examples/BumpMapVPShadowRcvCg -} - -// Bump map fragment program shadow receiver, support for this is optional -fragment_program Examples/BumpMapFPShadowRcvCg cg -{ - source Example_BumpMapping.cg - entry_point main_shadowreceiver_fp - profiles ps_2_0 arbfp1 fp20 -} - -// Bump map fragment program shadow receiver, support for this is optional -fragment_program Examples/BumpMapFPShadowRcvGLSL glsl glsles -{ - source Example_BumpMappingShadowRcvFp.glsl - default_params - { - // assign samplers as required by GLSL - param_named shadowMap int 0 - param_named normalMap int 1 - } -} - -fragment_program Examples/BumpMapFPShadowRcv unified -{ - delegate Examples/BumpMapFPShadowRcvGLSL - delegate Examples/BumpMapFPShadowRcvCg -} - -//![normal_map_multipass] -// Per-pixel normal mapping. Any number of lights, diffuse only -material Examples/BumpMapping/MultiLight -{ - technique - { - shadow_receiver_material Examples/BumpMapping/MultiLight/Rcv - - // Base ambient pass - pass ambient - { - // base colours, not needed for rendering, but as information - // to lighting pass categorisation routine - diffuse 0 0 0 - } - // Now do the lighting pass - // NB we don't do decal texture here because this is repeated per light - pass perlight - { - // do this for each light - iteration once_per_light - scene_blend add - - // base colours, not needed for rendering, but as information - // to lighting pass categorisation routine - ambient 0 0 0 - - // Vertex program reference - vertex_program_ref Examples/BumpMapVP - { - param_named_auto lightPosition light_position_object_space 0 - param_named_auto worldViewProj worldviewproj_matrix - } - - // Fragment program - fragment_program_ref Examples/BumpMapFP - { - param_named_auto lightDiffuse light_diffuse_colour 0 - } - - // Base bump map - texture_unit normalmap - { - texture NMBumpsOut.png - } - } - - // Decal pass - pass decal - { - // hint to pass categorisation routine, that this is decal only - lighting off - scene_blend dest_colour zero - texture_unit decalmap - { - texture RustedMetal.jpg - } - } - } -} - -material Examples/BumpMapping/MultiLight/Rcv -{ - technique - { - pass - { - scene_blend add - - // texture shadow receiver program - vertex_program_ref Examples/BumpMapVPShadowRcv - { - param_named_auto lightPosition light_position_object_space 0 - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto worldMatrix world_matrix - param_named_auto texViewProj texture_viewproj_matrix - } - // Additive texture shadow receiver program - fragment_program_ref Examples/BumpMapFPShadowRcv - { - param_named_auto lightDiffuse light_diffuse_colour 0 - } - - texture_unit shadowmap - { - content_type shadow - } - texture_unit normalmap - { - texture NMBumpsOut.png - } - } - } -} -//![normal_map_multipass] - -// Any number of lights, diffuse and specular. -material Examples/BumpMapping/MultiLightSpecular -{ - technique - { - pass - { - specular 1 1 1 4 - - texture_unit decalmap - { - texture RustedMetal.jpg - } - - rtshader_system - { - lighting_stage normal_map NMBumpsOut.png - } - } - - } - -} - -// Any number of lights, diffuse only, correct for tangent parity. -material Examples/BumpMapping/MultiLightTangentParity -{ - technique - { - pass - { - texture_unit decalmap - { - texture RustedMetal.jpg - } - - rtshader_system - { - lighting_stage normal_map NMBumpsOut.png - } - } - } - -} - - -//--------------------------- -// Projective texture section -//--------------------------- - - -vertex_program Examples/TexProjectionVP cg -{ - source Example_Projection.cg - entry_point generalPurposeProjection_vp - profiles vs_1_1 arbvp1 -} - -fragment_program Examples/TexProjectionFP cg -{ - source Example_Projection.cg - entry_point generalPurposeProjection_fp - // sorry, ps_1_1 can't do this, fp20 can though - profiles ps_2_0 arbfp1 fp20 -} - -material Examples/GeneralTexProjection -{ - technique - { - pass - { - - vertex_program_ref Examples/TexProjectionVP - { - param_named_auto worldViewProjMatrix worldviewproj_matrix - param_named_auto worldMatrix world_matrix - // You'll need to update the tex projection, I suggest using - // the Frustum class - //param_named_auto texWorldViewProj worldviewproj_matrix - } - fragment_program_ref Examples/TexProjectionFP - { - // no params - } - texture_unit - { - // Project the OGRE logo - texture ogrelogo.png - tex_address_mode clamp - } - } - - - } - -} - -//---------------------------- -// Distortion effects -//---------------------------- -vertex_program Examples/FresnelRefractReflectVP glsl glsles glslang hlsl -{ - source Example_FresnelVp.glsl -} -fragment_program Examples/FresnelRefractReflectFP glsl glsles glslang hlsl -{ - source Example_FresnelFp.glsl - default_params - { - // assign samplers as required by GLSL - param_named noiseMap int 0 - param_named reflectMap int 1 - param_named refractMap int 2 - } -} - -material Examples/FresnelReflectionRefraction -{ - // ps_2_0 / arbfp1 - technique - { - pass - { - - vertex_program_ref Examples/FresnelRefractReflectVP - { - param_named_auto worldViewProjMatrix worldviewproj_matrix - param_named_auto textureProjMatrix texture_worldviewproj_matrix 0 - param_named_auto eyePosition camera_position_object_space - param_named_auto timeVal time 0.05 - param_named scroll float 1 - param_named scale float 1 - param_named noise float 1 - // scroll and noisePos will need updating per frame - } - fragment_program_ref Examples/FresnelRefractReflectFP - { - param_named fresnelBias float -0.1 - param_named fresnelScale float 1.8 - param_named fresnelPower float 8 - param_named tintColour float4 0 0.05 0.05 1 - param_named noiseScale float 0.05 - } - // Noise - texture_unit - { - // Perlin noise volume - texture waves2.dds - // min / mag filtering, no mip - filtering linear linear none - } - // Reflection - texture_unit - { - content_type compositor Fresnel reflection - tex_address_mode clamp - } - // Refraction - texture_unit - { - content_type compositor Fresnel refraction - tex_address_mode clamp - } - } - - - } -} - -// Normal-mapped Athene statue -material Examples/Athene/NormalMapped : Examples/BumpMapping/MultiLight -{ - - // This is the preferred technique which uses both vertex and - // fragment programs, supports coloured lights - technique - { - // Now do the lighting pass - // NB we don't do decal texture here because this is repeated per light - pass perlight - { - - - // Base bump map - texture_unit normalmap - { - texture atheneNormalMap.png - colour_op replace - } - } - - // Decal pass - pass decal - { - texture_unit decalmap - { - texture egyptrockyfull.jpg - } - - } - } -} - -// Basic Athene statue -material Examples/Athene/Basic -{ - - technique - { - pass - { - ambient 0.3 0.3 0.3 - diffuse 1.0 1.0 0.9 - - texture_unit - { - texture egyptrockyfull.jpg - } - - } - } -} - - -// Any number of lights, diffuse and specular -material Examples/Athene/NormalMappedSpecular : Examples/BumpMapping/MultiLightSpecular -{ - - // This is the preferred technique which uses both vertex and - // fragment programs, supports coloured lights - technique - { - // Now do the lighting pass - // NB we don't do decal texture here because this is repeated per light - pass perlight - { - - // Base bump map - texture_unit normalmap - { - texture atheneNormalMap.png - } - } - - // Decal pass - pass decal - { - texture_unit decalmap - { - texture egyptrockyfull.jpg - } - - } - - } -} - -vertex_program Examples/TextureArrayVS glsl glsles hlsl glslang -{ - source Example_TextureArrayVS.glsl - - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -fragment_program Examples/TextureArrayPSglsl glsl glslang -{ - source Example_TextureArrayPS.glsl -} - -fragment_program Examples/TextureArrayPSglsles glsles -{ - source Example_TextureArrayPS.glsles - syntax glsl300es -} - -fragment_program Examples/TextureArrayPShlsl4 hlsl -{ - source Example_TextureArrayPS.glsl - target ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 -} - -fragment_program Examples/TextureArrayPS unified -{ - delegate Examples/TextureArrayPSglsl - delegate Examples/TextureArrayPSglsles - delegate Examples/TextureArrayPShlsl4 - default_params - { - param_named TextureArrayTex int 0 - } -} - -material Examples/TextureArray -{ - technique - { - pass - { - vertex_program_ref Examples/TextureArrayVS - { - } - - fragment_program_ref Examples/TextureArrayPS - { - } - } - } -} diff --git a/Samples/Media/materials/scripts/Examples-DynTex.material b/Samples/Media/materials/scripts/Examples-DynTex.material deleted file mode 100644 index 36edffa9759..00000000000 --- a/Samples/Media/materials/scripts/Examples-DynTex.material +++ /dev/null @@ -1,38 +0,0 @@ -material Examples/Frost -{ - technique - { - pass - { - lighting off - depth_write off - scene_blend colour_blend - - texture_unit 0 - { - texture frost.png - scale 0.5 0.5 - } - - texture_unit 1 - { - colour_op modulate - } - } - } -} - -material Examples/VTDarkStuff -{ - technique - { - pass - { - diffuse 0.0 0.0 0.0 - ambient 0.1 0.1 0.15 - cull_hardware none - lighting off - } - - } -} diff --git a/Samples/Media/materials/scripts/Examples-Water.material b/Samples/Media/materials/scripts/Examples-Water.material deleted file mode 100644 index 169059ba32c..00000000000 --- a/Samples/Media/materials/scripts/Examples-Water.material +++ /dev/null @@ -1,179 +0,0 @@ - -material Examples/Water0 -{ - technique - { - pass - { - scene_blend colour_blend - depth_write off - - texture_unit - { - texture Water01.jpg - env_map spherical - scroll_anim 0.01 0.01 - } - } - } -} -material Examples/Water1 -{ - technique - { - pass - { - scene_blend colour_blend - depth_write off - - texture_unit - { - texture BeachStones.jpg - scale 0.25 0.25 - } - - texture_unit - { - texture Water01.jpg - env_map spherical - scroll_anim 0.01 0.01 - } - } - } -} -material Examples/Water2 -{ - technique - { - pass - { - scene_blend colour_blend - depth_write off - - texture_unit - { - texture Water01.jpg - scroll_anim 0.01 0.01 - } - } - } -} -material Examples/Water3 -{ - technique - { - pass - { - scene_blend colour_blend - depth_write off - - texture_unit - { - texture Water02.jpg - env_map spherical - scroll_anim 0.01 0.01 - rotate_anim 0.03 - } - } - } -} -material Examples/Water4 -{ - technique - { - pass - { - cull_hardware none - - texture_unit - { - texture Water02.jpg - env_map spherical - scroll_anim 0.01 0.01 - } - } - } -} -material Examples/Water5 -{ - technique - { - pass - { - cull_hardware none - - texture_unit - { - texture BeachStones.jpg - scale 0.25 0.25 - } - - texture_unit - { - texture Water01.jpg - env_map spherical - scroll_anim 0.01 0.01 - } - } - } -} -material Examples/Water6 -{ - technique - { - pass - { - lighting off - - texture_unit - { - texture studio_garden.jpg cubic - tex_address_mode clamp - env_map cubic_reflection - } - } - } -} -material Examples/Water7 -{ - technique - { - pass - { - cull_hardware none - - texture_unit - { - texture BeachStones.jpg - scale 0.25 0.25 - } - - texture_unit - { - texture studio_garden.jpg cubic - tex_address_mode clamp - env_map cubic_reflection - } - } - } -} -material Examples/Water8 -{ - technique - { - pass - { - lighting off - scene_blend add - depth_write off - cull_hardware none - - texture_unit - { - texture studio_garden.jpg cubic - tex_address_mode clamp - env_map cubic_reflection - } - } - } -} diff --git a/Samples/Media/materials/scripts/Examples.compositor b/Samples/Media/materials/scripts/Examples.compositor deleted file mode 100644 index 57c474cb169..00000000000 --- a/Samples/Media/materials/scripts/Examples.compositor +++ /dev/null @@ -1,899 +0,0 @@ -//Dark Sylinc's Bloom -compositor Bloom -{ - technique - { - // Temporary textures - texture rt_output target_width target_height PF_BYTE_RGB - texture rt0 target_width_scaled 0.25 target_height_scaled 0.25 PF_BYTE_RGB - texture rt1 target_width_scaled 0.25 target_height_scaled 0.25 PF_BYTE_RGB - - target rt_output - { - // Render output from previous compositor (or original scene) - input previous - } - - target rt0 - { - // Start with clear texture - input none - // Horizontal blur pass - pass render_quad - { - // Renders a fullscreen quad with a material - material Ogre/Compositor/BrightPass2 - input 0 rt_output - } - } - - target rt1 - { - // Start with clear texture - input none - // Horizontal blur pass - pass render_quad - { - // Renders a fullscreen quad with a material - material Ogre/Compositor/BlurV - input 0 rt0 - } - } - - target rt0 - { - // Start with clear texture - input none - // Horizontal blur pass - pass render_quad - { - // Renders a fullscreen quad with a material - material Ogre/Compositor/BlurH - input 0 rt1 - } - } - - target_output - { - // Start with clear output - input none - // Draw a fullscreen quad - pass render_quad - { - // Renders a fullscreen quad with a material - material Ogre/Compositor/BloomBlend2 - input 0 rt_output - input 1 rt0 - } - } - } -} - -//! [glass_script] -compositor Glass -{ - technique - { - texture rt0 target_width target_height PF_BYTE_RGB - - target rt0 { input previous } - - target_output - { - // Start with clear output - input none - - pass render_quad - { - material Ogre/Compositor/GlassPass - input 0 rt0 - } - } - } -} -//! [glass_script] - -compositor "Old TV" -{ - technique - { - texture rt0 target_width target_height PF_BYTE_RGB - - // render scene to a texture - target rt0 { input previous } - - target_output - { - // Start with clear output - input none - - pass render_quad - { - // convert the previous render target to a black and white image, add some noise, distort it, - // then render to scene aligned quad - material Ogre/Compositor/OldTV - input 0 rt0 - } - } - } -} - -//! [manual_sample] -// Black and white effect -compositor B&W -{ - technique - { - // Temporary textures - texture rt0 target_width target_height PF_BYTE_RGBA - - target rt0 - { - // Render output from previous compositor (or original scene) - input previous - } - - target_output - { - // Start with clear output - input none - // Draw a fullscreen quad with the black and white image - pass render_quad - { - // Renders a fullscreen quad with a material - material Ogre/Compositor/BlackAndWhite - input 0 rt0 - } - } - } -} -//! [manual_sample] - -compositor DoF -{ - technique - { - // Temporary textures - texture scene target_width target_height PF_BYTE_RGBA PF_DEPTH16 - texture blur target_width_scaled 0.25 target_height_scaled 0.25 PF_BYTE_RGBA - - target scene - { - // Render original scene - input previous - } - - target blur - { - input none - // blur pass - pass render_quad - { - material Ogre/Compositor/DOF_Blur - input 0 scene 0 - } - } - - target_output - { - // Start with clear output - input none - // Draw a fullscreen quad - pass render_quad - { - material Ogre/Compositor/DOF_Blend - input 0 scene 0 - input 1 scene 1 - input 2 blur - } - } - } -} - -// Embossed (fake bump) effect -compositor Embossed -{ - technique - { - // Temporary textures - texture rt0 target_width target_height PF_BYTE_RGBA - - target rt0 - { - // Render output from previous compositor (or original scene) - input previous - } - - target_output - { - // Start with clear output - input none - // Draw a fullscreen quad with the black and white image - pass render_quad - { - // Renders a fullscreen quad with a material - material Ogre/Compositor/Embossed - input 0 rt0 - } - } - } -} - -// SharpenEdges -compositor "Sharpen Edges" -{ - technique - { - // Temporary textures - texture rt0 target_width target_height PF_BYTE_RGBA - - target rt0 - { - // Render output from previous compositor (or original scene) - input previous - } - - target_output - { - // Start with clear output - input none - // Draw a fullscreen quad with the black and white image - pass render_quad - { - // Renders a fullscreen quad with a material - material Ogre/Compositor/SharpenEdges - input 0 rt0 - } - } - } -} - -// Invert -compositor Invert -{ - technique - { - // Temporary textures - texture rt0 target_width target_height PF_BYTE_RGBA - - target rt0 - { - // Render output from previous compositor (or original scene) - input previous - } - - target_output - { - // Start with clear output - input none - // Draw a fullscreen quad with the black and white image - pass render_quad - { - // Renders a fullscreen quad with a material - material Ogre/Compositor/Invert - input 0 rt0 - } - } - } -} - -// Posterize -compositor Posterize -{ - technique - { - // Temporary textures - texture rt0 target_width target_height PF_BYTE_RGBA - - target rt0 - { - // Render output from previous compositor (or original scene) - input previous - } - - target_output - { - // Start with clear output - input none - // Draw a fullscreen quad with the black and white image - pass render_quad - { - // Renders a fullscreen quad with a material - material Ogre/Compositor/Posterize - input 0 rt0 - } - } - } -} - -// Laplace -compositor Laplace -{ - technique - { - // Temporary textures - texture rt0 target_width target_height PF_BYTE_RGBA - - target rt0 - { - // Render output from previous compositor (or original scene) - input previous - } - - target_output - { - // Start with clear output - input none - // Draw a fullscreen quad with the black and white image - pass render_quad - { - // Renders a fullscreen quad with a material - material Ogre/Compositor/Laplace - input 0 rt0 - } - } - } -} - -// Tiling -compositor Tiling -{ - technique - { - // Temporary textures - texture rt0 target_width target_height PF_BYTE_RGBA - - target rt0 - { - // Render output from previous compositor (or original scene) - input previous - } - - target_output - { - // Start with clear output - input none - // Draw a fullscreen quad with the black and white image - pass render_quad - { - // Renders a fullscreen quad with a material - material Ogre/Compositor/Tiling - input 0 rt0 - } - } - } -} - -// Old Movie -compositor "Old Movie" -{ - technique - { - // Temporary textures - texture rt0 target_width target_height PF_A8B8G8R8 - - target rt0 - { - // Render output from previous compositor (or original scene) - input previous - } - - target_output - { - // Start with clear output - input none - // Draw a fullscreen quad with the black and white image - pass render_quad - { - // Renders a fullscreen quad with a material - material Ogre/Compositor/OldMovie - input 0 rt0 - } - } - } -} - -// HDR -compositor HDR -{ - // floating point only for now - technique - { - compositor_logic HDR - - // Temporary textures - // Fullsize HDR render target, used as tone mapping source - texture rt_full target_width target_height PF_FLOAT16_RGB - // Targets used for luminance evaluation (3x3 downsample, point filtering) - texture rt_lum0 1 1 PF_FLOAT16_RGB - texture rt_lum1 4 4 PF_FLOAT16_RGB - texture rt_lum2 16 16 PF_FLOAT16_RGB - texture rt_lum3 64 64 PF_FLOAT16_RGB - texture rt_lum4 128 128 PF_FLOAT16_RGB - // Bright-pass filtered target (tone mapped) - texture rt_brightpass 128 128 PF_BYTE_RGB - // Bloom filter targets - texture rt_bloom0 128 128 PF_BYTE_RGB - texture rt_bloom1 128 128 PF_BYTE_RGB - - - target rt_full - { - // No input, render differently - input none - - // Use float target HDR material scheme (unclamped shaders) - material_scheme HDR - - pass clear - { - } - - pass render_scene - { - } - - } - - // Downsample the original HDR scene to extract luminence value - target rt_lum4 - { - input none - pass render_quad - { - // Downsample using a 2x2 filter and convert to greyscale - material Ogre/Compositor/HDR/Downsample2x2Luminence - input 0 rt_full - identifier 994 - } - } - target rt_lum3 - { - input none - pass render_quad - { - // Downsample using a 3x3 filter - material Ogre/Compositor/HDR/Downsample3x3 - input 0 rt_lum4 - identifier 993 - } - } - target rt_lum2 - { - input none - pass render_quad - { - // Downsample using a 3x3 filter - material Ogre/Compositor/HDR/Downsample3x3 - input 0 rt_lum3 - identifier 992 - } - } - target rt_lum1 - { - input none - pass render_quad - { - // Downsample using a 3x3 filter - material Ogre/Compositor/HDR/Downsample3x3 - input 0 rt_lum2 - identifier 991 - } - } - target rt_lum0 - { - input none - pass render_quad - { - // Downsample using a 3x3 filter - material Ogre/Compositor/HDR/Downsample3x3 - input 0 rt_lum1 - identifier 990 - } - } - - - target rt_brightpass - { - input none - pass render_quad - { - // Downsample using a 3x3 filter, hi-pass and tone map - material Ogre/Compositor/HDR/Downsample3x3Brightpass - input 0 rt_full - input 1 rt_lum0 - identifier 800 - } - } - - target rt_bloom1 - { - input none - pass render_quad - { - // Blur horizontally - material Ogre/Compositor/HDR/GaussianBloom - input 0 rt_brightpass - identifier 701 - } - } - target rt_bloom0 - { - input none - pass render_quad - { - // Blur horizontally - material Ogre/Compositor/HDR/GaussianBloom - input 0 rt_bloom1 - identifier 700 - } - } - - - // Final output combines tone mapping of the original scene, with an - // exposure setting passed in as a GPU parameter, and an additive bloom - // effect - target_output - { - input none - pass render_quad - { - material Ogre/Compositor/HDR/ToneMapping - input 0 rt_full - input 1 rt_bloom0 - input 2 rt_lum0 - } - } - - - } - -} - - -// Gaussian blur effect -compositor "Gaussian Blur" -{ - technique - { - compositor_logic GaussianBlur - - // Temporary textures - texture rt0 target_width target_height PF_BYTE_RGBA - texture rt1 target_width target_height PF_BYTE_RGBA - - target rt0 - { - // Render output from previous compositor (or original scene) - input previous - } - - target rt1 - { - // Blur horizontally - input none - pass render_quad - { - material Ogre/Compositor/HDR/GaussianBloom - input 0 rt0 - identifier 700 - } - } - - target_output - { - // Start with clear output - input none - // Blur vertically - pass render_quad - { - // Renders a fullscreen quad with a material - material Ogre/Compositor/HDR/GaussianBloom - input 0 rt1 - identifier 701 - } - } - } -} - -// Testing MRT -compositor TestMRT -{ - technique - { - // temporary texture (MRT!) - // 4 sub-surfaces, all 32-bit - texture mrt0 target_width target_height PF_BYTE_RGBA PF_BYTE_RGBA PF_BYTE_RGBA PF_BYTE_RGBA - - target mrt0 - { - // Render scene using MRT-compatible material scheme - input none - material_scheme MRT - pass clear - { - - } - pass render_scene - { - } - } - - target_output - { - input none - pass render_quad - { - // Renders a fullscreen quad - material Ogre/MRTtest/quad - // bind 4 MRT surfaces as texture inputs - input 0 mrt0 0 - input 1 mrt0 1 - input 2 mrt0 2 - input 3 mrt0 3 - } - - } - - } -} - -//Radial blur effect -compositor "Radial Blur" -{ - technique - { - // Temporary textures - texture rt0 target_width target_height PF_BYTE_RGBA - - target rt0 - { - // Render output from previous compositor (or original scene) - input previous - } - - target_output - { - // Start with clear output - input none - // Blur vertically - pass render_quad - { - // Renders a fullscreen quad with a material - material Ogre/Compositor/Radial_Blur - input 0 rt0 - } - } - } -} - -// ASCII effect -compositor ASCII -{ - technique - { - // Temporary textures - texture rt0 target_width target_height PF_BYTE_RGBA - target rt0 - { - // Render output from previous compositor (or original scene) - input previous - } - - target_output - { - // Start with clear output - input none - // Draw a fullscreen quad with the black and white image - pass render_quad - { - // Renders a fullscreen quad with a material - material Ogre/Compositor/ASCII - input 0 rt0 - } - } - } -} - -// Halftone effect -compositor Halftone -{ - technique - { - // Temporary textures - texture rt0 target_width target_height PF_BYTE_RGBA - - target rt0 - { - // Render output from previous compositor (or original scene) - input previous - } - - target_output - { - // Start with clear output - input none - // Draw a fullscreen quad with the black and white image - pass render_quad - { - // Renders a fullscreen quad with a material - material Ogre/Compositor/Halftone - input 0 rt0 - } - } - } -} - -//Night Vision effect -compositor "Night Vision" -{ - technique - { - texture rt0 target_width target_height PF_BYTE_RGBA - - target rt0 - { - input previous - } - - target_output - { - input none - - pass render_quad - { - material Ogre/Compositor/NightVision - input 0 rt0 - } - } - } -} - -//Dither effect -compositor Dither -{ - technique - { - texture rt0 target_width target_height PF_BYTE_RGBA - - target rt0 - { - input previous - } - - target_output - { - input none - - pass render_quad - { - material Ogre/Compositor/Dither - input 0 rt0 - } - } - } -} - -compositor Compute -{ - technique - { - target_output - { - // just do normal rendering - input previous - // execute compute shaders post-render - pass compute - { - material Compute/Compositor - // the texture size is 256x256x1 and we have 16x16x1 threads per group - // so we have to launch 16x16x1 groups - thread_groups 16 16 1 - } - } - } -} - -// abstract node to avoid copy & paste -abstract target CubeFace -{ - visibility_mask 0xF0 // avoid ogrehead in the reflection - pass clear {} - pass render_scene - { - camera CubeMapCamera align_to_face - } -} - -compositor CubeMap -{ - technique - { - texture tex 128 128 PF_BYTE_RGB cubic - target tex 0 : CubeFace {} - target tex 1 : CubeFace {} - target tex 2 : CubeFace {} - target tex 3 : CubeFace {} - target tex 4 : CubeFace {} - target tex 5 : CubeFace {} - - target_output - { - input previous - } - } -} - -compositor Fresnel -{ - technique - { - texture reflection 512 512 PF_BYTE_RGB - texture refraction 512 512 PF_BYTE_RGB - target reflection - { - visibility_mask 0x00F // SURFACE objects - input previous - } - target refraction - { - visibility_mask 0x0F0 // SUBMERGED objects - input previous - } - target_output - { - input previous - } - } -} - -compositor WBOIT -{ - technique - { - texture opaque target_width target_height PF_BYTE_RGBA no_fsaa depth_pool 1 - texture accum target_width target_height PF_FLOAT16_RGBA PF_FLOAT16_R no_fsaa depth_pool 1 - - target opaque - { - pass clear {} - pass render_scene - { - last_render_queue 90 - } - } - - target accum - { - pass clear - { - buffers colour - colour_value 0 0 0 1 - } - pass render_scene - { - // RTSS must use be used for transparents - material_scheme ShaderGeneratorDefaultScheme - first_render_queue 95 - last_render_queue 95 - } - } - - target_output - { - input none - pass clear {} - pass render_quad - { - material Compositor/Copy - input 0 opaque - } - pass render_quad - { - material Compositor/WBOIT - input 0 accum 0 - input 1 accum 1 - } - } - } -} \ No newline at end of file diff --git a/Samples/Media/materials/scripts/Examples.material b/Samples/Media/materials/scripts/Examples.material deleted file mode 100644 index 7650e246181..00000000000 --- a/Samples/Media/materials/scripts/Examples.material +++ /dev/null @@ -1,1494 +0,0 @@ -material Examples/SphereMappedRustySteel -{ - technique - { - pass - { - texture_unit - { - texture RustySteel.jpg - } - - texture_unit - { - texture spheremap.png - colour_op_ex add src_texture src_current - colour_op_multipass_fallback one one - env_map spherical - } - } - } -} - -material Examples/OgreLogo -{ - technique - { - pass - { - ambient 0.8 0.8 0.8 - - texture_unit - { - texture ogrelogo.png - } - } - } -} - -material Examples/BeachStones -{ - technique - { - pass - { - ambient 0.1 0.1 0.1 - - texture_unit - { - texture BeachStones.jpg - } - } - } -} - -material Examples/TrippySkyBox -{ - technique - { - pass - { - lighting off - depth_write off - - texture_unit - { - texture nm.png cubic - tex_address_mode clamp - } - } - } -} - -material Examples/SpaceSkyBox -{ - technique - { - pass - { - lighting off - depth_write off - - texture_unit - { - texture stevecube.jpg cubic - tex_address_mode clamp - } - } - } -} - -material Examples/SceneSkyBox2 -{ - technique - { - pass - { - lighting off - depth_write off - - texture_unit - { - texture studio_garden.jpg cubic - tex_address_mode clamp - } - } - } -} - -material Examples/CloudyNoonSkyBox -{ - technique - { - pass - { - lighting off - depth_write off - - texture_unit - { - texture cloudy_noon.jpg cubic - tex_address_mode clamp - } - } - } -} - -material Examples/StormySkyBox -{ - technique - { - pass - { - lighting off - depth_write off - - texture_unit - { - texture stormy.jpg cubic - tex_address_mode clamp - } - } - } -} - -material Examples/EarlyMorningSkyBox -{ - technique - { - pass - { - lighting off - depth_write off - - texture_unit - { - texture early_morning.jpg cubic - tex_address_mode clamp - } - } - } -} - -material Examples/MorningSkyBox -{ - technique - { - pass - { - lighting off - depth_write off - - texture_unit - { - texture morning.jpg cubic - tex_address_mode clamp - } - } - } - - // HDR technique (fake) - technique - { - // this causes the current FFP technique to be picked - // over the RTSS generated one - // scheme HDR - - pass - { - lighting off - depth_write off - - rtshader_system HDR {} // connect and set the scheme for the RTSS - - texture_unit - { - texture morning.jpg cubic - tex_address_mode clamp - // blow out the light a bit - colour_op_ex modulate src_texture src_manual 1.7 1.7 1.7 - } - } - } -} - -fragment_program Examples/MorningCubeMapHDRfp cg -{ - source hdr.cg - entry_point morningcubemap_fp - profiles ps_2_0 arbfp1 - -} - -material Examples/MorningCubeMap -{ - technique - { - pass - { - lighting off - - texture_unit - { - texture morning.jpg cubic - tex_address_mode clamp - env_map cubic_reflection - } - } - } - // HDR technique (fake) - technique - { - scheme HDR - - pass - { - lighting off - - fragment_program_ref Examples/MorningCubeMapHDRfp - { - } - texture_unit - { - texture morning.jpg cubic - tex_address_mode clamp - env_map cubic_reflection - } - } - } -} - -material Examples/EveningSkyBox -{ - technique - { - pass - { - lighting off - depth_write off - - texture_unit - { - texture evening.jpg cubic - tex_address_mode clamp - } - } - } -} - -material Examples/DynamicCubeMap -{ - technique - { - pass - { - texture_unit - { - content_type compositor CubeMap tex - tex_address_mode clamp - env_map cubic_reflection - } - } - } -} - -material Examples/CloudySky -{ - technique - { - pass - { - lighting off - depth_write off - - texture_unit - { - texture clouds.jpg - scroll_anim 0.15 0 - } - } - } -} - -material Examples/RustySteel -{ - technique - { - pass - { - texture_unit - { - texture RustySteel.jpg - } - } - } -} - -material Examples/Chrome -{ - technique - { - pass - { - texture_unit - { - texture Chrome.jpg - env_map spherical - } - } - } -} - -material Examples/SpaceSkyPlane -{ - technique - { - pass - { - lighting off - depth_write off - - texture_unit - { - texture spacesky.jpg - } - } - } -} - -material Examples/OgreDance -{ - technique - { - pass - { - lighting off - scene_blend alpha_blend - cull_hardware none - - texture_unit - { - anim_texture ogredance.png 8 2 - filtering none - } - } - } -} - -material Examples/OgreParade : Examples/OgreDance -{ - technique - { - pass - { - texture_unit - { - scroll 0.5 0 - scale 0.5 0.5 - scroll_anim 0 0.5 - } - } - } -} - -material Examples/OgreSpin : Examples/OgreDance -{ - technique - { - pass - { - texture_unit - { - texture ogredance_1.png - rotate_anim 0.25 - tex_address_mode clamp - } - } - } -} - -material Examples/OgreWobble : Examples/OgreDance -{ - technique - { - pass - { - texture_unit - { - texture ogredance_6.png - wave_xform scale_x sine 1 1.2 0 0.35 - wave_xform scale_y sine 1 1 0.5 0.25 - tex_address_mode clamp - } - } - } -} - -material Examples/BumpyMetal -{ - technique - { - pass - { - ambient 0.75 0.75 0.75 - - texture_unit - { - texture BumpyMetal.jpg - } - } - } -} - -material Examples/WaterStream -{ - technique - { - pass - { - ambient 0.1 0.1 0.1 - scene_blend add - depth_write off - cull_hardware none - - texture_unit - { - texture Water01.jpg - scroll_anim 0.125 0 - } - - texture_unit - { - texture Water01.jpg - wave_xform scroll_y sine 0 0.1 0 0.25 - } - } - } -} - -material Examples/WaterStream/OIT : Examples/WaterStream -{ - technique - { - pass - { - diffuse 1 1 1 0.9 - rtshader_system - { - weighted_blended_oit on - } - } - } -} - -material Examples/Flare -{ - technique - { - pass - { - lighting off - scene_blend add - depth_write off - diffuse vertexcolour - - texture_unit - { - texture flare.png - } - } - } -} -material Examples/Flare2 -{ - technique - { - pass - { - lighting off - scene_blend add - depth_write off - diffuse vertexcolour - - texture_unit - { - texture flaretrail.png - } - } - } -} -material Examples/Flare3 -{ - technique - { - pass - { - lighting off - scene_blend alpha_blend - depth_write off - diffuse vertexcolour - - texture_unit - { - texture flare_alpha.dds - } - } - } -} -material Examples/FlarePointSprite -{ - technique - { - pass - { - lighting off - scene_blend add - depth_write off - diffuse vertexcolour - - point_sprites on - point_size 2 - point_size_attenuation on - - texture_unit - { - texture flare.png - } - } - } -} - -material Examples/Droplet -{ - technique - { - pass - { - emissive 0.3 0.3 0.3 - scene_blend colour_blend - depth_write off - diffuse vertexcolour - lighting off - - texture_unit - { - texture basic_droplet.png - } - } - } -} -material Examples/Hilite/Yellow -{ - technique - { - pass - { - - texture_unit - { - texture dkyellow.png - } - } - } -} -material Examples/Rocky -{ - technique - { - pass - { - ambient 0.2 0.2 0.2 - - texture_unit - { - texture egyptrockyfull.jpg - } - } - } -} -material Examples/10PointBlock -{ - technique - { - pass - { - - texture_unit - { - texture 10points.png - } - } - } -} -material Material__25 -{ - technique - { - pass - { - - texture_unit - { - texture texmap2.jpg - } - } - } -} -material "2 - Default" -{ - technique - { - pass - { - - texture_unit - { - texture MtlPlat2.jpg - } - } - } -} -material "Material #8" -{ - technique - { - pass - { - - texture_unit - { - texture body.jpg - } - } - } -} -material "Material #3" -{ - technique - { - pass - { - - texture_unit - { - texture head4.jpg - } - } - } -} -material "Material #9" -{ - technique - { - pass - { - - texture_unit - { - texture legs.jpg - } - } - } -} - -material Examples/Fish -{ - technique - { - pass - { - texture_unit - { - texture steelhead.png - } - } - } -} -material Examples/Ninja -{ - technique - { - pass - { - - texture_unit - { - texture nskingr.jpg - } - } - } -} - -material Examples/Robot -{ - technique - { - pass - { - - texture_unit - { - texture r2skin.jpg - } - } - } -} - -material Examples/GrassFloor -{ - technique - { - pass - { - texture_unit - { - texture grass_1024.jpg - } - } - } -} - -vertex_program Examples/GrassWaverVpCg hlsl -{ - source Grass.cg - entry_point grass_vp -} -fragment_program Examples/GrassWaverFpCg hlsl -{ - source Grass.cg - entry_point grass_fp -} -vertex_program Examples/GrassWaverVpGLSL glsl glsles -{ - source GrassVp.glsl -} - -fragment_program Examples/GrassWaverFpGLSL glsl glsles -{ - source GrassFp.glsl - default_params - { - param_named diffuseMap int 0 - } -} - -fragment_program Examples/GrassWaverFp unified -{ - delegate Examples/GrassWaverFpGLSL - delegate Examples/GrassWaverFpCg - default_params - { - param_named_auto alphaThresh surface_alpha_rejection_value - } -} - -vertex_program Examples/GrassWaverVp unified -{ - delegate Examples/GrassWaverVpGLSL - delegate Examples/GrassWaverVpCg - - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto ambient ambient_light_colour - param_named_auto objSpaceLight light_position_object_space 0 - param_named_auto lightColour light_diffuse_colour 0 - - param_named_auto offset custom 999 - } -} - -material Examples/GrassBlades/Caster -{ - technique - { - pass - { - cull_hardware none - alpha_rejection greater 150 - diffuse 0 0 0 - - texture_unit - { - tex_address_mode clamp - texture gras_02.png - } - } - } -} - -material Examples/GrassBlades -{ - transparency_casts_shadows on - receive_shadows on - technique - { - shadow_caster_material Examples/GrassBlades/Caster - pass - { - alpha_rejection greater 150 - cull_hardware none - - texture_unit - { - tex_address_mode clamp - texture gras_02.png - } - } - } -} - -material Examples/GrassBladesWaver : Examples/GrassBlades -{ - technique - { - pass - { - // Vertex program waving grass - vertex_program_ref Examples/GrassWaverVp - { - } - fragment_program_ref Examples/GrassWaverFp - { - } - } - } -} - -material Examples/Rockwall -{ - technique - { - pass - { - texture_unit - { - texture rockwall.tga - } - } - } -} - -material Examples/Aureola -{ - technique - { - pass - { - lighting off - scene_blend alpha_blend - depth_write off - diffuse vertexcolour - cull_hardware none - - texture_unit - { - // FreeImage reads texture as 32 bpp, - // so either texture is 16-bit per - // channel when it should be 8-bit or - // FreeImage has a bug. Either way - // do not set texture type for now. - - //texture aureola.png PF_BYTE_LA - texture aureola.png - tex_address_mode clamp - } - } - } -} - - - -// Test hardware morph animation (no normals) -material Examples/HardwareMorphAnimation -{ - technique - { - pass - { - - vertex_program_ref Ogre/HardwareMorphAnimation - { - // all default - } - fragment_program_ref Ogre/BasicFragmentPrograms/PassthroughFP - { - } - - texture_unit - { - colour_op_ex source1 src_current src_current - } - - } - } -} - -// Test hardware pose animation (no normals) -material Examples/HardwarePoseAnimation -{ - technique - { - pass - { - - vertex_program_ref Ogre/HardwarePoseAnimation - { - // all default - } - fragment_program_ref Ogre/BasicFragmentPrograms/PassthroughFP - { - } - texture_unit - { - tex_coord_set 0 - colour_op_ex source1 src_current src_current - } - - } - } -} - - -// Test hardware morph animation (with normals) -material Examples/HardwareMorphAnimationWithNormals -{ - technique - { - pass - { - - vertex_program_ref Ogre/HardwareMorphAnimationWithNormals - { - // all default - } - fragment_program_ref Ogre/BasicFragmentPrograms/PassthroughFP - { - } - - texture_unit - { - colour_op_ex source1 src_current src_current - } - - } - } -} - -// Test hardware pose animation (no normals) -material Examples/HardwarePoseAnimationWithNormals -{ - technique - { - pass - { - - vertex_program_ref Ogre/HardwarePoseAnimationWithNormals - { - // all default - } - fragment_program_ref Ogre/BasicFragmentPrograms/PassthroughFP - { - } - texture_unit - { - tex_coord_set 0 - colour_op_ex source1 src_current src_current - } - - } - } -} - -material RustyBarrel -{ - technique - { - pass - { - ambient 0.5 0.5 0.5 1.0 - diffuse 1.0 1.0 1.0 1.0 - specular 0.0 0.0 0.0 1.0 12.5 - emissive 0.0 0.0 0.0 1.0 - texture_unit - { - texture RustyBarrel.png - filtering trilinear - } - } - } -} - -material WoodPallet -{ - receive_shadows on - technique - { - pass - { - ambient 0.5 0.5 0.5 1.0 - diffuse 1.0 1.0 1.0 1.0 - specular 0.0 0.0 0.0 1.0 12.5 - - texture_unit - { - texture WoodPallet.png - filtering trilinear - } - } - } -} - -material Examples/LightRibbonTrail -{ - technique - { - pass - { - lighting off - scene_blend add - depth_write off - diffuse vertexcolour - - texture_unit - { - texture ribbonband.png 1d - tex_address_mode clamp - filtering none - } - } - } -} - -material Examples/TudorHouse -{ - technique - { - pass - { - texture_unit - { - texture fw12b.jpg - tex_address_mode clamp - } - } - } -} - -material jaiqua -{ - technique - { - pass - { - texture_unit - { - texture blue_jaiqua.jpg - tex_address_mode clamp - } - - rtshader_system - { - // In case the system uses the RTSS, the following line will ensure - // that hardware animation is used. - // Alternatively, you can derive this information programatically via - // HardwareSkinningFactory::prepareEntityForSkinning - hardware_skinning 38 2 dual_quaternion true false - } - } - } - -} - - -material Examples/Plane/IntegratedShadows -{ - technique - { - pass - { - // Single-pass shadowing - texture_unit - { - texture MtlPlat2.jpg - } - texture_unit - { - // standard modulation blend - content_type shadow - tex_address_mode clamp - } - } - } - -} - -fragment_program Examples/ShowUV_pHLSL hlsl -{ - source Example_Basic.cg - entry_point showuv_p - target ps_2_0 -} - -fragment_program Examples/ShowUV_pGLSL glsl glsles -{ - source ShowUV.glsl -} - -fragment_program Examples/ShowUV_p unified -{ - delegate Examples/ShowUV_pGLSL - delegate Examples/ShowUV_pHLSL -} - -fragment_program Examples/ShowUVdir3D_pHLSL hlsl -{ - source Example_Basic.cg - entry_point showuvdir3d_p - target ps_2_0 -} - -fragment_program Examples/ShowUVdir3D_pGLSL glsl glsles -{ - source ShowUVdir3D.glsl -} - -fragment_program Examples/ShowUVdir3D_p unified -{ - delegate Examples/ShowUVdir3D_pGLSL - delegate Examples/ShowUVdir3D_pHLSL -} - -vertex_program Examples/ShowTangents_vHLSL hlsl -{ - source Example_Basic.cg - entry_point basicPassthroughTangent_v - target vs_2_0 - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -vertex_program Examples/ShowTangents_vGLSL glsl glsles -{ - source ShowTangents.glsl - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -vertex_program Examples/ShowTangents_v unified -{ - delegate Examples/ShowTangents_vGLSL - delegate Examples/ShowTangents_vHLSL -} - -vertex_program Examples/ShowNormals_vHLSL hlsl -{ - source Example_Basic.cg - entry_point basicPassthroughNormal_v - target vs_2_0 - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -vertex_program Examples/ShowNormals_vGLSL glsl glsles -{ - source ShowNormals.glsl - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -vertex_program Examples/ShowNormals_v unified -{ - delegate Examples/ShowNormals_vGLSL - delegate Examples/ShowNormals_vHLSL -} - -material Examples/ShowUV -{ - technique - { - pass - { - vertex_program_ref Ogre/BasicVertexPrograms/AmbientOneTextureWithUV - { - param_named_auto worldViewProj worldviewproj_matrix - } - fragment_program_ref Examples/ShowUV_p - { - } - } - } - - technique - { - pass - { - vertex_program_ref Ogre/BasicVertexPrograms/AmbientOneTextureUnified - { - } - fragment_program_ref Examples/ShowUV_p - { - } - } - } -} -material Examples/ShowTangents -{ - technique - { - pass - { - vertex_program_ref Examples/ShowTangents_v - { - } - fragment_program_ref Examples/ShowUVdir3D_p - { - } - } - } -} -material Examples/ShowNormals -{ - technique - { - pass - { - vertex_program_ref Examples/ShowNormals_v - { - } - fragment_program_ref Examples/ShowUVdir3D_p - { - } - } - } -} - - -material Examples/TransparentTest -{ - technique - { - pass - { - ambient 0.2 0.2 0.2 - scene_blend add - depth_write off - - texture_unit - { - texture Water01.jpg - scroll_anim 0.25 0 - } - - texture_unit - { - texture Water01.jpg - wave_xform scroll_y sine 0 0.1 0 0.5 - } - } - } -} - -material Examples/TextureEffect1 -{ - technique - { - pass - { - ambient 0.75 0.75 0.75 - cull_hardware none - - texture_unit - { - texture BumpyMetal.jpg - rotate_anim 0.2 - wave_xform scale_x sine 1 0.1 0 5 - wave_xform scale_y sine 0.5 0.2 0.5 3 - } - } - } -} -material Examples/TextureEffect2 -{ - technique - { - pass - { - - texture_unit - { - texture Water02.jpg - scroll_anim 0.5 0 - } - } - } -} -material Examples/TextureEffect3 -{ - technique - { - pass - { - ambient 0.7 0.7 0.7 - cull_hardware none - - texture_unit - { - texture Water01.jpg - scroll_anim -0.25 0.1 - } - - texture_unit - { - texture Water01.jpg - colour_op_ex add src_texture src_current - colour_op_multipass_fallback one one - scroll_anim -0.1 0.25 - } - } - } -} -material Examples/TextureEffect4 -{ - technique - { - pass - { - ambient 0.3 0.3 0.3 - scene_blend colour_blend - cull_hardware none - - texture_unit - { - texture Water02.jpg - scroll_anim 0.01 0.01 - } - } - } -} - -material Examples/EnvMappedRustySteel -{ - technique - { - pass - { - - texture_unit - { - texture RustySteel.jpg - } - - texture_unit - { - texture spheremap.png - colour_op_ex add src_texture src_current - colour_op_multipass_fallback one one - env_map spherical - } - } - } -} - -material Examples/TransparentBlue50 -{ - technique - { - pass - { - scene_blend alpha_blend - depth_write off - - texture_unit - { - colour_op_ex source1 src_manual src_current 0 0 1 - alpha_op_ex source1 src_manual src_current 0.5 - } - } - } -} - -// material Examples/Passthrough -// { -// technique -// { -// pass -// { -// diffuse vertexcolour -// specular vertexcolour -// ambient vertexcolour -// lighting off -// } -// } -// } - -material DebugSphere1000 -{ - technique - { - } -} - -material Examples/WoodenFloor -{ - technique - { - pass - { - texture_unit - { - texture WoodFloor043_1K_Color.jpg - } - rtshader_system - { - lighting_stage metal_roughness texture WoodFloor043_1K_MetalRoughness.jpg - lighting_stage normal_map WoodFloor043_1K_NormalGL.jpg - } - } - } -} - -material Examples/PBR_Sphere -{ - technique - { - pass - { - rtshader_system - { - lighting_stage metal_roughness - } - } - } -} - -material TestLevel_b0_m0/TEXFACE/Grass.jpg -{ - receive_shadows on - technique - { - pass - { - ambient 0.500000 0.500000 0.500000 1.000000 - diffuse 0.800000 0.800000 0.800000 1.000000 - texture_unit - { - texture grass_1024.jpg - } - } - } -} -material TestLevel_b0_m0/TEXFACE/Soil.jpg -{ - receive_shadows on - technique - { - pass - { - ambient 0.500000 0.500000 0.500000 1.000000 - diffuse 0.800000 0.800000 0.800000 1.000000 - texture_unit - { - texture egyptrockyfull.jpg - } - } - } -} \ No newline at end of file diff --git a/Samples/Media/materials/scripts/Examples.program b/Samples/Media/materials/scripts/Examples.program deleted file mode 100644 index 776c366c6a1..00000000000 --- a/Samples/Media/materials/scripts/Examples.program +++ /dev/null @@ -1,358 +0,0 @@ -//--------------------------------------------------- -// This file includes a number of basic GPU programs -// for use in many materials. -//--------------------------------------------------- - - -// A really basic ambient pass program, support for one texture coordinate set -vertex_program Ogre/BasicVertexPrograms/AmbientOneTextureCg cg -{ - source Example_Basic.cg - entry_point ambientOneTexture_vp - profiles vs_1_1 arbvp1 - - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto ambient ambient_light_colour - } - -} - -// A really basic ambient pass program, support for one texture coordinate set -vertex_program Ogre/BasicVertexPrograms/AmbientOneTextureHLSL hlsl -{ - source Example_Basic.cg - entry_point ambientOneTexture_vp - target vs_2_0 - - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto ambient ambient_light_colour - } -} - -// A really basic ambient pass program, support for one texture coordinate set -vertex_program Ogre/BasicVertexPrograms/AmbientOneTextureGLSL glsl glsles -{ - source AmbientOneTexture.glsl - - default_params - { - param_named_auto ambient ambient_light_colour - param_named_auto worldViewProj worldviewproj_matrix - } -} - -vertex_program Ogre/BasicVertexPrograms/AmbientOneTextureWithUVGLSL glsl glsles -{ - source AmbientOneTextureWithUV.glsl - - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto ambient ambient_light_colour - } -} - -vertex_program Ogre/BasicVertexPrograms/AmbientOneTextureWithUV unified -{ - delegate Ogre/BasicVertexPrograms/AmbientOneTextureWithUVGLSL - delegate Ogre/BasicVertexPrograms/AmbientOneTextureHLSL - delegate Ogre/BasicVertexPrograms/AmbientOneTextureCg -} - -vertex_program Ogre/BasicVertexPrograms/AmbientOneTextureUnified unified -{ - delegate Ogre/BasicVertexPrograms/AmbientOneTextureGLSL - delegate Ogre/BasicVertexPrograms/AmbientOneTextureHLSL - delegate Ogre/BasicVertexPrograms/AmbientOneTextureCg -} - -fragment_program Ogre/BasicFragmentPrograms/DiffuseOneTextureCg cg -{ - source Example_Basic.cg - entry_point diffuseOneTexture_fp - profiles ps_2_0 arbfp1 -} - -fragment_program Ogre/BasicFragmentPrograms/DiffuseOneTextureHLSL hlsl -{ - source Example_Basic.cg - entry_point diffuseOneTexture_fp - target ps_2_0 -} - -fragment_program Ogre/BasicFragmentPrograms/DiffuseOneTextureGLSL glsl glsles -{ - source DiffuseOneTexture.glsl - default_params - { - param_named texMap int 0 - } -} - -fragment_program Ogre/BasicFragmentPrograms/DiffuseOneTexture unified -{ - delegate Ogre/BasicFragmentPrograms/DiffuseOneTextureGLSL - delegate Ogre/BasicFragmentPrograms/DiffuseOneTextureHLSL - delegate Ogre/BasicFragmentPrograms/DiffuseOneTextureCg -} - -// A really basic ambient pass program, support for one texture coordinate set -fragment_program Ogre/BasicFragmentPrograms/PassthroughFP unified -{ - delegate Ogre/BasicFragmentPrograms/PassthroughFpGLSL - delegate Ogre/BasicFragmentPrograms/PassthroughFpHLSL - delegate Ogre/BasicFragmentPrograms/PassthroughFpCgSm4 - delegate Ogre/BasicFragmentPrograms/PassthroughFpCg -} - -// A really basic ambient pass program, support for one texture coordinate set -fragment_program Ogre/BasicFragmentPrograms/PassthroughFpCgSm4 cg -{ - source PassthroughFP_sm4.cg - profiles ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 -} - -// A really basic ambient pass program, support for one texture coordinate set -fragment_program Ogre/BasicFragmentPrograms/PassthroughFpHLSL hlsl -{ - source PassthroughFP_sm4.hlsl - target ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 -} - - -fragment_program Ogre/BasicFragmentPrograms/PassthroughFpCg cg -{ - entry_point mainCg - source PassthroughFP.cg - profiles ps_2_0 arbfp1 -} - -// A really basic ambient pass program, support for one texture coordinate set -fragment_program Ogre/BasicFragmentPrograms/PassthroughFpCgSm4ForAmbientOneTexture cg -{ - entry_point mainForAmbientOneTexture - source PassthroughFP_sm4.cg - profiles ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 -} - - -// A really basic ambient pass program, support for one texture coordinate set -fragment_program Ogre/BasicFragmentPrograms/PassthroughFpGLSL glsl glsles -{ - source PassthroughFP.glsl -} - -// Basic hardware morph animation (no normals) -vertex_program Ogre/HardwareMorphAnimationCg cg -{ - source Example_Basic.cg - entry_point hardwareMorphAnimation - profiles vs_4_0 vs_4_0_level_9_1 vs_4_0_level_9_3 vs_1_1 arbvp1 - - includes_morph_animation true - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto anim_t animation_parametric - } -} - -// Basic hardware morph animation (no normals) -vertex_program Ogre/HardwareMorphAnimationHLSL hlsl -{ - source Example_Basic.cg - entry_point hardwareMorphAnimation - target vs_4_0 vs_4_0_level_9_1 vs_4_0_level_9_3 - - includes_morph_animation true - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto anim_t animation_parametric - } -} - -// Basic hardware morph animation (no normals) -vertex_program Ogre/HardwareMorphAnimationGLSL glsl glsles -{ - source HardwareMorphAnimationVp.glsl - - includes_morph_animation true - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto anim_t animation_parametric - } -} - -vertex_program Ogre/HardwareMorphAnimation unified -{ - delegate Ogre/HardwareMorphAnimationHLSL - delegate Ogre/HardwareMorphAnimationCg - delegate Ogre/HardwareMorphAnimationGLSL -} - -// Basic hardware pose animation supporting 2 active poses (no normals) -vertex_program Ogre/HardwarePoseAnimationCg cg -{ - source Example_Basic.cg - entry_point hardwarePoseAnimation - profiles vs_4_0 vs_4_0_level_9_1 vs_4_0_level_9_3 vs_1_1 arbvp1 - - includes_pose_animation 2 - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto anim_t animation_parametric - } -} - -// Basic hardware pose animation supporting 2 active poses (no normals) -vertex_program Ogre/HardwarePoseAnimationHLSL hlsl -{ - source Example_Basic.cg - entry_point hardwarePoseAnimation - target vs_4_0 vs_4_0_level_9_1 vs_4_0_level_9_3 - - includes_pose_animation 2 - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto anim_t animation_parametric - } -} - -// Basic hardware pose animation supporting 2 active poses (no normals) -vertex_program Ogre/HardwarePoseAnimationGLSL glsl glsles -{ - source HardwarePoseAnimationVp.glsl - - includes_pose_animation 2 - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto anim_t animation_parametric - } -} -vertex_program Ogre/HardwarePoseAnimation unified -{ - delegate Ogre/HardwarePoseAnimationHLSL - delegate Ogre/HardwarePoseAnimationCg - delegate Ogre/HardwarePoseAnimationGLSL -} - -// Basic hardware morph animation (with normals) -vertex_program Ogre/HardwareMorphAnimationWithNormalsCg cg -{ - source Example_Basic.cg - entry_point hardwareMorphAnimationWithNormals - profiles vs_4_0 vs_4_0_level_9_1 vs_4_0_level_9_3 vs_1_1 arbvp1 - - includes_morph_animation true - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto anim_t animation_parametric - param_named_auto objSpaceLightPos light_position_object_space 0 - param_named_auto ambient ambient_light_colour - } -} - -// Basic hardware morph animation (with normals) -vertex_program Ogre/HardwareMorphAnimationWithNormalsHLSL hlsl -{ - source Example_Basic.cg - entry_point hardwareMorphAnimationWithNormals - target vs_4_0 vs_4_0_level_9_1 vs_4_0_level_9_3 - - includes_morph_animation true - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto anim_t animation_parametric - param_named_auto objSpaceLightPos light_position_object_space 0 - param_named_auto ambient ambient_light_colour - } -} - -// Basic hardware morph animation (with normals) -vertex_program Ogre/HardwareMorphAnimationWithNormalsGLSL glsl glsles -{ - source HardwareMorphAnimationWithNormalsVp.glsl - - includes_morph_animation true - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto anim_t animation_parametric - param_named_auto objSpaceLightPos light_position_object_space 0 - param_named_auto ambient ambient_light_colour - } -} - -vertex_program Ogre/HardwareMorphAnimationWithNormals unified -{ - delegate Ogre/HardwareMorphAnimationWithNormalsHLSL - delegate Ogre/HardwareMorphAnimationWithNormalsCg - delegate Ogre/HardwareMorphAnimationWithNormalsGLSL -} - -// Basic hardware pose animation supporting 2 active poses (with normals) -vertex_program Ogre/HardwarePoseAnimationWithNormalsHLSL hlsl -{ - source Example_Basic.cg - entry_point hardwarePoseAnimationWithNormals - target vs_4_0 vs_4_0_level_9_1 vs_4_0_level_9_3 - - includes_pose_animation 2 - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto anim_t animation_parametric - param_named_auto objSpaceLightPos light_position_object_space 0 - param_named_auto ambient ambient_light_colour - } -} - -// Basic hardware pose animation supporting 2 active poses (with normals) -vertex_program Ogre/HardwarePoseAnimationWithNormalsCg cg -{ - source Example_Basic.cg - entry_point hardwarePoseAnimationWithNormals - profiles vs_4_0 vs_4_0_level_9_1 vs_4_0_level_9_3 vs_1_1 arbvp1 - - includes_pose_animation 2 - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto anim_t animation_parametric - param_named_auto objSpaceLightPos light_position_object_space 0 - param_named_auto ambient ambient_light_colour - } -} - -// Basic hardware pose animation supporting 2 active poses (with normals) -vertex_program Ogre/HardwarePoseAnimationWithNormalsGLSL glsl glsles -{ - source HardwarePoseAnimationWithNormalsVp.glsl - - includes_pose_animation 2 - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto anim_t animation_parametric - param_named_auto objSpaceLightPos light_position_object_space 0 - param_named_auto ambient ambient_light_colour - } -} - -vertex_program Ogre/HardwarePoseAnimationWithNormals unified -{ - delegate Ogre/HardwarePoseAnimationWithNormalsHLSL - delegate Ogre/HardwarePoseAnimationWithNormalsCg - delegate Ogre/HardwarePoseAnimationWithNormalsGLSL -} diff --git a/Samples/Media/materials/scripts/FluidSim.material b/Samples/Media/materials/scripts/FluidSim.material deleted file mode 100644 index 06986d9de69..00000000000 --- a/Samples/Media/materials/scripts/FluidSim.material +++ /dev/null @@ -1,861 +0,0 @@ -/*vertex_program Ogre/FluidSim/VS_GRID hlsl -{ - source HairFluidSim.hlsl - entry_point VS_GRID - target vs_4_0 - - default_params - { - param_named g_textureWidth float 0.0 - param_named g_textureHeight float 0.0 - param_named g_textureDepth float 0.0 - } -} - -geometry_program Ogre/FluidSim/GS_ARRAY hlsl -{ - source HairFluidSim.hlsl - entry_point GS_ARRAY - target gs_4_0 - - default_params - { - - } -} - - -fragment_program Ogre/FluidSim/PS_ADVECT_MACCORMACK hlsl -{ - source HairFluidSim.hlsl - entry_point PS_ADVECT_MACCORMACK - target ps_4_0 - - default_params - { - param_named g_advectAsTemperature int 0 - param_named g_treatAsLiquidVelocity int 0 - param_named g_textureWidth float 0.0 - param_named g_textureHeight float 0.0 - param_named g_textureDepth float 0.0 - param_named g_timestep float 0.0 - param_named g_decay float 0.0 - param_named g_temperatureLoss float 0.0 - } -} - -fragment_program Ogre/FluidSim/PS_ADVECT hlsl -{ - source HairFluidSim.hlsl - entry_point PS_ADVECT - target ps_4_0 - - default_params - { - param_named g_advectAsTemperature int 0 - param_named g_treatAsLiquidVelocity int 0 - param_named g_textureWidth float 0.0 - param_named g_textureHeight float 0.0 - param_named g_textureDepth float 0.0 - param_named g_timestep float 0.0 - param_named g_decay float 0.0 - param_named g_temperatureLoss float 0.0 - } -} - -fragment_program Ogre/FluidSim/PS_VORTICITY hlsl -{ - source HairFluidSim.hlsl - entry_point PS_VORTICITY - target ps_4_0 - - default_params - { - - } -} - -fragment_program Ogre/FluidSim/PS_CONFINEMENT hlsl -{ - source HairFluidSim.hlsl - entry_point PS_CONFINEMENT - target ps_4_0 - - default_params - { - param_named g_treatAsLiquidVelocity int 0 - param_named g_timestep float 0.0 - param_named g_vortConfinementScale float 0.0 - } -} - -fragment_program Ogre/FluidSim/PS_DIFFUSE hlsl -{ - source HairFluidSim.hlsl - entry_point PS_DIFFUSE - target ps_4_0 - - default_params - { - param_named g_timestep float 0.0 - param_named g_viscosity float 0.0 - } -} - -fragment_program Ogre/FluidSim/PS_DIVERGENCE hlsl -{ - source HairFluidSim.hlsl - entry_point PS_DIVERGENCE - target ps_4_0 - - default_params - { - - } -} - -fragment_program Ogre/FluidSim/PS_SCALAR_JACOBI hlsl -{ - source HairFluidSim.hlsl - entry_point PS_SCALAR_JACOBI - target ps_4_0 - - default_params - { - - } -} - -fragment_program Ogre/FluidSim/PS_PROJECT hlsl -{ - source HairFluidSim.hlsl - entry_point PS_PROJECT - target ps_4_0 - - default_params - { - param_named g_treatAsLiquidVelocity int 0 - } -} - -fragment_program Ogre/FluidSim/PS_SIGNED_DISTANCE_TO_LIQUIDHEIGHT hlsl -{ - source HairFluidSim.hlsl - entry_point PS_SIGNED_DISTANCE_TO_LIQUIDHEIGHT - target ps_4_0 - - default_params - { - - } -} - -fragment_program Ogre/FluidSim/PS_INJECT_LIQUID hlsl -{ - source HairFluidSim.hlsl - entry_point PS_INJECT_LIQUID - target ps_4_0 - - default_params - { - - } -} - -fragment_program Ogre/FluidSim/PS_APPLY_AIR_PRESSURE hlsl -{ - source HairFluidSim.hlsl - entry_point PS_APPLY_AIR_PRESSURE - target ps_4_0 - - default_params - { - param_named g_treatAsLiquidVelocity int 0 - } -} - -fragment_program Ogre/FluidSim/PS_REDISTANCING hlsl -{ - source HairFluidSim.hlsl - entry_point PS_REDISTANCING - target ps_4_0 - - default_params - { - param_named g_textureWidth float 0.0 - param_named g_textureHeight float 0.0 - param_named g_textureDepth float 0.0 - } -} - -fragment_program Ogre/FluidSim/PS_EXTRAPOLATE_VELOCITY hlsl -{ - source HairFluidSim.hlsl - entry_point PS_EXTRAPOLATE_VELOCITY - target ps_4_0 - - default_params - { - param_named g_treatAsLiquidVelocity int 0 - param_named g_textureWidth float 0.0 - param_named g_textureHeight float 0.0 - param_named g_textureDepth float 0.0 - } -} - -fragment_program Ogre/FluidSim/PS_LIQUID_STREAM hlsl -{ - source HairFluidSim.hlsl - entry_point PS_LIQUID_STREAM - target ps_4_0 - - default_params - { - param_named g_radius float 0.0 - param_named g_center float 0.0 - param_named g_color float 0.0 - } -} - -fragment_program Ogre/FluidSim/PS_APPLY_GRAVITY hlsl -{ - source HairFluidSim.hlsl - entry_point PS_APPLY_GRAVITY - target ps_4_0 - - default_params - { - param_named g_treatAsLiquidVelocity int 0 - param_named g_gravity float 9.8 - } -} - -fragment_program Ogre/FluidSim/PS_GAUSSIAN hlsl -{ - source HairFluidSim.hlsl - entry_point PS_GAUSSIAN - target ps_4_0 - - default_params - { - param_named g_radius float 0.0 - param_named g_center float 0.0 - param_named g_color float 0.0 - } -} - -fragment_program Ogre/FluidSim/PS_COPY_TEXURE hlsl -{ - source HairFluidSim.hlsl - entry_point PS_COPY_TEXURE - target ps_4_0 - - default_params - { - param_named g_color float 0.0 - } -} - -fragment_program Ogre/FluidSim/PS_ADD_DERIVATIVE_VEL hlsl -{ - source HairFluidSim.hlsl - entry_point PS_ADD_DERIVATIVE_VEL - target ps_4_0 - - default_params - { - param_named g_color float 0.0 - } -} - -fragment_program Ogre/FluidSim/PS_ADD_DERIVATIVE_VEL hlsl -{ - source HairFluidSim.hlsl - entry_point PS_ADD_DERIVATIVE_VEL - target ps_4_0 - - default_params - { - - } -} - -fragment_program Ogre/FluidSim/PS_ADD_DERIVATIVE_VEL hlsl -{ - source HairFluidSim.hlsl - entry_point PS_ADD_DERIVATIVE_VEL - target ps_4_0 - - default_params - { - - } -} - -fragment_program Ogre/FluidSim/PS_ADD_DERIVATIVE_VEL hlsl -{ - source HairFluidSim.hlsl - entry_point PS_ADD_DERIVATIVE_VEL - target ps_4_0 - - default_params - { - - } -} - -fragment_program Ogre/FluidSim/PS_STATIC_OBSTACLE hlsl -{ - source HairFluidSim.hlsl - entry_point PS_STATIC_OBSTACLE - target ps_4_0 - - default_params - { - - } -} - -fragment_program Ogre/FluidSim/PS_DYNAMIC_OBSTACLE_BOX hlsl -{ - source HairFluidSim.hlsl - entry_point PS_DYNAMIC_OBSTACLE_BOX - target ps_4_0 - - default_params - { - param_named g_obstBoxVelocity float4 0.0 0.0 0.0 0.0 - param_named g_obstBoxRTUcorner float4 0.0 0.0 0.0 0.0 - param_named g_obstBoxLBDcorner float4 0.0 0.0 0.0 0.0 - } -} - -fragment_program Ogre/FluidSim/PS_DRAW_TEXTURE hlsl -{ - source HairFluidSim.hlsl - entry_point PS_DRAW_TEXTURE - target ps_4_0 - - default_params - { - param_named g_drawTextureNumber int 1 - param_named g_textureDepth float 0.0 - param_named g_color float 0.0 - } -} - -material Ogre/FluidSim -{ - technique AdvectMACCORMACK - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_ADVECT_MACCORMACK - { - - } - - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } - technique Advect - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_ADVECT - { - - } - - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } - technique Vorticity - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_VORTICITY - { - - } - - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } - technique Confinement - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_CONFINEMENT - { - - } - scene_blend add - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } - technique Diffuse - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_DIFFUSE - { - - } - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } - technique Divergence - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_DIVERGENCE - { - - } - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } - technique ScalarJacobi - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_SCALAR_JACOBI - { - - } - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } - technique Project - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_PROJECT - { - - } - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } - technique InitLevelSetToLiquidHeight - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_SIGNED_DISTANCE_TO_LIQUIDHEIGHT - { - - } - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } - technique InjectLiquid - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_INJECT_LIQUID - { - - } - scene_blend add - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } - technique AirPressure - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_APPLY_AIR_PRESSURE - { - - } - scene_blend add - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } - technique Redistance - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_REDISTANCING - { - - } - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } - technique ExtrapolateVelocity - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_EXTRAPOLATE_VELOCITY - { - - } - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } - technique LiquidStream_LevelSet - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_LIQUID_STREAM - { - - } - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } - technique LiquidStream_Velocity - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_LIQUID_STREAM - { - - } - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } - technique Gravity - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_APPLY_GRAVITY - { - - } - scene_blend add - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } - technique Gaussian - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_GAUSSIAN - { - - } - scene_blend add - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } - technique CopyTexture - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_COPY_TEXURE - { - - } - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } - technique AddDerivativeVelocity - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_ADD_DERIVATIVE_VEL - { - - } - scene_blend add - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } - technique StaticObstacleTriangles - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_STATIC_OBSTACLE - { - - } - cull_hardware none - cull_software back - depth_check off - depth_write off - } - } - technique StaticObstacleLines - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_STATIC_OBSTACLE - { - - } - cull_hardware none - cull_software back - depth_check off - depth_write off - } - } - technique DynamicObstacleBox - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - geometry_program_ref Ogre/FluidSim/GS_ARRAY - { - - } - fragment_program_ref Ogre/FluidSim/PS_DYNAMIC_OBSTACLE_BOX - { - - } - cull_hardware none - cull_software back - depth_check off - depth_write off - } - } - technique DrawTexture - { - pass - { - vertex_program_ref Ogre/FluidSim/VS_GRID - { - - } - - fragment_program_ref Ogre/FluidSim/PS_DRAW_TEXTURE - { - - } - cull_hardware none - cull_software none - depth_check off - depth_write off - } - } -}*/ \ No newline at end of file diff --git a/Samples/Media/materials/scripts/Glass.material b/Samples/Media/materials/scripts/Glass.material deleted file mode 100644 index 98b0bce3d53..00000000000 --- a/Samples/Media/materials/scripts/Glass.material +++ /dev/null @@ -1,56 +0,0 @@ -fragment_program Ogre/Compositor/GlassFP_cg hlsl -{ - source GlassFP.cg - entry_point main_ps -} - -fragment_program Ogre/Compositor/GlassFP_glsl glsl glsles -{ - source GlassFP.glsl - default_params - { - param_named RT int 0 - param_named NormalMap int 1 - } -} - -fragment_program Ogre/Compositor/GlassFP unified -{ - delegate Ogre/Compositor/GlassFP_glsl - delegate Ogre/Compositor/GlassFP_cg -} - -material Ogre/Compositor/GlassPass -{ - technique - { - pass - { - depth_check off - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_Tex2a_vp - { - } - - fragment_program_ref Ogre/Compositor/GlassFP - { - } - - texture_unit RT - { - tex_coord_set 0 - tex_address_mode clamp - filtering linear linear linear - } - - texture_unit - { - texture WaterNormal1.tga 2d - tex_coord_set 1 - //tex_address_mode clamp - filtering linear linear linear - } - } - } -} diff --git a/Samples/Media/materials/scripts/HWInstancing.material b/Samples/Media/materials/scripts/HWInstancing.material deleted file mode 100644 index c806ede3332..00000000000 --- a/Samples/Media/materials/scripts/HWInstancing.material +++ /dev/null @@ -1,67 +0,0 @@ -//--------------------------------------------------------------------------- -//These materials/shaders are part of the NEW InstanceManager implementation -//Written by Matias N. Goldberg ("dark_sylinc") -//--------------------------------------------------------------------------- - -material Examples/Instancing/HWBasic/shadow_caster -{ - technique - { - pass - { - rtshader_system - { - lighting_stage gbuffer depth - transform_stage instanced - } - } - } -} - -material Examples/Instancing/HWBasic/Robot -{ - technique - { - shadow_caster_material Examples/Instancing/HWBasic/shadow_caster - - pass - { - specular 1 1 1 1 12.5 - - texture_unit Diffuse - { - texture r2skin.jpg - } - - rtshader_system - { - transform_stage instanced - } - } - } -} - -material Examples/Instancing/HWBasic/spine -{ - technique - { - shadow_caster_material Examples/Instancing/HWBasic/shadow_caster - - pass - { - diffuse 0.3 0.3 0.3 - specular 0.1 0.1 0.1 0.1 12.5 - - texture_unit Diffuse - { - texture circuit.dds - tex_address_mode clamp - } - - rtshader_system - { - transform_stage instanced - } - } - } -} \ No newline at end of file diff --git a/Samples/Media/materials/scripts/HW_VTFInstancing.material b/Samples/Media/materials/scripts/HW_VTFInstancing.material deleted file mode 100644 index f1fd19c077a..00000000000 --- a/Samples/Media/materials/scripts/HW_VTFInstancing.material +++ /dev/null @@ -1,427 +0,0 @@ -//--------------------------------------------------------------------------- -//These materials/shaders are part of the NEW InstanceManager implementation -//Written by Matias N. Goldberg ("dark_sylinc") -//--------------------------------------------------------------------------- - -//-------------------------------------------------------------- -// GLSL Programs -//-------------------------------------------------------------- -vertex_program Ogre/Instancing/HW_VTF_glsl_vs glsl glsles -{ - source HW_VTFInstancing.vert - - preprocessor_defines DEPTH_SHADOWRECEIVER=1 - - uses_vertex_texture_fetch true - - default_params - { - param_named matrixTexture int 2 - } -} - -vertex_program Ogre/Instancing/VTF/HW/shadow_caster_glsl_vs glsl glsles -{ - source HW_VTFInstancing.vert - - preprocessor_defines DEPTH_SHADOWCASTER=1 - - uses_vertex_texture_fetch true - - default_params - { - param_named matrixTexture int 0 - } -} - -vertex_program Ogre/Instancing/HW_VTF_dq_glsl_vs glsl glsles -{ - source HW_VTFInstancing.vert - - preprocessor_defines ST_DUAL_QUATERNION,DEPTH_SHADOWRECEIVER=1 - - uses_vertex_texture_fetch true - - default_params - { - param_named matrixTexture int 2 - } -} - -vertex_program Ogre/Instancing/VTF/HW/shadow_caster_dq_glsl_vs glsl glsles -{ - source HW_VTFInstancing.vert - - preprocessor_defines ST_DUAL_QUATERNION,DEPTH_SHADOWCASTER=1 - - uses_vertex_texture_fetch true - - default_params - { - param_named matrixTexture int 0 - } -} - -vertex_program Ogre/Instancing/HW_VTF_dq_two_weights_glsl_vs glsl glsles -{ - source HW_VTFInstancing.vert - - preprocessor_defines ST_DUAL_QUATERNION,BONE_TWO_WEIGHTS,DEPTH_SHADOWRECEIVER=1 - - uses_vertex_texture_fetch true - - default_params - { - param_named matrixTexture int 2 - } -} - -vertex_program Ogre/Instancing/VTF/HW/shadow_caster_dq_two_weights_glsl_vs glsl glsles -{ - source HW_VTFInstancing.vert - - preprocessor_defines ST_DUAL_QUATERNION,BONE_TWO_WEIGHTS,DEPTH_SHADOWCASTER=1 - - uses_vertex_texture_fetch true - - default_params - { - param_named matrixTexture int 0 - } -} - -//-------------------------------------------------------------- -// hlsl Programs -//-------------------------------------------------------------- -vertex_program Ogre/Instancing/HW_VTF_hlsl_vs hlsl -{ - source HW_VTFInstancing.cg - entry_point main_vs - target vs_3_0 - - preprocessor_defines DEPTH_SHADOWRECEIVER - - uses_vertex_texture_fetch true -} - -vertex_program Ogre/Instancing/VTF/HW/shadow_caster_hlsl_vs hlsl -{ - source HW_VTFInstancing.cg - entry_point main_vs - target vs_3_0 - - preprocessor_defines DEPTH_SHADOWCASTER - - uses_vertex_texture_fetch true -} - -vertex_program Ogre/Instancing/HW_VTF_dq_hlsl_vs hlsl -{ - source HW_VTFInstancing.cg - entry_point main_vs - target vs_3_0 - - preprocessor_defines DEPTH_SHADOWRECEIVER,ST_DUAL_QUATERNION - - uses_vertex_texture_fetch true -} - -vertex_program Ogre/Instancing/VTF/HW/shadow_caster_dq_hlsl_vs hlsl -{ - source HW_VTFInstancing.cg - entry_point main_vs - target vs_3_0 - - preprocessor_defines DEPTH_SHADOWCASTER,ST_DUAL_QUATERNION - - uses_vertex_texture_fetch true -} - -vertex_program Ogre/Instancing/HW_VTF_dq_two_weights_hlsl_vs hlsl -{ - source HW_VTFInstancing.cg - entry_point main_vs - target vs_3_0 - - preprocessor_defines DEPTH_SHADOWRECEIVER,ST_DUAL_QUATERNION,BONE_TWO_WEIGHTS - - uses_vertex_texture_fetch true -} - -vertex_program Ogre/Instancing/VTF/HW/shadow_caster_dq_two_weights_hlsl_vs hlsl -{ - source HW_VTFInstancing.cg - entry_point main_vs - target vs_3_0 - - preprocessor_defines DEPTH_SHADOWCASTER,ST_DUAL_QUATERNION,BONE_TWO_WEIGHTS - - uses_vertex_texture_fetch true -} - -//-------------------------------------------------------------- -// Unified CG/GLSL Programs -//-------------------------------------------------------------- -vertex_program Ogre/Instancing/HW_VTF_vs unified -{ - delegate Ogre/Instancing/HW_VTF_glsl_vs - delegate Ogre/Instancing/HW_VTF_hlsl_vs - - default_params - { - param_named_auto viewProjMatrix viewproj_matrix - param_named_auto texViewProjMatrix texture_viewproj_matrix 0 - } -} - -vertex_program Ogre/Instancing/VTF/HW/shadow_caster_vs unified -{ - delegate Ogre/Instancing/VTF/HW/shadow_caster_glsl_vs - delegate Ogre/Instancing/VTF/HW/shadow_caster_hlsl_vs - - default_params - { - param_named_auto viewProjMatrix viewproj_matrix - } -} - -vertex_program Ogre/Instancing/HW_VTF_dq_vs unified -{ - delegate Ogre/Instancing/HW_VTF_dq_glsl_vs - delegate Ogre/Instancing/HW_VTF_dq_hlsl_vs - - default_params - { - param_named_auto viewProjMatrix viewproj_matrix - param_named_auto texViewProjMatrix texture_viewproj_matrix 0 - } -} - -vertex_program Ogre/Instancing/VTF/HW/shadow_caster_dq_vs unified -{ - delegate Ogre/Instancing/VTF/HW/shadow_caster_dq_glsl_vs - delegate Ogre/Instancing/VTF/HW/shadow_caster_dq_hlsl_vs - - default_params - { - param_named_auto viewProjMatrix viewproj_matrix - } -} - -vertex_program Ogre/Instancing/HW_VTF_dq_two_weights_vs unified -{ - delegate Ogre/Instancing/HW_VTF_dq_two_weights_glsl_vs - delegate Ogre/Instancing/HW_VTF_dq_two_weights_hlsl_vs - - default_params - { - param_named_auto viewProjMatrix viewproj_matrix - param_named_auto texViewProjMatrix texture_viewproj_matrix 0 - } -} - -vertex_program Ogre/Instancing/VTF/HW/shadow_caster_dq_two_weights_vs unified -{ - delegate Ogre/Instancing/VTF/HW/shadow_caster_dq_two_weights_glsl_vs - delegate Ogre/Instancing/VTF/HW/shadow_caster_dq_two_weights_hlsl_vs - - default_params - { - param_named_auto viewProjMatrix viewproj_matrix - } -} - -material Examples/Instancing/VTF/HW/shadow_caster -{ - technique - { - pass - { - vertex_program_ref Ogre/Instancing/VTF/HW/shadow_caster_vs - { - } - fragment_program_ref Ogre/Instancing/shadow_caster_ps - { - } - - texture_unit InstancingVTF - { - filtering none - } - } - } -} - -material Examples/Instancing/VTF/HW/shadow_caster_dq -{ - technique - { - pass - { - vertex_program_ref Ogre/Instancing/VTF/HW/shadow_caster_dq_vs - { - } - fragment_program_ref Ogre/Instancing/shadow_caster_ps - { - } - - texture_unit InstancingVTF - { - filtering none - } - } - } -} - -material Examples/Instancing/VTF/HW/shadow_caster_dq_two_weights -{ - technique - { - pass - { - vertex_program_ref Ogre/Instancing/VTF/HW/shadow_caster_dq_two_weights_vs - { - param_named_auto viewProjMatrix viewproj_matrix - } - fragment_program_ref Ogre/Instancing/shadow_caster_ps - { - } - - texture_unit InstancingVTF - { - filtering none - } - } - } -} - -abstract material Examples/Instancing/HW_VTF -{ - technique - { - shadow_caster_material Examples/Instancing/VTF/HW/shadow_caster - - pass - { - specular 1 1 1 1 12.5 - vertex_program_ref Ogre/Instancing/HW_VTF_vs - { - } - - fragment_program_ref Ogre/Instancing_ps - { - } - - texture_unit Diffuse - { - texture $DiffuseMap - } - - texture_unit shadow0 - { - content_type shadow - tex_address_mode border - tex_border_colour 1 1 1 1 - } - - texture_unit InstancingVTF - { - filtering none - } - } - } -} - -material Examples/Instancing/VTF/HW/Robot : Examples/Instancing/HW_VTF -{ - set $DiffuseMap r2skin.jpg -} - -abstract material Examples/Instancing/HW_VTF_dq -{ - technique - { - shadow_caster_material Examples/Instancing/VTF/HW/shadow_caster_dq - - pass - { - specular 1 1 1 1 12.5 - - vertex_program_ref Ogre/Instancing/HW_VTF_dq_vs - { - } - - fragment_program_ref Ogre/Instancing_ps - { - } - - texture_unit Diffuse - { - texture $DiffuseMap - } - - texture_unit shadow0 - { - content_type shadow - tex_address_mode border - tex_border_colour 1 1 1 1 - } - - texture_unit InstancingVTF - { - filtering none - } - } - } -} - -material Examples/Instancing/VTF/HW/Robot_dq : Examples/Instancing/HW_VTF_dq -{ - set $DiffuseMap r2skin.jpg -} - -abstract material Examples/Instancing/HW_VTF_dq_two_weights -{ - technique - { - shadow_caster_material Examples/Instancing/VTF/HW/shadow_caster_dq_two_weights - - pass - { - diffuse 0.3 0.3 0.3 - specular 0.1 0.1 0.1 0.1 12.5 - - vertex_program_ref Ogre/Instancing/HW_VTF_dq_two_weights_vs - { - param_named_auto viewProjMatrix viewproj_matrix - } - - fragment_program_ref Ogre/Instancing_ps - { - } - - texture_unit Diffuse - { - texture $DiffuseMap - tex_address_mode clamp - } - - texture_unit shadow0 - { - content_type shadow - tex_address_mode border - tex_border_colour 1 1 1 1 - } - - texture_unit InstancingVTF - { - filtering none - } - } - } -} - -material Examples/Instancing/VTF/HW/spine_dq_two_weights : Examples/Instancing/HW_VTF_dq_two_weights -{ - set $DiffuseMap circuit.dds -} diff --git a/Samples/Media/materials/scripts/HW_VTF_LUTInstancing.material b/Samples/Media/materials/scripts/HW_VTF_LUTInstancing.material deleted file mode 100644 index fc1758a8a26..00000000000 --- a/Samples/Media/materials/scripts/HW_VTF_LUTInstancing.material +++ /dev/null @@ -1,426 +0,0 @@ -//--------------------------------------------------------------------------- -//These materials/shaders are part of the NEW InstanceManager implementation -//Written by Matias N. Goldberg ("dark_sylinc") -//--------------------------------------------------------------------------- - -//-------------------------------------------------------------- -// GLSL Programs -//-------------------------------------------------------------- -vertex_program Ogre/Instancing/HW_VTF_LUT_glsl_vs glsl glsles -{ - source HW_VTFInstancing.vert - - preprocessor_defines DEPTH_SHADOWRECEIVER=1,BONE_MATRIX_LUT=1 - - uses_vertex_texture_fetch true - - default_params - { - param_named matrixTexture int 2 - } -} - -vertex_program Ogre/Instancing/VTF/HW/LUT/shadow_caster_glsl_vs glsl glsles -{ - source HW_VTFInstancing.vert - - preprocessor_defines DEPTH_SHADOWCASTER=1,BONE_MATRIX_LUT=1 - - uses_vertex_texture_fetch true - - default_params - { - param_named matrixTexture int 0 - } -} - -vertex_program Ogre/Instancing/HW_VTF_LUT_dq_glsl_vs glsl glsles -{ - source HW_VTFInstancing.vert - - preprocessor_defines ST_DUAL_QUATERNION,DEPTH_SHADOWRECEIVER=1,BONE_MATRIX_LUT=1 - - uses_vertex_texture_fetch true - - default_params - { - param_named matrixTexture int 2 - } -} - -vertex_program Ogre/Instancing/VTF/HW/LUT/shadow_caster_dq_glsl_vs glsl glsles -{ - source HW_VTFInstancing.vert - - preprocessor_defines ST_DUAL_QUATERNION,DEPTH_SHADOWCASTER=1,BONE_MATRIX_LUT=1 - - uses_vertex_texture_fetch true - - default_params - { - param_named matrixTexture int 0 - } -} - -vertex_program Ogre/Instancing/HW_VTF_LUT_dq_two_weights_glsl_vs glsl glsles -{ - source HW_VTFInstancing.vert - - preprocessor_defines ST_DUAL_QUATERNION,BONE_TWO_WEIGHTS,DEPTH_SHADOWRECEIVER=1,BONE_MATRIX_LUT=1 - - uses_vertex_texture_fetch true - - default_params - { - param_named matrixTexture int 2 - } -} - -vertex_program Ogre/Instancing/VTF/HW/LUT/shadow_caster_dq_two_weights_glsl_vs glsl glsles -{ - source HW_VTFInstancing.vert - - preprocessor_defines ST_DUAL_QUATERNION,BONE_TWO_WEIGHTS,DEPTH_SHADOWCASTER=1,BONE_MATRIX_LUT=1 - - uses_vertex_texture_fetch true - - default_params - { - param_named matrixTexture int 0 - } -} - -//-------------------------------------------------------------- -// HLSL Programs -//-------------------------------------------------------------- -vertex_program Ogre/Instancing/HW_VTF_LUT_hlsl_vs hlsl -{ - source HW_VTFInstancing.cg - entry_point main_vs - target vs_3_0 - - preprocessor_defines DEPTH_SHADOWRECEIVER,BONE_MATRIX_LUT - - uses_vertex_texture_fetch true -} - -vertex_program Ogre/Instancing/VTF/HW/LUT/shadow_caster_hlsl_vs hlsl -{ - source HW_VTFInstancing.cg - entry_point main_vs - target vs_3_0 - - preprocessor_defines DEPTH_SHADOWCASTER,BONE_MATRIX_LUT - - uses_vertex_texture_fetch true -} - -vertex_program Ogre/Instancing/HW_VTF_LUT_dq_hlsl_vs hlsl -{ - source HW_VTFInstancing.cg - entry_point main_vs - target vs_3_0 - - preprocessor_defines DEPTH_SHADOWRECEIVER,BONE_MATRIX_LUT,ST_DUAL_QUATERNION - - uses_vertex_texture_fetch true -} - -vertex_program Ogre/Instancing/VTF/HW/LUT/shadow_caster_dq_hlsl_vs hlsl -{ - source HW_VTFInstancing.cg - entry_point main_vs - target vs_3_0 - - preprocessor_defines DEPTH_SHADOWCASTER,BONE_MATRIX_LUT,ST_DUAL_QUATERNION - - uses_vertex_texture_fetch true -} - -vertex_program Ogre/Instancing/HW_VTF_LUT_dq_two_weights_hlsl_vs hlsl -{ - source HW_VTFInstancing.cg - entry_point main_vs - target vs_3_0 - - preprocessor_defines DEPTH_SHADOWRECEIVER,BONE_MATRIX_LUT,ST_DUAL_QUATERNION,BONE_TWO_WEIGHTS - - uses_vertex_texture_fetch true -} - -vertex_program Ogre/Instancing/VTF/HW/LUT/shadow_caster_dq_two_weights_hlsl_vs hlsl -{ - source HW_VTFInstancing.cg - entry_point main_vs - target vs_3_0 - - preprocessor_defines DEPTH_SHADOWCASTER,BONE_MATRIX_LUT,ST_DUAL_QUATERNION,BONE_TWO_WEIGHTS - - uses_vertex_texture_fetch true -} - - - - -//-------------------------------------------------------------- -// Unified CG/GLSL Programs -//-------------------------------------------------------------- -vertex_program Ogre/Instancing/HW_VTF_LUT_vs unified -{ - delegate Ogre/Instancing/HW_VTF_LUT_glsl_vs - delegate Ogre/Instancing/HW_VTF_LUT_hlsl_vs - - default_params - { - param_named_auto viewProjMatrix viewproj_matrix - param_named_auto texViewProjMatrix texture_viewproj_matrix 0 - } -} - -vertex_program Ogre/Instancing/VTF/HW/LUT/shadow_caster_vs unified -{ - delegate Ogre/Instancing/VTF/HW/LUT/shadow_caster_glsl_vs - delegate Ogre/Instancing/VTF/HW/LUT/shadow_caster_hlsl_vs - - default_params - { - param_named_auto viewProjMatrix viewproj_matrix - } -} - -vertex_program Ogre/Instancing/HW_VTF_LUT_dq_vs unified -{ - delegate Ogre/Instancing/HW_VTF_LUT_dq_glsl_vs - delegate Ogre/Instancing/HW_VTF_LUT_dq_hlsl_vs - - default_params - { - param_named_auto viewProjMatrix viewproj_matrix - param_named_auto texViewProjMatrix texture_viewproj_matrix 0 - } -} - -vertex_program Ogre/Instancing/VTF/HW/LUT/shadow_caster_dq_vs unified -{ - delegate Ogre/Instancing/VTF/HW/LUT/shadow_caster_dq_glsl_vs - delegate Ogre/Instancing/VTF/HW/LUT/shadow_caster_dq_hlsl_vs - - default_params - { - param_named_auto viewProjMatrix viewproj_matrix - } -} - -vertex_program Ogre/Instancing/HW_VTF_LUT_dq_two_weights_vs unified -{ - delegate Ogre/Instancing/HW_VTF_LUT_dq_two_weights_glsl_vs - delegate Ogre/Instancing/HW_VTF_LUT_dq_two_weights_hlsl_vs - - default_params - { - param_named_auto viewProjMatrix viewproj_matrix - param_named_auto texViewProjMatrix texture_viewproj_matrix 0 - } -} - -vertex_program Ogre/Instancing/VTF/HW/LUT/shadow_caster_dq_two_weights_vs unified -{ - delegate Ogre/Instancing/VTF/HW/LUT/shadow_caster_dq_two_weights_glsl_vs - delegate Ogre/Instancing/VTF/HW/LUT/shadow_caster_dq_two_weights_hlsl_vs - - default_params - { - param_named_auto viewProjMatrix viewproj_matrix - } -} - -material Examples/Instancing/VTF/HW/LUT/shadow_caster -{ - technique - { - pass - { - vertex_program_ref Ogre/Instancing/VTF/HW/LUT/shadow_caster_vs - { - } - fragment_program_ref Ogre/Instancing/shadow_caster_ps - { - } - - texture_unit InstancingVTF - { - filtering none - } - } - } -} - -material Examples/Instancing/VTF/HW/LUT/shadow_caster_dq -{ - technique - { - pass - { - vertex_program_ref Ogre/Instancing/VTF/HW/LUT/shadow_caster_dq_vs - { - } - fragment_program_ref Ogre/Instancing/shadow_caster_ps - { - } - - texture_unit InstancingVTF - { - filtering none - } - } - } -} - -material Examples/Instancing/VTF/HW/LUT/shadow_caster_dq_two_weights -{ - technique - { - pass - { - vertex_program_ref Ogre/Instancing/VTF/HW/LUT/shadow_caster_dq_two_weights_vs - { - } - fragment_program_ref Ogre/Instancing/shadow_caster_ps - { - } - - texture_unit InstancingVTF - { - filtering none - } - } - } -} - -abstract material Examples/Instancing/HW_VTF_LUT -{ - technique - { - shadow_caster_material Examples/Instancing/VTF/HW/LUT/shadow_caster - - pass - { - specular 1 1 1 1 12.5 - vertex_program_ref Ogre/Instancing/HW_VTF_LUT_vs - { - } - - fragment_program_ref Ogre/Instancing_ps - { - } - - texture_unit Diffuse - { - texture $DiffuseMap - } - - texture_unit shadow0 - { - content_type shadow - tex_address_mode border - tex_border_colour 1 1 1 1 - } - - texture_unit InstancingVTF - { - filtering none - } - } - } -} - -material Examples/Instancing/VTF/HW/LUT/Robot : Examples/Instancing/HW_VTF_LUT -{ - set $DiffuseMap r2skin.jpg -} - -abstract material Examples/Instancing/HW_VTF_LUT_dq -{ - technique - { - shadow_caster_material Examples/Instancing/VTF/HW/LUT/shadow_caster_dq - - pass - { - specular 1 1 1 1 12.5 - vertex_program_ref Ogre/Instancing/HW_VTF_LUT_dq_vs - { - } - - fragment_program_ref Ogre/Instancing_ps - { - } - - texture_unit Diffuse - { - texture $DiffuseMap - } - - texture_unit shadow0 - { - content_type shadow - tex_address_mode border - tex_border_colour 1 1 1 1 - } - - texture_unit InstancingVTF - { - filtering none - } - } - } -} - -material Examples/Instancing/VTF/HW/LUT/Robot_dq : Examples/Instancing/HW_VTF_LUT_dq -{ - set $DiffuseMap r2skin.jpg -} - -abstract material Examples/Instancing/HW_VTF_LUT_dq_two_weights -{ - technique - { - shadow_caster_material Examples/Instancing/VTF/HW/LUT/shadow_caster_dq_two_weights - - pass - { - diffuse 0.3 0.3 0.3 - specular 0.1 0.1 0.1 0.1 12.5 - vertex_program_ref Ogre/Instancing/HW_VTF_LUT_dq_two_weights_vs - { - } - - fragment_program_ref Ogre/Instancing_ps - { - } - - texture_unit Diffuse - { - texture $DiffuseMap - tex_address_mode clamp - } - - texture_unit shadow0 - { - content_type shadow - tex_address_mode border - tex_border_colour 1 1 1 1 - } - - texture_unit InstancingVTF - { - filtering none - } - } - } -} - -material Examples/Instancing/VTF/HW/LUT/spine_dq_two_weights : Examples/Instancing/HW_VTF_LUT_dq_two_weights -{ - set $DiffuseMap circuit.dds -} diff --git a/Samples/Media/materials/scripts/Hair.material b/Samples/Media/materials/scripts/Hair.material deleted file mode 100644 index c347f2c7e09..00000000000 --- a/Samples/Media/materials/scripts/Hair.material +++ /dev/null @@ -1,2619 +0,0 @@ -/*vertex_program Ogre/Hair/AddAngularForcesVS hlsl -{ - source Hair.hlsl - entry_point AddAngularForcesVS - target vs_4_0 - - default_params - { - - } -} - -geometry_program Ogre/Hair/AddAngularForcesGS hlsl -{ - source Hair.hlsl - entry_point AddAngularForcesGS - target gs_4_0 - - default_params - { - param_named g_bClearForces int 0 - } -} - -vertex_program Ogre/Hair/addForcesAndIntegrateVS hlsl -{ - source Hair.hlsl - entry_point addForcesAndIntegrateVS - target vs_4_0 - - default_params - { - param_named g_bApplyAdditionalTransform int 0 - param_named g_bApplyHorizontalForce int 0 - param_named g_bAddGravity int 0 - param_named g_TimeStep float 1.0 - param_named g_gravityStrength float 1.0 - param_named g_bSimulate int 0 - param_named g_windForce float3 1.0 1.0 1.0 - param_named g_NumSphereImplicits int 1 - param_named g_NumCylinderImplicits int 1 - param_named g_NumSphereNoMoveImplicits int 1 - } -} - -geometry_program Ogre/Hair/addForcesAndIntegrateVSG hlsl -{ - source Hair.hlsl - entry_point addForcesAndIntegrateVS - target vs_4_0 - - default_params - { - param_named g_bApplyAdditionalTransform int 0 - param_named g_bApplyHorizontalForce int 0 - param_named g_bAddGravity int 0 - param_named g_TimeStep float 1.0 - param_named g_gravityStrength float 1.0 - param_named g_bSimulate int 0 - param_named g_windForce float3 1.0 1.0 1.0 - param_named g_NumSphereImplicits int 1 - param_named g_NumCylinderImplicits int 1 - param_named g_NumSphereNoMoveImplicits int 1 - } -} - -vertex_program Ogre/Hair/SatisfySpringConstraintsVS hlsl -{ - source Hair.hlsl - entry_point SatisfySpringConstraintsGS - target vs_4_0 - - default_params - { - - } -} - -geometry_program Ogre/Hair/SatisfySpringConstraintsGS hlsl -{ - source Hair.hlsl - entry_point SatisfySpringConstraintsGS - target gs_4_0 - - default_params - { - - } -} - -vertex_program Ogre/Hair/SatisfyAngularSpringConstraintsVS hlsl -{ - source Hair.hlsl - entry_point SatisfyAngularSpringConstraintsVS - target vs_4_0 - - default_params - { - - } -} - -geometry_program Ogre/Hair/SatisfyAngularSpringConstraintsGS hlsl -{ - source Hair.hlsl - entry_point SatisfyAngularSpringConstraintsGS - target gs_4_0 - - default_params - { - param_named g_angularStiffness float 1.0 - } -} - -vertex_program Ogre/Hair/SatisfyCollisionConstraintsVS hlsl -{ - source Hair.hlsl - entry_point SatisfyCollisionConstraintsVS - target vs_4_0 - - default_params - { - - } -} - -geometry_program Ogre/Hair/SatisfyCollisionConstraintsVSG hlsl -{ - source Hair.hlsl - entry_point SatisfyCollisionConstraintsVS - target vs_4_0 - - default_params - { - - } -} - -vertex_program Ogre/Hair/UpdateCoordinateFrameVS hlsl -{ - source Hair.hlsl - entry_point UpdateCoordinateFrameVS - target vs_4_0 - - default_params - { - param_named g_blendAxis float 0.0 - } -} - -geometry_program Ogre/Hair/UpdateCoordinateFrameVSG hlsl -{ - source Hair.hlsl - entry_point UpdateCoordinateFrameVS - target vs_4_0 - - default_params - { - param_named g_blendAxis float 0.0 - } -} - -vertex_program Ogre/Hair/PropagateCoordinateFrameVS hlsl -{ - source Hair.hlsl - entry_point PropagateCoordinateFrameVS - target vs_4_0 - - default_params - { - - } -} - - -geometry_program Ogre/Hair/PropagateCoordinateFrameVSG hlsl -{ - source Hair.hlsl - entry_point PropagateCoordinateFrameVS - target vs_4_0 - - default_params - { - - } -} - -vertex_program Ogre/Hair/restoreToDefaultPositionsVS hlsl -{ - source Hair.hlsl - entry_point restoreToDefaultPositionsVS - target vs_4_0 - - default_params - { - - } -} - -geometry_program Ogre/Hair/restoreToDefaultPositionsVSG hlsl -{ - source Hair.hlsl - entry_point restoreToDefaultPositionsVS - target vs_4_0 - - default_params - { - - } -} - -vertex_program Ogre/Hair/RenderCoordinateFrameVSUnTess hlsl -{ - source Hair.hlsl - entry_point RenderCoordinateFrameVSUnTess - target vs_4_0 - - default_params - { - - } -} - -vertex_program Ogre/Hair/RenderCoordinateFrameVSUnTessSB hlsl -{ - source Hair.hlsl - entry_point RenderCoordinateFrameVSUnTessSB - target vs_4_0 - - default_params - { - - } -} - -vertex_program Ogre/Hair/RenderCoordinateFrameVS hlsl -{ - source Hair.hlsl - entry_point RenderCoordinateFrameVS - target vs_4_0 - - default_params - { - - } -} - -geometry_program Ogre/Hair/RenderCoordinateFrameGSUnTessellated hlsl -{ - source Hair.hlsl - entry_point RenderCoordinateFrameGSUnTessellated - target gs_4_0 - - default_params - { - - } -} - -geometry_program Ogre/Hair/RenderCoordinateFrameGSUnTessellatedSB hlsl -{ - source Hair.hlsl - entry_point RenderCoordinateFrameGSUnTessellatedSB - target gs_4_0 - - default_params - { - - } -} - -geometry_program Ogre/Hair/RenderCoordinateFrameGSTessellated hlsl -{ - source Hair.hlsl - entry_point RenderCoordinateFrameGSTessellated - target gs_4_0 - - default_params - { - - } -} - -fragment_program Ogre/Hair/RenderCoordinateFramePS hlsl -{ - source Hair.hlsl - entry_point restoreToDefaultPositionsVS - target ps_4_0 - - default_params - { - - } -} - -material Ogre/Hair/SimulateHair -{ - technique SimulateHair - { - pass addAngularForces - { - vertex_program_ref Ogre/Hair/AddAngularForcesVS - { - - } - geometry_program_ref Ogre/Hair/AddAngularForcesGS - { - - } - depth_check off - depth_write off - } - pass addForcesAndIntegrate - { - vertex_program_ref Ogre/Hair/addForcesAndIntegrateVS - { - - } - geometry_program_ref Ogre/Hair/addForcesAndIntegrateVSG - { - - } - depth_check off - depth_write off - } - pass SatisfySpringConstraints - { - vertex_program_ref Ogre/Hair/SatisfySpringConstraintsVS - { - - } - geometry_program_ref Ogre/Hair/SatisfySpringConstraintsGS - { - - } - depth_check off - depth_write off - } - pass SatisfyAngularSpringConstraints - { - vertex_program_ref Ogre/Hair/SatisfyAngularSpringConstraintsVS - { - - } - geometry_program_ref Ogre/Hair/SatisfyAngularSpringConstraintsGS - { - - } - depth_check off - depth_write off - } - pass SatisfyCollisionConstraints - { - vertex_program_ref Ogre/Hair/SatisfyCollisionConstraintsVS - { - - } - geometry_program_ref Ogre/Hair/SatisfyCollisionConstraintsVSG - { - - } - depth_check off - depth_write off - } - pass restoreToDefaultPositions - { - vertex_program_ref Ogre/Hair/restoreToDefaultPositionsVS - { - - } - geometry_program_ref Ogre/Hair/restoreToDefaultPositionsVSG - { - - } - depth_check off - depth_write off - } - pass RenderCoordinateFrameUnTessellated - { - vertex_program_ref Ogre/Hair/RenderCoordinateFrameVSUnTess - { - - } - geometry_program_ref Ogre/Hair/RenderCoordinateFrameGSUnTessellated - { - - } - fragment_program_ref Ogre/Hair/RenderCoordinateFramePS - { - - } - - depth_check on - depth_write on - } - pass RenderCoordinateFrameUnTessellatedSB - { - vertex_program_ref Ogre/Hair/RenderCoordinateFrameVSUnTessSB - { - - } - geometry_program_ref Ogre/Hair/RenderCoordinateFrameGSUnTessellatedSB - { - - } - fragment_program_ref Ogre/Hair/RenderCoordinateFramePS - { - - } - - depth_check on - depth_write on - } - pass RenderCoordinateFrameTessellated - { - vertex_program_ref Ogre/Hair/RenderCoordinateFrameVS - { - - } - geometry_program_ref Ogre/Hair/RenderCoordinateFrameGSTessellated - { - - } - fragment_program_ref Ogre/Hair/RenderCoordinateFramePS - { - - } - - depth_check on - depth_write on - } - pass UpdateCoordinateFrame - { - vertex_program_ref Ogre/Hair/UpdateCoordinateFrameVS - { - - } - geometry_program_ref Ogre/Hair/UpdateCoordinateFrameVSG - { - - } - - depth_check off - depth_write off - } - pass PropagateCoordinateFrame - { - vertex_program_ref Ogre/Hair/PropagateCoordinateFrameVS - { - - } - geometry_program_ref Ogre/Hair/PropagateCoordinateFrameVSG - { - - } - - depth_check off - depth_write off - } - } -} - -vertex_program Ogre/Hair/InterpolateVS_DUMMY11 hlsl -{ - source Hair.hlsl - entry_point InterpolateVS_DUMMY11 - target vs_5_0 - - default_params - { - - } -} - -vertex_program Ogre/Hair/InterpolateVSMultiStrand_LOAD hlsl -{ - source Hair.hlsl - entry_point InterpolateVSMultiStrand_LOAD - target vs_5_0 - - default_params - { - param_named g_bApplyAdditionalRenderingTransform int 0 - param_named g_useShadows int 1 - param_named g_SigmaA float 1.0 - param_named g_ZNear float 1.0 - param_named g_ZFar float 2.0 - } -} - -vertex_program Ogre/Hair/InterpolateVSMultiStrandDepthShadows_LOAD hlsl -{ - source Hair.hlsl - entry_point InterpolateVSMultiStrandDepthShadows_LOAD - target vs_5_0 - - default_params - { - param_named g_bApplyAdditionalRenderingTransform int 0 - } -} - -vertex_program Ogre/Hair/InterpolateVSMultiStrandCollisions hlsl -{ - source Hair.hlsl - entry_point InterpolateVSMultiStrandCollisions - target vs_5_0 - - default_params - { - param_named g_NumTotalWisps int 0 - param_named g_NumMaxStrandsPerWisp int 0 - } -} - -tesselation_hull_program Ogre/Hair/InterpolateHSMultiStrand hlsl -{ - source Hair.hlsl - entry_point InterpolateHSMultiStrand - target hs_5_0 - - default_params - { - param_named g_fNumHairsLOD float 1.0 - } -} - -tesselation_hull_program Ogre/Hair/InterpolateHSMultiStrandDepth hlsl -{ - source Hair.hlsl - entry_point InterpolateHSMultiStrandDepth - target hs_5_0 - - default_params - { - param_named g_fNumHairsLOD float 1.0 - } -} - -tesselation_hull_program Ogre/Hair/InterpolateHSMultiStrandCollisions hlsl -{ - source Hair.hlsl - entry_point InterpolateHSMultiStrandCollisions - target hs_5_0 - - default_params - { - param_named g_fNumHairsLOD float 1.0 - } -} - -tesselation_domain_program Ogre/Hair/InterpolateDSMultiStrand hlsl -{ - source Hair.hlsl - entry_point InterpolateDSMultiStrand - target ds_5_0 - - default_params - { - param_named g_bApplyAdditionalRenderingTransform int 0 - param_named g_fWidthHairsLOD float 1.0 - param_named g_maxLengthToRoot float 12.0 - param_named g_NumTotalWisps int 0 - param_named g_NumMaxStrandsPerWisp int 0 - param_named g_thinning float 0.5 - param_named g_useShadows int 1 - param_named g_SigmaA float 1.0 - param_named g_ZNear float 1.0 - param_named g_ZFar float 2.0 - } -} - -tesselation_domain_program Ogre/Hair/InterpolateDSMultiStrandDepth hlsl -{ - source Hair.hlsl - entry_point InterpolateDSMultiStrandDepth - target ds_5_0 - - default_params - { - param_named g_bApplyAdditionalRenderingTransform bool 0 - param_named g_fWidthHairsLOD float 1.0 - param_named g_NumTotalWisps int 0 - param_named g_NumMaxStrandsPerWisp int 0 - param_named g_thinning float 0.5 - } -} - -tesselation_domain_program Ogre/Hair/InterpolateDSMultiStrandCollisions hlsl -{ - source Hair.hlsl - entry_point InterpolateDSMultiStrandCollisions - target ds_5_0 - - default_params - { - - } -} - -tesselation_domain_program Ogre/Hair/InterpolateDSMultiStrandCollisionsWithGS hlsl -{ - source Hair.hlsl - entry_point InterpolateDSMultiStrandCollisionsWithGS - target ds_5_0 - - default_params - { - param_named g_NumTotalWisps int 0 - param_named g_NumMaxStrandsPerWisp int 0 - } -} - -geometry_program Ogre/Hair/InterpolateGS hlsl -{ - source Hair.hlsl - entry_point InterpolateGS - target gs_5_0 - - default_params - { - param_named g_ScreenWidth float 1280.0 - param_named g_ScreenHeight float 1024.0 - } -} - -geometry_program Ogre/Hair/InterpolateGSDepthShadows hlsl -{ - source Hair.hlsl - entry_point InterpolateGSDepthShadows - target gs_5_0 - - default_params - { - - } -} - -geometry_program Ogre/Hair/InterpolateGSMultiStrandCollisions hlsl -{ - source Hair.hlsl - entry_point InterpolateGSMultiStrandCollisions - target gs_5_0 - - default_params - { - - } -} - -fragment_program Ogre/Hair/RenderPS hlsl -{ - source Hair.hlsl - entry_point RenderPS - target ps_5_0 - - default_params - { - param_named g_ksP float 0.0 - param_named g_ksS float 0.0 - param_named g_kd float 0.0 - param_named g_specPowerPrimary float 0.0 - param_named g_specPowerSecondary float 0.0 - param_named g_ksP_sparkles float 0.0 - param_named g_specPowerPrimarySparkles float 0.0 - param_named g_ka float 0.0 - param_named g_baseColor float4 0.0 0.0 0.0 0.0 - param_named g_specColor float4 0.0 0.0 0.0 0.0 - param_named g_useShadows int 1 - param_named g_SigmaA float 1.0 - param_named g_ZNear float 1.0 - param_named g_ZFar float 2.0 - } -} - -fragment_program Ogre/Hair/RenderDepthPSSmall hlsl -{ - source Hair.hlsl - entry_point RenderDepthPSSmall - target ps_5_0 - - default_params - { - - } -} - -fragment_program Ogre/Hair/InterpolatePSMultiStrandCollisions hlsl -{ - source Hair.hlsl - entry_point InterpolatePSMultiStrandCollisions - target ps_5_0 - - default_params - { - param_named g_densityThreshold float 1.0 - param_named g_textureDepth float 1.0 - } -} - -fragment_program Ogre/Hair/RenderDepthPSSmall_DOM hlsl -{ - source Hair.hlsl - entry_point RenderDepthPSSmall_DOM - target ps_5_0 - - default_params - { - - } -} - -vertex_program Ogre/Hair/TessellateVSBSplinePassThrough hlsl -{ - source Hair.hlsl - entry_point TessellateVSBSplinePassThrough - target vs_4_0 - - default_params - { - - } -} - -vertex_program Ogre/Hair/TessellateVSBSplineCFs hlsl -{ - source Hair.hlsl - entry_point TessellateVSBSplineCFs - target vs_4_0 - - default_params - { - - } -} - -vertex_program Ogre/Hair/TessellateVSBSplineSBCFs hlsl -{ - source Hair.hlsl - entry_point TessellateVSBSplineSBCFs - target vs_4_0 - - default_params - { - - } -} - -vertex_program Ogre/Hair/TessellateVSBSplineLengths hlsl -{ - source Hair.hlsl - entry_point TessellateVSBSplineLengths - target vs_4_0 - - default_params - { - - } -} - -vertex_program Ogre/Hair/InterpolateVSMultiStrand_SO hlsl -{ - source Hair.hlsl - entry_point InterpolateVSMultiStrand_SO - target vs_4_0 - - default_params - { - param_named g_maxLengthToRoot float 12.0 - param_named g_NumTotalWisps int 0 - param_named g_NumMaxStrandsPerWisp int 0 - param_named g_doCurlyHair int 0 - param_named g_thinning float 0.5 - param_named g_TessellatedMasterStrandLengthMax int 1 - } -} - -vertex_program Ogre/Hair/InterpolateVSSingleStrand_SO hlsl -{ - source Hair.hlsl - entry_point InterpolateVSSingleStrand_SO - target vs_4_0 - - default_params - { - param_named g_maxLengthToRoot float 12.0 - param_named g_thinning float 0.5 - param_named g_TessellatedMasterStrandLengthMax int 1 - } -} - -vertex_program Ogre/Hair/InterpolateVSDepthPrepass hlsl -{ - source Hair.hlsl - entry_point InterpolateVSDepthPrepass - target vs_4_0 - - default_params - { - param_named g_maxLengthToRoot float 12.0 - param_named g_NumTotalWisps int 0 - param_named g_NumMaxStrandsPerWisp int 0 - param_named g_doCurlyHair int 0 - param_named g_thinning float 0.5 - param_named g_TessellatedMasterStrandLengthMax int 1 - } -} - -vertex_program Ogre/Hair/InterpolateVSDepthPrepass_LOAD hlsl -{ - source Hair.hlsl - entry_point InterpolateVSDepthPrepass_LOAD - target vs_4_0 - - default_params - { - param_named g_bApplyAdditionalRenderingTransform int 0 - param_named g_NumTotalWisps int 0 - param_named g_NumMaxStrandsPerWisp int 0 - } -} - -vertex_program Ogre/Hair/InterpolateVSMultiStrand hlsl -{ - source Hair.hlsl - entry_point InterpolateVSMultiStrand - target vs_4_0 - - default_params - { - param_named g_maxLengthToRoot float 12.0 - param_named g_doCurlyHair int 0 - } -} - -vertex_program Ogre/Hair/InterpolateVSClumpDepthPrepass hlsl -{ - source Hair.hlsl - entry_point InterpolateVSClumpDepthPrepass - target vs_4_0 - - default_params - { - param_named g_maxLengthToRoot float 12.0 - param_named g_thinning float 0.5 - param_named g_TessellatedMasterStrandLengthMax int 1 - } -} - -vertex_program Ogre/Hair/InterpolateVSClumpDepthPrepass_LOAD hlsl -{ - source Hair.hlsl - entry_point InterpolateVSClumpDepthPrepass_LOAD - target vs_4_0 - - default_params - { - param_named g_bApplyAdditionalRenderingTransform int 0 - param_named g_TessellatedMasterStrandLengthMax int 1 - } -} - -vertex_program Ogre/Hair/InterpolateVSSingleStrand hlsl -{ - source Hair.hlsl - entry_point InterpolateVSSingleStrand - target vs_4_0 - - default_params - { - param_named g_maxLengthToRoot float 12.0 - param_named g_thinning float 0.5 - param_named g_TessellatedMasterStrandLengthMax int 1 - } -} - -vertex_program Ogre/Hair/InterpolateVSSingleStrand_LOAD hlsl -{ - source Hair.hlsl - entry_point InterpolateVSSingleStrand_LOAD - target vs_4_0 - - default_params - { - param_named g_bApplyAdditionalRenderingTransform int 0 - param_named g_NumTotalWisps int 0 - param_named g_NumMaxStrandsPerWisp int 0 - param_named g_useShadows int 1 - param_named g_SigmaA float 1.0 - param_named g_ZNear float 1.0 - param_named g_ZFar float 2.0 - } -} - -vertex_program Ogre/Hair/InterpolateVSMCollisions hlsl -{ - source Hair.hlsl - entry_point InterpolateVSMCollisions - target vs_4_0 - - default_params - { - param_named g_NumTotalWisps int 0 - param_named g_NumMaxStrandsPerWisp int 0 - } -} - -vertex_program Ogre/Hair/InterpolateVS2Grid hlsl -{ - source Hair.hlsl - entry_point InterpolateVS2Grid - target vs_4_0 - - default_params - { - - } -} - -geometry_program Ogre/Hair/TessellateGSBSpline hlsl -{ - source Hair.hlsl - entry_point TessellateGSBSpline - target gs_4_0 - - default_params - { - - } -} - -geometry_program Ogre/Hair/TessellateGSBSplineSB hlsl -{ - source Hair.hlsl - entry_point TessellateGSBSplineSB - target gs_4_0 - - default_params - { - - } -} - -geometry_program Ogre/Hair/TessellateVSBSplineCFsG hlsl -{ - source Hair.hlsl - entry_point TessellateVSBSplineCFs - target vs_4_0 - - default_params - { - - } -} - -geometry_program Ogre/Hair/TessellateVSBSplineSBCFsG hlsl -{ - source Hair.hlsl - entry_point TessellateVSBSplineSBCFs - target vs_4_0 - - default_params - { - - } -} - -geometry_program Ogre/Hair/TessellateVSBSplineLengthsG hlsl -{ - source Hair.hlsl - entry_point TessellateVSBSplineLengths - target vs_4_0 - - default_params - { - - } -} - -geometry_program Ogre/Hair/InterpolateVSMultiStrand_SOG hlsl -{ - source Hair.hlsl - entry_point InterpolateVSMultiStrand_SO - target vs_4_0 - - default_params - { - param_named g_TessellatedMasterStrandLengthMax int 1 - } -} - -geometry_program Ogre/Hair/InterpolateVSSingleStrand_SOG hlsl -{ - source Hair.hlsl - entry_point TessellateVSBSplineCFs - target vs_4_0 - - default_params - { - - } -} - -geometry_program Ogre/Hair/InterpolateGSDepthPrepass hlsl -{ - source Hair.hlsl - entry_point InterpolateGSDepthPrepass - target gs_4_0 - - default_params - { - param_named g_ScreenWidth float 1280.0 - param_named g_ScreenHeight float 1024.0 - } -} - -geometry_program Ogre/Hair/InterpolateGSMCollisions hlsl -{ - source Hair.hlsl - entry_point InterpolateGSMCollisions - target gs_4_0 - - default_params - { - - } -} - -geometry_program Ogre/Hair/InterpolateGS2Grid hlsl -{ - source Hair.hlsl - entry_point InterpolateGS2Grid - target gs_4_0 - - default_params - { - - } -} - -geometry_program Ogre/Hair/GS_ARRAY hlsl -{ - source Hair.hlsl - entry_point GS_ARRAY - target gs_4_0 - - default_params - { - - } -} - -tesselation_hull_program Ogre/Hair/InterpolateHSSingleStrand hlsl -{ - source Hair.hlsl - entry_point InterpolateHSSingleStrand - target hs_5_0 - - default_params - { - param_named g_fNumHairsLOD float 1.0 - } -} - -tesselation_domain_program Ogre/Hair/InterpolateDSSingleStrand_DEPTH hlsl -{ - source Hair.hlsl - entry_point InterpolateHSSingleStrand - target ds_5_0 - - default_params - { - param_named g_bApplyAdditionalRenderingTransform int 0 - param_named g_fWidthHairsLOD float 1.0 - param_named g_maxLengthToRoot float 12.0 - param_named g_doCurlyHair int 0 - param_named g_thinning float 0.5 - param_named g_TessellatedMasterStrandLengthMax int 1 - } -} - -tesselation_domain_program Ogre/Hair/InterpolateDSSingleStrand_NORMAL hlsl -{ - source Hair.hlsl - entry_point InterpolateDSSingleStrand_NORMAL - target ds_5_0 - - default_params - { - param_named g_bApplyAdditionalRenderingTransform int 0 - param_named g_fWidthHairsLOD float 1.0 - param_named g_maxLengthToRoot float 12.0 - param_named g_doCurlyHair int 0 - param_named g_thinning float 0.5 - param_named g_TessellatedMasterStrandLengthMax int 1 - param_named g_useShadows int 1 - param_named g_SigmaA float 1.0 - param_named g_ZNear float 1.0 - param_named g_ZFar float 2.0 - } -} - -fragment_program Ogre/Hair/RenderPSDepthPrepass hlsl -{ - source Hair.hlsl - entry_point RenderPSDepthPrepass - target ps_4_0 - - default_params - { - - } -} - -fragment_program Ogre/Hair/InterpolatePSMCollisions hlsl -{ - source Hair.hlsl - entry_point InterpolatePSMCollisions - target ps_4_0 - - default_params - { - - } -} - -fragment_program Ogre/Hair/RenderPSForGridMRT hlsl -{ - source Hair.hlsl - entry_point RenderPSForGridMRT - target ps_4_0 - - default_params - { - - } -} - -vertex_program Ogre/Hair/InterpolateVSBMultiStrandDepthShadows hlsl -{ - source Hair.hlsl - entry_point InterpolateVSBMultiStrandDepthShadows - target vs_4_0 - - default_params - { - param_named g_doCurlyHair int 0 - } -} - -vertex_program Ogre/Hair/InterpolateVSSingleStrandDepthShadows hlsl -{ - source Hair.hlsl - entry_point InterpolateVSSingleStrandDepthShadows - target vs_4_0 - - default_params - { - param_named g_TessellatedMasterStrandLengthMax int 1 - } -} - -vertex_program Ogre/Hair/InterpolateVSSingleStrandDepthShadows_LOAD hlsl -{ - source Hair.hlsl - entry_point InterpolateVSSingleStrandDepthShadows_LOAD - target vs_4_0 - - default_params - { - param_named g_bApplyAdditionalRenderingTransform int 0 - } -} - -vertex_program Ogre/Hair/FullScreenTriVS hlsl -{ - source Hair.hlsl - entry_point FullScreenTriVS - target vs_4_0 - - default_params - { - - } -} - -vertex_program Ogre/Hair/MeshVS hlsl -{ - source Hair.hlsl - entry_point MeshVS - target vs_4_0 - - default_params - { - - } -} - -vertex_program Ogre/Hair/MeshVSShadows hlsl -{ - source Hair.hlsl - entry_point MeshVSShadows - target vs_4_0 - - default_params - { - - } -} - -vertex_program Ogre/Hair/VSDrawPlane hlsl -{ - source Hair.hlsl - entry_point VSDrawPlane - target vs_4_0 - - default_params - { - - } -} - -vertex_program Ogre/Hair/MeshDepthVS hlsl -{ - source Hair.hlsl - entry_point MeshDepthVS - target vs_4_0 - - default_params - { - param_named g_ZNear float 1.0 - param_named g_ZFar float 2.0 - } -} - -vertex_program Ogre/Hair/VS_GRID hlsl -{ - source Hair.hlsl - entry_point VS_GRID - target vs_4_0 - - default_params - { - param_named g_textureHeight float 1.0 - param_named g_textureWidth float 1.0 - } -} - -vertex_program Ogre/Hair/VS_COLLISIONS hlsl -{ - source Hair.hlsl - entry_point VS_COLLISIONS - target vs_4_0 - - default_params - { - - } -} - -vertex_program Ogre/Hair/VS_GRID_FLUIDSIM hlsl -{ - source Hair.hlsl - entry_point VS_GRID_FLUIDSIM - target vs_4_0 - - default_params - { - param_named fluidg_textureWidth int 1 - param_named fluidg_textureHeight int 1 - param_named fluidg_textureDepth int 1 - param_named g_textureDepth float 1.0 - } -} - -vertex_program Ogre/Hair/VSArrow hlsl -{ - source Hair.hlsl - entry_point VSArrow - target vs_4_0 - - default_params - { - - } -} - -vertex_program Ogre/Hair/CollisionVS hlsl -{ - source Hair.hlsl - entry_point CollisionVS - target vs_4_0 - - default_params - { - param_named g_currentCollisionSphere int 1 - } -} - -fragment_program Ogre/Hair/CollisionPS hlsl -{ - source Hair.hlsl - entry_point CollisionPS - target ps_4_0 - - default_params - { - - } -} - -fragment_program Ogre/Hair/VisDepthsPS hlsl -{ - source Hair.hlsl - entry_point VisDepthsPS - target ps_4_0 - - default_params - { - param_named g_ZNear float 1.0 - param_named g_ZFar float 2.0 - } -} - -fragment_program Ogre/Hair/CopyTexturePS hlsl -{ - source Hair.hlsl - entry_point CopyTexturePS - target ps_4_0 - - default_params - { - - } -} - -fragment_program Ogre/Hair/MeshPS hlsl -{ - source Hair.hlsl - entry_point MeshPS - target ps_4_0 - - default_params - { - param_named g_useScalpTexture int 0 - } -} - -fragment_program Ogre/Hair/MeshPSShadows hlsl -{ - source Hair.hlsl - entry_point MeshPSShadows - target ps_4_0 - - default_params - { - param_named g_useScalpTexture int 0 - param_named g_useShadows int 1 - } -} - -fragment_program Ogre/Hair/PSDrawPlane hlsl -{ - source Hair.hlsl - entry_point PSDrawPlane - target ps_4_0 - - default_params - { - param_named g_useShadows bool 1 - } -} - -fragment_program Ogre/Hair/MeshDepthPS hlsl -{ - source Hair.hlsl - entry_point MeshDepthPS - target ps_4_0 - - default_params - { - - } -} - -fragment_program Ogre/Hair/MeshDepthPS_DOM hlsl -{ - source Hair.hlsl - entry_point MeshDepthPS_DOM - target ps_4_0 - - default_params - { - - } -} - -fragment_program Ogre/Hair/PS_DRAW_TEXTURE hlsl -{ - source Hair.hlsl - entry_point PS_DRAW_TEXTURE - target ps_4_0 - - default_params - { - param_named g_densityThreshold float 1.0 - param_named g_rowWidth int 1 - param_named g_colWidth int 1 - } -} - -fragment_program Ogre/Hair/PS_DRAW_COLLISIONS_TEXTURE hlsl -{ - source Hair.hlsl - entry_point PS_DRAW_COLLISIONS_TEXTURE - target ps_4_0 - - default_params - { - - } -} - -fragment_program Ogre/Hair/PS_RESOLVE_SUPERSAMPLE hlsl -{ - source Hair.hlsl - entry_point PS_RESOLVE_SUPERSAMPLE - target ps_4_0 - - default_params - { - param_named g_SSg_textureWidth float 0.0 - param_named g_SSg_textureHeight float 0.0 - } -} - -fragment_program Ogre/Hair/PS_RECONSTRUCT_DEPTH hlsl -{ - source Hair.hlsl - entry_point PS_RECONSTRUCT_DEPTH - target ps_4_0 - - default_params - { - - } -} - -fragment_program Ogre/Hair/PS_DRAW_TEXTURE_DEMUX hlsl -{ - source Hair.hlsl - entry_point PS_DRAW_TEXTURE_DEMUX - target ps_4_0 - - default_params - { - param_named g_densityThreshold float 1.0 - param_named g_rowWidth int 1 - param_named g_colWidth int 1 - param_named g_textureIndex int 1 - } -} - -fragment_program Ogre/Hair/PS_DEMUX hlsl -{ - source Hair.hlsl - entry_point PS_DEMUX - target ps_4_0 - - default_params - { - param_named g_gridZIndex int 1 - } -} - -fragment_program Ogre/Hair/PS_VOXELIZE_OBSTACLES hlsl -{ - source Hair.hlsl - entry_point PS_VOXELIZE_OBSTACLES - target ps_4_0 - - default_params - { - param_named g_NumSphereImplicits int 1 - param_named g_NumCylinderImplicits int 1 - param_named g_NumSphereNoMoveImplicits int 1 - param_named g_densityThreshold float 1.0 - param_named g_textureDepth float 1.0 - param_named g_gridZIndex int 1 - } -} - -fragment_program Ogre/Hair/PS_DEMUX_TO_3D_OBSTACLE_TEX hlsl -{ - source Hair.hlsl - entry_point PS_DEMUX_TO_3D_OBSTACLE_TEX - target ps_4_0 - - default_params - { - param_named g_NumSphereImplicits int 1 - param_named g_NumCylinderImplicits int 1 - param_named g_NumSphereNoMoveImplicits int 1 - param_named g_densityThreshold float 1.0 - param_named g_textureDepth float 1.0 - } -} - -fragment_program Ogre/Hair/PSArrow hlsl -{ - source Hair.hlsl - entry_point PSArrow - target ps_4_0 - - default_params - { - - } -} - -material Ogre/Hair/RenderHair -{ - technique RenderHair - { - //hardwareTessellation passes for multistrand interpolation ------------------------------------------------ - pass InterpolateAndRenderM_HardwareTess - { - vertex_program_ref Ogre/Hair/InterpolateVS_DUMMY11 - { - - } - - tesselation_hull_program_ref Ogre/Hair/InterpolateHSMultiStrand - { - - } - - tesselation_domain_program_ref Ogre/Hair/InterpolateDSMultiStrand - { - - } - geometry_program_ref Ogre/Hair/InterpolateGS - { - - } - fragment_program_ref Ogre/Hair/RenderPS - { - - } - - scene_blend alpha_blend - depth_check on - depth_write on - cull_hardware none - cull_software none - } - pass InterpolateInstancedVS_LOAD - { - vertex_program_ref Ogre/Hair/InterpolateVSMultiStrand_LOAD - { - - } - geometry_program_ref Ogre/Hair/InterpolateGS - { - - } - fragment_program_ref Ogre/Hair/RenderPS - { - - } - - scene_blend alpha_blend - depth_check on - depth_write on - cull_hardware none - cull_software none - } - pass InterpolateAndRenderDepth_HardwareTess - { - vertex_program_ref Ogre/Hair/InterpolateVS_DUMMY11 - { - - } - - tesselation_hull_program_ref Ogre/Hair/InterpolateHSMultiStrandDepth - { - - } - - tesselation_domain_program_ref Ogre/Hair/InterpolateDSMultiStrandDepth - { - - } - geometry_program_ref Ogre/Hair/InterpolateGSDepthShadows - { - - } - fragment_program_ref Ogre/Hair/RenderDepthPSSmall - { - - } - - scene_blend alpha_blend - depth_check on - depth_write on - cull_hardware none - cull_software none - } - - pass InterpolateAndRenderDepth_HardwareTess_DOM - { - vertex_program_ref Ogre/Hair/InterpolateVS_DUMMY11 - { - - } - - tesselation_hull_program_ref Ogre/Hair/InterpolateHSMultiStrandDepth - { - - } - - tesselation_domain_program_ref Ogre/Hair/InterpolateDSMultiStrandDepth - { - - } - geometry_program_ref Ogre/Hair/InterpolateGSDepthShadows - { - - } - fragment_program_ref Ogre/Hair/RenderDepthPSSmall_DOM - { - - } - - scene_blend add - scene_blend_op min - depth_check on - depth_write on - cull_hardware none - cull_software none - } - - pass InterpolateInstancedDepthVS_LOAD - { - vertex_program_ref Ogre/Hair/InterpolateVSMultiStrandDepthShadows_LOAD - { - - } - geometry_program_ref Ogre/Hair/InterpolateGSDepthShadows - { - - } - fragment_program_ref Ogre/Hair/RenderDepthPSSmall - { - - } - - depth_check on - depth_write on - cull_hardware none - cull_software none - } - - pass InterpolateInstancedDepthVS_LOAD_DOM - { - vertex_program_ref Ogre/Hair/InterpolateVSMultiStrandDepthShadows_LOAD - { - - } - geometry_program_ref Ogre/Hair/InterpolateGSDepthShadows - { - - } - fragment_program_ref Ogre/Hair/RenderDepthPSSmall_DOM - { - - } - - scene_blend add - scene_blend_op min - depth_check on - depth_write on - cull_hardware none - cull_software none - } - - pass InterpolateAndRenderCollisions_HardwareTess - { - vertex_program_ref Ogre/Hair/InterpolateVS_DUMMY11 - { - - } - - tesselation_hull_program_ref Ogre/Hair/InterpolateHSMultiStrandCollisions - { - - } - - tesselation_domain_program_ref Ogre/Hair/InterpolateDSMultiStrandCollisionsWithGS - { - - } - geometry_program_ref Ogre/Hair/InterpolateGSMultiStrandCollisions - { - - } - fragment_program_ref Ogre/Hair/InterpolatePSMultiStrandCollisions - { - - } - - scene_blend add - scene_blend_op min - depth_check off - depth_write off - cull_hardware none - cull_software none - } - pass InterpolateInstancedBaryCentricCollisions - { - vertex_program_ref Ogre/Hair/InterpolateVSMultiStrandCollisions - { - - } - fragment_program_ref Ogre/Hair/InterpolatePSMultiStrandCollisions - { - - } - - scene_blend add - scene_blend_op min - depth_check off - depth_write off - cull_hardware none - cull_software none - } - - //tessellation - pass Tessellate - { - vertex_program_ref Ogre/Hair/TessellateVSBSplinePassThrough - { - - } - geometry_program_ref Ogre/Hair/TessellateGSBSpline - { - - } - depth_check off - depth_write off - } - pass TessellateSB - { - vertex_program_ref Ogre/Hair/TessellateVSBSplinePassThrough - { - - } - geometry_program_ref Ogre/Hair/TessellateGSBSplineSB - { - - } - depth_check off - depth_write off - } - - pass TessellateCoordinateFrames - { - vertex_program_ref Ogre/Hair/TessellateVSBSplineCFs - { - - } - geometry_program_ref Ogre/Hair/TessellateVSBSplineCFsG - { - - } - depth_check off - depth_write off - } - - pass TessellateCoordinateFramesSB - { - vertex_program_ref Ogre/Hair/TessellateVSBSplineSBCFs - { - - } - geometry_program_ref Ogre/Hair/TessellateVSBSplineSBCFsG - { - - } - depth_check off - depth_write off - } - - pass TessellateLengths - { - vertex_program_ref Ogre/Hair/TessellateVSBSplineLengths - { - - } - geometry_program_ref Ogre/Hair/TessellateVSBSplineLengthsG - { - - } - - depth_check off - depth_write off - } - - //streamout the attributes----------------------------------------------------- - pass SO_M_Attributes - { - vertex_program_ref Ogre/Hair/InterpolateVSMultiStrand_SO - { - - } - geometry_program_ref Ogre/Hair/InterpolateVSMultiStrand_SOG - { - - } - - depth_check off - depth_write off - } - pass SO_S_Attributes - { - vertex_program_ref Ogre/Hair/InterpolateVSSingleStrand_SO - { - - } - geometry_program_ref Ogre/Hair/InterpolateVSSingleStrand_SOG - { - - } - - depth_check off - depth_write off - } - pass InterpolateInstancedDepthVSSingleStrand11 - { - vertex_program_ref Ogre/Hair/InterpolateVS_DUMMY11 - { - - } - - tesselation_hull_program_ref Ogre/Hair/InterpolateHSSingleStrand - { - - } - - tesselation_domain_program_ref Ogre/Hair/InterpolateDSSingleStrand_DEPTH - { - - } - geometry_program_ref Ogre/Hair/InterpolateGSDepthShadows - { - - } - fragment_program_ref Ogre/Hair/RenderDepthPSSmall - { - - } - - depth_check on - depth_write on - cull_hardware none - cull_software none - } - pass InterpolateInstancedDepthVSSingleStrand11_DOM - { - vertex_program_ref Ogre/Hair/InterpolateVS_DUMMY11 - { - - } - - tesselation_hull_program_ref Ogre/Hair/InterpolateHSSingleStrand - { - - } - - tesselation_domain_program_ref Ogre/Hair/InterpolateDSSingleStrand_DEPTH - { - - } - geometry_program_ref Ogre/Hair/InterpolateGSDepthShadows - { - - } - fragment_program_ref Ogre/Hair/RenderDepthPSSmall_DOM - { - - } - - scene_blend add - scene_blend_op min - depth_check off - depth_write off - cull_hardware none - cull_software none - } - pass InterpolateAndRenderS_HardwareTess - { - vertex_program_ref Ogre/Hair/InterpolateVS_DUMMY11 - { - - } - - tesselation_hull_program_ref Ogre/Hair/InterpolateHSSingleStrand - { - - } - - tesselation_domain_program_ref Ogre/Hair/InterpolateDSSingleStrand_NORMAL - { - - } - geometry_program_ref Ogre/Hair/InterpolateGS - { - - } - fragment_program_ref Ogre/Hair/RenderPS - { - - } - - scene_blend alpha_blend - depth_check on - depth_write on - cull_hardware none - cull_software none - } - - //normal rendering - pass InterpolateInstancedDepthPrepassVS - { - vertex_program_ref Ogre/Hair/InterpolateVSDepthPrepass - { - - } - geometry_program_ref Ogre/Hair/InterpolateGSDepthPrepass - { - - } - fragment_program_ref Ogre/Hair/RenderPSDepthPrepass - { - - } - - alpha_to_coverage on - depth_check on - depth_write on - cull_hardware none - cull_software none - } - pass InterpolateInstancedDepthPrepassVS_LOAD - { - vertex_program_ref Ogre/Hair/InterpolateVSDepthPrepass_LOAD - { - - } - geometry_program_ref Ogre/Hair/InterpolateGSDepthPrepass - { - - } - fragment_program_ref Ogre/Hair/RenderPSDepthPrepass - { - - } - - alpha_to_coverage on - depth_check on - depth_write on - cull_hardware none - cull_software none - } - - pass InterpolateInstancedVS - { - vertex_program_ref Ogre/Hair/InterpolateVSMultiStrand - { - - } - geometry_program_ref Ogre/Hair/InterpolateGS - { - - } - fragment_program_ref Ogre/Hair/RenderPS - { - - } - - scene_blend alpha_blend - depth_check on - depth_write on - cull_hardware none - cull_software none - } - - - pass InterpolateInstancedVSSingleStrandDepthPrepass - { - vertex_program_ref Ogre/Hair/InterpolateVSClumpDepthPrepass - { - - } - geometry_program_ref Ogre/Hair/InterpolateGSDepthPrepass - { - - } - fragment_program_ref Ogre/Hair/RenderPSDepthPrepass - { - - } - - alpha_to_coverage on - depth_check on - depth_write on - cull_hardware none - cull_software none - } - pass InterpolateInstancedVSSingleStrandDepthPrepass_LOAD - { - vertex_program_ref Ogre/Hair/InterpolateVSClumpDepthPrepass_LOAD - { - - } - geometry_program_ref Ogre/Hair/InterpolateGSDepthPrepass - { - - } - fragment_program_ref Ogre/Hair/RenderPSDepthPrepass - { - - } - - alpha_to_coverage on - depth_check on - depth_write on - cull_hardware none - cull_software none - } - - pass InterpolateInstancedVSSingleStrand - { - vertex_program_ref Ogre/Hair/InterpolateVSSingleStrand - { - - } - geometry_program_ref Ogre/Hair/InterpolateGS - { - - } - fragment_program_ref Ogre/Hair/RenderPS - { - - } - - scene_blend alpha_blend - depth_check on - depth_write on - cull_hardware none - cull_software none - } - pass InterpolateInstancedVSSingleStrand_LOAD - { - vertex_program_ref Ogre/Hair/InterpolateVSSingleStrand_LOAD - { - - } - geometry_program_ref Ogre/Hair/InterpolateGS - { - - } - fragment_program_ref Ogre/Hair/RenderPS - { - - } - - scene_blend alpha_blend - depth_check on - depth_write on - cull_hardware none - cull_software none - } - - //density rendering - - pass InterpolateInstancedVSRenderCollisionsNormal - { - vertex_program_ref Ogre/Hair/InterpolateVSMCollisions - { - - } - geometry_program_ref Ogre/Hair/InterpolateGSMCollisions - { - - } - fragment_program_ref Ogre/Hair/InterpolatePSMCollisions - { - - } - - depth_check on - depth_write on - cull_hardware none - cull_software none - } - - pass InterpolateInstancedVSForGrid3DTextureMRT - { - vertex_program_ref Ogre/Hair/InterpolateVS2Grid - { - - } - geometry_program_ref Ogre/Hair/InterpolateGS2Grid - { - - } - fragment_program_ref Ogre/Hair/RenderPSForGridMRT - { - - } - scene_blend add - depth_check on - depth_write on - cull_hardware none - cull_software none - } - //next passes are for shadows - pass InterpolateInstancedDepthVS - { - vertex_program_ref Ogre/Hair/InterpolateVSBMultiStrandDepthShadows - { - - } - geometry_program_ref Ogre/Hair/InterpolateGSDepthShadows - { - - } - fragment_program_ref Ogre/Hair/RenderDepthPSSmall - { - - } - depth_check on - depth_write on - cull_hardware none - cull_software none - } - - pass InterpolateInstancedDepthVS_DOM - { - vertex_program_ref Ogre/Hair/InterpolateVSBMultiStrandDepthShadows - { - - } - geometry_program_ref Ogre/Hair/InterpolateGSDepthShadows - { - - } - fragment_program_ref Ogre/Hair/RenderDepthPSSmall_DOM - { - - } - scene_blend add - depth_check on - depth_write on - cull_hardware none - cull_software none - } - - pass InterpolateInstancedDepthVSSingleStrand - { - vertex_program_ref Ogre/Hair/InterpolateVSSingleStrandDepthShadows - { - - } - geometry_program_ref Ogre/Hair/InterpolateGSDepthShadows - { - - } - fragment_program_ref Ogre/Hair/RenderDepthPSSmall - { - - } - depth_check on - depth_write on - cull_hardware none - cull_software none - } - - pass InterpolateInstancedDepthVSSingleStrand_DOM - { - vertex_program_ref Ogre/Hair/InterpolateVSSingleStrandDepthShadows - { - - } - geometry_program_ref Ogre/Hair/InterpolateGSDepthShadows - { - - } - fragment_program_ref Ogre/Hair/RenderDepthPSSmall_DOM - { - - } - scene_blend add - depth_check on - depth_write on - cull_hardware none - cull_software none - } - - pass InterpolateInstancedDepthVSSingleStrand_LOAD - { - vertex_program_ref Ogre/Hair/InterpolateVSSingleStrandDepthShadows_LOAD - { - - } - geometry_program_ref Ogre/Hair/InterpolateGSDepthShadows - { - - } - fragment_program_ref Ogre/Hair/RenderDepthPSSmall - { - - } - depth_check on - depth_write on - cull_hardware none - cull_software none - } - pass InterpolateInstancedDepthVSSingleStrand_LOAD_DOM - { - vertex_program_ref Ogre/Hair/InterpolateVSSingleStrandDepthShadows_LOAD - { - - } - geometry_program_ref Ogre/Hair/InterpolateGSDepthShadows - { - - } - fragment_program_ref Ogre/Hair/RenderDepthPSSmall_DOM - { - - } - scene_blend add - depth_check on - depth_write on - cull_hardware none - cull_software none - } - - pass VisualizeShadowMap - { - vertex_program_ref Ogre/Hair/FullScreenTriVS - { - - } - fragment_program_ref Ogre/Hair/VisDepthsPS - { - - } - depth_check off - depth_write off - cull_hardware none - cull_software none - } - - pass copyTexture - { - vertex_program_ref Ogre/Hair/FullScreenTriVS - { - - } - fragment_program_ref Ogre/Hair/CopyTexturePS - { - - } - scene_blend alpha_blend - depth_check off - depth_write off - cull_hardware none - cull_software none - } - - pass AllNulls - { - } - } -} - -material Ogre/Hair/RenderMesh -{ - technique RenderMesh - { - pass RenderWithoutShadows - { - vertex_program_ref Ogre/Hair/MeshVS - { - - } - fragment_program_ref Ogre/Hair/MeshPS - { - - } - depth_check on - depth_write off - cull_hardware none - cull_software none - } - pass RenderWithShadows - { - vertex_program_ref Ogre/Hair/MeshVSShadows - { - - } - fragment_program_ref Ogre/Hair/MeshPSShadows - { - - } - depth_check on - depth_write off - cull_hardware none - cull_software none - } - pass RenderMeshDepthPass - { - vertex_program_ref Ogre/Hair/MeshVS - { - - } - fragment_program_ref Ogre/Hair/MeshPS - { - - } - depth_check off - depth_write off - cull_hardware none - cull_software none - colour_write off - } - } -} -material Ogre/Hair/RenderPlane -{ - technique RenderPlane - { - pass RenderPlaneWithShadows - { - vertex_program_ref Ogre/Hair/VSDrawPlane - { - - } - fragment_program_ref Ogre/Hair/PSDrawPlane - { - - } - depth_check on - depth_write on - cull_hardware none - cull_software none - - } - pass RenderPlaneWithoutShadows - { - vertex_program_ref Ogre/Hair/VSDrawPlane - { - - } - fragment_program_ref Ogre/Hair/PSDrawPlane - { - - } - depth_check on - depth_write on - cull_hardware none - cull_software none - } - } -} - -material Ogre/Hair/RenderMeshDepth -{ - technique RenderMeshDepth - { - pass - { - vertex_program_ref Ogre/Hair/MeshDepthVS - { - - } - fragment_program_ref Ogre/Hair/MeshDepthPS - { - - } - depth_check on - depth_write on - cull_hardware none - cull_software none - } - } -} -material Ogre/Hair/RenderMeshDepth_DOM -{ - technique RenderMeshDepth_DOM - { - pass - { - vertex_program_ref Ogre/Hair/MeshDepthVS - { - - } - fragment_program_ref Ogre/Hair/MeshDepthPS_DOM - { - - } - scene_blend add - depth_check off - depth_write off - cull_hardware none - cull_software none - } - } -} - -material Ogre/Hair/RenderArrow -{ - technique RenderArrow - { - pass P0 - { - vertex_program_ref Ogre/Hair/VSArrow - { - - } - fragment_program_ref Ogre/Hair/PSArrow - { - - } - depth_check on - depth_write off - cull_hardware none - cull_software none - } - } -} - -material Ogre/Hair/DrawTexture -{ - technique DrawTexture - { - pass - { - vertex_program_ref Ogre/Hair/VS_GRID - { - - } - - fragment_program_ref Ogre/Hair/PS_DRAW_TEXTURE - { - - } - depth_check off - depth_write off - } - pass drawCollisionsTexture - { - vertex_program_ref Ogre/Hair/VS_COLLISIONS - { - - } - - fragment_program_ref Ogre/Hair/PS_DRAW_COLLISIONS_TEXTURE - { - - } - depth_check off - depth_write off - } - pass ResolveSuperSample - { - vertex_program_ref Ogre/Hair/VS_COLLISIONS - { - - } - - fragment_program_ref Ogre/Hair/PS_RESOLVE_SUPERSAMPLE - { - - } - depth_check off - depth_write off - } - pass ReconstructDepth - { - vertex_program_ref Ogre/Hair/VS_COLLISIONS - { - - } - - fragment_program_ref Ogre/Hair/PS_RECONSTRUCT_DEPTH - { - - } - depth_check off - depth_write on - colour_write off - } - } -} - -material Ogre/Hair/DrawTextureDemuxed -{ - technique DrawTextureDemuxed - { - pass - { - vertex_program_ref Ogre/Hair/VS_GRID - { - - } - - fragment_program_ref Ogre/Hair/PS_DRAW_TEXTURE_DEMUX - { - - } - depth_check off - depth_write off - } - } -} - -material Ogre/Hair/TextureDemux -{ - technique TextureDemux - { - pass - { - vertex_program_ref Ogre/Hair/VS_GRID - { - - } - - fragment_program_ref Ogre/Hair/PS_DEMUX - { - - } - depth_check off - depth_write off - } - } -} - -material Ogre/Hair/VoxelizeObstacles -{ - technique VoxelizeObstacles - { - pass - { - vertex_program_ref Ogre/Hair/VS_GRID - { - - } - - fragment_program_ref Ogre/Hair/PS_VOXELIZE_OBSTACLES - { - - } - depth_check off - depth_write off - } - } -} - -material Ogre/Hair/RenderCollisionObjects -{ - technique RenderCollisionObjects - { - pass - { - vertex_program_ref Ogre/Hair/CollisionVS - { - - } - - fragment_program_ref Ogre/Hair/CollisionPS - { - - } - depth_check on - depth_write off - cull_hardware none - cull_software none - } - } -} - -material Ogre/Hair/DemuxTo3DFluidObstacles -{ - technique DemuxTo3DFluidObstacles - { - pass - { - vertex_program_ref Ogre/Hair/VS_GRID_FLUIDSIM - { - - } - geometry_program_ref Ogre/Hair/GS_ARRAY - { - - } - fragment_program_ref Ogre/Hair/PS_DEMUX_TO_3D_OBSTACLE_TEX - { - - } - depth_check off - depth_write off - } - - } -}*/ \ No newline at end of file diff --git a/Samples/Media/materials/scripts/Halftone.material b/Samples/Media/materials/scripts/Halftone.material deleted file mode 100644 index 6ce22b4aab7..00000000000 --- a/Samples/Media/materials/scripts/Halftone.material +++ /dev/null @@ -1,93 +0,0 @@ -fragment_program Ogre/Compositor/HalftoneFPCg hlsl -{ - source HalftoneFP.cg - entry_point Halftone_ps - - default_params - { - param_named numTiles float2 133.3 100 - param_named iNumTiles float2 0.00750750 0.01 - param_named iNumTiles2 float2 0.00375375 0.005 - param_named lum float4 0.30 0.59 0.11 0.0 - } -} - -fragment_program Ogre/Compositor/HalftoneFPGLSL glsl -{ - source HalftoneFP.glsl - syntax glsl150 - - default_params - { - param_named numTiles float2 133.3 100 - param_named iNumTiles float2 0.00750750 0.01 - param_named iNumTiles2 float2 0.00375375 0.005 - param_named lum float4 0.30 0.59 0.11 0.0 - param_named RT int 0 - param_named noise int 1 - } -} - -fragment_program Ogre/Compositor/HalftoneFPGLSLES glsles -{ - source HalftoneFP.glsles - syntax glsl300es - - default_params - { - param_named numTiles float2 133.3 100 - param_named iNumTiles float2 0.00750750 0.01 - param_named iNumTiles2 float2 0.00375375 0.005 - param_named lum float4 0.30 0.59 0.11 0.0 - param_named RT int 0 - param_named noise int 1 - } -} - -fragment_program Ogre/Compositor/HalftoneFP unified -{ - delegate Ogre/Compositor/HalftoneFPGLSL - delegate Ogre/Compositor/HalftoneFPGLSLES - delegate Ogre/Compositor/HalftoneFPCg -} - -material Ogre/Compositor/Halftone -{ - technique - { - - pass - { - cull_hardware none - depth_func always_pass - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_Tex2a_vp - { - } - - - fragment_program_ref Ogre/Compositor/HalftoneFP - { - - } - - texture_unit RT - { - tex_coord_set 0 - tex_address_mode clamp - filtering trilinear - } - - texture_unit noise - { - tex_coord_set 0 - filtering trilinear - tex_address_mode clamp - tex_border_colour 1.0 0.0 0.0 - } - - } - } -} - diff --git a/Samples/Media/materials/scripts/HardwareSkinningShadow.material b/Samples/Media/materials/scripts/HardwareSkinningShadow.material deleted file mode 100644 index 48476262026..00000000000 --- a/Samples/Media/materials/scripts/HardwareSkinningShadow.material +++ /dev/null @@ -1,204 +0,0 @@ -/////////////////////////////////////////////////////////////////////////// -/// Declare materials for casters and casters with hardware skinning -/////////////////////////////////////////////////////////////////////////// - -material Ogre/RTShader/shadow_caster_skinning_1weight -{ - technique - { - pass - { - diffuse 0 0 0 - fog_override true none - rtshader_system - { - hardware_skinning 24 1 - } - } - } -} - - -material Ogre/RTShader/shadow_caster_skinning_2weight -{ - technique - { - pass - { - diffuse 0 0 0 - fog_override true none - rtshader_system - { - hardware_skinning 24 2 - } - } - } -} - - -material Ogre/RTShader/shadow_caster_skinning_3weight -{ - technique - { - pass - { - diffuse 0 0 0 - fog_override true none - rtshader_system - { - hardware_skinning 24 3 - } - } - } -} - - -material Ogre/RTShader/shadow_caster_skinning_4weight -{ - technique - { - pass - { - diffuse 0 0 0 - fog_override true none - rtshader_system - { - hardware_skinning 24 4 - } - } - } -} - -material Ogre/RTShader/shadow_caster_dq_skinning_1weight -{ - technique - { - pass - { - diffuse 0 0 0 - fog_override true none - rtshader_system - { - hardware_skinning 24 1 dual_quaternion true false - } - } - } -} - - -material Ogre/RTShader/shadow_caster_dq_skinning_2weight -{ - technique - { - pass - { - diffuse 0 0 0 - fog_override true none - rtshader_system - { - hardware_skinning 24 2 dual_quaternion true false - } - } - } -} - - -material Ogre/RTShader/shadow_caster_dq_skinning_3weight -{ - technique - { - pass - { - diffuse 0 0 0 - fog_override true none - rtshader_system - { - hardware_skinning 24 3 dual_quaternion true false - } - } - } -} - - -material Ogre/RTShader/shadow_caster_dq_skinning_4weight -{ - technique - { - pass - { - diffuse 0 0 0 - fog_override true none - rtshader_system - { - hardware_skinning 24 4 dual_quaternion true false - } - } - } -} - -material Ogre/RTShader/shadow_caster_dq_skinning_1weight_twophase -{ - technique - { - pass - { - diffuse 0 0 0 - fog_override true none - rtshader_system - { - hardware_skinning 24 1 dual_quaternion true true - } - } - } -} - - -material Ogre/RTShader/shadow_caster_dq_skinning_2weight_twophase -{ - technique - { - pass - { - diffuse 0 0 0 - fog_override true none - rtshader_system - { - hardware_skinning 24 2 dual_quaternion true true - } - } - } -} - - -material Ogre/RTShader/shadow_caster_dq_skinning_3weight_twophase -{ - technique - { - pass - { - diffuse 0 0 0 - fog_override true none - rtshader_system - { - hardware_skinning 24 3 dual_quaternion true true - } - } - } -} - - -material Ogre/RTShader/shadow_caster_dq_skinning_4weight_twophase -{ - technique - { - pass - { - diffuse 0 0 0 - fog_override true none - rtshader_system - { - hardware_skinning 24 4 dual_quaternion true true - } - } - } -} diff --git a/Samples/Media/materials/scripts/HeatVision.material b/Samples/Media/materials/scripts/HeatVision.material deleted file mode 100644 index abf27d44b01..00000000000 --- a/Samples/Media/materials/scripts/HeatVision.material +++ /dev/null @@ -1,308 +0,0 @@ -/////////////////////////////////// -// PASS 0 -// HEAT CASTERS PASS -/////////////////////////////////// - -vertex_program Fury/HeatVision/HeatCaster_Cg_vp cg -{ - source HeatVision.cg - entry_point HeatCaster_vp - profiles vs_4_0 vs_4_0_level_9_1 vs_4_0_level_9_3 vs_1_1 arbvp1 -} - -fragment_program Fury/HeatVision/HeatCaster_Cg_fp cg -{ - source HeatVision.cg - entry_point HeatCaster_fp - profiles ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 ps_2_0 arbfp1 -} - -vertex_program Fury/HeatVision/HeatCaster_HLSL_vp hlsl -{ - source HeatVision.hlsl - entry_point HeatCaster_vp - target vs_4_0 vs_4_0_level_9_1 vs_4_0_level_9_3 -} - -fragment_program Fury/HeatVision/HeatCaster_HLSL_fp hlsl -{ - source HeatVision.hlsl - entry_point HeatCaster_fp - target ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 -} - -vertex_program Fury/HeatVision/HeatCaster_GLSL_vp glsl glsles -{ - source HeatCasterVp.glsl -} - -fragment_program Fury/HeatVision/HeatCaster_GLSL_fp glsl glsles -{ - source HeatCasterFp.glsl -} - -vertex_program Fury/HeatVision/HeatCaster_vp unified -{ - delegate Fury/HeatVision/HeatCaster_GLSL_vp - delegate Fury/HeatVision/HeatCaster_HLSL_vp - delegate Fury/HeatVision/HeatCaster_Cg_vp -} - -fragment_program Fury/HeatVision/HeatCaster_fp unified -{ - delegate Fury/HeatVision/HeatCaster_GLSL_fp - delegate Fury/HeatVision/HeatCaster_HLSL_fp - delegate Fury/HeatVision/HeatCaster_Cg_fp -} - -material Fury/HeatVision/HeatCaster -{ - technique - { - pass - { - polygon_mode_overrideable false - vertex_program_ref Fury/HeatVision/HeatCaster_vp - { - param_named_auto eyePosition camera_position_object_space - param_named_auto worldViewProj worldviewproj_matrix - } - - fragment_program_ref Fury/HeatVision/HeatCaster_fp - { - } - } - } -} - -/////////////////////////////////// -// PASS 0 -// HEAT CASTERS PASS -/////////////////////////////////// - -vertex_program Fury/HeatVision/ColdCaster_Cg_vp cg -{ - source HeatVision.cg - entry_point ColdCaster_vp - profiles vs_4_0 vs_4_0_level_9_1 vs_4_0_level_9_3 vs_1_1 arbvp1 -} - -fragment_program Fury/HeatVision/ColdCaster_Cg_fp cg -{ - source HeatVision.cg - entry_point ColdCaster_fp - profiles ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 ps_2_0 arbfp1 -} - -vertex_program Fury/HeatVision/ColdCaster_HLSL_vp hlsl -{ - source HeatVision.hlsl - entry_point ColdCaster_vp - target vs_4_0 vs_4_0_level_9_1 vs_4_0_level_9_3 -} - -fragment_program Fury/HeatVision/ColdCaster_HLSL_fp hlsl -{ - source HeatVision.hlsl - entry_point ColdCaster_fp - target ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 -} - -vertex_program Fury/HeatVision/ColdCaster_GLSL_vp glsl glsles -{ - source ColdCasterVp.glsl -} - -fragment_program Fury/HeatVision/ColdCaster_GLSL_fp glsl glsles -{ - source ColdCasterFp.glsl -} - -vertex_program Fury/HeatVision/ColdCaster_vp unified -{ - delegate Fury/HeatVision/ColdCaster_GLSL_vp - delegate Fury/HeatVision/ColdCaster_HLSL_vp - delegate Fury/HeatVision/ColdCaster_Cg_vp -} - -fragment_program Fury/HeatVision/ColdCaster_fp unified -{ - delegate Fury/HeatVision/ColdCaster_GLSL_fp - delegate Fury/HeatVision/ColdCaster_HLSL_fp - delegate Fury/HeatVision/ColdCaster_Cg_fp -} - -material Fury/HeatVision/ColdCaster -{ - technique - { - pass - { - polygon_mode_overrideable false - vertex_program_ref Fury/HeatVision/ColdCaster_vp - { - param_named_auto eyePosition camera_position_object_space - param_named_auto worldViewProj worldviewproj_matrix - } - - fragment_program_ref Fury/HeatVision/ColdCaster_fp - { - } - } - } -} - -/////////////////////////////////// -// PASS 1 -// LIGHT TO HEAT CONVERSION PASS -/////////////////////////////////// - -fragment_program Fury/HeatVision/LightToHeat_Cg_fp cg -{ - source HeatVision.cg - entry_point LightToHeat_fp - profiles ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 ps_2_0 arbfp1 -} - -fragment_program Fury/HeatVision/LightToHeat_HLSL_fp hlsl -{ - source HeatVision.hlsl - entry_point LightToHeat_fp - target ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 -} - -fragment_program Fury/HeatVision/LightToHeat_GLSL_fp glsl glsles -{ - source LightToHeatFp.glsl - default_params - { - param_named Input int 0 - param_named NoiseMap int 1 - param_named HeatLookup int 2 - } -} - -fragment_program Fury/HeatVision/LightToHeat_fp unified -{ - delegate Fury/HeatVision/LightToHeat_GLSL_fp - delegate Fury/HeatVision/LightToHeat_HLSL_fp - delegate Fury/HeatVision/LightToHeat_Cg_fp -} - -material Fury/HeatVision/LightToHeat -{ - technique - { - pass - { - cull_hardware none - depth_func always_pass - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_vp - { - } - - fragment_program_ref Fury/HeatVision/LightToHeat_fp - { - // these should be *really* random! - param_named random_fractions float4 0.3 0.7 0 0 - - param_named depth_modulator float4 0.6 0 0 0 - - // this one can be fixed - param_named heatBiasScale float4 0.0 1.0 0 0 - } - - // INPUT (from scene, where entities has "Fury/HeatVision/Caster" material for heat emanation) - texture_unit - { - tex_coord_set 0 - filtering linear linear none - tex_address_mode clamp - } - - // Noise map - texture_unit - { - texture HeatNoise.tga - tex_coord_set 0 - } - - // heat conversion texture - texture_unit - { - texture HeatLookup.tga - tex_coord_set 0 - filtering point point none - } - } - } - -} - - -/////////////////////////////////// -// PASS 2 -// BLUR PASS -/////////////////////////////////// - -fragment_program Fury/HeatVision/Blur_Cg_fp cg -{ - source HeatVision.cg - entry_point Blur_fp - profiles ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 ps_2_0 arbfp1 -} - -fragment_program Fury/HeatVision/Blur_HLSL_fp hlsl -{ - source HeatVision.hlsl - entry_point Blur_fp - target ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 -} - -fragment_program Fury/HeatVision/Blur_GLSL_fp glsl glsles -{ - source HeatBlurFp.glsl - default_params - { - param_named Input int 0 - } -} - -fragment_program Fury/HeatVision/Blur_fp unified -{ - delegate Fury/HeatVision/Blur_GLSL_fp - delegate Fury/HeatVision/Blur_HLSL_fp - delegate Fury/HeatVision/Blur_Cg_fp -} - -material Fury/HeatVision/Blur -{ - technique - { - pass - { - cull_hardware none - depth_func always_pass - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_vp - { - } - - fragment_program_ref Fury/HeatVision/Blur_fp - { - param_named blurAmount float4 0.5 0 0 0 - } - - // INPUT (from previous) - texture_unit - { - tex_coord_set 0 - filtering linear linear none - tex_address_mode clamp - } - } - } -} diff --git a/Samples/Media/materials/scripts/Hurt.material b/Samples/Media/materials/scripts/Hurt.material deleted file mode 100644 index e70ab4de693..00000000000 --- a/Samples/Media/materials/scripts/Hurt.material +++ /dev/null @@ -1,18 +0,0 @@ -/// Just a simple red quad blended over the scene -material RedQuad -{ - technique - { - pass - { - lighting on - diffuse 0.0 0.0 0.0 0.5 - specular 0.0 0.0 0.0 1.0 - ambient 0.0 0.0 0.0 - emissive 1.0 0.0 0.0 - cull_hardware none - depth_check off - scene_blend alpha_blend - } - } -} diff --git a/Samples/Media/materials/scripts/Instancing.program b/Samples/Media/materials/scripts/Instancing.program deleted file mode 100644 index c5afe034f0c..00000000000 --- a/Samples/Media/materials/scripts/Instancing.program +++ /dev/null @@ -1,90 +0,0 @@ -//--------------------------------------------------------------------------- -//These materials/shaders are part of the NEW InstanceManager implementation -//Written by Matias N. Goldberg ("dark_sylinc") -//--------------------------------------------------------------------------- - -//-------------------------------------------------------------- -// GLSL Programs -//-------------------------------------------------------------- -fragment_program Ogre/Instancing_glsl_ps glsl -{ - source Instancing.frag - - preprocessor_defines DEPTH_SHADOWRECEIVER=1 - - default_params - { - param_named diffuseMap int 0 - param_named shadowMap int 1 - } -} - -fragment_program Ogre/Instancing/shadow_caster_glsl_ps glsl glsles -{ - source pssmCasterFp.glsl -} - -//-------------------------------------------------------------- -// GLSL ES Programs -//-------------------------------------------------------------- -fragment_program Ogre/Instancing_glsles_ps glsles -{ - source Instancing.frag - syntax glsl300es - - preprocessor_defines DEPTH_SHADOWRECEIVER=1 - - default_params - { - param_named diffuseMap int 0 - param_named shadowMap int 1 - } -} - -//-------------------------------------------------------------- -// CG Programs -//-------------------------------------------------------------- -fragment_program Ogre/Instancing_hlsl_ps hlsl -{ - source Instancing_ps.cg - entry_point main_ps - preprocessor_defines DEPTH_SHADOWRECEIVER -} - -fragment_program Ogre/Instancing/shadow_caster_hlsl_ps hlsl -{ - source pssm.cg - target ps_3_0 - entry_point shadow_caster_ps - - default_params - { - } -} - - -//-------------------------------------------------------------- -// Unified CG/GLSL Programs -//-------------------------------------------------------------- -fragment_program Ogre/Instancing_ps unified -{ - delegate Ogre/Instancing_glsl_ps - delegate Ogre/Instancing_glsles_ps - delegate Ogre/Instancing_hlsl_ps - - default_params - { - param_named_auto lightPosition light_position 0 - param_named_auto cameraPosition camera_position - param_named_auto lightAmbient ambient_light_colour - param_named_auto lightDiffuse light_diffuse_colour 0 - param_named_auto lightSpecular light_specular_colour 0 - param_named_auto lightGloss surface_shininess - } -} - -fragment_program Ogre/Instancing/shadow_caster_ps unified -{ - delegate Ogre/Instancing/shadow_caster_glsl_ps - delegate Ogre/Instancing/shadow_caster_hlsl_ps -} diff --git a/Samples/Media/materials/scripts/Invert.material b/Samples/Media/materials/scripts/Invert.material deleted file mode 100644 index 7152acf86f5..00000000000 --- a/Samples/Media/materials/scripts/Invert.material +++ /dev/null @@ -1,46 +0,0 @@ -fragment_program Ogre/Compositor/Invert_Cg_FP hlsl -{ - source InvertFP.cg - entry_point Invert_ps -} - -fragment_program Ogre/Compositor/Invert_GLSL_FP glsl glsles -{ - source InvertFP.glsl -} - -fragment_program Ogre/Compositor/InvertFP unified -{ - delegate Ogre/Compositor/Invert_GLSL_FP - delegate Ogre/Compositor/Invert_Cg_FP -} - -material Ogre/Compositor/Invert -{ - technique - { - - pass - { - cull_hardware none - depth_func always_pass - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_Tex2a_vp - { - } - - fragment_program_ref Ogre/Compositor/InvertFP - { - } - - texture_unit RT - { - tex_coord_set 0 - tex_address_mode clamp - filtering trilinear - } - - } - } -} diff --git a/Samples/Media/materials/scripts/Island.material b/Samples/Media/materials/scripts/Island.material deleted file mode 100644 index f700b1ef846..00000000000 --- a/Samples/Media/materials/scripts/Island.material +++ /dev/null @@ -1,376 +0,0 @@ -vertex_program Ogre/Island/FullScreenQuadVS hlsl -{ - source Island.hlsl - entry_point FullScreenQuadVS - target vs_4_0 - - default_params - { - - } -} - -fragment_program Ogre/Island/RefractionDepthManualResolvePS1 hlsl -{ - source Island.hlsl - entry_point RefractionDepthManualResolvePS1 - target ps_4_0 - - default_params - { - - } -} - -fragment_program Ogre/Island/RefractionDepthManualResolvePS2 hlsl -{ - source Island.hlsl - entry_point RefractionDepthManualResolvePS2 - target ps_4_0 - - default_params - { - - } -} - -fragment_program Ogre/Island/RefractionDepthManualResolvePS4 hlsl -{ - source Island.hlsl - entry_point RefractionDepthManualResolvePS2 - target ps_4_0 - - default_params - { - - } -} - -material Ogre/Island/RefractionDepthManualResolve -{ - technique RefractionDepthManualResolve - { - pass MS1 - { - vertex_program_ref Ogre/Island/FullScreenQuadVS - { - - } - fragment_program_ref Ogre/Island/RefractionDepthManualResolvePS1 - { - - } - - cull_hardware none - depth_check off - depth_write off - } - pass MS2 - { - vertex_program_ref Ogre/Island/FullScreenQuadVS - { - - } - fragment_program_ref Ogre/Island/RefractionDepthManualResolvePS2 - { - - } - - cull_hardware none - depth_check off - depth_write off - } - pass MS4 - { - vertex_program_ref Ogre/Island/FullScreenQuadVS - { - - } - fragment_program_ref Ogre/Island/RefractionDepthManualResolvePS4 - { - - } - - cull_hardware none - depth_check off - depth_write off - } - } - -} - -fragment_program Ogre/Island/MainToBackBufferPS hlsl -{ - source Island.hlsl - entry_point MainToBackBufferPS - target ps_4_0 - - default_params - { - param_named g_MainBufferSizeMultiplier float2 0.0 0.0 - } -} - -material Ogre/Island/MainToBackBuffer -{ - technique MainToBackBuffer - { - pass Solid - { - vertex_program_ref Ogre/Island/FullScreenQuadVS - { - - } - fragment_program_ref Ogre/Island/MainToBackBufferPS - { - - } - - cull_hardware none - depth_check off - depth_write off - } - } -} - -vertex_program Ogre/Island/WaterNormalmapCombineVS hlsl -{ - source Island.hlsl - entry_point WaterNormalmapCombineVS - target vs_4_0 - - default_params - { - - } -} - -fragment_program Ogre/Island/WaterNormalmapCombinePS hlsl -{ - source Island.hlsl - entry_point WaterNormalmapCombinePS - target ps_4_0 - - default_params - { - param_named_auto g_CameraPosition camera_position - param_named g_WaterBumpTexcoordShift float2 0.0 0.0 - } -} - -material Ogre/Island/WaterNormalmapCombine -{ - technique WaterNormalmapCombine - { - pass Solid - { - vertex_program_ref Ogre/Island/WaterNormalmapCombineVS - { - - } - fragment_program_ref Ogre/Island/WaterNormalmapCombinePS - { - - } - - cull_hardware none - depth_check off - depth_write off - } - } -} - -vertex_program Ogre/Island/PassThroughVS hlsl -{ - source Island.hlsl - entry_point PassThroughVS - target vs_5_0 - - default_params - { - - } -} - -tessellation_hull_program Ogre/Island/PatchHS hlsl -{ - source Island.hlsl - entry_point PatchHS - target hs_5_0 - - default_params - { - param_named g_FrustumCullInHS float 0.0 - param_named g_TerrainBeingRendered float 0.0 - param_named_auto g_ModelViewProjectionMatrix worldviewproj_matrix - param_named_auto g_CameraPosition camera_position - param_named_auto g_CameraDirection view_direction - } -} - -tessellation_domain_program Ogre/Island/HeightFieldPatchDS hlsl -{ - source Island.hlsl - entry_point HeightFieldPatchDS - target ds_5_0 - - default_params - { - param_named g_RenderCaustics float 0.0 - param_named g_UseDynamicLOD float 0.0 - param_named g_DynamicTessFactor float 0.0 - param_named g_StaticTessFactor float 0.0 - param_named g_SkipCausticsCalculation float 0.0 - param_named_auto g_ModelViewProjectionMatrix worldviewproj_matrix - param_named_auto g_CameraPosition camera_position - } -} - -fragment_program Ogre/Island/HeightFieldPatchPS hlsl -{ - source Island.hlsl - entry_point HeightFieldPatchPS - target ps_5_0 - - default_params - { - param_named g_HalfSpaceCullSign float 0.0 - param_named g_HalfSpaceCullPosition float 0.0 - param_named_auto g_LightModelViewProjectionMatrix worldviewproj_matrix - param_named_auto g_CameraPosition camera_position - param_named_auto g_LightPosition light_position - } -} - -fragment_program Ogre/Island/ColorPS hlsl -{ - source IslandCommon.hlsl - entry_point ColorPS - target ps_5_0 - - default_params - { - - } -} - -material Ogre/Island/RenderHeightfield -{ - technique RenderHeightfield - { - pass Solid - { - vertex_program_ref Ogre/Island/PassThroughVS - { - - } - tessellation_hull_program_ref Ogre/Island/PatchHS - { - - } - tessellation_domain_program_ref Ogre/Island/HeightFieldPatchDS - { - - } - fragment_program_ref Ogre/Island/HeightFieldPatchPS - { - - } - - depth_check on - depth_write on - } - - pass DepthOnly - { - vertex_program_ref Ogre/Island/PassThroughVS - { - - } - tessellation_hull_program_ref Ogre/Island/PatchHS - { - - } - tessellation_domain_program_ref Ogre/Island/HeightFieldPatchDS - { - - } - fragment_program_ref Ogre/Island/ColorPS - { - - } - - depth_check on - depth_write on - } - } -} - -tessellation_domain_program Ogre/Island/WaterPatchDS hlsl -{ - source Island.hlsl - entry_point WaterPatchDS - target ds_5_0 - - default_params - { - param_named g_UseDynamicLOD float 0.0 - param_named g_DynamicTessFactor float 0.0 - param_named g_StaticTessFactor float 0.0 - param_named_auto g_ModelViewProjectionMatrix worldviewproj_matrix - param_named_auto g_CameraPosition camera_position - param_named_auto g_LightPosition light_position - param_named g_WaterBumpTexcoordShift float2 0.0 0.0 - } -} - -fragment_program Ogre/Island/WaterPatchPS hlsl -{ - source IslandCommon.hlsl - entry_point WaterPatchPS - target ps_5_0 - - default_params - { - param_named_auto g_ModelViewMatrix worldview_matrix - param_named_auto g_ModelViewProjectionMatrix worldviewproj_matrix - param_named_auto g_LightModelViewProjectionMatrix worldviewproj_matrix - param_named_auto g_CameraPosition camera_position - param_named_auto g_LightPosition light_position - param_named g_WaterBumpTexcoordShift float2 0.0 0.0 - param_named g_ScreenSizeInv float2 0.0 0.0 - param_named g_ZNear float 0.0 - param_named g_ZFar float 0.0 - param_named g_something float 10.0 - } -} - -material Ogre/Island/RenderWater -{ - technique RenderWater - { - pass Solid - { - vertex_program_ref Ogre/Island/PassThroughVS - { - - } - tessellation_hull_program_ref Ogre/Island/PatchHS - { - - } - tessellation_domain_program_ref Ogre/Island/WaterPatchDS - { - - } - fragment_program_ref Ogre/Island/WaterPatchPS - { - - } - - depth_check on - depth_write on - } - - } -} diff --git a/Samples/Media/materials/scripts/IsoSurf.material b/Samples/Media/materials/scripts/IsoSurf.material deleted file mode 100644 index 8da3720f203..00000000000 --- a/Samples/Media/materials/scripts/IsoSurf.material +++ /dev/null @@ -1,126 +0,0 @@ -////////// -// HLSL // -////////// -geometry_program Ogre/Isosurf/TessellateTetrahedraGS_HLSL hlsl -{ - source isosurf.hlsl - entry_point mainGS - target gs_4_0 - - default_params - { - param_named IsoValue float 1 - } -} - -////////// -// CG // -////////// -vertex_program Ogre/Isosurf/SampleFieldVS_CG cg -{ - source IsosurfVS.glsl - profiles vp40 arbvp1 - - default_params - { - param_named IsoValue float 1.0 - param_named_auto WorldViewProj worldviewproj_matrix - param_named_auto origWorldViewIT inverse_transpose_worldview_matrix - } -} - -geometry_program Ogre/Isosurf/TessellateTetrahedraGS_CG cg -{ - source isosurf.cg - entry_point mainGS - profiles gpu_gp gp4_gp - - default_params - { - param_named IsoValue float 1.0 - } -} - -fragment_program Ogre/Isosurf/MetaballPS_CG cg -{ - source IsosurfFS.glsl - profiles fp40 arbfp1 -} - -////////// -// GLSL // -////////// -vertex_program Ogre/Isosurf/SampleFieldVS_GLSL glsl hlsl -{ - source IsosurfVS.glsl - - default_params - { - param_named IsoValue float 1.0 - param_named_auto WorldViewProj worldviewproj_matrix - param_named_auto origWorldViewIT inverse_transpose_worldview_matrix - } -} - -geometry_program Ogre/Isosurf/TessellateTetrahedraGS_GLSL glsl -{ - source IsosurfGS.glsl - syntax glsl150 - - default_params - { - param_named IsoValue float 1.0 - } -} - -fragment_program Ogre/Isosurf/MetaballPS_GLSL glsl hlsl -{ - source IsosurfFS.glsl -} - -vertex_program Ogre/Isosurf/SampleFieldVS unified -{ - delegate Ogre/Isosurf/SampleFieldVS_CG - delegate Ogre/Isosurf/SampleFieldVS_GLSL -} - -geometry_program Ogre/Isosurf/TessellateTetrahedraGS unified -{ - delegate Ogre/Isosurf/TessellateTetrahedraGS_GLSL - delegate Ogre/Isosurf/TessellateTetrahedraGS_HLSL - delegate Ogre/Isosurf/TessellateTetrahedraGS_CG - default_params - { - - } -} - -fragment_program Ogre/Isosurf/MetaballPS unified -{ - delegate Ogre/Isosurf/MetaballPS_CG - delegate Ogre/Isosurf/MetaballPS_GLSL -} - -material Ogre/Isosurf/TessellateTetrahedra -{ - technique - { - pass - { - vertex_program_ref Ogre/Isosurf/SampleFieldVS - { - - } - - geometry_program_ref Ogre/Isosurf/TessellateTetrahedraGS - { - - } - - fragment_program_ref Ogre/Isosurf/MetaballPS - { - - } - } - } -} diff --git a/Samples/Media/materials/scripts/Laplace.material b/Samples/Media/materials/scripts/Laplace.material deleted file mode 100644 index d9a677e3c2a..00000000000 --- a/Samples/Media/materials/scripts/Laplace.material +++ /dev/null @@ -1,48 +0,0 @@ -fragment_program Ogre/Compositor/Laplace_Cg_FP hlsl -{ - source LaplaceFP.cg - entry_point Laplace_ps -} - -fragment_program Ogre/Compositor/Laplace_GLSL_FP glsl glsles -{ - source LaplaceFP.glsl -} - -fragment_program Ogre/Compositor/LaplaceFP unified -{ - delegate Ogre/Compositor/Laplace_GLSL_FP - delegate Ogre/Compositor/Laplace_Cg_FP -} - -material Ogre/Compositor/Laplace -{ - technique - { - - pass - { - cull_hardware none - depth_func always_pass - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_Tex2a_vp - { - } - - fragment_program_ref Ogre/Compositor/LaplaceFP - { - param_named pixelSize float 0.0031 - param_named scale float 1.0 - } - - texture_unit RT - { - tex_coord_set 0 - tex_address_mode clamp - filtering trilinear - } - - } - } -} diff --git a/Samples/Media/materials/scripts/LigthShafts.material b/Samples/Media/materials/scripts/LigthShafts.material deleted file mode 100644 index b4815538506..00000000000 --- a/Samples/Media/materials/scripts/LigthShafts.material +++ /dev/null @@ -1,78 +0,0 @@ -// --------------------------------------------------------------------------------------- -// Light shafts shaders with shadows and noise support -// Inpirated on the ATI paper https://developer.amd.com/wordpress/media/2012/10/Mitchell_LightShafts.pdf -// Ogre3D implementation by Xavier Verguín González (xavyiy [at] gmail [dot] com) -// --------------------------------------------------------------------------------------- - -// --------------------- Light shafts material ------------------------ - -vertex_program LightShafts_VP glsl glsles hlsl glslang -{ - source LightShafts.vert - - default_params - { - param_named_auto uWorldView worldview_matrix - param_named_auto uWorldViewProj worldviewproj_matrix - param_named_auto uTexWorldViewProj texture_worldviewproj_matrix 0 - } -} - -fragment_program LightShafts_FP glsl glsles hlsl glslang -{ - source LightShafts.frag - default_params - { - param_named uDepthMap int 0 - param_named uCookieMap int 1 - param_named uNoiseMap int 2 - } -} - -material LightShafts -{ - technique - { - pass - { - lighting off - - depth_write off - depth_check on - - scene_blend add - - vertex_program_ref LightShafts_VP - { - } - - fragment_program_ref LightShafts_FP - { - param_named_auto uAttenuation light_attenuation 0 - param_named_auto uLightPosition light_position_view_space 0 - param_named_auto Time time_0_1 44 - } - - // Depth map - texture_unit - { - tex_address_mode clamp - content_type shadow - } - - // Projector cookie - texture_unit - { - tex_address_mode clamp - texture Cookie0.png - } - - // Noise texture - texture_unit - { - tex_address_mode wrap - texture Noise.png - } - } - } -} \ No newline at end of file diff --git a/Samples/Media/materials/scripts/MRTtest.material b/Samples/Media/materials/scripts/MRTtest.material deleted file mode 100644 index a132b8c9b7c..00000000000 --- a/Samples/Media/materials/scripts/MRTtest.material +++ /dev/null @@ -1,134 +0,0 @@ -// Scene material -// MRT testing -fragment_program Ogre/MRTtest/scenefp/HLSL hlsl -{ - source mrttestfp.hlsl - entry_point mainfp_scene - target ps_2_0 -} - -fragment_program Ogre/MRTtest/scenefp/GLSL glsl -{ - source mrttestfp_scene.glsl -} - -fragment_program Ogre/MRTtest/scenefp/GLSLES glsles -{ - source mrttestfp_scene.glsles -} - -fragment_program Ogre/MRTtest/scenefp unified -{ - delegate Ogre/MRTtest/scenefp/HLSL - delegate Ogre/MRTtest/scenefp/GLSL - delegate Ogre/MRTtest/scenefp/GLSLES -} - -material Ogre/MRTtest/scene -{ - technique - { - scheme MRT - pass - { - polygon_mode_overrideable false - vertex_program_ref Ogre/BasicVertexPrograms/AmbientOneTextureUnified - { - param_named ambient float4 1 1 1 1 - } - fragment_program_ref Ogre/MRTtest/scenefp - { - } - - texture_unit - { - texture ogrelogo.png - } - - } - } -} - - -fragment_program Ogre/MRTtest/quadfp/HLSL hlsl -{ - source mrttestfp.hlsl - entry_point mainfp_quad - target ps_2_0 -} - -fragment_program Ogre/MRTtest/quadfp/GLSL glsl -{ - source mrttestfp_quad.glsl - - default_params - { - param_named rt0 int 0 - param_named rt1 int 1 - param_named rt2 int 2 - param_named rt3 int 3 - } -} - -fragment_program Ogre/MRTtest/quadfp/GLSLES glsles -{ - source mrttestfp_quad.glsles - - default_params - { - param_named rt0 int 0 - param_named rt1 int 1 - param_named rt2 int 2 - param_named rt3 int 3 - } -} - -fragment_program Ogre/MRTtest/quadfp unified -{ - delegate Ogre/MRTtest/quadfp/HLSL - delegate Ogre/MRTtest/quadfp/GLSL - delegate Ogre/MRTtest/quadfp/GLSLES -} - - -// Quad material -material Ogre/MRTtest/quad -{ - technique - { - - pass - { - cull_hardware none - depth_func always_pass - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_NoCG_vp - { - } - - fragment_program_ref Ogre/MRTtest/quadfp - { - } - - texture_unit RT0 - { - tex_address_mode clamp - } - texture_unit RT1 - { - tex_address_mode clamp - } - texture_unit RT2 - { - tex_address_mode clamp - } - texture_unit RT3 - { - tex_address_mode clamp - } - - - } - } -} diff --git a/Samples/Media/materials/scripts/MotionBlur.material b/Samples/Media/materials/scripts/MotionBlur.material deleted file mode 100644 index a172a6547db..00000000000 --- a/Samples/Media/materials/scripts/MotionBlur.material +++ /dev/null @@ -1,103 +0,0 @@ -fragment_program Ogre/Compositor/Combine_HLSL_fp hlsl -{ - source Combine_fp.cg - entry_point Combine_fp - - default_params - { - param_named blur float 0.8 - } -} - -fragment_program Ogre/Compositor/Combine_GLSL_fp glsl glsles -{ - source Combine_fp.glsl - default_params - { - param_named blur float 0.8 - param_named RT int 0 - param_named Sum int 1 - } -} - -fragment_program Ogre/Compositor/Combine_fp unified -{ - delegate Ogre/Compositor/Combine_GLSL_fp - delegate Ogre/Compositor/Combine_HLSL_fp -} - -material Ogre/Compositor/Combine -{ - technique - { - pass - { - depth_check off - polygon_mode_overrideable false - - fragment_program_ref Ogre/Compositor/Combine_fp - { - } - - vertex_program_ref Ogre/Compositor/StdQuad_Tex2a_vp - { - } - - texture_unit RT - { - tex_address_mode clamp - filtering linear linear none - tex_coord_set 0 - } - - texture_unit Sum - { - tex_address_mode clamp - filtering linear linear none - tex_coord_set 0 - } - } - } -} - -material Ogre/Compositor/Copyback -{ - technique - { - pass - { - lighting off - depth_check off - polygon_mode_overrideable false - - texture_unit Temp - { - tex_address_mode clamp - filtering linear linear none - colour_op replace - tex_coord_set 0 - } - } - } -} - -material Ogre/Compositor/MotionBlur -{ - technique - { - pass - { - lighting off - depth_check off - polygon_mode_overrideable false - - texture_unit Sum - { - tex_address_mode clamp - filtering linear linear none - colour_op replace - tex_coord_set 0 - } - } - } -} diff --git a/Samples/Media/materials/scripts/NightVision.material b/Samples/Media/materials/scripts/NightVision.material deleted file mode 100644 index 44280ff6a45..00000000000 --- a/Samples/Media/materials/scripts/NightVision.material +++ /dev/null @@ -1,84 +0,0 @@ -fragment_program Ogre/Compositor/NightVisionFPCg cg -{ - source NightVisionFP.cg - entry_point NightVision_ps - profiles ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 ps_2_0 arbfp1 - - default_params - { - param_named lum float4 0.30 0.59 0.11 0.0 - param_named_auto time time_0_1 1 - } -} - -fragment_program Ogre/Compositor/NightVisionFPGLSL glsl -{ - source NightVisionFP.glsl - syntax glsl150 - - default_params - { - param_named lum float4 0.30 0.59 0.11 0.0 - param_named_auto time time_0_1 1 - param_named RT int 0 - param_named noiseVol int 1 - } -} - -fragment_program Ogre/Compositor/NightVisionFPGLSLES glsles -{ - source NightVisionFP.glsles - syntax glsl300es - - default_params - { - param_named lum float4 0.30 0.59 0.11 0.0 - param_named_auto time time_0_1 1 - param_named RT int 0 - param_named noiseVol int 1 - } -} - -fragment_program Ogre/Compositor/NightVisionFP unified -{ - delegate Ogre/Compositor/NightVisionFPGLSL - delegate Ogre/Compositor/NightVisionFPGLSLES - delegate Ogre/Compositor/NightVisionFPCg -} - -material Ogre/Compositor/NightVision -{ - technique - { - - pass - { - cull_hardware none - depth_func always_pass - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_Tex2a_vp - { - } - - fragment_program_ref Ogre/Compositor/NightVisionFP - { - - } - - texture_unit RT - { - tex_coord_set 0 - tex_address_mode clamp - filtering trilinear - } - - texture_unit noise - { - texture Random3D.dds 3d - tex_address_mode wrap - tex_coord_set 1 - } - } - } -} diff --git a/Samples/Media/materials/scripts/Ocean.controls b/Samples/Media/materials/scripts/Ocean.controls deleted file mode 100644 index 52010123a39..00000000000 --- a/Samples/Media/materials/scripts/Ocean.controls +++ /dev/null @@ -1,46 +0,0 @@ -[Ocean2] -material = Ocean2_HLSL_GLSL -control = Wavelet Scale, BumpScale, GPU_VERTEX, 0, 2, 0 -control = Texture Scale X, textureScale, GPU_VERTEX, 0, 40, 0 -control = Texture Scale Y, textureScale, GPU_VERTEX, 0, 40, 1 -control = Wavelet Speed X, bumpSpeed, GPU_VERTEX, -0.1, 0.1, 0 -control = Wavelet Speed Y, bumpSpeed, GPU_VERTEX, -0.1, 0.1, 1 -control = Wave Frequency, waveFreq, GPU_VERTEX, 0, 0.05, 0 -control = Wave Amplitude, waveAmp, GPU_VERTEX, 0, 25, 0 - -control = Deep Color [Red], deepColor, GPU_FRAGMENT, 0, 1, 0 -control = Deep Color [Green], deepColor, GPU_FRAGMENT, 0, 1, 1 -control = Deep Color [Blue], deepColor, GPU_FRAGMENT, 0, 1, 2 - -control = Shallow Color [Red], shallowColor, GPU_FRAGMENT, 0, 1, 0 -control = Shallow Color [Green], shallowColor, GPU_FRAGMENT, 0, 1, 1 -control = Shallow Color [Blue], shallowColor, GPU_FRAGMENT, 0, 1, 2 - -control = Reflection Color [Red], reflectionColor, GPU_FRAGMENT, 0, 1, 0 -control = Reflection Color [Green], reflectionColor, GPU_FRAGMENT, 0, 1, 1 -control = Reflection Color [Blue], reflectionColor, GPU_FRAGMENT, 0, 1, 2 - -control = Reflection Amount, reflectionAmount, GPU_FRAGMENT, 0, 1, 0 -control = Reflection Blur, reflectionBlur, GPU_FRAGMENT, 0, 8, 0 -control = Water Amount, waterAmount, GPU_FRAGMENT, 0, 1, 0 -control = Fresnel Power, fresnelPower, GPU_FRAGMENT, 0, 10, 0 -control = Fresnel Bias, fresnelBias, GPU_FRAGMENT, 0, 1, 0 -control = HDR Mulitplier, hdrMultiplier, GPU_FRAGMENT, 0, 2, 0 - -[Ocean1] -material = OceanHLSL_GLSL -control = scale x, scale, GPU_VERTEX, 0, 0.1, 0 -control = scale y, scale, GPU_VERTEX, 0, 0.1, 1 -control = scale z, scale, GPU_VERTEX, 0, 0.1, 2 -control = Wave Speed X, waveSpeed, GPU_VERTEX, 0, 1, 0 -control = Wave Speed Y, waveSpeed, GPU_VERTEX, 0, 1, 1 -control = Noise Speed, noiseSpeed, GPU_VERTEX, 0, 1, 0 - -control = Fade Bias, fadeBias, GPU_FRAGMENT, 0, 1, 0 -control = Fade Exponent, fadeExp, GPU_FRAGMENT, 0, 20, 0 -control = Water Color (r), waterColor, GPU_FRAGMENT, 0, 1, 0 -control = Water Color (g), waterColor, GPU_FRAGMENT, 0, 1, 1 -control = Water Color (b), waterColor, GPU_FRAGMENT, 0, 1, 2 - - - diff --git a/Samples/Media/materials/scripts/Ocean.material b/Samples/Media/materials/scripts/Ocean.material deleted file mode 100644 index 883a0335235..00000000000 --- a/Samples/Media/materials/scripts/Ocean.material +++ /dev/null @@ -1,225 +0,0 @@ -vertex_program HLSL4/OceanVS hlsl -{ - source oceanHLSL_Cg.vert - - default_params - { - param_named_auto worldViewProj_matrix worldviewproj_matrix - param_named_auto eyePosition camera_position_object_space - param_named scale float3 0.012 0.005 0.03 - param_named_auto time_0_X time_0_x 100.0 - } -} - -fragment_program HLSL4/OceanFS hlsl -{ - source oceanHLSL_Cg.frag -} - -vertex_program GLSL/OceanVS glsl -{ - source oceanGLSL.vert - - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - param_named_auto eyePosition camera_position_object_space - param_named scale float3 0.012 0.005 0.03 - param_named_auto time_0_X time_0_x 100.0 - } -} - -fragment_program GLSL/OceanFS glsl -{ - source oceanGLSL.frag - - default_params - { - param_named Noise int 0 - param_named skyBox int 1 - } -} - -vertex_program Ogre/OceanVS unified -{ - delegate HLSL4/OceanVS - delegate GLSL/OceanVS -} - -fragment_program Ogre/OceanFS unified -{ - delegate HLSL4/OceanFS - delegate GLSL/OceanFS -} - - -material OceanHLSL_GLSL -{ - technique - { - pass - { - vertex_program_ref Ogre/OceanVS - { - param_named waveSpeed float2 0.0 0.168 - param_named noiseSpeed float 0.155 - } - - fragment_program_ref Ogre/OceanFS - { - param_named fadeBias float 0.336 - param_named fadeExp float 5.546 - param_named waterColor float4 0.0 0.244 0.395 1.0 - } - - texture_unit - { - texture NoiseVolume.dds 3d - tex_coord_set 0 - filtering linear linear none - } - - texture_unit - { - texture morning.jpg cubic - tex_address_mode clamp - tex_coord_set 1 - } - - } - - } -} - -vertex_program HLSL4/Ocean2VS hlsl -{ - source Ocean2HLSL_Cg.vert - - default_params - { - param_named_auto WorldViewProj worldviewproj_matrix - } -} - -fragment_program HLSL4/Ocean2FS hlsl -{ - source Ocean2HLSL_Cg.frag -} - -vertex_program GLSL/Ocean2VS glsl glsles -{ - source Ocean2GLSL.vert - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -fragment_program GLSL/Ocean2FS glsl glsles -{ - source Ocean2GLSL.frag - default_params - { - param_named NormalMap int 0 - param_named EnvironmentMap int 1 - } -} - -vertex_program Ogre/Ocean2VS unified -{ - delegate HLSL4/Ocean2VS - delegate GLSL/Ocean2VS -} - -fragment_program Ogre/Ocean2FS unified -{ - delegate HLSL4/Ocean2FS - delegate GLSL/Ocean2FS -} - -material Ocean2_HLSL_GLSL -{ - technique - { - pass - { - vertex_program_ref Ogre/Ocean2VS - { - param_named_auto eyePosition camera_position_object_space - param_named BumpScale float 0.2 - param_named textureScale float2 25 26 - param_named bumpSpeed float2 0.015 0.005 - param_named_auto time time_0_x 100.0 - param_named waveFreq float 0.028 - param_named waveAmp float 1.8 - } - - fragment_program_ref Ogre/Ocean2FS - { - param_named deepColor float4 0 0.3 0.5 1.0 - param_named shallowColor float4 0 1 1 1.0 - param_named reflectionColor float4 0.95 1 1 1.0 - param_named reflectionAmount float 1.0 - param_named reflectionBlur float 0.0 - param_named waterAmount float 0.3 - param_named fresnelPower float 5.0 - param_named fresnelBias float 0.328 - param_named hdrMultiplier float 0.471 - } - - texture_unit - { - texture waves2.dds - tex_coord_set 0 - filtering linear linear linear - } - - texture_unit - { - texture morning.jpg cubic - tex_address_mode clamp - filtering linear linear linear - tex_coord_set 1 - } - - } - - } -} - -material SkyBox -{ - technique - { - pass - { - lighting off - depth_write off - depth_check off - - texture_unit - { - texture morning.jpg cubic - tex_address_mode clamp - } - } - } -} - -material LightFlare -{ - technique - { - pass - { - lighting off - scene_blend add - depth_write off - - texture_unit - { - texture flare.png - } - } - } -} \ No newline at end of file diff --git a/Samples/Media/materials/scripts/OffsetMapping.material b/Samples/Media/materials/scripts/OffsetMapping.material deleted file mode 100644 index 6cff0e7d529..00000000000 --- a/Samples/Media/materials/scripts/OffsetMapping.material +++ /dev/null @@ -1,88 +0,0 @@ -// Bump map with Parallax offset -material RTSS/OffsetMapping -{ - technique - { - pass - { - specular 1 1 1 32 - - // Base diffuse texture map - texture_unit - { - texture Bricks076C_diffspec.dds - } - - texture_unit - { - texture Bricks076C_normheight.dds - rtshader_system - { - normal_map parallax - } - } - } - } -} - -material Examples/OffsetMapping/Specular -{ - technique - { - // ambient / depth - pass - { - illumination_stage ambient - diffuse 0 0 0 - } - // do the lighting and bump mapping with parallax pass - pass - { - illumination_stage per_light - iteration once_per_light point - scene_blend add - specular 0.5 0.5 0.5 32 - - // Base diffuse texture map - texture_unit - { - texture rockwall.tga - } - rtshader_system - { - lighting_stage normal_map rockwall_NH.tga parallax - } - } - } -} - -material Examples/OffsetMapping/IntegratedShadows -{ - - technique - { - // do the lighting and bump mapping with parallax pass - pass - { - rtshader_system - { - shadow_mapping light_count 2 - } - // Normal + height(alpha) map - texture_unit - { - texture rockwall_NH.tga - rtshader_system - { - normal_map parallax - } - } - - // Base diffuse texture map - texture_unit - { - texture rockwall.tga - } - } - } -} diff --git a/Samples/Media/materials/scripts/Ogre.material b/Samples/Media/materials/scripts/Ogre.material deleted file mode 100644 index 58591e0b491..00000000000 --- a/Samples/Media/materials/scripts/Ogre.material +++ /dev/null @@ -1,66 +0,0 @@ -material Ogre/Earring -{ - technique - { - pass - { - ambient 0.7 0.7 0 - diffuse 0.7 0.7 0 - - texture_unit - { - texture spheremap.png - colour_op_ex add src_texture src_current - colour_op_multipass_fallback one one - env_map spherical - } - } - } -} - -material Ogre/Skin -{ - technique - { - pass - { - ambient 0.3 0.8 0.3 - - texture_unit - { - texture GreenSkin.jpg - tex_address_mode mirror - } - } - } -} - -material Ogre/Tusks -{ - technique - { - pass - { - ambient 0.7 0.7 0.6 - - texture_unit - { - texture tusk.jpg - scale 0.2 0.2 - } - } - } -} - -material Ogre/Eyes -{ - technique - { - pass - { - ambient 1 0.4 0.4 - diffuse 1 0.7 0 - emissive 0.3 0.1 0 - } - } -} diff --git a/Samples/Media/materials/scripts/OldMovie.material b/Samples/Media/materials/scripts/OldMovie.material deleted file mode 100644 index 8b0caf98e71..00000000000 --- a/Samples/Media/materials/scripts/OldMovie.material +++ /dev/null @@ -1,84 +0,0 @@ -fragment_program Ogre/Compositor/OldMovie_HLSL_FP hlsl -{ - source OldMovieFP.cg - entry_point OldMovie_ps -} - -fragment_program Ogre/Compositor/OldMovie_GLSL_FP glsl glsles -{ - source OldMovieFP.glsl - default_params - { - param_named RT int 0 - param_named SplotchesTx int 1 - param_named Texture2 int 2 - param_named SepiaTx int 3 - } -} - -fragment_program Ogre/Compositor/OldMovieFP unified -{ - delegate Ogre/Compositor/OldMovie_GLSL_FP - delegate Ogre/Compositor/OldMovie_HLSL_FP -} - -material Ogre/Compositor/OldMovie -{ - technique - { - - pass - { - cull_hardware none - depth_func always_pass - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_Tex2a_vp - { - } - - fragment_program_ref Ogre/Compositor/OldMovieFP - { - param_named_auto time_cycle_period time 20 - param_named flicker float 0.4 - param_named DirtFrequency float 0.0005 - param_named luminance float3 0.30 0.59 0.11 - param_named frameJitter float 0.004 - param_named lumiShift float 0.03 - } - - texture_unit RT - { - tex_coord_set 0 - tex_address_mode clamp - filtering trilinear - } - - texture_unit SplotchesTx - { - texture 8x8PagesSplotches2.png - tex_coord_set 1 - tex_address_mode wrap - filtering trilinear - } - - texture_unit - { - texture 1D_Noise.png - tex_coord_set 2 - tex_address_mode wrap - filtering point point none - } - - - texture_unit SepiaTx - { - texture Sepia1D.tga - tex_coord_set 3 - tex_address_mode mirror - filtering point point none - } - - } - } -} diff --git a/Samples/Media/materials/scripts/OldTV.material b/Samples/Media/materials/scripts/OldTV.material deleted file mode 100644 index 5d50abfca42..00000000000 --- a/Samples/Media/materials/scripts/OldTV.material +++ /dev/null @@ -1,98 +0,0 @@ -fragment_program Ogre/Compositor/OldTV_FPCg cg -{ - source OldTV.cg - entry_point OldTV_ps - profiles ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 ps_2_0 arbfp1 -} - -fragment_program Ogre/Compositor/OldTV_FPGLSL glsl -{ - source OldTV.glsl - syntax glsl150 - default_params - { - param_named Image int 0 - param_named Rand int 1 - param_named Noise int 2 - } -} - -fragment_program Ogre/Compositor/OldTV_FPGLSLES glsles -{ - source OldTV.glsles - syntax glsl300es - default_params - { - param_named Image int 0 - param_named Rand int 1 - param_named Noise int 2 - } -} - -fragment_program Ogre/Compositor/OldTV_FPHLSL hlsl -{ - source OldTV.hlsl - entry_point OldTV_ps - target ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 -} - -fragment_program Ogre/Compositor/OldTV_FP unified -{ - delegate Ogre/Compositor/OldTV_FPGLSL - delegate Ogre/Compositor/OldTV_FPGLSLES - delegate Ogre/Compositor/OldTV_FPHLSL - delegate Ogre/Compositor/OldTV_FPCg -} - -material Ogre/Compositor/OldTV -{ - technique - { - - pass - { - depth_check off - polygon_mode_overrideable false - vertex_program_ref Ogre/Compositor/StdQuad_Tex2a_vp - { - } - - fragment_program_ref Ogre/Compositor/OldTV_FP - { - param_named distortionFreq float 2.7 - param_named distortionScale float 2.5 - param_named distortionRoll float 0.93 - param_named interference float 0.5 - param_named frameLimit float 0.40 - param_named frameShape float 0.26 - param_named frameSharpness float 6.0 - - param_named_auto time_0_X time_0_x 120 - param_named_auto sin_time_0_X sintime_0_x 120 - } - - texture_unit 0 - { - tex_coord_set 0 - tex_address_mode clamp - filtering linear linear linear - } - - texture_unit 1 - { - texture Random3D.dds 3d - tex_coord_set 1 - tex_address_mode wrap - filtering linear linear linear - } - - texture_unit 2 - { - texture NoiseVolume.dds 3d - tex_coord_set 2 - tex_address_mode wrap - filtering linear linear linear - } - } - } -} diff --git a/Samples/Media/materials/scripts/ParticleGS.material b/Samples/Media/materials/scripts/ParticleGS.material deleted file mode 100644 index 0b7bfd98cfe..00000000000 --- a/Samples/Media/materials/scripts/ParticleGS.material +++ /dev/null @@ -1,241 +0,0 @@ -vertex_program Ogre/ParticleGS/GenerateVScg cg -{ - source ParticleGS.cg - entry_point GenerateParticles_VS - profiles arbvp1 -} - -geometry_program Ogre/ParticleGS/GenerateGScg cg -{ - source ParticleGS.cg - entry_point GenerateParticles_GS - profiles gp4gp gpu_gp -} - -vertex_program Ogre/ParticleGS/DisplayVScg cg -{ - source ParticleGS.cg - entry_point DisplayParticles_VS - profiles arbvp1 -} - -geometry_program Ogre/ParticleGS/DisplayGScg cg -{ - source ParticleGS.cg - entry_point DisplayParticles_GS - profiles gp4gp gpu_gp -} - -fragment_program Ogre/ParticleGS/DisplayPScg cg -{ - source ParticleGS.cg - entry_point DisplayParticles_PS - profiles arbfp1 -} - -vertex_program Ogre/ParticleGS/GenerateVShlsl4 hlsl -{ - source ParticleGS.hlsl - entry_point GenerateParticles_VS - enable_backwards_compatibility no - target vs_4_0 vs_4_0_level_9_1 vs_4_0_level_9_3 -} - -geometry_program Ogre/ParticleGS/GenerateGShlsl4 hlsl -{ - source ParticleGS.hlsl - entry_point GenerateParticles_GS - enable_backwards_compatibility no - target gs_4_0 -} - -vertex_program Ogre/ParticleGS/DisplayVShlsl4 hlsl -{ - source ParticleGS.hlsl - entry_point DisplayParticles_VS - enable_backwards_compatibility no - target vs_4_0 vs_4_0_level_9_1 vs_4_0_level_9_3 -} - -geometry_program Ogre/ParticleGS/DisplayGShlsl4 hlsl -{ - source ParticleGS.hlsl - entry_point DisplayParticles_GS - enable_backwards_compatibility no - target gs_4_0 -} - -fragment_program Ogre/ParticleGS/DisplayPShlsl4 hlsl -{ - source ParticleGS.hlsl - entry_point DisplayParticles_PS - enable_backwards_compatibility no - target ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 -} - -vertex_program Ogre/ParticleGS/GenerateVSglsl glsl -{ - source ParticleGS_GenerateVS.glsl - syntax glsl150 -} - -geometry_program Ogre/ParticleGS/GenerateGSglsl glsl -{ - source ParticleGS_GenerateGS.glsl - syntax glsl150 -} - -vertex_program Ogre/ParticleGS/DisplayVSglsl glsl -{ - source ParticleGS_DisplayVS.glsl - syntax glsl150 -} - -geometry_program Ogre/ParticleGS/DisplayGSglsl glsl -{ - source ParticleGS_DisplayGS.glsl - syntax glsl150 -} - -fragment_program Ogre/ParticleGS/DisplayPSglsl glsl -{ - source ParticleGS_DisplayFS.glsl - syntax glsl150 -} - -vertex_program Ogre/ParticleGS/GenerateVS unified -{ - delegate Ogre/ParticleGS/GenerateVSglsl - delegate Ogre/ParticleGS/GenerateVShlsl4 - delegate Ogre/ParticleGS/GenerateVScg -} - -geometry_program Ogre/ParticleGS/GenerateGS unified -{ - delegate Ogre/ParticleGS/GenerateGSglsl - delegate Ogre/ParticleGS/GenerateGShlsl4 - delegate Ogre/ParticleGS/GenerateGScg -} - -// Generate the particle system geometry. -material Ogre/ParticleGS/Generate -{ - technique - { - pass - { - vertex_program_ref Ogre/ParticleGS/GenerateVS - { - - } - - geometry_program_ref Ogre/ParticleGS/GenerateGS - { - param_named gravity float3 0 -9.8 0 - param_named_auto globalTime time - param_named_auto elapsedTime frame_time - param_named secondsPerFirework float 0.3 - } - - // This texture unit will be filled at runtime. - texture_unit RandomTexture - { - tex_address_mode wrap - filtering none - } - } - } -} - -// Display the generated particle system geometry. -material Ogre/ParticleGS/Display -{ - technique cg - { - pass - { - depth_write off - - vertex_program_ref Ogre/ParticleGS/DisplayVScg - { - param_named_auto proj projection_matrix - param_named_auto worldView worldview_matrix - } - - geometry_program_ref Ogre/ParticleGS/DisplayGScg - { - } - - fragment_program_ref Ogre/ParticleGS/DisplayPScg - { - - } - - texture_unit - { - tex_coord_set 0 - texture particle.dds - } - - scene_blend alpha_blend - } - } - technique hlsl4 - { - pass - { - depth_write off - - vertex_program_ref Ogre/ParticleGS/DisplayVShlsl4 - { - param_named_auto proj projection_matrix - param_named_auto worldView worldview_matrix - } - - geometry_program_ref Ogre/ParticleGS/DisplayGShlsl4 - { - } - - fragment_program_ref Ogre/ParticleGS/DisplayPShlsl4 - { - - } - - texture_unit - { - tex_coord_set 0 - texture particle.dds - } - - scene_blend alpha_blend - } - } - technique glsl - { - pass - { - depth_write off - - vertex_program_ref Ogre/ParticleGS/DisplayVSglsl - { - param_named_auto worldView worldview_matrix - param_named_auto proj projection_matrix - param_named_auto height viewport_height - } - - fragment_program_ref Ogre/ParticleGS/DisplayPSglsl - { - - } - - texture_unit - { - tex_coord_set 0 - texture particle.dds - } - - scene_blend alpha_blend - } - } -} - diff --git a/Samples/Media/materials/scripts/Penguin.material b/Samples/Media/materials/scripts/Penguin.material deleted file mode 100644 index 0cf6af33979..00000000000 --- a/Samples/Media/materials/scripts/Penguin.material +++ /dev/null @@ -1,13 +0,0 @@ -material Penguin -{ - technique - { - pass - { - texture_unit - { - texture penguin.jpg - } - } - } -} diff --git a/Samples/Media/materials/scripts/Posterize.material b/Samples/Media/materials/scripts/Posterize.material deleted file mode 100644 index b59603d7a55..00000000000 --- a/Samples/Media/materials/scripts/Posterize.material +++ /dev/null @@ -1,45 +0,0 @@ -fragment_program Ogre/Compositor/Posterize_Cg_FP hlsl -{ - source PosterizeFP.cg - entry_point Posterize_ps -} - -fragment_program Ogre/Compositor/Posterize_GLSL_FP glsl glsles -{ - source PosterizeFP.glsl -} - -fragment_program Ogre/Compositor/PosterizeFP unified -{ - delegate Ogre/Compositor/Posterize_GLSL_FP - delegate Ogre/Compositor/Posterize_Cg_FP -} - -material Ogre/Compositor/Posterize -{ - technique - { - pass - { - cull_hardware none - depth_func always_pass - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_Tex2a_vp - { - } - - fragment_program_ref Ogre/Compositor/PosterizeFP - { - } - - texture_unit RT - { - tex_coord_set 0 - tex_address_mode clamp - filtering trilinear - } - - } - } -} diff --git a/Samples/Media/materials/scripts/RTShaderSystem.material b/Samples/Media/materials/scripts/RTShaderSystem.material deleted file mode 100644 index 857b68b27e6..00000000000 --- a/Samples/Media/materials/scripts/RTShaderSystem.material +++ /dev/null @@ -1,263 +0,0 @@ - -// RTShader System materials. - -// This is a single pass per pixel lighting based material. -// All scene lights will be applied within a single rendering pass. -// It saves geometry overdraw but it consumes more instructions during vertex and pixel shaders. -// Use this method when your scene uses small amount of lights. (1-3). -material RTSS/PerPixel_SinglePass -{ - technique - { - pass - { - // Turn off specular in order to use only diffuse based bump map technique. - specular 1.0 1.0 1.0 32 - - texture_unit - { - texture Panels_Diffuse.png - } - - //![rtss_per_pixel] - // RT Shader system section. - rtshader_system - { - // Override lighting stage with per pixel lighting. - lighting_stage per_pixel - } - //![rtss_per_pixel] - } - } -} - -sampler RTSS/NormalMapSampler -{ - filtering bilinear - max_anisotropy 1 - mipmap_bias -1.0 -} - -// This is a single pass normal map lighting based material. -// All scene lights will be applied within a single rendering pass. -// Supports all kind of lights - directional, point and spot. -// It saves geometry overdraw but it consumes more instructions during vertex and pixel shaders. -// Use this method when your scene uses small amount of lights. (1-3). -material RTSS/NormalMapping_SinglePass -{ - technique - { - pass - { - // Comment the specular in order to use only diffuse based normal map technique. - specular 1.0 1.0 1.0 32 - - texture_unit - { - texture Bricks076C_diffspec.dds - } - - texture_unit - { - texture Bricks076C_normheight.dds - sampler_ref RTSS/NormalMapSampler - // RT Shader system section. - rtshader_system - { - normal_map tangent_space - } - } - } - } -} - -// This is a multi pass normal map lighting based material. -// It acts as any other multi light material. -// This material defined to use only one type of light per lighting pass because the RTSS need to -// know what code to produce for the iterative lighting pass, otherwise it will throw an exception. -// It support any number of lights drawing but it uses more geometry drawing. -// Use this method when your scene uses large amount of lights. (3-8). -material RTSS/NormalMapping_MultiPass -{ - technique - { - // Base ambient pass - pass ambient - { - // base colours, not needed for rendering, but as information - // to lighting pass categorisation routine - diffuse 0 0 0 - - // RT Shader system section. - rtshader_system - { - // Override dynamic light count with zero light count. - // Doing this will cause the RTSS to create - // ambient lighting shaders. - // If not doing that the RTSS it will use the current scene light count - // which will result in full lighting calculation in this pass. - light_count 0 - } - } - - // Lighting pass. - pass lighting - { - // Comment the specular in order to use only diffuse based normal map technique. - specular 1.0 1.0 1.0 32 - - // base colours, not needed for rendering, but as information - // to lighting pass categorisation routine - ambient 0 0 0 - - // do this for each point light - // You MUST specify the light type when working with the RT Shader System in iterative lighting method. - // otherwise an exception will be thrown. - iteration once_per_light point - - scene_blend add - - texture_unit - { - texture Bricks076C_normheight.dds - sampler_ref RTSS/NormalMapSampler - // RT Shader system section. - rtshader_system - { - normal_map tangent_space - } - } - } - - // Decal pass - pass decal - { - - lighting off - - scene_blend dest_colour zero - texture_unit decalmap - { - texture Bricks076C_diffspec.dds - } - } - } -} - -// Athene single multi pass material override. -material RTSS/Athene/NormalMapping_SinglePass : RTSS/NormalMapping_SinglePass -{ - technique - { - pass - { - // Override the diffuse map. - texture_unit - { - texture egyptrockyfull.jpg - } - - texture_unit - { - texture atheneNormalMap.png - sampler_ref RTSS/NormalMapSampler - // RT Shader system section. - rtshader_system - { - normal_map tangent_space - } - } - } - } -} - -// Athene model multi pass material override. -material RTSS/Athene/NormalMapping_MultiPass : RTSS/NormalMapping_MultiPass -{ - technique - { - pass lighting - { - texture_unit - { - texture atheneNormalMap.png - sampler_ref RTSS/NormalMapSampler - // RT Shader system section. - rtshader_system - { - normal_map tangent_space - } - } - } - - // Decal pass - pass decal - { - // Override the decal map. - texture_unit decalmap - { - texture egyptrockyfull.jpg - } - } - } -} - -// This material derive from the multi pass normal map material. -// The only difference is that it process 2 point lights at each lighting pass. -material RTSS/NormalMapping_MultiPass_2lights : RTSS/NormalMapping_MultiPass -{ - technique - { - pass lighting - { - // Override light iteration definition. - iteration 1 per_n_lights 2 point - } - } -} - -// This material demonstrates the texture blending extension. -material RTSS/LayeredBlending -{ - technique - { - pass - { - lighting off - texture_unit - { - scale 0.1 0.1 - texture rockwall.tga - } - - texture_unit - { - // RT Shader system section - required by the layered blend extension. - rtshader_system - { - layered_blend luminosity - source_modifier src1_inverse_modulate custom 2 - } - texture ogrelogo.png - } - } - } -} - -material Ogre/RTShader/TriplanarTexturing -{ - technique - { - pass - { - ambient 0.5 0.5 0.5 - diffuse 1.0 1.0 1.0 - rtshader_system - { - // Texturescale, Plateau-size (0 to 0.57, not bigger to avoid division by zero!), transition-speed - // Texture from x, from y, from z - triplanarTexturing 0.05 0.2 4.0 BumpyMetal.jpg egyptrockyfull.jpg MtlPlat2.jpg - } - } - } -} diff --git a/Samples/Media/materials/scripts/RZR-002.material b/Samples/Media/materials/scripts/RZR-002.material deleted file mode 100644 index 4b2dcc10d27..00000000000 --- a/Samples/Media/materials/scripts/RZR-002.material +++ /dev/null @@ -1,15 +0,0 @@ - -material RZR-002 -{ - technique - { - pass - { - - texture_unit - { - texture RZR-002.png - } - } - } -} \ No newline at end of file diff --git a/Samples/Media/materials/scripts/RadialBlur.material b/Samples/Media/materials/scripts/RadialBlur.material deleted file mode 100644 index 010bf868169..00000000000 --- a/Samples/Media/materials/scripts/RadialBlur.material +++ /dev/null @@ -1,47 +0,0 @@ -//Cg Pixel Shader ps_2_0 -fragment_program Radial_Blur_Cg_ps hlsl -{ - source Radial_Blur_FP.cg -} - -fragment_program Radial_Blur_GLSL_ps glsl glsles -{ - source Radial_Blur_FP.glsl -} - -fragment_program Radial_Blur_ps unified -{ - delegate Radial_Blur_GLSL_ps - delegate Radial_Blur_Cg_ps -} - -//Effect: Radial Blur -material Ogre/Compositor/Radial_Blur -{ - technique - { - pass - { - //State: D3DRS_CULLMODE, Value : D3DCULL_NONE - cull_hardware none - depth_check off - polygon_mode_overrideable false - - fragment_program_ref Radial_Blur_ps - { - param_named sampleDist float 1.0 - param_named sampleStrength float 2.2 - } - vertex_program_ref Ogre/Compositor/StdQuad_Tex2a_vp - { - } - - texture_unit - { - tex_coord_set 0 - tex_address_mode clamp - filtering trilinear - } - } - } -} diff --git a/Samples/Media/materials/scripts/RasterizationOrder.material b/Samples/Media/materials/scripts/RasterizationOrder.material deleted file mode 100644 index 09804bf183e..00000000000 --- a/Samples/Media/materials/scripts/RasterizationOrder.material +++ /dev/null @@ -1,28 +0,0 @@ -shared_params CounterBuffer -{ - shared_param_named ac uint 0 -} - -fragment_program Ogre/RasterizationOrderFp glsl -{ - source RasterizationOrderFp.glsl - syntax glsl400 - - default_params - { - shared_params_ref CounterBuffer - } -} - -material Example/RasterizationOrder -{ - technique - { - pass - { - vertex_program_ref Ogre/BasicVertexPrograms/AmbientOneTextureUnified {} - fragment_program_ref Ogre/RasterizationOrderFp {} - } - } -} - diff --git a/Samples/Media/materials/scripts/SSAO/BoxFilterFP.glsl b/Samples/Media/materials/scripts/SSAO/BoxFilterFP.glsl deleted file mode 100644 index 4735cdead4b..00000000000 --- a/Samples/Media/materials/scripts/SSAO/BoxFilterFP.glsl +++ /dev/null @@ -1,27 +0,0 @@ -// a very simple 4x4 box filter -// the kernel has the following form -// o o o o -// o o o o -// o o x o -// o o o o -// where x marks the fragment position and the o marks a sampling point -#version 120 - -varying vec2 oUv0; - -uniform sampler2D sOcclusion; -uniform vec4 screenSize; -uniform float farClipDistance; - -void main() -{ - float color = 0; - for (int x = -2; x < 2; x++) - for (int y = -2; y < 2; y++) - { - color += texture2D(sOcclusion, vec2(oUv0.x + x * screenSize.z, oUv0.y + y * screenSize.w)).x; - } - color /= 16; - - gl_FragColor = vec4(color, color, color, 1); -} \ No newline at end of file diff --git a/Samples/Media/materials/scripts/SSAO/CreaseShading.cg b/Samples/Media/materials/scripts/SSAO/CreaseShading.cg deleted file mode 100644 index bc869706ecf..00000000000 --- a/Samples/Media/materials/scripts/SSAO/CreaseShading.cg +++ /dev/null @@ -1,69 +0,0 @@ -// original sources found at Game Developer Magazine March 2008 - -#include "HLSL_SM4Support.hlsl" - -SAMPLER2D(sNormal, 0); // xyz normal + depth [0, 1] -SAMPLER2D(sPosition, 1); // view space position -SAMPLER2D(sRandom, 1); // random texture sampler - -void CreaseShading_fp -( - in float4 position : POSITION, - in float2 uv : TEXCOORD0, - - out float4 oColor0 : COLOR0, - - uniform const float cRange, // the three(four) artistic parameters - uniform const float cBias, - uniform const float cAverager, - uniform const float cMinimumCrease, - uniform const float cKernelSize, // Bias for the kernel size, Hack for the fixed size 11x11 stipple kernel - uniform const float4 cViewportSize // (width, height, 1/width, 1/height) -) -{ - // get the view space position and normal of the fragment - const float3 fragmentPosition = tex2D(sPosition, uv).xyz; - const float3 fragmentNormal = tex2D(sNormal, uv).xyz; - - float totalGI = 0.0f; - - // a diamond shaped (45deg rotated square) stipple pattern around (0, 0) this will be used as offset for the samples - // O - // O O - // O O O - // O O O O - // O O X O O - // O O O O - // O O O - // O O - // O - // the algorith starts with the leftmost element and walks the diagonal to the topmost element - // a stippleSize of n yields (((n - 1) / 2)^2) - 1 samples - // the 'image' above has a stipple size of 11 'cuz it has 5 samples (minus - // the current fragment position and 4 gaps = 11. - - const int stippleSize = 11; // must be odd - for (int i = 0; i < (stippleSize + 1) / 2; i++) - { - float2 diagonalStart = float2(-(stippleSize - 1) / 2, 0) + i; - for(int j = 0; j < (stippleSize + 1) / 2; j++) - { - float2 sampleOffset = diagonalStart + float2(j, -j); - - float2 sampleUV = uv + (sampleOffset * cViewportSize.zw * cKernelSize); - float3 samplePos = tex2D(sPosition, sampleUV).xyz; - - float3 toCenter = samplePos - fragmentPosition; - float distance = length(toCenter); - - toCenter = normalize(toCenter); - float centerContrib = saturate((dot(toCenter, fragmentNormal) - cMinimumCrease) * cBias); - float rangeAttenuation = 1.0f - saturate(distance / cRange); - - totalGI += centerContrib * rangeAttenuation; - } - } - - totalGI /= cAverager; - oColor0 = 1 - float4(totalGI.xxx, 1); -} diff --git a/Samples/Media/materials/scripts/SSAO/CreaseShading.material b/Samples/Media/materials/scripts/SSAO/CreaseShading.material deleted file mode 100644 index e36a5eb2e3b..00000000000 --- a/Samples/Media/materials/scripts/SSAO/CreaseShading.material +++ /dev/null @@ -1,69 +0,0 @@ -fragment_program SSAO/CreaseShading_fp_hlsl hlsl -{ - source CreaseShading.cg - entry_point CreaseShading_fp - target ps_2_a -} - -fragment_program SSAO/CreaseShading_fp_cg cg -{ - source CreaseShading.cg - entry_point CreaseShading_fp - profiles ps_2_x arbfp1 -} - -fragment_program SSAO/CreaseShading_fp_glsl glsl -{ - source CreaseShadingFP.glsl - - default_params - { - param_named sNormal int 0 - param_named sPosition int 1 - } -} - -fragment_program SSAO/CreaseShading_fp unified -{ - delegate SSAO/CreaseShading_fp_glsl - delegate SSAO/CreaseShading_fp_hlsl - delegate SSAO/CreaseShading_fp_cg -} - -material SSAO/CreaseShading -{ - technique - { - pass - { - depth_check off - - vertex_program_ref Ogre/Compositor/StdQuad_vp {} - fragment_program_ref SSAO/CreaseShading_fp - { - param_named_auto cViewportSize viewport_size - } - - texture_unit // normals - { - content_type compositor SSAO/GBuffer mrt 0 - tex_address_mode clamp - filtering none - } - - texture_unit // view space position - { - content_type compositor SSAO/GBuffer mrt 1 - tex_address_mode clamp - filtering none - } - - texture_unit // random texture will be replace by 11x11 stipple - { - texture rand1x32.png - tex_address_mode clamp - filtering none - } - } - } -} diff --git a/Samples/Media/materials/scripts/SSAO/CreaseShadingFP.glsl b/Samples/Media/materials/scripts/SSAO/CreaseShadingFP.glsl deleted file mode 100644 index 1ec5d43f724..00000000000 --- a/Samples/Media/materials/scripts/SSAO/CreaseShadingFP.glsl +++ /dev/null @@ -1,46 +0,0 @@ -#version 120 -varying vec2 oUv0; - -uniform sampler2D sNormal; -uniform sampler2D sPosition; - -uniform float cRange; // the three(four) artistic parameters -uniform float cBias; -uniform float cAverager; -uniform float cMinimumCrease; -uniform float cKernelSize; // Bias for the kernel size, Hack for the fixed size 11x11 stipple kernel -uniform vec4 cViewportSize; - -void main() -{ - // get the view space position and normal of the fragment - vec3 fragmentPosition = texture2D(sPosition, oUv0).xyz; - vec3 fragmentNormal = texture2D(sNormal, oUv0).xyz; - - float totalGI = 0.0f; - - const int stippleSize = 11; // must be odd - for (int i = 0; i < (stippleSize + 1) / 2; i++) - { - vec2 diagonalStart = vec2(-(stippleSize - 1.0) / 2.0, 0) + i; - for(int j = 0; j < (stippleSize + 1) / 2; j++) - { - vec2 sampleOffset = diagonalStart + vec2(j, -j); - - vec2 sampleUV = oUv0 + (sampleOffset * cViewportSize.zw * cKernelSize); - vec3 samplePos = texture2D(sPosition, sampleUV).xyz; - - vec3 toCenter = samplePos - fragmentPosition; - float distance = length(toCenter); - - toCenter = normalize(toCenter); - float centerContrib = clamp((dot(toCenter, fragmentNormal) - cMinimumCrease) * cBias, 0.0, 1.0); - float rangeAttenuation = 1.0f - clamp(distance / cRange, 0.0, 1.0); - - totalGI += centerContrib * rangeAttenuation; - } - } - - totalGI /= cAverager; - gl_FragColor = 1.0 - vec4(totalGI, totalGI, totalGI, 1.0); -} diff --git a/Samples/Media/materials/scripts/SSAO/CrossBilateralFilterXFP.glsl b/Samples/Media/materials/scripts/SSAO/CrossBilateralFilterXFP.glsl deleted file mode 100644 index b183aacd91c..00000000000 --- a/Samples/Media/materials/scripts/SSAO/CrossBilateralFilterXFP.glsl +++ /dev/null @@ -1,35 +0,0 @@ -// cross bilateral filter -// gaussian blur with photometric weighting -// note: encode the viewspace z component in the accessibility texture to reduce -// the texture fetch count -#version 120 -varying vec2 oUv0; - -uniform sampler2D sAccessibility; -uniform sampler2D sMRT2; -uniform float stepX; // inverse viewport width -uniform float cPhotometricExponent; - -void main() -{ - const int kernelWidth = 13; - float sigma = (kernelWidth - 1) / 6; // make the kernel span 6 sigma - - float fragmentDepth = texture2D(sMRT2, oUv0).z; - - float weights = 0; - float blurred = 0; - - for (float i = -(kernelWidth - 1) / 2; i < (kernelWidth - 1) / 2; i++) - { - float geometricWeight = exp(-pow(i, 2) / (2 * pow(sigma, 2))); - float sampleDepth = texture2D(sMRT2, vec2(oUv0.x - i * stepX, oUv0.y)).z; - float photometricWeight = 1 / pow((1 + abs(fragmentDepth - sampleDepth)), cPhotometricExponent); - - weights += (geometricWeight * photometricWeight); - blurred += texture2D(sAccessibility, vec2(oUv0.x - i * stepX, oUv0.y)).r * geometricWeight * photometricWeight; - } - - blurred /= weights; - gl_FragColor = vec4(blurred, blurred, blurred, 1); -} \ No newline at end of file diff --git a/Samples/Media/materials/scripts/SSAO/CrossBilateralFilterYFP.glsl b/Samples/Media/materials/scripts/SSAO/CrossBilateralFilterYFP.glsl deleted file mode 100644 index d0b7cd9d0a3..00000000000 --- a/Samples/Media/materials/scripts/SSAO/CrossBilateralFilterYFP.glsl +++ /dev/null @@ -1,31 +0,0 @@ -#version 120 -varying vec2 oUv0; - -uniform sampler2D sAccessibility; -uniform sampler2D sMRT2; -uniform float stepY; // inverse viewport width -uniform float cPhotometricExponent; - -void main() -{ - const int kernelWidth = 13; - float sigma = (kernelWidth - 1) / 6; // make the kernel span 6 sigma - - float fragmentDepth = texture2D(sMRT2, oUv0).z; - - float weights = 0; - float blurred = 0; - - for (float i = -(kernelWidth - 1) / 2; i < (kernelWidth - 1) / 2; i++) - { - float geometricWeight = exp(-pow(i, 2) / (2 * pow(sigma, 2))); - float sampleDepth = texture2D(sMRT2, vec2(oUv0.x, oUv0.y - i * stepY)).z; - float photometricWeight = 1 / pow((1 + abs(fragmentDepth - sampleDepth)), cPhotometricExponent); - - weights += (geometricWeight * photometricWeight); - blurred += texture2D(sAccessibility, vec2(oUv0.x, oUv0.y - i * stepY)).r * geometricWeight * photometricWeight; - } - - blurred /= weights; - gl_FragColor = vec4(blurred, blurred, blurred, 1); -} diff --git a/Samples/Media/materials/scripts/SSAO/Crytek.cg b/Samples/Media/materials/scripts/SSAO/Crytek.cg deleted file mode 100644 index 23118f8bb6e..00000000000 --- a/Samples/Media/materials/scripts/SSAO/Crytek.cg +++ /dev/null @@ -1,85 +0,0 @@ -void Crytek_fp -( - in float4 position : POSITION, - in float2 fragmentTC : TEXCOORD0, - - out float4 oColor0 : COLOR0, - - uniform sampler sSceneDepthSampler : register(s0), // depth = w component [0, 1] - uniform sampler sRotSampler4x4 : register(s1), // rotation sampler -> pseudo random spherical weighted sampling - uniform float4 cViewportSize, // auto param width/height/inv. width/inv. height - uniform float cFov, // vertical field of view in radians - uniform float farClipDistance, - uniform float cSampleInScreenspace, // whether to sample in screen or world space - uniform float cSampleLengthScreenSpace, // The sample length in screen space [0, 1] - uniform float cSampleLengthWorldSpace, // the sample length in world space in units - uniform float cOffsetScale, // [0, 1] The distance of the first sample. samples are the - // placed in [cOffsetScale * cSampleLengthScreenSpace, cSampleLengthScreenSpace] - uniform float cDefaultAccessibility, // the default value used in the lerp() expression for invalid samples [0, 1] - uniform float cEdgeHighlight // multiplier for edge highlighting in [1, 2] 1 is full highlighting 2 is off -) -{ - const int nSampleNum = 32; // number of samples - - // get the depth of the current pixel and convert into world space unit [0, inf] - float fragmentWorldDepth = tex2D(sSceneDepthSampler, fragmentTC).w * farClipDistance; - - // get rotation vector, rotation is tiled every 4 screen pixels - float2 rotationTC = fragmentTC * cViewportSize.xy / 4; - float3 rotationVector = 2 * tex2D(sRotSampler4x4, rotationTC).xyz - 1; // [-1, 1]x[-1. 1]x[-1. 1] - - float rUV = 0; // radius of influence in screen space - float r = 0; // radius of influence in world space - if (cSampleInScreenspace == 1) - { - rUV = cSampleLengthScreenSpace; - r = tan(rUV * cFov) * fragmentWorldDepth; - } - else - { - rUV = atan(cSampleLengthWorldSpace / fragmentWorldDepth) / cFov; // the radius of influence projected into screen space - r = cSampleLengthWorldSpace; - } - - float sampleLength = cOffsetScale; // the offset for the first sample - const float sampleLengthStep = pow((rUV / sampleLength), 1.0f/nSampleNum); - - float accessibility = 0; - // sample the sphere and accumulate accessibility - for (int i = 0; i < (nSampleNum/8); i++) - { - for (int x = -1; x <= 1; x += 2) - for (int y = -1; y <= 1; y += 2) - for (int z = -1; z <= 1; z += 2) - { - //generate offset vector - float3 offset = normalize(float3(x, y, z)) * sampleLength; - - // update sample length - sampleLength *= sampleLengthStep; - - // reflect offset vector by random rotation sample (i.e. rotating it) - float3 rotatedOffset = reflect(offset, rotationVector); - - float2 sampleTC = fragmentTC + rotatedOffset.xy * rUV; - - // read scene depth at sampling point and convert into world space units (m or whatever) - float sampleWorldDepth = tex2D(sSceneDepthSampler, sampleTC).w * farClipDistance; - - // check if depths of both pixels are close enough and sampling point should affect our center pixel - float fRangeIsInvalid = saturate((fragmentWorldDepth - sampleWorldDepth) / r); - - // accumulate accessibility, use default value of 0.5 if right computations are not possible - accessibility += lerp(sampleWorldDepth > (fragmentWorldDepth + rotatedOffset.z * r), cDefaultAccessibility, fRangeIsInvalid); - } - } - - // get average value - accessibility /= nSampleNum; - - // normalize, remove edge highlighting - accessibility *= cEdgeHighlight; - - // amplify and saturate if necessary - oColor0 = float4(accessibility.xxx, 1); -} diff --git a/Samples/Media/materials/scripts/SSAO/Crytek.material b/Samples/Media/materials/scripts/SSAO/Crytek.material deleted file mode 100644 index 925a9c6e17e..00000000000 --- a/Samples/Media/materials/scripts/SSAO/Crytek.material +++ /dev/null @@ -1,75 +0,0 @@ -fragment_program SSAO/Crytek_fp_hlsl hlsl -{ - source Crytek.cg - entry_point Crytek_fp - target ps_3_0 -} - -fragment_program SSAO/Crytek_fp_cg cg -{ - source Crytek.cg - entry_point Crytek_fp - profiles ps_3_0 arbfp1 -} - -fragment_program SSAO/Crytek_fp_glsl glsl -{ - source CrytekFP.glsl - - default_params - { - param_named sSceneDepthSampler int 0 - param_named sRotSampler4x4 int 1 - } -} - -fragment_program SSAO/Crytek_fp unified -{ - delegate SSAO/Crytek_fp_glsl - delegate SSAO/Crytek_fp_hlsl - delegate SSAO/Crytek_fp_cg -} - -material SSAO/Crytek -{ - technique - { - pass - { - depth_check off - - vertex_program_ref Ogre/Compositor/StdQuad_vp {} - fragment_program_ref SSAO/Crytek_fp - { - param_named_auto cViewportSize viewport_size - param_named_auto farClipDistance far_clip_distance - param_named_auto cFov fov - - param_named cSampleInScreenspace float 0 - param_named cSampleLengthScreenSpace float 0.06 - param_named cSampleLengthWorldSpace float 2 - param_named cOffsetScale float 0.05 - param_named cDefaultAccessibility float 0.5 - param_named cEdgeHighlight float 2 - } - - texture_unit - { - content_type compositor SSAO/GBuffer mrt 0 - tex_address_mode clamp - filtering none - } - - texture_unit - { - // texture regularSphere4.png - texture regularSphereJittered4.png - // texture regularSphereOctant4.png - // texture regularSphereJitteredOctant4.png - // texture rand4x4.png - tex_address_mode wrap - filtering none - } - } - } -} diff --git a/Samples/Media/materials/scripts/SSAO/CrytekFP.glsl b/Samples/Media/materials/scripts/SSAO/CrytekFP.glsl deleted file mode 100644 index 56ee89202f1..00000000000 --- a/Samples/Media/materials/scripts/SSAO/CrytekFP.glsl +++ /dev/null @@ -1,83 +0,0 @@ -#version 120 -varying vec2 oUv0; - -uniform sampler2D sSceneDepthSampler; -uniform sampler2D sRotSampler4x4; -uniform vec4 cViewportSize; // auto param width/height/inv. width/inv. height -uniform float cFov; // vertical field of view in radians -uniform float farClipDistance; -uniform float cSampleInScreenspace; // whether to sample in screen or world space -uniform float cSampleLengthScreenSpace; // The sample length in screen space [0, 1] -uniform float cSampleLengthWorldSpace; // the sample length in world space in units -uniform float cOffsetScale; // [0, 1] The distance of the first sample. samples are the - // placed in [cOffsetScale * cSampleLengthScreenSpace, cSampleLengthScreenSpace] -uniform float cDefaultAccessibility; // the default value used in the lerp() expression for invalid samples [0, 1] -uniform float cEdgeHighlight; // multiplier for edge highlighting in [1, 2] 1 is full highlighting 2 is off - -void main() -{ - const int nSampleNum = 32; // number of samples - - // get the depth of the current pixel and convert into world space unit [0, inf] - float fragmentWorldDepth = texture2D(sSceneDepthSampler, oUv0).w * farClipDistance; - - // get rotation vector, rotation is tiled every 4 screen pixels - vec2 rotationTC = oUv0 * cViewportSize.xy / 4.0; - vec3 rotationVector = 2.0 * texture2D(sRotSampler4x4, rotationTC).xyz - 1.0; // [-1, 1]x[-1. 1]x[-1. 1] - - float rUV = 0; // radius of influence in screen space - float r = 0; // radius of influence in world space - if (cSampleInScreenspace == 1) - { - rUV = cSampleLengthScreenSpace; - r = tan(rUV * cFov) * fragmentWorldDepth; - } - else - { - rUV = atan(cSampleLengthWorldSpace / fragmentWorldDepth) / cFov; // the radius of influence projected into screen space - r = cSampleLengthWorldSpace; - } - - float sampleLength = cOffsetScale; // the offset for the first sample - float sampleLengthStep = pow((rUV / sampleLength), 1.0f/nSampleNum); - - float accessibility = 0; - // sample the sphere and accumulate accessibility - for (int i = 0; i < (nSampleNum/8); i++) - { - for (int x = -1; x <= 1; x += 2) - for (int y = -1; y <= 1; y += 2) - for (int z = -1; z <= 1; z += 2) - { - //generate offset vector - vec3 offset = normalize(vec3(x, y, z)) * sampleLength; - - // update sample length - sampleLength *= sampleLengthStep; - - // reflect offset vector by random rotation sample (i.e. rotating it) - vec3 rotatedOffset = reflect(offset, rotationVector); - - vec2 sampleTC = oUv0 + rotatedOffset.xy * rUV; - - // read scene depth at sampling point and convert into world space units (m or whatever) - float sampleWorldDepth = texture2D(sSceneDepthSampler, sampleTC).w * farClipDistance; - - // check if depths of both pixels are close enough and sampling point should affect our center pixel - float fRangeIsInvalid = clamp((fragmentWorldDepth - sampleWorldDepth) / r, 0.0, 1.0); - - // accumulate accessibility, use default value of 0.5 if right computations are not possible - - accessibility += mix(float(sampleWorldDepth > (fragmentWorldDepth + rotatedOffset.z * r)) , cDefaultAccessibility, fRangeIsInvalid); - } - } - - // get average value - accessibility /= nSampleNum; - - // normalize, remove edge highlighting - accessibility *= cEdgeHighlight; - - // amplify and saturate if necessary - gl_FragColor = vec4(accessibility, accessibility, accessibility, 1.0); -} diff --git a/Samples/Media/materials/scripts/SSAO/GBuffer.material b/Samples/Media/materials/scripts/SSAO/GBuffer.material deleted file mode 100644 index ca03442cc83..00000000000 --- a/Samples/Media/materials/scripts/SSAO/GBuffer.material +++ /dev/null @@ -1,13 +0,0 @@ -material SSAO/GBuffer -{ - technique - { - pass - { - rtshader_system GBuffer - { - lighting_stage gbuffer normal_viewdepth viewpos - } - } - } -} diff --git a/Samples/Media/materials/scripts/SSAO/GaussianBlurXFP.glsl b/Samples/Media/materials/scripts/SSAO/GaussianBlurXFP.glsl deleted file mode 100644 index 764290eea70..00000000000 --- a/Samples/Media/materials/scripts/SSAO/GaussianBlurXFP.glsl +++ /dev/null @@ -1,26 +0,0 @@ -#version 120 -varying vec2 oUv0; - -uniform sampler2D mrt1; - -uniform float stepX; -uniform float cKernelWidthBias; - -void main() -{ - const int kernelWidth = 19; - float sigma = (kernelWidth - 1) / 6; // make the kernel span 6 sigma - - float weights = 0; - float blurredDepth = 0; - - for (float i = -(kernelWidth - 1) / 2; i < (kernelWidth - 1) / 2; i++) - { - float geometricWeight = exp(-pow(i, 2) / (2 * pow(sigma, 2))); - weights += geometricWeight; - blurredDepth += texture2D(mrt1, vec2(oUv0.x - i * stepX * cKernelWidthBias, oUv0.y)).w * geometricWeight; - } - - blurredDepth /= weights; - gl_FragColor = vec4(texture2D(mrt1, oUv0).xyz, blurredDepth); -} \ No newline at end of file diff --git a/Samples/Media/materials/scripts/SSAO/GaussianBlurYFP.glsl b/Samples/Media/materials/scripts/SSAO/GaussianBlurYFP.glsl deleted file mode 100644 index b84fe14b21b..00000000000 --- a/Samples/Media/materials/scripts/SSAO/GaussianBlurYFP.glsl +++ /dev/null @@ -1,26 +0,0 @@ -#version 120 -varying vec2 oUv0; - -uniform sampler2D mrt1; - -uniform float stepY; -uniform float cKernelWidthBias; - -void main() -{ - const int kernelWidth = 19; - float sigma = (kernelWidth - 1) / 6; // make the kernel span 6 sigma - - float weights = 0; - float blurredDepth = 0; - - for (float i = -(kernelWidth - 1) / 2; i < (kernelWidth - 1) / 2; i++) - { - float geometricWeight = exp(-pow(i, 2) / (2 * pow(sigma, 2))); - weights += geometricWeight; - blurredDepth += texture2D(mrt1, vec2(oUv0.x, oUv0.y - i * stepY * cKernelWidthBias)).w * geometricWeight; - } - - blurredDepth /= weights; - gl_FragColor = vec4(texture2D(mrt1, oUv0).xyz, blurredDepth); -} diff --git a/Samples/Media/materials/scripts/SSAO/HemisphereMC.cg b/Samples/Media/materials/scripts/SSAO/HemisphereMC.cg deleted file mode 100644 index 6f1ac64140b..00000000000 --- a/Samples/Media/materials/scripts/SSAO/HemisphereMC.cg +++ /dev/null @@ -1,86 +0,0 @@ -void HemisphereMC_fp -( - in const float2 uv : TEXCOORD0, - - out float4 oColor0 : COLOR0, - - uniform sampler sMRT1 : register(s0), // fragment normals - uniform sampler sMRT2 : register(s1), // view space position, remember that we are looking down the negative Z axis!!! - uniform sampler sRand : register(s2), // MxN random texture, M sets of N precomputed low-discrepancy samples - - uniform const float4 cViewportSize, // (viewport_width, viewport_height, inverse_viewport_width, inverse_viewport_height) - uniform const float cFov, // vertical field of view in radians - uniform const float cSampleInScreenspace, // whether to sample in screen or world space - uniform const float cSampleLengthScreenSpace, // The sample length in screen space [0, 1] - uniform const float cSampleLengthWorldSpace, // the sample length in world space in units - uniform const float cSampleLengthExponent // The exponent of the sample length -) -{ - const int interleaved = 4; - const int m = 8; - const int n = 4; - const int numSamples = m * n; - const float2 interleaveOffset = uv * cViewportSize.xy / interleaved; - const float3 fragmentPosition = tex2D(sMRT2, uv).xyz; // the current fragment in view space - const float3 fragmentNormal = tex2D(sMRT1, uv).xyz; // the fragment normal - float rUV = 0; // radius of influence in screen space - float r = 0; // radius of influence in world space - - if (cSampleInScreenspace == 1) - { - rUV = cSampleLengthScreenSpace; - r = tan(rUV * cFov) * -fragmentPosition.z; - } - else - { - rUV = atan(cSampleLengthWorldSpace / -fragmentPosition.z) / cFov; // the radius of influence projected into screen space - r = cSampleLengthWorldSpace; - } - - if (rUV < (cViewportSize.z)) // abort if the projected radius of influence is smaller than 1 fragment - { - oColor0 = 1; - return; - } - - - float accessibility = 0; // accessibility of the fragment - - const float3 viewVector = float3(0, 0, 1); // the constant view vector in view space - - // the reflection vector to align the hemisphere with the fragment normal - // somehow the x component must be flipped...??? - const float3 reflector = normalize(fragmentNormal + viewVector) * float3(-1, 1, 1); - - float count = 0; - float sampleLength; - - for (float i = 0.0f; i < m; i++) - for (float j = 0.0f; j < n; j++) - { - count ++; - - const float2 randomTC = interleaveOffset + float2(i/(interleaved * m), j/(interleaved * n)); - float3 randomVector = (tex2D(sRand, randomTC) * 2 - 1); // unpack to [-1, 1]x[-1, 1]x[1, 1] - - sampleLength = pow(count/(float)numSamples, cSampleLengthExponent); - - const float3 sampleVector = reflect(randomVector, reflector) * sampleLength; - - const float2 sampleTC = uv + sampleVector.xy * rUV; - - const float3 samplePosition = tex2D(sMRT2, sampleTC); - - if (samplePosition.z < (fragmentPosition.z - sampleVector.z * r)) // thin air - accessibility++; - else // solid geometry - accessibility += length(fragmentPosition - samplePosition) > r; // out of reach, i.e. false occluder - } - - accessibility /= numSamples; - oColor0 = float4(accessibility.xxx, 1); - - float3 direction = 0; - direction += reflect(float3(0, 0, -1), reflector); - direction = normalize(direction); -} diff --git a/Samples/Media/materials/scripts/SSAO/HemisphereMC.hlsl b/Samples/Media/materials/scripts/SSAO/HemisphereMC.hlsl deleted file mode 100644 index 9f5afc90b2d..00000000000 --- a/Samples/Media/materials/scripts/SSAO/HemisphereMC.hlsl +++ /dev/null @@ -1,100 +0,0 @@ -SamplerState g_samLinear -{ - Filter = MIN_MAG_MIP_LINEAR; - AddressU = Wrap; - AddressV = Wrap; - AddressW = Wrap; -}; - -Texture2D sMRT1 : register(s0); // fragment normals -Texture2D sMRT2 : register(s1); // view space position, remember that we are looking down the negative Z axis!!! -Texture2D sRand : register(s2); // MxN random texture, M sets of N precomputed low-discrepancy samples - -struct v2p -{ - float4 position : SV_POSITION; - float2 uv : TEXCOORD0; -}; - -float4 HemisphereMC_fp -( - v2p input, - uniform const float4 cViewportSize, // (viewport_width, viewport_height, inverse_viewport_width, inverse_viewport_height) - uniform const float cFov, // vertical field of view in radians - uniform const float cSampleInScreenspace, // whether to sample in screen or world space - uniform const float cSampleLengthScreenSpace, // The sample length in screen space [0, 1] - uniform const float cSampleLengthWorldSpace, // the sample length in world space in units - uniform const float cSampleLengthExponent // The exponent of the sample length -) : SV_Target -{ - const int interleaved = 4; - const int m = 8; - const int n = 4; - const int numSamples = m * n; - const float2 interleaveOffset = input.uv * cViewportSize.xy / interleaved; - const float3 fragmentPosition = sMRT2.Sample(g_samLinear, input.uv).xyz; // the current fragment in view space - const float3 fragmentNormal = sMRT1.Sample(g_samLinear, input.uv).xyz; // the fragment normal - float rUV = 0; // radius of influence in screen space - float r = 0; // radius of influence in world space - - if (cSampleInScreenspace == 1) - { - rUV = cSampleLengthScreenSpace; - r = tan(rUV * cFov) * -fragmentPosition.z; - } - else - { - rUV = atan(cSampleLengthWorldSpace / -fragmentPosition.z) / cFov; // the radius of influence projected into screen space - r = cSampleLengthWorldSpace; - } - - if (rUV < (cViewportSize.z)) // abort if the projected radius of influence is smaller than 1 fragment - { - return float4(1.0,1.0,1.0,1.0); - } - - float accessibility = 0; // accessibility of the fragment - - const float3 viewVector = float3(0, 0, 1); // the constant view vector in view space - - // the reflection vector to align the hemisphere with the fragment normal - // somehow the x component must be flipped...??? - const float3 reflector = normalize(fragmentNormal + viewVector) * float3(-1, 1, 1); - - float count = 0; - float sampleLength; - float2 randomTC; - float3 randomVector; - float3 sampleVector; - float2 sampleTC; - float3 samplePosition; - for (float i = 0.0f; i < m; i++) - for (float j = 0.0f; j < n; j++) - { - count ++; - - randomTC = interleaveOffset + float2(i/(interleaved * m), j/(interleaved * n)); - randomVector = (sRand.SampleLevel(g_samLinear, randomTC, 0) * 2 - 1).xyz; // unpack to [-1, 1]x[-1, 1]x[1, 1] - - sampleLength = pow(count/(float)numSamples, cSampleLengthExponent); - - sampleVector = reflect(randomVector, reflector) * sampleLength; - - sampleTC = input.uv + sampleVector.xy * rUV; - - samplePosition = sMRT2.SampleLevel(g_samLinear, sampleTC, 0).xyz; - - if (samplePosition.z < (fragmentPosition.z - sampleVector.z * r)) // thin air - accessibility++; - else // solid geometry - accessibility += length(fragmentPosition - samplePosition) > r; // out of reach, i.e. false occluder - } - - accessibility /= numSamples; - - float3 direction = 0; - direction += reflect(float3(0, 0, -1), reflector); - direction = normalize(direction); - - return float4(accessibility.xxx, 1); -} diff --git a/Samples/Media/materials/scripts/SSAO/HemisphereMC.material b/Samples/Media/materials/scripts/SSAO/HemisphereMC.material deleted file mode 100644 index bacc1ad6a59..00000000000 --- a/Samples/Media/materials/scripts/SSAO/HemisphereMC.material +++ /dev/null @@ -1,79 +0,0 @@ -fragment_program SSAO/HemisphereMC_fp_hlsl hlsl -{ - source HemisphereMC.hlsl - entry_point HemisphereMC_fp - target ps_4_0 -} - -fragment_program SSAO/HemisphereMC_fp_cg cg -{ - source HemisphereMC.cg - entry_point HemisphereMC_fp - profiles ps_3_0 arbfp1 -} - -fragment_program SSAO/HemisphereMC_fp_glsl glsl -{ - source HemisphereMCFP.glsl - - default_params - { - param_named sMRT1 int 0 - param_named sMRT2 int 1 - param_named sRand int 2 - } -} - -fragment_program SSAO/HemisphereMC_fp unified -{ - delegate SSAO/HemisphereMC_fp_glsl - delegate SSAO/HemisphereMC_fp_hlsl - delegate SSAO/HemisphereMC_fp_cg -} - -// Monte Carlo Integration of the hemisphere definded by the fragment normal -// lossely based on Ritschel et al. SSDO. -material SSAO/HemisphereMC -{ - technique - { - pass - { - depth_check off - - vertex_program_ref Ogre/Compositor/StdQuad_vp {} - fragment_program_ref SSAO/HemisphereMC_fp - { - param_named_auto cViewportSize viewport_size - param_named_auto cFov fov - - param_named cSampleInScreenspace float 0 - param_named cSampleLengthScreenSpace float 0.06 - param_named cSampleLengthWorldSpace float 2 - param_named cSampleLengthExponent float 1 - - } - - texture_unit // normals - { - content_type compositor SSAO/GBuffer mrt 0 - tex_address_mode clamp - filtering none - } - - texture_unit // view space position - { - content_type compositor SSAO/GBuffer mrt 1 - tex_address_mode clamp - filtering none - } - - texture_unit - { - texture importance4InterleavedSphereHemisphere8x4.png - tex_address_mode wrap - filtering none - } - } - } -} diff --git a/Samples/Media/materials/scripts/SSAO/HemisphereMCFP.glsl b/Samples/Media/materials/scripts/SSAO/HemisphereMCFP.glsl deleted file mode 100644 index 70a1d91581a..00000000000 --- a/Samples/Media/materials/scripts/SSAO/HemisphereMCFP.glsl +++ /dev/null @@ -1,79 +0,0 @@ -#version 120 -varying vec2 oUv0; - -uniform sampler2D sMRT1; -uniform sampler2D sMRT2; -uniform sampler2D sRand; - -uniform vec4 cViewportSize; // (viewport_width, viewport_height, inverse_viewport_width, inverse_viewport_height) -uniform float cFov; // vertical field of view in radians -uniform float cSampleInScreenspace; // whether to sample in screen or world space -uniform float cSampleLengthScreenSpace; // The sample length in screen space [0, 1] -uniform float cSampleLengthWorldSpace; // the sample length in world space in units -uniform float cSampleLengthExponent; // The exponent of the sample length - -void main() -{ - const int interleaved = 4; - const int m = 8; - const int n = 4; - const int numSamples = m * n; - vec2 interleaveOffset = oUv0 * cViewportSize.xy / interleaved; - vec3 fragmentPosition = texture2D(sMRT2, oUv0).xyz; // the current fragment in view space - vec3 fragmentNormal = texture2D(sMRT1, oUv0).xyz; // the fragment normal - float rUV = 0; // radius of influence in screen space - float r = 0; // radius of influence in world space - - if (cSampleInScreenspace == 1) - { - rUV = cSampleLengthScreenSpace; - r = tan(rUV * cFov) * -fragmentPosition.z; - } - else - { - rUV = atan(cSampleLengthWorldSpace / -fragmentPosition.z) / cFov; // the radius of influence projected into screen space - r = cSampleLengthWorldSpace; - } - - if (rUV < cViewportSize.z) // abort if the projected radius of influence is smaller than 1 fragment - { - gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0); - return; - } - - float accessibility = 0; // accessibility of the fragment - - const vec3 viewVector = vec3(0.0, 0.0, 1.0); // the constant view vector in view space - - // the reflection vector to align the hemisphere with the fragment normal - // somehow the x component must be flipped...??? - vec3 reflector = normalize(fragmentNormal + viewVector) * vec3(-1.0, 1.0, 1.0); - - float count = 0; - float sampleLength; - - for (float i = 0.0f; i < m; i++) - for (float j = 0.0f; j < n; j++) - { - count ++; - - vec2 randomTC = interleaveOffset + vec2(i/(interleaved * m), j/(interleaved * n)); - vec3 randomVector = (texture2D(sRand, randomTC) * 2 - 1).xyz; // unpack to [-1, 1]x[-1, 1]x[1, 1] - - sampleLength = pow(count/(numSamples * 1.0), cSampleLengthExponent); - - vec3 sampleVector = reflect(randomVector, reflector) * sampleLength; - - vec2 sampleTC = oUv0 + sampleVector.xy * rUV; - - vec3 samplePosition = texture2D(sMRT2, sampleTC).xyz; - - if (samplePosition.z < (fragmentPosition.z - sampleVector.z * r)) // thin air - accessibility++; - else if(length(fragmentPosition - samplePosition) > r) // solid geometry - accessibility++; // out of reach, i.e. false occluder - } - - accessibility /= numSamples; - gl_FragColor = vec4(accessibility, accessibility, accessibility, 1.0); -} diff --git a/Samples/Media/materials/scripts/SSAO/HorizonBased.cg b/Samples/Media/materials/scripts/SSAO/HorizonBased.cg deleted file mode 100644 index 35a5d437294..00000000000 --- a/Samples/Media/materials/scripts/SSAO/HorizonBased.cg +++ /dev/null @@ -1,95 +0,0 @@ -void HorizonBased_fp -( - in float2 uv : TEXCOORD0, - - out float4 oColor0 : COLOR0, - - uniform sampler sMRT1 : register(s0), // fragment normal - uniform sampler sMRT2 : register(s1), // view space position - uniform sampler sRand : register(s2), // (cos(a), sin(a), jitter - - uniform float4 cViewportSize, // (viewport_width, viewport_height, inverse_viewport_width, inverse_viewport_height) - uniform float cFov, // vertical field of view in radians - uniform float cSampleInScreenspace, // whether to sample in screen or world space - uniform float cSampleLengthScreenSpace, // The sample length in screen space [0, 1] - uniform float cSampleLengthWorldSpace, // the sample length in world space in units - uniform float cAngleBias // angle bias to avoid shadows in low tessellated curvatures [0, pi/2] -) -{ - const float pi = 3.1415926535897932384626433832795028841971693993751; - - const float numSteps = 7; // number of samples/steps along a direction - const float numDirections = 4; // number of sampling directions in uv space - - float3 p = tex2D(sMRT2, uv).xyz; // the current fragment in view space - float3 pointNormal = tex2D(sMRT1, uv).xyz; // the fragment normal - - float Ruv = 0; // radius of influence in screen space - float R = 0; // radius of influence in world space - if (cSampleInScreenspace == 1) - { - Ruv = cSampleLengthScreenSpace; - R = tan(Ruv * cFov) * -p.z; - } - else - { - Ruv = atan(cSampleLengthWorldSpace / -p.z) / cFov; // the radius of influence projected into screen space - R = cSampleLengthWorldSpace; - } - - // if the radius of influence is smaller than one fragment we exit early, - // since all samples would hit the current fragment. - if (Ruv < (1 / cViewportSize.x)) - { - oColor0 = float4(1, 1, 1, 1); - return; - } - - float occlusion = 0; // occlusion of the fragment - float2x2 directionMatrix; // the matrix to create the sample directions - // the compiler should evaluate the directions at compile time - directionMatrix._m00 = cos((2 * pi) / numDirections); - directionMatrix._m01 = sin((2 * pi) / numDirections); - directionMatrix._m10 = - sin((2 * pi) / numDirections); - directionMatrix._m11 = cos((2 * pi) / numDirections); - float2 deltaUV = float2(1, 0) * (Ruv / (numSteps + 1)); // The step vector in view space. scale it to the step size - // we don't want to sample to the perimeter of R since those samples would be - // omitted by the distance attenuation (W(R) = 0 by definition) - // Therefore we add a extra step and don't use the last sample. - - float3 randomValues = tex2D(sRand, (uv * cViewportSize.xy) / 4); //4px tiles - float2x2 rotationMatrix; - rotationMatrix._m00 = (randomValues.x - 0.5) * 2; - rotationMatrix._m01 = (randomValues.y - 0.5) * 2; - rotationMatrix._m10 = - rotationMatrix._m01; - rotationMatrix._m11 = rotationMatrix._m00; - float jitter = randomValues.z; - - for (int i = 0; i < numDirections; i++) - { - deltaUV = mul(deltaUV, directionMatrix); // rotate the deltaUV vector by 1/numDirections - float2 sampleDirection = mul(deltaUV, rotationMatrix); // now rotate this vector with the random rotation - - float oldAngle = cAngleBias; - - for (int j = 1; j <= numSteps; j++) // sample along a direction, needs to start at one, for the sake of the next line - { - float2 sampleUV = uv + ((jitter + j) * sampleDirection); // jitter the step a little bit - - float3 sample = tex2D(sMRT2, sampleUV); // the sample in view space - float3 sampleVector = (sample - p); - float gamma = (pi / 2) - acos(dot(pointNormal, normalize(sampleVector))); //the angle between the fragment tangent and the sample - - if (gamma > oldAngle) - { - float attenuation = saturate(1 - (pow((length(sampleVector) / R), 2))); - occlusion += attenuation * (sin(gamma) - sin(oldAngle)); - oldAngle = gamma; - } - } - } - - // ??? should step samples that fall under the horizontal be considered in the following line??? - occlusion /= (numDirections * numSteps); - oColor0 = 1 - float4(occlusion.xxx, 1) * 2 * pi; -} diff --git a/Samples/Media/materials/scripts/SSAO/HorizonBased.hlsl b/Samples/Media/materials/scripts/SSAO/HorizonBased.hlsl deleted file mode 100644 index e40a19ce503..00000000000 --- a/Samples/Media/materials/scripts/SSAO/HorizonBased.hlsl +++ /dev/null @@ -1,115 +0,0 @@ -SamplerState g_samLinear -{ - Filter = MIN_MAG_MIP_LINEAR; - AddressU = Wrap; - AddressV = Wrap; - AddressW = Wrap; -}; - -uniform Texture2D sMRT1 : register(s0); // fragment normals -uniform Texture2D sMRT2 : register(s1); // view space position, remember that we are looking down the negative Z axis!!! -uniform Texture2D sRand : register(s2); // MxN random texture, M sets of N precomputed low-discrepancy samples - -struct fragmentIn -{ - float4 position : SV_POSITION; - float2 uv : TEXCOORD0; -}; - -float4 HorizonBased_fp -( - fragmentIn input, - - uniform float4 cViewportSize, // (viewport_width, viewport_height, inverse_viewport_width, inverse_viewport_height) - uniform float cFov, // vertical field of view in radians - uniform float cSampleInScreenspace, // whether to sample in screen or world space - uniform float cSampleLengthScreenSpace, // The sample length in screen space [0, 1] - uniform float cSampleLengthWorldSpace, // the sample length in world space in units - uniform float cAngleBias // angle bias to avoid shadows in low tessellated curvatures [0, pi/2] -) : SV_Target -{ - const float pi = 3.1415926535897932384626433832795028841971693993751; - - const float numSteps = 7; // number of samples/steps along a direction - const float numDirections = 4; // number of sampling directions in uv space - - float3 p = sMRT2.Sample(g_samLinear, input.uv).xyz; // the current fragment in view space - float3 pointNormal = sMRT1.Sample(g_samLinear, input.uv).xyz; // the fragment normal - - float Ruv = 0; // radius of influence in screen space - float R = 0; // radius of influence in world space - if (cSampleInScreenspace == 1) - { - Ruv = cSampleLengthScreenSpace; - R = tan(Ruv * cFov) * -p.z; - } - else - { - Ruv = atan(cSampleLengthWorldSpace / -p.z) / cFov; // the radius of influence projected into screen space - R = cSampleLengthWorldSpace; - } - - // if the radius of influence is smaller than one fragment we exit early, - // since all samples would hit the current fragment. - if (Ruv < (1 / cViewportSize.x)) - { - return float4(1, 1, 1, 1); - } - - float occlusion = 0; // occlusion of the fragment - float2x2 directionMatrix; // the matrix to create the sample directions - // the compiler should evaluate the directions at compile time - directionMatrix._m00 = cos((2 * pi) / numDirections); - directionMatrix._m01 = sin((2 * pi) / numDirections); - directionMatrix._m10 = - sin((2 * pi) / numDirections); - directionMatrix._m11 = cos((2 * pi) / numDirections); - float2 deltaUV = float2(1, 0) * (Ruv / (numSteps + 1)); // The step vector in view space. scale it to the step size - // we don't want to sample to the perimeter of R since those samples would be - // omitted by the distance attenuation (W(R) = 0 by definition) - // Therefore we add a extra step and don't use the last sample. - - float3 randomValues = sRand.Sample(g_samLinear, (input.uv * cViewportSize.xy) / 4).xyz; //4px tiles - float2x2 rotationMatrix; - rotationMatrix._m00 = (randomValues.x - 0.5) * 2; - rotationMatrix._m01 = (randomValues.y - 0.5) * 2; - rotationMatrix._m10 = - rotationMatrix._m01; - rotationMatrix._m11 = rotationMatrix._m00; - float jitter = randomValues.z; - - float2 sampleDirection; - float oldAngle; - float2 sampleUV; - float3 sample; - float3 sampleVector; - float gamma; - float attenuation; - - /*[unroll]*/ for (int i = 0; i < numDirections; i++) - { - deltaUV = mul(deltaUV, directionMatrix); // rotate the deltaUV vector by 1/numDirections - sampleDirection = mul(deltaUV, rotationMatrix); // now rotate this vector with the random rotation - - oldAngle = cAngleBias; - - /*[unroll]*/ for (int j = 1; j <= numSteps; j++) // sample along a direction, needs to start at one, for the sake of the next line - { - sampleUV = input.uv + ((jitter + j) * sampleDirection); // jitter the step a little bit - - sample = sMRT2.SampleLevel(g_samLinear, sampleUV, 0).xyz; // the sample in view space - sampleVector = (sample - p); - gamma = (pi / 2) - acos(dot(pointNormal, normalize(sampleVector))); //the angle between the fragment tangent and the sample - - if (gamma > oldAngle) - { - attenuation = saturate(1 - (pow((length(sampleVector) / R), 2))); - occlusion += attenuation * (sin(gamma) - sin(oldAngle)); - oldAngle = gamma; - } - } - } - - // ??? should step samples that fall under the horizontal be considered in the following line??? - occlusion /= (numDirections * numSteps); - float4 oColor0 = 1 - float4(occlusion.xxx, 1) * 2 * pi; - return oColor0; -} \ No newline at end of file diff --git a/Samples/Media/materials/scripts/SSAO/HorizonBased.material b/Samples/Media/materials/scripts/SSAO/HorizonBased.material deleted file mode 100644 index 2c3f3cc2183..00000000000 --- a/Samples/Media/materials/scripts/SSAO/HorizonBased.material +++ /dev/null @@ -1,75 +0,0 @@ -fragment_program SSAO/HorizonBased_fp_hlsl hlsl -{ - source HorizonBased.hlsl - entry_point HorizonBased_fp - target ps_4_0 -} - -fragment_program SSAO/HorizonBased_fp_cg cg -{ - source HorizonBased.cg - entry_point HorizonBased_fp - profiles ps_3_0 arbfp1 -} - -fragment_program SSAO/HorizonBased_fp_glsl glsl -{ - source HorizonBasedFP.glsl - - default_params - { - param_named sMRT1 int 0 - param_named sMRT2 int 1 - param_named sRand int 2 - } -} -fragment_program SSAO/HorizonBased_fp unified -{ - delegate SSAO/HorizonBased_fp_glsl - delegate SSAO/HorizonBased_fp_hlsl - delegate SSAO/HorizonBased_fp_cg -} - -material SSAO/HorizonBased -{ - technique - { - pass - { - depth_check off - - vertex_program_ref Ogre/Compositor/StdQuad_vp {} - fragment_program_ref SSAO/HorizonBased_fp - { - param_named_auto cViewportSize viewport_size - param_named_auto cFov fov - - param_named cSampleInScreenspace float 0 - param_named cSampleLengthScreenSpace float 0.06 - param_named cSampleLengthWorldSpace float 2 - param_named cAngleBias float 0.2 - } - - texture_unit // fragment normal - { - content_type compositor SSAO/GBuffer mrt 0 - tex_address_mode clamp - filtering none - } - - texture_unit // view position - { - content_type compositor SSAO/GBuffer mrt 1 - tex_address_mode clamp - filtering none - } - - texture_unit - { - texture randCosSinJitter4x4.png - tex_address_mode wrap - filtering none - } - } - } -} diff --git a/Samples/Media/materials/scripts/SSAO/HorizonBasedFP.glsl b/Samples/Media/materials/scripts/SSAO/HorizonBasedFP.glsl deleted file mode 100644 index 75b9b42804c..00000000000 --- a/Samples/Media/materials/scripts/SSAO/HorizonBasedFP.glsl +++ /dev/null @@ -1,91 +0,0 @@ -#version 120 -varying vec2 oUv0; - -uniform sampler2D sMRT1; -uniform sampler2D sMRT2; -uniform sampler2D sRand; - -uniform vec4 cViewportSize; // (viewport_width, viewport_height, inverse_viewport_width, inverse_viewport_height) -uniform float cFov; // vertical field of view in radians -uniform float cSampleInScreenspace; // whether to sample in screen or world space -uniform float cSampleLengthScreenSpace; // The sample length in screen space [0, 1] -uniform float cSampleLengthWorldSpace; // the sample length in world space in units -uniform float cAngleBias; // angle bias to avoid shadows in low tessellated curvatures [0, pi/2] - -void main() -{ - const float pi = 3.1415926535897932384626433832795028841971693993751; - - const float numSteps = 7; // number of samples/steps along a direction - const float numDirections = 4; // number of sampling directions in oUv0 space - - vec3 p = texture2D(sMRT2, oUv0).xyz; // the current fragment in view space - vec3 pointNormal = texture2D(sMRT1, oUv0).xyz; // the fragment normal - - float Ruv = 0; // radius of influence in screen space - float R = 0; // radius of influence in world space - if (cSampleInScreenspace == 1) - { - Ruv = cSampleLengthScreenSpace; - R = tan(Ruv * cFov) * -p.z; - } - else - { - Ruv = atan(cSampleLengthWorldSpace / -p.z) / cFov; // the radius of influence projected into screen space - R = cSampleLengthWorldSpace; - } - - // if the radius of influence is smaller than one fragment we exit early, - // since all samples would hit the current fragment. - if (Ruv < (1 / cViewportSize.x)) - { - gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0); - return; - } - - float occlusion = 0; // occlusion of the fragment - - // the matrix to create the sample directions - // the compiler should evaluate the directions at compile time - mat2 directionMatrix = mat2( cos( (2 * pi) / numDirections ), -sin( (2 * pi) / numDirections ), - sin( (2 * pi) / numDirections ), cos( (2 * pi) / numDirections )); - - vec2 deltaUV = vec2(1, 0) * (Ruv / (numSteps + 1)); // The step vector in view space. scale it to the step size - - // we don't want to sample to the perimeter of R since those samples would be - // omitted by the distance attenuation (W(R) = 0 by definition) - // Therefore we add a extra step and don't use the last sample. - vec3 randomValues = texture2D(sRand, (oUv0 * cViewportSize.xy) / 4).xyz; //4px tiles - mat2 rotationMatrix = mat2( (randomValues.x - 0.5) * 2, -(randomValues.y - 0.5) * 2, - (randomValues.y - 0.5) * 2, (randomValues.x - 0.5) * 2); - - float jitter = randomValues.z; - - for (int i = 0; i < numDirections; i++) - { - deltaUV = directionMatrix * deltaUV; // rotate the deltaUV vector by 1/numDirections - vec2 sampleDirection = rotationMatrix * deltaUV; // now rotate this vector with the random rotation - - float oldAngle = cAngleBias; - - for (int j = 1; j <= numSteps; j++) // sample along a direction, needs to start at one, for the sake of the next line - { - vec2 sampleUV = oUv0 + ((jitter + j) * sampleDirection); // jitter the step a little bit - - vec3 sample = texture2D(sMRT2, sampleUV).xyz; // the sample in view space - vec3 sampleVector = (sample - p); - float gamma = (pi / 2) - acos(dot(pointNormal, normalize(sampleVector))); //the angle between the fragment tangent and the sample - - if (gamma > oldAngle) - { - float attenuation = clamp(1 - (pow((length(sampleVector) / R), 2)), 0.0, 1.0); - occlusion += attenuation * (sin(gamma) - sin(oldAngle)); - oldAngle = gamma; - } - } - } - - // ??? should step samples that fall under the horizontal be considered in the following line??? - occlusion /= (numDirections * numSteps); - gl_FragColor = 1 - vec4(occlusion, occlusion, occlusion, 1) * 2 * pi; -} diff --git a/Samples/Media/materials/scripts/SSAO/Modulate.material b/Samples/Media/materials/scripts/SSAO/Modulate.material deleted file mode 100644 index ffdcc293722..00000000000 --- a/Samples/Media/materials/scripts/SSAO/Modulate.material +++ /dev/null @@ -1,24 +0,0 @@ -material SSAO/Post/Modulate -{ - technique - { - pass - { - lighting off - polygon_mode_overrideable false - - texture_unit - { - content_type compositor SSAO/Post/Modulate ssao - filtering none - } - - texture_unit - { - content_type compositor SSAO/GBuffer scene - filtering none - colour_op modulate - } - } - } -} diff --git a/Samples/Media/materials/scripts/SSAO/SSAO.compositor b/Samples/Media/materials/scripts/SSAO/SSAO.compositor deleted file mode 100644 index c8e1117ec77..00000000000 --- a/Samples/Media/materials/scripts/SSAO/SSAO.compositor +++ /dev/null @@ -1,231 +0,0 @@ -compositor SSAO/GBuffer -{ - technique - { - // GBuffer enconding: -------------------------------------------------- - // mrt0: rgba --> unused in this sample (plain white, (1, 1, 1, 1)) - // mrt1: xyz --> normals, w --> normalized linear depth [0, 1] - // mrt2: xyz --> position in view space - // - // use a better packing of variables in the mrt to (possibly) increase - // performance! - // --------------------------------------------------------------------- - texture mrt target_width target_height PF_FLOAT32_RGBA PF_FLOAT32_RGBA chain_scope - texture occlusion target_width target_height PF_FLOAT32_RGBA chain_scope - texture scene target_width target_height PF_BYTE_RGBA chain_scope - - // the scene we want to modulate - target scene - { - input previous - } - - target mrt - { - input none - shadows off - material_scheme GBuffer - - pass clear - { - buffers colour depth stencil - depth_value 1.0 - } - - pass render_scene {} - } - } -} - -compositor SSAO/Volumetric // Szirmay-Kalos et al 2010 -{ - technique - { - texture_ref occlusion SSAO/GBuffer occlusion - - target occlusion - { - input none - - pass render_quad - { - material SSAO/Volumetric - } - } - } -} - - -compositor SSAO/HemisphereMC // Ritschel et al. inspired hemisphere mc integration -{ - technique - { - texture_ref occlusion SSAO/GBuffer occlusion - - target occlusion - { - input none - - pass render_quad - { - material SSAO/HemisphereMC - } - } - } -} - -compositor SSAO/HorizonBased // Bavoil and Sainz in ShaderX7 -{ - technique - { - texture_ref occlusion SSAO/GBuffer occlusion - - target occlusion - { - input none - - pass render_quad - { - material SSAO/HorizonBased - } - } - } -} - - -compositor SSAO/Crytek // Crytek style ssao as found in shaderX7 -{ - technique - { - texture_ref occlusion SSAO/GBuffer occlusion - - target occlusion - { - input none - - pass render_quad - { - material SSAO/Crytek - } - } - } -} - - -compositor SSAO/CreaseShading // Megan Fox's crease shading http://www.shalinor.com/research.html -{ - technique - { - texture_ref occlusion SSAO/GBuffer occlusion - - target occlusion - { - input none - - pass render_quad - { - material SSAO/CreaseShading - } - } - } -} - -compositor SSAO/UnsharpMask //Unsharp mask the depth buffer [LCD2006] -{ - technique - { - texture blurred target_width target_height PF_FLOAT32_RGBA - texture_ref occlusion SSAO/GBuffer occlusion - - target blurred - { - input none - - pass render_quad - { - material SSAO/UnsharpMask/GaussianBlurX - } - } - - target blurred - { - input none - - pass render_quad - { - material SSAO/UnsharpMask/GaussianBlurY - input 0 blurred - } - } - - target occlusion - { - input none - pass clear {} - - pass render_quad - { - material SSAO/UnsharpMask - input 0 blurred - } - } - } -} - -compositor SSAO/ShowNormals -{ - technique - { - texture_ref occlusion SSAO/GBuffer occlusion - - target occlusion - { - input none - - pass render_quad - { - // Renders a fullscreen quad with a material - material SSAO/ShowNormals - } - } - } -} - -compositor SSAO/ShowDepth -{ - technique - { - texture_ref occlusion SSAO/GBuffer occlusion - - target occlusion - { - input none - - pass render_quad - { - // Renders a fullscreen quad with a material - material SSAO/ShowDepth - } - } - } -} - -compositor SSAO/ShowViewPos -{ - technique - { - texture_ref occlusion SSAO/GBuffer occlusion - - target occlusion - { - input none - - pass render_quad - { - // Renders a fullscreen quad with a material - material SSAO/ShowViewPos - } - } - } -} - diff --git a/Samples/Media/materials/scripts/SSAO/SSAOPost.cg b/Samples/Media/materials/scripts/SSAO/SSAOPost.cg deleted file mode 100644 index 0b1eb27dac4..00000000000 --- a/Samples/Media/materials/scripts/SSAO/SSAOPost.cg +++ /dev/null @@ -1,145 +0,0 @@ -#include - -SAMPLER2D(sOcclusion, 0); -SAMPLER2D(sMrt1, 1); // normals + depth - -SAMPLER2D(sAccessibility, 0); -SAMPLER2D(sMRT2, 1); // the view space position, xyz - -// a very simple 4x4 box filter -// the kernel has the following form -// o o o o -// o o o o -// o o x o -// o o o o -// where x marks the fragment position and the o marks a sampling point -void boxFilter_fp -( - in float4 position : POSITION, - in float2 screenTC : TEXCOORD0, - - out float4 oColor0 : COLOR0, - - uniform float4 screenSize, - uniform float farClipDistance -) -{ - float color = 0; - for (int x = -2; x < 2; x++) - for (int y = -2; y < 2; y++) - { - color += tex2D(sOcclusion, float2(screenTC.x + x * screenSize.z, screenTC.y + y * screenSize.w)).x; - } - color /= 16; - - oColor0 = float4(color.xxx, 1); -} - - -// a very simple and slightly dumb depth aware 4x4 box filter -// the kernel has the following form -// o o o o -// o o o o -// o o x o -// o o o o -// where x marks the fragment position and the o marks a sampling point -void smartBoxFilter_fp -( - in float4 position : POSITION, - in float2 screenTC : TEXCOORD0, - - out float4 oColor0 : COLOR0, - - uniform float4 screenSize, - uniform float farClipDistance -) -{ - float fragmentDepth = tex2D(sMrt1, screenTC).x; - - float color = 0; - float weight = 0; - for (int x = -2; x < 2; x++) - for (int y = -2; y < 2; y++) - { - float sampleDepth = tex2D(sMrt1, float2(screenTC.x + x * screenSize.z, screenTC.y + y * screenSize.w)).x; - float dist = abs(fragmentDepth - sampleDepth) * farClipDistance + 0.5; - float sampleWeight = 1 / (pow(dist, 1) + 1); - color += sampleWeight * tex2D(sOcclusion, float2(screenTC.x + x * screenSize.z, screenTC.y + y * screenSize.w)).x; - weight += sampleWeight; - } - color /= weight; - - oColor0 = float4(color.xxx, 1); -// oColor0 = float4(tex2D(sOcclusion, screenTC).www, 1); -} - - -// cross bilateral filter -// gaussian blur with photometric weighting -// note: encode the viewspace z component in the accessibility texture to reduce -// the texture fetch count -void crossBilateralFilterX_fp -( - in float4 position : POSITION, - in float2 uv : TEXCOORD0, - - out float4 oColor0 : COLOR0, - - uniform float stepX, // inverse viewport width - uniform float cPhotometricExponent -) -{ - const int kernelWidth = 13; - float sigma = (kernelWidth - 1) / 6; // make the kernel span 6 sigma - - float fragmentDepth = tex2D(sMRT2, uv).z; - - float weights = 0; - float blurred = 0; - - for (float i = -(kernelWidth - 1) / 2; i < (kernelWidth - 1) / 2; i++) - { - float geometricWeight = exp(-pow(i, 2) / (2 * pow(sigma, 2))); - float sampleDepth = tex2D(sMRT2, float2(uv.x - i * stepX, uv.y)).z; - float photometricWeight = 1 / pow((1 + abs(fragmentDepth - sampleDepth)), cPhotometricExponent); - - weights += (geometricWeight * photometricWeight); - blurred += tex2D(sAccessibility, float2(uv.x - i * stepX, uv.y)).r * geometricWeight * photometricWeight; - } - - blurred /= weights; - oColor0 = float4(blurred.xxx, 1); -} - -void crossBilateralFilterY_fp -( - in float4 position : POSITION, - in float2 uv : TEXCOORD0, - - out float4 oColor0 : COLOR0, - - uniform float stepY, // inverse viewport width - uniform float cPhotometricExponent -) -{ - const int kernelWidth = 13; - float sigma = (kernelWidth - 1) / 6; // make the kernel span 6 sigma - - float fragmentDepth = tex2D(sMRT2, uv).z; - - float weights = 0; - float blurred = 0; - - for (float i = -(kernelWidth - 1) / 2; i < (kernelWidth - 1) / 2; i++) - { - float geometricWeight = exp(-pow(i, 2) / (2 * pow(sigma, 2))); - float sampleDepth = tex2D(sMRT2, float2(uv.x, uv.y - i * stepY)).z; - float photometricWeight = 1 / pow((1 + abs(fragmentDepth - sampleDepth)), cPhotometricExponent); - - weights += (geometricWeight * photometricWeight); - blurred += tex2D(sAccessibility, float2(uv.x, uv.y - i * stepY)).r * geometricWeight * photometricWeight; - } - - blurred /= weights; - oColor0 = float4(blurred.xxx, 1); -} diff --git a/Samples/Media/materials/scripts/SSAO/SSAOPost.compositor b/Samples/Media/materials/scripts/SSAO/SSAOPost.compositor deleted file mode 100644 index ab773edd7e4..00000000000 --- a/Samples/Media/materials/scripts/SSAO/SSAOPost.compositor +++ /dev/null @@ -1,100 +0,0 @@ -compositor SSAO/Post/Modulate -{ - technique - { - texture ssao target_width target_height PF_BYTE_RGBA chain_scope - - target ssao - { - input previous - } - - target_output - { - input none - - pass render_quad - { - material SSAO/Post/Modulate - } - } - } -} - -compositor SSAO/Post/NoFilter -{ - technique - { - target_output - { - input none - - pass render_quad - { - material SSAO/Post/NoFilter - } - } - } -} - -compositor SSAO/Post/BoxFilter -{ - technique - { - target_output - { - input none - - pass render_quad - { - material SSAO/Post/BoxFilter - } - } - } -} - -compositor SSAO/Post/SmartBoxFilter -{ - technique - { - target_output - { - input none - - pass render_quad - { - material SSAO/Post/SmartBoxFilter - } - } - } -} - - -compositor SSAO/Post/CrossBilateralFilter -{ - technique - { - texture accessibility target_width target_height PF_BYTE_RGBA - - target accessibility - { - input none - - pass render_quad - { - material SSAO/HorizonBased/CrossBilateralFilter/X - } - } - - target_output - { - input none - - pass render_quad - { - material SSAO/HorizonBased/CrossBilateralFilter/Y - input 0 accessibility - } - } - } -} diff --git a/Samples/Media/materials/scripts/SSAO/SSAOPost.material b/Samples/Media/materials/scripts/SSAO/SSAOPost.material deleted file mode 100644 index a12f6aacfc5..00000000000 --- a/Samples/Media/materials/scripts/SSAO/SSAOPost.material +++ /dev/null @@ -1,265 +0,0 @@ -fragment_program SSAO/Post/BoxFilter_fp_hlsl hlsl -{ - source SSAOPost.cg - entry_point boxFilter_fp - target ps_3_0 -} - -fragment_program SSAO/Post/SmartBoxFilter_fp_hlsl hlsl -{ - source SSAOPost.cg - entry_point smartBoxFilter_fp - target ps_3_0 -} - -fragment_program SSAO/HorizonBased/CrossBilateralFilter/X_fp_hlsl hlsl -{ - source SSAOPost.cg - entry_point crossBilateralFilterX_fp - target ps_3_0 -} - -fragment_program SSAO/HorizonBased/CrossBilateralFilter/Y_fp_hlsl hlsl -{ - source SSAOPost.cg - entry_point crossBilateralFilterY_fp - target ps_3_0 -} - -fragment_program SSAO/Post/BoxFilter_fp_cg cg -{ - source SSAOPost.cg - entry_point boxFilter_fp - profiles ps_3_0 arbfp1 -} - -fragment_program SSAO/Post/SmartBoxFilter_fp_cg cg -{ - source SSAOPost.cg - entry_point smartBoxFilter_fp - profiles ps_3_0 arbfp1 -} - -fragment_program SSAO/HorizonBased/CrossBilateralFilter/X_fp_cg cg -{ - source SSAOPost.cg - entry_point crossBilateralFilterX_fp - profiles ps_3_0 arbfp1 -} - -fragment_program SSAO/HorizonBased/CrossBilateralFilter/Y_fp_cg cg -{ - source SSAOPost.cg - entry_point crossBilateralFilterY_fp - profiles ps_3_0 arbfp1 -} - -fragment_program SSAO/Post/BoxFilter_fp_glsl glsl -{ - source BoxFilterFP.glsl - - default_params - { - param_named sOcclusion int 0 - } -} - -fragment_program SSAO/Post/SmartBoxFilter_fp_glsl glsl -{ - source SmartBoxFilterFP.glsl - - default_params - { - param_named sOcclusion int 0 - param_named sMrt1 int 1 - } -} - -fragment_program SSAO/HorizonBased/CrossBilateralFilter/X_fp_glsl glsl -{ - source CrossBilateralFilterXFP.glsl - - default_params - { - param_named sAccessibility int 0 - param_named sMRT2 int 1 - } -} - -fragment_program SSAO/HorizonBased/CrossBilateralFilter/Y_fp_glsl glsl -{ - source CrossBilateralFilterYFP.glsl - - default_params - { - param_named sAccessibility int 0 - param_named sMRT2 int 1 - } -} - -fragment_program SSAO/Post/BoxFilter_fp unified -{ - delegate SSAO/Post/BoxFilter_fp_glsl - delegate SSAO/Post/BoxFilter_fp_hlsl - delegate SSAO/Post/BoxFilter_fp_cg -} - -fragment_program SSAO/Post/SmartBoxFilter_fp unified -{ - delegate SSAO/Post/SmartBoxFilter_fp_glsl - delegate SSAO/Post/SmartBoxFilter_fp_hlsl - delegate SSAO/Post/SmartBoxFilter_fp_cg -} - -fragment_program SSAO/HorizonBased/CrossBilateralFilter/X_fp unified -{ - delegate SSAO/HorizonBased/CrossBilateralFilter/X_fp_glsl - delegate SSAO/HorizonBased/CrossBilateralFilter/X_fp_hlsl - delegate SSAO/HorizonBased/CrossBilateralFilter/X_fp_cg -} - -fragment_program SSAO/HorizonBased/CrossBilateralFilter/Y_fp unified -{ - delegate SSAO/HorizonBased/CrossBilateralFilter/Y_fp_glsl - delegate SSAO/HorizonBased/CrossBilateralFilter/Y_fp_hlsl - delegate SSAO/HorizonBased/CrossBilateralFilter/Y_fp_cg -} - -material SSAO/Post/NoFilter -{ - technique - { - pass - { - cull_hardware none - depth_check off - lighting off - - texture_unit - { - content_type compositor SSAO/GBuffer occlusion - tex_address_mode clamp - filtering none - } - } - } -} - -material SSAO/Post/BoxFilter -{ - technique - { - pass - { - depth_check off - - vertex_program_ref Ogre/Compositor/StdQuad_vp {} - fragment_program_ref SSAO/Post/BoxFilter_fp - { - param_named_auto screenSize viewport_size - } - - texture_unit - { - content_type compositor SSAO/GBuffer occlusion - tex_address_mode clamp - filtering none - } - } - } -} - -material SSAO/Post/SmartBoxFilter -{ - technique - { - pass - { - depth_check off - - vertex_program_ref Ogre/Compositor/StdQuad_vp {} - fragment_program_ref SSAO/Post/SmartBoxFilter_fp - { - param_named_auto screenSize viewport_size - param_named_auto farClipDistance far_clip_distance - } - - texture_unit - { - content_type compositor SSAO/GBuffer occlusion - tex_address_mode clamp - filtering none - } - - texture_unit - { - content_type compositor SSAO/GBuffer mrt 0 - tex_address_mode clamp - filtering none - } - } - } -} - -material SSAO/HorizonBased/CrossBilateralFilter/X -{ - technique - { - pass // two pass in x and y direction - { - depth_check off - - vertex_program_ref Ogre/Compositor/StdQuad_vp {} - fragment_program_ref SSAO/HorizonBased/CrossBilateralFilter/X_fp - { - param_named_auto stepX inverse_viewport_width - param_named cPhotometricExponent float 10 - } - - texture_unit // the accessability texture - { - content_type compositor SSAO/GBuffer occlusion - tex_address_mode clamp - filtering none - } - - texture_unit - { - content_type compositor SSAO/GBuffer mrt 1 - tex_address_mode clamp - filtering none - } - } - } -} - -material SSAO/HorizonBased/CrossBilateralFilter/Y -{ - technique - { - pass // two pass in x and y direction - { - depth_check off - - vertex_program_ref Ogre/Compositor/StdQuad_vp {} - fragment_program_ref SSAO/HorizonBased/CrossBilateralFilter/Y_fp - { - param_named_auto stepY inverse_viewport_height - param_named cPhotometricExponent float 10 - } - - texture_unit // the accessability texture, injected by the compositor - { - tex_address_mode clamp - filtering none - } - - texture_unit - { - content_type compositor SSAO/GBuffer mrt 1 - tex_address_mode clamp - filtering none - } - } - } -} diff --git a/Samples/Media/materials/scripts/SSAO/ShowDepth.cg b/Samples/Media/materials/scripts/SSAO/ShowDepth.cg deleted file mode 100644 index af07e47d38c..00000000000 --- a/Samples/Media/materials/scripts/SSAO/ShowDepth.cg +++ /dev/null @@ -1,14 +0,0 @@ -void ShowDepth_fp -( - in float4 position : POSITION, - in float2 iTexCoord: TEXCOORD0, - - out float4 oColor0 : COLOR0, - - uniform sampler mrt1: register(s0) -) -{ - float depth = tex2D(mrt1, iTexCoord).w; - depth = pow(depth, 0.3); - oColor0 = float4(depth, depth, depth, 1); -} diff --git a/Samples/Media/materials/scripts/SSAO/ShowDepth.material b/Samples/Media/materials/scripts/SSAO/ShowDepth.material deleted file mode 100644 index f32aeb062ae..00000000000 --- a/Samples/Media/materials/scripts/SSAO/ShowDepth.material +++ /dev/null @@ -1,43 +0,0 @@ -fragment_program SSAO/ShowDepth_fp_hlsl hlsl -{ - source ShowDepth.cg - entry_point ShowDepth_fp - target ps_2_a -} - -fragment_program SSAO/ShowDepth_fp_glsl glsl -{ - source ShowDepthFP.glsl - - default_params - { - param_named mrt1 int 0 - } -} - -fragment_program SSAO/ShowDepth_fp unified -{ - delegate SSAO/ShowDepth_fp_glsl - delegate SSAO/ShowDepth_fp_hlsl -} - -material SSAO/ShowDepth -{ - technique - { - pass - { - depth_check off - - vertex_program_ref Ogre/Compositor/StdQuad_vp {} - fragment_program_ref SSAO/ShowDepth_fp {} - - texture_unit - { - content_type compositor SSAO/GBuffer mrt 0 - tex_address_mode clamp - filtering none - } - } - } -} diff --git a/Samples/Media/materials/scripts/SSAO/ShowDepthFP.glsl b/Samples/Media/materials/scripts/SSAO/ShowDepthFP.glsl deleted file mode 100644 index c7e7bda6229..00000000000 --- a/Samples/Media/materials/scripts/SSAO/ShowDepthFP.glsl +++ /dev/null @@ -1,10 +0,0 @@ -#version 120 -varying vec2 oUv0; - -uniform sampler2D mrt1; - -void main() -{ - float depth = texture2D(mrt1, oUv0).w; - gl_FragColor = vec4(vec3(pow(depth, 0.3)), 1.0); -} diff --git a/Samples/Media/materials/scripts/SSAO/ShowNormals.cg b/Samples/Media/materials/scripts/SSAO/ShowNormals.cg deleted file mode 100644 index 9b6edc16d10..00000000000 --- a/Samples/Media/materials/scripts/SSAO/ShowNormals.cg +++ /dev/null @@ -1,12 +0,0 @@ -void ShowNormals_fp -( - in float4 position : POSITION, - in float2 iTexCoord : TEXCOORD0, - - out float4 oColor0: COLOR0, - - uniform sampler mrt1: register(s0) -) -{ - oColor0 = float4(tex2D(mrt1, iTexCoord).xyz / 2 + 0.5, 1); -} diff --git a/Samples/Media/materials/scripts/SSAO/ShowNormals.material b/Samples/Media/materials/scripts/SSAO/ShowNormals.material deleted file mode 100644 index 665a9372d71..00000000000 --- a/Samples/Media/materials/scripts/SSAO/ShowNormals.material +++ /dev/null @@ -1,43 +0,0 @@ -fragment_program SSAO/ShowNormals_fp_hlsl hlsl -{ - source ShowNormals.cg - entry_point ShowNormals_fp - target ps_2_0 -} - -fragment_program SSAO/ShowNormals_fp_glsl glsl -{ - source ShowNormalsFP.glsl - - default_params - { - param_named mrt1 int 0 - } -} - -fragment_program SSAO/ShowNormals_fp unified -{ - delegate SSAO/ShowNormals_fp_glsl - delegate SSAO/ShowNormals_fp_hlsl -} - -material SSAO/ShowNormals -{ - technique - { - pass - { - depth_check off - - vertex_program_ref Ogre/Compositor/StdQuad_vp {} - fragment_program_ref SSAO/ShowNormals_fp {} - - texture_unit - { - content_type compositor SSAO/GBuffer mrt 0 - tex_address_mode clamp - filtering none - } - } - } -} diff --git a/Samples/Media/materials/scripts/SSAO/ShowNormalsFP.glsl b/Samples/Media/materials/scripts/SSAO/ShowNormalsFP.glsl deleted file mode 100644 index 9b533eadfd3..00000000000 --- a/Samples/Media/materials/scripts/SSAO/ShowNormalsFP.glsl +++ /dev/null @@ -1,9 +0,0 @@ -#version 120 -varying vec2 oUv0; - -uniform sampler2D mrt1; - -void main() -{ - gl_FragColor = vec4(texture2D(mrt1, oUv0).rgb / 2.0 + 0.5, 1.0); -} diff --git a/Samples/Media/materials/scripts/SSAO/ShowViewPos.cg b/Samples/Media/materials/scripts/SSAO/ShowViewPos.cg deleted file mode 100644 index 891cdc9f8ca..00000000000 --- a/Samples/Media/materials/scripts/SSAO/ShowViewPos.cg +++ /dev/null @@ -1,12 +0,0 @@ -void ShowViewPos_fp -( - in float4 position : POSITION, - in float2 iTexCoord : TEXCOORD0, - - out float4 oColor0: COLOR0, - - uniform sampler mrt2: register(s0) -) -{ - oColor0 = float4(tex2D(mrt2, iTexCoord).xyz * float3(0.1, 0.1, -0.01), 1); -} diff --git a/Samples/Media/materials/scripts/SSAO/ShowViewPos.material b/Samples/Media/materials/scripts/SSAO/ShowViewPos.material deleted file mode 100644 index 37ab1115e79..00000000000 --- a/Samples/Media/materials/scripts/SSAO/ShowViewPos.material +++ /dev/null @@ -1,43 +0,0 @@ -fragment_program SSAO/ShowViewPos_fp_hlsl hlsl -{ - source ShowViewPos.cg - entry_point ShowViewPos_fp - target ps_2_0 -} - -fragment_program SSAO/ShowViewPos_fp_glsl glsl -{ - source ShowViewPosFP.glsl - - default_params - { - param_named mrt2 int 0 - } -} - -fragment_program SSAO/ShowViewPos_fp unified -{ - delegate SSAO/ShowViewPos_fp_glsl - delegate SSAO/ShowViewPos_fp_hlsl -} - -material SSAO/ShowViewPos -{ - technique - { - pass - { - depth_check off - - vertex_program_ref Ogre/Compositor/StdQuad_vp {} - fragment_program_ref SSAO/ShowViewPos_fp {} - - texture_unit - { - content_type compositor SSAO/GBuffer mrt 0 - tex_address_mode clamp - filtering none - } - } - } -} diff --git a/Samples/Media/materials/scripts/SSAO/ShowViewPosFP.glsl b/Samples/Media/materials/scripts/SSAO/ShowViewPosFP.glsl deleted file mode 100644 index bd7fba90801..00000000000 --- a/Samples/Media/materials/scripts/SSAO/ShowViewPosFP.glsl +++ /dev/null @@ -1,9 +0,0 @@ -#version 120 -varying vec2 oUv0; - -uniform sampler2D mrt2; - -void main() -{ - gl_FragColor = vec4(texture2D(mrt2, oUv0).rgb * vec3(0.1, 0.1, -0.01), 1.0); -} diff --git a/Samples/Media/materials/scripts/SSAO/SmartBoxFilterFP.glsl b/Samples/Media/materials/scripts/SSAO/SmartBoxFilterFP.glsl deleted file mode 100644 index 628bf6ed675..00000000000 --- a/Samples/Media/materials/scripts/SSAO/SmartBoxFilterFP.glsl +++ /dev/null @@ -1,34 +0,0 @@ -// a very simple and slightly dumb depth aware 4x4 box filter -// the kernel has the following form -// o o o o -// o o o o -// o o x o -// o o o o -// where x marks the fragment position and the o marks a sampling point -#version 120 -varying vec2 oUv0; - -uniform sampler2D sMrt1; -uniform sampler2D sOcclusion; -uniform vec4 screenSize; -uniform float farClipDistance; - -void main() -{ - float fragmentDepth = texture2D(sMrt1, oUv0).x; - - float color = 0; - float weight = 0; - for (int x = -2; x < 2; x++) - for (int y = -2; y < 2; y++) - { - float sampleDepth = texture2D(sMrt1, vec2(oUv0.x + x * screenSize.z, oUv0.y + y * screenSize.w)).x; - float dist = abs(fragmentDepth - sampleDepth) * farClipDistance + 0.5; - float sampleWeight = 1 / (pow(dist, 1) + 1); - color += sampleWeight * texture2D(sOcclusion, vec2(oUv0.x + x * screenSize.z, oUv0.y + y * screenSize.w)).x; - weight += sampleWeight; - } - color /= weight; - - gl_FragColor = vec4(color, color, color, 1); -} \ No newline at end of file diff --git a/Samples/Media/materials/scripts/SSAO/UnsharpMask.cg b/Samples/Media/materials/scripts/SSAO/UnsharpMask.cg deleted file mode 100644 index 3805bd7aebc..00000000000 --- a/Samples/Media/materials/scripts/SSAO/UnsharpMask.cg +++ /dev/null @@ -1,81 +0,0 @@ -void UnsharpMask_fp -( - in float4 position : POSITION, - in float2 iTexCoord : TEXCOORD0, - - out float4 oColor0 : COLOR0, - - uniform sampler blurred: register(s0), - uniform sampler mrt0: register(s1), - uniform float cLambda -) -{ - float spacialImportance = tex2D(blurred, iTexCoord).w - tex2D(mrt0, iTexCoord).w; - float4 color = float4(1,1,1,1); - if (spacialImportance < 0) // darkening only - { - oColor0 = float4(color.rgb + (cLambda * spacialImportance), 1); - } else - { - oColor0 = color; - } -} - -void GaussianBlurX_fp -( - in float4 position : POSITION, - in float2 uv : TEXCOORD0, - - out float4 oColor0 : COLOR0, - - uniform sampler mrt1 : register(s0), - uniform float stepX, - uniform const float cKernelWidthBias -) -{ - const int kernelWidth = 19; - float sigma = (kernelWidth - 1) / 6; // make the kernel span 6 sigma - - float weights = 0; - float blurredDepth = 0; - - for (float i = -(kernelWidth - 1) / 2; i < (kernelWidth - 1) / 2; i++) - { - float geometricWeight = exp(-pow(i, 2) / (2 * pow(sigma, 2))); - weights += geometricWeight; - blurredDepth += tex2D(mrt1, float2(uv.x - i * stepX * cKernelWidthBias, uv.y)).w * geometricWeight; - } - - blurredDepth /= weights; - oColor0 = float4(tex2D(mrt1, uv).xyz, blurredDepth); -} - -void GaussianBlurY_fp -( - in float4 position : POSITION, - in float2 uv : TEXCOORD0, - - out float4 oColor0 : COLOR0, - - uniform sampler mrt1 : register(s0), - uniform const float stepY, - uniform const float cKernelWidthBias -) -{ - const int kernelWidth = 19; - float sigma = (kernelWidth - 1) / 6; // make the kernel span 6 sigma - - float weights = 0; - float blurredDepth = 0; - - for (float i = -(kernelWidth - 1) / 2; i < (kernelWidth - 1) / 2; i++) - { - float geometricWeight = exp(-pow(i, 2) / (2 * pow(sigma, 2))); - weights += geometricWeight; - blurredDepth += tex2D(mrt1, float2(uv.x, uv.y - i * stepY * cKernelWidthBias)).w * geometricWeight; - } - - blurredDepth /= weights; - oColor0 = float4(tex2D(mrt1, uv).xyz, blurredDepth); -} - diff --git a/Samples/Media/materials/scripts/SSAO/UnsharpMask.material b/Samples/Media/materials/scripts/SSAO/UnsharpMask.material deleted file mode 100644 index ef1a49ca4e7..00000000000 --- a/Samples/Media/materials/scripts/SSAO/UnsharpMask.material +++ /dev/null @@ -1,173 +0,0 @@ -fragment_program SSAO/UnsharpMask_fp_hlsl hlsl -{ - source UnsharpMask.cg - entry_point UnsharpMask_fp - target ps_2_0 -} - -fragment_program SSAO/UnsharpMask/GaussianBlurX_fp_hlsl hlsl -{ - source UnsharpMask.cg - entry_point GaussianBlurX_fp - target ps_2_0 -} - -fragment_program SSAO/UnsharpMask/GaussianBlurY_fp_hlsl hlsl -{ - source UnsharpMask.cg - entry_point GaussianBlurY_fp - target ps_2_0 -} - -fragment_program SSAO/UnsharpMask_fp_cg cg -{ - source UnsharpMask.cg - entry_point UnsharpMask_fp - profiles ps_2_0 arbfp1 -} - -fragment_program SSAO/UnsharpMask/GaussianBlurX_fp_cg cg -{ - source UnsharpMask.cg - entry_point GaussianBlurX_fp - profiles ps_2_0 arbfp1 -} - -fragment_program SSAO/UnsharpMask/GaussianBlurY_fp_cg cg -{ - source UnsharpMask.cg - entry_point GaussianBlurY_fp - profiles ps_2_0 arbfp1 -} - -fragment_program SSAO/UnsharpMask_fp_glsl glsl -{ - source UnsharpMaskFP.glsl - - default_params - { - param_named blurred int 0 - param_named mrt0 int 1 - } -} - -fragment_program SSAO/UnsharpMask/GaussianBlurX_fp_glsl glsl -{ - source GaussianBlurXFP.glsl - - default_params - { - param_named mrt1 int 0 - } -} - -fragment_program SSAO/UnsharpMask/GaussianBlurY_fp_glsl glsl -{ - source GaussianBlurYFP.glsl - - default_params - { - param_named mrt1 int 0 - } -} - -fragment_program SSAO/UnsharpMask_fp unified -{ - delegate SSAO/UnsharpMask_fp_glsl - delegate SSAO/UnsharpMask_fp_hlsl - delegate SSAO/UnsharpMask_fp_cg -} - -fragment_program SSAO/UnsharpMask/GaussianBlurX_fp unified -{ - delegate SSAO/UnsharpMask/GaussianBlurX_fp_glsl - delegate SSAO/UnsharpMask/GaussianBlurX_fp_hlsl - delegate SSAO/UnsharpMask/GaussianBlurX_fp_cg -} - -fragment_program SSAO/UnsharpMask/GaussianBlurY_fp unified -{ - delegate SSAO/UnsharpMask/GaussianBlurY_fp_glsl - delegate SSAO/UnsharpMask/GaussianBlurY_fp_hlsl - delegate SSAO/UnsharpMask/GaussianBlurY_fp_cg -} - -material SSAO/UnsharpMask/GaussianBlurX -{ - technique - { - pass - { - depth_check off - - vertex_program_ref Ogre/Compositor/StdQuad_vp {} - fragment_program_ref SSAO/UnsharpMask/GaussianBlurX_fp - { - param_named_auto stepX inverse_viewport_width - param_named cKernelWidthBias float 1 - } - - texture_unit - { - content_type compositor SSAO/GBuffer mrt 0 - tex_address_mode clamp - filtering none - } - } - } -} - -material SSAO/UnsharpMask/GaussianBlurY -{ - technique - { - pass - { - depth_check off - - vertex_program_ref Ogre/Compositor/StdQuad_vp {} - fragment_program_ref SSAO/UnsharpMask/GaussianBlurY_fp - { - param_named_auto stepY inverse_viewport_height - param_named cKernelWidthBias float 1 - } - - texture_unit - { - content_type compositor SSAO/GBuffer mrt 0 - tex_address_mode clamp - filtering none - } - } - } -} - -material SSAO/UnsharpMask -{ - technique - { - pass - { - depth_check off - - vertex_program_ref Ogre/Compositor/StdQuad_vp {} - fragment_program_ref SSAO/UnsharpMask_fp - { - param_named cLambda float 5 - } - - texture_unit // blurred depth buffer - { - tex_address_mode clamp - filtering none - } - - texture_unit // original depth buffer - { - content_type compositor SSAO/GBuffer mrt 0 - tex_address_mode clamp - filtering none - } - } - } -} diff --git a/Samples/Media/materials/scripts/SSAO/UnsharpMaskFP.glsl b/Samples/Media/materials/scripts/SSAO/UnsharpMaskFP.glsl deleted file mode 100644 index 69971a89288..00000000000 --- a/Samples/Media/materials/scripts/SSAO/UnsharpMaskFP.glsl +++ /dev/null @@ -1,21 +0,0 @@ -#version 120 -varying vec2 oUv0; - -uniform sampler2D blurred; -uniform sampler2D mrt0; - -uniform float cLambda; - -void main() -{ - float spacialImportance = texture2D(blurred, oUv0).w - texture2D(mrt0, oUv0).w; - vec4 color = vec4(1,1,1,1); - if (spacialImportance < 0) // darkening only - { - gl_FragColor = vec4(color.rgb + (cLambda * spacialImportance), 1); - } - else - { - gl_FragColor = color; - } -} \ No newline at end of file diff --git a/Samples/Media/materials/scripts/SSAO/Volumetric.cg b/Samples/Media/materials/scripts/SSAO/Volumetric.cg deleted file mode 100644 index 3b4d6673079..00000000000 --- a/Samples/Media/materials/scripts/SSAO/Volumetric.cg +++ /dev/null @@ -1,82 +0,0 @@ -void Volumetric_fp -( - in const float2 uv : TEXCOORD0, - - out float4 oColor0 : COLOR0, - - uniform sampler sMRT1 : register(s0), // fragment normals - uniform sampler sMRT2 : register(s1), // view space position, remember that we are looking down the negative Z axis!!! - uniform sampler sRand : register(s2), - - uniform const float4 cViewportSize, // (viewport_width, viewport_height, inverse_viewport_width, inverse_viewport_height) - uniform const float cFov, // vertical field of view in radians - uniform const float cSampleInScreenspace, // whether to sample in screen or world space - uniform const float cSampleLengthScreenSpace, // The sample length in screen space [0, 1] - uniform const float cSampleLengthWorldSpace // the sample length in world space in units -) -{ - const int interleaved = 4; - const int m = 8; - const int n = 4; - const int numSamples = m * n; - - const float2 interleaveOffset = uv * cViewportSize.xy / interleaved; - - const float3 fragmentPosition = tex2D(sMRT2, uv).xyz; // the current fragment in view space - const float3 fragmentNormal = tex2D(sMRT1, uv).xyz * float3(1, -1, 1); // the fragment normal - - float rUV = 0; // radius of influence in screen space - float r = 0; // radius of influence in world space - if (cSampleInScreenspace == 1) - { - rUV = cSampleLengthScreenSpace; - r = tan(rUV * cFov) * -fragmentPosition.z; - } - else - { - rUV = atan(cSampleLengthWorldSpace / -fragmentPosition.z) / cFov; // the radius of influence projected into screen space - r = cSampleLengthWorldSpace; - } - - - if (rUV < (cViewportSize.z)) // abort if the projected radius of influence is smaller than 1 fragment - { - oColor0 = 1; - return; - } - - const float r2 = r/2; - const float rUV2 = rUV /2; - - const float3 center = fragmentPosition + fragmentNormal * (r2); - const float2 centerUV = uv + fragmentNormal * (rUV2); - - float F = 0; // unoccluded Volume - float V = 0; // occluded Volume - float invalid = 0; - - for (float i = 0.0f; i < m; i++) - for (float j = 0.0f; j < n; j++) - { - const float2 randomTC = interleaveOffset + float2(i/(interleaved * m), j/(interleaved * n)); - const float2 randomVector = (tex2D(sRand, randomTC) * 2 - 1).xy; // unpack to [-1, 1]^2 - - const float2 sample = randomVector * (r2); - const float2 sampleUV = randomVector * (rUV2); - - const float zEntry = center.z + (r2) * sqrt(1 - sample.x * sample.x - sample.y * sample.y); - const float zExit = center.z - (r2) * sqrt(1 - sample.x * sample.x - sample.y * sample.y); - const float zStar = tex2D(sMRT2, centerUV + sampleUV).z; - - F += zExit - zEntry; - - if (zExit <= zStar && zStar <= zEntry) - V += zStar - zEntry; - else //if (zStar < zExit) - V += zExit - zEntry; - } - - float accessibility = V / F; - oColor0 = float4(accessibility.xxx, 1); - -} diff --git a/Samples/Media/materials/scripts/SSAO/Volumetric.hlsl b/Samples/Media/materials/scripts/SSAO/Volumetric.hlsl deleted file mode 100644 index a5eb5e9f5a6..00000000000 --- a/Samples/Media/materials/scripts/SSAO/Volumetric.hlsl +++ /dev/null @@ -1,93 +0,0 @@ -SamplerState g_samLinear -{ - Filter = MIN_MAG_MIP_LINEAR; - AddressU = Wrap; - AddressV = Wrap; - AddressW = Wrap; -}; - -struct v2p -{ - float4 position : SV_POSITION; - float2 uv : TEXCOORD0; -}; - -uniform Texture2D sMRT1 : register(s0); // fragment normals -uniform Texture2D sMRT2 : register(s1); // view space position, remember that we are looking down the negative Z axis!!! -uniform Texture2D sRand : register(s2); - -float4 Volumetric_fp -( - v2p input, - - uniform const float4 cViewportSize, // (viewport_width, viewport_height, inverse_viewport_width, inverse_viewport_height) - uniform const float cFov, // vertical field of view in radians - uniform const float cSampleInScreenspace, // whether to sample in screen or world space - uniform const float cSampleLengthScreenSpace, // The sample length in screen space [0, 1] - uniform const float cSampleLengthWorldSpace // the sample length in world space in units -) : SV_Target -{ - const int interleaved = 4; - const int m = 8; - const int n = 4; - const int numSamples = m * n; - - const float2 interleaveOffset = input.uv * cViewportSize.xy / interleaved; - - const float3 fragmentPosition = sMRT2.Sample(g_samLinear, input.uv).xyz; // the current fragment in view space - const float3 fragmentNormal = sMRT1.Sample(g_samLinear, input.uv).xyz * float3(1, -1, 1); // the fragment normal - - float rUV = 0; // radius of influence in screen space - float r = 0; // radius of influence in world space - if (cSampleInScreenspace == 1) - { - rUV = cSampleLengthScreenSpace; - r = tan(rUV * cFov) * -fragmentPosition.z; - } - else - { - rUV = atan(cSampleLengthWorldSpace / -fragmentPosition.z) / cFov; // the radius of influence projected into screen space - r = cSampleLengthWorldSpace; - } - - - if (rUV < (cViewportSize.z)) // abort if the projected radius of influence is smaller than 1 fragment - { - return float4(1.0,1.0,1.0,1.0); - } - - const float r2 = r/2; - const float rUV2 = rUV /2; - - const float3 center = fragmentPosition + fragmentNormal * (r2); - const float2 centerUV = input.uv + fragmentNormal.xy * (rUV2); - - float F = 0; // unoccluded Volume - float V = 0; // occluded Volume - float invalid = 0; - - for (float i = 0.0f; i < m; i++) - for (float j = 0.0f; j < n; j++) - { - const float2 randomTC = interleaveOffset + float2(i/(interleaved * m), j/(interleaved * n)); - const float2 randomVector = (sRand.SampleLevel(g_samLinear, randomTC, 0) * 2 - 1).xy; // unpack to [-1, 1]^2 - - const float2 sample = randomVector * (r2); - const float2 sampleUV = randomVector * (rUV2); - - const float zEntry = center.z + (r2) * sqrt(1 - sample.x * sample.x - sample.y * sample.y); - const float zExit = center.z - (r2) * sqrt(1 - sample.x * sample.x - sample.y * sample.y); - const float zStar = sMRT2.SampleLevel(g_samLinear, centerUV + sampleUV, 0).z; - - F += zExit - zEntry; - - if (zExit <= zStar && zStar <= zEntry) - V += zStar - zEntry; - else //if (zStar < zExit) - V += zExit - zEntry; - } - - float accessibility = V / F; - return float4(accessibility.xxx, 1); - -} diff --git a/Samples/Media/materials/scripts/SSAO/Volumetric.material b/Samples/Media/materials/scripts/SSAO/Volumetric.material deleted file mode 100644 index f6d481ffa91..00000000000 --- a/Samples/Media/materials/scripts/SSAO/Volumetric.material +++ /dev/null @@ -1,76 +0,0 @@ -fragment_program SSAO/Volumetric_fp_hlsl hlsl -{ - source Volumetric.hlsl - entry_point Volumetric_fp - target ps_4_0 -} - -fragment_program SSAO/Volumetric_fp_cg cg -{ - source Volumetric.cg - entry_point Volumetric_fp - profiles arbfp1 ps_3_0 -} - -fragment_program SSAO/Volumetric_fp_glsl glsl -{ - source VolumetricFP.glsl - - default_params - { - param_named sMRT1 int 0 - param_named sMRT2 int 1 - param_named sRand int 2 - } -} - -fragment_program SSAO/Volumetric_fp unified -{ - delegate SSAO/Volumetric_fp_glsl - delegate SSAO/Volumetric_fp_hlsl - delegate SSAO/Volumetric_fp_cg -} - - -material SSAO/Volumetric -{ - technique - { - pass - { - depth_check off - - vertex_program_ref Ogre/Compositor/StdQuad_vp {} - fragment_program_ref SSAO/Volumetric_fp - { - param_named_auto cViewportSize viewport_size - param_named_auto cFov fov - - param_named cSampleInScreenspace float 0 - param_named cSampleLengthScreenSpace float 0.06 - param_named cSampleLengthWorldSpace float 2 - } - - texture_unit // normals - { - content_type compositor SSAO/GBuffer mrt 0 - tex_address_mode clamp - filtering none - } - - texture_unit // view space position - { - content_type compositor SSAO/GBuffer mrt 1 - tex_address_mode clamp - filtering none - } - - texture_unit - { - texture 4InterleavedKMeansDisk8x4.png - tex_address_mode wrap - filtering none - } - } - } -} diff --git a/Samples/Media/materials/scripts/SSAO/VolumetricFP.glsl b/Samples/Media/materials/scripts/SSAO/VolumetricFP.glsl deleted file mode 100644 index 85d891671f0..00000000000 --- a/Samples/Media/materials/scripts/SSAO/VolumetricFP.glsl +++ /dev/null @@ -1,80 +0,0 @@ -#version 120 -varying vec2 oUv0; - -uniform sampler2D sMRT1; // fragment normals -uniform sampler2D sMRT2; // view space position, remember that we are looking down the negative Z axis!!! -uniform sampler2D sRand; - -uniform vec4 cViewportSize; // (viewport_width, viewport_height, inverse_viewport_width, inverse_viewport_height) -uniform float cFov; // vertical field of view in radians -uniform float cSampleInScreenspace; // whether to sample in screen or world space -uniform float cSampleLengthScreenSpace; // The sample length in screen space [0, 1] -uniform float cSampleLengthWorldSpace; // the sample length in world space in units - -void main() -{ - const int interleaved = 4; - const int m = 8; - const int n = 4; - const int numSamples = m * n; - - vec2 interleaveOffset = oUv0 * cViewportSize.xy / interleaved; - - vec3 fragmentPosition = texture2D(sMRT2, oUv0).xyz; // the current fragment in view space - vec3 fragmentNormal = texture2D(sMRT1, oUv0).xyz * vec3(1, -1, 1); // the fragment normal - - float rUV = 0; // radius of influence in screen space - float r = 0; // radius of influence in world space - if (cSampleInScreenspace == 1) - { - rUV = cSampleLengthScreenSpace; - r = tan(rUV * cFov) * -fragmentPosition.z; - } - else - { - rUV = atan(cSampleLengthWorldSpace / -fragmentPosition.z) / cFov; // the radius of influence projected into screen space - r = cSampleLengthWorldSpace; - } - - - if (rUV < (cViewportSize.z)) // abort if the projected radius of influence is smaller than 1 fragment - { - gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0); - return; - } - - float r2 = r/2; - float rUV2 = rUV /2; - - vec3 center = fragmentPosition + fragmentNormal * (r2); - vec2 centerUV = oUv0 + (fragmentNormal * (rUV2)).xy; - - float F = 0; // unoccluded Volume - float V = 0; // occluded Volume - float invalid = 0; - - for (float i = 0.0f; i < m; i++) - for (float j = 0.0f; j < n; j++) - { - vec2 randomTC = interleaveOffset + vec2(i/(interleaved * m), j/(interleaved * n)); - vec2 randomVector = (texture2D(sRand, randomTC) * 2 - 1).xy; // unpack to [-1, 1]^2 - - vec2 sample = randomVector * (r2); - vec2 sampleUV = randomVector * (rUV2); - - float zEntry = center.z + (r2) * sqrt(1 - sample.x * sample.x - sample.y * sample.y); - float zExit = center.z - (r2) * sqrt(1 - sample.x * sample.x - sample.y * sample.y); - float zStar = texture2D(sMRT2, centerUV + sampleUV).z; - - F += zExit - zEntry; - - if (zExit <= zStar && zStar <= zEntry) - V += zStar - zEntry; - else //if (zStar < zExit) - V += zExit - zEntry; - } - - float accessibility = V / F; - gl_FragColor = vec4(accessibility, accessibility, accessibility, 1.0); - -} diff --git a/Samples/Media/materials/scripts/ShaderInstancing.material b/Samples/Media/materials/scripts/ShaderInstancing.material deleted file mode 100644 index 9c20543e5ff..00000000000 --- a/Samples/Media/materials/scripts/ShaderInstancing.material +++ /dev/null @@ -1,119 +0,0 @@ -//--------------------------------------------------------------------------- -//These materials/shaders are part of the NEW InstanceManager implementation -//Written by Matias N. Goldberg ("dark_sylinc") -//--------------------------------------------------------------------------- - -material Examples/Instancing/ShaderBased/shadow_caster -{ - technique - { - pass - { - rtshader_system - { - lighting_stage gbuffer depth - hardware_skinning 70 1 linear - } - } - } -} - -material Examples/Instancing/ShaderBased/shadow_caster_dq -{ - technique - { - pass - { - rtshader_system - { - lighting_stage gbuffer depth - hardware_skinning 80 1 dual_quaternion true false - } - } - } -} - -material Examples/Instancing/ShaderBased/shadow_caster_dq_two_weights -{ - technique - { - pass - { - rtshader_system - { - lighting_stage gbuffer depth - hardware_skinning 80 2 dual_quaternion true false - } - } - } -} - -material Examples/Instancing/RTSS/Robot -{ - technique - { - shadow_caster_material Examples/Instancing/ShaderBased/shadow_caster - - pass - { - specular 1 1 1 1 12.5 - - texture_unit - { - texture r2skin.jpg - } - - rtshader_system - { - hardware_skinning 70 1 linear - } - } - } -} - -material Examples/Instancing/RTSS/Robot_dq -{ - technique - { - shadow_caster_material Examples/Instancing/ShaderBased/shadow_caster_dq - - pass - { - specular 1 1 1 1 12.5 - - texture_unit - { - texture r2skin.jpg - } - - rtshader_system - { - hardware_skinning 80 1 dual_quaternion true false - } - } - } -} - -material Examples/Instancing/RTSS/spine_dq_two_weights -{ - technique - { - shadow_caster_material Examples/Instancing/ShaderBased/shadow_caster_dq_two_weights - - pass - { - diffuse 0.3 0.3 0.3 - specular 0.1 0.1 0.1 0.1 12.5 - - texture_unit - { - texture circuit.dds - } - - rtshader_system - { - hardware_skinning 80 2 dual_quaternion true false - } - } - } -} diff --git a/Samples/Media/materials/scripts/ShaderSystem.material b/Samples/Media/materials/scripts/ShaderSystem.material deleted file mode 100644 index a164e08c489..00000000000 --- a/Samples/Media/materials/scripts/ShaderSystem.material +++ /dev/null @@ -1,20 +0,0 @@ - -material Panels -{ - technique - { - pass - { - specular 0.64 0.64 0.64 32 0 - - texture_unit - { - texture Panels_Diffuse.png - } - } - - } - -} - - diff --git a/Samples/Media/materials/scripts/SharpenEdges.material b/Samples/Media/materials/scripts/SharpenEdges.material deleted file mode 100644 index 665464ffc79..00000000000 --- a/Samples/Media/materials/scripts/SharpenEdges.material +++ /dev/null @@ -1,51 +0,0 @@ -fragment_program Ogre/Compositor/SharpenEdgesFP_hlsl hlsl -{ - source SharpenEdgesFP.cg - entry_point sharpenEdges_fp -} - -fragment_program Ogre/Compositor/SharpenEdgesFP_glsl glsl glsles -{ - source SharpenEdgesFP.glsl -} - -fragment_program Ogre/Compositor/SharpenEdgesFP unified -{ - delegate Ogre/Compositor/SharpenEdgesFP_hlsl - delegate Ogre/Compositor/SharpenEdgesFP_glsl - - default_params - { - param_named_auto vTexelSize inverse_texture_size 0 - } -} - -material Ogre/Compositor/SharpenEdges -{ - technique - { - - pass - { - cull_hardware none - depth_func always_pass - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_Tex2a_vp - { - } - - fragment_program_ref Ogre/Compositor/SharpenEdgesFP - { - } - - texture_unit - { - tex_coord_set 0 - tex_address_mode clamp - filtering trilinear - } - - } - } -} diff --git a/Samples/Media/materials/scripts/StdQuad_vp.program b/Samples/Media/materials/scripts/StdQuad_vp.program deleted file mode 100644 index 5f5faa0d0d5..00000000000 --- a/Samples/Media/materials/scripts/StdQuad_vp.program +++ /dev/null @@ -1,176 +0,0 @@ -vertex_program Ogre/Compositor/StdQuad_Cg_vp cg -{ - source StdQuad_vp.cg - entry_point StdQuad_vp - profiles vs_4_0 vs_4_0_level_9_1 vs_4_0_level_9_3 vs_2_0 vs_1_1 arbvp1 - - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -vertex_program Ogre/Compositor/StdQuad_Tex2a_Cg_vp cg -{ - source StdQuad_vp.cg - entry_point StdQuad_Tex2a_vp - profiles vs_4_0 vs_4_0_level_9_1 vs_4_0_level_9_3 vs_2_0 vs_1_1 arbvp1 - - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -vertex_program Ogre/Compositor/StdQuad_Tex3_Cg_vp cg -{ - source StdQuad_vp.cg - entry_point StdQuad_Tex3_vp - profiles vs_4_0 vs_4_0_level_9_1 vs_4_0_level_9_3 vs_2_0 vs_1_1 arbvp1 - - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -vertex_program Ogre/Compositor/StdQuad_Tex4_Cg_vp cg -{ - source StdQuad_vp.cg - entry_point StdQuad_Tex4_vp - profiles vs_4_0 vs_4_0_level_9_1 vs_4_0_level_9_3 vs_2_0 vs_1_1 arbvp1 - - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -vertex_program Ogre/Compositor/StdQuad_GLSL_vp glsl glsles -{ - source StdQuad_vp.glsl - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -vertex_program Ogre/Compositor/StdQuad_Tex2_vp glsl glsles glslang hlsl -{ - source StdQuad_Tex2_vp.glsl - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -vertex_program Ogre/Compositor/StdQuad_Tex2a_GLSL_vp glsl glsles -{ - source StdQuad_Tex2a_vp.glsl - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -vertex_program Ogre/Compositor/StdQuad_Tex3_GLSL_vp glsl glsles -{ - source StdQuad_Tex3_vp.glsl - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -vertex_program Ogre/Compositor/StdQuad_Tex4_GLSL_vp glsl glsles -{ - source StdQuad_Tex4_vp.glsl - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -vertex_program Ogre/Compositor/StdQuad_HLSL_vp hlsl -{ - source StdQuad_vp.cg - entry_point StdQuad_vp - target vs_1_1 vs_2_0 - - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -vertex_program Ogre/Compositor/StdQuad_Tex2a_HLSL_vp hlsl -{ - source StdQuad_vp.cg - entry_point StdQuad_Tex2a_vp - target vs_1_1 vs_2_0 - - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -vertex_program Ogre/Compositor/StdQuad_Tex3_HLSL_vp hlsl -{ - source StdQuad_vp.cg - entry_point StdQuad_Tex3_vp - target vs_1_1 vs_2_0 - - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -vertex_program Ogre/Compositor/StdQuad_Tex4_HLSL_vp hlsl -{ - source StdQuad_vp.cg - entry_point StdQuad_Tex4_vp - target vs_1_1 vs_2_0 - - default_params - { - param_named_auto worldViewProj worldviewproj_matrix - } -} - -// Unified definitions -vertex_program Ogre/Compositor/StdQuad_vp unified -{ - delegate Ogre/Compositor/StdQuad_HLSL_vp - delegate Ogre/Compositor/StdQuad_GLSL_vp - delegate Ogre/Compositor/StdQuad_Cg_vp -} - -vertex_program Ogre/Compositor/StdQuad_NoCG_vp unified -{ - delegate Ogre/Compositor/StdQuad_HLSL_vp - delegate Ogre/Compositor/StdQuad_GLSL_vp -} - -vertex_program Ogre/Compositor/StdQuad_Tex2a_vp unified -{ - delegate Ogre/Compositor/StdQuad_Tex2a_GLSL_vp - delegate Ogre/Compositor/StdQuad_Tex2a_HLSL_vp - delegate Ogre/Compositor/StdQuad_Tex2a_Cg_vp -} - -vertex_program Ogre/Compositor/StdQuad_Tex3_vp unified -{ - delegate Ogre/Compositor/StdQuad_Tex3_GLSL_vp - delegate Ogre/Compositor/StdQuad_Tex3_HLSL_vp - delegate Ogre/Compositor/StdQuad_Tex3_Cg_vp -} - -vertex_program Ogre/Compositor/StdQuad_Tex4_vp unified -{ - delegate Ogre/Compositor/StdQuad_Tex4_GLSL_vp - delegate Ogre/Compositor/StdQuad_Tex4_HLSL_vp - delegate Ogre/Compositor/StdQuad_Tex4_Cg_vp -} - diff --git a/Samples/Media/materials/scripts/SteepParallaxOcclusionMapping.material b/Samples/Media/materials/scripts/SteepParallaxOcclusionMapping.material deleted file mode 100644 index 60ee6113b93..00000000000 --- a/Samples/Media/materials/scripts/SteepParallaxOcclusionMapping.material +++ /dev/null @@ -1,26 +0,0 @@ -// Steep parallax occlusion mapping -material RTSS/ParallaxOcclusionMapping -{ - technique - { - pass - { - specular 1 1 1 32 - - // Base diffuse texture map - texture_unit - { - texture Bricks076C_diffspec.dds - } - - texture_unit - { - texture Bricks076C_normheight.dds - rtshader_system - { - normal_map parallax_occlusion - } - } - } - } -} \ No newline at end of file diff --git a/Samples/Media/materials/scripts/Swizzle.material b/Samples/Media/materials/scripts/Swizzle.material deleted file mode 100644 index e67eafbf9a7..00000000000 --- a/Samples/Media/materials/scripts/Swizzle.material +++ /dev/null @@ -1,101 +0,0 @@ -// asm -//FIXME Replace with HLSL. -// geometry_program Ogre/GPTest/Swizzle/GP_ASM asm -// { -// source Swizzle.gp -// syntax nvgp4 -// } - - -// CG -//TODO Finish me. - -// geometry_program Ogre/GPTest/Swizzle/GP_CG cg -// { -// source SwizzleGP.cg -// entry_point gs_swizzle -// profiles gp4gp gpu_gp -// } - -// GLSL 120 -vertex_program Ogre/GPTest/Swizzle/VP_GLSL_120 glsl -{ - source PassthroughVP.glsl - syntax glsl -} - -geometry_program Ogre/GPTest/Swizzle/GP_GLSL_120 glsl -{ - source SwizzleGP.glsl - syntax glsl - input_operation_type triangle_list - output_operation_type line_strip - max_output_vertices 6 -} - - -fragment_program Ogre/GPTest/Swizzle/FP_GLSL_120 glsl -{ - source PassthroughFP.glsl - syntax glsl -} - -geometry_program Ogre/GPTest/Swizzle/GP_GLSL_150 glsl -{ - source SwizzleGP.glsl - syntax glsl150 - preprocessor_defines USE_LAYOUT -} - -// unified -vertex_program Ogre/GPTest/Swizzle/VP unified -{ - delegate Ogre/GPTest/Swizzle/VP_GLSL_120 - - default_params - { - param_named_auto WorldViewProj worldviewproj_matrix - } -} - -geometry_program Ogre/GPTest/Swizzle/GP unified -{ - delegate Ogre/GPTest/Swizzle/GP_GLSL_150 - delegate Ogre/GPTest/Swizzle/GP_GLSL_120 - - default_params - { - param_named origColour float4 1 0 0 1 - param_named cloneColour float4 1 1 1 0.3 - } -} - -fragment_program Ogre/GPTest/Swizzle/FP unified -{ - delegate Ogre/GPTest/Swizzle/FP_GLSL_120 -} - - -material Ogre/GPTest/Swizzle -{ - technique - { - pass - { - vertex_program_ref Ogre/GPTest/Swizzle/VP - { - - } - - geometry_program_ref Ogre/GPTest/Swizzle/GP - { - - } - - fragment_program_ref Ogre/GPTest/Swizzle/FP - { - - } - } - } -} diff --git a/Samples/Media/materials/scripts/TerrainTessellation.material b/Samples/Media/materials/scripts/TerrainTessellation.material deleted file mode 100644 index d52be67bc28..00000000000 --- a/Samples/Media/materials/scripts/TerrainTessellation.material +++ /dev/null @@ -1,223 +0,0 @@ -/* ----------------------------------------------------------- -Terrain Tessellation sample from NVIDIA's DirectX 11 SDK: -http://developer.nvidia.com/nvidia-graphics-sdk-11-direct3d ----------------------------------------------------------- -*/ - -vertex_program Ogre/TerrainTessellation/InitializationVS hlsl -{ - source TerrainTessellationDeformation.hlsl - entry_point InitializationVS - target vs_4_0 - - default_params - { - param_named g_DeformMin float3 0.0 0.0 0.0 - param_named g_DeformMax float3 1.0 1.0 1.0 - } -} - -fragment_program Ogre/TerrainTessellation/InitializationPS hlsl -{ - source TerrainTessellationDeformation.hlsl - entry_point InitializationPS - target ps_4_0 - - default_params - { - param_named g_FractalOctaves int3 0 0 0 - param_named g_TextureWorldOffset float3 0.0 0.0 0.0 - } -} - -fragment_program Ogre/TerrainTessellation/GradientPS hlsl -{ - source TerrainTessellationDeformation.hlsl - entry_point GradientPS - target ps_4_0 - - default_params - { - - } -} - - -material Ogre/TerrainTessellation/TerrainDeformation -{ - technique initialization - { - pass init - { - vertex_program_ref Ogre/TerrainTessellation/InitializationVS - { - - } - - fragment_program_ref Ogre/TerrainTessellation/InitializationPS - { - - } - depth_write off - cull_hardware none - } - - } - - technique gradienttech - { - pass gradient - { - vertex_program_ref Ogre/TerrainTessellation/InitializationVS - { - - } - - fragment_program_ref Ogre/TerrainTessellation/GradientPS - { - - } - depth_write off - cull_hardware none - } - } -} - -vertex_program Ogre/TerrainTessellation/HwTessellationPassThruVS hlsl -{ - source TerrainTessellation.hlsl - entry_point HwTessellationPassThruVS - target vs_5_0 - - default_params - { - param_named g_DebugShowTiles int 0 - param_named g_DetailNoiseScale float 5 - param_named g_tileSize float 5 - param_named g_DetailUVScale float2 0.0 0.0 - param_named g_TextureWorldOffset float3 0.0 0.0 0.0 - } -} - -vertex_program Ogre/TerrainTessellation/VTFDisplacementVS hlsl -{ - source TerrainTessellation.hlsl - entry_point VTFDisplacementVS - target vs_4_0 - - default_params - { - param_named_auto g_WorldViewProj worldviewproj_matrix - param_named g_DebugShowTiles int 0 - param_named g_DebugShowPatches int 0 - param_named g_DetailNoiseScale float 5 - param_named g_tileSize float 5 - param_named g_DetailUVScale float2 0.0 0.0 - param_named g_TextureWorldOffset float3 0.0 0.0 0.0 - } -} - -tessellation_hull_program Ogre/TerrainTessellation/TerrainScreenspaceLODHS hlsl -{ - source TerrainTessellation.hlsl - entry_point TerrainScreenspaceLODHS - target hs_5_0 - - default_params - { - param_named_auto g_WorldViewProj worldviewproj_matrix - param_named_auto g_WorldViewProjLOD worldviewproj_matrix - param_named_auto g_WorldViewLOD worldview_matrix - param_named_auto g_Proj projection_matrix - param_named_auto g_EyePos camera_position - param_named_auto g_ViewDir view_direction - } -} - -tessellation_domain_program Ogre/TerrainTessellation/TerrainDisplaceDS hlsl -{ - source TerrainTessellation.hlsl - entry_point TerrainDisplaceDS - target ds_5_0 - - default_params - { - param_named_auto g_WorldViewProj worldviewproj_matrix - param_named g_DebugShowPatches int 1 - param_named g_fDisplacementHeight float 5 - } -} - -fragment_program Ogre/TerrainTessellation/SmoothShadePS hlsl -{ - source TerrainTessellation.hlsl - entry_point SmoothShadePS - target ps_5_0 - - default_params - { - param_named g_CoarseSampleSpacing float 1.0 - } -} - -material Ogre/TerrainTessellation/Terrain -{ - technique - { - pass HwTessellated - { - vertex_program_ref Ogre/TerrainTessellation/HwTessellationPassThruVS - { - - } - - tessellation_hull_program_ref Ogre/TerrainTessellation/TerrainScreenspaceLODHS - { - - } - - tessellation_domain_program_ref Ogre/TerrainTessellation/TerrainDisplaceDS - { - - } - - fragment_program_ref Ogre/TerrainTessellation/SmoothShadePS - { - - } - - texture_unit - { - - } - - texture_unit - { - - } - } - pass ShadedTriStrip - { - vertex_program_ref Ogre/TerrainTessellation/VTFDisplacementVS - { - - } - - fragment_program_ref Ogre/TerrainTessellation/SmoothShadePS - { - - } - - texture_unit - { - - } - - texture_unit - { - - } - } - } -} diff --git a/Samples/Media/materials/scripts/Tessellation.material b/Samples/Media/materials/scripts/Tessellation.material deleted file mode 100644 index 1da07bc0e74..00000000000 --- a/Samples/Media/materials/scripts/Tessellation.material +++ /dev/null @@ -1,129 +0,0 @@ -vertex_program Ogre/Tessellation/VertexProgramHLSL hlsl -{ - source Tessellation.hlsl - entry_point VS - target vs_5_0 -} - -vertex_program Ogre/Tessellation/VertexProgramGLSL glsl -{ - source TessellationVp.glsl - syntax glsl400 -} - -vertex_program Ogre/Tessellation/VertexProgram unified -{ - delegate Ogre/Tessellation/VertexProgramHLSL - delegate Ogre/Tessellation/VertexProgramGLSL -} - -tessellation_hull_program Ogre/Tessellation/TessellationHullProgramHLSL hlsl -{ - source Tessellation.hlsl - entry_point HS - target hs_5_0 - - default_params - { - param_named g_fTessellationFactor float 16 - } -} - -tessellation_hull_program Ogre/Tessellation/TessellationHullProgramGLSL glsl -{ - source TessellationTh.glsl - syntax glsl400 - - default_params - { - param_named g_fTessellationFactor float 16 - } -} - -tessellation_hull_program Ogre/Tessellation/TessellationHullProgram unified -{ - delegate Ogre/Tessellation/TessellationHullProgramHLSL - delegate Ogre/Tessellation/TessellationHullProgramGLSL -} - -tessellation_domain_program Ogre/Tessellation/TessellationDomainProgramHLSL hlsl -{ - source Tessellation.hlsl - entry_point DS - target ds_5_0 - - default_params - { - param_named_auto g_mViewProjection worldviewproj_matrix - } -} - -tessellation_domain_program Ogre/Tessellation/TessellationDomainProgramGLSL glsl -{ - source TessellationTd.glsl - syntax glsl400 - - default_params - { - param_named_auto g_mWorldViewProjection worldviewproj_matrix - } -} - -tessellation_domain_program Ogre/Tessellation/TessellationDomainProgram unified -{ - delegate Ogre/Tessellation/TessellationDomainProgramHLSL - delegate Ogre/Tessellation/TessellationDomainProgramGLSL -} - -fragment_program Ogre/Tessellation/FragmentProgramHLSL hlsl -{ - source Tessellation.hlsl - entry_point SolidColorPS - target ps_5_0 -} - -fragment_program Ogre/Tessellation/FragmentProgramGLSL glsl -{ - source TessellationFp.glsl - syntax glsl400 -} - -fragment_program Ogre/Tessellation/FragmentProgram unified -{ - delegate Ogre/Tessellation/FragmentProgramHLSL - delegate Ogre/Tessellation/FragmentProgramGLSL -} - -material Ogre/TessellationExample -{ - technique - { - pass - { - lighting off - depth_write off - cull_hardware none - polygon_mode wireframe - - vertex_program_ref Ogre/Tessellation/VertexProgram - { - - } - - tessellation_hull_program_ref Ogre/Tessellation/TessellationHullProgram - { - - } - - tessellation_domain_program_ref Ogre/Tessellation/TessellationDomainProgram - { - - } - - fragment_program_ref Ogre/Tessellation/FragmentProgram - { - - } - } - } -} diff --git a/Samples/Media/materials/scripts/TextureAtlasSampleOrg.tai b/Samples/Media/materials/scripts/TextureAtlasSampleOrg.tai deleted file mode 100644 index ff74d83ee97..00000000000 --- a/Samples/Media/materials/scripts/TextureAtlasSampleOrg.tai +++ /dev/null @@ -1,36 +0,0 @@ -# TextureAtlasSampleOrg.tai -# AtlasCreationTool.exe -width 2048 -height 2048 -o TextureAtlasSampleOrg -# -# , , , , , , , -# -# Texture can be found in texture atlas , i.e., -# TextureAtlasSampleOrg.png of type with texture coordinates boundary given by: -# A = ( , ) -# B = ( + , + ) -# -# where coordinates (0,0) and (1,1) of the original texture map correspond -# to coordinates A and B, respectively, in the texture atlas. -# If the atlas is a volume texture then is the w-coordinate -# to use the access the appropriate slice in the volume atlas. - -ogrelogo-small.jpg TextureAtlasSampleOrg0.png, 0, 2D, 0.000000, 0.000000, 0.000000, 0.500000, 0.500000 -img2.png TextureAtlasSampleOrg0.png, 0, 2D, 0.500000, 0.000000, 0.000000, 0.250000, 0.500000 -radial.png TextureAtlasSampleOrg0.png, 0, 2D, 0.750000, 0.000000, 0.000000, 0.250000, 0.500000 -1d_SPIRAL.png TextureAtlasSampleOrg0.png, 0, 2D, 0.000000, 0.500000, 0.000000, 0.125000, 0.250000 -img1.png TextureAtlasSampleOrg0.png, 0, 2D, 0.125000, 0.500000, 0.000000, 0.125000, 0.250000 -Dirt.jpg TextureAtlasSampleOrg0.png, 0, 2D, 0.250000, 0.500000, 0.000000, 0.125000, 0.250000 -flare.png TextureAtlasSampleOrg0.png, 0, 2D, 0.375000, 0.500000, 0.000000, 0.125000, 0.250000 -rockwall.tga TextureAtlasSampleOrg0.png, 0, 2D, 0.500000, 0.500000, 0.000000, 0.125000, 0.250000 -steelhead.png TextureAtlasSampleOrg0.png, 0, 2D, 0.625000, 0.500000, 0.000000, 0.125000, 0.250000 -RustyBarrel.png TextureAtlasSampleOrg0.png, 0, 2D, 0.750000, 0.500000, 0.000000, 0.125000, 0.250000 -NMBalls.png TextureAtlasSampleOrg0.png, 0, 2D, 0.875000, 0.500000, 0.000000, 0.125000, 0.250000 -terr_dirt-grass.jpg TextureAtlasSampleOrg0.png, 0, 2D, 0.000000, 0.750000, 0.000000, 0.125000, 0.250000 -SmallLeaf_BP.png TextureAtlasSampleOrg0.png, 0, 2D, 0.125000, 0.750000, 0.000000, 0.062500, 0.250000 -1d_debug.png TextureAtlasSampleOrg0.png, 0, 2D, 0.187500, 0.750000, 0.000000, 0.062500, 0.125000 -checker.png TextureAtlasSampleOrg0.png, 0, 2D, 0.250000, 0.750000, 0.000000, 0.062500, 0.125000 -spotlight_image.png TextureAtlasSampleOrg0.png, 0, 2D, 0.312500, 0.750000, 0.000000, 0.062500, 0.125000 -nm_bk.png TextureAtlasSampleOrg0.png, 0, 2D, 0.375000, 0.750000, 0.000000, 0.062500, 0.125000 -dirt01.jpg TextureAtlasSampleOrg0.png, 0, 2D, 0.437500, 0.750000, 0.000000, 0.062500, 0.125000 -tusk.jpg TextureAtlasSampleOrg0.png, 0, 2D, 0.500000, 0.750000, 0.000000, 0.062500, 0.125000 -LowRes.png TextureAtlasSampleOrg0.png, 0, 2D, 0.562500, 0.750000, 0.000000, 0.015625, 0.031250 -scr-up-p.png TextureAtlasSampleOrg0.png, 0, 2D, 0.578125, 0.750000, 0.000000, 0.007813, 0.015625 diff --git a/Samples/Media/materials/scripts/TextureAtlasSampleWrap.tai b/Samples/Media/materials/scripts/TextureAtlasSampleWrap.tai deleted file mode 100644 index c5e319a7dbc..00000000000 --- a/Samples/Media/materials/scripts/TextureAtlasSampleWrap.tai +++ /dev/null @@ -1,36 +0,0 @@ -# TextureAtlasSampleWrap.tai -# AtlasCreationTool.exe -width 2048 -height 2048 -o TextureAtlasSampleWrap -# -# , , , , , , , -# -# Texture can be found in texture atlas , i.e., -# TextureAtlasSampleWrap.png of type with texture coordinates boundary given by: -# A = ( , ) -# B = ( + , + ) -# -# where coordinates (0,0) and (1,1) of the original texture map correspond -# to coordinates A and B, respectively, in the texture atlas. -# If the atlas is a volume texture then is the w-coordinate -# to use the access the appropriate slice in the volume atlas. - -ogrelogo-small.jpg TextureAtlasSampleWrap0.png, 0, 2D, 0.125000, 0.125000, 0.000000, 0.250000, 0.250000 -img2.png TextureAtlasSampleWrap0.png, 0, 2D, 0.562500, 0.125000, 0.000000, 0.125000, 0.250000 -radial.png TextureAtlasSampleWrap0.png, 0, 2D, 0.812500, 0.125000, 0.000000, 0.125000, 0.250000 -1d_SPIRAL.png TextureAtlasSampleWrap0.png, 0, 2D, 0.031250, 0.562500, 0.000000, 0.062500, 0.125000 -img1.png TextureAtlasSampleWrap0.png, 0, 2D, 0.156250, 0.562500, 0.000000, 0.062500, 0.125000 -Dirt.jpg TextureAtlasSampleWrap0.png, 0, 2D, 0.281250, 0.562500, 0.000000, 0.062500, 0.125000 -flare.png TextureAtlasSampleWrap0.png, 0, 2D, 0.406250, 0.562500, 0.000000, 0.062500, 0.125000 -rockwall.tga TextureAtlasSampleWrap0.png, 0, 2D, 0.531250, 0.562500, 0.000000, 0.062500, 0.125000 -steelhead.png TextureAtlasSampleWrap0.png, 0, 2D, 0.656250, 0.562500, 0.000000, 0.062500, 0.125000 -RustyBarrel.png TextureAtlasSampleWrap0.png, 0, 2D, 0.781250, 0.562500, 0.000000, 0.062500, 0.125000 -NMBalls.png TextureAtlasSampleWrap0.png, 0, 2D, 0.906250, 0.562500, 0.000000, 0.062500, 0.125000 -terr_dirt-grass.jpg TextureAtlasSampleWrap0.png, 0, 2D, 0.031250, 0.812500, 0.000000, 0.062500, 0.125000 -SmallLeaf_BP.png TextureAtlasSampleWrap0.png, 0, 2D, 0.140625, 0.812500, 0.000000, 0.031250, 0.125000 -1d_debug.png TextureAtlasSampleWrap0.png, 0, 2D, 0.203125, 0.781250, 0.000000, 0.031250, 0.062500 -checker.png TextureAtlasSampleWrap0.png, 0, 2D, 0.265625, 0.781250, 0.000000, 0.031250, 0.062500 -spotlight_image.png TextureAtlasSampleWrap0.png, 0, 2D, 0.328125, 0.781250, 0.000000, 0.031250, 0.062500 -nm_bk.png TextureAtlasSampleWrap0.png, 0, 2D, 0.390625, 0.781250, 0.000000, 0.031250, 0.062500 -dirt01.jpg TextureAtlasSampleWrap0.png, 0, 2D, 0.453125, 0.781250, 0.000000, 0.031250, 0.062500 -tusk.jpg TextureAtlasSampleWrap0.png, 0, 2D, 0.515625, 0.781250, 0.000000, 0.031250, 0.062500 -LowRes.png TextureAtlasSampleWrap0.png, 0, 2D, 0.566406, 0.757813, 0.000000, 0.007813, 0.015625 -scr-up-p.png TextureAtlasSampleWrap0.png, 0, 2D, 0.580078, 0.753906, 0.000000, 0.003906, 0.007813 diff --git a/Samples/Media/materials/scripts/Tiling.material b/Samples/Media/materials/scripts/Tiling.material deleted file mode 100644 index 695c248a8e3..00000000000 --- a/Samples/Media/materials/scripts/Tiling.material +++ /dev/null @@ -1,49 +0,0 @@ -fragment_program Ogre/Compositor/Tiling_Cg_FP hlsl -{ - source TilingFP.cg - entry_point Tiling_ps -} - -fragment_program Ogre/Compositor/Tiling_GLSL_FP glsl glsles -{ - source TilingFP.glsl -} - -fragment_program Ogre/Compositor/TilingFP unified -{ - delegate Ogre/Compositor/Tiling_GLSL_FP - delegate Ogre/Compositor/Tiling_Cg_FP -} - -material Ogre/Compositor/Tiling -{ - technique - { - - pass - { - cull_hardware none - depth_func always_pass - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_Tex2a_vp - { - } - - //DirectX 9.0 HLSL Pixel Shader ps_2_0 - fragment_program_ref Ogre/Compositor/TilingFP - { - param_named NumTiles float 75.0 - param_named Threshold float 0.15 - } - - texture_unit RT - { - tex_coord_set 0 - tex_address_mode clamp - filtering trilinear - } - - } - } -} diff --git a/Samples/Media/materials/scripts/VTFInstancing.material b/Samples/Media/materials/scripts/VTFInstancing.material deleted file mode 100644 index 7f95711eca7..00000000000 --- a/Samples/Media/materials/scripts/VTFInstancing.material +++ /dev/null @@ -1,426 +0,0 @@ -//--------------------------------------------------------------------------- -//These materials/shaders are part of the NEW InstanceManager implementation -//Written by Matias N. Goldberg ("dark_sylinc") -//--------------------------------------------------------------------------- - -//-------------------------------------------------------------- -// GLSL Programs -//-------------------------------------------------------------- -vertex_program Ogre/Instancing/VTF_glsl_vs glsl glsles -{ - source VTFInstancing.vert - - preprocessor_defines DEPTH_SHADOWRECEIVER=1 - - uses_vertex_texture_fetch true - - default_params - { - param_named matrixTexture int 2 - } -} - -vertex_program Ogre/Instancing/VTF/shadow_caster_glsl_vs glsl glsles -{ - source VTFInstancing.vert - - preprocessor_defines DEPTH_SHADOWCASTER=1 - - uses_vertex_texture_fetch true - - default_params - { - param_named matrixTexture int 0 - } -} - -vertex_program Ogre/Instancing/VTF_dq_glsl_vs glsl glsles -{ - source VTFInstancing.vert - - preprocessor_defines ST_DUAL_QUATERNION,DEPTH_SHADOWRECEIVER=1 - - uses_vertex_texture_fetch true - - default_params - { - param_named matrixTexture int 2 - } -} - -vertex_program Ogre/Instancing/VTF/shadow_caster_dq_glsl_vs glsl glsles -{ - source VTFInstancing.vert - - preprocessor_defines ST_DUAL_QUATERNION,DEPTH_SHADOWCASTER=1 - - uses_vertex_texture_fetch true - - default_params - { - param_named matrixTexture int 0 - } -} - -vertex_program Ogre/Instancing/VTF_dq_two_weights_glsl_vs glsl glsles -{ - source VTFInstancing.vert - - preprocessor_defines ST_DUAL_QUATERNION,BONE_TWO_WEIGHTS,DEPTH_SHADOWRECEIVER=1 - - uses_vertex_texture_fetch true - - default_params - { - param_named matrixTexture int 2 - } -} - -vertex_program Ogre/Instancing/VTF/shadow_caster_dq_two_weights_glsl_vs glsl glsles -{ - source VTFInstancing.vert - - preprocessor_defines ST_DUAL_QUATERNION,BONE_TWO_WEIGHTS,DEPTH_SHADOWCASTER=1 - - uses_vertex_texture_fetch true - - default_params - { - param_named matrixTexture int 0 - } -} - -//-------------------------------------------------------------- -// hlsl Programs -//-------------------------------------------------------------- -vertex_program Ogre/Instancing/VTF_hlsl_vs hlsl -{ - source VTFInstancing.cg - entry_point main_vs - target vs_3_0 - - preprocessor_defines DEPTH_SHADOWRECEIVER - - uses_vertex_texture_fetch true -} - -vertex_program Ogre/Instancing/VTF/shadow_caster_hlsl_vs hlsl -{ - source VTFInstancing.cg - entry_point main_vs - target vs_3_0 - - preprocessor_defines DEPTH_SHADOWCASTER - - uses_vertex_texture_fetch true -} - -vertex_program Ogre/Instancing/VTF_dq_hlsl_vs hlsl -{ - source VTFInstancing.cg - entry_point main_vs - target vs_3_0 - - preprocessor_defines DEPTH_SHADOWRECEIVER,ST_DUAL_QUATERNION - - uses_vertex_texture_fetch true -} - -vertex_program Ogre/Instancing/VTF/shadow_caster_dq_hlsl_vs hlsl -{ - source VTFInstancing.cg - entry_point main_vs - target vs_3_0 - - preprocessor_defines DEPTH_SHADOWCASTER,ST_DUAL_QUATERNION - - uses_vertex_texture_fetch true -} - -vertex_program Ogre/Instancing/VTF_dq_two_weights_hlsl_vs hlsl -{ - source VTFInstancing.cg - entry_point main_vs - target vs_3_0 - - preprocessor_defines DEPTH_SHADOWRECEIVER,ST_DUAL_QUATERNION,BONE_TWO_WEIGHTS - - uses_vertex_texture_fetch true -} - -vertex_program Ogre/Instancing/VTF/shadow_caster_dq_two_weights_hlsl_vs hlsl -{ - source VTFInstancing.cg - entry_point main_vs - target vs_3_0 - - preprocessor_defines DEPTH_SHADOWCASTER,ST_DUAL_QUATERNION,BONE_TWO_WEIGHTS - - uses_vertex_texture_fetch true -} - -//-------------------------------------------------------------- -// Unified CG/GLSL Programs -//-------------------------------------------------------------- -vertex_program Ogre/Instancing/VTF_vs unified -{ - delegate Ogre/Instancing/VTF_glsl_vs - delegate Ogre/Instancing/VTF_hlsl_vs - - default_params - { - param_named_auto viewProjMatrix viewproj_matrix - - param_named_auto texViewProjMatrix texture_viewproj_matrix 0 - } -} - -vertex_program Ogre/Instancing/VTF/shadow_caster_vs unified -{ - delegate Ogre/Instancing/VTF/shadow_caster_glsl_vs - delegate Ogre/Instancing/VTF/shadow_caster_hlsl_vs - - default_params - { - param_named_auto viewProjMatrix viewproj_matrix - } -} - -vertex_program Ogre/Instancing/VTF_dq_vs unified -{ - delegate Ogre/Instancing/VTF_dq_glsl_vs - delegate Ogre/Instancing/VTF_dq_hlsl_vs - - default_params - { - param_named_auto viewProjMatrix viewproj_matrix - - param_named_auto texViewProjMatrix texture_viewproj_matrix 0 - } -} - -vertex_program Ogre/Instancing/VTF/shadow_caster_dq_vs unified -{ - delegate Ogre/Instancing/VTF/shadow_caster_dq_glsl_vs - delegate Ogre/Instancing/VTF/shadow_caster_dq_hlsl_vs - - default_params - { - param_named_auto viewProjMatrix viewproj_matrix - } -} - -vertex_program Ogre/Instancing/VTF_dq_two_weights_vs unified -{ - delegate Ogre/Instancing/VTF_dq_two_weights_glsl_vs - delegate Ogre/Instancing/VTF_dq_two_weights_hlsl_vs - - default_params - { - param_named_auto viewProjMatrix viewproj_matrix - - param_named_auto texViewProjMatrix texture_viewproj_matrix 0 - } -} - -vertex_program Ogre/Instancing/VTF/shadow_caster_dq_two_weights_vs unified -{ - delegate Ogre/Instancing/VTF/shadow_caster_dq_two_weights_glsl_vs - delegate Ogre/Instancing/VTF/shadow_caster_dq_two_weights_hlsl_vs - - default_params - { - param_named_auto viewProjMatrix viewproj_matrix - } -} - -material Examples/Instancing/VTF/shadow_caster -{ - technique - { - pass - { - vertex_program_ref Ogre/Instancing/VTF/shadow_caster_vs - { - } - fragment_program_ref Ogre/Instancing/shadow_caster_ps - { - } - - texture_unit InstancingVTF - { - filtering none - } - } - } -} - -material Examples/Instancing/VTF/shadow_caster_dq -{ - technique - { - pass - { - vertex_program_ref Ogre/Instancing/VTF/shadow_caster_dq_vs - { - } - fragment_program_ref Ogre/Instancing/shadow_caster_ps - { - } - - texture_unit InstancingVTF - { - filtering none - } - } - } -} - -material Examples/Instancing/VTF/shadow_caster_dq_two_weights -{ - technique - { - pass - { - vertex_program_ref Ogre/Instancing/VTF/shadow_caster_dq_two_weights_vs - { - } - fragment_program_ref Ogre/Instancing/shadow_caster_ps - { - } - - texture_unit InstancingVTF - { - filtering none - } - } - } -} - -abstract material Examples/Instancing/VTF -{ - technique - { - shadow_caster_material Examples/Instancing/VTF/shadow_caster - - pass - { - specular 1 1 1 1 12.5 - vertex_program_ref Ogre/Instancing/VTF_vs - { - } - - fragment_program_ref Ogre/Instancing_ps - { - } - - texture_unit Diffuse - { - texture $DiffuseMap - } - - texture_unit shadow0 - { - content_type shadow - tex_address_mode border - tex_border_colour 1 1 1 1 - } - - texture_unit InstancingVTF - { - filtering none - } - } - } -} - -abstract material Examples/Instancing/VTF_dq -{ - technique - { - shadow_caster_material Examples/Instancing/VTF/shadow_caster_dq - - pass - { - specular 1 1 1 1 12.5 - vertex_program_ref Ogre/Instancing/VTF_dq_vs - { - } - - fragment_program_ref Ogre/Instancing_ps - { - } - - texture_unit Diffuse - { - texture $DiffuseMap - } - - texture_unit shadow0 - { - content_type shadow - tex_address_mode border - tex_border_colour 1 1 1 1 - } - - texture_unit InstancingVTF - { - filtering none - } - } - } -} - -abstract material Examples/Instancing/VTF_dq_two_weights -{ - technique - { - shadow_caster_material Examples/Instancing/VTF/shadow_caster_dq_two_weights - - pass - { - diffuse 0.3 0.3 0.3 - specular 0.1 0.1 0.1 0.1 12.5 - vertex_program_ref Ogre/Instancing/VTF_dq_two_weights_vs - { - } - - fragment_program_ref Ogre/Instancing_ps - { - } - - texture_unit Diffuse - { - texture $DiffuseMap - tex_address_mode clamp - } - - texture_unit shadow0 - { - content_type shadow - tex_address_mode border - tex_border_colour 1 1 1 1 - } - - texture_unit InstancingVTF - { - filtering none - } - } - } -} - -material Examples/Instancing/VTF/Robot : Examples/Instancing/VTF -{ - set $DiffuseMap r2skin.jpg -} - -material Examples/Instancing/VTF/Robot_dq : Examples/Instancing/VTF_dq -{ - set $DiffuseMap r2skin.jpg -} - -material Examples/Instancing/VTF/spine_dq_two_weights : Examples/Instancing/VTF_dq_two_weights -{ - set $DiffuseMap circuit.dds -} diff --git a/Samples/Media/materials/scripts/VarianceShadowmap.material b/Samples/Media/materials/scripts/VarianceShadowmap.material deleted file mode 100644 index 16d9e594567..00000000000 --- a/Samples/Media/materials/scripts/VarianceShadowmap.material +++ /dev/null @@ -1,103 +0,0 @@ - -// Shadow Caster __________________________________________________ - - -vertex_program VarianceShadowMapping/ShadowCasterVP cg -{ - source varianceshadowcastervp.cg - entry_point main - profiles arbvp1 vs_2_x - - default_params - { - param_named_auto uModelViewProjection worldviewproj_matrix - } -} - -fragment_program VarianceShadowMapping/ShadowCasterFP cg -{ - source varianceshadowcasterfp.cg - entry_point main - profiles arbfp1 ps_2_x - - default_params - { - param_named uDepthOffset float 1.0 - param_named_auto uProjection projection_matrix - } -} - -material VarianceShadowMapping/ShadowCaster -{ - technique default - { - // Z-write only pass - pass Z-write - { - //Instead of using depth_bias, we'll be implementing it manually - - vertex_program_ref VarianceShadowMapping/ShadowCasterVP - { - } - fragment_program_ref VarianceShadowMapping/ShadowCasterFP - { - } - } - } -} - - - -// Shadow Receiver ________________________________________________ - -vertex_program VarianceShadowMapping/ShadowReceiverVP cg -{ - source varianceshadowreceivervp.cg - entry_point main - profiles arbvp1 vs_2_x - - default_params - { - param_named_auto uModelViewProjection worldviewproj_matrix - param_named_auto uLightPosition light_position_object_space 0 - param_named_auto uModel world_matrix - param_named_auto uTextureViewProjection texture_viewproj_matrix - } -} - -fragment_program VarianceShadowMapping/ShadowReceiverFP cg -{ - source varianceshadowreceiverfp.cg - entry_point main - profiles arbfp1 ps_2_x - - default_params - { - param_named uSTexWidth float 512.0 - param_named uSTexHeight float 512.0 - } -} - -material VarianceShadowMapping/ShadowReceiver -{ - technique default - { - pass lighting - { - vertex_program_ref VarianceShadowMapping/ShadowReceiverVP - { - } - - fragment_program_ref VarianceShadowMapping/ShadowReceiverFP - { - } - - // we won't rely on hardware specific filtering of z-tests - texture_unit ShadowMap - { - tex_address_mode clamp - filtering none - } - } - } -} diff --git a/Samples/Media/materials/scripts/WBOIT.material b/Samples/Media/materials/scripts/WBOIT.material deleted file mode 100644 index 18927dc9b2b..00000000000 --- a/Samples/Media/materials/scripts/WBOIT.material +++ /dev/null @@ -1,54 +0,0 @@ -material Compositor/Copy -{ - technique - { - pass - { - lighting off - texture_unit - { - filtering bilinear - tex_address_mode clamp - } - } - } -} - -fragment_program Compositor/wboitFP glsl glsles hlsl -{ - source wboit.frag - default_params - { - param_named accumTexture int 0 - param_named revealageTexture int 1 - } -} - -material Compositor/WBOIT -{ - technique - { - pass - { - scene_blend add - // for correct alpha blending: - //scene_blend one_minus_src_alpha src_alpha - vertex_program_ref Ogre/Compositor/StdQuad_vp - { - } - fragment_program_ref Compositor/wboitFP - { - } - texture_unit - { - filtering none - tex_address_mode clamp - } - texture_unit - { - filtering none - tex_address_mode clamp - } - } - } -} \ No newline at end of file diff --git a/Samples/Media/materials/scripts/facial.material b/Samples/Media/materials/scripts/facial.material deleted file mode 100644 index 6a481980d99..00000000000 --- a/Samples/Media/materials/scripts/facial.material +++ /dev/null @@ -1,98 +0,0 @@ - -material drbunsen_head -{ - technique - { - pass - { - ambient 0.25 0.25 0.25 - diffuse 1.0 1.0 1.0 - - texture_unit - { - texture Dr_Bunsen_Head.jpg - } - } - } -} - -material drbunsen_eye -{ - technique - { - pass - { - ambient 0.25 0.25 0.25 - diffuse 1.0 1.0 1.0 - - } - } -} - -material drbunsen_teeth -{ - technique - { - pass - { - ambient 0.25 0.25 0.25 - diffuse 1.0 1.0 1.0 - - } - } -} - -material drbunsen_tongue -{ - technique - { - pass - { - ambient 0.25 0.25 0.25 - diffuse 1.0 0.1 0.1 - - } - } -} - -material drbunsen_gums -{ - technique - { - pass - { - ambient 0.25 0.25 0.25 - diffuse 1.0 0.1 0.1 - - } - } -} - -material drbunsen_glasses -{ - technique - { - pass - { - depth_write off - scene_blend modulate - ambient 0.25 0.25 0.25 - diffuse 0.75 0.75 0.75 - - } - } -} - -material drbunsen_glasses_frame -{ - technique - { - pass - { - ambient 0.25 0.25 0.25 - diffuse 0.35 0.18 0 1 - - } - } -} - diff --git a/Samples/Media/materials/scripts/hdr.material b/Samples/Media/materials/scripts/hdr.material deleted file mode 100644 index 41dff75d4d7..00000000000 --- a/Samples/Media/materials/scripts/hdr.material +++ /dev/null @@ -1,315 +0,0 @@ -// Downsample a 2x2 area & turn into luminence (unclamped) -fragment_program Ogre/Compositor/HDR/downscale2x2LuminenceHLSL_fp hlsl -{ - source hdr.hlsl - entry_point downscale2x2Luminence - target ps_2_0 -} - -fragment_program Ogre/Compositor/HDR/downscale2x2LuminenceHLSL_fp4 hlsl -{ - source hdrfp4.hlsl - entry_point downscale2x2Luminencefp4 - target ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 -} - -fragment_program Ogre/Compositor/HDR/downscale2x2LuminenceGLSL_fp glsl glsles -{ - source hdr_downscale2x2luminence.glsl - default_params - { - param_named inRTT int 0 - } -} - -fragment_program Ogre/Compositor/HDR/downscale2x2Luminence_fp unified -{ - delegate Ogre/Compositor/HDR/downscale2x2LuminenceHLSL_fp4 - delegate Ogre/Compositor/HDR/downscale2x2LuminenceGLSL_fp - delegate Ogre/Compositor/HDR/downscale2x2LuminenceHLSL_fp - default_params - { - param_named_auto texelSize inverse_texture_size 0 - } -} - -material Ogre/Compositor/HDR/Downsample2x2Luminence -{ - technique - { - pass - { - cull_hardware none - depth_check off - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_NoCG_vp - { - } - fragment_program_ref Ogre/Compositor/HDR/downscale2x2Luminence_fp - { - } - - texture_unit - { - tex_coord_set 0 - tex_address_mode clamp - filtering none - } - } - } -} - -// Downsample a 3x3 area -fragment_program Ogre/Compositor/HDR/downscale3x3HLSL_fp hlsl -{ - source hdr.hlsl - entry_point downscale3x3 - target ps_2_0 -} -fragment_program Ogre/Compositor/HDR/downscale3x3HLSL_fp4 hlsl -{ - source hdrfp4.hlsl - entry_point downscale3x3fp4 - target ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 -} -fragment_program Ogre/Compositor/HDR/downscale3x3GLSL_fp glsl glsles -{ - source hdr_downscale3x3.glsl - default_params - { - param_named inRTT int 0 - } -} -fragment_program Ogre/Compositor/HDR/downscale3x3_fp unified -{ - delegate Ogre/Compositor/HDR/downscale3x3HLSL_fp4 - delegate Ogre/Compositor/HDR/downscale3x3GLSL_fp - delegate Ogre/Compositor/HDR/downscale3x3HLSL_fp - default_params - { - param_named_auto texelSize inverse_texture_size 0 - } -} - - -material Ogre/Compositor/HDR/Downsample3x3 -{ - technique - { - pass - { - cull_hardware none - depth_check off - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_NoCG_vp - { - } - fragment_program_ref Ogre/Compositor/HDR/downscale3x3_fp - { - } - - texture_unit - { - tex_coord_set 0 - tex_address_mode clamp - filtering none - } - } - } -} - -// Downsample a 3x3 area and perform a brightness filter pass -fragment_program Ogre/Compositor/HDR/downscale3x3brightpassHLSL_fp hlsl -{ - source hdr.hlsl - entry_point downscale3x3brightpass - target ps_2_0 -} -fragment_program Ogre/Compositor/HDR/downscale3x3brightpassHLSL_fp4 hlsl -{ - source hdrfp4.hlsl - entry_point downscale3x3brightpassfp4 - target ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 -} -fragment_program Ogre/Compositor/HDR/downscale3x3brightpassGLSL_fp glsl glsles -{ - source hdr_downscale3x3brightpass.glsl - default_params - { - param_named inRTT int 0 - param_named inLum int 1 - } -} -fragment_program Ogre/Compositor/HDR/downscale3x3brightpass_fp unified -{ - delegate Ogre/Compositor/HDR/downscale3x3brightpassHLSL_fp4 - delegate Ogre/Compositor/HDR/downscale3x3brightpassGLSL_fp - delegate Ogre/Compositor/HDR/downscale3x3brightpassHLSL_fp - default_params - { - param_named_auto texelSize inverse_texture_size 0 - } -} - - -material Ogre/Compositor/HDR/Downsample3x3Brightpass -{ - technique - { - pass - { - cull_hardware none - depth_check off - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_NoCG_vp - { - } - fragment_program_ref Ogre/Compositor/HDR/downscale3x3brightpass_fp - { - } - - // Scene - texture_unit - { - tex_coord_set 0 - tex_address_mode clamp - filtering none - } - // Luminence - texture_unit - { - tex_address_mode clamp - filtering none - } - } - } -} - -// Bloom an area using gaussian distribution -fragment_program Ogre/Compositor/HDR/bloomHLSL_fp hlsl -{ - source hdr.hlsl - entry_point bloom - target ps_2_0 -} -fragment_program Ogre/Compositor/HDR/bloomHLSL_fp4 hlsl -{ - source hdrfp4.hlsl - entry_point bloomfp4 - target ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 -} -fragment_program Ogre/Compositor/HDR/bloomGLSL_fp glsl glsles -{ - source hdr_bloom.glsl - default_params - { - param_named inRTT int 0 - } -} -fragment_program Ogre/Compositor/HDR/bloom_fp unified -{ - delegate Ogre/Compositor/HDR/bloomHLSL_fp4 - delegate Ogre/Compositor/HDR/bloomGLSL_fp - delegate Ogre/Compositor/HDR/bloomHLSL_fp -} - - -material Ogre/Compositor/HDR/GaussianBloom -{ - technique - { - pass - { - cull_hardware none - depth_check off - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_NoCG_vp - { - } - fragment_program_ref Ogre/Compositor/HDR/bloom_fp - { - } - - // Input - texture_unit - { - tex_coord_set 0 - tex_address_mode clamp - filtering none - } - } - } -} - - -// Perform final tone mapping -fragment_program Ogre/Compositor/HDR/finaltonemappingHLSL_fp hlsl -{ - source hdr.hlsl - entry_point finalToneMapping - target ps_2_0 -} -fragment_program Ogre/Compositor/HDR/finaltonemappingHLSL_fp4 hlsl -{ - source hdrfp4.hlsl - entry_point finalToneMappingfp4 - target ps_4_0 ps_4_0_level_9_1 ps_4_0_level_9_3 -} - -fragment_program Ogre/Compositor/HDR/finaltonemappingGLSL_fp glsl glsles -{ - source hdr_finalToneMapping.glsl - default_params - { - param_named inRTT int 0 - param_named inBloom int 1 - param_named inLum int 2 - } -} -fragment_program Ogre/Compositor/HDR/finaltonemapping_fp unified -{ - delegate Ogre/Compositor/HDR/finaltonemappingHLSL_fp4 - delegate Ogre/Compositor/HDR/finaltonemappingGLSL_fp - delegate Ogre/Compositor/HDR/finaltonemappingHLSL_fp -} - -material Ogre/Compositor/HDR/ToneMapping -{ - technique - { - pass - { - cull_hardware none - depth_check off - polygon_mode_overrideable false - - vertex_program_ref Ogre/Compositor/StdQuad_Tex2a_vp - { - } - fragment_program_ref Ogre/Compositor/HDR/finaltonemapping_fp - { - } - - // Scene - texture_unit - { - tex_coord_set 0 - tex_address_mode clamp - } - // Bloom - texture_unit - { - tex_address_mode clamp - } - // Luminence - texture_unit - { - tex_address_mode clamp - } - } - } -} diff --git a/Samples/Media/materials/scripts/pssm.material b/Samples/Media/materials/scripts/pssm.material deleted file mode 100644 index d32dffe8210..00000000000 --- a/Samples/Media/materials/scripts/pssm.material +++ /dev/null @@ -1,18 +0,0 @@ -material PSSM/shadow_caster -{ - technique - { - // all this will do is write depth - pass - { - fog_override true none - depth_bias -1 -1 - - rtshader_system - { - lighting_stage gbuffer depth - } - } - } -} - diff --git a/Samples/Media/materials/scripts/sibenik.material b/Samples/Media/materials/scripts/sibenik.material deleted file mode 100644 index 0f860c259cc..00000000000 --- a/Samples/Media/materials/scripts/sibenik.material +++ /dev/null @@ -1,305 +0,0 @@ - -material sibenik/Default -{ - technique - { - pass - { - ambient 0.698039 0.698039 0.698039 1 - diffuse 0.698039 0.698039 0.698039 1 - } - - } - -} - -material sibenik/poplocenje -{ - technique - { - pass - { - ambient 0 0 0 1 - diffuse 0.65098 0.647059 0.596078 1 - - texture_unit - { - texture KAMEN320x240.jpg - } - } - - } - -} - -material sibenik/kuce -{ - technique - { - pass - { - ambient 0 0 0 1 - diffuse 0.733333 0.729412 0.670588 1 - - texture_unit - { - texture KAMEN320x240.jpg - } - } - - } - -} - -material sibenik/staklo_zuto -{ - technique - { - pass - { - ambient 0 0 0 1 - diffuse 0.498039 0.443137 0.00392157 1.19 - } - - } - -} - -material sibenik/kamen_zid_prozor -{ - technique - { - pass - { - ambient 0 0 0 1 - diffuse 0.733333 0.729412 0.670588 1 - - texture_unit - { - texture KAMEN320x240.jpg - } - } - - } - -} - -material sibenik/pod-rub -{ - technique - { - pass - { - ambient 0 0 0 1 - diffuse 0.733333 0.729412 0.670588 1 - - texture_unit - { - texture KAMEN320x240.jpg - } - } - - } - -} - -material sibenik/staklo_plavo -{ - technique - { - pass - { - ambient 0 0 0 1 - diffuse 0.0392157 0.0705882 0.392157 1.19 - } - - } - -} - -material sibenik/staklo_crveno -{ - technique - { - pass - { - ambient 0 0 0 1 - diffuse 0.439216 0.101961 0.0470588 1.19 - } - - } - -} - -material sibenik/sprljci -{ - technique - { - pass - { - ambient 0 0 0 1 - diffuse 0.784314 0.784314 0.784314 1 - } - - } - -} - -material sibenik/staklo_zeleno -{ - technique - { - pass - { - ambient 0 0 0 1 - diffuse 0.0313726 0.313726 0.0352941 1.19 - } - - } - -} - -material sibenik/rozeta -{ - technique - { - pass - { - ambient 0 0 0 1 - diffuse 0.733333 0.729412 0.670588 1 - - texture_unit - { - texture KAMEN-stup.jpg - } - } - - } - -} - -material sibenik/kamen_zid_parape -{ - technique - { - pass - { - ambient 0 0 0 1 - diffuse 0.733333 0.729412 0.670588 1 - - texture_unit - { - texture KAMEN-stup.jpg - } - } - - } - -} - -material sibenik/zid_vani -{ - technique - { - pass - { - ambient 0 0 0 1 - diffuse 0.733333 0.729412 0.670588 1 - - texture_unit - { - texture KAMEN320x240.jpg - } - } - - } - -} - -material sibenik/glas -{ - technique - { - pass - { - ambient 0.639216 0.639216 0.639216 1 - diffuse 1 1 1 0.5 - scene_blend alpha_blend - depth_write off - } - - } - -} - -material sibenik/pod -{ - technique - { - pass - { - ambient 0 0 0 1 - diffuse 0.733333 0.705882 0.670588 1 - - texture_unit - { - texture MRAMOR6X6.jpg - } - } - - } - -} - -material sibenik/pod_tepih -{ - technique - { - pass - { - ambient 0 0 0 1 - diffuse 0.545098 0.219608 0.180392 1 - } - - } - -} - -material sibenik/stupovi -{ - technique - { - pass - { - ambient 0 0 0 1 - diffuse 0.733333 0.729412 0.670588 1 - - texture_unit - { - texture KAMEN-stup.jpg - } - } - - } - -} - -material sibenik/kamen_zid -{ - technique - { - pass - { - ambient 0.733333 0.729412 0.670588 1 - diffuse 0.733333 0.729412 0.670588 1 - cull_hardware none - - texture_unit - { - texture KAMEN320x240.jpg - } - } - - } - -} diff --git a/Samples/Media/materials/scripts/smoke.material b/Samples/Media/materials/scripts/smoke.material deleted file mode 100644 index f36a7b5dbbb..00000000000 --- a/Samples/Media/materials/scripts/smoke.material +++ /dev/null @@ -1,19 +0,0 @@ -material Examples/Smoke -{ - technique - { - pass - { - lighting off - scene_blend alpha_blend - depth_write off - diffuse vertexcolour - - texture_unit - { - texture Smoke15Frames.png - tex_address_mode clamp - } - } - } -} \ No newline at end of file diff --git a/Samples/Media/materials/textures/10points.png b/Samples/Media/materials/textures/10points.png deleted file mode 100644 index a932146c273..00000000000 Binary files a/Samples/Media/materials/textures/10points.png and /dev/null differ diff --git a/Samples/Media/materials/textures/1D_Noise.png b/Samples/Media/materials/textures/1D_Noise.png deleted file mode 100644 index d03ed1ee355..00000000000 Binary files a/Samples/Media/materials/textures/1D_Noise.png and /dev/null differ diff --git a/Samples/Media/materials/textures/1D_Noise2.png b/Samples/Media/materials/textures/1D_Noise2.png deleted file mode 100644 index 9dfd6f845a6..00000000000 Binary files a/Samples/Media/materials/textures/1D_Noise2.png and /dev/null differ diff --git a/Samples/Media/materials/textures/1d_SPIRAL.png b/Samples/Media/materials/textures/1d_SPIRAL.png deleted file mode 100644 index 505ba108893..00000000000 Binary files a/Samples/Media/materials/textures/1d_SPIRAL.png and /dev/null differ diff --git a/Samples/Media/materials/textures/1d_debug.png b/Samples/Media/materials/textures/1d_debug.png deleted file mode 100644 index 5664094e7ec..00000000000 Binary files a/Samples/Media/materials/textures/1d_debug.png and /dev/null differ diff --git a/Samples/Media/materials/textures/8x8PagesSplotches2.png b/Samples/Media/materials/textures/8x8PagesSplotches2.png deleted file mode 100644 index 6a6b1051d86..00000000000 Binary files a/Samples/Media/materials/textures/8x8PagesSplotches2.png and /dev/null differ diff --git a/Samples/Media/materials/textures/ASCII.dds b/Samples/Media/materials/textures/ASCII.dds deleted file mode 100644 index 845f1bdcc74..00000000000 Binary files a/Samples/Media/materials/textures/ASCII.dds and /dev/null differ diff --git a/Samples/Media/materials/textures/BeachStones.jpg b/Samples/Media/materials/textures/BeachStones.jpg deleted file mode 100644 index faaa16fe041..00000000000 Binary files a/Samples/Media/materials/textures/BeachStones.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/BumpyMetal.jpg b/Samples/Media/materials/textures/BumpyMetal.jpg deleted file mode 100644 index 146102fe205..00000000000 Binary files a/Samples/Media/materials/textures/BumpyMetal.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/Chrome.jpg b/Samples/Media/materials/textures/Chrome.jpg deleted file mode 100644 index 0ae5c526038..00000000000 Binary files a/Samples/Media/materials/textures/Chrome.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/Cookie0.png b/Samples/Media/materials/textures/Cookie0.png deleted file mode 100644 index d23eee467e8..00000000000 Binary files a/Samples/Media/materials/textures/Cookie0.png and /dev/null differ diff --git a/Samples/Media/materials/textures/Cookie1.png b/Samples/Media/materials/textures/Cookie1.png deleted file mode 100644 index ddb3470f423..00000000000 Binary files a/Samples/Media/materials/textures/Cookie1.png and /dev/null differ diff --git a/Samples/Media/materials/textures/Cookie2.png b/Samples/Media/materials/textures/Cookie2.png deleted file mode 100644 index 6c6f906be55..00000000000 Binary files a/Samples/Media/materials/textures/Cookie2.png and /dev/null differ diff --git a/Samples/Media/materials/textures/Cookie3.png b/Samples/Media/materials/textures/Cookie3.png deleted file mode 100644 index 7c9e3aaf5dd..00000000000 Binary files a/Samples/Media/materials/textures/Cookie3.png and /dev/null differ diff --git a/Samples/Media/materials/textures/Dirt.jpg b/Samples/Media/materials/textures/Dirt.jpg deleted file mode 100644 index 8b74a42f1a4..00000000000 Binary files a/Samples/Media/materials/textures/Dirt.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/Dr_Bunsen_Head.jpg b/Samples/Media/materials/textures/Dr_Bunsen_Head.jpg deleted file mode 100644 index 3ef969d7b0e..00000000000 Binary files a/Samples/Media/materials/textures/Dr_Bunsen_Head.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/GLX_icon.png b/Samples/Media/materials/textures/GLX_icon.png deleted file mode 100644 index a13699bedba..00000000000 Binary files a/Samples/Media/materials/textures/GLX_icon.png and /dev/null differ diff --git a/Samples/Media/materials/textures/GreenSkin.jpg b/Samples/Media/materials/textures/GreenSkin.jpg deleted file mode 100644 index 35d55252f30..00000000000 Binary files a/Samples/Media/materials/textures/GreenSkin.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/HeatLookup.tga b/Samples/Media/materials/textures/HeatLookup.tga deleted file mode 100644 index e45ec53efc8..00000000000 Binary files a/Samples/Media/materials/textures/HeatLookup.tga and /dev/null differ diff --git a/Samples/Media/materials/textures/HeatNoise.tga b/Samples/Media/materials/textures/HeatNoise.tga deleted file mode 100644 index 159e3620542..00000000000 Binary files a/Samples/Media/materials/textures/HeatNoise.tga and /dev/null differ diff --git a/Samples/Media/materials/textures/KAMEN-stup.jpg b/Samples/Media/materials/textures/KAMEN-stup.jpg deleted file mode 100644 index ba307918013..00000000000 Binary files a/Samples/Media/materials/textures/KAMEN-stup.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/KAMEN320x240-bump.jpg b/Samples/Media/materials/textures/KAMEN320x240-bump.jpg deleted file mode 100644 index 525f8f8c107..00000000000 Binary files a/Samples/Media/materials/textures/KAMEN320x240-bump.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/KAMEN320x240.jpg b/Samples/Media/materials/textures/KAMEN320x240.jpg deleted file mode 100644 index 0524edec5f6..00000000000 Binary files a/Samples/Media/materials/textures/KAMEN320x240.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/LowRes.png b/Samples/Media/materials/textures/LowRes.png deleted file mode 100644 index c89f9abffb0..00000000000 Binary files a/Samples/Media/materials/textures/LowRes.png and /dev/null differ diff --git a/Samples/Media/materials/textures/MRAMOR-bump.jpg b/Samples/Media/materials/textures/MRAMOR-bump.jpg deleted file mode 100644 index c9692710d39..00000000000 Binary files a/Samples/Media/materials/textures/MRAMOR-bump.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/MRAMOR6X6.jpg b/Samples/Media/materials/textures/MRAMOR6X6.jpg deleted file mode 100644 index f3f25ce13c0..00000000000 Binary files a/Samples/Media/materials/textures/MRAMOR6X6.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/MtlPlat2.jpg b/Samples/Media/materials/textures/MtlPlat2.jpg deleted file mode 100644 index 2a200183e41..00000000000 Binary files a/Samples/Media/materials/textures/MtlPlat2.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/NMBalls.png b/Samples/Media/materials/textures/NMBalls.png deleted file mode 100644 index 74f02e379a2..00000000000 Binary files a/Samples/Media/materials/textures/NMBalls.png and /dev/null differ diff --git a/Samples/Media/materials/textures/NMBumpsOut.png b/Samples/Media/materials/textures/NMBumpsOut.png deleted file mode 100644 index b5ef61e54f3..00000000000 Binary files a/Samples/Media/materials/textures/NMBumpsOut.png and /dev/null differ diff --git a/Samples/Media/materials/textures/NMHollyBumps.png b/Samples/Media/materials/textures/NMHollyBumps.png deleted file mode 100644 index ac91b020002..00000000000 Binary files a/Samples/Media/materials/textures/NMHollyBumps.png and /dev/null differ diff --git a/Samples/Media/materials/textures/NMStripes.png b/Samples/Media/materials/textures/NMStripes.png deleted file mode 100644 index 407816215b3..00000000000 Binary files a/Samples/Media/materials/textures/NMStripes.png and /dev/null differ diff --git a/Samples/Media/materials/textures/NPRMetallic.tga b/Samples/Media/materials/textures/NPRMetallic.tga deleted file mode 100644 index 6649a6fb61c..00000000000 Binary files a/Samples/Media/materials/textures/NPRMetallic.tga and /dev/null differ diff --git a/Samples/Media/materials/textures/Noise.png b/Samples/Media/materials/textures/Noise.png deleted file mode 100644 index 986185071f7..00000000000 Binary files a/Samples/Media/materials/textures/Noise.png and /dev/null differ diff --git a/Samples/Media/materials/textures/NoiseVolume.dds b/Samples/Media/materials/textures/NoiseVolume.dds deleted file mode 100644 index bd8147d49fd..00000000000 Binary files a/Samples/Media/materials/textures/NoiseVolume.dds and /dev/null differ diff --git a/Samples/Media/materials/textures/Panels_Diffuse.png b/Samples/Media/materials/textures/Panels_Diffuse.png deleted file mode 100644 index 15b242c4adc..00000000000 Binary files a/Samples/Media/materials/textures/Panels_Diffuse.png and /dev/null differ diff --git a/Samples/Media/materials/textures/Panels_Normal_Obj.png b/Samples/Media/materials/textures/Panels_Normal_Obj.png deleted file mode 100644 index cd02bba35c9..00000000000 Binary files a/Samples/Media/materials/textures/Panels_Normal_Obj.png and /dev/null differ diff --git a/Samples/Media/materials/textures/Panels_Normal_Tangent.png b/Samples/Media/materials/textures/Panels_Normal_Tangent.png deleted file mode 100644 index 5501cb11de1..00000000000 Binary files a/Samples/Media/materials/textures/Panels_Normal_Tangent.png and /dev/null differ diff --git a/Samples/Media/materials/textures/Panels_reflection.png b/Samples/Media/materials/textures/Panels_reflection.png deleted file mode 100644 index d685d9bbaea..00000000000 Binary files a/Samples/Media/materials/textures/Panels_reflection.png and /dev/null differ diff --git a/Samples/Media/materials/textures/Panels_refmask.png b/Samples/Media/materials/textures/Panels_refmask.png deleted file mode 100644 index 6c4eaabe110..00000000000 Binary files a/Samples/Media/materials/textures/Panels_refmask.png and /dev/null differ diff --git a/Samples/Media/materials/textures/RZR-002.png b/Samples/Media/materials/textures/RZR-002.png deleted file mode 100644 index 663eb05d914..00000000000 Binary files a/Samples/Media/materials/textures/RZR-002.png and /dev/null differ diff --git a/Samples/Media/materials/textures/Random3D.dds b/Samples/Media/materials/textures/Random3D.dds deleted file mode 100644 index 08b61959fa6..00000000000 Binary files a/Samples/Media/materials/textures/Random3D.dds and /dev/null differ diff --git a/Samples/Media/materials/textures/Rocks_Diffuse.tga b/Samples/Media/materials/textures/Rocks_Diffuse.tga deleted file mode 100644 index 5c74b84a96b..00000000000 Binary files a/Samples/Media/materials/textures/Rocks_Diffuse.tga and /dev/null differ diff --git a/Samples/Media/materials/textures/Rocks_Normal.tga b/Samples/Media/materials/textures/Rocks_Normal.tga deleted file mode 100644 index 65d9e11b8ca..00000000000 Binary files a/Samples/Media/materials/textures/Rocks_Normal.tga and /dev/null differ diff --git a/Samples/Media/materials/textures/Rocks_Spec.tga b/Samples/Media/materials/textures/Rocks_Spec.tga deleted file mode 100644 index 5e471ec2408..00000000000 Binary files a/Samples/Media/materials/textures/Rocks_Spec.tga and /dev/null differ diff --git a/Samples/Media/materials/textures/RustedMetal.jpg b/Samples/Media/materials/textures/RustedMetal.jpg deleted file mode 100644 index 070346d3225..00000000000 Binary files a/Samples/Media/materials/textures/RustedMetal.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/RustyBarrel.png b/Samples/Media/materials/textures/RustyBarrel.png deleted file mode 100644 index 8448a8e72d3..00000000000 Binary files a/Samples/Media/materials/textures/RustyBarrel.png and /dev/null differ diff --git a/Samples/Media/materials/textures/RustySteel.jpg b/Samples/Media/materials/textures/RustySteel.jpg deleted file mode 100644 index a2d7b9dff11..00000000000 Binary files a/Samples/Media/materials/textures/RustySteel.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/SSAO/4InterleavedKMeansDisk8x4.png b/Samples/Media/materials/textures/SSAO/4InterleavedKMeansDisk8x4.png deleted file mode 100644 index 286e25e59ff..00000000000 Binary files a/Samples/Media/materials/textures/SSAO/4InterleavedKMeansDisk8x4.png and /dev/null differ diff --git a/Samples/Media/materials/textures/SSAO/importance4InterleavedSphereHemisphere8x4.png b/Samples/Media/materials/textures/SSAO/importance4InterleavedSphereHemisphere8x4.png deleted file mode 100644 index 892160009d7..00000000000 Binary files a/Samples/Media/materials/textures/SSAO/importance4InterleavedSphereHemisphere8x4.png and /dev/null differ diff --git a/Samples/Media/materials/textures/SSAO/rand1x32.png b/Samples/Media/materials/textures/SSAO/rand1x32.png deleted file mode 100644 index c3ff3cbc798..00000000000 Binary files a/Samples/Media/materials/textures/SSAO/rand1x32.png and /dev/null differ diff --git a/Samples/Media/materials/textures/SSAO/randCosSinJitter4x4.png b/Samples/Media/materials/textures/SSAO/randCosSinJitter4x4.png deleted file mode 100644 index 0f9d1514cd8..00000000000 Binary files a/Samples/Media/materials/textures/SSAO/randCosSinJitter4x4.png and /dev/null differ diff --git a/Samples/Media/materials/textures/SSAO/regularSphereJittered4.png b/Samples/Media/materials/textures/SSAO/regularSphereJittered4.png deleted file mode 100644 index 0a1f34f9f2c..00000000000 Binary files a/Samples/Media/materials/textures/SSAO/regularSphereJittered4.png and /dev/null differ diff --git a/Samples/Media/materials/textures/Sepia1D.tga b/Samples/Media/materials/textures/Sepia1D.tga deleted file mode 100644 index dcc42620428..00000000000 Binary files a/Samples/Media/materials/textures/Sepia1D.tga and /dev/null differ diff --git a/Samples/Media/materials/textures/SmallLeaf_BP.png b/Samples/Media/materials/textures/SmallLeaf_BP.png deleted file mode 100644 index c8c49a7045f..00000000000 Binary files a/Samples/Media/materials/textures/SmallLeaf_BP.png and /dev/null differ diff --git a/Samples/Media/materials/textures/Smoke15Frames.png b/Samples/Media/materials/textures/Smoke15Frames.png deleted file mode 100644 index 449139fa73b..00000000000 Binary files a/Samples/Media/materials/textures/Smoke15Frames.png and /dev/null differ diff --git a/Samples/Media/materials/textures/TextureAtlasSampleOrg0.png b/Samples/Media/materials/textures/TextureAtlasSampleOrg0.png deleted file mode 100644 index 8a4fb9b313b..00000000000 Binary files a/Samples/Media/materials/textures/TextureAtlasSampleOrg0.png and /dev/null differ diff --git a/Samples/Media/materials/textures/TextureAtlasSampleWrap0.png b/Samples/Media/materials/textures/TextureAtlasSampleWrap0.png deleted file mode 100644 index 223591fce76..00000000000 Binary files a/Samples/Media/materials/textures/TextureAtlasSampleWrap0.png and /dev/null differ diff --git a/Samples/Media/materials/textures/Water01.jpg b/Samples/Media/materials/textures/Water01.jpg deleted file mode 100644 index f9c9b7feec5..00000000000 Binary files a/Samples/Media/materials/textures/Water01.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/Water02.jpg b/Samples/Media/materials/textures/Water02.jpg deleted file mode 100644 index 3efda7b6a88..00000000000 Binary files a/Samples/Media/materials/textures/Water02.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/WaterNormal1.tga b/Samples/Media/materials/textures/WaterNormal1.tga deleted file mode 100644 index a9ca11b7ed0..00000000000 Binary files a/Samples/Media/materials/textures/WaterNormal1.tga and /dev/null differ diff --git a/Samples/Media/materials/textures/WaterNormal2.tga b/Samples/Media/materials/textures/WaterNormal2.tga deleted file mode 100644 index 771d1504192..00000000000 Binary files a/Samples/Media/materials/textures/WaterNormal2.tga and /dev/null differ diff --git a/Samples/Media/materials/textures/WoodFloor043_1K_Color.jpg b/Samples/Media/materials/textures/WoodFloor043_1K_Color.jpg deleted file mode 100644 index 876f906fef2..00000000000 Binary files a/Samples/Media/materials/textures/WoodFloor043_1K_Color.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/WoodFloor043_1K_MetalRoughness.jpg b/Samples/Media/materials/textures/WoodFloor043_1K_MetalRoughness.jpg deleted file mode 100644 index 60b491140d7..00000000000 Binary files a/Samples/Media/materials/textures/WoodFloor043_1K_MetalRoughness.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/WoodFloor043_1K_NormalGL.jpg b/Samples/Media/materials/textures/WoodFloor043_1K_NormalGL.jpg deleted file mode 100644 index d8679239464..00000000000 Binary files a/Samples/Media/materials/textures/WoodFloor043_1K_NormalGL.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/WoodPallet.png b/Samples/Media/materials/textures/WoodPallet.png deleted file mode 100644 index 7727d71a9bb..00000000000 Binary files a/Samples/Media/materials/textures/WoodPallet.png and /dev/null differ diff --git a/Samples/Media/materials/textures/atheneNormalMap.png b/Samples/Media/materials/textures/atheneNormalMap.png deleted file mode 100644 index 00dbf15e2df..00000000000 Binary files a/Samples/Media/materials/textures/atheneNormalMap.png and /dev/null differ diff --git a/Samples/Media/materials/textures/aureola.png b/Samples/Media/materials/textures/aureola.png deleted file mode 100644 index 757f593fe87..00000000000 Binary files a/Samples/Media/materials/textures/aureola.png and /dev/null differ diff --git a/Samples/Media/materials/textures/basic_droplet.png b/Samples/Media/materials/textures/basic_droplet.png deleted file mode 100644 index 27ca8e8affe..00000000000 Binary files a/Samples/Media/materials/textures/basic_droplet.png and /dev/null differ diff --git a/Samples/Media/materials/textures/blue_jaiqua.jpg b/Samples/Media/materials/textures/blue_jaiqua.jpg deleted file mode 100644 index 6016e140993..00000000000 Binary files a/Samples/Media/materials/textures/blue_jaiqua.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/cel_shading_diffuse.png b/Samples/Media/materials/textures/cel_shading_diffuse.png deleted file mode 100644 index 9cd4efbbe83..00000000000 Binary files a/Samples/Media/materials/textures/cel_shading_diffuse.png and /dev/null differ diff --git a/Samples/Media/materials/textures/cel_shading_edge.png b/Samples/Media/materials/textures/cel_shading_edge.png deleted file mode 100644 index 9cc118ab9f2..00000000000 Binary files a/Samples/Media/materials/textures/cel_shading_edge.png and /dev/null differ diff --git a/Samples/Media/materials/textures/cel_shading_specular.png b/Samples/Media/materials/textures/cel_shading_specular.png deleted file mode 100644 index 9cc118ab9f2..00000000000 Binary files a/Samples/Media/materials/textures/cel_shading_specular.png and /dev/null differ diff --git a/Samples/Media/materials/textures/checker.png b/Samples/Media/materials/textures/checker.png deleted file mode 100644 index 288c0a0c3ac..00000000000 Binary files a/Samples/Media/materials/textures/checker.png and /dev/null differ diff --git a/Samples/Media/materials/textures/circuit.dds b/Samples/Media/materials/textures/circuit.dds deleted file mode 100644 index d249d384fa2..00000000000 Binary files a/Samples/Media/materials/textures/circuit.dds and /dev/null differ diff --git a/Samples/Media/materials/textures/clouds.jpg b/Samples/Media/materials/textures/clouds.jpg deleted file mode 100644 index 4db0f11e208..00000000000 Binary files a/Samples/Media/materials/textures/clouds.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/cursor.png b/Samples/Media/materials/textures/cursor.png deleted file mode 100644 index 3d1c756cf17..00000000000 Binary files a/Samples/Media/materials/textures/cursor.png and /dev/null differ diff --git a/Samples/Media/materials/textures/dark_grid.png b/Samples/Media/materials/textures/dark_grid.png deleted file mode 100644 index 3619f81c90d..00000000000 Binary files a/Samples/Media/materials/textures/dark_grid.png and /dev/null differ diff --git a/Samples/Media/materials/textures/dirt01.jpg b/Samples/Media/materials/textures/dirt01.jpg deleted file mode 100644 index 7c7cc5eb3ac..00000000000 Binary files a/Samples/Media/materials/textures/dirt01.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/dkyellow.png b/Samples/Media/materials/textures/dkyellow.png deleted file mode 100644 index 88c1d64790f..00000000000 Binary files a/Samples/Media/materials/textures/dkyellow.png and /dev/null differ diff --git a/Samples/Media/materials/textures/droplet.png b/Samples/Media/materials/textures/droplet.png deleted file mode 100644 index f1cfc4a804f..00000000000 Binary files a/Samples/Media/materials/textures/droplet.png and /dev/null differ diff --git a/Samples/Media/materials/textures/egyptrockyfull.jpg b/Samples/Media/materials/textures/egyptrockyfull.jpg deleted file mode 100644 index 044ce9f1692..00000000000 Binary files a/Samples/Media/materials/textures/egyptrockyfull.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/flare.png b/Samples/Media/materials/textures/flare.png deleted file mode 100644 index 9f8a2a8414d..00000000000 Binary files a/Samples/Media/materials/textures/flare.png and /dev/null differ diff --git a/Samples/Media/materials/textures/flare_alpha.dds b/Samples/Media/materials/textures/flare_alpha.dds deleted file mode 100644 index c9a357ece16..00000000000 Binary files a/Samples/Media/materials/textures/flare_alpha.dds and /dev/null differ diff --git a/Samples/Media/materials/textures/flaretrail.png b/Samples/Media/materials/textures/flaretrail.png deleted file mode 100644 index 55812b2fb77..00000000000 Binary files a/Samples/Media/materials/textures/flaretrail.png and /dev/null differ diff --git a/Samples/Media/materials/textures/floor_ao.PNG b/Samples/Media/materials/textures/floor_ao.PNG deleted file mode 100644 index 33628d5e8ad..00000000000 Binary files a/Samples/Media/materials/textures/floor_ao.PNG and /dev/null differ diff --git a/Samples/Media/materials/textures/floor_bump.PNG b/Samples/Media/materials/textures/floor_bump.PNG deleted file mode 100644 index fb95387a9e4..00000000000 Binary files a/Samples/Media/materials/textures/floor_bump.PNG and /dev/null differ diff --git a/Samples/Media/materials/textures/floor_diffuse.PNG b/Samples/Media/materials/textures/floor_diffuse.PNG deleted file mode 100644 index f84c4f96274..00000000000 Binary files a/Samples/Media/materials/textures/floor_diffuse.PNG and /dev/null differ diff --git a/Samples/Media/materials/textures/floor_specular.PNG b/Samples/Media/materials/textures/floor_specular.PNG deleted file mode 100644 index 04ee65a9d7b..00000000000 Binary files a/Samples/Media/materials/textures/floor_specular.PNG and /dev/null differ diff --git a/Samples/Media/materials/textures/frost.png b/Samples/Media/materials/textures/frost.png deleted file mode 100644 index 22fb89c35f0..00000000000 Binary files a/Samples/Media/materials/textures/frost.png and /dev/null differ diff --git a/Samples/Media/materials/textures/fw12b.jpg b/Samples/Media/materials/textures/fw12b.jpg deleted file mode 100644 index 980060541bf..00000000000 Binary files a/Samples/Media/materials/textures/fw12b.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/gras_02.png b/Samples/Media/materials/textures/gras_02.png deleted file mode 100644 index 1110724cdc5..00000000000 Binary files a/Samples/Media/materials/textures/gras_02.png and /dev/null differ diff --git a/Samples/Media/materials/textures/grass.PNG b/Samples/Media/materials/textures/grass.PNG deleted file mode 100644 index a23e27cdecb..00000000000 Binary files a/Samples/Media/materials/textures/grass.PNG and /dev/null differ diff --git a/Samples/Media/materials/textures/grassWalpha.tga b/Samples/Media/materials/textures/grassWalpha.tga deleted file mode 100644 index 09067221ada..00000000000 Binary files a/Samples/Media/materials/textures/grassWalpha.tga and /dev/null differ diff --git a/Samples/Media/materials/textures/grass_1024.jpg b/Samples/Media/materials/textures/grass_1024.jpg deleted file mode 100644 index e65691b3ade..00000000000 Binary files a/Samples/Media/materials/textures/grass_1024.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/img1.png b/Samples/Media/materials/textures/img1.png deleted file mode 100644 index e55c57d9b8d..00000000000 Binary files a/Samples/Media/materials/textures/img1.png and /dev/null differ diff --git a/Samples/Media/materials/textures/img2.png b/Samples/Media/materials/textures/img2.png deleted file mode 100644 index d5c7db1377b..00000000000 Binary files a/Samples/Media/materials/textures/img2.png and /dev/null differ diff --git a/Samples/Media/materials/textures/leaf.png b/Samples/Media/materials/textures/leaf.png deleted file mode 100644 index 9309d71a7f3..00000000000 Binary files a/Samples/Media/materials/textures/leaf.png and /dev/null differ diff --git a/Samples/Media/materials/textures/nm_bk.png b/Samples/Media/materials/textures/nm_bk.png deleted file mode 100644 index 65998a439cd..00000000000 Binary files a/Samples/Media/materials/textures/nm_bk.png and /dev/null differ diff --git a/Samples/Media/materials/textures/nm_dn.png b/Samples/Media/materials/textures/nm_dn.png deleted file mode 100644 index 2b50b027a8f..00000000000 Binary files a/Samples/Media/materials/textures/nm_dn.png and /dev/null differ diff --git a/Samples/Media/materials/textures/nm_fr.png b/Samples/Media/materials/textures/nm_fr.png deleted file mode 100644 index e1f90f39da6..00000000000 Binary files a/Samples/Media/materials/textures/nm_fr.png and /dev/null differ diff --git a/Samples/Media/materials/textures/nm_lf.png b/Samples/Media/materials/textures/nm_lf.png deleted file mode 100644 index 28606136a03..00000000000 Binary files a/Samples/Media/materials/textures/nm_lf.png and /dev/null differ diff --git a/Samples/Media/materials/textures/nm_rt.png b/Samples/Media/materials/textures/nm_rt.png deleted file mode 100644 index 9d0d57176b6..00000000000 Binary files a/Samples/Media/materials/textures/nm_rt.png and /dev/null differ diff --git a/Samples/Media/materials/textures/nm_up.png b/Samples/Media/materials/textures/nm_up.png deleted file mode 100644 index 959347ac781..00000000000 Binary files a/Samples/Media/materials/textures/nm_up.png and /dev/null differ diff --git a/Samples/Media/materials/textures/normalNoiseColor.png b/Samples/Media/materials/textures/normalNoiseColor.png deleted file mode 100644 index fc5f77bf72f..00000000000 Binary files a/Samples/Media/materials/textures/normalNoiseColor.png and /dev/null differ diff --git a/Samples/Media/materials/textures/nskingr.jpg b/Samples/Media/materials/textures/nskingr.jpg deleted file mode 100644 index 9397f5d91ad..00000000000 Binary files a/Samples/Media/materials/textures/nskingr.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/ogreborder.png b/Samples/Media/materials/textures/ogreborder.png deleted file mode 100644 index 9cc0d9da1c1..00000000000 Binary files a/Samples/Media/materials/textures/ogreborder.png and /dev/null differ diff --git a/Samples/Media/materials/textures/ogreborderUp.png b/Samples/Media/materials/textures/ogreborderUp.png deleted file mode 100644 index d1ee4a6b6d5..00000000000 Binary files a/Samples/Media/materials/textures/ogreborderUp.png and /dev/null differ diff --git a/Samples/Media/materials/textures/ogrebordercenter.png b/Samples/Media/materials/textures/ogrebordercenter.png deleted file mode 100644 index c62c02af7a7..00000000000 Binary files a/Samples/Media/materials/textures/ogrebordercenter.png and /dev/null differ diff --git a/Samples/Media/materials/textures/ogregui.tga b/Samples/Media/materials/textures/ogregui.tga deleted file mode 100644 index 74f5efdabd0..00000000000 Binary files a/Samples/Media/materials/textures/ogregui.tga and /dev/null differ diff --git a/Samples/Media/materials/textures/ogrelogo-small.jpg b/Samples/Media/materials/textures/ogrelogo-small.jpg deleted file mode 100644 index 9cee64742db..00000000000 Binary files a/Samples/Media/materials/textures/ogrelogo-small.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/ogrelogo.png b/Samples/Media/materials/textures/ogrelogo.png deleted file mode 100644 index 1bc197551c9..00000000000 Binary files a/Samples/Media/materials/textures/ogrelogo.png and /dev/null differ diff --git a/Samples/Media/materials/textures/particle.dds b/Samples/Media/materials/textures/particle.dds deleted file mode 100644 index 8161803a824..00000000000 Binary files a/Samples/Media/materials/textures/particle.dds and /dev/null differ diff --git a/Samples/Media/materials/textures/penguin.jpg b/Samples/Media/materials/textures/penguin.jpg deleted file mode 100644 index 65e92487a02..00000000000 Binary files a/Samples/Media/materials/textures/penguin.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/perlinvolume.dds b/Samples/Media/materials/textures/perlinvolume.dds deleted file mode 100644 index bd8147d49fd..00000000000 Binary files a/Samples/Media/materials/textures/perlinvolume.dds and /dev/null differ diff --git a/Samples/Media/materials/textures/r2skin.jpg b/Samples/Media/materials/textures/r2skin.jpg deleted file mode 100644 index 3e83a1246c0..00000000000 Binary files a/Samples/Media/materials/textures/r2skin.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/radial.png b/Samples/Media/materials/textures/radial.png deleted file mode 100644 index e44794221d6..00000000000 Binary files a/Samples/Media/materials/textures/radial.png and /dev/null differ diff --git a/Samples/Media/materials/textures/random.png b/Samples/Media/materials/textures/random.png deleted file mode 100644 index 292c801d265..00000000000 Binary files a/Samples/Media/materials/textures/random.png and /dev/null differ diff --git a/Samples/Media/materials/textures/ribbonband.png b/Samples/Media/materials/textures/ribbonband.png deleted file mode 100644 index e6966640c0b..00000000000 Binary files a/Samples/Media/materials/textures/ribbonband.png and /dev/null differ diff --git a/Samples/Media/materials/textures/rockwall.tga b/Samples/Media/materials/textures/rockwall.tga deleted file mode 100644 index 5703a03aa89..00000000000 Binary files a/Samples/Media/materials/textures/rockwall.tga and /dev/null differ diff --git a/Samples/Media/materials/textures/rockwall_NH.tga b/Samples/Media/materials/textures/rockwall_NH.tga deleted file mode 100644 index 12fa50bd801..00000000000 Binary files a/Samples/Media/materials/textures/rockwall_NH.tga and /dev/null differ diff --git a/Samples/Media/materials/textures/scr-back.png b/Samples/Media/materials/textures/scr-back.png deleted file mode 100644 index 05cf80124fd..00000000000 Binary files a/Samples/Media/materials/textures/scr-back.png and /dev/null differ diff --git a/Samples/Media/materials/textures/scr-down-p.png b/Samples/Media/materials/textures/scr-down-p.png deleted file mode 100644 index 31b575ea4ae..00000000000 Binary files a/Samples/Media/materials/textures/scr-down-p.png and /dev/null differ diff --git a/Samples/Media/materials/textures/scr-down.png b/Samples/Media/materials/textures/scr-down.png deleted file mode 100644 index d52b5475630..00000000000 Binary files a/Samples/Media/materials/textures/scr-down.png and /dev/null differ diff --git a/Samples/Media/materials/textures/scr-thumb.png b/Samples/Media/materials/textures/scr-thumb.png deleted file mode 100644 index 8f05cc72d6b..00000000000 Binary files a/Samples/Media/materials/textures/scr-thumb.png and /dev/null differ diff --git a/Samples/Media/materials/textures/scr-up-p.png b/Samples/Media/materials/textures/scr-up-p.png deleted file mode 100644 index b9b45dcb89a..00000000000 Binary files a/Samples/Media/materials/textures/scr-up-p.png and /dev/null differ diff --git a/Samples/Media/materials/textures/scr-up.png b/Samples/Media/materials/textures/scr-up.png deleted file mode 100644 index 1e0f9b46ae1..00000000000 Binary files a/Samples/Media/materials/textures/scr-up.png and /dev/null differ diff --git a/Samples/Media/materials/textures/smokecolors.png b/Samples/Media/materials/textures/smokecolors.png deleted file mode 100644 index 72bc634d7af..00000000000 Binary files a/Samples/Media/materials/textures/smokecolors.png and /dev/null differ diff --git a/Samples/Media/materials/textures/snow_1024.jpg b/Samples/Media/materials/textures/snow_1024.jpg deleted file mode 100644 index 56590af4f76..00000000000 Binary files a/Samples/Media/materials/textures/snow_1024.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/spacesky.jpg b/Samples/Media/materials/textures/spacesky.jpg deleted file mode 100644 index 34d89d6cc9e..00000000000 Binary files a/Samples/Media/materials/textures/spacesky.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/spheremap.png b/Samples/Media/materials/textures/spheremap.png deleted file mode 100644 index e6b91475024..00000000000 Binary files a/Samples/Media/materials/textures/spheremap.png and /dev/null differ diff --git a/Samples/Media/materials/textures/spine_strips.dds b/Samples/Media/materials/textures/spine_strips.dds deleted file mode 100644 index 51538caecf6..00000000000 Binary files a/Samples/Media/materials/textures/spine_strips.dds and /dev/null differ diff --git a/Samples/Media/materials/textures/spotlight_image.png b/Samples/Media/materials/textures/spotlight_image.png deleted file mode 100644 index 5719e81821e..00000000000 Binary files a/Samples/Media/materials/textures/spotlight_image.png and /dev/null differ diff --git a/Samples/Media/materials/textures/steelhead.png b/Samples/Media/materials/textures/steelhead.png deleted file mode 100644 index 4c2ba37040c..00000000000 Binary files a/Samples/Media/materials/textures/steelhead.png and /dev/null differ diff --git a/Samples/Media/materials/textures/strugotine.jpg b/Samples/Media/materials/textures/strugotine.jpg deleted file mode 100644 index 18020f98548..00000000000 Binary files a/Samples/Media/materials/textures/strugotine.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/terr_dirt-grass.jpg b/Samples/Media/materials/textures/terr_dirt-grass.jpg deleted file mode 100644 index 001bd3e7890..00000000000 Binary files a/Samples/Media/materials/textures/terr_dirt-grass.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/terr_rock-dirt.jpg b/Samples/Media/materials/textures/terr_rock-dirt.jpg deleted file mode 100644 index 6fda5c7c19e..00000000000 Binary files a/Samples/Media/materials/textures/terr_rock-dirt.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/terr_rock6.jpg b/Samples/Media/materials/textures/terr_rock6.jpg deleted file mode 100644 index 3100ed7413a..00000000000 Binary files a/Samples/Media/materials/textures/terr_rock6.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/terrain.png b/Samples/Media/materials/textures/terrain.png deleted file mode 100644 index 16e853fe50d..00000000000 Binary files a/Samples/Media/materials/textures/terrain.png and /dev/null differ diff --git a/Samples/Media/materials/textures/terrain/Bricks076C_diffspec.dds b/Samples/Media/materials/textures/terrain/Bricks076C_diffspec.dds deleted file mode 100644 index 52bd347e664..00000000000 Binary files a/Samples/Media/materials/textures/terrain/Bricks076C_diffspec.dds and /dev/null differ diff --git a/Samples/Media/materials/textures/terrain/Bricks076C_normheight.dds b/Samples/Media/materials/textures/terrain/Bricks076C_normheight.dds deleted file mode 100644 index 4ac5423d860..00000000000 Binary files a/Samples/Media/materials/textures/terrain/Bricks076C_normheight.dds and /dev/null differ diff --git a/Samples/Media/materials/textures/terrain/Ground23_col.jpg b/Samples/Media/materials/textures/terrain/Ground23_col.jpg deleted file mode 100644 index 31a9cbf8bcd..00000000000 Binary files a/Samples/Media/materials/textures/terrain/Ground23_col.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/terrain/Ground23_normheight.dds b/Samples/Media/materials/textures/terrain/Ground23_normheight.dds deleted file mode 100644 index 97cf4573418..00000000000 Binary files a/Samples/Media/materials/textures/terrain/Ground23_normheight.dds and /dev/null differ diff --git a/Samples/Media/materials/textures/terrain/Ground23_spec.png b/Samples/Media/materials/textures/terrain/Ground23_spec.png deleted file mode 100644 index a6a31c6c738..00000000000 Binary files a/Samples/Media/materials/textures/terrain/Ground23_spec.png and /dev/null differ diff --git a/Samples/Media/materials/textures/terrain/Ground37_diffspec.dds b/Samples/Media/materials/textures/terrain/Ground37_diffspec.dds deleted file mode 100644 index 235e16d02f0..00000000000 Binary files a/Samples/Media/materials/textures/terrain/Ground37_diffspec.dds and /dev/null differ diff --git a/Samples/Media/materials/textures/terrain/Ground37_normheight.dds b/Samples/Media/materials/textures/terrain/Ground37_normheight.dds deleted file mode 100644 index 66e5cba34a1..00000000000 Binary files a/Samples/Media/materials/textures/terrain/Ground37_normheight.dds and /dev/null differ diff --git a/Samples/Media/materials/textures/terrain/README.md b/Samples/Media/materials/textures/terrain/README.md deleted file mode 100644 index 7f546af64d7..00000000000 --- a/Samples/Media/materials/textures/terrain/README.md +++ /dev/null @@ -1 +0,0 @@ -Textures are CC0 from https://cc0textures.com/ adapted for Ogre \ No newline at end of file diff --git a/Samples/Media/materials/textures/terrain/Rock20_diffspec.dds b/Samples/Media/materials/textures/terrain/Rock20_diffspec.dds deleted file mode 100644 index 66888bb6bd1..00000000000 Binary files a/Samples/Media/materials/textures/terrain/Rock20_diffspec.dds and /dev/null differ diff --git a/Samples/Media/materials/textures/terrain/Rock20_normheight.dds b/Samples/Media/materials/textures/terrain/Rock20_normheight.dds deleted file mode 100644 index 3e1142b26a4..00000000000 Binary files a/Samples/Media/materials/textures/terrain/Rock20_normheight.dds and /dev/null differ diff --git a/Samples/Media/materials/textures/terrain_detail.jpg b/Samples/Media/materials/textures/terrain_detail.jpg deleted file mode 100644 index 981e37e6f71..00000000000 Binary files a/Samples/Media/materials/textures/terrain_detail.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/terrain_texture.jpg b/Samples/Media/materials/textures/terrain_texture.jpg deleted file mode 100644 index 8d4fda5a54b..00000000000 Binary files a/Samples/Media/materials/textures/terrain_texture.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/texmap2.jpg b/Samples/Media/materials/textures/texmap2.jpg deleted file mode 100644 index 8acc84d77cd..00000000000 Binary files a/Samples/Media/materials/textures/texmap2.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/tusk.jpg b/Samples/Media/materials/textures/tusk.jpg deleted file mode 100644 index b699a525fd4..00000000000 Binary files a/Samples/Media/materials/textures/tusk.jpg and /dev/null differ diff --git a/Samples/Media/materials/textures/waveNM.png b/Samples/Media/materials/textures/waveNM.png deleted file mode 100644 index 766e2e73398..00000000000 Binary files a/Samples/Media/materials/textures/waveNM.png and /dev/null differ diff --git a/Samples/Media/materials/textures/waves2.dds b/Samples/Media/materials/textures/waves2.dds deleted file mode 100644 index c379886faec..00000000000 Binary files a/Samples/Media/materials/textures/waves2.dds and /dev/null differ diff --git a/Samples/Media/models/Barrel.mesh b/Samples/Media/models/Barrel.mesh deleted file mode 100644 index 808c2959beb..00000000000 Binary files a/Samples/Media/models/Barrel.mesh and /dev/null differ diff --git a/Samples/Media/models/RZR-002.mesh b/Samples/Media/models/RZR-002.mesh deleted file mode 100644 index 60469daffe1..00000000000 Binary files a/Samples/Media/models/RZR-002.mesh and /dev/null differ diff --git a/Samples/Media/models/ShaderSystem.mesh b/Samples/Media/models/ShaderSystem.mesh deleted file mode 100644 index b372e8e9ff3..00000000000 Binary files a/Samples/Media/models/ShaderSystem.mesh and /dev/null differ diff --git a/Samples/Media/models/Sphere1000.mesh b/Samples/Media/models/Sphere1000.mesh deleted file mode 100644 index 39f0a15f818..00000000000 Binary files a/Samples/Media/models/Sphere1000.mesh and /dev/null differ diff --git a/Samples/Media/models/TestLevel_b0.mesh b/Samples/Media/models/TestLevel_b0.mesh deleted file mode 100644 index 9c2f88affe8..00000000000 Binary files a/Samples/Media/models/TestLevel_b0.mesh and /dev/null differ diff --git a/Samples/Media/models/WoodPallet.mesh b/Samples/Media/models/WoodPallet.mesh deleted file mode 100644 index 0ffdfca5b7e..00000000000 Binary files a/Samples/Media/models/WoodPallet.mesh and /dev/null differ diff --git a/Samples/Media/models/athene.mesh b/Samples/Media/models/athene.mesh deleted file mode 100644 index d42b4f6c060..00000000000 Binary files a/Samples/Media/models/athene.mesh and /dev/null differ diff --git a/Samples/Media/models/column.mesh b/Samples/Media/models/column.mesh deleted file mode 100644 index 7f772e1a935..00000000000 Binary files a/Samples/Media/models/column.mesh and /dev/null differ diff --git a/Samples/Media/models/cornell.mesh b/Samples/Media/models/cornell.mesh deleted file mode 100644 index 672bb821237..00000000000 Binary files a/Samples/Media/models/cornell.mesh and /dev/null differ diff --git a/Samples/Media/models/cube.mesh b/Samples/Media/models/cube.mesh deleted file mode 100644 index e19d0a388e8..00000000000 Binary files a/Samples/Media/models/cube.mesh and /dev/null differ diff --git a/Samples/Media/models/facial.mesh b/Samples/Media/models/facial.mesh deleted file mode 100644 index 6153ec4cfcb..00000000000 Binary files a/Samples/Media/models/facial.mesh and /dev/null differ diff --git a/Samples/Media/models/fish.mesh b/Samples/Media/models/fish.mesh deleted file mode 100644 index e048c54c33f..00000000000 Binary files a/Samples/Media/models/fish.mesh and /dev/null differ diff --git a/Samples/Media/models/fish.skeleton b/Samples/Media/models/fish.skeleton deleted file mode 100644 index 7a970fda23e..00000000000 Binary files a/Samples/Media/models/fish.skeleton and /dev/null differ diff --git a/Samples/Media/models/geosphere4500.mesh b/Samples/Media/models/geosphere4500.mesh deleted file mode 100644 index ee4908d1d80..00000000000 Binary files a/Samples/Media/models/geosphere4500.mesh and /dev/null differ diff --git a/Samples/Media/models/geosphere8000.mesh b/Samples/Media/models/geosphere8000.mesh deleted file mode 100644 index 3d4a42418c0..00000000000 Binary files a/Samples/Media/models/geosphere8000.mesh and /dev/null differ diff --git a/Samples/Media/models/jaiqua.mesh b/Samples/Media/models/jaiqua.mesh deleted file mode 100644 index e1ccd349af1..00000000000 Binary files a/Samples/Media/models/jaiqua.mesh and /dev/null differ diff --git a/Samples/Media/models/jaiqua.skeleton b/Samples/Media/models/jaiqua.skeleton deleted file mode 100644 index 3d7622c5b5b..00000000000 Binary files a/Samples/Media/models/jaiqua.skeleton and /dev/null differ diff --git a/Samples/Media/models/knot.mesh b/Samples/Media/models/knot.mesh deleted file mode 100644 index 7f98d1ea65d..00000000000 Binary files a/Samples/Media/models/knot.mesh and /dev/null differ diff --git a/Samples/Media/models/ninja.mesh b/Samples/Media/models/ninja.mesh deleted file mode 100644 index c9b36ffba95..00000000000 Binary files a/Samples/Media/models/ninja.mesh and /dev/null differ diff --git a/Samples/Media/models/ninja.skeleton b/Samples/Media/models/ninja.skeleton deleted file mode 100644 index 787f5f753cb..00000000000 Binary files a/Samples/Media/models/ninja.skeleton and /dev/null differ diff --git a/Samples/Media/models/ogrehead.mesh b/Samples/Media/models/ogrehead.mesh deleted file mode 100644 index c9ea728e3cf..00000000000 Binary files a/Samples/Media/models/ogrehead.mesh and /dev/null differ diff --git a/Samples/Media/models/penguin.mesh b/Samples/Media/models/penguin.mesh deleted file mode 100644 index 6c9348554b4..00000000000 Binary files a/Samples/Media/models/penguin.mesh and /dev/null differ diff --git a/Samples/Media/models/penguin.skeleton b/Samples/Media/models/penguin.skeleton deleted file mode 100644 index 105557bb3f2..00000000000 Binary files a/Samples/Media/models/penguin.skeleton and /dev/null differ diff --git a/Samples/Media/models/razor.mesh b/Samples/Media/models/razor.mesh deleted file mode 100644 index 819c17cd889..00000000000 Binary files a/Samples/Media/models/razor.mesh and /dev/null differ diff --git a/Samples/Media/models/robot.mesh b/Samples/Media/models/robot.mesh deleted file mode 100644 index 5b8e1d48ed0..00000000000 Binary files a/Samples/Media/models/robot.mesh and /dev/null differ diff --git a/Samples/Media/models/robot.skeleton b/Samples/Media/models/robot.skeleton deleted file mode 100644 index 0aa8bde5381..00000000000 Binary files a/Samples/Media/models/robot.skeleton and /dev/null differ diff --git a/Samples/Media/models/sibenik.mesh b/Samples/Media/models/sibenik.mesh deleted file mode 100644 index 6303b6af26c..00000000000 Binary files a/Samples/Media/models/sibenik.mesh and /dev/null differ diff --git a/Samples/Media/models/sphere.mesh b/Samples/Media/models/sphere.mesh deleted file mode 100644 index 8b79cc5a52e..00000000000 Binary files a/Samples/Media/models/sphere.mesh and /dev/null differ diff --git a/Samples/Media/models/spine.mesh b/Samples/Media/models/spine.mesh deleted file mode 100644 index d2ae5e04d64..00000000000 Binary files a/Samples/Media/models/spine.mesh and /dev/null differ diff --git a/Samples/Media/models/spine.mesh.skeleton b/Samples/Media/models/spine.mesh.skeleton deleted file mode 100644 index 66a5f4a9d69..00000000000 Binary files a/Samples/Media/models/spine.mesh.skeleton and /dev/null differ diff --git a/Samples/Media/models/tudorhouse.mesh b/Samples/Media/models/tudorhouse.mesh deleted file mode 100644 index 7d58ec40525..00000000000 Binary files a/Samples/Media/models/tudorhouse.mesh and /dev/null differ diff --git a/Samples/Media/models/uv_sphere.mesh b/Samples/Media/models/uv_sphere.mesh deleted file mode 100644 index bef0dc73bf8..00000000000 Binary files a/Samples/Media/models/uv_sphere.mesh and /dev/null differ diff --git a/Samples/Media/packs/DamagedHelmet.zip b/Samples/Media/packs/DamagedHelmet.zip deleted file mode 100644 index 5b4c45563c9..00000000000 Binary files a/Samples/Media/packs/DamagedHelmet.zip and /dev/null differ diff --git a/Samples/Media/packs/Sinbad.zip b/Samples/Media/packs/Sinbad.zip deleted file mode 100644 index 99c263a9745..00000000000 Binary files a/Samples/Media/packs/Sinbad.zip and /dev/null differ diff --git a/Samples/Media/packs/cubemap.zip b/Samples/Media/packs/cubemap.zip deleted file mode 100644 index 675e74eb411..00000000000 Binary files a/Samples/Media/packs/cubemap.zip and /dev/null differ diff --git a/Samples/Media/packs/cubemapsJS.zip b/Samples/Media/packs/cubemapsJS.zip deleted file mode 100644 index 07bb65bcdf6..00000000000 Binary files a/Samples/Media/packs/cubemapsJS.zip and /dev/null differ diff --git a/Samples/Media/packs/dragon.zip b/Samples/Media/packs/dragon.zip deleted file mode 100644 index 945d2735c86..00000000000 Binary files a/Samples/Media/packs/dragon.zip and /dev/null differ diff --git a/Samples/Media/packs/filament_shaders.zip b/Samples/Media/packs/filament_shaders.zip deleted file mode 100644 index 041a3261b79..00000000000 Binary files a/Samples/Media/packs/filament_shaders.zip and /dev/null differ diff --git a/Samples/Media/packs/fresneldemo.zip b/Samples/Media/packs/fresneldemo.zip deleted file mode 100644 index f51c44517cf..00000000000 Binary files a/Samples/Media/packs/fresneldemo.zip and /dev/null differ diff --git a/Samples/Media/packs/oa_rpg3dm2.pk3 b/Samples/Media/packs/oa_rpg3dm2.pk3 deleted file mode 100644 index a535ec1232b..00000000000 Binary files a/Samples/Media/packs/oa_rpg3dm2.pk3 and /dev/null differ diff --git a/Samples/Media/packs/ogredance.zip b/Samples/Media/packs/ogredance.zip deleted file mode 100644 index e34ace08799..00000000000 Binary files a/Samples/Media/packs/ogredance.zip and /dev/null differ diff --git a/Samples/Media/packs/ogretestmap.zip b/Samples/Media/packs/ogretestmap.zip deleted file mode 100644 index 63fb78609ec..00000000000 Binary files a/Samples/Media/packs/ogretestmap.zip and /dev/null differ diff --git a/Samples/Media/packs/skybox.zip b/Samples/Media/packs/skybox.zip deleted file mode 100644 index 35fefe93569..00000000000 Binary files a/Samples/Media/packs/skybox.zip and /dev/null differ diff --git a/Samples/Media/particle/Examples-Water.particle b/Samples/Media/particle/Examples-Water.particle deleted file mode 100644 index 5916e743f31..00000000000 --- a/Samples/Media/particle/Examples-Water.particle +++ /dev/null @@ -1,36 +0,0 @@ -particle_system Examples/Water/Rain -{ - material Examples/Droplet - particle_width 100 - particle_height 300 - cull_each true - quota 100 - // Make common direction straight down (faster than self oriented) - billboard_type oriented_common - billboard_origin bottom_center - common_direction 0 -1 0 - - // Area emitter - emitter Box - { - angle 0 - emission_rate 20 - time_to_live 5 - direction 0 -1 0 - velocity 1000 - colour_range_start 0.3 1 0.3 - colour_range_end 0.7 1 0.7 - width 3000 - height 3000 - depth 0 - } - - // Gravity - affector LinearForce - { - force_vector 0 -1000 0 - force_application add - } - -} - diff --git a/Samples/Media/particle/Examples.particle b/Samples/Media/particle/Examples.particle deleted file mode 100644 index f619593cb26..00000000000 --- a/Samples/Media/particle/Examples.particle +++ /dev/null @@ -1,382 +0,0 @@ -// Example particle systems - -// Exudes greeny particles which float upwards. -particle_system Examples/GreenyNimbus -{ - material Examples/FlarePointSprite - particle_width 35 - particle_height 35 - cull_each false - quota 5000 - billboard_type point - point_rendering true - - // Area emitter. - emitter Box - { - angle 30 - emission_rate 30 - time_to_live 1 - direction 0 1 0 - velocity 0 - colour_range_start 1 1 0 - colour_range_end 0.3 1 0.3 - width 60 - height 60 - depth 60 - } - - // Make 'em float upwards. - affector LinearForce - { - force_vector 0 100 0 - force_application add - } - - // Fader. - affector ColourFader - { - red -0.25 - green -0.25 - blue -0.25 - } -} - -//! [manual_sample] -// A sparkly purple fountain. -particle_system Examples/PurpleFountain -{ - material Examples/Flare2 - particle_width 20 - particle_height 40 - cull_each false - quota 10000 - billboard_type oriented_self - - // Area emitter. - emitter Point - { - angle 15 - emission_rate 75 - time_to_live 3 - direction 0 1 0 - velocity_min 250 - velocity_max 300 - colour_range_start 0 0 0 - colour_range_end 1 1 1 - } - - // Gravity. - affector LinearForce - { - force_vector 0 -100 0 - force_application add - } - - // Fader. - affector ColourFader - { - red -0.25 - green -0.25 - blue -0.25 - } -} -//! [manual_sample] - -// A downpour. -particle_system Examples/Rain -{ - material Examples/Droplet - particle_width 20 - particle_height 100 - cull_each true - quota 10000 - // Make common direction straight down (faster than self oriented) - billboard_type oriented_common - common_direction 0 -1 0 - - // Area emitter. - emitter Box - { - angle 0 - emission_rate 100 - time_to_live 5 - direction 0 -1 0 - velocity 50 - width 1000 - height 1000 - depth 0 - } - - // Gravity. - affector LinearForce - { - force_vector 0 -200 0 - force_application add - } - -} - -// A jet engine (of sorts). -particle_system Examples/JetEngine1 -{ - material Examples/Flare - particle_width 25 - particle_height 25 - cull_each false - quota 200 - billboard_type point - - emitter Point - { - angle 5 - emission_rate 100 - time_to_live 1 - direction 0 -1 0 - velocity_min 250 - velocity_max 300 - colour_range_start 1 1 0.5 - colour_range_end 1 0.8 0.3 - - } - affector ColourFader - { - red -0.25 - green -1 - blue -1 - } - -} -particle_system Examples/JetEngine2 -{ - material Examples/Flare - particle_width 15 - particle_height 15 - cull_each false - quota 200 - billboard_type point - - emitter Point - { - angle 3 - emission_rate 100 - time_to_live 1 - direction 0 -1 0 - velocity_min 350 - velocity_max 400 - colour_range_start 0.5 1 1 - colour_range_end 0.3 0.8 1 - - } - affector ColourFader - { - red -1 - green -1 - blue -0.5 - } - -} - -// Exudes aureola particles which float upwards around the model. -particle_system Examples/Aureola -{ - material Examples/Aureola - particle_width 200 - particle_height 200 - cull_each false - quota 100 - billboard_type perpendicular_common - common_direction 0 1 0 - common_up_vector 0 0 1 - - // Area emitter. - emitter Box - { - angle 30 - emission_rate 4 - time_to_live 5 - position 0 -100 0 - direction 0 1 0 - velocity_min 0 - velocity_max 30 - colour_range_start 0.3 0.3 0.3 0.0 - colour_range_end 0.8 0.8 0.8 0.0 - width 10 - height 10 - depth 30 - } - - // Make 'em float upwards. - affector LinearForce - { - force_vector 0 70 0 - force_application add - } - - // Fader. - affector ColourFader2 - { - red1 +0.4 - green1 +0.4 - blue1 +0.4 - alpha1 +0.7 - - red2 -0.25 - green2 -0.25 - blue2 -0.25 - alpha2 -0.3333 - - state_change 3.5 - } - - // Rotater. - affector Rotator - { - rotation_range_start 0 - rotation_range_end 360 - rotation_speed_range_start 0 - rotation_speed_range_end 360 - } -} - - -particle_system Examples/Swarm -{ - quota 3000 - material Examples/Flare2 - particle_width 12 - particle_height 24 - cull_each true - renderer billboard - sorted true - local_space false - billboard_type oriented_self - - emitter Box - { - angle 180 - colour 1 1 1 1 - colour_range_start 1 1 1 1 - colour_range_end 1 1 1 1 - direction 0 1 0 - emission_rate 30 - position 0 0 0 - velocity 50 - velocity_min 50 - velocity_max 1 - time_to_live 20 - time_to_live_min 20 - time_to_live_max 20 - duration 0 - duration_min 0 - duration_max 0 - repeat_delay 0 - repeat_delay_min 0 - repeat_delay_max 0 - width 80 - height 80 - depth 80 - } - - affector ColourFader - { - red -0.05 - green 0 - blue 0 - alpha 0 - } - - affector DeflectorPlane - { - plane_point 0 -50 0 - plane_normal 0 1 0 - bounce 1 - } - - affector DeflectorPlane - { - plane_point 0 50 0 - plane_normal 0 -1 0 - bounce 1 - } - - affector DeflectorPlane - { - plane_point 50 0 0 - plane_normal -1 0 0 - bounce 1 - } - - affector DeflectorPlane - { - plane_point -50 0 0 - plane_normal 1 0 0 - bounce 1 - } - - affector DeflectorPlane - { - plane_point 0 0 50 - plane_normal 0 0 -1 - bounce 1 - } - - affector DeflectorPlane - { - plane_point 0 0 -50 - plane_normal 0 0 1 - bounce 1 - } - - affector DirectionRandomiser - { - randomness 60 - } -} - - -particle_system Examples/Snow -{ - quota 2000 - material Examples/Flare - particle_width 4 - particle_height 4 - cull_each true - renderer billboard - sorted true - local_space false - billboard_type point - - emitter Box - { - angle 0 - colour 1 1 1 1 - colour_range_start 1 1 1 1 - colour_range_end 1 1 1 1 - direction 0 -1 0 - emission_rate 100 - position 0 200 0 - velocity 20 - velocity_min 20 - velocity_max 20 - time_to_live 20 - time_to_live_min 20 - time_to_live_max 20 - duration 0 - duration_min 0 - duration_max 0 - repeat_delay 0 - repeat_delay_min 0 - repeat_delay_max 0 - width 200 - height 200 - depth 1 - } - - affector DirectionRandomiser - { - randomness 10 - } -} - - diff --git a/Samples/Media/particle/emitted_emitter.particle b/Samples/Media/particle/emitted_emitter.particle deleted file mode 100644 index 774c332ee28..00000000000 --- a/Samples/Media/particle/emitted_emitter.particle +++ /dev/null @@ -1,56 +0,0 @@ -// Example emitted emitters -particle_system Examples/Fireworks -{ - material Examples/Flare - point_rendering false - particle_width 10 - particle_height 10 - cull_each false - quota 1000 - emit_emitter_quota 10 - billboard_type point - - // Emitter that emits multiple Point emitters with name 'explosion' - emitter Box - { - name mainEmitter - emit_emitter explosion - angle 30 - emission_rate 1000 - time_to_live 3 - direction 0 1 0 - velocity 200 - } - - // This Point emitter is emitted by the Box emitter and emits billboard particles itself - emitter Point - { - name explosion - angle 180 - emission_rate 100 - time_to_live 2 - direction 0 1 0 - velocity 80 - duration -1 - repeat_delay_min 2 - repeat_delay_max 3 - } - - // Make em float downwards - affector LinearForce - { - force_vector 0 -100 0 - force_application add - } - - // Give em some nice colours - affector ColourInterpolator - { - time0 0 - colour0 1 1 0 - time1 0.5 - colour1 1 0 0 - time2 0.9 - colour2 0 0 1 - } -} diff --git a/Samples/Media/particle/smoke.particle b/Samples/Media/particle/smoke.particle deleted file mode 100644 index 15f3658ce88..00000000000 --- a/Samples/Media/particle/smoke.particle +++ /dev/null @@ -1,44 +0,0 @@ -// Example particle systems - -// smoke -particle_system Examples/Smoke -{ - material Examples/Smoke - particle_width 35 - particle_height 35 - cull_each true - quota 500 - billboard_type point - sorted true - texture_sheet_size 3 5 - - // Area emitter - emitter Point - { - position 0 15 -15 - angle 35 - emission_rate 15 - time_to_live 4 - direction 0 1 0 - velocity_min 50 - velocity_max 80 - } - - affector TextureAnimator - { - texcoord_count 15 - duration 4 - random_offset true - } - - affector ColourImage - { - image smokecolors.png - } - - affector Scaler - { - rate 50 - } - -} diff --git a/Samples/Media/terrain.cfg b/Samples/Media/terrain.cfg deleted file mode 100644 index 5d69f11265b..00000000000 --- a/Samples/Media/terrain.cfg +++ /dev/null @@ -1,71 +0,0 @@ -# The main world texture (if you wish the terrain manager to create a material for you) -WorldTexture=terrain_texture.jpg - -# The detail texture (if you wish the terrain manager to create a material for you) -DetailTexture=terrain_detail.jpg - -#number of times the detail texture will tile in a terrain tile -DetailTile=3 - -# Heightmap source -PageSource=Heightmap - -# Heightmap-source specific settings -Heightmap.image=terrain.png - -# If you use RAW, fill in the below too -# RAW-specific setting - size (horizontal/vertical) -#Heightmap.raw.size=513 -# RAW-specific setting - bytes per pixel (1 = 8bit, 2=16bit) -#Heightmap.raw.bpp=2 - -# How large is a page of tiles (in vertices)? Must be (2^n)+1 -PageSize=513 - -# How large is each tile? Must be (2^n)+1 and be smaller than PageSize -TileSize=65 - -# The maximum error allowed when determining which LOD to use -MaxPixelError=3 - -# The size of a terrain page, in world units -PageWorldX=1500 -PageWorldZ=1500 -# Maximum height of the terrain -MaxHeight=100 - -# Upper LOD limit -MaxMipMapLevel=5 - -#VertexNormals=yes -#VertexColors=yes -#UseTriStrips=yes - -# Use vertex program to morph LODs, if available -VertexProgramMorph=yes - -# The proportional distance range at which the LOD morph starts to take effect -# This is as a proportion of the distance between the current LODs effective range, -# and the effective range of the next lower LOD -LODMorphStart=0.2 - -# This following section is for if you want to provide your own terrain shading routine -# Note that since you define your textures within the material this makes the -# WorldTexture and DetailTexture settings redundant - -# The name of the vertex program parameter you wish to bind the morph LOD factor to -# this is 0 when there is no adjustment (highest) to 1 when the morph takes it completely -# to the same position as the next lower LOD -# USE THIS IF YOU USE HIGH-LEVEL VERTEX PROGRAMS WITH LOD MORPHING -#MorphLODFactorParamName=morphFactor - -# The index of the vertex program parameter you wish to bind the morph LOD factor to -# this is 0 when there is no adjustment (highest) to 1 when the morph takes it completely -# to the same position as the next lower LOD -# USE THIS IF YOU USE ASSEMBLER VERTEX PROGRAMS WITH LOD MORPHING -#MorphLODFactorParamIndex=4 - -# The name of the material you will define to shade the terrain -#CustomMaterialName=TestTerrainMaterial - - diff --git a/Samples/Media/thumbnails/README.md b/Samples/Media/thumbnails/README.md deleted file mode 100644 index 24e7538db36..00000000000 --- a/Samples/Media/thumbnails/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Sample Thumbnails - -- The resolution is `128x128px`, which is a power of 2 (POT). -- However, the images are displayed at `128x96px`, which corresponds to an aspect of 4:3, but is not POT. -- Therefore, you should crop the image at `171x128px` and resize accordingly \ No newline at end of file diff --git a/Samples/Media/thumbnails/thumb_atomicc.png b/Samples/Media/thumbnails/thumb_atomicc.png deleted file mode 100644 index 6117ffa2f03..00000000000 Binary files a/Samples/Media/thumbnails/thumb_atomicc.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_bezier.png b/Samples/Media/thumbnails/thumb_bezier.png deleted file mode 100644 index 18e95b88ba1..00000000000 Binary files a/Samples/Media/thumbnails/thumb_bezier.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_bsp.png b/Samples/Media/thumbnails/thumb_bsp.png deleted file mode 100644 index bf4eab7cf86..00000000000 Binary files a/Samples/Media/thumbnails/thumb_bsp.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_bullet.png b/Samples/Media/thumbnails/thumb_bullet.png deleted file mode 100644 index 1beac1beb64..00000000000 Binary files a/Samples/Media/thumbnails/thumb_bullet.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_bump.png b/Samples/Media/thumbnails/thumb_bump.png deleted file mode 100644 index 9a6a36eaba6..00000000000 Binary files a/Samples/Media/thumbnails/thumb_bump.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_camtrack.png b/Samples/Media/thumbnails/thumb_camtrack.png deleted file mode 100644 index 10cbf7a59bc..00000000000 Binary files a/Samples/Media/thumbnails/thumb_camtrack.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_cel.png b/Samples/Media/thumbnails/thumb_cel.png deleted file mode 100644 index 899ec4a2d99..00000000000 Binary files a/Samples/Media/thumbnails/thumb_cel.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_char.png b/Samples/Media/thumbnails/thumb_char.png deleted file mode 100644 index 800d93a3384..00000000000 Binary files a/Samples/Media/thumbnails/thumb_char.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_comp.png b/Samples/Media/thumbnails/thumb_comp.png deleted file mode 100644 index c1b77105afb..00000000000 Binary files a/Samples/Media/thumbnails/thumb_comp.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_compute.png b/Samples/Media/thumbnails/thumb_compute.png deleted file mode 100644 index 56d982254d5..00000000000 Binary files a/Samples/Media/thumbnails/thumb_compute.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_csm.png b/Samples/Media/thumbnails/thumb_csm.png deleted file mode 100644 index 6f1fd91add8..00000000000 Binary files a/Samples/Media/thumbnails/thumb_csm.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_cubemap.png b/Samples/Media/thumbnails/thumb_cubemap.png deleted file mode 100644 index f82e2129c41..00000000000 Binary files a/Samples/Media/thumbnails/thumb_cubemap.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_deferred.png b/Samples/Media/thumbnails/thumb_deferred.png deleted file mode 100644 index 55a3c24c3ec..00000000000 Binary files a/Samples/Media/thumbnails/thumb_deferred.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_dualquaternionskinning.png b/Samples/Media/thumbnails/thumb_dualquaternionskinning.png deleted file mode 100644 index 89b34bad134..00000000000 Binary files a/Samples/Media/thumbnails/thumb_dualquaternionskinning.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_dyntex.png b/Samples/Media/thumbnails/thumb_dyntex.png deleted file mode 100644 index 12deac38620..00000000000 Binary files a/Samples/Media/thumbnails/thumb_dyntex.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_error.png b/Samples/Media/thumbnails/thumb_error.png deleted file mode 100644 index 056d139775d..00000000000 Binary files a/Samples/Media/thumbnails/thumb_error.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_facial.png b/Samples/Media/thumbnails/thumb_facial.png deleted file mode 100644 index 173bf732df5..00000000000 Binary files a/Samples/Media/thumbnails/thumb_facial.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_fresnel.png b/Samples/Media/thumbnails/thumb_fresnel.png deleted file mode 100644 index d1030625898..00000000000 Binary files a/Samples/Media/thumbnails/thumb_fresnel.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_grass.png b/Samples/Media/thumbnails/thumb_grass.png deleted file mode 100644 index 431de625749..00000000000 Binary files a/Samples/Media/thumbnails/thumb_grass.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_hlms.png b/Samples/Media/thumbnails/thumb_hlms.png deleted file mode 100644 index 4271579d080..00000000000 Binary files a/Samples/Media/thumbnails/thumb_hlms.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_imgui.png b/Samples/Media/thumbnails/thumb_imgui.png deleted file mode 100644 index 8c0ce030716..00000000000 Binary files a/Samples/Media/thumbnails/thumb_imgui.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_instancing.png b/Samples/Media/thumbnails/thumb_instancing.png deleted file mode 100644 index 2c02d99001a..00000000000 Binary files a/Samples/Media/thumbnails/thumb_instancing.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_isosurf.png b/Samples/Media/thumbnails/thumb_isosurf.png deleted file mode 100644 index 1399f6c2835..00000000000 Binary files a/Samples/Media/thumbnails/thumb_isosurf.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_lighting.png b/Samples/Media/thumbnails/thumb_lighting.png deleted file mode 100644 index 5d6db48ae8e..00000000000 Binary files a/Samples/Media/thumbnails/thumb_lighting.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_lightshafts.png b/Samples/Media/thumbnails/thumb_lightshafts.png deleted file mode 100644 index 989efd47689..00000000000 Binary files a/Samples/Media/thumbnails/thumb_lightshafts.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_meshlod.png b/Samples/Media/thumbnails/thumb_meshlod.png deleted file mode 100644 index 4c36a25fb5e..00000000000 Binary files a/Samples/Media/thumbnails/thumb_meshlod.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_newinstancing.png b/Samples/Media/thumbnails/thumb_newinstancing.png deleted file mode 100644 index 680e0742d1b..00000000000 Binary files a/Samples/Media/thumbnails/thumb_newinstancing.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_ocean.png b/Samples/Media/thumbnails/thumb_ocean.png deleted file mode 100644 index f035d52cd9f..00000000000 Binary files a/Samples/Media/thumbnails/thumb_ocean.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_particlegs.png b/Samples/Media/thumbnails/thumb_particlegs.png deleted file mode 100644 index c52a50b6b89..00000000000 Binary files a/Samples/Media/thumbnails/thumb_particlegs.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_particles.png b/Samples/Media/thumbnails/thumb_particles.png deleted file mode 100644 index f7c1f424ce8..00000000000 Binary files a/Samples/Media/thumbnails/thumb_particles.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_pbr.png b/Samples/Media/thumbnails/thumb_pbr.png deleted file mode 100644 index 4dfaf5a960e..00000000000 Binary files a/Samples/Media/thumbnails/thumb_pbr.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_pcz.png b/Samples/Media/thumbnails/thumb_pcz.png deleted file mode 100644 index d2b78557306..00000000000 Binary files a/Samples/Media/thumbnails/thumb_pcz.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_playpen.png b/Samples/Media/thumbnails/thumb_playpen.png deleted file mode 100644 index 5157584a5e7..00000000000 Binary files a/Samples/Media/thumbnails/thumb_playpen.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_rectlight.png b/Samples/Media/thumbnails/thumb_rectlight.png deleted file mode 100644 index 6ddaf0b9adb..00000000000 Binary files a/Samples/Media/thumbnails/thumb_rectlight.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_shadersystem.png b/Samples/Media/thumbnails/thumb_shadersystem.png deleted file mode 100644 index 05e25f8bd3e..00000000000 Binary files a/Samples/Media/thumbnails/thumb_shadersystem.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_shadersystemmultilight.png b/Samples/Media/thumbnails/thumb_shadersystemmultilight.png deleted file mode 100644 index b6e9d28aa9c..00000000000 Binary files a/Samples/Media/thumbnails/thumb_shadersystemmultilight.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_shadows.png b/Samples/Media/thumbnails/thumb_shadows.png deleted file mode 100644 index 2443721dd4d..00000000000 Binary files a/Samples/Media/thumbnails/thumb_shadows.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_skelanim.png b/Samples/Media/thumbnails/thumb_skelanim.png deleted file mode 100644 index d72ff5d48ae..00000000000 Binary files a/Samples/Media/thumbnails/thumb_skelanim.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_skybox.png b/Samples/Media/thumbnails/thumb_skybox.png deleted file mode 100644 index 0aba3efa9fc..00000000000 Binary files a/Samples/Media/thumbnails/thumb_skybox.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_skydome.png b/Samples/Media/thumbnails/thumb_skydome.png deleted file mode 100644 index 3b0ec022954..00000000000 Binary files a/Samples/Media/thumbnails/thumb_skydome.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_skyplane.png b/Samples/Media/thumbnails/thumb_skyplane.png deleted file mode 100644 index 5ff249ce753..00000000000 Binary files a/Samples/Media/thumbnails/thumb_skyplane.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_smoke.png b/Samples/Media/thumbnails/thumb_smoke.png deleted file mode 100644 index 78417c9b829..00000000000 Binary files a/Samples/Media/thumbnails/thumb_smoke.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_spheremap.png b/Samples/Media/thumbnails/thumb_spheremap.png deleted file mode 100644 index 4156349e635..00000000000 Binary files a/Samples/Media/thumbnails/thumb_spheremap.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_ssao.png b/Samples/Media/thumbnails/thumb_ssao.png deleted file mode 100644 index 699e61202f1..00000000000 Binary files a/Samples/Media/thumbnails/thumb_ssao.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_terrain.png b/Samples/Media/thumbnails/thumb_terrain.png deleted file mode 100644 index 6634af17be4..00000000000 Binary files a/Samples/Media/thumbnails/thumb_terrain.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_tessellation.png b/Samples/Media/thumbnails/thumb_tessellation.png deleted file mode 100644 index 81347085796..00000000000 Binary files a/Samples/Media/thumbnails/thumb_tessellation.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_texarray.png b/Samples/Media/thumbnails/thumb_texarray.png deleted file mode 100644 index 2566f09ad71..00000000000 Binary files a/Samples/Media/thumbnails/thumb_texarray.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_texfx.png b/Samples/Media/thumbnails/thumb_texfx.png deleted file mode 100644 index f982ef9e962..00000000000 Binary files a/Samples/Media/thumbnails/thumb_texfx.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_texturedfog.png b/Samples/Media/thumbnails/thumb_texturedfog.png deleted file mode 100644 index f7e11a489a0..00000000000 Binary files a/Samples/Media/thumbnails/thumb_texturedfog.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_trans.png b/Samples/Media/thumbnails/thumb_trans.png deleted file mode 100644 index 6957e7faefa..00000000000 Binary files a/Samples/Media/thumbnails/thumb_trans.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_visual_tests.png b/Samples/Media/thumbnails/thumb_visual_tests.png deleted file mode 100644 index c1edb4e5af7..00000000000 Binary files a/Samples/Media/thumbnails/thumb_visual_tests.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_voltex.png b/Samples/Media/thumbnails/thumb_voltex.png deleted file mode 100644 index 055f2084217..00000000000 Binary files a/Samples/Media/thumbnails/thumb_voltex.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_volumecsg.png b/Samples/Media/thumbnails/thumb_volumecsg.png deleted file mode 100644 index 29aefae2f2e..00000000000 Binary files a/Samples/Media/thumbnails/thumb_volumecsg.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_volumeterrain.png b/Samples/Media/thumbnails/thumb_volumeterrain.png deleted file mode 100644 index d8dd4a7aed1..00000000000 Binary files a/Samples/Media/thumbnails/thumb_volumeterrain.png and /dev/null differ diff --git a/Samples/Media/thumbnails/thumb_water.png b/Samples/Media/thumbnails/thumb_water.png deleted file mode 100644 index 973b88bbab2..00000000000 Binary files a/Samples/Media/thumbnails/thumb_water.png and /dev/null differ diff --git a/Samples/Media/volumeTerrain/triplanarReference.material b/Samples/Media/volumeTerrain/triplanarReference.material deleted file mode 100644 index 74e5a72d8c4..00000000000 --- a/Samples/Media/volumeTerrain/triplanarReference.material +++ /dev/null @@ -1,18 +0,0 @@ -material triplanarReference -{ - technique - { - pass - { - ambient 0.41 0.41 0.41 - diffuse 1.0 1.0 1.0 - rtshader_system - { - lighting_stage ffp - // Texturescale, Plateau-size (0 to 0.57, not bigger to avoid division by zero!), transition-speed - // Texture from x, from y, from z - triplanarTexturing 0.05 0.2 2.0 Rock20_diffspec.dds Ground37_diffspec.dds Ground23_col.jpg - } - } - } -} diff --git a/Samples/Media/volumeTerrain/volumeTerrain.cfg b/Samples/Media/volumeTerrain/volumeTerrain.cfg deleted file mode 100644 index 3698ebe0975..00000000000 --- a/Samples/Media/volumeTerrain/volumeTerrain.cfg +++ /dev/null @@ -1,44 +0,0 @@ -# World data -source = volumeTerrainBig.dds -# World size of the data -sourceDimensions = 384 384 384 -# World scale -scale = 10.0 -# Whether to use trilinear interpolation for the source or not -trilinearValue = true -# Whether to use trilinear interpolation for the gradients of the source or not -trilinearGradient = false -# Whether to use sobel filtering for the gradients of the source or not -sobelGradient = false -# Whether to load the terrain asynchronously -async = false - -# Spatial part to scan and build the volume meshes from -scanFrom = 0 0 0 -scanTo = 384 384 384 - -# Amount of LOD level -level = 5 -# The first LOD level to create geometry for. For scenarios where the lower levels won't be visible anyway. 0 is the default and switches this off. -createGeometryFromLevel = 3 -# The geometric error of LOD level with the highest detail * errorMultiplicator -baseError = 1.8 -# The multiplicator between LOD levels. errorOfCurrentLevel = baseError * levelIndex * errorMultiplicator -errorMultiplicator = 0.9 -# The maximum accepted screen space error when chosing the LOD levels to render -maxScreenSpaceError = 20 - -# Whether or not to create the visualization of the octrees -createOctreeVisualization = false -# Whether or not to create the visualization of the dual grids -createDualGridVisualization = false -# The factor defining the length of the skirts. Less means more triangles and less loading time, but if too small, cracks can occure. -skirtFactor = 1.0 - -# The material of the chunks -material = triplanarReference - -# The material for the lowest 3 levels of the chunktree. This is set after the global material above. -materialOfLevel0 = triplanarReference -materialOfLevel1 = triplanarReference -materialOfLevel2 = triplanarReference diff --git a/Samples/Media/volumeTerrain/volumeTerrainBig.zip b/Samples/Media/volumeTerrain/volumeTerrainBig.zip deleted file mode 100644 index 1329a424143..00000000000 Binary files a/Samples/Media/volumeTerrain/volumeTerrainBig.zip and /dev/null differ diff --git a/Samples/OceanDemo/include/MaterialControls.h b/Samples/OceanDemo/include/MaterialControls.h deleted file mode 100644 index 42c0b2479c2..00000000000 --- a/Samples/OceanDemo/include/MaterialControls.h +++ /dev/null @@ -1,113 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#ifndef __MaterialControls_H__ -#define __MaterialControls_H__ - -#include "OgreString.h" - -enum ShaderValType -{ - GPU_VERTEX, GPU_FRAGMENT, MAT_SPECULAR, MAT_DIFFUSE, MAT_AMBIENT, MAT_SHININESS, MAT_EMISSIVE -}; - -//--------------------------------------------------------------------------- -struct ShaderControl -{ - Ogre::String Name; - Ogre::String ParamName; - ShaderValType ValType; - float MinVal; - float MaxVal; - size_t ElementIndex; - mutable size_t PhysicalIndex; - - float getRange(void) const { return MaxVal - MinVal; } - float convertParamToScrollPosition(const float val) const { return val - MinVal; } - float convertScrollPositionToParam(const float val) const { return val + MinVal; } -}; - -typedef std::vector ShaderControlsContainer; -typedef ShaderControlsContainer::iterator ShaderControlIterator; -// used for materials that have user controls - -//--------------------------------------------------------------------------- -class MaterialControls -{ -public: - MaterialControls(const Ogre::String& displayName, const Ogre::String& materialName) - : mDisplayName(displayName) - , mMaterialName(materialName) - { - }; - - ~MaterialControls(void){} - - const Ogre::String& getDisplayName(void) const { return mDisplayName; } - const Ogre::String& getMaterialName(void) const { return mMaterialName; } - size_t getShaderControlCount(void) const { return mShaderControlsContainer.size(); } - const ShaderControl& getShaderControl(const size_t idx) const - { - assert( idx < mShaderControlsContainer.size() ); - return mShaderControlsContainer[idx]; - } - /** add a new control by passing a string parameter - - @param - params is a string using the following format: - ", , , , , " - - is the string displayed for the control name on screen - is the name of the variable in the shader - can be GPU_VERTEX, GPU_FRAGMENT - minimum value that parameter can be - maximum value that parameter can be - index into the the float array of the parameter. All GPU parameters are assumed to be float[4]. - - */ - void addControl(const Ogre::String& params); - -protected: - - Ogre::String mDisplayName; - Ogre::String mMaterialName; - - ShaderControlsContainer mShaderControlsContainer; -}; - -typedef std::vector MaterialControlsContainer; -typedef MaterialControlsContainer::iterator MaterialControlsIterator; - -//--------------------------------------------------------------------------- -/** loads material shader controls from a configuration file - A .controls file is made up of the following: - - [] - material = - control = , , , , , - - is what is displayed in the material combo box. - is the name of the material in the material script. - control is the shader control associated with the material. The order - of the contol definitions in the .controls file determines their order - when displayed in the controls window. - - you can have multiple .controls files or put them all in one. -*/ -void loadMaterialControlsFile(MaterialControlsContainer& controlsContainer, const Ogre::String& filename); -/** load all control files found in resource paths -*/ -void loadAllMaterialControlFiles(MaterialControlsContainer& controlsContainer); - -#endif // __MaterialControls_H__ diff --git a/Samples/OceanDemo/include/OceanDemo.h b/Samples/OceanDemo/include/OceanDemo.h deleted file mode 100644 index 01e62ffd074..00000000000 --- a/Samples/OceanDemo/include/OceanDemo.h +++ /dev/null @@ -1,479 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#ifndef _Sample_Ocean_H_ -#define _Sample_Ocean_H_ - -#include "SdkSample.h" -#include "SamplePlugin.h" -#include "MaterialControls.h" -#include "OgreBillboard.h" - -using namespace Ogre; -using namespace OgreBites; - -#define MINSPEED .150f -#define MOVESPEED 30 -#define MAXSPEED 1.800f - -#define CONTROLS_PER_PAGE 5 - -class _OgreSampleClassExport Sample_Ocean : public SdkSample -{ -public: - Sample_Ocean(); -protected: - //Things from the frame listener - Ogre::Vector3 mTranslateVector; - int mSceneDetailIndex; - float mUpdateFreq; - bool mSpinLight; - // just to stop toggles flipping too fast - Ogre::TextureFilterOptions mFiltering; - int mAniso; - - Ogre::SceneNode* mMainNode; - Ogre::Entity* mOceanSurfaceEnt; - - size_t mCurrentMaterial; - size_t mCurrentPage; - size_t mNumPages; - Ogre::MaterialPtr mActiveMaterial; - Ogre::Pass* mActivePass; - Ogre::GpuProgramPtr mActiveFragmentProgram; - Ogre::GpuProgramPtr mActiveVertexProgram; - Ogre::GpuProgramParametersSharedPtr mActiveFragmentParameters; - Ogre::GpuProgramParametersSharedPtr mActiveVertexParameters; - Real mRotateSpeed; - Slider* mShaderControls[CONTROLS_PER_PAGE]; - - ShaderControlsContainer mShaderControlContainer; - MaterialControlsContainer mMaterialControlsContainer; - - void setupGUI(); - void setupScene(); - void setupContent() override; - void cleanupContent() override; - - void sliderMoved(Slider* slider) override; - void buttonHit(OgreBites::Button* button) override; - void checkBoxToggled(CheckBox* box) override; - void itemSelected(SelectMenu* menu) override; - void changePage(int nextPage = -1); - bool frameRenderingQueued(const FrameEvent& evt) override; -}; - -/********************************************************************** - Static declarations -**********************************************************************/ -// Lights -#define NUM_LIGHTS 1 - -// the light -Ogre::Light* mLights[NUM_LIGHTS]; -// billboards for lights -Ogre::BillboardSet* mLightFlareSets[NUM_LIGHTS]; -Ogre::Billboard* mLightFlares[NUM_LIGHTS]; -// Positions for lights -Ogre::Vector3 mLightPositions[NUM_LIGHTS] = -{ - Ogre::Vector3(00, 400, 00) -}; -// Base orientations of the lights -Ogre::Real mLightRotationAngles[NUM_LIGHTS] = { 35 }; -Ogre::Vector3 mLightRotationAxes[NUM_LIGHTS] = { - Ogre::Vector3::UNIT_X -}; -// Rotation speed for lights, degrees per second -Ogre::Real mLightSpeeds[NUM_LIGHTS] = { 30}; - -// Colours for the lights -Ogre::ColourValue mDiffuseLightColours[NUM_LIGHTS] = -{ - Ogre::ColourValue(0.6, 0.6, 0.6) -}; - -Ogre::ColourValue mSpecularLightColours[NUM_LIGHTS] = -{ - Ogre::ColourValue(0.5, 0.5, 0.5) -}; - -// Which lights are enabled -bool mLightState[NUM_LIGHTS] = -{ - true -}; - -// the light nodes -Ogre::SceneNode* mLightNodes[NUM_LIGHTS]; -// the light node pivots -Ogre::SceneNode* mLightPivots[NUM_LIGHTS]; - - -Sample_Ocean::Sample_Ocean() -{ - mInfo["Title"] = "Ocean"; - mInfo["Description"] = "An example demonstrating ocean rendering using shaders."; - mInfo["Thumbnail"] = "thumb_ocean.png"; - mInfo["Category"] = "Environment"; -} -/************************************************************************* - Sample_Ocean Methods -*************************************************************************/ -void Sample_Ocean::cleanupContent() -{ - MeshManager::getSingleton().remove("OceanSurface", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - // get rid of the shared pointers before shutting down ogre or exceptions occur - mActiveFragmentProgram.reset(); - mActiveFragmentParameters.reset(); - mActiveVertexProgram.reset(); - mActiveVertexParameters.reset(); - mActiveMaterial.reset(); -} - -//-------------------------------------------------------------------------- -void Sample_Ocean::setupGUI(void) -{ - SelectMenu* selectMenu = mTrayMgr->createLongSelectMenu( - TL_TOPLEFT, "MaterialSelectMenu", "Material", 300, 200, 5); - - for (size_t i=0; iaddItem(mMaterialControlsContainer[i].getDisplayName()); - } - - mTrayMgr->createCheckBox(TL_TOPLEFT, "SpinLightButton", "Spin Light", 175)->setChecked(true); - - mTrayMgr->createButton(TL_TOPRIGHT, "PageButtonControl", "Page", 175); - - for (size_t i=0; icreateThickSlider(TL_TOPRIGHT, - "ShaderControlSlider" + StringConverter::toString(i), "Control", 256, 80, 0, 1, 100); - } - - selectMenu->selectItem(0); - mTrayMgr->showCursor(); - -} -//-------------------------------------------------------------------------- -void Sample_Ocean::setupContent(void) -{ - loadAllMaterialControlFiles(mMaterialControlsContainer); - setupScene(); - setupGUI(); - - // Position it at 500 in Z direction - mCameraNode->setPosition(Ogre::Vector3(0,0,0)); - // Look back along -Z - mCameraNode->lookAt(Ogre::Vector3(0,0,-300), Ogre::Node::TS_PARENT); - mCamera->setNearClipDistance(1); - - setDragLook(true); -} - -void Sample_Ocean::setupScene() -{ - // Set ambient light - mSceneMgr->setAmbientLight(Ogre::ColourValue(0.3, 0.3, 0.3)); - mSceneMgr->setSkyBox(true, "SkyBox", 1000); - - mMainNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - - for (unsigned int i = 0; i < NUM_LIGHTS; ++i) - { - mLightPivots[i] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mLightPivots[i]->rotate(mLightRotationAxes[i], Ogre::Angle(mLightRotationAngles[i])); - // Create a light, use default parameters - mLights[i] = mSceneMgr->createLight("Light" + Ogre::StringConverter::toString(i)); - mLights[i]->setDiffuseColour(mDiffuseLightColours[i]); - mLights[i]->setSpecularColour(mSpecularLightColours[i]); - mLights[i]->setVisible(mLightState[i]); - //mLights[i]->setAttenuation(400, 0.1 , 1 , 0); - // Attach light - mLightPivots[i]->createChildSceneNode(mLightPositions[i])->attachObject(mLights[i]); - // Create billboard for light - mLightFlareSets[i] = mSceneMgr->createBillboardSet("Flare" + Ogre::StringConverter::toString(i)); - mLightFlareSets[i]->setMaterialName("LightFlare"); - mLightPivots[i]->attachObject(mLightFlareSets[i]); - mLightFlares[i] = mLightFlareSets[i]->createBillboard(mLightPositions[i]); - mLightFlares[i]->setColour(mDiffuseLightColours[i]); - mLightFlareSets[i]->setVisible(mLightState[i]); - } - - // move the camera a bit right and make it look at the knot - mCameraNode->translate(Ogre::Vector3(50, 0, 100), Node::TS_LOCAL); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); - - // Define a plane mesh that will be used for the ocean surface - Ogre::Plane oceanSurface; - oceanSurface.normal = Ogre::Vector3::UNIT_Y; - oceanSurface.d = 20; - Ogre::MeshManager::getSingleton().createPlane("OceanSurface", - Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - oceanSurface, - 1000, 1000, 50, 50, true, 1, 1, 1, Ogre::Vector3::UNIT_Z); - - mOceanSurfaceEnt = mSceneMgr->createEntity( "OceanSurface", "OceanSurface" ); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(mOceanSurfaceEnt); -} - - -//-------------------------------------------------------------------------- -void Sample_Ocean::sliderMoved(Slider* slider) -{ - using namespace Ogre; - - int sliderIndex = -1; - for (int i=0; igetValue(); - - if(mActivePass) - { - switch(ActiveShaderDef.ValType) - { - case GPU_VERTEX: - case GPU_FRAGMENT: - { - GpuProgramParametersSharedPtr activeParameters = - (ActiveShaderDef.ValType == GPU_VERTEX) ? - mActiveVertexParameters : mActiveFragmentParameters; - - if(activeParameters) - { - activeParameters->_writeRawConstant( - ActiveShaderDef.PhysicalIndex + ActiveShaderDef.ElementIndex, val); - } - } - break; - - case MAT_SPECULAR: - { - // get the specular values from the material pass - ColourValue OldSpec(mActivePass->getSpecular()); - OldSpec[ActiveShaderDef.ElementIndex] = val; - mActivePass->setSpecular( OldSpec ); - } - - break; - - case MAT_DIFFUSE: - { - // get the specular values from the material pass - ColourValue OldSpec(mActivePass->getDiffuse()); - OldSpec[ActiveShaderDef.ElementIndex] = val; - mActivePass->setDiffuse( OldSpec ); - } - break; - - case MAT_AMBIENT: - { - // get the specular values from the material pass - ColourValue OldSpec(mActivePass->getAmbient()); - OldSpec[ActiveShaderDef.ElementIndex] = val; - mActivePass->setAmbient( OldSpec ); - } - break; - - case MAT_SHININESS: - // get the specular values from the material pass - mActivePass->setShininess( val ); - break; - - case MAT_EMISSIVE: - break; - } - } -} - -//-------------------------------------------------------------------------- -void Sample_Ocean::changePage(int pageNum /* = -1 : toggle */) -{ - if (mMaterialControlsContainer.empty()) return; - mCurrentPage = (pageNum == -1) ? (mCurrentPage+1) % mNumPages : pageNum; - - static char pageText[64]; - sprintf(pageText, "Parameters %zu / %zu", mCurrentPage+1, mNumPages); - static_cast(mTrayMgr->getWidget("PageButtonControl"))->setCaption(pageText); - - if(mActiveMaterial && !mActiveMaterial->getSupportedTechniques().empty()) - { - Ogre::Technique* currentTechnique = mActiveMaterial->getSupportedTechniques().front(); - if(currentTechnique) - { - mActivePass = currentTechnique->getPass(0); - if(mActivePass) - { - if (mActivePass->hasFragmentProgram()) - { - mActiveFragmentProgram = mActivePass->getFragmentProgram(); - mActiveFragmentParameters = mActivePass->getFragmentProgramParameters(); - } - if (mActivePass->hasVertexProgram()) - { - mActiveVertexProgram = mActivePass->getVertexProgram(); - mActiveVertexParameters = mActivePass->getVertexProgramParameters(); - } - - size_t activeControlCount = mMaterialControlsContainer[mCurrentMaterial].getShaderControlCount(); - - size_t startControlIndex = mCurrentPage * CONTROLS_PER_PAGE; - int numControls = static_cast(activeControlCount - startControlIndex); - if (numControls <= 0) - { - mCurrentPage = 0; - startControlIndex = 0; - numControls = (int)activeControlCount; - } - - for (size_t i=0; ishow(); - size_t controlIndex = startControlIndex + i; - const ShaderControl& ActiveShaderDef = mMaterialControlsContainer[mCurrentMaterial].getShaderControl(controlIndex); - shaderControlSlider->setRange(ActiveShaderDef.MinVal, ActiveShaderDef.MaxVal, 50, false); - shaderControlSlider->setCaption(ActiveShaderDef.Name); - - float uniformVal = 0.0; - switch(ActiveShaderDef.ValType) - { - case GPU_VERTEX: - case GPU_FRAGMENT: - { - Ogre::GpuProgramParametersSharedPtr activeParameters = - (ActiveShaderDef.ValType == GPU_VERTEX) ? - mActiveVertexParameters : mActiveFragmentParameters; - if(activeParameters) - { - // use param name to get index : use appropriate parameters ptr - const Ogre::GpuConstantDefinition& def = - activeParameters->getConstantDefinition(ActiveShaderDef.ParamName); - ActiveShaderDef.PhysicalIndex = def.physicalIndex; - // use index to get RealConstantEntry - const float* pFloat = activeParameters->getFloatPointer(ActiveShaderDef.PhysicalIndex); - // set position of ScrollWidget as param value - uniformVal = pFloat[ActiveShaderDef.ElementIndex]; - } - } - break; - - case MAT_SPECULAR: - { - // get the specular values from the material pass - - Ogre::ColourValue OldSpec(mActivePass->getSpecular()); - uniformVal = OldSpec[ActiveShaderDef.ElementIndex]; - } - break; - - case MAT_DIFFUSE: - { - // get the diffuse values from the material pass - - Ogre::ColourValue OldSpec(mActivePass->getDiffuse()); - uniformVal = OldSpec[ActiveShaderDef.ElementIndex]; - } - break; - - case MAT_AMBIENT: - { - // get the ambient values from the material pass - - Ogre::ColourValue OldSpec(mActivePass->getAmbient()); - uniformVal = OldSpec[ActiveShaderDef.ElementIndex]; - } - break; - - case MAT_SHININESS: - { - // get the ambient values from the material pass - uniformVal = mActivePass->getShininess(); - } - - break; - - case MAT_EMISSIVE: - { - // get the ambient values from the material pass - - //ColourValue OldSpec(mActivePass->gete()); - //activeScrollWidget->setScrollPosition( OldSpec.val[ActiveShaderDef->ElementIndex] ); - } - break; - } - shaderControlSlider->setValue(uniformVal); - - } - else - { - shaderControlSlider->hide(); - } - } - } - } - } - -} -void Sample_Ocean::itemSelected(SelectMenu *menu) -{ - //Only one selection menu - the material one - mCurrentMaterial = menu->getSelectionIndex(); - mActiveMaterial = Ogre::MaterialManager::getSingleton().getByName( mMaterialControlsContainer[mCurrentMaterial].getMaterialName() ); - mActiveMaterial->load(); - size_t numShaders = mMaterialControlsContainer[mCurrentMaterial].getShaderControlCount(); - mNumPages = (numShaders / CONTROLS_PER_PAGE) + (numShaders % CONTROLS_PER_PAGE == 0 ? 0 : 1); - changePage(0); - - if (mOceanSurfaceEnt) - mOceanSurfaceEnt->setMaterialName(mMaterialControlsContainer[mCurrentMaterial].getMaterialName()); -} -bool Sample_Ocean::frameRenderingQueued(const FrameEvent& evt) -{ - mRotateSpeed = evt.timeSinceLastFrame * 20; - if(mSpinLight) - { - mLightPivots[0]->rotate(mLightRotationAxes[0], Ogre::Angle(mRotateSpeed * 2.0f)); - } - return SdkSample::frameRenderingQueued(evt); -} -void Sample_Ocean::buttonHit(OgreBites::Button* button) -{ - //Only one button - change page - changePage(); -} - -void Sample_Ocean::checkBoxToggled(CheckBox* cb) -{ - //Only one checkbox - mSpinLight = cb->isChecked(); -} - -#endif // end _Sample_Ocean_H_ diff --git a/Samples/OceanDemo/src/MaterialControls.cpp b/Samples/OceanDemo/src/MaterialControls.cpp deleted file mode 100644 index 3f5d1a224c4..00000000000 --- a/Samples/OceanDemo/src/MaterialControls.cpp +++ /dev/null @@ -1,132 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#include "MaterialControls.h" -#include "OgreLogManager.h" -#include "OgreStringVector.h" -#include "OgreStringConverter.h" -#include "OgreConfigFile.h" -#include "OgreResourceGroupManager.h" -#include "OgreException.h" -#include "OgreMaterial.h" -#include "OgreTechnique.h" -#include "OgreMaterialManager.h" - -/******************************************************************************** - MaterialControls Methods -*********************************************************************************/ -void MaterialControls::addControl(const Ogre::String& params) -{ - // params is a string containing using the following format: - // ", , , , , " - - // break up long string into components - Ogre::StringVector vecparams = Ogre::StringUtil::split(params, ","); - - // if there are not five elements then log error and move on - if (vecparams.size() != 6) - { - Ogre::LogManager::getSingleton().logMessage( - "Incorrect number of parameters passed in params string for MaterialControls::addControl()", Ogre::LML_CRITICAL); - - return; - } - - ShaderControl newControl; - Ogre::StringUtil::trim(vecparams[0]); - newControl.Name = vecparams[0]; - - Ogre::StringUtil::trim(vecparams[1]); - newControl.ParamName = vecparams[1]; - - Ogre::StringUtil::trim(vecparams[2]); - if (vecparams[2] == "GPU_VERTEX") - newControl.ValType = GPU_VERTEX; - else if (vecparams[2] == "GPU_FRAGMENT") - newControl.ValType = GPU_FRAGMENT; - - newControl.MinVal = Ogre::StringConverter::parseReal(vecparams[3]); - newControl.MaxVal = Ogre::StringConverter::parseReal(vecparams[4]); - newControl.ElementIndex = Ogre::StringConverter::parseInt(vecparams[5]); - - mShaderControlsContainer.push_back(newControl); - -} - -void loadMaterialControlsFile(MaterialControlsContainer& controlsContainer, const Ogre::String& filename) -{ - // Load material controls from config file - Ogre::ConfigFile cf; - - try - { - - cf.loadFromResourceSystem(filename, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "\t;=", true); - - // Go through all sections & controls in the file - Ogre::String secName, typeName, materialName, dataString; - - Ogre::ConfigFile::SettingsBySection_::const_iterator seci; - for(seci = cf.getSettingsBySection().begin(); seci != cf.getSettingsBySection().end(); ++seci) { - secName = seci->first; - const Ogre::ConfigFile::SettingsMultiMap& settings = seci->second; - if (!secName.empty()) - { - materialName = cf.getSetting("material", secName); - - Ogre::MaterialPtr curMat = Ogre::MaterialManager::getSingleton().getByName(materialName); - curMat->load(); - Ogre::Technique * curTec = curMat->getBestTechnique(); - if (!curTec || !curTec->isSupported()) - { - continue; - } - - MaterialControls newMaaterialControls(secName, materialName); - controlsContainer.push_back(newMaaterialControls); - - size_t idx = controlsContainer.size() - 1; - - Ogre::ConfigFile::SettingsMultiMap::const_iterator i; - - for (i = settings.begin(); i != settings.end(); ++i) - { - typeName = i->first; - dataString = i->second; - if (typeName == "control") - controlsContainer[idx].addControl(dataString); - } - } - } - - Ogre::LogManager::getSingleton().logMessage( "Material Controls setup" ); - } - catch (Ogre::Exception& e) - { - // Guess the file didn't exist - } -} - - -void loadAllMaterialControlFiles(MaterialControlsContainer& controlsContainer) -{ - Ogre::StringVectorPtr fileStringVector = Ogre::ResourceGroupManager::getSingleton().findResourceNames( "General", "*.controls"); - Ogre::StringVector::iterator controlsFileNameIterator = fileStringVector->begin(); - - while ( controlsFileNameIterator != fileStringVector->end() ) - { - loadMaterialControlsFile(controlsContainer, *controlsFileNameIterator); - ++controlsFileNameIterator; - } -} diff --git a/Samples/PCZTestApp/include/PCZTestApp.h b/Samples/PCZTestApp/include/PCZTestApp.h deleted file mode 100644 index 9109648a6cd..00000000000 --- a/Samples/PCZTestApp/include/PCZTestApp.h +++ /dev/null @@ -1,317 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#include - -#include -#include -#include -#include - -#include "RoomObject.h" - -using namespace Ogre; -using namespace OgreBites; - -class Sample_PCZTest : public SdkSample -{ - SceneNode * buildingNode; - Vector3 buildingTranslate; - RaySceneQuery* raySceneQuery; - MovableObject* targetMO; -public: - Sample_PCZTest() : raySceneQuery(0), targetMO(0) - { - mInfo["Title"] = "PCZTest"; - mInfo["Description"] = "Demonstrates use of the Portal Connected Zone(PCZ) Scene Manager Plugin."; - mInfo["Thumbnail"] = "thumb_pcz.png"; - mInfo["Category"] = "Environment"; - mInfo["Help"] = "Note that there is no collision detection and transitioning from zone to zone " - "will only work correctly if the user moves the camera through the doorways (as " - "opposed to going through the walls)."; - } - - void cleanupContent() override - { - delete raySceneQuery; - } - - void createSceneManager(void) override - { - // Create the SceneManager, in this case a generic one - mSceneMgr = mRoot->createSceneManager("PCZSceneManager"); - // initialize the scene manager using terrain as default zone - String zoneTypeName = "ZoneType_Default"; - ((PCZSceneManager*)mSceneMgr)->init(zoneTypeName); - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - mShaderGenerator->addSceneManager(mSceneMgr); -#endif - - if(mOverlaySystem) - mSceneMgr->addRenderQueueListener(mOverlaySystem); - } - - // utility function to create terrain zones easily - PCZone * createTerrainZone(String & zoneName, String & terrain_cfg) - { - // load terrain into the terrain zone - PCZone * terrainZone = ((PCZSceneManager*)mSceneMgr)->createZone(String("ZoneType_Terrain"), zoneName); - terrainZone->notifyCameraCreated(mCamera); - ((PCZSceneManager*)mSceneMgr)->setZoneGeometry( zoneName, (PCZSceneNode*)mSceneMgr->getRootSceneNode(), terrain_cfg ); - - // create aab portal(s) around the terrain - String portalName; - Vector3 corners[2]; - AxisAlignedBox aabb; - - // make portal from terrain to default - Portal * p; - terrainZone->getAABB(aabb); - portalName = Ogre::String("PortalFrom"+zoneName+"ToDefault_Zone"); - p = ((PCZSceneManager*)mSceneMgr)->createPortal(portalName, Ogre::Portal::PORTAL_TYPE_AABB); - corners[0] = aabb.getMinimum(); - corners[1] = aabb.getMaximum(); - p->setCorner(0, corners[0]); - p->setCorner(1, corners[1]); - p->setDirection(Ogre::Vector3::NEGATIVE_UNIT_Z); // this indicates an "inward" pointing normal - // associate the portal with the terrain's main node - p->setNode(terrainZone->getEnclosureNode()); - // IMPORTANT: Update the derived values of the portal - p->updateDerivedValues(); - // add the portal to the zone - terrainZone->_addPortal(p); - - // make portal from default to terrain - portalName = Ogre::String("PortalFromDefault_ZoneTo"+zoneName); - Portal * p2; - p2 = ((PCZSceneManager*)mSceneMgr)->createPortal(portalName, Ogre::Portal::PORTAL_TYPE_AABB); - corners[0] = aabb.getMinimum(); - corners[1] = aabb.getMaximum(); - p2->setCorner(0, corners[0]); - p2->setCorner(1, corners[1]); - p2->setDirection(Ogre::Vector3::UNIT_Z); // this indicates an "outward" pointing normal - // associate the portal with the terrain's main node - p2->setNode(terrainZone->getEnclosureNode()); - // IMPORTANT: Update the derived values of the portal - p2->updateDerivedValues(); - // add the portal to the zone - ((PCZSceneManager*)mSceneMgr)->getDefaultZone()->_addPortal(p2); - - // connect the portals manually - p->setTargetPortal(p2); - p2->setTargetPortal(p); - p->setTargetZone(((PCZSceneManager*)mSceneMgr)->getDefaultZone()); - p2->setTargetZone(terrainZone); - - return terrainZone; - } - - SceneNode* createAntiPortal(const String& name) - { - // Create antiportal test. - SceneNode* antiPortalNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - PCZone* defaultZone = ((PCZSceneManager*)mSceneMgr)->getDefaultZone(); - AntiPortal* antiPortal = ((PCZSceneManager*)mSceneMgr)->createAntiPortal(name); - antiPortal->setCorner(0, Vector3(100.0f, 100.0f, 0.0f)); - antiPortal->setCorner(1, Vector3(100.0f, -100.0f, 0.0f)); - antiPortal->setCorner(2, Vector3(-100.0f, -100.0f, 0.0f)); - antiPortal->setCorner(3, Vector3(-100.0f, 100.0f, 0.0f)); - antiPortalNode->attachObject(antiPortal); - defaultZone->_addAntiPortal(antiPortal); - ((PCZSceneManager*)mSceneMgr)->addPCZSceneNode((PCZSceneNode*)antiPortalNode, defaultZone); - - // Anti portal prop. - Entity* planeEnt = mSceneMgr->createEntity(name + "Entity", SceneManager::PT_PLANE); - planeEnt->setMaterialName("TransparentGlassTinted"); - antiPortalNode->attachObject(planeEnt); - - return antiPortalNode; - } - - void setupContent(void) override - { - mCameraMan->setTopSpeed(15); - mCamera->setNearClipDistance(2); - - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.25, 0.25, 0.25)); - - // Create a skybox - mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox", 500 ); - // put the skybox node in the default zone - ((PCZSceneManager*)mSceneMgr)->setSkyZone(0); - - // Create a light - Light* l = mSceneMgr->createLight("MainLight"); - l->setAttenuation(500, 0.5, 1.0, 0.0); - // Accept default settings: point light, white diffuse, just set position - // attach light to a scene node so the PCZSM can handle it properly (zone-wise) - SceneNode * lightNode = mCameraNode->createChildSceneNode("light_Node"); - lightNode->attachObject(l); - - // Fog - // NB it's VERY important to set this before calling setWorldGeometry - // because the vertex program picked will be different - ColourValue fadeColour(0.101, 0.125, 0.1836); - mSceneMgr->setFog( FOG_LINEAR, fadeColour, .001, 500, 1000); - mViewport->setBackgroundColour(fadeColour); - - // create a terrain zone -// String terrain_cfg("terrain.cfg"); -// String zoneName("Terrain1_Zone"); -// PCZone * terrainZone = createTerrainZone(zoneName, terrain_cfg); - -/* // Create another terrain zone - terrain_cfg = "terrain.cfg"; - zoneName = "Terrain2_Zone"; - terrainZone = createTerrainZone(zoneName, terrain_cfg); - // move second terrain next to first terrain - terrainZone->getEnclosureNode()->setPosition(1500, 0, 0); - - // Create another terrain zone - terrain_cfg = "terrain.cfg"; - zoneName = "Terrain3_Zone"; - terrainZone = createTerrainZone(zoneName, terrain_cfg); - // move terrain next to first terrain - terrainZone->getEnclosureNode()->setPosition(0, 0, 1500); - - // Create another terrain zone - terrain_cfg = "terrain.cfg"; - zoneName = "Terrain4_Zone"; - terrainZone = createTerrainZone(zoneName, terrain_cfg); - // move terrain next to first terrain - terrainZone->getEnclosureNode()->setPosition(-1500, 0, 0); - - // Create another terrain zone - terrain_cfg = "terrain.cfg"; - zoneName = "Terrain5_Zone"; - terrainZone = createTerrainZone(zoneName, terrain_cfg); - // move terrain next to first terrain - terrainZone->getEnclosureNode()->setPosition(0, 0, -1500); - - // Create another terrain zone - terrain_cfg = "terrain.cfg"; - zoneName = "Terrain6_Zone"; - terrainZone = createTerrainZone(zoneName, terrain_cfg); - // move terrain next to first terrain - terrainZone->getEnclosureNode()->setPosition(1500, 0, 1500); - - // Create another terrain zone - terrain_cfg = "terrain.cfg"; - zoneName = "Terrain7_Zone"; - terrainZone = createTerrainZone(zoneName, terrain_cfg); - // move terrain next to first terrain - terrainZone->getEnclosureNode()->setPosition(-1500, 0, -1500); - - // Create another terrain zone - terrain_cfg = "terrain.cfg"; - zoneName = "Terrain8_Zone"; - terrainZone = createTerrainZone(zoneName, terrain_cfg); - // move terrain next to first terrain - terrainZone->getEnclosureNode()->setPosition(-1500, 0, 1500); - - // Create another terrain zone - terrain_cfg = "terrain.cfg"; - zoneName = "Terrain9_Zone"; - terrainZone = createTerrainZone(zoneName, terrain_cfg); - // move terrain next to first terrain - terrainZone->getEnclosureNode()->setPosition(1500, 0, -1500); -*/ - // set far clip plane to one terrain zone width (we have a LOT of terrain here, so we need to do far clipping!) - mCamera->setFarClipDistance(1500); - - // create test buildinig - RoomObject roomObj; - buildingNode = roomObj.createTestBuilding(mSceneMgr, String("1")); - buildingNode->setPosition(500, 165, 570); - //Ogre::Radian r = Radian(3.1416/7.0); - //buildingNode->rotate(Vector3::UNIT_Y, r); - - // create another test buildinig - RoomObject roomObj2; - buildingNode = roomObj2.createTestBuilding(mSceneMgr, String("2")); - buildingNode->setPosition(400, 165, 570); - //Ogre::Radian r = Radian(3.1416/7.0); - //buildingNode->rotate(Vector3::UNIT_Y, r); - - SceneNode* antiPortalNode1 = createAntiPortal("AntiPortal1"); - antiPortalNode1->setPosition(Vector3(450, 200, 800)); - antiPortalNode1->setScale(0.5f, 0.5f, 0.5f); - - SceneNode* antiPortalNode2 = createAntiPortal("AntiPortal2"); - antiPortalNode2->setPosition(Vector3(460, 200, 700)); - antiPortalNode2->setScale(0.5f, 0.5f, 0.5f); - - // Position camera in the center of the building - mCameraNode->setPosition(buildingNode->getPosition()); - // Update bounds for camera - mCameraNode->_updateBounds(); - - // create the ray scene query - raySceneQuery = mSceneMgr->createRayQuery( - Ray(mCamera->getParentNode()->getPosition(), Vector3::NEGATIVE_UNIT_Z)); - raySceneQuery->setSortByDistance(true, 5); - - } - - /** - a simple Ray Scene query which highlights the 'furthest' object in - front of the camera (not very visible inside the castle since the room the - camera is in is usually what gets highlighted). It's just a simple test of - ray scene queries. Scene Queries will (at least, should) traverse portals. - */ - bool frameRenderingQueued( const FrameEvent& evt ) override - { - SdkSample::frameRenderingQueued(evt); -#if 0 - buildingTranslate = Vector3(0,0,0); - if( mKeyboard->isKeyDown( OIS::KC_LBRACKET ) ) - { - buildingTranslate = Vector3(0,-10,0); - } - if( mKeyboard->isKeyDown( OIS::KC_RBRACKET ) ) - { - buildingTranslate = Vector3(0,10,0); - } -#endif - // test the ray scene query by showing bounding box of whatever the camera is pointing directly at - // (takes furthest hit) - static Ray updateRay; - updateRay.setOrigin(mCamera->getParentSceneNode()->getPosition()); - updateRay.setDirection(mCamera->getParentSceneNode()->getOrientation()*Vector3::NEGATIVE_UNIT_Z); - raySceneQuery->setRay(updateRay); - PCZone * zone = ((PCZSceneNode*)(mCamera->getParentSceneNode()))->getHomeZone(); - ((PCZRaySceneQuery*)raySceneQuery)->setStartZone(zone); - ((PCZRaySceneQuery*)raySceneQuery)->setExcludeNode(mCamera->getParentSceneNode()); - RaySceneQueryResult& qryResult = raySceneQuery->execute(); - RaySceneQueryResult::iterator i = qryResult.begin(); - if (i != qryResult.end()) - { - RaySceneQueryResult::reverse_iterator ri = qryResult.rbegin(); - MovableObject * mo = ri->movable; - if (targetMO != mo) - { - if (targetMO != 0) - { - targetMO->getParentSceneNode()->showBoundingBox(false); - } - targetMO = mo; - targetMO->getParentSceneNode()->showBoundingBox(true); - } - } - - return true; - } -}; diff --git a/Samples/PCZTestApp/include/RoomObject.h b/Samples/PCZTestApp/include/RoomObject.h deleted file mode 100644 index a77bea1c92a..00000000000 --- a/Samples/PCZTestApp/include/RoomObject.h +++ /dev/null @@ -1,74 +0,0 @@ -#ifndef _ROOM_OBJECT_H_ -#define _ROOM_OBJECT_H_ - -#include "OgreSceneNode.h" -#include "OgrePCZSceneManager.h" -#include - -/** - Creates a "test" room (& building) for the PCZSceneManager. The box-shaped room - can have "doorways" (rectangular openings) in any of the 6 walls, but - each doorway must have a separate portal object created for it (not - done in this class). - */ -class RoomObject -{ - enum RoomWalls - { - TOP_WALL, - BOT_WALL, - FRONT_WALL, - BACK_WALL, - LEFT_WALL, - RIGHT_WALL - }; - -private: - void addMaterial(const Ogre::String& mat, - const Ogre::ColourValue &clr, - Ogre::SceneBlendType sbt); - void createPoints(Ogre::Vector3 dimensions, - Ogre::Vector3 doorDimensions); - void createWalls(Ogre::ManualObject* room, - short doorFlags, - bool isEnclosure); - void createPortals(Ogre::SceneManager *scene, - Ogre::ManualObject* room, - Ogre::SceneNode * roomNode, - Ogre::PCZone * zone, - short doorFlags, - bool isEnclosure); - void createPortals(Ogre::SceneManager *scene, - Ogre::Entity* room, - Ogre::SceneNode * roomNode, - Ogre::PCZone * zone, - short doorFlags, - bool isEnclosure); - -private: - Ogre::Vector3 points[32]; - int mPortalCount; -public: - enum RoomDoors - { - DOOR_NONE = 0x00, - DOOR_TOP = 0x01, - DOOR_BOT = 0x02, - DOOR_FRONT = 0x04, - DOOR_BACK = 0x08, - DOOR_LEFT = 0x10, - DOOR_RIGHT = 0x20, - DOOR_ALL = 0xFF - }; - - Ogre::PCZSceneNode * createTestBuilding(Ogre::SceneManager *scene, const Ogre::String & name); - - Ogre::ManualObject*createRoom(Ogre::SceneManager *scene, - const Ogre::String &name, - short doorFlags, - bool isEnclosure, - Ogre::Vector3 dimensions, - Ogre::Vector3 doorDimensions); -}; - -#endif //--_ROOM_OBJECT_H_ diff --git a/Samples/PCZTestApp/src/RoomObject.cpp b/Samples/PCZTestApp/src/RoomObject.cpp deleted file mode 100644 index 6d0e7d7f373..00000000000 --- a/Samples/PCZTestApp/src/RoomObject.cpp +++ /dev/null @@ -1,990 +0,0 @@ -// -// -// -// Filename : RoomObject.cpp - -#include "Ogre.h" -#include "OgreMaterial.h" -#include "RoomObject.h" -#include "OgrePortal.h" - -using namespace Ogre; -static int count = 0; - -PCZSceneNode * RoomObject::createTestBuilding(Ogre::SceneManager *scene, const String & name) -{ - count++; - mPortalCount = 0; - Ogre::PCZSceneManager * pczSM = (Ogre::PCZSceneManager*)scene; - - // set points to building exterior size - createPoints(Vector3(60.0, 40.0, 60.0), Vector3(4.0, 10.0, 4.0)); - - // create the building exterior - Entity *exterior = pczSM->createEntity( name + "_building_exterior", "building_exterior.mesh" ); - - // make the enclosure a child node of the root scene node - PCZSceneNode * exteriorNode, * baseNode; - baseNode = (PCZSceneNode*)scene->getRootSceneNode()->createChildSceneNode(name +"_base_node"); - exteriorNode = (PCZSceneNode*)baseNode->createChildSceneNode(name +"_building_exterior_node", Vector3( 0.0f, 0.0f, 0.0f ) ); - exteriorNode->attachObject(exterior); - pczSM->addPCZSceneNode(exteriorNode, pczSM->getDefaultZone()); - - // create portals for the building exterior - createPortals(scene, - exterior, - exteriorNode, - pczSM->getDefaultZone(), - DOOR_FRONT|DOOR_BACK|DOOR_LEFT|DOOR_RIGHT, - true); - - // reset points to room size - createPoints(Vector3(20.0, 10.0, 20.0), Vector3(4.0, 10.0, 4.0)); - - // create an interior room - Entity *room = pczSM->createEntity( name +"_room1", "room_nzpz.mesh" ); - - // add the room as a child node to the enclosure node - PCZSceneNode * roomNode; - roomNode = (PCZSceneNode*)baseNode->createChildSceneNode( name +"_room1_node", Vector3( 0.0f, 0.0f, 20.0f ) ); - roomNode->attachObject(room); - - // room needs it's own zone - Ogre::String zoneType = "ZoneType_Default"; - Ogre::String zoneName = name +"_room1_zone"; - PCZone * newZone = pczSM->createZone(zoneType, zoneName); - newZone->setEnclosureNode(roomNode); - pczSM->addPCZSceneNode(roomNode, newZone); - - // create portals for the room - createPortals(scene, - room, - roomNode, - newZone, - DOOR_FRONT|DOOR_BACK, - false); - - // create another interior room - room = pczSM->createEntity( name +"_room2", "room_nxpxnypynzpz.mesh" ); - - // add the room as a child node to the enclosure node - roomNode = (PCZSceneNode*)baseNode->createChildSceneNode( name +"_room2_node", Vector3( 0.0f, 0.0f, 0.0f ) ); - roomNode->attachObject(room); - - // room needs it's own zone - zoneName = name +"_room2_zone"; - newZone = pczSM->createZone(zoneType, zoneName); - newZone->setEnclosureNode(roomNode); - pczSM->addPCZSceneNode(roomNode, newZone); - - // create portals for the room - createPortals(scene, - room, - roomNode, - newZone, - DOOR_FRONT|DOOR_BACK|DOOR_LEFT|DOOR_RIGHT|DOOR_TOP|DOOR_BOT, - false); - - // create another interior room - room = pczSM->createEntity( name +"_room3", "room_nzpz.mesh" ); - - // add the room as a child node to the enclosure node - roomNode = (PCZSceneNode*)baseNode->createChildSceneNode( name +"_room3_node", Vector3( 0.0f, 0.0f, -20.0f ) ); - roomNode->attachObject(room); - - // room needs it's own zone - zoneName = name +"_room3_zone"; - newZone = pczSM->createZone(zoneType, zoneName); - newZone->setEnclosureNode(roomNode); - pczSM->addPCZSceneNode(roomNode, newZone); - - // create portals for the room - createPortals(scene, - room, - roomNode, - newZone, - DOOR_FRONT|DOOR_BACK, - false); - - // create another interior room - room = pczSM->createEntity( name +"_room4", "room_nxpx.mesh" ); - - // add the room as a child node to the enclosure node - roomNode = (PCZSceneNode*)baseNode->createChildSceneNode( name +"_room4_node", Vector3( -20.0f, 0.0f, 0.0f ) ); - roomNode->attachObject(room); - - // room needs it's own zone - zoneName = name +"_room4_zone"; - newZone = pczSM->createZone(zoneType, zoneName); - newZone->setEnclosureNode(roomNode); - pczSM->addPCZSceneNode(roomNode, newZone); - - // create portals for the room - createPortals(scene, - room, - roomNode, - newZone, - DOOR_LEFT|DOOR_RIGHT, - false); - - // create another interior room - room = pczSM->createEntity( name +"_room5", "room_nxpx.mesh" ); - - // add the room as a child node to the enclosure node - roomNode = (PCZSceneNode*)baseNode->createChildSceneNode( name +"_room5_node", Vector3( 20.0f, 0.0f, 0.0f ) ); - roomNode->attachObject(room); - - // room needs it's own zone - zoneName = name +"_room5_zone"; - newZone = pczSM->createZone(zoneType, zoneName); - newZone->setEnclosureNode(roomNode); - pczSM->addPCZSceneNode(roomNode, newZone); - - // create portals for the room - createPortals(scene, - room, - roomNode, - newZone, - DOOR_LEFT|DOOR_RIGHT, - false); - - // create another interior room - room = pczSM->createEntity( name +"_room6", "ROOM_NY.mesh" ); - - // add the room as a child node to the enclosure node - roomNode = (PCZSceneNode*)baseNode->createChildSceneNode( name +"_room6_node", Vector3( 0.0f, 10.0f, 0.0f ) ); - roomNode->attachObject(room); - - // room needs it's own zone - zoneName = name +"_room6_zone"; - newZone = pczSM->createZone(zoneType, zoneName); - newZone->setEnclosureNode(roomNode); - pczSM->addPCZSceneNode(roomNode, newZone); - - // create portals for the room - createPortals(scene, - room, - roomNode, - newZone, - DOOR_BOT, - false); - - // create another interior room - room = pczSM->createEntity( name +"_room7", "ROOM_PY.mesh" ); - - // add the room as a child node to the enclosure node - roomNode = (PCZSceneNode*)baseNode->createChildSceneNode( name +"_room7_node", Vector3( 0.0f, -50.0f, 0.0f ) ); - roomNode->attachObject(room); - - // room needs it's own zone - zoneName = name +"_room7_zone"; - newZone = pczSM->createZone(zoneType, zoneName); - newZone->setEnclosureNode(roomNode); - pczSM->addPCZSceneNode(roomNode, newZone); - - // create portals for the room - createPortals(scene, - room, - roomNode, - newZone, - DOOR_TOP, - false); - - // reset points to tall room size - createPoints(Vector3(20.0, 40.0, 20.0), Vector3(4.0, 10.0, 4.0)); - - // create another interior room - room = pczSM->createEntity( name +"_room8", "room_nypy_4y.mesh" ); - - // add the room as a child node to the enclosure node - roomNode = (PCZSceneNode*)baseNode->createChildSceneNode( name +"_room8_node", Vector3( 0.0f, -25.0f, 0.0f ) ); - roomNode->attachObject(room); - - // room needs it's own zone - zoneName = name +"_room8_zone"; - newZone = pczSM->createZone(zoneType, zoneName); - newZone->setEnclosureNode(roomNode); - pczSM->addPCZSceneNode(roomNode, newZone); - - // create portals for the room - createPortals(scene, - room, - roomNode, - newZone, - DOOR_BOT|DOOR_TOP, - false); - - - // resolve portal zone pointers - pczSM->connectPortalsToTargetZonesByLocation(); - - return baseNode; -} - - -Ogre::ManualObject* RoomObject::createRoom(Ogre::SceneManager *scene, - const Ogre::String &name, - short doorFlags, - bool isEnclosure, - Ogre::Vector3 dimensions, - Ogre::Vector3 doorDimensions) -{ - addMaterial(name, Ogre::ColourValue(1,1,1,.75), Ogre::SBT_TRANSPARENT_ALPHA); - - Ogre::ManualObject* room = scene->createManualObject(name); - - room->begin(name, Ogre::RenderOperation::OT_TRIANGLE_LIST); - - // create points - createPoints(dimensions, doorDimensions); - -// Ogre::Real fade=.5; - Ogre::Real solid=.8; - Ogre::ColourValue color = ColourValue(0, 0, solid, solid); - - // copy to room - for (auto & point : points) - { - room->position(point); - room->colour(color); - } - - createWalls(room, doorFlags, isEnclosure); - - room->end(); - - return room; -} - -void RoomObject::addMaterial(const Ogre::String &mat, - const Ogre::ColourValue &clr, - Ogre::SceneBlendType sbt) -{ - static int init=false; - if(init) - return; - else - init=true; - - Ogre::MaterialPtr matptr = Ogre::MaterialManager::getSingleton().create(mat, "General"); - matptr->setReceiveShadows(false); - matptr->getTechnique(0)->setLightingEnabled(true); - matptr->getTechnique(0)->getPass(0)->setDiffuse(clr); - matptr->getTechnique(0)->getPass(0)->setAmbient(clr); - matptr->getTechnique(0)->getPass(0)->setSelfIllumination(clr); - matptr->getTechnique(0)->getPass(0)->setSceneBlending(sbt); - matptr->getTechnique(0)->getPass(0)->setLightingEnabled(false); - matptr->getTechnique(0)->getPass(0)->setVertexColourTracking(Ogre::TVC_DIFFUSE); -} - -void RoomObject::createPoints(Ogre::Vector3 dimensions, - Ogre::Vector3 doorDimensions) -{ - Ogre::Real l = dimensions.x/2; - Ogre::Real h = dimensions.y/2; - Ogre::Real w = dimensions.z/2; - -// 4 7 -// *-------* -// /| /| -// / | / | y -// / 5| 3/ 6| | -// 0*---*---*---* *-- x -// | / | / / -// | / | / z -// |/ |/ -// 1*-------*2 - - points[0] = Ogre::Vector3(-l, h, w);//0 - points[1] = Ogre::Vector3(-l, -h, w);//1 - points[2] = Ogre::Vector3(l, -h, w);//2 - points[3] = Ogre::Vector3(l, h, w);//3 - - points[4] = Ogre::Vector3(-l, h, -w);//4 - points[5] = Ogre::Vector3(-l, -h, -w);//5 - points[6] = Ogre::Vector3(l, -h, -w);//6 - points[7] = Ogre::Vector3(l, h, -w);//7 - - // doors - Ogre::Real l2 = doorDimensions.x/2; - Ogre::Real h2 = doorDimensions.y/2; - Ogre::Real w2 = doorDimensions.z/2; - - // front door - points[8] = Ogre::Vector3(-l2, h2, w);//8 - points[9] = Ogre::Vector3(-l2, -h2, w);//9 - points[10] = Ogre::Vector3(l2, -h2, w);//10 - points[11] = Ogre::Vector3(l2, h2, w);//11 - - // back door - points[12] = Ogre::Vector3(-l2, h2, -w);//12 - points[13] = Ogre::Vector3(-l2, -h2, -w);//13 - points[14] = Ogre::Vector3(l2, -h2, -w);//14 - points[15] = Ogre::Vector3(l2, h2, -w);//15 - - // top door - points[16] = Ogre::Vector3(-l2, h, -w2);//16 - points[17] = Ogre::Vector3(-l2, h, w2);//17 - points[18] = Ogre::Vector3(l2, h, w2);//18 - points[19] = Ogre::Vector3(l2, h, -w2);//19 - - // bottom door - points[20] = Ogre::Vector3(-l2, -h, -w2);//20 - points[21] = Ogre::Vector3(-l2, -h, w2);//21 - points[22] = Ogre::Vector3(l2, -h, w2);//22 - points[23] = Ogre::Vector3(l2, -h, -w2);//23 - - // left door - points[24] = Ogre::Vector3(-l, h2, w2);//24 - points[25] = Ogre::Vector3(-l, -h2, w2);//25 - points[26] = Ogre::Vector3(-l, -h2, -w2);//26 - points[27] = Ogre::Vector3(-l, h2, -w2);//27 - - // right door - points[28] = Ogre::Vector3(l, h2, w2);//28 - points[29] = Ogre::Vector3(l, -h2, w2);//29 - points[30] = Ogre::Vector3(l, -h2, -w2);//30 - points[31] = Ogre::Vector3(l, h2, -w2);//31 -} - -void RoomObject::createWalls(Ogre::ManualObject* room, - short doorFlags, - bool isEnclosure) -{ - - if (isEnclosure) - { - if(doorFlags & DOOR_FRONT) - { - // make front wall outward facing with door - room->quad(0, 8, 11, 3); - room->quad(1, 9, 8, 0); - room->quad(2, 10, 9, 1); - room->quad(3, 11, 10, 2); - } - else - { - // make front wall outward facing without door - room->quad(0, 1, 2, 3); - } - if(doorFlags & DOOR_BACK) - { - // make back wall outward facing with door - room->quad(7, 15, 12, 4); - room->quad(6, 14, 15, 7); - room->quad(5, 13, 14, 6); - room->quad(4, 12, 13, 5); - } - else - { - // make back wall outward facing without door - room->quad(7, 6, 5, 4); - } - if(doorFlags & DOOR_TOP) - { - // make top wall outward facing with door - room->quad(0, 17, 16, 4); - room->quad(4, 16, 19, 7); - room->quad(7, 19, 18, 3); - room->quad(3, 18, 17, 0); - } - else - { - // make top wall outward facing without door - room->quad(0, 3, 7, 4); - } - if(doorFlags & DOOR_BOT) - { - // make bottom wall outward facing with door - room->quad(5, 20, 21, 1); - room->quad(6, 23, 20, 5); - room->quad(2, 22, 23, 6); - room->quad(1, 21, 22, 2); - } - else - { - // make bottom wall outward facing without door - room->quad(2, 1, 5, 6); - } - if(doorFlags & DOOR_LEFT) - { - // make left wall outward facing with door - room->quad(0, 24, 25, 1); - room->quad(4, 27, 24, 0); - room->quad(5, 26, 27, 4); - room->quad(1, 25, 26, 5); - } - else - { - // make left side wall outward facing without door - room->quad(1, 0, 4, 5); - } - if(doorFlags & DOOR_RIGHT) - { - // make right wall outward facing with door - room->quad(2, 29, 28, 3); - room->quad(6, 30, 29, 2); - room->quad(7, 31, 30, 6); - room->quad(3, 28, 31, 7); - } - else - { - // make right side wall outward facing without door - room->quad(3, 2, 6, 7); - } - } - else - { - // front back - if(doorFlags & DOOR_FRONT) - { - // make front wall inward facing with door - room->quad(3, 11, 8, 0); - room->quad(0, 8, 9, 1); - room->quad(1, 9, 10, 2); - room->quad(2, 10, 11, 3); - } - else - { - // make front wall inward facing without door - room->quad(3, 2, 1, 0); - } - if(doorFlags & DOOR_BACK) - { - // make back wall inward facing with door - room->quad(4, 12, 15, 7); - room->quad(7, 15, 14, 6); - room->quad(6, 14, 13, 5); - room->quad(5, 13, 12, 4); - } - else - { - // make back wall inward facing without door - room->quad(4, 5, 6, 7); - } - // top bottom - if(doorFlags & DOOR_TOP) - { - // make top wall inward facing with door - room->quad(4, 16, 17, 0); - room->quad(7, 19, 16, 4); - room->quad(3, 18, 19, 7); - room->quad(0, 17, 18, 3); - } - else - { - // make top wall inward facing without door - room->quad(4, 7, 3, 0); - } - if(doorFlags & DOOR_BOT) - { - // make bottom wall inward facing with door - room->quad(1, 21, 20, 5); - room->quad(5, 20, 23, 6); - room->quad(6, 23, 22, 2); - room->quad(2, 22, 21, 1); - } - else - { - // make bottom wall inward facing without door - room->quad(6, 5, 1, 2); - } - // end caps - if(doorFlags & DOOR_LEFT) - { - // make left wall inward facing with door - room->quad(1, 25, 24, 0); - room->quad(0, 24, 27, 4); - room->quad(4, 27, 26, 5); - room->quad(5, 26, 25, 1); - } - else - { - // make left side wall inward facing without door - room->quad(5, 4, 0, 1); - } - if(doorFlags & DOOR_RIGHT) - { - // make right wall inward facing with door - room->quad(3, 28, 29, 2); - room->quad(2, 29, 30, 6); - room->quad(6, 30, 31, 7); - room->quad(7, 31, 28, 3); - } - else - { - // make right side wall inward facing without door - room->quad(7, 6, 2, 3); - } - } -} - -// Create portals for every door -void RoomObject::createPortals(Ogre::SceneManager *scene, - Ogre::ManualObject* room, - Ogre::SceneNode * roomNode, - Ogre::PCZone * zone, - short doorFlags, - bool isEnclosure) -{ - Ogre::String portalName; - Vector3 corners[4]; - - if (isEnclosure) - { - if(doorFlags & DOOR_FRONT) - { - // set the corners to the front door corners - corners[0] = points[8]; - corners[1] = points[9]; - corners[2] = points[10]; - corners[3] = points[11]; - // create the portal - portalName = room->getName() + Ogre::String("_FrontDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_BACK) - { - // set the corners to the front door corners - corners[0] = points[15]; - corners[1] = points[14]; - corners[2] = points[13]; - corners[3] = points[12]; - // create the portal - portalName = room->getName() + Ogre::String("_BackDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_TOP) - { - // set the corners to the front door corners - corners[0] = points[16]; - corners[1] = points[17]; - corners[2] = points[18]; - corners[3] = points[19]; - // create the portal - portalName = room->getName() + Ogre::String("_TopDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_BOT) - { - // set the corners to the front door corners - corners[0] = points[23]; - corners[1] = points[22]; - corners[2] = points[21]; - corners[3] = points[20]; - // create the portal - portalName = room->getName() + Ogre::String("_BottomDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_LEFT) - { - // set the corners to the front door corners - corners[0] = points[27]; - corners[1] = points[26]; - corners[2] = points[25]; - corners[3] = points[24]; - // create the portal - portalName = room->getName() + Ogre::String("_LeftDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_RIGHT) - { - // set the corners to the front door corners - corners[0] = points[28]; - corners[1] = points[29]; - corners[2] = points[30]; - corners[3] = points[31]; - // create the portal - portalName = room->getName() + Ogre::String("_RightDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - } - else - { - if(doorFlags & DOOR_FRONT) - { - // set the corners to the front door corners - corners[0] = points[11]; - corners[1] = points[10]; - corners[2] = points[9]; - corners[3] = points[8]; - // create the portal - portalName = room->getName() + Ogre::String("_FrontDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_BACK) - { - // set the corners to the front door corners - corners[0] = points[12]; - corners[1] = points[13]; - corners[2] = points[14]; - corners[3] = points[15]; - // create the portal - portalName = room->getName() + Ogre::String("_BackDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_TOP) - { - // set the corners to the front door corners - corners[0] = points[19]; - corners[1] = points[18]; - corners[2] = points[17]; - corners[3] = points[16]; - // create the portal - portalName = room->getName() + Ogre::String("_TopDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_BOT) - { - // set the corners to the front door corners - corners[0] = points[20]; - corners[1] = points[21]; - corners[2] = points[22]; - corners[3] = points[23]; - // create the portal - portalName = room->getName() + Ogre::String("_BottomDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_LEFT) - { - // set the corners to the front door corners - corners[0] = points[24]; - corners[1] = points[25]; - corners[2] = points[26]; - corners[3] = points[27]; - // create the portal - portalName = room->getName() + Ogre::String("_LeftDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_RIGHT) - { - // set the corners to the front door corners - corners[0] = points[31]; - corners[1] = points[30]; - corners[2] = points[29]; - corners[3] = points[28]; - // create the portal - portalName = room->getName() + Ogre::String("_RightDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - } -} - -// Create portals for every door -void RoomObject::createPortals(Ogre::SceneManager *scene, - Ogre::Entity* room, - Ogre::SceneNode * roomNode, - Ogre::PCZone * zone, - short doorFlags, - bool isEnclosure) -{ - Ogre::String portalName; - Vector3 corners[4]; - - if (isEnclosure) - { - if(doorFlags & DOOR_FRONT) - { - // set the corners to the front door corners - corners[0] = points[8]; - corners[1] = points[9]; - corners[2] = points[10]; - corners[3] = points[11]; - // create the portal - portalName = room->getName() + Ogre::String("_FrontDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_BACK) - { - // set the corners to the front door corners - corners[0] = points[15]; - corners[1] = points[14]; - corners[2] = points[13]; - corners[3] = points[12]; - // create the portal - portalName = room->getName() + Ogre::String("_BackDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_TOP) - { - // set the corners to the front door corners - corners[0] = points[16]; - corners[1] = points[17]; - corners[2] = points[18]; - corners[3] = points[19]; - // create the portal - portalName = room->getName() + Ogre::String("_TopDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_BOT) - { - // set the corners to the front door corners - corners[0] = points[23]; - corners[1] = points[22]; - corners[2] = points[21]; - corners[3] = points[20]; - // create the portal - portalName = room->getName() + Ogre::String("_BottomDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_LEFT) - { - // set the corners to the front door corners - corners[0] = points[27]; - corners[1] = points[26]; - corners[2] = points[25]; - corners[3] = points[24]; - // create the portal - portalName = room->getName() + Ogre::String("_LeftDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_RIGHT) - { - // set the corners to the front door corners - corners[0] = points[28]; - corners[1] = points[29]; - corners[2] = points[30]; - corners[3] = points[31]; - // create the portal - portalName = room->getName() + Ogre::String("_RightDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - } - else - { - if(doorFlags & DOOR_FRONT) - { - // set the corners to the front door corners - corners[0] = points[11]; - corners[1] = points[10]; - corners[2] = points[9]; - corners[3] = points[8]; - // create the portal - portalName = room->getName() + Ogre::String("_FrontDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_BACK) - { - // set the corners to the front door corners - corners[0] = points[12]; - corners[1] = points[13]; - corners[2] = points[14]; - corners[3] = points[15]; - // create the portal - portalName = room->getName() + Ogre::String("_BackDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_TOP) - { - // set the corners to the front door corners - corners[0] = points[19]; - corners[1] = points[18]; - corners[2] = points[17]; - corners[3] = points[16]; - // create the portal - portalName = room->getName() + Ogre::String("_TopDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_BOT) - { - // set the corners to the front door corners - corners[0] = points[20]; - corners[1] = points[21]; - corners[2] = points[22]; - corners[3] = points[23]; - // create the portal - portalName = room->getName() + Ogre::String("_BottomDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_LEFT) - { - // set the corners to the front door corners - corners[0] = points[24]; - corners[1] = points[25]; - corners[2] = points[26]; - corners[3] = points[27]; - // create the portal - portalName = room->getName() + Ogre::String("_LeftDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - if(doorFlags & DOOR_RIGHT) - { - // set the corners to the front door corners - corners[0] = points[31]; - corners[1] = points[30]; - corners[2] = points[29]; - corners[3] = points[28]; - // create the portal - portalName = room->getName() + Ogre::String("_RightDoorPortal"); - Portal * p = ((PCZSceneManager*)scene)->createPortal(portalName); - p->setCorners(corners); - // associate the portal with the roomnode - p->setNode(roomNode); - // add the portal to the zone - zone->_addPortal(p); - // update derived values for the portal - p->updateDerivedValues(); - } - } -} diff --git a/Samples/ParticleGS/include/ParticleGS.h b/Samples/ParticleGS/include/ParticleGS.h deleted file mode 100644 index ff0b7527b53..00000000000 --- a/Samples/ParticleGS/include/ParticleGS.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef __Sample_ParticleGS_H__ -#define __Sample_ParticleGS_H__ - - -#include "ProceduralManualObject.h" -#include "OgreRenderToVertexBuffer.h" -#include "RandomTools.h" -#include "SamplePlugin.h" -#include "SdkSample.h" - -// #define LOG_GENERATED_BUFFER -namespace OgreBites { -using namespace Ogre; - -class _OgreSampleClassExport Sample_ParticleGS : public SdkSample -{ - public: - Sample_ParticleGS(); - - protected: - - void createProceduralParticleSystem(); - void testCapabilities(const RenderSystemCapabilities* caps) override; - void setupContent(void) override; - void cleanupContent() override; -#ifdef LOG_GENERATED_BUFFER - bool frameEnded(const FrameEvent& evt); -#endif - ProceduralManualObject* mParticleSystem; -}; -} -#endif diff --git a/Samples/ParticleGS/include/ProceduralManualObject.h b/Samples/ParticleGS/include/ProceduralManualObject.h deleted file mode 100644 index eee00d66ff3..00000000000 --- a/Samples/ParticleGS/include/ProceduralManualObject.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - - You may use this sample code for anything you like, it is not covered by the - same license as the rest of the engine. - ----------------------------------------------------------------------------- -*/ - -#ifndef __PROCEDURAL_MANUAL_OBJECT_H__ -#define __PROCEDURAL_MANUAL_OBJECT_H__ - -#include "OgreManualObject.h" -#include "OgreSimpleRenderable.h" -#include "OgreRenderToVertexBuffer.h" - -namespace Ogre -{ - class ProceduralManualObject : public SimpleRenderable - { - public: - ProceduralManualObject() {} - virtual ~ProceduralManualObject() {} - - void setRenderToVertexBuffer(const RenderToVertexBufferSharedPtr& r2vbObject) - { mR2vbObject = r2vbObject; } - const RenderToVertexBufferSharedPtr& getRenderToVertexBuffer() - { return mR2vbObject; } - - void _updateRenderQueue(RenderQueue* queue) override; - void getRenderOperation(RenderOperation& op) override { mR2vbObject->getRenderOperation(op); } - - // Delegate to the manual object. - Real getBoundingRadius(void) const override { return 0; } - Real getSquaredViewDepth(const Camera* cam) const override { return 0; } - - protected: - RenderToVertexBufferSharedPtr mR2vbObject; - }; - -} -#endif diff --git a/Samples/ParticleGS/include/RandomTools.h b/Samples/ParticleGS/include/RandomTools.h deleted file mode 100644 index 6bec729a10e..00000000000 --- a/Samples/ParticleGS/include/RandomTools.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef __RANDOM_TOOLS_H__ -#define __RANDOM_TOOLS_H__ - -#include "OgreTexture.h" - -class RandomTools -{ -public: - static Ogre::TexturePtr generateRandomVelocityTexture(); -}; - -#endif diff --git a/Samples/ParticleGS/src/ParticleGS.cpp b/Samples/ParticleGS/src/ParticleGS.cpp deleted file mode 100644 index ebbf9b06174..00000000000 --- a/Samples/ParticleGS/src/ParticleGS.cpp +++ /dev/null @@ -1,180 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - - You may use this sample code for anything you like, it is not covered by the - same license as the rest of the engine. - ----------------------------------------------------------------------------- -*/ -/* - ----------------------------------------------------------------------------- - Filename: ParticleGS.cpp - Description: Demonstrates the use of the geometry shader and render to vertex - buffer to create a particle system that is entirely calculated on the GPU. - Partial implementation of ParticlesGS example from Microsoft's DirectX 10 - SDK : http://msdn.microsoft.com/en-us/library/ee416421.aspx - ----------------------------------------------------------------------------- -*/ - -#include "ParticleGS.h" - -using namespace Ogre; -using namespace OgreBites; - -namespace OgreBites { - -#ifdef LOG_GENERATED_BUFFER -struct FireworkParticle -{ - float pos[3]; - float timer; - float type; - float vel[3]; -}; -#endif - - Sample_ParticleGS::Sample_ParticleGS() - { - mInfo["Title"] = "Geometry Shader Particle System"; - mInfo["Description"] = "A demo of particle systems using geometry shaders and render to vertex buffers."; - mInfo["Thumbnail"] = "thumb_particlegs.png"; - mInfo["Category"] = "Effects"; - } - - void Sample_ParticleGS::createProceduralParticleSystem() - { - mParticleSystem = new ProceduralManualObject(); - mParticleSystem->_notifyManager(mSceneMgr); - MaterialPtr mat = MaterialManager::getSingleton().getByName("Ogre/ParticleGS/Display", "General"); - mParticleSystem->setMaterial(mat); - - // Generate the geometry that will seed the particle system. - ManualObject* particleSystemSeed = mSceneMgr->createManualObject("ParticleSeed"); - // This needs to be the initial launcher particle. - particleSystemSeed->begin("Ogre/ParticleGS/Display", RenderOperation::OT_POINT_LIST); - particleSystemSeed->position(0,0,0); // Position - particleSystemSeed->textureCoord(1); // Timer - particleSystemSeed->textureCoord(0); // Type - particleSystemSeed->textureCoord(0,0,0); // Velocity - particleSystemSeed->end(); - - // Generate the RenderToBufferObject. - auto r2vb = HardwareBufferManager::getSingleton().createRenderToVertexBuffer(); - r2vb->setRenderToBufferMaterialName("Ogre/ParticleGS/Generate"); - - // Apply the random texture. - TexturePtr randomTexture = RandomTools::generateRandomVelocityTexture(); - r2vb->getRenderToBufferMaterial() - ->getTechnique(0) - ->getPass(0) - ->getTextureUnitState("RandomTexture") - ->setTexture(randomTexture); - - r2vb->setOperationType(RenderOperation::OT_POINT_LIST); - r2vb->setMaxVertexCount(16000); - r2vb->setResetsEveryUpdate(false); - VertexDeclaration* vertexDecl = r2vb->getVertexDeclaration(); - // Define input / feedback variables. - size_t offset = 0; - // Position - offset += vertexDecl->addElement(0, offset, VET_FLOAT3, VES_POSITION).getSize(); - // Timer - offset += vertexDecl->addElement(0, offset, VET_FLOAT1, VES_TEXTURE_COORDINATES, 0).getSize(); - // Type - offset += vertexDecl->addElement(0, offset, VET_FLOAT1, VES_TEXTURE_COORDINATES, 1).getSize(); - // Velocity - vertexDecl->addElement(0, offset, VET_FLOAT3, VES_TEXTURE_COORDINATES, 2).getSize(); - - // Bind the two together. - r2vb->setSourceRenderable(particleSystemSeed->getSections()[0]); - mParticleSystem->setRenderToVertexBuffer(r2vb); - - // Set bounds. - AxisAlignedBox aabb; - aabb.setMinimum(-100,-100,-100); - aabb.setMaximum(100,100,100); - mParticleSystem->setBoundingBox(aabb); - } - - void Sample_ParticleGS::testCapabilities(const RenderSystemCapabilities* caps) - { - requireMaterial("Ogre/ParticleGS/Generate"); - } - - void Sample_ParticleGS::setupContent(void) - { - mCameraNode->setPosition(0,35,-100); - mCameraNode->lookAt(Vector3(0,35,0), Node::TS_PARENT); - - mSceneMgr->setAmbientLight(ColourValue(0.7, 0.7, 0.7)); - - createProceduralParticleSystem(); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(mParticleSystem); - // mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(mParticleSystem->getManualObject()); - - // Add an ogre head to the scene. - SceneNode* ogreHeadSN = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - Entity *ogreHead = mSceneMgr->createEntity("head", "ogrehead.mesh"); - ogreHeadSN->scale(0.1,0.1,0.1); - ogreHeadSN->yaw(Degree(180)); - ogreHeadSN->attachObject(ogreHead); - - // Add a plane to the scene. - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 100; - MeshManager::getSingleton().createPlane("Myplane", - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane, - 1500,1500,20,20,true,1,60,60,Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("Examples/Rockwall"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,95,0))->attachObject(pPlaneEnt); - } - - void Sample_ParticleGS::cleanupContent() - { - delete mParticleSystem; - mParticleSystem = 0; - - MeshManager::getSingleton().remove("Myplane", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - } - -#ifdef LOG_GENERATED_BUFFER - bool Sample_ParticleGS::frameEnded(const FrameEvent& evt) - { - // This will only work if the vertex buffer usage is dynamic - // (see R2VB implementation). - LogManager::getSingleton().getDefaultLog()->stream() << - "Particle system for frame " << Root::getSingleton().getNextFrameNumber(); - RenderOperation renderOp; - mParticleSystem->getRenderToVertexBuffer()->getRenderOperation(renderOp); - const HardwareVertexBufferSharedPtr& vertexBuffer = - renderOp.vertexData->vertexBufferBinding->getBuffer(0); - - assert(vertexBuffer->getVertexSize() == sizeof(FireworkParticle)); - FireworkParticle* particles = static_cast - (vertexBuffer->lock(HardwareBuffer::HBL_READ_ONLY)); - int vertexCount = renderOp.vertexData->vertexCount; - - for (size_t i = 0; i < renderOp.vertexData->vertexCount; i++) - { - FireworkParticle& p = particles[i]; - LogManager::getSingleton().getDefaultLog()->stream() << - "FireworkParticle " << i + 1 << " : " << - "Position : " << p.pos[0] << " " << p.pos[1] << " " << p.pos[2] << " , " << - "Timer : " << p.timer << " , " << - "Type : " << p.type << " , " << - "Velocity : " << p.vel[0] << " " << p.vel[1] << " " << p.vel[2]; - } - - vertexBuffer->unlock(); - return SdkSample::frameEnded(evt); - } -#endif -} diff --git a/Samples/ParticleGS/src/ProceduralManualObject.cpp b/Samples/ParticleGS/src/ProceduralManualObject.cpp deleted file mode 100644 index a43e492e462..00000000000 --- a/Samples/ParticleGS/src/ProceduralManualObject.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - - You may use this sample code for anything you like, it is not covered by the - same license as the rest of the engine. - ----------------------------------------------------------------------------- -*/ - -#include "ProceduralManualObject.h" -#include "OgreRenderQueue.h" - -namespace Ogre -{ - //----------------------------------------------------------------------------- - void ProceduralManualObject::_updateRenderQueue(RenderQueue* queue) - { - mR2vbObject->update(mManager); - queue->addRenderable(this); - } -} diff --git a/Samples/ParticleGS/src/RandomTools.cpp b/Samples/ParticleGS/src/RandomTools.cpp deleted file mode 100644 index 3bd9e3e6706..00000000000 --- a/Samples/ParticleGS/src/RandomTools.cpp +++ /dev/null @@ -1,38 +0,0 @@ -#include "RandomTools.h" -#include "OgreTextureManager.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreRoot.h" -using namespace Ogre; - -static const int NUM_RAND_VALUES = 1024; - -TexturePtr RandomTools::generateRandomVelocityTexture() -{ - TexturePtr texPtr = TextureManager::getSingleton().createManual( - "RandomVelocityTexture", - RGN_DEFAULT, - TEX_TYPE_1D, - 1024, 1, 1, - 0, - PF_FLOAT32_RGBA, HBU_CPU_TO_GPU); - - HardwarePixelBufferSharedPtr pixelBuf = texPtr->getBuffer(); - - // Lock the buffer so we can write to it. - pixelBuf->lock(HardwareBuffer::HBL_DISCARD); - const PixelBox &pb = pixelBuf->getCurrentLock(); - - float *randomData = reinterpret_cast(pb.data); - // float randomData[NUM_RAND_VALUES * 4]; - for(int i = 0; i < NUM_RAND_VALUES * 4; i++) - { - randomData[i] = float( (rand() % 10000) - 5000 ); - } - - // PixelBox pixelBox(1024, 1, 1, PF_FLOAT32_RGBA, &randomData[0]); - // pixelBuf->blitFromMemory(pixelBox); - - pixelBuf->unlock(); - - return texPtr; -} diff --git a/Samples/Python/numpy_sample.ipynb b/Samples/Python/numpy_sample.ipynb deleted file mode 100644 index 98355a2adc0..00000000000 --- a/Samples/Python/numpy_sample.ipynb +++ /dev/null @@ -1,119 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "\n", - "!pip install ogre-python\n", - "\n", - "import matplotlib.pyplot as plt\n", - "import numpy as np\n", - "\n", - "import Ogre\n", - "import Ogre.Bites\n", - "import Ogre.RTShader\n", - "\n", - "class Application(Ogre.Bites.ApplicationContextBase):\n", - " def __init__(self):\n", - " Ogre.Bites.ApplicationContextBase.__init__(self, \"OgreColab\")\n", - "\n", - " def oneTimeConfig(self):\n", - " rs = self.getRoot().getRenderSystemByName(\"OpenGL 3+ Rendering Subsystem\")\n", - " self.getRoot().setRenderSystem(rs)\n", - " return True\n", - "\n", - " def pollEvents(self):\n", - " pass\n", - "\n", - "\n", - "ctx = Application()\n", - "ctx.initApp()\n", - "root = ctx.getRoot()\n", - "\n", - "scn_mgr = root.createSceneManager()\n", - "\n", - "shadergen = Ogre.RTShader.ShaderGenerator.getSingleton()\n", - "shadergen.addSceneManager(scn_mgr)\n", - "\n", - "# no RenderWindows are available here, so create an offscreen rendertarget and use that\n", - "w, h = 640, 480\n", - "tex = Ogre.TextureManager.getSingleton().createManual(\n", - " \"target\", Ogre.RGN_DEFAULT, Ogre.TEX_TYPE_2D, w, h, 0, Ogre.PF_BYTE_RGB,\n", - " Ogre.TU_RENDERTARGET, None)\n", - "win = tex.getBuffer().getRenderTarget()\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# this is the same code as in the numpy_sample.py example\n", - "cam = scn_mgr.createCamera(\"myCam\")\n", - "vp = win.addViewport(cam)\n", - "\n", - "# create a numpy image\n", - "arr = np.zeros((256, 256, 3), dtype=np.uint8)\n", - "arr[:, :, 1] = np.mgrid[0:256, 0:256][1]\n", - "\n", - "# convert to an Ogre image and create a texture out of it\n", - "ogre_img = Ogre.Image()\n", - "ogre_img.loadDynamicImage(arr, 256, 256, Ogre.PF_BYTE_RGB)\n", - "\n", - "Ogre.TextureManager.getSingleton().loadImage(\"gradient\", \"General\", ogre_img)\n", - "\n", - "## apply texture to a rectangle\n", - "mat = Ogre.MaterialManager.getSingleton().create(\"gradient_mat\", \"General\")\n", - "rpass = mat.getTechniques()[0].getPasses()[0]\n", - "rpass.setLightingEnabled(False)\n", - "rpass.createTextureUnitState(\"gradient\")\n", - "\n", - "rect = scn_mgr.createScreenSpaceRect(True)\n", - "rect.setCorners(-0.5, 0.5, 0.5, -0.5) # in normalized screen space\n", - "rect.setMaterial(mat)\n", - "\n", - "scn_mgr.getRootSceneNode().createChildSceneNode().attachObject(rect)\n", - "\n", - "vp.setBackgroundColour((0.3, 0.3, 0.3))\n", - "\n", - "win.update()\n", - "\n", - "## read back the pixels to a numpy array\n", - "mem = np.empty((win.getHeight(), win.getWidth(), 3), dtype=np.uint8)\n", - "pb = Ogre.PixelBox(win.getWidth(), win.getHeight(), 1, Ogre.PF_BYTE_RGB, mem)\n", - "win.copyContentsToMemory(pb, pb)\n", - "\n", - "plt.imshow(mem)\n" - ] - } - ], - "metadata": { - "interpreter": { - "hash": "767d51c1340bd893661ea55ea3124f6de3c7a262a8b4abca0554b478b1e2ff90" - }, - "kernelspec": { - "display_name": "Python 3.8.10 64-bit", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.8.10" - }, - "orig_nbformat": 4 - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/Samples/Python/numpy_sample.py b/Samples/Python/numpy_sample.py deleted file mode 100644 index da028e6a1b8..00000000000 --- a/Samples/Python/numpy_sample.py +++ /dev/null @@ -1,65 +0,0 @@ -import Ogre -import Ogre.Bites -import Ogre.RTShader - -import numpy as np -from matplotlib import pyplot - -def main(): - app = Ogre.Bites.ApplicationContext("PySample") - app.initApp() - - root = app.getRoot() - scn_mgr = root.createSceneManager() - - shadergen = Ogre.RTShader.ShaderGenerator.getSingleton() - shadergen.addSceneManager(scn_mgr) - - ## [numpy_image] - arr = np.zeros((256, 256, 3), dtype=np.uint8) - arr[:,:,1] = np.mgrid[0:256,0:256][1] - ## [numpy_image] - - ## [np_to_ogre] - ogre_img = Ogre.Image() - ogre_img.loadDynamicImage(arr, 256, 256, Ogre.PF_BYTE_RGB) - - Ogre.TextureManager.getSingleton().loadImage("gradient", "General", ogre_img) - ## [np_to_ogre] - - ## [apply_to_rect] - mat = Ogre.MaterialManager.getSingleton().create("gradient_mat", "General") - rpass = mat.getTechniques()[0].getPasses()[0] - rpass.setLightingEnabled(False) - rpass.createTextureUnitState("gradient") - - rect = scn_mgr.createScreenSpaceRect(True) - rect.setCorners(-0.5, 0.5, 0.5, -0.5) # in normalized screen space - rect.setMaterial(mat) - - scn_mgr.getRootSceneNode().createChildSceneNode().attachObject(rect) - ## [apply_to_rect] - - cam = scn_mgr.createCamera("myCam") - win = app.getRenderWindow() - vp = win.addViewport(cam) - - ## [py_to_primitive] - gray = np.array([0.3, 0.3, 0.3]) - vp.setBackgroundColour(gray) - ## [py_to_primitive] - - root.startRendering() - - ## [ogre_to_np] - mem = np.empty((win.getHeight(), win.getWidth(), 3), dtype=np.uint8) - pb = Ogre.PixelBox(win.getWidth(), win.getHeight(), 1, Ogre.PF_BYTE_RGB, mem) - win.copyContentsToMemory(pb, pb) - ## [ogre_to_np] - - ## [zero_copy_view] - pyplot.imsave("screenshot.png", mem) - ## [zero_copy_view] - -if __name__ == "__main__": - main() diff --git a/Samples/Python/opencv_aruco.py b/Samples/Python/opencv_aruco.py deleted file mode 100644 index 2f5c9a6ee75..00000000000 --- a/Samples/Python/opencv_aruco.py +++ /dev/null @@ -1,109 +0,0 @@ -import math - -import numpy as np -import cv2 - -import Ogre -import Ogre.Bites -import Ogre.RTShader - -def set_camera_intrinsics(cam, K, imsize): - cam.setAspectRatio(imsize[0]/imsize[1]) - - zNear = cam.getNearClipDistance() - top = zNear * K[1, 2] / K[1, 1] - left = -zNear * K[0, 2] / K[0, 0] - right = zNear * (imsize[0] - K[0, 2]) / K[0, 0] - bottom = -zNear * (imsize[1] - K[1, 2]) / K[1, 1] - - cam.setFrustumExtents(left, right, top, bottom) - - fovy = math.atan2(K[1, 2], K[1, 1]) + math.atan2(imsize[1] - K[1, 2], K[1, 1]) - cam.setFOVy(fovy) - -def create_image_background(scn_mgr): - tex = Ogre.TextureManager.getSingleton().create("bgtex", Ogre.RGN_DEFAULT, True) - tex.setNumMipmaps(0) - - mat = Ogre.MaterialManager.getSingleton().create("bgmat", Ogre.RGN_DEFAULT) - mat.getTechnique(0).getPass(0).createTextureUnitState().setTexture(tex) - mat.getTechnique(0).getPass(0).setDepthWriteEnabled(False) - mat.getTechnique(0).getPass(0).setLightingEnabled(False) - - rect = scn_mgr.createScreenSpaceRect(True) - rect.setMaterial(mat) - rect.setRenderQueueGroup(Ogre.RENDER_QUEUE_BACKGROUND) - scn_mgr.getRootSceneNode().attachObject(rect) - - return tex - -def main(ctx): - ## random calibration data. your mileage may vary - imsize = (800, 600) - K = cv2.getDefaultNewCameraMatrix(np.diag([800, 800, 1]), imsize, True) - - ## setup Ogre for AR - scn_mgr = ctx.getRoot().createSceneManager() - Ogre.RTShader.ShaderGenerator.getSingleton().addSceneManager(scn_mgr) - - cam = scn_mgr.createCamera("camera") - cam.setNearClipDistance(5) - ctx.getRenderWindow().addViewport(cam) - - camnode = scn_mgr.getRootSceneNode().createChildSceneNode() - # convert OpenCV to OGRE coordinate system - camnode.rotate((1, 0, 0), math.pi) - camnode.attachObject(cam) - - set_camera_intrinsics(cam, K, imsize) - bgtex = create_image_background(scn_mgr) - - ## setup 3D scene - scn_mgr.setAmbientLight((.1, .1, .1)) - scn_mgr.getRootSceneNode().createChildSceneNode().attachObject(scn_mgr.createLight()) - - marker_node = scn_mgr.getRootSceneNode().createChildSceneNode() - mesh_node = marker_node.createChildSceneNode() - mesh_node.attachObject(scn_mgr.createEntity("Sinbad.mesh")) - mesh_node.rotate((1, 0, 0), math.pi/2) - mesh_node.translate((0, 0, 5)) - mesh_node.setVisible(False) - - ## video capture - cap = cv2.VideoCapture(0) - cap.set(cv2.CAP_PROP_FRAME_WIDTH, imsize[0]) - cap.set(cv2.CAP_PROP_FRAME_HEIGHT, imsize[1]) - - ## aruco - adict = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_50) - cv2.imshow("marker", cv2.aruco.drawMarker(adict, 0, 400)) - - rvec, tvec = None, None - while cv2.waitKey(1) != 27: - cont, img = cap.read() - if not cont: break - - im = Ogre.Image(Ogre.PF_BYTE_BGR, img.shape[1], img.shape[0], 1, img, False) - if bgtex.getBuffer(): - bgtex.getBuffer().blitFromMemory(im.getPixelBox()) - else: - bgtex.loadImage(im) - - corners, ids = cv2.aruco.detectMarkers(img, adict)[:2] - - if ids is not None: - rvecs, tvecs = cv2.aruco.estimatePoseSingleMarkers(corners, 5, K, None)[:2] - rvec, tvec = rvecs[0].ravel(), tvecs[0].ravel() - - ax = Ogre.Vector3(*rvec) - ang = ax.normalise() - marker_node.setOrientation(Ogre.Quaternion(ang, ax)) - marker_node.setPosition(tvec) - mesh_node.setVisible(True) - - ctx.getRoot().renderOneFrame() - -ctx = Ogre.Bites.ApplicationContext() -ctx.initApp() -main(ctx) -ctx.closeApp() \ No newline at end of file diff --git a/Samples/Python/raw_sample.py b/Samples/Python/raw_sample.py deleted file mode 100644 index 157e057546a..00000000000 --- a/Samples/Python/raw_sample.py +++ /dev/null @@ -1,80 +0,0 @@ -import Ogre -import Ogre.RTShader - -class SGResolver(Ogre.MaterialManager_Listener): - def __init__(self, shadergen): - Ogre.MaterialManager_Listener.__init__(self) - self.shadergen = shadergen - - def handleSchemeNotFound(self, idx, sname, mat, lod_idx, rend): - if sname != Ogre.MSN_SHADERGEN: - return None - - succ = self.shadergen.createShaderBasedTechnique(mat, Ogre.MSN_DEFAULT, sname) - - if not succ: - return None - - self.shadergen.validateMaterial(sname, mat.getName(), mat.getGroup()) - - return mat.getTechnique(1) - -def main(): - root = Ogre.Root("plugins.cfg", "ogre.cfg", "") - - cfg = Ogre.ConfigFile() - cfg.loadDirect("resources.cfg") - - rgm = Ogre.ResourceGroupManager.getSingleton() - - for sec, settings in cfg.getSettingsBySection().items(): - for kind, loc in settings.items(): - rgm.addResourceLocation(loc, kind, sec) - - if not root.restoreConfig(): - root.showConfigDialog(None) - root.saveConfig() - - win = root.initialise(True) - - Ogre.RTShader.ShaderGenerator.initialize() - shadergen = Ogre.RTShader.ShaderGenerator.getSingleton() - - sgres = SGResolver(shadergen) - Ogre.MaterialManager.getSingleton().addListener(sgres) - - rgm.initialiseAllResourceGroups() - - rs = shadergen.getRenderState(Ogre.MSN_SHADERGEN) - rs.addTemplateSubRenderState(shadergen.createSubRenderState("SGX_PerPixelLighting")) - - scn_mgr = root.createSceneManager() - shadergen.addSceneManager(scn_mgr) - - scn_mgr.setAmbientLight((.1, .1, .1)) - - light = scn_mgr.createLight("MainLight") - lightnode = scn_mgr.getRootSceneNode().createChildSceneNode() - lightnode.setPosition(0, 10, 15) - lightnode.attachObject(light) - - cam = scn_mgr.createCamera("myCam") - cam.setNearClipDistance(5) - - camnode = scn_mgr.getRootSceneNode().createChildSceneNode() - camnode.attachObject(cam) - camnode.lookAt((0, 0, -1), Ogre.Node.TS_WORLD) - camnode.setPosition(0, 0, 15) - - vp = win.addViewport(cam) - vp.setBackgroundColour((.3, .3, .3)) - - ent = scn_mgr.createEntity("Sinbad.mesh") - node = scn_mgr.getRootSceneNode().createChildSceneNode() - node.attachObject(ent) - - while not root.endRenderingQueued(): - root.renderOneFrame() - -if __name__ == "__main__": - main() diff --git a/Samples/Python/sample.py b/Samples/Python/sample.py deleted file mode 100644 index cbe7b7b73bc..00000000000 --- a/Samples/Python/sample.py +++ /dev/null @@ -1,65 +0,0 @@ -import Ogre -import Ogre.Bites -import Ogre.RTShader - -class KeyListener(Ogre.Bites.InputListener): - def __init__(self): - Ogre.Bites.InputListener.__init__(self) - - def keyPressed(self, evt): - if evt.keysym.sym == Ogre.Bites.SDLK_ESCAPE: - Ogre.Root.getSingleton().queueEndRendering() - - return True - -def main(): - ctx = Ogre.Bites.ApplicationContext("PySample") - - ctx.initApp() - - # register for input events - klistener = KeyListener() # must keep a reference around - ctx.addInputListener(klistener) - - root = ctx.getRoot() - scn_mgr = root.createSceneManager() - - shadergen = Ogre.RTShader.ShaderGenerator.getSingleton() - shadergen.addSceneManager(scn_mgr) # must be done before we do anything with the scene - - # without light we would just get a black screen - scn_mgr.setAmbientLight((.1, .1, .1)) - - light = scn_mgr.createLight("MainLight") - lightnode = scn_mgr.getRootSceneNode().createChildSceneNode() - lightnode.setPosition(0, 10, 15) - lightnode.attachObject(light) - - # create the camera - cam = scn_mgr.createCamera("myCam") - cam.setNearClipDistance(5) - cam.setAutoAspectRatio(True) - camnode = scn_mgr.getRootSceneNode().createChildSceneNode() - camnode.attachObject(cam) - - # map input events to camera controls - camman = Ogre.Bites.CameraMan(camnode) - camman.setStyle(Ogre.Bites.CS_ORBIT) - camman.setYawPitchDist(0, 0.3, 15) - ctx.addInputListener(camman) - - # and tell it to render into the main window - vp = ctx.getRenderWindow().addViewport(cam) - vp.setBackgroundColour((.3, .3, .3)) - - # finally something to render - ent = scn_mgr.createEntity("Sinbad.mesh") - node = scn_mgr.getRootSceneNode().createChildSceneNode() - node.attachObject(ent) - - root.startRendering() # blocks until queueEndRendering is called - - ctx.closeApp() - -if __name__ == "__main__": - main() diff --git a/Samples/ShaderSystem/include/OgreShaderExInstancedViewports.h b/Samples/ShaderSystem/include/OgreShaderExInstancedViewports.h deleted file mode 100644 index d14bf653a0b..00000000000 --- a/Samples/ShaderSystem/include/OgreShaderExInstancedViewports.h +++ /dev/null @@ -1,188 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderExInstancedViewports_ -#define _ShaderExInstancedViewports_ - -#include "OgreShaderPrerequisites.h" -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS -#include "OgreRTShaderSystem.h" -#include "OgreShaderSubRenderState.h" -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ - - -/**todo -*/ -class ShaderExInstancedViewports : public SubRenderState -{ - friend class ShaderExInstancedViewportsFactory; - bool mOwnsGlobalData; // only true for template sub render state -// Interface. -public: - /** Class default constructor */ - ShaderExInstancedViewports(); - ~ShaderExInstancedViewports(); - - /** - @see SubRenderState::getType. - */ - const String& getType () const override; - - /** - @see SubRenderState::getExecutionOrder. - */ - int getExecutionOrder () const override; - - /** - @see SubRenderState::copyFrom. - */ - void copyFrom (const SubRenderState& rhs) override; - - /** - @see SubRenderState::preAddToRenderState. - */ - bool preAddToRenderState (const RenderState* renderState, Pass* srcPass, Pass* dstPass) override; - - /** - @see SubRenderState::updateGpuProgramsParams. - */ - void updateGpuProgramsParams (Renderable* rend, const Pass* pass, const AutoParamDataSource* source, const LightList* pLightList) override; - - - /** Set the monitors count. */ - void setMonitorsCount (const Vector2 monitorsCount); - - /** Return the monitors count. */ - Vector2 getMonitorsCount () const { return mMonitorsCount; } - - static String Type; - -// Protected methods. -protected: - - - /** - @see SubRenderState::resolveParameters. - */ - bool resolveParameters (ProgramSet* programSet) override; - - /** - @see SubRenderState::resolveDependencies. - */ - bool resolveDependencies (ProgramSet* programSet) override; - - /** - @see SubRenderState::addFunctionInvocations. - */ - bool addFunctionInvocations (ProgramSet* programSet) override; - - /** - Internal method that adds related vertex shader functions invocations. - */ - bool addVSInvocations (Function* vsMain, const int groupOrder); - - - /** - Internal method that adds related pixel shader functions invocations. - */ - bool addPSInvocations (Function* psMain, const int groupOrder); - - -// Attributes. -protected: - ParameterPtr mVSInPosition; // Vertex shader original input position in projective space. - ParameterPtr mVSOriginalOutPositionProjectiveSpace; // Vertex shader original output position in projective space. - ParameterPtr mVSOutPositionProjectiveSpace; // Vertex shader output texcord position in projective space. - ParameterPtr mPSInPositionProjectiveSpace; // Pixel shader input position in projective space. - UniformParameterPtr mVSInMonitorsCount; // Vertex shader uniform monitors count. - UniformParameterPtr mPSInMonitorsCount; // Pixel shader uniform monitors count. - ParameterPtr mVSInMonitorIndex; // Vertex shader uniform monitor index. - ParameterPtr mVSOutMonitorIndex; // Vertex shader output monitor index. - ParameterPtr mPSInMonitorIndex; // Pixel shader input monitor index. - - ParameterPtr mVSInViewportOffsetMatrixR0; - ParameterPtr mVSInViewportOffsetMatrixR1; - ParameterPtr mVSInViewportOffsetMatrixR2; - ParameterPtr mVSInViewportOffsetMatrixR3; - - UniformParameterPtr mWorldViewMatrix; // world & view parameter. - UniformParameterPtr mProjectionMatrix; // projection parameter. - - Vector2 mMonitorsCount; - bool mMonitorsCountChanged; - -}; - - -/** -A factory that enables creation of ShaderExInstancedViewports instances. -@remarks Sub class of SubRenderStateFactory -*/ -class ShaderExInstancedViewportsFactory : public SubRenderStateFactory -{ -public: - - /** - @see SubRenderStateFactory::getType. - */ - const String& getType () const override; - - /** - @see SubRenderStateFactory::createInstance. - */ - SubRenderState* createInstance (ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) override; - - /** - @see SubRenderStateFactory::writeInstance. - */ - void writeInstance (MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, Pass* dstPass) override; - -protected: - - /** - @see SubRenderStateFactory::createInstanceImpl. - */ - SubRenderState* createInstanceImpl () override; - - - -}; - - -} -} - -#endif -#endif - diff --git a/Samples/ShaderSystem/include/OgreShaderExTextureAtlasSampler.h b/Samples/ShaderSystem/include/OgreShaderExTextureAtlasSampler.h deleted file mode 100644 index 0c6fd73c1e3..00000000000 --- a/Samples/ShaderSystem/include/OgreShaderExTextureAtlasSampler.h +++ /dev/null @@ -1,370 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderSGXAtlasTexture_ -#define _ShaderSGXAtlasTexture_ - -#include "OgreShaderPrerequisites.h" -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS -#include "OgreShaderSubRenderState.h" - -#define TAS_MAX_TEXTURES 4 -namespace Ogre { -namespace RTShader { - -/** \addtogroup Optional -* @{ -*/ -/** \addtogroup RTShader -* @{ -*/ -struct TextureAtlasRecord -{ - TextureAtlasRecord(const String & texOriginalName, const String & texAtlasName, - const float texPosU, const float texPosV, const float texWidth, const float texHeight, - const size_t texIndexInAtlas) : - posU(texPosU) - , posV(texPosV) - , width(texWidth) - , height(texHeight) - , originalTextureName(texOriginalName) - , atlasTextureName(texAtlasName) - , indexInAtlas(texIndexInAtlas) - { } - - float posU; - float posV; - float width; - float height; - String originalTextureName; - String atlasTextureName; - size_t indexInAtlas; -}; - -typedef std::vector TextureAtlasTable; -typedef SharedPtr TextureAtlasTablePtr; -typedef std::map TextureAtlasMap; - - - -/** Implements texture atlas sampling. - -This class implements a sub render state which allows sampling of a texture -from a texture atlas. - -Note: This class does not implement the entire texture sub-render state. It -only implement the sampling of textures. This class needs to work in conjunction -with the default FFPTexturing to work. - -\par Using the TextureAtlasSampler -There are 2 pieces of information that are need to be provided for this sub -render state to work. - -The first is the texture atlas table. This table consists of several records -containing the position and size of each texture in the in the texture atlas. -This information needs to be provided per atlas texture. The information is -entered to the system though the TextureAtlasSamplerFactory using the -functions setTextureAtlasTable and removeTextureAtlasTable. - -The second information is the index of the record in the texture atlas table -to which a given texture is associated with. This information is provided -through an extra texture coordinate in the vertex buffer. This texture coordinate -might can be placed either relative or in absolute position. - -For example: - - given 3 texture sand a relative position of 2, the shader will search assume - that the indexes exist in texture coordinate 5 (2+3) - - given an absolute position of 2, the shader will search for the indexes in - texture coordinate 2, regardless of the amount of textures - -The position of the indexes can be controlled globally through the -TextureAtlasSamplerFactory class using the function setTableIndexPosition -The default index position is set to relative + 1. - -\par Preparing atlas textures -When preparing the atlas texture to be used in this system you should make sure -that all texture with in the atlas have power-of-2 dimensions. And also that -the inserted textures will be padded with 1 pixel of their own border color. -This will prevent visual artifacts caused when sampling textures at their borders. - -\par Border issues -There is an inherit problem in texture atlases. This issue occurs because individual textures within -the atlas texture are adjacent to one another. when polling the color of a texture near the texture's -edges, especially in lower mipmaps pixel color from other images may be mixed in with the result. -There are 3 ways to handle this issue, each with it's own limitations: --# Ignore the problem - bad for repetitive images in which the border colour may be quite apparent. --# Auto adjust the polling position - This the default implementation of the TextureAtlasSampler SRS. - Auto adjust the polling position in the shader according the mipmap level in use. This means that - a different (smaller) section of an image may be polled instead of the original section (especially - with in mipmaps). Bad for non repetitive accurate images. --# Generate a texture atlas where each image will contain around it a wrapped version of itself. - This solves all visual problems but is wasteful in gpu memory (up to 3 times the size of the original image) - - -You can use the NVidia "Texture Atlas Tools" to create the texture. -*/ -class TextureAtlasSampler : public SubRenderState -{ -public: - -// Interface. -public: - - /** Class default constructor */ - TextureAtlasSampler(); - - /** - @see SubRenderState::getType. - */ - const String& getType() const override; - - /** - @see SubRenderState::getType. - */ - int getExecutionOrder() const override; - - /** - @see SubRenderState::copyFrom. - */ - void copyFrom(const SubRenderState& rhs) override; - - /** - @see SubRenderState::updateGpuProgramsParams. - */ - void updateGpuProgramsParams(Renderable* rend, const Pass* pass, const AutoParamDataSource* source, const LightList* pLightList) override; - - /** - @see SubRenderState::preAddToRenderState. - */ - bool preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) override; - - static String Type; - -// Protected methods -protected: - bool resolveParameters(ProgramSet* programSet) override; - bool resolveDependencies(ProgramSet* programSet) override; - bool addFunctionInvocations(ProgramSet* programSet) override; - - /** - Given an address mode returns the function name which calculates the UV values for that addressing mode - */ - const char* getAdressingFunctionName(TextureAddressingMode mode); - - -// Attributes. -protected: - /// The index of the information on the texture in the table - ParameterPtr mVSInpTextureTableIndex; - - /// The addressing mode for each texture - Sampler::UVWAddressingMode mTextureAddressings[TAS_MAX_TEXTURES]; - /// The position and size of the texture in the atlas - ParameterPtr mVSOutTextureDatas[TAS_MAX_TEXTURES]; - /// The position and size of the texture in the atlas - ParameterPtr mPSInpTextureDatas[TAS_MAX_TEXTURES]; - /// A parameter carrying the sizes of the atlas textures - UniformParameterPtr mPSTextureSizes[TAS_MAX_TEXTURES]; - /// The table containing information on the textures in the atlas - UniformParameterPtr mVSTextureTable[TAS_MAX_TEXTURES]; - - /// The position of the texture coordinates containing the index information - ushort mAtlasTexcoordPos; - /// The texture atlas table data - TextureAtlasTablePtr mAtlasTableDatas[TAS_MAX_TEXTURES]; - /// For each texture unit in the pass tells if it uses atlas texture - bool mIsAtlasTextureUnits[TAS_MAX_TEXTURES]; - /// Tells if the data in mAtlasTableData has been uploaded to the corresponding mVSTextureTable parameter - bool mIsTableDataUpdated; - /// Tells whether border issue handling uses auto adjust polling position. - bool mAutoAdjustPollPosition; -}; - - - -/** -A factory that enables creation of TextureAtlasSampler instances. -@remarks Sub class of SubRenderStateFactory -*/ -class TextureAtlasSamplerFactory : public SubRenderStateFactory, public Singleton -{ -public: - enum IndexPositionMode - { - ipmRelative, - ipmAbsolute - }; - - struct TextureAtlasAttib - { - TextureAtlasAttib(IndexPositionMode _posMode = ipmRelative, ushort _posOffset = 1, - bool _autoBorderAdjust = true) : positionMode(_posMode), positionOffset(_posOffset), - autoBorderAdjust(_autoBorderAdjust) {} - - IndexPositionMode positionMode; - ushort positionOffset; - bool autoBorderAdjust; - }; - -public: - - //TextureAtlasSamplerFactory c_tor - TextureAtlasSamplerFactory(); - - //Singleton implementation - static TextureAtlasSamplerFactory* getSingletonPtr(void); - static TextureAtlasSamplerFactory& getSingleton(void); - - - - /** - @see SubRenderStateFactory::getType. - */ - const String& getType() const override; - - /** - @see SubRenderStateFactory::createInstance. - */ - SubRenderState* createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) override; - - /** - @see SubRenderStateFactory::writeInstance. - */ - void writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, Pass* dstPass) override; - - /** - Adds a texture atlas definition from a stream. - - This function loads a texture atlas definition file from a stream. The accepted format for - this file is the NVidia Texture Atlas Tools ".tai" file format. This file as - - The ".tai" format consist of lines, where each line corresponds to a specific texture - in the texture atlas. Each line has the following format: - @verbatim - /t/t, , , , , , , - @endverbatim - - @param filename The full path to the file containing a ".tai" format data. - @param textureAtlasTable A table into which the data in the stream will be filled. This - parameter will be filled only if it is not null. The system factory keeps a copy of this - information in any case. - */ - bool addTexutreAtlasDefinition( const Ogre::String& filename, const TextureAtlasTablePtr& textureAtlasTable = TextureAtlasTablePtr()); - /// @overload - bool addTexutreAtlasDefinition( const DataStreamPtr& stream, const TextureAtlasTablePtr& textureAtlasTable = TextureAtlasTablePtr()); - - /** - Set the texture atlas information for a given texture - @param textureName Name of an atlas texture - @param atlasData A list of records containing the position and size of each - texture in the atlas - @param autoBorderAdjust Sets whether to automatically adjust the image polling area for border - issues.See the Border issues paragraph under the class documentation for more information. - */ - void setTextureAtlasTable(const String& textureName, const TextureAtlasTablePtr& atlasData, bool autoBorderAdjust = true); - - /** - Removes the texture atlas information from a given texture - @param textureName Name of an atlas texture - */ - void removeTextureAtlasTable(const String& textureName); - - /** - Removes all texture atlas table information - */ - void removeAllTextureAtlasTables(); - - /** - Retrieve the texture atlas table information for a given texture - @param textureName Name of an atlas texture - */ - const TextureAtlasTablePtr& getTextureAtlasTable(const String& textureName) const; - - /** - Set the default attributes concerning atlas texture processing - @param mode The index positioning mode. Tells relative to where the the texture coordinates - containing the atlas image to use are positioned. - @param offset The index positioning offset. Tells the offset relative to the index positioning - mode. - @param autoAdjustBorders Tells whether to automatically adjust the polled area in the texture - relative to the used mipmap level. - @see TextureAtlasSampler - */ - void setDefaultAtlasingAttributes(IndexPositionMode mode, ushort offset, bool autoAdjustBorders); - - /** - Returns the default attributes of texture atlas processing - @see setDefaultAtlasingAttributes - */ - const TextureAtlasAttib& getDefaultAtlasingAttributes() const; - - /** - Set the default attributes concerning atlas texture processing for a specific material - @param material The material to which to add the information - @param mode The index positioning mode. Tells relative to where the the texture coordinates - containing the atlas image to use are positioned. - @param offset The index positioning offset. Tells the offset relative to the index positioning - mode. - @param autoAdjustBorders Tells whether to automatically adjust the polled area in the texture - relative to the used mipmap level. - @see TextureAtlasSampler - */ - void setMaterialAtlasingAttributes(Ogre::Material* material, - IndexPositionMode mode, ushort offset, bool autoAdjustBorders); - - - /** - Tells whether a specific material has atlas attributes associated with it. And returns the - attributes to be used. - @see setMaterialAtlasingAttributes - */ - bool hasMaterialAtlasingAttributes(Ogre::Material* material, TextureAtlasAttib* attrib = NULL) const; - -protected: - - - - /** - @see SubRenderStateFactory::createInstanceImpl. - */ - SubRenderState* createInstanceImpl() override; - -private: - - //Holds a mapping of texture names and the atlas table information associated with them - TextureAtlasMap mAtlases; - - TextureAtlasAttib mDefaultAtlasAttrib; -}; - -/** @} */ -/** @} */ - -} -} - -#endif -#endif diff --git a/Samples/ShaderSystem/include/ShaderSystem.h b/Samples/ShaderSystem/include/ShaderSystem.h deleted file mode 100644 index c50d9a47276..00000000000 --- a/Samples/ShaderSystem/include/ShaderSystem.h +++ /dev/null @@ -1,224 +0,0 @@ -#ifndef __ShaderSystem_H__ -#define __ShaderSystem_H__ - -#include "SdkSample.h" -#include "OgreShaderExLayeredBlending.h" - -using namespace Ogre; -using namespace OgreBites; - -// Lighting models. -enum ShaderSystemLightingModel -{ - SSLM_PerPixelLighting, - SSLM_CookTorranceLighting, - SSLM_ImageBasedLighting, - SSLM_NormalMapLightingTangentSpace, - SSLM_NormalMapLightingObjectSpace -}; - -// a hack class to get infinite frustum - needed by instanced viewports demo -// a better solution will be to check the frustums of all the viewports in a similer class -class _OgreSampleClassExport InfiniteFrustum : public Frustum -{ -public: - InfiniteFrustum() : Frustum() - { - mFrustumPlanes[FRUSTUM_PLANE_LEFT].normal = Vector3::NEGATIVE_UNIT_X; - mFrustumPlanes[FRUSTUM_PLANE_LEFT].d = 9999999999999999999.0f; - mFrustumPlanes[FRUSTUM_PLANE_RIGHT].normal = Vector3::UNIT_X; - mFrustumPlanes[FRUSTUM_PLANE_RIGHT].d = 9999999999999999999.0f; - mFrustumPlanes[FRUSTUM_PLANE_TOP].normal = Vector3::NEGATIVE_UNIT_Y; - mFrustumPlanes[FRUSTUM_PLANE_TOP].d = 9999999999999999999.0f; - mFrustumPlanes[FRUSTUM_PLANE_BOTTOM].normal = Vector3::UNIT_Y; - mFrustumPlanes[FRUSTUM_PLANE_BOTTOM].d = 9999999999999999999.0f; - mFrustumPlanes[FRUSTUM_PLANE_NEAR].normal = Vector3::NEGATIVE_UNIT_Z; - mFrustumPlanes[FRUSTUM_PLANE_NEAR].d = 9999999999999999999.0f; - mFrustumPlanes[FRUSTUM_PLANE_FAR].normal = Vector3::UNIT_Z; - mFrustumPlanes[FRUSTUM_PLANE_FAR].d = 9999999999999999999.0f; - } - bool isVisible(const AxisAlignedBox& bound, FrustumPlane* culledBy = 0) const override {return true;}; - bool isVisible(const Sphere& bound, FrustumPlane* culledBy = 0) const override {return true;}; - bool isVisible(const Vector3& vert, FrustumPlane* culledBy = 0) const override {return true;}; - bool projectSphere(const Sphere& sphere, - Real* left, Real* top, Real* right, Real* bottom) const override {*left = *bottom = -1.0f; *right = *top = 1.0f; return true;}; - Real getNearClipDistance(void) const {return 1.0;}; - Real getFarClipDistance(void) const {return 9999999999999.0f;}; - const Plane& getFrustumPlane( unsigned short plane ) const override - { - return mFrustumPlanes[plane]; - } - -}; - - -// Listener class for frame updates -class _OgreSampleClassExport Sample_ShaderSystem : public SdkSample -{ -public: - Sample_ShaderSystem(); - ~Sample_ShaderSystem(); - - void _shutdown() override; - - /** @see Sample::checkBoxToggled. */ - void checkBoxToggled(CheckBox* box) override; - - /** @see Sample::itemSelected. */ - void itemSelected(SelectMenu* menu) override; - - /** @see Sample::buttonHit. */ - void buttonHit(OgreBites::Button* b) override; - - /** @see Sample::sliderMoved. */ - void sliderMoved(Slider* slider) override; - - /** @see Sample::testCapabilities. */ - void testCapabilities(const RenderSystemCapabilities* caps) override; - - /** @see Sample::frameRenderingQueued. */ - bool frameRenderingQueued(const FrameEvent& evt) override; - - void updateTargetObjInfo(); - - /** @see Sample::mousePressed. */ - bool mousePressed(const MouseButtonEvent& evt) override; - - /** @see Sample::mouseReleased. */ - bool mouseReleased(const MouseButtonEvent& evt) override; - - /** @see Sample::mouseMoved. */ - bool mouseMoved(const MouseMotionEvent& evt) override; - -protected: - - /** Set the current lighting model. */ - void setCurrentLightingModel(ShaderSystemLightingModel lightingModel); - - /** Return the current lighting model. */ - ShaderSystemLightingModel getCurrentLightingMode() const { return mCurLightingModel; } - - /** Set specular enable state. */ - void setSpecularEnable(bool enable); - - /** Return current specular state. */ - bool getSpecularEnable() const { return mSpecularEnable; } - - - /** Set fog per pixel enable state. */ - void setPerPixelFogEnable(bool enable); - - /** Set auto border adjustment mode in texture atlasing. */ - void setAtlasBorderMode( bool enable ); - - /** Set instanced viewports enable state. */ - void setInstancedViewportsEnable( bool enable ); - - /** Create directional light. */ - void createDirectionalLight(); - - /** Create point light. */ - void createPointLight(); - - /** Create spot light. */ - void createSpotLight(); - - /** Toggle adding of lots of models */ - void updateAddLotsOfModels(bool addThem); - void addModelToScene(const String & modelName); - - /** Toggle instanced viewports */ - void updateInstancedViewports(bool enabled); - - /** Toggle light visibility. */ - void updateLightState(const String& lightName, bool visible); - - /** Update runtime generated shaders of the target entities in this demo. */ - void updateSystemShaders(); - - /** Create shaders based techniques using the given entity based on its sub entities material set. */ - void generateShaders(Entity* entity); - - /** @see Sample::setupView. */ -// virtual void setupView(); - - /** @see Sample::setupContent. */ - void setupContent() override; - - /** Setup the UI for the sample. */ - void setupUI(); - - /** @see Sample::setupContent. */ - void cleanupContent() override; - - /** @see Sample::loadResources. */ - void loadResources() override; - - /** @see Sample::unloadResources. */ - void unloadResources() override; - - void createInstancedViewports(); - void destroyInstancedViewports(); - void destroyInstancedViewportsFactory(); - - /** Pick the target object. */ - void pickTargetObject( const MouseButtonEvent &evt ); - - /** Apply shadow type from the given shadow menu selected index. */ - void applyShadowType(int menuIndex); - - /** Change the current texture layer blend mode. */ - void changeTextureLayerBlendMode(); - - ManualObject* createTextureAtlasObject(); - void createMaterialForTexture( const String & texName, bool isTextureAtlasTexture ); - // Types. -protected: - typedef std::vector EntityList; - typedef EntityList::iterator EntityListIterator; - - typedef std::map StringMap; - typedef StringMap::iterator StringMapIterator; - -protected: - EntityList mTargetEntities; // Target entities that will use runtime shader generated materials. - ShaderSystemLightingModel mCurLightingModel; // The current lighting model. - SelectMenu* mLightingModelMenu; // The lighting model menu. - SelectMenu* mFogModeMenu; // The fog mode menu. - Label* mLanguage; // The shading language menu. - SelectMenu* mShadowMenu; // The shadow type menu. - bool mPerPixelFogEnable; // When true the RTSS will do per pixel fog calculations. - bool mSpecularEnable; // The current specular state. - RTShader::SubRenderStateFactory* mTextureAtlasFactory; - RTShader::SubRenderState* mInstancedViewportsSubRenderState;// todo - doc - bool mInstancedViewportsEnable; // todo - doc - InfiniteFrustum mInfiniteFrustum; // todo - doc - BillboardSet* mBbsFlare; // todo - doc - bool mAddedLotsOfModels; // todo - doc - std::vector mLotsOfModelsEntities; // todo - doc - std::vector mLotsOfModelsNodes; // todo - doc - int mNumberOfModelsAdded; // todo - doc - RTShader::SubRenderStateFactory * mInstancedViewportsFactory; // todo - doc - - RTShader::SubRenderState* mReflectionMapSubRS; // The reflection map sub render state. - RTShader::LayeredBlending* mLayerBlendSubRS; // The layer blending sub render state. - Label* mLayerBlendLabel; // The layer blending label. - Slider* mReflectionPowerSlider; // The reflection power controller slider. - Slider* mModifierValueSlider; // The value of the modifier for the layered blend controller slider. - Entity* mLayeredBlendingEntity; // Entity used to show layered blending SRS - SceneNode* mPointLightNode; // Point light scene node. - SceneNode* mDirectionalLightNode; // Directional light scene node. - RaySceneQuery* mRayQuery; // The ray scene query. - MovableObject* mTargetObj; // The current picked target object. - Label* mTargetObjMatName; // The target object material name label. - Label* mTargetObjVS; // The target object vertex shader label. - Label* mTargetObjFS; // The target object fragment shader label. - CheckBox* mDirLightCheckBox; // The directional light check box. - CheckBox* mPointLightCheckBox; // The point light check box. - CheckBox* mSpotLightCheckBox; // The spot light check box. - CheckBox* mInstancedViewportsCheckBox; // The instanced viewports check box. - CheckBox* mAddLotsOfModels; // The "add lots of models" check box. - int mCurrentBlendMode; -}; - -#endif diff --git a/Samples/ShaderSystem/src/OgreShaderExInstancedViewports.cpp b/Samples/ShaderSystem/src/OgreShaderExInstancedViewports.cpp deleted file mode 100644 index ebf5b418529..00000000000 --- a/Samples/ShaderSystem/src/OgreShaderExInstancedViewports.cpp +++ /dev/null @@ -1,364 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderExInstancedViewports.h" -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS -#include "OgreShaderFFPRenderState.h" -#include "OgreShaderProgram.h" -#include "OgreShaderParameter.h" -#include "OgreShaderProgramSet.h" -#include "OgreScriptCompiler.h" -#include "OgreTechnique.h" -#include "OgreHardwareBufferManager.h" -#include "OgreRoot.h" - -namespace Ogre { -namespace RTShader { - - -/************************************************************************/ -/* */ -/************************************************************************/ -String ShaderExInstancedViewports::Type = "SGX_InstancedViewports"; - -//----------------------------------------------------------------------- -#define SGX_LIB_INSTANCED_VIEWPORTS "SampleLib_InstancedViewports" -#define SGX_FUNC_INSTANCED_VIEWPORTS_TRANSFORM "SGX_InstancedViewportsTransform" -#define SGX_FUNC_INSTANCED_VIEWPORTS_DISCARD_OUT_OF_BOUNDS "SGX_InstancedViewportsDiscardOutOfBounds" - - -//----------------------------------------------------------------------- -ShaderExInstancedViewports::ShaderExInstancedViewports() -{ - mMonitorsCount = Vector2(1.0, 1.0); - mMonitorsCountChanged = true; - mOwnsGlobalData = false; -} - -//----------------------------------------------------------------------- -const String& ShaderExInstancedViewports::getType() const -{ - return Type; -} - - -//----------------------------------------------------------------------- -int ShaderExInstancedViewports::getExecutionOrder() const -{ - // We place this effect after texturing stage and before fog stage. - return FFP_POST_PROCESS+1; -} - -//----------------------------------------------------------------------- -void ShaderExInstancedViewports::copyFrom(const SubRenderState& rhs) -{ - const ShaderExInstancedViewports& rhsInstancedViewports = static_cast(rhs); - - // Copy all settings that affect this sub render state output code. - mMonitorsCount = rhsInstancedViewports.mMonitorsCount; - mMonitorsCountChanged = rhsInstancedViewports.mMonitorsCountChanged; -} - -//----------------------------------------------------------------------- -bool ShaderExInstancedViewports::preAddToRenderState( const RenderState* renderState, Pass* srcPass, Pass* dstPass ) -{ - auto matname = srcPass->getParent()->getParent()->getName(); - return matname.find("SdkTrays") == String::npos && matname.find("Instancing") == String::npos; -} -//----------------------------------------------------------------------- -bool ShaderExInstancedViewports::resolveParameters(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Function* psMain = psProgram->getEntryPointFunction(); - - - // Resolve vertex shader output position in projective space. - - mVSInPosition = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE); - - mVSOriginalOutPositionProjectiveSpace = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_PROJECTIVE_SPACE); - -#define SPC_POSITION_PROJECTIVE_SPACE_AS_TEXCORD ((Parameter::Content)(Parameter::SPC_CUSTOM_CONTENT_BEGIN + 1)) - - mVSOutPositionProjectiveSpace = vsMain->resolveOutputParameter(SPC_POSITION_PROJECTIVE_SPACE_AS_TEXCORD, GCT_FLOAT4); - - // Resolve ps input position in projective space. - mPSInPositionProjectiveSpace = psMain->resolveInputParameter(mVSOutPositionProjectiveSpace); - // Resolve vertex shader uniform monitors count - mVSInMonitorsCount = vsProgram->resolveParameter(GCT_FLOAT2, "monitorsCount"); - - // Resolve pixel shader uniform monitors count - mPSInMonitorsCount = psProgram->resolveParameter(GCT_FLOAT2, "monitorsCount"); - - - // Resolve the current world & view matrices concatenated - mWorldViewMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLDVIEW_MATRIX); - - // Resolve the current projection matrix - mProjectionMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_PROJECTION_MATRIX); - - -#define SPC_MONITOR_INDEX Parameter::SPC_TEXTURE_COORDINATE1 - // Resolve vertex shader monitor index - mVSInMonitorIndex = vsMain->resolveInputParameter(SPC_MONITOR_INDEX, GCT_FLOAT4); - -#define SPC_MATRIX_R0 Parameter::SPC_TEXTURE_COORDINATE2 -#define SPC_MATRIX_R1 Parameter::SPC_TEXTURE_COORDINATE3 -#define SPC_MATRIX_R2 Parameter::SPC_TEXTURE_COORDINATE4 -#define SPC_MATRIX_R3 Parameter::SPC_TEXTURE_COORDINATE5 - - // Resolve vertex shader viewport offset matrix - mVSInViewportOffsetMatrixR0 = vsMain->resolveInputParameter(SPC_MATRIX_R0, GCT_FLOAT4); - mVSInViewportOffsetMatrixR1 = vsMain->resolveInputParameter(SPC_MATRIX_R1, GCT_FLOAT4); - mVSInViewportOffsetMatrixR2 = vsMain->resolveInputParameter(SPC_MATRIX_R2, GCT_FLOAT4); - mVSInViewportOffsetMatrixR3 = vsMain->resolveInputParameter(SPC_MATRIX_R3, GCT_FLOAT4); - - - - // Resolve vertex shader output monitor index. - mVSOutMonitorIndex = vsMain->resolveOutputParameter(SPC_MONITOR_INDEX, GCT_FLOAT4); - - // Resolve ps input monitor index. - mPSInMonitorIndex = psMain->resolveInputParameter(mVSOutMonitorIndex); - - return true; -} - -//----------------------------------------------------------------------- -bool ShaderExInstancedViewports::resolveDependencies(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - - vsProgram->addDependency(SGX_LIB_INSTANCED_VIEWPORTS); - - psProgram->addDependency(SGX_LIB_INSTANCED_VIEWPORTS); - - return true; -} - - -//----------------------------------------------------------------------- -bool ShaderExInstancedViewports::addFunctionInvocations(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* psMain = psProgram->getEntryPointFunction(); - - - // Add vertex shader invocations. - if (false == addVSInvocations(vsMain, FFP_VS_TRANSFORM + 1)) - return false; - - - // Add pixel shader invocations. - if (false == addPSInvocations(psMain, FFP_PS_PRE_PROCESS + 1)) - return false; - - return true; -} - -//----------------------------------------------------------------------- -bool ShaderExInstancedViewports::addVSInvocations( Function* vsMain, const int groupOrder ) -{ - FunctionAtom* funcInvocation = NULL; - - funcInvocation = OGRE_NEW FunctionInvocation(SGX_FUNC_INSTANCED_VIEWPORTS_TRANSFORM, groupOrder); - funcInvocation->pushOperand(mVSInPosition, Operand::OPS_IN); - funcInvocation->pushOperand(mWorldViewMatrix, Operand::OPS_IN); - funcInvocation->pushOperand(mProjectionMatrix, Operand::OPS_IN); - funcInvocation->pushOperand(mVSInViewportOffsetMatrixR0, Operand::OPS_IN); - funcInvocation->pushOperand(mVSInViewportOffsetMatrixR1, Operand::OPS_IN); - funcInvocation->pushOperand(mVSInViewportOffsetMatrixR2, Operand::OPS_IN); - funcInvocation->pushOperand(mVSInViewportOffsetMatrixR3, Operand::OPS_IN); - funcInvocation->pushOperand(mVSInMonitorsCount, Operand::OPS_IN); - funcInvocation->pushOperand(mVSInMonitorIndex, Operand::OPS_IN); - funcInvocation->pushOperand(mVSOriginalOutPositionProjectiveSpace, Operand::OPS_OUT); - vsMain->addAtomInstance(funcInvocation); - - // Output position in projective space. - funcInvocation = OGRE_NEW AssignmentAtom( groupOrder); - funcInvocation->pushOperand(mVSOriginalOutPositionProjectiveSpace, Operand::OPS_IN); - funcInvocation->pushOperand(mVSOutPositionProjectiveSpace, Operand::OPS_OUT); - vsMain->addAtomInstance(funcInvocation); - - // Output monitor index. - funcInvocation = OGRE_NEW AssignmentAtom( groupOrder); - funcInvocation->pushOperand(mVSInMonitorIndex, Operand::OPS_IN); - funcInvocation->pushOperand(mVSOutMonitorIndex, Operand::OPS_OUT); - vsMain->addAtomInstance(funcInvocation); - - return true; -} - -//----------------------------------------------------------------------- -bool ShaderExInstancedViewports::addPSInvocations( Function* psMain, const int groupOrder ) -{ - FunctionInvocation* funcInvocation = NULL; - - funcInvocation = OGRE_NEW FunctionInvocation(SGX_FUNC_INSTANCED_VIEWPORTS_DISCARD_OUT_OF_BOUNDS, groupOrder); - funcInvocation->pushOperand(mPSInMonitorsCount, Operand::OPS_IN); - funcInvocation->pushOperand(mPSInMonitorIndex, Operand::OPS_IN); - funcInvocation->pushOperand(mPSInPositionProjectiveSpace, Operand::OPS_IN); - - psMain->addAtomInstance(funcInvocation); - - return true; -} -//----------------------------------------------------------------------- -void ShaderExInstancedViewports::updateGpuProgramsParams(Renderable* rend, const Pass* pass, const AutoParamDataSource* source, const LightList* pLightList) -{ - if (mMonitorsCountChanged) - { - mVSInMonitorsCount->setGpuParameter(mMonitorsCount + Vector2(0.0001, 0.0001)); - mPSInMonitorsCount->setGpuParameter(mMonitorsCount + Vector2(0.0001, 0.0001)); - - mMonitorsCountChanged = false; - } -} -//----------------------------------------------------------------------- -void ShaderExInstancedViewports::setMonitorsCount( const Vector2 monitorCount ) -{ - mMonitorsCount = monitorCount; - mMonitorsCountChanged = true; - - Ogre::VertexDeclaration* vertexDeclaration = Ogre::HardwareBufferManager::getSingleton().createVertexDeclaration(); - size_t offset = 0; - offset = vertexDeclaration->getVertexSize(0); - vertexDeclaration->addElement(0, offset, Ogre::VET_FLOAT4, Ogre::VES_TEXTURE_COORDINATES, 1); - offset = vertexDeclaration->getVertexSize(0); - vertexDeclaration->addElement(0, offset, Ogre::VET_FLOAT4, Ogre::VES_TEXTURE_COORDINATES, 2); - offset = vertexDeclaration->getVertexSize(0); - vertexDeclaration->addElement(0, offset, Ogre::VET_FLOAT4, Ogre::VES_TEXTURE_COORDINATES, 3); - offset = vertexDeclaration->getVertexSize(0); - vertexDeclaration->addElement(0, offset, Ogre::VET_FLOAT4, Ogre::VES_TEXTURE_COORDINATES, 4); - offset = vertexDeclaration->getVertexSize(0); - vertexDeclaration->addElement(0, offset, Ogre::VET_FLOAT4, Ogre::VES_TEXTURE_COORDINATES, 5); - - Ogre::HardwareVertexBufferSharedPtr vbuf = - Ogre::HardwareBufferManager::getSingleton().createVertexBuffer( - vertexDeclaration->getVertexSize(0), monitorCount.x * monitorCount.y, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY); - vbuf->setInstanceDataStepRate(1); - vbuf->setIsInstanceData(true); - - float * buf = (float *)vbuf->lock(Ogre::HardwareBuffer::HBL_DISCARD); - for (int x = 0 ; x < monitorCount.x ; x++) - for (int y = 0 ; y < monitorCount.y ; y++) - { - *buf = x; buf++; - *buf = y; buf++; - *buf = 0; buf++; - *buf = 0; buf++; - - Ogre::Quaternion q; - Ogre::Radian angle = Ogre::Degree(90 / ( monitorCount.x * monitorCount.y) * (x + y * monitorCount.x) ); - q.FromAngleAxis(angle,Ogre::Vector3::UNIT_Y); - q.normalise(); - Ogre::Matrix3 rotMat; - q.ToRotationMatrix(rotMat); - - *buf = rotMat.GetColumn(0).x; buf++; - *buf = rotMat.GetColumn(0).y; buf++; - *buf = rotMat.GetColumn(0).z; buf++; - *buf = x * -20; buf++; - - *buf = rotMat.GetColumn(1).x; buf++; - *buf = rotMat.GetColumn(1).y; buf++; - *buf = rotMat.GetColumn(1).z; buf++; - *buf = 0; buf++; - - *buf = rotMat.GetColumn(2).x; buf++; - *buf = rotMat.GetColumn(2).y; buf++; - *buf = rotMat.GetColumn(2).z; buf++; - *buf = y * 20; buf++; - - *buf = 0; buf++; - *buf = 0; buf++; - *buf = 0; buf++; - *buf = 1; buf++; - } - vbuf->unlock(); - - mOwnsGlobalData = true; - - auto rs = Ogre::Root::getSingleton().getRenderSystem(); - rs->setGlobalInstanceVertexBuffer(vbuf); - rs->setGlobalInstanceVertexDeclaration(vertexDeclaration); - rs->setGlobalInstanceCount(monitorCount.x * monitorCount.y); -} -ShaderExInstancedViewports::~ShaderExInstancedViewports() -{ - if (!mOwnsGlobalData) - return; - - auto rs = Ogre::Root::getSingleton().getRenderSystem(); - if (auto decl = rs->getGlobalInstanceVertexDeclaration()) - { - Ogre::HardwareBufferManager::getSingleton().destroyVertexDeclaration(decl); - } - - rs->setGlobalInstanceVertexDeclaration(NULL); - rs->setGlobalInstanceCount(1); - rs->setGlobalInstanceVertexBuffer( NULL ); -} - -//----------------------------------------------------------------------- -SubRenderState* ShaderExInstancedViewportsFactory::createInstance(ScriptCompiler* compiler, - PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) -{ - SubRenderState* subRenderState = SubRenderStateFactory::createInstance(); - return subRenderState; -} -//----------------------------------------------------------------------- -void ShaderExInstancedViewportsFactory::writeInstance(MaterialSerializer* ser, - SubRenderState* subRenderState, - Pass* srcPass, Pass* dstPass) -{ - -} - -//----------------------------------------------------------------------- -const String& ShaderExInstancedViewportsFactory::getType() const -{ - return ShaderExInstancedViewports::Type; -} - - -//----------------------------------------------------------------------- -SubRenderState* ShaderExInstancedViewportsFactory::createInstanceImpl() -{ - return OGRE_NEW ShaderExInstancedViewports; -} - -//----------------------------------------------------------------------- - -} -} - -#endif diff --git a/Samples/ShaderSystem/src/OgreShaderExTextureAtlasSampler.cpp b/Samples/ShaderSystem/src/OgreShaderExTextureAtlasSampler.cpp deleted file mode 100644 index f79ec0dfd57..00000000000 --- a/Samples/ShaderSystem/src/OgreShaderExTextureAtlasSampler.cpp +++ /dev/null @@ -1,547 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreShaderExTextureAtlasSampler.h" - -#include - -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS -#include "OgreShaderFFPRenderState.h" -#include "OgreShaderProgram.h" -#include "OgreShaderParameter.h" -#include "OgreShaderProgramSet.h" -#include "OgreLogManager.h" -#include "OgreTechnique.h" - -#define SGX_LIB_TEXTURE_ATLAS "SGXLib_TextureAtlas" - -#define SGX_FUNC_ATLAS_SAMPLE_AUTO_ADJUST "SGX_Atlas_Sample_Auto_Adjust" -#define SGX_FUNC_ATLAS_SAMPLE_NORMAL "SGX_Atlas_Sample_Normal" - -#define SGX_FUNC_ATLAS_WRAP "SGX_Atlas_Wrap" -#define SGX_FUNC_ATLAS_MIRROR "SGX_Atlas_Mirror" -#define SGX_FUNC_ATLAS_CLAMP "SGX_Atlas_Clamp" -#define SGX_FUNC_ATLAS_BORDER "SGX_Atlas_Border" -#define TAS_MAX_SAFE_ATLASED_TEXTURES 250 - -namespace Ogre { -template<> RTShader::TextureAtlasSamplerFactory* Singleton::msSingleton = 0; - -namespace RTShader { - -const TextureAtlasTablePtr c_BlankAtlasTable; -const String c_ParamTexel("texel_"); -String TextureAtlasSampler::Type = "SGX_TextureAtlasSampler"; -String c_RTAtlasKey = "RTAtlas"; - -//----------------------------------------------------------------------- -TextureAtlasSampler::TextureAtlasSampler() : - mAtlasTexcoordPos(0), - mIsTableDataUpdated(false), - mAutoAdjustPollPosition(true) -{ - mTextureAddressings->u = mTextureAddressings->v = mTextureAddressings->w = TAM_WRAP; - memset(mIsAtlasTextureUnits, 0, sizeof(bool) * TAS_MAX_TEXTURES); -} - -//----------------------------------------------------------------------- -const String& TextureAtlasSampler::getType() const -{ - return Type; -} - - -//----------------------------------------------------------------------- -int TextureAtlasSampler::getExecutionOrder() const -{ - return FFP_TEXTURING + 25; -} - -//----------------------------------------------------------------------- -bool TextureAtlasSampler::resolveParameters(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Function* psMain = psProgram->getEntryPointFunction(); - - - // - // Define vertex shader parameters used to find the position of the textures in the atlas - // - Parameter::Content indexContent = (Parameter::Content)((int)Parameter::SPC_TEXTURE_COORDINATE0 + mAtlasTexcoordPos); - GpuConstantType indexType = GCT_FLOAT4; - - mVSInpTextureTableIndex = vsMain->resolveInputParameter(indexContent, indexType); - - - // - // Define parameters to carry the information on the location of the texture from the vertex to - // the pixel shader - // - for(ushort i = 0 ; i < TAS_MAX_TEXTURES ; ++ i) - { - if (mIsAtlasTextureUnits[i] == true) - { - mVSTextureTable[i] = vsProgram->resolveParameter(GCT_FLOAT4, -1, (uint16)GPV_GLOBAL, "AtlasData", mAtlasTableDatas[i]->size()); - mVSOutTextureDatas[i] = vsMain->resolveOutputParameter(Parameter::SPC_UNKNOWN, GCT_FLOAT4); - mPSInpTextureDatas[i] = psMain->resolveInputParameter(mVSOutTextureDatas[i]); - mPSTextureSizes[i] = psProgram->resolveParameter(GCT_FLOAT2,-1, (uint16)GPV_PER_OBJECT, "AtlasSize"); - } - } - return true; -} - - -//----------------------------------------------------------------------- -bool TextureAtlasSampler::resolveDependencies(ProgramSet* programSet) -{ - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - psProgram->addDependency(SGX_LIB_TEXTURE_ATLAS); - - return true; -} - -//----------------------------------------------------------------------- -bool TextureAtlasSampler::addFunctionInvocations(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* psMain = psProgram->getEntryPointFunction(); - FunctionAtom* curFuncInvocation = NULL; - - // - // Calculate the position and size of the texture in the atlas in the vertex shader - // - int groupOrder = (FFP_VS_TEXTURING - FFP_VS_LIGHTING) / 2; - - for(ushort i = 0 ; i < TAS_MAX_TEXTURES; ++i) - { - if (mIsAtlasTextureUnits[i] == true) - { - Operand::OpMask textureIndexMask = Operand::OPM_X; - switch (i) - { - case 1: textureIndexMask = Operand::OPM_Y; break; - case 2: textureIndexMask = Operand::OPM_Z; break; - case 3: textureIndexMask = Operand::OPM_W; break; - } - - curFuncInvocation = OGRE_NEW AssignmentAtom(groupOrder); - curFuncInvocation->pushOperand(mVSTextureTable[i], Operand::OPS_IN); - curFuncInvocation->pushOperand(mVSInpTextureTableIndex, Operand::OPS_IN, textureIndexMask, 1); - curFuncInvocation->pushOperand(mVSOutTextureDatas[i], Operand::OPS_OUT); - vsMain->addAtomInstance(curFuncInvocation); - } - } - - // - // sample the texture in the fragment shader given the extracted data in the pixel shader - // - - - groupOrder = (FFP_PS_SAMPLING + FFP_PS_TEXTURING) / 2; - - ParameterPtr psAtlasTextureCoord = psMain->resolveLocalParameter(GCT_FLOAT2, "atlasCoord"); - - for(ushort j = 0 ; j < TAS_MAX_TEXTURES; ++j) - { - if (mIsAtlasTextureUnits[j] == true) - { - //Find the texture coordinates texel and sampler from the original FFPTexturing - ParameterPtr texcoord = psMain->getInputParameter((Parameter::Content)(Parameter::SPC_TEXTURE_COORDINATE0 + j), GCT_FLOAT2); - ParameterPtr texel = psMain->getLocalParameter(c_ParamTexel + StringConverter::toString(j)); - UniformParameterPtr sampler = psProgram->getParameterByType(GCT_SAMPLER2D, j); - - const char* addressUFuncName = getAdressingFunctionName(mTextureAddressings[j].u); - const char* addressVFuncName = getAdressingFunctionName(mTextureAddressings[j].v); - - //Create a function which will replace the texel with the texture texel - if (texcoord && texel && sampler && addressUFuncName && addressVFuncName) - { - //calculate the U value due to addressing mode - curFuncInvocation = OGRE_NEW FunctionInvocation(addressUFuncName, groupOrder); - curFuncInvocation->pushOperand(texcoord, Operand::OPS_IN, Operand::OPM_X); - curFuncInvocation->pushOperand(psAtlasTextureCoord, Operand::OPS_OUT, Operand::OPM_X); - psMain->addAtomInstance(curFuncInvocation); - - //calculate the V value due to addressing mode - curFuncInvocation = OGRE_NEW FunctionInvocation(addressVFuncName, groupOrder); - curFuncInvocation->pushOperand(texcoord, Operand::OPS_IN, Operand::OPM_Y); - curFuncInvocation->pushOperand(psAtlasTextureCoord, Operand::OPS_OUT, Operand::OPM_Y); - psMain->addAtomInstance(curFuncInvocation); - - //sample the texel color - curFuncInvocation = OGRE_NEW FunctionInvocation( - mAutoAdjustPollPosition ? SGX_FUNC_ATLAS_SAMPLE_AUTO_ADJUST : SGX_FUNC_ATLAS_SAMPLE_NORMAL, groupOrder); - curFuncInvocation->pushOperand(sampler, Operand::OPS_IN); - curFuncInvocation->pushOperand(texcoord, Operand::OPS_IN, Operand::OPM_XY); - curFuncInvocation->pushOperand(psAtlasTextureCoord, Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSInpTextureDatas[j], Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSTextureSizes[j], Operand::OPS_IN); - curFuncInvocation->pushOperand(texel, Operand::OPS_OUT); - psMain->addAtomInstance(curFuncInvocation); - - } - } - } - return true; -} - -//----------------------------------------------------------------------- -const char* TextureAtlasSampler::getAdressingFunctionName(TextureAddressingMode mode) -{ - switch (mode) - { - case TextureUnitState::TAM_WRAP: return SGX_FUNC_ATLAS_WRAP; - case TextureUnitState::TAM_MIRROR: return SGX_FUNC_ATLAS_MIRROR; - case TextureUnitState::TAM_CLAMP: return SGX_FUNC_ATLAS_CLAMP; - case TextureUnitState::TAM_BORDER: return SGX_FUNC_ATLAS_BORDER; - } - return NULL; -} - - -//----------------------------------------------------------------------- -void TextureAtlasSampler::copyFrom(const SubRenderState& rhs) -{ - const TextureAtlasSampler& rhsColour = static_cast(rhs); - - mAtlasTexcoordPos = rhsColour.mAtlasTexcoordPos; - for(ushort j = 0 ; j < TAS_MAX_TEXTURES ; ++j) - { - mIsAtlasTextureUnits[j] = rhsColour.mIsAtlasTextureUnits[j]; - mTextureAddressings[j] = rhsColour.mTextureAddressings[j]; - mAtlasTableDatas[j] = rhsColour.mAtlasTableDatas[j]; - mIsAtlasTextureUnits[j] = rhsColour.mIsAtlasTextureUnits[j]; - } -} - -//----------------------------------------------------------------------- -void TextureAtlasSampler::updateGpuProgramsParams(Renderable* rend, const Pass* pass, const AutoParamDataSource* source, const LightList* pLightList) -{ - if (mIsTableDataUpdated == false) - { - mIsTableDataUpdated = true; - for(ushort j = 0 ; j < TAS_MAX_TEXTURES ; ++j) - { - if (mIsAtlasTextureUnits[j] == true) - { - // - // Update the information of the size of the atlas textures - // - std::pair< size_t, size_t > texSizeInt = pass->getTextureUnitState(j)->getTextureDimensions(); - Vector2 texSize((Ogre::Real)texSizeInt.first, (Ogre::Real)texSizeInt.second); - mPSTextureSizes[j]->setGpuParameter(texSize); - - // - //Update the information of which texture exist where in the atlas - // - GpuProgramParametersSharedPtr vsGpuParams = pass->getVertexProgramParameters(); - std::vector buffer(mAtlasTableDatas[j]->size() * 4); - for(size_t i = 0 ; i < mAtlasTableDatas[j]->size() ; ++i) - { - buffer[i*4] = (*(mAtlasTableDatas[j]))[i].posU; - buffer[i*4 + 1] = (*(mAtlasTableDatas[j]))[i].posV; - buffer[i*4 + 2] = (float)Ogre::Math::Log2((*(mAtlasTableDatas[j]))[i].width * texSize.x); - buffer[i*4 + 3] = (float)Ogre::Math::Log2((*(mAtlasTableDatas[j]))[i].height * texSize.y); - } - vsGpuParams->setNamedConstant(mVSTextureTable[j]->getName(), (const float*)(&(buffer[0])), (mAtlasTableDatas[j])->size()); - } - } - } -} - -//----------------------------------------------------------------------- -bool TextureAtlasSampler::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) -{ - mAtlasTexcoordPos = 0; - - const TextureAtlasSamplerFactory& factory = TextureAtlasSamplerFactory::getSingleton(); - - bool hasAtlas = false; - unsigned short texCount = srcPass->getNumTextureUnitStates(); - for(unsigned short i = 0 ; i < texCount ; ++i) - { - TextureUnitState* pState = srcPass->getTextureUnitState(i); - - const TextureAtlasTablePtr& table = factory.getTextureAtlasTable(pState->getTextureName()); - if (table) - { - if (table->size() > TAS_MAX_SAFE_ATLASED_TEXTURES) - { - LogManager::getSingleton().logWarning( - "Compiling atlas texture has to many internally defined textures. Shader may fail to compile."); - } - if (i >= TAS_MAX_TEXTURES) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "Texture atlas sub-render does not support more than TAS_MAX_TEXTURES (4) atlas textures", - "TextureAtlasSampler::preAddToRenderState" ); - } - if (pState->getTextureType() != TEX_TYPE_2D) - { - OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, - "Texture atlas sub-render state only supports 2d textures.", - "TextureAtlasSampler::preAddToRenderState" ); - - } - - mAtlasTableDatas[i] = table; - mTextureAddressings[i] = pState->getTextureAddressingMode(); - mIsAtlasTextureUnits[i] = true; - hasAtlas = true; - } - } - - //gather the materials atlas processing attributes - //and calculate the position of the indexes - TextureAtlasSamplerFactory::TextureAtlasAttib attrib; - factory.hasMaterialAtlasingAttributes(srcPass->getParent()->getParent(), &attrib); - - mAutoAdjustPollPosition = attrib.autoBorderAdjust; - mAtlasTexcoordPos = attrib.positionOffset; - if (attrib.positionMode == TextureAtlasSamplerFactory::ipmRelative) - { - mAtlasTexcoordPos += texCount - 1; - } - - return hasAtlas; -} - -TextureAtlasSamplerFactory::TextureAtlasSamplerFactory() -{ - -} - - -TextureAtlasSamplerFactory* TextureAtlasSamplerFactory::getSingletonPtr(void) -{ - return msSingleton; -} -TextureAtlasSamplerFactory& TextureAtlasSamplerFactory::getSingleton(void) -{ - assert( msSingleton ); return ( *msSingleton ); -} - - - -//----------------------------------------------------------------------- -const String& TextureAtlasSamplerFactory::getType() const -{ - return TextureAtlasSampler::Type; -} - -//----------------------------------------------------------------------- -SubRenderState* TextureAtlasSamplerFactory::createInstance(ScriptCompiler* compiler, - PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) -{ - return NULL; -} - -//----------------------------------------------------------------------- -void TextureAtlasSamplerFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, - Pass* srcPass, Pass* dstPass) -{ -} - -//----------------------------------------------------------------------- -bool TextureAtlasSamplerFactory::addTexutreAtlasDefinition( const Ogre::String& filename, const TextureAtlasTablePtr& textureAtlasTable ) -{ - std::ifstream inp; - inp.open(filename.c_str(), std::ios::in | std::ios::binary); - if(!inp) - { - OGRE_EXCEPT(Exception::ERR_FILE_NOT_FOUND, "'" + filename + "' file not found!", - "TextureAtlasSamplerFactory::addTexutreAtlasDefinition" ); - } - DataStreamPtr stream(OGRE_NEW FileStreamDataStream(filename, &inp, false)); - return addTexutreAtlasDefinition(stream, textureAtlasTable); - -} -//----------------------------------------------------------------------- -bool TextureAtlasSamplerFactory::addTexutreAtlasDefinition( const DataStreamPtr& stream, const TextureAtlasTablePtr& textureAtlasTable ) -{ - stream->seek(0); - - bool isSuccess = false; - if (stream->isReadable() == true) - { - TextureAtlasMap tmpMap; - - while (stream->eof() == false) - { - String line = stream->getLine(true); - size_t nonWhiteSpacePos = line.find_first_not_of(" \t\r\n"); - //check this is a line with information - if ((nonWhiteSpacePos != String::npos) && (line[nonWhiteSpacePos] != '#')) - { - //parse the line - std::vector strings = StringUtil::split(line, ",\t"); - - if (strings.size() > 8) - { - String textureName = strings[1]; - - TextureAtlasMap::iterator it = tmpMap.find(textureName); - if (it == tmpMap.end()) - { - it = tmpMap.emplace(textureName, std::make_shared()).first; - } - - // file line format: /t/t, , , , , , , - // 0 1 2 3 4 5 6 7 8 - TextureAtlasRecord newRecord( - strings[0], // original texture filename - strings[1], // atlas filename - (float)StringConverter::parseReal(strings[4]), // woffset - (float)StringConverter::parseReal(strings[5]), // hoffset - (float)StringConverter::parseReal(strings[7]), // width - (float)StringConverter::parseReal(strings[8]), // height - it->second->size() // texture index in atlas texture - ); - - it->second->push_back(newRecord); - if (textureAtlasTable) - { - textureAtlasTable->push_back(newRecord); - } - - isSuccess = true; - } - } - } - - //place the information in the main texture - size_t maxTextureCount = 0; - TextureAtlasMap::const_iterator it = tmpMap.begin(); - TextureAtlasMap::const_iterator itEnd = tmpMap.end(); - for(;it != itEnd; ++it) - { - setTextureAtlasTable(it->first, it->second); - maxTextureCount = std::max(maxTextureCount, it->second->size()); - } - - if (maxTextureCount > TAS_MAX_SAFE_ATLASED_TEXTURES) - { - LogManager::getSingleton().logMessage(LML_CRITICAL, - ("Warning : " + stream->getName() + - " atlas texture has to many internally defined textures. Shader may fail to compile.")); - } - } - return isSuccess; -} - -//----------------------------------------------------------------------- -void TextureAtlasSamplerFactory::setTextureAtlasTable(const String& textureName, const TextureAtlasTablePtr& atlasData, bool autoBorderAdjust) -{ - if (!atlasData || atlasData->empty()) - removeTextureAtlasTable(textureName); - else mAtlases.emplace(textureName, atlasData); -} - -//----------------------------------------------------------------------- -void TextureAtlasSamplerFactory::removeTextureAtlasTable(const String& textureName) -{ - mAtlases.erase(textureName); -} - -//----------------------------------------------------------------------- -void TextureAtlasSamplerFactory::removeAllTextureAtlasTables() -{ - mAtlases.clear(); -} - -//----------------------------------------------------------------------- -const TextureAtlasTablePtr& TextureAtlasSamplerFactory::getTextureAtlasTable(const String& textureName) const -{ - TextureAtlasMap::const_iterator it = mAtlases.find(textureName); - if (it != mAtlases.end()) - { - return it->second; - } - else return c_BlankAtlasTable; -} - -//----------------------------------------------------------------------- -void TextureAtlasSamplerFactory::setDefaultAtlasingAttributes(IndexPositionMode mode, ushort offset, bool autoAdjustBorders) -{ - mDefaultAtlasAttrib = TextureAtlasAttib(mode, offset, autoAdjustBorders); -} - -//----------------------------------------------------------------------- -const TextureAtlasSamplerFactory::TextureAtlasAttib& TextureAtlasSamplerFactory::getDefaultAtlasingAttributes() const -{ - return mDefaultAtlasAttrib; -} - -//----------------------------------------------------------------------- -void TextureAtlasSamplerFactory::setMaterialAtlasingAttributes(Ogre::Material* material, - IndexPositionMode mode, ushort offset, bool autoAdjustBorders) -{ - if ((material) && (material->getNumTechniques())) - { - material->getTechnique(0)->getUserObjectBindings().setUserAny(c_RTAtlasKey, - TextureAtlasAttib(mode, offset, autoAdjustBorders)); - } -} - - -//----------------------------------------------------------------------- -bool TextureAtlasSamplerFactory::hasMaterialAtlasingAttributes(Ogre::Material* material, - TextureAtlasAttib* attrib) const -{ - bool isMaterialSpecific = false; - if ((material) && (material->getNumTechniques())) - { - const Ogre::Any& anyAttrib = - //find if the "IsTerrain" flag exists in the first technique - material->getTechnique(0)->getUserObjectBindings().getUserAny(c_RTAtlasKey); - isMaterialSpecific = anyAttrib.has_value(); - if ((isMaterialSpecific) && (attrib)) - { - *attrib = Ogre::any_cast(anyAttrib); - } - } - if ((!isMaterialSpecific) && (attrib)) - { - *attrib = mDefaultAtlasAttrib; - } - return isMaterialSpecific; -} - -//----------------------------------------------------------------------- -SubRenderState* TextureAtlasSamplerFactory::createInstanceImpl() -{ - return OGRE_NEW TextureAtlasSampler; -} - - -} -} - -#endif diff --git a/Samples/ShaderSystem/src/ShaderSystem.cpp b/Samples/ShaderSystem/src/ShaderSystem.cpp deleted file mode 100644 index af8a392614f..00000000000 --- a/Samples/ShaderSystem/src/ShaderSystem.cpp +++ /dev/null @@ -1,1259 +0,0 @@ -#include "SamplePlugin.h" -#include "OgreShaderSubRenderState.h" -#include "ShaderSystem.h" -#include "OgreShaderExInstancedViewports.h" -#include "OgreShaderExTextureAtlasSampler.h" -#include "OgreBillboard.h" -using namespace Ogre; -using namespace OgreBites; -using namespace Ogre::RTShader; - -//----------------------------------------------------------------------- -const String DIRECTIONAL_LIGHT_NAME = "DirectionalLight"; -const String POINT_LIGHT_NAME = "PointLight"; -const String INSTANCED_VIEWPORTS_NAME = "InstancedViewports"; -const String ADD_LOTS_OF_MODELS_NAME = "AddLotsOfModels"; -const String SPOT_LIGHT_NAME = "SpotLight"; -const String PER_PIXEL_FOG_BOX = "PerPixelFog"; -const String ATLAS_AUTO_BORDER_MODE = "AutoBorderAtlasing"; -const String MAIN_ENTITY_MESH = "ShaderSystem.mesh"; -const String SPECULAR_BOX = "SpecularBox"; -const String REFLECTIONMAP_BOX = "ReflectionMapBox"; -const String REFLECTIONMAP_POWER_SLIDER = "ReflectionPowerSlider"; -const String MAIN_ENTITY_NAME = "MainEntity"; -const String FLUSH_BUTTON_NAME = "FlushShaderCache"; -const String LAYERBLEND_BUTTON_NAME = "ChangeLayerBlendType"; -const String MODIFIER_VALUE_SLIDER = "ModifierValueSlider"; -const String SAMPLE_MATERIAL_GROUP = "RTShaderSystemMaterialsGroup"; -const int MESH_ARRAY_SIZE = 2; -const String MESH_ARRAY[MESH_ARRAY_SIZE] = -{ - MAIN_ENTITY_MESH, - "knot.mesh" -}; - -const char* blendModes[] = {"default", "normal", "lighten", "darken", "multiply", "average", - "add", "subtract", "difference", "negation", "exclusion", "screen", - "overlay", "hard_light", "soft_light", "color_dodge", "color_burn", "linear_dodge", - "linear_burn", "linear_light", "vivid_light", "pin_light", "hard_mix", "reflect", - "glow", "phoenix", "saturation", "color", "luminosity"}; -#define NUM_BLEND_MODES (sizeof(blendModes) / sizeof(blendModes[0])) - -//----------------------------------------------------------------------- -Sample_ShaderSystem::Sample_ShaderSystem() : - mLayeredBlendingEntity(NULL) -{ - mInfo["Title"] = "Shader System"; - mInfo["Description"] = "Demonstrate the capabilities of the RT Shader System component." - "1. Fixed Function Pipeline emulation." - "2. On the fly shader generation based on existing material." - "3. On the fly shader synchronization with scene state (Lights, Fog)." - "4. Built in lighting models: Per vertex, Per pixel, Normal map tangent and object space." - "5. Pluggable custom shaders extensions." - "6. Built in material script parsing that includes extended attributes." - "7. Built in material script serialization." - ; - mInfo["Thumbnail"] = "thumb_shadersystem.png"; - mInfo["Category"] = "Lighting"; - mInfo["Help"] = "F2 Toggle Shader System globally. " - "F3 Toggles Global Lighting Model. " - "Modify target model attributes and scene settings and observe the generated shaders count. " - "Press the export button in order to export current target model material. " - "The model above the target will import this material next time the sample reloads. " - "Right click on object to see the shaders it currently uses. " - ; - mPointLightNode = NULL; - mTextureAtlasFactory = NULL; - mInstancedViewportsEnable = false; - mInstancedViewportsSubRenderState = NULL; - mInstancedViewportsFactory = NULL; - mBbsFlare = NULL; - mAddedLotsOfModels = false; - mNumberOfModelsAdded = 0; - mCurrentBlendMode = NUM_BLEND_MODES - 1; -} -//----------------------------------------------------------------------- -Sample_ShaderSystem::~Sample_ShaderSystem() -{ -} -//----------------------------------------------------------------------- - -void Sample_ShaderSystem::_shutdown() -{ - mShaderGenerator->getRenderState(MSN_SHADERGEN)->resetToBuiltinSubRenderStates(); - destroyInstancedViewports(); - SdkSample::_shutdown(); -} - -//----------------------------------------------------------------------- - -void Sample_ShaderSystem::checkBoxToggled(CheckBox* box) -{ - const String& cbName = box->getName(); - - if (cbName == SPECULAR_BOX) - { - setSpecularEnable(box->isChecked()); - } - else if (cbName == DIRECTIONAL_LIGHT_NAME) - { - updateLightState(cbName, box->isChecked()); - } - else if (cbName == POINT_LIGHT_NAME) - { - updateLightState(cbName, box->isChecked()); - } - else if (cbName == INSTANCED_VIEWPORTS_NAME) - { - updateInstancedViewports(box->isChecked()); - } - else if (cbName == ADD_LOTS_OF_MODELS_NAME) - { - updateAddLotsOfModels(box->isChecked()); - } - else if (cbName == SPOT_LIGHT_NAME) - { - updateLightState(cbName, box->isChecked()); - } - else if (cbName == PER_PIXEL_FOG_BOX) - { - setPerPixelFogEnable(box->isChecked()); - } - else if (cbName == ATLAS_AUTO_BORDER_MODE) - { - setAtlasBorderMode(box->isChecked()); - } -} - -//----------------------------------------------------------------------- -void Sample_ShaderSystem::itemSelected(SelectMenu* menu) -{ - if (menu == mLightingModelMenu) - { - int curModelIndex = menu->getSelectionIndex(); - - if (curModelIndex >= SSLM_PerPixelLighting&& curModelIndex <= SSLM_NormalMapLightingObjectSpace) - { - setCurrentLightingModel((ShaderSystemLightingModel)curModelIndex); - } - } - else if (menu == mFogModeMenu) - { - int curModeIndex = menu->getSelectionIndex(); - - if (curModeIndex >= FOG_NONE && curModeIndex <= FOG_LINEAR) - { - mSceneMgr->setFog((FogMode)curModeIndex, ColourValue(1.0, 1.0, 1.0, 0.0), 0.0015, 350.0, 1500.0); - } - } - else if (menu == mShadowMenu) - { - int curShadowTypeIndex = menu->getSelectionIndex(); - - applyShadowType(curShadowTypeIndex); - } -} - -//----------------------------------------------------------------------- -void Sample_ShaderSystem::buttonHit( OgreBites::Button* b ) -{ - // Case the shader cache should be flushed. - if (b->getName() == FLUSH_BUTTON_NAME) - { - mShaderGenerator->flushShaderCache(); - } - - // Case the blend layer type modified. - else if (b->getName() == LAYERBLEND_BUTTON_NAME && mLayerBlendSubRS) - { - changeTextureLayerBlendMode(); - - } -} - -//-------------------------------------------------------------------------- -void Sample_ShaderSystem::sliderMoved(Slider* slider) -{ - if (slider->getName() == REFLECTIONMAP_POWER_SLIDER && mReflectionMapSubRS) - { - String luminance = std::to_string(slider->getValue()); - - // Grab the instances set and update them with the new reflection power value. - // The instances are the actual sub render states that have been assembled to create the final shaders. - // Every time that the shaders have to be re-generated (light changes, fog changes etc..) a new set of sub render states - // based on the template sub render states assembled for each pass. - // From that set of instances a CPU program is generated and afterward a GPU program finally generated. - auto instanceSet = mReflectionMapSubRS->getAccessor()->getSubRenderStateInstanceSet(); - for (auto inst : instanceSet) - { - inst->setParameter("luminance", luminance); - } - } - - if (slider->getName() == MODIFIER_VALUE_SLIDER) - { - if (mLayeredBlendingEntity != NULL) - { - Ogre::Real val = mModifierValueSlider->getValue(); - mLayeredBlendingEntity->getSubEntity(0)->setCustomParameter(2, Vector4f(val,val,val,0)); - } - } -} - -//----------------------------------------------------------------------- -bool Sample_ShaderSystem::frameRenderingQueued( const FrameEvent& evt ) -{ - if (mPointLightNode != NULL) - { - static Real sToatalTime = 0.0; - - sToatalTime += evt.timeSinceLastFrame; - mPointLightNode->yaw(Degree(evt.timeSinceLastFrame * 15)); - mPointLightNode->setPosition(0.0, Math::Sin(sToatalTime) * 30.0, 0.0); - } - - updateTargetObjInfo(); - - return SdkSample::frameRenderingQueued(evt); -} - -//----------------------------------------------------------------------- -void Sample_ShaderSystem::setupContent() -{ - - // Setup default effects values. - mCurLightingModel = SSLM_PerPixelLighting; - mPerPixelFogEnable = false; - mSpecularEnable = false; - mReflectionMapSubRS = NULL; - mLayerBlendSubRS = NULL; - - mRayQuery = mSceneMgr->createRayQuery(Ray()); - mTargetObj = NULL; - - - // Set ambient lighting. - mSceneMgr->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); - - // Setup the sky box, - mSceneMgr->setSkyBox(true, "Examples/SceneSkyBox2"); - - MeshManager::getSingleton().createPlane("Myplane", - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Plane(Vector3::UNIT_Y, 0), - 1500,1500,25,25,true,1,60,60,Vector3::UNIT_Z); - - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("Examples/Rockwall"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,0,0))->attachObject(pPlaneEnt); - - mCamera->setNearClipDistance(30); - - // Load sample meshes and generate tangent vectors. - for (const auto & curMeshName : MESH_ARRAY) - { - MeshPtr pMesh = MeshManager::getSingleton().load(curMeshName, - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY, - HardwareBuffer::HBU_STATIC_WRITE_ONLY, - true, true); //so we can still read it - - // Build tangent vectors, all our meshes use only 1 texture coordset - pMesh->buildTangentVectors(); - } - - - - Entity* entity; - SceneNode* childNode; - - // Create the main entity and mark it as the current target object. - entity = mSceneMgr->createEntity(MAIN_ENTITY_NAME, MAIN_ENTITY_MESH); - mTargetEntities.push_back(entity); - childNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - childNode->attachObject(entity); - mTargetObj = entity; - childNode->showBoundingBox(true); - - // Create reflection entity that will show the exported material. - MaterialPtr matMainEnt = mSceneMgr->getEntity(MAIN_ENTITY_NAME)->getSubEntity(0)->getMaterial()->clone("_RTSS_Export"); - - entity = mSceneMgr->createEntity("ExportedMaterialEntity", MAIN_ENTITY_MESH); - entity->setMaterial(matMainEnt); - childNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - childNode->setPosition(0.0, 200.0, -200.0); - childNode->attachObject(entity); - - // Create texture layer blending demonstration entity. - mLayeredBlendingEntity = mSceneMgr->createEntity("LayeredBlendingMaterialEntity", MAIN_ENTITY_MESH); - mLayeredBlendingEntity->setMaterialName("RTSS/LayeredBlending"); - mLayeredBlendingEntity->getSubEntity(0)->setCustomParameter(2, Vector4f(0)); - childNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - childNode->setPosition(300.0, 200.0, -200.0); - childNode->attachObject(mLayeredBlendingEntity); - - // Grab the render state of the material. - auto renderState = mShaderGenerator->getRenderState(MSN_SHADERGEN, "RTSS/LayeredBlending", RGN_DEFAULT, 0); - - if (renderState) - { - // Search for the texture layer blend sub state. - if (auto srs = renderState->getSubRenderState(SRS_LAYERED_BLENDING)) - { - mLayerBlendSubRS = static_cast(srs); - } - } - - - // Create per pixel lighting demonstration entity. - entity = mSceneMgr->createEntity("PerPixelEntity", "knot.mesh"); - entity->setMaterialName("RTSS/PerPixel_SinglePass"); - childNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - childNode->setPosition(300.0, 100.0, -100.0); - childNode->attachObject(entity); - - // Create normal map lighting demonstration entity. - entity = mSceneMgr->createEntity("NormalMapEntity", "knot.mesh"); - entity->setMaterialName("RTSS/NormalMapping_SinglePass"); - childNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - childNode->setPosition(-300.0, 100.0, -100.0); - childNode->attachObject(entity); - - // OpenGL ES 2.0 does not support texture atlases. But ES 3.0 does! - if (Root::getSingletonPtr()->getRenderSystem()->getName().find("OpenGL ES 2") == String::npos - || Root::getSingletonPtr()->getRenderSystem()->getNativeShadingLanguageVersion() >= 300) - { - RTShader::RenderState* pMainRenderState = - RTShader::ShaderGenerator::getSingleton().createOrRetrieveRenderState(MSN_SHADERGEN).first; - pMainRenderState->addTemplateSubRenderState( - mShaderGenerator->createSubRenderState()); - - // Create texture atlas object and node - ManualObject* atlasObject = createTextureAtlasObject(); - childNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - childNode->setPosition(-600.0, 0, -850.0); - childNode->attachObject(atlasObject); - } - - createDirectionalLight(); - createPointLight(); - createSpotLight(); - - setupUI(); - - - mCameraNode->setPosition(0.0, 300.0, 450.0); - mCameraNode->lookAt(Vector3(0.0, 150.0, 0.0), Node::TS_PARENT); - - // Make this viewport work with shader generator scheme. - mViewport->setMaterialScheme(MSN_SHADERGEN); - - // a friendly reminder - StringVector names; - names.push_back("Help"); - mTrayMgr->createParamsPanel(TL_TOPLEFT, "Help", 100, names)->setParamValue(0, "H/F1"); - - updateSystemShaders(); -} - -//----------------------------------------------------------------------- -void Sample_ShaderSystem::setupUI() -{ - // Create language label - mLanguage = mTrayMgr->createLabel(TL_TOPLEFT, "Language", "Language: "+mShaderGenerator->getTargetLanguage(), 220); - - // create check boxes to toggle lights. - mDirLightCheckBox = mTrayMgr->createCheckBox(TL_TOPLEFT, DIRECTIONAL_LIGHT_NAME, "Directional Light", 220); - mPointLightCheckBox = mTrayMgr->createCheckBox(TL_TOPLEFT, POINT_LIGHT_NAME, "Point Light", 220); - mSpotLightCheckBox = mTrayMgr->createCheckBox(TL_TOPLEFT, SPOT_LIGHT_NAME, "Spot Light", 220); - - mInstancedViewportsCheckBox = mTrayMgr->createCheckBox(TL_TOPLEFT, INSTANCED_VIEWPORTS_NAME, "Instanced Viewports", 220); - mAddLotsOfModels = mTrayMgr->createCheckBox(TL_TOPLEFT, ADD_LOTS_OF_MODELS_NAME, "Add lots of models", 220); - - mDirLightCheckBox->setChecked(true); - mPointLightCheckBox->setChecked(true); - mSpotLightCheckBox->setChecked(false); - mInstancedViewportsCheckBox->setChecked(false); - mAddLotsOfModels->setChecked(false); - - -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS - mTrayMgr->createCheckBox(TL_TOPLEFT, PER_PIXEL_FOG_BOX, "Per Pixel Fog", 220)->setChecked(mPerPixelFogEnable); -#endif - -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS - mTrayMgr->createCheckBox(TL_TOPLEFT, ATLAS_AUTO_BORDER_MODE, "Atlas auto border", 220)->setChecked(true); - setAtlasBorderMode(true); -#endif - - // Create fog widgets. - mFogModeMenu = mTrayMgr->createLongSelectMenu(TL_TOPLEFT, "FogMode", "Fog Mode", 220, 120, 10); - mFogModeMenu->addItem("None"); - mFogModeMenu->addItem("Exp"); - mFogModeMenu->addItem("Exp2"); - mFogModeMenu->addItem("Linear"); - - // Create shadow menu. - mShadowMenu = mTrayMgr->createLongSelectMenu(TL_TOPLEFT, "ShadowType", "Shadow", 220, 120, 10); - mShadowMenu->addItem("None"); - -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS - mShadowMenu->addItem("PSSM 3"); - mShadowMenu->addItem("PSSM debug"); -#endif - - - // Flush shader cache button. - mTrayMgr->createButton(TL_TOPLEFT, FLUSH_BUTTON_NAME, "Flush Shader Cache", 220); - - // create target model widgets. - mTargetObjMatName = mTrayMgr->createLabel(TL_TOPLEFT, "TargetObjMatName", "", 220); - mTargetObjVS = mTrayMgr->createLabel(TL_TOPLEFT, "TargetObjVS", "", 220); - mTargetObjFS = mTrayMgr->createLabel(TL_TOPLEFT, "TargetObjFS", "", 220); - - - // Create main entity widgets. - mTrayMgr->createLabel(TL_BOTTOM, "MainEntityLabel", "Main Entity Settings", 240); - mTrayMgr->createCheckBox(TL_BOTTOM, SPECULAR_BOX, "Specular", 240)->setChecked(mSpecularEnable); - - mLightingModelMenu = mTrayMgr->createLongSelectMenu(TL_BOTTOM, "TargetModelLighting", "", 240, 230, 10); - mLightingModelMenu ->addItem("Per Pixel"); - mLightingModelMenu ->addItem("Cook Torrance"); - mLightingModelMenu ->addItem("Image Based"); - mLightingModelMenu ->addItem("Normal Map - Tangent Space"); - mLightingModelMenu ->addItem("Normal Map - Object Space"); - - mReflectionPowerSlider = mTrayMgr->createThickSlider(TL_BOTTOM, REFLECTIONMAP_POWER_SLIDER, "IBL Luminace", 240, 80, 0, 5, 100); - mReflectionPowerSlider->setValue(0.5, false); - -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS - mLayerBlendLabel = mTrayMgr->createLabel(TL_RIGHT, "Blend Type", "Blend Type", 240); - mTrayMgr->createButton(TL_RIGHT, LAYERBLEND_BUTTON_NAME, "Change Blend Type", 220); - mModifierValueSlider = mTrayMgr->createThickSlider(TL_RIGHT, MODIFIER_VALUE_SLIDER, "Modifier", 240, 80, 0, 1, 100); - mModifierValueSlider->setValue(0.0,false); - // Update the caption. - mLayerBlendLabel->setCaption(blendModes[mCurrentBlendMode]); -#endif - - mTrayMgr->showCursor(); -} - -//----------------------------------------------------------------------- -void Sample_ShaderSystem::cleanupContent() -{ - // UnLoad sample meshes and generate tangent vectors. - for (const auto & curMeshName : MESH_ARRAY) - { - MeshManager::getSingleton().unload(curMeshName, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - } - - MeshManager::getSingleton().remove(MAIN_ENTITY_MESH, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - mTargetEntities.clear(); - - MeshManager::getSingleton().remove("Myplane", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - mSceneMgr->destroyQuery(mRayQuery); -} - -//----------------------------------------------------------------------- -void Sample_ShaderSystem::setCurrentLightingModel(ShaderSystemLightingModel lightingModel) -{ - if (mCurLightingModel != lightingModel) - { - mCurLightingModel = lightingModel; - - updateSystemShaders(); - } -} - -//----------------------------------------------------------------------- -void Sample_ShaderSystem::setSpecularEnable(bool enable) -{ - if (mSpecularEnable != enable) - { - mSpecularEnable = enable; - updateSystemShaders(); - } -} - -//----------------------------------------------------------------------- -void Sample_ShaderSystem::setPerPixelFogEnable( bool enable ) -{ -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS - if (mPerPixelFogEnable != enable) - { - mPerPixelFogEnable = enable; - - // Grab the scheme render state. - RenderState* schemRenderState = mShaderGenerator->getRenderState(MSN_SHADERGEN); - // Search for the fog sub state. - auto fogSubRenderState = schemRenderState->getSubRenderState(SRS_FOG); - - // Select the desired fog calculation mode. - fogSubRenderState->setParameter("calc_mode", mPerPixelFogEnable ? "per_pixel" : "per_vertex"); - - // Invalidate the scheme in order to re-generate all shaders based technique related to this scheme. - mShaderGenerator->invalidateScheme(Ogre::MSN_SHADERGEN); - } -#endif - -} - -void Sample_ShaderSystem::setAtlasBorderMode( bool enable ) -{ -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS - TextureAtlasSamplerFactory::getSingleton().setDefaultAtlasingAttributes( - TextureAtlasSamplerFactory::ipmRelative, 1, enable); - mShaderGenerator->invalidateScheme(Ogre::MSN_SHADERGEN); -#endif -} - - -//----------------------------------------------------------------------- -void Sample_ShaderSystem::updateSystemShaders() -{ - for (auto e : mTargetEntities) - { - generateShaders(e); - } -} - -//----------------------------------------------------------------------- -static void setNormalMap(Pass* pass, const String& normalMapName) -{ - if(pass->getNumTextureUnitStates() > 1) - { - // remove the previous normal map - pass->removeTextureUnitState(1); - } - - auto tu = pass->createTextureUnitState(normalMapName); - ShaderGenerator::_markNonFFP(tu); -} - -void Sample_ShaderSystem::generateShaders(Entity* entity) -{ - for (unsigned int i=0; i < entity->getNumSubEntities(); ++i) - { - SubEntity* curSubEntity = entity->getSubEntity(i); - MaterialPtr curMaterial = curSubEntity->getMaterial(); - bool success; - - // Create the shader based technique of this material. - success = mShaderGenerator->createShaderBasedTechnique(*curMaterial, MSN_DEFAULT, MSN_SHADERGEN); - - // Setup custom shader sub render states according to current setup. - if (success) - { - Pass* curPass = curMaterial->getTechnique(0)->getPass(0); - - bool cookTorrance = mCurLightingModel == SSLM_CookTorranceLighting || mCurLightingModel == SSLM_ImageBasedLighting; - - if (mSpecularEnable) - { - curPass->setSpecular(!cookTorrance ? ColourValue::White : ColourValue(0.1, 0.0)); - curPass->setShininess(32.0); - } - else - { - curPass->setSpecular(!cookTorrance ? ColourValue::Black : ColourValue(1.0, 0.0)); - curPass->setShininess(0.0); - } - - - // Grab the first pass render state. - // NOTE: For more complicated samples iterate over the passes and build each one of them as desired. - RTShader::RenderState* renderState = mShaderGenerator->getRenderState( - MSN_SHADERGEN, *curMaterial); - - // Remove all sub render states. - renderState->resetToBuiltinSubRenderStates(); - - -#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS - if (mCurLightingModel == SSLM_CookTorranceLighting || mCurLightingModel == SSLM_ImageBasedLighting) - { - auto lightModel = mShaderGenerator->createSubRenderState(RTShader::SRS_COOK_TORRANCE_LIGHTING); - renderState->addTemplateSubRenderState(lightModel); - } - else if (mCurLightingModel == SSLM_PerPixelLighting) - { - RTShader::SubRenderState* perPixelLightModel = mShaderGenerator->createSubRenderState(RTShader::SRS_PER_PIXEL_LIGHTING); - - renderState->addTemplateSubRenderState(perPixelLightModel); - } - else if (mCurLightingModel == SSLM_NormalMapLightingObjectSpace) - { - // Apply normal map only on main entity. - if (entity->getName() == MAIN_ENTITY_NAME) - { - RTShader::SubRenderState* normalMapSubRS = mShaderGenerator->createSubRenderState(RTShader::SRS_NORMALMAP); - - normalMapSubRS->setParameter("normalmap_space", "object_space"); - setNormalMap(curPass, "Panels_Normal_Obj.png"); - normalMapSubRS->setParameter("texture_index", "1"); - renderState->addTemplateSubRenderState(normalMapSubRS); - } - - // It is secondary entity -> use simple per pixel lighting. - else - { - RTShader::SubRenderState* perPixelLightModel = mShaderGenerator->createSubRenderState(RTShader::SRS_PER_PIXEL_LIGHTING); - renderState->addTemplateSubRenderState(perPixelLightModel); - } - } - - if (mCurLightingModel == SSLM_NormalMapLightingTangentSpace || - mCurLightingModel == SSLM_CookTorranceLighting || mCurLightingModel == SSLM_ImageBasedLighting) - { - // Apply normal map only on main entity. - if (entity->getName() == MAIN_ENTITY_NAME) - { - RTShader::SubRenderState* normalMapSubRS = mShaderGenerator->createSubRenderState(RTShader::SRS_NORMALMAP); - - normalMapSubRS->setParameter("normalmap_space", "tangent_space"); - setNormalMap(curPass, "Panels_Normal_Tangent.png"); - normalMapSubRS->setParameter("texture_index", "1"); - - renderState->addTemplateSubRenderState(normalMapSubRS); - } - - // It is secondary entity -> use simple per pixel lighting. - else - { - RTShader::SubRenderState* perPixelLightModel = mShaderGenerator->createSubRenderState(RTShader::SRS_PER_PIXEL_LIGHTING); - renderState->addTemplateSubRenderState(perPixelLightModel); - } - } -#endif - if (mCurLightingModel == SSLM_ImageBasedLighting) - { - RTShader::SubRenderState* subRenderState = mShaderGenerator->createSubRenderState(RTShader::SRS_IMAGE_BASED_LIGHTING); - subRenderState->setParameter("texture", "studio_garden.jpg"); - subRenderState->setParameter("luminance", std::to_string(mReflectionPowerSlider->getValue())); - renderState->addTemplateSubRenderState(subRenderState); - mReflectionMapSubRS = subRenderState; - } - else - { - mReflectionMapSubRS = NULL; - } - - // Invalidate this material in order to re-generate its shaders. - mShaderGenerator->invalidateMaterial(MSN_SHADERGEN, - *curMaterial); - } - } -} - -//----------------------------------------------------------------------- -void Sample_ShaderSystem::createDirectionalLight() -{ - Light* light; - Vector3 dir; - - light = mSceneMgr->createLight(DIRECTIONAL_LIGHT_NAME); - light->setType(Light::LT_DIRECTIONAL); - light->setCastShadows(true); - dir.x = 0.5; - dir.y = -1.0; - dir.z = 0.3; - dir.normalise(); - light->setDiffuseColour(0.65, 0.15, 0.15); - light->setSpecularColour(0.5, 0.5, 0.5); - - // create pivot node - mDirectionalLightNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mDirectionalLightNode->setDirection(dir); - - // Create billboard set. - mBbsFlare = mSceneMgr->createBillboardSet(); - mBbsFlare->setMaterialName("Examples/Flare3"); - mBbsFlare->createBillboard(-dir * 500.0)->setColour(light->getDiffuseColour()); - mBbsFlare->setCastShadows(false); - - mDirectionalLightNode->attachObject(mBbsFlare); - mDirectionalLightNode->attachObject(light); -} - -//----------------------------------------------------------------------- -void Sample_ShaderSystem::createPointLight() -{ - Light* light; - - light = mSceneMgr->createLight(POINT_LIGHT_NAME); - light->setType(Light::LT_POINT); - light->setCastShadows(false); - light->setDiffuseColour(0.15, 0.65, 0.15); - light->setSpecularColour(0.5, 0.5, 0.5); - light->setAttenuation(250.0, 0.5, 0, 0.00003); - - // create pivot node - mPointLightNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - BillboardSet* bbs; - - // Create billboard set. - bbs = mSceneMgr->createBillboardSet(); - bbs->setMaterialName("Examples/Flare3"); - bbs->createBillboard(200, 100, 0)->setColour(light->getDiffuseColour()); - bbs->setCastShadows(false); - - mPointLightNode->attachObject(bbs); - SceneNode* ln = mPointLightNode->createChildSceneNode(Vector3(200, 100, 0)); - ln->attachObject(light); - ln->setDirection(1, 0, 0); -} - -//----------------------------------------------------------------------- -void Sample_ShaderSystem::createSpotLight() -{ - Light* light; - light = mSceneMgr->createLight(SPOT_LIGHT_NAME); - light->setType(Light::LT_SPOTLIGHT); - light->setCastShadows(false); - light->setSpotlightRange(Degree(20.0), Degree(25.0), 0.95); - light->setDiffuseColour(0.15, 0.15, 0.65); - light->setSpecularColour(0.5, 0.5, 0.5); - light->setAttenuation(1000.0, 1.0, 0.0005, 0.0); - - auto ln = mCameraNode->createChildSceneNode(Vector3::UNIT_Y * 20); - ln->attachObject(light); -} - -void Sample_ShaderSystem::addModelToScene(const String & modelName) -{ - mNumberOfModelsAdded++; - for(int i = 0 ; i < 8 ; i++) - { - float scaleFactor = 30; - Entity* entity; - SceneNode* childNode; - entity = mSceneMgr->createEntity(modelName); - mLotsOfModelsEntities.push_back(entity); - childNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mLotsOfModelsNodes.push_back(childNode); - childNode->setPosition(mNumberOfModelsAdded * scaleFactor, 15, i * scaleFactor); - childNode->attachObject(entity); - MeshPtr modelMesh = MeshManager::getSingleton().getByName(modelName, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - Vector3 modelSize = modelMesh->getBounds().getSize(); - childNode->scale(1 / modelSize.x * scaleFactor, - 1 / modelSize.y * scaleFactor, - 1 / modelSize.z * scaleFactor - ); - } -} - -void Sample_ShaderSystem::updateAddLotsOfModels(bool addThem) -{ - if (mAddedLotsOfModels != addThem) - { - mAddedLotsOfModels = addThem; - - if(mNumberOfModelsAdded == 0) - { - addModelToScene("Barrel.mesh"); - addModelToScene("facial.mesh"); - addModelToScene("fish.mesh"); - addModelToScene("ninja.mesh"); - addModelToScene("penguin.mesh"); - addModelToScene("razor.mesh"); - addModelToScene("RZR-002.mesh"); - addModelToScene("tudorhouse.mesh"); - addModelToScene("WoodPallet.mesh"); - } - for (auto & n : mLotsOfModelsNodes) - { - n->setVisible(mAddedLotsOfModels); - } - - } -} -//----------------------------------------------------------------------- -void Sample_ShaderSystem::updateInstancedViewports(bool enabled) -{ - if (mInstancedViewportsEnable != enabled) - { - mInstancedViewportsEnable = enabled; - - if (mInstancedViewportsEnable) - { - mCamera->setCullingFrustum(&mInfiniteFrustum); - - // having problems with bb... - mDirectionalLightNode->detachObject(mBbsFlare); - } - else - { - mCamera->setCullingFrustum(NULL); - mDirectionalLightNode->attachObject(mBbsFlare); - } - - - - if(mInstancedViewportsEnable) - { - createInstancedViewports(); - } - else - { - destroyInstancedViewports(); - } - - } -} -//----------------------------------------------------------------------- -void Sample_ShaderSystem::updateLightState(const String& lightName, bool visible) -{ - if (mSceneMgr->hasLight(lightName)) - { - // Case it is the point light, - // toggle its visibility and billboard set visibility. - if (lightName == POINT_LIGHT_NAME) - { - if (visible) - { - if (mPointLightNode->isInSceneGraph() == false) - { - mSceneMgr->getRootSceneNode()->addChild(mPointLightNode); - } - } - else - { - if (mPointLightNode->isInSceneGraph() == true) - { - mSceneMgr->getRootSceneNode()->removeChild(mPointLightNode); - } - } - mSceneMgr->getLight(lightName)->setVisible(visible); - } - - // Case it is the directional light, - // toggle its visibility and billboard set visibility. - else if (lightName == DIRECTIONAL_LIGHT_NAME) - { - mDirectionalLightNode->setVisible(visible, false); - } - - // Spot light has no scene node representation. - else - { - mSceneMgr->getLight(lightName)->setVisible(visible); - } - - // Invalidate the scheme in order to re-generate all shaders based technique related to this scheme. - mShaderGenerator->invalidateScheme(Ogre::MSN_SHADERGEN); - } -} - -//----------------------------------------------------------------------- -void Sample_ShaderSystem::applyShadowType(int menuIndex) -{ - // Grab the scheme render state. - Ogre::RTShader::RenderState* schemRenderState = mShaderGenerator->getRenderState(Ogre::MSN_SHADERGEN); - - - // No shadow - if (menuIndex == 0) - { - mSceneMgr->setShadowTechnique(SHADOWTYPE_NONE); - -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS - if (auto srs = schemRenderState->getSubRenderState(SRS_SHADOW_MAPPING)) - { - schemRenderState->removeSubRenderState(srs); - } -#endif - - mTrayMgr->moveWidgetToTray(mDirLightCheckBox, TL_TOPLEFT, 1); - mTrayMgr->moveWidgetToTray(mPointLightCheckBox, TL_TOPLEFT, 2); - mTrayMgr->moveWidgetToTray(mSpotLightCheckBox, TL_TOPLEFT, 3); - - mDirLightCheckBox->show(); - mPointLightCheckBox->show(); - mSpotLightCheckBox->show(); - - } - -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS - // Integrated shadow PSSM with 3 splits. - else if (menuIndex >= 1) - { - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE_INTEGRATED); - mSceneMgr->setShadowFarDistance(3000); - - // 3 textures per directional light - mSceneMgr->setShadowTextureCountPerLightType(Ogre::Light::LT_DIRECTIONAL, 3); - mSceneMgr->setShadowTextureSettings(512, 3, PF_DEPTH16); - mSceneMgr->setShadowTextureSelfShadow(true); - - // Leave only directional light. - mDirLightCheckBox->setChecked(true); - mPointLightCheckBox->setChecked(false); - mSpotLightCheckBox->setChecked(false); - - mTrayMgr->removeWidgetFromTray(mDirLightCheckBox); - mDirLightCheckBox->hide(); - - // Disable fog on the caster pass. - MaterialPtr passCaterMaterial = MaterialManager::getSingleton().getByName("PSSM/shadow_caster"); - Pass* pssmCasterPass = passCaterMaterial->getTechnique(0)->getPass(0); - pssmCasterPass->setFog(true); - - // Set up caster material - this is just a standard depth/shadow map caster - mSceneMgr->setShadowTextureCasterMaterial(passCaterMaterial); - - // shadow camera setup - PSSMShadowCameraSetup* pssmSetup = new PSSMShadowCameraSetup(); - pssmSetup->calculateSplitPoints(3, mCamera->getNearClipDistance(), mSceneMgr->getShadowFarDistance()); - pssmSetup->setSplitPadding(mCamera->getNearClipDistance()*2); - pssmSetup->setOptimalAdjustFactor(0, 2); - pssmSetup->setOptimalAdjustFactor(1, 1); - pssmSetup->setOptimalAdjustFactor(2, 0.5); - - mSceneMgr->setShadowCameraSetup(ShadowCameraSetupPtr(pssmSetup)); - - - auto subRenderState = mShaderGenerator->createSubRenderState(SRS_SHADOW_MAPPING); - subRenderState->setParameter("split_points", pssmSetup->getSplitPoints()); - subRenderState->setParameter("debug", menuIndex > 1); - schemRenderState->addTemplateSubRenderState(subRenderState); - } -#endif - - // Invalidate the scheme in order to re-generate all shaders based technique related to this scheme. - mShaderGenerator->invalidateScheme(Ogre::MSN_SHADERGEN); -} - -//----------------------------------------------------------------------- -void Sample_ShaderSystem::testCapabilities( const RenderSystemCapabilities* caps ) -{ - if(RTShader::ShaderGenerator::getSingleton().getTargetLanguage() != "null") - return; - - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "RTSS not supported on your system"); -} - -//----------------------------------------------------------------------- -void Sample_ShaderSystem::loadResources() -{ - mTextureAtlasFactory = OGRE_NEW TextureAtlasSamplerFactory; - mShaderGenerator->addSubRenderStateFactory(mTextureAtlasFactory); -} - -//----------------------------------------------------------------------- -void Sample_ShaderSystem::unloadResources() -{ - if (mTextureAtlasFactory != NULL) - { - mTextureAtlasFactory->destroyAllInstances(); - mShaderGenerator->removeSubRenderStateFactory(mTextureAtlasFactory); - OGRE_DELETE mTextureAtlasFactory; - mTextureAtlasFactory = NULL; - } -} - -//----------------------------------------------------------------------- -void Sample_ShaderSystem::pickTargetObject( const MouseButtonEvent &evt ) -{ - int xPos = evt.x; - int yPos = evt.y; - int width = mWindow->getWidth(), height = mWindow->getHeight(); - - Ray mouseRay = mCamera->getCameraToViewportRay(xPos / float(width), yPos/float(height)); - mRayQuery->setRay(mouseRay); - - RaySceneQueryResult &result = mRayQuery->execute(); - RaySceneQueryResult::iterator it = result.begin(); - RaySceneQueryResult::iterator itEnd = result.end(); - - for (; it != itEnd; ++it) - { - RaySceneQueryResultEntry& curEntry = *it; - - if (mTargetObj != NULL) - { - mTargetObj->getParentSceneNode()->showBoundingBox(false); - } - - mTargetObj = curEntry.movable; - mTargetObj ->getParentSceneNode()->showBoundingBox(true); - } -} - -//----------------------------------------------------------------------- -void Sample_ShaderSystem::updateTargetObjInfo() -{ - if (mTargetObj == NULL) - return; - - String targetObjMaterialName; - - if (mTargetObj->getMovableType() == MOT_ENTITY) - { - Entity* targetEnt = static_cast(mTargetObj); - targetObjMaterialName = targetEnt->getSubEntity(0)->getMaterialName(); - } - - mTargetObjMatName->setCaption(targetObjMaterialName); - - if (mViewport->getMaterialScheme() == MSN_SHADERGEN) - { - MaterialPtr matMainEnt = MaterialManager::getSingleton().getByName(targetObjMaterialName); - - if (!matMainEnt == false) - { - Technique* shaderGeneratedTech = NULL; - - for (unsigned int i=0; i < matMainEnt->getNumTechniques(); ++i) - { - Technique* curTech = matMainEnt->getTechnique(i); - - if (curTech->getSchemeName() == MSN_SHADERGEN) - { - shaderGeneratedTech = curTech; - break; - } - } - - if (shaderGeneratedTech != NULL) - { - mTargetObjVS->setCaption("VS: " + shaderGeneratedTech->getPass(0)->getVertexProgramName()); - mTargetObjFS->setCaption("FS: " + shaderGeneratedTech->getPass(0)->getFragmentProgramName()); - } - - } - - - } - else - { - mTargetObjVS->setCaption("VS: N/A"); - mTargetObjFS->setCaption("FS: N/A"); - } -} - - -//----------------------------------------------------------------------- -void Sample_ShaderSystem::changeTextureLayerBlendMode() -{ - // Update the next blend layer mode. - mCurrentBlendMode = (mCurrentBlendMode + 1) % NUM_BLEND_MODES; - - mLayerBlendSubRS->setBlendMode(1, blendModes[mCurrentBlendMode]); - mShaderGenerator->invalidateMaterial(MSN_SHADERGEN, "RTSS/LayeredBlending", RGN_DEFAULT); - - mLayerBlendLabel->setCaption(blendModes[mCurrentBlendMode]); -} - -//----------------------------------------------------------------------- -bool Sample_ShaderSystem::mousePressed(const MouseButtonEvent& evt) -{ - if (mTrayMgr->mousePressed(evt)) - return true; - if (evt.button == BUTTON_LEFT) - mTrayMgr->hideCursor(); // hide the cursor if user left-clicks in the scene - if (evt.button == BUTTON_RIGHT) - pickTargetObject(evt); - - return true; -} - -//----------------------------------------------------------------------- -bool Sample_ShaderSystem::mouseReleased(const MouseButtonEvent& evt) -{ - if (mTrayMgr->mouseReleased(evt)) - return true; - if (evt.button == BUTTON_LEFT) - mTrayMgr->showCursor(); // unhide the cursor if user lets go of LMB - - return true; -} - -//----------------------------------------------------------------------- -bool Sample_ShaderSystem::mouseMoved(const MouseMotionEvent& evt) -{ - // only rotate the camera if cursor is hidden - if (mTrayMgr->isCursorVisible()) - mTrayMgr->mouseMoved(evt); - else - mCameraMan->mouseMoved(evt); - - - return true; -} -//----------------------------------------------------------------------- - -void Sample_ShaderSystem::destroyInstancedViewports() -{ - if (mInstancedViewportsSubRenderState) - { - Ogre::RTShader::RenderState* renderState = mShaderGenerator->getRenderState(Ogre::MSN_SHADERGEN); - renderState->removeSubRenderState(mInstancedViewportsSubRenderState); - mInstancedViewportsSubRenderState = NULL; - } - - mShaderGenerator->invalidateScheme(Ogre::MSN_SHADERGEN); - mShaderGenerator->validateScheme(Ogre::MSN_SHADERGEN); - - destroyInstancedViewportsFactory(); - -} -//----------------------------------------------------------------------- -void Sample_ShaderSystem::destroyInstancedViewportsFactory() -{ - if (mInstancedViewportsFactory != NULL) - { - mInstancedViewportsFactory->destroyAllInstances(); - mShaderGenerator->removeSubRenderStateFactory(mInstancedViewportsFactory); - delete mInstancedViewportsFactory; - mInstancedViewportsFactory = NULL; - } -} -//----------------------------------------------------------------------- - -void Sample_ShaderSystem::createInstancedViewports() -{ - if (mInstancedViewportsFactory == NULL) - { - mInstancedViewportsFactory = OGRE_NEW ShaderExInstancedViewportsFactory; - mShaderGenerator->addSubRenderStateFactory(mInstancedViewportsFactory); - } - - Ogre::Vector2 monitorCount(2.0, 2.0); - mInstancedViewportsSubRenderState = mShaderGenerator->createSubRenderState(); - Ogre::RTShader::ShaderExInstancedViewports* shaderExInstancedViewports - = static_cast(mInstancedViewportsSubRenderState); - shaderExInstancedViewports->setMonitorsCount(monitorCount); - Ogre::RTShader::RenderState* renderState = mShaderGenerator->getRenderState(Ogre::MSN_SHADERGEN); - renderState->addTemplateSubRenderState(mInstancedViewportsSubRenderState); - - // Invalidate the scheme in order to re-generate all shaders based technique related to this scheme. - mShaderGenerator->invalidateScheme(Ogre::MSN_SHADERGEN); - mShaderGenerator->validateScheme(Ogre::MSN_SHADERGEN); -} - -void Sample_ShaderSystem::createMaterialForTexture( const String & texName, bool isTextureAtlasTexture ) -{ - MaterialManager * matMgr = MaterialManager::getSingletonPtr(); - if ( !matMgr->resourceExists(texName, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME) ) - { - MaterialPtr newMat = matMgr->create(texName, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - newMat->getTechnique(0)->getPass(0)->setLightingEnabled(false); - TextureUnitState* pState = newMat->getTechnique(0)->getPass(0)->createTextureUnitState(texName); - if(isTextureAtlasTexture) - { - // to solve wrap edge bleed - pState->setTextureFiltering(TFO_TRILINEAR); - } - } - -} - -ManualObject* Sample_ShaderSystem::createTextureAtlasObject() -{ - TextureAtlasSamplerFactory * textureAtlasSamplerFactory = - static_cast(mShaderGenerator->getSubRenderStateFactory(TextureAtlasSampler::Type)); - TextureAtlasTablePtr textureAtlasTable(new TextureAtlasTable); - - DataStreamPtr taiFile = Ogre::ResourceGroupManager::getSingleton().openResource("TextureAtlasSampleWrap.tai"); - - textureAtlasSamplerFactory->addTexutreAtlasDefinition(taiFile, textureAtlasTable); - - //Generate the geometry that will seed the particle system - ManualObject* textureAtlasObject = mSceneMgr->createManualObject("TextureAtlasObject"); - - int sliceSize = 30.0; - int wrapSize = 5.0; - - String curMatName; - - // create original texture geometry - for( size_t i = 0 ; i < textureAtlasTable->size() ; i++ ) - { - bool changeMat = (curMatName != (*textureAtlasTable)[i].atlasTextureName); - - if (changeMat) - { - if (curMatName.empty() == false) // we don't want to end before we begin - { - textureAtlasObject->end(); - } - - curMatName = (*textureAtlasTable)[i].originalTextureName; - createMaterialForTexture(curMatName, false); - textureAtlasObject->begin(curMatName, RenderOperation::OT_TRIANGLE_LIST); - } - - // triangle 0 - textureAtlasObject->position(i * sliceSize, 0, 0); //Position - textureAtlasObject->textureCoord(0,0); //UV - - textureAtlasObject->position(i * sliceSize, 0, sliceSize); //Position - textureAtlasObject->textureCoord(0,wrapSize); //UV - - textureAtlasObject->position((i + 1) * sliceSize, 0 , sliceSize); //Position - textureAtlasObject->textureCoord(wrapSize,wrapSize); //UV - - // triangle 1 - textureAtlasObject->position(i * sliceSize, 0, 0); //Position - textureAtlasObject->textureCoord(0,0); //UV - - textureAtlasObject->position((i + 1) * sliceSize, 0, sliceSize); //Position - textureAtlasObject->textureCoord(wrapSize,wrapSize); //UV - - textureAtlasObject->position((i + 1) * sliceSize, 0, 0); //Position - textureAtlasObject->textureCoord(wrapSize, 0); //UV - - } - - // create texture atlas geometry - for( size_t i = 0 ; i < (*textureAtlasTable).size() ; i++ ) - { - bool changeMat = (curMatName != (*textureAtlasTable)[i].atlasTextureName); - - if (changeMat) - { - if (curMatName.empty() == false) // we don't want to end before we begin - { - textureAtlasObject->end(); - } - - curMatName = (*textureAtlasTable)[i].atlasTextureName; - createMaterialForTexture(curMatName, true); - textureAtlasObject->begin(curMatName, RenderOperation::OT_TRIANGLE_LIST); - } - - // triangle 0 - textureAtlasObject->position(i * sliceSize, 0, sliceSize); //Position - textureAtlasObject->textureCoord(0,0); //UV - textureAtlasObject->textureCoord((*textureAtlasTable)[i].indexInAtlas); //Texture ID - - textureAtlasObject->position(i * sliceSize, 0, sliceSize * 2); //Position - textureAtlasObject->textureCoord(0,wrapSize); //UV - textureAtlasObject->textureCoord((*textureAtlasTable)[i].indexInAtlas); //Texture ID - - textureAtlasObject->position((i + 1) * sliceSize, 0 , sliceSize * 2); //Position - textureAtlasObject->textureCoord(wrapSize,wrapSize); //UV - textureAtlasObject->textureCoord((*textureAtlasTable)[i].indexInAtlas); //Texture ID - - // triangle 1 - textureAtlasObject->position(i * sliceSize, 0, sliceSize); //Position - textureAtlasObject->textureCoord(0,0); //UV - textureAtlasObject->textureCoord((*textureAtlasTable)[i].indexInAtlas); //Texture ID - - textureAtlasObject->position((i + 1) * sliceSize, 0, sliceSize * 2); //Position - textureAtlasObject->textureCoord(wrapSize,wrapSize); //UV - textureAtlasObject->textureCoord((*textureAtlasTable)[i].indexInAtlas); //Texture ID - - textureAtlasObject->position((i + 1) * sliceSize, 0, sliceSize); //Position - textureAtlasObject->textureCoord(wrapSize, 0); //UV - textureAtlasObject->textureCoord((*textureAtlasTable)[i].indexInAtlas); //Texture ID - - } - - textureAtlasObject->end(); - - return textureAtlasObject; -} - diff --git a/Samples/ShaderSystemMultiLight/include/RTShaderSRSSegmentedLights.h b/Samples/ShaderSystemMultiLight/include/RTShaderSRSSegmentedLights.h deleted file mode 100644 index 6aa81d33b3c..00000000000 --- a/Samples/ShaderSystemMultiLight/include/RTShaderSRSSegmentedLights.h +++ /dev/null @@ -1,260 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _RTShaderSRSSegmentedLights_ -#define _RTShaderSRSSegmentedLights_ - -#include "OgreShaderPrerequisites.h" -#include "OgreShaderSubRenderState.h" -#include "OgreVector.h" -#include "OgreLight.h" -#include "OgreCommon.h" - -/** Segmented lighting sub render state -* The following is sub render state handles lighting in the scene. -* This sub render state is heavily based on PerPixelLighting -*/ -class RTShaderSRSSegmentedLights : public Ogre::RTShader::SubRenderState -{ - - // Interface. -public: - /** Class default constructor */ - RTShaderSRSSegmentedLights(); - - /** - @see SubRenderState::getType. - */ - const Ogre::String& getType() const override; - - /** - @see SubRenderState::getType. - */ - int getExecutionOrder() const override; - - /** - @see SubRenderState::updateGpuProgramsParams. - */ - void updateGpuProgramsParams(Ogre::Renderable* rend, const Ogre::Pass* pass, const Ogre::AutoParamDataSource* source, const Ogre::LightList* pLightList) override; - - /** - @see SubRenderState::copyFrom. - */ - void copyFrom(const Ogre::RTShader::SubRenderState& rhs) override; - - - /** - @see SubRenderState::preAddToRenderState. - */ - bool preAddToRenderState(const Ogre::RTShader::RenderState* renderState, Ogre::Pass* srcPass, Ogre::Pass* dstPass) override; - - - - static Ogre::String Type; - - // Protected types: -protected: - - // Per light parameters. - struct LightParams - { - Ogre::Light::LightTypes mType; // Light type. - Ogre::RTShader::UniformParameterPtr mPosition; // Light position. - Ogre::RTShader::UniformParameterPtr mDirection; // Light direction. - Ogre::RTShader::UniformParameterPtr mSpotParams; // Spot light parameters. - Ogre::RTShader::UniformParameterPtr mDiffuseColour; // Diffuse colour. - Ogre::RTShader::UniformParameterPtr mSpecularColour; // Specular colour. - - }; - - typedef std::vector LightParamsList; - typedef LightParamsList::iterator LightParamsIterator; - typedef LightParamsList::const_iterator LightParamsConstIterator; - - // Protected methods -protected: - - /** - Set the track per vertex colour type. Ambient, Diffuse, Specular and Emissive lighting components source - can be the vertex colour component. To establish such a link one should provide the matching flags to this - sub render state. - */ - void setTrackVertexColourType(Ogre::TrackVertexColourType type) { mTrackVertexColourType = type; } - - /** - Return the current track per vertex type. - */ - Ogre::TrackVertexColourType getTrackVertexColourType() const { return mTrackVertexColourType; } - - - /** - Set the light count per light type that this sub render state will generate. - @see ShaderGenerator::setLightCount. - */ - void setLightCount(int lightCount); - - /** - Set the specular component state. If set to true this sub render state will compute a specular - lighting component in addition to the diffuse component. - @param enable Pass true to enable specular component computation. - */ - void setSpecularEnable(bool enable) { mSpecularEnable = enable; } - - /** - Get the specular component state. - */ - bool getSpecularEnable() const { return mSpecularEnable; } - - - /** - @see SubRenderState::resolveParameters. - */ - bool resolveParameters(Ogre::RTShader::ProgramSet* programSet) override; - - /** Resolve global lighting parameters */ - bool resolveGlobalParameters(Ogre::RTShader::ProgramSet* programSet); - - /** Resolve per light parameters */ - bool resolvePerLightParameters(Ogre::RTShader::ProgramSet* programSet); - - /** - @see SubRenderState::resolveDependencies. - */ - bool resolveDependencies(Ogre::RTShader::ProgramSet* programSet) override; - - /** - @see SubRenderState::addFunctionInvocations. - */ - bool addFunctionInvocations(Ogre::RTShader::ProgramSet* programSet) override; - - - /** - Internal method that adds related vertex shader functions invocations. - */ - bool addVSInvocation(Ogre::RTShader::Function* vsMain, const int groupOrder); - - - /** - Internal method that adds global illumination component functions invocations. - */ - bool addPSGlobalIlluminationInvocationBegin(Ogre::RTShader::Function* psMain, const int groupOrder); - bool addPSGlobalIlluminationInvocationEnd(Ogre::RTShader::Function* psMain, const int groupOrder); - - /** - Internal method that adds per light illumination component functions invocations. - */ - bool addPSIlluminationInvocation(LightParams* curLightParams, Ogre::RTShader::Function* psMain, const int groupOrder); - - /** - Internal method that adds light illumination component calculated from the segmented texture. - */ - bool addPSSegmentedTextureLightInvocation(Ogre::RTShader::Function* psMain, const int groupOrder); - - /** - Internal method that adds the final colour assignments. - */ - bool addPSFinalAssignmentInvocation(Ogre::RTShader::Function* psMain, const int groupOrder); - - - // Attributes. -protected: - Ogre::TrackVertexColourType mTrackVertexColourType; // Track per vertex colour type. - bool mSpecularEnable; // Specular component enabled/disabled. - LightParamsList mLightParamsList; // Light list. - Ogre::RTShader::UniformParameterPtr mWorldMatrix; // World view matrix parameter. - Ogre::RTShader::UniformParameterPtr mWorldITMatrix; // World view matrix inverse transpose parameter. - Ogre::RTShader::ParameterPtr mVSInPosition; // Vertex shader input position parameter. - Ogre::RTShader::ParameterPtr mVSOutWorldPos; // Vertex shader output view position (position in camera space) parameter. - Ogre::RTShader::ParameterPtr mPSInWorldPos; // Pixel shader input view position (position in camera space) parameter. - Ogre::RTShader::ParameterPtr mVSInNormal; // Vertex shader input normal. - Ogre::RTShader::ParameterPtr mVSOutNormal; // Vertex shader output normal. - Ogre::RTShader::ParameterPtr mPSInNormal; // Pixel shader input normal. - Ogre::RTShader::ParameterPtr mPSLocalNormal; - Ogre::RTShader::ParameterPtr mPSTempDiffuseColour; // Pixel shader temporary diffuse calculation parameter. - Ogre::RTShader::ParameterPtr mPSTempSpecularColour; // Pixel shader temporary specular calculation parameter. - Ogre::RTShader::ParameterPtr mPSDiffuse; // Pixel shader input/local diffuse parameter. - Ogre::RTShader::ParameterPtr mPSSpecular; // Pixel shader input/local specular parameter. - Ogre::RTShader::ParameterPtr mPSOutDiffuse; // Pixel shader output diffuse parameter. - Ogre::RTShader::ParameterPtr mPSOutSpecular; // Pixel shader output specular parameter. - Ogre::RTShader::UniformParameterPtr mDerivedSceneColour; // Derived scene colour parameter. - Ogre::RTShader::UniformParameterPtr mLightAmbientColour; // Ambient light colour parameter. - Ogre::RTShader::UniformParameterPtr mDerivedAmbientLightColour; // Derived ambient light colour parameter. - Ogre::RTShader::UniformParameterPtr mSurfaceAmbientColour; // Surface ambient colour parameter. - Ogre::RTShader::UniformParameterPtr mSurfaceDiffuseColour; // Surface diffuse colour parameter. - Ogre::RTShader::UniformParameterPtr mSurfaceSpecularColour; // Surface specular colour parameter. - Ogre::RTShader::UniformParameterPtr mSurfaceEmissiveColour; // Surface emissive colour parameter. - Ogre::RTShader::UniformParameterPtr mSurfaceShininess; // Surface shininess parameter. - - //Segmented texture - bool mUseSegmentedLightTexture; - bool mIsDebugMode; - unsigned short mLightSamplerIndex; - Ogre::RTShader::UniformParameterPtr mPSLightTextureIndexLimit; - Ogre::RTShader::UniformParameterPtr mPSLightTextureLightBounds; - Ogre::RTShader::UniformParameterPtr mPSSegmentedLightTexture; - //Ogre::RTShader::UniformParameterPtr mPSLightAreaBounds; - - static Ogre::Light msBlankLight; // Shared blank light. - -}; - - -/** -A factory that enables creation of PerPixelLighting instances. -@remarks Sub class of SubRenderStateFactory -*/ -class RTShaderSRSSegmentedLightsFactory : public Ogre::RTShader::SubRenderStateFactory -{ -public: - - /** - @see SubRenderStateFactory::getType. - */ - const Ogre::String& getType() const override; - - /** - @see SubRenderStateFactory::createInstance. - */ - Ogre::RTShader::SubRenderState* createInstance(Ogre::ScriptCompiler* compiler, Ogre::PropertyAbstractNode* prop, Ogre::Pass* pass, Ogre::RTShader::SGScriptTranslator* translator) override; - - /** - @see SubRenderStateFactory::writeInstance. - */ - void writeInstance(Ogre::MaterialSerializer* ser, Ogre::RTShader::SubRenderState* subRenderState, Ogre::Pass* srcPass, Ogre::Pass* dstPass) override; - - -protected: - - /** - @see SubRenderStateFactory::createInstanceImpl. - */ - Ogre::RTShader::SubRenderState* createInstanceImpl() override; - - -}; - -#endif - diff --git a/Samples/ShaderSystemMultiLight/include/SegmentedDynamicLightManager.h b/Samples/ShaderSystemMultiLight/include/SegmentedDynamicLightManager.h deleted file mode 100644 index 08b47834bb0..00000000000 --- a/Samples/ShaderSystemMultiLight/include/SegmentedDynamicLightManager.h +++ /dev/null @@ -1,167 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _SegmentedLightManager_ -#define _SegmentedLightManager_ - -#include "OgreShaderPrerequisites.h" -#include "OgreSingleton.h" -#include "OgreLight.h" -#include "OgreTexture.h" -#include "OgreLight.h" -#include "OgreSceneManager.h" - -#define SDL_SEGMENT_DIVISIONS 9 -#define SDL_SEGMENT_GRID_SIZE (SDL_SEGMENT_DIVISIONS * SDL_SEGMENT_DIVISIONS) -#define SDL_LIGHT_DATA_SIZE 3 -#define SDL_TEXTURE_ROWS 32 -#define SDL_TEXTURE_DATA_ROWS 1 -#define SDL_LIGHT_PER_BLOCK (SDL_TEXTURE_ROWS - SDL_TEXTURE_DATA_ROWS) - - -using namespace Ogre; - -class SegmentedDynamicLightManager : public Singleton, - public SceneManager::Listener -{ - -public: - SegmentedDynamicLightManager(); - ~SegmentedDynamicLightManager(); - - bool setDebugMode(bool i_IsDebugMode); - //Set the system to active mode - void setSceneManager(SceneManager* i_Manager); - //Tells if the system is active - bool isActive() const { return mManager != NULL; } - //Get the name of the texture used to store the light information - const String& getSDLTextureName(); - - //Get the range of lights in the supplied texture data that need to be calculated for a given renderable - bool getLightListRange(const Renderable* i_Rend, Vector4& o_GridBounds, unsigned int& o_IndexMin, unsigned int& o_IndexMax); - - //Get the width of the texture containing the light information - unsigned int getTextureWidth() const { return mTextureWidth; } - //Get the height of the texture containing the light information - unsigned int getTextureHeight() const { return mTextureHeight; } - //Get the amount of cells the texture is divided into on either axis - unsigned int getGridDivision() const { return SDL_SEGMENT_DIVISIONS; } - //Get whether to display the lights in debug mode - bool isDebugMode() const { return mIsDebugMode; } - - void postFindVisibleObjects(SceneManager* source, - SceneManager::IlluminationRenderStage irs, Viewport* v) override; - - /// @copydoc Singleton::getSingleton() - static SegmentedDynamicLightManager& getSingleton(void); - /// @copydoc Singleton::getSingleton() - static SegmentedDynamicLightManager* getSingletonPtr(void); -private: - - class LightData - { - public: - //Constructor for LightData - LightData(); - //Sets the values of the boundaries of the light - void setBounds(const AxisAlignedBox& i_Bounds); - //Add an index to the possible range of indexes - void addIndexToRange(unsigned int i_LightIndex); - - unsigned int getIndexMin() const { return mIndexMin; } - unsigned int getIndexMax() const { return mIndexMax; } - - Real getMinX() const { return mMinX; } - Real getMaxX() const { return mMaxX; } - Real getMinZ() const { return mMinZ; } - Real getMaxZ() const { return mMaxZ; } - - private: - unsigned int mIndexMin; - unsigned int mIndexMax; - - Real mMinX; - Real mMaxX; - Real mMinZ; - Real mMaxZ; - }; - - typedef std::map MapLightData; - -private: - //Update the systems internal light lists - void updateLightList(const Camera* i_pCamera, const LightList& i_LightList); - //Initialize the texture to be used to store the light information - bool initTexture(); - //Arrange the lights in the different lists - void arrangeLightsInSegmentedLists(const Camera* i_pCamera, const LightList& i_LightList); - //Repopulate the m_ActiveLights list which keeps track of all lights being rendered in the frame - void regenerateActiveLightList(const LightList& i_LightList); - //Calculate the bounds of a single light - void calculateLightBounds(const Light* i_Light, LightData &o_LightData); - //Calculate the area which bounds area in which the lights exist - void recalculateGridSize(); - //Distribute the lights in the active light list (mActiveLights) in the grid parameter (mSegmentedLightGrid) - void distributeLightsInGrid(); - //Get the index in the grid of a given world position - unsigned int calcGridColumn(Real i_Position, Real i_BoundStart, Real i_BoundEnd); - //Returns a grid index for a given x and y index positions - unsigned int calcGridIndex(unsigned int i_X, unsigned int i_Y); - - //Load the lights information from the internal lists to the texture - void updateTextureFromSegmentedLists(const Camera* i_pCamera); - -private: - //Tells whether to run the lights in debug mode - bool mIsDebugMode; - //Pointer to a scene manager on which the lights will work - SceneManager* mManager; - - //List of active lights in the frame - MapLightData mActiveLights; - - //A Grid structures to contain the lights as they are represented in the light texture - typedef std::vector VecLights; - typedef std::vector SegmentedVecLight; - SegmentedVecLight mSegmentedLightGrid; - - //A pointer to a texture which containing information from which a shader renders the lights - TexturePtr mLightTexture; - //The height of the width information texture - unsigned int mTextureWidth; - //The height of the light information texture - unsigned int mTextureHeight; - - - //Light grid bounds - Real mGridMinX; - Real mGridMinZ; - Real mGridMaxX; - Real mGridMaxZ; -}; - -#endif - diff --git a/Samples/ShaderSystemMultiLight/include/ShaderSystemMultiLight.h b/Samples/ShaderSystemMultiLight/include/ShaderSystemMultiLight.h deleted file mode 100644 index 5b9fde8090f..00000000000 --- a/Samples/ShaderSystemMultiLight/include/ShaderSystemMultiLight.h +++ /dev/null @@ -1,352 +0,0 @@ -#ifndef __ShaderSystemMultiLight_H__ -#define __ShaderSystemMultiLight_H__ - -#include "SdkSample.h" -#include "SegmentedDynamicLightManager.h" -#include "RTShaderSRSSegmentedLights.h" -#include "OgreControllerManager.h" -#include "OgreBillboard.h" - -/* -Part of the original guidelines under which the RTSS was created was to emulate the fixed pipeline mechanism as close as possible. -Due to this fact and how it was interpreted using multiple lights in RTSS with the default implementation is problematic. Every light -requires it's own line in the shader. Every time an object receives a different amount of lights the shader for is invalidated and lights -recompiled. Amount of is also limited by the amount of const registers a shader supports. - -The following example shows a different approach to rendering lights in RTSS. A few points on this system - - Only one directional light is supported. - - Point lights and spot lights are handled through the same code. - - Light attenuation is only controlled by range. all other parameters are ignored (to produce more efficient shader programs) - - point light specular effect is not calculated (to produce more faster shader programs). If any one wants to add it feel free. - - Large amount of lights can be supported. Limited currently by the size of the texture used to send the light information to the - shader (currently set to a 9x9 grid. each grid cell can contain 32 lights). - - No need to recompile the shader when the number of lights on an object changes - - Sample requires shader model 3 or higher to run in order - - The world is divided into a grid of 9x9 cells (can be easily increased). Each cell receives it's own list of lights appropriate - only for it. This can be increased depending on your situation. - - The information of the lights in the grid is transferred onto a texture. Which is sent to the shader. - - The list of lights is iterated over in the shader through a dynamic loop. - - -Note: -This code was somewhat inspired by Kojack's "Tons of street lights" (http://www.ogre3d.org/forums/viewtopic.php?t=48412) idea. One of -the more innovative ideas I've seen of late. - -*/ - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_ShaderSystemMultiLight : public SdkSample -{ - static const uint8 cPriorityMain = 50; - static const uint8 cPriorityQuery = 51; - static const uint8 cPriorityLights = 55; - static const uint32 cInitialLightCount = 3; - - static const String DEBUG_MODE_CHECKBOX; - static const String NUM_OF_LIGHTS_SLIDER; - static const String TWIRL_LIGHTS_CHECKBOX; -public: - - Sample_ShaderSystemMultiLight() : - mTwirlLights(false), - mSRSSegLightFactory(NULL), - mPathNameGen("RTPath") - { - mInfo["Title"] = "ShaderSystem - Multi Light"; - mInfo["Description"] = "Shows a possible way to support a large varying amount of spot lights in the RTSS using a relatively simple system." - "Note in debug mode green and red lines show the light grid. Blue shows the amount of lights processed per grid position."; - mInfo["Thumbnail"] = "thumb_shadersystemmultilight.png"; - mInfo["Category"] = "Lighting"; - - } - - ~Sample_ShaderSystemMultiLight() - { - - } - - void _shutdown() override - { - delete SegmentedDynamicLightManager::getSingletonPtr(); - - RTShader::RenderState* pMainRenderState = - RTShader::ShaderGenerator::getSingleton().createOrRetrieveRenderState(MSN_SHADERGEN).first; - pMainRenderState->resetToBuiltinSubRenderStates(); - - if (mSRSSegLightFactory) - { - RTShader::ShaderGenerator::getSingleton().removeAllShaderBasedTechniques(); - RTShader::ShaderGenerator::getSingleton().removeSubRenderStateFactory(mSRSSegLightFactory); - delete mSRSSegLightFactory; - mSRSSegLightFactory = NULL; - } - - while (mLights.size()) - { - removeSpotLight(); - } - - SdkSample::_shutdown(); - } - - bool frameRenderingQueued(const FrameEvent& evt) override - { - // Move the lights along their paths - for(size_t i = 0 ; i < mLights.size() ; ++i) - { - mLights[i].animState->addTime(evt.timeSinceLastFrame); - if (mTwirlLights) - { - mLights[i].dirnode->setDirection( - Quaternion(Degree(ControllerManager::getSingleton().getElapsedTime() * 150 + 360 * i / (float)mLights.size()), Vector3::UNIT_Y) * - Vector3(0,-1,-1).normalisedCopy(), Node::TS_WORLD); - } - else - { - mLights[i].dirnode->setDirection(Vector3::NEGATIVE_UNIT_Y, Node::TS_WORLD); - } - } - - - return SdkSample::frameRenderingQueued(evt); // don't forget the parent class updates! - } - -protected: - - void setupContent() override - { - mTrayMgr->createThickSlider(TL_BOTTOM, NUM_OF_LIGHTS_SLIDER, "Num of lights", 240, 80, 0, 64, 65)->setValue(cInitialLightCount, false); - mTrayMgr->createCheckBox(TL_BOTTOM, TWIRL_LIGHTS_CHECKBOX, "Twirl Lights", 240)->setChecked(false, false); - mTrayMgr->createCheckBox(TL_BOTTOM, DEBUG_MODE_CHECKBOX, "Show Grid", 240)->setChecked(false, false); - - // Set our camera to orbit around the origin at a suitable distance - mCameraMan->setStyle(CS_ORBIT); - mCameraMan->setYawPitchDist(Degree(0), Degree(25), 600); - - mTrayMgr->showCursor(); - - // create a floor mesh resource - MeshManager::getSingleton().createPlane("floor", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - Plane(Vector3::UNIT_Y, -30), 1000, 1000, 10, 10, true, 1, 8, 8, Vector3::UNIT_Z); - - // create a floor entity, give it a material, and place it at the origin - Entity* floor = mSceneMgr->createEntity("Floor", "floor"); - floor->setMaterialName("Examples/BumpyMetal"); - mSceneMgr->getRootSceneNode()->attachObject(floor); - - // Create an ogre head and place it at the origin - Entity* head = mSceneMgr->createEntity("Head", "ogrehead.mesh"); - head->setRenderQueueGroup(cPriorityMain); - mSceneMgr->getRootSceneNode()->attachObject(head); - - setupShaderGenerator(); - - setupLights(); - } - - void cleanupContent() override - { - MeshManager::getSingleton().remove("floor", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - } - - void setupShaderGenerator() - { - new SegmentedDynamicLightManager; - - SegmentedDynamicLightManager::getSingleton().setSceneManager(mSceneMgr); - - RTShader::ShaderGenerator* mGen = RTShader::ShaderGenerator::getSingletonPtr(); - - RTShader::RenderState* pMainRenderState = - mGen->createOrRetrieveRenderState(MSN_SHADERGEN).first; - pMainRenderState->resetToBuiltinSubRenderStates(); - - // If we are using segmented lighting, no auto light update required. (prevent constant invalidation) - pMainRenderState->setLightCountAutoUpdate(false); - - mSRSSegLightFactory = new RTShaderSRSSegmentedLightsFactory; - mGen->addSubRenderStateFactory(mSRSSegLightFactory); - pMainRenderState->addTemplateSubRenderState( - mGen->createSubRenderState()); - - mGen->invalidateScheme(Ogre::MSN_SHADERGEN); - - // Make this viewport work with shader generator scheme. - mViewport->setMaterialScheme(MSN_SHADERGEN); - } - - - void setupLights() - { - mSceneMgr->setAmbientLight(ColourValue(0.1, 0.1, 0.1)); - // set the single directional light - Light* light = mSceneMgr->createLight(); - light->setType(Light::LT_DIRECTIONAL); - light->setDiffuseColour(ColourValue(0.1, 0.1, 0.1)); - light->setCastShadows(false); - - auto ln = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - ln->setDirection(Vector3(-1,-1,0).normalisedCopy()); - ln->attachObject(light); - - for(unsigned int i = 0 ; i < cInitialLightCount ; ++i) - { - addSpotLight(); - } - } - - void addSpotLight() - { - LightState state; - - // Create a light node - state.node = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(50, 30, 0)); - - String animName = mPathNameGen.generate(); - // Create a 14 second animation with spline interpolation - - const int animPoints = 5; - const int animTimeBetweenPoints = 4; - state.anim = mSceneMgr->createAnimation(animName, animPoints * animTimeBetweenPoints); - state.anim->setInterpolationMode(Animation::IM_SPLINE); - - state.track = state.anim->createNodeTrack(1, state.node); // Create a node track for our animation - - // Enter keyframes for our track to define a path for the light to follow - Vector3 firstFramePos; - for(int i = 0 ; i <= animPoints ; ++i) - { - Vector3 framePos(rand01() * 900 - 500, 10 + rand01() * 100, rand01() * 900 - 500); - if (i == 0) - { - firstFramePos = framePos; - } - if (i == animPoints) - { - framePos = firstFramePos; - } - state.track->createNodeKeyFrame(i * animTimeBetweenPoints)->setTranslate(framePos); - } - - - ColourValue lightColor(rand01(), rand01(), rand01()); - float complement = 1 - std::max(std::max(lightColor.r, lightColor.g), lightColor.b); - lightColor.r += complement; - lightColor.g += complement; - lightColor.b += complement; - - // Create an animation state from the animation and enable it - state.animState = mSceneMgr->createAnimationState(animName); - state.animState->setEnabled(true); - - // Attach a light with the same colour to the light node - state.light = mSceneMgr->createLight(); - state.light->setCastShadows(false); - state.light->setType(mLights.size() % 10 ? Light::LT_SPOTLIGHT : Light::LT_POINT); - state.light->setAttenuation(200,0,0,0); - state.light->setDiffuseColour(lightColor); - state.dirnode = state.node->createChildSceneNode(); - state.dirnode->setDirection(Vector3::NEGATIVE_UNIT_Y, Node::TS_WORLD); - state.dirnode->attachObject(state.light); - - // Attach a flare with the same colour to the light node - state.bbs = mSceneMgr->createBillboardSet(1); - Billboard* bb = state.bbs->createBillboard(Vector3::ZERO, lightColor); - bb->setColour(lightColor); - state.bbs->setMaterialName("Examples/Flare"); - state.bbs->setRenderQueueGroup(cPriorityLights); - state.node->attachObject(state.bbs); - - mLights.push_back(state); - } - - float rand01() - { - return (abs(rand()) % 1000) / 1000.0f; - } - - void setDebugModeState(bool state) - { - bool needInvalidate = SegmentedDynamicLightManager::getSingleton().setDebugMode(state); - if (needInvalidate) - { - RTShader::ShaderGenerator::getSingleton().invalidateScheme(MSN_SHADERGEN); - } - } - - //-------------------------------------------------------------------------- - void sliderMoved(Slider* slider) override - { - if (slider->getName() == NUM_OF_LIGHTS_SLIDER) - { - size_t numOfLights = (size_t)slider->getValue(); - - while (mLights.size() < numOfLights) - { - addSpotLight(); - } - - while (numOfLights < mLights.size()) - { - removeSpotLight(); - } - } - } - - void removeSpotLight() - { - if (!mLights.empty()) - { - LightState& state = mLights[mLights.size() - 1]; - - // Delete the nodes - mSceneMgr->destroyBillboardSet(state.bbs); - mSceneMgr->destroyLight(state.light); - mSceneMgr->destroyAnimationState(state.anim->getName()); - mSceneMgr->destroyAnimation(state.anim->getName()); - mSceneMgr->destroySceneNode(state.node); - - - mLights.resize(mLights.size() - 1); - } - } - - - void checkBoxToggled(CheckBox* box) override - { - const String& cbName = box->getName(); - - if (cbName == DEBUG_MODE_CHECKBOX) - { - setDebugModeState(box->isChecked()); - } - if (cbName == TWIRL_LIGHTS_CHECKBOX) - { - mTwirlLights = box->isChecked(); - } - } -private: - - struct LightState - { - SceneNode* node; - SceneNode* dirnode; - Animation* anim; - NodeAnimationTrack* track; - AnimationState* animState; - Light* light; - BillboardSet* bbs; - }; - - typedef std::vector VecLights; - VecLights mLights; - bool mTwirlLights; - - RTShaderSRSSegmentedLightsFactory* mSRSSegLightFactory; - - NameGenerator mPathNameGen; -}; - -#endif diff --git a/Samples/ShaderSystemMultiLight/src/RTShaderSRSSegmentedLights.cpp b/Samples/ShaderSystemMultiLight/src/RTShaderSRSSegmentedLights.cpp deleted file mode 100644 index bd8af4fe35e..00000000000 --- a/Samples/ShaderSystemMultiLight/src/RTShaderSRSSegmentedLights.cpp +++ /dev/null @@ -1,812 +0,0 @@ -#include "RTShaderSRSSegmentedLights.h" -#include "OgreShaderFFPRenderState.h" -#include "OgreShaderProgram.h" -#include "OgreShaderParameter.h" -#include "OgreShaderProgramSet.h" -#include "OgreGpuProgram.h" -#include "OgrePass.h" -#include "OgreShaderGenerator.h" -#include "OgreSceneManager.h" -#include "OgreViewport.h" -#include "OgreMaterialSerializer.h" -#include "SegmentedDynamicLightManager.h" - -#define SL_LIB_PERPIXELLIGHTING "SegmentedPerPixelLighting" -#define SL_FUNC_TRANSFORMNORMAL "SL_TransformNormal" -#define SL_FUNC_TRANSFORMPOSITION "SL_TransformPosition" -#define SL_FUNC_LIGHT_DIRECTIONAL_DIFFUSE "SL_Light_Directional_Diffuse" -#define SL_FUNC_LIGHT_DIRECTIONAL_DIFFUSESPECULAR "SL_Light_Directional_DiffuseSpecular" -#define SL_FUNC_LIGHT_AMBIENT_DIFFUSE "SL_Light_Ambient_Diffuse" -#define SL_FUNC_LIGHT_SEGMENT_TEXTURE_AMBIENT_DIFFUSE "SL_Light_Segment_Texture_Ambient_Diffuse" -#define SL_FUNC_LIGHT_SEGMENT_DEBUG "SL_Light_Segment_Debug" - -using namespace Ogre; -using namespace Ogre::RTShader; - -String RTShaderSRSSegmentedLights::Type = "Segmented_PerPixelLighting"; -Light RTShaderSRSSegmentedLights::msBlankLight; - - -//----------------------------------------------------------------------- -RTShaderSRSSegmentedLights::RTShaderSRSSegmentedLights() -{ - mTrackVertexColourType = TVC_NONE; - mSpecularEnable = false; - mUseSegmentedLightTexture = false; - mLightSamplerIndex = 0; - - msBlankLight.setDiffuseColour(ColourValue::Black); - msBlankLight.setSpecularColour(ColourValue::Black); - msBlankLight.setAttenuation(0,1,0,0); -} - -//----------------------------------------------------------------------- -const String& RTShaderSRSSegmentedLights::getType() const -{ - return Type; -} - - -//----------------------------------------------------------------------- -int RTShaderSRSSegmentedLights::getExecutionOrder() const -{ - return FFP_LIGHTING; -} - -//----------------------------------------------------------------------- -void RTShaderSRSSegmentedLights::updateGpuProgramsParams(Renderable* rend, const Pass* pass, const AutoParamDataSource* source, - const LightList* pLightList) -{ - if ((mLightParamsList.empty()) && (!mUseSegmentedLightTexture)) - return; - - Light::LightTypes curLightType = Light::LT_DIRECTIONAL; - unsigned int curSearchLightIndex = 0; - - //update spot strength - float spotIntensity = 1; - - // Update per light parameters. - for (auto & curParams : mLightParamsList) - { - if (curLightType != curParams.mType) - { - curLightType = curParams.mType; - curSearchLightIndex = 0; - } - - Light* srcLight = NULL; - Vector4 vParameter; - ColourValue colour; - - // Search a matching light from the current sorted lights of the given renderable. - for (unsigned int j = curSearchLightIndex; j < pLightList->size(); ++j) - { - if (pLightList->at(j)->getType() == curLightType) - { - srcLight = pLightList->at(j); - curSearchLightIndex = j + 1; - break; - } - } - - // No matching light found -> use a blank dummy light for parameter update. - if (srcLight == NULL) - { - srcLight = &msBlankLight; - } - - - switch (curParams.mType) - { - case Light::LT_DIRECTIONAL: - - // Update light direction. - vParameter = srcLight->getAs4DVector(true); - curParams.mDirection->setGpuParameter(vParameter.ptr(),3,1); - break; - - case Light::LT_POINT: - - // Update light position. - vParameter = srcLight->getAs4DVector(true); - curParams.mPosition->setGpuParameter(vParameter.ptr(),3,1); - - // Update light attenuation parameters. - curParams.mSpotParams->setGpuParameter(Ogre::Vector3(1 / srcLight->getAttenuationRange(),0,0)); - break; - case Light::LT_RECTLIGHT: - case Light::LT_SPOTLIGHT: - { - Ogre::Vector3 vec3; - - // Update light position. - vParameter = srcLight->getAs4DVector(true); - curParams.mPosition->setGpuParameter(vParameter.ptr(),3,1); - - - // Update light direction. - vec3 = source->getInverseTransposeWorldMatrix().linear() * srcLight->getDerivedDirection(); - vec3.normalise(); - - vParameter.x = -vec3.x; - vParameter.y = -vec3.y; - vParameter.z = -vec3.z; - vParameter.w = 0.0; - curParams.mDirection->setGpuParameter(vParameter.ptr(),3,1); - - // Update spotlight parameters. - Real phi = Math::Cos(srcLight->getSpotlightOuterAngle().valueRadians() * 0.5f); - Real theta = Math::Cos(srcLight->getSpotlightInnerAngle().valueRadians() * 0.5f); - - vec3.x = 1 / srcLight->getAttenuationRange(); - vec3.y = phi; - vec3.z = 1 / (theta - phi); - - curParams.mSpotParams->setGpuParameter(vec3); - } - break; - } - - float lightIntensity = 1; - if (curParams.mType == Light::LT_SPOTLIGHT) - { - lightIntensity = spotIntensity; - } - - // Update diffuse colour. - colour = srcLight->getDiffuseColour() * lightIntensity; - if ((mTrackVertexColourType & TVC_DIFFUSE) == 0) - { - colour = colour * pass->getDiffuse(); - } - curParams.mDiffuseColour->setGpuParameter(colour.ptr(),3,1); - - // Update specular colour if need to. - if ((mSpecularEnable) && (curParams.mType == Light::LT_DIRECTIONAL)) - { - // Update diffuse colour. - colour = srcLight->getSpecularColour() * lightIntensity; - if ((mTrackVertexColourType & TVC_SPECULAR) == 0) - { - colour = colour * pass->getSpecular(); - } - curParams.mSpecularColour->setGpuParameter(colour.ptr(),3,1); - } - } - - if (mUseSegmentedLightTexture) - { - unsigned int indexStart = 0, indexEnd = 0; - Ogre::Vector4 lightBounds; - SegmentedDynamicLightManager::getSingleton().getLightListRange(rend, lightBounds, indexStart, indexEnd); - mPSLightTextureIndexLimit->setGpuParameter(Ogre::Vector2((Ogre::Real)indexStart, (Ogre::Real)indexEnd)); - mPSLightTextureLightBounds->setGpuParameter(lightBounds); - - Ogre::TextureUnitState* pLightTexture = pass->getTextureUnitState(mLightSamplerIndex); - const Ogre::String& textureName = SegmentedDynamicLightManager::getSingleton().getSDLTextureName(); - if (textureName != pLightTexture->getTextureName()) - { - pLightTexture->setTextureName(textureName, Ogre::TEX_TYPE_2D); - } - } -} - -//----------------------------------------------------------------------- -bool RTShaderSRSSegmentedLights::resolveParameters(ProgramSet* programSet) -{ - if (false == resolveGlobalParameters(programSet)) - return false; - - if (false == resolvePerLightParameters(programSet)) - return false; - - return true; -} - -//----------------------------------------------------------------------- -bool RTShaderSRSSegmentedLights::resolveGlobalParameters(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Function* psMain = psProgram->getEntryPointFunction(); - - - // Resolve world IT matrix. - mWorldITMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_INVERSE_TRANSPOSE_WORLD_MATRIX); - - // Get surface ambient colour if need to. - if ((mTrackVertexColourType & TVC_AMBIENT) == 0) - { - mDerivedAmbientLightColour = psProgram->resolveParameter(GpuProgramParameters::ACT_DERIVED_AMBIENT_LIGHT_COLOUR); - } - else - { - mLightAmbientColour = psProgram->resolveParameter(GpuProgramParameters::ACT_AMBIENT_LIGHT_COLOUR); - mSurfaceAmbientColour = psProgram->resolveParameter(GpuProgramParameters::ACT_SURFACE_AMBIENT_COLOUR); - } - - // Get surface diffuse colour if need to. - if ((mTrackVertexColourType & TVC_DIFFUSE) == 0) - { - mSurfaceDiffuseColour = psProgram->resolveParameter(GpuProgramParameters::ACT_SURFACE_DIFFUSE_COLOUR); - } - - // Get surface specular colour if need to. - if ((mTrackVertexColourType & TVC_SPECULAR) == 0) - { - mSurfaceSpecularColour = psProgram->resolveParameter(GpuProgramParameters::ACT_SURFACE_SPECULAR_COLOUR); - } - - // Get surface emissive colour if need to. - if ((mTrackVertexColourType & TVC_EMISSIVE) == 0) - { - mSurfaceEmissiveColour = psProgram->resolveParameter(GpuProgramParameters::ACT_SURFACE_EMISSIVE_COLOUR); - } - - // Get derived scene colour. - mDerivedSceneColour = psProgram->resolveParameter(GpuProgramParameters::ACT_DERIVED_SCENE_COLOUR); - // Get surface shininess. - mSurfaceShininess = psProgram->resolveParameter(GpuProgramParameters::ACT_SURFACE_SHININESS); - - - //Check if another SRS already defined a normal in world space to be used - mPSLocalNormal = psMain->getLocalParameter(Parameter::SPC_NORMAL_WORLD_SPACE); - if (mPSLocalNormal.get() == NULL) - { - //create parameters to fetch the normal from the vertex shader - - // Resolve input vertex shader normal. - mVSInNormal = vsMain->resolveInputParameter(Parameter::SPC_NORMAL_OBJECT_SPACE); - // Resolve output vertex shader normal. - mVSOutNormal = vsMain->resolveOutputParameter(Parameter::SPC_NORMAL_WORLD_SPACE); - // Resolve input pixel shader normal. - mPSInNormal = psMain->resolveInputParameter(mVSOutNormal); - mPSLocalNormal = psMain->resolveLocalParameter(Parameter::SPC_NORMAL_WORLD_SPACE); - } - - mPSDiffuse = psMain->getInputParameter(Parameter::SPC_COLOR_DIFFUSE); - if (mPSDiffuse.get() == NULL) - { - mPSDiffuse = psMain->getLocalParameter(Parameter::SPC_COLOR_DIFFUSE); - if (mPSDiffuse.get() == NULL) - return false; - } - - mPSOutDiffuse = psMain->resolveOutputParameter(Parameter::SPS_COLOR, 0, Parameter::SPC_COLOR_DIFFUSE, GCT_FLOAT4); - mPSTempDiffuseColour = psMain->resolveLocalParameter(GCT_FLOAT4, "lPerPixelDiffuse"); - mVSOutWorldPos = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_WORLD_SPACE); - mPSInWorldPos = psMain->resolveInputParameter(mVSOutWorldPos); - mWorldMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLD_MATRIX); - mVSInPosition = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE); - - - if (mSpecularEnable) - { - mPSSpecular = psMain->getInputParameter(Parameter::SPC_COLOR_SPECULAR); - if (mPSSpecular.get() == NULL) - { - mPSSpecular = psMain->getLocalParameter(Parameter::SPC_COLOR_SPECULAR); - if (mPSSpecular.get() == NULL) - return false; - } - - mPSTempSpecularColour = psMain->resolveLocalParameter(GCT_FLOAT4, "lPerPixelSpecular"); - mVSInPosition = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE); - mWorldMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLD_MATRIX); - } - - - if (mUseSegmentedLightTexture) - { - mPSLightTextureIndexLimit = psProgram->resolveParameter(GCT_FLOAT2, -1, (uint16)GPV_PER_OBJECT, "LightTextureIndexLimits"); - mPSLightTextureLightBounds = psProgram->resolveParameter(GCT_FLOAT4, -1, (uint16)GPV_PER_OBJECT, "LightTextureBounds"); - mPSSegmentedLightTexture = psProgram->resolveParameter(Ogre::GCT_SAMPLER2D, mLightSamplerIndex, (Ogre::uint16)Ogre::GPV_GLOBAL, "segmentedLightTexture"); - } - - return true; -} - -//----------------------------------------------------------------------- -bool RTShaderSRSSegmentedLights::resolvePerLightParameters(ProgramSet* programSet) -{ - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - - // Resolve per light parameters. - for (auto & i : mLightParamsList) - { - switch (i.mType) - { - case Light::LT_RECTLIGHT: - case Light::LT_DIRECTIONAL: - i.mDirection = psProgram->resolveParameter(GCT_FLOAT3, -1, (uint16)GPV_LIGHTS, "light_direction_space"); - break; - - case Light::LT_POINT: - case Light::LT_SPOTLIGHT: - i.mPosition = psProgram->resolveParameter(GCT_FLOAT3, -1, (uint16)GPV_LIGHTS, "light_position_space"); - i.mDirection = psProgram->resolveParameter(GCT_FLOAT3, -1, (uint16)GPV_LIGHTS, "light_direction_space"); - i.mSpotParams = psProgram->resolveParameter(GCT_FLOAT3, -1, (uint16)GPV_LIGHTS, "spotlight_params"); - break; - } - - // Resolve diffuse colour. - if ((mTrackVertexColourType & TVC_DIFFUSE) == 0) - { - i.mDiffuseColour = psProgram->resolveParameter(GCT_FLOAT3, -1, (uint16)GPV_LIGHTS | (uint16)GPV_GLOBAL, "derived_light_diffuse"); - } - else - { - i.mDiffuseColour = psProgram->resolveParameter(GCT_FLOAT3, -1, (uint16)GPV_LIGHTS, "light_diffuse"); - } - - if ((mSpecularEnable) && (i.mType == Light::LT_DIRECTIONAL)) - { - // Resolve specular colour. - if ((mTrackVertexColourType & TVC_SPECULAR) == 0) - { - i.mSpecularColour = psProgram->resolveParameter(GCT_FLOAT3, -1, (uint16)GPV_LIGHTS | (uint16)GPV_GLOBAL, "derived_light_specular"); - } - else - { - i.mSpecularColour = psProgram->resolveParameter(GCT_FLOAT3, -1, (uint16)GPV_LIGHTS, "light_specular"); - } - } - - } - - return true; -} - -//----------------------------------------------------------------------- -bool RTShaderSRSSegmentedLights::resolveDependencies(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - - vsProgram->addDependency(SL_LIB_PERPIXELLIGHTING); - - psProgram->addDependency(SL_LIB_PERPIXELLIGHTING); - - return true; -} - -//----------------------------------------------------------------------- -bool RTShaderSRSSegmentedLights::addFunctionInvocations(ProgramSet* programSet) -{ - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* psMain = psProgram->getEntryPointFunction(); - - // Add the global illumination functions. - if (false == addVSInvocation(vsMain, FFP_VS_LIGHTING)) - return false; - - // Add the global illumination functions. - if (false == addPSGlobalIlluminationInvocationBegin(psMain, FFP_PS_COLOUR_BEGIN + 1)) - return false; - - - // Add per light functions. - for (auto & i : mLightParamsList) - { - if (false == addPSIlluminationInvocation(&i, psMain, FFP_PS_COLOUR_BEGIN + 1)) - return false; - } - - if (mUseSegmentedLightTexture) - { - addPSSegmentedTextureLightInvocation(psMain, FFP_PS_COLOUR_BEGIN + 1); - } - - - // Add the global illumination functions. - if (false == addPSGlobalIlluminationInvocationEnd(psMain, FFP_PS_COLOUR_BEGIN + 1)) - return false; - - - // Assign back temporary variables to the ps diffuse and specular components. - if (false == addPSFinalAssignmentInvocation(psMain, FFP_PS_COLOUR_BEGIN + 1)) - return false; - - - return true; -} - -//----------------------------------------------------------------------- -bool RTShaderSRSSegmentedLights::addVSInvocation(Function* vsMain, const int groupOrder) -{ - FunctionInvocation* curFuncInvocation = NULL; - - if (mVSInNormal.get() != NULL) - { - // Transform normal in world space. - curFuncInvocation = OGRE_NEW FunctionInvocation(SL_FUNC_TRANSFORMNORMAL, groupOrder); - curFuncInvocation->pushOperand(mWorldITMatrix, Operand::OPS_IN); - curFuncInvocation->pushOperand(mVSInNormal, Operand::OPS_IN); - curFuncInvocation->pushOperand(mVSOutNormal, Operand::OPS_OUT); - vsMain->addAtomInstance(curFuncInvocation); - } - - // Transform world space position if need to. - if (mVSOutWorldPos.get() != NULL) - { - curFuncInvocation = OGRE_NEW FunctionInvocation(SL_FUNC_TRANSFORMPOSITION, groupOrder); - curFuncInvocation->pushOperand(mWorldMatrix, Operand::OPS_IN); - curFuncInvocation->pushOperand(mVSInPosition, Operand::OPS_IN); - curFuncInvocation->pushOperand(mVSOutWorldPos, Operand::OPS_OUT); - vsMain->addAtomInstance(curFuncInvocation); - } - - - return true; -} - - -//----------------------------------------------------------------------- -bool RTShaderSRSSegmentedLights::addPSGlobalIlluminationInvocationBegin(Function* psMain, const int groupOrder) -{ - FunctionAtom* curFuncInvocation = NULL; - - if (mPSInNormal.get()) - { - curFuncInvocation = OGRE_NEW AssignmentAtom(FFP_PS_PRE_PROCESS + 1); - curFuncInvocation->pushOperand(mPSInNormal, Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSLocalNormal, Operand::OPS_OUT); - psMain->addAtomInstance(curFuncInvocation); - } - - //alpha channel is controlled by the diffuse value - if (mTrackVertexColourType & TVC_DIFFUSE) - { - curFuncInvocation = OGRE_NEW AssignmentAtom(groupOrder); - curFuncInvocation->pushOperand(mPSDiffuse, Operand::OPS_IN, Operand::OPM_W); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_OUT, Operand::OPM_W); - psMain->addAtomInstance(curFuncInvocation); - } - else - { - curFuncInvocation = OGRE_NEW AssignmentAtom(groupOrder); - curFuncInvocation->pushOperand(mDerivedSceneColour, Operand::OPS_IN, Operand::OPM_W); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_OUT, Operand::OPM_W); - psMain->addAtomInstance(curFuncInvocation); - } - - ParameterPtr pZeroParam = ParameterFactory::createConstParam(Ogre::Vector3::ZERO); - - curFuncInvocation = OGRE_NEW AssignmentAtom(groupOrder); - curFuncInvocation->pushOperand(pZeroParam, Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_OUT, Operand::OPM_XYZ); - psMain->addAtomInstance(curFuncInvocation); - - if (mSpecularEnable) - { - curFuncInvocation = OGRE_NEW AssignmentAtom(groupOrder); - curFuncInvocation->pushOperand(pZeroParam, Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSTempSpecularColour, Operand::OPS_OUT, Operand::OPM_XYZ); - psMain->addAtomInstance(curFuncInvocation); - } - - return true; -} - - - -//----------------------------------------------------------------------- -bool RTShaderSRSSegmentedLights::addPSGlobalIlluminationInvocationEnd(Function* psMain, const int groupOrder) -{ - FunctionAtom* curFuncInvocation = NULL; - - // Merge diffuse colour with vertex colour if need to. - if (mTrackVertexColourType & TVC_DIFFUSE) - { - curFuncInvocation = OGRE_NEW BinaryOpAtom('*', groupOrder); - curFuncInvocation->pushOperand(mPSDiffuse, Operand::OPS_IN, Operand::OPM_XYZ); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_IN, Operand::OPM_XYZ); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_OUT, Operand::OPM_XYZ); - psMain->addAtomInstance(curFuncInvocation); - } - - // Merge specular colour with vertex colour if need to. - if ((mSpecularEnable == true) && (mTrackVertexColourType & TVC_SPECULAR)) - { - curFuncInvocation = OGRE_NEW BinaryOpAtom('*', groupOrder); - curFuncInvocation->pushOperand(mPSDiffuse, Operand::OPS_IN, Operand::OPM_XYZ); - curFuncInvocation->pushOperand(mPSTempSpecularColour, Operand::OPS_IN, Operand::OPM_XYZ); - curFuncInvocation->pushOperand(mPSTempSpecularColour, Operand::OPS_OUT, Operand::OPM_XYZ); - psMain->addAtomInstance(curFuncInvocation); - } - - - if ((mTrackVertexColourType & TVC_AMBIENT) == 0 && - (mTrackVertexColourType & TVC_EMISSIVE) == 0) - { - curFuncInvocation = OGRE_NEW BinaryOpAtom('+', groupOrder); - curFuncInvocation->pushOperand(mDerivedSceneColour, Operand::OPS_IN, (Operand::OPM_XYZ)); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_IN, (Operand::OPM_XYZ)); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_OUT, Operand::OPM_XYZ); - psMain->addAtomInstance(curFuncInvocation); - } - else - { - if (mTrackVertexColourType & TVC_AMBIENT) - { - curFuncInvocation = OGRE_NEW BinaryOpAtom('*', groupOrder); - curFuncInvocation->pushOperand(mPSDiffuse, Operand::OPS_IN, Operand::OPM_XYZ); - curFuncInvocation->pushOperand(mLightAmbientColour, Operand::OPS_IN, Operand::OPM_XYZ); - curFuncInvocation->pushOperand(mLightAmbientColour, Operand::OPS_OUT, Operand::OPM_XYZ); - psMain->addAtomInstance(curFuncInvocation); - - curFuncInvocation = OGRE_NEW BinaryOpAtom('+', groupOrder); - curFuncInvocation->pushOperand(mLightAmbientColour, Operand::OPS_IN, Operand::OPM_XYZ); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_IN, Operand::OPM_XYZ); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_OUT, Operand::OPM_XYZ); - psMain->addAtomInstance(curFuncInvocation); - } - else - { - curFuncInvocation = OGRE_NEW BinaryOpAtom('+', groupOrder); - curFuncInvocation->pushOperand(mDerivedAmbientLightColour, Operand::OPS_IN, Operand::OPM_XYZ); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_IN, Operand::OPM_XYZ); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_OUT, Operand::OPM_XYZ); - psMain->addAtomInstance(curFuncInvocation); - } - - if (mTrackVertexColourType & TVC_EMISSIVE) - { - curFuncInvocation = OGRE_NEW BinaryOpAtom('+', groupOrder); - curFuncInvocation->pushOperand(mPSDiffuse, Operand::OPS_IN, Operand::OPM_XYZ); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_IN, Operand::OPM_XYZ); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_OUT, Operand::OPM_XYZ); - psMain->addAtomInstance(curFuncInvocation); - } - else - { - curFuncInvocation = OGRE_NEW BinaryOpAtom('+', groupOrder); - curFuncInvocation->pushOperand(mSurfaceEmissiveColour, Operand::OPS_IN, Operand::OPM_XYZ); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_IN, Operand::OPM_XYZ); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_OUT, Operand::OPM_XYZ); - psMain->addAtomInstance(curFuncInvocation); - } - } - - if (mSpecularEnable) - { - curFuncInvocation = OGRE_NEW BinaryOpAtom('+', groupOrder); - curFuncInvocation->pushOperand(mPSSpecular, Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSTempSpecularColour, Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSTempSpecularColour, Operand::OPS_OUT); - psMain->addAtomInstance(curFuncInvocation); - } - - return true; -} - -//----------------------------------------------------------------------- -bool RTShaderSRSSegmentedLights::addPSIlluminationInvocation(LightParams* curLightParams, Function* psMain, const int groupOrder) -{ - FunctionInvocation* curFuncInvocation = NULL; - - - switch (curLightParams->mType) - { - case Light::LT_RECTLIGHT: - case Light::LT_DIRECTIONAL: - if (mSpecularEnable) - { - curFuncInvocation = OGRE_NEW FunctionInvocation(SL_FUNC_LIGHT_DIRECTIONAL_DIFFUSESPECULAR, groupOrder); - curFuncInvocation->pushOperand(mPSLocalNormal, Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSInWorldPos, Operand::OPS_IN); - curFuncInvocation->pushOperand(curLightParams->mDirection, Operand::OPS_IN); - curFuncInvocation->pushOperand(curLightParams->mDiffuseColour, Operand::OPS_IN); - curFuncInvocation->pushOperand(curLightParams->mSpecularColour, Operand::OPS_IN); - curFuncInvocation->pushOperand(mSurfaceShininess, Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_IN, Operand::OPM_XYZ); - curFuncInvocation->pushOperand(mPSTempSpecularColour, Operand::OPS_IN, Operand::OPM_XYZ); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_OUT, Operand::OPM_XYZ); - curFuncInvocation->pushOperand(mPSTempSpecularColour, Operand::OPS_OUT, Operand::OPM_XYZ); - psMain->addAtomInstance(curFuncInvocation); - } - - else - { - curFuncInvocation = OGRE_NEW FunctionInvocation(SL_FUNC_LIGHT_DIRECTIONAL_DIFFUSE, groupOrder); - curFuncInvocation->pushOperand(mPSLocalNormal, Operand::OPS_IN); - curFuncInvocation->pushOperand(curLightParams->mDirection, Operand::OPS_IN); - curFuncInvocation->pushOperand(curLightParams->mDiffuseColour, Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_IN, Operand::OPM_XYZ); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_OUT, Operand::OPM_XYZ); - psMain->addAtomInstance(curFuncInvocation); - } - break; - - case Light::LT_POINT: - case Light::LT_SPOTLIGHT: - { - curFuncInvocation = OGRE_NEW FunctionInvocation(SL_FUNC_LIGHT_AMBIENT_DIFFUSE, groupOrder); - curFuncInvocation->pushOperand(mPSLocalNormal, Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSInWorldPos, Operand::OPS_IN); - curFuncInvocation->pushOperand(curLightParams->mPosition, Operand::OPS_IN); - curFuncInvocation->pushOperand(curLightParams->mDirection, Operand::OPS_IN); - curFuncInvocation->pushOperand(curLightParams->mSpotParams, Operand::OPS_IN); - curFuncInvocation->pushOperand(curLightParams->mDiffuseColour, Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_INOUT, Operand::OPM_XYZ); - psMain->addAtomInstance(curFuncInvocation); - } - break; - } - - return true; -} - -bool RTShaderSRSSegmentedLights::addPSSegmentedTextureLightInvocation(Function* psMain, const int groupOrder) -{ - float invWidth = 1.0f / (float)SegmentedDynamicLightManager::getSingleton().getTextureWidth(); - float invHeight = 1.0f / (float)SegmentedDynamicLightManager::getSingleton().getTextureHeight(); - ParameterPtr paramInvWidth = ParameterFactory::createConstParam(invWidth); - ParameterPtr paramInvHeight = ParameterFactory::createConstParam(invHeight); - - FunctionInvocation* curFuncInvocation = NULL; - curFuncInvocation = OGRE_NEW FunctionInvocation(SL_FUNC_LIGHT_SEGMENT_TEXTURE_AMBIENT_DIFFUSE, groupOrder); - curFuncInvocation->pushOperand(mPSLocalNormal, Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSInWorldPos, Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSSegmentedLightTexture, Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSLightTextureIndexLimit, Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSLightTextureLightBounds, Operand::OPS_IN); - curFuncInvocation->pushOperand(paramInvWidth, Operand::OPS_IN); - curFuncInvocation->pushOperand(paramInvHeight, Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_INOUT, Operand::OPM_XYZ); - psMain->addAtomInstance(curFuncInvocation); - - if (SegmentedDynamicLightManager::getSingleton().isDebugMode()) - { - ParameterPtr psOutColor = psMain->resolveOutputParameter(Parameter::SPS_COLOR, -1, Parameter::SPC_COLOR_DIFFUSE, GCT_FLOAT4); - - FunctionInvocation* curDebugFuncInvocation = NULL; - curDebugFuncInvocation = OGRE_NEW FunctionInvocation(SL_FUNC_LIGHT_SEGMENT_DEBUG, FFP_PS_COLOUR_END + 1); - curDebugFuncInvocation->pushOperand(mPSLocalNormal, Operand::OPS_IN); - curDebugFuncInvocation->pushOperand(mPSInWorldPos, Operand::OPS_IN); - curDebugFuncInvocation->pushOperand(mPSSegmentedLightTexture, Operand::OPS_IN); - curDebugFuncInvocation->pushOperand(mPSLightTextureIndexLimit, Operand::OPS_IN); - curDebugFuncInvocation->pushOperand(mPSLightTextureLightBounds, Operand::OPS_IN); - curDebugFuncInvocation->pushOperand(paramInvWidth, Operand::OPS_IN); - curDebugFuncInvocation->pushOperand(paramInvHeight, Operand::OPS_IN); - - curDebugFuncInvocation->pushOperand(psOutColor, Operand::OPS_INOUT, Operand::OPM_XYZ); - psMain->addAtomInstance(curDebugFuncInvocation); - } - - return true; -} - - -//----------------------------------------------------------------------- -bool RTShaderSRSSegmentedLights::addPSFinalAssignmentInvocation( Function* psMain, const int groupOrder) -{ - FunctionAtom* curFuncInvocation; - - curFuncInvocation = OGRE_NEW AssignmentAtom(FFP_PS_COLOUR_BEGIN + 1); - curFuncInvocation->pushOperand(mPSTempDiffuseColour, Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSDiffuse, Operand::OPS_OUT); - psMain->addAtomInstance(curFuncInvocation); - - curFuncInvocation = OGRE_NEW AssignmentAtom(FFP_PS_COLOUR_BEGIN + 1); - curFuncInvocation->pushOperand(mPSDiffuse, Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSOutDiffuse, Operand::OPS_OUT); - psMain->addAtomInstance(curFuncInvocation); - - if (mSpecularEnable) - { - curFuncInvocation = OGRE_NEW AssignmentAtom(FFP_PS_COLOUR_BEGIN + 1); - curFuncInvocation->pushOperand(mPSTempSpecularColour, Operand::OPS_IN); - curFuncInvocation->pushOperand(mPSSpecular, Operand::OPS_OUT); - psMain->addAtomInstance(curFuncInvocation); - } - - return true; -} - - -//----------------------------------------------------------------------- -void RTShaderSRSSegmentedLights::copyFrom(const SubRenderState& rhs) -{ - const RTShaderSRSSegmentedLights& rhsLighting = static_cast(rhs); - - mUseSegmentedLightTexture = rhsLighting.mUseSegmentedLightTexture; - mLightParamsList = rhsLighting.mLightParamsList; -} - -//----------------------------------------------------------------------- -bool RTShaderSRSSegmentedLights::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) -{ - if (srcPass->getLightingEnabled() == false) - return false; - - mUseSegmentedLightTexture = SegmentedDynamicLightManager::getSingleton().isActive(); - setTrackVertexColourType(srcPass->getVertexColourTracking()); - - if (srcPass->getShininess() > 0.0 && - srcPass->getSpecular() != ColourValue::Black) - { - setSpecularEnable(true); - } - else - { - setSpecularEnable(false); - } - - setLightCount(renderState->getLightCount()); - - if (mUseSegmentedLightTexture) - { - const_cast(renderState)->setLightCountAutoUpdate(false); - - Ogre::TextureUnitState* pLightTexture = dstPass->createTextureUnitState(); - pLightTexture->setTextureName(SegmentedDynamicLightManager::getSingleton().getSDLTextureName(), Ogre::TEX_TYPE_2D); - pLightTexture->setTextureFiltering(Ogre::TFO_NONE); - mLightSamplerIndex = dstPass->getNumTextureUnitStates() - 1; - } - - - return true; -} - -//----------------------------------------------------------------------- -void RTShaderSRSSegmentedLights::setLightCount(int lightCount) -{ - mLightParamsList.clear(); - //Set always to have one single directional lights - LightParams curParams; - curParams.mType = Light::LT_DIRECTIONAL; - mLightParamsList.push_back(curParams); - - curParams.mType = Light::LT_POINT; - for (int i=0; i < lightCount; ++i) - { - if ((!mUseSegmentedLightTexture) || (curParams.mType == Light::LT_DIRECTIONAL)) - { - mLightParamsList.push_back(curParams); - } - } -} - -//----------------------------------------------------------------------- -const String& RTShaderSRSSegmentedLightsFactory::getType() const -{ - return RTShaderSRSSegmentedLights::Type; -} - -//----------------------------------------------------------------------- -SubRenderState* RTShaderSRSSegmentedLightsFactory::createInstance(ScriptCompiler* compiler, - PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) -{ - if (prop->name == "lighting_stage") - { - if(prop->values.size() == 1) - { - if (prop->values.front()->getString() == "per_pixel") - { - return createOrRetrieveInstance(translator); - } - } - } - - return NULL; -} - -//----------------------------------------------------------------------- -void RTShaderSRSSegmentedLightsFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, - Pass* srcPass, Pass* dstPass) -{ - ser->writeAttribute(4, "lighting_stage"); - ser->writeValue("per_pixel"); -} - -//----------------------------------------------------------------------- -SubRenderState* RTShaderSRSSegmentedLightsFactory::createInstanceImpl() -{ - return OGRE_NEW RTShaderSRSSegmentedLights; -} - diff --git a/Samples/ShaderSystemMultiLight/src/SegmentedDynamicLightManager.cpp b/Samples/ShaderSystemMultiLight/src/SegmentedDynamicLightManager.cpp deleted file mode 100644 index 247f9f4d5df..00000000000 --- a/Samples/ShaderSystemMultiLight/src/SegmentedDynamicLightManager.cpp +++ /dev/null @@ -1,433 +0,0 @@ -#include "SegmentedDynamicLightManager.h" -#include "OgreTextureManager.h" -#include "OgreCamera.h" -#include "OgreSceneManager.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreRenderable.h" -#include "OgreBitwise.h" -#include "OgrePixelFormat.h" -#include "OgreRoot.h" -#include "OgreViewport.h" - -#define SDL_LIGHT_DATA_SIZE 3 // 12 floats divided by 4 slots (rgba) - -namespace Ogre -{ - template<> SegmentedDynamicLightManager* Singleton::msSingleton = 0; -} - -SegmentedDynamicLightManager* SegmentedDynamicLightManager::getSingletonPtr(void) -{ - return msSingleton; -} -SegmentedDynamicLightManager& SegmentedDynamicLightManager::getSingleton(void) -{ - assert( msSingleton ); return ( *msSingleton ); -} - -using namespace Ogre; - -const String c_SDLTextureName = "Simigon/SDLTexture"; - -SegmentedDynamicLightManager::SegmentedDynamicLightManager() : - mIsDebugMode(false), - mManager(NULL), - mSegmentedLightGrid(SDL_SEGMENT_GRID_SIZE), - mLightTexture(), - mTextureWidth(0), - mTextureHeight(SDL_TEXTURE_ROWS) -{ - //calculate needed texture width - mTextureWidth = SDL_LIGHT_DATA_SIZE * SDL_SEGMENT_GRID_SIZE; - //round up to the nearest power of 2 - unsigned int pow2Val = 1; - for( ; mTextureWidth > pow2Val; pow2Val = pow2Val << 1); - mTextureWidth = pow2Val; -} - -//------------------------------------------------------------------------------ -SegmentedDynamicLightManager::~SegmentedDynamicLightManager() -{ - setSceneManager(NULL); - if (mLightTexture.get()) - { - TextureManager::getSingleton().remove(mLightTexture->getHandle()); - } -} - -//------------------------------------------------------------------------------ -bool SegmentedDynamicLightManager::setDebugMode(bool i_IsDebugMode) -{ - bool requireInvalidate = false; - if (mIsDebugMode != i_IsDebugMode) - { - mIsDebugMode = i_IsDebugMode; - requireInvalidate = true; - } - return requireInvalidate; -} - -//------------------------------------------------------------------------------ -void SegmentedDynamicLightManager::postFindVisibleObjects(SceneManager* source, - SceneManager::IlluminationRenderStage irs, Viewport* v) -{ - if (irs == SceneManager::IRS_NONE) - { - updateLightList(v->getCamera(), source->_getLightsAffectingFrustum()); - } -} - -//------------------------------------------------------------------------------ -void SegmentedDynamicLightManager::setSceneManager(SceneManager* i_Manager) -{ - if (mManager != i_Manager) - { - if (mManager) mManager->removeListener(this); - mManager = i_Manager; - if (mManager) - { - mManager->addListener(this); - initTexture(); - } - } -} - -//------------------------------------------------------------------------------ -void SegmentedDynamicLightManager::updateLightList(const Camera* i_pCamera, const LightList& i_LightList) -{ - if (isActive()) - { - arrangeLightsInSegmentedLists(i_pCamera, i_LightList); - updateTextureFromSegmentedLists(i_pCamera); - } -} - -//------------------------------------------------------------------------------ -bool SegmentedDynamicLightManager::initTexture() -{ - if (mLightTexture.get() == NULL) - { - const String& sdlTextureName = getSDLTextureName(); - // create the render texture - mLightTexture = TextureManager::getSingleton().createManual(sdlTextureName, - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,TEX_TYPE_2D, - mTextureWidth,mTextureHeight,0,PF_FLOAT16_RGBA,TU_STATIC_WRITE_ONLY); - } - return mLightTexture.get() != NULL; -} - -//------------------------------------------------------------------------------ -const String& SegmentedDynamicLightManager::getSDLTextureName() -{ - return c_SDLTextureName; -} - -//------------------------------------------------------------------------------ -void SegmentedDynamicLightManager::arrangeLightsInSegmentedLists(const Camera* i_pCamera, const LightList& i_LightList) -{ - //Clear the previous buffers - for(int i = 0; i < SDL_SEGMENT_GRID_SIZE; ++i) - { - mSegmentedLightGrid[i].clear(); - } - mActiveLights.clear(); - - regenerateActiveLightList(i_LightList); - recalculateGridSize(); - distributeLightsInGrid(); -} - -//------------------------------------------------------------------------------ -void SegmentedDynamicLightManager::regenerateActiveLightList(const LightList& i_LightList) -{ - //add the buffers to the segmented lists - LightList::const_iterator itLight = i_LightList.begin(), - itLightEnd = i_LightList.end(); - for(;itLight != itLightEnd ; ++itLight) - { - const Light* pLight = (*itLight); - Light::LightTypes type = pLight->getType(); - if (((type == Light::LT_SPOTLIGHT) || (type == Light::LT_POINT)) && - (pLight->getAttenuationRange() > 0)) - { - - MapLightData::iterator it = mActiveLights.emplace(pLight,LightData()).first; - LightData& lightData = it->second; - - calculateLightBounds(pLight, lightData); - } - } -} - -//------------------------------------------------------------------------------ -void SegmentedDynamicLightManager::calculateLightBounds(const Light* i_Light, LightData& o_LightData) -{ - Real lightRange = i_Light->getAttenuationRange(); - const Vector3& lightPosition = i_Light->getDerivedPosition(true); - - AxisAlignedBox boundBox(lightPosition - lightRange, lightPosition + lightRange); - - if (i_Light->getType() == Light::LT_SPOTLIGHT) - { - static const Radian c_RadianPI(Math::PI); - static const Radian c_RadianZero(0); - - Radian halfOuterAngle = i_Light->getSpotlightOuterAngle() * 0.5; - Real boxOffset = Math::Sin(halfOuterAngle) * lightRange; - const Vector3& lightDirection = i_Light->getDerivedDirection(); - - Radian dirUpAngle(fabs(Math::ASin(lightDirection.y).valueRadians())); - Radian dirUpMaxAngle = std::max(dirUpAngle - halfOuterAngle,c_RadianZero); - Radian dirUpMinAngle = std::min(dirUpAngle + halfOuterAngle, c_RadianPI); - Real dirDistanceMax = Math::Cos(dirUpMaxAngle) * lightRange; - Real dirDistanceMin = Math::Cos(dirUpMinAngle) * lightRange; - - Vector3 flatDirection(lightDirection.x, 0, lightDirection.z); - Real flatDirLen = flatDirection.length(); - if (flatDirLen != 0) flatDirection /= flatDirLen; - else flatDirection = Vector3(1,0,0); - - Vector3 flatDirectionPerp(flatDirection.z, 0, -flatDirection.x); - flatDirectionPerp *= boxOffset; - - Vector3 flatPositionMax = lightPosition + dirDistanceMax * flatDirection; - Vector3 flatPositionMin = lightPosition + dirDistanceMin * flatDirection; - - AxisAlignedBox spotBox; - spotBox.merge(flatPositionMax + flatDirectionPerp); - spotBox.merge(flatPositionMax - flatDirectionPerp); - spotBox.merge(flatPositionMin + flatDirectionPerp); - spotBox.merge(flatPositionMin - flatDirectionPerp); - spotBox.merge(lightPosition); - - boundBox.getMaximum().makeFloor(spotBox.getMaximum()); - boundBox.getMinimum().makeCeil(spotBox.getMinimum()); - } - - o_LightData.setBounds(boundBox); -} - -//------------------------------------------------------------------------------ -void SegmentedDynamicLightManager::recalculateGridSize() -{ - mGridMinX = std::numeric_limits::max(); - mGridMinZ = std::numeric_limits::max(); - mGridMaxX = -std::numeric_limits::max(); - mGridMaxZ = -std::numeric_limits::max(); - - MapLightData::const_iterator it = mActiveLights.begin(), - itEnd = mActiveLights.end(); - for(;it != itEnd ; ++it) - { - const LightData& lightData = it->second; - mGridMinX = std::min(mGridMinX,lightData.getMinX()); - mGridMaxX = std::max(mGridMaxX,lightData.getMaxX()); - mGridMinZ = std::min(mGridMinZ,lightData.getMinZ()); - mGridMaxZ = std::max(mGridMaxZ,lightData.getMaxZ()); - } -} - -//------------------------------------------------------------------------------ -void SegmentedDynamicLightManager::distributeLightsInGrid() -{ - MapLightData::iterator it = mActiveLights.begin(), - itEnd = mActiveLights.end(); - for(;it != itEnd ; ++it) - { - LightData& lightData = it->second; - unsigned int indexXStart = calcGridColumn(lightData.getMinX(), mGridMinX, mGridMaxX); - unsigned int indexXEnd = calcGridColumn(lightData.getMaxX(), mGridMinX, mGridMaxX); - unsigned int indexZStart = calcGridColumn(lightData.getMinZ(), mGridMinZ, mGridMaxZ); - unsigned int indexZEnd = calcGridColumn(lightData.getMaxZ(), mGridMinZ, mGridMaxZ); - for(unsigned int i = indexXStart ; i <= indexXEnd ; ++i) - { - for(unsigned int j = indexZStart ; j <= indexZEnd ; ++j) - { - VecLights& block = mSegmentedLightGrid[calcGridIndex(i,j)]; - unsigned int lightIndex = (unsigned int)block.size(); - if (lightIndex < SDL_LIGHT_PER_BLOCK) - { - block.push_back(it->first); - lightData.addIndexToRange(lightIndex); - } - } - } - } -} - -//------------------------------------------------------------------------------ -unsigned int SegmentedDynamicLightManager::calcGridColumn(Real i_Position, - Real i_BoundStart, Real i_BoundEnd) -{ - int index = (unsigned int) - (((i_Position - i_BoundStart) / (i_BoundEnd - i_BoundStart)) * SDL_SEGMENT_DIVISIONS); - return (unsigned int)Math::Clamp(index, 0 ,SDL_SEGMENT_DIVISIONS - 1); -} - -unsigned int SegmentedDynamicLightManager::calcGridIndex(unsigned int i_X, unsigned int i_Y) -{ - return i_X + i_Y * SDL_SEGMENT_DIVISIONS; -} - - -//------------------------------------------------------------------------------ -void SegmentedDynamicLightManager::updateTextureFromSegmentedLists(const Camera* i_pCamera) -{ - float spotIntensity = 1; - - HardwarePixelBufferSharedPtr pBuf = mLightTexture->getBuffer(); - void* pStartPos = pBuf->lock(HardwareBuffer::HBL_DISCARD); - uint16* pData = (uint16*)pStartPos; - - size_t remainBufWidth = mTextureWidth; - for(size_t j = 0; j < SDL_SEGMENT_GRID_SIZE; ++j) - { - //assign first row with number of indexes in the block - float maxRow = (float)(mSegmentedLightGrid[j].size() - 1 + SDL_TEXTURE_DATA_ROWS); - PixelUtil::packColour(maxRow,0.0f,0.0f,0.0f,PF_FLOAT16_RGBA, pData); - pData += 4 * SDL_LIGHT_DATA_SIZE; - remainBufWidth -= SDL_LIGHT_DATA_SIZE; - } - - //advance the remaining space of the row - pData += 4 * remainBufWidth; - - for(size_t i = 0 ; i < SDL_LIGHT_PER_BLOCK ; ++i) - { - remainBufWidth = mTextureWidth; - for(size_t j = 0; j < SDL_SEGMENT_GRID_SIZE; ++j) - { - if (i < mSegmentedLightGrid[j].size()) - { - const Light* pLight = mSegmentedLightGrid[j][i]; - - const Vector3& position = pLight->getDerivedPosition(true); - Vector3 direction = -pLight->getDerivedDirection(); - direction.normalise(); - - // Update spotlight parameters. - Vector3 spotParam; - float inverseRange = 1.0f / (float)pLight->getAttenuationRange(); - float spotAngle = -1; - float spotInvAngleRange = std::numeric_limits::max(); - if (pLight->getType() == Light::LT_SPOTLIGHT) - { - Real phi = Math::Cos(pLight->getSpotlightOuterAngle().valueRadians() * 0.5f); - Real theta = Math::Cos(pLight->getSpotlightInnerAngle().valueRadians() * 0.5f); - spotAngle = (float)phi; - spotInvAngleRange = 1.0f / (float)(theta - phi); - } - - PixelUtil::packColour( - (float)position.x, - (float)position.y, - (float)position.z, - inverseRange, - PF_FLOAT16_RGBA, pData); - pData += 4; - - PixelUtil::packColour( - (float)direction.x, - (float)direction.y, - (float)direction.z, - spotAngle, - PF_FLOAT16_RGBA, pData); - pData += 4; - - PixelUtil::packColour( - pLight->getDiffuseColour().r * spotIntensity, - pLight->getDiffuseColour().g * spotIntensity, - pLight->getDiffuseColour().b * spotIntensity, - spotInvAngleRange, - PF_FLOAT16_RGBA, pData); - pData += 4; - - } - else - { - //assign position zero with zero width - PixelUtil::packColour(0.0f,0.0f,0.0f,std::numeric_limits::max(), - PF_FLOAT16_RGBA, pData); - pData += 4; - for(int d = 0 ; d < (SDL_LIGHT_DATA_SIZE - 1) ; ++d) - { - PixelUtil::packColour(0.0f,0.0f,0.0f,0.0f,PF_FLOAT16_RGBA, pData); - pData += 4; - } - } - remainBufWidth -= 3; - } - - //advance the remaining space of the row - pData += 4 * remainBufWidth; - } - - //Check for memory overrun - if (pBuf->getSizeInBytes() != (size_t)((const char*)(void*)pData - (const char*)pStartPos)) - { - throw "memory overrun"; - } - - pBuf->unlock(); -} - -//------------------------------------------------------------------------------ -bool SegmentedDynamicLightManager::getLightListRange(const Renderable* i_Rend, - Vector4& o_GridBounds, unsigned int& o_IndexMin, unsigned int& o_IndexMax) -{ - o_IndexMin = 100000; - o_IndexMax = 0; - - const LightList& lights = i_Rend->getLights(); - LightList::const_iterator it = lights.begin(), itEnd = lights.end(); - for(; it != itEnd ; ++it) - { - MapLightData::const_iterator itActive = mActiveLights.find(*it); - if (itActive != mActiveLights.end()) - { - o_IndexMin = (unsigned int)std::min(o_IndexMin, itActive->second.getIndexMin()); - o_IndexMax = (unsigned int)std::max(o_IndexMax, itActive->second.getIndexMax()); - } - } - - o_GridBounds.x = mGridMinX; - o_GridBounds.y = mGridMinZ; - o_GridBounds.z = SDL_SEGMENT_DIVISIONS / (mGridMaxX - mGridMinX); - o_GridBounds.w = SDL_SEGMENT_DIVISIONS / (mGridMaxZ - mGridMinZ); - o_IndexMin += SDL_TEXTURE_DATA_ROWS; - o_IndexMax += SDL_TEXTURE_DATA_ROWS; - return o_IndexMin <= o_IndexMax; -} - -////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// -////// SegmentedDynamicLightManager::LightData -////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// - -//------------------------------------------------------------------------------ -SegmentedDynamicLightManager::LightData::LightData() -{ - mIndexMin = 100000; - mIndexMax = 0; - mMinX = std::numeric_limits::max(); - mMaxX = -std::numeric_limits::max(); - mMinZ = std::numeric_limits::max(); - mMaxZ = -std::numeric_limits::max(); -} - -//------------------------------------------------------------------------------ -void SegmentedDynamicLightManager::LightData::setBounds(const AxisAlignedBox& i_Bounds) -{ - mMinX = i_Bounds.getMinimum().x; - mMaxX = i_Bounds.getMaximum().x; - mMinZ = i_Bounds.getMinimum().z; - mMaxZ = i_Bounds.getMaximum().z; -} - -//------------------------------------------------------------------------------ -void SegmentedDynamicLightManager::LightData::addIndexToRange(unsigned int i_LightIndex) -{ - mIndexMin = (unsigned int)std::min(mIndexMin, i_LightIndex); - mIndexMax = (unsigned int)std::max(mIndexMax, i_LightIndex); -} diff --git a/Samples/ShaderSystemMultiLight/src/ShaderSystemMultiLight.cpp b/Samples/ShaderSystemMultiLight/src/ShaderSystemMultiLight.cpp deleted file mode 100644 index 813ab7d9b96..00000000000 --- a/Samples/ShaderSystemMultiLight/src/ShaderSystemMultiLight.cpp +++ /dev/null @@ -1,9 +0,0 @@ -#include "SamplePlugin.h" -#include "ShaderSystemMultiLight.h" - -using namespace Ogre; -using namespace OgreBites; - -const String Sample_ShaderSystemMultiLight::DEBUG_MODE_CHECKBOX = "DebugMode"; -const String Sample_ShaderSystemMultiLight::NUM_OF_LIGHTS_SLIDER = "NumOfLights"; -const String Sample_ShaderSystemMultiLight::TWIRL_LIGHTS_CHECKBOX = "TwirlLights"; diff --git a/Samples/ShaderSystemTexturedFog/include/RTShaderSRSTexturedFog.h b/Samples/ShaderSystemTexturedFog/include/RTShaderSRSTexturedFog.h deleted file mode 100644 index e62b7a6c539..00000000000 --- a/Samples/ShaderSystemTexturedFog/include/RTShaderSRSTexturedFog.h +++ /dev/null @@ -1,180 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef _ShaderSRSTexturedFog_ -#define _ShaderSRSTexturedFog_ - -#include "OgreShaderPrerequisites.h" -#include "OgreShaderSubRenderState.h" -#include "OgreVector.h" - -using namespace Ogre; -using namespace RTShader; - -class RTShaderSRSTexturedFogFactory; -/** Textured Fog sub render state implementation. -This class implements a sub render state which is viewed as fog like effect. However, unlike a regular for -that as objects get further they become a single color, in this implementation they take the texture of a background image. - -Derives from SubRenderState class. -*/ -class RTShaderSRSTexturedFog : public SubRenderState -{ -public: -// Interface. -public: - - /** Class default constructor */ - RTShaderSRSTexturedFog(RTShaderSRSTexturedFogFactory* factory = NULL); - - /** - @see SubRenderState::getType. - */ - const String& getType() const override; - - /** - @see SubRenderState::getType. - */ - int getExecutionOrder() const override; - - /** - @see SubRenderState::updateGpuProgramsParams. - */ - void updateGpuProgramsParams(Renderable* rend, const Pass* pass, const AutoParamDataSource* source, const LightList* pLightList) override; - - /** - @see SubRenderState::copyFrom. - */ - void copyFrom(const SubRenderState& rhs) override; - - /** - @see SubRenderState::preAddToRenderState. - */ - bool preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) override; - - /** - Set the fog properties this fog sub render state should emulate. - @param fogMode The fog mode to emulate (FOG_NONE, FOG_EXP, FOG_EXP2, FOG_LINEAR). - @param fogStart Start distance of fog, used for linear mode only. - @param fogEnd End distance of fog, used for linear mode only. - @param fogDensity Fog density used in exponential modes only. - */ - void setFogProperties(FogMode fogMode, float fogStart, float fogEnd, float fogDensity); - - static String Type; - -// Protected methods -protected: - - /** - @see SubRenderState::resolveParameters. - */ - bool resolveParameters(ProgramSet* programSet) override; - - /** - @see SubRenderState::resolveDependencies. - */ - bool resolveDependencies(ProgramSet* programSet) override; - - /** - @see SubRenderState::addFunctionInvocations. - */ - bool addFunctionInvocations(ProgramSet* programSet) override; - -// Attributes. -protected: - /// The factory which created the texture fog instance - RTShaderSRSTexturedFogFactory* mFactory; - /// Fog formula. - FogMode mFogMode; - /// Fog parameters (density, start, end, 1/end-start). - Vector4 mFogParamsValue; - /// True if the fog parameters should be taken from the pass. - bool mPassOverrideParams; - /// The index of the background texture unit state in the pass - unsigned int mBackgroundSamplerIndex; - - // World matrix parameter. - UniformParameterPtr mWorldMatrix; - // camera position parameter. - UniformParameterPtr mCameraPos; - // Fog parameters program parameter. - UniformParameterPtr mFogParams; - // Vertex shader input position parameter. - ParameterPtr mVSInPos; - // Fog colour parameter. - ParameterPtr mFogColour; - // Vertex shader output fog colour parameter. - ParameterPtr mVSOutFogFactor; - // Pixel shader input fog factor. - ParameterPtr mPSInFogFactor; - // Vertex shader output depth. - ParameterPtr mVSOutDepth; - // Pixel shader input depth. - ParameterPtr mPSInDepth; - // Vertex shader world position relative to camera. - ParameterPtr mVSOutPosView; - // Pixel shader world position relative to camera. - ParameterPtr mPSInPosView; - // Pixel shader output diffuse colour. - ParameterPtr mPSOutDiffuse; - //Background color texture parameter - ParameterPtr mBackgroundTextureSampler; - -}; - - -/** -A factory that enables creation of RTShaderSRSTexturedFog instances. -@remarks Sub class of SubRenderStateFactory -*/ -class RTShaderSRSTexturedFogFactory : public SubRenderStateFactory -{ -public: - - /** - @see SubRenderStateFactory::getType. - */ - const String& getType() const override; - - /** Set the name of the texture to use as a background for the fog */ - const String& getBackgroundTextureName() const { return mBackgroundTextureName; } - /** Return the name of the texture used as a background for the fog */ - void setBackgroundTextureName(const String& name) { mBackgroundTextureName = name; } - -protected: - - /** - @see SubRenderStateFactory::createInstanceImpl. - */ - SubRenderState* createInstanceImpl() override; - -private: - String mBackgroundTextureName; -}; - -#endif - diff --git a/Samples/ShaderSystemTexturedFog/include/ShaderSystemTexturedFog.h b/Samples/ShaderSystemTexturedFog/include/ShaderSystemTexturedFog.h deleted file mode 100644 index 43d5fbf9548..00000000000 --- a/Samples/ShaderSystemTexturedFog/include/ShaderSystemTexturedFog.h +++ /dev/null @@ -1,224 +0,0 @@ -#ifndef __ShaderSystemTexturedFog_H__ -#define __ShaderSystemTexturedFog_H__ - -#include "SdkSample.h" -#include "RTShaderSRSTexturedFog.h" -#include "OgreControllerManager.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_ShaderSystemTexturedFog : public SdkSample -{ - static const uint8 cPriorityMain = 50; - static const String FOG_DISTANCE_SLIDER; - static const String ACTIVATE_FOG_BUTTON; - static const String FOG_BACKGROUND_SLIDER; - static const String ACTIVATE_SKY_BUTTON; -public: - - Sample_ShaderSystemTexturedFog() : - mSRSTextureFogFactory(NULL), - mEntityNameGen("Head") - { - mInfo["Title"] = "Shader System - Textured Fog"; - mInfo["Description"] = "Shows a simple implementation of a RTSS sub-render state implementing a fog based on texture effect."; - mInfo["Thumbnail"] = "thumb_texturedfog.png"; - mInfo["Category"] = "Lighting"; - } - - ~Sample_ShaderSystemTexturedFog() - { - - } - - void _shutdown() override - { - RTShader::RenderState* pMainRenderState = - RTShader::ShaderGenerator::getSingleton().createOrRetrieveRenderState(MSN_SHADERGEN).first; - pMainRenderState->resetToBuiltinSubRenderStates(); - - if (mSRSTextureFogFactory) - { - RTShader::ShaderGenerator::getSingleton().removeAllShaderBasedTechniques(); - RTShader::ShaderGenerator::getSingleton().removeSubRenderStateFactory(mSRSTextureFogFactory); - delete mSRSTextureFogFactory; - mSRSTextureFogFactory = NULL; - } - - SdkSample::_shutdown(); - } - - bool frameRenderingQueued(const FrameEvent& evt) override - { - return SdkSample::frameRenderingQueued(evt); // don't forget the parent class updates! - } - -protected: - - void setupContent() override - { - mTrayMgr->createCheckBox(TL_BOTTOM, ACTIVATE_FOG_BUTTON, "Fog Active")->setChecked(true,false); - mTrayMgr->createCheckBox(TL_BOTTOM, ACTIVATE_SKY_BUTTON, "Sky Box Active")->setChecked(true,false); - mTrayMgr->createThickSlider(TL_BOTTOM, FOG_DISTANCE_SLIDER, "Fog Distance", 240, 80, 20, 2000, 100)->setValue(1000, false); - mTrayMgr->createThickSlider(TL_BOTTOM, FOG_BACKGROUND_SLIDER, "Background", 240, 80, 0, 3, 4)->setValue(0, false); - - setupShaderGenerator(); - - mSceneMgr->setFog(FOG_LINEAR, ColourValue::White, 0, 500, 1000); - - mCameraNode->setPosition(0, -20, 470); - - mTrayMgr->showCursor(); - - // create a floor mesh resource - MeshManager::getSingleton().createPlane("floor", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - Plane(Vector3::UNIT_Y, -30), 1000, 1000, 10, 10, true, 1, 8, 8, Vector3::UNIT_Z); - - // create a floor entity, give it a material, and place it at the origin - Entity* floor = mSceneMgr->createEntity("Floor", "floor"); - floor->setMaterialName("Examples/BumpyMetal"); - mSceneMgr->getRootSceneNode()->attachObject(floor); - - addHead(Vector3(100,0,-400)); - addHead(Vector3(100,0,-200)); - addHead(Vector3(100,0,0)); - addHead(Vector3(100,0,200)); - - addHead(Vector3(-100,0,-400)); - addHead(Vector3(-100,0,-200)); - addHead(Vector3(-100,0,0)); - addHead(Vector3(-100,0,200)); - - //We will set the sky box far away so it will render with the color of the background - mSceneMgr->setSkyBox(true,"BaseWhiteNoLighting",2000); - } - - void addHead(const Vector3& pos) - { - - // Create an ogre head and place it at the origin - Entity* head = mSceneMgr->createEntity(mEntityNameGen.generate(), "ogrehead.mesh"); - head->setRenderQueueGroup(cPriorityMain); - mSceneMgr->getRootSceneNode()->createChildSceneNode(pos) - ->attachObject(head); - } - - - void setupShaderGenerator() - { - RTShader::ShaderGenerator* mGen = RTShader::ShaderGenerator::getSingletonPtr(); - - RTShader::RenderState* pMainRenderState = - mGen->createOrRetrieveRenderState(MSN_SHADERGEN).first; - pMainRenderState->resetToBuiltinSubRenderStates(); - - mSRSTextureFogFactory = new RTShaderSRSTexturedFogFactory; - mGen->addSubRenderStateFactory(mSRSTextureFogFactory); - pMainRenderState->addTemplateSubRenderState(mGen->createSubRenderState()); - - mSRSTextureFogFactory->setBackgroundTextureName("early_morning.jpg"); - - - - mGen->invalidateScheme(Ogre::MSN_SHADERGEN); - - // Make this viewport work with shader generator scheme. - mViewport->setMaterialScheme(MSN_SHADERGEN); - } - - - - - //-------------------------------------------------------------------------- - void sliderMoved(Slider* slider) override - { - if (slider->getName() == FOG_DISTANCE_SLIDER) - { - Real fogDist = slider->getValue(); - mSceneMgr->setFog(mSceneMgr->getFogMode(), ColourValue::White, 0, fogDist * 0.5f, fogDist); - } - if (slider->getName() == FOG_BACKGROUND_SLIDER) - { - String textureName; - size_t back = (size_t)(slider->getValue() + 0.5); - switch (back) - { - case 0: textureName = "early_morning.jpg"; break; - case 1: textureName = "cloudy_noon.jpg"; break; - case 2: textureName = "stormy.jpg"; break; - default: textureName = "evening.jpg"; break; - } - mSRSTextureFogFactory->setBackgroundTextureName(textureName); - RTShader::ShaderGenerator* gen = RTShader::ShaderGenerator::getSingletonPtr(); - gen->invalidateScheme(Ogre::MSN_SHADERGEN); - } - } - - void checkBoxToggled(CheckBox* box) override - { - const String& cbName = box->getName(); - if (cbName == ACTIVATE_FOG_BUTTON) - { - //With our shader the 3 middle parameters don't really make a difference. Only the first and last do. - FogMode mode = mSceneMgr->getFogMode() == FOG_NONE ? FOG_LINEAR : FOG_NONE; - mSceneMgr->setFog(mode, ColourValue::White, 0, mSceneMgr->getFogStart(), mSceneMgr->getFogEnd()); - } - if (cbName == ACTIVATE_SKY_BUTTON) - { - mSceneMgr->setSkyBox(!mSceneMgr->isSkyBoxEnabled(),"BaseWhiteNoLighting",2000); - - } - } - - bool mousePressed(const MouseButtonEvent& evt) override - { - if (mTrayMgr->mousePressed(evt)) - return true; - - if (evt.button == BUTTON_LEFT) - // Hide the cursor if user left-clicks in the scene. - mTrayMgr->hideCursor(); - - return true; - } - - - bool mouseReleased(const MouseButtonEvent& evt) override - { - if (mTrayMgr->mouseReleased(evt)) - return true; - - if (evt.button == BUTTON_LEFT) - // Unhide the cursor if user lets go of LMB. - mTrayMgr->showCursor(); - - return true; - } - - - bool mouseMoved(const MouseMotionEvent& evt) override - { - if(mTrayMgr->mouseMoved(evt)) - return true; - - // Only rotate the camera if cursor is hidden. - if (!mTrayMgr->isCursorVisible()) - mCameraMan->mouseMoved(evt); - - return true; - } - - void cleanupContent() override - { - MeshManager::getSingleton().remove("floor", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - } - -private: - RTShaderSRSTexturedFogFactory* mSRSTextureFogFactory; - - NameGenerator mEntityNameGen; - -}; - -#endif diff --git a/Samples/ShaderSystemTexturedFog/src/RTShaderSRSTexturedFog.cpp b/Samples/ShaderSystemTexturedFog/src/RTShaderSRSTexturedFog.cpp deleted file mode 100644 index 5de7c805e0b..00000000000 --- a/Samples/ShaderSystemTexturedFog/src/RTShaderSRSTexturedFog.cpp +++ /dev/null @@ -1,281 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "RTShaderSRSTexturedFog.h" -#include "OgreShaderFFPRenderState.h" -#include "OgreShaderProgram.h" -#include "OgreShaderParameter.h" -#include "OgreShaderProgramSet.h" -#include "OgreGpuProgram.h" -#include "OgrePass.h" -#include "OgreShaderGenerator.h" -#include "OgreTextureManager.h" - - -using namespace Ogre; -using namespace RTShader; -/************************************************************************/ -/* */ -/************************************************************************/ -String RTShaderSRSTexturedFog::Type = "TexturedFog"; - -//----------------------------------------------------------------------- -RTShaderSRSTexturedFog::RTShaderSRSTexturedFog(RTShaderSRSTexturedFogFactory* factory) -{ - mFactory = factory; - mFogMode = FOG_NONE; - mPassOverrideParams = false; -} - -//----------------------------------------------------------------------- -const String& RTShaderSRSTexturedFog::getType() const -{ - return Type; -} - - -//----------------------------------------------------------------------- -int RTShaderSRSTexturedFog::getExecutionOrder() const -{ - return FFP_FOG; -} -//----------------------------------------------------------------------- -void RTShaderSRSTexturedFog::updateGpuProgramsParams(Renderable* rend, const Pass* pass, const AutoParamDataSource* source, - const LightList* pLightList) -{ - if (mFogMode == FOG_NONE) - return; - - FogMode fogMode; - Real newFogStart, newFogEnd, newFogDensity; - - //Check if this is an overlay element if so disable fog - if ((rend->getUseIdentityView() == true) && (rend->getUseIdentityProjection() == true)) - { - fogMode = FOG_NONE; - newFogStart = 100000000; - newFogEnd = 200000000; - newFogDensity = 0; - } - else - { - if (mPassOverrideParams) - { - fogMode = pass->getFogMode(); - newFogStart = pass->getFogStart(); - newFogEnd = pass->getFogEnd(); - newFogDensity = pass->getFogDensity(); - } - else - { - SceneManager* sceneMgr = ShaderGenerator::getSingleton().getActiveSceneManager(); - - fogMode = sceneMgr->getFogMode(); - newFogStart = sceneMgr->getFogStart(); - newFogEnd = sceneMgr->getFogEnd(); - newFogDensity = sceneMgr->getFogDensity(); - } - } - - // Set fog properties. - setFogProperties(fogMode, newFogStart, newFogEnd, newFogDensity); - - mFogParams->setGpuParameter(mFogParamsValue); -} - -//----------------------------------------------------------------------- -bool RTShaderSRSTexturedFog::resolveParameters(ProgramSet* programSet) -{ - if (mFogMode == FOG_NONE) - return true; - - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Function* psMain = psProgram->getEntryPointFunction(); - - - // Resolve world view matrix. - mWorldMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLD_MATRIX); - // Resolve world view matrix. - mCameraPos = vsProgram->resolveParameter(GpuProgramParameters::ACT_CAMERA_POSITION); - // Resolve vertex shader input position. - mVSInPos = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE); - - // Resolve fog colour. - mFogColour = psMain->resolveLocalParameter(GCT_FLOAT4, "FogColor"); - - // Resolve pixel shader output diffuse color. - mPSOutDiffuse = psMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE); - - // Resolve fog params. - mFogParams = psProgram->resolveParameter(GCT_FLOAT4, "gFogParams"); - - // Resolve vertex shader output depth. - mVSOutPosView = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_VIEW_SPACE); - // Resolve pixel shader input depth. - mPSInPosView = psMain->resolveInputParameter(mVSOutPosView); - // Resolve vertex shader output depth. - mVSOutDepth = vsMain->resolveOutputParameter(Parameter::SPC_DEPTH_VIEW_SPACE); - // Resolve pixel shader input depth. - mPSInDepth = psMain->resolveInputParameter(mVSOutDepth); - // Resolve texture sampler parameter. - mBackgroundTextureSampler = psProgram->resolveParameter(GCT_SAMPLERCUBE, "FogBackgroundSampler", mBackgroundSamplerIndex); - - return true; -} - -//----------------------------------------------------------------------- -bool RTShaderSRSTexturedFog::resolveDependencies(ProgramSet* programSet) -{ - if (mFogMode == FOG_NONE) - return true; - - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - - vsProgram->addDependency("FFPLib_Fog"); - - psProgram->addDependency("FFPLib_Fog"); - - return true; -} - -//----------------------------------------------------------------------- -bool RTShaderSRSTexturedFog::addFunctionInvocations(ProgramSet* programSet) -{ - if (mFogMode == FOG_NONE) - return true; - - Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); - Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); - Function* vsMain = vsProgram->getEntryPointFunction(); - Function* psMain = psProgram->getEntryPointFunction(); - - vsMain->getStage(FFP_VS_FOG) - .callFunction("FFP_PixelFog_PositionDepth", - {In(mWorldMatrix), In(mCameraPos), In(mVSInPos), Out(mVSOutPosView), Out(mVSOutDepth)}); - - auto psStage = psMain->getStage(FFP_PS_FOG); - psStage.sampleTexture(mBackgroundTextureSampler, mPSInPosView, mFogColour); - - psProgram->addPreprocessorDefines(StringUtil::format("FOG_TYPE=%d", mFogMode)); - vsProgram->addPreprocessorDefines(StringUtil::format("FOG_TYPE=%d", mFogMode)); - - psStage.callFunction("FFP_PixelFog", - {In(mPSInDepth), In(mFogParams), In(mFogColour), In(mPSOutDiffuse), Out(mPSOutDiffuse)}); - return true; -} - -//----------------------------------------------------------------------- -void RTShaderSRSTexturedFog::copyFrom(const SubRenderState& rhs) -{ - const RTShaderSRSTexturedFog& rhsFog = static_cast(rhs); - - mFogMode = rhsFog.mFogMode; - mFogParamsValue = rhsFog.mFogParamsValue; - mFactory = rhsFog.mFactory; -} - -//----------------------------------------------------------------------- -bool RTShaderSRSTexturedFog::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) -{ - if (mFactory == NULL) - return false; - - FogMode fogMode; - ColourValue newFogColour; - Real newFogStart, newFogEnd, newFogDensity; - - if (srcPass->getFogOverride()) - { - fogMode = srcPass->getFogMode(); - newFogStart = srcPass->getFogStart(); - newFogEnd = srcPass->getFogEnd(); - newFogDensity = srcPass->getFogDensity(); - mPassOverrideParams = true; - } - else - { - SceneManager* sceneMgr = ShaderGenerator::getSingleton().getActiveSceneManager(); - - if (sceneMgr == NULL) - { - fogMode = FOG_NONE; - newFogStart = 0.0; - newFogEnd = 0.0; - newFogDensity = 0.0; - } - else - { - fogMode = sceneMgr->getFogMode(); - newFogStart = sceneMgr->getFogStart(); - newFogEnd = sceneMgr->getFogEnd(); - newFogDensity = sceneMgr->getFogDensity(); - } - mPassOverrideParams = false; - } - - // Set fog properties. - setFogProperties(fogMode, newFogStart, newFogEnd, newFogDensity); - - - // Override scene fog since it will happen in shader. - dstPass->setFog(true, FOG_NONE, ColourValue::White, newFogDensity, newFogStart, newFogEnd); - - TextureUnitState* tus = dstPass->createTextureUnitState(); - auto tex = TextureManager::getSingleton().load( - mFactory->getBackgroundTextureName(), RGN_DEFAULT, TEX_TYPE_CUBE_MAP); - tus->setTexture(tex); - mBackgroundSamplerIndex = dstPass->getNumTextureUnitStates() - 1; - - return true; -} - -//----------------------------------------------------------------------- -void RTShaderSRSTexturedFog::setFogProperties(FogMode fogMode, - float fogStart, - float fogEnd, - float fogDensity) -{ - mFogMode = fogMode; - mFogParamsValue.x = fogDensity; - mFogParamsValue.y = fogStart; - mFogParamsValue.z = fogEnd; - mFogParamsValue.w = fogEnd != fogStart ? 1 / (fogEnd - fogStart) : 0; -} - -//----------------------------------------------------------------------- -const String& RTShaderSRSTexturedFogFactory::getType() const -{ - return RTShaderSRSTexturedFog::Type; -} - -//----------------------------------------------------------------------- -SubRenderState* RTShaderSRSTexturedFogFactory::createInstanceImpl() -{ - return OGRE_NEW RTShaderSRSTexturedFog(this); -} diff --git a/Samples/ShaderSystemTexturedFog/src/ShaderSystemTexturedFog.cpp b/Samples/ShaderSystemTexturedFog/src/ShaderSystemTexturedFog.cpp deleted file mode 100644 index 5337639d23f..00000000000 --- a/Samples/ShaderSystemTexturedFog/src/ShaderSystemTexturedFog.cpp +++ /dev/null @@ -1,10 +0,0 @@ -#include "SamplePlugin.h" -#include "ShaderSystemTexturedFog.h" - -using namespace Ogre; -using namespace OgreBites; - -const String Sample_ShaderSystemTexturedFog::FOG_DISTANCE_SLIDER = "FogDistance"; -const String Sample_ShaderSystemTexturedFog::ACTIVATE_FOG_BUTTON = "ActivateFog"; -const String Sample_ShaderSystemTexturedFog::FOG_BACKGROUND_SLIDER = "FogBackground"; -const String Sample_ShaderSystemTexturedFog::ACTIVATE_SKY_BUTTON = "ActivateSkyBox"; diff --git a/Samples/Simple/include/AtomicCounters.h b/Samples/Simple/include/AtomicCounters.h deleted file mode 100644 index c5e8f604c07..00000000000 --- a/Samples/Simple/include/AtomicCounters.h +++ /dev/null @@ -1,57 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ -#include "SdkSample.h" -#include "SamplePlugin.h" -#include "OgreRectangle2D.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_AtomicCounters : public SdkSample -{ - public: - Sample_AtomicCounters() - { - mInfo["Title"] = "Atomic Counters"; - mInfo["Description"] = "An example of using atomic counters to visualise GPU rasterization order"; - mInfo["Thumbnail"] = "thumb_atomicc.png"; - mInfo["Category"] = "Unsorted"; - } - - void testCapabilities(const RenderSystemCapabilities* caps) override - { - requireMaterial("Example/RasterizationOrder"); - } - - bool frameEnded(const FrameEvent& evt) override - { - GpuProgramManager::getSingleton().getSharedParameters("CounterBuffer")->setNamedConstant("ac", 0); - return true; - } - - void setupContent() override - { - mViewport->setBackgroundColour(ColourValue(0.3, 0.3, 0.3)); - - float w = 480.0 / mWindow->getWidth(); - float h = 480.0 / mWindow->getHeight(); - - auto rect = mSceneMgr->createScreenSpaceRect(); - rect->setCorners(-w, h, w, -h, false); - - MaterialPtr mat = MaterialManager::getSingleton().getByName("Example/RasterizationOrder"); - rect->setMaterial(mat); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(rect); - } -}; diff --git a/Samples/Simple/include/BSP.h b/Samples/Simple/include/BSP.h deleted file mode 100644 index 145d47938c0..00000000000 --- a/Samples/Simple/include/BSP.h +++ /dev/null @@ -1,90 +0,0 @@ -#ifndef __BSP_H__ -#define __BSP_H__ - -#include "SdkSample.h" -#include "OgreFileSystemLayer.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_BSP : public SdkSample -{ - public: - - Sample_BSP() - { - mInfo["Title"] = "BSP"; - mInfo["Description"] = "A demo of the indoor, or BSP (Binary Space Partition) scene manager. " - "Also demonstrates how to load BSP maps from Quake 3."; - mInfo["Thumbnail"] = "thumb_bsp.png"; - mInfo["Category"] = "Geometry"; - } - - StringVector getRequiredPlugins() override - { - StringVector names; - names.push_back("BSP Scene Manager"); - return names; - } - - protected: - - void locateResources() override - { - // Pick a new resource group so Q3Shader parser is correctly registered - ResourceGroupManager::getSingleton().setWorldResourceGroupName("BSPWorld"); - } - - void createSceneManager() override - { - mSceneMgr = mRoot->createSceneManager("BspSceneManager"); // the BSP scene manager is required for this sample -#ifdef INCLUDE_RTSHADER_SYSTEM - mShaderGenerator->addSceneManager(mSceneMgr); -#endif - if(mOverlaySystem) - mSceneMgr->addRenderQueueListener(mOverlaySystem); - } - - void loadResources() override - { - /* NOTE: The browser initialises everything at the beginning already, so we use a 0 init proportion. - If you're not compiling this sample for use with the browser, then leave the init proportion at 0.7. */ - mTrayMgr->showLoadingBar(1, 1, 0); - - // associate the world geometry with the world resource group, and then load the group - ResourceGroupManager& rgm = ResourceGroupManager::getSingleton(); - rgm.setCustomStagesForResourceGroup("BSPWorld", mSceneMgr->estimateWorldGeometry("maps/oa_rpg3dm2.bsp")); - rgm.initialiseResourceGroup("BSPWorld"); - rgm.loadResourceGroup("BSPWorld"); - // one would register a ResourceGroupListener for this, if we were not to call it right away - mSceneMgr->setWorldGeometry("maps/oa_rpg3dm2.bsp"); - - mTrayMgr->hideLoadingBar(); - } - - void unloadResources() override - { - // unload the map so we don't interfere with subsequent samples - ResourceGroupManager& rgm = ResourceGroupManager::getSingleton(); - rgm.clearResourceGroup(rgm.getWorldResourceGroupName()); - rgm.setWorldResourceGroupName(ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - } - - void setupContent() override - { - // modify camera for close work - mCamera->setNearClipDistance(4); - mCamera->setFarClipDistance(4000); - - // Quake uses the Z axis as the up axis, so make necessary adjustments - mCameraNode->setFixedYawAxis(true, Vector3::UNIT_Z); - mCameraNode->pitch(Degree(90)); - - // specific for this map - mCameraNode->setPosition(Vector3(0, 0, 340)); - - mCameraMan->setTopSpeed(350); // make the camera move a bit faster - } -}; - -#endif diff --git a/Samples/Simple/include/BezierPatch.h b/Samples/Simple/include/BezierPatch.h deleted file mode 100644 index d7710313d71..00000000000 --- a/Samples/Simple/include/BezierPatch.h +++ /dev/null @@ -1,117 +0,0 @@ -#ifndef __BezierPatch_H__ -#define __BezierPatch_H__ - -#include "SdkSample.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_BezierPatch : public SdkSample -{ -public: - - Sample_BezierPatch() - { - mInfo["Title"] = "Bezier Patch"; - mInfo["Description"] = "A demonstration of the Bezier patch support."; - mInfo["Thumbnail"] = "thumb_bezier.png"; - mInfo["Category"] = "Geometry"; - } - - void checkBoxToggled(CheckBox* box) override - { - mPatchPass->setPolygonMode(box->isChecked() ? PM_WIREFRAME : PM_SOLID); - -#ifdef INCLUDE_RTSHADER_SYSTEM - Material* mat = mPatchPass->getParent()->getParent(); - // Invalidate material in order to reflect polygon mode change in the generated shader based pass. - mShaderGenerator->invalidateMaterial(MSN_SHADERGEN, *mat); -#endif - } - - void sliderMoved(Slider* slider) override - { - mPatch->setSubdivision(slider->getValue()); - } - -protected: - -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -# pragma pack(push, 1) -#endif - struct PatchVertex - { - float x, y, z; - float nx, ny, nz; - float u, v; - }; -#if OGRE_COMPILER == OGRE_COMPILER_MSVC -# pragma pack(pop) -#endif - - void setupContent() override - { - // setup some basic lighting for our scene - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - mSceneMgr->getRootSceneNode() - ->createChildSceneNode(Vector3(100, 100, 100)) - ->attachObject(mSceneMgr->createLight()); - - // define the control point vertices for our patch - PatchVertex verts[9] = - { - {-50, -35, -50, -0.5, 0.5, 0.0, 0.0, 0.0}, - { 0, 0, -50, 0.0, 0.5, 0.0, 0.5, 0.0}, - { 50, 35, -50, 0.5, 0.5, 0.0, 1.0, 0.0}, - {-50, 0, 0, -0.5, 0.5, 0.0, 0.0, 0.5}, - { 0, 0, 0, 0.0, 0.5, 0.0, 0.5, 0.5}, - { 50, 0, 0, 0.5, 0.5, 0.0, 1.0, 0.5}, - {-50, 35, 50, -0.5, 0.5, 0.0, 0.0, 1.0}, - { 0, 0, 50, 0.0, 0.5, 0.0, 0.5, 1.0}, - { 50, -35, 50, 0.5, 0.5, 0.0, 1.0, 1.0} - }; - - // specify a vertex format declaration for our patch: 3 floats for position, 3 floats for normal, 2 floats for UV - mDecl = HardwareBufferManager::getSingleton().createVertexDeclaration(); - mDecl->addElement(0, 0, VET_FLOAT3, VES_POSITION); - mDecl->addElement(0, sizeof(float) * 3, VET_FLOAT3, VES_NORMAL); - mDecl->addElement(0, sizeof(float) * 6, VET_FLOAT2, VES_TEXTURE_COORDINATES, 0); - - // create a patch mesh using vertices and declaration - mPatch = MeshManager::getSingleton().createBezierPatch("patch", - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, (float*)verts, mDecl, 3, 3, 5, 5, PatchSurface::VS_BOTH); - - mPatch->setSubdivision(0); // start at 0 detail - - // create a patch entity from the mesh, give it a material, and attach it to the origin - Entity* ent = mSceneMgr->createEntity("Patch", "patch"); - ent->setMaterialName("Examples/BumpyMetal"); - mSceneMgr->getRootSceneNode()->attachObject(ent); - - // save the main pass of the material so we can toggle wireframe on it - mPatchPass = ent->getSubEntity(0)->getMaterial()->getTechnique(0)->getPass(0); - - // use an orbit style camera - mCameraMan->setStyle(CS_ORBIT); - mCameraMan->setYawPitchDist(Degree(0), Degree(30), 250); - - mTrayMgr->showCursor(); - - // create slider to adjust detail and checkbox to toggle wireframe - mTrayMgr->createThickSlider(TL_TOPLEFT, "Detail", "Detail", 120, 44, 0, 1, 6); - mTrayMgr->createCheckBox(TL_TOPLEFT, "Wireframe", "Wireframe", 120); - } - - void cleanupContent() override - { - HardwareBufferManager::getSingleton().destroyVertexDeclaration(mDecl); - mPatchPass->setPolygonMode(PM_SOLID); - MeshManager::getSingleton().remove(mPatch->getHandle()); - } - - VertexDeclaration* mDecl; - PatchMeshPtr mPatch; - Pass* mPatchPass; -}; - -#endif diff --git a/Samples/Simple/include/Bullet.h b/Samples/Simple/include/Bullet.h deleted file mode 100644 index 2961711aa1b..00000000000 --- a/Samples/Simple/include/Bullet.h +++ /dev/null @@ -1,61 +0,0 @@ -#pragma once - -#include "SdkSample.h" -#include "OgreBullet.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_Bullet : public SdkSample, public RenderTargetListener -{ - std::unique_ptr mDynWorld; - std::unique_ptr mDbgDraw; - -public: - Sample_Bullet() - { - mInfo["Title"] = "Bullet physics integration"; - mInfo["Description"] = "Bullet with Ogre"; - mInfo["Category"] = "Unsorted"; - mInfo["Thumbnail"] = "thumb_bullet.png"; - } - - bool frameStarted(const FrameEvent& evt) override - { - mDynWorld->getBtWorld()->stepSimulation(evt.timeSinceLastFrame, 10); - mDbgDraw->update(); - - return true; - } - - void setupContent(void) override - { - mCameraMan->setStyle(OgreBites::CS_ORBIT); - mCameraMan->setYawPitchDist(Degree(45), Degree(45), 20); - - // without light we would just get a black screen - Light* light = mSceneMgr->createLight("MainLight"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 10, 15))->attachObject(light); - mSceneMgr->setAmbientLight(ColourValue(0.7, 0.7, 0.7)); - - mCamera->setNearClipDistance(0.05); - mTrayMgr->showCursor(); - - // Player object - auto player = mSceneMgr->createEntity("ogrehead.mesh"); - auto playerNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 10, 0)); - playerNode->setScale(1.0/50, 1.0/50, 1.0/50); - playerNode->attachObject(player); - - // Ground - auto level = mSceneMgr->createEntity("TestLevel_b0.mesh"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(level); - - // Physics world and debug drawing - mDynWorld.reset(new Bullet::DynamicsWorld(Vector3(0, -9.8, 0))); - mDbgDraw.reset(new Bullet::DebugDrawer(mSceneMgr->getRootSceneNode(), mDynWorld->getBtWorld())); - - mDynWorld->addRigidBody(5, player, Bullet::CT_SPHERE); - mDynWorld->addRigidBody(0, level, Bullet::CT_TRIMESH); - } -}; diff --git a/Samples/Simple/include/CameraTrack.h b/Samples/Simple/include/CameraTrack.h deleted file mode 100644 index f21cbea9ba7..00000000000 --- a/Samples/Simple/include/CameraTrack.h +++ /dev/null @@ -1,66 +0,0 @@ -#ifndef __CameraTrack_H__ -#define __CameraTrack_H__ - -#include "SdkSample.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_CameraTrack : public SdkSample -{ -public: - - Sample_CameraTrack() - { - mInfo["Title"] = "Camera Tracking"; - mInfo["Description"] = "An example of using AnimationTracks to make a node smoothly follow " - "a predefined path with spline interpolation. Also uses the auto-tracking feature of the camera."; - mInfo["Thumbnail"] = "thumb_camtrack.png"; - mInfo["Category"] = "Unsorted"; - } - -protected: - - void setupContent() override - { - // setup some basic lighting for our scene - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); - mSceneMgr->getRootSceneNode() - ->createChildSceneNode(Vector3(20, 80, 50)) - ->attachObject(mSceneMgr->createLight()); - - mSceneMgr->setSkyBox(true, "Examples/MorningSkyBox"); - - // create an ogre head entity and attach it to a node - Entity* head = mSceneMgr->createEntity("Head", "ogrehead.mesh"); - SceneNode* headNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - headNode->attachObject(head); - - mCameraMan->setStyle(CS_MANUAL); // we will be controlling the camera ourselves, so disable the camera man - mCameraNode->setAutoTracking(true, headNode); // make the camera face the head - mCameraNode->setFixedYawAxis(true); - - // set up a 10 second animation for our camera, using spline interpolation for nice curves - Animation* anim = mSceneMgr->createAnimation("CameraTrack", 10); - anim->setInterpolationMode(Animation::IM_SPLINE); - - // create a track to animate the camera's node - NodeAnimationTrack* track = anim->createNodeTrack(0, mCameraNode); - - // create keyframes for our track - track->createNodeKeyFrame(0)->setTranslate(Vector3(200, 0, 0)); - track->createNodeKeyFrame(2.5)->setTranslate(Vector3(0, -50, 100)); - track->createNodeKeyFrame(5)->setTranslate(Vector3(-500, 100, 0)); - track->createNodeKeyFrame(7.5)->setTranslate(Vector3(0, 200, -300)); - track->createNodeKeyFrame(10)->setTranslate(Vector3(200, 0, 0)); - - // create a new animation state to track this - auto animState = mSceneMgr->createAnimationState("CameraTrack"); - animState->setEnabled(true); - - auto& controllerMgr = ControllerManager::getSingleton(); - controllerMgr.createFrameTimePassthroughController(AnimationStateControllerValue::create(animState, true)); - } -}; - -#endif diff --git a/Samples/Simple/include/CelShading.h b/Samples/Simple/include/CelShading.h deleted file mode 100644 index 3a7c49313cd..00000000000 --- a/Samples/Simple/include/CelShading.h +++ /dev/null @@ -1,93 +0,0 @@ -#ifndef __CelShading_H__ -#define __CelShading_H__ - -#include "SdkSample.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_CelShading : public SdkSample -{ -public: - - Sample_CelShading() - { - mInfo["Title"] = "Cel-shading"; - mInfo["Description"] = "A demo of cel-shaded graphics using vertex & fragment programs."; - mInfo["Thumbnail"] = "thumb_cel.png"; - mInfo["Category"] = "Lighting"; - } - - void testCapabilities(const RenderSystemCapabilities* caps) override - { - requireMaterial("Examples/CelShading"); - } - - bool frameRenderingQueued(const FrameEvent& evt) override - { - // make the light revolve around our model if and only if the check box is checked - if (mMoveLight->isChecked()) mLightPivot->yaw(Degree(evt.timeSinceLastFrame * 30)); - - return SdkSample::frameRenderingQueued(evt); // don't forget the parent class updates! - } - -protected: - - void setupContent() override - { - mViewport->setBackgroundColour(ColourValue::White); - - // set our camera to orbit around the origin and show cursor - mCameraMan->setStyle(CS_ORBIT); - mTrayMgr->showCursor(); - - // attach the light to a pivot node - mLightPivot = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - // create a basic point light with an offset - Light* light = mSceneMgr->createLight(); - mLightPivot->createChildSceneNode(Vector3(20, 40, 50))->attachObject(light); - - // create our model, give it the shader material, and place it at the origin - Entity *ent = mSceneMgr->createEntity("Head", "ogrehead.mesh"); - ent->setMaterialName("Examples/CelShading"); - mSceneMgr->getRootSceneNode()->attachObject(ent); - - /* We set the same material for all parts of the head, but use custom shader parameters to set the - colours for each part. See Examples-Advanced.material for how these are bound to GPU parameters. */ - - SubEntity* sub; - - sub = ent->getSubEntity(0); // eyes - sub->setCustomParameter(SP_SHININESS, Vector4f(35, 0, 0, 0)); - sub->setCustomParameter(SP_DIFFUSE, Vector4f(1, 0.3, 0.3, 1)); - sub->setCustomParameter(SP_SPECULAR, Vector4f(1, 0.6, 0.6, 1)); - - sub = ent->getSubEntity(1); // skin - sub->setCustomParameter(SP_SHININESS, Vector4f(10, 0, 0, 0)); - sub->setCustomParameter(SP_DIFFUSE, Vector4f(0, 0.5, 0, 1)); - sub->setCustomParameter(SP_SPECULAR, Vector4f(0.3, 0.5, 0.3, 1)); - - sub = ent->getSubEntity(2); // earring - sub->setCustomParameter(SP_SHININESS, Vector4f(25, 0, 0, 0)); - sub->setCustomParameter(SP_DIFFUSE, Vector4f(1, 1, 0, 1)); - sub->setCustomParameter(SP_SPECULAR, Vector4f(1, 1, 0.7, 1)); - - sub = ent->getSubEntity(3); // teeth - sub->setCustomParameter(SP_SHININESS, Vector4f(20, 0, 0, 0)); - sub->setCustomParameter(SP_DIFFUSE, Vector4f(1, 1, 0.7, 1)); - sub->setCustomParameter(SP_SPECULAR, Vector4f(1, 1, 1, 1)); - - // create a check box to toggle light movement - mMoveLight = mTrayMgr->createCheckBox(TL_TOPLEFT, "MoveLight", "Move Light"); - mMoveLight->setChecked(true); - } - - // custom shader parameter bindings - enum ShaderParam { SP_SHININESS = 1, SP_DIFFUSE, SP_SPECULAR }; - - SceneNode* mLightPivot; - CheckBox* mMoveLight; -}; - -#endif diff --git a/Samples/Simple/include/Compute.h b/Samples/Simple/include/Compute.h deleted file mode 100644 index 28a29edd453..00000000000 --- a/Samples/Simple/include/Compute.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - - You may use this sample code for anything you like, it is not covered by the - same license as the rest of the engine. - ----------------------------------------------------------------------------- -*/ - -#ifndef __Compute_H__ -#define __Compute_H__ - -#include "SdkSample.h" -#include "SamplePlugin.h" - -namespace OgreBites { -using namespace Ogre; -class _OgreSampleClassExport Sample_Compute : public SdkSample -{ - Entity* mOgreEnt; - - public: - Sample_Compute(); - void testCapabilities(const RenderSystemCapabilities* caps) override; - void setupContent(void) override; -}; -} -#endif // end _CompositorDemo_H_ diff --git a/Samples/Simple/include/CubeMapping.h b/Samples/Simple/include/CubeMapping.h deleted file mode 100644 index 7900103a16f..00000000000 --- a/Samples/Simple/include/CubeMapping.h +++ /dev/null @@ -1,100 +0,0 @@ -#ifndef __CubeMapping_H__ -#define __CubeMapping_H__ - -#include "SdkSample.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_CubeMapping : public SdkSample, public RenderTargetListener -{ -public: - - Sample_CubeMapping() - { - mInfo["Title"] = "Cube Mapping"; - mInfo["Description"] = "Demonstrates the cube mapping feature where a wrap-around environment is reflected " - "off of an object. Uses render-to-texture to create dynamic cubemaps."; - mInfo["Thumbnail"] = "thumb_cubemap.png"; - mInfo["Category"] = "Unsorted"; - } - - bool frameRenderingQueued(const FrameEvent& evt) override - { - mPivot->yaw(Radian(evt.timeSinceLastFrame)); // spin the fishy around the cube mapped one - mFishSwim->addTime(evt.timeSinceLastFrame * 3); // make the fishy swim - return SdkSample::frameRenderingQueued(evt); // don't forget the parent updates! - } - -protected: - - void setupContent() override - { - mSceneMgr->setSkyDome(true, "Examples/CloudySky"); - - // setup some basic lighting for our scene - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); - mSceneMgr->getRootSceneNode() - ->createChildSceneNode(Vector3(20, 80, 50)) - ->attachObject(mSceneMgr->createLight()); - - createCubeMap(); - - // create an ogre head, give it the dynamic cube map material, and place it at the origin - mHead = mSceneMgr->createEntity("CubeMappedHead", "ogrehead.mesh"); - mHead->setMaterialName("Examples/DynamicCubeMap"); - mHead->setVisibilityFlags(0xF); // hide from reflection - mSceneMgr->getRootSceneNode()->attachObject(mHead); - - mPivot = mSceneMgr->getRootSceneNode()->createChildSceneNode(); // create a pivot node - - Entity* fish = mSceneMgr->createEntity("Fish", "fish.mesh"); - mFishSwim = fish->getAnimationState("swim"); - mFishSwim->setEnabled(true); - - // create a child node at an offset and attach a regular ogre head and a nimbus to it - SceneNode* node = mPivot->createChildSceneNode(Vector3(-60, 10, 0)); - node->setScale(7, 7, 7); - node->yaw(Degree(90)); - node->attachObject(fish); - - // create a floor mesh resource - MeshManager::getSingleton().createPlane("floor", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - Plane(Vector3::UNIT_Y, -30), 1000, 1000, 10, 10, true, 1, 8, 8, Vector3::UNIT_Z); - - // create a floor entity, give it a material, and place it at the origin - Entity* floor = mSceneMgr->createEntity("Floor", "floor"); - floor->setMaterialName("Examples/BumpyMetal"); - mSceneMgr->getRootSceneNode()->attachObject(floor); - - // set our camera to orbit around the head and show cursor - mCameraMan->setStyle(CS_ORBIT); - mTrayMgr->showCursor(); - } - - void createCubeMap() - { - // use compositors for easy referencing in material - CompositorManager::getSingleton().addCompositor(mViewport, "CubeMap"); - CompositorManager::getSingleton().setCompositorEnabled(mViewport, "CubeMap", true); - - // create the camera used to render to our cubemap - Camera* cubeCamera = mSceneMgr->createCamera("CubeMapCamera"); - cubeCamera->setFOVy(Degree(90)); - cubeCamera->setAspectRatio(1); - cubeCamera->setNearClipDistance(5); - - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(cubeCamera); - } - - void cleanupContent() override - { - MeshManager::getSingleton().remove("floor", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - } - - Entity* mHead; - SceneNode* mPivot; - AnimationState* mFishSwim; -}; - -#endif diff --git a/Samples/Simple/include/Dot3Bump.h b/Samples/Simple/include/Dot3Bump.h deleted file mode 100644 index f1ed3843c3a..00000000000 --- a/Samples/Simple/include/Dot3Bump.h +++ /dev/null @@ -1,223 +0,0 @@ -#ifndef __Dot3Bump_H__ -#define __Dot3Bump_H__ - -#include "SdkSample.h" -#include "OgreBillboard.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_Dot3Bump : public SdkSample -{ -public: - - Sample_Dot3Bump() - : mMoveLights (true) - { - mInfo["Title"] = "Bump Mapping"; - mInfo["Description"] = "Shows how to use the dot product blending operation and normalization cube map " - "to achieve a bump mapping effect. Tangent space computations made through the guide of the tutorial " - "on bump mapping from http://users.ox.ac.uk/~univ1234 by paul.baker@univ.ox.ac.uk."; - mInfo["Thumbnail"] = "thumb_bump.png"; - mInfo["Category"] = "Lighting"; - mInfo["Help"] = "Left click and drag anywhere in the scene to look around. Let go again to show " - "cursor and access widgets. Use WASD keys to move."; - } - - bool frameRenderingQueued(const FrameEvent& evt) override - { - if (mMoveLights) - { - // rotate the light pivots - mLightPivot1->roll(Degree(evt.timeSinceLastFrame * 30)); - mLightPivot2->roll(Degree(evt.timeSinceLastFrame * 10)); - } - - return SdkSample::frameRenderingQueued(evt); // don't forget the parent class updates! - } - - void itemSelected(SelectMenu* menu) override - { - if (menu == mMeshMenu) - { - // change to the selected entity - mObjectNode->detachAllObjects(); - mObjectNode->attachObject(mSceneMgr->getEntity(mMeshMenu->getSelectedItem())); - - // remember which material is currently selected - int index = std::max(0, mMaterialMenu->getSelectionIndex()); - - // update the material menu's options - mMaterialMenu->setItems(mPossibilities[mMeshMenu->getSelectedItem()]); - - mMaterialMenu->selectItem(index); // select the material with the saved index - } - else - { - // set the selected material for the active mesh - ((Entity*)mObjectNode->getAttachedObject(0))->setMaterialName(menu->getSelectedItem()); - } - } - - void checkBoxToggled(CheckBox* box) override - { - if (StringUtil::startsWith(box->getName(), "Light", false)) - { - // get the light pivot that corresponds to this checkbox - SceneNode* pivot = box->getName() == "Light1" ? mLightPivot1 : mLightPivot2; - - // toggle visibility of light and billboard set - pivot->setVisible(box->isChecked()); - } - else if (box->getName() == "MoveLights") - { - mMoveLights = !mMoveLights; - } - } - -protected: - - void setupContent() override - { - // Make this viewport work with shader generator scheme. - mViewport->setMaterialScheme(MSN_SHADERGEN); - - // create our main node to attach our entities to - mObjectNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - setupModels(); - setupLights(); - setupControls(); - - mCameraMan->setStyle(CS_ORBIT); - mCameraMan->setYawPitchDist(Radian(0), Radian(0), 500); - } - - void setupModels() - { - StringVector matNames; - - -#ifdef INCLUDE_RTSHADER_SYSTEM - matNames.push_back("RTSS/NormalMapping_SinglePass"); - matNames.push_back("RTSS/OffsetMapping"); - matNames.push_back("RTSS/ParallaxOcclusionMapping"); - matNames.push_back("RTSS/NormalMapping_MultiPass"); -#endif - matNames.push_back("Examples/BumpMapping/MultiLight"); - matNames.push_back("Examples/ShowUV"); - matNames.push_back("Examples/ShowNormals"); - matNames.push_back("Examples/ShowTangents"); - - - - mPossibilities["ogrehead.mesh"] = matNames; - mPossibilities["cube.mesh"] = matNames; - mPossibilities["knot.mesh"] = matNames; - - matNames.clear(); -#ifdef INCLUDE_RTSHADER_SYSTEM - matNames.push_back("RTSS/Athene/NormalMapping_SinglePass"); - matNames.push_back("RTSS/Athene/NormalMapping_MultiPass"); -#endif - matNames.push_back("Examples/Athene/NormalMapped"); - matNames.push_back("Examples/ShowUV"); - matNames.push_back("Examples/ShowNormals"); - matNames.push_back("Examples/ShowTangents"); - - - mPossibilities["athene.mesh"] = matNames; - - for (std::map::iterator it = mPossibilities.begin(); it != mPossibilities.end(); it++) - { - // load each mesh with non-default hardware buffer usage options - MeshPtr mesh = MeshManager::getSingleton().load(it->first, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY); - - // build tangent vectors for our mesh - mesh->buildTangentVectors(); - // this version cleans mirrored and rotated UVs but requires quality models - // mesh->buildTangentVectors(VES_TANGENT, src, dest, true, true); - - // create an entity from the mesh and set the first available material - Entity* ent = mSceneMgr->createEntity(mesh->getName(), mesh->getName()); - ent->setMaterialName(it->second.front()); - } - } - - void setupLights() - { - mSceneMgr->setAmbientLight(ColourValue::Black); // disable ambient lighting - - // create pivot nodes - mLightPivot1 = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mLightPivot2 = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - Light* l; - BillboardSet* bbs; - - // create white light - l = mSceneMgr->createLight(); - mLightPivot1->createChildSceneNode(Vector3(200, 0, 0))->attachObject(l); - l->setDiffuseColour(1, 1, 1); - l->setSpecularColour(1, 1, 1); - // create white flare - bbs = mSceneMgr->createBillboardSet(); - bbs->setMaterialName("Examples/Flare"); - bbs->createBillboard(200, 0, 0)->setColour(ColourValue::White); - - mLightPivot1->attachObject(bbs); - - // create red light - l = mSceneMgr->createLight(); - mLightPivot2->createChildSceneNode(Vector3(50, 200, 50))->attachObject(l); - l->setDiffuseColour(1, 0, 0); - l->setSpecularColour(1, 0.8, 0.8); - // create white flare - bbs = mSceneMgr->createBillboardSet(); - bbs->setMaterialName("Examples/Flare"); - bbs->createBillboard(50, 200, 50)->setColour(ColourValue::Red); - - mLightPivot2->attachObject(bbs); - } - - void setupControls() - { - mTrayMgr->showCursor(); - - // make room for the controls - mTrayMgr->showLogo(TL_TOPRIGHT); - mTrayMgr->showFrameStats(TL_TOPRIGHT); - mTrayMgr->toggleAdvancedFrameStats(); - - // create a menu to choose the model displayed - mMeshMenu = mTrayMgr->createLongSelectMenu(TL_BOTTOM, "Mesh", "Mesh", 370, 290, 10); - for (std::map::iterator it = mPossibilities.begin(); it != mPossibilities.end(); it++) - mMeshMenu->addItem(it->first); - - // create a menu to choose the material used by the model - mMaterialMenu = mTrayMgr->createLongSelectMenu(TL_BOTTOM, "Material", "Material", 370, 290, 10); - - // create checkboxes to toggle lights - mTrayMgr->createCheckBox(TL_TOPLEFT, "Light1", "Light A")->setChecked(true, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "Light2", "Light B")->setChecked(true, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "MoveLights", "Move Lights")->setChecked(true, false); - - // a friendly reminder - StringVector names; - names.push_back("Help"); - mTrayMgr->createParamsPanel(TL_TOPLEFT, "Help", 100, names)->setParamValue(0, "H/F1"); - - mMeshMenu->selectItem(0); // select first mesh - } - - std::map mPossibilities; - SceneNode* mObjectNode; - SceneNode* mLightPivot1; - SceneNode* mLightPivot2; - bool mMoveLights; - SelectMenu* mMeshMenu; - SelectMenu* mMaterialMenu; -}; - -#endif diff --git a/Samples/Simple/include/DualQuaternion.h b/Samples/Simple/include/DualQuaternion.h deleted file mode 100644 index b81f202eaa0..00000000000 --- a/Samples/Simple/include/DualQuaternion.h +++ /dev/null @@ -1,192 +0,0 @@ -#ifndef __DualQuaternion_Sample_H__ -#define __DualQuaternion_Sample_H__ - -#include "SdkSample.h" -#include "OgreBillboard.h" - -#if defined(INCLUDE_RTSHADER_SYSTEM) && defined(RTSHADER_SYSTEM_BUILD_EXT_SHADERS) -#include "OgreShaderExHardwareSkinning.h" -#endif - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_DualQuaternion : public SdkSample -{ - public: - Sample_DualQuaternion() : ent(0), entDQ(0), totalTime(0) -#if defined(INCLUDE_RTSHADER_SYSTEM) && defined(RTSHADER_SYSTEM_BUILD_EXT_SHADERS) - , mSrsHardwareSkinning(0) -#endif - { - mInfo["Title"] = "Dual Quaternion Skinning"; - mInfo["Description"] = "A demo of the dual quaternion skinning feature in conjunction with the linear skinning feature."; - mInfo["Thumbnail"] = "thumb_dualquaternionskinning.png"; - mInfo["Category"] = "Animation"; - } - - bool frameRenderingQueued(const FrameEvent& evt) override - { - const Real start = 30; - const Real range = 145; - const Real speed = 1; - const Vector3 vec = Vector3(1,0.3,0).normalisedCopy(); - totalTime += evt.timeSinceLastFrame; - Quaternion orient = Quaternion(Degree(start + Ogre::Math::Sin(totalTime * speed) * range), vec); - ent->getSkeleton()->getBone("Bone02")->setOrientation(orient); - entDQ->getSkeleton()->getBone("Bone02")->setOrientation(orient); - - return SdkSample::frameRenderingQueued(evt); - } - - protected: - void setupContent() override - { -#if defined(INCLUDE_RTSHADER_SYSTEM) && defined(RTSHADER_SYSTEM_BUILD_EXT_SHADERS) - // Make this viewport work with shader generator scheme. - mViewport->setMaterialScheme(MSN_SHADERGEN); - - // Add the hardware skinning to the shader generator default - // render state. - mSrsHardwareSkinning = mShaderGenerator->createSubRenderState(RTShader::SRS_HARDWARE_SKINNING); - Ogre::RTShader::RenderState* renderState = mShaderGenerator->getRenderState(MSN_SHADERGEN); - renderState->addTemplateSubRenderState(mSrsHardwareSkinning); - - mShaderGenerator->invalidateScheme(MSN_SHADERGEN); - - Ogre::MaterialPtr pCast1 = Ogre::MaterialManager::getSingleton().getByName("Ogre/RTShader/shadow_caster_dq_skinning_1weight_twophase"); - Ogre::MaterialPtr pCast2 = Ogre::MaterialManager::getSingleton().getByName("Ogre/RTShader/shadow_caster_dq_skinning_2weight_twophase"); - Ogre::MaterialPtr pCast3 = Ogre::MaterialManager::getSingleton().getByName("Ogre/RTShader/shadow_caster_dq_skinning_3weight_twophase"); - Ogre::MaterialPtr pCast4 = Ogre::MaterialManager::getSingleton().getByName("Ogre/RTShader/shadow_caster_dq_skinning_4weight_twophase"); - - Ogre::RTShader::HardwareSkinningFactory::setCustomShadowCasterMaterials(RTShader::ST_DUAL_QUATERNION, pCast1, pCast2, pCast3, pCast4); - - Ogre::MaterialPtr pCast1l = Ogre::MaterialManager::getSingleton().getByName("Ogre/RTShader/shadow_caster_skinning_1weight"); - Ogre::MaterialPtr pCast2l = Ogre::MaterialManager::getSingleton().getByName("Ogre/RTShader/shadow_caster_skinning_2weight"); - Ogre::MaterialPtr pCast3l = Ogre::MaterialManager::getSingleton().getByName("Ogre/RTShader/shadow_caster_skinning_3weight"); - Ogre::MaterialPtr pCast4l = Ogre::MaterialManager::getSingleton().getByName("Ogre/RTShader/shadow_caster_skinning_4weight"); - - Ogre::RTShader::HardwareSkinningFactory::setCustomShadowCasterMaterials(RTShader::ST_LINEAR, pCast1l, pCast2l, pCast3l, pCast4l); -#endif - // Set shadow properties. - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE); - mSceneMgr->setShadowTextureSize(2048); - mSceneMgr->setShadowColour(ColourValue(0.6, 0.6, 0.6)); - mSceneMgr->setShadowTextureCount(1); - - // Add a little ambient lighting. - mSceneMgr->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); - - SceneNode* lightsBbsNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - BillboardSet* bbs; - - // Create billboard set for lights. - bbs = mSceneMgr->createBillboardSet(); - bbs->setMaterialName("Examples/Flare"); - lightsBbsNode->attachObject(bbs); - - Light* l = mSceneMgr->createLight(Light::LT_POINT); - Vector3 pos(30, 70, 40); - auto ln = mSceneMgr->getRootSceneNode()->createChildSceneNode(pos); - ln->attachObject(l); - ln->setDirection(-pos.normalisedCopy()); - l->setDiffuseColour(1, 1, 1); - bbs->createBillboard(pos)->setColour(l->getDiffuseColour()); - - // Create a floor mesh resource. - MeshManager::getSingleton().createPlane("floor", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - Plane(Vector3::UNIT_Y, -1), 250, 250, 25, 25, true, 1, 15, 15, Vector3::UNIT_Z); - - // Add a floor to our scene using the floor mesh we created. - Entity* floor = mSceneMgr->createEntity("Floor", "floor"); - floor->setMaterialName("Examples/Rockwall"); - floor->setCastShadows(false); - mSceneMgr->getRootSceneNode()->attachObject(floor); - - // Set camera initial transform and speed. - mCameraNode->setPosition(100, 20, 0); - mCameraNode->lookAt(Vector3(0, 10, 0), Node::TS_PARENT); - mCameraMan->setTopSpeed(50); - - setupModels(); - } - - void setupModels() - { - SceneNode* sn = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - sn->translate(0, 0, 20, Node::TS_LOCAL); - - // Create and attach a spine entity with standard skinning. - ent = mSceneMgr->createEntity("Spine", "spine.mesh"); - ent->setMaterialName("spine"); - ent->getSkeleton()->getBone("Bone02")->setManuallyControlled(true); - sn->attachObject(ent); - sn->scale(Vector3(0.2,0.2,0.2)); - - sn = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - sn->translate(0, 0, -20, Node::TS_LOCAL); - - // Create and attach a spine entity with dual - // quaternion skinning. - entDQ = mSceneMgr->createEntity("SpineDQ", "spine.mesh"); - entDQ->setMaterialName("spineDualQuat"); - entDQ->getSkeleton()->getBone("Bone02")->setManuallyControlled(true); - sn->attachObject(entDQ); - sn->scale(Vector3(0.2,0.2,0.2)); - -#if defined(INCLUDE_RTSHADER_SYSTEM) && defined(RTSHADER_SYSTEM_BUILD_EXT_SHADERS) - // In case the system uses the RTSS, the following line will - // ensure that the entity is using hardware animation in RTSS - // as well. - RTShader::HardwareSkinningFactory::prepareEntityForSkinning(ent); - RTShader::HardwareSkinningFactory::prepareEntityForSkinning(entDQ, RTShader::ST_DUAL_QUATERNION, false, true); -#endif - - // make sure we query the correct scheme - MaterialManager::getSingleton().setActiveScheme(mViewport->getMaterialScheme()); - - // Create name and value for skinning mode. - StringVector names; - names.push_back("Skinning"); - String value = "Software"; - - // Change the value if hardware skinning is enabled. - MaterialPtr dqMat = ent->getSubEntity(0)->getMaterial(); - if(dqMat) - { - Technique* bestTechnique = dqMat->getBestTechnique(); - if(bestTechnique) - { - Pass* pass = bestTechnique->getPass(0); - if (pass && pass->hasVertexProgram() && pass->getVertexProgram()->isSkeletalAnimationIncluded()) - { - value = "Hardware"; - } - } - } - - // Create a params panel to display the skinning mode. - mTrayMgr->createParamsPanel(TL_TOPLEFT, "Skinning", 170, names)->setParamValue(0, value); - } - - void cleanupContent() override - { - MeshManager::getSingleton().remove("floor", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - -#if defined(INCLUDE_RTSHADER_SYSTEM) && defined(RTSHADER_SYSTEM_BUILD_EXT_SHADERS) - Ogre::RTShader::RenderState* renderState = mShaderGenerator->getRenderState(MSN_SHADERGEN); - renderState->removeSubRenderState(mSrsHardwareSkinning); -#endif - } - - Entity* ent; - Entity* entDQ; - - Real totalTime; - -#if defined(INCLUDE_RTSHADER_SYSTEM) && defined(RTSHADER_SYSTEM_BUILD_EXT_SHADERS) - RTShader::SubRenderState* mSrsHardwareSkinning; -#endif -}; - -#endif diff --git a/Samples/Simple/include/DynTex.h b/Samples/Simple/include/DynTex.h deleted file mode 100644 index c17eee34ac3..00000000000 --- a/Samples/Simple/include/DynTex.h +++ /dev/null @@ -1,191 +0,0 @@ -#ifndef __DynTex_H__ -#define __DynTex_H__ - -#include "SdkSample.h" -#include "OgreParticleSystem.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_DynTex : public SdkSample -{ -public: - - Sample_DynTex() : TEXTURE_SIZE(128), SQR_BRUSH_RADIUS(Math::Sqr(12)) - { - mInfo["Title"] = "Dynamic Texturing"; - mInfo["Description"] = "Demonstrates how to create and use dynamically changing textures."; - mInfo["Thumbnail"] = "thumb_dyntex.png"; - mInfo["Category"] = "Unsorted"; - mInfo["Help"] = "Use the left mouse button to wipe away the frost. " - "It's cold though, so the frost will return after a while."; - } - - bool frameRenderingQueued(const FrameEvent& evt) override - { - // shoot a ray from the cursor to the plane - Ray ray = mTrayMgr->getCursorRay(mCamera); - mCursorQuery->setRay(ray); - RaySceneQueryResult& result = mCursorQuery->execute(); - - if (!result.empty()) - { - // using the point of intersection, find the corresponding texel on our texture - Vector3 pt = ray.getPoint(result.back().distance); - mBrushPos = (Vector2(pt.x, -pt.y) / mPlaneSize + Vector2(0.5, 0.5)) * TEXTURE_SIZE; - } - - uint8 freezeAmount = 0; - mTimeSinceLastFreeze += evt.timeSinceLastFrame; - - // find out how much to freeze the plane based on time passed - while (mTimeSinceLastFreeze >= 0.1) - { - mTimeSinceLastFreeze -= 0.1; - freezeAmount += 0x04; - } - - updateTexture(freezeAmount); // rebuild texture contents - - mPenguinAnimState->addTime(evt.timeSinceLastFrame); // increment penguin idle animation time - mPenguinNode->yaw(Radian(evt.timeSinceLastFrame)); // spin the penguin around - - return SdkSample::frameRenderingQueued(evt); // don't forget the parent class updates! - } - - bool mousePressed(const MouseButtonEvent& evt) override - { - if (mTrayMgr->mousePressed(evt)) return true; - mWiping = true; // wipe frost if user left clicks in the scene - return true; - } - - bool mouseReleased(const MouseButtonEvent& evt) override - { - if (mTrayMgr->mouseReleased(evt)) return true; - mWiping = false; // stop wiping frost if user releases LMB - return true; - } - -protected: - - void setupContent() override - { - mSceneMgr->setSkyBox(true, "Examples/StormySkyBox"); // add a skybox - - // setup some basic lighting for our scene - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - mSceneMgr->getRootSceneNode() - ->createChildSceneNode(Vector3(20, 80, 50)) - ->attachObject(mSceneMgr->createLight()); - - // set initial camera position - mCameraMan->setStyle(CS_MANUAL); - mCameraNode->setPosition(0, 0, 200); - - mTrayMgr->showCursor(); - - // create our dynamic texture with 8-bit luminance texels - TexturePtr tex = TextureManager::getSingleton().createManual("thaw", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - TEX_TYPE_2D, TEXTURE_SIZE, TEXTURE_SIZE, 0, PF_L8, TU_DYNAMIC_WRITE_ONLY); - MaterialManager::getSingleton() - .getByName("Examples/Frost", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME) - ->getTechnique(0) - ->getPass(0) - ->getTextureUnitState(1) - ->setTexture(tex); - - mTexBuf = tex->getBuffer(); // save off the texture buffer - - // initialise the texture to have full luminance - mConstantTexBuf.resize(mTexBuf->getSizeInBytes(), 0xff); - - mBox = PixelBox(TEXTURE_SIZE, TEXTURE_SIZE, 1, PF_L8, mConstantTexBuf.data()); - mTexBuf->blitFromMemory(mBox); - - // create a penguin and attach him to our penguin node - Entity* penguin = mSceneMgr->createEntity("Penguin", "penguin.mesh"); - mPenguinNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mPenguinNode->attachObject(penguin); - - // get and enable the penguin idle animation - mPenguinAnimState = penguin->getAnimationState("amuse"); - mPenguinAnimState->setEnabled(true); - - // create a snowstorm over the scene, and fast forward it a little - ParticleSystem* ps = mSceneMgr->createParticleSystem("Snow", "Examples/Snow"); - mSceneMgr->getRootSceneNode()->attachObject(ps); - ps->fastForward(30); - - // create a frosted screen in front of the camera, using our dynamic texture to "thaw" certain areas - Entity* ent = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); - ent->setMaterialName("Examples/Frost"); - SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - node->setPosition(0, 0, 50); - node->attachObject(ent); - - mPlaneSize = ent->getBoundingBox().getSize().x; // remember the size of the plane - - mCursorQuery = mSceneMgr->createRayQuery(Ray()); // create a ray scene query for the cursor - - mTimeSinceLastFreeze = 0; - mWiping = false; - } - - void updateTexture(uint8 freezeAmount) - { - // get access to raw texel data - uint8* data = &mConstantTexBuf[0]; - - uint8 temperature; - Real sqrDistToBrush; - - // go through every texel... - for (unsigned int y = 0; y < TEXTURE_SIZE; y++) - { - for (unsigned int x = 0; x < TEXTURE_SIZE; x++) - { - if (freezeAmount != 0) - { - // gradually refreeze anything that isn't completely frozen - temperature = 0xff - *data; - if (temperature > freezeAmount) *data += freezeAmount; - else *data = 0xff; - } - - if (mWiping) - { - // wipe frost from under the cursor - sqrDistToBrush = Math::Sqr(x - mBrushPos.x) + Math::Sqr(y - mBrushPos.y); - if (sqrDistToBrush <= SQR_BRUSH_RADIUS) - *data = std::min(sqrDistToBrush / SQR_BRUSH_RADIUS * 0xff, *data); - } - - data++; - } - } - - mTexBuf->blitFromMemory(mBox); - } - - void cleanupContent() override - { - TextureManager::getSingleton().remove("thaw", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - mSceneMgr->destroyQuery(mCursorQuery); - } - - const unsigned int TEXTURE_SIZE; - const unsigned int SQR_BRUSH_RADIUS; - HardwarePixelBufferSharedPtr mTexBuf; - PixelBox mBox; - std::vector mConstantTexBuf; - Real mPlaneSize; - RaySceneQuery* mCursorQuery; - Vector2 mBrushPos; - Real mTimeSinceLastFreeze; - bool mWiping; - SceneNode* mPenguinNode; - AnimationState* mPenguinAnimState; -}; - -#endif diff --git a/Samples/Simple/include/FacialAnimation.h b/Samples/Simple/include/FacialAnimation.h deleted file mode 100644 index 4551aff4f72..00000000000 --- a/Samples/Simple/include/FacialAnimation.h +++ /dev/null @@ -1,160 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#ifndef __FacialAnimation_H__ -#define __FacialAnimation_H__ - -#include "SdkSample.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_FacialAnimation : public SdkSample -{ - public: - - Sample_FacialAnimation(): - mSpeakAnimState(0), mManualAnimState(0), mManualKeyFrame(0), mPlayAnimation(0) - { - mInfo["Title"] = "Facial Animation"; - mInfo["Description"] = "A demonstration of the facial animation feature, using pose animation."; - mInfo["Thumbnail"] = "thumb_facial.png"; - mInfo["Category"] = "Animation"; - mInfo["Help"] = "Use the checkbox to enable/disable manual animation. " - "When manual animation is enabled, use the sliders to adjust each pose's influence."; - } - - protected: - - void setupContent(void) override - { - // setup some basic lighting for our scene - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - mSceneMgr->getRootSceneNode() - ->createChildSceneNode(Vector3(40, 60, 50)) - ->attachObject(mSceneMgr->createLight()); - mSceneMgr->getRootSceneNode() - ->createChildSceneNode(Vector3(-120, -80, -50)) - ->attachObject(mSceneMgr->createLight()); - - // pre-load the mesh so that we can tweak it with a manual animation - mHeadMesh = MeshManager::getSingleton().load("facial.mesh", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - // create a manual animation, create a pose track for it, and create a keyframe in that track - mManualKeyFrame = mHeadMesh->createAnimation("Manual", 0)->createVertexTrack(4, VAT_POSE)->createVertexPoseKeyFrame(0); - - // create pose references for the first 15 poses - for (unsigned int i = 0; i < 15; i++) mManualKeyFrame->addPoseReference(i, 0); - - // create a head entity from the mesh and attach it to a node with a vertical offset to center it - Entity* head = mSceneMgr->createEntity("Head", "facial.mesh"); - - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, -30, 0))->attachObject(head); - - // get the animation states - mSpeakAnimState = head->getAnimationState("Speak"); - mManualAnimState = head->getAnimationState("Manual"); - - // make the camera orbit around the head, and show the cursor - mCameraMan->setStyle(CS_ORBIT); - mCameraMan->setYawPitchDist(Radian(0), Radian(0), 130); - mTrayMgr->showCursor(); - - // by default, the speaking animation is enabled - auto& controllerMgr = ControllerManager::getSingleton(); - mPlayAnimation = controllerMgr.createFrameTimePassthroughController( - AnimationStateControllerValue::create(mSpeakAnimState, true)); - - setupControls(); - } - - void setupControls() - { - // make logo and frame stats a little more compact to make room for controls - mTrayMgr->showLogo(TL_BOTTOMLEFT); - mTrayMgr->toggleAdvancedFrameStats(); - - // create group labels for the different sliders - mExpressions.push_back(mTrayMgr->createLabel(TL_NONE, "ExpressionLabel", "Expressions")); - mMouthShapes.push_back(mTrayMgr->createLabel(TL_NONE, "MouthShapeLabel", "Mouth Shapes")); - - // create sliders to adjust pose influence - for (unsigned int i = 0; i < mManualKeyFrame->getPoseReferences().size(); i++) - { - String sliderName = "Pose" + StringConverter::toString(i); - String poseName = mHeadMesh->getPoseList()[i]->getName(); - - if (poseName.find("Expression") != std::string::npos) - mExpressions.push_back(mTrayMgr->createLongSlider(TL_NONE, sliderName, poseName.substr(11), 200, 80, 44, 0, 1, 11)); - else mMouthShapes.push_back(mTrayMgr->createLongSlider(TL_NONE, sliderName, poseName.substr(0, 1), 160, 80, 44, 0, 1, 11)); - } - - // checkbox to switch between automatic animation and manual animation. - mTrayMgr->createCheckBox(TL_TOP, "Manual", "Manual Animation")->setChecked(!mPlayAnimation); - } - - void cleanupContent() override - { - mExpressions.clear(); - mMouthShapes.clear(); - mSpeakAnimState = 0; - mManualAnimState = 0; - mManualKeyFrame = 0; - mHeadMesh->unload(); - } - - void checkBoxToggled(OgreBites::CheckBox * box) override - { - bool play = !box->isChecked(); - mPlayAnimation->setEnabled(play); - - // toggle animation states - mSpeakAnimState->setEnabled(play); - mManualAnimState->setEnabled(!play); - - // toggle expression controls - for (unsigned int i = 0; i < mExpressions.size(); i++) - { - mTrayMgr->moveWidgetToTray(mExpressions[i], play ? TL_NONE : TL_TOPLEFT); - if (play) mExpressions[i]->hide(); - else mExpressions[i]->show(); - } - - // toggle mouth shape controls - for (unsigned int i = 0; i < mMouthShapes.size(); i++) - { - mTrayMgr->moveWidgetToTray(mMouthShapes[i], play ? TL_NONE : TL_TOPRIGHT); - if (play) mMouthShapes[i]->hide(); - else mMouthShapes[i]->show(); - } - } - - void sliderMoved(OgreBites::Slider * slider) override - { - // update the pose reference controlled by this slider - mManualKeyFrame->updatePoseReference(StringConverter::parseInt(slider->getName().substr(4)), slider->getValue()); - // dirty animation state since we're fudging this manually - mManualAnimState->getParent()->_notifyDirty(); - } - - MeshPtr mHeadMesh; - AnimationState* mSpeakAnimState; - AnimationState* mManualAnimState; - VertexPoseKeyFrame* mManualKeyFrame; - ControllerFloat* mPlayAnimation; - WidgetList mExpressions; - WidgetList mMouthShapes; -}; - -#endif diff --git a/Samples/Simple/include/Fresnel.h b/Samples/Simple/include/Fresnel.h deleted file mode 100644 index bc7e4f7a285..00000000000 --- a/Samples/Simple/include/Fresnel.h +++ /dev/null @@ -1,233 +0,0 @@ -#ifndef __Fresnel_H__ -#define __Fresnel_H__ - -#include "SdkSample.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_Fresnel : public SdkSample, public RenderTargetListener -{ -public: - static const uint32 SUBMERGED_MASK = 0x0F0; - static const uint32 SURFACE_MASK = 0x00F; - static const uint32 WATER_MASK = 0xF00; - - Sample_Fresnel() : NUM_FISH(30), NUM_FISH_WAYPOINTS(10), FISH_PATH_LENGTH(200), FISH_SCALE(2) - { - mInfo["Title"] = "Fresnel"; - mInfo["Description"] = "Shows how to create reflections and refractions using render-to-texture and shaders."; - mInfo["Thumbnail"] = "thumb_fresnel.png"; - mInfo["Category"] = "Unsorted"; - } - - void testCapabilities(const RenderSystemCapabilities* caps) override - { - requireMaterial("Examples/FresnelReflectionRefraction"); - } - - bool frameRenderingQueued(const FrameEvent &evt) override - { - // update the fish spline path animations and loop as needed - mFishAnimTime += evt.timeSinceLastFrame; - while (mFishAnimTime >= FISH_PATH_LENGTH) mFishAnimTime -= FISH_PATH_LENGTH; - - for (unsigned int i = 0; i < NUM_FISH; i++) - { - mFishAnimStates[i]->addTime(evt.timeSinceLastFrame * 2); // update fish swim animation - - // set the new position based on the spline path and set the direction based on displacement - Vector3 lastPos = mFishNodes[i]->getPosition(); - mFishNodes[i]->setPosition(mFishSplines[i].interpolate(mFishAnimTime / FISH_PATH_LENGTH)); - mFishNodes[i]->setDirection(mFishNodes[i]->getPosition() - lastPos, Node::TS_PARENT, Vector3::NEGATIVE_UNIT_X); - mFishNodes[i]->setFixedYawAxis(true); - } - - return SdkSample::frameRenderingQueued(evt); - } - - void preRenderTargetUpdate(const RenderTargetEvent& evt) override - { - mCamera->enableReflection(mWaterPlane); - } - - void postRenderTargetUpdate(const RenderTargetEvent& evt) override - { - mCamera->disableReflection(); - } - -protected: - - void setupContent() override - { - mCameraNode->setPosition(-50, 125, 760); - mCameraMan->setTopSpeed(280); - - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); // set ambient light - - mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); // set a skybox - - // make the scene's main light come from above - auto ln = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - ln->setDirection(Vector3::NEGATIVE_UNIT_Y); - ln->attachObject(mSceneMgr->createLight(Light::LT_DIRECTIONAL)); - - setupWater(); - setupProps(); - setupFish(); - - for (auto e : mSurfaceEnts) - e->setVisibilityFlags(SURFACE_MASK); - for (auto e : mSubmergedEnts) - e->setVisibilityFlags(SUBMERGED_MASK); - } - - void setupWater() - { - auto compositor = CompositorManager::getSingleton().addCompositor(mViewport, "Fresnel"); - CompositorManager::getSingleton().setCompositorEnabled(mViewport, "Fresnel", true); - - // toggle reflection in camera - compositor->getRenderTarget("reflection")->addListener(this); - - mCamera->setAutoAspectRatio(true); - // create our water plane mesh - mWaterPlane = Plane(Vector3::UNIT_Y, 0); - MeshManager::getSingleton().createPlane("water", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - mWaterPlane, 700, 1300, 10, 10, true, 1, 3, 5, Vector3::UNIT_Z); - - // create a water entity using our mesh, give it the shader material, and attach it to the origin - mWater = mSceneMgr->createEntity("Water", "water"); - auto mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefraction"); - mat->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setProjectiveTexturing(true, mCamera); - mWater->setMaterial(mat); - mSceneMgr->getRootSceneNode()->attachObject(mWater); - - // hide the water from the render textures - mWater->setVisibilityFlags(WATER_MASK); - } - - void windowUpdate() - { - mWindow->update(); - } - - void setupProps() - { - Entity* ent; - - // setting up props might take a while, so create a progress bar for visual feedback - ProgressBar* pb = mTrayMgr->createProgressBar(TL_CENTER, "FresnelBuildingBar", "Creating Props...", 280, 100); - mTrayMgr->showBackdrop("SdkTrays/Shade"); - - pb->setComment("Upper Bath"); - windowUpdate(); - ent = mSceneMgr->createEntity("UpperBath", "RomanBathUpper.mesh" ); - mSceneMgr->getRootSceneNode()->attachObject(ent); - mSurfaceEnts.push_back(ent); - pb->setProgress(0.4); - - pb->setComment("Columns"); - windowUpdate(); - ent = mSceneMgr->createEntity("Columns", "Columns.mesh"); - mSceneMgr->getRootSceneNode()->attachObject(ent); - mSurfaceEnts.push_back(ent); - pb->setProgress(0.5); - - pb->setComment("Ogre Head"); - windowUpdate(); - ent = mSceneMgr->createEntity("Head", "ogrehead.mesh"); - ent->setMaterialName("RomanBath/OgreStone"); - mSurfaceEnts.push_back(ent); - pb->setProgress(0.6); - - SceneNode* headNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - headNode->setPosition(-350, 55, 130); - headNode->yaw(Degree(90)); - headNode->attachObject(ent); - - pb->setComment("Lower Bath"); - windowUpdate(); - ent = mSceneMgr->createEntity("LowerBath", "RomanBathLower.mesh"); - mSceneMgr->getRootSceneNode()->attachObject(ent); - mSubmergedEnts.push_back(ent); - pb->setProgress(1); - windowUpdate(); - - mTrayMgr->destroyWidget(pb); - mTrayMgr->hideBackdrop(); - } - - void setupFish() - { - mFishNodes.resize(NUM_FISH); - mFishAnimStates.resize(NUM_FISH); - mFishSplines.resize(NUM_FISH); - - for (unsigned int i = 0; i < NUM_FISH; i++) - { - // create fish entity - Entity* ent = mSceneMgr->createEntity("Fish" + StringConverter::toString(i + 1), "fish.mesh"); - mSubmergedEnts.push_back(ent); - - // create an appropriately scaled node and attach the entity - mFishNodes[i] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mFishNodes[i]->setScale(Vector3::UNIT_SCALE * FISH_SCALE); - mFishNodes[i]->attachObject(ent); - - // enable and save the swim animation state - mFishAnimStates[i] = ent->getAnimationState("swim"); - mFishAnimStates[i]->setEnabled(true); - - mFishSplines[i].setAutoCalculate(false); // save the tangent calculation for when we are all done - - // generate random waypoints for the fish to swim through - for (unsigned int j = 0; j < NUM_FISH_WAYPOINTS; j++) - { - Vector3 pos(Math::SymmetricRandom() * 270, -10, Math::SymmetricRandom() * 700); - - if (j > 0) // make sure the waypoint isn't too far from the last, or our fish will be turbo-fish - { - const Vector3& lastPos = mFishSplines[i].getPoint(j - 1); - Vector3 delta = pos - lastPos; - if (delta.length() > 750) pos = lastPos + delta.normalisedCopy() * 750; - } - - mFishSplines[i].addPoint(pos); - } - - // close the spline and calculate all the tangents at once - mFishSplines[i].addPoint(mFishSplines[i].getPoint(0)); - mFishSplines[i].recalcTangents(); - } - - mFishAnimTime = 0; - } - - void cleanupContent() override - { - mSurfaceEnts.clear(); - mSubmergedEnts.clear(); - mFishNodes.clear(); - mFishAnimStates.clear(); - mFishSplines.clear(); - - MeshManager::getSingleton().remove("water", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - MaterialManager::getSingleton().unload("Examples/FresnelReflectionRefraction", RGN_DEFAULT); - } - - const unsigned int NUM_FISH; - const unsigned int NUM_FISH_WAYPOINTS; - const unsigned int FISH_PATH_LENGTH; - const Real FISH_SCALE; - std::vector mSurfaceEnts; - std::vector mSubmergedEnts; - Plane mWaterPlane; - Entity* mWater; - std::vector mFishNodes; - std::vector mFishAnimStates; - std::vector mFishSplines; - Real mFishAnimTime; -}; - -#endif diff --git a/Samples/Simple/include/Grass.h b/Samples/Simple/include/Grass.h deleted file mode 100644 index 72acf5f0a8b..00000000000 --- a/Samples/Simple/include/Grass.h +++ /dev/null @@ -1,319 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - Also see acknowledgements in Readme.html - - You may use this sample code for anything you like, it is not covered by the - same license as the rest of the engine. - ----------------------------------------------------------------------------- -*/ -#ifndef __Grass_H__ -#define __Grass_H__ - -#include "SdkSample.h" -#include "OgreBillboard.h" -#include "OgrePredefinedControllers.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_Grass : public SdkSample -{ - public: - - Sample_Grass() - { - mInfo["Title"] = "Grass"; - mInfo["Description"] = "Demonstrates how to use the StaticGeometry class to create 'baked' " - "instances of many meshes, to create effects like grass efficiently."; - mInfo["Thumbnail"] = "thumb_grass.png"; - mInfo["Category"] = "Environment"; - mInfo["Help"] = "Press B to toggle bounding boxes."; - } - - bool frameRenderingQueued(const FrameEvent& evt) override - { - mLightAnimState->addTime(evt.timeSinceLastFrame); // move the light around - waveGrass(evt.timeSinceLastFrame); // wave the grass around slowly to simulate wind - return SdkSample::frameRenderingQueued(evt); // don't forget the parent class updates! - } - - bool keyPressed(const KeyboardEvent& evt) override - { - Keycode key = evt.keysym.sym; - // toggle bounding boxes with B key unless the help dialog is visible - if (key == 'b' && !mTrayMgr->isDialogVisible()) - mSceneMgr->showBoundingBoxes(!mSceneMgr->getShowBoundingBoxes()); - return SdkSample::keyPressed(evt); - } - - protected: - - /*============================================================================= - // This class will be used to pulsate the light and billboard. - =============================================================================*/ - class LightPulse : public ControllerValue - { - public: - - LightPulse(Light* light, Billboard* billboard, const ColourValue& maxColour, Real maxSize) - { - mLight = light; - mBillboard = billboard; - mMaxColour = maxColour; - mMaxSize = maxSize; - } - - float getValue () const override - { - return mIntensity; - } - - void setValue (float value) override - { - mIntensity = value; - - // calculate new colour and apply it to the light and billboard - ColourValue newColour = mMaxColour * mIntensity; - mLight->setDiffuseColour(newColour); - mBillboard->setColour(newColour); - - // calculate new billboard size and apply it - float newSize = mMaxSize * mIntensity; - mBillboard->setDimensions(newSize, newSize); - } - - protected: - - Light* mLight; - Billboard* mBillboard; - ColourValue mMaxColour; - Real mMaxSize; - Real mIntensity; - }; - - void setupContent() override - { - // Make this viewport work with shader generator - mViewport->setMaterialScheme(MSN_SHADERGEN); - mSceneMgr->setSkyBox(true, "Examples/SpaceSkyBox"); - - // create a mesh for our ground - MeshManager::getSingleton().createPlane("ground", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - Plane(Vector3::UNIT_Y, 0), 1000, 1000, 20, 20, true, 1, 6, 6, Vector3::UNIT_Z); - - // create a ground entity from our mesh and attach it to the origin - Entity* ground = mSceneMgr->createEntity("Ground", "ground"); - ground->setMaterialName("Examples/GrassFloor"); - ground->setCastShadows(false); - mSceneMgr->getRootSceneNode()->attachObject(ground); - - //! [static_geom] - // create our grass mesh, and create a grass entity from it - createGrassMesh(); - Entity* grass = mSceneMgr->createEntity("Grass", "grass"); - - // create a static geometry field, which we will populate with grass - mField = mSceneMgr->createStaticGeometry("Field"); - mField->setRegionDimensions(Vector3(140, 140, 140)); - mField->setOrigin(Vector3(70, 70, 70)); - //! [static_geom] - - //! [grass_field] - // add grass uniformly throughout the field, with some random variations - for (int x = -280; x < 280; x += 20) - { - for (int z = -280; z < 280; z += 20) - { - Vector3 pos(x + Math::RangeRandom(-7, 7), 0, z + Math::RangeRandom(-7, 7)); - Quaternion ori(Degree(Math::RangeRandom(0, 359)), Vector3::UNIT_Y); - Vector3 scale(1, Math::RangeRandom(0.85, 1.15), 1); - - mField->addEntity(grass, pos, ori, scale); - } - } - - mField->build(); // build our static geometry (bake the grass into it) - //! [grass_field] - - // build tangent vectors for the ogre head mesh - MeshPtr headMesh = MeshManager::getSingleton().load("ogrehead.mesh", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - headMesh->buildTangentVectors(); - - // put an ogre head in the middle of the field - Entity* head = mSceneMgr->createEntity("Head", "ogrehead.mesh"); - head->setMaterialName("RTSS/OffsetMapping"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 30, 0))->attachObject(head); - - setupLighting(); - - mTrayMgr->createCheckBox(TL_TOPLEFT, "wind", "Wind")->setChecked(false, false); - mTrayMgr->showCursor(); - - mCameraMan->setStyle(CS_ORBIT); - mCameraMan->setYawPitchDist(Degree(0), Degree(25), 200); - } - - void createGrassMesh() - { - const float width = 40; - const float height = 40; - - //! [mo] - ManualObject obj("GrassObject"); - obj.begin("Examples/GrassBlades"); - //! [mo] - // to apply wind in vertex shader: - // obj.begin("Examples/GrassBladesWaver"); - - for (unsigned int i = 0; i < 3; i++) // each grass mesh consists of 3 planes - { - //! [grass_base] - // planes intersect along the Y axis with 60 degrees between them - Vector3 vec = Quaternion(Degree(i * 60), Vector3::UNIT_Y) * Vector3(width / 2, 0, 0); - //! [grass_base] - - //! [mo_quad] - for (unsigned int j = 0; j < 4; j++) // each plane has 4 vertices - { - vec.y = j % 2 ? 0 : height; - obj.position(j < 2 ? Vector3(-1, 1, -1) * vec : vec); - obj.textureCoord(j < 2 ? 0 : 1, j % 2); - - // all normals point straight up - obj.normal(0, 1, 0); - } - //! [mo_quad] - //! [mo_index] - unsigned int off = i * 4; - // each plane consists of 2 triangles - obj.triangle(off + 0, off + 3, off + 1); - obj.triangle(off + 0, off + 2, off + 3); - //! [mo_index] - } - - //! [finish] - obj.end(); - obj.convertToMesh("grass"); - //! [finish] - } - - void setupLighting() - { - mSceneMgr->setAmbientLight(ColourValue::Black); // turn off ambient light - - ColourValue lightColour(1, 1, 0.3); - - // create a light - Light* light = mSceneMgr->createLight(); - light->setDiffuseColour(lightColour); - light->setSpecularColour(1, 1, 0.3); - light->setAttenuation(1500, 1, 0.0005, 0); - - // create a flare - BillboardSet* bbs = mSceneMgr->createBillboardSet(1); - bbs->setMaterialName("Examples/Flare"); - Billboard* bb = bbs->createBillboard(0, 0, 0, lightColour); - - // create a controller for the light intensity, using our LightPulsator class - ControllerFunctionRealPtr func(OGRE_NEW WaveformControllerFunction(Ogre::WFT_SINE, 0.5, 0.5, 0, 0.5)); - ControllerValueRealPtr dest(OGRE_NEW LightPulse(light, bb, lightColour, 15)); - ControllerManager& cm = ControllerManager::getSingleton(); - mLightController = cm.createController(cm.getFrameTimeSource(), dest, func); - - // create a light node and attach the light and flare to it - SceneNode* lightNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - lightNode->attachObject(light); - lightNode->attachObject(bbs); - - // set up a 20 second animation for our light, using spline interpolation for nice curves - Animation* anim = mSceneMgr->createAnimation("LightTrack", 20); - anim->setInterpolationMode(Animation::IM_SPLINE); - - // create a track to animate the camera's node - NodeAnimationTrack* track = anim->createNodeTrack(0, lightNode); - - // create keyframes for our track - track->createNodeKeyFrame(0)->setTranslate(Vector3(42, 77, -42)); - track->createNodeKeyFrame(2)->setTranslate(Vector3(21, 84, -35)); - track->createNodeKeyFrame(4)->setTranslate(Vector3(-21, 91, -14)); - track->createNodeKeyFrame(6)->setTranslate(Vector3(-56, 70, -28)); - track->createNodeKeyFrame(8)->setTranslate(Vector3(-28, 70, -56)); - track->createNodeKeyFrame(10)->setTranslate(Vector3(-14, 63, -28)); - track->createNodeKeyFrame(12)->setTranslate(Vector3(-14, 56, 28)); - track->createNodeKeyFrame(14)->setTranslate(Vector3(0, 35, 84)); - track->createNodeKeyFrame(16)->setTranslate(Vector3(14, 35, 14)); - track->createNodeKeyFrame(18)->setTranslate(Vector3(35, 84, 0)); - track->createNodeKeyFrame(20)->setTranslate(Vector3(42, 77, -42)); - - lightNode->setPosition(track->getNodeKeyFrame(0)->getTranslate()); - - // create a new animation state to track this - mLightAnimState = mSceneMgr->createAnimationState("LightTrack"); - mLightAnimState->setEnabled(true); - } - - void waveGrass(Real timeElapsed) - { - static float xinc = Math::PI * 0.3; - static float zinc = Math::PI * 0.44; - static float xpos = Math::RangeRandom(-Math::PI, Math::PI); - static float zpos = Math::RangeRandom(-Math::PI, Math::PI); - static Vector4f offset(0); - - xpos += xinc * timeElapsed; - zpos += zinc * timeElapsed; - - // update vertex program parameters by binding a value to each renderable - for (const auto& reg : mField->getRegions()) - { - // a little randomness - xpos += reg.second->getCentre().x * 0.001; - zpos += reg.second->getCentre().z * 0.001; - offset[0] = std::sin(xpos) * 4; - offset[2] = std::sin(zpos) * 4; - - for (auto lod : reg.second->getLODBuckets()) - { - for (const auto& mb : lod->getMaterialBuckets()) - { - for (auto geom : mb.second->getGeometryList()) - geom->setCustomParameter(999, offset); - } - } - } - } - - void checkBoxToggled(CheckBox* box) override - { - auto mat = MaterialManager::getSingleton().getByName(box->isChecked() ? "Examples/GrassBladesWaver" - : "Examples/GrassBlades"); - for (const auto& reg : mField->getRegions()) - { - for (auto lod : reg.second->getLODBuckets()) - { - for (const auto& mb : lod->getMaterialBuckets()) - { - mb.second->_setMaterial(mat); - } - } - } - } - - void cleanupContent() override - { - ControllerManager::getSingleton().destroyController(mLightController); - MeshManager::getSingleton().remove("ground", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - MeshManager::getSingleton().remove("grass", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - } - - StaticGeometry* mField; - AnimationState* mLightAnimState; - ControllerFloat* mLightController; -}; - -#endif diff --git a/Samples/Simple/include/Hair.h b/Samples/Simple/include/Hair.h deleted file mode 100644 index b7d21a15938..00000000000 --- a/Samples/Simple/include/Hair.h +++ /dev/null @@ -1,320 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2013 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#ifndef __Hair_H__ -#define __Hair_H__ - -#include "SdkSample.h" -#include "OgreImage.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_Hair : public SdkSample -{ -public: - - Sample_Hair() - { - mInfo["Title"] = "Hair"; - mInfo["Description"] = "Sample for terrain, water tessellation and the use of displacement mapping"; - mInfo["Thumbnail"] = "thumb_tesselation.png"; - mInfo["Category"] = "Unsorted"; - mInfo["Help"] = "Top Left: Multi-frame\nTop Right: Scrolling\nBottom Left: Rotation\nBottom Right: Scaling"; - } - - void testCapabilities(const RenderSystemCapabilities* caps) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "This sample is not yet finished." - " Sorry!", "Sample_Hair::testCapabilities"); - - if (!caps->hasCapability(RSC_TESSELLATION_HULL_PROGRAM) || !caps->hasCapability(RSC_TESSELLATION_DOMAIN_PROGRAM)) - { - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Your graphics card does not support tesselation shaders. Sorry!", - "Sample_Hair:testCapabilities"); - } - if (!GpuProgramManager::getSingleton().isSyntaxSupported("vs_5_0") && - !GpuProgramManager::getSingleton().isSyntaxSupported("hs_5_0") && - !GpuProgramManager::getSingleton().isSyntaxSupported("ds_5_0") && - !GpuProgramManager::getSingleton().isSyntaxSupported("ps_5_0") && - !GpuProgramManager::getSingleton().isSyntaxSupported("hlsl")) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Your card does not support the shader model 5.0 needed for this sample, " - "so you cannot run this sample. Sorry!", "Sample_Hair::testCapabilities"); - } - } - - bool frameRenderingQueued(const FrameEvent& evt) - { - return SdkSample::frameRenderingQueued(evt); // don't forget the parent class updates! - } - - void checkBoxToggled(CheckBox* box) - { - if (box->getName() == "Wire") - { - if( mCamera->getPolygonMode() == PM_WIREFRAME ) - mCamera->setPolygonMode(PM_SOLID); - else - mCamera->setPolygonMode(PM_WIREFRAME); - } - if (box->getName() == "PlayAnimation") - { - mPlayAnimation = !mPlayAnimation; - } - if (box->getName() == "LoopAnimation") - { - mLoopAnimation = !mLoopAnimation; - } - if (box->getName() == "ShortHair") - { - mShortHair = !mShortHair; - // change mesh / model - } - if (box->getName() == "CurlyHair") - { - mCurlyHair = !mCurlyHair; - // change mesh / model - } - if (box->getName() == "Shadows") - { - mShadows = !mShadows; - // render or not shadows / using Ogre shadows. - } - if (box->getName() == "RenderMStrands") - { - mRenderMStrands = !mRenderMStrands; - - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( "Hair" ).staticCast(); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_RenderMStrands", mRenderMStrands ); - } - if (box->getName() == "RenderSStrands") - { - mRenderSStrands = !mRenderSStrands; - - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( "Hair" ).staticCast(); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_RenderSStrands", mRenderSStrands ); - } - if (box->getName() == "HWTessellation") - { - mHWTessellation = !mHWTessellation; - - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( "Hair" ).staticCast(); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_HWTessellation", mHWTessellation ); - } - if (box->getName() == "DynamicLOD" && mHWTessellation) - { - mDynamicLOD = !mDynamicLOD; - - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( "Hair" ).staticCast(); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_DynamicLOD", mDynamicLOD ); - } - if (box->getName() == "WindForce") - { - mAddWindForce = !mAddWindForce; - } - if (box->getName() == "ComputeShader") - { - mComputeShader = !mComputeShader; - } - if (box->getName() == "SimulationLOD") - { - mSimulationLOD = !mSimulationLOD; - } - if (box->getName() == "Simulate") - { - mSimulate = !mSimulate; - } - if (box->getName() == "ShowCollision") - { - mShowCollision = !mShowCollision; - } - if (box->getName() == "ShowScene") - { - mShowScene = !mShowScene; - } - } - - void sliderMoved(Slider* slider) - { - if (slider->getName() == "tessellationLOD") - if (!mDynamicLOD && mHWTessellation) - { - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( "Hair" ).staticCast(); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_ManualLOD", slider->getValue() ); - } - if (slider->getName() == "HairWidth") - if (!mDynamicLOD && mHWTessellation) - { - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( "Hair" ).staticCast(); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_HairWidth", slider->getValue() ); - } - if (slider->getName()=="LODRate") - { - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( "Hair" ).staticCast(); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_LODRate", slider->getValue() ); - } - if (slider->getName()=="WindStrength") - if (mAddWindForce) - { - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( "Hair" ).staticCast(); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_WindStrength", slider->getValue() ); - } - } - -protected: - - void setupContent() - { - // create our main node to attach our entities to - mObjectNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - mSceneMgr->setSkyBox(true, "Examples/SpaceSkyBox", 5000); // set our skybox - - setupModels(); - setupLights(); - setupControls(); - - // set our camera - mCamera->setFOVy(Ogre::Degree(50.0)); - mCamera->setFOVy(Ogre::Degree(50.0)); - mCamera->setNearClipDistance(0.01f); - mCamera->lookAt(Ogre::Vector3::ZERO); - mCameraNode->setPosition(0, 0, 500); - - - // Set our camera to orbit around the origin at a suitable distance - mCameraMan->setStyle(CS_ORBIT); - mCameraMan->setYawPitchDist(Radian(0), Radian(0), 400); - - mTrayMgr->showCursor(); - } - - void unloadResources() - { - - } - - void setupModels() - { - - } - - void setupLights() - { - mSceneMgr->setAmbientLight(ColourValue::Black); - mViewport->setBackgroundColour(ColourValue(0.41f, 0.41f, 0.41f)); - } - - void setupControls() - { - mTrayMgr->showCursor(); - - // make room for the controls - mTrayMgr->showLogo(TL_TOPRIGHT); - mTrayMgr->showFrameStats(TL_TOPRIGHT); - mTrayMgr->toggleAdvancedFrameStats(); - - mTrayMgr->createCheckBox(TL_TOPLEFT, "Wire", "Render Wire Frame")->setChecked(false, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "PlayAnimation", "Play Animation")->setChecked(false, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "LoopAnimation", "Loop Animation")->setChecked(false, false); - - // create a menu to choose the model displayed - mMeshMenu = mTrayMgr->createLongSelectMenu(TL_LEFT, "Mesh", "Mesh", 370, 290, 10); - for (std::map::iterator it = mPossibilities.begin(); it != mPossibilities.end(); it++) - mMeshMenu->addItem(it->first); - - mTrayMgr->createCheckBox(TL_TOPLEFT, "ShortHair", "Short Hair")->setChecked(false, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "CurlyHair", "Curly Hair")->setChecked(false, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "Shadows", "Shadows")->setChecked(true, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "RenderMStrands", "Render M strands")->setChecked(true, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "RenderSStrands", "Render S strands")->setChecked(true, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "HWTessellation", "HW Tessellation")->setChecked(true, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "DynamicLOD", "Dynamic LOD")->setChecked(true, false); - - mManualLOD = mTrayMgr->createThickSlider(TL_TOPLEFT, "tessellationLOD", "Manual tessellation LOD", 200, 40, 1, 50, 50); - mManualLOD->show(); - - mHairWidth = mTrayMgr->createThickSlider(TL_TOPLEFT, "HairWidth", "Hair Width", 200, 40, 1, 100, 100); - mHairWidth->show(); - - mLODRate = mTrayMgr->createThickSlider(TL_TOPLEFT, "LODRate", "LOD Rate", 200, 40, 1, 100, 100); - mLODRate->show(); - - mTrayMgr->createCheckBox(TL_TOPLEFT, "WindForce", "Add wind force")->setChecked(true, false); - - mWindStrength = mTrayMgr->createThickSlider(TL_TOPLEFT, "WindStrength", "Wind Strength", 200, 40, 0.01, 0.25, 25); - mWindStrength->show(); - - mTrayMgr->createCheckBox(TL_TOPLEFT, "ComputeShader", "Compute Shader")->setChecked(true, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "SimulationLOD", "SimulationLOD")->setChecked(true, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "Simulate", "Simulate")->setChecked(true, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "ShowCollision", "Show Collision")->setChecked(false, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "ShowScene", "Show Scene")->setChecked(true, false); - - // a friendly reminder - StringVector names; - names.push_back("Help"); - mTrayMgr->createParamsPanel(TL_TOPLEFT, "Help", 100, names)->setParamValue(0, "H/F1"); - - mPlayAnimation = false; - mLoopAnimation = false; - mShortHair = false; - mCurlyHair = false; - mShadows = true; - mRenderMStrands = true; - mRenderSStrands = true; - mHWTessellation = true; - mDynamicLOD = true; - mAddWindForce = true; - mComputeShader = true; - mSimulationLOD = true; - mSimulate = true; - mShowCollision = false; - mShowScene = true; - } - - void cleanupContent() - { - // clean up properly to avoid interfering with subsequent samples - } - - SelectMenu* mMeshMenu; - SceneNode* mObjectNode; - bool mPlayAnimation; - bool mLoopAnimation; - - SelectMenu* mColorMenu; - std::map mPossibilities; - - bool mShortHair; - bool mCurlyHair; - bool mShadows; - bool mRenderMStrands; - bool mRenderSStrands; - bool mHWTessellation; - bool mDynamicLOD; - Slider* mManualLOD; - Slider* mHairWidth; - Slider* mLODRate; - bool mAddWindForce; - Slider* mWindStrength; - bool mComputeShader; - bool mSimulationLOD; - bool mSimulate; - bool mShowCollision; - bool mShowScene; -}; - -#endif \ No newline at end of file diff --git a/Samples/Simple/include/ImGuiDemo.h b/Samples/Simple/include/ImGuiDemo.h deleted file mode 100644 index 5d9eeafae13..00000000000 --- a/Samples/Simple/include/ImGuiDemo.h +++ /dev/null @@ -1,85 +0,0 @@ -#pragma once - -#include "SdkSample.h" -#include "OgreImGuiOverlay.h" -#include - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_ImGui : public SdkSample, public RenderTargetListener -{ - std::unique_ptr mImguiListener; - InputListenerChain mListenerChain; -public: - // Basic constructor - Sample_ImGui() - { - mInfo["Title"] = "Dear ImGui integration"; - mInfo["Description"] = "Overlay ImGui interactions"; - mInfo["Category"] = "Unsorted"; - mInfo["Thumbnail"] = "thumb_imgui.png"; - } - - void preViewportUpdate(const RenderTargetViewportEvent& evt) override - { - if(!evt.source->getOverlaysEnabled()) return; - if(!mTrayMgr->getTraysLayer()->isVisible()) return; - - ImGuiOverlay::NewFrame(); - - ImGui::ShowDemoWindow(); - } - - bool keyPressed(const KeyboardEvent& evt) override { return mListenerChain.keyPressed(evt); } - bool keyReleased(const KeyboardEvent& evt) override { return mListenerChain.keyReleased(evt); } - bool mouseMoved(const MouseMotionEvent& evt) override { return mListenerChain.mouseMoved(evt); } - bool mouseWheelRolled(const MouseWheelEvent& evt) override { return mListenerChain.mouseWheelRolled(evt); } - bool mousePressed(const MouseButtonEvent& evt) override { return mListenerChain.mousePressed(evt); } - bool mouseReleased(const MouseButtonEvent& evt) override { return mListenerChain.mouseReleased(evt); } - bool textInput (const TextInputEvent& evt) override { return mListenerChain.textInput (evt); } - - void setupContent(void) override - { - auto imguiOverlay = new ImGuiOverlay(); - - // handle DPI scaling - float vpScale = OverlayManager::getSingleton().getPixelRatio(); - ImGui::GetIO().FontGlobalScale = std::round(vpScale); // default font does not work with fractional scaling - ImGui::GetStyle().ScaleAllSizes(vpScale); - - imguiOverlay->setZOrder(300); - imguiOverlay->show(); - OverlayManager::getSingleton().addOverlay(imguiOverlay); // now owned by overlaymgr - - /* - NOTE: - Custom apps will ASSERT on ImGuiOverlay::NewFrame() and not display any UI if they - have not registered the overlay system by calling mSceneMgr->addRenderQueueListener(mOverlaySystem). - OgreBites::SampleBrowser does this on behalf of the ImGuiDemo but custom applications will need to - call this themselves. See ApplicationContextBase::createDummyScene(). - */ - mWindow->addListener(this); - - mImguiListener.reset(new ImGuiInputListener()); - mListenerChain = InputListenerChain({mTrayMgr.get(), mImguiListener.get(), mCameraMan.get()}); - - mTrayMgr->showCursor(); - mCameraMan->setStyle(OgreBites::CS_ORBIT); - mCameraMan->setYawPitchDist(Degree(0), Degree(0), 15); - - SceneNode* lightNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - lightNode->setPosition(0, 10, 15); - lightNode->attachObject(mSceneMgr->createLight("MainLight")); - - Entity* ent = mSceneMgr->createEntity("Sinbad.mesh"); - SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - node->attachObject(ent); - } - - void cleanupContent() override - { - OverlayManager::getSingleton().destroy("ImGuiOverlay"); - mWindow->removeListener(this); - } -}; diff --git a/Samples/Simple/include/Island.h b/Samples/Simple/include/Island.h deleted file mode 100644 index c7bd99ddc09..00000000000 --- a/Samples/Simple/include/Island.h +++ /dev/null @@ -1,181 +0,0 @@ -#ifndef __Island_H__ -#define __Island_H__ - -#include "SdkSample.h" -#include "OgreImage.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_Island : public SdkSample -{ -public: - - Sample_Island() - { - mInfo["Title"] = "Island"; - mInfo["Description"] = "Sample for terrain, water tessellation and the use of displacement mapping"; - mInfo["Thumbnail"] = "thumb_tesselation.png"; - mInfo["Category"] = "Unsorted"; - mInfo["Help"] = "Top Left: Multi-frame\nTop Right: Scrolling\nBottom Left: Rotation\nBottom Right: Scaling"; - } - - void testCapabilities(const RenderSystemCapabilities* caps) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "This sample is not yet finished." - " Sorry!", "Sample_Island::testCapabilities"); - if (!caps->hasCapability(RSC_TESSELLATION_HULL_PROGRAM) || !caps->hasCapability(RSC_TESSELLATION_DOMAIN_PROGRAM)) - { - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Your graphics card does not support tesselation shaders. Sorry!", - "Sample_Island:testCapabilities"); - } - if (!GpuProgramManager::getSingleton().isSyntaxSupported("vs_5_0") && - !GpuProgramManager::getSingleton().isSyntaxSupported("hs_5_0") && - !GpuProgramManager::getSingleton().isSyntaxSupported("ds_5_0") && - !GpuProgramManager::getSingleton().isSyntaxSupported("ps_5_0") && - !GpuProgramManager::getSingleton().isSyntaxSupported("hlsl")) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Your card does not support the shader model 5.0 needed for this sample, " - "so you cannot run this sample. Sorry!", "Sample_Island::testCapabilities"); - } - } - - bool frameRenderingQueued(const FrameEvent& evt) - { - return SdkSample::frameRenderingQueued(evt); // don't forget the parent class updates! - } - - void checkBoxToggled(CheckBox* box) - { - if (box->getName() == "Wire") - { - if( mCamera->getPolygonMode() == PM_WIREFRAME ) - mCamera->setPolygonMode(PM_SOLID); - else - mCamera->setPolygonMode(PM_WIREFRAME); - } - if (box->getName() == "Tessellation") - { - g_UseDynamicLOD = !g_UseDynamicLOD; - - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( "Island" ).staticCast(); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_UseDynamicLOD", g_UseDynamicLOD ); - } - if (box->getName() == "FrustumCull") - { - g_FrustumCullInHS = !g_FrustumCullInHS; - - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( "Island" ).staticCast(); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_FrustumCullInHS", g_FrustumCullInHS ); - } - if (box->getName() == "RenderRefraction") - { - g_RenderCaustics = !g_RenderCaustics; - - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( "Island" ).staticCast(); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_RenderCaustics", g_RenderCaustics ); - } - } - - void sliderMoved(Slider* slider) - { - if (slider->getName() == "tessellationLOD") - { - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( "Island" ).staticCast(); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_DynamicTessFactor", slider->getValue() ); - } - if (slider->getName() == "tessellationFactor") - { - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( "Island" ).staticCast(); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_StaticTessFactor", slider->getValue() ); - } - } - -protected: - - void setupContent() - { - // create our main node to attach our entities to - mObjectNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - mSceneMgr->setSkyBox(true, "Examples/SpaceSkyBox", 5000); // set our skybox - - setupModels(); - setupLights(); - setupControls(); - - // set our camera - mCamera->setFOVy(Ogre::Degree(50.0)); - mCamera->setFOVy(Ogre::Degree(50.0)); - mCamera->setNearClipDistance(0.01f); - mCamera->lookAt(Ogre::Vector3::ZERO); - mCameraNode->setPosition(0, 0, 500); - - - // Set our camera to orbit around the origin at a suitable distance - mCameraMan->setStyle(CS_ORBIT); - mCameraMan->setYawPitchDist(Radian(0), Radian(0), 400); - - mTrayMgr->showCursor(); - } - - void unloadResources() - { - - } - - void setupModels() - { - - } - - void setupLights() - { - mSceneMgr->setAmbientLight(ColourValue::Black); - mViewport->setBackgroundColour(ColourValue(0.41f, 0.41f, 0.41f)); - } - - void setupControls() - { - mTrayMgr->showCursor(); - - // make room for the controls - mTrayMgr->showLogo(TL_TOPRIGHT); - mTrayMgr->showFrameStats(TL_TOPRIGHT); - mTrayMgr->toggleAdvancedFrameStats(); - - mTrayMgr->createCheckBox(TL_TOPLEFT, "Wire", "Render Wire Frame")->setChecked(false, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "Tessellation", "Use Dynamic Tessellation LOD")->setChecked(true, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "FrustumCull", "Use Frustum Cull in HS")->setChecked(true, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "RenderRefraction", "Render Refraction Caustics")->setChecked(true, false); - - mTessellationLOD = mTrayMgr->createThickSlider(TL_TOPLEFT, "tessellationLOD", "Dynamic tessellation LOD", 200, 40, 1, 100, 100); - mTessellationLOD->show(); - - mTessellationFactor = mTrayMgr->createThickSlider(TL_TOPLEFT, "tessellationFactor", "Static tessellation factor", 200, 40, 1, 64, 64); - mTessellationFactor->show(); - - // a friendly reminder - StringVector names; - names.push_back("Help"); - mTrayMgr->createParamsPanel(TL_TOPLEFT, "Help", 100, names)->setParamValue(0, "H/F1"); - - g_UseDynamicLOD = true; - g_FrustumCullInHS = true; - g_RenderCaustics = true; - } - - void cleanupContent() - { - // clean up properly to avoid interfering with subsequent samples - } - - SceneNode* mObjectNode; - Slider* mTessellationLOD; - Slider* mTessellationFactor; - bool g_UseDynamicLOD; - bool g_FrustumCullInHS; - bool g_RenderCaustics; -}; - -#endif \ No newline at end of file diff --git a/Samples/Simple/include/LightShafts.h b/Samples/Simple/include/LightShafts.h deleted file mode 100644 index 6226b9b574b..00000000000 --- a/Samples/Simple/include/LightShafts.h +++ /dev/null @@ -1,230 +0,0 @@ -#pragma once - -#include "SdkSample.h" -#include "OgreBillboard.h" - -using namespace Ogre; -using namespace OgreBites; - -// Main light billboard set -BillboardSet* mBillboardSet = 0; -// Camera used for rendering the shadow map and as light frustum -Camera* mLightCamera = 0; -// Light camera scene node -SceneNode* mLightCameraSN = 0; - -// Knot scene node -SceneNode* mKnotSN = 0; - -// Current cookie selected -int mCurrentCookie = 0; - -class _OgreSampleClassExport Sample_LightShafts : public SdkSample -{ - bool mRotateEnable; - bool mRotateKnot; - - MaterialPtr mLightShaftsMat; - -public: - // Basic constructor - Sample_LightShafts() : mRotateEnable(false), mRotateKnot(true) - { - mInfo["Title"] = "Light Shafts"; - mInfo["Description"] = "Demonstrates volumetric light shafts"; - mInfo["Category"] = "Lighting"; - mInfo["Thumbnail"] = "thumb_lightshafts.png"; - mInfo["Help"] = "Controls:\n" - "C - Show/Hide light frustum\n" - "V - Enable/Disable light rotation\n" - "B - Enable/Disable knot rotation\n" - "N - Change light cookie"; - } - - bool frameStarted(const FrameEvent& e) override - { - // Update light position - updatePosition(e); - - return SdkSample::frameStarted(e); - } - - bool keyPressed(const OgreBites::KeyboardEvent& evt) override - { - switch (evt.keysym.sym) - { - case 'c': - mLightCamera->setVisible(!mLightCamera->getVisible()); - break; - case 'v': - mRotateEnable = !mRotateEnable; - break; - case 'b': - mRotateKnot = !mRotateKnot; - break; - case 'n': - mCurrentCookie = (mCurrentCookie + 1) % 4; - mLightShaftsMat->getTechnique(0)->getPass(0)->getTextureUnitState(1)->setTextureName( - StringUtil::format("Cookie%d.png", mCurrentCookie)); - break; - } - return SdkSample::keyPressed(evt); - } - - void updatePosition(const FrameEvent& e) - { - // Just a simple circular trajectory - const Real& SimulationTime = Root::getSingleton().getTimer()->getMilliseconds(); - Real Radius = 8; - - if (!mRotateEnable) - { - Radius = 0; - } - - mLightCameraSN->setPosition(Math::Sin(SimulationTime / 1000) * Radius, - mLightCameraSN->getPosition().y, - Math::Cos(SimulationTime / 1000) * Radius); - - // Set the the scene node direction to 0,KnotHeight,0 point - Vector3 NormalisedDirection = - (Vector3(0, mKnotSN->getPosition().y, 0) - mLightCameraSN->getPosition()).normalisedCopy(); - mLightCameraSN->setDirection(NormalisedDirection, Node::TS_WORLD); - - if (mRotateKnot) - { - mKnotSN->setOrientation(Quaternion( - Degree(Root::getSingleton().getTimer()->getMilliseconds() / 50), Vector3(0, 1, 0))); - } - } - - void setupContent(void) override - { -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - // Make this viewport work with shader generator scheme. - mViewport->setMaterialScheme(MSN_SHADERGEN); - RTShader::ShaderGenerator& rtShaderGen = RTShader::ShaderGenerator::getSingleton(); - RTShader::RenderState* schemRenderState = rtShaderGen.getRenderState(MSN_SHADERGEN); - RTShader::SubRenderState* subRenderState = rtShaderGen.createSubRenderState("SGX_IntegratedPSSM3"); - schemRenderState->addTemplateSubRenderState(subRenderState); -#endif - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE_INTEGRATED); - mSceneMgr->setShadowTextureSettings(256, 1, PF_FLOAT32_R); - mSceneMgr->setShadowTextureSelfShadow( true ); - mSceneMgr->setShadowTextureCasterMaterial(MaterialManager::getSingleton().getByName("PSSM/shadow_caster")); - - auto statusPanel = mTrayMgr->createParamsPanel(TL_TOPLEFT, "HelpMessage", 200, {"Help"}); - statusPanel->setParamValue("Help", "H / F1"); - - mCameraMan->setStyle(OgreBites::CS_ORBIT); - mCameraMan->setYawPitchDist(Degree(0), Degree(15), 30); - - mTrayMgr->showCursor(); - - // Set some camera params - mCamera->setNearClipDistance(1); - - // add a little ambient lighting - mSceneMgr->setAmbientLight(ColourValue(0.1, 0.1, 0.1)); - - // Set up light 0 - Light* mLight0 = mSceneMgr->createLight(Light::LT_SPOTLIGHT); - mLight0->setDiffuseColour(0.9, 0.9, 0.9); - mLight0->setSpecularColour(1, 1, 1); - mLight0->setSpotlightRange(Degree(17.5f), Degree(22.5f)); - mLight0->setShadowNearClipDistance(8); - mLight0->setShadowFarClipDistance(48); - mLight0->setAttenuation(48, 1.0, 0, 0.001); - - mLightShaftsMat = MaterialManager::getSingleton().getByName("LightShafts"); - - // Set up our light camera - - mLightCameraSN = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mLightCameraSN->setPosition(0, 20, 0); - mLightCameraSN->setDirection(0, -1, 0); - - mLightCameraSN->attachObject(mLight0); - - // Create our billboardset for volumetric rendering - mBillboardSet = mSceneMgr->createBillboardSet("LightBillboardSet", 1); - mBillboardSet->setMaterial(mLightShaftsMat); - mBillboardSet->setBillboardRotationType(BBR_VERTEX); - mBillboardSet->setCastShadows(false); - mLightCameraSN->attachObject(mBillboardSet); - - getLightCamera(); - - // Create a rush of billboards according to the frustum of the camera(mLightCamera) - // After it, we can use the lightcamera/billboards scenenode like a light projector - createLightShafts(mBillboardSet, mLightCamera, 100); - - // Set a floor plane - MeshManager::getSingleton().createPlane("FloorPlaneMesh", RGN_DEFAULT, Plane(Vector3::UNIT_Y, 0), - 250, 250, 100, 100, true, 1, 15, 15, Vector3::UNIT_Z); - - Entity* pPlaneEnt = mSceneMgr->createEntity("Plane", "FloorPlaneMesh"); - pPlaneEnt->setMaterialName("Examples/Rockwall"); - pPlaneEnt->setCastShadows(false); - SceneNode* pPlaneNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - pPlaneNode->attachObject(pPlaneEnt); - pPlaneNode->setPosition(0, -20, 0); - - // Set a knot - Entity* mKnot = mSceneMgr->createEntity("Knot", "knot.mesh"); - mKnotSN = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mKnotSN->attachObject(mKnot); - mKnotSN->setScale(0.0225, 0.0225, 0.0225); - } - - bool createLightShafts(BillboardSet* billboard, Camera* LightCamera, const int& NumberOfPlanes) - { - mViewport->update(); // make sure LightCamera is synced to scene settings - - // Calculate the distance between planes - float DistanceBetweenPlanes = - (LightCamera->getFarClipDistance() - LightCamera->getNearClipDistance()) / NumberOfPlanes; - - // Get frustum corners to calculate near/far planes dimensions - const Vector3* FrustumCorners = LightCamera->getWorldSpaceCorners(); - - // Calcule near and far planes dimensions - float NearWidth = (FrustumCorners[0] - FrustumCorners[1]).length(), - NearHeigth = (FrustumCorners[1] - FrustumCorners[2]).length(), - FarWidth = (FrustumCorners[4] - FrustumCorners[5]).length(), - FarHeigth = (FrustumCorners[5] - FrustumCorners[6]).length(); - - // Now width/heigth setp - float WidthStep = (FarWidth - NearWidth) / NumberOfPlanes, - HeigthStep = (FarHeigth - NearHeigth) / NumberOfPlanes; - - // Add billboards - Billboard* CurrentBB = 0; - for (int k = 0; k < NumberOfPlanes; k++) - { - CurrentBB = billboard->createBillboard( - Vector3(0, 0, -LightCamera->getNearClipDistance() - k * DistanceBetweenPlanes), - ColourValue::White); - CurrentBB->setDimensions(NearWidth + k * WidthStep, NearHeigth + k * HeigthStep); - } - - return true; - } - - void getLightCamera() - { - // Create a texture for use as rtt - TexturePtr LightCameraRTT = mSceneMgr->getShadowTexture(0); - RenderTarget* RT_Texture = LightCameraRTT->getBuffer()->getRenderTarget(); - - Viewport* RT_Texture_Viewport = RT_Texture->getViewport(0); - mLightCamera = RT_Texture_Viewport->getCamera(); - - mLightCamera->setDebugDisplayEnabled(true); - } - - void cleanupContent() override - { - MeshManager::getSingleton().remove("FloorPlaneMesh", RGN_DEFAULT); - } -}; diff --git a/Samples/Simple/include/Lighting.h b/Samples/Simple/include/Lighting.h deleted file mode 100644 index 853045fbf3b..00000000000 --- a/Samples/Simple/include/Lighting.h +++ /dev/null @@ -1,354 +0,0 @@ -#ifndef __Lighting_H__ -#define __Lighting_H__ - -#include "SdkSample.h" -#include "OgreBillboard.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_Lighting : public SdkSample, public RenderObjectListener -{ - static const uint8 cPriorityMain = 50; - static const uint8 cPriorityQuery = 51; - static const uint8 cPriorityLights = 55; - -public: - - Sample_Lighting() : - mLight1BBFlare(NULL), - mLight1BBQueryArea(NULL), - mLight1BBQueryVisible(NULL), - mLight2BBFlare(NULL), - mLight2BBQueryArea(NULL), - mLight2BBQueryVisible(NULL), - mLight1QueryArea(NULL), - mLight1QueryVisible(NULL), - mLight2QueryArea(NULL), - mLight2QueryVisible(NULL), - mActiveQuery(NULL), - mUseOcclusionQuery(false), - mDoOcclusionQuery(false) - - { - mInfo["Title"] = "Lighting"; - mInfo["Description"] = "Shows OGRE's lighting support. Also demonstrates " - "usage of occlusion queries and automatic time-relative behaviour " - "using billboards and controllers."; - mInfo["Thumbnail"] = "thumb_lighting.png"; - mInfo["Category"] = "Lighting"; - } - - bool frameRenderingQueued(const FrameEvent& evt) override - { - // Modulate the light flare according to performed occlusion queries - if (mUseOcclusionQuery) - { - // Stop occlusion queries until we get their information - // (may not happen on the same frame they are requested in) - mDoOcclusionQuery = false; - - // Check if all query information available - if ((mLight1QueryArea->isStillOutstanding() == false) && - (mLight1QueryVisible->isStillOutstanding() == false) && - (mLight2QueryArea->isStillOutstanding() == false) && - (mLight2QueryVisible->isStillOutstanding() == false)) - { - // Modulate the lights according to the query data - unsigned int lightAreaCount; - unsigned int lightVisibleCount; - float ratio; - - mLight1QueryArea->pullOcclusionQuery(&lightAreaCount); - mLight1QueryVisible->pullOcclusionQuery(&lightVisibleCount); - ratio = float(lightVisibleCount) / float(lightAreaCount); - mLight1BBFlare->setColour(mTrail->getInitialColour(0) * ratio); - - mLight2QueryArea->pullOcclusionQuery(&lightAreaCount); - mLight2QueryVisible->pullOcclusionQuery(&lightVisibleCount); - ratio = float(lightVisibleCount) / float(lightAreaCount); - mLight2BBFlare->setColour(mTrail->getInitialColour(1) * ratio); - - // Request new query data - mDoOcclusionQuery = true; - } - } - - - return SdkSample::frameRenderingQueued(evt); // don't forget the parent class updates! - } - -protected: - - void setupContent() override - { - // Set our camera to orbit around the origin at a suitable distance - mCameraMan->setStyle(CS_ORBIT); - mCameraMan->setYawPitchDist(Radian(0), Radian(0), 400); - - mTrayMgr->showCursor(); - - // Create an ogre head and place it at the origin - Entity* head = mSceneMgr->createEntity("Head", "ogrehead.mesh"); - head->setRenderQueueGroup(cPriorityMain); - mSceneMgr->getRootSceneNode()->attachObject(head); - - setupLights(); - } - - void setupLights() - { - - mSceneMgr->setAmbientLight(ColourValue(0.1, 0.1, 0.1)); // Dim ambient lighting - - // Create a ribbon trail that our lights will leave behind - NameValuePairList params; - params["numberOfChains"] = "2"; - params["maxElements"] = "80"; - mTrail = (RibbonTrail*)mSceneMgr->createMovableObject("RibbonTrail", ¶ms); - mSceneMgr->getRootSceneNode()->attachObject(mTrail); - mTrail->setMaterialName("Examples/LightRibbonTrail"); - mTrail->setTrailLength(400); - mTrail->setRenderQueueGroup(cPriorityLights); - - // Create the occlusion queries to be used in this sample - try { - RenderSystem* renderSystem = Ogre::Root::getSingleton().getRenderSystem(); - mLight1QueryArea = renderSystem->createHardwareOcclusionQuery(); - mLight1QueryVisible = renderSystem->createHardwareOcclusionQuery(); - mLight2QueryArea = renderSystem->createHardwareOcclusionQuery(); - mLight2QueryVisible = renderSystem->createHardwareOcclusionQuery(); - - mUseOcclusionQuery = (mLight1QueryArea != NULL) && - (mLight1QueryVisible != NULL) && - (mLight2QueryArea != NULL) && - (mLight2QueryVisible != NULL); - } - catch (Exception& e) - { - mUseOcclusionQuery = false; - } - - if (mUseOcclusionQuery == false) - { - LogManager::getSingleton().logError("Sample_Lighting - failed to create hardware occlusion query"); - } - - // Create the materials to be used by the objects used fo the occlusion query - MaterialPtr matBase = MaterialManager::getSingleton().getDefaultMaterial(false); - MaterialPtr matQueryArea = matBase->clone("QueryArea"); - matQueryArea->setDepthWriteEnabled(false); - matQueryArea->setColourWriteEnabled(false); - matQueryArea->setDepthCheckEnabled(false); // Not occluded by objects - MaterialPtr matQueryVisible = matBase->clone("QueryVisible"); - matQueryVisible->setDepthWriteEnabled(false); - matQueryVisible->setColourWriteEnabled(false); - matQueryVisible->setDepthCheckEnabled(true); // Occluded by objects - - SceneNode* node; - Animation* anim; - NodeAnimationTrack* track; - Light* light; - BillboardSet* bbs; - - // Create a light node - node = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(50, 30, 0)); - - // Create a 14 second animation with spline interpolation - anim = mSceneMgr->createAnimation("Path1", 14); - anim->setInterpolationMode(Animation::IM_SPLINE); - - track = anim->createNodeTrack(1, node); // Create a node track for our animation - - // Enter keyframes for our track to define a path for the light to follow - track->createNodeKeyFrame(0)->setTranslate(Vector3(50, 30, 0)); - track->createNodeKeyFrame(2)->setTranslate(Vector3(100, -30, 0)); - track->createNodeKeyFrame(4)->setTranslate(Vector3(120, -80, 150)); - track->createNodeKeyFrame(6)->setTranslate(Vector3(30, -80, 50)); - track->createNodeKeyFrame(8)->setTranslate(Vector3(-50, 30, -50)); - track->createNodeKeyFrame(10)->setTranslate(Vector3(-150, -20, -100)); - track->createNodeKeyFrame(12)->setTranslate(Vector3(-50, -30, 0)); - track->createNodeKeyFrame(14)->setTranslate(Vector3(50, 30, 0)); - - auto& controllerMgr = ControllerManager::getSingleton(); - // Create an animation state from the animation and enable it - auto animState = mSceneMgr->createAnimationState("Path1"); - animState->setEnabled(true); - controllerMgr.createFrameTimePassthroughController(AnimationStateControllerValue::create(animState, true)); - - // Set initial settings for the ribbon mTrail and add the light node - mTrail->setInitialColour(0, 1.0, 0.8, 0); - mTrail->setColourChange(0, 0.5, 0.5, 0.5, 0.5); - mTrail->setInitialWidth(0, 5); - mTrail->addNode(node); - - - // Attach a light with the same colour to the light node - light = mSceneMgr->createLight(); - light->setDiffuseColour(mTrail->getInitialColour(0)); - node->attachObject(light); - - // Attach a flare with the same colour to the light node - bbs = mSceneMgr->createBillboardSet(1); - mLight1BBFlare = bbs->createBillboard(Vector3::ZERO, mTrail->getInitialColour(0)); - bbs->setMaterialName("Examples/Flare"); - bbs->setRenderQueueGroup(cPriorityLights); - node->attachObject(bbs); - - if (mUseOcclusionQuery) - { - // Attach a billboard which will be used to get a relative area occupied by the light - mLight1BBQueryArea = mSceneMgr->createBillboardSet(1); - mLight1BBQueryArea->setDefaultDimensions(10,10); - mLight1BBQueryArea->createBillboard(Vector3::ZERO); - mLight1BBQueryArea->setMaterialName("QueryArea"); - mLight1BBQueryArea->setRenderQueueGroup(cPriorityQuery); - node->attachObject(mLight1BBQueryArea); - - // Attach a billboard which will be used to get the visible area occupied by the light - mLight1BBQueryVisible = mSceneMgr->createBillboardSet(1); - mLight1BBQueryVisible->setDefaultDimensions(10,10); - mLight1BBQueryVisible->createBillboard(Vector3::ZERO); - mLight1BBQueryVisible->setMaterialName("QueryVisible"); - mLight1BBQueryVisible->setRenderQueueGroup(cPriorityQuery); - node->attachObject(mLight1BBQueryVisible); - } - - // Create a second light node - node = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-50, 100, 0)); - - // Create a 10 second animation with spline interpolation - anim = mSceneMgr->createAnimation("Path2", 10); - anim->setInterpolationMode(Animation::IM_SPLINE); - - track = anim->createNodeTrack(1, node); // Create a node track for our animation - - // Enter keyframes for our track to define a path for the light to follow - track->createNodeKeyFrame(0)->setTranslate(Vector3(-50, 100, 0)); - track->createNodeKeyFrame(2)->setTranslate(Vector3(-100, 150, -30)); - track->createNodeKeyFrame(4)->setTranslate(Vector3(-200, 0, 40)); - track->createNodeKeyFrame(6)->setTranslate(Vector3(0, -150, 70)); - track->createNodeKeyFrame(8)->setTranslate(Vector3(50, 0, 30)); - track->createNodeKeyFrame(10)->setTranslate(Vector3(-50, 100, 0)); - - // Create an animation state from the animation and enable it - animState = mSceneMgr->createAnimationState("Path2"); - animState->setEnabled(true); - controllerMgr.createFrameTimePassthroughController(AnimationStateControllerValue::create(animState, true)); - - // Set initial settings for the ribbon mTrail and add the light node - mTrail->setInitialColour(1, 0.0, 1.0, 0.4); - mTrail->setColourChange(1, 0.5, 0.5, 0.5, 0.5); - mTrail->setInitialWidth(1, 5); - mTrail->addNode(node); - - // Attach a light with the same colour to the light node - light = mSceneMgr->createLight(); - light->setDiffuseColour(mTrail->getInitialColour(1)); - node->attachObject(light); - - // Attach a flare with the same colour to the light node - bbs = mSceneMgr->createBillboardSet(1); - mLight2BBFlare = bbs->createBillboard(Vector3::ZERO, mTrail->getInitialColour(1)); - bbs->setMaterialName("Examples/Flare"); - bbs->setRenderQueueGroup(cPriorityLights); - node->attachObject(bbs); - - if (mUseOcclusionQuery) - { - // Attach a billboard which will be used to get a relative area occupied by the light - mLight2BBQueryArea = mSceneMgr->createBillboardSet(1); - mLight2BBQueryArea->setDefaultDimensions(10,10); - mLight2BBQueryArea->createBillboard(Vector3::ZERO); - mLight2BBQueryArea->setMaterialName("QueryArea"); - mLight2BBQueryArea->setRenderQueueGroup(cPriorityQuery); - node->attachObject(mLight2BBQueryArea); - - // Attach a billboard which will be used to get the visible area occupied by the light - mLight2BBQueryVisible = mSceneMgr->createBillboardSet(1); - mLight2BBQueryVisible->setDefaultDimensions(10,10); - mLight2BBQueryVisible->createBillboard(Vector3::ZERO); - mLight2BBQueryVisible->setMaterialName("QueryVisible"); - mLight2BBQueryVisible->setRenderQueueGroup(cPriorityQuery); - node->attachObject(mLight2BBQueryVisible); - } - - // Setup the listener for the occlusion query - if (mUseOcclusionQuery) - { - mSceneMgr->addRenderObjectListener(this); - mDoOcclusionQuery = true; - } - } - - // Event raised when render single object started. - void notifyRenderSingleObject(Renderable* rend, const Pass* pass, const AutoParamDataSource* source, - const LightList* pLightList, bool suppressRenderStateChanges) override - { - // - // The following code activates and deactivates the occlusion queries - // so that the queries only include the rendering of their intended targets - // - - // Close the last occlusion query - // Each occlusion query should only last a single rendering - if (mActiveQuery != NULL) - { - mActiveQuery->endOcclusionQuery(); - mActiveQuery = NULL; - } - - // Open a new occlusion query - if (mDoOcclusionQuery == true) - { - // Check if a the object being rendered needs - // to be occlusion queried, and by which query instance. - if (rend == mLight1BBQueryArea) - mActiveQuery = mLight1QueryArea; - else if (rend == mLight1BBQueryVisible) - mActiveQuery = mLight1QueryVisible; - else if (rend == mLight2BBQueryArea) - mActiveQuery = mLight2QueryArea; - else if (rend == mLight2BBQueryVisible) - mActiveQuery = mLight2QueryVisible; - - if (mActiveQuery != NULL) - { - mActiveQuery->beginOcclusionQuery(); - } - } - } - - void cleanupContent() override - { - RenderSystem* renderSystem = Ogre::Root::getSingleton().getRenderSystem(); - if (mLight1QueryArea != NULL) - renderSystem->destroyHardwareOcclusionQuery(mLight1QueryArea); - if (mLight1QueryVisible != NULL) - renderSystem->destroyHardwareOcclusionQuery(mLight1QueryVisible); - if (mLight2QueryArea != NULL) - renderSystem->destroyHardwareOcclusionQuery(mLight2QueryArea); - if (mLight2QueryVisible != NULL) - renderSystem->destroyHardwareOcclusionQuery(mLight2QueryVisible); - } - - RibbonTrail* mTrail; - - Billboard* mLight1BBFlare; - BillboardSet* mLight1BBQueryArea; - BillboardSet* mLight1BBQueryVisible; - Billboard* mLight2BBFlare; - BillboardSet* mLight2BBQueryArea; - BillboardSet* mLight2BBQueryVisible; - - HardwareOcclusionQuery* mLight1QueryArea; - HardwareOcclusionQuery* mLight1QueryVisible; - HardwareOcclusionQuery* mLight2QueryArea; - HardwareOcclusionQuery* mLight2QueryVisible; - HardwareOcclusionQuery* mActiveQuery; - - bool mUseOcclusionQuery; - bool mDoOcclusionQuery; -}; - -#endif diff --git a/Samples/Simple/include/MeshLod.h b/Samples/Simple/include/MeshLod.h deleted file mode 100644 index 13d53633176..00000000000 --- a/Samples/Simple/include/MeshLod.h +++ /dev/null @@ -1,88 +0,0 @@ -#ifndef __MeshLod_H__ -#define __MeshLod_H__ - -#include "SamplePlugin.h" -#include "SdkSample.h" -#include "OgreLodConfig.h" -#include "OgreMeshLodGenerator.h" -#include "OgreLodWorkQueueInjectorListener.h" - -// To reduce checkboxes some developer features can be enabled with macros. -#define SHOW_MESH_HULL 0 -#define ENABLE_THREADING 1 -#define ENABLE_COMPRESSION 1 -#define PREVENT_HOLES_BREAKS 0 - -class _OgreSampleClassExport Sample_MeshLod : - public OgreBites::SdkSample, - public Ogre::LodWorkQueueInjectorListener -{ -public: - Sample_MeshLod(); -protected: - -// Events: - void setupContent() override; - void cleanupContent() override; - void setupControls(int uimode = 0); - void cleanupControls(); - bool frameStarted(const Ogre::FrameEvent& evt) override; - -// GUI input events: - void buttonHit(OgreBites::Button* button) override; - void sliderMoved(OgreBites::Slider* slider) override; - void itemSelected(OgreBites::SelectMenu* menu) override; - void checkBoxToggled(OgreBites::CheckBox * box) override; - -// Queued Lod injector events: - bool shouldInject(Ogre::LodWorkQueueRequest* request) override; - void injectionCompleted(Ogre::LodWorkQueueRequest* request) override; - -// Other functions: - void changeSelectedMesh(const Ogre::String& name); // Changes current mesh to a mesh with given mesh name. - bool loadConfig(); /// Loads the LodConfig with LodConfigSerializer for current mesh. - void saveConfig(); /// Saves the LodConfig with LodConfigSerializer for current mesh. - void loadUserLod(bool useWorkLod = true); /// Loads current Lod config. If useWorkLod is selected only current work Lod level will be shown. - void forceLodLevel(int lodLevelID, bool forceDelayed = true); /// Forces given Lod Level or -1 for disable forcing. - - void loadAutomaticLod(); /// Produces acceptable output on any kind of mesh. - - size_t getUniqueVertexCount(Ogre::MeshPtr mesh); /// Returns the unique vertex count of mesh. - bool getResourceFullPath(Ogre::MeshPtr& mesh, Ogre::String& outPath); /// Sets outPath to full resource file path. Returns true if location is writable. - - void addLodLevel(); /// Adds current work Lod level to the mesh Lod levels. - void loadLodLevel(int id); /// Loads the Lod levels with id to the work Lod level. - void removeLodLevel(); /// Removes currently selected Lod level. - void removeInitialLodLevel(); /// Removes Lod level #0 and unused vertices. - - void addToProfile(Ogre::Real cost); /// Add the currently reduced last vertex to the profile with given cost. - - void moveCameraToPixelDistance(Ogre::Real pixels); /// Moves camera to the swapping distance of PixelCountLodStrategy with given pixels. - Ogre::Real getCameraLODValue(); /// Returns the LOD value of mesh in pixels using the current camera - void recreateEntity(); - - -// Variables: - int mForcedLodLevel; /// Currently forced Lod level or -1 for disabled. - Ogre::LodLevel mWorkLevel; /// Current Lod Level, which we are seeing. - Ogre::LodConfig mLodConfig; /// Current LodConfig, which we are editing. - Ogre::Entity* mMeshEntity; /// Entity of the mesh. - Ogre::SceneNode* mMeshNode; /// Node of the mesh. -#if SHOW_MESH_HULL - Ogre::Entity* mHullEntity; /// Entity of the mesh hull. - Ogre::SceneNode* mHullNode; /// Node of the mesh hull. -#endif - -// GUI elements: - OgreBites::CheckBox* mUseVertexNormals; - OgreBites::CheckBox* mWireframe; - OgreBites::SelectMenu* mProfileList; - OgreBites::SelectMenu* mLodLevelList; - OgreBites::SelectMenu* mManualMeshes; - OgreBites::Slider* mReductionSlider; - OgreBites::Slider* mOutsideWeightSlider; - OgreBites::Slider* mOutsideWalkAngle; - OgreBites::Label* mDistanceLabel; -}; - -#endif diff --git a/Samples/Simple/include/NewInstancing.h b/Samples/Simple/include/NewInstancing.h deleted file mode 100644 index 0551a94865e..00000000000 --- a/Samples/Simple/include/NewInstancing.h +++ /dev/null @@ -1,101 +0,0 @@ -#ifndef __NewInstancing_H__ -#define __NewInstancing_H__ - -#include "SdkSample.h" -#include "OgreInstancedEntity.h" - -using namespace Ogre; -using namespace OgreBites; - -#define NUM_IM_TECHNIQUES (((int)InstanceManager::InstancingTechniquesCount) + 1) -#define NUM_TECHNIQUES (NUM_IM_TECHNIQUES + 2) - -class _OgreSampleClassExport Sample_NewInstancing : public SdkSample -{ -public: - - Sample_NewInstancing(); - - bool frameRenderingQueued(const FrameEvent& evt) override; - - bool keyPressed(const KeyboardEvent& evt) override; - - -protected: - void setupContent() override; - - void setupLighting(); - - void switchInstancingTechnique(); - - void switchSkinningTechnique(int index); - - void createEntities(int technique); - - void createInstancedEntities(); - - void createSceneNodes(); - - void clearScene(); - - void destroyManagers(); - - void cleanupContent() override; - - void animateUnits( float timeSinceLast ); - - void moveUnits( float timeSinceLast ); - - //Helper function to look towards normDir, where this vector is normalized, with fixed Yaw - Quaternion lookAt( const Vector3 &normDir ); - - void defragmentBatches(); - - void setupGUI(); - - void itemSelected(SelectMenu* menu) override; - - void buttonHit( OgreBites::Button* button ) override; - - void checkBoxToggled(CheckBox* box) override; - - void sliderMoved(Slider* slider) override; - - //The difference between testCapabilities() is that features checked here aren't fatal errors. - //which means the sample can run (with limited functionality) on those computers - void checkHardwareSupport(); - - //You can also use a union type to switch between Entity and InstancedEntity almost flawlessly: - /* - union FusionEntity - { - Entity entity - InstancedEntity instancedEntity; - }; - */ - int NUM_INST_ROW; - int NUM_INST_COLUMN; - int mInstancingTechnique; - int mCurrentMesh; - std::vector mEntities; - std::vector mMovedInstances; - std::vector mSceneNodes; - std::set mAnimations; - InstanceManager *mCurrentManager; - std::array mSupportedTechniques; - const char** mCurrentMaterialSet; - uint16 mCurrentFlags; - - SelectMenu *mTechniqueMenu; - CheckBox *mMoveInstances; - CheckBox *mAnimateInstances; - SelectMenu *mSkinningTechniques; - CheckBox *mEnableShadows; - CheckBox *mSetStatic; - CheckBox *mUseSceneNodes; - OgreBites::Button *mDefragmentBatches; - CheckBox *mDefragmentOptimumCull; - Slider *mInstancesSlider; -}; - -#endif diff --git a/Samples/Simple/include/PBR.h b/Samples/Simple/include/PBR.h deleted file mode 100644 index 3418a420cf6..00000000000 --- a/Samples/Simple/include/PBR.h +++ /dev/null @@ -1,98 +0,0 @@ -#ifndef __Sample_PBR_H__ -#define __Sample_PBR_H__ - -#include "SdkSample.h" -#include "SamplePlugin.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_PBR : public SdkSample -{ -public: - - Sample_PBR() - { - mInfo["Title"] = "Physically Based Rendering"; - mInfo["Description"] = "Shows how to do physically based rendering using a custom material"; - mInfo["Thumbnail"] = "thumb_pbr.png"; - mInfo["Category"] = "Lighting"; - } - -protected: - GpuProgramParametersSharedPtr mParams; - Entity* mEntity; - - void setupControls() - { - int gui_width = 250; - - SelectMenu* objectType = mTrayMgr->createThickSelectMenu(TL_TOPLEFT, "term", "Material", gui_width, 9); - objectType->addItem("glTF2 Shader"); - objectType->addItem("RTSS"); - if(GpuProgramManager::getSingleton().isSyntaxSupported("glsl330")) - objectType->addItem("Filament Shader"); - objectType->selectItem(0, false); - - mTrayMgr->createCheckBox(TL_TOPLEFT, "ibl", "Image Based Lighting", gui_width)->setChecked(true, false); - } - - void setupContent() override - { - // Make this viewport work with shader generator - mViewport->setMaterialScheme(MSN_SHADERGEN); - setupControls(); - - mCamera->setNearClipDistance(0.1); - mCameraMan->setStyle(CS_ORBIT); - mCameraMan->setYawPitchDist(Degree(-30), Degree(30), 3); - mTrayMgr->showCursor(); - - Light* light = mSceneMgr->createLight(); - light->setDiffuseColour(ColourValue::White); - light->setSpecularColour(ColourValue::White); - - mSceneMgr->getRootSceneNode() - ->createChildSceneNode(Vector3(4, 1, 6)) - ->attachObject(light); - - mEntity = mSceneMgr->createEntity("DamagedHelmet.mesh"); - - unsigned short src; - if (!mEntity->getMesh()->suggestTangentVectorBuildParams(src)) - { - // ensure that we have tangent vectors - mEntity->getMesh()->buildTangentVectors(src); - } - - SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - node->attachObject(mEntity); - - mViewport->setBackgroundColour(ColourValue(0.05, 0.05, 0.05)); - - MaterialPtr mat = MaterialManager::getSingleton().getByName("DamagedHelmet"); - mParams = mat->getTechnique(0)->getPass(0)->getFragmentProgramParameters(); - } - - void itemSelected(SelectMenu* menu) override - { - static const char* materials[] = {"DamagedHelmet", "DamagedHelmet_RTSS", "DamagedHelmet_Filament"}; - int n = menu->getSelectionIndex(); - - mEntity->setMaterialName(materials[n]); - } - - void checkBoxToggled(CheckBox* box) override - { - bool checked = box->isChecked(); - mParams->setNamedConstant("u_ScaleIBLAmbient", Vector4(float(checked))); - - using namespace RTShader; - MaterialPtr mat = MaterialManager::getSingleton().getByName("DamagedHelmet_RTSS"); - const auto& renderstate = any_cast( - mat->getTechnique(1)->getPass(0)->getUserObjectBindings().getUserAny(TargetRenderState::UserKey)); - renderstate->getSubRenderState(SRS_IMAGE_BASED_LIGHTING)->setParameter("luminance", checked ? "4" : "0"); - } -}; - -#endif diff --git a/Samples/Simple/include/PNTrianglesTessellation.h b/Samples/Simple/include/PNTrianglesTessellation.h deleted file mode 100644 index 5776863b2bf..00000000000 --- a/Samples/Simple/include/PNTrianglesTessellation.h +++ /dev/null @@ -1,275 +0,0 @@ -/** -* Modified by: Juan Camilo Acosta Arango (ja0335 ) -* Date: 09-04-2014 -**/ - -#ifndef __PNTriangles_H__ -#define __PNTriangles_H__ - -#include "SdkSample.h" -#include "OgreImage.h" -#include "OgreBillboard.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_PNTriangles : public SdkSample -{ -public: - - Sample_PNTriangles() - : mMoveLights (true) - { - mInfo["Title"] = "PNTriangles"; - mInfo["Description"] = "Sample for parametric PN-Triangles tessellation algorithm"; - mInfo["Thumbnail"] = "thumb_tessellation.png"; - mInfo["Category"] = "Unsorted"; - mInfo["Help"] = "Top Left: Multi-frame\nTop Right: Scrolling\nBottom Left: Rotation\nBottom Right: Scaling"; - } - - void testCapabilities(const RenderSystemCapabilities* caps) override - { - if (!caps->hasCapability(RSC_TESSELLATION_HULL_PROGRAM) || !caps->hasCapability(RSC_TESSELLATION_DOMAIN_PROGRAM)) - { - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Your graphics card does not support tessellation shaders. Sorry!", - "Sample_PNTrianglesTessellation:testCapabilities"); - } - if (!GpuProgramManager::getSingleton().isSyntaxSupported("vs_5_0") && - !GpuProgramManager::getSingleton().isSyntaxSupported("hs_5_0") && - !GpuProgramManager::getSingleton().isSyntaxSupported("ds_5_0") && - !GpuProgramManager::getSingleton().isSyntaxSupported("ps_5_0") && - !GpuProgramManager::getSingleton().isSyntaxSupported("hlsl")) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Your card does not support the shader model 5.0 needed for this sample, " - "so you cannot run this sample. Sorry!", "Sample_PNTrianglesTessellation::testCapabilities"); - } - } - - bool frameRenderingQueued(const FrameEvent& evt) override - { - if (mMoveLights) - { - // rotate the light pivots - mLightPivot1->roll(Degree(evt.timeSinceLastFrame * 10)); - mLightPivot2->roll(Degree(evt.timeSinceLastFrame * 15)); - } - - return SdkSample::frameRenderingQueued(evt); // don't forget the parent class updates! - } - - void itemSelected(SelectMenu* menu) override - { - if (menu == mMeshMenu) - { - // change to the selected entity - mObjectNode->detachAllObjects(); - mObjectNode->attachObject(mSceneMgr->getEntity(mMeshMenu->getSelectedItem())); - - // remember which material is currently selected - int index = std::max(0, mMaterialMenu->getSelectionIndex()); - - // update the material menu's options - mMaterialMenu->setItems(mPossibilities[mMeshMenu->getSelectedItem()]); - - mMaterialMenu->selectItem(index); // select the material with the saved index - } - else - { - // set the selected material for the active mesh - ((Entity*)mObjectNode->getAttachedObject(0))->setMaterialName(menu->getSelectedItem()); - - if( menu->getSelectionIndex() == 2 ) - mTessellationAmount->show(); - else - mTessellationAmount->hide(); - } - } - - void checkBoxToggled(CheckBox* box) override - { - if (box->getName() == "Wire") - { - if( mCamera->getPolygonMode() == PM_WIREFRAME ) - mCamera->setPolygonMode(PM_SOLID); - else - mCamera->setPolygonMode(PM_WIREFRAME); - } - else if (StringUtil::startsWith(box->getName(), "Light", false)) - { - // get the light pivot that corresponds to this checkbox - SceneNode* pivot = box->getName() == "Light1" ? mLightPivot1 : mLightPivot2; - // toggle visibility of light and billboard set - pivot->setVisible(box->isChecked()); - } - else if (box->getName() == "MoveLights") - { - mMoveLights = !mMoveLights; - } - } - - void sliderMoved(Slider* slider) override - { - if( slider->getName() == "tessellationAmount" ) - { - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( mMaterialMenu->getSelectedItem() ); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_tessellationAmount", slider->getValue() ); - } - } - -protected: - - void setupContent() override - { - // create our main node to attach our entities to - mObjectNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - setupModels(); - setupLights(); - setupControls(); - - // set our camera - mCamera->setFOVy(Ogre::Degree(50.0)); - mCamera->setFOVy(Ogre::Degree(50.0)); - mCamera->setNearClipDistance(0.01f); - mCameraNode->lookAt(Ogre::Vector3::ZERO, Ogre::Node::TS_PARENT); - mCameraNode->setPosition(0, 0, 500); - - - // Set our camera to orbit around the origin at a suitable distance - mCameraMan->setStyle(CS_ORBIT); - mCameraMan->setYawPitchDist(Radian(0), Radian(0), 400); - - mTrayMgr->showCursor(); - } - - void unloadResources() override - { - - } - - void setupModels() - { - StringVector matNames; - - matNames.push_back("Ogre/NoTessellation"); - matNames.push_back("Ogre/TessellationExample"); - matNames.push_back("Ogre/SimpleTessellation"); - //matNames.push_back("Ogre/AdaptiveTessellation"); - matNames.push_back("Ogre/AdaptivePNTrianglesTessellation"); - - mPossibilities["ogrehead.mesh"] = matNames; - mPossibilities["knot.mesh"] = matNames; - mPossibilities["uv_sphere.mesh"] = matNames; - - for (std::map::iterator it = mPossibilities.begin(); it != mPossibilities.end(); it++) - { - // load each mesh with non-default hardware buffer usage options - MeshPtr mesh = MeshManager::getSingleton().load(it->first, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY); - - // build tangent vectors for our mesh - mesh->buildTangentVectors(); - - // create an entity from the mesh and set the first available material - Entity* ent = mSceneMgr->createEntity(mesh->getName(), mesh->getName()); - ent->setMaterialName(it->second.front()); - } - } - - void setupLights() - { - mSceneMgr->setAmbientLight(ColourValue::Black); - mViewport->setBackgroundColour(ColourValue(0.41f, 0.41f, 0.41f)); - - // create pivot nodes - mLightPivot1 = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mLightPivot2 = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - mLightPivot1->setPosition(Vector3(200, 0, 0)); - mLightPivot2->setPosition(Vector3(-200, 0, 0)); - - mLightPivot1->setDirection(-Vector3::UNIT_X); - mLightPivot2->setDirection(Vector3::UNIT_X); - - Light* l; - BillboardSet* bbs; - - // create white light - l = mSceneMgr->createLight(); - l->setDiffuseColour(1.0f, 1.0f, 1.0f); - l->setSpecularColour(1.0f, 1.0f, 1.0f); - mLightPivot1->attachObject(l); - - // create white flare - bbs = mSceneMgr->createBillboardSet(); - bbs->setMaterialName("Examples/Flare"); - bbs->createBillboard(200, 0, 0)->setColour(ColourValue::White); - mLightPivot1->attachObject(bbs); - - // create red light - l = mSceneMgr->createLight(); - l->setDiffuseColour(1.0f, 0.0f, 0.0f); - l->setSpecularColour(1.0f, 0.0f, 0.0f); - mLightPivot2->attachObject(l); - - // create white flare - bbs = mSceneMgr->createBillboardSet(); - bbs->setMaterialName("Examples/Flare"); - bbs->createBillboard(-200, 0, 0)->setColour(ColourValue::Red); - mLightPivot2->attachObject(bbs); - } - - void setupControls() - { - mTrayMgr->showCursor(); - - // make room for the controls - mTrayMgr->showLogo(TL_TOPRIGHT); - mTrayMgr->showFrameStats(TL_TOPRIGHT); - mTrayMgr->toggleAdvancedFrameStats(); - - // create a menu to choose the model displayed - mMeshMenu = mTrayMgr->createLongSelectMenu(TL_BOTTOM, "Mesh", "Mesh", 370, 290, 10); - for (std::map::iterator it = mPossibilities.begin(); it != mPossibilities.end(); it++) - mMeshMenu->addItem(it->first); - - // create a menu to choose the material used by the model - mMaterialMenu = mTrayMgr->createLongSelectMenu(TL_BOTTOM, "Material", "Material", 370, 290, 10); - - mTrayMgr->createCheckBox(TL_TOPLEFT, "Wire", "Wire Frame")->setChecked(false, false); - // create checkboxes to toggle lights - mTrayMgr->createCheckBox(TL_TOPLEFT, "Light1", "Light A")->setChecked(true, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "Light2", "Light B")->setChecked(true, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "MoveLights", "Move Lights")->setChecked(true, false); - - mTessellationAmount = mTrayMgr->createThickSlider(TL_TOPLEFT, "tessellationAmount", "Tessellation Amount", 200, 40, 1, 8, 8); - mTessellationAmount->hide(); - - // a friendly reminder - StringVector names; - names.push_back("Help"); - mTrayMgr->createParamsPanel(TL_TOPLEFT, "Help", 100, names)->setParamValue(0, "H/F1"); - - mMeshMenu->selectItem(0); // select first mesh - } - - void cleanupContent() override - { - // clean up properly to avoid interfering with subsequent samples - for (std::map::iterator it = mPossibilities.begin(); it != mPossibilities.end(); it++) - MeshManager::getSingleton().unload(it->first, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - mPossibilities.clear(); - } - - std::map mPossibilities; - SceneNode* mObjectNode; - SceneNode* mLightPivot1; - SceneNode* mLightPivot2; - bool mMoveLights; - SelectMenu* mMeshMenu; - SelectMenu* mMaterialMenu; - Slider* mTessellationAmount; - -}; - -#endif diff --git a/Samples/Simple/include/ParticleFX.h b/Samples/Simple/include/ParticleFX.h deleted file mode 100644 index 2a5f7727852..00000000000 --- a/Samples/Simple/include/ParticleFX.h +++ /dev/null @@ -1,108 +0,0 @@ -#ifndef __ParticleFX_H__ -#define __ParticleFX_H__ - -#include "SdkSample.h" -#include "OgreParticleSystem.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_ParticleFX : public SdkSample -{ -public: - - Sample_ParticleFX() - { - mInfo["Title"] = "Particle Effects"; - mInfo["Description"] = "Demonstrates the creation and usage of particle effects."; - mInfo["Thumbnail"] = "thumb_particles.png"; - mInfo["Category"] = "Effects"; - mInfo["Help"] = "Use the checkboxes to toggle visibility of the individual particle systems."; - } - - bool frameRenderingQueued(const FrameEvent& evt) override - { - mFountainPivot->yaw(Degree(evt.timeSinceLastFrame * 30)); // spin the fountains around - - return SdkSample::frameRenderingQueued(evt); // don't forget the parent class updates! - } - - void checkBoxToggled(CheckBox* box) override - { - // show or hide the particle system with the same name as the check box - mSceneMgr->getParticleSystem(box->getName())->setVisible(box->isChecked()); - } - -protected: - - void setupContent() override - { - // setup some basic lighting for our scene - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); - mSceneMgr->getRootSceneNode() - ->createChildSceneNode(Vector3(20, 80, 50)) - ->attachObject(mSceneMgr->createLight()); - - // set our camera to orbit around the origin and show cursor - mCameraMan->setStyle(CS_ORBIT); - mCameraMan->setYawPitchDist(Degree(0), Degree(15), 250); - mTrayMgr->showCursor(); - - // create an ogre head entity and place it at the origin - Entity* ent = mSceneMgr->createEntity("Head", "ogrehead.mesh"); - mSceneMgr->getRootSceneNode()->attachObject(ent); - - setupParticles(); // setup particles - setupTogglers(); // setup particle togglers - } - - void setupParticles() - { - ParticleSystem::setDefaultNonVisibleUpdateTimeout(5); // set nonvisible timeout - - ParticleSystem* ps; - - // create some nice fireworks and place it at the origin - ps = mSceneMgr->createParticleSystem("Fireworks", "Examples/Fireworks"); - mSceneMgr->getRootSceneNode()->attachObject(ps); - - // create a green nimbus around the ogre head - ps = mSceneMgr->createParticleSystem("Nimbus", "Examples/GreenyNimbus"); - mSceneMgr->getRootSceneNode()->attachObject(ps); - - ps = mSceneMgr->createParticleSystem("Rain", "Examples/Rain"); // create a rainstorm - ps->fastForward(5); // fast-forward the rain so it looks more natural - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 1000, 0))->attachObject(ps); - - // create aureola around ogre head perpendicular to the ground - ps = mSceneMgr->createParticleSystem("Aureola", "Examples/Aureola"); - mSceneMgr->getRootSceneNode()->attachObject(ps); - - // create shared pivot node for spinning the fountains - mFountainPivot = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - ps = mSceneMgr->createParticleSystem("Fountain1", "Examples/PurpleFountain"); // create fountain 1 - // attach the fountain to a child node of the pivot at a distance and angle - mFountainPivot->createChildSceneNode(Vector3(200, -100, 0), Quaternion(Degree(20), Vector3::UNIT_Z))->attachObject(ps); - - ps = mSceneMgr->createParticleSystem("Fountain2", "Examples/PurpleFountain"); // create fountain 2 - // attach the fountain to a child node of the pivot at a distance and angle - mFountainPivot->createChildSceneNode(Vector3(-200, -100, 0), Quaternion(Degree(-20), Vector3::UNIT_Z))->attachObject(ps); - } - - void setupTogglers() - { - // create check boxes to toggle the visibility of our particle systems - mTrayMgr->createLabel(TL_TOPLEFT, "VisLabel", "Particles"); - mTrayMgr->createCheckBox(TL_TOPLEFT, "Fireworks", "Fireworks", 130)->setChecked(true); - mTrayMgr->createCheckBox(TL_TOPLEFT, "Fountain1", "Fountain A", 130)->setChecked(true); - mTrayMgr->createCheckBox(TL_TOPLEFT, "Fountain2", "Fountain B", 130)->setChecked(true); - mTrayMgr->createCheckBox(TL_TOPLEFT, "Aureola", "Aureola", 130)->setChecked(false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "Nimbus", "Nimbus", 130)->setChecked(false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "Rain", "Rain", 130)->setChecked(false); - } - - SceneNode* mFountainPivot; -}; - -#endif diff --git a/Samples/Simple/include/RectLight.h b/Samples/Simple/include/RectLight.h deleted file mode 100644 index 5cd8c8eb08c..00000000000 --- a/Samples/Simple/include/RectLight.h +++ /dev/null @@ -1,79 +0,0 @@ -#pragma once - -#include "SdkSample.h" -#include "SamplePlugin.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_RectLight : public SdkSample -{ - Ogre::Light* mLight; -public: - Sample_RectLight() - { - mInfo["Title"] = "Rectangular Area Light"; - mInfo["Description"] = "Shows how to use rectangular area lights"; - mInfo["Thumbnail"] = "thumb_rectlight.png"; - mInfo["Category"] = "Lighting"; - } - - bool frameStarted(const FrameEvent& e) override - { - mLight->getParentNode()->roll(Degree(e.timeSinceLastFrame * 45)); - - return SdkSample::frameStarted(e); - } - - void setupContent() override - { - // Make this viewport work with shader generator - mViewport->setMaterialScheme(MSN_SHADERGEN); - - auto rcvmat = MaterialManager::getSingleton().getDefaultMaterial()->clone("rcvmat"); - rcvmat->getTechnique(0)->getPass(0)->setSpecular(ColourValue::White * 0.25); - rcvmat->getTechnique(0)->getPass(0)->setShininess(80); - - auto srcmat = MaterialManager::getSingleton().getDefaultMaterial(false)->clone("lightsrcmat"); - srcmat->getTechnique(0)->getPass(0)->setCullingMode(CULL_ANTICLOCKWISE); - - auto ground = mSceneMgr->createEntity(SceneManager::PT_PLANE); - ground->setMaterial(rcvmat); - auto groundnode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - groundnode->pitch(Degree(-90)); - groundnode->attachObject(ground); - - auto sphere = mSceneMgr->createEntity(SceneManager::PT_SPHERE); - sphere->setMaterial(rcvmat); - auto spherenode = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(20, 6, 20)); - spherenode->attachObject(sphere); - spherenode->setScale(Vector3(0.1, 0.1, 0.1)); - spherenode->pitch(Degree(180)); - - auto srcsz = 12.0; - mLight = mSceneMgr->createLight("light", Light::LT_RECTLIGHT); - mLight->setSourceSize(srcsz, srcsz); - mLight->setSpotlightRange(Degree(160), Degree(180)); - - auto lightnode = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 6, 32)); - lightnode->attachObject(mLight); - auto lightrect = mSceneMgr->createEntity("lightsrc", SceneManager::PT_PLANE); - lightrect->setMaterial(srcmat); - auto lightrectnode = lightnode->createChildSceneNode(); - lightrectnode->setScale(Vector3(srcsz/200, srcsz/200, srcsz/200)); - lightrectnode->attachObject(lightrect); - - mCamera->setNearClipDistance(0.1); - mCameraMan->setStyle(OgreBites::CS_ORBIT); - mCameraMan->setTarget(lightnode); - mCameraMan->setYawPitchDist(Degree(180), Degree(15), 50); - - mTrayMgr->createCheckBox(TL_TOPLEFT, "rectlight", "Rectangular Light")->setChecked(true, false); - mTrayMgr->showCursor(); - } - - void checkBoxToggled(CheckBox* box) override - { - mLight->setType(box->isChecked() ? Light::LT_RECTLIGHT : Light::LT_SPOTLIGHT); - } -}; diff --git a/Samples/Simple/include/SSAO.h b/Samples/Simple/include/SSAO.h deleted file mode 100644 index ca96cf5f292..00000000000 --- a/Samples/Simple/include/SSAO.h +++ /dev/null @@ -1,778 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - - Copyright (c) 2000-2014 Torus Knot Software Ltd - Also see acknowledgements in Readme.html - - You may use this sample code for anything you like, it is not covered by the - same license as the rest of the engine. - ----------------------------------------------------------------------------- - */ - -#include "SdkSample.h" - -#ifndef __SSAO_H__ -#define __SSAO_H__ - -using namespace Ogre; -using namespace OgreBites; - -#define SSAO_GUI_WIDTH 250 -#define SSAO_GUI_TRACK_WIDTH 100 -#define SSAO_GUI_VALUE_BOX_WIDTH 50 - -#define SSAO_OBJECT_MENU_NAME "ObjectType" -#define SSAO_CAMERA_MENU_NAME "Camera" - -#define SSAO_COMPOSITOR_MENU_NAME "Compositor" -#define SSAO_POST_MENU_NAME "Post" -#define SSAO_CREASE_MINIMUM_NAME "CreaseMinimum" -#define SSAO_CREASE_RANGE_NAME "mCreaseRange" -#define SSAO_CREASE_BIAS_NAME "mCreaseBias" -#define SSAO_CREASE_AVERAGER_NAME "mCreaseAverager" -#define SSAO_CREASE_KERNELSIZE_NAME "mCreaseKernelsize" - -#define SSAO_MODUALTE "mdoulate" -#define SSAO_SAMPLE_SPACE_NAME "sampleSpace" -#define SSAO_SAMPLE_LENGTH_SCREENSPACE "sampleScreenSpace" -#define SSAO_SAMPLE_LENGTH_WORLDSPACE "sampleWorldSpace" -#define SSAO_SAMPLE_LENGTH_EXPONENT_NAME "sampleLengthExponent" - -#define SSAO_ANGLE_BIAS_NAME "angleBias" - -#define SSAO_CRYTEK_OFFSET_SCALE_NAME "offsetScale" -#define SSAO_CRYTEK_EDGE_HIGHLIGHT_NAME "edgeHighlight" -#define SSAO_CRYTEK_DEFAULT_ACCESSIBILITY_NAME "defaultOcclusion" - -#define SSAO_UNSHARP_KERNEL_BIAS_NAME "kernelBias" -#define SSAO_UNSHARP_LAMBDA_NAME "lambda" - -#define SSAO_BILATERAL_PHOTOMETRIC_EXPONENT "photometricExponent" - -#define SSAO_USER_CAMERA_ITEM "User Camera" -#define SSAO_CAMERA_SIBENIK "Sibenik" -#define SSAO_CAMERA_CORNELL "Cornell Box" - -/** Class for handling materials who did not specify techniques for rendering - * themselves into the GBuffer. - */ -class _OgreSampleClassExport SSAOGBufferSchemeHandler : public Ogre::MaterialManager::Listener -{ -public: - SSAOGBufferSchemeHandler() - { - mGBufRefMat = Ogre::MaterialManager::getSingleton().getByName("SSAO/GBuffer"); - RTShader::ShaderGenerator::getSingleton().validateMaterial("GBuffer", *mGBufRefMat); - mGBufRefMat->load(); - } - - Ogre::Technique* handleSchemeNotFound(unsigned short schemeIndex, - const Ogre::String& schemeName, Ogre::Material* originalMaterial, unsigned short lodIndex, - const Ogre::Renderable* rend) override - { - Technique* gBufferTech = originalMaterial->createTechnique(); - gBufferTech->setSchemeName(schemeName); - Ogre::Pass* gbufPass = gBufferTech->createPass(); - *gbufPass = *mGBufRefMat->getBestTechnique()->getPass(0); - return gBufferTech; - } -private: - Ogre::MaterialPtr mGBufRefMat; -}; - -class _OgreSampleClassExport Sample_SSAO : public SdkSample -{ -private: - std::vector mMeshNames; - std::vector mMeshes; - int mCurrentMeshIndex; - - std::vector mCompositorNames; - String mCurrentCompositor; - - std::vector mPostNames; - String mCurrentPost; - String mCurrentModulateScheme; - - SSAOGBufferSchemeHandler* mGBufSchemeHandler; - Light* mLight; - -public: - Sample_SSAO() - { - mInfo["Title"] = "SSAO Techniques"; - mInfo["Description"] = "A demo of several Screen Space Ambient Occlusion (SSAO) shading techniques using compositors."; - mInfo["Thumbnail"] = "thumb_ssao.png"; - mInfo["Category"] = "Lighting"; - - mMeshNames.push_back("sibenik"); - mMeshNames.push_back("cornell"); - - mCompositorNames.push_back("SSAO/HemisphereMC"); - mCompositorNames.push_back("SSAO/Volumetric"); - mCompositorNames.push_back("SSAO/HorizonBased"); - mCompositorNames.push_back("SSAO/Crytek"); - mCompositorNames.push_back("SSAO/CreaseShading"); - mCompositorNames.push_back("SSAO/UnsharpMask"); - mCompositorNames.push_back("SSAO/ShowDepth"); - mCompositorNames.push_back("SSAO/ShowNormals"); - mCompositorNames.push_back("SSAO/ShowViewPos"); - - mPostNames.push_back("SSAO/Post/NoFilter"); - mPostNames.push_back("SSAO/Post/CrossBilateralFilter"); - mPostNames.push_back("SSAO/Post/SmartBoxFilter"); - mPostNames.push_back("SSAO/Post/BoxFilter"); - - mCurrentCompositor = mCompositorNames[0]; - mCurrentPost = mPostNames[0]; - - mGBufSchemeHandler = NULL; - mLight = NULL; - } - - void cleanupContent() override - { - MaterialManager::getSingleton().removeListener(mGBufSchemeHandler, "GBuffer"); - delete mGBufSchemeHandler; - mGBufSchemeHandler = NULL; - - CompositorManager::getSingleton().setCompositorEnabled(mViewport, mCurrentCompositor, false); - CompositorManager::getSingleton().setCompositorEnabled(mViewport, mCurrentPost, false); - - CompositorManager::getSingleton().setCompositorEnabled(mViewport, "SSAO/GBuffer", false); - CompositorManager::getSingleton().removeCompositor(mViewport, "SSAO/GBuffer"); - - for (unsigned int i = 0; i < mCompositorNames.size(); i++) - { - CompositorManager::getSingleton().setCompositorEnabled(mViewport, mCompositorNames[i], false); - CompositorManager::getSingleton().removeCompositor(mViewport, mCompositorNames[i]); - } - - for (unsigned int i = 0; i < mPostNames.size(); i++) - { - CompositorManager::getSingleton().setCompositorEnabled(mViewport, mPostNames[i], false); - CompositorManager::getSingleton().removeCompositor(mViewport, mPostNames[i]); - } - - mMeshes.clear(); - } - - void testCapabilities(const RenderSystemCapabilities* caps) override - { - if (StringUtil::startsWith(caps->getRenderSystemName(), "OpenGL ES")) - { - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "This demo currently only supports OpenGL and DirectX9. Sorry!", - "Sample_SSAO:testCapabilities"); - } - } - -protected: - /** - * Setup the compositors to be used. - */ - void setupCompositors() - { - - if (CompositorManager::getSingleton().addCompositor(mViewport, "SSAO/GBuffer")) - CompositorManager::getSingleton().setCompositorEnabled(mViewport, "SSAO/GBuffer", true); - else - LogManager::getSingleton().logMessage("Sample_SSAO: Failed to add GBuffer compositor\n"); - - for (unsigned int i = 0; i < mCompositorNames.size(); i++) - { - if (CompositorManager::getSingleton().addCompositor(mViewport, mCompositorNames[i])) - CompositorManager::getSingleton().setCompositorEnabled(mViewport, mCompositorNames[i], false); - else - LogManager::getSingleton().logMessage("Sample_SSAO: Failed to add compositor: " + mCompositorNames[i] + "\n"); - } - - for (unsigned int i = 0; i < mPostNames.size(); i++) - { - - if (CompositorManager::getSingleton().addCompositor(mViewport, mPostNames[i])) - CompositorManager::getSingleton().setCompositorEnabled(mViewport, mPostNames[i], false); - else - LogManager::getSingleton().logMessage("Sample_SSAO: Failed to add " + mPostNames[i] + " compositor\n"); - } - - CompositorManager::getSingleton().setCompositorEnabled(mViewport, mCurrentCompositor, true); - CompositorManager::getSingleton().setCompositorEnabled(mViewport, mCurrentPost, true); - } - - /** - * Setup the controls, ie. the gui elements. - */ - void setupControls(void) - { - // --- select mesh menu --- - SelectMenu* objectType = mTrayMgr->createThickSelectMenu(TL_TOPLEFT, SSAO_OBJECT_MENU_NAME, "Object: ", SSAO_GUI_WIDTH, 16); - for (unsigned int i = 0; i < mMeshNames.size(); i++) - objectType->addItem(mMeshNames[i]); - - // --- select camera menu --- - SelectMenu* cameraMenu = mTrayMgr->createThickSelectMenu(TL_TOPLEFT, SSAO_CAMERA_MENU_NAME, "Camera Position", SSAO_GUI_WIDTH, 16); - cameraMenu->addItem(SSAO_USER_CAMERA_ITEM); - cameraMenu->addItem(SSAO_CAMERA_CORNELL); - cameraMenu->addItem(SSAO_CAMERA_SIBENIK); - - // --- select compositor menu --- - SelectMenu* compositor = mTrayMgr->createThickSelectMenu(TL_TOPLEFT, SSAO_COMPOSITOR_MENU_NAME, "Compositor: ", SSAO_GUI_WIDTH, 16); - for (unsigned int i = 0; i < mCompositorNames.size(); i++) - compositor->addItem(mCompositorNames[i]); - - // --- select post filter menu --- - SelectMenu * post = mTrayMgr->createThickSelectMenu(TL_TOPLEFT, SSAO_POST_MENU_NAME, "Post Filter: ", SSAO_GUI_WIDTH, 16); - for (unsigned int i = 0; i < mPostNames.size(); i++) - post->addItem(mPostNames[i]); - - // --- hemisphere MC sample length exponent --- // - mTrayMgr->createThickSlider(TL_TOPLEFT, - SSAO_SAMPLE_LENGTH_EXPONENT_NAME, - "Sample Length Exponent", - SSAO_GUI_WIDTH, - SSAO_GUI_VALUE_BOX_WIDTH, - 0, - 5, - 501); // snaps ??? - - - // --- bilateral photometric exponent --- - mTrayMgr->createThickSlider(TL_TOPLEFT, - SSAO_BILATERAL_PHOTOMETRIC_EXPONENT, - "Photometric Exponent", - SSAO_GUI_WIDTH, - SSAO_GUI_VALUE_BOX_WIDTH, - 0, - 50, - 501); // snaps ??? - - // --- crease shading options --- - mTrayMgr->createThickSlider(TL_TOPLEFT, - SSAO_CREASE_MINIMUM_NAME, - "Minimum Crease", - SSAO_GUI_WIDTH, - SSAO_GUI_VALUE_BOX_WIDTH, - 0, - 1, - 101); // snaps ??? - mTrayMgr->createThickSlider(TL_TOPLEFT, - SSAO_CREASE_RANGE_NAME, - "Crease Range", - SSAO_GUI_WIDTH, - SSAO_GUI_VALUE_BOX_WIDTH, - 0, - 10, - 101); // snaps ??? - mTrayMgr->createThickSlider(TL_TOPLEFT, - SSAO_CREASE_BIAS_NAME, - "Bias", - SSAO_GUI_WIDTH, - SSAO_GUI_VALUE_BOX_WIDTH, - 0, - 2, - 101); // snaps ??? - mTrayMgr->createThickSlider(TL_TOPLEFT, - SSAO_CREASE_AVERAGER_NAME, - "Averager", - SSAO_GUI_WIDTH, - SSAO_GUI_VALUE_BOX_WIDTH, - 0, - 100, - 101); // snaps ??? - - mTrayMgr->createThickSlider(TL_TOPLEFT, - SSAO_CREASE_KERNELSIZE_NAME, - "Kernel Size Bias", - SSAO_GUI_WIDTH, - SSAO_GUI_VALUE_BOX_WIDTH, - 0, - 10, - 101); // snaps ??? - // --- sample length parameter --- - mTrayMgr->createSeparator(TL_TOPLEFT, "sep"); - - mTrayMgr->createCheckBox(TL_TOPLEFT, SSAO_MODUALTE, "Modulate with scene", SSAO_GUI_WIDTH); - - // --- sample length parameter --- - mTrayMgr->createSeparator(TL_TOPLEFT, "sep2"); - mTrayMgr->createCheckBox(TL_TOPLEFT, SSAO_SAMPLE_SPACE_NAME, "Sample in Screen Space", SSAO_GUI_WIDTH); - mTrayMgr->createThickSlider(TL_TOPLEFT, - SSAO_SAMPLE_LENGTH_SCREENSPACE, - "Screen space length (in %)", - SSAO_GUI_WIDTH, - SSAO_GUI_VALUE_BOX_WIDTH, - 0, - 100, - 10001); - - mTrayMgr->createThickSlider(TL_TOPLEFT, - SSAO_SAMPLE_LENGTH_WORLDSPACE, - "World Space Length (units)", - SSAO_GUI_WIDTH, - SSAO_GUI_VALUE_BOX_WIDTH, - 0, - 10, - 10001); - - // --- angle bias --- - mTrayMgr->createThickSlider(TL_TOPLEFT, - SSAO_ANGLE_BIAS_NAME, - "Angle Bias (radians)", - SSAO_GUI_WIDTH, - SSAO_GUI_VALUE_BOX_WIDTH, - 0, - Math::HALF_PI, - 1001); - - // --- offset length --- - mTrayMgr->createThickSlider(TL_TOPLEFT, - SSAO_CRYTEK_OFFSET_SCALE_NAME, - "Offset Scale (% of sample length)", - SSAO_GUI_WIDTH, - SSAO_GUI_VALUE_BOX_WIDTH, - 0, - 100, - 10001); - - // --- crytek edge highlight --- - mTrayMgr->createThickSlider(TL_TOPLEFT, - SSAO_CRYTEK_EDGE_HIGHLIGHT_NAME, - "Edge Highlight Factor", - SSAO_GUI_WIDTH, - SSAO_GUI_VALUE_BOX_WIDTH, - 0, - 1, - 101); - - // --- crytek default accesibility value for invalid samples --- - mTrayMgr->createThickSlider(TL_TOPLEFT, - SSAO_CRYTEK_DEFAULT_ACCESSIBILITY_NAME, - "Default Accessibility", - SSAO_GUI_WIDTH, - SSAO_GUI_VALUE_BOX_WIDTH, - 0, - 1, - 101); - - // --- unsharp mask kernel bias --- - mTrayMgr->createThickSlider(TL_TOPLEFT, - SSAO_UNSHARP_KERNEL_BIAS_NAME, - "Kernel Size Bias", - SSAO_GUI_WIDTH, - SSAO_GUI_VALUE_BOX_WIDTH, - 0, - 10, - 101); // snaps ??? - // --- unsharp mask lambda --- - mTrayMgr->createThickSlider(TL_TOPLEFT, - SSAO_UNSHARP_LAMBDA_NAME, - "Unsharp Lambda", - SSAO_GUI_WIDTH, - SSAO_GUI_VALUE_BOX_WIDTH, - 0, - 10, - 101); // snaps ??? - - // setup values - static_cast(mTrayMgr->getWidget(SSAO_CREASE_MINIMUM_NAME))->setValue(0.2f); - static_cast(mTrayMgr->getWidget(SSAO_CREASE_RANGE_NAME))->setValue(1.0f); - static_cast(mTrayMgr->getWidget(SSAO_CREASE_BIAS_NAME))->setValue(1.0f); - static_cast(mTrayMgr->getWidget(SSAO_CREASE_AVERAGER_NAME))->setValue(24); - static_cast(mTrayMgr->getWidget(SSAO_CREASE_KERNELSIZE_NAME))->setValue(3.0f); - - static_cast(mTrayMgr->getWidget(SSAO_SAMPLE_SPACE_NAME))->setChecked(false); - static_cast(mTrayMgr->getWidget(SSAO_SAMPLE_LENGTH_SCREENSPACE))->setValue(6.0f); - static_cast(mTrayMgr->getWidget(SSAO_SAMPLE_LENGTH_WORLDSPACE))->setValue(2.0f); - static_cast(mTrayMgr->getWidget(SSAO_ANGLE_BIAS_NAME))->setValue(0.2f); - static_cast(mTrayMgr->getWidget(SSAO_CRYTEK_OFFSET_SCALE_NAME))->setValue(1.0f); - static_cast(mTrayMgr->getWidget(SSAO_CRYTEK_EDGE_HIGHLIGHT_NAME))->setValue(0.0f); - static_cast(mTrayMgr->getWidget(SSAO_CRYTEK_DEFAULT_ACCESSIBILITY_NAME))->setValue(0.5f); - - static_cast(mTrayMgr->getWidget(SSAO_UNSHARP_KERNEL_BIAS_NAME))->setValue(1.0f); - static_cast(mTrayMgr->getWidget(SSAO_UNSHARP_LAMBDA_NAME))->setValue(5.0f); - - static_cast(mTrayMgr->getWidget(SSAO_BILATERAL_PHOTOMETRIC_EXPONENT))->setValue(10.0f); - - static_cast(mTrayMgr->getWidget(SSAO_SAMPLE_LENGTH_EXPONENT_NAME))->setValue(1.0f); - - mTrayMgr->showCursor(); - } - - /** - * Create the scene and load the content. - */ - void setupContent() override - { - mViewport->setBackgroundColour(ColourValue(0.5, 0.5, 0.5, 1)); - - // set our camera to orbit around the origin and show cursor - mCameraMan->setStyle(CS_FREELOOK); - mCameraMan->setTopSpeed(20.0); - mCameraNode->translate(Vector3(0, 10, 0)); - mCamera->setFOVy(Radian(Degree(45).valueRadians())); // i.e. 60deg * 1.3.. maya and ogre use fovX and fovY - mCamera->setFarClipDistance(400); - mCamera->setNearClipDistance(0.1); - mTrayMgr->showCursor(); - - // sibenik - mCameraNode->setPosition(27, 9, -2); - mCameraNode->lookAt(Vector3(-6, 2, 1), Node::TS_PARENT);; - - // setup all meshes - for (unsigned int i = 0; i < mMeshNames.size(); i++) { - Entity* ent = mSceneMgr->createEntity(mMeshNames[i], mMeshNames[i] + ".mesh"); - ent->setVisible(false); - - mSceneMgr->getRootSceneNode()->attachObject(ent); - mMeshes.push_back(ent); - } - mCurrentMeshIndex = 0; - mMeshes[mCurrentMeshIndex]->setVisible(true); - - setupCompositors(); - - setupControls(); - - changeCompositor(mCompositorNames[0]); - changePost(mPostNames[0]); - - mGBufSchemeHandler = new SSAOGBufferSchemeHandler(); - MaterialManager::getSingleton().addListener(mGBufSchemeHandler, "GBuffer"); - } - - /** - * Change the current displayed mesh to the new mesh identified by its index. - * @param index The index of the new mesh in the mesh vector. - */ - void changeMesh(int index) - { - mMeshes[mCurrentMeshIndex]->setVisible(false); - mMeshes[index]->setVisible(true); - mCurrentMeshIndex = index; - } - - /** - * Change the compositor to be used. - * @param compositor The name of the compositor - */ - void changeCompositor(const Ogre::String& compositor) - { - CompositorManager::getSingleton().setCompositorEnabled(mViewport, mCurrentCompositor, false); - mCurrentCompositor = compositor; - CompositorManager::getSingleton().setCompositorEnabled(mViewport, mCurrentCompositor, true); - - if (compositor == "SSAO/CreaseShading") - { - mTrayMgr->getWidget(SSAO_CREASE_MINIMUM_NAME)->show(); - mTrayMgr->moveWidgetToTray(SSAO_CREASE_MINIMUM_NAME, TL_TOPLEFT); - mTrayMgr->getWidget(SSAO_CREASE_RANGE_NAME)->show(); - mTrayMgr->moveWidgetToTray(SSAO_CREASE_RANGE_NAME, TL_TOPLEFT); - mTrayMgr->getWidget(SSAO_CREASE_BIAS_NAME)->show(); - mTrayMgr->moveWidgetToTray(SSAO_CREASE_BIAS_NAME, TL_TOPLEFT); - mTrayMgr->getWidget(SSAO_CREASE_AVERAGER_NAME)->show(); - mTrayMgr->moveWidgetToTray(SSAO_CREASE_AVERAGER_NAME, TL_TOPLEFT); - mTrayMgr->getWidget(SSAO_CREASE_KERNELSIZE_NAME)->show(); - mTrayMgr->moveWidgetToTray(SSAO_CREASE_KERNELSIZE_NAME, TL_TOPLEFT); - } - else - { - mTrayMgr->getWidget(SSAO_CREASE_MINIMUM_NAME)->hide(); - mTrayMgr->removeWidgetFromTray(SSAO_CREASE_MINIMUM_NAME); - mTrayMgr->getWidget(SSAO_CREASE_RANGE_NAME)->hide(); - mTrayMgr->removeWidgetFromTray(SSAO_CREASE_RANGE_NAME); - mTrayMgr->getWidget(SSAO_CREASE_BIAS_NAME)->hide(); - mTrayMgr->removeWidgetFromTray(SSAO_CREASE_BIAS_NAME); - mTrayMgr->getWidget(SSAO_CREASE_AVERAGER_NAME)->hide(); - mTrayMgr->removeWidgetFromTray(SSAO_CREASE_AVERAGER_NAME); - mTrayMgr->getWidget(SSAO_CREASE_KERNELSIZE_NAME)->hide(); - mTrayMgr->removeWidgetFromTray(SSAO_CREASE_KERNELSIZE_NAME); - } - - if (compositor == "SSAO/UnsharpMask") - { - mTrayMgr->getWidget(SSAO_UNSHARP_KERNEL_BIAS_NAME)->show(); - mTrayMgr->moveWidgetToTray(SSAO_UNSHARP_KERNEL_BIAS_NAME, TL_TOPLEFT); - mTrayMgr->getWidget(SSAO_UNSHARP_LAMBDA_NAME)->show(); - mTrayMgr->moveWidgetToTray(SSAO_UNSHARP_LAMBDA_NAME, TL_TOPLEFT); - } - else - { - mTrayMgr->getWidget(SSAO_UNSHARP_KERNEL_BIAS_NAME)->hide(); - mTrayMgr->removeWidgetFromTray(SSAO_UNSHARP_KERNEL_BIAS_NAME); - mTrayMgr->getWidget(SSAO_UNSHARP_LAMBDA_NAME)->hide(); - mTrayMgr->removeWidgetFromTray(SSAO_UNSHARP_LAMBDA_NAME); - } - - if (compositor == "SSAO/Crytek" || compositor == "SSAO/HorizonBased" || compositor == "SSAO/HemisphereMC" || compositor == "SSAO/Volumetric") - { - mTrayMgr->getWidget(SSAO_SAMPLE_SPACE_NAME)->show(); - mTrayMgr->moveWidgetToTray(SSAO_SAMPLE_SPACE_NAME, TL_TOPLEFT); - CheckBox *samplingCheckBox = (CheckBox *)mTrayMgr->getWidget(SSAO_SAMPLE_SPACE_NAME); - samplingCheckBox->setChecked(samplingCheckBox->isChecked()); // easy way to update the sliders... - } - else - { - mTrayMgr->getWidget(SSAO_SAMPLE_SPACE_NAME)->hide(); - mTrayMgr->removeWidgetFromTray(SSAO_SAMPLE_SPACE_NAME); - mTrayMgr->getWidget(SSAO_SAMPLE_LENGTH_SCREENSPACE)->hide(); - mTrayMgr->removeWidgetFromTray(SSAO_SAMPLE_LENGTH_SCREENSPACE); - mTrayMgr->getWidget(SSAO_SAMPLE_LENGTH_WORLDSPACE)->hide(); - mTrayMgr->removeWidgetFromTray(SSAO_SAMPLE_LENGTH_WORLDSPACE); - } - - if (compositor == "SSAO/HemisphereMC") - { - mTrayMgr->getWidget(SSAO_SAMPLE_LENGTH_EXPONENT_NAME)->show(); - mTrayMgr->moveWidgetToTray(SSAO_SAMPLE_LENGTH_EXPONENT_NAME, TL_TOPLEFT); - } - else - { - mTrayMgr->getWidget(SSAO_SAMPLE_LENGTH_EXPONENT_NAME)->hide(); - mTrayMgr->removeWidgetFromTray(SSAO_SAMPLE_LENGTH_EXPONENT_NAME); - } - - if (compositor == "SSAO/HorizonBased") - { - mTrayMgr->getWidget(SSAO_ANGLE_BIAS_NAME)->show(); - mTrayMgr->moveWidgetToTray(SSAO_ANGLE_BIAS_NAME, TL_TOPLEFT); - } - else - { - mTrayMgr->getWidget(SSAO_ANGLE_BIAS_NAME)->hide(); - mTrayMgr->removeWidgetFromTray(SSAO_ANGLE_BIAS_NAME); - } - - if (compositor == "SSAO/Crytek") - { - mTrayMgr->getWidget(SSAO_CRYTEK_OFFSET_SCALE_NAME)->show(); - mTrayMgr->moveWidgetToTray(SSAO_CRYTEK_OFFSET_SCALE_NAME, TL_TOPLEFT); - mTrayMgr->getWidget(SSAO_CRYTEK_EDGE_HIGHLIGHT_NAME)->show(); - mTrayMgr->moveWidgetToTray(SSAO_CRYTEK_EDGE_HIGHLIGHT_NAME, TL_TOPLEFT); - mTrayMgr->getWidget(SSAO_CRYTEK_DEFAULT_ACCESSIBILITY_NAME)->show(); - mTrayMgr->moveWidgetToTray(SSAO_CRYTEK_DEFAULT_ACCESSIBILITY_NAME, TL_TOPLEFT); - } - else - { - mTrayMgr->getWidget(SSAO_CRYTEK_OFFSET_SCALE_NAME)->hide(); - mTrayMgr->removeWidgetFromTray(SSAO_CRYTEK_OFFSET_SCALE_NAME); - mTrayMgr->getWidget(SSAO_CRYTEK_EDGE_HIGHLIGHT_NAME)->hide(); - mTrayMgr->removeWidgetFromTray(SSAO_CRYTEK_EDGE_HIGHLIGHT_NAME); - mTrayMgr->getWidget(SSAO_CRYTEK_DEFAULT_ACCESSIBILITY_NAME)->hide(); - mTrayMgr->removeWidgetFromTray(SSAO_CRYTEK_DEFAULT_ACCESSIBILITY_NAME); - } - } - - /** - * Change the post filter to be used. - * @param post The name of the new post processing filter. - */ - void changePost(const Ogre::String& post) - { - CompositorManager::getSingleton().setCompositorEnabled(mViewport, mCurrentPost, false); - mCurrentPost = post; - CompositorManager::getSingleton().setCompositorEnabled(mViewport, mCurrentPost, true); - - if (post == "SSAO/Post/CrossBilateralFilter") - { - mTrayMgr->getWidget(SSAO_BILATERAL_PHOTOMETRIC_EXPONENT)->show(); - mTrayMgr->moveWidgetToTray(SSAO_BILATERAL_PHOTOMETRIC_EXPONENT, TL_TOPLEFT); - } - else - { - mTrayMgr->getWidget(SSAO_BILATERAL_PHOTOMETRIC_EXPONENT)->hide(); - mTrayMgr->removeWidgetFromTray(SSAO_BILATERAL_PHOTOMETRIC_EXPONENT); - } - } - - // sdkTray listener callbacks - void itemSelected(SelectMenu* menu) override - { - if (menu->getName() == SSAO_OBJECT_MENU_NAME) - changeMesh(menu->getSelectionIndex()); - - else if (menu->getName() == SSAO_COMPOSITOR_MENU_NAME) - changeCompositor(menu->getSelectedItem()); - - else if (menu->getName() == SSAO_POST_MENU_NAME) - changePost(menu->getSelectedItem()); - - else if (menu->getName() == SSAO_CAMERA_MENU_NAME) - { - if (menu->getSelectedItem() == SSAO_CAMERA_SIBENIK) - { - mCameraNode->setPosition(27, 9, -2); - mCameraNode->lookAt(Vector3(-6, 2, 1), Node::TS_PARENT); - } - else if (menu->getSelectedItem() == SSAO_CAMERA_CORNELL) - { - mCameraNode->setPosition(0, 5, 20); - mCameraNode->lookAt(Vector3(0, 5, 0), Node::TS_PARENT); - } - } - } - - void sliderMoved(Slider* slider) override - { - if (slider->getName() == SSAO_CREASE_MINIMUM_NAME) - setUniform("SSAO/CreaseShading", "cMinimumCrease", slider->getValue()); - - else if (slider->getName() == SSAO_CREASE_BIAS_NAME) - setUniform("SSAO/CreaseShading", "cBias", slider->getValue()); - - else if (slider->getName() == SSAO_CREASE_AVERAGER_NAME) - setUniform("SSAO/CreaseShading", "cAverager", slider->getValue()); - - else if (slider->getName() == SSAO_CREASE_RANGE_NAME) - setUniform("SSAO/CreaseShading", "cRange", slider->getValue() * slider->getValue()); - - else if (slider->getName() == SSAO_CREASE_KERNELSIZE_NAME) - setUniform("SSAO/CreaseShading", "cKernelSize", slider->getValue()); - - else if (slider->getName() == SSAO_SAMPLE_LENGTH_SCREENSPACE) - { - setUniform("SSAO/Crytek", "cSampleLengthScreenSpace", slider->getValue()/100.0f); - setUniform("SSAO/HorizonBased", "cSampleLengthScreenSpace", slider->getValue()/100.0f); - setUniform("SSAO/HemisphereMC", "cSampleLengthScreenSpace", slider->getValue()/100.0f); - setUniform("SSAO/Volumetric", "cSampleLengthScreenSpace", slider->getValue()/100.0f); - } - else if (slider->getName() == SSAO_SAMPLE_LENGTH_WORLDSPACE) - { - setUniform("SSAO/Crytek", "cSampleLengthWorldSpace", slider->getValue()); - setUniform("SSAO/HorizonBased", "cSampleLengthWorldSpace", slider->getValue()); - setUniform("SSAO/HemisphereMC", "cSampleLengthWorldSpace", slider->getValue()); - setUniform("SSAO/Volumetric", "cSampleLengthWorldSpace", slider->getValue()); - } - - else if (slider->getName() == SSAO_ANGLE_BIAS_NAME) - setUniform("SSAO/HorizonBased", "cAngleBias", slider->getValue()); - - else if (slider->getName() == SSAO_CRYTEK_OFFSET_SCALE_NAME) - setUniform("SSAO/Crytek", "cOffsetScale", slider->getValue()/100); - - else if (slider->getName() == SSAO_CRYTEK_EDGE_HIGHLIGHT_NAME) - setUniform("SSAO/Crytek", "cEdgeHighlight", 2.0f - slider->getValue()); - - else if (slider->getName() == SSAO_CRYTEK_DEFAULT_ACCESSIBILITY_NAME) - setUniform("SSAO/Crytek", "cDefaultAccessibility", slider->getValue()); - - else if (slider->getName() == SSAO_UNSHARP_KERNEL_BIAS_NAME) - { - setUniform("SSAO/UnsharpMask/GaussianBlurY", "cKernelWidthBias", slider->getValue()); - setUniform("SSAO/UnsharpMask/GaussianBlurX", "cKernelWidthBias", slider->getValue()); - } - - else if (slider->getName() == SSAO_UNSHARP_LAMBDA_NAME) - setUniform("SSAO/UnsharpMask", "cLambda", slider->getValue() * slider->getValue()); - - else if (slider->getName() == SSAO_BILATERAL_PHOTOMETRIC_EXPONENT) - { - setUniform("SSAO/HorizonBased/CrossBilateralFilter/X", "cPhotometricExponent", slider->getValue()); - setUniform("SSAO/HorizonBased/CrossBilateralFilter/Y", "cPhotometricExponent", slider->getValue()); - } - - else if(slider->getName() == SSAO_SAMPLE_LENGTH_EXPONENT_NAME) - setUniform("SSAO/HemisphereMC", "cSampleLengthExponent", slider->getValue()); - } - - void checkBoxToggled(OgreBites::CheckBox *box) override - { - if(box->getName() == SSAO_MODUALTE) - { - if (box->isChecked()) - { - CompositorManager::getSingleton().addCompositor(mViewport, "SSAO/Post/Modulate"); - CompositorManager::getSingleton().setCompositorEnabled(mViewport, "SSAO/Post/Modulate", true); - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - mLight = mSceneMgr->createLight(); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(30, 80, 30))->attachObject(mLight); - } - else - { - mSceneMgr->destroyLight(mLight); - mLight = NULL; - CompositorManager::getSingleton().setCompositorEnabled(mViewport, "SSAO/Post/Modulate", false); - CompositorManager::getSingleton().removeCompositor(mViewport, "SSAO/Post/Modulate"); - } - } - else if (box->getName() == SSAO_SAMPLE_SPACE_NAME) - { - setUniform("SSAO/Crytek", "cSampleInScreenspace", box->isChecked()); - setUniform("SSAO/HorizonBased", "cSampleInScreenspace", box->isChecked()); - setUniform("SSAO/HemisphereMC", "cSampleInScreenspace", box->isChecked()); - setUniform("SSAO/Volumetric", "cSampleInScreenspace", box->isChecked()); - - if (box->isChecked()) // we sample in screen space - { - mTrayMgr->removeWidgetFromTray(SSAO_SAMPLE_LENGTH_WORLDSPACE); - mTrayMgr->getWidget(SSAO_SAMPLE_LENGTH_WORLDSPACE)->hide(); - mTrayMgr->moveWidgetToTray(SSAO_SAMPLE_LENGTH_SCREENSPACE, TL_TOPLEFT); - mTrayMgr->getWidget(SSAO_SAMPLE_LENGTH_SCREENSPACE)->show(); - } - else - { - mTrayMgr->removeWidgetFromTray(SSAO_SAMPLE_LENGTH_SCREENSPACE); - mTrayMgr->getWidget(SSAO_SAMPLE_LENGTH_SCREENSPACE)->hide(); - mTrayMgr->moveWidgetToTray(SSAO_SAMPLE_LENGTH_WORLDSPACE, TL_TOPLEFT); - mTrayMgr->getWidget(SSAO_SAMPLE_LENGTH_WORLDSPACE)->show(); - } - } - } - - // The following three methods are for mouse input - /** @see Sample::pointerPressed. */ - bool mousePressed(const MouseButtonEvent& evt) override - { - if (mTrayMgr->mousePressed(evt)) - return true; - if (evt.button == BUTTON_LEFT) - mTrayMgr->hideCursor(); // hide the cursor if user left-clicks in the scene - - return true; - } - - /** @see Sample::mouseReleased. */ - bool mouseReleased(const MouseButtonEvent& evt) override - { - if (mTrayMgr->mouseReleased(evt)) - return true; - if (evt.button == BUTTON_LEFT) - mTrayMgr->showCursor(); // unhide the cursor if user lets go of LMB - - return true; - } - - /** @see Sample::mouseMoved. */ - bool mouseMoved(const MouseMotionEvent& evt) override - { - // only rotate the camera if cursor is hidden - if (mTrayMgr->isCursorVisible()) - mTrayMgr->mouseMoved(evt); - else - { - mCameraMan->mouseMoved(evt); - static_cast(mTrayMgr->getWidget(SSAO_CAMERA_MENU_NAME))->selectItem(SSAO_USER_CAMERA_ITEM); - } - - return true; - } - - /** - * Set the uniform value in the compositor - * @param material The material that contains the uniform - * @param uniform The name of the uniform parameter - * @param value The value - */ - void setUniform(const String& material, const String& uniform, float value) - { - MaterialManager::getSingleton().getByName(material)->getTechnique(0)-> - getPass(0)->getFragmentProgramParameters()->setNamedConstant(uniform, value); - CompositorManager::getSingleton().getCompositorChain(mViewport)->_markDirty(); - } -}; - - - -#endif /* __SSAO_H__ */ diff --git a/Samples/Simple/include/Shadows.h b/Samples/Simple/include/Shadows.h deleted file mode 100644 index a1b39a6650e..00000000000 --- a/Samples/Simple/include/Shadows.h +++ /dev/null @@ -1,610 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -/** - @file - Shadows.cpp - @brief - Shows a few ways to use Ogre's shadowing techniques -*/ - -#include "SdkSample.h" -#include "OgreBillboard.h" -#include "OgreMovablePlane.h" -#include "OgrePredefinedControllers.h" - -using namespace Ogre; -using namespace OgreBites; - - - -// New depth shadowmapping -String CUSTOM_ROCKWALL_MATERIAL("Ogre/DepthShadowmap/Receiver/RockWall"); -String CUSTOM_CASTER_MATERIAL("PSSM/shadow_caster"); -String CUSTOM_ATHENE_MATERIAL("Ogre/DepthShadowmap/Receiver/Athene"); - -String BASIC_ROCKWALL_MATERIAL("Examples/Rockwall"); -String BASIC_ATHENE_MATERIAL("Examples/Athene/NormalMapped"); - -/** This class 'wibbles' the light and billboard */ -class LightWibbler : public ControllerValue -{ -protected: - Light* mLight; - Billboard* mBillboard; - ColourValue mColourRange; - ColourValue mMinColour; - Real mMinSize; - Real mSizeRange; - float intensity; -public: - LightWibbler(Light* light, Billboard* billboard, const ColourValue& minColour, - const ColourValue& maxColour, Real minSize, Real maxSize) - { - mLight = light; - mBillboard = billboard; - mMinColour = minColour; - mColourRange = maxColour - minColour; - mMinSize = minSize; - mSizeRange = maxSize - minSize; - - } - - float getValue (void) const override - { - return intensity; - } - - void setValue (float value) override - { - intensity = value; - - // Attenuate the brightness of the light - ColourValue newColour = mMinColour + (mColourRange * intensity); - - mLight->setDiffuseColour(newColour); - mBillboard->setColour(newColour); - // set billboard size - float newSize = mMinSize + (intensity * mSizeRange); - mBillboard->setDimensions(newSize, newSize); - } -}; - -Real timeDelay = 0; - - -class _OgreSampleClassExport Sample_Shadows : public SdkSample -{ -protected: - Entity* mAthene; - Entity* pPlaneEnt; - std::vector pColumns; - Light* mLight; - Light* mSunLight; - SceneNode* mLightNode; - AnimationState* mLightAnimationState; - ColourValue mMinLightColour; - ColourValue mMaxLightColour; - Real mMinFlareSize; - Real mMaxFlareSize; - ControllerFloat* mController; - - enum ShadowProjection - { - UNIFORM, - UNIFORM_FOCUSED, - LISPSM, - PLANE_OPTIMAL - }; - - enum ShadowMaterial - { - MAT_STANDARD, - MAT_DEPTH_FLOAT, - MAT_DEPTH_FLOAT_PCF - }; - - ShadowTechnique mCurrentShadowTechnique; - ShadowProjection mCurrentProjection; - ShadowMaterial mCurrentMaterial; - - ShadowCameraSetupPtr mCurrentShadowCameraSetup; - /// Plane that defines plane-optimal shadow mapping basis - MovablePlane* mPlane; -public: - Sample_Shadows() - : mLightNode(0) - , mLightAnimationState(0) - , mMinLightColour(0.2, 0.1, 0.0) - , mMaxLightColour(0.5, 0.3, 0.1) - , mMinFlareSize(40) - , mMaxFlareSize(80) - , mController(0) - , mPlane(0) - { - mInfo["Title"] = "Shadows"; - mInfo["Description"] = "A demonstration of ogre's various shadowing techniques."; - mInfo["Thumbnail"] = "thumb_shadows.png"; - mInfo["Category"] = "Lighting"; - - } - -protected: - - // Just override the mandatory create scene method - void setupContent(void) override - { - mCameraMan->setStyle(CS_ORBIT); - mCameraMan->setYawPitchDist(Degree(0), Degree(45), 400); - - // do this first so we generate edge lists - if (mRoot->getRenderSystem()->getCapabilities()->hasCapability(RSC_HWSTENCIL)) - { - mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_MODULATIVE); - mCurrentShadowTechnique = SHADOWTYPE_STENCIL_MODULATIVE; - } - else - { - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE); - mCurrentShadowTechnique = SHADOWTYPE_TEXTURE_MODULATIVE; - } - // Set ambient light off - mSceneMgr->setAmbientLight(ColourValue(0.0, 0.0, 0.0)); - - // Fixed light, dim - mSunLight = mSceneMgr->createLight(Light::LT_SPOTLIGHT); - - Vector3 pos(1500,1750,1300); - auto ln = mSceneMgr->getRootSceneNode()->createChildSceneNode(pos); - ln->attachObject(mSunLight); - ln->setDirection(-pos.normalisedCopy()); - mSunLight->setSpotlightRange(Degree(30), Degree(50)); - mSunLight->setDiffuseColour(0.35, 0.35, 0.38); - mSunLight->setSpecularColour(0.9, 0.9, 1); - - // Point light, movable, reddish - mLight = mSceneMgr->createLight("Light2"); - mLight->setDiffuseColour(mMinLightColour); - mLight->setSpecularColour(1, 1, 1); - mLight->setAttenuation(8000,1,0.0005,0); - - // Create light node - mLightNode = mSceneMgr->getRootSceneNode()->createChildSceneNode( - "MovingLightNode"); - mLightNode->attachObject(mLight); - // create billboard set - BillboardSet* bbs = mSceneMgr->createBillboardSet("lightbbs", 1); - bbs->setMaterialName("Examples/Flare"); - Billboard* bb = bbs->createBillboard(0,0,0,mMinLightColour); - // attach - mLightNode->attachObject(bbs); - - // create controller, after this is will get updated on its own - ControllerFunctionRealPtr func = WaveformControllerFunction::create(Ogre::WFT_SINE, 0.75, 0.5); - ControllerManager& contMgr = ControllerManager::getSingleton(); - ControllerValueRealPtr val = ControllerValueRealPtr( - new LightWibbler(mLight, bb, mMinLightColour, mMaxLightColour, - mMinFlareSize, mMaxFlareSize)); - mController = contMgr.createController( - contMgr.getFrameTimeSource(), val, func); - - //mLight->setPosition(Vector3(300,250,-300)); - mLightNode->setPosition(Vector3(300,1750,-700)); - - - // Create a track for the light - Animation* anim = mSceneMgr->createAnimation("LightTrack", 20); - // Spline it for nice curves - anim->setInterpolationMode(Animation::IM_SPLINE); - // Create a track to animate the camera's node - NodeAnimationTrack* track = anim->createNodeTrack(0, mLightNode); - // Setup keyframes - TransformKeyFrame* key = track->createNodeKeyFrame(0); // A startposition - key->setTranslate(Vector3(300,750,-700)); - key = track->createNodeKeyFrame(2);//B - key->setTranslate(Vector3(150,800,-250)); - key = track->createNodeKeyFrame(4);//C - key->setTranslate(Vector3(-150,850,-100)); - key = track->createNodeKeyFrame(6);//D - key->setTranslate(Vector3(-400,700,-200)); - key = track->createNodeKeyFrame(8);//E - key->setTranslate(Vector3(-200,700,-400)); - key = track->createNodeKeyFrame(10);//F - key->setTranslate(Vector3(-100,850,-200)); - key = track->createNodeKeyFrame(12);//G - key->setTranslate(Vector3(-100,575,180)); - key = track->createNodeKeyFrame(14);//H - key->setTranslate(Vector3(0,750,300)); - key = track->createNodeKeyFrame(16);//I - key->setTranslate(Vector3(100,850,100)); - key = track->createNodeKeyFrame(18);//J - key->setTranslate(Vector3(250,800,0)); - key = track->createNodeKeyFrame(20);//K == A - key->setTranslate(Vector3(300,750,-700)); - // Create a new animation state to track this - auto animState = mSceneMgr->createAnimationState("LightTrack"); - animState->setEnabled(true); - - auto& controllerMgr = ControllerManager::getSingleton(); - controllerMgr.createFrameTimePassthroughController(AnimationStateControllerValue::create(animState, true)); - - // Make light node look at origin, this is for when we - // change the moving light to a spotlight - mLightNode->setAutoTracking(true, mSceneMgr->getRootSceneNode()); - - // Prepare athene mesh for normalmapping - MeshPtr pAthene = MeshManager::getSingleton().load("athene.mesh", RGN_DEFAULT); - pAthene->buildTangentVectors(); - - SceneNode* node; - node = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mAthene = mSceneMgr->createEntity( "athene", "athene.mesh" ); - mAthene->setMaterialName(BASIC_ATHENE_MATERIAL); - node->attachObject( mAthene ); - node->translate(0,-27, 0); - node->yaw(Degree(90)); - - // Columns - for (int x = -2; x <= 2; ++x) - { - for (int z = -2; z <= 2; ++z) - { - if (x == 0 && z == 0) - continue; - - Entity* pEnt = mSceneMgr->createEntity("column.mesh" ); - pEnt->setMaterialName(BASIC_ROCKWALL_MATERIAL); - pColumns.push_back(pEnt); - node = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(x*300,0, z*300)); - node->attachObject( pEnt ); - } - } - - - // Skybox - mSceneMgr->setSkyBox(true, "Examples/StormySkyBox"); - - // Floor plane (use POSM plane def) - mPlane = new MovablePlane("*mPlane"); - mPlane->normal = Vector3::UNIT_Y; - mPlane->d = 107; - MeshManager::getSingleton().createPlane("Myplane", - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, *mPlane, - 1500,1500,50,50,true,1,5,5,Vector3::UNIT_Z); - pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName(BASIC_ROCKWALL_MATERIAL); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - mSceneMgr->setShadowTextureSettings(1024, 2); - mSceneMgr->setShadowColour(ColourValue(0.5, 0.5, 0.5)); - //mSceneMgr->setShowDebugShadows(true); - - setupGUI(); - } - - void setupView() override - { - SdkSample::setupView(); - - // incase infinite far distance is not supported - mCamera->setFarClipDistance(100000); - } - - void cleanupContent() override - { - ControllerManager::getSingleton().destroyController(mController); - - MeshManager::getSingleton().remove("Myplane", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - pColumns.clear(); - } - - /// Change basic shadow technique - void changeShadowTechnique(ShadowTechnique newTech) - { - mSceneMgr->setShadowTechnique(newTech); - - configureLights(newTech); - updateGUI(newTech); - - mCurrentShadowTechnique = newTech; - } - - void configureLights(ShadowTechnique newTech) - { - Vector3 dir; - switch (newTech) - { - case SHADOWTYPE_STENCIL_MODULATIVE: - // Multiple lights cause obvious silhouette edges in modulative mode - // mSunLight->setCastShadows(false); // turn off shadows on the direct light to fix it - case SHADOWTYPE_STENCIL_ADDITIVE: - // Point light, movable, reddish - mLight->setType(Light::LT_POINT); - break; - case SHADOWTYPE_TEXTURE_MODULATIVE: - case SHADOWTYPE_TEXTURE_ADDITIVE: - // Change moving light to spotlight - mLight->setType(Light::LT_SPOTLIGHT); - mLight->setSpotlightRange(Degree(80),Degree(90)); - break; - default: - break; - }; - - } - - SelectMenu* mTechniqueMenu; - SelectMenu* mLightingMenu; - SelectMenu* mProjectionMenu; - SelectMenu* mMaterialMenu; - - Slider* mFixedBiasSlider; - Slider* mSlopedBiasSlider; - - void setupGUI() - { - mTechniqueMenu = mTrayMgr->createLongSelectMenu( - TL_TOPLEFT, "TechniqueSelectMenu", "Technique", 300, 200, 5); - mTechniqueMenu->addItem("Stencil"); - mTechniqueMenu->addItem("Texture"); - if(mCurrentShadowTechnique & SHADOWDETAILTYPE_STENCIL) - mTechniqueMenu->selectItem("Stencil", false); - else - mTechniqueMenu->selectItem("Texture", false); - - mLightingMenu = mTrayMgr->createLongSelectMenu( - TL_TOPLEFT, "LightingSelectMenu", "Lighting", 300, 200, 5); - mLightingMenu->addItem("Additive"); - mLightingMenu->addItem("Modulative"); - if(mCurrentShadowTechnique == SHADOWTYPE_STENCIL_ADDITIVE) - mLightingMenu->selectItem("Additive", false); - else - mLightingMenu->selectItem("Modulative", false); - - //These values are synchronized with ShadowProjection enum - mProjectionMenu = mTrayMgr->createLongSelectMenu( - TL_TOPLEFT, "ProjectionSelectMenu", "Projection", 300, 200, 5); - mProjectionMenu->addItem("Uniform"); - mProjectionMenu->addItem("Uniform Focused"); - mProjectionMenu->addItem("LiSPSM"); - mProjectionMenu->addItem("Plane Optimal"); - - mMaterialMenu = mTrayMgr->createLongSelectMenu( - TL_TOPLEFT, "MaterialSelectMenu", "Material", 300, 200, 5); - mMaterialMenu->addItem("Standard"); - mMaterialMenu->addItem("Depth Shadowmap"); - mMaterialMenu->addItem("Depth Shadowmap (PCF)"); - - mFixedBiasSlider = mTrayMgr->createThickSlider(TL_NONE, "FixedBiasSlider", "Fixed Bias", 256, 80, 0, 5, 100); - mFixedBiasSlider->setValue(0.5, false); - mFixedBiasSlider->hide(); - - mSlopedBiasSlider = mTrayMgr->createThickSlider(TL_NONE, "SlopedBiasSlider", "Sloped Bias", 256, 80, 0, 10, 100); - mSlopedBiasSlider->setValue(1, false); - mSlopedBiasSlider->hide(); - - updateGUI(mCurrentShadowTechnique); - mTrayMgr->showCursor(); - - // Uncomment this to display the shadow textures - // addTextureDebugOverlay(TL_RIGHT, mSceneMgr->getShadowTexture(0), 0); - // addTextureDebugOverlay(TL_RIGHT, mSceneMgr->getShadowTexture(1), 1); - } - - void updateGUI(ShadowTechnique newTech) - { - if (newTech & SHADOWDETAILTYPE_TEXTURE) - { - mProjectionMenu->show(); - mTrayMgr->moveWidgetToTray(mProjectionMenu, TL_TOPLEFT); - } - else - { - mProjectionMenu->hide(); - mTrayMgr->removeWidgetFromTray(mProjectionMenu); - } - - if((newTech & SHADOWTYPE_TEXTURE_ADDITIVE) == SHADOWTYPE_TEXTURE_ADDITIVE) - { - mMaterialMenu->show(); - mTrayMgr->moveWidgetToTray(mMaterialMenu, TL_TOPLEFT); - } - else - { - mMaterialMenu->hide(); - mTrayMgr->removeWidgetFromTray(mMaterialMenu); - } - } - - void itemSelected(SelectMenu* menu) override - { - if (menu == mTechniqueMenu) handleShadowTypeChanged(); - else if (menu == mLightingMenu) handleShadowTypeChanged(); - else if (menu == mProjectionMenu) handleProjectionChanged(); - else if (menu == mMaterialMenu) handleMaterialChanged(); - } - - - void handleShadowTypeChanged() - { - bool isStencil = mTechniqueMenu->getSelectionIndex() == 0; - bool isAdditive = mLightingMenu->getSelectionIndex() == 0; - ShadowTechnique newTech = ShadowTechnique(mCurrentShadowTechnique & ~SHADOWDETAILTYPE_INTEGRATED); - - if (isStencil) - { - newTech = static_cast( - (newTech & ~SHADOWDETAILTYPE_TEXTURE) | SHADOWDETAILTYPE_STENCIL); - resetMaterials(); - } - else - { - newTech = static_cast( - (newTech & ~SHADOWDETAILTYPE_STENCIL) | SHADOWDETAILTYPE_TEXTURE); - } - - if (isAdditive) - { - newTech = static_cast( - (newTech & ~SHADOWDETAILTYPE_MODULATIVE) | SHADOWDETAILTYPE_ADDITIVE); - } - else - { - mMaterialMenu->selectItem(0); - newTech = static_cast( - (newTech & ~SHADOWDETAILTYPE_ADDITIVE) | SHADOWDETAILTYPE_MODULATIVE); - } - - changeShadowTechnique(newTech); - } - - void handleProjectionChanged() - { - ShadowProjection proj = (ShadowProjection)mProjectionMenu->getSelectionIndex(); - - if (proj != mCurrentProjection) - { - switch(proj) - { - case UNIFORM: - mCurrentShadowCameraSetup = DefaultShadowCameraSetup::create(); - break; - case UNIFORM_FOCUSED: - mCurrentShadowCameraSetup = FocusedShadowCameraSetup::create(); - break; - case LISPSM: - //mLiSPSMSetup->setUseAggressiveFocusRegion(false); - mCurrentShadowCameraSetup = LiSPSMShadowCameraSetup::create(); - break; - case PLANE_OPTIMAL: - mCurrentShadowCameraSetup = PlaneOptimalShadowCameraSetup::create(mPlane); - break; - - }; - mCurrentProjection = proj; - - mSceneMgr->setShadowCameraSetup(mCurrentShadowCameraSetup); - } - } - - void updateDepthShadowParams() - { - auto mat = MaterialManager::getSingleton().getByName(CUSTOM_CASTER_MATERIAL); - auto pass = mat->getTechniques().back()->getPass(0); - pass->setDepthBias(-mFixedBiasSlider->getValue(), -mSlopedBiasSlider->getValue()); - } - - void sliderMoved(Slider* slider) override - { - updateDepthShadowParams(); - } - - void resetMaterials() - { - // Sort out base materials - pPlaneEnt->setMaterialName(BASIC_ROCKWALL_MATERIAL); - mAthene->setMaterialName(BASIC_ATHENE_MATERIAL); - for (std::vector::iterator i = pColumns.begin(); - i != pColumns.end(); ++i) - { - (*i)->setMaterialName(BASIC_ROCKWALL_MATERIAL); - } - } - - void handleMaterialChanged() - { - bool showSliders = false; - ShadowMaterial mat = (ShadowMaterial)mMaterialMenu->getSelectionIndex(); - MaterialPtr themat; - if (mat != mCurrentMaterial) - { - switch(mat) - { - case MAT_STANDARD: - mSceneMgr->setShadowTexturePixelFormat(PF_BYTE_RGBA); - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_ADDITIVE); - - mSceneMgr->setShadowTextureCasterMaterial(MaterialPtr()); - mSceneMgr->setShadowTextureSelfShadow(false); - - resetMaterials(); - - break; - case MAT_DEPTH_FLOAT: - mViewport->setMaterialScheme(MSN_SHADERGEN); // ensure RTSS is enabled - mSceneMgr->setShadowTexturePixelFormat(PF_DEPTH16); - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_ADDITIVE_INTEGRATED); - - themat = MaterialManager::getSingleton().getByName(CUSTOM_CASTER_MATERIAL); - mSceneMgr->setShadowTextureCasterMaterial(themat); - mSceneMgr->setShadowTextureSelfShadow(true); - // Sort out base materials - pPlaneEnt->setMaterialName(CUSTOM_ROCKWALL_MATERIAL); - mAthene->setMaterialName(CUSTOM_ATHENE_MATERIAL); - for (std::vector::iterator i = pColumns.begin(); - i != pColumns.end(); ++i) - { - (*i)->setMaterialName(CUSTOM_ROCKWALL_MATERIAL); - } - - showSliders = true; - - // set the current params - updateDepthShadowParams(); - break; - case MAT_DEPTH_FLOAT_PCF: - mViewport->setMaterialScheme(MSN_SHADERGEN); // ensure RTSS is enabled - mSceneMgr->setShadowTexturePixelFormat(PF_DEPTH16); - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_ADDITIVE_INTEGRATED); - - themat = MaterialManager::getSingleton().getByName(CUSTOM_CASTER_MATERIAL); - mSceneMgr->setShadowTextureCasterMaterial(themat); - mSceneMgr->setShadowTextureSelfShadow(true); - // Sort out base materials - pPlaneEnt->setMaterialName(CUSTOM_ROCKWALL_MATERIAL + "/PCF"); - mAthene->setMaterialName(CUSTOM_ATHENE_MATERIAL + "/PCF"); - for (std::vector::iterator i = pColumns.begin(); - i != pColumns.end(); ++i) - { - (*i)->setMaterialName(CUSTOM_ROCKWALL_MATERIAL + "/PCF"); - } - - showSliders = true; - - // set the current params - updateDepthShadowParams(); - break; - }; - mCurrentMaterial = mat; - - if (showSliders) - { - mFixedBiasSlider->show(); - mTrayMgr->moveWidgetToTray(mFixedBiasSlider, TL_TOPRIGHT); - mSlopedBiasSlider->show(); - mTrayMgr->moveWidgetToTray(mSlopedBiasSlider, TL_TOPRIGHT); - } - else - { - mFixedBiasSlider->hide(); - mTrayMgr->removeWidgetFromTray(mFixedBiasSlider); - mSlopedBiasSlider->hide(); - mTrayMgr->removeWidgetFromTray(mSlopedBiasSlider); - } - - mShaderGenerator->invalidateScheme(MSN_SHADERGEN); - } - } -}; diff --git a/Samples/Simple/include/SkeletalAnimation.h b/Samples/Simple/include/SkeletalAnimation.h deleted file mode 100644 index 95fa115a76b..00000000000 --- a/Samples/Simple/include/SkeletalAnimation.h +++ /dev/null @@ -1,371 +0,0 @@ -#ifndef __SkeletalAnimation_H__ -#define __SkeletalAnimation_H__ - -#include "SdkSample.h" - -#ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS -#include "OgreShaderExHardwareSkinning.h" -#endif -#include "OgreBillboard.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_SkeletalAnimation : public SdkSample -{ - enum VisualiseBoundingBoxMode - { - kVisualiseNone, - kVisualiseOne, - kVisualiseAll - }; -public: - Sample_SkeletalAnimation() : NUM_MODELS(6), ANIM_CHOP(8) - { - mInfo["Title"] = "Skeletal Animation"; - mInfo["Description"] = "A demo of the skeletal animation feature, including spline animation."; - mInfo["Thumbnail"] = "thumb_skelanim.png"; - mInfo["Category"] = "Animation"; - mInfo["Help"] = "Controls:\n" - "WASD to move the camera. Mouse to look around.\n" - "V toggle visualise bounding boxes.\n" - "B toggle bone-based bounding boxes on/off."; - mStatusPanel = NULL; - mVisualiseBoundingBoxMode = kVisualiseNone; - mBoundingBoxModelIndex = 0; - mBoneBoundingBoxes = false; - mBoneBoundingBoxesItemName = "Bone AABBs"; - } - - void setVisualiseBoundingBoxMode( VisualiseBoundingBoxMode mode ) - { - mVisualiseBoundingBoxMode = mode; - for (int i = 0; i < NUM_MODELS; i++) - { - switch (mVisualiseBoundingBoxMode) - { - case kVisualiseNone: - mModelNodes[ i ]->showBoundingBox( false ); - break; - case kVisualiseOne: - mModelNodes[ i ]->showBoundingBox( i == mBoundingBoxModelIndex ); - break; - case kVisualiseAll: - mModelNodes[ i ]->showBoundingBox( true ); - break; - } - } - } - void enableBoneBoundingBoxMode( bool enable ) - { - // update bone bounding box mode for all models - mBoneBoundingBoxes = enable; - for (int iModel = 0; iModel < NUM_MODELS; iModel++) - { - SceneNode* node = mModelNodes[iModel]; - for (unsigned int iObj = 0; iObj < node->numAttachedObjects(); ++iObj) - { - if (Entity* ent = dynamic_cast( node->getAttachedObject( iObj ) )) - { - ent->setUpdateBoundingBoxFromSkeleton( mBoneBoundingBoxes ); - Node::queueNeedUpdate( node ); // when turning off bone bounding boxes, need to force an update - } - } - } - // update status panel - if ( mStatusPanel ) - { - mStatusPanel->setParamValue(mBoneBoundingBoxesItemName, mBoneBoundingBoxes ? "On" : "Off"); - } - } - bool keyPressed(const KeyboardEvent& evt) override - { - if ( !mTrayMgr->isDialogVisible() ) - { - // Handle keypresses. - switch (evt.keysym.sym) - { - case 'v': - // Toggle visualise bounding boxes. - switch (mVisualiseBoundingBoxMode) - { - case kVisualiseNone: - setVisualiseBoundingBoxMode( kVisualiseOne ); - break; - case kVisualiseOne: - setVisualiseBoundingBoxMode( kVisualiseAll ); - break; - case kVisualiseAll: - setVisualiseBoundingBoxMode( kVisualiseNone ); - break; - } - return true; - break; - - case 'b': - { - // Toggle bone based bounding boxes for all models. - enableBoneBoundingBoxMode( ! mBoneBoundingBoxes ); - return true; - } - break; - default: - break; - } - } - return SdkSample::keyPressed(evt); - } - - bool frameRenderingQueued(const FrameEvent& evt) override - { - for (int i = 0; i < NUM_MODELS; i++) - { - if (mAnimStates[i]->getTimePosition() >= ANIM_CHOP) // when it's time to loop... - { - /* We need reposition the scene node origin, since the animation includes translation. - Position is calculated from an offset to the end position, and rotation is calculated - from how much the animation turns the character. */ - - Quaternion rot(Degree(-60), Vector3::UNIT_Y); // how much the animation turns the character - - // find current end position and the offset - Vector3 currEnd = mModelNodes[i]->getOrientation() * mSneakEndPos + mModelNodes[i]->getPosition(); - Vector3 offset = rot * mModelNodes[i]->getOrientation() * -mSneakStartPos; - - mModelNodes[i]->setPosition(currEnd + offset); - mModelNodes[i]->rotate(rot); - - mAnimStates[i]->setTimePosition(0); // reset animation time - } - } - - return SdkSample::frameRenderingQueued(evt); - } - - -protected: - - void setupContent() override - { - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - // Make this viewport work with shader generator scheme. - mShaderGenerator->invalidateScheme(MSN_SHADERGEN); - mViewport->setMaterialScheme(MSN_SHADERGEN); - - //Add the hardware skinning to the shader generator default render state - auto srsHardwareSkinning = mShaderGenerator->createSubRenderState(RTShader::SRS_HARDWARE_SKINNING); - Ogre::RTShader::RenderState* renderState = mShaderGenerator->getRenderState(MSN_SHADERGEN); - renderState->addTemplateSubRenderState(srsHardwareSkinning); - - Ogre::MaterialPtr pCast1 = Ogre::MaterialManager::getSingleton().getByName("Ogre/RTShader/shadow_caster_dq_skinning_1weight"); - Ogre::MaterialPtr pCast2 = Ogre::MaterialManager::getSingleton().getByName("Ogre/RTShader/shadow_caster_dq_skinning_2weight"); - Ogre::MaterialPtr pCast3 = Ogre::MaterialManager::getSingleton().getByName("Ogre/RTShader/shadow_caster_dq_skinning_3weight"); - Ogre::MaterialPtr pCast4 = Ogre::MaterialManager::getSingleton().getByName("Ogre/RTShader/shadow_caster_dq_skinning_4weight"); - - Ogre::RTShader::HardwareSkinningFactory::setCustomShadowCasterMaterials(Ogre::RTShader::ST_DUAL_QUATERNION, - pCast1, pCast2, pCast3, pCast4); - - - auto srs = mShaderGenerator->createSubRenderState(RTShader::SRS_SHADOW_MAPPING); - srs->setParameter("light_count", "2"); - renderState->addTemplateSubRenderState(srs); - - // set shadow properties - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE_INTEGRATED); - mSceneMgr->setShadowTextureCount(2); - mSceneMgr->setShadowTextureSize(512); -#endif - - // add a little ambient lighting - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); - - SceneNode* lightsBbsNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - BillboardSet* bbs; - - // Create billboard set for lights . - bbs = mSceneMgr->createBillboardSet(); - bbs->setMaterialName("Examples/Flare"); - lightsBbsNode->attachObject(bbs); - - - // add a blue spotlight - Light* l = mSceneMgr->createLight(Light::LT_SPOTLIGHT); - Vector3 pos(-40, 180, -10); - SceneNode* ln = mSceneMgr->getRootSceneNode()->createChildSceneNode(pos); - ln->attachObject(l); - ln->setDirection(-pos); - l->setDiffuseColour(0.0, 0.0, 0.5); - bbs->createBillboard(pos)->setColour(l->getDiffuseColour()); - - - // add a green spotlight. - l = mSceneMgr->createLight(Light::LT_SPOTLIGHT); - pos = Vector3(0, 150, -100); - ln = mSceneMgr->getRootSceneNode()->createChildSceneNode(pos); - ln->attachObject(l); - ln->setDirection(-pos); - l->setDiffuseColour(0.0, 0.5, 0.0); - bbs->createBillboard(pos)->setColour(l->getDiffuseColour()); - - // create a floor mesh resource - MeshManager::getSingleton().createPlane("floor", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - Plane(Vector3::UNIT_Y, -1), 250, 250, 25, 25, true, 1, 15, 15, Vector3::UNIT_Z); - - // add a floor to our scene using the floor mesh we created - Entity* floor = mSceneMgr->createEntity("Floor", "floor"); - floor->setMaterialName("Examples/Rockwall"); - floor->setCastShadows(false); - mSceneMgr->getRootSceneNode()->attachObject(floor); - - // set camera initial transform and speed - mCameraMan->setStyle(CS_ORBIT); - mTrayMgr->showCursor(); - mCameraMan->setYawPitchDist(Degree(0), Degree(25), 100); - mCameraMan->setTopSpeed(50); - - setupModels(); - } - - void setupModels() - { - tweakSneakAnim(); - - SceneNode* sn = NULL; - Entity* ent = NULL; - AnimationState* as = NULL; - - // make sure we can get the buffers for bbox calculations - MeshManager::getSingleton().load("jaiqua.mesh", - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY, true, true); - - auto& controllerMgr = ControllerManager::getSingleton(); - - for (int i = 0; i < NUM_MODELS; i++) - { - // create scene nodes for the models at regular angular intervals - sn = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - sn->yaw(Radian(Math::TWO_PI * (float)i / (float)NUM_MODELS)); - sn->translate(0, 0, -20, Node::TS_LOCAL); - mModelNodes.push_back(sn); - - // create and attach a jaiqua entity - ent = mSceneMgr->createEntity("Jaiqua" + StringConverter::toString(i + 1), "jaiqua.mesh"); - ent->setMaterialName("jaiqua"); - sn->attachObject(ent); - - // enable the entity's sneaking animation at a random speed and loop it manually since translation is involved - as = ent->getAnimationState("Sneak"); - as->setEnabled(true); - as->setLoop(false); - - controllerMgr.createController(controllerMgr.getFrameTimeSource(), - AnimationStateControllerValue::create(as, true), - ScaleControllerFunction::create(Math::RangeRandom(0.5, 1.5))); - mAnimStates.push_back(as); - } - - // create name and value for skinning mode - StringVector names; - names.push_back("Help"); - names.push_back("Skinning"); - names.push_back(mBoneBoundingBoxesItemName); - - // create a params panel to display the help and skinning mode - mStatusPanel = mTrayMgr->createParamsPanel(TL_TOPLEFT, "HelpMessage", 200, names); - mStatusPanel->setParamValue("Help", "H / F1"); - String value = "Software"; - enableBoneBoundingBoxMode( false ); // update status panel entry - - // make sure we query the correct scheme - MaterialManager::getSingleton().setActiveScheme(mViewport->getMaterialScheme()); - - // change the value if hardware skinning is enabled - MaterialPtr entityMaterial = ent->getSubEntity(0)->getMaterial(); - if(entityMaterial) - { - Technique* bestTechnique = entityMaterial->getBestTechnique(); - if(bestTechnique) - { - Pass* pass = bestTechnique->getPass(0); - if (pass && pass->hasVertexProgram() && pass->getVertexProgram()->isSkeletalAnimationIncluded()) - { - value = "Hardware"; - } - } - } - mStatusPanel->setParamValue("Skinning", value); - } - - /*----------------------------------------------------------------------------- - | The jaiqua sneak animation doesn't loop properly. This method tweaks the - | animation to loop properly by altering the Spineroot bone track. - -----------------------------------------------------------------------------*/ - void tweakSneakAnim() - { - // get the skeleton, animation, and the node track iterator - SkeletonPtr skel = static_pointer_cast(SkeletonManager::getSingleton().load("jaiqua.skeleton", - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME)); - - for (const auto& it : skel->getAnimation("Sneak")->_getNodeTrackList()) // for every node track... - { - NodeAnimationTrack* track = it.second; - - // get the keyframe at the chopping point - TransformKeyFrame oldKf(0, 0); - track->getInterpolatedKeyFrame(ANIM_CHOP, &oldKf); - - // drop all keyframes after the chopping point - while (track->getKeyFrame(track->getNumKeyFrames()-1)->getTime() >= ANIM_CHOP - 0.3f) - track->removeKeyFrame(track->getNumKeyFrames()-1); - - // create a new keyframe at chopping point, and get the first keyframe - TransformKeyFrame* newKf = track->createNodeKeyFrame(ANIM_CHOP); - TransformKeyFrame* startKf = track->getNodeKeyFrame(0); - - Bone* bone = skel->getBone(track->getHandle()); - - if (bone->getName() == "Spineroot") // adjust spine root relative to new location - { - mSneakStartPos = startKf->getTranslate() + bone->getInitialPosition(); - mSneakEndPos = oldKf.getTranslate() + bone->getInitialPosition(); - mSneakStartPos.y = mSneakEndPos.y; - - newKf->setTranslate(oldKf.getTranslate()); - newKf->setRotation(oldKf.getRotation()); - newKf->setScale(oldKf.getScale()); - } - else // make all other bones loop back - { - newKf->setTranslate(startKf->getTranslate()); - newKf->setRotation(startKf->getRotation()); - newKf->setScale(startKf->getScale()); - } - } - } - - void cleanupContent() override - { - mModelNodes.clear(); - mAnimStates.clear(); - MeshManager::getSingleton().remove("floor", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - } - - const int NUM_MODELS; - const Real ANIM_CHOP; - VisualiseBoundingBoxMode mVisualiseBoundingBoxMode; - int mBoundingBoxModelIndex; // which model to show the bounding box for - bool mBoneBoundingBoxes; - ParamsPanel* mStatusPanel; - String mBoneBoundingBoxesItemName; - - std::vector mModelNodes; - std::vector mAnimStates; - - Vector3 mSneakStartPos; - Vector3 mSneakEndPos; -}; - -#endif diff --git a/Samples/Simple/include/SkyBox.h b/Samples/Simple/include/SkyBox.h deleted file mode 100644 index 7312e1c75c9..00000000000 --- a/Samples/Simple/include/SkyBox.h +++ /dev/null @@ -1,66 +0,0 @@ -#ifndef __SkyBox_H__ -#define __SkyBox_H__ - -#include "SdkSample.h" -#include "OgreParticleSystem.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_SkyBox : public SdkSample -{ -public: - - Sample_SkyBox() - { - mInfo["Title"] = "Sky Box"; - mInfo["Description"] = "Shows how to use skyboxes (fixed-distance cubes used for backgrounds)."; - mInfo["Thumbnail"] = "thumb_skybox.png"; - mInfo["Category"] = "Environment"; - } - -protected: - - void setupContent() override - { - // setup some basic lighting for our scene - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); - mSceneMgr->getRootSceneNode() - ->createChildSceneNode(Vector3(20, 80, 50)) - ->attachObject(mSceneMgr->createLight()); - - mSceneMgr->setSkyBox(true, "Examples/SpaceSkyBox", 5000); // set our skybox - - // create a spaceship model, and place it at the origin - mSceneMgr->getRootSceneNode()->attachObject(mSceneMgr->createEntity("Razor", "razor.mesh")); - - // create a particle system with 200 quota, then set its material and dimensions - ParticleSystem* thrusters = mSceneMgr->createParticleSystem(25); - thrusters->setMaterialName("Examples/Flare"); - thrusters->setDefaultDimensions(25, 25); - - // create two emitters for our thruster particle system - for (unsigned int i = 0; i < 2; i++) - { - ParticleEmitter* emitter = thrusters->addEmitter("Point"); // add a point emitter - - // set the emitter properties - emitter->setAngle(Degree(3)); - emitter->setTimeToLive(0.5); - emitter->setEmissionRate(25); - emitter->setParticleVelocity(25); - emitter->setDirection(Vector3::NEGATIVE_UNIT_Z); - emitter->setColour(ColourValue::White, ColourValue::Red); - emitter->setPosition(Vector3(i == 0 ? 5.7 : -18, 0, 0)); - } - - // attach our thruster particles to the rear of the ship - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 6.5, -67))->attachObject(thrusters); - - // set the camera's initial position and orientation - mCameraNode->setPosition(0, 0, 150); - mCameraNode->yaw(Degree(5)); - } -}; - -#endif diff --git a/Samples/Simple/include/SkyDome.h b/Samples/Simple/include/SkyDome.h deleted file mode 100644 index b600fb8bad8..00000000000 --- a/Samples/Simple/include/SkyDome.h +++ /dev/null @@ -1,74 +0,0 @@ -#ifndef __SkyDome_H__ -#define __SkyDome_H__ - -#include "SdkSample.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_SkyDome : public SdkSample -{ -public: - - Sample_SkyDome() - { - mInfo["Title"] = "Sky Dome"; - mInfo["Description"] = "Shows how to use skydomes (fixed-distance domes used for backgrounds)."; - mInfo["Thumbnail"] = "thumb_skydome.png"; - mInfo["Category"] = "Environment"; - } - - void sliderMoved(Slider* slider) override - { - // use the values from the sliders to update the skydome properties - mSceneMgr->setSkyDome(true, "Examples/CloudySky", mCurvatureSlider->getValue(), mTilingSlider->getValue()); - } - -protected: - - void setupContent() override - { - // setup some basic lighting for our scene - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); - mSceneMgr->getRootSceneNode() - ->createChildSceneNode(Vector3(20, 80, 50)) - ->attachObject(mSceneMgr->createLight()); - - // set our camera to orbit around the origin and show cursor - mCameraMan->setStyle(CS_ORBIT); - mCameraMan->setYawPitchDist(Degree(0), Degree(0), 250); - mTrayMgr->showCursor(); - - // create a floor mesh resource - MeshManager::getSingleton().createPlane("floor", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - Plane(Vector3::UNIT_Y, -30), 1000, 1000, 10, 10, true, 1, 8, 8, Vector3::UNIT_Z); - - // create a floor entity, give it a material, and place it at the origin - Entity* floor = mSceneMgr->createEntity("Floor", "floor"); - floor->setMaterialName("Examples/BumpyMetal"); - mSceneMgr->getRootSceneNode()->attachObject(floor); - - // create an ogre head entity and place it at the origin - mSceneMgr->getRootSceneNode()->attachObject(mSceneMgr->createEntity("Head", "ogrehead.mesh")); - - // create slider bars to control the dome curvature and texture tiling - mCurvatureSlider = mTrayMgr->createThickSlider(TL_TOPLEFT, "Curvature", "Dome Curvature", 200, 60, 0, 50, 11); - mTilingSlider = mTrayMgr->createThickSlider(TL_TOPLEFT, "Tiling", "Dome Tiling", 200, 60, 1, 20, 191); - - /* Here, we set default values for our sliders. We do not need to setup a skydome here, because when - slider values change, the sliderMoved callback is invoked, and we setup the skydome with the appropriate - values in there. See its definition above. */ - mCurvatureSlider->setValue(10); - mTilingSlider->setValue(8); - } - - void cleanupContent() override - { - MeshManager::getSingleton().remove("floor", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - } - - Slider* mCurvatureSlider; - Slider* mTilingSlider; -}; - -#endif diff --git a/Samples/Simple/include/SkyPlane.h b/Samples/Simple/include/SkyPlane.h deleted file mode 100644 index 8c3c3e6c053..00000000000 --- a/Samples/Simple/include/SkyPlane.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef __SkyPlane_H__ -#define __SkyPlane_H__ - -#include "SdkSample.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_SkyPlane : public SdkSample -{ -public: - - Sample_SkyPlane() - { - mInfo["Title"] = "Sky Plane"; - mInfo["Description"] = "Shows how to use skyplanes (fixed-distance planes used for backgrounds)."; - mInfo["Thumbnail"] = "thumb_skyplane.png"; - mInfo["Category"] = "Environment"; - } - -protected: - - void setupContent() override - { - // setup some basic lighting for our scene - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); - mSceneMgr->getRootSceneNode() - ->createChildSceneNode(Vector3(20, 80, 50)) - ->attachObject(mSceneMgr->createLight()); - - // create a skyplane 5000 units away, facing down, 10000 square units large, with 3x texture tiling - mSceneMgr->setSkyPlane(true, Plane(0, -1, 0, 5000), "Examples/SpaceSkyPlane", 10000, 3); - - // and finally... omg it's a DRAGON! - mSceneMgr->getRootSceneNode()->attachObject(mSceneMgr->createEntity("Dragon", "dragon.mesh")); - - // turn around and look at the DRAGON! - mCameraNode->yaw(Degree(210)); - mCameraNode->pitch(Degree(-10)); - } -}; - -#endif diff --git a/Samples/Simple/include/Smoke.h b/Samples/Simple/include/Smoke.h deleted file mode 100644 index 5c33c38e709..00000000000 --- a/Samples/Simple/include/Smoke.h +++ /dev/null @@ -1,59 +0,0 @@ -#ifndef __Smoke_H__ -#define __Smoke_H__ - -#include "SdkSample.h" -#include "OgreParticleSystem.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_Smoke : public SdkSample -{ -public: - - Sample_Smoke() - { - mInfo["Title"] = "Smoke"; - mInfo["Description"] = "Demonstrates depth-sorting and texture-animation of particles."; - mInfo["Thumbnail"] = "thumb_smoke.png"; - mInfo["Category"] = "Effects"; - } - - bool frameRenderingQueued(const FrameEvent& evt) override - { - // spin the head around and make it float up and down - mPivot->setPosition(0, Math::Sin(mRoot->getTimer()->getMilliseconds() / 150.0) * 10, 0); - mPivot->yaw(Radian(-evt.timeSinceLastFrame * 1.5)); - return SdkSample::frameRenderingQueued(evt); - } - -protected: - - void setupContent() override - { - - mSceneMgr->setSkyBox(true, "Examples/EveningSkyBox"); - - // dim orange ambient and two bright orange lights to match the skybox - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.2, 0)); - Light* light = mSceneMgr->createLight(); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(2000, 1000, -1000))->attachObject(light); - light->setDiffuseColour(1, 0.5, 0); - light = mSceneMgr->createLight(); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-2000, 1000, 1000))->attachObject(light); - light->setDiffuseColour(1, 0.5, 0); - - mPivot = mSceneMgr->getRootSceneNode()->createChildSceneNode(); // create a pivot node - - // create a child node and attach an ogre head and some smoke to it - SceneNode* headNode = mPivot->createChildSceneNode(Vector3(100, 0, 0)); - headNode->attachObject(mSceneMgr->createEntity("Head", "ogrehead.mesh")); - headNode->attachObject(mSceneMgr->createParticleSystem("Smoke", "Examples/Smoke")); - - mCameraNode->setPosition(0, 30, 350); - } - - SceneNode* mPivot; -}; - -#endif diff --git a/Samples/Simple/include/SphereMapping.h b/Samples/Simple/include/SphereMapping.h deleted file mode 100644 index a687efc0b69..00000000000 --- a/Samples/Simple/include/SphereMapping.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef __SphereMapping_H__ -#define __SphereMapping_H__ - -#include "SdkSample.h" - -using namespace Ogre; -using namespace OgreBites; - -/* NOTE: This sample simply displays an object with an sphere mapped material. The really relevant stuff -is all in the material script itself. You won't find anything even vaguely related to sphere mapping in -this source code. Check out the Examples/SphereMappedRustySteel material in Examples.material. */ - -class _OgreSampleClassExport Sample_SphereMapping : public SdkSample -{ -public: - - Sample_SphereMapping() - { - mInfo["Title"] = "Sphere Mapping"; - mInfo["Description"] = "Shows the sphere mapping feature of materials. " - "Sphere maps are not wrapped, and look the same from all directions."; - mInfo["Thumbnail"] = "thumb_spheremap.png"; - mInfo["Category"] = "Unsorted"; - } - -protected: - - void setupContent() override - { - mViewport->setBackgroundColour(ColourValue::White); - - // setup some basic lighting for our scene - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); - mSceneMgr->getRootSceneNode() - ->createChildSceneNode(Vector3(20, 80, 50)) - ->attachObject(mSceneMgr->createLight()); - - // set our camera to orbit around the origin and show cursor - mCameraMan->setStyle(CS_ORBIT); - mTrayMgr->showCursor(); - - // create our model, give it the environment mapped material, and place it at the origin - Entity *ent = mSceneMgr->createEntity("Head", "ogrehead.mesh"); - ent->setMaterialName("Examples/SphereMappedRustySteel"); - mSceneMgr->getRootSceneNode()->attachObject(ent); - } -}; - -#endif diff --git a/Samples/Simple/include/Terrain.h b/Samples/Simple/include/Terrain.h deleted file mode 100644 index 79e6c2ed5ad..00000000000 --- a/Samples/Simple/include/Terrain.h +++ /dev/null @@ -1,828 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - - You may use this sample code for anything you like, it is not covered by the - same license as the rest of the engine. - ----------------------------------------------------------------------------- -*/ -#ifndef __Terrain_H__ -#define __Terrain_H__ - -//#define PAGING - -#define TERRAIN_PAGE_MIN_X 0 -#define TERRAIN_PAGE_MIN_Y 0 -#define TERRAIN_PAGE_MAX_X 0 -#define TERRAIN_PAGE_MAX_Y 0 - -#include "OgrePageManager.h" -#include "OgreTerrain.h" -#include "OgreTerrainGroup.h" -#include "OgreTerrainMaterialGeneratorA.h" -#include "OgreTerrainPaging.h" -#include "OgreTerrainQuadTreeNode.h" -#include "SdkSample.h" - -#define TERRAIN_FILE_PREFIX String("testTerrain") -#define TERRAIN_FILE_SUFFIX String("dat") -#define TERRAIN_WORLD_SIZE 12000.0f -#define TERRAIN_SIZE 513 - -#define SHADOWS_IN_LOW_LOD_MATERIAL false - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_Terrain : public SdkSample -{ -public: - Sample_Terrain() - : mTerrainGlobals(0), mTerrainGroup(0), mTerrainPaging(0), mPageManager(0), mFly(false), mParallaxOcclusion(false), - mFallVelocity(0), mMode(MODE_NORMAL), mLayerEdit(1), mBrushSizeTerrainSpace(0.02), mHeightUpdateCountDown(0), - mTerrainPos(1000, 0, 5000), mTerrainsImported(false), mKeyPressed(0) - - { - mInfo["Title"] = "Terrain"; - mInfo["Description"] = "Demonstrates use of the terrain rendering plugin."; - mInfo["Thumbnail"] = "thumb_terrain.png"; - mInfo["Category"] = "Environment"; - mInfo["Help"] = - "Left click and drag anywhere in the scene to look around. Let go again to show " - "cursor and access widgets. Use WASD keys to move. Use +/- keys when in edit mode to change content."; - - // Update terrain at max 20fps - mHeightUpdateRate = 1.0 / 20.0; - } - - void doTerrainModify(Terrain* terrain, const Vector3& centrepos, Real timeElapsed) - { - Vector3 tsPos; - terrain->getTerrainPosition(centrepos, &tsPos); -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - if (mKeyPressed == '+' || mKeyPressed == '-' || mKeyPressed == SDLK_KP_PLUS || mKeyPressed == SDLK_KP_MINUS) - { - switch (mMode) - { - case MODE_EDIT_HEIGHT: - { - // we need point coords - Real terrainSize = (terrain->getSize() - 1); - int startx = (tsPos.x - mBrushSizeTerrainSpace) * terrainSize; - int starty = (tsPos.y - mBrushSizeTerrainSpace) * terrainSize; - int endx = (tsPos.x + mBrushSizeTerrainSpace) * terrainSize; - int endy = (tsPos.y + mBrushSizeTerrainSpace) * terrainSize; - startx = std::max(startx, 0); - starty = std::max(starty, 0); - endx = std::min(endx, (int)terrainSize); - endy = std::min(endy, (int)terrainSize); - for (int y = starty; y <= endy; ++y) - { - for (int x = startx; x <= endx; ++x) - { - Real tsXdist = (x / terrainSize) - tsPos.x; - Real tsYdist = (y / terrainSize) - tsPos.y; - - Real weight = std::min((Real)1.0, Math::Sqrt(tsYdist * tsYdist + tsXdist * tsXdist) / - Real(0.5 * mBrushSizeTerrainSpace)); - weight = 1.0 - (weight * weight); - - float addedHeight = weight * 250.0 * timeElapsed; - float newheight; - if (mKeyPressed == '+' || mKeyPressed == SDLK_KP_PLUS) - newheight = terrain->getHeightAtPoint(x, y) + addedHeight; - else - newheight = terrain->getHeightAtPoint(x, y) - addedHeight; - terrain->setHeightAtPoint(x, y, newheight); - } - } - if (mHeightUpdateCountDown == 0) - mHeightUpdateCountDown = mHeightUpdateRate; - } - break; - case MODE_EDIT_BLEND: - { - TerrainLayerBlendMap* layer = terrain->getLayerBlendMap(mLayerEdit); - // we need image coords - Real imgSize = terrain->getLayerBlendMapSize(); - int startx = (tsPos.x - mBrushSizeTerrainSpace) * imgSize; - int starty = (tsPos.y - mBrushSizeTerrainSpace) * imgSize; - int endx = (tsPos.x + mBrushSizeTerrainSpace) * imgSize; - int endy = (tsPos.y + mBrushSizeTerrainSpace) * imgSize; - startx = std::max(startx, 0); - starty = std::max(starty, 0); - endx = std::min(endx, (int)imgSize); - endy = std::min(endy, (int)imgSize); - for (int y = starty; y <= endy; ++y) - { - for (int x = startx; x <= endx; ++x) - { - Real tsXdist = (x / imgSize) - tsPos.x; - Real tsYdist = (y / imgSize) - tsPos.y; - - Real weight = std::min((Real)1.0, Math::Sqrt(tsYdist * tsYdist + tsXdist * tsXdist) / - Real(0.5 * mBrushSizeTerrainSpace)); - weight = 1.0 - (weight * weight); - - float paint = weight * timeElapsed; - uint32 imgY = imgSize - y; - float val; - if (mKeyPressed == '+' || mKeyPressed == SDLK_KP_PLUS) - val = layer->getBlendValue(x, imgY) + paint; - else - val = layer->getBlendValue(x, imgY) - paint; - val = Math::Clamp(val, 0.0f, 1.0f); - layer->setBlendValue(x, imgY, val); - } - } - - layer->update(); - } - break; - case MODE_NORMAL: - case MODE_COUNT: - break; - }; - } -#endif - } - bool frameRenderingQueued(const FrameEvent& evt) override - { - if (mMode != MODE_NORMAL) - { - // fire ray - Ray ray; - // ray = mCamera->getCameraToViewportRay(0.5, 0.5); - ray = mTrayMgr->getCursorRay(mCamera); - - TerrainGroup::RayResult rayResult = mTerrainGroup->rayIntersects(ray); - if (rayResult.hit) - { - mEditMarker->setVisible(true); - mEditNode->setPosition(rayResult.position); - - // figure out which terrains this affects - TerrainGroup::TerrainList terrainList; - Real brushSizeWorldSpace = TERRAIN_WORLD_SIZE * mBrushSizeTerrainSpace; - Sphere sphere(rayResult.position, brushSizeWorldSpace); - mTerrainGroup->sphereIntersects(sphere, &terrainList); - - for (TerrainGroup::TerrainList::iterator ti = terrainList.begin(); ti != terrainList.end(); ++ti) - doTerrainModify(*ti, rayResult.position, evt.timeSinceLastFrame); - } - else - { - mEditMarker->setVisible(false); - } - } - - if (!mFly) - { - // clamp to terrain - Vector3 camPos = mCameraNode->getPosition(); - Ray ray; - ray.setOrigin(Vector3(camPos.x, mTerrainPos.y + 10000, camPos.z)); - ray.setDirection(Vector3::NEGATIVE_UNIT_Y); - - TerrainGroup::RayResult rayResult = mTerrainGroup->rayIntersects(ray); - Real distanceAboveTerrain = 50; - Real fallSpeed = 300; - Real newy = camPos.y; - if (rayResult.hit) - { - if (camPos.y > rayResult.position.y + distanceAboveTerrain) - { - mFallVelocity += evt.timeSinceLastFrame * 20; - mFallVelocity = std::min(mFallVelocity, fallSpeed); - newy = camPos.y - mFallVelocity * evt.timeSinceLastFrame; - } - newy = std::max(rayResult.position.y + distanceAboveTerrain, newy); - mCameraNode->setPosition(camPos.x, newy, camPos.z); - } - } - - if (mHeightUpdateCountDown > 0) - { - mHeightUpdateCountDown -= evt.timeSinceLastFrame; - if (mHeightUpdateCountDown <= 0) - { - mTerrainGroup->update(); - mHeightUpdateCountDown = 0; - } - } - - //! [loading_label] - if (mTerrainGroup->isDerivedDataUpdateInProgress()) - { - mTrayMgr->moveWidgetToTray(mInfoLabel, TL_TOP, 0); - mInfoLabel->show(); - if (mTerrainsImported) - { - mInfoLabel->setCaption("Building terrain, please wait..."); - } - else - { - mInfoLabel->setCaption("Updating textures, patience..."); - } - } - else - { - mTrayMgr->removeWidgetFromTray(mInfoLabel); - mInfoLabel->hide(); - if (mTerrainsImported) - { - // FIXME does not end up in the correct resource group - // saveTerrains(true); - mTerrainsImported = false; - } - } - //! [loading_label] - - return SdkSample::frameRenderingQueued(evt); // don't forget the parent updates! - } - - void saveTerrains(bool onlyIfModified) { mTerrainGroup->saveAllTerrains(onlyIfModified); } - - bool keyReleased(const KeyboardEvent& evt) override - { - mKeyPressed = 0; - return SdkSample::keyReleased(evt); - } - - bool keyPressed(const KeyboardEvent& e) override - { -#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS - mKeyPressed = e.keysym.sym; - - switch (e.keysym.sym) - { - case 's': - // CTRL-S to save - if (e.keysym.mod & KMOD_CTRL) - { - saveTerrains(true); - } - else - return SdkSample::keyPressed(e); - break; - case SDLK_F10: - // dump - { - for (const auto& ti : mTerrainGroup->getTerrainSlots()) - { - TerrainGroup::TerrainSlot* ts = ti.second; - if (ts->instance && ts->instance->isLoaded()) - { - ts->instance->_dumpTextures("terrain_" + std::to_string(ti.first), ".png"); - } - } - } - break; - /* - case SDLK_F7: - // change terrain size - if (mTerrainGroup->getTerrainSize() == 513) - mTerrainGroup->setTerrainSize(1025); - else - mTerrainGroup->setTerrainSize(513); - break; - case SDLK_F8: - // change terrain world size - if (mTerrainGroup->getTerrainWorldSize() == TERRAIN_WORLD_SIZE) - mTerrainGroup->setTerrainWorldSize(TERRAIN_WORLD_SIZE * 2); - else - mTerrainGroup->setTerrainWorldSize(TERRAIN_WORLD_SIZE); - break; - */ - default: - return SdkSample::keyPressed(e); - } -#endif - - return true; - } - - void itemSelected(SelectMenu* menu) override - { - if (menu == mEditMenu) - { - mMode = (Mode)mEditMenu->getSelectionIndex(); - } - else if (menu == mShadowsMenu) - { - mShadowMode = (ShadowMode)mShadowsMenu->getSelectionIndex(); - changeShadows(); - } - } - - void checkBoxToggled(CheckBox* box) override - { - if (box == mFlyBox) - { - mFly = mFlyBox->isChecked(); - } - if (box == mParallaxOcclusionBox) - { - mParallaxOcclusion = mParallaxOcclusionBox->isChecked(); - changeShadows(); - } - } - -protected: - TerrainGlobalOptions* mTerrainGlobals; - TerrainGroup* mTerrainGroup; - bool mPaging; - TerrainPaging* mTerrainPaging; - PageManager* mPageManager; -#ifdef PAGING - /// This class just pretends to provide prcedural page content to avoid page loading - class DummyPageProvider : public PageProvider - { - public: - bool prepareProceduralPage(Page* page, PagedWorldSection* section) { return true; } - bool loadProceduralPage(Page* page, PagedWorldSection* section) { return true; } - bool unloadProceduralPage(Page* page, PagedWorldSection* section) { return true; } - bool unprepareProceduralPage(Page* page, PagedWorldSection* section) { return true; } - }; - DummyPageProvider mDummyPageProvider; -#endif - bool mFly; - bool mParallaxOcclusion; - Real mFallVelocity; - enum Mode - { - MODE_NORMAL = 0, - MODE_EDIT_HEIGHT = 1, - MODE_EDIT_BLEND = 2, - MODE_COUNT = 3 - }; - enum ShadowMode - { - SHADOWS_NONE = 0, - SHADOWS_COLOUR = 1, - SHADOWS_DEPTH = 2, - SHADOWS_COUNT = 3 - }; - Mode mMode; - ShadowMode mShadowMode; - Ogre::uint8 mLayerEdit; - Real mBrushSizeTerrainSpace; - SceneNode* mEditNode; - Entity* mEditMarker; - Real mHeightUpdateCountDown; - Real mHeightUpdateRate; - Vector3 mTerrainPos; - SelectMenu* mEditMenu; - SelectMenu* mShadowsMenu; - CheckBox* mFlyBox; - CheckBox* mParallaxOcclusionBox; - //! [infolabel] - OgreBites::Label* mInfoLabel = nullptr; - //! [infolabel] - bool mTerrainsImported; - ShadowCameraSetupPtr mPSSMSetup; - - typedef std::list EntityList; - EntityList mHouseList; - - Keycode mKeyPressed; - - void defineTerrain(long x, long y, bool flat = false) - { - // if a file is available, use it - // if not, generate file from import - - // Usually in a real project you'll know whether the compact terrain data is - // available or not; I'm doing it this way to save distribution size - - if (flat) - { - mTerrainGroup->defineTerrain(x, y, 0.0f); - return; - } - - //! [define] - String filename = mTerrainGroup->generateFilename(x, y); - if (ResourceGroupManager::getSingleton().resourceExists(mTerrainGroup->getResourceGroup(), filename)) - { - mTerrainGroup->defineTerrain(x, y); - } - else - { - Image img; - getTerrainImage(x % 2 != 0, y % 2 != 0, img); - mTerrainGroup->defineTerrain(x, y, &img); - mTerrainsImported = true; - } - //! [define] - } - - void getTerrainImage(bool flipX, bool flipY, Image& img) - { - //! [heightmap] - img.load("terrain.png", mTerrainGroup->getResourceGroup()); - if (flipX) - img.flipAroundY(); - if (flipY) - img.flipAroundX(); - //! [heightmap] - } - - void initBlendMaps(Terrain* terrain) - { - //! [blendmap] - using namespace Ogre; - TerrainLayerBlendMap* blendMap0 = terrain->getLayerBlendMap(1); - TerrainLayerBlendMap* blendMap1 = terrain->getLayerBlendMap(2); - float minHeight0 = 20; - float fadeDist0 = 15; - float minHeight1 = 70; - float fadeDist1 = 15; - float* pBlend0 = blendMap0->getBlendPointer(); - float* pBlend1 = blendMap1->getBlendPointer(); - for (uint16 y = 0; y < terrain->getLayerBlendMapSize(); ++y) - { - for (uint16 x = 0; x < terrain->getLayerBlendMapSize(); ++x) - { - Real tx, ty; - - blendMap0->convertImageToTerrainSpace(x, y, &tx, &ty); - float height = terrain->getHeightAtTerrainPosition(tx, ty); - - *pBlend0++ = Math::saturate((height - minHeight0) / fadeDist0); - *pBlend1++ = Math::saturate((height - minHeight1) / fadeDist1); - } - } - blendMap0->dirty(); - blendMap1->dirty(); - blendMap0->update(); - blendMap1->update(); - //! [blendmap] - // set up a colour map - /* - if (!terrain->getGlobalColourMapEnabled()) - { - terrain->setGlobalColourMapEnabled(true); - Image colourMap; - colourMap.load("testcolourmap.jpg", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - terrain->getGlobalColourMap()->loadImage(colourMap); - } - */ - } - - void configureTerrainDefaults(Light* l) - { - //! [configure_lod] - mTerrainGlobals->setMaxPixelError(8); - mTerrainGlobals->setCompositeMapDistance(3000); - //! [configure_lod] - - // mTerrainGlobals->setUseRayBoxDistanceCalculation(true); - // mTerrainGlobals->getDefaultMaterialGenerator()->setDebugLevel(1); - // mTerrainGlobals->setLightMapSize(256); - - TerrainMaterialGeneratorA::SM2Profile* matProfile = static_cast( - mTerrainGlobals->getDefaultMaterialGenerator()->getActiveProfile()); - - // Disable the lightmap for OpenGL ES 2.0. The minimum number of samplers allowed is 8(as opposed to 16 on - // desktop). Otherwise we will run over the limit by just one. The minimum was raised to 16 in GL ES 3.0. - if (Ogre::Root::getSingletonPtr()->getRenderSystem()->getCapabilities()->getNumTextureUnits() < 9) - { - matProfile->setLightmapEnabled(false); - } - - // Disable steep parallax by default - matProfile->setLayerParallaxOcclusionMappingEnabled(false); - - //! [composite_lighting] - // Important to set these so that the terrain knows what to use for baked (non-realtime) data - mTerrainGlobals->setLightMapDirection(l->getDerivedDirection()); - mTerrainGlobals->setCompositeMapAmbient(mSceneMgr->getAmbientLight()); - mTerrainGlobals->setCompositeMapDiffuse(l->getDiffuseColour()); - //! [composite_lighting] - // mTerrainGlobals->setCompositeMapAmbient(ColourValue::Red); - - // Configure default import settings for if we use imported image - //! [import_settings] - Ogre::Terrain::ImportData& defaultimp = mTerrainGroup->getDefaultImportSettings(); - defaultimp.inputScale = 600; - defaultimp.minBatchSize = 33; - defaultimp.maxBatchSize = 65; - //! [import_settings] - - //! [tex_from_src] - Image combined; - combined.loadTwoImagesAsRGBA("Ground23_col.jpg", "Ground23_spec.png", "General"); - TextureManager::getSingleton().loadImage("Ground23_diffspec", "General", combined); - //! [tex_from_src] - - //! [textures] - defaultimp.layerList.resize(3); - defaultimp.layerList[0].worldSize = 200; - defaultimp.layerList[0].textureNames.push_back("Ground37_diffspec.dds"); - defaultimp.layerList[0].textureNames.push_back("Ground37_normheight.dds"); - defaultimp.layerList[1].worldSize = 200; - defaultimp.layerList[1].textureNames.push_back("Ground23_diffspec"); // loaded from memory - defaultimp.layerList[1].textureNames.push_back("Ground23_normheight.dds"); - defaultimp.layerList[2].worldSize = 400; - defaultimp.layerList[2].textureNames.push_back("Rock20_diffspec.dds"); - defaultimp.layerList[2].textureNames.push_back("Rock20_normheight.dds"); - //! [textures] - } - - void addTextureShadowDebugOverlay(TrayLocation loc, size_t num) - { - for (size_t i = 0; i < num; ++i) - { - TexturePtr shadowTex = mSceneMgr->getShadowTexture(i); - addTextureDebugOverlay(loc, shadowTex, i); - } - } - - void changeShadows() { configureShadows(mShadowMode != SHADOWS_NONE, mShadowMode == SHADOWS_DEPTH); } - - void configureShadows(bool enabled, bool depthShadows) - { - auto matProfile = static_cast( - mTerrainGlobals->getDefaultMaterialGenerator()->getActiveProfile()); - matProfile->setReceiveDynamicShadowsEnabled(enabled); - matProfile->setReceiveDynamicShadowsLowLod(SHADOWS_IN_LOW_LOD_MATERIAL); - - RTShader::RenderState* schemRenderState = mShaderGenerator->getRenderState(MSN_SHADERGEN); - if (auto srs = schemRenderState->getSubRenderState(RTShader::SRS_SHADOW_MAPPING)) - { - schemRenderState->removeSubRenderState(srs); - } - - if (enabled) - { - // General scene setup - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_ADDITIVE_INTEGRATED); - mSceneMgr->setShadowFarDistance(3000); - - // 3 textures per directional light (PSSM) - mSceneMgr->setShadowTextureCountPerLightType(Ogre::Light::LT_DIRECTIONAL, 3); - - if (!mPSSMSetup) - { - // shadow camera setup - PSSMShadowCameraSetup* pssmSetup = new PSSMShadowCameraSetup(); - pssmSetup->setSplitPadding(mCamera->getNearClipDistance() * 2); - pssmSetup->calculateSplitPoints(3, mCamera->getNearClipDistance(), mSceneMgr->getShadowFarDistance()); - pssmSetup->setOptimalAdjustFactor(0, 2); - pssmSetup->setOptimalAdjustFactor(1, 1); - pssmSetup->setOptimalAdjustFactor(2, 0.5); - - mPSSMSetup.reset(pssmSetup); - } - mSceneMgr->setShadowCameraSetup(mPSSMSetup); - - if (depthShadows) - { - mSceneMgr->setShadowTextureCount(3); - mSceneMgr->setShadowTextureConfig(0, 2048, 2048, PF_DEPTH16); - mSceneMgr->setShadowTextureConfig(1, 1024, 1024, PF_DEPTH16); - mSceneMgr->setShadowTextureConfig(2, 1024, 1024, PF_DEPTH16); - mSceneMgr->setShadowTextureSelfShadow(true); - mSceneMgr->setShadowCasterRenderBackFaces(true); - - auto subRenderState = mShaderGenerator->createSubRenderState(RTShader::SRS_SHADOW_MAPPING); - subRenderState->setParameter("split_points", - static_cast(mPSSMSetup.get())->getSplitPoints()); - schemRenderState->addTemplateSubRenderState(subRenderState); - - mSceneMgr->setShadowTextureCasterMaterial( - MaterialManager::getSingleton().getByName("PSSM/shadow_caster")); - } - else - { - mSceneMgr->setShadowTextureCount(3); - mSceneMgr->setShadowTextureConfig(0, 2048, 2048, PF_X8B8G8R8); - mSceneMgr->setShadowTextureConfig(1, 1024, 1024, PF_X8B8G8R8); - mSceneMgr->setShadowTextureConfig(2, 1024, 1024, PF_X8B8G8R8); - mSceneMgr->setShadowTextureSelfShadow(false); - mSceneMgr->setShadowCasterRenderBackFaces(false); - mSceneMgr->setShadowTextureCasterMaterial(MaterialPtr()); - } - - matProfile->setReceiveDynamicShadowsPSSM(static_cast(mPSSMSetup.get())); - - // addTextureShadowDebugOverlay(TL_RIGHT, 3); - } - else - { - mSceneMgr->setShadowTechnique(SHADOWTYPE_NONE); - } - - // Update parallax occlusion - matProfile->setLayerParallaxOcclusionMappingEnabled(mParallaxOcclusion); - - mShaderGenerator->invalidateScheme(MSN_SHADERGEN); - } - - /*----------------------------------------------------------------------------- - | Extends setupView to change some initial camera settings for this sample. - -----------------------------------------------------------------------------*/ - void setupView() override - { - SdkSample::setupView(); - // Make this viewport work with shader generator scheme. - mViewport->setMaterialScheme(MSN_SHADERGEN); - - //! [camera_setup] - mCameraNode->setPosition(mTerrainPos + Vector3(1683, 50, 2116)); - mCameraNode->lookAt(Vector3(1963, 50, 1660), Node::TS_PARENT); - mCamera->setNearClipDistance(40); // tight near plane important for shadows - mCamera->setFarClipDistance(50000); - //! [camera_setup] - - //! [camera_inf] - mCamera->setFarClipDistance(0); // enable infinite far clip distance - //! [camera_inf] - } - - void setupControls() - { - mTrayMgr->showCursor(); - - // make room for the controls - mTrayMgr->showLogo(TL_TOPRIGHT); - mTrayMgr->showFrameStats(TL_TOPRIGHT); - mTrayMgr->toggleAdvancedFrameStats(); - - //! [infolabel_create] - mInfoLabel = mTrayMgr->createLabel(TL_TOP, "TInfo", "", 350); - //! [infolabel_create] - - mEditMenu = mTrayMgr->createLongSelectMenu(TL_BOTTOM, "EditMode", "Edit Mode", 370, 250, 3); - mEditMenu->addItem("None"); - mEditMenu->addItem("Elevation"); - mEditMenu->addItem("Blend"); - mEditMenu->selectItem(0); // no edit mode - - mFlyBox = mTrayMgr->createCheckBox(TL_BOTTOM, "Fly", "Fly"); - mFlyBox->setChecked(false, false); - - mParallaxOcclusionBox = mTrayMgr->createCheckBox(TL_BOTTOM, "ParallaxOcclusion", "Parallax Occlusion Mapping"); - mParallaxOcclusionBox->setChecked(false, false); - - mShadowsMenu = mTrayMgr->createLongSelectMenu(TL_BOTTOM, "Shadows", "Shadows", 370, 250, 3); - mShadowsMenu->addItem("None"); - mShadowsMenu->addItem("Colour Shadows"); - mShadowsMenu->addItem("Depth Shadows"); - mShadowsMenu->selectItem(0); // no edit mode - - // a friendly reminder - StringVector names; - names.push_back("Help"); - mTrayMgr->createParamsPanel(TL_TOPLEFT, "Help", 100, names)->setParamValue(0, "H/F1"); - } - - void setupContent() override - { - //! [global_opts] - mTerrainGlobals = new Ogre::TerrainGlobalOptions(); - //! [global_opts] - - mEditMarker = mSceneMgr->createEntity("editMarker", "sphere.mesh"); - mEditNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mEditNode->attachObject(mEditMarker); - mEditNode->setScale(0.05, 0.05, 0.05); - - setupControls(); - - mCameraMan->setTopSpeed(50); - - setDragLook(true); - -#if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID - MaterialManager::getSingleton().setDefaultTextureFiltering(TFO_ANISOTROPIC); - MaterialManager::getSingleton().setDefaultAnisotropy(8); -#endif - - ColourValue fadeColour(0.7, 0.7, 0.8); - //! [linear_fog] - mSceneMgr->setFog(Ogre::FOG_LINEAR, fadeColour, 0, 2000, 10000); - //! [linear_fog] - - LogManager::getSingleton().setMinLogLevel(LML_TRIVIAL); - - //! [light] - Ogre::Light* l = mSceneMgr->createLight(); - l->setType(Ogre::Light::LT_DIRECTIONAL); - l->setDiffuseColour(ColourValue::White); - l->setSpecularColour(ColourValue(0.4, 0.4, 0.4)); - - Ogre::SceneNode* ln = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - ln->setDirection(Vector3(0.55, -0.3, 0.75).normalisedCopy()); - ln->attachObject(l); - //! [light] - mSceneMgr->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); - - //! [terrain_create] - mTerrainGroup = new Ogre::TerrainGroup(mSceneMgr, Ogre::Terrain::ALIGN_X_Z, TERRAIN_SIZE, TERRAIN_WORLD_SIZE); - mTerrainGroup->setFilenameConvention(TERRAIN_FILE_PREFIX, TERRAIN_FILE_SUFFIX); - mTerrainGroup->setOrigin(mTerrainPos); - //! [terrain_create] - - configureTerrainDefaults(l); -#ifdef PAGING - // Paging setup - mPageManager = OGRE_NEW PageManager(); - // Since we're not loading any pages from .page files, we need a way just - // to say we've loaded them without them actually being loaded - mPageManager->setPageProvider(&mDummyPageProvider); - mPageManager->addCamera(mCamera); - mTerrainPaging = OGRE_NEW TerrainPaging(mPageManager); - PagedWorld* world = mPageManager->createWorld(); - mTerrainPaging->createWorldSection(world, mTerrainGroup, 2000, 3000, TERRAIN_PAGE_MIN_X, TERRAIN_PAGE_MIN_Y, - TERRAIN_PAGE_MAX_X, TERRAIN_PAGE_MAX_Y); -#else - //! [define_loop] - for (long x = TERRAIN_PAGE_MIN_X; x <= TERRAIN_PAGE_MAX_X; ++x) - for (long y = TERRAIN_PAGE_MIN_Y; y <= TERRAIN_PAGE_MAX_Y; ++y) - defineTerrain(x, y); - // sync load since we want everything in place when we start - mTerrainGroup->loadAllTerrains(true); - //! [define_loop] -#endif - - //! [init_blend] - if (mTerrainsImported) - { - for (const auto& ti : mTerrainGroup->getTerrainSlots()) - { - initBlendMaps(ti.second->instance); - } - } - - mTerrainGroup->freeTemporaryResources(); - //! [init_blend] - - // create a few entities on the terrain - Entity* e = mSceneMgr->createEntity("tudorhouse.mesh"); - Vector3 entPos(mTerrainPos.x + 2043, 0, mTerrainPos.z + 1715); - Quaternion rot; - entPos.y = mTerrainGroup->getHeightAtWorldPosition(entPos) + 65.5 + mTerrainPos.y; - rot.FromAngleAxis(Degree(Math::RangeRandom(-180, 180)), Vector3::UNIT_Y); - SceneNode* sn = mSceneMgr->getRootSceneNode()->createChildSceneNode(entPos, rot); - sn->setScale(Vector3(0.12, 0.12, 0.12)); - sn->attachObject(e); - mHouseList.push_back(e); - - e = mSceneMgr->createEntity("tudorhouse.mesh"); - entPos = Vector3(mTerrainPos.x + 1850, 0, mTerrainPos.z + 1478); - entPos.y = mTerrainGroup->getHeightAtWorldPosition(entPos) + 65.5 + mTerrainPos.y; - rot.FromAngleAxis(Degree(Math::RangeRandom(-180, 180)), Vector3::UNIT_Y); - sn = mSceneMgr->getRootSceneNode()->createChildSceneNode(entPos, rot); - sn->setScale(Vector3(0.12, 0.12, 0.12)); - sn->attachObject(e); - mHouseList.push_back(e); - - e = mSceneMgr->createEntity("tudorhouse.mesh"); - entPos = Vector3(mTerrainPos.x + 1970, 0, mTerrainPos.z + 2180); - entPos.y = mTerrainGroup->getHeightAtWorldPosition(entPos) + 65.5 + mTerrainPos.y; - rot.FromAngleAxis(Degree(Math::RangeRandom(-180, 180)), Vector3::UNIT_Y); - sn = mSceneMgr->getRootSceneNode()->createChildSceneNode(entPos, rot); - sn->setScale(Vector3(0.12, 0.12, 0.12)); - sn->attachObject(e); - mHouseList.push_back(e); - - //! [skybox] - mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); - //! [skybox] - } - - void _shutdown() override - { - if (mTerrainPaging) - { - OGRE_DELETE mTerrainPaging; - mTerrainPaging = 0; - OGRE_DELETE mPageManager; - mPageManager = 0; - } - else if (mTerrainGroup) - { - OGRE_DELETE mTerrainGroup; - mTerrainGroup = 0; - } - - if (mTerrainGlobals) - { - OGRE_DELETE mTerrainGlobals; - mTerrainGlobals = 0; - } - - mHouseList.clear(); - - SdkSample::_shutdown(); - } -}; - -#endif \ No newline at end of file diff --git a/Samples/Simple/include/Tessellation.h b/Samples/Simple/include/Tessellation.h deleted file mode 100644 index 846365746aa..00000000000 --- a/Samples/Simple/include/Tessellation.h +++ /dev/null @@ -1,52 +0,0 @@ -#ifndef __Tessellation_H__ -#define __Tessellation_H__ - -#include "SdkSample.h" -#include "OgreImage.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_Tessellation : public SdkSample -{ - public: - - Sample_Tessellation() - { - mInfo["Title"] = "Tessellation"; - mInfo["Description"] = "Sample for tessellation support (Hull, Domain shaders)"; - mInfo["Thumbnail"] = "thumb_tessellation.png"; - mInfo["Category"] = "Unsorted"; - mInfo["Help"] = "Top Left: Multi-frame\nTop Right: Scrolling\nBottom Left: Rotation\nBottom Right: Scaling"; - } - - void testCapabilities(const RenderSystemCapabilities* caps) override - { - requireMaterial("Ogre/TessellationExample"); - } - - protected: - - void setupContent() override - { - // set our camera - mTrayMgr->showCursor(); - mCameraNode->setPosition(0, 0, 20); - mCameraMan->setStyle(CS_ORBIT); - - // create a plain with float3 tex cord - ManualObject* tObject = mSceneMgr->createManualObject("TesselatedObject"); - - // create a triangle that uses our material - tObject->begin("Ogre/TessellationExample", RenderOperation::OT_TRIANGLE_LIST); - tObject->position(-10, -10, 0); - tObject->position(0, 10, 0); - tObject->position(10, -10, 0); - tObject->end(); - - // attach it to a node and position appropriately - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(tObject); - } -}; - -#endif diff --git a/Samples/Simple/include/TextureArray.h b/Samples/Simple/include/TextureArray.h deleted file mode 100644 index a8ee2c5659e..00000000000 --- a/Samples/Simple/include/TextureArray.h +++ /dev/null @@ -1,99 +0,0 @@ -#ifndef __TextureArray_H__ -#define __TextureArray_H__ - -#include "SdkSample.h" -#include "OgreImage.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_TextureArray : public SdkSample -{ -public: - - Sample_TextureArray() - { - mInfo["Title"] = "Texture Array"; - mInfo["Description"] = "Demonstrates texture array support."; - mInfo["Thumbnail"] = "thumb_texarray.png"; - mInfo["Category"] = "Unsorted"; - mInfo["Help"] = "Top Left: Multi-frame\nTop Right: Scrolling\nBottom Left: Rotation\nBottom Right: Scaling"; - } - -protected: - - void testCapabilities( const RenderSystemCapabilities* caps ) override - { - requireMaterial("Examples/TextureArray"); - } - - void setupContent() override - { - mSceneMgr->setSkyBox(true, "Examples/TrippySkyBox"); - - // set our camera to orbit around the origin and show cursor - mCameraMan->setStyle(CS_ORBIT); - mTrayMgr->showCursor(); - - // the names of the textures we will use (all need to be the same size: 512*512 in our case) - std::vector texNames; - texNames.push_back("BeachStones.jpg"); - texNames.push_back("BumpyMetal.jpg"); - texNames.push_back("egyptrockyfull.jpg"); - texNames.push_back("frost.png"); - texNames.push_back("MtlPlat2.jpg"); - texNames.push_back("nskingr.jpg"); - texNames.push_back("Panels_Diffuse.png"); - texNames.push_back("Panels_reflection.png"); - texNames.push_back("RustedMetal.jpg"); - texNames.push_back("spacesky.jpg"); - texNames.push_back("terrain_texture.jpg"); - texNames.push_back("texmap2.jpg"); - texNames.push_back("Water01.jpg"); - texNames.push_back("Water02.jpg"); - texNames.push_back("body.jpg"); - texNames.push_back("stone1.jpg"); - texNames.push_back("wall3.jpg"); - texNames.push_back("sinbad_body.tga"); - texNames.push_back("sinbad_clothes.tga"); - texNames.push_back("stevecube_bk.jpg"); - - // create material and set the texture unit to our texture - MaterialPtr texArrayMat = MaterialManager::getSingleton().getByName("Examples/TextureArray", RGN_DEFAULT); - texArrayMat->compile(); - Pass * pass = texArrayMat->getBestTechnique()->getPass(0); - pass->setLightingEnabled(false); - pass->createTextureUnitState()->setLayerArrayNames(TEX_TYPE_2D_ARRAY, texNames); - - // create a plane with float3 tex coord - the third value will be the texture index in our case - ManualObject* textureArrayObject = mSceneMgr->createManualObject("TextureAtlasObject"); - - // create a quad that uses our material - int quadSize = 100; - textureArrayObject->begin(texArrayMat->getName(), RenderOperation::OT_TRIANGLE_LIST); - // triangle 0 of the quad - textureArrayObject->position(0, 0, 0); - textureArrayObject->textureCoord(0, 0, 0); - textureArrayObject->position(quadSize, 0, 0); - textureArrayObject->textureCoord(1, 0, 0); - textureArrayObject->position(quadSize, quadSize, 0); - textureArrayObject->textureCoord(1, 1, texNames.size()); - - // triangle 1 of the quad - textureArrayObject->position(0, 0, 0); - textureArrayObject->textureCoord(0, 0, 0); - textureArrayObject->position(quadSize, quadSize, 0); - textureArrayObject->textureCoord(1, 1, texNames.size()); - textureArrayObject->position(0, quadSize, 0); - textureArrayObject->textureCoord(0, 1, texNames.size()); - - textureArrayObject->end(); - - // attach it to a node and position appropriately - SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - node->setPosition(-quadSize / 2, -quadSize / 2, 0); - node->attachObject(textureArrayObject); - } -}; - -#endif diff --git a/Samples/Simple/include/TextureFX.h b/Samples/Simple/include/TextureFX.h deleted file mode 100644 index d8e1725ca96..00000000000 --- a/Samples/Simple/include/TextureFX.h +++ /dev/null @@ -1,57 +0,0 @@ -#ifndef __TextureFX_H__ -#define __TextureFX_H__ - -#include "SdkSample.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_TextureFX : public SdkSample -{ -public: - - Sample_TextureFX() - { - mInfo["Title"] = "Texture Effects"; - mInfo["Description"] = "Demonstrates OGRE's many different animated texture effects."; - mInfo["Thumbnail"] = "thumb_texfx.png"; - mInfo["Category"] = "Unsorted"; - mInfo["Help"] = "Top Left: Multi-frame\nTop Right: Scrolling\nBottom Left: Rotation\nBottom Right: Scaling"; - - addScreenshotFrame(50); - } - -protected: - - void setupContent() override - { - mSceneMgr->setSkyBox(true, "Examples/TrippySkyBox"); - - // set our camera to orbit around the origin and show cursor - mCameraMan->setStyle(CS_ORBIT); - - if (mTrayMgr) - { - mTrayMgr->showCursor(); - } - - // the names of the four materials we will use - String matNames[] = {"Examples/OgreDance", "Examples/OgreParade", "Examples/OgreSpin", "Examples/OgreWobble"}; - - for (unsigned int i = 0; i < 4; i++) - { - // create a standard plane entity - Entity* ent = mSceneMgr->createEntity("Plane" + StringConverter::toString(i + 1), SceneManager::PT_PLANE); - - // attach it to a node, scale it, and position appropriately - SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - node->setPosition(i % 2 ? 25 : -25, i / 2 ? -25 : 25, 0); - node->setScale(0.25, 0.25, 0.25); - node->attachObject(ent); - - ent->setMaterialName(matNames[i]); // give it the material we prepared - } - } -}; - -#endif diff --git a/Samples/Simple/include/Transparency.h b/Samples/Simple/include/Transparency.h deleted file mode 100644 index 16c2fb35bf4..00000000000 --- a/Samples/Simple/include/Transparency.h +++ /dev/null @@ -1,119 +0,0 @@ -#ifndef __Transparency_H__ -#define __Transparency_H__ - -#include "SdkSample.h" - -using namespace Ogre; -using namespace OgreBites; - -/* NOTE: This sample simply displays an object with a transparent material. The really relevant stuff -is all in the material script itself. You won't find anything even vaguely related to transparency in -this source code. Check out the Examples/WaterStream material in Examples.material. */ - -class _OgreSampleClassExport Sample_Transparency : public SdkSample -{ -public: - - Sample_Transparency() - { - mInfo["Title"] = "Transparency"; - mInfo["Description"] = "Demonstrates the use of transparent materials (or scene blending)."; - mInfo["Thumbnail"] = "thumb_trans.png"; - mInfo["Category"] = "Lighting"; - - addScreenshotFrame(25); - } - - bool frameRenderingQueued(const FrameEvent& evt) override - { - Real theta = ControllerManager::getSingleton().getElapsedTime(); - - // this is the equation for a PQ torus knot - Ogre::Real r = 28 * (2 + Math::Sin(theta * 3 / 2 + 0.2)); - Ogre::Real x = r * Math::Cos(theta); - Ogre::Real y = r * Math::Sin(theta); - Ogre::Real z = 60 * Math::Cos(theta * 3 / 2 + 0.2); - - Vector3 lastPos = mFishNode->getPosition(); // save fishy's last position - mFishNode->setPosition(x, y, z); // set fishy's new position - - // set fishy's direction based on the change in position - mFishNode->setDirection(mFishNode->getPosition() - lastPos, Node::TS_PARENT, Vector3::NEGATIVE_UNIT_X); - - mFishSwim->addTime(evt.timeSinceLastFrame * 5); // update fishy's swimming animation - - return SdkSample::frameRenderingQueued(evt); // don't forget the parent class updates! - } - -protected: - - void checkBoxToggled(CheckBox* box) override - { - auto& cm = CompositorManager::getSingleton(); - cm.setCompositorEnabled(mViewport, "WBOIT", box->isChecked()); - - if(box->isChecked()) - { - mWaterStream->setMaterialName("Examples/WaterStream/OIT"); - } - else - { - mWaterStream->setMaterialName("Examples/WaterStream"); - } - } - - void setupContent() override - { -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - // Need RTSS for WBOIT - mViewport->setMaterialScheme(MSN_SHADERGEN); - MaterialManager::getSingleton().setActiveScheme(mViewport->getMaterialScheme()); -#endif - mSceneMgr->setSkyBox(true, "Examples/TrippySkyBox"); - - mCameraMan->setStyle(CS_ORBIT); - mCameraMan->setYawPitchDist(Radian(0), Radian(0), 300); // set camera's starting position - - mSceneMgr->getRootSceneNode() - ->createChildSceneNode(Vector3(20, 80, 50)) - ->attachObject(mSceneMgr->createLight()); // add basic point light - - // create a torus knot model, give it the translucent texture, and attach it to the origin - mWaterStream = mSceneMgr->createEntity("Knot", "knot.mesh"); - mSceneMgr->getRootSceneNode()->attachObject(mWaterStream); - - // create a fishy and enable its swimming animation - auto ent = mSceneMgr->createEntity("Fish", "fish.mesh"); - mFishSwim = ent->getAnimationState("swim"); - mFishSwim->setEnabled(true); - - // create a scene node, attach fishy to it, and scale it by a factor of 2 - mFishNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mFishNode->attachObject(ent); - mFishNode->setScale(2, 2, 2); - - mWaterStream->setMaterialName("Examples/WaterStream"); - if(!mTrayMgr) - return; - - // OIT compositor (disabled) - auto& cm = CompositorManager::getSingleton(); - cm.addCompositor(mViewport, "WBOIT"); - - // GUI - mTrayMgr->showCursor(); - - auto oitMat = Ogre::MaterialManager::getSingleton().getByName("Examples/WaterStream/OIT"); - oitMat->load(); - if (oitMat->getBestTechnique()->getSchemeName() != mViewport->getMaterialScheme()) - return; - - mTrayMgr->createCheckBox(TL_TOPLEFT, "OIT", "Order Independent Transparency")->setChecked(false, true); - } - - Entity* mWaterStream; - SceneNode* mFishNode; - AnimationState* mFishSwim; -}; - -#endif diff --git a/Samples/Simple/include/VolumeCSG.h b/Samples/Simple/include/VolumeCSG.h deleted file mode 100644 index ba45aedb338..00000000000 --- a/Samples/Simple/include/VolumeCSG.h +++ /dev/null @@ -1,90 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __VolumeCSG_H__ -#define __VolumeCSG_H__ - -#include -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 -#include -#include -#endif -#include -#include - -#include "SdkSample.h" - -#include "OgreVolumeChunk.h" -#include "OgreMath.h" - - -using namespace Ogre; -using namespace OgreBites; -using namespace Ogre::Volume; - -/** Sample for the volume CSG. -*/ -class _OgreSampleClassExport Sample_VolumeCSG : public SdkSample -{ -protected: - - /// Holds the volume root. - Chunk *mVolumeRoot; - - /// To show or hide everything. - bool mHideAll; - - /// To rotate the scene. - Radian mRotation; - - /** Sets up the sample. - */ - void setupContent(void) override; - - /** Sets up the UI. - */ - virtual void setupControls(void); - - /** Is called when the sample is stopped. - */ - void cleanupContent(void) override; -public: - - /** Constructor. - */ - Sample_VolumeCSG(void); - - /** Overridden from SdkSample. - */ - bool keyPressed(const KeyboardEvent& evt) override; - - /** Overridden from SdkSample. - */ - bool frameRenderingQueued(const Ogre::FrameEvent& evt) override; -}; - -#endif diff --git a/Samples/Simple/include/VolumeTerrain.h b/Samples/Simple/include/VolumeTerrain.h deleted file mode 100644 index f32634b841a..00000000000 --- a/Samples/Simple/include/VolumeTerrain.h +++ /dev/null @@ -1,127 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __VolumeTerrain_H__ -#define __VolumeTerrain_H__ - -#include -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 -#include -#include -#endif -#include -#include - -#include "SdkSample.h" - -#include "OgreVolumeChunk.h" - -using namespace Ogre; -using namespace OgreBites; -using namespace Ogre::Volume; - -/** Sample for the volume terrain. -*/ -class _OgreSampleClassExport Sample_VolumeTerrain : public SdkSample -{ -protected: - - /// Min. time when the mouse is painting - static const Real MOUSE_MODIFIER_TIME_LIMIT; - - /// Holds the volume root. - Chunk *mVolumeRoot; - - /// The node on which the terrain is attached. - SceneNode *mVolumeRootNode; - - /// To show or hide everything. - bool mHideAll; - - /// Whether we bevel, emboss or do nothing with the mouse. - int mMouseState; - - /// A countdown when the next mouse modifier update will happen. - Real mMouseCountdown; - - /// Current mouse position, X-part. - Real mMouseX; - - /// Current mouse position, Y-part. - Real mMouseY; - - /** Sets up the sample. - */ - void setupContent(void) override; - - /** Sets up the UI. - */ - virtual void setupControls(void); - - /** Is called when the sample is stopped. - */ - void cleanupContent(void) override; - - /** Intersects a ray with the volume and adds a sphere at the intersection. - @param ray - The ray. - @param doUnion - Whether to add or subtract a sphere - */ - void shootRay(Ray ray, bool doUnion); -public: - - /** Constructor. - */ - Sample_VolumeTerrain(void); - - /** Overridden from SdkSample. - */ - bool keyPressed(const KeyboardEvent& evt) override; - - /** Overridden from SdkSample. - */ - bool touchPressed(const TouchFingerEvent& evt) override; - - /** Overridden from SdkSample. - */ - bool mousePressed(const MouseButtonEvent& evt) override; - - /** Overridden from SdkSample. - */ - bool mouseReleased(const MouseButtonEvent& evt) override; - - /** Overridden from SdkSample. - */ - bool mouseMoved(const MouseMotionEvent& evt) override; - - /** Overridden from SdkSample. - */ - bool frameRenderingQueued(const Ogre::FrameEvent& evt) override; -}; - -#endif diff --git a/Samples/Simple/src/Compute.cpp b/Samples/Simple/src/Compute.cpp deleted file mode 100644 index b57a5880863..00000000000 --- a/Samples/Simple/src/Compute.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ -#include "Compute.h" - -namespace OgreBites { - Sample_Compute::Sample_Compute() : mOgreEnt(NULL) - { - mInfo["Title"] = "Compute"; - mInfo["Description"] = "A basic example of the compute shader."; - mInfo["Thumbnail"] = "thumb_compute.png"; - mInfo["Category"] = "Tests"; - mInfo["Help"] = "The shader is executed in groups of 16x16 workers\n" - "in total there are 16x16 groups forming a grid of 256x256\n" - "each worker writes the color based on the local id\n" - "the sine overlay is based on the global id"; - } - - void Sample_Compute::testCapabilities(const RenderSystemCapabilities* caps) - { - requireMaterial("Compute/Compositor"); - } - - // Just override the mandatory create scene method - void Sample_Compute::setupContent(void) - { - mCameraMan->setStyle(CS_ORBIT); - mCameraMan->setYawPitchDist(Degree(0), Degree(0), 30); - - mOgreEnt = mSceneMgr->createEntity(SceneManager::PT_PLANE); - - mOgreEnt->setMaterial(MaterialManager::getSingleton().getByName("Compute/Show")); - SceneNode* ogre = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - ogre->setScale(0.1,0.1,0.1); - ogre->attachObject(mOgreEnt); - - CompositorManager::getSingleton().addCompositor(mViewport, "Compute"); - CompositorManager::getSingleton().setCompositorEnabled(mViewport, "Compute", true); - } -} diff --git a/Samples/Simple/src/MeshLod.cpp b/Samples/Simple/src/MeshLod.cpp deleted file mode 100644 index ca2ddc7076b..00000000000 --- a/Samples/Simple/src/MeshLod.cpp +++ /dev/null @@ -1,657 +0,0 @@ -#include "OgreComponents.h" -#ifdef OGRE_BUILD_COMPONENT_MESHLODGENERATOR -#include "MeshLod.h" - -using namespace Ogre; -using namespace OgreBites; - -#include "OgreLodConfigSerializer.h" -#include "OgreMeshLodGenerator.h" -#include "OgreLodCollapseCostQuadric.h" -#include "OgreLodOutsideMarker.h" -#include "OgreLodData.h" -#include "OgreLod0Stripifier.h" - -#include "OgrePixelCountLodStrategy.h" -#include "OgreMeshSerializer.h" - -Sample_MeshLod::Sample_MeshLod() -{ - mInfo["Title"] = "Mesh Lod"; - mInfo["Description"] = "Shows how to add Lod levels to a mesh using the ProgressiveMesh class."; - mInfo["Thumbnail"] = "thumb_meshlod.png"; - mInfo["Category"] = "Unsorted"; -} - -void Sample_MeshLod::setupContent() -{ - mCameraMan->setStyle(CS_ORBIT); - - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); // set ambient light - - // make the scene's main light come from above - Light* l = mSceneMgr->createLight(); - l->setType(Light::LT_DIRECTIONAL); - SceneNode* ln = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - ln->setDirection(Vector3::NEGATIVE_UNIT_Y); - ln->attachObject(l); - - // create a node for the model - mMeshNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mMeshEntity = NULL; -#if SHOW_MESH_HULL - mHullNode = mMeshNode->createChildSceneNode(); - mHullNode->scale(1.001,1.001,1.001); - mHullEntity = NULL; -#endif - if(!MeshLodGenerator::getSingletonPtr()) { - new MeshLodGenerator(); - } - MeshLodGenerator::getSingleton().setInjectorListener(this); - - // setup gui - setupControls(); - - // load mesh - changeSelectedMesh("Sinbad.mesh"); -} - -void Sample_MeshLod::cleanupContent() -{ - MeshLodGenerator::getSingleton().removeInjectorListener(); - if(mMeshEntity){ - mSceneMgr->destroyEntity(mMeshEntity); - mMeshEntity = 0; - } - cleanupControls(); -} - -void Sample_MeshLod::setupControls( int uimode /*= 0*/ ) -{ - cleanupControls(); - - SelectMenu* models = mTrayMgr->createLongSelectMenu(TL_TOPLEFT, "cmbModels", "Model:", 150, 8); - models->addItem("Sinbad.mesh"); - models->addItem("ogrehead.mesh"); - models->addItem("knot.mesh"); - models->addItem("fish.mesh"); - models->addItem("penguin.mesh"); - models->addItem("ninja.mesh"); - models->addItem("dragon.mesh"); - models->addItem("athene.mesh"); - models->addItem("sibenik.mesh"); - - // Add all meshes from popular: - StringVectorPtr meshes = ResourceGroupManager::getSingleton().findResourceNames("General", "*.mesh"); - StringVector::iterator it, itEnd; - it = meshes->begin(); - itEnd = meshes->end(); - for(; it != itEnd; it++){ - models->addItem(*it); - } - - - // Basic options: - mWireframe = mTrayMgr->createCheckBox(TL_TOPLEFT, "chkShowWireframe", "Show wireframe", 200); - mUseVertexNormals = mTrayMgr->createCheckBox(TL_TOPLEFT, "chkUseVertexNormals", "Use vertex normals", 200); - mOutsideWeightSlider = mTrayMgr->createThickSlider(TL_TOPLEFT, "sldOutsideWeight", "Weighten outside", 200, 50, 0, 100, 101); - mOutsideWalkAngle = mTrayMgr->createThickSlider(TL_TOPLEFT, "sldOutsideWalkAngle", "Outside angle", 200, 50, -1, 1, 201); - mManualMeshes = mTrayMgr->createLongSelectMenu(TL_TOPLEFT, "cmbManualMesh", "Manual LOD:", 100, 8); - mManualMeshes->copyItemsFrom(models); - mManualMeshes->insertItem(0,""); - mReductionSlider = mTrayMgr->createThickSlider(TL_TOPLEFT, "sldReductionValue", "Reduced vertices", 200, 50, 0, 100, 101); - mTrayMgr->createButton(TL_TOPLEFT, "btnReduceMore","Reduce More"); - mTrayMgr->createButton(TL_TOPLEFT, "btnReduceLess","Reduce Less"); - - // Level options: - mDistanceLabel = mTrayMgr->createLabel(TL_TOPRIGHT, "lblDistance", "Distance: ", 250); - mLodLevelList = mTrayMgr->createLongSelectMenu(TL_TOPRIGHT, "cmbLodLevels", "Lod level:", 150, 4); - mTrayMgr->createButton(TL_TOPRIGHT, "btnAddLodLevel","Add level", 220); - mTrayMgr->createButton(TL_TOPRIGHT, "btnRemoveSelectedLodLevel","Remove level", 220); - mTrayMgr->createButton(TL_TOPRIGHT, "btnRemoveInitialLodLevel","Remove level #0", 220); - - // Serializer options: - mTrayMgr->createButton(TL_TOPRIGHT, "btnShowAll", "Show all levels", 220); - mTrayMgr->createButton(TL_TOPRIGHT, "btnAutoconfigure", "Show autoconfigured LODs", 220); - mTrayMgr->createButton(TL_TOPRIGHT, "btnShowMesh", "Show LODs stored in mesh", 220); - mTrayMgr->createButton(TL_TOPRIGHT, "btnSaveMesh", "Save mesh", 220); - mTrayMgr->createButton(TL_TOPRIGHT, "btnRestoreMesh", "Restore original mesh", 220); - - // Profile options - mProfileList = mTrayMgr->createLongSelectMenu(TL_TOPRIGHT, "cmbProfiledVertices", "Profile:", 180, 4); - mTrayMgr->createButton(TL_TOPRIGHT, "btnRemoveFromProfile","Remove from profile", 220.0); - mTrayMgr->createButton(TL_TOPRIGHT, "btnAddToProfile","Add to profile", 220.0); - - //mTrayMgr->createTextBox(TL_TOPRIGHT, "Help","Help", 200, 200) - // ->setText("The last reduced vertex is the selected vertex. Use the slider to select the vertex, then decide to keep or remove it. You can export the Lod buffers into the .mesh file after configuration."); - - mTrayMgr->showCursor(); -} - -void Sample_MeshLod::cleanupControls() -{ - mTrayMgr->clearTray(TL_TOPLEFT); - mTrayMgr->clearTray(TL_TOPRIGHT); - mTrayMgr->clearTray(TL_TOP); -} -void Sample_MeshLod::recreateEntity() -{ - // If you change the lod of a mesh, every entity referencing it should be recreated. - if(mMeshEntity){ - mSceneMgr->destroyEntity(mMeshEntity); - mMeshEntity = 0; // createEntity may throw exception, so it is safer to reset to 0. - } - mMeshEntity = mSceneMgr->createEntity(mLodConfig.mesh->getName(), mLodConfig.mesh); - mMeshNode->attachObject(mMeshEntity); -} -void Sample_MeshLod::changeSelectedMesh( const String& name ) -{ - if(mMeshEntity){ - mSceneMgr->destroyEntity(mMeshEntity); - mMeshEntity = 0; - } - mLodConfig.mesh = MeshManager::getSingleton().load(name, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - if(mLodConfig.mesh->getBounds().isNull() || mLodConfig.mesh->getBoundingSphereRadius() == 0.0){ - mTrayMgr->showOkDialog("Error", "Failed to load mesh!"); - return; - } - mMeshEntity = mSceneMgr->createEntity(name, mLodConfig.mesh); - mMeshNode->attachObject(mMeshEntity); - mCameraMan->setYawPitchDist(Radian(0), Radian(0), mLodConfig.mesh->getBoundingSphereRadius() * 2); - mCamera->setNearClipDistance(mLodConfig.mesh->getBoundingSphereRadius() / 16); - mCamera->setFarClipDistance(mLodConfig.mesh->getBoundingSphereRadius() * 256); - - size_t vertexCount = getUniqueVertexCount(mLodConfig.mesh); - mReductionSlider->setRange(0,vertexCount,vertexCount+1,false); - mOutsideWeightSlider->setValue(0, false); - mOutsideWalkAngle->setValue(0, false); - mLodLevelList->clearItems(); - mManualMeshes->selectItem(0, false); - mWorkLevel.distance = 1.0; - mWorkLevel.reductionMethod = LodLevel::VRM_CONSTANT; - mWorkLevel.reductionValue = 0.0; - mWorkLevel.manualMeshName = ""; - - loadConfig(); - - if(mLodLevelList->getNumItems() > 0){ - loadLodLevel(mLodLevelList->getSelectionIndex()); - } else { - loadUserLod(); - } -#if SHOW_MESH_HULL - const String meshHullName("ConvexHull.mesh"); - if(mHullEntity){ - mHullNode->detachObject(mHullEntity); - mSceneMgr->destroyEntity(mHullEntity); - // Removes from the resources list. - mHullEntity = NULL; - Ogre::MeshManager::getSingleton().remove(meshHullName); - } - - LodConfig inputConfig(mLodConfig.mesh); - LodInputProviderPtr input; - LodCollapseCostPtr cost; - LodDataPtr data; - LodOutputProviderPtr output; - LodCollapserPtr collapser; - MeshLodGenerator::getSingleton()._resolveComponents(inputConfig, cost, data, input, output, collapser); - - input->initData(data.get()); - LodOutsideMarker outsideMarker(data->mVertexList, data->mMeshBoundingSphereRadius, 0.0); - MeshPtr meshHull = outsideMarker.createConvexHullMesh(meshHullName); - - mHullEntity = mSceneMgr->createEntity(meshHull); - mHullNode->attachObject(mHullEntity); -#endif -} - -bool Sample_MeshLod::loadConfig() -{ - mLodConfig.advanced = LodConfig::Advanced(); - mLodConfig.strategy = PixelCountLodStrategy::getSingletonPtr(); - mLodConfig.levels.clear(); - mLodConfig.advanced.profile.clear(); - - // The mesh should already be set. - assert(mLodConfig.mesh.get()); - - String filename(mLodConfig.mesh->getName()); - filename += ".lodconfig"; - LodConfigSerializer lcs; - lcs.importLodConfig(&mLodConfig, filename); - - mLodLevelList->clearItems(); - for(auto & level : mLodConfig.levels){ - mLodLevelList->addItem(StringConverter::toString(level.distance) + "px"); - } - - mProfileList->clearItems(); - for(auto & i : mLodConfig.advanced.profile){ - mProfileList->addItem(StringConverter::toString(i.src)); - } - - mUseVertexNormals->setChecked(mLodConfig.advanced.useVertexNormals, false); - mOutsideWeightSlider->setValue(std::sqrt(mLodConfig.advanced.outsideWeight), false); - mOutsideWalkAngle->setValue(mLodConfig.advanced.outsideWalkAngle, false); - return true; -} - -void Sample_MeshLod::saveConfig() -{ - String filename(mLodConfig.mesh->getName()); - filename += ".lodconfig"; - LodConfigSerializer lcs; - lcs.exportLodConfig(mLodConfig, filename); -} - -void Sample_MeshLod::loadAutomaticLod() -{ - // Remove outdated Lod requests to reduce delay. - MeshLodGenerator::getSingleton().clearPendingLodRequests(); - - MeshLodGenerator& gen = MeshLodGenerator::getSingleton(); - //gen.generateAutoconfiguredLodLevels(mLodConfig.mesh); - LodConfig lodConfig; - gen.getAutoconfig(mLodConfig.mesh, lodConfig); - lodConfig.advanced.useBackgroundQueue = ENABLE_THREADING; - lodConfig.advanced.useCompression = ENABLE_COMPRESSION; - lodConfig.advanced.preventPunchingHoles = PREVENT_HOLES_BREAKS; - lodConfig.advanced.preventBreakingLines = PREVENT_HOLES_BREAKS; - lodConfig.advanced.profile = mLodConfig.advanced.profile; - lodConfig.advanced.useVertexNormals = mLodConfig.advanced.useVertexNormals; - gen.generateLodLevels(lodConfig); - recreateEntity(); -} - -void Sample_MeshLod::loadUserLod( bool useWorkLod ) -{ - if(mLodConfig.mesh->getBoundingSphereRadius() == 0){ - // failed to load mesh - return; - } - if(mLodConfig.levels.empty()){ - useWorkLod = true; - } - mTrayMgr->destroyAllWidgetsInTray(TL_TOP); - // Remove outdated Lod requests to reduce delay. - MeshLodGenerator::getSingleton().clearPendingLodRequests(); - - MeshLodGenerator& gen = MeshLodGenerator::getSingleton(); - mLodConfig.advanced.useBackgroundQueue = ENABLE_THREADING; - mLodConfig.advanced.useCompression = ENABLE_COMPRESSION; - mLodConfig.advanced.preventPunchingHoles = PREVENT_HOLES_BREAKS; - mLodConfig.advanced.preventBreakingLines = PREVENT_HOLES_BREAKS; - if(!useWorkLod){ - gen.generateLodLevels(mLodConfig); -#if !ENABLE_THREADING - recreateEntity(); // Needed for manual Lod levels -#endif - forceLodLevel(-1); - } else { - LodConfig config(mLodConfig); - config.levels.clear(); - config.levels.push_back(mWorkLevel); - gen.generateLodLevels(config); - //gen.generateLodLevels(config, new LodCollapseCostQuadric()); // Use quadric error -#if !ENABLE_THREADING - recreateEntity(); // Needed for manual Lod levels -#endif - forceLodLevel(1); - } -} -void Sample_MeshLod::forceLodLevel(int lodLevelID, bool forceDelayed) -{ - mForcedLodLevel = lodLevelID; - // These are the requirements for async Lod generation - if(!forceDelayed || !ENABLE_THREADING || OGRE_THREAD_SUPPORT == 0){ - if(lodLevelID == -1 || mLodConfig.mesh->getNumLodLevels() <= 1) { - // Clear forced Lod level - mMeshEntity->setMeshLodBias(1.0, 0, std::numeric_limits::max()); - } else { - mMeshEntity->setMeshLodBias(1.0, lodLevelID, lodLevelID); - } - } -} -size_t Sample_MeshLod::getUniqueVertexCount( MeshPtr mesh ) -{ - - // The vertex buffer contains the same vertex position multiple times. - // To get the count of the vertices, which has unique positions, we can use progressive mesh. - // It is constructing a mesh grid at the beginning, so if we reduce 0%, we will get the unique vertex count. - LodConfig lodConfig(mesh, PixelCountLodStrategy::getSingletonPtr()); - lodConfig.advanced.useBackgroundQueue = false; // Non-threaded - lodConfig.advanced.useCompression = ENABLE_COMPRESSION; - lodConfig.advanced.preventPunchingHoles = PREVENT_HOLES_BREAKS; - lodConfig.advanced.preventBreakingLines = PREVENT_HOLES_BREAKS; - lodConfig.createGeneratedLodLevel(0, 0); - MeshLodGenerator& gen = MeshLodGenerator::getSingleton(); - gen.generateLodLevels(lodConfig); - //ProgressiveMeshGenerator pm; - //pm.generateLodLevels(lodConfig); - return lodConfig.levels[0].outUniqueVertexCount; -} - -void Sample_MeshLod::addLodLevel() -{ - LodLevel lvl(mWorkLevel); - lvl.distance = getCameraLODValue(); - Real distepsilon = lvl.distance + lvl.distance * 0.001; - size_t i = 0; - bool addLevel = true; - for(; i < mLodConfig.levels.size(); i++){ - if(mLodConfig.levels[i].distance < distepsilon){ - addLevel = false; - break; - } - } - if(/*mLodConfig.levels.empty() || */addLevel){ - mLodConfig.levels.push_back(lvl); - mLodLevelList->addItem(StringConverter::toString(lvl.distance) + "px"); - mLodLevelList->selectItem(mLodLevelList->getNumItems() - 1, false); - } else { - mLodConfig.levels.insert(mLodConfig.levels.begin() + i, lvl); - mLodLevelList->insertItem(i, StringConverter::toString(lvl.distance) + "px"); - mLodLevelList->selectItem(i, false); - } -} - -void Sample_MeshLod::loadLodLevel( int id ) -{ - assert(mLodConfig.levels[id].reductionMethod == LodLevel::VRM_CONSTANT); - mWorkLevel = mLodConfig.levels[id]; - mReductionSlider->setValue(mWorkLevel.reductionValue, false); - mLodLevelList->selectItem(id, false); - mManualMeshes->selectItem(mWorkLevel.manualMeshName, false); - loadUserLod(); - moveCameraToPixelDistance(mWorkLevel.distance); -} - -void Sample_MeshLod::removeLodLevel() -{ - if(mLodConfig.levels.empty()){ - return; - } - int selectedLevel = mLodLevelList->getSelectionIndex(); - mLodConfig.levels.erase(mLodConfig.levels.begin() + selectedLevel); - mLodLevelList->removeItem(selectedLevel); -} - -void Sample_MeshLod::removeInitialLodLevel() -{ - Ogre::Real stripValue = mLodConfig.levels.empty() ? mWorkLevel.reductionValue : mLodConfig.levels[0].reductionValue; - if(mWorkLevel.reductionMethod == LodLevel::VRM_CONSTANT && stripValue > 0.0) - { - Lod0Stripifier stripifier; - if(stripifier.StripLod0Vertices(mLodConfig.mesh)) - { - if(!mLodConfig.levels.empty()) - { - mLodConfig.levels.erase(mLodConfig.levels.begin()); - mLodLevelList->removeItem(0); - loadLodLevel(0); - } - else - { - mWorkLevel.reductionValue = 0.0; - mReductionSlider->setValue(mWorkLevel.reductionValue, false); - loadUserLod(); - } - } - } -} - -Real Sample_MeshLod::getCameraLODValue() -{ - if(mLodConfig.mesh->getBoundingSphereRadius() != 0.0){ - return PixelCountLodStrategy::getSingleton().getValue(mMeshEntity, mCamera); - } else { - return 0.0; - } -} - -void Sample_MeshLod::moveCameraToPixelDistance( Real pixels ) -{ - PixelCountLodStrategy& strategy = PixelCountLodStrategy::getSingleton(); - Real distance = mLodConfig.mesh->getBoundingSphereRadius() * 4; - const Real epsilon = pixels * 0.000001; - const int iterations = 64; - mCameraNode->setPosition(Vector3(0, 0, 0)); - mCameraNode->translate(Vector3(0, 0, distance), Node::TS_LOCAL); - // We need to find a distance, which is bigger then requested - for(int i=0;i pixels) { - distance *= 2.0; - mCameraNode->translate(Vector3(0, 0, distance), Node::TS_LOCAL); - } else { - break; - } - } - // Binary search for distance - for(int i=0;i pixels) { - // move camera further - mCameraNode->translate(Vector3(0, 0, distance), Node::TS_LOCAL); - } else { - // move camera nearer - mCameraNode->translate(Vector3(0, 0, -distance), Node::TS_LOCAL); - } - } -} - -bool Sample_MeshLod::getResourceFullPath(MeshPtr& mesh, String& outPath) -{ - ResourceGroupManager& resourceGroupMgr = ResourceGroupManager::getSingleton(); - String group = mesh->getGroup(); - String name = mesh->getName(); - Ogre::FileInfo* info = NULL; - FileInfoListPtr locPtr = resourceGroupMgr.listResourceFileInfo(group); - FileInfoList::iterator it, itEnd; - it = locPtr->begin(); - itEnd = locPtr->end(); - for (; it != itEnd; it++) { - if (StringUtil::startsWith(name, it->filename)) { - info = &*it; - break; - } - } - if(!info) { - outPath = name; - return false; - } - outPath = info->archive->getName(); - if (outPath[outPath .size()-1] != '/' && outPath[outPath .size()-1] != '\\') { - outPath += '/'; - } - outPath += info->path; - if (outPath[outPath .size()-1] != '/' && outPath[outPath .size()-1] != '\\') { - outPath += '/'; - } - outPath += info->filename; - - return (info->archive->getType() == "FileSystem"); -} - -void Sample_MeshLod::addToProfile( Real cost ) -{ - LodConfig config(mLodConfig); - config.levels.clear(); - config.levels.push_back(mWorkLevel); - config.advanced.useBackgroundQueue = false; - config.advanced.useCompression = ENABLE_COMPRESSION; - config.advanced.preventPunchingHoles = PREVENT_HOLES_BREAKS; - config.advanced.preventBreakingLines = PREVENT_HOLES_BREAKS; - MeshLodGenerator& gen = MeshLodGenerator::getSingleton(); - LodCollapserPtr collapser(new LodCollapser()); - LodDataPtr data(new LodData()); - gen.generateLodLevels(config, LodCollapseCostPtr(), data, LodInputProviderPtr(), LodOutputProviderPtr(), collapser); - - ProfiledEdge pv; - if(collapser->_getLastVertexPos(data.get(), pv.src)){ - collapser->_getLastVertexCollapseTo(data.get(), pv.dst); - // Prevent duplicates if you edit the same vertex twice. - size_t size = mLodConfig.advanced.profile.size(); - for(uint i=0;iselectItem(i, false); - loadUserLod(); - return; - } - } - // Copy profile in queued build. - pv.cost = cost; - mLodConfig.advanced.profile.push_back(pv); - mProfileList->addItem(StringConverter::toString(pv.src)); - mProfileList->selectItem(mProfileList->getNumItems() - 1, false); - } else { - mTrayMgr->showOkDialog("Error", "No vertex selected, because the mesh is not reduced."); - } - loadUserLod(); -} - -bool Sample_MeshLod::frameStarted( const FrameEvent& evt ) -{ - mDistanceLabel->setCaption(StringUtil::format("Pixel Count: %d px", int(getCameraLODValue()))); - return true; -} - -void Sample_MeshLod::checkBoxToggled( CheckBox * box ) -{ - if(box->getName() == "chkUseVertexNormals") { - mLodConfig.advanced.useVertexNormals = box->isChecked(); - loadUserLod(); - } else if (box->getName() == "chkShowWireframe") { - mCamera->setPolygonMode(mWireframe->isChecked() ? PM_WIREFRAME : PM_SOLID); - } -} - -void Sample_MeshLod::itemSelected( SelectMenu* menu ) -{ - if (menu->getName() == "cmbModels") { - changeSelectedMesh(menu->getSelectedItem()); - } else if(menu->getName() == "cmbLodLevels") { - loadLodLevel(menu->getSelectionIndex()); - } else if(menu->getName() == "cmbManualMesh") { - mWorkLevel.manualMeshName = menu->getSelectedItem(); - loadUserLod(); - } -} - -void Sample_MeshLod::sliderMoved(Slider* slider) -{ - if (slider->getName() == "sldReductionValue") { - mWorkLevel.reductionValue = slider->getValue(); - loadUserLod(); - } else if (slider->getName() == "sldOutsideWeight") { - if(mOutsideWeightSlider->getValue() == 100){ - mLodConfig.advanced.outsideWeight = LodData::NEVER_COLLAPSE_COST; - } else { - mLodConfig.advanced.outsideWeight = (mOutsideWeightSlider->getValue() * mOutsideWeightSlider->getValue()) / 10000; - } - loadUserLod(); - } else if (slider->getName() == "sldOutsideWalkAngle") { - mLodConfig.advanced.outsideWalkAngle = mOutsideWalkAngle->getValue(); - loadUserLod(); - } - -} - -void Sample_MeshLod::buttonHit( OgreBites::Button* button ) -{ - if(button->getName() == "btnReduceMore") { - mReductionSlider->setValue(mReductionSlider->getValue()+1); - } else if(button->getName() == "btnReduceLess") { - mReductionSlider->setValue(mReductionSlider->getValue()-1); - } else if(button->getName() == "btnAddToProfile") { - addToProfile(std::numeric_limits::max()); - } else if(button->getName() == "btnRemoveFromProfile") { - if(!mLodConfig.advanced.profile.empty()){ - LodProfile& profile = mLodConfig.advanced.profile; - profile.erase(profile.begin() + mProfileList->getSelectionIndex()); - mProfileList->removeItem(mProfileList->getSelectionIndex()); - loadUserLod(); - } - } else if(button->getName() == "btnAddLodLevel") { - addLodLevel(); - } else if(button->getName() == "btnRemoveSelectedLodLevel") { - removeLodLevel(); - } else if(button->getName() == "btnRemoveInitialLodLevel") { - removeInitialLodLevel(); - } else if(button->getName() == "btnAutoconfigure") { - mTrayMgr->destroyAllWidgetsInTray(TL_TOP); - mTrayMgr->createLabel(TL_TOP, "lblWhatYouSee", "Showing autoconfigured LOD", 300); - loadAutomaticLod(); - forceLodLevel(-1); // disable Lod level forcing - } else if (button->getName() == "btnShowAll") { - loadUserLod(false); - mTrayMgr->destroyAllWidgetsInTray(TL_TOP); - mTrayMgr->createLabel(TL_TOP, "lblWhatYouSee", "Showing all LOD levels", 300); - forceLodLevel(-1); // disable Lod level forcing - } else if(button->getName() == "btnShowMesh") { - mTrayMgr->destroyAllWidgetsInTray(TL_TOP); - mTrayMgr->createLabel(TL_TOP, "lblWhatYouSee", "Showing LOD from mesh file", 300); - if(mMeshEntity){ - mSceneMgr->destroyEntity(mMeshEntity); - mMeshEntity = 0; - } - mLodConfig.mesh->reload(Resource::LF_DEFAULT); - mMeshEntity = mSceneMgr->createEntity(mLodConfig.mesh->getName(), mLodConfig.mesh); - mMeshNode->attachObject(mMeshEntity); - forceLodLevel(-1); // disable Lod level forcing - //String filename(""); - //getResourceFullPath(mLodConfig.mesh, filename); - //mTrayMgr->showOkDialog("Success", "Showing mesh from: " + filename); - } else if(button->getName() == "btnSaveMesh") { - if(!mTrayMgr->getTrayContainer(TL_TOP)->isVisible() && !mLodConfig.levels.empty()){ - MeshLodGenerator::getSingleton().clearPendingLodRequests(); - MeshLodGenerator& gen = MeshLodGenerator::getSingleton(); - mLodConfig.advanced.useBackgroundQueue = false; // Non-threaded - mLodConfig.advanced.useCompression = ENABLE_COMPRESSION; - mLodConfig.advanced.preventPunchingHoles = PREVENT_HOLES_BREAKS; - mLodConfig.advanced.preventBreakingLines = PREVENT_HOLES_BREAKS; - gen.generateLodLevels(mLodConfig); - forceLodLevel(-1); // disable Lod level forcing - } - String filename(""); - if(!getResourceFullPath(mLodConfig.mesh, filename) || filename == "") { - mTrayMgr->showOkDialog("Error", "'" + filename + "' is not a writable path!"); - } else { - if(!FileSystemLayer::fileExists(filename + ".orig")) - FileSystemLayer::renameFile(filename, filename + ".orig"); - MeshSerializer ms; - ms.exportMesh(mLodConfig.mesh, filename); - mTrayMgr->showOkDialog("Success", "Mesh saved to: " + filename); - } - if(!mTrayMgr->getTrayContainer(TL_TOP)->isVisible()){ - loadUserLod(); - } - } - else if(button->getName() == "btnRestoreMesh") { - String filename(""); - if(getResourceFullPath(mLodConfig.mesh, filename) && filename != "") { - if(FileSystemLayer::fileExists(filename + ".orig")) - FileSystemLayer::renameFile(filename + ".orig", filename); - } - changeSelectedMesh(mLodConfig.mesh->getName()); - } -} - -bool Sample_MeshLod::shouldInject( LodWorkQueueRequest* request ) -{ - return true; -} - -void Sample_MeshLod::injectionCompleted( LodWorkQueueRequest* request ) -{ - recreateEntity(); // Needed for manual lod levels. - forceLodLevel(mForcedLodLevel, false); -} -#endif diff --git a/Samples/Simple/src/NewInstancing.cpp b/Samples/Simple/src/NewInstancing.cpp deleted file mode 100644 index 6ed324c8bfd..00000000000 --- a/Samples/Simple/src/NewInstancing.cpp +++ /dev/null @@ -1,719 +0,0 @@ -#include "SamplePlugin.h" -#include "NewInstancing.h" - -#include - -using namespace Ogre; -using namespace OgreBites; - -static const char *c_instancingTechniques[] = -{ - "Shader Based", - "Vertex Texture Fetch (VTF)", - "Hardware Instancing Basic", - "Hardware Instancing + VTF", - "Limited Animation - Hardware Instancing + VTF", - "Automatic HW Instancing", - "No Instancing" -}; - -static const char *c_materialsTechniques[] = -{ - "Examples/Instancing/RTSS/Robot", - "Examples/Instancing/VTF/Robot", - "Examples/Instancing/HWBasic/Robot", - "Examples/Instancing/VTF/HW/Robot", - "Examples/Instancing/VTF/HW/LUT/Robot", - "Examples/Instancing/HWBasic/Robot", - "Examples/Instancing/RTSS/Robot" -}; - -static const char *c_materialsTechniques_dq[] = -{ - "Examples/Instancing/RTSS/Robot_dq", - "Examples/Instancing/VTF/Robot_dq", - "Examples/Instancing/HWBasic/Robot", - "Examples/Instancing/VTF/HW/Robot_dq", - "Examples/Instancing/VTF/HW/LUT/Robot_dq", - "Examples/Instancing/HWBasic/Robot", - "Examples/Instancing/RTSS/Robot_dq" -}; - -static const char *c_materialsTechniques_dq_two_weights[] = -{ - "Examples/Instancing/RTSS/spine_dq_two_weights", - "Examples/Instancing/VTF/spine_dq_two_weights", - "Examples/Instancing/HWBasic/spine", - "Examples/Instancing/VTF/HW/spine_dq_two_weights", - "Examples/Instancing/VTF/HW/LUT/spine_dq_two_weights", - "Examples/Instancing/HWBasic/spine", - "Examples/Instancing/RTSS/spine_dq_two_weights" -}; - -static const char *c_meshNames[] = -{ - "robot.mesh", - "spine.mesh" -}; - -//------------------------------------------------------------------------------ -Sample_NewInstancing::Sample_NewInstancing() : NUM_INST_ROW(50), NUM_INST_COLUMN(50), mCurrentManager(0), mCurrentMaterialSet(c_materialsTechniques), mCurrentFlags(0), mSkinningTechniques(NULL) -{ - mInfo["Title"] = "New Instancing"; - mInfo["Description"] = "Demonstrates how to use the new InstancedManager to setup many dynamic" - " instances of the same mesh with much less performance impact"; - mInfo["Thumbnail"] = "thumb_newinstancing.png"; - mInfo["Category"] = "Environment"; - mInfo["Help"] = "Press Space to switch Instancing Techniques.\n" - "Press B to toggle bounding boxes.\n\n" - "Changes in the slider take effect after switching instancing technique\n" - "Different batch sizes give different results depending on CPU culling" - " and instance numbers on the scene.\n\n" - "If performance is too slow, try defragmenting batches once in a while"; -} - - -//------------------------------------------------------------------------------ -bool Sample_NewInstancing::frameRenderingQueued(const FrameEvent& evt) -{ - if( mAnimateInstances->isChecked() ) - animateUnits( evt.timeSinceLastEvent ); - - if( mMoveInstances->isChecked() ) - moveUnits( evt.timeSinceLastEvent ); - - return SdkSample::frameRenderingQueued(evt); // don't forget the parent class updates! -} - -//------------------------------------------------------------------------------ -bool Sample_NewInstancing::keyPressed(const KeyboardEvent& evt) -{ - Keycode key = evt.keysym.sym; - //Toggle bounding boxes with B key unless the help dialog is visible - if (key == 'b' && !mTrayMgr->isDialogVisible() && mCurrentManager) - { - bool oldShow = mCurrentManager->getSetting( InstanceManager::SHOW_BOUNDINGBOX, - mCurrentMaterialSet[mInstancingTechnique] ); - mCurrentManager->setSetting( InstanceManager::SHOW_BOUNDINGBOX, !oldShow ); - } - - //Switch to next instancing technique with space bar - if (key == SDLK_SPACE && !mTrayMgr->isDialogVisible()) - mTechniqueMenu->selectItem( (mTechniqueMenu->getSelectionIndex() + 1) % NUM_TECHNIQUES ); - - return SdkSample::keyPressed(evt); -} - -//------------------------------------------------------------------------------ -void Sample_NewInstancing::setupContent() -{ -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - // Make this viewport work with shader generator scheme. - mViewport->setMaterialScheme(MSN_SHADERGEN); - RTShader::ShaderGenerator& rtShaderGen = RTShader::ShaderGenerator::getSingleton(); - RTShader::RenderState* schemRenderState = rtShaderGen.getRenderState(MSN_SHADERGEN); - RTShader::SubRenderState* subRenderState = rtShaderGen.createSubRenderState(RTShader::SRS_SHADOW_MAPPING); - schemRenderState->addTemplateSubRenderState(subRenderState); - - //Add the hardware skinning to the shader generator default render state - subRenderState = mShaderGenerator->createSubRenderState(RTShader::SRS_HARDWARE_SKINNING); - schemRenderState->addTemplateSubRenderState(subRenderState); - - // increase max bone count for higher efficiency - RTShader::HardwareSkinningFactory::setMaxCalculableBoneCount(80); - - // re-generate shaders to include new SRSs - rtShaderGen.invalidateScheme(MSN_SHADERGEN); - - // update scheme for FFP supporting rendersystems - MaterialManager::getSingleton().setActiveScheme(mViewport->getMaterialScheme()); -#endif - - //Initialize the techniques and current mesh variables - mInstancingTechnique = 0; - mCurrentMesh = 0; - mCurrentManager = 0; - - checkHardwareSupport(); - - mSceneMgr->setShadowTechnique( SHADOWTYPE_TEXTURE_ADDITIVE_INTEGRATED ); - mSceneMgr->setShadowTextureSelfShadow( true ); - mSceneMgr->setShadowCasterRenderBackFaces( true ); - - if (Ogre::Root::getSingletonPtr()->getRenderSystem()->getName().find("OpenGL ES 2") == String::npos) - { - mSceneMgr->setShadowTextureConfig( 0, 2048, 2048, PF_DEPTH16 ); - } - else - { - // Use a smaller texture for GL ES 3.0 - mSceneMgr->setShadowTextureConfig( 0, 512, 512, PF_DEPTH16 ); - } - - mSceneMgr->setShadowCameraSetup( LiSPSMShadowCameraSetup::create() ); - - mEntities.reserve( NUM_INST_ROW * NUM_INST_COLUMN ); - mSceneNodes.reserve( NUM_INST_ROW * NUM_INST_COLUMN ); - - mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); - - // create a mesh for our ground - MeshManager::getSingleton().createPlane("ground", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - Plane(Vector3::UNIT_Y, 0), 10000, 10000, 20, 20, true, 1, 6, 6, Vector3::UNIT_Z); - - // create a ground entity from our mesh and attach it to the origin - Entity* ground = mSceneMgr->createEntity("Ground", "ground"); - ground->setMaterialName("Examples/GrassFloor"); - ground->setCastShadows(false); - mSceneMgr->getRootSceneNode()->attachObject(ground); - - setupLighting(); - - // set initial camera position and speed - mCameraNode->setPosition( 0, 120, 100 ); - - setupGUI(); - setDragLook(true); - - switchInstancingTechnique(); -} -//------------------------------------------------------------------------------ -void Sample_NewInstancing::setupLighting() -{ - mSceneMgr->setAmbientLight( ColourValue( 0.40f, 0.40f, 0.40f ) ); - - //Create main light - Light* light = mSceneMgr->createLight(); - light->setType( Light::LT_DIRECTIONAL ); - light->setDiffuseColour(1, 0.5, 0.3); - auto n = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - n->attachObject(light); - n->setDirection(0, -1, -1); - light->setSpecularColour( 0.6, 0.82, 1.0 ); - light->setShadowFarDistance( 10000 ); -} - -//------------------------------------------------------------------------------ -void Sample_NewInstancing::switchInstancingTechnique() -{ - mInstancingTechnique = mTechniqueMenu->getSelectionIndex(); - - if( mCurrentManager ) - mSceneMgr->destroyInstanceManager(mCurrentManager); - - if( !mSupportedTechniques[mInstancingTechnique] ) - { - //Hide GUI features available only to instancing - mCurrentManager = 0; - mDefragmentBatches->hide(); - mDefragmentOptimumCull->hide(); - return; - } - - if( mInstancingTechnique < NUM_IM_TECHNIQUES ) - { - //Instancing - - //Create the manager if we haven't already (i.e. first time) - //Because we use IM_USEALL as flags, the actual num of instances per batch might be much lower - //If you're not bandwidth limited, you may want to lift IM_VTFBESTFIT flag away - - InstanceManager::InstancingTechnique technique = InstanceManager::ShaderBased; - - switch( mInstancingTechnique ) - { - case 0: technique = InstanceManager::ShaderBased; break; - case 1: technique = InstanceManager::TextureVTF; break; - case 2: technique = InstanceManager::HWInstancingBasic; break; - case 3: - case 4: technique = InstanceManager::HWInstancingVTF; break; - } - - uint16 flags = IM_USEALL; - flags |= mCurrentFlags; - - if (mInstancingTechnique == 4) - { - flags |= IM_VTFBONEMATRIXLOOKUP; - } - //Only one weight is recommended for the VTF technique, but force the use of more for the demo - if(mInstancingTechnique == 1 && (flags & IM_USEBONEDUALQUATERNIONS)) - { - flags &= ~IM_USEONEWEIGHT; - } - - mCurrentManager = mSceneMgr->createInstanceManager( - "InstanceMgr" + StringConverter::toString(mInstancingTechnique), c_meshNames[mCurrentMesh], - ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME, technique, - NUM_INST_ROW * NUM_INST_COLUMN, flags); - - createInstancedEntities(); - - //Show GUI features available only to instancing - mDefragmentBatches->show(); - mDefragmentOptimumCull->show(); - } - else - { - //Non-instancing - createEntities(mInstancingTechnique); - - //Hide GUI features available only to instancing - mCurrentManager = 0; - mDefragmentBatches->hide(); - mDefragmentOptimumCull->hide(); - } - - createSceneNodes(); - - //Show/hide "static" button, and restore config. Do this _after_ createSceneNodes() - if( mInstancingTechnique == InstanceManager::HWInstancingBasic || - mInstancingTechnique == InstanceManager::HWInstancingVTF || - mInstancingTechnique == InstanceManager::HWInstancingVTF + 1) // instancing with lookup - { - if( mSetStatic->isChecked() ) - mCurrentManager->setBatchesAsStaticAndUpdate( mSetStatic->isChecked() ); - mSetStatic->show(); - } - else - mSetStatic->hide(); - if( mInstancingTechnique < NUM_IM_TECHNIQUES) - { - mUseSceneNodes->show(); - } - else - { - mUseSceneNodes->hide(); - } -} - -//------------------------------------------------------------------------------ -void Sample_NewInstancing::switchSkinningTechnique(int index) -{ - switch(index) - { - default: - //Linear Skinning - case 0: - mCurrentMesh = 0; - mCurrentMaterialSet = c_materialsTechniques; - mCurrentFlags = 0; - break; - //Dual Quaternion Skinning - case 1: - mCurrentMesh = 0; - mCurrentMaterialSet = c_materialsTechniques_dq; - mCurrentFlags = IM_USEBONEDUALQUATERNIONS; - break; - //Dual Quaternion Skinning with two weights - case 2: - mCurrentMesh = 1; - mCurrentMaterialSet = c_materialsTechniques_dq_two_weights; - mCurrentFlags = IM_USEBONEDUALQUATERNIONS; - break; - }; -} - -//------------------------------------------------------------------------------ -void Sample_NewInstancing::createEntities(int technique) -{ - std::mt19937 rng; - for( int i=0; icreateEntity( c_meshNames[mCurrentMesh] ); - ent->setMaterialName( mCurrentMaterialSet[technique] ); - mEntities.push_back( ent ); - - if(technique == NUM_IM_TECHNIQUES) - continue; - - //Get the animation - AnimationState *anim = ent->getAnimationState( "Walk" ); - if (mAnimations.insert( anim ).second) - { - anim->setEnabled( true ); - anim->addTime( double(rng())/rng.max() * 10 ); //Random start offset - } - } -} -//------------------------------------------------------------------------------ -void Sample_NewInstancing::createInstancedEntities() -{ - std::mt19937 rng; - std::mt19937 orng; // separate oriention rng for consistency with other techniques - for( int i=0; icreateInstancedEntity(mCurrentMaterialSet[mInstancingTechnique] ); - mEntities.push_back( ent ); - - //HWInstancingBasic is the only technique without animation support - if( mInstancingTechnique != InstanceManager::HWInstancingBasic) - { - //Get the animation - AnimationState *anim = ent->getAnimationState( "Walk" ); - anim->setEnabled( true ); - anim->addTime( double(rng())/rng.max() * 10); //Random start offset - mAnimations.insert( anim ); - } - - if ((mInstancingTechnique < NUM_IM_TECHNIQUES) && (!mUseSceneNodes->isChecked())) - { - mMovedInstances.push_back( ent ); - ent->setOrientation(Quaternion(Radian(float(orng())/float(orng.max()) * 10 * Math::PI), Vector3::UNIT_Y)); - ent->setPosition( Ogre::Vector3(mEntities[0]->getBoundingRadius() * (i - NUM_INST_ROW * 0.5f), 0, - mEntities[0]->getBoundingRadius() * (j - NUM_INST_COLUMN * 0.5f)) ); - } - } - } -} -//------------------------------------------------------------------------------ -void Sample_NewInstancing::createSceneNodes() -{ - //Here the SceneNodes are created. Since InstancedEntities derive from MovableObject, - //they behave like regular Entities on this. - SceneNode *rootNode = mSceneMgr->getRootSceneNode(); - - std::mt19937 rng; - for( int i=0; i= NUM_IM_TECHNIQUES) || (mUseSceneNodes->isChecked())) - { - SceneNode *sceneNode = rootNode->createChildSceneNode(); - sceneNode->attachObject( mEntities[idx] ); - sceneNode->yaw( Radian( double(rng())/rng.max() * 10 * Math::PI )); //Random orientation - sceneNode->setPosition( mEntities[idx]->getBoundingRadius() * (i - NUM_INST_ROW * 0.5f), 0, - mEntities[idx]->getBoundingRadius() * (j - NUM_INST_COLUMN * 0.5f) ); - mSceneNodes.push_back( sceneNode ); - } - - } - } -} -//------------------------------------------------------------------------------ -void Sample_NewInstancing::clearScene() -{ - std::vector::const_iterator itor = mEntities.begin(); - std::vector::const_iterator end = mEntities.end(); - - //Note: Destroying the instance manager automatically destroys all instanced entities - //created by this manager (beware of not leaving reference to those pointers) - while( itor != end ) - { - SceneNode *sceneNode = (*itor)->getParentSceneNode(); - if (sceneNode) - { - sceneNode->detachAllObjects(); - sceneNode->getParentSceneNode()->removeAndDestroyChild( sceneNode ); - } - if( mInstancingTechnique >= NUM_IM_TECHNIQUES ) - mSceneMgr->destroyEntity( (*itor)->getName() ); - else - mSceneMgr->destroyInstancedEntity( static_cast(*itor) ); - - ++itor; - } - - //Free some memory, but don't destroy the manager so when we switch this technique - //back again it doesn't take too long - if( mCurrentManager ) - mCurrentManager->cleanupEmptyBatches(); - - mEntities.clear(); - mMovedInstances.clear(); - mSceneNodes.clear(); - mAnimations.clear(); -} -//----------------------------------------------------------------------------------- -void Sample_NewInstancing::destroyManagers() -{ - mSceneMgr->destroyInstanceManager(mCurrentManager);; -} - -//------------------------------------------------------------------------------ -void Sample_NewInstancing::cleanupContent() -{ - MeshManager::getSingleton().remove("ground", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - clearScene(); - destroyManagers(); -} - -//------------------------------------------------------------------------------ -void Sample_NewInstancing::animateUnits( float timeSinceLast ) -{ - //Iterates through all AnimationSets and updates the animation being played. Demonstrates the - //animation is unique and independent to each instance - std::set::const_iterator itor = mAnimations.begin(); - std::set::const_iterator end = mAnimations.end(); - - while( itor != end ) - { - (*itor)->addTime( timeSinceLast ); - ++itor; - } -} - -//------------------------------------------------------------------------------ -void Sample_NewInstancing::moveUnits( float timeSinceLast ) -{ - Real fMovSpeed = 1.0f; - - if( !mEntities.empty() ) - fMovSpeed = mEntities[0]->getBoundingRadius() * 0.30f; - - if (!mSceneNodes.empty()) - { - //Randomly move the units along their normal, bouncing around invisible walls - std::vector::const_iterator itor = mSceneNodes.begin(); - std::vector::const_iterator end = mSceneNodes.end(); - - while( itor != end ) - { - //Calculate bounces - Vector3 entityPos = (*itor)->getPosition(); - Vector3 planeNormal = Vector3::ZERO; - if( (*itor)->getPosition().x < -5000.0f ) - { - planeNormal = Vector3::UNIT_X; - entityPos.x = -4999.0f; - } - else if( (*itor)->getPosition().x > 5000.0f ) - { - planeNormal = Vector3::NEGATIVE_UNIT_X; - entityPos.x = 4999.0f; - } - else if( (*itor)->getPosition().z < -5000.0f ) - { - planeNormal = Vector3::UNIT_Z; - entityPos.z = -4999.0f; - } - else if( (*itor)->getPosition().z > 5000.0f ) - { - planeNormal = Vector3::NEGATIVE_UNIT_Z; - entityPos.z = 4999.0f; - } - - if( planeNormal != Vector3::ZERO ) - { - const Vector3 vDir( (*itor)->getOrientation().xAxis().normalisedCopy() ); - (*itor)->setOrientation( lookAt( planeNormal.reflect( vDir ) ) ); - (*itor)->setPosition( entityPos ); - } - - //Move along the direction we're looking to - (*itor)->translate( Vector3::UNIT_X * timeSinceLast * fMovSpeed, Node::TS_LOCAL ); - ++itor; - } - } - else - { - //No scene nodes (instanced entities only) - //Update instanced entities directly - - //Randomly move the units along their normal, bouncing around invisible walls - std::vector::const_iterator itor = mMovedInstances.begin(); - std::vector::const_iterator end = mMovedInstances.end(); - - while( itor != end ) - { - //Calculate bounces - InstancedEntity* pEnt = *itor; - Vector3 entityPos = pEnt->getPosition(); - Vector3 planeNormal = Vector3::ZERO; - if( pEnt->getPosition().x < -5000.0f ) - { - planeNormal = Vector3::UNIT_X; - entityPos.x = -4999.0f; - } - else if( pEnt->getPosition().x > 5000.0f ) - { - planeNormal = Vector3::NEGATIVE_UNIT_X; - entityPos.x = 4999.0f; - } - else if( pEnt->getPosition().z < -5000.0f ) - { - planeNormal = Vector3::UNIT_Z; - entityPos.z = -4999.0f; - } - else if( pEnt->getPosition().z > 5000.0f ) - { - planeNormal = Vector3::NEGATIVE_UNIT_Z; - entityPos.z = 4999.0f; - } - - if( planeNormal != Vector3::ZERO ) - { - const Vector3 vDir(pEnt->getOrientation().xAxis().normalisedCopy() ); - pEnt->setOrientation( lookAt( planeNormal.reflect( vDir ) ), false ); - pEnt->setPosition( entityPos, false); - } - - //Move along the direction we're looking to - Vector3 transAmount = Vector3::UNIT_X * timeSinceLast * fMovSpeed; - pEnt->setPosition( pEnt->getPosition() + pEnt->getOrientation() * transAmount ); - ++itor; - } - } -} - -//------------------------------------------------------------------------------ -Quaternion Sample_NewInstancing::lookAt( const Vector3 &normDir ) -{ - return Math::lookRotation(normDir.normalisedCopy(), Vector3::UNIT_Y); -} - -//------------------------------------------------------------------------------ -void Sample_NewInstancing::defragmentBatches() -{ - //Defragment batches is used after many InstancedEntities were removed (and you won't - //be requesting more). However, then the optimize cull option is on, it can cause - //quite a perf. boost on large batches (i.e. VTF) even if not a single instance was ever removed. - if( mCurrentManager ) - mCurrentManager->defragmentBatches( mDefragmentOptimumCull->isChecked() ); -} - -//------------------------------------------------------------------------------ -void Sample_NewInstancing::setupGUI() -{ - mTechniqueMenu = mTrayMgr->createLongSelectMenu( - TL_TOPLEFT, "TechniqueSelectMenu", "Technique", 450, 350, 5); - for( int i=0; iaddItem( text ); - } - //Check box to enable dual quaternion skinning - mSkinningTechniques = mTrayMgr->createLongSelectMenu(TL_TOPLEFT, "SkinningTechnique", "Skinning Technique", 450, 285, 5); - mSkinningTechniques->addItem("Linear Skinning"); - mSkinningTechniques->addItem("Dual Quaternion Skinning"); - mSkinningTechniques->addItem("Dual Quaternion Skinning (2 wgts)"); - - //Check box to move the units - mMoveInstances = mTrayMgr->createCheckBox(TL_TOPRIGHT, "MoveInstances", "Move Instances", 175); - mMoveInstances->setChecked(false); - - //Check box to animate the units - mAnimateInstances = mTrayMgr->createCheckBox(TL_TOPRIGHT, "AnimateInstances", - "Animate Instances", 175); - mAnimateInstances->setChecked(false); - - //Checkbox to toggle shadows - mEnableShadows = mTrayMgr->createCheckBox(TL_TOPRIGHT, "EnableShadows", - "Enable Shadows", 175); - mEnableShadows->setChecked(true); - - //Check box to make instances static (where supported) - mSetStatic = mTrayMgr->createCheckBox(TL_TOPRIGHT, "SetStatic", "Set Static", 175); - mSetStatic->setChecked(false); - - //Checkbox to toggle use of scene nodes - mUseSceneNodes = mTrayMgr->createCheckBox(TL_TOPRIGHT, "UseSceneNodes", - "Use Scene Nodes", 175); - mUseSceneNodes->setChecked(true, false); - - //Controls to control batch defragmentation on the fly - mDefragmentBatches = mTrayMgr->createButton(TL_RIGHT, "DefragmentBatches", - "Defragment Batches", 175); - mDefragmentOptimumCull = mTrayMgr->createCheckBox(TL_RIGHT, "DefragmentOptimumCull", - "Optimum Cull", 175); - mDefragmentOptimumCull->setChecked(true); - - //Slider to control max number of instances - mInstancesSlider = mTrayMgr->createThickSlider( TL_TOPLEFT, "InstancesSlider", "Instances (NxN)", - 300, 50, 4, 100, 97 ); - mInstancesSlider->setValue( NUM_INST_ROW ); - - mTrayMgr->showCursor(); -} - -//------------------------------------------------------------------------------ -void Sample_NewInstancing::itemSelected( SelectMenu* menu ) -{ - if (menu == mTechniqueMenu) - { - clearScene(); - switchInstancingTechnique(); - } - else if(menu == mSkinningTechniques) - { - clearScene(); - switchSkinningTechnique(menu->getSelectionIndex()); - switchInstancingTechnique(); - } -} - -//------------------------------------------------------------------------------ -void Sample_NewInstancing::buttonHit( OgreBites::Button* button ) -{ - if( button == mDefragmentBatches ) defragmentBatches(); -} - -//------------------------------------------------------------------------------ -void Sample_NewInstancing::checkBoxToggled( CheckBox* box ) -{ - if( box == mEnableShadows ) - { - mSceneMgr->setShadowTechnique( mEnableShadows->isChecked() ? - SHADOWTYPE_TEXTURE_ADDITIVE_INTEGRATED : SHADOWTYPE_NONE ); - } - else if( box == mSetStatic && mCurrentManager ) - { - mCurrentManager->setBatchesAsStaticAndUpdate( mSetStatic->isChecked() ); - } - else if (box == mUseSceneNodes) - { - clearScene(); - switchInstancingTechnique(); - } -} - -//------------------------------------------------------------------------------ -void Sample_NewInstancing::sliderMoved( Slider* slider ) -{ - if( slider == mInstancesSlider ) NUM_INST_ROW = static_cast(mInstancesSlider->getValue()); - NUM_INST_COLUMN = static_cast(mInstancesSlider->getValue()); -} - -//------------------------------------------------------------------------------ - -void Sample_NewInstancing::checkHardwareSupport() -{ - //Non instancing is always supported - mSupportedTechniques.fill(true); - - //Check Technique support - for( int i=0; igetNumInstancesPerBatch( c_meshNames[mCurrentMesh], - ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME, - mCurrentMaterialSet[i], technique, NUM_INST_ROW * NUM_INST_COLUMN, flags ); - - mSupportedTechniques[i] = numInstances > 0; - } -} diff --git a/Samples/Simple/src/VolumeCSG.cpp b/Samples/Simple/src/VolumeCSG.cpp deleted file mode 100644 index 1ce73e874f5..00000000000 --- a/Samples/Simple/src/VolumeCSG.cpp +++ /dev/null @@ -1,176 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "SamplePlugin.h" -#include "VolumeCSG.h" - -#include "OgreVolumeCSGSource.h" -#include "OgreVolumeCacheSource.h" -#include "OgreVolumeTextureSource.h" -#include "OgreVolumeMeshBuilder.h" -#include "OgreMath.h" - -using namespace Ogre; -using namespace OgreBites; -using namespace Ogre::Volume; - -void Sample_VolumeCSG::setupContent(void) -{ - setupControls(); - mViewport->setMaterialScheme(MSN_SHADERGEN); - Real size = (Real)31.0; - Vector3 to(size); - - // Light - Light* directionalLight0 = mSceneMgr->createLight("directionalLight0"); - directionalLight0->setType(Light::LT_DIRECTIONAL); - directionalLight0->setDiffuseColour((Real)1, (Real)0.98, (Real)0.73); - directionalLight0->setSpecularColour((Real)0.1, (Real)0.1, (Real)0.1); - - auto ln = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - ln->attachObject(directionalLight0); - ln->setDirection(Vector3(1, -1, 1)); - - // Spheres - CSGSphereSource sphere1((Real)5.0, Vector3((Real)5.5)); - CSGSphereSource sphere2((Real)5.0, Vector3((Real)25.5, (Real)5.5, (Real)5.5)); - CSGSphereSource sphere3((Real)5.0, Vector3((Real)25.5, (Real)5.5, (Real)25.5)); - CSGSphereSource sphere4((Real)5.0, Vector3((Real)5.5, (Real)5.5, (Real)25.5)); - - // Cubes - Real halfWidth = (Real)(2.5 / 2.0); - CSGCubeSource cube1(Vector3((Real)5.5 - halfWidth), Vector3((Real)25.5 + halfWidth, (Real)5.5 + halfWidth, (Real)25.5 + halfWidth)); - CSGCubeSource cube2(Vector3((Real)5.5 + halfWidth, (Real)0.0, (Real)5.5 + halfWidth), Vector3((Real)25.5 - halfWidth, to.y, (Real)25.5 - halfWidth)); - CSGDifferenceSource difference1(&cube1, &cube2); - - // Inner rounded cube - Real innerHalfWidth = (Real)(7.0 / 2.0); - Vector3 center((Real)15.5, (Real)5.5, (Real)15.5); - CSGCubeSource cube3(center - innerHalfWidth, center + innerHalfWidth); - CSGSphereSource sphere5(innerHalfWidth + (Real)0.75, center); - CSGIntersectionSource intersection1(&cube3, &sphere5); - - // A plane with noise - CSGPlaneSource plane1((Real)1.0, Vector3::UNIT_Y); - Real frequencies[] = {(Real)1.01, (Real)0.48}; - Real amplitudes[] = {(Real)0.25, (Real)0.5}; - CSGNoiseSource noise1(&plane1, frequencies, amplitudes, 2, 100); - - // Combine everything - CSGUnionSource union1(&sphere1, &sphere2); - CSGUnionSource union2(&union1, &sphere3); - CSGUnionSource union3(&union2, &sphere4); - CSGUnionSource union4(&union3, &difference1); - CSGUnionSource union5(&union4, &intersection1); - CSGUnionSource union6(&union5, &noise1); - Source *src = &union6; - - mVolumeRoot = OGRE_NEW Chunk(); - SceneNode *volumeRootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("VolumeParent"); - - - ChunkParameters parameters; - parameters.sceneManager = mSceneMgr; - parameters.src = src; - parameters.baseError = (Real)0.25; - - mVolumeRoot->load(volumeRootNode, Vector3::ZERO, to, 1, ¶meters); - - MaterialPtr mat = MaterialManager::getSingleton().getByName("Ogre/RTShader/TriplanarTexturing", "General"); - mVolumeRoot->setMaterial(mat); - - // Camera - mCameraNode->setPosition(to + (Real)7.5); - mCameraNode->lookAt(center + (Real)11.0, Node::TS_PARENT); - mCamera->setNearClipDistance((Real)0.5); - - mRotation = (Real)0.0; - -} - -//----------------------------------------------------------------------- - -void Sample_VolumeCSG::setupControls(void) -{ - mTrayMgr->showCursor(); - mCameraMan->setStyle(OgreBites::CS_MANUAL); - mCameraMan->setTopSpeed((Real)25.0); - // make room for the volume - mTrayMgr->showLogo(TL_TOPRIGHT); - mTrayMgr->showFrameStats(TL_TOPRIGHT); - mTrayMgr->toggleAdvancedFrameStats(); -} - -//----------------------------------------------------------------------- -void Sample_VolumeCSG::cleanupContent(void) -{ - OGRE_DELETE mVolumeRoot; - mVolumeRoot = 0; -} - -//----------------------------------------------------------------------- - -Sample_VolumeCSG::Sample_VolumeCSG(void) : mVolumeRoot(0), mHideAll(false) -{ - mInfo["Title"] = "Volume CSG"; - mInfo["Description"] = "Demonstrates a volumetric constructive solid geometry scene, showing sphere, cube, plane, union, difference and intersection. The triplanar texturing is generated by the RTSS."; - mInfo["Thumbnail"] = "thumb_volumecsg.png"; - mInfo["Category"] = "Geometry"; -} - -//----------------------------------------------------------------------- - -bool Sample_VolumeCSG::keyPressed(const KeyboardEvent& evt) -{ - Keycode key = evt.keysym.sym; - if (key == 'h') - { - if (mHideAll) - { - mTrayMgr->showAll(); - } - else - { - mTrayMgr->hideAll(); - } - mHideAll = !mHideAll; - } - return SdkSample::keyPressed(evt); -} - -bool Sample_VolumeCSG::frameRenderingQueued(const Ogre::FrameEvent& evt) -{ - Vector3 center((Real)15.5, (Real)5.5, (Real)15.5); - mRotation += Radian(evt.timeSinceLastFrame * (Real)0.5); - Real r = (Real)35.0; - mCameraNode->setPosition( - Math::Sin(mRotation) * r + center.x, - (Real)15.0 + center.y, - Math::Cos(mRotation) * r + center.z - ); - mCameraNode->lookAt(center, Node::TS_PARENT); - return SdkSample::frameRenderingQueued(evt); -} diff --git a/Samples/Simple/src/VolumeTerrain.cpp b/Samples/Simple/src/VolumeTerrain.cpp deleted file mode 100644 index 08e3f7084f8..00000000000 --- a/Samples/Simple/src/VolumeTerrain.cpp +++ /dev/null @@ -1,233 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "SamplePlugin.h" -#include "VolumeTerrain.h" - -#include "OgreVolumeTextureSource.h" -#include "OgreVolumeCSGSource.h" - -#include "OgreRay.h" - -using namespace Ogre; -using namespace OgreBites; -using namespace Ogre::Volume; - -const Real Sample_VolumeTerrain::MOUSE_MODIFIER_TIME_LIMIT = (Real)0.033333; - -void Sample_VolumeTerrain::setupContent(void) -{ - setupControls(); - - // Skydome - mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8); - - // Light - Light* directionalLight0 = mSceneMgr->createLight("directionalLight0"); - directionalLight0->setType(Light::LT_DIRECTIONAL); - directionalLight0->setDiffuseColour((Real)1, (Real)0.98, (Real)0.73); - directionalLight0->setSpecularColour((Real)0.1, (Real)0.1, (Real)0.1); - SceneNode* ln = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - ln->setDirection(1, -1, 1); - ln->attachObject(directionalLight0); - - mSceneMgr->setAmbientLight(Ogre::ColourValue::White); - - // Volume - mVolumeRoot = OGRE_NEW Chunk(); - mVolumeRootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("VolumeParent"); - Timer t; - mVolumeRoot->load(mVolumeRootNode, mSceneMgr, "volumeTerrain.cfg", true); - LogManager::getSingleton().stream() << "Loaded volume terrain in " << t.getMillisecondsCPU() << " ms"; - - // Make this viewport work with shader generator scheme. - mViewport->setMaterialScheme(MSN_SHADERGEN); - - // Camera - mCameraNode->setPosition((Real)3264, (Real)2700, (Real)3264); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - mCamera->setNearClipDistance((Real)0.5); - -} - -//----------------------------------------------------------------------- - -void Sample_VolumeTerrain::setupControls(void) -{ - mMouseState = 0; - mTrayMgr->showCursor(); - setDragLook(true); - mCameraMan->setTopSpeed((Real)100.0); - // make room for the volume - mTrayMgr->showLogo(TL_TOPRIGHT); - mTrayMgr->showFrameStats(TL_TOPRIGHT); - mTrayMgr->toggleAdvancedFrameStats(); - - mTrayMgr->createTextBox(TL_TOPLEFT, "VolumeTerrainHelp", "Usage:\n\nHold the left mouse button, press\nwasd for movement and move the\nmouse for the direction.\nYou can add spheres with the\nmiddle mouse button and remove\nspheres with the right one.", 310, 150); -} - -//----------------------------------------------------------------------- - -void Sample_VolumeTerrain::cleanupContent(void) -{ - delete mVolumeRoot->getChunkParameters()->src; - OGRE_DELETE mVolumeRoot; - mVolumeRoot = 0; -} - -//----------------------------------------------------------------------- - -Sample_VolumeTerrain::Sample_VolumeTerrain(void) : mVolumeRoot(0), mHideAll(false) -{ - mInfo["Title"] = "Volume Terrain"; - mInfo["Description"] = "Demonstrates a volumetric terrain defined by an 3D texture and manipulation of the volume. The middle mouse button adds a sphere, a rightclick removes one."; - mInfo["Thumbnail"] = "thumb_volumeterrain.png"; - mInfo["Category"] = "Geometry"; -} - -//----------------------------------------------------------------------- - -bool Sample_VolumeTerrain::keyPressed(const KeyboardEvent& evt) -{ - switch(evt.keysym.sym) - { - case SDLK_F10: - mVolumeRoot->setVolumeVisible(!mVolumeRoot->getVolumeVisible()); - break; - case SDLK_F11: - mVolumeRoot->setOctreeVisible(!mVolumeRoot->getOctreeVisible()); - break; - case SDLK_F12: - mVolumeRoot->setDualGridVisible(!mVolumeRoot->getDualGridVisible()); - break; - case 'h': - if (mHideAll) - { - mTrayMgr->showAll(); - } - else - { - mTrayMgr->hideAll(); - } - mHideAll = !mHideAll; - break; - default: - break; - } - return SdkSample::keyPressed(evt); -} - -//----------------------------------------------------------------------- - -void Sample_VolumeTerrain::shootRay(Ray ray, bool doUnion) -{ - Vector3 intersection; - Real scale = mVolumeRoot->getChunkParameters()->scale; - bool intersects = mVolumeRoot->getChunkParameters()->src->getFirstRayIntersection(ray, intersection, scale); - if (intersects) - { - Real radius = (Real)2.5; - CSGSphereSource sphere(radius, intersection); - CSGOperationSource *operation = doUnion ? static_cast(new CSGUnionSource()) : new CSGDifferenceSource(); - static_cast(mVolumeRoot->getChunkParameters()->src)->combineWithSource(operation, &sphere, intersection, radius * (Real)1.5); - - mVolumeRoot->getChunkParameters()->updateFrom = intersection - radius * (Real)1.5; - mVolumeRoot->getChunkParameters()->updateTo = intersection + radius * (Real)1.5; - mVolumeRoot->load(mVolumeRootNode, Vector3::ZERO, Vector3(384), 5, mVolumeRoot->getChunkParameters()); - delete operation; - } -} - -//----------------------------------------------------------------------- - -bool Sample_VolumeTerrain::touchPressed(const TouchFingerEvent& evt) -{ - Ray ray = mCamera->getCameraToViewportRay(evt.x, evt.y); - shootRay(ray, true); - - return SdkSample::touchPressed(evt); -} - -//----------------------------------------------------------------------- - -bool Sample_VolumeTerrain::mousePressed(const MouseButtonEvent& evt) -{ - if (mMouseState == 0) - { - if (evt.button == BUTTON_MIDDLE) - { - mMouseState = 1; - mMouseCountdown = MOUSE_MODIFIER_TIME_LIMIT; - } - if (evt.button == BUTTON_RIGHT) - { - mMouseState = 2; - mMouseCountdown = MOUSE_MODIFIER_TIME_LIMIT; - } - } - - return SdkSample::mousePressed(evt); -} - -//----------------------------------------------------------------------- - -bool Sample_VolumeTerrain::mouseReleased(const MouseButtonEvent& evt) -{ - if (evt.button == BUTTON_MIDDLE || evt.button == BUTTON_RIGHT) - { - mMouseState = 0; - } - - return SdkSample::mouseReleased(evt); -} - -//----------------------------------------------------------------------- - -bool Sample_VolumeTerrain::mouseMoved(const MouseMotionEvent& evt) -{ - int width = mWindow->getWidth(), height = mWindow->getHeight(); - - mMouseX = (Real)evt.x / (Real)width; - mMouseY = (Real)evt.y / (Real)height; - return SdkSample::mouseMoved(evt); -} - -//----------------------------------------------------------------------- - -bool Sample_VolumeTerrain::frameRenderingQueued(const Ogre::FrameEvent& evt) -{ - if (mMouseState != 0) - { - mMouseCountdown -= evt.timeSinceLastEvent; - if (mMouseCountdown <= (Real)0.0) - { - mMouseCountdown = MOUSE_MODIFIER_TIME_LIMIT; - Ray ray = mCamera->getCameraToViewportRay(mMouseX, mMouseY); - shootRay(ray, mMouseState == 1); - } - } - return SdkSample::frameRenderingQueued(evt); -} diff --git a/Samples/TerrainTessellation/include/TerrainTessellation.h b/Samples/TerrainTessellation/include/TerrainTessellation.h deleted file mode 100644 index 7ca4735c501..00000000000 --- a/Samples/TerrainTessellation/include/TerrainTessellation.h +++ /dev/null @@ -1,351 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2013 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#ifndef __TerrainTessellation_H__ -#define __TerrainTessellation_H__ - -#define TERRAIN_PAGE_MIN_X 0 -#define TERRAIN_PAGE_MIN_Y 0 -#define TERRAIN_PAGE_MAX_X 0 -#define TERRAIN_PAGE_MAX_Y 0 - -#include "SdkSample.h" -#include "OgreTerrain.h" -#include "OgreTerrainGroup.h" -#include "OgreTerrainQuadTreeNode.h" -#include "TerrainTessellationMaterialGenerator.h" -#include "OgreTerrainPaging.h" -#include "OgrePageManager.h" -#include "OgreImage.h" -#include "OgreTerrainAutoUpdateLod.h" - -#define TERRAIN_FILE_PREFIX String("testTerrain") -#define TERRAIN_FILE_SUFFIX String("dat") -#define TERRAIN_WORLD_SIZE 12000.0f -#define TERRAIN_SIZE 513 - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_TerrainTessellation : public SdkSample -{ -public: - - Sample_TerrainTessellation() - : mTerrainGroup(0) - , mTerrainPaging(0) - , mPageManager(0) - //, mFallVelocity(0) - //, mMode(MODE_NORMAL) - //, mLayerEdit(1) - //, mBrushSizeTerrainSpace(0.02) - //, mHeightUpdateCountDown(0) - , mTerrainsImported(false) - , mFly(false) - , mTerrainPos(1,1,1) - { - mInfo["Title"] = "TerrainTessellation"; - mInfo["Description"] = "Sample for terrain tessellation and the use of displacement mapping"; - mInfo["Thumbnail"] = "thumb_tesselation.png"; - mInfo["Category"] = "Unsorted"; - mInfo["Help"] = "Top Left: Multi-frame\nTop Right: Scrolling\nBottom Left: Rotation\nBottom Right: Scaling"; - } - - void testCapabilities(const RenderSystemCapabilities* caps) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "This sample is not yet finished." - " Sorry!", "Sample_TerrainTessellation::testCapabilities"); - if (!caps->hasCapability(RSC_TESSELLATION_HULL_PROGRAM) || !caps->hasCapability(RSC_TESSELLATION_DOMAIN_PROGRAM)) - { - OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Your graphics card does not support tesselation shaders. Sorry!", - "Sample_TerrainTessellation:testCapabilities"); - } - if (!GpuProgramManager::getSingleton().isSyntaxSupported("vs_5_0") && - !GpuProgramManager::getSingleton().isSyntaxSupported("hs_5_0") && - !GpuProgramManager::getSingleton().isSyntaxSupported("ds_5_0") && - !GpuProgramManager::getSingleton().isSyntaxSupported("ps_5_0") && - !GpuProgramManager::getSingleton().isSyntaxSupported("hlsl")) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Your card does not support the shader model 5.0 needed for this sample, " - "so you cannot run this sample. Sorry!", "Sample_TerrainTessellation::testCapabilities"); - } - } - - bool frameRenderingQueued(const FrameEvent& evt) - { - if (!mFly) - { - // clamp to terrain - Vector3 camPos = mCamera->getPosition(); - Ray ray; - ray.setOrigin(Vector3(camPos.x, mTerrainPos.y + 10000, camPos.z)); - ray.setDirection(Vector3::NEGATIVE_UNIT_Y); - - TerrainGroup::RayResult rayResult = mTerrainGroup->rayIntersects(ray); - const Real distanceAboveTerrain = 50; - if (rayResult.hit) - mCameraNode->setPosition(camPos.x, rayResult.position.y + distanceAboveTerrain, camPos.z); - } - - return SdkSample::frameRenderingQueued(evt); // don't forget the parent class updates! - } - - void checkBoxToggled(CheckBox* box) - { - if (box->getName() == "Wire") - { - if( mCamera->getPolygonMode() == PM_WIREFRAME ) - mCamera->setPolygonMode(PM_SOLID); - else - mCamera->setPolygonMode(PM_WIREFRAME); - } - if (box->getName() == "Tessellation") - { - // disable tessellation - } - if (box == mFlyBox) - { - mFly = mFlyBox->isChecked(); - } - } - - void sliderMoved(Slider* slider) - { - if (slider->getName() == "tessellationAmount") - { - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( "TerrainTessellation" ).staticCast(); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_tessellationAmount", slider->getValue() ); - } - if (slider->getName() == "ridgeOctaves") - { - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( "TerrainTessellation" ).staticCast(); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_ridgeOctaves", slider->getValue() ); - } - if (slider->getName() == "fBmOctaves") - { - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( "TerrainTessellation" ).staticCast(); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_fBmOctaves", slider->getValue() ); - } - if (slider->getName() == "TwistOctaves") - { - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( "TerrainTessellation" ).staticCast(); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_TwistOctaves", slider->getValue() ); - } - if (slider->getName() == "detailNoiseScale") - { - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( "TerrainTessellation" ).staticCast(); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_detailNoiseScale", slider->getValue() ); - } - if (slider->getName() == "targetTrianglesWidth") - { - MaterialPtr lMaterialPtr = MaterialManager::getSingleton().getByName( "TerrainTessellation" ).staticCast(); - lMaterialPtr->getTechnique(0)->getPass(0)->getTessellationHullProgramParameters()->setNamedConstant( "g_targetTrianglesWidth", slider->getValue() ); - } - } - -protected: - - void configureTerrainDefaults(Light* l) - { - // Configure global - mTerrainGlobals->setMaxPixelError(8); - // testing composite map - mTerrainGlobals->setCompositeMapDistance(3000); - //mTerrainGlobals->setUseRayBoxDistanceCalculation(true); - mTerrainGlobals->getDefaultMaterialGenerator()->setLightmapEnabled(false); - - mTerrainGlobals->setCompositeMapAmbient(mSceneMgr->getAmbientLight()); - //mTerrainGlobals->setCompositeMapAmbient(ColourValue::Red); - mTerrainGlobals->setCompositeMapDiffuse(l->getDiffuseColour()); - - // Configure default import settings for if we use imported image - Terrain::ImportData& defaultimp = mTerrainGroup->getDefaultImportSettings(); - defaultimp.terrainSize = TERRAIN_SIZE; - defaultimp.worldSize = TERRAIN_WORLD_SIZE; - defaultimp.inputScale = 600; - defaultimp.minBatchSize = 33; - defaultimp.maxBatchSize = 65; - // textures - defaultimp.layerList.resize(3); - defaultimp.layerList[0].worldSize = 100; - defaultimp.layerList[0].textureNames.push_back("dirt_grayrocky_diffusespecular.dds"); - defaultimp.layerList[0].textureNames.push_back("dirt_grayrocky_normalheight.dds"); - defaultimp.layerList[1].worldSize = 30; - defaultimp.layerList[1].textureNames.push_back("grass_green-01_diffusespecular.dds"); - defaultimp.layerList[1].textureNames.push_back("grass_green-01_normalheight.dds"); - defaultimp.layerList[2].worldSize = 200; - defaultimp.layerList[2].textureNames.push_back("growth_weirdfungus-03_diffusespecular.dds"); - defaultimp.layerList[2].textureNames.push_back("growth_weirdfungus-03_normalheight.dds"); - - // Init custom materialgenerator - TerrainMaterialGeneratorPtr terrainMaterialGenerator; - - // Set Ogre Material with the name "TerrainMaterial" in constructor - TerrainTessellationMaterialGenerator *terrainMaterial = OGRE_NEW TerrainTessellationMaterialGenerator("Ogre/TerrainTessellation/Terrain"); - terrainMaterialGenerator.bind( terrainMaterial ); - - mTerrainGlobals->setDefaultMaterialGenerator( terrainMaterialGenerator ); - } - - void setupContent() - { - // create our main node to attach our entities to - mObjectNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mSceneMgr->setSkyBox(true, "Examples/SpaceSkyBox", 5000); // set our skybox - - setupLights(); - setupControls(); - - // set our camera - mCamera->setFOVy(Ogre::Degree(50.0)); - mCamera->setFOVy(Ogre::Degree(50.0)); - mCamera->setNearClipDistance(0.01f); - mCamera->lookAt(Ogre::Vector3::ZERO); - mCameraNode->setPosition(0, 0, 500); - mCameraMan->setTopSpeed(100); - - setDragLook(true); - - // Set our camera to orbit around the origin at a suitable distance - mCameraMan->setStyle(CS_ORBIT); - mCameraMan->setYawPitchDist(Radian(0), Radian(0), 400); - - MaterialManager::getSingleton().setDefaultTextureFiltering(TFO_ANISOTROPIC); - MaterialManager::getSingleton().setDefaultAnisotropy(7); - - mSceneMgr->setFog(FOG_LINEAR, ColourValue(0.7, 0.7, 0.8), 0, 4000, 10000); - - mTrayMgr->showCursor(); - - mTerrainGlobals = OGRE_NEW TerrainGlobalOptions(); - - mTerrainGroup = OGRE_NEW TerrainGroup(mSceneMgr, Terrain::ALIGN_X_Z, TERRAIN_SIZE, TERRAIN_WORLD_SIZE); - mTerrainGroup->setFilenameConvention(TERRAIN_FILE_PREFIX, TERRAIN_FILE_SUFFIX); - mTerrainGroup->setOrigin(mTerrainPos); - mTerrainGroup->setAutoUpdateLod( TerrainAutoUpdateLodFactory::getAutoUpdateLod(BY_DISTANCE) ); // probably will do it in tessellation stages. - - Vector3 lightdir(0.55, -0.3, 0.75); - lightdir.normalise(); - - Light* l = mSceneMgr->createLight("tstLight"); - l->setType(Light::LT_DIRECTIONAL); - l->setDirection(lightdir); - l->setDiffuseColour(ColourValue::White); - l->setSpecularColour(ColourValue(0.4, 0.4, 0.4)); - - configureTerrainDefaults(l); - - mTerrainGroup->freeTemporaryResources(); - } - - void unloadResources() - { - - } - - void setupView() - { - SdkSample::setupView(); - // put camera at world center, so that it's difficult to reach the edge - Vector3 worldCenter(0,0,0); - mCameraNode->setPosition(mTerrainPos+worldCenter); - mCamera->lookAt(mTerrainPos); - mCamera->setNearClipDistance(0.1); - mCamera->setFarClipDistance(50000); - - mCamera->setFarClipDistance(0); // enable infinite far clip distance - } - - void setupLights() - { - mSceneMgr->setAmbientLight(ColourValue::Black); - mViewport->setBackgroundColour(ColourValue(0.41f, 0.41f, 0.41f)); - } - - void setupControls() - { - mTrayMgr->showCursor(); - - // make room for the controls - mTrayMgr->showLogo(TL_TOPRIGHT); - mTrayMgr->showFrameStats(TL_TOPRIGHT); - mTrayMgr->toggleAdvancedFrameStats(); - - mTrayMgr->createCheckBox(TL_TOPLEFT, "Wire", "Wire Frame")->setChecked(false, false); - mTrayMgr->createCheckBox(TL_TOPLEFT, "Tessellation", "Hardware Tessellation")->setChecked(true, false); - - mTessellationAmount = mTrayMgr->createThickSlider(TL_TOPLEFT, "tessellationAmount", "Tessellation Amount", 200, 40, 1, 8, 8); - mTessellationAmount->show(); - - mRidgeOctaves = mTrayMgr->createThickSlider(TL_TOPLEFT, "ridgeOctaves", "Ridge Octaves", 200, 40, 0, 15, 15); - mRidgeOctaves->show(); - - mfBmOctaves = mTrayMgr->createThickSlider(TL_TOPLEFT, "fBmOctaves", "fBm Octaves", 200, 40, 0, 15, 15); - mfBmOctaves->show(); - - mTwistOctaves = mTrayMgr->createThickSlider(TL_TOPLEFT, "TwistOctaves", "Twist Octaves", 200, 40, 0, 15, 15); - mTwistOctaves->show(); - - mDetailNoiseScale = mTrayMgr->createThickSlider(TL_TOPLEFT, "detailNoiseScale", "Detail noise scale", 200, 40, 0, 2.0, 200); - mDetailNoiseScale->show(); - - mTargetTrianglesWidth = mTrayMgr->createThickSlider(TL_TOPLEFT, "targetTrianglesWidth", "Target triangles width", 200, 40, 1, 50, 50); - mTargetTrianglesWidth->show(); - - mFlyBox = mTrayMgr->createCheckBox(TL_BOTTOM, "Fly", "Fly"); - mFlyBox->setChecked(false, true); - - // a friendly reminder - StringVector names; - names.push_back("Help"); - mTrayMgr->createParamsPanel(TL_TOPLEFT, "Help", 100, names)->setParamValue(0, "H/F1"); - } - - void cleanupContent() - { - // clean up properly to avoid interfering with subsequent samples - if (mPaging) - { - OGRE_DELETE mTerrainPaging; - OGRE_DELETE mPageManager; - } - else - OGRE_DELETE mTerrainGroup; - - OGRE_DELETE mTerrainGlobals; - } - - SceneNode* mObjectNode; - Slider* mTessellationAmount; - Slider* mRidgeOctaves; - Slider* mfBmOctaves; - Slider* mTwistOctaves; - Slider* mDetailNoiseScale; - Slider* mTargetTrianglesWidth; - CheckBox* mFlyBox; - - TerrainGlobalOptions* mTerrainGlobals; - TerrainGroup* mTerrainGroup; - bool mPaging; - TerrainPaging* mTerrainPaging; - PageManager* mPageManager; - - bool mTerrainsImported; - - bool mFly; - Vector3 mTerrainPos; - -}; - -#endif \ No newline at end of file diff --git a/Samples/TerrainTessellation/include/TerrainTessellationMaterialGenerator.h b/Samples/TerrainTessellation/include/TerrainTessellationMaterialGenerator.h deleted file mode 100644 index 990b94a75e4..00000000000 --- a/Samples/TerrainTessellation/include/TerrainTessellationMaterialGenerator.h +++ /dev/null @@ -1,72 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2013 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#ifndef CUSTOMTERRAINMATERIAL_H -#define CUSTOMTERRAINMATERIAL_H - -#include "Ogre.h" -#include "OgreTerrain.h" -#include "OgreTerrainMaterialGenerator.h" -#include "OgreTerrainPrerequisites.h" -#include "OgreGpuProgramParams.h" - -using namespace Ogre; - -class TerrainTessellationMaterialGenerator : public TerrainMaterialGenerator -{ -public: - - TerrainTessellationMaterialGenerator(Ogre::String materialName, bool addNormalmap=true, bool cloneMaterial=true); - - void setMaterialByName(const Ogre::String materialName); - void addNormalMapOnGenerate(bool set) { mAddNormalMap=set; }; - void cloneMaterialOnGenerate(bool set) { mCloneMaterial=set; }; - - Ogre::String getMaterialName() { return mMaterialName; }; - - class Profile : public TerrainMaterialGenerator::Profile - { - public: - Profile(Ogre::TerrainMaterialGenerator* parent, const Ogre::String& name, const Ogre::String& desc); - ~Profile(); - - bool isVertexCompressionSupported() const { return false; } - - MaterialPtr generate(const Terrain* terrain); - - MaterialPtr generateForCompositeMap(const Terrain* terrain); - - Ogre::uint8 getMaxLayers(const Terrain* terrain) const; - - void updateParams(const MaterialPtr& mat, const Terrain* terrain); - - void updateParamsForCompositeMap(const MaterialPtr& mat, const Terrain* terrain); - - void requestOptions(Terrain* terrain); - - bool isLightmapEnabled() const { return mLightmapEnabled; } - /** Whether to support a light map over the terrain in the shader, - if it's present (default true). - */ - void setLightmapEnabled(bool enabled); - - bool mLightmapEnabled; - }; -protected: - Ogre::String mMaterialName; - bool mCloneMaterial; - bool mAddNormalMap; -}; - -#endif \ No newline at end of file diff --git a/Samples/TerrainTessellation/src/TerrainTessellationMaterialGenerator.cpp b/Samples/TerrainTessellation/src/TerrainTessellationMaterialGenerator.cpp deleted file mode 100644 index 8ab63ff1588..00000000000 --- a/Samples/TerrainTessellation/src/TerrainTessellationMaterialGenerator.cpp +++ /dev/null @@ -1,126 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2013 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#include "OgreTerrainMaterialGeneratorA.h" -#include "OgreTerrain.h" -#include "OgreMaterialManager.h" -#include "OgreTechnique.h" -#include "OgrePass.h" -#include "OgreTextureUnitState.h" -#include "OgreGpuProgramManager.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreShadowCameraSetupPSSM.h" -#include "TerrainTessellationMaterialGenerator.h" - -using namespace Ogre; -TerrainTessellationMaterialGenerator::TerrainTessellationMaterialGenerator(Ogre::String materialName, bool addNormalmap, bool cloneMaterial) - : mMaterialName(materialName) - , mCloneMaterial(cloneMaterial) - , mAddNormalMap(addNormalmap) -{ - mProfiles.push_back(OGRE_NEW Profile(this, materialName, "Profile for rendering Ogre standard material")); - setActiveProfile(materialName); -} -// ----------------------------------------------------------------------------------------------------------------------- -void TerrainTessellationMaterialGenerator::setMaterialByName(const Ogre::String materialName) -{ - mMaterialName = materialName; - _markChanged(); -} -// ----------------------------------------------------------------------------------------------------------------------- -TerrainTessellationMaterialGenerator::Profile::Profile(TerrainMaterialGenerator* parent, const Ogre::String& name, const Ogre::String& desc) - : TerrainMaterialGenerator::Profile(parent, name, desc) - , mLightmapEnabled(false) -{ - -} -// ----------------------------------------------------------------------------------------------------------------------- -TerrainTessellationMaterialGenerator::Profile::~Profile() -{ - -} -// ----------------------------------------------------------------------------------------------------------------------- -MaterialPtr TerrainTessellationMaterialGenerator::Profile::generate(const Terrain* terrain) -{ - const Ogre::String& matName = terrain->getMaterialName(); - MaterialPtr mat = MaterialManager::getSingleton().getByName( matName ).staticCast(); - - if (mat) - MaterialManager::getSingleton().remove(matName); - - TerrainTessellationMaterialGenerator* parent = (TerrainTessellationMaterialGenerator*)getParent(); - - // Set Ogre material - mat = MaterialManager::getSingleton().getByName( parent->mMaterialName ).staticCast(); - - // Clone material - if(parent->mCloneMaterial) - { - mat = mat->clone(matName); - parent->mMaterialName = matName; - } - - // Add normalmap - if(parent->mAddNormalMap) - { - // Get default pass - Pass *p = mat->getTechnique(0)->getPass(0); - - // Add terrain's global normalmap to renderpass so the fragment program can find it. - TextureUnitState *tu = p->createTextureUnitState(matName+"/nm"); - - TexturePtr nmtx = terrain->getTerrainNormalMap(); - tu->_setTexturePtr(nmtx); - } - - return mat; -} -// ----------------------------------------------------------------------------------------------------------------------- -MaterialPtr TerrainTessellationMaterialGenerator::Profile::generateForCompositeMap(const Terrain* terrain) -{ - return terrain->_getCompositeMapMaterial(); -} -// ----------------------------------------------------------------------------------------------------------------------- -Ogre::uint8 TerrainTessellationMaterialGenerator::Profile::getMaxLayers(const Terrain* terrain) const -{ - return 0; -} -// ----------------------------------------------------------------------------------------------------------------------- -void TerrainTessellationMaterialGenerator::Profile::updateParams(const MaterialPtr& mat, const Terrain* terrain) -{ - -} -// ----------------------------------------------------------------------------------------------------------------------- -void TerrainTessellationMaterialGenerator::Profile::updateParamsForCompositeMap(const MaterialPtr& mat, const Terrain* terrain) -{ - -} -// ----------------------------------------------------------------------------------------------------------------------- -void TerrainTessellationMaterialGenerator::Profile::requestOptions(Terrain* terrain) -{ - terrain->_setMorphRequired(false); - terrain->_setNormalMapRequired(true); // enable global normal map - terrain->_setLightMapRequired(false); - terrain->_setCompositeMapRequired(false); -}; -// ----------------------------------------------------------------------------------------------------------------------- -void TerrainTessellationMaterialGenerator::Profile::setLightmapEnabled(bool enabled) -{ - if (enabled != mLightmapEnabled) - { - mLightmapEnabled = enabled; - mParent->_markChanged(); - } -}; \ No newline at end of file diff --git a/Samples/Tutorials/BasicTutorial1.cpp b/Samples/Tutorials/BasicTutorial1.cpp deleted file mode 100644 index 34db429e727..00000000000 --- a/Samples/Tutorials/BasicTutorial1.cpp +++ /dev/null @@ -1,172 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - - -Copyright (c) 2000-2013 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ - -//! [fullsource] - -#include "Ogre.h" -#include "OgreApplicationContext.h" -#include "OgreInput.h" -#include "OgreRTShaderSystem.h" -#include - -using namespace Ogre; -using namespace OgreBites; - -class BasicTutorial1 - : public ApplicationContext - , public InputListener -{ -public: - BasicTutorial1(); - virtual ~BasicTutorial1() {} - - void setup(); - bool keyPressed(const KeyboardEvent& evt); -}; - - -BasicTutorial1::BasicTutorial1() - : ApplicationContext("OgreTutorialApp") -{ -} - - -void BasicTutorial1::setup() -{ - // do not forget to call the base first - ApplicationContext::setup(); - addInputListener(this); - - // get a pointer to the already created root - Root* root = getRoot(); - SceneManager* scnMgr = root->createSceneManager(); - - // register our scene with the RTSS - RTShader::ShaderGenerator* shadergen = RTShader::ShaderGenerator::getSingletonPtr(); - shadergen->addSceneManager(scnMgr); - - // -- tutorial section start -- - //! [turnlights] - scnMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - //! [turnlights] - - //! [newlight] - Light* light = scnMgr->createLight("MainLight"); - SceneNode* lightNode = scnMgr->getRootSceneNode()->createChildSceneNode(); - lightNode->attachObject(light); - //! [newlight] - - //! [lightpos] - lightNode->setPosition(20, 80, 50); - //! [lightpos] - - //! [camera] - SceneNode* camNode = scnMgr->getRootSceneNode()->createChildSceneNode(); - - // create the camera - Camera* cam = scnMgr->createCamera("myCam"); - cam->setNearClipDistance(5); // specific to this sample - cam->setAutoAspectRatio(true); - camNode->attachObject(cam); - camNode->setPosition(0, 0, 140); - - // and tell it to render into the main window - getRenderWindow()->addViewport(cam); - //! [camera] - - //! [entity1] - Entity* ogreEntity = scnMgr->createEntity("ogrehead.mesh"); - //! [entity1] - - //! [entity1node] - SceneNode* ogreNode = scnMgr->getRootSceneNode()->createChildSceneNode(); - //! [entity1node] - - //! [entity1nodeattach] - ogreNode->attachObject(ogreEntity); - //! [entity1nodeattach] - - //! [cameramove] - camNode->setPosition(0, 47, 222); - //! [cameramove] - - //! [entity2] - Entity* ogreEntity2 = scnMgr->createEntity("ogrehead.mesh"); - SceneNode* ogreNode2 = scnMgr->getRootSceneNode()->createChildSceneNode(Vector3(84, 48, 0)); - ogreNode2->attachObject(ogreEntity2); - //! [entity2] - - //! [entity3] - Entity* ogreEntity3 = scnMgr->createEntity("ogrehead.mesh"); - SceneNode* ogreNode3 = scnMgr->getRootSceneNode()->createChildSceneNode(); - ogreNode3->setPosition(0, 104, 0); - ogreNode3->setScale(2, 1.2, 1); - ogreNode3->attachObject(ogreEntity3); - //! [entity3] - - //! [entity4] - Entity* ogreEntity4 = scnMgr->createEntity("ogrehead.mesh"); - SceneNode* ogreNode4 = scnMgr->getRootSceneNode()->createChildSceneNode(); - ogreNode4->setPosition(-84, 48, 0); - ogreNode4->roll(Degree(-90)); - ogreNode4->attachObject(ogreEntity4); - //! [entity4] - - // -- tutorial section end -- -} - - -bool BasicTutorial1::keyPressed(const KeyboardEvent& evt) -{ - if (evt.keysym.sym == SDLK_ESCAPE) - { - getRoot()->queueEndRendering(); - } - return true; -} - - -int main(int argc, char **argv) -{ - try - { - BasicTutorial1 app; - app.initApp(); - app.getRoot()->startRendering(); - app.closeApp(); - } - catch (const std::exception& e) - { - std::cerr << "Error occurred during execution: " << e.what() << '\n'; - return 1; - } - - return 0; -} - -//! [fullsource] diff --git a/Samples/Tutorials/BasicTutorial2.cpp b/Samples/Tutorials/BasicTutorial2.cpp deleted file mode 100644 index 19055b62210..00000000000 --- a/Samples/Tutorials/BasicTutorial2.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/*------------------------------------------------------------------------- -This source file is a part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - - -Copyright (c) 2000-2013 Torus Knot Software Ltd -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE --------------------------------------------------------------------------*/ - -//! [starter] - -#include -#include - -#include "Ogre.h" -#include "OgreApplicationContext.h" -#include "OgreInput.h" -#include "OgreRTShaderSystem.h" -#include "OgreCameraMan.h" - -using namespace Ogre; -using namespace OgreBites; - -class TutorialApplication - : public ApplicationContext - , public InputListener -{ -public: - TutorialApplication(); - virtual ~TutorialApplication(); - - void setup(); - bool keyPressed(const KeyboardEvent& evt); -}; - - -TutorialApplication::TutorialApplication() - : ApplicationContext("OgreTutorialApp") -{ -} - - -TutorialApplication::~TutorialApplication() -{ -} - - -void TutorialApplication::setup() -{ - // do not forget to call the base first - ApplicationContext::setup(); - addInputListener(this); - - // get a pointer to the already created root - Root* root = getRoot(); - SceneManager* scnMgr = root->createSceneManager(); - - // register our scene with the RTSS - RTShader::ShaderGenerator* shadergen = RTShader::ShaderGenerator::getSingletonPtr(); - shadergen->addSceneManager(scnMgr); - - // -- tutorial section start -- - //! [cameracreate] - SceneNode* camNode = scnMgr->getRootSceneNode()->createChildSceneNode(); - Camera* cam = scnMgr->createCamera("myCam"); - //! [cameracreate] - - //! [cameraposition] - camNode->setPosition(200, 300, 400); - camNode->lookAt(Vector3(0, 0, 0), Node::TransformSpace::TS_WORLD); - //! [cameraposition] - - //! [cameralaststep] - cam->setNearClipDistance(5); - camNode->attachObject(cam); - //! [cameralaststep] - - //! [addviewport] - Viewport* vp = getRenderWindow()->addViewport(cam); - //! [addviewport] - - //! [viewportback] - vp->setBackgroundColour(ColourValue(0, 0, 0)); - //! [viewportback] - - //! [cameraratio] - cam->setAspectRatio(Real(vp->getActualWidth()) / Real(vp->getActualHeight())); - //! [cameraratio] - - //! [lightingsset] - scnMgr->setAmbientLight(ColourValue(0, 0, 0)); - scnMgr->setShadowTechnique(ShadowTechnique::SHADOWTYPE_STENCIL_ADDITIVE); - //! [lightingsset] - - //! [ninja] - Entity* ninjaEntity = scnMgr->createEntity("ninja.mesh"); - ninjaEntity->setCastShadows(true); - - scnMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ninjaEntity); - //! [ninja] - - //! [plane] - Plane plane(Vector3::UNIT_Y, 0); - //! [plane] - - //! [planedefine] - MeshManager::getSingleton().createPlane( - "ground", RGN_DEFAULT, - plane, - 1500, 1500, 20, 20, - true, - 1, 5, 5, - Vector3::UNIT_Z); - //! [planedefine] - - //! [planecreate] - Entity* groundEntity = scnMgr->createEntity("ground"); - scnMgr->getRootSceneNode()->createChildSceneNode()->attachObject(groundEntity); - //! [planecreate] - - //! [planenoshadow] - groundEntity->setCastShadows(false); - //! [planenoshadow] - - //! [planesetmat] - groundEntity->setMaterialName("Examples/Rockwall"); - //! [planesetmat] - - //! [spotlight] - Light* spotLight = scnMgr->createLight("SpotLight"); - //! [spotlight] - - //! [spotlightcolor] - spotLight->setDiffuseColour(0, 0, 1.0); - spotLight->setSpecularColour(0, 0, 1.0); - //! [spotlightcolor] - - //! [spotlighttype] - spotLight->setType(Light::LT_SPOTLIGHT); - //! [spotlighttype] - - //! [spotlightposrot] - SceneNode* spotLightNode = scnMgr->getRootSceneNode()->createChildSceneNode(); - spotLightNode->attachObject(spotLight); - spotLightNode->setDirection(-1, -1, 0); - spotLightNode->setPosition(Vector3(200, 200, 0)); - //! [spotlightposrot] - - //! [spotlightrange] - spotLight->setSpotlightRange(Degree(35), Degree(50)); - //! [spotlightrange] - - //! [directlight] - Light* directionalLight = scnMgr->createLight("DirectionalLight"); - directionalLight->setType(Light::LT_DIRECTIONAL); - //! [directlight] - - //! [directlightcolor] - directionalLight->setDiffuseColour(ColourValue(0.4, 0, 0)); - directionalLight->setSpecularColour(ColourValue(0.4, 0, 0)); - //! [directlightcolor] - - //! [directlightdir] - SceneNode* directionalLightNode = scnMgr->getRootSceneNode()->createChildSceneNode(); - directionalLightNode->attachObject(directionalLight); - directionalLightNode->setDirection(Vector3(0, -1, 1)); - //! [directlightdir] - - //! [pointlight] - Light* pointLight = scnMgr->createLight("PointLight"); - pointLight->setType(Light::LT_POINT); - //! [pointlight] - - //! [pointlightcolor] - pointLight->setDiffuseColour(0.3, 0.3, 0.3); - pointLight->setSpecularColour(0.3, 0.3, 0.3); - //! [pointlightcolor] - - //! [pointlightpos] - SceneNode* pointLightNode = scnMgr->getRootSceneNode()->createChildSceneNode(); - pointLightNode->attachObject(pointLight); - pointLightNode->setPosition(Vector3(0, 150, 250)); - //! [pointlightpos] - // -- tutorial section end -- -} - - -bool TutorialApplication::keyPressed(const KeyboardEvent& evt) -{ - if (evt.keysym.sym == SDLK_ESCAPE) - { - getRoot()->queueEndRendering(); - } - return true; -} - - -int main(int argc, char **argv) -{ - try - { - TutorialApplication app; - app.initApp(); - app.getRoot()->startRendering(); - app.closeApp(); - } - catch (const std::exception& e) - { - std::cerr << "Error occurred during execution: " << e.what() << '\n'; - return 1; - } - - return 0; -} - -//! [starter] diff --git a/Samples/Tutorials/Bootstrap.cpp b/Samples/Tutorials/Bootstrap.cpp deleted file mode 100644 index 6f4ab4ee770..00000000000 --- a/Samples/Tutorials/Bootstrap.cpp +++ /dev/null @@ -1,74 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#include "Ogre.h" -#include "OgreApplicationContext.h" - -//! [key_handler] -class KeyHandler : public OgreBites::InputListener -{ - bool keyPressed(const OgreBites::KeyboardEvent& evt) override - { - if (evt.keysym.sym == OgreBites::SDLK_ESCAPE) - { - Ogre::Root::getSingleton().queueEndRendering(); - } - return true; - } -}; -//! [key_handler] - -int main(int argc, char *argv[]) -{ -//! [constructor] - OgreBites::ApplicationContext ctx("OgreTutorialApp"); - ctx.initApp(); -//! [constructor] - -//! [setup] - // get a pointer to the already created root - Ogre::Root* root = ctx.getRoot(); - Ogre::SceneManager* scnMgr = root->createSceneManager(); - - // register our scene with the RTSS - Ogre::RTShader::ShaderGenerator* shadergen = Ogre::RTShader::ShaderGenerator::getSingletonPtr(); - shadergen->addSceneManager(scnMgr); - - // without light we would just get a black screen - Ogre::Light* light = scnMgr->createLight("MainLight"); - Ogre::SceneNode* lightNode = scnMgr->getRootSceneNode()->createChildSceneNode(); - lightNode->setPosition(0, 10, 15); - lightNode->attachObject(light); - - // also need to tell where we are - Ogre::SceneNode* camNode = scnMgr->getRootSceneNode()->createChildSceneNode(); - camNode->setPosition(0, 0, 15); - camNode->lookAt(Ogre::Vector3(0, 0, -1), Ogre::Node::TS_PARENT); - - // create the camera - Ogre::Camera* cam = scnMgr->createCamera("myCam"); - cam->setNearClipDistance(5); // specific to this sample - cam->setAutoAspectRatio(true); - camNode->attachObject(cam); - - // and tell it to render into the main window - ctx.getRenderWindow()->addViewport(cam); - - // finally something to render - Ogre::Entity* ent = scnMgr->createEntity("Sinbad.mesh"); - Ogre::SceneNode* node = scnMgr->getRootSceneNode()->createChildSceneNode(); - node->attachObject(ent); -//! [setup] - -//! [main] - // register for input events - KeyHandler keyHandler; - ctx.addInputListener(&keyHandler); - - ctx.getRoot()->startRendering(); - ctx.closeApp(); -//! [main] - return 0; -} diff --git a/Samples/Tutorials/CMakeLists.txt b/Samples/Tutorials/CMakeLists.txt deleted file mode 100644 index 0397276fa7b..00000000000 --- a/Samples/Tutorials/CMakeLists.txt +++ /dev/null @@ -1,23 +0,0 @@ -cmake_minimum_required (VERSION 3.10) -project(OgreTutorialsSample) - -# required for Ogre 1.11+ -set(CMAKE_CXX_STANDARD 11) - -## [discover_ogre] -# The COMPONENTS part checks that OGRE was built the way we need it -# The CONFIG flag makes sure we get OGRE instead of OGRE-next -find_package(OGRE REQUIRED COMPONENTS Bites CONFIG) - -# add the source files as usual -add_executable(0_Bootstrap Bootstrap.cpp) - -# this also sets the includes and pulls third party dependencies -target_link_libraries(0_Bootstrap OgreBites) -## [discover_ogre] - -add_executable(1_FirstScene BasicTutorial1.cpp) -target_link_libraries(1_FirstScene OgreBites) - -add_executable(2_CamerasAndShadows BasicTutorial2.cpp) -target_link_libraries(2_CamerasAndShadows OgreBites) diff --git a/Samples/VolumeTex/include/Julia.h b/Samples/VolumeTex/include/Julia.h deleted file mode 100644 index 54f2c7a223b..00000000000 --- a/Samples/VolumeTex/include/Julia.h +++ /dev/null @@ -1,113 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ -/* Original author: John C. Hare - * Date: June 26, 1996 (although I've had these around for at least 6 years) - * Adapted to C++ by W.J. van der Laan 2004 - */ -#ifndef H_Q_Julia -#define H_Q_Julia -#include - -/** - * Simple, fast, inline quaternion math functions - */ -struct Quat { - float r,i,j,k; -}; - -inline void qadd(Quat &a, const Quat &b) -{ - a.r += b.r; - a.i += b.i; - a.j += b.j; - a.k += b.k; -} - -inline void qmult(Quat &c, const Quat &a, const Quat &b) -{ - c.r = a.r*b.r - a.i*b.i - a.j*b.j - a.k*b.k; - c.i = a.r*b.i + a.i*b.r + a.j*b.k - a.k*b.j; - c.j = a.r*b.j + a.j*b.r + a.k*b.i - a.i*b.k; - c.k = a.r*b.k + a.k*b.r + a.i*b.j - a.j*b.i; -} - -inline void qsqr(Quat &b, const Quat &a) -{ - b.r = a.r*a.r - a.i*a.i - a.j*a.j - a.k*a.k; - b.i = 2.0f*a.r*a.i; - b.j = 2.0f*a.r*a.j; - b.k = 2.0f*a.r*a.k; -} - -/** - * Implicit function that evaluates the Julia set. - */ -class Julia { -private: - float global_real, global_imag, global_theta; - Quat oc,c,eio,emio; -public: - Julia(float global_real, float global_imag, float global_theta); - inline float eval(float x, float y, float z) { - Quat q, temp; - int i; - - q.r = x; - q.i = y; - q.j = z; - q.k = 0.0; - - for (i = 30; i > 0; i--) { - qsqr(temp, q); - qmult(q, emio, temp); - qadd(q, c); - - if (q.r*q.r + q.i*q.i + q.j*q.j + q.k*q.k > 8.0) - break; - } - - return((float)i); - } -}; - - -Julia::Julia(float in_global_real, float in_global_imag, float in_global_theta): - global_real(in_global_real), global_imag(in_global_imag), global_theta(in_global_theta) { - - oc.r = global_real; - oc.i = global_imag; - oc.j = oc.k = 0.0; - - eio.r = cos(global_theta); - eio.i = sin(global_theta); - eio.j = 0.0; - eio.k = 0.0; - - emio.r = cos(-global_theta); - emio.i = sin(-global_theta); - emio.j = 0.0; - emio.k = 0.0; - - /*** - *** multiply eio*c only once at the beginning of iteration - *** (since q |-> sqrt(eio*(q-eio*c))) - *** q -> e-io*q^2 - eio*c - ***/ - - qmult(c, eio,oc); - -} - - -#endif diff --git a/Samples/VolumeTex/include/ThingRenderable.h b/Samples/VolumeTex/include/ThingRenderable.h deleted file mode 100644 index 38c868bf8ef..00000000000 --- a/Samples/VolumeTex/include/ThingRenderable.h +++ /dev/null @@ -1,53 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ -#ifndef H_THINGRENDERABLE -#define H_THINGRENDERABLE - -#include "OgrePrerequisites.h" -#include "OgreSimpleRenderable.h" -#include "OgreQuaternion.h" -#include "OgreVector.h" - -/** Quad fragments that rotate around origin (0,0,0) in a random orbit, always oriented to 0,0,0. - @author W.J. van der Laan -*/ -class ThingRenderable: public Ogre::SimpleRenderable { -public: - /** Create one this object. - @param radius Radius of orbits - @param count Number of quads - @param qsize Size of quads - */ - ThingRenderable(float radius, size_t count, float qsize); - ~ThingRenderable(); - - Ogre::Real getBoundingRadius() const override; - Ogre::Real getSquaredViewDepth(const Ogre::Camera*) const override; - /** - * Notify that t seconds have elapsed. - */ - void addTime(float t); -protected: - void initialise(); - void fillBuffer(); - - Ogre::HardwareVertexBufferSharedPtr vbuf;// Our vertex buffer - float mRadius; - size_t mCount; - float mQSize; - std::vector things; - std::vector orbits; -}; - -#endif diff --git a/Samples/VolumeTex/include/VolumeRenderable.h b/Samples/VolumeTex/include/VolumeRenderable.h deleted file mode 100644 index 33fc9098d4c..00000000000 --- a/Samples/VolumeTex/include/VolumeRenderable.h +++ /dev/null @@ -1,49 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ -#ifndef OWL_VOLUMERENDERABLE -#define OWL_VOLUMERENDERABLE -#include "OgrePrerequisites.h" -#include "OgreSimpleRenderable.h" - -/** Direct Volume Rendering. - TODO: LOD: reduce number of slices in distance - TODO: option to generate normals for lighting - @author W.J. van der Laan -*/ -class VolumeRenderable: public Ogre::SimpleRenderable { -public: - VolumeRenderable(size_t nSlices, float size, const Ogre::String & texture); - ~VolumeRenderable(); - - // Copydoc Ogre::SimpleRenderable::notifyCurrentCamera - void _notifyCurrentCamera( Ogre::Camera* cam ) override; - void getWorldTransforms( Ogre::Matrix4* xform ) const override; - - /** - * Retrieves ratios of the origin-centered bounding sphere for this - * object. - */ - Ogre::Real getBoundingRadius() const override; - - Ogre::Real getSquaredViewDepth(const Ogre::Camera*) const override; -protected: - void initialise(); - - size_t mSlices; - float mSize; - float mRadius; - Ogre::Matrix3 mFakeOrientation; - Ogre::String mTexture; -}; -#endif diff --git a/Samples/VolumeTex/include/VolumeTex.h b/Samples/VolumeTex/include/VolumeTex.h deleted file mode 100644 index 2d4c24bcc7f..00000000000 --- a/Samples/VolumeTex/include/VolumeTex.h +++ /dev/null @@ -1,105 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ -#ifndef SAMPLES_VOLUMETEX_INCLUDE_VOLUMETEX_H_ -#define SAMPLES_VOLUMETEX_INCLUDE_VOLUMETEX_H_ - - -/** Generate 3D julia sets and render them as volume texture - This demonstrates - - User generated textures - - Procedural volume textures (Julia makes nice dust clouds) - - Custom renderables - @author W.J. van der Laan -*/ - -#include "SamplePlugin.h" -#include "SdkSample.h" - -using namespace Ogre; -using namespace OgreBites; - -class _OgreSampleClassExport Sample_VolumeTex : public SdkSample -{ -public: - - Sample_VolumeTex() - { - mInfo["Title"] = "Volume Textures"; - mInfo["Description"] = "Demonstrates the use of volume textures."; - mInfo["Thumbnail"] = "thumb_voltex.png"; - mInfo["Category"] = "Unsorted"; - } - - void testCapabilities(const RenderSystemCapabilities* caps) override - { - if (!caps->hasCapability(RSC_TEXTURE_3D)) - { - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "Your card does not support 3D textures, so cannot " - "run this demo. Sorry!", "Sample_VolumeTex::testCapabilities"); - } - } - -protected: - - TexturePtr ptex; - float global_real, global_imag, global_theta; - - void setupView(void) override - { - SdkSample::setupView(); - - // Create the camera - mCameraNode->setPosition(Vector3(220,-2,176)); - mCameraNode->lookAt(Vector3(0,0,0), Node::TS_PARENT); - mCamera->setNearClipDistance(5); - } - - void setupContent(void) override; - - bool frameRenderingQueued( const FrameEvent& evt ) override; - - void cleanupContent(void) override; - - void createControls() - { - mTrayMgr->createLabel(TL_TOPLEFT, "JuliaParamLabel", "Julia Parameters", 200); - mTrayMgr->createThickSlider(TL_TOPLEFT, "RealSlider", "Real", 200, 80, -1, 1, 50)->setValue(global_real, false); - mTrayMgr->createThickSlider(TL_TOPLEFT, "ImagSlider", "Imag", 200, 80, -1, 1, 50)->setValue(global_imag, false); - mTrayMgr->createThickSlider(TL_TOPLEFT, "ThetaSlider", "Theta", 200, 80, -1, 1, 50)->setValue(global_theta, false); - mTrayMgr->showCursor(); - } - - void sliderMoved(Slider* slider) override - { - if (slider->getName() == "RealSlider") - { - global_real = slider->getValue(); - } - else if (slider->getName() == "ImagSlider") - { - global_imag = slider->getValue(); - } - else if (slider->getName() == "ThetaSlider") - { - global_theta = slider->getValue(); - } - generate(); - } - - void generate(); -}; - - - -#endif /* SAMPLES_VOLUMETEX_INCLUDE_VOLUMETEX_H_ */ diff --git a/Samples/VolumeTex/src/ThingRenderable.cpp b/Samples/VolumeTex/src/ThingRenderable.cpp deleted file mode 100644 index fc10bb19ce5..00000000000 --- a/Samples/VolumeTex/src/ThingRenderable.cpp +++ /dev/null @@ -1,163 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ -#include "ThingRenderable.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreHardwareIndexBuffer.h" -#include "OgreHardwareBufferManager.h" -#include "OgreCamera.h" -using namespace Ogre; - -ThingRenderable::ThingRenderable(float radius, size_t count, float qsize): - mRadius(radius), - mCount(count), - mQSize(qsize) -{ - mBox = Ogre::AxisAlignedBox(-radius, -radius, -radius, radius, radius, radius); - initialise(); - fillBuffer(); -} -ThingRenderable::~ThingRenderable() -{ - // need to release IndexData and vertexData created for renderable - delete mRenderOp.indexData; - delete mRenderOp.vertexData; -} - -void ThingRenderable::addTime(float t) -{ - for(size_t x=0; xvertexStart = 0; - vdata->vertexCount = nvertices; - - VertexDeclaration* decl = vdata->vertexDeclaration; - VertexBufferBinding* bind = vdata->vertexBufferBinding; - - size_t offset = 0; - offset += decl->addElement(0, offset, VET_FLOAT3, VES_POSITION).getSize(); - - vbuf = - HardwareBufferManager::getSingleton().createVertexBuffer( - offset, nvertices, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY); - - bind->setBinding(0, vbuf); - - //vbuf->writeData(0, vbuf->getSizeInBytes(), vertices, true); - - HardwareIndexBufferSharedPtr ibuf = HardwareBufferManager::getSingleton(). - createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, - mCount*6, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - idata->indexBuffer = ibuf; - idata->indexCount = mCount*6; - idata->indexStart = 0; - ibuf->writeData(0, ibuf->getSizeInBytes(), faces, true); - - // Delete temporary buffers - delete [] faces; - - // Now make the render operation - mRenderOp.operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST; - mRenderOp.indexData = idata; - mRenderOp.vertexData = vdata; - mRenderOp.useIndexes = true; -} - -void ThingRenderable::fillBuffer() -{ - // Transfer vertices and normals - float *vIdx = static_cast(vbuf->lock(Ogre::HardwareBuffer::HBL_DISCARD)); - size_t elemsize = 1*3; // position only - size_t planesize = 4*elemsize; // four vertices per plane - for(size_t x=0; xunlock(); -} -Ogre::Real ThingRenderable::getBoundingRadius() const -{ - return mRadius; -} -Ogre::Real ThingRenderable::getSquaredViewDepth(const Ogre::Camera* cam) const -{ - return (cam->getDerivedPosition() - mBox.getCenter()).squaredLength(); -} - diff --git a/Samples/VolumeTex/src/VolumeRenderable.cpp b/Samples/VolumeTex/src/VolumeRenderable.cpp deleted file mode 100644 index e7a7f67bd72..00000000000 --- a/Samples/VolumeTex/src/VolumeRenderable.cpp +++ /dev/null @@ -1,221 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ -#include "VolumeRenderable.h" -#include "OgreCamera.h" -#include "OgreSceneNode.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreHardwareIndexBuffer.h" -#include "OgreHardwareBufferManager.h" -#include "OgreMaterial.h" -#include "OgreTechnique.h" -#include "OgrePass.h" -#include "OgreTextureUnitState.h" -#include "OgreTextureManager.h" -#include "OgreMaterialManager.h" -using namespace Ogre; - -VolumeRenderable::VolumeRenderable(size_t nSlices, float size, const String &texture): - mSlices(nSlices), - mSize(size/2), - mTexture(texture) -{ - mBox = Ogre::AxisAlignedBox(-mSize, -mSize, -mSize, mSize, mSize, mSize); - mRadius = mBox.getMaximum().length(); - - // No shadows - setCastShadows(false); - - initialise(); -} -VolumeRenderable::~VolumeRenderable() -{ - // Remove private material - MaterialManager::getSingleton().remove(mTexture, "VolumeRenderable"); - // need to release IndexData and vertexData created for renderable - delete mRenderOp.indexData; - delete mRenderOp.vertexData; - -} - -void VolumeRenderable::_notifyCurrentCamera( Camera* cam ) -{ - MovableObject::_notifyCurrentCamera(cam); - - // Fake orientation toward camera - Vector3 zVec = getParentNode()->_getDerivedPosition() - cam->getDerivedPosition(); - mFakeOrientation = Math::lookRotation(zVec.normalisedCopy(), cam->getDerivedOrientation().yAxis()); - - Matrix3 tempMat; - getParentNode()->_getDerivedOrientation().UnitInverse().ToRotationMatrix(tempMat); - - Matrix4 rotMat = Matrix4::IDENTITY; - rotMat = tempMat * mFakeOrientation; - rotMat.setTrans(Vector3(0.5f, 0.5f, 0.5f)); - - Technique* tech = mMaterial->getBestTechnique(); - - // set the texture transform anyway, so the RTSS picks it up when it runs - if(!tech) - tech = mMaterial->getTechniques().front(); - - tech->getPass(0)->getTextureUnitState(0)->setTextureTransform(rotMat); -} - - - -void VolumeRenderable::getWorldTransforms( Matrix4* xform ) const -{ - Matrix4 destMatrix(Matrix4::IDENTITY); // this initialisation is needed - - const Vector3 &position = getParentNode()->_getDerivedPosition(); - const Vector3 &scale = getParentNode()->_getDerivedScale(); - Matrix3 scale3x3(Matrix3::ZERO); - scale3x3[0][0] = scale.x; - scale3x3[1][1] = scale.y; - scale3x3[2][2] = scale.z; - - destMatrix = mFakeOrientation * scale3x3; - destMatrix.setTrans(position); - - *xform = destMatrix; -} - -void VolumeRenderable::initialise() -{ - // Create geometry - size_t nvertices = mSlices*4; // n+1 planes - size_t elemsize = 3*3; - size_t dsize = elemsize*nvertices; - - Ogre::IndexData *idata = new Ogre::IndexData(); - Ogre::VertexData *vdata = new Ogre::VertexData(); - - // Create structures - float *vertices = new float[dsize]; - - float coords[4][2] = { - {0.0f, 0.0f}, - {0.0f, 1.0f}, - {1.0f, 0.0f}, - {1.0f, 1.0f} - }; - for(size_t x=0; xvertexStart = 0; - vdata->vertexCount = nvertices; - - VertexDeclaration* decl = vdata->vertexDeclaration; - VertexBufferBinding* bind = vdata->vertexBufferBinding; - - size_t offset = 0; - offset += decl->addElement(0, offset, VET_FLOAT3, VES_POSITION).getSize(); - offset += decl->addElement(0, offset, VET_FLOAT3, VES_NORMAL).getSize(); - offset += decl->addElement(0, offset, VET_FLOAT3, VES_TEXTURE_COORDINATES).getSize(); - - HardwareVertexBufferSharedPtr vbuf = - HardwareBufferManager::getSingleton().createVertexBuffer( - offset, nvertices, HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - bind->setBinding(0, vbuf); - - vbuf->writeData(0, vbuf->getSizeInBytes(), vertices, true); - - HardwareIndexBufferSharedPtr ibuf = HardwareBufferManager::getSingleton(). - createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, - mSlices*6, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - idata->indexBuffer = ibuf; - idata->indexCount = mSlices*6; - idata->indexStart = 0; - ibuf->writeData(0, ibuf->getSizeInBytes(), faces, true); - - // Delete temporary buffers - delete [] vertices; - delete [] faces; - - // Now make the render operation - mRenderOp.operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST; - mRenderOp.indexData = idata; - mRenderOp.vertexData = vdata; - mRenderOp.useIndexes = true; - - // Create a brand new private material - MaterialPtr material = - MaterialManager::getSingleton().create(mTexture, "VolumeRenderable", - false, 0); // Manual, loader - - // Remove pre-created technique from defaults - material->removeAllTechniques(); - - // Create a techinique and a pass and a texture unit - Technique * technique = material->createTechnique(); - Pass * pass = technique->createPass(); - TextureUnitState * textureUnit = pass->createTextureUnitState(); - - // Set pass parameters - pass->setSceneBlending(SBT_TRANSPARENT_ALPHA); - pass->setDepthWriteEnabled(false); - pass->setCullingMode(CULL_NONE); - pass->setLightingEnabled(false); - - // Set texture unit parameters - textureUnit->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); - textureUnit->setTextureName(mTexture, TEX_TYPE_3D); - textureUnit->setTextureFiltering(TFO_TRILINEAR); - - mMaterial = material; -} - -Ogre::Real VolumeRenderable::getBoundingRadius() const -{ - return mRadius; -} -Ogre::Real VolumeRenderable::getSquaredViewDepth(const Ogre::Camera* cam) const -{ - return (cam->getDerivedPosition() - mBox.getCenter()).squaredLength(); -} - diff --git a/Samples/VolumeTex/src/VolumeTex.cpp b/Samples/VolumeTex/src/VolumeTex.cpp deleted file mode 100644 index 1f279cd0403..00000000000 --- a/Samples/VolumeTex/src/VolumeTex.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - -#include "VolumeTex.h" - -#include "OgreTexture.h" -#include "OgreHardwarePixelBuffer.h" -#include "OgreTextureManager.h" -#include "OgreLogManager.h" -#include - -#include "VolumeRenderable.h" -#include "ThingRenderable.h" -#include "Julia.h" - -namespace { -SimpleRenderable *vrend; -SimpleRenderable *trend; -SceneNode *snode,*fnode; -} - -void Sample_VolumeTex::setupContent() -{ - if (!ResourceGroupManager::getSingleton().resourceGroupExists("VolumeRenderable")) - { - ResourceGroupManager::getSingleton().createResourceGroup("VolumeRenderable"); - } - // Create dynamic texture - ptex = TextureManager::getSingleton().createManual( - "DynaTex","VolumeRenderable", TEX_TYPE_3D, 64, 64, 64, 0, PF_BYTE_RGBA); - - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.6, 0.6, 0.6)); - mSceneMgr->setSkyBox(true, "Examples/MorningSkyBox", 50 ); - - //mRoot->getRenderSystem()->clearFrameBuffer(FBT_COLOUR, ColourValue(255,255,255,0)); - - // Create a light - Light* l = mSceneMgr->createLight("MainLight"); - l->setDiffuseColour(0.75, 0.75, 0.80); - l->setSpecularColour(0.9, 0.9, 1); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-100,80,50))->attachObject(l); - - // Create volume renderable - snode = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,0,0)); - - vrend = new VolumeRenderable(32, 750.0f, "DynaTex"); - snode->attachObject( vrend ); - - trend = new ThingRenderable(90.0f, 32, 7.5f); - MaterialPtr mat = MaterialManager::getSingleton().getByName("Examples/VTDarkStuff", "General"); - trend->setMaterial(mat); - snode->attachObject(trend); - - // Ogre head node - fnode = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,0,0)); - // Load ogre head - Entity* head = mSceneMgr->createEntity("head", "ogrehead.mesh"); - fnode->attachObject(head); - - // Animation for ogre head - // Create a track for the light - Animation* anim = mSceneMgr->createAnimation("OgreTrack", 10); - // Spline it for nice curves - anim->setInterpolationMode(Animation::IM_SPLINE); - // Create a track to animate the camera's node - NodeAnimationTrack* track = anim->createNodeTrack(0, fnode); - // Setup keyframes - TransformKeyFrame* key = track->createNodeKeyFrame(0); // A startposition - key->setTranslate(Vector3(0.0f, -15.0f, 0.0f)); - key = track->createNodeKeyFrame(5);//B - key->setTranslate(Vector3(0.0f, 15.0f, 0.0f)); - key = track->createNodeKeyFrame(10);//C - key->setTranslate(Vector3(0.0f, -15.0f, 0.0f)); - // Create a new animation state to track this - auto animState = mSceneMgr->createAnimationState("OgreTrack"); - animState->setEnabled(true); - auto& controllerMgr = ControllerManager::getSingleton(); - controllerMgr.createFrameTimePassthroughController(AnimationStateControllerValue::create(animState, true)); - - //mFountainNode->attachObject(pSys2); - - //Setup defaults - global_real = 0.4f; - global_imag = 0.6f; - global_theta = 0.0f; - - // show GUI - createControls(); - - mCameraMan->setStyle(CS_ORBIT); - - generate(); -} - -bool Sample_VolumeTex::frameRenderingQueued(const FrameEvent &evt) -{ - //snode->roll(Degree(evt.timeSinceLastFrame * 20.0f)); - //fnode->roll(Degree(evt.timeSinceLastFrame * 20.0f)); - static_cast(trend)->addTime(evt.timeSinceLastFrame * 0.05f); - return SdkSample::frameRenderingQueued(evt); -} - -void Sample_VolumeTex::cleanupContent() -{ - TextureManager::getSingleton().remove("DynaTex", "VolumeRenderable"); - delete vrend; - delete trend; -} - -void Sample_VolumeTex::generate() -{ - /* Evaluate julia fractal for each point */ - Julia julia(global_real, global_imag, global_theta); - const float scale = 2.5; - const float vcut = 29.0f; - const float vscale = 1.0f/vcut; - - HardwarePixelBufferSharedPtr buffer = ptex->getBuffer(0, 0); - Ogre::StringStream d; - d << "HardwarePixelBuffer " << buffer->getWidth() << " " << buffer->getHeight() << " " << buffer->getDepth(); - LogManager::getSingleton().logMessage(d.str()); - - buffer->lock(HardwareBuffer::HBL_NORMAL); - const PixelBox &pb = buffer->getCurrentLock(); - d.str(""); - d << "PixelBox " << pb.getWidth() << " " << pb.getHeight() << " " << pb.getDepth() << " " << pb.rowPitch << " " << pb.slicePitch << " " << pb.data << " " << PixelUtil::getFormatName(pb.format); - LogManager::getSingleton().logMessage(d.str()); - - Ogre::uint32 *pbptr = reinterpret_cast(pb.data); - for(size_t z=pb.front; z vcut) - val = vcut; - - PixelUtil::packColour((float)x/pb.getWidth(), (float)y/pb.getHeight(), (float)z/pb.getDepth(), (1.0f-(val*vscale))*0.7f, PF_BYTE_RGBA, &pbptr[x]); - - } - } - pbptr += pb.rowPitch; - } - pbptr += pb.getSliceSkip(); - } - buffer->unlock(); -} diff --git a/Samples/Water/include/Water.h b/Samples/Water/include/Water.h deleted file mode 100644 index e8dad1e65d6..00000000000 --- a/Samples/Water/include/Water.h +++ /dev/null @@ -1,381 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - - -#ifndef _WATER_H_ -#define _WATER_H_ - -#include "SdkSample.h" -#include "OgreBillboardParticleRenderer.h" -#include "WaterMesh.h" -#include "OgreParticleSystem.h" - -#include - -using namespace Ogre; -using namespace OgreBites; - -// Mesh stuff -#define MESH_NAME "WaterMesh" -#define ENTITY_NAME "WaterEntity" -#define MATERIAL_PREFIX "Examples/Water" -#define MATERIAL_NAME "Examples/Water0" -#define COMPLEXITY 64 // watch out - number of polys is 2*ACCURACY*ACCURACY ! -#define PLANE_SIZE 3000.0f -#define CIRCLES_MATERIAL "Examples/Water/Circles" -#define CIRCLE_SIZE 500.0 -#define CIRCLE_TIME 0.5f - -static void prepareCircleMaterial() -{ - Image bmap(PF_L8, 256, 256); - bmap.setTo(ColourValue(0.5)); - for(int b=0;b<16;b++) { - int x0 = b % 4 ; - int y0 = b / 4 ; - float radius = 4.0f + 1.4 * (float) b ; - for(int x=0;x<64;x++) { - for(int y=0;y<64;y++) { - Real dist = Math::Sqrt((x-32)*(x-32)+(y-32)*(y-32)); // 0..ca.45 - dist = fabs(dist -radius -2) / 2.0f ; - dist = dist * 255.0f; - if (dist>255) - dist=255 ; - uchar colour = 255 - (uchar)dist; - colour = (uchar)((15 - b) / 15.0f * colour); - - *bmap.getData(x+64*x0, y+64*y0) = colour; - } - } - } - - auto tex = TextureManager::getSingleton().loadImage(CIRCLES_MATERIAL, RGN_DEFAULT, bmap); - MaterialPtr material = MaterialManager::getSingleton().create(CIRCLES_MATERIAL, RGN_DEFAULT); - auto texLayer = material->getTechnique(0)->getPass(0)->createTextureUnitState(); - texLayer->setTexture(tex); - texLayer->setTextureAddressingMode( TextureUnitState::TAM_CLAMP ); - material->setSceneBlending( SBT_ADD ); - material->setLightingEnabled(false); - material->setDepthWriteEnabled( false ) ; -} - -class _OgreSampleClassExport Sample_Water : public SdkSample -{ -public: - Sample_Water(): waterMesh(0) - { - mInfo["Title"] = "Water"; - mInfo["Description"] = "A demo of a simple water effect."; - mInfo["Thumbnail"] = "thumb_water.png"; - mInfo["Category"] = "Environment"; - } - -protected: - WaterMesh *waterMesh ; - Entity *waterEntity ; - AnimationState* mAnimState; - SceneNode *headNode ; - Overlay* waterOverlay ; - ParticleSystem *particleSystem ; - ParticleEmitter *particleEmitter ; - SceneManager *sceneMgr ; - - // Just override the mandatory create scene method - void setupContent(void) override - { - sceneMgr = mSceneMgr ; - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.75, 0.75, 0.75)); - - // Create a light - // Accept default settings: point light, white diffuse, just set position - Light* l = mSceneMgr->createLight("MainLight"); - - // Create water mesh and entity - waterMesh = new WaterMesh(MESH_NAME, PLANE_SIZE, COMPLEXITY); - waterEntity = mSceneMgr->createEntity(ENTITY_NAME, - MESH_NAME); - //~ waterEntity->setMaterialName(MATERIAL_NAME); - SceneNode *waterNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - waterNode->attachObject(waterEntity); - - // Add a head, give it it's own node - headNode = waterNode->createChildSceneNode(); - Entity *ent = mSceneMgr->createEntity("head", "ogrehead.mesh"); - headNode->attachObject(ent); - - // Make sure the camera track this node - //~ mCamera->setAutoTracking(true, headNode); - - // Create the camera node, set its position & attach camera - mCameraNode->translate(0, 500, PLANE_SIZE); - mCameraNode->yaw(Degree(-45)); - - // Create light node - SceneNode* lightNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - lightNode->setPosition(200,300,100); - lightNode->attachObject(l); - - // set up spline animation of light node - Animation* anim = mSceneMgr->createAnimation("WaterLight", 20); - NodeAnimationTrack *track ; - TransformKeyFrame *key ; - // create a random spline for light - track = anim->createNodeTrack(0, lightNode); - track->createNodeKeyFrame(0); - for(int ff=1;ff<=19;ff++) { - key = track->createNodeKeyFrame(ff); - Vector3 lpos ( - rand()%(int)PLANE_SIZE , //- PLANE_SIZE/2, - rand()%300+100, - rand()%(int)PLANE_SIZE //- PLANE_SIZE/2 - ); - key->setTranslate(lpos); - } - track->createNodeKeyFrame(20); - - // Create a new animation state to track this - mAnimState = mSceneMgr->createAnimationState("WaterLight"); - mAnimState->setEnabled(true); - - // Put in a bit of fog for the hell of it - //mSceneMgr->setFog(FOG_EXP, ColourValue::White, 0.0002); - - // Let there be rain - particleSystem = mSceneMgr->createParticleSystem("rain", - "Examples/Water/Rain"); - particleEmitter = particleSystem->getEmitter(0); - particleEmitter->setEmissionRate(0); - SceneNode* rNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - rNode->translate(PLANE_SIZE/2.0f, 3000, PLANE_SIZE/2.0f); - rNode->attachObject(particleSystem); - // Fast-forward the rain so it looks more natural - particleSystem->fastForward(20); - - prepareCircleMaterial(); - - billboardSet = mSceneMgr->createBillboardSet("circles", 100); - billboardSet->setMaterialName(CIRCLES_MATERIAL); - billboardSet->setDefaultDimensions(CIRCLE_SIZE, CIRCLE_SIZE); - billboardSet->setBillboardType(BBT_PERPENDICULAR_COMMON); - billboardSet->setCommonDirection(Vector3::UNIT_Y); - billboardSet->setCommonUpVector(Vector3::UNIT_Z); - - billboardSet->setTextureStacksAndSlices(4, 4); - - waterNode->attachObject(billboardSet); - - setupControls(); - setDragLook(true); - - timeoutDelay = 0.0f; - } - -#define PANEL_WIDTH 200 - void setupControls() - { - mTrayMgr->createLabel(TL_TOPLEFT, "GeneralLabel", "General", PANEL_WIDTH); - mTrayMgr->createCheckBox(TL_TOPLEFT, "FakeNormalsCB", "Fake normals", PANEL_WIDTH); - mTrayMgr->createCheckBox(TL_TOPLEFT, "SkyboxCB", "Skybox", PANEL_WIDTH); - mTrayMgr->createThickSlider(TL_TOPLEFT, "HeadDepthSlider", "Head Depth", PANEL_WIDTH, 80, 1, 3, 50)->setValue(2.0f); - SelectMenu* waterMaterial = mTrayMgr->createThickSelectMenu(TL_TOPLEFT, "WaterMaterialMenu", "Water material", PANEL_WIDTH, 9); - for (size_t i = 0; i < 9; i++) - { - waterMaterial->addItem(MATERIAL_PREFIX + StringConverter::toString(i)); - } - waterMaterial->selectItem(8); - mTrayMgr->createLabel(TL_TOPLEFT, "RainLabel", "Rain : [Space]", PANEL_WIDTH); - - mTrayMgr->createLabel(TL_TOPRIGHT, "AdvancedLabel", "Advanced", PANEL_WIDTH); - mTrayMgr->createThickSlider(TL_TOPRIGHT, "RippleSpeedSlider", "Ripple Speed", PANEL_WIDTH, 80, 0, 2, 50)->setValue(0.3, false); - mTrayMgr->createThickSlider(TL_TOPRIGHT, "DistanceSlider", "Distance", PANEL_WIDTH, 80, 0.1, 5.0, 50)->setValue(0.4, false); - mTrayMgr->createThickSlider(TL_TOPRIGHT, "ViscositySlider", "Viscosity", PANEL_WIDTH, 80, 0, 1, 50)->setValue(0.05, false); - mTrayMgr->createThickSlider(TL_TOPRIGHT, "FrameTimeSlider", "FrameTime", PANEL_WIDTH, 80, 0, 1, 61)->setValue(0.13, false); - - mTrayMgr->showCursor(); - } - - void cleanupContent() override - { - delete waterMesh; - waterMesh = 0; - } - -protected: - Real timeoutDelay ; - -#define RAIN_HEIGHT_RANDOM 5 -#define RAIN_HEIGHT_CONSTANT 5 - - struct WaterCircle - { - Billboard* bb; - float time; - }; - std::list circles; - BillboardSet* billboardSet; - - void processCircles(Real timeSinceLastFrame) - { - for (auto it = circles.begin(); it != circles.end(); ) - { - it->time += timeSinceLastFrame; - if(it->time >= CIRCLE_TIME) - { - billboardSet->removeBillboard(it->bb); - it = circles.erase(it); - continue; - } - - it->bb->setTexcoordIndex(it->time / CIRCLE_TIME * 16); - it++; - } - } - - void processParticles() - { - for (auto particle : particleSystem->_getActiveParticles()) - { - Vector3 ppos = particle->mPosition; - if (ppos.y<=0 && particle->mTimeToLive>0) { // hits the water! - // delete particle - particle->mTimeToLive = 0.0f; - // push the water - float x = ppos.x / PLANE_SIZE * COMPLEXITY ; - float y = ppos.z / PLANE_SIZE * COMPLEXITY ; - float h = rand() % RAIN_HEIGHT_RANDOM + RAIN_HEIGHT_CONSTANT ; - if (x<1) x=1 ; - if (x>COMPLEXITY-1) x=COMPLEXITY-1; - if (y<1) y=1 ; - if (y>COMPLEXITY-1) y=COMPLEXITY-1; - waterMesh->push(x,y,-h) ; - auto bb = billboardSet->createBillboard(x*(PLANE_SIZE/COMPLEXITY), 10, y*(PLANE_SIZE/COMPLEXITY)); - circles.push_back({bb, 0}); - } - } - } - - void sliderMoved(Slider* slider) override - { - if (slider->getName() == "HeadDepthSlider") - { - headDepth = slider->getValue(); - } - else if (slider->getName() == "RippleSpeedSlider") - { - waterMesh->PARAM_C = slider->getValue(); - } - else if (slider->getName() == "DistanceSlider") - { - waterMesh->PARAM_D = slider->getValue(); - } - else if (slider->getName() == "ViscositySlider") - { - waterMesh->PARAM_U = slider->getValue(); - } - else if (slider->getName() == "FrameTimeSlider") - { - waterMesh->PARAM_T = slider->getValue(); - } - } - - void checkBoxToggled(CheckBox* checkBox) override - { - if (checkBox->getName() == "FakeNormalsCB") - { - waterMesh->useFakeNormals = checkBox->isChecked(); - } - else if (checkBox->getName() == "SkyboxCB") - { - sceneMgr->setSkyBox(checkBox->isChecked(), "Examples/SceneSkyBox2"); - } - } - - void itemSelected(SelectMenu* menu) override - { - //Only one menu in this demo - const String& materialName = menu->getSelectedItem(); - MaterialPtr material = MaterialManager::getSingleton().getByName(materialName); - if (!material) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Material "+materialName+"doesn't exist!", - "WaterListener::updateMaterial"); - } - waterEntity->setMaterialName(materialName); - } - - /** Head animation */ - Real headDepth ; - void animateHead(Real timeSinceLastFrame) - { - // sine track? :) - static double sines[4] = {0,100,200,300}; - static const double adds[4] = {0.3,-1.6,1.1,0.5}; - static Vector3 oldPos = Vector3::UNIT_Z; - for(int i=0;i<4;i++) { - sines[i]+=adds[i]*timeSinceLastFrame; - } - Real tx = ((sin(sines[0]) + sin(sines[1])) / 4 + 0.5 ) * (float)(COMPLEXITY-2) + 1 ; - Real ty = ((sin(sines[2]) + sin(sines[3])) / 4 + 0.5 ) * (float)(COMPLEXITY-2) + 1 ; - waterMesh->push(tx,ty, -headDepth); - Real step = PLANE_SIZE / COMPLEXITY ; - headNode->resetToInitialState(); - headNode->scale(3,3,3); - Vector3 newPos = Vector3(step*tx, headDepth, step*ty); - Vector3 diffPos = newPos - oldPos ; - Quaternion headRotation = Vector3::UNIT_Z.getRotationTo(diffPos); - oldPos = newPos ; - headNode->translate(newPos); - headNode->rotate(headRotation); - } - -public: - - bool keyPressed(const KeyboardEvent& evt) override - { - static bool rain = false; - - if(evt.keysym.sym == SDLK_SPACE) { - rain = !rain; - particleEmitter->setEmissionRate(rain ? 20.0f : 0.0f); - } - - return SdkSample::keyPressed(evt); - } - - bool frameRenderingQueued(const FrameEvent& evt) override - { - if( SdkSample::frameRenderingQueued(evt) == false ) - return false; - - mAnimState->addTime(evt.timeSinceLastFrame); - - // rain - processCircles(evt.timeSinceLastFrame); - processParticles(); - - timeoutDelay-=evt.timeSinceLastFrame ; - if (timeoutDelay<=0) - timeoutDelay = 0; - - animateHead(evt.timeSinceLastFrame); - - waterMesh->updateMesh(evt.timeSinceLastFrame); - - return true; - } -}; - -#endif diff --git a/Samples/Water/include/WaterMesh.h b/Samples/Water/include/WaterMesh.h deleted file mode 100644 index c288272bbf1..00000000000 --- a/Samples/Water/include/WaterMesh.h +++ /dev/null @@ -1,75 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - - -#ifndef _WATER_MESH_H_ -#define _WATER_MESH_H_ - -#include "OgrePlatform.h" -#include "Ogre.h" - -using namespace Ogre ; - -class WaterMesh -{ -private: - MeshPtr mesh ; - SubMesh *subMesh ; - float *vertexBuffers[3] ; // we need 3 vertex buffers - int currentBuffNumber ; - int complexity ; - String meshName ; - int numFaces ; - int numVertices ; - Vector3* vNormals ; - - HardwareVertexBufferSharedPtr posVertexBuffer ; - HardwareVertexBufferSharedPtr normVertexBuffer ; - HardwareVertexBufferSharedPtr texcoordsVertexBuffer ; - HardwareIndexBufferSharedPtr indexBuffer ; - - Real lastTimeStamp ; - Real lastAnimationTimeStamp; - Real lastFrameTime ; - - void calculateFakeNormals(); - void calculateNormals(); -public: - WaterMesh(const String& meshName, Real planeSize, int complexity) ; - - virtual ~WaterMesh (); - - - /** "pushes" a mesh at position [x,y]. Note, that x,y are float, hence - * 4 vertices are actually pushed - * @note - * This should be replaced by push with 'radius' parameter to simulate - * big objects falling into water - */ - void push(Real x, Real y, Real depth, bool absolute=false) ; - - /** gets height at given x and y, takes average value of the closes nodes */ - Real getHeight(Real x, Real y); - - /** updates mesh */ - void updateMesh(Real timeSinceLastFrame) ; - - Real PARAM_C ; // ripple speed - Real PARAM_D ; // distance - Real PARAM_U ; // viscosity - Real PARAM_T ; // time - bool useFakeNormals ; -} ; - -#endif diff --git a/Samples/Water/src/WaterMesh.cpp b/Samples/Water/src/WaterMesh.cpp deleted file mode 100644 index 5c36d54f9a7..00000000000 --- a/Samples/Water/src/WaterMesh.cpp +++ /dev/null @@ -1,329 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd -Also see acknowledgements in Readme.html - -You may use this sample code for anything you like, it is not covered by the -same license as the rest of the engine. ------------------------------------------------------------------------------ -*/ - - -#include "WaterMesh.h" - -#include - -#define ANIMATIONS_PER_SECOND 100.0f - -WaterMesh::WaterMesh(const String& inMeshName, Real planeSize, int inComplexity) -{ - int x,y,b; // I prefer to initialize for() variables inside it, but VC doesn't like it ;( - - this->meshName = inMeshName ; - this->complexity = inComplexity ; - numFaces = 2 * complexity * complexity; - numVertices = (complexity + 1) * (complexity + 1) ; - lastTimeStamp = 0 ; - lastAnimationTimeStamp = 0; - lastFrameTime = 0 ; - - // initialize algorithm parameters - PARAM_C = 0.3f ; // ripple speed - PARAM_D = 0.4f ; // distance - PARAM_U = 0.05f ; // viscosity - PARAM_T = 0.13f ; // time - useFakeNormals = false ; - - // allocate space for normal calculation - vNormals = new Vector3[numVertices]; - - // create mesh and submesh - mesh = MeshManager::getSingleton().createManual(meshName, - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - subMesh = mesh->createSubMesh(); - - // Vertex buffers - subMesh->createVertexData(); - subMesh->vertexData->vertexStart = 0; - subMesh->vertexData->vertexCount = numVertices; - - VertexDeclaration* vdecl = subMesh->vertexData->vertexDeclaration; - VertexBufferBinding* vbind = subMesh->vertexData->vertexBufferBinding; - - - vdecl->addElement(0, 0, VET_FLOAT3, VES_POSITION); - vdecl->addElement(1, 0, VET_FLOAT3, VES_NORMAL); - vdecl->addElement(2, 0, VET_FLOAT2, VES_TEXTURE_COORDINATES); - - // Prepare buffer for positions - todo: first attempt, slow - posVertexBuffer = - HardwareBufferManager::getSingleton().createVertexBuffer( - 3*sizeof(float), - numVertices, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE); - vbind->setBinding(0, posVertexBuffer); - - // Prepare buffer for normals - write only - normVertexBuffer = - HardwareBufferManager::getSingleton().createVertexBuffer( - 3*sizeof(float), - numVertices, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE); - vbind->setBinding(1, normVertexBuffer); - - // Prepare texture coords buffer - static one - // todo: optimize to write directly into buffer - float *texcoordsBufData = new float[numVertices*2]; - for(y=0;y<=complexity;y++) { - for(x=0;x<=complexity;x++) { - texcoordsBufData[2*(y*(complexity+1)+x)+0] = (float)x / complexity ; - texcoordsBufData[2*(y*(complexity+1)+x)+1] = 1.0f - ((float)y / (complexity)) ; - } - } - texcoordsVertexBuffer = - HardwareBufferManager::getSingleton().createVertexBuffer( - 2*sizeof(float), - numVertices, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - texcoordsVertexBuffer->writeData(0, - texcoordsVertexBuffer->getSizeInBytes(), - texcoordsBufData, - true); // true? - delete [] texcoordsBufData; - vbind->setBinding(2, texcoordsVertexBuffer); - - // Prepare buffer for indices - indexBuffer = - HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, - 3*numFaces, - HardwareBuffer::HBU_STATIC, true); - unsigned short *faceVertexIndices = (unsigned short*) - indexBuffer->lock(0, numFaces*3*2, HardwareBuffer::HBL_DISCARD); - for(y=0 ; yunlock(); - // Set index buffer for this submesh - subMesh->indexData->indexBuffer = indexBuffer; - subMesh->indexData->indexStart = 0; - subMesh->indexData->indexCount = 3*numFaces; - - /* prepare vertex positions - * note - we use 3 vertex buffers, since algorighm uses two last phases - * to calculate the next one - */ - for(b=0;b<3;b++) { - vertexBuffers[b] = new float[numVertices * 3] ; - for(y=0;y<=complexity;y++) { - for(x=0;x<=complexity;x++) { - int numPoint = y*(complexity+1) + x ; - float* vertex = vertexBuffers[b] + 3*numPoint ; - vertex[0]=(float)(x) / (float)(complexity) * (float) planeSize ; - vertex[1]= 0 ; // rand() % 30 ; - vertex[2]=(float)(y) / (float)(complexity) * (float) planeSize ; - } - } - } - - AxisAlignedBox meshBounds(0,0,0, - planeSize,0, planeSize); - mesh->_setBounds(meshBounds); - - currentBuffNumber = 0 ; - posVertexBuffer->writeData(0, - posVertexBuffer->getSizeInBytes(), // size - vertexBuffers[currentBuffNumber], // source - true); // discard? - - mesh->load(); - mesh->touch(); -} -/* ========================================================================= */ -WaterMesh::~WaterMesh () -{ - delete[] vertexBuffers[0]; - delete[] vertexBuffers[1]; - delete[] vertexBuffers[2]; - - delete[] vNormals; - - MeshManager::getSingleton().remove(meshName, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); -} -/* ========================================================================= */ -void WaterMesh::push(Real x, Real y, Real depth, bool absolute) -{ - float *buf = vertexBuffers[currentBuffNumber]+1 ; - // scale pressure according to time passed - depth = depth * lastFrameTime * ANIMATIONS_PER_SECOND ; -#define _PREP(addx,addy) { \ - float *vertex=buf+3*((int)(y+addy)*(complexity+1)+(int)(x+addx)) ; \ - float diffy = y - floor(y+addy); \ - float diffx = x - floor(x+addx); \ - float dist=sqrt(diffy*diffy + diffx*diffx) ; \ - float power = 1 - dist ; \ - if (power<0) \ - power = 0; \ - if (absolute) \ - *vertex = depth*power ; \ - else \ - *vertex += depth*power ; \ -} /* #define */ - _PREP(0,0); - _PREP(0,1); - _PREP(1,0); - _PREP(1,1); -#undef _PREP -} -/* ========================================================================= */ -Real WaterMesh::getHeight(Real x, Real y) -{ -#define hat(_x,_y) buf[3*((int)_y*(complexity+1)+(int)(_x))] - float *buf = vertexBuffers[currentBuffNumber] ; - Real xa = floor(x); - Real xb = xa + 1 ; - Real ya = floor(y); - Real yb = ya + 1 ; - Real yaxavg = hat(xa,ya) * (1.0f-std::fabs(xa-x)) + hat(xb,ya) * (1.0f-std::fabs(xb-x)); - Real ybxavg = hat(xa,yb) * (1.0f-std::fabs(xa-x)) + hat(xb,yb) * (1.0f-std::fabs(xb-x)); - Real yavg = yaxavg * (1.0f-std::fabs(ya-y)) + ybxavg * (1.0f-std::fabs(yb-y)) ; - return yavg ; -} -/* ========================================================================= */ -void WaterMesh::calculateFakeNormals() -{ - int x,y; - float *buf = vertexBuffers[currentBuffNumber] + 1; - float *pNormals = (float*) normVertexBuffer->lock( - 0,normVertexBuffer->getSizeInBytes(), HardwareBuffer::HBL_DISCARD); - for(y=1;yunlock(); -} -/* ========================================================================= */ -void WaterMesh::calculateNormals() -{ - int i,x,y; - float *buf = NULL; - // zero normals - for(i=0;ilock( - 0, indexBuffer->getSizeInBytes(), HardwareBuffer::HBL_READ_ONLY); - float *pNormals = (float*) normVertexBuffer->lock( - 0, normVertexBuffer->getSizeInBytes(), HardwareBuffer::HBL_DISCARD); - for(i=0;iunlock(); - normVertexBuffer->unlock(); -} -/* ========================================================================= */ -void WaterMesh::updateMesh(Real timeSinceLastFrame) -{ - int x, y ; - - lastFrameTime = timeSinceLastFrame ; - lastTimeStamp += timeSinceLastFrame ; - - // do rendering to get ANIMATIONS_PER_SECOND - while(lastAnimationTimeStamp <= lastTimeStamp) { - - // switch buffer numbers - currentBuffNumber = (currentBuffNumber + 1) % 3 ; - float *buf = vertexBuffers[currentBuffNumber] + 1 ; // +1 for Y coordinate - float *buf1 = vertexBuffers[(currentBuffNumber+2)%3] + 1 ; - float *buf2 = vertexBuffers[(currentBuffNumber+1)%3] + 1; - - /* we use an algorithm from - * http://collective.valve-erc.com/index.php?go=water_simulation - * The params could be dynamically changed every frame of course - */ - Real C = PARAM_C; // ripple speed - Real D = PARAM_D; // distance - Real U = PARAM_U; // viscosity - Real T = PARAM_T; // time - Real TERM1 = ( 4.0f - 8.0f*C*C*T*T/(D*D) ) / (U*T+2) ; - Real TERM2 = ( U*T-2.0f ) / (U*T+2.0f) ; - Real TERM3 = ( 2.0f * C*C*T*T/(D*D) ) / (U*T+2) ; - for(y=1;ywriteData(0, - posVertexBuffer->getSizeInBytes(), // size - vertexBuffers[currentBuffNumber], // source - true); // discard? -} diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt deleted file mode 100644 index 9b72bd8b9a0..00000000000 --- a/Tests/CMakeLists.txt +++ /dev/null @@ -1,159 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure Tests build -if (OGRE_BUILD_TESTS) - - if(NOT EXISTS ${PROJECT_BINARY_DIR}/googletest-1.11.0) - message(STATUS "Building gtest") - file(DOWNLOAD - https://github.com/google/googletest/archive/refs/tags/release-1.11.0.tar.gz - ${PROJECT_BINARY_DIR}/release-1.11.0.tar.gz) - execute_process(COMMAND ${CMAKE_COMMAND} - -E tar xf release-1.11.0.tar.gz WORKING_DIRECTORY ${PROJECT_BINARY_DIR}) - execute_process(COMMAND ${BUILD_COMMAND_COMMON} - ${PROJECT_BINARY_DIR}/googletest-release-1.11.0 - -Dgtest_force_shared_crt=TRUE - -DBUILD_GMOCK=FALSE - WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/googletest-release-1.11.0) - execute_process(COMMAND ${CMAKE_COMMAND} - --build ${PROJECT_BINARY_DIR}/googletest-release-1.11.0 ${BUILD_COMMAND_OPTS}) - endif() - find_package(GTest REQUIRED CONFIG) - include_directories(${CMAKE_CURRENT_SOURCE_DIR}/Common/include) - - # unit tests are go! - include_directories(${CMAKE_CURRENT_SOURCE_DIR}/OgreMain/include) - - file(GLOB HEADER_FILES "${CMAKE_CURRENT_SOURCE_DIR}/OgreMain/include/*.h") - file(GLOB SOURCE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/OgreMain/src/*.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/main.cpp") - - if (OGRE_CONFIG_ENABLE_ZIP) - list(APPEND HEADER_FILES OgreMain/include/ZipArchiveTests.h) - list(APPEND SOURCE_FILES OgreMain/src/ZipArchiveTests.cpp) - endif () - - if (OGRE_BUILD_COMPONENT_PAGING) - set(OGRE_LIBRARIES ${OGRE_LIBRARIES} OgrePaging) - list(APPEND SOURCE_FILES Components/PageCoreTests.cpp) - endif () - if (OGRE_BUILD_COMPONENT_MESHLODGENERATOR) - set(OGRE_LIBRARIES ${OGRE_LIBRARIES} OgreMeshLodGenerator) - list(APPEND SOURCE_FILES Components/MeshLodTests.cpp) - endif () - if (OGRE_BUILD_COMPONENT_TERRAIN) - set(OGRE_LIBRARIES ${OGRE_LIBRARIES} OgreTerrain) - list(APPEND SOURCE_FILES Components/TerrainTests.cpp) - endif () - if (OGRE_BUILD_COMPONENT_PROPERTY) - set(OGRE_LIBRARIES ${OGRE_LIBRARIES} OgreProperty) - list(APPEND SOURCE_FILES Components/PropertyTests.cpp) - endif () - if (OGRE_BUILD_COMPONENT_OVERLAY) - set(OGRE_LIBRARIES ${OGRE_LIBRARIES} OgreOverlay) - endif () - - if (OGRE_BUILD_COMPONENT_RTSHADERSYSTEM) - set(OGRE_LIBRARIES ${OGRE_LIBRARIES} OgreRTShaderSystem) - list(APPEND SOURCE_FILES Components/RTShaderSystemTests.cpp) - endif () - - if(TARGET OgreGLSupport) - set(OGRE_LIBRARIES ${OGRE_LIBRARIES} OgreGLSupport) - list(APPEND SOURCE_FILES RenderSystems/GLSupport/GLSLTests.cpp) - endif() - - if(ANDROID) - list(APPEND SOURCE_FILES ${ANDROID_NDK}/sources/android/cpufeatures/cpu-features.c) - list(APPEND OGRE_LIBRARIES EGL log android) - endif() - - if(UNIX) - add_definitions(-Wno-undef) - endif() - add_executable(Test_Ogre ${HEADER_FILES} ${SOURCE_FILES} ${RESOURCE_FILES} ) - ogre_install_target(Test_Ogre "" FALSE) - target_link_libraries(Test_Ogre OgreBites Codec_STBI ${OGRE_LIBRARIES} GTest::gtest) - - add_test(NAME Test_Ogre - COMMAND $ - WORKING_DIRECTORY $) - - if(ANDROID) - set_target_properties(Test_Ogre PROPERTIES LINK_FLAGS -pie) - endif() - - if(APPLE AND NOT APPLE_IOS) - set_property(TARGET Test_Ogre PROPERTY MACOSX_BUNDLE TRUE) - set(OGRE_BUILT_FRAMEWORK "$(PLATFORM_NAME)/$(CONFIGURATION)") - set(OGRE_TEST_CONTENTS_PATH ${PROJECT_BINARY_DIR}/bin/$(CONFIGURATION)/Test_Ogre.app/Contents) - add_custom_command(TARGET Test_Ogre POST_BUILD - COMMAND mkdir ARGS -p ${OGRE_TEST_CONTENTS_PATH}/Resources/Media/CustomCapabilities - COMMAND ditto - ${PROJECT_SOURCE_DIR}/Tests/Media/CustomCapabilities/* ${OGRE_TEST_CONTENTS_PATH}/Resources/Media/CustomCapabilities - ) - - add_custom_command(TARGET Test_Ogre POST_BUILD - COMMAND mkdir ARGS -p ${OGRE_TEST_CONTENTS_PATH}/Resources - COMMAND ln ARGS -s -f ${PROJECT_BINARY_DIR}/bin/plugins.cfg - ${OGRE_TEST_CONTENTS_PATH}/Resources/ - COMMAND ln ARGS -s -f ${PROJECT_BINARY_DIR}/bin/resources.cfg - ${OGRE_TEST_CONTENTS_PATH}/Resources/ - COMMAND ln ARGS -s -f ${PROJECT_BINARY_DIR}/bin/samples.cfg - ${OGRE_TEST_CONTENTS_PATH}/Resources/ - COMMAND ditto - ${PROJECT_SOURCE_DIR}/Samples/Media/ ${OGRE_TEST_CONTENTS_PATH}/Resources/Media/ - COMMAND ditto - ${PROJECT_SOURCE_DIR}/Tests/Media/ ${OGRE_TEST_CONTENTS_PATH}/Resources/Media/ - COMMAND ditto - ${PROJECT_SOURCE_DIR}/Samples/Common/misc/SampleBrowser_OSX.icns ${OGRE_TEST_CONTENTS_PATH}/Resources - ) - - add_custom_command(TARGET Test_Ogre POST_BUILD - COMMAND mkdir ARGS -p ${OGRE_TEST_CONTENTS_PATH}/Frameworks - COMMAND ln ARGS -s -f ${PROJECT_BINARY_DIR}/lib/${OGRE_BUILT_FRAMEWORK}/Ogre.framework - ${OGRE_TEST_CONTENTS_PATH}/Frameworks/ - COMMAND ln ARGS -s -f ${Cg_LIBRARY_REL} - ${OGRE_TEST_CONTENTS_PATH}/Frameworks/ - ) - add_custom_command(TARGET Test_Ogre POST_BUILD - COMMAND mkdir ARGS -p ${OGRE_TEST_CONTENTS_PATH}/Plugins) - - set(FRAMEWORKS OgreOverlay - OgreBites - OgrePaging - OgreProperty - OgreRTShaderSystem - OgreTerrain - OgreVolume - OgreMeshLodGenerator - Plugin_BSPSceneManager - Plugin_CgProgramManager - Plugin_OctreeSceneManager - Plugin_OctreeZone - Plugin_ParticleFX - Plugin_PCZSceneManager - Plugin_DotScene - Codec_STBI - Codec_FreeImage - RenderSystem_GL - RenderSystem_GL3Plus - RenderSystem_Metal - ) - - foreach(FWK ${FRAMEWORKS}) - add_custom_command(TARGET Test_Ogre POST_BUILD - COMMAND ARGS if [ -d ${PROJECT_BINARY_DIR}/lib/${OGRE_BUILT_FRAMEWORK}/${FWK}.framework ]\; then ln -s -f ${PROJECT_BINARY_DIR}/lib/${OGRE_BUILT_FRAMEWORK}/${FWK}.framework ${OGRE_TEST_CONTENTS_PATH}/Frameworks/${FWK}.framework\; fi - ) - endforeach() - endif() - - add_subdirectory(VisualTests) -endif (OGRE_BUILD_TESTS) diff --git a/Tests/Components/MeshLodTests.cpp b/Tests/Components/MeshLodTests.cpp deleted file mode 100644 index a5ea865c89e..00000000000 --- a/Tests/Components/MeshLodTests.cpp +++ /dev/null @@ -1,204 +0,0 @@ -#include "RootWithoutRenderSystemFixture.h" - -#include "OgreLodConfig.h" -#include "OgreDefaultHardwareBufferManager.h" -#include "OgreVertexIndexData.h" -#include "OgreEdgeListBuilder.h" -#include "OgreMesh.h" -#include "OgreMeshManager.h" -#include "OgreSubMesh.h" -#include "OgreMeshSerializer.h" -#include "OgreRoot.h" -#include "OgreException.h" -#include "OgreArchive.h" -#include "OgreArchiveManager.h" -#include "OgreFileSystem.h" -#include "OgreConfigFile.h" -#include "OgreMeshLodGenerator.h" -#include "OgrePixelCountLodStrategy.h" -#include "OgreLodCollapseCostQuadric.h" -#include "OgreRenderWindow.h" -#include "OgreLodConfigSerializer.h" -#include "OgreWorkQueue.h" - -using namespace Ogre; - -class MeshLodTests : public RootWithoutRenderSystemFixture -{ -public: - MeshPtr mMesh; - - void SetUp() override; - void TearDown() override; - void runMeshLodConfigTests(LodConfig::Advanced& advanced); - void blockedWaitForLodGeneration(const MeshPtr& mesh); - void addProfile(LodConfig& config); - void setTestLodConfig(LodConfig& config); -}; - -//-------------------------------------------------------------------------- -void MeshLodTests::SetUp() -{ - RootWithoutRenderSystemFixture::SetUp(); - - new MeshLodGenerator; - // Create the mesh for testing - mMesh = MeshManager::getSingleton().load("Sinbad.mesh", ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME); -} -//-------------------------------------------------------------------------- -void MeshLodTests::TearDown() -{ - if (mMesh) { - mMesh->unload(); - mMesh.reset(); - } - OGRE_DELETE MeshLodGenerator::getSingletonPtr(); - RootWithoutRenderSystemFixture::TearDown(); -} -//-------------------------------------------------------------------------- -void MeshLodTests::addProfile(LodConfig& config) -{ - // Get the first two vertices and put the edge into the profile - // It doesn't matter if there is no such edge, because edges are removed and created dynamically. - // The vertex positions should exist or you get an assert. - VertexData* vertexData = config.mesh->getSubMesh(0)->vertexData; - const VertexElement* elemPos = vertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); - HardwareVertexBufferSharedPtr vbuf = vertexData->vertexBufferBinding->getBuffer(elemPos->getSource()); - assert(vbuf->getNumVertices() > 2); - unsigned char* vertex = static_cast(vbuf->lock(HardwareBuffer::HBL_READ_ONLY)); - float* pFloat; - elemPos->baseVertexPointerToElement(vertex, &pFloat); - ProfiledEdge edge; - edge.src.x = *pFloat++; - edge.src.y = *pFloat++; - edge.src.z = *pFloat; - vertex += vbuf->getVertexSize(); - elemPos->baseVertexPointerToElement(vertex, &pFloat); - edge.dst.x = *pFloat++; - edge.dst.y = *pFloat++; - edge.dst.z = *pFloat; - edge.cost = LodData::NEVER_COLLAPSE_COST; - config.advanced.profile.push_back(edge); - vbuf->unlock(); -} -//-------------------------------------------------------------------------- -TEST_F(MeshLodTests,MeshLodGenerator) -{ - LodConfig config; - setTestLodConfig(config); - - MeshLodGenerator& gen = MeshLodGenerator::getSingleton(); - gen.generateLodLevels(config); - addProfile(config); - config.advanced.useBackgroundQueue = false; - config.advanced.useCompression = false; - config.advanced.useVertexNormals = false; - gen.generateLodLevels(config); - - LodConfig config2(config); - config2.advanced.useBackgroundQueue = true; - config2.mesh->removeLodLevels(); - gen.generateLodLevels(config); - blockedWaitForLodGeneration(config.mesh); - EXPECT_TRUE(config.levels.size() == config2.levels.size()); - for (size_t i = 0; i < config.levels.size(); i++) - { - EXPECT_TRUE(config.levels[i].outSkipped == config2.levels[i].outSkipped); - EXPECT_TRUE(config.levels[i].outUniqueVertexCount == config2.levels[i].outUniqueVertexCount); - } -} -//-------------------------------------------------------------------------- -void MeshLodTests::blockedWaitForLodGeneration(const MeshPtr& mesh) -{ - bool success = false; - const int timeout = 5000; - WorkQueue* wq = Root::getSingleton().getWorkQueue(); - for (int i = 0; i < timeout; i++) - { - OGRE_THREAD_SLEEP(1); - wq->processMainThreadTasks(); // Injects the Lod if ready - if (mesh->getNumLodLevels() != 1) { - success = true; - break; - } - } - // timeout - EXPECT_TRUE(success); -} -//-------------------------------------------------------------------------- -TEST_F(MeshLodTests,LodConfigSerializer) -{ - LodConfig config, config2; - setTestLodConfig(config); - addProfile(config); - LodConfigSerializer serializer; - serializer.exportLodConfig(config, "testLodConfigSerializer.lodconfig"); - serializer.importLodConfig(&config2, "testLodConfigSerializer.lodconfig"); - EXPECT_EQ(config.mesh->getHandle(), config2.mesh->getHandle()); - EXPECT_EQ(config.strategy, config2.strategy); - EXPECT_EQ(config.advanced.outsideWalkAngle, config.advanced.outsideWalkAngle); - EXPECT_EQ(config.advanced.outsideWeight, config.advanced.outsideWeight); - EXPECT_EQ(config.advanced.useBackgroundQueue, config.advanced.useBackgroundQueue); - EXPECT_EQ(config.advanced.useCompression, config.advanced.useCompression); - EXPECT_EQ(config.advanced.useVertexNormals, config.advanced.useVertexNormals); - - { - // Compare profiles - LodProfile& p1 = config.advanced.profile; - LodProfile& p2 = config2.advanced.profile; - - ASSERT_EQ(p1.size(), p2.size()); - for (size_t i = 0; i < p1.size(); i++) - { - EXPECT_EQ(p1[i].src, p2[i].src); - EXPECT_EQ(p1[i].dst, p2[i].dst); - EXPECT_FLOAT_EQ(p1[i].cost, p2[i].cost); - } - } - - { - // Compare Lod Levels - LodConfig::LodLevelList& l1 = config.levels; - LodConfig::LodLevelList& l2 = config2.levels; - - ASSERT_EQ(l1.size(), l2.size()); - for (size_t i = 0; i < l1.size(); i++) - { - EXPECT_EQ(l1[i].distance , l2[i].distance); - EXPECT_EQ(l1[i].manualMeshName, l2[i].manualMeshName); - EXPECT_EQ(l1[i].reductionMethod, l2[i].reductionMethod); - EXPECT_FLOAT_EQ(l1[i].reductionValue, l2[i].reductionValue); - } - } -} -//-------------------------------------------------------------------------- -TEST_F(MeshLodTests,ManualLodLevels) -{ - MeshLodGenerator& gen = MeshLodGenerator::getSingleton(); - LodConfig config; - setTestLodConfig(config); - gen.generateLodLevels(config, LodCollapseCostPtr(new LodCollapseCostQuadric())); -} -//-------------------------------------------------------------------------- -TEST_F(MeshLodTests,QuadricError) -{ - LodConfig config; - setTestLodConfig(config); - MeshLodGenerator& gen = MeshLodGenerator::getSingleton(); - gen.generateLodLevels(config, LodCollapseCostPtr(new LodCollapseCostQuadric())); -} -//-------------------------------------------------------------------------- -void MeshLodTests::setTestLodConfig(LodConfig& config) -{ - config.mesh = mMesh; - config.strategy = PixelCountLodStrategy::getSingletonPtr(); - config.levels.clear(); - config.createGeneratedLodLevel(10, 0.1); - config.createGeneratedLodLevel(9, 0.2); - config.createGeneratedLodLevel(8, 0.3); - config.advanced.outsideWeight = 1.0; - config.advanced.useCompression = true; - config.advanced.useVertexNormals = true; - config.advanced.useBackgroundQueue = false; -} -//-------------------------------------------------------------------------- diff --git a/Tests/Components/PageCoreTests.cpp b/Tests/Components/PageCoreTests.cpp deleted file mode 100644 index 21a071c4c2d..00000000000 --- a/Tests/Components/PageCoreTests.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include - -#include "OgreRoot.h" -#include "OgrePageManager.h" -#include "OgreGrid2DPageStrategy.h" -#include "OgreBuildSettings.h" - - -#include "OgreStaticPluginLoader.h" -#include "OgrePaging.h" -#include "OgreLogManager.h" - -using namespace Ogre; - -class PageCoreTests : public ::testing::Test -{ -public: - Root* mRoot; - PageManager* mPageManager; - SceneManager* mSceneMgr; - - void SetUp() override; - void TearDown() override; -}; -// Register the test suite - -//-------------------------------------------------------------------------- -void PageCoreTests::SetUp() -{ - mRoot = OGRE_NEW Root(""); - - mPageManager = OGRE_NEW PageManager(); - - // make certain the resource location is NOT read-only - ResourceGroupManager::getSingleton().addResourceLocation("./", "FileSystem", - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, false, false); - - mSceneMgr = mRoot->createSceneManager(); -} -//-------------------------------------------------------------------------- -void PageCoreTests::TearDown() -{ - OGRE_DELETE mPageManager; - OGRE_DELETE mRoot; -} -//-------------------------------------------------------------------------- -TEST_F(PageCoreTests,SimpleCreateSaveLoadWorld) -{ - String worldName = "MyWorld"; - String filename = "myworld.world"; - String sectionName1 = "Section1"; - String sectionName2 = "Section2"; - PagedWorld* world = mPageManager->createWorld(worldName); - PagedWorldSection* section = world->createSection("Grid2D", mSceneMgr, sectionName1); - section = world->createSection("Grid2D", mSceneMgr, sectionName2); - - // Create a page - Page* p = section->loadOrCreatePage(Vector3::ZERO); - - p->createContentCollection("Simple"); - - world->save(filename); - - mPageManager->destroyWorld(world); - world = 0; - world = mPageManager->loadWorld(filename); - - EXPECT_EQ(worldName, world->getName()); - EXPECT_EQ((size_t)2, world->getSectionCount()); - - section = world->getSection(sectionName1); - EXPECT_TRUE(section != 0); - section = world->getSection(sectionName2); - EXPECT_TRUE(section != 0); -} -//-------------------------------------------------------------------------- - diff --git a/Tests/Components/PropertyTests.cpp b/Tests/Components/PropertyTests.cpp deleted file mode 100644 index 910658a5c1e..00000000000 --- a/Tests/Components/PropertyTests.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreRoot.h" -#include "OgreProperty.h" - -#include - -#include - -using namespace Ogre; -//-------------------------------------------------------------------------- -class Foo -{ -protected: - String mName; -public: - void setName(const String& name) { mName = name; } - const String& getName() const { return mName; } -}; -//-------------------------------------------------------------------------- - -TEST(Property, StringProp) { - using namespace std; - - PropertyDefMap propertyDefs; - Foo foo; - PropertySet props; - - PropertyDefMap::iterator defi = - propertyDefs.emplace("name", PropertyDef("name", "The name of the object.", PROP_STRING)).first; - - props.addProperty( - OGRE_NEW Property(&(defi->second), - bind(&Foo::getName, &foo), - bind(&Foo::setName, &foo, placeholders::_1))); - - Ogre::String strName, strTest; - strTest = "A simple name"; - props.setValue("name", strTest); - props.getValue("name", strName); - - ASSERT_EQ(strTest, strName); -} -//-------------------------------------------------------------------------- diff --git a/Tests/Components/RTShaderSystemTests.cpp b/Tests/Components/RTShaderSystemTests.cpp deleted file mode 100644 index 57e35dd4851..00000000000 --- a/Tests/Components/RTShaderSystemTests.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "Ogre.h" -#include "RootWithoutRenderSystemFixture.h" -#include "OgreShaderGenerator.h" -#include "OgreShaderProgramManager.h" -#include "OgreShaderFunctionAtom.h" - -using namespace Ogre; - -struct RTShaderSystem : public RootWithoutRenderSystemFixture -{ - void SetUp() override - { - RootWithoutRenderSystemFixture::SetUp(); - - RTShader::ShaderGenerator::initialize(); - RTShader::ShaderGenerator::getSingleton().setTargetLanguage("glsl"); - } - void TearDown() override - { - RTShader::ShaderGenerator::destroy(); - RootWithoutRenderSystemFixture::TearDown(); - } -}; - -TEST_F(RTShaderSystem, createShaderBasedTechnique) -{ - auto& shaderGen = RTShader::ShaderGenerator::getSingleton(); - auto mat = MaterialManager::getSingleton().create("TestMat", RGN_DEFAULT); - - EXPECT_TRUE(shaderGen.createShaderBasedTechnique(mat->getTechniques()[0], "MyScheme")); - shaderGen.getRenderState("MyScheme")->setLightCountAutoUpdate(false); - - EXPECT_EQ(mat->getTechniques().size(), size_t(1)); - shaderGen.validateMaterial("MyScheme", *mat); - EXPECT_EQ(mat->getTechniques().size(), size_t(2)); - - auto newTech = mat->getTechniques()[1]; - - EXPECT_EQ(newTech->getSchemeName(), "MyScheme"); - EXPECT_TRUE(newTech->getPasses()[0]->hasGpuProgram(GPT_VERTEX_PROGRAM)); - EXPECT_TRUE(newTech->getPasses()[0]->hasGpuProgram(GPT_FRAGMENT_PROGRAM)); - - EXPECT_TRUE(shaderGen.removeShaderBasedTechnique(mat->getTechniques()[0], "MyScheme")); -} - -TEST_F(RTShaderSystem, MaterialSerializer) -{ - auto& shaderGen = RTShader::ShaderGenerator::getSingleton(); - auto mat = MaterialManager::getSingleton().create("TestMat", RGN_DEFAULT); - - shaderGen.createShaderBasedTechnique(mat->getTechniques()[0], "MyScheme"); - shaderGen.getRenderState("MyScheme")->setLightCountAutoUpdate(false); - - auto rstate = shaderGen.getRenderState("MyScheme", *mat); - rstate->addTemplateSubRenderState(shaderGen.createSubRenderState("FFP_Colour")); - - shaderGen.validateMaterial("MyScheme", *mat); - - MaterialSerializer ser; - ser.addListener(shaderGen.getMaterialSerializerListener()); - ser.queueForExport(mat); - EXPECT_TRUE(ser.getQueuedAsString().find("colour_stage") != String::npos); -} - -TEST_F(RTShaderSystem, TargetRenderState) -{ - auto mat = MaterialManager::getSingleton().create("TestMat", RGN_DEFAULT); - auto pass = mat->getTechniques()[0]->getPasses()[0]; - - using namespace RTShader; - TargetRenderState targetRenderState; - targetRenderState.link({"FFP_Transform", "FFP_Colour"}, pass, pass); - targetRenderState.acquirePrograms(pass); - - EXPECT_TRUE(pass->hasGpuProgram(GPT_VERTEX_PROGRAM)); - EXPECT_TRUE(pass->hasGpuProgram(GPT_FRAGMENT_PROGRAM)); -} - -TEST_F(RTShaderSystem, FunctionInvocationOrder) -{ - using namespace RTShader; - - FunctionInvocation a("name", 0); - FunctionInvocation b("name", 0); - FunctionInvocation c("name", 0); - - a.pushOperand(ParameterFactory::createConstParam(Vector3()), Operand::OPS_IN); - b.pushOperand(ParameterFactory::createConstParam(Vector3()), Operand::OPS_IN, Operand::OPM_XY); - c.pushOperand(ParameterFactory::createConstParam(Vector3()), Operand::OPS_IN, Operand::OPM_XYZ); - - EXPECT_FALSE(b == a); - EXPECT_TRUE(b < a); - - EXPECT_TRUE(c == a); - EXPECT_FALSE(c < a); -} diff --git a/Tests/Components/TerrainTests.cpp b/Tests/Components/TerrainTests.cpp deleted file mode 100644 index 88f866dac83..00000000000 --- a/Tests/Components/TerrainTests.cpp +++ /dev/null @@ -1,127 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include - -#include "OgreRoot.h" -#include "OgreTerrain.h" -#include "OgreFileSystemLayer.h" - -#include "OgreBuildSettings.h" -#include "OgreStaticPluginLoader.h" -#include "OgreConfigFile.h" -#include "OgreResourceGroupManager.h" -#include "OgreLogManager.h" -#include "OgreSTBICodec.h" -#include "OgreStreamSerialiser.h" -#include "OgreDefaultHardwareBufferManager.h" - -using namespace Ogre; - -class TerrainTests : public ::testing::Test -{ -public: - Root* mRoot; - SceneManager* mSceneMgr; - TerrainGlobalOptions* mTerrainOpts; - - void SetUp() override; - void TearDown() override; -}; - -//-------------------------------------------------------------------------- -void TerrainTests::SetUp() -{ - mRoot = OGRE_NEW Root(""); - - - STBIImageCodec::startup(); - - mTerrainOpts = OGRE_NEW TerrainGlobalOptions(); - - // Load resource paths from config file - ConfigFile cf; - cf.load(FileSystemLayer(OGRE_VERSION_NAME).getConfigFilePath("resources.cfg")); - - // Go through all sections & settings in the file - String secName, typeName, archName; - ConfigFile::SettingsBySection_::const_iterator seci; - for(seci = cf.getSettingsBySection().begin(); seci != cf.getSettingsBySection().end(); ++seci) { - secName = seci->first; - const ConfigFile::SettingsMultiMap& settings = seci->second; - ConfigFile::SettingsMultiMap::const_iterator i; - for (i = settings.begin(); i != settings.end(); ++i) - { - typeName = i->first; - archName = i->second; - ResourceGroupManager::getSingleton().addResourceLocation( - archName, typeName, secName); - } - } - - mSceneMgr = mRoot->createSceneManager(); -} -//-------------------------------------------------------------------------- -void TerrainTests::TearDown() -{ - STBIImageCodec::shutdown(); - OGRE_DELETE mTerrainOpts; - OGRE_DELETE mRoot; -} -//-------------------------------------------------------------------------- -TEST_F(TerrainTests, create) -{ - Terrain* t = OGRE_NEW Terrain(mSceneMgr); - Image img; - img.load("terrain.png", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - Terrain::ImportData imp; - imp.inputImage = &img; - imp.terrainSize = 513; - imp.worldSize = 1000; - imp.minBatchSize = 33; - imp.maxBatchSize = 65; - ASSERT_TRUE(t->prepare(imp)); - - { - DefaultHardwareBufferManager hbm; - StreamSerialiser ser(Root::createFileStream("TerrainTest.dat")); - t->save(ser); - OGRE_DELETE t; - } - - // read-back from file - t = OGRE_NEW Terrain(mSceneMgr); - StreamSerialiser ser(Root::openFileStream("TerrainTest.dat")); - ASSERT_TRUE(t->prepare(ser)); - ASSERT_EQ(t->getSize(), imp.terrainSize); - - OGRE_DELETE t; - - FileSystemLayer::removeFile("TerrainTest.dat"); -} -//-------------------------------------------------------------------------- diff --git a/Tests/Media/BillboardText.fontdef b/Tests/Media/BillboardText.fontdef deleted file mode 100755 index fb03f28591f..00000000000 --- a/Tests/Media/BillboardText.fontdef +++ /dev/null @@ -1,8 +0,0 @@ -font DejaVu/SerifCondensedItalic -{ - type truetype - source DejaVuSerifCondensed-Italic.ttf - size 15 - resolution 180 - code_points 32-126 192-255 -} \ No newline at end of file diff --git a/Tests/Media/BumpyMetal_dxt1.dds b/Tests/Media/BumpyMetal_dxt1.dds deleted file mode 100644 index da026b00537..00000000000 Binary files a/Tests/Media/BumpyMetal_dxt1.dds and /dev/null differ diff --git a/Tests/Media/BumpyMetal_float16.dds b/Tests/Media/BumpyMetal_float16.dds deleted file mode 100644 index ff97cfec664..00000000000 Binary files a/Tests/Media/BumpyMetal_float16.dds and /dev/null differ diff --git a/Tests/Media/BumpyMetal_float32.dds b/Tests/Media/BumpyMetal_float32.dds deleted file mode 100644 index f35accb0bbf..00000000000 Binary files a/Tests/Media/BumpyMetal_float32.dds and /dev/null differ diff --git a/Tests/Media/CustomCapabilities/customCapabilitiesTest.cfg b/Tests/Media/CustomCapabilities/customCapabilitiesTest.cfg deleted file mode 100644 index d5a43427079..00000000000 --- a/Tests/Media/CustomCapabilities/customCapabilitiesTest.cfg +++ /dev/null @@ -1,4 +0,0 @@ -Custom Capabilities=TestCaps Realistic Low-End GPU - -[Capabilities Database] -FileSystem=. diff --git a/Tests/Media/CustomCapabilities/realisticLowEnd.rendercaps b/Tests/Media/CustomCapabilities/realisticLowEnd.rendercaps deleted file mode 100644 index bc9024c7429..00000000000 --- a/Tests/Media/CustomCapabilities/realisticLowEnd.rendercaps +++ /dev/null @@ -1,61 +0,0 @@ -render_system_capabilities "TestCaps Realistic Low-End GPU" -{ -render_system_name Direct3D9 Rendering Subsystem -automipmap_compressed true -blending true -anisotropy true -dot3 true -cubemapping true -hwstencil true -vbo true -vertex_program true -fragment_program true -scissor_test true -two_sided_stencil true -stencil_wrap true -hwocclusion true -user_clip_planes true -vertex_format_ubyte4 true -infinite_far_plane true -hwrender_to_texture true -texture_float true -non_power_of_2_textures false -texture_3d true -point_sprites true -point_extended_parameters true -vertex_texture_fetch false -mipmap_lod_bias true -texture_compression true -texture_compression_dxt true -texture_compression_vtc false -gl1_5_novbo false -fbo true -fbo_arb false -fbo_ati false -pbuffer false -gl1_5_nohwocclusion false -perstageconstant false -shader_profile arbfp1 -shader_profile arbvp1 -shader_profile glsl -shader_profile ps_1_1 -shader_profile ps_1_2 -shader_profile ps_1_3 -shader_profile ps_1_4 -max_point_size 1024 -non_pow2_textures_limited false -vertex_texture_units_shared true -num_world_matrices 0 -num_texture_units 16 -stencil_buffer_bit_depth 8 -num_vertex_blend_matrices 0 -num_multi_render_targets 4 -vertex_program_constant_float_count 256 -vertex_program_constant_int_count 0 -vertex_program_constant_bool_count 0 -fragment_program_constant_float_count 64 -fragment_program_constant_int_count 0 -fragment_program_constant_bool_count 0 -num_vertex_texture_units 0 -separate_shader_objects false -} diff --git a/Tests/Media/CustomCapabilities/test1.rendercaps b/Tests/Media/CustomCapabilities/test1.rendercaps deleted file mode 100644 index a1b5bc8e950..00000000000 --- a/Tests/Media/CustomCapabilities/test1.rendercaps +++ /dev/null @@ -1,46 +0,0 @@ -render_system_capabilities "TestCaps Blank" -{ - // there is absolutely nothing here -} - -render_system_capabilities "TestCaps enum Capabilities" -{ - // this rsc definition only contains RSC_XXX style caps - automipmap_compressed true - vao true -} - -render_system_capabilities "TestCaps set String" -{ - // this rsc definition contains only caps set with a method, like: - // void setXXX(String& val) - - shader_profile vs99 -} - -render_system_capabilities "TestCaps set bool (true)" -{ - vertex_texture_units_shared true -} - -render_system_capabilities "TestCaps set bool (false)" -{ - vertex_texture_units_shared false -} - -render_system_capabilities "TestCaps set int" -{ - num_multi_render_targets 99 -} - -render_system_capabilities "TestCaps set Real" -{ - max_point_size 99.5 -} - -render_system_capabilities "TestCaps addShaderProfile" -{ - shader_profile vp1 - shader_profile vs_1_1 - shader_profile ps_99 -} diff --git a/Tests/Media/DejaVuSerifCondensed-Italic.ttf b/Tests/Media/DejaVuSerifCondensed-Italic.ttf deleted file mode 100644 index 2ba11a51035..00000000000 Binary files a/Tests/Media/DejaVuSerifCondensed-Italic.ttf and /dev/null differ diff --git a/Tests/Media/Earth-Color10x6.astc b/Tests/Media/Earth-Color10x6.astc deleted file mode 100644 index f743b06a0f3..00000000000 Binary files a/Tests/Media/Earth-Color10x6.astc and /dev/null differ diff --git a/Tests/Media/Model1/UniqueModel.MESH b/Tests/Media/Model1/UniqueModel.MESH deleted file mode 100644 index 617fd978bad..00000000000 Binary files a/Tests/Media/Model1/UniqueModel.MESH and /dev/null differ diff --git a/Tests/Media/Model1/UniqueModel.MESH.material b/Tests/Media/Model1/UniqueModel.MESH.material deleted file mode 100644 index df48f6135f5..00000000000 --- a/Tests/Media/Model1/UniqueModel.MESH.material +++ /dev/null @@ -1,20 +0,0 @@ - -material UniqueMaterial -{ - technique Default - { - pass Main - { - ambient 0.588 0.588 0.588 1 - diffuse 0.588 0.588 0.588 1 - specular 0.9 0.9 0.9 1 10 - - texture_unit - { - texture UniqueTexture.dds -1 - } - } - - } - -} diff --git a/Tests/Media/Model1/UniqueModel.mesh.skeleton b/Tests/Media/Model1/UniqueModel.mesh.skeleton deleted file mode 100644 index c5aaf50c94f..00000000000 Binary files a/Tests/Media/Model1/UniqueModel.mesh.skeleton and /dev/null differ diff --git a/Tests/Media/Model1/UniqueTexture.dds b/Tests/Media/Model1/UniqueTexture.dds deleted file mode 100644 index d9e41c93d02..00000000000 Binary files a/Tests/Media/Model1/UniqueTexture.dds and /dev/null differ diff --git a/Tests/Media/Model2/UniqueModel.MESH b/Tests/Media/Model2/UniqueModel.MESH deleted file mode 100644 index b4b51b6da5b..00000000000 Binary files a/Tests/Media/Model2/UniqueModel.MESH and /dev/null differ diff --git a/Tests/Media/Model2/UniqueModel.MESH.material b/Tests/Media/Model2/UniqueModel.MESH.material deleted file mode 100644 index 621542754b3..00000000000 --- a/Tests/Media/Model2/UniqueModel.MESH.material +++ /dev/null @@ -1,18 +0,0 @@ - -material UniqueMaterial -{ - technique Default - { - pass Main - { - specular 0.25098 0.25098 0.25098 1 20 - - texture_unit - { - texture UniqueTexture.dds -1 - } - } - - } - -} diff --git a/Tests/Media/Model2/UniqueModel.mesh.skeleton b/Tests/Media/Model2/UniqueModel.mesh.skeleton deleted file mode 100644 index ed4cb8d2a2a..00000000000 Binary files a/Tests/Media/Model2/UniqueModel.mesh.skeleton and /dev/null differ diff --git a/Tests/Media/Model2/UniqueTexture.dds b/Tests/Media/Model2/UniqueTexture.dds deleted file mode 100644 index d1793bafe7a..00000000000 Binary files a/Tests/Media/Model2/UniqueTexture.dds and /dev/null differ diff --git a/Tests/Media/Texture.pkm b/Tests/Media/Texture.pkm deleted file mode 100644 index ac6ff61227f..00000000000 Binary files a/Tests/Media/Texture.pkm and /dev/null differ diff --git a/Tests/Media/decal0.png b/Tests/Media/decal0.png deleted file mode 100644 index 487dd7f49e9..00000000000 Binary files a/Tests/Media/decal0.png and /dev/null differ diff --git a/Tests/Media/decal1.png b/Tests/Media/decal1.png deleted file mode 100644 index 786487e2570..00000000000 Binary files a/Tests/Media/decal1.png and /dev/null differ diff --git a/Tests/Media/decal1small.png b/Tests/Media/decal1small.png deleted file mode 100644 index 25df4a3cd17..00000000000 Binary files a/Tests/Media/decal1small.png and /dev/null differ diff --git a/Tests/Media/decal1vflip.png b/Tests/Media/decal1vflip.png deleted file mode 100644 index eaeb748d0e3..00000000000 Binary files a/Tests/Media/decal1vflip.png and /dev/null differ diff --git a/Tests/Media/decal2.png b/Tests/Media/decal2.png deleted file mode 100644 index 9871e363fef..00000000000 Binary files a/Tests/Media/decal2.png and /dev/null differ diff --git a/Tests/Media/decal3.png b/Tests/Media/decal3.png deleted file mode 100644 index 6c1369bf731..00000000000 Binary files a/Tests/Media/decal3.png and /dev/null differ diff --git a/Tests/Media/decal4.png b/Tests/Media/decal4.png deleted file mode 100644 index c8f58ff57b0..00000000000 Binary files a/Tests/Media/decal4.png and /dev/null differ diff --git a/Tests/Media/decal5.png b/Tests/Media/decal5.png deleted file mode 100644 index 4e298afa77f..00000000000 Binary files a/Tests/Media/decal5.png and /dev/null differ diff --git a/Tests/Media/decal6.png b/Tests/Media/decal6.png deleted file mode 100644 index 6a143c5d341..00000000000 Binary files a/Tests/Media/decal6.png and /dev/null differ diff --git a/Tests/Media/etc2-rgba8.ktx b/Tests/Media/etc2-rgba8.ktx deleted file mode 100644 index 5ebb00055df..00000000000 Binary files a/Tests/Media/etc2-rgba8.ktx and /dev/null differ diff --git a/Tests/Media/glow.material b/Tests/Media/glow.material deleted file mode 100644 index b0d67d4e76e..00000000000 --- a/Tests/Media/glow.material +++ /dev/null @@ -1,123 +0,0 @@ -vertex_program glow_vs_glsl glsl glsles -{ - source vs_glow.glsl -} -fragment_program glow_ps_glsl glsl glsles -{ - source ps_glow.glsl -} - -vertex_program glow_vs_cg hlsl -{ - source vs_glow.cg - target vs_2_0 -} - -fragment_program glow_ps_cg hlsl -{ - source ps_glow.cg - target ps_2_0 -} - -vertex_program glow_vs unified -{ - delegate glow_vs_glsl - delegate glow_vs_cg - - default_params - { - param_named_auto worldViewProjMatrix worldviewproj_matrix - param_named size_value float 1.1 - param_named_auto time time_0_x 100 - } -} - -fragment_program glow_ps unified -{ - delegate glow_ps_glsl - delegate glow_ps_cg -} - -material glow -{ - technique - { - pass - { - scene_blend alpha_blend - depth_check on - lighting off - - fragment_program_ref glow_ps - { - param_named_auto time time_0_x 100 - param_named alpha_value float 0.4 - } - vertex_program_ref glow_vs - { - } - } - - } -} - -material alpha_glow -{ - technique - { - pass - { - scene_blend alpha_blend - depth_check on - lighting off - - fragment_program_ref glow_ps - { - param_named_auto time time_0_x 100 - param_named alpha_value float 0.0 - } - vertex_program_ref glow_vs - { - } - } - - pass - { - scene_blend alpha_blend - depth_check on - lighting off - - vertex_program_ref Ogre/BasicVertexPrograms/AmbientOneTextureUnified - { - } - - fragment_program_ref glow_ps - { - param_named_auto time time_0_x 100 - param_named alpha_value float 0.0 - } - } - } -} - -material no_depth_check_glow -{ - technique - { - pass - { - scene_blend alpha_blend - depth_check off - lighting off - - fragment_program_ref glow_ps - { - param_named_auto time time_0_x 100 - param_named alpha_value float 0.4 - } - vertex_program_ref glow_vs - { - } - } - } -} diff --git a/Tests/Media/grace_cube.dds b/Tests/Media/grace_cube.dds deleted file mode 100644 index 3edae722f1a..00000000000 Binary files a/Tests/Media/grace_cube.dds and /dev/null differ diff --git a/Tests/Media/gras_02_dxt1.dds b/Tests/Media/gras_02_dxt1.dds deleted file mode 100644 index beda75c74ca..00000000000 Binary files a/Tests/Media/gras_02_dxt1.dds and /dev/null differ diff --git a/Tests/Media/misc/ArchiveTest.zip b/Tests/Media/misc/ArchiveTest.zip deleted file mode 100644 index dcb7eafebaf..00000000000 Binary files a/Tests/Media/misc/ArchiveTest.zip and /dev/null differ diff --git a/Tests/Media/misc/ArchiveTest/level1/materials/scripts/file.material b/Tests/Media/misc/ArchiveTest/level1/materials/scripts/file.material deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/Tests/Media/misc/ArchiveTest/level1/materials/scripts/file2.material b/Tests/Media/misc/ArchiveTest/level1/materials/scripts/file2.material deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/Tests/Media/misc/ArchiveTest/level2/materials/scripts/file3.material b/Tests/Media/misc/ArchiveTest/level2/materials/scripts/file3.material deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/Tests/Media/misc/ArchiveTest/level2/materials/scripts/file4.material b/Tests/Media/misc/ArchiveTest/level2/materials/scripts/file4.material deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/Tests/Media/misc/ArchiveTest/rootfile.txt b/Tests/Media/misc/ArchiveTest/rootfile.txt deleted file mode 100644 index 705b180fbc1..00000000000 --- a/Tests/Media/misc/ArchiveTest/rootfile.txt +++ /dev/null @@ -1,5 +0,0 @@ -this is line 1 in file 1 -this is line 2 in file 1 -this is line 3 in file 1 -this is line 4 in file 1 -this is line 5 in file 1 diff --git a/Tests/Media/misc/ArchiveTest/rootfile2.txt b/Tests/Media/misc/ArchiveTest/rootfile2.txt deleted file mode 100644 index 444e6144798..00000000000 --- a/Tests/Media/misc/ArchiveTest/rootfile2.txt +++ /dev/null @@ -1,6 +0,0 @@ -this is line 1 in file 2 -this is line 2 in file 2 -this is line 3 in file 2 -this is line 4 in file 2 -this is line 5 in file 2 -this is line 6 in file 2 diff --git a/Tests/Media/ogreborderUp_dxt3.dds b/Tests/Media/ogreborderUp_dxt3.dds deleted file mode 100644 index aceb780124b..00000000000 Binary files a/Tests/Media/ogreborderUp_dxt3.dds and /dev/null differ diff --git a/Tests/Media/ogreborderUp_dxt5.dds b/Tests/Media/ogreborderUp_dxt5.dds deleted file mode 100644 index c298431fa82..00000000000 Binary files a/Tests/Media/ogreborderUp_dxt5.dds and /dev/null differ diff --git a/Tests/Media/ogreborderUp_float128.dds b/Tests/Media/ogreborderUp_float128.dds deleted file mode 100644 index a1fbce64c6f..00000000000 Binary files a/Tests/Media/ogreborderUp_float128.dds and /dev/null differ diff --git a/Tests/Media/ogreborderUp_float64.dds b/Tests/Media/ogreborderUp_float64.dds deleted file mode 100644 index d88143b1d67..00000000000 Binary files a/Tests/Media/ogreborderUp_float64.dds and /dev/null differ diff --git a/Tests/Media/ogreborderUp_pvr2.pvr b/Tests/Media/ogreborderUp_pvr2.pvr deleted file mode 100644 index 8a81fa17147..00000000000 Binary files a/Tests/Media/ogreborderUp_pvr2.pvr and /dev/null differ diff --git a/Tests/Media/ogreborderUp_pvr2a.pvr b/Tests/Media/ogreborderUp_pvr2a.pvr deleted file mode 100644 index 97d3f2abfab..00000000000 Binary files a/Tests/Media/ogreborderUp_pvr2a.pvr and /dev/null differ diff --git a/Tests/Media/ogreborderUp_pvr4.pvr b/Tests/Media/ogreborderUp_pvr4.pvr deleted file mode 100644 index 5dc039e200f..00000000000 Binary files a/Tests/Media/ogreborderUp_pvr4.pvr and /dev/null differ diff --git a/Tests/Media/ogreborderUp_pvr4a.pvr b/Tests/Media/ogreborderUp_pvr4a.pvr deleted file mode 100644 index dd3766c63ec..00000000000 Binary files a/Tests/Media/ogreborderUp_pvr4a.pvr and /dev/null differ diff --git a/Tests/Media/ps_glow.cg b/Tests/Media/ps_glow.cg deleted file mode 100644 index 11c1241ff53..00000000000 --- a/Tests/Media/ps_glow.cg +++ /dev/null @@ -1,14 +0,0 @@ - -float4 main(uniform float alpha_value, - uniform float time -) : COLOR -{ - float4 color; - color.x = 1.0; - color.y = 1.0; - color.z = 0.0; - color.w = alpha_value * ((sin(time * 5.0) / 3.14 + 1.0) / 2.0 ); - return color; - - -} diff --git a/Tests/Media/ps_glow.glsl b/Tests/Media/ps_glow.glsl deleted file mode 100644 index 7ae134442b6..00000000000 --- a/Tests/Media/ps_glow.glsl +++ /dev/null @@ -1,12 +0,0 @@ -uniform float alpha_value; -uniform float time; - -void main(void) -{ - vec4 color; - color.x = 1.0; - color.y = 1.0; - color.z = 0.0; - color.w = alpha_value * ((sin(time * 5.0) + 1.0) / 2.0 ); - gl_FragColor = color; -} \ No newline at end of file diff --git a/Tests/Media/rockwall_flare.png b/Tests/Media/rockwall_flare.png deleted file mode 100644 index 768c62485ba..00000000000 Binary files a/Tests/Media/rockwall_flare.png and /dev/null differ diff --git a/Tests/Media/testmirroreduvmesh.mesh b/Tests/Media/testmirroreduvmesh.mesh deleted file mode 100644 index 703dc45dfb3..00000000000 Binary files a/Tests/Media/testmirroreduvmesh.mesh and /dev/null differ diff --git a/Tests/Media/tests.material b/Tests/Media/tests.material deleted file mode 100644 index 409dabfe543..00000000000 --- a/Tests/Media/tests.material +++ /dev/null @@ -1,16 +0,0 @@ -material Tests/TwoSidedLighting -{ - technique - { - pass - { - diffuse 0 0.0 0.8 - specular 0.8 0 0 128 - cull_hardware none - rtshader_system - { - lighting_stage per_pixel two_sided - } - } - } -} \ No newline at end of file diff --git a/Tests/Media/vs_glow.cg b/Tests/Media/vs_glow.cg deleted file mode 100644 index 0678604262e..00000000000 --- a/Tests/Media/vs_glow.cg +++ /dev/null @@ -1,19 +0,0 @@ -void main(float4 position : POSITION, - float3 normal : NORMAL, - float2 uv : TEXCOORD0, - out float4 oPosition : POSITION, - out float2 oUv : TEXCOORD0, - out float4 colour : COLOR, - - uniform float4x4 worldViewProjMatrix, - uniform float size_value, - uniform float time - ) -{ - - float4 mypos = position; - mypos.xyz += size_value * (1.0 + (sin(time * 5.0) + 1.0) / 5.0 ) * normal; - oPosition = mul(worldViewProjMatrix, mypos); - -} - diff --git a/Tests/Media/vs_glow.glsl b/Tests/Media/vs_glow.glsl deleted file mode 100644 index b99b5a9ce6e..00000000000 --- a/Tests/Media/vs_glow.glsl +++ /dev/null @@ -1,17 +0,0 @@ -#ifdef GL_ES -precision mediump float; -#endif - -uniform float size_value; -uniform float time; -uniform mat4 worldViewProjMatrix; - -attribute vec4 vertex; -attribute vec3 normal; - -void main(void) -{ - vec3 Pos = vertex.xyz + (size_value * (1.0 + (sin(time * 5.0) + 1.0) / 15.0 ) * normal); - - gl_Position = worldViewProjMatrix * vec4(Pos,1.0); -} diff --git a/Tests/OgreMain/include/EdgeBuilderTests.h b/Tests/OgreMain/include/EdgeBuilderTests.h deleted file mode 100644 index 91d044b9957..00000000000 --- a/Tests/OgreMain/include/EdgeBuilderTests.h +++ /dev/null @@ -1,49 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __EdgeBuilderTests_H__ -#define __EdgeBuilderTests_H__ - -#include -#include "OgreLogManager.h" -#include "OgreHardwareBufferManager.h" - -using namespace Ogre; - -class EdgeBuilderTests : public ::testing::Test -{ - -protected: - HardwareBufferManager* mBufMgr; - -public: - void SetUp() override; - void TearDown() override; -}; - -#endif diff --git a/Tests/OgreMain/include/FileSystemArchiveTests.h b/Tests/OgreMain/include/FileSystemArchiveTests.h deleted file mode 100644 index 6ffae592ff6..00000000000 --- a/Tests/OgreMain/include/FileSystemArchiveTests.h +++ /dev/null @@ -1,53 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __FileSystemArchiveTests_H__ -#define __FileSystemArchiveTests_H__ - -#include -#include "OgreString.h" -#include "OgreFileSystem.h" - -using namespace Ogre; - -class FileSystemArchiveTests : public ::testing::Test -{ - -protected: - FileSystemArchiveFactory mFactory; - Archive* mArch; - String mTestPath; - size_t mFileSizeRoot1; - size_t mFileSizeRoot2; - -public: - void SetUp() override; - void TearDown() override; -}; - -#endif diff --git a/Tests/OgreMain/include/MeshSerializerTests.h b/Tests/OgreMain/include/MeshSerializerTests.h deleted file mode 100644 index 12f21e25d26..00000000000 --- a/Tests/OgreMain/include/MeshSerializerTests.h +++ /dev/null @@ -1,73 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __MeshSerializerTests_H__ -#define __MeshSerializerTests_H__ - -#include -#include "OgreMesh.h" -#include "OgreMeshSerializer.h" -#include "OgreFileSystemLayer.h" - -using namespace Ogre; - -class MeshSerializerTests : public ::testing::Test -{ - -protected: - MeshPtr mMesh; - MeshPtr mOrigMesh; - String mMeshFullPath; - String mSkeletonFullPath; - SkeletonPtr mSkeleton; - Real mErrorFactor; - FileSystemLayer* mFSLayer; - -public: - void SetUp() override; - void TearDown() override; - void testMesh(MeshVersion version); - void assertMeshClone(Mesh* a, Mesh* b, MeshVersion version = MESH_VERSION_LATEST); - void assertVertexDataClone(VertexData* a, VertexData* b, MeshVersion version = MESH_VERSION_LATEST); - void assertIndexDataClone(IndexData* a, IndexData* b, MeshVersion version = MESH_VERSION_LATEST); - void assertEdgeDataClone(EdgeData* a, EdgeData* b, MeshVersion version = MESH_VERSION_LATEST); - void assertLodUsageClone(const MeshLodUsage& a, const MeshLodUsage& b, MeshVersion version = MESH_VERSION_LATEST); - - template - bool isContainerClone(T& a, T& b); - template - bool isHashMapClone(const std::unordered_map& a, const std::unordered_map& b); - - void getResourceFullPath(const ResourcePtr& resource, String& outPath); - bool copyFile(const String& srcPath, const String& dstPath); - bool isLodMixed(const Mesh* pMesh); - bool isEqual(Real a, Real b); - bool isEqual(const Vector3& a, const Vector3& b); -}; - -#endif diff --git a/Tests/OgreMain/include/MeshWithoutIndexDataTests.h b/Tests/OgreMain/include/MeshWithoutIndexDataTests.h deleted file mode 100644 index 73e4d678788..00000000000 --- a/Tests/OgreMain/include/MeshWithoutIndexDataTests.h +++ /dev/null @@ -1,48 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __MeshWithoutIndexDataTests_H__ -#define __MeshWithoutIndexDataTests_H__ - -#include - -using namespace Ogre; - -class MeshWithoutIndexDataTests : public ::testing::Test -{ - -protected: - HardwareBufferManager* mBufMgr; - MeshManager* mMeshMgr; - ArchiveManager* mArchiveMgr; - -public: - void SetUp() override; - void TearDown() override; -}; -#endif diff --git a/Tests/OgreMain/include/PixelFormatTests.h b/Tests/OgreMain/include/PixelFormatTests.h deleted file mode 100644 index 6d9378aac86..00000000000 --- a/Tests/OgreMain/include/PixelFormatTests.h +++ /dev/null @@ -1,54 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __PixelFormatTests_H__ -#define __PixelFormatTests_H__ - -#include -#include "OgrePixelFormat.h" - -using namespace Ogre; - -class PixelFormatTests : public ::testing::Test -{ - -public: - void SetUp() override; - void TearDown() override; - - // Utils - void setupBoxes(PixelFormat srcFormat, PixelFormat dstFormat); - void testCase(PixelFormat srcFormat, PixelFormat dstFormat); - - int mSize; - uint8 *mRandomData; - uint8 *mTemp, *mTemp2; - PixelBox mSrc, mDst1, mDst2; -}; - -#endif diff --git a/Tests/OgreMain/include/RadixSortTests.h b/Tests/OgreMain/include/RadixSortTests.h deleted file mode 100644 index ef8544451a1..00000000000 --- a/Tests/OgreMain/include/RadixSortTests.h +++ /dev/null @@ -1,41 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __RadixSortTests_H__ -#define __RadixSortTests_H__ - -#include - -class RadixSortTests : public ::testing::Test -{ -public: - void SetUp() override; - void TearDown() override; -}; - -#endif diff --git a/Tests/OgreMain/include/RenderSystemCapabilitiesTests.h b/Tests/OgreMain/include/RenderSystemCapabilitiesTests.h deleted file mode 100644 index 17d20a99a88..00000000000 --- a/Tests/OgreMain/include/RenderSystemCapabilitiesTests.h +++ /dev/null @@ -1,55 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __RenderSystemCapabilitiesTests_H__ -#define __RenderSystemCapabilitiesTests_H__ - -#include - -#include "OgrePrerequisites.h" -#include "OgreArchiveManager.h" -#include "OgreFileSystem.h" -#include "OgreRenderSystemCapabilitiesManager.h" - -using namespace Ogre; - -class RenderSystemCapabilitiesTests : public ::testing::Test -{ - -public: - void SetUp() override; - void TearDown() override; - - // For serializing .rendercaps we need RSCManager - RenderSystemCapabilitiesManager* mRenderSystemCapabilitiesManager; - // Need these for loading .rendercaps from the file system - ArchiveManager* mArchiveManager; - FileSystemArchiveFactory* mFileSystemArchiveFactory; -}; - -#endif diff --git a/Tests/OgreMain/include/ResourceLocationPriorityTest.h b/Tests/OgreMain/include/ResourceLocationPriorityTest.h deleted file mode 100644 index 12c21a4831d..00000000000 --- a/Tests/OgreMain/include/ResourceLocationPriorityTest.h +++ /dev/null @@ -1,137 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2019 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __ResourceLocationPriorityTest_H__ -#define __ResourceLocationPriorityTest_H__ - -#include "OgreArchive.h" -#include "OgreArchiveFactory.h" -#include "OgreDataStream.h" - -// Barebones archive containing a single 1-byte file "dummyArchiveTest" whose -// contents are an unsigned char that increments on each construction of the -// archive. -class DummyArchive : public Ogre::Archive -{ -public: - DummyArchive(const Ogre::String& name, const Ogre::String& archType) - : Ogre::Archive(name, archType), mContents(DummyArchive::makeContents()) {} - - virtual ~DummyArchive() {} - - bool exists(const Ogre::String& name) const override { return name == "dummyArchiveTest"; } - - Ogre::StringVectorPtr find(const Ogre::String& pattern, bool recursive = true, bool dirs = false) const override - { - Ogre::StringVectorPtr results = std::make_shared(); - if (dirs) return results; - if (Ogre::StringUtil::match("dummyArchiveTest", pattern)) - { - results->push_back("dummyArchiveTest"); - } - return results; - } - - Ogre::FileInfoListPtr findFileInfo(const Ogre::String& pattern, bool recursive = true, - bool dirs = false) const override - { - Ogre::FileInfoListPtr results = std::make_shared(); - if (dirs) return results; - if (Ogre::StringUtil::match("dummyArchiveTest", pattern)) - { - results->push_back(Ogre::FileInfo{this, "dummyArchiveTest", "/", "dummyArchiveTest", 0, 1}); - } - return results; - } - - time_t getModifiedTime(const Ogre::String& filename) const override { return 0; } - - bool isCaseSensitive() const override { return true; } - - Ogre::StringVectorPtr list(bool recursive = true, bool dirs = false) const override - { - Ogre::StringVectorPtr results = std::make_shared(); - if (dirs) return results; - results->push_back("dummyArchiveTest"); - return results; - } - - Ogre::FileInfoListPtr listFileInfo(bool recursive = true, bool dirs = false) const override - { - Ogre::FileInfoListPtr results = std::make_shared(); - if (dirs) return results; - results->push_back(Ogre::FileInfo{this, "dummyArchiveTest", "/", "dummyArchiveTest", 0, 1}); - return results; - } - - void load() override {} - - void unload() override {} - - Ogre::DataStreamPtr open(const Ogre::String& filename, bool readOnly = true) const override - { - if (filename == "dummyArchiveTest") - { - unsigned char* ptr = OGRE_ALLOC_T(unsigned char, 1, Ogre::MEMCATEGORY_GENERAL); - *ptr = mContents; - return std::make_shared(ptr, 1, true, true); - } - return Ogre::MemoryDataStreamPtr(); - } - -private: - static unsigned char makeContents() - { - // Don't start at zero so it's obvious if things aren't initialized. - static unsigned char counter = 1; - return counter++; - } - - unsigned char mContents; -}; - -class DummyArchiveFactory : public Ogre::ArchiveFactory -{ -public: - virtual ~DummyArchiveFactory() {} - - Ogre::Archive* createInstance(const Ogre::String& name, bool) override - { - return OGRE_NEW DummyArchive(name, "DummyArchive"); - } - - void destroyInstance(Ogre::Archive* ptr) override { OGRE_DELETE ptr; } - - const Ogre::String& getType() const override - { - static Ogre::String type = "DummyArchive"; - return type; - } -}; - -#endif diff --git a/Tests/OgreMain/include/RootWithoutRenderSystemFixture.h b/Tests/OgreMain/include/RootWithoutRenderSystemFixture.h deleted file mode 100644 index bb59789b2e8..00000000000 --- a/Tests/OgreMain/include/RootWithoutRenderSystemFixture.h +++ /dev/null @@ -1,46 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef TESTS_OGREMAIN_INCLUDE_ROOTWITHOUTRENDERSYSTEMFIXTURE_H_ -#define TESTS_OGREMAIN_INCLUDE_ROOTWITHOUTRENDERSYSTEMFIXTURE_H_ - -#include -#include "OgreRoot.h" -#include "OgreFileSystemLayer.h" -#include "OgreHardwareBufferManager.h" - -class RootWithoutRenderSystemFixture : public ::testing::Test { -public: - Ogre::Root* mRoot; - Ogre::HardwareBufferManager* mHBM; - Ogre::FileSystemLayer* mFSLayer; - void SetUp() override; - void TearDown() override; -}; - -#endif /* TESTS_OGREMAIN_INCLUDE_ROOTWITHOUTRENDERSYSTEMFIXTURE_H_ */ diff --git a/Tests/OgreMain/include/StringTests.h b/Tests/OgreMain/include/StringTests.h deleted file mode 100644 index 9f557de702c..00000000000 --- a/Tests/OgreMain/include/StringTests.h +++ /dev/null @@ -1,50 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __StringTests_H__ -#define __StringTests_H__ - -#include -#include "OgreString.h" - -class StringTests : public ::testing::Test -{ - -protected: - Ogre::String testFileNoPath; - Ogre::String testFileRelativePathWindows; - Ogre::String testFileRelativePathUnix; - Ogre::String testFileAbsolutePathWindows; - Ogre::String testFileAbsolutePathUnix; - -public: - void SetUp() override; - void TearDown() override; -}; - -#endif diff --git a/Tests/OgreMain/include/ZipArchiveTests.h b/Tests/OgreMain/include/ZipArchiveTests.h deleted file mode 100644 index cdb8dda8dd0..00000000000 --- a/Tests/OgreMain/include/ZipArchiveTests.h +++ /dev/null @@ -1,45 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __ZipArchiveTests_H__ -#define __ZipArchiveTests_H__ - -#include -#include "OgreZip.h" - -class ZipArchiveTests : public ::testing::Test -{ - -protected: - Ogre::Archive* arch; -public: - void SetUp() override; - void TearDown() override; -}; - -#endif diff --git a/Tests/OgreMain/src/BitwiseTests.cpp b/Tests/OgreMain/src/BitwiseTests.cpp deleted file mode 100644 index 2d482795904..00000000000 --- a/Tests/OgreMain/src/BitwiseTests.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include - -#include "OgreBitwise.h" -#include "OgreStringConverter.h" - -using namespace Ogre; - -//-------------------------------------------------------------------------- -TEST(BitwiseTests,FixedPointConversion) -{ - EXPECT_EQ(Bitwise::fixedToFixed(0x0, 1,8), (unsigned int)0x00); - EXPECT_EQ(Bitwise::fixedToFixed(0x1, 1,8), (unsigned int)0xFF); - EXPECT_EQ(Bitwise::fixedToFixed(0x2, 2,8), (unsigned int)0xAA); // 10101010 - EXPECT_EQ(Bitwise::fixedToFixed(0x1, 2,8), (unsigned int)0x55); // 01010101 - EXPECT_EQ(Bitwise::fixedToFixed(0x2, 2,9), (unsigned int)0x155); // 1 01010101 - EXPECT_EQ(Bitwise::fixedToFixed(0x1, 2,9), (unsigned int)0x0AA); // 0 10101010 - EXPECT_EQ(Bitwise::fixedToFixed(0xFE, 8,3), (unsigned int)0x7); // 111 - EXPECT_EQ(Bitwise::fixedToFixed(0xFE, 8,9), (unsigned int)0x1FD); // 111111101 - - EXPECT_EQ(Bitwise::fixedToFloat(0xFF, 8), 1.0f); - EXPECT_EQ(Bitwise::fixedToFloat(0x00, 8), 0.0f); - - EXPECT_EQ(Bitwise::floatToFixed(1.0f, 8), (unsigned int)0xFF); - EXPECT_EQ(Bitwise::floatToFixed(0.0f, 8), (unsigned int)0x00); - - // Test clamping - EXPECT_EQ(Bitwise::floatToFixed(-1.0f,8), (unsigned int)0x00); - EXPECT_EQ(Bitwise::floatToFixed(2.0f, 8), (unsigned int)0xFF); - - // Test circular conversion - bool failed = false; - for(unsigned int x = 0; x < 0x0010; x++) - if(Bitwise::floatToFixed(Bitwise::fixedToFloat(x, 4), 4) != x) - failed = true; - EXPECT_TRUE(!failed) << "circular floatToFixed/fixedToFloat for 4 bit failed"; - - failed = false; - for(unsigned int x = 0; x < 0x0100; x++) - if(Bitwise::floatToFixed(Bitwise::fixedToFloat(x, 8), 8) != x) - failed = true; - EXPECT_TRUE(!failed) << "circular floatToFixed/fixedToFloat for 8 bit failed"; - - failed = false; - for(unsigned int x = 0; x < 0xFFE; x++) // originally loop ran till 0x1000, but precision issues sometimes prevent that - if(Bitwise::floatToFixed(Bitwise::fixedToFloat(x, 12), 12) != x) - failed = true; - EXPECT_TRUE(!failed) << "circular floatToFixed/fixedToFloat for 12 bit failed"; -} -//-------------------------------------------------------------------------- -TEST(BitwiseTests,IntReadWrite) -{ - // Test reading and writing integers - uint32 testje = 0x12345678; - EXPECT_TRUE(Bitwise::intRead(&testje, 4) == 0x12345678); - uint16 testje2 = 0x1234; - EXPECT_TRUE(Bitwise::intRead(&testje2, 2) == 0x1234); - uint8 testje3 = 0xD3; - EXPECT_TRUE(Bitwise::intRead(&testje3, 1) == 0xD3); -#if OGRE_ENDIAN == OGRE_ENDIAN_BIG - uint8 testje4[] = {0x12, 0x34, 0x56}; -#else - uint8 testje4[] = {0x56, 0x34, 0x12}; -#endif - EXPECT_TRUE(Bitwise::intRead(&testje4, 3) == 0x123456); - - Bitwise::intWrite(&testje, 4, 0x87654321); - EXPECT_TRUE(testje == 0x87654321); - - Bitwise::intWrite(&testje2, 2, 0x4321); - EXPECT_TRUE(testje2 == 0x4321); - - Bitwise::intWrite(&testje3, 1, 0x12); - EXPECT_TRUE(testje3 == 0x12); -} -//-------------------------------------------------------------------------- -TEST(BitwiseTests,Half) -{ - for(float f : {1.f, -1.f, float(INFINITY), 65504.f}) - { - uint16 g = Bitwise::floatToHalf(f); - float h = Bitwise::halfToFloat(g); - EXPECT_EQ(f, h); - } -} -//-------------------------------------------------------------------------- diff --git a/Tests/OgreMain/src/DualQuaternionTests.cpp b/Tests/OgreMain/src/DualQuaternionTests.cpp deleted file mode 100644 index c4750828f17..00000000000 --- a/Tests/OgreMain/src/DualQuaternionTests.cpp +++ /dev/null @@ -1,88 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include -#include "OgreDualQuaternion.h" -#include "OgreVector.h" -#include "OgreMatrix4.h" - - -using namespace Ogre; - -//-------------------------------------------------------------------------- -TEST(DualQuaternionTests,Conversion) -{ - DualQuaternion dQuat; - Quaternion quat(Radian(Degree(60)), Vector3::UNIT_Y); - Vector3 translation(0, 0, 10); - dQuat.fromRotationTranslation(quat, translation); - - Quaternion result; - Vector3 resTrans; - dQuat.toRotationTranslation(result, resTrans); - - EXPECT_EQ(result, quat); - EXPECT_TRUE(resTrans.positionEquals(translation)); -} -//-------------------------------------------------------------------------- -TEST(DualQuaternionTests,DefaultValue) -{ - DualQuaternion dQuatDefault; - - Quaternion quatDefault; - Vector3 transDefault; - - dQuatDefault.toRotationTranslation(quatDefault, transDefault); - - EXPECT_EQ(quatDefault, Quaternion::IDENTITY); - EXPECT_TRUE(transDefault.positionEquals(Vector3::ZERO)); -} -//-------------------------------------------------------------------------- -TEST(DualQuaternionTests,Matrix) -{ - Affine3 transform; - Vector3 translation(10, 4, 0); - Vector3 scale = Vector3::UNIT_SCALE; - Quaternion rotation; - rotation.FromAngleAxis(Radian(Math::PI), Vector3::UNIT_Z); - transform.makeTransform(translation, scale, rotation); - - DualQuaternion dQuat; - dQuat.fromTransformationMatrix(transform); - Affine3 transformResult; - dQuat.toTransformationMatrix(transformResult); - - Vector3 translationResult; - Vector3 scaleResult; - Quaternion rotationResult; - transformResult.decomposition(translationResult, scaleResult, rotationResult); - - EXPECT_TRUE(translationResult.positionEquals(translation)); - EXPECT_TRUE(scaleResult.positionEquals(scale)); - EXPECT_TRUE(rotationResult.equals(rotation, Radian(0.001))); -} -//-------------------------------------------------------------------------- diff --git a/Tests/OgreMain/src/EdgeBuilderTests.cpp b/Tests/OgreMain/src/EdgeBuilderTests.cpp deleted file mode 100644 index ef9daf2f6ab..00000000000 --- a/Tests/OgreMain/src/EdgeBuilderTests.cpp +++ /dev/null @@ -1,285 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "EdgeBuilderTests.h" -#include "OgreDefaultHardwareBufferManager.h" -#include "OgreVertexIndexData.h" -#include "OgreEdgeListBuilder.h" - - -// Register the test suite - -//-------------------------------------------------------------------------- -void EdgeBuilderTests::SetUp() -{ - mBufMgr = OGRE_NEW DefaultHardwareBufferManager(); -} -//-------------------------------------------------------------------------- -void EdgeBuilderTests::TearDown() -{ - OGRE_DELETE mBufMgr; -} -//-------------------------------------------------------------------------- -TEST_F(EdgeBuilderTests,SingleIndexBufSingleVertexBuf) -{ - /* This tests the edge builders ability to find shared edges in the simple case - of a single index buffer referencing a single vertex buffer - */ - VertexData vd; - IndexData id; - - // Test pyramid - vd.vertexCount = 4; - vd.vertexStart = 0; - vd.vertexDeclaration = HardwareBufferManager::getSingleton().createVertexDeclaration(); - vd.vertexDeclaration->addElement(0, 0, VET_FLOAT3, VES_POSITION); - HardwareVertexBufferSharedPtr vbuf = HardwareBufferManager::getSingleton().createVertexBuffer(sizeof(float)*3, 4, HardwareBuffer::HBU_STATIC,true); - vd.vertexBufferBinding->setBinding(0, vbuf); - float* pFloat = static_cast(vbuf->lock(HardwareBuffer::HBL_DISCARD)); - *pFloat++ = 0 ; *pFloat++ = 0 ; *pFloat++ = 0 ; - *pFloat++ = 50 ; *pFloat++ = 0 ; *pFloat++ = 0 ; - *pFloat++ = 0 ; *pFloat++ = 100; *pFloat++ = 0 ; - *pFloat++ = 0 ; *pFloat++ = 0 ; *pFloat++ = -50; - vbuf->unlock(); - - id.indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, 12, HardwareBuffer::HBU_STATIC, true); - id.indexCount = 12; - id.indexStart = 0; - unsigned short* pIdx = static_cast(id.indexBuffer->lock(HardwareBuffer::HBL_DISCARD)); - *pIdx++ = 0; *pIdx++ = 1; *pIdx++ = 2; - *pIdx++ = 0; *pIdx++ = 2; *pIdx++ = 3; - *pIdx++ = 1; *pIdx++ = 3; *pIdx++ = 2; - *pIdx++ = 0; *pIdx++ = 3; *pIdx++ = 1; - id.indexBuffer->unlock(); - - EdgeListBuilder edgeBuilder; - edgeBuilder.addVertexData(&vd); - edgeBuilder.addIndexData(&id); - EdgeData* edgeData = edgeBuilder.build(); - - // Should be only one group, since only one vertex buffer - EXPECT_TRUE(edgeData->edgeGroups.size() == 1); - // 4 triangles - EXPECT_TRUE(edgeData->triangles.size() == 4); - EdgeData::EdgeGroup& eg = edgeData->edgeGroups[0]; - // 6 edges - EXPECT_TRUE(eg.edges.size() == 6); - - delete edgeData; -} -//-------------------------------------------------------------------------- -TEST_F(EdgeBuilderTests,MultiIndexBufSingleVertexBuf) -{ - /* This tests the edge builders ability to find shared edges when there are - multiple index sets (submeshes) using a single vertex buffer. - */ - VertexData vd; - IndexData id[4]; - - // Test pyramid - vd.vertexCount = 4; - vd.vertexStart = 0; - vd.vertexDeclaration = HardwareBufferManager::getSingleton().createVertexDeclaration(); - vd.vertexDeclaration->addElement(0, 0, VET_FLOAT3, VES_POSITION); - HardwareVertexBufferSharedPtr vbuf = HardwareBufferManager::getSingleton().createVertexBuffer(sizeof(float)*3, 4, HardwareBuffer::HBU_STATIC,true); - vd.vertexBufferBinding->setBinding(0, vbuf); - float* pFloat = static_cast(vbuf->lock(HardwareBuffer::HBL_DISCARD)); - *pFloat++ = 0 ; *pFloat++ = 0 ; *pFloat++ = 0 ; - *pFloat++ = 50 ; *pFloat++ = 0 ; *pFloat++ = 0 ; - *pFloat++ = 0 ; *pFloat++ = 100; *pFloat++ = 0 ; - *pFloat++ = 0 ; *pFloat++ = 0 ; *pFloat++ = -50; - vbuf->unlock(); - - id[0].indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, 3, HardwareBuffer::HBU_STATIC, true); - id[0].indexCount = 3; - id[0].indexStart = 0; - unsigned short* pIdx = static_cast(id[0].indexBuffer->lock(HardwareBuffer::HBL_DISCARD)); - *pIdx++ = 0; *pIdx++ = 1; *pIdx++ = 2; - id[0].indexBuffer->unlock(); - - id[1].indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, 3, HardwareBuffer::HBU_STATIC, true); - id[1].indexCount = 3; - id[1].indexStart = 0; - pIdx = static_cast(id[1].indexBuffer->lock(HardwareBuffer::HBL_DISCARD)); - *pIdx++ = 0; *pIdx++ = 2; *pIdx++ = 3; - id[1].indexBuffer->unlock(); - - id[2].indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, 3, HardwareBuffer::HBU_STATIC, true); - id[2].indexCount = 3; - id[2].indexStart = 0; - pIdx = static_cast(id[2].indexBuffer->lock(HardwareBuffer::HBL_DISCARD)); - *pIdx++ = 1; *pIdx++ = 3; *pIdx++ = 2; - id[2].indexBuffer->unlock(); - - id[3].indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, 3, HardwareBuffer::HBU_STATIC, true); - id[3].indexCount = 3; - id[3].indexStart = 0; - pIdx = static_cast(id[3].indexBuffer->lock(HardwareBuffer::HBL_DISCARD)); - *pIdx++ = 0; *pIdx++ = 3; *pIdx++ = 1; - id[3].indexBuffer->unlock(); - - EdgeListBuilder edgeBuilder; - edgeBuilder.addVertexData(&vd); - edgeBuilder.addIndexData(&id[0]); - edgeBuilder.addIndexData(&id[1]); - edgeBuilder.addIndexData(&id[2]); - edgeBuilder.addIndexData(&id[3]); - EdgeData* edgeData = edgeBuilder.build(); - - // Should be only one group, since only one vertex buffer - EXPECT_TRUE(edgeData->edgeGroups.size() == 1); - // 4 triangles - EXPECT_TRUE(edgeData->triangles.size() == 4); - EdgeData::EdgeGroup& eg = edgeData->edgeGroups[0]; - // 6 edges - EXPECT_TRUE(eg.edges.size() == 6); - - delete edgeData; -} -//-------------------------------------------------------------------------- -TEST_F(EdgeBuilderTests,MultiIndexBufMultiVertexBuf) -{ - /* This tests the edge builders ability to find shared edges when there are - both multiple index sets (submeshes) each using a different vertex buffer - (not using shared geometry). - */ - - VertexData vd[4]; - IndexData id[4]; - - // Test pyramid - vd[0].vertexCount = 3; - vd[0].vertexStart = 0; - vd[0].vertexDeclaration = HardwareBufferManager::getSingleton().createVertexDeclaration(); - vd[0].vertexDeclaration->addElement(0, 0, VET_FLOAT3, VES_POSITION); - HardwareVertexBufferSharedPtr vbuf = HardwareBufferManager::getSingleton().createVertexBuffer(sizeof(float)*3, 3, HardwareBuffer::HBU_STATIC,true); - vd[0].vertexBufferBinding->setBinding(0, vbuf); - float* pFloat = static_cast(vbuf->lock(HardwareBuffer::HBL_DISCARD)); - *pFloat++ = 0 ; *pFloat++ = 0 ; *pFloat++ = 0 ; - *pFloat++ = 50 ; *pFloat++ = 0 ; *pFloat++ = 0 ; - *pFloat++ = 0 ; *pFloat++ = 100; *pFloat++ = 0 ; - vbuf->unlock(); - - vd[1].vertexCount = 3; - vd[1].vertexStart = 0; - vd[1].vertexDeclaration = HardwareBufferManager::getSingleton().createVertexDeclaration(); - vd[1].vertexDeclaration->addElement(0, 0, VET_FLOAT3, VES_POSITION); - vbuf = HardwareBufferManager::getSingleton().createVertexBuffer(sizeof(float)*3, 3, HardwareBuffer::HBU_STATIC,true); - vd[1].vertexBufferBinding->setBinding(0, vbuf); - pFloat = static_cast(vbuf->lock(HardwareBuffer::HBL_DISCARD)); - *pFloat++ = 0 ; *pFloat++ = 0 ; *pFloat++ = 0 ; - *pFloat++ = 0 ; *pFloat++ = 100; *pFloat++ = 0 ; - *pFloat++ = 0 ; *pFloat++ = 0 ; *pFloat++ = -50; - vbuf->unlock(); - - vd[2].vertexCount = 3; - vd[2].vertexStart = 0; - vd[2].vertexDeclaration = HardwareBufferManager::getSingleton().createVertexDeclaration(); - vd[2].vertexDeclaration->addElement(0, 0, VET_FLOAT3, VES_POSITION); - vbuf = HardwareBufferManager::getSingleton().createVertexBuffer(sizeof(float)*3, 3, HardwareBuffer::HBU_STATIC,true); - vd[2].vertexBufferBinding->setBinding(0, vbuf); - pFloat = static_cast(vbuf->lock(HardwareBuffer::HBL_DISCARD)); - *pFloat++ = 50 ; *pFloat++ = 0 ; *pFloat++ = 0 ; - *pFloat++ = 0 ; *pFloat++ = 100; *pFloat++ = 0 ; - *pFloat++ = 0 ; *pFloat++ = 0 ; *pFloat++ = -50; - vbuf->unlock(); - - vd[3].vertexCount = 3; - vd[3].vertexStart = 0; - vd[3].vertexDeclaration = HardwareBufferManager::getSingleton().createVertexDeclaration(); - vd[3].vertexDeclaration->addElement(0, 0, VET_FLOAT3, VES_POSITION); - vbuf = HardwareBufferManager::getSingleton().createVertexBuffer(sizeof(float)*3, 3, HardwareBuffer::HBU_STATIC,true); - vd[3].vertexBufferBinding->setBinding(0, vbuf); - pFloat = static_cast(vbuf->lock(HardwareBuffer::HBL_DISCARD)); - *pFloat++ = 0 ; *pFloat++ = 0 ; *pFloat++ = 0 ; - *pFloat++ = 50 ; *pFloat++ = 0 ; *pFloat++ = 0 ; - *pFloat++ = 0 ; *pFloat++ = 0 ; *pFloat++ = -50; - vbuf->unlock(); - - id[0].indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, 3, HardwareBuffer::HBU_STATIC, true); - id[0].indexCount = 3; - id[0].indexStart = 0; - unsigned short* pIdx = static_cast(id[0].indexBuffer->lock(HardwareBuffer::HBL_DISCARD)); - *pIdx++ = 0; *pIdx++ = 1; *pIdx++ = 2; - id[0].indexBuffer->unlock(); - - id[1].indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, 3, HardwareBuffer::HBU_STATIC, true); - id[1].indexCount = 3; - id[1].indexStart = 0; - pIdx = static_cast(id[1].indexBuffer->lock(HardwareBuffer::HBL_DISCARD)); - *pIdx++ = 0; *pIdx++ = 1; *pIdx++ = 2; - id[1].indexBuffer->unlock(); - - id[2].indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, 3, HardwareBuffer::HBU_STATIC, true); - id[2].indexCount = 3; - id[2].indexStart = 0; - pIdx = static_cast(id[2].indexBuffer->lock(HardwareBuffer::HBL_DISCARD)); - *pIdx++ = 0; *pIdx++ = 2; *pIdx++ = 1; - id[2].indexBuffer->unlock(); - - id[3].indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, 3, HardwareBuffer::HBU_STATIC, true); - id[3].indexCount = 3; - id[3].indexStart = 0; - pIdx = static_cast(id[3].indexBuffer->lock(HardwareBuffer::HBL_DISCARD)); - *pIdx++ = 0; *pIdx++ = 2; *pIdx++ = 1; - id[3].indexBuffer->unlock(); - - EdgeListBuilder edgeBuilder; - edgeBuilder.addVertexData(&vd[0]); - edgeBuilder.addVertexData(&vd[1]); - edgeBuilder.addVertexData(&vd[2]); - edgeBuilder.addVertexData(&vd[3]); - edgeBuilder.addIndexData(&id[0], 0); - edgeBuilder.addIndexData(&id[1], 1); - edgeBuilder.addIndexData(&id[2], 2); - edgeBuilder.addIndexData(&id[3], 3); - EdgeData* edgeData = edgeBuilder.build(); - - // Should be 4 groups - EXPECT_TRUE(edgeData->edgeGroups.size() == 4); - // 4 triangles - EXPECT_TRUE(edgeData->triangles.size() == 4); - // 6 edges in total - EXPECT_TRUE( - (edgeData->edgeGroups[0].edges.size() + - edgeData->edgeGroups[1].edges.size() + - edgeData->edgeGroups[2].edges.size() + - edgeData->edgeGroups[3].edges.size()) - == 6); - - delete edgeData; -} -//-------------------------------------------------------------------------- diff --git a/Tests/OgreMain/src/FileSystemArchiveTests.cpp b/Tests/OgreMain/src/FileSystemArchiveTests.cpp deleted file mode 100644 index c0af024a449..00000000000 --- a/Tests/OgreMain/src/FileSystemArchiveTests.cpp +++ /dev/null @@ -1,314 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "FileSystemArchiveTests.h" -#include "OgreFileSystem.h" -#include "OgreException.h" -#include "OgreCommon.h" -#include "OgreConfigFile.h" -#include "OgreFileSystemLayer.h" - - -namespace Ogre { -static bool operator<(const FileInfo& a, const FileInfo& b) { - return a.basename < b.basename; -} -} -// Register the test suite - -//-------------------------------------------------------------------------- -void FileSystemArchiveTests::SetUp() -{ - mFileSizeRoot1 = 125; - mFileSizeRoot2 = 150; - - Ogre::ConfigFile cf; - cf.load(Ogre::FileSystemLayer(OGRE_VERSION_NAME).getConfigFilePath("resources.cfg")); - mTestPath = cf.getSettings("Tests").begin()->second+"/misc/ArchiveTest"; - - mArch = mFactory.createInstance(mTestPath, false); - mArch->load(); -} -//-------------------------------------------------------------------------- -void FileSystemArchiveTests::TearDown() -{ - if(mArch) - mFactory.destroyInstance(mArch); -} -//-------------------------------------------------------------------------- -TEST_F(FileSystemArchiveTests,ListNonRecursive) -{ - StringVectorPtr vec = mArch->list(false); - - EXPECT_EQ((unsigned int)2, (unsigned int)vec->size()); - sort(vec->begin(), vec->end()); - EXPECT_EQ(String("rootfile.txt"), vec->at(0)); - EXPECT_EQ(String("rootfile2.txt"), vec->at(1)); - - EXPECT_EQ("rootfile.txt", mArch->open("rootfile.txt")->getName()); -} - -TEST_F(FileSystemArchiveTests,Exists) -{ - EXPECT_FALSE(mArch->exists("")); -} -//-------------------------------------------------------------------------- -TEST_F(FileSystemArchiveTests,ListRecursive) -{ - StringVectorPtr vec = mArch->list(true); - - EXPECT_EQ((size_t)6, vec->size()); - sort(vec->begin(), vec->end()); - EXPECT_EQ(String("level1/materials/scripts/file.material"), vec->at(0)); - EXPECT_EQ(String("level1/materials/scripts/file2.material"), vec->at(1)); - EXPECT_EQ(String("level2/materials/scripts/file3.material"), vec->at(2)); - EXPECT_EQ(String("level2/materials/scripts/file4.material"), vec->at(3)); - EXPECT_EQ(String("rootfile.txt"), vec->at(4)); - EXPECT_EQ(String("rootfile2.txt"), vec->at(5)); -} -//-------------------------------------------------------------------------- -TEST_F(FileSystemArchiveTests,ListFileInfoNonRecursive) -{ - FileInfoListPtr vec = mArch->listFileInfo(false); - - // Only execute size checks, if the values have been set for the current platform - if(mFileSizeRoot1 >0 && mFileSizeRoot2 > 0) - { - EXPECT_EQ((size_t)2, vec->size()); - sort(vec->begin(), vec->end()); - FileInfo& fi1 = vec->at(0); - EXPECT_EQ(String("rootfile.txt"), fi1.filename); - EXPECT_EQ(String("rootfile.txt"), fi1.basename); - EXPECT_EQ(BLANKSTRING, fi1.path); - EXPECT_EQ((size_t)mFileSizeRoot1, fi1.compressedSize); - EXPECT_EQ((size_t)mFileSizeRoot1, fi1.uncompressedSize); - - FileInfo& fi2 = vec->at(1); - EXPECT_EQ(String("rootfile2.txt"), fi2.filename); - EXPECT_EQ(String("rootfile2.txt"), fi2.basename); - EXPECT_EQ(BLANKSTRING, fi2.path); - EXPECT_EQ((size_t)mFileSizeRoot2, fi2.compressedSize); - EXPECT_EQ((size_t)mFileSizeRoot2, fi2.uncompressedSize); - } -} -//-------------------------------------------------------------------------- -TEST_F(FileSystemArchiveTests,ListFileInfoRecursive) -{ - FileInfoListPtr vec = mArch->listFileInfo(true); - sort(vec->begin(), vec->end()); - - // Only execute size checks, if the values have been set for the current platform - if(mFileSizeRoot1 >0 && mFileSizeRoot2 > 0) - { - EXPECT_EQ((size_t)6, vec->size()); - FileInfo& fi1 = vec->at(4); - EXPECT_EQ(String("rootfile.txt"), fi1.filename); - EXPECT_EQ(String("rootfile.txt"), fi1.basename); - EXPECT_EQ(BLANKSTRING, fi1.path); - EXPECT_EQ((size_t)mFileSizeRoot1, fi1.compressedSize); - EXPECT_EQ((size_t)mFileSizeRoot1, fi1.uncompressedSize); - - FileInfo& fi2 = vec->at(5); - EXPECT_EQ(String("rootfile2.txt"), fi2.filename); - EXPECT_EQ(String("rootfile2.txt"), fi2.basename); - EXPECT_EQ(BLANKSTRING, fi2.path); - EXPECT_EQ((size_t)mFileSizeRoot2, fi2.compressedSize); - EXPECT_EQ((size_t)mFileSizeRoot2, fi2.uncompressedSize); - } - - FileInfo& fi3 = vec->at(0); - EXPECT_EQ(String("level1/materials/scripts/file.material"), fi3.filename); - EXPECT_EQ(String("file.material"), fi3.basename); - EXPECT_EQ(String("level1/materials/scripts/"), fi3.path); - EXPECT_EQ((size_t)0, fi3.compressedSize); - EXPECT_EQ((size_t)0, fi3.uncompressedSize); - - FileInfo& fi4 = vec->at(1); - EXPECT_EQ(String("level1/materials/scripts/file2.material"), fi4.filename); - EXPECT_EQ(String("file2.material"), fi4.basename); - EXPECT_EQ(String("level1/materials/scripts/"), fi4.path); - EXPECT_EQ((size_t)0, fi4.compressedSize); - EXPECT_EQ((size_t)0, fi4.uncompressedSize); - - FileInfo& fi5 = vec->at(2); - EXPECT_EQ(String("level2/materials/scripts/file3.material"), fi5.filename); - EXPECT_EQ(String("file3.material"), fi5.basename); - EXPECT_EQ(String("level2/materials/scripts/"), fi5.path); - EXPECT_EQ((size_t)0, fi5.compressedSize); - EXPECT_EQ((size_t)0, fi5.uncompressedSize); - - FileInfo& fi6 = vec->at(3); - EXPECT_EQ(String("level2/materials/scripts/file4.material"), fi6.filename); - EXPECT_EQ(String("file4.material"), fi6.basename); - EXPECT_EQ(String("level2/materials/scripts/"), fi6.path); - EXPECT_EQ((size_t)0, fi6.compressedSize); - EXPECT_EQ((size_t)0, fi6.uncompressedSize); -} -//-------------------------------------------------------------------------- -TEST_F(FileSystemArchiveTests,FindNonRecursive) -{ - StringVectorPtr vec = mArch->find("*.txt", false); - - EXPECT_EQ((size_t)2, vec->size()); - sort(vec->begin(), vec->end()); - EXPECT_EQ(String("rootfile.txt"), vec->at(0)); - EXPECT_EQ(String("rootfile2.txt"), vec->at(1)); -} -//-------------------------------------------------------------------------- -TEST_F(FileSystemArchiveTests,FindRecursive) -{ - StringVectorPtr vec = mArch->find("*.material", true); - - EXPECT_EQ((size_t)4, vec->size()); - sort(vec->begin(), vec->end()); - EXPECT_EQ(String("level1/materials/scripts/file.material"), vec->at(0)); - EXPECT_EQ(String("level1/materials/scripts/file2.material"), vec->at(1)); - EXPECT_EQ(String("level2/materials/scripts/file3.material"), vec->at(2)); - EXPECT_EQ(String("level2/materials/scripts/file4.material"), vec->at(3)); -} -//-------------------------------------------------------------------------- -TEST_F(FileSystemArchiveTests,FindFileInfoNonRecursive) -{ - FileInfoListPtr vec = mArch->findFileInfo("*.txt", false); - - // Only execute size checks, if the values have been set for the current platform - if(mFileSizeRoot1 >0 && mFileSizeRoot2 > 0) - { - EXPECT_EQ((size_t)2, vec->size()); - sort(vec->begin(), vec->end()); - FileInfo& fi1 = vec->at(0); - EXPECT_EQ(String("rootfile.txt"), fi1.filename); - EXPECT_EQ(String("rootfile.txt"), fi1.basename); - EXPECT_EQ(BLANKSTRING, fi1.path); - EXPECT_EQ((size_t)mFileSizeRoot1, fi1.compressedSize); - EXPECT_EQ((size_t)mFileSizeRoot1, fi1.uncompressedSize); - - FileInfo& fi2 = vec->at(1); - EXPECT_EQ(String("rootfile2.txt"), fi2.filename); - EXPECT_EQ(String("rootfile2.txt"), fi2.basename); - EXPECT_EQ(BLANKSTRING, fi2.path); - EXPECT_EQ((size_t)mFileSizeRoot2, fi2.compressedSize); - EXPECT_EQ((size_t)mFileSizeRoot2, fi2.uncompressedSize); - } -} -//-------------------------------------------------------------------------- -TEST_F(FileSystemArchiveTests,FindFileInfoRecursive) -{ - FileInfoListPtr vec = mArch->findFileInfo("*.material", true); - - EXPECT_EQ((size_t)4, vec->size()); - sort(vec->begin(), vec->end()); - - FileInfo& fi3 = vec->at(0); - EXPECT_EQ(String("level1/materials/scripts/file.material"), fi3.filename); - EXPECT_EQ(String("file.material"), fi3.basename); - EXPECT_EQ(String("level1/materials/scripts/"), fi3.path); - EXPECT_EQ((size_t)0, fi3.compressedSize); - EXPECT_EQ((size_t)0, fi3.uncompressedSize); - - FileInfo& fi4 = vec->at(1); - EXPECT_EQ(String("level1/materials/scripts/file2.material"), fi4.filename); - EXPECT_EQ(String("file2.material"), fi4.basename); - EXPECT_EQ(String("level1/materials/scripts/"), fi4.path); - EXPECT_EQ((size_t)0, fi4.compressedSize); - EXPECT_EQ((size_t)0, fi4.uncompressedSize); - - FileInfo& fi5 = vec->at(2); - EXPECT_EQ(String("level2/materials/scripts/file3.material"), fi5.filename); - EXPECT_EQ(String("file3.material"), fi5.basename); - EXPECT_EQ(String("level2/materials/scripts/"), fi5.path); - EXPECT_EQ((size_t)0, fi5.compressedSize); - EXPECT_EQ((size_t)0, fi5.uncompressedSize); - - FileInfo& fi6 = vec->at(3); - EXPECT_EQ(String("level2/materials/scripts/file4.material"), fi6.filename); - EXPECT_EQ(String("file4.material"), fi6.basename); - EXPECT_EQ(String("level2/materials/scripts/"), fi6.path); - EXPECT_EQ((size_t)0, fi6.compressedSize); - EXPECT_EQ((size_t)0, fi6.uncompressedSize); -} -//-------------------------------------------------------------------------- -TEST_F(FileSystemArchiveTests,FileRead) -{ - DataStreamPtr stream = mArch->open("rootfile.txt"); - EXPECT_EQ(String("this is line 1 in file 1"), stream->getLine()); - EXPECT_EQ(String("this is line 2 in file 1"), stream->getLine()); - EXPECT_EQ(String("this is line 3 in file 1"), stream->getLine()); - EXPECT_EQ(String("this is line 4 in file 1"), stream->getLine()); - EXPECT_EQ(String("this is line 5 in file 1"), stream->getLine()); - EXPECT_EQ(BLANKSTRING, stream->getLine()); // blank at end of file - EXPECT_TRUE(stream->eof()); -} -//-------------------------------------------------------------------------- -TEST_F(FileSystemArchiveTests,ReadInterleave) -{ - // Test overlapping reads from same archive - - // File 1 - DataStreamPtr stream1 = mArch->open("rootfile.txt"); - EXPECT_EQ(String("this is line 1 in file 1"), stream1->getLine()); - EXPECT_EQ(String("this is line 2 in file 1"), stream1->getLine()); - - // File 2 - DataStreamPtr stream2 = mArch->open("rootfile2.txt"); - EXPECT_EQ(String("this is line 1 in file 2"), stream2->getLine()); - EXPECT_EQ(String("this is line 2 in file 2"), stream2->getLine()); - EXPECT_EQ(String("this is line 3 in file 2"), stream2->getLine()); - - // File 1 - EXPECT_EQ(String("this is line 3 in file 1"), stream1->getLine()); - EXPECT_EQ(String("this is line 4 in file 1"), stream1->getLine()); - EXPECT_EQ(String("this is line 5 in file 1"), stream1->getLine()); - EXPECT_EQ(BLANKSTRING, stream1->getLine()); // blank at end of file - EXPECT_TRUE(stream1->eof()); - - // File 2 - EXPECT_EQ(String("this is line 4 in file 2"), stream2->getLine()); - EXPECT_EQ(String("this is line 5 in file 2"), stream2->getLine()); - EXPECT_EQ(String("this is line 6 in file 2"), stream2->getLine()); - EXPECT_EQ(BLANKSTRING, stream2->getLine()); // blank at end of file - EXPECT_TRUE(stream2->eof()); -} -//-------------------------------------------------------------------------- -TEST_F(FileSystemArchiveTests,CreateAndRemoveFile) -{ - EXPECT_TRUE(!mArch->isReadOnly()); - - String fileName = "a_test_file.txt"; - DataStreamPtr stream = mArch->create(fileName); - - String testString = "Some text here"; - size_t written = stream->write((const void*)testString.c_str(), testString.size()); - EXPECT_EQ(testString.size(), written); - - stream->close(); - - mArch->remove(fileName); - - EXPECT_TRUE(!mArch->exists(fileName)); -} -//-------------------------------------------------------------------------- diff --git a/Tests/OgreMain/src/General.cpp b/Tests/OgreMain/src/General.cpp deleted file mode 100644 index 9e9b570b0a4..00000000000 --- a/Tests/OgreMain/src/General.cpp +++ /dev/null @@ -1,661 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include - -#include "OgreRoot.h" -#include "OgreSceneNode.h" -#include "OgreEntity.h" -#include "OgreCamera.h" -#include "RootWithoutRenderSystemFixture.h" -#include "OgreStaticPluginLoader.h" - -#include "OgreMaterialSerializer.h" -#include "OgreTechnique.h" -#include "OgrePass.h" -#include "OgreMaterialManager.h" -#include "OgreConfigFile.h" -#include "OgreSTBICodec.h" -#include "OgreHighLevelGpuProgramManager.h" -#include "OgreMeshManager.h" -#include "OgreMesh.h" -#include "OgreSkeletonManager.h" -#include "OgreSkeletonInstance.h" -#include "OgreCompositorManager.h" -#include "OgreTextureManager.h" -#include "OgreFileSystem.h" -#include "OgreArchiveManager.h" - -#include "OgreHighLevelGpuProgram.h" - -#include "OgreKeyFrame.h" - -#include -using std::minstd_rand; - -using namespace Ogre; - -typedef RootWithoutRenderSystemFixture CameraTests; -TEST_F(CameraTests,customProjectionMatrix) -{ - Camera cam("", NULL); - std::vector corners(cam.getWorldSpaceCorners(), cam.getWorldSpaceCorners() + 8); - RealRect extents = cam.getFrustumExtents(); - cam.setCustomProjectionMatrix(true, cam.getProjectionMatrix()); - for(int j = 0; j < 8; j++) { - for(int k = 0; k < 3; k++) { - if(OGRE_DOUBLE_PRECISION == 0) - EXPECT_FLOAT_EQ(corners[j][k], cam.getWorldSpaceCorners()[j][k]); - else - EXPECT_DOUBLE_EQ(corners[j][k], cam.getWorldSpaceCorners()[j][k]); - } - } - - if(OGRE_DOUBLE_PRECISION == 0) { - EXPECT_FLOAT_EQ(extents.bottom, cam.getFrustumExtents().bottom); - EXPECT_FLOAT_EQ(extents.top, cam.getFrustumExtents().top); - EXPECT_FLOAT_EQ(extents.left, cam.getFrustumExtents().left); - EXPECT_FLOAT_EQ(extents.right, cam.getFrustumExtents().right); - } else { - EXPECT_DOUBLE_EQ(extents.bottom, cam.getFrustumExtents().bottom); - EXPECT_DOUBLE_EQ(extents.top, cam.getFrustumExtents().top); - EXPECT_DOUBLE_EQ(extents.left, cam.getFrustumExtents().left); - EXPECT_DOUBLE_EQ(extents.right, cam.getFrustumExtents().right); - } - -} - -TEST(Root,shutdown) -{ -#ifdef OGRE_STATIC_LIB - Root root(""); - OgreBites::StaticPluginLoader mStaticPluginLoader; - mStaticPluginLoader.load(); -#else - Root root; -#endif - root.shutdown(); -} - -TEST(SceneManager, removeAndDestroyAllChildren) -{ - Root root(""); - SceneManager* sm = root.createSceneManager(); - sm->getRootSceneNode()->createChildSceneNode(); - sm->getRootSceneNode()->createChildSceneNode(); - sm->getRootSceneNode()->removeAndDestroyAllChildren(); -} - -struct SceneNodeTest : public RootWithoutRenderSystemFixture { - SceneManager* mSceneMgr; - - void SetUp() override { - RootWithoutRenderSystemFixture::SetUp(); - mSceneMgr = mRoot->createSceneManager(); - } -}; - -TEST_F(SceneNodeTest, detachAllObjects){ - auto sinbad = mSceneMgr->createEntity("sinbad", "Sinbad.mesh"); - auto sinbad2 = mSceneMgr->createEntity("sinbad2", "Sinbad.mesh"); - SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode("parent"); - node->attachObject(sinbad); - node->attachObject(sinbad2); - - auto sinbad3 = mSceneMgr->createEntity("sinbad3", "Sinbad.mesh"); - SceneNode* child = node->createChildSceneNode("child"); - child->attachObject(sinbad3); - node->destroyAllObjects(); - EXPECT_FALSE(mSceneMgr->hasEntity("sinbad")); - EXPECT_FALSE(mSceneMgr->hasEntity("sinbad2")); - EXPECT_TRUE(mSceneMgr->hasEntity("sinbad3")); - EXPECT_EQ(node->numAttachedObjects(), 0); - EXPECT_EQ(child->numAttachedObjects(), 1); -} - -TEST_F(SceneNodeTest, destroyAllChildrenAndObjects) -{ - auto sinbad = mSceneMgr->createEntity("sinbad", "Sinbad.mesh"); - SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode("parent"); - node->attachObject(sinbad); - - auto sinbad2 = mSceneMgr->createEntity("sinbad2", "Sinbad.mesh"); - SceneNode* child = node->createChildSceneNode("child"); - child->attachObject(sinbad2); - - auto sinbad3 = mSceneMgr->createEntity("sinbad3", "Sinbad.mesh"); - SceneNode* grandchild = node->createChildSceneNode("grandchild"); - grandchild->attachObject(sinbad3); - - node->destroyAllChildrenAndObjects(); - EXPECT_FALSE(mSceneMgr->hasSceneNode("grandchild")); - EXPECT_FALSE(mSceneMgr->hasEntity("sinbad3")); - EXPECT_FALSE(mSceneMgr->hasSceneNode("child")); - EXPECT_FALSE(mSceneMgr->hasEntity("sinbad2")); - EXPECT_FALSE(mSceneMgr->hasEntity("sinbad")); - EXPECT_TRUE(mSceneMgr->hasSceneNode("parent")); -} - -TEST_F(SceneNodeTest, destroyChildAndObjects) -{ - - auto sinbad = mSceneMgr->createEntity("sinbad", "Sinbad.mesh"); - SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode("parent"); - node->attachObject(sinbad); - - auto sinbad2 = mSceneMgr->createEntity("sinbad2", "Sinbad.mesh"); - SceneNode* child = node->createChildSceneNode("child"); - child->attachObject(sinbad2); - - auto sinbad3 = mSceneMgr->createEntity("sinbad3", "Sinbad.mesh"); - SceneNode* grandchild = child->createChildSceneNode("grandchild"); - grandchild->attachObject(sinbad3); - - node->destroyChildAndObjects("child"); - - EXPECT_FALSE(mSceneMgr->hasSceneNode("grandchild")); - EXPECT_FALSE(mSceneMgr->hasSceneNode("child")); - EXPECT_TRUE(mSceneMgr->hasSceneNode("parent")); - EXPECT_FALSE(mSceneMgr->hasEntity("sinbad2")); - EXPECT_FALSE(mSceneMgr->hasEntity("sinbad3")); - EXPECT_TRUE(mSceneMgr->hasEntity("sinbad")); -} - -static void createRandomEntityClones(Entity* ent, size_t cloneCount, const Vector3& min, - const Vector3& max, SceneManager* mgr) -{ - // we want cross platform consistent sequence - minstd_rand rng; - - for (size_t n = 0; n < cloneCount; ++n) - { - // Create a new node under the root. - SceneNode* node = mgr->createSceneNode(); - // Random translate. - Vector3 nodePos = max - min; - nodePos.x *= double(rng())/rng.max(); - nodePos.y *= double(rng())/rng.max(); - nodePos.z *= double(rng())/rng.max(); - nodePos += min; - node->setPosition(nodePos); - mgr->getRootSceneNode()->addChild(node); - Entity* cloneEnt = ent->clone(StringConverter::toString(n)); - // Attach to new node. - node->attachObject(cloneEnt); - } -} - -struct SceneQueryTest : public RootWithoutRenderSystemFixture { - SceneManager* mSceneMgr; - Camera* mCamera; - SceneNode* mCameraNode; - - void SetUp() override { - RootWithoutRenderSystemFixture::SetUp(); - - mSceneMgr = mRoot->createSceneManager(); - mCamera = mSceneMgr->createCamera("Camera"); - mCameraNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mCameraNode->attachObject(mCamera); - mCameraNode->setPosition(0,0,500); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); - - // Create a set of random balls - Entity* ent = mSceneMgr->createEntity("501", "sphere.mesh", "General"); - - // stick one at the origin so one will always be hit by ray - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); - createRandomEntityClones(ent, 500, Vector3(-2500,-2500,-2500), Vector3(2500,2500,2500), mSceneMgr); - - mSceneMgr->_updateSceneGraph(mCamera); - } -}; - -TEST_F(SceneQueryTest,Intersection) -{ - IntersectionSceneQuery* intersectionQuery = mSceneMgr->createIntersectionQuery(); - - int expected[][2] = { - {0, 391}, {1, 8}, {117, 128}, {118, 171}, {118, 24}, {121, 72}, {121, 95}, - {132, 344}, {14, 227}, {14, 49}, {144, 379}, {151, 271}, {153, 28}, {164, 222}, - {169, 212}, {176, 20}, {179, 271}, {185, 238}, {190, 47}, {193, 481}, {201, 210}, - {205, 404}, {235, 366}, {239, 3}, {250, 492}, {256, 67}, {26, 333}, {260, 487}, - {263, 272}, {265, 319}, {265, 472}, {270, 45}, {284, 329}, {289, 405}, {316, 80}, - {324, 388}, {334, 337}, {336, 436}, {34, 57}, {340, 440}, {342, 41}, {348, 82}, - {35, 478}, {372, 412}, {380, 460}, {398, 92}, {417, 454}, {432, 99}, {448, 79}, - {498, 82}, {72, 77} - }; - - IntersectionSceneQueryResult& results = intersectionQuery->execute(); - EXPECT_EQ(results.movables2movables.size(), sizeof(expected)/sizeof(expected[0])); - - int i = 0; - for (auto & thepair : results.movables2movables) - { - // printf("{%d, %d},", StringConverter::parseInt(thepair.first->getName()), StringConverter::parseInt(thepair.second->getName())); - ASSERT_EQ(expected[i][0], StringConverter::parseInt(thepair.first->getName())); - ASSERT_EQ(expected[i][1], StringConverter::parseInt(thepair.second->getName())); - i++; - } - // printf("\n"); -} - -TEST_F(SceneQueryTest, Ray) { - RaySceneQuery* rayQuery = mSceneMgr->createRayQuery(mCamera->getCameraToViewportRay(0.5, 0.5)); - rayQuery->setSortByDistance(true, 2); - - RaySceneQueryResult& results = rayQuery->execute(); - - ASSERT_EQ("501", results[0].movable->getName()); - ASSERT_EQ("397", results[1].movable->getName()); -} - -TEST(MaterialSerializer, Basic) -{ - Root root; - DefaultTextureManager texMgr; - - String group = "General"; - - auto mat = std::make_shared(nullptr, "Material Name", 0, group); - auto pass = mat->createTechnique()->createPass(); - auto tus = pass->createTextureUnitState(); - tus->setContentType(TextureUnitState::CONTENT_SHADOW); - tus->setName("Test TUS"); - pass->setAmbient(ColourValue::Green); - - pass->createTextureUnitState("TextureName"); - - // export to string - MaterialSerializer ser; - ser.queueForExport(mat); - auto str = ser.getQueuedAsString(); - - // printf("%s\n", str.c_str()); - - // load again - DataStreamPtr stream = std::make_shared("memory.material", &str[0], str.size()); - MaterialManager::getSingleton().parseScript(stream, group); - - auto mat2 = MaterialManager::getSingleton().getByName("Material Name", group); - ASSERT_TRUE(mat2); - EXPECT_EQ(mat2->getTechniques().size(), mat->getTechniques().size()); - EXPECT_EQ(mat2->getTechniques()[0]->getPasses()[0]->getAmbient(), ColourValue::Green); - EXPECT_EQ(mat2->getTechniques()[0]->getPasses()[0]->getTextureUnitState(0)->getName(), - "Test TUS"); - EXPECT_EQ(mat2->getTechniques()[0]->getPasses()[0]->getTextureUnitState("Test TUS")->getContentType(), - TextureUnitState::CONTENT_SHADOW); - EXPECT_EQ(mat2->getTechniques()[0]->getPasses()[0]->getTextureUnitState(1)->getTextureName(), - "TextureName"); -} - -TEST(Image, FlipV) -{ - ResourceGroupManager mgr; - STBIImageCodec::startup(); - ConfigFile cf; - cf.load(FileSystemLayer(OGRE_VERSION_NAME).getConfigFilePath("resources.cfg")); - auto testPath = cf.getSettings("Tests").begin()->second; - - Image ref; - ref.load(Root::openFileStream(testPath+"/decal1vflip.png"), "png"); - - Image img; - img.load(Root::openFileStream(testPath+"/decal1.png"), "png"); - img.flipAroundX(); - - // img.save(testPath+"/decal1vflip.png"); - - STBIImageCodec::shutdown(); - ASSERT_TRUE(!memcmp(img.getData(), ref.getData(), ref.getSize())); -} - -TEST(Image, Resize) -{ - ResourceGroupManager mgr; - STBIImageCodec::startup(); - ConfigFile cf; - cf.load(FileSystemLayer(OGRE_VERSION_NAME).getConfigFilePath("resources.cfg")); - auto testPath = cf.getSettings("Tests").begin()->second; - - Image ref; - ref.load(Root::openFileStream(testPath+"/decal1small.png"), "png"); - - Image img; - img.load(Root::openFileStream(testPath+"/decal1.png"), "png"); - img.resize(128, 128); - - //img.save(testPath+"/decal1small.png"); - - STBIImageCodec::shutdown(); - ASSERT_TRUE(!memcmp(img.getData(), ref.getData(), ref.getSize())); -} - - -TEST(Image, Combine) -{ - ResourceGroupManager mgr; - FileSystemArchiveFactory fs; - ArchiveManager amgr; - amgr.addArchiveFactory(&fs); - STBIImageCodec::startup(); - ConfigFile cf; - cf.load(FileSystemLayer(OGRE_VERSION_NAME).getConfigFilePath("resources.cfg")); - mgr.addResourceLocation(cf.getSettings("General").begin()->second+"/../materials/textures", fs.getType()); - mgr.initialiseAllResourceGroups(); - - auto testPath = cf.getSettings("Tests").begin()->second; - Image ref; - ref.load(Root::openFileStream(testPath+"/rockwall_flare.png"), "png"); - - Image combined; - // pick 2 files that are the same size, alpha texture will be made greyscale - combined.loadTwoImagesAsRGBA("rockwall.tga", "flare.png", RGN_DEFAULT, PF_BYTE_RGBA); - - // combined.save(testPath+"/rockwall_flare.png"); - STBIImageCodec::shutdown(); - ASSERT_TRUE(!memcmp(combined.getData(), ref.getData(), ref.getSize())); -} - -TEST(Image, Compressed) -{ - Root root; - ConfigFile cf; - cf.load(FileSystemLayer(OGRE_VERSION_NAME).getConfigFilePath("resources.cfg")); - auto testPath = cf.getSettings("Tests").begin()->second; - - Image img; -#if OGRE_NO_PVRTC_CODEC == 0 - // 2bpp - img.load(Root::openFileStream(testPath+"/ogreborderUp_pvr2.pvr"), "pvr"); - EXPECT_EQ(img.getFormat(), PF_PVRTC_RGB2); - // 2bpp alpha - img.load(Root::openFileStream(testPath+"/ogreborderUp_pvr2a.pvr"), "pvr"); - EXPECT_EQ(img.getFormat(), PF_PVRTC_RGBA2); - // 4bpp - img.load(Root::openFileStream(testPath+"/ogreborderUp_pvr4.pvr"), "pvr"); - EXPECT_EQ(img.getFormat(), PF_PVRTC_RGB4); - // 4 bpp alpha - img.load(Root::openFileStream(testPath+"/ogreborderUp_pvr4a.pvr"), "pvr"); - EXPECT_EQ(img.getFormat(), PF_PVRTC_RGBA4); -#endif - -#if OGRE_NO_ETC_CODEC == 0 - img.load(Root::openFileStream(testPath+"/Texture.pkm"), "pkm"); - EXPECT_EQ(img.getFormat(), PF_ETC2_RGB8); - img.load(Root::openFileStream(testPath+"/etc2-rgba8.ktx"), "ktx"); - EXPECT_EQ(img.getFormat(), PF_ETC2_RGBA8); -#endif - -#if OGRE_NO_ASTC_CODEC == 0 - img.load(Root::openFileStream(testPath+"/Earth-Color10x6.astc"), "astc"); - EXPECT_EQ(img.getFormat(), PF_ASTC_RGBA_10X6_LDR); -#endif - -#if OGRE_NO_DDS_CODEC == 0 - img.load(Root::openFileStream(testPath+"/ogreborderUp_dxt3.dds"), "dds"); - EXPECT_EQ(img.getFormat(), PF_BYTE_RGBA); // no RenderSystem available, will decompress -#endif -} - -struct UsePreviousResourceLoadingListener : public ResourceLoadingListener -{ - bool resourceCollision(Resource *resource, ResourceManager *resourceManager) override { return false; } -}; - -typedef RootWithoutRenderSystemFixture ResourceLoading; -TEST_F(ResourceLoading, CollsionUseExisting) -{ - UsePreviousResourceLoadingListener listener; - ResourceGroupManager::getSingleton().setLoadingListener(&listener); - - MaterialPtr mat = MaterialManager::getSingleton().create("Collision", "Tests"); - EXPECT_TRUE(mat); - EXPECT_FALSE(MaterialManager::getSingleton().create("Collision", "Tests")); - EXPECT_FALSE(mat->clone("Collision")); - - MeshPtr mesh = MeshManager::getSingleton().create("Collision", "Tests"); - EXPECT_TRUE(mesh); - EXPECT_FALSE(MeshManager::getSingleton().create("Collision", "Tests")); - EXPECT_FALSE(mesh->clone("Collision")); - - EXPECT_TRUE(SkeletonManager::getSingleton().create("Collision", "Tests")); - EXPECT_FALSE(SkeletonManager::getSingleton().create("Collision", "Tests")); - - EXPECT_TRUE(CompositorManager::getSingleton().create("Collision", "Tests")); - EXPECT_FALSE(CompositorManager::getSingleton().create("Collision", "Tests")); - - EXPECT_TRUE(HighLevelGpuProgramManager::getSingleton().createProgram( - "Collision", "Tests", "null", GPT_VERTEX_PROGRAM)); - EXPECT_FALSE(HighLevelGpuProgramManager::getSingleton().createProgram( - "Collision", "Tests", "null", GPT_VERTEX_PROGRAM)); -} - -struct DeletePreviousResourceLoadingListener : public ResourceLoadingListener -{ - bool resourceCollision(Resource* resource, ResourceManager* resourceManager) override - { - resourceManager->remove(resource->getName(), resource->getGroup()); - return true; - } -}; - -TEST_F(ResourceLoading, CollsionDeleteExisting) -{ - DeletePreviousResourceLoadingListener listener; - ResourceGroupManager::getSingleton().setLoadingListener(&listener); - ResourceGroupManager::getSingleton().createResourceGroup("EmptyGroup", false); - - MaterialPtr mat = MaterialManager::getSingleton().create("Collision", "EmptyGroup"); - EXPECT_TRUE(mat); - EXPECT_TRUE(MaterialManager::getSingleton().create("Collision", "EmptyGroup")); - EXPECT_TRUE(mat->clone("Collision")); -} - -typedef RootWithoutRenderSystemFixture TextureTests; -TEST_F(TextureTests, Blank) -{ - auto mat = std::make_shared(nullptr, "Material Name", 0, "Group"); - auto tus = mat->createTechnique()->createPass()->createTextureUnitState(); - - EXPECT_EQ(tus->isBlank(), true); - EXPECT_EQ(tus->getTextureName(), ""); - EXPECT_EQ(tus->getTextureType(), TEX_TYPE_2D); - EXPECT_EQ(tus->getNumMipmaps(), MIP_DEFAULT); - EXPECT_EQ(tus->getDesiredFormat(), PF_UNKNOWN); - EXPECT_EQ(tus->getFrameTextureName(0), ""); - EXPECT_EQ(tus->getGamma(), 1.0f); - EXPECT_EQ(tus->isHardwareGammaEnabled(), false); -} - -TEST(GpuSharedParameters, align) -{ - Root root(""); - GpuSharedParameters params("dummy"); - - // trivial case - params.addConstantDefinition("a", GCT_FLOAT1); - EXPECT_EQ(params.getConstantDefinition("a").logicalIndex, 0); - - // 16 byte alignment - params.addConstantDefinition("b", GCT_FLOAT4); - EXPECT_EQ(params.getConstantDefinition("b").logicalIndex, 16); - - // break alignment again - params.addConstantDefinition("c", GCT_FLOAT1); - EXPECT_EQ(params.getConstantDefinition("c").logicalIndex, 32); - - // 16 byte alignment - params.addConstantDefinition("d", GCT_MATRIX_4X4); - EXPECT_EQ(params.getConstantDefinition("d").logicalIndex, 48); -} - -typedef RootWithoutRenderSystemFixture HighLevelGpuProgramTest; -TEST_F(HighLevelGpuProgramTest, resolveIncludes) -{ - auto mat = MaterialManager::getSingleton().create("Dummy", RGN_DEFAULT); - - auto& rgm = ResourceGroupManager::getSingleton(); - rgm.addResourceLocation(".", "FileSystem", RGN_DEFAULT, false, false); - - // recursive inclusion - String bar = "World"; - rgm.createResource("bar.cg", RGN_DEFAULT)->write(bar.c_str(), bar.size()); - String foo = "Hello\n#include \n"; - rgm.createResource("foo.cg", RGN_DEFAULT)->write(foo.c_str(), foo.size()); - const char* src = "#include "; - - String res = HighLevelGpuProgram::_resolveIncludes(src, mat.get(), "main.cg", true); - rgm.deleteResource("foo.cg", RGN_DEFAULT); - rgm.deleteResource("bar.cg", RGN_DEFAULT); - - String ref = "#line 1 \"foo.cg\"\n" - "Hello\n" - "#line 1 \"bar.cg\"\n" - "World\n" - "#line 3 \"foo.cg\""; - - ASSERT_EQ(res.substr(0, ref.size()), ref); -} - -TEST(Math, TriangleRayIntersection) -{ - Vector3 tri[3] = {{-1, 0, 0}, {1, 0, 0}, {0, 1, 0}}; - auto ray = Ray({0, 0.5, 1}, {0, 0, -1}); - - EXPECT_TRUE(Math::intersects(ray, tri[0], tri[1], tri[2], true, true).first); - EXPECT_TRUE(Math::intersects(ray, tri[0], tri[1], tri[2], true, false).first); - EXPECT_FALSE(Math::intersects(ray, tri[0], tri[1], tri[2], false, true).first); - EXPECT_FALSE(Math::intersects(ray, tri[0], tri[1], tri[2], false, false).first); - - ray = Ray({0, 0.5, -1}, {0, 0, 1}); - - EXPECT_TRUE(Math::intersects(ray, tri[0], tri[1], tri[2], true, true).first); - EXPECT_FALSE(Math::intersects(ray, tri[0], tri[1], tri[2], true, false).first); - EXPECT_TRUE(Math::intersects(ray, tri[0], tri[1], tri[2], false, true).first); - EXPECT_FALSE(Math::intersects(ray, tri[0], tri[1], tri[2], false, false).first); -} - -typedef RootWithoutRenderSystemFixture SkeletonTests; -TEST_F(SkeletonTests, linkedSkeletonAnimationSource) -{ - auto sceneMgr = mRoot->createSceneManager(); - auto entity = sceneMgr->createEntity("jaiqua.mesh"); - entity->getSkeleton()->addLinkedSkeletonAnimationSource("ninja.skeleton"); - entity->refreshAvailableAnimationState(); - EXPECT_TRUE(entity->getAnimationState("Stealth")); // animation from ninja.sekeleton -} - -TEST(MaterialLoading, LateShadowCaster) -{ - Root root(""); - auto tech = MaterialManager::getSingleton().create("Material", RGN_DEFAULT)->createTechnique(); - tech->setShadowCasterMaterial("Caster"); - EXPECT_FALSE(tech->getShadowCasterMaterial()); - - MaterialManager::getSingleton().create("Caster", RGN_DEFAULT); - - // force call _load() due to missing rendersystem - tech->_load(); - - EXPECT_TRUE(tech->getShadowCasterMaterial()); -} - -TEST(Light, AnimableValue) -{ - Light l; - - l.setDiffuseColour(0, 0, 0); - auto diffuseColour = l.createAnimableValue("diffuseColour"); - diffuseColour->applyDeltaValue(ColourValue(1, 2, 3, 0)); - EXPECT_EQ(l.getDiffuseColour(), ColourValue(1, 2, 3)); - - l.setSpecularColour(0, 0, 0); - auto specularColour = l.createAnimableValue("specularColour"); - specularColour->applyDeltaValue(ColourValue(1, 2, 3, 0)); - EXPECT_EQ(l.getSpecularColour(), ColourValue(1, 2, 3)); - - l.setAttenuation(0, 0, 0, 0); - auto attenuation = l.createAnimableValue("attenuation"); - attenuation->applyDeltaValue(Vector4(1, 2, 3, 4)); - EXPECT_EQ(l.getAttenuation(), Vector4f(1, 2, 3, 4)); - - l.setSpotlightInnerAngle(Radian(0)); - auto spotlightInner = l.createAnimableValue("spotlightInner"); - spotlightInner->applyDeltaValue(Radian(1)); - EXPECT_EQ(l.getSpotlightInnerAngle(), Radian(1)); - - l.setSpotlightOuterAngle(Radian(0)); - auto spotlightOuter = l.createAnimableValue("spotlightOuter"); - spotlightOuter->applyDeltaValue(Radian(1)); - EXPECT_EQ(l.getSpotlightOuterAngle(), Radian(1)); - - l.setSpotlightFalloff(0); - auto spotlightFalloff = l.createAnimableValue("spotlightFalloff"); - spotlightFalloff->applyDeltaValue(Real(1)); - EXPECT_EQ(l.getSpotlightFalloff(), 1); -} - -TEST(Light, AnimationTrack) -{ - Light l; - l.setDiffuseColour(0, 0, 0); - l.setAttenuation(0, 0, 0, 0); - - Animation anim("test", 1.0); - auto diffuse = anim.createNumericTrack(0, l.createAnimableValue("diffuseColour")); - diffuse->createNumericKeyFrame(0)->setValue(ColourValue(1, 2, 3, 0)); - diffuse->createNumericKeyFrame(1)->setValue(ColourValue(2, 4, 6, 0)); - - diffuse->apply(0.5); - - EXPECT_EQ(l.getDiffuseColour(), ColourValue(1.5, 3, 4.5)); - - auto attenuation = anim.createNumericTrack(1, l.createAnimableValue("attenuation")); - attenuation->createNumericKeyFrame(0)->setValue(Vector4(1, 2, 3, 4)); - attenuation->createNumericKeyFrame(1)->setValue(Vector4(2, 4, 6, 8)); - - attenuation->apply(0.5); - EXPECT_EQ(l.getAttenuation(), Vector4f(1.5, 3, 4.5, 6)); -} - -TEST(GpuProgramParams, Variability) -{ - auto constants = std::make_shared(); - constants->map["parameter"] = GpuConstantDefinition(); - constants->map["parameter"].constType = GCT_MATRIX_4X4; - - GpuProgramParameters params; - params._setNamedConstants(constants); - params.setNamedAutoConstant("parameter", GpuProgramParameters::ACT_WORLD_MATRIX); - - GpuProgramParameters params2; - params2._setNamedConstants(constants); - params2.clearNamedAutoConstant("parameter"); - - EXPECT_EQ(params.getConstantDefinition("parameter").variability, GPV_PER_OBJECT); -} diff --git a/Tests/OgreMain/src/InstancingTests.cpp b/Tests/OgreMain/src/InstancingTests.cpp deleted file mode 100644 index 4074ae7acc8..00000000000 --- a/Tests/OgreMain/src/InstancingTests.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "Ogre.h" -#include "OgreInstancedEntity.h" -#include "OgreInstanceBatchShader.h" -#include "RootWithoutRenderSystemFixture.h" - -using namespace Ogre; - -typedef RootWithoutRenderSystemFixture Instancing; - -TEST_F(Instancing, Bounds) { - SceneManager* sceneMgr = mRoot->createSceneManager(); - Entity* entity = sceneMgr->createEntity("robot.mesh"); - - MeshPtr mesh = entity->getMesh(); - InstanceBatchShader batch(NULL, mesh, entity->getSubEntity(0)->getMaterial(), 1, NULL, ""); - InstancedEntity instanced_entity(&batch, 0); - - SceneNode* node = sceneMgr->createSceneNode(); - node->attachObject(&instanced_entity); - node->attachObject(entity); - node->translate(Vector3::UNIT_X); - node->setScale(Vector3(2, 2, 2)); - - EXPECT_EQ(instanced_entity.getBoundingBox(), entity->getBoundingBox()); - EXPECT_EQ(instanced_entity.getBoundingRadius(), entity->getBoundingRadius()); -} - - - diff --git a/Tests/OgreMain/src/MeshSerializerTests.cpp b/Tests/OgreMain/src/MeshSerializerTests.cpp deleted file mode 100644 index 51f6151adfc..00000000000 --- a/Tests/OgreMain/src/MeshSerializerTests.cpp +++ /dev/null @@ -1,670 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "MeshSerializerTests.h" -#include "OgreDefaultHardwareBufferManager.h" -#include "OgreVertexIndexData.h" -#include "OgreEdgeListBuilder.h" -#include "OgreMesh.h" -#include "OgreMeshManager.h" -#include "OgreSubMesh.h" -#include "OgreMeshSerializer.h" -#include "OgreRoot.h" -#include "OgreException.h" -#include "OgreArchive.h" -#include "OgreArchiveManager.h" -#include "OgreFileSystem.h" -#include "OgreConfigFile.h" -#include "OgreSkeletonManager.h" -#include "OgreSkeletonSerializer.h" -#include "OgreDistanceLodStrategy.h" -#include "OgreMaterialManager.h" -#include "OgreLodStrategyManager.h" -#include "OgreSkeleton.h" -#include "OgreKeyFrame.h" - -#include - -//#define I_HAVE_LOT_OF_FREE_TIME - -// To run XML test, you need to symlink all files (except main.cpp) from XMLConverter tool to the Test_Ogre component! -// You also need to set TIXML_USE_STL macro globally. -// #define OGRE_TEST_XMLSERIALIZER - -#ifdef OGRE_TEST_XMLSERIALIZER -// #define TIXML_USE_STL -#include "OgreXMLMeshSerializer.h" -#endif - -#ifdef OGRE_BUILD_COMPONENT_MESHLODGENERATOR -#include "OgreMeshLodGenerator.h" -#include "OgreLodConfig.h" -#endif - -// Register the test suite - -//-------------------------------------------------------------------------- -void MeshSerializerTests::SetUp() -{ - mErrorFactor = 0.05; - - mFSLayer = OGRE_NEW_T(Ogre::FileSystemLayer, Ogre::MEMCATEGORY_GENERAL)(OGRE_VERSION_NAME); - - OGRE_NEW ResourceGroupManager(); - OGRE_NEW LodStrategyManager(); - OGRE_NEW DefaultHardwareBufferManager(); - OGRE_NEW MeshManager(); - OGRE_NEW SkeletonManager(); - ArchiveManager* archiveMgr = OGRE_NEW ArchiveManager(); - archiveMgr->addArchiveFactory(OGRE_NEW FileSystemArchiveFactory()); - - MaterialManager* matMgr = OGRE_NEW MaterialManager(); - matMgr->initialise(); - - // Load resource paths from config file - ConfigFile cf; - String resourcesPath = mFSLayer->getConfigFilePath("resources.cfg"); - - // Go through all sections & settings in the file - cf.load(resourcesPath); - String secName, typeName, archName; - - ConfigFile::SettingsBySection_::const_iterator seci; - for(seci = cf.getSettingsBySection().begin(); seci != cf.getSettingsBySection().end(); ++seci) { - secName = seci->first; - const ConfigFile::SettingsMultiMap& settings = seci->second; - ConfigFile::SettingsMultiMap::const_iterator i; - for (i = settings.begin(); i != settings.end(); ++i) { - typeName = i->first; - archName = i->second; - if (typeName == "FileSystem") { - ResourceGroupManager::getSingleton().addResourceLocation( - archName, typeName, secName); - } - } - } - - mMesh = MeshManager::getSingleton().load("facial.mesh", "General"); - - getResourceFullPath(mMesh, mMeshFullPath); - if (!copyFile(mMeshFullPath + ".bak", mMeshFullPath)) { - // If there is no backup, create one. - copyFile(mMeshFullPath, mMeshFullPath + ".bak"); - } - mSkeletonFullPath = ""; - mSkeleton = static_pointer_cast(SkeletonManager::getSingleton().load("jaiqua.skeleton", "General")); - getResourceFullPath(mSkeleton, mSkeletonFullPath); - if (!copyFile(mSkeletonFullPath + ".bak", mSkeletonFullPath)) { - // If there is no backup, create one. - copyFile(mSkeletonFullPath, mSkeletonFullPath + ".bak"); - } - - mMesh->reload(); - -#ifdef OGRE_BUILD_COMPONENT_MESHLODGENERATOR - { - MeshLodGenerator().generateAutoconfiguredLodLevels(mMesh); - } -#endif /* ifdef OGRE_BUILD_COMPONENT_MESHLODGENERATOR */ - - mOrigMesh = mMesh->clone(mMesh->getName() + ".orig.mesh", mMesh->getGroup()); -} -//-------------------------------------------------------------------------- -void MeshSerializerTests::TearDown() -{ - // Copy back original file. - if (!mMeshFullPath.empty()) { - copyFile(mMeshFullPath + ".bak", mMeshFullPath); - } - if (!mSkeletonFullPath.empty()) { - copyFile(mSkeletonFullPath + ".bak", mSkeletonFullPath); - } - if (mMesh) { - mMesh->unload(); - mMesh.reset(); - } - if (mOrigMesh) { - mOrigMesh->unload(); - mOrigMesh.reset(); - } - if (mSkeleton) { - mSkeleton->unload(); - mSkeleton.reset(); - } - - OGRE_DELETE MeshManager::getSingletonPtr(); - OGRE_DELETE SkeletonManager::getSingletonPtr(); - OGRE_DELETE DefaultHardwareBufferManager::getSingletonPtr(); - OGRE_DELETE ArchiveManager::getSingletonPtr(); - OGRE_DELETE MaterialManager::getSingletonPtr(); - OGRE_DELETE LodStrategyManager::getSingletonPtr(); - OGRE_DELETE ResourceGroupManager::getSingletonPtr(); - OGRE_DELETE_T(mFSLayer, FileSystemLayer, Ogre::MEMCATEGORY_GENERAL); -} -//-------------------------------------------------------------------------- -TEST_F(MeshSerializerTests,Mesh_clone) -{ - MeshPtr cloneMesh = mMesh->clone(mMesh->getName() + ".clone.mesh", mMesh->getGroup()); - assertMeshClone(mMesh.get(), cloneMesh.get()); -} -//-------------------------------------------------------------------------- -void MeshSerializerTests::testMesh(MeshVersion version) -{ - MeshSerializer serializer; - serializer.exportMesh(mOrigMesh.get(), mMeshFullPath, version); - mMesh->reload(); - assertMeshClone(mOrigMesh.get(), mMesh.get(), version); -} -//-------------------------------------------------------------------------- -TEST_F(MeshSerializerTests,Skeleton_Version_1_8) -{ - if (mSkeleton) { - SkeletonSerializer skeletonSerializer; - skeletonSerializer.exportSkeleton(mSkeleton.get(), mSkeletonFullPath, SKELETON_VERSION_1_8); - mSkeleton->reload(); - } -} -//-------------------------------------------------------------------------- -TEST_F(MeshSerializerTests,Skeleton_Version_1_0) -{ - if (mSkeleton) { - SkeletonSerializer skeletonSerializer; - skeletonSerializer.exportSkeleton(mSkeleton.get(), mSkeletonFullPath, SKELETON_VERSION_1_0); - mSkeleton->reload(); - } -} -//-------------------------------------------------------------------------- -TEST_F(MeshSerializerTests,Mesh_Version_1_10) -{ - testMesh(MESH_VERSION_LATEST); -} -//-------------------------------------------------------------------------- -TEST_F(MeshSerializerTests,Mesh_Version_1_8) -{ - testMesh(MESH_VERSION_1_8); -} -//-------------------------------------------------------------------------- -TEST_F(MeshSerializerTests,Mesh_Version_1_41) -{ - testMesh(MESH_VERSION_1_7); -} -//-------------------------------------------------------------------------- -TEST_F(MeshSerializerTests,Mesh_Version_1_4) -{ - testMesh(MESH_VERSION_1_4); -} -//-------------------------------------------------------------------------- -TEST_F(MeshSerializerTests,Mesh_Version_1_3) -{ - testMesh(MESH_VERSION_1_0); -} -//-------------------------------------------------------------------------- -#ifdef I_HAVE_LOT_OF_FREE_TIME -TEST_F(MeshSerializerTests,Mesh_Version_1_2) -{ - // My sandboxing test. Takes a long time to complete! - // Runs on all meshes and exports all to every LoD version. - char* groups [] = { "Popular", "General", "Tests" }; - for (int i = 0; i < 3; i++) { - StringVectorPtr meshes = ResourceGroupManager::getSingleton().findResourceNames(groups[i], "*.mesh"); - StringVector::iterator it, itEnd; - it = meshes->begin(); - itEnd = meshes->end(); - for (; it != itEnd; it++) { - try { - mMesh = MeshManager::getSingleton().load(*it, groups[i]); - } - catch(std::exception e) - { - // OutputDebugStringA(e.what()); - } - getResourceFullPath(mMesh, mMeshFullPath); - if (!copyFile(mMeshFullPath + ".bak", mMeshFullPath)) { - // If there is no backup, create one. - copyFile(mMeshFullPath, mMeshFullPath + ".bak"); - } - mOrigMesh = mMesh->clone(mMesh->getName() + ".orig.mesh", mMesh->getGroup()); - testMesh_XML(); - testMesh(MESH_VERSION_1_10); - testMesh(MESH_VERSION_1_8); - testMesh(MESH_VERSION_1_7); - testMesh(MESH_VERSION_1_4); - testMesh(MESH_VERSION_1_0); - } - meshes = ResourceGroupManager::getSingleton().findResourceNames(groups[i], "*.skeleton"); - it = meshes->begin(); - itEnd = meshes->end(); - for (; it != itEnd; it++) { - mSkeleton = SkeletonManager::getSingleton().load(*it, groups[i]); - getResourceFullPath(mSkeleton, mSkeletonFullPath); - if (!copyFile(mSkeletonFullPath + ".bak", mSkeletonFullPath)) { - // If there is no backup, create one. - copyFile(mSkeletonFullPath, mSkeletonFullPath + ".bak"); - } - SkeletonSerializer skeletonSerializer; - skeletonSerializer.exportSkeleton(mSkeleton.get(), mSkeletonFullPath, SKELETON_VERSION_1_8); - mSkeleton->reload(); - skeletonSerializer.exportSkeleton(mSkeleton.get(), mSkeletonFullPath, SKELETON_VERSION_1_0); - mSkeleton->reload(); - } - } -} -#endif /* ifdef I_HAVE_LOT_OF_FREE_TIME */ -//-------------------------------------------------------------------------- -#ifdef OGRE_TEST_XMLSERIALIZER -TEST_F(MeshSerializerTests,Mesh_XML) -{ - XMLMeshSerializer serializerXML; - serializerXML.exportMesh(mOrigMesh.get(), mMeshFullPath + ".xml"); - mMesh = MeshManager::getSingleton().create(mMesh->getName() + ".test.mesh", mMesh->getGroup()); - serializerXML.importMesh(mMeshFullPath + ".xml", VET_COLOUR_ABGR, mMesh.get()); - assertMeshClone(mOrigMesh.get(), mMesh.get()); -} -#endif - -namespace Ogre -{ -static bool operator==(const VertexPoseKeyFrame::PoseRef& a, const VertexPoseKeyFrame::PoseRef& b) -{ - - return a.poseIndex == b.poseIndex && a.influence == b.influence; -} -} - -//-------------------------------------------------------------------------- -void MeshSerializerTests::assertMeshClone(Mesh* a, Mesh* b, MeshVersion version /*= MESH_VERSION_LATEST*/) -{ - // TODO: Compare skeleton - // TODO: Compare animations - - // EXPECT_TRUE(a->getGroup() == b->getGroup()); - // EXPECT_TRUE(a->getName() == b->getName()); - -#ifndef OGRE_TEST_XMLSERIALIZER - // XML serializer fails on these! - EXPECT_TRUE(isEqual(a->getBoundingSphereRadius(), b->getBoundingSphereRadius())); - EXPECT_TRUE(isEqual(a->getBounds().getMinimum(), b->getBounds().getMinimum())); - EXPECT_TRUE(isEqual(a->getBounds().getMaximum(), b->getBounds().getMaximum())); -#else - StringStream str; - Real val1 = a->getBoundingSphereRadius(); - Real val2 = b->getBoundingSphereRadius(); - Real diff = (val1 > val2) ? (val1 / val2) : (val2 / val1); - if (diff > 1.1) { - str << "bound sphere diff: " << diff << std::endl; - } - val1 = a->getBounds().getMinimum().length(); - val2 = b->getBounds().getMinimum().length(); - diff = (val1 > val2) ? (val1 / val2) : (val2 / val1); - if (diff > 1.1) { - str << "bound min diff: " << diff << std::endl; - } - val1 = a->getBounds().getMaximum().length(); - val2 = b->getBounds().getMaximum().length(); - diff = (val1 > val2) ? (val1 / val2) : (val2 / val1); - if (diff > 1.1) { - str << "bound max diff: " << diff << std::endl; - } - if (!str.str().empty()) { - StringStream str2; - str2 << std::endl << "Mesh name: " << b->getName() << std::endl; - str2 << str.str(); - std::cout << str2.str(); - // OutputDebugStringA(str2.str().c_str()); - } -#endif /* ifndef OGRE_TEST_XMLSERIALIZER */ - - // AutobuildEdgeLists is not saved to mesh file. You need to set it after loading a mesh! - // EXPECT_TRUE(a->getAutoBuildEdgeLists() == b->getAutoBuildEdgeLists()); - EXPECT_TRUE(isHashMapClone(a->getSubMeshNameMap(), b->getSubMeshNameMap())); - - assertVertexDataClone(a->sharedVertexData, b->sharedVertexData); - EXPECT_TRUE(a->getCreator() == b->getCreator()); - EXPECT_TRUE(a->getIndexBufferUsage() == b->getIndexBufferUsage()); - EXPECT_TRUE(a->getSharedVertexDataAnimationIncludesNormals() == b->getSharedVertexDataAnimationIncludesNormals()); - EXPECT_TRUE(a->getSharedVertexDataAnimationType() == b->getSharedVertexDataAnimationType()); - EXPECT_TRUE(a->getVertexBufferUsage() == b->getVertexBufferUsage()); - EXPECT_TRUE(a->hasVertexAnimation() == b->hasVertexAnimation()); - -#ifndef OGRE_TEST_XMLSERIALIZER - EXPECT_TRUE(a->isEdgeListBuilt() == b->isEdgeListBuilt()); // <== OgreXMLSerializer is doing post processing to generate edgelists! -#endif // !OGRE_TEST_XMLSERIALIZER - - if ((a->getNumLodLevels() > 1 || b->getNumLodLevels() > 1) && - ((version < MESH_VERSION_1_8 || (!isLodMixed(a) && !isLodMixed(b))) && // mixed lod only supported in v1.10+ - (version < MESH_VERSION_1_4 || (a->getLodStrategy() == DistanceLodBoxStrategy::getSingletonPtr() && - b->getLodStrategy() == DistanceLodBoxStrategy::getSingletonPtr())))) { // Lod Strategy only supported in v1.41+ - EXPECT_TRUE(a->getNumLodLevels() == b->getNumLodLevels()); - EXPECT_TRUE(a->hasManualLodLevel() == b->hasManualLodLevel()); - EXPECT_TRUE(a->getLodStrategy() == b->getLodStrategy()); - - int numLods = a->getNumLodLevels(); - for (int i = 0; i < numLods; i++) { - if (version != MESH_VERSION_1_0 && a->getAutoBuildEdgeLists() == b->getAutoBuildEdgeLists()) { - assertEdgeDataClone(a->getEdgeList(i), b->getEdgeList(i)); - } else if (a->getLodLevel(i).edgeData != NULL && b->getLodLevel(i).edgeData != NULL) { - assertEdgeDataClone(a->getLodLevel(i).edgeData, b->getLodLevel(i).edgeData); - } - assertLodUsageClone(a->getLodLevel(i), b->getLodLevel(i)); - } - } - - EXPECT_TRUE(a->getNumSubMeshes() == b->getNumSubMeshes()); - int numLods = std::min(a->getNumLodLevels(), b->getNumLodLevels()); - size_t numSubmeshes = a->getNumSubMeshes(); - for (size_t i = 0; i < numSubmeshes; i++) { - SubMesh* aSubmesh = a->getSubMesh(i); - SubMesh* bSubmesh = b->getSubMesh(i); - - EXPECT_TRUE(aSubmesh->getMaterialName() == bSubmesh->getMaterialName()); - EXPECT_EQ(bool(aSubmesh->getMaterial()), bool(bSubmesh->getMaterial())); - EXPECT_TRUE(aSubmesh->useSharedVertices == bSubmesh->useSharedVertices); - EXPECT_TRUE(aSubmesh->getVertexAnimationIncludesNormals() == bSubmesh->getVertexAnimationIncludesNormals()); - EXPECT_TRUE(aSubmesh->getVertexAnimationType() == bSubmesh->getVertexAnimationType()); - EXPECT_TRUE(isContainerClone(aSubmesh->blendIndexToBoneIndexMap, bSubmesh->blendIndexToBoneIndexMap)); - // TODO: Compare getBoneAssignments and getTextureAliases - for (int n = 0; n < numLods; n++) { - if (a->_isManualLodLevel(n)) { - continue; - } - RenderOperation aop, bop; - aSubmesh->_getRenderOperation(aop, n); - bSubmesh->_getRenderOperation(bop, n); - assertIndexDataClone(aop.indexData, bop.indexData); - assertVertexDataClone(aop.vertexData, bop.vertexData); - EXPECT_TRUE(aop.operationType == bop.operationType); - EXPECT_TRUE(aop.useIndexes == bop.useIndexes); - } - } - - // animations - ASSERT_EQ(b->getNumAnimations(), a->getNumAnimations()); - - // pose animations - const PoseList& aPoseList = a->getPoseList(); - const PoseList& bPoseList = a->getPoseList(); - ASSERT_EQ(bPoseList.size(), aPoseList.size()); - for (size_t i = 0; i < aPoseList.size(); i++) - { - EXPECT_EQ(bPoseList[i]->getName(), aPoseList[i]->getName()); - EXPECT_EQ(bPoseList[i]->getTarget(), aPoseList[i]->getTarget()); - EXPECT_EQ(bPoseList[i]->getNormals(), aPoseList[i]->getNormals()); - EXPECT_EQ(bPoseList[i]->getVertexOffsets(), aPoseList[i]->getVertexOffsets()); - } - - for (int i = 0; i < a->getNumAnimations(); i++) - { - EXPECT_EQ(b->getAnimation(i)->getLength(), a->getAnimation(i)->getLength()); - ASSERT_EQ(b->getAnimation(i)->getNumVertexTracks(), - a->getAnimation(i)->getNumVertexTracks()); - - const Animation::VertexTrackList& aList = a->getAnimation(i)->_getVertexTrackList(); - const Animation::VertexTrackList& bList = b->getAnimation(i)->_getVertexTrackList(); - - Animation::VertexTrackList::const_iterator it = aList.begin(); - for (; it != aList.end(); ++it) - { - EXPECT_EQ(bList.at(it->first)->getAnimationType(), it->second->getAnimationType()); - ASSERT_EQ(bList.at(it->first)->getNumKeyFrames(), it->second->getNumKeyFrames()); - - for (size_t j = 0; j < it->second->getNumKeyFrames(); j++) - { - VertexPoseKeyFrame* aKeyFrame = it->second->getVertexPoseKeyFrame(j); - VertexPoseKeyFrame* bKeyFrame = bList.at(it->first)->getVertexPoseKeyFrame(j); - ASSERT_EQ(bKeyFrame->getPoseReferences(), aKeyFrame->getPoseReferences()); - } - } - } -} -//-------------------------------------------------------------------------- -bool MeshSerializerTests::isLodMixed(const Mesh* pMesh) -{ - if (!pMesh->hasManualLodLevel()) { - return false; - } - - unsigned short numLods = pMesh->getNumLodLevels(); - for (unsigned short i = 1; i < numLods; ++i) { - if (!pMesh->_isManualLodLevel(i)) { - return true; - } - } - - return false; -} -//-------------------------------------------------------------------------- -void MeshSerializerTests::assertVertexDataClone(VertexData* a, VertexData* b, MeshVersion version /*= MESH_VERSION_LATEST*/) -{ - EXPECT_TRUE((a == NULL) == (b == NULL)); - if (a) { - // compare bindings - { - const VertexBufferBinding::VertexBufferBindingMap& aBindings = a->vertexBufferBinding->getBindings(); - const VertexBufferBinding::VertexBufferBindingMap& bBindings = b->vertexBufferBinding->getBindings(); - EXPECT_TRUE(aBindings.size() == bBindings.size()); - typedef VertexBufferBinding::VertexBufferBindingMap::const_iterator bindingIterator; - bindingIterator aIt = aBindings.begin(); - bindingIterator aEndIt = aBindings.end(); - bindingIterator bIt = bBindings.begin(); - for (; aIt != aEndIt; aIt++, bIt++) { - EXPECT_TRUE(aIt->first == bIt->first); - EXPECT_TRUE((aIt->second.get() == NULL) == (bIt->second.get() == NULL)); - if (a) { - EXPECT_TRUE(aIt->second->getManager() == bIt->second->getManager()); - EXPECT_TRUE(aIt->second->getNumVertices() == bIt->second->getNumVertices()); - } - } - } - - { - const VertexDeclaration::VertexElementList& aElements = a->vertexDeclaration->getElements(); - const VertexDeclaration::VertexElementList& bElements = a->vertexDeclaration->getElements(); - EXPECT_TRUE(aElements.size() == bElements.size()); - typedef VertexDeclaration::VertexElementList::const_iterator bindingIterator; - bindingIterator aIt = aElements.begin(); - bindingIterator aEndIt = aElements.end(); - bindingIterator bIt; - for (; aIt != aEndIt; aIt++) { - bIt = std::find(bElements.begin(), bElements.end(), *aIt); - EXPECT_TRUE(bIt != bElements.end()); - -#ifndef OGRE_TEST_XMLSERIALIZER - const VertexElement& aElem = *aIt; - const VertexElement& bElem = *bIt; - HardwareVertexBufferSharedPtr abuf = a->vertexBufferBinding->getBuffer(aElem.getSource()); - HardwareVertexBufferSharedPtr bbuf = b->vertexBufferBinding->getBuffer(bElem.getSource()); - unsigned char* avertex = static_cast(abuf->lock(HardwareBuffer::HBL_READ_ONLY)); - unsigned char* bvertex = static_cast(bbuf->lock(HardwareBuffer::HBL_READ_ONLY)); - size_t avSize = abuf->getVertexSize(); - size_t bvSize = bbuf->getVertexSize(); - size_t elemSize = VertexElement::getTypeSize(aElem.getType()); - unsigned char* avEnd = avertex + a->vertexCount * avSize; - bool error = false; - for (; avertex < avEnd; avertex += avSize, bvertex += bvSize) { - float* afloat, * bfloat; - aElem.baseVertexPointerToElement(avertex, &afloat); - bElem.baseVertexPointerToElement(bvertex, &bfloat); - error |= (memcmp(afloat, bfloat, elemSize) != 0); - } - abuf->unlock(); - bbuf->unlock(); - EXPECT_TRUE(!error && "Content of vertex buffer differs!"); -#endif /* ifndef OGRE_TEST_XMLSERIALIZER */ - } - } - - EXPECT_TRUE(a->vertexStart == b->vertexStart); - EXPECT_TRUE(a->vertexCount == b->vertexCount); - EXPECT_TRUE(a->hwAnimDataItemsUsed == b->hwAnimDataItemsUsed); - - // Compare hwAnimationData - { - const VertexData::HardwareAnimationDataList& aAnimData = a->hwAnimationDataList; - const VertexData::HardwareAnimationDataList& bAnimData = b->hwAnimationDataList; - EXPECT_TRUE(aAnimData.size() == bAnimData.size()); - typedef VertexData::HardwareAnimationDataList::const_iterator bindingIterator; - bindingIterator aIt = aAnimData.begin(); - bindingIterator aEndIt = aAnimData.end(); - bindingIterator bIt = bAnimData.begin(); - for (; aIt != aEndIt; aIt++, bIt++) { - EXPECT_TRUE(aIt->parametric == bIt->parametric); - EXPECT_TRUE(aIt->targetBufferIndex == bIt->targetBufferIndex); - } - } - } -} -//-------------------------------------------------------------------------- -template -bool MeshSerializerTests::isContainerClone(T& a, T& b) -{ - return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin()); -} -//-------------------------------------------------------------------------- -template -bool MeshSerializerTests::isHashMapClone(const std::unordered_map& a, const std::unordered_map& b) -{ - // if you recreate a HashMap with same elements, then iteration order may differ! - // So isContainerClone is not always working on HashMap. - if (a.size() != b.size()) { - return false; - } - typename std::unordered_map::const_iterator it, itFind, itEnd; - it = a.begin(); - itEnd = a.end(); - for (; it != itEnd; it++) { - itFind = b.find(it->first); - if (itFind == b.end() || itFind->second != it->second) { - return false; - } - } - return true; -} -//-------------------------------------------------------------------------- -void MeshSerializerTests::assertIndexDataClone(IndexData* a, IndexData* b, MeshVersion version /*= MESH_VERSION_LATEST*/) -{ - EXPECT_TRUE((a == NULL) == (b == NULL)); - if (a) { - EXPECT_TRUE(a->indexCount == b->indexCount); - // EXPECT_TRUE(a->indexStart == b->indexStart); - EXPECT_TRUE((a->indexBuffer.get() == NULL) == (b->indexBuffer.get() == NULL)); - if (a->indexBuffer) { - EXPECT_TRUE(a->indexBuffer->getManager() == b->indexBuffer->getManager()); - // EXPECT_TRUE(a->indexBuffer->getNumIndexes() == b->indexBuffer->getNumIndexes()); - EXPECT_TRUE(a->indexBuffer->getIndexSize() == b->indexBuffer->getIndexSize()); - EXPECT_TRUE(a->indexBuffer->getType() == b->indexBuffer->getType()); - - char* abuf = (char*) a->indexBuffer->lock(HardwareBuffer::HBL_READ_ONLY); - char* bbuf = (char*) b->indexBuffer->lock(HardwareBuffer::HBL_READ_ONLY); - size_t size = a->indexBuffer->getIndexSize(); - char* astart = abuf + a->indexStart * size; - char* bstart = bbuf + b->indexStart * size; - EXPECT_TRUE(memcmp(astart, bstart, a->indexCount * size) == 0); - a->indexBuffer->unlock(); - b->indexBuffer->unlock(); - } - } -} -//-------------------------------------------------------------------------- -void MeshSerializerTests::assertEdgeDataClone(EdgeData* a, EdgeData* b, MeshVersion version /*= MESH_VERSION_LATEST*/) -{ - EXPECT_TRUE((a == NULL) == (b == NULL)); - if (a) { - EXPECT_TRUE(a->isClosed == b->isClosed); - EXPECT_TRUE(isContainerClone(a->triangleFaceNormals, b->triangleFaceNormals)); - EXPECT_TRUE(isContainerClone(a->triangleLightFacings, b->triangleLightFacings)); - // TODO: Compare triangles and edgeGroups in more detail. - EXPECT_TRUE(a->triangles.size() == b->triangles.size()); - EXPECT_TRUE(a->edgeGroups.size() == b->edgeGroups.size()); - } -} -//-------------------------------------------------------------------------- -void MeshSerializerTests::assertLodUsageClone(const MeshLodUsage& a, const MeshLodUsage& b, MeshVersion version /*= MESH_VERSION_LATEST*/) -{ - EXPECT_TRUE(a.manualName == b.manualName); - EXPECT_TRUE(isEqual(a.userValue, b.userValue)); - EXPECT_TRUE(isEqual(a.value, b.value)); -} -//-------------------------------------------------------------------------- -void MeshSerializerTests::getResourceFullPath(const ResourcePtr& resource, String& outPath) -{ - ResourceGroupManager& resourceGroupMgr = ResourceGroupManager::getSingleton(); - String group = resource->getGroup(); - String name = resource->getName(); - FileInfo* info = NULL; - FileInfoListPtr locPtr = resourceGroupMgr.listResourceFileInfo(group); - FileInfoList::iterator it, itEnd; - it = locPtr->begin(); - itEnd = locPtr->end(); - for (; it != itEnd; it++) { - if (StringUtil::startsWith(name, it->filename)) { - info = &*it; - break; - } - } - if(!info) { - outPath = name; - return; - } - outPath = info->archive->getName(); - if (outPath[outPath .size()-1] != '/' && outPath[outPath .size()-1] != '\\') { - outPath += '/'; - } - outPath += info->path; - if (outPath[outPath .size()-1] != '/' && outPath[outPath .size()-1] != '\\') { - outPath += '/'; - } - outPath += info->filename; - - OgreAssert(info->archive->getType() == "FileSystem", ""); -} -//-------------------------------------------------------------------------- -bool MeshSerializerTests::copyFile(const String& srcPath, const String& dstPath) -{ - std::ifstream src(srcPath.c_str(), std::ios::binary); - if (!src.is_open()) { - return false; - } - std::ofstream dst(dstPath.c_str(), std::ios::binary); - if (!dst.is_open()) { - return false; - } - - dst << src.rdbuf(); - return true; -} -//-------------------------------------------------------------------------- -bool MeshSerializerTests::isEqual(Real a, Real b) -{ - Real absoluteError = std::abs(a * mErrorFactor); - return ((a - absoluteError) <= b) && ((a + absoluteError) >= b); -} -//-------------------------------------------------------------------------- -bool MeshSerializerTests::isEqual(const Vector3& a, const Vector3& b) -{ - return isEqual(a.x, b.x) && isEqual(a.y, b.y) && isEqual(a.z, b.z); -} -//-------------------------------------------------------------------------- diff --git a/Tests/OgreMain/src/MeshWithoutIndexDataTests.cpp b/Tests/OgreMain/src/MeshWithoutIndexDataTests.cpp deleted file mode 100644 index b121cc75edc..00000000000 --- a/Tests/OgreMain/src/MeshWithoutIndexDataTests.cpp +++ /dev/null @@ -1,488 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include -#include "Ogre.h" -#include "OgreDistanceLodStrategy.h" -#include "OgreDefaultHardwareBufferManager.h" -#include "OgreFileSystem.h" -#include "OgreArchiveManager.h" -#include "MeshWithoutIndexDataTests.h" -#include "OgreLodStrategyManager.h" - -#ifdef OGRE_BUILD_COMPONENT_MESHLODGENERATOR -#include "OgreLodConfig.h" -#include "OgreMeshLodGenerator.h" -#endif - -// Register the test suite - -//-------------------------------------------------------------------------- -void MeshWithoutIndexDataTests::SetUp() -{ - OGRE_NEW ResourceGroupManager(); - OGRE_NEW LodStrategyManager(); - mBufMgr = OGRE_NEW DefaultHardwareBufferManager(); - mMeshMgr = OGRE_NEW MeshManager(); - mArchiveMgr = OGRE_NEW ArchiveManager(); - mArchiveMgr->addArchiveFactory(OGRE_NEW FileSystemArchiveFactory()); - - MaterialManager* matMgr = OGRE_NEW MaterialManager(); - matMgr->initialise(); -} -//-------------------------------------------------------------------------- -void MeshWithoutIndexDataTests::TearDown() -{ - OGRE_DELETE MaterialManager::getSingletonPtr(); - OGRE_DELETE mArchiveMgr; - OGRE_DELETE mMeshMgr; - OGRE_DELETE mBufMgr; - OGRE_DELETE LodStrategyManager::getSingletonPtr(); - OGRE_DELETE ResourceGroupManager::getSingletonPtr(); -} -//-------------------------------------------------------------------------- -TEST_F(MeshWithoutIndexDataTests,CreateSimpleLine) -{ - ManualObject* line = OGRE_NEW ManualObject("line"); - line->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_LIST); - line->position(0, 50, 0); - line->position(50, 100, 0); - line->end(); - String fileName = "line.mesh"; - MeshPtr lineMesh = line->convertToMesh(fileName); - OGRE_DELETE line; - - EXPECT_TRUE(lineMesh->getNumSubMeshes() == 1); - EXPECT_TRUE(lineMesh->getSubMesh(0)->indexData->indexCount == 0); - RenderOperation rop; - lineMesh->getSubMesh(0)->_getRenderOperation(rop); - EXPECT_TRUE(rop.useIndexes == false); - EXPECT_TRUE(lineMesh->getSubMesh(0)->vertexData->vertexCount == 2); - - MeshSerializer meshWriter; - meshWriter.exportMesh(lineMesh.get(), fileName); - - mMeshMgr->remove(fileName, "General"); - - ResourceGroupManager::getSingleton().addResourceLocation(".", "FileSystem"); - MeshPtr loadedLine = mMeshMgr->load(fileName, "General"); - - remove(fileName.c_str()); - - EXPECT_TRUE(loadedLine->getNumSubMeshes() == 1); - EXPECT_TRUE(loadedLine->getSubMesh(0)->indexData->indexCount == 0); - loadedLine->getSubMesh(0)->_getRenderOperation(rop); - EXPECT_TRUE(rop.useIndexes == false); - EXPECT_TRUE(lineMesh->getSubMesh(0)->vertexData->vertexCount == 2); - - mMeshMgr->remove(fileName, "General"); -} -//-------------------------------------------------------------------------- -TEST_F(MeshWithoutIndexDataTests,CreateLineList) -{ - ManualObject* lineList = OGRE_NEW ManualObject("line"); - lineList->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_LIST); - lineList->position(0, 50, 0); - lineList->position(50, 100, 0); - lineList->position(50, 50, 0); - lineList->position(100, 100, 0); - lineList->position(0, 50, 0); - lineList->position(50, 50, 0); - lineList->end(); - String fileName = "lineList.mesh"; - MeshPtr lineListMesh = lineList->convertToMesh(fileName); - OGRE_DELETE lineList; - - EXPECT_TRUE(lineListMesh->getNumSubMeshes() == 1); - EXPECT_TRUE(lineListMesh->getSubMesh(0)->indexData->indexCount == 0); - RenderOperation rop; - lineListMesh->getSubMesh(0)->_getRenderOperation(rop); - EXPECT_TRUE(rop.useIndexes == false); - EXPECT_TRUE(lineListMesh->getSubMesh(0)->vertexData->vertexCount == 6); - - MeshSerializer meshWriter; - meshWriter.exportMesh(lineListMesh.get(), fileName); - - mMeshMgr->remove(fileName, "General"); - - ResourceGroupManager::getSingleton().addResourceLocation(".", "FileSystem"); - MeshPtr loadedLineList = mMeshMgr->load(fileName, "General"); - - remove(fileName.c_str()); - - EXPECT_TRUE(loadedLineList->getNumSubMeshes() == 1); - EXPECT_TRUE(loadedLineList->getSubMesh(0)->indexData->indexCount == 0); - loadedLineList->getSubMesh(0)->_getRenderOperation(rop); - EXPECT_TRUE(rop.useIndexes == false); - EXPECT_TRUE(loadedLineList->getSubMesh(0)->vertexData->vertexCount == 6); - - mMeshMgr->remove(fileName, "General"); -} -//-------------------------------------------------------------------------- -TEST_F(MeshWithoutIndexDataTests,CreateLineStrip) -{ - ManualObject* lineStrip = OGRE_NEW ManualObject("line"); - lineStrip->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_STRIP); - lineStrip->position(50, 100, 0); - lineStrip->position(0, 50, 0); - lineStrip->position(50, 50, 0); - lineStrip->position(100, 100, 0); - lineStrip->end(); - String fileName = "lineStrip.mesh"; - MeshPtr lineStripMesh = lineStrip->convertToMesh(fileName); - OGRE_DELETE lineStrip; - - EXPECT_TRUE(lineStripMesh->getNumSubMeshes() == 1); - EXPECT_TRUE(lineStripMesh->getSubMesh(0)->indexData->indexCount == 0); - RenderOperation rop; - lineStripMesh->getSubMesh(0)->_getRenderOperation(rop); - EXPECT_TRUE(rop.useIndexes == false); - EXPECT_TRUE(lineStripMesh->getSubMesh(0)->vertexData->vertexCount == 4); - - MeshSerializer meshWriter; - meshWriter.exportMesh(lineStripMesh.get(), fileName); - - mMeshMgr->remove(fileName, "General"); - - ResourceGroupManager::getSingleton().addResourceLocation(".", "FileSystem"); - MeshPtr loadedLineStrip = mMeshMgr->load(fileName, "General"); - - remove(fileName.c_str()); - - EXPECT_TRUE(loadedLineStrip->getNumSubMeshes() == 1); - EXPECT_TRUE(loadedLineStrip->getSubMesh(0)->indexData->indexCount == 0); - loadedLineStrip->getSubMesh(0)->_getRenderOperation(rop); - EXPECT_TRUE(rop.useIndexes == false); - EXPECT_TRUE(loadedLineStrip->getSubMesh(0)->vertexData->vertexCount == 4); - - mMeshMgr->remove(fileName, "General"); -} -//-------------------------------------------------------------------------- -TEST_F(MeshWithoutIndexDataTests,CreatePointList) -{ - ManualObject* pointList = OGRE_NEW ManualObject("line"); - pointList->begin("BaseWhiteNoLighting", RenderOperation::OT_POINT_LIST); - pointList->position(50, 100, 0); - pointList->position(0, 50, 0); - pointList->position(50, 50, 0); - pointList->position(100, 100, 0); - pointList->end(); - String fileName = "pointList.mesh"; - MeshPtr pointListMesh = pointList->convertToMesh(fileName); - OGRE_DELETE pointList; - - EXPECT_TRUE(pointListMesh->getNumSubMeshes() == 1); - EXPECT_TRUE(pointListMesh->getSubMesh(0)->indexData->indexCount == 0); - RenderOperation rop; - pointListMesh->getSubMesh(0)->_getRenderOperation(rop); - EXPECT_TRUE(rop.useIndexes == false); - EXPECT_TRUE(pointListMesh->getSubMesh(0)->vertexData->vertexCount == 4); - - MeshSerializer meshWriter; - meshWriter.exportMesh(pointListMesh.get(), fileName); - - mMeshMgr->remove(fileName, "General"); - - ResourceGroupManager::getSingleton().addResourceLocation(".", "FileSystem"); - MeshPtr loadedPointList = mMeshMgr->load(fileName, "General"); - - remove(fileName.c_str()); - - EXPECT_TRUE(loadedPointList->getNumSubMeshes() == 1); - EXPECT_TRUE(loadedPointList->getSubMesh(0)->indexData->indexCount == 0); - loadedPointList->getSubMesh(0)->_getRenderOperation(rop); - EXPECT_TRUE(rop.useIndexes == false); - EXPECT_TRUE(loadedPointList->getSubMesh(0)->vertexData->vertexCount == 4); - - mMeshMgr->remove(fileName, "General"); -} -//-------------------------------------------------------------------------- -TEST_F(MeshWithoutIndexDataTests,CreateLineWithMaterial) -{ - String matName = "lineMat"; - MaterialPtr matPtr = MaterialManager::getSingleton().create(matName, "General"); - Pass* pass = matPtr->getTechnique(0)->getPass(0); - pass->setDiffuse(1.0, 0.1, 0.1, 0); - - ManualObject* line = OGRE_NEW ManualObject("line"); - line->begin(matName, RenderOperation::OT_LINE_LIST); - line->position(0, 50, 0); - line->position(50, 100, 0); - line->end(); - String fileName = "lineWithMat.mesh"; - MeshPtr lineMesh = line->convertToMesh(fileName); - OGRE_DELETE line; - - EXPECT_TRUE(lineMesh->getNumSubMeshes() == 1); - EXPECT_TRUE(lineMesh->getSubMesh(0)->indexData->indexCount == 0); - RenderOperation rop; - lineMesh->getSubMesh(0)->_getRenderOperation(rop); - EXPECT_TRUE(rop.useIndexes == false); - EXPECT_TRUE(lineMesh->getSubMesh(0)->vertexData->vertexCount == 2); - - MeshSerializer meshWriter; - meshWriter.exportMesh(lineMesh.get(), fileName); - MaterialSerializer matWriter; - matWriter.exportMaterial( - MaterialManager::getSingleton().getByName(matName), - matName + ".material"); - - mMeshMgr->remove(fileName, "General"); - - ResourceGroupManager::getSingleton().addResourceLocation(".", "FileSystem"); - MeshPtr loadedLine = mMeshMgr->load(fileName, "General"); - - remove(fileName.c_str()); - remove((matName + ".material").c_str()); - - EXPECT_TRUE(loadedLine->getNumSubMeshes() == 1); - EXPECT_TRUE(loadedLine->getSubMesh(0)->indexData->indexCount == 0); - loadedLine->getSubMesh(0)->_getRenderOperation(rop); - EXPECT_TRUE(rop.useIndexes == false); - EXPECT_TRUE(lineMesh->getSubMesh(0)->vertexData->vertexCount == 2); - - mMeshMgr->remove(fileName, "General"); -} -//-------------------------------------------------------------------------- -static void createMeshWithMaterial(const String& fileName) -{ - String matFileNameSuffix = ".material"; - String matName1 = "red"; - String matFileName1 = matName1 + matFileNameSuffix; - MaterialPtr matPtr = MaterialManager::getSingleton().create(matName1, "General"); - Pass* pass = matPtr->getTechnique(0)->getPass(0); - pass->setDiffuse(1.0, 0.1, 0.1, 0); - - String matName2 = "green"; - String matFileName2 = matName2 + matFileNameSuffix; - matPtr = MaterialManager::getSingleton().create(matName2, "General"); - pass = matPtr->getTechnique(0)->getPass(0); - pass->setDiffuse(0.1, 1.0, 0.1, 0); - - String matName3 = "blue"; - String matFileName3 = matName3 + matFileNameSuffix; - matPtr = MaterialManager::getSingleton().create(matName3, "General"); - pass = matPtr->getTechnique(0)->getPass(0); - pass->setDiffuse(0.1, 0.1, 1.0, 0); - - String matName4 = "yellow"; - String matFileName4 = matName4 + matFileNameSuffix; - matPtr = MaterialManager::getSingleton().create(matName4, "General"); - pass = matPtr->getTechnique(0)->getPass(0); - pass->setDiffuse(1.0, 1.0, 0.1, 0); - - ManualObject* manObj = OGRE_NEW ManualObject("mesh"); - manObj->begin(matName1, RenderOperation::OT_TRIANGLE_LIST); - manObj->position(0, 50, 0); - manObj->position(50, 50, 0); - manObj->position(0, 100, 0); - manObj->triangle(0, 1, 2); - manObj->position(50, 100, 0); - manObj->position(0, 100, 0); - manObj->position(50, 50, 0); - manObj->triangle(3, 4, 5); - manObj->end(); - manObj->begin(matName2, RenderOperation::OT_LINE_LIST); - manObj->position(0, 100, 0); - manObj->position(-50, 50, 0); - manObj->position(-50, 0, 0); - manObj->position(-50, 50, 0); - manObj->position(-100, 0, 0); - manObj->position(-50, 0, 0); - manObj->end(); - manObj->begin(matName3, RenderOperation::OT_LINE_STRIP); - manObj->position(50, 100, 0); - manObj->position(100, 50, 0); - manObj->position(100, 0, 0); - manObj->position(150, 0, 0); - manObj->end(); - manObj->begin(matName4, RenderOperation::OT_POINT_LIST); - manObj->position(50, 0, 0); - manObj->position(0, 0, 0); - manObj->end(); - manObj->convertToMesh(fileName); - OGRE_DELETE manObj; -} -//-------------------------------------------------------------------------- -TEST_F(MeshWithoutIndexDataTests,CreateMesh) -{ - String fileName = "indexMix.mesh"; - createMeshWithMaterial(fileName); - MeshPtr mesh = mMeshMgr->getByName(fileName, "General"); - - EXPECT_TRUE(mesh->getNumSubMeshes() == 4); - RenderOperation rop; - for (int i=0; i<4; ++i) - { - mesh->getSubMesh(i)->_getRenderOperation(rop); - // First submesh has indexes, the others does not. - EXPECT_TRUE( rop.useIndexes == (i == 0) ); - } - - MeshSerializer meshWriter; - meshWriter.exportMesh(mesh.get(), fileName); - - mMeshMgr->remove(fileName, "General"); - - ResourceGroupManager::getSingleton().addResourceLocation(".", "FileSystem"); - MeshPtr loadedMesh = mMeshMgr->load(fileName, "General"); - - remove(fileName.c_str()); - - EXPECT_TRUE(loadedMesh->getNumSubMeshes() == 4); - - mMeshMgr->remove(fileName, "General"); -} -//-------------------------------------------------------------------------- -TEST_F(MeshWithoutIndexDataTests,CloneMesh) -{ - String originalName = "toClone.mesh"; - createMeshWithMaterial(originalName); - MeshPtr mesh = mMeshMgr->getByName(originalName, "General"); - - String fileName = "clone.mesh"; - MeshPtr clone = mesh->clone(fileName); - EXPECT_TRUE(mesh->getNumSubMeshes() == 4); - - MeshSerializer meshWriter; - meshWriter.exportMesh(mesh.get(), fileName); - - mMeshMgr->remove(fileName, "General"); - - ResourceGroupManager::getSingleton().addResourceLocation(".", "FileSystem"); - MeshPtr loadedMesh = mMeshMgr->load(fileName, "General"); - - remove(fileName.c_str()); - - EXPECT_TRUE(loadedMesh->getNumSubMeshes() == 4); - - mMeshMgr->remove(fileName, "General"); -} -//-------------------------------------------------------------------------- -TEST_F(MeshWithoutIndexDataTests,EdgeList) -{ - String fileName = "testEdgeList.mesh"; - ManualObject* line = OGRE_NEW ManualObject("line"); - line->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_LIST); - line->position(0, 50, 0); - line->position(50, 100, 0); - line->end(); - MeshPtr mesh = line->convertToMesh(fileName); - OGRE_DELETE line; - - // whole mesh must not contain index data, for this test - EXPECT_TRUE(mesh->getNumSubMeshes() == 1); - EXPECT_TRUE(mesh->getSubMesh(0)->indexData->indexCount == 0); - - mesh->buildEdgeList(); - MeshSerializer meshWriter; - // if it does not crash here, test is passed - meshWriter.exportMesh(mesh.get(), fileName); - - remove(fileName.c_str()); - - mMeshMgr->remove(fileName, "General"); -} -//-------------------------------------------------------------------------- -TEST_F(MeshWithoutIndexDataTests,GenerateExtremes) -{ - String fileName = "testGenerateExtremes.mesh"; - createMeshWithMaterial(fileName); - MeshPtr mesh = mMeshMgr->getByName(fileName, "General"); - - const size_t NUM_EXTREMES = 4; - for (ushort i = 0; i < mesh->getNumSubMeshes(); ++i) - { - mesh->getSubMesh(i)->generateExtremes(NUM_EXTREMES); - } - for (ushort i = 0; i < mesh->getNumSubMeshes(); ++i) - { - SubMesh* subMesh = mesh->getSubMesh(i); - // According to generateExtremes, extremes are built based upon the bounding box indices. - // But it also creates indices for all bounding boxes even if the mesh does not have any. - // So...there should always be some extremity points. The number of which may vary. - if (subMesh->indexData->indexCount > 0) - { - EXPECT_TRUE(subMesh->extremityPoints.size() == NUM_EXTREMES); - } - } - - mMeshMgr->remove(fileName, "General"); -} -//-------------------------------------------------------------------------- -TEST_F(MeshWithoutIndexDataTests,BuildTangentVectors) -{ - String fileName = "testBuildTangentVectors.mesh"; - createMeshWithMaterial(fileName); - MeshPtr mesh = mMeshMgr->getByName(fileName, "General"); - - EXPECT_THROW(mesh->buildTangentVectors(), InvalidParametersException); - - mMeshMgr->remove(fileName, "General"); -} -//-------------------------------------------------------------------------- -TEST_F(MeshWithoutIndexDataTests,GenerateLodLevels) -{ -#ifdef OGRE_BUILD_COMPONENT_MESHLODGENERATOR - String fileName = "testGenerateLodLevels.mesh"; - createMeshWithMaterial(fileName); - MeshPtr mesh = mMeshMgr->getByName(fileName, "General"); - - LodConfig lodConfig(mesh); - lodConfig.createGeneratedLodLevel(600, 2, LodLevel::VRM_CONSTANT); - MeshLodGenerator().generateLodLevels(lodConfig); - // It may be less then 2, when two levels have the same vertex count it will be optimized out and lodLevel.outSkipped=true - EXPECT_TRUE(mesh->getNumLodLevels() == 2); - for (ushort i = 0; i < mesh->getNumSubMeshes(); ++i) - { - SubMesh* subMesh = mesh->getSubMesh(i); - for (ushort j = 0; j < mesh->getNumLodLevels() - 1; ++j) - { - if (subMesh->indexData->indexCount > 0) - { - // This may not be true for all meshes, but in this test we don't have reduced to 0. - EXPECT_TRUE(subMesh->mLodFaceList[j]->indexCount > 0); - } - else - { - // Should be 3 because of the dummy triangle being generated - EXPECT_TRUE(subMesh->mLodFaceList[j]->indexCount == 3); - } - } - } - - MeshSerializer meshWriter; - meshWriter.exportMesh(mesh.get(), fileName); - - remove(fileName.c_str()); - - mMeshMgr->remove(fileName, "General"); -#else - GTEST_SKIP() << "MeshLodGenerator is not built"; -#endif -} -//--------------------------------------------------------------------------//-------------------------------------------------------------------------- diff --git a/Tests/OgreMain/src/PixelFormatTests.cpp b/Tests/OgreMain/src/PixelFormatTests.cpp deleted file mode 100644 index f06d06f3f40..00000000000 --- a/Tests/OgreMain/src/PixelFormatTests.cpp +++ /dev/null @@ -1,251 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "PixelFormatTests.h" -#include -#include - - -// Register the test suite - -//-------------------------------------------------------------------------- -void PixelFormatTests::SetUp() -{ - mSize = 4096; - mRandomData = new uint8[mSize]; - mTemp = new uint8[mSize]; - mTemp2 = new uint8[mSize]; - - // Generate reproducible random data - srand(0); - for(unsigned int x=0; x<(unsigned int)mSize; x++) - mRandomData[x] = (uint8)rand(); -} -//-------------------------------------------------------------------------- -void PixelFormatTests::TearDown() -{ - delete [] mRandomData; - delete [] mTemp; - delete [] mTemp2; -} -//-------------------------------------------------------------------------- -TEST_F(PixelFormatTests,IntegerPackUnpack) -{ - ColourValue src(1./1023, 512./1023, 0, 1./3); - - // naive implementation - const uint16 ir = static_cast( Math::saturate( src.r ) * 1023.0f + 0.5f ); - const uint16 ig = static_cast( Math::saturate( src.g ) * 1023.0f + 0.5f ); - const uint16 ib = static_cast( Math::saturate( src.b ) * 1023.0f + 0.5f ); - const uint16 ia = static_cast( Math::saturate( src.a ) * 3.0f + 0.5f ); - uint32 ref = (ia << 30u) | (ir << 20u) | (ig << 10u) | (ib); - - uint32 packed; - PixelUtil::packColour(src, PF_A2R10G10B10, &packed); - - EXPECT_EQ(packed, ref); - - ColourValue dst; - PixelUtil::unpackColour(dst, PF_A2R10G10B10, &packed); - - EXPECT_EQ(src, dst); -} -//-------------------------------------------------------------------------- -TEST_F(PixelFormatTests,FloatPackUnpack) -{ - // Float32 - float data[4] = {1.0f, 2.0f, 3.0f, 4.0f}; - float r,g,b,a; - PixelUtil::unpackColour(&r, &g, &b, &a, PF_FLOAT32_RGBA, data); - EXPECT_EQ(r, 1.0f); - EXPECT_EQ(g, 2.0f); - EXPECT_EQ(b, 3.0f); - EXPECT_EQ(a, 4.0f); - - // Float16 - setupBoxes(PF_A8B8G8R8, PF_FLOAT16_RGBA); - mDst2.format = PF_A8B8G8R8; - unsigned int eob = mSrc.getWidth()*4; - - PixelUtil::bulkPixelConversion(mSrc, mDst1); - PixelUtil::bulkPixelConversion(mDst1, mDst2); - - // Locate errors - std::stringstream s; - unsigned int x; - for(x=0; xPF_A8B8G8R8 conversion was not lossless "+s.str(); -} -//-------------------------------------------------------------------------- -// Pure 32 bit float precision brute force pixel conversion; for comparison -static void naiveBulkPixelConversion(const PixelBox &src, const PixelBox &dst) -{ - uint8 *srcptr = src.data; - uint8 *dstptr = dst.data; - size_t srcPixelSize = PixelUtil::getNumElemBytes(src.format); - size_t dstPixelSize = PixelUtil::getNumElemBytes(dst.format); - - // Calculate pitches+skips in bytes - unsigned long srcRowSkipBytes = src.getRowSkip()*srcPixelSize; - unsigned long srcSliceSkipBytes = src.getSliceSkip()*srcPixelSize; - - unsigned long dstRowSkipBytes = dst.getRowSkip()*dstPixelSize; - unsigned long dstSliceSkipBytes = dst.getSliceSkip()*dstPixelSize; - - // The brute force fallback - float r,g,b,a; - for(size_t z=src.front; z width2) - width = width2; - - mSrc = PixelBox(width, 1, 1, srcFormat, mRandomData); - mDst1 = PixelBox(width, 1, 1, dstFormat, mTemp); - mDst2 = PixelBox(width, 1, 1, dstFormat, mTemp2); -} -//-------------------------------------------------------------------------- -void PixelFormatTests::testCase(PixelFormat srcFormat, PixelFormat dstFormat) -{ - setupBoxes(srcFormat, dstFormat); - // Check end of buffer - unsigned long eob = mDst1.getWidth()*PixelUtil::getNumElemBytes(dstFormat); - mTemp[eob] = (unsigned char)0x56; - mTemp[eob+1] = (unsigned char)0x23; - - //std::cerr << "["+PixelUtil::getFormatName(srcFormat)+"->"+PixelUtil::getFormatName(dstFormat)+"]" << " " << eob << std::endl; - - // Do pack/unpacking with both naive and optimized version - PixelUtil::bulkPixelConversion(mSrc, mDst1); - naiveBulkPixelConversion(mSrc, mDst2); - - EXPECT_EQ(mTemp[eob], (unsigned char)0x56); - EXPECT_EQ(mTemp[eob+1], (unsigned char)0x23); - - std::stringstream s; - int x; - s << "src="; - for(x=0; x<16; x++) - s << std::hex << std::setw(2) << std::setfill('0') << (unsigned int) mRandomData[x]; - s << " dst="; - for(x=0; x<16; x++) - s << std::hex << std::setw(2) << std::setfill('0') << (unsigned int) mTemp[x]; - s << " dstRef="; - for(x=0; x<16; x++) - s << std::hex << std::setw(2) << std::setfill('0') << (unsigned int) mTemp2[x]; - s << " "; - - // Compare result - StringStream msg; - msg << "Conversion mismatch [" << PixelUtil::getFormatName(srcFormat) << - "->" << PixelUtil::getFormatName(dstFormat) << "] " << s.str(); - EXPECT_TRUE(memcmp(mDst1.data, mDst2.data, eob) == 0) << msg.str().c_str(); -} -//-------------------------------------------------------------------------- -TEST_F(PixelFormatTests,BulkConversion) -{ - // Self match - testCase(PF_A8R8G8B8, PF_A8R8G8B8); - - // Optimized - testCase(PF_A8R8G8B8,PF_A8B8G8R8); - testCase(PF_A8R8G8B8,PF_B8G8R8A8); - testCase(PF_A8R8G8B8,PF_R8G8B8A8); - testCase(PF_A8B8G8R8,PF_A8R8G8B8); - testCase(PF_A8B8G8R8,PF_B8G8R8A8); - testCase(PF_A8B8G8R8,PF_R8G8B8A8); - testCase(PF_B8G8R8A8,PF_A8R8G8B8); - testCase(PF_B8G8R8A8,PF_A8B8G8R8); - testCase(PF_B8G8R8A8,PF_R8G8B8A8); - testCase(PF_R8G8B8A8,PF_A8R8G8B8); - testCase(PF_R8G8B8A8,PF_A8B8G8R8); - testCase(PF_R8G8B8A8,PF_B8G8R8A8); - - testCase(PF_A8B8G8R8, PF_R8); - testCase(PF_R8, PF_A8B8G8R8); - testCase(PF_A8R8G8B8, PF_R8); - testCase(PF_R8, PF_A8R8G8B8); - testCase(PF_B8G8R8A8, PF_R8); - testCase(PF_R8, PF_B8G8R8A8); - - testCase(PF_A8B8G8R8, PF_L8); - testCase(PF_L8, PF_A8B8G8R8); - testCase(PF_A8R8G8B8, PF_L8); - testCase(PF_L8, PF_A8R8G8B8); - testCase(PF_B8G8R8A8, PF_L8); - testCase(PF_L8, PF_B8G8R8A8); - testCase(PF_L8, PF_L16); - testCase(PF_L16, PF_L8); - testCase(PF_R8G8B8, PF_B8G8R8); - testCase(PF_B8G8R8, PF_R8G8B8); - testCase(PF_B8G8R8, PF_R8G8B8); - testCase(PF_R8G8B8, PF_B8G8R8); - testCase(PF_R8G8B8, PF_A8R8G8B8); - testCase(PF_B8G8R8, PF_A8R8G8B8); - testCase(PF_R8G8B8, PF_A8B8G8R8); - testCase(PF_B8G8R8, PF_A8B8G8R8); - testCase(PF_R8G8B8, PF_B8G8R8A8); - testCase(PF_B8G8R8, PF_B8G8R8A8); - testCase(PF_A8R8G8B8, PF_R8G8B8); - testCase(PF_A8R8G8B8, PF_B8G8R8); - testCase(PF_X8R8G8B8, PF_A8R8G8B8); - testCase(PF_X8R8G8B8, PF_A8B8G8R8); - testCase(PF_X8R8G8B8, PF_B8G8R8A8); - testCase(PF_X8R8G8B8, PF_R8G8B8A8); - testCase(PF_X8B8G8R8, PF_A8R8G8B8); - testCase(PF_X8B8G8R8, PF_A8B8G8R8); - testCase(PF_X8B8G8R8, PF_B8G8R8A8); - testCase(PF_X8B8G8R8, PF_R8G8B8A8); -} -//-------------------------------------------------------------------------- - diff --git a/Tests/OgreMain/src/PluginTests.cpp b/Tests/OgreMain/src/PluginTests.cpp deleted file mode 100644 index 2b9bc4f2bb8..00000000000 --- a/Tests/OgreMain/src/PluginTests.cpp +++ /dev/null @@ -1,71 +0,0 @@ - -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#include - -#include -#include -#include -#include - -#include "RootWithoutRenderSystemFixture.h" - -using namespace Ogre; - -typedef RootWithoutRenderSystemFixture DotSceneTests; - -TEST_F(DotSceneTests, exportImport) -{ - String pluginsCfg = mFSLayer->getConfigFilePath("plugins.cfg"); - ConfigFile cf; - cf.load(pluginsCfg); - - auto pluginDir = cf.getSetting("PluginFolder"); - - try - { - mRoot->loadPlugin(pluginDir+"/Plugin_DotScene"); - } - catch (const std::exception& e) - { - GTEST_SKIP() << "Plugin_DotScene not found"; - } - - mRoot->getInstalledPlugins().front()->initialise(); - - auto sceneMgr = mRoot->createSceneManager(); - auto entity = sceneMgr->createEntity("Entity", "jaiqua.mesh"); - auto entityUnlit = sceneMgr->createEntity("EntityUnlit", "jaiqua.mesh"); - entityUnlit->setMaterialName("BaseWhiteNoLighting"); - auto camera = sceneMgr->createCamera("MainCamera"); - auto light = sceneMgr->createLight(); - sceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(1, 0, 0))->attachObject(entity); - sceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 1, 0))->attachObject(camera); - sceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 0, 1))->attachObject(light); - sceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(1, 1, 1))->attachObject(entityUnlit); - - sceneMgr->getRootSceneNode()->saveChildren("DotSceneTest.scene"); - - sceneMgr->clearScene(); - sceneMgr->destroyAllCameras(); - - EXPECT_TRUE(sceneMgr->getRootSceneNode()->getChildren().empty()); - - sceneMgr->getRootSceneNode()->loadChildren("DotSceneTest.scene"); - - EXPECT_EQ(sceneMgr->getRootSceneNode()->getChildren().size(), 4); - - for (auto c : sceneMgr->getRootSceneNode()->getChildren()) - EXPECT_EQ(dynamic_cast(c)->getAttachedObjects().size(), 1); - - EXPECT_TRUE(sceneMgr->getCamera("MainCamera")->getParentSceneNode()->getPosition() == Vector3(0, 1, 0)); - EXPECT_TRUE(sceneMgr->getEntity("Entity")->getParentSceneNode()->getPosition() == Vector3(1, 0, 0)); - EXPECT_EQ(sceneMgr->getEntity("EntityUnlit")->getSubEntity(0)->getMaterialName(), "BaseWhiteNoLighting"); - - FileSystemLayer::removeFile("DotSceneTest.scene"); - - mRoot->getInstalledPlugins().front()->shutdown(); -} \ No newline at end of file diff --git a/Tests/OgreMain/src/QuaternionTests.cpp b/Tests/OgreMain/src/QuaternionTests.cpp deleted file mode 100644 index 32aff4e5c40..00000000000 --- a/Tests/OgreMain/src/QuaternionTests.cpp +++ /dev/null @@ -1,137 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include -#include "OgreQuaternion.h" -#include "OgreVector.h" - -using namespace Ogre; - -TEST(QuaternionTests,Norm) -{ - EXPECT_NEAR(Quaternion(0, 2, 2, 2).Norm(), Vector3(2, 2, 2).length(), 1e-6); -} - -TEST(QuaternionTests,FromVectors) -{ - // VectorBase<3, Real>::getRotationTo tests - Vector3 list[][2] = - { - // Generate identity quaternions - { Vector3(1, 0, 0), Vector3(1, 0, 0) }, - { Vector3(2, 0, 0), Vector3(3, 0, 0) }, - // Generate 90-degree rotations - { Vector3(1, 0, 0), Vector3(0, 1, 0) }, - { Vector3(2, 0, 0), Vector3(0, 3, 0) }, - // Generate 180-degree rotations - { Vector3(1, 0, 0), Vector3(0, -1, 0) }, - { Vector3(2, 0, 0), Vector3(0, -3, 0) }, - // Some random test values - { Vector3(1, 2, 3), Vector3(-2, 1, 2) }, - { Vector3(2, -1, -3), Vector3(0, 1, -1) }, - { Vector3(100, 100, 0), Vector3(100, 100, 1) }, - { Vector3(10000, 10000, 0), Vector3(10000, 10000, 1) }, - }; - - for (size_t index = 0; index < sizeof(list) / sizeof(Vector3[2]); ++index) - { - Vector3 from = list[index][0]; - Vector3 to = list[index][1]; - Vector3 result = from.getRotationTo(to) * from; - EXPECT_TRUE(to.normalisedCopy().positionEquals(result.normalisedCopy())) << " index is " << index << std::endl; - EXPECT_NEAR(from.length(), result.length(), 1e-6) << " index is " << index << std::endl; - } - Vector3 list2[][2] = - { - // Edge cases, return IDENTITY, because there is no correct rotation - { Vector3(0, 0, 0), Vector3(1, 0, 0) }, - { Vector3(1, 0, 0), Vector3(0, 0, 0) }, - }; - for (size_t index = 0; index < sizeof(list2) / sizeof(Vector3[2]); ++index) - { - Vector3 from = list2[index][0]; - Vector3 to = list2[index][1]; - Quaternion quat = from.getRotationTo(to); - EXPECT_EQ(quat, Quaternion::IDENTITY) << " index is " << index << std::endl; - } -} - -TEST(QuaternionTests,Exp) -{ - /** Comparison values got from the Octave quaternion package. */ - - // Case a quaternion for which angle is 0 degrees. - Quaternion quatA(1., 0., 0., 0.); - Quaternion expQuatA = quatA.Exp(); - EXPECT_NEAR(expQuatA.w, 2.71828182845905, 1e-6); - EXPECT_NEAR(expQuatA.x, 0., 1e-6); - EXPECT_NEAR(expQuatA.y, 0., 1e-6); - EXPECT_NEAR(expQuatA.z, 0., 1e-6); - - // Case of a common quaternion (no specific rotation). - Quaternion quatB(0.2, 0.7, Ogre::Math::PI, 0.9); - Quaternion expQuatB = quatB.Exp(); - EXPECT_NEAR(expQuatB.w, -1.19693377635754, 1e-6); - EXPECT_NEAR(expQuatB.x, -0.05095014937169, 1e-6); - EXPECT_NEAR(expQuatB.y, -0.22866373566485, 1e-6); - EXPECT_NEAR(expQuatB.z, -0.06550733490645, 1e-6); - - // Normalised quaternion B. - quatB.normalise() ; - Quaternion expUnitQuatB = quatB.Exp(); - EXPECT_NEAR(expUnitQuatB.w, 0.575155457731263, 1e-6); - EXPECT_NEAR(expUnitQuatB.x, 0.186879761760123, 1e-6); - EXPECT_NEAR(expUnitQuatB.y, 0.838714409500305, 1e-6); - EXPECT_NEAR(expUnitQuatB.z, 0.240273979405873, 1e-6); -} - -TEST(QuaternionTests,Log) -{ - /** Comparison values got from the Octave quaternion package. */ - - // Case of a common quaternion (no specific rotation). - Quaternion quat(0.85, Ogre::Math::PI, 0.6, 0.2); - quat.normalise() ; - Quaternion logUnitQuat = quat.Log(); - EXPECT_NEAR(logUnitQuat.w, 0., 1e-6); - EXPECT_NEAR(logUnitQuat.x, 1.28572906735070, 1e-6); - EXPECT_NEAR(logUnitQuat.y, 0.24555616385496, 1e-6); - EXPECT_NEAR(logUnitQuat.z, 0.08185205461832, 1e-6); -} - -TEST(QuaternionTests, Precision) -{ - if(OGRE_DOUBLE_PRECISION == 0) - GTEST_SKIP() << "OGRE_DOUBLE_PRECISION required"; - - Quaternion rot(Radian(5), Vector3::UNIT_X); - Quaternion rot_inv(Radian(-5), Vector3::UNIT_X); - Vector3 v_s(0, 5e6, 0); - Vector3 v_e = rot * v_s; - v_e = rot_inv * v_e; - EXPECT_LE((v_s - v_e).length(), 0.6); -} \ No newline at end of file diff --git a/Tests/OgreMain/src/RadixSort.cpp b/Tests/OgreMain/src/RadixSort.cpp deleted file mode 100644 index 8d226350f96..00000000000 --- a/Tests/OgreMain/src/RadixSort.cpp +++ /dev/null @@ -1,207 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "RadixSortTests.h" -#include "OgreMath.h" -#include -#include "../../../OgreMain/src/OgreRadixSort.h" - -using namespace Ogre; - -// Register the test suite - -//-------------------------------------------------------------------------- -void RadixSortTests::SetUp() -{ srand(0); - -} -//-------------------------------------------------------------------------- -void RadixSortTests::TearDown() -{ -} -//-------------------------------------------------------------------------- -class FloatSortFunctor -{ -public: - float operator()(const float& p) const - { - return p; - } -}; -//-------------------------------------------------------------------------- -class IntSortFunctor -{ -public: - int operator()(const int& p) const - { - return p; - } -}; -//-------------------------------------------------------------------------- -class UnsignedIntSortFunctor -{ -public: - unsigned int operator()(const unsigned int& p) const - { - return p; - } -}; -//-------------------------------------------------------------------------- -TEST_F(RadixSortTests,FloatVector) -{ - std::vector container; - FloatSortFunctor func; - RadixSort, float, float> sorter; - - for (int i = 0; i < 1000; ++i) - { - container.push_back((float)Math::RangeRandom(-1e10, 1e10)); - } - - sorter.sort(container, func); - - std::vector::iterator v = container.begin(); - float lastValue = *v++; - for (;v != container.end(); ++v) - { - EXPECT_TRUE(*v >= lastValue); - lastValue = *v; - } -} -//-------------------------------------------------------------------------- -TEST_F(RadixSortTests,FloatList) -{ - std::list container; - FloatSortFunctor func; - RadixSort, float, float> sorter; - - for (int i = 0; i < 1000; ++i) - { - container.push_back((float)Math::RangeRandom(-1e10, 1e10)); - } - - sorter.sort(container, func); - - std::list::iterator v = container.begin(); - float lastValue = *v++; - for (;v != container.end(); ++v) - { - EXPECT_TRUE(*v >= lastValue); - lastValue = *v; - } -} -//-------------------------------------------------------------------------- -TEST_F(RadixSortTests,UnsignedIntList) -{ - std::list container; - UnsignedIntSortFunctor func; - RadixSort, unsigned int, unsigned int> sorter; - - for (int i = 0; i < 1000; ++i) - { - container.push_back((unsigned int)Math::RangeRandom(0, float(UINT_MAX))); - } - - sorter.sort(container, func); - - std::list::iterator v = container.begin(); - unsigned int lastValue = *v++; - for (;v != container.end(); ++v) - { - EXPECT_TRUE(*v >= lastValue); - lastValue = *v; - } -} -//-------------------------------------------------------------------------- -TEST_F(RadixSortTests,IntList) -{ - std::list container; - IntSortFunctor func; - RadixSort, int, int> sorter; - - for (int i = 0; i < 1000; ++i) - { - container.push_back((int)Math::RangeRandom(float(INT_MIN), float(INT_MAX))); - } - - sorter.sort(container, func); - - std::list::iterator v = container.begin(); - int lastValue = *v++; - for (;v != container.end(); ++v) - { - EXPECT_TRUE(*v >= lastValue); - lastValue = *v; - } -} -//-------------------------------------------------------------------------- -TEST_F(RadixSortTests,UnsignedIntVector) -{ - std::vector container; - UnsignedIntSortFunctor func; - RadixSort, unsigned int, unsigned int> sorter; - - for (int i = 0; i < 1000; ++i) - { - container.push_back((unsigned int)Math::RangeRandom(0, float(UINT_MAX))); - } - - sorter.sort(container, func); - - std::vector::iterator v = container.begin(); - unsigned int lastValue = *v++; - for (;v != container.end(); ++v) - { - EXPECT_TRUE(*v >= lastValue); - lastValue = *v; - } -} -//-------------------------------------------------------------------------- -TEST_F(RadixSortTests,IntVector) -{ - std::vector container; - IntSortFunctor func; - RadixSort, int, int> sorter; - - for (int i = 0; i < 1000; ++i) - { - container.push_back((int)Math::RangeRandom(float(INT_MIN), float(INT_MAX))); - } - - sorter.sort(container, func); - - std::vector::iterator v = container.begin(); - int lastValue = *v++; - for (;v != container.end(); ++v) - { - EXPECT_TRUE(*v >= lastValue); - lastValue = *v; - } -} -//-------------------------------------------------------------------------- - - diff --git a/Tests/OgreMain/src/RenderSystemCapabilitiesTests.cpp b/Tests/OgreMain/src/RenderSystemCapabilitiesTests.cpp deleted file mode 100644 index 44d0cb64ed9..00000000000 --- a/Tests/OgreMain/src/RenderSystemCapabilitiesTests.cpp +++ /dev/null @@ -1,602 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "RenderSystemCapabilitiesTests.h" -#include "OgreRenderSystemCapabilities.h" -#include "OgreRenderSystemCapabilitiesManager.h" -#include "OgreStringConverter.h" -#include "OgreRenderSystemCapabilitiesSerializer.h" -#include "OgreArchiveManager.h" -#include "OgreLogManager.h" -#include "OgreConfigFile.h" -#include "OgreFileSystemLayer.h" - -#include -#include - -// Register the test suite - -//-------------------------------------------------------------------------- -void RenderSystemCapabilitiesTests::SetUp() -{ - using namespace Ogre; - - // We need to be able to create FileSystem archives to load .rendercaps - mFileSystemArchiveFactory = OGRE_NEW FileSystemArchiveFactory(); - - mArchiveManager = OGRE_NEW ArchiveManager(); - ArchiveManager::getSingleton().addArchiveFactory(mFileSystemArchiveFactory); - - mRenderSystemCapabilitiesManager = OGRE_NEW RenderSystemCapabilitiesManager(); - - Ogre::ConfigFile cf; - cf.load(Ogre::FileSystemLayer(OGRE_VERSION_NAME).getConfigFilePath("resources.cfg")); - Ogre::String testPath = cf.getSettings("Tests").begin()->second+"/CustomCapabilities"; - - // Actual parsing happens here. The following test methods confirm parse results only. - mRenderSystemCapabilitiesManager->parseCapabilitiesFromArchive(testPath, "FileSystem", true); -} -//-------------------------------------------------------------------------- -void RenderSystemCapabilitiesTests::TearDown() -{ - OGRE_DELETE mRenderSystemCapabilitiesManager; - OGRE_DELETE mArchiveManager; - OGRE_DELETE mFileSystemArchiveFactory; -} -//-------------------------------------------------------------------------- -TEST_F(RenderSystemCapabilitiesTests,IsShaderProfileSupported) -{ - // create a new RSC - Ogre::RenderSystemCapabilities rsc; - - // check that no shader profile is supported - EXPECT_TRUE(!rsc.isShaderProfileSupported("vs_1")); - EXPECT_TRUE(!rsc.isShaderProfileSupported("ps_1_1")); - EXPECT_TRUE(!rsc.isShaderProfileSupported("fp1")); - - rsc.addShaderProfile("vs_1"); - rsc.addShaderProfile("fp1"); - - // check that the added shader profiles are supported - EXPECT_TRUE(rsc.isShaderProfileSupported("vs_1")); - EXPECT_TRUE(rsc.isShaderProfileSupported("fp1")); - - - // check that non added profile is not supported - EXPECT_TRUE(!rsc.isShaderProfileSupported("ps_1_1")); - - - // check that empty string is not supported - EXPECT_TRUE(!rsc.isShaderProfileSupported("")); -} -//-------------------------------------------------------------------------- -TEST_F(RenderSystemCapabilitiesTests,HasCapability) -{ - RenderSystemCapabilities rsc; - - // check that no caps (from 2 categories) are supported - EXPECT_TRUE(!rsc.hasCapability(RSC_TWO_SIDED_STENCIL)); - EXPECT_TRUE(!rsc.hasCapability(RSC_MIPMAP_LOD_BIAS)); - EXPECT_TRUE(!rsc.hasCapability(RSC_TEXTURE_COMPRESSION)); - EXPECT_TRUE(!rsc.hasCapability(RSC_TEXTURE_COMPRESSION_VTC)); - EXPECT_TRUE(!rsc.hasCapability(RSC_PBUFFER)); - - // add support for few caps from each category - rsc.setCapability(RSC_TEXTURE_COMPRESSION); - - // check that the newly set caps are supported - EXPECT_TRUE(rsc.hasCapability(RSC_TEXTURE_COMPRESSION)); - - // check that the non-set caps are NOT supported - EXPECT_TRUE(!rsc.hasCapability(RSC_TWO_SIDED_STENCIL)); - EXPECT_TRUE(!rsc.hasCapability(RSC_MIPMAP_LOD_BIAS)); - EXPECT_TRUE(!rsc.hasCapability(RSC_TEXTURE_COMPRESSION_VTC)); - EXPECT_TRUE(!rsc.hasCapability(RSC_PBUFFER)); -} -//-------------------------------------------------------------------------- -TEST_F(RenderSystemCapabilitiesTests,SerializeBlank) -{ - RenderSystemCapabilitiesManager* rscManager = RenderSystemCapabilitiesManager::getSingletonPtr(); - - RenderSystemCapabilities* rsc = rscManager->loadParsedCapabilities("TestCaps Blank"); - - // if we have a non-NULL it's good enough - EXPECT_TRUE(rsc != 0); -} -//-------------------------------------------------------------------------- -TEST_F(RenderSystemCapabilitiesTests,SerializeEnumCapability) -{ - RenderSystemCapabilitiesManager* rscManager = RenderSystemCapabilitiesManager::getSingletonPtr(); - - RenderSystemCapabilities* rsc = rscManager->loadParsedCapabilities("TestCaps enum Capabilities"); - - // confirm that RSC was loaded - EXPECT_TRUE(rsc != 0); - - // confirm that the contents are the same as in .rendercaps file - EXPECT_TRUE(rsc->hasCapability(RSC_AUTOMIPMAP_COMPRESSED)); -} -//-------------------------------------------------------------------------- -TEST_F(RenderSystemCapabilitiesTests,SerializeStringCapability) -{ - RenderSystemCapabilitiesManager* rscManager = RenderSystemCapabilitiesManager::getSingletonPtr(); - - RenderSystemCapabilities* rsc = rscManager->loadParsedCapabilities("TestCaps set String"); - - // confirm that RSC was loaded - EXPECT_TRUE(rsc != 0); - - EXPECT_TRUE(rsc->isShaderProfileSupported("vs99")); -} -//-------------------------------------------------------------------------- -TEST_F(RenderSystemCapabilitiesTests,SerializeBoolCapability) -{ - RenderSystemCapabilitiesManager* rscManager = RenderSystemCapabilitiesManager::getSingletonPtr(); - - RenderSystemCapabilities* rscTrue = rscManager->loadParsedCapabilities("TestCaps set bool (true)"); - RenderSystemCapabilities* rscFalse = rscManager->loadParsedCapabilities("TestCaps set bool (false)"); - - // confirm that RSC was loaded - EXPECT_TRUE(rscTrue != 0); - EXPECT_TRUE(rscFalse != 0); -} -//-------------------------------------------------------------------------- -TEST_F(RenderSystemCapabilitiesTests,SerializeIntCapability) -{ - RenderSystemCapabilitiesManager* rscManager = RenderSystemCapabilitiesManager::getSingletonPtr(); - - RenderSystemCapabilities* rsc = rscManager->loadParsedCapabilities("TestCaps set int"); - - // confirm that RSC was loaded - EXPECT_TRUE(rsc != 0); - - // TODO: why no get? - EXPECT_TRUE(rsc->getNumMultiRenderTargets() == 99); -} -//-------------------------------------------------------------------------- -TEST_F(RenderSystemCapabilitiesTests,SerializeRealCapability) -{ - RenderSystemCapabilitiesManager* rscManager = RenderSystemCapabilitiesManager::getSingletonPtr(); - - RenderSystemCapabilities* rsc = rscManager->loadParsedCapabilities("TestCaps set Real"); - - // confirm that RSC was loaded - EXPECT_TRUE(rsc != 0); - - EXPECT_TRUE(rsc->getMaxPointSize() == 99.5); -} -//-------------------------------------------------------------------------- -TEST_F(RenderSystemCapabilitiesTests,SerializeShaderCapability) -{ - RenderSystemCapabilitiesManager* rscManager = RenderSystemCapabilitiesManager::getSingletonPtr(); - - RenderSystemCapabilities* rsc = rscManager->loadParsedCapabilities("TestCaps addShaderProfile"); - - // confirm that RSC was loaded - EXPECT_TRUE(rsc != 0); - - EXPECT_TRUE(rsc->isShaderProfileSupported("vp1")); - EXPECT_TRUE(rsc->isShaderProfileSupported("vs_1_1")); - EXPECT_TRUE(rsc->isShaderProfileSupported("ps_99")); -} -//-------------------------------------------------------------------------- -TEST_F(RenderSystemCapabilitiesTests,WriteSimpleCapabilities) -{ - using namespace Ogre; - using namespace std; - String name = "simple caps"; - String filename = "simpleCapsTest.rendercaps"; - - // set up caps of every type - RenderSystemCapabilitiesSerializer serializer; - RenderSystemCapabilities caps; - caps.setMaxPointSize(10.5); - caps.addShaderProfile("vs999"); - caps.addShaderProfile("sp999"); - - // write them to file - serializer.writeScript(&caps, name, filename); - - // read them back - ifstream capsfile(filename.c_str()); - char buff[255]; - - capsfile.getline(buff, 255); - EXPECT_EQ(String("render_system_capabilities \"") + name + "\"", String(buff)); - - capsfile.getline(buff, 255); - EXPECT_EQ(String("{"), String(buff)); - - // scan every line and find the set capabilities it them - std::vector lines; - while(capsfile.good()) - { - capsfile.getline(buff, 255); - lines.push_back(String(buff)); - } - - // check that the file is closed nicely - String closeBracket = *(lines.end() - 2); - EXPECT_EQ(String("}"), closeBracket); - EXPECT_EQ(String(""), lines.back()); - - // check that all the set caps are there - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tmax_point_size 10.5") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tshader_profile sp999") != lines.end()); -} -//-------------------------------------------------------------------------- -TEST_F(RenderSystemCapabilitiesTests,WriteAllFalseCapabilities) -{ - using namespace Ogre; - using namespace std; - String name = "all false caps"; - String filename = "allFalseCapsTest.rendercaps"; - - // set up caps of every type - RenderSystemCapabilitiesSerializer serializer; - RenderSystemCapabilities caps; - - // write them to file - serializer.writeScript(&caps, name, filename); - - // read them back - ifstream capsfile(filename.c_str()); - char buff[255]; - - capsfile.getline(buff, 255); - EXPECT_EQ(String("render_system_capabilities \"") + name + "\"", String(buff)); - - capsfile.getline(buff, 255); - EXPECT_EQ(String("{"), String(buff)); - - // scan every line and find the set capabilities it them - std::vector lines; - while(capsfile.good()) - { - capsfile.getline(buff, 255); - lines.push_back(String(buff)); - } - - // check that the file is closed nicely - String closeBracket = *(lines.end() - 2); - EXPECT_EQ(String("}"), closeBracket); - EXPECT_EQ(String(""), lines.back()); - - // confirm every caps - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tautomipmap_compressed false") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tanisotropy false") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\thwstencil false") != lines.end()); - - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tvertex_program false") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\ttwo_sided_stencil false") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tstencil_wrap false") != lines.end()); - - EXPECT_TRUE(find(lines.begin(), lines.end(), "\thwocclusion false") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tuser_clip_planes false") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\thwrender_to_texture false") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\ttexture_float false") != lines.end()); - - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tnon_power_of_2_textures false") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\ttexture_3d false") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tpoint_sprites false") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tvertex_texture_fetch false") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tmipmap_lod_bias false") != lines.end()); - - EXPECT_TRUE(find(lines.begin(), lines.end(), "\ttexture_compression false") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\ttexture_compression_dxt false") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\ttexture_compression_vtc false") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\ttexture_compression_pvrtc false") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\ttexture_compression_bc4_bc5 false") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\ttexture_compression_bc6h_bc7 false") != lines.end()); - - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tpbuffer false") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tperstageconstant false") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tseparate_shader_objects false") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tvao false") != lines.end()); -} -//-------------------------------------------------------------------------- -TEST_F(RenderSystemCapabilitiesTests,WriteAllTrueCapabilities) -{ - using namespace Ogre; - using namespace std; - String name = "all false caps"; - String filename = "allFalseCapsTest.rendercaps"; - - // set up caps of every type - RenderSystemCapabilitiesSerializer serializer; - RenderSystemCapabilities caps; - - // set all caps - caps.setCapability(RSC_AUTOMIPMAP_COMPRESSED); - caps.setCapability(RSC_ANISOTROPY); - caps.setCapability(RSC_HWSTENCIL); - - caps.setCapability(RSC_TWO_SIDED_STENCIL); - caps.setCapability(RSC_STENCIL_WRAP); - - caps.setCapability(RSC_HWOCCLUSION); - caps.setCapability(RSC_USER_CLIP_PLANES); - caps.setCapability(RSC_HWRENDER_TO_TEXTURE); - caps.setCapability(RSC_TEXTURE_FLOAT); - - caps.setCapability(RSC_NON_POWER_OF_2_TEXTURES); - caps.setCapability(RSC_TEXTURE_3D); - caps.setCapability(RSC_POINT_SPRITES); - caps.setCapability(RSC_VERTEX_TEXTURE_FETCH); - caps.setCapability(RSC_MIPMAP_LOD_BIAS); - - caps.setCapability(RSC_TEXTURE_COMPRESSION); - caps.setCapability(RSC_TEXTURE_COMPRESSION_DXT); - caps.setCapability(RSC_TEXTURE_COMPRESSION_VTC); - caps.setCapability(RSC_TEXTURE_COMPRESSION_PVRTC); - caps.setCapability(RSC_TEXTURE_COMPRESSION_BC4_BC5); - caps.setCapability(RSC_TEXTURE_COMPRESSION_BC6H_BC7); - - caps.setCapability(RSC_PBUFFER); - caps.setCapability(RSC_PERSTAGECONSTANT); - caps.setCapability(RSC_SEPARATE_SHADER_OBJECTS); - caps.setCapability(RSC_VAO); - - // write them to file - serializer.writeScript(&caps, name, filename); - - // read them back - ifstream capsfile(filename.c_str()); - char buff[255]; - - capsfile.getline(buff, 255); - EXPECT_EQ(String("render_system_capabilities \"") + name + "\"", String(buff)); - - capsfile.getline(buff, 255); - EXPECT_EQ(String("{"), String(buff)); - - // scan every line and find the set capabilities it them - std::vector lines; - while(capsfile.good()) - { - capsfile.getline(buff, 255); - lines.push_back(String(buff)); - } - - // check that the file is closed nicely - String closeBracket = *(lines.end() - 2); - EXPECT_EQ(String("}"), closeBracket); - EXPECT_EQ(String(""), lines.back()); - - // confirm all caps - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tautomipmap_compressed true") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tanisotropy true") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\thwstencil true") != lines.end()); - - EXPECT_TRUE(find(lines.begin(), lines.end(), "\ttwo_sided_stencil true") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tstencil_wrap true") != lines.end()); - - EXPECT_TRUE(find(lines.begin(), lines.end(), "\thwocclusion true") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tuser_clip_planes true") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\thwrender_to_texture true") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\ttexture_float true") != lines.end()); - - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tnon_power_of_2_textures true") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\ttexture_3d true") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tpoint_sprites true") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tvertex_texture_fetch true") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tmipmap_lod_bias true") != lines.end()); - - EXPECT_TRUE(find(lines.begin(), lines.end(), "\ttexture_compression true") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\ttexture_compression_dxt true") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\ttexture_compression_vtc true") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\ttexture_compression_pvrtc true") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\ttexture_compression_bc4_bc5 true") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\ttexture_compression_bc6h_bc7 true") != lines.end()); - - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tpbuffer true") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tperstageconstant true") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tseparate_shader_objects true") != lines.end()); - EXPECT_TRUE(find(lines.begin(), lines.end(), "\tvao true") != lines.end()); -} -//-------------------------------------------------------------------------- -TEST_F(RenderSystemCapabilitiesTests,WriteAndReadComplexCapabilities) -{ - using namespace Ogre; - using namespace std; - String name = "complex caps"; - String filename = "complexCapsTest.rendercaps"; - - // set up caps of every type - RenderSystemCapabilitiesSerializer serializer; - RenderSystemCapabilities caps; - - // set all caps - caps.setCapability(RSC_HWSTENCIL); - caps.setCapability(RSC_TWO_SIDED_STENCIL); - caps.setCapability(RSC_HWOCCLUSION); - caps.setCapability(RSC_HWRENDER_TO_TEXTURE); - caps.setCapability(RSC_TEXTURE_FLOAT); - caps.setCapability(RSC_NON_POWER_OF_2_TEXTURES); - caps.setCapability(RSC_TEXTURE_3D); - caps.setCapability(RSC_MIPMAP_LOD_BIAS); - caps.setCapability(RSC_TEXTURE_COMPRESSION); - caps.setCapability(RSC_TEXTURE_COMPRESSION_DXT); - caps.setCapability(RSC_TEXTURE_COMPRESSION_VTC); - caps.setCapability(RSC_TEXTURE_COMPRESSION_PVRTC); - caps.setCapability(RSC_TEXTURE_COMPRESSION_BC4_BC5); - caps.setCapability(RSC_TEXTURE_COMPRESSION_BC6H_BC7); - caps.setCapability(RSC_PERSTAGECONSTANT); - caps.setCapability(RSC_SEPARATE_SHADER_OBJECTS); - caps.setCapability(RSC_VAO); - - caps.setNumTextureUnits(22); - caps.setNumMultiRenderTargets(23); - - caps.addShaderProfile("99foo100"); - - // try out stranger names - caps.addShaderProfile("..f(_)specialsymbolextravaganza!@#$%^&*_but_no_spaces"); - - caps.setVertexProgramConstantFloatCount(1111); - caps.setFragmentProgramConstantFloatCount(4444); - - caps.setMaxPointSize(123.75); - caps.setNonPOW2TexturesLimited(true); - - DriverVersion driverversion; - driverversion.major = 11; - driverversion.minor = 13; - driverversion.release = 17; - driverversion.build = 0; - - caps.setDriverVersion(driverversion); - caps.setDeviceName("Dummy Device"); - caps.setRenderSystemName("Dummy RenderSystem"); - - // write them to file - serializer.writeScript(&caps, name, filename); - - FileStreamDataStream* fdatastream = new FileStreamDataStream(filename, - OGRE_NEW_T(ifstream, MEMCATEGORY_GENERAL)(filename.c_str())); - - DataStreamPtr dataStreamPtr(fdatastream); - - // parsing does not return a raw RSC, but adds it to the Manager - serializer.parseScript(dataStreamPtr); - - RenderSystemCapabilitiesManager* rscManager = RenderSystemCapabilitiesManager::getSingletonPtr(); - - RenderSystemCapabilities* rsc = rscManager->loadParsedCapabilities(name); - // confirm that RSC was loaded - EXPECT_TRUE(rsc != 0); - - // create a reference, so that were are working with two refs - RenderSystemCapabilities& caps2 = *rsc; - - EXPECT_EQ(caps.hasCapability(RSC_ANISOTROPY), caps2.hasCapability(RSC_ANISOTROPY)); - EXPECT_EQ(caps.hasCapability(RSC_HWSTENCIL), caps2.hasCapability(RSC_HWSTENCIL)); - - EXPECT_EQ(caps.hasCapability(RSC_TWO_SIDED_STENCIL), caps2.hasCapability(RSC_TWO_SIDED_STENCIL)); - EXPECT_EQ(caps.hasCapability(RSC_STENCIL_WRAP), caps2.hasCapability(RSC_STENCIL_WRAP)); - - EXPECT_EQ(caps.hasCapability(RSC_HWOCCLUSION), caps2.hasCapability(RSC_HWOCCLUSION)); - EXPECT_EQ(caps.hasCapability(RSC_USER_CLIP_PLANES), caps2.hasCapability(RSC_USER_CLIP_PLANES)); - EXPECT_EQ(caps.hasCapability(RSC_HWRENDER_TO_TEXTURE), caps2.hasCapability(RSC_HWRENDER_TO_TEXTURE)); - EXPECT_EQ(caps.hasCapability(RSC_TEXTURE_FLOAT), caps2.hasCapability(RSC_TEXTURE_FLOAT)); - - EXPECT_EQ(caps.hasCapability(RSC_NON_POWER_OF_2_TEXTURES), caps2.hasCapability(RSC_NON_POWER_OF_2_TEXTURES)); - EXPECT_EQ(caps.hasCapability(RSC_TEXTURE_3D), caps2.hasCapability(RSC_TEXTURE_3D)); - EXPECT_EQ(caps.hasCapability(RSC_POINT_SPRITES), caps2.hasCapability(RSC_POINT_SPRITES)); - EXPECT_EQ(caps.hasCapability(RSC_VERTEX_TEXTURE_FETCH), caps2.hasCapability(RSC_VERTEX_TEXTURE_FETCH)); - EXPECT_EQ(caps.hasCapability(RSC_MIPMAP_LOD_BIAS), caps2.hasCapability(RSC_MIPMAP_LOD_BIAS)); - - EXPECT_EQ(caps.hasCapability(RSC_TEXTURE_COMPRESSION), caps2.hasCapability(RSC_TEXTURE_COMPRESSION)); - EXPECT_EQ(caps.hasCapability(RSC_TEXTURE_COMPRESSION_DXT), caps2.hasCapability(RSC_TEXTURE_COMPRESSION_DXT)); - EXPECT_EQ(caps.hasCapability(RSC_TEXTURE_COMPRESSION_VTC), caps2.hasCapability(RSC_TEXTURE_COMPRESSION_VTC)); - EXPECT_EQ(caps.hasCapability(RSC_TEXTURE_COMPRESSION_PVRTC), caps2.hasCapability(RSC_TEXTURE_COMPRESSION_PVRTC)); - EXPECT_EQ(caps.hasCapability(RSC_TEXTURE_COMPRESSION_BC4_BC5), caps2.hasCapability(RSC_TEXTURE_COMPRESSION_BC4_BC5)); - EXPECT_EQ(caps.hasCapability(RSC_TEXTURE_COMPRESSION_BC6H_BC7), caps2.hasCapability(RSC_TEXTURE_COMPRESSION_BC6H_BC7)); - - EXPECT_EQ(caps.hasCapability(RSC_PBUFFER), caps2.hasCapability(RSC_PBUFFER)); - EXPECT_EQ(caps.hasCapability(RSC_PERSTAGECONSTANT), caps2.hasCapability(RSC_PERSTAGECONSTANT)); - EXPECT_EQ(caps.hasCapability(RSC_SEPARATE_SHADER_OBJECTS), caps2.hasCapability(RSC_SEPARATE_SHADER_OBJECTS)); - EXPECT_EQ(caps.hasCapability(RSC_VAO), caps2.hasCapability(RSC_VAO)); - - EXPECT_EQ(caps.getNumTextureUnits(), caps2.getNumTextureUnits()); - EXPECT_EQ(caps.getNumMultiRenderTargets(), caps2.getNumMultiRenderTargets()); - - EXPECT_EQ(caps.getConstantFloatCount(GPT_VERTEX_PROGRAM), caps2.getConstantFloatCount(GPT_VERTEX_PROGRAM)); - EXPECT_EQ(caps.getConstantFloatCount(GPT_FRAGMENT_PROGRAM), caps2.getConstantFloatCount(GPT_FRAGMENT_PROGRAM)); - - EXPECT_EQ(caps.getMaxPointSize(), caps2.getMaxPointSize()); - EXPECT_EQ(caps.getNonPOW2TexturesLimited(), caps2.getNonPOW2TexturesLimited()); - - // test versions - EXPECT_EQ(caps.getDriverVersion().major, caps2.getDriverVersion().major); - EXPECT_EQ(caps.getDriverVersion().minor, caps2.getDriverVersion().minor); - EXPECT_EQ(caps.getDriverVersion().release, caps2.getDriverVersion().release); - EXPECT_EQ(0, caps2.getDriverVersion().build); - - dataStreamPtr.reset(); -} -//-------------------------------------------------------------------------- -TEST_F(RenderSystemCapabilitiesTests, CustomCapabilities) -{ - using namespace Ogre; - - Ogre::ConfigFile cf; - cf.load(Ogre::FileSystemLayer(OGRE_VERSION_NAME).getConfigFilePath("resources.cfg")); - Ogre::String testPath = cf.getSettings("Tests").begin()->second+"/CustomCapabilities/customCapabilitiesTest.cfg"; - - auto caps = RenderSystemCapabilitiesManager::getSingleton().loadCapabilitiesConfig(testPath); - - EXPECT_EQ(caps->hasCapability(RSC_ANISOTROPY), true); - EXPECT_EQ(caps->hasCapability(RSC_HWSTENCIL), true); - - EXPECT_EQ(caps->hasCapability(RSC_TWO_SIDED_STENCIL), true); - EXPECT_EQ(caps->hasCapability(RSC_STENCIL_WRAP), true); - - EXPECT_EQ(caps->hasCapability(RSC_HWOCCLUSION), true); - EXPECT_EQ(caps->hasCapability(RSC_USER_CLIP_PLANES), true); - EXPECT_EQ(caps->hasCapability(RSC_HWRENDER_TO_TEXTURE), true); - EXPECT_EQ(caps->hasCapability(RSC_TEXTURE_FLOAT), true); - - EXPECT_EQ(caps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES), false); - EXPECT_EQ(caps->hasCapability(RSC_TEXTURE_3D), true); - EXPECT_EQ(caps->hasCapability(RSC_POINT_SPRITES), true); - EXPECT_EQ(caps->hasCapability(RSC_VERTEX_TEXTURE_FETCH), false); - EXPECT_EQ(caps->hasCapability(RSC_MIPMAP_LOD_BIAS), true); - - EXPECT_EQ(caps->hasCapability(RSC_TEXTURE_COMPRESSION), true); - EXPECT_EQ(caps->hasCapability(RSC_TEXTURE_COMPRESSION_DXT), true); - EXPECT_EQ(caps->hasCapability(RSC_TEXTURE_COMPRESSION_VTC), false); - EXPECT_EQ(caps->hasCapability(RSC_TEXTURE_COMPRESSION_PVRTC), false); - EXPECT_EQ(caps->hasCapability(RSC_TEXTURE_COMPRESSION_BC4_BC5), false); - EXPECT_EQ(caps->hasCapability(RSC_TEXTURE_COMPRESSION_BC6H_BC7), false); - - EXPECT_EQ(caps->hasCapability(RSC_PBUFFER), false); - EXPECT_EQ(caps->hasCapability(RSC_PERSTAGECONSTANT), false); - EXPECT_EQ(caps->hasCapability(RSC_VAO), false); - EXPECT_EQ(caps->hasCapability(RSC_SEPARATE_SHADER_OBJECTS), false); - - EXPECT_TRUE(caps->isShaderProfileSupported("arbfp1")); - EXPECT_TRUE(caps->isShaderProfileSupported("arbvp1")); - EXPECT_TRUE(caps->isShaderProfileSupported("glsl")); - EXPECT_TRUE(caps->isShaderProfileSupported("ps_1_1")); - EXPECT_TRUE(caps->isShaderProfileSupported("ps_1_2")); - EXPECT_TRUE(caps->isShaderProfileSupported("ps_1_3")); - EXPECT_TRUE(caps->isShaderProfileSupported("ps_1_4")); - - EXPECT_EQ(caps->getMaxPointSize(), (Real)1024); - EXPECT_EQ(caps->getNonPOW2TexturesLimited(), false); - EXPECT_EQ(caps->getNumTextureUnits(), (Ogre::ushort)16); - EXPECT_EQ(caps->getNumMultiRenderTargets(), (Ogre::ushort)4); - - EXPECT_EQ(caps->getConstantFloatCount(GPT_VERTEX_PROGRAM), (Ogre::ushort)256); - EXPECT_EQ(caps->getConstantFloatCount(GPT_FRAGMENT_PROGRAM), (Ogre::ushort)64); - - EXPECT_EQ(caps->getNumVertexTextureUnits(), (Ogre::ushort)0); - EXPECT_TRUE(caps->isShaderProfileSupported("arbvp1")); - EXPECT_TRUE(caps->isShaderProfileSupported("arbfp1")); -} \ No newline at end of file diff --git a/Tests/OgreMain/src/ResourceLocationPriorityTest.cpp b/Tests/OgreMain/src/ResourceLocationPriorityTest.cpp deleted file mode 100644 index 10bfbac6636..00000000000 --- a/Tests/OgreMain/src/ResourceLocationPriorityTest.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2019 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include - -#include "ResourceLocationPriorityTest.h" -#include "RootWithoutRenderSystemFixture.h" - -#include "OgreArchiveManager.h" - -TEST(ResourceGroupLocationTest, ResourceLocationPriority) -{ - std::unique_ptr fact = std::unique_ptr(new DummyArchiveFactory); - Ogre::Root root(""); - Ogre::ArchiveManager& archiveMgr = Ogre::ArchiveManager::getSingleton(); - archiveMgr.addArchiveFactory(fact.get()); - - Ogre::ResourceGroupManager& resGrpMgr = Ogre::ResourceGroupManager::getSingleton(); - resGrpMgr.addResourceLocation("ResourceLocationPriority0", "DummyArchive"); - resGrpMgr.addResourceLocation("ResourceLocationPriority1", "DummyArchive"); - - Ogre::DataStreamPtr filePtr = resGrpMgr.openResource("dummyArchiveTest"); - EXPECT_TRUE(filePtr); - - unsigned char contents; - filePtr->read(&contents, 1); - // If the archive added first is returned then the file will contain 0x1, - // otherwise it will contain 0x2. - // Expect 0x1, as locations added first are preferred over locations added later. - EXPECT_EQ(contents, 1); - - resGrpMgr.removeResourceLocation("ResourceLocationPriority0"); - resGrpMgr.removeResourceLocation("ResourceLocationPriority1"); -} \ No newline at end of file diff --git a/Tests/OgreMain/src/RootWithoutRenderSystemFixture.cpp b/Tests/OgreMain/src/RootWithoutRenderSystemFixture.cpp deleted file mode 100644 index f51bc4a158d..00000000000 --- a/Tests/OgreMain/src/RootWithoutRenderSystemFixture.cpp +++ /dev/null @@ -1,47 +0,0 @@ -// This file is part of the OGRE project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at https://www.ogre3d.org/licensing. -// SPDX-License-Identifier: MIT - -#include "RootWithoutRenderSystemFixture.h" - -#include "Ogre.h" -#include "OgreDefaultHardwareBufferManager.h" - -using namespace Ogre; - -void RootWithoutRenderSystemFixture::SetUp() -{ - mFSLayer = new FileSystemLayer(OGRE_VERSION_NAME); - mRoot = new Root(""); - mHBM = new DefaultHardwareBufferManager; - - MaterialManager::getSingleton().initialise(); - - // Load resource paths from config file - ConfigFile cf; - String resourcesPath = mFSLayer->getConfigFilePath("resources.cfg"); - - cf.load(resourcesPath); - // Go through all sections & settings in the file - String secName, typeName, archName; - ConfigFile::SettingsBySection_::const_iterator seci; - for(seci = cf.getSettingsBySection().begin(); seci != cf.getSettingsBySection().end(); ++seci) { - secName = seci->first; - const ConfigFile::SettingsMultiMap& settings = seci->second; - ConfigFile::SettingsMultiMap::const_iterator i; - for (i = settings.begin(); i != settings.end(); ++i) - { - typeName = i->first; - archName = i->second; - ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName); - } - } -} - -void RootWithoutRenderSystemFixture::TearDown() -{ - delete mRoot; - delete mHBM; - delete mFSLayer; -} diff --git a/Tests/OgreMain/src/StreamSerialiserTests.cpp b/Tests/OgreMain/src/StreamSerialiserTests.cpp deleted file mode 100644 index d0215b033a7..00000000000 --- a/Tests/OgreMain/src/StreamSerialiserTests.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include -#include "OgreStreamSerialiser.h" -#include "OgreFileSystem.h" -#include "OgreException.h" -#include "OgreVector.h" - - -using namespace Ogre; - -//-------------------------------------------------------------------------- -TEST(StreamSerialiserTests,WriteBasic) -{ - FileSystemArchiveFactory factory; - Archive* arch = factory.createInstance("./", false); - arch->load(); - - String fileName = "testSerialiser.dat"; - Vector3 aTestVector(0.3, 15.2, -12.0); - String aTestString = "Some text here"; - int aTestValue = 99; - uint32 chunkID = StreamSerialiser::makeIdentifier("TEST"); - - // write the data - { - DataStreamPtr stream = arch->create(fileName); - - StreamSerialiser serialiser(stream); - - serialiser.writeChunkBegin(chunkID); - - serialiser.write(&aTestVector); - serialiser.write(&aTestString); - serialiser.write(&aTestValue); - serialiser.writeChunkEnd(chunkID); - } - - // read it back - { - DataStreamPtr stream = arch->open(fileName); - - StreamSerialiser serialiser(stream); - - const StreamSerialiser::Chunk* c = serialiser.readChunkBegin(); - - EXPECT_EQ(chunkID, c->id); - EXPECT_EQ(sizeof(Vector3) + sizeof(int) + aTestString.size() + 4, (size_t)c->length); - - Vector3 inVector; - String inString; - int inValue; - - serialiser.read(&inVector); - serialiser.read(&inString); - serialiser.read(&inValue); - serialiser.readChunkEnd(chunkID); - - EXPECT_EQ(aTestVector, inVector); - EXPECT_EQ(aTestString, inString); - EXPECT_EQ(aTestValue, inValue); - } - - arch->remove(fileName); - - EXPECT_TRUE(!arch->exists(fileName)); - - factory.destroyInstance(arch); -} -//-------------------------------------------------------------------------- diff --git a/Tests/OgreMain/src/StringTests.cpp b/Tests/OgreMain/src/StringTests.cpp deleted file mode 100755 index 18774603ae6..00000000000 --- a/Tests/OgreMain/src/StringTests.cpp +++ /dev/null @@ -1,290 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "StringTests.h" -#include "OgreStringConverter.h" -#include "OgreVector.h" -#include "OgreQuaternion.h" -#include "OgreMatrix4.h" -#include "OgreColourValue.h" - - -using namespace Ogre; - -// Register the test suite - -//-------------------------------------------------------------------------- -void StringTests::SetUp() -{ - testFileNoPath = "testfile.txt"; - testFileRelativePathUnix = "this/is/relative/testfile.txt"; - testFileRelativePathWindows = "this\\is\\relative\\testfile.txt"; - testFileAbsolutePathUnix = "/this/is/absolute/testfile.txt"; - testFileAbsolutePathWindows = "c:\\this\\is\\absolute\\testfile.txt"; - setlocale(LC_NUMERIC, ""); -} -//-------------------------------------------------------------------------- -void StringTests::TearDown() -{ -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,SplitBaseFilename) -{ - String base, ext; - - StringUtil::splitBaseFilename("basename.ext", base, ext); - EXPECT_EQ("basename", base); - EXPECT_EQ("ext", ext); - - StringUtil::splitBaseFilename("basename.", base, ext); - EXPECT_EQ("basename", base); - EXPECT_EQ("", ext); -} -TEST_F(StringTests,SplitFileNameNoPath) -{ - String basename, path; - StringUtil::splitFilename(testFileNoPath, basename, path); - - EXPECT_EQ(testFileNoPath, basename); - EXPECT_TRUE(path.empty()); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,SplitFileNameRelativePath) -{ - String basename, path; - - // Unix - StringUtil::splitFilename(testFileRelativePathUnix, basename, path); - EXPECT_EQ(String("testfile.txt"), basename); - EXPECT_EQ(String("this/is/relative/"), path); - - // Windows - StringUtil::splitFilename(testFileRelativePathWindows, basename, path); - EXPECT_EQ(String("testfile.txt"), basename); - EXPECT_EQ(String("this/is/relative/"), path); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,SplitFileNameAbsolutePath) -{ - String basename, path; - - // Unix - StringUtil::splitFilename(testFileAbsolutePathUnix, basename, path); - EXPECT_EQ(String("testfile.txt"), basename); - EXPECT_EQ(String("/this/is/absolute/"), path); - - // Windows - StringUtil::splitFilename(testFileAbsolutePathWindows, basename, path); - EXPECT_EQ(String("testfile.txt"), basename); - EXPECT_EQ(String("c:/this/is/absolute/"), path); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,MatchCaseSensitive) -{ - // Test positive - EXPECT_TRUE(StringUtil::match(testFileNoPath, testFileNoPath, true)); - - // Test negative - String upperCase = testFileNoPath; - StringUtil::toUpperCase(upperCase); - EXPECT_TRUE(!StringUtil::match(testFileNoPath, upperCase, true)); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,MatchCaseInSensitive) -{ - // Test positive - EXPECT_TRUE(StringUtil::match(testFileNoPath, testFileNoPath, false)); - - // Test positive - String upperCase = testFileNoPath; - StringUtil::toUpperCase(upperCase); - EXPECT_TRUE(StringUtil::match(testFileNoPath, upperCase, false)); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,MatchGlobAll) -{ - EXPECT_TRUE(StringUtil::match(testFileNoPath, "*", true)); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,MatchGlobStart) -{ - EXPECT_TRUE(StringUtil::match(testFileNoPath, "*stfile.txt", true)); - EXPECT_TRUE(!StringUtil::match(testFileNoPath, "*astfile.txt", true)); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,MatchGlobEnd) -{ - EXPECT_TRUE(StringUtil::match(testFileNoPath, "testfile.*", true)); - EXPECT_TRUE(!StringUtil::match(testFileNoPath, "testfile.d*", true)); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,MatchGlobStartAndEnd) -{ - EXPECT_TRUE(StringUtil::match(testFileNoPath, "*stfile.*", true)); - EXPECT_TRUE(!StringUtil::match(testFileNoPath, "*astfile.d*", true)); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,MatchGlobMiddle) -{ - EXPECT_TRUE(StringUtil::match(testFileNoPath, "test*.txt", true)); - EXPECT_TRUE(!StringUtil::match(testFileNoPath, "last*.txt*", true)); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,MatchSuperGlobtastic) -{ - EXPECT_TRUE(StringUtil::match(testFileNoPath, "*e*tf*e.t*t", true)); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,MatchSuperGlobEnd) -{ - EXPECT_TRUE(StringUtil::match("normal", "*normal*", true)); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,ParseReal) -{ - Real r = 23.454; - - String s = StringConverter::toString(r); - - EXPECT_EQ(r, StringConverter::parseReal(s)); - EXPECT_EQ(r, StringConverter::parseReal("23.454")); - EXPECT_NE(r, StringConverter::parseReal("23,454")); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,ParseInt32) -{ - int32 r = -223546; - - String s = StringConverter::toString(r); - int32 t = StringConverter::parseInt(s); - - EXPECT_EQ(r, t); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,ParseInt64) -{ - long r = -2147483647; - - String s = StringConverter::toString(r); - int64 t; - StringConverter::parse(s, t); - - EXPECT_EQ(r, t); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,ParseUInt64) -{ - uint64 r = ~0; - - String s = StringConverter::toString(r); - uint64 t; - StringConverter::parse(s, t); - - EXPECT_EQ(r, t); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,ParseSizeT) -{ - size_t r = ~0; - - String s = StringConverter::toString(r); - size_t t = StringConverter::parseSizeT(s); - - EXPECT_EQ(r, t); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,ParseVector3) -{ - Vector3 r(0.12, 3.22, -4.04); - - String s = StringConverter::toString(r); - Vector3 t = StringConverter::parseVector3(s); - - EXPECT_EQ(r, t); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,ParseMatrix4) -{ - Matrix4 r(1.12, 0, 0, 34, 0, 0.87, 0, 20, 0, 0, 0.56, 10, 0, 0, 0, 1); - - String s = StringConverter::toString(r); - Matrix4 t = StringConverter::parseMatrix4(s); - - EXPECT_EQ(r, t); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,ParseQuaternion) -{ - Quaternion r(1.12, 0.87, 0.67, 1); - - String s = StringConverter::toString(r); - Quaternion t = StringConverter::parseQuaternion(s); - - EXPECT_EQ(r, t); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,ParseBool) -{ - bool r = true; - String s = StringConverter::toString(r); - bool t = StringConverter::parseBool(s); - EXPECT_EQ(r, t); - - r = false; - s = StringConverter::toString(r); - t = StringConverter::parseBool(s); - EXPECT_EQ(r, t); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,ParseColourValue) -{ - ColourValue r(0.34, 0.44, 0.77, 1.0); - - String s = StringConverter::toString(r); - ColourValue t = StringConverter::parseColourValue(s); - EXPECT_EQ(r, t); -} -//-------------------------------------------------------------------------- -TEST_F(StringTests,EndsWith) -{ - String s = "Hello World!"; - - EXPECT_TRUE(StringUtil::endsWith(s, "world!")); - EXPECT_FALSE(StringUtil::endsWith(s, "hello")); - EXPECT_FALSE(StringUtil::endsWith(s, "world!", false)); - EXPECT_FALSE(StringUtil::endsWith(s, "", false)); -} - -TEST_F(StringTests,StartsWith) -{ - String s = "Hello World!"; - - EXPECT_TRUE(StringUtil::startsWith(s, "hello")); - EXPECT_FALSE(StringUtil::startsWith(s, "world")); - EXPECT_FALSE(StringUtil::startsWith(s, "hello", false)); - EXPECT_FALSE(StringUtil::startsWith(s, "", false)); -} diff --git a/Tests/OgreMain/src/VectorTests.cpp b/Tests/OgreMain/src/VectorTests.cpp deleted file mode 100644 index 400ab29f4ff..00000000000 --- a/Tests/OgreMain/src/VectorTests.cpp +++ /dev/null @@ -1,230 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include -#include "OgreVector.h" -#include "OgreMatrix4.h" - -using namespace Ogre; - -//-------------------------------------------------------------------------- -TEST(VectorTests,Vector2Scaler) -{ - EXPECT_EQ(Vector2(1, 1) + Vector2(2, 2), Vector2(3, 3)); - EXPECT_EQ(1 + Vector2(2), Vector2(3, 3)); - Vector2 v1; - v1 = Vector2(1); - EXPECT_EQ(v1, Vector2(1, 1)); - v1 = Vector2(0.0); - EXPECT_EQ(v1, Vector2::ZERO); - v1 += 3; - EXPECT_EQ(v1, Vector2(3, 3)); - - v1 = 3 - Vector2(2); - EXPECT_EQ(v1, Vector2(1)); - v1 = Vector2(5) - 7; - EXPECT_EQ(v1, Vector2(-2)); - v1 -= 4; - EXPECT_EQ(v1, Vector2(-6)); -} -//-------------------------------------------------------------------------- -TEST(VectorTests,Vector3Scaler) -{ - EXPECT_EQ(Vector3(1, 1, 1) + Vector3(2, 2, 2), Vector3(3, 3, 3)); - EXPECT_EQ(1 + Vector3(2), Vector3(3, 3, 3)); - Vector3 v1; - v1 = Vector3(1); - EXPECT_EQ(v1, Vector3(1)); - v1 = Vector3(0.0); - EXPECT_EQ(v1, Vector3::ZERO); - v1 += 3; - EXPECT_EQ(v1, Vector3(3)); - - v1 = 3 - Vector3(2); - EXPECT_EQ(v1, Vector3(1)); - v1 = Vector3(5) - 7; - EXPECT_EQ(v1, Vector3(-2)); - v1 -= 4; - EXPECT_EQ(v1, Vector3(-6)); -} -//-------------------------------------------------------------------------- -TEST(VectorTests,Vector4Scaler) -{ - EXPECT_EQ(Vector4(1, 1, 1, 1) + Vector4(2, 2, 2, 2), Vector4(3, 3, 3, 3)); - EXPECT_EQ(1 + Vector4(2, 2, 2, 2), Vector4(3, 3, 3, 3)); - Vector4 v1; - v1 = Vector4(1); - EXPECT_EQ(v1, Vector4(1, 1, 1, 1)); - v1 = Vector4(0.0); - EXPECT_EQ(v1, Vector4(0,0,0,0)); - v1 += 3; - EXPECT_EQ(v1, Vector4(3,3,3,3)); - - v1 = 3 - Vector4(2,2,2,2); - EXPECT_EQ(v1, Vector4(1,1,1,1)); - v1 = Vector4(5,5,5,5) - 7; - EXPECT_EQ(v1, Vector4(-2,-2,-2,-2)); - v1 -= 4; - EXPECT_EQ(v1, Vector4(-6,-6,-6,-6)); -} -//-------------------------------------------------------------------------- -TEST(VectorTests,PerpendicularVector) -{ - Vector3 v1(1, 0, 0); - Vector3 v2(0, 1, 0); - Vector3 v3(0, 0, 1); - - EXPECT_EQ(v1.dotProduct(v1.perpendicular()), (Real)0); - EXPECT_EQ(v2.dotProduct(v2.perpendicular()), (Real)0); - EXPECT_EQ(v3.dotProduct(v3.perpendicular()), (Real)0); - - EXPECT_EQ((v1 + v2).dotProduct((v1 + v2).perpendicular()), (Real)0); - EXPECT_EQ((v2 + v3).dotProduct((v2 + v3).perpendicular()), (Real)0); - EXPECT_EQ((v3 + v1).dotProduct((v3 + v1).perpendicular()), (Real)0); -} -//-------------------------------------------------------------------------- -TEST(VectorTests, Matrix4ArrayLoading) -{ - Real arr0[16] = { 1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1 }; - - Matrix4 mat0(arr0); - - EXPECT_EQ(1, mat0[0][0]); - EXPECT_EQ(1, mat0[1][1]); - EXPECT_EQ(1, mat0[2][2]); - EXPECT_EQ(1, mat0[3][3]); - - Real arr1[16] = { 0, 1, 2, 3, - 4, 5, 6, 7, - 8, 9, 10, 11, - 12, 13, 14, 15}; - - Matrix4 mat1(arr1); - - EXPECT_EQ(0, mat1[0][0]); - EXPECT_EQ(1, mat1[0][1]); - EXPECT_EQ(2, mat1[0][2]); - EXPECT_EQ(3, mat1[0][3]); - - EXPECT_EQ(4, mat1[1][0]); - EXPECT_EQ(5, mat1[1][1]); - EXPECT_EQ(6, mat1[1][2]); - EXPECT_EQ(7, mat1[1][3]); - - EXPECT_EQ(8, mat1[2][0]); - EXPECT_EQ(9, mat1[2][1]); - EXPECT_EQ(10, mat1[2][2]); - EXPECT_EQ(11, mat1[2][3]); - - EXPECT_EQ(12, mat1[3][0]); - EXPECT_EQ(13, mat1[3][1]); - EXPECT_EQ(14, mat1[3][2]); - EXPECT_EQ(15, mat1[3][3]); -} -//-------------------------------------------------------------------------- -TEST(VectorTests, Matrix3SVD) -{ - Matrix3 U, V, mat; - Vector3 w; - - // bidiagonal matrix - Matrix3 ref(3, 1, 0, - 0, 2, 0, - 0, 0, 1); - - ref.SingularValueDecomposition(U, w, V); - mat.SingularValueComposition(U, w, V); - - for(int i = 0; i < 3; i++) - for(int j = 0; j < 3; j++) - EXPECT_NEAR(ref[i][j], mat[i][j], Matrix3::EPSILON); -} -//-------------------------------------------------------------------------- -TEST(VectorTests, Matrix3QDU) -{ - Matrix3 linear = Matrix3::IDENTITY * -2; // some scaling and reflection - Matrix3 rot; - Vector3 scale, shear; - - linear.QDUDecomposition(rot, scale, shear); - - Matrix3 ref_rot = Matrix3::IDENTITY; - for(int i = 0; i < 3; i++) - for(int j = 0; j < 3; j++) - EXPECT_FLOAT_EQ(ref_rot[i][j], rot[i][j]); - - for(int i = 0; i < 3; i++) - EXPECT_FLOAT_EQ(scale[i], -2); -} -//-------------------------------------------------------------------------- -TEST(VectorTests, TransformBaseArrayLoading) -{ - typedef TransformBase<3, float> Matrix3x4f; - - double arr1[12] = { 0, 1, 2, 3, - 4, 5, 6, 7, - 8, 9, 10, 11}; - - Matrix3x4f mat1(arr1); - - EXPECT_EQ(0, mat1[0][0]); - EXPECT_EQ(1, mat1[0][1]); - EXPECT_EQ(2, mat1[0][2]); - EXPECT_EQ(3, mat1[0][3]); - - EXPECT_EQ(4, mat1[1][0]); - EXPECT_EQ(5, mat1[1][1]); - EXPECT_EQ(6, mat1[1][2]); - EXPECT_EQ(7, mat1[1][3]); - - EXPECT_EQ(8, mat1[2][0]); - EXPECT_EQ(9, mat1[2][1]); - EXPECT_EQ(10, mat1[2][2]); - EXPECT_EQ(11, mat1[2][3]); -} -//-------------------------------------------------------------------------- -TEST(VectorTests, TypeCasts) -{ - int arr[16] = { 0 }; - - Affine3 affine(arr); - Matrix4 matrix(arr); - - EXPECT_EQ(affine, Affine3::ZERO); - EXPECT_EQ(matrix, Matrix4::ZERO); - - typedef TransformBase<4, int> Matrix4i; // something that is neither float nor double - Matrix4i imat; - - Vector3i vec(1, 2, 3); - imat.setTrans(vec); - - EXPECT_EQ(imat.getTrans(), vec); -} diff --git a/Tests/OgreMain/src/ZipArchiveTests.cpp b/Tests/OgreMain/src/ZipArchiveTests.cpp deleted file mode 100644 index d0d706ecded..00000000000 --- a/Tests/OgreMain/src/ZipArchiveTests.cpp +++ /dev/null @@ -1,252 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "ZipArchiveTests.h" -#include "Threading/OgreThreadHeaders.h" -#include "OgreCommon.h" -#include "OgreConfigFile.h" -#include "OgreFileSystemLayer.h" - -using namespace Ogre; - -static String fileId(const String& path) { -#if !OGRE_RESOURCEMANAGER_STRICT - String file; - String base; - StringUtil::splitFilename(path, file, base); - return file; -#endif - return path; -} - -//-------------------------------------------------------------------------- -void ZipArchiveTests::SetUp() -{ - Ogre::ConfigFile cf; - cf.load(Ogre::FileSystemLayer(OGRE_VERSION_NAME).getConfigFilePath("resources.cfg")); - Ogre::String testPath = cf.getSettings("Tests").begin()->second+"/misc/ArchiveTest.zip"; - - arch = Ogre::ZipArchiveFactory().createInstance(testPath, true); - arch->load(); -} -//-------------------------------------------------------------------------- -void ZipArchiveTests::TearDown() -{ - OGRE_DELETE arch; -} -//-------------------------------------------------------------------------- -TEST_F(ZipArchiveTests,ListNonRecursive) -{ - StringVectorPtr vec = arch->list(false); - - EXPECT_EQ((size_t)2, vec->size()); - EXPECT_EQ(String("rootfile.txt"), vec->at(0)); - EXPECT_EQ(String("rootfile2.txt"), vec->at(1)); - - EXPECT_EQ("rootfile.txt", arch->open("rootfile.txt")->getName()); -} -//-------------------------------------------------------------------------- -TEST_F(ZipArchiveTests,ListRecursive) -{ - StringVectorPtr vec = arch->list(true); - - EXPECT_EQ((size_t)6, vec->size()); - EXPECT_EQ(fileId("level1/materials/scripts/file.material"), vec->at(0)); - EXPECT_EQ(fileId("level1/materials/scripts/file2.material"), vec->at(1)); - EXPECT_EQ(fileId("level2/materials/scripts/file3.material"), vec->at(2)); - EXPECT_EQ(fileId("level2/materials/scripts/file4.material"), vec->at(3)); - EXPECT_EQ(String("rootfile.txt"), vec->at(4)); - EXPECT_EQ(String("rootfile2.txt"), vec->at(5)); -} -//-------------------------------------------------------------------------- -TEST_F(ZipArchiveTests,ListFileInfoNonRecursive) -{ - FileInfoListPtr vec = arch->listFileInfo(false); - - EXPECT_EQ((size_t)2, vec->size()); - FileInfo& fi1 = vec->at(0); - EXPECT_EQ(String("rootfile.txt"), fi1.filename); - EXPECT_EQ(BLANKSTRING, fi1.path); - EXPECT_EQ((size_t)40, fi1.compressedSize); - EXPECT_EQ((size_t)130, fi1.uncompressedSize); - - FileInfo& fi2 = vec->at(1); - EXPECT_EQ(String("rootfile2.txt"), fi2.filename); - EXPECT_EQ(BLANKSTRING, fi2.path); - EXPECT_EQ((size_t)45, fi2.compressedSize); - EXPECT_EQ((size_t)156, fi2.uncompressedSize); -} -//-------------------------------------------------------------------------- -TEST_F(ZipArchiveTests,ListFileInfoRecursive) -{ - FileInfoListPtr vec = arch->listFileInfo(true); - - EXPECT_EQ((size_t)6, vec->size()); - FileInfo& fi3 = vec->at(0); - EXPECT_EQ(fileId("level1/materials/scripts/file.material"), fi3.filename); - EXPECT_EQ(String("level1/materials/scripts/"), fi3.path); - EXPECT_EQ((size_t)0, fi3.compressedSize); - EXPECT_EQ((size_t)0, fi3.uncompressedSize); - - FileInfo& fi4 = vec->at(1); - EXPECT_EQ(fileId("level1/materials/scripts/file2.material"), fi4.filename); - EXPECT_EQ(String("level1/materials/scripts/"), fi4.path); - EXPECT_EQ((size_t)0, fi4.compressedSize); - EXPECT_EQ((size_t)0, fi4.uncompressedSize); - - FileInfo& fi5 = vec->at(2); - EXPECT_EQ(fileId("level2/materials/scripts/file3.material"), fi5.filename); - EXPECT_EQ(String("level2/materials/scripts/"), fi5.path); - EXPECT_EQ((size_t)0, fi5.compressedSize); - EXPECT_EQ((size_t)0, fi5.uncompressedSize); - - FileInfo& fi6 = vec->at(3); - EXPECT_EQ(fileId("level2/materials/scripts/file4.material"), fi6.filename); - EXPECT_EQ(String("level2/materials/scripts/"), fi6.path); - EXPECT_EQ((size_t)0, fi6.compressedSize); - EXPECT_EQ((size_t)0, fi6.uncompressedSize); - - FileInfo& fi1 = vec->at(4); - EXPECT_EQ(String("rootfile.txt"), fi1.filename); - EXPECT_EQ(BLANKSTRING, fi1.path); - EXPECT_EQ((size_t)40, fi1.compressedSize); - EXPECT_EQ((size_t)130, fi1.uncompressedSize); - - FileInfo& fi2 = vec->at(5); - EXPECT_EQ(String("rootfile2.txt"), fi2.filename); - EXPECT_EQ(BLANKSTRING, fi2.path); - EXPECT_EQ((size_t)45, fi2.compressedSize); - EXPECT_EQ((size_t)156, fi2.uncompressedSize); -} -//-------------------------------------------------------------------------- -TEST_F(ZipArchiveTests,FindNonRecursive) -{ - StringVectorPtr vec = arch->find("*.txt", false); - - EXPECT_EQ((size_t)2, vec->size()); - EXPECT_EQ(String("rootfile.txt"), vec->at(0)); - EXPECT_EQ(String("rootfile2.txt"), vec->at(1)); -} -//-------------------------------------------------------------------------- -TEST_F(ZipArchiveTests,FindRecursive) -{ - StringVectorPtr vec = arch->find("*.material", true); - - EXPECT_EQ((size_t)4, vec->size()); - EXPECT_EQ(fileId("level1/materials/scripts/file.material"), vec->at(0)); - EXPECT_EQ(fileId("level1/materials/scripts/file2.material"), vec->at(1)); - EXPECT_EQ(fileId("level2/materials/scripts/file3.material"), vec->at(2)); - EXPECT_EQ(fileId("level2/materials/scripts/file4.material"), vec->at(3)); -} -//-------------------------------------------------------------------------- -TEST_F(ZipArchiveTests,FindFileInfoNonRecursive) -{ - FileInfoListPtr vec = arch->findFileInfo("*.txt", false); - - EXPECT_EQ((size_t)2, vec->size()); - FileInfo& fi1 = vec->at(0); - EXPECT_EQ(String("rootfile.txt"), fi1.filename); - EXPECT_EQ(BLANKSTRING, fi1.path); - EXPECT_EQ((size_t)40, fi1.compressedSize); - EXPECT_EQ((size_t)130, fi1.uncompressedSize); - - FileInfo& fi2 = vec->at(1); - EXPECT_EQ(String("rootfile2.txt"), fi2.filename); - EXPECT_EQ(BLANKSTRING, fi2.path); - EXPECT_EQ((size_t)45, fi2.compressedSize); - EXPECT_EQ((size_t)156, fi2.uncompressedSize); -} -//-------------------------------------------------------------------------- -TEST_F(ZipArchiveTests,FindFileInfoRecursive) -{ - FileInfoListPtr vec = arch->findFileInfo("*.material", true); - - EXPECT_EQ((size_t)4, vec->size()); - - FileInfo& fi3 = vec->at(0); - EXPECT_EQ(fileId("level1/materials/scripts/file.material"), fi3.filename); - EXPECT_EQ(String("level1/materials/scripts/"), fi3.path); - EXPECT_EQ((size_t)0, fi3.compressedSize); - EXPECT_EQ((size_t)0, fi3.uncompressedSize); - - FileInfo& fi4 = vec->at(1); - EXPECT_EQ(fileId("level1/materials/scripts/file2.material"), fi4.filename); - EXPECT_EQ(String("level1/materials/scripts/"), fi4.path); - EXPECT_EQ((size_t)0, fi4.compressedSize); - EXPECT_EQ((size_t)0, fi4.uncompressedSize); - - FileInfo& fi5 = vec->at(2); - EXPECT_EQ(fileId("level2/materials/scripts/file3.material"), fi5.filename); - EXPECT_EQ(String("level2/materials/scripts/"), fi5.path); - EXPECT_EQ((size_t)0, fi5.compressedSize); - EXPECT_EQ((size_t)0, fi5.uncompressedSize); - - FileInfo& fi6 = vec->at(3); - EXPECT_EQ(fileId("level2/materials/scripts/file4.material"), fi6.filename); - EXPECT_EQ(String("level2/materials/scripts/"), fi6.path); - EXPECT_EQ((size_t)0, fi6.compressedSize); - EXPECT_EQ((size_t)0, fi6.uncompressedSize); -} -//-------------------------------------------------------------------------- -TEST_F(ZipArchiveTests,FileRead) -{ - DataStreamPtr stream = arch->open("rootfile.txt"); - EXPECT_EQ(String("this is line 1 in file 1"), stream->getLine()); - EXPECT_EQ(String("this is line 2 in file 1"), stream->getLine()); - EXPECT_EQ(String("this is line 3 in file 1"), stream->getLine()); - EXPECT_EQ(String("this is line 4 in file 1"), stream->getLine()); - EXPECT_EQ(String("this is line 5 in file 1"), stream->getLine()); - EXPECT_TRUE(stream->eof()); -} -//-------------------------------------------------------------------------- -TEST_F(ZipArchiveTests,ReadInterleave) -{ - // Test overlapping reads from same archive - // File 1 - DataStreamPtr stream1 = arch->open("rootfile.txt"); - EXPECT_EQ(String("this is line 1 in file 1"), stream1->getLine()); - EXPECT_EQ(String("this is line 2 in file 1"), stream1->getLine()); - - // File 2 - DataStreamPtr stream2 = arch->open("rootfile2.txt"); - EXPECT_EQ(String("this is line 1 in file 2"), stream2->getLine()); - EXPECT_EQ(String("this is line 2 in file 2"), stream2->getLine()); - EXPECT_EQ(String("this is line 3 in file 2"), stream2->getLine()); - - // File 1 - EXPECT_EQ(String("this is line 3 in file 1"), stream1->getLine()); - EXPECT_EQ(String("this is line 4 in file 1"), stream1->getLine()); - EXPECT_EQ(String("this is line 5 in file 1"), stream1->getLine()); - EXPECT_TRUE(stream1->eof()); - - // File 2 - EXPECT_EQ(String("this is line 4 in file 2"), stream2->getLine()); - EXPECT_EQ(String("this is line 5 in file 2"), stream2->getLine()); - EXPECT_EQ(String("this is line 6 in file 2"), stream2->getLine()); - EXPECT_TRUE(stream2->eof()); -} -//-------------------------------------------------------------------------- diff --git a/Tests/RenderSystems/GLSupport/GLSLTests.cpp b/Tests/RenderSystems/GLSupport/GLSLTests.cpp deleted file mode 100644 index a8d83e1b928..00000000000 --- a/Tests/RenderSystems/GLSupport/GLSLTests.cpp +++ /dev/null @@ -1,190 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "GLSL/OgreGLSLPreprocessor.h" -#include "OgreString.h" - -#include - -using namespace Ogre; - -TEST(CPreprocessorTests, MacroBraces) -{ - CPreprocessor prep; - String src = "#define MY_MACRO(x) print( x )\n" - "MY_MACRO( (myValue * 3) * 2)"; - - size_t olen; - char* out = prep.Parse(src.c_str(), src.size(), olen); - String str(out, olen); - StringUtil::trim(str); - EXPECT_EQ(str, "print( (myValue * 3) * 2 )"); - free(out); -} - -TEST(CPreprocessorTests, MacroExpansion) -{ - CPreprocessor prep; - String src = "#define mad( a, b, c ) fma( a, b, c )\n" - "mad( x.s, y, a )"; - - size_t olen; - char* out = prep.Parse(src.c_str(), src.size(), olen); - String str(out, olen); - StringUtil::trim(str); - EXPECT_EQ(str, "fma( x.s, y, a )"); - free(out); -} - -TEST(CPreprocessorTests, IfDef) -{ - CPreprocessor prep; - String src = "#define A\n" - "#ifndef A\n" - "undefined\n" - "#else\n" - "defined\n" - "#endif"; - - size_t olen; - char* out = prep.Parse(src.c_str(), src.size(), olen); - String str(out, olen); - StringUtil::trim(str); - EXPECT_EQ(str, "defined"); - free(out); -} - -TEST(CPreprocessorTests, ElseIf) -{ - CPreprocessor prep; - String src = "#define A 0\n" - "#if A == 1\n" - "value is 1\n" - "#elif A == 0\n" - "value is 0\n" - "#elif A == 2\n" - "value is 2\n" - "#else\n" - "value is 3\n" - "#endif"; - - size_t olen; - char* out = prep.Parse(src.c_str(), src.size(), olen); - String str(out, olen); - StringUtil::trim(str); - EXPECT_EQ(str, "value is 0"); - free(out); -} - -TEST(CPreprocessorTests, MacroMacroArgument) -{ - CPreprocessor prep; - String src = "#define LEFT(left, right) (left)\n" - "#define USE(a, b, F) F(a, b)\n" - "USE(A, B, LEFT)"; - - size_t olen; - char* out = prep.Parse(src.c_str(), src.size(), olen); - String str(out, olen); - StringUtil::trim(str); - EXPECT_EQ(str, "(A)"); - free(out); -} - -TEST(CPreprocessorTests, MacroMacroArgumentAndExpansion) -{ - CPreprocessor prep; - String src = "#define RIGHT(left, right) (right)\n" - "#define LEFT(left, right) (left)\n" - "#define USE(a, b, F) F(a, b)\n" - "USE(RIGHT(A, C), B, LEFT)"; - - size_t olen; - char* out = prep.Parse(src.c_str(), src.size(), olen); - String str(out, olen); - StringUtil::trim(str); - EXPECT_EQ(str, "((C))"); - free(out); -} - -TEST(CPreprocessorTests, MacroRecursion1) -{ - CPreprocessor prep; - String src = "#define U(b) (b,U(b),b)\n" - "U(U)"; - - size_t olen; - char* out = prep.Parse(src.c_str(), src.size(), olen); - String str(out, olen); - StringUtil::trim(str); - EXPECT_EQ(str, "(U,U(U),U)"); - free(out); -} - - -TEST(CPreprocessorTests, MacroRecursion2) -{ - CPreprocessor prep; - String src = "#define Z(b) (b,b,b)\n" - "Z(Z+Z(1))"; - - size_t olen; - char* out = prep.Parse(src.c_str(), src.size(), olen); - String str(out, olen); - StringUtil::trim(str); - EXPECT_EQ(str, "(Z+(1,1,1),Z+(1,1,1),Z+(1,1,1))"); - free(out); -} - -TEST(CPreprocessorTests, MacroRecursion3) -{ - CPreprocessor prep; - String src = "#define Z(b) (b,b,b)\n" - "Z(Z(Z(1)+Z(2)))"; - - size_t olen; - char* out = prep.Parse(src.c_str(), src.size(), olen); - String str(out, olen); - StringUtil::trim(str); - EXPECT_EQ(str, "(((1,1,1)+(2,2,2),(1,1,1)+(2,2,2),(1,1,1)+(2,2,2)),((1,1,1)+(2,2,2),(1,1,1)+(2,2,2),(1,1,1)+(2,2,2)),((1,1,1)+(2,2,2),(1,1,1)+(2,2,2),(1,1,1)+(2,2,2)))"); - free(out); -} - -TEST(CPreprocessorTests, MacroConcat) -{ - CPreprocessor prep; - String src = "#define concat( a, b ) a##b\n" - "concat( Hello , World )"; - - size_t olen; - char* out = prep.Parse(src.c_str(), src.size(), olen); - String str(out, olen); - StringUtil::trim(str); - EXPECT_EQ(str, "HelloWorld"); - free(out); -} \ No newline at end of file diff --git a/Tests/VisualTests/CMakeLists.txt b/Tests/VisualTests/CMakeLists.txt deleted file mode 100644 index 015d724801d..00000000000 --- a/Tests/VisualTests/CMakeLists.txt +++ /dev/null @@ -1,85 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure Visual Test build - -if (OGRE_BUILD_COMPONENT_RTSHADERSYSTEM) - add_definitions(-DINCLUDE_RTSHADER_SYSTEM) -endif () - -add_definitions(${OGRE_VISIBILITY_FLAGS}) - -if(NOT ANDROID) - # add Context directory - add_subdirectory(Context) -endif() - -# add the PlayPen test plugin's directory -add_subdirectory(PlayPen) - -# add VTests plugin directory -add_subdirectory(VTests) - -if(ANDROID) - # skip the CTest stuff - return() -endif() - -# build a list of render systems to test -set(TEST_RENDER_SYSTEMS "") - -if (OGRE_BUILD_RENDERSYSTEM_GL) - list(APPEND TEST_RENDER_SYSTEMS "OpenGL Rendering Subsystem") -endif () -if (OGRE_BUILD_RENDERSYSTEM_GL3PLUS) - list(APPEND TEST_RENDER_SYSTEMS "OpenGL 3+ Rendering Subsystem") -endif () -if (OGRE_BUILD_RENDERSYSTEM_D3D9) - list(APPEND TEST_RENDER_SYSTEMS "Direct3D9 Rendering Subsystem") -endif () -if (OGRE_BUILD_RENDERSYSTEM_D3D11) - list(APPEND TEST_RENDER_SYSTEMS "Direct3D11 Rendering Subsystem") -endif () -if (OGRE_BUILD_RENDERSYSTEM_GLES2) - list(APPEND TEST_RENDER_SYSTEMS "OpenGL ES 2.x Rendering Subsystem") -endif () - -# Figure out the home directory for this system (this is where the context outputs result data for now) -if (UNIX) - set(USER_HOME_DIRECTORY $ENV{HOME}) -elseif (WIN32) - string(REPLACE "\\" "/" USER_HOME_DIRECTORY "$ENV{HOMEDRIVE}$ENV{HOMEPATH}") -# other platforms? -endif () - -# function for running visual tests for a given render system -function (TestRenderSystem render_system) - - # strip spaces from rendersystem name - string (REPLACE " " "" render_system_nospace ${render_system}) - - # Run a CMake script that handles the test context - add_test(NAME "TestContext_${render_system_nospace}" - COMMAND $ - -rs "${render_system}" # Pick rendersystem - -n "AutomatedTest" # Name it, so it overwrites itself each run - -m "Automated Test - ${render_system}" # A brief comment - -o "${USER_HOME_DIRECTORY}" - WORKING_DIRECTORY $) - - # Set a longer timeout to avoid timeouts on the riscv hardware - set_tests_properties("TestContext_${render_system_nospace}" PROPERTIES TIMEOUT 4500 ENVIRONMENT OGRE_ONLY_COMMON_GL_TESTS=1) - -endfunction (TestRenderSystem) - -# Run the tests once for each rendersystem -foreach (rs ${TEST_RENDER_SYSTEMS}) - TestRenderSystem(${rs}) -endforeach () - diff --git a/Tests/VisualTests/Common/include/CppUnitResultWriter.h b/Tests/VisualTests/Common/include/CppUnitResultWriter.h deleted file mode 100644 index ce65ad1fd70..00000000000 --- a/Tests/VisualTests/Common/include/CppUnitResultWriter.h +++ /dev/null @@ -1,116 +0,0 @@ - -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __CppUnitResultWriter_H__ -#define __CppUnitResultWriter_H__ - -#include "Ogre.h" -#include "TinyHTML.h" -#include "ImageValidator.h" -#include "TestBatch.h" -#include "TestResultWriter.h" - -/** Writes a simple plain text file with pass/fail result for each test */ -class CppUnitResultWriter : public TestResultWriter -{ -public: - - CppUnitResultWriter(const TestBatch& set1, const TestBatch& set2, const ComparisonResultVector& results) - :TestResultWriter(set1, set2, results){} - -protected: - - Ogre::String getOutput() override - { - StringStream out; - int numFailed = 0; - out << "" << std::endl; - out << "" << std::endl; - - out << " " << std::endl; - for(size_t i = 0; i < mResults.size(); ++i) - { - Ogre::String test = mResults[i].testName; - size_t j = i; - - // a test may have multiple images, so we check all, and fail the whole test if any one fails - for(; j < mResults.size() && mResults[j].testName == test; ++j) - { - if(!mResults[j].passed) - { - numFailed++; - - // Start counting at 10000 to make sure that they are unique test id's. - out << " " << std::endl; - out << " VisualTests::test" << test << "" << std::endl; - out << " Error" << std::endl; - out << " Visual Test Image Mismatch" << std::endl; - out << " " << std::endl; - } - } - - i = j - 1; - } - out << " " << std::endl; - - out << " " << std::endl; - for(size_t i = 0; i < mResults.size(); ++i) - { - Ogre::String test = mResults[i].testName; - size_t j = i; - - // a test may have multiple images, so we check all, and fail the whole test if any one fails - for(; j < mResults.size() && mResults[j].testName == test; ++j) - { - if(mResults[j].passed) - { - // Start counting at 10000 to make sure that they are unique test id's. - out << " " << std::endl; - out << " VisualTests::test" << test << "" << std::endl; - out << " " << std::endl; - } - } - - i = j - 1; - } - out << " " << std::endl; - - out << " " << std::endl; - out << " " << mResults.size() << "" << std::endl; - out << " " << numFailed << "" << std::endl; - out << " " << numFailed << "" << std::endl; - out << " 0" << std::endl; - out << " " << std::endl; - out << "" << std::endl; - - return out.str(); - } -}; - -#endif diff --git a/Tests/VisualTests/Common/include/HTMLWriter.h b/Tests/VisualTests/Common/include/HTMLWriter.h deleted file mode 100644 index fd7f16fa67c..00000000000 --- a/Tests/VisualTests/Common/include/HTMLWriter.h +++ /dev/null @@ -1,321 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __HTMLWriter_H__ -#define __HTMLWriter_H__ - -#include "Ogre.h" -#include "TinyHTML.h" -#include "TestResultWriter.h" - -class HtmlWriter : public TestResultWriter -{ -public: - - HtmlWriter(const TestBatch& set1, const TestBatch& set2, const ComparisonResultVector& results) - :TestResultWriter(set1, set2, results){} - -protected: - - Ogre::String getOutput() override - { - StringStream output; - - // just dump the doctype in beforehand, since it's formatted strangely - output<<"\n"; - - // root 'html' tag - HtmlElement html = HtmlElement("html"); - - // add the head - HtmlElement* head = html.appendElement("head"); - head->appendElement("title")->appendText("OGRE Visual Testing Output"); - - // link the stylesheet - HtmlElement* css = head->appendElement("link"); - css->appendAttribute("rel","stylesheet"); - - // Hosted as an attachment on the wiki - css->appendAttribute("href","https://ogrecave.github.io/ogre/vtests/vtests.css"); - css->appendAttribute("type","text/css"); - - // link a little javascript - HtmlElement* js = head->appendElement("script"); - js->appendAttribute("src","https://ogrecave.github.io/ogre/vtests/vtests.js"); - js->appendText("");// so it doesn't self close - - // - - // add body - HtmlElement* body = html.appendElement("body"); - - // title - body->appendElement("h1")->appendText("OGRE Visual Test Output"); - - // div for summary - HtmlElement* summaryDiv = body->appendElement("div"); - summaryDiv->appendElement("h2")->appendText("Overall:"); - HtmlElement* contentDiv = summaryDiv->appendElement("div"); - contentDiv->appendAttribute("class", "contentarea"); - contentDiv->appendElement("hr"); - - // add info tables about the sets - contentDiv->pushChild(writeBatchInfoTable(mSet1, "Reference Set:")); - contentDiv->pushChild(writeBatchInfoTable(mSet2, "Test Set:")); - contentDiv->appendElement("hr"); - - // summarize results - - // tests may include multiple images - size_t numPassed = 0; - size_t numTests = 0; - - for (unsigned int i = 0; i < mResults.size(); ++i) - { - ++numTests; - const Ogre::String& testName = mResults[i].testName; - bool passed = true; - unsigned int j = i; - - for (; j < mResults.size() && mResults[j].testName == testName; ++j) - { - if(!mResults[j].passed) - passed = false; - } - - i = j - 1; - - if(passed) - ++numPassed; - } - - contentDiv->appendElement("h3")->appendText( - Ogre::StringConverter::toString(numPassed) + " of " - + Ogre::StringConverter::toString(numTests) + " tests passed."); - contentDiv->appendElement("hr"); - - // add thumbnails - HtmlElement* thumbs = contentDiv->appendElement("p"); - for (unsigned int i = 0; i < mResults.size(); ++i) - { - HtmlElement* anchor = thumbs->appendElement("a"); - anchor->appendAttribute("href", Ogre::String("#") + mResults[i].testName); - anchor->appendAttribute("title", mResults[i].testName); - HtmlElement* img = anchor->appendElement("img"); - img->appendAttribute("src",mSet2.name + "/" + mResults[i].image); - img->appendAttribute("class", mResults[i].passed ? "thumb" : "thumb_fail"); - } - - // add side-by-side images and summary for each test - for (unsigned int i = 0; i < mResults.size(); ++i) - { - - // since a test can have multiple images, we find all images with this tets name - const Ogre::String& testName = mResults[i].testName; - bool passed = true; - unsigned int j = i; - std::vector results; - - for (; j < mResults.size() && mResults[j].testName == testName; ++j) - { - results.push_back(&mResults[j]); - if(!mResults[j].passed) - passed = false; - } - - i = j - 1; - - body->pushChild(summarizeSingleResult(results, passed, mSet1, mSet2)); - } - - // print to the stream and return - output<& result, bool passed, const TestBatch& set1, const TestBatch& set2) - { - // container and header - HtmlElement* container = OGRE_NEW HtmlElement("div"); - container->appendAttribute("id",result[0]->testName); - container->appendElement("h2")->appendText(result[0]->testName); - //+ " (frame " + Ogre::StringConverter::toString(result.frame) + ")"); - HtmlElement* content = container->appendElement("div"); - // if failed, we give it a different class, and make it red - content->appendAttribute("class", Ogre::String("contentarea") - + (passed ? "" : " failed_test")); - - // summary - content->appendElement("hr"); - HtmlElement* status = content->appendElement("h3"); - status->appendText("Status: "); - HtmlElement* span = status->appendElement("span"); - span->appendText(passed ? "Passed" : "Failed"); - span->appendAttribute("class", passed ? "passed" : "failed"); - - // if more than one image for this test, and it failed, report how many passed - if(!passed && result.size() > 1) - { - int p = 0; - - for(unsigned int i = 0; i < result.size(); ++i) - if(result[i]->passed) - ++p; - - content->appendElement("h4")->appendText( - Ogre::StringConverter::toString(p) + " of " + - Ogre::StringConverter::toString(result.size()) + " images passed."); - } - - // loop over images - for(unsigned int i = 0; i < result.size(); ++i) - { - // add a divider - content->appendElement("hr"); - - // add a frame label if more than one image - if(result.size() > 1) - content->appendElement("h4")->appendText("Frame " + Ogre::StringConverter::toString(result[i]->frame) + ":"); - - HtmlElement* imageBox = content->appendElement("div"); - - // first image - HtmlElement* column1 = imageBox->appendElement("div"); - column1->appendAttribute("class", Ogre::String("img_column") + (result[i]->passed ? "" : " failed_test")); - column1->appendElement("h3")->appendText("Original:"); - HtmlElement* img = column1->appendElement("img"); - img->appendAttribute("alt", result[i]->testName + Ogre::StringConverter::toString(result[i]->frame) + " original"); - img->appendAttribute("src", set1.name + "/" + result[i]->image); - - // second image - HtmlElement* column2 = imageBox->appendElement("div"); - column2->appendAttribute("class", Ogre::String("img_column") + (result[i]->passed ? "" : " failed_test")); - column2->appendElement("h3")->appendText("New:"); - img = column2->appendElement("img"); - img->appendAttribute("alt", result[i]->testName + Ogre::StringConverter::toString(result[i]->frame) + " new"); - img->appendAttribute("src", set2.name + "/" + result[i]->image); - - imageBox->appendElement("h4")->appendText("Comparison Summary:"); - - if(result[i]->incorrectPixels) - { - HtmlElement* absDiff = imageBox->appendElement("p"); - absDiff->appendAttribute("class", "diffreport"); - absDiff->appendText(Ogre::StringConverter::toString(result[i]->incorrectPixels) + - " pixels differed."); - - HtmlElement* mse = imageBox->appendElement("p"); - mse->appendAttribute("class", "diffreport"); - mse->appendElement("strong")->appendText(" MSE | "); - mse->appendText("Overall: " + formatFloat(result[i]->mse) + " | "); - mse->appendText("R: " + formatFloat(result[i]->mseChannels.r) + " | "); - mse->appendText("G: " + formatFloat(result[i]->mseChannels.g) + " | "); - mse->appendText("B: " + formatFloat(result[i]->mseChannels.b) + " |"); - - HtmlElement* psnr = imageBox->appendElement("p"); - psnr->appendAttribute("class", "diffreport"); - psnr->appendElement("strong")->appendText("PSNR| "); - psnr->appendText("Overall: " + formatFloat(result[i]->psnr) + " | "); - psnr->appendText("R: " + formatFloat(result[i]->psnrChannels.r) + " | "); - psnr->appendText("G: " + formatFloat(result[i]->psnrChannels.g) + " | "); - psnr->appendText("B: " + formatFloat(result[i]->psnrChannels.b) + " |"); - - HtmlElement* ssim = imageBox->appendElement("p"); - ssim->appendAttribute("class", "diffreport"); - ssim->appendText("Structural Similarity Index: " + formatFloat(result[i]->ssim)); - } - else - { - imageBox->appendElement("p")->appendText("Images are identical."); - } - } - - return container; - } - //----------------------------------------------------------------------- - - /** Writes a table with some info about a test batch - * @param set The set - * @param name The name to use in the header above the table */ - HtmlElement* writeBatchInfoTable(const TestBatch& set, Ogre::String name) - { - // main div - HtmlElement* column = OGRE_NEW HtmlElement("div"); - column->appendAttribute("class", "img_column"); - - // add a bit of header text - column->appendElement("h3")->appendText(name); - - // make the table, and rows for each stat - HtmlElement* table = column->appendElement("table"); - HtmlElement* row = table->appendElement("tr"); - row->appendElement("th")->appendText("Name:"); - row->appendElement("td")->appendText(set.name); - row = table->appendElement("tr"); - row->appendElement("th")->appendText("Time:"); - row->appendElement("td")->appendText(set.timestamp); - row = table->appendElement("tr"); - row->appendElement("th")->appendText("Version:"); - row->appendElement("td")->appendText(set.version); - row = table->appendElement("tr"); - row->appendElement("th")->appendText("Resolution:"); - row->appendElement("td")->appendText(Ogre::StringConverter::toString(set.resolutionX) - + " x " + Ogre::StringConverter::toString(set.resolutionY)); - row = table->appendElement("tr"); - row->appendElement("th")->appendText("Comment:"); - row->appendElement("td")->appendText(set.comment); - - // return the whole thing, ready to be attached into a larger document - return column; - } - //----------------------------------------------------------------------- - - // helper that formats a float nicely for output - static Ogre::String formatFloat(float num, unsigned int length=6) - { - std::stringstream ss; - ss.setf(std::ios::fixed, std::ios::floatfield); - ss.setf(std::ios::showpoint); - ss.precision(6); - ss<>out; - out = out.substr(0, length); - if(out.size() < length) - while(out.size() < length) - out += "0"; - return out; - } - //----------------------------------------------------------------------- -}; - -#endif diff --git a/Tests/VisualTests/Common/include/ImageValidator.h b/Tests/VisualTests/Common/include/ImageValidator.h deleted file mode 100644 index e3194cc8bd0..00000000000 --- a/Tests/VisualTests/Common/include/ImageValidator.h +++ /dev/null @@ -1,215 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __ImageValidator_H__ -#define __ImageValidator_H__ - -#include "Ogre.h" - -#if OGRE_DOUBLE_PRECISION == 1 -#define WITH_FLOAT_SUFFIX(x) x -#else -#define WITH_FLOAT_SUFFIX(x) x##f -#endif - -/** Some functionality for comparing images */ - -/* Results of comparing two test images */ -struct ComparisonResult -{ - bool passed; - Ogre::String image; - Ogre::String testName; - unsigned int frame; - - // various metrics of image difference - unsigned int incorrectPixels; - float mse; // mean squared error - Ogre::ColourValue mseChannels; - float psnr; // peak signal-to-noise ratio - Ogre::ColourValue psnrChannels; - float ssim; // structural similarity index -}; - -typedef std::vector ComparisonResultVector; -typedef Ogre::SharedPtr ComparisonResultVectorPtr; - -/** Simple object for doing image comparison between two image sets */ -class ImageValidator -{ -public: - - /** Constructor, takes paths to each set's directory */ - ImageValidator(Ogre::String directory1, Ogre::String directory2) - :mDirectory1(directory1),mDirectory2(directory2) {} - - /** Compare the the two set's versions of the specified image name - * @param name filename of the image (filename only, no path) */ - ComparisonResult compare(Ogre::String image) - { - ComparisonResult out; - out.image = image + ".png"; - - // extract test name and frame from image filename - size_t end = image.find_last_of("_"); - out.testName = image.substr(0, end); - out.frame = atoi(image.substr(end+1).c_str()); - - // load manually, so this can be done without all of Ogre initialized (i.e. for a - // command line utility for comparing test sets or something to that effect) - // The FreeImage codecs must be loaded for this to work, but no resource stuff is needed. - std::ifstream file1(Ogre::String(mDirectory1 + "/" + image + ".png").c_str(), std::ios::in | std::ios::binary); - std::ifstream file2(Ogre::String(mDirectory2 + "/" + image + ".png").c_str(), std::ios::in | std::ios::binary); - Ogre::DataStreamPtr data1 = Ogre::DataStreamPtr( - OGRE_NEW Ogre::FileStreamDataStream(&file1, false)); - Ogre::DataStreamPtr data2 = Ogre::DataStreamPtr( - OGRE_NEW Ogre::FileStreamDataStream(&file2, false)); - Ogre::Image img1 = Ogre::Image(); - Ogre::Image img2 = Ogre::Image(); - img1.load(data1, "png"); - img2.load(data2, "png"); - - // do the actual comparison - compare(img1,img2,out); - - return out; - } - - -protected: - - /** Do the actual comparison, override this if you wish to do some - * alternate method of comparison - * @param img1 The image data for the first image - * @param img2 The image data for the second image - * @param out The struct we'll write results to */ - virtual void compare(const Ogre::Image& img1, const Ogre::Image& img2, - ComparisonResult& out) - { - // This computes the MSE, PSNR and SSIM for the two images - - out.incorrectPixels = 0; - Ogre::ColourValue disparity = Ogre::ColourValue(0,0,0); - Ogre::Real ssim = 0.0; - - int width = img1.getWidth(); - int height = img1.getHeight(); - - // iterate through in 8x8 chunks, so we can calc SSIM at the same time as MSE - for(int i = 0; i < width / 8; ++i) - { - for(int j = 0; j < height / 8; ++j) - { - // number of pixels processed - int n = 0; - // dynamic range (just 0.0-1.0, since we're using floats) - Ogre::Real L = 1.f; - // constants - Ogre::Real c1 = (0.01f * L)*(0.01f * L); - Ogre::Real c2 = (0.03f * L)*(0.03f * L); - // averages - Ogre::Real avg_x = 0.f; - Ogre::Real avg_y = 0.f; - // variances - Ogre::Real var_x = 0.f; - Ogre::Real var_y = 0.f; - // covariance - Ogre::Real covar = 0.f; - - // iterate through the 8x8 window - for(int k = 0; k < 8 && i * 8 + k < width; ++k) - { - for(int l = 0; l < 8 && j * 8 + l < height; ++l) - { - ++n; - - Ogre::ColourValue col1 = img1.getColourAt(i*8 + k, j*8 + l, 0); - Ogre::ColourValue col2 = img2.getColourAt(i*8 + k, j*8 + l, 0); - - if(col1 != col2) - { - ++out.incorrectPixels; - disparity += (col1 - col2) * (col1 - col2); - } - - // calculations for SSIM: - // we'll be working with the luminosity for SSIM (computed by standard Rec. 709 definition) - Ogre::Real lum1 = 0.2126f * col1.r + 0.7152f * col1.g + 0.0722f * col1.b; - Ogre::Real lum2 = 0.2126f * col2.r + 0.7152f * col2.g + 0.0722f * col2.b; - Ogre::Real delta_x = lum1 - avg_x; - Ogre::Real delta_y = lum2 - avg_y; - avg_x += delta_x/(k*8+l+1); - avg_y += delta_y/(k*8+l+1); - var_x += delta_x * (lum1 - avg_x); - var_y += delta_y * (lum2 - avg_y); - covar += lum1 * lum2; - } - } - - // more SSIM stuff: - var_x = var_x/n; - var_y = var_y/n; - covar = covar/n - avg_x * avg_y; - - // calculation based on: Z. Wang, A. C. Bovik, H. R. Sheikh and E. P. Simoncelli, - // "Image quality assessment: From error visibility to structural - // similarity," IEEE Transactions on Image Processing, vol. 13, - // no. 4, pp. 600-612, Apr. 2004. - ssim += ((2 * avg_x * avg_y + c1) * (2 * covar + c2)) / - ((avg_x*avg_x + avg_y*avg_y + c1) * (var_x + var_y + c2)); - } - } - - // only bother with these calculations if the images aren't identical - if(out.incorrectPixels != 0) - { - // average and clamp to [-1,1] - out.ssim = std::max(WITH_FLOAT_SUFFIX(-1.0), - std::min(WITH_FLOAT_SUFFIX(1.0), ssim/(width*height/WITH_FLOAT_SUFFIX(64.)))); - - // average the raw deviance value to get MSE - out.mseChannels = disparity / (width*height); - out.mse = (out.mseChannels.r + out.mseChannels.g + out.mseChannels.b) / 3.f; - - // PSNR = 20 * log10(range/sqrt(mse)) - for(int i = 0; i < 3; ++i) - out.psnrChannels[i] = 20 * log10(1.f / sqrt(out.mseChannels[i])); - out.psnr = 20 * log10(1.f / sqrt(out.mse)); - } - - out.passed = out.incorrectPixels == 0 || out.ssim > 0.999; - } - -private: - - Ogre::String mDirectory1; - Ogre::String mDirectory2; - -}; - -#endif diff --git a/Tests/VisualTests/Common/include/SimpleResultWriter.h b/Tests/VisualTests/Common/include/SimpleResultWriter.h deleted file mode 100644 index 2a322f052d9..00000000000 --- a/Tests/VisualTests/Common/include/SimpleResultWriter.h +++ /dev/null @@ -1,76 +0,0 @@ - -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __SimpleResultWriter_H__ -#define __SimpleResultWriter_H__ - -#include "Ogre.h" -#include "TinyHTML.h" -#include "ImageValidator.h" -#include "TestBatch.h" -#include "TestResultWriter.h" - -/** Writes a simple plain text file with pass/fail result for each test */ -class SimpleResultWriter : public TestResultWriter -{ -public: - - SimpleResultWriter(const TestBatch& set1, const TestBatch& set2, ComparisonResultVectorPtr results) - :TestResultWriter(set1, set2, results){} - -protected: - - virtual Ogre::String getOutput() - { - StringStream out; - - for(size_t i = 0; i < mResults->size(); ++i) - { - Ogre::String test = (*mResults)[i].testName; - bool passed = true; - - size_t j = i; - - // a test may have multiple images, so we check all, and fail the whole test if any one fails - for(; j < mResults->size() && (*mResults)[j].testName == test; ++j) - { - if(!(*mResults)[j].passed) - passed = false; - } - - i = j - 1; - - out << test << "=" << (passed ? "Passed" : "Failed") << "\n"; - } - - return out.str(); - } -}; - -#endif diff --git a/Tests/VisualTests/Common/include/TestBatch.h b/Tests/VisualTests/Common/include/TestBatch.h deleted file mode 100644 index 086b1d3b290..00000000000 --- a/Tests/VisualTests/Common/include/TestBatch.h +++ /dev/null @@ -1,210 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __TestBatch_H__ -#define __TestBatch_H__ - -#include "Ogre.h" -#include "ImageValidator.h" - -class TestBatch; -typedef std::set > TestBatchSet; - -/** Represents the output from running a batch of tests - * (i.e. a single run of the TestContext) */ -class TestBatch : public Ogre::GeneralAllocatedObject -{ -public: - - // image files from this batch - std::vector images; - // This set's name (usually of the form: [TestPluginName]_[Timestamp]) - Ogre::String name; - // name of the tets plugin - Ogre::String plugin; - // version string - Ogre::String version; - // timestamp (when the batch was run) - Ogre::String timestamp; - // user comment made at the time of the run - Ogre::String comment; - // resolution the batch was run at - size_t resolutionX; - size_t resolutionY; - - /** Initialize based on a config file - * @param info Reference to loaded config file with details about the set - * @param directory The full path to this set's directory */ - TestBatch(Ogre::ConfigFile& info, Ogre::String directory):mDirectory(directory) - { - // fill out basic info - Ogre::String res = info.getSetting("Resolution","Info"); - resolutionX = atoi(res.c_str()); - resolutionY = atoi(res.substr(res.find('x')+1).c_str()); - version = info.getSetting("Version","Info"); - timestamp = info.getSetting("Time","Info"); - comment = info.getSetting("Comment","Info"); - name = info.getSetting("Name","Info"); - // grab image names - const Ogre::ConfigFile::SettingsMultiMap& tests = info.getSettings("Tests"); - for(Ogre::ConfigFile::SettingsMultiMap::const_iterator i = tests.begin(); i != tests.end(); ++i) - images.push_back(i->second); - } - - /** Manually initialize a batch object - * @param batchName The name of the overall test batch - * @param pluginName The name of the test plugin being used - * @param timestamp The time the test was begun - * @param resx The width of the render window used - * @param resy The height of the render window used - * @param directory The directory this batch is saved to */ - TestBatch(Ogre::String batchName, Ogre::String pluginName, - Ogre::String t, size_t resx, size_t resy, Ogre::String directory) - :name(batchName) - ,plugin(pluginName) - ,timestamp(t) - ,comment("") - ,resolutionX(resx) - ,resolutionY(resy) - ,mDirectory(directory) - { - StringStream ver; - ver<(const TestBatch& other) const - { - // due to the way timestamps are formatted, lexicographical ordering will also be chronological - return timestamp > other.timestamp; - } - - /** Loads all test batches found in a directory and returns a reference counted ptr - * to a set containing all the valid batches */ - static TestBatchSet loadTestBatches(Ogre::String directory) - { - TestBatchSet out; - // use ArchiveManager to get a list of all subdirectories - Ogre::Archive* testDir = Ogre::ArchiveManager::getSingleton().load(directory, "FileSystem", true); - Ogre::StringVectorPtr tests = testDir->list(false, true); - for (unsigned int i = 0; i < tests->size(); ++i) - { - Ogre::ConfigFile info; - - // look for info.cfg, if none found, must not be a batch directory - try - { - info.load(directory + (*tests)[i] + "/info.cfg"); - } - catch (Ogre::FileNotFoundException& e) - { - continue; - } - - out.insert(TestBatch(info, directory + (*tests)[i])); - } - - return out; - } - -private: - - Ogre::String mDirectory; - -}; - - - -#endif diff --git a/Tests/VisualTests/Common/include/TestResultWriter.h b/Tests/VisualTests/Common/include/TestResultWriter.h deleted file mode 100644 index fde33e8320d..00000000000 --- a/Tests/VisualTests/Common/include/TestResultWriter.h +++ /dev/null @@ -1,68 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __TestResultWriter_H__ -#define __TestResultWriter_H__ - -#include "Ogre.h" -#include "TinyHTML.h" -#include "ImageValidator.h" -#include "TestBatch.h" - -/** Abstract class for outputting test results in some format */ -class TestResultWriter : public Ogre::GeneralAllocatedObject -{ -public: - - TestResultWriter(const TestBatch& set1, const TestBatch& set2, const ComparisonResultVector& results) - :mSet1(set1),mSet2(set2),mResults(results){} - - virtual ~TestResultWriter() {} - - virtual void writeToFile(Ogre::String filename) - { - std::ofstream file; - file.open(filename.c_str()); - if(file.is_open()) - { - file< > attributes; - std::list children; - - HtmlElement(Ogre::String tag) - { - tagname = tag; - } - //------------------------------------------------------------------- - - virtual ~HtmlElement() - { - while (!children.empty()) - { - OGRE_DELETE children.back(); - children.pop_back(); - } - } - //------------------------------------------------------------------- - - void appendAttribute(Ogre::String name, Ogre::String value) - { - attributes.push_back(std::pair(name,value)); - } - //------------------------------------------------------------------- - - void pushChild(HtmlNode* node) - { - children.push_back(node); - } - //------------------------------------------------------------------- - - HtmlElement* appendElement(Ogre::String type) - { - HtmlElement* newNode = OGRE_NEW HtmlElement(type); - children.push_back(newNode); - return newNode; - } - //------------------------------------------------------------------- - - HtmlTextNode* appendText(Ogre::String text) - { - HtmlTextNode* newNode = OGRE_NEW HtmlTextNode(text); - children.push_back(newNode); - return newNode; - } - //------------------------------------------------------------------- - - Ogre::String print(Ogre::String indent = "") override - { - // stream we'll output to - StringStream out; - - out<<"\n"< >::iterator it = attributes.begin(); - it != attributes.end(); ++it) - { - // name="value" - out<<" "<<(*it).first<<"=\""<<(*it).second<<"\""; - } - - // self-closing is done here - if (children.empty()) - { - out<<"/>"; - return out.str(); - } - // closing bracket - out<<">"; - - // print children - for (std::list::iterator it = children.begin(); - it != children.end(); ++it) - { - out<<(*it)->print(indent + "\t"); - } - - // if the last child was an actual element start a newline (otherwise, if text, we'll close on the same line) - if (dynamic_cast(children.back())) - out<<"\n"<"; - return out.str(); - } -}; - -#endif diff --git a/Tests/VisualTests/Common/include/VisualTest.h b/Tests/VisualTests/Common/include/VisualTest.h deleted file mode 100644 index cf3038611f7..00000000000 --- a/Tests/VisualTests/Common/include/VisualTest.h +++ /dev/null @@ -1,97 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __VisualTest_H__ -#define __VisualTest_H__ - -#include "OgreBuildSettings.h" - -#include "Sample.h" -#include "Ogre.h" - -// resource group that will be automatically unloaded after the close of the sample -#define TRANSIENT_RESOURCE_GROUP "VisualTestTransient" -#define ASSETS_RESOURCE_GROUP "General" - -/** The base class for a visual test scene */ -class VisualTest : public OgreBites::Sample -{ - public: - - VisualTest() - { - mInfo["Category"] = "Tests"; - mInfo["Thumbnail"] = "thumb_visual_tests.png"; - Ogre::ResourceGroupManager& rgm = Ogre::ResourceGroupManager::getSingleton(); - if (!rgm.resourceGroupExists(TRANSIENT_RESOURCE_GROUP)) - rgm.createResourceGroup(TRANSIENT_RESOURCE_GROUP, true); - } - - /** set up the camera and viewport */ - void setupView() override - { - mCamera = mSceneMgr->createCamera("MainCamera"); - mCameraNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mCameraNode->attachObject(mCamera); - mCameraNode->setFixedYawAxis(true); // fix lookAt calls - mViewport = mWindow->addViewport(mCamera); - mCamera->setAspectRatio((Ogre::Real)mViewport->getActualWidth() / (Ogre::Real)mViewport->getActualHeight()); - mCamera->setNearClipDistance(0.5f); - mCamera->setFarClipDistance(10000.f); - } - - /** Unload all resources used by this sample */ - void unloadResources() override - { - Ogre::ResourceGroupManager::getSingleton().clearResourceGroup(TRANSIENT_RESOURCE_GROUP); - Sample::unloadResources(); - mAnimStateList.clear(); - } - - /** Default frame started callback, advances animations */ - bool frameStarted(const Ogre::FrameEvent& evt) override - { - for(unsigned int i = 0; i < mAnimStateList.size(); ++i) - mAnimStateList[i]->addTime(evt.timeSinceLastFrame); - return true; - } - - bool keyPressed(const OgreBites::KeyboardEvent& evt) override - { - if (evt.keysym.sym == OgreBites::SDLK_F6) - mCamera->getViewport()->getTarget()->writeContentsToTimestampedFile("screenshot", ".png"); - - return true; - } - - protected: - // a list of animation states to automatically update - std::vector mAnimStateList; -}; - -#endif diff --git a/Tests/VisualTests/Context/CMakeLists.txt b/Tests/VisualTests/Context/CMakeLists.txt deleted file mode 100644 index d6364f27a3b..00000000000 --- a/Tests/VisualTests/Context/CMakeLists.txt +++ /dev/null @@ -1,146 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -set(HEADER_FILES - include/TestContext.h - ../Common/include/ImageValidator.h - ../Common/include/TestBatch.h - ../Common/include/CppUnitResultWriter.h - ../Common/include/TestResultWriter.h - ../Common/include/SimpleResultWriter.h - ../Common/include/HTMLWriter.h - ../Common/include/VisualTest.h - ../Common/include/TinyHTML.h - ) - -set(SOURCE_FILES - src/TestContext.cpp) - -if(APPLE) - set_source_files_properties(src/TestContext.cpp PROPERTIES COMPILE_FLAGS "-x objective-c++") -endif() - -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) -include_directories(${PROJECT_SOURCE_DIR}/Samples/Common/include) -include_directories(${PROJECT_SOURCE_DIR}/Samples/Browser/include) -include_directories(${PROJECT_SOURCE_DIR}/Tests/VisualTests/Common/include) -include_directories(${PROJECT_SOURCE_DIR}/Tests/VisualTests/VTests/include) -include_directories(${PROJECT_SOURCE_DIR}/Tests/VisualTests/PlayPen/include) - -set(SAMPLE_LIBRARIES VTests PlayPenTests) - -add_executable(TestContext ${HEADER_FILES} ${SOURCE_FILES}) -target_link_libraries(TestContext OgreMain ${SAMPLE_LIBRARIES} OgreOverlay OgreRTShaderSystem OgreBites) -ogre_config_common(TestContext) - -# Make sure all plugins are built -if (OGRE_BUILD_PLUGIN_OCTREE) - add_dependencies(TestContext Plugin_OctreeSceneManager) -endif () -if (OGRE_BUILD_PLUGIN_BSP) - add_dependencies(TestContext Plugin_BSPSceneManager) -endif () -if (OGRE_BUILD_PLUGIN_CG) - add_dependencies(TestContext Plugin_CgProgramManager) -endif (OGRE_BUILD_PLUGIN_CG) -if (OGRE_BUILD_PLUGIN_PFX) - add_dependencies(TestContext Plugin_ParticleFX) -endif () - -if (OGRE_BUILD_PLUGIN_PCZ) - add_dependencies(TestContext Plugin_PCZSceneManager) - add_dependencies(TestContext Plugin_OctreeZone) -endif () - -if (OGRE_BUILD_RENDERSYSTEM_D3D9) - add_dependencies(TestContext RenderSystem_Direct3D9) -endif () -if (OGRE_BUILD_RENDERSYSTEM_D3D11) - add_dependencies(TestContext RenderSystem_Direct3D11) -endif () -if (OGRE_BUILD_RENDERSYSTEM_GL) - add_dependencies(TestContext RenderSystem_GL) -endif () -if (OGRE_BUILD_RENDERSYSTEM_GL3PLUS) - add_dependencies(TestContext RenderSystem_GL3Plus) -endif () -if (OGRE_BUILD_RENDERSYSTEM_GLES2) - add_dependencies(TestContext RenderSystem_GLES2) -endif () - -add_dependencies(TestContext VTests PlayPenTests) - -if (APPLE) - if (APPLE_IOS) - set_property(TARGET TestContext PROPERTY MACOSX_BUNDLE TRUE) - set_property(TARGET TestContext PROPERTY MACOSX_BUNDLE_INFO_PLIST ${PROJECT_SOURCE_DIR}/Tests/VisualTests/Context/misc/Info.plist) - set(MACOSX_BUNDLE_GUI_IDENTIFIER "org.ogre3d.\${PRODUCT_NAME:rfc1034identifier}") - set_target_properties(TestContext PROPERTIES XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH "NO") - set_target_properties(TestContext PROPERTIES XCODE_ATTRIBUTE_TARGETED_DEVICE_FAMILY "1,2") - set (OGRE_TESTCONTEXT_CONTENTS_PATH - ${PROJECT_BINARY_DIR}/bin/$(CONFIGURATION)/TestContext.app) - add_custom_command(TARGET TestContext POST_BUILD - COMMAND ditto ${PROJECT_SOURCE_DIR}/Samples/Common/misc/*.png ${OGRE_TESTCONTEXT_CONTENTS_PATH}/ - COMMAND ditto ${PROJECT_BINARY_DIR}/bin/*.cfg ${OGRE_TESTCONTEXT_CONTENTS_PATH}/ - ) - add_custom_command(TARGET TestContext POST_BUILD - COMMAND mkdir ARGS -p ${PROJECT_BINARY_DIR}/lib/$(CONFIGURATION)/ - COMMAND ditto ${PROJECT_SOURCE_DIR}/Media ${OGRE_TESTCONTEXT_CONTENTS_PATH}/Media - COMMAND ditto ${PROJECT_SOURCE_DIR}/Samples/Media ${OGRE_TESTCONTEXT_CONTENTS_PATH}/Media - COMMAND ditto ${PROJECT_SOURCE_DIR}/Tests/Media ${OGRE_TESTCONTEXT_CONTENTS_PATH}/Media - ) - else() - set_property(TARGET TestContext PROPERTY MACOSX_BUNDLE TRUE) - set_property(TARGET TestContext PROPERTY MACOSX_BUNDLE_ICON_FILE SampleBrowser_OSX.icns) - set_property(TARGET TestContext PROPERTY MACOSX_BUNDLE_INFO_PLIST ${PROJECT_SOURCE_DIR}/Tests/VisualTests/Context/misc/Info.plist) - set(MACOSX_BUNDLE_GUI_IDENTIFIER "org.ogre3d.\${PRODUCT_NAME:rfc1034identifier}") - set_target_properties(TestContext PROPERTIES XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH "NO") - set (OGRE_TESTCONTEXT_CONTENTS_PATH - ${PROJECT_BINARY_DIR}/bin/$(CONFIGURATION)/TestContext.app/Contents) - add_custom_command(TARGET TestContext POST_BUILD - COMMAND mkdir ARGS -p ${OGRE_TESTCONTEXT_CONTENTS_PATH}/Frameworks - COMMAND ln ARGS -s -f ${PROJECT_BINARY_DIR}/lib/${OGRE_BUILT_FRAMEWORK}/Ogre.framework - ${OGRE_TESTCONTEXT_CONTENTS_PATH}/Frameworks/ - COMMAND ln ARGS -s -f ${Cg_LIBRARY_REL} - ${OGRE_TESTCONTEXT_CONTENTS_PATH}/Frameworks/ - ) - # now cfg files - add_custom_command(TARGET TestContext POST_BUILD - COMMAND mkdir ARGS -p ${OGRE_TESTCONTEXT_CONTENTS_PATH}/Resources - COMMAND ln ARGS -s -f ${PROJECT_BINARY_DIR}/bin/plugins.cfg - ${OGRE_TESTCONTEXT_CONTENTS_PATH}/Resources/ - COMMAND ln ARGS -s -f ${PROJECT_BINARY_DIR}/bin/resources.cfg - ${OGRE_TESTCONTEXT_CONTENTS_PATH}/Resources/ - COMMAND ln ARGS -s -f ${PROJECT_SOURCE_DIR}/Samples/Media - ${OGRE_TESTCONTEXT_CONTENTS_PATH}/Resources/ - COMMAND ditto - ${PROJECT_SOURCE_DIR}/Samples/Common/misc/SampleBrowser_OSX.icns ${OGRE_TESTCONTEXT_CONTENTS_PATH}/Resources - ) - - add_custom_command(TARGET TestContext POST_BUILD - COMMAND mkdir ARGS -p ${OGRE_TESTCONTEXT_CONTENTS_PATH}/Plugins - COMMAND ln ARGS -s -f ${PROJECT_BINARY_DIR}/lib/${OGRE_BUILT_FRAMEWORK}/PlayPenTests.dylib - ${OGRE_TESTCONTEXT_CONTENTS_PATH}/Plugins/ - COMMAND ln ARGS -s -f ${PROJECT_BINARY_DIR}/lib/${OGRE_BUILT_FRAMEWORK}/VTests.dylib - ${OGRE_TESTCONTEXT_CONTENTS_PATH}/Plugins/ - ) - - foreach(FWK ${FRAMEWORKS}) - add_custom_command(TARGET TestContext POST_BUILD - COMMAND ARGS if [ -d ${PROJECT_BINARY_DIR}/lib/${OGRE_BUILT_FRAMEWORK}/${FWK}.framework ]\; then ln -s -f ${PROJECT_BINARY_DIR}/lib/${OGRE_BUILT_FRAMEWORK}/${FWK}.framework ${OGRE_TESTCONTEXT_CONTENTS_PATH}/Frameworks/${FWK}.framework\; fi - ) - endforeach() - endif() -endif() - -# In Windows TestContext cannot be run from the build directory -# and thus must be installed to be useful. -if (WIN32) - ogre_install_target(TestContext "" FALSE) -endif() diff --git a/Tests/VisualTests/Context/include/TestContext.h b/Tests/VisualTests/Context/include/TestContext.h deleted file mode 100644 index 60e55a8d577..00000000000 --- a/Tests/VisualTests/Context/include/TestContext.h +++ /dev/null @@ -1,283 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#ifndef __TestContext_H__ -#define __TestContext_H__ - -#include "VisualTest.h" -#include "SampleContext.h" -#include "SamplePlugin.h" - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS && defined(__OBJC__) -#include -#import -#import -#endif - -class TestBatch; -using namespace Ogre; - -/** The common environment that all of the tests run in */ -class TestContext : public OgreBites::SampleContext -{ - public: - - TestContext(int argc = 0, char** argv = 0); - virtual ~TestContext(); - - /** Does basic setup for the context */ - void setup() override; - - bool frameRenderingQueued(const Ogre::FrameEvent& evt) override; - - /** Frame listener callback, handles updating of the tests at the start of frames - * @param evt The frame event (passed in for the framelistener) */ - bool frameStarted(const FrameEvent& evt) override; - - /** Frame listener callback, handles updating of the tests at the end of frames - * @param evt The frame event (passed in for the framelistener) */ - bool frameEnded(const FrameEvent& evt) override; - - /** Runs a given test or sample - * @param s The OgreBites::Sample to run - * @remarks If s is a VisualTest, then timing and rand will be setup for - * determinism. */ - void runSample(OgreBites::Sample* s) override; - - /** Loads test plugins - * @return The initial tets or sample to run */ - OgreBites::Sample* loadTests(); - - /** Setup the Root */ - void createRoot() override; - - /** Start it up */ - void go(OgreBites::Sample* initialSample = 0) override; - - /** Handles the config dialog */ - bool oneTimeConfig() override; - - /** Set up directories for the tests to output to */ - virtual void setupDirectories(String batchName); - - /** Called after tests successfully complete, generates output */ - virtual void finishedTests(); - - /** Sets the timstep value - * @param timestep The time to simulate elapsed between each frame - * @remarks Use with care! Screenshots produced at different timesteps - * will almost certainly turn out different. */ - void setTimestep(Real timestep); - - /** Gets the current timestep value */ - Real getTimestep(); - - /// Returns whether the entire test was successful or not. - bool wasSuccessful() const { - return mSuccess; - } - - private: - typedef std::map PluginMap; - bool mSuccess; - - /// The timestep - Real mTimestep; - - /// The tests to be run - std::deque mTests; - - /// Path to the output directory for the running test - String mOutputDir; - - /// Path to the reference set location - String mReferenceSetPath; - - /// The current frame of a running test - int mCurrentFrame; - - /// Info about the running batch of tests - TestBatch* mBatch; - - // A structure to map plugin names to class types - PluginMap mPluginNameMap; - - // command line options - // Is a reference set being generated? - bool mReferenceSet; - // Should html output be created? - bool mGenerateHtml; - // Force the config dialog - bool mForceConfig; - // Do not confine mouse to window - bool mNoGrabMouse; - // Show usage details - bool mHelp; - // Render system to use - String mRenderSystemName; - // Optional name for this batch - String mBatchName; - // Set to compare against - String mCompareWith; - // Optional comment - String mComment; - // Name of the test set to use - String mTestSetName; - // Location to output a test summary (used for CTest) - String mSummaryOutputDir; -}; - -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS && defined(__OBJC__) -@interface AppDelegate : NSObject -{ - TestContext *tc; - - CADisplayLink *mDisplayLink; - NSDate* mDate; - NSTimeInterval mLastFrameTime; -} - -- (void)go; -- (void)renderOneFrame:(id)sender; - -@property (nonatomic) NSTimeInterval mLastFrameTime; - - @end - - @implementation AppDelegate - - @dynamic mLastFrameTime; - - - (NSTimeInterval)mLastFrameTime -{ - return mLastFrameTime; -} - -- (void)setLastFrameTime:(NSTimeInterval)frameInterval -{ - // Frame interval defines how many display frames must pass between each time the - // display link fires. The display link will only fire 30 times a second when the - // frame internal is two on a display that refreshes 60 times a second. The default - // frame interval setting of one will fire 60 times a second when the display refreshes - // at 60 times a second. A frame interval setting of less than one results in undefined - // behavior. - if (frameInterval >= 1) - { - mLastFrameTime = frameInterval; - } -} - -- (void)go { - - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - NSArray * arguments = [[NSProcessInfo processInfo] arguments]; - char *argv[[arguments count]+1]; - int i = 0; - for (NSString *str in arguments) - { - argv[i++] = (char *)[str UTF8String]; - } - argv[i] = NULL; - - try { - tc = new TestContext([arguments count], &argv[0]); - tc->go(); - } catch( Exception& e ) { - std::cerr << "An exception has occurred: " << - e.getFullDescription().c_str() << std::endl; - } - - [pool release]; -} - -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions -{ - // Defaulting to 2 means that we run at 30 frames per second. For 60 frames, use a value of 1. - // 30 FPS is usually sufficient and results in lower power consumption. - mLastFrameTime = 2; - mDisplayLink = nil; - - [self go]; - - return YES; -} - -- (void)applicationWillTerminate:(UIApplication *)application -{ - tc->finishedTests(); -} - -- (void)applicationDidBecomeActive:(UIApplication *)application -{ - // Reset event times and reallocate the date and displaylink objects - Root::getSingleton().clearEventTimes(); - mDate = [[NSDate alloc] init]; - mLastFrameTime = 2; // Reset the timer - - mDisplayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(renderOneFrame:)]; - [mDisplayLink setFrameInterval:mLastFrameTime]; - [mDisplayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; -} - -- (void)applicationWillResignActive:(UIApplication *)application -{ - Root::getSingleton().saveConfig(); - - [mDate release]; - mDate = nil; - - [mDisplayLink invalidate]; - mDisplayLink = nil; -} - -- (void)renderOneFrame:(id)sender -{ - // NSTimeInterval is a simple typedef for double - NSTimeInterval currentFrameTime = -[mDate timeIntervalSinceNow]; - NSTimeInterval differenceInSeconds = currentFrameTime - mLastFrameTime; - mLastFrameTime = currentFrameTime; - - dispatch_async(dispatch_get_main_queue(), ^(void) - { - Root::getSingleton().renderOneFrame((Real)differenceInSeconds); - }); - - if(Root::getSingletonPtr() && Root::getSingleton().isInitialised() && !tc->getCurrentSample()) - { - tc->finishedTests(); - - // Force the app to exit. Acts like a crash which isn't very elegant but good enough in this case. - exit(0); - } -} - -@end - -#endif // OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS && defined(__OBJC__) - -#endif diff --git a/Tests/VisualTests/Context/misc/Info.plist b/Tests/VisualTests/Context/misc/Info.plist deleted file mode 100644 index 19c9331e8cf..00000000000 --- a/Tests/VisualTests/Context/misc/Info.plist +++ /dev/null @@ -1,58 +0,0 @@ - - - - - BuildMachineOSBuild - 12C60 - CFBundleDevelopmentRegion - English - CFBundleExecutable - TestContext - CFBundleIconFile - SampleBrowser_OSX.icns - CFBundleIdentifier - org.ogre3d.TestContext - CFBundleInfoDictionaryVersion - 6.0 - CFBundleLongVersionString - 1.0 - CFBundleShortVersionString - 1.0 - CFBundlePackageType - APPL - CFBundleSignature - ???? - CFBundleVersion - 1.0 - CSResourcesFileMapped - - DTCompiler - com.apple.compilers.llvm.clang.1_0 - DTPlatformBuild - 4H95e - DTPlatformVersion - GM - DTSDKBuild - 12C37 - DTSDKName - macosx10.8 - DTXcode - 0460 - DTXcodeBuild - 4H95e - LSRequiresCarbon - - NSHumanReadableCopyright - - NSPrincipalClass - NSApplication - UIStatusBarHidden - - UISupportedInterfaceOrientations - - UIInterfaceOrientationPortrait - UIInterfaceOrientationLandscapeRight - UIInterfaceOrientationLandscapeLeft - - - diff --git a/Tests/VisualTests/Context/src/TestContext.cpp b/Tests/VisualTests/Context/src/TestContext.cpp deleted file mode 100644 index 48cc57c6ca3..00000000000 --- a/Tests/VisualTests/Context/src/TestContext.cpp +++ /dev/null @@ -1,573 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "TestContext.h" -#include "SamplePlugin.h" -#include "TestResultWriter.h" -#include "HTMLWriter.h" -#include "CppUnitResultWriter.h" -#include "OgreConfigFile.h" -#include "OgrePlatform.h" -#include "OgreBitesConfigDialog.h" - -#include - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 -#define WIN32_LEAN_AND_MEAN -#include -#endif - -#include "VTestPlugin.h" -#include "PlayPenTestPlugin.h" - -TestContext::TestContext(int argc, char** argv) : OgreBites::SampleContext(), mSuccess(true), mTimestep(0.01f), mBatch(0) -{ - Ogre::UnaryOptionList unOpt; - Ogre::BinaryOptionList binOpt; - - // Prepopulate expected options. - unOpt["-r"] = false; // generate reference set - unOpt["--no-html"] = false; // whether or not to generate HTML - unOpt["-d"] = false; // force config dialog - unOpt["--nograb"] = false; // do not grab mouse - unOpt["-h"] = false; // help, give usage details - unOpt["--help"] = false; // help, give usage details - binOpt["-m"] = ""; // optional comment - binOpt["-rp"] = ""; // optional specified reference set location - binOpt["-od"] = ""; // directory to write output to - binOpt["-ts"] = "VTests"; // name of the test set to use - binOpt["-c"] = "Reference"; // name of batch to compare against - binOpt["-n"] = "AUTO"; // name for this batch - binOpt["-rs"] = "SAVED"; // rendersystem to use (default: use name from the config file/dialog) - binOpt["-o"] = "NONE"; // path to output a summary file to (default: don't output a file) - - // Parse. - Ogre::findCommandLineOpts(argc, argv, unOpt, binOpt); - - mReferenceSet = unOpt["-r"]; - mTestSetName = binOpt["-ts"]; - mComment = binOpt["-m"]; - mGenerateHtml = !unOpt["--no-html"]; - mBatchName = binOpt["-n"]; - mCompareWith = binOpt["-c"]; - mForceConfig = unOpt["-d"]; - mNoGrabMouse = unOpt["--nograb"]; - mOutputDir = binOpt["-od"]; - mRenderSystemName = binOpt["-rs"]; - mReferenceSetPath = binOpt["-rp"]; - mSummaryOutputDir = binOpt["-o"]; - mHelp = unOpt["-h"] || unOpt["--help"]; - - if(mReferenceSetPath.empty()) - mReferenceSetPath = mOutputDir; -} -//----------------------------------------------------------------------- - -TestContext::~TestContext() -{ - if (mBatch) - delete mBatch; -} -//----------------------------------------------------------------------- - -void TestContext::setup() -{ - mRoot->initialise(false); - - // Standard setup. -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - NameValuePairList miscParams; - CGSize modeSize = [[UIScreen mainScreen] currentMode].size; - uint w = modeSize.width / [UIScreen mainScreen].scale; - uint h = modeSize.height / [UIScreen mainScreen].scale; - - UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation; - - if (UIInterfaceOrientationIsPortrait(orientation)) - std::swap(w, h); - - - miscParams["retainedBacking"] = StringConverter::toString(true); - mWindow = mRoot->createRenderWindow("OGRE Sample Browser", w, h, true, &miscParams); -#else - auto desc = mRoot->getRenderSystem()->getRenderWindowDescription(); - desc.name = "OGRE VTest Context"; - mWindow = mRoot->createRenderWindow(desc); -#endif - - mWindow->setDeactivateOnFocusChange(false); - - locateResources(); - initialiseRTShaderSystem(); - - loadResources(); - Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5); - mRoot->addFrameListener(this); - - mPluginNameMap["VTests"] = new VTestPlugin(); - mPluginNameMap["PlayPenTests"] = new PlaypenTestPlugin(); - - Ogre::String batchName = BLANKSTRING; - time_t raw = time(0); - - // timestamp for the filename - char temp[25]; - strftime(temp, 19, "%Y_%m_%d_%H%M_%S", gmtime(&raw)); - - // A nicer formatted version for display. - strftime(temp, 20, "%Y-%m-%d %H:%M:%S", gmtime(&raw)); - Ogre::String timestamp = Ogre::String(temp); - - if(mOutputDir.empty()) - { - Ogre::String filestamp = Ogre::String(temp); - // name for this batch (used for naming the directory, and uniquely identifying this batch) - batchName = mTestSetName + "_" + filestamp; - - if (mReferenceSet) - batchName = "Reference"; - else if (mBatchName != "AUTO") - batchName = mBatchName; - } - - // Set up output directories. - setupDirectories(batchName); - - // An object storing info about this set. - mBatch = new TestBatch(batchName, mTestSetName, timestamp, - mWindow->getWidth(), mWindow->getHeight(), mOutputDir + batchName + "/"); - mBatch->comment = mComment; - - OgreBites::Sample* firstTest = loadTests(); - if (firstTest) - runSample(firstTest); -} -//----------------------------------------------------------------------- - -OgreBites::Sample* TestContext::loadTests() -{ - OgreBites::Sample* startSample = 0; - - // load all of the plugins in the set - for(auto it : mPluginNameMap) - { - OgreBites::SampleSet newSamples = it.second->getSamples(); - for (auto newSample : newSamples) - { - // capability check - try - { - newSample->testCapabilities(mRoot->getRenderSystem()->getCapabilities()); - } - catch(Ogre::Exception&) - { - continue; - } - - mTests.push_back(newSample); - } - } - - // start with the first one on the list - if (!mTests.empty()) - { - startSample = mTests.front(); - return startSample; - } - else - return 0; -} -//----------------------------------------------------------------------- - -bool TestContext::frameRenderingQueued(const Ogre::FrameEvent& evt) -{ - // pass a fixed timestep along to the tests - Ogre::FrameEvent fixed_evt = Ogre::FrameEvent(); - fixed_evt.timeSinceLastFrame = mTimestep; - fixed_evt.timeSinceLastEvent = mTimestep; - - return mCurrentSample->frameRenderingQueued(fixed_evt); -} - -bool TestContext::frameStarted(const Ogre::FrameEvent& evt) -{ - pollEvents(); - - // pass a fixed timestep along to the tests - Ogre::FrameEvent fixed_evt = Ogre::FrameEvent(); - fixed_evt.timeSinceLastFrame = mTimestep; - fixed_evt.timeSinceLastEvent = mTimestep; - - if (mCurrentSample) // if a test is running - { - // track frame number for screenshot purposes - ++mCurrentFrame; - - // regular update function - return mCurrentSample->frameStarted(fixed_evt); - } - else - { - // if no more tests are queued, generate output and exit - finishedTests(); - return false; - } -} -//----------------------------------------------------------------------- - -bool TestContext::frameEnded(const Ogre::FrameEvent& evt) -{ - // pass a fixed timestep along to the tests - Ogre::FrameEvent fixed_evt = Ogre::FrameEvent(); - fixed_evt.timeSinceLastFrame = mTimestep; - fixed_evt.timeSinceLastEvent = mTimestep; - - if (mCurrentSample) // if a test is running - { - if (mCurrentSample->isScreenshotFrame(mCurrentFrame)) - { - // take a screenshot - Ogre::String filename = mOutputDir + mBatch->name + "/" + - mCurrentSample->getInfo()["Title"] + "_" + - Ogre::StringConverter::toString(mCurrentFrame) + ".png"; - // remember the name of the shot, for later comparison purposes - mBatch->images.push_back(mCurrentSample->getInfo()["Title"] + "_" + - Ogre::StringConverter::toString(mCurrentFrame)); - mWindow->writeContentsToFile(filename); - } - - if (mCurrentSample->isDone()) - { - // continue onto the next test - runSample(0); - - return true; - } - - // standard update function - return mCurrentSample->frameEnded(fixed_evt); - } - else - { - // if no more tests are queued, generate output and exit - finishedTests(); - return false; - } -} -//----------------------------------------------------------------------- - -void TestContext::runSample(OgreBites::Sample* sampleToRun) -{ - // reset frame timing - mCurrentFrame = 0; - - // If a valid test is passed, then run it - // If null, grab the next one from the deque - if (!sampleToRun && !mTests.empty()) - { - mTests.pop_front(); - if (!mTests.empty()) - sampleToRun = mTests.front(); - } - - if(mCurrentSample) - { - mCurrentSample->_shutdown(); - mCurrentSample = NULL; - } - - // Set things up to be deterministic - // Seed rand with a predictable value - srand(5); // 5 is completely arbitrary, the idea is simply to use a constant - // Give a fixed timestep for particles and other time-dependent things in OGRE - Ogre::ControllerManager::getSingleton().setFrameDelay(mTimestep); - - if(sampleToRun) - LogManager::getSingleton().logMessage("----- Running Visual Test " + sampleToRun->getInfo()["Title"] + " -----"); - SampleContext::runSample(sampleToRun); -} -//----------------------------------------------------------------------- - -void TestContext::createRoot() -{ - // note that we use a separate config file here -#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID - mRoot = Ogre::Root::getSingletonPtr(); -#else - Ogre::String pluginsPath = Ogre::BLANKSTRING; -#ifndef OGRE_STATIC_LIB - pluginsPath = mFSLayer->getConfigFilePath("plugins.cfg"); -#endif - // we use separate config and log files for the tests - mRoot = OGRE_NEW Ogre::Root(pluginsPath, mFSLayer->getWritablePath("ogretests.cfg"), - mFSLayer->getWritablePath("ogretests.log")); -#endif - -#ifdef OGRE_STATIC_LIB - mStaticPluginLoader.load(); -#endif - mOverlaySystem = OGRE_NEW Ogre::OverlaySystem(); -} -//----------------------------------------------------------------------- - -void TestContext::go(OgreBites::Sample* initialSample) -{ - // Either start up as usual or print usage details. - if (!mHelp) - { - SampleContext::go(initialSample); - } - else - { - std::cout<<"\nOgre Visual Testing Context:\n"; - std::cout<<"Runs sets of visual test scenes, taking screenshots, and running comparisons.\n\n"; - std::cout<<"Usage: TestContext [opts]\n\n"; - std::cout<<"Options:\n"; - std::cout<<"\t-r Generate reference set.\n"; - std::cout<<"\t--no-html Suppress html output.\n"; - std::cout<<"\t-d Force config dialog.\n"; - std::cout<<"\t-h, --help Show usage details.\n"; - std::cout<<"\t-m [comment] Optional comment.\n"; - std::cout<<"\t-ts [name] Name of the test set to use.\n"; - std::cout<<"\t-c [name] Name of the test result batch to compare against.\n"; - std::cout<<"\t-n [name] Name for this result image set.\n"; - std::cout<<"\t-rs [name] Render system to use.\n"; - std::cout<<"\t-o [path] Path to output a simple summary file to.\n"; - std::cout<<"\t--nograb Do not restrict mouse to window (warning: may affect results).\n\n"; - } -} -//----------------------------------------------------------------------- - -bool TestContext::oneTimeConfig() -{ - // if forced, just do it and return - if(mForceConfig) - { - bool temp = mRoot->showConfigDialog(OgreBites::getNativeConfigDialog()); - if(!temp) - mRoot->setRenderSystem(NULL); - return temp; - } - - // try restore - bool restore = mRoot->restoreConfig(); - - // set render system if user-defined - if(restore && mRenderSystemName != "SAVED" && mRoot->getRenderSystemByName(mRenderSystemName)) { - mRoot->setRenderSystem(mRoot->getRenderSystemByName(mRenderSystemName)); - } - else if(!restore) { - RenderSystem* rs = NULL; - - const auto& allRS = Root::getSingleton().getAvailableRenderers(); - - if(mRenderSystemName != "SAVED") - rs = mRoot->getRenderSystemByName(mRenderSystemName); - else if(!allRS.empty()) - rs = allRS.front(); // just select the first available - - mRoot->setRenderSystem(rs); - - if(rs) { - // set sane defaults - rs->setConfigOption("Full Screen", "No"); - rs->setConfigOption("Video Mode", "640x 480"); - - // test alpha to coverage and MSAA resolve - rs->setConfigOption("FSAA", "2"); - - try { - rs->setConfigOption("VSync", "No"); - } catch(...) {} - } - } - - mRenderSystemName = mRoot->getRenderSystem() ? mRoot->getRenderSystem()->getName() : ""; - - return mRoot->getRenderSystem() != NULL; -} -//----------------------------------------------------------------------- - -void TestContext::setupDirectories(Ogre::String batchName) -{ - // ensure there's a root directory for visual tests - if(mOutputDir.empty()) - { - mOutputDir = mFSLayer->getWritablePath("VisualTests/"); - static_cast(mFSLayer)->createDirectory(mOutputDir); - - // make sure there's a directory for the test set - mOutputDir += mTestSetName + "/"; - static_cast(mFSLayer)->createDirectory(mOutputDir); - - // add a directory for the render system - Ogre::String rsysName = Ogre::Root::getSingleton().getRenderSystem()->getName(); - // strip spaces from render system name - for (char i : rsysName) - if (i != ' ') - mOutputDir += i; - mOutputDir += "/"; - static_cast(mFSLayer)->createDirectory(mOutputDir); - } - - if(mSummaryOutputDir != "NONE") - { - static_cast(mFSLayer)->createDirectory(mSummaryOutputDir); - } - - // and finally a directory for the test batch itself - static_cast(mFSLayer)->createDirectory(mOutputDir - + batchName + "/"); -} -//----------------------------------------------------------------------- - -void TestContext::finishedTests() -{ - if ((mGenerateHtml || mSummaryOutputDir != "NONE") && !mReferenceSet) - { - const TestBatch* compareTo = 0; - TestBatchSet batches; - - Ogre::ConfigFile info; - bool foundReference = true; - TestBatch* ref = 0; - - // look for a reference set first (either "Reference" or a user-specified image set) - try - { - info.load(mReferenceSetPath + mCompareWith + "/info.cfg"); - } - catch (Ogre::FileNotFoundException&) - { - // if no luck, just grab the most recent compatible set - foundReference = false; - batches = TestBatch::loadTestBatches(mOutputDir); - - TestBatchSet::iterator i; - for (i = batches.begin(); i != batches.end(); ++i) - { - if (mBatch->canCompareWith((*i))) - { - compareTo = &(*i); - break; - } - } - } - - if (foundReference) - { - ref = OGRE_NEW TestBatch(info, mReferenceSetPath + mCompareWith); - if (mBatch->canCompareWith(*ref)) - compareTo = ref; - } - - if (compareTo) - { - ComparisonResultVector results = mBatch->compare(*compareTo); - - if(mGenerateHtml) - { - HtmlWriter writer(*compareTo, *mBatch, results); - - // we save a generally named "out.html" that gets overwritten each run, - // plus a uniquely named one for this run - writer.writeToFile(mOutputDir + "out.html"); - writer.writeToFile(mOutputDir + "TestResults_" + mBatch->name + ".html"); - } - - // also save a summary file for CTest to parse, if required - if(mSummaryOutputDir != "NONE") - { - Ogre::String rs; - for(char j : mRenderSystemName) - if(j!=' ') - rs += j; - - CppUnitResultWriter cppunitWriter(*compareTo, *mBatch, results); - cppunitWriter.writeToFile(mSummaryOutputDir + "/TestResults_" + rs + ".xml"); - } - - for(auto & result : results) { - mSuccess = mSuccess && result.passed; - } - } - - OGRE_DELETE ref; - } - - // write this batch's config file - mBatch->writeConfig(); -} -//----------------------------------------------------------------------- - -Ogre::Real TestContext::getTimestep() -{ - return mTimestep; -} -//----------------------------------------------------------------------- - -void TestContext::setTimestep(Ogre::Real timestep) -{ - // ensure we're getting a positive value - mTimestep = timestep >= 0.f ? timestep : mTimestep; -} - -// main, platform-specific stuff is copied from SampleBrowser and not guaranteed to work... - -// since getting commandline args out of WinMain isn't pretty, just use plain main for now... -//#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 -//INT WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, INT) -//#else -int main(int argc, char *argv[]) -//#endif -{ -#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - int retVal = UIApplicationMain(argc, argv, @"UIApplication", @"AppDelegate"); - [pool release]; - return retVal; -#else - TestContext tc(argc, argv); - - try - { - tc.go(); - } - catch (Ogre::Exception& e) - { -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 - MessageBoxA(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_ICONERROR | MB_TASKMODAL); -#else - std::cerr << "An exception has occurred: " << e.getFullDescription().c_str() << std::endl; - - return -1; -#endif - } - - return !tc.wasSuccessful(); -#endif -} diff --git a/Tests/VisualTests/PlayPen/CMakeLists.txt b/Tests/VisualTests/PlayPen/CMakeLists.txt deleted file mode 100644 index d62b7893fef..00000000000 --- a/Tests/VisualTests/PlayPen/CMakeLists.txt +++ /dev/null @@ -1,33 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -set(HEADER_FILES - include/PlayPenTestPlugin.h - include/PlayPenTests.h) - -set(SOURCE_FILES - src/PlayPenTests.cpp - src/PlayPenTestPlugin.cpp) - -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) -include_directories(${PROJECT_SOURCE_DIR}/Samples/Common/include) -include_directories(${PROJECT_SOURCE_DIR}/Samples/Browser/include) -include_directories(${PROJECT_SOURCE_DIR}/Tests/VisualTests/Common/include) - -add_library(PlayPenTests ${OGRE_LIB_TYPE} ${HEADER_FILES} ${SOURCE_FILES}) -target_link_libraries(PlayPenTests ${OGRE_LIBRARIES} ${SDL2_LIBRARY} OgreBites OgreOverlay OgreRTShaderSystem) -ogre_config_sample_lib(PlayPenTests) - -if (APPLE AND NOT APPLE_IOS) - # Set the INSTALL_PATH so that Samples can be installed in the application package - set_target_properties(PlayPenTests - PROPERTIES BUILD_WITH_INSTALL_RPATH 1 - INSTALL_NAME_DIR "@executable_path/../Plugins" - ) -endif() diff --git a/Tests/VisualTests/PlayPen/include/PlayPenTestPlugin.h b/Tests/VisualTests/PlayPen/include/PlayPenTestPlugin.h deleted file mode 100644 index f7af4446255..00000000000 --- a/Tests/VisualTests/PlayPen/include/PlayPenTestPlugin.h +++ /dev/null @@ -1,42 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __PlayPenPlugin_H__ -#define __PlayPenPlugin_H__ - -#include "SamplePlugin.h" - -/** Plugin class for visual tests */ -class _OgreSampleExport PlaypenTestPlugin : public OgreBites::SamplePlugin -{ -public: - PlaypenTestPlugin(); - ~PlaypenTestPlugin(); -}; - -#endif diff --git a/Tests/VisualTests/PlayPen/include/PlayPenTests.h b/Tests/VisualTests/PlayPen/include/PlayPenTests.h deleted file mode 100644 index b95b5e88ac2..00000000000 --- a/Tests/VisualTests/PlayPen/include/PlayPenTests.h +++ /dev/null @@ -1,1559 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __PlayPenTests_H__ -#define __PlayPenTests_H__ - -#include "VisualTest.h" -#include "SamplePlugin.h" -#include "SdkSample.h" - -using namespace Ogre; - -#ifdef OGRE_BUILD_COMPONENT_MESHLODGENERATOR -//--------------------------------------------------------------------------- -/** Test of manual LOD */ -class _OgreSampleClassExport PlayPen_ManualLOD : public VisualTest -{ -public: - - PlayPen_ManualLOD(); - bool frameStarted(const FrameEvent& evt) override; - -protected: - - void setupContent() override; - String getLODMesh(); - - AnimationState* mAnimation; - -}; - -//--------------------------------------------------------------------------- -/** Test of Manual LOD from a file */ -class _OgreSampleClassExport PlayPen_ManualLODFromFile : public PlayPen_ManualLOD -{ -public: - - PlayPen_ManualLODFromFile(); - -protected: - - String getLODMesh(); - -}; -#endif -//--------------------------------------------------------------------------- -/** Test of Manual Blending */ -class _OgreSampleClassExport PlayPen_ManualBlend : public VisualTest -{ -public: - - PlayPen_ManualBlend(); - -protected: - - void setupContent() override; - -}; - -//--------------------------------------------------------------------------- -/** Testing sphere projection */ -class _OgreSampleClassExport PlayPen_ProjectSphere : public VisualTest -{ -public: - - PlayPen_ProjectSphere(); - bool frameStarted(const FrameEvent& evt) override; - -protected: - - Sphere* mProjectionSphere; - ManualObject* mScissorRect; - void setupContent() override; - -}; - -//--------------------------------------------------------------------------- -/** Testing setting the camera's direction */ -class _OgreSampleClassExport PlayPen_CameraSetDirection : public VisualTest -{ -public: - - PlayPen_CameraSetDirection(); - void buttonHit(OgreBites::Button* button) override; - void checkBoxToggled(OgreBites::CheckBox* box) override; - -protected: - - bool mUseParentNode; - bool mUseFixedYaw; - SceneNode* mParentNode; - Vector3 mFocus; - void setupContent() override; - void toggleParentNode(); - void toggleFixedYaw(); - void track(); - -}; - -//--------------------------------------------------------------------------- -/** Testing morph animation with normals */ -class _OgreSampleClassExport PlayPen_MorphAnimationWithNormals : public VisualTest -{ -public: - - PlayPen_MorphAnimationWithNormals(); - bool frameStarted(const FrameEvent& evt) override; - -protected: - - void setupContent() override; - AnimationState* mAnimations[2]; - -}; - -//--------------------------------------------------------------------------- -/** Testing morph animation without normals */ -class _OgreSampleClassExport PlayPen_MorphAnimationWithoutNormals : public VisualTest -{ -public: - - PlayPen_MorphAnimationWithoutNormals(); - bool frameStarted(const FrameEvent& evt) override; - -protected: - - void setupContent() override; - AnimationState* mAnimations[2]; - -}; - -//--------------------------------------------------------------------------- -/** Testing pose animation with normals */ -class _OgreSampleClassExport PlayPen_PoseAnimationWithNormals : public VisualTest -{ -public: - - PlayPen_PoseAnimationWithNormals(); - bool frameStarted(const FrameEvent& evt) override; - -protected: - - void setupContent() override; - AnimationState* mAnimations[2]; - -}; - -//--------------------------------------------------------------------------- -/** Testing pose animation without normals */ -class _OgreSampleClassExport PlayPen_PoseAnimationWithoutNormals : public VisualTest -{ -public: - - PlayPen_PoseAnimationWithoutNormals(); - bool frameStarted(const FrameEvent& evt) override; - -protected: - - void setupContent() override; - AnimationState* mAnimations[2]; - -}; -// -//--------------------------------------------------------------------------- -/** Testing scene node tracking */ -class _OgreSampleClassExport PlayPen_SceneNodeTracking : public VisualTest -{ -public: - - PlayPen_SceneNodeTracking(); - bool frameStarted(const FrameEvent& evt) override; - -protected: - - void setupContent() override; - AnimationState* mAnimState; - -}; -//--------------------------------------------------------------------------- - -// forward declare, but don't define yet to keep this header clean -class StencilOpQueueListener; - -/** Testing stencil glow effects */ -class _OgreSampleClassExport PlayPen_StencilGlow : public VisualTest -{ -public: - - PlayPen_StencilGlow(); - virtual ~PlayPen_StencilGlow(); - -protected: - - void setupContent() override; - StencilOpQueueListener* mStencilListener; - -}; -//------------------------------------------------------------------------------ -/** Tests normal mapping with mirrored UVs */ -class _OgreSampleClassExport PlayPen_NormalMapMirroredUVs : public VisualTest -{ -public: - - PlayPen_NormalMapMirroredUVs(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests mipmaps on a transparent material */ -class _OgreSampleClassExport PlayPen_TransparencyMipMaps : public VisualTest -{ -public: - - PlayPen_TransparencyMipMaps(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests basic plane object rendering */ -class _OgreSampleClassExport PlayPen_BasicPlane : public VisualTest -{ -public: - - PlayPen_BasicPlane(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests BSP plugin */ -class _OgreSampleClassExport PlayPen_Bsp : public VisualTest -{ -public: - - PlayPen_Bsp(); - - StringVector getRequiredPlugins() override - { - StringVector names; - names.push_back("BSP Scene Manager"); - return names; - } - - void createSceneManager() override - { - mSceneMgr = mRoot->createSceneManager("BspSceneManager"); -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - mShaderGenerator->addSceneManager(mSceneMgr); -#endif - } - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests simple projection */ -class _OgreSampleClassExport PlayPen_Projection : public VisualTest -{ -public: - - PlayPen_Projection(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests multiple viewports */ -class _OgreSampleClassExport PlayPen_MultiViewports : public VisualTest -{ -public: - - PlayPen_MultiViewports(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ - -class RefractionTextureListener; -class ReflectionTextureListener; - -/** Tests reflection/refraction. */ -class _OgreSampleClassExport PlayPen_Distortion : public VisualTest -{ -public: - - PlayPen_Distortion(); - virtual ~PlayPen_Distortion(); - -protected: - - void setupContent() override; - void cleanupContent() override; - - RefractionTextureListener* mRefractionListener; - ReflectionTextureListener* mReflectionListener; - -}; - -//------------------------------------------------------------------------------ -/** Tests skeletal animation */ -class _OgreSampleClassExport PlayPen_SkeletalAnimation : public VisualTest -{ -public: - - PlayPen_SkeletalAnimation(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests windowed viewports */ -class _OgreSampleClassExport PlayPen_WindowedViewportMode : public VisualTest -{ -public: - - PlayPen_WindowedViewportMode(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests visibility settings for sub entities */ -class _OgreSampleClassExport PlayPen_SubEntityVisibility : public VisualTest -{ -public: - - PlayPen_SubEntityVisibility(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests attaching objects to bones */ -class _OgreSampleClassExport PlayPen_AttachObjectsToBones : public VisualTest -{ -public: - - PlayPen_AttachObjectsToBones(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests orthographic rendering */ -class _OgreSampleClassExport PlayPen_Ortho : public VisualTest -{ -public: - - PlayPen_Ortho(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests clearing a running scene */ -class _OgreSampleClassExport PlayPen_ClearScene : public VisualTest -{ -public: - - PlayPen_ClearScene(); - bool isScreenshotFrame(int frame) override; - -protected: - void setupContent() override; -}; - -//------------------------------------------------------------------------------ -/** Tests stencil shadows */ -class _OgreSampleClassExport PlayPen_StencilShadows : public VisualTest -{ -public: - - PlayPen_StencilShadows(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests stencil shadows with mixed operation submeshes */ -class _OgreSampleClassExport PlayPen_StencilShadowsMixedOpSubMeshes : public VisualTest -{ -public: - - PlayPen_StencilShadowsMixedOpSubMeshes(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests 2 spotlights casting light on a single mesh */ -class _OgreSampleClassExport PlayPen_2Spotlights : public VisualTest -{ -public: - - PlayPen_2Spotlights(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests texture shadows */ -class _OgreSampleClassExport PlayPen_TextureShadows : public VisualTest -{ -public: - - PlayPen_TextureShadows(); - -protected: - - void setupContent() override; - void cleanupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests custom texture shadow caster materials */ -class _OgreSampleClassExport PlayPen_TextureShadowsCustomCasterMat : public PlayPen_TextureShadows -{ -public: - - PlayPen_TextureShadowsCustomCasterMat(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests a custom shadow receiver material for texture shadows */ -class _OgreSampleClassExport PlayPen_TextureShadowsCustomReceiverMat : public PlayPen_TextureShadows -{ -public: - - PlayPen_TextureShadowsCustomReceiverMat(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests applying a compositor to texture shadow rendering */ -class _OgreSampleClassExport PlayPen_CompositorTextureShadows : public VisualTest -{ -public: - - PlayPen_CompositorTextureShadows(); - -protected: - - void setupContent() override; - void cleanupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests switching compositor techniques rapidly */ -class _OgreSampleClassExport PlayPen_CompositorTechniqueSwitch : public VisualTest -{ -public: - - PlayPen_CompositorTechniqueSwitch(); - bool frameStarted(const FrameEvent& evt) override; - -protected: - - void setupContent() override; - void cleanupContent() override; - - CompositorInstance* mCompositorToSwitch; - size_t mCompositorIndex; - Real mTimeUntilNextToggle; - StringVector mCompositorSchemeList; - -}; - -//------------------------------------------------------------------------------ -/** Tests creation and rendering of a whole lot of entities */ -class _OgreSampleClassExport PlayPen_LotsAndLotsOfEntities : public VisualTest -{ -public: - - PlayPen_LotsAndLotsOfEntities(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests infinite bounding boxes */ -class _OgreSampleClassExport PlayPen_InfiniteAAB : public VisualTest -{ -public: - - PlayPen_InfiniteAAB(); - - StringVector getRequiredPlugins() override - { - StringVector names; - names.push_back("BSP Scene Manager"); - return names; - } - - void createSceneManager() override - { - mSceneMgr = mRoot->createSceneManager("BspSceneManager"); -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - mShaderGenerator->addSceneManager(mSceneMgr); -#endif - } - -protected: - - void setupContent() override; - void cleanupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests static geometry */ -class _OgreSampleClassExport PlayPen_StaticGeometry : public VisualTest -{ -public: - - PlayPen_StaticGeometry(); - -protected: - - void setupContent() override; - -}; - -#ifdef OGRE_BUILD_COMPONENT_MESHLODGENERATOR -//------------------------------------------------------------------------------ -/** Tests static geometry with LODs */ -class _OgreSampleClassExport PlayPen_StaticGeometryWithLOD : public VisualTest -{ -public: - - PlayPen_StaticGeometryWithLOD(); - -protected: - - void setupContent() override; - -}; -#endif - -//------------------------------------------------------------------------------ -/** Tests reloading resources */ -class _OgreSampleClassExport PlayPen_ReloadResources : public VisualTest -{ -public: - - PlayPen_ReloadResources(); - bool frameStarted(const FrameEvent& evt) override; - -protected: - - void setupContent() override; - Real mReloadTimer; - -}; - -//------------------------------------------------------------------------------ -/** Tests billboard texture coordinates */ -class _OgreSampleClassExport PlayPen_BillboardTextureCoords : public VisualTest -{ -public: - - PlayPen_BillboardTextureCoords(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests particles with an RTT reflection */ -class _OgreSampleClassExport PlayPen_ReflectedBillboards : public VisualTest -{ -public: - - PlayPen_ReflectedBillboards(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests non-indexed manual object */ -class _OgreSampleClassExport PlayPen_ManualObjectNonIndexed : public VisualTest -{ -public: - - PlayPen_ManualObjectNonIndexed(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests non-indexed manual objects updated with fewer verts/faces */ -class _OgreSampleClassExport PlayPen_ManualObjectNonIndexedUpdateSmaller : public PlayPen_ManualObjectNonIndexed -{ -public: - - PlayPen_ManualObjectNonIndexedUpdateSmaller(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests non-indexed manual objects updated with more verts/faces */ -class _OgreSampleClassExport PlayPen_ManualObjectNonIndexedUpdateLarger : public PlayPen_ManualObjectNonIndexed -{ -public: - - PlayPen_ManualObjectNonIndexedUpdateLarger(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests indexed manual objects */ -class _OgreSampleClassExport PlayPen_ManualObjectIndexed : public VisualTest -{ -public: - - PlayPen_ManualObjectIndexed(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests indexed manual objects updating with less verts/faces */ -class _OgreSampleClassExport PlayPen_ManualObjectIndexedUpdateSmaller : public PlayPen_ManualObjectIndexed -{ -public: - - PlayPen_ManualObjectIndexedUpdateSmaller(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests indexed manual objects updating with more verts/faces */ -class _OgreSampleClassExport PlayPen_ManualObjectIndexedUpdateLarger : public PlayPen_ManualObjectIndexed -{ -public: - - PlayPen_ManualObjectIndexedUpdateLarger(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests billboard chain rendering */ -class _OgreSampleClassExport PlayPen_BillboardChain : public VisualTest -{ -public: - - PlayPen_BillboardChain(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests DDS cubemaps */ -class _OgreSampleClassExport PlayPen_CubeDDS : public VisualTest -{ -public: - - PlayPen_CubeDDS(); - -protected: - - void setupContent() override; - -}; - -class _OgreSampleClassExport PlayPen_AlphaTex : public VisualTest -{ -public: - - PlayPen_AlphaTex(); - -protected: - - void setupContent() override; - -}; - -class PlayPen_TwoSidedLighting : public VisualTest -{ -public: - - PlayPen_TwoSidedLighting(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests DXT1 loading */ -class _OgreSampleClassExport PlayPen_Dxt1 : public VisualTest -{ -public: - - PlayPen_Dxt1(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests DXT1 loading from memory */ -class _OgreSampleClassExport PlayPen_Dxt1FromMemory : public VisualTest -{ -public: - - PlayPen_Dxt1FromMemory(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests DXT1 loading with alpha channel */ -class _OgreSampleClassExport PlayPen_Dxt1Alpha : public VisualTest -{ -public: - - PlayPen_Dxt1Alpha(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests DXT3 loading */ -class _OgreSampleClassExport PlayPen_Dxt3 : public VisualTest -{ -public: - - PlayPen_Dxt3(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests DXT3 loading from memory */ -class _OgreSampleClassExport PlayPen_Dxt3FromMemory : public VisualTest -{ -public: - - PlayPen_Dxt3FromMemory(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests DXT5 loading */ -class _OgreSampleClassExport PlayPen_Dxt5 : public VisualTest -{ -public: - - PlayPen_Dxt5(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests ribbon trail rendering */ -class _OgreSampleClassExport PlayPen_RibbonTrail : public VisualTest -{ -public: - - PlayPen_RibbonTrail(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests diffuse blending */ -class _OgreSampleClassExport PlayPen_BlendDiffuseColour : public VisualTest -{ -public: - - PlayPen_BlendDiffuseColour(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests custom projection matrices */ -class _OgreSampleClassExport PlayPen_CustomProjectionMatrix : public PlayPen_LotsAndLotsOfEntities -{ -public: - - PlayPen_CustomProjectionMatrix(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests point sprites */ -class _OgreSampleClassExport PlayPen_PointSprites : public VisualTest -{ -public: - - PlayPen_PointSprites(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests excluding shadows from a viewport */ -class _OgreSampleClassExport PlayPen_ViewportNoShadows : public VisualTest -{ -public: - - PlayPen_ViewportNoShadows(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests serializing vertex colors in meshes */ -class _OgreSampleClassExport PlayPen_SerialisedColour : public VisualTest -{ -public: - - PlayPen_SerialisedColour(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests billboard facing */ -class _OgreSampleClassExport PlayPen_BillboardAccurateFacing : public VisualTest -{ -public: - - PlayPen_BillboardAccurateFacing(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests multiple scene managers */ -class _OgreSampleClassExport PlayPen_MultiSceneManagersSimple : public VisualTest -{ -public: - - PlayPen_MultiSceneManagersSimple(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests manually moving bones */ -class _OgreSampleClassExport PlayPen_ManualBoneMovement : public VisualTest -{ -public: - - PlayPen_ManualBoneMovement(); - bool frameStarted(const FrameEvent& evt) override; - -protected: - - void setupContent() override; - Bone* mBone; - -}; - -//------------------------------------------------------------------------------ -/** Tests material schemes in viewports */ -class _OgreSampleClassExport PlayPen_MaterialSchemes : public VisualTest -{ -public: - - PlayPen_MaterialSchemes(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests material scehemes with listener */ -class _OgreSampleClassExport PlayPen_MaterialSchemesListener : public VisualTest -{ -public: - - PlayPen_MaterialSchemesListener(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests material schemes with LODs */ -class _OgreSampleClassExport PlayPen_MaterialSchemesWithLOD : public VisualTest -{ -public: - - PlayPen_MaterialSchemesWithLOD(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests material schemes in viewports with different LODs */ -class _OgreSampleClassExport PlayPen_MaterialSchemesWithMismatchedLOD : public VisualTest -{ -public: - - PlayPen_MaterialSchemesWithMismatchedLOD(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests hardware/software animation */ -class _OgreSampleClassExport PlayPen_SkeletonAnimationOptimise : public VisualTest -{ -public: - - PlayPen_SkeletonAnimationOptimise(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests vertex textures (DX only) */ -class _OgreSampleClassExport PlayPen_VertexTexture : public VisualTest -{ -public: - - PlayPen_VertexTexture(); - - void testCapabilities(const RenderSystemCapabilities* caps) override - { - if(!caps->isShaderProfileSupported("hlsl") && !caps->isShaderProfileSupported("glsl")) - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "not implemented"); - } - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests setting billboard origin */ -class _OgreSampleClassExport PlayPen_BillboardOrigins : public VisualTest -{ -public: - - PlayPen_BillboardOrigins(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests depth biasing */ -class _OgreSampleClassExport PlayPen_DepthBias : public VisualTest -{ -public: - - PlayPen_DepthBias(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests transparent texture shadow casters */ -class _OgreSampleClassExport PlayPen_TextureShadowsTransparentCaster : public VisualTest -{ -public: - - PlayPen_TextureShadowsTransparentCaster(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests integrated texture shadows */ -class _OgreSampleClassExport PlayPen_TextureShadowsIntegrated : public VisualTest -{ -public: - - PlayPen_TextureShadowsIntegrated(); - -protected: - - void setupContent() override; - void cleanupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests integrated texture shadows with parallel splits */ -class _OgreSampleClassExport PlayPen_TextureShadowsIntegratedPSSM : public VisualTest -{ -public: - - PlayPen_TextureShadowsIntegratedPSSM(); - -protected: - - void setupContent() override; - void cleanupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests light scissoring */ -class _OgreSampleClassExport PlayPen_LightScissoring : public VisualTest -{ -public: - - PlayPen_LightScissoring(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests light clipping planes */ -class _OgreSampleClassExport PlayPen_LightClipPlanes : public VisualTest -{ -public: - - PlayPen_LightClipPlanes(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests light clipping planes with lots of lights */ -class _OgreSampleClassExport PlayPen_LightClipPlanesMoreLights : public VisualTest -{ -public: - - PlayPen_LightClipPlanesMoreLights(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests MRT */ -class _OgreSampleClassExport PlayPen_MRT : public VisualTest -{ -public: - - PlayPen_MRT(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests applying many textures to a single material */ -class _OgreSampleClassExport PlayPen_16Textures : public VisualTest -{ -public: - - PlayPen_16Textures(); - void testCapabilities(const Ogre::RenderSystemCapabilities* caps) override; - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests view projections for spotlight shadow cameras */ -class _OgreSampleClassExport PlayPen_SpotlightViewProj : public VisualTest -{ -public: - - PlayPen_SpotlightViewProj(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests manual illumination stages */ -class _OgreSampleClassExport PlayPen_ManualIlluminationStage : public VisualTest -{ -public: - - PlayPen_ManualIlluminationStage(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests altering a mesh mid-simulation */ -class _OgreSampleClassExport PlayPen_ReinitialiseEntityAlteredMesh : public VisualTest -{ -public: - - PlayPen_ReinitialiseEntityAlteredMesh(); - bool frameStarted(const FrameEvent& evt) override; - -protected: - - void setupContent() override; - - Mesh* mUpdate; - Real mTimer; - -}; - -//------------------------------------------------------------------------------ -/** Tests sRGB textures */ -class _OgreSampleClassExport PlayPen_SRGBtexture : public VisualTest -{ -public: - - PlayPen_SRGBtexture(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests negative scaling */ -class _OgreSampleClassExport PlayPen_NegativeScale : public VisualTest -{ -public: - - PlayPen_NegativeScale(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests 2d manual object */ -class _OgreSampleClassExport PlayPen_ManualObject2D : public VisualTest -{ -public: - - PlayPen_ManualObject2D(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests shadow LODs */ -class _OgreSampleClassExport PlayPen_ShadowLod : public VisualTest -{ -public: - - PlayPen_ShadowLod(); - -protected: - - void setupContent() override; - void cleanupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests rendering far from the origin */ -class _OgreSampleClassExport PlayPen_FarFromOrigin : public VisualTest -{ -public: - - PlayPen_FarFromOrigin(); - -protected: - - void setupContent() override; - void cleanupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests geometry shaders */ -class _OgreSampleClassExport PlayPen_GeometryShaders : public VisualTest -{ -public: - - PlayPen_GeometryShaders(); - void testCapabilities(const Ogre::RenderSystemCapabilities* caps) override; - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests alpha to coverage support */ -class _OgreSampleClassExport PlayPen_AlphaToCoverage : public VisualTest -{ -public: - - PlayPen_AlphaToCoverage(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests light space shadow mapping (LiSPSM) shadow camera setup */ -class _OgreSampleClassExport PlayPen_LiSPSM : public VisualTest -{ -public: - - PlayPen_LiSPSM(); - -protected: - - void setupContent() override; - void cleanupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests blitting one texture onto another */ -class _OgreSampleClassExport PlayPen_BlitSubTextures : public VisualTest -{ -public: - - PlayPen_BlitSubTextures(); - -protected: - - void setupContent() override; - -}; -//------------------------------------------------------------------------------ -/** Tests blitting to texture with hardware scaling */ -class _OgreSampleClassExport PlayPen_HardwareScaleBlit : public VisualTest -{ -public: - - PlayPen_HardwareScaleBlit(); - -protected: - - void setupContent() override; - -}; -//------------------------------------------------------------------------------ -/** Tests depth shadow mapping */ -class _OgreSampleClassExport PlayPen_DepthShadowMap : public VisualTest -{ -public: - - PlayPen_DepthShadowMap(); - -protected: - std::unique_ptr movablePlane; - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests non-unique resource names in different resource groups */ -class _OgreSampleClassExport PlayPen_NonUniqueResourceNames : public VisualTest -{ -public: - - PlayPen_NonUniqueResourceNames(); - -protected: - - void setupContent() override; - void createMeshEntity(const String& group, Vector3 pos); - -}; -//------------------------------------------------------------------------------ -/** Tests non-unique resource names in different resource groups */ -class _OgreSampleClassExport PlayPen_BuildTangentOnAnimatedMesh : public VisualTest -{ -public: - - PlayPen_BuildTangentOnAnimatedMesh(); - -protected: - - void setupContent() override; - -}; -//------------------------------------------------------------------------------ -/** Tests 64 bit float DDS */ -class _OgreSampleClassExport PlayPen_Float64DDS : public VisualTest -{ -public: - - PlayPen_Float64DDS(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests 128bit float DDS */ -class _OgreSampleClassExport PlayPen_Float128DDS : public VisualTest -{ -public: - - PlayPen_Float128DDS(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests 16bit float DDS */ -class _OgreSampleClassExport PlayPen_Float16DDS : public VisualTest -{ -public: - - PlayPen_Float16DDS(); - -protected: - - void setupContent() override; - -}; - -//------------------------------------------------------------------------------ -/** Tests 32bit float DDS */ -class _OgreSampleClassExport PlayPen_Float32DDS : public VisualTest -{ -public: - - PlayPen_Float32DDS(); - -protected: - - void setupContent() override; - -}; - -class _OgreSampleClassExport PlayPen_BillboardText : public VisualTest -{ -public: - PlayPen_BillboardText(); - -protected: - void setupContent() override; -}; - -class _OgreSampleClassExport PlayPen_PBR : public OgreBites::SdkSample -{ -public: - PlayPen_PBR(); - -protected: - void setupContent() override; - void unloadResources() override; -}; -//------------------------------------------------------------------------------ - -// some common tasks for these tests: -void addTextureDebugOverlay(const Ogre::String& texname, size_t i); -void addTextureDebugOverlay(const Ogre::TexturePtr& tex, size_t i); -void addTextureShadowDebugOverlay(size_t num, Ogre::SceneManager* mgr); -void clearDebugTextureOverlays(); - -#endif diff --git a/Tests/VisualTests/PlayPen/src/PlayPenTestPlugin.cpp b/Tests/VisualTests/PlayPen/src/PlayPenTestPlugin.cpp deleted file mode 100644 index ad66b964b30..00000000000 --- a/Tests/VisualTests/PlayPen/src/PlayPenTestPlugin.cpp +++ /dev/null @@ -1,210 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "PlayPenTestPlugin.h" -#include "PlayPenTests.h" -#include "OgreResourceGroupManager.h" - -PlaypenTestPlugin::PlaypenTestPlugin() - :SamplePlugin("PlaypenTestPlugin") -{ - // tests that run on all GL RS - char* only_common = getenv("OGRE_ONLY_COMMON_GL_TESTS"); - - // add the playpen tests - addSample(new PlayPen_2Spotlights()); - addSample(new PlayPen_AlphaToCoverage()); - addSample(new PlayPen_AttachObjectsToBones()); - addSample(new PlayPen_AlphaTex()); - addSample(new PlayPen_BasicPlane()); - addSample(new PlayPen_BillboardAccurateFacing()); // blocks are not lit (no darkness) - addSample(new PlayPen_BillboardChain()); - addSample(new PlayPen_BillboardOrigins()); - addSample(new PlayPen_BillboardTextureCoords()); - addSample(new PlayPen_BillboardText()); - addSample(new PlayPen_BlendDiffuseColour()); - addSample(new PlayPen_BlitSubTextures()); // center tex missing - addSample(new PlayPen_BuildTangentOnAnimatedMesh()); - addSample(new PlayPen_CameraSetDirection()); - addSample(new PlayPen_ClearScene()); - addSample(new PlayPen_CompositorTechniqueSwitch()); - addSample(new PlayPen_CompositorTextureShadows()); - addSample(new PlayPen_CubeDDS()); - addSample(new PlayPen_CustomProjectionMatrix()); - addSample(new PlayPen_DepthBias()); // glPolygonOffset misbehaving? - addSample(new PlayPen_DepthShadowMap()); - - addSample(new PlayPen_Distortion()); - addSample(new PlayPen_Dxt1()); - addSample(new PlayPen_Dxt1Alpha()); - addSample(new PlayPen_Dxt1FromMemory()); - addSample(new PlayPen_Dxt3()); - addSample(new PlayPen_Dxt3FromMemory()); // tex missing Win? - if(!only_common) addSample(new PlayPen_Dxt5()); - addSample(new PlayPen_FarFromOrigin()); - - if(!only_common) addSample(new PlayPen_GeometryShaders()); - if(!only_common) addSample(new PlayPen_HardwareScaleBlit()); // unsupported on GLES2 - - addSample(new PlayPen_LightClipPlanes()); - addSample(new PlayPen_LightClipPlanesMoreLights()); - addSample(new PlayPen_LightScissoring()); - addSample(new PlayPen_LiSPSM()); // skids on Win - addSample(new PlayPen_LotsAndLotsOfEntities()); - addSample(new PlayPen_ManualBlend()); - addSample(new PlayPen_ManualBoneMovement()); - addSample(new PlayPen_ManualIlluminationStage()); // stencil shadows - addSample(new PlayPen_ManualObject2D()); - addSample(new PlayPen_ManualObjectIndexed()); - addSample(new PlayPen_ManualObjectIndexedUpdateLarger()); - addSample(new PlayPen_ManualObjectIndexedUpdateSmaller()); - addSample(new PlayPen_ManualObjectNonIndexed()); - addSample(new PlayPen_ManualObjectNonIndexedUpdateLarger()); - addSample(new PlayPen_ManualObjectNonIndexedUpdateSmaller()); - addSample(new PlayPen_MaterialSchemes()); - //addSample(new PlayPen_MaterialSchemesListener()); // works in SampleBrowser, but not TestContext, SEGV on Linux - addSample(new PlayPen_MorphAnimationWithNormals()); // bugged on Lin - addSample(new PlayPen_MorphAnimationWithoutNormals()); // bugged on Lin - addSample(new PlayPen_MultiSceneManagersSimple()); // upper right only has ambient lighting, ignores light source - addSample(new PlayPen_MultiViewports()); - addSample(new PlayPen_NegativeScale()); - addSample(new PlayPen_NonUniqueResourceNames()); - addSample(new PlayPen_NormalMapMirroredUVs()); // texture is missing - addSample(new PlayPen_Ortho()); - addSample(new PlayPen_PBR()); - addSample(new PlayPen_PointSprites()); // not sure if RTSS (via gl_PointSize shader input) or glPointSize that makes points too small - addSample(new PlayPen_PoseAnimationWithNormals()); // bugged on Lin - addSample(new PlayPen_PoseAnimationWithoutNormals()); // bugged on Lin - addSample(new PlayPen_ProjectSphere()); // does not seem to have ever worked in any RS - addSample(new PlayPen_Projection()); - addSample(new PlayPen_ReflectedBillboards()); - addSample(new PlayPen_ReinitialiseEntityAlteredMesh()); // RTSS vertex shader bug - - if(!only_common) addSample(new PlayPen_ReloadResources()); - - addSample(new PlayPen_RibbonTrail()); - addSample(new PlayPen_SRGBtexture()); // bug on Win - addSample(new PlayPen_SceneNodeTracking()); - addSample(new PlayPen_SerialisedColour()); - addSample(new PlayPen_ShadowLod()); // causes bugs? - addSample(new PlayPen_SkeletalAnimation()); - - if(!only_common) addSample(new PlayPen_SkeletonAnimationOptimise()); - - addSample(new PlayPen_StaticGeometry()); // possibly incorrect lighting? - addSample(new PlayPen_StencilGlow()); - addSample(new PlayPen_StencilShadows()); - - if(!only_common) addSample(new PlayPen_StencilShadowsMixedOpSubMeshes()); - - addSample(new PlayPen_SubEntityVisibility()); - addSample(new PlayPen_TextureShadows()); - addSample(new PlayPen_TextureShadowsIntegrated()); - addSample(new PlayPen_TextureShadowsIntegratedPSSM()); // should have textures - - addSample(new PlayPen_TextureShadowsTransparentCaster()); // crashes on Windows - - addSample(new PlayPen_TransparencyMipMaps()); - addSample(new PlayPen_TwoSidedLighting()); - addSample(new PlayPen_VertexTexture()); // needs to be implemented in OpenGL - addSample(new PlayPen_ViewportNoShadows()); - addSample(new PlayPen_WindowedViewportMode()); // possibly should only show quarter of screen? - addSample(new PlayPen_16Textures()); - - // addSample(new PlayPen_Bsp()); // results in conflicting resource ids if this and the one below are enabled - addSample(new PlayPen_InfiniteAAB()); - - if (!only_common && Root::getSingletonPtr()->getRenderSystem()->getCapabilities()->hasCapability(RSC_FIXED_FUNCTION)) - { - addSample(new PlayPen_MaterialSchemesWithLOD()); - addSample(new PlayPen_MaterialSchemesWithMismatchedLOD()); - } - - if (!only_common && Root::getSingletonPtr()->getRenderSystem()->getName().find("OpenGL ES 2") == String::npos) - { - addSample(new PlayPen_SpotlightViewProj()); // Only Cg at this time - addSample(new PlayPen_TextureShadowsCustomCasterMat()); // Only Cg at this time - addSample(new PlayPen_TextureShadowsCustomReceiverMat()); // Only Cg at this time - } - - //TODO - // These should work, but my hardware doesn't seem to support 'em. - // (and I'm unaware of a way to reliably check capabilities in this area...) - - // addSample(new PlayPen_2bppAlphaPVR()); - // addSample(new PlayPen_2bppPVR()); - // addSample(new PlayPen_4bppAlphaPVR()); - // addSample(new PlayPen_4bppPVR()); - addSample(new PlayPen_Float16DDS()); - addSample(new PlayPen_Float32DDS()); - addSample(new PlayPen_Float64DDS()); - addSample(new PlayPen_Float128DDS()); - - //TODO - // There was some shader issue (possibly my hardware, but either way I can't verify these two). - // addSample(new PlayPen_MRT()); - // addSample(new PlayPen_MRTCompositorScript()); - -#ifdef OGRE_BUILD_COMPONENT_MESHLODGENERATOR - addSample(new PlayPen_StaticGeometryWithLOD()); // possibly incorrect lighting? - addSample(new PlayPen_ManualLOD()); - addSample(new PlayPen_ManualLODFromFile()); -#endif -} -//--------------------------------------------------------------------- - -PlaypenTestPlugin::~PlaypenTestPlugin() -{ - for (auto s : mSamples) - { - delete s; - } - mSamples.clear(); -} -//--------------------------------------------------------------------- - -#ifndef OGRE_STATIC_LIB - -static PlaypenTestPlugin* testPlugin = 0; - -extern "C" void _OgreSampleExport dllStartPlugin(void); -extern "C" void _OgreSampleExport dllStopPlugin(void); - -extern "C" _OgreSampleExport void dllStartPlugin() -{ - testPlugin = OGRE_NEW PlaypenTestPlugin(); - Ogre::Root::getSingleton().installPlugin(testPlugin); -} - -extern "C" _OgreSampleExport void dllStopPlugin() -{ - Ogre::Root::getSingleton().uninstallPlugin(testPlugin); - OGRE_DELETE testPlugin; -} - -#endif diff --git a/Tests/VisualTests/PlayPen/src/PlayPenTests.cpp b/Tests/VisualTests/PlayPen/src/PlayPenTests.cpp deleted file mode 100644 index c3d9a369454..00000000000 --- a/Tests/VisualTests/PlayPen/src/PlayPenTests.cpp +++ /dev/null @@ -1,7068 +0,0 @@ -/* - ----------------------------------------------------------------------------- - This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) - For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ----------------------------------------------------------------------------- -*/ - -#include "PlayPenTests.h" -#include "OgreResourceGroupManager.h" -#include "OgreCodec.h" -#include "OgreFileSystemLayer.h" -#include "OgreMovablePlane.h" -#include "OgreRectangle2D.h" -#include "OgreMovableObject.h" -#include "OgreBillboard.h" -#include "OgreParticleSystem.h" - -#ifdef OGRE_BUILD_COMPONENT_MESHLODGENERATOR -#include "OgreLodConfig.h" -#include "OgreMeshLodGenerator.h" -#endif - -using namespace Ogre; - -struct OrientedLightPtr -{ - Light* l; - SceneNode* ln; - - OrientedLightPtr(Light* _l) : l(_l) - { - ln = l->_getManager()->getRootSceneNode()->createChildSceneNode(); - ln->attachObject(l); - } - - OrientedLightPtr* operator->() { return this; } - - void setType(Light::LightTypes type) { l->setType(type); } - void setDirection(const Vector3& v) { ln->setDirection(v, Node::TS_WORLD); } - void setCastShadows(bool b) { l->setCastShadows(b); } - void setDiffuseColour(float r, float g, float b) { l->setDiffuseColour(r, g, b); } - void setSpecularColour(float r, float g, float b) { l->setSpecularColour(r, g, b); } -}; - -static void createRandomEntityClones(Entity* ent, size_t cloneCount, - const Vector3& min, const Vector3& max, SceneManager* mgr); - -#ifdef OGRE_BUILD_COMPONENT_MESHLODGENERATOR -PlayPen_ManualLOD::PlayPen_ManualLOD() -{ - mInfo["Title"] = "PlayPen_ManualLOD"; - mInfo["Description"] = "Testing meshes with manual LODs assigned"; - addScreenshotFrame(75); -} -//--------------------------------------------------------------------------- - -void PlayPen_ManualLOD::setupContent() -{ - String meshName = getLODMesh(); - - Entity *ent; - for (int i = 0; i < 5; ++i) - { - ent = mSceneMgr->createEntity("robot" + StringConverter::toString(i), meshName); - // Add entity to the scene node - SceneNode* n = mSceneMgr->getRootSceneNode()->createChildSceneNode( - Vector3(0, 0, (i * 50) - (5 * 50 / 2))); - n->setScale(0.2, 0.2, 0.2); - n->attachObject(ent); - } - - mAnimation = ent->getAnimationState("Walk"); - mAnimation->setEnabled(true); - - // Give it a little ambience with lights - Light* l; - l = mSceneMgr->createLight("BlueLight"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-200,-80,-100))->attachObject(l); - l->setDiffuseColour(0.5, 0.5, 1.0); - - l = mSceneMgr->createLight("GreenLight"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,0,-100))->attachObject(l); - l->setDiffuseColour(0.5, 1.0, 0.5); - - // Position the camera - mCameraNode->setPosition(100,25,100); - mCameraNode->lookAt(Vector3(-50, 0, -25), Node::TS_PARENT); - - mSceneMgr->setAmbientLight(ColourValue::White); -} -//--------------------------------------------------------------------------- - -bool PlayPen_ManualLOD::frameStarted(const FrameEvent& evt) -{ - mAnimation->addTime(evt.timeSinceLastFrame); - return true; -} -//----------------------------------------------------------------------- - -String PlayPen_ManualLOD::getLODMesh() -{ - MeshPtr msh1 = MeshManager::getSingleton().load("robot.mesh", ASSETS_RESOURCE_GROUP); - - LodConfig lodConfig(msh1); - lodConfig.createManualLodLevel(136, "razor.mesh"); - lodConfig.createManualLodLevel(211, "sphere.mesh"); - MeshLodGenerator().generateLodLevels(lodConfig); - - return msh1->getName(); -} -//--------------------------------------------------------------------------- -//--------------------------------------------------------------------------- - -PlayPen_ManualLODFromFile::PlayPen_ManualLODFromFile() -{ - mInfo["Title"] = "PlayPen_ManualLOD_File"; - mInfo["Description"] = "Testing meshes with manual LODs assigned, loaded from a file"; - addScreenshotFrame(75); -} -//--------------------------------------------------------------------- - -String PlayPen_ManualLODFromFile::getLODMesh() -{ - MeshPtr msh1 = MeshManager::getSingleton().load("robot.mesh", ASSETS_RESOURCE_GROUP); - - LodConfig lodConfig(msh1); - lodConfig.createManualLodLevel(136, "razor.mesh"); - lodConfig.createManualLodLevel(211, "sphere.mesh"); - MeshLodGenerator().generateLodLevels(lodConfig); - - // this time, we save this data to a file and re-load it - - MeshSerializer ser; - const ResourceGroupManager::LocationList& ll = - ResourceGroupManager::getSingleton().getResourceLocationList("Tests"); - String prefix; - for (auto i : ll) - { - if (StringUtil::endsWith(i.archive->getName(), "media")) - { - prefix = i.archive->getName(); - } - } - ser.exportMesh(msh1.get(), prefix + "/testlod.mesh"); - - MeshManager::getSingleton().removeAll(); - - return "testlod.mesh"; -} -#endif -//--------------------------------------------------------------------------- -//--------------------------------------------------------------------------- - -PlayPen_ManualBlend::PlayPen_ManualBlend() -{ - mInfo["Title"] = "PlayPen_ManualBlending"; - mInfo["Description"] = "Manual blending"; - addScreenshotFrame(10); -} -//--------------------------------------------------------------------------- - -void PlayPen_ManualBlend::setupContent() -{ - // create material - MaterialPtr mat = MaterialManager::getSingleton().create("TestMat", - TRANSIENT_RESOURCE_GROUP); - Pass * p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->createTextureUnitState("Dirt.jpg"); - TextureUnitState* t = p->createTextureUnitState("ogrelogo.png"); - t->setColourOperationEx(LBX_BLEND_MANUAL, LBS_TEXTURE, LBS_CURRENT, - ColourValue::White, ColourValue::White, 0.75); - - Entity *planeEnt = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(planeEnt); - planeEnt->setMaterialName("TestMat"); - - mCameraNode->setPosition(0,0,600); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); -} -//--------------------------------------------------------------------- -//--------------------------------------------------------------------- - -PlayPen_ProjectSphere::PlayPen_ProjectSphere() -{ - mInfo["Title"] = "PlayPen_ProjectSphere"; - mInfo["Description"] = "Projecting a sphere's bounds onto the camera."; - addScreenshotFrame(10); -} -//--------------------------------------------------------------------------- - -void PlayPen_ProjectSphere::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue::White); - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 0; - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 4500,4500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("Examples/GrassFloor"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - mProjectionSphere = new Sphere(Vector3(0, 2000, 0), 1500.0); - - ManualObject* debugSphere = mSceneMgr->createManualObject("debugSphere"); - debugSphere->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_STRIP); - - for (int i = 0; i <= 20; ++i) - { - Vector3 basePos(mProjectionSphere->getRadius(), 0, 0); - Quaternion quat; - quat.FromAngleAxis(Radian(((float)i/(float)20)*Math::TWO_PI), Vector3::UNIT_Y); - basePos = quat * basePos; - debugSphere->position(basePos); - } - for (int i = 0; i <= 20; ++i) - { - Vector3 basePos(mProjectionSphere->getRadius(), 0, 0); - Quaternion quat; - quat.FromAngleAxis(Radian(((float)i/(float)20)*Math::TWO_PI), Vector3::UNIT_Z); - basePos = quat * basePos; - debugSphere->position(basePos); - } - - debugSphere->end(); - - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,2000,0))->attachObject(debugSphere); - - MaterialPtr mat = MaterialManager::getSingleton().create( - "scissormat", TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setDepthWriteEnabled(false); - p->setSceneBlending(SBT_TRANSPARENT_ALPHA); - TextureUnitState* t = p->createTextureUnitState(); - t->setColourOperationEx(LBX_SOURCE1, LBS_MANUAL, LBS_CURRENT, - ColourValue::Red); - t->setAlphaOperation(LBX_SOURCE1, LBS_MANUAL, LBS_CURRENT, 0.5f); - - - mScissorRect = mSceneMgr->createManualObject("mScissorRect"); - mScissorRect->setUseIdentityProjection(true); - mScissorRect->setUseIdentityView(true); - AxisAlignedBox aabb; - aabb.setInfinite(); - mScissorRect->setBoundingBox(aabb); - mScissorRect->begin(mat->getName()); - mScissorRect->position(Vector3::ZERO); - mScissorRect->position(Vector3::ZERO); - mScissorRect->position(Vector3::ZERO); - mScissorRect->quad(0, 1, 2, 3); - mScissorRect->end(); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(mScissorRect); - - mCameraNode->setPosition(0,3000,5000); - mCameraNode->lookAt(mProjectionSphere->getCenter(), Node::TS_PARENT); - -} -//--------------------------------------------------------------------------- - -bool PlayPen_ProjectSphere::frameStarted(const FrameEvent& evt) -{ - Real left, top, right, bottom; - mCamera->projectSphere(*mProjectionSphere, &left, &top, &right, &bottom); - - mScissorRect->beginUpdate(0); - mScissorRect->position(left, top, 0); - mScissorRect->position(left, bottom, 0); - mScissorRect->position(right, bottom, 0); - mScissorRect->position(right, top, 0); - mScissorRect->quad(0,1,2,3); - mScissorRect->end(); - return true; -} -//--------------------------------------------------------------------- -//--------------------------------------------------------------------- - -PlayPen_CameraSetDirection::PlayPen_CameraSetDirection() - : mUseParentNode(false) - , mUseFixedYaw(true) - , mFocus(100,200,-300) -{ - mInfo["Title"] = "PlayPen_CameraSetDirection"; - mInfo["Description"] = "Testing various settings for Camera::setDirection"; - addScreenshotFrame(10); -} -//--------------------------------------------------------------------- - -void PlayPen_CameraSetDirection::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue::White); - - Entity* e = mSceneMgr->createEntity("1", "knot.mesh"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(mFocus)->attachObject(e); - - - mCameraNode->setPosition(200,1000,1000); - mCameraNode->lookAt(mFocus, Node::TS_PARENT); - - //mTrayMgr->createButton(OgreBites::TL_BOTTOM, "Look At", "Look At"); - //mTrayMgr->createCheckBox(OgreBites::TL_BOTTOM, "tglParent", "Use Parent Node"); - //OgreBites::CheckBox* chk = mTrayMgr->createCheckBox(OgreBites::TL_BOTTOM, "tglFixedYaw", "Use Fixed Yaw"); - //chk->setChecked(true, false); - //mTrayMgr->showCursor(); - //setDragLook(true); - - mParentNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(1000, 2000, -1000)); - -} -//--------------------------------------------------------------------- - -void PlayPen_CameraSetDirection::buttonHit(OgreBites::Button* button) -{ - mCameraNode->lookAt(mFocus, Node::TS_PARENT); -} -//--------------------------------------------------------------------- - -void PlayPen_CameraSetDirection::checkBoxToggled(OgreBites::CheckBox* box) -{ - if (box->getName() == "tglParent") - { - mUseParentNode = !mUseParentNode; - - if (mUseParentNode) - mParentNode->attachObject(mCamera); - else - mParentNode->detachAllObjects(); - } - else if (box->getName() == "tglFixedYaw") - { - mUseFixedYaw = !mUseFixedYaw; - if (mUseFixedYaw) - mCameraNode->setFixedYawAxis(true); - else - mCameraNode->setFixedYawAxis(false); - - } -} -//--------------------------------------------------------------------- -//--------------------------------------------------------------------- - -PlayPen_MorphAnimationWithNormals::PlayPen_MorphAnimationWithNormals() -{ - mInfo["Title"] = "PlayPen_MorphAnimNormals"; - mInfo["Description"] = "Testing morph animation with normals"; - addScreenshotFrame(200); -} -//--------------------------------------------------------------------- - -void PlayPen_MorphAnimationWithNormals::setupContent() -{ - // explicitly disable stencil volume prep - MeshManager::getSingleton().setPrepareAllMeshesForShadowVolumes(false); - - // Cannot change this to true, not possible to use software morph - // animation + normals with stencil shadows because the former - // requires pos & normals to be in the same buffer, and the latter - // requires positions to be on their own. - // bool testStencil = false; - - //if (testStencil) - // mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_MODULATIVE); - - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - Vector3 dir(-1, -1, 0.5); - dir.normalise(); - OrientedLightPtr l = mSceneMgr->createLight("light1"); - l->setType(Light::LT_DIRECTIONAL); - l->setDirection(dir); - - MeshPtr mesh = MeshManager::getSingleton().load("sphere.mesh", ASSETS_RESOURCE_GROUP); - - String morphName = "testmorphwithnormals.mesh"; - mesh = mesh->clone(morphName); - - SubMesh* sm = mesh->getSubMesh(0); - // Re-organise geometry since this mesh has no animation and all - // vertex elements are packed into one buffer - VertexDeclaration* newDecl = - sm->vertexData->vertexDeclaration->getAutoOrganisedDeclaration(false, true, true); - sm->vertexData->reorganiseBuffers(newDecl); - //if (testStencil) - // sm->vertexData->prepareForShadowVolume(); // need to re-prep since reorganised - // get the position buffer (which should now be separate); - const VertexElement* posElem = - sm->vertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); - HardwareVertexBufferSharedPtr origbuf = - sm->vertexData->vertexBufferBinding->getBuffer( - posElem->getSource()); - - // Create a new position & normal buffer with updated values - HardwareVertexBufferSharedPtr newbuf = - HardwareBufferManager::getSingleton().createVertexBuffer( - VertexElement::getTypeSize(VET_FLOAT3) * 2, - sm->vertexData->vertexCount, - HardwareBuffer::HBU_STATIC, true); - float* pSrc = static_cast(origbuf->lock(HardwareBuffer::HBL_READ_ONLY)); - float* pDst = static_cast(newbuf->lock(HardwareBuffer::HBL_DISCARD)); - - // Make the sphere turn into a cube - // Do this just by clamping each of the directions (we shrink it) - float cubeDimension = 0.3f * mesh->getBoundingSphereRadius(); - size_t srcSkip = origbuf->getVertexSize() / sizeof(float) - 3; - for (size_t v = 0; v < sm->vertexData->vertexCount; ++v) - { - // x/y/z position - Vector3 pos; - for (int d = 0; d < 3; ++d) - { - if (*pSrc >= 0) - { - pos.ptr()[d] = std::min(cubeDimension, *pSrc++); - } - else - { - pos.ptr()[d] = std::max(-cubeDimension, *pSrc++); - } - *pDst++ = pos.ptr()[d]; - } - - // normal - // this should point along the major axis - // unfortunately since vertices are not duplicated at edges there will be - // some inaccuracy here but the most important thing is to add sharp edges - Vector3 norm = pos.normalisedCopy(); - norm = norm.primaryAxis(); - *pDst++ = norm.x; - *pDst++ = norm.y; - *pDst++ = norm.z; - - pSrc += srcSkip; - - } - - origbuf->unlock(); - newbuf->unlock(); - - // create a morph animation - Animation* anim = mesh->createAnimation("testAnim", 10.0f); - VertexAnimationTrack* vt = anim->createVertexTrack(1, sm->vertexData, VAT_MORPH); - // re-use start positions for frame 0 - VertexMorphKeyFrame* kf = vt->createVertexMorphKeyFrame(0); - kf->setVertexBuffer(origbuf); - - // Use translated buffer for mid frame - kf = vt->createVertexMorphKeyFrame(4.0f); - kf->setVertexBuffer(newbuf); - - // Pause there - kf = vt->createVertexMorphKeyFrame(6.0f); - kf->setVertexBuffer(newbuf); - - // re-use start positions for final frame - kf = vt->createVertexMorphKeyFrame(10.0f); - kf->setVertexBuffer(origbuf); - - // Export the mesh - String outPath, baseName; - String exportName = mFSLayer->getWritablePath(morphName); - StringUtil::splitFilename(exportName, baseName, outPath); - Ogre::ResourceGroupManager& resMgr = Ogre::ResourceGroupManager::getSingleton(); - resMgr.addResourceLocation(outPath, "FileSystem", TRANSIENT_RESOURCE_GROUP, false, false); - - DataStreamPtr stream = resMgr.createResource(morphName, TRANSIENT_RESOURCE_GROUP); - MeshSerializer ser; - ser.exportMesh(mesh.get(), stream); - stream->close(); - - // Unload old mesh to force reload - MeshManager::getSingleton().remove(mesh->getHandle()); - mesh->unload(); - mesh.reset(); - - Entity* e = mSceneMgr->createEntity("test", morphName); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - AnimationState* animState = e->getAnimationState("testAnim"); - animState->setEnabled(true); - animState->setWeight(1.0f); - mAnimations[0] = animState; - - e = mSceneMgr->createEntity("test2", morphName); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(200,0,0))->attachObject(e); - // test hardware morph - e->setMaterialName("Examples/HardwareMorphAnimationWithNormals"); - animState = e->getAnimationState("testAnim"); - animState->setEnabled(true); - animState->setWeight(1.0f); - mAnimations[1] = animState; - - resMgr.deleteResource(morphName, TRANSIENT_RESOURCE_GROUP); - - mCamera->setNearClipDistance(0.5); - mCameraNode->setPosition(0,100,-400); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - //mSceneMgr->setShowDebugShadows(true); - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 200; - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("2 - Default"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); -} - -bool PlayPen_MorphAnimationWithNormals::frameStarted(const FrameEvent& evt) -{ - mAnimations[0]->addTime(evt.timeSinceLastFrame); - mAnimations[1]->addTime(evt.timeSinceLastFrame); - return true; -} -//--------------------------------------------------------------------- -//--------------------------------------------------------------------- - -PlayPen_MorphAnimationWithoutNormals::PlayPen_MorphAnimationWithoutNormals() -{ - mInfo["Title"] = "PlayPen_MorphAnimNoNormals"; - mInfo["Description"] = "Testing morph animation without normals"; - addScreenshotFrame(200); -} -//--------------------------------------------------------------------- - -void PlayPen_MorphAnimationWithoutNormals::setupContent() -{ - //bool testStencil = false; - - //if (testStencil) - // mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_MODULATIVE); - - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - Vector3 dir(-1, -1, 0.5); - dir.normalise(); - OrientedLightPtr l = mSceneMgr->createLight("light1"); - l->setType(Light::LT_DIRECTIONAL); - l->setDirection(dir); - - - MeshPtr mesh = MeshManager::getSingleton().load("sphere.mesh", - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - String morphName = "testmorphnonormals.mesh"; - mesh = mesh->clone(morphName); - - SubMesh* sm = mesh->getSubMesh(0); - // Re-organise geometry since this mesh has no animation and all - // vertex elements are packed into one buffer - VertexDeclaration* newDecl = - sm->vertexData->vertexDeclaration->getAutoOrganisedDeclaration(false, true, false); - sm->vertexData->reorganiseBuffers(newDecl); - //if (testStencil) - // sm->vertexData->prepareForShadowVolume(); // need to re-prep since reorganised - // get the position buffer (which should now be separate); - const VertexElement* posElem = - sm->vertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); - HardwareVertexBufferSharedPtr origbuf = - sm->vertexData->vertexBufferBinding->getBuffer( - posElem->getSource()); - - // Create a new position & normal buffer with updated values - HardwareVertexBufferSharedPtr newbuf = - HardwareBufferManager::getSingleton().createVertexBuffer( - VertexElement::getTypeSize(VET_FLOAT3), - sm->vertexData->vertexCount, - HardwareBuffer::HBU_STATIC, true); - float* pSrc = static_cast(origbuf->lock(HardwareBuffer::HBL_READ_ONLY)); - float* pDst = static_cast(newbuf->lock(HardwareBuffer::HBL_DISCARD)); - - // Make the sphere turn into a cube - // Do this just by clamping each of the directions (we shrink it) - float cubeDimension = 0.3f * mesh->getBoundingSphereRadius(); - for (size_t v = 0; v < sm->vertexData->vertexCount; ++v) - { - // x/y/z position - Vector3 pos; - for (int d = 0; d < 3; ++d) - { - if (*pSrc >= 0) - { - pos.ptr()[d] = std::min(cubeDimension, *pSrc++); - } - else - { - pos.ptr()[d] = std::max(-cubeDimension, *pSrc++); - } - *pDst++ = pos.ptr()[d]; - } - - } - - origbuf->unlock(); - newbuf->unlock(); - - // create a morph animation - Animation* anim = mesh->createAnimation("testAnim", 10.0f); - VertexAnimationTrack* vt = anim->createVertexTrack(1, sm->vertexData, VAT_MORPH); - // re-use start positions for frame 0 - VertexMorphKeyFrame* kf = vt->createVertexMorphKeyFrame(0); - kf->setVertexBuffer(origbuf); - - // Use translated buffer for mid frame - kf = vt->createVertexMorphKeyFrame(4.0f); - kf->setVertexBuffer(newbuf); - - // Pause there - kf = vt->createVertexMorphKeyFrame(6.0f); - kf->setVertexBuffer(newbuf); - - // re-use start positions for final frame - kf = vt->createVertexMorphKeyFrame(10.0f); - kf->setVertexBuffer(origbuf); - - // Add resource location for exported mesh - String exportName = mFSLayer->getWritablePath(morphName); - String path; - StringUtil::splitFilename(exportName, morphName, path); - ResourceGroupManager::getSingleton().addResourceLocation(path, "FileSystem", TRANSIENT_RESOURCE_GROUP, false, false); - - // Export the mesh - DataStreamPtr stream = ResourceGroupManager::getSingleton().createResource(morphName, TRANSIENT_RESOURCE_GROUP); - MeshSerializer ser; - ser.exportMesh(mesh.get(), stream); - stream->close(); - - - // Unload old mesh to force reload - MeshManager::getSingleton().remove(mesh->getHandle()); - mesh->unload(); - mesh.reset(); - - Entity* e = mSceneMgr->createEntity("test", morphName); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - AnimationState* animState = e->getAnimationState("testAnim"); - animState->setEnabled(true); - animState->setWeight(1.0f); - mAnimations[0] = animState; - - e = mSceneMgr->createEntity("test2", morphName); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(200,0,0))->attachObject(e); - // test hardware morph - e->setMaterialName("Examples/HardwareMorphAnimation"); - animState = e->getAnimationState("testAnim"); - animState->setEnabled(true); - animState->setWeight(1.0f); - mAnimations[1] = animState; - - ResourceGroupManager::getSingleton().deleteResource(morphName, TRANSIENT_RESOURCE_GROUP); - - mCamera->setNearClipDistance(0.5); - mCameraNode->setPosition(0,100,-400); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - // mSceneMgr->setShowDebugShadows(true); - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 200; - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("2 - Default"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - -} - -bool PlayPen_MorphAnimationWithoutNormals::frameStarted(const FrameEvent& evt) -{ - mAnimations[0]->addTime(evt.timeSinceLastFrame); - mAnimations[1]->addTime(evt.timeSinceLastFrame); - return true; -} -//--------------------------------------------------------------------- -//--------------------------------------------------------------------- - -PlayPen_PoseAnimationWithNormals::PlayPen_PoseAnimationWithNormals() -{ - mInfo["Title"] = "PlayPen_PoseAnimNormals"; - mInfo["Description"] = "Testing pose animation with normals"; - addScreenshotFrame(200); -} -//--------------------------------------------------------------------- - -void PlayPen_PoseAnimationWithNormals::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - Vector3 dir(-1, -1, 0.5); - dir.normalise(); - OrientedLightPtr l = mSceneMgr->createLight("light1"); - l->setType(Light::LT_DIRECTIONAL); - l->setDirection(dir); - - MeshPtr mesh = MeshManager::getSingleton().load("cube.mesh", ASSETS_RESOURCE_GROUP); - - String newName = "testposewithnormals.mesh"; - mesh = mesh->clone(newName); - - - SubMesh* sm = mesh->getSubMesh(0); - // Re-organise geometry since this mesh has no animation and all - // vertex elements are packed into one buffer - VertexDeclaration* newDecl = - sm->vertexData->vertexDeclaration->getAutoOrganisedDeclaration(false, true, true); - sm->vertexData->reorganiseBuffers(newDecl); - - // create 2 poses - Pose* pose = mesh->createPose(1, "pose1"); - // Pose1 moves vertices 0, 1, 2 and 3 upward and pushes normals left - Vector3f offset1(0, 50, 0); - pose->addVertex(0, offset1, Vector3f(-1, 0, 0)); - pose->addVertex(1, offset1, Vector3f(-1, 0, 0)); - pose->addVertex(2, offset1, Vector3f(-1, 0, 0)); - pose->addVertex(3, offset1, Vector3f(-1, 0, 0)); - - pose = mesh->createPose(1, "pose2"); - // Pose2 moves vertices 3, 4, and 5 to the right and pushes normals right - // Note 3 gets affected by both - Vector3f offset2(100, 0, 0); - pose->addVertex(3, offset2, Vector3f(1, 0, 0)); - pose->addVertex(4, offset2, Vector3f(1, 0, 0)); - pose->addVertex(5, offset2, Vector3f(1, 0, 0)); - - - Animation* anim = mesh->createAnimation("poseanim", 20.0f); - VertexAnimationTrack* vt = anim->createVertexTrack(1, sm->vertexData, VAT_POSE); - - // Frame 0 - no effect - vt->createVertexPoseKeyFrame(0); - - // Frame 1 - bring in pose 1 (index 0) - VertexPoseKeyFrame* kf = vt->createVertexPoseKeyFrame(3); - kf->addPoseReference(0, 1.0f); - - // Frame 2 - remove all - vt->createVertexPoseKeyFrame(6); - - // Frame 3 - bring in pose 2 (index 1) - kf = vt->createVertexPoseKeyFrame(9); - kf->addPoseReference(1, 1.0f); - - // Frame 4 - remove all - vt->createVertexPoseKeyFrame(12); - - - // Frame 5 - bring in pose 1 at 50%, pose 2 at 100% - kf = vt->createVertexPoseKeyFrame(15); - kf->addPoseReference(0, 0.5f); - kf->addPoseReference(1, 1.0f); - - // Frame 6 - bring in pose 1 at 100%, pose 2 at 50% - kf = vt->createVertexPoseKeyFrame(18); - kf->addPoseReference(0, 1.0f); - kf->addPoseReference(1, 0.5f); - - // Frame 7 - reset - vt->createVertexPoseKeyFrame(20); - - - // Export the mesh - String exportName = mFSLayer->getWritablePath(newName); - String outPath, baseName; - StringUtil::splitFilename(exportName, baseName, outPath); - Ogre::ResourceGroupManager& resMgr = Ogre::ResourceGroupManager::getSingleton(); - resMgr.addResourceLocation(outPath, "FileSystem", TRANSIENT_RESOURCE_GROUP, false, false); - DataStreamPtr stream = resMgr.createResource(newName, TRANSIENT_RESOURCE_GROUP); - MeshSerializer ser; - ser.exportMesh(mesh.get(), stream); - stream->close(); - - // Unload old mesh to force reload - MeshManager::getSingleton().remove(mesh->getHandle()); - mesh->unload(); - mesh.reset(); - - Entity* e; - AnimationState* animState; - // software pose - e = mSceneMgr->createEntity("test2", newName); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(150,0,0))->attachObject(e); - animState = e->getAnimationState("poseanim"); - animState->setEnabled(true); - animState->setWeight(1.0f); - mAnimations[0] = animState; - - // test hardware pose - e = mSceneMgr->createEntity("test", newName); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - e->setMaterialName("Examples/HardwarePoseAnimationWithNormals"); - animState = e->getAnimationState("poseanim"); - animState->setEnabled(true); - animState->setWeight(1.0f); - mAnimations[1] = animState; - - resMgr.deleteResource(newName, TRANSIENT_RESOURCE_GROUP); - - mCamera->setNearClipDistance(0.5); - mSceneMgr->setShowDebugShadows(true); - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 200; - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("2 - Default"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - mCameraNode->setPosition(0,-200,-300); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); - -} -//--------------------------------------------------------------------- - -bool PlayPen_PoseAnimationWithNormals::frameStarted(const FrameEvent& evt) -{ - mAnimations[0]->addTime(evt.timeSinceLastFrame); - mAnimations[1]->addTime(evt.timeSinceLastFrame); - return true; -} -//--------------------------------------------------------------------- -//--------------------------------------------------------------------- - -PlayPen_PoseAnimationWithoutNormals::PlayPen_PoseAnimationWithoutNormals() -{ - mInfo["Title"] = "PlayPen_PoseAnimNoNormals"; - mInfo["Description"] = "Testing pose animation without normals"; - addScreenshotFrame(200); -} -//--------------------------------------------------------------------- - -void PlayPen_PoseAnimationWithoutNormals::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - Vector3 dir(-1, -1, 0.5); - dir.normalise(); - OrientedLightPtr l = mSceneMgr->createLight("light1"); - l->setType(Light::LT_DIRECTIONAL); - l->setDirection(dir); - - MeshPtr mesh = MeshManager::getSingleton().load("cube.mesh", ASSETS_RESOURCE_GROUP); - - String newName = "testposenonormals.mesh"; - mesh = mesh->clone(newName); - - - SubMesh* sm = mesh->getSubMesh(0); - // Re-organise geometry since this mesh has no animation and all - // vertex elements are packed into one buffer - VertexDeclaration* newDecl = - sm->vertexData->vertexDeclaration->getAutoOrganisedDeclaration(false, true, false); - sm->vertexData->reorganiseBuffers(newDecl); - - // create 2 poses - Pose* pose = mesh->createPose(1, "pose1"); - // Pose1 moves vertices 0, 1, 2 and 3 upward - Vector3f offset1(0, 50, 0); - pose->addVertex(0, offset1); - pose->addVertex(1, offset1); - pose->addVertex(2, offset1); - pose->addVertex(3, offset1); - - pose = mesh->createPose(1, "pose2"); - // Pose2 moves vertices 3, 4, and 5 to the right - // Note 3 gets affected by both - Vector3f offset2(100, 0, 0); - pose->addVertex(3, offset2); - pose->addVertex(4, offset2); - pose->addVertex(5, offset2); - - - Animation* anim = mesh->createAnimation("poseanim", 20.0f); - VertexAnimationTrack* vt = anim->createVertexTrack(1, sm->vertexData, VAT_POSE); - - // Frame 0 - no effect - vt->createVertexPoseKeyFrame(0); - - // Frame 1 - bring in pose 1 (index 0) - VertexPoseKeyFrame* kf = vt->createVertexPoseKeyFrame(3); - kf->addPoseReference(0, 1.0f); - - // Frame 2 - remove all - vt->createVertexPoseKeyFrame(6); - - // Frame 3 - bring in pose 2 (index 1) - kf = vt->createVertexPoseKeyFrame(9); - kf->addPoseReference(1, 1.0f); - - // Frame 4 - remove all - vt->createVertexPoseKeyFrame(12); - - - // Frame 5 - bring in pose 1 at 50%, pose 2 at 100% - kf = vt->createVertexPoseKeyFrame(15); - kf->addPoseReference(0, 0.5f); - kf->addPoseReference(1, 1.0f); - - // Frame 6 - bring in pose 1 at 100%, pose 2 at 50% - kf = vt->createVertexPoseKeyFrame(18); - kf->addPoseReference(0, 1.0f); - kf->addPoseReference(1, 0.5f); - - // Frame 7 - reset - vt->createVertexPoseKeyFrame(20); - - // Export the mesh - String outPath, baseName; - String exportName = mFSLayer->getWritablePath(newName); - StringUtil::splitFilename(exportName, baseName, outPath); - Ogre::ResourceGroupManager& resMgr = Ogre::ResourceGroupManager::getSingleton(); - resMgr.addResourceLocation(outPath, "FileSystem", TRANSIENT_RESOURCE_GROUP, false, false); - - DataStreamPtr stream = resMgr.createResource(newName, TRANSIENT_RESOURCE_GROUP); - MeshSerializer ser; - ser.exportMesh(mesh.get(), stream); - stream->close(); - - // Unload old mesh to force reload - MeshManager::getSingleton().remove(mesh->getHandle()); - mesh->unload(); - mesh.reset(); - - Entity* e; - AnimationState* animState; - // software pose - e = mSceneMgr->createEntity("test2", newName); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(150,0,0))->attachObject(e); - animState = e->getAnimationState("poseanim"); - animState->setEnabled(true); - animState->setWeight(1.0f); - mAnimations[0] = animState; - - // test hardware pose - e = mSceneMgr->createEntity("test", newName); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - e->setMaterialName("Examples/HardwarePoseAnimation"); - animState = e->getAnimationState("poseanim"); - animState->setEnabled(true); - animState->setWeight(1.0f); - mAnimations[1] = animState; - - resMgr.deleteResource(newName, TRANSIENT_RESOURCE_GROUP); - - mCamera->setNearClipDistance(0.5); - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 200; - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("2 - Default"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - mCameraNode->setPosition(0,-200,-300); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); -} -//--------------------------------------------------------------------------- - -bool PlayPen_PoseAnimationWithoutNormals::frameStarted(const FrameEvent& evt) -{ - mAnimations[0]->addTime(evt.timeSinceLastFrame); - mAnimations[1]->addTime(evt.timeSinceLastFrame); - return true; -} -//--------------------------------------------------------------------------- - -PlayPen_SceneNodeTracking::PlayPen_SceneNodeTracking() -{ - mInfo["Title"] = "PlayPen_SceneNodeTracking"; - mInfo["Description"] = "Testing scenenode tracking."; - addScreenshotFrame(200); -} -//----------------------------------------------------------------------- - -bool PlayPen_SceneNodeTracking::frameStarted(const FrameEvent& evt) -{ - mAnimState->addTime(evt.timeSinceLastFrame); - return true; -} -//----------------------------------------------------------------------- - -void PlayPen_SceneNodeTracking::setupContent() -{ - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); - - // Create a skydome - mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8); - - // Create a light - Light* l = mSceneMgr->createLight("MainLight"); - // Accept default settings: point light, white diffuse, just set position - // NB I could attach the light to a SceneNode if I wanted it to move automatically with - // other objects, but I don't - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(20,80,50))->attachObject(l); - - Entity *ent; - - // Define a floor plane mesh - Plane p; - p.normal = Vector3::UNIT_Y; - p.d = 200; - MeshManager::getSingleton().createPlane("FloorPlane", - TRANSIENT_RESOURCE_GROUP, - p,200000,200000,20,20,true,1,50,50,Vector3::UNIT_Z); - - // Create an entity (the floor) - ent = mSceneMgr->createEntity("floor", "FloorPlane"); - ent->setMaterialName("Examples/RustySteel"); - // Attach to child of root node, better for culling (otherwise bounds are the combination of the 2) - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); - - // Add a head, give it it's own node - SceneNode* headNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - ent = mSceneMgr->createEntity("head", "ogrehead.mesh"); - headNode->attachObject(ent); - - // Add another head, give it it's own node - SceneNode* headNode2 = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - ent = mSceneMgr->createEntity("head2", "ogrehead.mesh"); - headNode2->attachObject(ent); - - // Make sure the head node tracks the root - headNode->setAutoTracking(true, headNode2, Vector3::UNIT_Z); - //headNode->setFixedYawAxis(true); - - // Create the camera node & attach camera - //SceneNode* camNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - //camNode->attachObject(mCamera); - - // set up spline animation of node - Animation* anim = mSceneMgr->createAnimation("CameraTrack", 10); - // Spline it for nice curves - anim->setInterpolationMode(Animation::IM_SPLINE); - // Create a track to animate the head's node - NodeAnimationTrack* track = anim->createNodeTrack(0, headNode); - // Setup keyframes - track->createNodeKeyFrame(0); // startposition - TransformKeyFrame* key = track->createNodeKeyFrame(2.5); - key->setTranslate(Vector3(500,500,-1000)); - key = track->createNodeKeyFrame(5); - key->setTranslate(Vector3(-1500,1000,-600)); - key = track->createNodeKeyFrame(7.5); - key->setTranslate(Vector3(0,-100,0)); - key = track->createNodeKeyFrame(10); - key->setTranslate(Vector3(0,0,0)); - // Create a track to animate the second head's node - track = anim->createNodeTrack(1, headNode2); - // Setup keyframes - track->createNodeKeyFrame(0); // startposition - key = track->createNodeKeyFrame(2.5); - key->setTranslate(Vector3(-500,600,-100)); - key = track->createNodeKeyFrame(5); - key->setTranslate(Vector3(800,200,-600)); - key = track->createNodeKeyFrame(7.5); - key->setTranslate(Vector3(200,-1000,0)); - key = track->createNodeKeyFrame(10); - key->setTranslate(Vector3(30,70,110)); - // Create a new animation state to track this - mAnimState = mSceneMgr->createAnimationState("CameraTrack"); - mAnimState->setEnabled(true); - - // Put in a bit of fog for the hell of it - //mSceneMgr->setFog(FOG_EXP, ColourValue::White, 0.0002); - - mCameraNode->setPosition(-300,600,2000); -} -//----------------------------------------------------------------------- -//----------------------------------------------------------------------- -PlayPen_NonUniqueResourceNames::PlayPen_NonUniqueResourceNames() -{ - mInfo["Title"] = "PlayPen_NonUniqueResourceNames"; - mInfo["Description"] = "Testing resources without unique names (in different resource groups)."; - addScreenshotFrame(50); -} -//----------------------------------------------------------------------- - -void PlayPen_NonUniqueResourceNames::setupContent() -{ - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - - // Define the required skyplane - Plane plane; - // 5000 world units from the camera - plane.d = 5000; - // Above the camera, facing down - plane.normal = -Vector3::UNIT_Y; - // Create the plane 10000 units wide, tile the texture 3 times - mSceneMgr->setSkyPlane(true, plane, "Examples/SpaceSkyPlane",10000,3); - - // Create a light - Light* l = mSceneMgr->createLight("MainLight"); - // Accept default settings: point light, white diffuse, just set position - // NB I could attach the light to a SceneNode if I wanted it to move automatically with - // other objects, but I don't - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(20,80,50))->attachObject(l); - - createMeshEntity("Model1", Vector3(10, 10, 10)); - createMeshEntity("Model2", Vector3(-10, -10, -10)); - - mCameraNode->setPosition(100,0,-100); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); -} -//----------------------------------------------------------------------- - -void PlayPen_NonUniqueResourceNames::createMeshEntity(const String& group, Vector3 pos) -{ - // Get path to test resources (ugly, but the only way I can think - // of to consistently get the right path (since it's determined by - // cmake build location) without explicitly defining the groups in - // resources.cfg). - const Ogre::ResourceGroupManager::LocationList& ll = Ogre::ResourceGroupManager::getSingleton().getResourceLocationList("Tests"); - const Ogre::ResourceGroupManager::ResourceLocation* loc = &ll.front(); - Ogre::String testResourcePath = loc->archive->getName(); - - Ogre::String meshFilePath = testResourcePath + "/" + group; - - Ogre::ResourceGroupManager& resMgr = Ogre::ResourceGroupManager::getSingleton(); - resMgr.createResourceGroup(group, false); - resMgr.addResourceLocation(meshFilePath, "FileSystem", group); - resMgr.initialiseResourceGroup(group); - - Ogre::MeshPtr newMesh = Ogre::MeshManager::getSingleton().load("UniqueModel.MESH", group); - Entity *newEnt = mSceneMgr->createEntity(group, "UniqueModel.MESH", group); - - SceneNode* newNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - newNode->attachObject(newEnt); - newNode->setPosition(pos); - - // I was getting an assertion on some part of the skeleton loading - //AnimationState* aniState =newEnt->getAnimationState(newEnt->getMesh()->getSkeleton()->getAnimation(0)->getName()); - //mAnimStateList.push_back(aniState); - //aniState->setEnabled(true); - //aniState->setLoop(true); -} -//----------------------------------------------------------------------- -//----------------------------------------------------------------------- - -PlayPen_16Textures::PlayPen_16Textures() -{ - mInfo["Title"] = "PlayPen_16Textures"; - mInfo["Description"] = "Tests applying 16 textures in a single material."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_16Textures::testCapabilities(const Ogre::RenderSystemCapabilities* caps) { - if(caps->getNumTextureUnits() < 16) - throw Ogre::Exception(999, "Needs 16 Texture Units to run", "testCapabilities"); -} - -void PlayPen_16Textures::setupContent() -{ - const char* lang = ""; - if(GpuProgramManager::getSingleton().isSyntaxSupported("glsles")) - lang = "glsles"; - else if (GpuProgramManager::getSingleton().isSyntaxSupported("glsl")) - lang = "glsl"; - else // DirectX - lang = "hlsl"; - - auto frag = HighLevelGpuProgramManager::getSingleton().createProgram("frag16", TRANSIENT_RESOURCE_GROUP, - lang, GPT_FRAGMENT_PROGRAM); - frag->setSource("#include \n\ - SAMPLER2D(tex0, 0); \ - SAMPLER2D(tex1, 1); \ - SAMPLER2D(tex2, 2); \ - SAMPLER2D(tex3, 3); \ - SAMPLER2D(tex4, 4); \ - SAMPLER2D(tex5, 5); \ - SAMPLER2D(tex6, 6); \ - SAMPLER2D(tex7, 7); \ - SAMPLER2D(tex8, 8); \ - SAMPLER2D(tex9, 9); \ - SAMPLER2D(tex10, 10); \ - SAMPLER2D(tex11, 11); \ - SAMPLER2D(tex12, 12); \ - SAMPLER2D(tex13, 13); \ - SAMPLER2D(tex14, 14); \ - SAMPLER2D(tex15, 15); \ - MAIN_PARAMETERS \ - IN(vec4 ambientUV, TEXCOORD0) \ - MAIN_DECLARATION \ - { \ - gl_FragColor = texture2D(tex15, ambientUV.xy); \ - } \ - "); - - MaterialPtr mat = MaterialManager::getSingleton().create("test16", TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setVertexProgram("Ogre/BasicVertexPrograms/AmbientOneTextureWithUV"); - p->setGpuProgram(GPT_FRAGMENT_PROGRAM, frag); - // create 15 textures the same - for (int i = 0; i < 15; ++i) - { - p->createTextureUnitState("Dirt.jpg"); - } - // create 16th texture differently - p->createTextureUnitState("ogrelogo.png"); - if (StringUtil::startsWith(frag->getSyntaxCode(), "glsl")) - { - // map samplers - GpuProgramParametersSharedPtr params = p->getFragmentProgramParameters(); - params->setIgnoreMissingParams(true); - for (int i = 0; i < 16; ++i) - { - params->setNamedConstant(String("tex") + StringConverter::toString(i), i); - } - } - - Entity* e = mSceneMgr->createEntity("1", "knot.mesh"); - e->setMaterial(mat); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - - mCameraNode->setPosition(0,0,250); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); - - -} - -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_2Spotlights::PlayPen_2Spotlights() -{ - mInfo["Title"] = "PlayPen_2Spotlights"; - mInfo["Description"] = "Tests 2 spotlights on one mesh."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_2Spotlights::setupContent() -{ - SceneNode* mTestNode[5]; - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); - - Light* mLight = mSceneMgr->createLight("MainLight"); - // Spotlight test - mLight->setType(Light::LT_SPOTLIGHT); - mLight->setDiffuseColour(1.0, 0.0, 0.8); - mLight->setSpotlightRange(Degree(30), Degree(40)); - mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mTestNode[0]->setPosition(800,600,0); - mTestNode[0]->lookAt(Vector3(800,0,0), Node::TS_WORLD); - mTestNode[0]->attachObject(mLight); - - mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mLight = mSceneMgr->createLight("AnotherLight"); - // Spotlight test - mLight->setType(Light::LT_SPOTLIGHT); - mLight->setDiffuseColour(0, 1.0, 0.8); - mLight->setSpotlightRange(Degree(30), Degree(40)); - mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mTestNode[1]->setPosition(0,600,800); - mTestNode[1]->lookAt(Vector3(0,0,800), Node::TS_WORLD); - mTestNode[1]->attachObject(mLight); - - Plane plane( Vector3::UNIT_Y, -100); - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 3500,3500,100,100,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt; - pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("2 - Default"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - mCameraNode->setPosition(-600,300,-600); - mCameraNode->lookAt(Vector3(300, 0, 300), Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_AlphaToCoverage::PlayPen_AlphaToCoverage() -{ - mInfo["Title"] = "PlayPen_AlphaToCoverage"; - mInfo["Description"] = "Tests alpha to coverage support."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_AlphaToCoverage::setupContent() -{ - - MaterialPtr mat = MaterialManager::getSingleton().create( - "testa2c", - TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setAlphaRejectSettings(CMPF_GREATER, 96); - p->setLightingEnabled(false); - p->setCullingMode(CULL_NONE); - p->setAlphaToCoverageEnabled(true); - TextureUnitState* t = p->createTextureUnitState("leaf.png"); - t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); - t->setColourOperation(LBO_ALPHA_BLEND); - Entity *e = mSceneMgr->createEntity("PlaneA2C", SceneManager::PT_PLANE); - e->setMaterialName(mat->getName()); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 0, 0))->attachObject(e); - - - mat = MaterialManager::getSingleton().create( - "testnoa2c", - TRANSIENT_RESOURCE_GROUP); - p = mat->getTechnique(0)->getPass(0); - p->setAlphaRejectSettings(CMPF_GREATER, 96); - p->setLightingEnabled(false); - p->setCullingMode(CULL_NONE); - p->setAlphaToCoverageEnabled(false); - t = p->createTextureUnitState("leaf.png"); - t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); - t->setColourOperation(LBO_ALPHA_BLEND); - e = mSceneMgr->createEntity("PlaneNoA2C", SceneManager::PT_PLANE); - e->setMaterialName(mat->getName()); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-100, 0, 0))->attachObject(e); - - mat = MaterialManager::getSingleton().create( - "bg", - TRANSIENT_RESOURCE_GROUP); - p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->setCullingMode(CULL_NONE); - t = p->createTextureUnitState(); - t->setColourOperationEx(LBX_SOURCE1, LBS_MANUAL, LBS_CURRENT, ColourValue::White); - e = mSceneMgr->createEntity("PlaneBg", SceneManager::PT_PLANE); - e->setMaterialName(mat->getName()); - e->setRenderQueueGroup(RENDER_QUEUE_BACKGROUND); - SceneNode* s = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 0, -10)); - s->setScale(5,5,5); - s->attachObject(e); - - mCameraNode->setPosition(0,0,300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_AttachObjectsToBones::PlayPen_AttachObjectsToBones() -{ - mInfo["Title"] = "PlayPen_AttachObjectsToBones"; - mInfo["Description"] = "Tests attaching objectes to bones."; - addScreenshotFrame(120); -} -//---------------------------------------------------------------------------- - -void PlayPen_AttachObjectsToBones::setupContent() -{ - Entity *ent; - for (int i = 0; i < 12; ++i) - { - ent = mSceneMgr->createEntity("robot" + StringConverter::toString(i), "robot.mesh"); - if (i % 2) - { - Entity* ent2 = mSceneMgr->createEntity("plane" + StringConverter::toString(i), "razor.mesh"); - ent->attachObjectToBone("Joint8", ent2); - } - else - { - ParticleSystem* psys = mSceneMgr->createParticleSystem("psys" + StringConverter::toString(i), "Examples/PurpleFountain"); - psys->getEmitter(0)->setTimeToLive(0.2); - ent->attachObjectToBone("Joint15", psys); - } - // Add entity to the scene node - mSceneMgr->getRootSceneNode()->createChildSceneNode( - Vector3(0,0,(i*200)-(12*200/2)))->attachObject(ent); - - ent->getParentNode()->yaw(Degree(i * 45)); - - AnimationState* animState = ent->getAnimationState("Walk"); - animState->setEnabled(true); - mAnimStateList.push_back(animState); - } - - - - // Give it a little ambience with lights - Light* l; - l = mSceneMgr->createLight("BlueLight"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-200,-80,-100))->attachObject(l); - l->setDiffuseColour(0.5, 0.5, 1.0); - - l = mSceneMgr->createLight("GreenLight"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,0,-100))->attachObject(l); - l->setDiffuseColour(0.5, 1.0, 0.5); - - // Position the camera - mCameraNode->setPosition(400,120,500); - mCameraNode->lookAt(Vector3(-50, 50, 0), Node::TS_PARENT); - - mSceneMgr->setAmbientLight(ColourValue(1,1,1,1)); - //mSceneMgr->showBoundingBoxes(true); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_BasicPlane::PlayPen_BasicPlane() -{ - mInfo["Title"] = "PlayPen_BasicPlane"; - mInfo["Description"] = "Tests basic planes."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_BasicPlane::setupContent() -{ - // Create a point light - OrientedLightPtr l = mSceneMgr->createLight("MainLight"); - l->setType(Light::LT_DIRECTIONAL); - l->setDirection(-Vector3::UNIT_Y); - Entity *ent; - - // Define a floor plane mesh - Plane p(Vector3::UNIT_Y, -200); - MeshManager::getSingleton().createPlane( - "FloorPlane", - TRANSIENT_RESOURCE_GROUP, - p, 2000, 2000, 1, 1, true, 1, 5, 5, Vector3::UNIT_Z); - - // Create an entity (the floor) - ent = mSceneMgr->createEntity("floor", "FloorPlane"); - ent->setMaterialName("Examples/RustySteel"); - // ent->setMaterialName("BaseWhiteNoLighting"); - // ent->setMaterialName("BaseWhite"); - - mSceneMgr->getRootSceneNode()->attachObject(ent); - - Entity* sphereEnt = mSceneMgr->createEntity("ogre", "ogrehead.mesh"); - - SceneNode* mRootNode = mSceneMgr->getRootSceneNode(); - SceneNode* node = mSceneMgr->createSceneNode(); - node->attachObject(sphereEnt); - mRootNode->addChild(node); - - //mCameraNode->lookAt(Vector3(1, 1, 1), Node::TS_PARENT); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_BillboardAccurateFacing::PlayPen_BillboardAccurateFacing() -{ - mInfo["Title"] = "PlayPen_BillboardAccurateFacing"; - mInfo["Description"] = "Tests billboard facing."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_BillboardAccurateFacing::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - OrientedLightPtr l = mSceneMgr->createLight("light1"); - l->setType(Light::LT_DIRECTIONAL); - l->setDirection(Vector3(-1, -1, 0.5).normalisedCopy()); - - Plane plane(Vector3::UNIT_Y, -100); - MeshManager::getSingleton().createPlane( - "Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 1500, 1500, 10, 10, true, 1, 5, 5, Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("2 - Default"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - BillboardSet* bbs = mSceneMgr->createBillboardSet("1"); - bbs->setDefaultDimensions(50, 50); - bbs->createBillboard(-100, 25, 0); - bbs->setBillboardType(BBT_ORIENTED_COMMON); - bbs->setCommonDirection(Vector3::UNIT_Y); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(bbs); - - bbs = mSceneMgr->createBillboardSet("2"); - bbs->setDefaultDimensions(50, 50); - bbs->createBillboard(100, 25, 0); - bbs->setUseAccurateFacing(true); - bbs->setBillboardType(BBT_ORIENTED_COMMON); - bbs->setCommonDirection(Vector3::UNIT_Y); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(bbs); - - mCameraNode->setPosition(200,120,300); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_BillboardChain::PlayPen_BillboardChain() -{ - mInfo["Title"] = "PlayPen_BillboardChain"; - mInfo["Description"] = "Tests billboard chains."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_BillboardChain::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - Vector3 dir(-1, -1, 0.5); - dir.normalise(); - OrientedLightPtr l = mSceneMgr->createLight("light1"); - l->setType(Light::LT_DIRECTIONAL); - l->setDirection(dir); - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 100; - MeshManager::getSingleton().createPlane( - "Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("2 - Default"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - BillboardChain* chain = static_cast( - mSceneMgr->createMovableObject("1", "BillboardChain")); - chain->setUseTextureCoords(true); - chain->setUseVertexColours(false); - - BillboardChain::Element elem; - elem.width = 10; - elem.texCoord = 0; - elem.position = Vector3(0,20,0); - chain->addChainElement(0, elem); - elem.position = Vector3(20,0,0); - elem.texCoord = 1.0; - chain->addChainElement(0, elem); - elem.position = Vector3(40,10,0); - elem.texCoord = 2.0; - chain->addChainElement(0, elem); - elem.position = Vector3(60,20,0); - elem.texCoord = 3.0; - chain->addChainElement(0, elem); - elem.position = Vector3(80,40,0); - elem.texCoord = 4.0; - chain->addChainElement(0, elem); - elem.position = Vector3(100,70,0); - elem.texCoord = 5.0; - chain->addChainElement(0, elem); - - // BillboardChain does not calculate normals, so result will be inconsistent. - //chain->setMaterialName("Examples/ShowNormals"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(chain); - - mSceneMgr->showBoundingBoxes(true); - - mCameraNode->setPosition(-20,60,200); - mCameraNode->lookAt(Vector3(60, 40, 0), Node::TS_PARENT); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_BillboardOrigins::PlayPen_BillboardOrigins() -{ - mInfo["Title"] = "PlayPen_BillboardOrigins"; - mInfo["Description"] = "Tests setting billboard origins."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_BillboardOrigins::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - - // Billboards currently have no normals. - // Vector3 dir(-1, -1, 0.5); - // dir.normalise(); - // Light* l = mSceneMgr->createLight("light1"); - // l->setType(Light::LT_DIRECTIONAL); - // l->setDirection(dir); - - BillboardSet* bbs = mSceneMgr->createBillboardSet("1"); - bbs->setDefaultDimensions(50,50); - bbs->createBillboard(0, 0, 0); - bbs->setBillboardOrigin(BBO_TOP_LEFT); - bbs->setMaterialName("2 - Default"); - // bbs->setBillboardType(BBT_ORIENTED_COMMON); - bbs->setCommonDirection(Vector3::UNIT_Y); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(bbs); - - bbs = mSceneMgr->createBillboardSet("2"); - bbs->setDefaultDimensions(50,50); - bbs->createBillboard(0, -10, 0); - bbs->setBillboardOrigin(BBO_CENTER); - bbs->setMaterialName("Examples/RustySteel"); - // bbs->setBillboardType(BBT_ORIENTED_COMMON); - bbs->setCommonDirection(Vector3::UNIT_Y); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(bbs); - - bbs = mSceneMgr->createBillboardSet("3"); - bbs->setDefaultDimensions(50,50); - bbs->createBillboard(0, -20, 0); - bbs->setBillboardOrigin(BBO_BOTTOM_RIGHT); - bbs->setMaterialName("Examples/OgreLogo"); - // bbs->setBillboardType(BBT_ORIENTED_COMMON); - bbs->setCommonDirection(Vector3::UNIT_Y); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(bbs); - - mCameraNode->setPosition(0,160,1); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_BillboardTextureCoords::PlayPen_BillboardTextureCoords() -{ - mInfo["Title"] = "PlayPen_BillboardTextureCoords"; - mInfo["Description"] = "Tests setting billboard texture coordinates."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_BillboardTextureCoords::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue::White); - - BillboardSet* bbs = mSceneMgr->createBillboardSet("test"); - BillboardSet* bbs2 = mSceneMgr->createBillboardSet("test2"); - float xsegs = 3; - float ysegs = 3; - float width = 300; - float height = 300; - float gap = 20; - - // set up texture coords - bbs->setTextureStacksAndSlices(ysegs, xsegs); - bbs->setDefaultDimensions(width/xsegs, height/xsegs); - bbs2->setDefaultDimensions(width/xsegs, height/xsegs); - - for (int y = 0; y < ysegs; ++y) - { - for (int x = 0; x < xsegs; ++x) - { - Vector3 midPoint; - midPoint.x = (x * width / xsegs) + ((x-1) * gap); - midPoint.y = (y * height / ysegs) + ((y-1) * gap); - midPoint.z = 0; - Billboard* bb = bbs->createBillboard(midPoint); - bb->setTexcoordIndex((ysegs - y - 1)*xsegs + x); - Billboard* bb2 = bbs2->createBillboard(midPoint); - bb2->setTexcoordRect( - FloatRect((x + 0) / xsegs, (ysegs - y - 1) / ysegs, - (x + 1) / xsegs, (ysegs - y - 0) / ysegs)); - } - } - - bbs->setMaterialName("Examples/OgreLogo"); - bbs2->setMaterialName("Examples/OgreLogo"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(bbs); - mSceneMgr->getRootSceneNode() - ->createChildSceneNode(Vector3(- (width + xsegs * gap), 0, 0)) - ->attachObject(bbs2); - - mCameraNode->setPosition(-100,150,900); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_BlendDiffuseColour::PlayPen_BlendDiffuseColour() -{ - mInfo["Title"] = "PlayPen_BlendDiffuseColour"; - mInfo["Description"] = "Tests diffuse blending."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_BlendDiffuseColour::setupContent() -{ - MaterialPtr mat = MaterialManager::getSingleton().create( - "testBlendDiffuseColour", TRANSIENT_RESOURCE_GROUP); - Pass* pass = mat->getTechnique(0)->getPass(0); - // no lighting, it will mess up vertex colours - pass->setLightingEnabled(false); - // Make sure we pull in vertex colour as diffuse - pass->setVertexColourTracking(TVC_DIFFUSE); - // Base layer - TextureUnitState* t = pass->createTextureUnitState("BeachStones.jpg"); - // don't want to bring in vertex diffuse on base layer - t->setColourOperation(LBO_REPLACE); - // Second layer (lerp based on colour) - t = pass->createTextureUnitState("terr_dirt-grass.jpg"); - t->setColourOperationEx(LBX_BLEND_DIFFUSE_COLOUR); - // third layer (lerp based on alpha) - ManualObject* man = mSceneMgr->createManualObject("quad"); - man->begin("testBlendDiffuseColour"); - man->position(-100, 100, 0); - man->textureCoord(0,0); - man->colour(0, 0, 0); - man->position(-100, -100, 0); - man->textureCoord(0,1); - man->colour(0.5, 0.5, 0.5); - man->position(100, -100, 0); - man->textureCoord(1,1); - man->colour(1, 1, 1); - man->position(100, 100, 0); - man->textureCoord(1,0); - man->colour(0.5, 0.5, 0.5); - man->quad(0, 1, 2, 3); - man->end(); - - mSceneMgr->getRootSceneNode()->attachObject(man); - - mCameraNode->setPosition(0,0,250); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_BlitSubTextures::PlayPen_BlitSubTextures() -{ - mInfo["Title"] = "PlayPen_BlitSubTextures"; - mInfo["Description"] = "Tests blitting textures onto on another."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_BlitSubTextures::setupContent() -{ - TexturePtr src = TextureManager::getSingleton().load("ogrelogo.png", ASSETS_RESOURCE_GROUP); - - TexturePtr tex = TextureManager::getSingleton().createManual( - "testblitdst", - TRANSIENT_RESOURCE_GROUP, TEX_TYPE_2D, 1024, 1024, 1, 0, src->getFormat()); - - Box srcBox; - // This box should select from halfway through the head, to the - // 'OG' part of the logo. - srcBox.left = 376; - srcBox.top = 379; - srcBox.right = 376 + 224; - srcBox.bottom = 379 + 278; - srcBox.back = 1; - srcBox.front = 0; - - // I was getting uninitialized memory written to the texture - // buffer, so clear it explicitly. - memset(tex->getBuffer()->lock( - 0, tex->getBuffer()->getSizeInBytes(), - HardwareBuffer::HBL_NORMAL), 0, tex->getBuffer()->getSizeInBytes()); - tex->getBuffer()->unlock(); - - tex->getBuffer()->blit(src->getBuffer(), srcBox, srcBox); - - MaterialPtr mat = MaterialManager::getSingleton().create( - "testblit", - TRANSIENT_RESOURCE_GROUP); - - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->setCullingMode(CULL_NONE); - p->createTextureUnitState(tex->getName()); - Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); - e->setMaterialName(mat->getName()); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - - mCameraNode->setPosition(0,0,300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - - mWindow->getViewport(0)->setBackgroundColour(ColourValue::Green); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_HardwareScaleBlit::PlayPen_HardwareScaleBlit() -{ - mInfo["Title"] = "PlayPen_HardwareScaleBlit"; - mInfo["Description"] = "Tests blitting texture with hardware scaling."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_HardwareScaleBlit::setupContent() -{ - Image img; - img.load("ogrelogo.png", ASSETS_RESOURCE_GROUP); - - TexturePtr tex = TextureManager::getSingleton().createManual( - "testblitdst", - TRANSIENT_RESOURCE_GROUP, TEX_TYPE_2D, 64, 64, 1, 0, img.getFormat()); - - Box dstBox(0, 0, 64, 64); - tex->getBuffer()->blitFromMemory(img.getPixelBox(), dstBox); - - MaterialPtr mat = MaterialManager::getSingleton().create( - "testblit", - TRANSIENT_RESOURCE_GROUP); - - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->setCullingMode(CULL_NONE); - p->createTextureUnitState(tex->getName()); - Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); - e->setMaterialName(mat->getName()); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - - mCameraNode->setPosition(0,0,300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - - mWindow->getViewport(0)->setBackgroundColour(ColourValue::Green); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_Bsp::PlayPen_Bsp() -{ - mInfo["Title"] = "PlayPen_Bsp"; - mInfo["Description"] = "Tests BSP plugin."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_Bsp::setupContent() -{ - // Load Quake3 locations from a file - ConfigFile cf; - - cf.load(mFSLayer->getConfigFilePath("quakemap.cfg")); - - String quakePk3 = cf.getSetting("Archive"); - String quakeLevel = cf.getSetting("Map"); - - //ResourceGroupManager::getSingleton().addResourceLocation(quakePk3, "Zip"); - - ResourceGroupManager::getSingleton().addResourceLocation( - quakePk3, "Zip", - ResourceGroupManager::getSingleton().getWorldResourceGroupName(), true); - - // Load world geometry - mSceneMgr->setWorldGeometry(quakeLevel); - - // modify camera for close work - mCamera->setNearClipDistance(4); - mCamera->setFarClipDistance(4000); - - // Also change position, and set Quake-type orientation - // Get random player start point - ViewPoint vp = mSceneMgr->getSuggestedViewpoint(true); - mCameraNode->setPosition(vp.position); - mCameraNode->pitch(Degree(90)); // Quake uses X/Y horizon, Z up - mCameraNode->rotate(vp.orientation); - // Don't yaw along variable axis, causes leaning - mCameraNode->setFixedYawAxis(true, Vector3::UNIT_Z); - - mCameraNode->yaw(Ogre::Degree(-90.f)); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_BuildTangentOnAnimatedMesh::PlayPen_BuildTangentOnAnimatedMesh() -{ - mInfo["Title"] = "PlayPen_BuildTangentOnAnimatedMesh"; - mInfo["Description"] = "Tests building tangents for an animated mesh."; - addScreenshotFrame(50); -} -//---------------------------------------------------------------------------- - -void PlayPen_BuildTangentOnAnimatedMesh::setupContent() -{ - SceneNode* mTestNode[2]; - Light* mLight = 0; - //mSceneMgr->setShadowTextureSize(512); - //mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_ADDITIVE); - //mSceneMgr->setShadowFarDistance(1500); - //mSceneMgr->setShadowColour(ColourValue(0.35, 0.35, 0.35)); - //mSceneMgr->setShadowFarDistance(800); - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); - - mLight = mSceneMgr->createLight("MainLight"); - - /*/ - // Directional test - mLight->setType(Light::LT_DIRECTIONAL); - Vector3 vec(-1,-1,0); - vec.normalise(); - mLight->setDirection(vec); - /*/ - // Point test - mLight->setType(Light::LT_POINT); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 200, 0))->attachObject(mLight); - //*/ - MeshPtr pMesh = MeshManager::getSingleton().load("ninja.mesh", ASSETS_RESOURCE_GROUP/*, - HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY, - HardwareBuffer::HBU_STATIC_WRITE_ONLY, - true, true*/); //so we can still read it - // Build tangent vectors, all our meshes use only 1 texture coordset - pMesh->buildTangentVectors(); - - Entity* pEnt = mSceneMgr->createEntity("Ninja", "ninja.mesh"); - pEnt->getAnimationState("Walk")->setEnabled(true); - mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mTestNode[1]->attachObject( pEnt ); - mTestNode[1]->translate(-100,-100,0); - - - Plane plane(Vector3::UNIT_Y, -100); - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt; - pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("2 - Default"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - mCameraNode->setPosition(0,0,400); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_ClearScene::PlayPen_ClearScene() -{ - mInfo["Title"] = "PlayPen_ClearScene"; - mInfo["Description"] = "Tests clearing a running scene."; - addScreenshotFrame(25); -} -//---------------------------------------------------------------------------- - -bool PlayPen_ClearScene::isScreenshotFrame(int frame) -{ - if(frame == 20) - mSceneMgr->clearScene(); - return VisualTest::isScreenshotFrame(frame); -} -//---------------------------------------------------------------------------- - -void PlayPen_ClearScene::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue::White); - - // Define a floor plane mesh - Plane p(Vector3::UNIT_Y, -200); - MeshManager::getSingleton().createPlane("FloorPlane", - TRANSIENT_RESOURCE_GROUP, - p,200000,200000,20,20,true,1,50,50,Vector3::UNIT_Z); - - Entity* planeEnt; - planeEnt = mSceneMgr->createEntity( "plane", "FloorPlane" ); - planeEnt->setMaterialName("Examples/Rockwall"); - mSceneMgr->getRootSceneNode()->attachObject(planeEnt); - - mCameraNode->setPosition(0,500,100); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_CompositorTechniqueSwitch::PlayPen_CompositorTechniqueSwitch() -{ - mInfo["Title"] = "PlayPen_CompositorTechniqueSwitch"; - mInfo["Description"] = "Tests switching compositor techniques rapidly."; - addScreenshotFrame(15); -} -//---------------------------------------------------------------------------- - -void PlayPen_CompositorTechniqueSwitch::cleanupContent() -{ - CompositorManager::getSingleton().removeCompositorChain(mViewport); -} -//---------------------------------------------------------------------------- - -bool PlayPen_CompositorTechniqueSwitch::frameStarted(const FrameEvent& evt) -{ - mTimeUntilNextToggle -= evt.timeSinceLastFrame; - - if(mTimeUntilNextToggle <= 0.f) - { - ++mCompositorIndex; - mCompositorIndex = mCompositorIndex % mCompositorSchemeList.size(); - mCompositorToSwitch->setScheme(mCompositorSchemeList[mCompositorIndex]); - mTimeUntilNextToggle = 0.1; - } - - return true; -} -//---------------------------------------------------------------------------- - -void PlayPen_CompositorTechniqueSwitch::setupContent() -{ - mTimeUntilNextToggle = 0.1f;// swap compositors every 10 frames - CompositorManager& cmgr = CompositorManager::getSingleton(); - CompositorPtr compositor = cmgr.create("testtechswitch", TRANSIENT_RESOURCE_GROUP); - // technique 1 (Invert) - CompositionTechnique* ctech1 = compositor->createTechnique(); - CompositionTechnique::TextureDefinition* tdef = ctech1->createTextureDefinition("rt0"); - tdef->formatList.push_back(PF_A8B8G8R8); - tdef->width = tdef->height = 0; - tdef->pooled = true; - - CompositionTargetPass* tpass = ctech1->createTargetPass(); - tpass->setOutputName("rt0"); - tpass->setInputMode(CompositionTargetPass::IM_PREVIOUS); - CompositionTargetPass* tout = ctech1->getOutputTargetPass(); - tout->setInputMode(CompositionTargetPass::IM_NONE); - CompositionPass* pass = tout->createPass(CompositionPass::PT_RENDERQUAD); - pass->setMaterialName("Ogre/Compositor/Invert"); - pass->setInput(0, "rt0"); - - // technique 2 (Tiling) - ctech1 = compositor->createTechnique(); - ctech1->setSchemeName("Tiling"); - tdef = ctech1->createTextureDefinition("rt0"); - tdef->formatList.push_back(PF_A8B8G8R8); - tdef->width = tdef->height = 0; - tdef->pooled = true; - - tpass = ctech1->createTargetPass(); - tpass->setOutputName("rt0"); - tpass->setInputMode(CompositionTargetPass::IM_PREVIOUS); - tout = ctech1->getOutputTargetPass(); - tout->setInputMode(CompositionTargetPass::IM_NONE); - pass = tout->createPass(CompositionPass::PT_RENDERQUAD); - pass->setMaterialName("Ogre/Compositor/Tiling"); - pass->setInput(0, "rt0"); - - compositor->load(); - - Entity* e = mSceneMgr->createEntity("1", "knot.mesh"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox", 1000); - - // enable compositor (should pick first technique) - Viewport* vp = mWindow->getViewport(0); - - mCompositorToSwitch = cmgr.addCompositor(vp, compositor->getName()); - mCompositorSchemeList.push_back(""); - mCompositorSchemeList.push_back("Tiling"); - - cmgr.setCompositorEnabled(vp, compositor->getName(), true); - - mCameraNode->setPosition(0, 0, -300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - - mCompositorIndex = 0; - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_CompositorTextureShadows::PlayPen_CompositorTextureShadows() -{ - mInfo["Title"] = "PlayPen_CompositorTextureShadows"; - mInfo["Description"] = "Tests applying a compositor to a texture shadow manager."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_CompositorTextureShadows::cleanupContent() -{ - TexturePtr shadowTex = mSceneMgr->getShadowTexture(0); - RenderTarget* shadowRtt = shadowTex->getBuffer()->getRenderTarget(); - Viewport* vp = shadowRtt->getViewport(0); - CompositorManager::getSingleton().removeCompositorChain(vp); - clearDebugTextureOverlays(); -} -//---------------------------------------------------------------------------- - -void PlayPen_CompositorTextureShadows::setupContent() -{ - SceneNode* mTestNode[10]; - - mSceneMgr->setShadowTextureSize(512); - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE); - mSceneMgr->setShadowFarDistance(1500); - mSceneMgr->setShadowColour(ColourValue(0.35, 0.35, 0.35)); - //mSceneMgr->setShadowFarDistance(800); - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); - - Light* mLight = mSceneMgr->createLight("MainLight"); - - /* - // Directional test - mLight->setType(Light::LT_DIRECTIONAL); - Vector3 vec(-1,-1,0); - vec.normalise(); - mLight->setDirection(vec); - - */ - // Spotlight test - mLight->setType(Light::LT_SPOTLIGHT); - mLight->setDiffuseColour(1.0, 1.0, 0.8); - mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mTestNode[0]->setPosition(800,600,0); - mTestNode[0]->lookAt(Vector3(0,0,0), Node::TS_WORLD); - mTestNode[0]->attachObject(mLight); - - - mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - - Entity* pEnt; - pEnt = mSceneMgr->createEntity( "1", "robot.mesh" ); - //pEnt->setRenderingDistance(100); - AnimationState* mAnimState = pEnt->getAnimationState("Walk"); - mAnimState->setEnabled(true); - mAnimStateList.push_back(mAnimState); - //pEnt->setMaterialName("2 - Default"); - mTestNode[1]->attachObject( pEnt ); - mTestNode[1]->translate(0,-100,0); - - pEnt = mSceneMgr->createEntity( "3", "knot.mesh" ); - mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-200, 0, -200)); - mTestNode[2]->attachObject( pEnt ); - - // Transparent object (can force cast shadows) - pEnt = mSceneMgr->createEntity( "3.5", "knot.mesh" ); - MaterialPtr tmat = MaterialManager::getSingleton().create("TestAlphaTransparency", - TRANSIENT_RESOURCE_GROUP); - tmat->setTransparencyCastsShadows(true); - Pass* tpass = tmat->getTechnique(0)->getPass(0); - tpass->setAlphaRejectSettings(CMPF_GREATER, 150); - tpass->setSceneBlending(SBT_TRANSPARENT_ALPHA); - tpass->createTextureUnitState("gras_02.png"); - tpass->setCullingMode(CULL_NONE); - - pEnt->setMaterialName("TestAlphaTransparency"); - mTestNode[3] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(350, 0, -200)); - mTestNode[3]->attachObject( pEnt ); - - pEnt = mSceneMgr->createEntity( "4", "knot.mesh" ); - mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 0, 200)); - mTestNode[2]->attachObject( pEnt ); - - mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); - - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 100; - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt; - pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("2 - Default"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - // Set up a debug panel to display the shadow - addTextureShadowDebugOverlay(1, mSceneMgr); - - - - ParticleSystem* pSys2 = mSceneMgr->createParticleSystem("smoke", - "Examples/Smoke"); - mTestNode[4] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-300, -100, 200)); - mTestNode[4]->attachObject(pSys2); - - TexturePtr shadowTex = mSceneMgr->getShadowTexture(0); - RenderTarget* shadowRtt = shadowTex->getBuffer()->getRenderTarget(); - Viewport* vp = shadowRtt->getViewport(0); - // This originally used gaussian blur, but since compositor logic stuff has changed since the test - // was originally written and I'm not especially familiar with it, I just swapped to a random - // compositor (it still tests the required functionality) - CompositorManager::getSingleton().addCompositor(vp, "Laplace"); - CompositorManager::getSingleton().setCompositorEnabled( - vp, "Laplace", true); - - mCameraNode->setPosition(400, 250, 350); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_CubeDDS::PlayPen_CubeDDS() -{ - mInfo["Title"] = "PlayPen_CubeDDS"; - mInfo["Description"] = "Tests DDS cubemaps."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_CubeDDS::setupContent() -{ - Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); - - MaterialPtr mat = MaterialManager::getSingleton().create("testcube", - TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - TextureUnitState* t = p->createTextureUnitState(); - t->setTextureName("grace_cube.dds", TEX_TYPE_CUBE_MAP); - t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); - t->setEnvironmentMap(true, TextureUnitState::ENV_REFLECTION); - Entity* e = mSceneMgr->createEntity("1", "sphere.mesh"); - e->setMaterialName(mat->getName()); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - - mCameraNode->setPosition(300,0,0); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_CustomProjectionMatrix::PlayPen_CustomProjectionMatrix() -{ - mInfo["Title"] = "PlayPen_CustomProjectionMatrix"; - mInfo["Description"] = "Tests custom projection matrix."; -} -//---------------------------------------------------------------------------- - -void PlayPen_CustomProjectionMatrix::setupContent() -{ - PlayPen_LotsAndLotsOfEntities::setupContent(); - Matrix4 mat = mCamera->getProjectionMatrix(); - mCamera->setCustomProjectionMatrix(true, mat); - mat = mCamera->getProjectionMatrix(); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_DepthBias::PlayPen_DepthBias() -{ - mInfo["Title"] = "PlayPen_DepthBias"; - mInfo["Description"] = "Tests depth biasing."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_DepthBias::setupContent() -{ - Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); - - mSceneMgr->setAmbientLight(ColourValue::White); - - MaterialPtr mat = MaterialManager::getSingleton().create("mat1", - TRANSIENT_RESOURCE_GROUP); - // mat->setSceneBlending(SBT_TRANSPARENT_ALPHA); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->createTextureUnitState("BumpyMetal.jpg"); - // t->setColourOperation(LBO_ALPHA_BLEND); - - const String meshName("cube.mesh"); - Entity* entity = mSceneMgr->createEntity("base", meshName); - entity->setMaterialName("mat1"); - mSceneMgr->getRootSceneNode()->attachObject(entity); - - entity = mSceneMgr->createEntity("base2", meshName); - entity->setMaterialName("Examples/SphereMappedRustySteel"); - SceneNode* n = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - n->setPosition(-30, 0, 0); - n->yaw(Degree(45)); - n->attachObject(entity); - - // for (size_t i = 0; i <= 6; ++i) - for (size_t i = 0; i <= 3; ++i) - { - String name("decal"); - name += StringConverter::toString(i); - - MaterialPtr pMat = MaterialManager::getSingleton().create(name, TRANSIENT_RESOURCE_GROUP); - - p = pMat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->setAlphaRejectSettings(CMPF_GREATER_EQUAL, 128); - p->setSceneBlending(SBT_TRANSPARENT_ALPHA); - p->setDepthBias(i); - p->createTextureUnitState(name + ".png"); - // t->setColourOperation(LBO_ALPHA_BLEND); - - entity = mSceneMgr->createEntity(name, meshName); - entity->setMaterialName(name); - mSceneMgr->getRootSceneNode()->attachObject(entity); - } - - mCameraNode->setPosition(0,0,200); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_DepthShadowMap::PlayPen_DepthShadowMap() -{ - mInfo["Title"] = "PlayPen_DepthShadowMap"; - mInfo["Description"] = "Tests depth shadowmapping."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_DepthShadowMap::setupContent() -{ - mSceneMgr->setShadowTextureCount(1); - mSceneMgr->setShadowTextureConfig(0, 1024, 1024, PF_FLOAT32_R); - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_ADDITIVE_INTEGRATED); - mSceneMgr->setShadowCasterRenderBackFaces(false); - mSceneMgr->setShadowFarDistance(500); - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - // Make this viewport work with shader generator scheme. - mViewport->setMaterialScheme(MSN_SHADERGEN); - RTShader::ShaderGenerator& rtShaderGen = RTShader::ShaderGenerator::getSingleton(); - RTShader::RenderState* schemRenderState = rtShaderGen.getRenderState(MSN_SHADERGEN); - auto subRenderState = rtShaderGen.createSubRenderState(RTShader::SRS_SHADOW_MAPPING); - schemRenderState->addTemplateSubRenderState(subRenderState); -#endif - mSceneMgr->setShadowTextureCasterMaterial( - MaterialManager::getSingleton().getByName("PSSM/shadow_caster", "General")); - - // ground plane - movablePlane.reset(new MovablePlane(Vector3::UNIT_Y, 0.f)); - - mSceneMgr->setShadowCameraSetup(PlaneOptimalShadowCameraSetup::create(movablePlane.get())); - - // Single light - Light* l = mSceneMgr->createLight("l1"); - l->setType(Light::LT_POINT); - Vector3 pos(-150, 100, -50); - mSceneMgr->getRootSceneNode()->createChildSceneNode(pos)->attachObject(l); - - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, *movablePlane, - 500,500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt; - pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("Examples/Rockwall"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - // box - ManualObject* man = mSceneMgr->createManualObject("box"); - Real boxsize = 50; - Real boxsizehalf = boxsize / 2.0; - man->begin("BaseWhite"); - man->position(-boxsizehalf, 0, boxsizehalf); - man->normal(0, 0, 0); - man->position(boxsizehalf, 0, boxsizehalf); - man->normal(0, 0, 0); - man->position(boxsizehalf, 0, -boxsizehalf); - man->normal(0, 0, 0); - man->position(-boxsizehalf, 0, -boxsizehalf); - man->normal(0, 0, 0); - man->position(-boxsizehalf, boxsize, boxsizehalf); - man->normal(0, 0, 0); - man->position(boxsizehalf, boxsize, boxsizehalf); - man->normal(0, 0, 0); - man->position(boxsizehalf, boxsize, -boxsizehalf); - man->normal(0, 0, 0); - man->position(-boxsizehalf, boxsize, -boxsizehalf); - man->normal(0, 0, 0); - man->quad(3, 2, 1, 0); - man->quad(4, 5, 6, 7); - man->quad(0, 1, 5, 4); - man->quad(1, 2, 6, 5); - man->quad(2, 3, 7, 6); - man->quad(3, 0, 4, 7); - man->end(); - - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(man); - - mCameraNode->setPosition(150, 100, 150); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - - // Create RTT - //TexturePtr rtt = TextureManager::getSingleton().createManual("rtt1", TRANSIENT_RESOURCE_GROUP, - // TEX_TYPE_2D, 1024, 1024, 1, 0, PF_FLOAT32_R); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -Entity* pTexListenerPlaneEnt = 0;// yucky global... -Camera* theCam = 0; - -class RefractionTextureListener : public RenderTargetListener -{ -public: - void preRenderTargetUpdate(const RenderTargetEvent& evt) override - { - pTexListenerPlaneEnt->setVisible(false); - - } - void postRenderTargetUpdate(const RenderTargetEvent& evt) override - { - pTexListenerPlaneEnt->setVisible(true); - } - -}; - -class ReflectionTextureListener : public RenderTargetListener -{ -public: - void preRenderTargetUpdate(const RenderTargetEvent& evt) override - { - static Plane reflectPlane(Vector3::UNIT_Y, -100); - pTexListenerPlaneEnt->setVisible(false); - theCam->enableReflection(reflectPlane); - - } - void postRenderTargetUpdate(const RenderTargetEvent& evt) override - { - pTexListenerPlaneEnt->setVisible(true); - theCam->disableReflection(); - } - -}; - -PlayPen_Distortion::PlayPen_Distortion() -{ - mInfo["Title"] = "PlayPen_Distortion"; - mInfo["Description"] = "Tests distortion."; - addScreenshotFrame(15); - - mRefractionListener = new RefractionTextureListener(); - mReflectionListener = new ReflectionTextureListener(); -} -//---------------------------------------------------------------------------- - -PlayPen_Distortion::~PlayPen_Distortion() -{ - delete mRefractionListener; - delete mReflectionListener; -} -//---------------------------------------------------------------------------- - -void PlayPen_Distortion::cleanupContent() -{ - TexturePtr rttTex = TextureManager::getSingleton().getByName("Refraction", TRANSIENT_RESOURCE_GROUP); - rttTex->getBuffer()->getRenderTarget()->removeAllListeners(); - rttTex->unload(); - rttTex = TextureManager::getSingleton().getByName("Reflection", TRANSIENT_RESOURCE_GROUP); - rttTex->getBuffer()->getRenderTarget()->removeAllListeners(); - rttTex->unload(); -} -//---------------------------------------------------------------------------- - -void PlayPen_Distortion::setupContent() -{ - theCam = mCamera; - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - - // Create a point light - OrientedLightPtr l = mSceneMgr->createLight("MainLight"); - l->setType(Light::LT_DIRECTIONAL); - l->setDirection(-Vector3::UNIT_Y); - - Entity* pEnt; - - TexturePtr rttTex = TextureManager::getSingleton().createManual("Refraction", - TRANSIENT_RESOURCE_GROUP, TEX_TYPE_2D, - 512, 512, 1, 0, PF_R8G8B8, TU_RENDERTARGET); - { - Viewport *v = rttTex->getBuffer()->getRenderTarget()->addViewport( mCamera ); - MaterialPtr mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefraction"); - mat->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setProjectiveTexturing(true, mCamera); - mat->getTechnique(0)->getPass(0)->getTextureUnitState(2)->setTextureName("Refraction"); - v->setOverlaysEnabled(false); - rttTex->getBuffer()->getRenderTarget()->addListener(mRefractionListener); - } - - rttTex = TextureManager::getSingleton().createManual("Reflection", - TRANSIENT_RESOURCE_GROUP, TEX_TYPE_2D, - 512, 512, 1, 0, PF_R8G8B8, TU_RENDERTARGET); - { - Viewport *v = rttTex->getBuffer()->getRenderTarget()->addViewport( mCamera ); - MaterialPtr mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefraction"); - mat->getTechnique(0)->getPass(0)->getTextureUnitState(1)->setTextureName("Reflection"); - v->setOverlaysEnabled(false); - rttTex->getBuffer()->getRenderTarget()->addListener(mReflectionListener); - } - // Define a floor plane mesh - Plane p(Vector3::UNIT_Y, -100); - MeshManager::getSingleton().createPlane("WallPlane", - TRANSIENT_RESOURCE_GROUP, - p,1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); - pTexListenerPlaneEnt = mSceneMgr->createEntity( "5", "WallPlane" ); - pTexListenerPlaneEnt->setMaterialName("Examples/FresnelReflectionRefraction"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pTexListenerPlaneEnt); - - mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); - - for (int i = 0; i < 10; ++i) - { - pEnt = mSceneMgr->createEntity( "ogre" + StringConverter::toString(i), "ogrehead.mesh" ); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(i*100 - 500, -75, 0))->attachObject(pEnt); - pEnt = mSceneMgr->createEntity( "knot" + StringConverter::toString(i), "knot.mesh" ); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(i*100 - 500, 140, 0))->attachObject(pEnt); - } - - mCameraNode->setPosition(100,200,300); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_Dxt1Alpha::PlayPen_Dxt1Alpha() -{ - mInfo["Title"] = "PlayPen_Dxt1Alpha"; - mInfo["Description"] = "Tests dxt1 loading with alpha."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_Dxt1Alpha::setupContent() -{ - Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); - - MaterialPtr mat = MaterialManager::getSingleton().create("testdxt", - TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setSceneBlending(SBT_TRANSPARENT_ALPHA); - p->setAlphaRejectSettings(CMPF_GREATER, 128); - p->setLightingEnabled(false); - p->setCullingMode(CULL_NONE); - p->createTextureUnitState("gras_02_dxt1.dds"); - Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); - e->setMaterialName(mat->getName()); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - - mCameraNode->setPosition(0,0,300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -PlayPen_AlphaTex::PlayPen_AlphaTex() -{ - mInfo["Title"] = "PlayPen_AlphaTex"; - mInfo["Description"] = "Tests alpha only texture."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_AlphaTex::setupContent() -{ - Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); - - TexturePtr tex = - TextureManager::getSingleton().load("terrain.png", TRANSIENT_RESOURCE_GROUP, TEX_TYPE_2D, 0, 1.0f, PF_A8); - - MaterialPtr mat = MaterialManager::getSingleton().create("test", TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->setCullingMode(CULL_NONE); - p->setSceneBlending(SBT_TRANSPARENT_ALPHA); - p->createTextureUnitState()->setTexture(tex); - Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); - e->setMaterialName(mat->getName()); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - - mCameraNode->setPosition(0,0,-300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - mWindow->getViewport(0)->setBackgroundColour(ColourValue::Green); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- -PlayPen_TwoSidedLighting::PlayPen_TwoSidedLighting() -{ - mInfo["Title"] = "PlayPen_TwoSidedLighting"; - mInfo["Description"] = "Tests alpha only texture."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_TwoSidedLighting::setupContent() -{ - // Make this viewport work with shader generator scheme. - mViewport->setMaterialScheme(MSN_SHADERGEN); - - Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); - e->setMaterialName("Tests/TwoSidedLighting"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - mViewport->setBackgroundColour(ColourValue(0.2, 0.2, 0.2)); - - mCameraNode->setPosition(0,0,-300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - - auto l = mSceneMgr->createLight(); - l->setSpecularColour(ColourValue::White); - mCameraNode->attachObject(l); -} -//---------------------------------------------------------------------------- -PlayPen_Dxt1::PlayPen_Dxt1() -{ - mInfo["Title"] = "PlayPen_Dxt1"; - mInfo["Description"] = "Tests dxt1 loading."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_Dxt1::setupContent() -{ - Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); - - MaterialPtr mat = MaterialManager::getSingleton().create("testdxt", - TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->setCullingMode(CULL_NONE); - p->createTextureUnitState("BumpyMetal_dxt1.dds"); - Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); - e->setMaterialName(mat->getName()); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - - mCameraNode->setPosition(0,0,-300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_Dxt1FromMemory::PlayPen_Dxt1FromMemory() -{ - mInfo["Title"] = "PlayPen_Dxt1FromMemory"; - mInfo["Description"] = "Tests dxt1 loading from memory."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_Dxt1FromMemory::setupContent() -{ - Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); - - DataStreamPtr stream = ResourceGroupManager::getSingleton().openResource("BumpyMetal_dxt1.dds", "Tests"); - // manually load into image - Image img; - img.load(stream, "dds"); - TextureManager::getSingleton().loadImage("testdxtfrommem", TRANSIENT_RESOURCE_GROUP, img); - - - - MaterialPtr mat = MaterialManager::getSingleton().create("testdxt", - TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->setCullingMode(CULL_NONE); - p->createTextureUnitState("testdxtfrommem"); - Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); - e->setMaterialName(mat->getName()); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - - mCameraNode->setPosition(0,0,-300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_Dxt3::PlayPen_Dxt3() -{ - mInfo["Title"] = "PlayPen_Dxt3"; - mInfo["Description"] = "Tests dxt3 loading."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_Dxt3::setupContent() -{ - Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); - - MaterialPtr mat = MaterialManager::getSingleton().create("testdxt", - TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->setCullingMode(CULL_NONE); - p->setSceneBlending(SBT_TRANSPARENT_ALPHA); - p->createTextureUnitState("ogreborderUp_dxt3.dds"); - Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); - e->setMaterialName(mat->getName()); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); - - mCameraNode->setPosition(0,0,300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_Dxt3FromMemory::PlayPen_Dxt3FromMemory() -{ - mInfo["Title"] = "PlayPen_Dxt3FromMemory"; - mInfo["Description"] = "Tests dxt3 loading from memory."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_Dxt3FromMemory::setupContent() -{ - Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); - - DataStreamPtr stream = ResourceGroupManager::getSingleton().openResource("ogreborderUp_dxt3.dds", "Tests"); - // manually load into image - Image img; - img.load(stream, "dds"); - TextureManager::getSingleton().loadImage("testdxtfrommem", TRANSIENT_RESOURCE_GROUP, img); - - MaterialPtr mat = MaterialManager::getSingleton().create("testdxt", - TRANSIENT_RESOURCE_GROUP); - - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->setCullingMode(CULL_NONE); - p->setSceneBlending(SBT_TRANSPARENT_ALPHA); - p->setAlphaRejectSettings(CMPF_GREATER, 128); - mat->setReceiveShadows(false); - TextureUnitState* t = p->createTextureUnitState("testdxtfrommem"); - t->setTextureScale(0.5,0.5); - Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); - e->setMaterialName(mat->getName()); - SceneNode* n = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - n->setPosition(-50, 0, 35); - n->yaw(Degree(90)); - n->attachObject(e); - mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); - - mCameraNode->setPosition(0,0,300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_Dxt5::PlayPen_Dxt5() -{ - mInfo["Title"] = "PlayPen_Dxt5"; - mInfo["Description"] = "Tests dxt5 loading."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_Dxt5::setupContent() -{ - Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); - - MaterialPtr mat = MaterialManager::getSingleton().create("testdxt", - TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->setCullingMode(CULL_NONE); - p->setSceneBlending(SBT_TRANSPARENT_ALPHA); - p->createTextureUnitState("ogreborderUp_dxt5.dds"); - Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); - e->setMaterialName(mat->getName()); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); - - mCameraNode->setPosition(0,0,300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_FarFromOrigin::PlayPen_FarFromOrigin() -{ - mInfo["Title"] = "PlayPen_FarFromOrigin"; - mInfo["Description"] = "Tests rending far from the origin."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_FarFromOrigin::cleanupContent() -{ - //clearDebugTextureOverlays(); -} - -void PlayPen_FarFromOrigin::setupContent() -{ - SceneNode* mTestNode[5]; - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE); - mSceneMgr->setShadowTextureSettings(1024, 2); - - Vector3 offset(100000, 0, 100000); - //Vector3 offset(0, 0, 0); - - mSceneMgr->setAmbientLight(ColourValue(0.1, 0.1, 0.1)); - - // Directional test - { - OrientedLightPtr mLight = mSceneMgr->createLight("MainLight"); - mLight->setType(Light::LT_DIRECTIONAL); - Vector3 vec(-1, -1, 0); - vec.normalise(); - mLight->setDirection(vec); - mLight->setDiffuseColour(0.5, 0.5, 1.0); - } - - // Spotlight test - auto mLight = mSceneMgr->createLight("SpotLight"); - mLight->setType(Light::LT_SPOTLIGHT); - mLight->setAttenuation(10000, 1, 0, 0); - mLight->setDiffuseColour(1.0, 1.0, 0.5); - - mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mTestNode[0]->setPosition(offset + Vector3(-400,300,1000)); - mTestNode[0]->lookAt(offset, Node::TS_WORLD); - mTestNode[0]->attachObject(mLight); - - - mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mTestNode[1]->setPosition(offset); - - Entity* pEnt; - pEnt = mSceneMgr->createEntity( "1", "knot.mesh" ); - mTestNode[1]->attachObject( pEnt ); - - - mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); - - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 100; - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 2500,2500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt; - pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("2 - Default"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode(offset)->attachObject(pPlaneEnt); - - ParticleSystem* pSys2 = mSceneMgr->createParticleSystem("smoke", - "Examples/Smoke"); - mTestNode[4] = mSceneMgr->getRootSceneNode()->createChildSceneNode(offset + Vector3(-300, -100, 200)); - mTestNode[4]->attachObject(pSys2); - - mCameraNode->setPosition(offset + Vector3(0, 1000, 500)); - mCameraNode->lookAt(offset, Node::TS_PARENT); - mCamera->setFarClipDistance(10000); - - mSceneMgr->setCameraRelativeRendering(true); - - mSceneMgr->setShadowCameraSetup(FocusedShadowCameraSetup::create()); - //addTextureShadowDebugOverlay(1, mSceneMgr); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_Float128DDS::PlayPen_Float128DDS() -{ - mInfo["Title"] = "PlayPen_Float128DDS"; - mInfo["Description"] = "Tests 128bit floating point dds textures."; - addScreenshotFrame(250); -} -//---------------------------------------------------------------------------- - -void PlayPen_Float128DDS::setupContent() -{ - Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); - - MaterialPtr mat = MaterialManager::getSingleton().create("testdds", - TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->setCullingMode(CULL_NONE); - p->setSceneBlending(SBT_TRANSPARENT_ALPHA); - p->createTextureUnitState("ogreborderUp_float128.dds"); - Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); - e->setMaterialName(mat->getName()); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); - - mCameraNode->setPosition(0,0,300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_Float16DDS::PlayPen_Float16DDS() -{ - mInfo["Title"] = "PlayPen_Float16DDS"; - mInfo["Description"] = "Tests 16bit floating point dds textures."; - addScreenshotFrame(250); -} -//---------------------------------------------------------------------------- - -void PlayPen_Float16DDS::setupContent() -{ - Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); - - MaterialPtr mat = MaterialManager::getSingleton().create("testdds", - TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->setCullingMode(CULL_NONE); - p->createTextureUnitState("BumpyMetal_float16.dds"); - Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); - e->setMaterialName(mat->getName()); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); - - mCameraNode->setPosition(0,0,300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_Float32DDS::PlayPen_Float32DDS() -{ - mInfo["Title"] = "PlayPen_Float32DDS"; - mInfo["Description"] = "Tests 32bit floating point dds textures."; - addScreenshotFrame(250); -} -//---------------------------------------------------------------------------- - -void PlayPen_Float32DDS::setupContent() -{ - Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); - - MaterialPtr mat = MaterialManager::getSingleton().create("testdds", - TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->setCullingMode(CULL_NONE); - p->createTextureUnitState("BumpyMetal_float32.dds"); - Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); - e->setMaterialName(mat->getName()); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); - - mCameraNode->setPosition(0,0,300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_Float64DDS::PlayPen_Float64DDS() -{ - mInfo["Title"] = "PlayPen_Float64DDS"; - mInfo["Description"] = "Tests 64bit floating point dds textures."; - addScreenshotFrame(250); -} -//---------------------------------------------------------------------------- - -void PlayPen_Float64DDS::setupContent() -{ - Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); - - MaterialPtr mat = MaterialManager::getSingleton().create("testdds", - TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->setCullingMode(CULL_NONE); - p->setSceneBlending(SBT_TRANSPARENT_ALPHA); - p->createTextureUnitState("ogreborderUp_float64.dds"); - Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); - e->setMaterialName(mat->getName()); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); - - mCameraNode->setPosition(0,0,300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_GeometryShaders::PlayPen_GeometryShaders() -{ - mInfo["Title"] = "PlayPen_GeometryShaders"; - mInfo["Description"] = "Tests geometry shaders."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_GeometryShaders::testCapabilities(const Ogre::RenderSystemCapabilities* caps) -{ - if(!caps->hasCapability(RSC_GEOMETRY_PROGRAM)) - throw Ogre::Exception(999, "Video card doesn't support geometry shaders.", "testCapabilities"); -} -//---------------------------------------------------------------------------- - -void PlayPen_GeometryShaders::setupContent() -{ - // Check capabilities - const RenderSystemCapabilities* caps = Root::getSingleton().getRenderSystem()->getCapabilities(); - if (!caps->hasCapability(RSC_GEOMETRY_PROGRAM)) - { - OGRE_EXCEPT(Ogre::Exception::ERR_NOT_IMPLEMENTED, - "Your card does not support geometry programs, so cannot " - "run this demo. Sorry!", - "GeometryShading::createScene"); - } - - int maxOutputVertices = caps->getGeometryProgramNumOutputVertices(); - Ogre::LogManager::getSingleton().getDefaultLog()->stream() << - "Num output vertices per geometry shader run : " << maxOutputVertices; - - Entity *ent = mSceneMgr->createEntity("head", "ogrehead.mesh"); - - // Set all of the material's sub entities to use the new material - for (unsigned int i = 0; i < ent->getNumSubEntities(); i++) - { - ent->getSubEntity(i)->setMaterialName("Ogre/GPTest/Swizzle"); - } - - // Add entity to the root scene node - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); - - mWindow->getViewport(0)->setBackgroundColour(ColourValue::Green); - - mCameraNode->setPosition(20, 0, 100); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_InfiniteAAB::PlayPen_InfiniteAAB() -{ - mInfo["Title"] = "PlayPen_InfiniteAAB"; - mInfo["Description"] = "Tests finite/infinite AABBs."; - addScreenshotFrame(15); -} -//---------------------------------------------------------------------------- - -void PlayPen_InfiniteAAB::setupContent() -{ - ResourceGroupManager::getSingleton().setWorldResourceGroupName("BSPWorld"); - mSceneMgr->setWorldGeometry("ogretestmap.bsp"); - - AxisAlignedBox b1; // null - assert( b1.isNull() ); - - AxisAlignedBox b2(Vector3::ZERO, 5.0 * Vector3::UNIT_SCALE); // finite - assert( b2.isFinite() ); - - AxisAlignedBox b3; - b3.setInfinite(); - assert( b3.isInfinite() ); - - { - // Create background material - MaterialPtr material = MaterialManager::getSingleton().create("Background", "General"); - material->getTechnique(0)->getPass(0)->createTextureUnitState("rockwall.tga"); - material->getTechnique(0)->getPass(0)->setDepthCheckEnabled(false); - material->getTechnique(0)->getPass(0)->setDepthWriteEnabled(false); - material->getTechnique(0)->getPass(0)->setLightingEnabled(false); - - // Create left background rectangle - // NOTE: Uses finite aab - Rectangle2D* rect1 = new Rectangle2D(true); - rect1->setCorners(-0.5, 0.1, -0.1, -0.1); - // Hacky, set small bounding box, to show problem - rect1->setBoundingBox(AxisAlignedBox(-10.0*Vector3::UNIT_SCALE, 10.0*Vector3::UNIT_SCALE)); - rect1->setMaterial(material); - rect1->setRenderQueueGroup(RENDER_QUEUE_OVERLAY - 1); - SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode("Background1"); - node->attachObject(rect1); - - // Create right background rectangle - // NOTE: Uses infinite aab - Rectangle2D* rect2 = new Rectangle2D(true); - rect2->setCorners(0.1, 0.1, 0.5, -0.1); - AxisAlignedBox aabInf; aabInf.setInfinite(); - rect2->setBoundingBox(aabInf); - rect2->setMaterial(material); - rect2->setRenderQueueGroup(RENDER_QUEUE_OVERLAY - 1); - node = mSceneMgr->getRootSceneNode()->createChildSceneNode("Background2"); - node->attachObject(rect2); - - // Create a manual object for 2D - ManualObject* manual = mSceneMgr->createManualObject("manual"); - manual->setUseIdentityProjection(true); - manual->setUseIdentityView(true); - manual->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_STRIP); - manual->position(-0.2, -0.2, 0.0); - manual->position( 0.2, -0.2, 0.0); - manual->position( 0.2, 0.2, 0.0); - manual->position(-0.2, 0.2, 0.0); - manual->index(0); - manual->index(1); - manual->index(2); - manual->index(3); - manual->index(0); - manual->end(); - manual->setBoundingBox(aabInf); // Use infinite aab to always stay visible - rect2->setRenderQueueGroup(RENDER_QUEUE_OVERLAY - 1); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(manual); - } - - mSceneMgr->showBoundingBoxes(true); - - Entity* ent = mSceneMgr->createEntity("test", "ogrehead.mesh"); - mSceneMgr->getRootSceneNode()->createChildSceneNode( - "test", 50.0 * Vector3::UNIT_X)->attachObject(ent); - - mCameraNode->setPosition(100,50,350); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); -} -void PlayPen_InfiniteAAB::cleanupContent() -{ - Ogre::ResourceGroupManager::getSingleton().clearResourceGroup("BSPWorld"); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_LightClipPlanes::PlayPen_LightClipPlanes() -{ - mInfo["Title"] = "PlayPen_LightClipPlanes"; - mInfo["Description"] = "Tests light clipping planes."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_LightClipPlanes::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue::White); - - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 0; - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 4500,4500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - - MaterialPtr mat = MaterialManager::getSingleton() - .getByName("Examples/GrassFloor") - ->clone("Myplane/Material", TRANSIENT_RESOURCE_GROUP); - - pPlaneEnt->setMaterial(mat); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(150,0,100))->attachObject(pPlaneEnt); - - Real lightRange = 1000; - Real spotWidth = 300; - - ManualObject* debugSphere = mSceneMgr->createManualObject("debugSphere"); - debugSphere->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_STRIP); - for (int i = 0; i <= 20; ++i) - { - Vector3 basePos(spotWidth, 0, 0); - Quaternion quat; - quat.FromAngleAxis(Radian(((float)i/(float)20)*Math::TWO_PI), Vector3::UNIT_Y); - basePos = quat * basePos; - debugSphere->position(basePos); - } - debugSphere->end(); - - Light* l = mSceneMgr->createLight("l1"); - l->setAttenuation(lightRange, 1, 0, 0); - SceneNode* n = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100,0,0)); - n->attachObject(debugSphere); - /* SPOT LIGHT - */ - // match spot width to groud - Real spotHeight = lightRange * 0.5; - n = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100,spotHeight,0)); - l->setType(Light::LT_SPOTLIGHT); - Radian spotAngle = Math::ATan(spotWidth / spotHeight) * 2; - l->setSpotlightOuterAngle(spotAngle); - l->setSpotlightInnerAngle(spotAngle * 0.75); - Vector3 dir(0, -1, 0); - dir.normalise(); - n->setDirection(dir); - - /* END SPOT LIGHT */ - n->attachObject(l); - - // Modify the plane material so that it clips to the light - // Normally you'd only clip a secondary pass but this is engineered so you - // can actually see the scissoring effect - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightClipPlanesEnabled(true); - - mCameraNode->setPosition(0, 200, 300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - - - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_LightClipPlanesMoreLights::PlayPen_LightClipPlanesMoreLights() -{ - mInfo["Title"] = "PlayPen_LightClipPlanesMoreLights"; - mInfo["Description"] = "Tests light clip planes with more lights."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_LightClipPlanesMoreLights::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.25, 0.2, 0)); - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_ADDITIVE); - mSceneMgr->setShadowTextureCount(3); - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 0; - MeshManager::getSingleton().createPlane( - "Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 4500, 4500, 100, 100, true, 1, 5, 5, Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - - MaterialPtr mat = MaterialManager::getSingleton() - .getByName("Examples/GrassFloor") - ->clone("Myplane/Material", TRANSIENT_RESOURCE_GROUP); - - pPlaneEnt->setMaterial(mat); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - Real lightRange = 1000; - Real spotWidth = 300; - - int numLights = 8; - Real xoff = -numLights * spotWidth * 0.5; - - for (int i = 0; i < numLights; ++i) - { - Light* l = mSceneMgr->createLight("l" + StringConverter::toString(i)); - l->setAttenuation(lightRange, 1, 0, 0); - /* SPOT LIGHT - */ - // match spot width to groud - Real spotHeight = lightRange * 0.5; - SceneNode* n = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3((spotWidth+50)*i + xoff,spotHeight,0)); - l->setType(Light::LT_SPOTLIGHT); - Radian spotAngle = Math::ATan(spotWidth / spotHeight) * 2; - l->setSpotlightOuterAngle(spotAngle); - l->setSpotlightInnerAngle(spotAngle * 0.75); - Vector3 dir(0, -1, 0); - dir.normalise(); - n->setDirection(dir, Node::TS_WORLD); - - /* END SPOT LIGHT */ - n->attachObject(l); - - Entity* e = mSceneMgr->createEntity("e" + StringConverter::toString(i), "robot.mesh"); - SceneNode* en = n->createChildSceneNode(Vector3(0, -200, 0)); - en->attachObject(e); - } - - // Modify the plane material so that it clips to the light on the second pass, post ambient - Pass* p = mat->getTechnique(0)->getPass(0); - String texname = p->getTextureUnitState(0)->getTextureName(); - p->removeAllTextureUnitStates(); - p->setIlluminationStage(IS_AMBIENT); - p->setDiffuse(ColourValue::Black); - p = mat->getTechnique(0)->createPass(); - p->setIlluminationStage(IS_PER_LIGHT); - p->setIteratePerLight(true, true); - //TODO Shouldn't the case below also be tested? - // p->setIteratePerLight(true, false); - p->setAmbient(ColourValue::Black); - p->setLightClipPlanesEnabled(true); - p->setSceneBlending(SBT_ADD); - //if (scissortoo) - //p->setLightScissoringEnabled(true); - p = mat->getTechnique(0)->createPass(); - p->setIlluminationStage(IS_DECAL); - p->createTextureUnitState(texname); - p->setLightingEnabled(false); - p->setSceneBlending(SBT_MODULATE); - - mCameraNode->setPosition(0, 200, 300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_LightScissoring::PlayPen_LightScissoring() -{ - mInfo["Title"] = "PlayPen_LightScissoring"; - mInfo["Description"] = "Tests light scissoring."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_LightScissoring::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue::White); - - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 0; - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 4500,4500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - - MaterialPtr mat = MaterialManager::getSingleton() - .getByName("Examples/GrassFloor") - ->clone("Myplane/Material", TRANSIENT_RESOURCE_GROUP); - - pPlaneEnt->setMaterial(mat); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - Real lightRange = 100; - - ManualObject* debugSphere = mSceneMgr->createManualObject("debugSphere"); - debugSphere->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_STRIP); - for (int i = 0; i <= 20; ++i) - { - Vector3 basePos(lightRange, 0, 0); - Quaternion quat; - quat.FromAngleAxis(Radian(((float)i/(float)20)*Math::TWO_PI), Vector3::UNIT_Y); - basePos = quat * basePos; - debugSphere->position(basePos); - } - for (int i = 0; i <= 20; ++i) - { - Vector3 basePos(lightRange, 0, 0); - Quaternion quat; - quat.FromAngleAxis(Radian(((float)i/(float)20)*Math::TWO_PI), Vector3::UNIT_Z); - basePos = quat * basePos; - debugSphere->position(basePos); - } - debugSphere->end(); - - ManualObject* debugSphere2 = mSceneMgr->createManualObject("debugSphere2"); - debugSphere2->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_STRIP); - for (int i = 0; i <= 20; ++i) - { - Vector3 basePos(lightRange, 0, 0); - Quaternion quat; - quat.FromAngleAxis(Radian(((float)i/(float)20)*Math::TWO_PI), Vector3::UNIT_Y); - basePos = quat * basePos; - debugSphere2->position(basePos); - } - for (int i = 0; i <= 20; ++i) - { - Vector3 basePos(lightRange, 0, 0); - Quaternion quat; - quat.FromAngleAxis(Radian(((float)i/(float)20)*Math::TWO_PI), Vector3::UNIT_Z); - basePos = quat * basePos; - debugSphere2->position(basePos); - } - debugSphere2->end(); - - Light* l = mSceneMgr->createLight("l1"); - l->setAttenuation(lightRange, 1, 0, 0); - SceneNode* n = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,95,0)); - n->attachObject(debugSphere); - n->attachObject(l); - - Light* l2 = mSceneMgr->createLight("l2"); - l2->setAttenuation(lightRange, 1, 0, 0); - SceneNode* n2 = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100,50,0)); - n2->attachObject(debugSphere2); - n2->attachObject(l2); - - // Modify the plane material so that it clips to the light - // Normally you'd only clip a secondary pass but this is engineered so you - // can actually see the scissoring effect - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightScissoringEnabled(true); - - mCameraNode->setPosition(0, 200, 300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_LiSPSM::PlayPen_LiSPSM() -{ - mInfo["Title"] = "PlayPen_LiSPSM"; - mInfo["Description"] = "Tests light-space shadow mapping camera setup."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_LiSPSM::cleanupContent() -{ - clearDebugTextureOverlays(); -} -//---------------------------------------------------------------------------- - -void PlayPen_LiSPSM::setupContent() -{ - SceneNode* mTestNode[10]; - - mSceneMgr->setShadowTextureSize(1024); - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE); - - //FocusedShadowCameraSetup* lispsmSetup = new FocusedShadowCameraSetup(); - LiSPSMShadowCameraSetup* lispsmSetup = new LiSPSMShadowCameraSetup(); - lispsmSetup->setOptimalAdjustFactor(2); - mSceneMgr->setShadowCameraSetup(ShadowCameraSetupPtr(lispsmSetup)); - - mSceneMgr->setShadowFarDistance(3000); - mSceneMgr->setShadowColour(ColourValue(0.35, 0.35, 0.35)); - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); - - OrientedLightPtr mLight = mSceneMgr->createLight("MainLight"); - mLight->setType(Light::LT_DIRECTIONAL); - Vector3 vec(-1,-1,0); - vec.normalise(); - mLight->setDirection(vec); - - mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - - Entity* pEnt; - pEnt = mSceneMgr->createEntity( "1", "robot.mesh" ); - //pEnt->setRenderingDistance(100); - AnimationState* mAnimState = pEnt->getAnimationState("Walk"); - mAnimState->setEnabled(true); - mAnimStateList.push_back(mAnimState); - //pEnt->setMaterialName("2 - Default"); - mTestNode[1]->attachObject( pEnt ); - mTestNode[1]->translate(0,-100,0); - - pEnt = mSceneMgr->createEntity( "3", "knot.mesh" ); - mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-200, 0, -200)); - mTestNode[2]->attachObject( pEnt ); - - createRandomEntityClones(pEnt, 20, Vector3(-1000,0,-1000), Vector3(1000,0,1000), mSceneMgr); - - // Transparent object (can force cast shadows) - pEnt = mSceneMgr->createEntity( "3.5", "knot.mesh" ); - MaterialPtr tmat = MaterialManager::getSingleton().create( - "TestAlphaTransparency", - TRANSIENT_RESOURCE_GROUP); - tmat->setTransparencyCastsShadows(true); - Pass* tpass = tmat->getTechnique(0)->getPass(0); - tpass->setAlphaRejectSettings(CMPF_GREATER, 150); - tpass->setSceneBlending(SBT_TRANSPARENT_ALPHA); - tpass->createTextureUnitState("gras_02.png"); - tpass->setCullingMode(CULL_NONE); - - pEnt->setMaterialName("TestAlphaTransparency"); - mTestNode[3] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(350, 0, -200)); - mTestNode[3]->attachObject( pEnt ); - - pEnt = mSceneMgr->createEntity( "4", "knot.mesh" ); - mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 0, 200)); - mTestNode[2]->attachObject( pEnt ); - - mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); - - MovablePlane movablePlane = MovablePlane(Vector3::UNIT_Y, 100); - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, movablePlane, - 2500,2500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt; - pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("2 - Default"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - addTextureShadowDebugOverlay(1, mSceneMgr); - - - mCameraNode->setPosition(0, 1000, 500); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); - mCamera->setFarClipDistance(10000); - - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - - -static void createRandomEntityClones(Entity* ent, size_t cloneCount, - const Vector3& min, const Vector3& max, SceneManager* mgr) -{ - Entity *cloneEnt; - for (size_t n = 0; n < cloneCount; ++n) - { - // Create a new node under the root. - SceneNode* node = mgr->createSceneNode(); - // Random translate. - Vector3 nodePos; - nodePos.x = Math::RangeRandom(min.x, max.x); - nodePos.y = Math::RangeRandom(min.y, max.y); - nodePos.z = Math::RangeRandom(min.z, max.z); - node->setPosition(nodePos); - mgr->getRootSceneNode()->addChild(node); - cloneEnt = ent->clone(ent->getName() + "_clone" + StringConverter::toString(n)); - // Attach to new node. - node->attachObject(cloneEnt); - - } -} - -PlayPen_LotsAndLotsOfEntities::PlayPen_LotsAndLotsOfEntities() -{ - mInfo["Title"] = "PlayPen_LotsAndLotsOfEntities"; - mInfo["Description"] = "Tests setting up and rendering a lot of entities."; - addScreenshotFrame(3);// only go a couple frames, this one is slow (and static) -} -//---------------------------------------------------------------------------- - -void PlayPen_LotsAndLotsOfEntities::setupContent() -{ - // Set ambient light. - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - - // Create a point light. - OrientedLightPtr l = mSceneMgr->createLight("MainLight"); - l->setType(Light::LT_DIRECTIONAL); - l->setDirection(-Vector3::UNIT_Y); - - // Create a set of random cubes. - Entity* ent = mSceneMgr->createEntity("Cube", "cube.mesh"); - ent->setMaterial(MaterialManager::getSingleton().getDefaultMaterial()); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); - createRandomEntityClones(ent, 3000, Vector3(-1000,-1000,-1000), Vector3(1000,1000,1000), mSceneMgr); - - //bool val = true; - //mSceneMgr->setOption("ShowOctree", &val); - - mCameraNode->setPosition(0,0, -4000); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - - // Enable the profiler. - Profiler* prof = Profiler::getSingletonPtr(); - if (prof) - prof->setEnabled(true); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_ManualBoneMovement::PlayPen_ManualBoneMovement() -{ - mInfo["Title"] = "PlayPen_ManualBoneMovement"; - mInfo["Description"] = "Tests manually controlling a skeletal animation bone."; - addScreenshotFrame(50); -} -//---------------------------------------------------------------------------- - -bool PlayPen_ManualBoneMovement::frameStarted(const FrameEvent& evt) -{ - mBone->yaw(Degree(evt.timeSinceLastFrame*100)); - return true; -} -//---------------------------------------------------------------------------- - -void PlayPen_ManualBoneMovement::setupContent() -{ - Entity *ent = mSceneMgr->createEntity("robot", "robot.mesh"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); - mSceneMgr->setAmbientLight(ColourValue(0.8, 0.8, 0.8)); - - //ent->setMaterialName("Examples/Rocky"); - - SkeletonInstance* skel = ent->getSkeleton(); - Animation* anim = skel->getAnimation("Walk"); - mBone = skel->getBone("Joint10"); - mBone->setManuallyControlled(true); - anim->destroyNodeTrack(mBone->getHandle()); - - //AnimationState* animState = ent->getAnimationState("Walk"); - //animState->setEnabled(true); - - mCameraNode->setPosition(100,50,200); - mCameraNode->lookAt(Vector3(0, 25, 0), Node::TS_PARENT); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_ManualIlluminationStage::PlayPen_ManualIlluminationStage() -{ - mInfo["Title"] = "PlayPen_ManualIlluminationStage"; - mInfo["Description"] = "Tests manual illumination stages."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_ManualIlluminationStage::setupContent() -{ - // Make this viewport work with shader generator scheme. - mViewport->setMaterialScheme(MSN_SHADERGEN); - - mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_ADDITIVE); - mSceneMgr->setShadowDirectionalLightExtrusionDistance(1000); - - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.0, 0.0, 0.0)); - - Light* mLight = mSceneMgr->createLight("MainLight"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-400,400,-300))->attachObject(mLight); - mLight->setDiffuseColour(0.9, 0.9, 1); - mLight->setSpecularColour(0.9, 0.9, 1); - mLight->setAttenuation(6000,1,0.001,0); - - mLight = mSceneMgr->createLight("Light2"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(300,200,100))->attachObject(mLight); - mLight->setDiffuseColour(1, 0.6, 0.5); - mLight->setSpecularColour(0.9, 0.9, 1); - mLight->setAttenuation(6000,1,0.001,0); - - MeshPtr msh = MeshManager::getSingleton().load("knot.mesh", ASSETS_RESOURCE_GROUP); - msh->buildTangentVectors(); - Entity* pEnt = mSceneMgr->createEntity( "3.5", "knot.mesh" ); - pEnt->setMaterialName("Examples/OffsetMapping/Specular"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject( pEnt ); - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 100; - MeshPtr planeMesh = MeshManager::getSingleton().createPlane( - "Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 1500, 1500, 100, 100, true, 1, 15, 15, Vector3::UNIT_Z); - planeMesh->buildTangentVectors(); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("Examples/OffsetMapping/Specular"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - mCameraNode->setPosition(180, 34, 223); - mCameraNode->lookAt(Vector3(0, 50, 0), Node::TS_PARENT); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_ManualObject2D::PlayPen_ManualObject2D() -{ - mInfo["Title"] = "PlayPen_ManualObject2D"; - mInfo["Description"] = "Tests 2d manual objects."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_ManualObject2D::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue::White); - - ManualObject* man = mSceneMgr->createManualObject("1"); - man->begin("Examples/OgreLogo"); - man->position( 0.0, 0.0, 0.0); man->textureCoord( 0, 1 ); man->normal(0, 0, 1); - man->position( 0.1, 0.0, 0.0); man->textureCoord( 1, 1 ); man->normal(0, 0, 1); - man->position( 0.1, 0.1, 0.0); man->textureCoord( 1, 0 ); man->normal(0, 0, 1); - man->position( 0.0, 0.1, 0.0); man->textureCoord( 0, 0 ); man->normal(0, 0, 1); - - man->triangle( 0, 1, 2 ); - man->triangle( 0, 2, 3 ); - - man->setRenderQueueGroup(RENDER_QUEUE_OVERLAY - 1); - man->end(); - man->setUseIdentityProjection(true); - man->setUseIdentityView(true); - man->setBoundingBox(AxisAlignedBox::EXTENT_INFINITE); - - SceneNode* sn = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - sn->setScale(5,5,1); - sn->attachObject(man); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_ManualObjectIndexed::PlayPen_ManualObjectIndexed() -{ - mInfo["Title"] = "PlayPen_ManualObjectIndexed"; - mInfo["Description"] = "Tests indexed manual objects."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_ManualObjectIndexed::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - Vector3 dir(-1, -1, 0.5); - dir.normalise(); - OrientedLightPtr l = mSceneMgr->createLight("light1"); - l->setType(Light::LT_DIRECTIONAL); - l->setDirection(dir); - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 100; - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("2 - Default"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - // Define a 40x40 plane, indexed - //! [manual_plane_begin] - Ogre::ManualObject* man = mSceneMgr->createManualObject("test"); - man->begin("Examples/OgreLogo", Ogre::RenderOperation::OT_TRIANGLE_LIST); - //! [manual_plane_begin] - - //! [manual_plane_vertices] - man->position(-20, 20, 20); - man->normal(0, 0, 1); - man->textureCoord(0, 0); - - man->position(-20, -20, 20); - man->normal(0, 0, 1); - man->textureCoord(0, 1); - - man->position(20, -20, 20); - man->normal(0, 0, 1); - man->textureCoord(1, 1); - - man->position(20, 20, 20); - man->normal(0, 0, 1); - man->textureCoord(1, 0); - //! [manual_plane_vertices] - - //! [manual_plane_faces] - man->quad(0, 1, 2, 3); - //! [manual_plane_faces] - - man->end(); - - man->begin("Examples/BumpyMetal"); - - // Define a 40x40 plane, indexed - man->position(-20, 20, 20); - man->normal(0, 1, 0); - man->textureCoord(0, 0); - - man->position(20, 20, 20); - man->normal(0, 1, 0); - man->textureCoord(0, 1); - - man->position(20, 20, -20); - man->normal(0, 1, 0); - man->textureCoord(1, 1); - - man->position(-20, 20, -20); - man->normal(0, 1, 0); - man->textureCoord(1, 0); - - man->quad(0, 1, 2, 3); - - //! [manual_plane_end] - man->end(); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(man); - //! [manual_plane_end] - - mCameraNode->setPosition(100,100,100); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_ManualObjectIndexedUpdateLarger::PlayPen_ManualObjectIndexedUpdateLarger() -{ - mInfo["Title"] = "PlayPen_ManualObjectIndexedUpdateLarger"; - mInfo["Description"] = "Tests updating indexed manual objects."; -} -//---------------------------------------------------------------------------- - -void PlayPen_ManualObjectIndexedUpdateLarger::setupContent() -{ - PlayPen_ManualObjectIndexed::setupContent(); - ManualObject* man = mSceneMgr->getManualObject("test"); - - man->beginUpdate(0); - // 1 quad larger - man->position(-20, 20, 20); - man->normal(0, 0, 1); - man->textureCoord(0, 0); - - man->position(-20, -20, 20); - man->normal(0, 0, 1); - man->textureCoord(0, 1); - - man->position(20, -20, 20); - man->normal(0, 0, 1); - man->textureCoord(1, 1); - - man->position(20, 20, 20); - man->normal(0, 0, 1); - man->textureCoord(1, 0); - - - man->position(-20, 40, 20); - man->normal(0, 0, 1); - man->textureCoord(0, 0); - - man->position(-20, 20, 20); - man->normal(0, 0, 1); - man->textureCoord(0, 1); - - man->position(20, 20, 20); - man->normal(0, 0, 1); - man->textureCoord(1, 1); - - man->position(20, 40, 20); - man->normal(0, 0, 1); - man->textureCoord(1, 0); - - man->quad(0, 1, 2, 3); - man->quad(4, 5, 6, 7); - - man->end(); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_ManualObjectIndexedUpdateSmaller::PlayPen_ManualObjectIndexedUpdateSmaller() -{ - mInfo["Title"] = "PlayPen_ManualObjectIndexedUpdateSmaller"; - mInfo["Description"] = "Tests updating indexed manual objects."; -} -//---------------------------------------------------------------------------- - -void PlayPen_ManualObjectIndexedUpdateSmaller::setupContent() -{ - PlayPen_ManualObjectIndexed::setupContent(); - ManualObject* man = mSceneMgr->getManualObject("test"); - - man->beginUpdate(0); - // 1 tri smaller - man->position(-20, 20, 20); - man->normal(0, 0, 1); - man->textureCoord(0, 0); - - man->position(-20, -20, 20); - man->normal(0, 0, 1); - man->textureCoord(0, 1); - - man->position(20, -20, 20); - man->normal(0, 0, 1); - man->textureCoord(1, 1); - - man->triangle(0, 1, 2); - - man->end(); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_ManualObjectNonIndexed::PlayPen_ManualObjectNonIndexed() -{ - mInfo["Title"] = "PlayPen_ManualObjectNonIndexed"; - mInfo["Description"] = "Tests non-indexed manual objects."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_ManualObjectNonIndexed::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - Vector3 dir(-1, -1, 0.5); - dir.normalise(); - OrientedLightPtr l = mSceneMgr->createLight("light1"); - l->setType(Light::LT_DIRECTIONAL); - l->setDirection(dir); - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 100; - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("2 - Default"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - ManualObject* man = mSceneMgr->createManualObject("test"); - - man->begin("Examples/OgreLogo"); - // Define a 40x40 plane, non-indexed - man->position(-20, 20, 20); - man->normal(0, 0, 1); - man->textureCoord(0, 0); - - man->position(-20, -20, 20); - man->normal(0, 0, 1); - man->textureCoord(0, 1); - - man->position(20, 20, 20); - man->normal(0, 0, 1); - man->textureCoord(1, 0); - - man->position(-20, -20, 20); - man->normal(0, 0, 1); - man->textureCoord(0, 1); - - man->position(20, -20, 20); - man->normal(0, 0, 1); - man->textureCoord(1, 1); - - man->position(20, 20, 20); - man->normal(0, 0, 1); - man->textureCoord(1, 0); - - man->end(); - - man->begin("Examples/BumpyMetal"); - - // Define a 40x40 plane, non-indexed - man->position(-20, 20, 20); - man->normal(0, 1, 0); - man->textureCoord(0, 0); - - man->position(20, 20, 20); - man->normal(0, 1, 0); - man->textureCoord(0, 1); - - man->position(20, 20, -20); - man->normal(0, 1, 0); - man->textureCoord(1, 1); - - man->position(20, 20, -20); - man->normal(0, 1, 0); - man->textureCoord(1, 1); - - man->position(-20, 20, -20); - man->normal(0, 1, 0); - man->textureCoord(1, 0); - - man->position(-20, 20, 20); - man->normal(0, 1, 0); - man->textureCoord(0, 0); - - man->end(); - - - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(man); - mCameraNode->setPosition(100,100,100); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_ManualObjectNonIndexedUpdateLarger::PlayPen_ManualObjectNonIndexedUpdateLarger() -{ - mInfo["Title"] = "PlayPen_ManualObjectNonIndexedUpdateLarger"; - mInfo["Description"] = "Tests updating non-indexed manual objects."; -} -//---------------------------------------------------------------------------- - -void PlayPen_ManualObjectNonIndexedUpdateLarger::setupContent() -{ - PlayPen_ManualObjectNonIndexed::setupContent(); - ManualObject* man = mSceneMgr->getManualObject("test"); - - // Redefine but make larger (2 more tri) - man->beginUpdate(0); - - man->position(-20, 20, 20); - man->normal(0, 0, 1); - man->textureCoord(0, 0); - - man->position(-20, -20, 20); - man->normal(0, 0, 1); - man->textureCoord(0, 1); - - man->position(20, 20, 20); - man->normal(0, 0, 1); - man->textureCoord(1, 0); - - man->position(-20, -20, 20); - man->normal(0, 0, 1); - man->textureCoord(0, 1); - - man->position(20, -20, 20); - man->normal(0, 0, 1); - man->textureCoord(1, 1); - - man->position(20, 20, 20); - man->normal(0, 0, 1); - man->textureCoord(1, 0); - - - man->position(-20, 40, 20); - man->normal(0, 0, 1); - man->textureCoord(0, 0); - - man->position(-20, 20, 20); - man->normal(0, 0, 1); - man->textureCoord(0, 1); - - man->position(20, 40, 20); - man->normal(0, 0, 1); - man->textureCoord(1, 0); - - man->position(-20, 20, 20); - man->normal(0, 0, 1); - man->textureCoord(0, 1); - - man->position(20, 20, 20); - man->normal(0, 0, 1); - man->textureCoord(1, 1); - - man->position(20, 40, 20); - man->normal(0, 0, 1); - man->textureCoord(1, 0); - - - man->end(); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_ManualObjectNonIndexedUpdateSmaller::PlayPen_ManualObjectNonIndexedUpdateSmaller() -{ - mInfo["Title"] = "PlayPen_ManualObjectNonIndexedUpdateSmaller"; - mInfo["Description"] = "Tests updating non-indexed manual objects."; -} -//---------------------------------------------------------------------------- - -void PlayPen_ManualObjectNonIndexedUpdateSmaller::setupContent() -{ - PlayPen_ManualObjectNonIndexed::setupContent(); - ManualObject* man = mSceneMgr->getManualObject("test"); - - // Redefine but make smaller (one tri less) - man->beginUpdate(0); - man->position(-30, 30, 30); - man->normal(0, 0, 1); - man->textureCoord(0, 0); - - man->position(-30, -30, 30); - man->normal(0, 0, 1); - man->textureCoord(0, 1); - - man->position(90, 30, 30); - man->normal(0, 0, 1); - man->textureCoord(1, 0); - - - man->end(); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_MaterialSchemes::PlayPen_MaterialSchemes() -{ - mInfo["Title"] = "PlayPen_MaterialSchemes"; - mInfo["Description"] = "Tests material scehemes in viewports."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_MaterialSchemes::setupContent() -{ - - Entity *ent = mSceneMgr->createEntity("robot", "robot.mesh"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); - mSceneMgr->setAmbientLight(ColourValue(0.8, 0.8, 0.8)); - - MaterialPtr mat = MaterialManager::getSingleton().create("schemetest", - TRANSIENT_RESOURCE_GROUP); - // default scheme - mat->getTechnique(0)->getPass(0)->createTextureUnitState("GreenSkin.jpg"); - - Technique* t = mat->createTechnique(); - t->setSchemeName("newscheme"); - t->createPass()->createTextureUnitState("rockwall.tga"); - ent->setMaterialName("schemetest"); - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - // force create shaders for non default scheme - t->setSchemeName("newscheme_tmp"); - RTShader::ShaderGenerator& rtShaderGen = RTShader::ShaderGenerator::getSingleton(); - rtShaderGen.createShaderBasedTechnique(*mat, "newscheme_tmp", "newscheme"); - rtShaderGen.validateMaterial("newscheme", *mat); -#endif - - // create a second viewport using alternate scheme - Viewport* vp = mWindow->addViewport(mCamera, 1, 0.75, 0, 0.25, 0.25); - vp->setMaterialScheme("newscheme"); - vp->setOverlaysEnabled(false); - - mCameraNode->setPosition(0,75,200); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_MaterialSchemesListener::PlayPen_MaterialSchemesListener() -{ - mInfo["Title"] = "PlayPen_MaterialSchemesListener"; - mInfo["Description"] = "Tests material scheme listener."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -class TestMatMgrListener : public MaterialManager::Listener -{ -public: - TestMatMgrListener() : mTech(0) {} - Technique* mTech; - - - Technique* handleSchemeNotFound(unsigned short schemeIndex, - const String& schemeName, Material* originalMaterial, unsigned short lodIndex, - const Renderable* rend) override - { - return mTech; - } -}; - -TestMatMgrListener schemeListener; - -void PlayPen_MaterialSchemesListener::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue(0.8, 0.8, 0.8)); - - Entity *ent = mSceneMgr->createEntity("robot", "robot.mesh"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); - - // create a second viewport using alternate scheme - // notice it's not defined in a technique - Viewport* vp = mWindow->addViewport(mCamera, 1, 0.75, 0, 0.25, 0.25); - vp->setMaterialScheme("newscheme"); - vp->setOverlaysEnabled(false); - - MaterialPtr mat = MaterialManager::getSingleton().create("schemetest", - TRANSIENT_RESOURCE_GROUP); - // default scheme - mat->getTechnique(0)->getPass(0)->createTextureUnitState("GreenSkin.jpg"); - - schemeListener.mTech = mat->getTechnique(0); - MaterialManager::getSingleton().addListener(&schemeListener); - - mCameraNode->setPosition(0, 75, 200); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_MaterialSchemesWithLOD::PlayPen_MaterialSchemesWithLOD() -{ - mInfo["Title"] = "PlayPen_MaterialSchemesWithLOD"; - mInfo["Description"] = "Tests material schemes with LODs."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_MaterialSchemesWithLOD::setupContent() -{ - - Entity *ent = mSceneMgr->createEntity("robot", "robot.mesh"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); - mSceneMgr->setAmbientLight(ColourValue(0.8, 0.8, 0.8)); - - MaterialPtr mat = MaterialManager::getSingleton().create("schemetest", - TRANSIENT_RESOURCE_GROUP); - // default scheme - mat->getTechnique(0)->getPass(0)->createTextureUnitState("GreenSkin.jpg"); - - // LOD 0, newscheme - Technique* t = mat->createTechnique(); - t->setSchemeName("newscheme"); - t->createPass()->createTextureUnitState("rockwall.tga"); - ent->setMaterialName("schemetest"); - - // LOD 1, default - t = mat->createTechnique(); - t->setLodIndex(1); - t->createPass()->createTextureUnitState("Water02.jpg"); - - // LOD 1, newscheme - t = mat->createTechnique(); - t->setLodIndex(1); - t->createPass()->createTextureUnitState("r2skin.jpg"); - t->setSchemeName("newscheme"); - - Material::LodValueList ldl; - //ldl.push_back(Math::Sqr(500.0f)); - ldl.push_back(150.0f); - mat->setLodLevels(ldl); - - - ent->setMaterialName("schemetest"); - - // create a second viewport using alternate scheme - Viewport* vp = mWindow->addViewport(mCamera, 1, 0.75, 0, 0.25, 0.25); - vp->setMaterialScheme("newscheme"); - vp->setOverlaysEnabled(false); - - mCameraNode->setPosition(0,90,250); - //mCameraNode->lookAt(Vector3(Vector3(0, 0, 0)), Node::TS_PARENT); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_MaterialSchemesWithMismatchedLOD::PlayPen_MaterialSchemesWithMismatchedLOD() -{ - mInfo["Title"] = "PlayPen_MaterialSchemesWithMismatchedLOD"; - mInfo["Description"] = "Tests material scehemes in viewports with mismatched LODs."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_MaterialSchemesWithMismatchedLOD::setupContent() -{ - - Entity *ent = mSceneMgr->createEntity("robot", "robot.mesh"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); - mSceneMgr->setAmbientLight(ColourValue(0.8, 0.8, 0.8)); - - MaterialPtr mat = MaterialManager::getSingleton().create("schemetest", - TRANSIENT_RESOURCE_GROUP); - // default scheme - mat->getTechnique(0)->getPass(0)->createTextureUnitState("GreenSkin.jpg"); - - // LOD 0, newscheme - Technique* t = mat->createTechnique(); - t->setSchemeName("newscheme"); - t->createPass()->createTextureUnitState("rockwall.tga"); - ent->setMaterialName("schemetest"); - - // LOD 1, default - t = mat->createTechnique(); - t->setLodIndex(1); - t->createPass()->createTextureUnitState("Water02.jpg"); - - // LOD 2, default - t = mat->createTechnique(); - t->setLodIndex(2); - t->createPass()->createTextureUnitState("clouds.jpg"); - - // LOD 1, newscheme - t = mat->createTechnique(); - t->setLodIndex(1); - t->createPass()->createTextureUnitState("r2skin.jpg"); - t->setSchemeName("newscheme"); - - // No LOD 2 for newscheme! Should fallback on LOD 1 - - Material::LodValueList ldl; - //ldl.push_back(Math::Sqr(250.0f)); - //ldl.push_back(Math::Sqr(500.0f)); - ldl.push_back(150.0f); - ldl.push_back(300.0f); - mat->setLodLevels(ldl); - - - ent->setMaterialName("schemetest"); - - // create a second viewport using alternate scheme - Viewport* vp = mWindow->addViewport(mCamera, 1, 0.75, 0, 0.25, 0.25); - vp->setMaterialScheme("newscheme"); - vp->setOverlaysEnabled(false); - - mCameraNode->setPosition(0,90,350); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -/*PlayPen_MRTCompositorScript::PlayPen_MRTCompositorScript() - { - mInfo["Title"] = "PlayPen_MRTCompositorScript"; - mInfo["Description"] = "Tests MRT compositor."; - addScreenshotFrame(250); - } - //---------------------------------------------------------------------------- - - void PlayPen_MRTCompositorScript::setupContent() - { - - Entity* e = mSceneMgr->createEntity("e1", "knot.mesh"); - e->setMaterialName("Ogre/MRTtest/scene"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - mCameraNode->setPosition(0, 0, -100); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - - CompositorInstance* compInst = - CompositorManager::getSingleton().addCompositor(mWindow->getViewport(0), "TestMRT"); - CompositorManager::getSingleton().setCompositorEnabled(mWindow->getViewport(0), "TestMRT", true); - - // Set up debug panels for each of the MRT outputs - String texName = compInst->getTextureInstanceName("mrt0", 0); - addTextureDebugOverlay(TextureManager::getSingleton().getByName(texName), 0); - texName = compInst->getTextureInstanceName("mrt0", 1); - addTextureDebugOverlay(TextureManager::getSingleton().getByName(texName), 1); - texName = compInst->getTextureInstanceName("mrt0", 2); - addTextureDebugOverlay(TextureManager::getSingleton().getByName(texName), 2); - texName = compInst->getTextureInstanceName("mrt0", 3); - addTextureDebugOverlay(TextureManager::getSingleton().getByName(texName), 3); - }*/ -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -/*PlayPen_MRT::PlayPen_MRT() - { - mInfo["Title"] = "PlayPen_MRT"; - mInfo["Description"] = "Tests MRT."; - addScreenshotFrame(250); - } - //---------------------------------------------------------------------------- - - void PlayPen_MRT::setupContent() - { - TexturePtr Tex[2]; - MultiRenderTarget* mrtTex; - - Viewport* viewport = mWindow->getViewport(0); - int width = viewport->getActualWidth(); - int height = viewport->getActualHeight(); - - Tex[0] = TextureManager::getSingleton().createManual("diffusemap", TRANSIENT_RESOURCE_GROUP, TEX_TYPE_2D, - width,height,0,PF_R8G8B8A8,TU_RENDERTARGET); - Tex[1] = TextureManager::getSingleton().createManual("normalmap",TRANSIENT_RESOURCE_GROUP, TEX_TYPE_2D, - width,height,0,PF_R8G8B8A8,TU_RENDERTARGET); - - // assert(Tex[0]->getFormat() == PF_FLOAT16_RGBA); - - mrtTex = Ogre::Root::getSingleton().getRenderSystem()->createMultiRenderTarget("MRT"); - RenderTexture* rTex[2]; - rTex[0] = Tex[0]->getBuffer()->getRenderTarget(); - rTex[1] = Tex[1]->getBuffer()->getRenderTarget(); - - rTex[0]->setAutoUpdated(false); - rTex[1]->setAutoUpdated(false); - mrtTex->bindSurface(0, rTex[0]); - mrtTex->bindSurface(1, rTex[1]); - mrtTex->setAutoUpdated(true); - - Viewport *v = mrtTex->addViewport(mCamera); - v->setMaterialScheme("MRT"); - v->setClearEveryFrame(true); - v->setOverlaysEnabled(false); - v->setSkiesEnabled(false); - v->setBackgroundColour(ColourValue(0,0,0,0)); - - // Create texture overlay here - Overlay *debugOverlay = OverlayManager::getSingleton().create("Core/DebugOverlay"); - MaterialPtr debugMat = MaterialManager::getSingleton().create("DebugRTTMat1", TRANSIENT_RESOURCE_GROUP); - debugMat->getTechnique(0)->getPass(0)->setLightingEnabled(false); - TextureUnitState *t = debugMat->getTechnique(0)->getPass(0)->createTextureUnitState("normalmap"); - t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); - OverlayContainer *debugPanel = (OverlayContainer *) (OverlayManager::getSingleton().createOverlayElement("Panel","DebugRTTPanel1")); - debugPanel->_setPosition(0.8,0); - debugPanel->_setDimensions(0.2,0.3); - debugPanel->setMaterialName(debugMat->getName()); - debugOverlay->add2D(debugPanel); - - debugMat = MaterialManager::getSingleton().create("DebugRTTMat2", TRANSIENT_RESOURCE_GROUP); - debugMat->getTechnique(0)->getPass(0)->setLightingEnabled(false); - t = debugMat->getTechnique(0)->getPass(0)->createTextureUnitState("diffusemap"); - t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); - debugPanel = (OverlayContainer *) (OverlayManager::getSingleton().createOverlayElement("Panel","DebugRTTPanel2")); - debugPanel->_setPosition(0.8,0.3); - debugPanel->_setDimensions(0.2,0.3); - debugPanel->setMaterialName(debugMat->getName()); - debugOverlay->add2D(debugPanel); - // Create scene items - - // Create a material to render differently to MRT compared to main viewport - MaterialPtr mat = MaterialManager::getSingleton().create("MRTTest", - TRANSIENT_RESOURCE_GROUP); - // normal technique (0), leave as default - Technique* mrtTech = mat->createTechnique(); - mrtTech->setSchemeName("MRT"); - Pass* mrtPass = mrtTech->createPass(); - mrtPass->setVertexProgram("DeferredShading/material/hlsl/vs"); - mrtPass->setFragmentProgram("DeferredShading/material/hlsl/ps"); - mrtPass->createTextureUnitState("rockwall.tga"); - mat->load(); - - Entity* ent = mSceneMgr->createEntity("knot", "knot.mesh"); - ent->setMaterialName("MRTTest"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); - - mCameraNode->setPosition(0, 0, 200); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - - - - }*/ -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_MultiSceneManagersSimple::PlayPen_MultiSceneManagersSimple() -{ - mInfo["Title"] = "PlayPen_MultiSceneManagersSimple"; - mInfo["Description"] = "Tests multiple scene managers."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_MultiSceneManagersSimple::setupContent() -{ - // Create a secondary scene manager with it's own camera - SceneManager* sm2 = Root::getSingleton().createSceneManager(); - Light* l = sm2->createLight("l2"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 50, -100))->attachObject(l); - l->setDiffuseColour(ColourValue::Green); - // l->setDiffuseColour(ColourValue::Red); - sm2->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); - // sm2->setAmbientLight(ColourValue(1, 1, 1)); - Entity* ent = sm2->createEntity("knot2", "knot.mesh"); - // Entity* ent = sm2->createEntity("head", "ogrehead.mesh"); - sm2->getRootSceneNode()->createChildSceneNode()->attachObject(ent); - Camera* camera2 = sm2->createCamera("cam2"); - SceneNode* camNode2 = sm2->getRootSceneNode()->createChildSceneNode(); - camNode2->attachObject(camera2); - camNode2->setPosition(0, 0, -500); - camNode2->lookAt(Vector3::ZERO, Node::TS_PARENT); - - Viewport* vp = mWindow->addViewport(camera2, 1, 0.67, 0, 0.33, 0.25); - vp->setOverlaysEnabled(false); - vp->setBackgroundColour(ColourValue(1,0,0)); - - // Use original SM for normal scene - l = mSceneMgr->createLight("l"); // note same name, will work since different SM - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 50, -100))->attachObject(l); - l->setDiffuseColour(ColourValue::Red); - mSceneMgr->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); - ent = mSceneMgr->createEntity("head", "ogrehead.mesh"); - // ent = mSceneMgr->createEntity("knot", "knot.mesh"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); - mCameraNode->setPosition(0, 0, 500); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_MultiViewports::PlayPen_MultiViewports() -{ - mInfo["Title"] = "PlayPen_MultiViewports"; - mInfo["Description"] = "Tests multiple viewports."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_MultiViewports::setupContent() -{ - SceneNode* mTestNode[3]; - - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - - // Create a point light - OrientedLightPtr l = mSceneMgr->createLight("MainLight"); - l->setType(Light::LT_DIRECTIONAL); - l->setDirection(-Vector3::UNIT_Y); - - Entity* pEnt = mSceneMgr->createEntity( "1", "knot.mesh" ); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-30,0,-50))->attachObject(pEnt); - - mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - pEnt = mSceneMgr->createEntity( "2", "ogrehead.mesh" ); - mTestNode[0]->attachObject( pEnt ); - mTestNode[0]->translate(0, 0, 200); - - Ogre::Frustum* frustum = new Frustum(); - //frustum->setVisible(true); - frustum->setFarClipDistance(5000); - frustum->setNearClipDistance(100); - mTestNode[0]->attachObject(frustum); - - Viewport* vp = mWindow->addViewport(mCamera, 1, 0.5, 0.5, 0.5, 0.5); - vp->setOverlaysEnabled(false); - vp->setBackgroundColour(ColourValue(1,0,0)); - - mCameraNode->setPosition(0,0,500); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_NegativeScale::PlayPen_NegativeScale() -{ - mInfo["Title"] = "PlayPen_NegativeScale"; - mInfo["Description"] = "Tests negative scaling."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_NegativeScale::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); - Light* l = mSceneMgr->createLight("l1"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(500, 500, 200))->attachObject(l); - l->setDiffuseColour(ColourValue::White); - - //mSceneMgr->setFlipCullingOnNegativeScale(false); - - Entity *e = mSceneMgr->createEntity("1", "knot.mesh"); - - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - - // one reflection - e = mSceneMgr->createEntity("2", "knot.mesh"); - SceneNode* n = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - n->translate(-200, 0, 0); - n->scale(-1, 1, 1); - n->attachObject(e); - - // three reflections - will need flipping - e = mSceneMgr->createEntity("3", "knot.mesh"); - n = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - n->translate(200, 0, 0); - n->scale(-1, -1, -1); - n->attachObject(e); - - // two reflections - won't need flipping - e = mSceneMgr->createEntity("4", "knot.mesh"); - n = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - n->translate(400, 0, 0); - n->scale(-1, 1, -1); - n->attachObject(e); - - mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); - - mCameraNode->setPosition(0,0,300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_NormalMapMirroredUVs::PlayPen_NormalMapMirroredUVs() -{ - mInfo["Title"] = "PlayPen_NormalMapMirroredUVs"; - mInfo["Description"] = "Tests mirrored UVs with normal mapping shader."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_NormalMapMirroredUVs::setupContent() -{ - // Make this viewport work with shader generator scheme. - mViewport->setMaterialScheme(MSN_SHADERGEN); - - Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); - - // this mesh has been generated with 4-component tangents, including a parity in w - Entity* e = mSceneMgr->createEntity("2", "testmirroreduvmesh.mesh"); - e->setMaterialName("Examples/BumpMapping/MultiLightTangentParity"); - // here's what it looks like without the parity - // e->setMaterialName("Examples/BumpMapping/MultiLight"); - - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - - Light* l = mSceneMgr->createLight("3"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(1000,500,1000))->attachObject(l); - - mCameraNode->setPosition(0,200,50); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - - mSceneMgr->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_Ortho::PlayPen_Ortho() -{ - mInfo["Title"] = "PlayPen_Ortho"; - mInfo["Description"] = "Tests orthographic rendering."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_Ortho::setupContent() -{ - SceneNode* mTestNode[3]; - - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.0, 0.0, 0.0)); - - // Create a point light - Light* l = mSceneMgr->createLight("MainLight"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(800,600,0))->attachObject(l); - - mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - Entity* pEnt = mSceneMgr->createEntity( "3", "knot.mesh" ); - mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-200, 0, -200)); - mTestNode[1]->attachObject( pEnt ); - - pEnt = mSceneMgr->createEntity( "4", "knot.mesh" ); - mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 0, 200)); - mTestNode[2]->attachObject( pEnt ); - - - mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); - - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 100; - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("2 - Default"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - mCameraNode->setFixedYawAxis(false); - mCamera->setProjectionType(PT_ORTHOGRAPHIC); - mCameraNode->setPosition(0,10000,0); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); - mCamera->setNearClipDistance(1000); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_PointSprites::PlayPen_PointSprites() -{ - mInfo["Title"] = "PlayPen_PointSprites"; - mInfo["Description"] = "Tests point sprites."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_PointSprites::setupContent() -{ - MaterialPtr mat = MaterialManager::getSingleton().create("spriteTest1", - TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setPointSpritesEnabled(true); - p->createTextureUnitState("flare.png"); - p->setLightingEnabled(false); - p->setDepthWriteEnabled(false); - p->setSceneBlending(SBT_ADD); - p->setPointAttenuation(true); - p->setPointSize(3); - p->setVertexColourTracking(TVC_DIFFUSE); - - ManualObject* man = mSceneMgr->createManualObject("man"); - man->begin("spriteTest1", RenderOperation::OT_POINT_LIST); - - for (size_t i = 0; i < 1000; ++i) - { - man->position(Math::SymmetricRandom() * 500, - Math::SymmetricRandom() * 500, - Math::SymmetricRandom() * 500); - man->colour(Math::RangeRandom(0.5f, 1.0f), - Math::RangeRandom(0.5f, 1.0f), Math::RangeRandom(0.5f, 1.0f)); - } - - // for (size_t i = 0; i < 20; ++i) - // { - // for (size_t j = 0; j < 20; ++j) - // { - // for (size_t k = 0; k < 20; ++k) - // { - // if (rand()%10 == 0) - // man->position(i * 30, j * 30, k * 30); - // } - // } - // } - - man->end(); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(man); - - mCameraNode->setPosition(0,0,1000); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_Projection::PlayPen_Projection() -{ - mInfo["Title"] = "PlayPen_Projection"; - mInfo["Description"] = "Tests projection."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_Projection::setupContent() -{ - SceneNode* mTestNode[3]; - - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - - // Create a point light - OrientedLightPtr l = mSceneMgr->createLight("MainLight"); - l->setType(Light::LT_DIRECTIONAL); - l->setDirection(-Vector3::UNIT_Y); - - Entity* pEnt; - //pEnt = mSceneMgr->createEntity( "1", "knot.mesh" ); - //mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-30,0,-50))->attachObject(pEnt); - //pEnt->setMaterialName("Examples/OgreLogo"); - - // Define a floor plane mesh - Plane p; - p.normal = Vector3::UNIT_Z; - p.d = 200; - MeshManager::getSingleton().createPlane("WallPlane", - TRANSIENT_RESOURCE_GROUP, - p,1500,1500,1,1,true,1,5,5,Vector3::UNIT_Y); - pEnt = mSceneMgr->createEntity( "5", "WallPlane" ); - pEnt->setMaterialName("Examples/OgreLogo"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pEnt); - - - mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - //pEnt = mSceneMgr->createEntity( "2", "ogrehead.mesh" ); - //mTestNode[0]->attachObject( pEnt ); - mTestNode[0]->translate(0, 0, 750); - - Ogre::Frustum* frustum = new Frustum(); - frustum->setVisible(true); - frustum->setFarClipDistance(5000); - frustum->setNearClipDistance(200); - frustum->setAspectRatio(1); - frustum->setProjectionType(PT_ORTHOGRAPHIC); - mTestNode[0]->attachObject(frustum); - - // Hook the frustum up to the material - MaterialPtr mat = MaterialManager::getSingleton().getByName("Examples/OgreLogo"); - TextureUnitState *t = mat->getTechnique(0)->getPass(0)->getTextureUnitState(0); - t->setProjectiveTexturing(true, frustum); - //t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_ReflectedBillboards::PlayPen_ReflectedBillboards() -{ - mInfo["Title"] = "PlayPen_ReflectedBillboards"; - mInfo["Description"] = "Tests reflected billboards."; - addScreenshotFrame(175); // needs to run for a bit so there are particles to be reflected... -} -//---------------------------------------------------------------------------- - -void PlayPen_ReflectedBillboards::setupContent() -{ - Camera* reflectCam = 0; - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); - - // Create a light - OrientedLightPtr l = mSceneMgr->createLight("MainLight"); - l->setType(Light::LT_DIRECTIONAL); - Vector3 dir(0.5, -1, 0); - dir.normalise(); - l->setDirection(dir); - l->setDiffuseColour(1.0f, 1.0f, 0.8f); - l->setSpecularColour(1.0f, 1.0f, 1.0f); - - - // Create a prefab plane - Plane plane; - plane.d = 0; - plane.normal = Vector3::UNIT_Y; - MeshManager::getSingleton().createPlane("ReflectionPlane", - TRANSIENT_RESOURCE_GROUP, - plane, 2000, 2000, - 1, 1, true, 1, 1, 1, Vector3::UNIT_Z); - Entity* planeEnt = mSceneMgr->createEntity( "Plane", "ReflectionPlane" ); - - // Attach the rtt entity to the root of the scene - SceneNode* rootNode = mSceneMgr->getRootSceneNode(); - SceneNode* planeNode = rootNode->createChildSceneNode(); - - // Attach both the plane entity, and the plane definition - planeNode->attachObject(planeEnt); - - mCameraNode->setPosition(-50, 100, 500); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); - - TexturePtr rttTex = TextureManager::getSingleton().createManual("RttTex", - TRANSIENT_RESOURCE_GROUP, TEX_TYPE_2D, - 512, 512, 1, 0, PF_R8G8B8, TU_RENDERTARGET); - { - reflectCam = mSceneMgr->createCamera("ReflectCam"); - reflectCam->setNearClipDistance(mCamera->getNearClipDistance()); - reflectCam->setFarClipDistance(mCamera->getFarClipDistance()); - reflectCam->setAspectRatio( - (Real)mWindow->getViewport(0)->getActualWidth() / - (Real)mWindow->getViewport(0)->getActualHeight()); - - SceneNode* reflectCamNode = rootNode->createChildSceneNode(); - reflectCamNode->attachObject(reflectCam); - reflectCamNode->setPosition(mCameraNode->getPosition()); - reflectCamNode->setOrientation(mCameraNode->getOrientation()); - - Viewport *v = rttTex->getBuffer()->getRenderTarget()->addViewport( reflectCam ); - v->setClearEveryFrame( true ); - v->setBackgroundColour( ColourValue::Black ); - - MaterialPtr mat = MaterialManager::getSingleton().create("RttMat", - TRANSIENT_RESOURCE_GROUP); - mat->getTechnique(0)->getPass(0)->createTextureUnitState("RustedMetal.jpg"); - TextureUnitState* t = mat->getTechnique(0)->getPass(0)->createTextureUnitState("RttTex"); - // Blend with base texture - t->setColourOperationEx(LBX_BLEND_MANUAL, LBS_TEXTURE, LBS_CURRENT, ColourValue::White, - ColourValue::White, 0.25); - t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); - t->setProjectiveTexturing(true, reflectCam); - - // set up linked reflection - reflectCam->enableReflection(plane); - // Also clip - reflectCam->enableCustomNearClipPlane(plane); - } - - // Give the plane a texture - planeEnt->setMaterialName("RttMat"); - - - // point billboards - ParticleSystem* pSys2 = mSceneMgr->createParticleSystem("fountain1", - "Examples/Smoke"); - // Point the fountain at an angle - SceneNode* fNode = static_cast(rootNode->createChild()); - fNode->attachObject(pSys2); - - // oriented_self billboards - ParticleSystem* pSys3 = mSceneMgr->createParticleSystem("fountain2", - "Examples/PurpleFountain"); - // Point the fountain at an angle - fNode = rootNode->createChildSceneNode(); - fNode->translate(-200,-100,0); - fNode->rotate(Vector3::UNIT_Z, Degree(-20)); - fNode->attachObject(pSys3); - - - - // oriented_common billboards - ParticleSystem* pSys4 = mSceneMgr->createParticleSystem("rain", - "Examples/Rain"); - SceneNode* rNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - rNode->translate(0,1000,0); - rNode->attachObject(pSys4); - // Fast-forward the rain so it looks more natural - pSys4->fastForward(5); - - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_ReinitialiseEntityAlteredMesh::PlayPen_ReinitialiseEntityAlteredMesh() -{ - mInfo["Title"] = "PlayPen_ReinitialiseEntityAlteredMesh"; - mInfo["Description"] = "Tests updating an entity while rendering."; - addScreenshotFrame(100); - mTimer = 0.5f; -} -//---------------------------------------------------------------------------- - -bool PlayPen_ReinitialiseEntityAlteredMesh::frameStarted(const FrameEvent& evt) -{ - if(mTimer > 0.f) - { - mTimer -= evt.timeSinceLastFrame; - if(mTimer <= 0.f) - { - // Change the mesh, add a new submesh. - - // Load another mesh. - MeshPtr msh = MeshManager::getSingleton().load( - "ogrehead.mesh", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - for (unsigned short e = 0; e < msh->getNumSubMeshes(); ++e) - { - SubMesh* sm = msh->getSubMesh(e); - sm->clone("", mUpdate); - } - mTimer = -5.f; - } - } - - return true; -} -//---------------------------------------------------------------------------- - -void PlayPen_ReinitialiseEntityAlteredMesh::setupContent() -{ - // test whether an Entity picks up that Mesh has changed - // and therefore rebuild SubEntities - - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - - Light* l = mSceneMgr->createLight("l1"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(200, 300, 0))->attachObject(l); - - Ogre::MeshManager::getSingleton().load("knot.mesh", - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME)->clone("knot_REINIT.mesh"); - - Entity* pEnt = mSceneMgr->createEntity("testEnt", "knot_REINIT.mesh"); - mUpdate = pEnt->getMesh().get(); - - mSceneMgr->getRootSceneNode()->attachObject(pEnt); - - mCameraNode->setPosition(0,0,200); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_ReloadResources::PlayPen_ReloadResources() -{ - mInfo["Title"] = "PlayPen_ReloadResources"; - mInfo["Description"] = "Tests unloading and reloading resources."; - addScreenshotFrame(100); - mReloadTimer = 0.5f; -} -//---------------------------------------------------------------------------- - -bool PlayPen_ReloadResources::frameStarted(const FrameEvent& evt) -{ - if(mReloadTimer > 0.f) - { - mReloadTimer -= evt.timeSinceLastFrame; - - if(mReloadTimer <= 0.f) - { - // unload - Entity* e = mSceneMgr->getEntity("1"); - e->getParentSceneNode()->detachObject("1"); - mSceneMgr->destroyAllEntities(); - ResourceGroupManager::getSingleton().unloadResourceGroup("TestReload"); - - // reload - e = mSceneMgr->createEntity("1", "UniqueModel.MESH"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - - mReloadTimer = -5.f; - } - } - return true; -} -//---------------------------------------------------------------------------- - -void PlayPen_ReloadResources::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue::White); - - // get path to test resources - const Ogre::ResourceGroupManager::LocationList& ll = Ogre::ResourceGroupManager::getSingleton().getResourceLocationList("Tests"); - const Ogre::ResourceGroupManager::ResourceLocation* loc = &ll.front(); - Ogre::String testResourcePath = loc->archive->getName(); - - // add a new group - // Ogre::String meshFilePath = testResourcePath + "/TestReload"; - Ogre::String meshFilePath = testResourcePath + "/Model2"; - Ogre::ResourceGroupManager& resMgr = Ogre::ResourceGroupManager::getSingleton(); - resMgr.createResourceGroup("TestReload", false); - resMgr.addResourceLocation(meshFilePath, "FileSystem", "TestReload"); - resMgr.initialiseResourceGroup("TestReload"); - - MeshManager& mmgr = MeshManager::getSingleton(); - mmgr.load("UniqueModel.MESH", "TestReload"); - - Entity* e = mSceneMgr->createEntity("1", "UniqueModel.MESH"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - - mCameraNode->setPosition(0,0,200); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_RibbonTrail::PlayPen_RibbonTrail() -{ - mInfo["Title"] = "PlayPen_RibbonTrail"; - mInfo["Description"] = "Tests ribbon trail effect."; - addScreenshotFrame(150); -} -//---------------------------------------------------------------------------- - -void PlayPen_RibbonTrail::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - Vector3 dir(-1, -1, 0.5); - dir.normalise(); - OrientedLightPtr l = mSceneMgr->createLight("light1"); - l->setType(Light::LT_DIRECTIONAL); - l->setDirection(dir); - - NameValuePairList pairList; - pairList["numberOfChains"] = "2"; - pairList["maxElements"] = "80"; - RibbonTrail* trail = static_cast( - mSceneMgr->createMovableObject("1", "RibbonTrail", &pairList)); - trail->setMaterialName("Examples/LightRibbonTrail"); - trail->setTrailLength(400); - //mRibbonTrail = trail; - - - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(trail); - - // Create 3 nodes for trail to follow - SceneNode* animNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - animNode->setPosition(0,20,0); - Animation* anim = mSceneMgr->createAnimation("an1", 10); - anim->setInterpolationMode(Animation::IM_SPLINE); - NodeAnimationTrack* track = anim->createNodeTrack(1, animNode); - TransformKeyFrame* kf = track->createNodeKeyFrame(0); - kf->setTranslate(Vector3::ZERO); - kf = track->createNodeKeyFrame(2); - kf->setTranslate(Vector3(100, 0, 0)); - kf = track->createNodeKeyFrame(4); - kf->setTranslate(Vector3(200, 0, 300)); - kf = track->createNodeKeyFrame(6); - kf->setTranslate(Vector3(0, 20, 500)); - kf = track->createNodeKeyFrame(8); - kf->setTranslate(Vector3(-100, 10, 100)); - kf = track->createNodeKeyFrame(10); - kf->setTranslate(Vector3::ZERO); - - //testremoveNode = animNode; - - AnimationState* animState = mSceneMgr->createAnimationState("an1"); - animState->setEnabled(true); - mAnimStateList.push_back(animState); - - trail->addNode(animNode); - trail->setInitialColour(0, 1.0, 0.8, 0); - trail->setColourChange(0, 0.5, 0.5, 0.5, 0.5); - trail->setInitialWidth(0, 5); - - // Add light - Light* l2 = mSceneMgr->createLight("l2"); - l2->setDiffuseColour(trail->getInitialColour(0)); - animNode->attachObject(l2); - - // Add billboard - BillboardSet* bbs = mSceneMgr->createBillboardSet("bb", 1); - bbs->createBillboard(Vector3::ZERO, trail->getInitialColour(0)); - bbs->setMaterialName("Examples/Flare"); - animNode->attachObject(bbs); - - animNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - animNode->setPosition(-50,10,0); - anim = mSceneMgr->createAnimation("an2", 10); - anim->setInterpolationMode(Animation::IM_SPLINE); - track = anim->createNodeTrack(1, animNode); - kf = track->createNodeKeyFrame(0); - kf->setTranslate(Vector3::ZERO); - kf = track->createNodeKeyFrame(2); - kf->setTranslate(Vector3(-100, 150, -30)); - kf = track->createNodeKeyFrame(4); - kf->setTranslate(Vector3(-200, 0, 40)); - kf = track->createNodeKeyFrame(6); - kf->setTranslate(Vector3(0, -150, 70)); - kf = track->createNodeKeyFrame(8); - kf->setTranslate(Vector3(50, 0, 30)); - kf = track->createNodeKeyFrame(10); - kf->setTranslate(Vector3::ZERO); - - animState = mSceneMgr->createAnimationState("an2"); - animState->setEnabled(true); - mAnimStateList.push_back(animState); - - trail->addNode(animNode); - trail->setInitialColour(1, 0.0, 1.0, 0.4); - trail->setColourChange(1, 0.5, 0.5, 0.5, 0.5); - trail->setInitialWidth(1, 5); - - - // Add light - l2 = mSceneMgr->createLight("l3"); - l2->setDiffuseColour(trail->getInitialColour(1)); - animNode->attachObject(l2); - - // Add billboard - bbs = mSceneMgr->createBillboardSet("bb2", 1); - bbs->createBillboard(Vector3::ZERO, trail->getInitialColour(1)); - bbs->setMaterialName("Examples/Flare"); - animNode->attachObject(bbs); - - - mCameraNode->setPosition(0,0,500); - //mSceneMgr->showBoundingBoxes(true); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_SerialisedColour::PlayPen_SerialisedColour() -{ - mInfo["Title"] = "PlayPen_SerialisedColour"; - mInfo["Description"] = "Tests serializing mesh color."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_SerialisedColour::setupContent() -{ - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - Vector3 dir(-1, -1, 0.5); - dir.normalise(); - OrientedLightPtr l = mSceneMgr->createLight("light1"); - l->setType(Light::LT_DIRECTIONAL); - l->setDirection(dir); - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 100; - MeshManager::getSingleton().createPlane( - "Myplane", TRANSIENT_RESOURCE_GROUP, plane, - 1500, 1500, 10, 10, true, 1, 5, 5, Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("2 - Default"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - ManualObject* man = mSceneMgr->createManualObject("test"); - - MaterialPtr mat = MaterialManager::getSingleton().create( - "AmbientVertexColourTracking", TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setVertexColourTracking(TVC_AMBIENT); - p->setLightingEnabled(false); - - man->begin("AmbientVertexColourTracking"); - //TODO Define a 40x40 plane, non-indexed - - // Define a 40x40 plane, indexed - man->position(-20, 20, 20); - man->colour(1, 0, 0); - - man->position(-20, -20, 20); - man->colour(1, 0, 0); - - man->position(20, -20, 20); - man->colour(1, 0, 0); - - man->position(20, 20, 20); - man->colour(1, 0, 0); - - man->quad(0, 1, 2, 3); - man->end(); - - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(man); - - MeshPtr mesh = man->convertToMesh("colourtest.mesh"); - MeshSerializer ms; - ms.exportMesh(mesh.get(), "colourtest.mesh"); - - Entity* c = mSceneMgr->createEntity("1", "colourtest.mesh"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(c); - - mCameraNode->setPosition(0,0,120); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_ShadowLod::PlayPen_ShadowLod() -{ - mInfo["Title"] = "PlayPen_ShadowLod"; - mInfo["Description"] = "Tests whether LOD is based on shadow cam or main cam."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_ShadowLod::cleanupContent() -{ - clearDebugTextureOverlays(); -} -//---------------------------------------------------------------------------- - -void PlayPen_ShadowLod::setupContent() -{ - SceneNode* mTestNode[10]; - - // Test that LOD is based on main camera, not shadow camera - - mSceneMgr->setShadowTextureSize(1024); - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE); - - //FocusedShadowCameraSetup* lispsmSetup = new FocusedShadowCameraSetup(); - //LiSPSMShadowCameraSetup* lispsmSetup = new LiSPSMShadowCameraSetup(); - //lispsmSetup->setOptimalAdjustFactor(1.5); - //mSceneMgr->setShadowCameraSetup(ShadowCameraSetupPtr(lispsmSetup)); - - mSceneMgr->setShadowColour(ColourValue(0.35, 0.35, 0.35)); - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); - - // Directional test - if (false) - { - OrientedLightPtr mLight = mSceneMgr->createLight("MainLight"); - mLight->setType(Light::LT_DIRECTIONAL); - Vector3 vec(-1,-1,0); - vec.normalise(); - mLight->setDirection(vec); - } - // Spotlight test - else - { - Light* mLight = mSceneMgr->createLight("MainLight"); - mLight->setType(Light::LT_SPOTLIGHT); - mLight->setAttenuation(10000, 1, 0, 0); - mLight->setDiffuseColour(1.0, 1.0, 0.8); - mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mTestNode[0]->setPosition(400,300,0); - mTestNode[0]->lookAt(Vector3(0,0,0), Node::TS_WORLD); - mTestNode[0]->attachObject(mLight); - } - - mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - - Entity* pEnt; - pEnt = mSceneMgr->createEntity( "1", "knot.mesh" ); - // rendering distance should also be based on main cam - //pEnt->setRenderingDistance(100); - //pEnt->setMaterialName("2 - Default"); - mTestNode[1]->attachObject( pEnt ); - //mTestNode[1]->translate(0,-100,0); - /* - pEnt = mSceneMgr->createEntity( "3", "knot.mesh" ); - mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-200, 0, -200)); - mTestNode[2]->attachObject( pEnt ); - - - createRandomEntityClones(pEnt, 20, Vector3(-1000,0,-1000), Vector3(1000,0,1000)); - - - // Transparent object (can force cast shadows) - pEnt = mSceneMgr->createEntity( "3.5", "knot.mesh" ); - MaterialPtr tmat = MaterialManager::getSingleton().create("TestAlphaTransparency", - TRANSIENT_RESOURCE_GROUP); - tmat->setTransparencyCastsShadows(true); - Pass* tpass = tmat->getTechnique(0)->getPass(0); - tpass->setAlphaRejectSettings(CMPF_GREATER, 150); - tpass->setSceneBlending(SBT_TRANSPARENT_ALPHA); - tpass->createTextureUnitState("gras_02.png"); - tpass->setCullingMode(CULL_NONE); - - pEnt->setMaterialName("TestAlphaTransparency"); - mTestNode[3] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(350, 0, -200)); - mTestNode[3]->attachObject( pEnt ); - - MeshPtr msh = MeshManager::getSingleton().load("knot.mesh", - TRANSIENT_RESOURCE_GROUP); - msh->buildTangentVectors(VES_TANGENT, 0, 0); - pEnt = mSceneMgr->createEntity( "4", "knot.mesh" ); - //pEnt->setMaterialName("Examples/BumpMapping/MultiLightSpecular"); - mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 0, 200)); - mTestNode[2]->attachObject( pEnt ); - - mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); - */ - - - MovablePlane movablePlane(Vector3::UNIT_Y, 100); - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, movablePlane, - 2500,2500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt; - pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - if (SHADOWTYPE_TEXTURE_MODULATIVE & SHADOWDETAILTYPE_INTEGRATED) - { - pPlaneEnt->setMaterialName("Examples/Plane/IntegratedShadows"); - } - else - { - pPlaneEnt->setMaterialName("2 - Default"); - } - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - addTextureShadowDebugOverlay(1, mSceneMgr); - - - /* - ParticleSystem* pSys2 = mSceneMgr->createParticleSystem("smoke", - "Examples/Smoke"); - mTestNode[4] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-300, -100, 200)); - mTestNode[4]->attachObject(pSys2); - */ - - mCameraNode->setPosition(0, 1000, 500); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); - mCamera->setFarClipDistance(10000); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_SkeletalAnimation::PlayPen_SkeletalAnimation() -{ - mInfo["Title"] = "PlayPen_SkeletalAnimation"; - mInfo["Description"] = "Tests skeletal animation."; - addScreenshotFrame(100); -} -//---------------------------------------------------------------------------- - -void PlayPen_SkeletalAnimation::setupContent() -{ - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - //mWindow->getViewport(0)->setBackgroundColour(ColourValue::White); - - - - Entity *ent = mSceneMgr->createEntity("robot", "robot.mesh"); - //ent->setDisplaySkeleton(true); - // Uncomment the below to test software skinning - ent->setMaterialName("Examples/Rocky"); - // Add entity to the scene node - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); - Ogre::AnimationState* mAnimState = ent->getAnimationState("Walk"); - mAnimState->setEnabled(true); - - // Give it a little ambience with lights - Light* l; - l = mSceneMgr->createLight("BlueLight"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-200,-80,-100))->attachObject(l); - l->setDiffuseColour(0.5, 0.5, 1.0); - - l = mSceneMgr->createLight("GreenLight"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,0,-100))->attachObject(l); - l->setDiffuseColour(0.5, 1.0, 0.5); - - // Position the camera - mCameraNode->setPosition(200,50,0); - mCameraNode->lookAt(Vector3(0, 50, 0), Node::TS_PARENT); - - // Report whether hardware skinning is enabled or not - /*Technique* t = ent->getSubEntity(0)->getTechnique(); - Pass* p = t->getPass(0); - OverlayElement* guiDbg = OverlayManager::getSingleton().getOverlayElement("Core/DebugText"); - if (p->hasVertexProgram() && - p->getVertexProgram()->isSkeletalAnimationIncluded()) - { - guiDbg->setCaption("Hardware skinning is enabled"); - } - else - { - guiDbg->setCaption("Software skinning is enabled"); - }*/ - - mAnimStateList.push_back(mAnimState); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_SkeletonAnimationOptimise::PlayPen_SkeletonAnimationOptimise() -{ - mInfo["Title"] = "PlayPen_SkeletonAnimationOptimise"; - mInfo["Description"] = "Tests skeletal animation with hardware and software."; - addScreenshotFrame(100); -} -//---------------------------------------------------------------------------- - -void PlayPen_SkeletonAnimationOptimise::setupContent() -{ - SceneNode* mTestNode[5]; - mSceneMgr->setShadowTextureSize(512); - mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_MODULATIVE); - mSceneMgr->setShadowFarDistance(1500); - mSceneMgr->setShadowColour(ColourValue(0.35, 0.35, 0.35)); - //mSceneMgr->setShadowFarDistance(800); - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); - - Light* mLight = mSceneMgr->createLight("MainLight"); - - /*/ - // Directional test - mLight->setType(Light::LT_DIRECTIONAL); - Vector3 vec(-1,-1,0); - vec.normalise(); - mLight->setDirection(vec); - /*/ - // Point test - mLight->setType(Light::LT_POINT); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 200, 0))->attachObject(mLight); - //*/ - - Entity* pEnt; - - // Hardware animation - pEnt = mSceneMgr->createEntity( "1", "robot.mesh" ); - AnimationState* a = pEnt->getAnimationState("Walk"); - a->setEnabled(true); - mAnimStateList.push_back(a); - mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mTestNode[0]->attachObject( pEnt ); - mTestNode[0]->translate(+100,-100,0); - - // Software animation - pEnt = mSceneMgr->createEntity( "2", "robot.mesh" ); - pEnt->setMaterialName("BaseWhite"); - a = pEnt->getAnimationState("Walk"); - a->setEnabled(true); - mAnimStateList.push_back(a); - - mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mTestNode[1]->attachObject( pEnt ); - mTestNode[1]->translate(-100,-100,0); - - - Plane plane(Vector3::UNIT_Y, -100); - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt; - pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("2 - Default"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - mCameraNode->setPosition(0,0,300); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_SpotlightViewProj::PlayPen_SpotlightViewProj() -{ - mInfo["Title"] = "PlayPen_SpotlightViewProj"; - mInfo["Description"] = "Tests spotlight camera projection."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_SpotlightViewProj::setupContent() -{ - SceneNode* mTestNode[10]; - bool worldViewProj = true; - // Define programs that use spotlight projection - - String vpStr; - vpStr = - "void vp(float4 position : POSITION,\n" - "out float4 oPosition : POSITION,\n" - "out float4 oUV : TEXCOORD0,\n"; - if (!worldViewProj) - { - vpStr += "uniform float4x4 world,\n" - "uniform float4x4 spotlightViewProj,\n"; - } - else - { - vpStr += "uniform float4x4 spotlightWorldViewProj,\n"; - } - vpStr += "uniform float4x4 worldViewProj)\n" - "{\n" - " oPosition = mul(worldViewProj, position);\n"; - if (worldViewProj) - { - vpStr += " oUV = mul(spotlightWorldViewProj, position);\n"; - } - else - { - vpStr += " float4 worldPos = mul(world, position);\n" - " oUV = mul(spotlightViewProj, worldPos);\n"; - } - vpStr += "}\n"; - - String fpStr = - "void fp(\n" - "float4 uv : TEXCOORD0,\n" - "uniform sampler2D tex : register(s0),\n" - "out float4 oColor : COLOR)\n" - "{\n" - " uv = uv / uv.w;\n" - " oColor = tex2D(tex, uv.xy);\n" - "}\n"; - - HighLevelGpuProgramPtr vp = HighLevelGpuProgramManager::getSingleton() - .createProgram("testvp", - TRANSIENT_RESOURCE_GROUP, - "cg", GPT_VERTEX_PROGRAM); - vp->setSource(vpStr); - vp->setParameter("profiles", "vs_1_1 arbvp1 glslv"); - vp->setParameter("entry_point", "vp"); - vp->load(); - - HighLevelGpuProgramPtr fp = HighLevelGpuProgramManager::getSingleton() - .createProgram("testfp", - TRANSIENT_RESOURCE_GROUP, - "cg", GPT_FRAGMENT_PROGRAM); - fp->setSource(fpStr); - fp->setParameter("profiles", "ps_2_0 arbfp1 glslf"); - fp->setParameter("entry_point", "fp"); - fp->load(); - - MaterialPtr mat = MaterialManager::getSingleton().create("TestSpotlightProj", - TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setVertexProgram("testvp"); - p->getVertexProgramParameters()->setNamedAutoConstant( - "worldViewProj", GpuProgramParameters::ACT_WORLDVIEWPROJ_MATRIX); - - if (worldViewProj) - { - p->getVertexProgramParameters()->setNamedAutoConstant( - "spotlightWorldViewProj", GpuProgramParameters::ACT_SPOTLIGHT_WORLDVIEWPROJ_MATRIX); - } - else - { - p->getVertexProgramParameters()->setNamedAutoConstant( - "world", GpuProgramParameters::ACT_WORLD_MATRIX); - p->getVertexProgramParameters()->setNamedAutoConstant( - "spotlightViewProj", GpuProgramParameters::ACT_SPOTLIGHT_VIEWPROJ_MATRIX); - } - p->setFragmentProgram("testfp"); - p->createTextureUnitState("ogrelogo.png"); - - Entity* pEnt; - - // Define a plane mesh, use the above material - Plane plane; - plane.normal = Vector3::UNIT_Z; - plane.d = 200; - MeshManager::getSingleton().createPlane("WallPlane", - TRANSIENT_RESOURCE_GROUP, - plane,1500,1500,100,100,true,1,5,5,Vector3::UNIT_Y); - pEnt = mSceneMgr->createEntity( "5", "WallPlane" ); - pEnt->setMaterialName(mat->getName()); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pEnt); - - - mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - mTestNode[0]->translate(0, 0, 750); - - Light* spot = mSceneMgr->createLight("l1"); - spot->setType(Light::LT_SPOTLIGHT); - - mTestNode[0]->attachObject(spot); - - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_SRGBtexture::PlayPen_SRGBtexture() -{ - mInfo["Title"] = "PlayPen_SRGBtexture"; - mInfo["Description"] = "Tests sRGB textures."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_SRGBtexture::setupContent() -{ - // NOTE: enable flag only turns on SRGB for texture sampling, you may - // need to configure the window for the reverse conversion for consistency! - MaterialPtr mat = MaterialManager::getSingleton().create("testsrgb", - TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - p->setCullingMode(CULL_NONE); - TextureUnitState* t = p->createTextureUnitState("ogrelogo.png"); - t->setHardwareGammaEnabled(true); - Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); - e->setMaterialName(mat->getName()); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); - - mCameraNode->setPosition(0,0,300); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_StaticGeometry::PlayPen_StaticGeometry() -{ - mInfo["Title"] = "PlayPen_StaticGeometry"; - mInfo["Description"] = "Tests static geometry."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_StaticGeometry::setupContent() -{ - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0, 0, 0)); - mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_MODULATIVE); - - // Create a point light - Light* l = mSceneMgr->createLight("MainLight"); - l->setDiffuseColour(0.4, 0.4, 0.4); - - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 600, 0))->attachObject(l); - l->setAttenuation(10000, 1, 0, 0); - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 0; - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 4500,4500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("Examples/GrassFloor"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - MeshPtr msh = MeshManager::getSingleton().load("ogrehead.mesh", ASSETS_RESOURCE_GROUP); - msh->buildTangentVectors(); - - Entity* e = mSceneMgr->createEntity("1", "ogrehead.mesh"); - e->setMaterialName("BaseWhite"); - - StaticGeometry* s = mSceneMgr->createStaticGeometry("bing"); - s->setCastShadows(true); - s->setRegionDimensions(Vector3(500,500,500)); - - Vector3 min(-500,60,-500); - Vector3 max(500,60,500); - for (int i = 0; i < 10; ++i) - { - Vector3 pos; - pos.x = Math::RangeRandom(min.x, max.x); - pos.y = Math::RangeRandom(min.y, max.y); - pos.z = Math::RangeRandom(min.z, max.z); - - s->addEntity(e, pos); - Entity* e2 = e->clone("clone" + StringConverter::toString(i)); - mSceneMgr->getRootSceneNode()->createChildSceneNode(pos+Vector3(0,60,0))->attachObject(e2); - - } - - s->build(); - - mCameraNode->setPosition(0,400,1200); - mCameraNode->setDirection(0,-0.3f,-1.2f); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- -#ifdef OGRE_BUILD_COMPONENT_MESHLODGENERATOR -PlayPen_StaticGeometryWithLOD::PlayPen_StaticGeometryWithLOD() -{ - mInfo["Title"] = "PlayPen_StaticGeometryWithLOD"; - mInfo["Description"] = "Tests static geometry with LODs."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_StaticGeometryWithLOD::setupContent() -{ - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0, 0, 0)); - - // Create a point light - Light* l = mSceneMgr->createLight("MainLight"); - l->setDiffuseColour(0.4, 0.4, 0.4); - l->setSpecularColour(ColourValue::White); - - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 600, 0))->attachObject(l); - l->setAttenuation(10000, 1, 0, 0); - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 0; - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 4500,4500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("Examples/GrassFloor"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - MeshPtr msh = MeshManager::getSingleton().load("knot.mesh", ASSETS_RESOURCE_GROUP); - LodConfig lodConfig(msh); - lodConfig.createGeneratedLodLevel(1000, 1400, LodLevel::VRM_CONSTANT); - MeshLodGenerator().generateLodLevels(lodConfig); - - Entity* e = mSceneMgr->createEntity("1", msh->getName()); - - StaticGeometry* s = mSceneMgr->createStaticGeometry("bing"); - s->setCastShadows(true); - s->setRegionDimensions(Vector3(500,500,500)); - - Vector3 min(-500,100,-500); - Vector3 max(500,100,500); - for (int i = 0; i < 10; ++i) - { - Vector3 pos; - pos.x = Math::RangeRandom(min.x, max.x); - pos.y = Math::RangeRandom(min.y, max.y); - pos.z = Math::RangeRandom(min.z, max.z); - - s->addEntity(e, pos); - } - - s->build(); - msh->freeEdgeList(); - msh->_setLodInfo(1); - mCameraNode->setPosition(0,400,1200); - mCameraNode->setDirection(0,-0.3f,-1.2f); -} -#endif -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -// render queues -#define RENDER_QUEUE_OUTLINE_GLOW_OBJECTS RENDER_QUEUE_MAIN + 1 -#define RENDER_QUEUE_OUTLINE_GLOW_GLOWS RENDER_QUEUE_MAIN + 2 -#define RENDER_QUEUE_FULL_GLOW_ALPHA_GLOW RENDER_QUEUE_MAIN + 3 -#define RENDER_QUEUE_FULL_GLOW_GLOW RENDER_QUEUE_MAIN + 4 -#define LAST_STENCIL_OP_RENDER_QUEUE RENDER_QUEUE_FULL_GLOW_GLOW - -// stencil values -#define STENCIL_VALUE_FOR_OUTLINE_GLOW 1 -#define STENCIL_VALUE_FOR_FULL_GLOW 2 -#define STENCIL_FULL_MASK 0xFFFFFFFF - -// a Render queue listener to change the stencil mode -class StencilOpQueueListener : public Ogre::RenderQueueListener -{ -public: - void renderQueueStarted(Ogre::uint8 queueGroupId, const Ogre::String& invocation, bool& skipThisInvocation) override - { - StencilState stencil; - stencil.enabled = true; - stencil.compareOp = CMPF_ALWAYS_PASS; - stencil.referenceValue = STENCIL_VALUE_FOR_OUTLINE_GLOW; - stencil.depthStencilPassOp = SOP_REPLACE; - - RenderSystem* rendersys = Root::getSingleton().getRenderSystem(); - - switch (queueGroupId) - { - default: - return; - case RENDER_QUEUE_OUTLINE_GLOW_OBJECTS: // outline glow object - rendersys->clearFrameBuffer(Ogre::FBT_STENCIL); - break; - case RENDER_QUEUE_OUTLINE_GLOW_GLOWS: // outline glow - stencil.compareOp = CMPF_NOT_EQUAL; - break; - case RENDER_QUEUE_FULL_GLOW_ALPHA_GLOW: // full glow - alpha glow - stencil.referenceValue = STENCIL_VALUE_FOR_FULL_GLOW; - break; - case RENDER_QUEUE_FULL_GLOW_GLOW: // full glow - glow - stencil.compareOp = CMPF_EQUAL; - stencil.referenceValue = STENCIL_VALUE_FOR_FULL_GLOW; - break; - } - - rendersys->setStencilState(stencil); - } - - void renderQueueEnded(Ogre::uint8 queueGroupId, const Ogre::String& invocation, bool& repeatThisInvocation) override - { - if ( queueGroupId == LAST_STENCIL_OP_RENDER_QUEUE ) - { - Root::getSingleton().getRenderSystem()->setStencilState(StencilState()); - } - } - -}; -//--------------------------------------------------------------------------- - -PlayPen_StencilGlow::PlayPen_StencilGlow() - :mStencilListener(0) -{ - mInfo["Title"] = "PlayPen_StencilGlow"; - mInfo["Description"] = "Tests stencil glow effect."; - addScreenshotFrame(100); -} -//--------------------------------------------------------------------------- - -PlayPen_StencilGlow::~PlayPen_StencilGlow() -{ - if(mStencilListener) - delete mStencilListener; -} -//--------------------------------------------------------------------------- - -void PlayPen_StencilGlow::setupContent(void) -{ - // test media - Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); - - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - - // Create a point light - Light* l = mSceneMgr->createLight("MainLight"); - // Accept default settings: point light, white diffuse, just set position - // NB I could attach the light to a SceneNode if I wanted it to move automatically with - // other objects, but I don't - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(20,80,50))->attachObject(l); - - - // outline glow entity - Entity *outlineGlowEntity = mSceneMgr->createEntity("outlineGlow", "ogrehead.mesh"); - outlineGlowEntity->setRenderQueueGroup(RENDER_QUEUE_OUTLINE_GLOW_OBJECTS); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(outlineGlowEntity); - - - // outline glow entity actual glow - Ogre::Entity* actualOutlineGlowEntity = outlineGlowEntity->clone(outlineGlowEntity->getName() + "_glow"); - actualOutlineGlowEntity->setRenderQueueGroup(RENDER_QUEUE_OUTLINE_GLOW_GLOWS); - actualOutlineGlowEntity->setMaterialName("glow"); - Ogre::SceneNode* actualOutlineGlowNode = outlineGlowEntity->getParentSceneNode()->createChildSceneNode("outlineGlowNode"); - actualOutlineGlowNode->attachObject(actualOutlineGlowEntity); - - - // normal entity - Entity *normalOgreEntity = mSceneMgr->createEntity("normalOgreEntity", "ogrehead.mesh"); - Ogre::SceneNode* normalOgreNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - normalOgreNode->attachObject(normalOgreEntity); - normalOgreNode->setPosition(80, 0, 0); - - - - // full glow entity - Entity *fullGlowEntity = mSceneMgr->createEntity("fullGlowEntity", "ogrehead.mesh"); - Ogre::SceneNode* fullGlowNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - fullGlowNode->attachObject(fullGlowEntity); - fullGlowNode->setPosition(-80, 0, 0); - - // full glow alpha glow - Ogre::Entity* alphaFullGlowEntity = fullGlowEntity->clone(fullGlowEntity->getName() + "_alphaGlow"); - alphaFullGlowEntity->setRenderQueueGroup(RENDER_QUEUE_FULL_GLOW_ALPHA_GLOW); - alphaFullGlowEntity->setMaterialName("alpha_glow"); - Ogre::SceneNode* alphaFullGlowNode = fullGlowEntity->getParentSceneNode()->createChildSceneNode("fullGlowAlphaNode"); - alphaFullGlowNode->attachObject(alphaFullGlowEntity); - - // full glow alpha glow - Ogre::Entity* glowFullGlowEntity = fullGlowEntity->clone(fullGlowEntity->getName() + "_glow"); - glowFullGlowEntity->setRenderQueueGroup(RENDER_QUEUE_FULL_GLOW_GLOW); - glowFullGlowEntity->setMaterialName("no_depth_check_glow"); - Ogre::SceneNode* glowFullGlowNode = fullGlowEntity->getParentSceneNode()->createChildSceneNode("fullGlowGlowNode"); - glowFullGlowNode->attachObject(glowFullGlowEntity); - - mCameraNode->setPosition(0,0,200); - mCameraNode->setDirection(0,0,-1); - - mStencilListener = new StencilOpQueueListener(); - mSceneMgr->addRenderQueueListener(mStencilListener); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_StencilShadows::PlayPen_StencilShadows() -{ - mInfo["Title"] = "PlayPen_StencilShadows"; - mInfo["Description"] = "Tests stencil shadows."; - addScreenshotFrame(20); -} -//---------------------------------------------------------------------------- - -void PlayPen_StencilShadows::setupContent() -{ - SceneNode* mTestNode[10]; - - mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_MODULATIVE); - //mSceneMgr->setShowDebugShadows(true); - mSceneMgr->setShadowDirectionalLightExtrusionDistance(1000); - //mSceneMgr->setShadowColour(ColourValue(0.4, 0.25, 0.25)); - - //mSceneMgr->setShadowFarDistance(800); - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.0, 0.0, 0.0)); - - // Point light - //if(pointLight) - { - Light* mLight = mSceneMgr->createLight("MainLight"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-400, 400, -300))->attachObject(mLight); - mLight->setDiffuseColour(0.9, 0.9, 1); - mLight->setSpecularColour(0.9, 0.9, 1); - mLight->setAttenuation(6000, 1, 0.001, 0); - } - // Directional light - //if (directionalLight) - { - OrientedLightPtr mLight = mSceneMgr->createLight("Light2"); - Vector3 dir(-1, -1, 0); - dir.normalise(); - mLight->setType(Light::LT_DIRECTIONAL); - mLight->setDirection(dir); - mLight->setDiffuseColour(1, 1, 0.8); - mLight->setSpecularColour(1, 1, 1); - } - - mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - // Hardware skin - Entity* pEnt; - pEnt = mSceneMgr->createEntity( "1", "robot.mesh" ); - AnimationState* anim = pEnt->getAnimationState("Walk"); - anim->setEnabled(true); - mAnimStateList.push_back(anim); - mTestNode[0]->attachObject( pEnt ); - - // Software skin - pEnt = mSceneMgr->createEntity( "12", "robot.mesh" ); - anim = pEnt->getAnimationState("Walk"); - anim->setEnabled(true); - mAnimStateList.push_back(anim); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 0, 0))->attachObject(pEnt); - pEnt->setMaterialName("Examples/Rocky"); - - // test object - //pEnt = mSceneMgr->createEntity("tst", "building.mesh"); - //mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(300, 0, 0))->attachObject(pEnt); - - - // Does not receive shadows - pEnt = mSceneMgr->createEntity( "3", "knot.mesh" ); - pEnt->setMaterialName("Examples/EnvMappedRustySteel"); - MaterialPtr mat2 = MaterialManager::getSingleton().getByName("Examples/SphereMappedRustySteel"); - mat2->setReceiveShadows(false); - mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-200, 0, -200)); - mTestNode[2]->attachObject( pEnt ); - - // Transparent object - pEnt = mSceneMgr->createEntity( "3.5", "knot.mesh" ); - pEnt->setMaterialName("Examples/TransparentTest"); - MaterialPtr mat3 = MaterialManager::getSingleton().getByName("Examples/TransparentTest"); - pEnt->setCastShadows(false); - mTestNode[3] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(350, 0, -200)); - mTestNode[3]->attachObject( pEnt ); - - // User test - /* - pEnt = mSceneMgr->createEntity( "3.6", "ogre_male_endCaps.mesh" ); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 0, 100))->attachObject( pEnt ); - */ - - MeshPtr msh = MeshManager::getSingleton().load("knot.mesh", ASSETS_RESOURCE_GROUP); - msh->buildTangentVectors(); - pEnt = mSceneMgr->createEntity( "4", "knot.mesh" ); - pEnt->setMaterialName("Examples/BumpMapping/MultiLightSpecular"); - mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 0, 200)); - mTestNode[2]->attachObject( pEnt ); - - // controller based material - pEnt = mSceneMgr->createEntity( "432", "knot.mesh" ); - pEnt->setMaterialName("Examples/TextureEffect2"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 200, 200))->attachObject( pEnt ); - - ParticleSystem* pSys2 = mSceneMgr->createParticleSystem("smoke", - "Examples/Smoke"); - mTestNode[4] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-300, -100, 200)); - mTestNode[4]->attachObject(pSys2); - - - mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); - - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 100; - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("2 - Default"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - //mCameraNode->setPosition(180, 34, 223); - //mCamera->setOrientation(Quaternion(0.7265, -0.2064, 0.6304, 0.1791)); - - mCameraNode->setPosition(0,0,400); - mCameraNode->setDirection(0,0,-1); - - // Create a render texture - /* TexturePtr rtt = TextureManager::getSingleton().createManual("rtt0", - TRANSIENT_RESOURCE_GROUP, - TEX_TYPE_2D, 512, 512, 0, PF_R8G8B8, TU_RENDERTARGET); - rtt->getBuffer()->getRenderTarget()->addViewport(mCamera); - // Create an overlay showing the rtt - MaterialPtr debugMat = MaterialManager::getSingleton().create( - "DebugRTT", TRANSIENT_RESOURCE_GROUP); - debugMat->getTechnique(0)->getPass(0)->setLightingEnabled(false); - TextureUnitState *t = debugMat->getTechnique(0)->getPass(0)->createTextureUnitState("rtt0"); - t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); - OverlayContainer* debugPanel = (OverlayContainer*) - (OverlayManager::getSingleton().createOverlayElement("Panel", "Ogre/DebugShadowPanel")); - debugPanel->_setPosition(0.6, 0); - debugPanel->_setDimensions(0.4, 0.6); - debugPanel->setMaterialName("DebugRTT"); - Overlay* debugOverlay = OverlayManager::getSingleton().getByName("Core/DebugOverlay"); - debugOverlay->add2D(debugPanel);*/ - - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_StencilShadowsMixedOpSubMeshes::PlayPen_StencilShadowsMixedOpSubMeshes() -{ - mInfo["Title"] = "PlayPen_StencilShadowsMixedOpSubMeshes"; - mInfo["Description"] = "Tests mixed operation submeshes."; - addScreenshotFrame(20); -} -//---------------------------------------------------------------------------- - -void PlayPen_StencilShadowsMixedOpSubMeshes::setupContent() -{ - mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_MODULATIVE); - //mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_ADDITIVE); - //mSceneMgr->setShowDebugShadows(true); - mSceneMgr->setShadowDirectionalLightExtrusionDistance(1000); - - //mSceneMgr->setShadowFarDistance(800); - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.0, 0.0, 0.0)); - - Light* mLight; - - // Point light - //if(pointLight) - //{ - mLight = mSceneMgr->createLight("MainLight"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-400,400,-300))->attachObject(mLight); - mLight->setDiffuseColour(0.9, 0.9, 1); - mLight->setSpecularColour(0.9, 0.9, 1); - mLight->setAttenuation(6000,1,0.001,0); - //} - // Directional light - //if (directionalLight) - //{ - /*mLight = mSceneMgr->createLight("Light2"); - Vector3 dir(-1,-1,0); - dir.normalise(); - mLight->setType(Light::LT_DIRECTIONAL); - mLight->setDirection(dir); - mLight->setDiffuseColour(1, 1, 0.8); - mLight->setSpecularColour(1, 1, 1);*/ - //} - - mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); - - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 100; - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("2 - Default"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - //mCameraNode->setPosition(180, 34, 223); - //mCamera->setOrientation(Quaternion(0.7265, -0.2064, 0.6304, 0.1791)); - - - ManualObject* man = mSceneMgr->createManualObject("testMO_"); - man->begin("2 - Default"); - man->position(0, 200, 0); - man->position(0, 50, 100); - man->position(100, 50, -100); - man->position(-100, 50, -100); - man->triangle(0, 1, 2); - man->triangle(0, 2, 3); - man->triangle(0, 3, 1); - man->end(); - man->begin("2 - Default", RenderOperation::OT_LINE_STRIP); - man->position(0, 200, 0); - man->position(50, 250, 0); - man->position(200, 300, 0); - man->index(0); - man->index(1); - man->index(2); - man->end(); - MeshPtr msh = man->convertToMesh("testMO.mesh_2"); - - Entity* e = mSceneMgr->createEntity("34", "testMO.mesh_2"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); - - mCameraNode->setPosition(100,320,600); - mCameraNode->lookAt(Vector3(0, 120, 0), Node::TS_PARENT); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_SubEntityVisibility::PlayPen_SubEntityVisibility() -{ - mInfo["Title"] = "PlayPen_SubEntityVisibility"; - mInfo["Description"] = "Tests sub entity visibility settings."; - addScreenshotFrame(250); -} -//---------------------------------------------------------------------------- - -void PlayPen_SubEntityVisibility::setupContent() -{ - SceneNode* mTestNode[5]; - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - - // Create a point light - OrientedLightPtr l = mSceneMgr->createLight("MainLight"); - l->setType(Light::LT_DIRECTIONAL); - l->setDirection(-Vector3::UNIT_Y); - - mTestNode[0] = (SceneNode*)mSceneMgr->getRootSceneNode()->createChild(); - - Entity* pEnt = mSceneMgr->createEntity( "1", "ogrehead.mesh" ); - mTestNode[0]->attachObject( pEnt ); - - pEnt->getSubEntity(1)->setVisible(false); - - mCameraNode->setPosition(0,0,125); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - - -PlayPen_TextureShadows::PlayPen_TextureShadows() -{ - mInfo["Title"] = "PlayPen_TextureShadows"; - mInfo["Description"] = "Tests texture shadows."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_TextureShadows::cleanupContent() -{ - clearDebugTextureOverlays(); -} -//---------------------------------------------------------------------------- - -void PlayPen_TextureShadows::setupContent() -{ - SceneNode* mTestNode[10]; - - mSceneMgr->setShadowTextureSize(1024); - mSceneMgr->setShadowTextureCount(1); - //mSceneMgr->setShadowTechnique(tech); - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE); - - //FocusedShadowCameraSetup* lispsmSetup = new FocusedShadowCameraSetup(); - //LiSPSMShadowCameraSetup* lispsmSetup = new LiSPSMShadowCameraSetup(); - //lispsmSetup->setOptimalAdjustFactor(1.5); - //mSceneMgr->setShadowCameraSetup(ShadowCameraSetupPtr(lispsmSetup)); - - mSceneMgr->setShadowFarDistance(1000); - mSceneMgr->setShadowColour(ColourValue(0.35, 0.35, 0.35)); - //mSceneMgr->setShadowFarDistance(800); - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); - - OrientedLightPtr mLight = mSceneMgr->createLight("MainLight"); - - - // Directional test - //if (directional) - //{ - mLight->setType(Light::LT_DIRECTIONAL); - Vector3 vec(-1,-1,0); - vec.normalise(); - mLight->setDirection(vec); - //} - // Spotlight test - /*else - { - mLight->setType(Light::LT_SPOTLIGHT); - mLight->setAttenuation(1500, 1, 0, 0); - mLight->setDiffuseColour(1.0, 1.0, 0.8); - mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - mTestNode[0]->setPosition(800,600,0); - mTestNode[0]->lookAt(Vector3(0,0,0), Node::TS_WORLD, Vector3::UNIT_Z); - mTestNode[0]->attachObject(mLight); - }*/ - - mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - - Entity* pEnt; - pEnt = mSceneMgr->createEntity( "1", "robot.mesh" ); - //pEnt->setRenderingDistance(100); - AnimationState* mAnimState = pEnt->getAnimationState("Walk"); - mAnimState->setEnabled(true); - mAnimStateList.push_back(mAnimState); - //pEnt->setMaterialName("2 - Default"); - mTestNode[1]->attachObject( pEnt ); - mTestNode[1]->translate(0,-100,0); - - Quaternion quat2; - quat2.FromAngleAxis(Degree(360), Vector3::UNIT_Y); - - pEnt = mSceneMgr->createEntity( "3", "knot.mesh" ); - mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-200, 0, -200)); - mTestNode[2]->attachObject( pEnt ); - - createRandomEntityClones(pEnt, 20, Vector3(-1000,0,-1000), Vector3(1000,0,1000), mSceneMgr); - - - // Transparent object (can force cast shadows) - pEnt = mSceneMgr->createEntity( "3.5", "knot.mesh" ); - mTestNode[3] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(350, 0, -200)); - mTestNode[3]->attachObject( pEnt ); - - pEnt = mSceneMgr->createEntity( "4", "knot.mesh" ); - mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 0, 200)); - mTestNode[2]->attachObject( pEnt ); - - mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); - - - MovablePlane movablePlane(Vector3::UNIT_Y, 100); - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, movablePlane, - 2500,2500,10,10,true,1,5,5,Vector3::UNIT_Z); - Entity* pPlaneEnt; - pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - if (SHADOWTYPE_TEXTURE_ADDITIVE & SHADOWDETAILTYPE_INTEGRATED) - { - pPlaneEnt->setMaterialName("Examples/Plane/IntegratedShadows"); - } - else - { - pPlaneEnt->setMaterialName("2 - Default"); - } - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - addTextureShadowDebugOverlay(1,mSceneMgr); - - - /* - ParticleSystem* pSys2 = mSceneMgr->createParticleSystem("smoke", - "Examples/Smoke"); - mTestNode[4] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-300, -100, 200)); - mTestNode[4]->attachObject(pSys2); - */ - - mCameraNode->setPosition(0, 1000, 500); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); - mCamera->setFarClipDistance(10000); - - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_TextureShadowsCustomCasterMat::PlayPen_TextureShadowsCustomCasterMat() -{ - mInfo["Title"] = "PlayPen_TextureShadowsCustomCasterMat"; - mInfo["Description"] = "Tests texture shadows with a custom caster material."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_TextureShadowsCustomCasterMat::setupContent() -{ - PlayPen_TextureShadows::setupContent(); - - MaterialPtr mat = MaterialManager::getSingleton().create("CustomShadowCaster", - TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setDiffuse(ColourValue::Black); - p->setEmissive(1, 1, 0); - - mSceneMgr->setShadowTextureCasterMaterial(mat); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_TextureShadowsCustomReceiverMat::PlayPen_TextureShadowsCustomReceiverMat() -{ - mInfo["Title"] = "PlayPen_TextureShadowsCustomReceiverMat"; - mInfo["Description"] = "Tests texture shadows with a custom receiver material."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_TextureShadowsCustomReceiverMat::setupContent() -{ - PlayPen_TextureShadows::setupContent(); - - auto mat = MaterialManager::getSingleton().create("CustomShadowReceiver", TRANSIENT_RESOURCE_GROUP); - Pass* p = mat->getTechnique(0)->getPass(0); - p->setLightingEnabled(false); - auto tus = p->createTextureUnitState(); // shadow texture will populate - tus->setColourOperationEx(LBX_MODULATE, LBS_MANUAL, LBS_TEXTURE, ColourValue(1, 0, 1)); - tus->setProjectiveTexturing(true); - - mSceneMgr->setShadowTextureReceiverMaterial(mat); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_TextureShadowsIntegrated::PlayPen_TextureShadowsIntegrated() -{ - mInfo["Title"] = "PlayPen_TextureShadowsIntegrated"; - mInfo["Description"] = "Tests integrated texture shadows."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_TextureShadowsIntegrated::cleanupContent() -{ - clearDebugTextureOverlays(); -} -//---------------------------------------------------------------------------- - -void PlayPen_TextureShadowsIntegrated::setupContent() -{ - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_ADDITIVE_INTEGRATED); - - mSceneMgr->setShadowTextureSettings(1024, 2); - - mSceneMgr->setAmbientLight(ColourValue::Black); - Light* l = mSceneMgr->createLight("Spot1"); - l->setType(Light::LT_SPOTLIGHT); - l->setAttenuation(5000,1,0,0); - l->setSpotlightRange(Degree(30),Degree(45),1.0f); - SceneNode* lightNode1 = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - lightNode1->attachObject(l); - lightNode1->setPosition(400, 250, 500); - lightNode1->lookAt(Vector3(0,-200,0), Node::TS_WORLD); - l->setDiffuseColour(0.7, 0.7, 0.5); - - l = mSceneMgr->createLight("Spot2"); - l->setAttenuation(5000,1,0,0); - /* // spotlight */ - l->setType(Light::LT_SPOTLIGHT); - l->setSpotlightRange(Degree(30),Degree(45),1.0f); - /**/ - // point - SceneNode* lightNode2 = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - lightNode2->attachObject(l); - lightNode2->setPosition(-500, 200, 500); - lightNode2->lookAt(Vector3(0,-200,0), Node::TS_WORLD); - /* // directional - l->setType(Light::LT_DIRECTIONAL); - Vector3 dir(0.5, -1, 0.5); - dir.normalise(); - l->setDirection(dir); - */ - l->setDiffuseColour(1, 0.2, 0.2); - - /* - // Test spot 3 - l = mSceneMgr->createLight("Spot3"); - l->setType(Light::LT_SPOTLIGHT); - l->setAttenuation(5000,1,0,0); - l->setSpotlightRange(Degree(30),Degree(45),1.0f); - SceneNode* lightNode3 = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - lightNode3->attachObject(l); - lightNode3->setPosition(700, 250, 500); - lightNode3->lookAt(Vector3(0,-200,0), Node::TS_WORLD); - l->setDiffuseColour(0.0, 0.7, 1.0); - */ - - // Create a basic plane to have something in the scene to look at - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 100; - MeshPtr msh = MeshManager::getSingleton().createPlane("Myplane_IS", - TRANSIENT_RESOURCE_GROUP, plane, - 4500,4500,100,100,true,1,40,40,Vector3::UNIT_Z); - msh->buildTangentVectors(); - Entity* pPlaneEnt; - pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane_IS" ); - //pPlaneEnt->setMaterialName("Examples/OffsetMapping/Specular"); - pPlaneEnt->setMaterialName("Examples/OffsetMapping/IntegratedShadows"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - pPlaneEnt = mSceneMgr->createEntity( "plane2", "Myplane_IS" ); - //pPlaneEnt->setMaterialName("Examples/OffsetMapping/Specular"); - pPlaneEnt->setMaterialName("Examples/OffsetMapping/IntegratedShadows"); - pPlaneEnt->setCastShadows(false); - SceneNode* n = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - n->roll(Degree(90)); - n->translate(100,0,0); - //n->attachObject(pPlaneEnt); - - pPlaneEnt = mSceneMgr->createEntity( "plane3", "Myplane_IS" ); - //pPlaneEnt->setMaterialName("Examples/OffsetMapping/Specular"); - pPlaneEnt->setMaterialName("Examples/OffsetMapping/IntegratedShadows"); - pPlaneEnt->setCastShadows(false); - n = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - n->pitch(Degree(90)); - n->yaw(Degree(-90)); - n->translate(0,0,-100); - n->attachObject(pPlaneEnt); - - mCameraNode->setPosition(-50, 500, 1000); - mCameraNode->lookAt(Vector3(Vector3(-50, -100, 0)), Node::TS_PARENT); - - Entity* ent = mSceneMgr->createEntity("athene", "athene.mesh"); - ent->setMaterialName("Examples/Athene/NormalMapped"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,-20,0))->attachObject(ent); - - addTextureShadowDebugOverlay(2, mSceneMgr); - - - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_TextureShadowsIntegratedPSSM::PlayPen_TextureShadowsIntegratedPSSM() -{ - mInfo["Title"] = "PlayPen_TextureShadowsIntegratedPSSM"; - mInfo["Description"] = "Tests integrated parallel split shadow mapping."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_TextureShadowsIntegratedPSSM::cleanupContent() -{ - clearDebugTextureOverlays(); -} -//---------------------------------------------------------------------------- - -void PlayPen_TextureShadowsIntegratedPSSM::setupContent() -{ - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE_INTEGRATED); - - // 3 textures per directional light - mSceneMgr->setShadowTextureCountPerLightType(Ogre::Light::LT_DIRECTIONAL, 3); - mSceneMgr->setShadowTextureSettings(512, 3, PF_FLOAT32_R); - mSceneMgr->setShadowTextureSelfShadow(true); - // Set up caster material - this is just a standard depth/shadow map caster - mSceneMgr->setShadowTextureCasterMaterial( - MaterialManager::getSingleton().getByName("PSSM/shadow_caster", "General")); - - mSceneMgr->setShadowFarDistance(5000); - mCamera->setFarClipDistance(5000); - - // shadow camera setup - PSSMShadowCameraSetup* pssmSetup = new PSSMShadowCameraSetup(); - pssmSetup->calculateSplitPoints(3, 250, mCamera->getFarClipDistance()); - pssmSetup->setSplitPadding(80); - pssmSetup->setOptimalAdjustFactor(0, 2); - pssmSetup->setOptimalAdjustFactor(1, 1); - pssmSetup->setOptimalAdjustFactor(2, 0.5); - - mSceneMgr->setShadowCameraSetup(ShadowCameraSetupPtr(pssmSetup)); - - - mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); - OrientedLightPtr l = mSceneMgr->createLight("Dir"); - l->setType(Light::LT_DIRECTIONAL); - Vector3 dir(0.3, -1, 0.2); - dir.normalise(); - l->setDirection(dir); - - - // Create a basic plane to have something in the scene to look at - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 100; - MeshPtr msh = MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 4500,4500,100,100,true,1,40,40,Vector3::UNIT_Z); - msh->buildTangentVectors(); - Entity* pPlaneEnt; - pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("Examples/BumpyMetal"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - mCameraNode->setPosition(-50, 500, 1000); - mCameraNode->lookAt(Vector3(Vector3(-50, -100, 0)), Node::TS_PARENT); - - Entity* ent = mSceneMgr->createEntity("knot", "knot.mesh"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,0,0))->attachObject(ent); - createRandomEntityClones(ent, 20, Vector3(-1000,0,-1000), Vector3(1000,0,1000), mSceneMgr); - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - // Make this viewport work with shader generator scheme. - mViewport->setMaterialScheme(MSN_SHADERGEN); - RTShader::ShaderGenerator& rtShaderGen = RTShader::ShaderGenerator::getSingleton(); - RTShader::RenderState* schemRenderState = rtShaderGen.getRenderState(MSN_SHADERGEN); - auto subRenderState = rtShaderGen.createSubRenderState(RTShader::SRS_SHADOW_MAPPING); - subRenderState->setParameter("split_points", pssmSetup->getSplitPoints()); - schemRenderState->addTemplateSubRenderState(subRenderState); -#endif - - addTextureShadowDebugOverlay(3, mSceneMgr); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_TextureShadowsTransparentCaster::PlayPen_TextureShadowsTransparentCaster() -{ - mInfo["Title"] = "PlayPen_TextureShadowsTransparentCaster"; - mInfo["Description"] = "Tests transparent shadow casters."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_TextureShadowsTransparentCaster::setupContent() -{ - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE); - mSceneMgr->setShadowCameraSetup(FocusedShadowCameraSetup::create()); - mSceneMgr->setShadowTextureSettings(1024, 1, PF_L8); - - // New depth shadow mapping - String CUSTOM_ROCKWALL_MATERIAL("Examples/Rockwall"); - - mSceneMgr->setShadowDirLightTextureOffset(0.2); - mSceneMgr->setShadowFarDistance(500); - - // Create a basic plane to have something in the scene to look at - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 100; - MeshPtr msh = MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 4500,4500,100,100,true,1,40,40,Vector3::UNIT_Z); - Entity* pPlaneEnt; - pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - - pPlaneEnt->setMaterialName(CUSTOM_ROCKWALL_MATERIAL); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - - - // Reorient the plane and create a plane mesh for the test planes - plane.normal = Vector3::UNIT_X; - MeshManager::getSingleton().createPlane("Test_Plane", TRANSIENT_RESOURCE_GROUP, plane, 50.0, 50.0); - - const String GRASSMAT("Examples/GrassBlades"); - - // Add test plane entities to the scene - Entity* entity = mSceneMgr->createEntity("GrassBlades0", "Test_Plane"); - entity->setMaterialName(GRASSMAT); - mSceneMgr->getRootSceneNode()->createChildSceneNode( - Vector3(0.0, -100.0+25.0, 0.0))->attachObject(entity); - - entity = mSceneMgr->createEntity("GrassBlades1", "Test_Plane"); - entity->setMaterialName(GRASSMAT); - mSceneMgr->getRootSceneNode()->createChildSceneNode( - Vector3(0.0, -100.0+25.0, -20.0))->attachObject(entity); - - entity = mSceneMgr->createEntity("GrassBlades2", "Test_Plane"); - entity->setMaterialName(GRASSMAT); - mSceneMgr->getRootSceneNode()->createChildSceneNode( - Vector3(0.0, -100.0+25.0, -40.0))->attachObject(entity); - - // Add test plane entities to the scene, shadowed partially by athene mesh - entity = mSceneMgr->createEntity("GrassBlades3", "Test_Plane"); - entity->setMaterialName(GRASSMAT); - mSceneMgr->getRootSceneNode()->createChildSceneNode( - Vector3(-80.0, -100.0+25.0, 0.0))->attachObject(entity); - - entity = mSceneMgr->createEntity("GrassBlades4", "Test_Plane"); - entity->setMaterialName(GRASSMAT); - mSceneMgr->getRootSceneNode()->createChildSceneNode( - Vector3(-130.0, -100.0+25.0, -20.0))->attachObject(entity); - - entity = mSceneMgr->createEntity("GrassBlades5", "Test_Plane"); - entity->setMaterialName(GRASSMAT); - mSceneMgr->getRootSceneNode()->createChildSceneNode( - Vector3(-180.0, -100.0+25.0, -40.0))->attachObject(entity); - - // Add test plane entities to the scene, one after another - entity = mSceneMgr->createEntity("GrassBlades6", "Test_Plane"); - entity->setMaterialName(GRASSMAT); - mSceneMgr->getRootSceneNode()->createChildSceneNode( - Vector3(-260.0, -100.0+25.0, 0.0))->attachObject(entity); - - entity = mSceneMgr->createEntity("GrassBlades7", "Test_Plane"); - entity->setMaterialName(GRASSMAT); - mSceneMgr->getRootSceneNode()->createChildSceneNode( - Vector3(-260.0, -100.0+25.0, -10.0))->attachObject(entity); - - entity = mSceneMgr->createEntity("GrassBlades8", "Test_Plane"); - entity->setMaterialName(GRASSMAT); - mSceneMgr->getRootSceneNode()->createChildSceneNode( - Vector3(-260.0, -100.0+25.0, -20.0))->attachObject(entity); - - // Add test plane entities to the scene, alone with other material - - const String GRASSMAT_CUSTOM_DEFAULT_CUSTOM("Examples/GrassBlades"); - const String GRASSMAT_CUSTOM_NOSPECIAL_CUSTOM("Examples/GrassBlades"); - const String GRASSMAT_ORIG("Examples/GrassBlades"); - - entity = mSceneMgr->createEntity("GrassBlades9", "Test_Plane"); - entity->setMaterialName(GRASSMAT_CUSTOM_DEFAULT_CUSTOM); - mSceneMgr->getRootSceneNode()->createChildSceneNode( - Vector3(-80.0, -100.0+25.0, -80.0))->attachObject(entity); - - entity = mSceneMgr->createEntity("GrassBlades10", "Test_Plane"); - entity->setMaterialName(GRASSMAT_CUSTOM_NOSPECIAL_CUSTOM); - mSceneMgr->getRootSceneNode()->createChildSceneNode( - Vector3(-130.0, -100.0+25.0, -90.0))->attachObject(entity); - - entity = mSceneMgr->createEntity("GrassBlades11", "Test_Plane"); - entity->setMaterialName(GRASSMAT_ORIG); - mSceneMgr->getRootSceneNode()->createChildSceneNode( - Vector3(-180.0, -100.0+25.0, -90.0))->attachObject(entity); - - Entity* ent = mSceneMgr->createEntity("athene", "athene.mesh"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,-20,-20))->attachObject(ent); - - // Position and orient the camera - mCameraNode->setPosition(100,50,150); - mCameraNode->lookAt(Vector3(-50, -25, 0), Node::TS_PARENT); - - OrientedLightPtr l = mSceneMgr->createLight("Dir1"); - l->setType(Light::LT_DIRECTIONAL); - Vector3 dir1(-2.5, -0.7, -0.5); - dir1.normalise(); - l->setDirection(dir1); - l->setDiffuseColour(1.0, 1.0, 1.0); - - mSceneMgr->setAmbientLight(ColourValue(0.0, 0.0, 0.2)); - - //addTextureShadowDebugOverlay(1, mSceneMgr); -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_TransparencyMipMaps::PlayPen_TransparencyMipMaps() -{ - mInfo["Title"] = "PlayPen_TransparencyMipMaps"; - mInfo["Description"] = "Tests transparent materials with mipmaps."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_TransparencyMipMaps::setupContent() -{ - MaterialPtr mat = MaterialManager::getSingleton().create("test", - TRANSIENT_RESOURCE_GROUP); - // known png with alpha - Pass* pass = mat->getTechnique(0)->getPass(0); - pass->createTextureUnitState("sdk_logo.png"); - pass->setSceneBlending(SBT_TRANSPARENT_ALPHA); - // alpha blend - pass->setDepthWriteEnabled(false); - - // alpha reject - //pass->setDepthWriteEnabled(true); - //pass->setAlphaRejectSettings(CMPF_LESS, 128); - - // Define a floor plane mesh - Plane p; - p.normal = Vector3::UNIT_Y; - p.d = 200; - MeshManager::getSingleton().createPlane("FloorPlane", - TRANSIENT_RESOURCE_GROUP, - p,2000,2000,1,1,true,1,5,5,Vector3::UNIT_Z); - - // Create an entity (the floor) - Entity* ent = mSceneMgr->createEntity("floor", "FloorPlane"); - ent->setMaterialName("test"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); - - mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8); - mSceneMgr->setAmbientLight(ColourValue::White); - - - { - - Real alphaLevel = 0.5f; - MaterialPtr alphamat = MaterialManager::getSingleton().create("testy", - TRANSIENT_RESOURCE_GROUP); - Pass* alphaPass = alphamat->getTechnique(0)->getPass(0); - alphaPass->setSceneBlending(SBT_TRANSPARENT_ALPHA); - alphaPass->setDepthWriteEnabled(false); - TextureUnitState* t = alphaPass->createTextureUnitState(); - t->setAlphaOperation(LBX_SOURCE1, LBS_MANUAL, LBS_CURRENT, alphaLevel); - - ent = mSceneMgr->createEntity("asd", "ogrehead.mesh"); - ent->setMaterialName("testy"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); - - } - - mCameraNode->setPosition(0,0,1000); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_VertexTexture::PlayPen_VertexTexture() -{ - mInfo["Title"] = "PlayPen_VertexTexture"; - mInfo["Description"] = "Tests vertex texture rendering (DX only)."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_VertexTexture::setupContent() -{ - Light* l = mSceneMgr->createLight("MainLight"); - l->setType(Light::LT_POINT); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 200, 0))->attachObject(l); - - - // Create single-channel floating point texture, no mips - TexturePtr tex = TextureManager::getSingleton().createManual( - "vertexTexture", TRANSIENT_RESOURCE_GROUP, TEX_TYPE_2D, - 128, 128, 0, PF_FLOAT32_R); - float* pData = static_cast( - tex->getBuffer()->lock(HardwareBuffer::HBL_DISCARD)); - // write concentric circles into the texture - for (int y = -64; y < 64; ++y) - { - for (int x = -64; x < 64; ++x) - { - - float val = Math::Sqrt(x*x + y*y); - // repeat every 20 pixels - val = val * Math::TWO_PI / 20.0f; - *pData++ = Math::Sin(val); - } - } - tex->getBuffer()->unlock(); - - auto lang = GpuProgramManager::getSingleton().isSyntaxSupported("glsl") ? "glsl" : "hlsl"; - - String progSource = - "#include \n" - "SAMPLER2D(heightmap, 1);\n" - "uniform mat4 world;\n" - "uniform mat4 viewProj;\n" - "uniform float heightscale;\n" - "MAIN_PARAMETERS\n" - "IN(vec4 pos , POSITION)\n" - "IN(vec2 uv0 , TEXCOORD0)\n" - "OUT(vec2 uv , TEXCOORD0)\n" - "OUT(vec4 colour , COLOR)\n" - "MAIN_DECLARATION\n" - "{\n" - "gl_Position = mul(world, pos);\n" - // tex2Dlod since no mip - "float height = texture2DLod(heightmap, uv0, 0.0).r;\n" - "gl_Position.y += (height * heightscale);\n" - "gl_Position = mul(viewProj, gl_Position);\n" - "uv = uv0;\n" - "colour = vec4(1,1,1,1);\n" - "}\n"; - HighLevelGpuProgramPtr prog = HighLevelGpuProgramManager::getSingleton().createProgram( - "TestVertexTextureFetch", TRANSIENT_RESOURCE_GROUP, - lang, GPT_VERTEX_PROGRAM); - prog->setSource(progSource); - prog->setParameter("target", "vs_3_0"); - prog->setVertexTextureFetchRequired(true); - prog->load(); - - - MaterialPtr mat = MaterialManager::getSingleton().create("TestVertexTexture", - TRANSIENT_RESOURCE_GROUP); - Pass* pass = mat->getTechnique(0)->getPass(0); - pass->setLightingEnabled(false); - pass->setVertexProgram("TestVertexTextureFetch"); - pass->setFragmentProgram("Ogre/BasicFragmentPrograms/DiffuseOneTexture"); - GpuProgramParametersSharedPtr vp = pass->getVertexProgramParameters(); - vp->setNamedAutoConstant("world", GpuProgramParameters::ACT_WORLD_MATRIX); - vp->setNamedAutoConstant("viewProj", GpuProgramParameters::ACT_VIEWPROJ_MATRIX); - vp->setNamedConstant("heightscale", 30.0f); - - if(prog->getSyntaxCode() == "glsl") - vp->setNamedConstant("heightmap", 1); - // regular texture - pass->createTextureUnitState("BumpyMetal.jpg"); - // vertex texture - pass->createTextureUnitState("vertexTexture"); - - Plane plane; - plane.normal = Vector3::UNIT_Y; - plane.d = 100; - // 128 x 128 segment plane - MeshManager::getSingleton().createPlane("Myplane", - TRANSIENT_RESOURCE_GROUP, plane, - 1500,1500,128,128,true,1,1,1,Vector3::UNIT_Z); - Entity* pPlaneEnt; - pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); - pPlaneEnt->setMaterialName("TestVertexTexture"); - pPlaneEnt->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); - - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_ViewportNoShadows::PlayPen_ViewportNoShadows() -{ - mInfo["Title"] = "PlayPen_ViewportNoShadows"; - mInfo["Description"] = "Tests disabling shadows for a viewport."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_ViewportNoShadows::setupContent() -{ - mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE); - - // Setup lighting - mSceneMgr->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); - OrientedLightPtr light = mSceneMgr->createLight("MainLight"); - light->setType(Light::LT_DIRECTIONAL); - Vector3 dir(-1, -1, 0.5); - dir.normalise(); - light->setDirection(dir); - - // Create a skydome - //mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8); - - // Create a floor plane mesh - Plane plane(Vector3::UNIT_Y, 0.0); - MeshManager::getSingleton().createPlane( - "FloorPlane", TRANSIENT_RESOURCE_GROUP, - plane, 200000, 200000, 20, 20, true, 1, 500, 500, Vector3::UNIT_Z); - - - // Add a floor to the scene - Entity* entity = mSceneMgr->createEntity("floor", "FloorPlane"); - entity->setMaterialName("Examples/RustySteel"); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(entity); - entity->setCastShadows(false); - - // Add the mandatory ogre head - entity = mSceneMgr->createEntity("head", "ogrehead.mesh"); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0.0, 10.0, 0.0))->attachObject(entity); - - // Position and orient the camera - mCameraNode->setPosition(-100.0, 50.0, 90.0); - mCameraNode->lookAt(Vector3(0.0, 10.0, -35.0), Node::TS_WORLD); - - // Add an additional viewport on top of the other one - Viewport* pip = mWindow->addViewport(mCamera, 1, 0.7, 0.0, 0.3, 0.3); - pip->setShadowsEnabled(false); - -} -//---------------------------------------------------------------------------- -//---------------------------------------------------------------------------- - -PlayPen_WindowedViewportMode::PlayPen_WindowedViewportMode() -{ - mInfo["Title"] = "PlayPen_WindowedViewportMode"; - mInfo["Description"] = "Tests windowed viewport."; - addScreenshotFrame(10); -} -//---------------------------------------------------------------------------- - -void PlayPen_WindowedViewportMode::setupContent() -{ - Ogre::SceneNode* mTestNode[5]; - - // Set ambient light - mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); - - // Create a point light - OrientedLightPtr l = mSceneMgr->createLight("MainLight"); - l->setType(Light::LT_DIRECTIONAL); - l->setDirection(-Vector3::UNIT_Y); - - mTestNode[0] = (SceneNode*)mSceneMgr->getRootSceneNode()->createChild(); - - Entity* pEnt = mSceneMgr->createEntity( "1", "ogrehead.mesh" ); - mTestNode[0]->attachObject( pEnt ); - - mCamera->setWindow(0,0,0.5,0.5); - - mCameraNode->setPosition(0,0,125); -} - -PlayPen_BillboardText::PlayPen_BillboardText() -{ - mInfo["Title"] = "PlayPen_BillboardText"; - mInfo["Description"] = "Tests setting billboard text"; - addScreenshotFrame(1); -} -//---------------------------------------------------------------------------- - -void PlayPen_BillboardText::setupContent() -{ - BillboardSet* bbs = mSceneMgr->createBillboardSet(); - - auto font = FontManager::getSingleton().getByName("DejaVu/SerifCondensedItalic", "Tests"); - - font->putText(bbs, "Jörg bäckt quasi\nzwei Haxenfüße vom", 10); - font->putText(bbs, "Wildpony", 15, ColourValue::Blue); - - mSceneMgr->getRootSceneNode() - ->createChildSceneNode(bbs->getBoundingBox().getHalfSize()*Vector3(-1, 1, 0)) - ->attachObject(bbs); - - mCameraNode->setPosition(0,0,160); - mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); -} - - -PlayPen_PBR::PlayPen_PBR() -{ - mInfo["Title"] = "PlayPen_PBR"; - mInfo["Description"] = "Tests PBR"; - mInfo["Category"] = "Tests"; - mInfo["Thumbnail"] = "thumb_visual_tests.png"; - addScreenshotFrame(1); -} -//---------------------------------------------------------------------------- - -void PlayPen_PBR::setupContent() -{ - // Make this viewport work with shader generator scheme. - mViewport->setMaterialScheme(MSN_SHADERGEN); - - mCamera->setNearClipDistance(0.5f); - - auto plane = MeshManager::getSingleton().createPlane("Plane", TRANSIENT_RESOURCE_GROUP, Plane(Vector3::UNIT_Y, 1), - 50, 50, 1, 1, true, 1, 8, 8, Vector3::UNIT_Z); - - // build tangent vectors for our mesh - plane->buildTangentVectors(); - - auto ground = mSceneMgr->createEntity("Plane"); - ground->setMaterialName("Examples/WoodenFloor"); - mSceneMgr->getRootSceneNode()->attachObject(ground); - - Ogre::Light* light = mSceneMgr->createLight(); - Ogre::SceneNode* lightNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - lightNode->attachObject(light); - light->setType(Light::LT_DIRECTIONAL); - lightNode->setDirection(Vector3(-1, -1, -1).normalisedCopy()); - - mSceneMgr->setAmbientLight(ColourValue(0.6f, 0.45f, 0.3f) * 0.065f * 0.75f); - - light = mSceneMgr->createLight(); - lightNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - lightNode->attachObject(light); - light->setDiffuseColour(0.8f, 0.4f, 0.2f); // Warm - light->setType(Light::LT_SPOTLIGHT); - light->setPowerScale(Math::PI); - lightNode->setPosition(-10.0f, 10.0f, 10.0f); - lightNode->setDirection(Vector3(1, -1, -1).normalisedCopy()); - light->setAttenuation(100, 0.5, 0, 0.5/100); - - light = mSceneMgr->createLight(); - lightNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - lightNode->attachObject(light); - light->setDiffuseColour(0.2f, 0.4f, 0.8f); // Cold - light->setType(Light::LT_SPOTLIGHT); - light->setPowerScale(Math::PI); - lightNode->setPosition(10.0f, 10.0f, -10.0f); - lightNode->setDirection(Vector3(-1, -1, 1).normalisedCopy()); - light->setAttenuation(100, 0.5, 0, 0.5/100); - - auto baseMat = MaterialManager::getSingleton().getByName("Examples/PBR_Sphere"); - - const float armsLength = 2.5f; - for (int i = 0; i < 4; ++i) - { - for (int j = 0; j < 4; ++j) - { - auto sphere = mSceneMgr->createEntity("Sphere1000.mesh"); - sphere->setMaterial(MaterialManager::getSingleton().getDefaultMaterial(true)); - auto node = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - - node->setPosition((i - 1.5f) * armsLength, 2.0f, (j - 1.5f) * armsLength); - node->setScale(0.65f, 0.65f, 0.65f); - node->attachObject(sphere); - - int idx = i * 4 + j; - auto mat = - baseMat->clone(StringUtil::format("Examples/PBR_Sphere%d", idx), String(TRANSIENT_RESOURCE_GROUP)); -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - RTShader::ShaderGenerator::getSingleton().cloneShaderBasedTechniques(*baseMat, *mat); -#endif - ColourValue spec; - spec[0] = i / 3.0; // metal - spec[1] = j / 3.0; // roughness - mat->setSpecular(spec); - sphere->setMaterial(mat); - } - } - - mCameraNode->setPosition(0, -5, 10); - mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); - - if(!mCameraMan) - return; - - mCameraMan->setStyle(OgreBites::CS_ORBIT); -} -void PlayPen_PBR::unloadResources() -{ - ResourceGroupManager::getSingleton().clearResourceGroup(TRANSIENT_RESOURCE_GROUP); -} -//----------------------------------------------------------------------- -//----------------------------------------------------------------------- - -void addTextureDebugOverlay(const Ogre::String& texname, size_t i) -{ - Ogre::Overlay* debugOverlay = Ogre::OverlayManager::getSingleton().getByName("Core/DebugOverlay"); - - if(!debugOverlay) - debugOverlay = Ogre::OverlayManager::getSingleton().create("Core/DebugOverlay"); - - debugOverlay->show(); - - // Set up a debug panel to display the shadow - Ogre::MaterialPtr debugMat = Ogre::MaterialManager::getSingleton().create( - "Ogre/DebugTexture" + Ogre::StringConverter::toString(i), - "VisualTestTransient"); - debugMat->getTechnique(0)->getPass(0)->setLightingEnabled(false); - debugMat->getTechnique(0)->getPass(0)->setDepthCheckEnabled(false); - Ogre::TextureUnitState *t = debugMat->getTechnique(0)->getPass(0)->createTextureUnitState(texname); - t->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP); - - Ogre::OverlayContainer* debugPanel = (Ogre::OverlayContainer*) - (Ogre::OverlayManager::getSingleton().createOverlayElement("Panel", "Ogre/DebugTexPanel" + Ogre::StringConverter::toString(i))); - debugPanel->_setPosition(0.8, i*0.25); - debugPanel->_setDimensions(0.2, 0.24); - debugPanel->setMaterial(debugMat); - debugOverlay->add2D(debugPanel); - -} -//----------------------------------------------------------------------- - -void clearDebugTextureOverlays() -{ - Ogre::Overlay* debugOverlay = Ogre::OverlayManager::getSingleton().getByName("Core/DebugOverlay"); - - if(debugOverlay) - Ogre::OverlayManager::getSingleton().destroy("Core/DebugOverlay"); - //debugOverlay->hide(); - - for(int i = 0; i < 10; ++i) - { - if(Ogre::OverlayManager::getSingleton().hasOverlayElement( - "Ogre/DebugTexPanel" + Ogre::StringConverter::toString(i))) - { - OverlayManager::getSingleton().destroyOverlayElement( - "Ogre/DebugTexPanel" + Ogre::StringConverter::toString(i)); - MaterialManager::getSingleton().remove("Ogre/DebugTexture" + StringConverter::toString(i), "VisualTestTransient"); - } - } -} -//----------------------------------------------------------------------- - -void addTextureDebugOverlay(const Ogre::TexturePtr& tex, size_t i) -{ - addTextureDebugOverlay(tex->getName(), i); -} -//----------------------------------------------------------------------- - -void addTextureShadowDebugOverlay(size_t num, Ogre::SceneManager* mgr) -{ - for (size_t i = 0; i < num; ++i) - { - Ogre::TexturePtr shadowTex = mgr->getShadowTexture(i); - addTextureDebugOverlay(shadowTex, i); - } -} -//----------------------------------------------------------------------- diff --git a/Tests/VisualTests/VTests/CMakeLists.txt b/Tests/VisualTests/VTests/CMakeLists.txt deleted file mode 100644 index c78cc3b92de..00000000000 --- a/Tests/VisualTests/VTests/CMakeLists.txt +++ /dev/null @@ -1,39 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -set(HEADER_FILES - include/StencilShadowTest.h - include/ParticleTest.h - include/TextureBlitTest.h - include/VTestPlugin.h) - -set(SOURCE_FILES - src/StencilShadowTest.cpp - src/TextureBlitTest.cpp - src/CubeMappingTest.cpp - src/ParticleTest.cpp - src/VTestPlugin.cpp) - -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) -include_directories(${PROJECT_SOURCE_DIR}/Samples/Common/include) -include_directories(${PROJECT_SOURCE_DIR}/Samples/Simple/include) -include_directories(${PROJECT_SOURCE_DIR}/Tests/VisualTests/Common/include) - -add_library(VTests ${OGRE_LIB_TYPE} ${HEADER_FILES} ${SOURCE_FILES} ) -target_link_libraries(VTests ${OGRE_LIBRARIES} OgreBites OgreOverlay OgreRTShaderSystem) -ogre_config_sample_lib(VTests) - -if (APPLE AND NOT APPLE_IOS) - # Set the INSTALL_PATH so that Samples can be installed in the application package - set_target_properties(VTests - PROPERTIES BUILD_WITH_INSTALL_RPATH 1 - INSTALL_NAME_DIR "@executable_path/../Plugins" - ) -endif() - diff --git a/Tests/VisualTests/VTests/include/CubeMappingTest.h b/Tests/VisualTests/VTests/include/CubeMappingTest.h deleted file mode 100644 index 90dafdb9f9d..00000000000 --- a/Tests/VisualTests/VTests/include/CubeMappingTest.h +++ /dev/null @@ -1,50 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __CubeMappingTest_H__ -#define __CubeMappingTest_H__ - -#include "VisualTest.h" -#include "SamplePlugin.h" - -using namespace Ogre; - -/** Tests basic fixed-function cube mapping */ -class _OgreSampleClassExport CubeMappingTest : public VisualTest -{ -public: - - CubeMappingTest(); - -protected: - - void setupContent() override; - -}; - -#endif diff --git a/Tests/VisualTests/VTests/include/ParticleTest.h b/Tests/VisualTests/VTests/include/ParticleTest.h deleted file mode 100644 index 7aaa7ecac73..00000000000 --- a/Tests/VisualTests/VTests/include/ParticleTest.h +++ /dev/null @@ -1,50 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __ParticleTest_H__ -#define __ParticleTest_H__ - -#include "VisualTest.h" -#include "SamplePlugin.h" - -using namespace Ogre; - -/** Tests basic particle system behavior */ -class _OgreSampleClassExport ParticleTest : public VisualTest -{ -public: - - ParticleTest(); - -protected: - - void setupContent() override; - -}; - -#endif diff --git a/Tests/VisualTests/VTests/include/StencilShadowTest.h b/Tests/VisualTests/VTests/include/StencilShadowTest.h deleted file mode 100644 index ef847654c20..00000000000 --- a/Tests/VisualTests/VTests/include/StencilShadowTest.h +++ /dev/null @@ -1,51 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __StencilShadowTest_H__ -#define __StencilShadowTest_H__ - -#include "VisualTest.h" -#include "SamplePlugin.h" - -using namespace Ogre; - -/** Tests basic stencil shadow behavior */ -class _OgreSampleClassExport StencilShadowTest : public VisualTest -{ -public: - - StencilShadowTest(); - -protected: - - void setupContent() override; - Ogre::Entity* mGroundPlane; - -}; - -#endif diff --git a/Tests/VisualTests/VTests/include/TextureBlitTest.h b/Tests/VisualTests/VTests/include/TextureBlitTest.h deleted file mode 100644 index 2dcfbed4a20..00000000000 --- a/Tests/VisualTests/VTests/include/TextureBlitTest.h +++ /dev/null @@ -1,54 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __TextureBlitTest_H__ -#define __TextureBlitTest_H__ - -#include "VisualTest.h" -#include "SamplePlugin.h" - -using namespace Ogre; - -/** Tests basic stencil shadow behavior */ -class _OgreSampleClassExport TextureBlitTest : public VisualTest -{ -public: - - TextureBlitTest(); - -protected: - - void setupContent() override; - -private: - TexturePtr m_colorTexture; - TexturePtr m_depthTexture; - -}; - -#endif diff --git a/Tests/VisualTests/VTests/include/VTestPlugin.h b/Tests/VisualTests/VTests/include/VTestPlugin.h deleted file mode 100644 index 41b0eecf66c..00000000000 --- a/Tests/VisualTests/VTests/include/VTestPlugin.h +++ /dev/null @@ -1,43 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __VTestPlugin_H__ -#define __VTestPlugin_H__ - -#include "SamplePlugin.h" - -/** Plugin class for visual tests */ -class _OgreSampleExport VTestPlugin : public OgreBites::SamplePlugin -{ -public: - - VTestPlugin(); - ~VTestPlugin(); -}; - -#endif diff --git a/Tests/VisualTests/VTests/src/CubeMappingTest.cpp b/Tests/VisualTests/VTests/src/CubeMappingTest.cpp deleted file mode 100644 index 4a79b1b3e0f..00000000000 --- a/Tests/VisualTests/VTests/src/CubeMappingTest.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "CubeMappingTest.h" - -CubeMappingTest::CubeMappingTest() -{ - mInfo["Title"] = "VTests_CubeMapping"; - mInfo["Description"] = "Tests basic fixed-function cube mapping."; - addScreenshotFrame(10); -} -//--------------------------------------------------------------------------- - -void CubeMappingTest::setupContent() -{ - mSceneMgr->setSkyBox(true, "Examples/MorningSkyBox"); - Ogre::SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - Ogre::Entity* head = mSceneMgr->createEntity("ogrehead.mesh"); - node->attachObject(head); - head->setMaterialName("Examples/MorningCubeMap"); - mCameraNode->setPosition(0,0,100); -} -//----------------------------------------------------------------------- - - diff --git a/Tests/VisualTests/VTests/src/ParticleTest.cpp b/Tests/VisualTests/VTests/src/ParticleTest.cpp deleted file mode 100644 index 7e638e3558f..00000000000 --- a/Tests/VisualTests/VTests/src/ParticleTest.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "ParticleTest.h" -#include "OgreParticleSystem.h" - -ParticleTest::ParticleTest() -{ - mInfo["Title"] = "VTests_Particles"; - mInfo["Description"] = "Tests basic particle system functionality."; - // take screenshot early, when emitters are just beginning - addScreenshotFrame(35); - // and another after particles have died, extra emitters emitted, etc - addScreenshotFrame(500); -} -//--------------------------------------------------------------------------- - -void ParticleTest::setupContent() -{ - // create a bunch of random particle systems - Ogre::ParticleSystem* ps = mSceneMgr->createParticleSystem("Fireworks", "Examples/Fireworks"); - mSceneMgr->getRootSceneNode()->attachObject(ps); - - // Multiple systems didn't seem to stay deterministic... (in gcc at least...) - //ps = mSceneMgr->createParticleSystem("Fountain", "Examples/PurpleFountain"); - //mSceneMgr->getRootSceneNode()->attachObject(ps); - //ps = mSceneMgr->createParticleSystem("Nimbus", "Examples/GreenyNimbus"); - //mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(150, 0, 0))->attachObject(ps); - //ps = mSceneMgr->createParticleSystem("Nimbus2", "Examples/GreenyNimbus"); - //mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-150, 0, 0))->attachObject(ps); - mCameraNode->setPosition(0,150,500); -} -//----------------------------------------------------------------------- - - diff --git a/Tests/VisualTests/VTests/src/StencilShadowTest.cpp b/Tests/VisualTests/VTests/src/StencilShadowTest.cpp deleted file mode 100644 index a82e4b99b96..00000000000 --- a/Tests/VisualTests/VTests/src/StencilShadowTest.cpp +++ /dev/null @@ -1,103 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "StencilShadowTest.h" -#include "OgreMovablePlane.h" - -StencilShadowTest::StencilShadowTest() -{ - mInfo["Title"] = "VTests_StencilShadows"; - mInfo["Description"] = "Tests basic stencil shadow functionality."; - - // take screenshot almost immediately, since the scene is static - addScreenshotFrame(10); -} -//--------------------------------------------------------------------------- - -void StencilShadowTest::setupContent() -{ - // turn ambient light off - mSceneMgr->setAmbientLight(ColourValue(0.0, 0.0, 0.0)); - - // turn on stencil shadows - mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_MODULATIVE); - - // add a couple lights - Ogre::Light* light = mSceneMgr->createLight("Light1"); - light->setDiffuseColour(0.5f,0.4f,0.35f); - light->setSpecularColour(0, 0, 0); - light->setAttenuation(8000,1,0.0005,0); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(220, 100, 0))->attachObject(light); - light->setCastShadows(true); - light->setType(Light::LT_POINT); - light = mSceneMgr->createLight("Light2"); - light->setDiffuseColour(0.5f,0.4f,0.35f); - light->setSpecularColour(0, 0, 0); - light->setAttenuation(8000,1,0.0005,0); - mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(220, 100, -200))->attachObject(light); - light->setCastShadows(true); - light->setType(Light::LT_POINT); - - // create a ground plane to receive some shadows - Plane pln = MovablePlane("plane"); - pln.normal = Vector3::UNIT_Y; - pln.d = 107; - MeshManager::getSingleton().createPlane("ground_plane", - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, pln, - 1500,1500,50,50,true,1,5,5,Vector3::UNIT_Z); - Ogre::Entity* groundPlane = mSceneMgr->createEntity( "plane", "ground_plane" ); - groundPlane->setMaterialName("Examples/Rocky"); - groundPlane->setCastShadows(false); - mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(groundPlane); - - // and a couple objects to cast the shadows - Ogre::Entity* bar = mSceneMgr->createEntity( "barrel", "Barrel.mesh" ); - bar->setCastShadows(true); - Ogre::SceneNode* barNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - barNode->attachObject(bar); - barNode->setScale(7,7,7); - barNode->setPosition(Ogre::Vector3(0,-85,-320)); - Ogre::Entity* head = mSceneMgr->createEntity( "ogrehead", "ogrehead.mesh" ); - head->setCastShadows(true); - Ogre::SceneNode* headNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - headNode->attachObject(head); - headNode->setPosition(Ogre::Vector3(-100,-80,-320)); - Ogre::Entity* torus = mSceneMgr->createEntity( "torus", "knot.mesh" ); - torus->setCastShadows(true); - torus->setMaterialName("Examples/RustySteel"); - Ogre::SceneNode* torusNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - torusNode->setScale(0.5,0.5,0.5); - torusNode->attachObject(torus); - torusNode->setPosition(Ogre::Vector3(100,-60,-320)); - - // point the camera down a bit - mCameraNode->pitch(Ogre::Degree(-20.f)); -} -//----------------------------------------------------------------------- - - diff --git a/Tests/VisualTests/VTests/src/TextureBlitTest.cpp b/Tests/VisualTests/VTests/src/TextureBlitTest.cpp deleted file mode 100644 index 9113b80689d..00000000000 --- a/Tests/VisualTests/VTests/src/TextureBlitTest.cpp +++ /dev/null @@ -1,222 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "TextureBlitTest.h" - -/* GIMP RGB C-Source image dump (image.c) */ - -static struct { - unsigned int width; - unsigned int height; - unsigned int bytes_per_pixel; /* 2:RGB16, 3:RGB, 4:RGBA */ - unsigned char pixel_data[16 * 16 * 3 + 1]; -} ColorImage = { - 16, 16, 3, - "\377\0\0\377\0T\377\0\265\351\0\377\210\0\377'\0\377\0:\377\0\233\377\0\373" - "\377\0\377\243\0\377B\37\377\0\177\377\0\340\377\0\377\275\0\377\\\0\377" - "\0\0\377\0T\377\0\265\350\0\377\210\0\377(\0\377\0""9\377\0\232\377\0\373" - "\377\0\377\242\0\377A\37\377\0\177\377\0\340\377\0\377\275\0\377]\0\377\0" - "\0\377\0T\377\0\265\350\0\377\207\0\377'\0\377\0""9\377\0\232\377\0\373\377" - "\0\377\243\0\377B\37\377\0\177\377\0\341\377\0\377\275\0\377\\\0\377\0\0" - "\377\0T\377\0\264\351\0\377\210\0\377'\0\377\0:\377\0\232\377\0\373\377\0" - "\377\242\0\377B\37\377\0\177\377\0\340\377\0\377\275\0\377]\0\377\0\0\377" - "\0T\377\0\265\351\0\377\210\0\377(\0\377\0""9\377\0\233\377\0\373\377\0\377" - "\242\0\377B\37\377\0\177\377\0\340\377\0\377\275\0\377\\\0\377\0\0\377\0" - "T\377\0\264\351\0\377\210\0\377'\0\377\0""9\377\0\232\377\0\373\377\0\377" - "\243\0\377B\37\377\0\177\377\0\340\377\0\377\275\0\377]\0\377\0\0\377\0U" - "\377\0\265\351\0\377\210\0\377'\0\377\0:\377\0\232\377\0\373\377\0\377\243" - "\0\377B\37\377\0\177\377\0\340\377\0\377\275\0\377\\\0\377\0\0\377\0U\377" - "\0\264\351\0\377\210\0\377'\0\377\0""9\377\0\233\377\0\373\377\0\377\242" - "\0\377B\37\377\0\200\377\0\340\377\0\377\275\0\377\\\0\377\0\0\377\0T\377" - "\0\265\350\0\377\210\0\377'\0\377\0""9\377\0\232\377\0\373\377\0\377\242" - "\0\377B\37\377\0\177\377\0\340\377\0\377\275\0\377]\0\377\0\0\377\0T\377" - "\0\264\351\0\377\210\0\377'\0\377\0""9\377\0\232\377\0\373\377\0\377\242" - "\0\377B\37\377\0\200\377\0\341\377\0\377\275\0\377]\0\377\0\0\377\0T\377" - "\0\265\351\0\377\210\0\377'\0\377\0:\377\0\232\377\0\373\377\0\377\243\0" - "\377B\37\377\0\177\377\0\341\377\0\377\275\0\377\\\0\377\0\0\377\0T\377\0" - "\265\350\0\377\210\0\377'\0\377\0""9\377\0\232\377\0\372\377\0\377\243\0" - "\377B\37\377\0\200\377\0\340\377\0\377\275\0\377\\\0\377\0\0\377\0T\377\0" - "\265\350\0\377\207\0\377'\0\377\0""9\377\0\232\377\0\372\377\0\377\243\0" - "\377B\37\377\0\200\377\0\340\377\0\377\275\0\377]\0\377\0\0\377\0T\377\0" - "\265\350\0\377\207\0\377'\0\377\0:\377\0\232\377\0\373\377\0\377\243\0\377" - "B\37\377\0\177\377\0\340\377\0\377\275\0\377\\\0\377\0\0\377\0U\377\0\264" - "\350\0\377\210\0\377'\0\377\0:\377\0\232\377\0\372\377\0\377\243\0\377A\37" - "\377\0\177\377\0\340\377\0\377\275\0\377\\\0\377\0\0\377\0T\377\0\265\351" - "\0\377\210\0\377'\0\377\0""9\377\0\232\377\0\373\377\0\377\243\0\377B\37" - "\377\0\200\377\0\340\377\0\377\275\0\377\\\0", -}; - -/* GIMP RGB C-Source image dump (depth.c) */ - -static struct { - unsigned int width; - unsigned int height; - unsigned int bytes_per_pixel; /* 2:RGB16, 3:RGB, 4:RGBA */ - unsigned char pixel_data[16 * 16 * 2 + 1]; -} DepthImage = { - 16, 16, 2, - "\0\0a\10\343\30f)\3479\211R\353b\216k\357{r\224\24\245\226\255\30\276\232" - "\326\374\346\236\357\0\0b\10\344\30e)\3479jJ\353Z\216s\20|r\214\364\244\226" - "\265\27\276\232\326\34\347\236\367\0\0b\20\343\30e1\3509jJ\13[\216k\360{" - "q\214\24\235u\255\30\306z\326\34\347\236\367\0\0a\10\3\31e1\3479\211J\353" - "Zns\357{r\224\363\234\226\265\27\306\232\326\34\347\236\367\0\0a\10\3\31" - "e)\3479jJ\14[mk\20|r\224\364\244u\265\30\306\231\316\34\347\236\367\0\0a" - "\10\343\30e)\3479iJ\353Z\215s\357{q\224\23\235\225\265\30\306\231\326\34" - "\347\236\367\0\0a\10\343\30e1\3479jR\14[mk\17\204q\224\364\244u\265\30\306" - "\232\326\33\347\236\367\0\0\201\10\343\30e)\7B\212J\354bms\360{\222\224\24" - "\235\225\265\30\276\232\316\34\347\236\367\0\0a\10\343\30f)\3479iJ\353Zm" - "s\357{\222\214\24\235\226\265\27\306\231\326\34\347\236\367\0\0a\10\343\30" - "e)\347AiR\14[nk\17|q\224\24\245\225\255\30\306\232\326\34\347\236\367\0\0" - "a\10\343\30e)\7:\212J\353bns\17\204q\224\24\235\225\255\30\306\232\326\34" - "\347\236\367\0\0a\10\343\40e)\3509\212J\13[\215s\20\204\222\214\24\245\225" - "\255\30\276\232\326\34\337\236\357\0\0a\10\343\30e)\3509iJ\353b\215s\360" - "\203\222\214\364\234u\265\27\306\231\326\34\347\236\367\0\0a\10\343\30e1" - "\7:iR\13cnk\357\203\221\214\23\245v\265\30\306\232\326\374\346\236\367\0" - "\0a\10\343\30\206)\3479iJ\353Zmk\20|\222\214\24\235\226\255\30\276\232\326" - "\33\347\236\367\0\0a\10\343\30e1\350AjR\13[\216k\17|q\224\23\235v\265\370" - "\305\232\326\34\347\236\357", -}; - - -namespace -{ - void ReplaceTexture(const Ogre::MaterialPtr& mat, const Ogre::String & texture) - { - // Now look for the texture - bool found = false; - unsigned short numTechniques = mat->getNumTechniques(); - for (unsigned short i = 0; i < numTechniques; ++i) - { - Ogre::Technique* tech = mat->getTechnique(i); - unsigned short numPasses = tech->getNumPasses(); - for (unsigned short j = 0; j < numPasses; ++j) - { - Ogre::Pass* pass = tech->getPass(j); - unsigned short numTUs = pass->getNumTextureUnitStates(); - for (unsigned short k = 0; k < numTUs; ++k) - { - found = true; - - Ogre::TextureUnitState* tu = pass->getTextureUnitState(k); - - tu->setTextureName(texture); - } - - if (found) break; - } - - if (found) break; - } - - assert(found); - } -} - - -TextureBlitTest::TextureBlitTest() -{ - mInfo["Title"] = "VTests_TextureBlit"; - mInfo["Description"] = "Tests texture blitting."; - addScreenshotFrame(50); -} -//--------------------------------------------------------------------------- - -void TextureBlitTest::setupContent() -{ - static const Ogre::String ColorTextureName = "VTests_TextureBlit_color_texture"; - static const Ogre::String DepthTextureName = "VTests_TextureBlit_depth_texture"; - static const int TextureSize = 8; - - mViewport->setBackgroundColour(ColourValue(0.8,0.8,0.8)); - - /// TEST COLOUR - m_colorTexture = Ogre::TextureManager::getSingleton().createManual( - ColorTextureName, - Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - Ogre::TEX_TYPE_2D, - TextureSize, TextureSize, - 0, - Ogre::PF_BYTE_RGB, - Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE); - - Ogre::PixelBox pb(ColorImage.width, ColorImage.height, 1, Ogre::PF_BYTE_RGB, (void *)ColorImage.pixel_data); - Ogre::HardwarePixelBufferSharedPtr buffer = m_colorTexture->getBuffer(); - buffer->blitFromMemory(pb); - - // Get the material - Ogre::MaterialPtr matColourPtr = Ogre::MaterialManager::getSingleton().getByName("Examples/OgreDance"); - - ReplaceTexture(matColourPtr, ColorTextureName); - - // create a standard plane entity - Entity* ent = mSceneMgr->createEntity("Plane_color", SceneManager::PT_PLANE); - - // attach it to a node, scale it, and position appropriately - SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - node->setPosition(-30.0, 0.0, 0.0); - node->setScale(0.25, 0.25, 0.25); - node->attachObject(ent); - - ent->setMaterial(matColourPtr); // give it the material we prepared - - /// TEST DEPTH - m_depthTexture = Ogre::TextureManager::getSingleton().createManual( - DepthTextureName, - Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, - Ogre::TEX_TYPE_2D, - TextureSize, TextureSize, - 0, - Ogre::PF_DEPTH16, - Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE); - - Ogre::PixelBox dpb(DepthImage.width, DepthImage.height, 1, Ogre::PF_DEPTH16, (void *)DepthImage.pixel_data); - Ogre::HardwarePixelBufferSharedPtr dbuffer = m_depthTexture->getBuffer(); - dbuffer->blitFromMemory(dpb); - - // Get the material - Ogre::MaterialPtr matDepthPtr = Ogre::MaterialManager::getSingleton().getByName("Examples/OgreParade"); - - ReplaceTexture(matDepthPtr, DepthTextureName); - - // create a standard plane entity - Entity* depthEnt = mSceneMgr->createEntity("Plane_depth", SceneManager::PT_PLANE); - - // attach it to a node, scale it, and position appropriately - SceneNode* depthNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); - depthNode->setPosition(30.0, 0.0, 0.0); - depthNode->setScale(0.25, 0.25, 0.25); - depthNode->attachObject(depthEnt); - - depthEnt->setMaterial(matDepthPtr); // give it the material we prepared - - mCameraNode->setPosition(0,0,125); - mCameraNode->setDirection(0,0,-1); -} -//----------------------------------------------------------------------- - - diff --git a/Tests/VisualTests/VTests/src/VTestPlugin.cpp b/Tests/VisualTests/VTests/src/VTestPlugin.cpp deleted file mode 100644 index 7a8ed95ce7d..00000000000 --- a/Tests/VisualTests/VTests/src/VTestPlugin.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "VTestPlugin.h" -#include "StencilShadowTest.h" -#include "ParticleTest.h" -#include "CubeMappingTest.h" -#include "TextureBlitTest.h" -#include "OgreResourceGroupManager.h" - -// samples as tests -#include "TextureFX.h" -#include "Transparency.h" - -VTestPlugin::VTestPlugin() - :SamplePlugin("VTestPlugin") -{ - // add the playpen tests - // addSample(new TextureBlitTest()); SEGFAULT reading depth texture - addSample(new CubeMappingTest()); - addSample(new ParticleTest()); - addSample(new StencilShadowTest()); - addSample(new Sample_TextureFX()); - addSample(new Sample_Transparency()); -} -//--------------------------------------------------------------------- - -VTestPlugin::~VTestPlugin() -{ - for (auto s : mSamples) - { - delete s; - } - mSamples.clear(); -} -//--------------------------------------------------------------------- - -#ifndef OGRE_STATIC_LIB - -static VTestPlugin* testPlugin = 0; - -extern "C" void _OgreSampleExport dllStartPlugin(void); -extern "C" void _OgreSampleExport dllStopPlugin(void); - -extern "C" _OgreSampleExport void dllStartPlugin() -{ - testPlugin = OGRE_NEW VTestPlugin(); - Ogre::Root::getSingleton().installPlugin(testPlugin); -} - -extern "C" _OgreSampleExport void dllStopPlugin() -{ - Ogre::Root::getSingleton().uninstallPlugin(testPlugin); - OGRE_DELETE testPlugin; -} - -#endif diff --git a/Tests/src/main.cpp b/Tests/src/main.cpp deleted file mode 100644 index 2b918bdc308..00000000000 --- a/Tests/src/main.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include - -#include "OgreLogManager.h" - -int main(int argc, char *argv[]) -{ - Ogre::LogManager* logMgr = new Ogre::LogManager(); - logMgr->createLog("OgreTest.log", true, false); - logMgr->setMinLogLevel(Ogre::LML_TRIVIAL); - - ::testing::InitGoogleTest(&argc, argv); - - return RUN_ALL_TESTS(); -} diff --git a/Tools/AssimpConverter/CMakeLists.txt b/Tools/AssimpConverter/CMakeLists.txt deleted file mode 100644 index 58c996f7ec4..00000000000 --- a/Tools/AssimpConverter/CMakeLists.txt +++ /dev/null @@ -1,18 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -add_executable(OgreAssimpConverter main.cpp) -target_link_libraries(OgreAssimpConverter OgreMain Codec_Assimp) -if (OGRE_PROJECT_FOLDERS) - set_property(TARGET OgreAssimpConverter PROPERTY FOLDER Tools) -endif () -ogre_config_tool(OgreAssimpConverter) - -set_property(TARGET OgreAssimpConverter PROPERTY - INSTALL_RPATH "$ORIGIN/../${OGRE_PLUGINS_PATH}") \ No newline at end of file diff --git a/Tools/AssimpConverter/main.cpp b/Tools/AssimpConverter/main.cpp deleted file mode 100644 index a9117e8565f..00000000000 --- a/Tools/AssimpConverter/main.cpp +++ /dev/null @@ -1,252 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of - _ - ___ __ _ _ __ ___ __ _ ___ ___(_)_ __ ___ _ __ - / _ \ / _` | '__/ _ \/ _` / __/ __| | '_ ` _ \| '_ \ -| (_) | (_| | | | __/ (_| \__ \__ \ | | | | | | |_) | - \___/ \__, |_| \___|\__,_|___/___/_|_| |_| |_| .__/ - |___/ |_| - -For the latest info, see https://bitbucket.org/jacmoe/ogreassimp - -Copyright (c) 2011 Jacob 'jacmoe' Moen - -Licensed under the MIT license: - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include - -#include "Ogre.h" -#include "OgreDefaultHardwareBufferManager.h" - -#include "OgreAssimpLoader.h" -#include - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM -#include -#endif - -using namespace Ogre; - -namespace -{ - -void help(void) -{ - std::cout << -R"HELP(Usage: OgreAssimpConverter [options] sourcefile [destination] - - Converts 3D-formats supported by assimp to native OGRE formats - -Available options: --q = Quiet mode, less output --log filename = name of the log file (default: 'OgreAssimp.log') --aniSpeedMod [0..1] = Factor to scale the animation speed (default: 1.0) --3ds_ani_fix = Fix for 3ds max, which exports the animation over a - longer time frame than the animation actually plays --max_edge_angle deg = When normals are generated, max angle between - two faces to smooth over -sourcefile = name of file to convert -destination = optional name of directory to write to. If you don't - specify this the converter will use the same - directory as the sourcefile. -)HELP"; -} - -struct AssOptions -{ - String source; - String dest; - String logFile; - - AssimpLoader::Options options; - - AssOptions() { logFile = "OgreAssimp.log"; }; -}; - -AssOptions parseArgs(int numArgs, char** args) -{ - AssOptions opts; - - // ignore program name - char* source = 0; - char* dest = 0; - - // Set up options - UnaryOptionList unOpt; - BinaryOptionList binOpt; - - unOpt["-q"] = false; - unOpt["-3ds_ani_fix"] = false; - binOpt["-log"] = opts.logFile; - binOpt["-aniName"] = ""; - binOpt["-aniSpeedMod"] = "1.0"; - binOpt["-max_edge_angle"] = "30"; - - int startIndex = findCommandLineOpts(numArgs, args, unOpt, binOpt); - - if (unOpt["-q"]) - { - opts.options.params |= AssimpLoader::LP_QUIET_MODE; - } - if (unOpt["-3ds_ani_fix"]) - { - opts.options.params |= AssimpLoader::LP_CUT_ANIMATION_WHERE_NO_FURTHER_CHANGE; - } - - opts.options.postProcessSteps = aiProcessPreset_TargetRealtime_Quality; - opts.logFile = binOpt["-log"]; - StringConverter::parse(binOpt["-aniSpeedMod"], opts.options.animationSpeedModifier); - opts.options.customAnimationName = binOpt["-aniName"]; - StringConverter::parse(binOpt["-max_edge_angle"], opts.options.maxEdgeAngle); - - // Source / dest - if (numArgs > startIndex) - source = args[startIndex]; - if (numArgs > startIndex + 1) - dest = args[startIndex + 1]; - if (numArgs > startIndex + 2) - { - LogManager::getSingleton().logError("Too many command-line arguments supplied"); - help(); - exit(1); - } - - if (!source) - { - LogManager::getSingleton().logError("Missing source file"); - help(); - exit(1); - } - opts.source = source; - - if (dest) - { - opts.dest = dest; - } - - if (!unOpt["-q"]) - { - std::cout << std::endl; - std::cout << "-- OPTIONS --" << std::endl; - - std::cout << "source file = " << opts.source << std::endl; - std::cout << "destination = " << opts.dest << std::endl; - std::cout << "animation speed modifier = " << opts.options.animationSpeedModifier << std::endl; - std::cout << "log file = " << opts.logFile << std::endl; - - std::cout << "-- END OPTIONS --" << std::endl; - std::cout << std::endl; - } - - return opts; -} -} // namespace - -int main(int numargs, char** args) -{ - if (numargs < 2) - { - help(); - return -1; - } - - // Assume success - int retCode = 0; - - LogManager logMgr; - // this log catches output from the parseArgs call and routes it to stdout only - logMgr.createLog("Temporary log", true, true, true); - AssOptions opts = parseArgs(numargs, args); - - try - { - logMgr.setDefaultLog(NULL); // swallow startup messages - Root root("", "", ""); - // get rid of the temporary log as we use the new log now - logMgr.destroyLog("Temporary log"); - - // use the log specified by the cmdline params - logMgr.setDefaultLog(logMgr.createLog(opts.logFile, false, true)); - - MaterialManager::getSingleton().initialise(); - -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - RTShader::ShaderGenerator::initialize(); -#endif - - DefaultHardwareBufferManager bufferManager; // needed because we don't have a rendersystem - DefaultTextureManager texMgr; - - String basename, ext, path; - StringUtil::splitFullFilename(opts.source, basename, ext, path); - - MeshPtr mesh = MeshManager::getSingleton().createManual(basename + "." + ext, RGN_DEFAULT); - SkeletonPtr skeleton; - - AssimpLoader loader; - loader.load(opts.source, mesh.get(), skeleton, opts.options); - - if (!opts.dest.empty()) - { - path = opts.dest + "/"; - } - - MeshSerializer meshSer; - meshSer.exportMesh(mesh, path + basename + ".mesh"); - - if (skeleton) - { - SkeletonSerializer binSer; - binSer.exportSkeleton(skeleton.get(), path + skeleton->getName()); - } - - // serialise the materials - std::set exportNames; - for (SubMesh* sm : mesh->getSubMeshes()) - exportNames.insert(sm->getMaterialName()); - - // queue up the materials for serialise - MaterialSerializer ms; -#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM - auto& shadergen = RTShader::ShaderGenerator::getSingleton(); - shadergen.setTargetLanguage("glsl"); // must be valid, but otherwise arbitrary - shadergen.getRenderState(MSN_SHADERGEN)->setLightCountAutoUpdate(false); - shadergen.validateScheme(MSN_SHADERGEN); - ms.addListener(shadergen.getMaterialSerializerListener()); -#endif - for (const String& name : exportNames) - ms.queueForExport(MaterialManager::getSingleton().getByName(name)); - - if (!exportNames.empty()) - ms.exportQueued(path + basename + ".material"); - - logMgr.setDefaultLog(NULL); // swallow shutdown messages - } - catch (Exception& e) - { - LogManager::getSingleton().logError(e.getDescription()); - retCode = 1; - } - - return retCode; -} diff --git a/Tools/CMakeLists.txt b/Tools/CMakeLists.txt deleted file mode 100644 index f6343618333..00000000000 --- a/Tools/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure Tools build - -# Tools can't be run on the iOS so don't build them -if (NOT APPLE_IOS AND NOT (WINDOWS_STORE OR WINDOWS_PHONE)) - add_subdirectory(XMLConverter) - add_subdirectory(VRMLConverter) - if(OGRE_BUILD_COMPONENT_MESHLODGENERATOR) - add_subdirectory(MeshUpgrader) - endif() - if(OGRE_BUILD_PLUGIN_ASSIMP) - add_subdirectory(AssimpConverter) - endif() -endif (NOT APPLE_IOS AND NOT (WINDOWS_STORE OR WINDOWS_PHONE)) diff --git a/Tools/LightwaveConverter/LWO2MESH.dsw b/Tools/LightwaveConverter/LWO2MESH.dsw deleted file mode 100644 index f89fddb21f6..00000000000 --- a/Tools/LightwaveConverter/LWO2MESH.dsw +++ /dev/null @@ -1,29 +0,0 @@ -Microsoft Developer Studio Workspace File, Format Version 6.00 -# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! - -############################################################################### - -Project: "LWO2MESH"=.\scripts\LWO2MESH.dsp - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ -}}} - -############################################################################### - -Global: - -Package=<5> -{{{ -}}} - -Package=<3> -{{{ -}}} - -############################################################################### - diff --git a/Tools/LightwaveConverter/LWO2MESH.sln b/Tools/LightwaveConverter/LWO2MESH.sln deleted file mode 100644 index 3ffd1f19d74..00000000000 --- a/Tools/LightwaveConverter/LWO2MESH.sln +++ /dev/null @@ -1,21 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 7.00 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Lwo2Mesh", "scripts\LWO2MESH.vcproj", "{3BDDA5EA-5C74-42E0-92C9-F5FC12463449}" -EndProject -Global - GlobalSection(SolutionConfiguration) = preSolution - ConfigName.0 = Debug - ConfigName.1 = Release - EndGlobalSection - GlobalSection(ProjectDependencies) = postSolution - EndGlobalSection - GlobalSection(ProjectConfiguration) = postSolution - {3BDDA5EA-5C74-42E0-92C9-F5FC12463449}.Debug.ActiveCfg = Debug|Win32 - {3BDDA5EA-5C74-42E0-92C9-F5FC12463449}.Debug.Build.0 = Debug|Win32 - {3BDDA5EA-5C74-42E0-92C9-F5FC12463449}.Release.ActiveCfg = Release|Win32 - {3BDDA5EA-5C74-42E0-92C9-F5FC12463449}.Release.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - EndGlobalSection - GlobalSection(ExtensibilityAddIns) = postSolution - EndGlobalSection -EndGlobal diff --git a/Tools/LightwaveConverter/Readme.md b/Tools/LightwaveConverter/Readme.md deleted file mode 100644 index cbc8e27f77a..00000000000 --- a/Tools/LightwaveConverter/Readme.md +++ /dev/null @@ -1,31 +0,0 @@ - -# LightwaveConverter -Lwo2Mesh v0.89 by Dennis Verbeek ( dennis.verbeek@chello.nl ) -Linux port by Magnus Møller Petersen ( magnus@moaner.dk ) - -Lwo2Mesh is a commandline tool to convert lightwave objects into ogre-meshes. -Use -? to get help. Use *.lwo to convert multiple objects in one run. - -``` -Usage: lwo2mesh [options] source [dest] -options: - -g do not use shared geometry - -d generate level of detail information - method (f)ixed or (p)roportional - reduction (fixed) or reductionfactor (proportional) - number of LOD levels - distances - example: -dp 0.5 4 1000.0 2000.0 4000.0 8000.0 - -l save layers separately - -m do not export materials - -r rename materials - method (i)nteractive, (o)bjectname or (p)refix - example: -rp prefix_ - -s do not export skeleton - -i info on .lwo only, no conversion to mesh - -v dump vertex maps -``` - -The lightwave-object loading code is based on Lightwave SDK code by Ernie Wright. - -This program is distributed as-is and WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. diff --git a/Tools/LightwaveConverter/include/BitArray.h b/Tools/LightwaveConverter/include/BitArray.h deleted file mode 100644 index 76d04b767cd..00000000000 --- a/Tools/LightwaveConverter/include/BitArray.h +++ /dev/null @@ -1,120 +0,0 @@ -#ifndef _BITARRAY_H_ -#define _BITARRAY_H_ - -class BitArray -{ -private: -/** The number of bits in this array - */ - unsigned long arraysize; - /** The number of unsigned longs for storing at least arraysize bits - */ - unsigned long bitlongs; - /** The array of unsigned longs containing the bits - */ - unsigned long *bits; -public: -/** Constructors. - */ - BitArray(unsigned long newsize); - BitArray(const BitArray& b); - - BitArray(unsigned long newsize, bool setclear); - BitArray(unsigned long newsize, unsigned long *newbits); - - /** Destructor. - */ - ~BitArray(); - - BitArray& operator =(const BitArray& b); - BitArray operator ~(void); - BitArray& operator ^=(const BitArray& b); - BitArray& operator &=(const BitArray& b); - BitArray& operator |=(const BitArray& b); - BitArray operator ^(const BitArray& b); - BitArray operator &(const BitArray& b); - BitArray operator |(const BitArray& b); - - /** Test to see if a single bit is set. - */ - inline bool bitSet(unsigned long index) const - { - return bits[(index>>5)] >> (index & 0x0000001f) & 0x00000001; - } - /** Clear all bits in this array. - */ - inline void clear(void) - { - fillBitArray(0x00000000); - } - /** Clear a single bit. - */ - inline void clearBit(unsigned long index) - { - bits[index >> 5] &= ~(0x00000001 << (index & 0x0000001f)); - } - /** fill with a 32-bit pattern. - */ - inline void fillBitArray(unsigned long pattern) - { - for (unsigned long i=0; i < bitlongs; bits[i++]=pattern); - } - - /** flip a single bit. - */ - inline void flipBit(unsigned long index) - { - if (bitSet(index)) - clearBit(index); - else - setBit(index); - }; - - /** Returns index of next set bit in array (wraps around) - */ - inline long getNextSet(unsigned long index) - { - unsigned long i; - for (i=index+1;i0;i--) if (bitSet(i)) return i; - if (bitSet(0)) return 0; - } - for (i=arraysize-1;i>index;i--) if (bitSet(i)) return i; - return -1; - } - - /** Set all bits in this array. - */ - inline void set(void) - { - fillBitArray(0xffffffff); - } - - /** Set a single bit. - */ - inline void setBit(unsigned long index) - { - bits[index >> 5] |= 0x00000001 << (index & 0x0000001f); - } - - /** return the number of bits in this bit array.. - */ - inline unsigned long size(void) - { - return arraysize; - } -}; - -#endif // _BITARRAY_H_ - diff --git a/Tools/LightwaveConverter/include/Point.h b/Tools/LightwaveConverter/include/Point.h deleted file mode 100644 index a86c805df0b..00000000000 --- a/Tools/LightwaveConverter/include/Point.h +++ /dev/null @@ -1,94 +0,0 @@ -#ifndef _POINT_H_ -#define _POINT_H_ - -#include "lwo.h" -#include "Vector3.h" - -using namespace std; - -class Point3 { - public: - inline Point3() {} - - inline Point3(float nx, float ny, float nz) : x(nx), y(ny), z(nz) {} - - inline Point3& operator =(const Vector3& v) - { - x = v.x; - y = v.y; - z = v.z; - return (*this); - } - - inline Point3& operator *=(float t) - { - x *= t; - y *= t; - z *= t; - return (*this); - } - - inline Point3& operator /=(float t) - { - float f = 1.0F / t; - x *= f; - y *= f; - z *= f; - return (*this); - } - - inline bool operator == ( const Point3& p ) const - { - return ( x == p.x && y == p.y && z == p.z ); - } - - inline bool operator != ( const Point3& p ) const - { - return ( x != p.x || y != p.y || z != p.z ); - } - - inline Point3 operator -(void) const - { - return (Point3(-x, -y, -z)); - } - - // Sum of point and vector (direction) is a point - inline Point3 operator +(const Vector3& v) const - { - return (Point3(x + v.x, y + v.y, z + v.z)); - } - - // Difference of point and vector (direction) is a point - inline Point3 operator -(const Vector3& v) const - { - return (Point3(x - v.x, y - v.y, z - v.z)); - } - - // Difference between to points is a vector (direction) - inline Vector3 operator -(const Point3& p) const - { - return (Vector3(x - p.x, y - p.y, z - p.z)); - } - - inline Point3 operator *(float t) const - { - return (Point3(x * t, y * t, z * t)); - } - - inline Point3 operator /(float t) const - { - float f = 1.0F / t; - return (Point3(x * f, y * f, z * f)); - } - - // Dot product - inline float operator *(const Vector3& v) const - { - return (x * v.x + y * v.y + z * v.z); - } - - float x, y, z; -}; - -#endif // _POINT_H_ - diff --git a/Tools/LightwaveConverter/include/Vector3.h b/Tools/LightwaveConverter/include/Vector3.h deleted file mode 100644 index 54cde5779e9..00000000000 --- a/Tools/LightwaveConverter/include/Vector3.h +++ /dev/null @@ -1,219 +0,0 @@ -#ifndef _VECTOR3_H_ -#define _VECTOR3_H_ - -#include "math.h" - -class Vector3 -{ -public: - float x, y, z; - - inline Vector3() {} - - inline Vector3( float nx, float ny, float nz ) : x(nx), y(ny), z(nz) {} - - inline Vector3( float v[3] ) : x(v[0]), y(v[1]), z(v[2]) {} - - inline Vector3( int v[3] ): x((float)v[0]), y((float)v[1]), z((float)v[2]) {} - - inline Vector3( const float* const v ) : x(v[0]), y(v[1]), z(v[2]) {} - - inline Vector3( const Vector3& v ) : x(v.x), y(v.y), z(v.z) {} - - inline float operator [] ( unsigned i ) const - { - return *(&x+i); - } - - inline float& operator [] ( unsigned i ) - { - return *(&x+i); - } - - inline Vector3& operator = ( const Vector3& v ) - { - x = v.x; - y = v.y; - z = v.z; - - return *this; - } - - inline bool operator == ( const Vector3& v ) const - { - return ( x == v.x && y == v.y && z == v.z ); - } - - inline bool operator != ( const Vector3& v ) const - { - return ( x != v.x || y != v.y || z != v.z ); - } - - // arithmetic operations - inline Vector3 operator + ( const Vector3& v ) const - { - return Vector3(x + v.x, y + v.y, z + v.z); - } - - inline Vector3 operator - ( const Vector3& v ) const - { - return Vector3(x - v.x, y - v.y, z - v.z); - } - - inline Vector3 operator * ( float f ) const - { - return Vector3(x * f, y * f, z * f); - } - - inline Vector3 operator * ( const Vector3& v) const - { - return Vector3(x * v.x, y * v.y, z * v.z); - } - - inline Vector3 operator / ( float f ) const - { - f = 1.0f / f; - return Vector3(x * f, y * f, z * f); - } - - inline Vector3 operator - () const - { - return Vector3( -x, -y, -z); - } - - inline friend Vector3 operator * ( float f, const Vector3& v ) - { - return Vector3(f * v.x, f * v.y, f * v.z); - } - - // arithmetic updates - inline Vector3& operator += ( const Vector3& v ) - { - x += v.x; - y += v.y; - z += v.z; - - return *this; - } - - inline Vector3& operator -= ( const Vector3& v ) - { - x -= v.x; - y -= v.y; - z -= v.z; - - return *this; - } - - inline Vector3& operator *= ( float f ) - { - x *= f; - y *= f; - z *= f; - return *this; - } - - inline Vector3& operator /= ( float f ) - { - f = 1.0f / f; - - x *= f; - y *= f; - z *= f; - - return *this; - } - - inline float length () const - { - return (float)sqrt( x * x + y * y + z * z ); - } - - inline float squaredLength () const - { - return x * x + y * y + z * z; - } - - inline float dotProduct(const Vector3& v) const - { - return x * v.x + y * v.y + z * v.z; - } - - inline Vector3 & normalise() - { - float f = (float)sqrt( x * x + y * y + z * z ); - - // Will also work for zero-sized vectors, but will change nothing - if ( f > 1e-06f ) - { - f = 1.0f / f; - x *= f; - y *= f; - z *= f; - } - - return *this; - } - - inline Vector3 crossProduct( const Vector3& v ) const - { - return Vector3(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x); - } - - inline Vector3 midPoint( const Vector3& v ) const - { - return Vector3( ( x + v.x ) * 0.5f, ( y + v.y ) * 0.5f, ( z + v.z ) * 0.5f ); - } - - inline bool operator < ( const Vector3& v ) const - { - return ( x < v.x && y < v.y && z < v.z ); - } - - inline bool operator > ( const Vector3& v ) const - { - return ( x > v.x && y > v.y && z > v.z ); - } - - inline void makeFloor( const Vector3& v ) - { - if( v.x < x ) x = v.x; - if( v.y < y ) y = v.y; - if( v.z < z ) z = v.z; - } - - inline void makeCeil( const Vector3& v ) - { - if( v.x > x ) x = v.x; - if( v.y > y ) y = v.y; - if( v.z > z ) z = v.z; - } - - inline Vector3 perpendicular(void) - { - static float fSquareZero = 1e-06f * 1e-06f; - - Vector3 perp = this->crossProduct( Vector3::UNIT_X ); - - // Check length - if( perp.squaredLength() < fSquareZero ) - { - /* This vector is the Y axis multiplied by a scalar, so we have - to use another axis. - */ - perp = this->crossProduct( Vector3::UNIT_Y ); - } - - return perp; - } - - // special points - static const Vector3 ZERO; - static const Vector3 UNIT_X; - static const Vector3 UNIT_Y; - static const Vector3 UNIT_Z; - static const Vector3 UNIT_SCALE; -}; - -#endif // _VECTOR3_H_ - diff --git a/Tools/LightwaveConverter/include/lwClip.h b/Tools/LightwaveConverter/include/lwClip.h deleted file mode 100644 index 8f3ea99ea6f..00000000000 --- a/Tools/LightwaveConverter/include/lwClip.h +++ /dev/null @@ -1,159 +0,0 @@ -#ifndef _LWCLIP_H_ -#define _LWCLIP_H_ - -class lwClipStill -{ -public: - lwClipStill() - { - name = 0; - } - ~lwClipStill() - { - if (name) free(name); - } - char *name; -}; - -class lwClipSeq -{ -public: - lwClipSeq() - { - prefix = 0; - suffix = 0; - } - ~lwClipSeq() - { - if (prefix) free(prefix); - if (suffix) free(suffix); - } - char *prefix; /* filename before sequence digits */ - char *suffix; /* after digits, e.g. extensions */ - int digits; - int flags; - int offset; - int start; - int end; -}; - -class lwClipAnim -{ -public: - lwClipAnim() - { - name = 0; - server = 0; - data = 0; - } - ~lwClipAnim() - { - if (name) free(name); - if (server) free(server); - if (data) free(data); - } - char *name; - char *server; /* anim loader plug-in */ - void *data; -}; - -class lwClipXRef -{ -public: - lwClipXRef() - { - string = 0; - clip = 0; - } - ~lwClipXRef() - { - if (string) free(string); - } - - char *string; - int index; - class lwClip *clip; -}; - -class lwClipCycle { -public: - lwClipCycle() - { - name = 0; - } - ~lwClipCycle() - { - if (name) free(name); - } - char *name; - int lo; - int hi; -}; - -class lwClip { -public: - lwClip() - { - source.still = 0; - contrast.val = 1.0f; - brightness.val = 1.0f; - saturation.val = 1.0f; - gamma.val = 1.0f; - } - - ~lwClip() - { - unsigned int i; - for (i=0; i < ifilters.size(); delete ifilters[i++]); - for (i=0; i < pfilters.size(); delete pfilters[i++]); - - if (source.still) - { - switch (type) - { - case ID_STIL: - delete source.still; - break; - case ID_ISEQ: - delete source.seq; - break; - case ID_ANIM: - delete source.anim; - break; - case ID_XREF: - delete source.xref; - break; - case ID_STCC: - delete source.cycle; - break; - default: - ; - } - } - } - int index; - unsigned int type; /* ID_STIL, ID_ISEQ, etc. */ - union { - lwClipStill *still; - lwClipSeq *seq; - lwClipAnim *anim; - lwClipXRef *xref; - lwClipCycle *cycle; - } source; - float start_time; - float duration; - float frame_rate; - lwEParam contrast; - lwEParam brightness; - lwEParam saturation; - lwEParam hue; - lwEParam gamma; - int negative; - vplugins ifilters; /* linked list of image filters */ - vplugins pfilters; /* linked list of pixel filters */ -}; - -typedef vector vclips; - -#endif // _LWCLIP_H_ - diff --git a/Tools/LightwaveConverter/include/lwEnvelope.h b/Tools/LightwaveConverter/include/lwEnvelope.h deleted file mode 100644 index b9462521189..00000000000 --- a/Tools/LightwaveConverter/include/lwEnvelope.h +++ /dev/null @@ -1,74 +0,0 @@ -#ifndef _LWENVELOPE_H_ -#define _LWENVELOPE_H_ - -#include "lwo.h" - -#include - -class lwKey -{ -public: - lwKey(float ntime, float nvalue) : time(ntime), value(nvalue) {} - float time; - float value; - unsigned int shape; /* ID_TCB, ID_BEZ2, etc. */ - float tension; - float continuity; - float bias; - float param[ 4 ]; -}; - -typedef vector vkeys; - -inline bool operator < (const lwKey &k1, const lwKey &k2) -{ - return k1.time < k2.time; -} - -#define BEH_RESET 0 -#define BEH_CONSTANT 1 -#define BEH_REPEAT 2 -#define BEH_OSCILLATE 3 -#define BEH_OFFSET 4 -#define BEH_LINEAR 5 - -class lwEnvelope -{ - float range( float v, float lo, float hi, int *i ); - void hermite( float t, float *h1, float *h2, float *h3, float *h4 ); - float bezier( float x0, float x1, float x2, float x3, float t ); - float bez2_time( float x0, float x1, float x2, float x3, float time, float *t0, float *t1 ); - float bez2( lwKey *key0, lwKey *key1, float time ); - float outgoing( unsigned int key0, unsigned int key1 ); - float incoming( unsigned int key0, unsigned int key1 ); - -public: - lwEnvelope() - { - name = 0; - } - - ~lwEnvelope() - { - if (name) free(name); - unsigned int i; - for (i=0; i venvelopes; - -#endif // _LWENVELOPE_H_ - diff --git a/Tools/LightwaveConverter/include/lwLayer.h b/Tools/LightwaveConverter/include/lwLayer.h deleted file mode 100644 index c79507735a2..00000000000 --- a/Tools/LightwaveConverter/include/lwLayer.h +++ /dev/null @@ -1,52 +0,0 @@ -#ifndef _LWLAYER_H_ -#define _LWLAYER_H_ - -#include "lwo.h" -#include "lwPolygon.h" - -class lwLayer { -public: - lwLayer() - { - name = 0; - pointsoffset = 0; - polygonsoffset = 0; - } - - ~lwLayer() - { - if (name) free(name); - unsigned int i; - for (i=0; i < points.size(); delete points[i++]); - for (i=0; i < polygons.size(); delete polygons[i++]); - for (i=0; i < vmaps.size(); delete vmaps[i++]); - } - - void lwResolveVertexPoints(void); - void lwGetPointPolygons(void); - void calculatePolygonNormals(void); - void triangulatePolygons(void); - void lwGetPointVMaps(void); - void lwGetPolyVMaps(void); - void lwGetBoundingBox(void); - void calculateVertexNormals(void); - int lwResolvePolySurfaces( vsurfaces &surfaces, vtags &tags ); - - char *name; - int index; - int parent; - int flags; - Point3 pivot; - Point3 bboxmin; - Point3 bboxmax; - int pointsoffset; /* only used during reading */ - vpoints points; /* array of points */ - int polygonsoffset; /* only used during reading */ - vpolygons polygons; /* array of polygons */ - vvmaps vmaps; /* linked list of vmaps */ -}; - -typedef vector vlayers; - -#endif // _LWLAYER_H_ - diff --git a/Tools/LightwaveConverter/include/lwObject.h b/Tools/LightwaveConverter/include/lwObject.h deleted file mode 100644 index 3a8a26d4d24..00000000000 --- a/Tools/LightwaveConverter/include/lwObject.h +++ /dev/null @@ -1,64 +0,0 @@ -#ifndef _LWOBJECT_H_ -#define _LWOBJECT_H_ - -#include "lwo.h" -#include "lwEnvelope.h" -#include "lwClip.h" -#include "lwLayer.h" - -class lwObject -{ -public: - lwObject() - { - tagsoffset = 0; - } - - ~lwObject() - { - unsigned int i; - - for (i=0; i < layers.size(); delete layers[i++]); - for (i=0; i < envelopes.size(); delete envelopes[i++]); - for (i=0; i < clips.size(); delete clips[i++]); - for (i=0; i < surfaces.size(); i++) - { - lwSurface *s = surfaces[i]; - if(s) - { - for (unsigned int j = i+1; j < surfaces.size(); j++) - if (s == surfaces[j]) surfaces[j] = 0; - delete s; - } - } - for (i=0; i < tags.size(); free(tags[i++])); - } - - lwClip *lwFindClip( int index ) - { - for (unsigned int i = 0; i < clips.size(); i++) - if (clips[i]->index == index) - return clips[i]; - return 0; - } - - lwEnvelope *lwFindEnvelope( int index ) - { - for (unsigned int i = 0; i < envelopes.size(); i++) - if (envelopes[i]->index == index) - return envelopes[i]; - return 0; - } - - vlayers layers; /* linked list of layers */ - venvelopes envelopes; /* linked list of envelopes */ - vclips clips; /* linked list of clips */ - vsurfaces surfaces; /* linked list of surfaces */ - int tagsoffset; - vtags tags; /* array of strings */ -}; - -typedef vector vobjects; - -#endif // _LWOBJECT_H_ - diff --git a/Tools/LightwaveConverter/include/lwPolygon.h b/Tools/LightwaveConverter/include/lwPolygon.h deleted file mode 100644 index 6eba9fd5f4e..00000000000 --- a/Tools/LightwaveConverter/include/lwPolygon.h +++ /dev/null @@ -1,45 +0,0 @@ -#ifndef _LWPOLYGON_H_ -#define _LWPOLYGON_H_ - -#include "lwo.h" - -class lwPolygon { -public: - lwPolygon() - { - } - - lwPolygon(const lwPolygon &p) - { - surface = p.surface; - surfidx = p.surfidx; - part = p.part; - smoothgrp = p.smoothgrp; - flags = p.flags; - type = p.type; - normal = p.normal; - } - - ~lwPolygon() - { - for (unsigned int i=0; i < vertices.size(); delete vertices[i++]); - } - - Vector3 &calculateNormal(void); - vpolygons triangulate(void); - void flip(void); -private: - lwPolygon *makeTriangle(long ia, long ib, long ic); -public: - lwSurface *surface; - int surfidx; /* surface index */ - int part; /* part index */ - int smoothgrp; /* smoothing group */ - int flags; - unsigned int type; - Vector3 normal; - vvertices vertices; /* array of vertex records */ -}; - -#endif // _LWPOLYGON_H_ - diff --git a/Tools/LightwaveConverter/include/lwReader.h b/Tools/LightwaveConverter/include/lwReader.h deleted file mode 100644 index 20695c644c2..00000000000 --- a/Tools/LightwaveConverter/include/lwReader.h +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef _LWREADER_H_ -#define _LWREADER_H_ - -#include "lwo.h" -#include "lwObject.h" -#include -#include - -class lwReader -{ -public: - lwObject *readObjectFromFile( const char *nfilename); - lwObject *readObjectFromStream( istream *nis); -private: - istream *is; - unsigned long chunksize; - unsigned long currentchunkid; - unsigned long formsize; - unsigned long flen; - - bool *flags; - - lwObject *lwGetLWLO(); - lwObject *lwGetLWO2(); - - int lwGetPoints( vpoints &points ); - int lwGetPolygons( vpolygons &polygons, int ptoffset ); - int lwGetLWOBPolygons( vpolygons &polygons, int ptoffset ); - int lwGetTags( vtags &tags ); - int lwGetPolygonTags( vtags &tags, int tagsoffset, vpolygons &polygons, int polygonsoffset ); - lwVMap *lwGetVMap( int ptoffset, int poloffset, int perpoly ); - lwClip *lwGetClip(); - lwEnvelope *lwGetEnvelope(); - int lwGetTHeader( int hsz, lwTexture &tex ); - int lwGetTMap( int tmapsz, lwTMap &tmap ); - lwImageMap *lwGetImageMap( int rsz, lwTexture &tex ); - lwProcedural *lwGetProcedural( int rsz, lwTexture &tex ); - lwGradient *lwGetGradient( int rsz, lwTexture &tex ); - lwTexture *lwGetTexture( int bloksz, unsigned int type ); - lwPlugin *lwGetShader( int bloksz ); - lwSurface *lwGetSurface(); - lwSurface *lwGetLWOBSurface( lwObject *obj ); - - int add_clip( char *s, vclips &clips ); - int add_tvel( float pos[], float vel[], venvelopes &envelopes ); - lwTexture *get_texture( char *s ); - - char *getbytes( int size ); - void skipbytes( int n ); - short getI2(); - long getI4(); - unsigned char getU1(); - unsigned short getU2(); - unsigned long getU4(); - int getVX(); - float getF4(); - char *getS0(); - short sgetI2( char **bp ); - long sgetI4( char **bp ); - unsigned char sgetU1( char **bp ); - unsigned short sgetU2( char **bp ); - unsigned long sgetU4( char **bp ); - int sgetVX( char **bp ); - float sgetF4( char **bp ); - char *sgetS0( char **bp ); - - unsigned short swappedShort(unsigned short w); - unsigned long swappedLong(unsigned long w); - void revbytes( void *bp, int elsize, int elcount ); -}; - -#endif // _LWREADER_H_ - diff --git a/Tools/LightwaveConverter/include/lwo.h b/Tools/LightwaveConverter/include/lwo.h deleted file mode 100644 index dd481033211..00000000000 --- a/Tools/LightwaveConverter/include/lwo.h +++ /dev/null @@ -1,734 +0,0 @@ -/* - -Lightwave Object Loader -(LWOB, LWLO, LWO2) - -converted by Dennis Verbeek (dennis.verbeek@chello.nl) - -These files were originally coded by Ernie Wright and were included in the -Lightwave SDK. -*/ - -#ifndef _LWO_H_ -#define _LWO_H_ - -#include -#include -#include -#include -#include "Point.h" - -//using namespace std; - -/* chunk and subchunk IDs */ - -#define LWID_(a,b,c,d) (((a)<<24)|((b)<<16)|((c)<<8)|(d)) - -#define ID_FORM LWID_('F','O','R','M') -#define ID_LWO2 LWID_('L','W','O','2') -#define ID_LWOB LWID_('L','W','O','B') -#define ID_LWLO LWID_('L','W','L','O') - -/* top-level chunks */ -#define ID_LAYR LWID_('L','A','Y','R') -#define ID_TAGS LWID_('T','A','G','S') -#define ID_PNTS LWID_('P','N','T','S') -#define ID_BBOX LWID_('B','B','O','X') -#define ID_VMAP LWID_('V','M','A','P') -#define ID_VMAD LWID_('V','M','A','D') -#define ID_POLS LWID_('P','O','L','S') -#define ID_PTAG LWID_('P','T','A','G') -#define ID_ENVL LWID_('E','N','V','L') -#define ID_CLIP LWID_('C','L','I','P') -#define ID_SURF LWID_('S','U','R','F') -#define ID_DESC LWID_('D','E','S','C') -#define ID_TEXT LWID_('T','E','X','T') -#define ID_ICON LWID_('I','C','O','N') - -/* polygon types */ -#define ID_FACE LWID_('F','A','C','E') -#define ID_CURV LWID_('C','U','R','V') -#define ID_PTCH LWID_('P','T','C','H') -#define ID_MBAL LWID_('M','B','A','L') -#define ID_BONE LWID_('B','O','N','E') - -/* polygon tags */ -#define ID_SURF LWID_('S','U','R','F') -#define ID_PART LWID_('P','A','R','T') -#define ID_SMGP LWID_('S','M','G','P') - -/* envelopes */ -#define ID_PRE LWID_('P','R','E',' ') -#define ID_POST LWID_('P','O','S','T') -#define ID_KEY LWID_('K','E','Y',' ') -#define ID_SPAN LWID_('S','P','A','N') -#define ID_TCB LWID_('T','C','B',' ') -#define ID_HERM LWID_('H','E','R','M') -#define ID_BEZI LWID_('B','E','Z','I') -#define ID_BEZ2 LWID_('B','E','Z','2') -#define ID_LINE LWID_('L','I','N','E') -#define ID_STEP LWID_('S','T','E','P') - -/* clips */ -#define ID_STIL LWID_('S','T','I','L') -#define ID_ISEQ LWID_('I','S','E','Q') -#define ID_ANIM LWID_('A','N','I','M') -#define ID_XREF LWID_('X','R','E','F') -#define ID_STCC LWID_('S','T','C','C') -#define ID_TIME LWID_('T','I','M','E') -#define ID_CONT LWID_('C','O','N','T') -#define ID_BRIT LWID_('B','R','I','T') -#define ID_SATR LWID_('S','A','T','R') -#define ID_HUE LWID_('H','U','E',' ') -#define ID_GAMM LWID_('G','A','M','M') -#define ID_NEGA LWID_('N','E','G','A') -#define ID_IFLT LWID_('I','F','L','T') -#define ID_PFLT LWID_('P','F','L','T') - -/* surfaces */ -#define ID_COLR LWID_('C','O','L','R') -#define ID_LUMI LWID_('L','U','M','I') -#define ID_DIFF LWID_('D','I','F','F') -#define ID_SPEC LWID_('S','P','E','C') -#define ID_GLOS LWID_('G','L','O','S') -#define ID_REFL LWID_('R','E','F','L') -#define ID_RFOP LWID_('R','F','O','P') -#define ID_RIMG LWID_('R','I','M','G') -#define ID_RSAN LWID_('R','S','A','N') -#define ID_TRAN LWID_('T','R','A','N') -#define ID_TROP LWID_('T','R','O','P') -#define ID_TIMG LWID_('T','I','M','G') -#define ID_RIND LWID_('R','I','N','D') -#define ID_TRNL LWID_('T','R','N','L') -#define ID_BUMP LWID_('B','U','M','P') -#define ID_SMAN LWID_('S','M','A','N') -#define ID_SIDE LWID_('S','I','D','E') -#define ID_CLRH LWID_('C','L','R','H') -#define ID_CLRF LWID_('C','L','R','F') -#define ID_ADTR LWID_('A','D','T','R') -#define ID_SHRP LWID_('S','H','R','P') -#define ID_LINE LWID_('L','I','N','E') -#define ID_LSIZ LWID_('L','S','I','Z') -#define ID_ALPH LWID_('A','L','P','H') -#define ID_AVAL LWID_('A','V','A','L') -#define ID_GVAL LWID_('G','V','A','L') -#define ID_BLOK LWID_('B','L','O','K') - -/* texture layer */ -#define ID_TYPE LWID_('T','Y','P','E') -#define ID_CHAN LWID_('C','H','A','N') -#define ID_NAME LWID_('N','A','M','E') -#define ID_ENAB LWID_('E','N','A','B') -#define ID_OPAC LWID_('O','P','A','C') -#define ID_FLAG LWID_('F','L','A','G') -#define ID_PROJ LWID_('P','R','O','J') -#define ID_STCK LWID_('S','T','C','K') -#define ID_TAMP LWID_('T','A','M','P') - -/* texture coordinates */ -#define ID_TMAP LWID_('T','M','A','P') -#define ID_AXIS LWID_('A','X','I','S') -#define ID_CNTR LWID_('C','N','T','R') -#define ID_SIZE LWID_('S','I','Z','E') -#define ID_ROTA LWID_('R','O','T','A') -#define ID_OREF LWID_('O','R','E','F') -#define ID_FALL LWID_('F','A','L','L') -#define ID_CSYS LWID_('C','S','Y','S') - -/* image map */ -#define ID_IMAP LWID_('I','M','A','P') -#define ID_IMAG LWID_('I','M','A','G') -#define ID_WRAP LWID_('W','R','A','P') -#define ID_WRPW LWID_('W','R','P','W') -#define ID_WRPH LWID_('W','R','P','H') -#define ID_VMAP LWID_('V','M','A','P') -#define ID_AAST LWID_('A','A','S','T') -#define ID_PIXB LWID_('P','I','X','B') - -/* procedural */ -#define ID_PROC LWID_('P','R','O','C') -#define ID_COLR LWID_('C','O','L','R') -#define ID_VALU LWID_('V','A','L','U') -#define ID_FUNC LWID_('F','U','N','C') -#define ID_FTPS LWID_('F','T','P','S') -#define ID_ITPS LWID_('I','T','P','S') -#define ID_ETPS LWID_('E','T','P','S') - -/* gradient */ -#define ID_GRAD LWID_('G','R','A','D') -#define ID_GRST LWID_('G','R','S','T') -#define ID_GREN LWID_('G','R','E','N') -#define ID_PNAM LWID_('P','N','A','M') -#define ID_INAM LWID_('I','N','A','M') -#define ID_GRPT LWID_('G','R','P','T') -#define ID_FKEY LWID_('F','K','E','Y') -#define ID_IKEY LWID_('I','K','E','Y') - -/* shader */ -#define ID_SHDR LWID_('S','H','D','R') -#define ID_DATA LWID_('D','A','T','A') - -/* IDs specific to LWOB */ -#define ID_SRFS LWID_('S','R','F','S') -#define ID_FLAG LWID_('F','L','A','G') -#define ID_VLUM LWID_('V','L','U','M') -#define ID_VDIF LWID_('V','D','I','F') -#define ID_VSPC LWID_('V','S','P','C') -#define ID_RFLT LWID_('R','F','L','T') -#define ID_BTEX LWID_('B','T','E','X') -#define ID_CTEX LWID_('C','T','E','X') -#define ID_DTEX LWID_('D','T','E','X') -#define ID_LTEX LWID_('L','T','E','X') -#define ID_RTEX LWID_('R','T','E','X') -#define ID_STEX LWID_('S','T','E','X') -#define ID_TTEX LWID_('T','T','E','X') -#define ID_TFLG LWID_('T','F','L','G') -#define ID_TSIZ LWID_('T','S','I','Z') -#define ID_TCTR LWID_('T','C','T','R') -#define ID_TFAL LWID_('T','F','A','L') -#define ID_TVEL LWID_('T','V','E','L') -#define ID_TCLR LWID_('T','C','L','R') -#define ID_TVAL LWID_('T','V','A','L') -#define ID_TAMP LWID_('T','A','M','P') -#define ID_TIMG LWID_('T','I','M','G') -#define ID_TAAS LWID_('T','A','A','S') -#define ID_TREF LWID_('T','R','E','F') -#define ID_TOPC LWID_('T','O','P','C') -#define ID_SDAT LWID_('S','D','A','T') -#define ID_TFP0 LWID_('T','F','P','0') -#define ID_TFP1 LWID_('T','F','P','1') - -/* Unknown tags */ - -#define ID_TFP2 LWID_('T','F','P','2') -#define ID_TFP3 LWID_('T','F','P','3') -#define ID_SHCP LWID_('S','H','C','P') -#define ID_CRVS LWID_('C','R','V','S') - -/* plug-in reference */ - -class lwPlugin -{ -public: - lwPlugin() - { - ord = 0; - name = 0; - data = 0; - } - - ~lwPlugin() - { - if (ord) free(ord); - if (name) free(name); - if (data) free(data); - } - - char *ord; - char *name; - int flags; - void *data; -}; - -typedef vector vplugins; - -inline bool operator < (const lwPlugin &p1, const lwPlugin &p2 ) -{ - return strcmp( p1.ord, p2.ord ) < 0; -} - -class lwEParam -{ -public: - lwEParam() - { - val = 0.0f; - eindex = 0; - } - float val; - int eindex; -}; - -class lwVParam -{ -public: - lwVParam() - { - val[0] = val[1] = val[2] = 0.0f; - eindex = 0; - } - float val[ 3 ]; - int eindex; -}; - - -/* clips */ - -/* textures */ - -class lwTMap { -public: - lwTMap() - { - ref_object = 0; - } - - ~lwTMap() - { - if (ref_object) free(ref_object); - } - lwVParam size; - lwVParam center; - lwVParam rotate; - lwVParam falloff; - int fall_type; - char *ref_object; - int coord_sys; -}; - -class lwImageMap { -public: - lwImageMap() - { - vmap_name = 0; - } - - ~lwImageMap() - { - if (vmap_name) free(vmap_name); - } - - int cindex; - int projection; - char *vmap_name; - int axis; - int wrapw_type; - int wraph_type; - lwEParam wrapw; - lwEParam wraph; - float aa_strength; - int aas_flags; - int pblend; - lwEParam stck; - lwEParam amplitude; -}; - -#define PROJ_PLANAR 0 -#define PROJ_CYLINDRICAL 1 -#define PROJ_SPHERICAL 2 -#define PROJ_CUBIC 3 -#define PROJ_FRONT 4 - -#define WRAP_NONE 0 -#define WRAP_EDGE 1 -#define WRAP_REPEAT 2 -#define WRAP_MIRROR 3 - -class lwProcedural { -public: - lwProcedural() - { - name = 0; - data = 0; - } - - ~lwProcedural() - { - if (name) free(name); - if (data) free(data); - } - - int axis; - float value[ 3 ]; - char *name; - void *data; -}; - -class lwGradKey { -public: - float value; - float rgba[ 4 ]; -}; - -class lwGradient { -public: - lwGradient() - { - paramname = 0; - itemname = 0; - key = 0; - ikey = 0; - } - - ~lwGradient() - { - if (paramname) free(paramname); - if (itemname) free(itemname); - if (key) free(key); - if (ikey) free(ikey); - } - - char *paramname; - char *itemname; - float start; - float end; - int repeat; - lwGradKey *key; /* array of gradient keys */ - short *ikey; /* array of interpolation codes */ -} ; - -class lwTexture -{ -public: - lwTexture() - { - ord = 0; - param.imap = 0; - - tmap.size.val[ 0 ] = - tmap.size.val[ 1 ] = - tmap.size.val[ 2 ] = 1.0f; - opacity.val = 1.0f; - enabled = 1; - } - - ~lwTexture() - { - if (ord) free(ord); - if(param.imap) - { - switch (type) - { - case ID_IMAP: - delete param.imap; - break; - case ID_PROC: - delete param.proc; - break; - case ID_GRAD: - delete param.grad; - break; - default: - ; - } - } - } - char *ord; - unsigned int type; - unsigned int chan; - lwEParam opacity; - short opac_type; - short enabled; - short negative; - short axis; - union - { - lwImageMap *imap; - lwProcedural *proc; - lwGradient *grad; - } param; - lwTMap tmap; -}; - -typedef vector vtextures; - -/* values that can be textured */ - -class lwTParam -{ -public: - lwTParam() - { - val = 0; - eindex = 0; - } - - ~lwTParam() - { - for (unsigned int i=0; i < textures.size(); delete textures[i++]); - } - - void addTexture( lwTexture *tex ) - { - textures.insert(lower_bound(textures.begin(), textures.end(), tex), tex); - } - - float val; - int eindex; - vtextures textures; /* linked list of texture layers */ -}; - -class lwCParam -{ -public: - lwCParam() - { - rgb[0] = 0.78431f; - rgb[1] = 0.78431f; - rgb[2] = 0.78431f; - eindex = 0; - } - - ~lwCParam() - { - for (unsigned int i=0; i < textures.size(); delete textures[i++]); - } - - void addTexture( lwTexture *tex ) - { - textures.insert(lower_bound(textures.begin(), textures.end(), tex), tex); - } - - float rgb[ 3 ]; - int eindex; - vtextures textures; /* linked list of texture layers */ -}; - - -/* surfaces */ - -class lwGlow -{ -public: - short enabled; - short type; - lwEParam intensity; - lwEParam size; -}; - -class lwRMap -{ -public: - lwRMap() - { - options = 0; - cindex = 0; - seam_angle = 0.0f; - } - lwTParam val; - int options; - int cindex; - float seam_angle; -}; - -class lwLine -{ -public: - short enabled; - unsigned short flags; - lwEParam size; -}; - -class lwSurface -{ -public: - lwSurface() - { - name = 0; - srcname = 0; - diffuse.val = 1.0f; - glossiness.val = 0.4f; - bump.val = 1.0f; - eta.val = 1.0f; - sideflags = 1; - } - - ~lwSurface() - { - if (name) free(name); - if (srcname) free(srcname); - for (unsigned int i=0; i < shaders.size(); delete shaders[i++]); - } - - int addTexture( lwTexture *tex ) - { - switch ( tex->chan ) - { - case ID_COLR: - color.addTexture(tex); - break; - case ID_LUMI: - luminosity.addTexture(tex); - break; - case ID_DIFF: - diffuse.addTexture(tex); - break; - case ID_SPEC: - specularity.addTexture(tex); - break; - case ID_GLOS: - glossiness.addTexture(tex); - break; - case ID_REFL: - reflection.val.addTexture(tex); - break; - case ID_TRAN: - transparency.val.addTexture(tex); - break; - case ID_RIND: - eta.addTexture(tex); - break; - case ID_TRNL: - translucency.addTexture(tex); - break; - case ID_BUMP: - bump.addTexture(tex); - break; - default: - return 0; - } - return 1; - } - - static lwSurface *lwDefaultSurface( void ) - { - return new lwSurface; - } - - char *setname(const char *newname) - { - unsigned int slength = strlen(newname); - - if (name && slength > strlen(name)) - { - free(name); - name = 0; - } - if (!name) name = (char *)malloc(slength+1); - - return strcpy(name, newname); - } - - char *name; - char *srcname; - lwCParam color; - lwTParam luminosity; - lwTParam diffuse; - lwTParam specularity; - lwTParam glossiness; - lwRMap reflection; - lwRMap transparency; - lwTParam eta; - lwTParam translucency; - lwTParam bump; - float smooth; - int sideflags; - float alpha; - int alpha_mode; - lwEParam color_hilite; - lwEParam color_filter; - lwEParam add_trans; - lwEParam dif_sharp; - lwEParam glow; - lwLine line; - vplugins shaders; /* linked list of shaders */ -}; - -typedef vector vsurfaces; - -/* vertex maps */ - -class lwVMap -{ -public: - lwVMap() - { - name = 0; - vindex = 0; - pindex = 0; - val = 0; - } - - ~lwVMap() - { - if (name) free(name); - if (vindex) free(vindex); - if (pindex) free(pindex); - - if (val) - { - for (unsigned int i = 0; i < nverts; free(val[i++])); - free (val); - } - } - - char *name; - unsigned int type; - unsigned int dim; - unsigned int nverts; - int perpoly; - int *vindex; /* array of point indexes */ - int *pindex; /* array of polygon indexes */ - float **val; -}; - -typedef vector vvmaps; - -class lwVMapPt -{ - lwVMapPt(); -public: - lwVMapPt(lwVMap *nvmap, int nindex) : vmap(nvmap), index(nindex) {}; - - lwVMap *vmap; - int index; /* vindex or pindex element */ -}; - -typedef vector vvmapptrs; - -/* points and polygons */ -class lwPolygon; - -typedef vector vpolygons; - -class lwPoint: public Point3 -{ - lwPoint(); -public: - lwPoint(float r, float s, float t) : Point3(r, s, t) {}; - - vvmapptrs vmaps; /* array of vmap references */ - vpolygons polygons; /* array of polygon indexes */ - unsigned short index; -}; - -typedef vector vpoints; - -class lwVertex -{ - lwVertex(); - -public: - lwVertex(int nindex) : index(nindex) {} - - lwVertex(const lwVertex &v) - { - index = v.index; - point = v.point; - normal = v.normal; - vmaps = v.vmaps; - } - - int index; /* index into the point array */ - lwPoint *point; - Vector3 normal; - vvmapptrs vmaps; /* array of vmap references */ -}; - -typedef vector vvertices; - -typedef vector vtags; - -inline bool operator < (const lwTexture &t1, const lwTexture &t2 ) -{ - return strcmp( t1.ord, t2.ord ) < 0; -} - -#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_WIN32 -void revbytes( void *bp, int elsize, int elcount ); -#else -#define revbytes( b, s, c ) -#endif - -#endif // _LWO_H_ - diff --git a/Tools/LightwaveConverter/include/lwo2mesh.h b/Tools/LightwaveConverter/include/lwo2mesh.h deleted file mode 100644 index 93ef375ed81..00000000000 --- a/Tools/LightwaveConverter/include/lwo2mesh.h +++ /dev/null @@ -1,106 +0,0 @@ -/* - Lwo2MeshWriter based on the MilkShape exporter - Dennis Verbeek (dennis.verbeek@chello.nl) - - Linux port by Magnus Møller Petersen (magnus@moaner.dk] - - doExportSkeleton is unfinished -*/ - -#ifndef _LWO2MESH_H_ -#define _LWO2MESH_H_ - -#include "lwObject.h" -#include "Ogre.h" - -#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX - -/* GNU libc has no equivalent to _splitpath() and _makepath(), so we'll write my - * own using a combination of string functions and dirname() / basname(). - */ - -// I've pulled the following values from the top of my head. -#define _MAX_DRIVE 256 -#define _MAX_FNAME 256 -#define _MAX_DIR 256 -#define _MAX_EXT 256 - -// Function prototypes. -void _splitpath( const char *_fn, char *_drive, char *_dir, char *_node, char *_ext ); -void _makepath( char *_fn, const char *_drive, const char *_dir, const char *_node, - const char *_ext ); - -#endif - -using namespace Ogre; - -enum Parameters -{ - InfoOnly, - PrintVMaps, - UseSharedVertexData, - UseSeparateLayers, - GenerateLOD, - GenerateEdgeLists, - GenerateTangents, - UseFixedMethod, - ExportMaterials, - RenameMaterials, - UseInteractiveMethod, - UseObjectMethod, - UsePrefixMethod, - ExportSkeleton, - HasNormals, - MakeNewSubMesh, - LinearCopy -}; - -#define NUMFLAGS 17 - -class Lwo2MeshWriter -{ -public: - bool writeLwo2Mesh(lwObject *nobject, char *ndest); -private: - void prepLwObject(void); - - void doExportMaterials(void); - - Skeleton *doExportSkeleton(const String &skelName, int layer); - - VertexData *setupVertexData(unsigned short vertexCount, VertexData *oldVertexData = 0, bool deleteOldVertexData = true); - void copyPoints(int surfaceIndex, unsigned long polygontype, vpoints &sourcepoints, vpoints &destpoints); - void copyPolygons(int surfaceIndex, unsigned long polygontype, vpolygons &sourcepolygons, vpolygons &destpolygons); - void copyDataToVertexData(vpoints &points, - vpolygons &polygons, - vvmaps &vmaps, - IndexData *indexData, - VertexData *vertexData, - unsigned short vertexDataOffset = 0); - - inline int getPointIndex(lwPoint *point, vpoints &points); - inline void getTextureVMaps(vtextures &textures, vvmaps &svmaps, vvmaps &dvmaps); - - inline String makeLayerFileName(char* dest, unsigned int l, char *layername); - inline String makeMaterialFileName(char* dest); - - char *dest; - lwObject *object; - MeshPtr ogreMesh; - - unsigned int nLayers; - unsigned int nSurfaces; - - unsigned int numPolygons; - unsigned int *numLayerPolygons; - unsigned int *numLayerSurfacePolygons; - unsigned int *numSurfacePolygons; - - unsigned int vertexCount; - unsigned int *numLayerVertices; - unsigned int *numLayerSurfaceVertices; - unsigned int *numSurfaceVertices; -}; - -#endif // _LWO2MESH_H_ - diff --git a/Tools/LightwaveConverter/scripts/LWO2MESH.dsp b/Tools/LightwaveConverter/scripts/LWO2MESH.dsp deleted file mode 100644 index 717d1813a0c..00000000000 --- a/Tools/LightwaveConverter/scripts/LWO2MESH.dsp +++ /dev/null @@ -1,187 +0,0 @@ -# Microsoft Developer Studio Project File - Name="Lwo2Mesh" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Console Application" 0x0103 - -CFG=Lwo2Mesh - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "LWO2MESH.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "LWO2MESH.mak" CFG="Lwo2Mesh - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "Lwo2Mesh - Win32 Release" (based on "Win32 (x86) Console Application") -!MESSAGE "Lwo2Mesh - Win32 Debug" (based on "Win32 (x86) Console Application") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "Lwo2Mesh - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "..\bin\Release" -# PROP BASE Intermediate_Dir "..\obj\Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "..\bin\Release" -# PROP Intermediate_Dir "..\obj\Release" -# PROP Ignore_Export_Lib 1 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /MD /W3 /Gi /GX /O2 /Ob2 /I "..\include" /I "..\..\..\OgreMain\include" /I "..\..\..\Dependencies\include" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /D "WIN32" /D "TIXML_USE_STL" /Fr /FD /c -# SUBTRACT CPP /YX -# ADD BASE RSC /l 0x809 /d "NDEBUG" -# ADD RSC /l 0x809 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 /nologo /subsystem:console /machine:I386 -# ADD LINK32 ogremain.lib /nologo /subsystem:console /profile /machine:I386 /nodefaultlib:"libcd.lib" /nodefaultlib:"libcmt.lib" /nodefaultlib:"libcmtd.lib" /libpath:"..\..\..\OgreMain\lib\Release" -# SUBTRACT LINK32 /debug - -!ELSEIF "$(CFG)" == "Lwo2Mesh - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "..\bin\Debug" -# PROP BASE Intermediate_Dir "..\obj\Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "..\bin\Debug" -# PROP Intermediate_Dir "..\obj\Debug" -# PROP Ignore_Export_Lib 1 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /MDd /W1 /Gm /GX /Zi /Od /I "..\include" /I "..\..\..\OgreMain\include" /I "..\..\..\Dependencies\include" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "WIN32" /D "TIXML_USE_STL" /FD /GZ /Zm500 /c -# SUBTRACT CPP /Fr -# ADD BASE RSC /l 0x809 /d "_DEBUG" -# ADD RSC /l 0x809 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept -# ADD LINK32 ogremain_d.lib /nologo /subsystem:console /incremental:no /debug /machine:I386 /nodefaultlib:"libc.lib" /nodefaultlib:"libcd.lib" /nodefaultlib:"libcmt.lib" /libpath:"..\..\..\OgreMain\lib\Debug" -# SUBTRACT LINK32 /verbose /profile - -!ENDIF - -# Begin Target - -# Name "Lwo2Mesh - Win32 Release" -# Name "Lwo2Mesh - Win32 Debug" -# Begin Group "Source Files" - -# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" -# Begin Source File - -SOURCE=..\src\BitArray.cpp -# End Source File -# Begin Source File - -SOURCE=..\src\lwEnvelope.cpp -# End Source File -# Begin Source File - -SOURCE=..\src\lwLayer.cpp -# End Source File -# Begin Source File - -SOURCE=..\src\lwo2mesh.cpp - -!IF "$(CFG)" == "Lwo2Mesh - Win32 Release" - -# ADD CPP /Ob2 - -!ELSEIF "$(CFG)" == "Lwo2Mesh - Win32 Debug" - -!ENDIF - -# End Source File -# Begin Source File - -SOURCE=..\src\lwPolygon.cpp -# End Source File -# Begin Source File - -SOURCE=..\src\lwReader.cpp -# End Source File -# Begin Source File - -SOURCE=..\src\main.cpp -# End Source File -# Begin Source File - -SOURCE=..\src\Vector3.cpp -# End Source File -# End Group -# Begin Group "Header Files" - -# PROP Default_Filter "h;hpp;hxx;hm;inl" -# Begin Source File - -SOURCE=..\include\BitArray.h -# End Source File -# Begin Source File - -SOURCE=..\include\lwClip.h -# End Source File -# Begin Source File - -SOURCE=..\include\lwEnvelope.h -# End Source File -# Begin Source File - -SOURCE=..\include\lwLayer.h -# End Source File -# Begin Source File - -SOURCE=..\include\lwo.h -# End Source File -# Begin Source File - -SOURCE=..\include\lwo2mesh.h -# End Source File -# Begin Source File - -SOURCE=..\include\lwObject.h -# End Source File -# Begin Source File - -SOURCE=..\include\lwPolygon.h -# End Source File -# Begin Source File - -SOURCE=..\include\lwReader.h -# End Source File -# Begin Source File - -SOURCE=..\include\Point.h -# End Source File -# Begin Source File - -SOURCE=..\include\Vector3.h -# End Source File -# End Group -# Begin Group "Resource Files" - -# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" -# End Group -# End Target -# End Project diff --git a/Tools/LightwaveConverter/scripts/LWO2MESH.vcproj b/Tools/LightwaveConverter/scripts/LWO2MESH.vcproj deleted file mode 100644 index e712bf783ea..00000000000 --- a/Tools/LightwaveConverter/scripts/LWO2MESH.vcproj +++ /dev/null @@ -1,202 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/LightwaveConverter/src/BitArray.cpp b/Tools/LightwaveConverter/src/BitArray.cpp deleted file mode 100644 index 3bf7cdbbf65..00000000000 --- a/Tools/LightwaveConverter/src/BitArray.cpp +++ /dev/null @@ -1,114 +0,0 @@ -#include "BitArray.h" - -BitArray::BitArray(unsigned long newsize) -{ - arraysize = newsize; - bitlongs = ((arraysize - 1) >> 5) + 1; - bits = new unsigned long[bitlongs]; -} - -BitArray::BitArray(const BitArray& b) -{ - arraysize = b.arraysize; - bitlongs = b.bitlongs; - bits = new unsigned long[bitlongs]; - for (unsigned long i = 0; i < bitlongs; i++) - bits[i] = b.bits[i]; -} - -BitArray::BitArray(unsigned long newsize, bool bitvalues) -{ - arraysize = newsize; - bitlongs = ((arraysize - 1) >> 5) + 1; - bits = new unsigned long[bitlongs]; - if (bitvalues) set(); else clear(); -} - -BitArray::BitArray(unsigned long newsize, unsigned long *newbits) -{ - arraysize = newsize; - bitlongs = ((arraysize - 1) >> 5) + 1; - bits = new unsigned long[bitlongs]; - for (unsigned long i = 0; i < bitlongs; i++) - bits[i] = newbits[i]; -} - -BitArray::~BitArray() -{ - delete []bits; -} - -BitArray& BitArray::operator =(const BitArray& b) -{ - bool equalsize = arraysize == b.arraysize; - - arraysize = b.arraysize; - bitlongs = b.bitlongs; - - if (!equalsize) { - delete []bits; - bits = new unsigned long[bitlongs]; - } - for (unsigned long i = 0; i < bitlongs; i++) - bits[i] = b.bits[i]; - - return (*this); -} - -BitArray BitArray::operator ~(void) -{ - BitArray result(arraysize); - - for (unsigned long i = 0; i < bitlongs; i++) - result.bits[i] = ~bits[i]; - - return (result); -} - -BitArray& BitArray::operator ^=(const BitArray& b) -{ - for (unsigned long i = 0; i < ((bitlongs < b.bitlongs) ? bitlongs : b.bitlongs); i++) - bits[i] ^= b.bits[i]; - return (*this); -} - -BitArray& BitArray::operator &=(const BitArray& b) -{ - for (unsigned long i = 0; i < ((bitlongs < b.bitlongs) ? bitlongs : b.bitlongs); i++) - bits[i] &= b.bits[i]; - return (*this); -} - -BitArray& BitArray::operator |=(const BitArray& b) -{ - for (unsigned long i = 0; i < (bitlongs < b.bitlongs ? bitlongs : b.bitlongs); i++) - bits[i] |= b.bits[i]; - return (*this); -} - -BitArray BitArray::operator ^(const BitArray& b) -{ - BitArray result((arraysize < b.arraysize) ? arraysize : b.arraysize); - - for (unsigned long i = 0; i < result.bitlongs; i++) - result.bits[i] = bits[i] ^ b.bits[i]; - return (result); -} - -BitArray BitArray::operator &(const BitArray& b) -{ - BitArray result((arraysize < b.arraysize) ? arraysize : b.arraysize); - - for (unsigned long i = 0; i < result.bitlongs; i++) - result.bits[i] = bits[i] & b.bits[i]; - return (result); -} - -BitArray BitArray::operator |(const BitArray& b) -{ - BitArray result((arraysize < b.arraysize) ? arraysize : b.arraysize); - - for (unsigned long i = 0; i < result.bitlongs; i++) - result.bits[i] = bits[i] | b.bits[i]; - return (result); -} diff --git a/Tools/LightwaveConverter/src/Vector3.cpp b/Tools/LightwaveConverter/src/Vector3.cpp deleted file mode 100644 index 88f50c5027f..00000000000 --- a/Tools/LightwaveConverter/src/Vector3.cpp +++ /dev/null @@ -1,7 +0,0 @@ -#include "Vector3.h" - -const Vector3 Vector3::ZERO( 0, 0, 0 ); -const Vector3 Vector3::UNIT_X( 1, 0, 0 ); -const Vector3 Vector3::UNIT_Y( 0, 1, 0 ); -const Vector3 Vector3::UNIT_Z( 0, 0, 1 ); -const Vector3 Vector3::UNIT_SCALE(1, 1, 1); diff --git a/Tools/LightwaveConverter/src/lwEnvelope.cpp b/Tools/LightwaveConverter/src/lwEnvelope.cpp deleted file mode 100644 index 0af21b9060d..00000000000 --- a/Tools/LightwaveConverter/src/lwEnvelope.cpp +++ /dev/null @@ -1,409 +0,0 @@ -#include "lwEnvelope.h" - -lwKey *lwEnvelope::addKey( float time, float value ) -{ - lwKey *key = new lwKey(time, value); - keys.insert(lower_bound(keys.begin(), keys.end(), key), key); - return key; -} - -/*====================================================================== -range() - -Given the value v of a periodic function, returns the equivalent value -v2 in the principal interval [lo, hi]. If i isn't NULL, it receives -the number of wavelengths between v and v2. - -v2 = v - i * (hi - lo) - -For example, range( 3 pi, 0, 2 pi, i ) returns pi, with i = 1. -====================================================================== */ - -float lwEnvelope::range( float v, float lo, float hi, int *i ) -{ - float v2, r = hi - lo; - - if ( r == 0.0 ) { - if ( i ) *i = 0; - return lo; - } - - v2 = lo + v - r * ( float ) floor(( double ) v / r ); - if ( i ) *i = -( int )(( v2 - v ) / r + ( v2 > v ? 0.5 : -0.5 )); - - return v2; -} - -/*====================================================================== -hermite() - -Calculate the Hermite coefficients. -====================================================================== */ - -void lwEnvelope::hermite( float t, float *h1, float *h2, float *h3, float *h4 ) -{ - float t2, t3; - - t2 = t * t; - t3 = t * t2; - - *h2 = 3.0f * t2 - t3 - t3; - *h1 = 1.0f - *h2; - *h4 = t3 - t2; - *h3 = *h4 - t2 + t; -} - -/*====================================================================== -bezier() - -Interpolate the value of a 1D Bezier curve. -====================================================================== */ - -float lwEnvelope::bezier( float x0, float x1, float x2, float x3, float t ) -{ - float a, b, c, t2, t3; - - t2 = t * t; - t3 = t2 * t; - - c = 3.0f * ( x1 - x0 ); - b = 3.0f * ( x2 - x1 ) - c; - a = x3 - x0 - c - b; - - return a * t3 + b * t2 + c * t + x0; -} - - -/*====================================================================== -bez2_time() - -Find the t for which bezier() returns the input time. The handle -endpoints of a BEZ2 curve represent the control points, and these have -(time, value) coordinates, so time is used as both a coordinate and a -parameter for this curve type. -====================================================================== */ - -float lwEnvelope::bez2_time( float x0, float x1, float x2, float x3, float time, float *t0, float *t1 ) -{ - float v, t; - - t = *t0 + ( *t1 - *t0 ) * 0.5f; - v = bezier( x0, x1, x2, x3, t ); - if ( fabs( time - v ) > .0001f ) { - if ( v > time ) - *t1 = t; - else - *t0 = t; - return bez2_time( x0, x1, x2, x3, time, t0, t1 ); - } - else - return t; -} - - - /* - ====================================================================== - bez2() - - Interpolate the value of a BEZ2 curve. - ====================================================================== */ - -float lwEnvelope::bez2( lwKey *key0, lwKey *key1, float time ) -{ - float x, y, t, t0 = 0.0f, t1 = 1.0f; - - if ( key0->shape == ID_BEZ2 ) - x = key0->time + key0->param[ 2 ]; - else - x = key0->time + ( key1->time - key0->time ) / 3.0f; - - t = bez2_time( key0->time, x, key1->time + key1->param[ 0 ], key1->time, - time, &t0, &t1 ); - - if ( key0->shape == ID_BEZ2 ) - y = key0->value + key0->param[ 3 ]; - else - y = key0->value + key0->param[ 1 ] / 3.0f; - - return bezier( key0->value, y, key1->param[ 1 ] + key1->value, key1->value, t ); -} - - - /* - ====================================================================== - outgoing() - - Return the outgoing tangent to the curve at key0. The value returned - for the BEZ2 case is used when extrapolating a linear pre behavior and - when interpolating a non-BEZ2 span. - ====================================================================== */ - -float lwEnvelope::outgoing( unsigned int key0, unsigned int key1 ) -{ - float a, b, d, t, tout; - - switch ( keys[key0]->shape ) - { - case ID_TCB: - a = ( 1.0f - keys[key0]->tension ) - * ( 1.0f + keys[key0]->continuity ) - * ( 1.0f + keys[key0]->bias ); - b = ( 1.0f - keys[key0]->tension ) - * ( 1.0f - keys[key0]->continuity ) - * ( 1.0f - keys[key0]->bias ); - d = keys[key1]->value - keys[key0]->value; - - - if ( key0 > 0 ) - { - t = ( keys[key1]->time - keys[key0]->time ) / ( keys[key1]->time - keys[ key0-1 ]->time ); - tout = t * ( a * ( keys[key0]->value - keys[ key0-1 ]->value ) + b * d ); - } - else - tout = b * d; - break; - - case ID_LINE: - d = keys[key1]->value - keys[key0]->value; - if ( key0 > 0 ) - { - t = ( keys[key1]->time - keys[key0]->time ) / ( keys[key1]->time - keys[ key0-1 ]->time ); - tout = t * ( keys[key0]->value - keys[ key0-1 ]->value + d ); - } - else - tout = d; - break; - - case ID_BEZI: - case ID_HERM: - tout = keys[key0]->param[ 1 ]; - - if ( key0 > 0 ) - tout *= ( keys[key1]->time - keys[key0]->time ) / ( keys[key1]->time - keys[ key0-1 ]->time ); - - break; - - case ID_BEZ2: - tout = keys[key0]->param[ 3 ] * ( keys[key1]->time - keys[key0]->time ); - if ( fabs( keys[key0]->param[ 2 ] ) > 1e-5f ) - tout /= keys[key0]->param[ 2 ]; - else - tout *= 1e5f; - break; - - case ID_STEP: - default: - tout = 0.0f; - break; - } - - return tout; -} - - -/*====================================================================== -incoming() - -Return the incoming tangent to the curve at key1. The value returned -for the BEZ2 case is used when extrapolating a linear post behavior. -====================================================================== */ - -float lwEnvelope::incoming( unsigned int key0, unsigned int key1 ) -{ - float a, b, d, t, tin; - - switch ( keys[key1]->shape ) - { - case ID_LINE: - d = keys[key1]->value - keys[key0]->value; - - if ( key1 < keys.size()-1 ) - { - t = ( keys[key1]->time - keys[key0]->time ) / ( keys[ key1+1 ]->time - keys[key0]->time ); - tin = t * ( keys[ key1+1 ]->value - keys[key1]->value + d ); - } - else - tin = d; - - break; - - case ID_TCB: - a = ( 1.0f - keys[key1]->tension ) - * ( 1.0f - keys[key1]->continuity ) - * ( 1.0f + keys[key1]->bias ); - b = ( 1.0f - keys[key1]->tension ) - * ( 1.0f + keys[key1]->continuity ) - * ( 1.0f - keys[key1]->bias ); - d = keys[key1]->value - keys[key0]->value; - if ( key1 < keys.size()-1 ) { - t = ( keys[key1]->time - keys[key0]->time ) / ( keys[ key1+1 ]->time - keys[key0]->time ); - tin = t * ( b * ( keys[ key1+1 ]->value - keys[key1]->value ) + a * d ); - } - else - tin = a * d; - break; - - case ID_BEZI: - case ID_HERM: - tin = keys[key1]->param[ 0 ]; - if ( key1 < keys.size()-1 ) - tin *= ( keys[key1]->time - keys[key0]->time ) / ( keys[ key1+1 ]->time - keys[key0]->time ); - break; - return tin; - - case ID_BEZ2: - tin = keys[key1]->param[ 1 ] * ( keys[key1]->time - keys[key0]->time ); - if ( fabs( keys[key1]->param[ 0 ] ) > 1e-5f ) - tin /= keys[key1]->param[ 0 ]; - else - tin *= 1e5f; - break; - - case ID_STEP: - default: - tin = 0.0f; - break; - } - - return tin; -} - -/*====================================================================== -evalEnvelope() - -Given a list of keys and a time, returns the interpolated value of the -envelope at that time. -====================================================================== */ - -float lwEnvelope::evaluate( float time ) -{ - lwKey *key0, *key1, *skey, *ekey; - float t, h1, h2, h3, h4, tin, tout, offset = 0.0f; - int noff; - int key0index, key1index; - - - /* if there's no key, the value is 0 */ - - if ( keys.size() == 0 ) return 0.0f; - - /* if there's only one key, the value is constant */ - - if ( keys.size() == 1 ) return keys[0]->value; - - /* find the first and last keys */ - - key0index = 0; - key1index = keys.size()-1; - skey = keys[key0index]; - ekey = keys[key1index]; - - /* use pre-behavior if time is before first key time */ - - if ( time < skey->time ) - { - switch ( behavior[ 0 ] ) - { - case BEH_RESET: - return 0.0f; - - case BEH_CONSTANT: - return skey->value; - - case BEH_REPEAT: - time = range( time, skey->time, ekey->time, NULL ); - break; - - case BEH_OSCILLATE: - time = range( time, skey->time, ekey->time, &noff ); - if ( noff % 2 ) - time = ekey->time - skey->time - time; - break; - - case BEH_OFFSET: - time = range( time, skey->time, ekey->time, &noff ); - offset = noff * ( ekey->value - skey->value ); - break; - - case BEH_LINEAR: - tout = outgoing( key0index, key0index+1 ) / ( keys[key0index+1]->time - keys[key0index]->time ); - - return tout * ( time - skey->time ) + skey->value; - } - } - - /* use post-behavior if time is after last key time */ - - else if ( time > ekey->time ) { - switch ( behavior[ 1 ] ) - { - case BEH_RESET: - return 0.0f; - - case BEH_CONSTANT: - return ekey->value; - - case BEH_REPEAT: - time = range( time, skey->time, ekey->time, NULL ); - break; - - case BEH_OSCILLATE: - time = range( time, skey->time, ekey->time, &noff ); - if ( noff % 2 ) - time = ekey->time - skey->time - time; - break; - - case BEH_OFFSET: - time = range( time, skey->time, ekey->time, &noff ); - offset = noff * ( ekey->value - skey->value ); - break; - - case BEH_LINEAR: - tin = incoming( key1index-1, key1index ) / ( ekey->time - keys[key1index-1]->time ); - return tin * ( time - ekey->time ) + ekey->value; - } - } - - /* get the endpoints of the interval being evaluated */ - - key0index = keys.size()-2; - key1index = keys.size()-1; - key0 = keys[key0index]; - key1 = keys[key1index]; - - /* check for singularities first */ - - if ( time == key0->time ) - return key0->value + offset; - else if ( time == key1->time ) - return key1->value + offset; - - /* get interval length, time in [0, 1] */ - - t = ( time - key0->time ) / ( key1->time - key0->time ); - - /* interpolate */ - - switch ( key1->shape ) - { - case ID_TCB: - case ID_BEZI: - case ID_HERM: - tout = outgoing( key0index, key1index ); - tin = incoming( key0index, key1index ); - hermite( t, &h1, &h2, &h3, &h4 ); - return h1 * key0->value + h2 * key1->value + h3 * tout + h4 * tin + offset; - - case ID_BEZ2: - return bez2( key0, key1, time ) + offset; - - case ID_LINE: - return key0->value + t * ( key1->value - key0->value ) + offset; - - case ID_STEP: - return key0->value + offset; - - default: - return offset; - } -} diff --git a/Tools/LightwaveConverter/src/lwLayer.cpp b/Tools/LightwaveConverter/src/lwLayer.cpp deleted file mode 100644 index c8413311f6e..00000000000 --- a/Tools/LightwaveConverter/src/lwLayer.cpp +++ /dev/null @@ -1,299 +0,0 @@ -#include "lwLayer.h" - -/*====================================================================== -lwResolveVertexPoints() - - For each point, fill in the indexes of the polygons that share the - point. Returns 0 if any of the memory allocations fail, otherwise - returns 1. -====================================================================== */ - -void lwLayer::lwResolveVertexPoints(void) -{ - unsigned int i, j; - - for ( i = 0; i < polygons.size(); i++ ) - { - lwPolygon *polygon = polygons[ i ]; - for ( j = 0; j < polygon->vertices.size(); j++ ) - { - lwVertex *vertex = polygon->vertices[ j ]; - vertex->point = points[ vertex->index ]; - } - } -} - -/*====================================================================== -lwGetPointPolygons() - -For each point, fill in the indexes of the polygons that share the point. -====================================================================== */ - -void lwLayer::lwGetPointPolygons(void) -{ - unsigned int i, j; - - for ( i = 0; i < polygons.size(); i++ ) - { - lwPolygon *polygon = polygons[ i ]; - for ( j = 0; j < polygon->vertices.size(); j++ ) - polygon->vertices[ j ]->point->polygons.push_back(polygon); - } -} - -/* -====================================================================== -calculatePolygonNormals() - - Calculate the polygon normals. By convention, LW's polygon normals - are found as the cross product of the first and last edges. It's - undefined for one- and two-point polygons. -====================================================================== */ - -void lwLayer::calculatePolygonNormals(void) -{ - for (unsigned int i = 0; i < polygons.size(); polygons[i++]->calculateNormal()); -} - -void lwLayer::triangulatePolygons(void) -{ - vpolygons newpolygons; - vpolygons newtriangles; - - unsigned int i, j; - - for (i = 0; i < polygons.size(); i++) - { - lwPolygon *polygon = polygons[i]; - - if (polygon->vertices.size() > 3) // needs triangulation ! - { - newtriangles = polygon->triangulate(); - delete polygon; - - for (j = 0; j < newtriangles.size(); j++) - { - polygon = newtriangles[j]; - polygon->calculateNormal(); - newpolygons.push_back(polygon); - } - } - else - newpolygons.push_back(polygon); - } - - polygons = newpolygons; -} - -/* -====================================================================== -lwGetBoundingBox() - - Calculate the bounding box for a point list, but only if the bounding - box hasn't already been initialized. -====================================================================== */ - -void lwLayer::lwGetBoundingBox(void) -{ - unsigned int i; - - if ( points.size() == 0 ) return; - - if ( bboxmin.x != 0.0f ) return; - if ( bboxmin.y != 0.0f ) return; - if ( bboxmin.z != 0.0f ) return; - if ( bboxmax.x != 0.0f ) return; - if ( bboxmax.y != 0.0f ) return; - if ( bboxmax.z != 0.0f ) return; - - bboxmin.x = bboxmin.y = bboxmin.z = 1e20f; - bboxmax.x = bboxmax.y = bboxmax.z = -1e20f; - - for ( i = 0; i < points.size(); i++ ) - { - if ( bboxmin.x > points[ i ]->x ) - bboxmin.x = points[ i ]->x; - if ( bboxmin.y > points[ i ]->y ) - bboxmin.y = points[ i ]->y; - if ( bboxmin.z > points[ i ]->z ) - bboxmin.z = points[ i ]->z; - - if ( bboxmax.x < points[ i ]->x ) - bboxmax.x = points[ i ]->x; - if ( bboxmax.y < points[ i ]->y ) - bboxmax.y = points[ i ]->y; - if ( bboxmax.z < points[ i ]->z ) - bboxmax.z = points[ i ]->z; - } -} - -/* -====================================================================== -lwResolvePolySurfaces() - - Convert tag indexes into actual lwSurface pointers. If any polygons - point to tags for which no corresponding surface can be found, a - default surface is created. -====================================================================== */ - -int lwLayer::lwResolvePolySurfaces( vsurfaces &surfaces, vtags &tags ) -{ - if ( tags.size() == 0 ) return 1; - - lwSurface **s = (lwSurface **)malloc (tags.size() * sizeof(lwSurface *)); - - if ( !s ) return 0; - - unsigned int i, j, index; - - for ( i = 0; i < tags.size(); i++ ) - { - s[i] = 0; - for (j = 0; j < surfaces.size(); j++) - { - if ( !strcmp( surfaces[j]->name, tags[i] )) - { - s[i] = surfaces[j]; - break; - } - } - if ( !s[i]) - { - s[i] = lwSurface::lwDefaultSurface(); - if ( !s[i] ) return 0; - - s[i]->name = (char *)malloc(strlen(tags[i])+1); - if ( !s[i]->name ) return 0; - - strcpy( s[i]->name, tags[i] ); - } - } - - surfaces.clear(); - surfaces.reserve(tags.size()); - for (i = 0; i < tags.size(); i++ ) - surfaces.push_back(s[i]); - - for (i = 0; i < polygons.size(); i++ ) - { - index = polygons[i]->surfidx; - if ( index < 0 || index > tags.size() ) return 0; - polygons[i]->surface = s[index]; - } - - free(s); - return 1; -} - - -/* -====================================================================== -calculateVertexNormals() - - Calculate the vertex normals. For each polygon vertex, sum the - normals of the polygons that share the point. If the normals of the - current and adjacent polygons form an angle greater than the max - smoothing angle for the current polygon's surface, the normal of the - adjacent polygon is excluded from the sum. It's also excluded if the - polygons aren't in the same smoothing group. - - Assumes that lwGetPointPolygons(), lwGetPolyNormals() and - lwResolvePolySurfaces() have already been called. -====================================================================== */ - -void lwLayer::calculateVertexNormals(void) -{ - unsigned int j, n, g; - float a; - lwPolygon *outerpolygon; - lwPolygon *innerpolygon; - lwVertex *vertex; - lwPoint *point; - - for ( j = 0; j < polygons.size(); j++ ) - { - outerpolygon = polygons[j]; - for ( n = 0; n < outerpolygon->vertices.size(); n++ ) - { - vertex = outerpolygon->vertices[n]; - vertex->normal = outerpolygon->normal; - - if ( outerpolygon->surface->smooth <= 0 ) continue; - - point = points[vertex->index]; - - for ( g = 0; g < point->polygons.size(); g++ ) - { - innerpolygon = point->polygons[ g ]; - if ( innerpolygon == outerpolygon ) continue; - if ( outerpolygon->smoothgrp != innerpolygon->smoothgrp ) continue; - a = (float)acos( outerpolygon->normal.dotProduct(innerpolygon->normal) ); - if ( a > outerpolygon->surface->smooth ) continue; - vertex->normal += innerpolygon->normal; - } - - vertex->normal.normalise(); - } - } -} - -/* -====================================================================== -lwGetPointVMaps() - - Fill in the lwVMapPt structure for each point. -====================================================================== */ - -void lwLayer::lwGetPointVMaps(void) -{ - lwVMap *vm; - unsigned int i, j; - - for (j = 0; j < vmaps.size(); j++) - { - vm = vmaps[j]; - if ( !vm->perpoly ) - { - for ( i = 0; i < vm->nverts; i++ ) - { - points[ vm->vindex[ i ] ]->vmaps.push_back( lwVMapPt(vm, i) ); - } - } - } -} - - -/* -====================================================================== -lwGetPolyVMaps() - - Fill in the lwVMapPt structure for each polygon vertex. -====================================================================== */ - -void lwLayer::lwGetPolyVMaps(void) -{ - lwVMap *vm; - lwVertex *pv; - unsigned int i, j, k; - - /* fill in vmap references for each mapped point */ - for (k = 0; k < vmaps.size(); k++) - { - vm = vmaps[k]; - if ( vm->perpoly ) - { - for ( i = 0; i < vm->nverts; i++ ) - { - for ( j = 0; j < polygons[ vm->pindex[ i ]]->vertices.size(); j++ ) - { - pv = polygons[ vm->pindex[ i ]]->vertices[ j ]; - if ( vm->vindex[ i ] == pv->index ) - { - pv->vmaps.push_back( lwVMapPt(vm, i) ); - break; - } - } - } - } - } -} diff --git a/Tools/LightwaveConverter/src/lwPolygon.cpp b/Tools/LightwaveConverter/src/lwPolygon.cpp deleted file mode 100644 index b067b15a147..00000000000 --- a/Tools/LightwaveConverter/src/lwPolygon.cpp +++ /dev/null @@ -1,172 +0,0 @@ -#include -#include "lwPolygon.h" -#include "BitArray.h" - -const float epsilon = 0.001F; // error margin - -void lwPolygon::flip(void) -{ - vvertices flipvertices; - flipvertices.reserve(vertices.size()); - vvertices::reverse_iterator i = vertices.rbegin(); - vvertices::reverse_iterator end = vertices.rend(); - for(; i!=end ; ++i) - flipvertices.push_back(*i); - vertices = flipvertices; -} - -lwPolygon *lwPolygon::makeTriangle(long ia, long ib, long ic) -{ - lwPolygon *triangle = new lwPolygon(*this); - - triangle->vertices.push_back(new lwVertex(*vertices[ia])); - triangle->vertices.push_back(new lwVertex(*vertices[ib])); - triangle->vertices.push_back(new lwVertex(*vertices[ic])); - - return triangle; -} - -Vector3 &lwPolygon::calculateNormal() -{ - if ( vertices.size() < 3 ) return normal; - - Point3 *p1 = vertices[ 0 ]->point; - Point3 *p2 = vertices[ 1 ]->point; - Point3 *pn = vertices[vertices.size() - 1]->point; - - normal = (*p2 - *p1).crossProduct(*pn - *p1); - normal.normalise(); - - return normal; -} - -vpolygons lwPolygon::triangulate() -{ - vpolygons triangles; - - BitArray active(vertices.size(), true); // vertex part of polygon ? - - long vertexCount = vertices.size(); - - long triangleCount = 0; - long start = 0; - - long p1 = 0; - long p2 = 1; - long m1 = vertexCount - 1; - long m2 = vertexCount - 2; - - bool lastPositive = false; - for (;;) - { - if (p2 == m2) - { - triangles.push_back(makeTriangle(m1, p1, p2)); - break; - } - - const Point3 vp1 = *vertices[p1]->point; - const Point3 vp2 = *vertices[p2]->point; - const Point3 vm1 = *vertices[m1]->point; - const Point3 vm2 = *vertices[m2]->point; - - bool positive = false; - bool negative = false; - - Vector3 n1 = normal.crossProduct((vm1 - vp2).normalise()); - if (n1.dotProduct(vp1 - vp2) > epsilon) - { - positive = true; - - Vector3 n2 = normal.crossProduct((vp1 - vm1).normalise()); - Vector3 n3 = normal.crossProduct((vp2 - vp1).normalise()); - - for (long a = 0; a < vertexCount; a++) - { - if ((a != p1) && (a != p2) && (a != m1) && active.bitSet(a)) - { - const Point3 v = *vertices[a]->point; - if (n1.dotProduct((v - vp2).normalise()) > -epsilon && n2.dotProduct((v - vm1).normalise()) > -epsilon && n3.dotProduct((v - vp1).normalise()) > -epsilon) - { - positive = false; - break; - } - } - } - } - - n1 = normal.crossProduct((vm2 - vp1).normalise()); - if (n1.dotProduct(vm1 - vp1) > epsilon) - { - negative = true; - - Vector3 n2 = normal.crossProduct((vm1 - vm2).normalise()); - Vector3 n3 = normal.crossProduct((vp1 - vm1).normalise()); - - for (long a = 0; a < vertexCount; a++) - { - if ((a != m1) && (a != m2) && (a != p1) && active.bitSet(a)) - { - const Point3 v = *vertices[a]->point; - if (n1.dotProduct((v - vp1).normalise()) > -epsilon && n2.dotProduct((v - vm2).normalise()) > -epsilon && n3.dotProduct((v - vm1).normalise()) > -epsilon) - { - negative = false; - break; - } - } - } - } - - if ((positive) && (negative)) - { - float pd = (vp2 - vm1).normalise().dotProduct((vm2 - vm1).normalise()); - float md = (vm2 - vp1).normalise().dotProduct((vp2 - vp1).normalise()); - - if (fabs(pd - md) < epsilon) - { - if (lastPositive) positive = false; - else negative = false; - } - else - { - if (pd < md) negative = false; - else positive = false; - } - } - - if (positive) - { - active.clearBit(p1); - triangles.push_back(makeTriangle(m1, p1, p2)); - - p1 = active.getNextSet(p1); - p2 = active.getNextSet(p2); - - lastPositive = true; - start = -1; - } - else if (negative) - { - active.clearBit(m1); - triangles.push_back(makeTriangle(m2, m1, p1)); - - m1 = active.getPreviousSet(m1); - m2 = active.getPreviousSet(m2); - - lastPositive = false; - start = -1; - } - else - { - if (start == -1) start = p2; - else if (p2 == start) break; - - m2 = m1; - m1 = p1; - p1 = p2; - p2 = active.getNextSet(p2); - } - } - - return triangles; -} diff --git a/Tools/LightwaveConverter/src/lwReader.cpp b/Tools/LightwaveConverter/src/lwReader.cpp deleted file mode 100644 index c9167556b24..00000000000 --- a/Tools/LightwaveConverter/src/lwReader.cpp +++ /dev/null @@ -1,2710 +0,0 @@ -#include "lwReader.h" - -lwObject *lwReader::readObjectFromFile( const char *nfilename) -{ - lwObject *nobject = NULL; - - ifstream *ifs = new ifstream(); - try - { - ifs->open(nfilename, ios::in|ios::binary); - if (ifs->fail()) - cout << "Could not open file: " << nfilename << endl; - else - nobject = readObjectFromStream( ifs ); - } - catch (...) - { - if (nobject) delete nobject; - nobject = NULL; - } - ifs->close(); - delete ifs; - return nobject; -} - -lwObject *lwReader::readObjectFromStream( istream *nis) -{ - lwObject *nobject = 0; - chunksize = 0; - currentchunkid = 0; - formsize = 0; - flen = 0; - - is = nis; - - try - { - long id = getU4(); - if ( id == ID_FORM ) - { - formsize = getU4(); - long type = getU4(); - - switch(type) - { - case ID_LWO2: - nobject = lwGetLWO2(); // FORM0000LWXX -> filelength - 12 - break; - case ID_LWOB: - case ID_LWLO: - nobject = lwGetLWLO(); // FORM0000LWXX -> filelength - 12 - break; - default: - throw "File does not contain Lightwave object."; - } - } - else - throw "Not an IFF FORM file."; - } - catch (char *errstr) - { - cout << "Error near byte " << is->tellg() << " in chunk " << currentchunkid << " : " << errstr << endl; - } - catch (...) - { - if (nobject) delete nobject; - nobject = NULL; - } - return nobject; -} - - -lwObject *lwReader::lwGetLWLO() -{ - long filepos = is->tellg(); - if (filepos == -1) return NULL; - long formstart = filepos; - long formend = filepos + formsize; // FORM0000LWXX -> filelength - 12 - - lwObject *object = new lwObject; - if ( !object ) return NULL; - - lwLayer *layer = new lwLayer; - if ( !layer ) goto Fail; - - lwSurface *surface; - unsigned int rlen; - unsigned long i; - while ( filepos < formend ) - { - currentchunkid = getU4(); - chunksize = getU4(); - chunksize += chunksize & 1; - - switch ( currentchunkid ) - { - case ID_SRFS: - if ( !lwGetTags(object->tags )) - goto Fail; - break; - case ID_LAYR: - if ( object->layers.size() > 0 ) - { - layer = new lwLayer; - if ( !layer ) goto Fail; - } - object->layers.push_back(layer); - - - flen = 0; - layer->index = getU2(); - layer->flags = getU2(); - layer->name = getS0(); - - rlen = flen; - if ( rlen < 0 || rlen > chunksize ) goto Fail; - if ( rlen < chunksize ) - is->seekg(chunksize - rlen, ios_base::cur); - break; - case ID_PNTS: - if ( !lwGetPoints(layer->points )) - goto Fail; - break; - - case ID_POLS: - if ( !lwGetLWOBPolygons(layer->polygons, layer->pointsoffset )) - goto Fail; - break; - - case ID_SURF: - surface = lwGetLWOBSurface(object ); - if ( surface ) object->surfaces.push_back( surface ); - break; - - case ID_SHCP: - default: - is->seekg(chunksize, ios_base::cur); - break; - } - - /* end of the file? */ - - filepos = is->tellg(); - if ( filepos == -1 ) break; - if ( filepos > formend ) break; // read too much - } - - if ( object->layers.size() == 0 ) - object->layers.push_back(layer); - - for (i = 0; i < object->layers.size(); i++) - { - layer = object->layers[i]; - layer->lwGetBoundingBox(); - layer->lwResolveVertexPoints(); - layer->calculatePolygonNormals(); - layer->lwGetPointPolygons(); - - if ( !layer->lwResolvePolySurfaces(object->surfaces, object->tags)) goto Fail; - layer->calculateVertexNormals(); - } - - return object; -Fail: - if (object) delete object; - return NULL; -} - -lwObject *lwReader::lwGetLWO2() -{ - long filepos = is->tellg(); - if (filepos == -1) return NULL; - long formstart = filepos; - long formend = filepos + formsize; // FORM0000LWXX -> filelength - 12 - - /* allocate an object and a default layer */ - - lwObject *object = new lwObject; - if ( !object ) return NULL; - - lwLayer *layer = new lwLayer; - if ( !layer ) goto Fail; - - unsigned int i, rlen; - - lwVMap *vmap; - lwEnvelope *envelope; - lwClip *clip; - lwSurface *surface; - - /* process chunks as they're encountered */ - - while ( filepos < formend ) - { - currentchunkid = getU4(); - chunksize = getU4(); - chunksize += chunksize & 1; - - switch ( currentchunkid ) - { - case ID_LAYR: - if ( object->layers.size() > 0 ) - { - layer = new lwLayer; - if ( !layer ) goto Fail; - } - object->layers.push_back(layer); - - flen = 0; - layer->index = getU2(); - layer->flags = getU2(); - layer->pivot.x = getF4(); - layer->pivot.y = getF4(); - layer->pivot.z = getF4(); - layer->name = getS0(); - - rlen = flen; - if ( rlen < 0 || rlen > chunksize ) goto Fail; - if ( rlen <= chunksize - 2 ) - layer->parent = getU2(); - rlen = flen; - if ( rlen < chunksize ) - is->seekg(chunksize - rlen, ios_base::cur); - break; - - case ID_PNTS: - if ( !lwGetPoints(layer->points )) - goto Fail; - break; - - case ID_POLS: - if ( !lwGetPolygons(layer->polygons, layer->pointsoffset )) - goto Fail; - break; - - case ID_VMAP: - case ID_VMAD: - vmap = lwGetVMap(layer->pointsoffset, layer->polygonsoffset, currentchunkid == ID_VMAD ); - if ( !vmap ) goto Fail; - layer->vmaps.push_back(vmap); - break; - - case ID_PTAG: - if ( !lwGetPolygonTags(object->tags, object->tagsoffset, layer->polygons, layer->polygonsoffset )) - goto Fail; - break; - - case ID_BBOX: - flen = 0; - layer->bboxmin.x = getF4(); - layer->bboxmin.y = getF4(); - layer->bboxmin.z = getF4(); - layer->bboxmax.x = getF4(); - layer->bboxmax.y = getF4(); - layer->bboxmax.z = getF4(); - rlen = flen; - if ( rlen < 0 || rlen > chunksize ) goto Fail; - if ( rlen < chunksize ) - is->seekg(chunksize - rlen, ios_base::cur ); - break; - - case ID_TAGS: - if ( !lwGetTags(object->tags )) - goto Fail; - break; - - case ID_ENVL: - envelope = lwGetEnvelope(); - if ( !envelope ) goto Fail; - object->envelopes.push_back( envelope ); - break; - - case ID_CLIP: - clip = lwGetClip(); - if ( !clip ) goto Fail; - object->clips.push_back( clip ); - break; - - case ID_SURF: - surface = lwGetSurface(); - if ( !surface ) goto Fail; - object->surfaces.push_back( surface ); - break; - - case ID_DESC: - case ID_TEXT: - case ID_ICON: - default: - is->seekg(chunksize, ios_base::cur ); - break; - } - - /* end of the file? */ - filepos = is->tellg(); - if ( filepos == -1 ) break; - if ( filepos > formend ) break; // read too much - } - - if ( object->layers.size() == 0 ) - object->layers.push_back(layer); - - for (i = 0; i < object->layers.size(); i++) - { - layer = object->layers[i]; - if ( !layer->lwResolvePolySurfaces(object->surfaces, object->tags)) goto Fail; - - layer->lwGetBoundingBox(); - layer->lwResolveVertexPoints(); - layer->calculatePolygonNormals(); - layer->lwGetPointPolygons(); - layer->calculateVertexNormals(); - layer->lwGetPointVMaps(); - layer->lwGetPolyVMaps(); - } - - return object; -Fail: - if(object) delete object; - return NULL; -} - -#define FLEN_ERROR INT_MIN - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_LINUX -/* -===================================================================== -revbytes() - -Reverses byte order in place. - -INPUTS -bp bytes to reverse -elsize size of the underlying data type -elcount number of elements to swap - -RESULTS -Reverses the byte order in each of elcount elements. - -This only needs to be defined on little-endian platforms, most -notably Windows. lwo2.h replaces this with a #define on big-endian -platforms. -===================================================================== */ - -unsigned short lwReader::swappedShort(unsigned short w) -{ - unsigned short tmp; - tmp = (w & 0x00ff); - tmp = ((w & 0xff00) >> 0x08) | (tmp << 0x08); - return tmp; -} - -unsigned long lwReader::swappedLong(unsigned long w) -{ - unsigned long tmp; - tmp = (w & 0x000000ff); - tmp = ((w & 0x0000ff00) >> 0x08) | (tmp << 0x08); - tmp = ((w & 0x00ff0000) >> 0x10) | (tmp << 0x08); - tmp = ((w & 0xff000000) >> 0x18) | (tmp << 0x08); - return tmp; -} - -void lwReader::revbytes( void *bp, int elsize, int elcount ) -{ - register char *p, *q; - - p = ( char * ) bp; - - if ( elsize == 2 ) { - q = p + 1; - while ( elcount-- ) { - *p ^= *q; - *q ^= *p; - *p ^= *q; - p += 2; - q += 2; - } - return; - } - - while ( elcount-- ) { - q = p + elsize - 1; - while ( p < q ) { - *p ^= *q; - *q ^= *p; - *p ^= *q; - ++p; - --q; - } - p += elsize >> 1; - } -} -#endif - -char *lwReader::getbytes( int size ) -{ - char *data; - - if ( flen == FLEN_ERROR ) return NULL; - if ( size < 0 ) { - flen = FLEN_ERROR; - return NULL; - } - if ( size == 0 ) return NULL; - - data = (char*)malloc(size); - - if ( !data ) - { - flen = FLEN_ERROR; - return NULL; - } - - is->read((char *)data, size); - if (is->gcount() != size) - { - flen = FLEN_ERROR; - free (data); - return NULL; - } - - flen += size; - return data; -} - - -void lwReader::skipbytes( int n ) -{ - if ( flen == FLEN_ERROR ) return; - - is->seekg(n, ios_base::cur); - - if (is->bad()) - flen = FLEN_ERROR; - else - flen += n; -} - -short lwReader::getI2() -{ - short i; - - if ( flen == FLEN_ERROR ) return 0; - - is->read((char *)&i, 2); - if (is->gcount() != 2) - { - flen = FLEN_ERROR; - return 0; - } - revbytes( &i, 2, 1 ); - flen += 2; - return i; -} - - -long lwReader::getI4() -{ - long i; - - if ( flen == FLEN_ERROR ) return 0; - - is->read((char *)&i, 4); - if (is->gcount() != 4) { - flen = FLEN_ERROR; - return 0; - } - revbytes( &i, 4, 1 ); - flen += 4; - return i; -} - - -unsigned char lwReader::getU1() -{ - unsigned char i; - - if ( flen == FLEN_ERROR ) return 0; - is->read((char *)&i, 1); - if (is->gcount() != 1) - { - flen = FLEN_ERROR; - return 0; - } - flen += 1; - return i; -} - - -unsigned short lwReader::getU2() -{ - unsigned short i; - - if ( flen == FLEN_ERROR ) return 0; - is->read((char *)&i, 2); - if (is->gcount() != 2) - { - flen = FLEN_ERROR; - return 0; - } - revbytes( &i, 2, 1 ); - flen += 2; - return i; -} - - -unsigned long lwReader::getU4() -{ - unsigned long i; - - if ( flen == FLEN_ERROR ) return 0; - is->read((char *)&i, 4); - if (is->gcount() != 4) - { - flen = FLEN_ERROR; - return 0; - } - revbytes( &i, 4, 1 ); - flen += 4; - return i; -} - - -int lwReader::getVX() -{ - int i; - short c; - - if ( flen == FLEN_ERROR ) return 0; - - is->read((char *)&c, 2); - - if ( (c & 0x00FF) != 0xFF ) - { - i = swappedShort(c); - flen += 2; - } - else - { - i = (swappedShort(c) & 0x00FF) << 16; - is->read((char *)&c, 2); - i |= swappedShort(c); - flen += 4; - } - - if ( is->bad() ) { - flen = FLEN_ERROR; - return 0; - } - return i; -} - - -float lwReader::getF4() -{ - float f; - - if ( flen == FLEN_ERROR ) return 0.0f; - is->read((char *)&f, 4); - if (is->gcount() != 4) - { - flen = FLEN_ERROR; - return 0.0f; - } - revbytes( &f, 4, 1 ); - flen += 4; - return f; -} - -char *lwReader::getS0() -{ - char *s; - int i, len, pos; - char c; - - if ( flen == FLEN_ERROR ) return NULL; - - pos = is->tellg(); - if (pos == -1) return 0; - - i = 0; - do - { - is->read(&c, 1); - i ++; - } - while (c > 0); - - if ( i == 1 ) // word align - { - is->read(&c, 1); - flen += 2; - return NULL; - } - - len = i + ( i & 1 ); - - s = (char *)malloc(len); - if ( !s ) - { - flen = FLEN_ERROR; - return NULL; - } - - is->seekg(pos, ios_base::beg); - if (is->bad()) - { - flen = FLEN_ERROR; - return NULL; - } - - is->read(s, len); - if (is->gcount() != len) - { - flen = FLEN_ERROR; - return NULL; - } - - flen += len; - return s; -} - -short lwReader::sgetI2( char **bp ) -{ - short i; - - if ( flen == FLEN_ERROR ) return 0; - memcpy( &i, *bp, 2 ); - revbytes( &i, 2, 1 ); - flen += 2; - *bp += 2; - return i; -} - - -long lwReader::sgetI4( char **bp ) -{ - long i; - - if ( flen == FLEN_ERROR ) return 0; - memcpy( &i, *bp, 4 ); - revbytes( &i, 4, 1 ); - flen += 4; - *bp += 4; - return i; -} - - -unsigned char lwReader::sgetU1( char **bp ) -{ - unsigned char c; - - if ( flen == FLEN_ERROR ) return 0; - c = **bp; - flen += 1; - *bp++; - return c; -} - -unsigned short lwReader::sgetU2(char **bp ) -{ - unsigned char *buf = (unsigned char *)*bp; - unsigned short i; - - if ( flen == FLEN_ERROR ) return 0; - i = ( buf[ 0 ] << 8 ) | buf[ 1 ]; - flen += 2; - *bp += 2; - return i; -} - -unsigned long lwReader::sgetU4( char **bp ) -{ - unsigned long i; - - if ( flen == FLEN_ERROR ) return 0; - memcpy( &i, *bp, 4 ); - revbytes( &i, 4, 1 ); - flen += 4; - *bp += 4; - return i; -} - -int lwReader::sgetVX( char **bp ) -{ - unsigned char *buf = (unsigned char *)*bp; - int i; - - if ( flen == FLEN_ERROR ) return 0; - - if ( buf[ 0 ] != 0xFF ) - { - i = buf[ 0 ] << 8 | buf[ 1 ]; - flen += 2; - *bp += 2; - } - else - { - i = ( buf[ 1 ] << 16 ) | ( buf[ 2 ] << 8 ) | buf[ 3 ]; - flen += 4; - *bp += 4; - } - return i; -} - - -float lwReader::sgetF4( char **bp ) -{ - float f; - - if ( flen == FLEN_ERROR ) return 0.0f; - memcpy( &f, *bp, 4 ); - revbytes( &f, 4, 1 ); - flen += 4; - *bp += 4; - return f; -} - - -char *lwReader::sgetS0( char **bp ) -{ - char *s; - const char *buf = (const char *)*bp; - unsigned int len; - - if ( flen == FLEN_ERROR ) return NULL; - - len = strlen( buf ) + 1; - if ( len == 1 ) { - flen += 2; - *bp += 2; - return NULL; - } - len += len & 1; - s = (char *)malloc(len); - if ( !s ) - { - flen = FLEN_ERROR; - return NULL; - } - - memcpy( s, buf, len ); - flen += len; - *bp += len; - return s; -} - -lwClip *lwReader::lwGetClip() -{ - lwClip *clip; - lwPlugin *filt; - unsigned int id; - unsigned short sz; - unsigned int pos, rlen; - - - /* allocate the Clip structure */ - - clip = new lwClip; - if ( !clip ) goto Fail; - - /* remember where we started */ - - flen = 0; - pos = is->tellg(); - - /* index */ - - clip->index = getI4(); - - /* first subchunk header */ - - clip->type = getU4(); - sz = getU2(); - if ( 0 > flen ) goto Fail; - - sz += sz & 1; - flen = 0; - - switch ( clip->type ) - { - case ID_STIL: - { - lwClipStill *still = new lwClipStill; - still->name = getS0(); - clip->source.still = still; - } - break; - - case ID_ISEQ: - { - lwClipSeq *seq = new lwClipSeq; - seq->digits = getU1(); - seq->flags = getU1(); - seq->offset = getI2(); - getU2(); /* reserved */ - seq->start = getI2(); - seq->end = getI2(); - seq->prefix = getS0(); - seq->suffix = getS0(); - clip->source.seq = seq; - } - break; - - case ID_ANIM: - { - lwClipAnim *anim = new lwClipAnim; - anim->name = getS0(); - anim->server = getS0(); - rlen = flen; - anim->data = getbytes( sz - rlen ); - clip->source.anim = anim; - } - break; - - case ID_XREF: - { - lwClipXRef *xref = new lwClipXRef; - xref->index = getI4(); - xref->string = getS0(); - clip->source.xref = xref; - } - break; - - case ID_STCC: - { - lwClipCycle *cycle = new lwClipCycle; - cycle->lo = getI2(); - cycle->hi = getI2(); - cycle->name = getS0(); - clip->source.cycle = cycle; - } - break; - - default: - break; - } - - /* error while reading current subchunk? */ - - rlen = flen; - if ( rlen < 0 || rlen > sz ) goto Fail; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - is->seekg(sz - rlen, ios_base::cur ); - - /* end of the CLIP chunk? */ - - rlen = is->tellg(); - rlen -= pos; - if ( chunksize < rlen ) goto Fail; - if ( chunksize == rlen ) - return clip; - - /* process subchunks as they're encountered */ - - id = getU4(); - sz = getU2(); - if ( 0 > flen ) goto Fail; - - for (;;) { - sz += sz & 1; - flen = 0; - - switch ( id ) { - case ID_TIME: - clip->start_time = getF4(); - clip->duration = getF4(); - clip->frame_rate = getF4(); - break; - - case ID_CONT: - clip->contrast.val = getF4(); - clip->contrast.eindex = getVX(); - break; - - case ID_BRIT: - clip->brightness.val = getF4(); - clip->brightness.eindex = getVX(); - break; - - case ID_SATR: - clip->saturation.val = getF4(); - clip->saturation.eindex = getVX(); - break; - - case ID_HUE: - clip->hue.val = getF4(); - clip->hue.eindex = getVX(); - break; - - case ID_GAMM: - clip->gamma.val = getF4(); - clip->gamma.eindex = getVX(); - break; - - case ID_NEGA: - clip->negative = getU2(); - break; - - case ID_IFLT: - case ID_PFLT: - filt = new lwPlugin; - if ( !filt ) goto Fail; - - filt->name = getS0(); - filt->flags = getU2(); - rlen = flen; - filt->data = getbytes( sz - rlen ); - - if ( id == ID_IFLT ) - clip->ifilters.push_back(filt); - else - clip->pfilters.push_back(filt); - - break; - - default: - break; - } - - /* error while reading current subchunk? */ - - rlen = flen; - if ( rlen < 0 || rlen > sz ) goto Fail; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - is->seekg(sz - rlen, ios_base::cur ); - - /* end of the CLIP chunk? */ - - rlen = is->tellg(); - rlen -= pos; - if ( chunksize < rlen ) goto Fail; - if ( chunksize == rlen ) break; - - /* get the next chunk header */ - - flen = 0; - id = getU4(); - sz = getU2(); - if ( 6 != flen ) goto Fail; - } - - return clip; - -Fail: - delete clip; - return NULL; -} - -lwEnvelope *lwReader::lwGetEnvelope() -{ - lwEnvelope *env; - lwKey *key; - lwPlugin *plug; - unsigned int id; - unsigned short sz; - float f[ 4 ]; - int i, nparams, pos; - unsigned int rlen; - - /* allocate the Envelope structure */ - - env = new lwEnvelope; - if ( !env ) goto Fail; - - /* remember where we started */ - - flen = 0; - pos = is->tellg(); - - /* index */ - - env->index = getVX(); - - /* first subchunk header */ - - id = getU4(); - sz = getU2(); - if ( 0 > flen ) goto Fail; - - /* process subchunks as they're encountered */ - - for (;;) { - sz += sz & 1; - flen = 0; - - switch ( id ) { - case ID_TYPE: - env->type = getU2(); - break; - - case ID_NAME: - env->name = getS0(); - break; - - case ID_PRE: - env->behavior[ 0 ] = getU2(); - break; - - case ID_POST: - env->behavior[ 1 ] = getU2(); - break; - - case ID_KEY: - key = env->addKey(getF4(), getF4()); - break; - - case ID_SPAN: - if ( !key ) goto Fail; - key->shape = getU4(); - - nparams = ( sz - 4 ) / 4; - if ( nparams > 4 ) nparams = 4; - for ( i = 0; i < nparams; i++ ) - f[ i ] = getF4(); - - switch ( key->shape ) { - case ID_TCB: - key->tension = f[ 0 ]; - key->continuity = f[ 1 ]; - key->bias = f[ 2 ]; - break; - - case ID_BEZI: - case ID_HERM: - case ID_BEZ2: - for ( i = 0; i < nparams; i++ ) - key->param[ i ] = f[ i ]; - break; - } - break; - - case ID_CHAN: - plug = new lwPlugin; - if ( !plug ) goto Fail; - - plug->name = getS0(); - plug->flags = getU2(); - plug->data = getbytes( sz - flen ); - - env->cfilters.push_back( plug ); - env->ncfilters++; - break; - - default: - break; - } - - /* error while reading current subchunk? */ - - rlen = flen; - if ( rlen < 0 || rlen > sz ) goto Fail; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - is->seekg(sz - rlen, ios_base::cur ); - - /* end of the ENVL chunk? */ - - rlen = is->tellg(); - rlen -= pos; - if ( chunksize < rlen ) goto Fail; - if ( chunksize == rlen ) break; - - /* get the next subchunk header */ - - flen = 0; - id = getU4(); - sz = getU2(); - if ( 6 != flen ) goto Fail; - } - - return env; - -Fail: - delete env; - return NULL; -} - -/* -====================================================================== -lwGetPoints() - - Read point records from a PNTS chunk in an LWO2 file. The points are - added to the array in the lwPointags. -====================================================================== */ - -int lwReader::lwGetPoints( vpoints &points ) -{ - if ( chunksize == 1 ) return 1; - - int npoints; - - npoints = chunksize / 12; - - int rpoints = npoints >= 4096 ? 4096 : npoints; - float *f = (float *)malloc(rpoints * 3 * sizeof(float)); - - while(npoints > 0) - { - is->read((char *)f, rpoints * 3 * sizeof(float)); - revbytes( f, sizeof(float), rpoints * 3 ); - for (int i = 0 ; i < rpoints * 3; i += 3 ) - points.push_back(new lwPoint(f[ i ], f[ i + 1 ], f[ i + 2 ])); - - npoints -= rpoints; - rpoints = npoints >= 4096 ? 4096 : npoints; - } - - free(f); - return 1; -} - -/* -====================================================================== -lwGetPolygons5() - -Read polygon records from a POLS chunk in an LWOB file. The polygons -are added to the array in the vpolygons. -======================================================================*/ - -int lwReader::lwGetLWOBPolygons( vpolygons &polygons, int ptoffset ) -{ - lwPolygon *polygon; - - char *buf, *bp; - int i, j, k, nv, nvertices, npolygons; - - if ( chunksize == 0 ) return 1; - - /* read the whole chunk */ - - flen = 0; - buf = getbytes( chunksize ); - if ( !buf ) goto Fail; - - /* count the polygons and vertices */ - - nvertices = 0; - npolygons = 0; - bp = buf; - - while ( bp < buf + chunksize ) - { - nv = sgetU2( &bp ); - nvertices += nv; - npolygons++; - bp += 2 * nv; - i = sgetI2( &bp ); - if ( i < 0 ) bp += 2; /* detail polygons */ - } - - k = 0; - bp = buf; - - for ( i = 0; i < npolygons; i++ ) - { - polygon = new lwPolygon; - nv = sgetU2( &bp ); - - polygon->type = ID_FACE; - for ( j = 0; j < nv; j++ ) - polygon->vertices.push_back(new lwVertex(sgetU2( &bp ) + ptoffset)); - - j = sgetI2( &bp ); - if ( j < 0 ) { - j = -j; - bp += 2; - } - j -= 1; - - polygon->surfidx = j; - polygons.push_back(polygon); - } - - free(buf); - return 1; - -Fail: - free(buf); - return 0; -} - -int lwReader::lwGetPolygons( vpolygons &polygons, int ptoffset ) -{ - lwPolygon *polygon; - char *buf, *bp; - - int i, j, flags, nv, nvertices, npolygons; - unsigned int type; - - if ( chunksize == 0 ) return 1; - - /* read the whole chunk */ - - flen = 0; - type = getU4(); - buf = getbytes( chunksize - 4 ); - if ( chunksize != flen ) goto Fail; - - /* count the polygons and vertices */ - - nvertices = 0; - npolygons = 0; - bp = buf; - - while ( bp < buf + chunksize - 4 ) - { - nv = sgetU2( &bp ); - nv &= 0x03FF; - nvertices += nv; - npolygons++; - for ( i = 0; i < nv; i++ ) - j = sgetVX( &bp ); - } - - /* fill in the new polygons */ - - bp = buf; - - for ( i = 0; i < npolygons; i++ ) - { - nv = sgetU2( &bp ); - flags = nv & 0xFC00; - nv &= 0x03FF; - - polygon = new lwPolygon; - - polygon->flags = flags; - polygon->type = type; - - for (j = 0; j < nv; j++ ) - polygon->vertices.push_back(new lwVertex( sgetVX( &bp ) + ptoffset )); - - polygons.push_back(polygon); - } - - free(buf); - return 1; - -Fail: - free(buf); - return 0; -} - -/* -====================================================================== -lwGetTags() - - Read tag strings from a TAGS chunk in an LWO2 file. The tags are - added to the lwTag array. -====================================================================== */ - -int lwReader::lwGetTags( vtags &tags ) -{ - char *buf, *bp; - - if ( chunksize == 0 ) return 1; - - /* read the whole chunk */ - - flen = 0; - buf = getbytes( chunksize ); - if ( !buf ) return 0; - - bp = buf; - while ( bp < buf + chunksize ) - tags.push_back( sgetS0( &bp )); - - free(buf); - return 1; -} - - -/* -====================================================================== -lwGetPolygonTags() - - Read polygon tags from a PTAG chunk in an LWO2 file. -====================================================================== */ - -int lwReader::lwGetPolygonTags( vtags &tags, int tagsoffset, vpolygons &polygons, int polygonsoffset ) -{ - unsigned int type; - unsigned int rlen; - int i, j; - - flen = 0; - type = getU4(); - rlen = flen; - if ( rlen < 0 ) return 0; - - if ( type != ID_SURF && type != ID_PART && type != ID_SMGP ) { - is->seekg(chunksize - 4, ios_base::cur ); - return 1; - } - - switch ( type ) - { - case ID_SURF: - while ( rlen < chunksize ) - { - i = getVX() + polygonsoffset; - j = getVX() + tagsoffset; - - rlen = flen; - if ( rlen < 0 || rlen > chunksize ) return 0; - - polygons[ i ]->surface = 0; - polygons[ i ]->surfidx = j; - } - break; - case ID_PART: - while ( rlen < chunksize ) - { - i = getVX() + polygonsoffset; - j = getVX() + tagsoffset; - rlen = flen; - if ( rlen < 0 || rlen > chunksize ) return 0; - - polygons[ i ]->part = j; - - } - break; - case ID_SMGP: - while ( rlen < chunksize ) - { - i = getVX() + polygonsoffset; - j = getVX() + tagsoffset; - rlen = flen; - if ( rlen < 0 || rlen > chunksize ) return 0; - - polygons[ i ]->smoothgrp = j; - - } - break; - } - - - return 1; -} - -/* -====================================================================== -lwGetTHeader() - - Read a texture map header from a SURF.BLOK in an LWO2 file. This is - the first subchunk in a BLOK, and its contents are common to all three - texture types. - ====================================================================== -*/ - -int lwReader::lwGetTHeader( int hsz, lwTexture &tex ) -{ - unsigned int id; - unsigned short sz; - int pos, rlen; - - /* remember where we started */ - - flen = 0; - pos = is->tellg(); - - /* ordinal string */ - - tex.ord = getS0(); - - /* first subchunk header */ - - id = getU4(); - sz = getU2(); - if ( 0 > flen ) return 0; - - /* process subchunks as they're encountered */ - - for (;;) { - sz += sz & 1; - flen = 0; - - switch ( id ) { - case ID_CHAN: - tex.chan = getU4(); - break; - - case ID_OPAC: - tex.opac_type = getU2(); - tex.opacity.val = getF4(); - tex.opacity.eindex = getVX(); - break; - - case ID_ENAB: - tex.enabled = getU2(); - break; - - case ID_NEGA: - tex.negative = getU2(); - break; - - case ID_AXIS: - tex.axis = getU2(); - break; - - default: - break; - } - - /* error while reading current subchunk? */ - - rlen = flen; - if ( rlen < 0 || rlen > sz ) return 0; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - is->seekg(sz - rlen, ios_base::cur ); - - /* end of the texture header subchunk? */ - - int fpos = is->tellg(); - if ( fpos == -1 ) break; - if ( hsz + pos <= fpos ) break; - -// if ( hsz + pos <= is->tellg()) -// break; - - /* get the next subchunk header */ - - flen = 0; - id = getU4(); - sz = getU2(); - if ( 6 != flen ) return 0; - }; - - int g = is->tellg(); - flen = g - pos; - return 1; -} - -/*====================================================================== -lwGetTMap() - - Read a texture map from a SURF.BLOK in an LWO2 file. The TMAP - defines the mapping from texture to world or object coordinates. -====================================================================== */ - -int lwReader::lwGetTMap( int tmapsz, lwTMap &tmap ) -{ - unsigned int id; - unsigned short sz; - int rlen, pos, i; - - pos = is->tellg(); - id = getU4(); - sz = getU2(); - if ( 0 > flen ) return 0; - - for (;;) { - sz += sz & 1; - flen = 0; - - switch ( id ) { - case ID_SIZE: - for ( i = 0; i < 3; i++ ) - tmap.size.val[ i ] = getF4(); - tmap.size.eindex = getVX(); - break; - - case ID_CNTR: - for ( i = 0; i < 3; i++ ) - tmap.center.val[ i ] = getF4(); - tmap.center.eindex = getVX(); - break; - - case ID_ROTA: - for ( i = 0; i < 3; i++ ) - tmap.rotate.val[ i ] = getF4(); - tmap.rotate.eindex = getVX(); - break; - - case ID_FALL: - tmap.fall_type = getU2(); - for ( i = 0; i < 3; i++ ) - tmap.falloff.val[ i ] = getF4(); - tmap.falloff.eindex = getVX(); - break; - - case ID_OREF: - tmap.ref_object = getS0(); - break; - - case ID_CSYS: - tmap.coord_sys = getU2(); - break; - - default: - break; - } - - /* error while reading the current subchunk? */ - - rlen = flen; - if ( rlen < 0 || rlen > sz ) return 0; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - is->seekg(sz - rlen, ios_base::cur ); - - /* end of the TMAP subchunk? */ - int fpos = is->tellg(); - if ( fpos == -1 ) break; - if ( tmapsz + pos <= fpos ) break; - -// if ( tmapsz + pos <= is->tellg() ) -// break; - - /* get the next subchunk header */ - - flen = 0; - id = getU4(); - sz = getU2(); - if ( 6 != flen ) return 0; - }; - - int g = is->tellg(); - flen = g - pos; - return 1; -} - -/*====================================================================== -lwGetImageMap() - -Read an lwImageMap from a SURF.BLOK in an LWO2 file. -====================================================================== */ - -lwImageMap *lwReader::lwGetImageMap( int rsz, lwTexture &tex ) -{ - unsigned int id; - unsigned short sz; - int rlen, pos; - - pos = is->tellg(); - id = getU4(); - sz = getU2(); - if ( 0 > flen ) return 0; - - lwImageMap *imap = new lwImageMap; - if (!imap) return NULL; - - for (;;) { - sz += sz & 1; - flen = 0; - - switch ( id ) { - case ID_TMAP: - if ( !lwGetTMap( sz, tex.tmap )) return 0; - break; - - case ID_PROJ: - imap->projection = getU2(); - break; - - case ID_VMAP: - imap->vmap_name = getS0(); - break; - - case ID_AXIS: - imap->axis = getU2(); - break; - - case ID_IMAG: - imap->cindex = getVX(); - break; - - case ID_WRAP: - imap->wrapw_type = getU2(); - imap->wraph_type = getU2(); - break; - - case ID_WRPW: - imap->wrapw.val = getF4(); - imap->wrapw.eindex = getVX(); - break; - - case ID_WRPH: - imap->wraph.val = getF4(); - imap->wraph.eindex = getVX(); - break; - - case ID_AAST: - imap->aas_flags = getU2(); - imap->aa_strength = getF4(); - break; - - case ID_PIXB: - imap->pblend = getU2(); - break; - - case ID_STCK: - imap->stck.val = getF4(); - imap->stck.eindex = getVX(); - break; - - case ID_TAMP: - imap->amplitude.val = getF4(); - imap->amplitude.eindex = getVX(); - break; - - default: - break; - } - - /* error while reading the current subchunk? */ - - rlen = flen; - if ( rlen < 0 || rlen > sz ) return 0; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - is->seekg(sz - rlen, ios_base::cur ); - - /* end of the image map? */ - - int fpos = is->tellg(); - if ( fpos == -1 ) break; - if ( rsz + pos <= fpos ) break; - -// if ( rsz + pos <= is->tellg() ) -// break; - - /* get the next subchunk header */ - - flen = 0; - id = getU4(); - sz = getU2(); - if ( 6 != flen ) return 0; - }; - - int g = is->tellg(); - flen = g - pos; - return imap; -} - - -/* -====================================================================== -lwGetProcedural() - -Read an lwProcedural from a SURF.BLOK in an LWO2 file. -====================================================================== -*/ - -lwProcedural *lwReader::lwGetProcedural( int rsz, lwTexture &tex ) -{ - unsigned int id; - unsigned short sz; - int rlen, pos, fpos; - - pos = is->tellg(); - id = getU4(); - sz = getU2(); - if ( 0 > flen ) return 0; - - lwProcedural *proc = new lwProcedural; - if (!proc) return NULL; - - for (;;) { - sz += sz & 1; - flen = 0; - - switch ( id ) { - case ID_TMAP: - if ( !lwGetTMap( sz, tex.tmap )) return 0; - break; - - case ID_AXIS: - proc->axis = getU2(); - break; - - case ID_VALU: - proc->value[ 0 ] = getF4(); - if ( sz >= 8 ) proc->value[ 1 ] = getF4(); - if ( sz >= 12 ) proc->value[ 2 ] = getF4(); - break; - - case ID_FUNC: - proc->name = getS0(); - rlen = flen; - proc->data = getbytes( sz - rlen ); - break; - - default: - break; - } - - /* error while reading the current subchunk? */ - - rlen = flen; - if ( rlen < 0 || rlen > sz ) return 0; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - is->seekg(sz - rlen, ios_base::cur ); - - /* end of the procedural block? */ - - fpos = is->tellg(); - - if (fpos == -1) - { - flen = -pos; - return proc; - } - - if ( rsz + pos <= fpos ) - break; - - // if ( rsz + pos <= is->tellg()) - // break; - - /* get the next subchunk header */ - - flen = 0; - id = getU4(); - sz = getU2(); - if ( 6 != flen ) return 0; - }; - - int g = is->tellg(); - flen = g - pos; - return proc; -} - - -/* -====================================================================== -lwGetGradient() - -Read an lwGradient from a SURF.BLOK in an LWO2 file. -====================================================================== */ - -lwGradient *lwReader::lwGetGradient( int rsz, lwTexture &tex ) -{ - unsigned int id; - unsigned short sz; - int rlen, pos, i, j, nkeys; - - pos = is->tellg(); - id = getU4(); - sz = getU2(); - if ( 0 > flen ) return 0; - - lwGradient *grad = new lwGradient; - if (!grad) return NULL; - - for (;;) { - sz += sz & 1; - flen = 0; - - switch ( id ) { - case ID_TMAP: - if ( !lwGetTMap( sz, tex.tmap )) return 0; - break; - - case ID_PNAM: - grad->paramname = getS0(); - break; - - case ID_INAM: - grad->itemname = getS0(); - break; - - case ID_GRST: - grad->start = getF4(); - break; - - case ID_GREN: - grad->end = getF4(); - break; - - case ID_GRPT: - grad->repeat = getU2(); - break; - - case ID_FKEY: - nkeys = sz / sizeof( lwGradKey ); - grad->key = (lwGradKey *)malloc(nkeys * sizeof(lwGradKey)); - if ( !grad->key ) return 0; - for ( i = 0; i < nkeys; i++ ) { - grad->key[ i ].value = getF4(); - for ( j = 0; j < 4; j++ ) - grad->key[ i ].rgba[ j ] = getF4(); - } - break; - - case ID_IKEY: - nkeys = sz / 2; - grad->ikey = (short *)malloc(nkeys * sizeof(short)); - if ( !grad->ikey ) return 0; - for ( i = 0; i < nkeys; i++ ) - grad->ikey[ i ] = getU2(); - break; - - default: - break; - } - - /* error while reading the current subchunk? */ - - rlen = flen; - if ( rlen < 0 || rlen > sz ) return 0; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - is->seekg(sz - rlen, ios_base::cur ); - - /* end of the gradient? */ - - int fpos = is->tellg(); - if ( fpos == -1 ) break; - if ( rsz + pos <= fpos ) break; - -// if ( rsz + pos <= is->tellg() ) -// break; - - /* get the next subchunk header */ - - flen = 0; - id = getU4(); - sz = getU2(); - if ( 6 != flen ) return 0; - }; - - int g = is->tellg(); - flen = g - pos; - return grad; -} - - -/* -====================================================================== -lwGetTexture() - -Read an lwTexture from a SURF.BLOK in an LWO2 file. -====================================================================== */ - -lwTexture *lwReader::lwGetTexture( int bloksz, unsigned int type ) -{ - lwTexture *tex; - unsigned short sz; - bool ok; - - tex = new lwTexture; - if ( !tex ) return NULL; - - tex->type = type; - - sz = getU2(); - if ( !lwGetTHeader( sz, *tex )) { - delete tex; - return NULL; - } - - sz = bloksz - sz - 6; - switch ( type ) { - case ID_IMAP: - tex->param.imap = lwGetImageMap( sz, *tex ); - ok = tex->param.imap!=0; - break; - case ID_PROC: - tex->param.proc = lwGetProcedural( sz, *tex ); - ok = tex->param.proc!=0; - break; - case ID_GRAD: - tex->param.grad = lwGetGradient( sz, *tex ); - ok = tex->param.grad!=0; - break; - default: - ok = !is->seekg(sz, ios_base::cur ); - } - - if ( !ok ) - { - delete tex; - return NULL; - } - - flen = bloksz; - return tex; -} - -/* -====================================================================== -lwGetShader() - -Read a shader record from a SURF.BLOK in an LWO2 file. -====================================================================== */ - -lwPlugin *lwReader::lwGetShader( int bloksz ) -{ - lwPlugin *shdr; - unsigned int id; - unsigned short sz; - int hsz, rlen, pos; - int g = 0; - - shdr = new lwPlugin; - if ( !shdr ) return NULL; - - pos = is->tellg(); - flen = 0; - hsz = getU2(); - shdr->ord = getS0(); - id = getU4(); - sz = getU2(); - if ( 0 > flen ) goto Fail; - - while ( hsz > 0 ) - { - sz += sz & 1; - hsz -= sz; - if ( id == ID_ENAB ) { - shdr->flags = getU2(); - break; - } - else { - is->seekg(sz, ios_base::cur ); - id = getU4(); - sz = getU2(); - } - } - - id = getU4(); - sz = getU2(); - if ( 0 > flen ) goto Fail; - - for (;;) - { - sz += sz & 1; - flen = 0; - - switch ( id ) { - case ID_FUNC: - shdr->name = getS0(); - rlen = flen; - shdr->data = getbytes( sz - rlen ); - break; - - default: - break; - } - - /* error while reading the current subchunk? */ - - rlen = flen; - if ( rlen < 0 || rlen > sz ) goto Fail; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - is->seekg(sz - rlen, ios_base::cur ); - - /* end of the shader block? */ - - int fpos = is->tellg(); - if ( fpos == -1 ) break; - if ( bloksz + pos <= fpos ) break; - - - // if ( bloksz + pos <= is->tellg() ) - // break; - - /* get the next subchunk header */ - - flen = 0; - id = getU4(); - sz = getU2(); - if ( 6 != flen ) goto Fail; - }; - - g = is->tellg(); - flen = g - pos; - return shdr; - -Fail: - delete shdr; - return NULL; -} - -/*====================================================================== -add_clip() - -Add a clip to the clip list. Used to store the contents of an RIMG or -TIMG surface subchunk. -======================================================================*/ - -int lwReader::add_clip( char *s, vclips &clips ) -{ - lwClip *clip; - char *p; - - clip = new lwClip; - if ( !clip ) return 0; - - if ( p = strstr( s, "(sequence)" )) - { - p[ -1 ] = 0; - clip->type = ID_ISEQ; - lwClipSeq *seq = new lwClipSeq; - seq->prefix = s; - seq->digits = 3; - clip->source.seq = seq; - } - else - { - clip->type = ID_STIL; - lwClipStill *still = new lwClipStill; - still->name = s; - clip->source.still = still; - } - - clips.push_back( clip ); - clip->index = clips.size()-1; - - return clip->index; -} - - -/*====================================================================== -add_tvel() - -Add a triple of envelopes to simulate the old texture velocity -parameters. -======================================================================*/ - -int lwReader::add_tvel( float pos[], float vel[], venvelopes &envelopes ) -{ - lwEnvelope *env; - lwKey *key0, *key1; - int i; - - for ( i = 0; i < 3; i++ ) - { - env = new lwEnvelope; - key0 = new lwKey(0.0f, pos[ i ]); - key1 = new lwKey(1.0f, pos[ i ] + vel[ i ] * 30.0f); // 30.0f == NTSC related ? - - key0->shape = key1->shape = ID_LINE; - - env->keys.push_back( key0 ); - env->keys.push_back( key1 ); - - env->type = 0x0301 + i; - env->name = (char *)malloc(11); - if ( env->name ) - { - strcpy( env->name, "Position.X" ); - env->name[ 9 ] += i; - } - - env->behavior[ 0 ] = BEH_LINEAR; - env->behavior[ 1 ] = BEH_LINEAR; - - envelopes.push_back( env ); - env->index = envelopes.size()-1; - } - return env->index - 2; -} - - -/*====================================================================== -get_texture() - -Create a new texture for BTEX, CTEX, etc. subchunks. -======================================================================*/ - -lwTexture *lwReader::get_texture( char *s ) -{ - lwTexture *tex = new lwTexture; - if ( !tex ) return NULL; - - if ( strstr( s, "Image Map" )) - { - tex->type = ID_IMAP; - lwImageMap *imap = new lwImageMap; - tex->param.imap = imap; - if ( strstr( s, "Planar" )) imap->projection = 0; - else if ( strstr( s, "Cylindrical" )) imap->projection = 1; - else if ( strstr( s, "Spherical" )) imap->projection = 2; - else if ( strstr( s, "Cubic" )) imap->projection = 3; - else if ( strstr( s, "Front" )) imap->projection = 4; - imap->aa_strength = 1.0f; - imap->amplitude.val = 1.0f; - free(s); - } - else - { - tex->type = ID_PROC; - lwProcedural *proc = new lwProcedural; - tex->param.proc = proc; - proc->name = s; - } - return tex; -} - -lwSurface *lwReader::lwGetLWOBSurface( lwObject *obj ) -{ - lwTexture *tex = 0; - lwPlugin *shdr = 0; - char *s; - float v[ 3 ]; - unsigned int flags; - unsigned short sz; - int rlen, i; - - long filepos = is->tellg(); - long chunkstart = filepos; - long chunkend = chunkstart + chunksize; - - /* allocate the Surface structure */ - - lwSurface *surf = new lwSurface; - if ( !surf ) return NULL; - - /* name */ - - surf->name = getS0(); - - /* process subchunks as they're encountered */ - filepos = is->tellg(); - if (filepos == -1) return surf; - if ( filepos > chunkend ) return surf; // error: read too much - - while( filepos < chunkend ) - { - currentchunkid = getU4(); - sz = getU2(); - sz += sz & 1; - flen = 0; - - switch ( currentchunkid ) - { - case ID_COLR: - surf->color.rgb[ 0 ] = getU1() / 255.0f; - surf->color.rgb[ 1 ] = getU1() / 255.0f; - surf->color.rgb[ 2 ] = getU1() / 255.0f; - break; - - case ID_FLAG: - flags = getU2(); - if ( flags & 4 ) surf->smooth = 1.56207f; - if ( flags & 8 ) surf->color_hilite.val = 1.0f; - if ( flags & 16 ) surf->color_filter.val = 1.0f; - if ( flags & 128 ) surf->dif_sharp.val = 0.5f; - if ( flags & 256 ) surf->sideflags = 3; - if ( flags & 512 ) surf->add_trans.val = 1.0f; - break; - - case ID_LUMI: - surf->luminosity.val = getI2() / 256.0f; - break; - - case ID_VLUM: - surf->luminosity.val = getF4(); - break; - - case ID_DIFF: - surf->diffuse.val = getI2() / 256.0f; - break; - - case ID_VDIF: - surf->diffuse.val = getF4(); - break; - - case ID_SPEC: - surf->specularity.val = getI2() / 256.0f; - break; - - case ID_VSPC: - surf->specularity.val = getF4(); - break; - - case ID_GLOS: - surf->glossiness.val = (float)log((double)getU2()) / 20.7944f; - break; - - case ID_SMAN: - surf->smooth = getF4(); - break; - - case ID_REFL: - surf->reflection.val.val = getI2() / 256.0f; - break; - - case ID_RFLT: - surf->reflection.options = getU2(); - break; - - case ID_RIMG: - s = getS0(); - surf->reflection.cindex = add_clip( s, obj->clips ); - surf->reflection.options = 3; - break; - - case ID_RSAN: - surf->reflection.seam_angle = getF4(); - break; - - case ID_TRAN: - surf->transparency.val.val = getI2() / 256.0f; - break; - - case ID_RIND: - surf->eta.val = getF4(); - break; - - case ID_BTEX: - s = getbytes( sz ); - tex = get_texture( s ); - surf->bump.textures.push_back( tex ); - break; - - case ID_CTEX: - s = getbytes( sz ); - tex = get_texture( s ); - surf->color.textures.push_back( tex ); - break; - - case ID_DTEX: - s = getbytes( sz ); - tex = get_texture( s ); - surf->diffuse.textures.push_back( tex ); - break; - - case ID_LTEX: - s = getbytes( sz ); - tex = get_texture( s ); - surf->luminosity.textures.push_back( tex ); - break; - - case ID_RTEX: - s = getbytes( sz ); - tex = get_texture( s ); - surf->reflection.val.textures.push_back( tex ); - break; - - case ID_STEX: - s = getbytes( sz ); - tex = get_texture( s ); - surf->specularity.textures.push_back( tex ); - break; - - case ID_TTEX: - s = getbytes( sz ); - tex = get_texture( s ); - surf->transparency.val.textures.push_back( tex ); - break; - - case ID_TFLG: - flags = getU2(); - - if ( flags & 1 ) i = 0; - if ( flags & 2 ) i = 1; - if ( flags & 4 ) i = 2; - tex->axis = i; - if ( tex->type == ID_IMAP ) - { - tex->param.imap->axis = i; - if ( flags & 32 ) - tex->param.imap->pblend = 1; - if ( flags & 64 ) - { - tex->param.imap->aa_strength = 1.0f; - tex->param.imap->aas_flags = 1; - } - } - if ( tex->type == ID_PROC ) - tex->param.proc->axis = i; - - if ( flags & 8 ) tex->tmap.coord_sys = 1; - if ( flags & 16 ) tex->negative = 1; - break; - - case ID_TSIZ: - for ( i = 0; i < 3; i++ ) - tex->tmap.size.val[ i ] = getF4(); - break; - - case ID_TCTR: - for ( i = 0; i < 3; i++ ) - tex->tmap.center.val[ i ] = getF4(); - break; - - case ID_TFAL: - for ( i = 0; i < 3; i++ ) - tex->tmap.falloff.val[ i ] = getF4(); - break; - - case ID_TVEL: - for ( i = 0; i < 3; i++ ) - v[ i ] = getF4(); - tex->tmap.center.eindex = add_tvel( tex->tmap.center.val, v, obj->envelopes ); - break; - - case ID_TCLR: - if ( tex->type == ID_PROC ) - for ( i = 0; i < 3; i++ ) - tex->param.proc->value[ i ] = getU1() / 255.0f; - break; - - case ID_TVAL: - if ( tex->type == ID_PROC ) - tex->param.proc->value[ 0 ] = getI2() / 256.0f; - break; - - case ID_TAMP: - if ( tex->type == ID_IMAP ) - tex->param.imap->amplitude.val = getF4(); - break; - - case ID_TIMG: - if ( tex->type == ID_IMAP ) - { - s = getS0(); - tex->param.imap->cindex = add_clip( s, obj->clips ); - } - break; - - case ID_TAAS: - if ( tex->type == ID_IMAP ) - { - tex->param.imap->aa_strength = getF4(); - tex->param.imap->aas_flags = 1; - } - break; - - case ID_TREF: - tex->tmap.ref_object = getbytes( sz ); - break; - - case ID_TOPC: - tex->opacity.val = getF4(); - break; - - case ID_TFP0: - if ( tex->type == ID_IMAP ) - tex->param.imap->wrapw.val = getF4(); - break; - - case ID_TFP1: - if ( tex->type == ID_IMAP ) - tex->param.imap->wraph.val = getF4(); - break; - - case ID_SHDR: - shdr = new lwPlugin; - if ( !shdr ) goto Fail; - shdr->name = getbytes( sz ); - surf->shaders.push_back( shdr ); - break; - - case ID_SDAT: - shdr->data = getbytes( sz ); - break; - default: - break; - } - - /* error while reading current subchunk? */ - - rlen = flen; - if ( rlen < 0 || rlen > sz ) goto Fail; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - is->seekg(sz - rlen, ios_base::cur ); - - /* end of the SURF chunk? */ - - filepos = is->tellg(); - if ( filepos == -1 ) break; // end of file ? - if ( filepos > chunkend ) // error: read too much - { - is->seekg(chunkend, ios_base::beg ); - break; - } - } - return surf; -Fail: - if ( surf ) delete surf; - return NULL; -} - - -/* -====================================================================== -lwGetSurface() - -Read an lwSurface from an LWO2 file. -====================================================================== */ - -lwSurface *lwReader::lwGetSurface() -{ - lwSurface *surf; - lwTexture *tex; - lwPlugin *shdr; - unsigned int id, type; - unsigned short sz; - unsigned int pos, rlen, fpos; - - /* allocate the Surface structure */ - - surf = new lwSurface; - if ( !surf ) goto Fail; - - /* remember where we started */ - - flen = 0; - pos = is->tellg(); - - /* names */ - - surf->name = getS0(); - surf->srcname = getS0(); - - /* first subchunk header */ - - id = getU4(); - sz = getU2(); - if ( 0 > flen ) goto Fail; - - /* process subchunks as they're encountered */ - - for (;;) { - sz += sz & 1; - flen = 0; - - switch ( id ) { - case ID_COLR: - surf->color.rgb[ 0 ] = getF4(); - surf->color.rgb[ 1 ] = getF4(); - surf->color.rgb[ 2 ] = getF4(); - surf->color.eindex = getVX(); - break; - - case ID_LUMI: - surf->luminosity.val = getF4(); - surf->luminosity.eindex = getVX(); - break; - - case ID_DIFF: - surf->diffuse.val = getF4(); - surf->diffuse.eindex = getVX(); - break; - - case ID_SPEC: - surf->specularity.val = getF4(); - surf->specularity.eindex = getVX(); - break; - - case ID_GLOS: - surf->glossiness.val = getF4(); - surf->glossiness.eindex = getVX(); - break; - - case ID_REFL: - surf->reflection.val.val = getF4(); - surf->reflection.val.eindex = getVX(); - break; - - case ID_RFOP: - surf->reflection.options = getU2(); - break; - - case ID_RIMG: - surf->reflection.cindex = getVX(); - break; - - case ID_RSAN: - surf->reflection.seam_angle = getF4(); - break; - - case ID_TRAN: - surf->transparency.val.val = getF4(); - surf->transparency.val.eindex = getVX(); - break; - - case ID_TROP: - surf->transparency.options = getU2(); - break; - - case ID_TIMG: - surf->transparency.cindex = getVX(); - break; - - case ID_RIND: - surf->eta.val = getF4(); - surf->eta.eindex = getVX(); - break; - - case ID_TRNL: - surf->translucency.val = getF4(); - surf->translucency.eindex = getVX(); - break; - - case ID_BUMP: - surf->bump.val = getF4(); - surf->bump.eindex = getVX(); - break; - - case ID_SMAN: - surf->smooth = getF4(); - break; - - case ID_SIDE: - surf->sideflags = getU2(); - break; - - case ID_CLRH: - surf->color_hilite.val = getF4(); - surf->color_hilite.eindex = getVX(); - break; - - case ID_CLRF: - surf->color_filter.val = getF4(); - surf->color_filter.eindex = getVX(); - break; - - case ID_ADTR: - surf->add_trans.val = getF4(); - surf->add_trans.eindex = getVX(); - break; - - case ID_SHRP: - surf->dif_sharp.val = getF4(); - surf->dif_sharp.eindex = getVX(); - break; - - case ID_GVAL: - surf->glow.val = getF4(); - surf->glow.eindex = getVX(); - break; - - case ID_LINE: - surf->line.enabled = 1; - if ( sz >= 2 ) surf->line.flags = getU2(); - if ( sz >= 6 ) surf->line.size.val = getF4(); - if ( sz >= 8 ) surf->line.size.eindex = getVX(); - break; - - case ID_ALPH: - surf->alpha_mode = getU2(); - surf->alpha = getF4(); - break; - - case ID_AVAL: - surf->alpha = getF4(); - break; - - case ID_BLOK: - type = getU4(); - - switch ( type ) { - case ID_IMAP: - case ID_PROC: - case ID_GRAD: - tex = lwGetTexture( sz - 4, type ); - if ( !tex ) goto Fail; - if ( !surf->addTexture(tex) ) delete tex; - flen += 4; - break; - case ID_SHDR: - shdr = lwGetShader( sz - 4 ); - if ( !shdr ) goto Fail; - surf->shaders.insert(lower_bound(surf->shaders.begin(), surf->shaders.end(), shdr), shdr); - flen += 4; - break; - } - break; - - default: - break; - } - - /* error while reading current subchunk? */ - - rlen = flen; - if ( rlen < 0 || rlen > sz ) goto Fail; - - /* skip unread parts of the current subchunk */ - - if ( rlen < sz ) - is->seekg(sz - rlen, ios_base::cur ); - - /* end of the SURF chunk? */ - - fpos = is->tellg(); - if ( fpos == -1 ) break; - if ( chunksize + pos <= fpos ) break; - - /* get the next subchunk header */ - - flen = 0; - id = getU4(); - sz = getU2(); - if ( 6 != flen ) goto Fail; - } - - return surf; - -Fail: - if ( surf ) delete surf; - return NULL; -} - -/* -====================================================================== -lwGetVMap() - - Read an lwVMap from a VMAP or VMAD chunk in an LWO2. -====================================================================== */ - -lwVMap *lwReader::lwGetVMap( int ptoffset, int poloffset, int perpoly ) -{ - char *buf, *bp; - lwVMap *vmap; - unsigned int i, j, npts, rlen; - - /* read the whole chunk */ - - flen = 0; - buf = getbytes( chunksize ); - if ( !buf ) return NULL; - - vmap = new lwVMap; - if ( !vmap ) { - free(buf); - return NULL; - } - - /* initialize the vmap */ - - vmap->perpoly = perpoly; - - bp = buf; - flen = 0; - vmap->type = sgetU4( &bp ); - vmap->dim = sgetU2( &bp ); - vmap->name = sgetS0( &bp ); - rlen = flen; - - /* count the vmap records */ - - npts = 0; - while ( bp < buf + chunksize ) { - i = sgetVX( &bp ); - if ( perpoly ) - i = sgetVX( &bp ); - bp += vmap->dim * sizeof( float ); - ++npts; - } - - /* allocate the vmap */ - - vmap->nverts = npts; - vmap->vindex = (int *)malloc(npts * sizeof(int)); - if ( !vmap->vindex ) goto Fail; - if ( perpoly ) - { - vmap->pindex = (int *)malloc(npts * sizeof(int)); - if ( !vmap->pindex ) goto Fail; - } - - if ( vmap->dim > 0 ) - { - vmap->val = (float **)malloc(npts * sizeof(float *)); - if ( !vmap->val ) goto Fail; - for ( i = 0; i < npts; i++ ) - vmap->val[ i ] = (float *)malloc(vmap->dim * sizeof( float )); - } - - /* fill in the vmap values */ - - bp = buf + rlen; - for ( i = 0; i < npts; i++ ) { - vmap->vindex[ i ] = sgetVX( &bp ); - if ( perpoly ) - vmap->pindex[ i ] = sgetVX( &bp ); - for ( j = 0; j < vmap->dim; j++ ) - vmap->val[ i ][ j ] = sgetF4( &bp ); - } - - free(buf); - return vmap; - -Fail: - free(buf); - delete vmap; - return NULL; -} diff --git a/Tools/LightwaveConverter/src/lwo2mesh.cpp b/Tools/LightwaveConverter/src/lwo2mesh.cpp deleted file mode 100644 index a875b4d3dec..00000000000 --- a/Tools/LightwaveConverter/src/lwo2mesh.cpp +++ /dev/null @@ -1,764 +0,0 @@ -#include "Vector3.h" -#include "lwo2mesh.h" -#include "Ogre.h" -#include "OgreMesh.h" -#include "OgreStringConverter.h" -#include "OgreDefaultHardwareBufferManager.h" - -#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX -#include -#include // FLT_MIN, FLT_MAX -#include // dirname(), basename(). -#include // strtok(); -#include // string class -#endif - -#define POLYLIMIT 0x5555 -#define POINTLIMIT 0x5555 - -extern Mesh::LodDistanceList distanceList; -extern Real reduction; -extern bool flags[NUMFLAGS]; -extern MaterialSerializer* materialSerializer; -extern char *matPrefix; - -extern ostream& nl(ostream& os); - -#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX - -/* We expect the caller to provide an arrays of chars for the output. */ -void _splitpath( const char *_fn, char *_drive, char *_dir, char *_node, char *_ext ) { - - /* A crazy mix of both c and c++.. */ - - const char *delimiters = "."; - char buf[ _MAX_DRIVE+_MAX_DIR+_MAX_FNAME+_MAX_EXT + 5 ]; - char *exte, *ddir, *fnam, *_ext_tmp; - - strcpy( buf, _fn ); - strcpy( _drive, "" ); // _drive is always empth on linux. - - if ( String( buf ).empty() ) { - strcpy( _node, "" ); - strcpy( _dir, "" ); - strcpy( _ext, "" ); - return; - } - - fnam = basename( buf ); - strcpy( _node, fnam ); - ddir = dirname( buf ); - strcpy( _dir, ddir ); - - _ext_tmp = strtok( fnam, delimiters ); - while ( ( _ext_tmp = strtok( NULL, delimiters ) ) != NULL ) exte = _ext_tmp; - strcpy( _ext, exte ); - - _node[ strlen(_node) - strlen(_ext) - 1 ] = '\0'; - -} - -/* We expect the caller to provide an array of chars for the output. */ -void _makepath( char *_fn, const char *_drive, const char *_dir, - const char *_node, const char *_ext ) { - - /* A crazy mix of both c and c++.. */ - - std::string buf(""); - - if ( _drive != NULL ) // On Linux, this is usually empty. - buf += _drive; - - if ( _dir != NULL ) { // The directory part. - if ( std::string(_dir).empty() ) - buf += "."; - buf += _dir; - buf += "/"; - } - - if ( _node != NULL ) // The filename without the extension. - buf += _node; - - if ( _ext != NULL ) { // The extension. - if ( std::string( _ext ).compare( 0, 1, "." ) != 0 ) - buf += "."; - buf += _ext; - } - - strcpy( _fn, buf.c_str() ); -} - -#endif - -void Lwo2MeshWriter::doExportMaterials() -{ - char - drive[ _MAX_DRIVE ], - dir[ _MAX_DIR ], - node[ _MAX_FNAME ], - ext[ _MAX_EXT ], - texname [128]; - - unsigned int slength = 0; - - if (flags[RenameMaterials]) - { - if (flags[UseInteractiveMethod]) - { - for (unsigned int i = 0; i < object->surfaces.size(); ++i) - { - lwSurface *surface = object->surfaces[i]; - cout << "Rename surface " << surface->name << " to: "; - cin >> texname; - surface->setname(texname); - } - } else { - _splitpath( dest, drive, dir, node, ext ); - - for (unsigned int i = 0; i < object->surfaces.size(); ++i) - { - lwSurface *surface = object->surfaces[i]; - if (flags[UsePrefixMethod]) - strcpy(texname,matPrefix); - else - { - strcpy(texname,node); - strcat(texname,"_"); - } - - strcat(texname, surface->name); - surface->setname(texname); - } - } - } - - for (unsigned int i = 0; i < object->surfaces.size(); ++i) - { - lwSurface *surface = object->surfaces[i]; - - // Create deferred material so no load - MaterialPtr ogreMat = MaterialManager::getSingleton().getByName(surface->name); - - if (!ogreMat) - { - ogreMat = MaterialManager::getSingleton().create(surface->name, - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - ogreMat->setAmbient - ( - surface->color.rgb[0], - surface->color.rgb[1], - surface->color.rgb[2] - ); - - ogreMat->setDiffuse - ( - surface->diffuse.val * surface->color.rgb[0], - surface->diffuse.val * surface->color.rgb[1], - surface->diffuse.val * surface->color.rgb[2], - 1.0f - ); - - ogreMat->setSpecular - ( - surface->specularity.val * surface->color.rgb[0], - surface->specularity.val * surface->color.rgb[1], - surface->specularity.val * surface->color.rgb[2], - 1.0f - ); - - ogreMat->setShininess(surface->glossiness.val); - - ogreMat->setSelfIllumination - ( - surface->luminosity.val * surface->color.rgb[0], - surface->luminosity.val * surface->color.rgb[1], - surface->luminosity.val * surface->color.rgb[2] - ); - - unsigned int j; - lwTexture *tex; - int cindex; - lwClip *clip; - - for (j = 0; j < surface->color.textures.size(); j++) - { - tex = surface->color.textures[j]; - cindex = tex->param.imap->cindex; - clip = object->lwFindClip(cindex); - - if (clip) - { - _splitpath( clip->source.still->name, drive, dir, node, ext ); - _makepath( texname, 0, 0, node, ext ); - ogreMat->getTechnique(0)->getPass(0)->createTextureUnitState(texname); - } - } - - for (j = 0; j < surface->transparency.val.textures.size(); j++) - { - tex = surface->transparency.val.textures[j]; - cindex = tex->param.imap->cindex; - clip = object->lwFindClip(cindex); - - if (clip) - { - _splitpath( clip->source.still->name, drive, dir, node, ext ); - _makepath( texname, 0, 0, node, ext ); - ogreMat->getTechnique(0)->getPass(0)->createTextureUnitState(texname); - } - } - materialSerializer->queueForExport(ogreMat); - } - } -} - -Skeleton *Lwo2MeshWriter::doExportSkeleton(const String &skelName, int l) -{ - vpolygons bones; - bones.clear(); - bones.reserve(256); - - vpoints bonepoints; - bonepoints.clear(); - bonepoints.reserve(512); - - if (l == -1) - { - for (l = 0; l < object->layers.size(); ++l) - { - copyPoints(-1, ID_BONE, object->layers[l]->points, bonepoints); - copyPolygons(-1, ID_BONE, object->layers[l]->polygons, bones); - } - } - else - { - copyPoints(-1, ID_BONE, object->layers[l]->points, bonepoints); - copyPolygons(-1, ID_BONE, object->layers[l]->polygons, bones); - } - - if (!bones.size()) return NULL; // no bones means no skeleton - - SkeletonPtr ogreskel = Ogre::SkeletonManager::getSingleton().create(skelName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - unsigned int i; - // Create all the bones in turn - for (i = 0; i < bones.size(); ++i) - { - lwPolygon* bone = bones[i]; - if (bone->vertices.size() != 2) continue; // a bone has only 2 sides - - Bone* ogreBone = ogreskel->createBone("Bone"); - - Ogre::Vector3 bonePos(bone->vertices[0]->point->x, bone->vertices[0]->point->y, bone->vertices[0]->point->z); - - ogreBone->setPosition(bonePos); - // Hmm, Milkshape has chosen a Euler angle representation of orientation which is not smart - // Rotation Matrix or Quaternion would have been the smarter choice - // Might we have Gimbal lock here? What order are these 3 angles supposed to be applied? - // Grr, we'll try our best anyway... - Quaternion qx, qy, qz, qfinal; -/* - qx.FromAngleAxis(msBoneRot[0], Vector3::UNIT_X); - qy.FromAngleAxis(msBoneRot[1], Vector3::UNIT_Y); - qz.FromAngleAxis(msBoneRot[2], Vector3::UNIT_Z); -*/ - // Assume rotate by x then y then z - qfinal = qz * qy * qx; - ogreBone->setOrientation(qfinal); - } -/* - for (i = 0; i < numBones; ++i) - { - msBone* bone = msModel_GetBoneAt(pModel, i); - - if (strlen(bone->szParentName) == 0) - { - } - else - { - Bone* ogrechild = ogreskel->getBone(bone->szName); - Bone* ogreparent = ogreskel->getBone(bone->szParentName); - - if (ogrechild == 0) - { - continue; - } - if (ogreparent == 0) - { - continue; - } - // Make child - ogreparent->addChild(ogrechild); - } - - - } - - // Create the Animation(s) - doExportAnimations(pModel, ogreskel); - - // Create skeleton serializer & export - SkeletonSerializer serializer; - serializer.exportSkeleton(ogreskel, szFile); - - ogreMesh->_notifySkeleton(ogreskel); - - return ogreskel; -*/ - if (ogreskel) - Ogre::SkeletonManager::getSingleton().remove(ogreskel->getHandle()); - - return NULL; -} - -#define POSITION_BINDING 0 -#define NORMAL_BINDING 1 -#define TEXCOORD_BINDING 2 - -VertexData *Lwo2MeshWriter::setupVertexData(unsigned short vertexCount, VertexData *oldVertexData, bool deleteOldVertexData) -{ - VertexData *vertexData = new VertexData(); - - if (oldVertexData) - { - // Basic vertex info - vertexData->vertexStart = oldVertexData->vertexStart; - vertexData->vertexCount = oldVertexData->vertexCount + vertexCount; - - const VertexBufferBinding::VertexBufferBindingMap bindings = oldVertexData->vertexBufferBinding->getBindings(); - VertexBufferBinding::VertexBufferBindingMap::const_iterator vbi, vbend; - vbend = bindings.end(); - - for (vbi = bindings.begin(); vbi != vbend; ++vbi) - { - HardwareVertexBufferSharedPtr srcbuf = vbi->second; - // create new buffer with the same settings - HardwareVertexBufferSharedPtr dstBuf = - HardwareBufferManager::getSingleton().createVertexBuffer( - srcbuf->getVertexSize(), srcbuf->getNumVertices() + vertexCount, srcbuf->getUsage(), srcbuf->isSystemMemory()); - - // copy data - dstBuf->copyData(*srcbuf, 0, 0, srcbuf->getSizeInBytes(), true); - - // Copy binding - vertexData->vertexBufferBinding->setBinding(vbi->first, dstBuf); - } - - // Copy elements - const VertexDeclaration::VertexElementList elems = oldVertexData->vertexDeclaration->getElements(); - VertexDeclaration::VertexElementList::const_iterator ei, eiend; - eiend = elems.end(); - for (ei = elems.begin(); ei != eiend; ++ei) - { - vertexData->vertexDeclaration->addElement( - ei->getSource(), - ei->getOffset(), - ei->getType(), - ei->getSemantic(), - ei->getIndex() ); - } - if (deleteOldVertexData) delete oldVertexData; - } - else - { - vertexData->vertexCount = vertexCount; - - VertexBufferBinding* bind = vertexData->vertexBufferBinding; - VertexDeclaration* decl = vertexData->vertexDeclaration; - - decl->addElement(POSITION_BINDING, 0, VET_FLOAT3, VES_POSITION); - HardwareVertexBufferSharedPtr pbuf = HardwareBufferManager::getSingleton().createVertexBuffer(decl->getVertexSize(POSITION_BINDING), vertexData->vertexCount, HardwareBuffer::HBU_DYNAMIC, false); - bind->setBinding(POSITION_BINDING, pbuf); - - decl->addElement(NORMAL_BINDING, 0, VET_FLOAT3, VES_NORMAL); - HardwareVertexBufferSharedPtr nbuf = HardwareBufferManager::getSingleton().createVertexBuffer(decl->getVertexSize(NORMAL_BINDING), vertexData->vertexCount, HardwareBuffer::HBU_DYNAMIC, false); - bind->setBinding(NORMAL_BINDING, nbuf); - - decl->addElement(TEXCOORD_BINDING, 0, VET_FLOAT2, VES_TEXTURE_COORDINATES); - HardwareVertexBufferSharedPtr tbuf = HardwareBufferManager::getSingleton().createVertexBuffer(decl->getVertexSize(TEXCOORD_BINDING), vertexData->vertexCount, HardwareBuffer::HBU_DYNAMIC, false); - bind->setBinding(TEXCOORD_BINDING, tbuf); - } - return vertexData; -} - -void Lwo2MeshWriter::copyPoints(int surfaceIndex, unsigned long polygontype, vpoints &sourcepoints, vpoints &destpoints) -{ - for (unsigned int i = 0; i < sourcepoints.size(); i++) - { - lwPoint *point = sourcepoints[i]; - - for (unsigned int j = 0; j < point->polygons.size(); j++) - { - lwPolygon *polygon = point->polygons[j]; - if (polygon->type == polygontype) - if (surfaceIndex == -1 || surfaceIndex == polygon->surfidx) - { - destpoints.push_back(point); - break; - } - } - } -} - -void Lwo2MeshWriter::copyPolygons(int surfaceIndex, unsigned long polygontype, vpolygons &sourcepolygons, vpolygons &destpolygons) -{ - for (unsigned int i = 0; i < sourcepolygons.size(); i++) - { - lwPolygon *polygon = sourcepolygons[i]; - if (polygon->type == polygontype) - if (surfaceIndex == -1 || surfaceIndex == polygon->surfidx) - destpolygons.push_back(polygon); - } -} - -void Lwo2MeshWriter::copyDataToVertexData(vpoints &points, - vpolygons &polygons, - vvmaps &vmaps, - IndexData *indexData, - VertexData *vertexData, - unsigned short vertexDataOffset) -{ - lwVMap *vmap = 0; - unsigned int ni; - - HardwareVertexBufferSharedPtr pbuf = vertexData->vertexBufferBinding->getBuffer(POSITION_BINDING); - HardwareVertexBufferSharedPtr nbuf = vertexData->vertexBufferBinding->getBuffer(NORMAL_BINDING); - HardwareVertexBufferSharedPtr tbuf = vertexData->vertexBufferBinding->getBuffer(TEXCOORD_BINDING); - HardwareIndexBufferSharedPtr ibuf = indexData->indexBuffer; - - float* pPos = static_cast(pbuf->lock(HardwareBuffer::HBL_DISCARD)); - float* pNor = static_cast(nbuf->lock(HardwareBuffer::HBL_DISCARD)); - float* pTex = static_cast(tbuf->lock(HardwareBuffer::HBL_DISCARD)); - unsigned short *pIdx = static_cast(ibuf->lock(HardwareBuffer::HBL_DISCARD)); - - for (unsigned int p = 0; p < polygons.size(); p++) - { - lwPolygon *polygon = polygons[p]; - - if (polygon->vertices.size() != 3) continue; // only copy triangles; - - for (unsigned int v = 0; v < polygon->vertices.size(); v++) - { - lwVertex *vertex = polygon->vertices[v]; - lwPoint *point = vertex->point; - unsigned short i = getPointIndex(point, points); - - pIdx[p*3 + v] = vertexDataOffset + i; - - ni = (vertexDataOffset + i) * 3; - - pPos[ni] = vertex->point->x; - pPos[ni + 1] = vertex->point->y; - pPos[ni + 2] = vertex->point->z; - - pNor[ni] = vertex->normal.x; - pNor[ni + 1] = vertex->normal.y; - pNor[ni + 2] = vertex->normal.z; - - bool found = false; - - ni = (vertexDataOffset + i) * 2; - - for (unsigned int v = 0; v < point->vmaps.size(); v++) - { - for (unsigned int vr = 0; vr < vmaps.size(); vr++) - { - vmap = vmaps[vr]; - if (point->vmaps[v].vmap == vmap) - { - int n = point->vmaps[v].index; - - pTex[ni] = vmap->val[n][0]; - pTex[ni + 1] = 1.0f - vmap->val[n][1]; - found = true; - break; - } - } - if (found) break; - } - } - } - pbuf->unlock(); - nbuf->unlock(); - tbuf->unlock(); - ibuf->unlock(); -} - -void Lwo2MeshWriter::prepLwObject(void) -{ - unsigned int l, p; - - for (l = 0; l < object->layers.size(); l++) - { - lwLayer *layer = object->layers[l]; - -#ifdef _DEBUG - cout << "Triangulating layer " << l << ", Polygons before: " << layer->polygons.size(); -#endif - layer->triangulatePolygons(); -#ifdef _DEBUG - cout << ", Polygons after: " << layer->polygons.size() << endl; -#endif - - // Mirror x-coord for Ogre; - for (p = 0; p < layer->points.size(); p++) - { - layer->points[p]->x *= -1.0f; - layer->points[p]->polygons.clear(); - } - // Unscrew the bounding box - float x = layer->bboxmin.x * -1.0f; - layer->bboxmin.x = layer->bboxmax.x * -1.0f; - layer->bboxmax.x = x; - - for ( p = 0; p < layer->polygons.size(); p++ ) - { - lwPolygon *polygon = layer->polygons[ p ]; - for (unsigned int j = 0; j < polygon->vertices.size(); j++ ) - polygon->vertices[ j ]->point->polygons.push_back(polygon); - } - - for (p = 0; p < layer->polygons.size(); p++) - layer->polygons[p]->flip(); - - layer->calculatePolygonNormals(); - layer->calculateVertexNormals(); - } -} - -inline int Lwo2MeshWriter::getPointIndex(lwPoint *point, vpoints &points) -{ - for (unsigned int i = 0; i < points.size(); ++i) - if (points[i] == point) return i; - - return -1; -} - -inline String Lwo2MeshWriter::makeLayerFileName(char* dest, unsigned int l, char *layername) -{ - char - drive[ _MAX_DRIVE ], - dir[ _MAX_DIR ], - node[ _MAX_FNAME ], - ext[ _MAX_EXT ], - buf[ _MAX_DRIVE + _MAX_DIR + _MAX_FNAME + _MAX_EXT + 5 ]; - - String LayerFileName; - String TempName; - - _splitpath( dest, drive, dir, node, ext ); - - TempName = String( node ); - - if (layername) { - TempName += "."; - TempName += layername; - } else { - TempName += ".layer" + StringConverter::toString(l); - } - - _makepath( buf, drive, dir, TempName.c_str(), ext ); - LayerFileName = String( buf ); - - return LayerFileName; -} - -inline String Lwo2MeshWriter::makeMaterialFileName(char* dest) -{ - char - drive[ _MAX_DRIVE ], - dir[ _MAX_DIR ], - node[ _MAX_FNAME ], - ext[ _MAX_EXT ], - buf[ _MAX_DRIVE + _MAX_DIR + _MAX_FNAME + _MAX_EXT + 5 ]; - - String MaterialFileName; - - _splitpath( dest, drive, dir, node, ext ); - _makepath( buf, drive, dir, node, ".material" ); - - const char *test = MaterialFileName.c_str(); - MaterialFileName = String( buf ); - - return MaterialFileName; -} - -inline void Lwo2MeshWriter::getTextureVMaps(vtextures &textures, vvmaps &svmaps, vvmaps &dvmaps) -{ - for (unsigned int i = 0; i < textures.size(); i++) - { - lwTexture *texture = textures[i]; - - if (texture->type == ID_IMAP && texture->param.imap) - { - char *mapname = texture->param.imap->vmap_name; - if (mapname) - for (unsigned int v = 0; v < svmaps.size(); v++) - { - lwVMap *vmap = svmaps[v]; - if (strcmp(mapname, vmap->name) == 0) dvmaps.push_back(vmap); - } - } - } - return; -} - -bool Lwo2MeshWriter::writeLwo2Mesh(lwObject *nobject, char *ndest) -{ - object = nobject; - dest = ndest; - - if (!object) return false; - if (!object->layers.size()) return false; - - prepLwObject(); - - vpoints points; - vpolygons polygons; - vvmaps vmaps; - - MeshSerializer meshserializer; - - if (flags[ExportMaterials]) - { - doExportMaterials(); - materialSerializer->exportQueued(makeMaterialFileName(dest)); - } - - unsigned int ml = object->layers.size(); - - bool SeparateLayers = flags[UseSeparateLayers] && ml > 1; - - if (!SeparateLayers) ogreMesh = Ogre::MeshManager::getSingleton().create(ndest, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - Ogre::Vector3 boundingBoxMin(FLT_MAX, FLT_MAX, FLT_MAX); - Ogre::Vector3 boundingBoxMax(FLT_MIN, FLT_MIN, FLT_MIN); - - - for( unsigned int ol = 0; ol < ml; ++ol ) - { - if (!object->layers[ol]->polygons.size()) - continue; - - Ogre::Vector3 currentMin(object->layers[ol]->bboxmin.x, - object->layers[ol]->bboxmin.y, - object->layers[ol]->bboxmin.z); - Ogre::Vector3 currentMax(object->layers[ol]->bboxmax.x, - object->layers[ol]->bboxmax.y, - object->layers[ol]->bboxmax.z); - - if (SeparateLayers) - { - ogreMesh = Ogre::MeshManager::getSingleton().create(ndest, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - ogreMesh->_setBounds(Ogre::AxisAlignedBox(currentMin, currentMax)); - ogreMesh->_setBoundingSphereRadius(Ogre::Math::Sqrt(std::max(currentMin.squaredLength(), currentMax.squaredLength()))); - } - else - { - boundingBoxMin.makeFloor(currentMin); - boundingBoxMax.makeCeil(currentMax); - } - - for (unsigned int s = 0; s < object->surfaces.size(); s++) - { - lwSurface *surface = object->surfaces[s]; - - points.clear(); - polygons.clear(); - vmaps.clear(); - - unsigned int l = ol; - - for( unsigned int il = 0; il < ml; ++il ) - { - if (!SeparateLayers) l = il; - - copyPoints(s, ID_FACE, object->layers[l]->points, points); - copyPolygons(s, ID_FACE, object->layers[l]->polygons, polygons); - getTextureVMaps(surface->color.textures, object->layers[l]->vmaps, vmaps); - - if (SeparateLayers) break; - } - - if (!polygons.size()) continue; - - SubMesh *ogreSubMesh = ogreMesh->createSubMesh(); - ogreSubMesh->useSharedVertices = flags[UseSharedVertexData] && points.size() < POINTLIMIT; - - ogreSubMesh->indexData->indexCount = polygons.size() * 3; - ogreSubMesh->indexData->indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer(HardwareIndexBuffer::IT_16BIT, ogreSubMesh->indexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY); - ogreSubMesh->setMaterialName(surface->name); - - - if (ogreSubMesh->useSharedVertices) - { - unsigned short vertexDataOffset = 0; - if (ogreMesh->sharedVertexData) vertexDataOffset = ogreMesh->sharedVertexData->vertexCount; - ogreMesh->sharedVertexData = setupVertexData(points.size(), ogreMesh->sharedVertexData); - copyDataToVertexData(points, polygons, vmaps, ogreSubMesh->indexData, ogreMesh->sharedVertexData, vertexDataOffset); - } - else - { - ogreSubMesh->vertexData = setupVertexData(points.size()); - copyDataToVertexData(points, polygons, vmaps, ogreSubMesh->indexData, ogreSubMesh->vertexData); - } - } - - if (!SeparateLayers) - { - ogreMesh->_setBounds(Ogre::AxisAlignedBox(boundingBoxMin, boundingBoxMax)); - ogreMesh->_setBoundingSphereRadius(Ogre::Math::Sqrt(std::max(boundingBoxMin.squaredLength(), boundingBoxMax.squaredLength()))); - } - - String fname = SeparateLayers ? makeLayerFileName(dest, ol, object->layers[ol]->name) : dest; - - Skeleton *skeleton = 0; - - if (flags[ExportSkeleton]) - if (SeparateLayers) - skeleton = doExportSkeleton(fname, ol); - else - if (!ol) skeleton = doExportSkeleton(fname, -1); - - if (flags[GenerateLOD]) - { - ProgressiveMesh::VertexReductionQuota quota; - - if (flags[UseFixedMethod]) - quota = ProgressiveMesh::VRQ_CONSTANT; - else - quota = ProgressiveMesh::VRQ_PROPORTIONAL; - - ogreMesh->generateLodLevels(distanceList, quota, reduction); - } - - if (flags[GenerateEdgeLists]) - { - ogreMesh->buildEdgeList(); - } - - if (flags[GenerateTangents]) - { - ogreMesh->buildTangentVectors(); - } - - try - { - meshserializer.exportMesh(ogreMesh.get(), fname); - } - catch (...) - { - cout << "Could not export to file: " << fname << endl; - } - - ogreMesh->unload(); - - Ogre::MeshManager::getSingleton().remove(ogreMesh->getHandle()); - if (flags[ExportSkeleton] && skeleton) delete skeleton; - - if (!SeparateLayers) break; - } - - return true; -} diff --git a/Tools/LightwaveConverter/src/main.cpp b/Tools/LightwaveConverter/src/main.cpp deleted file mode 100644 index 766be18d640..00000000000 --- a/Tools/LightwaveConverter/src/main.cpp +++ /dev/null @@ -1,730 +0,0 @@ -#include "lwo.h" -#include "lwReader.h" -#include "lwo2mesh.h" - -#include "Ogre.h" -#include "OgreMeshSerializer.h" -#include "OgreSkeletonSerializer.h" -#include "OgreDefaultHardwareBufferManager.h" - -#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX -#include "asm/io.h" -#else -#include "io.h" -#endif -#include "time.h" - -LogManager* logMgr; -ResourceGroupManager* resourceGroupMgr; -Math* mth; -MaterialManager* matMgr; -SkeletonManager* skelMgr; -MeshManager* meshMgr; -MeshSerializer* meshSerializer; -MaterialSerializer* materialSerializer; -SkeletonSerializer* skeletonSerializer; -DefaultHardwareBufferManager* bufferMgr; - -bool flags[NUMFLAGS] = -{ - false, // lightwave info - false, // dump vmaps - true, // shared geometry - false, // layers - false, // generate LOD - true, // generate edge lists - true, // generate tangents - true, // use fixed method - true, // materials - false, // RenameMaterials - false, // UseInteractiveMethod - true, // UseObjectMethod, default - false, // UsePrefixMethod - true, // skeleton - true, // has normals - true, // new submesh - true // linear copy -}; - -Mesh::LodDistanceList distanceList; -Real reduction = 0.0f; -char *matPrefix = 0; - -ostream& nl(ostream& os) -{ - return os << '\n'; -} - -int nobjects = 0, nlayers = 0, nsurfs = 0, nenvs = 0, nclips = 0, npoints = 0, npolygons = 0; - -/* -====================================================================== -print_vmaps1() - - Print vmap values for a layer, looping through the vmaps. - - for each vmap - print vmap statistics - for each mapped point - print point index and position - if vmad, print polygon index and vertex number - print vmap values -====================================================================== */ - -static void print_vmaps1( FILE *fp, lwLayer *layer ) -{ - lwPoint *pt; - lwVMap *vmap; - char *tag; - unsigned int i, j, k, n; - - fprintf( fp, "\n\nVertex Maps (%d)\n\n", layer->vmaps.size() ); - - for ( i = 0; i < layer->vmaps.size(); i++ ) - { - vmap = layer->vmaps[i]; - - tag = ( char * ) &vmap->type; - - fprintf( fp, "%c%c%c%c \"%s\" dim %d nverts %d vmad (%s)\n", - tag[ 3 ], tag[ 2 ], tag[ 1 ], tag[ 0 ], - vmap->name, - vmap->dim, - vmap->nverts, - vmap->perpoly ? "yes" : "no" ); - - printf( "%c%c%c%c \"%s\" dim %d nverts %d vmad (%s)\n", - tag[ 3 ], tag[ 2 ], tag[ 1 ], tag[ 0 ], - vmap->name, - vmap->dim, - vmap->nverts, - vmap->perpoly ? "yes" : "no" ); - - for ( j = 0; j < vmap->nverts; j++ ) { - /* point index */ - fprintf( fp, " point %d ", vmap->vindex[ j ] ); - - /* if vmad */ - if ( vmap->perpoly ) { - lwPolygon *pol; - - /* polygon index */ - k = vmap->pindex[ j ]; - fprintf( fp, " poly %d ", k ); - - /* vertex index */ - pol = layer->polygons[ k ]; - for ( n = 0; n < pol->vertices.size(); n++ ) - if ( pol->vertices[ n ]->index == vmap->vindex[ j ] ) break; - fprintf( fp, " vert %d ", n ); - } - - /* point coords */ - pt = layer->points[ vmap->vindex[ j ]]; - fprintf( fp, " (%g, %g, %g) ", pt->x, pt->y, pt->z ); - - /* vmap values */ - for ( k = 0; k < vmap->dim; k++ ) - fprintf( fp, " %g", vmap->val[ j ][ k ] ); - - /* done with this point */ - fprintf( fp, "\n" ); - } - /* done with this vmap */ - fprintf( fp, "\n" ); - } - /* done with this layer */ - fprintf( fp, "\n\n" ); -} - - -/* -====================================================================== -print_vmaps2() - - Print vmap values for a layer, looping through the points. - - for each point - print point index, position, number of vmaps, polygon indexes - for each vmap on the point - print vmap name, type and values -====================================================================== */ - -static void print_vmaps2( FILE *fp, lwLayer *layer ) -{ - lwPoint *pt; - lwVMap *vmap; - char *tag; - unsigned int i, j, k, n; - - fprintf( fp, "\n\nPoints (%d)\n\n", layer->points.size() ); - - for ( i = 0; i < layer->points.size(); i++ ) { - pt = layer->points[ i ]; - - /* point index and position */ - fprintf( fp, "%d (%g, %g, %g)", i, pt->x, pt->y, pt->z ); - - /* number of vmaps and polygons */ - fprintf( fp, " nvmaps %d npolygons %d", pt->vmaps.size(), pt->polygons.size() ); - - /* polygon indexes */ - fprintf( fp, " [" ); - for ( j = 0; j < pt->polygons.size(); j++ ) - fprintf( fp, " %d", pt->polygons[ j ] ); - fprintf( fp, "]\n" ); - - /* vmaps for this point */ - for ( j = 0; j < pt->vmaps.size(); j++ ) { - vmap = pt->vmaps[ j ].vmap; - n = pt->vmaps[ j ].index; - - tag = ( char * ) &vmap->type; - - fprintf( fp, " %c%c%c%c \"%s\" vmad (%s)", - tag[ 3 ], tag[ 2 ], tag[ 1 ], tag[ 0 ], vmap->name, - vmap->perpoly ? "yes" : "no" ); - - /* vmap values */ - for ( k = 0; k < vmap->dim; k++ ) - fprintf( fp, " %g", vmap->val[ n ][ k ] ); - - /* done with this vmap */ - fprintf( fp, "\n" ); - } - /* done with this point */ - fprintf( fp, "\n" ); - } - /* done with this layer */ - fprintf( fp, "\n\n" ); -} - - -/* -====================================================================== -print_vmaps3() - - Print vmap values for a layer, looping through the polygons. - - for each polygon - print polygon index, number of points - for each vertex - print point index, position, number of vmaps - for each vmap on the point - print vmap name, type and values -====================================================================== */ - -static void print_vmaps3( FILE *fp, lwLayer *layer ) -{ - lwPoint *pt; - lwPolygon *pol; - lwVMap *vmap; - char *tag; - unsigned int i, j, k, m, n; - - fprintf( fp, "\n\nPolygons (%d)\n\n", layer->polygons.size() ); - - for ( i = 0; i < layer->polygons.size(); i++ ) { - pol = layer->polygons[ i ]; - - /* polygon index, type, number of vertices */ - tag = ( char * ) &pol->type; - fprintf( fp, "%d %c%c%c%c nverts %d\n", i, - tag[ 3 ], tag[ 2 ], tag[ 1 ], tag[ 0 ], pol->vertices.size() ); - - for ( k = 0; k < pol->vertices.size(); k++ ) { - /* point index, position, number of vmads and vmaps */ - n = pol->vertices[ k ]->index; - pt = layer->points[ n ]; - fprintf( fp, "%d (%g, %g, %g) nvmads %d nvmaps %d\n", n, - pt->x, pt->y, pt->z, - pol->vertices[ k ]->vmaps.size(), pt->vmaps.size() - pol->vertices[ k ]->vmaps.size() ); - - /* vmads for this vertex */ - for ( j = 0; j < pol->vertices[ k ]->vmaps.size(); j++ ) { - vmap = pol->vertices[ k ]->vmaps[ j ].vmap; - n = pol->vertices[ k ]->vmaps[ j ].index; - - tag = ( char * ) &vmap->type; - fprintf( fp, " %c%c%c%c vmad \"%s\"", - tag[ 3 ], tag[ 2 ], tag[ 1 ], tag[ 0 ], vmap->name ); - - /* vmap values */ - for ( m = 0; m < vmap->dim; m++ ) - fprintf( fp, " %g", vmap->val[ m ][ n ] ); - - /* done with this vmad */ - fprintf( fp, "\n" ); - } - - /* vmaps for this vertex */ - for ( j = 0; j < pt->vmaps.size(); j++ ) { - vmap = pt->vmaps[ j ].vmap; - if ( vmap->perpoly ) continue; - n = pt->vmaps[ j ].index; - - tag = ( char * ) &vmap->type; - fprintf( fp, " %c%c%c%c vmap \"%s\"", - tag[ 3 ], tag[ 2 ], tag[ 1 ], tag[ 0 ], vmap->name ); - - /* vmap values */ - for ( m = 0; m < vmap->dim; m++ ) - fprintf( fp, " %g", vmap->val[ m ][ n ] ); - - /* done with this vmap */ - fprintf( fp, "\n" ); - } - - /* done with this vertex */ - if ( pt->vmaps.size() ) - fprintf( fp, "\n" ); - } - /* done with this polygon */ - fprintf( fp, "\n" ); - } - /* done with this layer */ - fprintf( fp, "\n\n" ); -} - - -/* -====================================================================== -print_vmaps() - - Print vmap values for a layer. - - Calls print_vmaps1(), print_vmaps2() and print_vmaps3(). -====================================================================== */ - -void print_vmaps( lwObject *obj ) -{ - FILE *fp[ 3 ]; - char buf[ 64 ]; - lwLayer *layer; - unsigned int i, j; - - for ( i = 0; i < 3; i++ ) { - sprintf( buf, "vmapout%d.txt", i + 1 ); - fp[ i ] = fopen( buf, "w" ); - if ( !fp[ i ] ) { - for ( j = i - 1; j >= 0; j-- ) - fclose( fp[ j ] ); - return; - } - } - - for ( i = 0; i < obj->layers.size(); i++ ) - { - layer = obj->layers[i]; - - fprintf( fp[ 0 ], "------------------------\nLayer %d\n", i ); - print_vmaps1( fp[ 0 ], layer ); - - fprintf( fp[ 1 ], "------------------------\nLayer %d\n", i ); - print_vmaps2( fp[ 1 ], layer ); - - fprintf( fp[ 2 ], "------------------------\nLayer %d\n", i ); - print_vmaps3( fp[ 2 ], layer ); - } - - for ( i = 0; i < 3; i++ ) - fclose( fp[ i ] ); -} - -int make_filename( char *spec, char *name, char *fullname ) -{ - char - drive[ _MAX_DRIVE ], - dir[ _MAX_DIR ], - node[ _MAX_FNAME ], - ext[ _MAX_EXT ]; - - _splitpath( spec, drive, dir, node, ext ); - _makepath( fullname, drive, dir, name, NULL ); - return 1; -} - -int make_destname( char *spec, char *name, char *fullname ) -{ - char - drive[ _MAX_DRIVE ], - dir[ _MAX_DIR ], - node[ _MAX_FNAME ], - ext[ _MAX_EXT ], - dnode[ _MAX_FNAME ]; - - _splitpath( name, drive, dir, dnode, ext ); - _splitpath( spec, drive, dir, node, ext ); - _makepath( fullname, drive, dir, dnode, ".mesh" ); - return 1; -} - -int make_filespec( char *spec, char *subdir, char *fullname ) -{ - char - name[ _MAX_FNAME ], - drive[ _MAX_DRIVE ], - dir[ _MAX_DIR ], - node[ _MAX_FNAME ], - ext[ _MAX_EXT ]; - - _splitpath( spec, drive, dir, node, ext ); - _makepath( name, drive, dir, subdir, NULL ); - _makepath( fullname, NULL, name, node, ext ); - return 1; -} - -void help( char *filename ) -{ - cout << "lwo2mesh v0.89b (2005.02.09) by Dennis Verbeek." << nl - << "Converts a Lightwave object to an Ogre mesh." << nl - << "Please send any feedback to: dennis.verbeek@chello.nl" << nl << nl -#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX - << "Linux Port (2004.10.16) by Magnus Møller Petersen." << nl - << "Please send feedback concerning Linux to: magnus@moaner.dk" << nl << nl -#endif - << "Usage: " << filename << " [options] source [dest]" << nl - << "options:" << nl - << "-g do not use shared geometry" << nl - << "-d generate level of detail information" << nl - << " method (f)ixed or (p)roportional" << nl - << " reduction (fixed) or reductionfactor (proportional)" << nl - << " number of LOD levels" << nl - << " distances" << nl - << " example: -dp 0.5 4 1000.0 2000.0 4000.0 8000.0" << nl - << "-l save layers separately" << nl - << "-m do not export materials" << nl - << "-r rename materials" << nl - << " method (i)nteractive, (o)bjectname or (p)refix" << nl - << " example: -rp prefix_" << nl - << "-s do not export skeleton" << nl - << "-i info on .lwo only, no conversion to mesh" << nl - << " -v dump vertex maps" << endl; - exit(0); -} - -void info(lwObject *object, char *filename) -{ - unsigned int points = 0; - unsigned int polygons = 0; - - nlayers += object->layers.size(); - nsurfs += object->surfaces.size(); - nclips += object->clips.size(); - nenvs += object->envelopes.size(); - - cout << "File: " << filename << nl - << setw(8) << object->layers.size() << " layers" << nl - << setw(8) << object->surfaces.size() << " surfaces" << nl - << setw(8) << object->clips.size() << " clips" << nl - << setw(8) << object->envelopes.size() << " envelopes" << endl; - - if (object->layers.size() > 1) - { - for( unsigned int i = 0; i < object->layers.size(); i++ ) - { - points += object->layers[i]->points.size(); - cout << setw(8) << object->layers[i]->points.size() << " points (layer " << i; - - if (object->layers[i]->name) - cout << ", " << object->layers[i]->name << ")" << endl; - else - cout << ")" << endl; - - polygons += object->layers[i]->polygons.size(); - cout << setw(8) << object->layers[i]->polygons.size() << " polygons (layer " << i; - - if (object->layers[i]->name) - cout << ", " << object->layers[i]->name << ")" << endl; - else - cout << ")" << endl; - } - } - else - { - points += object->layers[0]->points.size(); - polygons += object->layers[0]->polygons.size(); - } - - cout << setw(8) << points << " points (total)" << nl - << setw(8) << polygons << " polygons (total)" << nl << endl; - - nobjects++; - npoints += points; - npolygons += polygons; - - if (flags[PrintVMaps]) - print_vmaps( object ); -} - -#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 -int readFiles( char *source, char *dest) -{ - long h, err; - struct _finddata_t data; - char *filename, *prevname, *destname; - unsigned int failID; - int failpos; - lwReader reader; - Lwo2MeshWriter lwo2mesh; - - filename = (char *)malloc(3 * 512); - if ( !filename ) return 0; - prevname = filename + 512; - destname = filename + 1024; - - err = h = _findfirst( source, &data ); - if ( err == -1 ) - { - printf( "No files found: '%s'\n", source ); - return 0; - } - - while ( err != -1 ) - { - if (( data.attrib & _A_SUBDIR ) && data.name[ 0 ] != '.' ) - { - make_filespec( source, data.name, filename ); - readFiles( filename, dest ); - } - if ( !( data.attrib & _A_SUBDIR )) - { - make_filename( source, data.name, filename ); - - if ( !strcmp( filename, prevname )) break; - strcpy( prevname, filename ); - failID = failpos = 0; - - lwObject *object = reader.readObjectFromFile( filename ); - if ( object ) - { - if (flags[InfoOnly]) - info(object, filename); - else - { - make_destname( dest, data.name, destname ); - lwo2mesh.writeLwo2Mesh(object, destname); - } - delete object; - } - } - err = _findnext( h, &data ); - } - - _findclose( h ); - free (filename); - return 1; -} -#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX -int readFiles( char *source, char *dest ) { - return 1; -} -#else -#define readFiles( a, b ) -#endif - -int main( int argc, char *argv[] ) -{ - int i = 1; - unsigned int ndistances = 0; - Real distance = 0; - char *source = 0; - char *dest = 0; - - if ( argc < 2 ) help(argv[0]); - - while (i < argc) - { - if (argv[i][0] == '-' || argv[i][0] == '/') - { - switch (argv[i++][1]) - { - case 'd': - case 'D': - i--; - flags[GenerateLOD] = true; - switch (argv[i++][2]) - { - case 'f': - case 'F': - flags[UseFixedMethod] = true; - break; - case 'p': - case 'P': - flags[UseFixedMethod] = false; - break; - default: - help(argv[0]); - } - try - { - reduction = atof(argv[i++]); - ndistances = atoi(argv[i++]); - while (ndistances > 0) - { - if (i < argc && argv[i][0] != '-' && argv[i][0] != '/') - distanceList.push_back(atof(argv[i++])); - else - ndistances = 0; - ndistances--; - } - } - catch (Exception *e) - { - ndistances = 0; - distanceList.clear(); - flags[GenerateLOD] = false; - } - break; - case 'g': - case 'G': - flags[UseSharedVertexData] = false; - break; - case 'i': - case 'I': - flags[InfoOnly] = true; - break; - case 'l': - case 'L': - flags[UseSeparateLayers] = true; - break; - case 'm': - case 'M': - flags[ExportMaterials] = false; - break; - case 'r': - case 'R': - flags[RenameMaterials] = true; - if (strlen(argv[i-1]) > 2) { - i--; - switch (argv[i++][2]) - { - case 'i': - case 'I': - flags[UseInteractiveMethod] = true; - break; - case 'o': - case 'O': - flags[UseObjectMethod] = true; // default - break; - case 'p': - case 'P': - flags[UsePrefixMethod] = true; - if (argv[i][0] != '-' && argv[i][0] != '/') - matPrefix = argv[i++]; - else - help(argv[0]); - break; - default: - help(argv[0]); - } - } - break; - case 's': - case 'S': - flags[ExportSkeleton] = false; - break; - case 'v': - case 'V': - flags[PrintVMaps] = true; - break; - default: - help(argv[0]); - } - } - else - { - if (!source) source = argv[i]; - else - if (!dest) dest = argv[i]; - i++; - } - } - - if ( !source ) help(argv[0]); - - if (!dest) dest = "\0"; - - float t1, t2; - - t1 = ( float ) clock() / CLOCKS_PER_SEC; - - if (!flags[InfoOnly]) - { - logMgr = new LogManager(); - logMgr->createLog("lwo2mesh.log", true); - resourceGroupMgr = new ResourceGroupManager(); - mth = new Math(); - matMgr = new MaterialManager(); - matMgr->initialise(); - meshMgr = new MeshManager(); - skelMgr = new SkeletonManager(); - meshSerializer = new MeshSerializer(); - materialSerializer = new MaterialSerializer(); - skeletonSerializer = new SkeletonSerializer(); - bufferMgr = new DefaultHardwareBufferManager(); // needed because we don't have a rendersystem - } - - if ( strchr(source, '*') ) - // On Linux this will only be called if you pass the source argument in - // quotation marks (e.g. as LightwaveConverter "abc..*" ). Otherwise the - // shell will expand the arguments. At least, this is how it works with - // bash. - readFiles( source, dest ); - else - { - lwReader reader; - lwObject *object = reader.readObjectFromFile(source); - if ( object ) - { - if (flags[InfoOnly]) - info(object, source); - else - { - char *destname = (char *)malloc(512); - if ( !destname ) return 1; - - if (strlen(dest)) - make_destname(dest, dest, destname); - else - make_destname(dest, source, destname); - - Lwo2MeshWriter lwo2mesh; - lwo2mesh.writeLwo2Mesh(object, destname); - free(destname); - } - delete object; - } - } - - t2 = ( float ) clock() / CLOCKS_PER_SEC - t1; - - if (flags[InfoOnly]) - { - cout << "Total:" << nl - << setw(8) << nobjects << " objects" << nl - << setw(8) << nlayers << " layers" << nl - << setw(8) << nsurfs << " surfaces" << nl - << setw(8) << nclips << " clips" << nl - << setw(8) << nenvs << " envelopes" << nl - << setw(8) << npoints << " points" << nl - << setw(8) << npolygons << " polygons" << nl - << setw(8) << t2 << " seconds processing time." << endl; - } - else - { - delete bufferMgr; - delete skeletonSerializer; - delete materialSerializer; - delete meshSerializer; - delete meshMgr; - delete skelMgr; - delete matMgr; - delete mth; - delete resourceGroupMgr; - delete logMgr; - } - - return 0; - -} diff --git a/Tools/MayaExport/Readme.md b/Tools/MayaExport/Readme.md deleted file mode 100644 index 1fab5dd9360..00000000000 --- a/Tools/MayaExport/Readme.md +++ /dev/null @@ -1,108 +0,0 @@ - -# Ogre exporter for Maya -``` -/******************************************************************************* - * Ogre exporter for Maya * - * * - * Author: Francesco Giordana ( fra.giordana@tiscali.it ) * - * * - * Sponsored by: Anygma N.V. ( http://www.nazooka.com ) * - * * - ******************************************************************************* -``` - -## Installation -1) Copy "ogreExporter.mll" to your Maya plug-ins directory (e.g.: `C:\Program Files\Alias\Maya7.0\bin\plug-ins`) - -2) Copy Ogre DLLs (you can find them in the "dlls" directory of this zip) to your Maya bin directory - (e.g.: `C:\Program Files\Alias\Maya7.0\bin`) - -3) Copy "ogreExporter.mel" (from the "mel" directory of this zip) to your Maya scripts directory - (e.g.: `C:\Documents and Settings\user\My Documents\maya\6.5\scripts`) - -4) If you already have a userSetup.mel in your scripts folder, then append the line - source ogreExporter.mel; - to the existing "userSetup.mel". - If you don't have a "userSetup.mel" file in your scripts directory, then copy there the one you find in - the "scripts" directory of this zip. - -5) Launch `vcredist_x86.exe` to install the latest Visual Studio DLLs - -## Usage - -1) Via GUI from the menu Ogre->Export - -2) Via script: -``` -ogreExport generalOptions - - ["-mesh" meshFilename meshOptions] - export mesh to .mesh binary file - - ["-mat" matFilename matOptions] - export materials to .material script file - - ["-skel" skelFilename] - export skeleton to .skeleton binary file - - ["-skeletonAnims" skelAnimsOptions ["-skeletonClip" clipName clipOptions] ["-clip" ...] [...] ] - export skeleton animations to the .skeleton file - [requires -skel] - - ["-vertexAnims" vertexAnimOptions ["-vertexClip" clipName clipOptions] ["-clip" ...] [...] ] - export vertex animations as morph animations to the .mesh file - [requires -mesh] - - ["-blendShapes"] bsOptions - export blend shapes as mesh poses to the .mesh file - [requires -mesh] - - ["-BSAnims" ["-BSClip" clipName clipOptions] ["-clip" ...] [...] ] - export blend shape animations as pose animations to the .mesh file - [requires -mesh] - - ["-particles" particlesFilename] - export particles to .particle file - -generalOptions: - "-sel" | "-all" export whole scene or only selected objects - "-world" | "-obj" export in world or object coordinates - "-lu " "pref | mm | cm | m | in | ft | yd" select length unit for export - ("-lu pref" means to get unit from scene - preferences) - "-scale" s scale the whole mesh by s - -meshOptions: - ["-shared"] export using shared geometry - ["-v"] export vertex bone assignements - ["-n"] export vertex normals - ["-c"] export vertex colours - ["-t"] export texture coordinates - ["-edges"] generate mesh edge list - ["-tangents" "TEXCOORD | TANGENT"] generate tangents - ["-tangentsplitmirrored"] split tangents mirrored - ["-tangentsplitrotated"] split tangents rotated - ["-tangentuseparity"] use parity for tangents - -matOptions: - ["-matPrefix" prefix] add prefix to all exported materials names [optional] - ["-copyTex" outDir] copy textures used in the exported materials to outDir [optional] - ["-lightOff"] export materials with lighting off [optional] - -skelAnimsOptions: - "-skelBB" include skeleton animations in bounding box calculation - "-np" ( "curFrame" | "bindPose" | "frame" n ) specify neutral pose, can be current frame or bind pose or specified frame - -bsOptions: - ["-bsBB"] include blend shapes in bounding box calculation - -vertexAnimOptions: - ["-vertBB"] include vertex animations in bounding box calculation - -clipOptions: - "startEnd" s e ("frames" | "seconds") | "timeSlider" specify clip range with start/end time or use time slider range -``` - -# Troubleshooting -- Some users reported that they need to add an additional "-v" parameter after "-q" into the file "ogreExporter.mel", - in the lines 1924 to 1926 (details: [Maya Ogre Exporter Save Settings problem - Download the fix](http://www.ogre3d.org/forums/viewtopic.php?f=8&t=46563)) diff --git a/Tools/MayaExport/include/_singleton.h b/Tools/MayaExport/include/_singleton.h deleted file mode 100644 index e97843d439e..00000000000 --- a/Tools/MayaExport/include/_singleton.h +++ /dev/null @@ -1,60 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// _singleton.h -// Author : Francesco Giordana -// Sponsored by : Anygma N.V. (http://www.nazooka.com) -// Start Date : January 13, 2005 -// Copyright : (C) 2006 by Francesco Giordana -// Email : fra.giordana@tiscali.it -//////////////////////////////////////////////////////////////////////////////// - -//////////////////////////////////////////////////////////////////////////////// -// Modified from the original version by -// Author : Steve Streeting -// Email : Doug@IceTecStudios.com -//////////////////////////////////////////////////////////////////////////////// - -/********************************************************************************* -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Lesser General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -**********************************************************************************/ - -#ifndef __SINGLETON_H__ -#define __SINGLETON_H__ - -#include - -// Copied frome Ogre::Singleton, created by Steve Streeting for Ogre - -namespace OgreMayaExporter -{ - /** Template class for creating single-instance global classes. - */ - template class Singleton - { - protected: - static T* msSingleton; - - public: - Singleton(){ - assert( !msSingleton ); - msSingleton = static_cast< T* >( this ); - } - ~Singleton(){ - assert( msSingleton ); - msSingleton = 0; - } - static T& getSingleton(){ - assert( msSingleton ); - return ( *msSingleton ); - } - static T* getSingletonPtr(){ - return msSingleton; - } - }; - -}; // end namespace -#endif \ No newline at end of file diff --git a/Tools/MayaExport/include/animation.h b/Tools/MayaExport/include/animation.h deleted file mode 100644 index fd83785abdb..00000000000 --- a/Tools/MayaExport/include/animation.h +++ /dev/null @@ -1,152 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// animation.h -// Author : Francesco Giordana -// Sponsored by : Anygma N.V. (http://www.nazooka.com) -// Start Date : January 13, 2005 -// Copyright : (C) 2006 by Francesco Giordana -// Email : fra.giordana@tiscali.it -//////////////////////////////////////////////////////////////////////////////// - -/********************************************************************************* -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Lesser General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -**********************************************************************************/ - -#ifndef ANIMATION_H -#define ANIMATION_H - -#include "mayaExportLayer.h" - -namespace OgreMayaExporter -{ - // Track type - typedef enum { TT_SKELETON, TT_MORPH, TT_POSE } trackType; - - // Target - typedef enum { T_MESH, T_SUBMESH } target; - - // Vertex position - typedef struct vertexPositiontag - { - float x,y,z; - } vertexPosition; - - // Vertex pose reference - typedef struct vertexPoseReftag - { - int poseIndex; - float poseWeight; - } vertexPoseRef; - - // Vertex animation keyframe - typedef struct vertexKeyframetag - { - float time; - std::vector positions; - std::vector poserefs; - } vertexKeyframe; - - // Skeleton animation keyframe - typedef struct skeletonKeyframeTag - { - float time; //time of keyframe - double tx,ty,tz; //translation - double angle,axis_x,axis_y,axis_z; //rotation - float sx,sy,sz; //scale - } skeletonKeyframe; - - // Blend shape data - typedef struct vertexOffestTag - { - long index; - float x,y,z; - } vertexOffset; - - typedef struct poseTag - { - target poseTarget; - long index; - int blendShapeIndex; - MString name; - std::vector offsets; - } pose; - - // A class for storing an animation track - // each track can be either skeleton, morph or pose animation - class Track - { - public: - //constructor - Track() { - clear(); - }; - //destructor - ~Track() { - clear(); - } - //clear track data - void clear() { - m_type = TT_SKELETON; - m_target = T_MESH; - m_index = 0; - m_bone = ""; - m_vertexKeyframes.clear(); - m_skeletonKeyframes.clear(); - } - //add vertex animation keyframe - void addVertexKeyframe(vertexKeyframe& k) { - m_vertexKeyframes.push_back(k); - } - //add skeleton animation keyframe - void addSkeletonKeyframe(skeletonKeyframe& k) { - m_skeletonKeyframes.push_back(k); - } - - //public members - trackType m_type; - target m_target; - int m_index; - MString m_bone; - std::vector m_vertexKeyframes; - std::vector m_skeletonKeyframes; - }; - - - // A class for storing animation information - // an animation is a collection of different tracks - class Animation - { - public: - //constructor - Animation() { - clear(); - } - //destructor - ~Animation() { - clear(); - }; - //clear animation data - void clear() { - m_name = ""; - m_length = 0; - m_tracks.clear(); - }; - //add track - void addTrack(Track& t) { - m_tracks.push_back(t); - } - - //public memebers - MString m_name; - float m_length; - std::vector m_tracks; - }; - -} // end namespace - - -#endif // ANIMATION_H \ No newline at end of file diff --git a/Tools/MayaExport/include/blendshape.h b/Tools/MayaExport/include/blendshape.h deleted file mode 100644 index 7a0ff08147a..00000000000 --- a/Tools/MayaExport/include/blendshape.h +++ /dev/null @@ -1,102 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// blendshape.h -// Author : Francesco Giordana -// Sponsored by : Anygma N.V. (http://www.nazooka.com) -// Start Date : January 13, 2005 -// Copyright : (C) 2006 by Francesco Giordana -// Email : fra.giordana@tiscali.it -//////////////////////////////////////////////////////////////////////////////// - -/********************************************************************************* -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Lesser General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -**********************************************************************************/ - -#ifndef _BLENDSHAPE_H -#define _BLENDSHAPE_H - -#include "mayaExportLayer.h" -#include "paramList.h" -#include "animation.h" -#include "vertex.h" - -namespace OgreMayaExporter -{ - typedef struct - { - MPlugArray srcConnections; - MPlugArray dstConnections; - } weightConnections; - - typedef struct - { - int targetIndex; - std::vector poses; - } poseGroup; - - // Blend Shape Class - class BlendShape - { - public: - // Constructor - BlendShape(); - // Destructor - ~BlendShape(); - // Clear blend shape data - void clear(); - // Load blend shape deformer from Maya - MStatus load(MObject &blendShapeObj); - // Load blend shape poses for shared geometry - MStatus loadPosesShared(MDagPath& meshDag,ParamList ¶ms,std::vector &vertices, - long numVertices,long offset=0); - // Load blend shape poses for a submesh - MStatus loadPosesSubmesh(MDagPath& meshDag,ParamList ¶ms,std::vector &vertices, - std::vector& indices,long targetIndex=0); - //load a blend shape animation track - Track loadTrack(float start,float stop,float rate,ParamList& params,int targetIndex,int startPoseId); - // Get blend shape deformer name - MString getName(); - // Get blend shape poses - stdext::hash_map& getPoseGroups(); - // Set maya blend shape deformer envelope - void setEnvelope(float envelope); - // Restore maya blend shape deformer original envelope - void restoreEnvelope(); - // Break connections to this blendshape - void breakConnections(); - // Restore connections on this blendshape - void restoreConnections(); - // Public members - MFnBlendShapeDeformer* m_pBlendShapeFn; - - protected: - // Internal methods - //load a blend shape pose for shared geometry - MStatus loadPoseShared(MDagPath& meshDag,ParamList& params,std::vector& vertices, - long numVertices,long offset,MString poseName, int blendShapeIndex); - //load a blend shape pose for a submesh - MStatus loadPoseSubmesh(MDagPath& meshDag,ParamList& params,std::vector& vertices, - std::vector& indices,MString poseName,int targetIndex, int blendShapeIndex); - //load a blend shape animation keyframe - vertexKeyframe loadKeyframe(float time,ParamList& params,int targetIndex,int startPoseId); - - // Protected members - //original values to restore after export - float m_origEnvelope; - std::vector m_origWeights; - //blend shape poses - stdext::hash_map m_poseGroups; - //blend shape target (shared geometry or submesh) - target m_target; - //blend shape weights connections - std::vector m_weightConnections; - }; - - -} // end namespace - -#endif \ No newline at end of file diff --git a/Tools/MayaExport/include/material.h b/Tools/MayaExport/include/material.h deleted file mode 100644 index b7d35b85d23..00000000000 --- a/Tools/MayaExport/include/material.h +++ /dev/null @@ -1,100 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// material.h -// Author : Francesco Giordana -// Sponsored by : Anygma N.V. (http://www.nazooka.com) -// Start Date : January 13, 2005 -// Copyright : (C) 2006 by Francesco Giordana -// Email : fra.giordana@tiscali.it -//////////////////////////////////////////////////////////////////////////////// - -/********************************************************************************* -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Lesser General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -**********************************************************************************/ - -#ifndef _MATERIAL_H -#define _MATERIAL_H - -#include "mayaExportLayer.h" -#include "paramList.h" - -namespace OgreMayaExporter -{ - - typedef enum {MT_SURFACE_SHADER,MT_LAMBERT,MT_PHONG,MT_BLINN,MT_CGFX} MaterialType; - - typedef enum {TOT_REPLACE,TOT_MODULATE,TOT_ADD,TOT_ALPHABLEND} TexOpType; - - typedef enum {TAM_CLAMP,TAM_BORDER,TAM_WRAP,TAM_MIRROR} TexAddressMode; - - class Texture - { - public: - //constructor - Texture() { - scale_u = scale_v = 1; - scroll_u = scroll_v = 0; - rot = 0; - am_u = am_v = TAM_CLAMP; - } - //destructor - ~Texture(){}; - - //public members - MString filename; - MString absFilename; - TexOpType opType; - MString uvsetName; - int uvsetIndex; - TexAddressMode am_u,am_v; - double scale_u,scale_v; - double scroll_u,scroll_v; - double rot; - }; - - - /***** Class Material *****/ - class Material - { - public: - //constructor - Material(); - //destructor - ~Material(); - //get material name - MString& name(); - //clear material data - void clear(); - //load material data - MStatus load(MFnDependencyNode* pShader,MStringArray& uvsets,ParamList& params); - //load a specific material type - MStatus loadSurfaceShader(MFnDependencyNode* pShader); - MStatus loadLambert(MFnDependencyNode* pShader); - MStatus loadPhong(MFnDependencyNode* pShader); - MStatus loadBlinn(MFnDependencyNode* pShader); - MStatus loadCgFxShader(MFnDependencyNode* pShader); - //write material data to Ogre material script - MStatus writeOgreScript(ParamList ¶ms); - //copy textures to path specified by params - MStatus copyTextures(ParamList ¶ms); - public: - //load texture data - MStatus loadTexture(MFnDependencyNode* pTexNode,TexOpType& opType,MStringArray& uvsets,ParamList& params); - - MString m_name; - MaterialType m_type; - MColor m_ambient, m_diffuse, m_specular, m_emissive; - bool m_lightingOff; - bool m_isTransparent; - bool m_isTextured; - bool m_isMultiTextured; - std::vector m_textures; - }; - -}; //end of namespace - -#endif \ No newline at end of file diff --git a/Tools/MayaExport/include/materialSet.h b/Tools/MayaExport/include/materialSet.h deleted file mode 100644 index d3ac66b9742..00000000000 --- a/Tools/MayaExport/include/materialSet.h +++ /dev/null @@ -1,113 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// materialSet.h -// Author : Francesco Giordana -// Sponsored by : Anygma N.V. (http://www.nazooka.com) -// Start Date : January 13, 2005 -// Copyright : (C) 2006 by Francesco Giordana -// Email : fra.giordana@tiscali.it -//////////////////////////////////////////////////////////////////////////////// - -/********************************************************************************* -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Lesser General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -**********************************************************************************/ - -#ifndef _MATERIALSET_H -#define _MATERIALSET_H - -#include "_singleton.h" -#include "material.h" -#include "mayaExportLayer.h" - -namespace OgreMayaExporter -{ - class MaterialSet : public Singleton - { - public: - //constructor - MaterialSet(){ - //create a default material - m_pDefaultMat = new Material(); - m_pDefaultMat->m_type = MT_LAMBERT; - m_pDefaultMat->m_name = "defaultLambert"; - m_pDefaultMat->m_ambient = MColor(0,0,0,1); - m_pDefaultMat->m_emissive = MColor(0,0,0,1); - m_pDefaultMat->m_diffuse = MColor(0.5,0.5,0.5,1); - }; - //destructor - ~MaterialSet(){ - clear(); - if (m_pDefaultMat) - delete m_pDefaultMat; - } - //clear - void clear(){ - for (int i=0; iname() == pMat->name()) - { - found = true; - delete pMat; - } - } - if (!found) - m_materials.push_back(pMat); - } - //get material - Material* getMaterial(const MString& name){ - for (int i=0; iname() == name) - return m_materials[i]; - } - return NULL; - }; - //get default material - Material* getDefaultMaterial() - { - return m_pDefaultMat; - }; - //get material set - static MaterialSet& getSingleton(){ - assert(msSingleton); - return (*msSingleton); - }; - static MaterialSet* getSingletonPtr(){ - return msSingleton; - }; - //write materials to Ogre XML - MStatus writeOgreScript(ParamList ¶ms){ - MStatus stat; - for (int i=0; iwriteOgreScript(params); - if (MS::kSuccess != stat) - { - MString msg = "Error writing material "; - msg += m_materials[i]->name(); - msg += ", aborting operation"; - MGlobal::displayInfo(msg); - } - } - return MS::kSuccess; - }; - - protected: - std::vector m_materials; - Material* m_pDefaultMat; - }; - -}; //end namespace - -#endif \ No newline at end of file diff --git a/Tools/MayaExport/include/mayaExportLayer.h b/Tools/MayaExport/include/mayaExportLayer.h deleted file mode 100644 index 21a97d75991..00000000000 --- a/Tools/MayaExport/include/mayaExportLayer.h +++ /dev/null @@ -1,90 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// mayaExportLayer.h -// Author : Francesco Giordana -// Sponsored by : Anygma N.V. (http://www.nazooka.com) -// Start Date : January 13, 2005 -// Copyright : (C) 2006 by Francesco Giordana -// Email : fra.giordana@tiscali.it -//////////////////////////////////////////////////////////////////////////////// - -/********************************************************************************* -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Lesser General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -**********************************************************************************/ - -#ifndef _MAYAEXPORTLAYER_H -#define _MAYAEXPORTLAYER_H - -#define PRECISION 0.0001 - -// standard libraries -#include -#include -#include -#include -#include - -#ifdef MAC_PLUGIN - #include -#else - #include -#endif - -// Maya API -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// OGRE API -#include "Ogre.h" -#include "OgreDefaultHardwareBufferManager.h" -#include "OgreHardwareVertexBuffer.h" - -#pragma warning (disable : 4018) - -#endif \ No newline at end of file diff --git a/Tools/MayaExport/include/mesh.h b/Tools/MayaExport/include/mesh.h deleted file mode 100644 index dd6fca40b0d..00000000000 --- a/Tools/MayaExport/include/mesh.h +++ /dev/null @@ -1,137 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// mesh.h -// Author : Francesco Giordana -// Sponsored by : Anygma N.V. (http://www.nazooka.com) -// Start Date : January 13, 2005 -// Copyright : (C) 2006 by Francesco Giordana -// Email : fra.giordana@tiscali.it -//////////////////////////////////////////////////////////////////////////////// - -/********************************************************************************* -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Lesser General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -**********************************************************************************/ - -#ifndef _MESH_H -#define _MESH_H - -#include "submesh.h" -#include "skeleton.h" -#include "mayaExportLayer.h" -#include "vertex.h" - -namespace OgreMayaExporter -{ - /***** structures to store shared geometry *****/ - typedef struct dagInfotag - { - long offset; - long numVertices; - MDagPath dagPath; - BlendShape* pBlendShape; - } dagInfo; - - typedef struct sharedGeometrytag - { - std::vector vertices; - std::vector dagMap; - } sharedGeometry; - - typedef stdext::hash_map submeshPoseRemapping; - - typedef stdext::hash_map poseRemapping; - - - /***** Class Mesh *****/ - class Mesh - { - public: - //constructor - Mesh(const MString& name = ""); - //destructor - ~Mesh(); - //clear data - void clear(); - //get pointer to linked skeleton - Skeleton* getSkeleton(); - //load mesh data from a maya Fn - MStatus load(const MDagPath& meshDag,ParamList ¶ms); - //load vertex animations - MStatus loadAnims(ParamList ¶ms); - //load blend shape deformers - MStatus loadBlendShapes(ParamList ¶ms); - //load blend shape animations - MStatus loadBlendShapeAnimations(ParamList& params); - //write to a OGRE binary mesh - MStatus writeOgreBinary(ParamList ¶ms); - - protected: - //get uvsets info from the maya mesh - MStatus getUVSets(const MDagPath& meshDag); - //get skin cluster linked to the maya mesh - MStatus getSkinCluster(const MDagPath& meshDag,ParamList& params); - //get blend shape deformer linked to the maya mesh - MStatus getBlendShapeDeformer(const MDagPath& meshDag,ParamList& params); - //get connected shaders - MStatus getShaders(const MDagPath& meshDag); - //get vertex data - MStatus getVertices(const MDagPath& meshDag,ParamList& params); - //get vertex bone assignements - MStatus getVertexBoneWeights(const MDagPath& meshDag,OgreMayaExporter::ParamList ¶ms); - //get faces data - MStatus getFaces(const MDagPath& meshDag,ParamList& params); - //build shared geometry - MStatus buildSharedGeometry(const MDagPath& meshDag,ParamList& params); - //create submeshes - MStatus createSubmeshes(const MDagPath& meshDag,ParamList& params); - //load a vertex animation clip - MStatus loadClip(MString& clipName,float start,float stop,float rate,ParamList& params); - //load a vertex animation track for the whole mesh - MStatus loadMeshTrack(Animation& a,std::vector& times,ParamList& params); - //load all submesh animation tracks (one for each submesh) - MStatus loadSubmeshTracks(Animation& a,std::vector& times,ParamList& params); - //load a keyframe for the whole mesh - MStatus loadKeyframe(Track& t,float time,ParamList& params); - //write shared geometry data to an Ogre compatible mesh - MStatus createOgreSharedGeometry(Ogre::MeshPtr pMesh,ParamList& params); - //create an Ogre compatible vertex buffer - MStatus createOgreVertexBuffer(Ogre::MeshPtr pMesh,Ogre::VertexDeclaration* pDecl,const std::vector& vertices); - //create Ogre poses for pose animation - MStatus createOgrePoses(Ogre::MeshPtr pMesh,ParamList& params); - //create vertex animations for an Ogre mesh - MStatus createOgreVertexAnimations(Ogre::MeshPtr pMesh,ParamList& params); - //create pose animations for an Ogre mesh - MStatus createOgrePoseAnimations(Ogre::MeshPtr pMesh,ParamList& params); - - //internal members - MString m_name; - long m_numTriangles; - std::vector m_uvsets; - std::vector m_submeshes; - Skeleton* m_pSkeleton; - sharedGeometry m_sharedGeom; - std::vector m_vertexClips; - std::vector m_BSClips; - //temporary members (existing only during translation from maya mesh) - std::vector newvertices; - std::vector newweights; - std::vector newjointIds; - MPointArray newpoints; - MFloatVectorArray newnormals; - MStringArray newuvsets; - MFnSkinCluster* pSkinCluster; - BlendShape* pBlendShape; - MObjectArray shaders; - MIntArray shaderPolygonMapping; - std::vector polygonSets; - bool opposite; - poseRemapping m_poseRemapping; - }; - -}; // end of namespace - -#endif \ No newline at end of file diff --git a/Tools/MayaExport/include/ogreExporter.h b/Tools/MayaExport/include/ogreExporter.h deleted file mode 100644 index c6441c43915..00000000000 --- a/Tools/MayaExport/include/ogreExporter.h +++ /dev/null @@ -1,110 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// ogreExporter.h -// Author : Francesco Giordana -// Sponsored by : Anygma N.V. (http://www.nazooka.com) -// Start Date : January 13, 2005 -// Copyright : (C) 2006 by Francesco Giordana -// Email : fra.giordana@tiscali.it -//////////////////////////////////////////////////////////////////////////////// - -/********************************************************************************* -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Lesser General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -**********************************************************************************/ -/********************************************************************************* - * Description: This is a plugin for Maya, that allows the export of animated * - * meshes in the OGRE file format. All meshes will be combined * - * together to form a single OGRE mesh, each Maya mesh will be * - * translated as a submesh. Multiple materials per mesh are allowed * - * each group of triangles sharing the same material will become * - * a separate submesh. Skeletal animation and blendshapes are * - * supported, or, alternatively, vertex animation as a sequence * - * of morph targets. * - * The export command can be run via script too, for instructions * - * on its usage please refer to the Instructions.txt file. * - *********************************************************************************/ -/********************************************************************************* - * Note: The particles exporter is an extra module submitted by the OGRE * - * community, it still has to be reviewed and fixed. * - *********************************************************************************/ - -#ifndef OGRE_EXPORTER_H -#define OGRE_EXPORTER_H - -#include "mesh.h" -#include "particles.h" -#include "mayaExportLayer.h" -#include -#include - -namespace OgreMayaExporter -{ - class OgreExporter : public MPxCommand - { - public: - // Public methods - //constructor - OgreExporter(); - //destructor - virtual ~OgreExporter(); - //override of MPxCommand methods - static void* creator(); - MStatus doIt(const MArgList& args); - bool isUndoable() const; - - protected: - // Internal methods - //analyses a dag node in Maya and translates it to the OGRE format, - //it is recursively applied until the whole dag nodes tree has been visited - MStatus translateNode(MDagPath& dagPath); - //writes animation data to an extra .anim file - MStatus writeAnim(MFnAnimCurve& anim); - //writes camera data to an extra .camera file - MStatus writeCamera(MFnCamera& camera); - //writes all translated data to a group of OGRE files - MStatus writeOgreData(); - //cleans up memory and exits - void exit(); - - private: - // private members - MStatus stat; - ParamList m_params; - Mesh* m_pMesh; - MaterialSet* m_pMaterialSet; - MSelectionList m_selList; - MTime m_curTime; - }; - - - - - /********************************************************************************************* - * INLINE Functions * - *********************************************************************************************/ - // Standard constructor - inline OgreExporter::OgreExporter() - :m_pMesh(0), m_pMaterialSet(0) - { - MGlobal::displayInfo("Translating scene to OGRE format"); - } - - // Routine for creating the plug-in - inline void* OgreExporter::creator() - { - return new OgreExporter(); - } - - // It tells that this command is not undoable - inline bool OgreExporter::isUndoable() const - { - MGlobal::displayInfo("Command is not undoable"); - return false; - } - -} //end namespace -#endif \ No newline at end of file diff --git a/Tools/MayaExport/include/paramlist.h b/Tools/MayaExport/include/paramlist.h deleted file mode 100644 index 8fe79233c73..00000000000 --- a/Tools/MayaExport/include/paramlist.h +++ /dev/null @@ -1,231 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// paramlist.h -// Author : Francesco Giordana -// Sponsored by : Anygma N.V. (http://www.nazooka.com) -// Start Date : January 13, 2005 -// Copyright : (C) 2006 by Francesco Giordana -// Email : fra.giordana@tiscali.it -//////////////////////////////////////////////////////////////////////////////// - -/********************************************************************************* -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Lesser General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -**********************************************************************************/ - -#ifndef PARAMLIST_H -#define PARAMLIST_H - -#include "mayaExportLayer.h" - -// Length units multipliers from Maya internal unit (cm) - -#define CM2MM 10.0 -#define CM2CM 1.0 -#define CM2M 0.01 -#define CM2IN 0.393701 -#define CM2FT 0.0328084 -#define CM2YD 0.0109361 - -namespace OgreMayaExporter -{ - class Submesh; - - typedef struct clipInfoTag - { - float start; //start time of the clip - float stop; //end time of the clip - float rate; //sample rate of anim curves, -1 means auto - MString name; //clip name - } clipInfo; - - typedef enum - { - NPT_CURFRAME, - NPT_BINDPOSE - } NeutralPoseType; - - typedef enum - { - TS_TEXCOORD, - TS_TANGENT - } TangentSemantic; - - /***** Class ParamList *****/ - class ParamList - { - public: - // class members - bool exportMesh, exportMaterial, exportAnimCurves, exportCameras, exportAll, exportVBA, - exportVertNorm, exportVertCol, exportTexCoord, exportCamerasAnim, - exportSkeleton, exportSkelAnims, exportBSAnims, exportVertAnims, exportBlendShapes, - exportWorldCoords, useSharedGeom, lightingOff, copyTextures, exportParticles, - buildTangents, buildEdges, skelBB, bsBB, vertBB, - tangentsSplitMirrored, tangentsSplitRotated, tangentsUseParity; - - float lum; // Length Unit Multiplier - - MString meshFilename, skeletonFilename, materialFilename, animFilename, camerasFilename, matPrefix, - texOutputDir, particlesFilename; - - std::ofstream outMaterial, outAnim, outCameras, outParticles; - - MStringArray writtenMaterials; - - std::vector skelClipList; - std::vector BSClipList; - std::vector vertClipList; - - NeutralPoseType neutralPoseType; - TangentSemantic tangentSemantic; - - std::vector loadedSubmeshes; - std::vector currentRootJoints; - - // constructor - ParamList() { - lum = 1.0; - exportMesh = false; - exportMaterial = false; - exportSkeleton = false; - exportSkelAnims = false; - exportBSAnims = false; - exportVertAnims = false; - exportBlendShapes = false; - exportAnimCurves = false; - exportCameras = false; - exportParticles = false; - exportAll = false; - exportWorldCoords = false; - exportVBA = false; - exportVertNorm = false; - exportVertCol = false; - exportTexCoord = false; - exportCamerasAnim = false; - useSharedGeom = false; - lightingOff = false; - copyTextures = false; - skelBB = false; - bsBB = false; - vertBB = false; - meshFilename = ""; - skeletonFilename = ""; - materialFilename = ""; - animFilename = ""; - camerasFilename = ""; - particlesFilename = ""; - matPrefix = ""; - texOutputDir = ""; - skelClipList.clear(); - BSClipList.clear(); - vertClipList.clear(); - neutralPoseType = NPT_CURFRAME; - buildEdges = false; - buildTangents = false; - tangentsSplitMirrored = false; - tangentsSplitRotated = false; - tangentsUseParity = false; - tangentSemantic = TS_TANGENT; - loadedSubmeshes.clear(); - currentRootJoints.clear(); - } - - ParamList& operator=(ParamList& source) - { - int i; - lum = source.lum; - exportMesh = source.exportMesh; - exportMaterial = source.exportMaterial; - exportSkeleton = source.exportSkeleton; - exportSkelAnims = source.exportSkelAnims; - exportBSAnims = source.exportBSAnims; - exportVertAnims = source.exportVertAnims; - exportBlendShapes = source.exportBlendShapes; - exportAnimCurves = source.exportAnimCurves; - exportCameras = source.exportCameras; - exportAll = source.exportAll; - exportWorldCoords = source.exportWorldCoords; - exportVBA = source.exportVBA; - exportVertNorm = source.exportVertNorm; - exportVertCol = source.exportVertCol; - exportTexCoord = source.exportTexCoord; - exportCamerasAnim = source.exportCamerasAnim; - exportParticles = source.exportParticles; - useSharedGeom = source.useSharedGeom; - lightingOff = source.lightingOff; - copyTextures = source.copyTextures; - skelBB = source.skelBB; - bsBB = source.bsBB; - vertBB = source.vertBB; - meshFilename = source.meshFilename; - skeletonFilename = source.skeletonFilename; - materialFilename = source.materialFilename; - animFilename = source.animFilename; - camerasFilename = source.camerasFilename; - particlesFilename = source.particlesFilename; - matPrefix = source.matPrefix; - texOutputDir = source.texOutputDir; - buildEdges = source.buildEdges; - buildTangents = source.buildTangents; - tangentsSplitMirrored = source.tangentsSplitMirrored; - tangentsSplitRotated = source.tangentsSplitRotated; - tangentsUseParity = source.tangentsUseParity; - tangentSemantic = source.tangentSemantic; - skelClipList.resize(source.skelClipList.size()); - for (i=0; i< skelClipList.size(); i++) - { - skelClipList[i].name = source.skelClipList[i].name; - skelClipList[i].start = source.skelClipList[i].start; - skelClipList[i].stop = source.skelClipList[i].stop; - skelClipList[i].rate = source.skelClipList[i].rate; - } - BSClipList.resize(source.BSClipList.size()); - for (i=0; i< BSClipList.size(); i++) - { - BSClipList[i].name = source.BSClipList[i].name; - BSClipList[i].start = source.BSClipList[i].start; - BSClipList[i].stop = source.BSClipList[i].stop; - BSClipList[i].rate = source.BSClipList[i].rate; - } - vertClipList.resize(source.vertClipList.size()); - for (i=0; i< vertClipList.size(); i++) - { - vertClipList[i].name = source.vertClipList[i].name; - vertClipList[i].start = source.vertClipList[i].start; - vertClipList[i].stop = source.vertClipList[i].stop; - vertClipList[i].rate = source.vertClipList[i].rate; - } - neutralPoseType = source.neutralPoseType; - for (i=0; i -#include -#ifdef MAC_PLUGIN -#include -#else -#include -#endif -#include -#include "paramList.h" -#include "mayaExportLayer.h" -#pragma warning(disable: 4996) - -namespace OgreMayaExporter -{ -//////////////////////////////////////////////////////////////////////////////////////////////////// -inline float fabs( float fVal ) { return ::fabs( fVal ); } -//////////////////////////////////////////////////////////////////////////////////////////////////// -struct SPos -{ - float x; - float y; - float z; - - SPos(): x(0), y(0), z(0) {} - SPos( float _x, float _y, float _z ): x(_x), y(_y), z(_z) {} -}; -inline const SPos operator-( const SPos &in ) { return SPos( -in.x, -in.y, -in.z ); } -inline const SPos operator+( const SPos &in1, const SPos &in2 ) { return SPos( in1.x + in2.x, in1.y + in2.y, in1.z + in2.z ); } -inline const SPos operator-( const SPos &in1, const SPos &in2 ) { return SPos( in1.x - in2.x, in1.y - in2.y, in1.z - in2.z ); } -inline float fabs2( const SPos &in ) { return in.x * in.x + in.y * in.y + in.z * in.z; } -inline float fabs( const SPos &in ) { return float( sqrt( fabs2( in ) ) ); } -//////////////////////////////////////////////////////////////////////////////////////////////////// -struct SColor -{ - union - { - struct - { - float x, y, z, w; - }; - struct - { - float r, g, b, a; - }; - }; - - SColor(): r(0), g(0), b(0), a(0) {} - SColor( float _r, float _g, float _b, float _a ): r(_r), g(_g), b(_b), a(_a) {} -}; -inline const SColor operator-( const SColor &in1) { return SColor( -in1.x, -in1.y, -in1.z, -in1.w ); } -inline const SColor operator+( const SColor &in1, const SColor &in2 ) { return SColor( in1.x + in2.x, in1.y + in2.y, in1.z + in2.z, in1.w + in2.w ); } -inline const SColor operator-( const SColor &in1, const SColor &in2 ) { return SColor( in1.x - in2.x, in1.y - in2.y, in1.z - in2.z, in1.w - in2.w ); } -inline float fabs2( const SColor &in ) { return in.x * in.x + in.y * in.y + in.z * in.z + in.w * in.w; } -inline float fabs( const SColor &in ) { return float( sqrt( fabs2( in ) ) ); } -//////////////////////////////////////////////////////////////////////////////////////////////////// -struct SScale -{ - float x; - float y; - - SScale(): x(0), y(0) {} - SScale( float _x, float _y ): x(_x), y(_y) {} -}; -inline const SScale operator+( const SScale &in1, const SScale &in2 ) { return SScale( in1.x + in2.x, in1.y + in2.y ); } -inline const SScale operator-( const SScale &in1, const SScale &in2 ) { return SScale( in1.x - in2.x, in1.y - in2.y ); } -inline float fabs2( const SScale &in ) { return in.x * in.x + in.y * in.y; } -inline float fabs( const SScale &in ) { return float( sqrt( fabs2( in ) ) ); } -//////////////////////////////////////////////////////////////////////////////////////////////////// -struct SParticleData -{ - int nFrame; - int nSprite; - SPos pos; - SColor color; - SScale scale; - float fRotation; - //// - SParticleData(): nFrame( 0 ), nSprite( 0 ), pos( 0, 0, 0 ), color( 1, 1, 1, 1 ), scale( 1, 1 ), fRotation( 0 ) {} -}; -typedef std::vector CParticlesTrack; -#ifdef MAC_PLUGIN -typedef __gnu_cxx::hash_map CParticlesData; -#else -typedef stdext::hash_map CParticlesData; -#endif -//////////////////////////////////////////////////////////////////////////////////////////////////// -template -inline void Interpolate( const T &v1, const T &v2, float fCoeff, T *pRes ) -{ - pRes->Interpolate( v1, v2, fCoeff ); -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -inline void Interpolate( const int &v1, const int &v2, float fCoeff, int *pRes ) -{ - *pRes = v1; -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -inline void Interpolate( const float &v1, const float &v2, float fCoeff, float *pRes ) -{ - *pRes = ( 1 - fCoeff ) * v1 + fCoeff * v2; -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -inline void Interpolate( const SPos &v1, const SPos &v2, float fCoeff, SPos *pRes ) -{ - Interpolate( v1.x, v2.x, fCoeff, &pRes->x ); - Interpolate( v1.y, v2.y, fCoeff, &pRes->y ); - Interpolate( v1.z, v2.z, fCoeff, &pRes->z ); -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -inline void Interpolate( const SColor &v1, const SColor &v2, float fCoeff, SColor *pRes ) -{ - Interpolate( v1.r, v2.r, fCoeff, &pRes->r ); - Interpolate( v1.g, v2.g, fCoeff, &pRes->g ); - Interpolate( v1.b, v2.b, fCoeff, &pRes->b ); - Interpolate( v1.a, v2.a, fCoeff, &pRes->a ); -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -inline void Interpolate( const SScale &v1, const SScale &v2, float fCoeff, SScale *pRes ) -{ - Interpolate( v1.x, v2.x, fCoeff, &pRes->x ); - Interpolate( v1.y, v2.y, fCoeff, &pRes->y ); -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -template -class TKey -{ -public: - T value; - int nTime; -}; -//////////////////////////////////////////////////////////////////////////////////////////////////// -template -class TKeyTrack -{ -public: - std::vector > keys; - -protected: - void GetValueBinSearch( float fTime, T *pRes ) const - { - int nLeft = 0, nRight = keys.size() - 1; - int nTime = int( fTime - 0.5f ); - while( nLeft - nRight > 1 ) - { - int nTemp = ( nLeft + nRight ) / 2; - if ( keys[nTemp].nTime <= nTime ) - nLeft = nTemp; - else - nRight = nTemp; - } - //// - const TKey &end = keys[nRight]; - const TKey &start = keys[nLeft]; - float fCoeff = ( fTime - start.nTime ) / ( end.nTime - start.nTime ); - Interpolate( start.value, end.value, fCoeff, pRes ); - } - -public: - void GetValue( float fTime, T *pRes ) const - { - if ( keys.size() == 1 ) - *pRes = keys[0].value; - else - GetValueBinSearch( fTime, pRes ); - } -}; -//////////////////////////////////////////////////////////////////////////////////////////////////// -struct SParticle -{ - int nEndTime; - int nStartTime; - TKeyTrack sprite; - TKeyTrack pos; - TKeyTrack color; - TKeyTrack scale; - TKeyTrack rotation; -}; -//////////////////////////////////////////////////////////////////////////////////////////////////// -// Particles -//////////////////////////////////////////////////////////////////////////////////////////////////// -class Particles -{ -private: - CParticlesData data; - //// - int nFrames; - std::vector particleTracks; - -protected: - MStatus ExportFrame( MDagPath &dagPath, int nFrame ); - MStatus FinalizeData( int nMinFrame, int nMaxFrame ); - -public: - Particles(); - virtual ~Particles(); - - MStatus load( MDagPath& dagPath, ParamList& params ); - MStatus writeToXML( ParamList& params ); - void clear(); -}; -//////////////////////////////////////////////////////////////////////////////////////////////////// -}; // end of namespace -//////////////////////////////////////////////////////////////////////////////////////////////////// -#endif \ No newline at end of file diff --git a/Tools/MayaExport/include/skeleton.h b/Tools/MayaExport/include/skeleton.h deleted file mode 100644 index 56e43f0be13..00000000000 --- a/Tools/MayaExport/include/skeleton.h +++ /dev/null @@ -1,87 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// skeleton.h -// Author : Francesco Giordana -// Sponsored by : Anygma N.V. (http://www.nazooka.com) -// Start Date : January 13, 2005 -// Copyright : (C) 2006 by Francesco Giordana -// Email : fra.giordana@tiscali.it -//////////////////////////////////////////////////////////////////////////////// - -/********************************************************************************* -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Lesser General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -**********************************************************************************/ - -#ifndef _SKELETON_H -#define _SKELETON_H - -#include "mayaExportLayer.h" -#include "paramList.h" -#include "animation.h" - -namespace OgreMayaExporter -{ - /***** structure to hold joint info *****/ - typedef struct jointTag - { - MString name; - int id; - MMatrix localMatrix; - MMatrix bindMatrix; - int parentIndex; - double posx,posy,posz; - double angle; - double axisx,axisy,axisz; - float scalex,scaley,scalez; - MDagPath jointDag; - } joint; - - - /*********** Class Skeleton **********************/ - class Skeleton - { - public: - //constructor - Skeleton(); - //destructor - ~Skeleton(); - //clear skeleton data - void clear(); - //load skeleton data - MStatus load(MFnSkinCluster* pSkinCluster,ParamList& params); - //load skeletal animations - MStatus loadAnims(ParamList& params); - //get joints - std::vector& getJoints(); - //get animations - std::vector& getAnimations(); - //restore skeleton pose - void restorePose(); - //write to an OGRE binary skeleton - MStatus writeOgreBinary(ParamList ¶ms); - - protected: - //load a joint - MStatus loadJoint(MDagPath& jointDag, joint* parent, ParamList& params,MFnSkinCluster* pSkinCluster); - //load a clip - MStatus loadClip(MString clipName,float start,float stop,float rate,ParamList& params); - //load a keyframe for a particular joint at current time - skeletonKeyframe loadKeyframe(joint& j,float time,ParamList& params); - //write joints to an Ogre skeleton - MStatus createOgreBones(Ogre::SkeletonPtr pSkeleton,ParamList& params); - // write skeleton animations to an Ogre skeleton - MStatus createOgreSkeletonAnimations(Ogre::SkeletonPtr pSkeleton,ParamList& params); - - std::vector m_joints; - std::vector m_animations; - std::vector m_roots; - MString m_restorePose; - }; - -} //end namespace - -#endif diff --git a/Tools/MayaExport/include/submesh.h b/Tools/MayaExport/include/submesh.h deleted file mode 100644 index e61a43fd1f7..00000000000 --- a/Tools/MayaExport/include/submesh.h +++ /dev/null @@ -1,76 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// submesh.h -// Author : Francesco Giordana -// Sponsored by : Anygma N.V. (http://www.nazooka.com) -// Start Date : January 13, 2005 -// Copyright : (C) 2006 by Francesco Giordana -// Email : fra.giordana@tiscali.it -//////////////////////////////////////////////////////////////////////////////// - -/********************************************************************************* -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Lesser General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -**********************************************************************************/ - -#ifndef _SUBMESH_H -#define _SUBMESH_H - -#include "mayaExportLayer.h" -#include "paramList.h" -#include "materialSet.h" -#include "animation.h" -#include "vertex.h" -#include "blendshape.h" - -namespace OgreMayaExporter -{ - /***** Class Submesh *****/ - class Submesh - { - public: - //constructor - Submesh(const MString& name = ""); - //destructor - ~Submesh(); - //clear data - void clear(); - //load data - MStatus loadMaterial(MObject& shader,MStringArray& uvsets,ParamList& params); - MStatus load(const MDagPath& dag,std::vector& faces, std::vector& vertInfo, MPointArray& points, - MFloatVectorArray& normals, MStringArray& texcoordsets,ParamList& params,bool opposite = false); - //load a keyframe for the whole mesh - MStatus loadKeyframe(Track& t,float time,ParamList& params); - //get number of triangles composing the submesh - long numTriangles(); - //get number of vertices - long numVertices(); - //get submesh name - MString& name(); - //write submesh data to an Ogre compatible mesh - MStatus createOgreSubmesh(Ogre::MeshPtr pMesh,const ParamList& params); - //create an Ogre compatible vertex buffer - MStatus createOgreVertexBuffer(Ogre::SubMesh* pSubmesh,Ogre::VertexDeclaration* pDecl,const std::vector& vertices); - - public: - //public members - MString m_name; - Material* m_pMaterial; - long m_numTriangles; - long m_numVertices; - std::vector m_indices; - std::vector m_vertices; - std::vector m_faces; - std::vector m_uvsets; - bool m_use32bitIndexes; - MDagPath m_dagPath; - BlendShape* m_pBlendShape; - MBoundingBox m_boundingBox; - }; - -}; // end of namespace - -#endif \ No newline at end of file diff --git a/Tools/MayaExport/include/vertex.h b/Tools/MayaExport/include/vertex.h deleted file mode 100644 index 33667524421..00000000000 --- a/Tools/MayaExport/include/vertex.h +++ /dev/null @@ -1,74 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// vertex.h -// Author : Francesco Giordana -// Sponsored by : Anygma N.V. (http://www.nazooka.com) -// Start Date : January 13, 2005 -// Copyright : (C) 2006 by Francesco Giordana -// Email : fra.giordana@tiscali.it -//////////////////////////////////////////////////////////////////////////////// - -/********************************************************************************* -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Lesser General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -**********************************************************************************/ - -#ifndef _VERTEX_H -#define _VERTEX_H - -/***** structure for uvsets info *****/ - typedef struct uvsettag - { - short size; //number of coordinates (between 1 and 3) - } uvset; - /***** structure for texture coordinates *****/ - typedef struct texcoordstag - { - float u, v, w; //texture coordinates - } texcoord; - - /***** structure for vertex bone assignements *****/ - typedef struct vbatag - { - float weight; //weight - int jointIdx; //index of associated joint - } vba; - - /***** structure for vertex data *****/ - typedef struct vertextag - { - double x, y, z; //vertex coordinates - MVector n; //vertex normal - float r,g,b,a; //vertex colour - std::vector texcoords; //vertex texture coordinates - std::vector vbas; //vertex bone assignements - long index; //vertex index in the maya mesh to which this vertex refers - } vertex; - - /***** structure for vertex info *****/ - // used to hold indices to access MFnMesh data - typedef struct vertexInfotag - { - int pointIdx; //index to points list (position) - int normalIdx; //index to normals list - float r,g,b,a; //colour - std::vector u; //u texture coordinates - std::vector v; //v texture coordinates - std::vector vba; //vertex bone assignements - std::vector jointIds; //ids of joints affecting this vertex - int next; //index of next vertex with same position - } vertexInfo; - - /***** structure for face info *****/ - typedef struct facetag - { - long v[3]; //vertex indices - } face; - - /***** array of face infos *****/ - typedef std::vector faceArray; - -#endif \ No newline at end of file diff --git a/Tools/MayaExport/mel/ogreExporter.mel b/Tools/MayaExport/mel/ogreExporter.mel deleted file mode 100644 index 49ee4606fe6..00000000000 --- a/Tools/MayaExport/mel/ogreExporter.mel +++ /dev/null @@ -1,2373 +0,0 @@ -// ===== Load Plug-in -loadPlugin "ogreExporter"; - -// ===== Create Ogre menu -setParent "MayaWindow"; -menu -label "Ogre" -tearOff false; - menuItem -label "Export" -command "ogreExporter"; - -// ===== Launch exporter UI -global proc ogreExporter() -{ - defineOgreExporterUIView(); - loadOgreExporterSettings(); -} - -// ===== Export -global proc runOgreExport() -{ - global int $numSkelClips; - global int $numBSClips; - global int $numVertClips; - // ===== Files and directories - string $sceneFile = `file -query -sceneName`; - string $mayaFile = basename($sceneFile, ""); - string $sceneDir = dirname($sceneFile); - string $baseFile = basename($sceneFile, ".mb"); - string $outputDir = (`textField -query -text OutputDirectory`); - if (!endsWith($outputDir,"\\") && !endsWith($outputDir,"/") && (size($outputDir)>0)) - $outputDir += "/"; - string $meshFile = (`textField -query -text ExportMeshFilename`); - string $materialFile = (`textField -query -text ExportMaterialFilename`); - string $skeletonFile = (`textField -query -text ExportSkeletonFilename`); - string $animFile = (`textField -query -text ExportAnimCurvesFilename`); - string $camerasFile = (`textField -query -text ExportCamerasFilename`); - string $particlesFile= (`textField -query -text ExportParticlesFilename`); - - // ===== Options - string $options = ""; - string $selectedExportTypeButton = `radioCollection -query -select ExportTypeCollection`; - if ($selectedExportTypeButton == "RadioButtonSelected") - { - $options += " -sel"; - } - else - { - $options += " -all"; - } - string $selectedCoordsTypeButton = `radioCollection -query -select CoordsTypeCollection`; - if ($selectedCoordsTypeButton == "RadioButtonWorld") - { - $options += " -world"; - } - else - { - $options += " -obj"; - } - $options += " -lu"; - int $lenghtUnit = `optionMenu -query -select UnitsMenu`; - switch ($lenghtUnit) - { - case 1: - $options += " pref"; - break; - case 2: - $options += " mm"; - break; - case 3: - $options += " cm"; - break; - case 4: - $options += " m"; - break; - case 5: - $options += " in"; - break; - case 6: - $options += " ft"; - break; - case 7: - $options += " yd"; - break; - } - $options += " -scale "; - float $globScale = `floatField -query -value GlobalScale`; - $options += $globScale; - - // --- Mesh export - int $exportMesh = `checkBox -query -value ExportMesh`; - if ($exportMesh) - { - $options += " -mesh"; - $options += " \"" + encodeString(toNativePath($outputDir+$meshFile)) + "\""; - - if (`checkBox -query -value UseSharedGeometry`) - { - $options += " -shared"; - } - - if (`checkBox -query -value ExportVBA`) - { - $options += " -v"; - } - - if (`checkBox -query -value ExportMeshNormals`) - { - $options += " -n"; - } - - if (`checkBox -query -value ExportMeshColours`) - { - $options += " -c"; - } - - if (`checkBox -query -value ExportMeshUVs`) - { - $options += " -t"; - } - if (`checkBox -query -value BuildEdges`) - { - $options += " -edges"; - } - if (`checkBox -query -value BuildTangents`) - { - $options += " -tangents"; - if (`radioButton -query -select TangentSemanticTexCoord`) - $options += " TEXCOORD"; - else - $options += " TANGENT"; - - if (`checkBox -query -value TangentsSplitMirrored`) - { - $options += " -tangentsplitmirrored"; - } - if (`checkBox -query -value TangentsSplitRotated`) - { - $options += " -tangentsplitrotated"; - } - if (`checkBox -query -value TangentsUseParity`) - { - $options += " -tangentuseparity"; - } - - } - } - - // --- Material export - int $exportMaterial = `checkBox -query -value ExportMaterial`; - if ($exportMaterial) - { - $options += " -mat \"" + encodeString(toNativePath($outputDir+$materialFile)) + "\""; - string $matPrefix = `textField -query -text ExportMaterialPrefix`; - if ($matPrefix != "") - { - $options += " -matPrefix \"" + $matPrefix + "\""; - } - if (`checkBox -query -value CopyTextures`) - { - $options += " -copyTex \"" + encodeString(toNativePath($outputDir)) + "\""; - } - if (`checkBox -query -value MatLightingOff`) - { - $options += " -lightOff"; - } - } - - // --- Skeleton export - int $exportSkeleton = `checkBox -query -value ExportSkeleton`; - if ($exportSkeleton) - { - $options += " -skel \"" + encodeString(toNativePath($outputDir+$skeletonFile)) + "\""; - } - - // --- Skeleton Animations export - int $exportSkelAnims = `checkBox -query -value ExportSkelAnims`; - if ($exportSkelAnims) - { - $options += " -skeletonAnims"; - - // check if we need to include skeleton animations in bounding box calculation - int $skelBB = `checkBox -query -value SkelBB`; - if ($skelBB) - { - $options += " -skelBB"; - } - - // neutral pose - int $neutralPose = `radioButtonGrp -q -select NeutralPoseRadio`; - if ($neutralPose == 1) - { - $options += " -np curFrame"; - } - else if ($neutralPose == 2) - { - $options += " -np bindPose"; - } - - // clips - int $i; - for ($i=1; $i<=$numSkelClips; $i++) - { - string $command = "checkBox -q -v ExportSkelClip" + $i; - if(eval($command)) - { - $options += " -skeletonClip "; - // clip name - $options += "\"" + eval("textField -q -tx SkelClipName"+$i) + "\""; - // clip range - int $skelClipRangeType = eval("radioButtonGrp -q -sl SkelClipRangeRadio"+$i); - if ($skelClipRangeType == 1) - { - $options += " startEnd "; - $options += eval("floatField -q -v SkelClipRangeStart"+$i); - $options += " " + eval("floatField -q -v SkelClipRangeEnd"+$i); - int $skelRangeUnits = eval("radioButtonGrp -q -sl SkelClipRangeUnits"+$i); - if ($skelRangeUnits == 1) - $options += " frames"; - else - $options += " seconds"; - } - else - $options += " timeSlider"; - // sample rate - int $skelClipRateType = eval("radioButtonGrp -q -sl SkelClipRateType"+$i); - if ($skelClipRateType == 1) - { - $options += " sampleByFrames "; - $options += eval("intField -q -v SkelClipRateFrames"+$i); - } - else - { - $options += " sampleBySec "; - $options += eval("floatField -q -v SkelClipRateSeconds"+$i); - } - } - } - } - - // --- Blend Shape export - int $exportBlendShapes = `checkBox -query -value ExportBlendShapes`; - if ($exportBlendShapes) - { - $options += " -blendShapes"; - - // check if we need to include blendshape animations in bounding box calculation - int $bsBB = `checkBox -query -value BsBB`; - if ($bsBB) - { - $options += " -bsBB"; - } - } - - // --- Blend Shape Animations export - int $exportBSAnims = `checkBox -query -value ExportBSAnims`; - if ($exportBSAnims) - { - $options += " -BSAnims"; - - // clips - int $i; - for ($i=1; $i<=$numBSClips; $i++) - { - string $command = "checkBox -q -v ExportBSClip" + $i; - if(eval($command)) - { - $options += " -BSClip "; - // clip name - $options += "\"" + eval("textField -q -tx BSClipName"+$i) + "\""; - // clip range - int $clipRangeType = eval("radioButtonGrp -q -sl BSClipRangeRadio"+$i); - if ($clipRangeType == 1) - { - $options += " startEnd "; - $options += eval("floatField -q -v BSClipRangeStart"+$i); - $options += " " + eval("floatField -q -v BSClipRangeEnd"+$i); - int $rangeUnits = eval("radioButtonGrp -q -sl BSClipRangeUnits"+$i); - if ($rangeUnits == 1) - $options += " frames"; - else - $options += " seconds"; - } - else - $options += " timeSlider"; - // sample rate - int $clipRateType = eval("radioButtonGrp -q -sl BSClipRateType"+$i); - if ($clipRateType == 1) - { - $options += " sampleByFrames "; - $options += eval("intField -q -v BSClipRateFrames"+$i); - } - else - { - $options += " sampleBySec "; - $options += eval("floatField -q -v BSClipRateSeconds"+$i); - } - } - } - } - - // --- Vertex Animations export - int $exportVertexAnims = `checkBox -query -value ExportVertexAnims`; - if ($exportVertexAnims) - { - $options += " -vertexAnims"; - - // check if we need to include vertex animations in bounding box calculation - int $vertBB = `checkBox -query -value VertBB`; - if ($vertBB) - { - $options += " -vertBB"; - } - - // clips - int $i; - for ($i=1; $i<=$numVertClips; $i++) - { - string $command = "checkBox -q -v ExportVertexClip" + $i; - if(eval($command)) - { - $options += " -vertexClip "; - // clip name - $options += "\"" + eval("textField -q -tx VertexClipName"+$i) + "\""; - // clip range - int $clipRangeType = eval("radioButtonGrp -q -sl VertexClipRangeRadio"+$i); - if ($clipRangeType == 1) - { - $options += " startEnd "; - $options += eval("floatField -q -v VertexClipRangeStart"+$i); - $options += " " + eval("floatField -q -v VertexClipRangeEnd"+$i); - int $rangeUnits = eval("radioButtonGrp -q -sl VertexClipRangeUnits"+$i); - if ($rangeUnits == 1) - $options += " frames"; - else - $options += " seconds"; - } - else - $options += " timeSlider"; - // sample rate - int $clipRateType = eval("radioButtonGrp -q -sl VertexClipRateType"+$i); - if ($clipRateType == 1) - { - $options += " sampleByFrames "; - $options += eval("intField -q -v VertexClipRateFrames"+$i); - } - else - { - $options += " sampleBySec "; - $options += eval("floatField -q -v VertexClipRateSeconds"+$i); - } - } - } - } - - // --- Anim Curves export - int $exportAnimCurves = `checkBox -query -value ExportAnimCurves`; - if ($exportAnimCurves) - { - $options += " -animCur \"" + encodeString(toNativePath($outputDir+$animFile)) + "\""; - } - - // --- Cameras export - int $exportCameras = `checkBox -query -value ExportCameras`; - if ($exportCameras) - { - $options += " -cam \"" + encodeString(toNativePath($outputDir+$camerasFile)) + "\""; - if (`checkBox -query -value ExportCamerasAnim`) - { - $options += " -camAnim"; - } - } - - // --- Particles export - int $exportParticles = `checkBox -query -value ExportParticles`; - if ($exportParticles) - { - $options += " -particles \"" + encodeString(toNativePath($outputDir+$particlesFile)) + "\""; - } - - // ===== Export - print ("ogreExport" + $options + ";\n"); - eval ("ogreExport" + $options); -} - -// ===== Format UI -// (Primarily enabling/disabling controls) -global proc formatOgreExporterUI() -{ - global int $numSkelClips; - global int $numBSClips; - global int $numVertClips; - // --- Common parameters - int $animType = `optionMenu -q -select AnimationTypeMenu`; - - // --- Mesh Export - int $exportMesh = `checkBox -q -v ExportMesh`; - checkBox -edit -enable $exportMesh UseSharedGeometry; - checkBox -edit -enable $exportMesh ExportVBA; - checkBox -edit -enable $exportMesh ExportMeshNormals; - checkBox -edit -enable $exportMesh ExportMeshColours; - int $exportColours = `checkBox -query -value ExportMeshColours`; - checkBox -edit -enable $exportMesh ExportMeshUVs; - text -edit -enable $exportMesh ExportMeshFilenameLabel; - textField -edit -enable $exportMesh ExportMeshFilename; - checkBox -edit -enable $exportMesh BuildEdges; - checkBox -edit -enable $exportMesh BuildTangents; - int $buildTangents = `checkBox -query -value BuildTangents`; - if ($exportMesh) - { - text -edit -enable $buildTangents TangentSemanticLabel; - radioButton -edit -enable $buildTangents TangentSemanticTexCoord; - radioButton -edit -enable $buildTangents TangentSemanticTangent; - checkBox -edit -enable $buildTangents TangentsSplitMirrored; - checkBox -edit -enable $buildTangents TangentsSplitRotated; - checkBox -edit -enable $buildTangents TangentsUseParity; - } - else - { - text -edit -enable false TangentSemanticLabel; - radioButton -edit -enable false TangentSemanticTexCoord; - radioButton -edit -enable false TangentSemanticTangent; - checkBox -edit -enable false TangentsSplitMirrored; - checkBox -edit -enable false TangentsSplitRotated; - checkBox -edit -enable false TangentsUseParity; - } - - // --- Material Export - int $exportMaterial = `checkBox -query -value ExportMaterial`; - text -edit -enable $exportMaterial ExportMaterialFilenameLabel; - textField -edit -enable $exportMaterial ExportMaterialFilename; - text -edit -enable $exportMaterial ExportMaterialPrefixLabel; - textField -edit -enable $exportMaterial ExportMaterialPrefix; - if (!$exportMaterial) - checkBox -edit -value false CopyTextures; - checkBox -edit -enable $exportMaterial CopyTextures; - if (!$exportMaterial) - checkBox -edit -value false MatLightingOff; - checkBox -edit -enable $exportMaterial MatLightingOff; - - // --- Skeleton Export - if ($animType == 1) - { - checkBox -edit -enable true ExportSkeleton; - } - else - { - checkBox -edit -value false ExportSkeleton; - checkBox -edit -enable false ExportSkeleton; - } - int $exportSkeleton = `checkBox -query -value ExportSkeleton`; - text -edit -enable $exportSkeleton ExportSkeletonFilenameLabel; - textField -edit -enable $exportSkeleton ExportSkeletonFilename; - - // --- Skeleton Animations Export - if (!$exportSkeleton) - checkBox -edit -value false ExportSkelAnims; - checkBox -edit -enable $exportSkeleton ExportSkelAnims; - int $exportSkelAnims = `checkBox -query -value ExportSkelAnims`; - if (!$exportSkelAnims) - checkBox -edit -value false SkelBB; - checkBox -edit -enable $exportSkelAnims SkelBB; - text -edit -enable $exportSkelAnims NeutralPoseLabel; - radioButtonGrp -edit -enable $exportSkelAnims NeutralPoseRadio; - int $neutralPoseType = `radioButtonGrp -query -select NeutralPoseRadio`; - int $i; - for ($i=1; $i<=$numSkelClips; $i++) - { - if (!$exportSkelAnims) - checkBox -edit -value false ("ExportSkelClip"+$i); - checkBox -edit -enable $exportSkelAnims ("ExportSkelClip"+$i); - - int $exportSkelClip = `checkBox -query -value ("ExportSkelClip"+$i)`; - textField -edit -enable $exportSkelClip ("SkelClipName"+$i); - text -edit -enable $exportSkelClip ("SkelClipRangeLabel"+$i); - radioButtonGrp -edit -enable $exportSkelClip ("SkelClipRangeRadio"+$i); - text -edit -enable $exportSkelClip ("SkelClipRateTypeLabel"+$i); - radioButtonGrp -edit -enable $exportSkelClip ("SkelClipRateType"+$i); - - int $skelRangeType = `radioButtonGrp -query -select ("SkelClipRangeRadio"+$i)`; - text -edit -enable (($skelRangeType == 1)&&($exportSkelClip)) ("SkelClipRangeStartLabel"+$i); - floatField -edit -enable (($skelRangeType == 1)&&($exportSkelClip)) ("SkelClipRangeStart"+$i); - text -edit -enable (($skelRangeType == 1)&&($exportSkelClip)) ("SkelClipRangeEndLabel"+$i); - floatField -edit -enable (($skelRangeType == 1)&&($exportSkelClip)) ("SkelClipRangeEnd"+$i); - radioButtonGrp -edit -enable (($skelRangeType == 1)&&($exportSkelClip)) ("SkelClipRangeUnits"+$i); - - int $skelRateType = `radioButtonGrp -query -select ("SkelClipRateType"+$i)`; - intField -edit -enable (($skelRateType == 1)&&($exportSkelClip)) ("SkelClipRateFrames"+$i); - floatField -edit -enable (($skelRateType == 2)&&($exportSkelClip)) ("SkelClipRateSeconds"+$i); - } - - // --- Blend Shape Export - if (!$exportMesh) - checkBox -edit -value false ExportBlendShapes; - if ($animType == 1) - { - checkBox -edit -enable $exportMesh ExportBlendShapes; - } - else - { - checkBox -edit -value false ExportBlendShapes; - checkBox -edit -enable false ExportBlendShapes; - } - int $exportBS = `checkBox -query -value ExportBlendShapes`; - if (!$exportBS) - checkBox -edit -value false BsBB; - checkBox -edit -enable $exportBS BsBB; - - // --- Blend Shape Animations Export - if (!$exportBS) - checkBox -edit -value false ExportBSAnims; - checkBox -edit -enable $exportBS ExportBSAnims; - int $exportBSAnims = `checkBox -query -value ExportBSAnims`; - int $i; - for ($i=1; $i<=$numBSClips; $i++) - { - if (!$exportBSAnims) - checkBox -edit -value false ("ExportBSClip"+$i); - checkBox -edit -enable $exportBSAnims ("ExportBSClip"+$i); - - int $exportBSClip = `checkBox -query -value ("ExportBSClip"+$i)`; - textField -edit -enable $exportBSClip ("BSClipName"+$i); - text -edit -enable $exportBSClip ("BSClipRangeLabel"+$i); - radioButtonGrp -edit -enable $exportBSClip ("BSClipRangeRadio"+$i); - text -edit -enable $exportBSClip ("BSClipRateTypeLabel"+$i); - radioButtonGrp -edit -enable $exportBSClip ("BSClipRateType"+$i); - - int $skelRangeType = `radioButtonGrp -query -select ("BSClipRangeRadio"+$i)`; - text -edit -enable (($skelRangeType == 1)&&($exportBSClip)) ("BSClipRangeStartLabel"+$i); - floatField -edit -enable (($skelRangeType == 1)&&($exportBSClip)) ("BSClipRangeStart"+$i); - text -edit -enable (($skelRangeType == 1)&&($exportBSClip)) ("BSClipRangeEndLabel"+$i); - floatField -edit -enable (($skelRangeType == 1)&&($exportBSClip)) ("BSClipRangeEnd"+$i); - radioButtonGrp -edit -enable (($skelRangeType == 1)&&($exportBSClip)) ("BSClipRangeUnits"+$i); - - int $skelRateType = `radioButtonGrp -query -select ("BSClipRateType"+$i)`; - intField -edit -enable (($skelRateType == 1)&&($exportBSClip)) ("BSClipRateFrames"+$i); - floatField -edit -enable (($skelRateType == 2)&&($exportBSClip)) ("BSClipRateSeconds"+$i); - } - - // --- Vertex Animations Export - if (!$exportMesh) - checkBox -edit -value false ExportVertexAnims; - if ($animType == 2) - { - checkBox -edit -enable $exportMesh ExportVertexAnims; - } - else - { - checkBox -edit -value false ExportVertexAnims; - checkBox -edit -enable false ExportVertexAnims; - } - int $exportVertexAnims = `checkBox -query -value ExportVertexAnims`; - if (!$exportVertexAnims) - checkBox -edit -value false VertBB; - checkBox -edit -enable $exportVertexAnims VertBB; - int $i; - for ($i=1; $i<=$numVertClips; $i++) - { - if (!$exportVertexAnims) - checkBox -edit -value false ("ExportVertexClip"+$i); - checkBox -edit -enable $exportVertexAnims ("ExportVertexClip"+$i); - - int $exportVertexClip = `checkBox -query -value ("ExportVertexClip"+$i)`; - textField -edit -enable $exportVertexClip ("VertexClipName"+$i); - text -edit -enable $exportVertexClip ("VertexClipRangeLabel"+$i); - radioButtonGrp -edit -enable $exportVertexClip ("VertexClipRangeRadio"+$i); - text -edit -enable $exportVertexClip ("VertexClipRateTypeLabel"+$i); - radioButtonGrp -edit -enable $exportVertexClip ("VertexClipRateType"+$i); - - int $rangeType = `radioButtonGrp -query -select ("VertexClipRangeRadio"+$i)`; - text -edit -enable (($rangeType == 1)&&($exportVertexClip)) ("VertexClipRangeStartLabel"+$i); - floatField -edit -enable (($rangeType == 1)&&($exportVertexClip)) ("VertexClipRangeStart"+$i); - text -edit -enable (($rangeType == 1)&&($exportVertexClip)) ("VertexClipRangeEndLabel"+$i); - floatField -edit -enable (($rangeType == 1)&&($exportVertexClip)) ("VertexClipRangeEnd"+$i); - radioButtonGrp -edit -enable (($rangeType == 1)&&($exportVertexClip)) ("VertexClipRangeUnits"+$i); - - int $rateType = `radioButtonGrp -query -select ("VertexClipRateType"+$i)`; - intField -edit -enable (($rateType == 1)&&($exportVertexClip)) ("VertexClipRateFrames"+$i); - floatField -edit -enable (($rateType == 2)&&($exportVertexClip)) ("VertexClipRateSeconds"+$i); - } - - // --- Anim Curves Export - int $exportAnimCurves = `checkBox -query -value ExportAnimCurves`; - text -edit -enable $exportAnimCurves ExportAnimCurvesFilenameLabel; - textField -edit -enable $exportAnimCurves ExportAnimCurvesFilename; - - // --- Camera Export - int $exportCameras = `checkBox -query -value ExportCameras`; - checkBox -edit -enable ($exportCameras && $exportAnimCurves) ExportCamerasAnim; - if (!$exportAnimCurves) - { - checkBox -edit -value false ExportCamerasAnim; - } - text -edit -enable $exportCameras ExportCamerasFilenameLabel; - textField -edit -enable $exportCameras ExportCamerasFilename; - - // --- particles Export - int $exportParticles = `checkBox -query -value ExportParticles`; - text -edit -enable $exportParticles ExportParticlesFilenameLabel; - textField -edit -enable $exportParticles ExportParticlesFilename; -} - -// ===== Define UI -global proc defineOgreExporterUIView() -{ - global int $numSkelClips; - $numSkelClips = 0; - global int $numBSClips; - $numBSClips = 0; - global int $numVertClips; - $numVertClips = 0; - - // --- Main window for Ogre exporter - if (`window -exists "OgreExportWindow"`) - { - deleteUI OgreExportWindow; - } - window - -title "Ogre Exporter" - OgreExportWindow; - scrollLayout - OgreExportScrollLayout; - columnLayout - OgreExportLayout; - - // --- Common Parameters Frame - frameLayout - -parent OgreExportLayout - -label "Common Parameters" - -collapsable true - CommonFrame; - - columnLayout - -parent CommonFrame - -columnAttach "left" 20 - CommonLayout; - - text - -parent CommonLayout - -label "Current Directory" - SceneDirectoryLabel; - - textField - -parent CommonLayout - -width 305 - -editable false - SceneDirectory; - - text - -parent CommonLayout - -label "Output Directory" - OutputDirectoryLabel; - - textField - -parent CommonLayout - -width 305 - OutputDirectory; - - rowColumnLayout - -parent CommonLayout - -numberOfColumns 3 - ExportTypeLayout; - - text -label "Export:"; - radioCollection ExportTypeCollection; - radioButton -label "all" -select RadioButtonAll; - radioButton -label "selected" RadioButtonSelected; - - rowColumnLayout - -parent CommonLayout - -numberOfColumns 3 - CoordsType; - - text -label "Coordinate space:"; - radioCollection CoordsTypeCollection; - radioButton -label "world" -select RadioButtonWorld; - radioButton -label "object" RadioButtonObject; - - rowColumnLayout - -parent CommonLayout - -numberOfColumns 2 - -columnWidth 1 100 - -columnWidth 2 150 - GeneralOptionsLayout; - - // Length measurement units - - text -label "Length Units:" - -parent GeneralOptionsLayout; - - optionMenu -parent GeneralOptionsLayout - -w 200 - UnitsMenu; - - menuItem -label "from prefs"; - menuItem -label "millimeter"; - menuItem -label "centimeter"; - menuItem -label "meter"; - menuItem -label "inch"; - menuItem -label "foot"; - menuItem -label "yard"; - - optionMenu -edit -select 1 UnitsMenu; - - // Animation type - - text -label "Animation Type:" - -parent GeneralOptionsLayout; - - optionMenu -parent GeneralOptionsLayout - -changeCommand "formatOgreExporterUI" - -w 200 - AnimationTypeMenu; - - menuItem -label "Skeleton / Blend Shapes"; - menuItem -label "Vertex"; - - optionMenu -edit -select 1 AnimationTypeMenu; - - // Global scale - - text -label "Scale all by:" - -parent GeneralOptionsLayout; - - floatField - -parent GeneralOptionsLayout - -width 50 - -value 1 - GlobalScale; - - // --- Mesh - frameLayout - -parent OgreExportLayout - -collapsable true - -label "Mesh" - MeshFrame; - - columnLayout - -parent MeshFrame - -columnAttach "left" 20 - MeshLayout; - - checkBox - -parent MeshLayout - -value false - -changeCommand "formatOgreExporterUI" - -label "Export mesh" - ExportMesh; - - checkBox - -parent MeshLayout - -value false - -changeCommand "formatOgreExporterUI" - -label "Use shared geometry" - UseSharedGeometry; - - checkBox - -parent MeshLayout - -value true - -enable false - -label "Include vertex bone assignements" - ExportVBA; - - checkBox - -parent MeshLayout - -value true - -enable false - -label "Include vertex normals" - ExportMeshNormals; - - checkBox - -parent MeshLayout - -value false - -changeCommand "formatOgreExporterUI" - -enable false - -label "Include diffuse vertex colours" - ExportMeshColours; - - checkBox - -parent MeshLayout - -value true - -enable false - -label "Include texture coordinates" - ExportMeshUVs; - - text - -parent MeshLayout - -label "Mesh Filename" - -enable false - ExportMeshFilenameLabel; - - textField - -parent MeshLayout - -width 305 - -enable false - ExportMeshFilename; - - checkBox - -parent MeshLayout - -value false - -enable false - -label "Build edges list (for shadows)" - BuildEdges; - - checkBox - -parent MeshLayout - -value false - -enable false - -label "Build tangent vectors (for normal maps)" - -changeCommand "formatOgreExporterUI" - BuildTangents; - - rowColumnLayout - -parent MeshLayout - -numberOfColumns 3 - TangentSemanticLayout; - - text - -parent TangentSemanticLayout - -label "Tangent semantic:" - -enable false - TangentSemanticLabel; - - radioCollection TangentSemanticCollection; - radioButton -label "TANGENT" -enable true -select TangentSemanticTangent; - radioButton -label "TEXCOORD" -enable true TangentSemanticTexCoord; - - checkBox - -parent MeshLayout - -value false - -enable false - -label "Split tangents at mirrored UVs" - TangentsSplitMirrored; - checkBox - -parent MeshLayout - -value false - -enable false - -label "Split tangents at rotated UVs" - TangentsSplitRotated; - checkBox - -parent MeshLayout - -value false - -enable false - -label "Use 4D tangents" - TangentsUseParity; - - - - - // --- Materials - frameLayout - -parent OgreExportLayout - -collapsable true - -label "Materials" - MaterialFrame; - - columnLayout - -parent MaterialFrame - -columnAttach "left" 20 - MaterialLayout; - - checkBox - -parent MaterialLayout - -value false - -changeCommand "formatOgreExporterUI" - -label "Export materials to Ogre .material file" - ExportMaterial; - - text - -parent MaterialLayout - -label "Material Filename" - -enable false - ExportMaterialFilenameLabel; - - textField - -parent MaterialLayout - -width 305 - -enable false - ExportMaterialFilename; - - text - -parent MaterialLayout - -label "Material name prefix" - -enable false - ExportMaterialPrefixLabel; - - textField - -parent MaterialLayout - -width 305 - -enable false - -text "" - ExportMaterialPrefix; - - checkBox - -parent MaterialLayout - -value false - -label "Copy texture files to output dir" - CopyTextures; - - checkBox - -parent MaterialLayout - -value false - -label "Export with \"ligthing off\" option" - MatLightingOff; - - // --- Skeleton - frameLayout - -parent OgreExportLayout - -collapsable true - -label "Skeleton" - SkeletonFrame; - - columnLayout - -parent SkeletonFrame - -columnAttach "left" 20 - SkeletonLayout; - - checkBox - -parent SkeletonLayout - -value false - -changeCommand "formatOgreExporterUI" - -label "Export skeleton" - ExportSkeleton; - - text - -parent SkeletonLayout - -label "Skeleton Filename" - -enable false - ExportSkeletonFilenameLabel; - - textField - -parent SkeletonLayout - -width 305 - -enable false - ExportSkeletonFilename; - - - // --- Skeleton Animations - frameLayout - -parent OgreExportLayout - -collapsable true - -label "Skeleton Animations" - -width 329 - SkelAnimsFrame; - - columnLayout - -parent SkelAnimsFrame - -columnAttach "left" 20 - SkelAnimsLayout; - - checkBox - -parent SkelAnimsLayout - -value false - -changeCommand "formatOgreExporterUI" - -label "Export animations (requires export of skeleton)" - ExportSkelAnims; - - checkBox - -parent SkelAnimsLayout - -value false - -changeCommand "formatOgreExporterUI" - -label "Include animations in bounding box" - SkelBB; - - text - -parent SkelAnimsLayout - -label "Neutral pose:" - NeutralPoseLabel; - - radioButtonGrp - -parent SkelAnimsLayout - -numberOfRadioButtons 2 - -labelArray2 "Current frame" "Skin bind pose" - -cw 1 100 - -cw 2 100 - -select 1 - -changeCommand "formatOgreExporterUI()" - NeutralPoseRadio; - - columnLayout - -parent SkelAnimsLayout - -columnAttach "left" 0 - SkelClipsLayout; - - rowLayout - -parent SkelAnimsLayout - -numberOfColumns 2 - -columnWidth 1 160 - -columnWidth 2 60 - -columnAttach 1 "left" 100 - SkelClipsButtonsLayout; - - button - -parent SkelClipsButtonsLayout - -label "Add Clip" - -width 60 - -command "addOgreExporterSkeletonClip()" - ButtonAddSkelClip; - - button - -parent SkelClipsButtonsLayout - -label "Delete Clip" - -width 60 - -command "delOgreExporterSkeletonClip()" - ButtonDelSkelClip; - - // --- Blend Shapes - frameLayout - -parent OgreExportLayout - -collapsable true - -label "Blend Shapes" - -width 329 - BlendShapesFrame; - - columnLayout - -parent BlendShapesFrame - -columnAttach "left" 20 - BlendShapesLayout; - - checkBox - -parent BlendShapesLayout - -value false - -changeCommand "formatOgreExporterUI" - -label "Export blend shapes (to mesh file)" - ExportBlendShapes; - - checkBox - -parent BlendShapesLayout - -value false - -changeCommand "formatOgreExporterUI" - -label "Include blend shapes in bounding box" - BsBB; - - // --- Blend Shapes Animations - frameLayout - -parent OgreExportLayout - -collapsable true - -label "Blend Shape Animations" - -width 329 - BSAnimsFrame; - - columnLayout - -parent BSAnimsFrame - -columnAttach "left" 20 - BSAnimsLayout; - - checkBox - -parent BSAnimsLayout - -value false - -changeCommand "formatOgreExporterUI" - -label "Export animations (to mesh file)" - ExportBSAnims; - - columnLayout - -parent BSAnimsLayout - -columnAttach "left" 0 - BSClipsLayout; - - rowLayout - -parent BSAnimsLayout - -numberOfColumns 2 - -columnWidth 1 160 - -columnWidth 2 60 - -columnAttach 1 "left" 100 - BSClipsButtonsLayout; - - button - -parent BSClipsButtonsLayout - -label "Add Clip" - -width 60 - -command "addOgreExporterBSClip()" - ButtonAddBSClip; - - button - -parent BSClipsButtonsLayout - -label "Delete Clip" - -width 60 - -command "delOgreExporterBSClip()" - ButtonDelBSClip; - - // --- Vertex Animations - frameLayout - -parent OgreExportLayout - -collapsable true - -label "Vertex Animations" - -width 329 - VertexAnimsFrame; - - columnLayout - -parent VertexAnimsFrame - -columnAttach "left" 20 - VertexAnimsLayout; - - checkBox - -parent VertexAnimsLayout - -value false - -changeCommand "formatOgreExporterUI" - -label "Export animations (to mesh file)" - ExportVertexAnims; - - checkBox - -parent VertexAnimsLayout - -value false - -changeCommand "formatOgreExporterUI" - -label "Include animations in bounding box" - VertBB; - - columnLayout - -parent VertexAnimsLayout - -columnAttach "left" 0 - VertexClipsLayout; - - rowLayout - -parent VertexAnimsLayout - -numberOfColumns 2 - -columnWidth 1 160 - -columnWidth 2 60 - -columnAttach 1 "left" 100 - VertexClipsButtonsLayout; - - button - -parent VertexClipsButtonsLayout - -label "Add Clip" - -width 60 - -command "addOgreExporterVertexClip()" - ButtonAddVertexClip; - - button - -parent VertexClipsButtonsLayout - -label "Delete Clip" - -width 60 - -command "delOgreExporterVertexClip()" - ButtonDelVertexClip; - - - // --- Anim Curves - frameLayout - -parent OgreExportLayout - -collapsable true - -label "Animation Curves" - AnimCurvesFrame; - - columnLayout - -parent AnimCurvesFrame - -columnAttach "left" 20 - AnimCurvesLayout; - - checkBox - -parent AnimCurvesLayout - -value false - -changeCommand "formatOgreExporterUI" - -label "Export animation curves to Ogre .anim file" - ExportAnimCurves; - - text - -parent AnimCurvesLayout - -label "Anim Curves Filename" - -enable false - ExportAnimCurvesFilenameLabel; - - textField - -parent AnimCurvesLayout - -width 305 - -enable false - ExportAnimCurvesFilename; - - // --- Cameras - frameLayout - -parent OgreExportLayout - -collapsable true - -label "Cameras" - CameraFrame; - - columnLayout - -parent CameraFrame - -columnAttach "left" 20 - CameraLayout; - - checkBox - -parent CameraLayout - -value false - -changeCommand "formatOgreExporterUI" - -label "Export cameras to Ogre .camera file" - ExportCameras; - - checkBox - -parent CameraLayout - -value false - -changeCommand "formatOgreExporterUI" - -label "Export Camera Animations(requires export of anim curves)" - ExportCamerasAnim; - - text - -parent CameraLayout - -label "Cameras Filename" - -enable false - ExportCamerasFilenameLabel; - - textField - -parent CameraLayout - -width 305 - -enable false - ExportCamerasFilename; - - // --- Particles - frameLayout - -parent OgreExportLayout - -collapsable true - -label "Particles" - ParticlesFrame; - - columnLayout - -parent ParticlesFrame - -columnAttach "left" 20 - ParticlesLayout; - - checkBox - -parent ParticlesLayout - -value false - -changeCommand "formatOgreExporterUI" - -label "Export particles to Ogre .particles file" - ExportParticles; - - text - -parent ParticlesLayout - -label "Particles Filename" - -enable false - ExportParticlesFilenameLabel; - - textField - -parent ParticlesLayout - -width 305 - -enable false - ExportParticlesFilename; - - // --- Export! - separator - -parent OgreExportLayout - -style "none" - -height 10; - - button - -parent OgreExportLayout - -label "EXPORT" - -command "runOgreExport" - -width 325 - ButtonExport; - - // --- Manage settings - separator - -parent OgreExportLayout - -style "in" - -width 325 - -height 5; - - rowLayout - -parent OgreExportLayout - -numberOfColumns 3 - -columnWidth3 110 110 100 - -columnAlign 1 "center" - -columnAlign 2 "center" - -columnAlign 3 "center" - SettingsButtonsLayout; - - button - -parent SettingsButtonsLayout - -label "Load settings" - -command "loadOgreExporterSettings" - -width 100 - LoadSettingsButton; - - button - -parent SettingsButtonsLayout - -label "Save settings" - -command "saveOgreExporterSettings" - -width 100 - SaveSettingsButton; - - button - -parent SettingsButtonsLayout - -label "Default settings" - -command "defaultOgreExporterSettings" - -width 100 - DefaultSettingsButton; - - - // --- Add an empty skeleton clip - addOgreExporterSkeletonClip(); - // --- Add an empty blend shape clip - addOgreExporterBSClip(); - // --- Add an empty vertex clip - addOgreExporterVertexClip(); - // --- Show the Window - showWindow OgreExportWindow; -} - -global proc addOgreExporterSkeletonClip() -{ - global int $numSkelClips; - $numSkelClips++; - - frameLayout - -parent SkelClipsLayout - -width 309 - -label ("Clip"+$numSkelClips) - ("SkelClipFrame"+$numSkelClips); - - columnLayout - -parent ("SkelClipFrame"+$numSkelClips) - -columnAttach "left" 0 - ("SkelClipLayout"+$numSkelClips); - - rowLayout - -parent ("SkelClipLayout"+$numSkelClips) - -numberOfColumns 2 - -columnWidth2 100 200 - -columnOffset2 5 5 - -columnAlign 1 "left" - -columnAlign 2 "left" - ("SkelClipNameLayout"+$numSkelClips); - - checkBox - -parent ("SkelClipNameLayout"+$numSkelClips) - -value false - -changeCommand "formatOgreExporterUI" - -label "Clip Name" - ("ExportSkelClip"+$numSkelClips); - - textField - -parent ("SkelClipNameLayout"+$numSkelClips) - -width 200 - -text ("clip"+$numSkelClips) - ("SkelClipName"+$numSkelClips); - - separator - -parent ("SkelClipLayout"+$numSkelClips) - -style "in" - -width 309 - -height 5; - - rowLayout - -parent ("SkelClipLayout"+$numSkelClips) - -numberOfColumns 2 - -columnWidth2 100 200 - -columnAlign 1 "left" - -columnAlign 2 "left" - ("SkelClipRangeTypeLayout"+$numSkelClips); - - text - -parent ("SkelClipRangeTypeLayout"+$numSkelClips) - -label "Time Range:" - ("SkelClipRangeLabel"+$numSkelClips); - - radioButtonGrp - -parent ("SkelClipRangeTypeLayout"+$numSkelClips) - -numberOfRadioButtons 2 - -labelArray2 "Start/End" "Time Slider" - -cw 1 100 - -cw 2 100 - -select 2 - -changeCommand "formatOgreExporterUI" - ("SkelClipRangeRadio"+$numSkelClips); - - columnLayout - -parent ("SkelClipLayout"+$numSkelClips) - -columnAttach "left" 70 - ("SkelClipRangeLayout"+$numSkelClips); - - rowLayout - -parent ("SkelClipRangeLayout"+$numSkelClips) - -numberOfColumns 2 - -columnAlign 1 "left" - -columnAlign 2 "left" - -columnAttach 1 "both" 0 - -columnAttach 2 "both" 0 - -columnOffset2 5 5 - -columnWidth 1 70 - -columnWidth 2 50 - ("SkelClipRangeStartLayout"+$numSkelClips); - - text - -parent ("SkelClipRangeStartLayout"+$numSkelClips) - -label "Start Time:" - -width 50 - ("SkelClipRangeStartLabel"+$numSkelClips); - - floatField - -parent ("SkelClipRangeStartLayout"+$numSkelClips) - -width 50 - -value 0.000 - ("SkelClipRangeStart"+$numSkelClips); - - rowLayout - -parent ("SkelClipRangeLayout"+$numSkelClips) - -numberOfColumns 2 - -columnAlign 1 "left" - -columnAlign 2 "left" - -columnAttach 1 "both" 0 - -columnAttach 2 "both" 0 - -columnOffset2 5 5 - -columnWidth 1 70 - -columnWidth 2 50 - ("SkelClipRangeEndLayout"+$numSkelClips); - - text - -parent ("SkelClipRangeEndLayout"+$numSkelClips) - -label "End Time:" - ("SkelClipRangeEndLabel"+$numSkelClips); - - floatField - -parent ("SkelClipRangeEndLayout"+$numSkelClips) - -value 0.000 - -width 50 - ("SkelClipRangeEnd"+$numSkelClips); - - columnLayout - -parent ("SkelClipRangeLayout"+$numSkelClips) - -columnAttach "left" 0 - ("SkelClipRangeUnitsLayout"+$numSkelClips); - - radioButtonGrp - -parent ("SkelClipRangeUnitsLayout"+$numSkelClips) - -numberOfRadioButtons 2 - -labelArray2 "Frames" "Seconds" - -cw 1 65 - -cw 2 65 - -select 1 - ("SkelClipRangeUnits"+$numSkelClips); - - separator - -parent ("SkelClipLayout"+$numSkelClips) - -style "in" - -width 309 - -height 5; - - rowLayout - -parent ("SkelClipLayout"+$numSkelClips) - -numberOfColumns 2 - -columnWidth 1 70 - -columnWidth 2 230 - -columnAlign 1 "left" - -columnAlign 2 "left" - -columnAttach 1 "both" 0 - -columnAttach 2 "both" 0 - -columnOffset2 5 5 - ("SkelClipRateTypeLayout"+$numSkelClips); - - text - -parent ("SkelClipRateTypeLayout"+$numSkelClips) - -label "Sample by:" - ("SkelClipRateTypeLabel"+$numSkelClips); - - radioButtonGrp - -parent ("SkelClipRateTypeLayout"+$numSkelClips) - -numberOfRadioButtons 2 - -labelArray2 "Frames" "Seconds" - -cw 1 65 - -cw 2 65 - -select 1 - -changeCommand "formatOgreExporterUI" - ("SkelClipRateType"+$numSkelClips); - - rowLayout - -parent ("SkelClipLayout"+$numSkelClips) - -numberOfColumns 2 - -columnWidth 1 125 - -columnWidth 2 80 - -columnAlign 1 "left" - -columnAlign 2 "left" - -columnAttach 1 "left" 75 - -columnAttach 2 "both" 15 - ("SkelClipRateLayout"+$numSkelClips); - - intField - -parent ("SkelClipRateLayout"+$numSkelClips) - -width 50 - -value 1.000 - ("SkelClipRateFrames"+$numSkelClips); - - floatField - -parent ("SkelClipRateLayout"+$numSkelClips) - -width 50 - -value 0.100 - ("SkelClipRateSeconds"+$numSkelClips); - formatOgreExporterUI(); -} - -global proc delOgreExporterSkeletonClip() -{ - global int $numSkelClips; - if ($numSkelClips > 1) - { - deleteUI("SkelClipFrame"+$numSkelClips); - $numSkelClips--; - } - formatOgreExporterUI(); -} - -global proc addOgreExporterBSClip() -{ - global int $numBSClips; - $numBSClips++; - - frameLayout - -parent BSClipsLayout - -width 309 - -label ("Clip"+$numBSClips) - ("BSClipFrame"+$numBSClips); - - columnLayout - -parent ("BSClipFrame"+$numBSClips) - -columnAttach "left" 0 - ("BSClipLayout"+$numBSClips); - - rowLayout - -parent ("BSClipLayout"+$numBSClips) - -numberOfColumns 2 - -columnWidth2 100 200 - -columnOffset2 5 5 - -columnAlign 1 "left" - -columnAlign 2 "left" - ("BSClipNameLayout"+$numBSClips); - - checkBox - -parent ("BSClipNameLayout"+$numBSClips) - -value false - -changeCommand "formatOgreExporterUI" - -label "Clip Name" - ("ExportBSClip"+$numBSClips); - - textField - -parent ("BSClipNameLayout"+$numBSClips) - -width 200 - -text ("clip"+$numBSClips) - ("BSClipName"+$numBSClips); - - separator - -parent ("BSClipLayout"+$numBSClips) - -style "in" - -width 309 - -height 5; - - rowLayout - -parent ("BSClipLayout"+$numBSClips) - -numberOfColumns 2 - -columnWidth2 100 200 - -columnAlign 1 "left" - -columnAlign 2 "left" - ("BSClipRangeTypeLayout"+$numBSClips); - - text - -parent ("BSClipRangeTypeLayout"+$numBSClips) - -label "Time Range:" - ("BSClipRangeLabel"+$numBSClips); - - radioButtonGrp - -parent ("BSClipRangeTypeLayout"+$numBSClips) - -numberOfRadioButtons 2 - -labelArray2 "Start/End" "Time Slider" - -cw 1 100 - -cw 2 100 - -select 2 - -changeCommand "formatOgreExporterUI" - ("BSClipRangeRadio"+$numBSClips); - - columnLayout - -parent ("BSClipLayout"+$numBSClips) - -columnAttach "left" 70 - ("BSClipRangeLayout"+$numBSClips); - - rowLayout - -parent ("BSClipRangeLayout"+$numBSClips) - -numberOfColumns 2 - -columnAlign 1 "left" - -columnAlign 2 "left" - -columnAttach 1 "both" 0 - -columnAttach 2 "both" 0 - -columnOffset2 5 5 - -columnWidth 1 70 - -columnWidth 2 50 - ("BSClipRangeStartLayout"+$numBSClips); - - text - -parent ("BSClipRangeStartLayout"+$numBSClips) - -label "Start Time:" - -width 50 - ("BSClipRangeStartLabel"+$numBSClips); - - floatField - -parent ("BSClipRangeStartLayout"+$numBSClips) - -width 50 - -value 0.000 - ("BSClipRangeStart"+$numBSClips); - - rowLayout - -parent ("BSClipRangeLayout"+$numBSClips) - -numberOfColumns 2 - -columnAlign 1 "left" - -columnAlign 2 "left" - -columnAttach 1 "both" 0 - -columnAttach 2 "both" 0 - -columnOffset2 5 5 - -columnWidth 1 70 - -columnWidth 2 50 - ("BSClipRangeEndLayout"+$numBSClips); - - text - -parent ("BSClipRangeEndLayout"+$numBSClips) - -label "End Time:" - ("BSClipRangeEndLabel"+$numBSClips); - - floatField - -parent ("BSClipRangeEndLayout"+$numBSClips) - -value 0.000 - -width 50 - ("BSClipRangeEnd"+$numBSClips); - - columnLayout - -parent ("BSClipRangeLayout"+$numBSClips) - -columnAttach "left" 0 - ("BSClipRangeUnitsLayout"+$numBSClips); - - radioButtonGrp - -parent ("BSClipRangeUnitsLayout"+$numBSClips) - -numberOfRadioButtons 2 - -labelArray2 "Frames" "Seconds" - -cw 1 65 - -cw 2 65 - -select 1 - ("BSClipRangeUnits"+$numBSClips); - - separator - -parent ("BSClipLayout"+$numBSClips) - -style "in" - -width 309 - -height 5; - - rowLayout - -parent ("BSClipLayout"+$numBSClips) - -numberOfColumns 2 - -columnWidth 1 70 - -columnWidth 2 230 - -columnAlign 1 "left" - -columnAlign 2 "left" - -columnAttach 1 "both" 0 - -columnAttach 2 "both" 0 - -columnOffset2 5 5 - ("BSClipRateTypeLayout"+$numBSClips); - - text - -parent ("BSClipRateTypeLayout"+$numBSClips) - -label "Sample by:" - ("BSClipRateTypeLabel"+$numBSClips); - - radioButtonGrp - -parent ("BSClipRateTypeLayout"+$numBSClips) - -numberOfRadioButtons 2 - -labelArray2 "Frames" "Seconds" - -cw 1 65 - -cw 2 65 - -select 1 - -changeCommand "formatOgreExporterUI" - ("BSClipRateType"+$numBSClips); - - rowLayout - -parent ("BSClipLayout"+$numBSClips) - -numberOfColumns 2 - -columnWidth 1 125 - -columnWidth 2 80 - -columnAlign 1 "left" - -columnAlign 2 "left" - -columnAttach 1 "left" 75 - -columnAttach 2 "both" 15 - ("BSClipRateLayout"+$numBSClips); - - intField - -parent ("BSClipRateLayout"+$numBSClips) - -width 50 - -value 1.000 - ("BSClipRateFrames"+$numBSClips); - - floatField - -parent ("BSClipRateLayout"+$numBSClips) - -width 50 - -value 0.100 - ("BSClipRateSeconds"+$numBSClips); - formatOgreExporterUI(); -} - -global proc delOgreExporterBSClip() -{ - global int $numBSClips; - if ($numBSClips > 1) - { - deleteUI("BSClipFrame"+$numBSClips); - $numBSClips--; - } - formatOgreExporterUI(); -} - -global proc addOgreExporterVertexClip() -{ - global int $numVertClips; - $numVertClips++; - - frameLayout - -parent VertexClipsLayout - -width 309 - -label ("Clip"+$numVertClips) - ("VertexClipFrame"+$numVertClips); - - columnLayout - -parent ("VertexClipFrame"+$numVertClips) - -columnAttach "left" 0 - ("VertexClipLayout"+$numVertClips); - - rowLayout - -parent ("VertexClipLayout"+$numVertClips) - -numberOfColumns 2 - -columnWidth2 100 200 - -columnOffset2 5 5 - -columnAlign 1 "left" - -columnAlign 2 "left" - ("VertexClipNameLayout"+$numVertClips); - - checkBox - -parent ("VertexClipNameLayout"+$numVertClips) - -value false - -changeCommand "formatOgreExporterUI" - -label "Clip Name" - ("ExportVertexClip"+$numVertClips); - - textField - -parent ("VertexClipNameLayout"+$numVertClips) - -width 200 - -text ("clip"+$numVertClips) - ("VertexClipName"+$numVertClips); - - separator - -parent ("VertexClipLayout"+$numVertClips) - -style "in" - -width 309 - -height 5; - - rowLayout - -parent ("VertexClipLayout"+$numVertClips) - -numberOfColumns 2 - -columnWidth2 100 200 - -columnAlign 1 "left" - -columnAlign 2 "left" - ("VertexClipRangeTypeLayout"+$numVertClips); - - text - -parent ("VertexClipRangeTypeLayout"+$numVertClips) - -label "Time Range:" - ("VertexClipRangeLabel"+$numVertClips); - - radioButtonGrp - -parent ("VertexClipRangeTypeLayout"+$numVertClips) - -numberOfRadioButtons 2 - -labelArray2 "Start/End" "Time Slider" - -cw 1 100 - -cw 2 100 - -select 2 - -changeCommand "formatOgreExporterUI" - ("VertexClipRangeRadio"+$numVertClips); - - columnLayout - -parent ("VertexClipLayout"+$numVertClips) - -columnAttach "left" 70 - ("VertexClipRangeLayout"+$numVertClips); - - rowLayout - -parent ("VertexClipRangeLayout"+$numVertClips) - -numberOfColumns 2 - -columnAlign 1 "left" - -columnAlign 2 "left" - -columnAttach 1 "both" 0 - -columnAttach 2 "both" 0 - -columnOffset2 5 5 - -columnWidth 1 70 - -columnWidth 2 50 - ("VertexClipRangeStartLayout"+$numVertClips); - - text - -parent ("VertexClipRangeStartLayout"+$numVertClips) - -label "Start Time:" - -width 50 - ("VertexClipRangeStartLabel"+$numVertClips); - - floatField - -parent ("VertexClipRangeStartLayout"+$numVertClips) - -width 50 - -value 0.000 - ("VertexClipRangeStart"+$numVertClips); - - rowLayout - -parent ("VertexClipRangeLayout"+$numVertClips) - -numberOfColumns 2 - -columnAlign 1 "left" - -columnAlign 2 "left" - -columnAttach 1 "both" 0 - -columnAttach 2 "both" 0 - -columnOffset2 5 5 - -columnWidth 1 70 - -columnWidth 2 50 - ("VertexClipRangeEndLayout"+$numVertClips); - - text - -parent ("VertexClipRangeEndLayout"+$numVertClips) - -label "End Time:" - ("VertexClipRangeEndLabel"+$numVertClips); - - floatField - -parent ("VertexClipRangeEndLayout"+$numVertClips) - -value 0.000 - -width 50 - ("VertexClipRangeEnd"+$numVertClips); - - columnLayout - -parent ("VertexClipRangeLayout"+$numVertClips) - -columnAttach "left" 0 - ("VertexClipRangeUnitsLayout"+$numVertClips); - - radioButtonGrp - -parent ("VertexClipRangeUnitsLayout"+$numVertClips) - -numberOfRadioButtons 2 - -labelArray2 "Frames" "Seconds" - -cw 1 65 - -cw 2 65 - -select 1 - ("VertexClipRangeUnits"+$numVertClips); - - separator - -parent ("VertexClipLayout"+$numVertClips) - -style "in" - -width 309 - -height 5; - - rowLayout - -parent ("VertexClipLayout"+$numVertClips) - -numberOfColumns 2 - -columnWidth 1 70 - -columnWidth 2 230 - -columnAlign 1 "left" - -columnAlign 2 "left" - -columnAttach 1 "both" 0 - -columnAttach 2 "both" 0 - -columnOffset2 5 5 - ("VertexClipRateTypeLayout"+$numVertClips); - - text - -parent ("VertexClipRateTypeLayout"+$numVertClips) - -label "Sample by:" - ("VertexClipRateTypeLabel"+$numVertClips); - - radioButtonGrp - -parent ("VertexClipRateTypeLayout"+$numVertClips) - -numberOfRadioButtons 2 - -labelArray2 "Frames" "Seconds" - -cw 1 65 - -cw 2 65 - -select 1 - -changeCommand "formatOgreExporterUI" - ("VertexClipRateType"+$numVertClips); - - rowLayout - -parent ("VertexClipLayout"+$numVertClips) - -numberOfColumns 2 - -columnWidth 1 125 - -columnWidth 2 80 - -columnAlign 1 "left" - -columnAlign 2 "left" - -columnAttach 1 "left" 75 - -columnAttach 2 "both" 15 - ("VertexClipRateLayout"+$numVertClips); - - intField - -parent ("VertexClipRateLayout"+$numVertClips) - -width 50 - -value 1.000 - ("VertexClipRateFrames"+$numVertClips); - - floatField - -parent ("VertexClipRateLayout"+$numVertClips) - -width 50 - -value 0.100 - ("VertexClipRateSeconds"+$numVertClips); - formatOgreExporterUI(); -} - -global proc delOgreExporterVertexClip() -{ - global int $numVertClips; - if ($numVertClips > 1) - { - deleteUI("VertexClipFrame"+$numVertClips); - $numVertClips--; - } - formatOgreExporterUI(); -} - - -global proc saveOgreExporterSettings() -{ - fileInfo "ogreExporter_savedSettings" "1"; - - // Common parameters - fileInfo "ogreExporter_outputDir" `textField -query -fileName OutputDirectory`; - fileInfo "ogreExporter_exportType" `radioCollection -q -select ExportTypeCollection`; - fileInfo "ogreExporter_coordsType" `radioCollection -q -select CoordsTypeCollection`; - fileInfo "ogreExporter_lengthUnit" `optionMenu -q -select UnitsMenu`; - fileInfo "ogreExporter_animationType" `optionMenu -q -select AnimationTypeMenu`; - fileInfo "ogreExporter_globalScale" `floatField -q -v GlobalScale`; - - // Mesh - fileInfo "ogreExporter_exportMesh" `checkBox -q -v ExportMesh`; - fileInfo "ogreExporter_useSharedGeom" `checkBox -q -v UseSharedGeometry`; - fileInfo "ogreExporter_exportVBA" `checkBox -q -v ExportVBA`; - fileInfo "ogreExporter_exportNormals" `checkBox -q -v ExportMeshNormals`; - fileInfo "ogreExporter_exportColours" `checkBox -q -v ExportMeshColours`; - fileInfo "ogreExporter_exportUVs" `checkBox -q -v ExportMeshUVs`; - fileInfo "ogreExporter_meshFilename" `textField -q -text ExportMeshFilename`; - fileInfo "ogreExporter_buildEdges" `checkBox -q -v BuildEdges`; - fileInfo "ogreExporter_buildTangents" `checkBox -q -v BuildTangents`; - fileInfo "ogreExporter_tangentSemantic" `radioCollection -q -select TangentSemanticCollection`; - fileInfo "ogreExporter_tangentSplitMirrored" `checkBox -q -select TangentsSplitMirrored`; - fileInfo "ogreExporter_tangentSplitRotated" `checkBox -q -select TangentsSplitRotated`; - fileInfo "ogreExporter_tangentUseParity" `checkBox -q -select TangentsUseParity`; - - // Materials - fileInfo "ogreExporter_exportMat" `checkBox -q -v ExportMaterial`; - fileInfo "ogreExporter_materialFile" `textField -q -text ExportMaterialFilename`; - fileInfo "ogreExporter_matPrefix" `textField -q -text ExportMaterialPrefix`; - fileInfo "ogreExporter_copyTextures" `checkBox -q -v CopyTextures`; - fileInfo "ogreExporter_lightingOff" `checkBox -q -v MatLightingOff`; - - // Skeleton - fileInfo "ogreExporter_exportSkel" `checkBox -q -v ExportSkeleton`; - fileInfo "ogreExporter_skelFilename" `textField -q -text ExportSkeletonFilename`; - - // Skeleton Animations - fileInfo "ogreExporter_exportSkelAnims" `checkBox -q -v ExportSkelAnims`; - fileInfo "ogreExporter_skelBB" `checkBox -q -v SkelBB`; - fileInfo "ogreExporter_neutralPoseType" `radioButtonGrp -q -select NeutralPoseRadio`; - global int $numSkelClips; - fileInfo "ogreExporter_numSkelClips" $numSkelClips; - int $i; - for ($i=1; $i<=$numSkelClips; $i++) - { - fileInfo ("ogreExporter_exportSkelClip"+$i) `checkBox -q -v ("ExportSkelClip"+$i)`; - fileInfo ("ogreExporter_skelClipName"+$i) `textField -q -text ("SkelClipName"+$i)`; - fileInfo ("ogreExporter_skelClipRangeType"+$i) `radioButtonGrp -q -select ("SkelClipRangeRadio"+$i)`; - fileInfo ("ogreExporter_skelClipStart"+$i) `floatField -q -v ("SkelClipRangeStart"+$i)`; - fileInfo ("ogreExporter_skelClipEnd"+$i) `floatField -q -v ("SkelClipRangeEnd"+$i)`; - fileInfo ("ogreExporter_skelClipRangeUnits"+$i) `radioButtonGrp -q -select ("SkelClipRangeUnits"+$i)`; - fileInfo ("ogreExporter_skelClipRateType"+$i) `radioButtonGrp -q -select ("SkelClipRateType"+$i)`; - fileInfo ("ogreExporter_skelClipRateFrames"+$i) `intField -q -v ("SkelClipRateFrames"+$i)`; - fileInfo ("ogreExporter_skelClipRangeSeconds"+$i) `floatField -q -v ("SkelClipRateSeconds"+$i)`; - } - - // Blend Shapes - fileInfo "ogreExporter_exportBlendShapes" `checkBox -q -v ExportBlendShapes`; - fileInfo "ogreExporter_bsBB" `checkBox -q -v BsBB`; - - // Blend Shape Animations - fileInfo "ogreExporter_exportBSAnims" `checkBox -q -v ExportBSAnims`; - global int $numBSClips; - fileInfo "ogreExporter_numBSClips" $numBSClips; - int $i; - for ($i=1; $i<=$numBSClips; $i++) - { - fileInfo ("ogreExporter_exportBSClip"+$i) `checkBox -q -v ("ExportBSClip"+$i)`; - fileInfo ("ogreExporter_BSClipName"+$i) `textField -q -text ("BSClipName"+$i)`; - fileInfo ("ogreExporter_BSClipRangeType"+$i) `radioButtonGrp -q -select ("BSClipRangeRadio"+$i)`; - fileInfo ("ogreExporter_BSClipStart"+$i) `floatField -q -v ("BSClipRangeStart"+$i)`; - fileInfo ("ogreExporter_BSClipEnd"+$i) `floatField -q -v ("BSClipRangeEnd"+$i)`; - fileInfo ("ogreExporter_BSClipRangeUnits"+$i) `radioButtonGrp -q -select ("BSClipRangeUnits"+$i)`; - fileInfo ("ogreExporter_BSClipRateType"+$i) `radioButtonGrp -q -select ("BSClipRateType"+$i)`; - fileInfo ("ogreExporter_BSClipRateFrames"+$i) `intField -q -v ("BSClipRateFrames"+$i)`; - fileInfo ("ogreExporter_BSClipRangeSeconds"+$i) `floatField -q -v ("BSClipRateSeconds"+$i)`; - } - - // Vertex Animations - fileInfo "ogreExporter_exportVertexAnims" `checkBox -q -v ExportVertexAnims`; - fileInfo "ogreExporter_vertBB" `checkBox -q -v VertBB`; - global int $numVertClips; - fileInfo "ogreExporter_numVertClips" $numVertClips; - int $i; - for ($i=1; $i<=$numVertClips; $i++) - { - fileInfo ("ogreExporter_exportVertexClip"+$i) `checkBox -q -v ("ExportVertexClip"+$i)`; - fileInfo ("ogreExporter_vertexClipName"+$i) `textField -q -text ("VertexClipName"+$i)`; - fileInfo ("ogreExporter_vertexClipRangeType"+$i) `radioButtonGrp -q -select ("VertexClipRangeRadio"+$i)`; - fileInfo ("ogreExporter_vertexClipStart"+$i) `floatField -q -v ("VertexClipRangeStart"+$i)`; - fileInfo ("ogreExporter_vertexClipEnd"+$i) `floatField -q -v ("VertexClipRangeEnd"+$i)`; - fileInfo ("ogreExporter_vertexClipRangeUnits"+$i) `radioButtonGrp -q -select ("VertexClipRangeUnits"+$i)`; - fileInfo ("ogreExporter_vertexClipRateType"+$i) `radioButtonGrp -q -select ("VertexClipRateType"+$i)`; - fileInfo ("ogreExporter_vertexClipRateFrames"+$i) `intField -q -v ("VertexClipRateFrames"+$i)`; - fileInfo ("ogreExporter_vertexClipRangeSeconds"+$i) `floatField -q -v ("VertexClipRateSeconds"+$i)`; - } - - // Anim Curves - fileInfo "ogreExporter_exportAnimCurves" `checkBox -q -v ExportAnimCurves`; - fileInfo "ogreExporter_animCurvesFilename" `textField -q -text ExportAnimCurvesFilename`; - - // Cameras - fileInfo "ogreExporter_exportCameras" `checkBox -q -v ExportCameras`; - fileInfo "ogreExporter_exportCamerasAnim" `checkBox -q -v ExportCamerasAnim`; - fileInfo "ogreExporter_camerasFilename" `textField -q -text ExportCamerasFilename`; - - // Particles - fileInfo "ogreExporter_exportParticles" `checkBox -q -v ExportParticles`; - fileInfo "ogreExporter_particlesFilename" `textField -q -text ExportParticlesFilename`; -} - -global proc loadOgreExporterSettings() -{ - string $valStrings[]; - int $valInt; - float $valFloat; - $valStrings = `fileInfo -q "ogreExporter_savedSettings"`; - if (`gmatch $valStrings[0] "1"`) - { - // Common parameters - textField -edit -fileName `fileInfo -q "ogreExporter_outputDir"` OutputDirectory; - radioCollection -edit -select `fileInfo -q "ogreExporter_exportType"` ExportTypeCollection; - radioCollection -edit -select `fileInfo -q "ogreExporter_coordsType"` CoordsTypeCollection; - $valStrings = `fileInfo -q "ogreExporter_lengthUnit"`; - string $lengthUnitSel = $valStrings[0]; - if (`gmatch $lengthUnitSel "1"`) - optionMenu -edit -select 1 UnitsMenu; - else if (`gmatch $lengthUnitSel "2"`) - optionMenu -edit -select 2 UnitsMenu; - else if (`gmatch $lengthUnitSel "3"`) - optionMenu -edit -select 3 UnitsMenu; - else if (`gmatch $lengthUnitSel "4"`) - optionMenu -edit -select 4 UnitsMenu; - else if (`gmatch $lengthUnitSel "5"`) - optionMenu -edit -select 5 UnitsMenu; - else if (`gmatch $lengthUnitSel "6"`) - optionMenu -edit -select 6 UnitsMenu; - else if (`gmatch $lengthUnitSel "7"`) - optionMenu -edit -select 7 UnitsMenu; - $valStrings = `fileInfo -q "ogreExporter_animationType"`; - string $animType = $valStrings[0]; - if (`gmatch $animType "1"`) - optionMenu -edit -select 1 AnimationTypeMenu; - else - optionMenu -edit -select 2 AnimationTypeMenu; - $valStrings = `fileInfo -q "ogreExporter_globalScale"`; - $valFloat = $valStrings[0]; - floatField -edit -v $valFloat GlobalScale; - - // Mesh - $valStrings = `fileInfo -q "ogreExporter_exportMesh"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` ExportMesh; - $valStrings = `fileInfo -q "ogreExporter_useSharedGeom"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` UseSharedGeometry; - $valStrings = `fileInfo -q "ogreExporter_exportVBA"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` ExportVBA; - $valStrings = `fileInfo -q "ogreExporter_exportNormals"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` ExportMeshNormals; - $valStrings = `fileInfo -q "ogreExporter_exportColours"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` ExportMeshColours; - $valStrings = `fileInfo -q "ogreExporter_exportUVs"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` ExportMeshUVs; - textField -edit -text `fileInfo -q "ogreExporter_meshFilename"` ExportMeshFilename; - $valStrings = `fileInfo -q "ogreExporter_buildEdges"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` BuildEdges; - $valStrings = `fileInfo -q "ogreExporter_buildTangents"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` BuildTangents; - radioCollection -edit -select `fileInfo -q "ogreExporter_tangentSemantic"` TangentSemanticCollection; - checkBox -edit -v `gmatch $valStrings[0] "1"` TangentsSplitMirrored; - checkBox -edit -v `gmatch $valStrings[0] "1"` TangentsSplitRotated; - checkBox -edit -v `gmatch $valStrings[0] "1"` TangentsUseParity; - - // Materials - $valStrings = `fileInfo -q "ogreExporter_exportMat"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` ExportMaterial; - textField -edit -text `fileInfo -q "ogreExporter_materialFile"` ExportMaterialFilename; - textField -edit -text `fileInfo -q "ogreExporter_matPrefix"` ExportMaterialPrefix; - $valStrings = `fileInfo -q "ogreExporter_copyTextures"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` CopyTextures; - $valStrings = `fileInfo -q "ogreExporter_lightingOff"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` MatLightingOff; - - // Skeleton - $valStrings = `fileInfo -q "ogreExporter_exportSkel"` ; - checkBox -edit -v `gmatch $valStrings[0] "1"` ExportSkeleton; - textField -edit -text `fileInfo -q "ogreExporter_skelFilename"` ExportSkeletonFilename; - - // Skeleton Animations - $valStrings = `fileInfo -q "ogreExporter_exportSkelAnims"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` ExportSkelAnims; - $valStrings = `fileInfo -q "ogreExporter_skelBB"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` SkelBB; - $valStrings = `fileInfo -q "ogreExporter_neutralPoseType"`; - $valInt = $valStrings[0]; - radioButtonGrp -edit -select $valInt NeutralPoseRadio; - $valStrings = `fileInfo -q "ogreExporter_numSkelClips"`; - int $n = $valStrings[0]; - $valInt = $valStrings[0]; - global int $numSkelClips; - for (;$numSkelClips>1;delOgreExporterSkeletonClip()); - int $i; - for ($i=1; $i<=$n; $i++) - { - if ($i > 1) - addOgreExporterSkeletonClip(); - $valStrings = `fileInfo -q ("ogreExporter_exportSkelClip"+$i)`; - checkBox -edit -v `gmatch $valStrings[0] "1"` ("ExportSkelClip"+$i); - textField -edit -text `fileInfo -q ("ogreExporter_skelClipName"+$i)` ("SkelClipName"+$i); - $valStrings = `fileInfo -q ("ogreExporter_skelClipRangeType"+$i)`; - $valInt = $valStrings[0]; - radioButtonGrp -edit -select $valInt ("SkelClipRangeRadio"+$i); - $valStrings = `fileInfo -q ("ogreExporter_skelClipStart"+$i)`; - $valFloat = $valStrings[0]; - floatField -edit -v $valFloat ("SkelClipRangeStart"+$i); - $valStrings = `fileInfo -q ("ogreExporter_skelClipEnd"+$i)`; - $valFloat = $valStrings[0]; - floatField -edit -v $valFloat ("SkelClipRangeEnd"+$i); - $valStrings = `fileInfo -q ("ogreExporter_skelClipRangeUnits"+$i)`; - $valInt = $valStrings[0]; - radioButtonGrp -edit -select $valInt ("SkelClipRangeUnits"+$i); - $valStrings = `fileInfo -q ("ogreExporter_skelClipRateType"+$i)`; - $valInt = $valStrings[0]; - radioButtonGrp -edit -select $valInt ("SkelClipRateType"+$i); - $valStrings = `fileInfo -q ("ogreExporter_skelClipRateFrames"+$i)`; - $valInt = $valStrings[0]; - intField -edit -v $valInt ("SkelClipRateFrames"+$i); - $valStrings = `fileInfo -q ("ogreExporter_skelClipRateSeconds"+$i)`; - $valFloat = $valStrings[0]; - floatField -edit -v $valFloat ("SkelClipRateSeconds"+$i); - } - - // Blend Shapes - $valStrings = `fileInfo -q "ogreExporter_exportBlendShapes"` ; - checkBox -edit -v `gmatch $valStrings[0] "1"` ExportBlendShapes; - $valStrings = `fileInfo -q "ogreExporter_bsBB"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` BsBB; - - // Blend Shape Animations - $valStrings = `fileInfo -q "ogreExporter_exportBSAnims"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` ExportBSAnims; - $valStrings = `fileInfo -q "ogreExporter_numBSClips"`; - int $n = $valStrings[0]; - $valInt = $valStrings[0]; - global int $numBSClips; - for (;$numBSClips>1;delOgreExporterBSClip()); - int $i; - for ($i=1; $i<=$n; $i++) - { - if ($i > 1) - addOgreExporterBSClip(); - $valStrings = `fileInfo -q ("ogreExporter_exportBSClip"+$i)`; - checkBox -edit -v `gmatch $valStrings[0] "1"` ("ExportBSClip"+$i); - textField -edit -text `fileInfo -q ("ogreExporter_BSClipName"+$i)` ("BSClipName"+$i); - $valStrings = `fileInfo -q ("ogreExporter_BSClipRangeType"+$i)`; - $valInt = $valStrings[0]; - radioButtonGrp -edit -select $valInt ("BSClipRangeRadio"+$i); - $valStrings = `fileInfo -q ("ogreExporter_BSClipStart"+$i)`; - $valFloat = $valStrings[0]; - floatField -edit -v $valFloat ("BSClipRangeStart"+$i); - $valStrings = `fileInfo -q ("ogreExporter_BSClipEnd"+$i)`; - $valFloat = $valStrings[0]; - floatField -edit -v $valFloat ("BSClipRangeEnd"+$i); - $valStrings = `fileInfo -q ("ogreExporter_BSClipRangeUnits"+$i)`; - $valInt = $valStrings[0]; - radioButtonGrp -edit -select $valInt ("BSClipRangeUnits"+$i); - $valStrings = `fileInfo -q ("ogreExporter_BSClipRateType"+$i)`; - $valInt = $valStrings[0]; - radioButtonGrp -edit -select $valInt ("BSClipRateType"+$i); - $valStrings = `fileInfo -q ("ogreExporter_BSClipRateFrames"+$i)`; - $valInt = $valStrings[0]; - intField -edit -v $valInt ("BSClipRateFrames"+$i); - $valStrings = `fileInfo -q ("ogreExporter_BSClipRateSeconds"+$i)`; - $valFloat = $valStrings[0]; - floatField -edit -v $valFloat ("BSClipRateSeconds"+$i); - } - - // Vertex Animations - $valStrings = `fileInfo -q "ogreExporter_exportVertexAnims"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` ExportVertexAnims; - $valStrings = `fileInfo -q "ogreExporter_vertBB"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` VertBB; - $valStrings = `fileInfo -q "ogreExporter_numVertClips"`; - int $n = $valStrings[0]; - $valInt = $valStrings[0]; - global int $numVertClips; - for (;$numVertClips>1;delOgreExporterVertexClip()); - int $i; - for ($i=1; $i<=$n; $i++) - { - if ($i > 1) - addOgreExporterVertexClip(); - $valStrings = `fileInfo -q ("ogreExporter_exportVertexClip"+$i)`; - checkBox -edit -v `gmatch $valStrings[0] "1"` ("ExportVertexClip"+$i); - textField -edit -text `fileInfo -q ("ogreExporter_vertexSkelClipName"+$i)` ("VertexClipName"+$i); - $valStrings = `fileInfo -q ("ogreExporter_vertexClipRangeType"+$i)`; - $valInt = $valStrings[0]; - radioButtonGrp -edit -select $valInt ("VertexClipRangeRadio"+$i); - $valStrings = `fileInfo -q ("ogreExporter_vertexClipStart"+$i)`; - $valFloat = $valStrings[0]; - floatField -edit -v $valFloat ("VertexClipRangeStart"+$i); - $valStrings = `fileInfo -q ("ogreExporter_vertexClipEnd"+$i)`; - $valFloat = $valStrings[0]; - floatField -edit -v $valFloat ("VertexClipRangeEnd"+$i); - $valStrings = `fileInfo -q ("ogreExporter_vertexClipRangeUnits"+$i)`; - $valInt = $valStrings[0]; - radioButtonGrp -edit -select $valInt ("VertexClipRangeUnits"+$i); - $valStrings = `fileInfo -q ("ogreExporter_vertexClipRateType"+$i)`; - $valInt = $valStrings[0]; - radioButtonGrp -edit -select $valInt ("VertexClipRateType"+$i); - $valStrings = `fileInfo -q ("ogreExporter_vertexClipRateFrames"+$i)`; - $valInt = $valStrings[0]; - intField -edit -v $valInt ("VertexClipRateFrames"+$i); - $valStrings = `fileInfo -q ("ogreExporter_vertexClipRateSeconds"+$i)`; - $valFloat = $valStrings[0]; - floatField -edit -v $valFloat ("VertexClipRateSeconds"+$i); - } - - // Anim Curves - $valStrings = `fileInfo -q "ogreExporter_exportAnimCurves"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` ExportAnimCurves; - textField -edit -text `fileInfo -q "ogreExporter_animCurvesFilename"` ExportAnimCurvesFilename; - - // Cameras - $valStrings = `fileInfo -q "ogreExporter_exportCameras"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` ExportCameras; - $valStrings = `fileInfo -q "ogreExporter_exportCamerasAnim"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` ExportCamerasAnim; - textField -edit -text `fileInfo -q "ogreExporter_camerasFilename"` ExportCamerasFilename; - - // Particles - $valStrings = `fileInfo -q "ogreExporter_exportParticles"`; - checkBox -edit -v `gmatch $valStrings[0] "1"` ExportParticles; - textField -edit -text `fileInfo -q "ogreExporter_particlesFilename"` ExportParticlesFilename; - - formatOgreExporterUI(); - } - else - defaultOgreExporterSettings(); -} - -global proc defaultOgreExporterSettings() -{ - // Common parameters - textField -edit -fileName "" OutputDirectory; - radioCollection -edit -select "RadioButtonAll" ExportTypeCollection; - radioCollection -edit -select "RadioButtonWorld" CoordsTypeCollection; - optionMenu -edit -select 1 UnitsMenu; - optionMenu -edit -select 1 AnimationTypeMenu; - floatField -edit -v 1 GlobalScale; - - // Mesh - checkBox -edit -v 0 ExportMesh; - checkBox -edit -v 1 UseSharedGeometry; - checkBox -edit -v 1 ExportVBA; - checkBox -edit -v 1 ExportMeshNormals; - checkBox -edit -v 0 ExportMeshColours; - checkBox -edit -v 1 ExportMeshUVs; - textField -edit -text "" ExportMeshFilename; - checkBox -edit -v 0 BuildEdges; - checkBox -edit -v 0 BuildTangents; - radioCollection -edit -select "TangentSemanticTangent" TangentSemanticCollection; - checkBox -edit -v 0 TangentsSplitMirrored; - checkBox -edit -v 0 TangentsSplitRotated; - checkBox -edit -v 0 TangentsUseParity; - - // Materials - checkBox -edit -v 0 ExportMaterial; - textField -edit -text "" ExportMaterialFilename; - textField -edit -text "" ExportMaterialPrefix; - checkBox -edit -v 0 CopyTextures; - checkBox -edit -v 0 MatLightingOff; - - // Skeleton - checkBox -edit -v 0 ExportSkeleton; - textField -edit -text "" ExportSkeletonFilename; - - // Skeleton Animations - checkBox -edit -v 0 ExportSkelAnims; - checkBox -edit -v 0 SkelBB; - radioButtonGrp -edit -select 1 NeutralPoseRadio; - global int $numSkelClips; - for (;$numSkelClips>1;delOgreExporterSkeletonClip()); - checkBox -edit -v 0 ExportSkelClip1; - textField -edit -text "clip1" SkelClipName1; - radioButtonGrp -edit -select 1 SkelClipRangeRadio1; - floatField -edit -v 0 SkelClipRangeStart1; - floatField -edit -v 0 SkelClipRangeEnd1; - radioButtonGrp -edit -select 1 SkelClipRangeUnits1; - radioButtonGrp -edit -select 1 SkelClipRateType1; - intField -edit -v 1 SkelClipRateFrames1; - floatField -edit -v 0.1 SkelClipRateSeconds1; - - // Blend Shapes - checkBox -edit -v 0 ExportBlendShapes; - checkBox -edit -v 0 BsBB; - - // Blend Shape Animations - checkBox -edit -v 0 ExportBSAnims; - global int $numBSClips; - for (;$numBSClips>1;delOgreExporterBSClip()); - checkBox -edit -v 0 ExportBSClip1; - textField -edit -text "clip1" BSClipName1; - radioButtonGrp -edit -select 1 BSClipRangeRadio1; - floatField -edit -v 0 BSClipRangeStart1; - floatField -edit -v 0 BSClipRangeEnd1; - radioButtonGrp -edit -select 1 BSClipRangeUnits1; - radioButtonGrp -edit -select 1 BSClipRateType1; - intField -edit -v 1 BSClipRateFrames1; - floatField -edit -v 0.1 BSClipRateSeconds1; - - // Vertex Animation - checkBox -edit -v 0 ExportVertexAnims; - checkBox -edit -v 0 VertBB; - global int $numVertClips; - for (;$numVertClips>1;delOgreExporterVertexClip()); - checkBox -edit -v 0 ExportSkelClip1; - textField -edit -text "clip1" VertexClipName1; - radioButtonGrp -edit -select 1 VertexClipRangeRadio1; - floatField -edit -v 0 VertexClipRangeStart1; - floatField -edit -v 0 VertexClipRangeEnd1; - radioButtonGrp -edit -select 1 VertexClipRangeUnits1; - radioButtonGrp -edit -select 1 VertexClipRateType1; - intField -edit -v 1 VertexClipRateFrames1; - floatField -edit -v 0.1 VertexClipRateSeconds1; - - // Anim Curves - checkBox -edit -v 0 ExportAnimCurves; - textField -edit -text "" ExportAnimCurvesFilename; - - // Cameras - checkBox -edit -v 0 ExportCameras; - checkBox -edit -v 0 ExportCamerasAnim; - textField -edit -text `fileInfo -q "ogreExporter_camerasFilename"` ExportCamerasFilename; - - // Particles - checkBox -edit -v 0 ExportParticles; - textField -edit -text "" ExportParticlesFilename; - - // Initialize filenames - string $sceneFile = `file -query -sceneName`; - string $sceneDir = dirname($sceneFile); - string $baseFile = basename($sceneFile, ".mb"); - textField -edit -fileName $sceneDir SceneDirectory; - - // --- Mesh File - string $meshFile = $baseFile + ".mesh"; - textField -edit -fileName $meshFile ExportMeshFilename; - - // --- Material File - string $matFile = $baseFile + ".material"; - textField -edit -fileName $matFile ExportMaterialFilename; - - // --- Skeleton File - string $skelFile = $baseFile + ".skeleton"; - textField -edit -fileName $skelFile ExportSkeletonFilename; - - // --- Camera File - string $camFile = $baseFile + ".camera"; - textField -edit -fileName $camFile ExportCamerasFilename; - - // --- Anim Curves File - string $animFile = $baseFile + ".anim"; - textField -edit -fileName $animFile ExportAnimCurvesFilename; - - // --- Particles File - string $particlesFile = $baseFile + ".particles.xml"; - textField -edit -fileName $particlesFile ExportParticlesFilename; - - formatOgreExporterUI(); -} - diff --git a/Tools/MayaExport/mel/userSetup.mel b/Tools/MayaExport/mel/userSetup.mel deleted file mode 100644 index 111257e254d..00000000000 --- a/Tools/MayaExport/mel/userSetup.mel +++ /dev/null @@ -1 +0,0 @@ -source ogreExporter; diff --git a/Tools/MayaExport/scripts/MayaExport.xcodeproj/project.pbxproj b/Tools/MayaExport/scripts/MayaExport.xcodeproj/project.pbxproj deleted file mode 100644 index 3a68e5d7c2b..00000000000 --- a/Tools/MayaExport/scripts/MayaExport.xcodeproj/project.pbxproj +++ /dev/null @@ -1,438 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 42; - objects = { - -/* Begin PBXBuildFile section */ - 012D5E370B632F7C00BAAF45 /* _singleton.h in Headers */ = {isa = PBXBuildFile; fileRef = 012D5E2A0B632F7C00BAAF45 /* _singleton.h */; }; - 012D5E380B632F7C00BAAF45 /* animation.h in Headers */ = {isa = PBXBuildFile; fileRef = 012D5E2B0B632F7C00BAAF45 /* animation.h */; }; - 012D5E390B632F7C00BAAF45 /* blendshape.h in Headers */ = {isa = PBXBuildFile; fileRef = 012D5E2C0B632F7C00BAAF45 /* blendshape.h */; }; - 012D5E3A0B632F7C00BAAF45 /* material.h in Headers */ = {isa = PBXBuildFile; fileRef = 012D5E2D0B632F7C00BAAF45 /* material.h */; }; - 012D5E3B0B632F7C00BAAF45 /* materialSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 012D5E2E0B632F7C00BAAF45 /* materialSet.h */; }; - 012D5E3C0B632F7C00BAAF45 /* mayaExportLayer.h in Headers */ = {isa = PBXBuildFile; fileRef = 012D5E2F0B632F7C00BAAF45 /* mayaExportLayer.h */; }; - 012D5E3D0B632F7C00BAAF45 /* mesh.h in Headers */ = {isa = PBXBuildFile; fileRef = 012D5E300B632F7C00BAAF45 /* mesh.h */; }; - 012D5E3E0B632F7C00BAAF45 /* ogreExporter.h in Headers */ = {isa = PBXBuildFile; fileRef = 012D5E310B632F7C00BAAF45 /* ogreExporter.h */; }; - 012D5E3F0B632F7C00BAAF45 /* paramlist.h in Headers */ = {isa = PBXBuildFile; fileRef = 012D5E320B632F7C00BAAF45 /* paramlist.h */; }; - 012D5E400B632F7C00BAAF45 /* particles.h in Headers */ = {isa = PBXBuildFile; fileRef = 012D5E330B632F7C00BAAF45 /* particles.h */; }; - 012D5E410B632F7C00BAAF45 /* skeleton.h in Headers */ = {isa = PBXBuildFile; fileRef = 012D5E340B632F7C00BAAF45 /* skeleton.h */; }; - 012D5E420B632F7C00BAAF45 /* submesh.h in Headers */ = {isa = PBXBuildFile; fileRef = 012D5E350B632F7C00BAAF45 /* submesh.h */; }; - 012D5E430B632F7C00BAAF45 /* vertex.h in Headers */ = {isa = PBXBuildFile; fileRef = 012D5E360B632F7C00BAAF45 /* vertex.h */; }; - 012D5E4C0B632F9E00BAAF45 /* blendshape.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 012D5E440B632F9E00BAAF45 /* blendshape.cpp */; }; - 012D5E4D0B632F9E00BAAF45 /* material.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 012D5E450B632F9E00BAAF45 /* material.cpp */; }; - 012D5E4E0B632F9E00BAAF45 /* mesh.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 012D5E460B632F9E00BAAF45 /* mesh.cpp */; }; - 012D5E4F0B632F9E00BAAF45 /* ogreExporter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 012D5E470B632F9E00BAAF45 /* ogreExporter.cpp */; }; - 012D5E500B632F9E00BAAF45 /* paramlist.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 012D5E480B632F9E00BAAF45 /* paramlist.cpp */; }; - 012D5E510B632F9E00BAAF45 /* particles.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 012D5E490B632F9E00BAAF45 /* particles.cpp */; }; - 012D5E520B632F9E00BAAF45 /* skeleton.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 012D5E4A0B632F9E00BAAF45 /* skeleton.cpp */; }; - 012D5E530B632F9E00BAAF45 /* submesh.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 012D5E4B0B632F9E00BAAF45 /* submesh.cpp */; }; - 012D5F4C0B6336A400BAAF45 /* materialSet.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 012D5F4B0B6336A400BAAF45 /* materialSet.cpp */; }; - 012D5F890B6337C200BAAF45 /* Ogre.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 012D5F880B6337C200BAAF45 /* Ogre.framework */; }; - 012D606B0B63384500BAAF45 /* libOpenMayaRender.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 012D606A0B63384500BAAF45 /* libOpenMayaRender.dylib */; }; -/* End PBXBuildFile section */ - -/* Begin PBXFileReference section */ - 012D5E2A0B632F7C00BAAF45 /* _singleton.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = _singleton.h; path = ../include/_singleton.h; sourceTree = SOURCE_ROOT; }; - 012D5E2B0B632F7C00BAAF45 /* animation.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = animation.h; path = ../include/animation.h; sourceTree = SOURCE_ROOT; }; - 012D5E2C0B632F7C00BAAF45 /* blendshape.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = blendshape.h; path = ../include/blendshape.h; sourceTree = SOURCE_ROOT; }; - 012D5E2D0B632F7C00BAAF45 /* material.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = material.h; path = ../include/material.h; sourceTree = SOURCE_ROOT; }; - 012D5E2E0B632F7C00BAAF45 /* materialSet.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = materialSet.h; path = ../include/materialSet.h; sourceTree = SOURCE_ROOT; }; - 012D5E2F0B632F7C00BAAF45 /* mayaExportLayer.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = mayaExportLayer.h; path = ../include/mayaExportLayer.h; sourceTree = SOURCE_ROOT; }; - 012D5E300B632F7C00BAAF45 /* mesh.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = mesh.h; path = ../include/mesh.h; sourceTree = SOURCE_ROOT; }; - 012D5E310B632F7C00BAAF45 /* ogreExporter.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = ogreExporter.h; path = ../include/ogreExporter.h; sourceTree = SOURCE_ROOT; }; - 012D5E320B632F7C00BAAF45 /* paramlist.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = paramlist.h; path = ../include/paramlist.h; sourceTree = SOURCE_ROOT; }; - 012D5E330B632F7C00BAAF45 /* particles.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = particles.h; path = ../include/particles.h; sourceTree = SOURCE_ROOT; }; - 012D5E340B632F7C00BAAF45 /* skeleton.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = skeleton.h; path = ../include/skeleton.h; sourceTree = SOURCE_ROOT; }; - 012D5E350B632F7C00BAAF45 /* submesh.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = submesh.h; path = ../include/submesh.h; sourceTree = SOURCE_ROOT; }; - 012D5E360B632F7C00BAAF45 /* vertex.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = vertex.h; path = ../include/vertex.h; sourceTree = SOURCE_ROOT; }; - 012D5E440B632F9E00BAAF45 /* blendshape.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = blendshape.cpp; path = ../src/blendshape.cpp; sourceTree = SOURCE_ROOT; }; - 012D5E450B632F9E00BAAF45 /* material.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = material.cpp; path = ../src/material.cpp; sourceTree = SOURCE_ROOT; }; - 012D5E460B632F9E00BAAF45 /* mesh.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = mesh.cpp; path = ../src/mesh.cpp; sourceTree = SOURCE_ROOT; }; - 012D5E470B632F9E00BAAF45 /* ogreExporter.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = ogreExporter.cpp; path = ../src/ogreExporter.cpp; sourceTree = SOURCE_ROOT; }; - 012D5E480B632F9E00BAAF45 /* paramlist.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = paramlist.cpp; path = ../src/paramlist.cpp; sourceTree = SOURCE_ROOT; }; - 012D5E490B632F9E00BAAF45 /* particles.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = particles.cpp; path = ../src/particles.cpp; sourceTree = SOURCE_ROOT; }; - 012D5E4A0B632F9E00BAAF45 /* skeleton.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = skeleton.cpp; path = ../src/skeleton.cpp; sourceTree = SOURCE_ROOT; }; - 012D5E4B0B632F9E00BAAF45 /* submesh.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = submesh.cpp; path = ../src/submesh.cpp; sourceTree = SOURCE_ROOT; }; - 012D5F4B0B6336A400BAAF45 /* materialSet.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = materialSet.cpp; path = ../src/materialSet.cpp; sourceTree = SOURCE_ROOT; }; - 012D5F880B6337C200BAAF45 /* Ogre.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Ogre.framework; path = /Library/Frameworks/Ogre.framework; sourceTree = ""; }; - 012D606A0B63384500BAAF45 /* libOpenMayaRender.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libOpenMayaRender.dylib; path = /Applications/Autodesk/maya8.5/Maya.app/Contents/MacOS/libOpenMayaRender.dylib; sourceTree = ""; }; - 012D60700B63387100BAAF45 /* ogreExporter.mel */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = ogreExporter.mel; path = ../mel/ogreExporter.mel; sourceTree = SOURCE_ROOT; }; - 012D60710B63387100BAAF45 /* userSetup.mel */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = userSetup.mel; path = ../mel/userSetup.mel; sourceTree = SOURCE_ROOT; }; - D2AAC0630554660B00DB518D /* ogreExporter.bundle */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; path = ogreExporter.bundle; sourceTree = BUILT_PRODUCTS_DIR; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - D289988505E68E00004EDB86 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 012D5F890B6337C200BAAF45 /* Ogre.framework in Frameworks */, - 012D606B0B63384500BAAF45 /* libOpenMayaRender.dylib in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 012D5F870B63377200BAAF45 /* External Frameworks and Libraries */ = { - isa = PBXGroup; - children = ( - 012D5F880B6337C200BAAF45 /* Ogre.framework */, - ); - name = "External Frameworks and Libraries"; - sourceTree = ""; - }; - 08FB7794FE84155DC02AAC07 /* exportJointClusterDataCmdPlugin */ = { - isa = PBXGroup; - children = ( - 012D5F870B63377200BAAF45 /* External Frameworks and Libraries */, - 08FB7795FE84155DC02AAC07 /* Source */, - 8A7F063208688F460064D097 /* Mel */, - 8A7F063308688F580064D097 /* Resources */, - 1AB674ADFE9D54B511CA2CBB /* Products */, - ); - name = exportJointClusterDataCmdPlugin; - sourceTree = ""; - }; - 08FB7795FE84155DC02AAC07 /* Source */ = { - isa = PBXGroup; - children = ( - 012D5F4B0B6336A400BAAF45 /* materialSet.cpp */, - 012D5E440B632F9E00BAAF45 /* blendshape.cpp */, - 012D5E450B632F9E00BAAF45 /* material.cpp */, - 012D5E460B632F9E00BAAF45 /* mesh.cpp */, - 012D5E470B632F9E00BAAF45 /* ogreExporter.cpp */, - 012D5E480B632F9E00BAAF45 /* paramlist.cpp */, - 012D5E490B632F9E00BAAF45 /* particles.cpp */, - 012D5E4A0B632F9E00BAAF45 /* skeleton.cpp */, - 012D5E4B0B632F9E00BAAF45 /* submesh.cpp */, - 012D5E2A0B632F7C00BAAF45 /* _singleton.h */, - 012D5E2B0B632F7C00BAAF45 /* animation.h */, - 012D5E2C0B632F7C00BAAF45 /* blendshape.h */, - 012D5E2D0B632F7C00BAAF45 /* material.h */, - 012D5E2E0B632F7C00BAAF45 /* materialSet.h */, - 012D5E2F0B632F7C00BAAF45 /* mayaExportLayer.h */, - 012D5E300B632F7C00BAAF45 /* mesh.h */, - 012D5E310B632F7C00BAAF45 /* ogreExporter.h */, - 012D5E320B632F7C00BAAF45 /* paramlist.h */, - 012D5E330B632F7C00BAAF45 /* particles.h */, - 012D5E340B632F7C00BAAF45 /* skeleton.h */, - 012D5E350B632F7C00BAAF45 /* submesh.h */, - 012D5E360B632F7C00BAAF45 /* vertex.h */, - ); - name = Source; - sourceTree = ""; - }; - 1AB674ADFE9D54B511CA2CBB /* Products */ = { - isa = PBXGroup; - children = ( - 012D606A0B63384500BAAF45 /* libOpenMayaRender.dylib */, - D2AAC0630554660B00DB518D /* ogreExporter.bundle */, - ); - name = Products; - sourceTree = ""; - }; - 8A7F063208688F460064D097 /* Mel */ = { - isa = PBXGroup; - children = ( - 012D60700B63387100BAAF45 /* ogreExporter.mel */, - 012D60710B63387100BAAF45 /* userSetup.mel */, - ); - name = Mel; - sourceTree = ""; - }; - 8A7F063308688F580064D097 /* Resources */ = { - isa = PBXGroup; - children = ( - ); - name = Resources; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXHeadersBuildPhase section */ - D2AAC0600554660B00DB518D /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 012D5E370B632F7C00BAAF45 /* _singleton.h in Headers */, - 012D5E380B632F7C00BAAF45 /* animation.h in Headers */, - 012D5E390B632F7C00BAAF45 /* blendshape.h in Headers */, - 012D5E3A0B632F7C00BAAF45 /* material.h in Headers */, - 012D5E3B0B632F7C00BAAF45 /* materialSet.h in Headers */, - 012D5E3C0B632F7C00BAAF45 /* mayaExportLayer.h in Headers */, - 012D5E3D0B632F7C00BAAF45 /* mesh.h in Headers */, - 012D5E3E0B632F7C00BAAF45 /* ogreExporter.h in Headers */, - 012D5E3F0B632F7C00BAAF45 /* paramlist.h in Headers */, - 012D5E400B632F7C00BAAF45 /* particles.h in Headers */, - 012D5E410B632F7C00BAAF45 /* skeleton.h in Headers */, - 012D5E420B632F7C00BAAF45 /* submesh.h in Headers */, - 012D5E430B632F7C00BAAF45 /* vertex.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXHeadersBuildPhase section */ - -/* Begin PBXNativeTarget section */ - D2AAC0620554660B00DB518D /* MayaExport */ = { - isa = PBXNativeTarget; - buildConfigurationList = 8A7F05ED086863A70064D097 /* Build configuration list for PBXNativeTarget "MayaExport" */; - buildPhases = ( - D2AAC0600554660B00DB518D /* Headers */, - D2AAC0610554660B00DB518D /* Sources */, - D289988505E68E00004EDB86 /* Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = MayaExport; - productName = exportJointClusterDataCmdPlugin; - productReference = D2AAC0630554660B00DB518D /* ogreExporter.bundle */; - productType = "com.apple.product-type.library.dynamic"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 08FB7793FE84155DC02AAC07 /* Project object */ = { - isa = PBXProject; - buildConfigurationList = 8A7F05F1086863A70064D097 /* Build configuration list for PBXProject "MayaExport" */; - hasScannedForEncodings = 1; - mainGroup = 08FB7794FE84155DC02AAC07 /* exportJointClusterDataCmdPlugin */; - projectDirPath = ""; - targets = ( - D2AAC0620554660B00DB518D /* MayaExport */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXSourcesBuildPhase section */ - D2AAC0610554660B00DB518D /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 012D5E4C0B632F9E00BAAF45 /* blendshape.cpp in Sources */, - 012D5E4D0B632F9E00BAAF45 /* material.cpp in Sources */, - 012D5E4E0B632F9E00BAAF45 /* mesh.cpp in Sources */, - 012D5E4F0B632F9E00BAAF45 /* ogreExporter.cpp in Sources */, - 012D5E500B632F9E00BAAF45 /* paramlist.cpp in Sources */, - 012D5E510B632F9E00BAAF45 /* particles.cpp in Sources */, - 012D5E520B632F9E00BAAF45 /* skeleton.cpp in Sources */, - 012D5E530B632F9E00BAAF45 /* submesh.cpp in Sources */, - 012D5F4C0B6336A400BAAF45 /* materialSet.cpp in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin XCBuildConfiguration section */ - 8A7F05EE086863A70064D097 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ARCHS = ( - ppc, - i386, - ); - COPY_PHASE_STRIP = NO; - DYLIB_COMPATIBILITY_VERSION = ""; - DYLIB_CURRENT_VERSION = ""; - EXECUTABLE_EXTENSION = bundle; - GCC_DYNAMIC_NO_PIC = NO; - GCC_ENABLE_FIX_AND_CONTINUE = YES; - GCC_GENERATE_DEBUGGING_SYMBOLS = YES; - GCC_MODEL_TUNING = G5; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - GENERATE_MASTER_OBJECT_FILE = YES; - HEADER_SEARCH_PATHS = ( - "$(MAYA_DIRECTORY)/devkit/include/", - ../../../OgreMain/include, - ../../../Mac/Ogre/include, - ); - INSTALL_PATH = /usr/local/lib; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(LIBRARY_SEARCH_PATHS_QUOTED_1)", - ); - LIBRARY_SEARCH_PATHS_QUOTED_1 = "\"$(SYSTEM_APPS_DIR)/Autodesk/maya8.5/Maya.app/Contents/MacOS\""; - LIBRARY_STYLE = BUNDLE; - MACH_O_TYPE = mh_bundle; - PREBINDING = NO; - PRODUCT_NAME = ogreExporter; - ZERO_LINK = NO; - }; - name = Debug; - }; - 8A7F05EF086863A70064D097 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ARCHS = ( - ppc, - i386, - ); - COPY_PHASE_STRIP = YES; - DYLIB_COMPATIBILITY_VERSION = ""; - DYLIB_CURRENT_VERSION = ""; - EXECUTABLE_EXTENSION = bundle; - GCC_ENABLE_FIX_AND_CONTINUE = NO; - GCC_GENERATE_DEBUGGING_SYMBOLS = NO; - GCC_MODEL_TUNING = G5; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - GENERATE_MASTER_OBJECT_FILE = YES; - HEADER_SEARCH_PATHS = ( - "$(MAYA_DIRECTORY)/devkit/include/", - ../../../OgreMain/include, - ../../../Mac/Ogre/include, - ); - INSTALL_PATH = /usr/local/lib; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(LIBRARY_SEARCH_PATHS_QUOTED_1)", - ); - LIBRARY_SEARCH_PATHS_QUOTED_1 = "\"$(SYSTEM_APPS_DIR)/Autodesk/maya8.5/Maya.app/Contents/MacOS\""; - LIBRARY_STYLE = BUNDLE; - MACH_O_TYPE = mh_bundle; - PREBINDING = NO; - PRODUCT_NAME = ogreExporter; - ZERO_LINK = NO; - }; - name = Release; - }; - 8A7F05F0086863A70064D097 /* Default */ = { - isa = XCBuildConfiguration; - buildSettings = { - ARCHS = ( - ppc, - i386, - ); - DYLIB_COMPATIBILITY_VERSION = ""; - DYLIB_CURRENT_VERSION = ""; - EXECUTABLE_EXTENSION = bundle; - GCC_GENERATE_DEBUGGING_SYMBOLS = NO; - GCC_MODEL_TUNING = G5; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - HEADER_SEARCH_PATHS = ( - "$(MAYA_DIRECTORY)/devkit/include/", - ../../../OgreMain/include, - ../../../Mac/Ogre/include, - ); - INSTALL_PATH = /usr/local/lib; - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(LIBRARY_SEARCH_PATHS_QUOTED_1)", - ); - LIBRARY_SEARCH_PATHS_QUOTED_1 = "\"$(SYSTEM_APPS_DIR)/Autodesk/maya8.5/Maya.app/Contents/MacOS\""; - LIBRARY_STYLE = BUNDLE; - MACH_O_TYPE = mh_bundle; - PREBINDING = NO; - PRODUCT_NAME = ogreExporter; - ZERO_LINK = NO; - }; - name = Default; - }; - 8A7F05F2086863A70064D097 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "$(MAYA_DIRECTORY)/devkit/include/maya/OpenMayaMac.h"; - GCC_PREPROCESSOR_DEFINITIONS = ( - MAC_PLUGIN, - _BOOL, - REQUIRE_IOSTREAM, - ); - HEADER_SEARCH_PATHS = "$(MAYA_DIRECTORY)/devkit/include/"; - LIBRARY_SEARCH_PATHS = "$(MAYA_DIRECTORY)/Maya.app/Contents/MacOS"; - LIBRARY_STYLE = BUNDLE; - MAYA_DIRECTORY = /Applications/Autodesk/maya8.5; - OTHER_LDFLAGS = ( - "-lOpenMaya", - "-lFoundation", - "-Wl,-executable_path,$(MAYA_DIRECTORY)/Maya.app/Contents/MacOS", - "-lOpenMayaAnim", - "-lOpenMaya", - "-lFoundation", - ); - }; - name = Debug; - }; - 8A7F05F3086863A70064D097 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "$(MAYA_DIRECTORY)/devkit/include/maya/OpenMayaMac.h"; - GCC_PREPROCESSOR_DEFINITIONS = ( - MAC_PLUGIN, - _BOOL, - REQUIRE_IOSTREAM, - ); - HEADER_SEARCH_PATHS = "$(MAYA_DIRECTORY)/devkit/include/"; - LIBRARY_SEARCH_PATHS = "$(MAYA_DIRECTORY)/Maya.app/Contents/MacOS"; - LIBRARY_STYLE = BUNDLE; - MAYA_DIRECTORY = /Applications/Autodesk/maya8.5; - OTHER_LDFLAGS = ( - "-lOpenMaya", - "-lFoundation", - "-Wl,-executable_path,$(MAYA_DIRECTORY)/Maya.app/Contents/MacOS", - "-lOpenMayaAnim", - "-lOpenMaya", - "-lFoundation", - ); - }; - name = Release; - }; - 8A7F05F4086863A70064D097 /* Default */ = { - isa = XCBuildConfiguration; - buildSettings = { - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "$(MAYA_DIRECTORY)/devkit/include/maya/OpenMayaMac.h"; - GCC_PREPROCESSOR_DEFINITIONS = ( - MAC_PLUGIN, - _BOOL, - REQUIRE_IOSTREAM, - ); - HEADER_SEARCH_PATHS = "$(MAYA_DIRECTORY)/devkit/include/"; - LIBRARY_SEARCH_PATHS = "$(MAYA_DIRECTORY)/Maya.app/Contents/MacOS"; - MAYA_DIRECTORY = /Applications/Autodesk/maya8.5; - OTHER_LDFLAGS = ( - "-lOpenMaya", - "-lFoundation", - "-Wl,-executable_path,$(MAYA_DIRECTORY)/Maya.app/Contents/MacOS", - "-lOpenMayaAnim", - "-lOpenMaya", - "-lFoundation", - ); - }; - name = Default; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 8A7F05ED086863A70064D097 /* Build configuration list for PBXNativeTarget "MayaExport" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 8A7F05EE086863A70064D097 /* Debug */, - 8A7F05EF086863A70064D097 /* Release */, - 8A7F05F0086863A70064D097 /* Default */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Default; - }; - 8A7F05F1086863A70064D097 /* Build configuration list for PBXProject "MayaExport" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 8A7F05F2086863A70064D097 /* Debug */, - 8A7F05F3086863A70064D097 /* Release */, - 8A7F05F4086863A70064D097 /* Default */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Default; - }; -/* End XCConfigurationList section */ - }; - rootObject = 08FB7793FE84155DC02AAC07 /* Project object */; -} diff --git a/Tools/MayaExport/scripts/MayaExport_vc8.sln b/Tools/MayaExport/scripts/MayaExport_vc8.sln deleted file mode 100644 index 2536c012a6f..00000000000 --- a/Tools/MayaExport/scripts/MayaExport_vc8.sln +++ /dev/null @@ -1,38 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 9.00 -# Visual Studio 2005 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MayaExport", "MayaExport_vc8.vcproj", "{B8E79576-F7E4-4E50-97DB-08FF62F206AD}" - ProjectSection(ProjectDependencies) = postProject - {35AFBABB-DF05-43DE-91A7-BB828A874015} = {35AFBABB-DF05-43DE-91A7-BB828A874015} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "OgreMain", "..\..\..\OgreMain\scripts\OgreMain_vc8.vcproj", "{35AFBABB-DF05-43DE-91A7-BB828A874015}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - DebugStaticLib|Win32 = DebugStaticLib|Win32 - Release|Win32 = Release|Win32 - ReleaseStaticLib|Win32 = ReleaseStaticLib|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {B8E79576-F7E4-4E50-97DB-08FF62F206AD}.Debug|Win32.ActiveCfg = Debug|Win32 - {B8E79576-F7E4-4E50-97DB-08FF62F206AD}.Debug|Win32.Build.0 = Debug|Win32 - {B8E79576-F7E4-4E50-97DB-08FF62F206AD}.DebugStaticLib|Win32.ActiveCfg = Debug|Win32 - {B8E79576-F7E4-4E50-97DB-08FF62F206AD}.DebugStaticLib|Win32.Build.0 = Debug|Win32 - {B8E79576-F7E4-4E50-97DB-08FF62F206AD}.Release|Win32.ActiveCfg = Release|Win32 - {B8E79576-F7E4-4E50-97DB-08FF62F206AD}.Release|Win32.Build.0 = Release|Win32 - {B8E79576-F7E4-4E50-97DB-08FF62F206AD}.ReleaseStaticLib|Win32.ActiveCfg = Release 7.0|Win32 - {B8E79576-F7E4-4E50-97DB-08FF62F206AD}.ReleaseStaticLib|Win32.Build.0 = Release 7.0|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.Debug|Win32.ActiveCfg = Debug|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.Debug|Win32.Build.0 = Debug|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.DebugStaticLib|Win32.ActiveCfg = DebugStaticLib|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.DebugStaticLib|Win32.Build.0 = DebugStaticLib|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.Release|Win32.ActiveCfg = Release|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.Release|Win32.Build.0 = Release|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.ReleaseStaticLib|Win32.ActiveCfg = ReleaseStaticLib|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.ReleaseStaticLib|Win32.Build.0 = ReleaseStaticLib|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/Tools/MayaExport/scripts/MayaExport_vc8.suo b/Tools/MayaExport/scripts/MayaExport_vc8.suo deleted file mode 100644 index 20fd8046ac7..00000000000 Binary files a/Tools/MayaExport/scripts/MayaExport_vc8.suo and /dev/null differ diff --git a/Tools/MayaExport/scripts/MayaExport_vc8.vcproj b/Tools/MayaExport/scripts/MayaExport_vc8.vcproj deleted file mode 100644 index fab0c70db48..00000000000 --- a/Tools/MayaExport/scripts/MayaExport_vc8.vcproj +++ /dev/null @@ -1,667 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/MayaExport/src/blendshape.cpp b/Tools/MayaExport/src/blendshape.cpp deleted file mode 100644 index 1b412965221..00000000000 --- a/Tools/MayaExport/src/blendshape.cpp +++ /dev/null @@ -1,537 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// blendshape.cpp -// Author : Francesco Giordana -// Sponsored by : Anygma N.V. (http://www.nazooka.com) -// Start Date : January 13, 2005 -// Copyright : (C) 2006 by Francesco Giordana -// Email : fra.giordana@tiscali.it -//////////////////////////////////////////////////////////////////////////////// - -/********************************************************************************* -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Lesser General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -**********************************************************************************/ - -#include "blendshape.h" -#include "submesh.h" - -namespace OgreMayaExporter -{ - // Constructor - BlendShape::BlendShape() - { - m_pBlendShapeFn = NULL; - clear(); - } - - // Destructor - BlendShape::~BlendShape() - { - clear(); - } - - // Clear blend shape data - void BlendShape::clear() - { - if (m_pBlendShapeFn) - delete m_pBlendShapeFn; - m_pBlendShapeFn = NULL; - m_origEnvelope = 0; - m_origWeights.clear(); - m_poseGroups.clear(); - poseGroup pg; - pg.targetIndex = 0; - m_poseGroups.insert(std::pair(0, pg)); - m_target = T_MESH; - m_weightConnections.clear(); - } - - // Load blend shape deformer from Maya - MStatus BlendShape::load(MObject &blendShapeObj) - { - // Create a Fn for relative Maya blend shape deformer - m_pBlendShapeFn = new MFnBlendShapeDeformer(blendShapeObj); - // Save original envelope value for the deformer - m_origEnvelope = m_pBlendShapeFn->envelope(); - // Save original target weights - m_origWeights.clear(); - MIntArray indexList; - m_pBlendShapeFn->weightIndexList(indexList); - for (int i=0; iweight(indexList[i])); - } - return MS::kSuccess; - } - - // Load blend shape poses for shared geometry - MStatus BlendShape::loadPosesShared(MDagPath& meshDag,ParamList ¶ms, - std::vector &vertices,long numVertices,long offset) - { - MStatus stat; - // Set blend shape target - m_target = T_MESH; - // Set blend shape deformer envelope to 1 to get target shapes - m_pBlendShapeFn->setEnvelope(1); - // Break connections on weights - breakConnections(); - // Set weight to 0 for all targets - MIntArray indexList; - m_pBlendShapeFn->weightIndexList(indexList); - for (int i=0; isetWeight(indexList[i],0); - if (MS::kSuccess != stat) - { - std::cout << "Error setting weight " << indexList[i] << " to 0 on blendhape deformer " << m_pBlendShapeFn->name().asChar() << "\n"; - std::cout << stat.errorString().asChar() << "\n"; - std::cout.flush(); - } - } - // Get pose names - MStringArray poseNames; - MString cmd = "aliasAttr -q " + m_pBlendShapeFn->name(); - MGlobal::executeCommand(cmd,poseNames,false,false); - // Get all poses: set iteratively weight to 1 for current target shape and keep 0 for the other targets - for (int i=0; isetWeight(indexList[i],1); - if (MS::kSuccess != stat) - { - std::cout << "Error setting weight " << indexList[i] << " to 1 on blend shape deformer " << m_pBlendShapeFn->name().asChar() << "\n"; - std::cout << stat.errorString().asChar() << "\n"; - std::cout.flush(); - } - // load the pose - stat = loadPoseShared(meshDag,params,vertices,numVertices,offset,poseName,i); - if (stat != MS::kSuccess) - { - std::cout << "Failed loading target pose " << indexList[i] << "\n"; - std::cout << stat.errorString().asChar(); - std::cout.flush(); - } - // set weight to 0 - stat = m_pBlendShapeFn->setWeight(indexList[i],0); - if (MS::kSuccess != stat) - { - std::cout << "Error resetting weight " << indexList[i] << " to 0 on blend shape deformer " << m_pBlendShapeFn->name().asChar() << "\n"; - std::cout << stat.errorString().asChar() << "\n"; - std::cout.flush(); - } - } - // Set blend shape envelope to 0 - m_pBlendShapeFn->setEnvelope(0); - // Restore targets weights - for (int i=0; isetWeight(indexList[i],m_origWeights[i]); - } - // Restore connections on weights - restoreConnections(); - return MS::kSuccess; - } - - // Load blend shape poses for a submesh - MStatus BlendShape::loadPosesSubmesh(MDagPath& meshDag,ParamList ¶ms, - std::vector &vertices,std::vector& indices,long targetIndex) - { - MStatus stat; - // Set blend shape target - m_target = T_SUBMESH; - // Set blend shape deformer envelope to 1 to get target shapes - m_pBlendShapeFn->setEnvelope(1); - // Break connections on weights - breakConnections(); - // Set weight to 0 for all targets - MIntArray indexList; - m_pBlendShapeFn->weightIndexList(indexList); - for (int i=0; isetWeight(indexList[i],0); - if (MS::kSuccess != stat) - { - std::cout << "Error setting weight " << indexList[i] << " to 0 on blendhape deformer " << m_pBlendShapeFn->name().asChar() << "\n"; - std::cout << stat.errorString().asChar() << "\n"; - std::cout.flush(); - } - } - - // Get pose names - MStringArray poseNames; - MString cmd = "aliasAttr -q " + m_pBlendShapeFn->name(); - MGlobal::executeCommand(cmd,poseNames,false,false); - // Get all poses: set iteratively weight to 1 for current target shape and keep 0 for the other targets - poseGroup pg; - pg.targetIndex = targetIndex; - m_poseGroups.insert(std::pair(targetIndex,pg)); - for (int i=0; isetWeight(indexList[i],1); - if (MS::kSuccess != stat) - { - std::cout << "Error setting weight " << indexList[i] << " to 1 on blend shape deformer " << m_pBlendShapeFn->name().asChar() << "\n"; - std::cout << stat.errorString().asChar() << "\n"; - std::cout.flush(); - } - // load the pose - stat = loadPoseSubmesh(meshDag,params,vertices,indices,poseName,targetIndex,i); - if (stat != MS::kSuccess) - { - std::cout << "Failed loading target pose " << indexList[i] << "\n"; - std::cout << stat.errorString().asChar(); - std::cout.flush(); - } - // set weight to 0 - stat = m_pBlendShapeFn->setWeight(indexList[i],0); - if (MS::kSuccess != stat) - { - std::cout << "Error resetting weight " << indexList[i] << " to 0 on blend shape deformer " << m_pBlendShapeFn->name().asChar() << "\n"; - std::cout << stat.errorString().asChar() << "\n"; - std::cout.flush(); - } - } - // Set blend shape envelope to 0 - m_pBlendShapeFn->setEnvelope(0); - // Restore targets weights - for (int i=0; isetWeight(indexList[i],m_origWeights[i]); - } - // Restore connections on weights - restoreConnections(); - return MS::kSuccess; - } - - // Load a single blend shape pose for shared geometry - MStatus BlendShape::loadPoseShared(MDagPath& meshDag,ParamList ¶ms,std::vector &vertices, - long numVertices,long offset,MString poseName,int blendShapeIndex) - { - // get the mesh Fn - MFnMesh mesh(meshDag); - // get pose group - poseGroup& pg = m_poseGroups.find(0)->second; - // create a new pose - pose p; - p.poseTarget = m_target; - p.index = 0; - p.blendShapeIndex = blendShapeIndex; - p.name = poseName.asChar(); - // get vertex positions - MFloatPointArray points; - if (params.exportWorldCoords) - mesh.getPoints(points,MSpace::kWorld); - else - mesh.getPoints(points,MSpace::kObject); - // calculate vertex offsets - for (int i=0; i 0) - pg.poses.push_back(p); - if (params.bsBB) - { - // update bounding boxes of loaded submeshes - for (int i=0; im_dagPath); - MPoint min = mesh.boundingBox().min(); - MPoint max = mesh.boundingBox().max(); - MBoundingBox bbox(min,max); - if (params.exportWorldCoords) - bbox.transformUsing(params.loadedSubmeshes[i]->m_dagPath.inclusiveMatrix()); - min = bbox.min() * params.lum; - max = bbox.max() * params.lum; - MBoundingBox newbbox(min,max); - params.loadedSubmeshes[i]->m_boundingBox.expand(newbbox); - } - } - // pose loaded succesfully - return MS::kSuccess; - } - - // Load a single blend shape pose for a submesh - MStatus BlendShape::loadPoseSubmesh(MDagPath& meshDag,ParamList ¶ms,std::vector& vertices, - std::vector& indices,MString poseName,int targetIndex,int blendShapeIndex) - { - // get the mesh Fn - MFnMesh mesh(meshDag); - // get pose group - poseGroup& pg = m_poseGroups.find(targetIndex)->second; - // create a new pose - pose p; - p.poseTarget = m_target; - p.index = targetIndex; - p.blendShapeIndex = blendShapeIndex; - p.name = poseName.asChar(); - // get vertex positions - MFloatPointArray points; - if (params.exportWorldCoords) - mesh.getPoints(points,MSpace::kWorld); - else - mesh.getPoints(points,MSpace::kObject); - // calculate vertex offsets - for (int i=0; i 0) - pg.poses.push_back(p); - if (params.bsBB) - { - // update bounding boxes of loaded submeshes - for (int i=0; im_dagPath); - MPoint min = mesh.boundingBox().min(); - MPoint max = mesh.boundingBox().max(); - MBoundingBox bbox(min,max); - if (params.exportWorldCoords) - bbox.transformUsing(params.loadedSubmeshes[i]->m_dagPath.inclusiveMatrix()); - min = bbox.min() * params.lum; - max = bbox.max() * params.lum; - MBoundingBox newbbox(min,max); - params.loadedSubmeshes[i]->m_boundingBox.expand(newbbox); - } - } - // pose loaded succesfully - return MS::kSuccess; - } - - - - // Load a blend shape animation track - Track BlendShape::loadTrack(float start,float stop,float rate,ParamList& params,int targetIndex,int startPoseId) - { - MStatus stat; - MString msg; - std::vector times; - // Create a track for current clip - Track t; - t.m_type = TT_POSE; - t.m_target = m_target; - t.m_index = targetIndex; - t.m_vertexKeyframes.clear(); - // Calculate times from clip sample rate - times.clear(); - if (rate <= 0) - { - std::cout << "invalid sample rate for the clip (must be >0), we skip it\n"; - std::cout.flush(); - return t; - } - for (float time=start; time= 0) - length = times[times.size()-1] - times[0]; - if (length < 0) - { - std::cout << "invalid time range for the clip, we skip it\n"; - std::cout.flush(); - return t; - } - // Evaluate animation curves at selected times - for (int i=0; i 0) - t.addVertexKeyframe(key); - } - // Clip successfully loaded - return t; - } - - - // Load a blend shape animation keyframe - vertexKeyframe BlendShape::loadKeyframe(float time,ParamList& params,int targetIndex, int startPoseId) - { - poseGroup& pg = m_poseGroups.find(targetIndex)->second; - // Create keyframe - vertexKeyframe key; - key.time = time; - key.poserefs.clear(); - // Read weights of all poses at current time - // Get blend shape deformer envelope - float envelope = m_pBlendShapeFn->envelope(); - // Get weights of all targets - MIntArray indexList; - m_pBlendShapeFn->weightIndexList(indexList); - for (int i=0; iweight(indexList[p.blendShapeIndex]); - key.poserefs.push_back(poseref); - } - return key; - } - - // Get blend shape deformer name - MString BlendShape::getName() - { - return m_pBlendShapeFn->name(); - } - - // Get blend shape poses - stdext::hash_map& BlendShape::getPoseGroups() - { - return m_poseGroups; - } - - // Set maya blend shape deformer envelope - void BlendShape::setEnvelope(float envelope) - { - m_pBlendShapeFn->setEnvelope(envelope); - } - // Restore maya blend shape deformer original envelope - void BlendShape::restoreEnvelope() - { - m_pBlendShapeFn->setEnvelope(m_origEnvelope); - } - // Break connections to this blendshape - void BlendShape::breakConnections() - { - MStatus stat; - MDagModifier dagModifier; - // Clear the stored connections - m_weightConnections.clear(); - // Save node connections and break them - MPlug weightsPlug = m_pBlendShapeFn->findPlug("weight",true); - for (int i=0; ifindPlug("weight",true); - for (int i=0; iname(); - MStringArray tmpStrArray; - tmpStr.split(':',tmpStrArray); - m_name = ""; - for (int i=0; iobject().hasFn(MFn::kPhong)) - { - stat = loadPhong(pShader); - } - else if (pShader->object().hasFn(MFn::kBlinn)) - { - stat = loadBlinn(pShader); - } - else if (pShader->object().hasFn(MFn::kLambert)) - { - stat = loadLambert(pShader); - } - else if (pShader->object().hasFn(MFn::kPluginHwShaderNode)) - { - stat = loadCgFxShader(pShader); - } - else - { - stat = loadSurfaceShader(pShader); - } - - // Get textures data - MPlugArray colorSrcPlugs; - MPlugArray texSrcPlugs; - MPlugArray placetexSrcPlugs; - if (m_isTextured) - { - // Translate multiple textures if material is multitextured - if (m_isMultiTextured) - { - // Get layered texture node - MFnDependencyNode* pLayeredTexNode = NULL; - if (m_type == MT_SURFACE_SHADER) - pShader->findPlug("outColor").connectedTo(colorSrcPlugs,true,false); - else - pShader->findPlug("color").connectedTo(colorSrcPlugs,true,false); - for (int i=0; ifindPlug("inputs"); - - // Scan inputs and export textures - for (int i=inputsPlug.numElements()-1; i>=0; i--) - { - MFnDependencyNode* pTextureNode = NULL; - // Search for a connected texture - inputsPlug[i].child(0).connectedTo(colorSrcPlugs,true,false); - for (int j=0; jfindPlug("outColor").connectedTo(colorSrcPlugs,true,false); - else - pShader->findPlug("color").connectedTo(colorSrcPlugs,true,false); - for (int i=0; ifindPlug("outColor").connectedTo(colorSrcPlugs,true,false); - for (int i=0; ifindPlug("outTransparencyR").getValue(trasp); - if (pShader->findPlug("outTransparency").isConnected() || trasp>0.0f) - m_isTransparent = true; - - // Get material colours - if (m_isTextured) - m_diffuse = MColor(1.0,1.0,1.0,1.0); - else - { - pShader->findPlug("outColorR").getValue(m_diffuse.r); - pShader->findPlug("outColorG").getValue(m_diffuse.g); - pShader->findPlug("outColorB").getValue(m_diffuse.b); - float trasp; - pShader->findPlug("outTransparencyR").getValue(trasp); - m_diffuse.a = 1.0 - trasp; - } - m_ambient = MColor(0,0,0,1); - m_emissive = MColor(0,0,0,1); - m_specular = MColor(0,0,0,1); - return MS::kSuccess; - } - - // Load a lambert shader - MStatus Material::loadLambert(MFnDependencyNode *pShader) - { - MPlugArray colorSrcPlugs; - m_type = MT_LAMBERT; - MFnLambertShader* pLambert = new MFnLambertShader(pShader->object()); - // Check if material is textured - pLambert->findPlug("color").connectedTo(colorSrcPlugs,true,false); - for (int i=0; ifindPlug("transparency").isConnected() || pLambert->transparency().r>0.0f) - m_isTransparent = true; - - // Get material colours - //diffuse colour - if (m_isTextured) - m_diffuse = MColor(1.0,1.0,1.0,1.0); - else - { - m_diffuse = pLambert->color(); - m_diffuse.a = 1.0 - pLambert->transparency().r; - } - //ambient colour - m_ambient = pLambert->ambientColor(); - //emissive colour - m_emissive = pLambert->incandescence(); - //specular colour - m_specular = MColor(0,0,0,1); - delete pLambert; - return MS::kSuccess; - } - - // Load a phong shader - MStatus Material::loadPhong(MFnDependencyNode *pShader) - { - MPlugArray colorSrcPlugs; - m_type = MT_PHONG; - MFnPhongShader* pPhong = new MFnPhongShader(pShader->object()); - // Check if material is textured - pPhong->findPlug("color").connectedTo(colorSrcPlugs,true,false); - for (int i=0; ifindPlug("transparency").isConnected() || pPhong->transparency().r>0.0f) - m_isTransparent = true; - - // Get material colours - //diffuse colour - if (m_isTextured) - m_diffuse = MColor(1.0,1.0,1.0,1.0); - else - { - m_diffuse = pPhong->color(); - m_diffuse.a = 1.0 - pPhong->transparency().r; - } - //ambient colour - m_ambient = pPhong->ambientColor(); - //emissive colour - m_emissive = pPhong->incandescence(); - //specular colour - m_specular = pPhong->specularColor(); - m_specular.a = pPhong->cosPower()*1.28; - delete pPhong; - return MS::kSuccess; - } - - // load a blinn shader - MStatus Material::loadBlinn(MFnDependencyNode *pShader) - { - MPlugArray colorSrcPlugs; - m_type = MT_BLINN; - MFnBlinnShader* pBlinn = new MFnBlinnShader(pShader->object()); - // Check if material is textured - pBlinn->findPlug("color").connectedTo(colorSrcPlugs,true,false); - for (int i=0; ifindPlug("transparency").isConnected() || pBlinn->transparency().r>0.0f) - m_isTransparent = true; - - // Get material colours - //diffuse colour - if (m_isTextured) - m_diffuse = MColor(1.0,1.0,1.0,1.0); - else - { - m_diffuse = pBlinn->color(); - m_diffuse.a = 1.0 - pBlinn->transparency().r; - } - //ambient colour - m_ambient = pBlinn->ambientColor(); - //emissive colour - m_emissive = pBlinn->incandescence(); - //specular colour - m_specular = pBlinn->specularColor(); - m_specular.a = 128.0-(128.0*pBlinn->eccentricity()); - delete pBlinn; - return MS::kSuccess; - } - - // load a cgFx shader - MStatus Material::loadCgFxShader(MFnDependencyNode *pShader) - { - m_type = MT_CGFX; - // Create a default white lambert - m_isTextured = false; - m_isMultiTextured = false; - m_diffuse = MColor(1.0,1.0,1.0,1.0); - m_specular = MColor(0,0,0,1); - m_emissive = MColor(0,0,0,1); - m_ambient = MColor(0,0,0,1); - return MS::kSuccess; - } - - // Load texture data from a texture node - MStatus Material::loadTexture(MFnDependencyNode* pTexNode,TexOpType& opType,MStringArray& uvsets,ParamList& params) - { - Texture tex; - // Get texture filename - MString filename, absFilename; - MRenderUtil::exactFileTextureName(pTexNode->object(),absFilename); - filename = absFilename.substring(absFilename.rindex('/')+1,absFilename.length()-1); - MString command = "toNativePath(\""; - command += absFilename; - command += "\")"; - MGlobal::executeCommand(command,absFilename); - tex.absFilename = absFilename; - tex.filename = filename; - tex.uvsetIndex = 0; - tex.uvsetName = ""; - // Set texture operation type - tex.opType = opType; - // Get connections to uvCoord attribute of texture node - MPlugArray texSrcPlugs; - pTexNode->findPlug("uvCoord").connectedTo(texSrcPlugs,true,false); - // Get place2dtexture node (if connected) - MFnDependencyNode* pPlace2dTexNode = NULL; - for (int j=0; jfindPlug("uvCoord").connectedTo(placetexSrcPlugs,true,false); - for (int j=0; jfindPlug("uvSets"); - MPlugArray uvsetsSrcPlugs; - for (int i=0; ifindPlug("wrapU").getValue(wrapU); - pPlace2dTexNode->findPlug("mirrorU").getValue(mirrorU); - if (mirrorU) - tex.am_u = TAM_MIRROR; - else if (wrapU) - tex.am_u = TAM_WRAP; - else - tex.am_u = TAM_CLAMP; - // V - bool wrapV,mirrorV; - pPlace2dTexNode->findPlug("wrapV").getValue(wrapV); - pPlace2dTexNode->findPlug("mirrorV").getValue(mirrorV); - if (mirrorV) - tex.am_v = TAM_MIRROR; - else if (wrapV) - tex.am_v = TAM_WRAP; - else - tex.am_v = TAM_CLAMP; - // Get texture scale - double covU,covV; - pPlace2dTexNode->findPlug("coverageU").getValue(covU); - pPlace2dTexNode->findPlug("coverageV").getValue(covV); - tex.scale_u = covU; - if (fabs(tex.scale_u) < PRECISION) - tex.scale_u = 0; - tex.scale_v = covV; - if (fabs(tex.scale_v) < PRECISION) - tex.scale_v = 0; - // Get texture scroll - double transU,transV; - pPlace2dTexNode->findPlug("translateFrameU").getValue(transU); - pPlace2dTexNode->findPlug("translateFrameV").getValue(transV); - tex.scroll_u = -0.5 * (covU-1.0)/covU - transU/covU; - if (fabs(tex.scroll_u) < PRECISION) - tex.scroll_u = 0; - tex.scroll_v = 0.5 * (covV-1.0)/covV + transV/covV; - if (fabs(tex.scroll_v) < PRECISION) - tex.scroll_v = 0; - // Get texture rotation - double rot; - pPlace2dTexNode->findPlug("rotateFrame").getValue(rot); - tex.rot = -rot; - if (fabs(rot) < PRECISION) - tex.rot = 0; - } - // add texture to material texture list - m_textures.push_back(tex); - // free up memory - if (pUvChooserNode) - delete pUvChooserNode; - if (pPlace2dTexNode) - delete pPlace2dTexNode; - - return MS::kSuccess; - } - - - // Write material data to an Ogre material script file - MStatus Material::writeOgreScript(ParamList ¶ms) - { - //Start material description - params.outMaterial << "material " << m_name.asChar() << "\n"; - params.outMaterial << "{\n"; - - //Start technique description - params.outMaterial << "\ttechnique\n"; - params.outMaterial << "\t{\n"; - - //Start render pass description - params.outMaterial << "\t\tpass\n"; - params.outMaterial << "\t\t{\n"; - //set lighting off option if requested - if (m_lightingOff) - params.outMaterial << "\t\t\tlighting off\n\n"; - //set phong shading if requested (default is gouraud) - if (m_type == MT_PHONG) - params.outMaterial << "\t\t\tshading phong\n"; - //ambient colour - params.outMaterial << "\t\t\tambient " << m_ambient.r << " " << m_ambient.g << " " << m_ambient.b - << " " << m_ambient.a << "\n"; - //diffuse colour - params.outMaterial << "\t\t\tdiffuse " << m_diffuse.r << " " << m_diffuse.g << " " << m_diffuse.b - << " " << m_diffuse.a << "\n"; - //specular colour - params.outMaterial << "\t\t\tspecular " << m_specular.r << " " << m_specular.g << " " << m_specular.b - << " " << m_specular.a << "\n"; - //emissive colour - params.outMaterial << "\t\t\temissive " << m_emissive.r << " " << m_emissive.g << " " - << m_emissive.b << "\n"; - //if material is transparent set blend mode and turn off depth_writing - if (m_isTransparent) - { - params.outMaterial << "\n\t\t\tscene_blend alpha_blend\n"; - params.outMaterial << "\t\t\tdepth_write off\n"; - } - //write texture units - for (int i=0; i MaterialSet* Singleton::msSingleton = 0; -}; //end namespace \ No newline at end of file diff --git a/Tools/MayaExport/src/mesh.cpp b/Tools/MayaExport/src/mesh.cpp deleted file mode 100644 index 0cb6f936170..00000000000 --- a/Tools/MayaExport/src/mesh.cpp +++ /dev/null @@ -1,1594 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// mesh.cpp -// Author : Francesco Giordana -// Sponsored by : Anygma N.V. (http://www.nazooka.com) -// Start Date : January 13, 2005 -// Copyright : (C) 2006 by Francesco Giordana -// Email : fra.giordana@tiscali.it -//////////////////////////////////////////////////////////////////////////////// - -/********************************************************************************* -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Lesser General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -**********************************************************************************/ - -#include "mesh.h" -#include - -namespace OgreMayaExporter -{ - /***** Class Mesh *****/ - // constructor - Mesh::Mesh(const MString& name) - { - m_name = name; - m_numTriangles = 0; - m_pSkeleton = NULL; - m_sharedGeom.vertices.clear(); - m_sharedGeom.dagMap.clear(); - m_vertexClips.clear(); - m_BSClips.clear(); - } - - // destructor - Mesh::~Mesh() - { - clear(); - } - - // clear data - void Mesh::clear() - { - m_name = ""; - m_numTriangles = 0; - for (int i=0; isetEnvelope(0.0f); - } - // Get connected shaders - stat = getShaders(meshDag); - if (stat != MS::kSuccess) - { - std::cout << "Error getting shaders connected to current mesh\n"; - std::cout.flush(); - } - // Get vertex data - stat = getVertices(meshDag,params); - if (stat != MS::kSuccess) - { - std::cout << "Error retrieving vertex data for current mesh\n"; - std::cout.flush(); - } - // Get vertex bone weights - if (pSkinCluster) - { - getVertexBoneWeights(meshDag,params); - if (stat != MS::kSuccess) - { - std::cout << "Error retrieving veretex bone assignements for current mesh\n"; - std::cout.flush(); - } - } - // Get faces data - stat = getFaces(meshDag,params); - if (stat != MS::kSuccess) - { - std::cout << "Error retrieving faces data for current mesh\n"; - std::cout.flush(); - } - // Build shared geometry - if (params.useSharedGeom) - { - stat = buildSharedGeometry(meshDag,params); - if (stat != MS::kSuccess) - { - std::cout << "Error building shared geometry for current mesh\n"; - std::cout.flush(); - } - } - // Create submeshes (a different submesh for every different shader linked to the mesh) - stat = createSubmeshes(meshDag,params); - if (stat != MS::kSuccess) - { - std::cout << "Error creating submeshes for current mesh\n"; - std::cout.flush(); - } - // Restore blendshape envelope - if (pBlendShape) - { - pBlendShape->restoreEnvelope(); - } - // Free up memory - newvertices.clear(); - newweights.clear(); - newjointIds.clear(); - newpoints.clear(); - newnormals.clear(); - newuvsets.clear(); - shaders.clear(); - shaderPolygonMapping.clear(); - polygonSets.clear(); - if (pSkinCluster) - delete pSkinCluster; - pBlendShape = NULL; - - return MS::kSuccess; - } - - - /******************************************************************************* - * Load mesh animations from Maya * - *******************************************************************************/ - // Load vertex animations - MStatus Mesh::loadAnims(ParamList& params) - { - MStatus stat; - // save current time for later restore - MTime curTime = MAnimControl::currentTime(); - std::cout << "Loading vertex animations...\n"; - std::cout.flush(); - // clear animations data - m_vertexClips.clear(); - // load the requested clips - for (int i=0; isetEnvelope(0); - } - } - else - { - for (int i=0; im_pBlendShape) - pSubmesh->m_pBlendShape->setEnvelope(0); - } - } - // Get the blend shape poses - if (params.useSharedGeom) - { - for (int i=0; iloadPosesShared(di.dagPath,params,m_sharedGeom.vertices,di.numVertices,di.offset); - } - } - else - { - for (int i=0; im_pBlendShape) - pSubmesh->m_pBlendShape->loadPosesSubmesh(pSubmesh->m_dagPath,params,pSubmesh->m_vertices, - pSubmesh->m_indices,i+1); - } - } - // Enable constraints, IK, etc... - MGlobal::executeCommand("doEnableNodeItems true all",true); - // Restore blend shape deformers original envelopes - if (params.useSharedGeom) - { - for (int i=0; irestoreEnvelope(); - } - } - else - { - for (int i=0; im_pBlendShape) - pSubmesh->m_pBlendShape->restoreEnvelope(); - } - } - // Read blend shape animations - if (params.exportBSAnims) - { - stat = loadBlendShapeAnimations(params); - } - return MS::kSuccess; - } - - // Load blend shape animations - MStatus Mesh::loadBlendShapeAnimations(ParamList& params) - { - std::cout << "Loading blend shape animations...\n"; - std::cout.flush(); - // Read the list of blend shape clips to export - for (int i=0; i tracks; - for (int j=0; jloadTrack(ci.start,ci.stop,ci.rate,params,0,startPoseId); - tracks.push_back(t); - startPoseId += di.pBlendShape->getPoseGroups().find(0)->second.poses.size(); - } - } - // Merge the tracks into a single track (shared geometry must have a single animation track) - if (tracks.size() > 0) - { - Track newTrack; - // Merge keyframes at the same time position from all tracks - for (int j=0; jposerefs.size(); pri++) - { - // Create a new pose reference - vertexPoseRef poseref; - // Copy pose reference settings from source keyframe - poseref.poseIndex = pSrcKeyframe->poserefs[pri].poseIndex; - poseref.poseWeight = pSrcKeyframe->poserefs[pri].poseWeight; - // Add the new pose reference to the new keyframe - newKeyframe.poserefs.push_back(poseref); - } - } - // Add the keyframe to the new joined track - newTrack.m_vertexKeyframes.push_back(newKeyframe); - } - // Add the joined track to current animation clip - a.addTrack(newTrack); - } - } - else - { - // Create a track for each submesh - std::vector tracks; - for (int j=0; jm_pBlendShape) - { - int startPoseId = 0; - Track t = pSubmesh->m_pBlendShape->loadTrack(ci.start,ci.stop,ci.rate,params,j+1,startPoseId); - a.addTrack(t); - } - } - } - if (a.m_tracks.size() > 0) - { - std::cout << "length: " << a.m_length << "\n"; - std::cout << "num keyframes: " << a.m_tracks[0].m_vertexKeyframes.size() << "\n"; - std::cout.flush(); - m_BSClips.push_back(a); - } - else - { - std::cout << "no tracks exported: skipped. \n"; - std::cout.flush(); - } - } - return MS::kSuccess; - } - - -/******************** Methods to parse geometry data from Maya ************************/ - // Get uvsets info from the maya mesh - MStatus Mesh::getUVSets(const MDagPath& meshDag) - { - MFnMesh mesh(meshDag); - MStatus stat; - // Get uv texture coordinate sets' names - if (mesh.numUVSets() > 0) - { - stat = mesh.getUVSetNames(newuvsets); - if (MS::kSuccess != stat) - { - std::cout << "Error retrieving UV sets names\n"; - std::cout.flush(); - return MS::kFailure; - } - } - // Save uvsets info - for (int i=m_uvsets.size(); inumOutputConnections(); - for(uint uiGeometry = 0; uiGeometry < uiNumGeometries; ++uiGeometry ) - { - unsigned int uiIndex = pSkinCluster->indexForOutputConnection(uiGeometry); - MObject kOutputObject = pSkinCluster->outputShapeAtIndex(uiIndex); - if(kOutputObject == mesh.object()) - { - std::cout << "Found skin cluster " << pSkinCluster->name().asChar() << " for mesh " - << mesh.name().asChar() << "\n"; - std::cout.flush(); - } - else - { - delete pSkinCluster; - pSkinCluster = NULL; - } - } - } - if (pSkinCluster) - { - // load the skeleton - std::cout << "Loading skeleton data...\n"; - std::cout.flush(); - if (!m_pSkeleton) - m_pSkeleton = new Skeleton(); - stat = m_pSkeleton->load(pSkinCluster,params); - if (MS::kSuccess != stat) - { - std::cout << "Error loading skeleton data\n"; - std::cout.flush(); - } - else - { - std::cout << "OK\n"; - std::cout.flush(); - } - } - } - return MS::kSuccess; - } - - - // Get blend shape deformer linked to the maya mesh - MStatus Mesh::getBlendShapeDeformer(const MDagPath &meshDag, OgreMayaExporter::ParamList ¶ms) - { - MStatus stat; - MFnMesh mesh(meshDag); - if (params.exportBlendShapes) - { - // get connected blend shape deformer (if present) - MItDependencyNodes kDepNodeIt( MFn::kBlendShape ); - for( ;!kDepNodeIt.isDone() && !pBlendShape; kDepNodeIt.next()) - { - MObject kObject = kDepNodeIt.item(); - MItDependencyGraph itGraph(kObject,MFn::kMesh,MItDependencyGraph::kDownstream,MItDependencyGraph::kDepthFirst); - for (;!itGraph.isDone() && !pBlendShape; itGraph.next()) - { - MFnMesh connectedMesh(itGraph.thisNode()); - if (connectedMesh.fullPathName() == mesh.fullPathName()) - { - pBlendShape = new BlendShape(); - pBlendShape->load(kObject); - std::cout << "Found blend shape deformer " << pBlendShape->getName().asChar() << " for mesh " - << mesh.name().asChar() << "\n"; - } - } - } - } - return MS::kSuccess; - } - // Get connected shaders - MStatus Mesh::getShaders(const MDagPath& meshDag) - { - MStatus stat; - MFnMesh mesh(meshDag); - stat = mesh.getConnectedShaders(0,shaders,shaderPolygonMapping); - std::cout.flush(); - if (MS::kSuccess != stat) - { - std::cout << "Error getting connected shaders\n"; - std::cout.flush(); - return MS::kFailure; - } - std::cout << "Found " << shaders.length() << " connected shaders\n"; - std::cout.flush(); - if (shaders.length() <= 0) - { - std::cout << "No connected shaders, skipping mesh\n"; - std::cout.flush(); - return MS::kFailure; - } - // create a series of arrays of faces for each different submesh - polygonSets.clear(); - polygonSets.resize(shaders.length()); - return MS::kSuccess; - } - - - // Get vertex data - MStatus Mesh::getVertices(const MDagPath &meshDag, OgreMayaExporter::ParamList ¶ms) - { - MFnMesh mesh(meshDag); - // prepare vertex table - newvertices.resize(mesh.numVertices()); - newweights.resize(mesh.numVertices()); - newjointIds.resize(mesh.numVertices()); - for (int i=0; igetWeights(meshDag,component,vertexWeights,numWeights); - // save the normalized weights - newweights[i]=vertexWeights; - if (MS::kSuccess != stat) - { - std::cout << "Error retrieving vertex weights\n"; - std::cout.flush(); - } - // get ids for the joints - if (m_pSkeleton) - { - MDagPathArray influenceObjs; - pSkinCluster->influenceObjects(influenceObjs,&stat); - if (MS::kSuccess != stat) - { - std::cout << "Error retrieving influence objects for given skin cluster\n"; - std::cout.flush(); - } - newjointIds[i].setLength(newweights[i].length()); - for (int j=0; jgetJoints().size() && !foundJoint; k++) - { - if (partialPathName == m_pSkeleton->getJoints()[k].name) - { - foundJoint=true; - newjointIds[i][j] = m_pSkeleton->getJoints()[k].id; - } - } - } - } - } - return MS::kSuccess; - } - - - // Get faces data - MStatus Mesh::getFaces(const MDagPath &meshDag, ParamList ¶ms) - { - MStatus stat; - MFnMesh mesh(meshDag); - // create an iterator to go through mesh polygons - if (mesh.numPolygons() > 0) - { - std::cout << "Iterate over mesh polygons\n"; - std::cout.flush(); - MItMeshPolygon faceIter(mesh.object(),&stat); - if (MS::kSuccess != stat) - { - std::cout << "Error accessing mesh polygons\n"; - std::cout.flush(); - return MS::kFailure; - } - std::cout << "num polygons = " << mesh.numPolygons() << "\n"; - std::cout.flush(); - // iterate over mesh polygons - for (; !faceIter.isDone(); faceIter.next()) - { - int numTris=0; - bool different; - int vtxIdx, nrmIdx; - faceIter.numTriangles(numTris); - // for every triangle composing current polygon extract triangle info - for (int iTris=0; iTris 1) - color.r = 1; - else if (color.r < PRECISION) - color.r = 0; - if (color.g > 1) - color.g = 1; - else if (color.g < PRECISION) - color.g = 0; - if (color.b > 1) - color.b = 1; - else if (color.b < PRECISION) - color.b = 0; - if (color.a > 1) - color.a = 1; - else if (color.a < PRECISION) - color.a = 0; - } - else - { - color = MColor(1,1,1,1); - } - if (newvertices[vtxIdx].next == -2) // first time we encounter a vertex in this position - { - // save vertex position - newpoints[vtxIdx].cartesianize(); - newvertices[vtxIdx].pointIdx = vtxIdx; - // save vertex normal - newvertices[vtxIdx].normalIdx = nrmIdx; - // save vertex colour - newvertices[vtxIdx].r = color.r; - newvertices[vtxIdx].g = color.g; - newvertices[vtxIdx].b = color.b; - newvertices[vtxIdx].a = color.a; - // save vertex texture coordinates - newvertices[vtxIdx].u.resize(newuvsets.length()); - newvertices[vtxIdx].v.resize(newuvsets.length()); - // save vbas - newvertices[vtxIdx].vba.resize(newweights[vtxIdx].length()); - for (int j=0; j= 0) - polygonSets[shaderPolygonMapping[faceIter.index()]].push_back(newFace); - } // end iteration of triangles - } - } - std::cout << "done reading mesh triangles\n"; - std::cout.flush(); - return MS::kSuccess; - } - - - // Build shared geometry - MStatus Mesh::buildSharedGeometry(const MDagPath &meshDag,ParamList& params) - { - std::cout << "Create list of shared vertices\n"; - std::cout.flush(); - // save a new entry in the shared geometry map: we associate the index of the first - // vertex we're loading with the dag path from which it has been read - dagInfo di; - di.offset = m_sharedGeom.vertices.size(); - di.dagPath = meshDag; - di.pBlendShape = pBlendShape; - // load shared vertices - for (int i=0; itexcoords.size(); jtexcoords.push_back(newTexCoords); - } - } - // save number of vertices referring to this mesh dag in the dag path map - di.numVertices = m_sharedGeom.vertices.size() - di.offset; - m_sharedGeom.dagMap.push_back(di); - std::cout << "done creating vertices list\n"; - std::cout.flush(); - return MS::kSuccess; - } - - - // Create submeshes - MStatus Mesh::createSubmeshes(const MDagPath& meshDag,ParamList& params) - { - MStatus stat; - MFnMesh mesh(meshDag); - for (int i=0; i 0) - { - //create a name for the submesh - MString submesh_name = meshDag.partialPathName(); - MFnDependencyNode shader_node(shaders[i]); - if (shaders.length()>1) - { - submesh_name += "_"; - submesh_name += shader_node.name(); - } - //create new submesh - Submesh* pSubmesh = new Submesh(submesh_name); - //load linked shader - stat = pSubmesh->loadMaterial(shaders[i],newuvsets,params); - if (stat != MS::kSuccess) - { - MFnDependencyNode shadingGroup(shaders[i]); - std::cout << "Error loading material for submesh: " << submesh_name.asChar() << "\n"; - std::cout.flush(); - return MS::kFailure; - } - //load vertex and face data - stat = pSubmesh->load(meshDag,polygonSets[i],newvertices,newpoints,newnormals,newuvsets,params,opposite); - //if we're not using shared geometry, save a pointer to the blend shape deformer - if (pBlendShape && !params.useSharedGeom) - pSubmesh->m_pBlendShape = pBlendShape; - //add submesh to current mesh - m_submeshes.push_back(pSubmesh); - //update number of triangles composing the mesh - m_numTriangles += pSubmesh->numTriangles(); - } - } - return MS::kSuccess; - } - - -/******************** Methods to read vertex animations from Maya ************************/ - //load a vertex animation clip - MStatus Mesh::loadClip(MString& clipName,float start,float stop,float rate,ParamList& params) - { - MStatus stat; - MString msg; - std::vector times; - // calculate times from clip sample rate - times.clear(); - for (float t=start; t= 0) - length = times[times.size()-1] - times[0]; - if (length < 0) - { - std::cout << "invalid time range for the clip, we skip it\n"; - std::cout.flush(); - return MS::kFailure; - } - // create a new animation - Animation a; - a.m_name = clipName; - a.m_length = length; - a.m_tracks.clear(); - // if we're using shared geometry, create a single animation track for the whole mesh - if (params.useSharedGeom) - { - // load the animation track - stat = loadMeshTrack(a,times,params); - if (stat != MS::kSuccess) - { - std::cout << "Error loading mesh vertex animation\n"; - std::cout.flush(); - } - } - // else creae a different animation track for each submesh - else - { - // load all tracks (one for each submesh) - stat = loadSubmeshTracks(a,times,params); - if (stat != MS::kSuccess) - { - std::cout << "Error loading submeshes vertex animation\n"; - std::cout.flush(); - return MS::kFailure; - } - } - // add newly created animation to animations list - m_vertexClips.push_back(a); - // display info - std::cout << "length: " << a.m_length << "\n"; - std::cout << "num keyframes: " << a.m_tracks[0].m_vertexKeyframes.size() << "\n"; - std::cout.flush(); - // clip successfully loaded - return MS::kSuccess; - } - - - //load an animation track for the whole mesh (using shared geometry) - MStatus Mesh::loadMeshTrack(Animation& a,std::vector ×, OgreMayaExporter::ParamList ¶ms) - { - MStatus stat; - // create a new track - Track t; - t.m_type = TT_MORPH; - t.m_target = T_MESH; - t.m_vertexKeyframes.clear(); - // get keyframes at given times - for (int i=0; i ×, OgreMayaExporter::ParamList ¶ms) - { - MStatus stat; - // create a new track for each submesh - std::vector tracks; - for (int i=0; iloadKeyframe(tracks[j],times[i]-times[0],params); - if (stat != MS::kSuccess) - { - std::cout << "Error reading animation keyframe at time: " << times[i] << " for submesh: " << j << "\n"; - std::cout.flush(); - } - } - } - // add tracks to given animation - for (int i=0; i< tracks.size(); i++) - a.addTrack(tracks[i]); - // track sucessfully loaded - return MS::kSuccess; - return MS::kSuccess; - } - - - // Load a keyframe for the whole mesh - MStatus Mesh::loadKeyframe(Track& t,float time,ParamList& params) - { - // create a new keyframe - vertexKeyframe k; - // set keyframe time - k.time = time; - for (int i=0; icreateOgreSubmesh(pMesh,params); - } - // Set skeleton link (if present) - if (m_pSkeleton && params.exportSkeleton) - { - int ri = params.skeletonFilename.rindex('\\'); - int end = params.skeletonFilename.length() - 1; - MString filename = params.skeletonFilename.substring(ri+1,end); - pMesh->setSkeletonName(filename.asChar()); - } - // Write poses - if (params.exportBlendShapes) - { - createOgrePoses(pMesh,params); - } - // Write vertex animations - if (params.exportVertAnims) - { - createOgreVertexAnimations(pMesh,params); - } - // Write pose animations - if (params.exportBSAnims) - { - createOgrePoseAnimations(pMesh,params); - } - // Create a bounding box for the mesh - Ogre::AxisAlignedBox bbox = pMesh->getBounds(); - for(int i=0; im_boundingBox.min(); - MPoint max1 = m_submeshes[i]->m_boundingBox.max(); - Ogre::Vector3 min2(min1.x,min1.y,min1.z); - Ogre::Vector3 max2(max1.x,max1.y,max1.z); - Ogre::AxisAlignedBox newbbox; - newbbox.setExtents(min2,max2); - bbox.merge(newbbox); - } - // Define mesh bounds - pMesh->_setBounds(bbox,false); - // Build edges list - if (params.buildEdges) - { - pMesh->buildEdgeList(); - } - // Build tangents - if (params.buildTangents) - { - Ogre::VertexElementSemantic targetSemantic = params.tangentSemantic == TS_TANGENT ? - Ogre::VES_TANGENT : Ogre::VES_TEXTURE_COORDINATES; - bool canBuild = true; - unsigned short srcTex, destTex; - try { - canBuild = !pMesh->suggestTangentVectorBuildParams(targetSemantic, srcTex, destTex); - } catch(Ogre::Exception e) { - canBuild = false; - } - if (canBuild) - pMesh->buildTangentVectors(targetSemantic, srcTex, destTex, - params.tangentsSplitMirrored, params.tangentsSplitRotated, params.tangentsUseParity); - } - // Export the binary mesh - Ogre::MeshSerializer serializer; - serializer.exportMesh(pMesh.get(),params.meshFilename.asChar()); - pMesh.reset(); - return MS::kSuccess; - } - - // Create shared geometry data for an Ogre mesh - MStatus Mesh::createOgreSharedGeometry(Ogre::MeshPtr pMesh,ParamList& params) - { - MStatus stat; - pMesh->sharedVertexData = new Ogre::VertexData(); - pMesh->sharedVertexData->vertexCount = m_sharedGeom.vertices.size(); - // Define a new vertex declaration - Ogre::VertexDeclaration* pDecl = new Ogre::VertexDeclaration(); - pMesh->sharedVertexData->vertexDeclaration = pDecl; - unsigned buf = 0; - size_t offset = 0; - // Add vertex position - pDecl->addElement(buf,offset,Ogre::VET_FLOAT3,Ogre::VES_POSITION); - offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3); - // Add vertex normal - if (params.exportVertNorm) - { - pDecl->addElement(buf, offset, Ogre::VET_FLOAT3, Ogre::VES_NORMAL); - offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3); - } - // Add vertex colour - if (params.exportVertCol) - { - pDecl->addElement(buf, offset, Ogre::VET_COLOUR, Ogre::VES_DIFFUSE); - offset += Ogre::VertexElement::getTypeSize(Ogre::VET_COLOUR); - } - // Add texture coordinates - for (int i=0; iaddElement(buf, offset, uvType, Ogre::VES_TEXTURE_COORDINATES, i); - offset += Ogre::VertexElement::getTypeSize(uvType); - } - // Get optimal vertex declaration - Ogre::VertexDeclaration* pOptimalDecl = pDecl->getAutoOrganisedDeclaration(params.exportVBA,params.exportBlendShapes || params.exportVertAnims); - // Create the vertex buffer using the newly created vertex declaration - stat = createOgreVertexBuffer(pMesh,pDecl,m_sharedGeom.vertices); - // Write vertex bone assignements list - if (params.exportVBA) - { - // Create a new vertex bone assignements list - Ogre::Mesh::VertexBoneAssignmentList vbas; - // Scan list of shared geometry vertices - for (int i=0; i 0.0f) - vbas.insert(Ogre::Mesh::VertexBoneAssignmentList::value_type(i, vba)); - } - } - // Rationalise the bone assignements list - pMesh->_rationaliseBoneAssignments(pMesh->sharedVertexData->vertexCount,vbas); - // Add bone assignements to the mesh - for (Ogre::Mesh::VertexBoneAssignmentList::iterator bi = vbas.begin(); bi != vbas.end(); bi++) - { - pMesh->addBoneAssignment(bi->second); - } - pMesh->_compileBoneAssignments(); - pMesh->_updateCompiledBoneAssignments(); - } - // Reorganize vertex buffers - pMesh->sharedVertexData->reorganiseBuffers(pOptimalDecl); - - return MS::kSuccess; - } - - // Create an Ogre compatible vertex buffer - MStatus Mesh::createOgreVertexBuffer(Ogre::MeshPtr pMesh,Ogre::VertexDeclaration* pDecl,const std::vector& vertices) - { - Ogre::HardwareVertexBufferSharedPtr vbuf = - Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(pDecl->getVertexSize(0), - pMesh->sharedVertexData->vertexCount, - Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY); - pMesh->sharedVertexData->vertexBufferBinding->setBinding(0, vbuf); - size_t vertexSize = pDecl->getVertexSize(0); - char* pBase = static_cast(vbuf->lock(Ogre::HardwareBuffer::HBL_DISCARD)); - Ogre::VertexDeclaration::VertexElementList elems = pDecl->findElementsBySource(0); - Ogre::VertexDeclaration::VertexElementList::iterator ei, eiend; - eiend = elems.end(); - float* pFloat; - Ogre::RGBA* pRGBA; - // Fill the vertex buffer with shared geometry data - Ogre::ColourValue col; - float ucoord, vcoord; - for (long vi=0; viunlock(); - return MS::kSuccess; - } - // Create mesh poses for an Ogre mesh - MStatus Mesh::createOgrePoses(Ogre::MeshPtr pMesh,ParamList& params) - { - int poseCounter = 0; - if (params.useSharedGeom) - { - // Create an entry in the submesh pose remapping table for the shared geometry - submeshPoseRemapping new_sbr; - m_poseRemapping.insert(std::pair(0,new_sbr)); - submeshPoseRemapping& sbr = m_poseRemapping.find(0)->second; - // Read poses associated from all blendshapes associated to the shared geometry - for (int i=0; igetPoseGroups().find(0)->second; - for (int j=0; jname == "") - { - p->name = "pose"; - p->name += poseCounter; - } - // Create a new pose for the ogre mesh - Ogre::Pose* pPose = pMesh->createPose(0,p->name.asChar()); - // Set the pose attributes - for (int k=0; koffsets.size(); k++) - { - Ogre::Vector3 offset(p->offsets[k].x,p->offsets[k].y,p->offsets[k].z); - pPose->addVertex(p->offsets[k].index,offset); - } - // Add a pose remapping for current pose - sbr.insert(std::pair(poseCounter,poseCounter)); - poseCounter++; - } - } - } - } - else - { - // Get poses associated to the submeshes - for (int i=0; im_pBlendShape; - // Check if this submesh has a blend shape deformer associated - if (pBS) - { - // Create an entry in the submesh pose remapping table for this submesh - submeshPoseRemapping new_sbr; - m_poseRemapping.insert(std::pair(i+1,new_sbr)); - submeshPoseRemapping& sbr = m_poseRemapping.find(i+1)->second; - // Get the pose group corresponding to the current submesh - poseGroup& pg = pBS->getPoseGroups().find(i+1)->second; - // Get all poses from current blend shape deformer and current pose group - for (int j=0; jname == "") - { - p->name = "pose"; - p->name += poseCounter; - } - // Create a new pose for the ogre mesh - Ogre::Pose* pPose = pMesh->createPose(p->index,p->name.asChar()); - // Set the pose attributes - for (int k=0; koffsets.size(); k++) - { - Ogre::Vector3 offset(p->offsets[k].x,p->offsets[k].y,p->offsets[k].z); - pPose->addVertex(p->offsets[k].index,offset); - } - // Add a pose remapping for current pose - sbr.insert(std::pair(j,poseCounter)); - - poseCounter++; - } - } - } - } - return MS::kSuccess; - } - // Create vertex animations for an Ogre mesh - MStatus Mesh::createOgreVertexAnimations(Ogre::MeshPtr pMesh,ParamList& params) - { - // Read the list of vertex animation clips - for (int i=0; icreateAnimation(m_vertexClips[i].m_name.asChar(),m_vertexClips[i].m_length); - // Create all tracks for current animation - for (int j=0; jm_target == T_MESH) - pTrack = pAnimation->createVertexTrack(0,pMesh->sharedVertexData,Ogre::VAT_MORPH); - else - { - pTrack = pAnimation->createVertexTrack(t->m_index+1,pMesh->getSubMesh(t->m_index)->vertexData, - Ogre::VAT_MORPH); - } - // Create keyframes for current track - for (int k=0; km_vertexKeyframes.size(); k++) - { - // Create a new keyframe - Ogre::VertexMorphKeyFrame* pKeyframe = pTrack->createVertexMorphKeyFrame(t->m_vertexKeyframes[k].time); - // Create vertex buffer for current keyframe - Ogre::HardwareVertexBufferSharedPtr pBuffer = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer( - Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3), - t->m_vertexKeyframes[k].positions.size(), - Ogre::HardwareBuffer::HBU_STATIC, true); - float* pFloat = static_cast(pBuffer->lock(Ogre::HardwareBuffer::HBL_DISCARD)); - // Fill the vertex buffer with vertex positions - std::vector& positions = t->m_vertexKeyframes[k].positions; - for (int vi=0; vi(positions[vi].x); - *pFloat++ = static_cast(positions[vi].y); - *pFloat++ = static_cast(positions[vi].z); - } - // Unlock vertex buffer - pBuffer->unlock(); - // Set vertex buffer for current keyframe - pKeyframe->setVertexBuffer(pBuffer); - } - } - } - return MS::kSuccess; - } - // Create pose animations for an Ogre mesh - MStatus Mesh::createOgrePoseAnimations(Ogre::MeshPtr pMesh,ParamList& params) - { - // Get all loaded blend shape clips - for (int i=0; icreateAnimation(m_BSClips[i].m_name.asChar(),m_BSClips[i].m_length); - // Create animation tracks for this animation - for (int j=0; jm_target == T_MESH) - pTrack = pAnimation->createVertexTrack(0,pMesh->sharedVertexData,Ogre::VAT_POSE); - else - { - pTrack = pAnimation->createVertexTrack(t->m_index,pMesh->getSubMesh(t->m_index-1)->vertexData, - Ogre::VAT_POSE); - } - // Create keyframes for current track - for (int k=0; km_vertexKeyframes.size(); k++) - { - Ogre::VertexPoseKeyFrame* pKeyframe = pTrack->createVertexPoseKeyFrame(t->m_vertexKeyframes[k].time); - for (int pri=0; prim_vertexKeyframes[k].poserefs.size(); pri++) - { - vertexPoseRef* pr = &t->m_vertexKeyframes[k].poserefs[pri]; - // Get the correct absolute index of the pose from the remapping - int poseIndex = m_poseRemapping.find(t->m_index)->second.find(pr->poseIndex)->second; - pKeyframe->addPoseReference(poseIndex,pr->poseWeight); - } - } - } - } - return MS::kSuccess; - } - -}; //end of namespace diff --git a/Tools/MayaExport/src/ogreExporter.cpp b/Tools/MayaExport/src/ogreExporter.cpp deleted file mode 100644 index f14f270e929..00000000000 --- a/Tools/MayaExport/src/ogreExporter.cpp +++ /dev/null @@ -1,585 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// ogreExporter.cpp -// Author : Francesco Giordana -// Sponsored by : Anygma N.V. (http://www.nazooka.com) -// Start Date : January 13, 2005 -// Copyright : (C) 2006 by Francesco Giordana -// Email : fra.giordana@tiscali.it -//////////////////////////////////////////////////////////////////////////////// - -/********************************************************************************* -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Lesser General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -**********************************************************************************/ - -#include "OgreExporter.h" - -namespace OgreMayaExporter -{ - OgreExporter::~OgreExporter() - { - exit(); - } - // Restore the scene to a state previous to the export, clean up memory and exit - void OgreExporter::exit() - { - // Restore active selection list - MGlobal::setActiveSelectionList(m_selList); - // Restore current time - MAnimControl::setCurrentTime(m_curTime); - // Free memory - delete m_pMesh; - m_pMesh = 0; - delete m_pMaterialSet; - m_pMaterialSet = 0; - // Close output files - m_params.closeFiles(); - std::cout.flush(); - } - - // Execute the command - MStatus OgreExporter::doIt(const MArgList& args) - { - // clean up - delete m_pMesh; - delete m_pMaterialSet; - - // Parse the arguments. - m_params.parseArgs(args); - // Create output files - m_params.openFiles(); - // Create a new empty mesh - m_pMesh = new Mesh(); - // Create a new empty material set - m_pMaterialSet = new MaterialSet(); - // Save current time for later restore - m_curTime = MAnimControl::currentTime(); - // Save active selection list for later restore - MGlobal::getActiveSelectionList(m_selList); - /**************************** LOAD DATA **********************************/ - if (m_params.exportAll) - { // We are exporting the whole scene - std::cout << "Export the whole scene\n"; - std::cout.flush(); - MItDag dagIter; - MFnDagNode worldDag (dagIter.root()); - MDagPath worldPath; - worldDag.getPath(worldPath); - stat = translateNode(worldPath); - } - else - { // We are translating a selection - std::cout << "Export selected objects\n"; - std::cout.flush(); - // Get the selection list - MSelectionList activeList; - stat = MGlobal::getActiveSelectionList(activeList); - if (MS::kSuccess != stat) - { - std::cout << "Error retrieving selection list\n"; - std::cout.flush(); - exit(); - return MS::kFailure; - } - MItSelectionList iter(activeList); - - for ( ; !iter.isDone(); iter.next()) - { - MDagPath dagPath; - stat = iter.getDagPath(dagPath); - stat = translateNode(dagPath); - } - } - - // Load vertex animations - if (m_params.exportVertAnims) - m_pMesh->loadAnims(m_params); - - // Load blend shapes - if (m_params.exportBlendShapes) - m_pMesh->loadBlendShapes(m_params); - - // Restore skeleton to correct pose - if (m_pMesh->getSkeleton()) - m_pMesh->getSkeleton()->restorePose(); - - // Load skeleton animation (do it now, so we have loaded all needed joints) - if (m_pMesh->getSkeleton() && m_params.exportSkelAnims) - { - // Load skeleton animations - m_pMesh->getSkeleton()->loadAnims(m_params); - } - - /**************************** WRITE DATA **********************************/ - stat = writeOgreData(); - - std::cout << "Export completed succesfully\n"; - std::cout.flush(); - exit(); - - return MS::kSuccess; - } - - - /**************************** TRANSLATE A NODE **********************************/ - // Method for iterating over nodes in a dependency graph from top to bottom - MStatus OgreExporter::translateNode(MDagPath& dagPath) - { - if (m_params.exportAnimCurves) - { - MObject dagPathNode = dagPath.node(); - MItDependencyGraph animIter( dagPathNode, - MFn::kAnimCurve, - MItDependencyGraph::kUpstream, - MItDependencyGraph::kDepthFirst, - MItDependencyGraph::kNodeLevel, - &stat ); - - if (stat) - { - for (; !animIter.isDone(); animIter.next()) - { - MObject anim = animIter.thisNode(&stat); - MFnAnimCurve animFn(anim,&stat); - std::cout << "Found animation curve: " << animFn.name().asChar() << "\n"; - std::cout << "Translating animation curve: " << animFn.name().asChar() << "...\n"; - std::cout.flush(); - stat = writeAnim(animFn); - if (MS::kSuccess == stat) - { - std::cout << "OK\n"; - std::cout.flush(); - } - else - { - std::cout << "Error, Aborting operation\n"; - std::cout.flush(); - return MS::kFailure; - } - } - } - } - if (dagPath.hasFn(MFn::kMesh)&&(m_params.exportMesh||m_params.exportMaterial||m_params.exportSkeleton) - && (dagPath.childCount() == 0)) - { // we have found a mesh shape node, it can't have any children, and it contains - // all the mesh geometry data - MDagPath meshDag = dagPath; - MFnMesh meshFn(meshDag); - if (!meshFn.isIntermediateObject()) - { - std::cout << "Found mesh node: " << meshDag.fullPathName().asChar() << "\n"; - std::cout << "Loading mesh node " << meshDag.fullPathName().asChar() << "...\n"; - std::cout.flush(); - stat = m_pMesh->load(meshDag,m_params); - if (MS::kSuccess == stat) - { - std::cout << "OK\n"; - std::cout.flush(); - } - else - { - std::cout << "Error, mesh skipped\n"; - std::cout.flush(); - } - } - } - else if (dagPath.hasFn(MFn::kCamera)&&(m_params.exportCameras) && (!dagPath.hasFn(MFn::kShape))) - { // we have found a camera shape node, it can't have any children, and it contains - // all information about the camera - MFnCamera cameraFn(dagPath); - if (!cameraFn.isIntermediateObject()) - { - std::cout << "Found camera node: "<< dagPath.fullPathName().asChar() << "\n"; - std::cout << "Translating camera node: "<< dagPath.fullPathName().asChar() << "...\n"; - std::cout.flush(); - stat = writeCamera(cameraFn); - if (MS::kSuccess == stat) - { - std::cout << "OK\n"; - std::cout.flush(); - } - else - { - std::cout << "Error, Aborting operation\n"; - std::cout.flush(); - return MS::kFailure; - } - } - } - else if ( ( dagPath.apiType() == MFn::kParticle ) && m_params.exportParticles ) - { // we have found a set of particles - MFnDagNode fnNode(dagPath); - if (!fnNode.isIntermediateObject()) - { - std::cout << "Found particles node: "<< dagPath.fullPathName().asChar() << "\n"; - std::cout << "Translating particles node: "<< dagPath.fullPathName().asChar() << "...\n"; - std::cout.flush(); - Particles particles; - particles.load(dagPath,m_params); - stat = particles.writeToXML(m_params); - if (MS::kSuccess == stat) - { - std::cout << "OK\n"; - std::cout.flush(); - } - else - { - std::cout << "Error, Aborting operation\n"; - std::cout.flush(); - return MS::kFailure; - } - } - } - // look for meshes and cameras within the node's children - for (uint i=0; ipartialPathName().asChar() << "\n"; - m_params.outCameras << "{\n"; - - //write camera type - m_params.outCameras << "\ttype "; - if (camera.isOrtho()) - m_params.outCameras << "ortho\n"; - else - m_params.outCameras << "persp\n"; - - // write translation data - m_params.outCameras << "\ttranslation\n"; - m_params.outCameras << "\t{\n"; - //translateX - m_params.outCameras << "\t\tx "; - plug = cameraTransform->findPlug("translateX"); - if (plug.isConnected() && m_params.exportCamerasAnim) - { - plug.connectedTo(srcplugarray,true,false,&stat); - for (int i=0; i < srcplugarray.length(); i++) - { - if (srcplugarray[i].node().hasFn(MFn::kAnimCurve)) - { - if (animCurve) - delete animCurve; - animCurve = new MFnAnimCurve(srcplugarray[i].node()); - continue; - } - else if (i == srcplugarray.length()-1) - { - std::cout << "Invalid link to translateX attribute\n"; - return MS::kFailure; - } - } - m_params.outCameras << "anim " << animCurve->name().asChar() << "\n"; - } - else - { - plug.getValue(dist); - m_params.outCameras << "= " << dist << "\n"; - } - //translateY - m_params.outCameras << "\t\ty "; - plug = cameraTransform->findPlug("translateY"); - if (plug.isConnected() && m_params.exportCamerasAnim) - { - plug.connectedTo(srcplugarray,true,false,&stat); - for (int i=0; i< srcplugarray.length(); i++) - { - if (srcplugarray[i].node().hasFn(MFn::kAnimCurve)) - { - if (animCurve) - delete animCurve; - animCurve = new MFnAnimCurve(srcplugarray[i].node()); - continue; - } - else if (i == srcplugarray.length()-1) - { - std::cout << "Invalid link to translateY attribute\n"; - return MS::kFailure; - } - } - m_params.outCameras << "anim " << animCurve->name().asChar() << "\n"; - } - else - { - plug.getValue(dist); - m_params.outCameras << "= " << dist << "\n"; - } - //translateZ - m_params.outCameras << "\t\tz "; - plug = cameraTransform->findPlug("translateZ"); - if (plug.isConnected() && m_params.exportCamerasAnim) - { - plug.connectedTo(srcplugarray,true,false,&stat); - for (int i=0; i< srcplugarray.length(); i++) - { - if (srcplugarray[i].node().hasFn(MFn::kAnimCurve)) - { - if (animCurve) - delete animCurve; - animCurve = new MFnAnimCurve(srcplugarray[i].node()); - continue; - } - else if (i == srcplugarray.length()-1) - { - std::cout << "Invalid link to translateZ attribute\n"; - return MS::kFailure; - } - } - m_params.outCameras << "anim " << animCurve->name().asChar() << "\n"; - } - else - { - plug.getValue(dist); - m_params.outCameras << "= " << dist << "\n"; - } - m_params.outCameras << "\t}\n"; - - // write rotation data - m_params.outCameras << "\trotation\n"; - m_params.outCameras << "\t{\n"; - m_params.outCameras << "\t\tx "; - //rotateX - plug = cameraTransform->findPlug("rotateX"); - if (plug.isConnected() && m_params.exportCamerasAnim) - { - plug.connectedTo(srcplugarray,true,false,&stat); - for (int i=0; i< srcplugarray.length(); i++) - { - if (srcplugarray[i].node().hasFn(MFn::kAnimCurve)) - { - if (animCurve) - delete animCurve; - animCurve = new MFnAnimCurve(srcplugarray[i].node()); - continue; - } - else if (i == srcplugarray.length()-1) - { - std::cout << "Invalid link to rotateX attribute\n"; - return MS::kFailure; - } - } - m_params.outCameras << "anim " << animCurve->name().asChar() << "\n"; - } - else - { - plug.getValue(angle); - m_params.outCameras << "= " << angle.asDegrees() << "\n"; - } - //rotateY - m_params.outCameras << "\t\ty "; - plug = cameraTransform->findPlug("rotateY"); - if (plug.isConnected() && m_params.exportCamerasAnim) - { - plug.connectedTo(srcplugarray,true,false,&stat); - for (int i=0; i< srcplugarray.length(); i++) - { - if (srcplugarray[i].node().hasFn(MFn::kAnimCurve)) - { - if (animCurve) - delete animCurve; - animCurve = new MFnAnimCurve(srcplugarray[i].node()); - continue; - } - else if (i == srcplugarray.length()-1) - { - std::cout << "Invalid link to rotateY attribute\n"; - return MS::kFailure; - } - } - m_params.outCameras << "anim " << animCurve->name().asChar() << "\n"; - } - else - { - plug.getValue(angle); - m_params.outCameras << "= " << angle.asDegrees() << "\n"; - } - //rotateZ - m_params.outCameras << "\t\tz "; - plug = cameraTransform->findPlug("rotateZ"); - if (plug.isConnected() && m_params.exportCamerasAnim) - { - plug.connectedTo(srcplugarray,true,false,&stat); - for (int i=0; i< srcplugarray.length(); i++) - { - if (srcplugarray[i].node().hasFn(MFn::kAnimCurve)) - { - if (animCurve) - delete animCurve; - animCurve = new MFnAnimCurve(srcplugarray[i].node()); - continue; - } - else if (i == srcplugarray.length()-1) - { - std::cout << "Invalid link to rotateZ attribute\n"; - return MS::kFailure; - } - } - m_params.outCameras << "anim " << animCurve->name().asChar() << "\n"; - } - else - { - plug.getValue(angle); - m_params.outCameras << "= " << angle.asDegrees() << "\n"; - } - m_params.outCameras << "\t}\n"; - - // end camera description - m_params.outCameras << "}\n\n"; - if (cameraTransform != NULL) - delete cameraTransform; - if (animCurve != NULL) - delete animCurve; - return MS::kSuccess; - } - - /******************************************************************************************************** - * Method to write data to OGRE format * - ********************************************************************************************************/ - MStatus OgreExporter::writeOgreData() - { - // Create singletons - Ogre::LogManager logMgr; - Ogre::ResourceGroupManager rgm; - Ogre::MeshManager meshMgr; - Ogre::SkeletonManager skelMgr; - Ogre::MaterialManager matMgr; - Ogre::DefaultHardwareBufferManager hardwareBufMgr; - - // Create a log - logMgr.createLog("ogreMayaExporter.log", true); - - // Write mesh binary - if (m_params.exportMesh) - { - std::cout << "Writing mesh binary...\n"; - std::cout.flush(); - stat = m_pMesh->writeOgreBinary(m_params); - if (stat != MS::kSuccess) - { - std::cout << "Error writing mesh binary file\n"; - std::cout.flush(); - } - } - - // Write skeleton binary - if (m_params.exportSkeleton) - { - if (m_pMesh->getSkeleton()) - { - std::cout << "Writing skeleton binary...\n"; - std::cout.flush(); - stat = m_pMesh->getSkeleton()->writeOgreBinary(m_params); - if (stat != MS::kSuccess) - { - std::cout << "Error writing mesh binary file\n"; - std::cout.flush(); - } - } - } - - // Write materials data - if (m_params.exportMaterial) - { - std::cout << "Writing materials data...\n"; - std::cout.flush(); - stat = m_pMaterialSet->writeOgreScript(m_params); - if (stat != MS::kSuccess) - { - std::cout << "Error writing materials file\n"; - std::cout.flush(); - } - } - - return MS::kSuccess; - } - -} // end namespace - - -// Routine for registering the command within Maya -MStatus initializePlugin( MObject obj ) -{ - MStatus status; - MFnPlugin plugin( obj, "OgreExporter", "7.0", "Any"); - status = plugin.registerCommand( "ogreExport", OgreMayaExporter::OgreExporter::creator ); - if (!status) { - status.perror("registerCommand"); - return status; - } - - return status; -} - -// Routine for unregistering the command within Maya -MStatus uninitializePlugin( MObject obj) -{ - MStatus status; - MFnPlugin plugin( obj ); - status = plugin.deregisterCommand( "ogreExport" ); - if (!status) { - status.perror("deregisterCommand"); - return status; - } - - return status; -} - diff --git a/Tools/MayaExport/src/paramlist.cpp b/Tools/MayaExport/src/paramlist.cpp deleted file mode 100644 index fd350ca590f..00000000000 --- a/Tools/MayaExport/src/paramlist.cpp +++ /dev/null @@ -1,473 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// paramlist.cpp -// Author : Francesco Giordana -// Sponsored by : Anygma N.V. (http://www.nazooka.com) -// Start Date : January 13, 2005 -// Copyright : (C) 2006 by Francesco Giordana -// Email : fra.giordana@tiscali.it -//////////////////////////////////////////////////////////////////////////////// - -/********************************************************************************* -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Lesser General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -**********************************************************************************/ - -#include "paramlist.h" -#include - -/***** Class ParamList *****/ -// method to parse arguments from command line -namespace OgreMayaExporter -{ - void ParamList::parseArgs(const MArgList &args) - { - MStatus stat; - // Parse arguments from command line - for (uint i=0; i < args.length(); i++ ) - { - if ((MString("-all") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - exportAll = true; - else if ((MString("-world") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - exportWorldCoords = true; - else if ((MString("-lu") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - MString lengthUnit = args.asString(++i,&stat); - if (MString("pref") == lengthUnit) - { - MGlobal::executeCommand("currentUnit -q -l",lengthUnit,false); - } - if (MString("mm") == lengthUnit) - lum = CM2MM; - else if (MString("cm") == lengthUnit) - lum = CM2CM; - else if (MString("m") == lengthUnit) - lum = CM2M; - else if (MString("in") == lengthUnit) - lum = CM2IN; - else if (MString("ft") == lengthUnit) - lum = CM2FT; - else if (MString("yd") == lengthUnit) - lum = CM2YD; - } - else if ((MString("-scale") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - float s = args.asDouble(++i,&stat); - lum *= s; - } - else if ((MString("-mesh") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - exportMesh = true; - meshFilename = args.asString(++i,&stat); - } - else if ((MString("-mat") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - exportMaterial = true; - materialFilename = args.asString(++i,&stat); - } - else if ((MString("-matPrefix") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - matPrefix = args.asString(++i,&stat); - } - else if ((MString("-copyTex") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - copyTextures = true; - texOutputDir = args.asString(++i,&stat); - } - else if ((MString("-lightOff") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - lightingOff = true; - } - else if ((MString("-skel") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - exportSkeleton = true; - skeletonFilename = args.asString(++i,&stat); - } - else if ((MString("-skeletonAnims") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - exportSkelAnims = true; - } - else if ((MString("-vertexAnims") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - exportVertAnims = true; - } - else if ((MString("-blendShapes") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - exportBlendShapes = true; - } - else if ((MString("-BSAnims") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - exportBSAnims = true; - } - else if ((MString("-skelBB") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - skelBB = true; - } - else if ((MString("-bsBB") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - bsBB = true; - } - else if ((MString("-vertBB") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - vertBB = true; - } - else if ((MString("-animCur") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - exportAnimCurves = true; - animFilename = args.asString(++i,&stat); - } - else if ((MString("-cam") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - exportCameras = true; - camerasFilename = args.asString(++i,&stat); - } - else if ((MString("-v") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - exportVBA = true; - } - else if ((MString("-n") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - exportVertNorm = true; - } - else if ((MString("-c") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - exportVertCol = true; - } - else if ((MString("-t") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - exportTexCoord = true; - } - else if ((MString("-edges") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - buildEdges = true; - } - else if ((MString("-tangents") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - buildTangents = true; - MString tanSem = args.asString(++i,&stat); - if (tanSem == "TEXCOORD") - tangentSemantic = TS_TEXCOORD; - else if (tanSem == "TANGENT") - tangentSemantic = TS_TANGENT; - } - else if ((MString("-tangentsplitmirrored") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - tangentsSplitMirrored = true; - } - else if ((MString("-tangentsplitrotated") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - tangentsSplitRotated = true; - } - else if ((MString("-tangentuseparity") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - tangentsUseParity = true; - } - else if ((MString("-camAnim") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - exportCamerasAnim = true; - } - else if ((MString("-particles") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - exportParticles = true; - particlesFilename = args.asString(++i,&stat); - } - else if ((MString("-shared") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - useSharedGeom = true; - } - else if ((MString("-np") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - MString npType = args.asString(++i,&stat); - if (npType == "curFrame") - neutralPoseType = NPT_CURFRAME; - else if (npType == "bindPose") - neutralPoseType = NPT_BINDPOSE; - } - else if ((MString("-skeletonClip") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - //get clip name - MString clipName = args.asString(++i,&stat); - //check if name is unique, otherwise skip the clip - bool uniqueName = true; - for (int k=0; k convert to seconds - MTime t1(startTime, MTime::uiUnit()); - MTime t2(stopTime, MTime::uiUnit()); - startTime = t1.as(MTime::kSeconds); - stopTime = t2.as(MTime::kSeconds); - } - } - else - { - //range specified by time slider - MTime t1 = MAnimControl::minTime(); - MTime t2 = MAnimControl::maxTime(); - startTime = t1.as(MTime::kSeconds); - stopTime = t2.as(MTime::kSeconds); - } - // get sample rate - float rate; - MString sampleRateType = args.asString(++i,&stat); - if (sampleRateType == "sampleByFrames") - { - // rate specified in frames - int intRate = args.asInt(++i,&stat); - MTime t = MTime(intRate, MTime::uiUnit()); - rate = t.as(MTime::kSeconds); - } - else - { - // rate specified in seconds - rate = args.asDouble(++i,&stat); - } - //add clip info - clipInfo clip; - clip.name = clipName; - clip.start = startTime; - clip.stop = stopTime; - clip.rate = rate; - skelClipList.push_back(clip); - std::cout << "skeleton clip " << clipName.asChar() << "\n"; - std::cout << "start: " << startTime << ", stop: " << stopTime << "\n"; - std::cout << "rate: " << rate << "\n"; - std::cout << "-----------------\n"; - std::cout.flush(); - } - //warn of duplicate clip name - else - { - std::cout << "Warning! A skeleton clip with name \"" << clipName.asChar() << "\" already exists\n"; - std::cout.flush(); - } - } - else if ((MString("-BSClip") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - //get clip name - MString clipName = args.asString(++i,&stat); - //check if name is unique, otherwise skip the clip - bool uniqueName = true; - for (int k=0; k convert to seconds - MTime t1(startTime, MTime::uiUnit()); - MTime t2(stopTime, MTime::uiUnit()); - startTime = t1.as(MTime::kSeconds); - stopTime = t2.as(MTime::kSeconds); - } - } - else - { - //range specified by time slider - MTime t1 = MAnimControl::minTime(); - MTime t2 = MAnimControl::maxTime(); - startTime = t1.as(MTime::kSeconds); - stopTime = t2.as(MTime::kSeconds); - } - // get sample rate - float rate; - MString sampleRateType = args.asString(++i,&stat); - if (sampleRateType == "sampleByFrames") - { - // rate specified in frames - int intRate = args.asInt(++i,&stat); - MTime t = MTime(intRate, MTime::uiUnit()); - rate = t.as(MTime::kSeconds); - } - else - { - // rate specified in seconds - rate = args.asDouble(++i,&stat); - } - //add clip info - clipInfo clip; - clip.name = clipName; - clip.start = startTime; - clip.stop = stopTime; - clip.rate = rate; - BSClipList.push_back(clip); - std::cout << "blend shape clip " << clipName.asChar() << "\n"; - std::cout << "start: " << startTime << ", stop: " << stopTime << "\n"; - std::cout << "rate: " << rate << "\n"; - std::cout << "-----------------\n"; - std::cout.flush(); - } - //warn of duplicate clip name - else - { - std::cout << "Warning! A blend shape clip with name \"" << clipName.asChar() << "\" already exists\n"; - std::cout.flush(); - } - } - else if ((MString("-vertexClip") == args.asString(i,&stat)) && (MS::kSuccess == stat)) - { - //get clip name - MString clipName = args.asString(++i,&stat); - //check if name is unique, otherwise skip the clip - bool uniqueName = true; - for (int k=0; k convert to seconds - MTime t1(startTime, MTime::uiUnit()); - MTime t2(stopTime, MTime::uiUnit()); - startTime = t1.as(MTime::kSeconds); - stopTime = t2.as(MTime::kSeconds); - } - } - else - { - //range specified by time slider - MTime t1 = MAnimControl::minTime(); - MTime t2 = MAnimControl::maxTime(); - startTime = t1.as(MTime::kSeconds); - stopTime = t2.as(MTime::kSeconds); - } - // get sample rate - float rate; - MString sampleRateType = args.asString(++i,&stat); - if (sampleRateType == "sampleByFrames") - { - // rate specified in frames - int intRate = args.asInt(++i,&stat); - MTime t = MTime(intRate, MTime::uiUnit()); - rate = t.as(MTime::kSeconds); - } - else - { - // rate specified in seconds - rate = args.asDouble(++i,&stat); - } - //add clip info - clipInfo clip; - clip.name = clipName; - clip.start = startTime; - clip.stop = stopTime; - clip.rate = rate; - vertClipList.push_back(clip); - std::cout << "vertex clip " << clipName.asChar() << "\n"; - std::cout << "start: " << startTime << ", stop: " << stopTime << "\n"; - std::cout << "rate: " << rate << "\n"; - std::cout << "-----------------\n"; - std::cout.flush(); - } - //warn of duplicate clip name - else - { - std::cout << "Warning! A vertex animation clip with name \"" << clipName.asChar() << "\" already exists\n"; - std::cout.flush(); - } - } - } - } - - - // method to open output files for writing - MStatus ParamList::openFiles() - { - MString msg; - if (exportMaterial) - { - outMaterial.open(materialFilename.asChar()); - if (!outMaterial) - { - std::cout << "Error opening file: " << materialFilename.asChar() << "\n"; - return MS::kFailure; - } - } - if (exportAnimCurves) - { - outAnim.open(animFilename.asChar()); - if (!outAnim) - { - std::cout << "Error opening file: " << animFilename.asChar() << "\n"; - return MS::kFailure; - } - } - if (exportCameras) - { - outCameras.open(camerasFilename.asChar()); - if (!outCameras) - { - std::cout << "Error opening file: " << camerasFilename.asChar() << "\n"; - return MS::kFailure; - } - } - if (exportParticles) - { - outParticles.open(particlesFilename.asChar()); - if (!outParticles) - { - std::cout << "Error opening file: " << particlesFilename.asChar() << "\n"; - return MS::kFailure; - } - } - return MS::kSuccess; - } - - // method to close open output files - MStatus ParamList::closeFiles() - { - if (exportMaterial) - outMaterial.close(); - - if (exportAnimCurves) - outAnim.close(); - - if (exportCameras) - outCameras.close(); - - return MS::kSuccess; - } - -} //end namespace \ No newline at end of file diff --git a/Tools/MayaExport/src/particles.cpp b/Tools/MayaExport/src/particles.cpp deleted file mode 100644 index 216ad4284bc..00000000000 --- a/Tools/MayaExport/src/particles.cpp +++ /dev/null @@ -1,352 +0,0 @@ -/**************************************************************** - Thanks to Bandures for the particle exporter - ****************************************************************/ - -/********************************************************************************* -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Lesser General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -**********************************************************************************/ - -#include "particles.h" - -//////////////////////////////////////////////////////////////////////////////////////////////////// -namespace OgreMayaExporter -{ -//////////////////////////////////////////////////////////////////////////////////////////////////// -const float FP_2PI = 6.28318531f; -static float FP_MINDELTA = 0.005f; -//////////////////////////////////////////////////////////////////////////////////////////////////// -inline float ToRadians( float fD ) { return fD * ( FP_2PI / 360.f ); } -inline float ToDegrees( float fR ) { return fR * ( 360.f / FP_2PI ); } -template void DropSame( const std::vector &values, int nBeginTime, TKeyTrack *pRes ); -template void MakeLinearSpline( const std::vector &values, int nBeginTime, float fEpsilon, TKeyTrack *pRes ); -template void writeTrackToXML( std::ofstream &outStream, const TKeyTrack &dataTrack, const std::string &name ); -//////////////////////////////////////////////////////////////////////////////////////////////////// -// Particles -//////////////////////////////////////////////////////////////////////////////////////////////////// -Particles::Particles(): - nFrames(0) -{ -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -Particles::~Particles() -{ - clear(); -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -MStatus Particles::load( MDagPath& dagPath, ParamList& params ) -{ - int nMaxFrame, nMinFrame; - MGlobal::executeCommand( "playbackOptions -q -max", nMaxFrame ); - MGlobal::executeCommand( "playbackOptions -q -min", nMinFrame ); - if ( nMinFrame > 0 ) - nMinFrame = 0; - - for ( int nFrame = nMinFrame; nFrame <= nMaxFrame; ++nFrame ) - ExportFrame( dagPath, nFrame ); - - FinalizeData( nMinFrame, nMaxFrame ); - return MS::kSuccess; -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -MStatus Particles::writeToXML( ParamList& params ) -{ - params.outParticles << "\n"; - for ( uint nTemp = 0; nTemp < particleTracks.size(); ++nTemp ) - { - const SParticle &particle = particleTracks[nTemp]; - params.outParticles << "\t\n"; - writeTrackToXML( params.outParticles, particle.pos, "position" ); - writeTrackToXML( params.outParticles, particle.rotation, "rotation" ); - writeTrackToXML( params.outParticles, particle.scale, "scale" ); - writeTrackToXML( params.outParticles, particle.color, "color" ); - writeTrackToXML( params.outParticles, particle.sprite, "sprite" ); - params.outParticles << "\t\n"; - } - params.outParticles << "\n"; - return MS::kSuccess; -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -void Particles::clear() -{ -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -MStatus Particles::ExportFrame( MDagPath &dagPath, int nFrame ) -{ - MGlobal::viewFrame( nFrame ); - - MStatus retStatus; - MFnDagNode dagNode( dagPath ); - //// - int nParticles = 0; - MPlug countPlug = dagNode.findPlug( MString( "count" ), &retStatus ); - retStatus = countPlug.getValue( nParticles ); - if ( nParticles <= 0 ) - return MS::kFailure; - //// - std::vector idIndex( nParticles ); - std::vector sortedId( nParticles ); - std::vector particlesFrame( nParticles ); - //// - MObject tempObj; - MPlug mappingPlug = dagNode.findPlug( MString( "idMapping" ), &retStatus ); - //// - MPlug idPlug = mappingPlug.child( 0 ); - retStatus = idPlug.getValue( tempObj ); - MFnIntArrayData sSortedIDArray( tempObj, &retStatus ); - for ( int nTemp = 0; nTemp < nParticles; ++nTemp ) - sortedId[nTemp] = sSortedIDArray[nTemp]; - //// - MPlug indexPlug = mappingPlug.child( 1 ); - retStatus = indexPlug.getValue( tempObj ); - MFnIntArrayData idIndexArray( tempObj, &retStatus ); - for ( int nTemp = 0; nTemp < nParticles; ++nTemp ) - idIndex[nTemp] = idIndexArray[nTemp]; - //// Position - MPlug posPlug = dagNode.findPlug( MString( "worldPosition" ), &retStatus ); - retStatus = posPlug.getValue( tempObj ); - MFnVectorArrayData posData( tempObj, &retStatus ); - for ( int nTemp = 0; nTemp < nParticles; ++nTemp ) - { - SParticleData &particle = particlesFrame[nTemp]; - particle.nFrame = nFrame; - particle.pos.x = (float)posData[idIndex[nTemp]].x; - particle.pos.y = (float)posData[idIndex[nTemp]].y; - particle.pos.z = (float)posData[idIndex[nTemp]].z; - } - //// Rotation - MPlug rotPlug = dagNode.findPlug( MString( "spriteTwistPP" ), &retStatus ); - if ( retStatus == MS::kSuccess ) - { - retStatus = rotPlug.getValue( tempObj ); - MFnDoubleArrayData rotPlug( tempObj, &retStatus ); - for ( int nTemp = 0; nTemp < nParticles; ++nTemp ) - particlesFrame[nTemp].fRotation = ToRadians( (float)rotPlug[idIndex[nTemp]] ); - } - //// ScaleX - MPlug scaleXPlug = dagNode.findPlug( MString( "spriteScaleXPP" ), &retStatus ); - if ( retStatus == MS::kSuccess ) - { - retStatus = scaleXPlug.getValue( tempObj ); - MFnDoubleArrayData scaleX( tempObj, &retStatus ); - for ( int nTemp = 0; nTemp < nParticles; ++nTemp ) - particlesFrame[nTemp].scale.x = float( scaleX[idIndex[nTemp]] ); - } - //// ScaleY - MPlug scaleYPlug = dagNode.findPlug( MString( "spriteScaleYPP" ), &retStatus ); - if ( retStatus == MS::kSuccess ) - { - retStatus = scaleYPlug.getValue( tempObj ); - MFnDoubleArrayData scaleY( tempObj, &retStatus ); - for ( int nTemp = 0; nTemp < nParticles; ++nTemp ) - particlesFrame[nTemp].scale.y = float( scaleY[idIndex[nTemp]] ); - } - //// Sprite - MPlug spritePlug = dagNode.findPlug( MString( "spriteNumPP" ), &retStatus ); - if ( retStatus == MS::kSuccess ) - { - retStatus = spritePlug.getValue( tempObj ); - MFnDoubleArrayData sprite( tempObj, &retStatus ); - for ( int nTemp = 0; nTemp < nParticles; ++nTemp ) - particlesFrame[nTemp].nSprite = int( sprite[idIndex[nTemp]] - 1 ); - } - //// Color - MPlug colorPlug = dagNode.findPlug( MString( "rgbPP" ), &retStatus ); - if ( retStatus == MS::kSuccess ) - { - retStatus = colorPlug.getValue( tempObj ); - MFnVectorArrayData rgbData( tempObj, &retStatus ); - for ( int nTemp = 0; nTemp < nParticles; ++nTemp ) - { - particlesFrame[nTemp].color.r = float( rgbData[idIndex[nTemp]].x ); - particlesFrame[nTemp].color.g = float( rgbData[idIndex[nTemp]].y ); - particlesFrame[nTemp].color.b = float( rgbData[idIndex[nTemp]].z ); - } - } - //// Opacity - MPlug alphaPlug = dagNode.findPlug( MString( "opacityPP" ), &retStatus ); - if ( retStatus == MS::kSuccess ) - { - retStatus = alphaPlug.getValue( tempObj ); - MFnDoubleArrayData alphaData( tempObj, &retStatus ); - for ( int nTemp = 0; nTemp < nParticles; ++nTemp ) - particlesFrame[nTemp].color.a = float( alphaData[idIndex[nTemp]] ); - } - - for ( int nTemp = 0; nTemp < nParticles; ++nTemp ) - data[sortedId[nTemp]].push_back( particlesFrame[nTemp] ); - - return MS::kSuccess; -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -MStatus Particles::FinalizeData( int nMinFrame, int nMaxFrame ) -{ - nFrames = nMaxFrame - nMinFrame + 1; - particleTracks.resize( data.size() ); - - int nTemp = 0; - for ( CParticlesData::const_iterator iTemp = data.begin(); iTemp != data.end(); ++iTemp, ++nTemp ) - { - SParticle &particle = particleTracks[nTemp]; - //// - const CParticlesTrack &particlesTrack = iTemp->second; - int nEndFrame = particlesTrack.back().nFrame; - int nStartFrame = particlesTrack.front().nFrame; - int nFrames = nEndFrame - nStartFrame + 1; - //// - if ( nFrames != particlesTrack.size() ) - { - std::cout << "ERROR: particle dosn't exist in some frames (unsupported)!\n"; - std::cout.flush(); - return MS::kFailure; - } - //// - int nBeginTime = nStartFrame; - particle.nEndTime = nEndFrame; - particle.nStartTime = nStartFrame; - //// - std::vector tmpPos( nFrames ); - for ( int nTemp = 0; nTemp < nFrames; ++nTemp ) - tmpPos[nTemp] = particlesTrack[nTemp].pos; - MakeLinearSpline( tmpPos, nBeginTime, FP_MINDELTA, &particle.pos ); - //// - std::vector tmpRot( nFrames ); - for ( int nTemp = 0; nTemp < nFrames; ++nTemp ) - tmpRot[nTemp] = particlesTrack[nTemp].fRotation; - MakeLinearSpline( tmpRot, nBeginTime, FP_MINDELTA, &particle.rotation ); - //// - std::vector tmpScale( nFrames ); - for ( int nTemp = 0; nTemp < nFrames; ++nTemp ) - tmpScale[nTemp] = particlesTrack[nTemp].scale; - MakeLinearSpline( tmpScale, nBeginTime, FP_MINDELTA, &particle.scale ); - //// - std::vector tmpColor( nFrames ); - for ( int nTemp = 0; nTemp < nFrames; ++nTemp ) - tmpColor[nTemp] = particlesTrack[nTemp].color; - MakeLinearSpline( tmpColor, nBeginTime, FP_MINDELTA, &particle.color ); - //// - std::vector tmpSprite( nFrames ); - for ( int nTemp = 0; nTemp < nFrames; ++nTemp ) - tmpSprite[nTemp] = particlesTrack[nTemp].nSprite; - DropSame( tmpSprite, nBeginTime, &particle.sprite ); - } - - return MS::kSuccess; -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -template -bool CanDropValue( const T &value, const T &prevVal, const T &nextVal, int nDelta, int nRange, float fEpsilon ) -{ - T resVal; - float fCoeff = float( nDelta ) / nRange; - Interpolate( prevVal, nextVal, fCoeff, &resVal ); - if ( fabs( resVal - value ) < fEpsilon ) - return true; - //// - return false; -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -template -void MakeLinearSpline( const std::vector &values, int nBeginTime, float fEpsilon, TKeyTrack *pRes ) -{ - if ( values.size() == 0 ) - return; - //// - TKey startKey; - startKey.nTime = nBeginTime; - startKey.value = values.front(); - pRes->keys.push_back( startKey ); - if ( values.size() == 1 ) - return; - //// - uint nIndex = 0; - uint nPrevIndex = 0; - while( nIndex < values.size() - 1 ) - { - if ( !CanDropValue( values[nIndex], values[nPrevIndex], values[nIndex + 1], nIndex - nPrevIndex, nIndex - nPrevIndex + 1, fEpsilon ) ) - { - nPrevIndex = nIndex; - TKey resKey; - resKey.nTime = nBeginTime + nIndex; - resKey.value = values[nIndex]; - pRes->keys.push_back( resKey ); - } - //// - nIndex++; - } - //// - TKey endKey; - endKey.nTime = nBeginTime + values.size() - 1; - endKey.value = values.back(); - pRes->keys.push_back( endKey ); -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -template -void DropSame( const std::vector &values, int nBeginTime, TKeyTrack *pRes ) -{ - if ( values.size() == 0 ) - return; - //// - TKey startKey; - startKey.nTime = nBeginTime; - startKey.value = values.front(); - pRes->keys.push_back( startKey ); - if ( values.size() == 1 ) - return; - //// - T nCurrent = values.front(); - TKey curKey; - for ( uint nTemp = 1; nTemp < values.size() - 1; ++nTemp ) - { - if ( values[nTemp] != nCurrent ) - { - curKey.nTime = nBeginTime + nTemp; - curKey.value = values[nTemp]; - pRes->keys.push_back( curKey ); - //// - nCurrent = values[nTemp]; - } - } - //// - TKey endKey; - endKey.nTime = nBeginTime + values.size() - 1; - endKey.value = values.back(); - pRes->keys.push_back( endKey ); -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -template -void writeKeyToXML( std::ofstream &outStream, const TKey &data ) -{ - outStream << "\t\t\t\n"; -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -void writeKeyToXML( std::ofstream &outStream, const TKey &data ) -{ - outStream << "\t\t\t\n"; -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -void writeKeyToXML( std::ofstream &outStream, const TKey &data ) -{ - outStream << "\t\t\t\n"; -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -void writeKeyToXML( std::ofstream &outStream, const TKey &data ) -{ - outStream << "\t\t\t\n"; -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -template -void writeTrackToXML( std::ofstream &outStream, const TKeyTrack &dataTrack, const std::string &name ) -{ - outStream << "\t\t<" << name.c_str() << " keys=\"" << dataTrack.keys.size() << "\" >\n"; - for ( uint nTemp = 0; nTemp < dataTrack.keys.size(); ++nTemp ) - writeKeyToXML( outStream, dataTrack.keys[nTemp] ); - outStream << "\t\t\n"; -} -//////////////////////////////////////////////////////////////////////////////////////////////////// -} // NAMESPACE -//////////////////////////////////////////////////////////////////////////////////////////////////// \ No newline at end of file diff --git a/Tools/MayaExport/src/skeleton.cpp b/Tools/MayaExport/src/skeleton.cpp deleted file mode 100644 index 902b4fc3e22..00000000000 --- a/Tools/MayaExport/src/skeleton.cpp +++ /dev/null @@ -1,635 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// skeleton.cpp -// Author : Francesco Giordana -// Sponsored by : Anygma N.V. (http://www.nazooka.com) -// Start Date : January 13, 2005 -// Copyright : (C) 2006 by Francesco Giordana -// Email : fra.giordana@tiscali.it -//////////////////////////////////////////////////////////////////////////////// - -/********************************************************************************* -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Lesser General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -**********************************************************************************/ - -#include "skeleton.h" -#include "submesh.h" -#include -#include - -namespace OgreMayaExporter -{ - // Constructor - Skeleton::Skeleton() - { - m_joints.clear(); - m_animations.clear(); - m_restorePose = ""; - } - - - // Destructor - Skeleton::~Skeleton() - { - clear(); - } - - - // Clear skeleton data - void Skeleton::clear() - { - m_joints.clear(); - m_animations.clear(); - m_restorePose = ""; - } - - - // Load skeleton data from given skin cluster - MStatus Skeleton::load(MFnSkinCluster* pSkinCluster,ParamList& params) - { - MStatus stat; - //check for valid skin cluster pointer - if (!pSkinCluster) - { - std::cout << "Could not load skeleton data, no skin cluster specified\n"; - std::cout.flush(); - return MS::kFailure; - } - //retrieve and load joints from the skin cluster - MDagPath jointDag,rootDag; - MDagPathArray influenceDags; - int numInfluenceObjs = pSkinCluster->influenceObjects(influenceDags,&stat); - std::cout << "num influence objects: " << numInfluenceObjs << "\n"; - std::cout.flush(); - for (int i=0; i0) - { - jointDag.pop(); - if (jointDag.hasFn(MFn::kJoint) && jointDag.length()>0) - rootDag = jointDag; - } - //check if skeleton has already been loaded - bool skip = false; - for (int j=0; jname.asChar() << ")\n"; - std::cout.flush(); - } - else - { - std::cout << "\n"; - std::cout.flush(); - } - // Get parent index - int idx=-1; - if (parent) - { - for (int i=0; iname) - idx=i; - } - } - // Get world bind matrix - MMatrix bindMatrix = jointDag.inclusiveMatrix();; - // Calculate local bind matrix - MMatrix localMatrix; - if (parent) - localMatrix = bindMatrix * parent->bindMatrix.inverse(); - else - { // root node of skeleton - localMatrix = bindMatrix; - } - // Get translation - MVector translation = ((MTransformationMatrix)localMatrix).translation(MSpace::kPostTransform); - if (fabs(translation.x) < PRECISION) - translation.x = 0; - if (fabs(translation.y) < PRECISION) - translation.y = 0; - if (fabs(translation.z) < PRECISION) - translation.z = 0; - // Calculate rotation data - double qx,qy,qz,qw; - ((MTransformationMatrix)localMatrix).getRotationQuaternion(qx,qy,qz,qw); - MQuaternion rotation(qx,qy,qz,qw); - MVector axis; - double theta; - rotation.getAxisAngle(axis,theta); - if (fabs(axis.x) < PRECISION) - axis.x = 0; - if (fabs(axis.y) < PRECISION) - axis.y = 0; - if (fabs(axis.z) < PRECISION) - axis.z = 0; - axis.normalize(); - if (fabs(theta) < PRECISION) - theta = 0; - if (axis.length() < 0.5) - { - axis.x = 0; - axis.y = 1; - axis.z = 0; - theta = 0; - } - // Get joint scale - double scale[3]; - ((MTransformationMatrix)localMatrix).getScale(scale,MSpace::kPostTransform); - if (fabs(scale[0]) < PRECISION) - scale[0] = 0; - if (fabs(scale[1]) < PRECISION) - scale[1] = 0; - if (fabs(scale[2]) < PRECISION) - scale[2] = 0; - // Set joint info - newJoint.name = jointFn.partialPathName(); - newJoint.id = m_joints.size(); - newJoint.parentIndex = idx; - newJoint.bindMatrix = bindMatrix; - newJoint.localMatrix = localMatrix; - newJoint.posx = translation.x * params.lum; - newJoint.posy = translation.y * params.lum; - newJoint.posz = translation.z * params.lum; - newJoint.angle = theta; - newJoint.axisx = axis.x; - newJoint.axisy = axis.y; - newJoint.axisz = axis.z; - newJoint.scalex = scale[0]; - newJoint.scaley = scale[1]; - newJoint.scalez = scale[2]; - newJoint.jointDag = jointDag; - m_joints.push_back(newJoint); - // If root is a root joint, save its index in the roots list - if (idx < 0) - { - m_roots.push_back(m_joints.size() - 1); - } - // Get pointer to newly created joint - parentJoint = &newJoint; - } - // Load child joints - for (int i=0; i times; - // if skeleton has no joints we can't load the clip - if (m_joints.size() < 0) - return MS::kFailure; - // display clip name - std::cout << "clip \"" << clipName.asChar() << "\"\n"; - std::cout.flush(); - // calculate times from clip sample rate - times.clear(); - if (rate <= 0) - { - std::cout << "invalid sample rate for the clip (must be >0), we skip it\n"; - std::cout.flush(); - return MS::kFailure; - } - for (float t=start; t= 0) - length = times[times.size()-1] - times[0]; - if (length < 0) - { - std::cout << "invalid time range for the clip, we skip it\n"; - std::cout.flush(); - return MS::kFailure; - } - // create the animation - Animation a; - a.m_name = clipName.asChar(); - a.m_tracks.clear(); - a.m_length = length; - m_animations.push_back(a); - int animIdx = m_animations.size() - 1; - // create a track for current clip for all joints - std::vector animTracks; - for (int i=0; im_dagPath); - MPoint min = mesh.boundingBox().min(); - MPoint max = mesh.boundingBox().max(); - MBoundingBox bbox(min,max); - if (params.exportWorldCoords) - bbox.transformUsing(params.loadedSubmeshes[j]->m_dagPath.inclusiveMatrix()); - min = bbox.min() * params.lum; - max = bbox.max() * params.lum; - MBoundingBox newbbox(min,max); - params.loadedSubmeshes[j]->m_boundingBox.expand(newbbox); - } - } - } - // add created tracks to current clip - for (int i=0; i= 0) - { - // Get parent joint - MDagPath parentDag = m_joints[parentIdx].jointDag; - localMatrix = worldMatrix * parentDag.inclusiveMatrixInverse(); - } - else - { // Root node of skeleton - if (params.exportWorldCoords) - localMatrix = worldMatrix; - else - localMatrix = worldMatrix * j.jointDag.exclusiveMatrixInverse(); - } - // Get relative transformation matrix - MMatrix relMatrix = localMatrix * j.localMatrix.inverse(); - // Get relative translation - MVector translation = ((MTransformationMatrix)localMatrix).translation(MSpace::kPostTransform) - - ((MTransformationMatrix)j.localMatrix).translation(MSpace::kPostTransform); - if (fabs(translation.x) < PRECISION) - translation.x = 0; - if (fabs(translation.y) < PRECISION) - translation.y = 0; - if (fabs(translation.z) < PRECISION) - translation.z = 0; - // Get relative rotation - double qx,qy,qz,qw; - ((MTransformationMatrix)relMatrix).getRotationQuaternion(qx,qy,qz,qw); - MQuaternion rotation(qx,qy,qz,qw); - MVector axis; - double theta; - rotation.getAxisAngle(axis,theta); - while (theta > Ogre::Math::PI) - { - theta -= Ogre::Math::TWO_PI; - } - while (theta < -Ogre::Math::PI) - { - theta += Ogre::Math::TWO_PI; - } - if (fabs(axis.x) < PRECISION) - axis.x = 0; - if (fabs(axis.y) < PRECISION) - axis.y = 0; - if (fabs(axis.z) < PRECISION) - axis.z = 0; - axis.normalize(); - if (fabs(theta) < PRECISION) - theta = 0; - if (axis.length() < 0.5) - { - axis.x = 0; - axis.y = 1; - axis.z = 0; - theta = 0; - } - // Get relative scale - double scale[3]; - ((MTransformationMatrix)relMatrix).getScale(scale,MSpace::kPostTransform); - if (fabs(scale[0]) < PRECISION) - scale[0] = 0; - if (fabs(scale[1]) < PRECISION) - scale[1] = 0; - if (fabs(scale[2]) < PRECISION) - scale[2] = 0; - //create keyframe - skeletonKeyframe key; - key.time = time; - key.tx = translation.x * params.lum; - key.ty = translation.y * params.lum; - key.tz = translation.z * params.lum; - key.angle = theta; - key.axis_x = axis.x; - key.axis_y = axis.y; - key.axis_z = axis.z; - key.sx = scale[0]; - key.sy = scale[1]; - key.sz = scale[2]; - return key; - } - - - // Restore skeleton pose - void Skeleton::restorePose() - { - //enable constraints, IK, etc... - MGlobal::executeCommand("doEnableNodeItems true all",true); - // save current selection list - MSelectionList selectionList; - MGlobal::getActiveSelectionList(selectionList); - // restore the pose on all parts of the skeleton - for (int i=0; i& Skeleton::getJoints() - { - return m_joints; - } - - - - // Get animations - std::vector& Skeleton::getAnimations() - { - return m_animations; - } - - - - // Write to an OGRE binary skeleton - MStatus Skeleton::writeOgreBinary(ParamList ¶ms) - { - MStatus stat; - // Construct skeleton - MString name = "exportSkeleton"; - Ogre::SkeletonPtr pSkeleton = Ogre::SkeletonManager::getSingleton().create(name.asChar(), - Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - // Create skeleton bones - stat = createOgreBones(pSkeleton,params); - if (stat != MS::kSuccess) - { - std::cout << "Error writing skeleton binary file\n"; - std::cout.flush(); - } - // Create skeleton animation - if (params.exportSkelAnims) - { - stat = createOgreSkeletonAnimations(pSkeleton,params); - if (stat != MS::kSuccess) - { - std::cout << "Error writing ogre skeleton animations\n"; - std::cout.flush(); - } - } - pSkeleton->setBindingPose(); - // Optimise animations - pSkeleton->optimiseAllAnimations(); - // Export skeleton binary - Ogre::SkeletonSerializer serializer; - serializer.exportSkeleton(pSkeleton.get(),params.skeletonFilename.asChar()); - pSkeleton.reset(); - // Skeleton successfully exported - return MS::kSuccess; - } - - // Write joints to an Ogre skeleton - MStatus Skeleton::createOgreBones(Ogre::SkeletonPtr pSkeleton,ParamList& params) - { - // Create the bones - for (int i=0; iname.asChar(); - int jointId = j->id; - Ogre::Bone* pBone = pSkeleton->createBone(jointName, jointId); - // Set bone position (relative to it's parent) - pBone->setPosition(j->posx,j->posy,j->posz); - // Set bone orientation (relative to it's parent) - Ogre::Quaternion orient; - orient.FromAngleAxis(Ogre::Radian(j->angle),Ogre::Vector3(j->axisx,j->axisy,j->axisz)); - pBone->setOrientation(orient); - // Set bone scale (relative to it's parent) - pBone->setScale(j->scalex,j->scaley,j->scalez); - } - // Create the hierarchy - for (int i=0; iparentIndex; - if (parentIdx >= 0) - { - // Get the parent joint - joint* parentJoint = &m_joints[parentIdx]; - unsigned short parentId = m_joints[parentIdx].id; - Ogre::String parentName = parentJoint->name.asChar(); - Ogre::Bone* pParent = pSkeleton->getBone(parentName); - // Get current joint from skeleton - unsigned short jointId = j->id; - Ogre::String jointName = j->name.asChar(); - Ogre::Bone* pBone = pSkeleton->getBone(jointName); - // Place current bone in the parent's child list - pParent->addChild(pBone); - } - } - return MS::kSuccess; - } - - - // Write skeleton animations to an Ogre skeleton - MStatus Skeleton::createOgreSkeletonAnimations(Ogre::SkeletonPtr pSkeleton,ParamList& params) - { - // Read loaded skeleton animations - for (int i=0; icreateAnimation(m_animations[i].m_name.asChar(), - m_animations[i].m_length); - // Create tracks for current animation - for (int j=0; jcreateNodeTrack(j, - pSkeleton->getBone(t->m_bone.asChar())); - // Create keyframes for current track - for (int k=0; km_skeletonKeyframes.size(); k++) - { - skeletonKeyframe* keyframe = &t->m_skeletonKeyframes[k]; - // Create a new keyframe - Ogre::TransformKeyFrame* pKeyframe = pTrack->createNodeKeyFrame(keyframe->time); - // Set translation - pKeyframe->setTranslate(Ogre::Vector3(keyframe->tx,keyframe->ty,keyframe->tz)); - // Set rotation - Ogre::Quaternion rot; - rot.FromAngleAxis(Ogre::Radian(keyframe->angle), - Ogre::Vector3(keyframe->axis_x,keyframe->axis_y,keyframe->axis_z)); - pKeyframe->setRotation(rot); - // Set scale - pKeyframe->setScale(Ogre::Vector3(keyframe->sx,keyframe->sy,keyframe->sz)); - } - } - } - return MS::kSuccess; - } - - -}; //end namespace \ No newline at end of file diff --git a/Tools/MayaExport/src/submesh.cpp b/Tools/MayaExport/src/submesh.cpp deleted file mode 100644 index 85c16e8a63a..00000000000 --- a/Tools/MayaExport/src/submesh.cpp +++ /dev/null @@ -1,533 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// submesh.cpp -// Author : Francesco Giordana -// Sponsored by : Anygma N.V. (http://www.nazooka.com) -// Start Date : January 13, 2005 -// Copyright : (C) 2006 by Francesco Giordana -// Email : fra.giordana@tiscali.it -//////////////////////////////////////////////////////////////////////////////// - -/********************************************************************************* -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Lesser General Public License as published by * -* the Free Software Foundation; either version 2 of the License, or * -* (at your option) any later version. * -* * -**********************************************************************************/ - -#include "submesh.h" - -namespace OgreMayaExporter -{ - /***** Class Submesh *****/ - // constructor - Submesh::Submesh(const MString& name) - { - m_pBlendShape = NULL; - clear(); - m_name = name; - } - - // destructor - Submesh::~Submesh() - { - clear(); - } - - // clear data - void Submesh::clear() - { - m_name = ""; - m_numTriangles = 0; - m_pMaterial = NULL; - m_indices.clear(); - m_vertices.clear(); - m_faces.clear(); - m_uvsets.clear(); - m_use32bitIndexes = false; - m_pBlendShape = NULL; - } - - // return number of triangles composing the mesh - long Submesh::numTriangles() - { - return m_numTriangles; - } - - // return number of vertices composing the mesh - long Submesh::numVertices() - { - return m_numVertices; - } - - // return submesh name - MString& Submesh::name() - { - return m_name; - } - -/***** load data *****/ - MStatus Submesh::loadMaterial(MObject& shader,MStringArray& uvsets,ParamList& params) - { - MPlug plug; - MPlugArray srcplugarray; - bool foundShader = false; - MStatus stat; - MFnDependencyNode* pShader; - //get shader from shading group - MFnDependencyNode shadingGroup(shader); - plug = shadingGroup.findPlug("surfaceShader"); - plug.connectedTo(srcplugarray,true,false,&stat); - for (int i=0; iname().asChar() << "\n"; - std::cout.flush(); - //check if this material has already been created - //fix material name, adding the requested prefix - MString tmpStr = params.matPrefix; - if (tmpStr != "") - tmpStr += "/"; - tmpStr += pShader->name(); - MStringArray tmpStrArray; - tmpStr.split(':',tmpStrArray); - MString name = ""; - for (int i=0; iload(pShader,uvsets,params); - m_pMaterial = pMaterial; - MaterialSet::getSingleton().addMaterial(pMaterial); - } - //delete temporary shader - delete pShader; - } - else - { - std::cout << "Unsupported material, replacing with default lambert\n"; - std::cout.flush(); - m_pMaterial = MaterialSet::getSingleton().getDefaultMaterial(); - } - - //loading complete - return MS::kSuccess; - } - - MStatus Submesh::load(const MDagPath& dag,std::vector& faces, std::vector& vertInfo, MPointArray& points, - MFloatVectorArray& normals, MStringArray& texcoordsets,ParamList& params,bool opposite) - { - //save the dag path of the maya node from which this submesh will be created - m_dagPath = dag; - //create the mesh Fn - MFnMesh mesh(dag); - std::cout << "Loading submesh : " << m_name.asChar() << "..."; - std::cout.flush(); - //save uvsets info - for (int i=m_uvsets.size(); i vtx_mapping; - vtx_mapping.resize(vertInfo.size()); - for (int i=0; i PRECISION) - v.vbas.push_back(newVba); - } - // save texture coordinates - for (int k=0; k 65535) || (m_faces.size() > 65535)) - m_use32bitIndexes = true; - else - m_use32bitIndexes = false; - // get submesh bounding box - MPoint min = mesh.boundingBox().min(); - MPoint max = mesh.boundingBox().max(); - MBoundingBox bbox(min,max); - if (params.exportWorldCoords) - bbox.transformUsing(dag.inclusiveMatrix()); - min = bbox.min() * params.lum; - max = bbox.max() * params.lum; - MBoundingBox newbbox(min,max); - m_boundingBox = newbbox; - // add submesh pointer to parameters list - params.loadedSubmeshes.push_back(this); - - std::cout << "DONE\n"; - std::cout.flush(); - return MS::kSuccess; - } - - - // Load a keyframe for this submesh - MStatus Submesh::loadKeyframe(Track& t,float time,ParamList& params) - { - // create a new keyframe - vertexKeyframe k; - // set keyframe time - k.time = time; - // get the mesh Fn - MFnMesh mesh(m_dagPath); - // get vertex positions - MFloatPointArray points; - if (params.exportWorldCoords) - mesh.getPoints(points,MSpace::kWorld); - else - mesh.getPoints(points,MSpace::kObject); - // calculate vertex offsets - for (int i=0; icreateSubMesh(m_name.asChar()); - else - pSubmesh = pMesh->createSubMesh(); - // Set material - pSubmesh->setMaterialName(m_pMaterial->name().asChar()); - // Set use shared geometry flag - pSubmesh->useSharedVertices = params.useSharedGeom; - // Create vertex data for current submesh - pSubmesh->vertexData = new Ogre::VertexData(); - // Set number of indexes - pSubmesh->indexData->indexCount = 3*m_faces.size(); - pSubmesh->vertexData->vertexCount = m_vertices.size(); - // Check if we need to use 32 bit indexes - bool use32BitIndexes = false; - if (m_vertices.size() > 65536 || params.useSharedGeom) - { - use32BitIndexes = true; - } - // Create a new index buffer - pSubmesh->indexData->indexBuffer = - Ogre::HardwareBufferManager::getSingleton().createIndexBuffer( - use32BitIndexes ? Ogre::HardwareIndexBuffer::IT_32BIT : Ogre::HardwareIndexBuffer::IT_16BIT, - pSubmesh->indexData->indexCount, - Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY); - // Fill the index buffer with faces data - if (use32BitIndexes) - { - Ogre::uint32* pIdx = static_cast( - pSubmesh->indexData->indexBuffer->lock(Ogre::HardwareBuffer::HBL_DISCARD)); - for (int i=0; i(m_faces[i].v[0]); - *pIdx++ = static_cast(m_faces[i].v[1]); - *pIdx++ = static_cast(m_faces[i].v[2]); - } - pSubmesh->indexData->indexBuffer->unlock(); - } - else - { - Ogre::uint16* pIdx = static_cast( - pSubmesh->indexData->indexBuffer->lock(Ogre::HardwareBuffer::HBL_DISCARD)); - for (int i=0; i(m_faces[i].v[0]); - *pIdx++ = static_cast(m_faces[i].v[1]); - *pIdx++ = static_cast(m_faces[i].v[2]); - } - pSubmesh->indexData->indexBuffer->unlock(); - } - // Define vertex declaration (only if we're not using shared geometry) - if(!params.useSharedGeom) - { - Ogre::VertexDeclaration* pDecl = pSubmesh->vertexData->vertexDeclaration; - unsigned buf = 0; - size_t offset = 0; - // Add vertex position - pDecl->addElement(buf, offset, Ogre::VET_FLOAT3, Ogre::VES_POSITION); - offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3); - // Add vertex normal - if (params.exportVertNorm) - { - pDecl->addElement(buf, offset, Ogre::VET_FLOAT3, Ogre::VES_NORMAL); - offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3); - } - // Add vertex colour - if(params.exportVertCol) - { - pDecl->addElement(buf, offset, Ogre::VET_COLOUR, Ogre::VES_DIFFUSE); - offset += Ogre::VertexElement::getTypeSize(Ogre::VET_COLOUR); - } - // Add texture coordinates - for (int i=0; iaddElement(buf, offset, uvType, Ogre::VES_TEXTURE_COORDINATES, i); - offset += Ogre::VertexElement::getTypeSize(uvType); - } - Ogre::VertexDeclaration* pOptimalDecl = pDecl->getAutoOrganisedDeclaration( - params.exportVBA,params.exportBlendShapes || params.exportVertAnims); - // Fill the vertex buffer using the newly created vertex declaration - stat = createOgreVertexBuffer(pSubmesh,pDecl,m_vertices); - // Write vertex bone assignements list - if (params.exportVBA) - { - // Create a new vertex bone assignements list - Ogre::SubMesh::VertexBoneAssignmentList vbas; - // Scan list of shared geometry vertices - for (int i=0; iparent->_rationaliseBoneAssignments(pSubmesh->vertexData->vertexCount,vbas); - // Add bone assignements to the submesh - for (Ogre::SubMesh::VertexBoneAssignmentList::iterator bi = vbas.begin(); bi != vbas.end(); bi++) - { - pSubmesh->addBoneAssignment(bi->second); - } - pSubmesh->_compileBoneAssignments(); - } - pSubmesh->vertexData->reorganiseBuffers(pOptimalDecl); - } - return MS::kSuccess; - } - - - // Create an Ogre compatible vertex buffer - MStatus Submesh::createOgreVertexBuffer(Ogre::SubMesh* pSubmesh,Ogre::VertexDeclaration* pDecl,const std::vector& vertices) - { - Ogre::HardwareVertexBufferSharedPtr vbuf = - Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(pDecl->getVertexSize(0), - pSubmesh->vertexData->vertexCount, - Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY); - pSubmesh->vertexData->vertexBufferBinding->setBinding(0, vbuf); - size_t vertexSize = pDecl->getVertexSize(0); - char* pBase = static_cast(vbuf->lock(Ogre::HardwareBuffer::HBL_DISCARD)); - Ogre::VertexDeclaration::VertexElementList elems = pDecl->findElementsBySource(0); - Ogre::VertexDeclaration::VertexElementList::iterator ei, eiend; - eiend = elems.end(); - float* pFloat; - Ogre::RGBA* pRGBA; - // Fill the vertex buffer with shared geometry data - Ogre::ColourValue col; - float ucoord, vcoord; - for (long vi=0; viunlock(); - return MS::kSuccess; - } - -}; //end of namespace diff --git a/Tools/MeshUpgrader/CMakeLists.txt b/Tools/MeshUpgrader/CMakeLists.txt deleted file mode 100644 index 83c1b6cffa2..00000000000 --- a/Tools/MeshUpgrader/CMakeLists.txt +++ /dev/null @@ -1,16 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure MeshUpgrader -add_executable(OgreMeshUpgrader src/main.cpp) -target_link_libraries(OgreMeshUpgrader OgreMain OgreMeshLodGenerator) -if (OGRE_PROJECT_FOLDERS) - set_property(TARGET OgreMeshUpgrader PROPERTY FOLDER Tools) -endif () -ogre_config_tool(OgreMeshUpgrader) diff --git a/Tools/MeshUpgrader/src/main.cpp b/Tools/MeshUpgrader/src/main.cpp deleted file mode 100644 index 977dccae445..00000000000 --- a/Tools/MeshUpgrader/src/main.cpp +++ /dev/null @@ -1,571 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "Ogre.h" -#include "OgreDefaultHardwareBufferManager.h" -#include "OgreMeshLodGenerator.h" -#include "OgreDistanceLodStrategy.h" -#include "OgreLodStrategyManager.h" -#include "OgrePixelCountLodStrategy.h" -#include "OgreLodConfig.h" - -#include -#include - -using namespace std; -using namespace Ogre; - -namespace { - -void help(void) -{ - cout << -R"HELP(Usage: OgreMeshUpgrader [opts] sourcefile [destfile] - - Upgrades or downgrades .mesh file versions. - --pack = Pack normals and tangents as int_10_10_10_2 --autogen = Generate autoconfigured LOD. No LOD options needed --l lodlevels = number of LOD levels --d loddist = distance increment to reduce LOD --p lodpercent = Percentage triangle reduction amount per LOD --f lodnumtris = Fixed vertex reduction per LOD --el = generate edge lists (for stencil shadows) --t = Generate tangents (for normal mapping) --ts [3|4] = Tangent size (4 includes parity, default: 3) --tm = Split tangent vertices at UV mirror points --tr = Split tangent vertices where basis is rotated > 90 degrees --r = DON'T reorganise buffers to recommended format --E endian = Set endian mode 'big' 'little' or 'native' (default) --b = Recalculate bounding box (static meshes only) --V version = Specify OGRE version format to write instead of latest - Options are: 1.10, 1.8, 1.7, 1.4, 1.0 --log filename = name of the log file (default: 'OgreMeshUpgrader.log') -sourcefile = name of file to convert -destfile = optional name of file to write to. If you don't - specify this OGRE overwrites the existing file. -)HELP"; -} - -struct UpgradeOptions { - bool generateEdgeLists; - bool generateTangents; - bool tangentUseParity; - bool tangentSplitMirrored; - bool tangentSplitRotated; - bool dontReorganise; - bool lodAutoconfigure; - bool packNormalsTangents; - unsigned short numLods; - Real lodDist; - Real lodPercent; - size_t lodFixed; - bool usePercent; - Serializer::Endian endian; - bool recalcBounds; - MeshVersion targetVersion; - String logFile; -}; - -UpgradeOptions parseOpts(UnaryOptionList& unOpts, BinaryOptionList& binOpts) -{ - UpgradeOptions opts; - - // Defaults - opts.generateEdgeLists = false; - opts.generateTangents = false; - opts.tangentUseParity = false; - opts.tangentSplitMirrored = false; - opts.tangentSplitRotated = false; - opts.dontReorganise = false; - opts.endian = Serializer::ENDIAN_NATIVE; - - opts.packNormalsTangents = false; - - opts.lodAutoconfigure = false; - opts.lodDist = 500; - opts.lodFixed = 0; - opts.lodPercent = 20; - opts.numLods = 0; - opts.usePercent = true; - opts.recalcBounds = false; - opts.targetVersion = MESH_VERSION_LATEST; - - opts.generateEdgeLists = unOpts["-el"]; - opts.generateTangents = unOpts["-t"]; - opts.tangentSplitMirrored = unOpts["-tm"]; - opts.tangentSplitRotated = unOpts["-tr"]; - opts.lodAutoconfigure = unOpts["-autogen"]; - opts.dontReorganise = unOpts["-r"]; - opts.packNormalsTangents = unOpts["-pack"]; - - // Unary options (true/false options that don't take a parameter) - if (unOpts["-b"]) { - opts.recalcBounds = true; - } - - // Binary options (options that take a parameter) - BinaryOptionList::iterator bi = binOpts.find("-l"); - if (!bi->second.empty()) { - opts.numLods = StringConverter::parseInt(bi->second); - } - - bi = binOpts.find("-log"); - if (!bi->second.empty()) { - opts.logFile = binOpts["-log"]; - } - - bi = binOpts.find("-d"); - if (!bi->second.empty()) { - opts.lodDist = StringConverter::parseReal(bi->second); - } - - bi = binOpts.find("-p"); - if (!bi->second.empty()) { - opts.lodPercent = StringConverter::parseReal(bi->second); - opts.usePercent = true; - } - - bi = binOpts.find("-f"); - if (!bi->second.empty()) { - opts.lodFixed = StringConverter::parseInt(bi->second); - opts.usePercent = false; - } - - bi = binOpts.find("-E"); - if (!bi->second.empty()) { - if (bi->second == "big") { - opts.endian = Serializer::ENDIAN_BIG; - } else if (bi->second == "little") { - opts.endian = Serializer::ENDIAN_LITTLE; - } else { - opts.endian = Serializer::ENDIAN_NATIVE; - } - } - - bi = binOpts.find("-ts"); - if (!bi->second.empty()) { - if (bi->second == "4") { - opts.tangentUseParity = true; - } - } - - bi = binOpts.find("-V"); - if (!bi->second.empty()) { - if (bi->second == "1.10") { - opts.targetVersion = MESH_VERSION_1_10; - } else if (bi->second == "1.8") { - opts.targetVersion = MESH_VERSION_1_8; - } else if (bi->second == "1.7") { - opts.targetVersion = MESH_VERSION_1_7; - } else if (bi->second == "1.4") { - opts.targetVersion = MESH_VERSION_1_4; - } else if (bi->second == "1.0") { - opts.targetVersion = MESH_VERSION_1_0; - } else { - LogManager::getSingleton().logError("Unrecognised target mesh version '" + bi->second + "'"); - } - } - - return opts; -} - -// Utility function to allow the user to modify the layout of vertex buffers. -void reorganiseVertexBuffers(const UpgradeOptions& opts, Mesh& mesh) -{ - // Make sure animation types up to date - mesh._determineAnimationTypes(); - - if (mesh.sharedVertexData) { - // Automatic - VertexDeclaration* newDcl = - mesh.sharedVertexData->vertexDeclaration->getAutoOrganisedDeclaration( - mesh.hasSkeleton(), mesh.hasVertexAnimation(), mesh.getSharedVertexDataAnimationIncludesNormals()); - if (*newDcl != *(mesh.sharedVertexData->vertexDeclaration)) { - mesh.sharedVertexData->reorganiseBuffers(newDcl); - } - } - - for (size_t i = 0; i < mesh.getNumSubMeshes(); i++) - { - SubMesh* sm = mesh.getSubMesh(i); - if (!sm->useSharedVertices) { - const bool hasVertexAnim = sm->getVertexAnimationType() != Ogre::VAT_NONE; - - // Automatic - VertexDeclaration* newDcl = - sm->vertexData->vertexDeclaration->getAutoOrganisedDeclaration( - mesh.hasSkeleton(), hasVertexAnim, sm->getVertexAnimationIncludesNormals() ); - if (*newDcl != *(sm->vertexData->vertexDeclaration)) { - sm->vertexData->reorganiseBuffers(newDcl); - } - } - } -} - -void recalcBounds(const VertexData* vdata, AxisAlignedBox& aabb, Real& radius) -{ - const VertexElement* posElem = - vdata->vertexDeclaration->findElementBySemantic(VES_POSITION); - - const HardwareVertexBufferSharedPtr buf = vdata->vertexBufferBinding->getBuffer( - posElem->getSource()); - void* pBase = buf->lock(HardwareBuffer::HBL_READ_ONLY); - - for (size_t v = 0; v < vdata->vertexCount; ++v) { - float* pFloat; - posElem->baseVertexPointerToElement(pBase, &pFloat); - - Vector3 pos(pFloat[0], pFloat[1], pFloat[2]); - aabb.merge(pos); - radius = std::max(radius, pos.length()); - - pBase = static_cast(static_cast(pBase) + buf->getVertexSize()); - } - - buf->unlock(); -} - -void recalcBounds(Mesh* mesh) -{ - AxisAlignedBox aabb; - Real radius = 0.0f; - - if (mesh->sharedVertexData) { - recalcBounds(mesh->sharedVertexData, aabb, radius); - } - for (unsigned short i = 0; i < mesh->getNumSubMeshes(); ++i) { - SubMesh* sm = mesh->getSubMesh(i); - if (!sm->useSharedVertices) { - recalcBounds(sm->vertexData, aabb, radius); - } - } - - mesh->_setBounds(aabb, false); - mesh->_setBoundingSphereRadius(radius); -} - -void printLodConfig(const LodConfig& lodConfig) -{ - auto logMgr = LogManager::getSingletonPtr(); - logMgr->logMessage("LOD config summary:"); - logMgr->logMessage(" - lodConfig.strategy=" + lodConfig.strategy->getName()); - String reductionMethod("Unknown"); - if (lodConfig.levels[0].reductionMethod == LodLevel::VRM_PROPORTIONAL) { - reductionMethod = "VRM_PROPORTIONAL"; - } else if (lodConfig.levels[0].reductionMethod == LodLevel::VRM_CONSTANT) { - reductionMethod = "VRM_PROPORTIONAL"; - } else if (lodConfig.levels[0].reductionMethod == LodLevel::VRM_COLLAPSE_COST) { - reductionMethod = "VRM_COLLAPSE_COST"; - } - String distQuantity; - if (lodConfig.strategy == PixelCountLodStrategy::getSingletonPtr()) { - distQuantity = "px"; - } - for (unsigned short i = 0; i < lodConfig.levels.size(); i++) { - const LodLevel& lodLevel = lodConfig.levels[i]; - logMgr->logMessage(" - lodConfig.levels[" + StringConverter::toString(i) + "].distance=" + - StringConverter::toString(lodLevel.distance) + distQuantity); - logMgr->logMessage(" - lodConfig.levels[" + StringConverter::toString(i) + "].reductionMethod=" + - (lodLevel.manualMeshName.empty() ? reductionMethod : "N/A")); - logMgr->logMessage(" - lodConfig.levels[" + StringConverter::toString(i) + "].reductionValue=" + - (lodLevel.manualMeshName.empty() ? StringConverter::toString(lodLevel.reductionValue) : "N/A")); - logMgr->logMessage(" - lodConfig.levels[" + StringConverter::toString(i) + "].manualMeshName=" + - (lodLevel.manualMeshName.empty() ? "N/A" : lodLevel.manualMeshName)); - } -} - -void buildLod(UpgradeOptions& opts, MeshPtr& mesh) -{ - String response; - - // Prompt for LOD generation? - bool genLod = (opts.numLods != 0 || opts.lodAutoconfigure); - if (!genLod) { - return; - } - - int numLod; - LodConfig lodConfig; - lodConfig.mesh = mesh; - lodConfig.strategy = DistanceLodBoxStrategy::getSingletonPtr(); - - // not interactive: read parameters from console - numLod = opts.numLods; - LodLevel lodLevel = {}; - lodLevel.distance = 0.0; - for (unsigned short iLod = 0; iLod < numLod; ++iLod) { - - lodLevel.reductionMethod = opts.usePercent ? - LodLevel::VRM_PROPORTIONAL : LodLevel::VRM_CONSTANT; - if (opts.usePercent) { - lodLevel.reductionValue += opts.lodPercent * 0.01f; - } else { - lodLevel.reductionValue += (Ogre::Real)opts.lodFixed; - } - - lodLevel.distance += opts.lodDist; - lodConfig.levels.push_back(lodLevel); - } - - // ensure we use correct bounds - recalcBounds(mesh.get()); - - MeshLodGenerator gen; - if (opts.lodAutoconfigure) { - // In this case we ignore other settings - gen.getAutoconfig(mesh, lodConfig); - } - printLodConfig(lodConfig); - - LogManager::getSingleton().logMessage("Generating LOD levels..."); - gen.generateLodLevels(lodConfig); - LogManager::getSingleton().logMessage("Generating LOD levels... success"); -} - -void checkColour(VertexData* vdata, bool& hasColour, bool& hasAmbiguousColour, - VertexElementType& originalType) -{ - const VertexDeclaration::VertexElementList& elemList = vdata->vertexDeclaration->getElements(); - for (const auto & elem : elemList) { - switch (elem.getType()) { - case _DETAIL_SWAP_RB: - hasColour = true; - originalType = elem.getType(); - - default: - // do nothing - ; - } - } -} - -void resolveColourAmbiguities(Mesh* mesh) -{ - // Check what we're dealing with - bool hasColour = false; - bool hasAmbiguousColour = false; - VertexElementType originalType = VET_FLOAT1; - if (mesh->sharedVertexData) { - checkColour(mesh->sharedVertexData, hasColour, hasAmbiguousColour, originalType); - } - for (unsigned short i = 0; i < mesh->getNumSubMeshes(); ++i) { - SubMesh* sm = mesh->getSubMesh(i); - if (sm->useSharedVertices == false) { - checkColour(sm->vertexData, hasColour, hasAmbiguousColour, originalType); - } - } - - if(!hasColour) - return; - - VertexElementType desiredType = VET_UBYTE4_NORM; - if (mesh->sharedVertexData) { - mesh->sharedVertexData->convertPackedColour(originalType, desiredType); - } - for (unsigned short i = 0; i < mesh->getNumSubMeshes(); ++i) { - SubMesh* sm = mesh->getSubMesh(i); - if (!sm->useSharedVertices) { - sm->vertexData->convertPackedColour(originalType, desiredType); - } - } -} - -struct MeshResourceCreator : public MeshSerializerListener -{ - void processMaterialName(Mesh *mesh, String *name) override - { - if(name->empty()) { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, - "The provided mesh file has an empty material name. See https://ogrecave.github.io/ogre/api/latest/_mesh-_tools.html#autotoc_md32"); - } - else { - // create material because we do not load any .material files - MaterialManager::getSingleton().createOrRetrieve(*name, mesh->getGroup()); - } - } - - void processSkeletonName(Mesh *mesh, String *name) override - { - if (name->empty()) - { - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "The provided mesh file uses an empty skeleton name"); - } - - // create skeleton because we do not load any .skeleton files - SkeletonManager::getSingleton().createOrRetrieve(*name, mesh->getGroup(), true); - } - void processMeshCompleted(Mesh *mesh) override {} -}; -} - -int main(int numargs, char** args) -{ - if (numargs < 2) { - help(); - return -1; - } - - int retCode = 0; - - LogManager logMgr; - // this log catches output from the parseArgs call and routes it to stdout only - logMgr.createLog("Temporary log", true, true, true); - - try - { - UnaryOptionList unOptList; - BinaryOptionList binOptList; - - unOptList["-byte"] = true; // this is the only option now, dont error if specified - unOptList["-e"] = true; // this is default, dont error if specified - - unOptList["-el"] = false; - unOptList["-t"] = false; - unOptList["-tm"] = false; - unOptList["-tr"] = false; - unOptList["-r"] = false; - unOptList["-autogen"] = false; - unOptList["-pack"] = false; - unOptList["-b"] = false; - binOptList["-l"] = ""; - binOptList["-d"] = ""; - binOptList["-p"] = ""; - binOptList["-f"] = ""; - binOptList["-E"] = ""; - binOptList["-ts"] = ""; - binOptList["-V"] = ""; - binOptList["-log"] = "OgreMeshUpgrader.log"; - - int startIdx = findCommandLineOpts(numargs, args, unOptList, binOptList); - auto opts = parseOpts(unOptList, binOptList); - - logMgr.setDefaultLog(NULL); // swallow startup messages - DefaultHardwareBufferManager bufferManager; // needed because we don't have a rendersystem - Root root("", "", ""); - // get rid of the temporary log as we use the new log now - logMgr.destroyLog("Temporary log"); - - // use the log specified by the cmdline params - logMgr.setDefaultLog(logMgr.createLog(opts.logFile, true, true)); - - String source(args[startIdx]); - - MaterialManager::getSingleton().initialise(); - MeshSerializer meshSerializer; - MeshResourceCreator resCreator; - meshSerializer.setListener(&resCreator); - SkeletonSerializer skeletonSerializer; - // don't pad during upgrade - MeshManager::getSingleton().setBoundsPaddingFactor(0.0f); - - // Load the mesh - struct stat tagStat; - - FILE* pFile = fopen( source.c_str(), "rb" ); - if (!pFile) { - OGRE_EXCEPT(Exception::ERR_FILE_NOT_FOUND, - "File " + source + " not found.", "OgreMeshUpgrader"); - } - stat( source.c_str(), &tagStat ); - MemoryDataStream* memstream = new MemoryDataStream(source, tagStat.st_size, true); - size_t result = fread( (void*)memstream->getPtr(), 1, tagStat.st_size, pFile ); - if (result != size_t(tagStat.st_size)) - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Unexpected error while reading file " + source, "OgreMeshUpgrader"); - fclose( pFile ); - - MeshPtr meshPtr = MeshManager::getSingleton().createManual("TmpConversionMesh", RGN_DEFAULT); - Mesh* mesh = meshPtr.get(); - - DataStreamPtr stream(memstream); - meshSerializer.importMesh(stream, mesh); - - // Write out the converted mesh - String dest; - if (numargs == startIdx + 2) { - dest = args[startIdx + 1]; - } else { - dest = source; - } - - String response; - - reorganiseVertexBuffers(opts, *mesh); - - // Deal with VET_COLOUR ambiguities - resolveColourAmbiguities(mesh); - - buildLod(opts, meshPtr); - - // Make sure we generate edge lists, provided they are not deliberately disabled - if (opts.generateEdgeLists) { - logMgr.logMessage("Generating edge lists..."); - mesh->buildEdgeList(); - logMgr.logMessage("Generating edge lists... success"); - } else { - mesh->freeEdgeList(); - } - // Generate tangents? - if (opts.generateTangents) { - unsigned short srcTex; - bool existing = mesh->suggestTangentVectorBuildParams(srcTex); - if (existing) { - // safe - opts.generateTangents = false; - } - if (opts.generateTangents) { - logMgr.logMessage("Generating tangent vectors..."); - mesh->buildTangentVectors(srcTex, opts.tangentSplitMirrored, opts.tangentSplitRotated, - opts.tangentUseParity); - logMgr.logMessage("Generating tangent vectors... success"); - } - } - - if(opts.packNormalsTangents) - { - mesh->_convertVertexElement(VES_NORMAL, VET_INT_10_10_10_2_NORM); - mesh->_convertVertexElement(VES_TANGENT, VET_INT_10_10_10_2_NORM); - } - - if (opts.recalcBounds) { - recalcBounds(mesh); - } - - meshSerializer.exportMesh(mesh, dest, opts.targetVersion, opts.endian); - - logMgr.setDefaultLog(NULL); // swallow shutdown messages - } - catch (Exception& e) - { - LogManager::getSingleton().logError(e.getDescription()); - retCode = 1; - } - - return retCode; -} diff --git a/Tools/MilkshapeExport/MilkshapeExporter.sln b/Tools/MilkshapeExport/MilkshapeExporter.sln deleted file mode 100644 index a182bf91fe1..00000000000 --- a/Tools/MilkshapeExport/MilkshapeExporter.sln +++ /dev/null @@ -1,39 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 9.00 -# Visual Studio 2005 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MilkshapeExport", "scripts\MilkshapeExport_vc8.vcproj", "{D4929E45-2A25-4F53-96A1-E1BCD91D9B6A}" - ProjectSection(ProjectDependencies) = postProject - {35AFBABB-DF05-43DE-91A7-BB828A874015} = {35AFBABB-DF05-43DE-91A7-BB828A874015} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "OgreMain", "..\..\OgreMain\scripts\OgreMain_vc8.vcproj", "{35AFBABB-DF05-43DE-91A7-BB828A874015}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - DebugStaticLib|Win32 = DebugStaticLib|Win32 - Release|Win32 = Release|Win32 - ReleaseStaticLib|Win32 = ReleaseStaticLib|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {D4929E45-2A25-4F53-96A1-E1BCD91D9B6A}.Debug|Win32.ActiveCfg = Debug|Win32 - {D4929E45-2A25-4F53-96A1-E1BCD91D9B6A}.Debug|Win32.Build.0 = Debug|Win32 - {D4929E45-2A25-4F53-96A1-E1BCD91D9B6A}.DebugStaticLib|Win32.ActiveCfg = Debug|Win32 - {D4929E45-2A25-4F53-96A1-E1BCD91D9B6A}.DebugStaticLib|Win32.Build.0 = Debug|Win32 - {D4929E45-2A25-4F53-96A1-E1BCD91D9B6A}.Release|Win32.ActiveCfg = Release|Win32 - {D4929E45-2A25-4F53-96A1-E1BCD91D9B6A}.Release|Win32.Build.0 = Release|Win32 - {D4929E45-2A25-4F53-96A1-E1BCD91D9B6A}.ReleaseStaticLib|Win32.ActiveCfg = Release|Win32 - {D4929E45-2A25-4F53-96A1-E1BCD91D9B6A}.ReleaseStaticLib|Win32.Build.0 = Release|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.Debug|Win32.ActiveCfg = Debug|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.Debug|Win32.Build.0 = Debug|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.DebugStaticLib|Win32.ActiveCfg = DebugStaticLib|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.DebugStaticLib|Win32.Build.0 = DebugStaticLib|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.Release|Win32.ActiveCfg = Release|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.Release|Win32.Build.0 = Release|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.ReleaseStaticLib|Win32.ActiveCfg = ReleaseStaticLib|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.ReleaseStaticLib|Win32.Build.0 = ReleaseStaticLib|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/Tools/MilkshapeExport/MilkshapeExporter.suo b/Tools/MilkshapeExport/MilkshapeExporter.suo deleted file mode 100644 index fcc123d8d36..00000000000 Binary files a/Tools/MilkshapeExport/MilkshapeExporter.suo and /dev/null differ diff --git a/Tools/MilkshapeExport/ReadMe.html b/Tools/MilkshapeExport/ReadMe.html deleted file mode 100644 index 799c1249f42..00000000000 --- a/Tools/MilkshapeExport/ReadMe.html +++ /dev/null @@ -1,94 +0,0 @@ - - - OGRE Readme - - - - -

OGRE (Object-Oriented Graphics Rendering Engine)

-

Milkshape Exporter README file

-
-

Summary

-

- OGRE (Object-Oriented Graphics Rendering Engine) is a scene-oriented, flexible 3D engine written in C++ designed to make it easier and more intuitive for developers to produce games and demos utilising 3D hardware. The class - library abstracts all the details of using the underlying system libraries like Direct3D and OpenGL and provides an interface based on world objects and other intuitive classes. -

-

This distribution contains the bare files required to export OGRE .mesh files from the shareware modelling tool Milkshape3d.

-

How to Install

-

- If you are using the prebuilt archive, just extract it into the folder you installed Milkshape3D into (e.g. C:\Program Files\Milkshape3d). If you are building the exporter yourself, copy the msOGREExporter.dll into the Milkshape - folder, and either copy OgreMain.dll from the 'Release' build of OgreMain into the Milkshape folder too, or make sure it is somewhere on your path. -

-

How to Use

-

Select an object and click File|Export|OGRE Mesh / Skeleton...

-

- It's possible to export Material definitions from Milkshape into the .mesh file, but because Milkshape only supports very basic material types, I recommend you don't do this. Instead, create materials in Milkshape and use them - for skinning purposes, but don't check the 'Export Materials' box in the OGRE export dialog. Make sure you note down the names of the materials you defined in Milkshape, then write definitions for the materials in OGRE .material - scripts instead, using the same names. The meshes exported will still have a reference to the material name defined in Milkshape, but the superior OGRE material will be used at runtime. -

-

Skeletons can be exported too: if you choose not to export a skeleton and there are bones in the model, you must link the mesh to it's target skeleton.

-

- You can optionally choose to split the single animation sequence in Milkshape into multiple separate animations. To do this you have to supply a simple comma-separated text file to record which frames are for which animation, - e.g: -

-

- 1,30,Walk
- 31,40,Wave
- 41,80,Run -

-

These 3 animations would then show up under Skeleton::getAnimation("Walk"), Skeleton::getAnimation("Run") etc as well as Entity::getAnimationState("Walk") etc.

-

 

-

To get more information

-

To obtain more information and to download the OGRE source code, go to http://www.ogre3d.org.

-

-

 

- - diff --git a/Tools/MilkshapeExport/Readme.md b/Tools/MilkshapeExport/Readme.md deleted file mode 100644 index 007c075fe52..00000000000 --- a/Tools/MilkshapeExport/Readme.md +++ /dev/null @@ -1,25 +0,0 @@ - -# Milkshape Exporter README file - -## How to Install - -If you are using the prebuilt archive, just extract it into the folder you installed Milkshape3D into (e.g. `C:\Program Files\Milkshape3d`). -If you are building the exporter yourself, copy the msOGREExporter.dll into the Milkshape folder, and either copy OgreMain.dll from the 'Release' build of OgreMain into the Milkshape folder too, or make sure it is somewhere on your path. - -## How to Use -Select an object and click File|Export|OGRE Mesh / Skeleton... - -It's possible to export Material definitions from Milkshape into the .mesh file, but because Milkshape only supports very basic material types, I recommend you don't do this. -Instead, create materials in Milkshape and use them for skinning purposes, but don't check the 'Export Materials' box in the OGRE export dialog. -Make sure you note down the names of the materials you defined in Milkshape, then write definitions for the materials in OGRE .material scripts instead, using the same names. -The meshes exported will still have a reference to the material name defined in Milkshape, but the superior OGRE material will be used at runtime. - -Skeletons can be exported too: if you choose not to export a skeleton and there are bones in the model, you must link the mesh to it's target skeleton. - -You can optionally choose to split the single animation sequence in Milkshape into multiple separate animations. -To do this you have to supply a simple comma-separated text file to record which frames are for which animation, e.g: -1,30,Walk -31,40,Wave -41,80,Run - -These 3 animations would then show up under `Skeleton::getAnimation("Walk")`, `Skeleton::getAnimation("Run")` etc as well as `Entity::getAnimationState("Walk")` etc. diff --git a/Tools/MilkshapeExport/include/MilkshapeExport.h b/Tools/MilkshapeExport/include/MilkshapeExport.h deleted file mode 100644 index 260bf8e62de..00000000000 --- a/Tools/MilkshapeExport/include/MilkshapeExport.h +++ /dev/null @@ -1,44 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __MilkshapeExport_H__ -#define __MilkshapeExport_H__ - -#include "MilkshapePlugin.h" - -#define WIN32_LEAN_AND_MEAN - -#define NOMINMAX -#include - -// Implement the required DLL factory method -cMsPlugIn* CreatePlugIn (); - - -#endif - diff --git a/Tools/MilkshapeExport/include/MilkshapePlugin.h b/Tools/MilkshapeExport/include/MilkshapePlugin.h deleted file mode 100644 index 49b06de8451..00000000000 --- a/Tools/MilkshapeExport/include/MilkshapePlugin.h +++ /dev/null @@ -1,96 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __MilkshapePlugin_H__ -#define __MilkshapePlugin_H__ - -#include "msPlugIn.h" -#include "windows.h" -#include "Ogre.h" - - -/** A plugin class for Milkshape3D to export to OGRE model formats. - - This class is the implementor of the exporting interface for Milkshape3D, to allow - you to export your models to OGRE format from that tool. - Note that this plugin delegates most of the detail of exporting the model to the - generic model export framework. -*/ -class MilkshapePlugin : public cMsPlugIn -{ - - char mTitle[64]; - -public: - MilkshapePlugin (); - virtual ~MilkshapePlugin (); - -public: - /// As required by Milkshape - int GetType (); - /// As required by Milkshape - const char * GetTitle (); - /// As required by Milkshape - int Execute (msModel* pModel); - - /** Callback to process window events */ -#if OGRE_ARCHITECTURE_64 == OGRE_ARCH_TYPE - static INT_PTR CALLBACK DlgProc(HWND hDlg, UINT iMsg, WPARAM wParam, LPARAM lParam); -#else - static BOOL CALLBACK DlgProc(HWND hDlg, UINT iMsg, WPARAM wParam, LPARAM lParam); -#endif - - bool exportMaterials; - bool generateLods; - bool generateEdgeLists; - bool generateTangents; - Ogre::VertexElementSemantic tangentSemantic; - bool tangentsSplitMirrored; - bool tangentsSplitRotated; - bool tangentsUseParity; - unsigned short numLods; - float lodDepthIncrement; - Ogre::ProgressiveMesh::VertexReductionQuota lodReductionMethod; - float lodReductionAmount; - bool exportMesh; - bool exportSkeleton; - bool splitAnimations; - float fps; - -protected: - bool showOptions(void); - void doExportMesh(msModel* pModel); - void doExportMaterials(msModel* pModel); - void doExportAnimations(msModel* pModel, Ogre::SkeletonPtr& skel); - Ogre::SkeletonPtr doExportSkeleton(msModel* pModel, Ogre::MeshPtr& mesh); // Skeleton returned for deletion later - bool locateSkeleton(Ogre::MeshPtr& mesh); - Ogre::ColourValue msVec4ToColourValue(float prop[4]); -}; - -#endif - diff --git a/Tools/MilkshapeExport/include/msLib.h b/Tools/MilkshapeExport/include/msLib.h deleted file mode 100644 index 0c0203ad778..00000000000 --- a/Tools/MilkshapeExport/include/msLib.h +++ /dev/null @@ -1,407 +0,0 @@ -/********************************************************************** - * - * MilkShape 3D Model Import/Export API - * - * Jan 27 2007, Mete Ciragan, chUmbaLum sOft - * - **********************************************************************/ - -#ifndef __MSLIB_H__ -#define __MSLIB_H__ - - - -#ifdef MSLIB_EXPORTS -#define MSLIB_API __declspec(dllexport) -#else -#define MSLIB_API __declspec(dllimport) -#endif /* MSLIB_EXPORTS */ - - - -#ifdef WIN32 -#include -#endif /* WIN32 */ - - - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - - - -/********************************************************************** - * - * Constants - * - **********************************************************************/ - -#define MS_MAX_NAME 32 -#define MS_MAX_PATH 256 - -#define MAX_VERTICES 65534 -#define MAX_TRIANGLES 65534 -#define MAX_GROUPS 255 -#define MAX_MATERIALS 128 -#define MAX_JOINTS 128 - - - -/********************************************************************** - * - * Types - * - **********************************************************************/ - -#ifndef byte -typedef unsigned char byte; -#endif /* byte */ - -#ifndef word -typedef unsigned short word; -#endif /* word */ - -typedef float msVec4[4]; -typedef float msVec3[3]; -typedef float msVec2[2]; - -/* msFlag */ -typedef enum { - eSelected = 1, eSelected2 = 2, eHidden = 4, eDirty = 8, eAveraged = 16, eKeepVertex = 32, eSphereMap = 0x80, eHasAlpha = 0x40 -} msFlag; - - - -/* -!!! -!!! Do not use direct structs access like vertex->nFlags. Use msVertex_GetFlags(vertex) instead. This makes sure, -!!! that your plugin stays compatible with future versions of MilkShape 3D. -!!! -*/ - - - -/* msVertex: used internally only, DO NOT USE DIRECTLY, USE API INSTEAD */ -typedef struct msVertex -{ - byte nFlags; - msVec3 Vertex; - float u, v; - char nBoneIndex; -} msVertex; - -/* msVertexEx: used internally only, DO NOT USE DIRECTLY, USE API INSTEAD */ -typedef struct msVertexEx -{ - char nBoneIndices[3]; - byte nBoneWeights[3]; - unsigned int nExtra; -} msVertexEx; - -/* msTriangle: used internally only, DO NOT USE DIRECTLY, USE API INSTEAD */ -typedef struct msTriangle -{ - word nFlags; - word nVertexIndices[3]; - word nNormalIndices[3]; - msVec3 Normal; - byte nSmoothingGroup; -} msTriangle; - -/* msTriangleEx: used internally only, DO NOT USE DIRECTLY, USE API INSTEAD */ -typedef struct msTriangleEx -{ - msVec3 Normals[3]; - msVec2 TexCoords[3]; -} msTriangleEx; - -/* msMesh: used internally only, DO NOT USE DIRECTLY, USE API INSTEAD */ -typedef struct msMesh -{ - byte nFlags; - char szName[MS_MAX_NAME]; - char nMaterialIndex; - - word nNumVertices; - word nNumAllocedVertices; - msVertex* pVertices; - - word nNumNormals; - word nNumAllocedNormals; - msVec3* pNormals; - - word nNumTriangles; - word nNumAllocedTriangles; - msTriangle* pTriangles; - - char* pszComment; - msVertexEx *pVertexExs; - msTriangleEx *pTriangleExs; -} msMesh; - -/* msMaterial: used internally only, DO NOT USE DIRECTLY, USE API INSTEAD */ -typedef struct msMaterial -{ - int nFlags; - char szName[MS_MAX_NAME]; - msVec4 Ambient; - msVec4 Diffuse; - msVec4 Specular; - msVec4 Emissive; - float fShininess; - float fTransparency; - char szDiffuseTexture[MS_MAX_PATH]; - char szAlphaTexture[MS_MAX_PATH]; - int nName; - char* pszComment; -} msMaterial; - -/* msPositionKey */ -typedef struct msPositionKey -{ - float fTime; - msVec3 Position; -} msPositionKey; - -/* msRotationKey */ -typedef struct msRotationKey -{ - float fTime; - msVec3 Rotation; -} msRotationKey; - -/* msBone: used internally only, DO NOT USE DIRECTLY, USE API INSTEAD */ -typedef struct msBone -{ - int nFlags; - char szName[MS_MAX_NAME]; - char szParentName[MS_MAX_NAME]; - msVec3 Position; - msVec3 Rotation; - - int nNumPositionKeys; - int nNumAllocedPositionKeys; - msPositionKey* pPositionKeys; - - int nNumRotationKeys; - int nNumAllocedRotationKeys; - msRotationKey* pRotationKeys; - char* pszComment; -} msBone; - -/* msModel: used internally only, DO NOT USE DIRECTLY, USE API INSTEAD */ -typedef struct msModel -{ - int nNumMeshes; - int nNumAllocedMeshes; - msMesh* pMeshes; - - int nNumMaterials; - int nNumAllocedMaterials; - msMaterial* pMaterials; - - int nNumBones; - int nNumAllocedBones; - msBone* pBones; - - int nFrame; - int nTotalFrames; - - msVec3 Position; - msVec3 Rotation; - - msVec3 CameraPosition; - msVec2 CameraRotationXY; - - char* pszComment; -} msModel; - - - -/********************************************************************** - * - * MilkShape 3D Interface - * - **********************************************************************/ - -/********************************************************************** - * msModel - **********************************************************************/ - -MSLIB_API void msModel_Destroy (msModel *pModel); - -MSLIB_API int msModel_GetMeshCount (msModel *pModel); -MSLIB_API int msModel_AddMesh (msModel *pModel); -MSLIB_API msMesh* msModel_GetMeshAt (msModel *pModel, int nIndex); -MSLIB_API int msModel_FindMeshByName (msModel *pModel, const char *szName); - -MSLIB_API int msModel_GetMaterialCount (msModel *pModel); -MSLIB_API int msModel_AddMaterial (msModel *pModel); -MSLIB_API msMaterial* msModel_GetMaterialAt (msModel *pModel, int nIndex); -MSLIB_API int msModel_FindMaterialByName (msModel *pModel, const char *szName); - -MSLIB_API int msModel_GetBoneCount (msModel *pModel); -MSLIB_API int msModel_AddBone (msModel *pModel); -MSLIB_API msBone* msModel_GetBoneAt (msModel *pModel, int nIndex); -MSLIB_API int msModel_FindBoneByName (msModel *pModel, const char *szName); - -MSLIB_API int msModel_SetFrame (msModel *pModel, int nFrame); -MSLIB_API int msModel_GetFrame (msModel *pModel); -MSLIB_API int msModel_SetTotalFrames (msModel *pModel, int nTotalFrames); -MSLIB_API int msModel_GetTotalFrames (msModel *pModel); -MSLIB_API void msModel_SetPosition (msModel *pModel, msVec3 Position); -MSLIB_API void msModel_GetPosition (msModel *pModel, msVec3 Position); -MSLIB_API void msModel_SetRotation (msModel *pModel, msVec3 Rotation); -MSLIB_API void msModel_GetRotation (msModel *pModel, msVec3 Rotation); -MSLIB_API void msModel_SetCamera (msModel *pModel, msVec3 Position, msVec2 RotationXY); -MSLIB_API void msModel_GetCamera (msModel *pModel, msVec3 Position, msVec2 RotationXY); -MSLIB_API void msModel_SetComment (msModel *pModel, const char *pszComment); -MSLIB_API int msModel_GetComment (msModel *pModel, char *pszComment, int nMaxCommentLength); - -/********************************************************************** - * msMesh - **********************************************************************/ - -MSLIB_API void msMesh_Destroy (msMesh *pMesh); -MSLIB_API void msMesh_SetFlags (msMesh *pMesh, byte nFlags); -MSLIB_API byte msMesh_GetFlags (msMesh *pMesh); -MSLIB_API void msMesh_SetName (msMesh *pMesh, const char *szName); -MSLIB_API void msMesh_GetName (msMesh *pMesh, char *szName, int nMaxLength); -MSLIB_API void msMesh_SetMaterialIndex (msMesh *pMesh, int nIndex); -MSLIB_API int msMesh_GetMaterialIndex (msMesh *pMesh); - -MSLIB_API int msMesh_GetVertexCount (msMesh *pMesh); -MSLIB_API int msMesh_AddVertex (msMesh *pMesh); -MSLIB_API msVertex* msMesh_GetVertexAt (msMesh *pMesh, int nIndex); -MSLIB_API msVertexEx* msMesh_GetVertexExAt (msMesh *pMesh, int nIndex); -MSLIB_API msVertex* msMesh_GetInterpolatedVertexAt (msMesh *pMesh, int nIndex); // NOT YET IMPLEMENTED - -MSLIB_API int msMesh_GetTriangleCount (msMesh *pMesh); -MSLIB_API int msMesh_AddTriangle (msMesh *pMesh); -MSLIB_API msTriangle* msMesh_GetTriangleAt (msMesh *pMesh, int nIndex); -MSLIB_API msTriangleEx* msMesh_GetTriangleExAt (msMesh *pMesh, int nIndex); - -MSLIB_API int msMesh_GetVertexNormalCount (msMesh *pMesh); -MSLIB_API int msMesh_AddVertexNormal (msMesh *pMesh); -MSLIB_API void msMesh_SetVertexNormalAt (msMesh *pMesh, int nIndex, msVec3 Normal); -MSLIB_API void msMesh_GetVertexNormalAt (msMesh *pMesh, int nIndex, msVec3 Normal); -MSLIB_API void msMesh_GetInterpolatedVertexNormalAt (msMesh *pMesh, int nIndex, msVec3 Normal); // NOT YET IMPLEMENTED -MSLIB_API void msMesh_SetComment (msMesh *pMesh, const char *pszComment); -MSLIB_API int msMesh_GetComment (msMesh *pMesh, char *pszComment, int nMaxCommentLength); - -/********************************************************************** - * msTriangle - **********************************************************************/ - -MSLIB_API void msTriangle_SetFlags (msTriangle* pTriangle, word nFlags); -MSLIB_API word msTriangle_GetFlags (msTriangle* pTriangle); -MSLIB_API void msTriangle_SetVertexIndices (msTriangle *pTriangle, word nIndices[]); -MSLIB_API void msTriangle_GetVertexIndices (msTriangle *pTriangle, word nIndices[]); -MSLIB_API void msTriangle_SetNormalIndices (msTriangle *pTriangle, word nNormalIndices[]); -MSLIB_API void msTriangle_GetNormalIndices (msTriangle *pTriangle, word nNormalIndices[]); -MSLIB_API void msTriangle_SetSmoothingGroup (msTriangle *pTriangle, byte nSmoothingGroup); -MSLIB_API byte msTriangle_GetSmoothingGroup (msTriangle *pTriangle); - -/********************************************************************** - * msTriangleEx - **********************************************************************/ -MSLIB_API void msTriangleEx_SetNormal (msTriangleEx *pTriangle, int nIndex, msVec3 Normal); -MSLIB_API void msTriangleEx_GetNormal (msTriangleEx *pTriangle, int nIndex, msVec3 Normal); -MSLIB_API void msTriangleEx_SetTexCoord (msTriangleEx *pTriangle, int nIndex, msVec2 TexCoord); -MSLIB_API void msTriangleEx_GetTexCoord (msTriangleEx *pTriangle, int nIndex, msVec2 TexCoord); - -/********************************************************************** - * msVertex - **********************************************************************/ - -MSLIB_API void msVertex_SetFlags (msVertex* pVertex, byte nFlags); -MSLIB_API byte msVertex_GetFlags (msVertex* pVertex); -MSLIB_API void msVertex_SetVertex (msVertex* pVertex, msVec3 Vertex); -MSLIB_API void msVertex_GetVertex (msVertex* pVertex, msVec3 Vertex); -MSLIB_API void msVertex_SetTexCoords (msVertex* pVertex, msVec2 st); -MSLIB_API void msVertex_GetTexCoords (msVertex* pVertex, msVec2 st); -MSLIB_API int msVertex_SetBoneIndex (msVertex* pVertex, int nBoneIndex); -MSLIB_API int msVertex_GetBoneIndex (msVertex* pVertex); - -/********************************************************************** - * msVertexEx - **********************************************************************/ - -MSLIB_API int msVertexEx_SetBoneIndices (msVertexEx* pVertex, int nIndex, int nBoneIndex); -MSLIB_API int msVertexEx_GetBoneIndices (msVertexEx* pVertex, int nIndex); -MSLIB_API int msVertexEx_SetBoneWeights (msVertexEx* pVertex, int nIndex, int nWeight); -MSLIB_API int msVertexEx_GetBoneWeights (msVertexEx* pVertex, int nIndex); -MSLIB_API unsigned int msVertexEx_SetExtra (msVertexEx* pVertex, int nIndex, unsigned int nExtra); -MSLIB_API unsigned int msVertexEx_GetExtra (msVertexEx* pVertex, int nIndex); - -/********************************************************************** - * msMaterial - **********************************************************************/ - -MSLIB_API void msMaterial_SetFlags (msMaterial *pMaterial, int nFlags); -MSLIB_API int msMaterial_GetFlags (msMaterial *pMaterial); -MSLIB_API void msMaterial_SetName (msMaterial *pMaterial, const char *szName); -MSLIB_API void msMaterial_GetName (msMaterial *pMaterial, char *szName, int nMaxLength); -MSLIB_API void msMaterial_SetAmbient (msMaterial *pMaterial, msVec4 Ambient); -MSLIB_API void msMaterial_GetAmbient (msMaterial *pMaterial, msVec4 Ambient); -MSLIB_API void msMaterial_SetDiffuse (msMaterial *pMaterial, msVec4 Diffuse); -MSLIB_API void msMaterial_GetDiffuse (msMaterial *pMaterial, msVec4 Diffuse); -MSLIB_API void msMaterial_SetSpecular (msMaterial *pMaterial, msVec4 Specular); -MSLIB_API void msMaterial_GetSpecular (msMaterial *pMaterial, msVec4 Specular); -MSLIB_API void msMaterial_SetEmissive (msMaterial *pMaterial, msVec4 Emissive); -MSLIB_API void msMaterial_GetEmissive (msMaterial *pMaterial, msVec4 Emissive); -MSLIB_API void msMaterial_SetShininess (msMaterial *pMaterial, float fShininess); -MSLIB_API float msMaterial_GetShininess (msMaterial *pMaterial); -MSLIB_API void msMaterial_SetTransparency (msMaterial *pMaterial, float fTransparency); -MSLIB_API float msMaterial_GetTransparency (msMaterial *pMaterial); -MSLIB_API void msMaterial_SetDiffuseTexture (msMaterial *pMaterial, const char *szDiffuseTexture); -MSLIB_API void msMaterial_GetDiffuseTexture (msMaterial *pMaterial, char *szDiffuseTexture, int nMaxLength); -MSLIB_API void msMaterial_SetAlphaTexture (msMaterial *pMaterial, const char *szAlphaTexture); -MSLIB_API void msMaterial_GetAlphaTexture (msMaterial *pMaterial, char *szAlphaTexture, int nMaxLength); -MSLIB_API void msMaterial_SetComment (msMaterial *pMaterial, const char *pszComment); -MSLIB_API int msMaterial_GetComment (msMaterial *pMaterial, char *pszComment, int nMaxCommentLength); - -/********************************************************************** - * msBone - **********************************************************************/ - -MSLIB_API void msBone_Destroy (msBone *pBone); -MSLIB_API void msBone_SetFlags (msBone *pBone, int nFlags); -MSLIB_API int msBone_GetFlags (msBone *pBone); -MSLIB_API void msBone_SetName (msBone *pBone, const char *szName); -MSLIB_API void msBone_GetName (msBone *pBone, char *szName, int nMaxLength); -MSLIB_API void msBone_SetParentName (msBone *pBone, const char *szParentName); -MSLIB_API void msBone_GetParentName (msBone *pBone, char *szParentName, int nMaxLength); -MSLIB_API void msBone_SetPosition (msBone *pBone, msVec3 Position); -MSLIB_API void msBone_GetPosition (msBone *pBone, msVec3 Position); -MSLIB_API void msBone_GetInterpolatedPosition (msBone *pBone, msVec3 Position); // NOT YET IMPLEMENTED -MSLIB_API void msBone_SetRotation (msBone *pBone, msVec3 Rotation); -MSLIB_API void msBone_GetRotation (msBone *pBone, msVec3 Rotation); -MSLIB_API void msBone_GetInterpolatedRotation (msBone *pBone, msVec3 Rotation); // NOT YET IMPLEMENTED - -MSLIB_API int msBone_GetPositionKeyCount (msBone *pBone); -MSLIB_API int msBone_AddPositionKey (msBone *pBone, float fTime, msVec3 Position); -MSLIB_API msPositionKey* msBone_GetPositionKeyAt (msBone *pBone, int nIndex); - -MSLIB_API int msBone_GetRotationKeyCount (msBone *pBone); -MSLIB_API int msBone_AddRotationKey (msBone *pBone, float fTime, msVec3 Rotation); -MSLIB_API msRotationKey* msBone_GetRotationKeyAt (msBone *pBone, int nIndex); -MSLIB_API void msBone_SetComment (msBone *pBone, const char *pszComment); -MSLIB_API int msBone_GetComment (msBone *pBone, char *pszComment, int nMaxCommentLength); - - - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - - - -#ifdef WIN32 -#include -#endif /* WIN32 */ - - - -#endif /* __MSLIB_H__ */ \ No newline at end of file diff --git a/Tools/MilkshapeExport/include/msPlugIn.h b/Tools/MilkshapeExport/include/msPlugIn.h deleted file mode 100644 index d692332f970..00000000000 --- a/Tools/MilkshapeExport/include/msPlugIn.h +++ /dev/null @@ -1,42 +0,0 @@ -#ifndef __MS_PLUGIN_H__ -#define __MS_PLUGIN_H__ - - - -struct msModel; -class cMsPlugIn -{ -public: - enum - { - eTypeImport = 1, - eTypeExport = 2, - eTypeTool = 3, - eTypeEdit = 4, - eTypeVertex = 5, - eTypeFace = 6, - eTypeAnimate = 7, - eTypeMask = 0x000F, - - eNormalsAndTexCoordsPerTriangleVertex = 128 - }; - -public: - cMsPlugIn () {}; - virtual ~cMsPlugIn () {}; - -public: - virtual int GetType () = 0; - virtual const char * GetTitle () = 0; - virtual int Execute (msModel* pModel) = 0; -}; - - - -typedef cMsPlugIn* (*FN_CREATE_PLUGIN)(); - -cMsPlugIn *CreatePlugIn (); - - - -#endif // __MS_PLUGIN_H__ \ No newline at end of file diff --git a/Tools/MilkshapeExport/include/resource.h b/Tools/MilkshapeExport/include/resource.h deleted file mode 100644 index b3b3fb293cf..00000000000 --- a/Tools/MilkshapeExport/include/resource.h +++ /dev/null @@ -1,39 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by MilkshapeExport.rc -// -#define IDD_OPTIONS 101 -#define IDC_EXPORT_MATERIALS 1001 -#define IDC_EXPORT_MESH 1003 -#define IDC_CHECK2 1004 -#define IDC_EXPORT_SKEL 1004 -#define IDC_SPLIT_ANIMATION 1005 -#define IDC_EDIT1 1006 -#define IDC_FPS 1006 -#define IDC_GRP_MESH 1007 -#define IDC_GENERATE_LOD 1008 -#define IDC_LOD_DEPTH 1009 -#define IDC_LOD_VRQ 1010 -#define IDC_CBO_LOD_STYLE 1011 -#define IDC_GRP_SKELETON 1012 -#define IDC_GRP_MATERIAL 1013 -#define IDC_NUM_LODS 1014 -#define IDC_EDGE_LISTS 1016 -#define IDC_TANGENT_VECTORS 1017 -#define IDC_TANG_SPLIT_MIRR 1018 -#define IDC_TANGENTS_TARGET 1019 -#define IDC_TANG_SPLIT_ROT 1020 -#define IDC_4D_TANGENTS 1021 - - - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 103 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1014 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/Tools/MilkshapeExport/misc/MilkshapeExport.rc b/Tools/MilkshapeExport/misc/MilkshapeExport.rc deleted file mode 100644 index f336749ae87..00000000000 --- a/Tools/MilkshapeExport/misc/MilkshapeExport.rc +++ /dev/null @@ -1,151 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "winres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""winres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// English (U.K.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENG) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_UK -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_OPTIONS DIALOGEX 0, 0, 387, 182 -STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "OGRE Export Options" -FONT 8, "MS Shell Dlg", 0, 0, 0x0 -BEGIN - DEFPUSHBUTTON "OK",IDOK,277,157,50,14 - PUSHBUTTON "Cancel",IDCANCEL,330,157,50,14 - CONTROL "Export Mesh",IDC_EXPORT_MESH,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,13,16,56,10 - CONTROL "Export Skeleton && Animation",IDC_EXPORT_SKEL,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,197,17,107,10 - CONTROL "Split keyframe sequence into multiple animations",IDC_SPLIT_ANIMATION, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,197,53,165,10 - EDITTEXT IDC_FPS,261,30,23,13,ES_AUTOHSCROLL - LTEXT "Frame Rate:",IDC_STATIC,215,33,41,10 - LTEXT "(frames per second)",IDC_STATIC,289,33,75,10 - GROUPBOX "Mesh Export",IDC_GRP_MESH,7,7,180,150 - CONTROL "Generate Automatic Level Of Detail (LOD)",IDC_GENERATE_LOD, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,13,32,164,10 - EDITTEXT IDC_LOD_DEPTH,99,57,30,13,ES_AUTOHSCROLL - RTEXT "Depth between LODs:",IDC_STATIC,25,59,72,10 - RTEXT "Reduce each level by:",IDC_STATIC,25,74,72,10 - EDITTEXT IDC_LOD_VRQ,99,72,30,13,ES_AUTOHSCROLL - COMBOBOX IDC_CBO_LOD_STYLE,132,72,45,13,CBS_DROPDOWN | CBS_SORT | WS_VSCROLL | WS_TABSTOP - GROUPBOX "Skeleton / Animation Export",IDC_GRP_SKELETON,189,7,191,137 - LTEXT "To use the 'split' feature you have to supply a simple comma-separated text file to record which frames are for which animation, which you will be prompted for the location of. See Readme.html for more info.",IDC_STATIC,205,66,165,44 - EDITTEXT IDC_NUM_LODS,99,42,30,13,ES_AUTOHSCROLL - RTEXT "Number of lower LODs:",IDC_STATIC,16,44,81,10 - CONTROL "Generate Edge Lists (Allow Stencil Shadows)",IDC_EDGE_LISTS, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,13,89,165,10 - CONTROL "Generate Tangents (Allow Normal Maps)",IDC_TANGENT_VECTORS, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,13,103,149,10 - CONTROL "Export Materials",IDC_EXPORT_MATERIALS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,7,161,92,10 - COMBOBOX IDC_TANGENTS_TARGET,60,115,119,12,CBS_DROPDOWNLIST | CBS_SORT | WS_VSCROLL | WS_TABSTOP - RTEXT "Target:",IDC_STATIC,15,117,42,10 - CONTROL "Split Mirrored",IDC_TANG_SPLIT_MIRR,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,33,132,53,10 - CONTROL "Split Rotated",IDC_TANG_SPLIT_ROT,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,95,133,53,10 - CONTROL "4D Tangents",IDC_4D_TANGENTS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,33,144,53,10 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO -BEGIN - IDD_OPTIONS, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 380 - TOPMARGIN, 7 - BOTTOMMARGIN, 171 - END -END -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog Info -// - -IDD_OPTIONS DLGINIT -BEGIN - IDC_CBO_LOD_STYLE, 0x403, 1, 0 -"\000" - 0 -END - -#endif // English (U.K.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/Tools/MilkshapeExport/misc/MilkshapeExporter.def b/Tools/MilkshapeExport/misc/MilkshapeExporter.def deleted file mode 100644 index 0aa46f5a6f2..00000000000 --- a/Tools/MilkshapeExport/misc/MilkshapeExporter.def +++ /dev/null @@ -1,3 +0,0 @@ -LIBRARY msOGREExporter -EXPORTS - CreatePlugIn diff --git a/Tools/MilkshapeExport/misc/winres.h b/Tools/MilkshapeExport/misc/winres.h deleted file mode 100644 index e6f9c26a14b..00000000000 --- a/Tools/MilkshapeExport/misc/winres.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (C) 2000 Francois Gouget - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ - -#include - -#ifdef IDC_STATIC -#undef IDC_STATIC -#endif -#define IDC_STATIC (-1) - diff --git a/Tools/MilkshapeExport/obj/Debug/.keepme b/Tools/MilkshapeExport/obj/Debug/.keepme deleted file mode 100644 index e0808fa1636..00000000000 --- a/Tools/MilkshapeExport/obj/Debug/.keepme +++ /dev/null @@ -1 +0,0 @@ -keep me diff --git a/Tools/MilkshapeExport/obj/Release/.keepme b/Tools/MilkshapeExport/obj/Release/.keepme deleted file mode 100644 index e0808fa1636..00000000000 --- a/Tools/MilkshapeExport/obj/Release/.keepme +++ /dev/null @@ -1 +0,0 @@ -keep me diff --git a/Tools/MilkshapeExport/setup/License.rtf b/Tools/MilkshapeExport/setup/License.rtf deleted file mode 100644 index b1ccdf23779..00000000000 --- a/Tools/MilkshapeExport/setup/License.rtf +++ /dev/null @@ -1,462 +0,0 @@ -{\rtf1\ansi\deff0{\fonttbl{\f0\fswiss\fcharset0 Arial;}} -{\*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\lang1033\f0\fs20\tab\tab GNU LESSER GENERAL PUBLIC LICENSE\par -\tab\tab Version 2.1, February 1999\par -\par - Copyright (C) 1991, 1999 Free Software Foundation, Inc.\par - 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\par - Everyone is permitted to copy and distribute verbatim copies\par - of this license document, but changing it is not allowed.\par -\par -[This is the first released version of the Lesser GPL. It also counts\par - as the successor of the GNU Library Public License, version 2, hence\par - the version number 2.1.]\par -\par -\tab\tab\tab Preamble\par -\par - The licenses for most software are designed to take away your\par -freedom to share and change it. By contrast, the GNU General Public\par -Licenses are intended to guarantee your freedom to share and change\par -free software--to make sure the software is free for all its users.\par -\par - This license, the Lesser General Public License, applies to some\par -specially designated software packages--typically libraries--of the\par -Free Software Foundation and other authors who decide to use it. You\par -can use it too, but we suggest you first think carefully about whether\par -this license or the ordinary General Public License is the better\par -strategy to use in any particular case, based on the explanations below.\par -\par - When we speak of free software, we are referring to freedom of use,\par -not price. Our General Public Licenses are designed to make sure that\par -you have the freedom to distribute copies of free software (and charge\par -for this service if you wish); that you receive source code or can get\par -it if you want it; that you can change the software and use pieces of\par -it in new free programs; and that you are informed that you can do\par -these things.\par -\par - To protect your rights, we need to make restrictions that forbid\par -distributors to deny you these rights or to ask you to surrender these\par -rights. These restrictions translate to certain responsibilities for\par -you if you distribute copies of the library or if you modify it.\par -\par - For example, if you distribute copies of the library, whether gratis\par -or for a fee, you must give the recipients all the rights that we gave\par -you. You must make sure that they, too, receive or can get the source\par -code. If you link other code with the library, you must provide\par -complete object files to the recipients, so that they can relink them\par -with the library after making changes to the library and recompiling\par -it. And you must show them these terms so they know their rights.\par -\par - We protect your rights with a two-step method: (1) we copyright the\par -library, and (2) we offer you this license, which gives you legal\par -permission to copy, distribute and/or modify the library.\par -\par - To protect each distributor, we want to make it very clear that\par -there is no warranty for the free library. Also, if the library is\par -modified by someone else and passed on, the recipients should know\par -that what they have is not the original version, so that the original\par -author's reputation will not be affected by problems that might be\par -introduced by others.\par -\page\par - Finally, software patents pose a constant threat to the existence of\par -any free program. We wish to make sure that a company cannot\par -effectively restrict the users of a free program by obtaining a\par -restrictive license from a patent holder. Therefore, we insist that\par -any patent license obtained for a version of the library must be\par -consistent with the full freedom of use specified in this license.\par -\par - Most GNU software, including some libraries, is covered by the\par -ordinary GNU General Public License. This license, the GNU Lesser\par -General Public License, applies to certain designated libraries, and\par -is quite different from the ordinary General Public License. We use\par -this license for certain libraries in order to permit linking those\par -libraries into non-free programs.\par -\par - When a program is linked with a library, whether statically or using\par -a shared library, the combination of the two is legally speaking a\par -combined work, a derivative of the original library. The ordinary\par -General Public License therefore permits such linking only if the\par -entire combination fits its criteria of freedom. The Lesser General\par -Public License permits more lax criteria for linking other code with\par -the library.\par -\par - We call this license the "Lesser" General Public License because it\par -does Less to protect the user's freedom than the ordinary General\par -Public License. It also provides other free software developers Less\par -of an advantage over competing non-free programs. These disadvantages\par -are the reason we use the ordinary General Public License for many\par -libraries. However, the Lesser license provides advantages in certain\par -special circumstances.\par -\par - For example, on rare occasions, there may be a special need to\par -encourage the widest possible use of a certain library, so that it becomes\par -a de-facto standard. To achieve this, non-free programs must be\par -allowed to use the library. A more frequent case is that a free\par -library does the same job as widely used non-free libraries. In this\par -case, there is little to gain by limiting the free library to free\par -software only, so we use the Lesser General Public License.\par -\par - In other cases, permission to use a particular library in non-free\par -programs enables a greater number of people to use a large body of\par -free software. For example, permission to use the GNU C Library in\par -non-free programs enables many more people to use the whole GNU\par -operating system, as well as its variant, the GNU/Linux operating\par -system.\par -\par - Although the Lesser General Public License is Less protective of the\par -users' freedom, it does ensure that the user of a program that is\par -linked with the Library has the freedom and the wherewithal to run\par -that program using a modified version of the Library.\par -\par - The precise terms and conditions for copying, distribution and\par -modification follow. Pay close attention to the difference between a\par -"work based on the library" and a "work that uses the library". The\par -former contains code derived from the library, whereas the latter must\par -be combined with the library in order to run.\par -\page\par -\tab\tab GNU LESSER GENERAL PUBLIC LICENSE\par - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\par -\par - 0. This License Agreement applies to any software library or other\par -program which contains a notice placed by the copyright holder or\par -other authorized party saying it may be distributed under the terms of\par -this Lesser General Public License (also called "this License").\par -Each licensee is addressed as "you".\par -\par - A "library" means a collection of software functions and/or data\par -prepared so as to be conveniently linked with application programs\par -(which use some of those functions and data) to form executables.\par -\par - The "Library", below, refers to any such software library or work\par -which has been distributed under these terms. A "work based on the\par -Library" means either the Library or any derivative work under\par -copyright law: that is to say, a work containing the Library or a\par -portion of it, either verbatim or with modifications and/or translated\par -straightforwardly into another language. (Hereinafter, translation is\par -included without limitation in the term "modification".)\par -\par - "Source code" for a work means the preferred form of the work for\par -making modifications to it. For a library, complete source code means\par -all the source code for all modules it contains, plus any associated\par -interface definition files, plus the scripts used to control compilation\par -and installation of the library.\par -\par - Activities other than copying, distribution and modification are not\par -covered by this License; they are outside its scope. The act of\par -running a program using the Library is not restricted, and output from\par -such a program is covered only if its contents constitute a work based\par -on the Library (independent of the use of the Library in a tool for\par -writing it). Whether that is true depends on what the Library does\par -and what the program that uses the Library does.\par - \par - 1. You may copy and distribute verbatim copies of the Library's\par -complete source code as you receive it, in any medium, provided that\par -you conspicuously and appropriately publish on each copy an\par -appropriate copyright notice and disclaimer of warranty; keep intact\par -all the notices that refer to this License and to the absence of any\par -warranty; and distribute a copy of this License along with the\par -Library.\par -\par - You may charge a fee for the physical act of transferring a copy,\par -and you may at your option offer warranty protection in exchange for a\par -fee.\par -\page\par - 2. You may modify your copy or copies of the Library or any portion\par -of it, thus forming a work based on the Library, and copy and\par -distribute such modifications or work under the terms of Section 1\par -above, provided that you also meet all of these conditions:\par -\par - a) The modified work must itself be a software library.\par -\par - b) You must cause the files modified to carry prominent notices\par - stating that you changed the files and the date of any change.\par -\par - c) You must cause the whole of the work to be licensed at no\par - charge to all third parties under the terms of this License.\par -\par - d) If a facility in the modified Library refers to a function or a\par - table of data to be supplied by an application program that uses\par - the facility, other than as an argument passed when the facility\par - is invoked, then you must make a good faith effort to ensure that,\par - in the event an application does not supply such function or\par - table, the facility still operates, and performs whatever part of\par - its purpose remains meaningful.\par -\par - (For example, a function in a library to compute square roots has\par - a purpose that is entirely well-defined independent of the\par - application. Therefore, Subsection 2d requires that any\par - application-supplied function or table used by this function must\par - be optional: if the application does not supply it, the square\par - root function must still compute square roots.)\par -\par -These requirements apply to the modified work as a whole. If\par -identifiable sections of that work are not derived from the Library,\par -and can be reasonably considered independent and separate works in\par -themselves, then this License, and its terms, do not apply to those\par -sections when you distribute them as separate works. But when you\par -distribute the same sections as part of a whole which is a work based\par -on the Library, the distribution of the whole must be on the terms of\par -this License, whose permissions for other licensees extend to the\par -entire whole, and thus to each and every part regardless of who wrote\par -it.\par -\par -Thus, it is not the intent of this section to claim rights or contest\par -your rights to work written entirely by you; rather, the intent is to\par -exercise the right to control the distribution of derivative or\par -collective works based on the Library.\par -\par -In addition, mere aggregation of another work not based on the Library\par -with the Library (or with a work based on the Library) on a volume of\par -a storage or distribution medium does not bring the other work under\par -the scope of this License.\par -\par - 3. You may opt to apply the terms of the ordinary GNU General Public\par -License instead of this License to a given copy of the Library. To do\par -this, you must alter all the notices that refer to this License, so\par -that they refer to the ordinary GNU General Public License, version 2,\par -instead of to this License. (If a newer version than version 2 of the\par -ordinary GNU General Public License has appeared, then you can specify\par -that version instead if you wish.) Do not make any other change in\par -these notices.\par -\page\par - Once this change is made in a given copy, it is irreversible for\par -that copy, so the ordinary GNU General Public License applies to all\par -subsequent copies and derivative works made from that copy.\par -\par - This option is useful when you wish to copy part of the code of\par -the Library into a program that is not a library.\par -\par - 4. You may copy and distribute the Library (or a portion or\par -derivative of it, under Section 2) in object code or executable form\par -under the terms of Sections 1 and 2 above provided that you accompany\par -it with the complete corresponding machine-readable source code, which\par -must be distributed under the terms of Sections 1 and 2 above on a\par -medium customarily used for software interchange.\par -\par - If distribution of object code is made by offering access to copy\par -from a designated place, then offering equivalent access to copy the\par -source code from the same place satisfies the requirement to\par -distribute the source code, even though third parties are not\par -compelled to copy the source along with the object code.\par -\par - 5. A program that contains no derivative of any portion of the\par -Library, but is designed to work with the Library by being compiled or\par -linked with it, is called a "work that uses the Library". Such a\par -work, in isolation, is not a derivative work of the Library, and\par -therefore falls outside the scope of this License.\par -\par - However, linking a "work that uses the Library" with the Library\par -creates an executable that is a derivative of the Library (because it\par -contains portions of the Library), rather than a "work that uses the\par -library". The executable is therefore covered by this License.\par -Section 6 states terms for distribution of such executables.\par -\par - When a "work that uses the Library" uses material from a header file\par -that is part of the Library, the object code for the work may be a\par -derivative work of the Library even though the source code is not.\par -Whether this is true is especially significant if the work can be\par -linked without the Library, or if the work is itself a library. The\par -threshold for this to be true is not precisely defined by law.\par -\par - If such an object file uses only numerical parameters, data\par -structure layouts and accessors, and small macros and small inline\par -functions (ten lines or less in length), then the use of the object\par -file is unrestricted, regardless of whether it is legally a derivative\par -work. (Executables containing this object code plus portions of the\par -Library will still fall under Section 6.)\par -\par - Otherwise, if the work is a derivative of the Library, you may\par -distribute the object code for the work under the terms of Section 6.\par -Any executables containing that work also fall under Section 6,\par -whether or not they are linked directly with the Library itself.\par -\page\par - 6. As an exception to the Sections above, you may also combine or\par -link a "work that uses the Library" with the Library to produce a\par -work containing portions of the Library, and distribute that work\par -under terms of your choice, provided that the terms permit\par -modification of the work for the customer's own use and reverse\par -engineering for debugging such modifications.\par -\par - You must give prominent notice with each copy of the work that the\par -Library is used in it and that the Library and its use are covered by\par -this License. You must supply a copy of this License. If the work\par -during execution displays copyright notices, you must include the\par -copyright notice for the Library among them, as well as a reference\par -directing the user to the copy of this License. Also, you must do one\par -of these things:\par -\par - a) Accompany the work with the complete corresponding\par - machine-readable source code for the Library including whatever\par - changes were used in the work (which must be distributed under\par - Sections 1 and 2 above); and, if the work is an executable linked\par - with the Library, with the complete machine-readable "work that\par - uses the Library", as object code and/or source code, so that the\par - user can modify the Library and then relink to produce a modified\par - executable containing the modified Library. (It is understood\par - that the user who changes the contents of definitions files in the\par - Library will not necessarily be able to recompile the application\par - to use the modified definitions.)\par -\par - b) Use a suitable shared library mechanism for linking with the\par - Library. A suitable mechanism is one that (1) uses at run time a\par - copy of the library already present on the user's computer system,\par - rather than copying library functions into the executable, and (2)\par - will operate properly with a modified version of the library, if\par - the user installs one, as long as the modified version is\par - interface-compatible with the version that the work was made with.\par -\par - c) Accompany the work with a written offer, valid for at\par - least three years, to give the same user the materials\par - specified in Subsection 6a, above, for a charge no more\par - than the cost of performing this distribution.\par -\par - d) If distribution of the work is made by offering access to copy\par - from a designated place, offer equivalent access to copy the above\par - specified materials from the same place.\par -\par - e) Verify that the user has already received a copy of these\par - materials or that you have already sent this user a copy.\par -\par - For an executable, the required form of the "work that uses the\par -Library" must include any data and utility programs needed for\par -reproducing the executable from it. However, as a special exception,\par -the materials to be distributed need not include anything that is\par -normally distributed (in either source or binary form) with the major\par -components (compiler, kernel, and so on) of the operating system on\par -which the executable runs, unless that component itself accompanies\par -the executable.\par -\par - It may happen that this requirement contradicts the license\par -restrictions of other proprietary libraries that do not normally\par -accompany the operating system. Such a contradiction means you cannot\par -use both them and the Library together in an executable that you\par -distribute.\par -\page\par - 7. You may place library facilities that are a work based on the\par -Library side-by-side in a single library together with other library\par -facilities not covered by this License, and distribute such a combined\par -library, provided that the separate distribution of the work based on\par -the Library and of the other library facilities is otherwise\par -permitted, and provided that you do these two things:\par -\par - a) Accompany the combined library with a copy of the same work\par - based on the Library, uncombined with any other library\par - facilities. This must be distributed under the terms of the\par - Sections above.\par -\par - b) Give prominent notice with the combined library of the fact\par - that part of it is a work based on the Library, and explaining\par - where to find the accompanying uncombined form of the same work.\par -\par - 8. You may not copy, modify, sublicense, link with, or distribute\par -the Library except as expressly provided under this License. Any\par -attempt otherwise to copy, modify, sublicense, link with, or\par -distribute the Library is void, and will automatically terminate your\par -rights under this License. However, parties who have received copies,\par -or rights, from you under this License will not have their licenses\par -terminated so long as such parties remain in full compliance.\par -\par - 9. You are not required to accept this License, since you have not\par -signed it. However, nothing else grants you permission to modify or\par -distribute the Library or its derivative works. These actions are\par -prohibited by law if you do not accept this License. Therefore, by\par -modifying or distributing the Library (or any work based on the\par -Library), you indicate your acceptance of this License to do so, and\par -all its terms and conditions for copying, distributing or modifying\par -the Library or works based on it.\par -\par - 10. Each time you redistribute the Library (or any work based on the\par -Library), the recipient automatically receives a license from the\par -original licensor to copy, distribute, link with or modify the Library\par -subject to these terms and conditions. You may not impose any further\par -restrictions on the recipients' exercise of the rights granted herein.\par -You are not responsible for enforcing compliance by third parties with\par -this License.\par -\page\par - 11. If, as a consequence of a court judgment or allegation of patent\par -infringement or for any other reason (not limited to patent issues),\par -conditions are imposed on you (whether by court order, agreement or\par -otherwise) that contradict the conditions of this License, they do not\par -excuse you from the conditions of this License. If you cannot\par -distribute so as to satisfy simultaneously your obligations under this\par -License and any other pertinent obligations, then as a consequence you\par -may not distribute the Library at all. For example, if a patent\par -license would not permit royalty-free redistribution of the Library by\par -all those who receive copies directly or indirectly through you, then\par -the only way you could satisfy both it and this License would be to\par -refrain entirely from distribution of the Library.\par -\par -If any portion of this section is held invalid or unenforceable under any\par -particular circumstance, the balance of the section is intended to apply,\par -and the section as a whole is intended to apply in other circumstances.\par -\par -It is not the purpose of this section to induce you to infringe any\par -patents or other property right claims or to contest validity of any\par -such claims; this section has the sole purpose of protecting the\par -integrity of the free software distribution system which is\par -implemented by public license practices. Many people have made\par -generous contributions to the wide range of software distributed\par -through that system in reliance on consistent application of that\par -system; it is up to the author/donor to decide if he or she is willing\par -to distribute software through any other system and a licensee cannot\par -impose that choice.\par -\par -This section is intended to make thoroughly clear what is believed to\par -be a consequence of the rest of this License.\par -\par - 12. If the distribution and/or use of the Library is restricted in\par -certain countries either by patents or by copyrighted interfaces, the\par -original copyright holder who places the Library under this License may add\par -an explicit geographical distribution limitation excluding those countries,\par -so that distribution is permitted only in or among countries not thus\par -excluded. In such case, this License incorporates the limitation as if\par -written in the body of this License.\par -\par - 13. The Free Software Foundation may publish revised and/or new\par -versions of the Lesser General Public License from time to time.\par -Such new versions will be similar in spirit to the present version,\par -but may differ in detail to address new problems or concerns.\par -\par -Each version is given a distinguishing version number. If the Library\par -specifies a version number of this License which applies to it and\par -"any later version", you have the option of following the terms and\par -conditions either of that version or of any later version published by\par -the Free Software Foundation. If the Library does not specify a\par -license version number, you may choose any version ever published by\par -the Free Software Foundation.\par -\page\par - 14. If you wish to incorporate parts of the Library into other free\par -programs whose distribution conditions are incompatible with these,\par -write to the author to ask for permission. For software which is\par -copyrighted by the Free Software Foundation, write to the Free\par -Software Foundation; we sometimes make exceptions for this. Our\par -decision will be guided by the two goals of preserving the free status\par -of all derivatives of our free software and of promoting the sharing\par -and reuse of software generally.\par -\par -\tab\tab\tab NO WARRANTY\par -\par - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO\par -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.\par -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR\par -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY\par -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE\par -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\par -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE\par -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME\par -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\par -\par - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN\par -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY\par -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU\par -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR\par -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE\par -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING\par -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A\par -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF\par -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\par -DAMAGES.\par -\par -\tab\tab END OF TERMS AND CONDITIONS\par -\page\par -} - \ No newline at end of file diff --git a/Tools/MilkshapeExport/setup/build.bat b/Tools/MilkshapeExport/setup/build.bat deleted file mode 100644 index 128903243ad..00000000000 --- a/Tools/MilkshapeExport/setup/build.bat +++ /dev/null @@ -1,8 +0,0 @@ -@echo off - -candle milkshapeinstall.wxs -light -out OgreMilkshapeExporter.msi milkshapeinstall.wixobj %WIX_ROOT%\ui\wixui_featuretree.wixlib -goto end - -:end -pause diff --git a/Tools/MilkshapeExport/setup/milkshapeinstall.wxs b/Tools/MilkshapeExport/setup/milkshapeinstall.wxs deleted file mode 100644 index 5a26b77671a..00000000000 --- a/Tools/MilkshapeExport/setup/milkshapeinstall.wxs +++ /dev/null @@ -1,74 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - FILEEXISTS - - - - - - - - - - - diff --git a/Tools/MilkshapeExport/src/MilkshapeExporter.cpp b/Tools/MilkshapeExport/src/MilkshapeExporter.cpp deleted file mode 100644 index f3387a61dd3..00000000000 --- a/Tools/MilkshapeExport/src/MilkshapeExporter.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "MilkshapeExport.h" - -// Implement the required DLL factory method -cMsPlugIn* CreatePlugIn () -{ - return new MilkshapePlugin (); -} - -BOOL APIENTRY DllMain( HANDLE hModule, - DWORD ul_reason_for_call, - LPVOID lpReserved - ) -{ - switch (ul_reason_for_call) - { - case DLL_PROCESS_ATTACH: - case DLL_THREAD_ATTACH: - case DLL_THREAD_DETACH: - case DLL_PROCESS_DETACH: - break; - } - return TRUE; -} - - - diff --git a/Tools/MilkshapeExport/src/MilkshapePlugin.cpp b/Tools/MilkshapeExport/src/MilkshapePlugin.cpp deleted file mode 100644 index 650486ece2c..00000000000 --- a/Tools/MilkshapeExport/src/MilkshapePlugin.cpp +++ /dev/null @@ -1,1136 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "MilkshapePlugin.h" -#include "Ogre.h" -#include "msLib.h" -#include "resource.h" -#include "OgreStringConverter.h" -#include "OgreDefaultHardwareBufferManager.h" -#include "OgreHardwareVertexBuffer.h" -#include "OgreVertexIndexData.h" -#include "OgreResourceGroupManager.h" - - -//--------------------------------------------------------------------- -MilkshapePlugin::MilkshapePlugin () -{ - strcpy(mTitle, "OGRE Mesh / Skeleton..."); -} -//--------------------------------------------------------------------- -MilkshapePlugin::~MilkshapePlugin () -{ - // do nothing -} -//--------------------------------------------------------------------- -int MilkshapePlugin::GetType () -{ - return(cMsPlugIn::eTypeExport|eNormalsAndTexCoordsPerTriangleVertex); -} -//--------------------------------------------------------------------- -const char* MilkshapePlugin::GetTitle () -{ - return mTitle; -} -//--------------------------------------------------------------------- -int MilkshapePlugin::Execute (msModel* pModel) -{ - // Do nothing if no model selected - if (!pModel) - return -1; - - Ogre::LogManager logMgr; - logMgr.createLog("msOgreExporter.log", true); - logMgr.logMessage("OGRE Milkshape Exporter Log"); - logMgr.logMessage("---------------------------"); - Ogre::ResourceGroupManager resGrpMgr; - - // - // check, if we have something to export - // - if (msModel_GetMeshCount (pModel) == 0) - { - ::MessageBox (NULL, "The model is empty! Nothing exported!", "OGRE Export", MB_OK | MB_ICONWARNING); - return 0; - } - - if (!showOptions()) return 0; - - if (exportMesh) - { - doExportMesh(pModel); - } - - return 0; - -} -//--------------------------------------------------------------------- -MilkshapePlugin *plugin; -#if OGRE_ARCHITECTURE_64 == OGRE_ARCH_TYPE -INT_PTR MilkshapePlugin::DlgProc(HWND hDlg, UINT iMsg, WPARAM wParam, LPARAM lParam) -#else -BOOL MilkshapePlugin::DlgProc(HWND hDlg, UINT iMsg, WPARAM wParam, LPARAM lParam) -#endif -{ - HWND hwndDlgItem; - int sel; - - switch (iMsg) - { - - case WM_INITDIALOG: - // Center myself - int x, y, screenWidth, screenHeight; - RECT rcDlg; - GetWindowRect(hDlg, &rcDlg); - screenWidth = GetSystemMetrics(SM_CXFULLSCREEN); - screenHeight = GetSystemMetrics(SM_CYFULLSCREEN); - - x = (screenWidth / 2) - ((rcDlg.right - rcDlg.left) / 2); - y = (screenHeight / 2) - ((rcDlg.bottom - rcDlg.top) / 2); - - MoveWindow(hDlg, x, y, (rcDlg.right - rcDlg.left), - (rcDlg.bottom - rcDlg.top), TRUE); - - // Check mesh export - hwndDlgItem = GetDlgItem(hDlg, IDC_EXPORT_MESH); - SendMessage(hwndDlgItem, BM_SETCHECK, BST_CHECKED,0); - - // Set default LOD options - hwndDlgItem = GetDlgItem(hDlg, IDC_NUM_LODS); - SetWindowText(hwndDlgItem, "5"); - hwndDlgItem = GetDlgItem(hDlg, IDC_LOD_DEPTH); - SetWindowText(hwndDlgItem, "500"); - hwndDlgItem = GetDlgItem(hDlg, IDC_LOD_VRQ); - SetWindowText(hwndDlgItem, "25"); - hwndDlgItem = GetDlgItem(hDlg, IDC_CBO_LOD_STYLE); - SendMessage(hwndDlgItem, CB_ADDSTRING, 0, (LPARAM)"percent"); - SendMessage(hwndDlgItem, CB_ADDSTRING, 0, (LPARAM)"vertices"); - SendMessage(hwndDlgItem, CB_SETCURSEL, 0, 0); - - // Check edge lists - hwndDlgItem = GetDlgItem(hDlg, IDC_EDGE_LISTS); - SendMessage(hwndDlgItem, BM_SETCHECK, BST_CHECKED,0); - - // Check skeleton export - hwndDlgItem = GetDlgItem(hDlg, IDC_EXPORT_SKEL); - SendMessage(hwndDlgItem, BM_SETCHECK, BST_CHECKED,0); - - // Set tangents option - hwndDlgItem = GetDlgItem(hDlg, IDC_TANGENTS_TARGET); - SendMessage(hwndDlgItem, CB_ADDSTRING, 0, (LPARAM)"Tangent Semantic"); - SendMessage(hwndDlgItem, CB_ADDSTRING, 0, (LPARAM)"Texture Coord Semantic"); - SendMessage(hwndDlgItem, CB_SETCURSEL, 0, 0); - - - - // Set default FPS - hwndDlgItem = GetDlgItem(hDlg, IDC_FPS); - SetWindowText(hwndDlgItem, "24"); - - - return TRUE; - case WM_COMMAND: - switch (LOWORD(wParam)) - { - case IDOK: - char val[20]; - - // Set options - hwndDlgItem = GetDlgItem(hDlg, IDC_EXPORT_MESH); - plugin->exportMesh = (SendMessage(hwndDlgItem, BM_GETCHECK, 0, 0) == BST_CHECKED) ? true : false; - - hwndDlgItem = GetDlgItem(hDlg, IDC_GENERATE_LOD); - plugin->generateLods = (SendMessage(hwndDlgItem, BM_GETCHECK, 0, 0) == BST_CHECKED) ? true : false; - if (plugin->generateLods) - { - hwndDlgItem = GetDlgItem(hDlg, IDC_NUM_LODS); - GetWindowText(hwndDlgItem, val, 20); - plugin->numLods = atoi(val); - if (!plugin->numLods) - { - MessageBox(hDlg, "Invalid number of LODs specified", "Validation error", MB_OK | MB_ICONEXCLAMATION); - return TRUE; - } - hwndDlgItem = GetDlgItem(hDlg, IDC_LOD_DEPTH); - GetWindowText(hwndDlgItem, val, 20); - plugin->lodDepthIncrement = atof(val); - if (!plugin->lodDepthIncrement) - { - MessageBox(hDlg, "Invalid LOD depth increment specified", "Validation error", MB_OK | MB_ICONEXCLAMATION); - return TRUE; - } - hwndDlgItem = GetDlgItem(hDlg, IDC_LOD_VRQ); - GetWindowText(hwndDlgItem, val, 20); - plugin->lodReductionAmount = atof(val); - if (!plugin->lodReductionAmount) - { - MessageBox(hDlg, "Invalid LOD reduction amount specified", "Validation error", MB_OK | MB_ICONEXCLAMATION); - return TRUE; - } - hwndDlgItem = GetDlgItem(hDlg, IDC_CBO_LOD_STYLE); - sel = SendMessage(hwndDlgItem, CB_GETCURSEL,0,0); - if (sel == 0) - { - // percent - plugin->lodReductionMethod = Ogre::ProgressiveMesh::VRQ_PROPORTIONAL; - // adjust percent to parametric - plugin->lodReductionAmount *= 0.01; - } - else if (sel == 1) - { - // absolute - plugin->lodReductionMethod = Ogre::ProgressiveMesh::VRQ_CONSTANT; - } - else - { - MessageBox(hDlg, "Invalid LOD reduction method specified", "Validation error", MB_OK | MB_ICONEXCLAMATION); - return TRUE; - } - - } - - hwndDlgItem = GetDlgItem(hDlg, IDC_EDGE_LISTS); - plugin->generateEdgeLists = (SendMessage(hwndDlgItem, BM_GETCHECK, 0, 0) == BST_CHECKED) ? true : false; - - hwndDlgItem = GetDlgItem(hDlg, IDC_TANGENT_VECTORS); - plugin->generateTangents = (SendMessage(hwndDlgItem, BM_GETCHECK, 0, 0) == BST_CHECKED) ? true : false; - hwndDlgItem = GetDlgItem(hDlg, IDC_TANGENTS_TARGET); - sel = SendMessage(hwndDlgItem, CB_GETCURSEL,0,0); - if (sel == 0) - { - // tangents - plugin->tangentSemantic = Ogre::VES_TANGENT; - } - else - { - // texture coords - plugin->tangentSemantic = Ogre::VES_TEXTURE_COORDINATES; - } - hwndDlgItem = GetDlgItem(hDlg, IDC_TANG_SPLIT_MIRR); - plugin->tangentsSplitMirrored = (SendMessage(hwndDlgItem, BM_GETCHECK, 0, 0) == BST_CHECKED) ? true : false; - hwndDlgItem = GetDlgItem(hDlg, IDC_TANG_SPLIT_ROT); - plugin->tangentsSplitRotated = (SendMessage(hwndDlgItem, BM_GETCHECK, 0, 0) == BST_CHECKED) ? true : false; - hwndDlgItem = GetDlgItem(hDlg, IDC_4D_TANGENTS); - plugin->tangentsUseParity = (SendMessage(hwndDlgItem, BM_GETCHECK, 0, 0) == BST_CHECKED) ? true : false; - - hwndDlgItem = GetDlgItem(hDlg, IDC_EXPORT_SKEL); - plugin->exportSkeleton = (SendMessage(hwndDlgItem, BM_GETCHECK, 0, 0) == BST_CHECKED) ? true : false; - - - hwndDlgItem = GetDlgItem(hDlg, IDC_SPLIT_ANIMATION); - plugin->splitAnimations = (SendMessage(hwndDlgItem, BM_GETCHECK, 0, 0) == BST_CHECKED) ? true : false; - - hwndDlgItem = GetDlgItem(hDlg, IDC_EXPORT_MATERIALS); - plugin->exportMaterials = (SendMessage(hwndDlgItem, BM_GETCHECK, 0, 0) == BST_CHECKED) ? true : false; - - hwndDlgItem = GetDlgItem(hDlg, IDC_FPS); - GetWindowText(hwndDlgItem, val, 20); - plugin->fps = atof(val); - if (!plugin->fps) - { - MessageBox(hDlg, "Invalid frame rate specified", "Validation error", MB_OK | MB_ICONEXCLAMATION); - return TRUE; - } - - EndDialog(hDlg, TRUE); - return TRUE; - case IDCANCEL: - EndDialog(hDlg, FALSE); - return FALSE; - } - } - - return FALSE; - -} - -//--------------------------------------------------------------------- -bool MilkshapePlugin::showOptions(void) -{ - HINSTANCE hInst = NULL; - static const TCHAR staticVar; - GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, &staticVar, &hInst); - - plugin = this; - exportMesh = true; - exportSkeleton = false; - - return (DialogBox(hInst, MAKEINTRESOURCE(IDD_OPTIONS), NULL, DlgProc) == TRUE); - - - - - - -} - -void MilkshapePlugin::doExportMesh(msModel* pModel) -{ - - - // Create singletons - Ogre::SkeletonManager skelMgr; - Ogre::DefaultHardwareBufferManager defHWBufMgr; - Ogre::LogManager& logMgr = Ogre::LogManager::getSingleton(); - Ogre::MeshManager meshMgr; - - - // - // choose filename - // - OPENFILENAME ofn; - memset (&ofn, 0, sizeof (OPENFILENAME)); - - char szFile[MS_MAX_PATH]; - char szFileTitle[MS_MAX_PATH]; - char szDefExt[32] = "mesh"; - char szFilter[128] = "OGRE .mesh Files (*.mesh)\0*.mesh\0All Files (*.*)\0*.*\0\0"; - szFile[0] = '\0'; - szFileTitle[0] = '\0'; - - ofn.lStructSize = sizeof (OPENFILENAME); - ofn.lpstrDefExt = szDefExt; - ofn.lpstrFilter = szFilter; - ofn.lpstrFile = szFile; - ofn.nMaxFile = MS_MAX_PATH; - ofn.lpstrFileTitle = szFileTitle; - ofn.nMaxFileTitle = MS_MAX_PATH; - ofn.Flags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST; - ofn.lpstrTitle = "Export to OGRE Mesh"; - - if (!::GetSaveFileName (&ofn)) - return /*0*/; - - logMgr.logMessage("Creating Mesh object..."); - Ogre::MeshPtr ogreMesh = Ogre::MeshManager::getSingleton().create("export", - Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - logMgr.logMessage("Mesh object created."); - - bool foundBoneAssignment = false; - - // No shared geometry - int i; - int wh, numbones; - int intweight[3], intbones[3]; - size_t j; - Ogre::Vector3 min, max, currpos; - Ogre::Real maxSquaredRadius; - bool first = true; - for (i = 0; i < msModel_GetMeshCount (pModel); i++) - { - msMesh *pMesh = msModel_GetMeshAt (pModel, i); - - logMgr.logMessage("Creating SubMesh object..."); - Ogre::SubMesh* ogreSubMesh = ogreMesh->createSubMesh(); - logMgr.logMessage("SubMesh object created."); - // Set material - logMgr.logMessage("Getting SubMesh Material..."); - int matIdx = msMesh_GetMaterialIndex(pMesh); - - if (matIdx == -1) - { - // No material, use blank - ogreSubMesh->setMaterialName("BaseWhite"); - logMgr.logMessage("No Material, using default 'BaseWhite'."); - } - else - { - - msMaterial *pMat = msModel_GetMaterialAt(pModel, matIdx); - ogreSubMesh->setMaterialName(pMat->szName); - logMgr.logMessage("SubMesh Material Done."); - } - - - logMgr.logMessage("Setting up geometry..."); - // Set up mesh geometry - ogreSubMesh->vertexData = new Ogre::VertexData(); - ogreSubMesh->vertexData->vertexCount = msMesh_GetVertexCount (pMesh); - ogreSubMesh->vertexData->vertexStart = 0; - Ogre::VertexBufferBinding* bind = ogreSubMesh->vertexData->vertexBufferBinding; - Ogre::VertexDeclaration* decl = ogreSubMesh->vertexData->vertexDeclaration; - // Always 1 texture layer, 2D coords - #define POSITION_BINDING 0 - #define NORMAL_BINDING 1 - #define TEXCOORD_BINDING 2 - decl->addElement(POSITION_BINDING, 0, Ogre::VET_FLOAT3, Ogre::VES_POSITION); - decl->addElement(NORMAL_BINDING, 0, Ogre::VET_FLOAT3, Ogre::VES_NORMAL); - decl->addElement(TEXCOORD_BINDING, 0, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES); - // Create buffers - Ogre::HardwareVertexBufferSharedPtr pbuf = Ogre::HardwareBufferManager::getSingleton(). - createVertexBuffer(decl->getVertexSize(POSITION_BINDING), ogreSubMesh->vertexData->vertexCount, - Ogre::HardwareBuffer::HBU_DYNAMIC, false); - Ogre::HardwareVertexBufferSharedPtr nbuf = Ogre::HardwareBufferManager::getSingleton(). - createVertexBuffer(decl->getVertexSize(NORMAL_BINDING), ogreSubMesh->vertexData->vertexCount, - Ogre::HardwareBuffer::HBU_DYNAMIC, false); - Ogre::HardwareVertexBufferSharedPtr tbuf = Ogre::HardwareBufferManager::getSingleton(). - createVertexBuffer(decl->getVertexSize(TEXCOORD_BINDING), ogreSubMesh->vertexData->vertexCount, - Ogre::HardwareBuffer::HBU_DYNAMIC, false); - bind->setBinding(POSITION_BINDING, pbuf); - bind->setBinding(NORMAL_BINDING, nbuf); - bind->setBinding(TEXCOORD_BINDING, tbuf); - - ogreSubMesh->useSharedVertices = false; - - float* pPos = static_cast( - pbuf->lock(Ogre::HardwareBuffer::HBL_DISCARD)); - - logMgr.logMessage("Doing positions and texture coords..."); - for (j = 0; j < ogreSubMesh->vertexData->vertexCount; ++j) - { - logMgr.logMessage("Doing vertex " + Ogre::StringConverter::toString(j)); - msVertex *pVertex = msMesh_GetVertexAt (pMesh, (int)j); - msVertexEx *pVertexEx=msMesh_GetVertexExAt(pMesh, (int)j); - msVec3 Vertex; - msVertex_GetVertex (pVertex, Vertex); - - *pPos++ = Vertex[0]; - *pPos++ = Vertex[1]; - *pPos++ = Vertex[2]; - // Deal with bounds - currpos = Ogre::Vector3(Vertex[0], Vertex[1], Vertex[2]); - if (first) - { - min = max = currpos; - maxSquaredRadius = currpos.squaredLength(); - first = false; - } - else - { - min.makeFloor(currpos); - max.makeCeil(currpos); - maxSquaredRadius = std::max(maxSquaredRadius, currpos.squaredLength()); - } - - int boneIdx = msVertex_GetBoneIndex(pVertex); - if (boneIdx != -1) - { - foundBoneAssignment = true; - numbones = 1; - intbones[0] = intbones[1] = intbones[2] = -1; - intweight[0] = intweight[1] = intweight[2] = 0; - for(wh = 0; wh < 3; ++wh) - { - intbones[wh] = msVertexEx_GetBoneIndices(pVertexEx, wh); - if(intbones[wh] == -1) - break; - - ++numbones; - intweight[wh] = msVertexEx_GetBoneWeights(pVertexEx, wh); - - } // for(k) - Ogre::VertexBoneAssignment vertAssign; - vertAssign.boneIndex = boneIdx; - vertAssign.vertexIndex = (unsigned int)j; - if(numbones == 1) - { - vertAssign.weight = 1.0; - } // single assignment - else - { - vertAssign.weight=(Ogre::Real)intweight[0]/100.0; - } - ogreSubMesh->addBoneAssignment(vertAssign); - if(numbones > 1) - { - // this somewhat contorted logic is because the first weight [0] matches to the bone assignment - // located with pVertex. The next two weights [1][2] match up to the first two bones found - // with pVertexEx [0][1]. The weight for the fourth bone, if present, is the unassigned weight - for(wh = 0; wh < 3; wh++) - { - boneIdx = intbones[wh]; - if(boneIdx == -1) - break; - vertAssign.boneIndex = boneIdx; - vertAssign.vertexIndex = (unsigned int)j; - if(wh == 2) - { - // fourth weight is 1.0-(sumoffirstthreeweights) - vertAssign.weight = 1.0-(((Ogre::Real)intweight[0]/100.0)+ - ((Ogre::Real)intweight[1]/100.0)+((Ogre::Real)intweight[2]/100.0)); - } - else - { - vertAssign.weight=(Ogre::Real)intweight[wh+1]; - } - ogreSubMesh->addBoneAssignment(vertAssign); - } // for(k) - } // if(numbones) - } - - } - pbuf->unlock(); - - float* pTex = static_cast( - tbuf->lock(Ogre::HardwareBuffer::HBL_DISCARD)); - logMgr.logMessage("Doing uvs, normals and indexes (v2)..."); - - // Aargh, Milkshape uses stupid separate normal indexes for the same vertex like 3DS - // Normals aren't described per vertex but per triangle vertex index - // Pain in the arse, we have to do vertex duplication again if normals differ at a vertex (non smooth) - // WHY don't people realise this format is a pain for passing to 3D APIs in vertex buffers? - float* pNorm = static_cast( - nbuf->lock(Ogre::HardwareBuffer::HBL_DISCARD)); - ogreSubMesh->indexData->indexCount = msMesh_GetTriangleCount (pMesh) * 3; - // Always use 16-bit buffers, Milkshape can't handle more anyway - Ogre::HardwareIndexBufferSharedPtr ibuf = Ogre::HardwareBufferManager::getSingleton(). - createIndexBuffer(Ogre::HardwareIndexBuffer::IT_16BIT, - ogreSubMesh->indexData->indexCount, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY); - ogreSubMesh->indexData->indexBuffer = ibuf; - unsigned short *pIdx = static_cast( - ibuf->lock(Ogre::HardwareBuffer::HBL_DISCARD)); - for (j = 0; j < ogreSubMesh->indexData->indexCount; j+=3) - { - msTriangle *pTriangle = msMesh_GetTriangleAt (pMesh, (int)j/3); - msTriangleEx *pTriangleEx=msMesh_GetTriangleExAt(pMesh, (int)j/3); - word nIndices[3]; - msTriangle_GetVertexIndices (pTriangle, nIndices); - msVec3 Normal; - msVec2 uv; - int k, vertIdx; - - for (k = 0; k < 3; ++k) - { - vertIdx = nIndices[k]; - // Face index - pIdx[j+k] = vertIdx; - - // Vertex normals - // For the moment, ignore any discrepancies per vertex - msTriangleEx_GetNormal(pTriangleEx, k, &Normal[0]); - msTriangleEx_GetTexCoord(pTriangleEx, k, &uv[0]); - pTex[(vertIdx*2)]=uv[0]; - pTex[(vertIdx*2)+1]=uv[1]; - pNorm[(vertIdx*3)] = Normal[0]; - pNorm[(vertIdx*3)+1] = Normal[1]; - pNorm[(vertIdx*3)+2] = Normal[2]; - } - - } // Faces - nbuf->unlock(); - ibuf->unlock(); - tbuf->unlock(); - - // Now use Ogre's ability to reorganise the vertex buffers the best way - Ogre::VertexDeclaration* newDecl = - ogreSubMesh->vertexData->vertexDeclaration->getAutoOrganisedDeclaration( - foundBoneAssignment, false); - Ogre::BufferUsageList bufferUsages; - for (size_t u = 0; u <= newDecl->getMaxSource(); ++u) - bufferUsages.push_back(Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY); - ogreSubMesh->vertexData->reorganiseBuffers(newDecl, bufferUsages); - - - logMgr.logMessage("Geometry done."); - } // SubMesh - - // Set bounds - ogreMesh->_setBoundingSphereRadius(Ogre::Math::Sqrt(maxSquaredRadius)); - ogreMesh->_setBounds(Ogre::AxisAlignedBox(min, max), false); - - - // Keep hold of a Skeleton pointer for deletion later - // Mesh uses Skeleton pointer for skeleton name - Ogre::SkeletonPtr pSkel; - - if (exportSkeleton && foundBoneAssignment) - { - // export skeleton, also update mesh to point to it - pSkel = doExportSkeleton(pModel, ogreMesh); - } - else if (!exportSkeleton && foundBoneAssignment) - { - // We've found bone assignments, but skeleton is not to be exported - // Prompt the user to find the skeleton - if (!locateSkeleton(ogreMesh)) - return; - - } - - // Export - logMgr.logMessage("Creating MeshSerializer.."); - Ogre::MeshSerializer serializer; - logMgr.logMessage("MeshSerializer created."); - - // Generate LODs if required - if (generateLods) - { - // Build LOD depth list - Ogre::Mesh::LodDistanceList distList; - float depth = 0; - for (unsigned short depthidx = 0; depthidx < numLods; ++depthidx) - { - depth += lodDepthIncrement; - distList.push_back(depth); - } - - ogreMesh->generateLodLevels(distList, lodReductionMethod, lodReductionAmount); - } - - if (generateEdgeLists) - { - ogreMesh->buildEdgeList(); - } - - if (generateTangents) - { - unsigned short src, dest; - ogreMesh->suggestTangentVectorBuildParams(tangentSemantic, src, dest); - ogreMesh->buildTangentVectors(tangentSemantic, src, dest, tangentsSplitMirrored, tangentsSplitRotated, tangentsUseParity); - } - - // Export - Ogre::String msg; - msg = "Exporting mesh data to file '" + Ogre::String(szFile) + "'"; - logMgr.logMessage(msg); - serializer.exportMesh(ogreMesh.get(), szFile); - logMgr.logMessage("Export successful"); - - Ogre::MeshManager::getSingleton().remove(ogreMesh->getHandle()); - if (pSkel) - Ogre::SkeletonManager::getSingleton().remove(pSkel->getHandle()); - - if (exportMaterials && msModel_GetMaterialCount(pModel) > 0) - { - doExportMaterials(pModel); - } -} - - -Ogre::SkeletonPtr MilkshapePlugin::doExportSkeleton(msModel* pModel, Ogre::MeshPtr& mesh) -{ - Ogre::LogManager &logMgr = Ogre::LogManager::getSingleton(); - Ogre::String msg; - - // - // choose filename - // - OPENFILENAME ofn; - memset (&ofn, 0, sizeof (OPENFILENAME)); - - char szFile[MS_MAX_PATH]; - char szFileTitle[MS_MAX_PATH]; - char szDefExt[32] = "skeleton"; - char szFilter[128] = "OGRE .skeleton Files (*.skeleton)\0*.skeleton\0All Files (*.*)\0*.*\0\0"; - szFile[0] = '\0'; - szFileTitle[0] = '\0'; - - ofn.lStructSize = sizeof (OPENFILENAME); - ofn.lpstrDefExt = szDefExt; - ofn.lpstrFilter = szFilter; - ofn.lpstrFile = szFile; - ofn.nMaxFile = MS_MAX_PATH; - ofn.lpstrFileTitle = szFileTitle; - ofn.nMaxFileTitle = MS_MAX_PATH; - ofn.Flags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST; - ofn.lpstrTitle = "Export to OGRE Skeleton"; - - if (!::GetSaveFileName (&ofn)) - return Ogre::SkeletonPtr(); - - // Strip off the path - Ogre::String skelName = szFile; - size_t lastSlash = skelName.find_last_of("\\"); - skelName = skelName.substr(lastSlash+1); - - // Set up - logMgr.logMessage("Trying to create Skeleton object"); - Ogre::SkeletonPtr ogreskel = Ogre::SkeletonManager::getSingleton().create(skelName, - Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - logMgr.logMessage("Skeleton object created"); - - // Complete the details - - // Do the bones - int numBones = msModel_GetBoneCount(pModel); - msg = "Number of bones: " + Ogre::StringConverter::toString(numBones); - logMgr.logMessage(msg); - - int i; - // Create all the bones in turn - for (i = 0; i < numBones; ++i) - { - msBone* bone = msModel_GetBoneAt(pModel, i); - Ogre::Bone* ogrebone = ogreskel->createBone(bone->szName); - - msVec3 msBonePos, msBoneRot; - msBone_GetPosition(bone, msBonePos); - msBone_GetRotation(bone, msBoneRot); - - Ogre::Vector3 bonePos(msBonePos[0], msBonePos[1], msBonePos[2]); - ogrebone->setPosition(bonePos); - // Hmm, Milkshape has chosen a Euler angle representation of orientation which is not smart - // Rotation Matrix or Quaternion would have been the smarter choice - // Might we have Gimbal lock here? What order are these 3 angles supposed to be applied? - // Grr, we'll try our best anyway... - Ogre::Quaternion qx, qy, qz, qfinal; - qx.FromAngleAxis(Ogre::Radian(msBoneRot[0]), Ogre::Vector3::UNIT_X); - qy.FromAngleAxis(Ogre::Radian(msBoneRot[1]), Ogre::Vector3::UNIT_Y); - qz.FromAngleAxis(Ogre::Radian(msBoneRot[2]), Ogre::Vector3::UNIT_Z); - - // Assume rotate by x then y then z - qfinal = qz * qy * qx; - ogrebone->setOrientation(qfinal); - - Ogre::LogManager::getSingleton().stream() - << "Bone #" << i << ": " << - "Name='" << bone->szName << "' " << - "Position: " << bonePos << " " << - "Ms3d Rotation: {" << msBoneRot[0] << ", " << msBoneRot[1] << ", " << msBoneRot[2] << "} " << - "Orientation: " << qfinal; - - - } - // Now we've created all the bones, link them up - logMgr.logMessage("Establishing bone hierarchy.."); - for (i = 0; i < numBones; ++i) - { - msBone* bone = msModel_GetBoneAt(pModel, i); - - if (strlen(bone->szParentName) == 0) - { - // Root bone - msg = "Root bone detected: Name='" + Ogre::String(bone->szName) + "' Index=" - + Ogre::StringConverter::toString(i); - logMgr.logMessage(msg); - } - else - { - Ogre::Bone* ogrechild = ogreskel->getBone(bone->szName); - Ogre::Bone* ogreparent = ogreskel->getBone(bone->szParentName); - - if (ogrechild == 0) - { - msg = "Error: could not locate child bone '" + - Ogre::String(bone->szName) + "'"; - logMgr.logMessage(msg); - continue; - } - if (ogreparent == 0) - { - msg = "Error: could not locate parent bone '" - + Ogre::String(bone->szParentName) + "'"; - logMgr.logMessage(msg); - continue; - } - // Make child - ogreparent->addChild(ogrechild); - } - - - } - logMgr.logMessage("Bone hierarchy established."); - - // Create the Animation(s) - doExportAnimations(pModel, ogreskel); - - - - // Create skeleton serializer & export - Ogre::SkeletonSerializer serializer; - msg = "Exporting skeleton to " + Ogre::String(szFile); - logMgr.logMessage(msg); - serializer.exportSkeleton(ogreskel.get(), szFile); - logMgr.logMessage("Skeleton exported"); - - - msg = "Linking mesh to skeleton file '" + skelName + "'"; - Ogre::LogManager::getSingleton().logMessage(msg); - - mesh->_notifySkeleton(ogreskel); - - return ogreskel; - -} - -bool MilkshapePlugin::locateSkeleton(Ogre::MeshPtr& mesh) -{ - // - // choose filename - // - OPENFILENAME ofn; - memset (&ofn, 0, sizeof (OPENFILENAME)); - - char szFile[MS_MAX_PATH]; - char szFileTitle[MS_MAX_PATH]; - char szDefExt[32] = "skeleton"; - char szFilter[128] = "OGRE .skeleton Files (*.skeleton)\0*.skeleton\0All Files (*.*)\0*.*\0\0"; - szFile[0] = '\0'; - szFileTitle[0] = '\0'; - - ofn.lStructSize = sizeof (OPENFILENAME); - ofn.lpstrDefExt = szDefExt; - ofn.lpstrFilter = szFilter; - ofn.lpstrFile = szFile; - ofn.nMaxFile = MS_MAX_PATH; - ofn.lpstrFileTitle = szFileTitle; - ofn.nMaxFileTitle = MS_MAX_PATH; - ofn.Flags = OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; - ofn.lpstrTitle = "Locate OGRE Skeleton (since you're not exporting it)"; - - if (!::GetOpenFileName (&ofn)) - return false; - - // Strip off the path - Ogre::String skelName = szFile; - size_t lastSlash = skelName.find_last_of("\\"); - skelName = skelName.substr(lastSlash+1); - - Ogre::String msg = "Linking mesh to skeleton file '" + skelName + "'"; - Ogre::LogManager::getSingleton().logMessage(msg); - - // Create a dummy skeleton for Mesh to link to (saves it trying to load it) - Ogre::SkeletonPtr pSkel = Ogre::SkeletonManager::getSingleton().create(skelName, - Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - Ogre::LogManager::getSingleton().logMessage("Dummy Skeleton object created for link."); - - mesh->_notifySkeleton(pSkel); - - return true; - -} - -struct SplitAnimationStruct -{ - int start; - int end; - Ogre::String name; -}; - -void MilkshapePlugin::doExportMaterials(msModel* pModel) -{ - Ogre::LogManager& logMgr = Ogre::LogManager::getSingleton(); - Ogre::MaterialManager matMgrSgl; - Ogre::String msg; - - matMgrSgl.initialise(); - - int numMaterials = msModel_GetMaterialCount(pModel); - msg = "Number of materials: " + Ogre::StringConverter::toString(numMaterials); - logMgr.logMessage(msg); - - OPENFILENAME ofn; - memset (&ofn, 0, sizeof (OPENFILENAME)); - - char szFile[MS_MAX_PATH]; - char szFileTitle[MS_MAX_PATH]; - char szDefExt[32] = "material"; - char szFilter[128] = "OGRE .material Files (*.material)\0*.material\0All Files (*.*)\0*.*\0\0"; - szFile[0] = '\0'; - szFileTitle[0] = '\0'; - - ofn.lStructSize = sizeof (OPENFILENAME); - ofn.lpstrDefExt = szDefExt; - ofn.lpstrFilter = szFilter; - ofn.lpstrFile = szFile; - ofn.nMaxFile = MS_MAX_PATH; - ofn.lpstrFileTitle = szFileTitle; - ofn.nMaxFileTitle = MS_MAX_PATH; - ofn.Flags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST; - ofn.lpstrTitle = "Export to OGRE Material"; - - if (!::GetSaveFileName (&ofn)) - return; - - // Strip off the path - Ogre::String matName = szFile; - size_t lastSlash = matName.find_last_of("\\"); - matName = matName.substr(lastSlash+1); - - // Set up - logMgr.logMessage("Trying to create Material object"); - - Ogre::MaterialSerializer matSer; - - for (int i = 0; i < numMaterials; ++i) - { - msMaterial *mat = msModel_GetMaterialAt(pModel, i); - - msg = "Creating material " + Ogre::String(mat->szName); - logMgr.logMessage(msg); - Ogre::MaterialPtr ogremat = matMgrSgl.create(mat->szName, - Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - logMgr.logMessage("Created."); - - ogremat->setAmbient(msVec4ToColourValue(mat->Ambient)); - ogremat->setDiffuse(msVec4ToColourValue(mat->Diffuse)); - ogremat->setSpecular(msVec4ToColourValue(mat->Specular)); - ogremat->setShininess(mat->fShininess); - - if (0 < strlen(mat->szDiffuseTexture)) - ogremat->getTechnique(0)->getPass(0)->createTextureUnitState(mat->szDiffuseTexture); - - if (0 < strlen(mat->szAlphaTexture)) - ogremat->getTechnique(0)->getPass(0)->createTextureUnitState(mat->szAlphaTexture); - - - matSer.queueForExport(ogremat); - } - - msg = "Exporting materials to " + matName; - logMgr.logMessage(msg); - matSer.exportQueued(matName); -} - -Ogre::ColourValue MilkshapePlugin::msVec4ToColourValue(float prop[4]) -{ - Ogre::ColourValue colour; - colour.r = prop[0]; - colour.g = prop[1]; - colour.b = prop[2]; - colour.a = prop[3]; - - return colour; -} - -void MilkshapePlugin::doExportAnimations(msModel* pModel, Ogre::SkeletonPtr& ogreskel) -{ - - Ogre::LogManager& logMgr = Ogre::LogManager::getSingleton(); - std::vector splitInfo; - Ogre::String msg; - - int numFrames = msModel_GetTotalFrames(pModel); - msg = "Number of frames: " + Ogre::StringConverter::toString(numFrames); - logMgr.logMessage(msg); - - if (splitAnimations) - { - // Explain - msg = "You have chosen to create multiple discrete animations by splitting up the frames in " - "the animation sequence. In order to do this, you must supply a simple text file " - "describing the separate animations, which has a single line per animation in the format: \n\n" - "startFrame,endFrame,animationName\n\nFor example: \n\n" - "1,20,Walk\n21,35,Run\n36,40,Shoot\n\n" - "..creates 3 separate animations (the frame numbers are inclusive)." - "You must browse to this file in the next dialog."; - MessageBox(0,msg.c_str(), "Splitting Animations",MB_ICONINFORMATION | MB_OK); - // Prompt for a file which contains animation splitting info - OPENFILENAME ofn; - memset (&ofn, 0, sizeof (OPENFILENAME)); - - char szFile[MS_MAX_PATH]; - char szFileTitle[MS_MAX_PATH]; - char szDefExt[32] = "skeleton"; - char szFilter[128] = "All Files (*.*)\0*.*\0\0"; - szFile[0] = '\0'; - szFileTitle[0] = '\0'; - - ofn.lStructSize = sizeof (OPENFILENAME); - ofn.lpstrDefExt = szDefExt; - ofn.lpstrFilter = szFilter; - ofn.lpstrFile = szFile; - ofn.nMaxFile = MS_MAX_PATH; - ofn.lpstrFileTitle = szFileTitle; - ofn.nMaxFileTitle = MS_MAX_PATH; - ofn.Flags = OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; - ofn.lpstrTitle = "Open animation split configuration file"; - - if (!::GetOpenFileName (&ofn)) - { - msg = "Splitting aborted, generating a single animation called 'Default'"; - MessageBox(0, msg.c_str(), "Info", MB_OK | MB_ICONWARNING); - SplitAnimationStruct split; - split.start = 1; - split.end = numFrames; - split.name = "Default"; - splitInfo.push_back(split); - } - else - { - // Read file - Ogre::String sline; - char line[256]; - SplitAnimationStruct newSplit; - - std::ifstream istr; - istr.open(szFile); - - while (!istr.eof()) - { - istr.getline(line, 256); - sline = line; - - // Ignore blanks & comments - if (sline == "" || sline.substr(0,2) == "//") - continue; - - // Split on ',' - std::vector svec = Ogre::StringUtil::split(line, ",\n"); - - // Basic validation on number of elements - if (svec.size() != 3) - { - MessageBox(0, "Warning: corrupt animation details in file. You should look into this. ", - "Corrupt animations file", MB_ICONWARNING | MB_OK); - continue; - } - // Remove any embedded spaces - Ogre::StringUtil::trim(svec[0]); - Ogre::StringUtil::trim(svec[1]); - Ogre::StringUtil::trim(svec[2]); - // Create split info - newSplit.start = atoi(svec[0].c_str()); - newSplit.end = atoi(svec[1].c_str()); - newSplit.name = svec[2]; - splitInfo.push_back(newSplit); - - } - - - } - - } - else - { - // No splitting - SplitAnimationStruct split; - split.start = 1; - split.end = numFrames; - split.name = "Default"; - splitInfo.push_back(split); - } - - // Get animation length - // Map frames -> seconds, this can be changed in speed of animation anyway - - - - int numBones = msModel_GetBoneCount(pModel); - unsigned int frameTime; - float realTime; - - std::vector::iterator animsIt; - for (animsIt = splitInfo.begin(); animsIt != splitInfo.end(); ++animsIt) - { - SplitAnimationStruct& currSplit = *animsIt; - - // Create animation - frameTime = currSplit.end - currSplit.start; - realTime = frameTime / fps; - Ogre::LogManager::getSingleton().stream() - << "Trying to create Animation object for animation " - << currSplit.name << " For Frames " << currSplit.start << " to " - << currSplit.end << " inclusive. "; - - Ogre::LogManager::getSingleton().stream() - << "Frame time = " - << frameTime << ", Seconds = " << realTime; - - Ogre::Animation *ogreanim = - ogreskel->createAnimation(currSplit.name, realTime); - logMgr.logMessage("Animation object created."); - - int i; - // Create all the animation tracks - for (i = 0; i < numBones; ++i) - { - - msBone* bone = msModel_GetBoneAt(pModel, i); - Ogre::Bone* ogrebone = ogreskel->getBone(bone->szName); - - // Create animation tracks - msg = "Creating AnimationTrack for bone " + Ogre::StringConverter::toString(i); - logMgr.logMessage(msg); - - Ogre::NodeAnimationTrack *ogretrack = ogreanim->createNodeTrack(i, ogrebone); - logMgr.logMessage("Animation track created."); - - // OGRE uses keyframes which are both position and rotation - // Milkshape separates them, but never seems to use the ability to - // have a different # of pos & rot keys - - int numKeys = msBone_GetRotationKeyCount(bone); - - msg = "Number of keyframes: " + Ogre::StringConverter::toString(numKeys); - logMgr.logMessage(msg); - - int currKeyIdx; - msPositionKey* currPosKey; - msRotationKey* currRotKey; - for (currKeyIdx = 0; currKeyIdx < numKeys; ++currKeyIdx ) - { - currPosKey = msBone_GetPositionKeyAt(bone, currKeyIdx); - currRotKey = msBone_GetRotationKeyAt(bone, currKeyIdx); - - // Make sure keyframe is in current time frame (for splitting) - if (currRotKey->fTime >= currSplit.start && currRotKey->fTime <= currSplit.end) - { - - msg = "Creating KeyFrame #" + Ogre::StringConverter::toString(currKeyIdx) - + " for bone #" + Ogre::StringConverter::toString(i); - logMgr.logMessage(msg); - // Create keyframe - // Adjust for start time, and for the fact that frames are numbered from 1 - frameTime = currRotKey->fTime - currSplit.start; - realTime = frameTime / fps; - Ogre::TransformKeyFrame *ogrekey = ogretrack->createNodeKeyFrame(realTime); - logMgr.logMessage("KeyFrame created"); - - Ogre::Vector3 kfPos; - // Imported milkshape animations may not have positions - // for all rotation keys - if ( currKeyIdx < bone->nNumPositionKeys ) { - kfPos.x = currPosKey->Position[0]; - kfPos.y = currPosKey->Position[1]; - kfPos.z = currPosKey->Position[2]; - } - else { - kfPos.x = bone->Position[0]; - kfPos.y = bone->Position[1]; - kfPos.z = bone->Position[2]; - } - Ogre::Quaternion qx, qy, qz, kfQ; - - // Milkshape translations are local to own orientation, not parent - kfPos = ogrebone->getOrientation() * kfPos; - - ogrekey->setTranslate(kfPos); - qx.FromAngleAxis(Ogre::Radian(currRotKey->Rotation[0]), Ogre::Vector3::UNIT_X); - qy.FromAngleAxis(Ogre::Radian(currRotKey->Rotation[1]), Ogre::Vector3::UNIT_Y); - qz.FromAngleAxis(Ogre::Radian(currRotKey->Rotation[2]), Ogre::Vector3::UNIT_Z); - kfQ = qz * qy * qx; - ogrekey->setRotation(kfQ); - - Ogre::LogManager::getSingleton().stream() - << "KeyFrame details: Adjusted Frame Time=" << frameTime - << " Seconds: " << realTime << " Position=" << kfPos << " " - << "Ms3d Rotation= {" << currRotKey->Rotation[0] << ", " - << currRotKey->Rotation[1] << ", " << currRotKey->Rotation[2] - << "} " << "Orientation=" << kfQ; - } // keyframe creation - - } // keys - } //Bones - } // Animations - - - - -} - diff --git a/Tools/Readme.md b/Tools/Readme.md deleted file mode 100644 index c0dc5e9b67e..00000000000 --- a/Tools/Readme.md +++ /dev/null @@ -1,180 +0,0 @@ - -# OGRE COMMAND-LINE UTILITIES - -This archive contains a few prebuilt command-line tools for manipulating your media. -For further info, visit http://www.ogre3d.org - -## Index - - [AssimpConverter](#assimpconverter) - - [BitmapFontBuilderTool](#bitmapfontbuildertool) - - [LightwaveConverter](#lightwaveconverter) - - [MayaExport](#mayaexport) - - [OgreXMLConverter](#ogrexmlconverter) - - [OgreMeshUpgrader](#ogremeshupgrader) - - [MilkshapeExport](#milkshapeexport) - - [VRMLConverter](#vrmlconverter) - - [Wings3DExporter](#wings3dexporter) - - [XSIExport](#xsiexport) - - -## AssimpConverter -Converts 3D-formats supported by assimp to native OGRE formats - -``` -Usage: OgreAssimpConverter [options] sourcefile [destination] - -Available options: --q = Quiet mode, less output --log filename = name of the log file (default: 'OgreAssimp.log') --aniSpeedMod [0..1] = Factor to scale the animation speed (default: 1.0) --3ds_ani_fix = Fix for 3ds max, which exports the animation over a - longer time frame than the animation actually plays --max_edge_angle deg = When normals are generated, max angle between - two faces to smooth over -sourcefile = name of file to convert -destination = optional name of directory to write to. If you don't - specify this the converter will use the same - directory as the sourcefile. - -``` - -## BitmapFontBuilderTool -Tool designed to take the binary width files from BitmapFontBuilder http://www.lmnopc.com/bitmapfontbuilder/ and convert them into Ogre .fontdef 'glyph' statements. - -## LightwaveConverter -Lwo2Mesh v0.89 by Dennis Verbeek ( dennis.verbeek@chello.nl ) -Linux port by Magnus Møller Petersen ( magnus@moaner.dk ) - -Lwo2Mesh is a commandline tool to convert lightwave objects into ogre-meshes. -Use -? to get help. Use *.lwo to convert multiple objects in one run. - -``` -Usage: lwo2mesh [options] source [dest] -options: - -g do not use shared geometry - -d generate level of detail information - method (f)ixed or (p)roportional - reduction (fixed) or reductionfactor (proportional) - number of LOD levels - distances - example: -dp 0.5 4 1000.0 2000.0 4000.0 8000.0 - -l save layers separately - -m do not export materials - -r rename materials - method (i)nteractive, (o)bjectname or (p)refix - example: -rp prefix_ - -s do not export skeleton - -i info on .lwo only, no conversion to mesh - -v dump vertex maps -``` - -The lightwave-object loading code is based on Lightwave SDK code by Ernie Wright. - -This program is distributed as-is and WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -## MayaExport -Ogre exporter for Maya - -[MayaExport README](MayaExport/Readme.md) - -## OgreXMLConverter -Converts between the binary and XML formats for .mesh and .skeleton. -This tool is necessary to convert from the XML to OGRE's native runtime format if your exporter produces XML. -You can find the XML Schema for the .mesh and .skeleton formats in the Ogre source under Tools/XMLConverter/docs. - -``` -Usage: OgreXMLConverter [options] sourcefile [destfile] - -Available options: --o = DON'T optimise out redundant tracks & keyframes --d3d = Prefer D3D packed colour formats (default on Windows) --gl = Prefer GL packed colour formats (default on non-Windows) --E endian = Set endian mode 'big' 'little' or 'native' (default) --q = Quiet mode, less output --log filename = name of the log file (default: 'OgreXMLConverter.log') -sourcefile = name of file to convert -destfile = optional name of file to write to. If you don't - specify this OGRE works it out through the extension - and the XML contents if the source is XML. For example - test.mesh becomes test.xml, test.xml becomes test.mesh - if the XML document root is etc. -``` - -Because the default behaviour is to convert binary to XML and vice versa, you can simply drag files onto this converter and it will convert between the 2 formats. - -## OgreMeshUpgrader -This tool upgrades a .mesh file from any previous version of OGRE to the latest version. -You will be advised in Ogre.log if your meshes are of an old version; -OGRE can still load old versions but performance may not be as good as it would be with the latest version. -You are advised to upgrade your meshes whenever you update to another major version of OGRE. - -``` -Usage: OgreMeshUpgrader [options] sourcefile [destfile] --i = Interactive mode, prompt for options --l lodlevels = number of LOD levels --d loddist = distance increment to reduce LOD --p lodpercent = Percentage triangle reduction amount per LOD --f lodnumtris = Fixed vertex reduction per LOD --e = DON'T generate edge lists (for stencil shadows) --t = Generate tangents (for normal mapping) --r = DON'T reorganise buffers to recommended format --d3d = Convert to D3D colour formats --gl = Convert to GL colour formats --srcd3d = Interpret ambiguous colours as D3D style --srcgl = Interpret ambiguous colours as GL style --E endian = Set endian mode 'big' 'little' or 'native' (default) -sourcefile = name of file to convert -destfile = optional name of file to write to. If you don't - specify this OGRE overwrites the existing file. -``` - -Again you can drag files onto this tool, so long as you don't mind it overwriting the file in place. -If you'd prefer to keep a backup, make a copy or use the command line to upgrade to a different file. - -Reorganising vertex buffers: -This tool now allows you to restructure the vertex buffers in your mesh. -If you are upgrading from a version prior to 0.15.0, then you should answer 'y' when asked if you want to reorganise the buffers, since 0.15.0 and later allows more efficient structures in the binary mesh. -You will then be shown the buffer structures for each of the geometry sections; you can either reorganise the buffers yourself, or use 'automatic' mode, which is recommended unless you know what you're doing. - -## MilkshapeExport -Allows you to export OGRE .mesh files from the shareware modelling tool Milkshape3d. - -[Milkshape Exporter README](https://htmlpreview.github.io/?https://github.com/OGRECave/ogre/blob/master/Tools/MilkshapeExport/ReadMe.html) - -## VRMLConverter -VRML - OGRE .mesh converter - -``` -Usage: - VRML2mesh [output mesh file] - Or just drag-and-drop a VRML file on the progam. - - Well... before doing that, you have to export a VRML file from your - modeler. 3dsmax, Maya and Milkshape can all do this, and their - exporters have been confirmed to create trouble-free files. - Other programs should work as well, but there are no guarantees. - -Features: - Converts VRML97 files to .mesh files containing static meshes and materials. - That's all. - -Notes: - * Make sure your objects are tesselated. They don't have to be - triangulated - the converter takes care of that, but primitive - shapes (like spheres, boxes, etc) are not recognised. - - * If you want the mesh to contain normals (which is usually the case), - then make sure that normals are exported. There is usually an option - for this in the modeler, but the default is 'off' in most programs. -``` - -### Wings3DExporter -Wings3D to OGRE converter written in Python. - -[Wings3D to OGRE converter README](Wings3DExporter/Readme.md) - -### XSIExport -This distribution contains the files required to export OGRE .mesh, .skeleton and .material files from SoftImage|XSI. -Currently supported XSI versions are 6.5 up to Softimage 2011 - -[XSI Exporter README](https://htmlpreview.github.io/?https://github.com/OGRECave/ogre/blob/master/Tools/XSIExport/OGREXSI_Readme.html) diff --git a/Tools/VRMLConverter/CMakeLists.txt b/Tools/VRMLConverter/CMakeLists.txt deleted file mode 100644 index c286e35ce48..00000000000 --- a/Tools/VRMLConverter/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure VRMLConverter - -file(GLOB HEADER_FILES vrmllib/*.h) -file(GLOB SOURCE_FILES src/VRML2mesh.cpp vrmllib/src/*.cpp) - -add_executable(VRMLConverter ${HEADER_FILES} ${SOURCE_FILES}) -target_include_directories(VRMLConverter PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/vrmllib/include) -target_link_libraries(VRMLConverter OgreMain) - -if (OGRE_PROJECT_FOLDERS) - set_property(TARGET VRMLConverter PROPERTY FOLDER Tools) -endif () -ogre_config_tool(VRMLConverter) diff --git a/Tools/VRMLConverter/Readme.md b/Tools/VRMLConverter/Readme.md deleted file mode 100644 index e89cce5a6ff..00000000000 --- a/Tools/VRMLConverter/Readme.md +++ /dev/null @@ -1,23 +0,0 @@ - -# VRML - OGRE .mesh converter - -## Usage -``` -VRML2mesh [output mesh file] -``` -Or just drag-and-drop a VRML file on the progam. - -Well... before doing that, you have to export a VRML file from your modeler. -3dsmax, Maya and Milkshape can all do this, and their exporters have been confirmed to create trouble-free files. -Other programs should work as well, but there are no guarantees. - -## Features -Converts VRML97 files to .mesh files containing static meshes and materials. -That's all. - -## Notes - - Make sure your objects are tesselated. - They don't have to be triangulated - the converter takes care of that, but primitive shapes (like spheres, boxes, etc) are not recognised. - - - If you want the mesh to contain normals (which is usually the case), then make sure that normals are exported. - There is usually an option for this in the modeler, but the default is 'off' in most programs. diff --git a/Tools/VRMLConverter/src/VRML2mesh.cpp b/Tools/VRMLConverter/src/VRML2mesh.cpp deleted file mode 100644 index 612add57079..00000000000 --- a/Tools/VRMLConverter/src/VRML2mesh.cpp +++ /dev/null @@ -1,600 +0,0 @@ -#include -#include - -#include "Ogre.h" -#include "OgreDefaultHardwareBufferManager.h" -#include "OgreLodStrategyManager.h" - -using namespace Ogre; -using namespace vrmllib; - -struct vertex { - int pos, tc, normal, colour; - - bool operator<(const vertex &v) const { - if (pos < v.pos) return true; - if (pos > v.pos) return false; - if (normal < v.normal) return true; - if (normal > v.normal) return false; - if (tc < v.tc) return true; - if (tc > v.tc) return false; - return colour < v.colour; - } -}; - -// VRML face -struct face { - std::vector indices; -}; - -// OGRE face -struct triangle { - int vertices[3]; -}; - -typedef std::vector Vec3Vec; -typedef std::vector VertVec; -typedef std::vector FaceVec; -typedef std::vector TriVec; -typedef std::vector IntVec; -typedef std::map VertMap; - -// traverse the scene graph looking for Shapes -void parseFile(Mesh *, const vrmllib::file &); -void parseNode(Mesh *, const vrmllib::node *, Matrix4 = Matrix4::IDENTITY); - -// generate a SubMesh from a Shape -void parseShape(Mesh *, const Shape *, Matrix4); - - // helpers: - Ogre::MaterialPtr parseMaterial(const Appearance *, const String &name); - void parseFaces(FaceVec &, const IndexedFaceSet *); - void triangulateAndExpand(TriVec &, VertVec &, const FaceVec &, const Shape *); - void copyToSubMesh(SubMesh *, const TriVec &, const VertVec &, const Shape *, const Matrix4 &); - -// get the array index for a VRML vertex property -int getIndex(const IntVec &coordIndex, const IntVec &, bool perVertex, int facenr, int vertnr); - -// used by findName* -typedef std::map NameMap; -NameMap gNameMap; - -// find name of DEFined node -const String *findName(const vrmllib::node *n); -const String *findNameRecursive(const vrmllib::node *n); - -String gBaseName; // base name of the input file (no path or extension) - -// conversion functions: -inline Vector3 vec(const vrmllib::vec3 &v) { return Vector3(v.x, v.y, v.z); } -inline ColourValue col(const vrmllib::col3 &c) { return ColourValue(c.r, c.g, c.b); } -inline void copyVec(Real *d, const Vector3 &s) { d[0] = s.x; d[1] = s.y; d[2] = s.z; } -inline void copyVec(Real *d, const vec2 &s) { d[0] = s.x; d[1] = s.y; } - -Matrix4 transMat(vrmllib::vec3, bool inverse = false); -Matrix4 scaleMat(vrmllib::vec3, bool inverse = false); -Matrix4 rotMat(vrmllib::rot, bool inverse = false); - -int main(int argc, char **argv) -{ -try -{ - String inname, outname, path; - - if (argc != 2 && argc != 3) - throw - "Wrong number of arguments.\n" - " Usage: VRML2mesh [output mesh file]"; - - inname = argv[1]; - - // get base name - gBaseName = inname; - size_t p = gBaseName.find_last_of("/\\"); - if (p != gBaseName.npos) { - path.assign(gBaseName, 0, p+1); - gBaseName.erase(0, p+1); - } - p = gBaseName.rfind('.'); - if (p != gBaseName.npos) - gBaseName.erase(p); - - if (argc == 3) - outname = argv[2]; - else - outname = path + gBaseName + ".mesh"; - - LogManager log; - log.createLog(path + "VRML2mesh.log"); - - Math math; - ResourceGroupManager resGrpMgr; - LodStrategyManager lodMgr; - MeshManager meshMgr; - MaterialManager materialMgr; - materialMgr.initialise(); - MeshSerializer meshSer; - MaterialSerializer matSer; - DefaultHardwareBufferManager hbm; - - MeshPtr mesh = meshMgr.create("conversionTarget", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - try { - log.logMessage("Reading " + inname); - - // read VRML file - std::ifstream infile(inname.c_str()); - if (!infile.is_open()) - throw "failed to open input file"; - - vrmllib::file vfile(infile); - log.logMessage("Finished parsing VRML file"); - - // populate name map - for (auto & def : vfile.defs) - gNameMap[def.second] = def.first; - - // search from SubMeshes - parseFile(mesh.get(), vfile); - - if (mesh->getNumSubMeshes() == 0) - throw "No SubMeshes were generated, aborting."; - - log.logMessage("Exporting Mesh"); - meshSer.exportMesh(mesh.get(), outname); - - ResourceManager::ResourceMapIterator it = materialMgr.getResourceIterator(); - while(it.hasMoreElements()) { - matSer.queueForExport(static_pointer_cast(it.getNext())); - } - - matSer.exportQueued(path + gBaseName + ".material"); - - log.logMessage("Done."); - } - catch (const char *e) { - log.logMessage(LML_NORMAL, "Error: %s", e); - return 1; - } - catch (Exception &e) { - log.logMessage("Exception: " + e.getFullDescription()); - return 1; - } - catch (std::exception &e) { - log.logMessage(LML_NORMAL, e.what()); - return 1; - } - -} -catch (Exception &e) { - std::cerr << "Exception: " << e.getFullDescription() << std::endl; - return 1; -} -catch (const char *e) { - std::cerr << e << std::endl; - return 1; -} -} - -void parseFile(Mesh *mesh, const vrmllib::file &file) -{ - for (auto root : file.roots) - parseNode(mesh, root); -} - -void parseNode(Mesh *mesh, const vrmllib::node *n, Matrix4 m) -{ - if (const Transform *tr = dynamic_cast(n)) { - // TODO: handle center, scaleOrientation - - Matrix4 trans; - trans.makeTrans(vec(tr->translation)); - - Matrix4 scale = Matrix4::IDENTITY; - scale[0][0] = tr->scale.x; - scale[1][1] = tr->scale.y; - scale[2][2] = tr->scale.z; - - Matrix3 rot3; - rot3.FromAngleAxis(vec(tr->rotation.vector), Radian(tr->rotation.radians)); - Matrix4 rot = Matrix4::IDENTITY; - rot = rot3; - - m = m * transMat(tr->translation) * transMat(tr->center) - * rotMat(tr->rotation) * rotMat(tr->scaleOrientation) * scaleMat(tr->scale) - * rotMat(tr->scaleOrientation, true) * transMat(tr->center, true); - } - - if (const grouping_node *gn = dynamic_cast(n)) { - for (auto i : gn->children) - parseNode(mesh, i, m); - - } else if (const Shape *sh = dynamic_cast(n)) - parseShape(mesh, sh, m); -} - -void parseShape(Mesh *mesh, const Shape *sh, Matrix4 mat) -{ -try -{ - LogManager &log = LogManager::getSingleton(); - log.logMessage("Found a Shape..."); - - IndexedFaceSet *ifs = dynamic_cast(sh->geometry); - if (!ifs) - throw "Geometry was not an IndexedFaceSet, keep looking"; - - Coordinate *coord = dynamic_cast(ifs->coord); - if (!coord) - throw "Invalid Coordinate node"; - if (coord->point.empty()) - throw "No coordinates found, ignoring this Shape"; - - SubMesh *sub; - if (const String *name = findNameRecursive(sh)) { - log.logMessage("Creating SubMesh: " + *name); - sub = mesh->createSubMesh(*name); - } else { - log.logMessage("Creating unnamed SubMesh"); - sub = mesh->createSubMesh(); - } - - Appearance *app = dynamic_cast(sh->appearance); - TextureCoordinate *tcs = dynamic_cast(ifs->texCoord); - Normal *norm = dynamic_cast(ifs->normal); - Color *color = dynamic_cast(ifs->color); - - String message = "Found: geometry"; - if (tcs) - message += ", texcoords"; - if (norm) - message += ", normals"; - if (color) - message += ", colours"; - log.logMessage(message); - - if (!tcs && !norm && !color) - log.logWarning("OGRE will refuse to render SubMeshes that have neither\n" - "\ttexture coordinates, normals or vertex colours."); - - if (!norm) { - log.logWarning("No normals found.\n" - "\tVRML dictates that normals should be generated, but this program\n" - "\tdoes not do so. If you want the resulting mesh to contain normals,\n" - "\tmake sure they are exported."); - } - - // process material - static std::map matMap; - - Ogre::MaterialPtr material = matMap[app]; - if (material && app) { - log.logMessage("Using material " + material->getName()); - sub->setMaterialName(material->getName()); - } else { - String matName; - const String *mn; - if ((mn = findName(app))) - matName = *mn; - else if (app && (mn = findName(app->material))) { - static std::map postfix; - std::stringstream ss; - int &num = postfix[*mn]; - ss << *mn << '/' << num++; - matName = ss.str(); - } else { - static int matNum; - std::stringstream ss; - ss << gBaseName << '/' << matNum++; - matName = ss.str(); - log.logMessage("No material name found, using " + matName); - } - log.logMessage("Reading material " + matName); - - material = parseMaterial(app, matName); - - sub->setMaterialName(matName); - } - - FaceVec faces; - parseFaces(faces, ifs); - - VertVec vertices; - TriVec triangles; - - AxisAlignedBox bbox = mesh->getBounds(); - for(auto & i : coord->point) { - bbox.merge(vec(i)); - } - mesh->_setBounds(bbox); - log.logMessage("Processing geometry..."); - triangulateAndExpand(triangles, vertices, faces, sh); - - copyToSubMesh(sub, triangles, vertices, sh, mat); - - log.logMessage("Done with this SubMesh."); -} -catch (const char *e) { - LogManager::getSingleton().logMessage(e); -} -} - -void copyToSubMesh(SubMesh *sub, const TriVec &triangles, const VertVec &vertices, - const Shape *sh, const Matrix4 &mat) -{ - IndexedFaceSet *ifs = dynamic_cast(sh->geometry); - Coordinate *coord = dynamic_cast(ifs->coord); - TextureCoordinate *tcs = dynamic_cast(ifs->texCoord); - Normal *norm = dynamic_cast(ifs->normal); - Color *color = dynamic_cast(ifs->color); - - int nvertices = vertices.size(); - int nfaces = triangles.size(); - - sub->vertexData = new VertexData(); - VertexDeclaration* decl = sub->vertexData->vertexDeclaration; - sub->useSharedVertices = false; - - size_t offset = 0; - decl->addElement(0, offset, VET_FLOAT3, VES_POSITION); - offset += VertexElement::getTypeSize(VET_FLOAT3); - if(norm) { - decl->addElement(0, offset, VET_FLOAT3, VES_NORMAL); - offset += VertexElement::getTypeSize(VET_FLOAT3); - } - if(tcs) { - decl->addElement(0, offset, VET_FLOAT2, VES_TEXTURE_COORDINATES); - offset += VertexElement::getTypeSize(VET_FLOAT2); - } - - HardwareVertexBufferSharedPtr vbuf = - HardwareBufferManager::getSingleton().createVertexBuffer( - offset, nvertices, HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - ABGR* colors = NULL; - HardwareVertexBufferSharedPtr cbuf; - if(color) { - cbuf = HardwareBufferManager::getSingleton().createVertexBuffer(VertexElement::getTypeSize(VET_COLOUR), - nvertices, HardwareBuffer::HBU_STATIC_WRITE_ONLY); - colors = (ABGR*)cbuf->lock(HardwareBuffer::HBL_DISCARD); - - decl->addElement(1, 0, VET_COLOUR, VES_DIFFUSE); - } - - HardwareIndexBufferSharedPtr ibuf = HardwareBufferManager::getSingleton(). - createIndexBuffer( - HardwareIndexBuffer::IT_16BIT, - nfaces*3, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - uint16* faces = (uint16*)ibuf->lock(HardwareBuffer::HBL_DISCARD); - // populate face list - for (int i=0; i!=nfaces; ++i) { - unsigned short *f = &faces[i*3]; - f[0] = triangles[i].vertices[0]; - f[1] = triangles[i].vertices[1]; - f[2] = triangles[i].vertices[2]; - } - ibuf->unlock(); - - sub->indexData->indexBuffer = ibuf; - sub->indexData->indexStart = 0; - sub->indexData->indexCount = nfaces*3; - - Matrix3 normMat = mat.linear().inverse().transpose(); - - uchar* vattrs = (uchar*)vbuf->lock(HardwareBuffer::HBL_DISCARD); - // populate vertex arrays - for (int i=0; i!=nvertices; ++i) { - const vertex &v = vertices[i]; - - Real *pos = (Real*)&vattrs[i*offset]; - Real *n = pos + 3; - Real *tc = n + 3; - - copyVec(pos, mat * vec(coord->point[v.pos])); - if (norm) { - Vector3 t = normMat * vec(norm->vector[v.normal]); - t.normalise(); - copyVec(n, t); - } - if (tcs) - copyVec(tc, tcs->point[v.tc]); - - if (color) { - col3 c = color->color[v.colour]; - ColourValue cv(c.r, c.g, c.b); - colors[i] = cv.getAsABGR(); - } - } - - if(color) - cbuf->unlock(); - - vbuf->unlock(); -} - -void triangulateAndExpand(TriVec &triangles, VertVec &vertices, const FaceVec &faces, const Shape *sh) -{ - IndexedFaceSet *ifs = dynamic_cast(sh->geometry); - TextureCoordinate *tcs = dynamic_cast(ifs->texCoord); - Normal *norm = dynamic_cast(ifs->normal); - Color *color = dynamic_cast(ifs->color); - - VertMap vertexMap; - - // triangulate and expand vertices - for (FaceVec::const_iterator f=faces.begin(), e=faces.end(); f!=e; ++f) { - int faceNr = f - faces.begin(); - int triVerts[2] = { -1, -1 }; - for (IntVec::const_iterator i = f->indices.begin(), ei=f->indices.end(); i!=ei; ++i) { - int triVertNr = i - f->indices.begin(); - int index = *i; - - vertex vert; - - // get full indices for vertex data - vert.pos = ifs->coordIndex[index]; - vert.normal = norm ? getIndex(ifs->coordIndex, ifs->normalIndex, - ifs->normalPerVertex, faceNr, index) : 0; - vert.colour = color ? getIndex(ifs->coordIndex, ifs->colorIndex, - ifs->colorPerVertex, faceNr, index) : 0; - vert.tc = tcs ? getIndex(ifs->coordIndex, ifs->texCoordIndex, - true, faceNr, index) : 0; - - // avoid duplication - size_t nvert = vertexMap.size(); - int &vpos = vertexMap[vert]; - if (nvert != vertexMap.size()) { - vpos = vertices.size(); - vertices.push_back(vert); - } - - // emit triangle (maybe) - if (triVertNr == 0) - triVerts[0] = vpos; - else if (triVertNr == 1) - triVerts[1] = vpos; - else { - triangle t; - t.vertices[0] = triVerts[0]; - t.vertices[1] = triVerts[1]; - t.vertices[2] = vpos; - - if (!ifs->ccw) - std::swap(t.vertices[1], t.vertices[2]); - - triangles.push_back(t); - - triVerts[1] = vpos; - } - } - } -} - -int getIndex(const IntVec &coordIndex, const IntVec &vec, bool perVertex, int facenr, int index) -{ - if (!perVertex) { - if (!vec.empty()) - return vec[facenr]; - else - return facenr; - } else { - if (!vec.empty()) - return vec[index]; - else - return coordIndex[index]; - } -} - -const String *findName(const vrmllib::node *n) -{ - NameMap::const_iterator i = gNameMap.find(n); - if (i == gNameMap.end()) - return 0; - else - return &i->second; -} - -const String *findNameRecursive(const vrmllib::node *n) -{ - if (const String *name = findName(n)) - return name; - else if (n->parent) - return findNameRecursive(n->parent); - else - return 0; -} - -void parseFaces(FaceVec &faces, const IndexedFaceSet *ifs) -{ - face f; - for (IntVec::const_iterator i=ifs->coordIndex.begin(), e=ifs->coordIndex.end(); i!=e; ++i) { - if (*i == -1) { - faces.resize(faces.size()+1); - faces.back().indices.swap(f.indices); - } else - f.indices.push_back(i - ifs->coordIndex.begin()); - } - if (!f.indices.empty()) { - faces.resize(faces.size()+1); - faces.back().indices.swap(f.indices); - } -} - -Ogre::MaterialPtr parseMaterial(const Appearance *app, const String &name) -{ - vrmllib::Material *vm = app ? dynamic_cast(app->material) : 0; - vrmllib::ImageTexture *texture = app ? dynamic_cast(app->texture) : 0; - - MaterialPtr m = MaterialManager::getSingleton().getByName(name, - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - if(m.get()) { - return m; - } - - m = MaterialManager::getSingleton().create(name, - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - ColourValue diffuse = texture ? ColourValue::White : col(vm->diffuseColor); - // diffuse colour is unused by VRML when a texture is avaliable, - // set to white to give the same effect in OGRE - - ColourValue a = diffuse; - a.r *= vm->ambientIntensity; - a.g *= vm->ambientIntensity; - a.b *= vm->ambientIntensity; - - Pass* p = m->createTechnique()->createPass(); - - p->setAmbient(a); - p->setDiffuse(diffuse); - p->setSelfIllumination(col(vm->emissiveColor)); - p->setShininess(vm->shininess); - p->setSpecular(col(vm->specularColor)); - - p->setLightingEnabled(app); - - if (texture && !texture->url.empty()) { - String texName = texture->url.front(); - size_t pos = texName.find_last_of("/\\"); - if (pos != texName.npos) { - LogManager::getSingleton().logMessage("Stripping path from texture " + texName); - texName.erase(0, pos+1); - } - - LogManager::getSingleton().logMessage("Adding texture layer for " + texName); - - Ogre::TextureUnitState *l = p->createTextureUnitState(texName); - l->setTextureAddressingMode(texture->repeatS ? - Ogre::TextureUnitState::TAM_WRAP : Ogre::TextureUnitState::TAM_CLAMP); - } - - return m; -} - -Matrix4 transMat(vrmllib::vec3 v, bool inverse) -{ - if (inverse) - return Affine3::getTrans(-v.x, -v.y, -v.z); - else - return Affine3::getTrans(v.x, v.y, v.z); -} - -Matrix4 scaleMat(vrmllib::vec3 v, bool inverse) -{ - if (inverse) - return Affine3::getScale(1/v.x, 1/v.y, 1/v.z); - else - return Affine3::getScale(v.x, v.y, v.z); -} - -Matrix4 rotMat(vrmllib::rot r, bool inverse) -{ - Matrix3 rot3; - rot3.FromAngleAxis(vec(r.vector), Radian(inverse ? -r.radians : r.radians)); - Matrix4 rot = Matrix4::IDENTITY; - rot = rot3; - return rot; -} diff --git a/Tools/VRMLConverter/vrmllib/include/vrmllib/file.h b/Tools/VRMLConverter/vrmllib/include/vrmllib/file.h deleted file mode 100644 index 8f8084971e8..00000000000 --- a/Tools/VRMLConverter/vrmllib/include/vrmllib/file.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef VRMLLIB_FILE_H -#define VRMLLIB_FILE_H - -#include -#include -#include - -#include - -namespace vrmllib { - -/// the contents of a VRML97 stream -/** contains all nodes that could be found in the stream - * passed to the constructor. - * the file owns the nodes and will delete them when when it is - * destroyed. */ -class file { -public: - explicit file(std::istream &); - ~file(); - - typedef std::map defs_t; - typedef std::vector nodes_t; - typedef std::vector roots_t; - - defs_t defs; - nodes_t nodes; - roots_t roots; -}; - -} // namespace vrmllib - -#endif diff --git a/Tools/VRMLConverter/vrmllib/include/vrmllib/fwd.h b/Tools/VRMLConverter/vrmllib/include/vrmllib/fwd.h deleted file mode 100644 index 9987bc0d5c5..00000000000 --- a/Tools/VRMLConverter/vrmllib/include/vrmllib/fwd.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef VRMLLIB_FWD_H -#define VRMLLIB_FWD_H - -namespace vrmllib { - -class file; -class node; -class grouping_node; - -class Transform; -class Shape; -class Appearance; -class WorldInfo; -class Viewpoint; -class Material; -class IndexedFaceSet; -class Coordinate; -class TextureCoordinate; -class Normal; -class Color; -class ImageTexture; - -} // namespace vrmllib - -#endif diff --git a/Tools/VRMLConverter/vrmllib/include/vrmllib/node.h b/Tools/VRMLConverter/vrmllib/include/vrmllib/node.h deleted file mode 100644 index cd6fd0c6b87..00000000000 --- a/Tools/VRMLConverter/vrmllib/include/vrmllib/node.h +++ /dev/null @@ -1,36 +0,0 @@ -#ifndef VRMLLIB_NODE_H -#define VRMLLIB_NODE_H - -#include -#include - -#include - -namespace vrmllib { - -class file; -class node; -class grouping_node; - -namespace bits { - void parse_value(node *&, std::istream &, file &); -} // namespace bits - -class node { - friend class file; - static node *parse_node(std::istream &, file &, const std::string &type); - static node *parse_node_xdef(std::istream &, file &, const std::string &firstWord); - static node *create_node(const std::string &type); -protected: - virtual void parse_attribute(const std::string &name, std::istream &, - file &); - friend void bits::parse_value(node *&, std::istream &, file &); -public: - virtual ~node() = 0; - - grouping_node *parent; -}; - -} // namespace vrmllib - -#endif diff --git a/Tools/VRMLConverter/vrmllib/include/vrmllib/nodes.h b/Tools/VRMLConverter/vrmllib/include/vrmllib/nodes.h deleted file mode 100644 index 1935a514544..00000000000 --- a/Tools/VRMLConverter/vrmllib/include/vrmllib/nodes.h +++ /dev/null @@ -1,164 +0,0 @@ -#ifndef VRMLLIB_NODES_H -#define VRMLLIB_NODES_H - -#include - -#include - -namespace vrmllib { - -#define VRMLLIB_NODE_CLASS2(name, base) \ - public: \ - name(); \ - VRMLLIB_NODE_CLASS2_ND(name, base) - -#define VRMLLIB_NODE_CLASS2_ND(name, base) \ - protected: \ - void parse_attribute(const std::string &, std::istream &, file &) override;\ - private: \ - typedef base base_type; - -#define VRMLLIB_NODE_CLASS(name) \ - VRMLLIB_NODE_CLASS2(name, node) - -#define VRMLLIB_NODE_CLASS_ND(name) \ - VRMLLIB_NODE_CLASS2_ND(name, node) - -class grouping_node : public node { - VRMLLIB_NODE_CLASS_ND(grouping_node) -public: - std::vector children; -}; - -class Transform : public grouping_node { - VRMLLIB_NODE_CLASS2(Transform, grouping_node) -public: - vec3 translation, center, scale; - rot rotation, scaleOrientation; -}; - -class Group : public grouping_node { - VRMLLIB_NODE_CLASS2_ND(Group, grouping_node) -public: -}; - -class Switch : public node { - VRMLLIB_NODE_CLASS(Switch) -public: - std::vector choice; - int whichChoice; -}; - -class Shape : public node { - VRMLLIB_NODE_CLASS(Shape) -public: - node *appearance; - node *geometry; -}; - -class Appearance : public node { - VRMLLIB_NODE_CLASS(Appearance) -public: - node *material; - node *texture; -}; - -class WorldInfo : public node { - VRMLLIB_NODE_CLASS_ND(WorldInfo) -public: - std::string title; - std::vector info; -}; - -class Viewpoint : public node { - VRMLLIB_NODE_CLASS(Viewpoint) -public: - float fieldOfView; - rot orientation; - vec3 position; - std::string description; -}; - -class Material : public node { - VRMLLIB_NODE_CLASS(Material) -public: - col3 diffuseColor; - col3 specularColor; - col3 emissiveColor; - float ambientIntensity; - float shininess; - float transparency; -}; - -class IndexedFaceSet : public node { - VRMLLIB_NODE_CLASS(IndexedFaceSet) -public: - bool solid; - bool convex; - bool ccw; - bool normalPerVertex; - bool colorPerVertex; - node *coord; - node *normal; - node *texCoord; - node *color; - std::vector coordIndex; - std::vector texCoordIndex; - std::vector normalIndex; - std::vector colorIndex; - -public: - // extract the geometry - void geometry(std::vector &triangles, - std::vector &geometry, - std::vector &normals, - std::vector &texcoords, - std::vector &colors) const; -}; - -class Coordinate : public node { - VRMLLIB_NODE_CLASS_ND(Coordinate) -public: - std::vector point; -}; - -class TextureCoordinate : public node { - VRMLLIB_NODE_CLASS_ND(TextureCoordinate) -public: - std::vector point; -}; - -class Normal : public node { - VRMLLIB_NODE_CLASS_ND(Normal) -public: - std::vector vector; -}; - -class Color : public node { - VRMLLIB_NODE_CLASS_ND(Color) -public: - std::vector color; -}; - -class Box : public node { - VRMLLIB_NODE_CLASS_ND(Box) -public: - vec3 size; -}; - -class Sphere : public node { - VRMLLIB_NODE_CLASS_ND(Sphere) -public: - float radius; -}; - -class ImageTexture : public node { - VRMLLIB_NODE_CLASS(ImageTexture) -public: - std::vector url; - bool repeatS, repeatT; -}; - -} // namespace vrmllib - -#endif diff --git a/Tools/VRMLConverter/vrmllib/include/vrmllib/types.h b/Tools/VRMLConverter/vrmllib/include/vrmllib/types.h deleted file mode 100644 index f2e7948c414..00000000000 --- a/Tools/VRMLConverter/vrmllib/include/vrmllib/types.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef VRMLLIB_TYPES_H -#define VRMLLIB_TYPES_H - -#include - -namespace vrmllib { - -struct vec2 { - float x, y; -}; - -struct vec3 { - float x, y, z; - vec3() {} - vec3(float x_, float y_, float z_) : x(x_), y(y_), z(z_) {} -}; - -struct col3 { - float r, g, b; - col3() {} - col3(float r_, float g_, float b_) : r(r_), g(g_), b(b_) {} -}; - -class rot { -public: - rot() : vector(0,0,1), radians(0) {} - rot(float x, float y, float z, float r) : vector(x,y,z), radians(r) {} - - vec3 vector; - float radians; -}; - -} // namespace vrmllib - -#endif diff --git a/Tools/VRMLConverter/vrmllib/include/vrmllib/types_bits.h b/Tools/VRMLConverter/vrmllib/include/vrmllib/types_bits.h deleted file mode 100644 index 91bdb8d5a50..00000000000 --- a/Tools/VRMLConverter/vrmllib/include/vrmllib/types_bits.h +++ /dev/null @@ -1,57 +0,0 @@ -#ifndef VRMLLIB_TYPES_BITS_H -#define VRMLLIB_TYPES_BITS_H - -#include -#include - -#include - -namespace vrmllib { - -class file; - -namespace bits { - -void parse_value(bool &, std::istream &, file &); -void parse_value(col3 &, std::istream &, file &); -void parse_value(vec2 &, std::istream &, file &); -void parse_value(vec3 &, std::istream &, file &); -void parse_value(std::string &, std::istream &, file &); -void parse_value(rot &, std::istream &, file &); - -template void parse_value(T &v, std::istream &s, file &) - { s >> v; } - -template void parse_vector(std::vector &l, std::istream &s, - file &data) -{ - char c; - s >> c; - if (c == '[') { - l.clear(); - T t; - while (s >> c) { - if (c == ']') - break; - else - s.putback(c); - - parse_value(t, s, data); - - l.push_back(t); - s >> c; - if (c != ',') - s.putback(c); - } - } else { - l.clear(); - l.push_back(T()); - s.putback(c); - parse_value(l.back(), s, data); - } -} - -} // namespace bits -} // namespace vrmllib - -#endif diff --git a/Tools/VRMLConverter/vrmllib/src/commentstream.cpp b/Tools/VRMLConverter/vrmllib/src/commentstream.cpp deleted file mode 100644 index 001d38a4f99..00000000000 --- a/Tools/VRMLConverter/vrmllib/src/commentstream.cpp +++ /dev/null @@ -1,56 +0,0 @@ -#include "commentstream.h" -#include - -namespace utillib { - -class commentstreambuf : public std::streambuf { - std::streambuf * const m_sbuf; - char m_buf[512]; - const int m_start; - const int m_end; - bool m_comment; -public: - commentstreambuf(std::streambuf *, char start_sb, char end_sb); - - int underflow() override; -}; - -commentstreambuf::commentstreambuf(std::streambuf *sb, char start_sb, char end_sb) - : m_sbuf(sb), m_start(static_cast(start_sb)), - m_end(static_cast(end_sb)), m_comment(false) -{ - setg(m_buf, m_buf, m_buf); -} - -int commentstreambuf::underflow() -{ - char *p = m_buf; - int ch; - while (p != m_buf + sizeof m_buf && (ch = m_sbuf->sgetc()) != EOF) { - m_sbuf->sbumpc(); - - if (ch == m_start) m_comment = true; - else if (ch == m_end) m_comment = false; - - if (!m_comment) - *p++ = ch; - } - - if (p == m_buf) - return EOF; - - setg(m_buf, m_buf, p); - return *m_buf; -} - -commentstream::commentstream(std::istream &s, char start_sb, char end_sb) - : std::istream(new commentstreambuf(s.rdbuf(), start_sb, end_sb)) -{ -} - -commentstream::~commentstream() -{ - delete rdbuf(); -} - -} // namespace utillib diff --git a/Tools/VRMLConverter/vrmllib/src/commentstream.h b/Tools/VRMLConverter/vrmllib/src/commentstream.h deleted file mode 100644 index 189496d1d51..00000000000 --- a/Tools/VRMLConverter/vrmllib/src/commentstream.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef UTILLIB_COMMENTSTREAM_H -#define UTILLIB_COMMENTSTREAM_H - -#include - -namespace utillib { - -/// strips comments from another stream -/** \bug does not provide a putback area. is that required by the standard? - * \todo should be expanded to handle comment markers with more than one - * character. */ -class commentstream : public std::istream { -public: - explicit commentstream(std::istream &, char start = '#', - char end = '\n'); - ~commentstream(); -}; - -} // namespace utillib - -#endif diff --git a/Tools/VRMLConverter/vrmllib/src/file.cpp b/Tools/VRMLConverter/vrmllib/src/file.cpp deleted file mode 100644 index f5aa8a86cb7..00000000000 --- a/Tools/VRMLConverter/vrmllib/src/file.cpp +++ /dev/null @@ -1,85 +0,0 @@ -#include - -#include -#include -#include - -#include -#include "commentstream.h" - -namespace vrmllib { -namespace { - -void set_parent(std::vector &c, grouping_node *p) -{ - for (auto & i : c) { - if (!i) - continue; - i->parent = p; - if (grouping_node *n = dynamic_cast(i)) - set_parent(n->children, n); - } -} - -} // anonymous namespace - -file::file(std::istream &sarg) -{ - utillib::commentstream s(sarg, '#', '\n'); - std::ios::iostate exceptions = sarg.exceptions(); - sarg.exceptions(std::ios::goodbit); - - try { - for (;;) { - char t; - s >> t; - if (s) - s.putback(t); - else if (s.eof()) - break; - else - throw std::runtime_error( - "parse error: unexpected end of file"); - - s.exceptions(std::ios::badbit - | std::ios::failbit - | std::ios::eofbit); - - std::string word; - s >> word; - - if (word == "ROUTE") { - s >> word; - s >> word; // TO - s >> word; - } else { - node *n = node::parse_node_xdef(s, *this, word); - if (n) - roots.push_back(n); - } - - s.exceptions(std::ios::goodbit); - } - - } catch (std::ios::failure &e) { - sarg.exceptions(exceptions); - throw std::runtime_error(std::string("parse error: stream failure: ") + e.what()); - } catch (...) { - sarg.exceptions(exceptions); - throw; - } - sarg.exceptions(exceptions); - - set_parent(roots, 0); -} - -namespace { - inline void delnode(node *n) { delete n; } -} - -file::~file() -{ - std::for_each(nodes.begin(), nodes.end(), delnode); -} - -} // namespace vrmllib diff --git a/Tools/VRMLConverter/vrmllib/src/indexed_face_set.cpp b/Tools/VRMLConverter/vrmllib/src/indexed_face_set.cpp deleted file mode 100644 index 67ca6444dc6..00000000000 --- a/Tools/VRMLConverter/vrmllib/src/indexed_face_set.cpp +++ /dev/null @@ -1,158 +0,0 @@ -#include - -#include -#include - -namespace vrmllib { -namespace bits { - -struct index_set { - index_set() : geom(0), tex(0), norm(0), col(0) {} - int geom; - int tex; - int norm; - int col; -}; - -static bool operator<(const index_set &a, const index_set &b) -{ - if (a.geom < b.geom) return true; - if (a.geom > b.geom) return false; - if (a.tex < b.tex) return true; - if (a.tex > b.tex) return false; - if (a.norm < b.norm) return true; - if (a.norm > b.norm) return false; - return a.col < b.col; -} - -} // namespace bits - -using namespace bits; - -using std::vector; -using std::map; -using std::runtime_error; - -void IndexedFaceSet::geometry(vector &triangles, - vector &_geometry, vector &_normals, - vector &_texcoords, vector &_colors) const -{ - std::map index_map; - vector final_indices; - - Coordinate *_coord = dynamic_cast(coord); - if (!_coord) throw runtime_error("no coordinates for indexed face set"); - - TextureCoordinate *_texCoord = - dynamic_cast(texCoord); - Normal *_normal = dynamic_cast(normal); - Color *_color = dynamic_cast(color); - - int colcase = 0; - if (_color) { - colcase += colorIndex.empty() ? 2 : 1; - colcase += colorPerVertex ? 2 : 0; - } - int normcase = 0; - if (_normal) { - normcase += normalIndex.empty() ? 2 : 1; - normcase += normalPerVertex ? 2 : 0; - } - - // map vrml index tuples to vertices and output indices - triangles.clear(); - int facenum = 0, num_in_face = 0; - for (unsigned i=0; i!=coordIndex.size(); ++i) { - if (coordIndex[i] == -1) { - if (num_in_face != 3) - throw runtime_error( - "polygon is not a triangle"); - num_in_face = 0; - ++facenum; - continue; - } else - ++num_in_face; - - index_set is; - is.geom = coordIndex[i]; - if (_texCoord) { - if (!texCoordIndex.empty()) - is.tex = texCoordIndex[i]; - else - is.tex = coordIndex[i]; - } - switch (colcase) { - case 1: // !perVertex, !colorIndex.empty - is.col = colorIndex[facenum]; - break; - case 2: // !perVertex, colorIndex.empty - is.col = facenum; - break; - case 3: // perVertex, !colorIndex.empty - is.col = colorIndex[i]; - break; - case 4: // perVertex, colorIndex.empty - is.col = coordIndex[i]; - break; - }; - switch (normcase) { - case 1: // !perVertex, !normalIndex.empty - is.norm = normalIndex[facenum]; - break; - case 2: // !perVertex, normalIndex.empty - is.norm = facenum; - break; - case 3: // perVertex, !normalIndex.empty - is.norm = normalIndex[i]; - break; - case 4: // perVertex, normalIndex.empty - is.norm = coordIndex[i]; - break; - }; - - if (final_indices.empty()) { - index_map[is] = 0; - final_indices.push_back(is); - triangles.push_back(0); - } else { - map::iterator it - = index_map.find(is); - if (it == index_map.end()) { - index_map[is] = final_indices.size(); - triangles.push_back(final_indices.size()); - final_indices.push_back(is); - } else - triangles.push_back(it->second); - } - } - - // generate attributes - _geometry.resize(final_indices.size()); - for (unsigned i=0; i!=final_indices.size(); ++i) - _geometry[i] = _coord->point[final_indices[i].geom]; - if (_normal) { - _normals.resize(final_indices.size()); - for (unsigned i=0; i!=final_indices.size(); ++i) - _normals[i] = _normal->vector[final_indices[i].norm]; - } else - _normals.clear(); - if (_texCoord) { - _texcoords.resize(final_indices.size()); - for (unsigned i=0; i!=final_indices.size(); ++i) - _texcoords[i] = _texCoord->point[final_indices[i].tex]; - } else - _texcoords.clear(); - if (_color) { - _colors.resize(final_indices.size()); - for (unsigned i=0; i!=final_indices.size(); ++i) - _colors[i] = _color->color[final_indices[i].col]; - } else - _colors.clear(); - - // convert to ccw - if (!ccw) - for (unsigned i=0; i!=triangles.size(); i+=3) - std::swap(triangles[i+1], triangles[i+2]); -} - -} // namespace vrmllib diff --git a/Tools/VRMLConverter/vrmllib/src/node.cpp b/Tools/VRMLConverter/vrmllib/src/node.cpp deleted file mode 100644 index c768bd77b0c..00000000000 --- a/Tools/VRMLConverter/vrmllib/src/node.cpp +++ /dev/null @@ -1,125 +0,0 @@ -#include - -#include -#include - -#include - -namespace vrmllib { -namespace bits { - -void parse_value(node *&n, std::istream &s, file &data) -{ - std::string word; - s >> word; - if (!s) - throw std::runtime_error("parse error: end of file wile reading node"); - n = node::parse_node_xdef(s, data, word); -} - -} // namespace bits - -node::~node() -{ -} - -void node::parse_attribute(const std::string &name, std::istream &s, file &data) -{ - std::cerr << "unknown attribute: " << name << std::endl; - std::string val; - s >> val; - if (!s) - throw std::runtime_error("parse error: end of file while reading unknown attribute"); - if (val == "[") { - char c = 0; - int depth = 1; - s >> c; - while (depth != 0) { - if (!(s >> c)) - throw std::runtime_error("parse error: end of file while scanning for end of unknown attribute"); - if (c == '[') - ++depth; - else if (c == ']') - --depth; - } - } else if (val == "TRUE" || val == "FALSE" || val[0] == '-' || isdigit(val[0])) { - char c; - while (s.get(c) && c != '\n' && c != '\r') - ; - if (!s) - throw std::runtime_error("parse error: end of file while scanning for end of line"); - } else { - parse_node_xdef(s, data, val); - } -} - -node *node::parse_node(std::istream &s, file &data, - const std::string &type) -{ - node *n = create_node(type); - if (!n) { - char c = 0; - int depth = 1; - s >> c; - if (c != '{') - throw std::runtime_error( - std::string("parse error: expected {, got: ") + c); - while (depth != 0) { - if (!(s >> c)) - throw std::runtime_error("parse error: end of file while scanning for end of unknown node"); - if (c == '{') - ++depth; - else if (c == '}') - --depth; - } - return 0; - } - data.nodes.push_back(n); - - char c; - s >> c; - if (c != '{') - throw std::runtime_error( - std::string("parse error: expected {, got: ") + c); - - std::string str; - for (;;) { - s >> c; - if (c == '}') - break; - else - s.putback(c); - - s >> str; - n->parse_attribute(str, s, data); - } - - return n; -} - -node *node::parse_node_xdef(std::istream &s, file &data, const std::string &fword) -{ - if (fword == "DEF") { - std::string word; - s >> word; - std::string name = word; - s >> word; - node *n = parse_node(s, data, word); - node *&dest = data.defs[name]; - if (dest) - throw std::runtime_error( - "parse error: node already defined: " + name); - return dest = n; - } else if (fword == "USE") { - std::string word; - s >> word; - if (node *n = data.defs[word]) - return n; - else - throw std::runtime_error( - "parse error: node is not defined: " + word); - } else - return parse_node(s, data, fword); -} - -} // namespace vrmllib diff --git a/Tools/VRMLConverter/vrmllib/src/nodes.cpp b/Tools/VRMLConverter/vrmllib/src/nodes.cpp deleted file mode 100644 index 13b60c7ec40..00000000000 --- a/Tools/VRMLConverter/vrmllib/src/nodes.cpp +++ /dev/null @@ -1,208 +0,0 @@ -#include - -#include -#include - -#include - -#define BEGIN_NODE(type) \ - namespace {\ - node_creator register_##type##_creator(#type); \ - } \ - void type::parse_attribute(const std::string &a_name, \ - std::istream &a_stream, file &a_data) \ - { - -#define ATTR(d_var) \ - if (a_name == #d_var) { \ - using namespace bits; \ - return parse_value(d_var, a_stream, a_data); \ - } -#define VATTR(d_var) \ - if (a_name == #d_var) { \ - using namespace bits; \ - return parse_vector(d_var, a_stream, a_data); \ - } -#define END_NODE \ - base_type::parse_attribute(a_name, a_stream, a_data); \ - } - -#define BEGIN_DEFAULTS(type) \ - type::type() : -#define END_DEFAULTS \ - {} - -namespace vrmllib { -namespace bits { - -class node_creator_base { -public: - virtual ~node_creator_base() {} - virtual node *create() = 0; -}; - -std::map g_node_creators; - -template -class node_creator : public node_creator_base { -public: - node_creator(const char *type) { g_node_creators[type] = this; } - node *create() override { return new Type; } -}; - -} // namespace bits - -using namespace bits; - -node *node::create_node(const std::string &type) -{ - node_creator_base *c = g_node_creators[type]; - - if (c) - return c->create(); - else { - std::cerr << "unknown type: " << type << std::endl; - return 0; - } -} - -BEGIN_NODE(grouping_node) - VATTR(children) -END_NODE - -BEGIN_DEFAULTS(Transform) - translation(0,0,0), - center(0,0,0), - scale(1,1,1) -END_DEFAULTS -BEGIN_NODE(Transform) - ATTR(translation) - ATTR(rotation) - ATTR(center) - ATTR(scale) - ATTR(scaleOrientation) -END_NODE - -BEGIN_NODE(Group) -END_NODE - -BEGIN_DEFAULTS(Shape) - appearance(0), - geometry(0) -END_DEFAULTS -BEGIN_NODE(Shape) - ATTR(appearance) - ATTR(geometry) -END_NODE - -BEGIN_DEFAULTS(Switch) - whichChoice(0) -END_DEFAULTS -BEGIN_NODE(Switch) - VATTR(choice) - ATTR(whichChoice) -END_NODE - -BEGIN_DEFAULTS(Viewpoint) - fieldOfView(0.785398), - position(0,0,10) -END_DEFAULTS -BEGIN_NODE(Viewpoint) - ATTR(fieldOfView) - ATTR(orientation) - ATTR(position) - ATTR(description) -END_NODE - -BEGIN_DEFAULTS(Appearance) - material(0), - texture(0) -END_DEFAULTS -BEGIN_NODE(Appearance) - ATTR(material) - ATTR(texture) -END_NODE - -BEGIN_NODE(WorldInfo) - ATTR(title) - VATTR(info) -END_NODE - -BEGIN_DEFAULTS(Material) - diffuseColor(204,204,204), - specularColor(0,0,0), - emissiveColor(0,0,0), - ambientIntensity(0.2), - shininess(0.2), - transparency(0) -END_DEFAULTS -BEGIN_NODE(Material) - ATTR(diffuseColor) - ATTR(specularColor) - ATTR(emissiveColor) - ATTR(ambientIntensity) - ATTR(shininess) - ATTR(transparency) -END_NODE - -BEGIN_DEFAULTS(IndexedFaceSet) - solid(true), - convex(true), - ccw(true), - normalPerVertex(true), - colorPerVertex(true), - coord(0), - normal(0), - texCoord(0), - color(0) -END_DEFAULTS -BEGIN_NODE(IndexedFaceSet) - ATTR(solid) - ATTR(convex) - ATTR(ccw) - ATTR(normalPerVertex) - ATTR(colorPerVertex) - ATTR(coord) - ATTR(color) - ATTR(normal) - ATTR(texCoord) - VATTR(coordIndex) - VATTR(texCoordIndex) - VATTR(normalIndex) - VATTR(colorIndex) -END_NODE - -BEGIN_NODE(Coordinate) - VATTR(point) -END_NODE - -BEGIN_NODE(Color) - VATTR(color) -END_NODE - -BEGIN_NODE(Box) - ATTR(size) -END_NODE - -BEGIN_NODE(Sphere) - ATTR(radius) -END_NODE - -BEGIN_NODE(TextureCoordinate) - VATTR(point) -END_NODE - -BEGIN_NODE(Normal) - VATTR(vector) -END_NODE - -BEGIN_DEFAULTS(ImageTexture) - repeatS(true), repeatT(true) -END_DEFAULTS -BEGIN_NODE(ImageTexture) - VATTR(url) - ATTR(repeatS) - ATTR(repeatT) -END_NODE - -} // namespace vrmllib diff --git a/Tools/VRMLConverter/vrmllib/src/types.cpp b/Tools/VRMLConverter/vrmllib/src/types.cpp deleted file mode 100644 index c2b828f7fd9..00000000000 --- a/Tools/VRMLConverter/vrmllib/src/types.cpp +++ /dev/null @@ -1,60 +0,0 @@ -#include - -#include - -namespace vrmllib { -namespace bits { - -void parse_value(bool &b, std::istream &s, file &) -{ - std::string t; - s >> t; - if (t == "TRUE") - b = true; - else if (t == "FALSE") - b = false; - else - throw std::runtime_error("parse error: expected TRUE or FALSE, got: " + t); -} - -void parse_value(std::string &str, std::istream &s, file &) -{ - char c = 0; - s >> c; - - if (c != '"') { - s.putback(c); - throw std::runtime_error(std::string("expected start of string (\"), got: ") + c); - } - str.erase(); - c = 0; - while (s.get(c) && c != '"') str += c; - - if (c != '"') { - throw std::runtime_error(std::string("expected end of string (\"), got: ") + c); - } -} - -void parse_value(vec3 &v, std::istream &s, file &) -{ - s >> v.x >> v.y >> v.z; -} - -void parse_value(col3 &v, std::istream &s, file &) -{ - s >> v.r >> v.g >> v.b; -} - -void parse_value(vec2 &v, std::istream &s, file &) -{ - s >> v.x >> v.y; -} - -void parse_value(rot &r, std::istream &s, file &f) -{ - parse_value(r.vector, s, f); - s >> r.radians; -} - -} // namespace bits -} // namespace vrmllib diff --git a/Tools/Wings3DExporter/Makefile b/Tools/Wings3DExporter/Makefile deleted file mode 100644 index 7a07b62ac5b..00000000000 --- a/Tools/Wings3DExporter/Makefile +++ /dev/null @@ -1,19 +0,0 @@ - -.PHONY: dist - -DIST_NAME = wings-ogre -VERSION = 0.93 -FULL_NAME = $(DIST_NAME)-$(VERSION) - -dist: - -mkdir $(FULL_NAME) - cp README.txt $(FULL_NAME)/ - cp xmlout.py $(FULL_NAME)/ - cp Makefile $(FULL_NAME)/ - cp erlang_ext.py $(FULL_NAME)/ - cp vector.py mesh.py pgon.py $(FULL_NAME)/ - cp io3d_wings.py io3d_ogre.py $(FULL_NAME)/ - cp w2o.py $(FULL_NAME)/ - tar -czf $(FULL_NAME).tar.gz $(FULL_NAME) - -rm -rf $(FULL_NAME) - diff --git a/Tools/Wings3DExporter/Readme.md b/Tools/Wings3DExporter/Readme.md deleted file mode 100644 index 09f05ee4749..00000000000 --- a/Tools/Wings3DExporter/Readme.md +++ /dev/null @@ -1,61 +0,0 @@ - -# Wings3D to OGRE converter README -This is wings-ogre, my Wings3D to OGRE converter written in Python. - -Please send feedback, suggestions and bug reports to: Attila Tajti - -I'm also used to be around #Ogre3D on irc.freenode.net. - -## FEATURES - -It's basically a couple of Python modules to load and process the -structured Erlang binary file produced by Wings and save it in Ogre XML. -It does the following: - - Loads the polygon data - - Handles UV coordinates, material diffuse/ambient/specular/shininess values - - Handle copying vertices at hard edges (like smoothing groups in Max) - - Triangulates polygons using the ear-clipping method - - Writes internal images in the .wings file into PNG format - - Uses an own primitiev XML module, so no libxml2 dependency - -## USAGE - -Copy the .wings file to the directory containing the python files. -Then execute `./w2o.py ` from the command line, eg: -``` - % tar -xzf wings-ogre-0.9.tar.gz - % cd wings-ogre-0.9 - % cp ~/models/test.wings - % ./w2o.py test.wings -``` - -This will result in a .mesh.xml file. It has to be converted to a .mesh via the the XML converter: -``` - % OgreXMLConverter test.mesh.xml -``` - -The w2o.py program will also export internal Wings textures, using the name of the material (not the name of the image) as filename. - -## REQUIREMENTS -(These should be available on a recent Linux system) - - Python 2.2 - - Python Imaging Library (for Image export) - -## TODO -Speed things up. The exporter is terribly slow. This is mainly because of the soft/hard edge detection stuff. - -## NOTES -The xmlout module may be used using Temas's Blender exporter to remove the libxml2 dependency. -Don't use xmlout for anything more serious, though. - -## ACKNOWLEDGEMENTS - -The work of these people were particularily helpful for me: - - Thomas 'temas' Muldowney - the OGRE Blender exporter - - Anthony D'Agostino - IO Suide for Blender - -LINKS - - http://ogre.sf.net - OGRE homepage - - http://www.wings3d.org - Wings 3D homepage - - http://www.python.org - Python homepage - - http://www.pythonware.com/products/pil/ - Python Imaging Library homepage diff --git a/Tools/Wings3DExporter/erlang_ext.py b/Tools/Wings3DExporter/erlang_ext.py deleted file mode 100644 index bf8425fbb8a..00000000000 --- a/Tools/Wings3DExporter/erlang_ext.py +++ /dev/null @@ -1,234 +0,0 @@ - -# Python module to read erlang ext (term) format -# -# written by Attila Tajti on 2003, for -# -# TODO: reads compressed data only - -import os, sys, struct, zlib, cStringIO - -class erlang_atom: - - def __init__(self, atom): - self.atom = atom - - def __str__(self): - return self.atom - - def __eq__(self, other): - return self.atom == other.atom - - def __ne__(self, other): - return self.atom != other.atom - - def __repr__(self): - return "atom <%s>" % self.atom - -class erlang_ext_reader: - - def __init__(self, filename): - file = open(filename, "rb") - header = file.read(15) - fsize, = struct.unpack(">L", file.read(4)) # file_size - 19 - misc, = struct.unpack(">H", file.read(2)) - dsize, = struct.unpack(">L", file.read(4)) # uncompressed data size - data = file.read(fsize-6) - file.close() - - data = zlib.decompress(data) - if dsize != len(data): print "ERROR: uncompressed size does not match." - self.data = cStringIO.StringIO(data) - - self.logstr = "" - self.depth = 0 - self.datalog = "" - self.logging = 0 - - def log_str(self, str): - pass - #self.logstr += str + "\n" - - def log_data(self, str): - self.datalog += " " * self.depth + str + "\n" - - def log_begin_block(self): - self.datalog += " " * self.depth + "{\n" - self.depth += 1 - - def log_end_block(self): - self.depth -= 1 - if self.depth < 0: raise "hell" - self.datalog += " " * self.depth + "}\n" - - def read_small_int(self): - val, = struct.unpack(">B", self.data.read(1)) - if self.logging: - self.log_str("small_int: %d" % (val)) - self.log_data(str(val)) - return val - - def read_int(self): - val, = struct.unpack(">l", self.data.read(4)) - if self.logging: - self.log_str("int: %d\n" % (val)) - self.log_data(str(val)) - return val - - def read_float(self): - buf = self.data.read(31) - chrs = filter(lambda char: ord(char) > 0, buf) - val = float(chrs) - if self.logging: - self.log_str("float: %f\n" % (val)) - self.log_data(str(val)) - return val - - def read_atom(self): - namelen, = struct.unpack(">H", self.data.read(2)) - name = self.data.read(namelen) - if self.logging: - self.log_str("atom: %d %s" % (namelen, name)) - self.log_data("ATOM %s" % name) - return erlang_atom(name) - - def read_tuple(self, len): - if self.logging: - self.log_data("TUPLE [%d]" % len) - self.log_begin_block() - val = [] - for i in range(len): - val.append(self.read_element()) - if self.logging: - self.log_end_block() - return tuple(val) - - def read_small_tuple(self): - len, = struct.unpack(">B", self.data.read(1)) - if self.logging: - self.log_str("small_tuple: %d" % (len)) - return self.read_tuple(len) - - def read_large_tuple(self): - len, = struct.unpack(">L", self.data.read(4)) - if self.logging: - self.log_str("large_tuple: %d" % (len)) - return self.read_tuple(len) - - def read_listx(self): - len, = struct.unpack(">L", self.data.read(4)) - if self.logging: - self.log_str("list: %d" % len) - self.log_data("LIST [%d]" % len) - self.log_begin_block() - val = [] - elem = 1 - while elem != None: - elem = self.read_element() - val.append(elem) - if self.logging: - self.log_end_block() - return val - - def read_list(self): - len, = struct.unpack(">L", self.data.read(4)) - if self.logging: - self.log_str("list: %d" % len) - self.log_data("LIST [%d]" % len) - self.log_begin_block() - val = [] - for i in range(len): - #if self.depth == 5: self.log_str(str(i)) - elem = self.read_element() - val.append(elem) - elem = self.read_element() - if elem != None: raise "hey!" - if self.logging: - self.log_end_block() - return val - - def read_string(self): - namelen, = struct.unpack(">H", self.data.read(2)) - name = self.data.read(namelen) - if self.logging: - self.log_str("string: %d %s" % (namelen, name)) - self.log_data('STRING %s' % repr(name)) - return name - - def read_binary(self): - len, = struct.unpack(">L", self.data.read(4)) - data = self.data.read(len) - if self.logging: - def hexchar(x): - return hex(ord(x))[2:] - repr = "".join(map(hexchar, data)) - self.log_str("binary: %d %s" % (len, repr)) - self.log_data('BINARY [%d] 0x%s' % (len, repr)) - return data - - def read_nil(self): - if self.logging: - self.log_data('NIL') - return None - - def read_element(self): - id, = struct.unpack(">B", self.data.read(1)) - - return self.read_element_using_id(id) - - def read_element_using_id(self, id): - #if self.depth == 5: self.log_str("read element %d" % id) - - if id == 97: - return self.read_small_int() - - elif id == 98: - return self.read_int() - - elif id == 99: - return self.read_float() - - elif id == 100: - return self.read_atom() - - elif id == 104: - return self.read_small_tuple() - - elif id == 105: - return self.read_large_tuple() - - elif id == 106: - return self.read_nil() - - elif id == 107: - return self.read_string() - - elif id == 108: - return self.read_list() - - elif id == 109: - return self.read_binary() - - else: - raise "problem " + str(id) - - def read(self): - return self.read_element() - - def readtest(self): - self.read_element() - - #run = 1 - #while run: - #run = self.read_element() - -def test(): - e = erlang_ext_reader("tank1w.wings") - try: - data = e.read_element() - finally: - f = open("log.txt", "w") - f.write(e.datalog) - f.write(e.logstr) - f.write(repr(data)) - -#test() diff --git a/Tools/Wings3DExporter/io3d_ogre.py b/Tools/Wings3DExporter/io3d_ogre.py deleted file mode 100644 index 26858de70ef..00000000000 --- a/Tools/Wings3DExporter/io3d_ogre.py +++ /dev/null @@ -1,133 +0,0 @@ - -# write a mesh in OGRE XML format - -import sys - -#import libxml2 as myxml -import xmlout as myxml - -import pprint - -def vector_to_xml(elem, vector, coord_names): - for i in range(len(coord_names)): - coord = "%.6f" % vector[i] - elem.setProp(coord_names[i], coord) - -class ogre_writer: - - def __init__(self): - - self.xmldoc = myxml.newDoc("1.0") - if not self.xmldoc: - raise IOError("Unable to create doc!!!") - - mesh_elem = myxml.newNode("mesh") - try: - mesh_elem.docSetRootElement(self.xmldoc) - except myxml.treeError: - pass - self.materials_elem = mesh_elem.newChild(None, "materials", None) - self.sharedgeometry_elem = mesh_elem.newChild(None, "sharedgeometry", None) - self.submeshes_elem = mesh_elem.newChild(None, "submeshes", None) - - def add(self, mesh): - if mesh.shared_geometry: - self.add_geometry(self.sharedgeometry_elem, mesh.glverts) - else: - self.sharedgeometry_elem.setProp("vertexcount", "0") - for submesh in mesh.subs: - self.add_material(submesh.mat_data) - self.add_submesh(submesh, mesh.shared_geometry) - - def add_material(self, mat): - material_elem = self.materials_elem.newChild(None, "material", None) - material_elem.setProp("name", mat.name) - - rgba = ["red", "green", "blue", "alpha"] - - ambient_elem = material_elem.newChild(None, "ambient", None) - vector_to_xml(ambient_elem, mat.ambient, rgba) - - diffuse_elem = material_elem.newChild(None, "diffuse", None) - vector_to_xml(diffuse_elem, mat.diffuse, rgba) - - specular_elem = material_elem.newChild(None, "specular", None) - vector_to_xml(specular_elem, mat.specular, rgba) - - shininess_elem = material_elem.newChild(None, "shininess", None) - shininess_elem.setProp("value", str(mat.shininess)) - - texs_elem = material_elem.newChild(None, "texturelayers", None) - for tex in mat.textures: - tex_elem = texs_elem.newChild(None, "texturelayer", None) - tex_elem.setProp("texture", str(tex)) - - def add_geometry(self, geometry_elem, vertices): - "add given vertices to an XML element" - - geometry_elem.setProp("vertexcount", str(len(vertices))) - - want_uvs = vertices[0].uv != None - vb_elem = geometry_elem.newChild(None, "vertexbuffer", None) - vb_elem.setProp("positions", "true") - vb_elem.setProp("normals", "true") - vb_elem.setProp("colours_diffuse", "false") - if want_uvs: - vb_elem.setProp("texture_coords", "1") - vb_elem.setProp("texture_coord_dimensions_0", "2") - else: - vb_elem.setProp("texture_coords", "0") - - try: - for vert in vertices: - vertex_elem = vb_elem.newChild(None, "vertex", None) - - position_elem = vertex_elem.newChild(None, "position", None) - vector_to_xml(position_elem, vert.pos, ["x", "y", "z"]) - - normal_elem = vertex_elem.newChild(None, "normal", None) - vector_to_xml(normal_elem, vert.normal, ["x", "y", "z"]) - - if want_uvs: - texcoord_elem = vertex_elem.newChild(None, "texcoord", None) - vector_to_xml(texcoord_elem, vert.uv, ["u", "v"]) - except: - pp = pprint.PrettyPrinter(indent=4,width=78) - pp.pprint(vertices) - - raise - - def add_faces(self, submesh_elem, faces): - faces_elem = submesh_elem.newChild(None, "faces", None) - faces_elem.setProp("count", str(len(faces))) - for face in faces: - face_elem = faces_elem.newChild(None, "face", None) - for index in range(3): - face_elem.setProp("v%d" % (index + 1), str(face[index])) - - def add_submesh(self, submesh, use_shared): - submesh_elem = self.submeshes_elem.newChild(None, "submesh", None) - submesh_elem.setProp("material", submesh.mat_data.name) - if use_shared: - submesh_elem.setProp("usesharedvertices", "true") - self.add_faces(submesh_elem, submesh.gltris) - else: - submesh_elem.setProp("usesharedvertices", "false") - self.add_faces(submesh_elem, submesh.gltris) - geometry_elem = submesh_elem.newChild(None, "geometry", None) - self.add_geometry(geometry_elem, submesh.glverts) - submesh_elem.setProp("use32bitindexes", "false") - submesh_elem.setProp("operationtype", str("triangle_list")) - - def write(self, filename): - self.xmldoc.saveFormatFile(filename, 1) - self.xmldoc.freeDoc() - -# Create our xml document -def write_ogre(mesh, filename): - ow = ogre_writer() - ow.add(mesh) - ow.write(filename) - - - diff --git a/Tools/Wings3DExporter/io3d_wings.py b/Tools/Wings3DExporter/io3d_wings.py deleted file mode 100644 index fb8be66e918..00000000000 --- a/Tools/Wings3DExporter/io3d_wings.py +++ /dev/null @@ -1,342 +0,0 @@ - -# -# TODO: -# parse vertex colors and UV coordinates -# remove faces with the hole material -# - -from erlang_ext import * -import types -import pprint - -import mesh - -try: - import Image -except: - pass - -def safe_append(ctr, key, value): - if ctr.has_key(key): - ctr[key].append(value) - else: - ctr[key] = [value] - -class wings_reader: - - dump = __name__ == '__main__' - - def __init__(self, raw_data, writeImages, keepRotation): - self.data = raw_data - self.writeImages = writeImages - self.keepRotation = keepRotation - # read and check - a, self.ver, wingsdata = self.data - if a != erlang_atom("wings") or self.ver != 2: - raise IOError("Unknown wings version") - - #if self.dump: - # pp = pprint.PrettyPrinter(indent=4,width=78) - # pp.pprint(wingsdata) - - self.raw_objects, self.raw_materials, self.raw_props = wingsdata - - def parse(self): - return self.parse_2() - - def parse_2(self): - scene = mesh.Mesh() - scene.name = "wings_object" - self.materials = scene.materials - self.mat_images = {} - for raw_mat in self.raw_materials: - wmat = self.parse_2_material(raw_mat) - scene.materials.append(wmat) - self.parse_2_images() - for raw_obj in self.raw_objects: - wobj = self.parse_2_object(raw_obj) - scene.merge(wobj) - self.postprocess(scene) - return scene - - def parse_2_image(self, index, raw_image): - w, h, spp = 0, 0, 0 - pixels = None - filename = None - for elem in raw_image: - if elem[0] == erlang_atom("width"): - w = elem[1] - if elem[0] == erlang_atom("height"): - h = elem[1] - if elem[0] == erlang_atom("samples_per_pixel"): - spp = elem[1] - if elem[0] == erlang_atom("pixels"): - pixels = elem[1] - - if not pixels: - return None - - if spp == 3: mode = 'RGB' - else: mode = 'L' - im = Image.new(mode, (w, h)) - - print "processing image" - print mode, spp, w, h, len(pixels) - - pixels = map(lambda x: ord(x), pixels) - for x in range(w): - for y in range(h): - i = (x + y * w) * 3 - yy = h - 1 - y # huh? - im.putpixel((x, yy), tuple(pixels[i:i+3])) - #bands = [tuple(pixels[i*3:i*3+3]) for i in range(w * h)] - - #print pixels - #print bands - - #im.putdata(bands) - - if self.mat_images.has_key(index): - filename = self.mat_images[index] - im.save(filename) - return im - - def parse_2_images(self): - if not self.writeImages: - return - images = [] - if self.raw_props: - for elem in self.raw_props: - if elem[0] == erlang_atom('images'): - images = elem[1] - - for raw_im_data in images: - index, raw_im = raw_im_data[:2] - self.parse_2_image(index, raw_im) - - def parse_2_material(self, raw_mat): - - atom, data = raw_mat - - #pp = pprint.PrettyPrinter(indent=4,width=78) - #pp.pprint(data) - - #raw_maps, raw_gl = data[:2] - - mat = mesh.Material(str(atom)) - - for tag in data: - a, elem_data = tag - if a == erlang_atom('openg'): - for elem in elem_data: - if elem[0] == erlang_atom('ambient'): - mat.ambient = elem[1] - if elem[0] == erlang_atom('diffuse'): - mat.diffuse = elem[1] - if elem[0] == erlang_atom('specular'): - mat.specular = elem[1] - if elem[0] == erlang_atom('shininess'): - mat.shininess = elem[1] - elif a == erlang_atom('maps') and elem_data: - filename = str(atom) + '.png' - mat.textures.append(filename) - self.mat_images[elem_data[0][1]] = filename - - return mat - - - def check_atom(self, atom, name): - if atom != erlang_atom(name): - raise IOError("Unexpected atom: %s expected, %s found" % - (erlang_atom(name), atom)) - - def parse_2_edges(self, wobj, raw_edges, hard_edges): - faces = {} - for edge_index in range(len(raw_edges)): - raw_edge = raw_edges[edge_index] - LSp, LEp = None, None - for elem in raw_edge: - - if elem[0] == erlang_atom('edge'): - edgedata = elem - - # - # the color data for the face on the sides of this - # edge, rgb1/uv1 is for Lf:Sv, rgb2/uv2 is for Rf:Ev - # - if elem[0] == erlang_atom('uv'): - uvdata = struct.unpack('>dddd', elem[1]) - u1, v1, u2, v2 = uvdata - LSp = mesh.ColorProp((u1, v1)) - LEp = mesh.ColorProp((u2, v2)) - - # new UV packing for Wings3D 0.98.16b? - # I leave the old code in for older mesh files - if elem[0] == erlang_atom('uv_lt'): - uvdata = struct.unpack('>dd', elem[1]) - u1, v1 = uvdata - LSp = mesh.ColorProp((u1, v1)) - - if elem[0] == erlang_atom('uv_rt'): - uvdata = struct.unpack('>dd', elem[1]) - u2, v2 = uvdata - LEp = mesh.ColorProp((u2, v2)) - - if elem[0] == erlang_atom('color'): - colordata = struct.unpack('>dddddd', elem[1]) - r1, g1, b1, r2, g2, b2 = colordata - LSp = mesh.ColorProp((r1, g1, b1, 1)) - LEp = mesh.ColorProp((r2, g2, b2, 1)) - - # read winged data - a, Sv, Ev, Lf, Rf, LP, LS, RP, RS = edgedata - self.check_atom(a, "edge") - - minf, maxf = min(Lf, Rf), max(Lf, Rf) - wobj.edges.append((minf, maxf, Sv, Ev)) - - # store color info here if any - if LSp and LEp: - if wobj.face_vert_colors.has_key((Lf, Sv)) or \ - wobj.face_vert_colors.has_key((Rf, Ev)): - print "hey!" - wobj.face_vert_colors[(Lf, Sv)] = LSp - wobj.face_vert_colors[(Rf, Ev)] = LEp - - # store hardness info - if edge_index in hard_edges: - wobj.hard_edges.append((minf, maxf)) - - # store left and right face - safe_append(faces, Lf, (Sv, Ev)) - safe_append(faces, Rf, (Ev, Sv)) - - # === put edges (Sv & Ev) in correct order === - # === faces{} now contains a sorted list of edges (Sv & Ev) for each face - for i in range(len(faces)): - face = faces[i] - swaps = 1 - while swaps: - swaps = 0 - for j in range(len(face)-2): - if face[j][1] != face[j+1][0]: - face[j+1], face[j+2] = face[j+2], face[j+1] # swap them - swaps = 1 - - # replace tuples with vertex indices, also convert the map to sequence - # s is a sequence of edges, e is an edge - wobj.faces = map(lambda s: map(lambda e: e[0], s), faces.values()) - - if self.dump: - print "*** Edges parsed" - pp = pprint.PrettyPrinter(indent=4,width=78) - pp.pprint(wobj.faces) - pp.pprint(wobj.face_vert_colors) - pp.pprint(wobj.hard_edges) - - def parse_2_faces(self, wobj, raw_faces): - - for face in range(len(raw_faces)): - raw_face = raw_faces[face] - if raw_face: - for elem in raw_face: - if elem[0] == erlang_atom('material'): - mat_name = str(elem[1]) - mat_id = wobj.find_material(mat_name) - else: - try: - mat_id = wobj.find_material("default") - except: - mat_id = 0 - wobj.face_materials.append(mat_id) - - if self.dump: - print "*** Faces parsed" - pp = pprint.PrettyPrinter(indent=4,width=78) - pp.pprint(wobj.face_materials) - - - def parse_2_verts(self, wobj, raw_verts): - wobj.verts = [] - - for vertdata in raw_verts: - x, y, z = struct.unpack(">ddd", vertdata[0]) # double precision - if self.keepRotation: - wobj.verts.append((x, -z, y)) - else: - wobj.verts.append((x, y, z)) - - def parse_2_object(self, obj): - a, name, winged, mode = obj - self.check_atom(a, "object") - - # if mode is invisible, skip this - - a, raw_edges, raw_faces, raw_verts, raw_edge_htable = winged - self.check_atom(a, "winged") - - print "reading object '%s' (%d faces, %d edges, %d vertices)" % (name, - len(raw_faces), len(raw_edges), len(raw_verts)) - - # raw_edge_htable lists hard edges - # (edges are soft by default, so this table may be empty, thus None) - if raw_edge_htable == None: raw_edge_htable = [] - - if type(raw_edge_htable) == types.StringType: - raw_edge_htable = map(ord, raw_edge_htable) - #print raw_edge_htable - - wobj = mesh.Mesh() - wobj.materials = self.materials - wobj.name = name - self.parse_2_edges(wobj, raw_edges, raw_edge_htable) - self.parse_2_faces(wobj, raw_faces) - self.parse_2_verts(wobj, raw_verts) - - return wobj - - def postprocess(self, wobj): - wobj.make_face_normals() - wobj.make_vert_normals(1) - wobj.flatten() - wobj.triangulate() - wobj.submeshize() - - if self.dump: - wobj.dump() - -def read_wings(filename, writeImages, keepRotation): - e = erlang_ext_reader(filename) - raw_data = e.read() - - ob = wings_reader(raw_data, writeImages, keepRotation) - scene = ob.parse() - - return scene - -if __name__ == '__main__': - try: - e = erlang_ext_reader("C:/projects/3d/erpy/uv-cube.wings") - #e = erlang_ext_reader("C:/projects/3d/erpy/mycar.wings") - #e = erlang_ext_reader("/home/attis/src/erpy/cube-colored.wings") - #e = erlang_ext_reader("/home/attis/src/erpy/tank1w.wings") - raw_data = e.read() - - print "read" - - ob = wings_reader(raw_data) - ob.parse() - - print "done" - - #pp = pprint.PrettyPrinter(indent=4,width=78) - #file = open("log1.txt", "w") - #file.write(pp.pformat(raw_data)) - #file.write('\n') - - print "ok" - - finally: - pp = pprint.PrettyPrinter(indent=4,width=78) - pp.pprint(raw_data) - diff --git a/Tools/Wings3DExporter/mesh.py b/Tools/Wings3DExporter/mesh.py deleted file mode 100644 index 7a73165579f..00000000000 --- a/Tools/Wings3DExporter/mesh.py +++ /dev/null @@ -1,440 +0,0 @@ - -from __future__ import nested_scopes - -from vector import Vector -import pgon - -import pprint - -def sum(seq): - return reduce(lambda a, b: a + b, seq) - -# color property of a vertex -class ColorProp: - - color = None - uv = None - - def __init__(self, data): - if len(data) == 2: - self.color = None - self.uv = data - else: - self.color = data - self.uv = None - - def __repr__(self): - r = [] - if self.uv: - u, v = self.uv - r.append("uv %.3f %.3f" % (u, v)) - if self.color: - r, g, b, a = self.color - r.append("color %.3f %.3f %.3f %.3f" % (r, g, b, a)) - if r: return " ".join(r) - else: return "none" - - -# object material -class Material: - - """Material class: - class members: - name - diffuse: diffuse color - ambient: ambient color - specular: specular color - shininess - opacity - textures: list of texture layers - """ - - def __init__(self, name): - self.name = name - self.diffuse = (1,1,1,1) - self.ambient = (0,0,0,1) - self.specular = (0,0,0,1) - self.shininess = 0 - self.textures = [] - - def __repr__(self): - return 'Material("' + self.name + '")' - - -class GLVertex: - - pos = None - normal = None - uv = None - color = None - material = None - - def __eq__(self, other): - return self.pos == other.pos \ - and self.normal == other.normal \ - and self.uv == other.uv \ - and self.color == other.color \ - and self.material == other.material - - def __repr__(self): - seq = [] - seq.append("pos:" + str(self.pos)) - seq.append("normal:" + str(self.normal)) - if self.uv != None: - u, v = self.uv - seq.append("uv: (%.3f,%.3f)" % (u, v)) - if self.color != None: - r, g, b, a = self.color - seq.append("color: (%.3f,%.3f,%.3f,%.3f)" % (r, g, b, a)) - if self.material != None: seq.append("material:" + repr(self.material)) - return " ".join(seq) - -class SubMesh: - - """SubMesh class: - a set of triangles using the same material - - submesh data: - material: material index in parent's materials table - gltris: vertex indices to parent's glverts table - """ - - def __init__(self): - self.material = None - self.mat_data = None - self.gltris = [] - self.glverts = [] - -# object which describes a mesh -class Mesh: - - """Mesh class - class members: - verts: three dimensional coordinates of vertices in this mesh - faces: sequences containing the vertex indices of the polygons - hard_edges: contains face index tuples for hard edges - face_materials: material data for faces - - calculated data: - face_normals: normal vectors of faces - - data associated with (face, vertex) tuples: - face_vert_normals: vertex normals - face_vert_colors: color or uv information - - processed vertex data: - glverts - glfaces: faces - gltris: triangulated glfaces - """ - - def __init__(self): - self.verts = [] - self.faces = [] - self.edges = [] - self.hard_edges = [] - self.face_materials = [] - - self.materials = [] - - self.face_normals = [] - self.face_vert_normals = {} - self.face_vert_colors = {} - - self.glverts = [] - self.glfaces = [] - self.gltris = [] - self.tri_materials = [] - - self.shared_geometry = 0 - - def faces_containing_vertex(self, vertex): - return filter(lambda face: vertex in self.faces[face], - range(len(self.faces))) - - def face_material(self): - return None - - def make_face_normals(self): - "Calculate face normals" - - self.face_normals = [] - for face in self.faces: - n = pgon.pgon_normal(map(lambda v: self.verts[v], face)) - self.face_normals.append(n) - - def face_vert_shareable(self, face1, face2, vertex): - - # returns true if the vertex has the same gl data for the two vertices - glvert1 = self.make_gl_vert(face1, vertex) - glvert2 = self.make_gl_vert(face2, vertex) - - return glvert1 == glvert2 - - def faces_same_smoothing_simple(self, face1, face2, vertex): - - minf, maxf = min(face1, face2), max(face1, face2) - - # check if the edge is hard between the faces - return (minf, maxf) not in self.hard_edges - - def faces_same_smoothing_full(self, face1, face2, vertex): - - myedges = [] - for e in self.edges: - f1, f2, v1, v2 = e - if vertex in [v1, v2]: - myedges.append(e) - - same_smooth = [] - buf = [face1] - while len(buf) > 0: - face = buf.pop() - same_smooth.append(face) - for e in myedges: - f1, f2, v1, v2 = e - if face in [f1, f2] and vertex in [v1, v2]: - if face == f1: - otherface = f2 - else: - otherface = f1 - if otherface not in same_smooth: - if (f1, f2) not in self.hard_edges: - buf.append(otherface) - #print same_smooth - - return face2 in same_smooth - - def partition_verts(self, pred): - "Partition vertices using the given predicate" - - result = [] - for vertex in range(len(self.verts)): - buckets = [] - for face in self.faces_containing_vertex(vertex): - found_bucket = None - - # find a bucket for this face - for bucket in buckets: - - # find faces which are compatible with current - flags = map(lambda f: pred(face, f, vertex), bucket) - - # check if this is ok - if 0 not in flags: - found_bucket = bucket - - # add face to correct bucket or create new bucket - if found_bucket: - found_bucket.append(face) - else: - buckets.append([face]) - result.append(buckets) - - return result - - - def make_vert_normals(self, full_test): - - print "smoothing..." - if full_test: - self.faces_same_smoothing = self.faces_same_smoothing_full - else: - self.faces_same_smoothing = self.faces_same_smoothing_simple - - # find faces which are compatible with current - all_buckets = self.partition_verts(self.faces_same_smoothing) - - #pp = pprint.PrettyPrinter(indent=4,width=78) - #pp.pprint(self.hard_edges) - #pp.pprint(all_buckets) - - self.face_vert_normals = {} - for vertex in range(len(self.verts)): - buckets = all_buckets[vertex] - - for bucket in buckets: - bucket_normals = map(lambda x: self.face_normals[x], bucket) - try: - normal = sum(bucket_normals).unit() - for face in bucket: - self.face_vert_normals[(face, vertex)] = normal - except ValueError, x: - print bucket_normals - raise x - - def make_gl_vert(self, face, vertex): - - glvert = GLVertex() - - # these are mandatory - glvert.pos = self.verts[vertex] - glvert.normal = self.face_vert_normals[(face, vertex)] - - # check if there is color data - if self.face_vert_colors.has_key((face, vertex)): - data = self.face_vert_colors[(face, vertex)] - uv = data.uv - color = data.color - else: - uv, color = None, None - #glvert.uv, glvert.color = uv, color - # Sinbad: flip v texcoord for 0.13 - if uv: - newu, newv = uv - newv = 1 - newv - glvert.uv = newu, newv - else: - glvert.uv = uv - glvert.color = color - # End Sinbad - glvert.material = self.face_materials[face] - - return glvert - - def flatten(self): - "generate gl vertices" - - # create buckets for shareable vertices - all_buckets = self.partition_verts(self.face_vert_shareable) - - # calculate number of total verts - ntotal = sum(map(len, all_buckets)) - - # create duplicate vertices and vertex indices - cur_vert_idx = 0 - gl_indices = [] - self.glverts = [] - for vertex in range(len(self.verts)): - nsubverts = len(all_buckets[vertex]) - gl_indices.append(range(cur_vert_idx, cur_vert_idx + nsubverts)) - for bucket in all_buckets[vertex]: - face = bucket[0] - self.glverts.append(self.make_gl_vert(face, vertex)) - cur_vert_idx += nsubverts - - # create reindexed faces - self.glfaces = [] - for face in range(len(self.faces)): - vertices = self.faces[face] - glface = [] - for vi in vertices: - - def sublistindexelem(seq, val): - for i in range(len(seq)): - if val in seq[i]: return i - return None - - group = sublistindexelem(all_buckets[vi], face) - glface.append(gl_indices[vi][group]) - self.glfaces.append(glface) - - def triangulate(self): - "triangulate polygons" - - print "tesselating..." - - self.gltris = [] - self.tri_materials = [] - for i in range(len(self.glfaces)): - face = self.glfaces[i] - mat = self.face_materials[i] - if len(face) == 3: - self.gltris.append(face) - self.tri_materials.append(mat) - else: - verts = map(lambda vindex: Vector(self.glverts[vindex].pos), face) - - # triangulate using ear clipping method - tris = pgon.triangulate(verts) - - for tri in tris: - A, B, C = map(lambda pindex: face[pindex], tri) - self.gltris.append([A, B, C]) - self.tri_materials.append(mat) - - def submeshize(self): - "create submeshes" - - print "creating submeshes..." - - temp = {} - for t in self.tri_materials: - temp[t] = 1 - trimats = temp.keys() - - self.subs = [] - for mat in trimats: - submesh = SubMesh() - submesh.material = mat - submesh.mat_data = self.materials[mat] - if self.shared_geometry: - # use shared geometry - for i in range(len(self.tri_materials)): - if self.tri_materials[i] == mat: - submesh.gltris.append(self.gltris[i]) - else: - verts = {} - for i in range(len(self.tri_materials)): - if self.tri_materials[i] == mat: - for vert in self.gltris[i]: - verts[vert] = 1 - verts = verts.keys() - verts.sort() - for i in verts: - submesh.glverts.append(self.glverts[i]) - for i in range(len(self.tri_materials)): - if self.tri_materials[i] == mat: - tri = [] - for vert in self.gltris[i]: - tri.append(verts.index(vert)) - submesh.gltris.append(tri) - self.subs.append(submesh) - - def dump(self): - "show data" - - print "Mesh '%s':" % self.name - - print "%d vertices:" % len(self.glverts) - for vert in self.glverts: print " ", vert - - ntris = sum(map(lambda submesh: len(submesh.gltris), self.subs)) - print "%d submeshes, %d tris total:" % (len(self.subs), ntris) - for sub in self.subs: - print " material %d (%s), %d tris" % (sub.material, sub.mat_data.name, len(sub.gltris)) - for tri in sub.gltris: - A, B, C = tri - print " ", A, B, C - - def merge(self, other): - "add all mesh data from another mesh to self" - - nv = len(self.verts) - nf = len(self.faces) - - self.verts += other.verts - self.faces += map(lambda face: map(lambda x: x + nv, face), other.faces) - self.hard_edges += map(lambda (x, y): (x + nf, y + nf), other.hard_edges) - self.face_materials += other.face_materials - - for fv in other.face_vert_colors.keys(): - face, vert = fv - value = other.face_vert_colors[fv] - self.face_vert_colors[(face + nf, vert + nv)] = value - - for e in other.edges: - f1, f2, v1, v2 = e - self.edges.append((f1 + nf, f2 + nf, v1 + nv, v2 + nv)) - - def scale(self, value): - for v in self.glverts: - v.pos = Vector(v.pos) * value - - def find_material(self, mat_name): - for m in range(len(self.materials)): - if self.materials[m].name == mat_name: - return m - return None - - diff --git a/Tools/Wings3DExporter/pgon.py b/Tools/Wings3DExporter/pgon.py deleted file mode 100644 index 29358804d61..00000000000 --- a/Tools/Wings3DExporter/pgon.py +++ /dev/null @@ -1,221 +0,0 @@ -# ear-clipping polygon triangulation -# -# written in 2003 by Attila Tajti - -from vector import Vector - -def sum(a, b): - return a + b - -# get the average normal of a 3d polygon -def pgon_normal(verts): - normal = Vector(0,0,0) - for i in range(len(verts)): - x1, y1, z1 = verts[i - 1] - x2, y2, z2 = verts[i] - nx = (y1 - y2) * (z1 + z2) - ny = (z1 - z2) * (x1 + x2) - nz = (x1 - x2) * (y1 + y2) - normal += Vector(nx, ny, nz) - return normal.unit() - -class Triangulator: - - def dump(self, what): - if __name__ == "__main__": - print what - - def __init__(self, pgon): - self.pgon = pgon - - self.dump("pgon: %s" % repr(self.pgon)) - - # normal used for direction calculation - self.normal = pgon_normal(pgon) - self.dump("normal: %s" % repr(self.normal)) - - # original indices - self.indices = range(len(self.pgon)) - - # result triangles - self.tris = [] - - def process(self): - - while len(self.indices) > 3: - self.find_and_clip_ear() - - self.tris.append(self.indices) - - self.dump("triangles: %s\n" % repr(self.tris)) - - return self.tris - - def this_v(self, vert): - "return position of given vertex" - return self.pgon[vert] - - def pred_i(self, vert): - cur = self.indices.index(vert) - return self.indices[cur - 1] - - def pred_v(self, vert): - "return position of predecessor vertex" - pred = self.pred_i(vert) - return self.pgon[pred] - - def succ_i(self, vert): - cur = self.indices.index(vert) - return self.indices[cur + 1 - len(self.indices)] - - def succ_v(self, vert): - "return position of successor vertex" - succ = self.succ_i(vert) - return self.pgon[succ] - - def tri_i_at(self, vert): - Ai = self.pred_i(vert) - Bi = vert - Ci = self.succ_i(vert) - #self.dump(" tri %d,%d,%d" % (Ai,Bi,Ci)) - return Ai, Bi, Ci - - def tri_at(self, vert): - Ai, Bi, Ci = self.tri_i_at(vert) - A = self.pgon[Ai] - B = self.pgon[Bi] - C = self.pgon[Ci] - return A, B, C - - def reflex_factor(self, eartip): - A, B, C = self.tri_at(eartip) - AB = B - A - BC = C - B - # vector pointing outside - AB_out = Vector.cross(AB, self.normal).unit() - return Vector.dot(AB_out, BC.unit()) - - def is_convex(self, eartip): - return self.reflex_factor(eartip) < 0 - - def all_outside(self, eartip, verts): - tri = self.tri_at(eartip) - A, B, C = tri - sides = B - A, C - B, A - C - # vector pointing outside - normals = map(lambda x: Vector.cross(x, self.normal), sides) - for vert in map(lambda x: self.pgon[x], verts): - out = 0 - for i in range(3): - outside_edge = Vector.dot(vert - tri[i], normals[i]) - if outside_edge: - out = 1 - # vertex inside triangle - if not out: return 0 - return 1 - - def is_ear(self, eartip): - - # create array of other vertices - others = self.indices[:] - - # remove current triangle - A, B, C = self.tri_i_at(eartip) - others.remove(A) - others.remove(B) - others.remove(C) - - # check if all is outside - return self.all_outside(eartip, others) - - def clip_ear(self, vert): - self.tris.append(list(self.tri_i_at(vert))) - self.indices.remove(vert) - - def find_and_clip_ear(self): - "find clip one ear" - - # try to cut at the tightest angles first - # TODO: check if this is good for us - - # vertices we are working with - work = self.indices[:] - - # factors for all vertices - factors = map(self.reflex_factor, work) - - while len(factors): - f = min(factors) - eartip = work[factors.index(f)] - - if self.is_ear(eartip): - - self.clip_ear(eartip) - return - else: - # remove this from our work list - factors.remove(f) - work.remove(eartip) - - print self.pgon - print self.indices - raise ValueError("failed!") - - def find_and_clip_earx(self): - "find clip one ear" - - print self.indices - for vert in self.indices: - # check if point is convex - if self.is_convex(vert): - self.dump("%s is convex" % repr(vert)) - - # check if this vertex is an ear - if self.is_ear(vert): - - self.dump("%s is an ear" % repr(vert)) - - # found an eartip, remove it - self.clip_ear(vert) - return - else: - self.dump("%s is reflex" % repr(vert)) - raise ValueError("failed!") - - -def triangulate(pgon): - "triangulate a polygon defined by its vertices" - - t = Triangulator(pgon) - - return t.process() - -if __name__ == "__main__": - - print "* normal polygon" - pgon = [] - pgon.append(Vector(0,0,0)) - pgon.append(Vector(1,0,0)) - pgon.append(Vector(1,1,0)) - pgon.append(Vector(0,1,0)) - triangulate(pgon) - - print "* concave polygon" - pgon = [] - pgon.append(Vector(0,0,0)) - pgon.append(Vector(1,1,0)) - pgon.append(Vector(3,0,0)) - pgon.append(Vector(3,1,0)) - pgon.append(Vector(0,1,0)) - triangulate(pgon) - - print "* poly with straight edges" - pgon = [] - pgon.append(Vector(0,0,0)) - pgon.append(Vector(0.5,0,0)) - pgon.append(Vector(1,0,0)) - pgon.append(Vector(2,0,0)) - pgon.append(Vector(2,2,0)) - pgon.append(Vector(0,2,0)) - triangulate(pgon) - diff --git a/Tools/Wings3DExporter/vector.py b/Tools/Wings3DExporter/vector.py deleted file mode 100644 index 89a47bde732..00000000000 --- a/Tools/Wings3DExporter/vector.py +++ /dev/null @@ -1,114 +0,0 @@ - -import math - -class Vector: - - rep = None - - def __init__(self, x, y=None, z=None, w=None): - if y == None: - self.rep = tuple(x) - elif z == None: - self.rep = (x, y) - elif w == None: - self.rep = (x, y, z) - else: - self.rep = (x, y, z, w) - - # math functions - - def __add__(self, other): - return Vector(map(lambda a, b: a + b, self.rep, other.rep)) - - def __sub__(self, other): - return Vector(map(lambda a, b: a - b, self.rep, other.rep)) - - def __mul__(self, value): - return Vector(map(lambda x: x * value, self.rep)) - - def __div__(self, value): - return Vector(map(lambda x: x / value, self.rep)) - - def __abs__(self): - "absolute gives the length" - return math.sqrt(self % self) - - def __neg__(self): - return Vector(map(lambda x: -x, self.rep)) - - def __mod__(self, other): - "dot product" - return self.dot(other) - - def __xor__(self, other): - "3d cross product" - return self.cross(other) - - # coord access functions - - def __len__(self): - return len(self.rep) - - def __getitem__(self, index): - return self.rep[index] - - def __getattr__(self, name): - name_indices = {'x':0, 'y':1, 'z':2, 'w': 3, 'u': 0, 'v': 1} - if not name_indices.has_key(name): raise AttributeError(name) - return self.rep[name_indices[name]] - - # other useful basic functions - - def __eq__(self, other): - return 0 not in map(lambda a, b: a == b, self.rep, other.rep) - - def __ne__(self, other): - return 0 in map(lambda a, b: a == b, self.rep, other.rep) - - def __nonzero__(self): - return max(map(lambda x: abs(x), self.rep)) > 0 - - # string conversion functions - - def __str__(self): - s = ",".join(map(lambda x: "%.3f" % x, self.rep)) - return '(' + s + ')' - - def __repr__(self): - s = ",".join(map(lambda x: "%.3f" % x, self.rep)) - return 'Vector(' + s + ')' - - # other functions - - def dot(self, other): - temp = map(lambda x, y: x * y, self.rep, other.rep) - return reduce(lambda a, b: a + b, temp) - - def cross(self, other): - a1, a2, a3 = self - b1, b2, b3 = other - return Vector(a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1) - - def normalize(self): - len = abs(self) - if len < 1e-5: raise ValueError('zero vector') - self.rep = tuple(map(lambda x: x / len, self.rep)) - - def unit(self): - len = abs(self) - if len < 1e-5: raise ValueError('zero vector') - return self / len - -# test -if __name__ == "__main__": - a = Vector(0,3,4) - b = Vector(1,2,5) - - print a, b - print a + b - print abs(a) - print a + Vector(1,0,0) - print a ^ b - x, y, z = a - print x, y, z - diff --git a/Tools/Wings3DExporter/w2o.py b/Tools/Wings3DExporter/w2o.py deleted file mode 100644 index 57b34ef08dd..00000000000 --- a/Tools/Wings3DExporter/w2o.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/python - -from erlang_ext import * -import types -import pprint - -import io3d_wings -import io3d_ogre - -import getopt - -version = "0.93" - -def conv(infile, outfile, writeImages, keepRotation, scaleFactor): - obj = io3d_wings.read_wings(infile, writeImages, keepRotation) - if scaleFactor != 1.0: obj.scale(scaleFactor) - io3d_ogre.write_ogre(obj, outfile) - -if __name__ == "__main__": - - try: - options, args = getopt.getopt(sys.argv[1:], "hviks:") - - writeImages = 0 - keepRotation = 0 - scaleFactor = 1.0 - - for o in options: - option, value = o - - if option == '-h': - print """Usage: -w2o [-iks] file1.wings file2.wings - -Options: - -h This help - -v Print version - -i Export images from the wings file via PIL - -k Keep the coordinates as they are, do not correct them - to the OGRE coordinate system. Use this if you - want to rotate your objects around the X axis in - code or if you already rotated the objects in Wings. - -s n Scale the object uniformly using the given floating - point factor. -""" - sys.exit(1) - - elif option == '-v': - print "w2o", version - sys.exit(1) - - elif option == '-i': writeImages = 1 - - elif option == '-k': keepRotation = 1 - - elif option == '-s': scaleFactor = float(value) - - for arg in args: - - # process filename - if arg[-6:] == ".wings": - dstname = arg[:-6] - else: - dstname = arg - dstname += ".mesh.xml" - conv(arg, dstname, writeImages, keepRotation, scaleFactor) - - except getopt.GetoptError, e: - print e - print "try -h for help" - sys.exit(1) - diff --git a/Tools/Wings3DExporter/xmlout.py b/Tools/Wings3DExporter/xmlout.py deleted file mode 100644 index daeb56dc5db..00000000000 --- a/Tools/Wings3DExporter/xmlout.py +++ /dev/null @@ -1,75 +0,0 @@ - -# extremely simple XML writer -# -# This is to remove libxml2 dependency on platforms where it's -# difficult to build -# -# 2003 Attila Tajti - -class XMLDoc: - - def __init__(self, version): - self.version = version - self.root_element = None - - def saveFile(self, filename): - f = file(filename, "w") - f.write('\n') - self.root_element._write(f, 0) - - def saveFormatFile(self, filename, fmt): - self.saveFile(filename) - - def freeDoc(self): - pass - -class XMLNode: - - def __init__(self, name): - self.name = name - self.props = [] - self.children = [] - self.content = None - - def docSetRootElement(self, doc): - doc.root_element = self - - def newChild(self, namespace, name, content): - if namespace: - fullname = namespace + ':' + name - else: - fullname = name - child = XMLNode(fullname) - child.content = content - self.children.append(child) - return child - - def setProp(self, name, value): - self.props.append((name, value)) - - def _write(self, f, indent): - #istr = " " * indent - istr = "\t" * indent - - # put together our tag - tag = self.name - for prop in self.props: - name, value = prop - tag += ' ' + name + '="' + value + '"' - - # print tag, or children between tags - if self.children: - f.write(istr + '<%s>\n' % tag) - for child in self.children: - child._write(f, indent + 1) - f.write(istr + '\n' % self.name) - else: - f.write(istr + '<%s/>\n' % tag) - -def newDoc(version): - return XMLDoc(version) - -def newNode(name): - return XMLNode(name) - - diff --git a/Tools/XMLConverter/CMakeLists.txt b/Tools/XMLConverter/CMakeLists.txt deleted file mode 100644 index fa5411f140e..00000000000 --- a/Tools/XMLConverter/CMakeLists.txt +++ /dev/null @@ -1,31 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -# Configure XMLConverter - -set(HEADER_FILES - include/OgreXMLMeshSerializer.h - include/OgreXMLPrerequisites.h - include/OgreXMLSkeletonSerializer.h -) - -set(SOURCE_FILES - src/main.cpp - src/OgreXMLMeshSerializer.cpp - src/OgreXMLSkeletonSerializer.cpp -) - -add_executable(OgreXMLConverter ${HEADER_FILES} ${SOURCE_FILES}) -target_include_directories(OgreXMLConverter PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include) -target_link_libraries(OgreXMLConverter OgreMain pugixml) - -if (OGRE_PROJECT_FOLDERS) - set_property(TARGET OgreXMLConverter PROPERTY FOLDER Tools) -endif () -ogre_config_tool(OgreXMLConverter) diff --git a/Tools/XMLConverter/docs/ogremeshxml.dtd b/Tools/XMLConverter/docs/ogremeshxml.dtd deleted file mode 100644 index ef1209b2e4e..00000000000 --- a/Tools/XMLConverter/docs/ogremeshxml.dtd +++ /dev/null @@ -1,188 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/XMLConverter/docs/ogreskeletonxml.dtd b/Tools/XMLConverter/docs/ogreskeletonxml.dtd deleted file mode 100644 index 23edfd95314..00000000000 --- a/Tools/XMLConverter/docs/ogreskeletonxml.dtd +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/XMLConverter/docs/validate.py b/Tools/XMLConverter/docs/validate.py deleted file mode 100644 index 076a8dac187..00000000000 --- a/Tools/XMLConverter/docs/validate.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/python3 - -import sys -import os.path -from lxml import etree - -mesh_dtd = etree.DTD(sys.path[0]+"/ogremeshxml.dtd") -skel_dtd = etree.DTD(sys.path[0]+"/ogreskeletonxml.dtd") - -mesh = sys.argv[1] -meshxml = etree.parse(sys.argv[1]) - -ret = 0 - -if mesh_dtd.validate(meshxml): - print("mesh validation successful") -else: - print("mesh validation errors") - print(mesh_dtd.error_log.filter_from_errors()) - ret = -1 - -skel = meshxml.find("skeletonlink") - -if skel is None: - sys.exit(ret) - -skelxml = etree.parse("{}/{}.xml".format(os.path.dirname(sys.argv[1]), skel.attrib["name"])) -if skel_dtd.validate(skelxml): - print("skeleton validation successful") -else: - print("skeleton validation errors") - print(skel_dtd.error_log.filter_from_errors()) - ret = -1 - -sys.exit(ret) - diff --git a/Tools/XMLConverter/include/OgreXMLMeshSerializer.h b/Tools/XMLConverter/include/OgreXMLMeshSerializer.h deleted file mode 100644 index 4abb6ba17d4..00000000000 --- a/Tools/XMLConverter/include/OgreXMLMeshSerializer.h +++ /dev/null @@ -1,108 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __XMLMeshSerializer_H__ -#define __XMLMeshSerializer_H__ - -#include "OgreXMLPrerequisites.h" -#include "OgreMesh.h" - - -namespace Ogre { - - /** Class for serializing a Mesh to/from XML. - - This class behaves the same way as MeshSerializer in the main project, - but is here to allow conversions to / from XML. This class is - deliberately not included in the main project because
    -
  • Dependence on Xerces would unnecessarily bloat the main library
  • -
  • Runtime use of XML is discouraged because of the parsing overhead
- This class gives people the option of saving out a Mesh as XML for examination - and possible editing. It can then be converted back to the native format - for maximum runtime efficiency. - */ - class XMLMeshSerializer - { - public: - - XMLMeshSerializer(); - virtual ~XMLMeshSerializer(); - /** Imports a Mesh from the given XML file. - @param filename The name of the file to import, expected to be in XML format. - @param pMesh The pre-created Mesh object to be populated. - */ - void importMesh(const String& filename, Mesh* pMesh); - - /** Exports a mesh to the named XML file. */ - void exportMesh(const Mesh* pMesh, const String& filename); - - protected: - // State for import - Mesh* mMesh; - VertexElementType mColourElementType; - - // Internal methods - void writeMesh(const Mesh* pMesh, pugi::xml_node& rootNode); - void writeSubMesh(pugi::xml_node& mSubmeshesNode, const SubMesh* s); - void writeGeometry(pugi::xml_node& mParentNode, const VertexData* pData); - void writeSkeletonLink(pugi::xml_node& mMeshNode, const String& skelName); - void writeBoneAssignment(pugi::xml_node& mBoneAssignNode, const VertexBoneAssignment* assign); - void writeLodInfo(pugi::xml_node& mMeshNode, const Mesh* pMesh); - void writeLodUsageManual(pugi::xml_node& usageNode, unsigned short levelNum, - const MeshLodUsage& usage); - void writeLodUsageGenerated(pugi::xml_node& usageNode, unsigned short levelNum, - const MeshLodUsage& usage, const Mesh* pMesh); - void writeSubMeshNames(pugi::xml_node& mMeshNode, const Mesh* m); - void writePoses(pugi::xml_node& meshNode, const Mesh* m); - void writeAnimations(pugi::xml_node& meshNode, const Mesh* m); - void writeMorphKeyFrames(pugi::xml_node& trackNode, const VertexAnimationTrack* track); - void writePoseKeyFrames(pugi::xml_node& trackNode, const VertexAnimationTrack* track); - void writeExtremes(pugi::xml_node& mMeshNode, const Mesh* m); - - void readSubMeshes(pugi::xml_node& mSubmeshesNode); - void readGeometry(pugi::xml_node& mGeometryNode, VertexData* pData); - void readSkeletonLink(pugi::xml_node& mSkelNode); - void readBoneAssignments(pugi::xml_node& mBoneAssignmentsNode); - void readBoneAssignments(pugi::xml_node& mBoneAssignmentsNode, SubMesh* sm); -#if !OGRE_NO_MESHLOD - void readLodInfo(pugi::xml_node& lodNode); - void readLodUsageManual(pugi::xml_node& manualNode, unsigned short index); - void readLodUsageGenerated(pugi::xml_node& genNode, unsigned short index); -#endif - void readSubMeshNames(pugi::xml_node& mMeshNamesNode, Mesh* sm); - void readPoses(pugi::xml_node& posesNode, Mesh *m); - void readAnimations(pugi::xml_node& mAnimationsNode, Mesh *m); - void readTracks(pugi::xml_node& tracksNode, Mesh *m, Animation* anim); - void readMorphKeyFrames(pugi::xml_node& keyframesNode, VertexAnimationTrack* track, - size_t vertexCount); - void readPoseKeyFrames(pugi::xml_node& keyframesNode, VertexAnimationTrack* track); - void readExtremes(pugi::xml_node& extremesNode, Mesh *m); - }; -} - -#endif diff --git a/Tools/XMLConverter/include/OgreXMLPrerequisites.h b/Tools/XMLConverter/include/OgreXMLPrerequisites.h deleted file mode 100644 index c4287595468..00000000000 --- a/Tools/XMLConverter/include/OgreXMLPrerequisites.h +++ /dev/null @@ -1,38 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __XMLPrerequisites_H__ -#define __XMLPrerequisites_H__ - -#include "OgrePrerequisites.h" - -// Include tinyxml headers -#include - - -#endif diff --git a/Tools/XMLConverter/include/OgreXMLSkeletonSerializer.h b/Tools/XMLConverter/include/OgreXMLSkeletonSerializer.h deleted file mode 100644 index 1b870eb5bd3..00000000000 --- a/Tools/XMLConverter/include/OgreXMLSkeletonSerializer.h +++ /dev/null @@ -1,89 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#ifndef __XMLSkeletonSerializer_H__ -#define __XMLSkeletonSerializer_H__ - -#include "OgreXMLPrerequisites.h" -#include "OgreMaterial.h" -#include "OgreSkeleton.h" - - -namespace Ogre { - - /** Class for serializing a Skeleton to/from XML. - - This class behaves the same way as SkeletonSerializer in the main project, - but is here to allow conversions to / from XML. This class is - deliberately not included in the main project because
    -
  • Dependence on Xerces would unnecessarily bloat the main library
  • -
  • Runtime use of XML is discouraged because of the parsing overhead
- This class gives people the option of saving out a Skeleton as XML for examination - and possible editing. It can then be converted back to the native format - for maximum runtime efficiency. - */ - class XMLSkeletonSerializer - { - public: - - XMLSkeletonSerializer(); - virtual ~XMLSkeletonSerializer(); - /** Imports a Skeleton from the given XML file. - @param filename The name of the file to import, expected to be in XML format. - @param pSkeleton The pre-created Skeleton object to be populated. - */ - void importSkeleton(const String& filename, Skeleton* pSkeleton); - - /** Exports a skeleton to the named XML file. */ - void exportSkeleton(const Skeleton* pSkeleton, const String& filename); - - private: - void writeSkeleton(const Skeleton* pSkel, pugi::xml_node& root); - void writeBone(pugi::xml_node& bonesElement, const Bone* pBone); - void writeBoneParent(pugi::xml_node& boneHierarchyNode, const String& boneName , const String& parentName); - void writeAnimation(pugi::xml_node& animsNode, const Animation* anim); - void writeAnimationTrack(pugi::xml_node& tracksNode, - const NodeAnimationTrack* track); - void writeKeyFrame(pugi::xml_node& keysNode, const TransformKeyFrame* key); - void writeSkeletonAnimationLink(pugi::xml_node& linksNode, - const LinkedSkeletonAnimationSource& link); - - void readBones(Skeleton* skel, pugi::xml_node& mBonesNode); - void readBones2(Skeleton* skel, pugi::xml_node& mBonesNode); - void createHierarchy(Skeleton* skel, pugi::xml_node& mHierNode); - void readKeyFrames(NodeAnimationTrack* track, const pugi::xml_node& mKeyfNode); - void readAnimations(Skeleton* skel, pugi::xml_node& mAnimNode) ; - void readSkeletonAnimationLinks(Skeleton* skel, pugi::xml_node& linksNode); - - }; - - -} - -#endif - diff --git a/Tools/XMLConverter/src/OgreXMLMeshSerializer.cpp b/Tools/XMLConverter/src/OgreXMLMeshSerializer.cpp deleted file mode 100644 index 8a74703c7b6..00000000000 --- a/Tools/XMLConverter/src/OgreXMLMeshSerializer.cpp +++ /dev/null @@ -1,2135 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - - -#include "OgreXMLMeshSerializer.h" -#include "OgreSubMesh.h" -#include "OgreLogManager.h" -#include "OgreSkeleton.h" -#include "OgreStringConverter.h" -#include "OgreHardwareBufferManager.h" -#include "OgreException.h" -#include "OgreAnimation.h" -#include "OgreAnimationTrack.h" -#include "OgreKeyFrame.h" -#include "OgreLodStrategyManager.h" -#include "OgreLodStrategy.h" -#include "OgreMaterialManager.h" -#include "OgreSkeletonManager.h" -#include - -namespace Ogre { - - //--------------------------------------------------------------------- - XMLMeshSerializer::XMLMeshSerializer() - { - } - //--------------------------------------------------------------------- - XMLMeshSerializer::~XMLMeshSerializer() - { - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::importMesh(const String& filename, Mesh* pMesh) - { - LogManager::getSingleton().logMessage("XMLMeshSerializer reading mesh data from " + filename + "..."); - mMesh = pMesh; - mColourElementType = VET_UBYTE4_NORM; - pugi::xml_document mXMLDoc; - mXMLDoc.load_file(filename.c_str()); - - pugi::xml_node elem; - - pugi::xml_node rootElem = mXMLDoc.document_element(); - - // shared geometry - elem = rootElem.child("sharedgeometry"); - if (elem) - { - if(StringConverter::parseInt(elem.attribute("vertexcount").value()) > 0) - { - mMesh->createVertexData(); - readGeometry(elem, mMesh->sharedVertexData); - } - } - - // submeshes - elem = rootElem.child("submeshes"); - if (elem) - readSubMeshes(elem); - - // skeleton link - elem = rootElem.child("skeletonlink"); - if (elem) - readSkeletonLink(elem); - - // bone assignments - elem = rootElem.child("boneassignments"); - if (elem) - readBoneAssignments(elem); - -#if !OGRE_NO_MESHLOD - //Lod - elem = rootElem.child("levelofdetail"); - if (elem) - readLodInfo(elem); -#endif - - // submesh names - elem = rootElem.child("submeshnames"); - if (elem) - readSubMeshNames(elem, mMesh); - - // submesh extremes - elem = rootElem.child("extremes"); - if (elem) - readExtremes(elem, mMesh); - - // poses - elem = rootElem.child("poses"); - if (elem) - readPoses(elem, mMesh); - - // animations - elem = rootElem.child("animations"); - if (elem) - readAnimations(elem, mMesh); - - LogManager::getSingleton().logMessage("XMLMeshSerializer import successful."); - - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::exportMesh(const Mesh* pMesh, const String& filename) - { - LogManager::getSingleton().logMessage("XMLMeshSerializer writing mesh data to " + filename + "..."); - - mMesh = const_cast(pMesh); - - pugi::xml_document mXMLDoc; - pugi::xml_node rootNode = mXMLDoc.append_child("mesh"); - - LogManager::getSingleton().logMessage("Populating DOM..."); - - - - // Write to DOM - writeMesh(pMesh, rootNode); - LogManager::getSingleton().logMessage("DOM populated, writing XML file.."); - - // Write out to a file - if(! mXMLDoc.save_file(filename.c_str()) ) - { - LogManager::getSingleton().logMessage("XMLMeshSerializer failed writing the XML file.", LML_CRITICAL); - } - else - { - LogManager::getSingleton().logMessage("XMLMeshSerializer export successful."); - } - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::writeMesh(const Mesh* pMesh, pugi::xml_node& rootNode) - { - // Write geometry - if (pMesh->sharedVertexData) - { - pugi::xml_node geomNode = rootNode.append_child("sharedgeometry"); - writeGeometry(geomNode, pMesh->sharedVertexData); - } - - // Write Submeshes - pugi::xml_node subMeshesNode = rootNode.append_child("submeshes"); - for (size_t i = 0; i < pMesh->getNumSubMeshes(); ++i) - { - LogManager::getSingleton().logMessage("Writing submesh..."); - writeSubMesh(subMeshesNode, pMesh->getSubMesh(i)); - LogManager::getSingleton().logMessage("Submesh exported."); - } - - // Write skeleton info if required - if (pMesh->hasSkeleton()) - { - LogManager::getSingleton().logMessage("Exporting skeleton link..."); - // Write skeleton link - writeSkeletonLink(rootNode, pMesh->getSkeletonName()); - LogManager::getSingleton().logMessage("Skeleton link exported."); - - // Write bone assignments - const auto& boneAssigns = pMesh->getBoneAssignments(); - if (!boneAssigns.empty()) - { - LogManager::getSingleton().logMessage("Exporting shared geometry bone assignments..."); - pugi::xml_node boneAssignNode = rootNode.append_child("boneassignments"); - - for (const auto& e : boneAssigns) - { - writeBoneAssignment(boneAssignNode, &e.second); - } - - LogManager::getSingleton().logMessage("Shared geometry bone assignments exported."); - } - } - if (pMesh->getNumLodLevels() > 1) - { - LogManager::getSingleton().logMessage("Exporting LOD information..."); - writeLodInfo(rootNode, pMesh); - LogManager::getSingleton().logMessage("LOD information exported."); - } - // Write submesh names - writeSubMeshNames(rootNode, pMesh); - // Write poses - writePoses(rootNode, pMesh); - // Write animations - writeAnimations(rootNode, pMesh); - // Write extremes - writeExtremes(rootNode, pMesh); - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::writeSubMesh(pugi::xml_node& mSubMeshesNode, const SubMesh* s) - { - pugi::xml_node subMeshNode = mSubMeshesNode.append_child("submesh"); - - size_t numFaces; - - // Material name - subMeshNode.append_attribute("material") = s->getMaterialName().c_str(); - // bool useSharedVertices - subMeshNode.append_attribute("usesharedvertices") = - StringConverter::toString(s->useSharedVertices).c_str(); - // bool use32BitIndexes - bool use32BitIndexes = (s->indexData->indexBuffer && - s->indexData->indexBuffer->getType() == HardwareIndexBuffer::IT_32BIT); - subMeshNode.append_attribute("use32bitindexes") = - StringConverter::toString( use32BitIndexes ).c_str(); - - // Operation type - switch(s->operationType) - { - case RenderOperation::OT_LINE_LIST: - subMeshNode.append_attribute("operationtype") = "line_list"; - break; - case RenderOperation::OT_LINE_STRIP: - subMeshNode.append_attribute("operationtype") = "line_strip"; - break; - case RenderOperation::OT_POINT_LIST: - subMeshNode.append_attribute("operationtype") = "point_list"; - break; - case RenderOperation::OT_TRIANGLE_FAN: - subMeshNode.append_attribute("operationtype") = "triangle_fan"; - break; - case RenderOperation::OT_TRIANGLE_LIST: - subMeshNode.append_attribute("operationtype") = "triangle_list"; - break; - case RenderOperation::OT_TRIANGLE_STRIP: - subMeshNode.append_attribute("operationtype") = "triangle_strip"; - break; - case RenderOperation::OT_TRIANGLE_LIST_ADJ: - subMeshNode.append_attribute("operationtype") = "triangle_list_adj"; - break; - case RenderOperation::OT_TRIANGLE_STRIP_ADJ: - subMeshNode.append_attribute("operationtype") = "triangle_strip_adj"; - break; - case RenderOperation::OT_LINE_LIST_ADJ: - subMeshNode.append_attribute("operationtype") = "line_list_adj"; - break; - case RenderOperation::OT_LINE_STRIP_ADJ: - subMeshNode.append_attribute("operationtype") = "line_strip_adj"; - break; - default: - OgreAssert(false, "Patch control point operations not supported"); - break; - } - - if (s->indexData->indexCount > 0) - { - // Faces - pugi::xml_node facesNode = - subMeshNode.append_child("faces"); - switch(s->operationType) - { - case RenderOperation::OT_TRIANGLE_LIST: - // tri list - numFaces = s->indexData->indexCount / 3; - - break; - case RenderOperation::OT_LINE_LIST: - numFaces = s->indexData->indexCount / 2; - - break; - case RenderOperation::OT_TRIANGLE_FAN: - case RenderOperation::OT_TRIANGLE_STRIP: - // triangle fan or triangle strip - numFaces = s->indexData->indexCount - 2; - - break; - default: - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Unsupported render operation type"); - } - facesNode.append_attribute("count") = StringConverter::toString(numFaces).c_str(); - // Write each face in turn - size_t i; - unsigned int* pInt = 0; - unsigned short* pShort = 0; - HardwareIndexBufferSharedPtr ibuf = s->indexData->indexBuffer; - if (use32BitIndexes) - { - pInt = static_cast( - ibuf->lock(HardwareBuffer::HBL_READ_ONLY)); - } - else - { - pShort = static_cast( - ibuf->lock(HardwareBuffer::HBL_READ_ONLY)); - } - for (i = 0; i < numFaces; ++i) - { - pugi::xml_node faceNode = facesNode.append_child("face"); - if (use32BitIndexes) - { - faceNode.append_attribute("v1") = StringConverter::toString(*pInt++).c_str(); - if(s->operationType == RenderOperation::OT_LINE_LIST) - { - faceNode.append_attribute("v2") = StringConverter::toString(*pInt++).c_str(); - } - /// Only need all 3 vertex indices if trilist or first face - else if (s->operationType == RenderOperation::OT_TRIANGLE_LIST || i == 0) - { - faceNode.append_attribute("v2") = StringConverter::toString(*pInt++).c_str(); - faceNode.append_attribute("v3") = StringConverter::toString(*pInt++).c_str(); - } - } - else - { - faceNode.append_attribute("v1") = StringConverter::toString(*pShort++).c_str(); - if(s->operationType == RenderOperation::OT_LINE_LIST) - { - faceNode.append_attribute("v2") = StringConverter::toString(*pShort++).c_str(); - } - /// Only need all 3 vertex indices if trilist or first face - else if (s->operationType == RenderOperation::OT_TRIANGLE_LIST || i == 0) - { - faceNode.append_attribute("v2") = StringConverter::toString(*pShort++).c_str(); - faceNode.append_attribute("v3") = StringConverter::toString(*pShort++).c_str(); - } - } - } - ibuf->unlock(); - } - - // M_GEOMETRY chunk (Optional: present only if useSharedVertices = false) - if (!s->useSharedVertices) - { - pugi::xml_node geomNode = subMeshNode.append_child("geometry"); - writeGeometry(geomNode, s->vertexData); - } - - // Bone assignments - if (mMesh->hasSkeleton()) - { - LogManager::getSingleton().logMessage("Exporting dedicated geometry bone assignments..."); - - pugi::xml_node boneAssignNode = subMeshNode.append_child("boneassignments"); - for (const auto& e : s->getBoneAssignments()) - { - writeBoneAssignment(boneAssignNode, &e.second); - } - } - LogManager::getSingleton().logMessage("Dedicated geometry bone assignments exported."); - - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::writeGeometry(pugi::xml_node& mParentNode, const VertexData* vertexData) - { - // Write a vertex buffer per element - - pugi::xml_node vbNode, vertexNode, dataNode; - - // Set num verts on parent - mParentNode.append_attribute("vertexcount") = StringConverter::toString(vertexData->vertexCount).c_str(); - - VertexDeclaration* decl = vertexData->vertexDeclaration; - VertexBufferBinding* bind = vertexData->vertexBufferBinding; - - VertexBufferBinding::VertexBufferBindingMap::const_iterator b, bend; - bend = bind->getBindings().end(); - // Iterate over buffers - for(b = bind->getBindings().begin(); b != bend; ++b) - { - vbNode = mParentNode.append_child("vertexbuffer"); - const HardwareVertexBufferSharedPtr vbuf = b->second; - unsigned short bufferIdx = b->first; - // Get all the elements that relate to this buffer - VertexDeclaration::VertexElementList elems = decl->findElementsBySource(bufferIdx); - VertexDeclaration::VertexElementList::iterator i, iend; - iend = elems.end(); - - // Set up the data access for this buffer (lock read-only) - unsigned char* pVert; - float* pFloat; - uint16* pShort; - uint8* pChar; - ABGR* pColour; - - pVert = static_cast( - vbuf->lock(HardwareBuffer::HBL_READ_ONLY)); - - // Skim over the elements to set up the general data - unsigned short numTextureCoords = 0; - for (i = elems.begin(); i != iend; ++i) - { - VertexElement& elem = *i; - switch(elem.getSemantic()) - { - case VES_POSITION: - vbNode.append_attribute("positions") = "true"; - break; - case VES_NORMAL: - vbNode.append_attribute("normals") = "true"; - break; - case VES_TANGENT: - vbNode.append_attribute("tangents") = "true"; - if (elem.getType() == VET_FLOAT4) - { - vbNode.append_attribute("tangent_dimensions") = "4"; - } - break; - case VES_BINORMAL: - vbNode.append_attribute("binormals") = "true"; - break; - case VES_DIFFUSE: - vbNode.append_attribute("colours_diffuse") = "true"; - break; - case VES_SPECULAR: - vbNode.append_attribute("colours_specular") = "true"; - break; - case VES_TEXTURE_COORDINATES: - { - const char *type = "float2"; - switch (elem.getType()) - { - case VET_FLOAT1: - type = "float1"; - break; - case VET_FLOAT2: - type = "float2"; - break; - case VET_FLOAT3: - type = "float3"; - break; - case VET_FLOAT4: - type = "float4"; - break; - case VET_UBYTE4_NORM: - type = "colour"; - break; - case VET_SHORT1: - type = "short1"; - break; - case VET_SHORT2: - type = "short2"; - break; - case VET_SHORT3: - type = "short3"; - break; - case VET_SHORT4: - type = "short4"; - break; - case VET_UBYTE4: - type = "ubyte4"; - break; - default: - OgreAssert(false, "Unsupported VET"); - break; - } - vbNode.append_attribute( - ("texture_coord_dimensions_" + StringConverter::toString(numTextureCoords)).c_str()) = type; - ++numTextureCoords; - } - break; - - default: - break; - } - } - if (numTextureCoords > 0) - { - vbNode.append_attribute("texture_coords") = - StringConverter::toString(numTextureCoords).c_str(); - } - - // For each vertex - for (size_t v = 0; v < vertexData->vertexCount; ++v) - { - vertexNode = vbNode.append_child("vertex"); - // Iterate over the elements - for (i = elems.begin(); i != iend; ++i) - { - VertexElement& elem = *i; - switch(elem.getSemantic()) - { - case VES_POSITION: - elem.baseVertexPointerToElement(pVert, &pFloat); - dataNode = vertexNode.append_child("position"); - dataNode.append_attribute("x") = StringConverter::toString(pFloat[0]).c_str(); - dataNode.append_attribute("y") = StringConverter::toString(pFloat[1]).c_str(); - dataNode.append_attribute("z") = StringConverter::toString(pFloat[2]).c_str(); - break; - case VES_NORMAL: - elem.baseVertexPointerToElement(pVert, &pFloat); - dataNode = vertexNode.append_child("normal"); - dataNode.append_attribute("x") = StringConverter::toString(pFloat[0]).c_str(); - dataNode.append_attribute("y") = StringConverter::toString(pFloat[1]).c_str(); - dataNode.append_attribute("z") = StringConverter::toString(pFloat[2]).c_str(); - break; - case VES_TANGENT: - elem.baseVertexPointerToElement(pVert, &pFloat); - dataNode = vertexNode.append_child("tangent"); - dataNode.append_attribute("x") = StringConverter::toString(pFloat[0]).c_str(); - dataNode.append_attribute("y") = StringConverter::toString(pFloat[1]).c_str(); - dataNode.append_attribute("z") = StringConverter::toString(pFloat[2]).c_str(); - if (elem.getType() == VET_FLOAT4) - { - dataNode.append_attribute("w") = StringConverter::toString(pFloat[3]).c_str(); - } - break; - case VES_BINORMAL: - elem.baseVertexPointerToElement(pVert, &pFloat); - dataNode = vertexNode.append_child("binormal"); - dataNode.append_attribute("x") = StringConverter::toString(pFloat[0]).c_str(); - dataNode.append_attribute("y") = StringConverter::toString(pFloat[1]).c_str(); - dataNode.append_attribute("z") = StringConverter::toString(pFloat[2]).c_str(); - break; - case VES_DIFFUSE: - elem.baseVertexPointerToElement(pVert, &pColour); - dataNode = vertexNode.append_child("colour_diffuse"); - { - ColourValue cv; - elem.getType() == VET_COLOUR_ABGR ? cv.setAsABGR(*pColour) : cv.setAsARGB(*pColour); - dataNode.append_attribute("value") = StringConverter::toString(cv).c_str(); - } - break; - case VES_SPECULAR: - elem.baseVertexPointerToElement(pVert, &pColour); - dataNode = vertexNode.append_child("colour_specular"); - { - ColourValue cv; - elem.getType() == VET_COLOUR_ABGR ? cv.setAsABGR(*pColour) : cv.setAsARGB(*pColour); - dataNode.append_attribute("value") = StringConverter::toString(cv).c_str(); - } - break; - case VES_TEXTURE_COORDINATES: - dataNode = vertexNode.append_child("texcoord"); - - switch(elem.getType()) - { - case VET_FLOAT1: - elem.baseVertexPointerToElement(pVert, &pFloat); - dataNode.append_attribute("u") = StringConverter::toString(*pFloat++).c_str(); - break; - case VET_FLOAT2: - elem.baseVertexPointerToElement(pVert, &pFloat); - dataNode.append_attribute("u") = StringConverter::toString(*pFloat++).c_str(); - dataNode.append_attribute("v") = StringConverter::toString(*pFloat++).c_str(); - break; - case VET_FLOAT3: - elem.baseVertexPointerToElement(pVert, &pFloat); - dataNode.append_attribute("u") = StringConverter::toString(*pFloat++).c_str(); - dataNode.append_attribute("v") = StringConverter::toString(*pFloat++).c_str(); - dataNode.append_attribute("w") = StringConverter::toString(*pFloat++).c_str(); - break; - case VET_FLOAT4: - elem.baseVertexPointerToElement(pVert, &pFloat); - dataNode.append_attribute("u") = StringConverter::toString(*pFloat++).c_str(); - dataNode.append_attribute("v") = StringConverter::toString(*pFloat++).c_str(); - dataNode.append_attribute("w") = StringConverter::toString(*pFloat++).c_str(); - dataNode.append_attribute("x") = StringConverter::toString(*pFloat++).c_str(); - break; - case VET_SHORT1: - elem.baseVertexPointerToElement(pVert, &pShort); - dataNode.append_attribute("u") = StringConverter::toString(*pShort++ / 65535.0f).c_str(); - break; - case VET_SHORT2: - elem.baseVertexPointerToElement(pVert, &pShort); - dataNode.append_attribute("u") = StringConverter::toString(*pShort++ / 65535.0f).c_str(); - dataNode.append_attribute("v") = StringConverter::toString(*pShort++ / 65535.0f).c_str(); - break; - case VET_SHORT3: - elem.baseVertexPointerToElement(pVert, &pShort); - dataNode.append_attribute("u") = StringConverter::toString(*pShort++ / 65535.0f).c_str(); - dataNode.append_attribute("v") = StringConverter::toString(*pShort++ / 65535.0f).c_str(); - dataNode.append_attribute("w") = StringConverter::toString(*pShort++ / 65535.0f).c_str(); - break; - case VET_SHORT4: - elem.baseVertexPointerToElement(pVert, &pShort); - dataNode.append_attribute("u") = StringConverter::toString(*pShort++ / 65535.0f).c_str(); - dataNode.append_attribute("v") = StringConverter::toString(*pShort++ / 65535.0f).c_str(); - dataNode.append_attribute("w") = StringConverter::toString(*pShort++ / 65535.0f).c_str(); - dataNode.append_attribute("x") = StringConverter::toString(*pShort++ / 65535.0f).c_str(); - break; - case VET_UBYTE4_NORM: - elem.baseVertexPointerToElement(pVert, &pColour); - { - ColourValue cv; - elem.getType() == VET_COLOUR_ARGB ? cv.setAsARGB(*pColour) : cv.setAsABGR(*pColour); - dataNode.append_attribute("u") = StringConverter::toString(cv).c_str(); - } - break; - case VET_UBYTE4: - elem.baseVertexPointerToElement(pVert, &pChar); - dataNode.append_attribute("u") = StringConverter::toString(*pChar++ / 255.0f).c_str(); - dataNode.append_attribute("v") = StringConverter::toString(*pChar++ / 255.0f).c_str(); - dataNode.append_attribute("w") = StringConverter::toString(*pChar++ / 255.0f).c_str(); - dataNode.append_attribute("x") = StringConverter::toString(*pChar++ / 255.0f).c_str(); - break; - default: - OgreAssert(false, "Unsupported VET"); - break; - } - break; - default: - break; - - } - } - pVert += vbuf->getVertexSize(); - } - vbuf->unlock(); - } - - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::writeSkeletonLink(pugi::xml_node& mMeshNode, const String& skelName) - { - - pugi::xml_node skelNode = mMeshNode.append_child("skeletonlink"); - skelNode.append_attribute("name") = skelName.c_str(); - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::writeBoneAssignment(pugi::xml_node& mBoneAssignNode, const VertexBoneAssignment* assign) - { - pugi::xml_node assignNode = mBoneAssignNode.append_child("vertexboneassignment"); - - assignNode.append_attribute("vertexindex") = - StringConverter::toString(assign->vertexIndex).c_str(); - assignNode.append_attribute("boneindex") = - StringConverter::toString(assign->boneIndex).c_str(); - assignNode.append_attribute("weight" ) = - StringConverter::toString(assign->weight).c_str(); - - - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::readSubMeshes(pugi::xml_node& mSubmeshesNode) - { - LogManager::getSingleton().logMessage("Reading submeshes..."); - assert(mMesh->getNumSubMeshes() == 0); - for (pugi::xml_node& smElem : mSubmeshesNode.children()) - { - // All children should be submeshes - SubMesh* sm = mMesh->createSubMesh(); - - const char* mat = smElem.attribute("material").as_string(NULL); - if (mat && mat[0] != '\0') - { - // we do not load any materials - so create a dummy here to just store the name - sm->setMaterial(MaterialManager::getSingleton().create(mat, RGN_DEFAULT)); - } - else - { - LogManager::getSingleton().logError( - "empty material name encountered. This violates the specs and can lead to crashes."); - } - - // Read operation type - bool readFaces = true; - const char* optype = smElem.attribute("operationtype").as_string(NULL); - if (optype) - { - if (!strcmp(optype, "triangle_list")) - { - sm->operationType = RenderOperation::OT_TRIANGLE_LIST; - } - else if (!strcmp(optype, "triangle_fan")) - { - sm->operationType = RenderOperation::OT_TRIANGLE_FAN; - } - else if (!strcmp(optype, "triangle_strip")) - { - sm->operationType = RenderOperation::OT_TRIANGLE_STRIP; - } - else if (!strcmp(optype, "line_strip")) - { - sm->operationType = RenderOperation::OT_LINE_STRIP; - readFaces = false; - } - else if (!strcmp(optype, "line_list")) - { - sm->operationType = RenderOperation::OT_LINE_LIST; - readFaces = false; - } - else if (!strcmp(optype, "point_list")) - { - sm->operationType = RenderOperation::OT_POINT_LIST; - readFaces = false; - } - else if (!strcmp(optype, "triangle_list_adj")) - { - sm->operationType = RenderOperation::OT_TRIANGLE_LIST_ADJ; - } - else if (!strcmp(optype, "triangle_strip_adj")) - { - sm->operationType = RenderOperation::OT_TRIANGLE_STRIP_ADJ; - } - else if (!strcmp(optype, "line_strip_adj")) - { - sm->operationType = RenderOperation::OT_LINE_STRIP_ADJ; - readFaces = false; - } - else if (!strcmp(optype, "line_list_adj")) - { - sm->operationType = RenderOperation::OT_LINE_LIST_ADJ; - readFaces = false; - } - } - - sm->useSharedVertices = StringConverter::parseBool(smElem.attribute("usesharedvertices").value()); - bool use32BitIndexes = StringConverter::parseBool(smElem.attribute("use32bitindexes").value()); - - // Faces - if (readFaces) - { - pugi::xml_node faces = smElem.child("faces"); - int actualCount = std::distance(faces.begin(), faces.end()); - const char *claimedCount_ = faces.attribute("count").value(); - if (StringConverter::parseInt(claimedCount_)!=actualCount) - { - LogManager::getSingleton().stream(LML_WARNING) - << "WARNING: face count (" << actualCount << ") " << - "is not as claimed (" << claimedCount_ << ")"; - } - - - if (actualCount > 0) - { - // Faces - switch(sm->operationType) - { - case RenderOperation::OT_TRIANGLE_LIST: - // tri list - sm->indexData->indexCount = actualCount * 3; - - break; - case RenderOperation::OT_LINE_LIST: - sm->indexData->indexCount = actualCount * 2; - - break; - case RenderOperation::OT_TRIANGLE_FAN: - case RenderOperation::OT_TRIANGLE_STRIP: - // triangle fan or triangle strip - sm->indexData->indexCount = actualCount + 2; - - break; - default: - OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, - "operationType not implemented"); - } - - // Allocate space - HardwareIndexBufferSharedPtr ibuf = HardwareBufferManager::getSingleton(). - createIndexBuffer( - use32BitIndexes? HardwareIndexBuffer::IT_32BIT : HardwareIndexBuffer::IT_16BIT, - sm->indexData->indexCount, - HardwareBuffer::HBU_DYNAMIC, - false); - sm->indexData->indexBuffer = ibuf; - unsigned int *pInt = 0; - unsigned short *pShort = 0; - if (use32BitIndexes) - { - pInt = static_cast( - ibuf->lock(HardwareBuffer::HBL_DISCARD)); - } - else - { - pShort = static_cast( - ibuf->lock(HardwareBuffer::HBL_DISCARD)); - } - - bool firstTri = true; - for (auto faceElem : faces.children()) - { - if (use32BitIndexes) - { - *pInt++ = StringConverter::parseInt(faceElem.attribute("v1").value()); - if(sm->operationType == RenderOperation::OT_LINE_LIST) - { - *pInt++ = StringConverter::parseInt(faceElem.attribute("v2").value()); - } - // only need all 3 vertices if it's a trilist or first tri - else if (sm->operationType == RenderOperation::OT_TRIANGLE_LIST || firstTri) - { - *pInt++ = StringConverter::parseInt(faceElem.attribute("v2").value()); - *pInt++ = StringConverter::parseInt(faceElem.attribute("v3").value()); - } - } - else - { - *pShort++ = StringConverter::parseInt(faceElem.attribute("v1").value()); - if(sm->operationType == RenderOperation::OT_LINE_LIST) - { - *pShort++ = StringConverter::parseInt(faceElem.attribute("v2").value()); - } - // only need all 3 vertices if it's a trilist or first tri - else if (sm->operationType == RenderOperation::OT_TRIANGLE_LIST || firstTri) - { - *pShort++ = StringConverter::parseInt(faceElem.attribute("v2").value()); - *pShort++ = StringConverter::parseInt(faceElem.attribute("v3").value()); - } - } - firstTri = false; - } - ibuf->unlock(); - } - } - - // Geometry - if (!sm->useSharedVertices) - { - pugi::xml_node geomNode = smElem.child("geometry"); - if (geomNode) - { - sm->createVertexData(); - readGeometry(geomNode, sm->vertexData); - } - } - - // Bone assignments - pugi::xml_node boneAssigns = smElem.child("boneassignments"); - if(boneAssigns) - readBoneAssignments(boneAssigns, sm); - - } - LogManager::getSingleton().logMessage("Submeshes done."); - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::readGeometry(pugi::xml_node& mGeometryNode, VertexData* vertexData) - { - LogManager::getSingleton().logMessage("Reading geometry..."); - unsigned char *pVert; - float *pFloat; - uint16 *pShort; - uint8 *pChar; - ARGB *pCol; - - ptrdiff_t claimedVertexCount = - StringConverter::parseInt(mGeometryNode.attribute("vertexcount").value()); - - // Skip empty - if (claimedVertexCount <= 0) return; - - - VertexDeclaration* decl = vertexData->vertexDeclaration; - VertexBufferBinding* bind = vertexData->vertexBufferBinding; - unsigned short bufCount = 0; - unsigned short totalTexCoords = 0; // across all buffers - - // Information for calculating bounds - Vector3 min = Vector3::ZERO, max = Vector3::UNIT_SCALE, pos = Vector3::ZERO; - Real maxSquaredRadius = -1; - bool first = true; - - // Iterate over all children (vertexbuffer entries) - for (pugi::xml_node& vbElem : mGeometryNode.children("vertexbuffer")) - { - size_t offset = 0; - if (StringConverter::parseBool(vbElem.attribute("positions").value())) - { - offset += decl->addElement(bufCount, offset, VET_FLOAT3, VES_POSITION).getSize(); - } - if (StringConverter::parseBool(vbElem.attribute("normals").value())) - { - offset += decl->addElement(bufCount, offset, VET_FLOAT3, VES_NORMAL).getSize(); - } - if (StringConverter::parseBool(vbElem.attribute("tangents").value())) - { - VertexElementType tangentType = VET_FLOAT3; - unsigned int dims = StringConverter::parseUnsignedInt(vbElem.attribute("tangent_dimensions").value()); - if (dims == 4) - tangentType = VET_FLOAT4; - - offset += decl->addElement(bufCount, offset, tangentType, VES_TANGENT).getSize(); - } - if (StringConverter::parseBool(vbElem.attribute("binormals").value())) - { - offset += decl->addElement(bufCount, offset, VET_FLOAT3, VES_BINORMAL).getSize(); - } - if (StringConverter::parseBool(vbElem.attribute("colours_diffuse").value())) - { - offset += decl->addElement(bufCount, offset, mColourElementType, VES_DIFFUSE).getSize(); - } - if (StringConverter::parseBool(vbElem.attribute("colours_specular").value())) - { - // Add element - offset += decl->addElement(bufCount, offset, mColourElementType, VES_SPECULAR).getSize(); - } - if (StringConverter::parseInt(vbElem.attribute("texture_coords").value())) - { - unsigned short numTexCoords = StringConverter::parseInt(vbElem.attribute("texture_coords").value()); - for (unsigned short tx = 0; tx < numTexCoords; ++tx) - { - // NB set is local to this buffer, but will be translated into a - // global set number across all vertex buffers - StringStream str; - str << "texture_coord_dimensions_" << tx; - auto attrib = vbElem.attribute(str.str().c_str()).as_string(NULL); - VertexElementType vtype = VET_FLOAT2; // Default - if (attrib) - { - if (!::strcmp(attrib,"1")) - vtype = VET_FLOAT1; - else if (!::strcmp(attrib,"2")) - vtype = VET_FLOAT2; - else if (!::strcmp(attrib,"3")) - vtype = VET_FLOAT3; - else if (!::strcmp(attrib,"4")) - vtype = VET_FLOAT4; - else if (!::strcmp(attrib,"float1")) - vtype = VET_FLOAT1; - else if (!::strcmp(attrib,"float2")) - vtype = VET_FLOAT2; - else if (!::strcmp(attrib,"float3")) - vtype = VET_FLOAT3; - else if (!::strcmp(attrib,"float4")) - vtype = VET_FLOAT4; - else if (!::strcmp(attrib,"short1")) - vtype = VET_SHORT1; - else if (!::strcmp(attrib,"short2")) - vtype = VET_SHORT2; - else if (!::strcmp(attrib,"short3")) - vtype = VET_SHORT3; - else if (!::strcmp(attrib,"short4")) - vtype = VET_SHORT4; - else if (!::strcmp(attrib,"ubyte4")) - vtype = VET_UBYTE4; - else if (!::strcmp(attrib,"colour")) - vtype = VET_UBYTE4_NORM; - else if (!::strcmp(attrib,"colour_argb")) - vtype = _DETAIL_SWAP_RB; - else if (!::strcmp(attrib,"colour_abgr")) - vtype = VET_UBYTE4_NORM; - else - { - auto err = LogManager::getSingleton().stream(LML_CRITICAL); - err << "Did not recognise texture_coord_dimensions value of \""<addElement(bufCount, offset, vtype, - VES_TEXTURE_COORDINATES, totalTexCoords++).getSize(); - } - } - - // calculate how many vertexes there actually are - int actualVertexCount = std::distance(vbElem.begin(), vbElem.end()); - if (actualVertexCount!=claimedVertexCount) - { - LogManager::getSingleton().stream(LML_WARNING) - << "WARNING: vertex count (" << actualVertexCount - << ") is not as claimed (" << claimedVertexCount << ")"; - } - - vertexData->vertexCount = actualVertexCount; - // Now create the vertex buffer - HardwareVertexBufferSharedPtr vbuf = HardwareBufferManager::getSingleton(). - createVertexBuffer(offset, vertexData->vertexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY, false); - // Bind it - bind->setBinding(bufCount, vbuf); - // Lock it - pVert = static_cast( - vbuf->lock(HardwareBuffer::HBL_DISCARD)); - - // Get the element list for this buffer alone - VertexDeclaration::VertexElementList elems = decl->findElementsBySource(bufCount); - // Now the buffer is set up, parse all the vertices - for (pugi::xml_node& vertexElem : vbElem.children()) - { - // Now parse the elements, ensure they are all matched - VertexDeclaration::VertexElementList::const_iterator ielem, ielemend; - pugi::xml_node xmlElem; - pugi::xml_node texCoordElem; - ielemend = elems.end(); - for (ielem = elems.begin(); ielem != ielemend; ++ielem) - { - const VertexElement& elem = *ielem; - // Find child for this element - switch(elem.getSemantic()) - { - case VES_POSITION: - xmlElem = vertexElem.child("position"); - if (!xmlElem) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Missing element.", - "XMLSerializer::readGeometry"); - } - elem.baseVertexPointerToElement(pVert, &pFloat); - - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("x").value()); - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("y").value()); - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("z").value()); - - pos.x = StringConverter::parseReal(xmlElem.attribute("x").value()); - pos.y = StringConverter::parseReal(xmlElem.attribute("y").value()); - pos.z = StringConverter::parseReal(xmlElem.attribute("z").value()); - - if (first) - { - min = max = pos; - maxSquaredRadius = pos.squaredLength(); - first = false; - } - else - { - min.makeFloor(pos); - max.makeCeil(pos); - maxSquaredRadius = std::max(pos.squaredLength(), maxSquaredRadius); - } - break; - case VES_NORMAL: - xmlElem = vertexElem.child("normal"); - if (!xmlElem) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Missing element.", - "XMLSerializer::readGeometry"); - } - elem.baseVertexPointerToElement(pVert, &pFloat); - - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("x").value()); - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("y").value()); - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("z").value()); - break; - case VES_TANGENT: - xmlElem = vertexElem.child("tangent"); - if (!xmlElem) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Missing element.", - "XMLSerializer::readGeometry"); - } - elem.baseVertexPointerToElement(pVert, &pFloat); - - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("x").value()); - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("y").value()); - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("z").value()); - if (elem.getType() == VET_FLOAT4) - { - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("w").value()); - } - break; - case VES_BINORMAL: - xmlElem = vertexElem.child("binormal"); - if (!xmlElem) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Missing element.", - "XMLSerializer::readGeometry"); - } - elem.baseVertexPointerToElement(pVert, &pFloat); - - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("x").value()); - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("y").value()); - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("z").value()); - break; - case VES_DIFFUSE: - xmlElem = vertexElem.child("colour_diffuse"); - if (!xmlElem) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Missing element.", - "XMLSerializer::readGeometry"); - } - elem.baseVertexPointerToElement(pVert, &pCol); - { - auto cv = StringConverter::parseColourValue(xmlElem.attribute("value").value()); - *pCol++ = cv.getAsABGR(); - } - break; - case VES_SPECULAR: - xmlElem = vertexElem.child("colour_specular"); - if (!xmlElem) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Missing element.", - "XMLSerializer::readGeometry"); - } - elem.baseVertexPointerToElement(pVert, &pCol); - { - auto cv = StringConverter::parseColourValue(xmlElem.attribute("value").value()); - *pCol++ = cv.getAsABGR(); - } - break; - case VES_TEXTURE_COORDINATES: - if (!texCoordElem) - { - // Get first texcoord - xmlElem = vertexElem.child("texcoord"); - } - else - { - // Get next texcoord - xmlElem = texCoordElem.next_sibling("texcoord"); - } - if (!xmlElem) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Missing element.", - "XMLSerializer::readGeometry"); - } - // Record the latest texture coord entry - texCoordElem = xmlElem; - - if (!xmlElem.attribute("u")) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Texcoord 'u' attribute not found.", "XMLMeshSerializer::readGeometry"); - - // depending on type, pack appropriately, can process colour channels separately which is a bonus - switch (elem.getType()) - { - case VET_FLOAT1: - elem.baseVertexPointerToElement(pVert, &pFloat); - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("u").value()); - break; - - case VET_FLOAT2: - if (!xmlElem.attribute("v")) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Texcoord 'v' attribute not found.", "XMLMeshSerializer::readGeometry"); - elem.baseVertexPointerToElement(pVert, &pFloat); - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("u").value()); - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("v").value()); - break; - - case VET_FLOAT3: - if (!xmlElem.attribute("v")) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Texcoord 'v' attribute not found.", "XMLMeshSerializer::readGeometry"); - if (!xmlElem.attribute("w")) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Texcoord 'w' attribute not found.", "XMLMeshSerializer::readGeometry"); - elem.baseVertexPointerToElement(pVert, &pFloat); - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("u").value()); - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("v").value()); - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("w").value()); - break; - - case VET_FLOAT4: - if (!xmlElem.attribute("v")) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Texcoord 'v' attribute not found.", "XMLMeshSerializer::readGeometry"); - if (!xmlElem.attribute("w")) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Texcoord 'w' attribute not found.", "XMLMeshSerializer::readGeometry"); - if (!xmlElem.attribute("x")) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Texcoord 'x' attribute not found.", "XMLMeshSerializer::readGeometry"); - elem.baseVertexPointerToElement(pVert, &pFloat); - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("u").value()); - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("v").value()); - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("w").value()); - *pFloat++ = StringConverter::parseReal(xmlElem.attribute("x").value()); - break; - - case VET_SHORT1: - elem.baseVertexPointerToElement(pVert, &pShort); - *pShort++ = static_cast(65535.0f * StringConverter::parseReal(xmlElem.attribute("u").value())); - break; - - case VET_SHORT2: - if (!xmlElem.attribute("v")) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Texcoord 'v' attribute not found.", "XMLMeshSerializer::readGeometry"); - elem.baseVertexPointerToElement(pVert, &pShort); - *pShort++ = static_cast(65535.0f * StringConverter::parseReal(xmlElem.attribute("u").value())); - *pShort++ = static_cast(65535.0f * StringConverter::parseReal(xmlElem.attribute("v").value())); - break; - - case VET_SHORT3: - if (!xmlElem.attribute("v")) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Texcoord 'v' attribute not found.", "XMLMeshSerializer::readGeometry"); - if (!xmlElem.attribute("w")) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Texcoord 'w' attribute not found.", "XMLMeshSerializer::readGeometry"); - elem.baseVertexPointerToElement(pVert, &pShort); - *pShort++ = static_cast(65535.0f * StringConverter::parseReal(xmlElem.attribute("u").value())); - *pShort++ = static_cast(65535.0f * StringConverter::parseReal(xmlElem.attribute("v").value())); - *pShort++ = static_cast(65535.0f * StringConverter::parseReal(xmlElem.attribute("w").value())); - break; - - case VET_SHORT4: - if (!xmlElem.attribute("v")) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Texcoord 'v' attribute not found.", "XMLMeshSerializer::readGeometry"); - if (!xmlElem.attribute("w")) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Texcoord 'w' attribute not found.", "XMLMeshSerializer::readGeometry"); - if (!xmlElem.attribute("x")) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Texcoord 'x' attribute not found.", "XMLMeshSerializer::readGeometry"); - elem.baseVertexPointerToElement(pVert, &pShort); - *pShort++ = static_cast(65535.0f * StringConverter::parseReal(xmlElem.attribute("u").value())); - *pShort++ = static_cast(65535.0f * StringConverter::parseReal(xmlElem.attribute("v").value())); - *pShort++ = static_cast(65535.0f * StringConverter::parseReal(xmlElem.attribute("w").value())); - *pShort++ = static_cast(65535.0f * StringConverter::parseReal(xmlElem.attribute("x").value())); - break; - - case VET_UBYTE4: - if (!xmlElem.attribute("v")) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Texcoord 'v' attribute not found.", "XMLMeshSerializer::readGeometry"); - if (!xmlElem.attribute("w")) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Texcoord 'w' attribute not found.", "XMLMeshSerializer::readGeometry"); - if (!xmlElem.attribute("x")) - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Texcoord 'x' attribute not found.", "XMLMeshSerializer::readGeometry"); - elem.baseVertexPointerToElement(pVert, &pChar); - // round off instead of just truncating -- avoids magnifying rounding errors - *pChar++ = static_cast(0.5f + 255.0f * StringConverter::parseReal(xmlElem.attribute("u").value())); - *pChar++ = static_cast(0.5f + 255.0f * StringConverter::parseReal(xmlElem.attribute("v").value())); - *pChar++ = static_cast(0.5f + 255.0f * StringConverter::parseReal(xmlElem.attribute("w").value())); - *pChar++ = static_cast(0.5f + 255.0f * StringConverter::parseReal(xmlElem.attribute("x").value())); - break; - - case VET_UBYTE4_NORM: - { - elem.baseVertexPointerToElement(pVert, &pCol); - ColourValue cv = StringConverter::parseColourValue(xmlElem.attribute("u").value()); - *pCol++ = cv.getAsABGR(); - } - break; - default: - OgreAssert(false, "Unsupported VET"); - break; - } - - break; - default: - break; - } - } // semantic - pVert += vbuf->getVertexSize(); - } // vertex - bufCount++; - vbuf->unlock(); - } // vertexbuffer - - // Set bounds - const AxisAlignedBox& currBox = mMesh->getBounds(); - Real currRadius = mMesh->getBoundingSphereRadius(); - if (currBox.isNull()) - { - //do not pad the bounding box - mMesh->_setBounds(AxisAlignedBox(min, max), false); - mMesh->_setBoundingSphereRadius(Math::Sqrt(maxSquaredRadius)); - } - else - { - AxisAlignedBox newBox(min, max); - newBox.merge(currBox); - //do not pad the bounding box - mMesh->_setBounds(newBox, false); - mMesh->_setBoundingSphereRadius(std::max(Math::Sqrt(maxSquaredRadius), currRadius)); - } - - - LogManager::getSingleton().logMessage("Geometry done..."); - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::readSkeletonLink(pugi::xml_node& mSkelNode) - { - String name = mSkelNode.attribute("name").value(); - // create dummy, because we do not load external resources - auto skel = SkeletonManager::getSingleton().create(name, mMesh->getGroup()); - mMesh->_notifySkeleton(skel); - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::readBoneAssignments(pugi::xml_node& mBoneAssignmentsNode) - { - LogManager::getSingleton().logMessage("Reading bone assignments..."); - - // Iterate over all children (vertexboneassignment entries) - for (pugi::xml_node& elem : mBoneAssignmentsNode.children()) - { - VertexBoneAssignment vba; - vba.vertexIndex = StringConverter::parseInt(elem.attribute("vertexindex").value()); - vba.boneIndex = StringConverter::parseInt(elem.attribute("boneindex").value()); - vba.weight = StringConverter::parseReal(elem.attribute("weight").value()); - - mMesh->addBoneAssignment(vba); - } - - LogManager::getSingleton().logMessage("Bone assignments done."); - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::readSubMeshNames(pugi::xml_node& mMeshNamesNode, Mesh *sm) - { - LogManager::getSingleton().logMessage("Reading mesh names..."); - - // Iterate over all children (vertexboneassignment entries) - for (pugi::xml_node& elem : mMeshNamesNode.children()) - { - String meshName = elem.attribute("name").value(); - int index = StringConverter::parseInt(elem.attribute("index").value()); - - sm->nameSubMesh(meshName, index); - } - - LogManager::getSingleton().logMessage("Mesh names done."); - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::readBoneAssignments(pugi::xml_node& mBoneAssignmentsNode, SubMesh* sm) - { - LogManager::getSingleton().logMessage("Reading bone assignments..."); - // Iterate over all children (vertexboneassignment entries) - for (pugi::xml_node& elem : mBoneAssignmentsNode.children()) - { - VertexBoneAssignment vba; - vba.vertexIndex = StringConverter::parseInt(elem.attribute("vertexindex").value()); - vba.boneIndex = StringConverter::parseInt(elem.attribute("boneindex").value()); - vba.weight = StringConverter::parseReal(elem.attribute("weight").value()); - - sm->addBoneAssignment(vba); - } - LogManager::getSingleton().logMessage("Bone assignments done."); - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::writeLodInfo(pugi::xml_node& mMeshNode, const Mesh* pMesh) - { - pugi::xml_node lodNode = mMeshNode.append_child("levelofdetail"); - - const LodStrategy *strategy = pMesh->getLodStrategy(); - unsigned short numLvls = pMesh->getNumLodLevels(); - bool manual = pMesh->hasManualLodLevel(); - lodNode.append_attribute("strategy") = strategy->getName().c_str(); - lodNode.append_attribute("numlevels") = StringConverter::toString(numLvls).c_str(); - lodNode.append_attribute("manual") = StringConverter::toString(manual).c_str(); - - // Iterate from level 1, not 0 (full detail) - for (unsigned short i = 1; i < numLvls; ++i) - { - const MeshLodUsage& usage = pMesh->getLodLevel(i); - if (pMesh->_isManualLodLevel(i)) - { - writeLodUsageManual(lodNode, i, usage); - } - else - { - writeLodUsageGenerated(lodNode, i, usage, pMesh); - } - } - - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::writeSubMeshNames(pugi::xml_node& mMeshNode, const Mesh* m) - { - const Mesh::SubMeshNameMap& nameMap = m->getSubMeshNameMap(); - if (nameMap.empty()) - return; // do nothing - - pugi::xml_node namesNode = mMeshNode.append_child("submeshnames"); - Mesh::SubMeshNameMap::const_iterator i, iend; - iend = nameMap.end(); - for (i = nameMap.begin(); i != iend; ++i) - { - pugi::xml_node subNameNode = namesNode.append_child("submeshname"); - - subNameNode.append_attribute("name") = i->first.c_str(); - subNameNode.append_attribute("index") = - StringConverter::toString(i->second).c_str(); - } - - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::writeLodUsageManual(pugi::xml_node& usageNode, - unsigned short levelNum, const MeshLodUsage& usage) - { - pugi::xml_node manualNode = usageNode.append_child("lodmanual"); - - manualNode.append_attribute("value") = - StringConverter::toString(usage.userValue).c_str(); - manualNode.append_attribute("meshname") = usage.manualName.c_str(); - - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::writeLodUsageGenerated(pugi::xml_node& usageNode, - unsigned short levelNum, const MeshLodUsage& usage, - const Mesh* pMesh) - { - pugi::xml_node generatedNode = usageNode.append_child("lodgenerated"); - generatedNode.append_attribute("value") = - StringConverter::toString(usage.userValue).c_str(); - - // Iterate over submeshes at this level - size_t numsubs = pMesh->getNumSubMeshes(); - - for (size_t subi = 0; subi < numsubs; ++subi) - { - pugi::xml_node subNode = generatedNode.append_child("lodfacelist"); - SubMesh* sub = pMesh->getSubMesh(subi); - subNode.append_attribute("submeshindex") = StringConverter::toString(subi).c_str(); - // NB level - 1 because SubMeshes don't store the first index in geometry - IndexData* facedata = sub->mLodFaceList[levelNum - 1]; - subNode.append_attribute("numfaces") = StringConverter::toString(facedata->indexCount / 3).c_str(); - - if (facedata->indexCount > 0) - { - // Write each face in turn - bool use32BitIndexes = (facedata->indexBuffer->getType() == HardwareIndexBuffer::IT_32BIT); - - // Write each face in turn - unsigned int* pInt = 0; - unsigned short* pShort = 0; - HardwareIndexBufferSharedPtr ibuf = facedata->indexBuffer; - if (use32BitIndexes) - { - pInt = static_cast( - ibuf->lock(HardwareBuffer::HBL_READ_ONLY)); - pInt += facedata->indexStart; - } - else - { - pShort = static_cast( - ibuf->lock(HardwareBuffer::HBL_READ_ONLY)); - pShort += facedata->indexStart; - } - - for (size_t f = 0; f < facedata->indexCount; f += 3) - { - pugi::xml_node faceNode = - subNode.append_child("face"); - if (use32BitIndexes) - { - faceNode.append_attribute("v1") = StringConverter::toString(*pInt++).c_str(); - faceNode.append_attribute("v2") = StringConverter::toString(*pInt++).c_str(); - faceNode.append_attribute("v3") = StringConverter::toString(*pInt++).c_str(); - } - else - { - faceNode.append_attribute("v1") = StringConverter::toString(*pShort++).c_str(); - faceNode.append_attribute("v2") = StringConverter::toString(*pShort++).c_str(); - faceNode.append_attribute("v3") = StringConverter::toString(*pShort++).c_str(); - } - - } - - ibuf->unlock(); - } - - } - - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::writeExtremes(pugi::xml_node& mMeshNode, const Mesh* m) - { - pugi::xml_node extremesNode; - size_t submeshCount = m->getNumSubMeshes(); - for (size_t idx = 0; idx < submeshCount; ++idx) - { - SubMesh *sm = m->getSubMesh(idx); - if (sm->extremityPoints.empty()) - continue; // do nothing - - if (!extremesNode) - extremesNode = mMeshNode.append_child("extremes"); - - pugi::xml_node submeshNode = extremesNode.append_child("submesh_extremes"); - - submeshNode.append_attribute("index") = StringConverter::toString(idx).c_str(); - - for (auto extremityPoint : sm->extremityPoints) - { - pugi::xml_node vert = submeshNode.append_child("position"); - vert.append_attribute("x") = StringConverter::toString(extremityPoint.x).c_str(); - vert.append_attribute("y") = StringConverter::toString(extremityPoint.y).c_str(); - vert.append_attribute("z") = StringConverter::toString(extremityPoint.z).c_str(); - } - } - } -#if !OGRE_NO_MESHLOD - //--------------------------------------------------------------------- - void XMLMeshSerializer::readLodInfo(pugi::xml_node& lodNode) - { - - LogManager::getSingleton().logMessage("Parsing LOD information..."); - - const char* val = lodNode.attribute("strategy").as_string(NULL); - // This attribute is optional to maintain backwards compatibility - if (val) - { - String strategyName = val; - LodStrategy *strategy = LodStrategyManager::getSingleton().getStrategy(strategyName); - mMesh->setLodStrategy(strategy); - } - - val = lodNode.attribute("numlevels").value(); - unsigned short numLevels = static_cast( - StringConverter::parseUnsignedInt(val)); - - val = lodNode.attribute("manual").value(); - StringConverter::parseBool(val); - - // Set up the basic structures - mMesh->_setLodInfo(numLevels); - - // Parse the detail, start from 1 (the first sub-level of detail) - unsigned short i = 1; - for (auto usageElem : lodNode.children()) - { - if (usageElem.name() == String("lodmanual")) - { - readLodUsageManual(usageElem, i); - } - else if (usageElem.name() == String("lodgenerated")) - { - readLodUsageGenerated(usageElem, i); - } - ++i; - } - - LogManager::getSingleton().logMessage("LOD information done."); - - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::readLodUsageManual(pugi::xml_node& manualNode, unsigned short index) - { - MeshLodUsage usage; - const char* val = manualNode.attribute("value").as_string(NULL); - - // If value attribute not found check for old name - if (!val) - { - val = manualNode.attribute("fromdepthsquared").as_string(NULL); - if (val) - LogManager::getSingleton().logWarning("'fromdepthsquared' attribute has been renamed to 'value'."); - // user values are non-squared - usage.userValue = Math::Sqrt(StringConverter::parseReal(val)); - } - else - { - usage.userValue = StringConverter::parseReal(val); - } - usage.value = mMesh->getLodStrategy()->transformUserValue(usage.userValue); - usage.manualName = manualNode.attribute("meshname").value(); - usage.edgeData = NULL; - - // Generate for mixed - size_t numSubs, i; - numSubs = mMesh->getNumSubMeshes(); - for (i = 0; i < numSubs; ++i) - { - SubMesh* sm = mMesh->getSubMesh(i); - sm->mLodFaceList[index - 1] = OGRE_NEW IndexData(); - } - mMesh->_setLodUsage(index, usage); - } - //--------------------------------------------------------------------- - void XMLMeshSerializer::readLodUsageGenerated(pugi::xml_node& genNode, unsigned short index) - { - MeshLodUsage usage; - const char* val = genNode.attribute("value").as_string(NULL); - - // If value attribute not found check for old name - if (!val) - { - val = genNode.attribute("fromdepthsquared").value(); - if (val) - LogManager::getSingleton().logWarning("'fromdepthsquared' attribute has been renamed to 'value'."); - // user values are non-squared - usage.userValue = Math::Sqrt(StringConverter::parseReal(val)); - } - else - { - usage.userValue = StringConverter::parseReal(val); - } - usage.value = mMesh->getLodStrategy()->transformUserValue(usage.userValue); - usage.manualMesh.reset(); - usage.manualName = ""; - usage.edgeData = NULL; - - mMesh->_setLodUsage(index, usage); - - // Read submesh face lists - - HardwareIndexBufferSharedPtr ibuf; - for (pugi::xml_node faceListElem : genNode.children("lodfacelist")) - { - val = faceListElem.attribute("submeshindex").value(); - unsigned short subidx = StringConverter::parseUnsignedInt(val); - val = faceListElem.attribute("numfaces").value(); - unsigned short numFaces = StringConverter::parseUnsignedInt(val); - if (numFaces) - { - // use of 32bit indexes depends on submesh - HardwareIndexBuffer::IndexType itype = - mMesh->getSubMesh(subidx)->indexData->indexBuffer->getType(); - bool use32bitindexes = (itype == HardwareIndexBuffer::IT_32BIT); - - // Assign memory: this will be deleted by the submesh - ibuf = HardwareBufferManager::getSingleton(). - createIndexBuffer( - itype, numFaces * 3, HardwareBuffer::HBU_STATIC_WRITE_ONLY); - - unsigned short *pShort = 0; - unsigned int *pInt = 0; - if (use32bitindexes) - { - pInt = static_cast( - ibuf->lock(HardwareBuffer::HBL_DISCARD)); - } - else - { - pShort = static_cast( - ibuf->lock(HardwareBuffer::HBL_DISCARD)); - } - pugi::xml_node faceElem = faceListElem.child("face"); - for (unsigned int face = 0; face < numFaces; ++face, faceElem = faceElem.next_sibling()) - { - if (use32bitindexes) - { - val = faceElem.attribute("v1").value(); - *pInt++ = StringConverter::parseUnsignedInt(val); - val = faceElem.attribute("v2").value(); - *pInt++ = StringConverter::parseUnsignedInt(val); - val = faceElem.attribute("v3").value(); - *pInt++ = StringConverter::parseUnsignedInt(val); - } - else - { - val = faceElem.attribute("v1").value(); - *pShort++ = StringConverter::parseUnsignedInt(val); - val = faceElem.attribute("v2").value(); - *pShort++ = StringConverter::parseUnsignedInt(val); - val = faceElem.attribute("v3").value(); - *pShort++ = StringConverter::parseUnsignedInt(val); - } - - } - - ibuf->unlock(); - } - IndexData* facedata = new IndexData(); // will be deleted by SubMesh - facedata->indexCount = numFaces * 3; - facedata->indexStart = 0; - facedata->indexBuffer = ibuf; - mMesh->_setSubMeshLodFaceList(subidx, index, facedata); - } - - } -#endif - //----------------------------------------------------------------------------- - void XMLMeshSerializer::readExtremes(pugi::xml_node& extremesNode, Mesh *m) - { - LogManager::getSingleton().logMessage("Reading extremes..."); - - // Iterate over all children (submesh_extreme list) - for (pugi::xml_node& elem : extremesNode.children()) - { - int index = StringConverter::parseInt(elem.attribute("index").value()); - - SubMesh *sm = m->getSubMesh(index); - sm->extremityPoints.clear (); - for (pugi::xml_node& vert : elem.children()) - { - Vector3 v; - v.x = StringConverter::parseReal(vert.attribute("x").value()); - v.y = StringConverter::parseReal(vert.attribute("y").value()); - v.z = StringConverter::parseReal(vert.attribute("z").value()); - sm->extremityPoints.push_back (v); - } - } - - LogManager::getSingleton().logMessage("Extremes done."); - } - //----------------------------------------------------------------------------- - void XMLMeshSerializer::readPoses(pugi::xml_node& posesNode, Mesh *m) - { - - - for (pugi::xml_node poseNode : posesNode.children("pose")) - { - const char* target = poseNode.attribute("target").as_string(NULL); - if (!target) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Required attribute 'target' missing on pose", - "XMLMeshSerializer::readPoses"); - } - unsigned short targetID; - if(String(target) == "mesh") - { - targetID = 0; - } - else - { - // submesh, get index - const char* val = poseNode.attribute("index").as_string(NULL); - if (!val) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Required attribute 'index' missing on pose", - "XMLMeshSerializer::readPoses"); - } - unsigned short submeshIndex = static_cast( - StringConverter::parseUnsignedInt(val)); - - targetID = submeshIndex + 1; - } - - String name; - const char* val = poseNode.attribute("name").as_string(NULL); - if (val) - name = val; - Pose* pose = m->createPose(targetID, name); - - for (pugi::xml_node poseOffsetNode : poseNode.children("poseoffset")) - { - uint index = StringConverter::parseUnsignedInt(poseOffsetNode.attribute("index").value()); - Vector3f offset; - offset[0] = StringConverter::parseReal(poseOffsetNode.attribute("x").value()); - offset[1] = StringConverter::parseReal(poseOffsetNode.attribute("y").value()); - offset[2] = StringConverter::parseReal(poseOffsetNode.attribute("z").value()); - - if (poseOffsetNode.attribute("nx").value() && - poseOffsetNode.attribute("ny").value() && - poseOffsetNode.attribute("nz").value()) - { - Vector3f normal; - normal[0] = StringConverter::parseReal(poseOffsetNode.attribute("nx").value()); - normal[1] = StringConverter::parseReal(poseOffsetNode.attribute("ny").value()); - normal[2] = StringConverter::parseReal(poseOffsetNode.attribute("nz").value()); - pose->addVertex(index, offset, normal); - - } - else - { - pose->addVertex(index, offset); - } - } - } - - - } - //----------------------------------------------------------------------------- - void XMLMeshSerializer::readAnimations(pugi::xml_node& mAnimationsNode, Mesh *pMesh) - { - for (pugi::xml_node animElem : mAnimationsNode.children("animation")) - { - String name = animElem.attribute("name").value(); - Real len = StringConverter::parseReal(animElem.attribute("length").value()); - - Animation* anim = pMesh->createAnimation(name, len); - - pugi::xml_node baseInfoNode = animElem.child("baseinfo"); - if (baseInfoNode) - { - String baseName = baseInfoNode.attribute("baseanimationname").value(); - Real baseTime = StringConverter::parseReal(baseInfoNode.attribute("basekeyframetime").value()); - anim->setUseBaseKeyFrame(true, baseTime, baseName); - } - - pugi::xml_node tracksNode = animElem.child("tracks"); - if (tracksNode) - { - readTracks(tracksNode, pMesh, anim); - } - } - - - } - //----------------------------------------------------------------------------- - void XMLMeshSerializer::readTracks(pugi::xml_node& tracksNode, Mesh *m, Animation* anim) - { - for (pugi::xml_node trackNode : tracksNode.children("track")) - { - String target = trackNode.attribute("target").value(); - unsigned short targetID; - VertexData* vertexData = 0; - if(target == "mesh") - { - targetID = 0; - vertexData = m->sharedVertexData; - } - else - { - // submesh, get index - const char* val = trackNode.attribute("index").as_string(NULL); - if (!val) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Required attribute 'index' missing on submesh track", - "XMLMeshSerializer::readTracks"); - } - unsigned short submeshIndex = static_cast( - StringConverter::parseUnsignedInt(val)); - - targetID = submeshIndex + 1; - vertexData = m->getSubMesh(submeshIndex)->vertexData; - - } - - if (!vertexData) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Track cannot be created for " + target + " since VertexData " - "does not exist at the specified index", - "XMLMeshSerializer::readTracks"); - } - - // Get type - VertexAnimationType animType = VAT_NONE; - String strAnimType = trackNode.attribute("type").value(); - if (strAnimType == "morph") - { - animType = VAT_MORPH; - } - else if (strAnimType == "pose") - { - animType = VAT_POSE; - } - else - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Unrecognised animation track type '" + strAnimType + "'", - "XMLMeshSerializer::readTracks"); - } - - // Create track - VertexAnimationTrack* track = - anim->createVertexTrack(targetID, vertexData, animType); - - pugi::xml_node keyframesNode = trackNode.child("keyframes"); - if (keyframesNode) - { - if (track->getAnimationType() == VAT_MORPH) - { - readMorphKeyFrames(keyframesNode, track, vertexData->vertexCount); - } - else // VAT_POSE - { - readPoseKeyFrames(keyframesNode, track); - } - } - } - } - //----------------------------------------------------------------------------- - void XMLMeshSerializer::readMorphKeyFrames(pugi::xml_node& keyframesNode, - VertexAnimationTrack* track, size_t vertexCount) - { - for (pugi::xml_node keyNode : keyframesNode.children("keyframe")) - { - const char* val = keyNode.attribute("time").as_string(NULL); - if (!val) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Required attribute 'time' missing on keyframe", - "XMLMeshSerializer::readKeyFrames"); - } - Real time = StringConverter::parseReal(val); - - VertexMorphKeyFrame* kf = track->createVertexMorphKeyFrame(time); - - bool includesNormals = keyNode.child("normal"); - - size_t vertexSize = sizeof(float) * (includesNormals ? 6 : 3); - // create a vertex buffer - HardwareVertexBufferSharedPtr vbuf = - HardwareBufferManager::getSingleton().createVertexBuffer( - vertexSize, vertexCount, - HardwareBuffer::HBU_STATIC, true); - - float* pFloat = static_cast( - vbuf->lock(HardwareBuffer::HBL_DISCARD)); - - - pugi::xml_node posNode = keyNode.child("position"); - pugi::xml_node normNode = keyNode.child("normal"); - for (size_t v = 0; v < vertexCount; ++v) - { - if (!posNode) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Not enough 'position' elements under keyframe", - "XMLMeshSerializer::readKeyFrames"); - - } - - *pFloat++ = StringConverter::parseReal(posNode.attribute("x").value()); - *pFloat++ = StringConverter::parseReal(posNode.attribute("y").value()); - *pFloat++ = StringConverter::parseReal(posNode.attribute("z").value()); - - if (includesNormals) - { - if (!normNode) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Not enough 'normal' elements under keyframe", - "XMLMeshSerializer::readKeyFrames"); - - } - - *pFloat++ = StringConverter::parseReal(normNode.attribute("x").value()); - *pFloat++ = StringConverter::parseReal(normNode.attribute("y").value()); - *pFloat++ = StringConverter::parseReal(normNode.attribute("z").value()); - normNode = normNode.next_sibling("normal"); - } - - - posNode = posNode.next_sibling("position"); - } - - vbuf->unlock(); - - kf->setVertexBuffer(vbuf); - } - - - } - //----------------------------------------------------------------------------- - void XMLMeshSerializer::readPoseKeyFrames(pugi::xml_node& keyframesNode, VertexAnimationTrack* track) - { - for (pugi::xml_node keyNode : keyframesNode.children("keyframe")) - { - const char* val = keyNode.attribute("time").as_string(NULL); - if (!val) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Required attribute 'time' missing on keyframe", - "XMLMeshSerializer::readKeyFrames"); - } - Real time = StringConverter::parseReal(val); - - VertexPoseKeyFrame* kf = track->createVertexPoseKeyFrame(time); - - // Read all pose references - for (pugi::xml_node poseRefNode : keyNode.children("poseref")) - { - const char* attr = poseRefNode.attribute("poseindex").as_string(NULL); - if (!attr) - { - OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, - "Required attribute 'poseindex' missing on poseref", - "XMLMeshSerializer::readPoseKeyFrames"); - } - unsigned short poseIndex = StringConverter::parseUnsignedInt(attr); - Real influence = 1.0f; - attr = poseRefNode.attribute("influence").as_string(NULL); - if (attr) - { - influence = StringConverter::parseReal(attr); - } - - kf->addPoseReference(poseIndex, influence); - } - } - - } - //----------------------------------------------------------------------------- - void XMLMeshSerializer::writePoses(pugi::xml_node& meshNode, const Mesh* m) - { - if (m->getPoseList().empty()) - return; - - pugi::xml_node posesNode = meshNode.append_child("poses"); - - PoseList::const_iterator it; - for( it = m->getPoseList().begin(); it != m->getPoseList().end(); ++it) - { - const Pose* pose = *it; - pugi::xml_node poseNode = posesNode.append_child("pose"); - unsigned short target = pose->getTarget(); - if (target == 0) - { - // Main mesh - poseNode.append_attribute("target") = "mesh"; - } - else - { - // Submesh - rebase index - poseNode.append_attribute("target") = "submesh"; - poseNode.append_attribute("index") = - StringConverter::toString(target - 1).c_str(); - } - poseNode.append_attribute("name") = pose->getName().c_str(); - - bool includesNormals = !pose->getNormals().empty(); - auto nit = pose->getNormals().begin(); - for (const auto& vit : pose->getVertexOffsets()) - { - pugi::xml_node poseOffsetElement = poseNode.append_child("poseoffset"); - - poseOffsetElement.append_attribute("index") = - StringConverter::toString(vit.first).c_str(); - - const Vector3f& offset = vit.second; - poseOffsetElement.append_attribute("x") = StringConverter::toString(offset[0]).c_str(); - poseOffsetElement.append_attribute("y") = StringConverter::toString(offset[1]).c_str(); - poseOffsetElement.append_attribute("z") = StringConverter::toString(offset[2]).c_str(); - - if (includesNormals) - { - const Vector3f& normal = nit->second; - poseOffsetElement.append_attribute("nx") = StringConverter::toString(normal[0]).c_str(); - poseOffsetElement.append_attribute("ny") = StringConverter::toString(normal[1]).c_str(); - poseOffsetElement.append_attribute("nz") = StringConverter::toString(normal[2]).c_str(); - nit++; - } - - - - - } - - } - - } - //----------------------------------------------------------------------------- - void XMLMeshSerializer::writeAnimations(pugi::xml_node& meshNode, const Mesh* m) - { - // Skip if no animation - if (!m->hasVertexAnimation()) - return; - - pugi::xml_node animationsNode = meshNode.append_child("animations"); - - for (unsigned short a = 0; a < m->getNumAnimations(); ++a) - { - Animation* anim = m->getAnimation(a); - - pugi::xml_node animNode = - animationsNode.append_child("animation"); - animNode.append_attribute("name") = anim->getName().c_str(); - animNode.append_attribute("length") = - StringConverter::toString(anim->getLength()).c_str(); - - // Optional base keyframe information - if (anim->getUseBaseKeyFrame()) - { - pugi::xml_node baseInfoNode = - animNode.append_child("baseinfo"); - baseInfoNode.append_attribute("baseanimationname") = anim->getBaseKeyFrameAnimationName().c_str(); - baseInfoNode.append_attribute("basekeyframetime") = StringConverter::toString(anim->getBaseKeyFrameTime()).c_str(); - } - - pugi::xml_node tracksNode = animNode.append_child("tracks"); - for (const auto& trackIt : anim->_getVertexTrackList()) - { - const VertexAnimationTrack* track = trackIt.second; - pugi::xml_node trackNode = tracksNode.append_child("track"); - - unsigned short targetID = trackIt.first; - if (targetID == 0) - { - trackNode.append_attribute("target") = "mesh"; - } - else - { - trackNode.append_attribute("target") = "submesh"; - trackNode.append_attribute("index") = - StringConverter::toString(targetID-1).c_str(); - } - - if (track->getAnimationType() == VAT_MORPH) - { - trackNode.append_attribute("type") = "morph"; - writeMorphKeyFrames(trackNode, track); - } - else - { - trackNode.append_attribute("type") = "pose"; - writePoseKeyFrames(trackNode, track); - } - - - } - } - - - } - //----------------------------------------------------------------------------- - void XMLMeshSerializer::writeMorphKeyFrames(pugi::xml_node& trackNode, const VertexAnimationTrack* track) - { - pugi::xml_node keyframesNode = trackNode.append_child("keyframes"); - - size_t vertexCount = track->getAssociatedVertexData()->vertexCount; - - for (unsigned short k = 0; k < track->getNumKeyFrames(); ++k) - { - VertexMorphKeyFrame* kf = track->getVertexMorphKeyFrame(k); - pugi::xml_node keyNode = keyframesNode.append_child("keyframe"); - keyNode.append_attribute("time") = - StringConverter::toString(kf->getTime()).c_str(); - - HardwareVertexBufferSharedPtr vbuf = kf->getVertexBuffer(); - - bool includesNormals = vbuf->getVertexSize() > (sizeof(float) * 3); - - float* pFloat = static_cast( - vbuf->lock(HardwareBuffer::HBL_READ_ONLY)); - - for (size_t v = 0; v < vertexCount; ++v) - { - pugi::xml_node posNode = keyNode.append_child("position"); - posNode.append_attribute("x") = StringConverter::toString(*pFloat++).c_str(); - posNode.append_attribute("y") = StringConverter::toString(*pFloat++).c_str(); - posNode.append_attribute("z") = StringConverter::toString(*pFloat++).c_str(); - - if (includesNormals) - { - pugi::xml_node normNode = keyNode.append_child("normal"); - normNode.append_attribute("x") = StringConverter::toString(*pFloat++).c_str(); - normNode.append_attribute("y") = StringConverter::toString(*pFloat++).c_str(); - normNode.append_attribute("z") = StringConverter::toString(*pFloat++).c_str(); - } - } - - } - } - //----------------------------------------------------------------------------- - void XMLMeshSerializer::writePoseKeyFrames(pugi::xml_node& trackNode, const VertexAnimationTrack* track) - { - pugi::xml_node keyframesNode = trackNode.append_child("keyframes"); - - for (unsigned short k = 0; k < track->getNumKeyFrames(); ++k) - { - VertexPoseKeyFrame* kf = track->getVertexPoseKeyFrame(k); - pugi::xml_node keyNode = keyframesNode.append_child("keyframe"); - keyNode.append_attribute("time") = - StringConverter::toString(kf->getTime()).c_str(); - - VertexPoseKeyFrame::PoseRefList::const_iterator poseIt = - kf->getPoseReferences().begin(); - for (;poseIt != kf->getPoseReferences().end(); ++poseIt) - { - const VertexPoseKeyFrame::PoseRef& poseRef = *poseIt; - pugi::xml_node poseRefNode = keyNode.append_child("poseref"); - - poseRefNode.append_attribute("poseindex") = - StringConverter::toString(poseRef.poseIndex).c_str(); - poseRefNode.append_attribute("influence") = - StringConverter::toString(poseRef.influence).c_str(); - - } - - } - - - } - - - - -} - diff --git a/Tools/XMLConverter/src/OgreXMLSkeletonSerializer.cpp b/Tools/XMLConverter/src/OgreXMLSkeletonSerializer.cpp deleted file mode 100644 index c4420d59cfc..00000000000 --- a/Tools/XMLConverter/src/OgreXMLSkeletonSerializer.cpp +++ /dev/null @@ -1,649 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - -#include "OgreXMLSkeletonSerializer.h" -#include "OgreSkeleton.h" -#include "OgreAnimation.h" -#include "OgreAnimationTrack.h" -#include "OgreKeyFrame.h" -#include "OgreBone.h" -#include "OgreString.h" -#include "OgreLogManager.h" -#include "OgreStringConverter.h" -#include "Ogre.h" - -#include - -namespace Ogre { - - - //--------------------------------------------------------------------- - XMLSkeletonSerializer::XMLSkeletonSerializer() - { - } - //--------------------------------------------------------------------- - XMLSkeletonSerializer::~XMLSkeletonSerializer() - { - } - - //--------------------------------------------------------------------- - void XMLSkeletonSerializer::importSkeleton(const String& filename, Skeleton* pSkeleton) - { - LogManager::getSingleton().logMessage("XMLSkeletonSerializer: reading XML data from " + filename + "..."); - - pugi::xml_document mXMLDoc; - mXMLDoc.load_file(filename.c_str()); - - pugi::xml_node elem; - - pugi::xml_node rootElem = mXMLDoc.document_element(); - - // Optional blend mode - const char* blendModeStr = rootElem.attribute("blendmode").as_string(NULL); - if (blendModeStr) - { - if (String(blendModeStr) == "cumulative") - pSkeleton->setBlendMode(ANIMBLEND_CUMULATIVE); - else - pSkeleton->setBlendMode(ANIMBLEND_AVERAGE); - - } - - - // Bones - elem = rootElem.child("bones"); - if (elem) - { - readBones(pSkeleton, elem); - elem = rootElem.child("bonehierarchy"); - - if (elem) - { - createHierarchy(pSkeleton, elem) ; - elem = rootElem.child("bones"); - if (elem) - { - readBones2(pSkeleton, elem); - elem = rootElem.child("animations"); - if (elem) - { - readAnimations(pSkeleton, elem); - } - elem = rootElem.child("animationlinks"); - if (elem) - { - readSkeletonAnimationLinks(pSkeleton, elem); - } - } - } - } - LogManager::getSingleton().logMessage("XMLSkeletonSerializer: Finished. Running SkeletonSerializer..." ); - } - - - //--------------------------------------------------------------------- - // sets names - void XMLSkeletonSerializer::readBones(Skeleton* skel, pugi::xml_node& mBonesNode) - { - LogManager::getSingleton().logMessage("XMLSkeletonSerializer: Reading Bones name..."); - - Quaternion quat ; - - int max_id = -1; - - for (pugi::xml_node& bonElem : mBonesNode.children()) - { - String name = bonElem.attribute("name").value(); - int id = StringConverter::parseInt(bonElem.attribute("id").value()); - skel->createBone(name,id) ; - - max_id = std::max(id, max_id); - } - - OgreAssert(size_t(max_id + 1) == skel->getBones().size(), "Bone ids must be consecutive in range [0; N)"); - } - // --------------------------------------------------------- - // set positions and orientations. - void XMLSkeletonSerializer::readBones2(Skeleton* skel, pugi::xml_node& mBonesNode) - { - LogManager::getSingleton().logMessage("XMLSkeletonSerializer: Reading Bones data..."); - - Bone* btmp ; - Quaternion quat ; - - for (pugi::xml_node& bonElem : mBonesNode.children()) - { - String name = bonElem.attribute("name").value(); -// int id = StringConverter::parseInt(bonElem.attribute("id").c_str(); - - pugi::xml_node posElem = bonElem.child("position"); - pugi::xml_node rotElem = bonElem.child("rotation"); - pugi::xml_node axisElem = rotElem.child("axis"); - pugi::xml_node scaleElem = bonElem.child("scale"); - - Vector3 pos; - Vector3 axis; - Radian angle ; - Vector3 scale; - - pos.x = StringConverter::parseReal(posElem.attribute("x").value()); - pos.y = StringConverter::parseReal(posElem.attribute("y").value()); - pos.z = StringConverter::parseReal(posElem.attribute("z").value()); - - angle = Radian(StringConverter::parseReal(rotElem.attribute("angle").value())); - - axis.x = StringConverter::parseReal(axisElem.attribute("x").value()); - axis.y = StringConverter::parseReal(axisElem.attribute("y").value()); - axis.z = StringConverter::parseReal(axisElem.attribute("z").value()); - - // Optional scale - if (scaleElem) - { - // Uniform scale or per axis? - const char* factorAttrib = scaleElem.attribute("factor").as_string(NULL); - if (factorAttrib) - { - // Uniform scale - Real factor = StringConverter::parseReal(factorAttrib); - scale = Vector3(factor, factor, factor); - } - else - { - // axis scale - scale = Vector3::UNIT_SCALE; - const char* factorString = scaleElem.attribute("x").as_string(NULL); - if (factorString) - { - scale.x = StringConverter::parseReal(factorString); - } - factorString = scaleElem.attribute("y").value(); - if (factorString) - { - scale.y = StringConverter::parseReal(factorString); - } - factorString = scaleElem.attribute("z").value(); - if (factorString) - { - scale.z = StringConverter::parseReal(factorString); - } - } - } - else - { - scale = Vector3::UNIT_SCALE; - } - - /*LogManager::getSingleton().logMessage("bone " + name + " : position(" - + StringConverter::toString(pos.x) + "," + StringConverter::toString(pos.y) + "," + StringConverter::toString(pos.z) + ")" - + " - angle: " + StringConverter::toString(angle) +" - axe: " - + StringConverter::toString(axis.x) + "," + StringConverter::toString(axis.y) + "," + StringConverter::toString(axis.z) ); - */ - - btmp = skel->getBone(name) ; - - btmp -> setPosition(pos); - quat.FromAngleAxis(angle,axis); - btmp -> setOrientation(quat) ; - btmp -> setScale(scale); - - } // bones - } - //------------------------------------------------------------------- - void XMLSkeletonSerializer::createHierarchy(Skeleton* skel, pugi::xml_node& mHierNode) { - - LogManager::getSingleton().logMessage("XMLSkeletonSerializer: Reading Hierarchy data..."); - - Bone* bone ; - Bone* parent ; - String boneName ; - String parentName ; - - for (pugi::xml_node& hierElem : mHierNode.children()) - { - boneName = hierElem.attribute("bone").value(); - parentName = hierElem.attribute("parent").value(); - bone = skel->getBone(boneName); - parent = skel->getBone(parentName); - parent ->addChild(bone) ; - //LogManager::getSingleton().logMessage("XMLSkeletonSerialiser: lien: " + parent->getName() + "->" + bone->getName().c_str(); - - } - } - //--------------------------------------------------------------------- - void XMLSkeletonSerializer::readAnimations(Skeleton* skel, pugi::xml_node& mAnimNode) { - - Animation * anim ; - NodeAnimationTrack * track ; - LogManager::getSingleton().logMessage("XMLSkeletonSerializer: Reading Animations data..."); - - for (pugi::xml_node& animElem : mAnimNode.children("animation")) - { - String name = animElem.attribute("name").value(); - Real length = StringConverter::parseReal(animElem.attribute("length").value()); - anim = skel->createAnimation(name,length); - anim->setInterpolationMode(Animation::IM_LINEAR) ; - - - //LogManager::getSingleton().logMessage("Animation: nom: " + name + " et longueur: " - // + StringConverter::toString(length) ); - pugi::xml_node baseInfoNode = animElem.child("baseinfo"); - if (baseInfoNode) - { - String baseName = baseInfoNode.attribute("baseanimationname").value(); - Real baseTime = StringConverter::parseReal(baseInfoNode.attribute("basekeyframetime").value()); - anim->setUseBaseKeyFrame(true, baseTime, baseName); - } - - - - // lecture des tracks - pugi::xml_node tracksNode = animElem.child("tracks"); - - for (pugi::xml_node& trackElem : tracksNode.children("track")) - { - String boneName = trackElem.attribute("bone").value(); - Bone * bone = skel->getBone(boneName); - unsigned short handle = bone->getHandle(); - - //LogManager::getSingleton().logMessage("Track sur le bone: " + boneName ); - - track = anim->createNodeTrack(handle, bone); - readKeyFrames(track, trackElem.child("keyframes")); - } - - } - - - } - //--------------------------------------------------------------------- - void XMLSkeletonSerializer::readKeyFrames(NodeAnimationTrack* track, const pugi::xml_node& mKeyfNode) { - - TransformKeyFrame* kf ; - Quaternion q ; - - for (pugi::xml_node& keyfElem : mKeyfNode.children("keyframe")) - { - Vector3 trans; - Vector3 axis; - Radian angle; - Real time; - - // Get time and create keyframe - time = StringConverter::parseReal(keyfElem.attribute("time").value()); - kf = track->createNodeKeyFrame(time); - // Optional translate - pugi::xml_node transElem = keyfElem.child("translate"); - if (transElem) - { - trans.x = StringConverter::parseReal(transElem.attribute("x").value()); - trans.y = StringConverter::parseReal(transElem.attribute("y").value()); - trans.z = StringConverter::parseReal(transElem.attribute("z").value()); - kf->setTranslate(trans) ; - } - // Optional rotate - pugi::xml_node rotElem = keyfElem.child("rotate"); - if (rotElem) - { - pugi::xml_node axisElem = rotElem.child("axis"); - if (!axisElem) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Missing 'axis' element " - "expected under parent 'rotate'", "MXLSkeletonSerializer::readKeyFrames"); - } - angle = Radian(StringConverter::parseReal(rotElem.attribute("angle").value())); - - axis.x = StringConverter::parseReal(axisElem.attribute("x").value()); - axis.y = StringConverter::parseReal(axisElem.attribute("y").value()); - axis.z = StringConverter::parseReal(axisElem.attribute("z").value()); - - q.FromAngleAxis(angle,axis); - kf->setRotation(q) ; - - } - // Optional scale - pugi::xml_node scaleElem = keyfElem.child("scale"); - if (scaleElem) - { - // Uniform scale or per axis? - const char* factorAttrib = scaleElem.attribute("factor").as_string(NULL); - if (factorAttrib) - { - // Uniform scale - Real factor = StringConverter::parseReal(factorAttrib); - kf->setScale(Vector3(factor, factor, factor)); - } - else - { - // axis scale - Real xs = 1.0f, ys = 1.0f, zs=1.0f; - const char* factorString = scaleElem.attribute("x").as_string(NULL); - if(factorString) - { - xs = StringConverter::parseReal(factorString); - } - factorString = scaleElem.attribute("y").value(); - if(factorString) - { - ys = StringConverter::parseReal(factorString); - } - factorString = scaleElem.attribute("z").value(); - if(factorString) - { - zs = StringConverter::parseReal(factorString); - } - kf->setScale(Vector3(xs, ys, zs)); - - } - } - - - /* - LogManager::getSingleton().logMessage("Keyframe: translation(" - + StringConverter::toString(trans.x) + "," + StringConverter::toString(trans.y) + "," + StringConverter::toString(trans.z) + ")" - + " - angle: " + StringConverter::toString(angle) +" - axe: " - + StringConverter::toString(axis.x) + "," + StringConverter::toString(axis.y) + "," + StringConverter::toString(axis.z) ); - */ - - - } - } - - //--------------------------------------------------------------------- - void XMLSkeletonSerializer::exportSkeleton(const Skeleton* pSkeleton, - const String& filename) - { - - LogManager::getSingleton().logMessage("XMLSkeletonSerializer writing " - " skeleton data to " + filename + "..."); - - pugi::xml_document mXMLDoc; - pugi::xml_node rootNode = mXMLDoc.append_child("skeleton"); - - LogManager::getSingleton().logMessage("Populating DOM..."); - - - // Write main skeleton data - LogManager::getSingleton().logMessage("Exporting bones.."); - writeSkeleton(pSkeleton, rootNode); - LogManager::getSingleton().logMessage("Bones exported."); - - // Write all animations - unsigned short numAnims = pSkeleton->getNumAnimations(); - String msg = "Exporting animations, count=" + StringConverter::toString(numAnims); - LogManager::getSingleton().logMessage(msg); - - pugi::xml_node animsNode = rootNode.append_child("animations"); - - for (unsigned short i = 0; i < numAnims; ++i) - { - Animation* pAnim = pSkeleton->getAnimation(i); - msg = "Exporting animation: " + pAnim->getName(); - LogManager::getSingleton().logMessage(msg); - writeAnimation(animsNode, pAnim); - LogManager::getSingleton().logMessage("Animation exported."); - - } - - // Write links - if (!pSkeleton->getLinkedSkeletonAnimationSources().empty()) - { - LogManager::getSingleton().logMessage("Exporting animation links."); - pugi::xml_node linksNode = rootNode.append_child("animationlinks"); - for(const auto& link : pSkeleton->getLinkedSkeletonAnimationSources()) - { - writeSkeletonAnimationLink(linksNode, link); - } - } - - LogManager::getSingleton().logMessage("DOM populated, writing XML file.."); - - // Write out to a file - if(! mXMLDoc.save_file(filename.c_str()) ) - { - LogManager::getSingleton().logMessage("XMLSkeletonSerializer failed writing the XML file.", LML_CRITICAL); - } - else - { - LogManager::getSingleton().logMessage("XMLSkeletonSerializer export successful."); - } - } - //--------------------------------------------------------------------- - void XMLSkeletonSerializer::writeSkeleton(const Skeleton* pSkel, pugi::xml_node& rootNode) - { - // Blend mode - String blendModeStr = pSkel->getBlendMode() == ANIMBLEND_CUMULATIVE ? "cumulative" : "average"; - rootNode.append_attribute("blendmode") = blendModeStr.c_str(); - - pugi::xml_node bonesElem = rootNode.append_child("bones"); - - unsigned short numBones = pSkel->getNumBones(); - LogManager::getSingleton().logMessage("There are " + StringConverter::toString(numBones) + " bones."); - unsigned short i; - for (i = 0; i < numBones; ++i) - { - LogManager::getSingleton().logMessage(" Exporting Bone number " + StringConverter::toString(i)); - Bone* pBone = pSkel->getBone(i); - writeBone(bonesElem, pBone); - } - - // Write parents - pugi::xml_node hierElem = rootNode.append_child("bonehierarchy"); - for (i = 0; i < numBones; ++i) - { - Bone* pBone = pSkel->getBone(i); - String name = pBone->getName() ; - - if ((pBone->getParent())!=NULL) // root bone - { - Bone* pParent = (Bone*)pBone->getParent(); - writeBoneParent(hierElem, name, pParent->getName()); - } - } - - - } - //--------------------------------------------------------------------- - void XMLSkeletonSerializer::writeBone(pugi::xml_node& bonesElement, const Bone* pBone) - { - pugi::xml_node boneElem = bonesElement.append_child("bone"); - - // Bone name & handle - boneElem.append_attribute("id") = StringConverter::toString(pBone->getHandle()).c_str(); - boneElem.append_attribute("name") = pBone->getName().c_str(); - - // Position - pugi::xml_node subNode = boneElem.append_child("position"); - Vector3 pos = pBone->getPosition(); - subNode.append_attribute("x") = StringConverter::toString(pos.x).c_str(); - subNode.append_attribute("y") = StringConverter::toString(pos.y).c_str(); - subNode.append_attribute("z") = StringConverter::toString(pos.z).c_str(); - - // Orientation - subNode = - boneElem.append_child("rotation"); - // Show Quaternion as angle / axis - Radian angle; - Vector3 axis; - pBone->getOrientation().ToAngleAxis(angle, axis); - pugi::xml_node axisNode = subNode.append_child("axis"); - subNode.append_attribute("angle") = StringConverter::toString(angle.valueRadians()).c_str(); - axisNode.append_attribute("x") = StringConverter::toString(axis.x).c_str(); - axisNode.append_attribute("y") = StringConverter::toString(axis.y).c_str(); - axisNode.append_attribute("z") = StringConverter::toString(axis.z).c_str(); - - // Scale optional - Vector3 scale = pBone->getScale(); - if (scale != Vector3::UNIT_SCALE) - { - pugi::xml_node scaleNode = boneElem.append_child("scale"); - scaleNode.append_attribute("x") = StringConverter::toString(scale.x).c_str(); - scaleNode.append_attribute("y") = StringConverter::toString(scale.y).c_str(); - scaleNode.append_attribute("z") = StringConverter::toString(scale.z).c_str(); - } - - - } - //--------------------------------------------------------------------- - // - // Modifications effectu�es: - // - // on stoque les noms et pas les Id. c'est plus lisibles. - - - void XMLSkeletonSerializer::writeBoneParent(pugi::xml_node& boneHierarchyNode, - const String& boneName, const String& parentName) - { - pugi::xml_node boneParentNode = boneHierarchyNode.append_child("boneparent"); - /* - boneParentNode.append_attribute("boneid") = StringConverter::toString(boneId).c_str(); - boneParentNode.append_attribute("parentid") = StringConverter::toString(parentId).c_str(); - */ - // Modifications: on stoque les noms./ - boneParentNode.append_attribute("bone") = boneName.c_str(); - boneParentNode.append_attribute("parent") = parentName.c_str(); - - } - //--------------------------------------------------------------------- - void XMLSkeletonSerializer::writeAnimation(pugi::xml_node& animsNode, - const Animation* anim) - { - pugi::xml_node animNode = animsNode.append_child("animation"); - - animNode.append_attribute("name") = anim->getName().c_str(); - animNode.append_attribute("length") = StringConverter::toString(anim->getLength()).c_str(); - - // Optional base keyframe information - if (anim->getUseBaseKeyFrame()) - { - pugi::xml_node baseInfoNode = animNode.append_child("baseinfo"); - baseInfoNode.append_attribute("baseanimationname") = anim->getBaseKeyFrameAnimationName().c_str(); - baseInfoNode.append_attribute("basekeyframetime") = StringConverter::toString(anim->getBaseKeyFrameTime()).c_str(); - } - - // Write all tracks - pugi::xml_node tracksNode = animNode.append_child("tracks"); - - for (const auto& it : anim->_getNodeTrackList()) - { - writeAnimationTrack(tracksNode, it.second); - } - - } - //--------------------------------------------------------------------- - void XMLSkeletonSerializer::writeAnimationTrack(pugi::xml_node& tracksNode, - const NodeAnimationTrack* track) - { - pugi::xml_node trackNode = tracksNode.append_child("track"); - - // unsigned short boneIndex : Index of bone to apply to - Bone* bone = (Bone*)track->getAssociatedNode(); - //unsigned short boneid = bone->getHandle(); - String boneName = bone->getName(); - trackNode.append_attribute("bone") = boneName.c_str(); - - // Write all keyframes - pugi::xml_node keysNode = - trackNode.append_child("keyframes"); - for (unsigned short i = 0; i < track->getNumKeyFrames(); ++i) - { - writeKeyFrame(keysNode, track->getNodeKeyFrame(i)); - } - } - //--------------------------------------------------------------------- - void XMLSkeletonSerializer::writeKeyFrame(pugi::xml_node& keysNode, - const TransformKeyFrame* key) - { - pugi::xml_node keyNode = keysNode.append_child("keyframe"); - - keyNode.append_attribute("time") = StringConverter::toString(key->getTime()).c_str(); - - pugi::xml_node transNode = - keyNode.append_child("translate"); - Vector3 trans = key->getTranslate(); - transNode.append_attribute("x") = StringConverter::toString(trans.x).c_str(); - transNode.append_attribute("y") = StringConverter::toString(trans.y).c_str(); - transNode.append_attribute("z") = StringConverter::toString(trans.z).c_str(); - - pugi::xml_node rotNode = keyNode.append_child("rotate"); - // Show Quaternion as angle / axis - Radian angle; - Vector3 axis; - key->getRotation().ToAngleAxis(angle, axis); - pugi::xml_node axisNode = rotNode.append_child("axis"); - rotNode.append_attribute("angle") = StringConverter::toString(angle.valueRadians()).c_str(); - axisNode.append_attribute("x") = StringConverter::toString(axis.x).c_str(); - axisNode.append_attribute("y") = StringConverter::toString(axis.y).c_str(); - axisNode.append_attribute("z") = StringConverter::toString(axis.z).c_str(); - - // Scale optional - if (key->getScale() != Vector3::UNIT_SCALE) - { - pugi::xml_node scaleNode = keyNode.append_child("scale"); - - scaleNode.append_attribute("x") = StringConverter::toString(key->getScale().x).c_str(); - scaleNode.append_attribute("y") = StringConverter::toString(key->getScale().y).c_str(); - scaleNode.append_attribute("z") = StringConverter::toString(key->getScale().z).c_str(); - } - - } - //--------------------------------------------------------------------- - void XMLSkeletonSerializer::writeSkeletonAnimationLink(pugi::xml_node& linksNode, - const LinkedSkeletonAnimationSource& link) - { - pugi::xml_node linkNode = linksNode.append_child("animationlink"); - linkNode.append_attribute("skeletonName") = link.skeletonName.c_str(); - linkNode.append_attribute("scale") = StringConverter::toString(link.scale).c_str(); - - } - //--------------------------------------------------------------------- - void XMLSkeletonSerializer::readSkeletonAnimationLinks(Skeleton* skel, - pugi::xml_node& linksNode) - { - LogManager::getSingleton().logMessage("XMLSkeletonSerializer: Reading Animations links..."); - - for (pugi::xml_node& linkElem : linksNode.children("animationlink")) - { - String skelName = linkElem.attribute("skeletonName").value(); - const char* strScale = linkElem.attribute("scale").as_string(NULL); - Real scale; - // Scale optional - if (strScale == 0) - { - scale = 1.0f; - } - else - { - scale = StringConverter::parseReal(strScale); - } - skel->addLinkedSkeletonAnimationSource(skelName, scale); - - } - } -} - - diff --git a/Tools/XMLConverter/src/main.cpp b/Tools/XMLConverter/src/main.cpp deleted file mode 100644 index cace821ba11..00000000000 --- a/Tools/XMLConverter/src/main.cpp +++ /dev/null @@ -1,459 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE - (Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ - - -#include "Ogre.h" -#include "OgreXMLMeshSerializer.h" -#include "OgreXMLSkeletonSerializer.h" -#include "OgreXMLPrerequisites.h" -#include "OgreDefaultHardwareBufferManager.h" -#include - -using namespace std; -using namespace Ogre; - -namespace { - -// Some flags were deprecated, because they are provided in OgreMeshUpgrader too! -// Same feature with different implementation! Don't make duplicates! -// Also XMLConverter should only convert between XML format 1:1, while MeshUpgrader should modify it. -struct XmlOptions -{ - String source; - String dest; - String sourceExt; - String destExt; - String logFile; - size_t nuextremityPoints; - size_t mergeTexcoordResult; - size_t mergeTexcoordToDestroy; - bool optimiseAnimations; - bool quietMode; - Serializer::Endian endian; -}; - -void print_version(void) -{ - // OgreXMLConverter (1.10.0) unstable - cout << "OgreXMLConverter " << OGRE_VERSION_NAME << " " - << "(" << OGRE_VERSION_MAJOR << "." << OGRE_VERSION_MINOR << "." << OGRE_VERSION_PATCH << ")" - << " " << OGRE_VERSION_SUFFIX << endl; -} - -void help(void) -{ - // Print help message - cout << -R"HELP(Usage: OgreXMLConverter [options] sourcefile [destfile] - - Converts data between XML and OGRE binary formats. - -Available options: --v = Display version information --merge [n0,n1] = Merge texcoordn0 with texcoordn1. The , separator must be - present, otherwise only n0 is provided assuming n1 = n0+1; - n0 and n1 must be in the same buffer source & adjacent - to each other for the merge to work. --o = DON'T optimise out redundant tracks & keyframes --E endian = Set endian mode 'big' 'little' or 'native' (default) --x num = Generate no more than num eXtremes for every submesh (default 0) --q = Quiet mode, less output --log filename = name of the log file (default: 'OgreXMLConverter.log') -sourcefile = name of file to convert -destfile = optional name of file to write to. If you don't - specify this OGRE works it out through the extension - and the XML contents if the source is XML. For example - test.mesh becomes test.xml, test.xml becomes test.mesh - if the XML document root is etc. -)HELP"; -} - - -XmlOptions parseArgs(int numArgs, char **args) -{ - XmlOptions opts; - - opts.nuextremityPoints = 0; - opts.mergeTexcoordResult = 0; - opts.mergeTexcoordToDestroy = 0; - opts.optimiseAnimations = true; - opts.quietMode = false; - opts.endian = Serializer::ENDIAN_NATIVE; - - // ignore program name - char* source = 0; - char* dest = 0; - - // Set up options - UnaryOptionList unOpt; - BinaryOptionList binOpt; - - unOpt["-o"] = false; - unOpt["-q"] = false; - unOpt["-d3d"] = false; - unOpt["-gl"] = false; - unOpt["-byte"] = false; - unOpt["-h"] = false; - unOpt["-v"] = false; - binOpt["-E"] = ""; - binOpt["-x"] = ""; - binOpt["-log"] = "OgreXMLConverter.log"; - binOpt["-merge"] = "0,0"; - - int startIndex = findCommandLineOpts(numArgs, args, unOpt, binOpt); - - if (unOpt["-v"]) - { - print_version(); - exit(0); - } - if (unOpt["-h"]) - { - help(); - exit(1); - } - if (unOpt["-q"]) - { - opts.quietMode = true; - } - if (unOpt["-o"]) - { - opts.optimiseAnimations = false; - } - - auto bi = binOpt.find("-merge"); - if (!bi->second.empty()) - { - String::size_type separator = bi->second.find_first_of( "," ); - if( separator == String::npos ) - { - //Input format was "-merge 2" - //Assume we want to merge 2 with 3 - opts.mergeTexcoordResult = StringConverter::parseInt( bi->second, 0 ); - opts.mergeTexcoordToDestroy = opts.mergeTexcoordResult + 1; - } - else if( separator + 1 < bi->second.size() ) - { - //Input format was "-merge 1,2" - //We want to merge 1 with 2 - opts.mergeTexcoordResult = StringConverter::parseInt( - bi->second.substr( 0, separator ), 0 ); - opts.mergeTexcoordToDestroy = StringConverter::parseInt( - bi->second.substr( separator+1, - bi->second.size() ), 1 ); - } - } - else - { - //Very rare to reach here. - //Input format was "-merge" - //Assume we want to merge 0 with 1 - opts.mergeTexcoordResult = 0; - opts.mergeTexcoordResult = 1; - } - - bi = binOpt.find("-x"); - if (!bi->second.empty()) - { - opts.nuextremityPoints = StringConverter::parseInt(bi->second); - } - - opts.logFile = binOpt["-log"]; - - bi = binOpt.find("-E"); - if (!bi->second.empty()) - { - if (bi->second == "big") - opts.endian = Serializer::ENDIAN_BIG; - else if (bi->second == "little") - opts.endian = Serializer::ENDIAN_LITTLE; - else - opts.endian = Serializer::ENDIAN_NATIVE; - } - - // Source / dest - if (numArgs > startIndex) - source = args[startIndex]; - if (numArgs > startIndex+1) - dest = args[startIndex+1]; - if (numArgs > startIndex+2) { - LogManager::getSingleton().logError("Too many command-line arguments supplied"); - exit(1); - } - - if (!source) - { - LogManager::getSingleton().logError("Missing source file"); - exit(1); - } - // Work out what kind of conversion this is - opts.source = source; - std::vector srcparts = StringUtil::split(opts.source, "."); - String& ext = srcparts.back(); - StringUtil::toLowerCase(ext); - opts.sourceExt = ext; - - if (!dest) - { - if (opts.sourceExt == "xml") - { - // dest is source minus .xml - opts.dest = opts.source.substr(0, opts.source.size() - 4); - } - else - { - // dest is source + .xml - opts.dest = opts.source; - opts.dest.append(".xml"); - } - - } - else - { - opts.dest = dest; - } - std::vector dstparts = StringUtil::split(opts.dest, "."); - ext = dstparts.back(); - StringUtil::toLowerCase(ext); - opts.destExt = ext; - - if (!opts.quietMode) - { - cout << endl; - cout << "-- OPTIONS --" << endl; - cout << "source file = " << opts.source << endl; - cout << "destination file = " << opts.dest << endl; - cout << "log file = " << opts.logFile << endl; - if (opts.nuextremityPoints) - cout << "Generate extremes per submesh = " << opts.nuextremityPoints << endl; - - cout << "-- END OPTIONS --" << endl; - cout << endl; - } - - - return opts; -} - -void meshToXML(const XmlOptions& opts, MeshSerializer& meshSerializer) -{ - auto stream = Root::openFileStream(opts.source); - - if (!stream) - { - LogManager::getSingleton().logError("Unable to load file " + opts.source); - exit(1); - } - - MeshPtr mesh = MeshManager::getSingleton().create("conversion", - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - - meshSerializer.importMesh(stream, mesh.get()); - - XMLMeshSerializer xmlMeshSerializer; - xmlMeshSerializer.exportMesh(mesh.get(), opts.dest); - - // Clean up the conversion mesh - MeshManager::getSingleton().remove("conversion", - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); -} - -void XMLToBinary(const XmlOptions& opts, MeshSerializer& meshSerializer) -{ - // Read root element and decide from there what type - String response; - pugi::xml_document doc; - - // Some double-parsing here but never mind - if (!doc.load_file(opts.source.c_str())) - { - LogManager::getSingleton().logError("Unable to load file " + opts.source); - exit (1); - } - pugi::xml_node root = doc.document_element(); - if (StringUtil::startsWith("mesh", root.name())) - { - MeshPtr newMesh = MeshManager::getSingleton().createManual("conversion", - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - XMLMeshSerializer xmlMeshSerializer; - xmlMeshSerializer.importMesh(opts.source, newMesh.get()); - - if( opts.mergeTexcoordResult != opts.mergeTexcoordToDestroy ) - { - newMesh->mergeAdjacentTexcoords( uint16(opts.mergeTexcoordResult), uint16(opts.mergeTexcoordToDestroy) ); - } - - if (opts.nuextremityPoints) - { - for (size_t i = 0; i < newMesh->getNumSubMeshes(); i++) - { - SubMesh* sm = newMesh->getSubMesh(i); - sm->generateExtremes (opts.nuextremityPoints); - } - } - - meshSerializer.exportMesh(newMesh, opts.dest, opts.endian); - - // Clean up the conversion mesh - MeshManager::getSingleton().remove("conversion", RGN_DEFAULT); - } - else if (StringUtil::startsWith("skeleton", root.name())) - { - SkeletonPtr newSkel = SkeletonManager::getSingleton().create("conversion", RGN_DEFAULT); - - XMLSkeletonSerializer xmlSkeletonSerializer; - xmlSkeletonSerializer.importSkeleton(opts.source, newSkel.get()); - if (opts.optimiseAnimations) - { - newSkel->optimiseAllAnimations(); - } - SkeletonSerializer skeletonSerializer; - skeletonSerializer.exportSkeleton(newSkel.get(), opts.dest, SKELETON_VERSION_LATEST, opts.endian); - - // Clean up the conversion skeleton - SkeletonManager::getSingleton().remove("conversion", RGN_DEFAULT); - } -} - -void skeletonToXML(const XmlOptions& opts) -{ - auto stream = Root::openFileStream(opts.source); - if (!stream) - { - LogManager::getSingleton().logError("Unable to load file " + opts.source); - exit(1); - } - - SkeletonPtr skel = SkeletonManager::getSingleton().create("conversion", RGN_DEFAULT); - - SkeletonSerializer skeletonSerializer; - skeletonSerializer.importSkeleton(stream, skel.get()); - - XMLSkeletonSerializer xmlSkeletonSerializer; - xmlSkeletonSerializer.exportSkeleton(skel.get(), opts.dest); - - // Clean up the conversion skeleton - SkeletonManager::getSingleton().remove("conversion", RGN_DEFAULT); -} - -struct MeshResourceCreator : public MeshSerializerListener -{ - void processMaterialName(Mesh *mesh, String *name) override - { - if (name->empty()) - { - LogManager::getSingleton().logWarning("one of the SubMeshes is using an empty material name. " - "See https://ogrecave.github.io/ogre/api/latest/_mesh-_tools.html#autotoc_md32"); - // here, we explicitly want to allow fixing that - return; - } - - // create material because we do not load any .material files - MaterialManager::getSingleton().createOrRetrieve(*name, mesh->getGroup()); - } - - void processSkeletonName(Mesh *mesh, String *name) override - { - if (name->empty()) - { - LogManager::getSingleton().logWarning("the mesh is using an empty skeleton name."); - // here, we explicitly want to allow fixing that - return; - } - - // create skeleton because we do not load any .skeleton files - SkeletonManager::getSingleton().createOrRetrieve(*name, mesh->getGroup(), true); - } - void processMeshCompleted(Mesh *mesh) override {} -}; -} - -int main(int numargs, char** args) -{ - if (numargs < 2) - { - help(); - return -1; - } - - // Assume success - int retCode = 0; - - LogManager logMgr; - // this log catches output from the parseArgs call and routes it to stdout only - logMgr.createLog("Temporary log", true, true, true); - XmlOptions opts = parseArgs(numargs, args); - - try - { - logMgr.setDefaultLog(NULL); // swallow startup messages - Root root("", "", ""); - // get rid of the temporary log as we use the new log now - logMgr.destroyLog("Temporary log"); - - // use the log specified by the cmdline params - logMgr.setDefaultLog(logMgr.createLog(opts.logFile, false, !opts.quietMode)); - - MaterialManager::getSingleton().initialise(); - - MeshSerializer meshSerializer; - MeshResourceCreator resCreator; - meshSerializer.setListener(&resCreator); - DefaultHardwareBufferManager bufferManager; // needed because we don't have a rendersystem - - if (opts.sourceExt == "mesh") - { - meshToXML(opts, meshSerializer); - } - else if (opts.sourceExt == "skeleton") - { - skeletonToXML(opts); - } - else if (opts.sourceExt == "xml") - { - XMLToBinary(opts, meshSerializer); - } - else - { - logMgr.logError("Unknown input type: " + opts.sourceExt); - retCode = 1; - } - - logMgr.setDefaultLog(NULL); // swallow shutdown messages - } - catch(Exception& e) - { - LogManager::getSingleton().logError(e.getDescription()); - retCode = 1; - } - - return retCode; -} - diff --git a/Tools/XSIExport/CMakeLists.txt b/Tools/XSIExport/CMakeLists.txt deleted file mode 100755 index 46accb03f7a..00000000000 --- a/Tools/XSIExport/CMakeLists.txt +++ /dev/null @@ -1,30 +0,0 @@ -#------------------------------------------------------------------- -# This file is part of the CMake build system for OGRE -# (Object-oriented Graphics Rendering Engine) -# For the latest info, see http://www.ogre3d.org/ -# -# The contents of this file are placed in the public domain. Feel -# free to make use of it in any way you like. -#------------------------------------------------------------------- - -set(HEADER_FILES - include/OgreXSIHelper.h - include/OgreXSIMaterialExporter.h - include/OgreXSIMeshExporter.h - include/OgreXSISkeletonExporter.h -) - -set(SOURCE_FILES - src/OgreXSIExport.cpp - src/OgreXSIHelper.cpp - src/OgreXSIMaterialExporter.cpp - src/OgreXSIMeshExporter.cpp - src/OgreXSISkeletonExporter.cpp -) - -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include) - -include_directories(${Softimage_INCLUDE_DIR}) - -add_library(OgreXSIExporter MODULE ${HEADER_FILES} ${SOURCE_FILES} "misc/OgreXSIExport.def") -target_link_libraries(OgreXSIExporter ${OGRE_LIBRARIES} ${Softimage_LIBRARIES}) diff --git a/Tools/XSIExport/OGREXSI_Readme.html b/Tools/XSIExport/OGREXSI_Readme.html deleted file mode 100644 index 513f0afbdb8..00000000000 --- a/Tools/XSIExport/OGREXSI_Readme.html +++ /dev/null @@ -1,450 +0,0 @@ - - - - OGRE XSI Exporter Readme - - - - -

OGRE (Object-Oriented Graphics Rendering Engine)

-

XSI Exporter README file

-

http://www.ogre3d.org

-

Summary

-

- OGRE (Object-Oriented Graphics Rendering Engine) is a scene-oriented, flexible 3D engine written in C++ designed to make it easier and more intuitive for developers to produce games and demos utilising 3D hardware. The class - library abstracts all the details of using the underlying system libraries like Direct3D and OpenGL and provides an interface based on world objects and other intuitive classes. -

-

This distribution contains the files required to export OGRE .mesh, .skeleton and .material files from SoftImage|XSI. Currently supported XSI versions are 6.5 up to Softimage 2011

-

IMPORTANT: This exporter only works with a full version of XSI (Foundation or better). It will not work with the trial version.

- How To Install
- Features
- How To Use
- Using the Export Command
- Tips
- Change Log
-


-

How to Install

-

If you are using the installer, you don't need to do anything except to run it and point it at your XSI folder. If you're installing from source, you need to do the following:

-
    -
  • If 'OgreMain.dll' is included, copy it (and OgreMain_d.dll if you wish to use the debug version anytime) into $(XSI_ROOT)\Application\bin
  • -
  • copy OgreXSIExporter.dll into $(XSI_ROOT)\Application\plugins
  • -
- Back To Top
-

Features

-

The following features are supported:

-
    -
  1. Exporting selected PolygonMesh objects direct to the OGRE binary .mesh format
  2. -
  3. Exports vertex position, normals, multiple UV sets and vertex colours
  4. -
  5. Polygon clusters used to change materials in a single PolygonMesh are exported as separate SubMeshes
  6. -
  7. By default, separate PolygonMesh objects which use the same material are merged for efficiency
  8. -
  9. Mesh vertices are index-organised for efficiency
  10. -
  11. Exporting of up to 4 weighted bone assignments per vertex
  12. -
  13. Generation of edge lists, tangent vectors, and LOD levels during export (optional)
  14. -
  15. Exporting of deformers (bone chains, nulls used as deformers) direct to binary .skeleton format
  16. -
  17. Exporting animations from the mixer, sampled IK skeletal animation and shape animation (vertex animation)
  18. -
  19. Exporting of RealTime shaders on materials (OpenGL and DirectX)
  20. -
  21. Exporting meshes with subdivsion using the current subD level
  22. -
  23. Hidden polygons won't be exported. To hide polygons, create a cluster with clsvisibility property by selecting polygons then click Model -> Property -> Polygon Cluster Visibility)
  24. -
  25. Exporting directly from script (no GUI)
  26. -
- Back To Top -

How To Use

- It's a simple case of selecting the objects you wish to export, and clicking File > Export > OGRE Mesh / Skeleton... to bring up the OGRE export dialog.
- page1
-
- The first page of the exporter is concerned with the basic mesh export settings.
- -
- Object(s) to export: -
- This is pre-populated with your current selection
- Mesh: This is the .mesh file to export - you must complete this. Once you have selected a file, by default the other file-related fields in the exporter will be - completed for you based on the same filename pattern.
- Merge objects with the same material?: If this is checked, all polygon mesh objects with the same material will be merged into one for efficiency. Most of the - time you want this; but if you want more control over the splitting of your SubMesh objects, deselect it.
- Calculate Edge Lists: Select this if you want your mesh to support stencil shadows. This increases the size of the resulting .mesh object.
- Calculate Tangents: Select this if you wish to use normal mapping or some other technique which requires tangents vectors.
- Levels of Detail: Increase this value above 0 if you want lower LODs to be generated for - this mesh. The rest of the parameters control how the mesh is reduced.
-
- page2
-
- Export Materials: Whether to export a .material script or not. The field underneath contains the name of the script to export, and is pre-populated based on the - .mesh selection on the first page.
- Material Prefix: Optional prefix to give the name of each material.
- Copy Textures To Folder: If selected, any textures referenced in your materials will be - copied into the same folder as the .material script.
-
- page3
-
- Export Skeleton: If checked, skeleton and animation will be exported. Cannot be selected if no skeleton is referenced by this mesh. The field underneath - determines the target.skeleton file (pre-populated based on the mesh name).
- Frames per second: How to translate XSI frames into time values. Will be populated based on XSI's playback speed, but you can alter it if you wish.
- Animations: This is a list of animations, which should be pre-populated with what you have in the Mixer, with splits between multiple animations 'best guessed' by - the exporter, but you can tweak them afterwards. You can alter all the fields in the table.
- Export?: A checkbox determining whether to export this animation
- Name: The name of the animation.
- Start: The first frame of the animation
- End: The last frame of the animation
- Sample Freq: Skeletal animation which is based on Inverse Kinematics (IK) or other - constraints needs to be 'sampled' to turn it into Forward Kinematics (FK) in OGRE. This option determines the number of frames between each sample. For - vertex animation, this is ignored.
-
- Back To Top
-
- Back To Top -

Using the Export Command

- It is now possible to automate the exporting process by using 'OgreMeshExportCommand' from a script in Softimage. Below is a list of parameters of that command: -
    -
  1. targetMeshFileName: Exported mesh file name (default: "c:/default.mesh")
  2. -
  3. - mergeSubmeshes: Merge objects with same material? If false, a separate named SubMesh will be created for every PolygonMesh preserving your model divisions. If true, the exporter will merge all PolygonMesh objects with - the same material, which is more efficient, but does not preserve your modelling divisions. (default: true) -
  4. -
  5. exportChildren: If true, children of all selected objects will be exported.(default: true)
  6. -
  7. calculateEdgeLists: Calculate Edge Lists (stencil shadows). (default: true)
  8. -
  9. calculateTangents: Calculate Tangents (normal mapping). (default: false)
  10. -
  11. tangentSemantic: Tangent semantic. True for tangent, false for texture coords. (default: true)
  12. -
  13. tangentsSplitMirrored: Split tangents at UV mirror. (default: false)
  14. -
  15. tangentsSplitRotated: Split tangents at UV rotation. (default: false)
  16. -
  17. tangentsUseParity: 4D Tangents. (default: false)
  18. -
  19. numLodLevels: Levels of Detail. (default: 0)
  20. -
  21. lodDistanceIncrement: Distance Increment. (default: 2000)
  22. -
  23. lodQuota: Reduction Style. True for percentage, false for constant. (default: true)
  24. -
  25. lodReduction: Reduction Value. (default: 50)
  26. -
  27. exportMaterials: Export Materials. (default: true)
  28. -
  29. targetMaterialFileName: Material Filename. (default: "c:/default.material")
  30. -
  31. materialPrefix: Material Prefix. (default: "")
  32. -
  33. copyTextures: Copy Textures To Folder. (default: true)
  34. -
  35. exportVertexAnimation: Export Vertex Animation. (default: true)
  36. -
  37. exportSkeleton: Export Skeleton. (default: true)
  38. -
  39. targetSkeletonFilename: Skeleton Filename. (default: "c:/default.skeleton")
  40. -
  41. fps: Frames per second. (default: 24)
  42. -
  43. animationList: List of animations to be exported. Use GridData to populate the values. (default: null)
  44. -
- Back To Top
-
-

Tips

-

Important modelling / animating considerations:

-
    -
  1. The exporter writes one SubMesh per material if 'Merge objects with the same material' is selected. If unselected, you get one SubMesh per PolygonMesh (or clusters with differing materials within them)
  2. -
  3. The exporter writes all your export settings into a custom property in your scene, meaning that all your preferences are remembered for this scene, even between loads.
  4. -
  5. The exporter only exports PolygonMesh objects, so if you work with higher-order surfaces like NURBS you must create a PolygonMesh object from these surfaces before exporting
  6. -
  7. The exporter writes a single .mesh at a time and combines all the objects selected (and their children, if you select that option)
  8. -
  9. All global modelling coordinates are preserved, so the origin of your resulting .mesh will be where the world origin is in XSI
  10. -
  11. Animations must be placed in the mixer to be picked up by the exporter
  12. -
  13. The exporter automatically samples any skeletal IK animation and turns it in to FK, optimising the animation as it does it to remove redundant keys and tracks.
  14. -
  15. - Shape animation should be expressed in shape reference mode 'Local' if you expect the results to work in combination with skeletal animation. If you don't use skeletal animation, either 'Local' or 'Object' will work. You - shouldn't use 'Absolute' mode. -
  16. -
  17. - Make sure you remove any active shape key composition on the modifier stack for your meshes before exporting, they can mess up the initial base state of the mesh as seen by the exporter, since the shape keys are relative to - the mesh before this composition. -
  18. -
- Important material considerations:
-
    -
  • The defaults that XSI gives to some real time material components are not normally what you'd want (and not the OGRE default). For example:
  • -
      -
    • OGLDraw and DXDraw objects have a default culling mode of 'None', meaning all materials are double-sided by default, you will probably want to change that for efficiency
    • -
    • - OGLTexture and DXTexture both default to no mip mapping. You will probably want to alter the defaults so that you have at least sampled point mipmapping (in DXTexture this is a separate setting, in OGLTexture it's - combined with the minification filter) -
    • -
    -
- Back To Top -

Change Log

-

1.7.0

-
    -
  • Fixed a bug causing the bounding box to be larger than it should when selecting multiple meshes for export
  • -
  • Added subdivision support
  • -
  • Hidden polygon clusters will now not be exported
  • -
  • Added a command to export from the script without invoking the export dialog
  • -
-

1.4.6

-
    -
  • Fix a bug when using advanced rigs where there are extra animation components, previously these were stripped out.
  • -
  • Default the file name parameters to the name of the object(s) selected
  • -
  • Deal with omission of file extensions gracefully
  • -
  • Keep mesh/skeleton/material file names in sync when changing the mesh name in all cases
  • -
-

1.4.0

-
    -
  • Fixed pose animation for models not located at the origin
  • -
  • XSI v6 supported
  • -
-

1.2.0RC2

-
    -
  • Fixed translation and scale animation in skeletons
  • -
  • Fixed vertex colour export
  • -
  • Animations which take the skeleton outside the original mesh bounds will now pad the mesh bounds automatically
  • -
-

1.1.0

-
    -
  • - Shape animation support. You can now use the Shape Manager to define shape keys, and then place them in animations in the mixer at varying weights and combine them, e.g. to make facial animation. The exporter creates 'pose' - animation in OGRE from this. -
  • -
  • - Animation is now picked up from the mixer, not directly from action sources. This is to allow a consistent approach to both skeletal and vertex animation. Multiple animations must be split up in timeline start/end frame - pairs. -
  • -
-

1.0.6a

-
    -
  • Significant optimisation allowing larger meshes to be exported quicker (approx 15x faster per 1,000 faces than 1.0.6).
  • -
-

1.0.6

-
    -
  • Don't export clusters that become empty because triangles have been assigned to other clusters to customise material ID
  • -
  • Fix vertex bone assignments on vertices on the boundary of multiple clusters
  • -
  • Added XSI v5 support
  • -
-

1.0.5

-
    -
  • Fix export of multiple animations where initial pose is different
  • -
  • Material prefix should apply to the exported .mesh as well as the .material
  • -
-

1.0.3

-
    -
  • Don't crash if textures are not found, just warn instead.
  • -
  • Trap cases where too many texture coordinate sets are used and terminate with error, rather than crash
  • -
-

-
- 1.0.1c
-

-
    -
  • Added material exporting
  • -
  • Added animation sampling (handle IK, other constraints seamlessly)
  • -
  • Fixed vertex output format for software skinning
  • -
  • Fixed a problem with translation keyframes
  • -
  • Added optimisation of resulting animations (eliminate identity tracks, collapse identical keyframes)
  • -
  • Fixed frame -> time conversion with varying Action bases
  • -
  • Reorganised GUI a little
  • -
  • Deal with case-insensitive fcurve references
  • -
  • Linux build fixes
  • -
-

Back To Top

-

Reporting Issues

-

Please report any issues with the exporter in the OGRE Forums.

-

 Back To Top

- - diff --git a/Tools/XSIExport/OgreXSIExport.sln b/Tools/XSIExport/OgreXSIExport.sln deleted file mode 100644 index 471cb699f21..00000000000 --- a/Tools/XSIExport/OgreXSIExport.sln +++ /dev/null @@ -1,28 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 7.00 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "OgreMain", "..\..\OgreMain\scripts\OgreMain.vcproj", "{35AFBABB-DF05-43DE-91A7-BB828A874015}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "XSIExport", "scripts\XSIExport.vcproj", "{E7E7662C-4EBD-47A7-9EA6-CBA40FE63463}" -EndProject -Global - GlobalSection(SolutionConfiguration) = preSolution - ConfigName.0 = Debug - ConfigName.1 = Release - EndGlobalSection - GlobalSection(ProjectDependencies) = postSolution - {E7E7662C-4EBD-47A7-9EA6-CBA40FE63463}.0 = {35AFBABB-DF05-43DE-91A7-BB828A874015} - EndGlobalSection - GlobalSection(ProjectConfiguration) = postSolution - {35AFBABB-DF05-43DE-91A7-BB828A874015}.Debug.ActiveCfg = Debug|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.Debug.Build.0 = Debug|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.Release.ActiveCfg = Release|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.Release.Build.0 = Release|Win32 - {E7E7662C-4EBD-47A7-9EA6-CBA40FE63463}.Debug.ActiveCfg = Debug|Win32 - {E7E7662C-4EBD-47A7-9EA6-CBA40FE63463}.Debug.Build.0 = Debug|Win32 - {E7E7662C-4EBD-47A7-9EA6-CBA40FE63463}.Release.ActiveCfg = Release|Win32 - {E7E7662C-4EBD-47A7-9EA6-CBA40FE63463}.Release.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - EndGlobalSection - GlobalSection(ExtensibilityAddIns) = postSolution - EndGlobalSection -EndGlobal diff --git a/Tools/XSIExport/OgreXSIExport.suo b/Tools/XSIExport/OgreXSIExport.suo deleted file mode 100644 index 456208a1555..00000000000 Binary files a/Tools/XSIExport/OgreXSIExport.suo and /dev/null differ diff --git a/Tools/XSIExport/OgreXSIExport_vc8.sln b/Tools/XSIExport/OgreXSIExport_vc8.sln deleted file mode 100644 index 15e1fff9c61..00000000000 --- a/Tools/XSIExport/OgreXSIExport_vc8.sln +++ /dev/null @@ -1,28 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 9.00 -# Visual C++ Express 2005 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "OgreMain", "..\..\OgreMain\scripts\OgreMain_vc8.vcproj", "{35AFBABB-DF05-43DE-91A7-BB828A874015}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "XSIExport", "scripts\XSIExport_vc8.vcproj", "{E7E7662C-4EBD-47A7-9EA6-CBA40FE63463}" - ProjectSection(ProjectDependencies) = postProject - {35AFBABB-DF05-43DE-91A7-BB828A874015} = {35AFBABB-DF05-43DE-91A7-BB828A874015} - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {35AFBABB-DF05-43DE-91A7-BB828A874015}.Debug|Win32.ActiveCfg = Debug|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.Debug|Win32.Build.0 = Debug|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.Release|Win32.ActiveCfg = Release|Win32 - {35AFBABB-DF05-43DE-91A7-BB828A874015}.Release|Win32.Build.0 = Release|Win32 - {E7E7662C-4EBD-47A7-9EA6-CBA40FE63463}.Debug|Win32.ActiveCfg = Debug|Win32 - {E7E7662C-4EBD-47A7-9EA6-CBA40FE63463}.Debug|Win32.Build.0 = Debug|Win32 - {E7E7662C-4EBD-47A7-9EA6-CBA40FE63463}.Release|Win32.ActiveCfg = Release|Win32 - {E7E7662C-4EBD-47A7-9EA6-CBA40FE63463}.Release|Win32.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/Tools/XSIExport/OgreXSIExport_vc8.suo b/Tools/XSIExport/OgreXSIExport_vc8.suo deleted file mode 100644 index 443e563397f..00000000000 Binary files a/Tools/XSIExport/OgreXSIExport_vc8.suo and /dev/null differ diff --git a/Tools/XSIExport/Readme.md b/Tools/XSIExport/Readme.md deleted file mode 100644 index dcc1d41d568..00000000000 --- a/Tools/XSIExport/Readme.md +++ /dev/null @@ -1,5 +0,0 @@ - -# XSI Exporter README file - -You can read the HTML Readme at this link: - - [XSI Exporter README file](https://htmlpreview.github.io/?https://github.com/OGRECave/ogre/blob/master/Tools/XSIExport/OGREXSI_Readme.html) diff --git a/Tools/XSIExport/bootstrap b/Tools/XSIExport/bootstrap deleted file mode 100644 index d2a6bd03a32..00000000000 --- a/Tools/XSIExport/bootstrap +++ /dev/null @@ -1,3 +0,0 @@ -aclocal -autoconf -a -automake diff --git a/Tools/XSIExport/configure.in b/Tools/XSIExport/configure.in deleted file mode 100644 index 2ba9b8bd665..00000000000 --- a/Tools/XSIExport/configure.in +++ /dev/null @@ -1,15 +0,0 @@ -AC_PREREQ(2.50) - -AC_INIT([XSIExport], [1.0]) - -AC_CANONICAL_TARGET - -AM_INIT_AUTOMAKE([XSIExport], [1.0]) - -AC_PROG_CC -AC_PROG_CXX -AC_PROG_INSTALL - -AM_PROG_LIBTOOL - -AC_OUTPUT(Makefile src/Makefile) diff --git a/Tools/XSIExport/include/OgreXSIHelper.h b/Tools/XSIExport/include/OgreXSIHelper.h deleted file mode 100644 index d747130222d..00000000000 --- a/Tools/XSIExport/include/OgreXSIHelper.h +++ /dev/null @@ -1,261 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __XSIHELPER_H__ -#define __XSIHELPER_H__ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include "OgrePrerequisites.h" -#include "OgreString.h" -#include "OgreColourValue.h" -#include "OgreLogManager.h" -#include "OgreStringVector.h" -#include "OgreSingleton.h" -#include "OgreVector.h" -#include "OgreQuaternion.h" -#include "OgreHardwareVertexBuffer.h" - -#define OGRE_XSI_NUM_MESH_STEPS 200 - -/// Useful function to convert XSI CValue to an Ogre String -/* -inline Ogre::String XSItoOgre(const XSI::CValue& xsival) -{ - - switch(xsival.m_t) - { - case XSI::CValue::siString: - return XSItoOgre(XSI::CString(xsival)); - case XSI::CValue::siVector3: - return XSItoOgre(XSI::MATH::CVector3(xsival)); - default: - return XSItoOgre(XSI::CString(xsival.GetAsText())); - }; - -} -*/ - -/// Useful function to convert an XSI CString to an Ogre String -inline Ogre::String XSItoOgre(const XSI::CString& xsistr) -{ - // XSI CString is wide character - - if (xsistr.IsEmpty()) - { - return Ogre::BLANKSTRING; - } - - // first find out the size required - size_t c = ::wcstombs(0, xsistr.GetWideString(), 2048); - // temp character string (add one for terminator) - char* tmp = new char[c+1]; - // do the real conversion - ::wcstombs(tmp, xsistr.GetWideString(), c); - tmp[c] = '\0'; - Ogre::String ret(tmp); - delete [] tmp; - - return ret; -} -/// Useful function to convert an Ogre String to an XSI CString -inline XSI::CString OgretoXSI(const Ogre::String& str) -{ - // XSI CString is wide character - - if (str.empty()) - { - return XSI::CString(); - } - - // first find out the size required - size_t c = ::mbstowcs(0, str.c_str(), 2048); - // temp character string (add one for terminator) - wchar_t* tmp = new wchar_t[c+1]; - // do the real conversion - ::mbstowcs(tmp, str.c_str(), c); - tmp[c] = '\0'; - - XSI::CString ret(tmp); - delete [] tmp; - - return ret; -} - -inline Ogre::Vector3 XSItoOgre(const XSI::MATH::CVector3& xsiVec) -{ - return Ogre::Vector3(xsiVec.GetX(), xsiVec.GetY(), xsiVec.GetZ()); -} -inline Ogre::Quaternion XSItoOgre(const XSI::MATH::CQuaternion& xsiQuat) -{ - return Ogre::Quaternion(xsiQuat.GetW(), xsiQuat.GetX(), xsiQuat.GetY(), xsiQuat.GetZ()); -} - -inline Ogre::RGBA XSItoOgre(const XSI::CVertexColor& xsiColour) -{ - Ogre::ColourValue col(xsiColour.r / 255.0f, xsiColour.g / 255.0f, - xsiColour.b / 255.0f, xsiColour.a / 255.0f); - return Ogre::VertexElement::convertColourValue(col, - Ogre::VertexElement::getBestColourVertexElementType()); -} - -inline void LogOgreAndXSI(const Ogre::String& msg) -{ - static XSI::Application app; - Ogre::LogManager::getSingleton().logMessage(msg); - app.LogMessage(OgretoXSI(msg)); - -} - -inline void LogOgreAndXSI(const XSI::CString& msg) -{ - static XSI::Application app; - Ogre::LogManager::getSingleton().logMessage(XSItoOgre(msg)); - app.LogMessage(msg); - -} - -inline void LogOgreAndXSI(const char *msg) -{ - LogOgreAndXSI(Ogre::String(msg)); -} - -namespace Ogre { - - class ProgressManager : public Singleton - { - protected: - XSI::ProgressBar mProgressBar; - size_t mNumberOfStages; - size_t mProgress; - - public: - ProgressManager(size_t numberOfStages); - virtual ~ProgressManager(); - - void progress(void); - - static ProgressManager& getSingleton(void); - static ProgressManager* getSingletonPtr(void); - - }; - - enum XSITrackType - { - XTT_POS_X = 0, - XTT_POS_Y = 1, - XTT_POS_Z = 2, - XTT_ROT_X = 3, - XTT_ROT_Y = 4, - XTT_ROT_Z = 5, - XTT_SCL_X = 6, - XTT_SCL_Y = 7, - XTT_SCL_Z = 8, - XTT_COUNT = 9 - }; - /** An entry for a Deformer - need original index because this will be boneID */ - class DeformerEntry - { - public: - unsigned short boneID; - XSI::X3DObject obj; - String parentName; - StringVector childNames; - bool hasVertexAssignments; - bool parentIsChainEndEffector; - bool hasAnyTracks; - Bone* pBone; - bool ikSample; - double ikSampleInterval; - XSI::MATH::CTransformation initialXform; - // lists of action source items (probably only one per param?) - XSI::AnimationSourceItem xsiTrack[XTT_COUNT]; - - DeformerEntry(unsigned short theboneID, XSI::X3DObject& theobj) - :boneID(theboneID), obj(theobj), hasVertexAssignments(false), - parentIsChainEndEffector(false), hasAnyTracks(false), pBone(0) - - { - } - - }; - /// Map from deformer name to deformer entry - typedef std::map DeformerMap; - - - /** An entry for animation; allows the userto split the timeline into - multiple separate animations. - */ - struct AnimationEntry - { - String animationName; - long startFrame; - long endFrame; - double ikSampleInterval; // skeletal only - }; - /// List of animations - typedef std::list AnimationList; - - /** Record of an XSI GL shader material. */ - struct MaterialEntry - { - String name; - XSI::Shader xsiShader; - }; - /// Map from material name to material entry - typedef std::map MaterialMap; - - /** Record of XSI details that are to become a pass */ - struct PassEntry - { - XSI::CRefArray shaders; - }; - typedef std::deque PassQueue; - - /// Map from texture projection name to index - typedef std::map TextureProjectionMap; - - /** Platform-independent file copy (destination folder must exist) - Maybe use Boost::filesystem if this gets out of hand - */ - void copyFile(const String& src, const String& dest); - -} -#endif - diff --git a/Tools/XSIExport/include/OgreXSIMaterialExporter.h b/Tools/XSIExport/include/OgreXSIMaterialExporter.h deleted file mode 100644 index a79cf85e0ba..00000000000 --- a/Tools/XSIExport/include/OgreXSIMaterialExporter.h +++ /dev/null @@ -1,108 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __XSIMATERIALEXPORTER_H__ -#define __XSIMATERIALEXPORTER_H__ - -#include "OgreXSIHelper.h" -#include "OgreBlendMode.h" -#include "OgreMaterialSerializer.h" - -namespace Ogre { - - class XsiMaterialExporter - { - public: - XsiMaterialExporter(); - virtual ~XsiMaterialExporter(); - - /** Export a set of XSI materials to a material script. - @param materials List of materials to export - @param filename Name of the script file to create - @param copyTextures Whether to copy any textures used into the same - folder as the material script. - */ - void exportMaterials(MaterialMap& materials, TextureProjectionMap& texProjMap, - const String& filename, bool copyTextures); - protected: - MaterialSerializer mMatSerializer; - - typedef std::multimap TextureUnitTargetMap; - /// Map of target id -> texture unit to match up tex transforms - TextureUnitTargetMap mTextureUnitTargetMap; - /// Pass queue, used to invert ordering - PassQueue mPassQueue; - /// Texture projection map - TextureProjectionMap mTextureProjectionMap; - - - // Export a single material - void exportMaterial(MaterialEntry* matEntry, bool copyTextures, - const String& texturePath); - /// Fill in all the details of a pass - void populatePass(Pass* pass, XSI::Shader& xsishader); - /// Fill in the texture units - note this won't pick up transforms yet - void populatePassTextures(Pass* pass, PassEntry* passEntry, - bool copyTextures, const String& texturePath); - /// Find any texture transforms and hook them up via 'target' - void populatePassTextureTransforms(Pass* pass, XSI::Shader& xsishader); - /// Populate basic rejection parameters for the pass - void populatePassDepthCull(Pass* pass, XSI::Shader& xsishader); - /// Populate lighting parameters for the pass - void populatePassLighting(Pass* pass, XSI::Shader& xsishader); - /// Populate scene blending parameters for the pass - void populatePassSceneBlend(Pass* pass, XSI::Shader& xsishader); - void populatePassCgPrograms(Pass* pass, XSI::Shader& xsishader); - void populatePassHLSLPrograms(Pass* pass, XSI::Shader& xsishader); - void populatePassD3DAssemblerPrograms(Pass* pass, XSI::Shader& xsishader); - void populateOGLFiltering(TextureUnitState* tex, XSI::Shader& xsishader); - void populateDXFiltering(TextureUnitState* tex, XSI::Shader& xsishader); - - - // Utility method to get texture coord set from tspace_id name - unsigned short getTextureCoordIndex(const String& tspace); - - /// Add a 2D texture from a shader - TextureUnitState* add2DTexture(Pass* pass, XSI::Shader& shader, - bool copyTextures, const String& targetFolder); - /// Add a cubic texture from a shader - TextureUnitState* addCubicTexture(Pass* pass, XSI::Shader& shader, - bool copyTextures, const String& targetFolder); - - - void clearPassQueue(void); - - SceneBlendFactor convertSceneBlend(short xsiVal); - TextureAddressingMode convertAddressingMode(short xsiVal); - void convertTexGenOGL(TextureUnitState* tex, long xsiVal, XSI::Shader& shader); - void convertTexGenDX(TextureUnitState* tex, long xsiVal, XSI::Shader& shader); - }; -} - -#endif - - diff --git a/Tools/XSIExport/include/OgreXSIMeshExporter.h b/Tools/XSIExport/include/OgreXSIMeshExporter.h deleted file mode 100644 index c856ad8b585..00000000000 --- a/Tools/XSIExport/include/OgreXSIMeshExporter.h +++ /dev/null @@ -1,345 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __XSIMESHEXPORTER_H__ -#define __XSIMESHEXPORTER_H__ - -#include "OgrePrerequisites.h" -#include "OgreVector.h" -#include "OgreColourValue.h" -#include "OgreMesh.h" -#include "OgreProgressiveMesh.h" -#include "OgreXSIHelper.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace Ogre { - - /** Class for performing a mesh export from XSI. - */ - class XsiMeshExporter - { - public: - XsiMeshExporter(); - virtual ~XsiMeshExporter(); - - struct LodData - { - Mesh::LodValueList distances; - ProgressiveMesh::VertexReductionQuota quota; - Real reductionValue; - }; - - - - - /** Build an OGRe mesh ready for export. - - Every PolygonMesh object is exported as a different SubMesh. Other - object types are ignored. - @param mergeSubMeshes Whether to merge submeshes with the same material - @param exportChildren Whether to cascade down each objects children - @param edgeLists Whether to calculate edge lists - @param tangents Whether to calculate tangents - @param animList List of animations in use (of any type) - @param materialPrefix Prefix to give all materials - @param lod LOD generation parameters (if required) - @param skeletonName Name of the skeleton to link to if animated - @returns List of deformers (bones) which were found whilst exporting (if - skeletonName was provided) which can be used to determine the skeleton. - */ - DeformerMap& buildMeshForExport( - bool mergeSubMeshes, bool exportChildren, bool edgeLists, - bool tangents, VertexElementSemantic tangentSemantic, bool tangentsSplitMirrored, bool tangentsSplitRotated, bool tangentsUseParity, - bool vertexAnimation, AnimationList& animList, Real fps, const String& materialPrefix = BLANKSTRING, - LodData* lod = 0, const String& skeletonName = ""); - - /** Perform final export of built mesh. - @param fileName Target file name - @param skelAABB AABB of skeleton bones as found in animation, to pad - final bounds of mesh. - */ - void exportMesh(const String& fileName, const AxisAlignedBox& skelAABB); - - /** Get a list of materials which were located during the last call - * to exportMesh. - */ - MaterialMap& getMaterials(void); - - /** Get the map from texture projection names to uv indexes. */ - TextureProjectionMap& getTextureProjectionMap(void); - protected: - MeshPtr mMesh; - // XSI Objects - XSI::Application mXsiApp; - /** This struct represents a unique vertex, identified from a unique - combination of components. - */ - class UniqueVertex - { - public: - Vector3 position; - Vector3 normal; - Vector3 uv[OGRE_MAX_TEXTURE_COORD_SETS]; - RGBA colour; - // The index of the next component with the same base details - // but with some variation - size_t nextIndex; - - UniqueVertex(); - bool operator==(const UniqueVertex& rhs) const; - - }; - typedef std::vector UniqueVertexList; - // dynamic index list; 32-bit until we know the max vertex index - typedef std::vector IndexList; - - /** An entry for a PolygonMesh - need the parent X3DObject too */ - class PolygonMeshEntry - { - public: - XSI::CString name; - XSI::MATH::CTransformation transform; - XSI::CGeometryAccessor geometry; - - - PolygonMeshEntry(XSI::CString _name, XSI::MATH::CTransformation _transform, XSI::CGeometryAccessor _geometry) - : name(_name) - , transform(_transform) - , geometry(_geometry) - { - } - - }; - /// ordering function, required for set - struct PolygonMeshEntryLess - { - bool operator()(PolygonMeshEntry* lhs, PolygonMeshEntry* rhs) - { - // can't name objects the same in XSI, so use that - return XSItoOgre(lhs->name) < XSItoOgre(rhs->name); - } - }; - - /** Set of polygon mesh objects we're going to process - * Use a set to avoid exporting the same object twice when manually selected - * and as a child of a selected object. - */ - typedef std::set PolygonMeshList; - PolygonMeshList mXsiPolygonMeshList; - - - - /// List of deformers we've found whilst parsing the objects - DeformerMap mXsiDeformerMap; - /// LIst of materials we've found whilst parsing the objects - MaterialMap mXsiMaterialMap; - /// Map from texture projection names to uv index - TextureProjectionMap mTextureProjectionMap; - /// Material prefix - String mMaterialPrefix; - - - /// Build a list of PolygonMesh instances from selection - void buildPolygonMeshList(bool includeChildren); - /// Tidy up - void cleanupPolygonMeshList(void); - /// Recursive method to locate PolygonMeshes - void findPolygonMeshes(XSI::X3DObject& x3dObj, bool recurse); - /// Build the mesh - void buildMesh(Mesh* pMesh, bool mergeSubmeshes, bool lookForBoneAssignments, - bool vertexAnimation, AnimationList& animList, Real fps); - /// Process a single PolygonMesh into one or more ProtoSubMeshes - void processPolygonMesh(Mesh* pMesh, PolygonMeshEntry* pm, bool lookForBoneAssignments, unsigned short progressUpdates); - /// Find deformers and bone assignments - void processBoneAssignments(Mesh* pMesh, PolygonMeshEntry* pm); - /// Find shape keys for a given mesh - void processShapeKeys(Mesh* pMesh, PolygonMeshEntry* pm); - - /// Tidy up - void cleanupDeformerMap(void); - void cleanupMaterialMap(void); - - typedef std::map IndexRemap; - /** Working area which will become a submesh once we've finished figuring - out what goes in there. - */ - struct ProtoSubMesh - { - // Name of the submesh (may be blank if we're merging) - String name; - // Material name - String materialName; - // unique vertex list - UniqueVertexList uniqueVertices; - // Defines number of texture coord sets and their dimensions - std::vector textureCoordDimensions; - // Vertex colours? - bool hasVertexColours; - // Last polymesh entry added to this proto - PolygonMeshEntry* lastMeshEntry; - // Index offset for last polymesh entry - size_t lastMeshIndexOffset; - // index list - IndexList indices; - // map of polygon mesh -> position index offset (only > 0 when submeshes merged) - typedef std::map PolygonMeshOffsetMap; - PolygonMeshOffsetMap polygonMeshOffsetMap; - // map original position index (+any PM offset) -> first real instance in this one - IndexRemap posIndexRemap; - Mesh::VertexBoneAssignmentList boneAssignments; - /// By-value pose list, build up ready for transfer later - std::list poseList; - /// List of XSI shape keys which are being used in this proto - XSI::CRefArray shapeKeys; - - ProtoSubMesh() : lastMeshEntry(0), lastMeshIndexOffset(0) {} - - - }; - - /// Global shape key to pose mapping - struct ShapeKeyToPoseEntry - { - XSI::CRef shapeKey; - size_t poseIndex; - size_t targetHandle; - - }; - typedef std::list ShapeKeyMapping; - ShapeKeyMapping mShapeKeyMapping; - - struct ShapeClipEntry - { - XSI::Clip clip; - ShapeKeyToPoseEntry* keytoPose; - long startFrame; - long endFrame; - long originalStartFrame; // in case clamped - }; - typedef std::list ShapeClipList; - - - /// List of ProtoSubMeshes that use the same material but are not geometrically compatible - typedef std::list ProtoSubMeshList; - - /// List of proto submeshes by material - typedef std::map MaterialProtoSubMeshMap; - - /// List of proto submeshes by material - MaterialProtoSubMeshMap mMaterialProtoSubmeshMap; - - /// List of deviant proto submeshes by polygon index (clusters) - typedef std::map PolygonToProtoSubMeshList; - - /// List of deviant proto submeshes by polygon index (clusters) - PolygonToProtoSubMeshList mPolygonToProtoSubMeshList; - - // Holds PolygonMesh texture coord information - typedef std::vector TextureCoordDimensionList; - - // Holds PolygonMesh sampler-ordered UV information - typedef std::vector SamplerSetList; - - /// Export the current list of proto submeshes, and clear list - void exportProtoSubMeshes(Mesh* pMesh); - /// Export a single ProtoSubMesh - void exportProtoSubMesh(Mesh* pMesh, ProtoSubMesh* proto); - /// Export vertex animations - void exportAnimations(Mesh* pMesh, AnimationList& animList, Real fps); - /// Build a list of all shape clips - void buildShapeClipList(ShapeClipList& listToPopulate); - /// Build a list of all shape clips in a container - void buildShapeClipList(XSI::ClipContainer& container, ShapeClipList& listToPopulate); - /// Build a derived clip list for just a specific submesh, and a list of keys to sample - void deriveShapeClipAndKeyframeList(ushort targetIndex, - AnimationEntry& animEntry, ShapeClipList& inClipList, - ShapeClipList& outClipList, std::set& keyFrameList); - /// Retrieve a ProtoSubMesh for the given material name - /// (creates if required, validates if re-using) - ProtoSubMesh* createOrRetrieveProtoSubMesh(const String& materialName, - const String& name, TextureCoordDimensionList& texCoordDims, - bool hasVertexColours); - - /** Try to look up an existing vertex with the same information, or - create a new one. - - Note that we build up the list of unique position indexes that are - actually used by each ProtoSubMesh as we go. When new positions - are found, they are added and a remap entry created to take account - of the fact that there may be extra vertices created in between, or - there may be gaps due to clusters meaning not every position is - used by every ProtoSubMesh. When an existing entry is found, we - compare the vertex data, and if it differs, create a new vertex and - 'chain' it to the previous instances of this position index through - nextIndex. This means that every position vertex has a single - remapped starting point in the per-ProtoSubMesh vertex list, and a - unidirectional linked list of variants of that vertex where other - components differ. - @par - Note that this re-uses as many vertices as possible, and also places - every unique vertex in it's final index in one pass, so the return - value from this method can be used as an adjusted vertex index. - @returns The index of the unique vertex - */ - size_t createOrRetrieveUniqueVertex(ProtoSubMesh* proto, - size_t positionIndex, bool positionIndexIsOriginal, - const UniqueVertex& vertex); - - /** Templatised method for writing indexes */ - template void writeIndexes(T* buf, IndexList& indexes); - - /** Create and fill a vertex buffer */ - void createVertexBuffer(VertexData* vd, unsigned short bufIdx, - UniqueVertexList& uniqueVertexList); - - /** Find out the sampler indices for the given triangle */ - void deriveSamplerIndices(const XSI::Triangle& tri, const XSI::PolygonFace& face, - size_t* samplerIndices); - /** Get a single sampler index */ - size_t getSamplerIndex(const XSI::Facet &f, const XSI::Point &p); - - /** Register the use of a given XSI material. */ - void registerMaterial(const String& name, XSI::Material mat); - - }; - -} -#endif - diff --git a/Tools/XSIExport/include/OgreXSISkeletonExporter.h b/Tools/XSIExport/include/OgreXSISkeletonExporter.h deleted file mode 100644 index ccae3da2696..00000000000 --- a/Tools/XSIExport/include/OgreXSISkeletonExporter.h +++ /dev/null @@ -1,114 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#ifndef __XSISKELETONEXPORTER_H__ -#define __XSISKELETONEXPORTER_H__ - -#include "OgrePrerequisites.h" -#include "OgreVector.h" -#include "OgreAxisAlignedBox.h" -#include "OgreXSIHelper.h" -#include -#include -#include -#include -#include - - -namespace Ogre { - - /** Class for performing a skeleton export from XSI. - */ - class XsiSkeletonExporter - { - public: - XsiSkeletonExporter(); - virtual ~XsiSkeletonExporter(); - - - /** Export a skeleton to the provided filename. - @param skeletonFileName The file name to export to - @param deformers The list of deformers (bones) found during mesh traversal - @param framesPerSecond The number of frames per second - @param animList List of animation splits - @returns AABB derived from bone animations, should be used to pad mesh bounds - */ - const AxisAlignedBox& exportSkeleton(const String& skeletonFileName, - DeformerMap& deformers, float framesPerSecond, - AnimationList& animList); - protected: - // XSI Objects - XSI::Application mXsiApp; - XSI::X3DObject mXsiSceneRoot; - std::map mXSITrackTypeNames; - // Lower-case version of deformer map (XSI seems to be case insensitive and - // some animations rely on that!) - DeformerMap mLowerCaseDeformerMap; - // Actions created as part of IK sampling, will be deleted afterward - XSI::CStringArray mIKSampledAnimations; - AxisAlignedBox mAABB; - - /// Build the bone hierarchy from a simple list of bones - void buildBoneHierarchy(Skeleton* pSkeleton, DeformerMap& deformers, - AnimationList& animList); - /** Link the current bone with it's parent - */ - void linkBoneWithParent(DeformerEntry* deformer, - DeformerMap& deformers, std::list& deformerList); - /** Validate and create a bone, or eliminate the current bone if it - has no animated parameters - */ - void validateAsBone(Skeleton* pSkeleton, DeformerEntry* deformer, - DeformerMap& deformers, std::list& deformerList, - AnimationList& animList); - /// Process an action source - void processActionSource(const XSI::ActionSource& source, DeformerMap& deformers); - /// Bake animations - void createAnimations(Skeleton* pSkel, DeformerMap& deformers, - float framesPerSecond, AnimationList& animList, AxisAlignedBox& AABBPadding); - /// Bake animation tracks by sampling - void createAnimationTracksSampled(Animation* pAnim, AnimationEntry& animEntry, - DeformerMap& deformers, float fps, AxisAlignedBox& AABBPadding); - - void cleanup(void); - void copyDeformerMap(DeformerMap& deformers); - /// Get deformer from passed in map or lower case version - DeformerEntry* getDeformer(const String& name, DeformerMap& deformers); - // Sample all bones, and also sample max global bone position for AABB padding - void sampleAllBones(DeformerMap& deformers, - std::vector deformerTracks, double frame, - Real time, float fps, AxisAlignedBox& AABBPadding); - void establishInitialTransforms(DeformerMap& deformers); - - }; - - - -} - - -#endif diff --git a/Tools/XSIExport/misc/OgreXSIExport.def b/Tools/XSIExport/misc/OgreXSIExport.def deleted file mode 100644 index 91c06cc33d7..00000000000 --- a/Tools/XSIExport/misc/OgreXSIExport.def +++ /dev/null @@ -1,10 +0,0 @@ -EXPORTS - XSILoadPlugin @1 PRIVATE - XSIUnloadPlugin @2 PRIVATE - OgreMeshExportCommand_Init @3 PRIVATE - OgreMeshExportCommand_Execute @4 PRIVATE - OgreMeshExportMenu_Init @5 PRIVATE - OnOgreMeshExportMenu @6 PRIVATE - OgreMeshExportOptions_Define @7 PRIVATE - OgreMeshExportOptions_DefineLayout @8 PRIVATE - OgreMeshExportOptions_PPGEvent @9 PRIVATE diff --git a/Tools/XSIExport/page1.gif b/Tools/XSIExport/page1.gif deleted file mode 100644 index 0dd12fa0f5e..00000000000 Binary files a/Tools/XSIExport/page1.gif and /dev/null differ diff --git a/Tools/XSIExport/page2.gif b/Tools/XSIExport/page2.gif deleted file mode 100644 index f08d7e288c6..00000000000 Binary files a/Tools/XSIExport/page2.gif and /dev/null differ diff --git a/Tools/XSIExport/page3.gif b/Tools/XSIExport/page3.gif deleted file mode 100644 index ee0e4657893..00000000000 Binary files a/Tools/XSIExport/page3.gif and /dev/null differ diff --git a/Tools/XSIExport/scripts/XSIExport.vcproj b/Tools/XSIExport/scripts/XSIExport.vcproj deleted file mode 100644 index 2167696c668..00000000000 --- a/Tools/XSIExport/scripts/XSIExport.vcproj +++ /dev/null @@ -1,163 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/XSIExport/scripts/XSIExport_vc8.vcproj b/Tools/XSIExport/scripts/XSIExport_vc8.vcproj deleted file mode 100644 index ff24ff818b5..00000000000 --- a/Tools/XSIExport/scripts/XSIExport_vc8.vcproj +++ /dev/null @@ -1,258 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/XSIExport/setup/License.rtf b/Tools/XSIExport/setup/License.rtf deleted file mode 100644 index 4ab4ebe1ea7..00000000000 --- a/Tools/XSIExport/setup/License.rtf +++ /dev/null @@ -1,462 +0,0 @@ -{\rtf1\ansi\deff0{\fonttbl{\f0\fswiss\fcharset0 Arial;}} -{\*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\lang1033\f0\fs20\tab\tab GNU LESSER GENERAL PUBLIC LICENSE\par -\tab\tab Version 2.1, February 1999\par -\par - Copyright (C) 1991, 1999 Free Software Foundation, Inc.\par - 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\par - Everyone is permitted to copy and distribute verbatim copies\par - of this license document, but changing it is not allowed.\par -\par -[This is the first released version of the Lesser GPL. It also counts\par - as the successor of the GNU Library Public License, version 2, hence\par - the version number 2.1.]\par -\par -\tab\tab\tab Preamble\par -\par - The licenses for most software are designed to take away your\par -freedom to share and change it. By contrast, the GNU General Public\par -Licenses are intended to guarantee your freedom to share and change\par -free software--to make sure the software is free for all its users.\par -\par - This license, the Lesser General Public License, applies to some\par -specially designated software packages--typically libraries--of the\par -Free Software Foundation and other authors who decide to use it. You\par -can use it too, but we suggest you first think carefully about whether\par -this license or the ordinary General Public License is the better\par -strategy to use in any particular case, based on the explanations below.\par -\par - When we speak of free software, we are referring to freedom of use,\par -not price. Our General Public Licenses are designed to make sure that\par -you have the freedom to distribute copies of free software (and charge\par -for this service if you wish); that you receive source code or can get\par -it if you want it; that you can change the software and use pieces of\par -it in new free programs; and that you are informed that you can do\par -these things.\par -\par - To protect your rights, we need to make restrictions that forbid\par -distributors to deny you these rights or to ask you to surrender these\par -rights. These restrictions translate to certain responsibilities for\par -you if you distribute copies of the library or if you modify it.\par -\par - For example, if you distribute copies of the library, whether gratis\par -or for a fee, you must give the recipients all the rights that we gave\par -you. You must make sure that they, too, receive or can get the source\par -code. If you link other code with the library, you must provide\par -complete object files to the recipients, so that they can relink them\par -with the library after making changes to the library and recompiling\par -it. And you must show them these terms so they know their rights.\par -\par - We protect your rights with a two-step method: (1) we copyright the\par -library, and (2) we offer you this license, which gives you legal\par -permission to copy, distribute and/or modify the library.\par -\par - To protect each distributor, we want to make it very clear that\par -there is no warranty for the free library. Also, if the library is\par -modified by someone else and passed on, the recipients should know\par -that what they have is not the original version, so that the original\par -author's reputation will not be affected by problems that might be\par -introduced by others.\par -\page\par - Finally, software patents pose a constant threat to the existence of\par -any free program. We wish to make sure that a company cannot\par -effectively restrict the users of a free program by obtaining a\par -restrictive license from a patent holder. Therefore, we insist that\par -any patent license obtained for a version of the library must be\par -consistent with the full freedom of use specified in this license.\par -\par - Most GNU software, including some libraries, is covered by the\par -ordinary GNU General Public License. This license, the GNU Lesser\par -General Public License, applies to certain designated libraries, and\par -is quite different from the ordinary General Public License. We use\par -this license for certain libraries in order to permit linking those\par -libraries into non-free programs.\par -\par - When a program is linked with a library, whether statically or using\par -a shared library, the combination of the two is legally speaking a\par -combined work, a derivative of the original library. The ordinary\par -General Public License therefore permits such linking only if the\par -entire combination fits its criteria of freedom. The Lesser General\par -Public License permits more lax criteria for linking other code with\par -the library.\par -\par - We call this license the "Lesser" General Public License because it\par -does Less to protect the user's freedom than the ordinary General\par -Public License. It also provides other free software developers Less\par -of an advantage over competing non-free programs. These disadvantages\par -are the reason we use the ordinary General Public License for many\par -libraries. However, the Lesser license provides advantages in certain\par -special circumstances.\par -\par - For example, on rare occasions, there may be a special need to\par -encourage the widest possible use of a certain library, so that it becomes\par -a de-facto standard. To achieve this, non-free programs must be\par -allowed to use the library. A more frequent case is that a free\par -library does the same job as widely used non-free libraries. In this\par -case, there is little to gain by limiting the free library to free\par -software only, so we use the Lesser General Public License.\par -\par - In other cases, permission to use a particular library in non-free\par -programs enables a greater number of people to use a large body of\par -free software. For example, permission to use the GNU C Library in\par -non-free programs enables many more people to use the whole GNU\par -operating system, as well as its variant, the GNU/Linux operating\par -system.\par -\par - Although the Lesser General Public License is Less protective of the\par -users' freedom, it does ensure that the user of a program that is\par -linked with the Library has the freedom and the wherewithal to run\par -that program using a modified version of the Library.\par -\par - The precise terms and conditions for copying, distribution and\par -modification follow. Pay close attention to the difference between a\par -"work based on the library" and a "work that uses the library". The\par -former contains code derived from the library, whereas the latter must\par -be combined with the library in order to run.\par -\page\par -\tab\tab GNU LESSER GENERAL PUBLIC LICENSE\par - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\par -\par - 0. This License Agreement applies to any software library or other\par -program which contains a notice placed by the copyright holder or\par -other authorized party saying it may be distributed under the terms of\par -this Lesser General Public License (also called "this License").\par -Each licensee is addressed as "you".\par -\par - A "library" means a collection of software functions and/or data\par -prepared so as to be conveniently linked with application programs\par -(which use some of those functions and data) to form executables.\par -\par - The "Library", below, refers to any such software library or work\par -which has been distributed under these terms. A "work based on the\par -Library" means either the Library or any derivative work under\par -copyright law: that is to say, a work containing the Library or a\par -portion of it, either verbatim or with modifications and/or translated\par -straightforwardly into another language. (Hereinafter, translation is\par -included without limitation in the term "modification".)\par -\par - "Source code" for a work means the preferred form of the work for\par -making modifications to it. For a library, complete source code means\par -all the source code for all modules it contains, plus any associated\par -interface definition files, plus the scripts used to control compilation\par -and installation of the library.\par -\par - Activities other than copying, distribution and modification are not\par -covered by this License; they are outside its scope. The act of\par -running a program using the Library is not restricted, and output from\par -such a program is covered only if its contents constitute a work based\par -on the Library (independent of the use of the Library in a tool for\par -writing it). Whether that is true depends on what the Library does\par -and what the program that uses the Library does.\par - \par - 1. You may copy and distribute verbatim copies of the Library's\par -complete source code as you receive it, in any medium, provided that\par -you conspicuously and appropriately publish on each copy an\par -appropriate copyright notice and disclaimer of warranty; keep intact\par -all the notices that refer to this License and to the absence of any\par -warranty; and distribute a copy of this License along with the\par -Library.\par -\par - You may charge a fee for the physical act of transferring a copy,\par -and you may at your option offer warranty protection in exchange for a\par -fee.\par -\page\par - 2. You may modify your copy or copies of the Library or any portion\par -of it, thus forming a work based on the Library, and copy and\par -distribute such modifications or work under the terms of Section 1\par -above, provided that you also meet all of these conditions:\par -\par - a) The modified work must itself be a software library.\par -\par - b) You must cause the files modified to carry prominent notices\par - stating that you changed the files and the date of any change.\par -\par - c) You must cause the whole of the work to be licensed at no\par - charge to all third parties under the terms of this License.\par -\par - d) If a facility in the modified Library refers to a function or a\par - table of data to be supplied by an application program that uses\par - the facility, other than as an argument passed when the facility\par - is invoked, then you must make a good faith effort to ensure that,\par - in the event an application does not supply such function or\par - table, the facility still operates, and performs whatever part of\par - its purpose remains meaningful.\par -\par - (For example, a function in a library to compute square roots has\par - a purpose that is entirely well-defined independent of the\par - application. Therefore, Subsection 2d requires that any\par - application-supplied function or table used by this function must\par - be optional: if the application does not supply it, the square\par - root function must still compute square roots.)\par -\par -These requirements apply to the modified work as a whole. If\par -identifiable sections of that work are not derived from the Library,\par -and can be reasonably considered independent and separate works in\par -themselves, then this License, and its terms, do not apply to those\par -sections when you distribute them as separate works. But when you\par -distribute the same sections as part of a whole which is a work based\par -on the Library, the distribution of the whole must be on the terms of\par -this License, whose permissions for other licensees extend to the\par -entire whole, and thus to each and every part regardless of who wrote\par -it.\par -\par -Thus, it is not the intent of this section to claim rights or contest\par -your rights to work written entirely by you; rather, the intent is to\par -exercise the right to control the distribution of derivative or\par -collective works based on the Library.\par -\par -In addition, mere aggregation of another work not based on the Library\par -with the Library (or with a work based on the Library) on a volume of\par -a storage or distribution medium does not bring the other work under\par -the scope of this License.\par -\par - 3. You may opt to apply the terms of the ordinary GNU General Public\par -License instead of this License to a given copy of the Library. To do\par -this, you must alter all the notices that refer to this License, so\par -that they refer to the ordinary GNU General Public License, version 2,\par -instead of to this License. (If a newer version than version 2 of the\par -ordinary GNU General Public License has appeared, then you can specify\par -that version instead if you wish.) Do not make any other change in\par -these notices.\par -\page\par - Once this change is made in a given copy, it is irreversible for\par -that copy, so the ordinary GNU General Public License applies to all\par -subsequent copies and derivative works made from that copy.\par -\par - This option is useful when you wish to copy part of the code of\par -the Library into a program that is not a library.\par -\par - 4. You may copy and distribute the Library (or a portion or\par -derivative of it, under Section 2) in object code or executable form\par -under the terms of Sections 1 and 2 above provided that you accompany\par -it with the complete corresponding machine-readable source code, which\par -must be distributed under the terms of Sections 1 and 2 above on a\par -medium customarily used for software interchange.\par -\par - If distribution of object code is made by offering access to copy\par -from a designated place, then offering equivalent access to copy the\par -source code from the same place satisfies the requirement to\par -distribute the source code, even though third parties are not\par -compelled to copy the source along with the object code.\par -\par - 5. A program that contains no derivative of any portion of the\par -Library, but is designed to work with the Library by being compiled or\par -linked with it, is called a "work that uses the Library". Such a\par -work, in isolation, is not a derivative work of the Library, and\par -therefore falls outside the scope of this License.\par -\par - However, linking a "work that uses the Library" with the Library\par -creates an executable that is a derivative of the Library (because it\par -contains portions of the Library), rather than a "work that uses the\par -library". The executable is therefore covered by this License.\par -Section 6 states terms for distribution of such executables.\par -\par - When a "work that uses the Library" uses material from a header file\par -that is part of the Library, the object code for the work may be a\par -derivative work of the Library even though the source code is not.\par -Whether this is true is especially significant if the work can be\par -linked without the Library, or if the work is itself a library. The\par -threshold for this to be true is not precisely defined by law.\par -\par - If such an object file uses only numerical parameters, data\par -structure layouts and accessors, and small macros and small inline\par -functions (ten lines or less in length), then the use of the object\par -file is unrestricted, regardless of whether it is legally a derivative\par -work. (Executables containing this object code plus portions of the\par -Library will still fall under Section 6.)\par -\par - Otherwise, if the work is a derivative of the Library, you may\par -distribute the object code for the work under the terms of Section 6.\par -Any executables containing that work also fall under Section 6,\par -whether or not they are linked directly with the Library itself.\par -\page\par - 6. As an exception to the Sections above, you may also combine or\par -link a "work that uses the Library" with the Library to produce a\par -work containing portions of the Library, and distribute that work\par -under terms of your choice, provided that the terms permit\par -modification of the work for the customer's own use and reverse\par -engineering for debugging such modifications.\par -\par - You must give prominent notice with each copy of the work that the\par -Library is used in it and that the Library and its use are covered by\par -this License. You must supply a copy of this License. If the work\par -during execution displays copyright notices, you must include the\par -copyright notice for the Library among them, as well as a reference\par -directing the user to the copy of this License. Also, you must do one\par -of these things:\par -\par - a) Accompany the work with the complete corresponding\par - machine-readable source code for the Library including whatever\par - changes were used in the work (which must be distributed under\par - Sections 1 and 2 above); and, if the work is an executable linked\par - with the Library, with the complete machine-readable "work that\par - uses the Library", as object code and/or source code, so that the\par - user can modify the Library and then relink to produce a modified\par - executable containing the modified Library. (It is understood\par - that the user who changes the contents of definitions files in the\par - Library will not necessarily be able to recompile the application\par - to use the modified definitions.)\par -\par - b) Use a suitable shared library mechanism for linking with the\par - Library. A suitable mechanism is one that (1) uses at run time a\par - copy of the library already present on the user's computer system,\par - rather than copying library functions into the executable, and (2)\par - will operate properly with a modified version of the library, if\par - the user installs one, as long as the modified version is\par - interface-compatible with the version that the work was made with.\par -\par - c) Accompany the work with a written offer, valid for at\par - least three years, to give the same user the materials\par - specified in Subsection 6a, above, for a charge no more\par - than the cost of performing this distribution.\par -\par - d) If distribution of the work is made by offering access to copy\par - from a designated place, offer equivalent access to copy the above\par - specified materials from the same place.\par -\par - e) Verify that the user has already received a copy of these\par - materials or that you have already sent this user a copy.\par -\par - For an executable, the required form of the "work that uses the\par -Library" must include any data and utility programs needed for\par -reproducing the executable from it. However, as a special exception,\par -the materials to be distributed need not include anything that is\par -normally distributed (in either source or binary form) with the major\par -components (compiler, kernel, and so on) of the operating system on\par -which the executable runs, unless that component itself accompanies\par -the executable.\par -\par - It may happen that this requirement contradicts the license\par -restrictions of other proprietary libraries that do not normally\par -accompany the operating system. Such a contradiction means you cannot\par -use both them and the Library together in an executable that you\par -distribute.\par -\page\par - 7. You may place library facilities that are a work based on the\par -Library side-by-side in a single library together with other library\par -facilities not covered by this License, and distribute such a combined\par -library, provided that the separate distribution of the work based on\par -the Library and of the other library facilities is otherwise\par -permitted, and provided that you do these two things:\par -\par - a) Accompany the combined library with a copy of the same work\par - based on the Library, uncombined with any other library\par - facilities. This must be distributed under the terms of the\par - Sections above.\par -\par - b) Give prominent notice with the combined library of the fact\par - that part of it is a work based on the Library, and explaining\par - where to find the accompanying uncombined form of the same work.\par -\par - 8. You may not copy, modify, sublicense, link with, or distribute\par -the Library except as expressly provided under this License. Any\par -attempt otherwise to copy, modify, sublicense, link with, or\par -distribute the Library is void, and will automatically terminate your\par -rights under this License. However, parties who have received copies,\par -or rights, from you under this License will not have their licenses\par -terminated so long as such parties remain in full compliance.\par -\par - 9. You are not required to accept this License, since you have not\par -signed it. However, nothing else grants you permission to modify or\par -distribute the Library or its derivative works. These actions are\par -prohibited by law if you do not accept this License. Therefore, by\par -modifying or distributing the Library (or any work based on the\par -Library), you indicate your acceptance of this License to do so, and\par -all its terms and conditions for copying, distributing or modifying\par -the Library or works based on it.\par -\par - 10. Each time you redistribute the Library (or any work based on the\par -Library), the recipient automatically receives a license from the\par -original licensor to copy, distribute, link with or modify the Library\par -subject to these terms and conditions. You may not impose any further\par -restrictions on the recipients' exercise of the rights granted herein.\par -You are not responsible for enforcing compliance by third parties with\par -this License.\par -\page\par - 11. If, as a consequence of a court judgment or allegation of patent\par -infringement or for any other reason (not limited to patent issues),\par -conditions are imposed on you (whether by court order, agreement or\par -otherwise) that contradict the conditions of this License, they do not\par -excuse you from the conditions of this License. If you cannot\par -distribute so as to satisfy simultaneously your obligations under this\par -License and any other pertinent obligations, then as a consequence you\par -may not distribute the Library at all. For example, if a patent\par -license would not permit royalty-free redistribution of the Library by\par -all those who receive copies directly or indirectly through you, then\par -the only way you could satisfy both it and this License would be to\par -refrain entirely from distribution of the Library.\par -\par -If any portion of this section is held invalid or unenforceable under any\par -particular circumstance, the balance of the section is intended to apply,\par -and the section as a whole is intended to apply in other circumstances.\par -\par -It is not the purpose of this section to induce you to infringe any\par -patents or other property right claims or to contest validity of any\par -such claims; this section has the sole purpose of protecting the\par -integrity of the free software distribution system which is\par -implemented by public license practices. Many people have made\par -generous contributions to the wide range of software distributed\par -through that system in reliance on consistent application of that\par -system; it is up to the author/donor to decide if he or she is willing\par -to distribute software through any other system and a licensee cannot\par -impose that choice.\par -\par -This section is intended to make thoroughly clear what is believed to\par -be a consequence of the rest of this License.\par -\par - 12. If the distribution and/or use of the Library is restricted in\par -certain countries either by patents or by copyrighted interfaces, the\par -original copyright holder who places the Library under this License may add\par -an explicit geographical distribution limitation excluding those countries,\par -so that distribution is permitted only in or among countries not thus\par -excluded. In such case, this License incorporates the limitation as if\par -written in the body of this License.\par -\par - 13. The Free Software Foundation may publish revised and/or new\par -versions of the Lesser General Public License from time to time.\par -Such new versions will be similar in spirit to the present version,\par -but may differ in detail to address new problems or concerns.\par -\par -Each version is given a distinguishing version number. If the Library\par -specifies a version number of this License which applies to it and\par -"any later version", you have the option of following the terms and\par -conditions either of that version or of any later version published by\par -the Free Software Foundation. If the Library does not specify a\par -license version number, you may choose any version ever published by\par -the Free Software Foundation.\par -\page\par - 14. If you wish to incorporate parts of the Library into other free\par -programs whose distribution conditions are incompatible with these,\par -write to the author to ask for permission. For software which is\par -copyrighted by the Free Software Foundation, write to the Free\par -Software Foundation; we sometimes make exceptions for this. Our\par -decision will be guided by the two goals of preserving the free status\par -of all derivatives of our free software and of promoting the sharing\par -and reuse of software generally.\par -\par -\tab\tab\tab NO WARRANTY\par -\par - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO\par -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.\par -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR\par -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY\par -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE\par -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\par -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE\par -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME\par -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\par -\par - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN\par -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY\par -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU\par -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR\par -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE\par -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING\par -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A\par -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF\par -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\par -DAMAGES.\par -\par -\tab\tab END OF TERMS AND CONDITIONS\par -\page\par -} - \ No newline at end of file diff --git a/Tools/XSIExport/setup/build.bat b/Tools/XSIExport/setup/build.bat deleted file mode 100644 index e75e2b77926..00000000000 --- a/Tools/XSIExport/setup/build.bat +++ /dev/null @@ -1,24 +0,0 @@ -@echo off -if "%1" == "4" goto xsi4 -if "%1" == "5" goto xsi5 - -:xsi6 -candle xsi6install.wxs -light -out OgreXSIExporter6.msi xsi6install.wixobj %WIX_ROOT%\ui\wixui_featuretree.wixlib -goto end - - -:xsi5 -candle xsi5install.wxs -light -out OgreXSIExporter5.msi xsi5install.wixobj %WIX_ROOT%\ui\wixui_featuretree.wixlib -goto end - -:xsi4: -candle xsi4install.wxs -light -out OgreXSIExporter4.msi xsi4install.wixobj %WIX_ROOT%\ui\wixui_featuretree.wixlib -goto end - - - -:end -pause diff --git a/Tools/XSIExport/setup/xsi5install.wxs b/Tools/XSIExport/setup/xsi5install.wxs deleted file mode 100644 index a182091cb35..00000000000 --- a/Tools/XSIExport/setup/xsi5install.wxs +++ /dev/null @@ -1,101 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - FILEEXISTS - - - - - - - - - - - diff --git a/Tools/XSIExport/setup/xsi6install.wxs b/Tools/XSIExport/setup/xsi6install.wxs deleted file mode 100644 index c8ffd55299d..00000000000 --- a/Tools/XSIExport/setup/xsi6install.wxs +++ /dev/null @@ -1,102 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - FILEEXISTS - - - - - - - - - - - diff --git a/Tools/XSIExport/src/OgreXSIExport.cpp b/Tools/XSIExport/src/OgreXSIExport.cpp deleted file mode 100644 index 7a614a0bb47..00000000000 --- a/Tools/XSIExport/src/OgreXSIExport.cpp +++ /dev/null @@ -1,1396 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "OgreXSIMeshExporter.h" -#include "OgreXSISkeletonExporter.h" -#include "OgreXSIMaterialExporter.h" -#include "OgreLogManager.h" -#include "OgreException.h" -#include "OgreXSIHelper.h" -#include "OgreProgressiveMesh.h" -#include "OgreString.h" -#include "OgreLogManager.h" -#include "OgreMeshManager.h" -#include "OgreSkeletonManager.h" -#include "OgreDefaultHardwareBufferManager.h" -#include "OgreMaterialManager.h" -#include "OgreLodStrategyManager.h" - -using namespace XSI; - -#define OGRE_XSI_EXPORTER_VERSION L"1.7.0" - -// define columns of animations list -#define ANIMATION_LIST_EXPORT_COL 0 -#define ANIMATION_LIST_NAME_COL 1 -#define ANIMATION_LIST_START_COL 2 -#define ANIMATION_LIST_END_COL 3 -#define ANIMATION_LIST_IKFREQ_COL 4 - -/** This is the main file for the OGRE XSI plugin. -The purpose of the methods in this file are as follows: - -XSILoadPlugin - registers the export command, the menu item, and the option dialog - -XSIUnloadPlugin - cleans up - -OgreMeshExportCommand_Init - Defines the arguments to the export command - -OgreMeshExportCommand_Execute - Runs the exporter using arguments obtained from a context object - (I assume this is to allow general access to this export rather than using - the property dialog) - -OgreMeshExportMenu_Init - Defines the menu text and the event callback to execute (OnOgreMeshExportMenu) - -OnOgreMeshExportMenu - Callback event when clicking the export menu option. Adds an instance of the - options dialog as a property, then uses the InspectObj XSI command to pop it up - in a modal dialog. If it wasn't cancelled, performs an export. - -OgreMeshExportOptions_Define - Defines the persistable parameters on the options dialog - -OgreMeshExportOptions_DefineLayout - Defines the visual layout of the options dialog - -OgreMeshExportOptions_PPGEvent - Event handler for when the options dialog is interacted with -*/ - -CString GetUserSelectedObject(); -CStatus Popup( const CString& in_inputobjs, const CString& in_keywords, const CString& in_title, const CValue& in_mode, bool in_throw ); -void DeleteObj( const CValue& in_inputobj ); - -Ogre::AnimationList animList; - - -#ifdef unix -extern "C" -#endif -/** Registers the export command, the menu item, and the option dialog */ -CStatus XSILoadPlugin( XSI::PluginRegistrar& registrar ) -{ - registrar.PutAuthor( L"Steve Streeting" ); - registrar.PutName( L"OGRE Exporter Plugin" ); - registrar.PutVersion( 1, 0 ); - registrar.PutURL(L"http://www.ogre3d.org"); - - - // register the mesh export command - registrar.RegisterCommand( L"OgreMeshExportCommand", L"OgreMeshExportCommand" ); - - // register the menu under File > Export - registrar.RegisterMenu(siMenuMainFileExportID, L"OgreMeshExportMenu", false, false); - - // register the export dialog properties factory - registrar.RegisterProperty( L"OgreMeshExportOptions" ); - -#ifdef _DEBUG - Application app; - app.LogMessage( registrar.GetName() + L" has been loaded."); -#endif - - return XSI::CStatus::OK; -} - -#ifdef unix -extern "C" -#endif -/** Cleans up */ -XSI::CStatus XSIUnloadPlugin( const XSI::PluginRegistrar& registrar ) -{ -#ifdef _DEBUG - Application app; - app.LogMessage(registrar.GetName() + L" has been unloaded."); -#endif - - return XSI::CStatus::OK; -} - -#ifdef unix -extern "C" -#endif -/** Defines the arguments to the export command */ -XSI::CStatus OgreMeshExportCommand_Init( const XSI::CRef& context ) -{ - Context ctx(context); - Command cmd(ctx.GetSource()); - - Application app; - app.LogMessage( L"Defining: " + cmd.GetName() ); - - ArgumentArray args = cmd.GetArguments(); - - args.Add( L"targetMeshFileName", L"c:/default.mesh" ); - args.Add( L"mergeSubmeshes", L"true" ); - args.Add( L"exportChildren", L"true" ); - args.Add( L"calculateEdgeLists", L"true" ); - args.Add( L"calculateTangents", L"false" ); - args.Add( L"tangentSemantic", L"true" ); - args.Add( L"tangentsSplitMirrored", L"false" ); - args.Add( L"tangentsSplitRotated", L"false" ); - args.Add( L"tangentsUseParity", L"false" ); - args.Add( L"numLodLevels", L"0" ); - args.Add( L"lodDistanceIncrement", L"2000" ); - args.Add( L"lodQuota", L"true" ); - args.Add( L"lodReduction", L"50" ); - args.Add( L"exportMaterials", L"true" ); - args.Add( L"targetMaterialFileName", L"c:/default.material" ); - args.Add( L"materialPrefix", L"" ); - args.Add( L"copyTextures", L"true" ); - args.Add( L"exportVertexAnimation", L"true" ); - args.Add( L"exportSkeleton", L"true" ); - args.Add( L"targetSkeletonFilename", L"c:/default.skeleton" ); - args.Add( L"fps", L"24" ); - args.Add( L"animationList", L"" ); - - return XSI::CStatus::OK; -} - -#ifdef unix -extern "C" -#endif -/** Runs the exporter using arguments obtained from a context object - (I assume this is to allow general access to this export rather than using - the property dialog) -*/ -XSI::CStatus OgreMeshExportCommand_Execute( XSI::CRef& in_context ) -{ - Application app; - Context ctxt(in_context); - CValueArray args = ctxt.GetAttribute( L"Arguments" ); - -#ifdef _DEBUG - for (long i=0; i 0) - { - float distanceInc = args[10]; - - bool quota = args[11]; - - float reduction = args[12]; - - lodData = new Ogre::XsiMeshExporter::LodData; - float currentInc = distanceInc; - for (int l = 0; l < numlods; ++l) - { - lodData->distances.push_back(currentInc); - currentInc += distanceInc; - } - lodData->quota = (quota == true) ? - Ogre::ProgressiveMesh::VRQ_PROPORTIONAL : Ogre::ProgressiveMesh::VRQ_CONSTANT; - if (lodData->quota == Ogre::ProgressiveMesh::VRQ_PROPORTIONAL) - lodData->reductionValue = reduction * 0.01; - else - lodData->reductionValue = reduction; - - } - - bool exportMaterials = args[13]; - bool copyTextures = args[16]; - bool exportVertexAnimation = args[17]; - bool exportSkeleton = args[18]; - - // create singletons - Ogre::ResourceGroupManager rgm; - Ogre::MeshManager meshMgr; - Ogre::SkeletonManager skelMgr; - Ogre::MaterialManager matMgr; - Ogre::DefaultHardwareBufferManager hardwareBufMgr; - Ogre::LodStrategyManager lodStrategyBufMgr; - - - // determine number of exportsteps - size_t numSteps = 3 + OGRE_XSI_NUM_MESH_STEPS; - if (numlods > 0) - numSteps++; - if (edgeLists) - numSteps++; - if (tangents) - numSteps++; - if (exportSkeleton) - numSteps += 3; - - Ogre::ProgressManager progressMgr(numSteps); - - // Any material prefix? We need that for mesh linking too - Ogre::String materialPrefix = XSItoOgre(XSI::CString(args[15])); - - float fps = args[20]; - if (fps == 0.0f) - { - OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, - "You must supply a valid value for 'FPS'", - "OGRE Export"); - } - - Ogre::AnimationList selAnimList; - if (exportSkeleton || exportVertexAnimation) - { - - GridData gd(args[21]); - for (int a = 0; a < gd.GetRowCount(); ++a) - { - if (gd.GetCell(ANIMATION_LIST_EXPORT_COL, a) == true) - { - Ogre::AnimationEntry ae; - ae.animationName = XSItoOgre(XSI::CString(gd.GetCell(ANIMATION_LIST_NAME_COL, a))); - ae.ikSampleInterval = gd.GetCell(ANIMATION_LIST_IKFREQ_COL, a); - ae.startFrame = (LONG)gd.GetCell(ANIMATION_LIST_START_COL, a); - ae.endFrame = (LONG)gd.GetCell(ANIMATION_LIST_END_COL, a); - selAnimList.push_back(ae); - } - } - } - - if (exportSkeleton) - { - Ogre::String skeletonFileName = XSItoOgre(XSI::CString(args[19])); - if (skeletonFileName.empty()) - { - OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, - "You must supply a skeleton file name", - "OGRE Exporter"); - } - - // fix any omission of '.skeleton' - if (!Ogre::StringUtil::endsWith(skeletonFileName, ".skeleton")) - { - skeletonFileName += ".skeleton"; - } - - // Truncate the skeleton filename to just the name (no path) - Ogre::String skelName = skeletonFileName; - int pos = skeletonFileName.find_last_of("\\"); - if (pos == Ogre::String::npos) - { - pos = skeletonFileName.find_last_of("/"); - } - if (pos != Ogre::String::npos) - { - skelName = skelName.substr(pos+1, skelName.size() - pos - 1); - } - - - // Do the mesh - Ogre::DeformerMap& deformers = - meshExporter.buildMeshForExport(mergeSubmeshes, - exportChildren, edgeLists, tangents, tangentSemantic, - tangentsSplitMirrored, tangentsSplitRotated, tangentsUseParity, - exportVertexAnimation, selAnimList, fps, materialPrefix, - lodData, skelName); - // do the skeleton - const Ogre::AxisAlignedBox& skelAABB = - skelExporter.exportSkeleton(skeletonFileName, deformers, fps, selAnimList); - - // Do final mesh export - meshExporter.exportMesh(meshFileName, skelAABB); - } - else - { - Ogre::AxisAlignedBox nullbb; - // No skeleton - meshExporter.buildMeshForExport(mergeSubmeshes, - exportChildren, edgeLists, tangents, tangentSemantic, - tangentsSplitMirrored, tangentsSplitRotated, tangentsUseParity, - exportVertexAnimation, selAnimList, fps, materialPrefix, lodData); - meshExporter.exportMesh(meshFileName, nullbb); - } - - - delete lodData; - - // Do we want to export materials too? - if (exportMaterials) - { - Ogre::String materialFileName = XSItoOgre(XSI::CString(args[14])); - // fix any omission of '.material' - if (!Ogre::StringUtil::endsWith(materialFileName, ".material")) - { - materialFileName += ".material"; - } - - Ogre::XsiMaterialExporter matExporter; - try - { - matExporter.exportMaterials(meshExporter.getMaterials(), - meshExporter.getTextureProjectionMap(), - materialFileName, copyTextures); - } - catch (Ogre::Exception& e) - { - // ignore, non-fatal and will be in log - } - } - } - catch (Ogre::Exception& e) - { - // Will already have been logged to the Ogre log manager - // Tell XSI - app.LogMessage(OgretoXSI(e.getDescription()), XSI::siFatalMsg); - app.LogMessage(OgretoXSI(e.getFullDescription()), XSI::siInfoMsg); - } - - return st; - - return XSI::CStatus::OK; -} - - -#ifdef unix -extern "C" -#endif -/** Defines the menu text and the event callback to execute (OnOgreMeshExportMenu) */ -XSI::CStatus OgreMeshExportMenu_Init( XSI::CRef& in_ref ) -{ - Context ctxt = in_ref; - Menu menu = ctxt.GetSource(); - - CStatus st; - MenuItem item; - menu.AddCallbackItem(L"OGRE Mesh / Skeleton...", L"OnOgreMeshExportMenu", item); - - return CStatus::OK; -} - -CString exportPropertyDialogName = L"OgreMeshExportOptions"; - -#ifdef unix -extern "C" -#endif -/** Callback event when clicking the export menu option. Adds an instance of the - options dialog as a property, then uses the InspectObj XSI command to pop it up - in a modal dialog. If it wasn't cancelled, performs an export. -*/ -XSI::CStatus OnOgreMeshExportMenu( XSI::CRef& in_ref ) -{ - Ogre::LogManager logMgr; - logMgr.createLog("OgreXSIExporter.log", true); - CString msg(L"OGRE Exporter Version "); - msg += OGRE_XSI_EXPORTER_VERSION; - LogOgreAndXSI(msg); - - Application app; - CStatus st(CStatus::OK); - Property prop = app.GetActiveSceneRoot().GetProperties().GetItem(exportPropertyDialogName); - if (prop.IsValid()) - { - // Check version number - CString currVersion(prop.GetParameterValue(L"version")); - if (!currVersion.IsEqualNoCase(OGRE_XSI_EXPORTER_VERSION)) - { - DeleteObj(exportPropertyDialogName); - prop.ResetObject(); - } - } - if (!prop.IsValid()) - { - prop = app.GetActiveSceneRoot().AddProperty(exportPropertyDialogName); - prop.PutParameterValue(L"version", CString(OGRE_XSI_EXPORTER_VERSION)); - } - - try - { - // Popup Returns true if the command was cancelled otherwise it returns false. - CStatus ret = Popup(exportPropertyDialogName,CValue(),L"OGRE Mesh / Skeleton Export",((LONG)siModal),true); - if (ret == CStatus::OK) - { - Ogre::XsiMeshExporter meshExporter; - Ogre::XsiSkeletonExporter skelExporter; - - // retrieve the parameters - Parameter param = prop.GetParameters().GetItem(L"objectName"); - CString objectName = param.GetValue(); - param = prop.GetParameters().GetItem( L"targetMeshFileName" ); - Ogre::String meshFileName = XSItoOgre(XSI::CString(param.GetValue())); - if (meshFileName.empty()) - { - OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, - "You must supply a mesh file name", - "OGRE Exporter"); - } - // fix any omission of '.mesh' - if (!Ogre::StringUtil::endsWith(meshFileName, ".mesh")) - { - meshFileName += ".mesh"; - } - param = prop.GetParameters().GetItem( L"mergeSubmeshes" ); - bool mergeSubmeshes = param.GetValue(); - param = prop.GetParameters().GetItem( L"exportChildren" ); - bool exportChildren = param.GetValue(); - param = prop.GetParameters().GetItem( L"calculateEdgeLists" ); - bool edgeLists = param.GetValue(); - param = prop.GetParameters().GetItem( L"calculateTangents" ); - bool tangents = param.GetValue(); - param = prop.GetParameters().GetItem( L"tangentSemantic" ); - CString tangentSemStr = param.GetValue(); - Ogre::VertexElementSemantic tangentSemantic = (tangentSemStr == L"t")? - Ogre::VES_TANGENT : Ogre::VES_TEXTURE_COORDINATES; - param = prop.GetParameters().GetItem( L"tangentsSplitMirrored" ); - bool tangentsSplitMirrored = param.GetValue(); - param = prop.GetParameters().GetItem( L"tangentsSplitRotated" ); - bool tangentsSplitRotated = param.GetValue(); - param = prop.GetParameters().GetItem( L"tangentsUseParity" ); - bool tangentsUseParity = param.GetValue(); - param = prop.GetParameters().GetItem( L"numLodLevels" ); - long numlods = (LONG)param.GetValue(); - Ogre::XsiMeshExporter::LodData* lodData = 0; - if (numlods > 0) - { - param = prop.GetParameters().GetItem( L"lodDistanceIncrement" ); - float distanceInc = param.GetValue(); - - param = prop.GetParameters().GetItem(L"lodQuota"); - CString quota = param.GetValue(); - - param = prop.GetParameters().GetItem(L"lodReduction"); - float reduction = param.GetValue(); - - lodData = new Ogre::XsiMeshExporter::LodData; - float currentInc = distanceInc; - for (int l = 0; l < numlods; ++l) - { - lodData->distances.push_back(currentInc); - currentInc += distanceInc; - } - lodData->quota = (quota == L"p") ? - Ogre::ProgressiveMesh::VRQ_PROPORTIONAL : Ogre::ProgressiveMesh::VRQ_CONSTANT; - if (lodData->quota == Ogre::ProgressiveMesh::VRQ_PROPORTIONAL) - lodData->reductionValue = reduction * 0.01; - else - lodData->reductionValue = reduction; - - } - - param = prop.GetParameters().GetItem( L"exportSkeleton" ); - bool exportSkeleton = param.GetValue(); - param = prop.GetParameters().GetItem( L"exportVertexAnimation" ); - bool exportVertexAnimation = param.GetValue(); - param = prop.GetParameters().GetItem( L"exportMaterials" ); - bool exportMaterials = param.GetValue(); - param = prop.GetParameters().GetItem( L"copyTextures" ); - bool copyTextures = param.GetValue(); - - // create singletons - Ogre::ResourceGroupManager rgm; - Ogre::MeshManager meshMgr; - Ogre::SkeletonManager skelMgr; - Ogre::MaterialManager matMgr; - Ogre::DefaultHardwareBufferManager hardwareBufMgr; - Ogre::LodStrategyManager lodStrategyBufMgr; - - - // determine number of exportsteps - size_t numSteps = 3 + OGRE_XSI_NUM_MESH_STEPS; - if (numlods > 0) - numSteps++; - if (edgeLists) - numSteps++; - if (tangents) - numSteps++; - if (exportSkeleton) - numSteps += 3; - - Ogre::ProgressManager progressMgr(numSteps); - - // Any material prefix? We need that for mesh linking too - param = prop.GetParameters().GetItem( L"materialPrefix" ); - Ogre::String materialPrefix = XSItoOgre(XSI::CString(param.GetValue())); - - param = prop.GetParameters().GetItem( L"fps" ); - float fps = param.GetValue(); - if (fps == 0.0f) - { - OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, - "You must supply a valid value for 'FPS'", - "OGRE Export"); - } - - Ogre::AnimationList selAnimList; - if (exportSkeleton || exportVertexAnimation) - { - - param = prop.GetParameters().GetItem( L"animationList" ); - GridData gd(param.GetValue()); - for (int a = 0; a < gd.GetRowCount(); ++a) - { - if (gd.GetCell(ANIMATION_LIST_EXPORT_COL, a) == true) - { - Ogre::AnimationEntry ae; - ae.animationName = XSItoOgre(XSI::CString(gd.GetCell(ANIMATION_LIST_NAME_COL, a))); - ae.ikSampleInterval = gd.GetCell(ANIMATION_LIST_IKFREQ_COL, a); - ae.startFrame = (LONG)gd.GetCell(ANIMATION_LIST_START_COL, a); - ae.endFrame = (LONG)gd.GetCell(ANIMATION_LIST_END_COL, a); - selAnimList.push_back(ae); - } - } - } - - if (exportSkeleton) - { - param = prop.GetParameters().GetItem( L"targetSkeletonFileName" ); - Ogre::String skeletonFileName = XSItoOgre(XSI::CString(param.GetValue())); - if (skeletonFileName.empty()) - { - OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, - "You must supply a skeleton file name", - "OGRE Exporter"); - } - - // fix any omission of '.skeleton' - if (!Ogre::StringUtil::endsWith(skeletonFileName, ".skeleton")) - { - skeletonFileName += ".skeleton"; - } - - // Truncate the skeleton filename to just the name (no path) - Ogre::String skelName = skeletonFileName; - int pos = skeletonFileName.find_last_of("\\"); - if (pos == Ogre::String::npos) - { - pos = skeletonFileName.find_last_of("/"); - } - if (pos != Ogre::String::npos) - { - skelName = skelName.substr(pos+1, skelName.size() - pos - 1); - } - - - // Do the mesh - Ogre::DeformerMap& deformers = - meshExporter.buildMeshForExport(mergeSubmeshes, - exportChildren, edgeLists, tangents, tangentSemantic, - tangentsSplitMirrored, tangentsSplitRotated, tangentsUseParity, - exportVertexAnimation, selAnimList, fps, materialPrefix, - lodData, skelName); - // do the skeleton - const Ogre::AxisAlignedBox& skelAABB = - skelExporter.exportSkeleton(skeletonFileName, deformers, fps, selAnimList); - - // Do final mesh export - meshExporter.exportMesh(meshFileName, skelAABB); - } - else - { - Ogre::AxisAlignedBox nullbb; - // No skeleton - meshExporter.buildMeshForExport(mergeSubmeshes, - exportChildren, edgeLists, tangents, tangentSemantic, - tangentsSplitMirrored, tangentsSplitRotated, tangentsUseParity, - exportVertexAnimation, selAnimList, fps, materialPrefix, lodData); - meshExporter.exportMesh(meshFileName, nullbb); - } - - - delete lodData; - - // Do we want to export materials too? - if (exportMaterials) - { - param = prop.GetParameters().GetItem( L"targetMaterialFileName" ); - Ogre::String materialFileName = XSItoOgre(XSI::CString(param.GetValue())); - // fix any omission of '.material' - if (!Ogre::StringUtil::endsWith(materialFileName, ".material")) - { - materialFileName += ".material"; - } - - Ogre::XsiMaterialExporter matExporter; - try - { - matExporter.exportMaterials(meshExporter.getMaterials(), - meshExporter.getTextureProjectionMap(), - materialFileName, copyTextures); - } - catch (Ogre::Exception& e) - { - // ignore, non-fatal and will be in log - } - } - - } - - } - catch (Ogre::Exception& e) - { - // Will already have been logged to the Ogre log manager - // Tell XSI - app.LogMessage(OgretoXSI(e.getDescription()), XSI::siFatalMsg); - app.LogMessage(OgretoXSI(e.getFullDescription()), XSI::siInfoMsg); - } - - //DeleteObj( L"OgreMeshExportOptions" ); - return st; -} - - -#ifdef unix -extern "C" -#endif -/** Defines the persistable parameters on the options dialog */ -CStatus OgreMeshExportOptions_Define( const CRef & in_Ctx ) -{ - // Here is where we add all the parameters to the - // Custom Property. This will be called each time - // an new instance of the Custom Property is called. - // It is not called when an persisted Custom Property is loaded. - - Application app ; - CustomProperty prop = Context(in_Ctx).GetSource(); - Parameter param ; - - // Default capabilities for most of these parameters - int caps = siPersistable ; - CValue nullValue; // Used for arguments we don't want to set - - prop.AddParameter( - L"version",CValue::siString, caps, - L"Version", L"", - nullValue, param) ; - prop.AddParameter( - L"objectName",CValue::siString, caps, - L"Object Name", L"", - nullValue, param) ; - prop.AddParameter( - L"objects",CValue::siRefArray, caps, - L"Collection of selected objects", L"", - nullValue, param) ; - prop.AddParameter( - L"targetMeshFileName",CValue::siString, caps, - L"Mesh Filename", L"", - nullValue, param) ; - prop.AddParameter( - L"mergeSubmeshes",CValue::siBool, caps, - L"Merge objects with same material?", - L"If false, a separate named SubMesh will be created for every PolygonMesh " - L"preserving your model divisions. If true, the exporter will merge all " - L"PolygonMesh objects with the same material, which is more efficient, but " - L"does not preserve your modelling divisions.", - CValue(true), param) ; - prop.AddParameter( - L"exportChildren",CValue::siBool, caps, - L"Export Children", - L"If true, children of all selected objects will be exported.", - CValue(true), param) ; - prop.AddParameter( - L"calculateEdgeLists",CValue::siBool, caps, - L"Calculate Edge Lists (stencil shadows)", L"", - CValue(true), param) ; - prop.AddParameter( - L"calculateTangents",CValue::siBool, caps, - L"Calculate Tangents (normal mapping)", L"", - CValue(false), param) ; - prop.AddParameter( - L"tangentSemantic",CValue::siString, caps, - L"Tangent Semantic", L"", - L"t", param) ; - prop.AddParameter( - L"tangentsSplitMirrored",CValue::siBool, caps, - L"Split tangents at UV mirror", L"", - CValue(false), param) ; - prop.AddParameter( - L"tangentsSplitRotated",CValue::siBool, caps, - L"Split tangents at UV rotation", L"", - CValue(false), param) ; - prop.AddParameter( - L"tangentsUseParity",CValue::siBool, caps, - L"4D Tangents", L"", - CValue(false), param) ; - prop.AddParameter( - L"numLodLevels",CValue::siInt2, caps, - L"Levels of Detail", L"", - (LONG)0, param) ; - prop.AddParameter( - L"lodDistanceIncrement",CValue::siFloat, caps, - L"Distance Increment", L"", - (LONG)2000, //default - (LONG)1, // hard min - (LONG)1000000, // hard max - (LONG)50, // suggested min - (LONG)10000, // suggested max - param) ; - prop.AddParameter( - L"lodQuota",CValue::siString, caps, - L"Reduction Style", L"", - L"p", param) ; - prop.AddParameter( - L"lodReduction",CValue::siFloat, caps, - L"Reduction Value", L"", - CValue(50.0f), param) ; - prop.AddParameter( - L"exportSkeleton",CValue::siBool, caps, - L"Export Skeleton", L"", - CValue(true), param) ; - prop.AddParameter( - L"exportVertexAnimation",CValue::siBool, caps, - L"Export Vertex Animation", L"", - CValue(true), param) ; - prop.AddParameter( - L"targetSkeletonFileName",CValue::siString, caps, - L"Skeleton Filename", L"", - nullValue, param) ; - prop.AddParameter( - L"fps",CValue::siInt2, caps, - L"Frames per second", L"", - (LONG)24, param) ; - prop.AddGridParameter(L"animationList"); - prop.AddParameter( - L"exportMaterials", CValue::siBool, caps, - L"Export Materials", L"", - CValue(true), param); - prop.AddParameter( - L"copyTextures", CValue::siBool, caps, - L"Copy Textures To Folder", L"", - CValue(true), param); - prop.AddParameter( - L"targetMaterialFileName",CValue::siString, caps, - L"Material Filename", L"", - nullValue, param) ; - prop.AddParameter( - L"materialPrefix",CValue::siString, caps, - L"Material Prefix", L"", - nullValue, param) ; - - - - return CStatus::OK; -} - -#ifdef unix -extern "C" -#endif -/** Defines the visual layout of the options dialog */ -CStatus OgreMeshExportOptions_DefineLayout( const CRef & in_Ctx ) -{ - // XSI will call this to define the visual appearance of the CustomProperty - // The layout is shared between all instances of the CustomProperty - // and is CACHED!!!. You can force the code to re-execute by using the - // XSIUtils.Reload feature, or right-clicking the property page and selecting 'Refresh' - - PPGLayout oLayout = Context( in_Ctx ).GetSource() ; - PPGItem item ; - - oLayout.Clear() ; - - // Mesh tab - oLayout.AddTab(L"Basic"); - // Object - - oLayout.AddGroup(L"Object(s) to export"); - item = oLayout.AddItem(L"objectName"); - item.PutAttribute( siUINoLabel, true ); - oLayout.EndGroup(); - - oLayout.AddGroup(L"Mesh"); - item = oLayout.AddItem(L"targetMeshFileName", L"Target", siControlFilePath); - item.PutAttribute( siUINoLabel, true ); - item.PutAttribute( siUIFileFilter, L"OGRE Mesh format (*.mesh)|*.mesh|All Files (*.*)|*.*||" ); - item = oLayout.AddItem(L"mergeSubmeshes") ; - item = oLayout.AddItem(L"exportChildren") ; - - - item = oLayout.AddItem(L"calculateEdgeLists"); - item = oLayout.AddItem(L"calculateTangents"); - CValueArray tangentVals; - tangentVals.Add(L"Tangent"); - tangentVals.Add(L"t"); - tangentVals.Add(L"Texture Coords"); - tangentVals.Add(L"uvw"); - item = oLayout.AddEnumControl(L"tangentSemantic", tangentVals, L"Tangent Semantic", XSI::siControlCombo); - item = oLayout.AddItem(L"tangentsSplitMirrored"); - item = oLayout.AddItem(L"tangentsSplitRotated"); - item = oLayout.AddItem(L"tangentsUseParity"); - oLayout.AddGroup(L"Level of Detail Reduction"); - item = oLayout.AddItem(L"numLodLevels"); - item = oLayout.AddItem(L"lodDistanceIncrement"); - CValueArray vals; - vals.Add(L"Percentage"); - vals.Add(L"p"); - vals.Add(L"Constant"); - vals.Add(L"c"); - item = oLayout.AddEnumControl(L"lodQuota", vals, L"Quota", XSI::siControlCombo); - item = oLayout.AddItem(L"lodReduction"); - oLayout.EndGroup(); - oLayout.EndGroup(); - - oLayout.AddTab(L"Materials"); - // Material Tab - item = oLayout.AddItem(L"exportMaterials") ; - item = oLayout.AddItem(L"targetMaterialFileName", L"Target", siControlFilePath) ; - item.PutAttribute( siUINoLabel, true ); - item.PutAttribute( siUIFileFilter, L"OGRE Material script (*.material)|*.material|All Files (*.*)|*.*||" ); - item = oLayout.AddItem(L"materialPrefix"); - item = oLayout.AddItem(L"copyTextures"); - - - // Skeleton Tab - oLayout.AddTab(L"Animation"); - - item = oLayout.AddItem(L"exportVertexAnimation"); - item = oLayout.AddItem(L"exportSkeleton"); - item = oLayout.AddItem(L"targetSkeletonFileName", L"Target", siControlFilePath); - item.PutAttribute( siUINoLabel, true ); - item.PutAttribute( siUIFileFilter, L"OGRE Skeleton format (*.skeleton)|*.skeleton|All Files (*.*)|*.*||" ); - item = oLayout.AddItem(L"fps"); - - oLayout.AddGroup(L"Animations"); - item = oLayout.AddItem(L"animationList", L"Animations", siControlGrid); - item.PutAttribute( siUINoLabel, true ); - item.PutAttribute(siUIGridColumnWidths, L"0:15:250:30:30:75"); - item.PutAttribute(siUIGridHideRowHeader, true); - - oLayout.AddRow(); - item = oLayout.AddButton(L"refreshAnimation", L"Refresh"); - item = oLayout.AddButton(L"addAnimation", L"Add"); - item = oLayout.AddButton(L"removeAnimation", L"Remove"); - oLayout.EndRow(); - oLayout.EndGroup(); - - - // Make animatino name read-only (not any more) - //item.PutAttribute(siUIGridReadOnlyColumns, L"1:0:0:0"); - - - - - - - - return CStatus::OK; -} - - -bool hasSkeleton(X3DObject& si, bool recurse) -{ - if (si.GetEnvelopes().GetCount() > 0) - { - return true; - } - - if (recurse) - { - - CRefArray children = si.GetChildren(); - - for(long i = 0; i < children.GetCount(); i++) - { - X3DObject child(children[i]); - bool ret = hasSkeleton(child, recurse); - if (ret) - return ret; - } - } - - return false; - -} - -bool hasSkeleton(Selection& sel, bool recurse) -{ - // iterate over selection - for (int i = 0; i < sel.GetCount(); ++i) - { - X3DObject obj(sel[i]); - bool ret = hasSkeleton(obj, recurse); - if (ret) - return ret; - } - - return false; -} - - - -void findAnimations(XSI::Model& model, Ogre::AnimationList& animList) -{ - - if (model.HasMixer()) - { - // Scan the mixer for all clips - // At this point we're only interested in the top-level and do not - // cascade into all clip containers, since we're interested in the - // top-level timeline splits - XSI::Mixer mixer = model.GetMixer(); - CRefArray clips = mixer.GetClips(); - for (int c = 0; c < clips.GetCount(); ++c) - { - XSI::Clip clip(clips[c]); - XSI::CString clipType = clip.GetType(); - if (clipType == siClipAnimationType || - clipType == siClipShapeType || - clipType == siClipAnimCompoundType || // nested fcurves - clipType == siClipShapeCompoundType) // nested shape - { - XSI::TimeControl timeControl = clip.GetTimeControl(); - Ogre::AnimationEntry anim; - anim.animationName = XSItoOgre(clip.GetName()); - anim.startFrame = timeControl.GetStartOffset(); - long length = (1.0 / timeControl.GetScale()) * - (timeControl.GetClipOut() - timeControl.GetClipIn() + 1); - anim.endFrame = anim.startFrame + length - 1; - anim.ikSampleInterval = 5.0f; - animList.push_back(anim); - - } - - } - - } - -} - -void getAnimations(XSI::Model& root, Ogre::AnimationList& animList) -{ - animList.clear(); - - findAnimations(root, animList); - - // Find all children (recursively) - XSI::CRefArray children = root.FindChildren(L"", siModelType, XSI::CStringArray()); - for (int c = 0; c < children.GetCount(); ++c) - { - XSI::Model child(children[c]); - findAnimations(child, animList); - } - - // Now iterate over the list and eliminate overlapping elements - for (Ogre::AnimationList::iterator i = animList.begin(); - i != animList.end(); ++i) - { - Ogre::AnimationList::iterator j = i; - ++j; - for (; j != animList.end();) - { - bool remove = false; - if (j->startFrame <= i->endFrame && j->endFrame >= i->startFrame) - { - // Merge this one into i, extend boundaries - remove = true; - i->startFrame = std::min(j->startFrame, i->startFrame); - i->endFrame = std::max(j->endFrame, i->endFrame); - } - if (remove) - { - j = animList.erase(j); - } - else - { - ++j; - } - } - } - - -} - -void populateAnimationsList(XSI::GridData gd) -{ - // 5 columns - gd.PutColumnCount(5); - - // Export column is a check box - gd.PutColumnType(ANIMATION_LIST_EXPORT_COL, siColumnBool); - - // Labels - gd.PutColumnLabel(ANIMATION_LIST_EXPORT_COL, L""); - gd.PutColumnLabel(ANIMATION_LIST_NAME_COL, L"Name"); - gd.PutColumnLabel(ANIMATION_LIST_START_COL, L"Start"); - gd.PutColumnLabel(ANIMATION_LIST_END_COL, L"End"); - gd.PutColumnLabel(ANIMATION_LIST_IKFREQ_COL, L"Sample Freq"); - - - Application app; - Model appRoot(app.GetActiveSceneRoot()); - getAnimations(appRoot, animList); - gd.PutRowCount(animList.size()); - long row = 0; - for (Ogre::AnimationList::iterator a = animList.begin(); - a != animList.end(); ++a, ++row) - { - gd.PutCell(ANIMATION_LIST_NAME_COL, row, OgretoXSI(a->animationName)); - // default to export - gd.PutCell(ANIMATION_LIST_EXPORT_COL, row, true); - gd.PutCell(ANIMATION_LIST_START_COL, row, CValue((LONG)a->startFrame)); - gd.PutCell(ANIMATION_LIST_END_COL, row, CValue((LONG)a->endFrame)); - gd.PutCell(ANIMATION_LIST_IKFREQ_COL, row, a->ikSampleInterval); - } -} - - -#ifdef unix -extern "C" -#endif -/** Event handler for when the options dialog is interacted with */ -CStatus OgreMeshExportOptions_PPGEvent( const CRef& io_Ctx ) -{ - // This callback is called when events happen in the user interface - // This is where you implement the "logic" code. - - Application app ; - static bool hasSkel = false; - - PPGEventContext ctx( io_Ctx ) ; - - PPGEventContext::PPGEvent eventID = ctx.GetEventID() ; - - CustomProperty prop = ctx.GetSource() ; - Parameter objectNameParam = prop.GetParameters().GetItem( L"objectName" ) ; - // On open dialog - if ( eventID == PPGEventContext::siOnInit ) - { - CString theObjectName; - // Pre-populate object with currently selected item(s) - Selection sel(app.GetSelection()); - if (sel.GetCount() > 0) - { - CString val; - for (int i = 0; i < sel.GetCount(); ++i) - { - CString thisName = SIObject(sel[i]).GetName(); - val += thisName; - theObjectName += thisName; - if (i < sel.GetCount() - 1) - { - val += L", "; - theObjectName += L"_"; - } - } - prop.PutParameterValue(L"objectName", val); - } - else - { - // no selection, assume entire scene - prop.PutParameterValue(L"objectName", CString(L"[Entire Scene]")); - } - // Make the selection read-only - objectNameParam.PutCapabilityFlag( siReadOnly, true ); - - // Default mesh name - if (prop.GetParameterValue(L"targetMeshFileName") == L"") - { - // default name - prop.PutParameterValue(L"targetMeshFileName", theObjectName + L".mesh"); - } - - // Default material name - if (prop.GetParameterValue(L"targetMaterialFileName") == L"") - { - // default name - prop.PutParameterValue(L"targetMaterialFileName", theObjectName + L".material"); - } - - // default the frame rate to that selected in animation panel - prop.PutParameterValue(L"fps", CTime().GetFrameRate()); - - // enable / disable the skeleton export based on envelopes - if (!hasSkeleton(sel, true)) - { - prop.PutParameterValue(L"exportSkeleton", false); - Parameter param = prop.GetParameters().GetItem(L"exportSkeleton"); - param.PutCapabilityFlag(siReadOnly, true); - param = prop.GetParameters().GetItem(L"targetSkeletonFileName"); - param.PutCapabilityFlag(siReadOnly, true); - hasSkel = false; - } - else - { - prop.PutParameterValue(L"exportSkeleton", true); - Parameter param = prop.GetParameters().GetItem(L"exportSkeleton"); - param.PutCapabilityFlag(siReadOnly, false); - param = prop.GetParameters().GetItem(L"targetSkeletonFileName"); - param.PutCapabilityFlag(siReadOnly, false); - - if (prop.GetParameterValue(L"targetSkeletonFileName") == L"") - { - // default name - prop.PutParameterValue(L"targetSkeletonFileName", theObjectName + L".skeleton"); - } - hasSkel = true; - } - // value of param is a griddata object - // initialise it with all detected animations if it's empty - Parameter param = prop.GetParameters().GetItem(L"animationList"); - GridData gd(param.GetValue()); - if (gd.GetRowCount() == 0 || gd.GetCell(0,0) == L"No data has been set") - { - populateAnimationsList(gd); - } - - } - // On clicking a button - else if ( eventID == PPGEventContext::siButtonClicked ) - { - CValue buttonPressed = ctx.GetAttribute( L"Button" ); - // Clicked the refresh animation button - if ( buttonPressed.GetAsText() == L"refreshAnimation" ) - { - LONG btn; - CStatus ret = app.GetUIToolkit().MsgBox( - L"Are you sure you want to lose the current contents " - L"of the animations list and to refresh it from mixers?", - siMsgYesNo, - L"Confirm", - btn); - if (btn == 6) - { - Parameter param = prop.GetParameters().GetItem(L"animationList"); - GridData gd(param.GetValue()); - populateAnimationsList(gd); - } - - } - else if( buttonPressed.GetAsText() == L"addAnimation" ) - { - Parameter param = prop.GetParameters().GetItem(L"animationList"); - GridData gd(param.GetValue()); - - gd.PutRowCount(gd.GetRowCount() + 1); - // default export to true and sample rate - gd.PutCell(ANIMATION_LIST_EXPORT_COL, gd.GetRowCount()-1, true); - gd.PutCell(ANIMATION_LIST_IKFREQ_COL, gd.GetRowCount()-1, (LONG)5); - } - else if( buttonPressed.GetAsText() == L"removeAnimation" ) - { - Parameter param = prop.GetParameters().GetItem(L"animationList"); - GridData gd(param.GetValue()); - GridWidget gw = gd.GetGridWidget(); - - // cell-level selection, so have to search for selection in every cell - long selRow = -1; - for (long row = 0; row < gd.GetRowCount() && selRow == -1; ++row) - { - for (long col = 0; col < gd.GetColumnCount() && selRow == -1; ++col) - { - if (gw.IsCellSelected(col, row)) - { - selRow = row; - } - } - } - - if (selRow != -1) - { - LONG btn; - CStatus ret = app.GetUIToolkit().MsgBox( - L"Are you sure you want to remove this animation entry?", - siMsgYesNo, - L"Confirm", - btn); - if (btn == 6) - { - // Move all the contents up one - for (long row = selRow; row < gd.GetRowCount(); ++row) - { - for (long col = 0; col < gd.GetColumnCount(); ++col) - { - gd.PutCell(col, row, gd.GetCell(col, row+1)); - } - } - // remove last row - gd.PutRowCount(gd.GetRowCount() - 1); - } - - } - - } - } - // Changed a parameter - else if ( eventID == PPGEventContext::siParameterChange ) - { - Parameter changed = ctx.GetSource() ; - CustomProperty prop = changed.GetParent() ; - CString paramName = changed.GetScriptName() ; - - // Check paramName against parameter names, perform custom onChanged event - if (paramName == L"targetMeshFileName") - { - // Default skeleton & material name - Ogre::String meshName = XSItoOgre(XSI::CString(changed.GetValue())); - if (hasSkel) - { - Ogre::String skelName = meshName; - if (Ogre::StringUtil::endsWith(skelName, ".mesh")) - { - skelName = skelName.substr(0, skelName.size() - 5) + ".skeleton"; - } - CString xsiSkelName = OgretoXSI(skelName); - prop.PutParameterValue(L"targetSkeletonFileName", xsiSkelName); - } - // default material script name - Ogre::String matName = meshName; - if (Ogre::StringUtil::endsWith(matName, ".mesh")) - { - matName = matName.substr(0, matName.size() - 5) + ".material"; - } - CString xsiMatName = OgretoXSI(matName); - prop.PutParameterValue(L"targetMaterialFileName", xsiMatName); - - - } - } - - - return CStatus::OK; - -} - -CString GetUserSelectedObject() -{ - Application app; - Model root(app.GetActiveSceneRoot()); - CStringArray emptyArray; - CRefArray cRefArray = root.FindChildren( L"", L"", emptyArray, true ); - - CStringArray nameArray(cRefArray.GetCount()); - for ( long i=0; i < cRefArray.GetCount(); i++ ) - { - nameArray[i] = SIObject(cRefArray[i]).GetName(); - } - //todo qsort the nameArray - - // Using the COMAPIHandler for creating a "XSIDial.XSIDialog" - CComAPIHandler xsidialog; - xsidialog.CreateInstance( L"XSIDial.XSIDialog"); - CValue index; - CValueArray args(cRefArray.GetCount()); - for (long y=0; y < cRefArray.GetCount(); y++) - args[y]=nameArray[y]; - - xsidialog.Call(L"Combo",index,L"Select Item",args ); - - long ind = (LONG)index; - return args[ind]; -} - - -CStatus Popup( const CString& in_inputobjs, const CString& in_keywords, const CString& in_title, const CValue& /*number*/ in_mode, bool in_throw ) -{ - Application app; - CValueArray args(5); - CValue retval; - long i(0); - - args[i++]= in_inputobjs; - args[i++]= in_keywords; - args[i++]= in_title; - args[i++]= in_mode; - args[i++]= in_throw; - - return app.ExecuteCommand( L"InspectObj", args, retval ); - -} - -void DeleteObj( const CValue& in_inputobj ) -{ - Application app; - CValueArray args(1); - CValue retval; - long i(0); - - args[i++]= in_inputobj; - - CStatus st = app.ExecuteCommand( L"DeleteObj", args, retval ); - - return; -} diff --git a/Tools/XSIExport/src/OgreXSIHelper.cpp b/Tools/XSIExport/src/OgreXSIHelper.cpp deleted file mode 100644 index 0099af1ef6a..00000000000 --- a/Tools/XSIExport/src/OgreXSIHelper.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreXSIHelper.h" -#include - -namespace Ogre { - - //----------------------------------------------------------------------- - void copyFile(const String& src, const String& dst) - { - std::ifstream in(src.c_str(), std::ios::in | std::ios::binary); - std::ofstream out(dst.c_str(), std::ios::out | std::ios::binary | std::ios::trunc); - - if (!in || !out) - { - LogOgreAndXSI("Unable to copy texture '" + src + "' to '" + dst + "'"); - return; - } - - char tmpBuf[2048]; - - while (!in.eof()) - { - in.read(tmpBuf, 2048); - - std::streamsize c = in.gcount(); - - out.write(tmpBuf, c); - - } - - in.close(); - out.close(); - - - - } - //----------------------------------------------------------------------- - template<> ProgressManager* Singleton::msSingleton = 0; - ProgressManager* ProgressManager::getSingletonPtr(void) - { - return msSingleton; - } - ProgressManager& ProgressManager::getSingleton(void) - { - assert( msSingleton ); return ( *msSingleton ); - } - //----------------------------------------------------------------------------- - ProgressManager::ProgressManager(size_t numberOfStages) - :mNumberOfStages(numberOfStages), mProgress(0) - { - XSI::Application app; - - mProgressBar = app.GetUIToolkit().GetProgressBar(); - mProgressBar.PutMaximum(numberOfStages); - mProgressBar.PutStep(1); - mProgressBar.PutVisible(true); - mProgressBar.PutCaption(L"Exporting"); - } - //----------------------------------------------------------------------------- - ProgressManager::~ProgressManager() - { - } - //----------------------------------------------------------------------------- - void ProgressManager::progress(void) - { - ++mProgress; - mProgressBar.Increment(); - - } - -} \ No newline at end of file diff --git a/Tools/XSIExport/src/OgreXSIMaterialExporter.cpp b/Tools/XSIExport/src/OgreXSIMaterialExporter.cpp deleted file mode 100644 index b71b8b20691..00000000000 --- a/Tools/XSIExport/src/OgreXSIMaterialExporter.cpp +++ /dev/null @@ -1,986 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreXSIMaterialExporter.h" -#include "OgreMaterialManager.h" -#include "OgreMaterial.h" -#include "OgreTechnique.h" -#include "OgrePass.h" -#include "OgreTextureUnitState.h" - -#include -#include -#include - - -namespace Ogre { - - //------------------------------------------------------------------------- - XsiMaterialExporter::XsiMaterialExporter() - { - - } - //------------------------------------------------------------------------- - XsiMaterialExporter::~XsiMaterialExporter() - { - clearPassQueue(); - } - //------------------------------------------------------------------------- - void XsiMaterialExporter::exportMaterials(MaterialMap& materials, - TextureProjectionMap& texProjMap, const String& filename, - bool copyTextures) - { - LogOgreAndXSI("** Begin OGRE Material Export **"); - - mTextureProjectionMap = texProjMap; - - String texturePath; - if (copyTextures) - { - // derive the texture path - String::size_type pos = filename.find_last_of("\\"); - if (pos == String::npos) - { - pos = filename.find_last_of("/"); - } - if (pos != String::npos) - { - texturePath = filename.substr(0, pos + 1); - } - } - - mMatSerializer.clearQueue(); - - for (MaterialMap::iterator m = materials.begin(); m != materials.end(); ++m) - { - exportMaterial(m->second, copyTextures, texturePath); - } - - mMatSerializer.exportQueued(filename); - - LogOgreAndXSI("** OGRE Material Export Complete **"); - } - //------------------------------------------------------------------------- - void XsiMaterialExporter::exportMaterial(MaterialEntry* matEntry, - bool copyTextures, const String& texturePath) - { - LogOgreAndXSI("Exporting " + matEntry->name); - - MaterialPtr mat = MaterialManager::getSingleton().create( - matEntry->name, - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - Technique* t = mat->createTechnique(); - - // collect the passes into our queue - // XSI stores passes in reverse order, so invert them - clearPassQueue(); - XSI::Shader shader(matEntry->xsiShader); - PassEntry* passEntry = new PassEntry(); - mPassQueue.push_front(passEntry); - while (1) - { - passEntry->shaders.Add(shader); - - XSI::CRef source = shader.GetParameter(L"previous").GetSource(); - if(!source.IsValid() || !source.IsA(XSI::siShaderID)) - { - // finish - break; - } - - shader = XSI::Shader(source); - // If we find a 'blending' parameter, we're on a new pass - if (shader.GetParameter(L"blending").IsValid()) - { - passEntry = new PassEntry(); - mPassQueue.push_front(passEntry); // push front to invert order - } - } - - - // Now go through each pass and create OGRE version - for (PassQueue::iterator p = mPassQueue.begin(); p != mPassQueue.end(); ++p) - { - PassEntry* passEntry = *p; - Pass* pass = t->createPass(); - LogOgreAndXSI("Added Pass"); - - // Need to pre-populate pass textures to match up transforms - populatePassTextures(pass, passEntry, copyTextures, texturePath); - // Do the rest - for (int s = 0; s < passEntry->shaders.GetCount(); ++s) - { - XSI::Shader shader(passEntry->shaders[s]); - populatePass(pass, shader); - } - - } - - - mMatSerializer.queueForExport(mat); - - - } - //------------------------------------------------------------------------- - void XsiMaterialExporter::clearPassQueue(void) - { - for (PassQueue::iterator i = mPassQueue.begin(); i != mPassQueue.end(); ++i) - { - delete *i; - } - mPassQueue.clear(); - - } - //------------------------------------------------------------------------- - void XsiMaterialExporter::populatePass(Pass* pass, XSI::Shader& xsishader) - { - populatePassDepthCull(pass, xsishader); - populatePassSceneBlend(pass, xsishader); - populatePassLighting(pass, xsishader); - populatePassTextureTransforms(pass, xsishader); - populatePassCgPrograms(pass, xsishader); - populatePassHLSLPrograms(pass, xsishader); - populatePassD3DAssemblerPrograms(pass, xsishader); - } - //------------------------------------------------------------------------- - void XsiMaterialExporter::populatePassCgPrograms(Pass* pass, - XSI::Shader& xsishader) - { - XSI::Parameter param = xsishader.GetParameter(L"Cg_Program"); - if (param.IsValid()) - { - // TODO - // XSI can't reference external files which makes it v.difficult to - // re-use shaders - mod XSI plugin? - } - } - //------------------------------------------------------------------------- - void XsiMaterialExporter::populatePassHLSLPrograms(Pass* pass, - XSI::Shader& xsishader) - { - XSI::Parameter param = xsishader.GetParameter(L"HLSL_Program"); - if (param.IsValid()) - { - // TODO - // XSI can't reference external files which makes it v.difficult to - // re-use shaders - mod XSI plugin? - } - } - //------------------------------------------------------------------------- - void XsiMaterialExporter::populatePassD3DAssemblerPrograms(Pass* pass, - XSI::Shader& xsishader) - { - XSI::Parameter param = xsishader.GetParameter(L"Vertex_Shader"); - if (param.IsValid()) - { - // TODO - // XSI can't reference external files which makes it v.difficult to - // re-use shaders - mod XSI plugin? - } - param = xsishader.GetParameter(L"Pixel_Shader"); - if (param.IsValid()) - { - // TODO - // XSI can't reference external files which makes it v.difficult to - // re-use shaders - mod XSI plugin? - } - } - //------------------------------------------------------------------------- - void XsiMaterialExporter::populatePassDepthCull(Pass* pass, - XSI::Shader& xsishader) - { - XSI::Parameter param = xsishader.GetParameter(L"cullingmode"); - if (param.IsValid()) - { - short xsiCull = param.GetValue(); - switch (xsiCull) - { - case 0: - pass->setCullingMode(CULL_NONE); - pass->setManualCullingMode(MANUAL_CULL_NONE); - break; - case 1: - pass->setCullingMode(CULL_CLOCKWISE); - pass->setManualCullingMode(MANUAL_CULL_BACK); - break; - case 2: - pass->setCullingMode(CULL_ANTICLOCKWISE); - pass->setManualCullingMode(MANUAL_CULL_FRONT); - break; - - }; - } - - param = xsishader.GetParameter(L"depthtest"); - if (param.IsValid()) - { - bool depthTest = param.GetValue(); - pass->setDepthCheckEnabled(depthTest); - } - param = xsishader.GetParameter(L"depthwrite"); - if (param.IsValid()) - { - bool depthWrite = param.GetValue(); - pass->setDepthWriteEnabled(depthWrite); - } - } - //------------------------------------------------------------------------- - void XsiMaterialExporter::populatePassSceneBlend(Pass* pass, - XSI::Shader& xsishader) - { - XSI::Parameter param = xsishader.GetParameter(L"blending"); - if (param.IsValid() && (bool)param.GetValue()) - { - SceneBlendFactor src = SBF_ONE; - SceneBlendFactor dst = SBF_ONE; - - param = xsishader.GetParameter(L"srcblendingfunction"); - if (param.IsValid()) - { - src = convertSceneBlend(param.GetValue()); - } - param = xsishader.GetParameter(L"dstblendingfunction"); - if (param.IsValid()) - { - dst = convertSceneBlend(param.GetValue()); - } - - pass->setSceneBlending(src, dst); - } - } - //------------------------------------------------------------------------- - void XsiMaterialExporter::populatePassLighting(Pass* pass, - XSI::Shader& xsishader) - { - XSI::Parameter param = xsishader.GetParameter(L"Enable_Lighting"); - if (param.IsValid()) - { - pass->setLightingEnabled(param.GetValue()); - - ColourValue tmpColour; - xsishader.GetColorParameterValue(L"Ambient", tmpColour.r, tmpColour.g, - tmpColour.b, tmpColour.a); - pass->setAmbient(tmpColour); - xsishader.GetColorParameterValue(L"Diffuse", tmpColour.r, tmpColour.g, - tmpColour.b, tmpColour.a); - pass->setDiffuse(tmpColour); - xsishader.GetColorParameterValue(L"Emissive", tmpColour.r, tmpColour.g, - tmpColour.b, tmpColour.a); - pass->setSelfIllumination(tmpColour); - xsishader.GetColorParameterValue(L"Specular", tmpColour.r, tmpColour.g, - tmpColour.b, tmpColour.a); - pass->setSpecular(tmpColour); - - pass->setShininess(xsishader.GetParameter(L"Shininess").GetValue()); - } - - - } - //------------------------------------------------------------------------- - void XsiMaterialExporter::populatePassTextures(Pass* pass, - PassEntry* passEntry, bool copyTextures, const String& targetFolder) - { - // We need to search all shaders back to the point we would change - // passes, and add all the textures. This is because we don't know - // where in the shaders the texture transforms might be, since they - // are linked via 'target' not by being on the same object. - mTextureUnitTargetMap.clear(); - - for (int s = 0; s < passEntry->shaders.GetCount(); ++s) - { - XSI::Shader shader(passEntry->shaders[s]); - TextureUnitState* tex = 0; - - String progID = XSItoOgre(shader.GetProgID()); - if (progID.find("OGL13Texture") != String::npos || - progID.find("DXTexture") != String::npos || - progID.find("OGLCom") != String::npos) - { - if (!shader.GetParameter(L"bottom").IsValid()) - { - tex = add2DTexture(pass, shader, copyTextures, targetFolder); - } - else if (shader.GetParameter(L"bottom").IsValid()) - { - tex = addCubicTexture(pass, shader, copyTextures, targetFolder); - } - } - else - { - continue; // not a texture so skip the rest - } - - - // texture coordinate set - XSI::Parameter param = shader.GetParameter(L"tspace_id"); - if (param.IsValid()) - { - // this is a name, need to look up index - tex->setTextureCoordSet( - getTextureCoordIndex(XSItoOgre(XSI::CString(param.GetValue())))); - } - - // filtering & anisotropy - // DX and GL shaders deal differently - if (progID.find("OGL") != String::npos) - { - populateOGLFiltering(tex, shader); - } - else if (progID.find("DX") != String::npos) - { - populateDXFiltering(tex, shader); - } - - // colour operation - param = shader.GetParameter(L"modulation"); - if (param.IsValid()) - { - long colourop = ((LONG)param.GetValue()); - switch (colourop) - { - case 0: - // modulate - tex->setColourOperation(LBO_MODULATE); - break; - case 1: - // decal - tex->setColourOperation(LBO_ALPHA_BLEND); - break; - case 2: - // blend - tex->setColourOperation(LBO_MODULATE); - break; - case 3: - // replace - tex->setColourOperation(LBO_REPLACE); - break; - case 4: - // add - tex->setColourOperation(LBO_ADD); - break; - } - - } - - - - } - } - //------------------------------------------------------------------------- - TextureUnitState* XsiMaterialExporter::add2DTexture(Pass* pass, XSI::Shader& shader, - bool copyTextures, const String& targetFolder) - { - // create texture unit state and map from target incase future xforms - TextureUnitState* tex = pass->createTextureUnitState(); - - XSI::Parameter param = shader.GetParameter(L"target"); // OGL - if (!param.IsValid()) - param = shader.GetParameter(L"Texture_Target"); // DX - - long target = ((LONG)param.GetValue()); - mTextureUnitTargetMap.insert( - TextureUnitTargetMap::value_type(target, tex)); - - // Get image - XSI::CRef src = shader.GetParameter(L"Texture").GetSource(); - if (!src.IsValid() || !src.IsA(XSI::siImageClipID)) - { - // Try Texture_1 (OGL Combined) - src = shader.GetParameter(L"Texture_1").GetSource(); - - } - if (src.IsValid() && src.IsA(XSI::siImageClipID)) - { - XSI::ImageClip imgClip(src); - String srcTextureName = - XSItoOgre(XSI::CString(imgClip.GetParameter(L"SourceFileName").GetValue())); - - String::size_type pos = srcTextureName.find_last_of("\\"); - if (pos == String::npos) - { - pos = srcTextureName.find_last_of("/"); - } - String textureName = - srcTextureName.substr(pos+1, srcTextureName.size() - pos - 1); - String destTextureName = targetFolder + textureName; - - // copy texture if required - if (copyTextures) - { - copyFile(srcTextureName, destTextureName); - } - - LogOgreAndXSI("Adding texture " + textureName); - tex->setTextureName(textureName); - - } - - return tex; - } - //------------------------------------------------------------------------- - void XsiMaterialExporter::populateOGLFiltering(TextureUnitState* tex, - XSI::Shader& shader) - { - FilterOptions minFilter, mipFilter, magFilter; - minFilter = FO_LINEAR; - magFilter = FO_LINEAR; - mipFilter = FO_POINT; - XSI::Parameter param = shader.GetParameter(L"minfilter"); - if (param.IsValid()) - { - // XSI OGL shader uses minfilter to determine mip too - long filt = ((LONG)param.GetValue()); - switch(filt) - { - case 0: - minFilter = FO_POINT; - mipFilter = FO_NONE; - break; - case 1: - minFilter = FO_LINEAR; - mipFilter = FO_NONE; - break; - case 2: - minFilter = FO_POINT; - mipFilter = FO_POINT; - break; - case 3: - minFilter = FO_POINT; - mipFilter = FO_LINEAR; - break; - case 4: - minFilter = FO_LINEAR; - mipFilter = FO_POINT; - break; - case 5: - minFilter = FO_LINEAR; - mipFilter = FO_LINEAR; - break; - }; - - } - param = shader.GetParameter(L"magfilter"); - if (param.IsValid()) - { - long filt = ((LONG)param.GetValue()); - switch(filt) - { - case 0: - magFilter = FO_POINT; - break; - case 1: - magFilter = FO_LINEAR; - break; - }; - } - - param = shader.GetParameter(L"anisotropy"); - if (param.IsValid()) - { - long aniso = ((LONG)param.GetValue()); - if (aniso > 1) - { - // No specific aniso filtering option, so upgrade linear -> aniso - if (minFilter == FO_LINEAR) - minFilter = FO_ANISOTROPIC; - if (magFilter == FO_LINEAR) - magFilter = FO_ANISOTROPIC; - } - tex->setTextureAnisotropy(aniso); - } - - tex->setTextureFiltering(minFilter, magFilter, mipFilter); - } - //------------------------------------------------------------------------- - void XsiMaterialExporter::populateDXFiltering(TextureUnitState* tex, - XSI::Shader& shader) - { - FilterOptions minFilter, mipFilter, magFilter; - minFilter = FO_LINEAR; - magFilter = FO_LINEAR; - mipFilter = FO_POINT; - XSI::Parameter param = shader.GetParameter(L"minfilter"); - if (param.IsValid()) - { - // XSI DX shader has min/mag and mip, and has more options - long filt = ((LONG)param.GetValue()); - switch(filt) - { - case 0: - minFilter = FO_NONE; - break; - case 1: - minFilter = FO_POINT; - break; - case 2: - minFilter = FO_LINEAR; - break; - case 3: - case 4: // we don't support cubic/gaussian, use aniso - case 5: - minFilter = FO_ANISOTROPIC; - break; - }; - } - param = shader.GetParameter(L"magfilter"); - if (param.IsValid()) - { - // XSI DX shader has mag/mag and mip, and has more options - long filt = ((LONG)param.GetValue()); - switch(filt) - { - case 0: - magFilter = FO_NONE; - break; - case 1: - magFilter = FO_POINT; - break; - case 2: - magFilter = FO_LINEAR; - break; - case 3: - case 4: // we don't support cubic/gaussian, use aniso - case 5: - magFilter = FO_ANISOTROPIC; - break; - }; - } - param = shader.GetParameter(L"mipfilter"); - if (param.IsValid()) - { - // XSI DX shader has mip/mag and mip, and has more options - long filt = ((LONG)param.GetValue()); - switch(filt) - { - case 0: - mipFilter = FO_NONE; - break; - case 1: - mipFilter = FO_POINT; - break; - case 2: - mipFilter = FO_LINEAR; - break; - case 3: - case 4: // we don't support cubic/gaussian, use aniso - case 5: - mipFilter = FO_ANISOTROPIC; - break; - }; - } - // Aniso - param = shader.GetParameter(L"anisotropy"); - if (param.IsValid()) - { - long aniso = ((LONG)param.GetValue()); - tex->setTextureAnisotropy(aniso); - } - - tex->setTextureFiltering(minFilter, magFilter, mipFilter); - } - //------------------------------------------------------------------------- - TextureUnitState* XsiMaterialExporter::addCubicTexture(Pass* pass, XSI::Shader& shader, - bool copyTextures, const String& targetFolder) - { - // create texture unit state and map from target incase future xforms - TextureUnitState* tex = pass->createTextureUnitState(); - - XSI::Parameter param = shader.GetParameter(L"target"); // OGL - if (!param.IsValid()) - param = shader.GetParameter(L"Texture_Target"); // DX - - long target = ((LONG)param.GetValue()); - mTextureUnitTargetMap.insert( - TextureUnitTargetMap::value_type(target, tex)); - - // Get images - wchar_t* cubeFaceName[6] = { - L"front", L"back", L"top", L"bottom", L"left", L"right" }; - - String finalNames[6]; - - - for (int face = 0; face < 6; ++face) - { - XSI::CRef src = shader.GetParameter(cubeFaceName[face]).GetSource(); - if (src.IsValid() && src.IsA(XSI::siImageClipID)) - { - XSI::ImageClip imgClip(src); - String srcTextureName = - XSItoOgre(XSI::CString(imgClip.GetParameter(L"SourceFileName").GetValue())); - - String::size_type pos = srcTextureName.find_last_of("\\"); - if (pos == String::npos) - { - pos = srcTextureName.find_last_of("/"); - } - finalNames[face] = - srcTextureName.substr(pos+1, srcTextureName.size() - pos - 1); - String destTextureName = targetFolder + finalNames[face]; - - // copy texture if required - if (copyTextures) - { - copyFile(srcTextureName, destTextureName); - } - - - LogOgreAndXSI("Cubemap face: " + srcTextureName); - } - } - - LogOgreAndXSI("Adding cubic texture"); - // Cannot do combinedUVW for now, DevIL can't write DDS cubemap so - // go for separates (user can modify) - tex->setCubicTextureName(finalNames, false); - - return tex; - - } - //------------------------------------------------------------------------- - unsigned short XsiMaterialExporter::getTextureCoordIndex(const String& tspace) - { - TextureProjectionMap::iterator i = mTextureProjectionMap.find(tspace); - if (i != mTextureProjectionMap.end()) - { - return i->second; - } - else - { - // default - return 0; - } - } - //------------------------------------------------------------------------- - void XsiMaterialExporter::populatePassTextureTransforms(Pass* pass, - XSI::Shader& shader) - { - // TODO - // Check we have the right object - XSI::Parameter param = shader.GetParameter(L"wrap_u"); - if (param.IsValid()) - { - - // addressing mode - Sampler::UVWAddressingMode uvwadd; - uvwadd.u = convertAddressingMode(param.GetValue()); - // default other dimensions incase not supplied - uvwadd.v = uvwadd.u; - uvwadd.w = uvwadd.u; - - param = shader.GetParameter(L"wrap_v"); - if (param.IsValid()) - { - uvwadd.v = convertAddressingMode(param.GetValue()); - } - param = shader.GetParameter(L"wrap_w"); - if (param.IsValid()) - { - uvwadd.w = convertAddressingMode(param.GetValue()); - } - - // transform - bool usexform = false; - Matrix4 xform = Matrix4::IDENTITY; - param = shader.GetParameter(L"Transform"); - if (param.IsValid() && (bool)param.GetValue()) - { - Quaternion qx, qy, qz, qfinal; - qx.FromAngleAxis(Degree(shader.GetParameter(L"rotx").GetValue()), - Vector3::UNIT_X); - qy.FromAngleAxis(Degree(shader.GetParameter(L"roty").GetValue()), - Vector3::UNIT_Y); - qz.FromAngleAxis(Degree(shader.GetParameter(L"rotz").GetValue()), - Vector3::UNIT_Z); - qfinal = qx * qy * qz; - - Vector3 trans; - trans.x = shader.GetParameter(L"trsx").GetValue(); - trans.y = shader.GetParameter(L"trsy").GetValue(); - trans.z = shader.GetParameter(L"trsz").GetValue(); - - Matrix3 rot3x3, scale3x3; - qfinal.ToRotationMatrix(rot3x3); - scale3x3 = Matrix3::ZERO; - scale3x3[0][0] = shader.GetParameter(L"sclx").GetValue(); - scale3x3[1][1] = shader.GetParameter(L"scly").GetValue(); - scale3x3[2][2] = shader.GetParameter(L"sclz").GetValue(); - - xform = rot3x3 * scale3x3; - xform.setTrans(trans); - usexform = true; - - } - - - // Look up texture unit(s) that are using this target - long target = ((LONG)shader.GetParameter(L"Texture_Target").GetValue()); - TextureUnitTargetMap::iterator i = mTextureUnitTargetMap.find(target); - while (i != mTextureUnitTargetMap.end() && i->first == target) - { - TextureUnitState* tex = i->second; - tex->setTextureAddressingMode(uvwadd); - if (usexform) - tex->setTextureTransform(xform); - - // texgen (not texcoord_index as in OGRE!) - // Can turn into 2 different calls - param = shader.GetParameter(L"texcoord_index"); - if (param.IsValid()) - { - long e = ((LONG)param.GetValue()); - if (e != 0) - { - // Not Explicit - // details differ per DX/OGL - if (XSItoOgre(shader.GetProgID()).find("DX") != String::npos) - { - convertTexGenDX(tex, e, shader); - } - else - { - convertTexGenOGL(tex, e, shader); - } - - } - - } - ++i; - } - - - - - } - param = shader.GetParameter(L"Additive_Transform"); - if (param.IsValid()) - { - unsigned short target = shader.GetParameter(L"Texture_Coord_ID").GetValue(); - if (pass->getNumTextureUnitStates() > target) - { - TextureUnitState* tex = pass->getTextureUnitState(target); - - long uvType = ((LONG)shader.GetParameter(L"UV_Type").GetValue()); - if (uvType != 0) - { - double val1 = shader.GetParameter(L"Val1").GetValue(); - double val2 = shader.GetParameter(L"Val2").GetValue(); - long wave = ((LONG)shader.GetParameter(L"Wave").GetValue()); - WaveformType wft; - switch (wave) - { - case 1: - wft = WFT_SINE; - break; - case 2: - wft = WFT_TRIANGLE; - break; - case 3: - wft = WFT_SQUARE; - break; - case 4: - wft = WFT_SAWTOOTH; - break; - case 5: - wft = WFT_INVERSE_SAWTOOTH; - break; - } - double base = shader.GetParameter(L"Base").GetValue(); - double amp = shader.GetParameter(L"Amplitude").GetValue(); - double phase = shader.GetParameter(L"Phase").GetValue(); - double freq = shader.GetParameter(L"Frequency").GetValue(); - - switch(uvType) - { - case 1: - // translate - tex->setTextureScroll(val1, val2); - break; - case 2: - // rotate - tex->setTextureRotate(Degree(val1)); - break; - case 3: - // scale - tex->setTextureScale(val1, val2); - break; - case 4: - // scroll - if (wave != 0) - { - tex->setTransformAnimation(TextureUnitState::TT_TRANSLATE_U, - wft, base, freq, phase, amp); - tex->setTransformAnimation(TextureUnitState::TT_TRANSLATE_V, - wft, base, freq, phase, amp); - } - else - { - tex->setScrollAnimation(val1, val2); - } - break; - case 5: - // turn - if (wave != 0) - { - tex->setTransformAnimation(TextureUnitState::TT_ROTATE, - wft, base, freq, phase, amp); - } - else - { - tex->setRotateAnimation(val1 / 360.0f); - } - break; - case 6: - // stretch (only wave) - if (wave != 0) - { - tex->setTransformAnimation(TextureUnitState::TT_SCALE_U, - wft, base, freq, phase, amp); - tex->setTransformAnimation(TextureUnitState::TT_SCALE_V, - wft, base, freq, phase, amp); - } - break; - - } - } - } - - } - - // if more than one entry for the same target is found, it is ok for the - // latter to take precedence since this is what happens in XSI. - - } - //------------------------------------------------------------------------- - void XsiMaterialExporter::convertTexGenOGL(TextureUnitState* tex, - long xsiVal, XSI::Shader& shader) - { - switch(xsiVal) - { - // no 0 - case 1: - // Object linear - tex->setEnvironmentMap(true, TextureUnitState::ENV_PLANAR); - break; - case 2: - // Eye linear (texture projection) - tex->setProjectiveTexturing(true); - break; - case 3: - // Sphere map - tex->setEnvironmentMap(true, TextureUnitState::ENV_CURVED); - break; - case 4: - // Reflection map - tex->setEnvironmentMap(true, TextureUnitState::ENV_REFLECTION); - break; - case 5: - // Normal map - tex->setEnvironmentMap(true, TextureUnitState::ENV_NORMAL); - break; - - }; - } - //------------------------------------------------------------------------- - void XsiMaterialExporter::convertTexGenDX(TextureUnitState* tex, - long xsiVal, XSI::Shader& shader) - { - switch(xsiVal) - { - // no 0 - case 1: - // Normal in camera space - tex->setEnvironmentMap(true, TextureUnitState::ENV_CURVED); - break; - case 2: - // Position in camera space - tex->setEnvironmentMap(true, TextureUnitState::ENV_PLANAR); - break; - case 3: - // Reflection vector in camera space - tex->setEnvironmentMap(true, TextureUnitState::ENV_REFLECTION); - break; - - }; - } - //------------------------------------------------------------------------- - TextureAddressingMode - XsiMaterialExporter::convertAddressingMode(short xsiVal) - { - // same for OGL and DX - switch(xsiVal) - { - case 0: - return TextureUnitState::TAM_WRAP; - case 1: - return TextureUnitState::TAM_MIRROR; - case 2: - return TextureUnitState::TAM_CLAMP; - case 3: - // border? - return TextureUnitState::TAM_CLAMP; - case 4: - // mirror once - return TextureUnitState::TAM_MIRROR; - case 5: - // clamp to edge - return TextureUnitState::TAM_CLAMP; - - }; - - // Keep compiler happy - return TextureUnitState::TAM_WRAP; - } - //------------------------------------------------------------------------- - SceneBlendFactor XsiMaterialExporter::convertSceneBlend(short xsiVal) - { - switch(xsiVal) - { - case 0: - return SBF_ZERO; - case 1: - return SBF_ONE; - case 2: - return SBF_DEST_COLOUR; - case 3: - return SBF_ONE_MINUS_DEST_COLOUR; - case 4: - return SBF_SOURCE_ALPHA; - case 5: - return SBF_ONE_MINUS_SOURCE_ALPHA; - case 6: - return SBF_DEST_ALPHA; - case 7: - return SBF_ONE_MINUS_DEST_ALPHA; - }; - - return SBF_ZERO; - - } - -} - diff --git a/Tools/XSIExport/src/OgreXSIMeshExporter.cpp b/Tools/XSIExport/src/OgreXSIMeshExporter.cpp deleted file mode 100644 index 81696c33ac1..00000000000 --- a/Tools/XSIExport/src/OgreXSIMeshExporter.cpp +++ /dev/null @@ -1,1594 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreXSIMeshExporter.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "OgreException.h" -#include "OgreXSIHelper.h" -#include "OgreLogManager.h" -#include "OgreMeshManager.h" -#include "OgreMesh.h" -#include "OgreSubMesh.h" -#include "OgreMeshManager.h" -#include "OgreMeshSerializer.h" -#include "OgreHardwareBufferManager.h" -#include "OgreVertexBoneAssignment.h" -#include "OgrePose.h" -#include "OgreAnimation.h" -#include "OgreAnimationTrack.h" - -using namespace XSI; - - -namespace Ogre { - //----------------------------------------------------------------------- - XsiMeshExporter::UniqueVertex::UniqueVertex() - : position(Vector3::ZERO), normal(Vector3::ZERO), colour(0), nextIndex(0) - { - for (int i = 0; i < OGRE_MAX_TEXTURE_COORD_SETS; ++i) - uv[i] = Vector3::ZERO; - } - //----------------------------------------------------------------------- - bool XsiMeshExporter::UniqueVertex::operator==(const UniqueVertex& rhs) const - { - bool ret = position == rhs.position && - normal == rhs.normal && - colour == rhs.colour; - if (!ret) return ret; - - for (int i = 0; i < OGRE_MAX_TEXTURE_COORD_SETS && ret; ++i) - { - ret = ret && (uv[i] == rhs.uv[i]); - } - - return ret; - - - } - //----------------------------------------------------------------------- - //----------------------------------------------------------------------- - XsiMeshExporter::XsiMeshExporter() - { - } - //----------------------------------------------------------------------- - XsiMeshExporter::~XsiMeshExporter() - { - /// Tidy up - cleanupDeformerMap(); - cleanupMaterialMap(); - } - //----------------------------------------------------------------------- - DeformerMap& XsiMeshExporter::buildMeshForExport( - bool mergeSubMeshes, bool exportChildren, - bool edgeLists, bool tangents, VertexElementSemantic tangentSemantic, - bool tangentsSplitMirrored, bool tangentsSplitRotated, bool tangentsUseParity, - bool vertexAnimation, AnimationList& animList, Real fps, const String& materialPrefix, - LodData* lod, const String& skeletonName) - { - - LogOgreAndXSI(L"** Begin OGRE Mesh Export **"); - // Derive the scene root - X3DObject sceneRoot(mXsiApp.GetActiveSceneRoot()); - - // Construct mesh - mMesh = MeshManager::getSingleton().createManual("XSIExport", - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - - mMaterialPrefix = materialPrefix; - - cleanupDeformerMap(); - cleanupMaterialMap(); - mShapeKeyMapping.clear(); - - // Find all PolygonMesh objects - buildPolygonMeshList(exportChildren); - // progress report - ProgressManager::getSingleton().progress(); - - // notify of skeleton beforehand - if (!skeletonName.empty()) - { - mMesh->setSkeletonName(skeletonName); - } - - // write the data into a mesh - buildMesh(mMesh.get(), mergeSubMeshes, !skeletonName.empty(), - vertexAnimation, animList, fps); - - // progress report - ProgressManager::getSingleton().progress(); - - if (lod) - { - ProgressiveMesh::generateLodLevels(mMesh.get(), lod->distances, lod->quota, lod->reductionValue); - // progress report - ProgressManager::getSingleton().progress(); - } - - if(edgeLists) - { - LogOgreAndXSI(L"Calculating edge lists"); - mMesh->buildEdgeList(); - // progress report - ProgressManager::getSingleton().progress(); - } - - if(tangents) - { - LogOgreAndXSI(L"Calculating tangents"); - unsigned short src, dest; - if (!mMesh->suggestTangentVectorBuildParams(tangentSemantic, src, dest)) - { - mMesh->buildTangentVectors(tangentSemantic, src, dest, tangentsSplitMirrored, - tangentsSplitRotated, tangentsUseParity); - } - else - { - LogOgreAndXSI(L"Could not derive tangents parameters"); - } - // progress report - ProgressManager::getSingleton().progress(); - - } - - cleanupPolygonMeshList(); - - LogOgreAndXSI(L"** OGRE Mesh Export Complete **"); - - return mXsiDeformerMap; - } - //----------------------------------------------------------------------- - void XsiMeshExporter::exportMesh(const String& fileName, const AxisAlignedBox& skelAABB) - { - - // Pad bounds - AxisAlignedBox currBounds = mMesh->getBounds(); - currBounds.merge(skelAABB); - mMesh->_setBounds(currBounds, false); - - MeshSerializer serializer; - serializer.exportMesh(mMesh.get(), fileName); - - // progress report - ProgressManager::getSingleton().progress(); - - mMesh.reset(); - - - } - //----------------------------------------------------------------------- - MaterialMap& XsiMeshExporter::getMaterials(void) - { - return mXsiMaterialMap; - } - //----------------------------------------------------------------------- - TextureProjectionMap& XsiMeshExporter::getTextureProjectionMap(void) - { - return mTextureProjectionMap; - } - //----------------------------------------------------------------------- - void XsiMeshExporter::buildMesh(Mesh* pMesh, bool mergeSubmeshes, - bool lookForBoneAssignments, bool vertexAnimation, AnimationList& animList, - Real fps) - { - /* Iterate over the list of polygon meshes that we've already located. - For each one: - If we're not merging submeshes, bake any protosubmeshes built - into the mesh and clear the protosubmesh list - Scan the clusters for 'poly' clusters (which can contain material - discrepancies). Any that use a different material should be - noted in the polycluster list - Build ProtoSubMeshes by iterating over the triangles in the mesh, - building the list of UniqueVertices against the material as we - go. We check each triangle to see if the polygon index is in - the list of polyclusters & if so it goes into the other lists - - Finally, we bake any remaining protosubmeshes into submeshes. - */ - // Calculate the number of progress updates each mesh must raise - float progPerMesh = (float)OGRE_XSI_NUM_MESH_STEPS / (float)(mXsiPolygonMeshList.size()); - float currProg = 0.0f; - for (PolygonMeshList::iterator pm = mXsiPolygonMeshList.begin(); - pm != mXsiPolygonMeshList.end(); ++pm) - { - currProg += progPerMesh; - unsigned short progUpdates = (unsigned short)currProg; - currProg -= progUpdates; - // build contents of this polymesh into ProtoSubMesh(es) - processPolygonMesh(pMesh, *pm, lookForBoneAssignments, progUpdates); - - if (!mergeSubmeshes) - { - // export out at the end of every PolygonMesh - exportProtoSubMeshes(pMesh); - } - } - if (mergeSubmeshes) - { - // export out the combined result - exportProtoSubMeshes(pMesh); - } - - if (vertexAnimation) - { - exportAnimations(pMesh, animList, fps); - } - } - //----------------------------------------------------------------------- - XsiMeshExporter::ProtoSubMesh* XsiMeshExporter::createOrRetrieveProtoSubMesh( - const String& materialName, const String& name, - TextureCoordDimensionList& texCoordDims, bool hasVertexColours) - { - bool createNew = true; - ProtoSubMesh* ret = 0; - ProtoSubMeshList* protoList = 0; - - MaterialProtoSubMeshMap::iterator pi = mMaterialProtoSubmeshMap.find(materialName); - if (pi == mMaterialProtoSubmeshMap.end()) - { - protoList = new ProtoSubMeshList(); - mMaterialProtoSubmeshMap[materialName] = protoList; - } - else - { - // Iterate over the protos with the same material - protoList = pi->second; - - for (ProtoSubMeshList::iterator psi = protoList->begin(); psi != protoList->end(); ++psi) - { - ProtoSubMesh* candidate = *psi; - // Check format is compatible - if (candidate->textureCoordDimensions.size() != texCoordDims.size()) - { - continue; - } - if (candidate->hasVertexColours != hasVertexColours) - { - continue; - } - - bool compat = true; - std::vector::iterator t = texCoordDims.begin(); - std::vector::iterator u = candidate->textureCoordDimensions.begin(); - for (;t != texCoordDims.end(); ++t,++u) - { - if (*t != *u) - { - compat = false; - break; - } - } - - if (compat) - { - createNew = false; - ret = candidate; - break; - } - } - } - - if (createNew) - { - ret = new ProtoSubMesh(); - protoList->push_back(ret); - ret->materialName = materialName; - ret->name = name; - ret->textureCoordDimensions = texCoordDims; - ret->hasVertexColours = hasVertexColours; - } - - return ret; - - } - //----------------------------------------------------------------------- - void XsiMeshExporter::processPolygonMesh(Mesh* pMesh, PolygonMeshEntry* xsiMesh, - bool lookForBoneAssignments, unsigned short progressUpdates) - { - CRefArray uvs = xsiMesh->geometry.GetUVs(); - - StringStream msg; - msg << "-- " << XSItoOgre(xsiMesh->name) << " --" << std::endl; - msg << "Points: " << xsiMesh->geometry.GetVertexCount() << std::endl; - msg << "Triangles: " << xsiMesh->geometry.GetTriangleCount() << std::endl; - msg << "Normals: " << xsiMesh->geometry.GetNodeCount() << std::endl; - msg << "Num UVs: " << uvs.GetCount() << std::endl; - String str = msg.str(); - LogOgreAndXSI(str); - - if (uvs.GetCount() > OGRE_MAX_TEXTURE_COORD_SETS) - { - // too many texture coordinates! - StringStream str; - str << "PolygonMesh '" << XSItoOgre(xsiMesh->name) - << "' has too many texture coordinate sets (" - << uvs.GetCount() - << "); the limit is " << OGRE_MAX_TEXTURE_COORD_SETS; - - OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, str.str(), - "XsiMeshExporter::processPolygonMesh"); - } - - // Collect texture coordinates data - TextureCoordDimensionList textureCoordDimensions; - SamplerSetList samplerSets; - textureCoordDimensions.reserve(uvs.GetCount()); - samplerSets.reserve(uvs.GetCount()); - for (int i = 0; i < uvs.GetCount(); ++ i) - { - Vector3* samplerUVs = new Vector3[xsiMesh->geometry.GetNodeCount()]; - samplerSets.push_back(samplerUVs); - - ClusterProperty uvProp = uvs[i]; - CFloatArray uvValues; - uvProp.GetValues(uvValues); - - String textureProjectionName = XSItoOgre(uvProp.GetName()); - mTextureProjectionMap[textureProjectionName] = i; - - int usedDims = 0; - for (int j = 0; j < xsiMesh->geometry.GetNodeCount(); ++j) - { - if ((samplerUVs[j].x = uvValues[j * 3]) != 0) - usedDims |= 1; //u - if ((samplerUVs[j].y = 1.0f - uvValues[j * 3 + 1]) != 0) - usedDims |= 2; //v (invert) - if ((samplerUVs[j].z = uvValues[j * 3 + 2]) != 0) - usedDims |= 4; //w - } - - if (usedDims & 4) // w - textureCoordDimensions.push_back(3); - else if (usedDims & 2) // v - textureCoordDimensions.push_back(2); - else // u - textureCoordDimensions.push_back(1); - } - - - // Save transforms - MATH::CTransformation xsiTransform = xsiMesh->transform; - MATH::CTransformation rotTrans; - rotTrans.SetRotation(xsiTransform.GetRotation()); - - // Bounds calculation - Real squaredRadius = 0.0f; - Vector3 min, max; - bool first = true; - - UniqueVertex vertex; - - - float progPerTri = (float)progressUpdates / xsiMesh->geometry.GetTriangleCount(); - float prog = 0.0f; - - CLongArray polygonTriangleIndices; - xsiMesh->geometry.GetPolygonTriangleIndices(polygonTriangleIndices); - - CLongArray triangleVertexIndices; - xsiMesh->geometry.GetTriangleVertexIndices(triangleVertexIndices); - - CDoubleArray vertexPositions; - xsiMesh->geometry.GetVertexPositions(vertexPositions); - - CRefArray vertexColours = xsiMesh->geometry.GetVertexColors(); - bool hasVertexColours = vertexColours.GetCount() > 0? true : false; - CFloatArray vertexColoursValues; - if (hasVertexColours) - { - ClusterProperty c = vertexColours[0]; - c.GetValues(vertexColoursValues); - } - - CFloatArray nodeNormals; - xsiMesh->geometry.GetNodeNormals(nodeNormals); - - CLongArray triangleNodeIndices; - xsiMesh->geometry.GetTriangleNodeIndices(triangleNodeIndices); - - CLongArray polygonMaterialIndices; - xsiMesh->geometry.GetPolygonMaterialIndices(polygonMaterialIndices); - - CRefArray materials = xsiMesh->geometry.GetMaterials(); - - ProtoSubMesh** materialToProtoSubMesh = new ProtoSubMesh*[materials.GetCount()]; - for (LONG i = 0; i < materials.GetCount(); ++ i) - materialToProtoSubMesh[i] = 0; - - CRefArray polygonClusters = xsiMesh->geometry.GetClusters(siClusterPolygonType); - - // Test for hidden polygons - XSI::CBitArray hiddenPolygons(xsiMesh->geometry.GetPolygonCount()); - for (LONG c = 0; c < polygonClusters.GetCount(); ++ c) - { - XSI::Cluster cluster = XSI::Cluster(polygonClusters[c]); - XSI::CRef clsvisibility; - - if (cluster.GetProperties().Find(L"clsvisibility", clsvisibility) == CStatus::OK) - { - Property p(clsvisibility); - if (!p.GetParameterValue(L"viewvis")) - { - XSI::CBitArray clusterPolys; - cluster.GetGeometryElementFlags(clusterPolys); - hiddenPolygons.Or(clusterPolys); - } - } - } - - // Iterate through all the triangles - for (long t = 0; t < xsiMesh->geometry.GetTriangleCount(); ++t) - { - // Skip the triangle if it relates to a hidden polygon - if (hiddenPolygons[polygonTriangleIndices[t]]) - continue; - - LONG polygonIndex = polygonTriangleIndices[t]; - LONG materialIndex = polygonMaterialIndices[polygonIndex]; - ProtoSubMesh* currentProto = materialToProtoSubMesh[materialIndex]; - - // Do we already have a protosubmesh for the material of this triangle? - if (!currentProto) - { - CString SubMeshName = xsiMesh->name; - - XSI::Material m(materials[materialIndex]); - - // Use the name of the cluster as the submesh name - for (LONG c = 0; c < polygonClusters.GetCount(); ++ c) - { - XSI::Cluster cluster = XSI::Cluster(polygonClusters[c]); - if (cluster.GetMaterial().GetName() == m.GetName()) - { - LONG out_clusterIndex; - cluster.FindIndex(polygonIndex, out_clusterIndex); - if (out_clusterIndex != -1) - { - SubMeshName = cluster.GetName(); - break; - } - } - } - - currentProto = materialToProtoSubMesh[materialIndex] = createOrRetrieveProtoSubMesh( - mMaterialPrefix + XSItoOgre(m.GetName()), - XSItoOgre(SubMeshName), - textureCoordDimensions, - hasVertexColours); - } - - // has this mesh been used in this proto before? if not set offset - size_t positionIndexOffset; - if (currentProto->lastMeshEntry == xsiMesh) - { - positionIndexOffset = currentProto->lastMeshIndexOffset; - } - else - { - // first time this has been used - // since we assume we 100% process each polygon mesh before the next, - // just use last pointer since faster in this section - currentProto->lastMeshEntry = xsiMesh; - positionIndexOffset = currentProto->indices.size(); - currentProto->lastMeshIndexOffset = positionIndexOffset; - // Also have to store this for future reference - currentProto->polygonMeshOffsetMap[xsiMesh] = positionIndexOffset; - } - - for (long p = 0; p < 3; ++p) - { - LONG posIndex = triangleVertexIndices[t * 3 + p]; // unique position index - - // Get position - MATH::CVector3 xsipos(vertexPositions[posIndex * 3], - vertexPositions[posIndex * 3 + 1], - vertexPositions[posIndex * 3 + 2]); - - // Apply global SRT - xsipos.MulByTransformationInPlace(xsiTransform); - vertex.position = XSItoOgre(xsipos); - - // Get normal - MATH::CVector3 xsinorm(nodeNormals[triangleNodeIndices[t * 3 + p] * 3], - nodeNormals[triangleNodeIndices[t * 3 + p] * 3 + 1], - nodeNormals[triangleNodeIndices[t * 3 + p] * 3 + 2]); - - // Apply global rotation - xsinorm *= rotTrans; - vertex.normal = XSItoOgre(xsinorm); - - for (size_t i = 0; i < textureCoordDimensions.size(); ++i) - { - // sampler indices can correctly dereference to sampler-order - // uv sets we built earlier - vertex.uv[i] = (samplerSets[i])[triangleNodeIndices[t * 3 + p]]; - } - - if (hasVertexColours) - { - vertex.colour = XSItoOgre(CVertexColor((unsigned char)(vertexColoursValues[posIndex * 4] * 255), - (unsigned char)(vertexColoursValues[posIndex * 4 + 1] * 255), - (unsigned char)(vertexColoursValues[posIndex * 4 + 2] * 255), - (unsigned char)(vertexColoursValues[posIndex * 4 + 3] * 255))); - } - - // adjust index per offset, this makes position indices unique - // per polymesh in teh same protosubmesh - posIndex += positionIndexOffset; - - size_t index = createOrRetrieveUniqueVertex( - currentProto, posIndex, true, vertex); - currentProto->indices.push_back(index); - - // bounds - if (first) - { - squaredRadius = vertex.position.squaredLength(); - min = max = vertex.position; - first = false; - } - else - { - squaredRadius = - std::max(squaredRadius, vertex.position.squaredLength()); - min.makeFloor(vertex.position); - max.makeCeil(vertex.position); - } - } - - // Progress - prog += progPerTri; - while (prog >= 1.0f) - { - ProgressManager::getSingleton().progress(); - prog -= 1.0f; - } - - } - - // Merge bounds - AxisAlignedBox box; - box.setExtents(min, max); - box.merge(pMesh->getBounds()); - pMesh->_setBounds(box, false); - pMesh->_setBoundingSphereRadius( - std::max( - pMesh->getBoundingSphereRadius(), - Math::Sqrt(squaredRadius))); - - // Deal with any bone assignments - if (lookForBoneAssignments) - { - processBoneAssignments(pMesh, xsiMesh); - } - - // process any shape keys - processShapeKeys(pMesh, xsiMesh); - - // free temp UV data now - for(SamplerSetList::iterator s = samplerSets.begin(); - s != samplerSets.end(); ++s) - { - // init sampler points - delete [] *s; - } - samplerSets.clear(); - textureCoordDimensions.clear(); - } - //----------------------------------------------------------------------- - void XsiMeshExporter::processBoneAssignments(Mesh* pMesh, PolygonMeshEntry* xsiMesh) - { - // We have to iterate over the clusters which have envelope assignments - // then, for each protosubmesh which uses this polymesh, we need to create - // a bone assignment for each deformer, not forgetting to add one for - // each duplicated copy of this vertex too - // We build up a global list of deformers as we go which will get passed - // back to the top-level caller to build a skeleton from later - CRefArray clusterRefArray; - // Filter to 'vertex' types - xsiMesh->geometry.GetClusters().Filter( - siVertexCluster,CStringArray(),L"",clusterRefArray); - - - - for(int i = 0; i < clusterRefArray.GetCount(); ++i) - { - Cluster cluster(clusterRefArray[i]); - - CRefArray envelopes = cluster.GetEnvelopes(); - for (int e = 0; e < envelopes.GetCount(); ++e) - { - Envelope envelope(envelopes[e]); - - // Get mapping from cluster element index to geometry position index - CLongArray derefArray = envelope.GetElements(CTime().GetTime()).GetArray(); - - CRefArray deformers = envelope.GetDeformers(); - for (int d = 0; d < deformers.GetCount(); ++d) - { - X3DObject deformer(deformers[d]); - // Has this deformer been allocated a boneID already? - String deformerName = XSItoOgre(deformer.GetName()); - DeformerMap::iterator di = - mXsiDeformerMap.find(deformerName); - DeformerEntry* deformerEntry; - bool newDeformerEntry = false; - bool atLeastOneAssignment = false; - if (di == mXsiDeformerMap.end()) - { - deformerEntry = new DeformerEntry(mXsiDeformerMap.size(), deformer); - deformerEntry->hasVertexAssignments = true; - newDeformerEntry = true; - } - else - { - deformerEntry = di->second; - } - - // Get the weights for this deformer - CDoubleArray weights = - envelope.GetDeformerWeights(deformer, CTime().GetTime()); - // Weights are in order of cluster elements, we need to dereference - // those to the original point index using the cluster element array - for (int w = 0; w < weights.GetCount(); ++w) - { - size_t positionIndex = derefArray[w]; - float weight = weights[w]; - // Skip zero weights - if (weight == 0.0f) - continue; - - // Locate ProtoSubMeshes which use this mesh - for (MaterialProtoSubMeshMap::iterator mi = mMaterialProtoSubmeshMap.begin(); - mi != mMaterialProtoSubmeshMap.end(); ++mi) - { - for (ProtoSubMeshList::iterator psi = mi->second->begin(); - psi != mi->second->end(); ++psi) - { - ProtoSubMesh* ps = *psi; - ProtoSubMesh::PolygonMeshOffsetMap::iterator poli = - ps->polygonMeshOffsetMap.find(xsiMesh); - if (poli != ps->polygonMeshOffsetMap.end()) - { - // adjust index based on merging - size_t adjIndex = positionIndex + poli->second; - // look up real index - // If it doesn't exist, it's probably on a seam - // between clusters and we can safely skip it - IndexRemap::iterator remi = ps->posIndexRemap.find(adjIndex); - if (remi != ps->posIndexRemap.end()) - { - - size_t vertIndex = remi->second; - bool moreVerts = true; - // add UniqueVertex and clones - while (moreVerts) - { - UniqueVertex& vertex = ps->uniqueVertices[vertIndex]; - VertexBoneAssignment vba; - vba.boneIndex = deformerEntry->boneID; - vba.vertexIndex = vertIndex; - vba.weight = weight; - ps->boneAssignments.insert( - Mesh::VertexBoneAssignmentList::value_type(vertIndex, vba)); - atLeastOneAssignment = true; - - if (vertex.nextIndex == 0) - { - moreVerts = false; - } - else - { - vertIndex = vertex.nextIndex; - } - } - } - - } - } - - } - - - - } - - // Only add new deformer if we actually had any assignments - if (newDeformerEntry && atLeastOneAssignment) - { - mXsiDeformerMap[deformerName] = deformerEntry; - } - - - - - } - - - } - } - - - } - //----------------------------------------------------------------------- - void XsiMeshExporter::processShapeKeys(Mesh* pMesh, PolygonMeshEntry* xsiMesh) - { - CRefArray shapeKeys = xsiMesh->geometry.GetShapeKeys(); - - for (int i = 0; i < shapeKeys.GetCount(); ++ i) - { - ShapeKey shapeKey = shapeKeys[i]; - LogOgreAndXSI("Found shape key " + XSItoOgre(shapeKey.GetName())); - - // Locate ProtoSubMeshes which use this mesh - for (MaterialProtoSubMeshMap::iterator mi = mMaterialProtoSubmeshMap.begin(); - mi != mMaterialProtoSubmeshMap.end(); ++mi) - { - for (ProtoSubMeshList::iterator psi = mi->second->begin(); - psi != mi->second->end(); ++psi) - { - ProtoSubMesh* ps = *psi; - ProtoSubMesh::PolygonMeshOffsetMap::iterator poli = - ps->polygonMeshOffsetMap.find(xsiMesh); - if (poli != ps->polygonMeshOffsetMap.end()) - { - // remap from mesh vertex index to proto vertex index - size_t indexAdjustment = poli->second; - - // Create a new pose, target is implied by proto, final - // index to be determined later including merging - Pose pose(0, XSItoOgre(shapeKey.GetName())); - - CBitArray affectedPoints; - CFloatArray shapeValues; - shapeKey.GetValues(shapeValues, affectedPoints); // automatically converted to object relative reference mode - - // Iterate per vertex affected - LONG idxPoint = affectedPoints.GetIterator(); - while (affectedPoints.GetNextTrueBit(idxPoint) ) - { - // Now get offset - Vector3 offset(shapeValues[idxPoint * 3], shapeValues[idxPoint * 3 + 1], shapeValues[idxPoint * 3 + 2]); - - // Skip zero offsets - if (offset == Vector3::ZERO) - continue; - - // Convert to world space - MATH::CVector3 off(offset.x, offset.y, offset.z); - off.MulByTransformationInPlace(xsiMesh->transform); - offset = XSItoOgre(off); - - // adjust index based on merging - size_t adjIndex = idxPoint + indexAdjustment; - - // look up real index - // If it doesn't exist, it's probably on a seam - // between clusters and we can safely skip it - IndexRemap::iterator remi = ps->posIndexRemap.find(adjIndex); - if (remi != ps->posIndexRemap.end()) - { - size_t vertIndex = remi->second; - bool moreVerts = true; - - // add UniqueVertex and clones - while (moreVerts) - { - UniqueVertex& vertex = ps->uniqueVertices[vertIndex]; - - // Create a vertex pose entry - pose.addVertex(vertIndex, offset); - - if (vertex.nextIndex == 0) - { - moreVerts = false; - } - else - { - vertIndex = vertex.nextIndex; - } - } // more duplicate verts - } // found remap? - } // for each vertex affected - - // Add pose to proto - ps->poseList.push_back(pose); - - // record that we used this shape key - ps->shapeKeys.Add(shapeKey); - } // proto found? - } // for each proto - } - } - } - //----------------------------------------------------------------------- - void XsiMeshExporter::buildShapeClipList(ShapeClipList& listToPopulate) - { - // Process all mixers - Model root = mXsiApp.GetActiveSceneRoot(); - if (root.HasMixer()) - { - XSI::Mixer mixer = root.GetMixer(); - buildShapeClipList(mixer, listToPopulate); - } - - // Get all child models (recursive) - CRefArray models = root.GetModels(); - for (int m = 0; m < models.GetCount(); ++m) - { - Model model(models[m]); - if (model.HasMixer()) - { - XSI::Mixer mixer = root.GetMixer(); - buildShapeClipList(mixer, listToPopulate); - } - } - - } - //----------------------------------------------------------------------- - void XsiMeshExporter::buildShapeClipList(ClipContainer& container, - ShapeClipList& listToPopulate) - { - CRefArray clips = container.GetClips(); - for (int c = 0; c < clips.GetCount(); ++c) - { - if (clips[c].IsA(siClipContainerID)) - { - ClipContainer container(clips[c]); - // cascade - buildShapeClipList(container, listToPopulate); - } - else - { - - XSI::Clip clip(clips[c]); - XSI::CString clipType = clip.GetType(); - if (clip.GetType() == siClipShapeType) - { - XSI::TimeControl timeControl = clip.GetTimeControl(); - ShapeClipEntry sce; - sce.clip = clip; - sce.startFrame = sce.originalStartFrame = timeControl.GetStartOffset(); - long length = (1.0 / timeControl.GetScale()) * - (timeControl.GetClipOut() - timeControl.GetClipIn() + 1); - sce.endFrame = sce.startFrame + length - 1; - - // Find link to shape - sce.keytoPose = 0; - ActionSource source(clip.GetSource()); - CRefArray sourceItems = source.GetItems(); - assert (sourceItems.GetCount() == 1 && "More than one source item on shape clip!"); - AnimationSourceItem sourceItem(sourceItems[0]); - // Source is the shape key - // Locate this in the list we built while building poses - for (ShapeKeyMapping::iterator skm = mShapeKeyMapping.begin(); - skm != mShapeKeyMapping.end(); ++skm) - { - ShapeKeyToPoseEntry& mapping = *skm; - if(mapping.shapeKey == sourceItem.GetSource()) - { - // bingo - sce.keytoPose = &(*skm); - } - } - - listToPopulate.push_back(sce); - - } - } - - } - - - } - //----------------------------------------------------------------------- - void XsiMeshExporter::exportAnimations(Mesh* pMesh, AnimationList& animList, - Real fps) - { - ShapeClipList clipList; - buildShapeClipList(clipList); - // Add all animations - for (AnimationList::iterator i = animList.begin(); i != animList.end(); ++i) - { - // For each animation, we want to search for all shape clips using a - // shape key which has been used - AnimationEntry& animEntry = *i; - Animation* anim = 0; - - // Iterate per submesh since we want to collect a track per submesh - // Iterate over the 'target index' which is submesh index + 1 - for (ushort targetIndex = 1; targetIndex <= pMesh->getNumSubMeshes(); ++targetIndex) - { - // find all shape clips for this submesh overlapping this time period - // we'll clamp the clip too - ShapeClipList submeshClipList; - std::set keyframeList; - - deriveShapeClipAndKeyframeList(targetIndex, animEntry, clipList, - submeshClipList, keyframeList); - - if (!submeshClipList.empty()) - { - - // Create animation if we haven't already - if (!anim) - { - Real len = (float)(animEntry.endFrame - animEntry.startFrame + 1) / fps; - anim = pMesh->createAnimation(animEntry.animationName, len); - } - - // Create track - VertexAnimationTrack* track = - anim->createVertexTrack(targetIndex, VAT_POSE); - - // Now sample all the clips on all the keyframes - for (std::set::iterator k = keyframeList.begin(); - k != keyframeList.end(); ++k) - { - // Create a key - long frameNum = *k; - Real keyTime = (float)(frameNum - animEntry.startFrame) / fps; - VertexPoseKeyFrame* keyFrame = - track->createVertexPoseKeyFrame(keyTime); - - // Sample all the clips - for (ShapeClipList::iterator c = submeshClipList.begin(); - c != submeshClipList.end(); ++c) - { - ShapeClipEntry& sce = *c; - if(frameNum >= sce.startFrame && - frameNum <= sce.endFrame) - { - - // map the keyframe number to a local number - long localFrameNum = frameNum - sce.originalStartFrame * - sce.clip.GetTimeControl().GetScale(); - - // sample pose influences - // Iterate over the animated parameters, find a 'weight' fcurve entry - bool fcurveFound = false; - CRefArray params = sce.clip.GetAnimatedParameters(); - for (int p = 0; p < params.GetCount(); ++p) - { - Parameter param(params[p]); - if (param.GetSource().IsA(siFCurveID)) - { - fcurveFound = true; - FCurve fcurve(param.GetSource()); - CValue val = fcurve.Eval(localFrameNum); - if ((float)val != 0.0f) - { - keyFrame->addPoseReference( - sce.keytoPose->poseIndex, val); - } - - } - } - - if (!fcurveFound) - { - // No fcurves, so just assume 1.0 weight since that's - // how XSI deals with it - keyFrame->addPoseReference(sce.keytoPose->poseIndex, 1.0f); - - } - } - } - } - - } - - } - } - - } - //----------------------------------------------------------------------- - void XsiMeshExporter::deriveShapeClipAndKeyframeList(ushort targetIndex, - AnimationEntry& animEntry, ShapeClipList& inClipList, - ShapeClipList& outClipList, std::set& keyFrameList) - { - for (ShapeClipList::iterator sci = inClipList.begin(); - sci != inClipList.end(); ++sci) - { - ShapeClipEntry& sce = *sci; - - if (sce.startFrame <= animEntry.endFrame && - sce.endFrame >= animEntry.startFrame && - sce.keytoPose->targetHandle == targetIndex) - { - // Clip overlaps with the animation sampling area and - // applies to this submesh - ShapeClipEntry newClipEntry; - newClipEntry.originalStartFrame = sce.startFrame; - newClipEntry.startFrame = std::max(sce.startFrame, animEntry.startFrame); - newClipEntry.endFrame = std::min(sce.endFrame, animEntry.endFrame); - newClipEntry.clip = sce.clip; - newClipEntry.keytoPose = sce.keytoPose; - outClipList.push_back(newClipEntry); - - // Iterate over the animated parameters, find a 'weight' fcurve entry - CRefArray params = sce.clip.GetAnimatedParameters(); - for (int p = 0; p < params.GetCount(); ++p) - { - Parameter param(params[p]); - if (param.GetSource().IsA(siFCurveID)) - { - FCurve fcurve(param.GetSource()); - CRefArray keys = fcurve.GetKeys(); - for (int k = 0; k < keys.GetCount(); ++k) - { - FCurveKey key(keys[k]); - // convert from key time to global frame number - CTime time = key.GetTime(); - long frameNum = (long)((double)(time.GetTime() + sce.startFrame) - / sce.clip.GetTimeControl().GetScale()); - keyFrameList.insert(frameNum); - } - - - } - } - - } - } - // Always sample start & end frames - keyFrameList.insert(animEntry.startFrame); - keyFrameList.insert(animEntry.endFrame); - - } - //----------------------------------------------------------------------- - void XsiMeshExporter::exportProtoSubMeshes(Mesh* pMesh) - { - // Take the list of ProtoSubMesh instances and bake a SubMesh per - // instance, then clear the list - - for (MaterialProtoSubMeshMap::iterator mi = mMaterialProtoSubmeshMap.begin(); - mi != mMaterialProtoSubmeshMap.end(); ++mi) - { - for (ProtoSubMeshList::iterator psi = mi->second->begin(); - psi != mi->second->end(); ++psi) - { - // export each one - exportProtoSubMesh(pMesh, *psi); - - // free it - delete *psi; - } - // delete proto list - delete mi->second; - } - mMaterialProtoSubmeshMap.clear(); - } - //----------------------------------------------------------------------- - void XsiMeshExporter::exportProtoSubMesh(Mesh* pMesh, ProtoSubMesh* proto) - { - // Skip protos which have ended up empty - if (proto->indices.empty()) - return; - - SubMesh* sm = 0; - if (proto->name.empty()) - { - // anonymous submesh - sm = pMesh->createSubMesh(); - } - else - { - // named submesh - sm = pMesh->createSubMesh(proto->name); - } - - // Set material - sm->setMaterialName(proto->materialName); - // never use shared geometry - sm->useSharedVertices = false; - sm->vertexData = new VertexData(); - // always do triangle list - sm->indexData->indexCount = proto->indices.size(); - - sm->vertexData->vertexCount = proto->uniqueVertices.size(); - // Determine index size - bool use32BitIndexes = false; - if (proto->uniqueVertices.size() > 65536) - { - use32BitIndexes = true; - } - - sm->indexData->indexBuffer = - HardwareBufferManager::getSingleton().createIndexBuffer( - use32BitIndexes ? HardwareIndexBuffer::IT_32BIT : HardwareIndexBuffer::IT_16BIT, - sm->indexData->indexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - if (use32BitIndexes) - { - uint32* pIdx = static_cast( - sm->indexData->indexBuffer->lock(HardwareBuffer::HBL_DISCARD)); - writeIndexes(pIdx, proto->indices); - sm->indexData->indexBuffer->unlock(); - } - else - { - uint16* pIdx = static_cast( - sm->indexData->indexBuffer->lock(HardwareBuffer::HBL_DISCARD)); - writeIndexes(pIdx, proto->indices); - sm->indexData->indexBuffer->unlock(); - } - - - // define vertex declaration - unsigned buf = 0; - size_t offset = 0; - // always add position and normal - sm->vertexData->vertexDeclaration->addElement(buf, offset, VET_FLOAT3, VES_POSITION); - offset += VertexElement::getTypeSize(VET_FLOAT3); - // Split vertex data after position if poses present - if (!proto->poseList.empty()) - { - buf++; - offset = 0; - } - sm->vertexData->vertexDeclaration->addElement(buf, offset, VET_FLOAT3, VES_NORMAL); - offset += VertexElement::getTypeSize(VET_FLOAT3); - // split vertex data here if animated - if (pMesh->hasSkeleton()) - { - buf++; - offset = 0; - } - // Optional vertex colour - if(proto->hasVertexColours) - { - sm->vertexData->vertexDeclaration->addElement(buf, offset, VET_COLOUR, VES_DIFFUSE); - offset += VertexElement::getTypeSize(VET_COLOUR); - } - // Define UVs - for (unsigned short uvi = 0; uvi < proto->textureCoordDimensions.size(); ++uvi) - { - VertexElementType uvType = - VertexElement::multiplyTypeCount( - VET_FLOAT1, proto->textureCoordDimensions[uvi]); - sm->vertexData->vertexDeclaration->addElement( - buf, offset, uvType, VES_TEXTURE_COORDINATES, uvi); - offset += VertexElement::getTypeSize(uvType); - } - - // create & fill buffer(s) - for (unsigned short b = 0; b <= sm->vertexData->vertexDeclaration->getMaxSource(); ++b) - { - createVertexBuffer(sm->vertexData, b, proto->uniqueVertices); - } - - // deal with any bone assignments - if (!proto->boneAssignments.empty()) - { - // rationalise first (normalises and strips out any excessive bones) - sm->parent->_rationaliseBoneAssignments( - sm->vertexData->vertexCount, proto->boneAssignments); - - for (Mesh::VertexBoneAssignmentList::iterator bi = proto->boneAssignments.begin(); - bi != proto->boneAssignments.end(); ++bi) - { - sm->addBoneAssignment(bi->second); - } - } - - // poses - // derive target index (current submesh index + 1 since 0 is shared geom) - ushort targetIndex = pMesh->getNumSubMeshes(); - ushort sk = 0; - for (std::list::iterator pi = proto->poseList.begin(); - pi != proto->poseList.end(); ++pi, ++sk) - { - Pose* pose = pMesh->createPose(targetIndex, pi->getName()); - Pose::VertexOffsetIterator vertIt = - pi->getVertexOffsetIterator(); - while (vertIt.hasMoreElements()) - { - pose->addVertex(vertIt.peekNextKey(), vertIt.peekNextValue()); - vertIt.getNext(); - } - - // record shape key to pose mapping for animation later - ShapeKeyToPoseEntry se; - se.shapeKey = proto->shapeKeys[sk]; - se.poseIndex = pMesh->getPoseCount() - 1; - se.targetHandle = targetIndex; - mShapeKeyMapping.push_back(se); - - } - - } - //----------------------------------------------------------------------- - void XsiMeshExporter::buildPolygonMeshList(bool includeChildren) - { - Selection sel(mXsiApp.GetSelection()); - if (sel.GetCount() == 0) - { - // Whole scene - // Derive the scene root - X3DObject sceneRoot(mXsiApp.GetActiveSceneRoot()); - findPolygonMeshes(sceneRoot, true); - } - else - { - // iterate over selection - for (int i = 0; i < sel.GetCount(); ++i) - { - X3DObject obj(sel[i]); - findPolygonMeshes(obj,includeChildren); - } - } - } - //----------------------------------------------------------------------- - void XsiMeshExporter::findPolygonMeshes(X3DObject& x3dObj, bool recurse) - { - // Check validity of current object - if (!x3dObj.IsValid()) - { - OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, - "Invalid X3DObject found", - "XsiMeshExporter::exportX3DObject"); - } - // Log a message in script window - CString name = x3dObj.GetName() ; - LogOgreAndXSI(L"-- Traversing " + name) ; - - - // locate any geometry - if (!x3dObj.IsA(siCameraID) && - !x3dObj.IsA(siLightID) && - !x3dObj.IsA(siNullID) && - !x3dObj.IsA(siModelID)) - { - Primitive prim(x3dObj.GetActivePrimitive()); - if (prim.IsValid()) - { - Geometry geom(prim.GetGeometry()); - if (geom.GetRef().GetClassID() == siPolygonMeshID) - { - // Find the current level of subdivision - LONG subd = 0; - XSI::CRef geomapprox; - if (x3dObj.GetProperties().Find(L"geomapprox", geomapprox) == CStatus::OK) - { - Property p(geomapprox); - subd = p.GetParameterValue(L"gapproxmosl"); - } - - // add it to the list - PolygonMesh pmesh(geom); - mXsiPolygonMeshList.insert( - new PolygonMeshEntry(x3dObj.GetName(), x3dObj.GetKinematics().GetGlobal().GetTransform(), pmesh.GetGeometryAccessor(siConstructionModeSecondaryShape, siCatmullClark, subd))); - - LogOgreAndXSI(L"-- Queueing " + name) ; - } - } - - } - - // Cascade into children - if (recurse) - { - CRefArray children = x3dObj.GetChildren(); - - for(long i = 0; i < children.GetCount(); i++) - { - X3DObject childObj = children[i]; - findPolygonMeshes(childObj, recurse); - } - } - - } - //----------------------------------------------------------------------- - void XsiMeshExporter::cleanupPolygonMeshList(void) - { - for (PolygonMeshList::iterator pm = mXsiPolygonMeshList.begin(); - pm != mXsiPolygonMeshList.end(); ++pm) - { - delete *pm; - } - mXsiPolygonMeshList.clear(); - } - //----------------------------------------------------------------------- - void XsiMeshExporter::cleanupDeformerMap(void) - { - for (DeformerMap::iterator d = mXsiDeformerMap.begin(); - d != mXsiDeformerMap.end(); ++d) - { - delete d->second; - } - mXsiDeformerMap.clear(); - } - //----------------------------------------------------------------------- - void XsiMeshExporter::cleanupMaterialMap(void) - { - for (MaterialMap::iterator d = mXsiMaterialMap.begin(); - d != mXsiMaterialMap.end(); ++d) - { - delete d->second; - } - mXsiMaterialMap.clear(); - } - //----------------------------------------------------------------------- - void XsiMeshExporter::deriveSamplerIndices(const Triangle& tri, - const PolygonFace& face, size_t* samplerIndices) - { - //We want to find what is the SampleIndex associated with 3 - //vertex in a Triangle - CPointRefArray facePoints = face.GetPoints(); - - //Get the position of the 3 vertex in the triangle - MATH::CVector3Array triPos = tri.GetPositionArray(); - - //Get the position of the N Points in the polygon - MATH::CVector3Array facePos = facePoints.GetPositionArray(); - - //To know if the 3 vertex have a point in the same position - bool found[3]; - found[0] = false; - found[1] = false; - found[2] = false; - - int p,t; - //For the 3 triangle vertices - for(t=0; t<3 ; t++) - { //for each polygon point - for(p=0; p - void XsiMeshExporter::writeIndexes(T* buf, IndexList& indexes) - { - IndexList::const_iterator i, iend; - iend = indexes.end(); - for (i = indexes.begin(); i != iend; ++i) - { - *buf++ = static_cast(*i); - } - } - //----------------------------------------------------------------------- - void XsiMeshExporter::createVertexBuffer(VertexData* vd, - unsigned short bufIdx, UniqueVertexList& uniqueVertexList) - { - HardwareVertexBufferSharedPtr vbuf = - HardwareBufferManager::getSingleton().createVertexBuffer( - vd->vertexDeclaration->getVertexSize(bufIdx), - vd->vertexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - vd->vertexBufferBinding->setBinding(bufIdx, vbuf); - size_t vertexSize = vd->vertexDeclaration->getVertexSize(bufIdx); - - char* pBase = static_cast( - vbuf->lock(HardwareBuffer::HBL_DISCARD)); - - VertexDeclaration::VertexElementList elems = - vd->vertexDeclaration->findElementsBySource(bufIdx); - VertexDeclaration::VertexElementList::iterator ei, eiend; - eiend = elems.end(); - float* pFloat; - RGBA* pRGBA; - - UniqueVertexList::iterator srci = uniqueVertexList.begin(); - - for (size_t v = 0; v < vd->vertexCount; ++v, ++srci) - { - for (ei = elems.begin(); ei != eiend; ++ei) - { - VertexElement& elem = *ei; - switch(elem.getSemantic()) - { - case VES_POSITION: - elem.baseVertexPointerToElement(pBase, &pFloat); - *pFloat++ = srci->position.x; - *pFloat++ = srci->position.y; - *pFloat++ = srci->position.z; - break; - case VES_NORMAL: - elem.baseVertexPointerToElement(pBase, &pFloat); - *pFloat++ = srci->normal.x; - *pFloat++ = srci->normal.y; - *pFloat++ = srci->normal.z; - break; - case VES_DIFFUSE: - elem.baseVertexPointerToElement(pBase, &pRGBA); - *pRGBA = srci->colour; - break; - case VES_TEXTURE_COORDINATES: - elem.baseVertexPointerToElement(pBase, &pFloat); - for (int t = 0; t < VertexElement::getTypeCount(elem.getType()); ++t) - { - Real val = srci->uv[elem.getIndex()][t]; - *pFloat++ = val; - } - break; - } - } - pBase += vertexSize; - } - vbuf->unlock(); - - } - //----------------------------------------------------------------------- - size_t XsiMeshExporter::createOrRetrieveUniqueVertex( - ProtoSubMesh* proto, size_t positionIndex, - bool positionIndexIsOriginal, const UniqueVertex& vertex) - { - size_t lookupIndex; - if (positionIndexIsOriginal) - { - // look up the original index - IndexRemap::iterator remapi = - proto->posIndexRemap.find(positionIndex); - if (remapi == proto->posIndexRemap.end()) - { - // not found, add - size_t realIndex = proto->uniqueVertices.size(); - // add remap entry so we can find this again - proto->posIndexRemap[positionIndex] = realIndex; - proto->uniqueVertices.push_back(vertex); - return realIndex; - } - else - { - // Found existing mapping - lookupIndex = remapi->second; - } - } - else - { - // Not an original index, index is real - lookupIndex = positionIndex; - } - - // If we get here, either the position isn't an original index (ie - // we've already found that it doesn't match, and have cascaded) - // or there is an existing entry - // Get existing - UniqueVertex& orig = proto->uniqueVertices[lookupIndex]; - // Compare, do we have the same details? - if (orig == vertex) - { - // ok, they match - return lookupIndex; - } - else - { - // no match, go to next or create new - if (orig.nextIndex) - { - // cascade to the next candidate (which is a real index, not an original) - return createOrRetrieveUniqueVertex( - proto, orig.nextIndex, false, vertex); - } - else - { - // No more cascades to check, must be a new one - // get new index - size_t realIndex = proto->uniqueVertices.size(); - orig.nextIndex = realIndex; - // create new (NB invalidates 'orig' reference) - proto->uniqueVertices.push_back(vertex); - // note, don't add to remap, that's only for finding the - // first entry, nextIndex is used to chain to the others - - return realIndex; - } - } - } - //----------------------------------------------------------------------- - void XsiMeshExporter::registerMaterial(const String& name, - XSI::Material mat) - { - // Check we have a real-time shader based material first - XSI::Parameter rtParam = mat.GetParameter(L"RealTime"); - - if(rtParam.GetSource().IsValid() && - rtParam.GetSource().IsA(XSI::siShaderID)) - { - MaterialMap::iterator i = mXsiMaterialMap.find(name); - if (i == mXsiMaterialMap.end()) - { - // Add this one to the list - MaterialEntry* matEntry = new MaterialEntry(); - matEntry->name = name; - matEntry->xsiShader = XSI::Shader(rtParam.GetSource()); - mXsiMaterialMap[name] = matEntry; - } - } - } -} diff --git a/Tools/XSIExport/src/OgreXSISkeletonExporter.cpp b/Tools/XSIExport/src/OgreXSISkeletonExporter.cpp deleted file mode 100644 index 883b2ecb3a0..00000000000 --- a/Tools/XSIExport/src/OgreXSISkeletonExporter.cpp +++ /dev/null @@ -1,547 +0,0 @@ -/* ------------------------------------------------------------------------------ -This source file is part of OGRE -(Object-oriented Graphics Rendering Engine) -For the latest info, see http://www.ogre3d.org/ - -Copyright (c) 2000-2014 Torus Knot Software Ltd - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. ------------------------------------------------------------------------------ -*/ -#include "OgreXSISkeletonExporter.h" -#include "OgreResourceGroupManager.h" -#include "OgreSkeletonManager.h" -#include "OgreSkeleton.h" -#include "OgreBone.h" -#include "OgreAnimation.h" -#include "OgreAnimationTrack.h" -#include "OgreKeyFrame.h" -#include "OgreSkeletonSerializer.h" -#include "OgreQuaternion.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace XSI; - -namespace Ogre -{ - //----------------------------------------------------------------------------- - XsiSkeletonExporter::XsiSkeletonExporter() - { - mXsiSceneRoot = X3DObject(mXsiApp.GetActiveSceneRoot()); - mXSITrackTypeNames["posx"] = XTT_POS_X; - mXSITrackTypeNames["posy"] = XTT_POS_Y; - mXSITrackTypeNames["posz"] = XTT_POS_Z; - mXSITrackTypeNames["rotx"] = XTT_ROT_X; - mXSITrackTypeNames["roty"] = XTT_ROT_Y; - mXSITrackTypeNames["rotz"] = XTT_ROT_Z; - mXSITrackTypeNames["sclx"] = XTT_SCL_X; - mXSITrackTypeNames["scly"] = XTT_SCL_Y; - mXSITrackTypeNames["sclz"] = XTT_SCL_Z; - } - //----------------------------------------------------------------------------- - XsiSkeletonExporter::~XsiSkeletonExporter() - { - } - //----------------------------------------------------------------------------- - const AxisAlignedBox& XsiSkeletonExporter::exportSkeleton(const String& skeletonFileName, - DeformerMap& deformers, float framesPerSecond, AnimationList& animList) - { - LogOgreAndXSI(L"** Begin OGRE Skeleton Export **"); - - copyDeformerMap(deformers); - - SkeletonPtr skeleton = SkeletonManager::getSingleton().create("export", - ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); - // construct the hierarchy - buildBoneHierarchy(skeleton.get(), deformers, animList); - - // progress report - ProgressManager::getSingleton().progress(); - - establishInitialTransforms(deformers); - - // create animations - mAABB.reset(); - createAnimations(skeleton.get(), deformers, framesPerSecond, animList, mAABB); - // progress report - ProgressManager::getSingleton().progress(); - - // Optimise - skeleton->optimiseAllAnimations(); - - SkeletonSerializer ser; - ser.exportSkeleton(skeleton.get(), skeletonFileName); - // progress report - ProgressManager::getSingleton().progress(); - - LogOgreAndXSI(L"** OGRE Skeleton Export Complete **"); - - cleanup(); - - return mAABB; - - } - //----------------------------------------------------------------------------- - void XsiSkeletonExporter::copyDeformerMap(DeformerMap& deformers) - { - // Make lower-case version - // some XSI animations appear to like to use case insensitive references :( - for (DeformerMap::iterator i = deformers.begin(); i != deformers.end(); ++i) - { - DeformerEntry* deformer = i->second; - String name = XSItoOgre(deformer->obj.GetName()); - StringUtil::toLowerCase(name); - mLowerCaseDeformerMap[name] = deformer; - } - } - //----------------------------------------------------------------------------- - void XsiSkeletonExporter::buildBoneHierarchy(Skeleton* pSkeleton, - DeformerMap& deformers, AnimationList& animList) - { - /// Copy all entries from map into a list so iterators won't get invalidated - std::list deformerList; - LogOgreAndXSI(L"-- Bones with vertex assignments:"); - for (DeformerMap::iterator i = deformers.begin(); i != deformers.end(); ++i) - { - DeformerEntry* deformer = i->second; - deformerList.push_back(deformer); - LogOgreAndXSI(deformer->obj.GetName()); - } - - /* XSI allows you to use any object at all as a bone, not just chain elements. - A typical choice is a hierarchy of nulls, for example. In order to - build a skeleton hierarchy which represents the actual one, we need - to find the relationships between all the deformers that we found. - - Well do this by navigating up the scene tree from each bone, looking for - a match in the existing bone list or creating a new one where we need it - to reach the root. We add bones even if they're not assigned vertices - because the animation may depend on them. If the - traversal hits the scene root this bone is clearly a root bone - (there may be more than one). - */ - for (std::list::iterator i = deformerList.begin(); i != deformerList.end(); ++i) - { - DeformerEntry* deformer = *i; - if (deformer->parentName.empty()) - { - linkBoneWithParent(deformer, deformers, deformerList); - } - } - - // Now eliminate all bones without any animated kine parameters - // Need to do this after we've determined all relationships - for (std::list::iterator i = deformerList.begin(); i != deformerList.end(); ++i) - { - DeformerEntry* deformer = *i; - validateAsBone(pSkeleton, deformer, deformers, deformerList, animList); - } - - // Now link - for (DeformerMap::iterator i = deformers.begin(); i != deformers.end(); ++i) - { - DeformerEntry* deformer = i->second; - - // link to parent - if (!deformer->parentName.empty()) - { - DeformerEntry* parent = getDeformer(deformer->parentName, deformers); - assert (parent && "Parent not found"); - assert (deformer->pBone && "Child bone not created"); - assert(parent->pBone && "Parent bone not created"); - parent->pBone->addChild(deformer->pBone); - - } - } - - } - //----------------------------------------------------------------------------- - DeformerEntry* XsiSkeletonExporter::getDeformer(const String& name, - DeformerMap& deformers) - { - // Look in case sensitive list first - DeformerMap::iterator i = deformers.find(name); - if (i == deformers.end()) - { - String lcaseName = name; - StringUtil::toLowerCase(lcaseName); - i = mLowerCaseDeformerMap.find(lcaseName); - if (i == mLowerCaseDeformerMap.end()) - { - return 0; - } - else - { - return i->second; - } - } - else - { - return i->second; - } - - } - //----------------------------------------------------------------------------- - void XsiSkeletonExporter::linkBoneWithParent(DeformerEntry* child, - DeformerMap& deformers, std::list& deformerList) - { - X3DObject parent(child->obj.GetParent()); - String childName = XSItoOgre(child->obj.GetName()); - - if (child->obj == mXsiSceneRoot /* safety check for start node */) - return; - - // Check for parenting by a chain end effector - // These are sneaky little buggers - we actually want to attach the - // child to the end of the final bone in the chain - if (parent.IsA(XSI::siChainEffectorID)) - { - ChainEffector effector(parent); - CRefArray chainBones = effector.GetRoot().GetBones(); - // get the last - parent = chainBones[chainBones.GetCount()-1]; - child->parentIsChainEndEffector = true; - - } - // is the parent the scene root? - if (parent == mXsiSceneRoot) - { - // we hit the root node - } - else - { - - String parentName = XSItoOgre(parent.GetName()); - // Otherwise, check to see if the parent is in the deformer list - DeformerEntry* parentDeformer = getDeformer(parentName, deformers); - if (!parentDeformer) - { - // not found, create entry for parent - parentDeformer = new DeformerEntry(deformers.size(), parent); - deformers[parentName] = parentDeformer; - deformerList.push_back(parentDeformer); - LogOgreAndXSI(CString(L"Added ") + parent.GetName() + - CString(L" as a parent of ") + child->obj.GetName() ); - } - - // Link child entry with parent (not bone yet) - // link child to parent by name - child->parentName = parentName; - parentDeformer->childNames.push_back(childName); - - - - - } - - } - //----------------------------------------------------------------------------- - void XsiSkeletonExporter::validateAsBone(Skeleton* pSkeleton, - DeformerEntry* deformer, - DeformerMap& deformers, std::list& deformerList, - AnimationList& animList) - { - /* The purpose of this method is to find out whether a node in the - bone hierarchy is animated, and if not, to eliminate it and propagate - it's static transform contribution to it's children. - We do this because it's quite easy in XSI to build deep bone chains - with intermediate points that are only used for manipulation. We - don't want to include all of those. - */ - - // TODO - - - // if we weren't static, create bone - if (!deformer->pBone) - { - String name = XSItoOgre(deformer->obj.GetName()); - deformer->pBone = pSkeleton->createBone(name, deformer->boneID); - MATH::CTransformation trans; - - if (deformer->parentName.empty()) - { - // set transform on bone to global transform since no parents - trans = deformer->obj.GetKinematics().GetGlobal().GetTransform(); - } - else - { - // set transform on bone to local transform (since child) - trans = deformer->obj.GetKinematics().GetLocal().GetTransform(); - } - deformer->pBone->setPosition(XSItoOgre(trans.GetTranslation())); - deformer->pBone->setOrientation(XSItoOgre(trans.GetRotation().GetQuaternion())); - deformer->pBone->setScale(XSItoOgre(trans.GetScaling())); - - // special case a bone which is parented by a chain end - if (deformer->parentIsChainEndEffector) - { - ChainEffector effector(deformer->obj.GetParent()); - CRefArray chainBones = effector.GetRoot().GetBones(); - // get the last - X3DObject endBone = chainBones[chainBones.GetCount()-1]; - // offset along X the length of the bone - double boneLen = endBone.GetParameterValue(L"Length"); - deformer->pBone->setPosition( - deformer->pBone->getPosition() + Vector3::UNIT_X * boneLen); - } - - } - - } - //----------------------------------------------------------------------------- - void XsiSkeletonExporter::processActionSource(const XSI::ActionSource& actSource, - DeformerMap& deformers) - { - // Clear existing deformer links - for(DeformerMap::iterator di = deformers.begin(); di != deformers.end(); ++di) - { - for (int tt = XTT_POS_X; tt < XTT_COUNT; ++tt) - { - di->second->xsiTrack[tt].ResetObject(); - } - } - // Get all the items - CRefArray items = actSource.GetItems(); - for (int i = 0; i < items.GetCount(); ++i) - { - XSI::AnimationSourceItem item = items[i]; - - // Check the target - String target = XSItoOgre(item.GetTarget()); - size_t firstDotPos = target.find_first_of("."); - size_t lastDotPos = target.find_last_of("."); - if (firstDotPos != String::npos && lastDotPos != String::npos) - { - String targetName = target.substr(0, firstDotPos); - String paramName = target.substr(lastDotPos+1, - target.size() - lastDotPos - 1); - // locate deformer - DeformerEntry* deformer = getDeformer(targetName, deformers); - if (deformer) - { - // determine parameter - std::map::iterator pi = mXSITrackTypeNames.find(paramName); - if (pi != mXSITrackTypeNames.end()) - { - deformer->xsiTrack[pi->second] = item; - deformer->hasAnyTracks = true; - } - } - } - - } - } - //----------------------------------------------------------------------------- - void XsiSkeletonExporter::createAnimations(Skeleton* pSkel, - DeformerMap& deformers, float fps, AnimationList& animList, AxisAlignedBox& AABBPadding) - { - for (AnimationList::iterator ai = animList.begin(); ai != animList.end(); ++ai) - { - AnimationEntry& animEntry = *ai; - - // Note that we don't know if this time period includes bone animation - // but we sample it anyway just in case; animation optimisation will - // eliminate anything that's redundant - // A little wasteful perhaps, but it's the only guaranteed way to pick - // up all the potentially derived effects on deformers - - float animLength = (float)(animEntry.endFrame - animEntry.startFrame) / fps; - StringStream str; - str << "Creating animation " << animEntry.animationName << - " with length " << animLength << " seconds"; - LogOgreAndXSI(str.str()); - Animation* anim = pSkel->createAnimation(animEntry.animationName, animLength); - - createAnimationTracksSampled(anim, animEntry, deformers, fps, AABBPadding); - - } - } - //----------------------------------------------------------------------------- - void XsiSkeletonExporter::createAnimationTracksSampled(Animation* pAnim, - AnimationEntry& animEntry, DeformerMap& deformers, float fps, AxisAlignedBox& AABBPadding) - { - - // Create all tracks first - std::vector deformerTracks; - deformerTracks.resize(deformers.size()); - for (DeformerMap::iterator di = deformers.begin(); di != deformers.end(); ++di) - { - DeformerEntry* deformer = di->second; - NodeAnimationTrack* track = pAnim->createNodeTrack(deformer->boneID, deformer->pBone); - deformerTracks[deformer->boneID] = track; - } - - // Iterate over frames, keying as we go - long numFrames = animEntry.endFrame - animEntry.startFrame; - if (animEntry.ikSampleInterval == 0) - { - // Don't allow zero samplign frequency - infinite loop! - animEntry.ikSampleInterval = 5.0f; - } - - // Sample all bones from start to before the end frame - for (long frame = animEntry.startFrame; frame < animEntry.endFrame; - frame += animEntry.ikSampleInterval) - { - Real time = (float)(frame - animEntry.startFrame) / fps; - sampleAllBones(deformers, deformerTracks, frame, time, fps, AABBPadding); - - } - // sample final frame (must be guaranteed to be done) - Real time = (float)(animEntry.endFrame - animEntry.startFrame) / fps; - sampleAllBones(deformers, deformerTracks, animEntry.endFrame, time, fps, AABBPadding); - - - } - //----------------------------------------------------------------------------- - void XsiSkeletonExporter::establishInitialTransforms(DeformerMap& deformers) - { - for (DeformerMap::iterator di = deformers.begin(); di != deformers.end(); ++di) - { - DeformerEntry* deformer = di->second; - if (deformer->pBone->getParent() == 0) - { - // Based on global - deformer->initialXform = - deformer->obj.GetKinematics().GetGlobal().GetTransform(); - } - else - { - // Based on local - deformer->initialXform = - deformer->obj.GetKinematics().GetLocal().GetTransform(); - } - - } - } - //----------------------------------------------------------------------------- - void XsiSkeletonExporter::sampleAllBones(DeformerMap& deformers, - std::vector deformerTracks, double frame, - Real time, float fps, AxisAlignedBox& AABBPadding) - { - CValueArray args; - CValue dummy; - args.Resize(2); - // set the playcontrol - args[0] = L"PlayControl.Key"; - args[1] = frame; - mXsiApp.ExecuteCommand(L"SetValue", args, dummy); - args[0] = L"PlayControl.Current"; - mXsiApp.ExecuteCommand(L"SetValue", args, dummy); - - // Refresh - mXsiApp.ExecuteCommand(L"Refresh", CValueArray(), dummy); - // Sample all bones - for (DeformerMap::iterator di = deformers.begin(); di != deformers.end(); ++di) - { - DeformerEntry* deformer = di->second; - NodeAnimationTrack* track = deformerTracks[deformer->boneID]; - - double initposx, initposy, initposz; - deformer->initialXform.GetTranslationValues(initposx, initposy, initposz); - double initrotx, initroty, initrotz; - deformer->initialXform.GetRotation().GetXYZAngles(initrotx, initroty, initrotz); - double initsclx, initscly, initsclz; - deformer->initialXform.GetScalingValues(initsclx, initscly, initsclz); - XSI::MATH::CMatrix4 invTrans = deformer->initialXform.GetMatrix4(); - invTrans.InvertInPlace(); - - XSI::MATH::CTransformation transformation; - if (deformer->pBone->getParent() == 0) - { - // Based on global - transformation = - deformer->obj.GetKinematics().GetGlobal().GetTransform(); - } - else - { - // Based on local - transformation = - deformer->obj.GetKinematics().GetLocal().GetTransform(); - } - - double posx, posy, posz; - transformation.GetTranslationValues(posx, posy, posz); - double sclx, scly, sclz; - transformation.GetScalingValues(sclx, scly, sclz); - - // Make relative to initial - XSI::MATH::CMatrix4 transformationMatrix = transformation.GetMatrix4(); - transformationMatrix.MulInPlace(invTrans); - transformation.SetMatrix4(transformationMatrix); - - // create keyframe - TransformKeyFrame* kf = track->createNodeKeyFrame(time); - // not sure why inverted transform doesn't work for position, but it doesn't - // I thought XSI used same transform order as OGRE - kf->setTranslate(Vector3(posx - initposx, posy - initposy, posz - initposz)); - kf->setRotation(XSItoOgre(transformation.GetRotationQuaternion())); - kf->setScale(Vector3(sclx / initsclx, scly / initscly, sclz / initsclz)); - - // Derive AABB of bone positions, for padding animated mesh AABB - XSI::MATH::CVector3 bonePos = - deformer->obj.GetKinematics().GetGlobal().GetTransform().GetTranslation(); - AABBPadding.merge(XSItoOgre(bonePos)); - - - - } - - } - //----------------------------------------------------------------------------- - void XsiSkeletonExporter::cleanup(void) - { - - mLowerCaseDeformerMap.clear(); - - CValueArray args; - CValue dummy; - args.Resize(1); - - for (int i = 0; i < mIKSampledAnimations.GetCount(); ++i) - { - args[0] = mIKSampledAnimations[i]; - mXsiApp.ExecuteCommand(L"DeleteObj", args, dummy); - } - mIKSampledAnimations.Clear(); - - } -} diff --git a/Tools/dotXSIConverter/include/Exporter.h b/Tools/dotXSIConverter/include/Exporter.h deleted file mode 100644 index c03db041f12..00000000000 --- a/Tools/dotXSIConverter/include/Exporter.h +++ /dev/null @@ -1,75 +0,0 @@ -#ifndef __EXPORTER_H__ -#define __EXPORTER_H__ - - -#include "stdafx.h" -#include "SemanticLayer.h" -#include "OgrePrerequisites.h" -#include "OgreVector.h" -#include "OgreColourValue.h" -#include "OgreMesh.h" - -using namespace Ogre; - - -/* Class for performing a mesh and skeleton export from dotXSI */ - -class Exporter { - public: - /* Constructor to initialize .XSI scene data */ - Exporter(CSLModel* Root); - virtual ~Exporter(); - /* Function to perform an export to Ogre .mesh. */ - void exportMesh(std::string fileName, std::string skelName); - /* Function to perform an export to Ogre .skeleton. */ - void exportBones(std::string fileName); - - protected: - /* Internal recursive method for exporting a node in the scene */ - void exportCSLModel(Ogre::Mesh* pMesh, CSLModel* XSIModel); - /* Export a submesh from the attached information */ - void exportSubMesh(Ogre::Mesh* pMesh, CSLMesh* XSIMesh); - /* Recursive routine to traverse bone hierarchy tree */ - void recurseBones(Skeleton* pSkel, CSLModel* XSIModel); - /* Exports animation tracks */ - void exportAnim(Skeleton* pSkel, CSLModel* XSIModel); - - /* XSI Scene */ - CSLModel* SceneRoot; - int boneCount; - std::string boneArray[OGRE_MAX_NUM_BONES]; - bool root; - - /* This class represents a unique vertex, identified from a unique combination of components. */ - - class UniqueVertex { - public: - bool initialized; - Ogre::Vector3 position; - Ogre::Vector3 normal; - Ogre::Vector2 uv[OGRE_MAX_TEXTURE_COORD_SETS]; - Ogre::RGBA color; - /* The index of the next component with the same base details, but some variation. */ - size_t nextIndex; - UniqueVertex(); - bool operator==(const UniqueVertex& rhs) const; - }; - - typedef std::vector UniqueVertexList; - // Unique vertex list - UniqueVertexList mUniqueVertices; - // Dynamic index list - typedef std::vector IndexList; - IndexList mIndices; - - /* Function to start processing a polygon mesh. */ - void startPolygonMesh(size_t origPositionCount, size_t indexCount); - /* Try to look up an existing vertex with the same information, or create new one. */ - size_t createOrRetrieveUniqueVertex(size_t originalPositionIndex, const UniqueVertex& vertex); - /* Templatized method for writing indexes */ - template void writeIndexes(T* buf); - /* Create and fill a vertex buffer */ - void createVertexBuffer(VertexData* vd, unsigned short bufIdx); -}; - -#endif diff --git a/Tools/dotXSIConverter/src/Exporter.cpp b/Tools/dotXSIConverter/src/Exporter.cpp deleted file mode 100644 index b18c2d308d3..00000000000 --- a/Tools/dotXSIConverter/src/Exporter.cpp +++ /dev/null @@ -1,597 +0,0 @@ -#include "Exporter.h" -#include -#include -#include "stdafx.h" -#include "SemanticLayer.h" -#include "OgreException.h" -#include "OgreLogManager.h" -#include "OgreMeshManager.h" -#include "OgreSkeletonManager.h" -#include "OgreAnimation.h" -#include "OgreAnimationTrack.h" -#include "OgreKeyFrame.h" -#include "OgreMesh.h" -#include "OgreSubMesh.h" -#include "OgreSkeleton.h" -#include "OgreBone.h" -#include "OgreDefaultHardwareBufferManager.h" -#include "OgreMeshSerializer.h" -#include "OgreSkeletonSerializer.h" -#include "OgrePrerequisites.h" -#include "OgreColourValue.h" - -using namespace Ogre; - -//----------------------- GLOBALS FOR SINGLETONS ------------- -LogManager* logMgr; -ResourceGroupManager* rgm; -MeshManager* meshMgr; -DefaultHardwareBufferManager* hardwareBufMgr; -SkeletonManager* skelMgr; - -//------------------------------------------------------------ -Exporter::UniqueVertex::UniqueVertex() - : initialized(false), position(Ogre::Vector3::ZERO), normal(Ogre::Vector3::ZERO), color(0), - nextIndex(0) -{ - for (int i = 0; i < OGRE_MAX_TEXTURE_COORD_SETS; ++i) - uv[i] = Ogre::Vector2::ZERO; -} - -//------------------------------------------------------------ -bool Exporter::UniqueVertex::operator ==(const UniqueVertex& rhs) const -{ - bool ret = position == rhs.position && - normal == rhs.normal && - color == rhs.color; - if (!ret) return ret; - for (int i = 0; i < OGRE_MAX_TEXTURE_COORD_SETS && ret; ++i) - { - ret = ret && (uv[i] == rhs.uv[i]); - } - return ret; -} - -//------------------------------------------------------------ -Exporter::Exporter(CSLModel * Root) -{ - // Initialize Exporter object instance variables - this->SceneRoot = Root; - boneCount = 0; -} - -//------------------------------------------------------------ -Exporter::~Exporter() -{ -} - -//------------------------------------------------------------ -void Exporter::exportMesh(std::string fileName, std::string skelName) -{ - // Construct mesh - MeshPtr pMesh = MeshManager::getSingleton().createManual(fileName, ResourceGroupManager:: - DEFAULT_RESOURCE_GROUP_NAME); - pMesh->setSkeletonName(skelName); - - // We'll assume we want to export the entire scene - exportCSLModel(pMesh.get(), SceneRoot); - MeshSerializer serializer; - serializer.exportMesh(pMesh.get(), fileName); -} - -//-------------------------------------------------------------------------- -void Exporter::exportCSLModel(Mesh* pMesh, CSLModel* XSIModel) -{ - if (XSIModel->GetPrimitiveType() == CSLTemplate::SI_MESH) - exportSubMesh(pMesh, (CSLMesh *) XSIModel->Primitive()); - - CSLModel* *l_childrenList = XSIModel->GetChildrenList(); - - // Loop through all children - for (int i = 0; i < XSIModel->GetChildrenCount(); i++ ) - { - exportCSLModel (pMesh, l_childrenList[i]); - } -} - -//------------------------------------------------------------------------- -void Exporter::exportSubMesh(Mesh *pMesh, CSLMesh* XSIMesh) -{ - SubMesh* sm = 0; - sm = pMesh->createSubMesh(XSIMesh->GetName()); - - // HACK: No materials exporter yet, I hard coded this, wrong as hell, but did it anyway - // For now, I'm just creating the materials file manually. - sm->setMaterialName("Examples/Woman"); - CSLTriangleList** triangles = XSIMesh->TriangleLists(); - - // Assume only one triangle list for now - CSLTriangleList* triArray = triangles[0]; - std::cout << "Number of triangles: " << triArray->GetTriangleCount() << "\n"; - CSIBCVector3D* srcPosArray = XSIMesh->Shape()->GetVertexListPtr(); - std::cout << "Number of vertices: " << XSIMesh->Shape()->GetVertexCount() << "\n"; - CSIBCVector3D* srcNormArray = XSIMesh->Shape()->GetNormalListPtr(); - std::cout << "Number of normals: " << XSIMesh->Shape()->GetNormalCount() << "\n"; - CSLShape_35 * uv = ((CSLShape_35 *) XSIMesh->Shape()); - size_t numUVs = uv->UVCoordArrays()[0]->GetUVCoordCount(); - std::cout << "Number of UVs: " << numUVs << "\n"; - - // For now, assume only one set of UV's - CSIBCVector2D* uvValueArray = ((CSLShape_35 *) XSIMesh->Shape())->UVCoordArrays()[0]->GetUVCoordListPtr(); - - // Check for colors - bool hasVertexColors = false; - if (XSIMesh->Shape()->GetColorCount() > 0) - hasVertexColors = true; - - // Never use shared geometry - sm->useSharedVertices = false; - sm->vertexData = new VertexData(); - - // Always do triangle list - sm->indexData->indexCount = static_cast(triArray->GetTriangleCount() * 3); - - // Identify the unique vertices, write to a temp index buffer - startPolygonMesh(XSIMesh->Shape()->GetVertexCount(), triArray->GetTriangleCount() * 3); - - // Iterate through all the triangles - // There will often be less positions than normals and UV's - for (long t = 0; t < triArray->GetTriangleCount(); ++t) - { - for (int p = 0; p < 3; ++p) - { - UniqueVertex vertex; - CSIBCVector3D pos = srcPosArray[triArray->GetVertexIndicesPtr()[t*3+p]]; - CSIBCVector3D norm = srcNormArray[triArray->GetNormalIndicesPtr()[t*3+p]]; - CSIBCVector2D uv = uvValueArray[triArray->GetUVIndicesPtr(0)[t*3+p]]; - vertex.position = Vector3(pos.GetX(), pos.GetY(), pos.GetZ()); - vertex.normal = Vector3(norm.GetX(), norm.GetY(), norm.GetZ()); - - // We are assuming 1 UV -- in our files, number of UV's = number of Normals - vertex.uv[0] = Vector2(uv.GetX(), (1 - uv.GetY())); - - if (hasVertexColors) - vertex.color = triArray->GetColorIndicesPtr()[t*3+p]; - size_t index = createOrRetrieveUniqueVertex(triArray->GetVertexIndicesPtr()[t*3+p], vertex); - mIndices.push_back(index); - } - } - delete [] uvValueArray; - - // Now bake final geometry - sm->vertexData->vertexCount = mUniqueVertices.size(); - - // Determine index size - bool use32BitIndexes = false; - if (mUniqueVertices.size() > 65536) - use32BitIndexes = true; - sm->indexData->indexBuffer = - HardwareBufferManager::getSingleton().createIndexBuffer( - use32BitIndexes ? HardwareIndexBuffer::IT_32BIT : HardwareIndexBuffer::IT_16BIT, - triArray->GetTriangleCount() * 3, HardwareBuffer::HBU_STATIC_WRITE_ONLY); - if (use32BitIndexes) - { - uint32* pIdx = static_cast( - sm->indexData->indexBuffer->lock(HardwareBuffer::HBL_DISCARD)); - writeIndexes(pIdx); - sm->indexData->indexBuffer->unlock(); - } - else - { - uint16* pIdx = static_cast( - sm->indexData->indexBuffer->lock(HardwareBuffer::HBL_DISCARD)); - writeIndexes(pIdx); - sm->indexData->indexBuffer->unlock(); - } - - // Define vertex declaration - unsigned buf = 0; - size_t offset = 0; - sm->vertexData->vertexDeclaration->addElement(buf, offset, VET_FLOAT3, VES_POSITION); - offset += VertexElement::getTypeSize(VET_FLOAT3); - sm->vertexData->vertexDeclaration->addElement(buf, offset, VET_FLOAT3, VES_NORMAL); - offset += VertexElement::getTypeSize(VET_FLOAT3); - // TODO: Split Vertex Data if animated - - if (hasVertexColors) - { - sm->vertexData->vertexDeclaration->addElement(buf, offset, VET_COLOUR, VES_DIFFUSE); - offset += VertexElement::getTypeSize(VET_COLOUR); - } - - // Again, assume only 1 uv - sm->vertexData->vertexDeclaration->addElement(buf, offset, VET_FLOAT2, VES_TEXTURE_COORDINATES); - offset += VertexElement::getTypeSize(VET_FLOAT2); - - // Create and fill buffer(s) - for (unsigned short b = 0; b <= sm->vertexData->vertexDeclaration->getMaxSource(); ++b) - { - createVertexBuffer(sm->vertexData, b); - } - - // Bounds definitions - Real squaredRadius = 0.0f; - Vector3 min, max; - bool first = true; - for (long i = 0; i < XSIMesh->Shape()->GetVertexCount(); ++i) - { - Vector3 position = Vector3(srcPosArray[i].GetX(), srcPosArray[i].GetY(), srcPosArray[i].GetZ()); - if (first) - { - squaredRadius = position.squaredLength(); - min = max = position; - first = false; - } - else - { - squaredRadius = std::max(squaredRadius, position.squaredLength()); - min.makeFloor(position); - max.makeCeil(position); - } - } - AxisAlignedBox box; - box.setExtents(min, max); - box.merge(pMesh->getBounds()); - pMesh->_setBounds(box); - pMesh->_setBoundingSphereRadius(std::max(pMesh->getBoundingSphereRadius(), - Math::Sqrt(squaredRadius))); - - // Get Envelope list for this submesh - CSLEnvelope** envelopes = XSIMesh->ParentModel()->GetEnvelopeList(); - CSLEnvelope* env = 0; - int boneIdx; - bool done; - int index; - VertexBoneAssignment vertAssign; - for (int e = 0; e < XSIMesh->ParentModel()->GetEnvelopeCount(); ++e) - { - env = envelopes[e]; - for (int g = 0; g < boneCount; ++g) - { - if (boneArray[g] == env->GetDeformer()->GetName()) - boneIdx = g; - else - continue; - break; - } - - SLVertexWeight* wtList = env->GetVertexWeightListPtr(); - - // Go through all collocated vertices, assigning the same weights to each. - // All the dotXSI files I've seen normalize the weights to 100, so for now - // I'm just dividing by 100. TODO: Insert code to handle normalization - // just in case. - for (int h = 0; h < env->GetVertexWeightCount(); ++h) - { - vertAssign.boneIndex = boneIdx; - vertAssign.vertexIndex = index = (int) wtList[h].m_fVertexIndex; - vertAssign.weight = (Real) (wtList[h].m_fWeight / 100); - done = false; - while (!done) - { - sm->addBoneAssignment(vertAssign); - if (mUniqueVertices[index].nextIndex) - vertAssign.vertexIndex = index = mUniqueVertices[index].nextIndex; - else - done = true; - } - } - } - - // Last step here is to reorganise the vertex buffers - VertexDeclaration* newDecl = - sm->vertexData->vertexDeclaration->getAutoOrganisedDeclaration(true); - BufferUsageList bufferUsages; - for (size_t u = 0; u <= newDecl->getMaxSource(); ++u) - bufferUsages.push_back(HardwareBuffer::HBU_STATIC_WRITE_ONLY); - sm->vertexData->reorganiseBuffers(newDecl, bufferUsages); -} - -//----------------------------------------------------------------------------- -template -void Exporter::writeIndexes(T* buf) -{ - IndexList::const_iterator i, iend; - iend = mIndices.end(); - for (i = mIndices.begin(); i != iend; ++i) - { - *buf++ = static_cast(*i); - } -} - -//----------------------------------------------------------------------------- -void Exporter::createVertexBuffer(VertexData* vd, unsigned short bufIdx) -{ - HardwareVertexBufferSharedPtr vbuf = HardwareBufferManager::getSingleton().createVertexBuffer( - vd->vertexDeclaration->getVertexSize(bufIdx), - vd->vertexCount, - HardwareBuffer::HBU_STATIC_WRITE_ONLY); - vd->vertexBufferBinding->setBinding(bufIdx, vbuf); - size_t vertexSize = vd->vertexDeclaration->getVertexSize(bufIdx); - - char* pBase = static_cast(vbuf->lock(HardwareBuffer::HBL_DISCARD)); - - VertexDeclaration::VertexElementList elems = vd->vertexDeclaration->findElementsBySource(bufIdx); - VertexDeclaration::VertexElementList::iterator ei, eiend; - eiend = elems.end(); - float* pFloat; - RGBA* pRGBA; - - Exporter::UniqueVertexList::iterator srci = mUniqueVertices.begin(); - - for (size_t v = 0; v < vd->vertexCount; ++v, ++srci) - { - for (ei = elems.begin(); ei != eiend; ++ei) - { - VertexElement& elem = *ei; - switch(elem.getSemantic()) - { - case VES_POSITION: - elem.baseVertexPointerToElement(pBase, &pFloat); - *pFloat++ = srci->position.x; - *pFloat++ = srci->position.y; - *pFloat++ = srci->position.z; - break; - case VES_NORMAL: - elem.baseVertexPointerToElement(pBase, &pFloat); - *pFloat++ = srci->normal.x; - *pFloat++ = srci->normal.y; - *pFloat++ = srci->normal.z; - break; - case VES_DIFFUSE: - elem.baseVertexPointerToElement(pBase, &pRGBA); - *pRGBA = srci->color; - break; - case VES_TEXTURE_COORDINATES: - elem.baseVertexPointerToElement(pBase, &pFloat); - *pFloat++ = srci->uv[elem.getIndex()].x; - *pFloat++ = srci->uv[elem.getIndex()].y; - break; - } - } - pBase += vertexSize; - } - vbuf->unlock(); -} - -//---------------------------------------------------------------------- -void Exporter::startPolygonMesh(size_t count, size_t indexCount) -{ - mUniqueVertices.clear(); - mUniqueVertices.resize(count); - mIndices.clear(); - mIndices.reserve(indexCount); // intentionally reserved, not resized -} - -//---------------------------------------------------------------------- -size_t Exporter::createOrRetrieveUniqueVertex(size_t originalPositionIndex, const UniqueVertex& vertex) -{ - UniqueVertex& orig = mUniqueVertices[originalPositionIndex]; - - if (!orig.initialized) - { - orig = vertex; - orig.initialized = true; - return originalPositionIndex; - } - else if (orig == vertex) - { - return originalPositionIndex; - } - else - { - // no match, go to next or create new - if (orig.nextIndex) - { - // cascade - return createOrRetrieveUniqueVertex(orig.nextIndex, vertex); - } - else - { - // get new index - size_t newindex = mUniqueVertices.size(); - orig.nextIndex = newindex; - // create new (NB invalidates 'orig' reference) - mUniqueVertices.push_back(vertex); - // set initialised - mUniqueVertices[newindex].initialized = true; - - return newindex; - } - } -} - -//------------------------------------------------------------------------------ -void Exporter::exportBones(std::string fileName) -{ - // Construct skeleton - SkeletonPtr pSkel = SkeletonManager::getSingleton().create( fileName, ResourceGroupManager:: - DEFAULT_RESOURCE_GROUP_NAME, true); - - // Recursively traverse the bone tree - root = false; - recurseBones(pSkel.get(), SceneRoot); - - // Export animations - exportAnim(pSkel.get(), SceneRoot); - - // Call serializer to write .skeleton file - SkeletonSerializer serializer; - serializer.exportSkeleton(pSkel.get(), fileName); -} - -//----------------------------------------------------------------- -void Exporter::recurseBones(Skeleton* pSkel, CSLModel* XSIModel) -{ - CSIBCVector3D vec3d; - - // A plethora of logical expressions to ensure that the root null and - // its children are the only ones that will enter this if block. Eliminates - // any extraneous nulls not related to the skeleton. - - if ((XSIModel->GetPrimitiveType() == CSLTemplate::SI_NULL_OBJECT) && - ((XSIModel->ParentModel()->GetPrimitiveType() == CSLTemplate::SI_NULL_OBJECT) || (!root))) - { - boneArray[boneCount] = XSIModel->GetName(); - Bone* ogreBone = pSkel->createBone(XSIModel->GetName(), boneCount); - root = true; - vec3d = XSIModel->Transform()->GetScale(); - ogreBone->setScale(vec3d.GetX(), vec3d.GetY(), vec3d.GetZ()); - vec3d = XSIModel->Transform()->GetTranslation(); - Vector3 bonePos(vec3d.GetX(), vec3d.GetY(), vec3d.GetZ()); - ogreBone->setPosition(bonePos); - - // Yes, we are converting Euler angles to quaternions, at risk of gimbal lock. - // This is because XSI doesn't export quaternions, except through the animation - // mixer and action FCurves. It's possible to get a 3x3 Rotation matrix, which - // might be a better choice for conversion to quaternion. - vec3d = XSIModel->Transform()->GetEulerRotation(); - Ogre::Quaternion qx, qy, qz, qfinal; - qx.FromAngleAxis(Ogre::Degree(vec3d.GetX()), Ogre::Vector3::UNIT_X); - qy.FromAngleAxis(Ogre::Degree(vec3d.GetY()), Ogre::Vector3::UNIT_Y); - qz.FromAngleAxis(Ogre::Degree(vec3d.GetZ()), Ogre::Vector3::UNIT_Z); - - // Assume rotate by x then y then z - qfinal = qz * qy * qx; - ogreBone->setOrientation(qfinal); - ++boneCount; - - if ((boneCount > 1) && (XSIModel->ParentModel()->GetPrimitiveType() == CSLTemplate::SI_NULL_OBJECT)) - { - pSkel->getBone(XSIModel->ParentModel()->GetName())->addChild(ogreBone); - } - } - - CSLModel* *l_childrenList = XSIModel->GetChildrenList(); - - // Loop through all children - for (int i = 0; i < XSIModel->GetChildrenCount(); i++ ) - { - recurseBones (pSkel, l_childrenList[i]); - } -} - -//------------------------------------------------------------------------------ - -void Exporter::exportAnim(Skeleton* pSkel, CSLModel* XSIModel) -{ - CSLTransform* initial; - CSLTransform* keyfr = 0; - CSIBCMatrix4x4 initmat, invinitmat, keyfmat, newmat; - - // Timing conversions from XSI frames to OGRE time in seconds - float frameRate = XSIModel->Scene()->SceneInfo()->GetFrameRate(); - float lengthInFrames = XSIModel->Scene()->SceneInfo()->GetEnd() - - XSIModel->Scene()->SceneInfo()->GetStart(); - float realTime = lengthInFrames / frameRate; - - // HACK: You'd want to assign the correct name to your particular animation. - Animation *ogreanim = - pSkel->createAnimation("Jump", realTime ); - int i, numKeys; - - // Go to each bone and create the animation tracks - for (i = 0; i < boneCount; ++i) - { - Bone* ogrebone = pSkel->getBone(boneArray[i]); - CSLModel* XSIbone = XSIModel->Scene()->FindModelRecursively((char *) boneArray[i].c_str(), XSIModel); - if ((i == 0) || (XSIbone->ParentModel()->GetPrimitiveType() == CSLTemplate::SI_NULL_OBJECT)) - { - // Create animation tracks for a bone - AnimationTrack *ogretrack = ogreanim->createTrack(i, ogrebone); - numKeys = XSIbone->Transform()->FCurves()[0]->GetKeyCount(); - CSLLinearKey* scalx = XSIbone->Transform()->GetSpecificFCurve(CSLTemplate::SI_SCALING_X)->GetLinearKeyListPtr(); - CSLLinearKey* scaly = XSIbone->Transform()->GetSpecificFCurve(CSLTemplate::SI_SCALING_Y)->GetLinearKeyListPtr(); - CSLLinearKey* scalz = XSIbone->Transform()->GetSpecificFCurve(CSLTemplate::SI_SCALING_Z)->GetLinearKeyListPtr(); - CSLLinearKey* rotx = XSIbone->Transform()->GetSpecificFCurve(CSLTemplate::SI_ROTATION_X)->GetLinearKeyListPtr(); - CSLLinearKey* roty = XSIbone->Transform()->GetSpecificFCurve(CSLTemplate::SI_ROTATION_Y)->GetLinearKeyListPtr(); - CSLLinearKey* rotz = XSIbone->Transform()->GetSpecificFCurve(CSLTemplate::SI_ROTATION_Z)->GetLinearKeyListPtr(); - CSLLinearKey* tranx = XSIbone->Transform()->GetSpecificFCurve(CSLTemplate::SI_TRANSLATION_X)->GetLinearKeyListPtr(); - CSLLinearKey* trany = XSIbone->Transform()->GetSpecificFCurve(CSLTemplate::SI_TRANSLATION_Y)->GetLinearKeyListPtr(); - CSLLinearKey* tranz = XSIbone->Transform()->GetSpecificFCurve(CSLTemplate::SI_TRANSLATION_Z)->GetLinearKeyListPtr(); - - // Set up the bind pose matrix and take inverse - initial = XSIbone->Transform(); - initial->ComputeLocalMatrix(); - initmat = initial->GetMatrix(); - initmat.GetInverse(invinitmat); - - for (int currKeyIdx = 0; currKeyIdx < numKeys; ++currKeyIdx) - { - // Create keyframe - // Adjust for start time, and for the fact that frames are numbered from 1 - float frameTime = scalx[currKeyIdx].m_fTime - XSIModel->Scene()->SceneInfo()->GetStart(); - realTime = frameTime / frameRate; - KeyFrame *ogrekey = ogretrack->createKeyFrame(realTime); - keyfr = XSIbone->Transform(); - keyfr->SetScale(CSIBCVector3D(scalx[currKeyIdx].m_fValue, scaly[currKeyIdx].m_fValue, scalz[currKeyIdx].m_fValue)); - keyfr->SetEulerRotation(CSIBCVector3D(rotx[currKeyIdx].m_fValue, roty[currKeyIdx].m_fValue, rotz[currKeyIdx].m_fValue)); - keyfr->SetTranslation(CSIBCVector3D(tranx[currKeyIdx].m_fValue, trany[currKeyIdx].m_fValue, tranz[currKeyIdx].m_fValue)); - keyfr->ComputeLocalMatrix(); - keyfmat = keyfr->GetMatrix(); - - // Inverse bind pose matrix * keyframe transformation matrix - invinitmat.Multiply(keyfmat, newmat); - CSIBCVector3D kfSca, kfRot, kfPos; - newmat.GetTransforms(kfSca, kfRot, kfPos); - Vector3 kSca(kfSca.GetX(), kfSca.GetY(), kfSca.GetZ()); - Vector3 kPos(kfPos.GetX(), kfPos.GetY(), kfPos.GetZ()); - Quaternion qx, qy, qz, kfQ; - ogrekey->setScale(kSca); - ogrekey->setTranslate(kPos); - qx.FromAngleAxis(Ogre::Radian(kfRot.GetX()), Vector3::UNIT_X); - qy.FromAngleAxis(Ogre::Radian(kfRot.GetY()), Vector3::UNIT_Y); - qz.FromAngleAxis(Ogre::Radian(kfRot.GetZ()), Vector3::UNIT_Z); - kfQ = qz * qy * qx; - ogrekey->setRotation(kfQ); - } - } - } -} - -//------------------------------------------------------------------------------ -int main(int argc, char *argv[]) -{ - // Validate command line arguments - if (argc != 3) { - std::cout << "XSI Ogre Exporter should be invoked in the format: \n"; - std::cout << "exporter \n"; - std::cout << "Ex: exporter example.xsi example\n"; - return (0); - } - - // Ogre Singletons - logMgr = new LogManager(); - logMgr->createLog("XSIOgreExport"); - rgm = new ResourceGroupManager(); - meshMgr = new MeshManager(); - hardwareBufMgr = new DefaultHardwareBufferManager(); - skelMgr = new SkeletonManager(); - - // Initialize dotXSI Scene - CSLScene Scene; - std::string fn(argv[2]); - std::string meshFileName = fn + ".mesh"; - std::string skelFileName = fn + ".skeleton"; - - // Continue if valid dotXSI file, end gracefully if not - if (Scene.Open(argv[1]) == SI_SUCCESS) - { - Scene.Read(); - Exporter * e = new Exporter(Scene.Root()); - e->exportBones(skelFileName); - e->exportMesh(meshFileName, skelFileName); - delete e; - Scene.Close(); - } - else - std::cout << "Error opening file " << argv[1] << ". Please check for validity.\n"; - - // Get rid of Ogre Singletons - delete skelMgr; - delete meshMgr; - delete hardwareBufMgr; - delete rgm; - delete logMgr; - return (0); -} diff --git a/_clang-format b/_clang-format deleted file mode 100644 index 8f933d47ecf..00000000000 --- a/_clang-format +++ /dev/null @@ -1,2 +0,0 @@ -{UseTab: Never, ColumnLimit: 120, IndentWidth: 4, AccessModifierOffset: -4, PointerAlignment: Left, - Standard: Cpp11, Cpp11BracedListStyle: true, BasedOnStyle: LLVM, BreakBeforeBraces: Allman} diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index 6b5d75a5bf2..00000000000 --- a/appveyor.yml +++ /dev/null @@ -1,40 +0,0 @@ -platform: x64 -configuration: Release -environment: - CS_APIKEY: - secure: XiSyqXBlbnIqawfinZqXimatuEdpYsI38+HK2TgvuUGHQEoeFHA62700/EhFJ4M1 -image: - - Visual Studio 2019 -install: - - cmd: SET PATH=C:\Python310-x64;C:\Python310-x64\Scripts;%PATH% - - cmd: pip install swig==4.1.1 - - cmd: curl -sSf -o rustup-init.exe https://win.rustup.rs/ - - cmd: rustup-init.exe -y - - cmd: curl -LO https://sdk.lunarg.com/sdk/download/1.2.189.2/windows/VulkanSDK-1.2.189.2-Installer.exe - - cmd: VulkanSDK-1.2.189.2-Installer.exe --accept-licenses --default-answer --confirm-command install - - cmd: cd %APPVEYOR_BUILD_FOLDER% - - cmd: git submodule update --init --recursive -build_script: - - set PATH=C:\Qt\6.2\msvc2019_64\bin;C:\Users\appveyor\.cargo\bin;%PATH% - - set VULKAN_SDK=C:\VulkanSDK\1.2.189.2 - - cmake -P ci-build.cmake - - cmake --build build --config RelWithDebInfo --target INSTALL -test_script: - - set PATH=%PATH%;build\gtest\lib - - build\bin\RelWithDebInfo\Test_Ogre.exe --gtest_filter=-MeshWithoutIndexDataTests* -cache: -- ogredeps -> CMake/Dependencies.cmake -branches: - only: - - master - - stable - - /v\d+\.\d+\.\d+/ -after_build: - - IF NOT "%APPVEYOR_REPO_TAG%" == "true" set APPVEYOR_REPO_TAG_NAME=master - - 7z a ogre-sdk-%APPVEYOR_REPO_TAG_NAME%-msvc142-x64.zip ./build/sdk/* - - SET PATH=C:\Python310-x64;C:\Python310-x64\Scripts;%PATH% - - pip install --upgrade cloudsmith-cli - - IF "%APPVEYOR_PULL_REQUEST_NUMBER%" == "" cloudsmith push raw ogrecave/ogre ogre-sdk-%APPVEYOR_REPO_TAG_NAME%-msvc142-x64.zip --republish --version %APPVEYOR_REPO_TAG_NAME% -k %CS_APIKEY% -artifacts: - - path: ogre-sdk-master-msvc142-x64.zip - name: ogre-sdk-master-msvc142-x64 diff --git a/ci-build.cmake b/ci-build.cmake deleted file mode 100644 index 693e2328c6f..00000000000 --- a/ci-build.cmake +++ /dev/null @@ -1,118 +0,0 @@ -set(GENERATOR) -set(OTHER -DCMAKE_CXX_FLAGS=-Werror -DCMAKE_SHARED_LINKER_FLAGS=-Wl,--no-undefined -DOGRE_CONFIG_ENABLE_PVRTC=ON) -set(CROSS) - -set(CMAKE_BUILD_TYPE Debug) -set(BUILD_DEPS FALSE) -set(SWIG_EXECUTABLE /usr/bin/swig4.0) - -set(RENDERSYSTEMS - -DOGRE_BUILD_PLUGIN_GLSLANG=TRUE # only builds on Linux, this is the Linux specific config - -DOGRE_BUILD_PLUGIN_RSIMAGE=TRUE - -DOGRE_BUILD_RENDERSYSTEM_VULKAN=TRUE - -DOGRE_BUILD_RENDERSYSTEM_GL=TRUE - -DOGRE_BUILD_RENDERSYSTEM_GL3PLUS=TRUE - -DOGRE_BUILD_RENDERSYSTEM_GLES2=TRUE - -DOGRE_BUILD_RENDERSYSTEM_TINY=TRUE) - -if(DEFINED ENV{IOS}) - set(GENERATOR -G Xcode) - set(RENDERSYSTEMS - -DOGRE_BUILD_RENDERSYSTEM_METAL=TRUE - -DOGRE_BUILD_RENDERSYSTEM_GLES2=TRUE) - set(CROSS - -DIOS_PLATFORM=SIMULATOR - -DCMAKE_TOOLCHAIN_FILE=${CMAKE_CURRENT_SOURCE_DIR}/CMake/toolchain/ios.toolchain.xcode.cmake) - - set(OTHER - -DOGRE_DEPENDENCIES_DIR=${CMAKE_CURRENT_SOURCE_DIR}/ogredeps - ${CROSS}) - set(BUILD_DEPS TRUE) -elseif("$ENV{TRAVIS_OS_NAME}" STREQUAL "osx") - set(GENERATOR -G Xcode) - set(RENDERSYSTEMS - -DOGRE_BUILD_RENDERSYSTEM_METAL=TRUE - -DOGRE_BUILD_RENDERSYSTEM_GL=FALSE - -DOGRE_BUILD_RENDERSYSTEM_GL3PLUS=TRUE) - - set(OTHER - -DOGRE_DEPENDENCIES_DIR=${CMAKE_CURRENT_SOURCE_DIR}/ogredeps - ${CROSS}) -endif() - -if(DEFINED ENV{APPVEYOR}) - set(CMAKE_BUILD_TYPE Release) - set(RENDERSYSTEMS - -DOGRE_BUILD_RENDERSYSTEM_D3D9=TRUE - -DOGRE_BUILD_RENDERSYSTEM_TINY=TRUE - -DOGRE_BUILD_RENDERSYSTEM_VULKAN=TRUE - -DOGRE_BUILD_PLUGIN_RSIMAGE=TRUE - -DOGRE_BUILD_RENDERSYSTEM_GL=TRUE - -DOGRE_BUILD_RENDERSYSTEM_GLES2=TRUE - -DOGRE_BUILD_RENDERSYSTEM_GL3PLUS=TRUE) - - set(OTHER - "-DCMAKE_CXX_FLAGS=-WX -EHsc" - -DCMAKE_GENERATOR_PLATFORM=x64 - -DCMAKE_GENERATOR_TOOLSET=v142 - -DOGRE_BUILD_DEPENDENCIES=TRUE - "-DPYTHON_EXECUTABLE=C:\\Python310-x64\\python.exe" - "-DPYTHON_LIBRARY=C:\\Python310-x64\\libs\\python310.lib" - -DOGRE_DEPENDENCIES_DIR=${CMAKE_CURRENT_SOURCE_DIR}/ogredeps) - - set(GENERATOR -G "Visual Studio 16 2019") - set(OTHER ${OTHER} - -DCMAKE_PREFIX_PATH="C:\\Qt\\6.2\\msvc2019_64" - -DQt6_DIR="C:\\Qt\\6.2\\msvc2019_64\\lib\\cmake\\Qt6") - - set(BUILD_DEPS TRUE) - set(SWIG_EXECUTABLE "C:\\Python310-x64\\Scripts\\swig.exe") -endif() - -if(DEFINED ENV{ANDROID}) - set(CMAKE_BUILD_TYPE RelWithDebInfo) - set(CROSS - -DANDROID_PLATFORM=android-19 - -DANDROID_NDK=${CMAKE_CURRENT_SOURCE_DIR}/android-ndk-r25c - -DCMAKE_TOOLCHAIN_FILE=${CMAKE_CURRENT_SOURCE_DIR}/android-ndk-r25c/build/cmake/android.toolchain.cmake - -DANDROID_ARM_NEON=TRUE - -DANDROID_ABI=arm64-v8a) - - set(RENDERSYSTEMS - -DOGRE_BUILD_RENDERSYSTEM_VULKAN=TRUE - -DOGRE_BUILD_RENDERSYSTEM_GLES2=TRUE) - - set(OTHER - ${CROSS} - -DCMAKE_CXX_FLAGS="-Werror" - -DOGRE_BUILD_ANDROID_JNI_SAMPLE=TRUE - -DOGRE_DEPENDENCIES_DIR=${CMAKE_CURRENT_SOURCE_DIR}/ogredeps) - set(BUILD_DEPS TRUE) - - if(NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/android-ndk-r25c) - message(STATUS "Downloading Android NDK") - file(DOWNLOAD - https://dl.google.com/android/repository/android-ndk-r25c-linux.zip - ./android-ndk-r25c-linux.zip) - message(STATUS "Extracting Android NDK") - execute_process(COMMAND unzip android-ndk-r25c-linux.zip OUTPUT_QUIET) - message(STATUS "Building Shaderc") - execute_process(COMMAND - ../../../ndk-build -j2 NDK_PROJECT_PATH=. APP_BUILD_SCRIPT=Android.mk APP_STL=c++_static APP_ABI=arm64-v8a libshaderc_combined - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/android-ndk-r25c/sources/third_party/shaderc/) - endif() -endif() - -file(MAKE_DIRECTORY build) -execute_process(COMMAND ${CMAKE_COMMAND} - -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} - -DOGRE_BUILD_TESTS=ON - -DOGRE_RESOURCEMANAGER_STRICT=2 - -DOGRE_NODELESS_POSITIONING=OFF - -DOGRE_BUILD_DEPENDENCIES=${BUILD_DEPS} - -DSWIG_EXECUTABLE=${SWIG_EXECUTABLE} - ${RENDERSYSTEMS} - ${OTHER} - ${GENERATOR} - .. - WORKING_DIRECTORY build) diff --git a/pyproject.toml b/pyproject.toml deleted file mode 100644 index 9c640b935c7..00000000000 --- a/pyproject.toml +++ /dev/null @@ -1,2 +0,0 @@ -[build-system] -requires = ["setuptools", "wheel", "scikit-build", "cmake", "pip", "swig"] diff --git a/setup.py b/setup.py deleted file mode 100644 index b4aeeea384e..00000000000 --- a/setup.py +++ /dev/null @@ -1,126 +0,0 @@ -import os -import sys -import os.path -import re -import skbuild -from skbuild import cmaker - -# This creates a list which is empty but returns a length of 1. -# Should make the wheel a binary distribution and platlib compliant. -class EmptyListWithLength(list): - def __len__(self): - return 1 - -def cmake_process_manifest_hook(cmake_manifest): - return [name for name in cmake_manifest - if os.path.splitext(name)[1] not in (".a", ".h", ".i", ".pc", ".cmake", ".lib") - or "media/" in name.replace("\\", "/").lower()] - -def main(): - os.chdir(os.path.dirname(os.path.abspath(__file__))) - - os.makedirs("Ogre", exist_ok=True) - - cmaker.CMaker.check_for_bad_installs = lambda: None # barks at our self-built deps - - long_description = open("README.md", encoding="utf-8").read() - long_description = long_description.replace("![](Other", "![](https://raw.githubusercontent.com/OGRECave/ogre/master/Other") - long_description = long_description.replace("](Docs", "](https://github.com/OGRECave/ogre/blob/master/Docs") - - cmake_source_dir = "." - cmake_args = [ - "-DOGRE_LIB_DIRECTORY=Ogre", # install into Python package - "-DOGRE_BITES_STATIC_PLUGINS=ON", - "-DOGRE_NODELESS_POSITIONING=OFF", - "-DOGRE_BUILD_DEPENDENCIES=ON", - "-DOGRE_INSTALL_DEPENDENCIES=ON", - "-DOGRE_BUILD_SAMPLES=OFF", - "-DOGRE_BUILD_TOOLS=OFF", - "-DOGRE_BUILD_COMPONENT_CSHARP=OFF", - "-DOGRE_BUILD_COMPONENT_JAVA=OFF", - "-DOGRE_BUILD_COMPONENT_PROPERTY=OFF", - "-DOGRE_BUILD_RENDERSYSTEM_GL=ON", - "-DOGRE_BUILD_RENDERSYSTEM_GL3PLUS=ON", - "-DOGRE_BUILD_RENDERSYSTEM_GLES2=ON", - "-DOGRE_BUILD_RENDERSYSTEM_TINY=ON", - "-DOGRE_BUILD_PLUGIN_ASSIMP=ON", - "-DOGRE_BUILD_PLUGIN_FREEIMAGE=OFF", - "-DOGRE_BUILD_PLUGIN_EXRCODEC=OFF", - "-DOGRE_BUILD_PLUGIN_CG=OFF", - "-DOGRE_BUILD_PLUGIN_BSP=OFF", - "-DOGRE_BUILD_PLUGIN_PCZ=OFF", - # not yet wrapped components - "-DOGRE_BUILD_COMPONENT_MESHLODGENERATOR=OFF", - "-DOGRE_BUILD_COMPONENT_VOLUME=OFF" - ] - - if sys.platform == "win32": - cmake_args += ["-DOGRE_BIN_DIRECTORY=Ogre", # direct dlls into python package - "-DOGRE_CFG_INSTALL_PATH=bin", # but keep config files in bin, relative to Media - "-DOGRE_BUILD_RENDERSYSTEM_D3D9=OFF", # do not require old runtime - "-DOGRE_BUILD_RENDERSYSTEM_VULKAN=ON", - "-DOGRE_BUILD_PLUGIN_GLSLANG=ON" - ] - elif sys.platform == "linux": - cmake_args += ["-DOGRE_GLSUPPORT_USE_EGL=ON", - "-DOGRE_BUILD_RENDERSYSTEM_VULKAN=ON", - "-DOGRE_BUILD_PLUGIN_GLSLANG=ON", - "-DPYTHON_LIBRARY=dontcare", # workaround issue with cmake & manylinux - "-DCMAKE_CXX_FLAGS=-s", # strip assimp - "-DCMAKE_INSTALL_RPATH=$ORIGIN;$ORIGIN/OGRE"] - elif sys.platform == "darwin": - cmake_args += ["-DOGRE_BUILD_LIBS_AS_FRAMEWORKS=OFF", - "-DCMAKE_OSX_ARCHITECTURES=arm64", - "-DCMAKE_INSTALL_RPATH=@loader_path;@loader_path/OGRE"] - - version = re.search("project\(OGRE VERSION (\S+)\)", open("CMakeLists.txt").read()).group(1) - # version += ".dev0" - - skbuild.setup( - name="ogre-python", - version=version, - url="https://www.ogre3d.org", - project_urls={ - 'Documentation': 'https://ogrecave.github.io/ogre/api/latest/manual.html', - 'Source code': 'https://github.com/OGRECave/ogre', - 'Issues': 'https://github.com/OGRECave/ogre/issues', - "Funding": "https://www.patreon.com/ogre1" - }, - license="MIT", - description="Object-Oriented Graphics Rendering Engine - python package", - long_description=long_description, - long_description_content_type="text/markdown", - packages=["Ogre"], - package_data={}, - maintainer="Pavel Rojtberg", - ext_modules=EmptyListWithLength(), - python_requires=">=3.6", - classifiers=[ - "Development Status :: 5 - Production/Stable", - "Environment :: Console", - "Intended Audience :: Developers", - "Intended Audience :: Education", - "Intended Audience :: Information Technology", - "Intended Audience :: Science/Research", - "License :: OSI Approved :: MIT License", - "Operating System :: MacOS", - "Operating System :: Microsoft :: Windows", - "Operating System :: POSIX", - "Operating System :: Unix", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3.8", - "Programming Language :: C++", - "Programming Language :: Python :: Implementation :: CPython", - "Topic :: Scientific/Engineering", - "Topic :: Multimedia :: Graphics :: 3D Rendering", - "Topic :: Software Development", - ], - cmake_args=cmake_args, - cmake_source_dir=cmake_source_dir, - cmake_process_manifest_hook=cmake_process_manifest_hook - ) - -if __name__ == "__main__": - main()

http://www.ogre3d.org